{"repo_name": "akd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nOWNER=$1\n\nGH=$(which gh)\n\nif [ -z \"$GH\" ]\nthen\n    echo \"Github CLI is required for this script. Please go to https://cli.github.com/ to install a supported version for your platform\"\n    exit 1\nfi\n\nif [ -z \"$OWNER\" ]\nthen\n    echo \"Usage ./sync_fork.sh OWNER [branch_name]. OWNER is required\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]\nthen\n    $GH repo sync $OWNER/akd -b main\nelse\n    echo \"Overriding the branch to $2\"\n    $GH repo sync $OWNER/$2 -b main\nfi\n", "num_lines": 26}
{"repo_name": "Ax", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ManyLinux build\n# Mount top-level Ax directory as Ax-main.\ndocker container run --mount type=bind,source=\"$(pwd)/../\",target=/Ax-main -it quay.io/pypa/manylinux2010_x86_64\n\n# MANUAL STEP FOR NOW\n# Now, in Docker container, cd Ax-main and MANUALLY RUN ./docker_install.sh\n\n# LOCAL BUILD\n# Requires Python 3.7 installed locally, and on path\ncd ..\npip3.7 install numpy\npython3.7 setup.py bdist_wheel\n\n# Final PyPI Upload\ntwine upload dist/*\n", "num_lines": 22}
{"repo_name": "Ax", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nVERSION=$1\n\n# Build Linux Python3.7\n# Execute from Ax root directory.\ncd ../ || exit\n/opt/python/cp37-cp37m/bin/pip3.7 install numpy\n/opt/python/cp37-cp37m/bin/python3.7 setup.py bdist_wheel\n\n# Convert to manylinux\ncd dist || exit\nauditwheel repair ax_platform-\"$VERSION\"-cp37-cp37m-linux_x86_64.whl\nrm ./*\nmv wheelhouse/* .\nrm -rf wheelhouse\n", "num_lines": 21}
{"repo_name": "Ax", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Exit if any error occurs\nset -e\n\nusage() {\n  echo \"Usage: $0 [-b] [-o] [-r] [-t] [-k kernel_name]\"\n  echo \"\"\n  echo \"Build Ax documentation. Must be executed from root of Ax repository.\"\n  echo \"\"\n  echo \"  -b   Build static version of documentation (otherwise start server).\"\n  echo \"  -o   Only Docusaurus (skip Sphinx, tutorials). Useful when just make change to Docusaurus settings.\"\n  echo \"  -t   Execute tutorials (instead of just converting).\"\n  echo \"  -r   Convert backtick-quoted class or function names in .md files into links to API documentation.\"\n  echo \"  -k   Kernel name to use for executing tutorials. Use Jupyter default if not set.\"\n  echo \"\"\n  exit 1\n}\n\nBUILD_STATIC=false\nONLY_DOCUSAURUS=false\nBUILD_TUTORIALS=false\nKERNEL_NAME=false\nINSERT_API_REFS=false\n\nwhile getopts 'hbotrk:' flag; do\n  case \"${flag}\" in\n    h)\n      usage\n      ;;\n    b)\n      BUILD_STATIC=true\n      ;;\n    o)\n      ONLY_DOCUSAURUS=true\n      ;;\n    t)\n      BUILD_TUTORIALS=true\n      ;;\n    r)\n      INSERT_API_REFS=true\n      ;;\n    k)\n      KERNEL_NAME=${OPTARG}\n      ;;\n    *)\n      usage\n      ;;\n  esac\ndone\n\nif [[ $ONLY_DOCUSAURUS == false ]]; then\n  # generate Sphinx documentation\n  echo \"-----------------------------------\"\n  echo \"Generating API reference via Sphinx\"\n  echo \"-----------------------------------\"\n  cd sphinx || exit\n  make html\n  cd .. || exit\nfi\n\n# init Docusaurus deps\necho \"-----------------------------------\"\necho \"Getting Docusaurus deps\"\necho \"-----------------------------------\"\ncd website || exit\nyarn\n\nif [[ $ONLY_DOCUSAURUS == false ]]; then\n  # run script to parse html generated by sphinx\n  echo \"--------------------------------------------\"\n  echo \"Parsing Sphinx docs and moving to Docusaurus\"\n  echo \"--------------------------------------------\"\n  cd ..\n  mkdir -p \"website/pages/api/\"\n\n  cwd=$(pwd)\n  python3 scripts/parse_sphinx.py -i \"${cwd}/sphinx/build/html/\" -o \"${cwd}/website/pages/api/\"\n\n  SPHINX_JS_DIR='sphinx/build/html/_static/'\n  DOCUSAURUS_JS_DIR='website/static/js/'\n\n  mkdir -p $DOCUSAURUS_JS_DIR\n\n  # move JS files from /sphinx/build/html/_static/*:\n  cp \"${SPHINX_JS_DIR}documentation_options.js\" \"${DOCUSAURUS_JS_DIR}documentation_options.js\"\n  cp \"${SPHINX_JS_DIR}jquery.js\" \"${DOCUSAURUS_JS_DIR}jquery.js\"\n  cp \"${SPHINX_JS_DIR}underscore.js\" \"${DOCUSAURUS_JS_DIR}underscore.js\"\n  cp \"${SPHINX_JS_DIR}doctools.js\" \"${DOCUSAURUS_JS_DIR}doctools.js\"\n  cp \"${SPHINX_JS_DIR}language_data.js\" \"${DOCUSAURUS_JS_DIR}language_data.js\"\n  cp \"${SPHINX_JS_DIR}searchtools.js\" \"${DOCUSAURUS_JS_DIR}searchtools.js\"\n\n  # searchindex.js is not static util\n  cp \"sphinx/build/html/searchindex.js\" \"${DOCUSAURUS_JS_DIR}searchindex.js\"\n\n  # copy module sources\n  cp -r \"sphinx/build/html/_sources/\" \"website/static/_sphinx-sources/\"\n\n  echo \"-----------------------------------\"\n  echo \"Generating tutorials\"\n  echo \"-----------------------------------\"\n  # mkdir -p \"website/_tutorials\"\n  # mkdir -p \"website/static/files\"\n  if [[ $BUILD_TUTORIALS == true ]]; then\n    if [[ $KERNEL_NAME == false ]]; then\n      python3 scripts/make_tutorials.py -w \"${cwd}\" -e\n    else\n      python3 scripts/make_tutorials.py -w \"${cwd}\" -e -k \"${KERNEL_NAME}\"\n    fi\n  else\n    python3 scripts/make_tutorials.py -w \"${cwd}\"\n  fi\n\ncd website || exit\nfi  # end of not only Docusaurus block\n\nif [[ $INSERT_API_REFS == true ]]; then\n  echo \"-----------------------------------\"\n  echo \"Inserting API reference links in Markdown files\"\n  echo \"-----------------------------------\"\n  cd ..\n  cwd=$(pwd)\n  python3 scripts/insert_api_refs.py --source_path \"${cwd}/ax\" --docs_path \"${cwd}/docs\"\n  cd - || exit\nfi\n\nif [[ $BUILD_STATIC == true ]]; then\n  echo \"-----------------------------------\"\n  echo \"Building static Docusaurus site\"\n  echo \"-----------------------------------\"\n  yarn build\nelse\n  echo \"-----------------------------------\"\n  echo \"Starting local server\"\n  echo \"-----------------------------------\"\n  yarn start\nfi\n", "num_lines": 142}
{"repo_name": "Ax", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Exit if any error occurs\nset -e\nset -x\n\nusage() {\n  echo \"Usage: $0 [-d] [-k KERNEL_NAME] [-v VERSION]\"\n  echo \"\"\n  echo \"Build and push updated Ax site. Will either update latest or bump stable version.\"\n  echo \"\"\n  echo \"  -d                Use Docusaurus bot GitHub credentials. If not specified, will use default GitHub credentials.\"\n  echo \"  -k=KERNEL_NAME    Kernel name to use for executing tutorials. Use Jupyter default if not set.\"\n  echo \"  -v=VERSION        Build site for new library version. If not specified, will update latest.\"\n  echo \"\"\n  exit 1\n}\n\nVERSION=false\nDOCUSAURUS_BOT=false\nKERNEL_NAME=false\n\nwhile getopts 'dhk:v:' option; do\n  case \"${option}\" in\n    d)\n      DOCUSAURUS_BOT=true\n      ;;\n    h)\n      usage\n      ;;\n    k)\n      KERNEL_NAME=${OPTARG}\n      ;;\n    v)\n      VERSION=${OPTARG}\n      ;;\n    *)\n      usage\n      ;;\n  esac\ndone\n\n# Function to get absolute filename\nfullpath() {\n  echo \"$(cd \"$(dirname \"$1\")\" || exit; pwd -P)/$(basename \"$1\")\"\n}\n\n# Current directory (needed for cleanup later)\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Make temporary directory\nWORK_DIR=$(mktemp -d)\ncd \"${WORK_DIR}\" || exit\n\nif [[ $DOCUSAURUS_BOT == true ]]; then\n  # Setup git credentials\n  git config --global user.name \"Ax Website Deployment Script\"\n  git config --global user.email \"docusaurus-bot@users.noreply.github.com\"\n  echo \"machine github.com login docusaurus-bot password ${DOCUSAURUS_PUBLISH_TOKEN}\" > ~/.netrc\n\n  # Clone both main & gh-pages branches\n  git clone https://docusaurus-bot@github.com/facebook/Ax.git Ax-main\n  git clone --branch gh-pages https://docusaurus-bot@github.com/facebook/Ax.git Ax-gh-pages\nelse\n  git clone git@github.com:facebook/Ax.git Ax-main\n  git clone --branch gh-pages git@github.com:facebook/Ax.git Ax-gh-pages\nfi\n\n# A few notes about the script below:\n# * Docusaurus versioning was designed to *only* version the markdown\n#   files in the docs/ subdirectory. We are repurposing parts of Docusaurus\n#   versioning, but snapshotting the entire site. Versions of the site are\n#   stored in the versions/ subdirectory on gh-pages:\n#\n#   --gh-pages/\n#     |-- api/\n#     |-- css/\n#     |-- docs/\n#     |   ...\n#     |-- versions/\n#     |   |-- 1.0.1/\n#     |   |-- 1.0.2/\n#     |   |   ...\n#     |   |-- latest/\n#     |   ..\n#     |-- versions.html\n#\n# * The stable version is in the top-level directory. It is also\n#   placed into the versions/ subdirectory so that it does not need to\n#   be built again when the version is augmented.\n# * We want to support serving / building the Docusaurus site locally\n#   without any versions. This means that we have to keep versions.js\n#   outside of the website/ subdirectory.\n# * We do not want to have a tracked file that contains all versions of\n#   the site or the latest version. Instead, we determine this at runtime.\n#   We use what's on gh-pages in the versions subdirectory as the\n#   source of truth for available versions and use the latest tag on\n#   the main branch as the source of truth for the latest version.\n\nif [[ $VERSION == false ]]; then\n  echo \"-----------------------------------------\"\n  echo \"Updating latest (main) version of site \"\n  echo \"-----------------------------------------\"\n\n  # Populate _versions.json from existing versions; this is used\n  # by versions.js & needed to build the site (note that we don't actually\n  # use versions.js for latest build, but we do need versions.js\n  # in website/pages in order to use docusaurus-versions)\n  CMD=\"import os, json; \"\n  CMD+=\"vs = [v for v in os.listdir('Ax-gh-pages/versions') if v != 'latest' and not v.startswith('.')]; \"\n  CMD+=\"print(json.dumps(vs))\"\n  python3 -c \"$CMD\" > Ax-main/website/_versions.json\n\n  # Move versions.js to website subdirectory.\n  # This is the page you see when click on version in navbar.\n  cp Ax-main/scripts/versions.js Ax-main/website/pages/en/versions.js\n  cd Ax-main/website || exit\n\n  # Replace baseUrl (set to /versions/latest/) & disable Algolia\n  CONFIG_FILE=$(fullpath \"siteConfig.js\")\n  python3 ../scripts/patch_site_config.py -f \"${CONFIG_FILE}\" -b \"/versions/latest/\" --disable_algolia\n\n  # Tag site with \"latest\" version\n  yarn\n  yarn run version latest\n\n  # Build site\n  cd .. || exit\n  ./scripts/make_docs.sh -b -t -k \"${KERNEL_NAME}\"\n  rm -rf ../website/build/Ax/docs/next  # don't need this\n\n  # Move built site to gh-pages (but keep old versions.js)\n  cd \"${WORK_DIR}\" || exit\n  cp Ax-gh-pages/versions/latest/versions.html versions.html\n  rm -rf Ax-gh-pages/versions/latest\n  mv Ax-main/website/build/Ax Ax-gh-pages/versions/latest\n  # versions.html goes both in top-level and under en/ (default language)\n  cp versions.html Ax-gh-pages/versions/latest/versions.html\n  cp versions.html Ax-gh-pages/versions/latest/en/versions.html\n\n  # erase git history then force push to overwrite\n  cd Ax-gh-pages || exit\n  rm -rf .git\n  git init -b main\n  git add --all\n  git commit -m 'Update latest version of site'\n  git push --force \"git@github.com:facebook/Ax\" main:gh-pages\n\nelse\n  echo \"-----------------------------------------\"\n  echo \"Building new version ($VERSION) of site \"\n  echo \"-----------------------------------------\"\n\n  # Checkout main branch with specified tag\n  cd Ax-main || exit\n  git fetch --tags\n  git checkout \"${VERSION}\"\n\n  # Populate _versions.json from existing versions; this contains a list\n  # of versions present in gh-pages (excluding latest). This is then used\n  # to populate versions.js (which forms the page that people see when they\n  # click on version number in navbar).\n  # Note that this script doesn't allow building a version of the site that\n  # is already on gh-pages.\n  CMD=\"import os, json; \"\n  CMD+=\"vs = [v for v in os.listdir('../Ax-gh-pages/versions') if v != 'latest' and not v.startswith('.')]; \"\n  CMD+=\"assert '${VERSION}' not in vs, '${VERSION} is already on gh-pages.'; \"\n  CMD+=\"vs.append('${VERSION}'); \"\n  CMD+=\"print(json.dumps(vs))\"\n  python3 -c \"$CMD\" > website/_versions.json\n\n  cp scripts/versions.js website/pages/en/versions.js\n\n  # Set Docusaurus version as 'stable'\n  cd website || exit\n  yarn\n  yarn run version stable\n\n  # Build new version of site (this will be stable, default version)\n  # Execute tutorials\n  cd .. || exit\n  ./scripts/make_docs.sh -b -t -k \"${KERNEL_NAME}\"\n\n  # Move built site to new folder (new-site) & carry over old versions\n  # from existing gh-pages\n  cd \"${WORK_DIR}\" || exit\n  rm -rf Ax-main/website/build/Ax/docs/next  # don't need this\n  mv Ax-main/website/build/Ax new-site\n  mv Ax-gh-pages/versions new-site/versions\n\n  # Build new version of site (to be placed in versions/$VERSION/)\n  # the only thing that changes here is the baseUrl (for nav purposes)\n  # we build this now so that in the future, we can just bump version and not move\n  # previous stable to versions\n  cd Ax-main/website || exit\n\n  # Replace baseUrl & disable Algolia\n  CONFIG_FILE=$(fullpath \"siteConfig.js\")\n  python3 ../scripts/patch_site_config.py -f \"${CONFIG_FILE}\" -b \"/versions/${VERSION}/\" --disable_algolia\n\n  # Set Docusaurus version with exact version & build\n  yarn run version \"${VERSION}\"\n  cd .. || exit\n  # Only run Docusaurus (skip tutorial build & Sphinx)\n  ./scripts/make_docs.sh -b -o\n  rm -rf website/build/Ax/docs/next  # don't need this\n  rm -rf website/build/Ax/docs/stable  # or this\n  mv website/build/Ax \"../new-site/versions/${VERSION}\"\n\n  # Need to run script to update versions.js for previous versions in\n  # new-site/versions with the newly built versions.js. Otherwise,\n  # the versions.js for older versions in versions subdirectory\n  # won't be up-to-date and will not have a way to navigate back to\n  # newer versions. This is the only part of the old versions that\n  # needs to be updated when a new version is built.\n  cd \"${WORK_DIR}\" || exit\n  python3 Ax-main/scripts/update_versions_html.py -p \"${WORK_DIR}\"\n\n  # Init as Git repo and push to gh-pages\n  cd new-site || exit\n  git init -b main\n  git add --all\n  git commit -m \"Publish version ${VERSION} of site\"\n  git push --force \"git@github.com:facebook/Ax\" main:gh-pages\n\nfi\n\n# Clean up\ncd \"${SCRIPT_DIR}\" || exit\nrm -rf \"${WORK_DIR}\"\n", "num_lines": 235}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\n\nstart_soyweb() {\n  echo \"Starting soyweb-prod.sh\" >&2\n  docs/soyweb-prod.sh >&2 &\n  local soyweb_pid=$!\n  sleep 2\n  if ! kill -0 \"$soyweb_pid\" >/dev/null 2>&1; then\n    echo \"Soyweb not running after 2 seconds. kill 0 on pid ${soyweb_pid} failed\" >&2\n    exit 1\n  fi\n  echo \"Started soyweb-prod.sh as pid ${soyweb_pid}\" >&2\n  echo \"$soyweb_pid\"\n}\n\nshow_help() {\n  cat <<-EOF\nUsage: publish.sh [--start-soyweb] [--keep-files]\n  --start-soyweb Start soyweb and shut it down when the script is finished\n  --keep-files   Keep temporary files after attempting to publish\nEOF\n  exit 1\n}\n\nGIT_USER=\"buck-bot\"\nCNAME=\"buck.build\"\nSTART_SOYWEB=0\nKEEP_FILES=0\nSOYWEB_PID=0\nfor arg do\n  shift\n  case $arg in\n    --start-soyweb) START_SOYWEB=1 ;;\n    --keep-files) KEEP_FILES=1 ;;\n    --help) show_help ;;\n    *) set -- \"$@\" \"$arg\" ;;\n  esac\ndone\n\nSTATIC_FILES_DIR=$(mktemp -d)\n\nbuck run //docs:generate_buckconfig_aliases\nif ! git diff --quiet; then\n  echo \"Git repository is not clean; refusing to publish\"\n  exit 1\nfi\n\n# Always run this script from the root of the Buck project directory.\ncd $(git rev-parse --show-toplevel)\n\nif [ $START_SOYWEB -eq 1 ]; then\n  SOYWEB_PID=$(($(start_soyweb) + 0))\nfi\n\n# Make sure we cleanup\ntrap_command=\"\"\nif [ $SOYWEB_PID -gt 0 ]; then\n  trap_command=\"echo 'Stopping soyweb (pid ${SOYWEB_PID})'; kill -9 ${SOYWEB_PID};\"\nfi\nif [ $KEEP_FILES -eq 0 ] && [ -n \"$STATIC_FILES_DIR\" ]; then\n  trap_command=\"${trap_command}echo 'Removing temp dir at ${STATIC_FILES_DIR}'; rm -rf ${STATIC_FILES_DIR};\"\nfi\nif [ -n \"$trap_command\" ]; then\n  trap \"$trap_command\" EXIT\nfi\n\necho \"Documentation working directory is ${STATIC_FILES_DIR}\"\n\n# Create a clean checkout of the gh-pages branch with no data:\nif [ -z \"$1\" ]\nthen\n  git clone https://${GIT_USER}:${GITHUB_TOKEN}@github.com/facebook/buck.git $STATIC_FILES_DIR\nelse\n  cp -r \"$1\" $STATIC_FILES_DIR\nfi\ncd $STATIC_FILES_DIR\n\n# May need to do this if you are creating gh-pages for the first time.\ngit checkout main\n\ngit checkout --orphan gh-pages\ngit rm -rf .\ncd -\n\n# Generate the docs in the repo:\n./docs/soy2html.sh $STATIC_FILES_DIR\n\n# Commit the new version of the docs:\ncd $STATIC_FILES_DIR\necho \"${CNAME}\" > CNAME\ngit config --global user.name \"${GIT_USER}\"\ngit add .\ngit commit -m \"Updated HTML documentation.\"\n\n# Push the new version of the docs to GitHub:\nset +e\ngit push origin gh-pages --force\nEXIT_CODE=$?\nset -e\n\n# Unfortunately, this script is not bulletproof,\n# so inform the user of the failure.\nif [ $EXIT_CODE -ne 0 ]; then\n  echo \"WARNING: 'git push origin gh-pages failed'. \"\n  echo \"Try going to https://github.com/facebook/buck/branches\"\n  echo \"and re-running this script.\"\nfi\n", "num_lines": 124}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\n\n# Always run this script from the root of the Buck project directory.\ncd \"$(git rev-parse --show-toplevel)\"\n\n# The output directory should be the one and only argument.\nOUTPUT_DIR=\"$1\"\n\n# Run soy2html.py, taking care to unset proxy env variables as the script will\n# use curl internally.\n(\n  cd docs\n  HTTP_PROXY=\"\" HTTPS_PROXY=\"\" http_proxy=\"\" https_proxy=\"\" python soy2html.py \"$OUTPUT_DIR\"\n)\n\n# Generate javadoc and include it in the output directory.\nant javadoc-with-android\nmkdir -p \"${OUTPUT_DIR}\"/javadoc/\ncp -r ant-out/javadoc-with-android/* \"${OUTPUT_DIR}\"/javadoc/\n", "num_lines": 36}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Always run this script from the root of the Buck project directory.\ncd \"$(git rev-parse --show-toplevel)/docs\" || exit\nbuck run //docs:generate_buckconfig_aliases\nexec java -jar plovr-81ed862.jar soyweb --dir . --globals globals.json $@\n", "num_lines": 21}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Always run this script from the root of the Buck project directory.\n\n#\n# Remove any residual files that could derail build and publication.\n#\ncd \"$(git rev-parse --show-toplevel)\" || exit\nant clean\n\ncd \"$(git rev-parse --show-toplevel)/docs\" || exit\nbuck run //docs:generate_buckconfig_aliases\nexec java -jar plovr-81ed862.jar soyweb --port 9814 --dir . --globals globals.json\n\n", "num_lines": 29}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu\n\nexport PYTHONPATH=\"`dirname \"$0\"`\"\n\npython3 -m artificialproject \"$@\"\n", "num_lines": 21}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\n\n# $1: OS\nexport OS=\"linux\"\nif [ \"$1\" == \"macos\" ]; then\n  export OS=\"darwin\"\nfi\n\nexport NDK_VERSION_STRING=\"android-ndk-r10e\"\nexport NDK_FILENAME=\"$NDK_VERSION_STRING-${OS}-x86_64.bin\"\n\nexport CACHED_PATH=\"${HOME}/ndk_cache/$NDK_FILENAME\"\n\nif [ ! -f \"$CACHED_PATH\" ]; then\n  echo \"Downloading NDK.\"\n  curl -O \"https://dl.google.com/android/ndk/$NDK_FILENAME\"\nelse\n  echo \"Using cached NDK.\"\n  mv \"$CACHED_PATH\" .\nfi\n\n# Uncpack the ndk.\nchmod a+x \"$NDK_FILENAME\"\n# Suppress the output to not spam the logs.\n\"./$NDK_FILENAME\" > /dev/null\nrm \"$NDK_FILENAME\";\n\n# Move ndk into the proper place.\nrm -rf ${NDK_HOME}\nmv android-ndk-r10e ${NDK_HOME}\n", "num_lines": 46}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\n\nif [ -z \"$1\" ]; then\n  echo \"Must specify Android NDK version\"\n  exit 1\nfi\n\n# $1: NDK_VERSION_STRING\n# $2: OS\nexport NDK_VERSION_STRING=\"$1\"\nexport OS=\"linux\"\nif [ \"$2\" == \"macos\" ]; then\n  export OS=\"darwin\"\nfi\nexport NDK_FILENAME=\"$NDK_VERSION_STRING-${OS}-x86_64.zip\"\n\nexport CACHED_PATH=\"${HOME}/ndk_cache/$NDK_FILENAME\"\n\nif [ ! -f \"$CACHED_PATH\" ]; then\n  echo \"Downloading NDK.\"\n  curl -O \"https://dl.google.com/android/repository/$NDK_FILENAME\"\nelse\n  echo \"Using cached NDK.\"\n  mv \"$CACHED_PATH\" .\nfi\n\nunzip -o \"./$NDK_FILENAME\" > /dev/null\nrm \"$NDK_FILENAME\"\n\n# Move ndk into the proper place.\nrm -rf \"${NDK_HOME}\"\nmv \"${NDK_VERSION_STRING}\" \"${NDK_HOME}\"\n", "num_lines": 49}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nDIR=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\nBUCKRELEASE_FILE=\"$DIR\"/../.buckrelease\nDEFAULT_TAG=`date +v%Y.%m.%d.01`\n\nshopt -s nocasematch\n\nread -e -p \"Enter tag name to create [hit enter for $DEFAULT_TAG]: \" tag\n\nif [[ -z $tag ]]; then\n    tag=\"$DEFAULT_TAG\"\nfi\n\necho -n \"Creating and committing .buckrelease file for $tag... \"\n\necho \"$tag\" > \"$BUCKRELEASE_FILE\"\ngit add \"$BUCKRELEASE_FILE\"\ngit commit --allow-empty -q -m \"Prepare release $tag.\"\necho \"done.\"\n\ngit tag -f \"$tag\"\n\nread -e -p \"Run 'git push origin $tag'? [Y/n] \" ok\nif [[ $ok =~ ^(yes|y)$ ]]; then\n    git push origin \"$tag\"\nfi\n", "num_lines": 42}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Wrapper script that runs the exopackage installer test on all connected\n# devices\nset -x\nset -e\nset -o pipefail\n\ncd `dirname $0`\ncd `git rev-parse --show-cdup`\n\nRESULT=\"\"\nEXIT_CODE=\"0\"\n\nDEVICES=`adb devices | sed -Ene '2,$s/^([^[:space:]]+).*/\\1/p'`\nfor DEV in $DEVICES ; do\n  export ANDROID_SERIAL=$DEV\n  ANDROID_VERSION=`adb shell getprop ro.build.version.release | tr -d '\\r\\n'`\n  RESULT=\"$RESULT$DEV $ANDROID_VERSION\"\n  if ./scripts/exopackage_test_single.sh; then\n    RESULT=\"$RESULT SUCCESS^\"\n  else\n    RESULT=\"$RESULT FAILURE^\"\n    EXIT_CODE=1\n  fi\ndone\n\nset +x\necho\necho $RESULT | tr ^ '\\n'\nexit $EXIT_CODE\n", "num_lines": 46}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Integration test for the exopackage installer.\n# This just tests the happy path, so it's more a test of device compatibility.\n\nset -x\nset -e\nset -o pipefail\n\n# Just check that we can communicate with a device/emulator.\nadb get-state\n\nfunction sedInPlace() {\n  case \"$(uname -s)\" in\n    Darwin)\n      sed -i '' -e \"$1\" \"$2\"\n      ;;\n    Linux)\n      sed \"$1\" -i \"$2\"\n      ;;\n    *)\n      echo \"Unsupported OS name '$(uname -s)' for running sed.\"\n      exit 1\n  esac\n}\n\ncd `dirname $0`\ncd `git rev-parse --show-cdup`\n\nif [ \"$1\" == \"--debug\" ]; then\n  shift\n  TMP_DIR='/tmp/exopackage-test'\n  rm -rf $TMP_DIR/*\n  mkdir -p $TMP_DIR\nelse\n  TMP_DIR=`mktemp -d /tmp/exopackage-test.XXXXXX`\n  trap \"rm -rf $TMP_DIR\" EXIT HUP INT TERM\nfi\n\n# Copy the test project into a temp dir, then cd into it and make it a buck project.\ncp -r test/com/facebook/buck/android/testdata/exopackage-device/* $TMP_DIR\n# Copy the testrunner script\ncp test/com/facebook/buck/testutil/endtoend/testdata/mobile/simple_test_runner.py $TMP_DIR/\n# Copy the test libraries\nmkdir $TMP_DIR/test_libs\ncp -r test/com/facebook/buck/testutil/endtoend/testdata/mobile/android/libs/*.jar $TMP_DIR/test_libs/\n\nbuck build --out $TMP_DIR/buck.pex buck\nbuck build --out $TMP_DIR/buck-android-support.jar buck-android-support\n\ncd $TMP_DIR\nfor BUCKFILE in `find . -name BUCK.fixture` ; do\n  mv $BUCKFILE ${BUCKFILE%%.fixture}\ndone\ncat >.buckconfig <<EOF\n[java]\n  source_level = 7\n  target_level = 7\n[ndk]\n  cxx_runtime = system\n  cpu_abis = armv7, x86\nEOF\ncat >.bucklogging.properties <<EOF\ncom.facebook.buck.android.exopackage.level=FINER\nEOF\nexport NO_BUCKD=1\n\n# Clear out the phone.\n(\nset +e\nadb uninstall com.facebook.buck.android.agent\nadb uninstall buck.exotest\nadb uninstall buck.exotest.meta\nadb shell 'rm -r /data/local/tmp/exopackage/buck.exotest || rm -f -r /data/local/tmp/exopackage/buck.exotest'\n)\n\nEXP_APP_NAME='Exo Test App'\n\nOUT_COUNT=0\nfunction installAndLaunch() {\n  ./buck.pex install ${1:-//:exotest} | cat\n  adb logcat -c\n  adb shell am start -n buck.exotest/exotest.LogActivity\n  adb shell am start -n buck.exotest.meta/.ExoMetaLogActivity\n  SECONDARY_DEX_INSTALLED=$(cat buck-out/log/build.trace | \\\n    jq -r '[ .[] | select(.name == \"install_secondary_dex\") | select(.ph == \"B\") ] | length')\n  NATIVE_LIBS_INSTALLED=$(cat buck-out/log/build.trace | \\\n    jq -r '[ .[] | select(.name == \"install_native_library\") | select(.ph == \"B\") ] | length')\n  RESOURCE_APKS_INSTALLED=$(cat buck-out/log/build.trace | \\\n    jq -r '[ .[] | select(.name == \"install_resources\") | select(.ph == \"B\") ] | length')\n  MODULAR_DEX_INSTALLED=$(cat buck-out/log/build.trace | \\\n      jq -r '[ .[] | select(.name == \"install_modular_dex\") | select(.ph == \"B\") ] | length')\n  sleep 1\n  adb logcat -d '*:S' EXOPACKAGE_TEST:V EXOPACKAGE_TEST_META:V > out.txt\n  cp out.txt out$((++OUT_COUNT)).txt\n\n  # Check for values in the logs.\n  grep -q \"VALUE=$EXP_JAVA\" out.txt || (cat out.txt && false)\n  grep -q \"NATIVE_ONE=$EXP_CPP1\" out.txt || (cat out.txt && false)\n  grep -q \"NATIVE_TWO=$EXP_CPP2\" out.txt || (cat out.txt && false)\n  grep -q \"RESOURCE=$EXP_RESOURCE\" out.txt || (cat out.txt && false)\n  grep -q \"IMAGE=$EXP_IMAGE\" out.txt || (cat out.txt && false)\n  grep -q \"ASSET=$EXP_ASSET\" out.txt || (cat out.txt && false)\n  grep -q \"ASSET_TWO=$EXP_ASSET2\" out.txt || (cat out.txt && false)\n  grep -q \"MODULE_ONE=$EXP_MODULE\" out.txt || (cat out.txt && false)\n\n  grep -q \"META_ICON=.*_.*\" out.txt || (cat out.txt && false)\n  grep -q \"META_NAME=$EXP_APP_NAME\" out.txt || (cat out.txt && false)\n  grep -q \"META_DATA=<item0,item1,item2>\" out.txt || (cat out.txt && false)\n}\n\nfunction runInstrumentationTestWithExternalRunner() {\n  ./buck.pex test //:instrumentation_test --config test.external_runner=./simple_test_runner.py\n}\n\nfunction runInstrumentationTest() {\n  ./buck.pex test //:instrumentation_test\n}\n\nfunction create_image() {\n  mkdir -p res/drawable-nodpi\n  convert -size ${1}x${1} xc:none res/drawable-nodpi/image.png\n  EXP_IMAGE=png_${1}_${1}\n}\n\nfunction edit_asset() {\n  echo \"asset_$1\" > assets/asset.txt\n  EXP_ASSET=asset_$1\n}\n\nfunction edit_asset2() {\n  echo \"asset2_$1\" > assets2/asset2.txt\n  EXP_ASSET2=asset2_$1\n}\n\nfunction edit_resource() {\n  sedInPlace \"s/\\(string name=\\\"hello\\\">\\)[^<]*/\\1res_$1/\" res/values/strings.xml\n  EXP_RESOURCE=res_$1\n}\n\nfunction edit_java() {\n  echo \"$1\" > value.txt\n  EXP_JAVA=$1\n}\n\nfunction edit_module() {\n  echo \"$1\" > module_value.txt\n  EXP_MODULE=$1\n}\n\nfunction edit_cpp1() {\n  sedInPlace \"s/one_../one_$1/\" jni/one/one.c\n  EXP_CPP1=one_$1\n}\n\nfunction edit_cpp2() {\n  sedInPlace \"s/two_../two_$1/\" jni/two/two.c\n  EXP_CPP2=two_$1\n}\n\nfunction change_label() {\n  sedInPlace \"s/$EXP_APP_NAME/$1/\" res/values/strings.xml\n  sedInPlace \"s/$EXP_APP_NAME/$1/\" res-real-name/values/strings.xml\n  EXP_APP_NAME=$1\n}\n\n./buck.pex install //app-meta-tool:exometa\n\n# Build and do a clean install of the app.  Launch it and capture logs.\ncreate_image 1\nedit_java '1a'\nedit_module '1a'\n\ninstallAndLaunch\n\n# Check for full install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 1\ntest \"$NATIVE_LIBS_INSTALLED\" = 2\n# 1: exo-resources 2: exo-assets 3: exo-java-resources\ntest \"$RESOURCE_APKS_INSTALLED\" = 3\ntest \"$MODULAR_DEX_INSTALLED\" = 1\n\nchange_label 'Exo App New Label'\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 1\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Change java code and do an incremental install of the app.  Launch it and capture logs.\nedit_java '2b'\ninstallAndLaunch\n\n# Check for incremental java install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 1\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 0\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n# Check for the new values in the logs.\n\n# Change modular code and do an incremental install of the app.  Launch it and capture logs.\nedit_module '2bpart2'\ninstallAndLaunch\n\n# Check for incremental module install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 0\ntest \"$MODULAR_DEX_INSTALLED\" = 1\n# Check for the new values in the logs.\n\n# Change one of the native libraries, do an incremental install and capture logs.\nedit_cpp1 3c\ninstallAndLaunch\n\n# Check for incremental native install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 1\ntest \"$RESOURCE_APKS_INSTALLED\" = 0\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n\n# Change both native and java code and do an incremental build.\nedit_java '4d'\nedit_cpp2 4d\ninstallAndLaunch\n\n# Check for incremental java and native install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 1\ntest \"$NATIVE_LIBS_INSTALLED\" = 1\ntest \"$RESOURCE_APKS_INSTALLED\" = 0\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Change an image and do an incremental build.\ncreate_image 5\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 1\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Change an asset and do an incremental build.\nedit_asset '6f'\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 1\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Change a resource and do an incremental build.\nedit_resource '7g'\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 1\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Change all resources and do an incremental build.\ncreate_image 8\nedit_asset2 '8h'\nedit_resource '8h'\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 2\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n\n# Change everything and do a incremental build.\nedit_java '9i'\nedit_module '9i'\nedit_cpp2 '9i'\ncreate_image 9\nedit_asset '9i'\nedit_resource '9i'\ninstallAndLaunch\ntest \"$SECONDARY_DEX_INSTALLED\" = 1\ntest \"$NATIVE_LIBS_INSTALLED\" = 1\ntest \"$RESOURCE_APKS_INSTALLED\" = 2\ntest \"$MODULAR_DEX_INSTALLED\" = 1\n\n# Change everything and do a no-exopackage incremental build.\nedit_java '10j'\nedit_cpp2 '10j'\ncreate_image 10\nedit_resource '10j'\nedit_asset '10j'\ninstallAndLaunch //:exotest-noexo\n\n# Check for no exo install.\ntest \"$SECONDARY_DEX_INSTALLED\" = 0\ntest \"$NATIVE_LIBS_INSTALLED\" = 0\ntest \"$RESOURCE_APKS_INSTALLED\" = 0\ntest \"$MODULAR_DEX_INSTALLED\" = 0\n\n# Check for instrumentation test support\nrunInstrumentationTest\nrunInstrumentationTestWithExternalRunner\n\n# Clean up after ourselves.\n./buck.pex uninstall //:exotest-noexo\n./buck.pex uninstall //app-meta-tool:exometa\n./buck.pex uninstall //:instrumentation_test-apk\nadb uninstall com.facebook.buck.android.agent\n\n# Celebrate!  (And show that we succeeded, because grep doesn't print error messages.)\necho -e \"\\033[42;37m\\033[1mGREAT_SUCCESS\\033[0m\"\n", "num_lines": 322}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -euo pipefail\n\nBUCK_ROOT=$(git rev-parse --show-toplevel)\nBUCK_FBXCTEST_DIR=$BUCK_ROOT/test/com/facebook/buck/apple/testdata/fbxctest\n\nrm -rf $BUCK_FBXCTEST_DIR/{Frameworks,bin,lib}\nmkdir $BUCK_FBXCTEST_DIR/{Frameworks,bin,lib}\n\nTMPDIR=`mktemp -d`\ncd $TMPDIR\n\ngit clone https://github.com/facebook/xctool\npushd xctool\n./xctool.sh || true\nXCTOOL_LIB_DIR=$(ls -d build/*/*/Products/Release/lib)\ncp -r $XCTOOL_LIB_DIR $BUCK_FBXCTEST_DIR\npopd\n\ngit clone https://github.com/facebook/FBSimulatorControl\npushd FBSimulatorControl\n./build.sh fbxctest build\ncp build/Build/Products/Debug/fbxctest $BUCK_FBXCTEST_DIR/bin\n\n./build.sh framework build\nfind build/Build/Products/Debug/ -type l -delete\nfind build/Build/Products/Debug/ -name Frameworks | xargs rm -rf\nfind build/Build/Products/Debug/ -name Headers | xargs rm -rf\nfind build/Build/Products/Debug/ -name Modules | xargs rm -rf\ncp -r build/Build/Products/Debug/*.framework $BUCK_FBXCTEST_DIR/Frameworks\ncp -r $BUCK_FBXCTEST_DIR/Frameworks/XCTestBootstrap.framework/Versions/A/Resources $BUCK_FBXCTEST_DIR/Frameworks/XCTestBootstrap.framework\npopd\n", "num_lines": 49}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nPATH=/opt/homebrew/bin:$PATH\n./scripts/apple/build_script.py\n", "num_lines": 20}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Run with -e so the script will fail if any of the steps fail.\nset -e\n\n(\nfunction resolveList() {\n  echo $1 | tr ':' '\\n' | sed \"s/^\\([^/].*\\)$/$(echo $PWD | sed 's/\\//\\\\\\//g')\\/\\1/\" | tr '\\n' ':'\n}\n\nfunction resolve() {\n  echo $1 | sed \"s/^\\([^/].*\\)$/$(echo $PWD | sed 's/\\//\\\\\\//g')\\/\\1/\"\n}\n\nfunction getJavaPathForVersion() {\n  local java_path\n  java_path=\"java\"\n  echo \"$java_path\"\n}\n\nexport BUCK_CLASSPATH=$(resolveList $BUCK_CLASSPATH)\nexport CLASSPATH=$(resolveList $CLASSPATH)\nexport BUCK_ISOLATED_ROOT=$PWD\n\nexport BUCK_PLUGIN_RESOURCES=$(resolve $BUCK_PLUGIN_RESOURCES)\nexport BUCK_PLUGIN_ROOT=$(resolve $BUCK_PLUGIN_ROOT)\n# necessary for \"isolated buck\" invocations to work correctly\nexport BASE_BUCK_OUT_DIR=$BASE_BUCK_OUT_DIR\n# this env variable is used in some rules to check if build is running using BUCK\nexport BUCK_BUILD_ID=\"RE_buck_build_id\"\n\nif [ \"$BUCK_DEBUG_MODE\" == \"1\" ]; then\n  export BUCK_DEBUG_ARGS=\"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=8888\"\nfi\n\ncd $1\n\nJAVA_PATH=$(getJavaPathForVersion $BUCK_JAVA_VERSION)\n\n$JAVA_PATH -cp $CLASSPATH \\\n  $BUCK_DEBUG_ARGS \\\n  -Xverify:none -XX:+TieredCompilation -XX:TieredStopAtLevel=1 \\\n  -Dpf4j.pluginsDir=$BUCK_PLUGIN_ROOT \\\n  -Dbuck.module.resources=$BUCK_PLUGIN_RESOURCES \\\n  -Dbuck.base_buck_out_dir=$BASE_BUCK_OUT_DIR \\\n  com.facebook.buck.cli.bootstrapper.ClassLoaderBootstrapper \\\n  com.facebook.buck.rules.modern.builders.OutOfProcessIsolatedBuilder \\\n  $BUCK_ISOLATED_ROOT \"$@\"\n)\n", "num_lines": 64}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "echo $1 $2\n", "num_lines": 2}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nOUT=$1\nTMP=$2\nMANIFEST=$3\nPRIMARY=$4\nDEP=$5\n\ncp $MANIFEST $TMP\ncp $PRIMARY $TMP/classes.jar\nmkdir $TMP/libs\ncp $DEP $TMP/libs\nmkdir -p $TMP/res/values\necho '<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<resources>\n  <string name=\"app_name\">Sample App</string>\n  <string name=\"base_button\">Hello world!</string>\n</resources>' > $TMP/res/values/strings.xml\njar cf $OUT -C $TMP .\n", "num_lines": 20}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec < \"$1\" > \"$2\"\necho \"package com.gen;\"\necho \"public class MergedLibraryMapping {\"\nsed 's/[.]/_/g;s/\\(.*\\) \\(.*\\)/public static final String \\1 = \"\\2\";/'\necho \"}\"\n", "num_lines": 7}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"$1\";\necho \"$2\";\n", "num_lines": 5}
{"repo_name": "buck", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/sh\n\ncat <<'EOF'\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n  <key>AppIDName</key>\n  <string>Example</string>\n  <key>ApplicationIdentifierPrefix</key>\n  <array>\n  <string>ABCDE12345</string>\n  </array>\n  <key>CreationDate</key>\n  <date>2015-07-08T20:27:14Z</date>\n  <key>Platform</key>\n  <array>\n    <string>iOS</string>\n  </array>\n  <key>DeveloperCertificates</key>\n  <array>\n    <data>\n      MIIDSzCCAjOgAwIBAgIBATANBgkqhkiG9w0BAQsFADBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNp\n      Z24gQ2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wHhcN\n      MTUxMDIzMjAwNzI1WhcNMzIwMzI3MjAwNzI1WjBTMSAwHgYDVQQDDBdCdWNrIFRlc3QgQ29kZXNpZ24g\n      Q2VydDELMAkGA1UEBhMCVVMxIjAgBgkqhkiG9w0BCQEWE2V4YW1wbGVAZXhhbXBsZS5jb20wggEiMA0G\n      CSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCrmmMdeV17d72ihmdbB0MTn5v3iu9LSGVYlbnJbI+FNmDJ\n      1U/0PAR7aLIPux0puN3N1Rob5VMdSZCG+SvsjV5zUNyepiRYlhf1jMyYTGDuoF8EOtfE94w9kr1EH9gl\n      aKRqir4770oXrFywbOaDO1iLPkpiVnfKVkkoU4dM0UD3YEtXoM70LIpYouGtVvNyc0Sx9/emvyiMH3iA\n      yQz5erVdfJQ2O85eyXz+U6rrcsNQpE0AuyQNnBnm0irSvtvnoPxlCsf0EbLnmnkDlv8yTrgCxzj/jmys\n      0zs+EZFAjYCX/I2ef63Ll+Wm7ilh7CjwNaRMIQmL0QpJIR9kUYnp3v33AgMBAAGjKjAoMA4GA1UdDwEB\n      /wQEAwIHgDAWBgNVHSUBAf8EDDAKBggrBgEFBQcDAzANBgkqhkiG9w0BAQsFAAOCAQEATpWzY5IXhyb4\n      PXiRS64Q6Sh2YXj6Dot2srWC+FJwWngGbF6J8aQfoymsRTkgTa+69WinMefmdRkEzysmXvAUfD1iWpBX\n      jRREQXkUhmt2FwqKp8pWbYSlgOTaQMojQn3DdvDu8l5ZFIrU+8Z8X4g/aggvffoIOygHvhbwkcgrA6Lq\n      TziJssmKd56+QKfVfx52vg6pv1Ok03pmVsQ8semHTJr53juc4QutADhtJBXe9inVs1evosO15At0N731\n      Lz37Bzwedpu8DSEr4PIdwF5yBDRbQoyAF29zQaJgO/mU2G4i9wYTZJrj75BD/qr2ukjQOYOtz4IVNUuz\n      kPu+rDPz4A==\n    </data>\n  </array>\n  <key>Entitlements</key>\n  <dict>\n    <key>keychain-access-groups</key>\n    <array>\n      <string>ABCDE12345.*</string>\n    </array>\n    <key>get-task-allow</key>\n    <false/>\n    <key>application-identifier</key>\n    <string>0000000000.com.example.override</string>\n    <key>com.apple.security.application-groups</key>\n    <array>\n      <string>group.com.example</string>\n    </array>\n    <key>com.apple.developer.team-identifier</key>\n    <string>12345ABCDE</string>\n    <key>com.apple.developer.icloud-container-development-container-identifiers</key>\n    <array>\n      <string>iCloud.com.appleseedinc.MyProject</string>\n      <string>iCloud.com.appleseedinc.container1</string>\n    </array>\n  </dict>\n  <key>ExpirationDate</key>\n  <date>9999-03-05T01:33:40Z</date>\n  <key>Name</key>\n  <string>Example</string>\n  <key>ProvisionsAllDevices</key>\n  <true/>\n  <key>TeamIdentifier</key>\n  <array>\n    <string>12345ABCDE</string>\n  </array>\n  <key>TeamName</key>\n  <string>Example</string>\n  <key>TimeToLive</key>\n  <integer>240</integer>\n  <key>UUID</key>\n  <string>00000000-0000-0000-0000-000000000000</string>\n  <key>Version</key>\n  <integer>1</integer>\n</dict>\n</plist>\nEOF\n", "num_lines": 83}
{"repo_name": "buck2", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\n# This script is used to generate rust-project.json when using internal rust-analyzer\n# on internal VSCode on devserver/OD.\n# If this is not working, make sure your VSCode's root workspace is open at fbsource.\n# Check out the full wiki guide at https://www.internalfb.com/intern/wiki/Rust-at-meta/rust-project/\n\n# Fail if we have any errors\nset -e\n\n# Change to this directory\ncd -- \"$(dirname -- \"$0\")\"\n\narc rust-project develop fbcode//buck2:buck2 --out ../../rust-project.json\n", "num_lines": 21}
{"repo_name": "buck2", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\n# The commands in this script are to be executed in the current shell\n# and so invoke it via the builtin 'source' command e.g. `source\n# setup.sh`. It assumes an opam installation. In addition to\n# symlinking the 'prelude' directory it activates the 'default' opam\n# switch and create symlinks in the 'third-party/opam' directory to\n# support building the example OCaml targets.\n\nif ! command -v opam &> /dev/null\nthen\n    echo \"opam is not installed, which is a dependency for building targets in ocaml.\"\n    exit\nfi\n\n# Bring the OCaml toolchain into scope.\neval \"$(opam env --switch=default --set-switch)\"\n\n# Link 'third-party/ocaml/standard_library'.\nif [ ! -L third-party/ocaml/standard_library ]; then\n  (cd third-party/ocaml && ln -s \"$(ocamlopt.opt -config | grep standard_library: | awk '{ print $2 }' )\" standard_library)\nelse\n    echo \"Link 'third-party/ocaml/standard_library' exists. To overwrite it, first remove it and run $0 again\"\nfi\n\n# Link 'third-party/ocaml/opam'.\nif [ ! -L third-party/ocaml/opam ]; then\n  (cd third-party/ocaml && ln -s \"$OPAM_SWITCH_PREFIX\" opam)\nelse\n    echo \"Link 'third-party/ocaml/opam' exists. To overwrite it, first remove it and run $0 again\"\nfi\n", "num_lines": 37}
{"repo_name": "buck2", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -e\n\n# - Apply a debug prefix map for the current directory\n# to make debug info relocatable.\n# - Use $TMPDIR for the module cache location. This\n# will be set to a unique location for each RE action\n# which will avoid sharing modules across RE actions.\n# This is necessary as the inputs to the modules will\n# be transient and can be removed at any point, causing\n# module validation errors to fail builds.\nif [ -n \"$INSIDE_RE_WORKER\" ]; then\n    MODULE_CACHE_PATH=\"$TMPDIR/module-cache\"\nelse\n    # When building locally we can use a shared module\n    # cache as the inputs should remain at a fixed\n    # location.\n    MODULE_CACHE_PATH=\"/tmp/buck-module-cache\"\nfi\n\nmodule_cache_path_args=()\nif [ -z \"$EXPLICIT_MODULES_ENABLED\" ]; then\n    module_cache_path_args+=(\"-module-cache-path\")\n    module_cache_path_args+=(\"$MODULE_CACHE_PATH\")\nfi\n\n\"$@\" -debug-prefix-map \"$PWD\"=. \"${module_cache_path_args[@]}\"\n\nOUTPUT_PATHS=()\nfor ARG in \"$@\"\ndo\n    if [ \"${FOUND_OUTPUT_ARG}\" = 1 ]; then\n        OUTPUT_PATHS+=( \"${ARG}\" )\n    fi\n    FOUND_OUTPUT_ARG=0\n    if [ \"${ARG}\" = \"-o\" ] || [ \"${ARG}\" = \"-emit-module-path\" ] || [ \"${ARG}\" = \"-emit-objc-header-path\" ]; then\n        FOUND_OUTPUT_ARG=1\n    fi\ndone\n\nif [ ${#OUTPUT_PATHS[@]} -eq 0 ]; then\n    >&2 echo \"No output paths found, ensure output args are not passed in argfiles\"\n    exit 1\nfi\n\nfor OUTPUT_PATH in \"${OUTPUT_PATHS[@]}\"\ndo\n    # We've observed cases where the Swift compiler would return with a zero exit code but\n    # would not have created the output file, correctly a non-zero exit code in such cases.\n    if [ ! -f \"${OUTPUT_PATH}\" ]; then\n        >&2 echo \"Output file does not exist: '${OUTPUT_PATH}'\"\n        exit 1\n    fi\ndone\n", "num_lines": 62}
{"repo_name": "buck2", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -eu\n\n$1 \"${@:2}\" 1>&2\n", "num_lines": 12}
{"repo_name": "buck2", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nPYTHONPATH=\"$(dirname \"$(dirname \"$(dirname \"$(realpath \"$0\")\")\")\")\"\nexport PYTHONPATH\nexec python3 -m unittest sourcedb_merger.tests\n", "num_lines": 12}
{"repo_name": "buck2-prelude", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -e\n\n# - Apply a debug prefix map for the current directory\n# to make debug info relocatable.\n# - Use $TMPDIR for the module cache location. This\n# will be set to a unique location for each RE action\n# which will avoid sharing modules across RE actions.\n# This is necessary as the inputs to the modules will\n# be transient and can be removed at any point, causing\n# module validation errors to fail builds.\nif [ -n \"$INSIDE_RE_WORKER\" ]; then\n    MODULE_CACHE_PATH=\"$TMPDIR/module-cache\"\nelse\n    # When building locally we can use a shared module\n    # cache as the inputs should remain at a fixed\n    # location.\n    MODULE_CACHE_PATH=\"/tmp/buck-module-cache\"\nfi\n\nmodule_cache_path_args=()\nif [ -z \"$EXPLICIT_MODULES_ENABLED\" ]; then\n    module_cache_path_args+=(\"-module-cache-path\")\n    module_cache_path_args+=(\"$MODULE_CACHE_PATH\")\nfi\n\n\"$@\" -debug-prefix-map \"$PWD\"=. \"${module_cache_path_args[@]}\"\n\nOUTPUT_PATHS=()\nfor ARG in \"$@\"\ndo\n    if [ \"${FOUND_OUTPUT_ARG}\" = 1 ]; then\n        OUTPUT_PATHS+=( \"${ARG}\" )\n    fi\n    FOUND_OUTPUT_ARG=0\n    if [ \"${ARG}\" = \"-o\" ] || [ \"${ARG}\" = \"-emit-module-path\" ] || [ \"${ARG}\" = \"-emit-objc-header-path\" ]; then\n        FOUND_OUTPUT_ARG=1\n    fi\ndone\n\nif [ ${#OUTPUT_PATHS[@]} -eq 0 ]; then\n    >&2 echo \"No output paths found, ensure output args are not passed in argfiles\"\n    exit 1\nfi\n\nfor OUTPUT_PATH in \"${OUTPUT_PATHS[@]}\"\ndo\n    # We've observed cases where the Swift compiler would return with a zero exit code but\n    # would not have created the output file, correctly a non-zero exit code in such cases.\n    if [ ! -f \"${OUTPUT_PATH}\" ]; then\n        >&2 echo \"Output file does not exist: '${OUTPUT_PATH}'\"\n        exit 1\n    fi\ndone\n", "num_lines": 62}
{"repo_name": "buck2-prelude", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -eu\n\n$1 \"${@:2}\" 1>&2\n", "num_lines": 12}
{"repo_name": "buck2-prelude", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nPYTHONPATH=\"$(dirname \"$(dirname \"$(dirname \"$(realpath \"$0\")\")\")\")\"\nexport PYTHONPATH\nexec python3 -m unittest sourcedb_merger.tests\n", "num_lines": 12}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\ninput_logfile=$1\nif [[ $# -ne 1 ]] || [[ ! -s \"$input_logfile\" ]] || [[ ! -f \"$input_logfile\" ]]; then\n    echo \"USAGE: $0 LOGFILE\"\n    echo \"produces a tsv containing nvm read/write latencies from LOGFILE\"\n    echo \"if gnuplot is installed, will produce a plot of these latencies\"\n    echo \"LOGFILE should be logging output of cachebench with --progress-stats_file\"\n    exit 1\nfi\n\n\npercentiles=\"p50us p90us p99us p999us p9999us p99999us p999999us p100us\"\n# grep for the lines, convert sequential lines into columns\n#   NVM Read Latency p50     : 201.39 us\n#   NVM Read Latency p90     : 449.96 us\n#   NVM Read Latency p99     : 1054.32 us\n#   NVM Read Latency p999    : 2426.05 us\n#   NVM Read Latency p9999   : 4632.00 us\n#   NVM Read Latency p99999  : 5533.74 us\n#   NVM Read Latency p999999 : 5533.74 us\n#   NVM Read Latency p100    : 9111.00 us\n#\n#   becomes\n#   1 201.39   449.96   1054.32 .... 9111.00\nextract_latency() {\n    local in=$3\n    local out=$2\n    local search=$1\n\n    {\n        echo \"time $percentiles\"\n        # get the latency and translate from one per line into 8 columns\n        # use sequence number of line as time stamp\n        grep -e \"$search\" \"$in\"             | \\\n            awk '{print $6}'                | \\\n            perl -pe 's/\\n/ / if $. % 8'    | \\\n            awk '{print NR\" \"$0}'\n    }  | column -t > \"$out\"\n\n    # check if the file actually produced valid content\n    [[ \"$(wc -l < \"$out\")\" -eq \"1\" ]] &&                        \\\n        echo \"Incorrect log file. No latecny records found\" ||  \\\n        echo \"$search latency written to $out\"\n}\n\nbandwidth=\"egress_gb_s ingress_gb_s\"\n# grep for the last line, convert egressBytesPerSec/ingressBytesPerSec into columns\n# egressBytes : 4573.78 GB, ingressBytes: 771.18 GB, egressBytesPerSec :   9.53 GB/s, ingressBytesPerSec:   1.61 GB/s, ingressEgressratio:  83.14%\n#\n#   becomes\n#   9.53   1.61\nextract_bandwidth() {\n    local in=$3\n    local out=$2\n    local search=$1\n\n    {\n        echo \"$bandwidth\"\n        # get the bandwidth\n        grep -e \"$search\" \"$in\"             | \\\n            tail -1                         | \\\n            awk '{print $10 \" \" $13}'\n    }  | column -t > \"$out\"\n\n    # check if the file actually produced valid content\n    [[ \"$(wc -l < \"$out\")\" -eq \"1\" ]] &&                        \\\n        echo \"Incorrect log file. No bandwidth records found\" ||  \\\n        echo \"Bandwidth written to $out\"\n}\n\nextract_median() {\n    local in=\"$1\"\n    local column=\"$2\"\n    local cnt\n    cnt=$(wc -l \"$in\" | cut -f 1 -d \" \")\n    local median=$((\"$cnt\"/2))\n    # get the median line's value\n    awk -v col=\"$column\" '{print $col}' \"$in\" | grep -E  '^[0-9]' | sort -n |\\\n        head -n \"$median\" | tail -n 1\n}\n\nprint_median_percentile() {\n    local tsv=$1\n    local i=2\n    local type=\"$2\"\n    echo -n \"$type \"\n    for _ in $percentiles; do\n        pct_val=$(extract_median \"$tsv\" $i)\n        echo -n \"$pct_val \"\n        i=$((i+1))\n    done\n    echo\n}\n\n\nout_dir=$(dirname \"$input_logfile\")\nfilename=$(basename \"$input_logfile\")\n\n# location of the intermediate tsv\nread_tsv=\"$out_dir/${filename%%.*}_read_latency.tsv\"\nwrite_tsv=\"$out_dir/${filename%%.*}_write_latency.tsv\"\nbandwidth_tsv=\"$out_dir/${filename%%.*}_bandwidth.tsv\"\n\nextract_latency \"NVM Write Latency\" \"$write_tsv\"  \"$input_logfile\"\nextract_latency \"NVM Read  Latency\" \"$read_tsv\"  \"$input_logfile\"\nextract_bandwidth \"egressBytesPerSec\" \"$bandwidth_tsv\"  \"$input_logfile\"\n\n# location of the final latency charts\nread_png=\"$out_dir/${filename%%.*}_read_latency.png\"\nwrite_png=\"$out_dir/${filename%%.*}_write_latency.png\"\nplot_file=\"$(dirname \"$0\")/gnuplot_latency.plt\"\n\nplot_png() {\n    gnuplot                     \\\n        -e \"tsv='$1'\"           \\\n        -e \"out_file='$2'\"      \\\n        -e \"chart_title='$3'\"   \\\n        \"$4\"                &&  \\\n            echo \"Plotted $3 in $2\" || \\\n            echo \"Failed to plot $3\"\n}\n\nplot_png \"$read_tsv\" \"$read_png\" \"Read Latency\" \"$plot_file\"\nplot_png \"$write_tsv\" \"$write_png\" \"Write Latency\" \"$plot_file\"\n\necho -e \"\\n\\n======= Median Latency ======= \"\n{\n    echo \"OpType $percentiles\"\n    print_median_percentile \"$read_tsv\" \"read\"\n    print_median_percentile \"$write_tsv\" \"write\"\n} | column -t\n", "num_lines": 147}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nNAME=cachelib\n\ndie()\n{\n  base=$(basename \"0\")\n  echo \"$base: error: $*\" >&2\n  exit 1\n}\n\ndir=$(dirname \"$0\")\ncd \"$dir/..\" || die \"failed to change-dir into $dir/..\"\ntest -d cachelib || die \"failed to change-dir to expected root directory\"\n\n\nmkdir -p \"build-$NAME\" || die \"failed to create build-$NAME directory\"\ncd \"build-$NAME\" || die \"'cd' failed\"\n\ncmake ../cachelib/ || die \"cmake failed\"\nmake -j --keep-going || die \"make failed\"\n#sudo make install || die \"make install failed\"\n\n#echo \"$NAME library is now installed\"\n", "num_lines": 38}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n## Note about shellcheck SC2086\n## \"Double-quote arguments to prevent globbing and word-splitting\"\n## https://github.com/koalaman/shellcheck/wiki/SC2086\n## In few cases the $XXX_PARAMS argument is NOT double-quoted\n## on purpose: it might be empty, and it might have several\n## distinct arguments to be passed to other scripts (e.g. \"-i -t -D\").\n##\n## As this is done purposfully, and the content of $XXX_PARAMS\n## is closely controlled, an explicit 'shellcheck disable SC2086'\n## was added to the relevant lines.\n\nset -u\n\ndie()\n{\n  base=$(basename \"$0\")\n  echo \"$base: error: $*\" >&2\n  exit 1\n}\n\nshow_help_and_exit()\n{\n  base=$(basename \"$0\")\n  echo \"CacheLib dependencies builder\n\nusage: $base [-BdhijStv] NAME\n\noptions:\n  -B    skip build step\n        (default is to build with cmake & make)\n  -d    build with DEBUG configuration\n        (default is RELEASE with debug information)\n  -h    This help screen\n  -i    install after build using 'sudo make install'\n        (default is to build but not install)\n  -j    build using all available CPUs ('make -j')\n        (default is to use single CPU)\n  -S    skip git-clone/git-pull step\n        (default is to get the latest source)\n  -t    build tests\n        (default is to skip tests if supported by the package)\n  -v    verbose build\n\nNAME: the dependency to build supported values are:\n  zstd\n  googlelog, googleflags, googletest,\n  fmt, sparsemap,\n  folly, fizz, wangle, fbthrift,\n  cachelib\n\n  \"\n  exit 0\n}\n\n###############################\n## Parse Commandline arguments\n###############################\ninstall=\nbuild=yes\nsource=yes\ndebug_build=\nbuild_tests=\nshow_help=\nmany_jobs=\nverbose=\nPREFIX=\"$PWD/opt/cachelib/\"\n\nwhile getopts :BSdhijtvp: param\ndo\n  case $param in\n    i) install=yes ;;\n    B) build= ;;\n    S) source= ;;\n    h) show_help=yes ;;\n    d) debug_build=yes ;;\n    v) verbose=yes ;;\n    j) many_jobs=yes ;;\n    t) build_tests=yes ;;\n    p) PREFIX=$OPTARG ;;\n    ?) die \"unknown option. See -h for help.\"\n  esac\ndone\ntest -n \"$show_help\" && show_help_and_exit;\nshift $((OPTIND-1))\n\ntest \"$#\" -eq 0 \\\n    && die \"missing dependancy name to build. See -h for help\"\n\n######################################\n## Check which dependency was requested\n######################################\n\nexternal_git_clone=\nexternal_git_branch=\n# external_git_tag can also be used for commit hashes\nexternal_git_tag=\nupdate_submodules=\ncmake_custom_params=\n\ncase \"$1\" in\n  googlelog)\n    NAME=glog\n    REPO=https://github.com/google/glog\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR\n    external_git_clone=yes\n    external_git_tag=\"v0.5.0\"\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    ;;\n\n  googleflags)\n    NAME=gflags\n    REPO=https://github.com/gflags/gflags\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR\n    external_git_clone=yes\n    external_git_tag=\"v2.2.2\"\n    cmake_custom_params=\"-DGFLAGS_BUILD_SHARED_LIBS=YES\"\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DGFLAGS_BUILD_TESTING=YES\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DGFLAGS_BUILD_TESTING=NO\"\n    fi\n    ;;\n\n  googletest)\n    NAME=googletest\n    REPO=https://github.com/google/googletest.git\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR\n    # Work-around: build googletest with DEBUG information\n    # results in CMake problems in detecting the library.\n    # See https://gitlab.kitware.com/cmake/cmake/-/issues/17799\n    # Disable debug build, even if requested.\n    if test \"$debug_build\" ; then\n        echo \"Note: disabling DEBUG mode for googletest build\"\n        debug_build=\n    fi\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    external_git_clone=yes\n    ;;\n\n  fmt)\n    NAME=fmt\n    REPO=https://github.com/fmtlib/fmt.git\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR\n    external_git_clone=yes\n    external_git_tag=\"8.0.1\"\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DFMT_TEST=YES\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DFMT_TEST=NO\"\n    fi\n    ;;\n\n  zstd)\n    NAME=zstd\n    REPO=https://github.com/facebook/zstd\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR/build/cmake\n    external_git_clone=yes\n    # Previously, we pinned to release branch. v1.5.4 needed\n    # CMake >= 3.18, later reverted. While waiting for v1.5.5,\n    # pin to the fix: https://github.com/facebook/zstd/pull/3510\n    external_git_tag=8420502e\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"-DZSTD_BUILD_TESTS=ON\"\n    else\n        cmake_custom_params=\"-DZSTD_BUILD_TESTS=OFF\"\n    fi\n    ;;\n\n  sparsemap)\n    NAME=sparsemap\n    REPO=https://github.com/Tessil/sparse-map.git\n    REPODIR=cachelib/external/$NAME\n    SRCDIR=$REPODIR\n    external_git_clone=yes\n    ;;\n\n  folly)\n    NAME=folly\n    SRCDIR=cachelib/external/$NAME\n    update_submodules=yes\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=ON\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=OFF\"\n    fi\n    ;;\n\n  fizz)\n    NAME=fizz\n    SRCDIR=cachelib/external/$NAME/$NAME\n    update_submodules=yes\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=ON\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=OFF\"\n    fi\n    ;;\n\n  wangle)\n    NAME=wangle\n    SRCDIR=cachelib/external/$NAME/$NAME\n    update_submodules=yes\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=ON\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=OFF\"\n    fi\n    ;;\n\n  fbthrift)\n    NAME=fbthrift\n    SRCDIR=cachelib/external/$NAME\n    update_submodules=yes\n    cmake_custom_params=\"-DBUILD_SHARED_LIBS=ON\"\n    ;;\n\n  cachelib)\n    NAME=cachelib\n    SRCDIR=cachelib\n    if test \"$build_tests\" = \"yes\" ; then\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=ON\"\n    else\n        cmake_custom_params=\"$cmake_custom_params -DBUILD_TESTS=OFF\"\n    fi\n    ;;\n\n  *) die \"unknown dependency '$1'. See -h for help.\"\nesac\n\n####################################\n## Calculate cmake/make parameters\n####################################\n\nCMAKE_PARAMS=\"$cmake_custom_params\"\ntest \"$debug_build\" \\\n  && CMAKE_PARAMS=\"$CMAKE_PARAMS -DCMAKE_BUILD_TYPE=Debug\" \\\n  || CMAKE_PARAMS=\"$CMAKE_PARAMS -DCMAKE_BUILD_TYPE=RelWithDebInfo\"\n\n\nMAKE_PARAMS=\ntest \"$verbose\" && MAKE_PARAMS=\"$MAKE_PARAMS VERBOSE=YES\"\n\nJOBS=$(nproc --ignore 1)\ntest \"$many_jobs\" && MAKE_PARAMS=\"$MAKE_PARAMS -j$JOBS\"\n\n\n\n\n####################################\n# Real work starts here\n####################################\n\n\ndir=$(dirname \"$0\")\ncd \"$dir/..\" || die \"failed to change-dir into $dir/..\"\ntest -d cachelib || die \"expected 'cachelib' directory not found in $PWD\"\n\n\n# After ensuring we are in the correct directory, set the installation prefix\"\nCMAKE_PARAMS=\"$CMAKE_PARAMS -DCMAKE_INSTALL_PREFIX=$PREFIX\"\nCMAKE_PREFIX_PATH=\"$PREFIX/lib/cmake:$PREFIX/lib64/cmake:$PREFIX/lib:$PREFIX/lib64:$PREFIX:${CMAKE_PREFIX_PATH:-}\"\nexport CMAKE_PREFIX_PATH\nPKG_CONFIG_PATH=\"$PREFIX/lib/pkgconfig:$PREFIX/lib64/pkgconfig:${PKG_CONFIG_PATH:-}\"\nexport PKG_CONFIG_PATH\nLD_LIBRARY_PATH=\"$PREFIX/lib:$PREFIX/lib64:${LD_LIBRARY_PATH:-}\"\nexport LD_LIBRARY_PATH\nPATH=\"$PREFIX/bin:$PATH\"\nexport PATH\n\n##\n## Update the latest source code\n##\n\nif test \"$source\" ; then\n\n  if test \"$external_git_clone\" ; then\n\n    # This is an external (non-facebook) project, clone/pull it.\n    if test -d \"$SRCDIR\" ; then\n      # cloned repository already exists, update it, unless we're on a specific tag\n      ( cd \"$SRCDIR\" && git fetch --all ) \\\n        || die \"failed to fetch git repository for '$NAME' in '$SRCDIR'\"\n    else\n      # Clone new repository directory\n      git clone \"$REPO\" \"$REPODIR\" \\\n        || die \"failed to clone git repository $REPO to '$REPODIR'\"\n    fi\n\n\n    # switch to specific branch/tag if needed\n    if test \"$external_git_branch\" ; then\n        ( cd \"$REPODIR\" \\\n           && git checkout --force \"origin/$external_git_branch\" ) \\\n           || die \"failed to checkout branch $external_git_branch in $REPODIR\"\n    elif test \"$external_git_tag\" ; then\n        ( cd \"$REPODIR\" \\\n           && git checkout --force \"$external_git_tag\" ) \\\n           || die \"failed to checkout tag $external_git_tag in $REPODIR\"\n    fi\n\n  fi\n\n  if test \"$update_submodules\" ; then\n    ./contrib/update-submodules.sh || die \"failed to update git-submodules\"\n  fi\nfi\n\n\n## If we do not build or install (only download the source code),\n## exit now.\nif test -z \"$build\" && test -z \"$install\" ; then\n  echo \"Source for '$NAME' downloaded/updated\"\n  exit 0\nfi\n\n\n# The build directory is needed for both build and installation\nmkdir -p \"build-$NAME\" || die \"failed to create build-$NAME directory\"\ncd \"build-$NAME\" || die \"'cd' failed\"\n\n##\n## Build\n##\nif test \"$build\" ; then\n  # shellcheck disable=SC2086\n  cmake $CMAKE_PARAMS \"../$SRCDIR\" || die \"cmake failed on $SRCDIR\"\n  # shellcheck disable=SC2086\n  nice make $MAKE_PARAMS || die \"make failed\"\nfi\n\n## If no install requested, exit now\nif test -z \"install\" ; then\n  echo \"'$NAME' is now built in build-$NAME (source in $REPODIR)\"\n  exit 0\nfi\n\n\n##\n## Install\n##\n\nif test \"$install\" ; then\n  # shellcheck disable=SC2086\n  make $MAKE_PARAMS install || die \"make install failed\"\nfi\n\necho \"'$NAME' is now installed\"\n", "num_lines": 372}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n## Note about shellcheck SC2086\n## \"Double-quote arguments to prevent globbing and word-splitting\"\n## https://github.com/koalaman/shellcheck/wiki/SC2086\n## In few cases the $pass_params argument is NOT double-quoted\n## on purpose: it might be empty, and it might have several\n## distinct arguments to be passed to other scripts (e.g. \"-i -t -D\").\n##\n## As this is done purposfully, and the content of $pass_params\n## is closely controlled, an explicit 'shellcheck disable SC2086'\n## was added to the relevant lines.\n\nset -u\n\ndie()\n{\n  base=$(basename \"$0\")\n  echo \"$base: error: $*\" >&2\n  exit 1\n}\n\ndetect_os()\n{\n  ### Detect by /etc/os-release (if exists)\n  if test -e /etc/os-release ; then\n    DETECTED=$(sh -c '. /etc/os-release ; echo ${ID}${VERSION_ID} | tr A-Z a-z')\n  fi\n\n\n  if test -z \"$DETECTED\" ; then\n    ### Detect by lsb_release (if exists)\n    if command -v lsb_release >/dev/null 2>&1 ; then\n      DETECTED=$(lsb_release -s -ir | tr -d '\\n' | tr '[:upper:]' '[:lower:]')\n    fi\n  fi\n\n  test -n \"$DETECTED\" || die \"failed to detect operating system type\"\n}\n\nbuild_debian_10()\n{\n  ./contrib//prerequisites-debian10.sh \\\n    || die \"failed to install packages for Debian\"\n}\n\nbuild_centos_8()\n{\n  ./contrib/prerequisites-centos8.sh \\\n    || die \"failed to install packages for CentOS\"\n}\n\nbuild_rocky_9()\n{\n  ./contrib/prerequisites-rocky9.sh \\\n    || die \"failed to install packages for RockyLinux 9\"\n}\n\nbuild_ubuntu_18()\n{\n  ./contrib//prerequisites-ubuntu18.sh \\\n    || die \"failed to install packages for Ubuntu\"\n}\n\nbuild_fedora_34()\n{\n  ./contrib//prerequisites-fedora34.sh \\\n    || die \"failed to install packages for Fedora\"\n}\n\nbuild_arch()\n{\n  ./contrib//prerequisites-arch.sh \\\n    || die \"failed to install packages for ArchLinux\"\n}\n\nbuild_dependencies()\n{\n  for pkg in zstd googleflags googlelog googletest sparsemap fmt folly fizz wangle fbthrift ;\n  do\n    # shellcheck disable=SC2086\n    ./contrib/build-package.sh $pass_params \"$pkg\" \\\n      || die \"failed to build dependency '$pkg'\"\n  done\n}\n\nshow_help_and_exit()\n{\n  base=$(basename \"$0\")\n  echo \"CacheLib dependencies builder\n\nusage: $base [-BdhijOStv]\n\noptions:\n  -B    skip build - just download packages and git source\n  -d    build with DEBUG configuration\n        (default is RELEASE with debug information)\n  -h    This help screen\n  -j    build using all available CPUs ('make -j')\n        (default is to use single CPU)\n  -O    skip OS package installation (apt/yum/dnf)\n  -S    skip git-clone/git-pull step\n  -t    build tests\n        (default is to skip tests if supported by the package)\n  -T    build only CacheLib tests\n  -v    verbose build\n\n  \"\n  exit 0\n}\n\n\n###############################\n## Parse Commandline arguments\n###############################\npass_params=\nskip_os_pkgs=\nskip_build=\nshow_help=\nbuild_cachelib_tests=\nwhile getopts BdhjOStvTp: param\ndo\n  case $param in\n  h)  show_help=yes ;;\n  O)  skip_os_pkgs=yes ;;\n  B)  skip_build=yes ;;\n  d|j|S|t|v) pass_params=\"$pass_params -$param\" ;;\n  T)  build_cachelib_tests=yes ;;\n  p)  pass_params=\"$pass_params -$param $OPTARG\" ;;\n  ?)      die \"unknown option. See -h for help.\"\n  esac\ndone\ntest -n \"$show_help\" && show_help_and_exit;\n\ntest -n \"$skip_build\" \\\n  && pass_params=\"$pass_params -B\" \\\n  || pass_params=\"$pass_params -i\"\n\n\n# Nothing detected so far\nDETECTED=\ndetect_os\n\nif test -z \"$skip_os_pkgs\" ; then\n  case \"$DETECTED\" in\n    debian10|debian11) build_debian_10 ;;\n    ubuntu18.04|ubuntu20.04|ubuntu21.04|ubuntu22.04) build_ubuntu_18 ;;\n    centos8|rocky8.?) build_centos_8 ;;\n    rocky9.?) build_rocky_9 ;;\n    fedora3[456]) build_fedora_34 ;;\n    arch*|manjaro*) build_arch ;;\n    *) die \"No build recipe for detected operating system '$DETECTED'\" ;;\n  esac\nfi\n\nbuild_dependencies\n\ntest -n \"$build_cachelib_tests\" \\\n  && pass_params=\"$pass_params -t\"\n\n# shellcheck disable=SC2086\n./contrib/build-package.sh $pass_params cachelib \\\n  || die \"failed to build cachelib\"\n", "num_lines": 177}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o pipefail\nexport LC_ALL=C\n\n# In case these directories were not included\nexport LD_LIBRARY_PATH=/usr/local/lib64:/usr/local/lib:$LD_LIBRARY_PATH\n\n# Default installation path\nBINARY=opt/cachelib/bin/cachebench\n\n\n\ndie()\n{\n  base=$(basename \"$0\")\n  echo \"$base: error: $*\" >&2\n  exit 1\n}\n\ndir=$(dirname \"$0\")\ncd \"$dir/..\" || die \"failed to change-dir into $dir/..\"\ntest -d cachelib || die \"failed to change-dir to expected root directory\"\n\ntest -d build-cachelib || die \"the 'build-cachelib' directory wasn't found (try ./contrib/build-cachelib.sh)\"\n\ntest -e \"$BINARY\" || die \"the executable '$BINARY' was not found\"\n\n# Ensure all libraries are found\nif ldd \"$BINARY\" 2>&1 | grep -q \"not found\" ; then\n  die \"some shared-object/libraries not found for '$BINARY' - check \\$LD_LIBRARY_PATH\"\nfi\n\nd=$(date +%F-%H%M%S)\n\ndst=dist-$d\n\n# Find parent directory of the binary\nBASE_DIR=$(dirname \"$BINARY\")\nBASE_DIR=$(dirname \"$BASE_DIR\")\nLIB_OS_DIR=\"$BASE_DIR/lib-os\"\n\nmkdir -p \"$LIB_OS_DIR\" \\\n  || die \"failed to create directory '$LIB_OS_DIR'\"\n\nldd \"$BINARY\" \\\n    | awk '/=>/ { print $3 }' \\\n    | sort -u \\\n    | xargs -I% realpath --no-symlinks --relative-base=\"$BASE_DIR\" \"%\" \\\n    | grep \"^/\" \\\n    | grep -vE \"lib(c|m|dl|rt|pthread)[-.]\" \\\n    | sed -E 's/\\.so\\.[0-9.]*$/\\.so*/' \\\n    | xargs echo cp --no-dereference -t \"$LIB_OS_DIR\" \\\n    | sh \\\n   || die \"failed to extract and copy shared-object dependencies\"\n\n\ntar -C opt -czf \"cachelib-rpath-binary-$d.tar.gz\" cachelib \\\n  || die \"failed to create tarball\"\n\n\necho \"\n  Tarball in:\n     cachelib-rpath-binary-$d.tar.gz\n\"\n", "num_lines": 79}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo pacman -S --needed --noconfirm cmake \\\n  make \\\n  gcc \\\n  boost \\\n  double-conversion \\\n  libdwarf \\\n  numactl \\\n  libsodium\n", "num_lines": 24}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo dnf install -y epel-release\nsudo dnf groupinstall -y \"Development Tools\"\nsudo dnf install -y \\\n  libtool bison flex cmake \\\n  double-conversion double-conversion-devel \\\n  boost-devel \\\n  libevent-devel \\\n  openssl-devel \\\n  libunwind-devel \\\n  zlib-devel \\\n  lz4-devel \\\n  xz-devel \\\n  bzip2-devel \\\n  jemalloc-devel \\\n  libsodium-devel \\\n  libaio-devel \\\n  binutils-devel\n\n\n# Install and enable the \"PowerTools\" repository\nsudo dnf -y install dnf-plugins-core\nsudo dnf -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm\n\n# CentOS Repository name changed from \"PowerTools\" to \"powertools\" (and back?)\n# Get the list of ALL repositories, try to detect the 'powertools' one.\n# We could do:\n#    dnf config-manager --set-enabled PowerTools\n#    dnf config-manager --set-enabled powertools\n# But we don't want to change the system's repository configuration.\n\n# Show list of repos (for debugging)\nsudo dnf repolist --all\n\nPOWERTOOLS_REPO=$(sudo dnf repolist --all | grep -i '^powertools' | awk '{print $1}')\necho \"Detected CentOS Powertools repository: '$POWERTOOLS_REPO'\"\n\nsudo dnf --enablerepo=\"$POWERTOOLS_REPO\" install -y \\\n  libdwarf-devel \\\n  snappy-devel \\\n  gmock-devel \\\n  gtest-devel \\\n  libsodium-static \\\n  libdwarf-static \\\n  boost-static \\\n  double-conversion-static \\\n  numactl-devel\n\n#Do not install these from OS packages - they are typically outdated.\n#gflags-devel \\\n#glog \\\n#fmt \\\n", "num_lines": 67}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo apt-get update\nsudo apt-get install -y \\\n  build-essential \\\n  git \\\n  g++ \\\n  cmake \\\n  bison flex \\\n  libboost-all-dev \\\n  libevent-dev \\\n  libdouble-conversion-dev \\\n  libgoogle-glog-dev \\\n  libgflags-dev \\\n  libiberty-dev \\\n  liblz4-dev \\\n  liblzma-dev \\\n  libbz2-dev \\\n  libsnappy-dev \\\n  make \\\n  zlib1g-dev \\\n  binutils-dev \\\n  libjemalloc-dev \\\n  libssl-dev \\\n  pkg-config \\\n  libunwind-dev \\\n  libelf-dev \\\n  libdwarf-dev \\\n  libsodium-dev \\\n  libgmock-dev \\\n  libgtest-dev googletest \\\n  libnuma-dev\n", "num_lines": 46}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo dnf -y update\nsudo dnf groupinstall -y \"Development Tools\"\nsudo dnf -y install bison flex patch bzip2 cmake \\\n  double-conversion double-conversion-devel \\\n  boost-devel libevent-devel openssl-devel libunwind-devel \\\n  zlib-devel lz4-devel xz-devel bzip2-devel \\\n  jemalloc-devel snappy-devel libsodium-devel libdwarf-devel libaio-devel \\\n  gmock-devel gflags-devel gtest gtest-devel \\\n  numactl-devel \\\n  fmt fmt-devel\n\n# DO NOT INSTALL glog-devel - need to build from source for the glog-*.cmake files\n", "num_lines": 28}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo dnf -y update\nsudo dnf groupinstall -y \"Development Tools\"\nsudo dnf -y install bison flex patch bzip2 cmake \\\n  double-conversion double-conversion-devel make g++ \\\n  boost-devel libevent-devel openssl-devel libunwind-devel \\\n  zlib-devel lz4-devel xz-devel bzip2-devel \\\n  jemalloc-devel snappy-devel libsodium-devel libdwarf-devel libaio-devel \\\n  numactl-devel\n", "num_lines": 24}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# RockyLinux 9 diverged from CentOS, instead of \"Powertools\" repo,\n# use CRB (CodeBuild Ready).\n# see: https://wiki.rockylinux.org/rocky/repo/\n\nsudo dnf update -y\nsudo dnf install dnf-plugins-core\nsudo dnf install -y epel-release\nsudo dnf config-manager --set-enabled crb\n\nsudo dnf groupinstall -y \"Development Tools\"\nsudo dnf install -y \\\n  libtool bison flex cmake \\\n  double-conversion double-conversion-devel \\\n  boost-devel \\\n  libevent-devel \\\n  openssl-devel \\\n  libunwind-devel \\\n  zlib-devel \\\n  lz4-devel \\\n  xz-devel \\\n  bzip2-devel \\\n  jemalloc-devel \\\n  libsodium-devel \\\n  libaio-devel \\\n  binutils-devel \\\n  numactl-devel\n\n\nsudo dnf install -y \\\n  libdwarf-devel \\\n  snappy-devel \\\n  gmock-devel \\\n  gtest-devel \\\n  libsodium-static \\\n  libdwarf-static \\\n  boost-static \\\n  double-conversion-devel\n", "num_lines": 54}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nsudo apt-get update\nsudo apt-get install -y \\\n  build-essential \\\n  git \\\n  g++ \\\n  cmake \\\n  bison flex \\\n  libboost-all-dev \\\n  libevent-dev \\\n  libdouble-conversion-dev \\\n  libgoogle-glog-dev \\\n  libgflags-dev \\\n  libiberty-dev \\\n  liblz4-dev \\\n  liblzma-dev \\\n  libbz2-dev \\\n  libsnappy-dev \\\n  make \\\n  zlib1g-dev \\\n  binutils-dev \\\n  libjemalloc-dev \\\n  libssl-dev \\\n  pkg-config \\\n  libunwind-dev \\\n  libelf-dev \\\n  libdwarf-dev \\\n  libsodium-dev \\\n  libnuma-dev\n\n# NOTE:\n# GoogleTest/GoogleMock libraries are available in Ubuntu as\n# Standard packages, but the do not contain the required CMAKE\n# files, and aren't detected when building CacheLib.\n# So on Ubuntu-18 - build googletest from source.\n### googletest libgtest-dev google-mock\n", "num_lines": 51}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ndie()\n{\n  base=$(basename \"$0\")\n  echo \"$base: error: $*\" >&2\n  exit 1\n}\n\ndir=$(dirname \"$0\")\ncd \"$dir/..\" || die \"failed to change-dir into $dir/..\"\ntest -d cachelib || die \"failed to change-dir to expected root directory\"\n\ngit submodule update --init --checkout --force\ngit submodule foreach git fetch\n\nroot=./cachelib/external\n\n# Temporary hack:\n# After updating, checkout the required version based on fbthrift's files.\nfile=\"$root/fbthrift/build/deps/github_hashes/facebook/wangle-rev.txt\"\nwangle_rev=$(awk '{print $3}' $file) \\\n  || die \"failed to detect required wangle revision\"\n\n( cd \"$root/wangle\" ; git checkout --force \"$wangle_rev\" ) \\\n  || die \"failed to checkout required wangle revision '$wangle_rev'\"\n\n# Based on Wangle, checkout fizz\nfile=\"$root/wangle/build/deps/github_hashes/facebookincubator/fizz-rev.txt\"\nfizz_rev=$(awk '{print $3}' $file) \\\n  || die \"failed to detect required fizz revision\"\n\n( cd \"$root/fizz\" ; git checkout --force \"$fizz_rev\" ) \\\n  || die \"failed to checkout required fizz revision '$fizz_rev'\"\n", "num_lines": 48}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# Root directory for the CacheLib project\nCLBASE=\"$PWD/../..\"\n\n# Additional \"FindXXX.cmake\" files are here (e.g. FindSodium.cmake)\nCLCMAKE=\"$CLBASE/cachelib/cmake\"\n\n# After ensuring we are in the correct directory, set the installation prefix\"\nPREFIX=\"$CLBASE/opt/cachelib/\"\n\nCMAKE_PARAMS=\"-DCMAKE_INSTALL_PREFIX='$PREFIX' -DCMAKE_MODULE_PATH='$CLCMAKE'\"\n\nCMAKE_PREFIX_PATH=\"$PREFIX/lib/cmake:$PREFIX/lib64/cmake:$PREFIX/lib:$PREFIX/lib64:$PREFIX:${CMAKE_PREFIX_PATH:-}\"\nexport CMAKE_PREFIX_PATH\nPKG_CONFIG_PATH=\"$PREFIX/lib/pkgconfig:$PREFIX/lib64/pkgconfig:${PKG_CONFIG_PATH:-}\"\nexport PKG_CONFIG_PATH\nLD_LIBRARY_PATH=\"$PREFIX/lib:$PREFIX/lib64:${LD_LIBRARY_PATH:-}\"\nexport LD_LIBRARY_PATH\n\nmkdir -p build\ncd build\ncmake $CMAKE_PARAMS ..\nmake\n", "num_lines": 40}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# Root directory for the CacheLib project\nCLBASE=\"$PWD/../..\"\n\n# Additional \"FindXXX.cmake\" files are here (e.g. FindSodium.cmake)\nCLCMAKE=\"$CLBASE/cachelib/cmake\"\n\n# After ensuring we are in the correct directory, set the installation prefix\"\nPREFIX=\"$CLBASE/opt/cachelib/\"\n\nCMAKE_PARAMS=\"-DCMAKE_INSTALL_PREFIX='$PREFIX' -DCMAKE_MODULE_PATH='$CLCMAKE'\"\n\nCMAKE_PREFIX_PATH=\"$PREFIX/lib/cmake:$PREFIX/lib64/cmake:$PREFIX/lib:$PREFIX/lib64:$PREFIX:${CMAKE_PREFIX_PATH:-}\"\nexport CMAKE_PREFIX_PATH\nPKG_CONFIG_PATH=\"$PREFIX/lib/pkgconfig:$PREFIX/lib64/pkgconfig:${PKG_CONFIG_PATH:-}\"\nexport PKG_CONFIG_PATH\nLD_LIBRARY_PATH=\"$PREFIX/lib:$PREFIX/lib64:${LD_LIBRARY_PATH:-}\"\nexport LD_LIBRARY_PATH\n\nmkdir -p build\ncd build\ncmake $CMAKE_PARAMS ..\nmake\n", "num_lines": 40}
{"repo_name": "CacheLib", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\n\n# Root directory for the CacheLib project\nCLBASE=\"$PWD/../..\"\n\n# Additional \"FindXXX.cmake\" files are here (e.g. FindSodium.cmake)\nCLCMAKE=\"$CLBASE/cachelib/cmake\"\n\n# After ensuring we are in the correct directory, set the installation prefix\"\nPREFIX=\"$CLBASE/opt/cachelib/\"\n\nCMAKE_PARAMS=\"-DCMAKE_INSTALL_PREFIX='$PREFIX' -DCMAKE_MODULE_PATH='$CLCMAKE'\"\n\nCMAKE_PREFIX_PATH=\"$PREFIX/lib/cmake:$PREFIX/lib64/cmake:$PREFIX/lib:$PREFIX/lib64:$PREFIX:${CMAKE_PREFIX_PATH:-}\"\nexport CMAKE_PREFIX_PATH\nPKG_CONFIG_PATH=\"$PREFIX/lib/pkgconfig:$PREFIX/lib64/pkgconfig:${PKG_CONFIG_PATH:-}\"\nexport PKG_CONFIG_PATH\nLD_LIBRARY_PATH=\"$PREFIX/lib:$PREFIX/lib64:${LD_LIBRARY_PATH:-}\"\nexport LD_LIBRARY_PATH\n\nmkdir -p build\ncd build\ncmake $CMAKE_PARAMS ..\nmake\n", "num_lines": 41}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2022-present, Meta, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# Shell script so that this can be made non-dependent on\n# chef-workstation in the future\nexec /opt/chef-workstation/embedded/bin/ruby /usr/local/lib/bookworm/bookworm.rb \"$@\"\n", "num_lines": 20}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2018-present, Facebook, Inc.\n\nif [ $# -lt 1 ] || [ \"$1\" == \"-h\" ] || [ \"$1\" == \"--help\" ]; then\n  echo \"Uses file locking to runs a single instance of a command \"\n  echo \"on a host at a time. Intended to stop cron job stampedes\"\n  echo \"\"\n  echo \"Usage: exclusive_cron.sh <lockfile path> <command to run>\"\n  echo \"\"\n  echo \"NOTE: Uses flock, so lockfiles must be on local storage\" \n  exit 1;\nfi\n\nLOCKFILE=\"${1}\"\nshift 1\nCOMMAND=\"$*\"\n\nif [ -e \"${LOCKFILE}\" ] && [ ! -f \"${LOCKFILE}\" ]; then\n  echo \"Lockfile ${LOCKFILE} exists, but is not a file\"\n  exit 1;\nfi\n\nfunction on_exit() {\n  rm -f \"${LOCKFILE}\";\n}\n\n# FD200 is completely arbitrary\n(\n  if ! flock -x -w 0.001 200; then \n    echo \"Command '${COMMAND}' with lockfile '${LOCKFILE}' is already running\"\n    exit 1\n  fi\n  trap 'on_exit' EXIT\n  eval \"${COMMAND}\"\n) 200>\"${LOCKFILE}\"\n", "num_lines": 37}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2018-present, Facebook, Inc.\n#\n# OS X doesn't support cron.d directories. It also doesn't have a stock\n# /etc/crontab -- so we fake it here.\n\nset -e\n\n# OS X also doesn't have a \"tempfile\" command...\ntempfile=\"/tmp/cron.d.$$\"\n\ncat /etc/cron.d/* > \"$tempfile\"\n\nif ! diff \"$tempfile\" \"/etc/crontab\" > /dev/null 2> /dev/null\nthen\n  echo \"Installing new /etc/crontab\"\n  mv -f \"$tempfile\" /etc/crontab\nelse\n  rm -f \"$tempfile\"\nfi\n\n", "num_lines": 23}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# vim: syntax=sh:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n\nset -u\n\n# This script is meant to be called in dbus.service by ExecStartPost. It will\n# trigger a systemd reload, unless it's the first time it runs or when current\n# systemd target is active, which means systemd finished boot up procedure.\n\nflag='/run/dbus-was-started-once'\n\n# current systemd target\ntarget=$(systemctl get-default)\n\n# status of systemd target\nresult=$(systemctl is-active \"$target\")\n\nif [ -r \"$flag\" ]; then\n  echo 'dbus-restart-hack: reloading systemd as the flag file exists'\n  sleep 1\n  /usr/bin/systemctl daemon-reload\nelif [ \"$result\" = \"active\" ]; then\n  echo \"dbus-restart-hack: reloading systemd as current target $target is active\"\n  sleep 1\n  /usr/bin/systemctl daemon-reload\nelse\n  echo 'dbus-restart-hack: not reloading systemd as this is the first start'\nfi\n\ntouch \"$flag\"\n\nexit 0\n", "num_lines": 34}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# shellcheck disable=SC2086,SC2018,SC2019,SC1090,SC2064,SC2124,SC2181,SC2002,SC2153,SC2046,SC2173,SC2230\n#\n# Copyright (c) 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# Simple script for chef to call to\n# dump and reload custom chain rules\n\nset -u\n\nCONFIG='/etc/fb_iptables.conf'\nTMPDIR=$(mktemp -d /tmp/fb_iptables.XXXXXXXXXXXX)\ntrap \"rm -rf $TMPDIR &>/dev/null\" exit INT TERM KILL\n\nhelp_print() {\n  echo \"$0 [4|6] <action>\"\n  exit;\n}\n\nexit_error() {\n  msg=\"$@\"\n  echo \"ERROR: $msg\"\n  exit 1\n}\n\n# Walk dynamic changes for a table and dump them to temp files in, if they exist\ndump_dynamic_chains() {\n  local table=\"$1\"\n  local dynamic_chains=\"$2\"\n  local outfile\n  local chain_regex\n  echo -n \"  - Stashing dynamic chains on $table: \"\n  for chain in $dynamic_chains; do\n    echo -n \"$chain  \"\n    \"${IPTABLES_CMD}\" -t \"$table\" -S | grep -q \"\\-N $chain\"\n    if [ $? -ne 0 ]; then\n      echo '(no chain yet, nothing to stash) '\n      continue\n    fi\n    outfile=$TMPDIR/${table}_${chain}_rules\n    chain_regex=\"\\-A $chain \"\n    out=$(\"${IPTABLES_CMD}\" -t \"$table\" -S)\n    if [ $? -ne 0 ]; then\n      exit_error \"Failed to stash $chain on $table\"\n    fi\n    if [ -n \"$out\" ]; then\n      echo \"$out\" | grep \"$chain_regex\" > \"$outfile\"\n    fi\n  done\n  echo 'done.'\n}\n\n# Restore any registered chains we found and backed up\nrestore_dynamic_chains() {\n  local table=\"$1\"\n  local dynamic_chains=\"$2\"\n\n  echo -n \"  - Restoring dynamic chains on $table: \"\n  for chain in $dynamic_chains; do\n    echo -n \"$chain \"\n    local rules_file=$TMPDIR/${table}_${chain}_rules\n    if [ ! -r $rules_file ]; then\n      echo '(no chain to restore) '\n      continue\n    fi\n\n    ${IPTABLES_CMD} -t $table -F $chain\n    while read -r rule\n    do\n      ${IPTABLES_CMD} -t $table $rule\n    done < \"$rules_file\"\n  done\n  echo 'done.'\n}\n\nreload_static_chains() {\n  local table=\"$1\"\n\n  # NOTE: You cannot use '-t' here ... ip6tables-* choke on it... you must\n  # specify --table=\n  echo \"  - Reloading $table\"\n  cat \"${CONFIG_DIR}/${IPTABLES_RULES_FILE}\" | ${IPTABLES_CMD}-restore --table=$table\n}\n\nreload() {\n    for table in $TABLES; do\n      # iptables-restore triggers loading modules, even with empty\n      # rules.  Let's avoid that (t28313270).\n      echo \"Reloading $table...\"\n      cap_table=$(echo $table | tr 'a-z' 'A-Z')\n      static_chains=$(eval echo \\$STATIC_${cap_table}_CHAINS)\n      if [ -z \"$static_chains\" ] && ! grep -q $table /proc/net/ip*_tables_names; then\n        continue\n      fi\n      dynamic_chains=$(eval echo \\$${cap_table}_CHAINS)\n      dump_dynamic_chains $table \"$dynamic_chains\"\n      reload_static_chains $table\n      restore_dynamic_chains $table \"$dynamic_chains\"\n  done\n}\n\n[ -r \"$CONFIG\" ] && . $CONFIG\n\n# Poor mans help print\nif [ \"$1\" == \"help\" ]; then\n  help_print\nfi\n\n# v4 or v6\nIPTABLES_CMD=ip6tables\nIPTABLES_RULES_FILE=\"$RULES6_FILE\"\nif [ \"$1\" == \"4\" ]; then\n  IPTABLES_CMD=iptables\n  IPTABLES_RULES_FILE=\"$RULES_FILE\"\nfi\nACTION=\"$2\"\n\nif [ ! -x $(which \"${IPTABLES_CMD}\") ]; then\n  echo \"ERROR: No ${IPTABLES_CMD} in path bro ...\"\n  exit 1\nfi\n\ncase \"$ACTION\" in\n  reload)\n    reload\n    ;;\n  *)\n    help_print\n    ;;\nesac\n", "num_lines": 145}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# To use this filter with less, define LESSOPEN:\n# export LESSOPEN=\"|/usr/bin/lesspipe.sh %s\"\n#\n# The script should return zero if the output was valid and non-zero\n# otherwise, so less could detect even a valid empty output\n# (for example while uncompressing gzipped empty file).\n# For backward-compatibility, this is not required by default. To turn\n# this functionality there should be another vertical bar (|) straight\n# after the first one in the LESSOPEN environment variable:\n# export LESSOPEN=\"||/usr/bin/lesspipe.sh %s\"\n\nif [ ! -e \"$1\" ] ; then\n\texit 1\nfi\n\nif [ -d \"$1\" ] ; then\n\tls -alF -- \"$1\"\n\texit $?\nfi\n\nexec 2>/dev/null\n\n# Allow for user defined filters\nif [ -x ~/.lessfilter ]; then\n\tif ~/.lessfilter \"$1\"; then\n\t\texit 0\n\tfi\nfi\n\nmanfilter ()\n{\n\tif test -x /usr/bin/man ; then\n\t\t# See rhbz#1241543 for more info.  Well, actually we firstly\n\t\t# used 'man -l', then we switched to groff, and then we again\n\t\t# switched back to 'man -l'.\n\t\t/usr/bin/man -P /usr/bin/cat -l \"$1\"\n\telif test -x /usr/bin/groff; then\n\t\t# This is from pre-rhbz#1241543-time.\n\t\tgroff -Tascii -mandoc \"$1\" | cat -s\n\telse\n\t\techo \"WARNING:\"\n\t\techo \"WARNING: to better show manual pages, install 'man-db' package\"\n\t\techo \"WARNING:\"\n\t\tcat \"$1\"\n\tfi\n}\n\nexport MAN_KEEP_FORMATTING=1\n\ncase \"$1\" in\n*.[1-9n].bz2|*.[1-9]x.bz2|*.man.bz2|*.[1-9n].[gx]z|*.[1-9]x.[gx]z|*.man.[gx]z|*.[1-9n].lzma|*.[1-9]x.lzma|*.man.lzma|*.[1-9n].zst|*.[1-9]x.zst|*.man.zst)\n\tcase \"$1\" in\n\t*.gz)\t\tDECOMPRESSOR=\"gzip -dc\" ;;\n\t*.bz2)\t\tDECOMPRESSOR=\"bzip2 -dc\" ;;\n\t*.xz|*.lzma)\tDECOMPRESSOR=\"xz -dc\" ;;\n\t*.zst)\t\tDECOMPRESSOR=\"zstd -dcq\" ;;\n\tesac\n\tif [ -n \"$DECOMPRESSOR\" ] && $DECOMPRESSOR -- \"$1\" | file - | grep -q troff; then\n\t\t$DECOMPRESSOR -- \"$1\" | manfilter -\n\t\texit $?\n\tfi ;;&\n*.[1-9n]|*.[1-9]x|*.man)\n\tif file \"$1\" | grep -q troff; then\n\t\tmanfilter \"$1\"\n\t\texit $?\n\tfi ;;&\n*.tar) tar tvvf \"$1\"; exit $? ;;\n*.tgz|*.tar.gz|*.tar.[zZ]) tar tzvvf \"$1\"; exit $? ;;\n*.tar.xz) tar Jtvvf \"$1\"; exit $? ;;\n*.tzst|*.tar.zst) tar -I zstd tvvf \"$1\"; exit $? ;;\n*.xz|*.lzma) xz -dc -- \"$1\"; exit $? ;;\n*.tar.bz2|*.tbz2) bzip2 -dc -- \"$1\" | tar tvvf -; exit $? ;;\n*.[zZ]|*.gz) gzip -dc -- \"$1\"; exit $? ;;\n*.bz2) bzip2 -dc -- \"$1\"; exit $? ;;\n*.zst) zstd -dcq -- \"$1\"; exit $? ;;\n*.zip|*.jar|*.nbm) zipinfo -- \"$1\"; exit $? ;;\n# --nomanifest -> rhbz#1450277\n*.rpm) rpm -qpivl --changelog --nomanifest -- \"$1\"; exit $? ;;\n*.cpi|*.cpio) cpio -itv < \"$1\"; exit $? ;;\n*.gpg)\n\tif [ -x /usr/bin/gpg2 ]; then\n\t\tgpg2 -d \"$1\"\n\t\texit $?\n\telif [ -x /usr/bin/gpg ]; then\n\t\tgpg -d \"$1\"\n\t\texit $?\n\telse\n\t\techo \"No GnuPG available.\"\n\t\techo \"Install gnupg2 or gnupg to show encrypted files.\"\n\t\texit 1\n\tfi ;;\n*.gif|*.jpeg|*.jpg|*.pcd|*.png|*.tga|*.tiff|*.tif)\n\tif [ -x /usr/bin/identify ]; then\n\t\tidentify \"$1\"\n\t\texit $?\n\telif [ -x /usr/bin/gm ]; then\n\t\tgm identify \"$1\"\n\t\texit $?\n\telse\n\t\techo \"No identify available\"\n\t\techo \"Install ImageMagick or GraphicsMagick to browse images\"\n\t\texit 1\n\tfi ;;\n*)\n\tif [ -x /usr/bin/file ] && [ -x /usr/bin/iconv ] && [ -x /usr/bin/cut ]; then\n    case $(file -b \"$1\") in\n\t\t*UTF-16*) conv='UTF-16' ;;\n\t\t*UTF-32*) conv='UTF-32' ;;\n\t\tesac\n\t\tif [ -n \"$conv\" ]; then\n      env=$(echo \"$LANG\" | cut -d. -f2)\n\t\t\tif [ -n \"$env\" ] && [ \"$conv\" != \"$env\" ]; then\n\t\t\t\ticonv -f \"$conv\" -t \"$env\" \"$1\"\n\t\t\t\texit $?\n\t\t\tfi\n\t\tfi\n\tfi\n\texit 1\nesac\n", "num_lines": 122}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck shell=sh\n\n# Set some useful LESS options.  If you prefer your own, set it in\n# your shell startup script and it will be honored.\nif [ -z \"${LESS+set}\" ]; then\n    export LESS='-n -i'\nfi\nif [ -z \"${LESSOPEN+set}\" ]; then\n\texport LESSOPEN='||/usr/local/bin/lesspipe.sh %s'\nfi\n", "num_lines": 11}
{"repo_name": "chef-cookbooks", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n#\n# Copyright (c) 2022-present, Vicarious, Inc.\n# All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A script to help downstream users keep cookbooks in sync\n\nset -u\n\n# constants\nCONF=\"$HOME/.config/sync_fb_cookbooks.conf\"\n\n# defaults\nupstreamdir=\"$HOME/src/chef-cookbooks\"\ninternaldir=\"$HOME/src/chef\"\n\n# methods\nerror() {\n    echo \"ERROR: $*\"\n}\n\nwarn() {\n    echo \"WARNING: $*\"\n}\n\ndie() {\n    error \"$@\"\n    exit 1\n}\n\nourhelp() {\n    cat <<EOF\nUsage: $0 [<options>]\n\nOPTIONS\n    -c <cookbook>\n        Compare just <cookbook>\n\n    -d\n        Diff mode.\n\n    -h\n        This.\n\n    -i <dir>\n        Where your clone of the INTERNAL repo is.\n        Default: $internaldir\n\n    -p\n        Push changes internal -> upstream\n\n    -s\n        Sync changes upstream -> internal\n\n    -u <dir>\n        Where your clone of the UPSTREAM repo is.\n        Default: $internaldir\n\nCONFIG FILE\nYou can also tell this script where your repos are by creating $CONF\nin shell format and defining 'upstreamdir' and 'internaldir', like so:\n\n    upstreamdir=\"\\$HOME/mycheckouts/chef-cookbooks\"\n    internaldir=\"\\$HOME/mycheckouts/chef\"\n\nGENERAL USAGE\n    # get a list of cookbooks that differ\n    $ $0\n    ...\n    fb_sysfs does not match\n    ...\n\n    # Get a diff for a specific cookbook\n    $ $0 -c fb_sysfs\n    ...\n\n    # Pull in upstream changes\n    $ $0 -c fb_sysfs -s\n    ...\n\n    # OR.... push out internal changes\n    $ $0 -c fb_sysfs -p\n\nEOF\n}\n\n# people put repos in different places, don't make them pass in\n# -u and -i every time.\nif [ -e \"$CONF\" ]; then\n    # shellcheck disable=SC1090\n    source \"$CONF\" || die \"Configuration file $CONF malformed\"\nfi\n\nmode=''\ncookbook=''\nwhile getopts c:dhi:psu: opt; do\n    case $opt in\n        c)\n            cookbook=\"$OPTARG\"\n            ;;\n        d)\n            mode='diff'\n            ;;\n        h)\n            ourhelp\n            exit\n            ;;\n        i)\n            internaldir=\"$OPTARG\"\n            ;;\n        p)\n            mode='push'\n            ;;\n        s)\n            mode='sync'\n            ;;\n        u)\n            upstreamdir=\"$OPTARG\"\n            ;;\n        ?)\n            ourhelp\n            exit 1\n            ;;\n    esac\ndone\n\nif [ -z \"$mode\" ]; then\n    if [ -n \"$cookbook\" ]; then\n        mode='diff'\n    else\n        mode='status'\n    fi\nfi\n\ncd \"$internaldir/cookbooks\" || die \"where am I?\"\n[ -z \"$cookbook\" ] && cookbook=\"$(ls -d fb_*)\"\nfor cb in $cookbook; do\n    ours=\"$cb/\"\n    upstream=\"$upstreamdir/cookbooks/$cb/\"\n    if [ \"$cb\" = 'fb_init' ]; then\n        upstream=\"$upstreamdir/cookbooks/fb_init_sample/\"\n    fi\n    if [ \"$mode\" = 'status' ]; then\n        diff -Nru \"$ours\" \"$upstream\" &>/dev/null || echo \"$cb does not match\"\n    elif [ \"$mode\" = 'diff' ]; then\n        diff -Nru \"$ours\" \"$upstream\"\n    elif [ \"$mode\" = 'push' ]; then\n        rsync -avz \"$ours\" \"$upstream\"\n    elif [ \"$mode\" = 'sync' ]; then\n        rsync -avz \"$upstream\" \"$ours\"\n    else\n        die \"wut? wut mode is '$mode'\"\n    fi\ndone\n", "num_lines": 169}
{"repo_name": "componentkit", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Go to root directory of the script\npushd $(dirname $0)\n\nif [ -z $1 ]; then\n  echo \"usage: build.sh <subcommand>\"\n  echo \"available subcommands:\"\n  echo \"  ci-componentkit-ios\"\n  echo \"  ci-componentkit-tvos\"\n  echo \"  ci-wildeguess-ios\"\n  echo \"  docs\"\n  exit\nfi\n\nset -eu\n\nMODE=$1\n\nfunction project_version() {\n  # get contents -> grep for project version line -> cut string with '=' delimeter, take 2nd value -> trim whitespaces.\n  more ComponentKit/ComponentKit.xcconfig | grep \"CURRENT_PROJECT_VERSION = [\\.0-9]*\" | cut -d = -f 2 | xargs echo -n\n}\n\nfunction ci() {\n  # replace line contains s.version with a new line contains value of `project_version`.\n  sed -i -e \"s/s.version = \\'[\\.0-9]*\\'/s.version = \\'$(project_version)\\'/g\" ComponentKit.podspec\n\n  xcodebuild \\\n    clean \\\n    -project $1 \\\n    -scheme $2 \\\n    -sdk $3 \\\n    -destination \"$4\" \\\n    -configuration $5 \\\n    $6 \\\n    -json \\\n    -UseModernBuildSystem=NO\n}\n\nfunction ios_ci() {\n  ci $1 $2 iphonesimulator \"platform=iOS Simulator,name=iPhone 8\" Release $3\n}\n\nfunction tvos_ci() {\n  ci $1 $2 appletvsimulator \"platform=tvOS Simulator,name=Apple TV\" Release $3\n}\n\nfunction carthage_bootstrap() {\n  carthage bootstrap --platform iOS --no-use-binaries || true\n}\n\ncarthage_bootstrap\n\nif [ \"$MODE\" = \"ci-componentkit-ios\" ]; then\n  ios_ci ComponentKit.xcodeproj ComponentKit test\nfi\n\nif [ \"$MODE\" = \"ci-componentkit-tvos\" ]; then\n  tvos_ci ComponentKit.xcodeproj ComponentKitAppleTV test\nfi\n\nif [ \"$MODE\" = \"ci-wildeguess-ios\" ]; then\n  ios_ci Examples/WildeGuess/WildeGuess.xcodeproj WildeGuess build\nfi\n\nif [ \"$MODE\" = \"docs\" ]; then\n  HEADERS=`ls ComponentKit/**/*.h ComponentTextKit/**/*.h`\n  rm -rf appledoc\n  appledoc \\\n    --no-create-docset \\\n    --create-html \\\n    --exit-threshold 2 \\\n    --no-repeat-first-par \\\n    --no-merge-categories \\\n    --explicit-crossref \\\n    --warn-missing-output-path \\\n    --warn-missing-company-id \\\n    --warn-undocumented-object \\\n    --warn-undocumented-member \\\n    --warn-empty-description \\\n    --warn-unknown-directive \\\n    --warn-invalid-crossref \\\n    --warn-missing-arg \\\n    --project-name ComponentKit \\\n    --project-company Facebook \\\n    --company-id \"org.componentkit\" \\\n    --output appledoc \\\n    $HEADERS\nfi\n\n# Go back to the initial directory\npopd\n", "num_lines": 94}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end kitchensink test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# CLI, app, and test module temporary locations\n# http://unix.stackexchange.com/a/84980\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\n\n# Load functions for working with local NPM registry (Verdaccio)\nsource local-registry.sh\n\nfunction cleanup {\n  echo 'Cleaning up.'  \n  ps -ef | grep 'react-scripts' | grep -v grep | awk '{print $2}' | xargs kill -9\n  cd \"$root_path\"\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  stopLocalRegistry\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Check for the existence of one or more files.\nfunction exists {\n  for f in $*; do\n    test -e \"$f\"\n  done\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n\n# ******************************************************************************\n# First, publish the monorepo.\n# ******************************************************************************\n\n# Start the local NPM registry\nstartLocalRegistry \"$root_path\"/tasks/verdaccio.yaml\n\n# Publish the monorepo\npublishToLocalRegistry\n\n# ******************************************************************************\n# Now that we have published them, run all tests as if they were released.\n# ******************************************************************************\n\n# Run all tests\ncd test/\nCI=true ../node_modules/.bin/jest -w 2\n\n# Cleanup\ncleanup\n", "num_lines": 84}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# CLI and app temporary locations\n# http://unix.stackexchange.com/a/84980\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\n\n# Load functions for working with local NPM registry (Verdaccio)\nsource local-registry.sh\n\nfunction cleanup {\n  echo 'Cleaning up.'\n  cd \"$root_path\"\n  rm -rf \"$temp_app_path\"\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  stopLocalRegistry\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Check for the existence of one or more files.\nfunction exists {\n  for f in $*; do\n    test -e \"$f\"\n  done\n}\n\n# Check for accidental dependencies in package.json\nfunction checkDependencies {\n  if ! awk '/\"dependencies\": {/{y=1;next}/},/{y=0; next}y' package.json | \\\n  grep -v -q -E '^\\s*\"(@testing-library\\/.+)|web-vitals|(react(-dom|-scripts)?)\"'; then\n   echo \"Dependencies are correct\"\n  else\n   echo \"There are extraneous dependencies in package.json\"\n   exit 1\n  fi\n}\n\n# Check for accidental dependencies in package.json\nfunction checkTypeScriptDependencies {\n  if ! awk '/\"dependencies\": {/{y=1;next}/},/{y=0; next}y' package.json | \\\n  grep -v -q -E '^\\s*\"(@testing-library\\/.+)|web-vitals|(@types\\/.+)|typescript|(react(-dom|-scripts)?)\"'; then\n   echo \"Dependencies are correct\"\n  else\n   echo \"There are extraneous dependencies in package.json\"\n   exit 1\n  fi\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n\n# ******************************************************************************\n# First, publish the monorepo.\n# ******************************************************************************\n\n# Start the local NPM registry\nstartLocalRegistry \"$root_path\"/tasks/verdaccio.yaml\n\n# Publish the monorepo\npublishToLocalRegistry\n\necho \"Create React App Version: \"\nnpx create-react-app --version\n\n# ******************************************************************************\n# Test --scripts-version with a distribution tag\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nnpx create-react-app test-app-dist-tag --scripts-version=@latest\ncd test-app-dist-tag\n\n# Check corresponding scripts version is installed and no TypeScript or yarn is present by default\nexists node_modules/react-scripts\n! exists node_modules/typescript\n! exists src/index.tsx\n! exists yarn.lock\nexists src/index.js\ncheckDependencies\n\n# ******************************************************************************\n# Test --scripts-version with a version number\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nnpx create-react-app test-app-version-number --scripts-version=1.0.17\ncd test-app-version-number\n\n# Check corresponding scripts version is installed.\nexists node_modules/react-scripts\ngrep '\"version\": \"1.0.17\"' node_modules/react-scripts/package.json\ncheckDependencies\n\n# ******************************************************************************\n# Test yarn create\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nyarn create react-app test-use-yarn-create --scripts-version=1.0.17\ncd test-use-yarn-create\n\n# Check corresponding scripts version is installed.\nexists node_modules/react-scripts\nexists yarn.lock\ngrep '\"version\": \"1.0.17\"' node_modules/react-scripts/package.json\ncheckDependencies\n\n# ******************************************************************************\n# Test typescript setup\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nnpx create-react-app test-app-typescript --template typescript\ncd test-app-typescript\n\n# Check corresponding template is installed.\nexists node_modules/react-scripts\nexists node_modules/typescript\nexists src/index.tsx\nexists tsconfig.json\nexists src/react-app-env.d.ts\ncheckTypeScriptDependencies\n\n# Check that the TypeScript template passes smoke tests, build, and normal tests\nnpm start -- --smoke-test\nnpm run build\nCI=true npm test\n\n# Check eject behaves and works\n\n# Eject...\necho yes | npm run eject\n\n# Ensure env file still exists\nexists src/react-app-env.d.ts\n\n# Check that the TypeScript template passes ejected smoke tests, build, and normal tests\nnpm start -- --smoke-test\nnpm run build\nCI=true npm test\n\n# ******************************************************************************\n# Test --scripts-version with a tarball url\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nnpx create-react-app test-app-tarball-url --scripts-version=https://registry.npmjs.org/react-scripts/-/react-scripts-1.0.17.tgz\ncd test-app-tarball-url\n\n# Check corresponding scripts version is installed.\nexists node_modules/react-scripts\ngrep '\"version\": \"1.0.17\"' node_modules/react-scripts/package.json\ncheckDependencies\n\n# ******************************************************************************\n# Test --scripts-version with a custom fork of react-scripts\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nnpx create-react-app test-app-fork --scripts-version=react-scripts-fork\ncd test-app-fork\n\n# Check corresponding scripts version is installed.\nexists node_modules/react-scripts-fork\n\n# ******************************************************************************\n# Test project folder is deleted on failing package installation\n# ******************************************************************************\n\ncd \"$temp_app_path\"\n# we will install a non-existing package to simulate a failed installation.\nnpx create-react-app test-app-should-not-exist --scripts-version=`date +%s` || true\n# confirm that the project files were deleted\ntest ! -e test-app-should-not-exist/package.json\ntest ! -d test-app-should-not-exist/node_modules\n\n# ******************************************************************************\n# Test project folder is not deleted when creating app over existing folder\n# ******************************************************************************\n\ncd \"$temp_app_path\"\nmkdir test-app-should-remain\necho '## Hello' > ./test-app-should-remain/README.md\n# we will install a non-existing package to simulate a failed installation.\nnpx create-react-app test-app-should-remain --scripts-version=`date +%s` || true\n# confirm the file exist\ntest -e test-app-should-remain/README.md\n# confirm only README.md is the only file in the directory\nif [ \"$(ls -1 ./test-app-should-remain | wc -l | tr -d '[:space:]')\" != \"1\" ]; then\n  false\nfi\n\n# ******************************************************************************\n# Test --scripts-version with a scoped fork tgz of react-scripts\n# ******************************************************************************\n\ncd $temp_app_path\ncurl \"https://registry.npmjs.org/@enoah_netzach/react-scripts/-/react-scripts-0.9.0.tgz\" -o enoah-scripts-0.9.0.tgz\nnpx create-react-app test-app-scoped-fork-tgz --scripts-version=$temp_app_path/enoah-scripts-0.9.0.tgz\ncd test-app-scoped-fork-tgz\n\n# Check corresponding scripts version is installed.\nexists node_modules/@enoah_netzach/react-scripts\n\n# ******************************************************************************\n# Test nested folder path as the project name\n# ******************************************************************************\n\n# Testing a path that exists\ncd \"$temp_app_path\"\nmkdir test-app-nested-paths-t1\ncd test-app-nested-paths-t1\nmkdir -p test-app-nested-paths-t1/aa/bb/cc/dd\nnpx create-react-app test-app-nested-paths-t1/aa/bb/cc/dd\ncd test-app-nested-paths-t1/aa/bb/cc/dd\nnpm start -- --smoke-test\n\n# Testing a path that does not exist\ncd \"$temp_app_path\"\nnpx create-react-app test-app-nested-paths-t2/aa/bb/cc/dd\ncd test-app-nested-paths-t2/aa/bb/cc/dd\nnpm start -- --smoke-test\n\n# Testing a path that is half exists\ncd \"$temp_app_path\"\nmkdir -p test-app-nested-paths-t3/aa\nnpx create-react-app test-app-nested-paths-t3/aa/bb/cc/dd\ncd test-app-nested-paths-t3/aa/bb/cc/dd\nnpm start -- --smoke-test\n\n# ******************************************************************************\n# Test when PnP is enabled\n# ******************************************************************************\ncd \"$temp_app_path\"\nyarn create react-app test-app-pnp --use-pnp\ncd test-app-pnp\n! exists node_modules\nexists .pnp.js\n# TODO: start and build tasks error with --use-pnp\n# npm start -- --smoke-test\n# npm run build\n\n# Cleanup\ncleanup\n", "num_lines": 279}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end kitchensink test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# CLI, app, and test module temporary locations\n# http://unix.stackexchange.com/a/84980\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\ntemp_module_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_module_path'`\n\n# Load functions for working with local NPM registry (Verdaccio)\nsource local-registry.sh\n\nfunction cleanup {\n  echo 'Cleaning up.'\n  unset BROWSERSLIST\n  ps -ef | grep 'react-scripts' | grep -v grep | awk '{print $2}' | xargs kill -9\n  cd \"$root_path\"\n  # TODO: fix \"Device or resource busy\" and remove ``|| $CI`\n  rm -rf \"$temp_app_path\" \"$temp_module_path\" || $CI\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  stopLocalRegistry\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Check for the existence of one or more files.\nfunction exists {\n  for f in $*; do\n    test -e \"$f\"\n  done\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n# Set a Windows path for GitBash on Windows\nif [ \"$AGENT_OS\" == 'Windows_NT' ]; then\n  root_path=$(cmd //c cd)\nfi\n\n# ******************************************************************************\n# First, publish the monorepo.\n# ******************************************************************************\n\n# Start the local NPM registry\nstartLocalRegistry \"$root_path\"/tasks/verdaccio.yaml\n\n# Publish the monorepo\npublishToLocalRegistry\n\n# ******************************************************************************\n# Now that we have published them, create a clean app folder and install them.\n# ******************************************************************************\n\n# Install the app in a temporary location\ncd $temp_app_path\nnpx create-react-app test-kitchensink --template=file:\"$root_path\"/packages/react-scripts/fixtures/kitchensink\n\n# Install the test module\ncd \"$temp_module_path\"\nnpm install test-integrity@^2.0.1\n\n# ******************************************************************************\n# Now that we used create-react-app to create an app depending on react-scripts,\n# let's make sure all npm scripts are in the working state.\n# ******************************************************************************\n\n# Enter the app directory\ncd \"$temp_app_path/test-kitchensink\"\n\n# In kitchensink, we want to test all transforms\nexport BROWSERSLIST='ie 9'\n\n# ******************************************************************************\n# Finally, let's check that everything still works after ejecting.\n# ******************************************************************************\n\n# Eject...\necho yes | npm run eject\n\n# Test the build\nREACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  NODE_PATH=src \\\n  PUBLIC_URL=http://www.example.org/spa/ \\\n  npm run build\n\n# Check for expected output\nexists build/*.html\nexists build/static/js/main.*.js\n\n# Unit tests\nREACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  CI=true \\\n  NODE_PATH=src \\\n  NODE_ENV=test \\\n  npm test --no-cache --runInBand --testPathPattern=src\n\n# Test \"development\" environment\ntmp_server_log=`mktemp`\nPORT=3002 \\\n  REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  NODE_PATH=src \\\n  nohup npm start &>$tmp_server_log &\ngrep -q 'You can now view' <(tail -f $tmp_server_log)\nE2E_URL=\"http://localhost:3002\" \\\n  REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  CI=true NODE_PATH=src \\\n  NODE_ENV=development \\\n  BABEL_ENV=test \\\n  node_modules/.bin/jest --no-cache --runInBand --config='jest.integration.config.js'\n\n# Test \"production\" environment\nE2E_FILE=./build/index.html \\\n  CI=true \\\n  NODE_ENV=production \\\n  BABEL_ENV=test \\\n  NODE_PATH=src \\\n  PUBLIC_URL=http://www.example.org/spa/ \\\n  node_modules/.bin/jest --no-cache --runInBand --config='jest.integration.config.js'\n\n# Cleanup\ncleanup\n", "num_lines": 154}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end kitchensink test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# CLI, app, and test module temporary locations\n# http://unix.stackexchange.com/a/84980\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\ntemp_module_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_module_path'`\n\n# Load functions for working with local NPM registry (Verdaccio)\nsource local-registry.sh\n\nfunction cleanup {\n  echo 'Cleaning up.'\n  unset BROWSERSLIST\n  ps -ef | grep 'react-scripts' | grep -v grep | awk '{print $2}' | xargs kill -9\n  cd \"$root_path\"\n  # TODO: fix \"Device or resource busy\" and remove ``|| $CI`\n  rm -rf \"$temp_app_path\" \"$temp_module_path\" || $CI\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  stopLocalRegistry\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Check for the existence of one or more files.\nfunction exists {\n  for f in $*; do\n    test -e \"$f\"\n  done\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n# Set a Windows path for GitBash on Windows\nif [ \"$AGENT_OS\" == 'Windows_NT' ]; then\n  root_path=$(cmd //c cd)\nfi\n\n# ******************************************************************************\n# First, publish the monorepo.\n# ******************************************************************************\n\n# Start the local NPM registry\nstartLocalRegistry \"$root_path\"/tasks/verdaccio.yaml\n\n# Publish the monorepo\npublishToLocalRegistry\n\n# ******************************************************************************\n# Now that we have published them, create a clean app folder and install them.\n# ******************************************************************************\n\n# Install the app in a temporary location\ncd $temp_app_path\nnpx create-react-app test-kitchensink --template=file:\"$root_path\"/packages/react-scripts/fixtures/kitchensink\n\n# Install the test module\ncd \"$temp_module_path\"\nnpm install test-integrity@^2.0.1\n\n# ******************************************************************************\n# Now that we used create-react-app to create an app depending on react-scripts,\n# let's make sure all npm scripts are in the working state.\n# ******************************************************************************\n\n# Enter the app directory\ncd \"$temp_app_path/test-kitchensink\"\n\n# In kitchensink, we want to test all transforms\nexport BROWSERSLIST='ie 9'\n\n# Test the build\nREACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  PUBLIC_URL=http://www.example.org/spa/ \\\n  npm run build\n\n# Check for expected output\nexists build/*.html\nexists build/static/js/main.*.js\n\n# Unit tests\n# https://facebook.github.io/jest/docs/en/troubleshooting.html#tests-are-extremely-slow-on-docker-and-or-continuous-integration-ci-server\nREACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  CI=true \\\n  NODE_ENV=test \\\n  npm test --no-cache --runInBand --testPathPattern=src\n\n# Prepare \"development\" environment\ntmp_server_log=`mktemp`\nPORT=3001 \\\n  REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  NODE_PATH=src \\\n  nohup npm start &>$tmp_server_log &\ngrep -q 'You can now view' <(tail -f $tmp_server_log)\n\n# Test \"development\" environment\nE2E_URL=\"http://localhost:3001\" \\\n  REACT_APP_SHELL_ENV_MESSAGE=fromtheshell \\\n  CI=true NODE_PATH=src \\\n  NODE_ENV=development \\\n  BABEL_ENV=test \\\n  node_modules/.bin/jest --no-cache --runInBand --config='jest.integration.config.js'\n# Test \"production\" environment\nE2E_FILE=./build/index.html \\\n  CI=true \\\n  NODE_PATH=src \\\n  NODE_ENV=production \\\n  BABEL_ENV=test \\\n  PUBLIC_URL=http://www.example.org/spa/ \\\n  node_modules/.bin/jest --no-cache --runInBand --config='jest.integration.config.js'\n\n# Cleanup\ncleanup\n", "num_lines": 147}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\n\nfunction cleanup {\n  echo 'Cleaning up.'\n  cd \"$root_path\"\n  rm -rf $temp_app_path\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n\n# We need to install create-react-app deps to test it\ncd \"$root_path\"/packages/create-react-app\nnpm install\ncd \"$root_path\"\n\n# If the node version is < 10, the script should just give an error.\ncd $temp_app_path\nerr_output=`node \"$root_path\"/packages/create-react-app/index.js test-node-version 2>&1 > /dev/null || echo ''`\n[[ $err_output =~ You\\ are\\ running\\ Node ]] && exit 0 || exit 1\n\n# Cleanup\ncleanup\n", "num_lines": 62}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end test intended to run on CI.\n# You can also run it locally but it's slow.\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# App temporary location\n# http://unix.stackexchange.com/a/84980\ntemp_app_path=`mktemp -d 2>/dev/null || mktemp -d -t 'temp_app_path'`\n\n# Load functions for working with local NPM registry (Verdaccio)\nsource local-registry.sh\n\nfunction cleanup {\n  echo 'Cleaning up.'\n  cd \"$root_path\"\n  # Uncomment when snapshot testing is enabled by default:\n  # rm ./packages/react-scripts/template/src/__snapshots__/App.test.js.snap\n  rm -rf \"$temp_app_path\"\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  stopLocalRegistry\n}\n\n# Error messages are redirected to stderr\nfunction handle_error {\n  echo \"$(basename $0): ERROR! An error was encountered executing line $1.\" 1>&2;\n  cleanup\n  echo 'Exiting with error.' 1>&2;\n  exit 1\n}\n\nfunction handle_exit {\n  cleanup\n  echo 'Exiting without error.' 1>&2;\n  exit\n}\n\n# Check for the existence of one or more files.\nfunction exists {\n  for f in $*; do\n    test -e \"$f\"\n  done\n}\n\n# Exit the script with a helpful error message when any error is encountered\ntrap 'set +x; handle_error $LINENO $BASH_COMMAND' ERR\n\n# Cleanup before exit on any termination signal\ntrap 'set +x; handle_exit' SIGQUIT SIGTERM SIGINT SIGKILL SIGHUP\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n\n# Make sure we don't introduce accidental references to PATENTS.\nEXPECTED='packages/react-error-overlay/fixtures/bundle.mjs\npackages/react-error-overlay/fixtures/bundle.mjs.map\npackages/react-error-overlay/fixtures/bundle_u.mjs\npackages/react-error-overlay/fixtures/bundle_u.mjs.map\ntasks/e2e-simple.sh'\nACTUAL=$(git grep -l PATENTS)\nif [ \"$EXPECTED\" != \"$ACTUAL\" ]; then\n  echo \"PATENTS crept into some new files?\"\n  diff -u <(echo \"$EXPECTED\") <(echo \"$ACTUAL\") || true\n  exit 1\nfi\n\n# Start the local NPM registry\nstartLocalRegistry \"$root_path\"/tasks/verdaccio.yaml\n\nnpm test -w react-error-overlay\nif [ \"$AGENT_OS\" != 'Windows_NT' ]; then\n  # Flow started hanging on Windows build agents\n  npm run flow -w react-error-overlay\nfi\n\nnpm test -w react-dev-utils\n\nnpm test -w babel-plugin-named-asset-import\n\nnpm test -w confusing-browser-globals\n\n# ******************************************************************************\n# First, test the create-react-app development environment.\n# This does not affect our users but makes sure we can develop it.\n# ******************************************************************************\n\n# Test local build command\nnpm run build\n# Check for expected output\nexists build/*.html\nexists build/static/js/*.js\nexists build/static/css/*.css\nexists build/static/media/*.svg\nexists build/favicon.ico\n\n# Run tests with CI flag\nCI=true npm test\n# Uncomment when snapshot testing is enabled by default:\n# exists template/src/__snapshots__/App.test.js.snap\n\n# Test local start command\nnpm start -- --smoke-test\n\n# Publish the monorepo\npublishToLocalRegistry\n\n# ******************************************************************************\n# Install react-scripts prerelease via create-react-app prerelease.\n# ******************************************************************************\n\n# Install the app in a temporary location\ncd $temp_app_path\nnpx create-react-app test-app\n\n# TODO: verify we installed prerelease\n\n# ******************************************************************************\n# Now that we used create-react-app to create an app depending on react-scripts,\n# let's make sure all npm scripts are in the working state.\n# ******************************************************************************\n\nfunction verify_env_url {\n  # Backup package.json because we're going to make it dirty\n  cp package.json package.json.orig\n\n  # Test default behavior\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 0 || exit 1\n\n  # Test relative path build\n  awk -v n=2 -v s=\"  \\\"homepage\\\": \\\".\\\",\" 'NR == n {print s} {print}' package.json > tmp && mv tmp package.json\n\n  npm run build\n  # Disabled until this can be tested\n  # grep -F -R --exclude=*.map \"../../static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"./static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n\n  PUBLIC_URL=\"/anabsolute\" npm run build\n  grep -F -R --exclude=*.map \"/anabsolute/static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n\n  # Test absolute path build\n  sed \"2s/.*/  \\\"homepage\\\": \\\"\\/testingpath\\\",/\" package.json > tmp && mv tmp package.json\n\n  npm run build\n  grep -F -R --exclude=*.map \"/testingpath/static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n\n  PUBLIC_URL=\"https://www.example.net/overridetest\" npm run build\n  grep -F -R --exclude=*.map \"https://www.example.net/overridetest/static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n  grep -F -R --exclude=*.map \"testingpath/static\" build/ -q; test $? -eq 1 || exit 1\n\n  # Test absolute url build\n  sed \"2s/.*/  \\\"homepage\\\": \\\"https:\\/\\/www.example.net\\/testingpath\\\",/\" package.json > tmp && mv tmp package.json\n\n  npm run build\n  grep -F -R --exclude=*.map \"/testingpath/static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n\n  PUBLIC_URL=\"https://www.example.net/overridetest\" npm run build\n  grep -F -R --exclude=*.map \"https://www.example.net/overridetest/static/\" build/ -q; test $? -eq 0 || exit 1\n  grep -F -R --exclude=*.map \"\\\"/static/\" build/ -q; test $? -eq 1 || exit 1\n  grep -F -R --exclude=*.map \"testingpath/static\" build/ -q; test $? -eq 1 || exit 1\n\n  # Restore package.json\n  rm package.json\n  mv package.json.orig package.json\n}\n\nfunction verify_module_scope {\n  # Create stub json file\n  echo \"{}\" >> sample.json\n\n  # Save App.js, we're going to modify it\n  cp src/App.js src/App.js.bak\n\n  # Add an out of scope import\n  echo \"import sampleJson from '../sample'\" | cat - src/App.js > src/App.js.temp && mv src/App.js.temp src/App.js\n\n  # Make sure the build fails\n  npm run build; test $? -eq 1 || exit 1\n  # TODO: check for error message\n\n  rm sample.json\n\n  # Restore App.js\n  rm src/App.js\n  mv src/App.js.bak src/App.js\n}\n\n# Enter the app directory\ncd test-app\n\n# Test the build\nnpm run build\n# Check for expected output\nexists build/*.html\nexists build/static/js/*.js\nexists build/static/css/*.css\nexists build/static/media/*.svg\nexists build/favicon.ico\n\n# Run tests with CI flag\nCI=true npm test\n# Uncomment when snapshot testing is enabled by default:\n# exists src/__snapshots__/App.test.js.snap\n\n# Test the server\nnpm start -- --smoke-test\n\n# Test environment handling\nverify_env_url\n\n# Test reliance on webpack internals\nverify_module_scope\n\n# ******************************************************************************\n# Finally, let's check that everything still works after ejecting.\n# ******************************************************************************\n\n# Eject...\necho yes | npm run eject\n\n# Test ejected files were staged\ntest -n \"$(git diff --staged --name-only)\"\n\n# Test the build\nnpm run build\n# Check for expected output\nexists build/*.html\nexists build/static/js/*.js\nexists build/static/css/*.css\nexists build/static/media/*.svg\nexists build/favicon.ico\n\n# Run tests, overriding the watch option to disable it.\nnpm test --watch=no\n# Uncomment when snapshot testing is enabled by default:\n# exists src/__snapshots__/App.test.js.snap\n\n# Test the server\nnpm start -- --smoke-test\n\n# Test environment handling\nverify_env_url\n\n# Test reliance on webpack internals\nverify_module_scope\n\n# Cleanup\ncleanup\n", "num_lines": 265}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\ncustom_registry_url=http://localhost:4873\noriginal_npm_registry_url=`npm get registry`\noriginal_yarn_registry_url=`yarn config get registry`\ndefault_verdaccio_package=verdaccio@^4.5.1\n\nfunction startLocalRegistry {\n  # Start local registry\n  tmp_registry_log=`mktemp`\n  echo \"Registry output file: $tmp_registry_log\"\n  (cd && nohup npx ${VERDACCIO_PACKAGE:-$default_verdaccio_package} -c $1 &>$tmp_registry_log &)\n  # Wait for Verdaccio to boot\n  grep -q 'http address' <(tail -f $tmp_registry_log)\n\n  # Set registry to local registry\n  npm set registry \"$custom_registry_url\"\n  yarn config set registry \"$custom_registry_url\"\n}\n\nfunction stopLocalRegistry {\n  # Restore the original NPM and Yarn registry URLs and stop Verdaccio\n  npm set registry \"$original_npm_registry_url\"\n  yarn config set registry \"$original_yarn_registry_url\"\n}\n\nfunction publishToLocalRegistry {\n  git clean -df\n  ./tasks/publish.sh prerelease --yes --force-publish=* --no-git-tag-version --no-commit-hooks --no-push --exact --dist-tag=latest\n}\n", "num_lines": 31}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nnode_version=14\ncurrent_git_branch=`git rev-parse --abbrev-ref HEAD`\ngit_branch=${current_git_branch}\ntest_suite=all\ninteractive=false\n\nfunction print_help {\n  echo \"Usage: ${0} [OPTIONS]\"\n  echo \"\"\n  echo \"OPTIONS:\"\n  echo \"  --node-version <version>  the node version to use while testing [${node_version}]\"\n  echo \"  --git-branch <branch>     the git branch to checkout for testing [${current_git_branch}]\"\n  echo \"  --test-suite <suite>      which test suite to use ('all', 'behavior', installs', 'kitchensink', 'kitchensink-eject', 'simple') ['${test_suite}']\"\n  echo \"  --interactive             gain a bash shell after the test run [${interactive}]\"\n  echo \"  --help                    print this message and exit\"\n  echo \"\"\n}\n\ncd $(dirname $0)\n\nwhile [ \"$1\" != \"\" ]; do\n  case $1 in\n    \"--node-version\")\n      shift\n      node_version=$1\n      ;;\n    \"--git-branch\")\n      shift\n      git_branch=$1\n      ;;\n    \"--test-suite\")\n      shift\n      test_suite=$1\n      ;;\n    \"--interactive\")\n      interactive=true\n      ;;\n    \"--help\")\n      print_help\n      exit 0\n      ;;\n  esac\n  shift\ndone\n\ntest_command=\"./tasks/e2e-simple.sh && ./tasks/e2e-kitchensink.sh && ./tasks/e2e-kitchensink-eject.sh && ./tasks/e2e-installs.sh && ./tasks/e2e-behavior.sh\"\ncase ${test_suite} in\n  \"all\")\n    ;;\n  \"simple\")\n    test_command=\"./tasks/e2e-simple.sh\"\n    ;;\n  \"kitchensink\")\n    test_command=\"./tasks/e2e-kitchensink.sh\"\n    ;;\n  \"kitchensink-eject\")\n    test_command=\"./tasks/e2e-kitchensink-eject.sh\"\n    ;;\n  \"installs\")\n    test_command=\"./tasks/e2e-installs.sh\"\n    ;;\n  \"behavior\")\n    test_command=\"./tasks/e2e-behavior.sh\"\n    ;;\n  *)\n    ;;\nesac\n\nread -r -d '' apply_changes <<- CMD\ncd /var/create-react-app\ngit config --global user.name \"Create React App\"\ngit config --global user.email \"cra@email.com\"\ngit stash save -u\ngit stash show -p > patch\ngit diff 4b825dc642cb6eb9a060e54bf8d69288fbee4904 stash^3 >> patch\ngit stash pop\ncd -\nmv /var/create-react-app/patch .\ngit apply patch\nrm patch\ngit add -A\ngit commit -m 'Apply local changes'\nCMD\n\nif [ ${git_branch} != ${current_git_branch} ]; then\n  apply_changes=''\nfi\n\nread -r -d '' command <<- CMD\nnpm install npm@8 -g\nexport PATH=\\$(npm config get prefix -g)/bin:\\$PATH\nset -x\ngit clone /var/create-react-app create-react-app --branch ${git_branch}\ncd create-react-app\n${apply_changes}\nnode --version\nnpm --version\nnpm ci\nset +x\n${test_command}\nresult_code=\\$?\nif [ \\$result_code == 0 ]; then\n  echo -e \"\\n\\e[1;32m\u00e2\u0153\u201d Job passed\\e[0m\"\nelse\n  echo -e \"\\n\\e[1;31m\u00e2\u0153\u02dc Job failed\\e[0m\"\nfi\n$([[ ${interactive} == 'true' ]] && echo 'bash')\nexit \\$result_code\nCMD\n\ndocker run \\\n  --env CI=true \\\n  --env NPM_CONFIG_PREFIX=/home/node/.npm \\\n  --env NPM_CONFIG_QUIET=true \\\n  --tty \\\n  --rm \\\n  --user node \\\n  --volume ${PWD}/..:/var/create-react-app \\\n  --workdir /home/node \\\n  $([[ ${interactive} == 'true' ]] && echo '--interactive') \\\n  node:${node_version} \\\n  bash -c \"${command}\"\n", "num_lines": 129}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This releases an update to the `react-scripts` package.\n# Don't use `npm publish` for it.\n# Read the release instructions:\n# https://github.com/facebook/create-react-app/blob/main/CONTRIBUTING.md#cutting-a-release\n# ******************************************************************************\n\n# Start in tasks/ even if run from root directory\ncd \"$(dirname \"$0\")\"\n\n# Exit the script on any command with non 0 return code\n# We assume that all the commands in the pipeline set their return code\n# properly and that we do not need to validate that the output is correct\nset -e\n\n# Echo every command being executed\nset -x\n\n# Go to root\ncd ..\nroot_path=$PWD\n\nif [ -n \"$(git status --porcelain)\" ]; then\n  echo \"Your git status is not clean. Aborting.\";\n  exit 1;\nfi\n\n# Compile\nnpm run build:prod -w react-error-overlay\n\n# Get 2FA when not CI\notp=\"\"\nif [ -z $CI ]; then\n  echo \"Please enter npm two-factor auth code: \"\n  read otp\nfi\n\n# Go!\nNPM_CONFIG_OTP=\"$otp\" ./node_modules/.bin/lerna publish \"$@\"\n", "num_lines": 46}
{"repo_name": "create-react-app", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/zsh\n# Copyright (c) 2015-present, Facebook, Inc.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# ******************************************************************************\n# This is an end-to-end test intended to be run via screencast.js\n# Dependencies: asciinema, pv, core-utils\n# ******************************************************************************\nset -e\n\nprintf '\\e[32m%s\\e[m' \"\u00ce\u00bb \"\necho \"npx create-react-app my-app\" | pv -qL $[10+(-2 + RANDOM%5)]\nnpx create-react-app my-app\n\nprintf '\\e[32m%s\\e[m' \"\u00ce\u00bb \"\nsleep 1\necho \"cd my-app\" | pv -qL $[10+(-2 + RANDOM%5)]\ncd my-app\n\nprintf '\\e[32m%s\\e[m' \"\u00ce\u00bb \"\nsleep 1\necho \"npm start\" | pv -qL $[10+(-2 + RANDOM%5)]\n\nBROWSER=\"none\" node \"$(dirname $0)/screencast-start.js\" \\\n    --command \"npm start\" \\\n    --pattern=\"Compiled successfully*\" \\\n    --pattern-count 2 \\\n    --error-pattern=\"*already running on port\" \\\n    --timeout 10\n\necho \"\"", "num_lines": 33}
{"repo_name": "docusaurus", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -euo pipefail\n\nCUSTOM_REGISTRY_URL=\"http://localhost:4873\"\nNEW_VERSION=\"$(node -p \"require('./packages/docusaurus/package.json').version\")-NEW\"\nCONTAINER_NAME=\"verdaccio\"\nEXTRA_OPTS=\"\"\n\nusage() { echo \"Usage: $0 [-s] [-t]\" 1>&2; exit 1; }\n\nwhile getopts \":st\" o; do\n  case \"${o}\" in\n    s)\n      EXTRA_OPTS=\"${EXTRA_OPTS} --skip-install\"\n      ;;\n    t)\n      EXTRA_OPTS=\"${EXTRA_OPTS} --typescript\"\n      ;;\n    *)\n      usage\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\n\nif [ ! -z $EXTRA_OPTS ]\nthen\n  echo create-docusaurus extra options = ${EXTRA_OPTS}\nfi\n\n# Run Docker container with private npm registry Verdaccio\ndocker run -d --rm --name \"$CONTAINER_NAME\" -p 4873:4873 -v \"$PWD/admin/verdaccio.yaml\":/verdaccio/conf/config.yaml verdaccio/verdaccio:latest\n\n# Build packages\nyarn build:packages\n\n# Publish the monorepo\nnpx --no-install lerna publish --exact --yes --no-verify-access --no-git-reset --no-git-tag-version --no-push --registry \"$CUSTOM_REGISTRY_URL\" \"$NEW_VERSION\"\n\n# Revert version changes\ngit diff --name-only -- '*.json' | sed 's, ,\\\\&,g' | xargs git checkout --\n\n\n# The website is generated outside the repo to minimize chances of yarn resolving the wrong version\ncd ..\n\n# Build skeleton website with new version\nnpm_config_registry=\"$CUSTOM_REGISTRY_URL\" npx create-docusaurus@\"$NEW_VERSION\" test-website classic $EXTRA_OPTS\n\n# Stop Docker container\nif [[ -z \"${KEEP_CONTAINER:-true}\" ]] && ( $(docker container inspect \"$CONTAINER_NAME\" > /dev/null 2>&1) ); then\n  # Remove Docker container\n  docker container stop $CONTAINER_NAME > /dev/null\nfi\n\necho \"The website with to-be published packages was successfully build to the $(tput setaf 2)test-website$(tput sgr 0) directory.\"\n", "num_lines": 64}
{"repo_name": "errpy", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -euxo pipefail\n\nif ! command -v opam &> /dev/null\nthen\n    echo \"opam is not installed, which is a dependency for building targets in ocaml.\"\n    exit\nfi\n\nif [ -z \"$OPAM_SWITCH_PREFIX\" ]; then\n    echo \"OPAM_SWITCH_PREFIX is undefined. First execute \\`eval (\\$opam env)\\` and then try running $0 again.\"\n    exit\nfi\n\n# Link 'shim/third-party/ocaml/standard_library'.\nif [ ! -L shim/third-party/ocaml/standard_library ]; then\n  (cd shim/third-party/ocaml && ln -s \"$(ocamlopt.opt -config | grep standard_library: | awk '{ print $2 }' )\" standard_library)\nelse\n    echo \"Link 'shim/third-party/ocaml/standard_library' exists. To overwrite it, first remove it and run $0 again\"\nfi\n\n# Link 'third-party/ocaml/opam'.\nif [ ! -L shim/third-party/ocaml/opam ]; then\n  (cd shim/third-party/ocaml && ln -s \"$OPAM_SWITCH_PREFIX\" opam)\nelse\n    echo \"Link 'shim/third-party/ocaml/opam' exists. To overwrite it, first remove it and run $0 again\"\nfi\n", "num_lines": 36}
{"repo_name": "facebook-android-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script builds the API documentation from source-level comments.\n\n# Utility functions.\nfunction die() {\n  echo \"\"\n  echo \"FATAL: $*\" >&2\n  exit 1\n}\n\n# Make sure javadoc is installed.\nhash javadoc >/dev/null || die 'Javadoc is not installed!'\n\n# The directory containing this script\n# We need to go there and use pwd so these are all absolute paths\npushd \"$(dirname $BASH_SOURCE[0])\" > /dev/null\nFB_SDK_SCRIPT=$(pwd)\npopd >/dev/null\n\n# The root directory where the Facebook SDK for android is cloned\nFB_SDK_ROOT=$(dirname \"$FB_SDK_SCRIPT\")\n\n# Path to java source file under each kit folder\nPATH_TO_SRC='src/main/java'\n\n# mkdir -p $FB_SDK_ROOT/out\nmkdir -p $FB_SDK_ROOT/out/docs\n\n# The tmp directory where source files can processed\nDOCS_TMP_DIR=out/docs/tmp\n\n# Source folders for Facebook\nFB_SRC_FOLDERS=(\n  'facebook'\n  'facebook-core'\n  'facebook-common'\n  'facebook-login'\n  'facebook-share'\n  'facebook-messenger'\n  'facebook-applinks'\n  'facebook-gamingservices'\n)\n\n  echo \"\"\n  echo \"Preparing source files for docs generation\"\n  echo \"\"\n\n# 'Flattens' Facebook sources into a single folder.\nFB_SRC_DEST=$FB_SDK_ROOT/$DOCS_TMP_DIR/facebook/$PATH_TO_SRC\nmkdir -p $FB_SRC_DEST\n\nfor (( i = 0; i < ${#FB_SRC_FOLDERS[@]}; i++ ))\ndo\n  FB_SRC=${FB_SRC_FOLDERS[$i]}\n\n  FB_SRC_FOLDER=$FB_SDK_ROOT/$FB_SRC/$PATH_TO_SRC\n\n  cp -rn $FB_SRC_FOLDER/ $FB_SRC_DEST\ndone\n\n# Source folders of each kit\nKIT_SRC_FOLDERS=(\n  $DOCS_TMP_DIR/facebook\n  'accountkit/accountkitsdk'\n  'ads/AdsApi'\n)\n\n# Output doc folders for each kit\nKIT_DOC_FOLDERS=(\n  'facebook'\n  'accountkit'\n  'audiencenetwork'\n)\n\nfor (( i = 0; i < ${#KIT_SRC_FOLDERS[@]}; i++ ))\ndo\n  KIT_SRC=${KIT_SRC_FOLDERS[$i]}\n  KIT_DOC=${KIT_DOC_FOLDERS[$i]}\n\n  SRC_FOLDER=$FB_SDK_ROOT/$KIT_SRC/$PATH_TO_SRC\n  DOC_FOLDER=$FB_SDK_ROOT/out/docs/$KIT_DOC\n  LOG_FILE=$FB_SDK_ROOT/out/docs/$KIT_DOC.log\n\n  # Find all the facebook packages except internal ones\n  # Then use javadoc to generate docs for those packages\n  grep --recursive --no-filename -Po '(?<=package )com\\.facebook.*?(?=;)' $SRC_FOLDER | sort | uniq | grep -v internal \\\n    | xargs javadoc -quiet -d $DOC_FOLDER -sourcepath $SRC_FOLDER &> $LOG_FILE\n\n  cd $FB_SDK_ROOT/out/docs\n  zip --quiet --recurse-paths $DOC_FOLDER.zip $KIT_DOC\n\n  echo \"\"\n  echo \"Generated docs in $DOC_FOLDER\"\n  echo \"... zip as $DOC_FOLDER.zip\"\n  echo \"... see log file at $LOG_FILE\"\n  echo \"\"\ndone\n\n# Clean up tmp directory\nrm -rf ${FB_SDK_ROOT:?}/$DOCS_TMP_DIR\n", "num_lines": 108}
{"repo_name": "facebook-android-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script builds the API documentation from source-level comments.\n\npushd \"$(dirname ${BASH_SOURCE[0]})\" > /dev/null || exit 1\nFB_SDK_SCRIPT=$(pwd)\npopd >/dev/null || exit 1\nFB_SDK_ROOT=$(dirname \"$FB_SDK_SCRIPT\")\n\nDOC_OUT_FOLDER=\"$FB_SDK_ROOT/out/docs\"\nmkdir -p \"$DOC_OUT_FOLDER\"\n\ncd \"$FB_SDK_ROOT\" || exit 1\n./gradlew facebook:dokkaJavadoc\ncd \"$FB_SDK_ROOT/facebook/build/dokka/\" || exit 1\ncp -r javadoc \"$DOC_OUT_FOLDER/facebook\"\ncd \"$DOC_OUT_FOLDER\" || exit 1\nzip --quiet --recurse-paths facebook.zip facebook\n\necho \"\"\necho \"Generated docs in $DOC_OUT_FOLDER/facebook\"\necho \"... zipped as $DOC_OUT_FOLDER/facebook.zip\"\necho \"\"\n", "num_lines": 30}
{"repo_name": "facebook-android-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n# This script runs a few shell commands for additional code formatting cleanup\n\n# cd up one level if run from the scripts dir\nCURRENT_DIR_NAME=\"${PWD##*/}\"\nif [ \"$CURRENT_DIR_NAME\" = \"scripts\" ]; then\n  cd ..\nfi\n\n# Convert functions that return a single expression to single-expression functions\n# https://kotlinlang.org/docs/functions.html#single-expression-functions\nfind . -name '*.kt' -print0 | xargs -0 perl -0777 -pi -e 's/(fun.*) {\\n\\s*return ([\\w\\.]+)\\n\\s*}/\\1 = \\2/g'\n\n# Ensure a blank line above the package statement\nfind . -name '*.kt' -print0 | xargs -0 perl -0777 -pi -e 's/( \\*\\/)\\n(package)/\\1\\n\\n\\2/g'\n", "num_lines": 24}
{"repo_name": "facebook-android-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# this script configures your Android simulator for unit tests\n# Note: On Mac OS X, an easy way to generate a MACHINE_UNIQUE_USER_TAG is with the following:\n#   system_profiler SPHardwareDataType | grep -i \"Serial Number (system):\" | awk '{print $4}'\n\ncd $(dirname $0)/..\nFB_SDK_ROOT=$(pwd)\nFB_SDK_TESTS=$FB_SDK_ROOT/facebook/src/androidTest\n\nif [ \"$#\" -lt 3 ]; then\n      echo \"Usage: $0 APP_ID APP_SECRET CLIENT_TOKEN [MACHINE_UNIQUE_USER_KEY]\"\n      echo \"  APP_ID                   your unit-testing Facebook application's App ID\"\n      echo \"  APP_SECRET               your unit-testing Facebook application's App Secret\"\n      echo \"  CLIENT_TOKEN             your unit-testing Facebook application's client token\"\n      echo \"  MACHINE_UNIQUE_USER_TAG  optional text used to ensure this machine will use its own set of test users rather than sharing\"\n      die 'Arguments do not conform to usage'\nfi\n\nfunction write_config_json {\n    CONFIG_JSON_FILE=\"$FB_SDK_TESTS\"/assets/config.json\n\n    mkdir -p \"$FB_SDK_TESTS\"/assets\n\n    # use heredoc syntax to output the json\n    cat > \"$CONFIG_JSON_FILE\" \\\n<<DELIMIT\n{\"applicationId\":\"$1\",\"applicationSecret\":\"$2\",\"clientToken\":\"$3\",\"machineUniqueUserTag\":\"$4\"}\nDELIMIT\n# end heredoc\n\n    echo \"wrote unit test config file at $CONFIG_JSON_FILE\"\n}\n\nwrite_config_json $1 $2 $3\n", "num_lines": 42}
{"repo_name": "facebook-android-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script runs a few shell commands for additional code formatting cleanup\n\nread -r -d '' LICENSE_STRING << EOM\n/*\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n * All rights reserved.\n *\n * This source code is licensed under the license found in the\n * LICENSE file in the root directory of this source tree.\n */\nEOM\n\nread -r -d '' XML_LICENSE_STRING << EOM\n<!--\n    Copyright (c) Meta Platforms, Inc. and affiliates.\n    All rights reserved.\n\n    This source code is licensed under the license found in the\n    LICENSE file in the root directory of this source tree.\n-->\nEOM\n\n# cd up one level if run from the scripts dir\nCURRENT_DIR_NAME=\"${PWD##*/}\"\nif [ \"$CURRENT_DIR_NAME\" = \"scripts\" ]; then\n  cd ..\nfi\n\n# Ensure every java and kotlin file has the correct license header (also adds missing header)\ngit ls-files '*.java' '*.kt' | xargs perl -0777 -pi -e \"s|.*?package|$LICENSE_STRING\\n\\npackage|s\"\n\n# Fix copyright statement for kts files\ngit ls-files '*.kts' | xargs perl -0777 -pi -e \"s|.*?(import\\|plugins)|$LICENSE_STRING\\n\\n\\1|s\"\n\n# Fix copyright statement for xml files\ngit ls-files '*.xml' | xargs perl -0777 -pi -e \"s|<!--.+?Copyright.+?-->\\n+|$XML_LICENSE_STRING\\n\\n|s\"\n", "num_lines": 45}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Note: Use of this script requires Perl\n\n# @licenselint-loose-mode\n\n#\n# step 1 - confirm we have an app id and app secret to work with\n#\n\nif [ -z \"$APPID\" ]\nthen\n  echo '$APPID must be exported and set to the application id for the sample before running this script'\n  exit 1\nfi\n\nif [ -z \"$APPSECRET\" ]\nthen\n  echo '$APPSECRET must be exported set to the app secret for the sample before running this script'\n  exit 1\nfi\n\n#\n# step 2 - stage images and capture their URIs in variables\n#\n\necho curling...\n\nROCK_IMAGE_URI=` \\\n  curl -s -k -X POST https://graph.facebook.com/$APPID/staging_resources -F access_token=\"$APPID|$APPSECRET\" -F 'file=@RPSSample/left-rock-128.png;type=image/png' \\\n  | perl -ne '/\"uri\":\"(.*)\"}/ && print $1' `\n\nPAPER_IMAGE_URI=` \\\n  curl -s -k -X POST https://graph.facebook.com/$APPID/staging_resources -F access_token=\"$APPID|$APPSECRET\" -F 'file=@RPSSample/left-paper-128.png;type=image/png' \\\n  | perl -ne '/\"uri\":\"(.*)\"}/ && print $1' `\n\nSCISSORS_IMAGE_URI=` \\\n  curl -s -k -X POST https://graph.facebook.com/$APPID/staging_resources -F access_token=\"$APPID|$APPSECRET\" -F 'file=@RPSSample/left-scissors-128.png;type=image/png' \\\n  | perl -ne '/\"uri\":\"(.*)\"}/ && print $1' `\n\necho \"created staged resources...\"\necho \"  rock=$ROCK_IMAGE_URI\"\necho \"  paper=$PAPER_IMAGE_URI\"\necho \"  scissors=$SCISSORS_IMAGE_URI\"\n\n# step 3 - create facebook host applink page for the app:\n# For mobile only app, facebook provide applink host service to generate a page: https://developers.facebook.com/docs/graph-api/reference/v2.0/app/app_link_hosts\n\necho \"creating facebook host applink page for mobile-only app:\"\n\nFB_APPLINK_HOST_ID=` \\\ncurl https://graph.facebook.com/app/app_link_hosts -F access_token=\"$APPID|$APPSECRET\" -F pretty=true -F name=\"RPSSample\" \\\n-F ios='[\n    {\n      \"url\" : \"rps-sample-applink-example://\",\n      \"app_store_id\" : 794163692,\n      \"app_name\" : \"RPS Sample\",\n    },\n  ]' \\\n-F android=' [\n    {\n      \"package\" : \"com.facebook.samples.rps\",\n      \"app_name\" : \"RPS Sample\",\n    },\n  ]' \\\n-F web=' {\n    \"should_fallback\" : false,\n  }' \\\n| perl -ne '/\"id\":\\s*\"(.*)\"/ && print $1'`\n\nFB_APPLINK_HOST_URL=` \\\ncurl -X GET https://graph.facebook.com/v2.0/$FB_APPLINK_HOST_ID?access_token=\"$APPID|$APPSECRET\" \\\n| perl -ne '/\"canonical_url\":\\s*\"(.*)\"/ && print $1' `\n\necho \"  applink host url id: $FB_APPLINK_HOST_ID\"\necho \"  applink host url: $FB_APPLINK_HOST_URL\"\n\n#\n# step 4 - create objects and capture their IDs in variables\n#\n\n# rock\nROCK_OBJID=` \\\n  curl -s -X POST -F \"object={\\\"title\\\":\\\"Rock\\\",\\\"description\\\":\\\"Breaks scissors, alas is covered by paper.\\\",\\\"image\\\":\\\"$ROCK_IMAGE_URI\\\",\\\"url\\\":\\\"$FB_APPLINK_HOST_URL?gesture=rock\\\"}\" \"https://graph.facebook.com/$APPID/objects/fb_sample_rps:gesture?access_token=$APPID|$APPSECRET\" \\\n  | perl -ne '/\"id\":\"(.*)\"}/ && print $1' `\n\n# paper\nPAPER_OBJID=` \\\n  curl -s -X POST -F \"object={\\\"title\\\":\\\"Paper\\\",\\\"description\\\":\\\"Covers rock, sadly scissors cut it.\\\",\\\"image\\\":\\\"$PAPER_IMAGE_URI\\\",\\\"url\\\":\\\"$FB_APPLINK_HOST_URL?gesture=paper\\\"}\" \"https://graph.facebook.com/$APPID/objects/fb_sample_rps:gesture?access_token=$APPID|$APPSECRET\" \\\n  | perl -ne '/\"id\":\"(.*)\"}/ && print $1' `\n\n# scissors\nSCISSORS_OBJID=` \\\n  curl -s -X POST -F \"object={\\\"title\\\":\\\"Scissors\\\",\\\"description\\\":\\\"Cuts paper, broken by rock -- bother.\\\",\\\"image\\\":\\\"$SCISSORS_IMAGE_URI\\\",\\\"url\\\":\\\"$FB_APPLINK_HOST_URL?gesture=scissors\\\"}\" \"https://graph.facebook.com/$APPID/objects/fb_sample_rps:gesture?access_token=$APPID|$APPSECRET\" \\\n  | perl -ne '/\"id\":\"(.*)\"}/ && print $1' `\n\n\n#\n# step 5 - echo progress\n#\n\necho \"created application objects...\"\necho \"  rock=$ROCK_OBJID\"\necho \"  paper=$PAPER_OBJID\"\necho \"  scissors=$SCISSORS_OBJID\"\n\n#\n# step 6 - write .m file for common objects\n#\n\nMFILE=RPSSample/RPSCommonObjects.m\n\ncat > $MFILE << EOF\n// Copyright (c) Meta Platforms, Inc. and affiliates. All rights reserved.\n//\n// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n// copy, modify, and distribute this software in source code or binary form for use\n// in connection with the web services and APIs provided by Facebook.\n//\n// As with any software that integrates with the Facebook platform, your use of\n// this software is subject to the Facebook Platform Policy\n// [http://developers.facebook.com/policy/]. This copyright notice shall be\n// included in all copies or substantial portions of the software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nNSString *builtInOpenGraphObjects[3] = {\n                                        @\"$ROCK_OBJID\",      // rock\n                                        @\"$PAPER_OBJID\",      // paper\n                                        @\"$SCISSORS_OBJID\"};     // scissors\nEOF\n\necho \"created $MFILE ...\"\necho done.\n", "num_lines": 145}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# If $PROJECT_DIR is set, this is running from within Xcode from a project subfolder\nif [ -n \"$PROJECT_DIR\" ]; then\n  cd .. # cd one level up to find the .swiftlint.yml file\n  PROJECT_DIR_NAME=${PROJECT_DIR##*/} # ex FBSDKShareKit\nfi\n\nGIT_ROOT=$(git rev-parse --show-toplevel 2>/dev/null)\n\n# Get list of changed files\n# shellcheck disable=SC2207\nIFS=$'\\n' CHANGED_FILES=($(git -P diff --name-only --diff-filter=MA main...HEAD && git -P diff --name-only --diff-filter=MA HEAD))\n\nSWIFTLINT_PATH=\"internal/tools/swiftlint\"\nSWIFTFORMAT_PATH=\"internal/tools/swiftformat\"\n\n# If we don't have access to the internal directory, use whatever version is installed\nif [ -d \"$SWIFTFORMAT_PATH\" ]; then\n    SWIFTLINT_PATH=$(which swiftlint)\n    SWIFTFORMAT_PATH=$(which swiftformat)\nfi\n\n# Lint changes from the current revision and uncommitted changes\nif [ ${#CHANGED_FILES[@]} -eq 0 ]; then\n    echo \"No files changed.\"\n    exit\nfi\n\n# Run the script from the comand line and pass in \"--debug\" as an argument for debugging\n# i.e. scripts/build_phase_swiftlint.sh --debug\nif [ \"$1\" = \"--debug\" ]; then\n  printf \"\\\\nCHANGED_FILES:\\\\n\"\n  printf \"%s\\n\" \"${CHANGED_FILES[@]}\"\nfi\n\n\n# SwiftLint doesn't dedup file path args\n# shellcheck disable=SC2207\nIFS=$'\\n' UNIQUE_SWIFT_FILES=($(printf '%s\\n' \"${CHANGED_FILES[@]}\" | sort -u | grep \".*\\.swift$\"))\nif [ ${#UNIQUE_SWIFT_FILES[@]} -eq 0 ]; then\n    echo \"No Swift files to lint.\"\n    exit\nfi\n\nif [ \"$1\" = \"--debug\" ]; then\n  printf \"\\\\nUNIQUE_SWIFT_FILES:\\\\n\"\n  printf \"%s\\n\" \"${UNIQUE_SWIFT_FILES[@]}\"\nfi\n\n# Fix for issue in which a file was added in a previous commit but is removed in the working copy\nLINTABLE_FILES=()\nfor file in \"${UNIQUE_SWIFT_FILES[@]}\"; do\n    if [[ -e $file ]]; then\n      LINTABLE_FILES+=(\"$file\")\n    elif [ \"$1\" = \"--debug\" ]; then\n      echo \"FILE DOES NOT EXIST: $file\"\n    fi\ndone\n\nif [ \"$1\" = \"--debug\" ]; then\n  printf \"\\\\nLINTABLE_FILES:\\\\n\"\n  printf \"%s\\n\" \"${LINTABLE_FILES[@]}\"\nfi\n\n\n# Run SwiftFormat\nif [ -n \"$SWIFTFORMAT_PATH\" ]; then\n  if [ -n \"$PROJECT_DIR_NAME\" ]; then # if within Xcode filter by kit name\n    $SWIFTFORMAT_PATH --lint \"${LINTABLE_FILES[@]}\" 2>&1 | grep \"$PROJECT_DIR_NAME\" || true\n  else\n    $SWIFTFORMAT_PATH --lint \"${LINTABLE_FILES[@]}\"\n  fi\nelse\n  echo \"warning: SwiftFormat not installed. Install with 'brew install swiftformat' or from https://github.com/nicklockwood/SwiftFormat\"\nfi\n\n# Run SwiftLint\nif [ -n \"$SWIFTLINT_PATH\" ]; then\n  if [ -n \"$PROJECT_DIR_NAME\" ]; then # if within Xcode filter by kit name\n    $SWIFTLINT_PATH lint \"${LINTABLE_FILES[@]}\" | grep \"$PROJECT_DIR_NAME\" || true\n  else\n    $SWIFTLINT_PATH lint \"${LINTABLE_FILES[@]}\"\n  fi\nelse\n  echo \"warning: SwiftLint not installed, Install with 'brew install swiftlint' or from https://github.com/realm/SwiftLint\"\nfi\n", "num_lines": 93}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n# This script runs a few shell commands for additional code formatting cleanup\n\n# cd up one level if run from the scripts dir\nCURRENT_DIR_NAME=\"${PWD##*/}\"\nif [ \"$CURRENT_DIR_NAME\" = \"scripts\" ]; then\n  cd ..\nfi\n\n# Remove UIColor prefix. (Note: Dosen't work for .cgColor ones ex: \"layer.shadowColor = UIColor.black.cgColor\")\ngit ls-files '*.swift' -z | xargs -0 perl -pi -e 's/(\\.(?:background|text)Color) = UIColor(\\.\\w+)/\\1 = \\2/'\n", "num_lines": 20}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# carthage.sh\n# Xcode 12 workaround.\n# See: https://github.com/Carthage/Carthage/blob/master/Documentation/Xcode12Workaround.md\n#\n# Usage example: ./carthage.sh build --platform iOS\n\nset -euo pipefail\n\nxcconfig=$(mktemp /tmp/static.xcconfig.XXXXXX)\ntrap 'rm -f \"$xcconfig\"' INT TERM HUP EXIT\n\n# For Xcode 12 make sure EXCLUDED_ARCHS is set to arm architectures otherwise\n# the build will fail on lipo due to duplicate architectures.\n\nCURRENT_XCODE_VERSION=$(xcodebuild -version | grep \"Build version\" | cut -d' ' -f3)\n\n# Disabling check since Xcode will be expanding vars\n# shellcheck disable=SC2016\n{\n    echo \"EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_1200__BUILD_$CURRENT_XCODE_VERSION = arm64 arm64e armv7 armv7s armv6 armv8 i386\"\n    echo 'EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_1200 = $(EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_simulator__NATIVE_ARCH_64_BIT_x86_64__XCODE_1200__BUILD_$(XCODE_PRODUCT_BUILD_VERSION))'\n    echo 'EXCLUDED_ARCHS = $(inherited) $(EXCLUDED_ARCHS__EFFECTIVE_PLATFORM_SUFFIX_$(EFFECTIVE_PLATFORM_SUFFIX)__NATIVE_ARCH_64_BIT_$(NATIVE_ARCH_64_BIT)__XCODE_$(XCODE_VERSION_MAJOR))'\n} >> \"$xcconfig\"\n\nexport XCODE_XCCONFIG_FILE=\"$xcconfig\"\n", "num_lines": 33}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e # immediately exit if any command has a non-zero exit status\nset -u # flag undefined variables as errors\nset -o pipefail # propogate errors in pipeline to be the result of the pipeline\n# set -x # echo commands run (commented out for now since its noisy)\n\nCURRENT_VERSION=$(grep -Eo 'FBSDK_VERSION_STRING @\".*\"' FBSDKCoreKit/FBSDKCoreKit/include/FBSDKCoreKitVersions.h | awk -F'\"' '{print $2}')\n\npush_specs_and_update() {\n  for spec in \"$@\"; do\n    echo \"Checking version $CURRENT_VERSION for: $spec\"\n    # The \"|| [[ $? == 1 ]]\" prevents a non-zero exit from grep to cause the script to exit (due to \"set -e\")\n    FOUND=$(pod trunk info \"$spec\" | grep \"$CURRENT_VERSION\" || [ $? = 1 ])\n    if [ -z \"$FOUND\" ]; then\n      echo \"Running: pod trunk push --allow-warnings --synchronous $spec.podspec\"\n      pod trunk push --allow-warnings --synchronous \"$spec\".podspec || { echo \"Failed to push $spec\"; exit 1; }\n    fi\n  done\n}\n\n# 1. FBSDKCoreKit_Basics\npush_specs_and_update FBSDKCoreKit_Basics\n\n# 2. FBAEMKit (dependency: FBSDKCoreKit_Basics)\npush_specs_and_update FBAEMKit\n\n# 3. FBSDKCoreKit (dependencies: FBSDKCoreKit_Basics, FBAEMKit)\npush_specs_and_update FBSDKCoreKit\n\n# 4. FBSDKLoginKit, FBSDKShareKit (dependencies: FBSDKCoreKit_Basics, FBSDKCoreKit)\npush_specs_and_update FBSDKLoginKit FBSDKShareKit\n\n# 5. FBSDKGamingServicesKit (dependencies: FBSDKCoreKit_Basics, FBSDKCoreKit)\npush_specs_and_update FBSDKGamingServicesKit\n", "num_lines": 41}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2039\n# shellcheck disable=SC2005\n\nset -euo pipefail\n\n# --------------\n# Imports\n# --------------\n\nif [ -f \"$PWD/internal/scripts/internal_globals.sh\" ]; then\n  # shellcheck source=../internal/scripts/internal_globals.sh\n  . \"$PWD/internal/scripts/internal_globals.sh\"\nfi\n\nif [ -f \"$PWD/internal/scripts/intern_api.sh\" ]; then\n  # shellcheck source=../internal/scripts/intern_api.sh\n  . \"$PWD/internal/scripts/intern_api.sh\"\nfi\n\n# --------------\n# Functions\n# --------------\n\n# Main\nmain() {\n  if [ -z \"${SDK_SCRIPTS_DIR:-}\" ]; then\n\n    # Dirty trick to avoid having to install core utils on CircleCI\n    realpath() {\n      [[ $1 = /* ]] && echo \"$1\" || echo \"$PWD/${1#./}\"\n    }\n\n    # Set global variables\n\n    SDK_SCRIPTS_DIR=$(realpath \"$(dirname \"${BASH_SOURCE[0]}\")\")\n    SDK_DIR=\"$(dirname \"$SDK_SCRIPTS_DIR\")\"\n\n    CORE_KIT_BASICS=\"FBSDKCoreKit_Basics\"\n    AEM_KIT=\"FBAEMKit\"\n    CORE_KIT=\"FBSDKCoreKit\"\n    LOGIN_KIT=\"FBSDKLoginKit\"\n    SHARE_KIT=\"FBSDKShareKit\"\n    GAMING_SERVICES_KIT=\"FBSDKGamingServicesKit\"\n\n    SDK_BASE_KITS=(\n      \"$CORE_KIT_BASICS\"\n      \"$AEM_KIT\"\n      \"$CORE_KIT\"\n      \"$LOGIN_KIT\"\n      \"$SHARE_KIT\"\n    )\n\n    SDK_KITS=(\n      \"${SDK_BASE_KITS[@]}\"\n      \"$GAMING_SERVICES_KIT\"\n    )\n\n    DOCUMENTATION_KITS=(\n      \"$CORE_KIT\"\n      \"$LOGIN_KIT\"\n      \"$SHARE_KIT\"\n      \"$GAMING_SERVICES_KIT\"\n    )\n\n    SDK_VERSION_FILES=(\n      \"Configurations/Version.xcconfig\"\n      \"FBSDKCoreKit/FBSDKCoreKit/include/FBSDKCoreKitVersions.h\"\n      \"FBSDKCoreKit_Basics/FBSDKCoreKit_Basics/FBSDKCrashHandler.m\"\n      \"FBSDKCoreKit/FBSDKCoreKitTests/AppLinkNavigationTests.swift\"\n      \"FBAEMKit/FBAEMKit/AEMNetworker.swift\"\n    )\n\n    SDK_GRAPH_API_VERSION_FILES=(\n      \"FBSDKCoreKit/FBSDKCoreKit/include/FBSDKCoreKitVersions.h\"\n      \"FBSDKCoreKit/FBSDKCoreKitTests/GraphRequestTests.swift\"\n      \"FBAEMKit/FBAEMKit/_AEMNetworker.swift\"\n    )\n\n    SDK_MAIN_VERSION_FILE=\"FBSDKCoreKit/FBSDKCoreKit/include/FBSDKCoreKitVersions.h\"\n\n    SDK_POD_SPECS=(\"${SDK_KITS[@]}\")\n    SDK_POD_SPECS=(\"${SDK_POD_SPECS[@]/%/.podspec}\")\n\n    SDK_CURRENT_VERSION=$(grep -Eo 'FBSDK_VERSION_STRING @\".*\"' \"$SDK_DIR/$SDK_MAIN_VERSION_FILE\" | awk -F'\"' '{print $2}')\n    SDK_CURRENT_GRAPH_API_VERSION=$(grep -Eo 'FBSDK_DEFAULT_GRAPH_API_VERSION @\".*\"' \"$SDK_DIR/$SDK_MAIN_VERSION_FILE\" | awk -F'\"' '{print $2}')\n\n    SDK_GIT_REMOTE=\"https://github.com/facebook/facebook-ios-sdk\"\n\n    if [ -f \"$PWD/internal/scripts/internal_globals.sh\" ]; then SDK_INTERNAL=1; else SDK_INTERNAL=0; fi\n  fi\n\n  local command_type=${1:-}\n  if [ -n \"$command_type\" ]; then shift; fi\n\n  case \"$command_type\" in\n  \"build\") build_sdk \"$@\" ;;\n  \"bump-version\") bump_version \"$@\" ;;\n  \"bump-api-version\") bump_api_version \"$@\" ;;\n  \"bump-changelog\") bump_changelog \"$@\" ;;\n  \"check-release-status\") check_release_status \"$@\" ;;\n  \"is-valid-semver\") is_valid_semver \"$@\" ;;\n  \"does-version-exist\") does_version_exist \"$@\" ;;\n  \"release\") release_sdk \"$@\" ;;\n  \"setup\") setup_sdk \"$@\" ;;\n  \"tag-current-version\") tag_current_version \"$@\" ;;\n  \"verify-xcode-integration\") verify_xcode_integration \"$@\" ;;\n  \"--help\" | \"help\") echo \"Check main() for supported commands\" ;;\n  esac\n}\n\n# Setup SDK\nsetup_sdk() {\n  local sdk_test_app_id=${1:-$SDK_TEST_FB_APP_ID}\n  local sdk_test_app_secret=${2:-$SDK_TEST_FB_APP_SECRET}\n  local sdk_test_client_token=${3:-$SDK_TEST_FB_CLIENT_TOKEN}\n  local sdk_machine_unique_user_key=${4:-}\n\n  {\n    echo \"IOS_SDK_TEST_APP_ID = $sdk_test_app_id\"\n    echo \"IOS_SDK_TEST_APP_SECRET = $sdk_test_app_secret\"\n    echo \"IOS_SDK_TEST_CLIENT_TOKEN = $sdk_test_client_token\"\n    echo \"IOS_SDK_MACHINE_UNIQUE_USER_KEY = $sdk_machine_unique_user_key\"\n  } >>\"$SDK_DIR\"/Configurations/TestAppIdAndSecret.xcconfig\n}\n\ngrep_for_old_version() {\n  local old_version=${1:-}\n\n  RED='\\033[1;31m'\n  RESET='\\033[0m'\n\n  FILES_WITH_OLD_VERSION=$(grep -rF \"$old_version\" -- * | grep -Ev '(CHANGELOG.md|Package.swift|\\bbuild/|\\bdocs|\\.podspec)')\n  if [ -n \"$FILES_WITH_OLD_VERSION\" ]; then\n    echo \"${RED}ERROR: Grep found the old $old_version version in ${FILES_WITH_OLD_VERSION}${RESET}\" 1>&2;\n    exit 1\n  fi\n}\n\n# Bump Version\nbump_version() {\n  local new_version=${1:-}\n\n  if [ \"$new_version\" == \"$SDK_CURRENT_VERSION\" ]; then\n    echo \"This version is the same as the current version\"\n    false\n    return\n  fi\n\n  if ! is_valid_semver \"$new_version\"; then\n    echo \"This version isn't a valid semantic versioning\"\n    false\n    return\n  fi\n\n  echo \"Changing from: $SDK_CURRENT_VERSION to: $new_version\"\n\n  local version_change_files=(\n    \"${SDK_VERSION_FILES[@]}\"\n  )\n\n  # Replace the previous version to the new version in relative files\n  for file_path in \"${version_change_files[@]}\"; do\n    local full_file_path=\"$SDK_DIR/$file_path\"\n\n    if [ ! -f \"$full_file_path\" ]; then\n      echo \"*** NOTE: unable to find $full_file_path.\"\n      continue\n    fi\n\n    local temp_file=\"$full_file_path.tmp\"\n    sed -e \"s/$SDK_CURRENT_VERSION/$new_version/g\" \"$full_file_path\" >\"$temp_file\"\n    if diff \"$full_file_path\" \"$temp_file\" >/dev/null; then\n      echo \"*** ERROR: unable to update $full_file_path\"\n      rm \"$temp_file\"\n      continue\n    fi\n\n    mv \"$temp_file\" \"$full_file_path\"\n  done\n\n  bump_changelog \"$new_version\"\n\n  grep_for_old_version \"$SDK_CURRENT_VERSION\"\n}\n\n# Bump Version\nbump_api_version() {\n  local new_version=${1:-}\n\n  if [ \"$new_version\" == \"$SDK_CURRENT_GRAPH_API_VERSION\" ]; then\n    echo \"This version is the same as the current version\"\n    false\n    return\n  fi\n\n  echo \"Changing from: $SDK_CURRENT_GRAPH_API_VERSION to: $new_version\"\n\n  # Replace the previous version to the new version in relative files\n  for file_path in \"${SDK_GRAPH_API_VERSION_FILES[@]}\"; do\n    local full_file_path=\"$SDK_DIR/$file_path\"\n\n    if [ ! -f \"$full_file_path\" ]; then\n      echo \"*** NOTE: unable to find $full_file_path.\"\n      continue\n    fi\n\n    local temp_file=\"$full_file_path.tmp\"\n    sed -e \"s/$SDK_CURRENT_GRAPH_API_VERSION/$new_version/g\" \"$full_file_path\" >\"$temp_file\"\n    if diff \"$full_file_path\" \"$temp_file\" >/dev/null; then\n      echo \"*** ERROR: unable to update $full_file_path\"\n      rm \"$temp_file\"\n      continue\n    fi\n\n    mv \"$temp_file\" \"$full_file_path\"\n  done\n\n  grep_for_old_version \"$SDK_CURRENT_GRAPH_API_VERSION\"\n}\n\nbump_changelog() {\n  local new_version=${1:-}\n\n  # Edit Changelog\n  local updated_changelog=\"\"\n\n  while IFS= read -r line; do\n    local updated_line\n\n    case \"$line\" in\n    \"[Full Changelog](\"*\"$SDK_CURRENT_VERSION...HEAD)\")\n      local current_date\n      current_date=$(date +%Y-%m-%d)\n\n      updated_line=\"\\n\"\"${line/$SDK_CURRENT_VERSION/$new_version}\"\"\\n\\n\"\n      updated_line=$updated_line\"## $new_version\\n\\n\"\n      updated_line=$updated_line\"[$current_date]\"\n      updated_line=$updated_line\"($SDK_GIT_REMOTE/releases/tag/v$new_version) |\\n\"\n      updated_line=$updated_line\"[Full Changelog]($SDK_GIT_REMOTE/compare/v$SDK_CURRENT_VERSION...v$new_version)\"\n      ;;\n    \"# Changelog\") updated_line=$line ;;\n    *) updated_line=\"\\n\"$line ;;\n    esac\n\n    updated_changelog=$updated_changelog$updated_line\n  done <\"CHANGELOG.md\"\n\n  echo \"$updated_changelog\" >CHANGELOG.md\n}\n\n# Tag push current version\ntag_current_version() {\n  if ! is_valid_semver \"$SDK_CURRENT_VERSION\"; then\n    exit 1\n  fi\n\n  if does_version_exist \"$SDK_CURRENT_VERSION\"; then\n    echo \"Version $SDK_CURRENT_VERSION already exists\"\n    false\n    return\n  fi\n\n  git tag -a \"v$SDK_CURRENT_VERSION\" -m \"Version $SDK_CURRENT_VERSION\"\n\n  if [ \"${1:-}\" == \"--push\" ]; then\n    git push origin \"v$SDK_CURRENT_VERSION\"\n  fi\n}\n\nbuild_sdk() {\n  build_xcode_workspace() {\n    xcodebuild build \\\n      -workspace \"${1:-}\" \\\n      -sdk \"${2:-}\" \\\n      -scheme \"${3:-}\" \\\n      -configuration Debug | xcpretty\n  }\n\n  local build_type=${1:-}\n  if [ -n \"$build_type\" ]; then shift; fi\n\n  case \"$build_type\" in\n  \"xcode\") build_xcode_workspace \"$@\" ;;\n  *) echo \"Unsupported Build: $build_type\" ;;\n  esac\n}\n\nrelease_sdk() {\n  release_docs() {\n    for kit in \"${DOCUMENTATION_KITS[@]}\"; do\n      rm -rf \"$kit/build\" || true\n\n      ruby \"$SDK_SCRIPTS_DIR\"/genDocs.rb \"$kit\"\n\n      # Zip the result so it can be uploaded easily\n      pushd docs/ || continue\n      zip -r \"$kit\".zip \"$kit\"\n      if [[ $SDK_INTERNAL == 1 ]] && [ \"${1:-}\" == \"--publish\" ]; then\n        api_update_reference_doc \"$kit\"\n      fi\n      popd || continue\n    done\n  }\n\n  local release_type=${1:-}\n  if [ -n \"$release_type\" ]; then shift; fi\n\n  case \"$release_type\" in\n  \"docs\" | \"documentation\") release_docs \"$@\" ;;\n  *) echo \"Unsupported Release: $release_type\" ;;\n  esac\n}\n\n# Check Release Status\ncheck_release_status() {\n  local version_to_check=${1:-}\n\n  if [ -z \"$version_to_check\" ]; then\n    version_to_check=$SDK_CURRENT_VERSION\n  fi\n\n  local release_success=0\n\n  if ! is_valid_semver \"$version_to_check\"; then\n    echo \"$version_to_check isn't a valid semantic versioning\"\n    ((release_success += 1))\n  fi\n\n  if ! does_version_exist \"$version_to_check\"; then\n    echo \"$version_to_check isn't tagged in GitHub\"\n    ((release_success += 1))\n  fi\n\n  local pod_info\n\n  for spec in \"${SDK_POD_SPECS[@]}\"; do\n    if [ ! -f \"$spec\" ]; then\n      echo \"*** ERROR: unable to release $spec\"\n      continue\n    fi\n\n    pod_info=$(pod trunk info \"${spec/.podspec/}\")\n\n    if [[ $pod_info != *\"$version_to_check\"* ]]; then\n      echo \"$spec hasn't been released yet\"\n      ((release_success += 1))\n    fi\n  done\n\n  case $release_success in\n  0) return ;;\n  *) false ;;\n  esac\n}\n\n# Proper Semantic Version\nis_valid_semver() {\n  if ! [[ ${1:-} =~ ^([0-9]{1}|[1-9][0-9]+)\\.([0-9]{1}|[1-9][0-9]+)\\.([0-9]{1}|[1-9][0-9]+)($|[-+][0-9A-Za-z+.-]+$) ]]; then\n    false\n    return\n  fi\n}\n\n# Check Version Tag Exists\ndoes_version_exist() {\n  local version_to_check=${1:-}\n\n  if [ \"$version_to_check\" == \"\" ]; then\n    version_to_check=$SDK_CURRENT_VERSION\n  fi\n\n  if [ ! -d \"$SDK_DIR\"/.git ]; then\n    echo \"Not a Git Repository\"\n    return\n  fi\n\n  if git rev-parse \"v$version_to_check\" >/dev/null 2>&1; then\n    return\n  fi\n\n  if git rev-parse \"sdk-version-$version_to_check\" >/dev/null 2>&1; then\n    return\n  fi\n\n  false\n}\n\n# Builds the test app locally to ensure all frameworks still compile\nverify_xcode_integration() {\n  echo \"Verifying the TextXcodeIntegration App builds\"\n  xcodebuild clean build \\\n    -quiet \\\n    -sdk iphonesimulator \\\n    -workspace testing/TestXcodeIntegration/TestXcodeIntegration.xcworkspace/ \\\n    -scheme TestXcodeIntegration\n}\n\n# --------------\n# Main Script\n# --------------\n\nmain \"$@\"\n", "num_lines": 410}
{"repo_name": "facebook-ios-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2039\n# shellcheck source=./run.sh\n\n# --------------\n# Functions\n# --------------\n\n# Main\nmain() {\n  test_main_setup\n  test_run_routing\n  test_is_valid_semver\n  test_does_version_exist\n  test_check_release_status\n}\n\n# Test Success\ntest_success() {\n  local green='\\033[0;32m'\n  local none='\\033[0m'\n  echo \"${green}* Passed:${none} $*\"\n}\n\n# Test Failure\ntest_failure() {\n  local red='\\033[0;31m'\n  local none='\\033[0m'\n  echo \"${red}* Failed:${none} $*\"\n}\n\nlog_test_begin() {\n  echo \"Testing ${FUNCNAME[1]}\"\n}\n\nlog_test_results() {\n  # $1: Number of Test Failures\n  local test_failures=$1\n  local func_name=${FUNCNAME[1]}\n\n  case $test_failures in\n  0) test_success \"$func_name tests\" ;;\n  *) test_failure \"$test_failures $func_name tests\" ;;\n  esac\n}\n\n# Test Shared Setup\ntest_main_setup() {\n\n  # Arrange\n  local test_failures=$((0))\n\n  local test_sdk_kits=(\n    \"FBSDKCoreKit\"\n    \"FBSDKLoginKit\"\n    \"FBSDKShareKit\"\n    \"FBSDKMarketingKit\"\n  )\n\n  local test_pod_specs=(\n    \"FBSDKCoreKit.podspec\"\n    \"FBSDKLoginKit.podspec\"\n    \"FBSDKShareKit.podspec\"\n    \"FBSDKMarketingKit.podspec\"\n    \"FacebookSDK.podspec\"\n  )\n\n  local test_lint_pod_specs=(\n    \"FBSDKCoreKit.podspec\"\n    \"FBSDKLoginKit.podspec\"\n    \"FBSDKShareKit.podspec\"\n  )\n\n  local test_version_change_files=(\n    \"Configurations/Version.xcconfig\"\n    \"FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h\"\n  )\n\n  local test_graph_api_version_change_files=(\n    \"FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h\"\n    \"FBSDKCoreKit/FBSDKCoreKitTests/FBSDKGraphRequestTests.m\"\n  )\n\n  local test_main_version_file=\"FBSDKCoreKit/FBSDKCoreKit/FBSDKCoreKit.h\"\n\n  local test_current_version\n  test_current_version=$(grep -Eo 'FBSDK_VERSION_STRING @\".*\"' \"$PWD/$test_main_version_file\" | awk -F'\"' '{print $2}')\n\n  local test_sdk_current_graph_api_version\n  test_sdk_current_graph_api_version=$(grep -Eo 'FBSDK_DEFAULT_GRAPH_API_VERSION @\".*\"' \"$PWD/$test_main_version_file\" | awk -F'\"' '{print $2}')\n\n  if [ ! -f \"$PWD/scripts/run.sh\" ]; then\n    test_failure \"You're not in the correct working directory. Please change to the scripts/ parent directory\"\n  fi\n\n  # Act\n  log_test_begin\n\n  . \"$PWD/scripts/run.sh\"\n\n  # Assert\n  if [ -z \"$SDK_SCRIPTS_DIR\" ]; then\n    test_failure \"SDK_SCRIPTS_DIR\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_SCRIPTS_DIR\" != \"$SDK_DIR\"/scripts ]; then\n    test_failure \"SDK_SCRIPTS_DIR not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"${SDK_KITS[*]}\" != \"${test_sdk_kits[*]}\" ]; then\n    test_failure \"SDK_KITS not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"${SDK_POD_SPECS[*]}\" != \"${test_pod_specs[*]}\" ]; then\n    test_failure \"SDK_POD_SPECS not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"${SDK_LINT_POD_SPECS[*]}\" != \"${test_lint_pod_specs[*]}\" ]; then\n    test_failure \"SDK_LINT_POD_SPECS not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"${SDK_VERSION_FILES[*]}\" != \"${test_version_change_files[*]}\" ]; then\n    test_failure \"SDK_VERSION_FILES not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"${SDK_GRAPH_API_VERSION_FILES[*]}\" != \"${test_graph_api_version_change_files[*]}\" ]; then\n    test_failure \"SDK_GRAPH_API_VERSION_FILES not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_MAIN_VERSION_FILE\" != \"$test_main_version_file\" ]; then\n    test_failure \"SDK_MAIN_VERSION_FILE not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_FRAMEWORK_NAME\" != \"FacebookSDK\" ]; then\n    test_failure \"SDK_FRAMEWORK_NAME not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_CURRENT_VERSION\" != \"$test_current_version\" ]; then\n    test_failure \"SDK_CURRENT_VERSION not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_CURRENT_GRAPH_API_VERSION\" != \"$test_sdk_current_graph_api_version\" ]; then\n    test_failure \"SDK_CURRENT_GRAPH_API_VERSION not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ \"$SDK_GIT_REMOTE\" != \"https://github.com/facebook/facebook-ios-sdk\" ]; then\n    test_failure \"SDK_GIT_REMOTE not correct\"\n    ((test_failures += 1))\n  fi\n\n  if [ -f \"$PWD/internal/scripts/internal_globals.sh\" ] && [[ $SDK_INTERNAL == 0 ]]; then\n    test_failure \"SDK_INTERNAL not correct\"\n    ((test_failures += 1))\n  elif ! [ -f \"$PWD/internal/scripts/internal_globals.sh\" ] && [[ $SDK_INTERNAL == 1 ]]; then\n    test_failure \"SDK_INTERNAL not correct\"\n    ((test_failures += 1))\n  fi\n\n  log_test_results $test_failures\n}\n\ntest_is_valid_semver() {\n\n  # Arrange\n  local test_failures=$((0))\n  local func_name=${FUNCNAME[0]}\n\n  local proper_versions=(\n    \"0.0.0\"\n    \"1.0.0\"\n    \"0.1.0\"\n    \"0.0.1\"\n    \"0.1.1\"\n    \"10.1.0\"\n    \"100.1.0\"\n    \"10.10.10\"\n    \"1.9.0\"\n    \"1.10.0\"\n    \"1.11.0\"\n    \"1.0.0-alpha\"\n    \"1.0.0-alpha.1\"\n    \"1.0.0-0.3.7\"\n    \"1.0.0-x.7.z.92\"\n    \"1.0.0-alpha+001\"\n    \"1.0.0+alpha-001\"\n    \"1.0.0+20130313144700\"\n    \"1.0.0-beta+exp.sha.5114f85\"\n    \"1.0.0-alpha\"\n    \"1.0.0-alpha.1\"\n    \"1.0.0-alpha.beta\"\n    \"1.0.0-beta\"\n    \"1.0.0-beta.2\"\n    \"1.0.0-beta.11\"\n    \"1.0.0-rc.1\"\n  )\n\n  # Act\n  log_test_begin\n\n  for version in \"${proper_versions[@]}\"; do\n    # Assert\n    if ! sh \"$PWD\"/scripts/run.sh is-valid-semver \"$version\"; then\n      test_failure \"$version is valid, but returns false\"\n      ((test_failures += 1))\n    fi\n  done\n\n  # Arrange\n  local improper_versions=(\n    \"1.0.\"\n    \"0.1\"\n    \"10.1.0.1\"\n    \"a.b.c\"\n    \"1.0.0-\"\n    \"01.0.0\"\n    \"00.0.0\"\n    \"1.01.0\"\n    \"0.00.0\"\n    \"1.0.00\"\n    \"0.0.01\"\n  )\n\n  # Act\n  for version in \"${improper_versions[@]}\"; do\n    # Assert\n    if sh \"$PWD\"/scripts/run.sh is-valid-semver \"$version\"; then\n      test_failure \"$version is invalid, but returns true\"\n    fi\n  done\n\n  log_test_results $test_failures\n}\n\n# Test Build SDK\ntest_run_routing() {\n\n  # Arrange\n  local test_failures=$((0))\n  local func_name=${FUNCNAME[0]}\n\n  local inputs=(\n    \"build unsupported\"\n    \"lint unsupported\"\n    \"release unsupported\"\n    \"help\"\n    \"--help\"\n  )\n\n  local expected=(\n    \"Unsupported Build: unsupported\"\n    \"Unsupported Lint: unsupported\"\n    \"Unsupported Release: unsupported\"\n    \"Check main() for supported commands\"\n    \"Check main() for supported commands\"\n  )\n\n  # Act\n  log_test_begin\n\n  for i in \"${!inputs[@]}\"; do\n    local input_string=\"${inputs[$i]}\"\n    IFS=\" \" read -r -a input_params <<<\"$input_string\"\n\n    local actual\n    actual=$(sh \"$PWD\"/scripts/run.sh \"${input_params[@]}\")\n\n    # Assert\n    if [ \"$actual\" != \"${expected[$i]}\" ]; then\n      test_failure \"expected: ${expected[$i]} but got: $actual\"\n      ((test_failures += 1))\n    fi\n  done\n\n  log_test_results $test_failures\n}\n\ntest_does_version_exist() {\n\n  # Arrange\n  local test_failures=$((0))\n  local func_name=${FUNCNAME[0]}\n\n  # Act\n  log_test_begin\n\n  # Assert\n  if [ ! -d \"$SDK_DIR\"/.git ]; then\n    echo \"Not a Git Repository\"\n    return\n  fi\n\n  if ! sh \"$PWD\"/scripts/run.sh does-version-exist; then\n    test_failure \"Current version is valid, but returns false\"\n    ((test_failures += 1))\n  fi\n\n  if ! sh \"$PWD\"/scripts/run.sh does-version-exist 4.40.0; then\n    test_failure \"4.40.0 is valid, but returns false\"\n    ((test_failures += 1))\n  fi\n\n  if sh \"$PWD\"/scripts/run.sh does-version-exist 0.0.0; then\n    test_failure \"0.0.0 is invalid, but returns true\"\n    ((test_failures += 1))\n  fi\n\n  log_test_results $test_failures\n}\n\ntest_check_release_status() {\n\n  # Arrange\n  local test_failures=$((0))\n  local func_name=${FUNCNAME[0]}\n\n  # Act\n  log_test_begin\n\n  # Assert\n  if ! sh \"$PWD\"/scripts/run.sh check-release-status 4.38.0; then\n    test_failure \"Version 4.38.0 is valid, but returns false\"\n    ((test_failures += 1))\n  fi\n\n  log_test_results $test_failures\n}\n\n# --------------\n# Main Script\n# --------------\n\nmain \"$@\"\n", "num_lines": 350}
{"repo_name": "facebook-java-business-sdk", "repo_creator": "facebook", "programming_language": "Shell", "code": "main() {\n  echo \"start config\"\n  set -e\n  case $1 in\n    \"config_maven\") config_maven \"$@\" ;;\n  esac\n}\n\n\nconfig_maven(){\n  if [[ -z \"${OSSRH_USERNAME}\" || -z \"${OSSRH_PASSWORD}\" ]]; then\n    die \"ERROR: Variables OSSRH_USERNAME or OSSRH_PASSWORD not defined\"\n    exit 201\n  fi\n\n  if [[ -z \"${GPG_KEYNAME}\" || -z \"${GPG_PASSPHRASE}\" ]]; then\n    die \"ERROR: Variables GPG_KEYNAME or GPG_PASSPHRASE not defined\"\n    exit 201\n  fi\n\n  cat <<EOF> ./.github/workflows/settings.xml\n<settings>\n  <profiles>\n    <profile>\n      <id>ossrh</id>\n      <activation>\n        <activeByDefault>true</activeByDefault>\n      </activation>\n      <properties>\n        <gpg.executable>gpg</gpg.executable>\n        <gpg.keyname>${GPG_KEYNAME}</gpg.keyname>\n        <gpg.passphrase>${GPG_PASSPHRASE}</gpg.passphrase>\n      </properties>\n    </profile>\n  </profiles>\n  <servers>\n    <server>\n      <id>ossrh</id>\n      <username>${OSSRH_USERNAME}</username>\n      <password>${OSSRH_PASSWORD}</password>\n    </server>\n  </servers>\n</settings>\nEOF\n}\n\ndie() {\n  echo \"\"\n  echo \"FATAL: $*\" >&2\n  exit 1\n}\n\nmain \"$@\"\n", "num_lines": 54}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n# shellcheck disable=SC2039\n\nTARGET_OS=NONE\nTARGET_VERSION=NONE\nSELECTED_VERSION=-1\n\ncopyright()\n{\ncat <<EOT\nCopyright (c) 2014-present, Facebook, Inc. All rights reserved.\n\nEOT\n}\n\nhelp()\n{\ncopyright\ncat <<EOT\nThis script adjusts external references to Unity 3D for each of the Facebook SDK for Unity projects.\n\nUsage:\n./configure.sh\nor\n./configure.sh [Unity version]\nUnity version: Exactly full definition as it appears. Ex: 2017.4.40f1, 2018.4.36f1, 2021.1.17f1\n\nExamples:\n./configure.sh                     <- Interactive\n./configure.sh 2021.1.17f1         <- Use 2021.1.17f1 version\n./configure.sh 2018.4.36f1         <- Use 2018.4.36f1 version\n\nEOT\n}\n\nos_not_supported()\n{\ncopyright\ncat <<EOT\nAt this time this script does not support the operating system it is running on.\nYou will need to set the references to Unity by hand.\nWe are working to support this system, sorry for the inconvenience.\n\nEOT\n}\n\n# Cheking working dir\nif [ ! -f Facebook.sln ]; then\n    echo \"Please, execute configure.sh script from root project directory\"\n    exit 1\nfi\n\nunameOut=\"$(uname -s)\"\ncase \"${unameOut}\" in\n    Linux*)\n        os_not_supported\n        exit 1\n    ;;\n    Darwin*)\n        TARGET_OS=MAC\n    ;;\n    CYGWIN*)\n        os_not_supported\n        exit 1\n    ;;\n    MINGW*)\n        os_not_supported\n        exit 1\n    ;;\n    *)\n        os_not_supported\n        exit 1\nesac\n\nif [[ -z \"$1\" ]]\n    then\n        declare -a unity_versions\n        # Interactive process try to find versions\n        help\n        echo \"Interactive mode, the following versions of unity have been found on your system.\"\n\n        # Old version\n        if [ -d \"/Applications/Unity/Unity.app\" ]; then\n            # We assume 2017 version\n            unity_versions+=(\"2017.x.x\")\n        fi\n\n        # New versions Unity Hub\n        files=($(ls /Applications/Unity/Hub/Editor | tr '\\n' '\\0' | xargs -0 -n 1 basename))\n        for file in \"${files[@]}\"; do\n            if [[ $file == *\"2017\"* || $file == *\"2018\"* || $file == *\"2019\"* || $file == *\"2020\"* || $file == *\"2021\"* ]]; then\n                unity_versions+=(\"$file\")\n            fi\n        done\n\n        while [[ $SELECTED_VERSION == -1 ]]\n        do\n            option=1\n            for version in \"${unity_versions[@]}\"; do\n                echo \"$option- $version\"\n                ((option = option + 1))\n            done\n            read -r -p \"Select unity version (Ctrl+C to cancel): \" SELECTED_VERSION\n            if ! [[ $SELECTED_VERSION =~ ^[0-9]+$ ]] ; then\n                echo \"Wrong input\"\n                SELECTED_VERSION=-1\n            fi\n            if [[ \"$SELECTED_VERSION\" -ge \"$option\" ]] ; then\n                echo \"Wrong option\"\n                SELECTED_VERSION=-1\n            fi\n        done\n\n        ((SELECTED_VERSION = SELECTED_VERSION - 1))\n        echo \"You have selected ${unity_versions[SELECTED_VERSION]} version\"\n        IFS='.' read -ra INPUT_VERSION <<< \"${unity_versions[SELECTED_VERSION]}\"\n        TARGET_VERSION=${INPUT_VERSION[0]}\n        FULL_VERSION=${unity_versions[SELECTED_VERSION]}\n    else\n        # No interactive process\n        IFS='.' read -ra INPUT_VERSION <<< \"$1\"\n        TARGET_VERSION=${INPUT_VERSION[0]}\n        FULL_VERSION=$1\n        case \"$TARGET_VERSION\" in\n            '2017'|'2018'|'2019'|'2020'|'2021')\n                echo \"Full version name $FULL_VERSION selected.\"\n                echo \"Family version $TARGET_VERSION selected.\"\n            ;;\n            *)\n                echo \"!Incorrect family version $TARGET_VERSION or not supported.\"\n                help\n                exit 1\n            ;;\n        esac\nfi\n\n\nif [ $TARGET_OS = \"NONE\" ];\nthen\n    printf \"!Target OS not selected.\\n\"\n    help\n    exit 1\nfi\n\nif [[ $TARGET_VERSION = \"NONE\" ]];\nthen\n    printf \"!Unity family version not selected.\\n\"\n    help\n    exit 1\nfi\n\nTEMP_FILE=$(mktemp)\nTEMP_FILE2=$(mktemp)\n\nprintf \"\\n\"\n\n#define full paths for unity version\ncase \"$TARGET_VERSION\" in\n    2017)\n        UNITY_MANAGED_DIR=\"/Applications/Unity/Unity.app/Contents/Managed/\"\n        UNITY_UI_DIR=\"/Applications/Unity/Unity.app/Contents/UnityExtensions/Unity/GUISystem/\"\n        UNITY_ENGINE_DIR=\"/Applications/Unity/Unity.app/Contents/Managed/\"\n        UNITY_EXTENSIONS_DIR=\"/Applications/Unity/Unity.app/Contents/UnityExtensions/Unity/\"\n        UNITY_NETWORKING_DIR=\"NONE\"\n    ;;\n    2018)\n        UNITY_MANAGED_DIR=\"/Applications/Unity/hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/\"\n        UNITY_UI_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/UnityExtensions/Unity/GUISystem/\"\n        UNITY_ENGINE_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/UnityEngine/\"\n        UNITY_EXTENSIONS_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/UnityExtensions/Unity/\"\n        UNITY_NETWORKING_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/UnityExtensions/Unity/Networking/\"\n    ;;\n    2019)\n        #fix find template version\n        PRJ_TEMPLATE=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/\"\n        TEMPLATE_VERSION=$(ls \"$PRJ_TEMPLATE\" | tr '\\n' '\\0' | xargs -0 -n 1 basename | grep universal)\n\n\n        UNITY_MANAGED_DIR=\"/Applications/Unity/hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/\"\n        UNITY_UI_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/$TEMPLATE_VERSION/ScriptAssemblies/\"\n        UNITY_ENGINE_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/UnityEngine/\"\n        UNITY_EXTENSIONS_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/UnityExtensions/Unity/\"\n        UNITY_NETWORKING_DIR=\"NONE\"\n    ;;\n    2020)\n        #fix find template version\n        PRJ_TEMPLATE=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/\"\n        TEMPLATE_VERSION=$(ls \"$PRJ_TEMPLATE\" | tr '\\n' '\\0' | xargs -0 -n 1 basename | grep universal)\n\n        UNITY_MANAGED_DIR=\"/Applications/Unity/hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/\"\n        UNITY_UI_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/$TEMPLATE_VERSION/ScriptAssemblies/\"\n        UNITY_ENGINE_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/UnityEngine/\"\n        UNITY_EXTENSIONS_DIR=\"NONE\"\n        UNITY_NETWORKING_DIR=\"NONE\"\n    ;;\n    2021)\n        #fix find template version\n        PRJ_TEMPLATE=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/\"\n        TEMPLATE_VERSION=$(ls \"$PRJ_TEMPLATE\" | tr '\\n' '\\0' | xargs -0 -n 1 basename | grep universal)\n\n        UNITY_MANAGED_DIR=\"/Applications/Unity/hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/\"\n        UNITY_UI_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Resources/PackageManager/ProjectTemplates/libcache/$TEMPLATE_VERSION/ScriptAssemblies/\"\n        UNITY_ENGINE_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/Managed/UnityEngine/\"\n        UNITY_EXTENSIONS_DIR=\"NONE\"\n        UNITY_NETWORKING_DIR=\"/Applications/Unity/Hub/Editor/$FULL_VERSION/Unity.app/Contents/NetStandard/\"\n    ;;\n    *)\n        printf \"!Unknown version.\\n\"\n        exit 1\nesac\n\n# Set unity version for projects\nsed -n \"/\\<PropertyGroup Condition=\\\"\\'\\$(UNITY_VERSION)\\' == \\'$TARGET_VERSION\\'\\\"\\>/,/<\\/PropertyGroup>/p\" UnityReferences.xml | grep -v PropertyGroup > \"$TEMP_FILE\"\n\n# Set full paths for unity version\nsed \"s/\\<UNITY_MANAGED_DIR\\>.*\\<\\/UNITY_MANAGED_DIR\\>/\\<UNITY_MANAGED_DIR\\>${UNITY_MANAGED_DIR//\\//\\\\/}<\\/UNITY_MANAGED_DIR\\>/g\" \"$TEMP_FILE\" > \"$TEMP_FILE2\"\nsed \"s/\\<UNITY_UI_DIR\\>.*\\<\\/UNITY_UI_DIR\\>/\\<UNITY_UI_DIR\\>${UNITY_UI_DIR//\\//\\\\/}<\\/UNITY_UI_DIR\\>/g\" \"$TEMP_FILE2\" > \"$TEMP_FILE\"\nsed \"s/\\<UNITY_ENGINE_DIR\\>.*\\<\\/UNITY_ENGINE_DIR\\>/\\<UNITY_ENGINE_DIR\\>${UNITY_ENGINE_DIR//\\//\\\\/}<\\/UNITY_ENGINE_DIR\\>/g\" \"$TEMP_FILE\" > \"$TEMP_FILE2\"\nsed \"s/\\<UNITY_EXTENSIONS_DIR\\>.*\\<\\/UNITY_EXTENSIONS_DIR\\>/\\<UNITY_EXTENSIONS_DIR\\>${UNITY_EXTENSIONS_DIR//\\//\\\\/}<\\/UNITY_EXTENSIONS_DIR\\>/g\" \"$TEMP_FILE2\" > \"$TEMP_FILE\"\nsed \"s/\\<UNITY_NETWORKING_DIR\\>.*\\<\\/UNITY_NETWORKING_DIR\\>/\\<UNITY_NETWORKING_DIR\\>${UNITY_NETWORKING_DIR//\\//\\\\/}<\\/UNITY_NETWORKING_DIR\\>/g\" \"$TEMP_FILE\" > \"$TEMP_FILE2\"\n\n# Temp fix because the final result must to be in $TEMP_FILE\ncat \"$TEMP_FILE2\" > \"$TEMP_FILE\"\n\ncat \"$TEMP_FILE\"\n\n# Checking paths\nprintf \"\\n\"\ndirectories=(\"UNITY_MANAGED_DIR\" \"UNITY_UI_DIR\" \"UNITY_ENGINE_DIR\" \"UNITY_EXTENSIONS_DIR\" \"UNITY_NETWORKING_DIR\")\nfor TAG in \"${directories[@]}\"\ndo\n    echo $TAG\n    DIRECTORY_ARRAY=($(awk \"/\\<$TAG\\>/, /\\<\\/$TAG\\>/\" \"$TEMP_FILE\" | sed -e \"s/\\<$TAG\\>\\(.*\\)\\<\\/$TAG\\>/\\1/\" | xargs))\n    DIRECTORY=\"${DIRECTORY_ARRAY[0]}\"\n    if [ \"$DIRECTORY\" != 'NONE' ]; then\n        if [ ! -d \"$DIRECTORY\" ]; then\n            echo \"Path $DIRECTORY not found.\"\n            exit 1\n        else\n            echo \"Check $DIRECTORY Ok!\"\n        fi\n    fi\ndone\n\nline_add_from=$(grep -n '<PropertyGroup Condition=\"'\\''$(UNITY_VERSION)'\\'' == '\\'''\"$TARGET_VERSION\"''\\''\">' UnityReferences.xml | awk '{print $1}' FS=\":\")\nline_add_to_array=($(grep -n '<\\/PropertyGroup>'  UnityReferences.xml | awk '{print $1}' FS=\":\"))\n\n#find next close\nfor close_tag_position in \"${line_add_to_array[@]}\"; do\n    if [[ \"$close_tag_position\" -ge \"$line_add_from\" ]] ; then\n        line_add_to=$close_tag_position\n        break\n    fi\ndone\n\nline_add_from=$((line_add_from + 1))\nline_add_to=$((line_add_to - 1))\n\nif [ \"$line_add_to\" -ge \"$line_add_from\" ];\nthen\n    sed \"$line_add_from,$line_add_to d\" UnityReferences.xml > \"$TEMP_FILE2\"\n    mv \"$TEMP_FILE2\" UnityReferences.xml\nfi\n\nawk -v line_add_from=$line_add_from 'FNR==line_add_from{system(\"cat '\"$TEMP_FILE\"'\")} 1' UnityReferences.xml > \"$TEMP_FILE2\"\nawk '{ gsub(/\\xef\\xbb\\xbf/,\"\"); print }' \"$TEMP_FILE2\" > \"$TEMP_FILE\"\nmv \"$TEMP_FILE\" UnityReferences.xml\necho \" -> UnityReferences.xml Updated!\"\n\n# Set version\nsed \"s/\\<UNITY_VERSION\\>.*\\<\\/UNITY_VERSION\\>/\\<UNITY_VERSION\\>$TARGET_VERSION<\\/UNITY_VERSION\\>/g\" UnityReferences.xml > \"$TEMP_FILE\"\nmv \"$TEMP_FILE\" UnityReferences.xml\n\n# Only for Unity 2021: remove old System includes\nif [[ $TARGET_VERSION = \"2021\" ]];\nthen\n    sed -i '' 's/<Reference Include=\"System.Xml.Linq\" \\/>//g' \"UnitySDK/Assembly-CSharp.csproj\"\n    sed -i '' 's/<Reference Include=\"System.Runtime.Serialization\" \\/>//g' \"UnitySDK/Assembly-CSharp.csproj\"\n    sed -i '' 's/<Reference Include=\"System.Core\" \\/>//g' \"UnitySDK/Assembly-CSharp.csproj\"\n    sed -i '' 's/<Reference Include=\"System.XML\" \\/>//g' \"UnitySDK/Assembly-CSharp.csproj\"\n    sed -i '' 's/<Reference Include=\"System\" \\/>//g' \"UnitySDK/Assembly-CSharp.csproj\"\nfi\n\n# Fix projects files\nprintf \"\\n\"\nprojects=(\"Facebook.Unity\" \"Facebook.Unity.Settings\" \"Facebook.Unity.Android\" \"Facebook.Unity.Canvas\" \"Facebook.Unity.Editor\" \"Facebook.Unity.Tests\" \"UnitySDK\" \"Facebook.Unity.Windows\")\nfor PROJECT in \"${projects[@]}\"\ndo\n    printf \"Project: %s \\n\" \"$PROJECT\"\n    if [[ $PROJECT = \"UnitySDK\" ]];\n    then\n        PROJECT_FILE_NAME=\"Assembly-CSharp\"\n    else\n        PROJECT_FILE_NAME=$PROJECT\n    fi\n    line_add_from=$(grep -n '<!-- BEGIN_UNITY_REFERENCES -->' \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj | awk '{print $1}' FS=\":\")\n    line_add_to=$(grep -n '<!-- END_UNITY_REFERENCES -->' \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj | awk '{print $1}' FS=\":\")\n    line_add_from=$((line_add_from + 1))\n    line_add_to=$((line_add_to - 1))\n    if [ \"$line_add_to\" -ge \"$line_add_from\" ];\n    then\n        sed \"$line_add_from,$line_add_to d\" \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj > \"$TEMP_FILE\"\n        mv \"$TEMP_FILE\" \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj\n    fi\n    awk -v line_add_from=$line_add_from 'FNR==line_add_from{system(\"cat '\"$PROJECT\"'/UnityReferences/'\"$TARGET_VERSION\"'.xml\")} 1' \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj > \"$TEMP_FILE\"\n    mv \"$TEMP_FILE\" \"$PROJECT\"/\"$PROJECT_FILE_NAME\".csproj\n    echo \" -> $PROJECT/$PROJECT_FILE_NAME.csproj Updated!\"\ndone\n\nprintf \"\\nThe script finished successfully.\"\nexit 0\n", "num_lines": 333}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n# shellcheck disable=SC2039\n\n. \"$(dirname \"$0\")/common.sh\"\n\nBUILD_TYPE=\"Release\"\nlocalSettings=false\n\nwhile [ $# -gt 0 ]; do\n  opt=\"$1\"\n  shift\n  case $opt in\n  --debug)\n    BUILD_TYPE=Debug\n    ;;\n  --release)\n    ;;\n  --local)\n    localSettings=true\n    ;;\n    *)\n    die \"Invalid arguments\"\n    ;;\n  esac\ndone\n\n# Load settings\nsource \"$PROJECT_ROOT/scripts/build.properties\"\nLOCAL_PROPS=$PROJECT_ROOT/scripts/local.properties\nif [ \"$localSettings\" = true ]; then\n  if [ -f \"$LOCAL_PROPS\" ]; then\n    source \"$LOCAL_PROPS\"\n  else\n    echo \"No properties file found at $LOCAL_PROPS\"\n  fi\nfi\n\nPROJECT_SLN=$PROJECT_ROOT/Facebook.sln\nUNITY_CSPROJ=$UNITY_PACKAGE_ROOT/Assembly-CSharp.csproj\n\nANDROID_ROOT=$PROJECT_ROOT/Facebook.Unity.Android\nANDROID_DLL=$ANDROID_ROOT/bin/Release/Facebook.Unity.Android.dll\n\nCANVAS_ROOT=$PROJECT_ROOT/Facebook.Unity.Canvas\nCANVAS_DLL=$CANVAS_ROOT/bin/Release/Facebook.Unity.Canvas.dll\nCANVAS_JSLIB=$CANVAS_ROOT/bin/Release/CanvasJSSDKBindings.jslib\n\nEDITOR_ROOT=$PROJECT_ROOT/Facebook.Unity.Editor\nEDITOR_DLL=$EDITOR_ROOT/bin/Release/Facebook.Unity.Editor.dll\n\nIOS_ROOT=$PROJECT_ROOT/Facebook.Unity.IOS\nIOS_DLL=$IOS_ROOT/bin/Release/Facebook.Unity.IOS.dll\n\nSETTINGS_ROOT=$PROJECT_ROOT/Facebook.Unity.Settings\nSETTINGS_DLL=$SETTINGS_ROOT/bin/Release/Facebook.Unity.Settings.dll\n\nIOS_STRIPPING_HACK_ROOT=$PROJECT_ROOT/Facebook.Unity.IOS.StrippingHack\nIOS_STRIPPING_HACK_DLL=$IOS_STRIPPING_HACK_ROOT/bin/Release/Facebook.Unity.IOS.dll\nANDROID_STRIPPING_HACK_ROOT=$PROJECT_ROOT/Facebook.Unity.Android.StrippingHack\nANDROID_STRIPPING_HACK_DLL=$ANDROID_STRIPPING_HACK_ROOT/bin/Release/Facebook.Unity.Android.dll\n\nCORE_DLL=$CORE_ROOT/bin/Release/Facebook.Unity.dll\n\nWINDOWS_ROOT=$PROJECT_ROOT/Facebook.Unity.Windows\nWINDOWS_DLL=$WINDOWS_ROOT/bin/Release/Facebook.Unity.Windows.dll\nWINDOWS_SDK_DLL_DIR=$WINDOWS_ROOT/Plugins/\n\n###############################################################################\n# UPDATE BUILD VERSION\n###############################################################################\nsed -i \"\" -e \"s/[0-9]\\.[0-9][0-9]\\.[0-9]/$UNITY_SDK_BUILD_VERSION/g\" \"$PROJECT_ROOT/Facebook.Unity/FacebookSdkVersion.cs\" || die \"Failed to update the version\"\nsed -i \"\" -e \"s/AssemblyVersion(\\\"[0-9]\\.[0-9][0-9]\\.[0-9]\\\")/AssemblyVersion(\\\"$UNITY_SDK_BUILD_VERSION\\\")/g\" \\\n\"$PROJECT_ROOT/Facebook.Unity/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Canvas/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Windows/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Editor/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.IOS/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.IOS.StrippingHack/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Android/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Android.StrippingHack/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Settings/Properties/AssemblyInfo.cs\" \\\n\"$PROJECT_ROOT/Facebook.Unity.Tests/Properties/AssemblyInfo.cs\" || die \"Failed to update the DLL versions\"\n\n###############################################################################\n# BUILD SDK\n###############################################################################\ncommand -v mono >/dev/null 2>&1 || die \"mono command not found. Please install mono.\"\nmsbuild /p:Configuration=$BUILD_TYPE \"$PROJECT_SLN\" || die \"Facebook.sln Build Failed\"\n\n###############################################################################\n# COPY PLUGINS\n###############################################################################\nif [ ! -d \"$UNITY_PACKAGE_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_PACKAGE_PLUGIN\" || die \"Failed to create core plugins folder\"\nfi\ncp \"$CORE_DLL\" \"$UNITY_PACKAGE_PLUGIN\" || die \"Failed to copy core DLL\"\n\nif [ ! -d \"$UNITY_CANVAS_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_CANVAS_PLUGIN\" || die \"Failed to create Canvas plugins folder\"\nfi\ncp \"$CANVAS_DLL\" \"$UNITY_CANVAS_PLUGIN\" || die \"Failed to copy Canvas DLL\"\ncp \"$CANVAS_JSLIB\" \"$UNITY_CANVAS_PLUGIN\" || die \"Failed to copy Canvas JSLIB\"\n\nif [ ! -d \"$UNITY_ANDROID_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_ANDROID_PLUGIN\" || die \"Failed to create Android plugins folder\"\nfi\ncp \"$ANDROID_DLL\" \"$UNITY_ANDROID_PLUGIN\" || die \"Failed to copy Android DLL\"\n\nif [ ! -d \"$UNITY_WINDOWS_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_WINDOWS_PLUGIN\" || die \"Failed to create Windows plugins folder\"\nfi\ncp \"$WINDOWS_DLL\" \"$UNITY_WINDOWS_PLUGIN\" || die \"Failed to copy Windows DLL\"\ncp -R \"$WINDOWS_SDK_DLL_DIR\"* \"$UNITY_WINDOWS_PLUGIN\" || die \"Failed to copy Windows SDK DLLs\"\n\nif [ ! -d \"$UNITY_EDITOR_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_EDITOR_PLUGIN\" || die \"Failed to create Editor plugins folder\"\nfi\ncp \"$EDITOR_DLL\" \"$UNITY_EDITOR_PLUGIN\" || die \"Failed to copy Editor DLL\"\n\nif [ ! -d \"$UNITY_IOS_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_IOS_PLUGIN\" || die \"Failed to create IOS plugins folder\"\nfi\ncp \"$IOS_DLL\" \"$UNITY_IOS_PLUGIN\" || die \"Failed to copy IOS DLL\"\n\nif [ ! -d \"$UNITY_SETTINGS_PLUGIN\" ]; then\n  mkdir -p \"$UNITY_SETTINGS_PLUGIN\" || die \"Failed to create Settings plugins folder\"\nfi\ncp \"$SETTINGS_DLL\" \"$UNITY_SETTINGS_PLUGIN\" || die \"Failed to copy Settings DLL\"\n\n###############################################################################\n# BUILD EXAMPLE\n###############################################################################\nvalidate_file_exists \"$UNITY_PACKAGE_ROOT/Assembly-CSharp.csproj\" \"To generate csproj files open this project in unity at least once\"\nmsbuild /p:Configuration=$BUILD_TYPE \"$UNITY_CSPROJ\" || die \"Failed to build SDK DLL\"\n", "num_lines": 156}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# shellcheck disable=SC2039\n\ncd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" || exit 1\nPROJECT_ROOT=$(pwd)\n\nexport SCRIPTS_DIR=\"$PROJECT_ROOT/scripts\"\n\nCORE_ROOT=$PROJECT_ROOT/Facebook.Unity\n\nUNITY_PACKAGE_ROOT=$PROJECT_ROOT/UnitySDK\nUNITY_PACKAGE_PLUGIN=$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/\nexport UNITY_ANDROID_PLUGIN=$UNITY_PACKAGE_PLUGIN/Android/\nexport UNITY_CANVAS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Canvas/\nexport UNITY_EDITOR_PLUGIN=$UNITY_PACKAGE_PLUGIN/Editor/\nexport UNITY_IOS_PLUGIN=$UNITY_PACKAGE_PLUGIN/iOS/\nexport UNITY_SETTINGS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Settings/\nexport UNITY_WINDOWS_PLUGIN=$UNITY_PACKAGE_PLUGIN/Windows/\n\nRED='\\033[0;31m'\nNC='\\033[0m'\nCYAN='\\033[0;36m'\n\n# Extract the SDK version from FacebookSdkVersion.java\nSDK_VERSION_RAW=$(sed -n 's/.*\"\\(.*\\)\\\";/\\1/p' \"$CORE_ROOT/FacebookSdkVersion.cs\")\nSDK_VERSION_MAJOR=$(echo \"$SDK_VERSION_RAW\" | awk -F'.' '{print $1}')\nSDK_VERSION_MAJOR=${SDK_VERSION_MAJOR:-0}\nSDK_VERSION_MINOR=$(echo \"$SDK_VERSION_RAW\" | awk -F'.' '{print $2}')\nSDK_VERSION_MINOR=${SDK_VERSION_MINOR:-0}\nSDK_VERSION_REVISION=$(echo \"$SDK_VERSION_RAW\" | awk -F'.' '{print $3}' | tr -d '\\r')\n# SDK_VERSION_REVISION=${SDK_VERSION_REVISION:-0}\nexport SDK_VERSION=$SDK_VERSION_MAJOR.$SDK_VERSION_MINOR.$SDK_VERSION_REVISION\n\nUNITY_JAR_RESOLVER_NAME='unity-jar-resolver'\nUNITY_JAR_RESOLVER_PACKAGE_NAME='external-dependency-manager'\nUNITY_JAR_RESOLVER_BASE_URL=\"https://github.com/googlesamples/$UNITY_JAR_RESOLVER_NAME/archive/v\"\nUNITY_JAR_RESOLVER_VERSION='1.2.166'\nUNITY_JAR_RESOLVER_ZIP_URL=\"$UNITY_JAR_RESOLVER_BASE_URL$UNITY_JAR_RESOLVER_VERSION.zip\"\n\nexport OUT=\"$PROJECT_ROOT/out\"\n\n# Read UnityReferences.xml and extract unity executable path\nset_unity_path_from_settings() {\n  UNITY_VERSION_ARRAY=($(awk \"/\\<UNITY_VERSION\\>/, /\\<\\/UNITY_VERSION\\>/\" UnityReferences.xml | sed -e \"s/\\<UNITY_VERSION\\>\\(.*\\)\\<\\/UNITY_VERSION\\>/\\1/\" | xargs))\n  UNITY_VERSION=\"${UNITY_VERSION_ARRAY[0]}\"\n  if [ \"$UNITY_VERSION\" == 'NONE' ]; then\n    echo \"!Unity project not configured. Please, execute ./configure.sh to set Unity version.\"\n    exit 1\n  fi\n  UNITY_CONFIG=$(sed -n \"/\\<PropertyGroup Condition=\\\"\\'\\$(UNITY_VERSION)\\' == \\'$UNITY_VERSION\\'\\\"\\>/,/<\\/PropertyGroup>/p\" UnityReferences.xml | grep -v PropertyGroup)\n  MANAGED=($(awk \"/\\<UNITY_MANAGED_DIR\\>/, /\\<\\/UNITY_MANAGED_DIR\\>/\" <<< \"$UNITY_CONFIG\" | sed -e \"s/\\<UNITY_MANAGED_DIR\\>\\(.*\\)\\<\\/UNITY_MANAGED_DIR\\>/\\1/\" | xargs))\n  UNITY_PATH=$(sed \"s/Managed\\//MacOS\\/Unity/\" <<< \"${MANAGED[0]}\")\n  if [ ! -f \"$UNITY_PATH\" ]; then\n      echo \"Unity executable $UNITY_PATH not found.\"\n      exit 1\n  fi\n  echo \"Using Unity executable $UNITY_PATH \"\n}\n\nset_unity_path_from_settings\n\ndie() {\n  echo \"\"\n  echo \"${RED}FATAL: $* ${NC}\" >&2\n  exit 1\n}\n\n# Echoes a progress message to stderr\nprogress_message() {\n    echo \"$@\" >&2\n}\n\ninfo() {\n  echo \"${CYAN}$* ${NC}\" >&2\n}\n\ndownloadUnityJarResolverFromGithub() {\n  UNITY_JAR_RESOLVER_PACKAGE=\"$UNITY_JAR_RESOLVER_PACKAGE_NAME.unitypackage\"\n\n  pushd \"$PROJECT_ROOT\" > /dev/null || exit 1\n  info \"Downloading unity-jar-resolver...\"\n  curl -L \"$UNITY_JAR_RESOLVER_ZIP_URL\" > $UNITY_JAR_RESOLVER_NAME.zip || die \"Failed to download $UNITY_JAR_RESOLVER_URL\"\n  unzip -o -j -q $UNITY_JAR_RESOLVER_NAME.zip -d $UNITY_JAR_RESOLVER_NAME\n  mv $UNITY_JAR_RESOLVER_NAME/$UNITY_JAR_RESOLVER_PACKAGE_NAME-$UNITY_JAR_RESOLVER_VERSION.unitypackage \"$PROJECT_ROOT\"/$UNITY_JAR_RESOLVER_PACKAGE\n  rm -rf $UNITY_JAR_RESOLVER_NAME.zip $UNITY_JAR_RESOLVER_NAME\n  info \"Importing unity-jar-resolver to UnitySDK project...\"\n\n  UNITY_PACKAGE_PATH=\"$PROJECT_ROOT/$UNITY_JAR_RESOLVER_PACKAGE\"\n\n  $UNITY_PATH -quit -batchmode -logFile -nographics -projectPath=\"$PROJECT_ROOT/UnitySDK\" \\\n   -importPackage \"$UNITY_PACKAGE_PATH\" || die \"Failed to import $UNITY_PACKAGE_PATH\"\n  info \"Cleaning up...\"\n  rm \"$UNITY_PACKAGE_PATH\"\n  popd > /dev/null || exit 1\n}\n\nvalidate_file_exists() {\n  if [ ! -f \"$1\" ]; then\n    echo \"${RED}FATAL: File not found $1 ${NC}\" >&2\n    die \"$2\"\n  fi\n}\n\nvalidate_any_file_exists() {\n  FILE_COUNT=$(find \"$1\" -name \"$2\" | wc -l)\n\n  if [[ $FILE_COUNT -eq 0 ]]; then\n    echo \"${RED}FATAL: File not found $2 ${NC}\" >&2\n    die \"$3\"\n  fi\n}\n", "num_lines": 130}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n# shellcheck disable=SC2039\n\n. \"$(dirname \"$0\")/common.sh\"\n\nUNITY_CSPROJ=$UNITY_PACKAGE_ROOT/Assets/ExternalDependencyManager/Editor\n\nfix_meta(){\n  cp \"$1\" \"$UNITY_CSPROJ/meta.txt\"\n  sed s/_v1.2.166././g \"$UNITY_CSPROJ/meta.txt\" > \"$1\"\n  rm \"$UNITY_CSPROJ/meta.txt\"\n}\n\nset_name(){\n  if [ ! -f \"$1\" ]; then\n    echo \"Missing DLL\"\n    echo \"$1\"\n    exit 1\n  fi\n  mv \"$1\" \"$2\"\n  mv \"$1.meta\" \"$2.meta\"\n  fix_meta \"$2.meta\"\n}\n\nset_name $UNITY_CSPROJ/Google.IOSResolver*.dll \"$UNITY_CSPROJ/Google.IOSResolver.dll\"\nset_name $UNITY_CSPROJ/Google.IOSResolver*.dll.mdb \"$UNITY_CSPROJ/Google.IOSResolver.dll.mdb\"\nset_name $UNITY_CSPROJ/Google.JarResolver*.dll \"$UNITY_CSPROJ/Google.JarResolver.dll\"\nset_name $UNITY_CSPROJ/Google.JarResolver*.dll.mdb \"$UNITY_CSPROJ/Google.JarResolver.dll.mdb\"\nset_name $UNITY_CSPROJ/Google.PackageManagerResolver*.dll \"$UNITY_CSPROJ/Google.PackageManagerResolver.dll\"\nset_name $UNITY_CSPROJ/Google.PackageManagerResolver*.dll.mdb \"$UNITY_CSPROJ/Google.PackageManagerResolver.dll.mdb\"\nset_name $UNITY_CSPROJ/Google.VersionHandlerImpl*.dll \"$UNITY_CSPROJ/Google.VersionHandlerImpl.dll\"\nset_name $UNITY_CSPROJ/Google.VersionHandlerImpl*.dll.mdb \"$UNITY_CSPROJ/Google.VersionHandlerImpl.dll.mdb\"\n\ncp \"$UNITY_CSPROJ/external-dependency-manager_version-1.2.166_manifest.txt\" $UNITY_CSPROJ/tmp.txt\n## TO DO: obtain the dependency version dinamically\nsed s/_v1.2.166././g \"$UNITY_CSPROJ/tmp.txt\" > \"$UNITY_CSPROJ/external-dependency-manager_version-1.2.166_manifest.txt\"\nrm \"$UNITY_CSPROJ/tmp.txt\"\n\nmkdir -p \"$UNITY_CSPROJ/1.2.166/\"\nmv \"$UNITY_CSPROJ/Google.IOSResolver.dll\" \"$UNITY_CSPROJ/1.2.166/Google.IOSResolver.dll\"\nmv \"$UNITY_CSPROJ/Google.IOSResolver.dll.mdb\" \"$UNITY_CSPROJ/1.2.166/Google.IOSResolver.dll.mdb\"\nmv \"$UNITY_CSPROJ/Google.JarResolver.dll\" \"$UNITY_CSPROJ/1.2.166/Google.JarResolver.dll\"\nmv \"$UNITY_CSPROJ/Google.JarResolver.dll.mdb\" \"$UNITY_CSPROJ/1.2.166/Google.JarResolver.dll.mdb\"\nmv \"$UNITY_CSPROJ/Google.PackageManagerResolver.dll\" \"$UNITY_CSPROJ/1.2.166/Google.PackageManagerResolver.dll\"\nmv \"$UNITY_CSPROJ/Google.PackageManagerResolver.dll.mdb\" \"$UNITY_CSPROJ/1.2.166/Google.PackageManagerResolver.dll.mdb\"\nmv \"$UNITY_CSPROJ/Google.VersionHandlerImpl.dll\" \"$UNITY_CSPROJ/1.2.166/Google.VersionHandlerImpl.dll\"\nmv \"$UNITY_CSPROJ/Google.VersionHandlerImpl.dll.mdb\" \"$UNITY_CSPROJ/1.2.166/Google.VersionHandlerImpl.dll.mdb\"\n", "num_lines": 69}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n. $(dirname $0)/common.sh\n\n$UNITY_PATH -batchmode -nographics -projectPath \"$UNITY_PACKAGE_ROOT\" -executeMethod FacebookConsoleEndpoint.ExportPackage -quit \\\n|| die \"Failed to export package. Make sure the Facebook.Unity project is not open in Unity\"\n\ninfo \"Unity Package exported to $PROJECT_ROOT/out/facebook-unity-sdk-$SDK_VERSION.unitypackage\"\n", "num_lines": 29}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n# shellcheck disable=SC2039\n\nset -euo pipefail\n\n# --------------\n# Functions\n# --------------\n\n# Main\nmain() {\n  SDK_SCRIPTS_DIR=$(realpath \"$(dirname \"${BASH_SOURCE[0]}\")\")\n  SDK_DIR=\"$(dirname \"$SDK_SCRIPTS_DIR\")\"\n\n  SDK_VERSION_FILES=(\n    \"scripts/build.properties\"\n    \"Facebook.Unity/FacebookSdkVersion.cs\"\n    \"Facebook.Unity/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Canvas/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Editor/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.IOS/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.IOS.StrippingHack/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Android/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Android.StrippingHack/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Settings/Properties/AssemblyInfo.cs\"\n    \"Facebook.Unity.Tests/Properties/AssemblyInfo.cs\"\n  )\n\n  SDK_MAIN_VERSION_FILE=\"scripts/build.properties\"\n  SDK_CURRENT_VERSION=$(grep -Eo \"UNITY_SDK_BUILD_VERSION='.*'\" \"$SDK_MAIN_VERSION_FILE\" | awk -F \"'\" '{print $2}')\n\n  SDK_GIT_REMOTE=\"https://github.com/facebook/facebook-sdk-for-unity\"\n\n  local command_type=${1:-}\n  if [ -n \"$command_type\" ]; then shift; fi\n\n  case \"$command_type\" in\n  \"bump-changelog\") bump_changelog \"$@\" ;;\n  \"bump-version\") bump_version \"$@\" ;;\n  \"tag-current-version\") tag_current_version \"$@\" ;;\n  \"--help\" | \"help\") echo \"Check main() for supported commands\" ;;\n  esac\n}\n\n# Bump Changelog\nbump_changelog() {\n  local new_version=${1:-}\n\n  # Edit Changelog\n  updated_changelog=\"\"\n\n  while IFS= read -r line; do\n    if [[ $line == \"## [Unreleased]\"* ]]; then\n      current_date=$(date +%Y-%m-%d)\n      updated_line=$line\"\\n\"\n      updated_line=$updated_line\"\\n\"\n      updated_line=$updated_line\"## [$new_version] - $current_date\\n\"\n    elif [[ $line == \"[Unreleased]\"* ]]; then\n      updated_line=\"[Unreleased]: $SDK_GIT_REMOTE/compare/sdk-version-$new_version...HEAD\\n\"\n      updated_line=$updated_line\"[$new_version]: $SDK_GIT_REMOTE/compare/sdk-version-$SDK_CURRENT_VERSION...sdk-version-$new_version\\n\"\n    else\n      updated_line=$line\"\\n\"\n    fi\n    updated_changelog=$updated_changelog$updated_line\n  done <\"CHANGELOG.md\"\n\n  echo \"$updated_changelog\" >CHANGELOG.md\n}\n\n# Bump Version\nbump_version() {\n  local new_version=${1:-}\n\n  if [ \"$new_version\" == \"$SDK_CURRENT_VERSION\" ]; then\n    echo \"This version is the same as the current version\"\n    false\n    return\n  fi\n\n  if ! is_valid_semver \"$new_version\"; then\n    echo \"This version isn't a valid semantic versioning\"\n    false\n    return\n  fi\n\n  echo \"Changing from: $SDK_CURRENT_VERSION to: $new_version\"\n\n  # Replace the previous version to the new version in relative files\n  for file_path in \"${SDK_VERSION_FILES[@]}\"; do\n    local full_file_path=\"$SDK_DIR/$file_path\"\n\n    if [ ! -f \"$full_file_path\" ]; then\n      echo \"*** NOTE: unable to find $full_file_path.\"\n      continue\n    fi\n\n    local temp_file=\"$full_file_path.tmp\"\n    sed -e \"s/$SDK_CURRENT_VERSION/$new_version/g\" \"$full_file_path\" >\"$temp_file\"\n    if diff \"$full_file_path\" \"$temp_file\" >/dev/null; then\n      echo \"*** ERROR: unable to update $full_file_path\"\n      rm \"$temp_file\"\n      continue\n    fi\n\n    mv \"$temp_file\" \"$full_file_path\"\n  done\n\n  bump_changelog \"$new_version\"\n}\n\n# Tag push current version\ntag_current_version() {\n  if ! is_valid_semver \"$SDK_CURRENT_VERSION\"; then\n    exit 1\n  fi\n\n  if does_version_exist \"$SDK_CURRENT_VERSION\"; then\n    echo \"Version $SDK_CURRENT_VERSION already exists\"\n    false\n    return\n  fi\n\n  git tag -a \"sdk-version-$SDK_CURRENT_VERSION\" -m \"Version $SDK_CURRENT_VERSION\"\n\n  if [ \"${1:-}\" == \"--push\" ]; then\n    git push origin \"sdk-version-$SDK_CURRENT_VERSION\"\n  fi\n}\n\n# Proper Semantic Version\nis_valid_semver() {\n  if ! [[ ${1:-} =~ ^([0-9]{1}|[1-9][0-9]+)\\.([0-9]{1}|[1-9][0-9]+)\\.([0-9]{1}|[1-9][0-9]+)($|[-+][0-9A-Za-z+.-]+$) ]]; then\n    false\n    return\n  fi\n}\n\n# Check Version Tag Exists\ndoes_version_exist() {\n  local version_to_check=${1:-}\n\n  if [ \"$version_to_check\" == \"\" ]; then\n    version_to_check=$SDK_CURRENT_VERSION\n  fi\n\n  if [ ! -d \"$SDK_DIR\"/.git ]; then\n    echo \"Not a Git Repository\"\n    return\n  fi\n\n  if git rev-parse \"v$version_to_check\" >/dev/null 2>&1; then\n    return\n  fi\n\n  if git rev-parse \"sdk-version-$version_to_check\" >/dev/null 2>&1; then\n    return\n  fi\n\n  false\n}\n\n# --------------\n# Main Script\n# --------------\n\nmain \"$@\"\n", "num_lines": 185}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n. \"$(dirname \"$0\")/common.sh\"\n\n# Run build script to ensure that test DLL is built\n\"$SCRIPTS_DIR/build.sh\" || die \"Build failed\"\n\ncommand -v mono >/dev/null 2>&1 || die \"mono command not found. Please install mono.\"\n\nNSUBSTITUTE_CONSOLE=\"$PROJECT_ROOT/packages/NSubstitute.2.0.3/lib\"\nNUNIT_CONSOLE=\"$PROJECT_ROOT/packages/NUnit.ConsoleRunner.3.10.0/tools/nunit3-console.exe\"\nTEST_DLL=\"$PROJECT_ROOT/Facebook.Unity.Tests/bin/Release/Facebook.Unity.Tests.dll\"\n\nvalidate_any_file_exists \"$NSUBSTITUTE_CONSOLE\" \"NSubstitute.dll\" \"Make sure NSubstitute is installed at /packages\"\nvalidate_file_exists \"$NUNIT_CONSOLE\" \"Make sure mono is installed at this path\"\nvalidate_file_exists \"$TEST_DLL\" \"Make sure that the Unity Project successfully built\"\n\nmono \"$NUNIT_CONSOLE\" \"$TEST_DLL\" --workers=0 || die \"Some tests failed\"\n", "num_lines": 39}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# This file performs the custom build logic to setup the Plugins\n# in the unity project\n\n# shellcheck disable=SC2039\n\n. \"$(dirname \"$0\")/common.sh\"\n\ncommand -v nuget >/dev/null 2>&1 || die \"nuget command not found. Please install nuget.\"\necho \"checking packages...\"\nnuget restore \"$PROJECT_ROOT\"\necho \"checking packages done.\"\n\n#skycatle build\nskycastleBuild=false\nif [[ $* != *--skycastle* ]]; then\ncd \"$SCRIPTS_DIR\" || die \"$SCRIPTS_DIR not found\"\n./build.sh\nfi\n\n\"$SCRIPTS_DIR/setup_ios_unity_plugin.sh\" \"$@\" || die \"Failed to setup the ios sdk plugin\"\n\"$SCRIPTS_DIR/setup_android_unity_plugin.sh\" \"$@\" || die \"Failed to build the android sdk plugin\"\n\ncd \"$SCRIPTS_DIR\" || die \"$SCRIPTS_DIR not found\"\n./build.sh\n", "num_lines": 44}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# shellcheck disable=SC2039\n\n. $(dirname $0)/common.sh\n\nsource \"$PROJECT_ROOT/scripts/build.properties\"\n\ninfo \"Starting build\"\n# Check for required settings\nif [ -z \"$ANDROID_HOME\" ]; then\n    echo \"${RED}ERROR: ANDROID_HOME environment variable not set${NC}\"\n    echo \"${RED}Please set the ANDROID_HOME environment variable to point to your android sdk${NC}\"\n    exit 1\nfi\n\nlocalBuild=false\nif [[ $* == *--local* ]]; then\n  localBuild=true\nfi\n\n#skycatle build\nskycastleBuild=false\nif [[ $* == *--skycastle* ]]; then\n  skycastleBuild=true\nfi\n\n# Copy the required libs\nUNITY_PLUGIN_FACEBOOK=\"$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/Android/libs\"\n\nFB_WRAPPER_PATH=\"$PROJECT_ROOT/facebook-android-wrapper\"\nFB_ANDROID_SDK_WRAPPER_NAME=\"facebook-android-wrapper.aar\"\nFB_ANDROID_SDK_WRAPPER=\"$FB_WRAPPER_PATH/build/outputs/aar/$FB_ANDROID_SDK_WRAPPER_NAME\"\n\n# Local build only properties\nFB_WRAPPER_LIB_PATH=\"$FB_WRAPPER_PATH/libs\"\nFB_GS_SDK_AAR_NAME=\"facebook-gamingservices-release.aar\"\n# FB_GS_SDK_AAR_PATH=\"$FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME\"\nFB_GS_SDK_AAR=\"$FB_ANDROID_SDK_PATH/facebook-gamingservices/build/outputs/aar/$FB_GS_SDK_AAR_NAME\"\n\n# Get Unity Jar Resolver\ninfo \"Step 1 - Download $UNITY_JAR_RESOLVER_NAME\"\nif [ \"$skycastleBuild\" = true ]; then\n  info \"Using custom version from Skycastle builder resource repo.\"\nelse\n  downloadUnityJarResolverFromGithub\nfi\n\ninfo \"Step 2 - Build android wrapper\"\npushd \"$FB_WRAPPER_PATH\"\nif [ \"$localBuild\" = true ]; then\n  if [ ! -d \"$FB_WRAPPER_LIB_PATH\" ]; then\n    mkdir -p \"$FB_WRAPPER_LIB_PATH\" || die \"Failed to create wrapper libs folder\"\n  fi\n  info \"Step 2.1 - Build local Facebook Gaming Services Android SDK at '$FB_ANDROID_SDK_PATH'\"\n  pushd $FB_ANDROID_SDK_PATH\n  ./gradlew :facebook-gamingservices:assemble || die \"Failed to build Facebook Gaming Services Android SDK\"\n  popd\n  info \"Step 2.2 - Copy $FB_ANDROID_SDK_AAR to $FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME folder\"\n  cp \"$FB_GS_SDK_AAR\" \"$FB_WRAPPER_LIB_PATH/$FB_GS_SDK_AAR_NAME\" || die \"Failed to copy sdk to wrapper libs folder\"\n  ./gradlew clean -PlocalRepo=libs -PsdkVersion=\"$FB_ANDROID_SDK_VERSION\" -Pskycastle=$skycastleBuild || die \"Failed to perform gradle clean\"\n  ./gradlew assemble -PlocalRepo=libs -PsdkVersion=\"$FB_ANDROID_SDK_VERSION\" -Pskycastle=$skycastleBuild || die \"Failed to build facebook android wrapper\"\nelse\n  ./gradlew clean -Pskycastle=$skycastleBuild || die \"Failed to perform gradle clean\"\n  ./gradlew assemble -Pskycastle=$skycastleBuild || die \"Failed to build facebook android wrapper\"\nfi\npopd\n\ninfo \"Step 3 - Copy libs to unity plugin folder\"\nif [ ! -d \"$UNITY_PLUGIN_FACEBOOK\" ]; then\n  mkdir -p \"$UNITY_PLUGIN_FACEBOOK\" || die \"Failed to make unity plugin lib folder\"\nfi\n# clean the unity lib folder\nrm -rf $UNITY_PLUGIN_FACEBOOK/*.jar\nrm -rf $UNITY_PLUGIN_FACEBOOK/*.aar\nrm -rf $UNITY_PLUGIN_FACEBOOK/*.meta\n\n# Copy aars\ncp \"$FB_ANDROID_SDK_WRAPPER\" \"$UNITY_PLUGIN_FACEBOOK\" || die 'Failed to copy wrapper to unity plugin folder'\n# Rename wrapper to include sdk version\nmv \"$UNITY_PLUGIN_FACEBOOK/$FB_ANDROID_SDK_WRAPPER_NAME\" \"$UNITY_PLUGIN_FACEBOOK/facebook-android-wrapper-$SDK_VERSION.aar\"\n\ninfo \"Done!\"\n", "num_lines": 101}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n\n# shellcheck disable=SC2039\n\n. \"$(dirname \"$0\")/common.sh\"\n\ncd \"$(dirname \"$0\")/..\" || die \"$(dirname \"$0\")/.. not found\"\nPROJECT_ROOT=$(pwd)\n. \"$PROJECT_ROOT/scripts/build.properties\"\n\nrm -rf tempIosBuild\nmkdir tempIosBuild\ncd tempIosBuild || die \"Directory tempIosBuild not found\"\n\nUNITY_PLUGIN_FACEBOOK=\"$UNITY_PACKAGE_ROOT/Assets/FacebookSDK/Plugins/iOS\"\nmkdir -p \"$UNITY_PLUGIN_FACEBOOK\"\nrm -rf \"$UNITY_PLUGIN_FACEBOOK/*.framework\"\n\ncd \"$PROJECT_ROOT\" || die \"$PROJECT_ROOT not found\"\nrm -rf tempIosBuild\n", "num_lines": 38}
{"repo_name": "facebook-sdk-for-unity", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2014-present, Facebook, Inc. All rights reserved.\n#\n# You are hereby granted a non-exclusive, worldwide, royalty-free license to use,\n# copy, modify, and distribute this software in source code or binary form for use\n# in connection with the web services and APIs provided by Facebook.\n#\n# As with any software that integrates with the Facebook platform, your use of\n# this software is subject to the Facebook Developer Principles and Policies\n# [http://developers.facebook.com/policy/]. This copyright notice shall be\n# included in all copies or substantial portions of the software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n# shellcheck disable=SC2039\n\n# --------------\n# Main Script\n# --------------\n\nCACHE=\"$(pwd)/cache\"\nLOGFILE=\"$(pwd)/tmp.log\"\n\nOSX_DOTNET_PACKAGE_URL=\"https://download.visualstudio.microsoft.com/download/pr/5c281f95-91c4-499d-baa2-31fec919047a/38c6964d72438ac30032bce516b655d9/dotnet-sdk-3.0.100-osx-x64.pkg\"\nOSX_UNITY_PACKAGE_URL=\"https://download.unity3d.com/download_unity/e80cc3114ac1/MacEditorInstaller/Unity-5.6.7f1.pkg\"\n\ninstall() {\n  # Download Unity Package from URL if it doesn't exist in cache directory\n  local url=${1:-}\n  local filename=$(basename $url)\n\n  if [ ! -f \"$CACHE/$filename\" ]; then\n    echo \"*** NOTE: unable to find $filename, download from $url.\"\n    mkdir -p \"$CACHE\"\n    curl -o \"$CACHE/$filename\" \"$url\"\n  fi\n\n  # Install Unity Package\n  sudo installer -dumplog -package \"$CACHE/$filename\" -target /\n}\n\nbrew tap caskroom/cask\nbrew cask install android-sdk  > \"$LOGFILE\"\nbrew install gradle  > \"$LOGFILE\"\n\necho yes | $ANDROID_HOME/tools/bin/sdkmanager \"platforms;android-27\" \"build-tools;27.0.3\" > \"$LOGFILE\"\n\ninstall $OSX_DOTNET_PACKAGE_URL\ninstall $OSX_UNITY_PACKAGE_URL\n", "num_lines": 55}
{"repo_name": "facebook360_dep", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n# We must use the full path to aws, since non-interactive shells do not source ~/.bashrc\naws configure set aws_access_key_id $1\naws configure set aws_secret_access_key $2\naws configure set default.region $3\n\nKOPS_STATE_BUCKET=$6-facebook360-dep-kops-state-store\nexport KOPS_CLUSTER_NAME=$6.facebook360.dep.k8s.local\nexport KOPS_STATE_STORE=s3://${KOPS_STATE_BUCKET}\n\naws s3api create-bucket --bucket ${KOPS_STATE_BUCKET} --region us-west-2 --create-bucket-configuration LocationConstraint=us-west-2 &> /dev/null\naws s3api put-bucket-versioning --bucket ${KOPS_STATE_BUCKET} --versioning-configuration Status=Enabled\n\nkops create secret --name ${KOPS_CLUSTER_NAME} sshpublickey admin -i ~/.ssh/id_rsa.pub\n\nif $7; then\n  echo \"Deleting old cluster. This can take a few minutes...\"\n  kops delete cluster --yes\nfi\n\nkops create cluster \\\n  --node-count=$4 \\\n  --master-size=c4.large \\\n  --node-size=$5 \\\n  --zones=us-west-2a \\\n  --image kope.io/k8s-1.12-debian-stretch-amd64-hvm-ebs-2019-05-13 \\\n  --kubernetes-version 1.12.0 &> /dev/null\n\n# Enable Kops Installation Hook and DevicePlugins for Nvidia GPUs\nif [[ $5 == p* ]] || [[ $5 == g* ]]; then\n  kops get ig nodes -o yaml > scripts/aws/ig.yml\n  echo \"  hooks:\" >> scripts/aws/ig.yml\n  echo \"  - execContainer:\" >> scripts/aws/ig.yml\n  echo \"      image: dcwangmit01/nvidia-device-plugin:0.1.0\" >> scripts/aws/ig.yml\n  kops replace -f scripts/aws/ig.yml\nfi\n\nkops update cluster --name ${KOPS_CLUSTER_NAME} --yes &> /dev/null\n\necho \"Spawning $(($4 + 1)) machines. This can take several minutes...\"\nwhile [ 1 ]\ndo\n    kops validate cluster && break || (sleep 1 && echo -e \"\\nStill initializing...\\n\" && sleep 10)\ndone\n\n# Deploy the Daemonset for the Nvidia DevicePlugin\nif [[ $5 == p* ]] || [[ $5 == g* ]]; then\n  error_msg=$(kubectl create -f https://raw.githubusercontent.com/NVIDIA/k8s-device-plugin/v1.12/nvidia-device-plugin.yml 2>1&)\n  if [[ ${error_msg} == *AlreadyExists*  ]]; then\n    exit 0\n  fi\nfi\n", "num_lines": 59}
{"repo_name": "facebook360_dep", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\n# Flushes the queue from any previous (incomplete) runs\nsudo service rabbitmq-server restart\n\n# Allows access to AWS secretes\nif [ $(kubectl get secrets | grep aws-storage-key | wc -l) > 0 ]; then\n  kubectl delete secrets aws-storage-key\nfi\n\nkubectl create secret generic aws-storage-key \\\n  --from-literal=AWS_ACCESS_KEY_ID=$(aws configure get aws_access_key_id) \\\n  --from-literal=AWS_SECRET_ACCESS_KEY=$(aws configure get aws_secret_access_key)\n\n# Get k8s cluster ready\nsed \"s|<REPO_NAME>|$1:worker|g\" scripts/aws/farm.yml.template > scripts/aws/farm.yml\nsed -i \"s|<MASTER_IP>|$2|g\" scripts/aws/farm.yml\nsed -i \"s|<WORKER_COUNT>|$3|g\" scripts/aws/farm.yml\nkubectl apply -f scripts/aws/farm.yml\n\n# Ensure that all the pods receive the newest image\nkubectl delete pods --all --grace-period=0 --force\n", "num_lines": 28}
{"repo_name": "facebook360_dep", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nif hash nvidia-docker 2>/dev/null; then\n  echo \"Found nvidia-docker\"\nelse\n  # Check if we have an NVIDIA GPU\n  sudo apt-get install -y mesa-utils\n  if glxinfo | grep -i \"nvidia\"; then\n    echo \"Installing nvidia drivers. It make take a few minutes...\"\n    sudo apt-get update\n    sudo apt install -y build-essential gcc libc-dev\n    sudo apt-get install -y linux-headers-$(uname -r)\n    wget https://developer.nvidia.com/compute/cuda/10.1/Prod/local_installers/cuda_10.1.168_418.67_linux.run\n    sudo sh cuda_10.1.168_418.67_linux.run --silent --driver --toolkit\n\n    # Display GPU info\n    nvidia-smi\n\n    echo \"Installing nvidia-docker...\"\n\n    # Add the package repositories\n    curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | sudo apt-key add -\n    distribution=$(. /etc/os-release;echo $ID$VERSION_ID)\n    curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.list | sudo tee /etc/apt/sources.list.d/nvidia-docker.list\n    sudo apt-get update\n\n    # Install nvidia-docker2 and reload the Docker daemon configuration\n    sudo apt-get install -y nvidia-docker2\n    sudo pkill -SIGHUP dockerd\n\n    # To test nvidia-smi with the latest official CUDA image\n    # sudo docker run --runtime=nvidia --rm nvidia/cuda:9.0-base nvidia-smi\n  else\n    echo \"No NVIDIA GPU found. Skipping GPU setup...\"\n  fi\nfi\n", "num_lines": 42}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nexport MAX_JOBS=1\n\n# install python\napt-get update\napt-get -y install python python-pip git-core\n\npip install virtualenv\n\n# setup virtualenv\nVENV_DIR=/tmp/venv\nPYTHON=\"$(which python)\"\nif [[ \"${CIRCLE_JOB}\" =~ py((2|3)\\\\.?[0-9]?\\\\.?[0-9]?) ]]; then\n    PYTHON=$(which \"python${BASH_REMATCH[1]}\")\nfi\n$PYTHON -m virtualenv \"$VENV_DIR\"\nsource \"$VENV_DIR/bin/activate\"\npip install -U pip setuptools\n\n# define some variables\nFAI_PEP_DIR=/tmp/FAI-PEP\nCONFIG_DIR=/tmp/config\nLOCAL_REPORTER_DIR=/tmp/reporter\n\nREPO_DIR=/tmp/pytorch\n\nBENCHMARK_FILE=${FAI_PEP_DIR}/specifications/models/caffe2/squeezenet/squeezenet.json\n\nmkdir -p \"$CONFIG_DIR\"\nmkdir -p \"$LOCAL_REPORTER_DIR\"\n\n# clone FAI-PEP\nrm -rf ${FAI_PEP_DIR}\ngit clone https://github.com/facebook/FAI-PEP.git \"$FAI_PEP_DIR\"\npip install six requests\n\n# set up default arguments\necho \"\n{\n  \\\"--commit\\\": \\\"master\\\",\n  \\\"--exec_dir\\\": \\\"${CONFIG_DIR}/exec\\\",\n  \\\"--framework\\\": \\\"caffe2\\\",\n  \\\"--local_reporter\\\": \\\"${CONFIG_DIR}/reporter\\\",\n  \\\"--model_cache\\\": \\\"${CONFIG_DIR}/model_cache\\\",\n  \\\"--platforms\\\": \\\"host/incremental\\\",\n  \\\"--remote_repository\\\": \\\"origin\\\",\n  \\\"--repo\\\": \\\"git\\\",\n  \\\"--repo_dir\\\": \\\"${REPO_DIR}\\\",\n  \\\"--root_model_dir\\\": \\\"${CONFIG_DIR}/root_model_dir\\\",\n  \\\"--screen_reporter\\\": null\n}\n\" > ${CONFIG_DIR}/config.txt\n\n# clone/install pytorch\npip install numpy pyyaml mkl mkl-include setuptools cmake cffi typing\n\nif [ ! -d \"${REPO_DIR}\" ]; then\n  git clone --recursive --quiet https://github.com/pytorch/pytorch.git \"$REPO_DIR\"\nfi\n\n# install ninja to speedup the build\npip install ninja\n\n# run benchmark\nRUN_IMAGENET=0\nif [ $# -gt 0 ]; then\n  if [ ! -z \"$1\" ]; then\n    RUN_IMAGENET=1\n  fi\nfi\n\nif [ ${RUN_IMAGENET} -gt 0 ]; then\n  # install opencv for image conversion\n  if [ ! -d /tmp/opencv-3.4.3 ]; then\n    apt-get -y install wget unzip\n    wget -O /tmp/opencv.zip https://github.com/opencv/opencv/archive/3.4.3.zip\n    unzip -q /tmp/opencv.zip -d /tmp/\n    cd /tmp/opencv-3.4.3/\n    mkdir build\n    cd build\n    cmake ..\n    make -j 4\n    make install\n  fi\n\n  python ${FAI_PEP_DIR}/benchmarking/run_bench.py -b ${FAI_PEP_DIR}/specifications/models/caffe2/squeezenet/squeezenet_accuracy_imagenet.json --string_map \"{\\\"imagenet_dir\\\": \\\"$1\\\"}\" --config_dir \"${CONFIG_DIR}\"\n\nelse\n  python ${FAI_PEP_DIR}/benchmarking/run_bench.py -b \"${BENCHMARK_FILE}\" --config_dir \"${CONFIG_DIR}\"\nfi\n", "num_lines": 94}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nexport MAX_JOBS=1\n\n# install python\napt-get update\napt-get -y install python python-pip git-core\n\npip install virtualenv\n\n# setup virtualenv\nVENV_DIR=/tmp/venv\nPYTHON=\"$(which python)\"\nif [[ \"${CIRCLE_JOB}\" =~ py((2|3)\\\\.?[0-9]?\\\\.?[0-9]?) ]]; then\n    PYTHON=$(which \"python${BASH_REMATCH[1]}\")\nfi\n$PYTHON -m virtualenv \"$VENV_DIR\"\nsource \"$VENV_DIR/bin/activate\"\npip install -U pip setuptools\n\n# define some variables\nFAI_PEP_DIR=/tmp/FAI-PEP\nCONFIG_DIR=/tmp/config\nREPO_DIR=/tmp/tensorflow\nLOCAL_REPORTER_DIR=/tmp/reporter\n\nBAZEL_DIR=/tmp/bazel\nBAZEL=bazel-0.25.0-installer-linux-x86_64.sh\n\nBENCHMARK_FILE=${FAI_PEP_DIR}/specifications/models/tflite/mobilenet_v2/mobilenet_v2_0.35_96.json\n\nmkdir -p \"$CONFIG_DIR\"\nmkdir -p \"$LOCAL_REPORTER_DIR\"\n\n# clone FAI-PEP\nrm -rf ${FAI_PEP_DIR}\ngit clone https://github.com/facebook/FAI-PEP.git \"$FAI_PEP_DIR\"\npip install six requests\n\n# set up default arguments\necho \"\n{\n  \\\"--commit\\\": \\\"master\\\",\n  \\\"--exec_dir\\\": \\\"${CONFIG_DIR}/exec\\\",\n  \\\"--framework\\\": \\\"tflite\\\",\n  \\\"--local_reporter\\\": \\\"${CONFIG_DIR}/reporter\\\",\n  \\\"--model_cache\\\": \\\"${CONFIG_DIR}/model_cache\\\",\n  \\\"--platforms\\\": \\\"host\\\",\n  \\\"--remote_repository\\\": \\\"origin\\\",\n  \\\"--repo\\\": \\\"git\\\",\n  \\\"--repo_dir\\\": \\\"${REPO_DIR}\\\",\n  \\\"--root_model_dir\\\": \\\"${CONFIG_DIR}/root_model_dir\\\",\n  \\\"--screen_reporter\\\": null\n}\n\" > ${CONFIG_DIR}/config.txt\n\n# clone/install tflite\n\napt-get install wget pkg-config g++ zlib1g-dev python zip unzip -y\nif [ ! -z ${BAZEL_DIR} ]; then\n  mkdir -p ${BAZEL_DIR}\nfi\nif [ ! -f ${BAZEL_DIR}/${BAZEL} ]; then\n  wget -q -O ${BAZEL_DIR}/${BAZEL} https://github.com/bazelbuild/bazel/releases/download/0.25.0/${BAZEL}\nfi\nchmod +x ${BAZEL_DIR}/${BAZEL}\n${BAZEL_DIR}/${BAZEL} --user\nexport PATH=\"$PATH:$HOME/bin\"\n\nrm -rf ${REPO_DIR}\ngit clone --recursive --quiet https://github.com/tensorflow/tensorflow.git \"$REPO_DIR\"\n\n# run benchmark\n\npython ${FAI_PEP_DIR}/benchmarking/run_bench.py -b \"${BENCHMARK_FILE}\" --config_dir \"${CONFIG_DIR}\"\n", "num_lines": 78}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nrm -rf $1/build/\n$1/scripts/build_local.sh -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON\ncp $1/build/bin/caffe2_benchmark $2\n", "num_lines": 6}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nrm -rf $1/build*\n$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON\ncp $1/build_android/bin/caffe2_benchmark $2\n", "num_lines": 8}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nrm -rf $1/build*\n$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DANDROID_TOOLCHAIN=clang\ncp $1/build_android/bin/caffe2_benchmark $2\n", "num_lines": 8}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n set -ex\n\n$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON\ncp \"$1/build_android/bin/caffe2_benchmark\" \"$2\"\n", "num_lines": 7}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nDIR=$(dirname \"$2\")\n\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON\n$1/scripts/build_android.sh -DBUILD_BINARY=ON -DUSE_OBSERVERS=ON -DUSE_ZSTD=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON\ncp \"$1/build/bin/convert_image_to_tensor\" \"${DIR}/convert_image_to_tensor\"\ncp \"$1/build_android/bin/caffe2_benchmark\" \"$2\"\n", "num_lines": 11}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\nDIR=$(dirname \"$2\")\n\nrm -rf $1/build/\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON\ncp $1/build/bin/caffe2_benchmark $2\nif [ -f $1/build/bin/convert_image_to_tensor ]; then\n  cp \"$1/build/bin/convert_image_to_tensor\" \"${DIR}/convert_image_to_tensor\"\nfi\n", "num_lines": 12}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nDIR=$(dirname \"$2\")\n\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON -DUSE_OPENCV=ON\ncp $1/build/bin/caffe2_benchmark $2\nif [ -f $1/build/bin/convert_image_to_tensor ]; then\n  cp \"$1/build/bin/convert_image_to_tensor\" \"${DIR}/convert_image_to_tensor\"\nfi\n", "num_lines": 12}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nrm -rf $1/build/\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON\ncp $1/build/bin/caffe2_benchmark $2\n", "num_lines": 8}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nrm -rf $1/build/\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DUSE_OBSERVERS=ON\ncp $1/build/bin/caffe2_benchmark $2\n", "num_lines": 8}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nrm -rf $1/build/\n$1/scripts/build_local.sh -DBUILD_SHARED_LIBS=OFF -DBUILD_BINARY=ON -DBUILD_SHARE_DIR=ON -DBUILD_OBSERVERS=ON -DUSE_ZSTD=ON -DBLAS=MKL -DUSE_OBSERVERS=ON\ncp $1/build/bin/caffe2_benchmark $2\n", "num_lines": 8}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nDIR=${PWD}\n# the configure must be run once beforehand\ncd \"$1\"\n\n# build benchmark binary\n# assuming the configure has set up the NDK and SDK correctly\nbazel build -c opt \\\n  --config=android_arm \\\n  --cxxopt='--std=c++11' \\\n  tensorflow/lite/tools/benchmark:benchmark_model\n\ncd ${DIR}\n\ncp \"$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model\" \"$2\"\n", "num_lines": 19}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nDIR=${PWD}\n# the configure must be run once beforehand\ncd \"$1\"\n\n# build benchmark binary\n# assuming the configure has set up the NDK and SDK correctly\nbazel build -c opt \\\n  --config=android_arm \\\n  --cxxopt='--std=c++11' \\\n  --copt=-DTFLITE_PROFILING_ENABLED \\\n  tensorflow/lite/tools/benchmark:benchmark_model\n\ncd ${DIR}\ncp \"$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model\" \"$2\"\n", "num_lines": 19}
{"repo_name": "FAI-PEP", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -ex\n\nDIR=${PWD}\n# the configure must be run once beforehand\ncd \"$1\"\n\necho \"OS is $(uname)\"\n\nLINKER_OPTS=\"\"\nif [ \"$(uname)\" = 'Linux' ]; then\n  LINKER_OPTS=\"--linkopt -latomic\"\nfi\necho \"OPTS: ${LINKER_OPTS}\"\n# build benchmark binary\n# assuming the configure has set up the NDK and SDK correctly\nbazel build -c opt ${LINKER_OPTS} \\\n  tensorflow/lite/tools/benchmark:benchmark_model\n\ncd ${DIR}\n\ncp \"$1/bazel-bin/tensorflow/lite/tools/benchmark/benchmark_model\" \"$2\"\n", "num_lines": 24}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. ./scripts.inc\n\nset -e\n\nlclear\n\nif [ -z \"$USE_CC\" ]; then\n  for cc in $full_compilers_list; do\n    if which $cc; then\n      USE_CC=\"$cc\" NO_CLEAR=true \"$0\" \"$@\"\n    fi\n  done\nelse\n  if [ \"$EXCLUDE_BENCHMARKS\" = true ]; then\n    for f in `find fatal -name \\*.cpp|grep -v '/.*/.*benchmark/'`; do\n      CC_OPT=\"-O0\" USE_CC=\"$USE_CC\" NO_CLEAR=true ./compile.sh \"$f\" \"$@\"\n    done\n  else\n    for f in `find fatal -name \\*.cpp`; do\n      CC_OPT=\"-O0\" USE_CC=\"$USE_CC\" NO_CLEAR=true ./compile.sh \"$f\" \"$@\"\n    done\n  fi\nfi\n", "num_lines": 26}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 source_file\"\n  exit 1\nfi\n\nif [ -z \"$USE_CC\" ]; then\n  export USE_CC=\"$default_compiler\"\nfi\n\nCC_IS_CLANG=false\nif [ \"${USE_CC:0:5}\" = \"clang\" ]; then\n  CC_IS_CLANG=true\nfi\n\nif [ -z \"$USE_STD\" ]; then\n  export USE_STD=\"c++14\"\nfi\n\nCC_STDLIB=\"\"\nif [ \"$USE_STDLIB\" ]; then\n  CC_STDLIB=\"-stdlib=$USE_STDLIB\"\nfi\n\nfile_name=\"$1\"\nshift\nbase_dir=\"/tmp/.build/$USE_CC/$USE_STD\"\nout_dir=\"$base_dir/`dirname \"$file_name\"`\"\nlink_dir=\"/tmp/.bin\"\n\nif [ ! -d \"$out_dir\" ]; then\n  mkdir -p \"$out_dir\"\nfi\n\nif [ -e \"$link_dir\" ]; then\n  rm -rf \"$link_dir\"\nfi\nln -s \"$base_dir\" \"$link_dir\"\n\nout_binary=\"$out_dir/`basename \"$file_name\" .cpp`\"\n\nlclear\n\nif [ -z \"$CC_OPT\" ]; then\n  CC_OPT=\"-O0\"\nfi\n\nCC_ARGS=\"-o $out_binary $CC_ARGS $CC_OPT -g -pthread -ftemplate-depth-1024 -ftemplate-backtrace-limit=0\"\n\nif [ \"$CC_IS_CLANG\" == true ]; then\n  CC_ARGS=\"$CC_ARGS -ferror-limit=1\"\nfi\n\nif [ \"$PRE_PROC\" = \"true\" ]; then\n  CC_ARGS=\"-E\"\nfi\n\nif [ \"$USE_CCACHE\" = \"true\" ] && [ -e \"$out_binary\" ]; then\n  echo \"using cached version of $file_name: $out_binary\"\nelse\n  echo -n \"started: \"; date\n  if [ \"$BE_LENIENT\" == \"true\" ]; then\n    set +e\n  fi\n  set -x\n  time \"$USE_CC\" $CC_ARGS -Wall -Werror -Wextra \"-std=$USE_STD\" $CC_STDLIB -I . \"$file_name\" 2>&1\n  set +x\n  set -e\n  echo -n \"finished: \"; date\nfi\n\nif [ ! -e \"$out_binary\" ] && [ \"$BE_LENIENT\" != \"true\" ]; then\n  echo \"binary for $file_name was not properly built\"\n  exit 1\nfi\n\nif [ \"$DO_RUN\" = \"true\" ]; then\n  \"$out_binary\" \"$@\"\nfi\n", "num_lines": 85}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\ncc=\"$1\"\nif [ -z \"$cc\" ]; then\n  echo \"Usage: $0 compiler\"\n  exit 1\nfi\n\nif ! which $cc; then\n  echo \"no $cc installed\"\n  exit 1\nfi\n\ncpp_std=\"$2\"\n\nbase_dir=\"/tmp/_build/$cc/$cpp_std\"\n\nif [ -e \"$base_dir\" ]; then\n  rm -rf \"$base_dir\"\nfi\n\necho \"compiler: $cc\"\necho \"standard: $cpp_std\"\n$cc --version\nUSE_CC=\"$cc\" USE_STD=\"$cpp_std\" USE_CCACHE=true NO_CLEAR=true ./validate.sh\n", "num_lines": 30}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. ./scripts.inc\n\nif [ -z \"$USE_STD\" ]; then\n  export USE_STD=\"$(flag_std_cpp14 $default_compiler)\"\nfi\n\nfile_name=\"demo/$1.cpp\"\nshift\n\nDO_RUN=true ./compile.sh \"$file_name\" \"$@\"\n", "num_lines": 13}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\nlclear\n\nfor cc in $full_compilers_list; do\n  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do\n    NO_CLEAR=true USE_CC=\"$cc\" USE_STD=\"$std\" ./compile.sh \"$@\"\n  done\ndone\n", "num_lines": 14}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\nlclear\n\nfor cc in $full_compilers_list; do\n  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do\n    NO_CLEAR=true USE_CC=\"$cc\" USE_STD=\"$std\" ./test.sh \"$@\"\n  done\ndone\n", "num_lines": 14}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. ./scripts.inc\n\nwhile [ \"$1\" ]; do\n  DO_RUN=true ./compile.sh lesson/$1.cpp\n  shift\ndone\n", "num_lines": 9}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\nfor cc in $full_compilers_list; do\n  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do\n    echo \"## contbuild $cc $std\"\n    EXCLUDE_BENCHMARKS=true ./contbuild.sh \"$cc\" \"$std\"\n    echo\n    echo\n  done\ndone\n", "num_lines": 15}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. ./scripts.inc\n\nset -e\n\nif [ -z \"$1\" ]; then\n  echo \"Usage: $0 source_file\"\n  exit 1\nfi\n\nif [ -z \"$USE_STD\" ]; then\n  export USE_STD=\"c++14\"\nfi\n\nexport USE_CC=\"templight\"\n\nfile_name=\"$1\"\nshift\nbase_dir=\"/tmp/_build/$USE_CC/$USE_STD\"\nout_dir=\"$base_dir/`dirname \"$file_name\"`\"\n\nif [ ! -d \"$out_dir\" ]; then\n  mkdir -p \"$out_dir\"\nfi\n\nout_path=\"$out_dir/`basename \"$file_name\" .cpp`\"\nout_binary=\"${out_path}.o\"\nout_prof=\"${out_binary}.memory.trace.pbf\"\n\nlclear\n\necho -n \"started: \"; date\nset -x\ntemplight++ -Xtemplight -profiler -Xtemplight -memory -Xtemplight -ignore-system -o \"$out_binary\" -O2 -Wall -Werror \"-std=$USE_STD\" -I . -c \"$file_name\" 2>&1\nset +x\necho -n \"finished: \"; date\necho \"results written to $out_prof\"\n", "num_lines": 39}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC1113\n#/bin/sh\n\n. ./scripts.inc\n\nset -e\n\nlclear\n\nno_build_flag=\"\"\nfor cc in $short_compilers_list; do\n  NO_CLEAR=true CC_OPT=\"-O0\" USE_CC=\"$cc\" ./validate.sh \"$no_build_flag\" \"$@\"\n  if [ -z \"$no_build_flag\" ]; then\n    no_build_flag=\"nobuild\"\n  fi\ndone\n", "num_lines": 17}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. ./scripts.inc\n\nset -e\n\nif [ \"$1\" ]; then\n  full_compilers_list=\"$@\"\nfi\n\nif [ -z \"$BE_LENIENT\" ]; then\n  export BE_LENIENT=true\nfi\n\nfor cc in $full_compilers_list; do\n  for std in `flag_std_cpp14 $cc` `flag_std_cpp17 $cc`; do\n    echo \"## full build $cc $std\"\n    USE_CC=\"$cc\" USE_STD=\"$std\" USE_CCACHE=true NO_CLEAR=true ./build.sh\n    for f in `find demo -name '*.cpp'`; do\n      USE_CC=\"$cc\" USE_STD=\"$std\" USE_CCACHE=true NO_CLEAR=true ./compile.sh \"$f\"\n    done\n    echo\n    echo\n  done\ndone\n", "num_lines": 26}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. ./scripts.inc\n\nset -e\n\nlclear\n\nif [ -z \"$CC_OPT\" ]; then\n  export CC_OPT='-O0'\nfi\n\nif [ -z \"$1\" ]; then\n  if [ -z \"$USE_CC\" ]; then\n    for cc in $short_compilers_list; do\n      for f in `find . -name \\*_test.cpp`; do\n        USE_CC=\"$cc\" NO_CLEAR=true \"$0\" \"$f\" \"$@\"\n      done\n    done\n  else\n    for f in `find . -name \\*_test.cpp`; do\n      USE_CC=\"$USE_CC\" NO_CLEAR=true \"$0\" \"$f\" \"$@\"\n    done\n  fi\nelif [ -z \"$2\" ]; then\n  test_basename=\"`basename \"$1\" .cpp`\"\n  if ! [ -e \"$1\" ]; then\n    test_name=\"$1\"\n    test_path=\"fatal/test/${test_name}_test.cpp\"\n    if [ -e \"$test_path\" ]; then\n      shift\n      \"$0\" \"$test_path\"\n      exit 0\n    else\n      echo \"test $test_basename not found\">&2\n      exit 1\n    fi\n  fi\n  PRE_PROC=\"$PRE_PROC\" USE_CC=\"$USE_CC\" NO_CLEAR=true DO_RUN=true ./compile.sh \"$1\"\nelif [ \"$1\" ] && [ \"$2\" ]; then\n  while [ \"$1\" ] && [ \"$2\" ]; do\n    dir_name=\"$1\"\n    test_name=\"$2\"\n    shift\n    shift\n    \"$0\" \"fatal/$dir_name/test/${test_name}_test.cpp\"\n  done\nelse\n  echo \"no valid tests given\" >&2\nfi\n", "num_lines": 51}
{"repo_name": "fatal", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC1113\n#/bin/sh\n\n. ./scripts.inc\n\nset -xe\n\nskip_test=false\nskip_build=false\nskip_demo=false\nwhile [ \"$1\" ]; do\n  if [ \"$1\" = \"notest\" ]; then\n    skip_test=true\n  elif [ \"$1\" = \"nobuild\" ]; then\n    skip_build=true\n  elif [ \"$1\" = \"nodemo\" ]; then\n    skip_demo=true\n  fi\n\n  shift\ndone\n\nrun_validation() {\n  cc=\"$1\"\n\n  if ! which \"$cc\"; then\n    return\n  fi\n\n  lclear\n\n  if [ \"$skip_build\" != \"true\" ]; then\n    CC_OPT=\"-O0\" USE_CC=\"$cc\" NO_CLEAR=true ./build.sh\n  fi\n\n  if [ \"$skip_test\" != \"true\" ]; then\n    CC_OPT=\"-O0\" USE_CC=\"$cc\" NO_CLEAR=true ./test.sh\n  fi\n\n  if [ \"$skip_demo\" != \"true\" ]; then\n    for demo in ytse_jam; do\n      echo -n | CC_OPT=\"-O0\" USE_CC=\"$cc\" NO_CLEAR=true ./demo.sh $demo\n    done\n  fi\n}\n\nif [ \"$USE_CC\" ]; then\n  run_validation \"$USE_CC\"\nelse\n  for cc in $full_compilers_list; do\n    run_validation \"$cc\"\n  done\nfi\n", "num_lines": 54}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env nix-shell\n#! nix-shell -i bash shell.nix\n\n# This script sets up the build environment by invoking nix-shell shell.nix\n# and then runs the hadrian executable.\n\nfunction rl {\n    TARGET_FILE=\"$1\"\n\n    cd \"$(dirname \"$TARGET_FILE\")\"\n    TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n\n    # Iterate down a (possible) chain of symlinks\n    while [ -L \"$TARGET_FILE\" ]\n    do\n        TARGET_FILE=\"$(readlink \"$TARGET_FILE\")\"\n        cd \"$(dirname \"$TARGET_FILE\")\"\n        TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n    done\n\n    # Compute the canonicalized name by finding the physical path\n    # for the directory we're in and appending the target file.\n    PHYS_DIR=\"$(pwd -P)\"\n    RESULT=\"$PHYS_DIR/$TARGET_FILE\"\n    echo \"$RESULT\"\n}\n\nabsoluteRoot=\"$(dirname \"$(rl \"$0\")\")\"\necho $absoluteRoot\ncd \"$absoluteRoot\"\n\nhadrian         \\\n  --directory=\"$absoluteRoot/..\" \\\n  \"$@\"\n", "num_lines": 35}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nEXPECTED_VERSION=\"$1\"\n\n# Our shared libraries are currently executable (is that a bug?), so\n# we exclude anything that looks like a shared library\nfor f in `find bindisttest/a/b/c -type f -perm -u+x ! -name '*.so' ! -name '*.dylib' ! -name '*.dll'`\ndo\n    if grep -q '(\"GHC RTS\", \"YES\")' \"$f\"\n    then\n        # Looks like a GHC executable. Is it for the right version?\n        THIS_VERSION=`./$f +RTS --info | grep '\"GHC version\"' | sed -e 's/^ ,(\"GHC version\", \"//' -e 's/\")$//'`\n        if [ \"$THIS_VERSION\" != \"$EXPECTED_VERSION\" ]\n        then\n            echo \"Bad GHC version '$THIS_VERSION' for '$f'\" >&2\n            exit 1\n        fi\n    fi\ndone\n", "num_lines": 20}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nCABAL=cabal\nCABFLAGS=\"--disable-documentation --disable-profiling --disable-library-profiling\"\n\n# It is currently more robust to pass Cabal an absolute path to the project file.\nPROJ=\"$PWD/hadrian/cabal.project\"\n\nset -euo pipefail\n\nif ! [ -f \"$PROJ\" ]; then\n    echo \"Current working directory must be GHC's top-level folder\"\n    exit 2\nfi\n\nif ! type \"$CABAL\" > /dev/null; then\n    echo \"Please make sure 'cabal' is in your PATH\"\n    exit 2\nfi\n\nCABVERSTR=$(\"$CABAL\" --numeric-version)\nCABVER=( ${CABVERSTR//./ } )\n\nif [ \"${CABVER[0]}\" -gt 2 -o \"${CABVER[0]}\" -eq 2 -a \"${CABVER[1]}\" -ge 2 ];\nthen\n    \"$CABAL\" --project-file=\"$PROJ\" new-build $CABFLAGS -j exe:hadrian\n    # use new-exec instead of new-run to make sure that the build-tools (alex & happy) are in PATH\n    \"$CABAL\" --project-file=\"$PROJ\" new-exec  $CABFLAGS    hadrian -- \\\n        --directory \"$PWD\" \\\n        \"$@\"\nelse\n    echo \"Cabal version is too old; you need at least cabal-install 2.2\"\n    exit 2\nfi\n", "num_lines": 35}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# By default on Linux/MacOS we build Hadrian using Cabal\n(. \"hadrian/build.cabal.sh\" \"$@\")\n", "num_lines": 5}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\n# readlink on os x, doesn't support -f, to prevent the\n# need of installing coreutils (e.g. through brew, just\n# for readlink, we use the follownig substitute.\n#\n# source: http://stackoverflow.com/a/1116890\nfunction rl {\n    TARGET_FILE=\"$1\"\n\n    cd \"$(dirname \"$TARGET_FILE\")\"\n    TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n\n    # Iterate down a (possible) chain of symlinks\n    while [ -L \"$TARGET_FILE\" ]\n    do\n        TARGET_FILE=\"$(readlink \"$TARGET_FILE\")\"\n        cd \"$(dirname \"$TARGET_FILE\")\"\n        TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n    done\n\n    # Compute the canonicalized name by finding the physical path\n    # for the directory we're in and appending the target file.\n    PHYS_DIR=\"$(pwd -P)\"\n    RESULT=\"$PHYS_DIR/$TARGET_FILE\"\n    echo \"$RESULT\"\n}\n\nabsoluteRoot=\"$(dirname \"$(rl \"$0\")\")\"\n\nHADRIAN_NIX=YES ${absoluteRoot}/build.stack.sh\n", "num_lines": 34}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\n# readlink on os x, doesn't support -f, to prevent the\n# need of installing coreutils (e.g. through brew, just\n# for readlink, we use the follownig substitute.\n#\n# source: http://stackoverflow.com/a/1116890\nfunction rl {\n    TARGET_FILE=\"$1\"\n\n    cd \"$(dirname \"$TARGET_FILE\")\"\n    TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n\n    # Iterate down a (possible) chain of symlinks\n    while [ -L \"$TARGET_FILE\" ]\n    do\n        TARGET_FILE=\"$(readlink \"$TARGET_FILE\")\"\n        cd \"$(dirname \"$TARGET_FILE\")\"\n        TARGET_FILE=\"$(basename \"$TARGET_FILE\")\"\n    done\n\n    # Compute the canonicalized name by finding the physical path\n    # for the directory we're in and appending the target file.\n    PHYS_DIR=\"$(pwd -P)\"\n    RESULT=\"$PHYS_DIR/$TARGET_FILE\"\n    echo \"$RESULT\"\n}\n\nabsoluteRoot=\"$(dirname \"$(rl \"$0\")\")\"\ncd \"$absoluteRoot\"\n\nstack build --no-library-profiling ${HADRIAN_NIX:+--nix}\n\nstack exec hadrian --              \\\n    --directory \"$absoluteRoot/..\" \\\n    \"$@\"\n", "num_lines": 39}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\ndetect_cpu_count () {\n    if [ \"$CPUS\" = \"\" ]; then\n        # Windows standard environment variable\n        CPUS=\"$NUMBER_OF_PROCESSORS\"\n    fi\n\n    if [ \"$CPUS\" = \"\" ]; then\n        # Linux\n        CPUS=`getconf _NPROCESSORS_ONLN 2>/dev/null`\n    fi\n\n    if [ \"$CPUS\" = \"\" ]; then\n        # FreeBSD\n        CPUS=`getconf NPROCESSORS_ONLN 2>/dev/null`\n    fi\n\n    if [ \"$CPUS\" = \"\" ]; then\n        # nothing helped\n        CPUS=\"1\"\n    fi\n}\n\ndetect_cpu_count\necho \"$CPUS\"\n", "num_lines": 27}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ntarball_dir='ghc-tarballs'\nmissing_files=0\n\n# see #12502\nif test -z \"$FIND\"; then FIND=\"find\"; fi\n\nfail() {\n    echo >&2\n    echo \"$1\" >&2\n    exit 1\n}\n\ndownload_file() {\n    local file_url=\"$1\"\n    local dest_file=\"$2\"\n    local description=\"$3\"\n    local extra_curl_opts=\"$4\"\n    local backup_url=\"$5\"\n    local dest_dir=\"$(dirname $dest_file)\"\n\n    if ! test -f \"${dest_file}\"\n    then\n        local curl_cmd=\"curl -f -L ${file_url} -o ${dest_file} --create-dirs -# ${extra_curl_opts}\"\n        if test -n \"${backup_url}\"; then\n            local curl_cmd_bnk=\"curl -f -L ${backup_url} -o ${dest_file} --create-dirs -# ${extra_curl_opts}\"\n        else\n            local curl_cmd_bnk=\"true\"\n        fi\n\n        if test \"$download\" = \"0\"\n        then\n            echo \"ERROR: Missing ${description}\" >&2\n            echo \"${file_url}\"\n            missing_files=1\n            return\n        else\n            echo \"Downloading ${description} to ${dest_dir}...\"\n            $curl_cmd || echo \"Checking repo.msys2.org instead of Haskell.org...\" && $curl_cmd_bnk || {\n                rm -f \"${dest_file}\"\n                fail \"ERROR: Download failed.\"\n                exit 1\n            }\n        fi\n    fi\n\n    local sig_file=\"${dest_file}.sig\"\n    if test \"$sigs\" = \"1\" -a ! -f \"$sig_file\"\n    then\n        echo \"Downloading ${description} (signature) to ${dest_dir}...\"\n        local curl_cmd=\"curl -f -L ${file_url}.sig -o ${sig_file} --create-dirs -# ${extra_curl_opts}\"\n        if test -n \"${backup_url}\"; then\n            local curl_cmd_bnk=\"curl -f -L ${backup_url} -o ${sig_file} --create-dirs -# ${extra_curl_opts}\"\n        else\n            local curl_cmd_bnk=\"true\"\n        fi\n        $curl_cmd || echo \"Checking repo.msys2.org instead of Haskell.org...\" && $curl_cmd_bnk || {\n                rm -f \"${dest_file}.sig\"\n                fail \"ERROR: Download failed.\"\n                exit 1\n            }\n    fi\n\n    if test \"$verify\" = \"1\"\n    then\n        grep \"${dest_file}$\" mk/win32-tarballs.md5sum | md5sum --quiet -c - ||\n            fail \"ERROR: ${description} appears to be corrupted, please delete it and try again.\"\n    fi\n}\n\ndownload_mingw() {\n    local mingw_base_url_primary=\"https://downloads.haskell.org/~ghc/mingw\"\n    local mingw_base_url_secondary=\"http://repo.msys2.org/mingw\"\n\n    if test \"$mingw_arch\" = \"sources\"\n    then\n        mingw_url_tmp=`echo \"$1\" | sed -e 's/-any\\.pkg\\.tar\\.xz/\\.src\\.tar\\.gz/' \\\n                                       -e 's/-sources-/-/' \\\n                                       -e 's/-libwinpthread-git-/-winpthreads-git-/' `\n        local mingw_url=\"${mingw_base_url_primary}/${mingw_url_tmp}\"\n        local mingw_url_backup=\"${mingw_base_url_secondary}/${mingw_url_tmp}\"\n    else\n        local mingw_url=\"${mingw_base_url_primary}/$1\"\n        local mingw_url_backup=\"${mingw_base_url_secondary}/$1\"\n    fi\n\n    local mingw_toolchain=\"$(basename $mingw_url)\"\n    local mingw_w64=\"${tarball_dir}/${tarball_dest_dir}/${mingw_toolchain}\"\n\n    download_file \"${mingw_url}\" \"${mingw_w64}\" \"${mingw_toolchain}\" \"\" \"${mingw_url_backup}\"\n\n    # Mark the tree as needing updates by deleting the folder\n    if test -d inplace/mingw && test inplace/mingw -ot \"$mingw_w64\" ; then\n        echo \"In-tree MinGW-w64 tree requires updates...\"\n        rm -rf inplace/mingw\n    fi\n}\n\ndownload_tarballs() {\n    local package_prefix=\"mingw-w64\"\n    local format_url=\"/${mingw_arch}/${package_prefix}-${mingw_arch}\"\n\n    download_mingw \"${format_url}-crt-git-5.0.0.4795.e3d96cb1-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-winpthreads-git-5.0.0.4850.d1662dc7-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-headers-git-5.0.0.4966.1eee2140-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-libwinpthread-git-5.0.0.4850.d1662dc7-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-zlib-1.2.8-9-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-isl-0.18-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-mpfr-3.1.6-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-gmp-6.1.2-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-binutils-2.29.1-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-libidn2-2.0.4-1-any.pkg.tar.xz\"\n    download_mingw \"${format_url}-gcc-7.2.0-1-any.pkg.tar.xz\"\n\n    # Upstream is unfortunately quite inconsistent in naming\n    if test \"$mingw_arch\" != \"sources\"; then\n        download_mingw \"${format_url}-mpc-1.0.3-2-any.pkg.tar.xz\"\n        download_mingw \"${format_url}-gcc-libs-7.2.0-1-any.pkg.tar.xz\"\n        download_file \"https://downloads.haskell.org/~ghc/mingw/ghc-perl-1.tar.gz\" \"ghc-tarballs/perl/ghc-perl-1.tar.gz\" \"Windows Perl binary distributions\" \"\" \"\"\n    else\n        local format_url=\"${mingw_base_url}/${mingw_arch}/${package_prefix}\"\n        download_mingw \"${format_url}-i686-mpc-1.0.3-2.src.tar.gz\"\n        download_mingw \"${format_url}-x86_64-mpc-1.0.3-2.src.tar.gz\"\n    fi\n\n    if ! test \"$missing_files\" = \"0\"\n    then\n        exit 2\n    fi\n}\n\ndownload_i386() {\n    mingw_arch=\"i686\"\n    tarball_dest_dir=\"mingw-w64/x86\"\n    download_tarballs\n}\n\ndownload_x86_64() {\n    mingw_arch=\"x86_64\"\n    tarball_dest_dir=\"mingw-w64/x86_64\"\n    download_tarballs\n}\n\ndownload_sources() {\n    mingw_arch=\"sources\"\n    tarball_dest_dir=\"mingw-w64/sources\"\n    download_tarballs\n}\n\nsync_binaries_and_sources() {\n    gpg --recv-key  5F92EFC1A47D45A1\n\n    # ensure sources are downloaded\n    sigs=1\n    download_i386\n    download_x86_64\n    verify=0\n    download_sources\n\n    for f in $($FIND ghc-tarballs/mingw-w64 -iname '*.sig'); do\n        echo \"Verifying $f\"\n        gpg --verify $f\n    done\n\n    md5sum `$FIND ghc-tarballs -type f -a -not -iname '*.sig'` >| mk/win32-tarballs.md5sum\n    chmod -R ugo+rX ghc-tarballs\n\n    rsync -av ghc-tarballs/mingw-w64/* downloads.haskell.org:public_html/mingw\n    for f in $($FIND ghc-tarballs/mingw-w64); do\n        curl -XPURGE http://downloads.haskell.org/~ghc/mingw/$f\n    done\n}\n\nshow_hashes_for_binaries() {\n    $FIND ghc-tarballs/ -iname \"*.*\" | xargs md5sum | grep -v \"\\.sig\" | sed -s \"s/\\*//\"\n}\n\nusage() {\n    echo \"$0 - Download GHC mingw toolchain tarballs\"\n    echo\n    echo \"Usage: $0 <action> [<arch>]\"\n    echo\n    echo \"Where <action> is one of,\"\n    echo \"\"\n    echo \"    download     download the necessary tarballs for the given architecture\"\n    echo \"    fetch        download the necessary tarballs for the given architecture but doesn't verify their md5.\"\n    echo \"    verify       verify the existence and correctness of the necessary tarballs\"\n    echo \"    hash         generate md5 hashes for inclusion in win32-tarballs.md5sum\"\n    echo \"    sync         upload packages downloaded with 'fetch mirror' to haskell.org\"\n    echo \"\"\n    echo \"and <arch> is one of i386, x86_64,all or mirror (which includes sources)\"\n}\n\ncase $1 in\n    download)\n        download=1\n        verify=1\n        sigs=0\n        ;;\n    fetch)\n        download=1\n        verify=0\n        ;;\n    verify)\n        download=0\n        verify=1\n        ;;\n    sync)\n        download=1\n        verify=0\n        sync=1\n        ;;\n    hash)\n        show_hashes_for_binaries\n        exit 1\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\ncase $2 in\n    i386)\n        download_i386\n        ;;\n    x86_64)\n        download_x86_64\n        ;;\n    all)\n        download_i386\n        download_x86_64\n        ;;\n    mirror)\n        sigs=1\n        download_i386\n        download_x86_64\n        verify=0\n        download_sources\n        show_hashes_for_binaries\n        ;;\n    *)\n        if test \"$sync\" = \"1\"; then\n            sync_binaries_and_sources\n        else\n            usage\n            exit 1\n        fi\n        ;;\nesac\n", "num_lines": 252}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n\n# something like this...\nfor i in mod*.hs; do \n  if ! test -f ${i%.hs}.output; then \n     echo \"test('${i%.hs}', normal, compile, [''])\"\n  else if grep error ${i%.hs}.output >/dev/null; then\n     echo \"test('${i%.hs}', normal, compile_fail, [''])\"\n  else \n     echo \"test('${i%.hs}', normal, compile, [''])\"\n  fi fi\ndone\n", "num_lines": 13}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -xe\n\n# Runs ghc-stage2 with GHCi settings that allow GHC to be loaded and run in the\n# interpreter. Options provided on the command-line will be passed directly to\n# the GHCi invocation.\n\n# Note that this script is intended to be run from the root of the GHC repo,\n# like this:\n\n# ./utils/ghc-in-ghci/run.sh\n\n# This is substantially faster than doing an actual compile, and so can aid in\n# tighter development iterations. It can be made even faster by specifying \"-jN\"\n# for parallelism. Typically choosing an N value close to the number of logical\n# CPU cores you have leads to faster loads. Here's how to specify -j:\n\n# ./utils/ghc-in-ghci/run.sh -j4\n\n# The script will also run `:load Main`, to load GHC's main module. After that,\n# running `main` will run an inner GHCi, because there is a default `:set args\n# --interactive ...`. To override this, use `:set args ...` or `:main ...`.\n\n# If you don't want to wait for `:load Main`, since you want to load some other\n# module, then you can use `Ctrl+C` to cancel the initial load.\n\n# Look in two common locations for a GHC installation (the results of using\n# the make- and Hadrian-based build systems, respectively).\nif [ -d ./inplace/lib ]; then\n  GHC_BIN=./inplace/bin/ghc-stage2\n  _GHC_TOP_DIR=./inplace/lib\nelif [ -d ./_build/stage1/lib ]; then\n  GHC_BIN=./_build/stage1/bin/ghc\n  _GHC_TOP_DIR=./_build/stage1/lib\nelse\n  echo \"Could not find GHC installation\"\n  exit 1\nfi\n\nexec ${GHC_BIN} \\\n    --interactive \\\n    -ghci-script ./utils/ghc-in-ghci/settings.ghci \\\n    -ghci-script ./utils/ghc-in-ghci/load-main.ghci \\\n    +RTS -A128m -RTS \\\n    \"$@\"\n", "num_lines": 45}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# llvm-target generator\n#\n# Author: Moritz Angermann <moritz.angermann@gmail.com>\n#\n# This file generates the `llvm-targets` file, which contains the\n# data-layout, cpu and attributes for the target.  This is done by\n# querying `clang` for the data-layout, cpu and attributes based\n# on a given target.\n#\n# To utilize it run it as\n#\n#  $ ./gen-data-layout.sh > llvm-targets\n#\n# Add missing targets to the list below to have them included in\n# llvm-targets file.\n\n# Target sets for which to generate the llvm-targets file\nTARGETS=(\n    # Windows x86\n    \"i386-unknown-windows\" \"i686-unknown-windows\" \"x86_64-unknown-windows\"\n\n    # Linux ARM\n    \"arm-unknown-linux-gnueabihf\" \"armv6-unknown-linux-gnueabihf\" \"armv6l-unknown-linux-gnueabihf\"\n    \"armv7-unknown-linux-gnueabihf\" \"armv7a-unknown-linux-gnueabi\" \"armv7l-unknown-linux-gnueabihf\"\n    \"aarch64-unknown-linux-gnu\" \"aarch64-unknown-linux\"\n    # Linux x86\n    \"i386-unknown-linux-gnu\" \"i386-unknown-linux\" \"x86_64-unknown-linux-gnu\" \"x86_64-unknown-linux\"\n    # Linux Android\n    \"armv7-unknown-linux-androideabi\" \"aarch64-unknown-linux-android\"\n    # Linux ppc64le\n    \"powerpc64le-unknown-linux\"\n\n    # FreeBSD amd64\n    \"amd64-portbld-freebsd\"\n    \"x86_64-unknown-freebsd\" # See #15718\n\n    # QNX\n    \"arm-unknown-nto-qnx-eabi\"\n\n    # macOS\n    \"i386-apple-darwin\" \"x86_64-apple-darwin\"\n    # iOS\n    \"armv7-apple-ios arm64-apple-ios\" \"i386-apple-ios x86_64-apple-ios\"\n\n    # FreeBSD ARM\n    \"aarch64-unknown-freebsd\" \"armv6-unknown-freebsd-gnueabihf\" \"armv7-unknown-freebsd-gnueabihf\"\n)\n\n# given the call to clang -c11 that clang --target -v generates,\n# parse the -target-cpu <CPU> and -target-feature <feature> from\n# the output.\nfunction get_cpu_and_attr() {\n    # echo $@\n    while [ \"$#\" -gt 0 ]; do\n        case \"$1\" in\n            -target-cpu) CPU=$2; shift 2;;\n            -target-feature)\n                # translate clang to opt/llc target features\n                case \"$2\" in\n                    # we don't have support in GHC for proper soft-float.\n                    # if we extend the `llvm-target` file to contain two\n                    # additional columns for opt and llc flags, we could\n                    # pass -float-abi=soft; However ghc will use float\n                    # registers unconditionally on arm, and as such true\n                    # soft float with the registerised llvm backend is\n                    # currently not possible.\n                    +soft-float-abi) shift 2;;\n                    *) ATTR+=(\"$2\"); shift 2;;\n                esac\n                ;;\n            *) shift 1;;\n        esac\n    done\n}\n\n# first marker to discriminate the first line being outputted.\nFST=1\n# a dummy file to use for the clang invocation.\nFILE=_____dummy.c\ntouch $FILE\n\nfor target in \"${TARGETS[@]}\"; do\n    # find the cpu and attributes emitted by clang for the given $target\n    CPU=\"\"\n    ATTR=()\n    args=$(clang --target=$target -S $FILE -o /dev/null -v 2>&1 |grep $FILE)\n    get_cpu_and_attr $args\n\n    # find the data-layout from the llvm code emitted by clang.\n    dl=$(clang --target=$target -S $FILE -emit-llvm -o -|grep datalayout |awk -F\\  '{ print $4 }')\n    # GNU and Apple/LLVM can't agree on the aarch64 target.\n    # aarch64-apple-ios, is understood by autotools but not by LLVM.\n    # arm64-apple-ios, is understood by LLVM, but not by autotools.\n    #\n    # therefore, while we query clang with arm64-apple-ios, we put\n    # aarch64-apple-ios into the llvm-target list, as that is what\n    # we have to configure ghc with --target with anyway.  Also we\n    # want to retain the GNU naming for compatibility with libraries\n    # that use autotools.\n    if [ \"$target\" == \"arm64-apple-ios\" ]; then\n       target=\"aarch64-apple-ios\"\n    fi\n    if [ $FST -eq 1 ]; then\n        echo \"[(\\\"${target}\\\", ($dl, \\\"$CPU\\\", \\\"${ATTR[*]}\\\"))\"\n        FST=0\n    else\n        echo \",(\\\"${target}\\\", ($dl, \\\"$CPU\\\", \\\"${ATTR[*]}\\\"))\"\n    fi\ndone\nrm $FILE\necho \"]\"\n", "num_lines": 114}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nmkdir -p ${1+\"./$@\"}\n\n", "num_lines": 5}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\napt-get update\napt-get build-dep -y ghc\n", "num_lines": 4}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nyum update -y\nyum install -y glibc-devel ncurses-devel gmp-devel autoconf automake libtool \\\n gcc make perl python ghc git\n", "num_lines": 5}
{"repo_name": "fbghc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script will verify that the packages in ghc,\n# correspond to packages on hackage.\nrm -fR ghc-packages hackage-packages package-diffs\nmkdir -p ghc-packages hackage-packages package-diffs\n# We'll skip Cabal and tarballs, while looking only at packages in libraries\n# that we reference as gitmodules.\nfor lib in $(git submodule status|grep libraries|grep -v tarballs|grep -v Cabal|awk -F\\  '{ print $2 }'); do\n    (cd $lib && cabal new-sdist -o ../../ghc-packages);\ndone\n\nfor pkg in $(cd ghc-packages && ls *.tar.gz); do\n    PKG=${pkg%%.tar.gz}\n    (cd hackage-packages && cabal get --pristine ${PKG})\n    (cd hackage-packages/${PKG} && git init && git add . && git commit -q -m \"hackage packages\" && rm -fR *)\n    (cd hackage-packages && tar xzf ../ghc-packages/$pkg)\n    (cd hackage-packages/${PKG} && git -c core.fileMode=false diff > ../$PKG.patch)\ndone\nfind hackage-packages -name \"*.patch\" -not -empty -type f -print -exec false {} +\n", "num_lines": 21}
{"repo_name": "fbhaddock", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Mini-driver for Haddock\n\n# needs the following variables:\n#\tHADDOCKLIB\n#\tHADDOCKBIN\n\n$HADDOCKBIN --lib $HADDOCKLIB ${1+\"$@\"}\n", "num_lines": 8}
{"repo_name": "fbhaddock", "repo_creator": "facebook", "programming_language": "Shell", "code": "# mini script for building the relocatable Windows binary distribution.\n#\n#    sh build-windows-dist.sh\n#\n# NB. the Cabal that shipped with GHC 6.6 isn't enough for this, because it\n# is missing this patch:\n# \n# Fri Oct 13 11:09:41 BST 2006  Simon Marlow <simonmar@microsoft.com>\n#   * Fix getDataDir etc. when bindir=$prefix\n#\n# So you need to use a more recent Cabal.  GHC 6.6 is fine for building the\n# package, though.\n\nghc --make Setup\n./Setup configure --prefix=`pwd`/install --bindir='$prefix' --libdir='$prefix' --datadir='$prefix'\n./Setup build\n./Setup install\necho Now zip up `pwd`/install as \"haddock-<version>-Win32.zip\"\n", "num_lines": 19}
{"repo_name": "fbhaddock", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Put the Happy-generated .hs files in the right place in the source dist.\nset -e\nrm -f dist/haddock-*.tar.gz\nrm -rf dist/haddock-*/\n./Setup sdist\ncd dist\ntar xvzf haddock-*.tar.gz\ncd haddock-*/\nmkdir dist\nmkdir dist/build\nmv haddock dist/build\ncd ..\ntar cvzf haddock-*.tar.gz haddock-*/\n\n# Steps for doing a release:\n#  * Update version number in .cabal, doc/haddock.xml\n#  * Update CHANGES\n#  * Source:\n#    - do the above\n#    - upload the dist to haskell.org:haddock/dist/${version}\n#    - scp CHANGES haskell.org:haddock/CHANGES.txt\n#  * Binaries:\n#    - build the Windows binary zip (see build-windows-dist.sh)\n#    - scp haddock-<version>-Win32.zip haskell.org:haddock/dist\n#  * Documentation:\n#    - cd doc\n#    - make html\n#    - mv haddock haddock-html\n#    - tar cvzf haddock-doc-html-${version}.tar.gz haddock-html\n#    - scp haddock-doc-html-${version}.tar.gz www.haskell.org:../haskell/haddock/doc\n#    - ssh haskell.org\n#        - cd haddock/doc\n#        - tar xvzf haddock-doc-html-${version}.tar.gz\n#        - rm -rf html-OLD\n#        - mv html html-OLD && mv haddock-html html\n#  * Update the web page (~/darcs/www/haddock/index.html), and push it\n", "num_lines": 37}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# FBOSS is now built using fbcode_builder. Thus, just invoke fbcode_builder\n# getdeps.py to build fboss here.\n\nTOOLCHAIN_DIR=/opt/rh/devtoolset-8/root/usr/bin\nif [[ -d \"$TOOLCHAIN_DIR\" ]]; then\n    PATH=\"$TOOLCHAIN_DIR:$PATH\"\nfi\n\nFBOSS_DIR=$(dirname \"$0\")\nGETDEPS_PATHS=(\n    \"$FBOSS_DIR/build/fbcode_builder/getdeps.py\"\n    \"$FBOSS_DIR/../../opensource/fbcode_builder/getdeps.py\"\n)\nfor getdeps in \"${GETDEPS_PATHS[@]}\"; do\n    if [[ -x \"$getdeps\" ]]; then\n        exec \"$getdeps\" build fboss --current-project fboss \"$@\"\n    fi\ndone\necho \"Could not find getdeps.py!?\" >&2\nexit 1\n", "num_lines": 23}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n$1 --version | grep \"Package Version\"\n", "num_lines": 4}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nprefixtext() {\n  infile=$1\n  prefix=\"$2\"\n  echo \"${prefix}// SOURCE: $infile\"\n  echo \"${prefix}R\\\"__CONFIG__(\"\n  while IFS= read -r line;\n  do\n    echo \"${prefix}$line\"\n  done < \"$infile\"\n  echo -n \"${prefix})__CONFIG__\\\"\"\n}\n\ngencpp() {\n  inf=$1\n  outf=$2\n  namespace=$3\n  func=$4\n  if [ ! -e \"$inf\" ]; then\n    echo \"$inf does not exist\"\n    exit 1\n  fi\n  {\n    echo \"// Copyright 2021-present Facebook. All Rights Reserved.\"\n    echo \"// THIS FILE IS AUTOGENERATED DO NOT MODIFY\"\n    echo \"// GENERATED BY: \\`$0 $*\\`\"\n    echo \"#include <string>\"\n    echo \"#include <vector>\"\n    echo \"namespace $namespace {\"\n    if [ -d \"$inf\" ]; then\n      echo \"const std::vector<std::string> $func() {\"\n      echo \"  return {\"\n      for f in \"$inf\"/*.json; do\n        prefixtext \"$f\" \"    \"\n        echo \",\"\n      done\n      echo \"  };\"\n    else\n      echo \"const std::string $func() {\"\n      echo -n \"  return \"\n      prefixtext \"$inf\" \"  \"\n      echo \";\"\n    fi\n    echo \"}\"\n    echo \"}\"\n  } > \"$outf\"\n}\n\nINSTALL_DIR=\"\"\nfor i in \"$@\"; do\n  case $1 in\n    --install_dir=*)\n      INSTALL_DIR=\"${i#*=}\"\n      shift # past argumen=value\n      ;;\n    *)\n      echo \"Unknown positional $1\"\n      exit 1\n      ;;\n  esac\ndone\n\nSRC_DIR=$(dirname \"${BASH_SOURCE[0]}\")\nCONFIG_DIR=\"./configs\"\nif [ -d $CONFIG_DIR ]; then\n  echo \"CONFIG_DIR=$CONFIG_DIR\"\nelif [ -d \"${SRC_DIR}/configs\" ]; then\n  CONFIG_DIR=\"${SRC_DIR}/configs\"\n  echo \"CONFIG_DIR=$CONFIG_DIR\"\nelse\n  echo \"ERROR: $0 needs to be executed in project root containing configs\"\n  exit 1\nfi\nOUTPUT_DIR=\".\"\nif [ -n \"$INSTALL_DIR\" ]; then\n  OUTPUT_DIR=$INSTALL_DIR\nfi\n\nNAMESPACE=\"rackmonsvc\"\ngencpp \"$CONFIG_DIR/interface/rackmon.conf\" \"$OUTPUT_DIR/GeneratedRackmonInterfaceConfig.cpp\" \"$NAMESPACE\" getInterfaceConfig\ngencpp \"$CONFIG_DIR/interface/rackmon_pls.conf\" \"$OUTPUT_DIR/GeneratedRackmonPlsConfig.cpp\" \"$NAMESPACE\" getRackmonPlsConfig\ngencpp \"$CONFIG_DIR/register_map\" \"$OUTPUT_DIR/GeneratedRackmonRegisterMapConfig.cpp\" \"$NAMESPACE\" getRegisterMapConfig\n", "num_lines": 84}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2022-present Facebook. All Rights Reserved.\n\n# contruct the RPM remote server URL\nKERNEL_VER=$(uname -r)\nYUM_KERNEL_DIR=$(echo \"${KERNEL_VER}\" | cut -d '_' -f 1,2)\nRPM_REMOTE_SERVER_URL=\"https://yum.rftw0.facebook.com/yum/centos/kernel/${YUM_KERNEL_DIR}/x86_64/RPMS/\"\n\nstop_chef(){\n  # Stopping chef to perform kernel upgrades. Default is at least 1 hour\n\n  /usr/facebook/ops/scripts/chef/stop_chef_temporarily -r \"To perform BSP Kmods upgrade on Darwin platform\"\n\n}\n\nstop_platform_services(){\n  # stop rackmon\n  systemctl stop rackmon.service\n\n  # stop fan_service\n  systemctl stop fan_service.service\n\n  # stop sensor_service\n  systemctl stop sensor_service.service\n\n  # stop data_corral_service\n  systemctl stop data_corral_service.service\n\n}\n\nfan_speed_increase(){\n  # since fan_service is not running to dynamically control the fan speed\n  # so  we will increase the fan_speed to 70% to prevent the switch from overheating\n\n  bash set_fan_speed.sh 70\n\n}\n\nstop_forwarding_stack_services(){\n  # stop QSFP service\n  systemctl stop qsfp_service\n\n  # stop agent\n  systemctl stop wedge_agent\n\n}\n\nstop_watchdog(){\n  # stop watchdog\n  # watchdog timer will be stopped automatically when watchdog service\n  # is stopped.\n  systemctl stop watchdog\n\n}\n\nunload_bsp_kmods(){\n  # unload the I2C client drivers\n  modprobe -r rook_fan_cpld blackhawk_cpld i2c_dev_sysfs amax5970 aslg4f4527\n\n  # unload SCD and SCD subdevice drivers\n  modprobe -r scd_smbus scd_leds scd_watchdog scd\n}\n\n\ninstall_bsp_kmods(){\n  # Remove the old RPM\n  KMOD_RPM_VER=\"$1\"\n  old_rpm=$(rpm -qa | grep arista_darwin_bsp)\n  rpm -e \"$old_rpm\"\n\n  # Pull the Latest kmod rpm for the current running kernel version\n\n  # Get the context of the remote server into a file\n  wget \"${RPM_REMOTE_SERVER_URL}\" -q -O - | grep \"arista_darwin\" > /tmp/remote_server_output.txt\n\n  # remove the .x86_64.rpm since it won't be part of the rpm command\n  sed -i -e 's/.x86_64.rpm//' /tmp/remote_server_output.txt\n\n  # Sort the content of the file per date (both calendar date and time) and pull the rpm\n  # for the sorting one k2 full the column with the day, month, year first\n  # then  k3 pick the column with the hours and mins\n  # then the most recent rpm file will be at the bottom\n  rpm=$(sort -k2 -k3 /tmp/remote_server_output.txt | cut -d '>' -f 1 | cut -d '\"' -f 2 | tail -1)\n\n  #remove the tmp file since it's no longer needed\n  rm -rf /tmp/remote_server_output.txt\n\n  dnf install -y \"${rpm}\"\n}\n\nreload_bsp_kmods(){\n  # loading scd driver should be good enough: all the relevant scd-* and\n  # I2C client drivers should be loaded automatically when the corresponding\n  # devices are created.\n  modprobe scd\n}\n\nstart_watchdog(){\n  # restart the watchdog service\n  systemctl start watchdog\n\n}\n\nstart_forwarding_stack_services(){\n  # start wedge_agent\n  systemctl start wedge_agent\n\n  # start qsfp service\n  systemctl start qsfp_service\n\n}\n\nstart_platform_services(){\n  # start data_corral\n  systemctl start data_corral_service.service\n\n  # start sensor_service\n  systemctl start sensor_service.service\n\n  # start fan_service\n  systemctl start fan_service.service\n\n  # start rackmon\n  systemctl start rackmon.service\n\n}\n\n# start chef\nstart_chef(){\n  # resume chef operation\n  rm -rf /var/chef/cron.default.override\n\n}\n\n\n# Drain the swich since Kernel upgrade is being treated as disruptive\n# TODO: Figure out what is the command to drain switch on Darwin\n\n# stop chef so that it doesn't restart platform services\nstop_chef\n\n# Stop platform services\nstop_platform_services\n\n# increase fan_speed\nfan_speed_increase\n\n# stop forwarding stack services\nstop_forwarding_stack_services\n\n# stop watchdog\nstop_watchdog\n\n# unload bsp kernel Modules\nunload_bsp_kmods\n\n# install new bsp kmods\ninstall_bsp_kmods \"$KMOD_RPM_VER\"\n\n# reload bsp_kmods\nreload_bsp_kmods\n\n# start watchdog service\nstart_watchdog\n\n# start fowarding stack services\nstart_forwarding_stack_services\n\n# start platform services\nstart_platform_services\n\n# start chef\nstart_chef\n\n# undrain the switch\n# TODO: Figure out the command to undrain the switch\n", "num_lines": 177}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nusage() {\n  echo \"Usage: $0 <PWM_PERCENT> [FAN_TRAY] \"\n  echo \"<PWM_PERCENT> : From 0 to 100 \"\n  echo \"[FAN_TRAY] : 1, 2, 3, 4, 5 or 6.\"\n  echo \"If no FAN_TRAY is specified, all FANs will be programmed\"\n}\n\nFANCPLD=\"/run/devmap/sensors/FAN_CPLD\"\nSLGCONTROLLER=\"/run/devmap/sensors/FS_FAN_SLG4F4527\"\n\nset -e\n\n# Make sure we only have 1 or 2 arguments\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# Also make sure that percent value is really between 0 and 100\nif [ \"$1\" -lt 0 ] || [ \"$1\" -gt 100 ]; then\n    echo \"PWM_PERCENT $1: should be between 0 and 100\"\n    exit 1\nfi\n\n# Read FAN_TRAY value from user argument.\n# If no FAN_TRAY is given, configure all FANs\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4 5 6\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 7 ]; then\n        echo \"Fan $2: should be between 1 and 6\"\n        exit 1\n    fi\n    FAN_UNIT=\"$2\"\nfi\n\n# Convert input (0-100%) to PWM (0-255)\n# Multiple by 2.5\nstep=\"$(printf '%.*f' 0 \"$((255 * $1 / 100))\")\"\n\nfor unit in ${FAN_UNIT}; do\n    if [ \"$unit\" -le 5 ]; then\n        pwm=\"$FANCPLD/pwm${unit}\"\n        echo \"$step\" > \"${pwm}\"\n        echo \"$step will be set to ${pwm} !!!!\"\n        echo \"Successfully set system fan ${unit} speed to $1%\"\n    else\n        pwm=\"$SLGCONTROLLER/pwm\"\n        # Need to invert PWM setting for SLG because written value is lower duty cycle\n        step=\"$(printf '%.*f' 0 \"$((255 * (100 - $1) / 100))\")\"\n        echo \"$step\" > \"${pwm}\"\n        echo \"$step will be set to ${pwm} !!!!\"\n        echo \"Successfully set fanspinner fan speed to $1%\"\n    fi\ndone\n", "num_lines": 58}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsudo yum install -y git gcc gcc-c++ python-devel rh-python36 openssl*\nsudo yum install -y centos-release-scl-rh devtoolset-8-toolchain\nsudo yum group install \"Development Tools\" -y\nsudo yum install rpm-build rpmdevtools -y\nsudo yum --enablerepo=extras install epel-release -y\nsudo yum install python-pip -y\nsudo pip install gitpython\nsudo yum install openssl-devel -y\n", "num_lines": 11}
{"repo_name": "fboss", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsudo apt-get update\nsudo apt-get install git vim gcc m4 bison flex libssl-dev python-dev pkg-config build-essential zlib1g-dev -y\n", "num_lines": 5}
{"repo_name": "FBRetainCycleDetector", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n\nset -eu\n\nxcodebuild -project FBRetainCycleDetector.xcodeproj \\\n           -scheme FBRetainCycleDetector \\\n           -destination \"platform=iOS Simulator,name=iPhone 8\" \\\n           -sdk iphonesimulator \\\n           build test\n", "num_lines": 13}
{"repo_name": "FBRetainCycleDetector", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n\nset -x\nset -e\n\ncd -- \"$(dirname -- \"$0\")\"\n\n# Download data in temp dir.\nrcd_fishhook_path=\"$(pwd)/rcd_fishhook/\"\ngit_fishhook_path=$(mktemp -d /tmp/rcd-fishhook.XXXXXX)\nif [ $? -ne 0 ]; then\n    echo \"$0: Can't create temp file, exiting...\"\n    exit 1\nfi\ncd -- \"$git_fishhook_path\"\ngit clone 'git@github.com:facebook/fishhook.git'\n\n# Update repo.\ncd \"${rcd_fishhook_path}\"\nrm -- rcd_fishhook.* || true\ncp -r \"${git_fishhook_path}\"/fishhook/* .\nrm fishhook.podspec\n\nsed -i '' 's/fishhook_h/rcd_fishhook_h/g' fishhook.*\nsed -i '' 's/fishhook\\.h/rcd_fishhook\\.h/g' fishhook.*\nsed -i '' 's/struct rebinding/struct rcd_rebinding/g' fishhook.*\nsed -E -i '' 's/(rebind_symbols(_image)?|prepend_rebindings|perform_rebinding_with_section)\\(/rcd_\\1\\(/g' fishhook.*\n\nmv fishhook.h rcd_fishhook.h\nmv fishhook.c rcd_fishhook.c\n\n# Clean up.\nrm -rf \"$git_fishhook\"\n", "num_lines": 37}
{"repo_name": "fbt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#######################\n# Script to compare strings collected by the bleeding edge version of\n# fbt library (babel-plugin-fbt@0.21.0) with strings collected by a previous\n# version.\n#\n# Usage:\n#   - While you are still on old babel-plugin-fbt, run `yarn fbt-collect` to\n#     collect legacy strings\n#   - Upgrade to babel-plugin-fbt@~0.21.0 in your package.json and run `yarn install`\n#   - Run `yarn fbt-collect` to collect new strings\n#   - Run `./categorize_new_strings.sh <legacy_srings.json> <new_strings.json> [--return-new-hash-key]`\n#\n#######################\n\nset -euo pipefail\n\ninputFileLegacy=$1\ninputFileNew=$2\noptionReturnPhrasesWithNewHashKey=\"\"\nif [[ $# -gt 2 ]]; then\n  optionReturnPhrasesWithNewHashKey=$3\nfi\n\ntempFileLegacy=$inputFileLegacy.temp.json\ntempFileNew=$inputFileNew.temp.json\n\njq '.phrases' \"$inputFileLegacy\" | jq '.|=sort_by(.filepath, .line_beg, .col_beg)' --sort-keys >& \"$tempFileLegacy\"\njq '.phrases' \"$inputFileNew\" | jq '.|=sort_by(.filepath, .line_beg, .col_beg)' --sort-keys >& \"$tempFileNew\"\n\nnode categorizeNewStrings.js \\\n  \"$tempFileLegacy\" \"$tempFileNew\" \"$optionReturnPhrasesWithNewHashKey\" \\\n  > \"new_strings_by_category.json\" && rm \"$tempFileLegacy\" \"$tempFileNew\"\n", "num_lines": 34}
{"repo_name": "fbthrift", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nDIR=$( dirname \"${BASH_SOURCE[0]}\" )\n\nfor x in \"$DIR\"/*.mustache \"$DIR\"/**/*.mustache; do\n  ruby \"$DIR/validate.rb\" \"$x\" || exit;\ndone\n", "num_lines": 23}
{"repo_name": "fbthrift", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script exists to generate the test_key.pem, test_cert.pem,\n# ca-key.pem, and ca-cert.pem files.  It shouldn't really ever be run again\n# until the year 2041 (when these certs expire)., unless you need to change\n# or update attributes of the certificate (Common Name, Organization,\n# whatever).\n\nset -e\n\nDAYS=10000\n\n# Generate Certificate Authority Key\nopenssl genrsa -out ca-key.pem 2048\n\n# Generate Self-Signed Certificate Authority Cert\nopenssl req -x509 -new -nodes \\\n    -key ca-key.pem \\\n    -days ${DAYS} \\\n    -out ca-cert.pem \\\n    -subj '/C=US/O=Thrift/CN=Thrift Certificate Authority'\n\n# CA serial number\necho 00000009 > ca-cert.srl\n\nfunction generateCert() {\n    cat > conf.tmp <<EOF\nprompt = no\n[req]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n\n[req_distinguished_name]\ncountryName = US\nstateOrProvinceName = Ohio\nlocalityName = Hilliard\ncommonName = Asox Company\n\n[v3_req]\n# Extensions to add to a certificate request\n# basicConstraints = CA:FALSE\n# keyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = IP:$3, IP:$4\nEOF\n\n    # Generate the test key\n    openssl genrsa -out $1 2048\n\n    # Generate the test key certificate request\n    openssl req -new -nodes \\\n\t-config conf.tmp \\\n\t-key $1 \\\n\t-days ${DAYS} \\\n\t-out test_cert.csr \\\n\t-subj '/C=US/O=Asox/CN=test.thrift.org'\n\n    # Sign the test key\n    openssl x509 -req \\\n\t-extensions v3_req \\\n\t-extfile conf.tmp \\\n\t-days ${DAYS} \\\n\t-in test_cert.csr \\\n\t-CA ca-cert.pem \\\n\t-CAkey ca-key.pem \\\n\t-out $2\n\n    # Clean up the signing request as well as the serial number\n    rm ca-cert.srl test_cert.csr conf.tmp\n}\n\ngenerateCert tests-key.pem tests-cert.pem 127.0.0.1 ::1\n", "num_lines": 85}
{"repo_name": "fbthrift", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# remove --install_dir\nshift 1\n\n${PROTOC} --cpp_out=\"$INSTALL_DIR\" \"$@\"\n\n# Fix up include path\nsed -i \\\n  's|ProtoBufBenchData.pb.h|thrift/lib/cpp2/test/ProtoBufBenchData.pb.h|g' \\\n  \"$INSTALL_DIR\"/ProtoBufBenchData.pb.cc\n", "num_lines": 27}
{"repo_name": "fbthrift", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nrm -rf gen-py\n../../../compiler/cpp/thrift --gen py test1.thrift || exit 1\n../../../compiler/cpp/thrift --gen py test2.thrift || exit 1\nPYTHONPATH=./gen-py python -c 'import foo.bar.baz' || exit 1\nPYTHONPATH=./gen-py python -c 'import test2' || exit 1\nPYTHONPATH=./gen-py python -c 'import test1' &>/dev/null && exit 1  # Should fail.\ncp -r gen-py simple\n../../../compiler/cpp/thrift -r --gen py test2.thrift || exit 1\nPYTHONPATH=./gen-py python -c 'import test2' || exit 1\ndiff -ur simple gen-py > thediffs\nfile thediffs | grep -s -q empty || exit 1\nrm -rf simple thediffs\necho 'All tests pass!'\n", "num_lines": 29}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"Starting a manual test run ...\"\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\nDIST_DIR=\"$DIR/../dist\"\n\nif [[ ! -d $DIST_DIR/mac || ! -d $DIST_DIR/linux-unpacked || ! -d $DIST_DIR/win-unpacked ]]; then\n    echo \"ERR: Needs distributions built for Mac, Linux and Windows.\"\n    echo \"Please run in this in the desktop directory:\"\n    echo \"$ yarn build --mac --linux --win\"\n    exit 1\nfi\n\nhas_resources() {\n    if ! tar tf \"$1\" | grep '[Rr]esources/app.asar' > /dev/null; then\n        echo \"ERR: $1 for $2 does not contain a resource bundle. Check your packfile!\"\n        exit 2\n    fi\n}\n\nhas_no_resources() {\n    if (( $(tar tf \"$1\" | grep -cFv '[Rr]esources/app.asar') < 10 )); then\n        echo \"ERR: $1 for $2 has suspiciously low number of non-resource files. Check your packfile!\"\n        exit 2\n    fi\n}\n\necho \"Build for Mac ...\"\n\ncargo run mac\nhas_resources core.tar.xz mac\nhas_no_resources frameworks.tar.xz mac\ncat manifest.json\n\necho\necho \"All good.\"\n\necho \"Build for Linux ...\"\n\ncargo run linux\nhas_resources core.tar.xz linux\nhas_no_resources frameworks.tar.xz linux\ncat manifest.json\n\necho\necho \"All good.\"\n\necho \"Building for Windows ...\"\n\ncargo run windows\nhas_resources core.tar.xz windows\nhas_no_resources frameworks.tar.xz windows\ncat manifest.json\n\necho\necho \"All good. Ship it.\"\n", "num_lines": 62}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nBASEDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n# Run from here so we know we're having fbsource in our $PWD.\ncd \"$BASEDIR\" || exit\n\ncase $OSTYPE in\n  darwin*) ./bump.mac \"$@\" ;;\n  linux-gnu) ./bump.lnx64 \"$@\" ;;\n  *) echo \"Unknown OS. Using source version via https://haskellstack.org/\" && ./bump/bump.hs \"$@\" ;;\nesac\n", "num_lines": 16}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nRESULT_FILE=$1\n\nif [ -f \"$RESULT_FILE\" ]; then\n  rm \"$RESULT_FILE\"\nfi\ntouch \"$RESULT_FILE\"\n\nchecksum_file() {\n  openssl sha256 \"$1\" | awk '{print $2}'\n}\n\nFILES=()\nwhile read -r -d ''; do\n  FILES+=(\"$REPLY\")\ndone < <(find . -type f \\( -name \"build.gradle*\" -o -name \"gradle-wrapper.properties\" \\) -print0)\n\n# Loop through files and append checksum to result file\nfor FILE in \"${FILES[@]}\"; do\n  checksum_file \"$FILE\" >> \"$RESULT_FILE\"\ndone\n\nsort \"$RESULT_FILE\" -o \"$RESULT_FILE\"\n", "num_lines": 29}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nmain () {\n  local -r THIS_DIR=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\n  ROOT_DIR=$(cd \"$THIS_DIR\" && hg root)\n  source \"$ROOT_DIR/xplat/sonar/scripts/setup-env.sh\"\n\n  # save current cursor location\n  printf \"Ensuring correct dependencies...\"\n\n  PREV_DIR=\"`pwd`\"\n\n  # install dependencies\n  cd \"$INFINITY_DIR\"\n  \"$INSTALL_NODE_MODULES\"\n\n  # ensure electron gets installed\n  node node_modules/electron/install.js\n\n  # go back\n  cd \"$PREV_DIR\"\n\n  # remove correct dependencies log\n  printf \"\\r\"\n}\n\nmain\n", "num_lines": 34}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -xe\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# try to install with wget\ncommand -v wget &>/dev/null && wget -O /tmp/retry \"https://github.com/moul/retry/releases/download/v0.5.0/retry_$(uname -s)_$(uname -m)\" || true\n\n# try to install with curl\nif [ ! -f /tmp/retry ]; then\n  command -v curl &>/dev/null && curl -L -o /tmp/retry \"https://github.com/moul/retry/releases/download/v0.5.0/retry_$(uname -s)_$(uname -m)\"\nfi\n\nchmod +x /tmp/retry\n/tmp/retry --version\n", "num_lines": 17}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\necho \"\u00e2\u0153\u00a8 Making a new release...\"\n\n# When starting this job from SandcastleFlipperAutoReleaseCommand, we pass in the revision to release\nSANDCASTLE_REVISION=\"$1\"\nVERSION=\"$2\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nSONAR_DIR=\"$DIR/../\"\nDESKTOP_DIR=\"$SONAR_DIR/desktop\"\n\nsource \"$DIR\"/setup-env.sh\n\nif [[ ! -d \"$DESKTOP_DIR/node_modules\" ]]; then\n  yarn --cwd \"$DESKTOP_DIR\" install --ignore-scripts --ignore-engines\nfi\n\n# if we got called with a rev argument, we got triggered from our automatic sandcastle job\nif [ \"$SANDCASTLE_REVISION\" == \"\" ];\nthen\n  OLD_VERSION=$(jq -r '.version' \"$DESKTOP_DIR\"/package.json)\n  echo \"The currently released version is $OLD_VERSION. What should the version of the next release be?\"\n  read -r VERSION\n  yarn --cwd \"$DESKTOP_DIR\" version --new-version \"$VERSION\"\nfi\n\necho \"Preparing release $VERSION...\"\n\n# Update flipper app version to the very same version\nyarn --cwd \"$DESKTOP_DIR\" version --new-version \"$VERSION\"\n\n# Update react-native-flipper to the very same version\nyarn --cwd \"$SONAR_DIR\"/react-native/react-native-flipper version --new-version \"$VERSION\" --no-git-tag-version\n\n# Update js-flipper to the very same version\nyarn --cwd \"$SONAR_DIR\"/js/js-flipper version --new-version \"$VERSION\" --no-git-tag-version\n\n# This could be one expression with GNU sed, but I guess we want to support the BSD crap, too.\nSNAPSHOT_MINOR_VERSION=$(echo \"$VERSION\" | sed -Ee 's/([0-9]+)\\.([0-9]+)\\.([0-9]+)/\\3 + 1/' | bc)\nSNAPSHOT_VERSION=\"$(echo \"$VERSION\" | sed -Ee 's/([0-9]+)\\.([0-9]+)\\.([0-9]+)/\\1.\\2./')\"\"$SNAPSHOT_MINOR_VERSION\"\"-SNAPSHOT\"\n\necho \"Bumping version number for android related files...\"\n# Update Android related files\n\"$SONAR_DIR\"/scripts/bump.sh \"$VERSION\"\n\n# Generate changelog\n$nodejs \"$DESKTOP_DIR\"/scripts/generate-changelog.js\n\n# Create commit\necho \"Committing the files...\"\nhg addremove\nhg commit -m \"$(echo -e \"Flipper Release: v${VERSION}\\n\\n\\\nSummary:\\nReleasing version $VERSION\\n\\n\\\nTest Plan:\\n\\\nPlease follow these steps to ship the new Flipper release:\\n\\n\\\n1. Check Signal Hub for the ephemeral Flipper build. You will find instructions on how to run it in there: https://www.internalfb.com/intern/px/p/1Kcbk\\n\\\n2. Follow the [release smoke testing checklist](https://www.internalfb.com/intern/staticdocs/flipper/docs/fb/release-infra/#release-smoke-testing) to perform some brief exploratory tests.\\n\\\n3. If things are looking okay, accept both diffs and land them *together* as a stack.\\n\\\n4. Once landed, the Flipper bot will comment with \\\"#flipperrelease with bump\\\" on the diff. If this doesn't happen, please do this yourself. This will kick off the [\\\"flipper-release\\\"](https://fburl.com/sandcastle/uh698xj2) job, resulting in another diff which when landed pins the new release for our users.\\n\\\nSee more details about the Flipper release process [here](https://fburl.com/flipperreleasebot).\\n\\n\\\nReviewers: flipper\\n\\n\\\nTags: accept2ship\"\n)\"\n\n# Create snapshot commit\nRELEASE_REV=\"$(hg log -r . --template \"{node}\\\\n\")\"\n\necho \"Release commit made as $RELEASE_REV, creating new snapshot version $SNAPSHOT_VERSION...\"\n\"$SONAR_DIR\"/scripts/bump.sh --snapshot \"$SNAPSHOT_VERSION\"\n\nhg commit -m \"$(echo -e \"Flipper Snapshot Bump: v${SNAPSHOT_VERSION}\\n\\n\\\nSummary:\\nReleasing snapshot version $SNAPSHOT_VERSION\\n\\n\\\nTest Plan:\\n\\\nNo specific test action required. Please land this **together with the previous diff**.\\n\\\nThis diff is only exists to enable continuous snapshot releases on Maven. It's a Java thing. Don't think about it too much.\\n\\\n\\n\\n\\\nReviewers: flipper\\n\\n\\\nTags: accept2ship\"\n)\"\n\nif [ \"$SANDCASTLE_REVISION\" == \"\" ];\nthen\n  # Submit diffs, we only do this when running locally.\n  # From SandcastleFlipperAutoReleaseCommand, the diffs are submitted\n  # later by using the bot context\n  echo \"Submitting diffs for review...\"\n  jf submit -n -r.^::.\nelse\n  echo \"Skip submitting diffs, as this diffs should be submitted by SC\"\nfi\n", "num_lines": 97}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nBASEDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\"\nIS_SNAPSHOT=\"$(grep 'VERSION_NAME=[0-9\\.]\\+-SNAPSHOT' \"$BASEDIR/gradle.properties\" || echo \"\")\"\n\nif [ \"$ANDROID_PUBLISH_KEY\" == \"\" ]; then\n  echo \"No encryption key. Skipping snapshot deployment.\"\n  exit\nelif [ \"$IS_SNAPSHOT\" == \"\" ]; then\n  echo \"Skipping build. Given build doesn't appear to be a SNAPSHOT release.\"\n  exit 1\nelse\n  openssl aes-256-cbc -pbkdf2 -d -in scripts/gradle-publish-keys.enc -k \"$ANDROID_PUBLISH_KEY\" >> \"$BASEDIR/gradle.properties\"\n  \"$BASEDIR\"/gradlew publish\nfi\n", "num_lines": 22}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$1\" ]\nthen\n    echo \"Please pass the root directory of flipper repository as a first argument.\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]\nthen\n    echo \"Please pass the pod name to push, It just accepts 'Flipper' and 'FlipperKit', do not append podspec at the end\"\n    exit 1\nfi\n\nif [[ \"$2\" != \"Flipper\" ]] && [[ \"$2\" != \"FlipperKit\" ]]\nthen\n    echo \"This script just supports Flipper and FlipperKit pods. Please send either Flipper or FlipperKit as an argument.\"\n    exit 1\nfi\n\nFLIPPER_DIR=$1\nPOD_NAME=$2\nPOD_TO_PUSH=\"$FLIPPER_DIR/$POD_NAME.podspec\"\n\nif ! [[ -f \"$POD_TO_PUSH\" ]]; then\n    echo \"$POD_TO_PUSH does not exist. Please check the pod name.\"\nfi\n\nPOD_VERSION_TAG=$(< \"$POD_TO_PUSH\" grep \"flipperkit_version =\" )\nPOD_VERSION=\"${POD_VERSION_TAG##* }\"\nPOD_VERSION=$(sed -e \"s/^'//\" -e \"s/'$//\" <<<\"$POD_VERSION\")\n\npush_pods_and_retry () {\n    echo \"Pushing $POD_VERSION of $POD_NAME...\"\n    FLAGS=\"--use-libraries --allow-warnings --verbose --skip-import-validation\"\n    if [[ \"$POD_NAME\" == \"FlipperKit\" ]]\n    then\n        FLAGS=\"$FLAGS --synchronous\"\n    fi\n    POD_COMMAND=\"pod trunk push $POD_TO_PUSH $FLAGS\"\n    MAX_ATTEMPT=4\n    ATTEMPT_NUM=0\n    TIME_TO_WAIT=1\n    until [ \"$ATTEMPT_NUM\" -ge \"$MAX_ATTEMPT\" ]\n    do\n        echo \"Retry attempt $ATTEMPT_NUM...\"\n        if [ \"$ATTEMPT_NUM\" -ge 1 ]\n        then\n        echo \"Retry attempt $ATTEMPT_NUM...\"\n        fi\n        $POD_COMMAND && break\n        echo \"Failed to push. Will Retry in $TIME_TO_WAIT minute.\"\n        sleep $((60*TIME_TO_WAIT))\n        # Exponential back off.\n        TIME_TO_WAIT=$((2*TIME_TO_WAIT))\n        ATTEMPT_NUM=$((ATTEMPT_NUM+1))\n    done\n\n    if [ \"$ATTEMPT_NUM\" -ge \"$MAX_ATTEMPT\" ]\n    then\n        echo \"Exhausted all retry attempts and failed to push, please try again later...\"\n        exit 1\n    fi\n}\n\nENDPOINT_TO_CHECK=\"https://github.com/CocoaPods/Specs/blob/master/Specs/a/e/a/Flipper/$POD_VERSION\"\nif [[ \"$POD_NAME\" == \"FlipperKit\" ]]\nthen\n    STATUS_CODE=$(curl -LI \"$ENDPOINT_TO_CHECK\" -o /dev/null -w '%{http_code}\\n' -s)\n    if ! [[ $STATUS_CODE == 200 ]]\n    then\n    echo \"Please push $POD_VERSION of Flipper before pushing $POD_VERSION of FlipperKit.\"\n    exit 1;\n    fi\n    ENDPOINT_TO_CHECK=\"https://github.com/CocoaPods/Specs/tree/master/Specs/3/2/5/FlipperKit/$POD_VERSION\"\nfi\n\necho \"Verifying if $POD_VERSION already pushed for $POD_NAME...\"\necho \"Curling $ENDPOINT_TO_CHECK\"\nSTATUS_CODE=$(curl -LI \"$ENDPOINT_TO_CHECK\" -o /dev/null -w '%{http_code}\\n' -s)\necho \"$STATUS_CODE\"\n\nif  [[ \"$STATUS_CODE\" -ge 400 ]]\nthen\n    push_pods_and_retry \"$@\"\nelse\n    echo \"$POD_VERSION of $POD_NAME is already pushed.\"\n    exit 0\nfi\n\necho \"Successfully published $POD_VERSION of $POD_NAME.\"\n", "num_lines": 98}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"\u00e2\u0153\u00a8 Creating new Sonar iOS release on GitHub...\"\n\necho \"What should the patch version of the next release be?\"\nread -r VERSION\n\nTMP_DIR=$(mktemp -d)\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nJSON=$(cat \"$DIR/public-ios-release.json\")\nJSON=${JSON/__VERSION__/$VERSION}\nJSON=${JSON/__VERSION__/$VERSION}\nJSON=${JSON/__USER__/$USER}\necho \"$JSON\" > \"$TMP_DIR/job.json\"\nscutil create \"$TMP_DIR/job.json\"\necho \"\u00e2\u0153\u2026 GitHub release will be automatically created once the Sandcastle job finishes.\"\nrm -rf \"$TMP_DIR\"\n", "num_lines": 22}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nmain () {\n  local -r THIS_DIR=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\n  ROOT_DIR=$(cd \"$THIS_DIR\" && hg root)\n\n  source \"$ROOT_DIR/xplat/js/env-utils/setup_env_vars.sh\"\n\n  export SONAR_DIR=\"$ROOT_DIR/xplat/sonar\"\n  export PATH=\"$SONAR_DIR/node_modules/.bin:$ROOT_DIR/xplat/third-party/node/bin:$ROOT_DIR/xplat/third-party/yarn:$PATH\"\n}\n\nmain\n", "num_lines": 20}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nif [ -z \"$1\" ]\n  then\n    echo \"Please pass the root directory of flipper repository as a first argument.\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]\n  then\n    echo \"Please pass the path to update the pod version in your second argument.\"\n    exit 1\nfi\n\ndarwin=false\ncase \"$(uname)\" in\n  Darwin*) darwin=true ;;\nesac\n\nif ! jq --version > /dev/null; then\n  if $darwin; then\n    echo \"jq is not installed. Installing it...\"\n    brew install jq\n  else\n    echo >&2 \"jq is not installed. Please install it using your platform's package manager (apt-get, yum, pacman, etc.).\"\n    exit 1\n  fi\nfi\n\nFLIPPER_DIR=$1\nPACKAGE_VERSION=$(jq -r .version \"$FLIPPER_DIR/desktop/package.json\")\nOLD_VERSION_POD_ARG=$(< \"$2\" grep \"flipperkit_version =\" )\nOLD_VERSION=\"${OLD_VERSION_POD_ARG##* }\"\nFLIPPERKIT_VERSION_TAG='flipperkit_version'\n\necho \"Updating $2\"\nif $darwin; then\nsed -i '' \"s/${FLIPPERKIT_VERSION_TAG} = ${OLD_VERSION}/${FLIPPERKIT_VERSION_TAG} = '${PACKAGE_VERSION}'/\" \"$2\"\nelse\n  sed -i \"s/${FLIPPERKIT_VERSION_TAG} = ${OLD_VERSION}/${FLIPPERKIT_VERSION_TAG} = '${PACKAGE_VERSION}'/\" \"$2\"\nfi\n", "num_lines": 47}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nBASEDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\"\nNUM=$(unzip -l \"$BASEDIR\"/android/build/outputs/aar/android-debug.aar | grep -c libevent_core)\n\nif (( NUM >= 4 )); then\n    echo \"Found $NUM instances of libevent_core. Looks good.\"\n    exit 0\nelse\n    unzip -l \"$BASEDIR\"/android/build/outputs/aar/android-debug.aar | grep libevent_core\n    echo \"Expected 4 but found $NUM libevent_core.so files. Expecting one for each architecture. See #3395 for details.\"\n    exit 1\nfi\n", "num_lines": 18}
{"repo_name": "flipper", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ \"$#\" -ne 4 ] && [ \"$#\" -ne 2 ]; then\n    echo \"Utility for manipulating the sonar directory where certificates and connection config are stored on Android devices.\"\n    echo \"Usage: $0 pull APP_PACKAGE SOURCE DEST\"\n    echo \"E.g:   $0 pull com.facebook.flipper.sample device.crt /tmp/device.crt\"\n    echo \" or\"\n    echo \"Usage: $0 ls APP_PACKAGE\"\n    exit 1;\nfi\nPACKAGE=$2\nSOURCE=$3\nDEST=$4\ncase \"$1\" in\n  \"pull\")\n    # run-as opens a subshell on the device, so we echo the command we want to\n    # execute into that subshell.\n    echo \"cat files/sonar/$SOURCE\" | adb shell run-as \"$PACKAGE\" > \"$DEST\"\n    ;;\n  \"ls\")\n    echo \"ls -la files/sonar\" | adb shell run-as \"$PACKAGE\"\n    ;;\n  *)\n    echo \"Unrecognised command: $1\"\n    exit 1\n    ;;\nesac\n", "num_lines": 32}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nshow_help() {\n  printf \"Usage: runtests.sh [-hlqrv] [-d DIR] [-t TEST] [-b] FLOW_BINARY [[-f] TEST_FILTER]\\n\\n\"\n  printf \"Runs Flow's tests.\\n\\n\"\n  echo \"    [-b] FLOW_BINARY\"\n  echo \"        path to Flow binary (the -b is optional)\"\n  echo \"    [-f] TEST_FILTER\"\n  echo \"        optional regular expression to choose test directories to run\"\n  echo \"    -l\"\n  echo \"        lists the tests that will be run\"\n  echo \"    -d DIR\"\n  echo \"        run tests in DIR/tests/\"\n  echo \"    -t TEST\"\n  echo \"        run the test DIR/tests/TEST, equivalent to a filter of \\\"^TEST$\\\"\"\n  echo \"    -c\"\n  echo \"        only run check tests\"\n  echo \"    -r\"\n  echo \"        re-record failing tests to update expected output\"\n  echo \"    -q\"\n  echo \"        quiet output (hides status, just prints results)\"\n  echo \"    -s\"\n  echo \"        test saved state\"\n  echo \"    -L\"\n  echo \"        test long-lived workers\"\n  echo \"    -v\"\n  echo \"        verbose output (shows skipped tests)\"\n  echo \"    -h\"\n  echo \"        display this help and exit\"\n}\n\nexport IN_FLOW_TEST=1\nexport FLOW_LOG_LEVEL=debug\nexport FLOW_NODE_BINARY=${FLOW_NODE_BINARY:-${NODE_BINARY:-$(which node)}}\n\n# find git. to skip git tests even when git is available,\n# set FLOW_GIT_BINARY to empty string\nif [ -n \"${FLOW_GIT_BINARY-unset}\" ]; then\n  export FLOW_GIT_BINARY=${FLOW_GIT_BINARY:-$(which git)}\nfi\n\nOPTIND=1\nrecord=0\nsaved_state=0\nverbose=0\nquiet=0\nrelative=\".\"\ncheck_only=0\nlong_lived_workers=0\nexport saved_state filter check_only long_lived_workers\nwhile getopts \"b:d:f:clqxrsLt:vh?\" opt; do\n  case \"$opt\" in\n  b)\n    FLOW=\"$OPTARG\"\n    ;;\n  d)\n    relative=\"$OPTARG\"\n    ;;\n  f)\n    filter=\"$OPTARG\"\n    ;;\n  c)\n    check_only=1\n    ;;\n  l)\n    list_tests=1\n    ;;\n  t)\n    specific_test=\"$OPTARG\"\n    ;;\n  q)\n    quiet=1\n    ;;\n  r)\n    record=1\n    ;;\n  s)\n    saved_state=1\n    printf \"Testing saved state by running all tests using saved state\\\\n\"\n    ;;\n  L)\n    long_lived_workers=1\n    ;;\n  v)\n    verbose=1\n    ;;\n  h|\\?)\n    show_help\n    exit 0\n    ;;\n  esac\ndone\n\nshift $((OPTIND-1))\n\n[ \"$1\" = \"--\" ] && shift\n\nif [ -n \"$specific_test\" ]; then\n  if [[ \"$saved_state\" -eq 1 ]]; then\n    specific_test=$(echo $specific_test | sed 's/\\(.*\\)-saved-state$/\\1/')\n  fi\n  if [[ \"$long_lived_workers\" -eq 1 ]]; then\n    specific_test=$(echo $specific_test | sed 's/\\(.*\\)-long-lived-workers$/\\1/')\n  fi\n\n  filter=\"^$specific_test$\"\nfi\n\nFLOW=\"${FLOW:-$1}\"\nfilter=\"${filter:-$2}\"\n\nif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  _canonicalize_file_path() {\n    local dir file\n    dir=$(dirname -- \"$1\")\n    file=$(basename -- \"$1\")\n    (cd \"$dir\" 2>/dev/null && printf '%s/%s\\n' \"$(pwd -P)\" \"$file\")\n  }\n  FLOW=$(_canonicalize_file_path \"$FLOW\")\nelse\n  FLOW=$(readlink -f \"$FLOW\")\nfi\n\nVERSION=$(\"$FLOW\" version --semver)\n\nexport FLOW VERSION\n\nif [ -t 1 ]; then\n  COLOR_RESET=\"\\x1b[0m\"\n  COLOR_DEFAULT=\"\\x1b[39;49;0m\"\n  COLOR_DEFAULT_BOLD=\"\\x1b[39;49;1m\"\n  COLOR_RED_BOLD=\"\\x1b[31;1m\"\n  COLOR_GREEN_BOLD=\"\\x1b[32;1m\"\n  COLOR_YELLOW_BOLD=\"\\x1b[33;1m\"\n  COLOR_MAGENTA_BOLD=\"\\x1b[35;1m\"\n  COLOR_WHITE_ON_RED_BOLD=\"\\x1b[37;41;1m\"\nelse\n  COLOR_RESET=\"\"\n  COLOR_DEFAULT=\"\"\n  COLOR_DEFAULT_BOLD=\"\"\n  COLOR_RED_BOLD=\"\"\n  COLOR_GREEN_BOLD=\"\"\n  COLOR_YELLOW_BOLD=\"\"\n  COLOR_MAGENTA_BOLD=\"\"\n  COLOR_WHITE_ON_RED_BOLD=\"\"\nfi\nprint_failure() {\n    dir=$1\n    name=${dir%*/}\n    name=${name##*/}\n\n    if [[ \"$record\" -eq 1 ]]; then\n      printf \"%b[\u00e2\u0153\u2014] UPDATED:%b %s%b\\n\" \\\n        \"$COLOR_MAGENTA_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n    else\n      printf \"%b[\u00e2\u0153\u2014] FAILED:%b  %s%b\\n\" \\\n        \"$COLOR_RED_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n    fi\n\n    diff_file=\"${dir}${name}.diff\"\n    err_file=\"${dir}${name}.err\"\n    [ -f \"$err_file\" ] && cat \"$err_file\"\n    if [ -f \"$diff_file\" ]; then\n      if [ -t 1 ] ; then\n        esc=$(echo -e \"\\x1b\")\n        sed \\\n            \"s/^-/${esc}[31m-/;s/^+/${esc}[32m+/;s/^@/${esc}[35m@/;s/$/${esc}[0m/\" \\\n            < \"$diff_file\"\n      else\n        cat \"$diff_file\"\n      fi\n    fi\n    # Default expected file extension is .exp\n    ext=\".exp\"\n\n    if [[ \"$record\" -eq 1 ]]; then\n      # Copy .out to .exp, replacing the current version, if present, with\n      # <VERSION>, so that the .exp doesn't have to be updated on each release.\n      sed 's/'\"${VERSION//./\\\\.}\"'/<VERSION>/g' \"${dir}${name}.out\" > \"${dir}${name}${ext}\"\n      rm \"${dir}${name}.out\"\n      rm -f \"$err_file\"\n      rm \"$diff_file\"\n    fi\n}\nprint_error() {\n    dir=$1\n    name=${dir%*/}\n    name=${name##*/}\n\n    printf \"%b[\u00e2\u0153\u2014] ERRORED:%b %s%b\\n\" \\\n      \"$COLOR_RED_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n\n    out_file=\"${dir}${name}.out\"\n    [ -f \"$out_file\" ] && cat \"$out_file\"\n\n    err_file=\"${dir}${name}.err\"\n    [ -f \"$err_file\" ] && printf \"\\n\\nStderr:\\n\" && cat \"$err_file\"\n\n    monitor_log_file=\"${dir}${name}.monitor_log\"\n    [ -f \"$monitor_log_file\" ] && printf \"\\n\\nServer monitor log:\\n\" && cat \"$monitor_log_file\"\n\n    log_file=\"${dir}${name}.log\"\n    [ -f \"$log_file\" ] && printf \"\\n\\nServer log:\\n\" && cat \"$log_file\"\n}\nprint_skip() {\n    name=$1\n    name=${name%*/}\n    name=${name##*/}\n    verbose=$2\n    if [[ \"$verbose\" -eq 1 ]]; then\n      printf \"%b[-] SKIPPED:%b %s%b\\n\" \\\n        \"$COLOR_YELLOW_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n    elif [[ -t 1 ]]; then\n      printf \"             %*s\\r\" ${#name} \" \"\n    fi\n}\nprint_success() {\n    name=$1\n    name=${name%*/}\n    name=${name##*/}\n    printf \"%b[\u00e2\u0153\u201c] PASSED:%b  %s%b\\n\" \\\n      \"$COLOR_GREEN_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n}\nprint_run() {\n    if [[ -t 1 && \"$quiet\" -eq 0 ]]; then\n      name=$1\n      name=${name%*/}\n      name=${name##*/}\n      printf \"%b[ ] RUNNING:%b %s%b\\r\" \\\n        \"$COLOR_DEFAULT_BOLD\" \"$COLOR_DEFAULT\" \"$name\" \"$COLOR_RESET\"\n    fi\n}\n\ncd \"$relative\" || exit 1\npassed=0\nfailed=0\nskipped=0\nerrored=0\n\n# shellcheck source=fbcode/flow/scripts/lib/runtests-common.sh\n. \"./scripts/lib/runtests-common.sh\"\n\nif [ -z \"$FLOW_MAX_WORKERS\" ]; then\n  export FLOW_MAX_WORKERS=2\nfi\n\nnum_to_run_in_parallel=${FLOW_RUNTESTS_PARALLELISM-16}\nif [[ \"$quiet\" -eq 0 ]]; then\n  printf \"Running up to %d test(s) in parallel\\n\" \"$num_to_run_in_parallel\"\nfi\n\n# Index N of results should correspond to the test at index N of dirs\ndirs=(tests/*/)\nresults=()\n\nif [[ \"$list_tests\" -eq 1 ]]; then\n  for dir in \"${dirs[@]}\"; do\n    dir=${dir%*/}\n    name=${dir##*/}\n\n    if [[ -z $filter || $name =~ $filter ]]; then\n\n      if [[ \"$saved_state\" -eq 1 ]]; then\n        echo \"$name-saved-state\"\n      elif [[ \"$long_lived_workers\" -eq 1 ]]; then\n        echo \"$name-long-lived-workers\"\n      else\n        echo \"$name\"\n      fi\n    fi\n  done\n  exit 0\nfi\n\n# Run all tests, num_to_run_in_parallel at a time\nparallel_run_tests() {\n    (\n        i=0\n        for dir in \"${dirs[@]}\"; do\n            echo \"$(( i++ )):$dir\"\n        done\n    ) | xargs -P\"$num_to_run_in_parallel\" -n1 \\\n          \"./scripts/run-one-test\"\n}\n\n# Kick off all tests, reporting results over a pipe to our fd 3\nexec 3< <(parallel_run_tests)\n\n# Print a test's result, given its index in dirs and results\nprint_result() {\n    local test_to_print=$1\n    code=${results[$test_to_print]}\n    testname=${dirs[$test_to_print]}\n    case $code in\n      $RUNTEST_SUCCESS )\n        (( passed++ ))\n        print_success \"$testname\" ;;\n      $RUNTEST_FAILURE )\n        (( failed++ ))\n        print_failure \"$testname\" ;;\n      $RUNTEST_SKIP )\n        (( skipped++ ))\n        print_skip \"$testname\" \"$verbose\" ;;\n      $RUNTEST_MISSING_FILES )\n        (( errored++ ))\n        print_error \"$testname\"\n        name=${testname%*/}\n        name=${name##*/}\n        printf \"Missing %s.exp file or .flowconfig file\\n\" \"$name\" ;;\n      $RUNTEST_MISSING_ALL_OPTION )\n        (( errored++ ))\n        print_error \"$testname\"\n        echo 'You are required to set either `all=true` or `all=false` in your test `.flowconfig`.' ;;\n      $RUNTEST_ERROR | '')\n        # '' means the parallel runner stopped before giving a result\n        (( errored++ ))\n        print_error \"$testname\" ;;\n    esac\n}\n\n# Collect the results in the order the tests finish\nnext_test_to_print=0\nprint_run \"${dirs[$next_test_to_print]}\"\nwhile read -ru 3 index code; do\n    results[$index]=$code\n\n    # Print the results in order in a pretty way\n    while [ -n \"${results[$next_test_to_print]}\" ]; do\n        print_result \"$next_test_to_print\"\n        (( next_test_to_print++ ))\n    done\n\n    if (( next_test_to_print < ${#dirs[@]} )); then\n        print_run \"${dirs[$next_test_to_print]}\"\n    fi\ndone\n\nwhile (( next_test_to_print < ${#dirs[@]} )); do\n    # If the parallel runner stopped early, print the remaining tests\n    # (as errors, except any where we already have a result)\n    print_result \"$next_test_to_print\"\n    (( next_test_to_print++ ))\ndone\n\nif [ \"$failed\" -eq 0 ]; then\n  FAILED_COLOR=\"$COLOR_DEFAULT_BOLD\"\nelse\n  FAILED_COLOR=\"$COLOR_WHITE_ON_RED_BOLD\"\nfi\nif [ \"$errored\" -eq 0 ]; then\n  ERRORED_COLOR=\"$COLOR_DEFAULT_BOLD\"\nelse\n  ERRORED_COLOR=\"$COLOR_WHITE_ON_RED_BOLD\"\nfi\n\nif [[ \"$quiet\" -eq 0 ]]; then\n  echo\n  printf \"%bPassed: %d, %bFailed: %d%b, Skipped: %d, %bErrored: %d%b\\n\" \\\n    \"$COLOR_DEFAULT_BOLD\" \"$passed\" \\\n    \"$FAILED_COLOR\" \"$failed\" \\\n    \"$COLOR_DEFAULT_BOLD\" \"$skipped\" \\\n    \"$ERRORED_COLOR\" \"$errored\" \\\n    \"$COLOR_RESET\"\nfi\n\nif [[ \"$failed\" -gt 0 || \"$errored\" -gt 0 ]]; then\n  exit 1\nfi\n", "num_lines": 373}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Generate expected output\n./flow-remove-types test/source.js > test/expected.js;\n\n# Generate expected output with --ignore-uninitialized-fields flag\n./flow-remove-types --ignore-uninitialized-fields test/source.js > test/expected-uninitialized-fields.js;\n\n# Generate expected output with --pretty flag\n./flow-remove-types --pretty test/source.js > test/expected-pretty.js;\n\n# Test expected source maps with --pretty --sourcemaps\n./flow-remove-types --pretty --sourcemaps test/source.js -d test/expected-with-maps;\n\n# Test expected source maps with --pretty --sourcemaps inline\n./flow-remove-types --pretty --sourcemaps inline test/source.js > test/expected-pretty-inlinemap.js;\n\n# Test expected source maps with --pretty --sourcemaps inline, from stdin\n./flow-remove-types --pretty --sourcemaps inline < test/source.js > test/expected-pretty-inlinemap-stdin.js;\n", "num_lines": 24}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Test expected output\necho \"Test: flow-remove-types test/source.js\"\nDIFF=$(./flow-remove-types test/source.js | diff test/expected.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test expected output with --ignore-uninitialized-fields flag\necho \"Test: flow-remove-types --ignore-uninitialized-fields test/source.js\"\nDIFF=$(./flow-remove-types --ignore-uninitialized-fields test/source.js | diff test/expected-uninitialized-fields.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test expected output with --pretty flag\necho \"Test: flow-remove-types --pretty test/source.js\"\nDIFF=$(./flow-remove-types --pretty test/source.js | diff test/expected-pretty.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test expected source maps with --pretty --sourcemaps\necho \"Test: flow-remove-types --pretty --sourcemaps test/source.js -d test/expected-with-maps\"\nTEST_DIR=$(\n  DIR=$(dirname \"${BASH_SOURCE[0]}\");\n  cd \"$DIR\" && pwd\n)\nDIR=$(mktemp -d)\ncp -r test \"$DIR\"\npushd \"$DIR\" || exit 1 > /dev/null\n\"$TEST_DIR/flow-remove-types\" --pretty --sourcemaps test/source.js -d test/expected-with-maps;\npopd || exit 1 > /dev/null\nDIFF_SOURCE=$(diff test/expected-with-maps/test/source.js \"$DIR/test/expected-with-maps/test/source.js\");\nDIFF_MAP=$(diff test/expected-with-maps/test/source.js.map \"$DIR/test/expected-with-maps/test/source.js.map\");\nrm -rf \"$DIR\"\nif [ -n \"$DIFF_SOURCE\" ]; then echo \"$DIFF_SOURCE\"; exit 1; fi;\nif [ -n \"$DIFF_MAP\" ]; then echo \"$DIFF_MAP\"; exit 1; fi;\n\n# Test expected source maps with --pretty --sourcemaps inline\necho \"Test: flow-remove-types --pretty --sourcemaps inline test/source.js\"\nDIFF=$(./flow-remove-types --pretty --sourcemaps inline test/source.js | diff test/expected-pretty-inlinemap.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test expected source maps with --pretty --sourcemaps inline, from stdin\necho \"Test: flow-remove-types --pretty --sourcemaps inline < test/source.js\"\nDIFF=$(./flow-remove-types --pretty --sourcemaps inline < test/source.js | diff test/expected-pretty-inlinemap-stdin.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test expected output with @flow outside of comments\necho \"Test: flow-remove-types test/without-flow.js\"\nDIFF=$(./flow-remove-types test/without-flow.js | diff test/without-flow.js -);\nif [ -n \"$DIFF\" ]; then echo \"$DIFF\"; exit 1; fi;\n\n# Test node require hook\necho \"Test: node require hook\"\nRES=$(node -e 'require(\"./register\");require(\"./test/test-node-module.js\")');\nif [ \"$RES\" != 42 ]; then echo 'Node require hook failed'; exit 1; fi;\n\n# Test flow-node\necho \"Test: flow-node\"\nFLOW_NODE=$(./flow-node ./test/test-node-module.js);\nif [ \"$FLOW_NODE\" != 42 ]; then echo 'flow-node failed'; exit 1; fi;\n\n# Test flow-node with options\necho \"Test: flow-node with options\"\n# --no-warnings is a node flag. node doesn't count its own flags in process.argv, so we're left with\n# [\"node\", \"path/to/flow-node\", \"-p\", \"'process.argv.length'\"]\nFLOW_NODE_OPTS=$(./flow-node --no-warnings -p 'process.argv.length');\nif [ \"$FLOW_NODE_OPTS\" != 4 ]; then echo 'flow-node with options failed'; exit 1; fi;\n# --bogus-flag isn't a node flag, so node will error. this test ensures we're not just dropping flags\nFLOW_NODE_OPTS=$(./flow-node --bogus-flag 2>&1);\nif [[ \"$FLOW_NODE_OPTS\" != *\"bad option: --bogus-flag\"* ]]; then echo 'flow-node with options failed'; exit 1; fi;\n", "num_lines": 73}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ $# -ne 1 ]; then\n  echo \"version number is required\"\n  exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nROOT=\"$DIR/..\"\n\nVERSION=\"${1#v}\" # strip leading v if present\nOPAM_VERSION=\"${VERSION//-/'~'}\"\nREMOVE_TYPES_VERSION=\"2${VERSION#0}\" # replace leading 0 with 2: 0.123.0 -> 2.123.0\n\npushd \"$ROOT\" || exit > /dev/null\n\nset -x\nsed -i 's/^\\(let version = \"\\)[^\"]*\\(\"\\)/\\1'\"$VERSION\"'\\2/' src/common/flow_version.ml\nsed -i 's/^\\(version: \"\\)[^\"]*\\(\"\\)/\\1'\"$OPAM_VERSION\"'\\2/' flowtype.opam\nsed -i 's/^\\(version: \"\\)[^\"]*\\(\"\\)/\\1'\"$OPAM_VERSION\"'\\2/' flow_parser.opam\nsed -i 's/\\(\"version\": \"\\)[^\"]*\\(\"\\)/\\1'\"$VERSION\"'\\2/' packages/flow-parser-bin/package.json\nsed -i 's/\\(\"version\": \"\\)[^\"]*\\(\"\\)/\\1'\"$VERSION\"'\\2/' packages/flow-parser/package.json\nsed -i 's/\\(\"version\": \"\\)[^\"]*\\(\"\\)/\\1'\"$REMOVE_TYPES_VERSION\"'\\2/' packages/flow-remove-types/package.json\nsed -i 's/\\(\"flow-parser\": \"\\)[^\"]*\\(\"\\)/\\1^'\"$VERSION\"'\\2/' packages/flow-remove-types/package.json\n\npopd || exit > /dev/null\n", "num_lines": 31}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nWEBSITE=$(realpath \"$DIR/../website\")\n\n# We need flow.js to exist, so let's build it\n(cd \"$DIR/../\" && make deps && make && make deps-js && make js)\n\nFLOW_OUT_DIR=$(realpath \"$DIR/../bin\")\n\npushd \"$WEBSITE\" > /dev/null\n\n# Symlink flow.js and the flowlibs into place directly in the static folder\nln -sf \"$FLOW_OUT_DIR/flow.js\" \"static/flow/master/flow.js\"\nln -sfn \"$DIR/../lib\" \"static/flow/master/flowlib\"\n\nyarn install\nPATH=\"$FLOW_OUT_DIR:$PATH\" yarn start --host ::\n", "num_lines": 25}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2034\n\nRUNTEST_SUCCESS=0\nRUNTEST_FAILURE=1\nRUNTEST_SKIP=2\nRUNTEST_MISSING_FILES=3\nRUNTEST_ERROR=4\nRUNTEST_MISSING_ALL_OPTION=5\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n[ -d ~/.opam ] || opam init default 'https://github.com/fdopen/opam-repository-mingw.git#opam2' --bare --disable-sandboxing --no-setup\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# All these functions assume the $FLOW env variable is set to the Flow binary.\n# Globs should be expanded when you call these functions, so things like\n#\n#     remove *.js\n#\n# should work.\n\nremove() {\n  set -e\n  # shellcheck disable=SC2068\n  rm $@;\n  # shellcheck disable=SC2068\n  assert_ok \"$FLOW\" force-recheck $@;\n}\n\n# This only supports the mv a.js b.js form. It doesn't support mv *.js dir/\nmove() {\n  set -e\n  # shellcheck disable=SC2068\n  mv $@;\n  # shellcheck disable=SC2068\n  assert_ok \"$FLOW\" force-recheck $@;\n}\n\n# This only supports the cp a.js b.js form. It doesn't support cp *.js dir/\ncopy() {\n    set -e\n    # shellcheck disable=SC2068\n    cp $@;\n    # shellcheck disable=SC2068\n    assert_ok \"$FLOW\" force-recheck $@;\n}\n", "num_lines": 39}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"Get-def imported class:\\n\"\nassert_ok \"$FLOW\" get-def bar.js 5 23 --strip-root --pretty\n\nprintf \"Get-def class member:\\n\"\nassert_ok \"$FLOW\" get-def bar.js 7 6 --strip-root --pretty\n\nprintf \"Autocomplete class property:\\n\"\nassert_ok \"$FLOW\" autocomplete bar.js 7 5 --strip-root --pretty < bar.js.txt\n\nprintf \"dump types:\\n\"\nassert_ok \"$FLOW\" dump-types bar.js --strip-root --pretty\n\nprintf \"type-at-pos:\\n\"\nassert_ok \"$FLOW\" type-at-pos bar.js 7 6 --strip-root --pretty\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status --strip-root\n\n# We should drive merge based on the sig dependency graph, not the implementation dependency graph.\n# Therefore, only `foo.js` and `sig-dependent.js` should be considered for merge. At the time that\n# this test is being written, we consider all six files for merge. This results in unnecessary work.\n\nprintf \"\\\\nChanging the exported type should produce downstream errors.\\\\n\"\nprintf \"We should recheck all files, but should not remerge files that are not recursive sig \"\nprintf \"dependents.\\\\n\"\nsed -i -e 's/string/number/' foo.js\nassert_ok \"$FLOW\" force-recheck foo.js\nassert_errors \"$FLOW\" status --strip-root\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\nassert_ok \"$FLOW\" stop\n", "num_lines": 22}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nshow_obj_obj_fast_path() {\n  grep \"ObjT ~> ObjT fast path\" $1 | tail -n 1\n}\n\nprintf \"\\\\nServer should start in verbose mode\\\\n\"\nstart_flow . --verbose\nassert_ok \"$FLOW\" status --strip-root\nshow_obj_obj_fast_path \"$FLOW_LOG_FILE\"\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp test1.js tmp/\n\nprintf \"\\\\nServer should start in types-first mode\\\\n\"\nstart_flow .\nassert_errors \"$FLOW\" status --strip-root\n\nprintf \"\\\\nAdding a line should cause minimal rechecking (but preserve errors)\\\\n\"\ncp tmp1/test1.js test1.js\nassert_ok \"$FLOW\" force-recheck --focus test1.js\nassert_errors \"$FLOW\" status --strip-root\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\nprintf \"\\\\nAdding a comment should cause minimal rechecking (but preserve errors)\\\\n\"\ncp tmp2/test1.js test1.js\nassert_ok \"$FLOW\" force-recheck --focus test1.js\nassert_errors \"$FLOW\" status --strip-root\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\nassert_ok \"$FLOW\" stop\n\ncp tmp/test1.js test1.js\nrm -rf tmp\n", "num_lines": 30}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\necho\necho \"exact_by_default=false (should print: {|f: number|} for exact)\"\necho\nassert_ok \"$FLOW\" codemod annotate-exports --strip-root .\n\necho\necho \"exact_by_default=true (should print: {f: number, ...} for inexact)\"\necho\nmv flowconfig_exact_by_default_true .flowconfig\nassert_ok \"$FLOW\" codemod annotate-exports --strip-root .\n", "num_lines": 19}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\necho\necho '=== Okay to print any type'\necho\nassert_ok \"$FLOW\" codemod annotate-exports --strip-root .\n\necho\necho \"=== Should print \\$MyPreferedSuppression instead of the any type\"\necho\nassert_ok \"$FLOW\" codemod annotate-exports --strip-root --lints unclear-type=error .\n", "num_lines": 18}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"Reading JS from stdin:\\n\"\nassert_ok \"$FLOW\" ast --pretty < foo.js\n\nprintf \"\\nReading JSON from stdin:\\n\"\nassert_ok \"$FLOW\" ast --pretty --type json < bar.json\n\nprintf \"\\nReading JS from a file:\\n\"\nassert_ok \"$FLOW\" ast --pretty foo.js\n\nprintf \"\\nReading JSON from a file:\\n\"\nassert_ok \"$FLOW\" ast --pretty bar.json\n\nprintf \"\\nUsing absolute --path with stdin:\\n\"\nassert_ok \"$FLOW\" ast --pretty --path /some/path.js < foo.js\n\nprintf \"\\nUsing relative --path with stdin:\\n\"\nassert_ok \"$FLOW\" ast --pretty --path my/relative/path.js < foo.js\n\nprintf \"\\nUsing --path is ignore without stdin:\\n\"\nassert_ok \"$FLOW\" ast --pretty --path my/relative/path.js foo.js\n\nprintf \"\\nNon-ASCII characters without specifying offset style:\\n\"\nassert_ok \"$FLOW\" ast --pretty nonascii.js\n\nprintf \"\\nNon-ASCII characters with utf8-bytes offset style:\\n\"\nassert_ok \"$FLOW\" ast --pretty --offset-style utf8-bytes nonascii.js\n\nprintf \"\\nNon-ASCII characters with js-indices offset style:\\n\"\nassert_ok \"$FLOW\" ast --pretty --offset-style js-indices nonascii.js\n", "num_lines": 36}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2094\n\nqueries_in_file autocomplete \"foo_parse_fail.js\" --pretty\nqueries_in_file autocomplete \"foo.js\" --pretty\nqueries_in_file autocomplete \"bar.js\" --pretty\nqueries_in_file autocomplete \"str.js\" --pretty\nqueries_in_file autocomplete \"num.js\" --pretty\nqueries_in_file autocomplete \"bool.js\" --pretty\nqueries_in_file autocomplete \"union.js\" --pretty\nqueries_in_file autocomplete \"object_builtins.js\" --pretty\nqueries_in_file autocomplete \"function_builtins.js\" --pretty\nqueries_in_file autocomplete \"fun.js\" --pretty\nqueries_in_file autocomplete \"this.js\" --pretty\nqueries_in_file autocomplete \"this2.js\" --pretty\nqueries_in_file autocomplete \"typeparams.js\" --pretty\nqueries_in_file autocomplete \"typeparams_function.js\" --pretty\nqueries_in_file autocomplete \"generics.js\" --pretty\nqueries_in_file autocomplete \"optional.js\" --pretty\nqueries_in_file autocomplete \"jsx1.js\" --pretty\nqueries_in_file autocomplete \"jsx2.js\" --pretty\nqueries_in_file autocomplete \"jsx3.js\" --pretty\nqueries_in_file autocomplete \"jsx4.js\" --pretty\nqueries_in_file autocomplete \"jsx-attribute-member.js\" --pretty\nqueries_in_file autocomplete \"jsx-closing-tag.js\" --pretty\nqueries_in_file autocomplete \"jsx-closing-tag-unclosed.js\" --pretty\nqueries_in_file autocomplete \"jsx-function-component.js\" --pretty\nqueries_in_file autocomplete \"jsx-function-component-2.js\" --pretty\nqueries_in_file autocomplete \"jsx-function-component-3.js\" --pretty\nqueries_in_file autocomplete \"jsx-abstract-component.js\" --pretty\nqueries_in_file autocomplete \"jsx-with-children.js\" --pretty\nqueries_in_file autocomplete \"jsx-text.js\" --pretty\nqueries_in_file autocomplete \"customfun.js\" --pretty\nqueries_in_file autocomplete \"issue-1368.js\" --pretty\nqueries_in_file autocomplete \"if.js\" --pretty\nqueries_in_file autocomplete \"override.js\" --pretty\nqueries_in_file autocomplete \"member_class_property.js\" --lsp\nqueries_in_file autocomplete \"member_class_static.js\" --pretty\nqueries_in_file autocomplete \"member_interface_property.js\" --lsp\nqueries_in_file autocomplete \"member_middle.js\" --pretty\nqueries_in_file autocomplete \"opaque_types.js\" --pretty\nqueries_in_file autocomplete \"optional_chaining_middle.js\" --pretty\nqueries_in_file autocomplete \"optional_chaining_new.js\" --pretty\nqueries_in_file autocomplete \"optional_chaining_continue.js\" --pretty\nqueries_in_file autocomplete \"idx.js\" --pretty\nqueries_in_file autocomplete \"generic_alias.js\" --pretty\nqueries_in_file autocomplete \"object_literal.js\" --pretty\nqueries_in_file autocomplete \"optional_object.js\" --pretty\nqueries_in_file autocomplete \"indirect_array.js\" --pretty\nqueries_in_file autocomplete \"eval_predicate.js\" --pretty\nqueries_in_file autocomplete \"eval_destructor.js\" --pretty\nqueries_in_file autocomplete \"poly.js\" --pretty\nqueries_in_file autocomplete \"poly_no_args.js\" --pretty\nqueries_in_file autocomplete \"identifier.js\" --pretty\nqueries_in_file autocomplete \"identifier_middle.js\" --pretty\nqueries_in_file autocomplete \"identifier_import_type.js\" --pretty\nqueries_in_file autocomplete \"identifier_type.js\" --pretty\nqueries_in_file autocomplete \"super.js\" --pretty\nqueries_in_file autocomplete \"this-2.js\" --pretty\nqueries_in_file autocomplete \"pattern.js\" --pretty\nqueries_in_file autocomplete \"normalize-1.js\" --pretty\nqueries_in_file autocomplete \"normalize-2.js\" --pretty\nqueries_in_file autocomplete \"unqualified-type-annotation.js\" --lsp\nqueries_in_file autocomplete \"qualified-type-annotation.js\" --pretty\nqueries_in_file autocomplete \"qualified-type-annotation-require.js\" --pretty\nqueries_in_file autocomplete \"inherited-class-properties.js\" --pretty\nqueries_in_file autocomplete \"function-added-properties.js\" --pretty\nqueries_in_file autocomplete \"comments.js\" --pretty\nqueries_in_file autocomplete \"literal.js\" --pretty\nqueries_in_file autocomplete \"import_source.js\" --pretty\nqueries_in_file autocomplete \"import_specifiers_1.js\" --pretty\nqueries_in_file autocomplete \"import_specifiers_2.js\" --pretty\nqueries_in_file autocomplete \"object-spread-1.js\" --pretty\nqueries_in_file autocomplete \"object-spread-2.js\" --pretty\nqueries_in_file autocomplete \"object_keys_spread.js\" --pretty\nqueries_in_file autocomplete \"union-2.js\" --pretty\nqueries_in_file autocomplete \"type-alias.js\" --pretty\nqueries_in_file autocomplete \"intersection.js\" --pretty\nqueries_in_file autocomplete \"rank.js\" --lsp\nqueries_in_file autocomplete \"rank_union.js\" --lsp\nqueries_in_file autocomplete \"rank_intersection.js\" --lsp\nqueries_in_file autocomplete \"suggest_optional_chaining_1.js\" --lsp\nqueries_in_file autocomplete \"suggest_optional_chaining_2.js\" --lsp\nqueries_in_file autocomplete \"suggest_optional_chaining_3.js\" --lsp\nqueries_in_file autocomplete \"enums.js\" --lsp\nqueries_in_file autocomplete \"enum-key.js\" --lsp\nqueries_in_file autocomplete \"enum-id.js\" --pretty\nqueries_in_file autocomplete \"class_declaration_name.js\" --pretty\nqueries_in_file autocomplete \"pattern_object_key_middle.js\" --pretty\nqueries_in_file autocomplete \"jsdoc.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-1.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-2.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-3.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-4.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-5.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-6.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-7.js\" --lsp\nqueries_in_file autocomplete \"jsdoc-members-8.js\" --lsp\nqueries_in_file autocomplete \"types-jsdoc.js\" --lsp\nqueries_in_file autocomplete \"qualified-types-jsdoc.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_1.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_2.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_3.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_4.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_5.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_6.js\" --lsp\nqueries_in_file autocomplete \"iterator.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_needed.js\" --lsp\nqueries_in_file autocomplete \"bracket_syntax_needed_2.js\" --lsp\nqueries_in_file autocomplete \"upper_bounds_1.js\" --lsp\nqueries_in_file autocomplete \"upper_bounds_2.js\" --lsp\nqueries_in_file autocomplete \"upper_bounds_6.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_7.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_8.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_9.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_10.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_11.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_12.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_13.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_14.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_15.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_16.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_17.js\" --pretty\nqueries_in_file autocomplete \"upper_bounds_18.js\" --pretty\nqueries_in_file autocomplete \"indexed-access-1.js\" --lsp\nqueries_in_file autocomplete \"indexed-access-2.js\" --lsp\nqueries_in_file autocomplete \"indexed-access-optional-1.js\" --lsp\nqueries_in_file autocomplete \"indexed-access-optional-2.js\" --lsp\nqueries_in_file autocomplete \"typeof.js\" --lsp\nqueries_in_file autocomplete \"typeof_2.js\" --lsp\nqueries_in_file autocomplete \"recursive.js\" --pretty\nqueries_in_file autocomplete \"class_members.js\" --pretty\nqueries_in_file autocomplete \"method_signature.js\" --lsp\nquery_at_pos autocomplete \"last_empty_line.js\" 5 0 --pretty\nqueries_in_file autocomplete \"string_literal.js\" --lsp\nqueries_in_file autocomplete \"type_binding_id.js\" --pretty\nquery_at_pos autocomplete \"fixme.js\" 5 4 --lsp\nquery_at_pos autocomplete \"fixme.js\" 8 5 --lsp\nquery_at_pos autocomplete \"fixme.js\" 14 8 --lsp\nquery_at_pos autocomplete \"fixme.js\" 18 12 --pretty\nquery_at_pos autocomplete \"fixme.js\" 21 10 --lsp\nquery_at_pos autocomplete \"jsdoc_comment.js\" 3 4 --lsp\nquery_at_pos autocomplete \"jsdoc_comment.js\" 8 4 --lsp\nquery_at_pos autocomplete \"jsdoc_comment.js\" 11 4 --lsp\nqueries_in_file autocomplete \"super_member.js\" --pretty\nqueries_in_file autocomplete \"switch.js\" --pretty\nqueries_in_file autocomplete \"keywords_c.js\" --pretty\nqueries_in_file autocomplete \"keywords_f.js\" --pretty\n", "num_lines": 154}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ntest_file(){\n  FILE=$1\n  echo \"> insert-type\" \"$@\"\n  assert_ok \"$FLOW\" autofix insert-type --in-place \"$@\"\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\ntest_file a.js 6 15\ntest_file b.js 6 15 --strategy=generalize\ntest_file c.js 6 15 --strategy=specialize\n\necho \"> flow status\"\nassert_errors \"$FLOW\" status --strip-root\n", "num_lines": 22}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp || rm tmp/*\ncp .flowconfig tmp/.flowconfig\nstart_flow tmp\n\ntest_file () {\n  local FILE=$1\n  cp \"$FILE\" \"tmp/$FILE\"\n\n  echo \"> autofix insert-type\" \"$@\"\n  assert_ok \"$FLOW\" autofix insert-type --in-place \"$@\"\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\ntest_file a.js 5 20 --strategy=generalize\ntest_file b.js 5 20 --strategy=specialize\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n\necho \"> flow status tmp\"\nassert_ok \"$FLOW\" status tmp\n\nassert_ok \"$FLOW\" stop tmp\n", "num_lines": 32}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp || rm tmp/*\ncp .flowconfig tmp/.flowconfig\nstart_flow tmp\n\nfix_missing_local_annot() {\n  FILE=$1; shift\n\n  cp \"$FILE\" \"tmp/$FILE\"\n\n  echo \"> flow autofix missing-local-annot $FILE\"\n  assert_ok \"$FLOW\" autofix missing-local-annot --in-place \"$FILE\"\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\ninsert_type () {\n  FILE=$1; shift\n\n  cp \"$FILE\" \"tmp/$FILE\"\n\n  while [[ $# -ge 4 ]]; do\n    local a1=$1; shift;\n    local a2=$1; shift;\n    local a3=$1; shift;\n    local a4=$1; shift;\n    echo \"> flow autofix insert-type $FILE $a1 $a2 $a3 $a4\"\n    assert_ok \"$FLOW\" autofix insert-type --in-place \"$FILE\" \"$a1\" \"$a2\" \"$a3\" \"$a4\"\n  done\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\nfix_missing_local_annot a.js\ninsert_type a.js 7 3 7 11\nfix_missing_local_annot b.js\nfix_missing_local_annot c.js\ninsert_type c.js 4 3 4 32    9 17 9 17\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n\necho \"> flow status tmp\"\nassert_ok \"$FLOW\" status tmp\n\nassert_ok \"$FLOW\" stop tmp\n", "num_lines": 54}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 3 20\necho \"> cat a.js\"\ncat a.js\n\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js.flow 3 20\necho \"> cat a.js.flow\"\ncat a.js.flow\n\nassert_ok \"$FLOW\" force-recheck a.js a.js.flow\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n", "num_lines": 18}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp || rm -r tmp/*\ncp -r .flowconfig lib tmp\nstart_flow tmp\n\ncp a.js tmp/a.js\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 6 18 6 23\nassert_ok \"$FLOW\" force-recheck a.js\necho \"> cat a.js\"\ncat a.js\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n\necho \"> flow status tmp\"\nassert_ok \"$FLOW\" status tmp\n\nassert_ok \"$FLOW\" stop tmp\n", "num_lines": 24}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp || rm tmp/*\ncp .flowconfig tmp/.flowconfig\nstart_flow tmp\n\ndo_file () {\n  FILE=$1; shift\n\n  cp \"$FILE\" \"tmp/$FILE\"\n\n  while [[ $# -ge 2 ]]; do\n    local a1=$1; shift;\n    local a2=$1; shift;\n    echo \"> flow autofix insert-type $FILE $a1 $a2\"\n    assert_ok \"$FLOW\" autofix insert-type --in-place \"$FILE\" \"$a1\" \"$a2\"\n  done\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\ndo_file a.js 3 20\ndo_file b.js 3 25\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\necho \"> flow status tmp\"\nassert_ok \"$FLOW\" status tmp\n\nassert_ok \"$FLOW\" stop tmp\n", "num_lines": 36}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# autofix doesn't try to control the order of unions\nupdate_in_place(){\n  local FILE=$1;\n  assert_ok \"$FLOW\" autofix insert-type --in-place \"$@\"\n  assert_ok \"$FLOW\" force-recheck \"$FILE\"\n  echo \"> cat $FILE\"\n  cat \"$FILE\"\n}\n\nupdate_in_place any-in-union.js 12 5\nupdate_in_place any-in-union.js 13 5\nupdate_in_place any-in-union.js 14 5\nupdate_in_place any-in-union.js 15 5\nupdate_in_place any-in-union.js 16 5\nupdate_in_place any-to-flowfixme-no-strict.js 4 20\nupdate_in_place any-to-flowfixme-strict-local.js 4 20\nupdate_in_place any-to-flowfixme-strict.js 4 20\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n", "num_lines": 27}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 5 18 5 21\necho \"> cat a.js\"\ncat a.js\nassert_ok \"$FLOW\" force-recheck a.js\necho \"> flow status\"\nassert_ok \"$FLOW\" status --strip-root\n", "num_lines": 13}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 6 9\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 7 9\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 8 9\nassert_ok \"$FLOW\" autofix insert-type --in-place a.js 9 9\necho \"> cat a.js\"\ncat a.js\nassert_ok \"$FLOW\" force-recheck a.js\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n", "num_lines": 16}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nspec_it () {\n  assert_ok \"$FLOW\" autofix insert-type --in-place --strategy=specialize \"$@\"\n}\n\nspec_it a.js 8 9\nspec_it a.js 10 9\nspec_it a.js 12 9\nspec_it a.js 14 9\nspec_it a.js 16 19\nspec_it a.js 18 19\nspec_it a.js 20 17\nspec_it a.js 22 17\nspec_it a.js 24 15\nspec_it a.js 26 9\nspec_it a.js 28 9\nspec_it a.js 30 19\nspec_it a.js 32 9\nspec_it a.js 34 9\nspec_it a.js 36 19\nspec_it a.js 38 14\nspec_it a.js 40 31\nspec_it a.js 44 9\n\n\necho \"> cat a.js\"\ncat a.js\nassert_ok \"$FLOW\" force-recheck a.js\n\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n", "num_lines": 37}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" autofix insert-type --in-place simplify-empty.js 3 28\necho \"> cat simplify-empty.js\"\ncat simplify-empty.js\nassert_ok \"$FLOW\" force-recheck simplify-empty.js\necho \"> flow status\"\nassert_ok \"$FLOW\" status\n", "num_lines": 13}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\nInit cannot be canceled\\\\n\"\n# Add a file which sleeps for 100s\ncp sleep.js.ignored sleep.js\n\n# Don't wait for init - this server is going to hang\nassert_ok \"$FLOW\" start . \\\n  --all --no-flowlib \\\n  --file-watcher \"none\" \\\n  --log-file \"$FLOW_LOG_FILE\" \\\n  --monitor-log-file \"$FLOW_MONITOR_LOG_FILE\"\n\nassert_ok \"$FLOW\" force-recheck sleep.js\n\n# This will timeout\nassert_exit 3 \"$FLOW\" status --timeout 5 --no-auto-start\n\nrm sleep.js\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\n\\\\nRecheck can be canceled\\\\n\"\n# Wait for init\nstart_flow .\n\n# Kick off a recheck which will hang for 100s\ncp sleep.js.ignored sleep.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start sleep.js\n\n# This will timeout\nassert_exit 3 \"$FLOW\" status --timeout 5 --no-auto-start\n\n# If we change sleep_dependent.js, the recheck will cancel. If we for some\n# reason fail to rollback the transaction, sleep.js will be missing from the\n# shared memory, so typechecking sleep_dependent.js will produce\n#\n# Internal error: uncaught exception: Utils_js.Key_not_found(\"LeaderHeap\", \".../cancelable_rechecks/sleep.js\")\n#\n# So this is intended to test that we ARE rolling back the transaction properly\necho \" \" >> sleep_dependent.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start sleep_dependent.js\n\n# This will timeout\nassert_exit 3 \"$FLOW\" status --timeout 5 --no-auto-start\n\n# Removing the file and canceling the recheck will unhang the server\nrm sleep.js sleep_dependent.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start sleep.js\nassert_errors \"$FLOW\" status --no-auto-start --timeout 5\n", "num_lines": 57}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2094\n\nprintf \"syntax_error.js\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root syntax_error.js < syntax_error.js\n\nprintf \"docblock_error.js\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root docblock_error.js < docblock_error.js\n\nprintf \"docblock_error_with_syntax_error.js\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root docblock_error_with_syntax_error.js < docblock_error_with_syntax_error.js\n\nprintf \"docblock_error_with_module_type_conflict.js\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root docblock_error_with_module_type_conflict.js < docblock_error_with_module_type_conflict.js\n\nprintf \"module_type_conflict.js\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root module_type_conflict.js < module_type_conflict.js\n\nprintf \"syntax_error.js (no filename)\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root < syntax_error.js\n\nprintf \"\\n\\nnot_flow.js\\n\\n\"\nassert_ok \"$FLOW\" check-contents --strip-root not_flow.js < not_flow.js\n\nprintf \"\\n\\nnot_flow.js with --all\\n\\n\"\nassert_errors \"$FLOW\" check-contents --strip-root --all not_flow.js < not_flow.js\n\nprintf \"\\n\\nunsaved_foo.js depends on bar.js which is still checked against foo.js\\n\\n\"\nassert_ok \\\n  $FLOW check-contents --strip-root foo.js < unsaved_foo.js\n\nprintf \"\\n\\nbad_exports.js\\n\\n\"\nassert_errors \\\n  $FLOW check-contents --strip-root bad_exports.js < bad_exports.js\n\nprintf \"\\n\\njson.json\\n\\n\"\nassert_ok \\\n  $FLOW check-contents --strip-root json.json < json.json\n", "num_lines": 50}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --show-all-errors --include-warnings --color=always\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --show-all-errors --include-warnings --color=always --unicode=always\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --include-warnings\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --include-warnings\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --show-all-errors --unicode=always\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --show-all-errors --message-width=120\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$1\" check . --all --no-flowlib --show-all-errors --message-width=40\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --strip-root --show-all-errors\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" check . --strip-root --show-all-errors\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"flow config check:\"\nassert_exit 8 \"$FLOW\" config check --pretty\n\necho\necho \"flow config check --ignore-version:\"\nassert_ok \"$FLOW\" config check --ignore-version --pretty\n", "num_lines": 13}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"Invalid flowconfig should fail\"\nassert_exit 8 \"$FLOW\" check 2>&1\n\necho\necho \"Invalid flowconfig should pass\"\nassert_ok \"$FLOW\" check --quiet --ignore-version 2>&1\n\necho\necho \"flow config check:\"\nassert_exit 8 \"$FLOW\" config check --pretty\n\necho\necho \"flow config check --ignore-version:\"\nassert_ok \"$FLOW\" config check --ignore-version --pretty\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"Invalid flowconfig should fail\"\nassert_exit 8 \"$FLOW\" check 2>&1\n\necho\necho \"Invalid flowconfig should pass\"\nassert_ok \"$FLOW\" check --quiet --ignore-version 2>&1\n\necho\necho \"flow config check:\"\nassert_exit 8 \"$FLOW\" config check --pretty\n\necho\necho \"flow config check --ignore-version:\"\nassert_ok \"$FLOW\" config check --ignore-version --pretty\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_exit 8 \"$FLOW\" config check 2>&1\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nFlowconfig should not be valid:\\n\";\nassert_exit 8 \"$FLOW\" check --strip-root --no-flowlib . 2>&1\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop 2> /dev/null > /dev/null\nfor i in $(seq 1 20); do\n  assert_ok \"$FLOW\" status 2> /dev/null > /dev/null &\ndone\nassert_ok \"$FLOW\" status\n", "num_lines": 12}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" get-def --strip-root --json ignore/test.js 3 2\nassert_ok \"$FLOW\" type-at-pos --strip-root --json ignore/test.js 3 2\nassert_ok \"$FLOW\" get-def --strip-root --json no_flow/test.js 3 2\nassert_ok \"$FLOW\" type-at-pos --strip-root --json no_flow/test.js 3 2\n", "num_lines": 11}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"coverage of declare module:\\n\"\nassert_ok \"$FLOW\" coverage --color declare_module.js\n\nprintf \"\\nshould not crash:\\n\"\nassert_ok \"$FLOW\" coverage --color crash.js\n\nprintf \"\\nshould terminate:\\n\"\nassert_ok \"$FLOW\" coverage --color non-termination.js\n\nprintf \"\\nerrors because not @flow:\\n\"\nassert_ok \"$FLOW\" coverage --quiet no_pragma.js 2>&1\n\nprintf \"\\nforces @flow:\\n\"\nassert_ok \"$FLOW\" coverage --quiet --all no_pragma.js 2>&1\n\n#\n# some more detailed tests:\n#\n\necho \"-----------------------------\"\necho \"call.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --strip-root --pretty call.js\n\necho \"-----------------------------\"\necho \"coverage.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --strip-root --pretty coverage.js\n\necho \"-----------------------------\"\necho \"any-refinement.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --strip-root --pretty any-refinement.js\n\necho \"-----------------------------\"\necho \"unicode.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --strip-root --pretty unicode.js\nassert_ok \"$FLOW\" coverage --color unicode.js\n\n\"$FLOW\" stop\n\"$FLOW\" start --trust-mode=check\necho \"-----------------------------\"\necho \"trust.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --show-trust --strip-root --pretty trust.js\nassert_ok \"$FLOW\" coverage --show-trust trust.js\n\n\"$FLOW\" stop\n\"$FLOW\" start --trust-mode=check\necho \"-----------------------------\"\necho \"tparam.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --show-trust --strip-root --pretty tparam.js\nassert_ok \"$FLOW\" coverage --show-trust tparam.js\n\n\"$FLOW\" stop\n\"$FLOW\" start --trust-mode=check\necho \"-----------------------------\"\necho \"tparam_import.js\"\necho \"-----------------------------\"\necho\nassert_ok \"$FLOW\" coverage --show-trust --strip-root --pretty tparam_import.js\nassert_ok \"$FLOW\" coverage --show-trust tparam_import.js\n", "num_lines": 77}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\nStart server in types-first mode\\\\n\"\nstart_flow .\n\nprintf \"\\\\nValue cycle should include both files\\\\n\"\nassert_ok \"$FLOW\" cycle --strip-root fileA.js\n\nprintf \"\\\\nType cycle should be empty\\\\n\"\nassert_ok \"$FLOW\" cycle --strip-root --types fileA.js\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\n\"\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nOVERLAPPING_FILES=\"\n  A.js\n  ExplicitProvidesModuleSameName.js\n  ImplicitProvidesModule.js\n  external/_d3/min.js\n  node_modules/qux/corge/lib/index.js\n  node_modules/qux/docblock.js\n\"\nDECL_FILES=\"$(echo \"$OVERLAPPING_FILES\" | sed -e \"s/\\.js/.js.flow/g\") ExplicitProvidesModuleDifferentNameDefinitions.js.flow\"\nIMPL_FILES=\"$OVERLAPPING_FILES ExplicitProvidesModuleDifferentName.js md5.js ws/index.js ws/test/client.js\"\n\nignore_files() {\n  for file in $1; do\n    mv \"$file\" \"$file.ignored\" 2>&1\n  done\n}\n\nuse_files() {\n  for file in $1; do\n    mv \"$file.ignored\" \"$file\" 2>&1\n  done\n}\n\nprintf \"======Start off with the .js files but without the .flow file======\\n\"\nassert_errors \"$FLOW\" status .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\n\nprintf \"\\n\\n======Start off with the .js files and the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nuse_files \"$DECL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\n\nprintf \"\\n\\n======Start off without the .js files and with the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nignore_files \"$IMPL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status .\nuse_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck $IMPL_FILES\nassert_errors \"$FLOW\" status .\nignore_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck $IMPL_FILES\nassert_errors \"$FLOW\" status .\n\n# reset\nuse_files \"$IMPL_FILES\"\nignore_files \"$DECL_FILES\"\n", "num_lines": 68}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nIMPL_FILES=\"\n  A.js\n  node_modules/test/Test.js\n\"\nDECL_FILES=\"$(echo \"$IMPL_FILES\" | sed -e \"s/\\.js/.js.flow/g\")\"\n\nignore_files() {\n  for file in $1; do\n    mv \"$file\" \"$file.ignored\" 2>&1\n  done\n}\n\nuse_files() {\n  for file in $1; do\n    mv \"$file.ignored\" \"$file\" 2>&1\n  done\n}\n\nprintf \"======Start off with the .js files but without the .flow file======\\n\"\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\n\\n======Start off with the .js files and the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nuse_files \"$DECL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\n\\n======Start off without the .js files and with the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nignore_files \"$IMPL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nuse_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\nignore_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck --no-auto-start $IMPL_FILES $DECL_FILES\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\n\n# reset\nuse_files \"$IMPL_FILES\"\nignore_files \"$DECL_FILES\"\n", "num_lines": 63}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nIMPL_FILES=\"\n  A.js\n  node_modules/B.js\n  node_modules/package_with_dir_main/dir/index.js\n  node_modules/package_with_full_main/code.js\n  node_modules/package_with_no_package_json/index.js\n  node_modules/package_with_partial_main/code.js\n\"\nDECL_FILES=$(echo \"$IMPL_FILES\" | sed -e \"s/\\.js/.js.flow/g\")\n\nignore_files() {\n  for file in $1; do\n    mv \"$file\" \"$file.ignored\"\n  done\n}\n\nuse_files() {\n  for file in $1; do\n    mv \"$file.ignored\" \"$file\"\n  done\n}\n\nprintf \"======Start off with the .js files but without the .flow file======\\n\"\nassert_errors \"$FLOW\" status .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\n\nprintf \"\\n\\n======Start off with the .js files and the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nuse_files \"$DECL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status .\nignore_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\n\nprintf \"\\n\\n======Start off without the .js files and with the .flow file======\\n\"\nassert_ok \"$FLOW\" stop .\nignore_files \"$IMPL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status .\nuse_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck $IMPL_FILES\nassert_errors \"$FLOW\" status .\nignore_files \"$IMPL_FILES\"\nassert_ok \"$FLOW\" force-recheck $IMPL_FILES\nassert_errors \"$FLOW\" status .\n\nprintf \"\\n\\n======Start off with neither .js files nor .flow files======\\n\"\nassert_ok \"$FLOW\" stop .\nignore_files \"$DECL_FILES\"\nstart_flow .\n\nassert_errors \"$FLOW\" status .\nuse_files \"$DECL_FILES\"\nassert_ok \"$FLOW\" force-recheck $DECL_FILES\nassert_errors \"$FLOW\" status .\n\n# reset\nuse_files \"$IMPL_FILES\"\nignore_files \"$DECL_FILES\"\n", "num_lines": 77}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\n\\\\nStart server in types-first mode\\\\n\"\nstart_flow .\n\nprintf \"\\\\nValue dep-graph should include both edges\\\\n\"\nassert_ok \"$FLOW\" graph dep-graph --strip-root --out types-first-values.log\ncat types-first-values.log\n\nprintf \"\\\\n\\\\nType dep-graph should include one edge\\\\n\"\nassert_ok \"$FLOW\" graph dep-graph --strip-root --types --out types-first-types.log\ncat types-first-types.log\n\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\n\"\n", "num_lines": 23}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status\n\n# make a change to dependency.js, to populate its direct dependents cache\nprintf \"\\n(123: number);\\n\" >> dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\n\n# delete dependent.js\nrm dependent.js\nassert_ok \"$FLOW\" force-recheck dependent.js\n\n# make another change to dependency.js. if this hits the direct dependents cache\n# it will think dependent is still there, and blow up.\nprintf \"\\n(123: number);\\n\" >> dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\n\nassert_ok \"$FLOW\" status --no-auto-start\n", "num_lines": 23}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nlog_file=\"$FLOW_TEMP_DIR/direct_dependent_files_cache.log\"\n\nstart_flow src\n\nprintf \"== Initial there should be 2 errors ==\\n\"\nassert_errors \"$FLOW\" status --no-auto-start src\n\nprintf \"\\n== Delete unrelated.js and now there is 1 error ==\\n\"\n# Unchanged during `ResolvedRequires`\nassert_ok mv src/unrelated{.js,.js.ignored}\nassert_ok \"$FLOW\" force-recheck src/unrelated.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Restore unrelated.js and back to 2 errors ==\\n\"\n# Unchanged during `ResolvedRequires`\nassert_ok mv src/unrelated{.js.ignored,.js}\nassert_ok \"$FLOW\" force-recheck src/unrelated.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Delete src/node_modules/dependency.js changes an error ==\\n\"\n# Changed during `ResolvedRequires`\nassert_ok mv src/node_modules/dependency{.js,.js.ignored}\nassert_ok \"$FLOW\" force-recheck src/node_modules/dependency.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Restore src/node_modules/dependency.js change it back ==\\n\"\n# Changed during `ResolvedRequires`\nassert_ok mv src/node_modules/dependency{.js.ignored,.js}\nassert_ok \"$FLOW\" force-recheck src/node_modules/dependency.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Remove the import from dependent.js ==\\n\"\n# Changed during `ResolvedRequires`\nassert_ok mv src/dependent{.js,.js.ignored}\nassert_ok echo \"// @flow\" > src/dependent.js\nassert_ok \"$FLOW\" force-recheck src/dependent.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Add the import back to dependent.js ==\\n\"\n# Changed during `ResolvedRequires`\nassert_ok mv src/dependent{.js.ignored,.js}\nassert_ok \"$FLOW\" force-recheck src/dependent.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\nprintf \"\\n== Adding code that doesn't import has no effect on dep graph ==\\n\"\n# Unchanged during `ResolvedRequires`\nassert_ok echo \"export var foo: boolean = 123\" >> src/node_modules/dependency.js\nassert_ok \"$FLOW\" force-recheck src/node_modules/dependency.js\n\nassert_errors \"$FLOW\" status --no-auto-start src\nprintf \"\\n\"\n\n\"$FLOW\" stop src 1> /dev/null 2>&1\n", "num_lines": 72}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nFocus a file in node_modules with a dependent also in node_modules.\\n\"\nassert_ok \"$FLOW\" force-recheck --focus node_modules/a.js\n\nprintf \"\\nBy focusing on a.js, we should force-check main.js, and only report\\n\"\nprintf \"errors there, not in node_modules.\\n\"\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 13}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status\n\n# make a change to dependency.js, to populate its direct dependents cache\nprintf \"\\n(123: number);\\n\" >> dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\n\n# add a parse error to dependent.js, making it untyped\nprintf \"\\nparse error\" >> dependent.js\nassert_ok \"$FLOW\" force-recheck dependent.js\n\n# make another change to dependency.js. if this hits the direct dependents cache\n# it will think dependent is still typed, and blow up.\nprintf \"\\n(123: number);\\n\" >> dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\n\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 23}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncoverage() {\n  echo \"-----------------------------\"\n  echo \"restart server\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" stop\n  assert_ok \"$FLOW\" start\n  echo \"-----------------------------\"\n  echo \"root\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root .\n  echo \"-----------------------------\"\n  echo \"folder\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root folder\n  echo \"-----------------------------\"\n  echo \"cycle\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root cycle\n  echo \"-----------------------------\"\n  echo \"match_coverage\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root match_coverage\n  echo \"-----------------------------\"\n  echo \"other_folder\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root other_folder\n  echo \"-----------------------------\"\n  echo \"folder/subfolder\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root folder/subfolder\n  echo \"-----------------------------\"\n  echo \"file list\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root a.js folder/d.js folder/subfolder/j.js\n  echo \"-----------------------------\"\n  echo \"file and dir list\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root a.js folder folder/d.js\n  echo \"-----------------------------\"\n  echo \"files\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root --input-file files.txt\n  echo \"-----------------------------\"\n  echo \"json\"\n  echo \"-----------------------------\"\n  assert_ok \"$FLOW\" batch-coverage --strip-root --json --pretty --input-file files.txt\n  echo \"-----------------------------\"\n  echo \"root info survives recheck\"\n  echo \"-----------------------------\"\n  assert_ok cp a.js.ignored a.js\n  assert_ok \"$FLOW\" force-recheck a.js\n  assert_ok \"$FLOW\" batch-coverage --strip-root --wait-for-recheck true .\n  echo \"-----------------------------\"\n  echo \"delete file\"\n  echo \"-----------------------------\"\n  assert_ok rm a.js\n  assert_ok \"$FLOW\" force-recheck a.js\n  assert_ok \"$FLOW\" batch-coverage --strip-root --wait-for-recheck true .\n  echo \"-----------------------------\"\n  echo \"parsed -> unparsed file\"\n  echo \"-----------------------------\"\n  assert_ok cp non_flow.js b.js\n  assert_ok \"$FLOW\" force-recheck b.js\n  assert_ok \"$FLOW\" batch-coverage --strip-root --wait-for-recheck true .\n}\n\ncoverage > coverage.log\n\ncat coverage.log\n", "num_lines": 76}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"/**\\r\\n * @providesModule crlf\\r\\n */\\r\\n\" > crlf.js\nprintf \"/**\\r\\n * @providesModule foo\\r\\n */\\r\\nrequire('crlf');\\r\\n\" > foo.js\n\"$FLOW\" force-recheck crlf.js foo.js\n\"$FLOW\" status\nrm crlf.js foo.js\n", "num_lines": 12}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" dump-types --strip-root --json --pretty test.js\n\necho \"=== predicates.js ===\"\nassert_ok \"$FLOW\" dump-types --strip-root --json --pretty predicates.js\n\necho \"=== type-destructors.js ===\"\nassert_ok \"$FLOW\" dump-types --strip-root type-destructors.js | grep '^type-destructors.js:7'\n\necho \"=== type-destructors.js (--evaluate-type-destructors) ===\"\nassert_ok \"$FLOW\" dump-types --strip-root --evaluate-type-destructors type-destructors.js | grep '^type-destructors.js:7'\n", "num_lines": 17}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" dump-types --strip-root --json --pretty test.js\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This test is primarily intended to test that Types_js.ensure_parsed properly\n# parses things which were not originally parsed due to saved_state\n\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\n# focusing file.js means its dependency, dependency.js, needs to be parsed\n# when using lazy mode + saved state.\nassert_ok \"$FLOW\" force-recheck --focus file.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed does not recheck unrelated dependent ====\\\\n\"\n# ensure_parsed included dependency.js, but does not fan out to dependency.js's\n# dependents (dependent.js).\nassert_ok \"$FLOW\" status --no-auto-start\n\nassert_ok \"$FLOW\" stop\nstart_flow .\n\n# modify dependency.js from what's in saved state, but don't tell the server\n# about it (an unexpected change). this simulates a race condition between\n# the file watcher and the server.\nprintf \"\\nexport const bar = 123;\\n\" >> dependency.js\n\nprintf \"==== No errors after restart====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\n# focusing file.js means its dependency, dependency.js, needs to be parsed\n# when using lazy mode + saved state.\nassert_ok \"$FLOW\" force-recheck --focus file.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed skips dependent ====\\\\n\"\n# ensure_parsed included dependency.js as a dependency update, which means\n# it does not fan out to dependency.js's dependents (dependent.js)\nassert_ok \"$FLOW\" status --no-auto-start\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\n# now simulate the file system event for dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\n\nprintf \"\\\\n\\\\n==== force-recheck checks dependent ====\\\\n\"\n# even though we've already partially processed the change to dependency.js\n# (updated the parsing heaps and the dep graph), its signature changed so we\n# need to recheck its dependents now.\nassert_errors \"$FLOW\" status --no-auto-start\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\n# now focus dependent.js (similar to opening it in an IDE)\nassert_ok \"$FLOW\" force-recheck --focus dependent.js\n\nprintf \"\\\\n\\\\n==== force-recheck on dependent finds errors ====\\\\n\"\nassert_errors \"$FLOW\" status --no-auto-start\n# should check dependent.js (0 of 1 skipped)\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n", "num_lines": 60}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This test is intended to complement the ensure_parsed_saved_state test and\n# demonstrate the different behavior of ensure_parsed when saved state is not\n# used\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\ncp B.js B.js.orig\ncp C.js C.js.orig\n\n# Simulate a file watcher race condition. Let's say it notices A.js changed\n# but not that B.js changed\ncp B.js.with_parse_error B.js\nassert_ok \"$FLOW\" force-recheck --focus A.js\n\nprintf \"\\\\n\\\\n==== Still don't notice the error ====\\\\n\"\n# The parse error should not be noticed yet. The server does recheck B.js, but\n# it will use the AST stored in shared memory. If we started up with saved state\n# we wouldn't have the AST in memory and would notice the error when we try to\n# read B.js from disk and parse it\nassert_ok \"$FLOW\" status --no-auto-start\n\nassert_ok \"$FLOW\" force-recheck --focus B.js\n\nprintf \"\\\\n\\\\n==== Now we see the parse error ====\\\\n\"\n# The parse error should now be noticed\nassert_errors \"$FLOW\" status --no-auto-start\n\n\n# Reset the parse error\ncp B.js.orig B.js\ncp C.js.with_new_dependency C.js\nassert_ok \"$FLOW\" force-recheck --focus A.js B.js # But not C.js\n\nprintf \"\\\\n\\\\n==== We don't see the unknown module exception yet ====\\\\n\"\n# The error should not be noticed yet. The server does recheck C.js, but\n# it will use the AST stored in shared memory. If we started up with saved state\n# we wouldn't have the AST in memory and would notice the error when we try to\n# read C.js from disk, parse it, and recheck the changed file\nassert_ok \"$FLOW\" status --no-auto-start\n\nassert_ok \"$FLOW\" force-recheck --focus C.js\n\nprintf \"\\\\n\\\\n==== Now we see the unknown module error ====\\\\n\"\n# The error should now be noticed\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 52}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status --no-auto-start\n\n# rename Dependency and make it slow, so we can interrupt the recheck\nmv dependency.js dependency.js.ignored\nmv dependency_slow.js.ignored dependency_slow.js\n\n# start a very slow recheck\nassert_ok \"$FLOW\" force-recheck dependency.js dependency_slow.js\n\nsleep 2\n\n# modify Dependency to cancel the recheck. we overwrite it with\n# the fast version, so the test doesn't take forever.\nmv dependency.js.ignored dependency_slow.js\n\nassert_ok \"$FLOW\" force-recheck dependency_slow.js\n\nassert_ok \"$FLOW\" status --no-auto-start\n", "num_lines": 25}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This test is primarily intended to test that Types_js.ensure_parsed properly\n# parses things which were not originally parsed due to saved_state\n\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\ncp B.js B.js.orig\ncp C.js C.js.orig\n\n# Simulate a file watcher race condition. Let's say it notices A.js changed\n# but not that B.js changed\ncp B.js.with_parse_error B.js\nassert_ok \"$FLOW\" force-recheck --focus A.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed notices that B has changed ====\\\\n\"\n# Focusing on A.js requires B.js to be checked, so ensure_parsed tries to\n# parse it. But it notices it has changed and triggers a recheck, which finds\n# the parse errors\nassert_errors \"$FLOW\" status --no-auto-start\n\n# Reset the parse error\ncp B.js.orig B.js\nassert_ok \"$FLOW\" stop\nstart_flow . --lazy-mode fs --file-watcher none\n\nprintf \"==== No errors after restart====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\ncp C.js.with_new_dependency C.js\ncp A.js.modified A.js\n# Tell the server that A.js has changed but don't tell it about C\nassert_ok \"$FLOW\" force-recheck --focus A.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed notices that C has changed ====\\\\n\"\n# Focusing on A.js requires C.js to be checked, so ensure_parsed tries to\n# parse it. But it notices it has changed and triggers a recheck, which finds\n# the error\nassert_errors \"$FLOW\" status --no-auto-start\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\n# simulate the file watcher event for C\nassert_ok \"$FLOW\" force-recheck C.js\n\nprintf \"\\\\n\\\\n==== after file watcher update ====\\\\n\"\nassert_errors \"$FLOW\" status --no-auto-start\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n", "num_lines": 53}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\nrm B.js\n\n# Simulate a file watcher race condition. Let's say A.js becomes focused, but the\n# file watcher has not yet noticed that B.js was removed.\nassert_ok \"$FLOW\" force-recheck --focus A.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed notices that B was removed ====\\\\n\"\n# Focusing on A.js requires B.js to be checked, so ensure_parsed tries to parse\n# it. But it notices it has been removed and triggers a recheck, which now knows\n# B is gone. With B gone, C should error.\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\nrm A.js\n\n# Simulate a file watcher race condition. Let's say B.js becomes focused, but the file watcher has not yet noticed that A.js was removed.\nassert_ok \"$FLOW\" force-recheck --focus B.js\n\nprintf \"\\\\n\\\\n==== ensure_parsed notices that A was removed ====\\\\n\"\n# Focusing on A.js requires B.js to be checked, so ensure_parsed tries to parse\n# it. But it notices it has been removed and triggers a recheck, which finds the\n# error\nassert_errors \"$FLOW\" status --no-auto-start --strip-root\n", "num_lines": 20}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nInvoking status with no offset-style argument:\\n\"\nassert_errors \"$FLOW\" status --pretty --strip-root\n\nprintf \"\\nInvoking status with utf8-bytes offset-style:\\n\"\nassert_errors \"$FLOW\" status --pretty --strip-root --offset-style utf8-bytes\n\nprintf \"\\nInvoking status with js-indices offset-style:\\n\"\nassert_errors \"$FLOW\" status --pretty --strip-root --offset-style js-indices\n\nprintf \"\\nInvoking check with no offset-style argument:\\n\"\nassert_errors \"$FLOW\" check --pretty --strip-root\n\nprintf \"\\nInvoking check with utf8-bytes offset-style:\\n\"\nassert_errors \"$FLOW\" check --pretty --strip-root --offset-style utf8-bytes\n\nprintf \"\\nInvoking check with js-indices offset-style:\\n\"\nassert_errors \"$FLOW\" check --pretty --strip-root --offset-style js-indices\n\nprintf \"\\nInvoking check-contents with no offset-style argument:\\n\"\n# check-contents returns 0 even when errors are present\nassert_ok \"$FLOW\" check-contents --pretty < foo.js\n\nprintf \"\\nInvoking check-contents with utf8-bytes offset-style:\\n\"\nassert_ok \"$FLOW\" check-contents --pretty --offset-style utf8-bytes < foo.js\n\nprintf \"\\nInvoking check-contents with js-indices offset-style:\\n\"\nassert_ok \"$FLOW\" check-contents --pretty --offset-style js-indices < foo.js\n\n# Make sure there's a newline at the end of the file\necho\n", "num_lines": 37}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nshow_eval_eval_fast_path() {\n  grep \"EvalT ~> EvalT fast path\" $1 | tail -n 1\n}\n\nprintf \"\\\\nServer should start in verbose mode\\\\n\"\nstart_flow . --verbose\nassert_ok \"$FLOW\" status --strip-root\nshow_eval_eval_fast_path \"$FLOW_LOG_FILE\"\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nshow_union_union_slow_path() {\n  grep \"UnionT ~> UnionT slow case\" $1 | tail -n 7\n}\n\nprintf \"\\\\nServer should start in verbose mode\\\\n\"\nstart_flow . --verbose\nassert_ok \"$FLOW\" status --strip-root\nshow_union_union_slow_path \"$FLOW_LOG_FILE\"\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" find-module --strip-root --json ./req test.js\nassert_ok \"$FLOW\" get-def --strip-root --json test.js 3 2\nassert_ok \"$FLOW\" get-def --strip-root --json test.js 2 10\nassert_ok \"$FLOW\" get-def --strip-root --json test.js 5 18\n", "num_lines": 11}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"flow fix\\n\"\nassert_ok \"$FLOW\" fix --strip-root\nprintf \"flow fix --error-codes method-unbinding\\n\"\nassert_ok \"$FLOW\" fix --error-codes method-unbinding --strip-root\n", "num_lines": 11}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\nassert_ok \"$FLOW\" stop --flowconfig-name configure-flow\n\nprintf \"\\\\nWe should use the all flag from configure-flow to find an error:\\\\n\"\nassert_errors \"$FLOW\" check --flowconfig-name configure-flow\n\nprintf \"\\\\nWe can start a server using the configure-flow file:\\\\n\"\nstart_flow . --flowconfig-name configure-flow\n\nprintf \"\\\\nAnd still find the error with flow status!:\\\\n\"\nassert_errors \"$FLOW\" status --flowconfig-name configure-flow\n\nprintf \"\\\\nWe can simultaneously start a server with the regular .flowconfig:\\\\n\"\nstart_flow .\n\nprintf \"\\\\nAnd still find the error with the original configure-flow config:\\\\n\"\nassert_errors \"$FLOW\" status --flowconfig-name configure-flow\n\nprintf \"\\\\nAnd not check any non @flow files using the .flowconfig config:\\\\n\"\nassert_ok \"$FLOW\" status\n\nassert_ok \"$FLOW\" stop\nassert_ok \"$FLOW\" stop --flowconfig-name configure-flow\n\nprintf \"\\\\nWe should be able to run status without start:\\\\n\"\nassert_errors \"$FLOW\" status --flowconfig-name configure-flow\n\nassert_ok \"$FLOW\" stop --flowconfig-name configure-flow\n\nprintf \"\\\\nWe should be able to run without any command specified:\\\\n\"\nassert_errors \"$FLOW\" --flowconfig-name configure-flow\n\nassert_ok \"$FLOW\" stop --flowconfig-name configure-flow\n", "num_lines": 40}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nShould detect that rollout groups sum to less than 100%%:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.pct_sum_too_low\" . 2>&1\n\nprintf \"\\nShould detect that rollout groups sum to more than 100%%:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.pct_sum_too_high\" . 2>&1\n\nprintf \"\\nDuplicate rollout names are banned:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.duplicate_rollout_names\" . 2>&1\n\nprintf \"\\nDuplicate group names are banned:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.duplicate_group_names\" . 2>&1\n\nprintf \"\\nRollout names may only contain [a-zA-Z0-9._]:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.bad_rollout_name\" . 2>&1\n\nprintf \"\\nGroup names may only contain [a-zA-Z0-9._]:\\n\";\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.bad_group_name\" . 2>&1\n\nprintf \"\\n100%% on should always be on:\\n\";\nassert_errors \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.100_pct_short_literals\" .\n\nprintf \"\\n0%% on should always be off:\\n\";\nassert_ok \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.0_pct_short_literals\" .\n\nprintf \"\\nUnknown rollout:\\n\"\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.unknown_rollout\" . 2>&1\n\nprintf \"\\nUnknown group:\\n\"\nassert_exit 8 \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.unknown_group\" . 2>&1\n\nprintf \"\\nDisable a .*.js ignore via rollout:\\n\"\nassert_errors \"$FLOW\" check \\\n    --strip-root --no-flowlib --flowconfig-name \".flowconfig.0_pct_ignore\" .\n", "num_lines": 50}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nStop any already-running server.\"\nassert_ok \"$FLOW\" stop .\n\nprintf \"\\nFull check:\\n\"\nassert_errors \"$FLOW\" check .\n\nprintf \"\\nFull focus-check:\\n\"\nassert_errors \"$FLOW\" check .\n\nprintf \"\\nFocused check on a file with local errors but no dependency or reverse dependency:\\n\"\nassert_errors \"$FLOW\" focus-check test.js\n\nprintf \"\\nFocused check on a file with no local errors but a dependency:\\n\"\nassert_errors \"$FLOW\" focus-check a.js\n\nprintf \"\\nFocused check on a file with no local errors but a reverse dependency:\\n\"\nassert_errors \"$FLOW\" focus-check b.js\n\nprintf \"\\nFocused check on two files with overlapping errors:\\n\"\nassert_errors \"$FLOW\" focus-check {a,b}.js\n\nprintf \"\\nFocused check on multiple files with disjoint sets of errors:\\n\"\nassert_errors \"$FLOW\" focus-check {a,b,test}.js\n\nprintf \"\\nFocused check on a file and a directory:\\n\"\nassert_errors \"$FLOW\" focus-check test.js dir\n\nprintf \"\\nFocused check on files specified in list.txt:\\n\"\nassert_errors \"$FLOW\" focus-check --input-file=list.txt\n\nprintf \"\\nFocused check guessing root by looking at first file:\\n\"\nassert_errors \"$FLOW\" focus-check other_root/other_root_file.js\n\nprintf \"\\nFocused check with explicit root:\\n\"\nassert_errors \"$FLOW\" focus-check --root . other_root/other_root_file.js\n\nprintf \"\\nFocused check with syntax error:\\n\"\nassert_errors \"$FLOW\" focus-check syntax.js\n\nprintf \"\\nDone!\\n\"\n", "num_lines": 47}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nNo errors:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start --strip-root\n\nprintf \"\\nFocusing the unparsed file shouldn't blow up:\\n\"\nassert_ok \"$FLOW\" force-recheck --focus --no-auto-start unparsed.js\n\nprintf \"\\nNo errors:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start --strip-root\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"===== force-recheck of a unchanged file does nothing: =====\\\\n\"\nassert_ok \"$FLOW\" force-recheck a.js\nassert_ok \"$FLOW\" status --no-auto-start\n\nprintf \"\\\\n===== force-recheck --focus of a unchanged file does a recheck: =====\\\\n\"\nassert_ok \"$FLOW\" force-recheck --focus a.js\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 14}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2094\n\n# Classes\nassert_errors \"$FLOW\" check-contents setter_class_missing_param.js < setter_class_missing_param.js\nqueries_in_file type-at-pos setter_class_missing_param.js --pretty\nassert_errors \"$FLOW\" check-contents setter_class_multiple_params.js < setter_class_multiple_params.js\nqueries_in_file type-at-pos setter_class_multiple_params.js --pretty\n\n# Interfaces\nassert_errors \"$FLOW\" check-contents setter_interface_missing_param.js < setter_interface_missing_param.js\nqueries_in_file type-at-pos setter_interface_missing_param.js --pretty\nassert_errors \"$FLOW\" check-contents setter_interface_multiple_params.js < setter_interface_multiple_params.js\nqueries_in_file type-at-pos setter_interface_multiple_params.js --pretty\n\n# Objects\nassert_errors \"$FLOW\" check-contents setter_object_missing_param.js < setter_object_missing_param.js\nqueries_in_file type-at-pos setter_object_missing_param.js --pretty\nassert_errors \"$FLOW\" check-contents setter_object_multiple_params.js < setter_object_multiple_params.js\nqueries_in_file type-at-pos setter_object_multiple_params.js --pretty\n\n# Object types\nassert_errors \"$FLOW\" check-contents setter_type_missing_param.js < setter_type_missing_param.js\nqueries_in_file type-at-pos setter_type_missing_param.js --pretty\nassert_errors \"$FLOW\" check-contents setter_type_multiple_params.js < setter_type_multiple_params.js\nqueries_in_file type-at-pos setter_type_multiple_params.js --pretty\n", "num_lines": 32}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" get-def example.js 12 10 --strip-root --json\n\n# foo;\n#  ^\nprintf \"use of const binding = \"\nassert_ok \"$FLOW\" get-def const.js 7 4 --strip-root --pretty\nprintf \"use of shadowed const binding = \"\nassert_ok \"$FLOW\" get-def const.js 10 2 --strip-root --pretty\n\nprintf \"let binding = \"\nassert_ok \"$FLOW\" get-def let.js 3 6 --strip-root --pretty\nprintf \"use of let binding = \"\nassert_ok \"$FLOW\" get-def let.js 7 4 --strip-root --pretty\nprintf \"use of shadowed let binding = \"\nassert_ok \"$FLOW\" get-def let.js 10 2 --strip-root --pretty\nprintf \"uninitialized let binding = \"\nassert_ok \"$FLOW\" get-def let.js 12 6 --strip-root --pretty\nprintf \"conditional write of let binding = \"\nassert_ok \"$FLOW\" get-def let.js 14 4 --strip-root --pretty\nprintf \"use of conditionally initialized let binding = \"\nassert_ok \"$FLOW\" get-def let.js 18 2 --strip-root --pretty\nprintf \"let binding initialized to member expression = \"\nassert_ok \"$FLOW\" get-def let.js 28 8 --strip-root --pretty\n\n# import thing from \"./exports_default.js\";\n#           ^\nprintf \"default import points to default export = \"\nassert_ok \"$FLOW\" get-def imports.js 3 10 --strip-root --pretty\n\n# import thing from \"./exports_default.js\";\n#               ^\nprintf \"default import points to source file (from keyword) = \"\nassert_ok \"$FLOW\" get-def imports.js 3 15 --strip-root --pretty\n\n# import thing from \"./exports_default.js\";\n#                        ^\nprintf \"import source points to source file = \"\nassert_ok \"$FLOW\" get-def imports.js 3 24 --strip-root --pretty\n\n# thing;\n#    ^\nprintf \"local reference points to default import = \"\nassert_ok \"$FLOW\" get-def imports.js 4 4 --strip-root --pretty\n\n# import {foo, bar as baz} from \"./helpers/exports_named.js\";\n#          ^\nprintf \"named import of const points to named export = \"\nassert_ok \"$FLOW\" get-def imports.js 6 10 --strip-root --pretty\n\nprintf \"named import of let points to named export = \"\nassert_ok \"$FLOW\" get-def imports.js 6 29 --strip-root --pretty\n\nprintf \"named import of var points to named export = \"\nassert_ok \"$FLOW\" get-def imports.js 6 40 --strip-root --pretty\n\nprintf \"named import of function points to named export = \"\nassert_ok \"$FLOW\" get-def imports.js 6 51 --strip-root --pretty\n\nprintf \"named import of class points to named export = \"\nassert_ok \"$FLOW\" get-def imports.js 6 56 --strip-root --pretty\n\n# import {foo, bar as baz} from \"./helpers/exports_named.js\";\n#                   ^\nprintf \"aliased named import points to named export (as) = \"\nassert_ok \"$FLOW\" get-def imports.js 6 19 --strip-root --pretty\n\n# import {foo, bar as baz} from \"./helpers/exports_named.js\";\n#               ^\nprintf \"aliased named import points to named export (remote name) = \"\nassert_ok \"$FLOW\" get-def imports.js 6 15 --strip-root --pretty\n\n# import {foo, bar as baz} from \"./helpers/exports_named.js\";\n#                      ^\nprintf \"aliased named import points to named export (local name) = \"\nassert_ok \"$FLOW\" get-def imports.js 6 22 --strip-root --pretty\n\n# foo;\n#  ^\nprintf \"local reference points to named import = \"\nassert_ok \"$FLOW\" get-def imports.js 7 2 --strip-root --pretty\n\n# baz;\n#  ^\nprintf \"local reference points to aliased named import = \"\nassert_ok \"$FLOW\" get-def imports.js 8 2 --strip-root --pretty\n\n# import * as things from \"./helpers/exports_named.js\";\n#          ^\nprintf \"namespaced import points to imported file (as) = \"\nassert_ok \"$FLOW\" get-def imports.js 10 11 --strip-root --pretty\n\n# import * as things from \"./helpers/exports_named.js\";\n#        ^\nprintf \"namespaced import points to imported file (remote name) = \"\nassert_ok \"$FLOW\" get-def imports.js 10 8 --strip-root --pretty\n\n# import * as things from \"./helpers/exports_named.js\";\n#               ^\nprintf \"namespaced import points to imported file (local name) = \"\nassert_ok \"$FLOW\" get-def imports.js 10 15 --strip-root --pretty\n\n# things;\n#    ^\nprintf \"local reference points to namespaced import = \"\nassert_ok \"$FLOW\" get-def imports.js 11 4 --strip-root --pretty\n\n# import type {DoesNotExist} from \"./doesNotExist\";\n#                ^\nprintf \"imports of non-existent module leads to error = \"\nassert_ok \"$FLOW\" get-def imports.js 14 17 --strip-root --pretty\n\n# const x: DoesNotExist<number> = \"foo\";\n#                ^\nprintf \"use of imports of non-existent module points to import loc = \"\nassert_ok \"$FLOW\" get-def imports.js 15 17 --strip-root --pretty\n\n# import * as test_lib from 'test_lib';\n#        ^\nprintf \"namespaced import points to declare module (remote name) = \"\nassert_ok \"$FLOW\" get-def imports.js 24 8 --strip-root --pretty\n\n# import * as test_lib from 'test_lib';\n#          ^\nprintf \"namespaced import points to declare module (as) = \"\nassert_ok \"$FLOW\" get-def imports.js 24 11 --strip-root --pretty\n\n# import * as test_lib from 'test_lib';\n#               ^\nprintf \"namespaced import points to declare module (local name) = \"\nassert_ok \"$FLOW\" get-def imports.js 24 15 --strip-root --pretty\n\n# import * as test_lib from 'test_lib';\n#                               ^\nprintf \"import source points to declare module = \"\nassert_ok \"$FLOW\" get-def imports.js 24 33 --strip-root --pretty\n\n# test_lib;\n#    ^\nprintf \"local reference points to declare module = \"\nassert_ok \"$FLOW\" get-def imports.js 25 4 --strip-root --pretty\n\n\n# import typeof typeof_thing from \"./helpers/exports_default.js\";\n#          ^\nprintf \"typeof default import (typeof) = \"\nassert_ok \"$FLOW\" get-def imports.js 27 10 --strip-root --pretty\n\n# import typeof typeof_thing from \"./helpers/exports_default.js\";\n#                   ^\nprintf \"typeof default import (local name) = \"\nassert_ok \"$FLOW\" get-def imports.js 27 19 --strip-root --pretty\n\n# (\"foo\": typeof_thing);\n#             ^\nprintf \"local reference of typeof default import = \"\nassert_ok \"$FLOW\" get-def imports.js 28 13 --strip-root --pretty\n\n\n# import typeof * as things_ns from \"./helpers/exports_named.js\";\n#        ^\nprintf \"typeof namespace import (typeof) = \"\nassert_ok \"$FLOW\" get-def imports.js 30 8 --strip-root --pretty\n\n# import typeof * as things_ns from \"./helpers/exports_named.js\";\n#                       ^\nprintf \"typeof namespace import (local name) = \"\nassert_ok \"$FLOW\" get-def imports.js 30 23 --strip-root --pretty\n\n# ({}: things_ns);\n#         ^\nprintf \"local reference of typeof namespace import = \"\nassert_ok \"$FLOW\" get-def imports.js 32 9 --strip-root --pretty\n\n\nprintf \"class name (should be itself) = \"\nassert_ok \"$FLOW\" get-def class.js 3 8 --strip-root --pretty\nprintf \"class property read = \"\nassert_ok \"$FLOW\" get-def class.js 13 6 --strip-root --pretty\nprintf \"class property write = \"\nassert_ok \"$FLOW\" get-def class.js 14 6 --strip-root --pretty\nprintf \"class methods = \"\nassert_ok \"$FLOW\" get-def class.js 15 6 --strip-root --pretty\nprintf \"refined class properties = \"\nassert_ok \"$FLOW\" get-def class.js 18 8 --strip-root --pretty\n# TODO get private properties working\nprintf \"private class property access = \"\nassert_ok \"$FLOW\" get-def class.js 7 15 --strip-root --pretty\nprintf \"private class property assignment = \"\nassert_ok \"$FLOW\" get-def class.js 8 15 --strip-root --pretty\nprintf \"members of maybe types = \"\nassert_ok \"$FLOW\" get-def class.js 22 5 --strip-root --pretty\nprintf \"members of unions with null/void = \"\nassert_ok \"$FLOW\" get-def class.js 26 5 --strip-root --pretty\n\nprintf \"member of a nonexistent imported type with type parameters = \"\nassert_ok \"$FLOW\" get-def imports.js 16 4 --strip-root --pretty\nprintf \"member of a type alias for \\`any\\` with type parameters = \"\nassert_ok \"$FLOW\" get-def imports.js 22 4 --strip-root --pretty\n\nprintf \"member of an object type alias = \"\nassert_ok \"$FLOW\" get-def objects.js 5 4 --strip-root --pretty\nprintf \"member of an unannotated object type = \"\nassert_ok \"$FLOW\" get-def objects.js 8 4 --strip-root --pretty\n\nprintf \"optional chain initial property = \"\nassert_ok \"$FLOW\" get-def optional_chaining.js 17 6 --strip-root --pretty\nprintf \"optional chain subsequent property = \"\nassert_ok \"$FLOW\" get-def optional_chaining.js 17 10 --strip-root --pretty\nprintf \"optional chain initial property of null = \"\nassert_ok \"$FLOW\" get-def optional_chaining.js 18 7 --strip-root --pretty\nprintf \"optional chain subsequent property of null = \"\nassert_ok \"$FLOW\" get-def optional_chaining.js 18 11 --strip-root --pretty\n\nprintf \"shorthand destructuring = \"\nassert_ok \"$FLOW\" get-def objects.js 11 11 --strip-root --pretty\nprintf \"non-shorthand destructuring = \"\nassert_ok \"$FLOW\" get-def objects.js 12 11 --strip-root --pretty\nprintf \"destructuring without type alias = \"\nassert_ok \"$FLOW\" get-def objects.js 14 11 --strip-root --pretty\n# This one should return itself\nprintf \"bogus array destructuring of an object = \"\nassert_ok \"$FLOW\" get-def objects.js 15 11 --strip-root --pretty\nprintf \"property access assigned to a variable = \"\nassert_ok \"$FLOW\" get-def objects.js 16 10 --strip-root --pretty\n\nprintf \"property access on the arg to the idx callback = \"\nassert_ok \"$FLOW\" get-def idx.js 12 25 --strip-root --pretty\nprintf \"nested property access on the arg to the idx callback = \"\nassert_ok \"$FLOW\" get-def idx.js 12 29 --strip-root --pretty\n\nprintf \"global (builtin) variable = \"\nassert_ok \"$FLOW\" get-def global.js 3 3 --strip-root --pretty\n\nprintf \"object destructuring key = \"\nassert_ok \"$FLOW\" get-def destructuring.js 5 9 --strip-root --pretty\nprintf \"object destructuring binding = \"\nassert_ok \"$FLOW\" get-def destructuring.js 5 14 --strip-root --pretty\n\nqueries_in_file \"get-def\" \"annot.js\"\nqueries_in_file \"get-def\" \"exports.js\" --pretty\nqueries_in_file \"get-def\" \"identifier.js\"\nqueries_in_file \"get-def\" \"literals.js\"\nqueries_in_file \"get-def\" \"require.js\"\nqueries_in_file \"get-def\" \"imports_from_cjs.js\"\nqueries_in_file \"get-def\" \"utilities.js\"\n", "num_lines": 252}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nqueries_in_file get-def \"destructuring.js\"\nqueries_in_file get-def \"assignment.js\"\nqueries_in_file get-def \"require.js\"\nqueries_in_file get-def \"react.js\"\nqueries_in_file get-def \"override.js\"\nqueries_in_file get-def \"import.js\"\nqueries_in_file get-def \"module_ref.js\"\nqueries_in_file get-def \"refinements.js\"\nqueries_in_file get-def \"declare.js\"\nqueries_in_file get-def \"static.js\"\nqueries_in_file get-def \"constructor.js\"\nqueries_in_file get-def \"utilities.js\"\n", "num_lines": 19}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nqueries_in_file \"get-def\" \"main.js\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nqueries_in_file \"get-def\" \"requires.js\" --strip-root --pretty\nqueries_in_file \"get-def\" \"types.js\" --strip-root --pretty\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"nothing\"\nassert_exit \"$EXIT_COULD_NOT_FIND_FLOWCONFIG\" \"$FLOW\" type-at-pos 3 5 < d0.js\n\necho \"with file\"\nassert_exit \"$EXIT_COULD_NOT_FIND_FLOWCONFIG\" \"$FLOW\" type-at-pos no-config/d1.js 3 5\n\necho \"with file and config\"\nassert_ok \"$FLOW\" type-at-pos --strip-root config/no-config/d2.js 3 5\n\necho \"with bad root directory\"\nassert_ok \"$FLOW\" type-at-pos --root ./config/no-config 3 5 < ./config/no-config/d2.js\n\necho \"with bad root directory, and file\"\nassert_ok \"$FLOW\" type-at-pos --strip-root --root ./config/no-config ./config/no-config/d2.js 3 5\n\necho \"with bad root directory, and file\"\nassert_ok \"$FLOW\" type-at-pos --strip-root --root ./config/no-config ./config/no-config/d2.js 3 5\n\necho \"with file batch coverage\"\nassert_ok \"$FLOW\" batch-coverage --strip-root ./config/no-config/d2.js\n\necho \"with bad root directory, and file batch coverage\"\nassert_exit \"$EXIT_COULD_NOT_FIND_FLOWCONFIG\" \"$FLOW\" batch-coverage --root ./config/no-config ./config/no-config/d2.js\n", "num_lines": 30}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"'package/sub' does not resolve:\\n\"\nassert_errors \"$FLOW\" status\necho\n\n# package.js and package/package.json are duplicate providers. we pick package.js,\n# which means `package/sub` doesn't resolve.\nprintf \"duplicate provider:\\n\"\nmv fixtures/package package\n# changing a package will restart the server, so update saved_state_file_changes\nif [ -f .flow.saved_state_file_changes ]; then\n  printf \"package/package.json\\npackage/index.js\\npackage/sub.js\\n\" > .flow.saved_state_file_changes\nfi\nassert_ok \"$FLOW\" force-recheck package/package.json package/index.js package/sub.js\nassert_errors \"$FLOW\" status\necho\n\n# changing `package` should force `test` to get rechecked -- this tests whether\n# `test` has the proper phantom dependents to notice that package/package.json is now\n# the provider.\nprintf \"'package/sub' module resolves to package:\\n\"\nmv package.js fixtures/package.js\nassert_ok \"$FLOW\" force-recheck package/package.json package/index.js package/sub.js package.js\nassert_errors \"$FLOW\" status\necho\n\nprintf \"'package/sub' does not resolve again:\\n\"\nmv package fixtures/package\nmv fixtures/package.js package.js\n# changing a package will restart the server, so update saved_state_file_changes\nif [ -f .flow.saved_state_file_changes ]; then\n  echo \"\" > .flow.saved_state_file_changes\nfi\nassert_ok \"$FLOW\" force-recheck package/package.json package/index.js package/sub.js package.js\nassert_errors \"$FLOW\" status\n", "num_lines": 41}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"'package' module resolves to file:\\n\"\nassert_errors \"$FLOW\" status\necho\n\nprintf \"duplicate provider:\\n\"\nmv fixtures/package package\n# changing a package will restart the server, so update saved_state_file_changes\nif [ -f .flow.saved_state_file_changes ]; then\n  printf \"package/package.json\\npackage/index.js\\n\" > .flow.saved_state_file_changes\nfi\nassert_ok \"$FLOW\" force-recheck package/package.json package/index.js\nassert_errors \"$FLOW\" status\necho\n\nprintf \"'package' module resolves to package:\\n\"\nmv package.js fixtures/package.js\nassert_ok \"$FLOW\" force-recheck package.js\nassert_errors \"$FLOW\" status\necho\n\nprintf \"duplicate provider:\\n\"\nmv fixtures/package.js package.js\nassert_ok \"$FLOW\" force-recheck package.js\nassert_errors \"$FLOW\" status\necho\n\nprintf \"'package' module resolves to file again:\\n\"\nmv package fixtures/package\n# changing a package will restart the server, so update saved_state_file_changes\nif [ -f .flow.saved_state_file_changes ]; then\n  echo \"\" > .flow.saved_state_file_changes\nfi\nassert_ok \"$FLOW\" force-recheck package/package.json package/index.js\nassert_errors \"$FLOW\" status\n", "num_lines": 41}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# The server starts in lazy mode. First trigger a slow recheck.\n# This will check slow_dependent and dependency.\nprintf \"\\nTrigger a slow recheck: \"\nassert_ok \"$FLOW\" force-recheck --focus slow_dependent.js\nprintf \"DONE\\n\"\n\n# Sleep for a bit to give the recheck a chance to actually start\n# rechecking the file (vs calculating deps, etc).\nprintf \"\\nSleep: \"\nsleep 1\nprintf \"DONE\\n\"\n\nstart_time=$(date +\"%s.%N\")\n\n# While that's running, try to get-def on fast_dependent, which\n# also needs dependency. It should cancel the slow recheck and\n# answer quickly.\nprintf \"\\nGet-def with unchecked dependency:\\n\"\nassert_ok \"$FLOW\" get-def fast_dependent.js 5 2 --strip-root --json\n\nprintf \"\\nDid it finish in less than 2 seconds? \"\nend_time=$(date +\"%s.%N\")\necho \"$start_time $end_time\" | awk '{ s=$1; e=$2; print ((e - s) < 2) ? \"YES\" : \"NO\"; }'\n\n# Then the slow recheck should restart and eventually finish.\nprintf \"\\nOriginal recheck finished:\\n\"\nassert_errors \"$FLOW\" status --no-auto-start\n", "num_lines": 34}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC2094\n\nprintf \"==== No errors at start====\\\\n\"\nassert_ok \"$FLOW\" status --no-auto-start\n\n# simulate a file watcher race condition by changing dependency.js without\n# a force-recheck.\nprintf \"\\\\n\\\\nexport const y = 123;\\\\n\" >> dependency.js\n\n# checking file.js needs dependency.js, and we notice it's changed. we have\n# to re-merge it, but check-contents doesn't wait for dependent.js to be checked.\nprintf \"\\\\n==== Checking file.js finds errors ====\\\\n\"\nassert_errors \"$FLOW\" check-contents --strip-root file.js < file.js\n# 1 file should be merged (dependency) and nothing should be checked\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n\n# here's the late file watcher update\nassert_ok \"$FLOW\" force-recheck dependency.js\n\n# even though we've already noticed the update, now is when we actually\n# recheck dependency.js and its dependents, and find the error in\n# dependent.js\nprintf \"\\\\n==== force-recheck checks dependent ====\\\\n\"\nassert_errors \"$FLOW\" status --no-auto-start\n# 3 files (dependency.js and its dependents, dependent.js and file.js) should\n# be both merged and checked\nshow_skipping_stats \"$FLOW_LOG_FILE\"\n", "num_lines": 34}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"Without --include-suppressed\\n\"\nassert_errors \"$FLOW\" check --all --strip-root\n\nprintf \"\\n\\nWith --include-suppressed\\n\"\nassert_errors \"$FLOW\" check --all --strip-root --include-suppressed\n\nprintf \"\\n\\nJSON without --include-suppressed\\n\"\nassert_errors \\\n  \"$FLOW\" check --all --strip-root --json --pretty \\\n  | grep -v '^ *\"flowVersion\":.*'\n\nprintf \"\\n\\nJSON with --include-suppressed\\n\"\nassert_errors \\\n  \"$FLOW\" check --all --strip-root --include-suppressed --json --pretty \\\n  | grep -v '^ *\"flowVersion\":.*'\n\nprintf \"\\n\\nServer without --include-suppressed\\n\"\n\"$FLOW\" start --wait --all\nassert_errors \"$FLOW\" status --no-auto-start\n\"$FLOW\" stop\n\nprintf \"\\n\\nServer with --include-suppressed\\n\"\n\"$FLOW\" start --wait --all --include-suppressed\nassert_errors \"$FLOW\" status --no-auto-start\n\"$FLOW\" stop\n\nprintf \"\\n\"\n", "num_lines": 34}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"Without --include-warnings\\n\"\nassert_errors \"$FLOW\" check --all --strip-root\n\nprintf \"\\n\\nWith --include-warnings\\n\"\nassert_errors \"$FLOW\" check --all --strip-root --include-warnings\n\nprintf \"\\n\\nJSON without --include-warnings\\n\"\nassert_errors \"$FLOW\" check --all --strip-root --pretty \\\n  | grep -v '^ *\"flowVersion\":.*'\n\nprintf \"\\n\\nJSON with --include-warnings\\n\"\nassert_errors \"$FLOW\" check --all --strip-root --include-warnings --pretty \\\n  | grep -v '^ *\"flowVersion\":.*'\n\nprintf \"\\n\"\n", "num_lines": 22}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nprintf \"EMPTY FLOWCONFIG\\n\"\nassert_ok \"$FLOW\" stop\ncp empty_flowconfig .flowconfig\nstart_flow .\n\nprintf \"\\n\\nCheck Without --include-warnings\\n\"\nassert_errors \"$FLOW\" check --strip-root\n\nprintf \"\\n\\nCheck With --include-warnings\\n\"\nassert_errors \"$FLOW\" check --strip-root --include-warnings\n\nprintf \"\\n\\nCheck-contents Without --include-warnings\\n\"\nassert_errors \"$FLOW\" check-contents test.js --strip-root < test.js\n\nprintf \"\\n\\nCheck-contents With --include-warnings\\n\"\nassert_errors \"$FLOW\" check-contents test.js --strip-root --include-warnings < test.js\n\nprintf \"\\n\\nStatus Without --include-warnings\\n\"\nassert_errors \"$FLOW\" status --strip-root\n\nprintf \"\\n\\nStatus With --include-warnings\\n\"\nassert_errors \"$FLOW\" status --strip-root --include-warnings\n\n\n\nprintf \"\\n\\n\\n\\nINCLUDE_WARNINGS FLOWCONFIG\\n\"\nassert_ok \"$FLOW\" stop\ncp include_warnings_flowconfig .flowconfig\nstart_flow .\n\nprintf \"\\n\\nCheck Without --include-warnings\\n\"\nassert_errors \"$FLOW\" check --strip-root\n\nprintf \"\\n\\nCheck With --include-warnings\\n\"\nassert_errors \"$FLOW\" check --strip-root --include-warnings\n\nprintf \"\\n\\nCheck-contents Without --include-warnings\\n\"\nassert_errors \"$FLOW\" check-contents test.js --strip-root < test.js\n\nprintf \"\\n\\nCheck-contents With --include-warnings\\n\"\nassert_errors \"$FLOW\" check-contents test.js --strip-root --include-warnings < test.js\n\nprintf \"\\n\\nStatus Without --include-warnings\\n\"\nassert_errors \"$FLOW\" status --strip-root\n\nprintf \"\\n\\nStatus With --include-warnings\\n\"\nassert_errors \"$FLOW\" status --strip-root --include-warnings\n", "num_lines": 55}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp ./*.js tmp/\nassert_errors \"$FLOW\" status .\ncp tmp1/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\ncp tmp2/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\ncp tmp3/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\nmv tmp/*.js ./\nrmdir tmp\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp ./*.js tmp/\nassert_errors \"$FLOW\" status .\ncp tmp1/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\ncp tmp2/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\ncp tmp3/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors \"$FLOW\" status .\nmv tmp/*.js ./\nrmdir tmp\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\n\nprintf \"\\nInitial status:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start .\ncp A.js tmp/\n\nprintf \"\\nClear A.js:\\n\"\ncp tmp1/A.js A.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore A.js:\\n\"\nmv tmp/A.js A.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js\nassert_ok \"$FLOW\" status --no-auto-start .\n\nrmdir tmp\nprintf \"\\nDone!\\n\"\n", "num_lines": 25}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp foo.js tmp/\n\nprintf \"\\nInitial status...with type errors:\\n\"\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete foo.js (cannot resolve module!):\\n\"\nrm foo.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore foo.js (same as initial status):\\n\"\ncp tmp/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRemove @flow in foo.js:\\n\"\ncp tmp1/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore foo.js (same as initial status):\\n\"\ncp tmp/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nIntroduce parse error in foo.js (unexpected identifier!):\\n\"\ncp tmp2/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore foo.js (same as initial status):\\n\"\ncp tmp/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nrm tmp/foo.js\nrmdir tmp\nprintf \"\\nDone!\\n\"\n", "num_lines": 46}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\n\nprintf \"\\nInitial status:\\n\"\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete c.js:\\n\"\nmv c.js tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start c.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete b.js:\\n\"\nmv b.js tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start b.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore b.js:\\n\"\nmv tmp/b.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start b.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore c.js:\\n\"\nmv tmp/c.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start c.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete d.json:\\n\"\nmv d.json tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start d.json\nassert_errors \"$FLOW\" status --no-auto-start .\n\nmv tmp/d.json .\n\nprintf \"\\nDelete unchecked.js:\\n\"\nmv unchecked.js tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start unchecked.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore unchecked.js:\\n\"\nmv tmp/unchecked.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start unchecked.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete dupe2.js:\\n\"\nmv dupe2.js tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start dupe2.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore dupe2.js:\\n\"\nmv tmp/dupe2.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start dupe2.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nrmdir tmp\nprintf \"\\nDone!\\n\"\n", "num_lines": 61}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nrm foo.js\nrm bar.js\nmv baz.js.tmp baz.js\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js bar.js baz.js\nassert_errors \"$FLOW\" status --no-auto-start\n\nrm baz.js\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start baz.js\nassert_ok \"$FLOW\" status --no-auto-start\n", "num_lines": 18}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# server is auto-started\n\nrm b.js\n\nassert_ok \"$FLOW\" force-recheck --focus b.js\n\nassert_errors \"$FLOW\" status --strip-root --no-auto-start\n", "num_lines": 14}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nInitial status:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nCopy A.js to B.js:\\n\"\ncp A.js B.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start B.js\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nDelete A.js:\\n\"\nrm A.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js\nassert_ok \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nMove B.js to A.js:\\n\"\nmv B.js A.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js B.js\nassert_ok \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nDone!\\n\"\n", "num_lines": 26}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status\n\ncp a.js.after a.js\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start a.js b.js\n\nassert_errors \"$FLOW\" status\n", "num_lines": 14}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" status\n\ncp a.js.after a.js\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start a.js b.js\n\nassert_errors \"$FLOW\" status\n", "num_lines": 14}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" status\n\ncp a.js.after a.js\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start a.js b.js\n\nassert_ok \"$FLOW\" status\n", "num_lines": 14}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp ./*.js tmp/\n\nprintf \"Initial status:\\n\"\nassert_errors $FLOW status --no-auto-start --strip-root .\n\nprintf \"\\nChange .js file:\\n\"\ncp tmp1/*.js ./\nassert_ok \"$FLOW\" force-recheck ./*.js # overapproximation\nassert_errors $FLOW status --no-auto-start --strip-root .\n\nmv tmp/*.js ./\nrmdir tmp\n", "num_lines": 20}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nInitial status:\\n\"\nassert_ok $FLOW status --no-auto-start --strip-root .\n\nprintf \"\\nMove A.js to B.js (excluded):\\n\"\nmv A.js B.js\nsed -i -e \"s/require('A')/require('B')/g\" index.js\nassert_ok $FLOW force-recheck --no-auto-start A.js B.js index.js\nassert_errors $FLOW status --no-auto-start --strip-root .\n\nprintf \"\\nMove B.js to A.js:\\n\"\nmv B.js A.js\nsed -i -e \"s/require('B')/require('A')/g\" index.js\nassert_ok $FLOW force-recheck --no-auto-start A.js B.js index.js\nassert_ok $FLOW status --no-auto-start --strip-root .\n\nprintf \"\\nDone!\\n\"\n", "num_lines": 23}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nInitial status:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nCopy A.js to B.js:\\n\"\ncp A.js B.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js B.js\nassert_errors \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nMove B.js to A.js:\\n\"\nmv B.js A.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start A.js B.js\nassert_ok \"$FLOW\" status --no-auto-start --strip-root .\n\nprintf \"\\nDone!\\n\"\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\nInitial status:\\n\"\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nIntroduce haste module \\\"foo\\\"\\n\"\ncp tmp/foo.js foo.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRemove haste module \\\"foo\\\"\\n\"\nrm foo.js\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDone!\\n\"\n", "num_lines": 21}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" status\n\n# We change baz's re-export from ./foo to an identical ./bar, which causes qux's\n# re-export to change, which affects the error printed in thud, since it now\n# needs to point to bar.js instead of foo.js\nmv baz.js.after baz.js\nassert_ok \"$FLOW\" force-recheck baz.js\n\nassert_errors \"$FLOW\" status\n", "num_lines": 16}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start a.js\nassert_ok \"$FLOW\" status --no-auto-start .\n\ncp tmp/b.js ./\ntrap 'rm b.js' EXIT\n\nassert_ok \"$FLOW\" force-recheck --no-auto-start b.js\nassert_errors \"$FLOW\" status --no-auto-start .\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\ncp root.js tmp/\n\nassert_errors \"$FLOW\" status .\ncp tmp1/root.js ./\nassert_ok \"$FLOW\" force-recheck root.js\nassert_errors \"$FLOW\" status .\n\nmv tmp/root.js ./\nrmdir tmp\n", "num_lines": 17}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir tmp\n\nprintf \"\\nInitial status:\\n\"\nassert_ok \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nDelete non-@flow file foo.js:\\n\"\nmv foo.js tmp\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_errors \"$FLOW\" status --no-auto-start .\n\nprintf \"\\nRestore non-@flow file foo.js:\\n\"\nmv tmp/foo.js .\nassert_ok \"$FLOW\" force-recheck --no-auto-start foo.js\nassert_ok \"$FLOW\" status --no-auto-start .\n\nrmdir tmp\nprintf \"\\nDone!\\n\"\n", "num_lines": 24}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n. ../fs.sh\nmkdir -p tmp/node_modules\nprintf \"\\nShould resolve to dir/node_modules/b.js which is number\\n\"\nassert_errors \"$FLOW\" status .\nprintf \"\\nShould resolve to node_modules/b.js which is a string\\n\"\nmove dir/node_modules/b.js tmp/node_modules/b.js\nassert_errors \"$FLOW\" status .\nprintf \"\\nShould resolve to dir/node_modules/b.js which is number\\n\"\nmove tmp/node_modules/b.js dir/node_modules/b.js\nassert_errors \"$FLOW\" status .\nrm -r tmp\n", "num_lines": 18}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" status\n\n# We move a.js, which provides HasteName, to a different path, which causes b.js\n# to be rechecked, but we also need to recheck c.js because the error found in c\n# now needs to point to bar/a.js instead of foo/a.js\nmv foo/a.js bar/a.js\nassert_ok \"$FLOW\" force-recheck foo/a.js bar/a.js\n\nassert_errors \"$FLOW\" status\n", "num_lines": 16}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nrm .flowconfig\nassert_ok \"$FLOW\" init\n\nprintf \"Default .flowconfig should typecheck:\\n\"\nassert_ok \"$FLOW\" check\n\nprintf \"\\nDefault .flowconfig looks like this:\\n\"\ncat .flowconfig\n", "num_lines": 15}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmv bar.js _bar.js\nassert_ok $FLOW force-recheck --root . bar.js _bar.js\nassert_errors $FLOW status .\nmv _bar.js bar.js\n", "num_lines": 11}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" stop\n\nassert_errors \"$FLOW\" check --no-flowlib .\n\necho \"{\" > package.json\necho\necho \"============================================\"\necho \"Parse error in package.json will be reported\"\necho \"============================================\"\nassert_errors \"$FLOW\" check --no-flowlib .\n", "num_lines": 17}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\necho \"flow check --json-version=2\"\nassert_errors \"$FLOW\" check . --strip-root --json-version=2\necho \"\"\necho \"\"\n\necho \"flow check --json-version=2 --json\"\nassert_errors \"$FLOW\" check . --strip-root --json-version=2 --json\necho \"\"\necho \"\"\n\necho \"flow check --json-version=2 --pretty\"\nassert_errors \"$FLOW\" check . --strip-root --json-version=2 --pretty\necho \"\"\necho \"\"\n\necho \"flow focus-check test.js --json-version=2\"\nassert_errors \"$FLOW\" focus-check test.js --strip-root --json-version=2\necho \"\"\necho \"\"\n\necho \"flow focus-check test.js --json-version=2 --json\"\nassert_errors \"$FLOW\" focus-check test.js --strip-root --json-version=2 --json\necho \"\"\necho \"\"\n\necho \"flow focus-check test.js --json-version=2 --pretty\"\nassert_errors \"$FLOW\" focus-check test.js --strip-root --json-version=2 --pretty\necho \"\"\necho \"\"\n\necho \"flow check-contents --json-version=2 < test.js\"\nassert_ok \"$FLOW\" check-contents --json-version=2 < test.js\necho \"\"\necho \"\"\n\necho \"flow check-contents --json-version=2 --json < test.js\"\nassert_ok \"$FLOW\" check-contents --json-version=2 --json < test.js\necho \"\"\necho \"\"\n\necho \"flow check-contents --json-version=2 --pretty < test.js\"\nassert_ok \"$FLOW\" check-contents --json-version=2 --pretty < test.js\necho \"\"\necho \"\"\n\necho \"flow status --json-version=2\"\nassert_errors \"$FLOW\" status . --strip-root --json-version=2\necho \"\"\necho \"\"\n\necho \"flow status --json-version=2 --json\"\nassert_errors \"$FLOW\" status . --strip-root --json-version=2 --json\necho \"\"\necho \"\"\n\necho \"flow status --json-version=2 --pretty\"\nassert_errors \"$FLOW\" status . --strip-root --json-version=2 --pretty\necho \"\"\n", "num_lines": 66}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_exit \"$EXIT_COULD_NOT_FIND_FLOWCONFIG\" \\\n  \"$FLOW\" check --json pants\n\nassert_exit \"$EXIT_COULD_NOT_FIND_FLOWCONFIG\" \\\n  \"$FLOW\" check --pretty pants\n\nassert_exit \"$EXIT_USAGE\" \\\n  \"$FLOW\" check --json --pants\n\nassert_exit \"$EXIT_USAGE\" \\\n  \"$FLOW\" check --pretty --pants\n", "num_lines": 18}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\\\nA full check should ignore the lazy mode in the .flowconfig\\\\n\"\nassert_errors \"$FLOW\" check --strip-root\n\nprintf \"\\\\nServer should start in fs lazy mode\\\\n\"\nstart_flow .\nassert_ok \"$FLOW\" status --strip-root\n\nprintf \"\\\\nEditing a file should cause fs lazy mode to focus on the file\\\\n\"\necho \" \" >> foo.js\nassert_ok \"$FLOW\" force-recheck foo.js\nassert_errors \"$FLOW\" status --strip-root\nassert_ok \"$FLOW\" stop\n\nprintf \"\\\\nServer should start in non-lazy mode due to --lazy-mode none\\\\n\"\nstart_flow . --lazy-mode none\nassert_errors \"$FLOW\" status --strip-root\nassert_ok \"$FLOW\" stop\n", "num_lines": 24}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\\\nServer should start in fs lazy mode\\\\n\"\nstart_flow . --lazy-mode fs\n\nassert_ok \"$FLOW\" status --strip-root\n\nprintf \"\\\\nFocus a file\\\\n\"\nassert_ok \"$FLOW\" force-recheck --focus foo.js\nassert_errors \"$FLOW\" status --strip-root\n\nprintf \"\\\\nEdit a dependency\\\\n\"\ncp tmp1/node_modules_bar_index.js node_modules/bar/index.js\nassert_ok \"$FLOW\" force-recheck node_modules/bar/index.js\nassert_ok \"$FLOW\" status --strip-root\n\nprintf \"\\\\nRevert edit\\\\n\"\ncp tmp2/node_modules_bar_index.js node_modules/bar/index.js\nassert_ok \"$FLOW\" force-recheck node_modules/bar/index.js\nassert_errors \"$FLOW\" status --strip-root\n\nassert_ok \"$FLOW\" stop\n", "num_lines": 27}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\\\nServer should start in fs lazy mode\\\\n\"\nstart_flow . --lazy-mode fs\n\nassert_ok \"$FLOW\" status --strip-root\n\necho\n\nassert_ok \"$FLOW\" get-def --strip-root bar.js 5 2\n\nassert_ok \"$FLOW\" stop\n", "num_lines": 17}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"\\\\nServer should start in fs lazy mode\\\\n\"\nstart_flow . --lazy-mode fs\n\nassert_ok \"$FLOW\" status --strip-root\n\nprintf \"\\\\nFocus a file\\\\n\"\nassert_ok \"$FLOW\" force-recheck --focus focused.js\nassert_errors \"$FLOW\" status --strip-root\n\nprintf \"\\\\nEdit a dependency\\\\n\"\ncp tmp1/dependency.js dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\nassert_ok \"$FLOW\" status --strip-root\n\nprintf \"\\\\nRevert edit\\\\n\"\ncp tmp2/dependency.js dependency.js\nassert_ok \"$FLOW\" force-recheck dependency.js\nassert_errors \"$FLOW\" status --strip-root\n\nassert_ok \"$FLOW\" stop\n", "num_lines": 27}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"============================================\"\necho \"No warnings:\"\necho \"============================================\"\nassert_errors \"$FLOW\" check --no-flowlib\n\necho \"\"\necho \"============================================\"\necho \"With warnings:\"\necho \"============================================\"\nassert_errors \"$FLOW\" check --no-flowlib --include-warnings\n", "num_lines": 17}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --all --lints \"all=error\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --all --lints \"sketchy-null=error\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --all --lints \"\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" check . --all --lints \"\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" check . --all --lints \"all=off\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_ok \"$FLOW\" check . --all --lints \"sketchy-null=off\"\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"After start:\\n\"\nassert_ok \"$FLOW\" status .\n\ncp test1.js.fixture test.js\nprintf \"\\nAfter introducing a lint error:\\n\"\nassert_ok \"$FLOW\" force-recheck test.js\nassert_errors \"$FLOW\" status .\n\ncp test2.js.fixture test.js\nprintf \"\\nAfter suppressing the lint error:\\n\"\nassert_ok \"$FLOW\" force-recheck test.js\nassert_ok \"$FLOW\" status .\n\ncp test3.js.fixture test.js\nprintf \"\\nAfter fixing the lint error, leaving the suppression:\\n\"\nassert_ok \"$FLOW\" force-recheck test.js\nassert_ok \"$FLOW\" status . # 0 errors & 1 warning\n\ncp test4.js.fixture test.js\nprintf \"\\nAfter removing the unused suppression:\\n\"\nassert_ok \"$FLOW\" force-recheck test.js\nassert_ok \"$FLOW\" status .\n", "num_lines": 29}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_exit \"$EXIT_USAGE\" \\\n  \"$FLOW\" check . --all --lints \"sketchy-null=error,all=off\"\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_exit \"$EXIT_USAGE\" \\\n  \"$FLOW\" check . --all --lints \"sketchy-null=error,sketchy-null-bool=error\"\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_exit \"$EXIT_USAGE\" \\\n  \"$FLOW\" check . --all --lints \"sketchy-null-bool=error,sketchy-null=off\"\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --all --include-warnings --color always\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" check . --all --include-warnings --pretty --strip-root \\\n  | grep -v '^ *\"flowVersion\":.*'\n", "num_lines": 9}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nassert_errors \"$FLOW\" status --include-warnings --strip-root --from vim\n", "num_lines": 8}
{"repo_name": "flow", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nprintf \"Without --include-suppressed:\\n\"\nassert_ok \"$FLOW\" check\nprintf \"With --include-suppressed:\\n\"\nassert_errors \"$FLOW\" check --include-suppressed --strip-root\n", "num_lines": 11}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is just a simple wrapper around the\n# build/fbcode_builder/getdeps.py script.\n#\n# Feel free to invoke getdeps.py directly to have more control over the build.\n\nSCRIPT_DIR=$(dirname \"${BASH_SOURCE[0]}\")\nGETDEPS_PATHS=(\n    \"$SCRIPT_DIR/build/fbcode_builder/getdeps.py\"\n    \"$SCRIPT_DIR/../../opensource/fbcode_builder/getdeps.py\"\n)\nfor getdeps in \"${GETDEPS_PATHS[@]}\"; do\n    if [[ -x \"$getdeps\" ]]; then\n        exec \"$getdeps\" build folly \"$@\"\n    fi\ndone\necho \"Could not find getdeps.py\" >&2\nexit 1\n", "num_lines": 33}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -x\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# The only prerequisite should be homebrew. If something doesn't work out of\n# the box with just homebrew, let's fix it.\n\n# fail fast\nset -e\n\nBUILD_DIR=${BUILD_DIR:-_build}\n\n# brew install alias\nbrew_install() {\n    brew install \"$@\" || brew upgrade \"$@\"\n}\n\n# install deps\ninstall_deps() {\n    # folly deps\n    dependencies=(\n        boost\n        cmake\n        double-conversion\n        gflags\n        glog\n        jemalloc\n        libevent\n        lz4\n        openssl\n        pkg-config\n        snappy\n        xz\n        fmt\n    )\n\n    # fetch deps\n    for dependency in \"${dependencies[@]}\"; do\n        brew_install \"${dependency}\"\n    done\n}\n\ninstall_deps\n\n# Allows this script to be invoked from anywhere in the source tree but the\n# BUILD_DIR we create will always be in the top level folly directory\nTOP_LEVEL_DIR=\"$(cd \"$(dirname -- \"$0\")\"/../.. ; pwd)\"  # folly\ncd \"$TOP_LEVEL_DIR\"\nmkdir -p \"${BUILD_DIR}\"\ncd \"${BUILD_DIR}\"\n\nOPENSSL_INCLUDES=$(brew --prefix openssl)/include\ncmake \\\n    -DOPENSSL_INCLUDE_DIR=\"${OPENSSL_INCLUDES}\" \\\n    -DFOLLY_HAVE_WEAK_SYMBOLS=ON \\\n    \"$@\" \\\n    ..\n\n# fetch googletest, if doesn't exist\nGTEST_VER=1.10.0\nGTEST_DIR=gtest-${GTEST_VER}\nif [ ! -d ${GTEST_DIR} ]; then\n    mkdir ${GTEST_DIR}\n    curl -SL \\\n        https://github.com/google/googletest/archive/release-${GTEST_VER}.tar.gz | \\\n        tar -xvzf - --strip-components=1 -C ${GTEST_DIR}\nfi\n\n# make, test, install\nmake\nmake install\n", "num_lines": 83}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -x\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Note: this script was written on Ubuntu 18.04 and will need work in order to\n# work on additional platforms. This is left as an exercise for the reader.\n\nset -e\n\nBUILD_DIR=${BUILD_DIR:-_build}\nBOOST_VERSION=${BOOST_VERSION:-1.65.1}\nLIBEVENT_VERSION=${LIBEVENT_VERSION:-2.0-5}\nSSL_VERSION=${SSL_VERSION:-1.0.0}\n\nVERSION_FILE_PATH=folly/VERSION\nVERSION=${VERSION:-\"$(sed 's/:/./' ${VERSION_FILE_PATH})\"}\nITERATION=${ITERATION:-1}\n\nDESTDIR=${DESTDIR:-$(mktemp -d)}\nDEBUGDIR=${DEBUGDIR:-$DESTDIR/usr/lib/debug}\nPKGDIR=${PKGDIR:-/tmp}\n\nDESC=\"Folly is an open-source C++ library developed and used at Facebook\n  as a foundation for our infrastructure.\"\nURL=https://github.com/facebook/folly\nLICENSE=\"Apache License v2.0\"\nMAINTAINER=\"Folly Eng\"\n\ncommand -v fpm || (echo \"Please install fpm from https://github.com/jordansissel/fpm\" && exit 1)\n[ -d \"$DESTDIR\" ]\n\ncommand -v cmake || (echo \"Please install cmake.\" && exit 1)\n\n# Make\nrm -rf \"${BUILD_DIR}\"\nmkdir \"${BUILD_DIR}\"\ncd \"${BUILD_DIR}\"\ncmake ..\nmake\nmake install DESTDIR=\"$DESTDIR\"\n\n# Move symbols to debug file\n[ -d \"$DEBUGDIR/usr/lib\" ] || mkdir -p \"$DEBUGDIR/usr/lib\"\nfind \"$DESTDIR/usr/lib\" -maxdepth 1 -iname \"lib*.so.*\" -type f \\\n  -execdir objcopy --only-keep-debug {} \"$DEBUGDIR/usr/lib/{}.debug\" \\; \\\n  -execdir strip --strip-debug --strip-unneeded {} \\; \\\n  -execdir objcopy --add-gnu-debuglink \"$DEBUGDIR/usr/lib/{}.debug\" {} \\;\n\n# Build debs\nfpm \\\n  -s dir -t deb \\\n  -n \"libfolly$VERSION\" \\\n  -v \"$VERSION\" --iteration \"$ITERATION\" \\\n  -p \"$PKGDIR/NAME_VERSION-ITERATION_ARCH.deb\" \\\n  -C \"$DESTDIR\" \\\n  --description \"$DESC\" \\\n  --vendor Facebook \\\n  --url \"$URL\" \\\n  --license \"$LICENSE\" \\\n  --maintainer \"$MAINTAINER\" \\\n  --category libs \\\n  --provides libfolly \\\n  --depends libc6 \\\n  --depends libstdc++6 \\\n  --depends libboost-context\"$BOOST_VERSION\" \\\n  --depends libboost-filesystem\"$BOOST_VERSION\" \\\n  --depends libboost-program-options\"$BOOST_VERSION\" \\\n  --depends libboost-regex\"$BOOST_VERSION\" \\\n  --depends libboost-system\"$BOOST_VERSION\" \\\n  --depends libboost-thread\"$BOOST_VERSION\" \\\n  --depends libdouble-conversion1 \\\n  --depends libevent-\"$LIBEVENT_VERSION\" \\\n  --depends libgflags2 \\\n  --depends libgoogle-glog0 \\\n  --depends libicu52 \\\n  --depends libjemalloc1 \\\n  --depends liblz4-1 \\\n  --depends liblzma5 \\\n  --depends libsnappy1 \\\n  --depends libssl\"$SSL_VERSION\" \\\n  --depends zlib1g \\\n  --exclude usr/lib/debug \\\n  --exclude usr/lib/*.a \\\n  --exclude usr/lib/*.la \\\n  usr/lib\n\nfpm \\\n  -s dir -t deb \\\n  -n libfolly-dev \\\n  -v \"$VERSION\" --iteration \"$ITERATION\" \\\n  -p \"$PKGDIR/NAME_VERSION-ITERATION_ARCH.deb\" \\\n  -C \"$DESTDIR\" \\\n  --description \"$DESC\" \\\n  --vendor Facebook \\\n  --url \"$URL\" \\\n  --license \"$LICENSE\" \\\n  --maintainer \"$MAINTAINER\" \\\n  --category devel \\\n  --depends \"libfolly$VERSION\" \\\n  --exclude usr/lib/*.so* \\\n  usr/include \\\n  usr/lib/debug\n\necho \"${DESTDIR}\"\n\n", "num_lines": 117}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nFOLLY_ADDR2LINE=\"$1\"\nLLVM_ADDR2LINE=\"$2\"\nBINARY_TO_SYMBOLIZE=\"$3\"\n\nN=100\nADDRS=(\"$@\")\nADDRS=(\"${ADDRS[@]:3}\")\n\nif [[ ${#ADDRS[@]} == 0 ]]; then\n    SYMBOLS=$(readelf -s \"$BINARY_TO_SYMBOLIZE\")\n    # An address may be part of multiple functions.\n    # folly-addr2line and llvm-addr2line may choose either version leading to a comparison failure.\n    # Only compare symbolization output if a single function matches the address.\n    FUNCTION_ADDR_RANGES=$(echo \"$SYMBOLS\" | grep -E 'FUNC +GLOBAL +DEFAULT +[0-9]+' | awk '{print $2 \" \" $3}' | sort)\n    UNIQUE_ADDR_RANGES=$(echo \"$SYMBOLS\" | awk '{print $2 \" \" $3}' | sort | uniq -u)\n    FUNCTION_UNIQUE_ADDR_RANGES=$(comm -12 <(echo \"$FUNCTION_ADDR_RANGES\") <(echo \"$UNIQUE_ADDR_RANGES\") | shuf -n \"$N\")\n    if [[ -z \"$FUNCTION_UNIQUE_ADDR_RANGES\" ]]; then\n        exit 0\n    fi\n    readarray -t ADDRS < <(\n        echo \"$FUNCTION_UNIQUE_ADDR_RANGES\" | shuf -n \"$N\" | while read -r start_hex size; do\n            start=\"$((16#$start_hex))\"\n            end=\"$((start + size))\"\n            printf '0x%x\\n' \"$(seq \"$start\" \"$end\" | shuf -n 1)\"\n        done\n    )\nfi\n\necho ADDRS: \"${ADDRS[@]}\"\n\nset -x\nset -o pipefail\n\nif command -v wdiff &> /dev/null\nthen\n    DIFF=wdiff\nelse\n    DIFF=\"diff -U 10\"\nfi\n\nif command -v colordiff &> /dev/null\nthen\n    COLORDIFF=\"colordiff\"\nelse\n    COLORDIFF=\"cat\"\nfi\n\n$DIFF <(\"$FOLLY_ADDR2LINE\" -e \"$BINARY_TO_SYMBOLIZE\" -i -f -a \"${ADDRS[@]}\") <(\"$LLVM_ADDR2LINE\" -e \"$BINARY_TO_SYMBOLIZE\" -i -f -a \"${ADDRS[@]}\" | sed -E 's| \\(discriminator [0-9]+\\)||g') | \"$COLORDIFF\"\n", "num_lines": 65}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ncrash=\"$1\"\n\nuuid=$(cat /proc/sys/kernel/random/uuid)\nfor sig in 1 2 3 13 15; do eval \"trap 'exit $((sig + 128))' $sig\"; done\ntrap 'rm -f \"$crash.debuginfo.$uuid\" \"$crash.strip.$uuid\"' 0\n\nobjcopy --only-keep-debug \"$crash\" \"$crash.debuginfo.$uuid\"\nobjcopy --strip-debug --add-gnu-debuglink=\"$crash.debuginfo.$uuid\" \"$crash\" \"$crash.strip.$uuid\"\n\necho '{\"op\":\"start\",\"test\":\"gnu_debuglink_test\"}';\nstart=$(date +%s)\nif \"$crash.strip.$uuid\" 2>&1 | grep -q 'Crash.cpp:[0-9]*$'; then\n    result='\"status\":\"passed\"';\nelse\n    result='\"status\":\"failed\"';\nfi\nend=$(date +%s)\necho '{\"op\":\"test_done\",\"test\":\"gnu_debuglink_test\",'\"$result\"'}'\necho '{\"op\":\"all_done\",\"results\":[{\"name\":\"gnu_debuglink_test\",'\"$result\"',\"start_time\":'\"$start\"',\"end_time\":'\"$end\"',\"details\":\"nothing\"}]}'\n", "num_lines": 35}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nBINARY=\"$1\"\nDWP=\"$2\"\n\nNEW_BINARY=$(dirname \"$DWP\")\n# Keep the binary file with the dwp file in the same directory.\ncp \"$BINARY\" \"$NEW_BINARY\"\nNEW_BINARY+=\"/$(basename \"$BINARY\")\"\n\necho \"$NEW_BINARY\" \"$DWP\"\n\nOUTPUT=$(tr -d '[:space:]' <<<$($NEW_BINARY))\necho \"Unit test output is \" \"$OUTPUT\"\n[[ $OUTPUT =~ \"[PASSED]16tests\" ]] && exit 0 || exit 5\n", "num_lines": 30}
{"repo_name": "folly", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -ue\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nCERT_LIFETIME_DAYS=${CERT_LIFETIME_DAYS:-36500}\n\nextensions() {\n  cat << EOF\n[ca]\nbasicConstraints        = critical, CA:TRUE\nsubjectKeyIdentifier    = hash\nauthorityKeyIdentifier  = keyid:always, issuer:always\nkeyUsage                = critical, cRLSign, digitalSignature, keyCertSign\n\n[client]\nbasicConstraints        = critical, CA:FALSE\nsubjectKeyIdentifier    = hash\nauthorityKeyIdentifier  = keyid:always\nkeyUsage                = critical, nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage        = critical, clientAuth\n\n[server]\nbasicConstraints        = critical, CA:FALSE\nsubjectKeyIdentifier    = hash\nauthorityKeyIdentifier  = keyid:always\nkeyUsage                = critical, nonRepudiation, digitalSignature, keyEncipherment, keyAgreement\nextendedKeyUsage        = critical, serverAuth\nsubjectAltName          = IP:127.0.0.1,IP:::1\n\n[client_and_server]\nbasicConstraints        = critical, CA:FALSE\nsubjectKeyIdentifier    = hash\nauthorityKeyIdentifier  = keyid:always\nkeyUsage                = critical, nonRepudiation, digitalSignature, keyEncipherment, keyAgreement\nextendedKeyUsage        = critical, serverAuth, clientAuth\nsubjectAltName          = IP:127.0.0.1,IP:::1\nEOF\n}\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\ngenerate_key() {\n  keytype=\"$1\"\n  modulus_bits=\"$2\"\n  outfile=\"$3\"\n\n  [ \"$keytype\" != \"rsa\" ] && die \"unsupported key type\"\n\n  openssl genrsa -out \"$outfile\" \"$modulus_bits\" 2>/dev/null\n}\n\nmkcsr() {\n  local key=\"$1\"\n  local name=\"$2\"\n  local output=\"$3\"\n\n  openssl req -new \\\n    -sha256 \\\n    -key \"$key\" \\\n    -keyform PEM \\\n    -subj \"/CN=$name/\" \\\n    -outform PEM \\\n    -out \"$output\" \\\n\n}\n\nselfsign() {\n  local incsr=\"$1\"\n  local inkey=\"$2\"\n  local outfile=\"$3\"\n\n  openssl x509 \\\n    -req \\\n    -set_serial 1 \\\n    -signkey \"$inkey\" \\\n    -inform PEM \\\n    -in \"$incsr\" \\\n    -outform PEM \\\n    -out \"$outfile\" \\\n    -days \"$CERT_LIFETIME_DAYS\" \\\n    -extfile <(extensions) \\\n    -extensions \"ca\" \\\n\n}\n\nsign() {\n  csr=\"$1\"\n  cacert=\"$2\"\n  cakey=\"$3\"\n  serial=\"$4\"\n  extensions=\"$5\"\n  outfile=\"$6\"\n\n\n  openssl x509 \\\n    -req \\\n    -set_serial \"$serial\" \\\n    -CA \"$cacert\" \\\n    -CAkey \"$cakey\" \\\n    -inform PEM \\\n    -in \"$csr\" \\\n    -outform PEM \\\n    -out \"$outfile\" \\\n    -days \"$CERT_LIFETIME_DAYS\" \\\n    -extfile <(extensions) \\\n    -extensions \"$extensions\" \\\n\n}\n\n# Client CA\ngenerate_key rsa 2048 client_ca_key.pem\nmkcsr client_ca_key.pem \"Asox Certification Authority\" client_ca.csr.pem\nselfsign client_ca.csr.pem client_ca_key.pem client_ca_cert.pem\n\n# Client Intermediate CA\ngenerate_key rsa 2048 client_intermediate_ca_key.pem\nmkcsr client_intermediate_ca_key.pem \"Intermediate CA\" client_intermediate_ca.csr.pem\nsign client_intermediate_ca.csr.pem client_ca_cert.pem client_ca_key.pem 2 ca client_intermediate_ca.pem\n\n# Directly signed client cert (client_key.pem)\ngenerate_key rsa 2048 client_key.pem\nmkcsr client_key.pem \"testuser1\" client.csr.pem\nsign client.csr.pem client_ca_cert.pem client_ca_key.pem 100 client client_cert.pem\n\n# Client signed by an intermediate\ngenerate_key rsa 2048 clienti_key.pem\nmkcsr clienti_key.pem \"Leaf Certificate\" clienti.csr.pem\nsign clienti.csr.pem client_intermediate_ca.pem client_intermediate_ca_key.pem 200 client clienti_cert.pem\ncat clienti_cert.pem client_intermediate_ca.pem > client_chain.pem\n\n# Server CA \"Thrift Certificate Authority\"\ngenerate_key rsa 2048 ca-key.pem\nmkcsr ca-key.pem \"Thrift Certificate Authority\" ca.csr.pem\nselfsign ca.csr.pem ca-key.pem ca-cert.pem\n\n# Server cert \"Asox Company\"\ngenerate_key rsa 2048 tests-key.pem\nmkcsr tests-key.pem \"Asox Company\" tests.csr.pem\nsign tests.csr.pem ca-cert.pem ca-key.pem 300 client_and_server tests-cert.pem\n\n# Remove all of the CSRs but leave the keys in case you need to regenerate a\n# different cert with the same key.\nrm ./*.csr.pem\n", "num_lines": 158}
{"repo_name": "grocery-delivery", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o verbose\nbundle exec chef-zero &\nZERO=$!\ntrap \"kill -9 $ZERO\" EXIT\nSOURCE=/tmp/source\nsleep 5\n\nrm -rf /tmp/master_path\nrm -rf $SOURCE\nGIT=\"git -c user.email='foo@bar.com' -c user.name='foobar'\"\n\nfunction gd {\n  bundle exec ./bin/grocery-delivery -c test/gd-git.rb -vv\n}\n\n(\n  mkdir $SOURCE\n  $GIT init $SOURCE\n  cd $SOURCE && touch test && $GIT add . -A && $GIT commit -m \"Dummy commit\"\n)\ngd\n(\n  cd $SOURCE\n  mkdir chef/cookbooks/cookbook1/recipes -p\n  touch chef/cookbooks/cookbook1/recipes/default.rb\n  echo \"name 'cookbook1'\" > chef/cookbooks/cookbook1/metadata.rb\n  $GIT add . -A\n  $GIT commit -m \"Add cookbook1\"\n)\ngd\n(\n  cd $SOURCE\n  touch chef/cookbooks/cookbook1/recipes/recipe2.rb\n  $GIT add . -A\n  $GIT commit -m \"Modify cookbook1\"\n)\ngd\n(\n  cd $SOURCE\n  rm -rf chef/cookbooks/cookbook1\n  $GIT add . -A\n  $GIT commit -m \"Remove cookbook1\"\n)\ngd\n\n", "num_lines": 63}
{"repo_name": "grocery-delivery", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o verbose\nbundle exec chef-zero &\nZERO=$!\ntrap \"kill -9 $ZERO\" EXIT\nSOURCE=/tmp/source\nsleep 5\n\nrm -rf /tmp/master_path\nrm -rf $SOURCE\nrm -rf $SOURCE-import\nrm -rf $SOURCE-checkout\n\nfunction gd {\n  bundle exec ./bin/grocery-delivery -c test/gd-svn.rb -vv\n}\n\n(\n  mkdir $SOURCE\n  svnadmin create $SOURCE\n  mkdir $SOURCE-import && cd $SOURCE-import && touch test && svn import . file://$SOURCE -m\"Dummy commit\"\n)\ngd\n(\n  svn checkout file://$SOURCE $SOURCE-checkout\n  cd $SOURCE-checkout\n  mkdir chef/cookbooks/cookbook1/recipes -p\n  touch chef/cookbooks/cookbook1/recipes/default.rb\n  echo \"name 'cookbook1'\" > chef/cookbooks/cookbook1/metadata.rb\n  svn add chef\n  svn commit chef -m\"Add cookbook1\"\n)\ngd\n(\n  cd $SOURCE-checkout\n  touch chef/cookbooks/cookbook1/recipes/recipe2.rb\n  svn add chef/cookbooks/cookbook1/recipes/recipe2.rb\n  svn commit chef -m\"Modify cookbook1\"\n)\ngd\n(\n  cd $SOURCE-checkout\n  svn delete chef/cookbooks/cookbook1/metadata.rb\n  svn delete chef/cookbooks/cookbook1/recipes/default.rb\n  svn delete chef/cookbooks/cookbook1/recipes/recipe2.rb\n  svn status\n  svn commit -m\"Remove cookbook1\"\n)\ngd\n\n", "num_lines": 67}
{"repo_name": "grocery-delivery", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o verbose\nset -e\n./test/run-svn.sh\n./test/run-git.sh\n", "num_lines": 21}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncmake ~/fbsource/xplat/hermes \\\n    -DHERMES_FACEBOOK_BUILD=OFF \\\n    -DCMAKE_BUILD_TYPE=MinSizeRel \\\n    -DCMAKE_TOOLCHAIN_FILE=/opt/android_ndk/android-ndk-r15c/build/cmake/android.toolchain.cmake \\\n    -DICU_ROOT=/Users/tmikov/3rd/swift-libiconv-libicu-android.git/armeabi-v7a -G Ninja $*\n", "num_lines": 12}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: sh %s %hermesc %S/input1.js.txt %t-input1 %S/input1-p.js.txt\n# RUN: sh %s %hermesc %S/richards.js.txt %t-richards\n\nset -e\n\nHERMESC=$1\nINP=$2\nTMPN=$3\nPRETTY=$4\n\n\"$HERMESC\" -dump-ast -Xinclude-raw-ast-prop=0 \"$INP\" > \"${TMPN}.json\"\n\n\"$HERMESC\" -dump-js -pretty \"$INP\" > \"${TMPN}-p.js\"\nif [ -n \"$PRETTY\" ]; then\n    cmp \"$PRETTY\" \"${TMPN}-p.js\"\nfi\n\"$HERMESC\" -dump-ast -Xinclude-raw-ast-prop=0 \"${TMPN}-p.js\" > \"${TMPN}-p.json\"\ncmp \"${TMPN}.json\" \"${TMPN}-p.json\"\n\n\"$HERMESC\" -dump-js -pretty=0 \"$INP\" > \"${TMPN}-m.js\"\n\"$HERMESC\" -dump-ast -Xinclude-raw-ast-prop=0 \"${TMPN}-m.js\" > \"${TMPN}-m.json\"\ncmp \"${TMPN}.json\" \"${TMPN}-m.json\"\n", "num_lines": 29}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -xe\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Parse command-line arguments\nhermes_npm_package=\n\nwhile (( \"$#\" )); do\n  case $1 in\n    --hermes-npm-package)\n      shift || (\n        echo \"Missing NPM package argument\"\n        exit 1\n      )\n      hermes_npm_package=\"$1\"\n      ;;\n    *)\n      echo \"Unsupported argument: $1\"\n      exit 1\n      ;;\n   esac\n   shift\ndone\n\n# Clone a fresh copy of RN main\ngit clone --depth=1 https://github.com/facebook/react-native\n\ncd react-native\nnpm install\n# Install new Hermes NPM.\nnpm install \"$hermes_npm_package\"\n\n# Modify RN Tester app to print a log message at start-up\necho \"console.log('Using Hermes: ' + (global.HermesInternal != null));\" >> packages/rn-tester/js/RNTesterApp.android.js\n\n# Wait for emulator to boot\nadb wait-for-device\n\n# Build and install release app\n./gradlew :packages:rn-tester:android:app:installHermesRelease\n\ncd ..\n\n# Start screen recording for debug\nadb shell screenrecord /sdcard/screencap.mp4 &\nadb_screen_record_pid=$!\nfunction stashScreenCapture() {\n  local exit_code=$?\n  adb shell killall -s INT screenrecord\n  wait $adb_screen_record_pid || true\n  adb pull /sdcard/screencap.mp4 /tmp/hermes/output/screencap.mp4\n  exit \"$exit_code\"\n}\ntrap stashScreenCapture EXIT\n\n# Start app + wait to see relevant log message\nadb logcat -c || true  # This sometimes fails to clear the \"main\" log. This is benign.\nadb shell am start com.facebook.react.uiapp/.RNTesterActivity\nSECONDS=0\nuntil grep 'Using Hermes: true' <(adb logcat -d -s ReactNativeJS:I) ; do\n  if ((SECONDS > 30 )) ; then\n    echo \"Did not see correct log message within 30s\"\n    adb logcat -d > /tmp/hermes/output/adblog.txt\n    tar cfz /tmp/hermes/output/project.tar.gz react-native\n    exit 1\n  fi\n  sleep 2\ndone\n\necho \"Test passed: Hermes in use in RNTester App\"\nexit 0\n", "num_lines": 74}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: bash %s %S %T %hbc-deltaprep %hermes\n# shellcheck shell=bash\n\n# Exit on any failure.\nset -e\nset -o pipefail\n\nSRCDIR=$1\nTMPDIR=$2\nDELTAPREP=$3\nHERMES=$4\n\n# Compile the source and delta-prep it, then compare the original.\n${HERMES} -emit-binary -out \"${TMPDIR}/file1.hbc\" \"${SRCDIR}/file1.js\"\n${DELTAPREP} \"${TMPDIR}/file1.hbc\" -form=delta -out \"${TMPDIR}/file1-delta.hbc\"\n! diff -q \"${TMPDIR}/file1.hbc\" \"${TMPDIR}/file1-delta.hbc\"\n\n# Convert back and verify it matches the original.\n${DELTAPREP} \"${TMPDIR}/file1-delta.hbc\" -form=execution -out \"${TMPDIR}/file1-roundtrip.hbc\"\n! diff -q \"${TMPDIR}/file1-delta.hbc\" \"${TMPDIR}/file1-roundtrip.hbc\"\ndiff -q \"${TMPDIR}/file1.hbc\" \"${TMPDIR}/file1-roundtrip.hbc\"\n", "num_lines": 27}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: sh %s %S %t %hermes\n# RUN: sh %s %S %t %hermesc\n\n# shellcheck disable=SC2148\n\nSRCDIR=$1\nTMPFILE=$2\nHERMES=$3\n\n# Return values from hermes and hermesc.\nSuccess=0\nInvalidFlags=1\nParsingFailed=2\n# shellcheck disable=SC2034\nVerificationFailed=3\nLoadGlobalsFailed=4\nInputFileError=5\nOutputFileError=6\n# shellcheck disable=SC2034\nOptimizationFailed=7\n\nset -x\n\nexpect() {\n  EXPECTED=$1\n  shift\n  eval \"$@\" 2>\"$TMPFILE\"\n  if [[ $? != \"$EXPECTED\" ]]; then\n    echo \"Command '$CMD' produced wrong exit status\" >&2\n    exit 1\n  fi\n  true\n}\n\ncd \"${SRCDIR}\" || exit 1\nexpect \"${Success}\" \"${HERMES}\" test.js.in -target=HBC -emit-binary > \"$TMPFILE\"\nexpect \"${InvalidFlags}\" \"${HERMES}\" -lazy -commonjs test.js.in\nexpect \"${InvalidFlags}\" \"${HERMES}\" -nonsenseflag test.js.in\nexpect \"${ParsingFailed}\" \"${HERMES}\" bogus.js.in -target=HBC -emit-binary > \"$TMPFILE\"\nexpect \"${LoadGlobalsFailed}\" \"${HERMES}\" test.js.in -include-globals bogus.js.in -emit-binary -target=HBC > \"$TMPFILE\"\nexpect \"${InputFileError}\" \"${HERMES}\" ./not/a/valid/path.js -target=HBC -emit-binary > \"$TMPFILE\"\nexpect \"${OutputFileError}\" \"${HERMES}\" test.js.in -target=HBC -emit-binary -out ./not/a/valid/path.hbc\n", "num_lines": 48}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: bash %s %S %T %hermes\n# shellcheck shell=bash disable=SC2086\n\n# This test is an end-to-end source-map symbolication test. First it runs a\n# file thrower.js which throws an exception, and records the backtrace (which\n# has line and column numbers through its debug info). It then compiles the\n# same file to bytecode with a source map (thus omitting the debug info from\n# the binary), runs the bytecode file, and records that backtrace as the \"raw\"\n# trace. It then symbolicates the raw trace using the source-map project from\n# Mozilla, and compares the original and symbolicated trace. This tests that\n# a source-map symbolicated backtrace is identical to the one output when\n# debug info is present.\n\nSRCDIR=$1\nTMPDIR=$2\nHERMES=$3\n\n# Perform a symbolication test.\n# Argument 1: a name for the test\n# Argument 2: parameters to pass to hermes driver.\nrun_1_test() {\n  NAME=$1;\n  ARGS=$2;\n  HBC_FILE=$3;\n  SRC_FILES=(\"${@:4}\");\n\n  ORIG_TRACE=\"$TMPDIR/${NAME}_original_trace.txt\"\n  RAW_TRACE=\"$TMPDIR/${NAME}_raw_trace.txt\"\n  SYM_TRACE=\"$TMPDIR/${NAME}_symbolicated_trace.txt\"\n\n  # Run the JS directly, record the backtrace.\n  \"$HERMES\" $ARGS \"${SRC_FILES[@]}\" > \"$ORIG_TRACE\"\n\n  # Compile the JS to bytecode and have it emit a source map.\n  # Run the bytecode and store its trace (which will contain addresses).\n  \"$HERMES\" $ARGS -output-source-map -emit-binary -out \"$HBC_FILE\" \"${SRC_FILES[@]}\"\n  \"$HERMES\" \"$HBC_FILE\" > \"$RAW_TRACE\"\n\n  # Ensure that the two backtraces are different so the symbolicator has\n  # real work to do.\n  if diff -q \"$ORIG_TRACE\" \"$RAW_TRACE\" > /dev/null ; then\n    echo \"Raw and original backtraces should not be the same\"\n    echo \"Raw trace: $RAW_TRACE\"\n    echo \"Original trace: $ORIG_TRACE\"\n    echo \"Artifacts in $TMPDIR\"\n    exit 1\n  fi\n\n  # Stringize the sourcemap and raw stack trace, concatenate them along with\n  # the symbolicator source, and then execute that. The output will be a\n  # symbolicated stacktrace. This is to enable the test to run via Hermes alone\n  # (i.e. without introducing a node dependency).\n  ( python3 $SRCDIR/stringize.py SOURCEMAP < \"$HBC_FILE.map\" ;\n    python3 $SRCDIR/stringize.py STACKTRACE < \"$RAW_TRACE\" ;\n    cat $SRCDIR/symbolicator.js.in\n  ) | \"$HERMES\" - -target=HBC -gc-sanitize-handles=0 > \"$SYM_TRACE\"\n\n  # Ensure that the original and symbolicated stack trace are the same!\n  if ! diff \"$ORIG_TRACE\" \"$SYM_TRACE\" ; then\n    echo \"Symbolicated stack trace differed from debug-info version.\";\n    echo \"Symbolicated trace: $SYM_TRACE\"\n    echo \"Original trace: $ORIG_TRACE\"\n    echo \"Artifacts in $TMPDIR\";\n    exit 1\n  fi\n}\n\n(cat \"$SRCDIR/stack-formatter.js.in\" \"$SRCDIR/thrower.js\") > \"$TMPDIR/thrower-with-formatter.js\"\n\n# -gc-sanitize-handles=0 because ASAN build is far too slow without it.\nrun_1_test \"default\"   \"-gc-sanitize-handles=0 -target=HBC\" \"$TMPDIR/thrower.hbc\" \"$SRCDIR/thrower.js\"\nrun_1_test \"optimized\" \"-O -gc-sanitize-handles=0 -target=HBC\" \"$TMPDIR/thrower.hbc\" \"$SRCDIR/thrower.js\"\nrun_1_test \"default_cjs\" \"-commonjs -gc-sanitize-handles=0 -target=HBC\" \"$TMPDIR/cjs-1.hbc\" \"$SRCDIR/cjs-1.js\" \"$SRCDIR/cjs-2.js\"\nrun_1_test \"optimized_cjs\" \"-O -commonjs -gc-sanitize-handles=0 -target=HBC\" \"$TMPDIR/cjs-1.hbc\" \"$SRCDIR/cjs-1.js\" \"$SRCDIR/cjs-2.js\"\nrun_1_test \"formatter_optimized\" \"-w -O -gc-sanitize-handles=0 -target=HBC\" \"$TMPDIR/thrower-with-formatter.hbc\" \"$TMPDIR/thrower-with-formatter.js\"\n", "num_lines": 81}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: bash %s %S %T %hermes | %FileCheck %s\n# shellcheck shell=bash disable=SC2086\n\nSRCDIR=$1\nTMPDIR=$2\nHERMES=$3\n\nHBC_FILE=\"$TMPDIR/out.hbc\"\nRAW_TRACE=\"$TMPDIR/raw_trace.txt\"\nSYM_TRACE=\"$TMPDIR/symbolicated_trace.txt\"\n\n\"$HERMES\" -gc-sanitize-handles=0 -commonjs -output-source-map \\\n  -emit-binary -out \"$HBC_FILE\" \\\n  \"$SRCDIR\"\n\n\"$HERMES\" \"$HBC_FILE\" > \"$RAW_TRACE\"\n\n# Stringize the sourcemap and raw stack trace, concatenate them along with\n# the symbolicator source, and then execute that. The output will be a\n# symbolicated stacktrace. This is to enable the test to run via Hermes alone\n# (i.e. without introducing a node dependency).\n( python3 \"$SRCDIR/../stringize.py\" SOURCEMAP < \"$HBC_FILE.map\" ;\n  python3 \"$SRCDIR/../stringize.py\" STACKTRACE < \"$RAW_TRACE\" ;\n  cat \"$SRCDIR/../symbolicator.js.in\"\n) | \"$HERMES\" - -gc-sanitize-handles=0 > \"$SYM_TRACE\"\n\ncat \"$SYM_TRACE\"\n# CHECK: Error: ERROR_FOR_TESTING\n# CHECK-NEXT:     at mod2Inner ({{.*}}cjs-subdir-2.js:11:17)\n# CHECK-NEXT:     at unmappedFunction (null:null:null)\n# CHECK-NEXT:     at mappedFunction (/fake/source/of/mappedFunction.js:1:1)\n# CHECK-NEXT:     at anonymous ({{.*}}cjs-subdir-2.js:10:47)\n# CHECK-NEXT:     at immediatelyInvoke ({{.*}}cjs-subdir-shared.js:9:3)\n# CHECK-NEXT:     at mod2fun ({{.*}}cjs-subdir-2.js:9:39)\n# CHECK-NEXT:     at run ({{.*}}cjs-subdir-unminified.js:11:20)\n# CHECK-NEXT:     at mainInner ({{.*}}cjs-subdir-main.js:12:11)\n# CHECK-NEXT:     at immediatelyInvoke ({{.*}}cjs-subdir-shared.js:9:3)\n# CHECK-NEXT:     at cjs_module ({{.*}}cjs-subdir-main.js:8:37)\n", "num_lines": 44}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# RUN: bash %s %S %T %hermes\n# REQUIRES: !fbcode_coverage\n# shellcheck shell=bash disable=SC2086\n\n# This test is an end-to-end merge input source-map with hermes debuginfo symbolication test.\n# First it runs original non-transformed file throw.js which throws an exception, and records the backtrace.\n# It then runs the uglifyjs generated throw.min.js with input source map and records that backtrace\n# as the \"symbolicated trace\".\n# Finally it diffs both traces(ignoring full path/column number) to ensure they are the same.\n# This tests that generated js code backtrace merged with input source map is identical\n# to the original source file backtrace.\n\nSRCDIR=$1\nTMPDIR=$2\nHERMES=$3\n\n# Perform a symbolication test.\n# Argument 1: a name for the test\n# Argument 2: parameters to pass to hermes driver.\n# Argument 3: input js file to evaluate.\n# Argument 4: generated minified file correspoinding to input js file.\n# Argument 5: source map for input js file.\nrun_1_test() {\n  NAME=$1;\n  ARGS=$2;\n  ORIGINAL_JS_FILE=$3;\n  GENERATED_JS_FILE=$4;\n  JS_FILE_SOURCE_MAP=$5;\n\n  ORIG_TRACE=\"$TMPDIR/${NAME}_original_trace.txt\"\n  SYM_TRACE=\"$TMPDIR/${NAME}_symbolicated_trace.txt\"\n\n  # Run the original JS, record the backtrace.\n  \"$HERMES\" $ARGS \"$ORIGINAL_JS_FILE\" &> \"$ORIG_TRACE\"\n\n  # Run the generated JS with input source file, record the backtrace symbolicated with merged debuginfo.\n  \"$HERMES\" $ARGS \"$GENERATED_JS_FILE\" -source-map \"$JS_FILE_SOURCE_MAP\" &> \"$SYM_TRACE\"\n\n  # Check if original and symbolicated traces using input source map match using stacktrace_diff.py.\n  # stacktrace_diff.py matches stack frames ignoring file full path and column number. This is necessary because:\n  # 1. Ignore full path: Original trace's file full path depends on the running matchine while file path\n  #   in source map is hard-coded with full path stripped.\n  # 2. Ignore column number: Uglifyjs generated source map does not have full fidelity range mapping\n  #   for every single tokens so if a generated line/column is in the middle of a mapping range the symbolicated\n  #   trace will report the beginning of the range in original source most likely diff in column numbers.\n  python3 \"$SRCDIR/stacktrace_diff.py\" \"$ORIG_TRACE\" \"$SYM_TRACE\"\n}\n\n# -gc-sanitize-handles=0 because ASAN build is far too slow without it.\nrun_1_test \"default\"   \"-gc-sanitize-handles=0 -target=HBC\" \"$SRCDIR/throw.js\" \"$SRCDIR/throw.min.js\" \"$SRCDIR/throw.min.js.map\"\nrun_1_test \"optimized\"   \"-O -gc-sanitize-handles=0 -target=HBC\" \"$SRCDIR/throw.js\" \"$SRCDIR/throw.min.js\" \"$SRCDIR/throw.min.js.map\"\n", "num_lines": 57}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e -o pipefail\n\nhbcattribute() {\n  \"$HBC_ATTRIBUTE\"  \"$@\"\n}\n\nsymbolicate() {\n  \"$SYMBOLICATE\" \"$@\"\n}\n\naccumulate() {\n  \"$ACCUMULATE\"\n}\n\n# Buck passes in a series of variables like 'HBC_ATTRIBUTE_RUN=somevalue'\nwhile [[ $# != 0 && $1 != -- ]]\ndo\n  declare \"$1\"\n  shift\ndone\nshift\n\n\ncase $# in\n  1) hbcattribute \"$1\" | accumulate ;;\n  2) hbcattribute \"$1\" | symbolicate \"$2\" --attribution | accumulate ;;\n  *)\n    echo \"Usage: $(basename \"$0\") bundle.hbc [sourcemap.map]\" >&2\n    exit 1\nesac\n", "num_lines": 37}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Exit on any failure\nset -e\nset -o pipefail\n\n# Check that the supplied binaries exist\n[ -x \"$HERMES\" ] || exit 3\n[ -x \"$HBCDUMP\" ] || exit 4\n[ -x \"$HBC_READ_TRACE\" ] || exit 5\n\n# Create a workspace and make sure it is cleaned up when we exit.\nTMP=$(mktemp -d)\ntrap 'rm -rf $TMP' exit\n\n# The JS file we will compile.\ncat <<EOF > \"$TMP/test.js\"\nprint(\"Hello, world!\")\nEOF\n\n\"$HERMES\" -O -emit-binary -target=HBC -out=\"$TMP/test.hbc\" \"$TMP/test.js\"\n\n# The test trace of page accesses (states that we saw one access, of the 0'th\n# page and it took 42 microseconds).\n# The output test.log is a tsv file, and therefore there are tabs in the string\n# below, thus\n# @lint-ignore-every TXT2\ncat <<EOF > \"$TMP/test.log\"\nPage\tTime (us)\n0\t42\nEOF\n\n# The sections we expect hbc-read-trace to output\ncat <<EOF > \"$TMP/expected\"\n<unknown>\nfunction-table\nstring-kinds\nidentifier-hashes\nstring-table\noverflow-string-table\nstring-storage\narray-buffer\nobject-key-buffer\nobject-value-buffer\nbigint-storage\nregular-expression-table\nregular-expression-storage\ncommonjs-module-table\nfunction-body\nfunction-info\ndebug-info\nEOF\n\n# Run hbc-read-trace and compare it with the above list.\n\"$HBC_READ_TRACE\" -v -D \"$HBCDUMP\" -B \"$TMP/test.hbc\" < \"$TMP/test.log\" \\\n  | head -n 1 \\\n  | perl -pe 's/\\//\\n/g' \\\n  | diff -u - \"$TMP/expected\"\n", "num_lines": 63}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -xe -o pipefail\n\nTHIS_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n\nPACKAGES=(\n  hermes-estree\n  hermes-parser\n  hermes-eslint\n  hermes-transform\n  flow-api-translator\n  prettier-plugin-hermes-parser\n  babel-plugin-syntax-hermes-parser\n)\n\n# Yarn install all packages\nyarn install\n\n# Use internal FB build or pass path to WASM parser as first command line argument\nFB_BUILD_WASM_PARSER=\"$THIS_DIR/facebook/buildWasmParser.sh\"\nif [[ -f \"$1\" ]]; then\n  WASM_PARSER=\"$1\"\nelif [[ -f \"$FB_BUILD_WASM_PARSER\" ]]; then\n  WASM_PARSER=$(\"$FB_BUILD_WASM_PARSER\")\nelse\n  echo \"Failed to get WASM parser\" 1>&2\n  exit 1\nfi\n\n# Use internal FB build or pass path to include path as second command line argument\nFB_GET_INCLUDE_PATH=\"$THIS_DIR/facebook/getIncludePath.sh\"\nif [[ -d \"$2\" ]]; then\n  INCLUDE_PATH=\"$2\"\nelif [[ -f \"$FB_GET_INCLUDE_PATH\" ]]; then\n  INCLUDE_PATH=$(\"$FB_GET_INCLUDE_PATH\")\nelse\n  echo \"Failed to get include path\" 1>&2\n  exit 1\nfi\n\n# Generate the JSON blob used to drive the rest of the JS codegen\nyarn babel-node \"$THIS_DIR/genESTreeJSON.js\" \"$INCLUDE_PATH\"\n\n# Generate source code, written into package src directories\nyarn babel-node \"$THIS_DIR/genNodeDeserializers.js\" \"$INCLUDE_PATH\"\nyarn babel-node \"$THIS_DIR/genParserVisitorKeys.js\"\nyarn babel-node \"$THIS_DIR/genESTreeVisitorKeys.js\"\nyarn babel-node \"$THIS_DIR/genPredicateFunctions.js\"\nyarn babel-node \"$THIS_DIR/genTransformNodeTypes.js\"\n\n# Create fresh dist directory for each package, and copy source files in\nfor package in \"${PACKAGES[@]}\"; do\n  PACKAGE_DIR=\"$THIS_DIR/../$package\"\n  rm -rf \"$PACKAGE_DIR/dist\"\n\n  cp -r \"$PACKAGE_DIR/src\" \"$PACKAGE_DIR/dist\"\n\n  # There is no system for flow to emit flow declarations for files\n  # So we rename all the JS files to .js.flow so they are treated like flow declarations\n  find \"$PACKAGE_DIR/dist\" -type f -name \"*.js\" -exec grep -q \" @flow\" {} \\; -exec rename --no-overwrite \".js\" \".js.flow\" {} \\;\n\n  # Copy just the JS files again\n  (cd \"$PACKAGE_DIR/src\" && find . -type f -name '*.js' -exec cp --parents -t ../dist {} +)\ndone\n\n# Generate source code that only applies to dist directory\nyarn babel-node \"$THIS_DIR/genWasmParser.js\" \"$WASM_PARSER\"\n# TODO: Move these to `src` directory, currently causes Flow errors.\nyarn babel-node \"$THIS_DIR/genSelectorTypes.js\"\nyarn babel-node \"$THIS_DIR/genTransformCloneTypes.js\"\nyarn babel-node \"$THIS_DIR/genTransformModifyTypes.js\"\nyarn babel-node \"$THIS_DIR/genTransformReplaceNodeTypes.js\"\n\nfor package in \"${PACKAGES[@]}\"; do\n  PACKAGE_DIST_DIR=\"$THIS_DIR/../$package/dist\"\n  yarn babel --config-file=\"$THIS_DIR/../babel.config.js\" \"$PACKAGE_DIST_DIR\" --out-dir=\"$PACKAGE_DIST_DIR\"\ndone\n\n# Validate that the generated flow files are sane\n# We don't bother validating the raw-js files as they are validated by babel first\nyarn eslint \"*/dist/**/*.js.flow\" --no-ignore\n", "num_lines": 87}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2013, Ben Noordhuis <info@bnoordhuis.nl>\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\ncd `dirname \"$0\"`\n\nif [ \"$LIBTOOLIZE\" = \"\" ] && [ \"`uname`\" = \"Darwin\" ]; then\n  LIBTOOLIZE=glibtoolize\nfi\n\nACLOCAL=${ACLOCAL:-aclocal}\nAUTOCONF=${AUTOCONF:-autoconf}\nAUTOMAKE=${AUTOMAKE:-automake}\nLIBTOOLIZE=${LIBTOOLIZE:-libtoolize}\n\nautomake_version=`\"$AUTOMAKE\" --version | head -n 1 | sed 's/[^.0-9]//g'`\nautomake_version_major=`echo \"$automake_version\" | cut -d. -f1`\nautomake_version_minor=`echo \"$automake_version\" | cut -d. -f2`\n\nUV_EXTRA_AUTOMAKE_FLAGS=\nif test \"$automake_version_major\" -gt 1 || \\\n   test \"$automake_version_major\" -eq 1 && \\\n   test \"$automake_version_minor\" -gt 11; then\n  # serial-tests is available in v1.12 and newer.\n  UV_EXTRA_AUTOMAKE_FLAGS=\"$UV_EXTRA_AUTOMAKE_FLAGS serial-tests\"\nfi\necho \"m4_define([UV_EXTRA_AUTOMAKE_FLAGS], [$UV_EXTRA_AUTOMAKE_FLAGS])\" \\\n    > m4/libuv-extra-automake-flags.m4\n\nset -ex\n\"$LIBTOOLIZE\" --copy\n\"$ACLOCAL\" -I m4\n\"$AUTOCONF\"\n\"$AUTOMAKE\" --add-missing --copy\n", "num_lines": 47}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: gen_cpp.sh SOURCE\"\n  exit 1\nfi\n\nFNRUNTIME_DIR=$(dirname ${0})/runtime\nBIN_DIR=$(dirname ${0})/../../target/debug\n\nname=\"${1%.js}\"\nname=\"${name##*/}\"\n\"$BIN_DIR/fnc\" \"${1}\" | clang-format > \"${name}.cpp\"\n", "num_lines": 18}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ \"$#\" -ne 3 ]; then\n  echo \"Usage: run_fnc.sh FNC SOURCE OUTPUT\"\n  exit 1\nfi\n\nFNRUNTIME_DIR=$(dirname ${0})/runtime\n\n\"${1}\" -g \"${2}\" | c++ -x c++ -I \"${FNRUNTIME_DIR}\" \"${FNRUNTIME_DIR}/FNRuntime.cpp\" - -O3 -std=c++17 -o \"${3}\"\n", "num_lines": 15}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nTHIS_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n\n[ ! -d \"$HERMES_BUILD\" ] && echo \"HERMES_BUILD must be valid\" && exit 1\n\nrustgen=$HERMES_BUILD/bin/rustgen\n\n$rustgen ffi > \"$THIS_DIR/../../juno/crates/hermes/src/parser/generated_ffi.rs\"\n$rustgen cvt > \"$THIS_DIR/../../juno/crates/juno/src/hparser/generated_cvt.rs\"\n\n", "num_lines": 16}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ \"$DEBUG\" = true ]; then\n  BUILD_TYPE=\"Debug\"\nelse\n  BUILD_TYPE=\"Release\"\nfi\n\nfunction command_exists {\n  command -v \"${1}\" > /dev/null 2>&1\n}\n\nif command_exists \"cmake\"; then\n  if command_exists \"ninja\"; then\n    BUILD_SYSTEM=\"Ninja\"\n  else\n    BUILD_SYSTEM=\"Unix Makefiles\"\n  fi\nelse\n  echo >&2 'CMake is required to install Hermes, install it with: brew install cmake'\n  exit 1\nfi\n\nfunction get_release_version {\n  ruby -rcocoapods-core -rjson -e \"puts Pod::Specification.from_file('hermes-engine.podspec').version\"\n}\n\nfunction get_ios_deployment_target {\n  ruby -rcocoapods-core -rjson -e \"puts Pod::Specification.from_file('hermes-engine.podspec').deployment_target('ios')\"\n}\n\nfunction get_mac_deployment_target {\n  ruby -rcocoapods-core -rjson -e \"puts Pod::Specification.from_file('hermes-engine.podspec').deployment_target('osx')\"\n}\n\n# Build host hermes compiler for internal bytecode\nfunction build_host_hermesc {\n  cmake -S . -B build_host_hermesc\n  cmake --build ./build_host_hermesc --target hermesc\n}\n\n# Utility function to configure an Apple framework\nfunction configure_apple_framework {\n  local build_cli_tools enable_bitcode\n\n  if [[ $1 == iphoneos || $1 == catalyst ]]; then\n    enable_bitcode=\"true\"\n  else\n    enable_bitcode=\"false\"\n  fi\n  if [[ $1 == macosx ]]; then\n    build_cli_tools=\"true\"\n  else\n    build_cli_tools=\"false\"\n  fi\n\n  cmake -S . -B \"build_$1\" -G \"$BUILD_SYSTEM\" \\\n    -DHERMES_APPLE_TARGET_PLATFORM:STRING=\"$1\" \\\n    -DCMAKE_OSX_ARCHITECTURES:STRING=\"$2\" \\\n    -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=\"$3\" \\\n    -DHERMES_ENABLE_DEBUGGER:BOOLEAN=true \\\n    -DHERMES_ENABLE_INTL:BOOLEAN=true \\\n    -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \\\n    -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \\\n    -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \\\n    -DHERMES_ENABLE_BITCODE:BOOLEAN=\"$enable_bitcode\" \\\n    -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \\\n    -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \\\n    -DHERMES_ENABLE_TOOLS:BOOLEAN=\"$build_cli_tools\" \\\n    -DIMPORT_HERMESC:PATH=\"$PWD/build_host_hermesc/ImportHermesc.cmake\" \\\n    -DCMAKE_INSTALL_PREFIX:PATH=../destroot \\\n    -DCMAKE_BUILD_TYPE=\"$BUILD_TYPE\"\n}\n\n# Utility function to build an Apple framework\nfunction build_apple_framework {\n  echo \"Building framework for $1 with architectures: $2\"\n\n  build_host_hermesc\n  [ ! -f \"$PWD/build_host_hermesc/ImportHermesc.cmake\" ] &&\n  echo \"Host hermesc is required to build apple frameworks!\"\n\n  configure_apple_framework \"$1\" \"$2\" \"$3\"\n\n  if [[ \"$BUILD_SYSTEM\" == \"Ninja\" ]]; then\n    (cd \"./build_$1\" && ninja install/strip)\n  else\n    (cd \"./build_$1\" && make install/strip)\n  fi\n}\n\n# Accepts an array of frameworks and will place all of\n# the architectures into an universal folder and then remove\n# the merged frameworks from destroot\nfunction create_universal_framework {\n  cd ./destroot/Library/Frameworks || exit 1\n\n  local platforms=(\"$@\")\n  local args=\"\"\n\n  echo \"Creating universal framework for platforms: ${platforms[*]}\"\n\n  for i in \"${!platforms[@]}\"; do\n    args+=\"-framework ${platforms[$i]}/hermes.framework \"\n  done\n\n  mkdir universal\n  xcodebuild -create-xcframework $args -output \"universal/hermes.xcframework\"\n\n  for platform in $@; do\n    rm -r \"$platform\"\n  done\n\n  cd - || exit 1\n}\n", "num_lines": 120}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n. ./utils/build-apple-framework.sh\n\nif [ ! -d destroot/Library/Frameworks/universal/hermes.xcframework ]; then\n    ios_deployment_target=$(get_ios_deployment_target)\n\n    build_apple_framework \"iphoneos\" \"arm64\" \"$ios_deployment_target\"\n    build_apple_framework \"iphonesimulator\" \"x86_64;arm64\" \"$ios_deployment_target\"\n    build_apple_framework \"catalyst\" \"x86_64;arm64\" \"$ios_deployment_target\"\n\n    create_universal_framework \"iphoneos\" \"iphonesimulator\" \"catalyst\"\nelse\n    echo \"Skipping; Clean \\\"destroot\\\" to rebuild\".\nfi\n", "num_lines": 20}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n. ./utils/build-apple-framework.sh\nif [ ! -d destroot/Library/Frameworks/macosx/hermes.framework ]; then\n    mac_deployment_target=$(get_mac_deployment_target)\n\n    build_apple_framework \"macosx\" \"x86_64;arm64\" \"$mac_deployment_target\"\nelse\n    echo \"Skipping; Clean \\\"destroot\\\" to rebuild\".\nfi\n", "num_lines": 15}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif ! (return 0 2>/dev/null); then\n  echo \"commons.sh must be sourced\"\n  exit 1\nfi\n\n# Run a command repeatedly until it success (exit code is 0), up to X times.\n# For example, \"retry 3 make -j2\" will run \"make -j2\" repeatedly until\n# it fails 3 times or succeeds.\nfunction retry() {\n  RETRY=$1\n  ATTEMPTS=0\n  while (( ATTEMPTS <= RETRY )); do\n    \"${@:2}\" && return 0\n    ATTEMPTS=$((ATTEMPTS+1))\n    echo \"Retry: $ATTEMPTS failures so far\"\n  done\n  echo \"Retry depleted for command: ${*:2}\"\n  return 1\n}\n\n# Determine platform so that things like NT\n# don't need to be littered everywhere.\ncase \"$(uname)\" in\n  \"Linux\")\n    PLATFORM=\"linux\" ;;\n  \"Darwin\")\n    PLATFORM=\"macosx\" ;;\n  *\"_NT-\"*)\n    PLATFORM=\"windows\" ;;\n  *)\n    PLATFORM=\"unknown\" ;;\nesac\n\n# Setup Windows specific path conversion\nif [[ \"$PLATFORM\" == \"windows\" ]]; then\n  platform_path() {\n    # Cygwin, MSYS, and MSYS2 all provides cygpath\n    cygpath -m -- \"$@\"\n  }\n  # Disable MSYS and MSYS2 automatic path conversion. This script needs to run\n  # in both Cygwin and MSYS*. Allowing the automatic path conversion,\n  # which isn't available in Cygwin, allows bugs to hide.\n  export MSYS2_ARG_CONV_EXCL=\"*\"\n  export MSYS_NO_PATHCONV=1\nelse\n  platform_path() {\n    echo \"$@\"\n  }\nfi\n", "num_lines": 56}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nIFS=$'\\n'\nset -f\n\nall=0\nforce=0\nif [ \"$1\" == \"-a\" ]; then\n  shift\n  all=1\nelif [ \"$1\" == \"-f\" ]; then\n  shift\n  force=1\nfi\n\n[ -n \"$1\" ] && {\n  echo \"$0: Too many arguments\" >&2\n  exit 1\n}\n\n# Look for clang-format at a fixed path relative to the script.\nscript_path=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nclang_format_path=\"${script_path}/../../../tools/third-party/clang-format\"\nif [ \"$(uname)\" == Linux ]; then\n  clang_format=\"${clang_format_path}/linux/x86_64/clang-format\"\nelse\n  clang_format=\"${clang_format_path}/macos/clang-format\"\nfi\n\n# Fall back to one in $PATH if not found.\n[ -x \"${clang_format}\" ] || clang_format=\"$(which clang-format)\"\n\nif [ ! -x \"$clang_format\" ]; then\n  echo \"ERROR: Must have clang-format in PATH\"\n  exit 1\nfi\nclang_format_version=\"$(\"$clang_format\" --version)\"\nif echo \"$clang_format_version\" | grep -q -v '12.0.*'\nthen\n   printf \"ERROR: clang-format's version must match 12.0.*\\n  clang-format path: %s\\n  clang-format --version: %s\" \"$clang_format\" \"$clang_format_version\"\n   exit 1\nfi\n\nTHIS_DIR=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\ncd \"$THIS_DIR\"/../ || exit 1\n\nhave_changes=0       # We have uncommitted changes\nauthored_previous=0  # We authored the most recent commit on this branch\n\nif [[ $(hg status -mard 2>/dev/null) ]]; then\n  have_changes=1\nfi\n\nif hg log -l 1 --template=\"{author}\" | grep -q -e \"<$USER@\" -e \"^$USER$\"\nthen\n  authored_previous=1\nfi\n\nfiles=()\n\nif (( all )); then\n  echo \"Formatting all files...\"\n  files=(\n    $(find lib include tools unittests \\\n        -name \\*.h -print -o -name \\*.cpp -print)\n  )\nelif (( have_changes )); then\n  echo \"Formatting only modified files...\"\n  files=( $(hg st . -man --include \"**.{h,cpp,inc,def,mm,m}\") )\n\nelif (( authored_previous )) || (( force )); then\n  last_commit_files=( $(hg st . -man --change . | grep -E '\\.(h|cpp|inc|def|mm|m)$') )\n  echo \"There are no modified files, but you authored the last commit:\"\n  printf '  %s\\n' \"${last_commit_files[@]}\"\n  if (( !force )); then\n    read -r -p \"Format files in that commit? [y/N]\" reply\n    if [[ $reply != [Yy] ]]; then\n      echo \"Not doing anything.\"\n      exit 0\n    fi\n  fi\n  files=( \"${last_commit_files[@]}\" )\nelse\n  echo \"You have no modified files and you didn't recently commit on this branch.\"\n  echo \"To format all files: $0 -a\"\n  exit 1\nfi\n\nfor f in \"${files[@]}\"; do\n  before=$(date -r \"$f\")\n  \"$clang_format\" --verbose -i -style=file \"$f\" 2>&1 | tr -d \"\\n\"\n  echo -n '...'\n  after=$(date -r \"$f\")\n  test \"$before\" = \"$after\" && echo \"ok\" || echo \"reformatted\"\ndone\necho\necho \"Done\"\n", "num_lines": 102}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script generated the `lib/InternalBytecode/Promise.js` by performing the\n# below steps:\n#\n# 0. It copies the `util/promise/` to a tmp dir to run `yarn` and `rollup`. The\n#   tmp dir is always wiped away on Bash's trap exit so we can keep our source \n#   tree clean regardless of whether the script was success or not.\n#\n# 1. The Rollup is configured to build the `util/promise/index.js`, which\n#   imports the `promise` polyfill that we installed with `yarn`, exposes it to\n#   Hermes's globalThis, and then setup Hermes promise rejection tracking.\n#\n# 2. It adds `@nolint` to the start of the file and append a snippet to make \n#   the initialization of Promise conditionalized against \n#   `HermesInternal.hasPromise()` to ensure there is no runtime overhead when\n#   Hermes' Promise flag is disabled.\n#\n# 3. Finally, it moved the resulted file to the `InternalBytecode`.\n\n\nSCRIPT=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nBC_DIR=\"${SCRIPT}/../lib/InternalBytecode\"\nTMP_DIR=$(mktemp -d)\nPROMISE_DIR=\"${SCRIPT}/promise\"\nTMP_PROMISE_DIR=\"${TMP_DIR}/promise\"\n\nTMP_PROMISE_JS=\"${TMP_PROMISE_DIR}/Promise.js\"\nBC_PROMISE_JS=\"${BC_DIR}/01-Promise.js\"\n\nNOLINT=\"/* @nolint */\"\nPATCH1=\"  var useEngineQueue = HermesInternal.useEngineQueue()\\;\"\nPATCH2='(useEngineQueue ? HermesInternal.enqueueJob : setImmediate)'\n\ngen() {\n  # It's tricky to ensure `sed -i` work on both GNU and macOS consistently.\n  # https://stackoverflow.com/questions/5694228/sed-in-place-flag-that-works-both-on-mac-bsd-and-linux\n  sed -i.bak \"1s;^;${NOLINT};\" $TMP_PROMISE_JS && \\\n  sed -i.bak \"3s;^;${PATCH1};\" $TMP_PROMISE_JS && \\\n  sed -i.bak \"s/setImmediate/${PATCH2}/g\" $TMP_PROMISE_JS && \\\n  sed -i.bak '$ d' $TMP_PROMISE_JS && \\\n  cat <<EOT >> $TMP_PROMISE_JS\n});\nif (HermesInternal?.hasPromise?.()) {\n  initPromise();\n}\nEOT\n}\n\ncleanup() {\n  rm -rf $TMP_DIR\n}\n\ntrap cleanup EXIT\ncp -r $PROMISE_DIR $TMP_DIR\ncd $TMP_PROMISE_DIR\nyarn && yarn start && gen && mv $TMP_PROMISE_JS $BC_PROMISE_JS\n", "num_lines": 63}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ $(which clang-tidy) ]; then\n  FILES=`find lib include tools unittests -name \\*.h -print -o -name \\*.cpp -print`\n\n  FARRAY=( $FILES ) # count the number of files to process\n  echo  Inspecting ${#FARRAY[@]} files\n\n  for F in $FILES; do\n    clang-tidy $F -p ../build/ $1\n    echo -n .\n  done\n  echo\n  echo \"Done\"\n  exit\nfi\n\necho \"ERROR: can't find clang-tidy in your path.\"\n", "num_lines": 23}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# README:\n# To update the fbcode copy of Hermes, follow these steps:\n# 1) cd to fbsource/xplat/hermes/utils\n# 2) Run the current script: ./update-fbcode-hermes.sh\n#    This should leave you with files copied over, and new files as hg adds.\n# 3) Until we update the xplat hermes to the newer LLVM used in fbcode,\n#    if any of the files we had to modify for the LLVM version (only\n#    4, I believe) changed, we have to re-apply those changes.\n#    Those changes are in D10353003.  So attempt to build, in fbsource/fbcode:\n#      buick build xplat/hermes/...\n#    For any errors, check whether the file is one of those modified\n#    in the given diff, and reapply the changes.\n#    You may also get errors if BUCK files changed; if so, you need to\n#    make equivalent changes in the corresponding TARGETS file.\n#\n# Not completely automatic, but not too bad.\n\ncase $(pwd) in\n    *fbsource/xplat/hermes/utils) ;;\n    *) echo Must run from fbsource/xplat/hermes/utils; exit 1;;\nesac\n\n# Move to fbsource\ncd ../../.. || exit\n\n# copy hermes to fbcode\necho Copying hermes.\n/bin/cp -r xplat/hermes fbcode/xplat\n# Now remove some directories with large files we don't need in fbcode.\necho Removing unnecessary hermes subdirs.\n/bin/rm -rf fbcode/xplat/hermes/facebook/js_bundles\n/bin/rm -rf fbcode/xplat/hermes/facebook/sandcastle\n\n# copy jsi to fbcode\necho Copying jsi.\n/bin/cp -r xplat/jsi fbcode/xplat\n\n# Now do hg adds for any new files:\n\necho Doing hg adds.\nhg status > /tmp/hg-status.out\ngrep \"^\\\\? \" /tmp/hg-status.out > /tmp/hg-status2.out\nsed -e \"s/^\\\\?/hg add/\" /tmp/hg-status2.out > /tmp/hg-status3.out\n# This executes the shell commands in /tmp/hg-status3.out.  Like \"source\".\n. /tmp/hg-status3.out\n\n/bin/rm /tmp/hg-status.out /tmp/hg-status2.out /tmp/hg-status3.out\n", "num_lines": 54}
{"repo_name": "hermes", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script creates a build subdirectory called \"build_wasm\" and builds Hermes\n# inside it. The result (hermes.js, hermes.wasm) will be under \"build_wasm/bin\".\n# It requires three parameters:\n# - the path to Emscripten, so that it can find\n#   \"emscripten/cmake/Modules/Platform/Emscripten.cmake\" relative to it\n# - the path to the Hermes source tree\n# - the path to a host hermesc, so that it can find \"ImportHermesc.cmake\"\n#   relative to it. See <https://hermesengine.dev/docs/emscripten>\n#\n# An example of usage:\n#   ./build-hermes.sh ~/github/emsdk/upstream/ ~/github/hermes ~/hermes-host-hermesc\n\nSCRIPT=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nBUILD_DIR=\"${SCRIPT}/build_wasm\"\nREL_DIR=\"${SCRIPT}/static\"\n\nset -e\n\n[ -z \"$1\" ] && echo \"Emscripten path required\" && exit 1\nEMS_PATH=\"$1\"\nshift\n\n[ -z \"$1\" ] && echo \"Hermes path required\" && exit 1\nHERMES_PATH=\"$1\"\nshift\n\n[ -z \"$1\" ] && echo \"Host Hermesc path required\" && exit 1\nHOST_HERMESC_PATH=\"$1\"\nshift\n\nFLAGS=\"\"\nFLAGS=\"$FLAGS -s WASM=1\"\nFLAGS=\"$FLAGS -s ALLOW_MEMORY_GROWTH=0\"\nFLAGS=\"$FLAGS -s TOTAL_MEMORY=33554432\"\nFLAGS=\"$FLAGS -s MODULARIZE=1 -s EXPORT_NAME=createHermes\"\nFLAGS=\"$FLAGS -s INVOKE_RUN=0\"\nFLAGS=\"$FLAGS -s EXIT_RUNTIME=1\"\nFLAGS=\"$FLAGS -s NODERAWFS=0\"\nFLAGS=\"$FLAGS -s EXTRA_EXPORTED_RUNTIME_METHODS=[callMain,FS]\"\n\ncleanup() {\n  rm -rf \"$BUILD_DIR\"\n}\n\nconfigure() {\n  mkdir \"$BUILD_DIR\" && cd \"$BUILD_DIR\"\n  cmake \"$HERMES_PATH\" \\\n    -DCMAKE_TOOLCHAIN_FILE=\"$EMS_PATH/emscripten/cmake/Modules/Platform/Emscripten.cmake\" \\\n    -DCMAKE_BUILD_TYPE=MinSizeRel \\\n    -DIMPORT_HERMESC:PATH=\"$HOST_HERMESC_PATH/ImportHermesc.cmake\" \\\n    -DCMAKE_EXE_LINKER_FLAGS=\"$FLAGS\"\n}\n\nbuild () {\n  make -j hermes\n}\n\n# copy the build artifacts to release dir\ncopy () {\n  cp \"$BUILD_DIR/bin/hermes.js\" \"$REL_DIR/hermes.js\"\n  cp \"$BUILD_DIR/bin/hermes.wasm\" \"$REL_DIR/hermes.wasm\"\n}\n\ncleanup && configure && build && copy\n", "num_lines": 71}
{"repo_name": "idb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nset -o pipefail\n\nif hash xcpretty 2>/dev/null; then\n  HAS_XCPRETTY=true\nfi\n\nBUILD_DIRECTORY=build\n\nfunction invoke_xcodebuild() {\n  local arguments=$@\n  if [[ -n $HAS_XCPRETTY ]]; then\n    NSUnbufferedIO=YES xcodebuild $arguments | xcpretty -c\n  else\n    xcodebuild $arguments\n  fi\n}\n\nfunction framework_build() {\n  local name=$1\n  local output_directory=$2\n\n  invoke_xcodebuild \\\n    -project FBSimulatorControl.xcodeproj \\\n    -scheme $name \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    build\n\n  if [[ -n $output_directory ]]; then\n    framework_install $name $output_directory\n  fi\n}\n\nfunction framework_install() {\n  local name=$1\n  local output_directory=$2\n  local artifact=\"$BUILD_DIRECTORY/Build/Products/Debug/$name.framework\"\n  local output_directory_framework=\"$output_directory/Frameworks\"\n\n  echo \"Copying Build output of $artifact to $output_directory_framework\"\n  mkdir -p \"$output_directory_framework\"\n  cp -R $artifact \"$output_directory_framework/\"\n}\n\nfunction framework_test() {\n  local name=$1\n  invoke_xcodebuild \\\n    -project FBSimulatorControl.xcodeproj \\\n    -scheme $name \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    test\n}\n\nfunction core_framework_build() {\n  framework_build FBControlCore $1\n}\n\nfunction core_framework_test() {\n  framework_test FBControlCore\n}\n\nfunction xctest_framework_build() {\n  framework_build XCTestBootstrap $1\n}\n\nfunction xctest_framework_test() {\n  framework_test XCTestBootstrap\n}\n\nfunction simulator_framework_build() {\n  framework_build FBSimulatorControl $1\n}\n\nfunction simulator_framework_test() {\n  framework_test FBSimulatorControl\n}\n\nfunction device_framework_build() {\n  framework_build FBDeviceControl $1\n}\n\nfunction device_framework_test() {\n  framework_test FBDeviceControl\n}\n\nfunction all_frameworks_build() {\n  local output_directory=$1\n  core_framework_build $output_directory\n  xctest_framework_build $output_directory\n  simulator_framework_build $output_directory\n  device_framework_build $output_directory\n}\n\nfunction all_frameworks_test() {\n  core_framework_test\n  xctest_framework_test\n  simulator_framework_test\n  device_framework_test\n}\n\nfunction strip_framework() {\n  local FRAMEWORK_PATH=\"$BUILD_DIRECTORY/Build/Products/Debug/$1\"\n  if [ -d \"$FRAMEWORK_PATH\" ]; then\n    echo \"Stripping Framework $FRAMEWORK_PATH\"\n    rm -r \"$FRAMEWORK_PATH\"\n  fi\n}\n\nfunction cli_build() {\n  local name=$1\n  local output_directory=$2\n  local script_directory=$1/Scripts\n\n  invoke_xcodebuild \\\n    -workspace $name/$name.xcworkspace \\\n    -scheme $name \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    build\n\n  strip_framework \"FBSimulatorControlKit.framework/Versions/Current/Frameworks/FBSimulatorControl.framework\"\n  strip_framework \"FBSimulatorControlKit.framework/Versions/Current/Frameworks/FBDeviceControl.framework\"\n  strip_framework \"FBSimulatorControl.framework/Versions/Current/Frameworks/XCTestBootstrap.framework\"\n  strip_framework \"FBSimulatorControl.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n  strip_framework \"FBDeviceControl.framework/Versions/Current/Frameworks/XCTestBootstrap.framework\"\n  strip_framework \"FBDeviceControl.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n  strip_framework \"XCTestBootstrap.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n\n  if [[ -n $output_directory ]]; then\n    cli_install $output_directory $script_directory\n  fi\n}\n\nfunction cli_install() {\n  local output_directory=$1\n  local script_directory=$2\n  local cli_artifact=\"$BUILD_DIRECTORY/Build/Products/Debug/!(*.framework)\"\n  local framework_artifact=\"$BUILD_DIRECTORY/Build/Products/Debug/*.framework\"\n  local output_directory_cli=\"$output_directory/bin\"\n  local output_directory_framework=\"$output_directory/Frameworks\"\n\n  mkdir -p \"$output_directory_cli\"\n  mkdir -p \"$output_directory_framework\"\n\n  shopt -s extglob\n\n  echo \"Copying Build output from $cli_artifact to $output_directory_cli\"\n  cp -R $cli_artifact \"$output_directory_cli\"\n\n  echo \"Copying Build output from $framework_artifact to $output_directory_framework\"\n  cp -R $framework_artifact \"$output_directory_framework\"\n\n  if [[ -d $script_directory ]]; then\n    echo \"Copying Scripts from $script_directory to $output_directory_cli\"\n    cp -R \"$2\"/* \"$output_directory_cli\"\n  fi\n\n  shopt -u extglob\n}\n\nfunction cli_framework_test() {\n  NAME=$1\n  invoke_xcodebuild \\\n    -workspace $NAME/$NAME.xcworkspace \\\n    -scheme $NAME \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    test\n}\n\nfunction cli_e2e_test() {\n  NAME=$1\n  pushd $NAME/cli-tests\n  py=$(which python3.6 || which python3 || which python)\n  $py ./tests.py\n  popd\n}\n\nfunction print_usage() {\ncat <<EOF\n./build.sh usage:\n  /build.sh <target> <command> [<arg>]*\n\nSupported Commands:\n  help\n    Print usage.\n  framework build <output-directory>\n    Build the FBSimulatorControl.framework. Optionally copies the Framework to <output-directory>\n  framework test\n    Build then Test the FBSimulatorControl.framework.\n  fbxctest test\n    Builds the FBXCTestKit.framework and runs the tests.\nEOF\n}\n\nif [[ -n $TARGET ]]; then\n  echo \"using target $TARGET\"\nelif [[ -n $1 ]]; then\n  TARGET=$1\n  echo \"using target $TARGET\"\nelse\n  echo \"No target argument or $TARGET provided\"\n  print_usage\n  exit 1\nfi\n\nif [[ -n $COMMAND ]]; then\n  echo \"using command $COMMAND\"\nelif [[ -n $2 ]]; then\n  COMMAND=$2\n  echo \"using command $COMMAND\"\nelse\n  echo \"No command argument or $COMMAND provided\"\n  print_usage\n  exit 1\nfi\n\nif [[ -n $OUTPUT_DIRECTORY ]]; then\n  echo \"using output directory $OUTPUT_DIRECTORY\"\nelif [[ -n $3 ]]; then\n  echo \"using output directory $3\"\n  OUTPUT_DIRECTORY=$3\nelse\n  echo \"No output directory specified\"\nfi\n\ncase $TARGET in\n  help)\n    print_usage;;\n  framework)\n    case $COMMAND in\n      build)\n        all_frameworks_build $OUTPUT_DIRECTORY;;\n      test)\n        all_frameworks_test;;\n      *)\n        echo \"Unknown Command $2\"\n        exit 1;;\n    esac;;\n  fbxctest)\n    case $COMMAND in\n      build)\n        cli_build fbxctest $OUTPUT_DIRECTORY;;\n      test)\n        cli_framework_test fbxctest;;\n      *)\n        echo \"Unknown Command $COMMAND\"\n        exit 1;;\n    esac;;\n  *)\n    echo \"Unknown Command $TARGET\"\n    exit 1;;\nesac\n\n# vim: set tabstop=2 shiftwidth=2 filetype=sh:\n", "num_lines": 264}
{"repo_name": "idb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nset -o pipefail\n\nif hash xcpretty 2>/dev/null; then\n  HAS_XCPRETTY=true\nfi\n\nBUILD_DIRECTORY=build\n\nfunction invoke_xcodebuild() {\n  local arguments=$@\n  if [[ -n $HAS_XCPRETTY ]]; then\n    NSUnbufferedIO=YES xcodebuild $arguments | xcpretty -c\n  else\n    xcodebuild $arguments\n  fi\n}\n\nfunction build_idb_deps() {\n  if [ -n \"$CUSTOM_idb_DEPS_SCRIPT\" ]; then\n    \"$CUSTOM_idb_DEPS_SCRIPT\"\n  fi\n}\n\nfunction framework_build() {\n  local name=$1\n  local output_directory=$2\n\n  invoke_xcodebuild \\\n    -project FBSimulatorControl.xcodeproj \\\n    -scheme $name \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    build\n\n  if [[ -n $output_directory ]]; then\n    framework_install $name $output_directory\n  fi\n}\n\nfunction framework_install() {\n  local name=$1\n  local output_directory=$2\n  local artifact=\"$BUILD_DIRECTORY/Build/Products/Debug/$name.framework\"\n  local output_directory_framework=\"$output_directory/Frameworks\"\n\n  echo \"Copying Build output of $artifact to $output_directory_framework\"\n  mkdir -p \"$output_directory_framework\"\n  cp -R $artifact \"$output_directory_framework/\"\n}\n\nfunction core_framework_build() {\n  framework_build FBControlCore $1\n}\n\nfunction xctest_framework_build() {\n  framework_build XCTestBootstrap $1\n}\n\nfunction simulator_framework_build() {\n  framework_build FBSimulatorControl $1\n}\n\nfunction device_framework_build() {\n  framework_build FBDeviceControl $1\n}\n\nfunction all_frameworks_build() {\n  local output_directory=$1\n  core_framework_build $output_directory\n  xctest_framework_build $output_directory\n  simulator_framework_build $output_directory\n  device_framework_build $output_directory\n}\n\nfunction strip_framework() {\n  local FRAMEWORK_PATH=\"$BUILD_DIRECTORY/Build/Products/Release/$1\"\n  if [ -d \"$FRAMEWORK_PATH\" ]; then\n    echo \"Stripping Framework $FRAMEWORK_PATH\"\n    rm -r \"$FRAMEWORK_PATH\"\n  fi\n}\n\nfunction cli_build() {\n  local name=$1\n  local output_directory=$2\n  local script_directory=$1/Scripts\n\n  invoke_xcodebuild \\\n    ONLY_ACTIVE_ARCH=NO \\\n    -workspace $name.xcworkspace \\\n    -scheme $name \\\n    -sdk macosx \\\n    -derivedDataPath $BUILD_DIRECTORY \\\n    -configuration Release \\\n    build\n\n  strip_framework \"FBSimulatorControl.framework/Versions/Current/Frameworks/XCTestBootstrap.framework\"\n  strip_framework \"FBSimulatorControl.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n  strip_framework \"FBDeviceControl.framework/Versions/Current/Frameworks/XCTestBootstrap.framework\"\n  strip_framework \"FBDeviceControl.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n  strip_framework \"XCTestBootstrap.framework/Versions/Current/Frameworks/FBControlCore.framework\"\n\n  if [[ -n $output_directory ]]; then\n    cli_install $output_directory $script_directory\n  fi\n}\n\nfunction cli_install() {\n  local output_directory=$1\n  local script_directory=$2\n  local cli_artifact=\"$BUILD_DIRECTORY/Build/Products/Release/idb_companion\"\n  local framework_artifact=\"$BUILD_DIRECTORY/Build/Products/Release/*.framework\"\n  local output_directory_cli=\"$output_directory/bin\"\n  local output_directory_framework=\"$output_directory/Frameworks\"\n\n  mkdir -p \"$output_directory_cli\"\n  mkdir -p \"$output_directory_framework\"\n\n  shopt -s extglob\n\n  echo \"Copying Build output from $cli_artifact to $output_directory_cli\"\n  cp -R $cli_artifact \"$output_directory_cli\"\n\n  echo \"Copying Build output from $framework_artifact to $output_directory_framework\"\n  cp -R $framework_artifact \"$output_directory_framework\"\n\n  if [[ -d $script_directory ]]; then\n    echo \"Copying Scripts from $script_directory to $output_directory_cli\"\n    cp -R \"$2\"/* \"$output_directory_cli\"\n  fi\n\n  shopt -u extglob\n}\n\n\nfunction print_usage() {\ncat <<EOF\n./idb_build.sh usage:\n  /idb_build.sh <target> <command> [<arg>]*\n\nSupported Commands:\n  help\n    Print usage.\n  framework build <output-directory>\n    Build the frameworks. Optionally copies the Framework to <output-directory>\n  idb_companion build <output-directory>\n    Build the idb companion exectutable. Optionally copies the executable and its dependencies to <output-directory>\nEOF\n}\n\nif [[ -n $TARGET ]]; then\n  echo \"using target $TARGET\"\nelif [[ -n $1 ]]; then\n  TARGET=$1\n  echo \"using target $TARGET\"\nelse\n  echo \"No target argument or $TARGET provided\"\n  print_usage\n  exit 1\nfi\n\nif [[ -n $COMMAND ]]; then\n  echo \"using command $COMMAND\"\nelif [[ -n $2 ]]; then\n  COMMAND=$2\n  echo \"using command $COMMAND\"\nelse\n  echo \"No command argument or $COMMAND provided\"\n  print_usage\n  exit 1\nfi\n\nif [[ -n $OUTPUT_DIRECTORY ]]; then\n  echo \"using output directory $OUTPUT_DIRECTORY\"\nelif [[ -n $3 ]]; then\n  echo \"using output directory $3\"\n  OUTPUT_DIRECTORY=$3\nelse\n  echo \"No output directory specified\"\nfi\n\ncase $TARGET in\n  help)\n    print_usage;;\n  framework)\n    case $COMMAND in\n      build)\n        all_frameworks_build $OUTPUT_DIRECTORY;;\n      *)\n        echo \"Unknown Command $2\"\n        exit 1;;\n    esac;;\n  idb_companion)\n    build_idb_deps\n    case $COMMAND in\n      build)\n        cli_build idb_companion $OUTPUT_DIRECTORY;;\n      *)\n        echo \"Unknown Command $COMMAND\"\n        exit 1;;\n    esac;;\n  *)\n    echo \"Unknown Command $TARGET\"\n    exit 1;;\nesac\n\n# vim: set tabstop=2 shiftwidth=2 filetype=sh:\n", "num_lines": 215}
{"repo_name": "idb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nSCRIPT=\"$(realpath \"$0\")\"\nSCRIPTPATH=\"$(dirname \"$SCRIPT\")\"\nRUNNER_FRAMEWORK_DIR=\"$SCRIPTPATH/FBTestRunnerApp/Frameworks\"\nXCODE_PATH=$(xcode-select -p)\n\nif [ ! -d \"$RUNNER_FRAMEWORK_DIR\" ]; then\n  mkdir \"$RUNNER_FRAMEWORK_DIR\"\nfi\n\nrm -rf \"${RUNNER_FRAMEWORK_DIR:-}/*\"\ncp -rf \"$XCODE_PATH/Platforms/iPhoneSimulator.platform/Developer/Library/Frameworks/XCTest.framework\" \"$RUNNER_FRAMEWORK_DIR\"\ncp -rf \"$XCODE_PATH/Platforms/iPhoneSimulator.platform/Developer/Library/PrivateFrameworks/XCTAutomationSupport.framework\" \"$RUNNER_FRAMEWORK_DIR\"\n", "num_lines": 21}
{"repo_name": "idx", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n#\n# Build script for `idx`. Run using `npm run build`.\n#\n\nset -e\nset -u\n\nROOT_DIR=$(dirname \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\")\n\nbabel \"$ROOT_DIR/src\" --out-dir \"$ROOT_DIR/lib\" --ignore test.js --copy-files\n\n# Strip `@providesModule` from lib/**/*.js.\nfind \"$ROOT_DIR/lib\" -type f -name '*.js' -exec \\\n  sed -i '' '/^ \\* @providesModule /d' {} \\;\n", "num_lines": 21}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# make sure we run from the root of the repo\npushd \"$SCRIPT_DIR\" > /dev/null\n\n# We need to record the date that the documentation was last modified to put in our man\n# pages. Unfortunately that information is only available reliably from `git`, which we don't have\n# access to from other distributions of the infer source code. Such source distributions should\n# distribute the \"configure\" script too. The idea is to bake this date inside \"configure\" so that\n# it's available at build time. We do that by generating an m4 macro that hardcodes the date we\n# compute in this script for \"configure\" to find.\nMAN_LAST_MODIFIED_M4=m4/__GENERATED__ac_check_infer_man_last_modified.m4\nprintf 'generating %s' \"$MAN_LAST_MODIFIED_M4... \"\nif test -d '.git' ; then\n  # date at which the man pages were last modified, to record in the manpages themselves\n  MAN_FILES=(\n      infer/src/base/CommandLineOption.ml\n      infer/src/base/Config.ml\n  )\n  MAN_DATE=$(git log -n 1 --pretty=format:%cd --date=short -- \"${MAN_FILES[@]}\")\n  INFER_MAN_LAST_MODIFIED=${INFER_MAN_LAST_MODIFIED:-$MAN_DATE}\nelse\n  echo 'no git repository detected; setting last modified date to today'\n  # best effort: get today's date\n  INFER_MAN_LAST_MODIFIED=${INFER_MAN_LAST_MODIFIED:-$(date +%Y-%m-%d)}\nfi\n\nprintf \"AC_DEFUN([AC_CHECK_INFER_MAN_LAST_MODIFIED],\\n\" > \"$MAN_LAST_MODIFIED_M4\"\nprintf \"[INFER_MAN_LAST_MODIFIED=%s\\n\" \"$INFER_MAN_LAST_MODIFIED\" >> \"$MAN_LAST_MODIFIED_M4\"\nprintf \" AC_SUBST([INFER_MAN_LAST_MODIFIED])\\n\" >> \"$MAN_LAST_MODIFIED_M4\"\nprintf \"])\\n\" >> \"$MAN_LAST_MODIFIED_M4\"\nprintf 'done\\n'\n\n# older versions of `autoreconf` only support including macros via acinclude.m4\nACINCLUDE=\"acinclude.m4\"\nprintf \"generating $ACINCLUDE...\"\ncat m4/*.m4 > \"$ACINCLUDE\"\nprintf \" done\\n\"\n\nprintf \"generating ./configure script...\"\nautoreconf -fi\nprintf \" done\\n\"\n\necho \"\"\necho \"you may now run the following commands to build Infer:\"\necho \"\"\necho \"  ./configure\"\necho \"  make\"\necho \"\"\necho 'run `./configure --help` for more options'\n", "num_lines": 60}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Convenience script to build Infer when using opam\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nset -o pipefail\nset -u\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nINFER_ROOT=\"$SCRIPT_DIR\"\nDEPENDENCIES_DIR=\"$INFER_ROOT/facebook/dependencies\"\nPLATFORM=\"$(uname)\"\nSANDCASTLE=${SANDCASTLE:-}\nNCPU=\"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 1)\"\nINFER_OPAM_DEFAULT_SWITCH=\"4.14.0+flambda\"\nINFER_OPAM_DEFAULT_SWITCH_OPTIONS=\"--package=ocaml-variants.4.14.0+options,ocaml-option-flambda\"\nINFER_OPAM_SWITCH=${INFER_OPAM_SWITCH:-$INFER_OPAM_DEFAULT_SWITCH}\nINFER_OPAM_SWITCH_OPTIONS=${INFER_OPAM_SWITCH_OPTIONS:-$INFER_OPAM_DEFAULT_SWITCH_OPTIONS}\nPLUGIN_DIR=\"$INFER_ROOT/facebook-clang-plugins\"\nPLUGIN_SETUP_SCRIPT=${PLUGIN_SETUP_SCRIPT:-setup.sh}\nPLUGIN_SETUP=\"${PLUGIN_DIR}/clang/${PLUGIN_SETUP_SCRIPT}\"\n\nfunction usage() {\n  echo \"Usage: $0 [options] [targets] [-- options for ./configure]\"\n  echo\n  echo \" targets:\"\n  echo \"   all      build everything (default)\"\n  echo \"   clang    build C and Objective-C analyzer\"\n  echo \"   erlang   build Erlang analyzer\"\n  echo \"   hack     build Hack analyzer\"\n  echo \"   java     build Java analyzer\"\n  echo \"   python   build Python analyzer\"\n  echo\n  echo \" options:\"\n  echo \"   -h,--help             show this message\"\n  echo \"   --no-opam-lock        do not use the opam/infer.opam.locked file and let opam resolve dependencies\"\n  echo \"   --only-setup-opam     initialize opam, install the opam dependencies of infer, and exit\"\n  echo \"   --user-opam-switch    use the current opam switch to install infer (default: $INFER_OPAM_DEFAULT_SWITCH)\"\n  echo \"   -y,--yes              automatically agree to everything\"\n  echo \"   --                    stop parsing options and pass the remaining ones to ./configure\"\n  echo\n  echo \" examples:\"\n  echo \"    $0                                 # build infer with default options\"\n  echo \"    $0 -- --help                       # display the options from ./configure\"\n  echo \"    $0 java                            # build only the Java analyzer\"\n  echo \"    $0 -y -- --disable-clang-analyzers # build everything but clang support, agree to all questions\"\n}\n\n# arguments\nCONFIGURE_OPTS=()\nBUILD_CLANG=${BUILD_CLANG:-no}\nBUILD_ERLANG=${BUILD_ERLANG:-no}\nBUILD_HACK=${BUILD_HACK:-no}\nBUILD_JAVA=${BUILD_JAVA:-no}\nBUILD_PYTHON=${BUILD_PYTHON:-no}\nINTERACTIVE=${INTERACTIVE:-yes}\nJOBS=${JOBS:-$NCPU}\nONLY_SETUP_OPAM=${ONLY_SETUP_OPAM:-no}\nUSE_OPAM_LOCK=${USE_OPAM_LOCK:-yes}\nUSER_OPAM_SWITCH=no\n\nORIG_ARGS=\"$*\"\n\nfunction build_all() {\n  BUILD_CLANG=yes\n  BUILD_ERLANG=yes\n  BUILD_HACK=yes\n  BUILD_JAVA=yes\n  BUILD_PYTHON=yes\n}\n\nwhile [[ $# -gt 0 ]]; do\n  opt_key=\"$1\"\n  case $opt_key in\n    all)\n      build_all\n      shift\n      continue\n      ;;\n    clang)\n      BUILD_CLANG=yes\n      shift\n      continue\n      ;;\n    erlang)\n      BUILD_ERLANG=yes\n      shift\n      continue\n      ;;\n    hack)\n      BUILD_HACK=yes\n      shift\n      continue\n      ;;\n    java)\n      BUILD_JAVA=yes\n      shift\n      continue\n      ;;\n    python)\n      BUILD_PYTHON=yes\n      shift\n      continue\n      ;;\n    -h|--help)\n      usage\n      exit 0\n     ;;\n    --no-opam-lock)\n      USE_OPAM_LOCK=no\n      shift\n      continue\n     ;;\n    --user-opam-switch)\n      USER_OPAM_SWITCH=yes\n      shift\n      continue\n     ;;\n    --only-setup-opam)\n      ONLY_SETUP_OPAM=yes\n      shift\n      continue\n     ;;\n    -y|--yes)\n      INTERACTIVE=no\n      shift\n      continue\n     ;;\n    --)\n      shift\n      CONFIGURE_OPTS+=(\"$*\")\n      shift $#\n      continue\n     ;;\n     *)\n      usage\n      exit 1\n  esac\n  shift\ndone\n\nif [ \"$BUILD_CLANG\" == \"no\" ] && [ \"$BUILD_ERLANG\" == \"no\" ] && \\\n   [ \"$BUILD_HACK\" == \"no\" ] && [ \"$BUILD_JAVA\" == \"no\" ] && \\\n   [ \"$BUILD_PYTHON\" == \"no\" ]; then\n  build_all\nfi\n\n# enable --yes option for some commands in non-interactive mode\nYES=\nif [ \"$INTERACTIVE\" == \"no\" ]; then\n  YES=--yes\nfi\n# --yes by default for opam commands except if we are using the user's opam switch\nif [ \"$INTERACTIVE\" == \"no\" ] || [ \"$USER_OPAM_SWITCH\" == \"no\" ]; then\n    export OPAMYES=true\nfi\n\nsetup_opam () {\n    opam var root 1>/dev/null 2>/dev/null || opam init --reinit --bare --no-setup &&\n    opam_retry opam_switch_create_if_needed \"$INFER_OPAM_SWITCH\" \"$INFER_OPAM_SWITCH_OPTIONS\" &&\n    opam switch set \"$INFER_OPAM_SWITCH\"\n}\n\ninstall_opam_deps () {\n    local locked=\n    if [ \"$USE_OPAM_LOCK\" == yes ]; then\n        locked=.locked\n    fi\n    opam install --deps-only \"$INFER_ROOT\"/opam/infer.opam$locked\n}\n\necho \"initializing opam... \" >&2\n. \"$INFER_ROOT\"/scripts/opam_utils.sh\nif [ \"$USER_OPAM_SWITCH\" == \"no\" ]; then\n    setup_opam\nfi\neval $(SHELL=bash opam env)\necho >&2\necho \"installing infer dependencies; this can take up to 30 minutes... \" >&2\nopam_retry install_opam_deps\n\nif [ \"$ONLY_SETUP_OPAM\" == \"yes\" ]; then\n  exit 0\nfi\n\necho \"preparing build... \" >&2\n./autogen.sh > /dev/null\n\n# we want to add these before the ones passed explicitly by the user, if only because they\n# correspond to options that appear earlier on the command line of this script so it's the more\n# natural behaviour\nCONFIGURE_PREPEND_OPTS=\"\"\nif [ \"$BUILD_CLANG\" == \"no\" ]; then\n  CONFIGURE_PREPEND_OPTS+=\" --disable-c-analyzers\"\nfi\nif [ \"$BUILD_ERLANG\" == \"no\" ]; then\n  CONFIGURE_PREPEND_OPTS+=\" --disable-erlang-analyzers\"\nfi\nif [ \"$BUILD_HACK\" == \"no\" ]; then\n  CONFIGURE_PREPEND_OPTS+=\" --disable-hack-analyzers\"\nfi\nif [ \"$BUILD_JAVA\" == \"no\" ]; then\n  CONFIGURE_PREPEND_OPTS+=\" --disable-java-analyzers\"\nfi\nif [ \"$BUILD_PYTHON\" == \"no\" ]; then\n  CONFIGURE_PREPEND_OPTS+=\" --disable-python-analyzers\"\nfi\n\nset -x\n# empty arrays trigger unbound variable errors, use horrible syntax to work around it\n./configure $CONFIGURE_PREPEND_OPTS ${CONFIGURE_OPTS[@]+\"${CONFIGURE_OPTS[@]}\"}\nset +x\n\n# test if clang is enabled and if so are we about to build it? we cannot rely on $BUILD_CLANG\n# because the user can also set --disable-clang-analyzers\nif [ $(grep BUILD_C_ANALYZERS Makefile.autoconf | cut -d ' ' -f 3) = \"yes\" ]; then\n  if ! \"$PLUGIN_SETUP\" --only-check-install; then\n    echo \"\"\n    echo \"  Warning: you are not using a release of Infer. The C and\"\n    echo \"  Objective-C analyses require a custom clang to be compiled\"\n    echo \"  now. This step takes ~30-60 minutes, possibly more.\"\n    echo \"\"\n    echo \"  To speed this along, you are encouraged to use a release of\"\n    echo \"  Infer instead:\"\n    echo \"\"\n    echo \"  http://fbinfer.com/docs/getting-started\"\n    echo \"\"\n    echo \"  If you are only interested in analyzing Java programs, simply\"\n    echo \"  run this script with only the \\\"java\\\" argument:\"\n    echo \"\"\n    echo \"  $0 java\"\n    echo \"\"\n\n    confirm=\"n\"\n    printf \"Are you sure you want to compile clang? (y/N) \"\n    if [ \"$INTERACTIVE\" == \"no\" ]; then\n        confirm=\"y\"\n        echo \"$confirm\"\n    else\n        read confirm\n    fi\n\n    if [ \"x$confirm\" != \"xy\" ]; then\n        exit 0\n    fi\n\n    # only run this script if we are definitely building clang\n    facebook-clang-plugins/clang/src/prepare_clang_src.sh\n  fi\nfi\n\nmake -j \"$JOBS\" opt || (\n  echo >&2\n  echo '  compilation failure; you can try running' >&2\n  echo >&2\n  echo '    make clean' >&2\n  echo \"    '$0' $ORIG_ARGS\" >&2\n  echo >&2\n  exit 1)\n\necho\necho \"*** Success! Infer is now built in '$SCRIPT_DIR/infer/bin/'.\"\necho '*** Install infer on your system with `make install`.'\necho\necho '*** If you plan to hack on infer, check out CONTRIBUTING.md to setup your dev environment.'\n", "num_lines": 271}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\ninfer -- make -C 00 clean all\ninfer -- make -C 01 clean all\ninfer explore --no-source-preview --select 1\ninfer -- make -C 02 clean all\ninfer explore --no-source-preview --select 0\ninfer -- make -C 03 clean all\ninfer explore --no-source-preview --select 1\ninfer --eradicate-only -- make -C 04 clean all\n", "num_lines": 17}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Simple installation script for llvm/clang.\n\nset -e\nset -o pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nCLANG_RELATIVE_SRC=\"src/download/llvm-project/llvm\"\nCLANG_SRC=\"${CLANG_SRC:-$SCRIPT_DIR/$CLANG_RELATIVE_SRC}\"\nCLANG_PREFIX=\"$SCRIPT_DIR/install\"\nCLANG_INSTALLED_VERSION_FILE=\"$SCRIPT_DIR/installed.version\"\nPATCHELF=${PATCHELF:-patchelf}\nPLATFORM=$(uname)\nPLATFORM_ENV=${PLATFORM_ENV:-}\nSTRIP=${STRIP:-strip}\nCMAKE=${CMAKE:-cmake}\nZLIB=${ZLIB:-$CLANG_SRC}\n\nNCPUS=\"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)\"\nJOBS=\"${JOBS:-$(($NCPUS>=8?$NCPUS/4:2))}\"\n\nSHASUM=${SHASUM:-shasum -a 256}\n\nusage () {\n    echo \"Usage: $0 [-chr]\"\n    echo\n    echo \" options:\"\n    echo \"    -c,--only-check-install    check if recompiling clang is needed\"\n    echo \"    -h,--help                  show this message\"\n    echo \"    -n,--ninja                 use ninja for building\"\n    echo \"    -p,--clang-hash            print the installed clang hash\"\n    echo \"    -r,--only-record-install   do not install clang but pretend we did\"\n    echo \"    -s,--sequential-link       only use one process for linking (ninja only)\"\n}\n\nclang_hash () {\n    if [ \"$CLANG_HASH_USE_GIT\" = \"yes\" ]; then\n        HASH=$(git -C \"$CLANG_SRC\" rev-parse HEAD)\n        echo \"$HASH\"\n    else\n        pushd \"$SCRIPT_DIR\" > /dev/null\n        HASH=$($SHASUM setup.sh src/prepare_clang_src.sh | $SHASUM)\n        printf \"%s\" \"$HASH\" | cut -d ' ' -f 1\n        popd > /dev/null\n    fi\n}\n\ncheck_installed () {\n    pushd \"$SCRIPT_DIR\" > /dev/null\n    HASH=$(clang_hash)\n    RESULT=1\n    if [ -f \"$CLANG_INSTALLED_VERSION_FILE\" ]; then\n        FILE_HASH=$(cat \"$CLANG_INSTALLED_VERSION_FILE\")\n        if [ \"$HASH\" == \"$FILE_HASH\" ]; then\n            RESULT=0\n        fi\n    fi\n    popd > /dev/null\n    return $RESULT\n}\n\nrecord_installed () {\n    pushd \"$SCRIPT_DIR\" > /dev/null\n    HASH=$(clang_hash)\n    echo $HASH > \"$CLANG_INSTALLED_VERSION_FILE\"\n    popd > /dev/null\n}\n\nONLY_CHECK=\nONLY_RECORD=\nPRINT_CLANG_HASH=\nUSE_NINJA=\nSEQUENTIAL_LINK=\n\nwhile [[ $# -gt 0 ]]; do\n    opt_key=\"$1\"\n    case $opt_key in\n        -p|--clang-hash)\n            PRINT_CLANG_HASH=yes\n            shift\n            continue\n            ;;\n        -c|--only-check-install)\n            ONLY_CHECK=yes\n            shift\n            continue\n            ;;\n        -r|--only-record-install)\n            ONLY_RECORD=yes\n            shift\n            continue\n            ;;\n        -n|--ninja)\n            USE_NINJA=yes\n            shift\n            continue\n            ;;\n        -s|--sequential-link)\n            SEQUENTIAL_LINK=yes\n            shift\n            continue\n            ;;\n        -h|--help)\n            usage\n            exit 0\n            ;;\n        *)\n            usage\n            exit 2\n    esac\n    shift\ndone\n\nif [ \"$PRINT_CLANG_HASH\" = \"yes\" ]; then\n    clang_hash\n    exit 0\nfi\n\nif [ \"$ONLY_RECORD\" = \"yes\" ]; then\n    record_installed\n    exit 0\nfi\n\nif check_installed; then\n    # already installed\n    if [ \"$ONLY_CHECK\" = \"yes\" ]; then\n        exit 0\n    fi\n    echo \"Clang is already installed according to $CLANG_INSTALLED_VERSION_FILE\"\n    echo \"Nothing to do, exiting.\"\n    exit 0\nelse\n    if [ \"$ONLY_CHECK\" = \"yes\" ]; then\n        exit 1\n    fi\nfi\n\nset -x\n\nif [[ x\"$MAKEFLAGS\" != x ]]; then\n    echo \"WARNING: MAKEFLAGS var was set to: $MAKEFLAGS\"\n    echo \"         which may (and will!) interfere with the setup\"\n    echo \"         ... ignoring MAKEFLAGS.\"\n    unset MAKEFLAGS\nfi\n\nif [[ x\"$DESTDIR\" != x ]]; then\n    echo \"WARNING: DESTDIR var was set to: $DESTDIR\"\n    echo \"         but the setup script is not designed to handle\"\n    echo \"         relocation of the installation.\"\n    echo \"         ... ignoring DESTDIR.\"\n    unset DESTDIR\nfi\n\nif [[ \"$PLATFORM\" = \"Linux\" ]] && [[ -n \"${PLATFORM_ENV}\" ]] ; then\n    CXXFLAGS=\"$CXXFLAGS -DHAVE_RPC_XDR_H=0 -D_GLIBCXX_INCLUDE_NEXT_C_HEADERS -Wl,-rpath-link,${PLATFORM_ENV}/lib\"\nfi\n\nCMAKE_ARGS=(\n  -DCMAKE_BUILD_TYPE=Release\n  -DCMAKE_C_FLAGS=\"$CFLAGS $CMAKE_C_FLAGS\"\n  -DCMAKE_CXX_FLAGS=\"$CXXFLAGS $CPPFLAGS $CMAKE_CXX_FLAGS\"\n  -DCMAKE_INSTALL_PREFIX=\"$CLANG_PREFIX\"\n  -DLLVM_BUILD_EXTERNAL_COMPILER_RT=On\n  -DLLVM_BUILD_TOOLS=Off\n  -DLLVM_ENABLE_ASSERTIONS=Off\n  -DLLVM_ENABLE_EH=On\n  -DLLVM_ENABLE_RTTI=On\n  -DLLVM_INCLUDE_DOCS=Off\n  -DLLVM_INCLUDE_EXAMPLES=Off\n  -DLLVM_INCLUDE_TESTS=Off\n  -DLLVM_TARGETS_TO_BUILD=\"X86;AArch64;ARM;Mips\"\n)\n\nif [ \"$PLATFORM\" = \"Darwin\" ]; then\n    CMAKE_ARGS+=(\n      -DLLVM_ENABLE_LIBCXX=On\n      -DCMAKE_SHARED_LINKER_FLAGS=\"$LDFLAGS $CMAKE_SHARED_LINKER_FLAGS\"\n      -DLLVM_BUILD_LLVM_DYLIB=ON\n    )\nelse\n    CMAKE_ARGS+=(\n      -DCMAKE_SHARED_LINKER_FLAGS=\"$LDFLAGS $CMAKE_SHARED_LINKER_FLAGS -lstdc++ -fPIC\"\n    )\nfi\n\nif [[ \"$PLATFORM\" = \"Linux\" ]] && [[ -n \"${PLATFORM_ENV}\" ]] ; then\n    # Please note that this case only applies to infer/master platform builds\n    # Prevent CMAKE from adding -isystem /usr/include for platform builds\n    CMAKE_ARGS+=(\n        -DLLVM_ENABLE_PROJECTS=\"clang;compiler-rt\"\n        -DLLVM_ENABLE_RUNTIMES=\"libcxx;libcxxabi\"\n        -DZLIB_INCLUDE_DIR=\"$ZLIB/include\"\n    )\nelse\n    CMAKE_ARGS+=(-DLLVM_ENABLE_PROJECTS=\"clang;compiler-rt;openmp\"\n                 -DLLVM_ENABLE_RUNTIMES=\"libcxx;libcxxabi\"\n    )\nfi\n\nif [ \"$USE_NINJA\" = \"yes\" ]; then\n    CMAKE_GENERATOR=\"Ninja\"\n    BUILD_BIN=\"ninja\"\n    # Do not set a 'j' build default for Ninja (let Ninja decide)\n    BUILD_ARGS=\"\"\nelse\n    CMAKE_GENERATOR=\"Unix Makefiles\"\n    BUILD_BIN=\"make\"\n    BUILD_ARGS=\"-j $JOBS\"\nfi\n\nif [ \"$SEQUENTIAL_LINK\" = \"yes\" ]; then\n    if [[ x\"$USE_NINJA\" = x ]]; then\n        echo \"Linking with a single process is only supported with the Ninja generator.\"\n        echo \"Unable to proceed, exiting.\"\n        exit 1\n    fi\n    # For Ninja, the compile jobs is the number of CPUs *not* $JOBS\n    CMAKE_ARGS+=(\n        -DCMAKE_JOB_POOLS:STRING=\"compile=$NCPUS;link=1\"\n        -DCMAKE_JOB_POOL_COMPILE:STRING=\"compile\"\n        -DCMAKE_JOB_POOL_LINK:STRING=\"link\"\n    )\nfi\n\n# start the installation\nif [ ! -d \"$CLANG_SRC\" ]; then\n    echo \"Clang src (${CLANG_SRC}) missing, please run src/prepare_clang_src.sh\"\n    exit 1\nfi\n\nif [ -n \"$CLANG_TMP_DIR\" ]; then\n    TMP=$CLANG_TMP_DIR\nelse\n    TMP=`mktemp -d ${TMPDIR-/tmp}/clang-setup.XXXXXX`\nfi\npushd \"$TMP\"\n\nmkdir -p build\npushd build\n\n# workaround install issue with ocaml llvm bindings and ocamldoc\nmkdir -p docs/ocamldoc/html\n\n$CMAKE -G \"$CMAKE_GENERATOR\" \"$CLANG_SRC\" \"${CMAKE_ARGS[@]}\" $CLANG_CMAKE_ARGS\n\n$BUILD_BIN $BUILD_ARGS\n\necho \"testing clang build\"\n./bin/clang --version\n\n# \"uninstall\" previous clang\nrm -fr \"$CLANG_PREFIX\"\n\n$BUILD_BIN $BUILD_ARGS install\n\npopd # build\npopd # $TMP\n\n# On Linux, copy __config_site to install directory. This way we don't need additional -I statements\nCONFIG_SITE=\"$CLANG_PREFIX/include/x86_64-unknown-linux-gnu/c++/v1/__config_site\"\nif [[ \"$PLATFORM\" = \"Linux\" ]] && [[ -f \"$CONFIG_SITE\" ]]; then\n    cp -f \"$CONFIG_SITE\" \"$CLANG_PREFIX/include/c++/v1/__config_site\"\nfi\n\n# delete libs not needed by Infer\nif [ \"$KEEP_LIBS\" != \"yes\" ]; then\n    rm -v \"$CLANG_PREFIX\"/lib/libclang*\n    rm -v \"$CLANG_PREFIX\"/lib/libLLVM*\nfi\n\n# brutally strip everything, ignore errors\nset +e\nfind \"$CLANG_PREFIX\"/{bin,lib} -type f -exec \"$STRIP\" -x \\{\\} \\;\n\nif [[ \"$PLATFORM\" = \"Linux\" ]] && [[ -n \"${PLATFORM_ENV}\" ]]; then\n    # patch binaries to use platform_env rpath, ignore errors\n    find \"$CLANG_PREFIX\"/{bin,lib} -type f -exec \"$PATCHELF\" --set-rpath \"${PLATFORM_ENV}/lib\" \\{\\} \\;\nfi\nset -e\n\necho \"testing installed clang\"\n\"$CLANG_PREFIX\"/bin/clang --version\n\necho \"deleting temp dir '$CLANG_TMP_DIR'...\"\nif [ -n \"$CLANG_TMP_DIR\" ]; then\n    rm -rf \"$TMP/*\"\nelse\n    rm -rf \"$TMP\"\nfi\n\nrecord_installed\n", "num_lines": 298}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Download llvm, clang and needed libraries\n\nset -e\nset -o pipefail\n\nSCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nSHASUM=${SHASUM:-shasum -a 256}\nPATCH=${PATCH:-patch}\n\nLLVM_VER=\"16.0.0\"\nLLVM_URL=\"https://github.com/llvm/llvm-project/releases/download/llvmorg-${LLVM_VER}/llvm-project-${LLVM_VER}.src.tar.xz\"\nLLVM_SHA=\"9a56d906a2c81f16f06efc493a646d497c53c2f4f28f0cb1f3c8da7f74350254\"\nLLVM_FILE=\"llvm-project.src.tar.xz\"\nCLANG_PREBUILD_PATCHES=(\n    \"$SCRIPT_DIR/err_ret_local_block.patch\"\n    \"$SCRIPT_DIR/mangle_suppress_errors.patch\"\n    \"$SCRIPT_DIR/AArch64SVEACLETypes.patch\"\n)\n\nmkdir -p \"${SCRIPT_DIR}/download\"\npushd \"${SCRIPT_DIR}/download\" >/dev/null\n\nif ! echo \"${LLVM_SHA}  ${LLVM_FILE}\" | $SHASUM -c ; then\n  echo \"wrong checksum for $LLVM_FILE, downloading it again\"\n  rm -f \"$LLVM_FILE\"\nfi\n\nif [ ! -f \"${LLVM_FILE}\" ]; then\n    curl -L \"${LLVM_URL}\" --output \"${LLVM_FILE}\"\nfi\necho \"${LLVM_SHA}  ${LLVM_FILE}\" | $SHASUM -c\n\nrm -rf \"llvm-project-${LLVM_VER}.src\" \"llvm-project\"\n\ntar xf \"${LLVM_FILE}\"\nmv \"llvm-project-${LLVM_VER}.src\" \"llvm-project\"\n\nif [ \"$SKIP_PATCH\" != \"yes\" ]; then\n    # apply prebuild patch\n    for PATCH_FILE in \"${CLANG_PREBUILD_PATCHES[@]}\"; do\n        \"$PATCH\" --force -p 1 < \"$PATCH_FILE\"\n    done\nfi\n\npopd >/dev/null\n", "num_lines": 52}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Script to validate Yojson outputs w.r.t. ATD specifications.\n# This works by running a given 'converter' to parse and pretty-print the outputs, then observing the difference with gunzip + pretty-print.\n\nif [ \"$2\" == \"--std\" ]; then\n    CONVERTER=(\"$1\" --std --pretty)\n    YDUMP=(ydump -std)\n    shift 2\nelse\n    CONVERTER=(\"$1\" --pretty)\n    YDUMP=(ydump)\n    shift\nfi\n\nwhile [ -n \"$1\" ]\ndo\n    if [[ \"$1\" == *.gz ]]; then\n        DUMP_CMD=(gunzip -c \"$1\")\n    else\n        DUMP_CMD=(cat \"$1\")\n    fi\n\n    if ! diff -q <(\"${DUMP_CMD[@]}\" | \"${YDUMP[@]}\") <(\"${CONVERTER[@]}\" \"$1\" /dev/stdout) >/dev/null 2>&1; then\n        echo \"The file '$1' does not respect the ATD format implemented by $CONVERTER.\"\n        echo \"Here is the command that shows the problem:\"\n        echo -n \"  diff <(\"\n        printf '%s ' \"${DUMP_CMD[@]}\"\n        echo -n \"| \"\n        printf '\"%s\" ' \"${YDUMP[@]}\"\n        echo -n \") <(\"\n        printf '\"%s\" ' \"${CONVERTER[@]}\" \"$1\"\n        echo \"/dev/stdout)\"\n        exit 2\n    fi\n\n    shift;\ndone\n", "num_lines": 43}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n./build/binioutest | bdump\n", "num_lines": 8}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"$@\" | bdump\n", "num_lines": 7}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"$@\"\n", "num_lines": 7}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\"$@\"\n", "num_lines": 7}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n#!/bin/bash\n\nTESTFILE=\"$1\"\nshift\nTESTNAME=`basename \"$TESTFILE\"`\n\nOUTFILE=\"$TESTFILE.out\"\nEXPFILE=\"$TESTFILE.exp\"\nDIFFFILE=\"$TESTFILE.diff\"\n\nif [[ $VERBOSE > 0 ]]\nthen\n    DEST=/dev/stdout\nelse\n    DEST=/dev/null\nfi\n\nif $* 2>&1 | tee \"$OUTFILE\" > $DEST\nthen\n    if diff <(cat \"$EXPFILE\" 2> /dev/null || true) \"$OUTFILE\" > \"$DIFFFILE\"\n    then\n        echo \"[+] $TESTNAME succeeded\"\n        rm \"$DIFFFILE\"\n        exit 0\n    else\n        echo \"[-] $TESTNAME failed (unexpected output)\"\n        printf '\\033[1;31m\\n'\n        if [[ $LIMIT > 0 ]]\n        then\n            tail -n $LIMIT \"$DIFFFILE\"\n        else\n            cat \"$DIFFFILE\"\n        fi\n        printf '\\033[0m\\n'\n        rm \"$DIFFFILE\"\n        exit 1\n    fi\nelse\n    echo \"[-] $TESTNAME failed (error $?)\"\n    exit 2\nfi\n", "num_lines": 47}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -o pipefail\nset -u\n\nbasedir=$(dirname \"${BASH_SOURCE[0]}\")\nout=$(\"${basedir}\"/erlang.escript \"$@\")\nexit_code=$?\necho \"$out\"\nif [ $exit_code = 0 ]; then\n    sh -c \"$out\"\n    exit $?\nfi\nexit $exit_code\n", "num_lines": 19}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nmkdir -p jar\n\nwhile read -r file ; do\n    name=${file%.*}\n    javac \"$name.java\"\n    jar cvfe \"$name.jar\" \"$name\" *.class\n    rm *.class\n    mv \"$name.jar\" jar\ndone < <(ls | grep .java)\n", "num_lines": 17}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# create a release of the Infer Java annotations to send to oss.sonatype.org\n\nset -x\nset -e\n\n# This fixes 'gpg: signing failed: Inappropriate ioctl for device' error\n# during signing\nexport GPG_TTY=$(tty)\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nROOTDIR=\"$( cd $DIR/.. && pwd)\"\n\n# check if we're in the open-source repo\nif ! git remote get-url origin | grep -q \"\\bgithub\\.com\\b\"; then\n    echo \"Please run this script from the Git repo for open-source Infer!\"\n    exit 1\nfi\n\necho \"Starting release...\"\n\n( cd \"$ROOTDIR/infer/annotations\" && \\\n      mvn -e release:clean release:prepare && \\\n      mvn -e release:perform -DpushChanges=false )\n", "num_lines": 31}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nset -o pipefail\nset -u\nset -x\n\nif [ \"$#\" != \"1\" ]; then\n  set +x\n  echo \"Usage: $0 version_tag\" 1>&2\n  echo 1>&2\n  echo \"Example: $0 v0.11.0\" 1>&2\n  exit 1\nfi\n\nVERSION=$1\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nROOT_DIR=\"$SCRIPT_DIR\"/..\nNCPUS=\"$(getconf _NPROCESSORS_ONLN 2>/dev/null || echo 2)\"\nPLATFORM=$(uname)\nif [ \"$PLATFORM\" == 'Darwin' ]; then\n    RELEASE_NAME=infer-osx-\"$VERSION\"\nelse\n    RELEASE_NAME=infer-linux64-\"$VERSION\"\nfi\nRELEASE_TARBALL=\"$RELEASE_NAME\".tar.xz\n\n# configurable stuff\nDRYRUN=${DRYRUN:-no}\nJOBS=${JOBS:-$NCPUS}\n\npushd \"$ROOT_DIR\"\nrm -fr \"$RELEASE_NAME\"\n\n./build-infer.sh --only-setup-opam\neval $(opam env)\ntouch .release\n./autogen.sh\n./configure \\\n    --prefix=\"/$RELEASE_NAME\"\n\nmake -j \"$JOBS\" \\\n    install-with-libs \\\n    BUILD_MODE=opt \\\n    DESTDIR=\"$ROOT_DIR\" \\\n    libdir_relative_to_bindir=../lib\npopd\n\nif [ \"$DRYRUN\" = \"no\" ]; then\n    installed_version=\"$(./\"$RELEASE_NAME\"/bin/infer --version | head -1 | cut -d ' ' -f 3)\"\n    if [ \"$installed_version\" != \"$VERSION\" ]; then\n        set +x\n        printf \"Infer reports the wrong version number: got '%s' but expected '%s'\\n\" \\\n               \"$installed_version\" \"$VERSION\" 1>&2\n        exit 1\n    fi\n\n    # trick so that the String-Who-Must-Not-Be-Named doesn't appear verbatim in the script\n    FBDASHONLY=$(printf \"%s%s\" 'FB-O' 'NLY')\n    if grep -Ir \"$FBDASHONLY\" \"$RELEASE_NAME\"; then\n        set +x\n        echo \"Found files marked $FBDASHONLY\" 1>&2\n        exit 1\n    fi\nfi\n\ntar cJf \"$RELEASE_TARBALL\" \"$RELEASE_NAME\"\nrm -fr \"$RELEASE_NAME\"\n\n# special GitHub sauce for later steps to find the tarball\necho\necho \"::set-output name=tarball-path::$RELEASE_TARBALL\"\n", "num_lines": 79}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# USAGE\n#\n# 1. Follow instructions in https://source.android.com/setup/build/downloading to download\n#    the AOSP source and in https://source.android.com/setup/build/building to get proprietary\n#    binaries.  You will need lots of space (at least 100Gb).  Let <android-root> be its root as\n#    an *absolute path*.\n#\n# 2. Replace <android-root>/prebuilts/jdk/jdk9/<your OS>/bin/javac with the following script.\n#\n#    #!/bin/bash\n#    infer -q --capture --continue --starvation-only --no-starvation \\\n#      --project-root <android-root> --results-dir <android-root>/infer-out -- \\\n#      /usr/local/bin/javac \"$@\"\n#\n#    Here, my local installation of java is in /usr/local/, change accordingly.  I used a\n#    Java *8* installation without problems, YMMV.\n#\n# 3. From <android-root> do\n#\n#    $ . build/envsetup.sh\n#    $ export TEMPORARY_DISABLE_PATH_RESTRICTIONS=true\n#    $ cd libcore/ojluni\n#    $ mm -j1 javac-check\n#\n#    ... and wait.  It took me ~22h.\n#\n# 4. From <android-root> run\n#\n#    $ infer analyze --starvation-only --dev-android-strict-mode\n#\n# 5. From <android-root> run this script, capturing stdout.\n#\n#    $ <infer-root>/scripts/make-strict-mode.sh > \\\n#        <infer-root>/infer/src/concurrency/StrictModeModels.ml\n#\n# 6. You may need to adapt the optional ~actuals_pred argument for methods in the above ML file.\n#    The aim is to avoid false positives when there is an overloaded method with different\n#    signatures and it so happens that one of the versions makes a violation when another does not.\n#    Recompile Infer.\n\n\nSOURCE_FILES=$(grep \"error:\" infer-out/report.txt | cut -f1 -d: | sort -u | grep -v test )\nMATCHERS=\"\"\n\ncat <<EOF\n(*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *)\n\nopen! IStd\nopen ConcurrencyModels\n\nEOF\n\nfor SOURCE_FILE in $SOURCE_FILES ; do\n  PACKAGE=$(grep -E \"^package \" $SOURCE_FILE | cut -f2 -d' ' | cut -f1 -d\\;)\n\n  if [[ $PACKAGE != android.* ]] && [[ $PACKAGE != androidx.* ]] && [[ $PACKAGE != java.* ]] ; then\n    continue\n  fi\n\n  BASENAME=$(basename $SOURCE_FILE )\n  CLASS=${BASENAME%.*}\n\n  if ! grep -q -E \"public.*class.* ${CLASS}\" $SOURCE_FILE ; then\n    continue\n  fi\n\n  HIDE=$(grep -B 2 -E \"public.*class.* ${CLASS}\" $SOURCE_FILE | grep '@hide')\n  if [ ! -z \"$HIDE\" ] ; then\n    continue\n  fi\n\n  FULLCLASSNAME=\"${PACKAGE}.${CLASS}\"\n  METHOD_REXP=\"^  Method \\`.* $CLASS\\.\"\n  METHODS=$(grep -E \"$METHOD_REXP\" infer-out/report.txt | cut -f2 -d. | cut -f1 -d\\` | sort -u)\n\n  if [ -z \"$METHODS\" ] ; then\n    continue\n  fi\n\n  HEADER=\"\"\n  MATCHER=\"is_${CLASS}_method\"\n\n  for METHOD in $METHODS; do\n    METHODNAME=$(echo $METHOD | cut -f1 -d\\( )\n\n    if ! grep -q -E \"public.*${METHODNAME}\" $SOURCE_FILE ; then\n      continue\n    fi\n\n    if [ -z \"$HEADER\" ] ; then\n      echo \"(* $SOURCE_FILE *)\"\n      echo \"let ${MATCHER} =\"\n      echo \"  is_call_of_class \\\"${FULLCLASSNAME}\\\"\"\n      echo \"    [\"\n      HEADER=true\n    fi\n\n    echo \"      \\\"${METHODNAME}\\\"; (* $METHOD *)\"\n  done\n\n  if [ ! -z \"$HEADER\" ] ; then\n    echo \"    ]\"\n    echo '  |> Staged.unstage'\n    echo\n    MATCHERS=\"$MATCHERS $MATCHER\"\n  fi\ndone\n\necho\necho \"let is_strict_mode_violation =\"\necho \"  let matchers = [\"\nfor M in $MATCHERS ; do\n  echo \"    $M ;\"\ndone\necho \"    ]\"\necho \"  in\"\necho \"  fun tenv pn actuals -> List.exists matchers ~f:(fun m -> m tenv pn actuals)\"\n", "num_lines": 130}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# source this script to import its utility functions\n\nopam_retry () {\n  \"$@\" || {\n    echo >&2;\n    printf '*** `%s` failed\\n' \"$*\" >&2;\n    echo '*** Updating opam then retrying' >&2;\n    opam update &&\n    \"$@\" || {\n      echo >&2;\n      printf '*** ERROR: `%s` failed\\n' \"$*\" >&2;\n      exit 1\n    }\n  }\n}\n\nopam_failed () {\n    local command=$1\n    echo\n    printf '*** ERROR: %s failed\\n' \"$command\" >&2\n    printf \"*** ERROR: Try running \\$(opam update) then running this script again\\n\" >&2\n    exit 1\n}\n\nopam_require_version_2 () {\n    local status=0\n    local version=0\n    { version=$(opam --version 2>/dev/null); status=$?; }\n    if [ \"$status\" != 0 ]; then\n        printf '*** ERROR: `opam --version` failed, please install opam version 2\\n' >&2\n        env >&2\n        exit 1\n    fi\n    case $version in\n        2*) ;;\n        *)\n            printf '*** ERROR: opam version \"%s\" is not supported, please install opam version 2\\n' \"$version\" >&2\n            printf '*** NOTE: opam is \"%s\"\\n' \"$(which opam)\" >&2\n            env >&2\n            exit 1\n    esac\n}\n\n# assumes opam is available and initialized\nopam_switch_create_if_needed () {\n    local switch=$1\n    local options=$2\n    local switch_exists=no\n    printf \"looking if switch %s exists in this list:\\n\" \"$switch\";\n    opam switch list --short\n    for installed_switch in $(opam switch list --short); do\n        if [ \"$installed_switch\" == \"$switch\" ]; then\n            switch_exists=yes\n            break\n        fi\n    done\n    printf \"verdict: %s\\n\" $switch_exists;\n    if [ \"$switch_exists\" = \"no\" ]; then\n        if [ -e \"$(opam var root)/$switch\" ] ; then\n            rm -rf \"$(opam var root)/$switch\" || true\n        fi\n        opam switch create \"$switch\" $options\n    fi\n}\n\nopam_require_version_2\n\n# removes packages that cannot be found by ocamlfind\nopam_remove_broken_package () {\n    local pkg=\"$1\"\n    if ! ocamlfind query \"${pkg}\"; then\n        echo \"ocamlfind cannot find ${pkg} package. Removing the package...\"\n        opam remove \"${pkg}\" || true\n    fi\n}\n", "num_lines": 82}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Usage: set_libso_path.sh [LIBSO_DIR] [TARGET]\n#\n# This changes MacOSX's executable [TARGET] to use shared libraries in\n# [LIBSO_DIR] when rpath has been set to [LIBSO_DIR].\n\nset -e\nset -o pipefail\nset -u\n\nLIBSO_DIR=$1\nTARGET=$2\n\nTMP=$( mktemp )\ntrap \"rm $TMP\" EXIT\n\notool -L \"$TARGET\" | tail -n +2 > \"$TMP\"\nwhile IFS='' read -r line || [[ -n \"$line\" ]]; do\n  LIB_PATH=$( echo $line | awk '{print $1}' )\n  LIB_FILE=$( basename \"${LIB_PATH}\" )\n  if [ -f \"${LIBSO_DIR}/${LIB_FILE}\" ]; then\n    install_name_tool -change \"${LIB_PATH}\" \"@rpath/${LIB_FILE}\" \"$TARGET\"\n  fi\ndone < \"$TMP\"\n", "num_lines": 31}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# wrap execution of sledge with time and memory limits\n# and add status entries to report in case of an unexpected exit\n\n# usage: wrap.sh <timeout(sec)> <memout(GB)> <command> <testdir/testname>\n\nset -u\n\ntimeout=$1\nmemout=$(( $2*1024*1024 ))\ncommand=${@: 3: $#-3}\ntest=${@: -1}\n\nunknown_error () {\n  echo \"((name $test)(entry(Status(UnknownError \\\"$1\\\"))))\" >> $test.sexp\n}\n\nassert () {\n  echo \"((name $test)(entry(Status(Assert \\\"$1\\\"))))\" >> $test.sexp\n}\n\nabort () {\n  if grep -q \"Assertion failed\" $test.err;\n  then\n    assert \"$(\\\n      grep \"Assertion failed\" $test.err \\\n      | sed 's/</\\</g;s/>/\\>/g;s/Assertion failed: (\\(.*\\)), function.*/\\1/' \\\n      | sed 's/\"/\\\\\\\"/g' )\"\n  else\n    echo \"((name $test)(entry(Status Abort)))\" >> $test.sexp\n  fi\n}\n\ntimeout () {\n  echo \"((name $test)(entry(Status Timeout)))\" >> $test.sexp\n}\n\nmemout () {\n  echo \"((name $test)(entry(Status Memout)))\" >> $test.sexp\n}\n\n(\n  ulimit -t $timeout -v $memout\n  $command -report $test.sexp $test 1> $test.out 2> $test.err\n) &> /dev/null\nstatus=$?\n\ncase $status in\n  ( 0 | 1 ) ;;\n  ( 132 ) unknown_error \"illegal instruction\" ;;\n  ( 136 ) unknown_error \"floating-point exception\" ;;\n  ( 139 ) unknown_error \"segmentation violation\" ;;\n  ( 127 ) memout ;;\n  ( 134 ) abort ;;\n  ( 137 | 152 ) timeout ;;\n  ( * ) unknown_error \"exit $status\" ;;\nesac\n\n(test -f $test.sexp && grep -q \"Status\" $test.sexp) \\\n|| unknown_error \"exit $status\"\n\nexit $status\n", "num_lines": 69}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsledge=$PWD/cli/sledge_cli.exe\n\nexport SLEDGE_CONFIG=$PWD/../../test/config\n\nline=$(\\\n  $sledge help -recursive -expand \\\n    | grep -n \"== subcommands ===\" \\\n    | cut -d : -f1,1)\n\nline=$(($line+1))\n\n$sledge help -recursive | sed -e \"s/sledge_cli.exe/sledge/g\"\n\n$sledge h -r -e \\\n  | tail -n +$line \\\n  | sed -e \"s/  \\(.*\\)  .*/\\1/g;/^ *$/d\" \\\n  | while read cmd; do \\\n      printf \"\\n====== sledge $cmd ======\\n\\n\"; \\\n      $sledge $cmd -help | sed -e \"s/sledge_cli.exe/sledge/g\"; \\\n    done\n", "num_lines": 28}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -ex\n\nif test \"$#\" != 1; then\n    echo \"Usage: $0 <prefix>\"\n    exit 1\nfi\n\nPREFIX=$1\n\ndune install \"--prefix=$PREFIX\" --release\n\nfor pkg in $(basename -s .opam *.opam); do \n    case \"$pkg\" in\n    llvm)\n        cp META.llvm.in \"$PREFIX/lib/llvm/META\";;\n    llvm_*)\n        target=$(echo \"$pkg\" | cut -d_ -f2-)\n        sed \"s/@TARGET@/$target/g\" META.llvm_TARGET.in > \"$PREFIX/lib/llvm_$target/META\";;\n    *)\n        echo \"Something went wrong while processing $pkg. Please report.\"\n        exit 1;;\n    esac\ndone\n", "num_lines": 24}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -e\n\nif test \"$(dirname $0)\" != '.'; then\n    echo \"The script must be executed from its current directory.\"\n    exit 1\nfi\n\nif test \"$#\" -ne 1; then\n    echo \"Usage: $0 <llvm-config>\"\n    exit 1\nfi\n\nllvm_config=$1\ndefault_mode=\nsupport_static_mode=false\nsupport_shared_mode=false\n\nllvm_config() {\n    \"$llvm_config\" $@\n}\n\nif llvm_config --link-static; then\n    default_mode=static\n    support_static_mode=true\nfi\n\nif llvm_config --link-shared; then\n    default_mode=shared\n    support_shared_mode=true\nfi\n\nif test -z \"$default_mode\"; then\n    echo \"Something is wrong with the llvm-config command provided.\"\n    exit 1\nfi\n\nbase_cflags=$(llvm_config --cflags)\nldflags=\"$(llvm_config --ldflags) -lstdc++\"\nllvm_targets=$(llvm_config --targets-built)\n\nrm -rf src\ncp -r llvm-project/llvm/bindings/ocaml src\n\ncreate_dune_file() {\n    findlibname=$1\n    dirname=$2\n    modname=$3\n    cfile=$4\n    depends=$5\n    components=$6\n    extra_deps=$7\n\n    if test \"$dirname\" = \"backends\"; then\n        basedir=src/$dirname/$components\n        test ! -d \"$basedir\" && mkdir \"$basedir\"\n        sed \"s/@TARGET@/$components/g\" \"src/$dirname/llvm_backend.ml.in\" > \"$basedir/$modname.ml\"\n        sed \"s/@TARGET@/$components/g\" \"src/$dirname/llvm_backend.mli.in\" > \"$basedir/$modname.mli\"\n        sed \"s/@TARGET@/$components/g\" \"src/$dirname/backend_ocaml.c\" > \"$basedir/$cfile.c\"\n        cflags=\"$base_cflags \\\"-DTARGET=$components\\\"\"\n    else\n        basedir=src/$dirname\n        cflags=$base_cflags\n    fi\n\n    test ! -d \"$basedir/common\" && mkdir \"$basedir/common\"\n    cp \"$basedir/$modname.mli\" \"$basedir/common\"\n\n    echo \"\n(library\n (name $modname)\n (public_name $findlibname)\n (wrapped false)\n (virtual_modules $modname)\n (libraries $depends)\n (default_implementation $findlibname.$default_mode))\n\" > \"$basedir/common/dune\"\n\n    if $support_shared_mode; then\n        test ! -d \"$basedir/shared\" && mkdir \"$basedir/shared\"\n        cp \"$basedir/$modname.ml\" \"$basedir/shared\"\n        cp \"$basedir/$cfile.c\" \"$basedir/shared\"\n\n        echo \"\n(library\n (name ${modname}_shared)\n (public_name $findlibname.shared)\n (implements $findlibname)\n (foreign_stubs\n  (language c)\n  (names ${cfile})\n  (extra_deps ${extra_deps})\n  (flags ($cflags -I../../llvm)))\n (c_library_flags ($ldflags $(llvm_config --system-libs --link-shared --libs $components))))\n\" >> \"$basedir/shared/dune\"\n    fi\n\n    if $support_static_mode; then\n        test ! -d \"$basedir/static\" && mkdir \"$basedir/static\"\n        cp \"$basedir/$modname.ml\" \"$basedir/static\"\n        cp \"$basedir/$cfile.c\" \"$basedir/static\"\n\n        echo \"\n(library\n (name ${modname}_static)\n (public_name $findlibname.static)\n (implements $findlibname)\n (foreign_stubs\n  (language c)\n  (names ${cfile})\n  (extra_deps ${extra_deps})\n  (flags ($cflags -I../../llvm)))\n (c_library_flags ($ldflags $(llvm_config --system-libs --link-static --libs $components))))\n\" >> \"$basedir/static/dune\"\n    fi\n\n    rm \"$basedir/$modname.ml\"\n    rm \"$basedir/$cfile.c\"\n}\n\n# ------------------ public name -------- directory ---------------- module name -------- C file name --------- OCaml dependencies -------------- LLVM components (for the linker) - extra-deps\ncreate_dune_file     llvm                 llvm                       llvm                 llvm_ocaml            \"\"                                \"core support\"                     ../llvm_ocaml.h\ncreate_dune_file     llvm.analysis        analysis                   llvm_analysis        analysis_ocaml        \"llvm\"                            \"analysis\"\ncreate_dune_file     llvm.bitreader       bitreader                  llvm_bitreader       bitreader_ocaml       \"llvm\"                            \"bitreader\"\ncreate_dune_file     llvm.bitwriter       bitwriter                  llvm_bitwriter       bitwriter_ocaml       \"llvm unix\"                       \"bitwriter\"\ncreate_dune_file     llvm.executionengine executionengine            llvm_executionengine executionengine_ocaml \"llvm llvm.target ctypes.foreign\" \"executionengine mcjit native\"\ncreate_dune_file     llvm.ipo             transforms/ipo             llvm_ipo             ipo_ocaml             \"llvm\"                            \"ipo\"\ncreate_dune_file     llvm.irreader        irreader                   llvm_irreader        irreader_ocaml        \"llvm\"                            \"irreader\"\ncreate_dune_file     llvm.scalar_opts     transforms/scalar_opts     llvm_scalar_opts     scalar_opts_ocaml     \"llvm\"                            \"scalaropts\"\ncreate_dune_file     llvm.transform_utils transforms/utils           llvm_transform_utils transform_utils_ocaml \"llvm\"                            \"transformutils\"\ncreate_dune_file     llvm.vectorize       transforms/vectorize       llvm_vectorize       vectorize_ocaml       \"llvm\"                            \"vectorize\"\ncreate_dune_file     llvm.passmgr_builder transforms/passmgr_builder llvm_passmgr_builder passmgr_builder_ocaml \"llvm\"                            \"ipo\"\ncreate_dune_file     llvm.target          target                     llvm_target          target_ocaml          \"llvm\"                            \"target\"                           ../../llvm/llvm_ocaml.h\ncreate_dune_file     llvm.linker          linker                     llvm_linker          linker_ocaml          \"llvm\"                            \"linker\"\ncreate_dune_file     llvm.all_backends    all_backends               llvm_all_backends    all_backends_ocaml    \"llvm\"                            \"$llvm_targets\"\n\nfor target in $llvm_targets; do\n    touch \"llvm_${target}.opam\"\n    create_dune_file \"llvm_$target\"       backends                   \"llvm_$target\"       \"${target}_ocaml\"     \"llvm\"                            \"$target\"\ndone\n", "num_lines": 140}
{"repo_name": "infer", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copies the 'demangle' library, excluding 'DemangleConfig.h', to llvm. If no\n# llvm directory is specified, then assume a monorepo layout.\n\nset -e\n\nFILES=\"ItaniumDemangle.h StringView.h Utility.h README.txt\"\nLLVM_DEMANGLE_DIR=$1\n\nif [[ -z \"$LLVM_DEMANGLE_DIR\" ]]; then\n    LLVM_DEMANGLE_DIR=\"../../../llvm/include/llvm/Demangle\"\nfi\n\nif [[ ! -d \"$LLVM_DEMANGLE_DIR\" ]]; then\n    echo \"No such directory: $LLVM_DEMANGLE_DIR\" >&2\n    exit 1\nfi\n\nread -p \"This will overwrite the copies of $FILES in $LLVM_DEMANGLE_DIR; are you sure? [y/N]\" -n 1 -r ANSWER\necho\n\nif [[ $ANSWER =~ ^[Yy]$ ]]; then\n    for I in $FILES ; do\n        cp $I $LLVM_DEMANGLE_DIR/$I\n    done\nfi\n", "num_lines": 28}
{"repo_name": "jscodeshift", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env node\n\n/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n'use strict';\n\nrequire('./jscodeshift.js');\n", "num_lines": 13}
{"repo_name": "ktfmt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n./gradlew -q packageLibs\nmv build/distributions/lambda.zip build/lambda-lib.zip\n\n./gradlew build\n\nARTIFACT_BUCKET=ktfmt-online-formatter-lambda\nTEMPLATE=format.yaml\naws cloudformation package --template-file $TEMPLATE --s3-bucket $ARTIFACT_BUCKET --output-template-file out.yml\naws cloudformation deploy --template-file out.yml --stack-name ktfmt --capabilities CAPABILITY_NAMED_IAM --region=us-east-2\n", "num_lines": 26}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -xe\n\n# Author(s) - anirbanr-fb\n# Borrowed from\n# https://kudu.apache.org/docs/installation.html#build_from_source\n\n# We need to specify a specific version of Kerberos so we don't break certain\n# non-Kudu components that enforce a specific Kerberos version.\nKRB5_VERSION=1.18.2-12.el8.x86_64  # NOTE: only correct on CentOS 8!\n\n# INSTALL ALL DEPENDENCIES\nsudo dnf install -y autoconf automake cyrus-sasl-devel cyrus-sasl-gssapi \\\n  cyrus-sasl-plain flex gcc gcc-c++ gdb git java-1.8.0-openjdk \\\n  libtool make openssl-devel patch pkgconfig redhat-lsb-core rsync unzip \\\n  vim-common which cmake doxygen libcap-devel \\\n  krb5-server-${KRB5_VERSION} krb5-workstation-${KRB5_VERSION}\n\n# DOWNLOAD AND BUILD THE THIRD-PARTY libraries\n# IF THINGS BREAK IN MIDDLE\n# wipe out: you can use the big hammer!\n#  rm -f thirdparty/{src,installed,build}\n#  rerun\n./thirdparty/build-if-necessary.sh\n\nmkdir -p build/release\ncd build/release\ncmake -DCMAKE_BUILD_TYPE=release ../..\nmake -j20\n", "num_lines": 29}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Enables the Red Hat devtoolset on RHEL 6 based systems and executes the\n# arguments. On non-RHEL 6 systems, the arguments are executed without changes\n# to the environment.\n# USAGE: ./enable_devtoolset.sh <command> <args>...\n\nset -e\n\nif [[ \"$OSTYPE\" =~ ^linux ]] && \\\n   [[ \"$(lsb_release -irs)\" =~ (CentOS|RedHatEnterpriseServer)[[:space:]]+6\\.[[:digit:]]+ ]]; then\n  # Invoke the inner script, which may do some additional customization within\n  # the devtoolset.\n  ROOT=$(cd $(dirname \"$BASH_SOURCE\") ; pwd)\n  scl enable devtoolset-3 \"$ROOT/enable_devtoolset_inner.sh $*\"\nelse\n  $@\nfi\n", "num_lines": 36}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Executes the provided arguments within the context of a Red Hat devtoolset.\n#\n# This script should not be used directly; it is called by enable_devtoolset.sh.\n\nset -e\n\n# If ccache was on the PATH and CC/CXX have not already been set, set them to\n# devtoolset-3 specific ccache helper scripts (thus enabling ccache).\nif [ $(which ccache 2> /dev/null) -a ! \"$CC\" -a ! \"$CXX\" ]; then\n  ROOT=$(cd $(dirname \"$BASH_SOURCE\") ; pwd)\n  export CC=\"$ROOT/ccache-devtoolset-3/cc\"\n  export CXX=\"$ROOT/ccache-devtoolset-3/c++\"\nfi\n\n# Execute the arguments.\n$*\n", "num_lines": 36}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Script which embeds a piece of raw data into a C++ source file. Functionally\n# the same as xxd -i, but inserts custom namespace and variable names.\n\nIN_FILE=$1\nOUT_FILE=$2\n\necho \"// header generated by build-support/generate_precompiled_xxd.sh\" > $OUT_FILE\necho \"namespace kudu {\" >> $OUT_FILE\necho \"namespace codegen {\" >> $OUT_FILE\n\necho \"extern const char precompiled_ll_data[] = {\" >> $OUT_FILE\nxxd -i - < $IN_FILE >> $OUT_FILE\n# LLVM requires the binary to be null terminated.\necho \", 0x00\" >> $OUT_FILE\necho \"};\" >> $OUT_FILE\n\nLEN=$(wc -c $IN_FILE | awk '{print $1}')\necho \"extern const unsigned int precompiled_ll_len = ${LEN};\" >> $OUT_FILE\n\necho \"} // namespace codegen\" >> $OUT_FILE\necho \"} // namespace kudu\" >> $OUT_FILE\n", "num_lines": 41}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Script which tries to determine the most recent git hash in the current\n# branch which was checked in by gerrit. This commit hash is printed to\n# stdout.\n#\n# It does so by looking for the 'Reviewed-on' tag added by gerrit. This is\n# more foolproof than trying to guess at the \"origin/\" branch name, since the\n# developer might be working on some local topic branch.\nset -e\n\ngit log --grep='Reviewed-on: ' -n1 --pretty=format:%H\n", "num_lines": 30}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nROOT=$(cd $(dirname $BASH_SOURCE)/..; pwd)\n\nTMP=$(mktemp -t kudu-lint.XXXXXXXXX)\ntrap \"rm $TMP\" EXIT\n\nONLY_CHANGED=false\n\nfor flag in \"$@\" ; do\n  case $flag in\n    --changed-only | -c)\n      ONLY_CHANGED=true\n      ;;\n    *)\n      echo unknown flag: $flag\n      exit 1\n      ;;\n  esac\ndone\n\nif $ONLY_CHANGED; then\n  FILES=$(git diff --name-only $($ROOT/build-support/get-upstream-commit.sh)  \\\n    | egrep  '\\.(cc|h)$' | grep -v \"gutil\\|trace_event\\|x509_check_host\")\n  if [ -z \"$FILES\" ]; then\n    echo No source files changed\n    exit 0\n  fi\nelse\n  FILES=$(find $ROOT/src -name '*.cc' -or -name '*.h' | grep -v \"\\.pb\\.\\|\\.service\\.\\|\\.proxy\\.\\|\\.krpc\\.\\|gutil\\|trace_event\\|kudu_export\\.h\\|x509_check_host\")\nfi\n\ncd $ROOT\n\n$ROOT/thirdparty/installed/common/bin/cpplint.py \\\n  --verbose=4 \\\n  --filter=-whitespace/comments,-readability/todo,-readability/inheritance,-build/header_guard,-build/include_order,-legal/copyright,-build/c++11,-readability/nolint \\\n  $FILES 2>&1 | grep -v 'Done processing' | tee $TMP\n\nNUM_ERRORS=$(grep \"Total errors found\" $TMP | awk '{print $4}')\n\nif [[ \"$NUM_ERRORS\" -ne 0 ]]; then\n  exit 1\nfi\n", "num_lines": 62}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Reports a test run to the central test server, which records\n# the results in a database. This is what drives our \"flaky test dashboard\".\n# This script does blocking network IO, so if you are running it from the\n# context of a build, you may want to run it in the background.\n#\n# Note that this may exit with a non-zero code if the network is flaky or the\n# test result server is down.\n\nset -e\n\nROOT=$(dirname $BASH_SOURCE)/..\n\n# Verify and parse command line and options\nif [ $# -ne 3 ]; then\n  echo \"usage: $0 <path/to/test> <path/to/log> <exit-code>\"\n  echo\n  echo The \\$TEST_RESULT_SERVER environment variable may be used\n  echo to specify where to report the tests.\n  exit 1\nfi\nTEST_EXECUTABLE=$1\nLOGFILE=$2\nSTATUS=$3\nTEST_RESULT_SERVER=${TEST_RESULT_SERVER:-localhost:8080}\nREPORT_TIMEOUT=${REPORT_TIMEOUT:-10}\n\n# On Jenkins, we'll have this variable set. Otherwise,\n# report the build ID as non-jenkins.\nBUILD_ID=${BUILD_TAG:-non-jenkins}\n\n# Figure out the current git revision, and append a \"-dirty\" tag if it's\n# not a pristine checkout\nREVISION=$(cd $ROOT && git rev-parse HEAD)\nif ! ( cd $ROOT && git diff --quiet .  && git diff --cached --quiet . ) ; then\n  REVISION=\"${REVISION}-dirty\"\nfi\n\nBUILD_ROOT=$(dirname $TEST_EXECUTABLE)/..\n\n# Parse out our \"build config\" - a space-separated list of tags\n# which include the cmake build type as well as the list of configured\n# sanitizers\n\nCMAKECACHE=$BUILD_ROOT/CMakeCache.txt\nBUILD_CONFIG=$(grep '^CMAKE_BUILD_TYPE:' $CMAKECACHE | cut -f 2 -d=)\nif grep -q \"KUDU_USE_ASAN:UNINITIALIZED=1\" $CMAKECACHE ; then\n  BUILD_CONFIG=\"$BUILD_CONFIG asan\"\nfi\nif grep -q \"KUDU_USE_TSAN:UNINITIALIZED=1\" $CMAKECACHE ; then\n  BUILD_CONFIG=\"$BUILD_CONFIG tsan\"\nfi\nif grep -q \"KUDU_USE_UBSAN:UNINITIALIZED=1\" $CMAKECACHE ; then\n  BUILD_CONFIG=\"$BUILD_CONFIG ubsan\"\nfi\n\n# We sometimes have flaky infrastructure where NTP is broken. In that case\n# do not report it as a failed test.\nif zgrep -q 'Clock considered unsynchronized' $LOGFILE ; then\n  echo Not reporting test that failed due to NTP issues.\n  exit 1\nfi\n\n# Only upload a log if the test failed.\n# This saves some space on S3, network bandwidth, etc, and we don't\n# have a lot of use for the logs of successful tests anyway.\nif [ \"$STATUS\" -ne 0 ]; then\n  LOG_PARAM=\"-F log=@$LOGFILE\"\nelse\n  LOG_PARAM=\"\"\nfi\n\ncurl -s \\\n    --max-time $REPORT_TIMEOUT \\\n    $LOG_PARAM \\\n    -F \"build_id=$BUILD_ID\" \\\n    -F \"hostname=$(hostname)\" \\\n    -F \"test_name=$(basename $TEST_EXECUTABLE)\" \\\n    -F \"status=$STATUS\" \\\n    -F \"revision=$REVISION\" \\\n    -F \"build_config=$BUILD_CONFIG\" \\\n    http://$TEST_RESULT_SERVER/add_result\n", "num_lines": 101}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Script which wraps running a test and redirects its output to a\n# test log directory.\n#\n# If KUDU_COMPRESS_TEST_OUTPUT is non-empty, then the logs will be\n# gzip-compressed while they are written.\n#\n# If KUDU_FLAKY_TEST_ATTEMPTS is set, and either the test being run matches one\n# of the lines in the file KUDU_FLAKY_TEST_LIST or KUDU_RETRY_ALL_FAILED_TESTS\n# is non-zero, then the test will be retried on failure up to the specified\n# number of times. This can be used in the gerrit workflow to prevent annoying\n# false -1s caused by tests that are known to be flaky in master.\n#\n# If KUDU_REPORT_TEST_RESULTS is non-zero, then tests are reported to the\n# central test server.\n#\n# If KUDU_MEASURE_TEST_CPU_CONSUMPTION is non-zero, then tests will be wrapped\n# in a 'perf stat' command which measures the CPU consumption on a periodic\n# basis, writing the output into '<test>.<shard>.perf.txt' logs in the test log\n# directory. This is handy in order to determine an appropriate value for the\n# 'PROCESSORS' property passed to 'ADD_KUDU_TEST' in CMakeLists.txt.\n\n# Path to the test executable or script to be run.\n# May be relative or absolute.\nTEST_PATH=$1\n\n# Absolute path to the root source directory. This script is expected to live within it.\nSOURCE_ROOT=$(cd $(dirname \"$BASH_SOURCE\")/.. ; pwd)\n\n# Absolute path to the root build directory. The test path is expected to be within it.\nBUILD_ROOT=$(cd $(dirname \"$TEST_PATH\")/.. ; pwd)\n\nTEST_LOGDIR=$BUILD_ROOT/test-logs\nmkdir -p $TEST_LOGDIR\n\nTEST_DEBUGDIR=$BUILD_ROOT/test-debug\nmkdir -p $TEST_DEBUGDIR\n\nTEST_DIRNAME=$(cd $(dirname $TEST_PATH); pwd)\nTEST_FILENAME=$(basename $TEST_PATH)\nABS_TEST_PATH=$TEST_DIRNAME/$TEST_FILENAME\nshift\n# Remove path and extension (if any).\n\n# The \"short\" test name doesn't include the shard number.\nSHORT_TEST_NAME=$(echo $TEST_FILENAME | perl -pe 's/\\..+?$//')\n\n# The full test name does include the shard number if the test is sharded.\nif [ ${GTEST_TOTAL_SHARDS:-0} -gt 1 ]; then\n  TEST_NAME=${SHORT_TEST_NAME}.${GTEST_SHARD_INDEX:?}\nelse\n  TEST_NAME=${SHORT_TEST_NAME}\nfi\n\n# Determine whether the user has chosen to retry all failed tests, or whether\n# the test is a known flaky by comparing against the user-specified list.\nTEST_EXECUTION_ATTEMPTS=1\nif [ -n \"$KUDU_RETRY_ALL_FAILED_TESTS\" ]; then\n  echo \"Will retry all failed tests\"\n  TEST_IS_RETRYABLE=1\nelif [ -n \"$KUDU_FLAKY_TEST_LIST\" ]; then\n  if [ -f \"$KUDU_FLAKY_TEST_LIST\" ] && grep -q --count --line-regexp \"$SHORT_TEST_NAME\" \"$KUDU_FLAKY_TEST_LIST\"; then\n    TEST_IS_RETRYABLE=1\n  else\n    echo \"Flaky test list file $KUDU_FLAKY_TEST_LIST missing\"\n  fi\nfi\n\nif [ -n \"$TEST_IS_RETRYABLE\" ]; then\n  TEST_EXECUTION_ATTEMPTS=${KUDU_FLAKY_TEST_ATTEMPTS:-1}\n  echo $TEST_NAME is a retryable test. Will attempt running it\n  echo up to $TEST_EXECUTION_ATTEMPTS times.\nfi\n\n\n# We run each test in its own subdir to avoid core file related races.\nTEST_WORKDIR=$BUILD_ROOT/test-work/$TEST_NAME\nmkdir -p $TEST_WORKDIR\npushd $TEST_WORKDIR >/dev/null || exit 1\nrm -f *\n\nset -o pipefail\n\nLOGFILE=$TEST_LOGDIR/$TEST_NAME.txt\nXMLFILE=$TEST_LOGDIR/$TEST_NAME.xml\nexport GTEST_OUTPUT=\"xml:$XMLFILE\" # Enable JUnit-compatible XML output.\n\n# Remove both the compressed and uncompressed output, so the developer\n# doesn't accidentally get confused and read output from a prior test\n# run.\nrm -f $LOGFILE $LOGFILE.gz\n\nif [ -n \"$KUDU_COMPRESS_TEST_OUTPUT\" ] && [ \"$KUDU_COMPRESS_TEST_OUTPUT\" -ne 0 ] ; then\n  pipe_cmd=gzip\n  LOGFILE=${LOGFILE}.gz\nelse\n  pipe_cmd=cat\nfi\n\n# Set a 15-minute timeout for tests run via 'make test'.\n# This keeps our jenkins builds from hanging in the case that there's\n# a deadlock or anything.\n#\n# NOTE: this should be kept in sync with the default value of ARG_TIMEOUT\n# in the definition of ADD_KUDU_TEST in the top-level CMakeLists.txt.\nKUDU_TEST_TIMEOUT=${KUDU_TEST_TIMEOUT:-900}\n\n# Allow for collecting core dumps.\nKUDU_TEST_ULIMIT_CORE=${KUDU_TEST_ULIMIT_CORE:-0}\nulimit -c $KUDU_TEST_ULIMIT_CORE\n\n# Run the actual test.\nfor ATTEMPT_NUMBER in $(seq 1 $TEST_EXECUTION_ATTEMPTS) ; do\n  if [ $ATTEMPT_NUMBER -lt $TEST_EXECUTION_ATTEMPTS ]; then\n    # If the test fails, the test output may or may not be left behind,\n    # depending on whether the test cleaned up or exited immediately. Either\n    # way we need to clean it up. We do this by comparing the data directory\n    # contents before and after the test runs, and deleting anything new.\n    #\n    # The comm program requires that its two inputs be sorted.\n    TEST_TMPDIR_BEFORE=$(find $TEST_TMPDIR -maxdepth 1 -type d | sort)\n  fi\n\n  # gtest won't overwrite old junit test files, resulting in a build failure\n  # even when retries are successful.\n  rm -f $XMLFILE\n\n  if [[ $OSTYPE =~ ^darwin ]]; then\n    #\n    # For builds on MacOS X 10.11, neither (g)addr2line nor atos translates\n    # address into line number.  The atos utility is able to do that only\n    # if load address (-l <addr>) or reference to currently running process\n    # (-p <pid>) is given.  This is so even for binaries linked with\n    # PIE disabled.\n    #\n    addr2line_filter=cat\n  else\n    addr2line_filter=\"$SOURCE_ROOT/build-support/stacktrace_addr2line.pl $ABS_TEST_PATH\"\n  fi\n  echo \"Running $TEST_NAME, redirecting output into $LOGFILE\" \\\n       \"(attempt ${ATTEMPT_NUMBER}/$TEST_EXECUTION_ATTEMPTS)\"\n  test_command=$ABS_TEST_PATH\n  if [ -n \"$KUDU_MEASURE_TEST_CPU_CONSUMPTION\" ] && [ \"$KUDU_MEASURE_TEST_CPU_CONSUMPTION\" -ne 0 ] ; then\n    perf_file=$TEST_LOGDIR/$TEST_NAME.perf.txt\n    echo \"Will wrap test in perf-stat, output to ${perf_file}...\"\n    test_command=\"perf stat -I1000 -e task-clock -o $perf_file $test_command\"\n  fi\n  $test_command \"$@\" --test_timeout_after $KUDU_TEST_TIMEOUT 2>&1 \\\n    | $addr2line_filter \\\n    | $pipe_cmd > $LOGFILE\n  STATUS=$?\n\n  # An empty gzipped file is corrupt because even a logically empty gzipped file\n  # should contain at least the gzip header. If we detect this, treat the test\n  # log output as a plain text file.\n  if [[ -f $LOGFILE && ! -s $LOGFILE && $LOGFILE =~ .gz$ ]]; then\n    RENAMED_LOGFILE=${LOGFILE%%.gz}\n    mv $LOGFILE $RENAMED_LOGFILE\n    LOGFILE=$RENAMED_LOGFILE\n  fi\n\n  # TSAN doesn't always exit with a non-zero exit code due to a bug:\n  # mutex errors don't get reported through the normal error reporting infrastructure.\n  # So we make sure to detect this and exit 1.\n  #\n  # Additionally, certain types of failures won't show up in the standard JUnit\n  # XML output from gtest. We assume that gtest knows better than us and our\n  # regexes in most cases, but for certain errors we delete the resulting xml\n  # file and let our own post-processing step regenerate it.\n  export GREP=$(which egrep)\n  if zgrep --silent \"ThreadSanitizer|Leak check.*detected leaks\" $LOGFILE ; then\n    echo ThreadSanitizer or leak check failures in $LOGFILE\n    STATUS=1\n    rm -f $XMLFILE\n  fi\n\n  if [ $ATTEMPT_NUMBER -lt $TEST_EXECUTION_ATTEMPTS ]; then\n    # Now delete any new test output.\n    TEST_TMPDIR_AFTER=$(find $TEST_TMPDIR -maxdepth 1 -type d | sort)\n    DIFF=$(comm -13 <(echo \"$TEST_TMPDIR_BEFORE\") \\\n                    <(echo \"$TEST_TMPDIR_AFTER\"))\n    for DIR in $DIFF; do\n      # Multiple tests may be running concurrently. To avoid deleting the\n      # wrong directories, constrain to only directories beginning with the\n      # test name.\n      #\n      # This may delete old test directories belonging to this test, but\n      # that's not typically a concern when rerunning flaky tests.\n      if [[ $DIR =~ ^$TEST_TMPDIR/$TEST_NAME ]]; then\n        echo Deleting leftover flaky test directory \"$DIR\"\n        rm -Rf \"$DIR\"\n      fi\n    done\n  fi\n\n  if [ -n \"$KUDU_REPORT_TEST_RESULTS\" ] && [ \"$KUDU_REPORT_TEST_RESULTS\" -ne 0 ]; then\n    echo Reporting results\n    $SOURCE_ROOT/build-support/report-test.sh \"$ABS_TEST_PATH\" \"$LOGFILE\" \"$STATUS\" &\n\n    # On success, we'll do \"best effort\" reporting, and disown the subprocess.\n    # On failure, we want to upload the failed test log. So, in that case,\n    # wait for the report-test.sh job to finish, lest we accidentally run\n    # a test retry and upload the wrong log.\n    if [ \"$STATUS\" -eq \"0\" ]; then\n      disown\n    else\n      wait\n    fi\n  fi\n\n  if [ \"$STATUS\" -eq \"0\" ]; then\n    break\n  elif [ \"$ATTEMPT_NUMBER\" -lt \"$TEST_EXECUTION_ATTEMPTS\" ]; then\n    echo Test failed attempt number $ATTEMPT_NUMBER\n    echo Will retry...\n  fi\ndone\n\n# If we have a LeakSanitizer report, and XML reporting is configured, add a new test\n# case result to the XML file for the leak report. Otherwise Jenkins won't show\n# us which tests had LSAN errors.\nif zgrep --silent \"ERROR: LeakSanitizer: detected memory leaks\" $LOGFILE ; then\n    echo Test had memory leaks. Editing XML\n    perl -p -i -e '\n    if (m#</testsuite>#) {\n      print \"<testcase name=\\\"LeakSanitizer\\\" status=\\\"run\\\" classname=\\\"LSAN\\\">\\n\";\n      print \"  <failure message=\\\"LeakSanitizer failed\\\" type=\\\"\\\">\\n\";\n      print \"    See txt log file for details\\n\";\n      print \"  </failure>\\n\";\n      print \"</testcase>\\n\";\n    }' $XMLFILE\nfi\n\n# Capture and compress core file and binary.\nCOREFILES=$(ls | grep ^core)\nif [ -n \"$COREFILES\" ]; then\n  echo Found core dump. Saving executable and core files.\n  gzip < $ABS_TEST_PATH > \"$TEST_DEBUGDIR/$TEST_NAME.gz\" || exit $?\n  for COREFILE in $COREFILES; do\n    gzip < $COREFILE > \"$TEST_DEBUGDIR/$TEST_NAME.$COREFILE.gz\" || exit $?\n  done\n  # Pull in any .so files as well.\n  for LIB in $(ldd $ABS_TEST_PATH | grep $BUILD_ROOT | awk '{print $3}'); do\n    LIB_NAME=$(basename $LIB)\n    gzip < $LIB > \"$TEST_DEBUGDIR/$LIB_NAME.gz\" || exit $?\n  done\nfi\n\npopd >/dev/null\nrm -Rf $TEST_WORKDIR\n\nexit $STATUS\n", "num_lines": 271}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nset -e\n\nROOT=$(cd $(dirname $BASH_SOURCE)/..; pwd)\n\nLAST_COMMITTED_REV=$($ROOT/build-support/get-upstream-commit.sh)\nif [ -z \"$LAST_COMMITTED_REV\" ]; then\n  echo \"ERROR: could not find the last committed upstream changelist\"\n  exit 1\nfi\n\n$ROOT/build-support/clang_tidy_gerrit.py \\\n  --no-gerrit \\\n  --rev-range \\\n  \"${LAST_COMMITTED_REV}\"\n", "num_lines": 34}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This script is invoked from the Jenkins builds to build Kudu\n# and run all the unit tests.\n#\n# Environment variables may be used to customize operation:\n#   BUILD_TYPE: Default: DEBUG\n#     Maybe be one of ASAN|TSAN|DEBUG|RELEASE|COVERAGE|LINT|IWYU\n#\n#   KUDU_ALLOW_SLOW_TESTS   Default: 1\n#     Runs the \"slow\" version of the unit tests. Set to 0 to\n#     run the tests more quickly.\n#\n#   TEST_TMPDIR   Default: /tmp/kudutest-$UID\n#     Specifies the temporary directory where tests should write their\n#     data. It is expected that following the completion of all tests, this\n#     directory is empty (i.e. every test cleaned up after itself).\n#\n#   RUN_FLAKY_ONLY    Default: 0\n#     Only runs tests which have failed recently, if this is 1.\n#     Used by the kudu-flaky-tests jenkins build.\n#\n#   KUDU_FLAKY_TEST_ATTEMPTS  Default: 1\n#     If more than 1, will fetch the list of known flaky tests\n#     from the kudu-test jenkins job, and allow those tests to\n#     be flaky in this build.\n#\n#   TEST_RESULT_SERVER  Default: none\n#     The host:port pair of a server running test_result_server.py.\n#     This must be configured for flaky test resistance or test result\n#     reporting to work.\n#\n#   ENABLE_DIST_TEST  Default: 0\n#     If set to 1, will submit C++ and Java tests to be run by the\n#     distributed test runner instead of running them locally.\n#     This requires that $DIST_TEST_HOME be set to a working dist_test\n#     checkout (and that dist_test itself be appropriately configured to\n#     point to a cluster)\n#\n#   BUILD_JAVA        Default: 1\n#     Build and test java code if this is set to 1.\n#\n#   BUILD_MAVEN       Default: 0\n#     When building java code, build with Maven if this is set to 1.\n#\n#   BUILD_GRADLE      Default: 1\n#     When building java code, build with Gradle if this is set to 1.\n#\n#   BUILD_PYTHON       Default: 1\n#     Build and test the Python wrapper of the client API.\n#\n#   BUILD_PYTHON3      Default: 1\n#     Build and test the Python wrapper of the client API in Python. This\n#     option is not mutually exclusive from BUILD_PYTHON. If both options\n#     are set (default), then both will be run.\n#\n#   PIP_INSTALL_FLAGS  Default: \"\"\n#     Extra flags which are passed to 'pip install' when setting up the build\n#     environment for the Python wrapper.\n#\n#   MVN_FLAGS          Default: \"\"\n#     Extra flags which are passed to 'mvn' when building and running Java\n#     tests. This can be useful, for example, to choose a different maven\n#     repository location.\n#\n#   GRADLE_FLAGS       Default: \"\"\n#     Extra flags which are passed to 'gradle' when running Gradle commands.\n#\n#   ERROR_ON_TEST_FAILURE    Default: 1\n#     Whether test failures will cause this script to return an error.\n\n# If a commit messages contains a line that says 'DONT_BUILD', exit\n# immediately.\nDONT_BUILD=$(git show|egrep '^\\s{4}DONT_BUILD$')\nif [ \"x$DONT_BUILD\" != \"x\" ]; then\n    echo \"*** Build not requested. Exiting.\"\n    exit 1\nfi\n\nset -e\n# We pipe our build output to a log file with tee.\n# This bash setting ensures that the script exits if the build fails.\nset -o pipefail\n# gather core dumps\nulimit -c unlimited\n\nBUILD_TYPE=${BUILD_TYPE:-DEBUG}\nBUILD_TYPE=$(echo \"$BUILD_TYPE\" | tr a-z A-Z) # capitalize\nBUILD_TYPE_LOWER=$(echo \"$BUILD_TYPE\" | tr A-Z a-z)\n\n# Set up defaults for environment variables.\nDEFAULT_ALLOW_SLOW_TESTS=1\n\n# TSAN builds are pretty slow, so don't do SLOW tests unless explicitly\n# requested. Setting KUDU_USE_TSAN influences the thirdparty build.\nif [ \"$BUILD_TYPE\" = \"TSAN\" ]; then\n  DEFAULT_ALLOW_SLOW_TESTS=0\n  export KUDU_USE_TSAN=1\nfi\n\nexport KUDU_FLAKY_TEST_ATTEMPTS=${KUDU_FLAKY_TEST_ATTEMPTS:-1}\nexport KUDU_ALLOW_SLOW_TESTS=${KUDU_ALLOW_SLOW_TESTS:-$DEFAULT_ALLOW_SLOW_TESTS}\nexport KUDU_COMPRESS_TEST_OUTPUT=${KUDU_COMPRESS_TEST_OUTPUT:-1}\nexport TEST_TMPDIR=${TEST_TMPDIR:-/tmp/kudutest-$UID}\nBUILD_JAVA=${BUILD_JAVA:-1}\nBUILD_MAVEN=${BUILD_MAVEN:-0}\nBUILD_GRADLE=${BUILD_GRADLE:-1}\nBUILD_PYTHON=${BUILD_PYTHON:-1}\nBUILD_PYTHON3=${BUILD_PYTHON3:-1}\nERROR_ON_TEST_FAILURE=${ERROR_ON_TEST_FAILURE:-1}\n\n# Ensure that the test data directory is usable.\nmkdir -p \"$TEST_TMPDIR\"\nif [ ! -w \"$TEST_TMPDIR\" ]; then\n  echo \"Error: Test output directory ($TEST_TMPDIR) is not writable on $(hostname) by user $(whoami)\"\n  exit 1\nfi\n\nSOURCE_ROOT=$(cd $(dirname \"$BASH_SOURCE\")/../..; pwd)\nBUILD_ROOT=$SOURCE_ROOT/build/$BUILD_TYPE_LOWER\n\n# Remove testing artifacts from the previous run before we do anything\n# else. Otherwise, if we fail during the \"build\" step, Jenkins will\n# archive the test logs from the previous run, thinking they came from\n# this run, and confuse us when we look at the failed build.\nrm -rf $BUILD_ROOT\nmkdir -p $BUILD_ROOT\n\n# Same for the Java tests, which aren't inside BUILD_ROOT\nrm -rf $SOURCE_ROOT/java/*/target\nrm -rf $SOURCE_ROOT/java/*/build\n\nlist_flaky_tests() {\n  local url=\"http://$TEST_RESULT_SERVER/list_failed_tests?num_days=3&build_pattern=%25kudu-test%25\"\n  >&2 echo Fetching flaky test list from \"$url\" ...\n  curl -s --show-error \"$url\"\n  return $?\n}\n\nTEST_LOGDIR=\"$BUILD_ROOT/test-logs\"\nTEST_DEBUGDIR=\"$BUILD_ROOT/test-debug\"\n\ncleanup() {\n  echo Cleaning up all build artifacts...\n  $SOURCE_ROOT/build-support/jenkins/post-build-clean.sh\n}\n# If we're running inside Jenkins (the BUILD_ID is set), then install\n# an exit handler which will clean up all of our build results.\nif [ -n \"$BUILD_ID\" ]; then\n  trap cleanup EXIT\nfi\n\nexport TOOLCHAIN_DIR=/opt/toolchain\nif [ -d \"$TOOLCHAIN_DIR\" ]; then\n  PATH=$TOOLCHAIN_DIR/apache-maven-3.0/bin:$PATH\nfi\n\nTHIRDPARTY_TYPE=\nif [ \"$BUILD_TYPE\" = \"TSAN\" ]; then\n  THIRDPARTY_TYPE=tsan\nfi\n$SOURCE_ROOT/build-support/enable_devtoolset.sh thirdparty/build-if-necessary.sh $THIRDPARTY_TYPE\n\nTHIRDPARTY_BIN=$(pwd)/thirdparty/installed/common/bin\nexport PPROF_PATH=$THIRDPARTY_BIN/pprof\n\nif which ccache >/dev/null ; then\n  CLANG=$(pwd)/build-support/ccache-clang/clang\nelse\n  CLANG=$(pwd)/thirdparty/clang-toolchain/bin/clang\nfi\n\n# Configure the build\n#\n# ASAN/TSAN can't build the Python bindings because the exported Kudu client\n# library (which the bindings depend on) is missing ASAN/TSAN symbols.\ncd $BUILD_ROOT\nif [ \"$BUILD_TYPE\" = \"ASAN\" ]; then\n  USE_CLANG=1\n  CMAKE_BUILD=fastdebug\n  EXTRA_BUILD_FLAGS=\"-DKUDU_USE_ASAN=1 -DKUDU_USE_UBSAN=1\"\n  BUILD_PYTHON=0\n  BUILD_PYTHON3=0\nelif [ \"$BUILD_TYPE\" = \"TSAN\" ]; then\n  USE_CLANG=1\n  CMAKE_BUILD=fastdebug\n  EXTRA_BUILD_FLAGS=\"-DKUDU_USE_TSAN=1\"\n  EXTRA_TEST_FLAGS=\"$EXTRA_TEST_FLAGS -LE no_tsan\"\n  BUILD_PYTHON=0\n  BUILD_PYTHON3=0\nelif [ \"$BUILD_TYPE\" = \"COVERAGE\" ]; then\n  USE_CLANG=1\n  CMAKE_BUILD=debug\n  EXTRA_BUILD_FLAGS=\"-DKUDU_GENERATE_COVERAGE=1\"\n  DO_COVERAGE=1\n\n  # We currently dont capture coverage for Java or Python.\n  BUILD_JAVA=0\n  BUILD_PYTHON=0\n  BUILD_PYTHON3=0\nelif [ \"$BUILD_TYPE\" = \"LINT\" ]; then\n  CMAKE_BUILD=debug\nelif [ \"$BUILD_TYPE\" = \"IWYU\" ]; then\n  USE_CLANG=1\n  CMAKE_BUILD=debug\nelse\n  # Must be DEBUG or RELEASE\n  CMAKE_BUILD=$BUILD_TYPE\nfi\n\n# Assemble the cmake command line, starting with environment variables.\n\n# There's absolutely no reason to rebuild the thirdparty tree; we just ran\n# build-if-necessary.sh above.\nCMAKE=\"env NO_REBUILD_THIRDPARTY=1\"\n\n# If using clang, we have to change the compiler via environment variables.\nif [ -n \"$USE_CLANG\" ]; then\n  CMAKE=\"$CMAKE CC=$CLANG CXX=$CLANG++\"\nfi\n\n# This will be a passthrough for systems without devtoolset.\nCMAKE=\"$CMAKE $SOURCE_ROOT/build-support/enable_devtoolset.sh\"\n\nCMAKE=\"$CMAKE $THIRDPARTY_BIN/cmake\"\nCMAKE=\"$CMAKE -DCMAKE_BUILD_TYPE=$CMAKE_BUILD\"\n\n# On distributed tests, force dynamic linking even for release builds. Otherwise,\n# the test binaries are too large and we spend way too much time uploading them\n# to the test slaves.\nif [ \"$ENABLE_DIST_TEST\" == \"1\" ]; then\n  CMAKE=\"$CMAKE -DKUDU_LINK=dynamic\"\nfi\nif [ -n \"$EXTRA_BUILD_FLAGS\" ]; then\n  CMAKE=\"$CMAKE $EXTRA_BUILD_FLAGS\"\nfi\nCMAKE=\"$CMAKE $SOURCE_ROOT\"\n$CMAKE\n\n# Create empty test logs or else Jenkins fails to archive artifacts, which\n# results in the build failing.\nmkdir -p Testing/Temporary\nmkdir -p $TEST_LOGDIR\n\n# Short circuit for LINT builds.\nif [ \"$BUILD_TYPE\" = \"LINT\" ]; then\n  make lint | tee $TEST_LOGDIR/lint.log\n  exit $?\nfi\n\n# Short circuit for IWYU builds: run the include-what-you-use tool on the files\n# modified since the last committed changelist committed upstream.\nif [ \"$BUILD_TYPE\" = \"IWYU\" ]; then\n  make iwyu | tee $TEST_LOGDIR/iwyu.log\n  exit $?\nfi\n\n# Only enable test core dumps for certain build types.\nif [ \"$BUILD_TYPE\" != \"ASAN\" ]; then\n  export KUDU_TEST_ULIMIT_CORE=unlimited\nfi\n\n# If we are supposed to be resistant to flaky tests, we need to fetch the\n# list of tests to ignore\nif [ \"$KUDU_FLAKY_TEST_ATTEMPTS\" -gt 1 ]; then\n  echo Fetching flaky test list...\n  export KUDU_FLAKY_TEST_LIST=$BUILD_ROOT/flaky-tests.txt\n  mkdir -p $(dirname $KUDU_FLAKY_TEST_LIST)\n  echo -n > $KUDU_FLAKY_TEST_LIST\n    if [ -n \"$TEST_RESULT_SERVER\" ] && \\\n        list_flaky_tests > $KUDU_FLAKY_TEST_LIST ; then\n    echo Will retry flaky tests up to $KUDU_FLAKY_TEST_ATTEMPTS times:\n    cat $KUDU_FLAKY_TEST_LIST\n    echo ----------\n  else\n    echo Unable to fetch flaky test list. Disabling flaky test resistance.\n    export KUDU_FLAKY_TEST_ATTEMPTS=1\n  fi\nfi\n\n# our tests leave lots of data lying around, clean up before we run\nif [ -d \"$TEST_TMPDIR\" ]; then\n  rm -Rf $TEST_TMPDIR/*\nfi\n\n# actually do the build\necho\necho Building C++ code.\necho ------------------------------------------------------------\nNUM_PROCS=$(getconf _NPROCESSORS_ONLN)\nmake -j$NUM_PROCS 2>&1 | tee build.log\n\n# If compilation succeeds, try to run all remaining steps despite any failures.\nset +e\n\n# Run tests\nif [ \"$RUN_FLAKY_ONLY\" == \"1\" ] ; then\n  if [ -z \"$TEST_RESULT_SERVER\" ]; then\n    echo Must set TEST_RESULT_SERVER to use RUN_FLAKY_ONLY\n    exit 1\n  fi\n  echo\n  echo Running flaky tests only:\n  echo ------------------------------------------------------------\n  if ! ( set -o pipefail ;\n         list_flaky_tests | tee $BUILD_ROOT/flaky-tests.txt) ; then\n    echo Could not fetch flaky tests list.\n    exit 1\n  fi\n  test_regex=$(perl -e '\n    chomp(my @lines = <>);\n    print join(\"|\", map { \"^\" . quotemeta($_) } @lines);\n   ' $BUILD_ROOT/flaky-tests.txt)\n  if [ -z \"$test_regex\" ]; then\n    echo No tests are flaky.\n    exit 0\n  fi\n  EXTRA_TEST_FLAGS=\"$EXTRA_TEST_FLAGS -R $test_regex\"\n\n  # We don't support detecting java and python flaky tests at the moment.\n  echo Disabling Java and python build since RUN_FLAKY_ONLY=1\n  BUILD_PYTHON=0\n  BUILD_PYTHON3=0\n  BUILD_JAVA=0\nfi\n\nTESTS_FAILED=0\nEXIT_STATUS=0\nFAILURES=\"\"\n\n# If we're running distributed C++ tests, submit them asynchronously while\n# we run the Java and Python tests.\nif [ \"$ENABLE_DIST_TEST\" == \"1\" ]; then\n  echo\n  echo Submitting C++ distributed-test job.\n  echo ------------------------------------------------------------\n  # dist-test uses DIST_TEST_JOB_PATH to define where to output it's id file.\n  export DIST_TEST_JOB_PATH=$BUILD_ROOT/c-dist-test-job-id\n  rm -f $DIST_TEST_JOB_PATH\n  if ! $SOURCE_ROOT/build-support/dist_test.py --no-wait run ; then\n    EXIT_STATUS=1\n    FAILURES=\"$FAILURES\"$'Could not submit C++ distributed test job\\n'\n  fi\n  # Still need to run a few non-dist-test-capable tests locally.\n  EXTRA_TEST_FLAGS=\"$EXTRA_TEST_FLAGS -L no_dist_test\"\nfi\n\nif ! $THIRDPARTY_BIN/ctest -j$NUM_PROCS $EXTRA_TEST_FLAGS ; then\n  TESTS_FAILED=1\n  FAILURES=\"$FAILURES\"$'C++ tests failed\\n'\nfi\n\nif [ \"$DO_COVERAGE\" == \"1\" ]; then\n  echo\n  echo Generating coverage report...\n  echo ------------------------------------------------------------\n  if ! $SOURCE_ROOT/thirdparty/installed/common/bin/gcovr \\\n      -r $SOURCE_ROOT \\\n      --gcov-filter='.*src#kudu.*' \\\n      --gcov-executable=$SOURCE_ROOT/build-support/llvm-gcov-wrapper \\\n      --xml \\\n      > $BUILD_ROOT/coverage.xml ; then\n    EXIT_STATUS=1\n    FAILURES=\"$FAILURES\"$'Coverage report failed\\n'\n  fi\nfi\n\nif [ \"$BUILD_JAVA\" == \"1\" ]; then\n  echo\n  echo Building and testing java...\n  echo ------------------------------------------------------------\n\n  # Make sure we use JDK8\n  export JAVA_HOME=$JAVA8_HOME\n  export PATH=$JAVA_HOME/bin:$PATH\n  pushd $SOURCE_ROOT/java\n  set -x\n\n  # Run the full Maven build.\n  if [ \"$BUILD_MAVEN\" == \"1\" ]; then\n    EXTRA_MVN_FLAGS=\"-B\"\n    EXTRA_MVN_FLAGS=\"$EXTRA_MVN_FLAGS -Dsurefire.rerunFailingTestsCount=3\"\n    EXTRA_MVN_FLAGS=\"$EXTRA_MVN_FLAGS -Dfailsafe.rerunFailingTestsCount=3\"\n    EXTRA_MVN_FLAGS=\"$EXTRA_MVN_FLAGS -Dmaven.javadoc.skip\"\n    EXTRA_MVN_FLAGS=\"$EXTRA_MVN_FLAGS $MVN_FLAGS\"\n    if ! mvn $EXTRA_MVN_FLAGS clean verify ; then\n      TESTS_FAILED=1\n      FAILURES=\"$FAILURES\"$'Java Maven build/test failed\\n'\n    fi\n  fi\n\n  # Run the full Gradle build.\n  if [ \"$BUILD_GRADLE\" == \"1\" ]; then\n    export EXTRA_GRADLE_FLAGS=\"--console=plain\"\n    EXTRA_GRADLE_FLAGS=\"$EXTRA_GRADLE_FLAGS --no-daemon\"\n    EXTRA_GRADLE_FLAGS=\"$EXTRA_GRADLE_FLAGS --continue\"\n    EXTRA_GRADLE_FLAGS=\"$EXTRA_GRADLE_FLAGS -DrerunFailingTestsCount=3\"\n    # KUDU-2524: temporarily disable scalafmt until we can work out its JDK\n    # incompatibility issue.\n    EXTRA_GRADLE_FLAGS=\"$EXTRA_GRADLE_FLAGS -DskipFormat\"\n    EXTRA_GRADLE_FLAGS=\"$EXTRA_GRADLE_FLAGS $GRADLE_FLAGS\"\n    # If we're running distributed Java tests, submit them asynchronously.\n    if [ \"$ENABLE_DIST_TEST\" == \"1\" ]; then\n      echo\n      echo Submitting Java distributed-test job.\n      echo ------------------------------------------------------------\n      # dist-test uses DIST_TEST_JOB_PATH to define where to output it's id file.\n      export DIST_TEST_JOB_PATH=$BUILD_ROOT/java-dist-test-job-id\n      rm -f $DIST_TEST_JOB_PATH\n      if ! $SOURCE_ROOT/build-support/dist_test.py --no-wait java run-all ; then\n        EXIT_STATUS=1\n        FAILURES=\"$FAILURES\"$'Could not submit Java distributed test job\\n'\n      fi\n    else\n      # TODO: Run `gradle check` in BUILD_TYPE DEBUG when static code analysis is fixed\n      if ! ./gradlew $EXTRA_GRADLE_FLAGS clean test ; then\n        TESTS_FAILED=1\n        FAILURES=\"$FAILURES\"$'Java Gradle build/test failed\\n'\n      fi\n    fi\n  fi\n\n  # Run a script to verify the contents of the JARs to ensure the shading and\n  # packaging is correct.\n  $SOURCE_ROOT/build-support/verify_jars.pl .\n\n  set +x\n  popd\nfi\n\n\nif [ \"$BUILD_PYTHON\" == \"1\" ]; then\n  echo\n  echo Building and testing python.\n  echo ------------------------------------------------------------\n\n  # Failing to compile the Python client should result in a build failure.\n  set -e\n  export KUDU_HOME=$SOURCE_ROOT\n  export KUDU_BUILD=$BUILD_ROOT\n  pushd $SOURCE_ROOT/python\n\n  # Create a sane test environment.\n  rm -Rf $KUDU_BUILD/py_env\n  virtualenv $KUDU_BUILD/py_env\n  source $KUDU_BUILD/py_env/bin/activate\n\n  # Old versions of pip (such as the one found in el6) default to pypi's http://\n  # endpoint which no longer exists. The -i option lets us switch to the\n  # https:// endpoint in such cases.\n  #\n  # Unfortunately, in these old versions of pip, -i doesn't appear to apply\n  # recursively to transitive dependencies installed via a direct dependency's\n  # \"python setup.py\" command. Therefore we have no choice but to upgrade to a\n  # new version of pip to proceed.\n  #\n  # Beginning with pip 10, Python 2.6 is no longer supported. Attempting to\n  # upgrade to pip 10 on Python 2.6 yields syntax errors. We don't need any new\n  # pip features, so let's pin to the last pip version to support Python 2.6.\n  pip install -i https://pypi.python.org/simple $PIP_INSTALL_FLAGS --upgrade 'pip < 10.0.0b1'\n\n  # New versions of pip raise an exception when upgrading old versions of\n  # setuptools (such as the one found in el6). The workaround is to upgrade\n  # setuptools on its own, outside of requirements.txt, and with the pip version\n  # check disabled.\n  pip install --disable-pip-version-check $PIP_INSTALL_FLAGS --upgrade 'setuptools >= 0.8'\n\n  # One of our dependencies is pandas, installed via requirements.txt below. It\n  # depends on numpy, and if we don't install numpy directly, the pandas\n  # installation will install the latest numpy which is incompatible with Python 2.6.\n  #\n  # To work around this, we need to install a 2.6-compatible version of numpy\n  # before installing pandas. Listing such a numpy version in requirements.txt\n  # doesn't work; it needs to be explicitly installed here.\n  #\n  # Installing numpy may involve some compiler work, so we must pass in the\n  # current values of CC and CXX.\n  #\n  # See https://github.com/numpy/numpy/releases/tag/v1.12.0 for more details.\n  CC=$CLANG CXX=$CLANG++ pip install $PIP_INSTALL_FLAGS 'numpy <1.12.0'\n\n  # We've got a new pip and new setuptools. We can now install the rest of the\n  # Python client's requirements.\n  #\n  # Installing the Cython dependency may involve some compiler work, so we must\n  # pass in the current values of CC and CXX.\n  CC=$CLANG CXX=$CLANG++ pip install $PIP_INSTALL_FLAGS -r requirements.txt\n\n  # We need to install Pandas manually since its not a required package but is needed\n  # to run all of the tests.\n  # pandas 0.18 dropped support for python 2.6.\n  #\n  # See https://pandas.pydata.org/pandas-docs/version/0.23.0/whatsnew.html#v0-18-0-march-13-2016\n  # for more details.\n  pip install $PIP_INSTALL_FLAGS \"pandas<0.18\"\n\n  # Delete old Cython extensions to force them to be rebuilt.\n  rm -Rf build kudu_python.egg-info kudu/*.so\n\n  # Build the Python bindings. This assumes we run this script from base dir.\n  CC=$CLANG CXX=$CLANG++ python setup.py build_ext\n  set +e\n\n  # Run the Python tests.\n  if ! python setup.py test \\\n      --addopts=\"kudu --junit-xml=$TEST_LOGDIR/python_client.xml\" \\\n      2> $TEST_LOGDIR/python_client.log ; then\n    TESTS_FAILED=1\n    FAILURES=\"$FAILURES\"$'Python tests failed\\n'\n  fi\n\n  deactivate\n  popd\nfi\n\nif [ \"$BUILD_PYTHON3\" == \"1\" ]; then\n  echo\n  echo Building and testing python 3.\n  echo ------------------------------------------------------------\n\n  # Failing to compile the Python client should result in a build failure.\n  set -e\n  export KUDU_HOME=$SOURCE_ROOT\n  export KUDU_BUILD=$BUILD_ROOT\n  pushd $SOURCE_ROOT/python\n\n  # Create a sane test environment.\n  rm -Rf $KUDU_BUILD/py_env\n  virtualenv -p python3 $KUDU_BUILD/py_env\n  source $KUDU_BUILD/py_env/bin/activate\n\n  # Old versions of pip (such as the one found in el6) default to pypi's http://\n  # endpoint which no longer exists. The -i option lets us switch to the\n  # https:// endpoint in such cases.\n  #\n  # Unfortunately, in these old versions of pip, -i doesn't appear to apply\n  # recursively to transitive dependencies installed via a direct dependency's\n  # \"python setup.py\" command. Therefore we have no choice but to upgrade to a\n  # new version of pip to proceed.\n  pip install -i https://pypi.python.org/simple $PIP_INSTALL_FLAGS --upgrade pip\n\n  # New versions of pip raise an exception when upgrading old versions of\n  # setuptools (such as the one found in el6). The workaround is to upgrade\n  # setuptools on its own, outside of requirements.txt, and with the pip version\n  # check disabled.\n  pip install --disable-pip-version-check $PIP_INSTALL_FLAGS --upgrade 'setuptools >= 0.8'\n\n  # We've got a new pip and new setuptools. We can now install the rest of the\n  # Python client's requirements.\n  #\n  # Installing the Cython dependency may involve some compiler work, so we must\n  # pass in the current values of CC and CXX.\n  CC=$CLANG CXX=$CLANG++ pip install $PIP_INSTALL_FLAGS -r requirements.txt\n\n  # We need to install Pandas manually since its not a required package but is needed\n  # to run all of the tests.\n  pip install $PIP_INSTALL_FLAGS pandas\n\n  # Delete old Cython extensions to force them to be rebuilt.\n  rm -Rf build kudu_python.egg-info kudu/*.so\n\n  # Build the Python bindings. This assumes we run this script from base dir.\n  CC=$CLANG CXX=$CLANG++ python setup.py build_ext\n  set +e\n\n  # Run the Python tests.\n  if ! python setup.py test \\\n      --addopts=\"kudu --junit-xml=$TEST_LOGDIR/python3_client.xml\" \\\n      2> $TEST_LOGDIR/python3_client.log ; then\n    TESTS_FAILED=1\n    FAILURES=\"$FAILURES\"$'Python 3 tests failed\\n'\n  fi\n\n  deactivate\n  popd\nfi\n\n# If we submitted the tasks earlier, go fetch the results now\nif [ \"$ENABLE_DIST_TEST\" == \"1\" ]; then\n  echo\n  echo Fetching previously submitted C++ dist-test results...\n  echo ------------------------------------------------------------\n  C_DIST_TEST_ID=`cat $BUILD_ROOT/c-dist-test-job-id`\n  if ! $DIST_TEST_HOME/bin/client watch $C_DIST_TEST_ID ; then\n    TESTS_FAILED=1\n    FAILURES=\"$FAILURES\"$'Distributed C++ tests failed\\n'\n  fi\n  DT_DIR=$TEST_LOGDIR/dist-test-out\n  rm -Rf $DT_DIR\n  $DIST_TEST_HOME/bin/client fetch --artifacts -d $DT_DIR $C_DIST_TEST_ID\n  # Fetching the artifacts expands each log into its own directory.\n  # Move them back into the main log directory\n  rm -f $DT_DIR/*zip\n  for arch_dir in $DT_DIR/* ; do\n    mv $arch_dir/build/$BUILD_TYPE_LOWER/test-logs/* $TEST_LOGDIR\n    rm -Rf $arch_dir\n  done\n\n  if [ \"$BUILD_GRADLE\" == \"1\" ]; then\n    echo\n    echo Fetching previously submitted Java dist-test results...\n    echo ------------------------------------------------------------\n    JAVA_DIST_TEST_ID=`cat $BUILD_ROOT/java-dist-test-job-id`\n    if ! $DIST_TEST_HOME/bin/client watch $JAVA_DIST_TEST_ID ; then\n      TESTS_FAILED=1\n      FAILURES=\"$FAILURES\"$'Distributed Java tests failed\\n'\n    fi\n    DT_DIR=$TEST_LOGDIR/java-dist-test-out\n    rm -Rf $DT_DIR\n    $DIST_TEST_HOME/bin/client fetch --artifacts -d $DT_DIR $JAVA_DIST_TEST_ID\n    # Fetching the artifacts expands each log into its own directory.\n    # Move them back into the main log directory\n    rm -f $DT_DIR/*zip\n    for arch_dir in $DT_DIR/* ; do\n      mv $arch_dir/build/java/test-logs/* $TEST_LOGDIR\n      rm -Rf $arch_dir\n    done\n  fi\nfi\n\nif [ \"$TESTS_FAILED\" != \"0\" -o \"$EXIT_STATUS\" != \"0\" ]; then\n  echo\n  echo Tests failed, making sure we have XML files for all tests.\n  echo ------------------------------------------------------------\n\n  # Tests that crash do not generate JUnit report XML files.\n  # We go through and generate a kind of poor-man's version of them in those cases.\n  for GTEST_OUTFILE in $TEST_LOGDIR/*.txt.gz; do\n    TEST_EXE=$(basename $GTEST_OUTFILE .txt.gz)\n    GTEST_XMLFILE=\"$TEST_LOGDIR/$TEST_EXE.xml\"\n    if [ ! -f \"$GTEST_XMLFILE\" ]; then\n      echo \"JUnit report missing:\" \\\n           \"generating fake JUnit report file from $GTEST_OUTFILE and saving it to $GTEST_XMLFILE\"\n      zcat $GTEST_OUTFILE | $SOURCE_ROOT/build-support/parse_test_failure.py -x > $GTEST_XMLFILE\n    fi\n  done\nelse\n  # If all tests passed, ensure that they cleaned up their test output.\n  TEST_TMPDIR_CONTENTS=$(ls $TEST_TMPDIR)\n  if [ -n \"$TEST_TMPDIR_CONTENTS\" ]; then\n    echo \"All tests passed, yet some left behind their test output.\"\n    echo \"TEST_TMPDIR: $TEST_TMPDIR\"\n    find $TEST_TMPDIR -ls\n    EXIT_STATUS=1\n  fi\nfi\n\nset -e\n\nif [ -n \"$FAILURES\" ]; then\n  echo\n  echo\n  echo ======================================================================\n  echo Failure summary\n  echo ======================================================================\n  echo $FAILURES\n  echo\n  echo\nfi\n\n# If any of the tests failed and we are honoring test failures, set the exit\n# status to 1. Note that it may have already been set to 1 above.\nif [ \"$ERROR_ON_TEST_FAILURE\" == \"1\" -a \"$TESTS_FAILED\" == \"1\" ]; then\n  EXIT_STATUS=1\nfi\n\nexit $EXIT_STATUS\n", "num_lines": 685}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Script which, when run from Jenkins, will hunt and kill any other jenkins\n# processes running on the same machine from a different build.\n#\n# This is done by looking for all of the processes owned by the jenkins user,\n# checking their BUILD_ID environment variable, and killing any whose BUILD_ID\n# does not match the current $BUILD_ID environment.  This assumes that there are\n# no concurrent builds configured in Jenkins, for obvious reasons.\n#\n# Set $DRY_RUN before running this script to just see what would be killed.\n\nset -e\n\nJENKINS_USER=${JENKINS_USER:-jenkins}\nCURRENT_BUILD=$BUILD_ID\n\nif [ \"$USER\" != \"$JENKINS_USER\" ]; then\n  echo Not running as user \\'$JENKINS_USER\\'\n  exit 1\nfi\n\nif [ -z \"$CURRENT_BUILD\" ]; then\n  echo Not running in the context of a Jenkins build\n  exit 1\nfi\n\nJENKINS_PIDS=$(pgrep -u $JENKINS_USER)\nfor pid in $JENKINS_PIDS; do\n  cmdline=$(ps h -p $pid -o cmd || echo '[pid exited]')\n  build_env=$(cat /proc/$pid/environ 2>/dev/null | tr '\\0' '\\n' | egrep '^BUILD_ID=' || :)\n  if [ -z \"$build_env\" ]; then\n    # Some Jenkins processes, like the slave itself, don't have a BUILD_ID\n    # set. We shouldn't kill those.\n    echo \"Process $pid ($cmdline) not associated with any build. Skipping...\"\n    continue\n  fi\n  build_id=$(echo $build_env | cut -d= -f2)\n  if [ \"$build_id\" != \"$CURRENT_BUILD\" ]; then\n    echo \"Killing zombie process $pid (from build $build_id)\"\n    ps -fww -p $pid || :\n    if [ -z \"$DRY_RUN\" ]; then\n      kill -9 $pid || :\n    fi\n    echo ----------\n  else\n    echo \"pid $pid ($cmdline) is from the current build. Not killing\"\n  fi\ndone\n", "num_lines": 67}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -x\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Script which runs on Jenkins slaves after the build/test to clean up\n# disk space used by build artifacts. Our build tends to \"make clean\"\n# before running anyway, so doing the post-build cleanup shouldn't\n# hurt our build times. It does, however, save a fair amount of disk\n# space in the Jenkins workspace disk. This can help prevent our EC2\n# slaves from filling up and causing spurious failures.\n\nROOT=$(cd $(dirname \"$BASH_SOURCE\")/../..; pwd)\ncd $ROOT\n\n# Note that we use simple shell commands instead of \"make clean\"\n# or \"mvn clean\". This is more foolproof even if something ends\n# up partially compiling, etc.\n\n# Clean up intermediate object files in the src tree\nfind build/latest/src -name \\*.o -exec rm -f {} \\;\n\n# Clean up the actual build artifacts\nrm -Rf build/latest/bin build/latest/lib\n\n# Clean up any java build artifacts\nfind java -name \\*.jar -delete -o -name \\*.class -delete \n", "num_lines": 42}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n########################################################################\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This script runs after Kudu binaries are built. It does:\n# 1. For each binary, run $binary --helpxml and save the output to an XML file\n# 2. For each generated XML file, run it through xsltproc two times:\n#    a. Once to capture \"supported\" (stable) flags\n#    b. Once to capture \"unsupported\" (evolving or experimental) flags\n# 3. For each generated Asciidoc file, include it in either configuration_reference.adoc\n#    or configuration_reference_unsupported.adoc\n#\n# Usage: make_docs.sh <output_dir>\n########################################################################\nset -e\n\nusage() {\n  echo usage: \"$0 --build_root <path to build root> [--site <path to gh-pages checkout>]\"\n}\n\nwhile [[ $# > 0 ]] ; do\n    arg=$1\n    case $arg in\n      --help)\n        usage\n        exit 1\n        ;;\n      --build_root)\n        BUILD_ROOT=$2\n        shift\n        shift\n        ;;\n      --site|-s)\n        SITE=$2\n        if [ -z \"$SITE\" ]; then\n          usage\n          exit 1\n        fi\n        shift\n        shift\n        if [ ! -d \"$SITE\"/.git ] || [ ! -d \"$SITE/_layouts/\" ]; then\n          echo \"path $SITE doesn't appear to be the root of a git checkout \"\n          echo \"of the Kudu site. Expected to find .git/ and _layouts/ directories\"\n          exit 1\n        fi\n        SITE=$(cd $SITE && pwd)\n        OUTPUT_DIR=$SITE/docs\n        ;;\n      --no-jekyll)\n        NO_JEKYLL=1\n        shift\n        ;;\n      *)\n        echo unknown argument: $arg\n        exit 1\n    esac\ndone\n\nif [ -z \"$BUILD_ROOT\" ]; then\n  usage\n  exit 1\nfi\n\nif [ -z \"$SITE\" ]; then\n  OUTPUT_DIR=$BUILD_ROOT/docs\nfi\n\nGEN_DOC_DIR=$BUILD_ROOT/gen-docs\nSOURCE_ROOT=$(cd $(dirname $0)/../../..; pwd)\n\nif ! which ruby > /dev/null; then\n  echo \"ruby must be installed in order to build the docs.\"\n  echo 1\nfi\n\nDOCS_SCRIPTS=\"$SOURCE_ROOT/docs/support/scripts\"\n\n# We must set GEM_PATH because bundler depends on it to find its own libraries.\nexport GEM_PATH=\"$BUILD_ROOT/gems\"\necho GEM_PATH=$GEM_PATH\n\nexport PATH=\"$GEM_PATH/bin:$PATH\"\necho PATH=\"$GEM_PATH/bin:$PATH\"\n\nBUNDLE=\"$GEM_PATH/bin/bundle\"\n\necho \"Locally installing ruby gems needed to build docs.\"\nif [ ! -x \"$BUNDLE\" ]; then\n  set -x\n  gem install --no-ri --no-rdoc -q --install-dir \"$GEM_PATH\" bundler\n  set +x\nfi\n\nset -x\ncd \"$BUILD_ROOT\"\ncp $DOCS_SCRIPTS/Gemfile .\ncp $DOCS_SCRIPTS/Gemfile.lock .\n$BUNDLE install --no-color --path \"$GEM_PATH\"\nset +x\n\n# We need the xsltproc package.\nfor requirement in \"xsltproc\"; do\n  if ! which $requirement > /dev/null; then\n    echo \"$requirement is required, but cannot be found. Make sure it is in your path.\"\n    exit 1\n  fi\ndone\n\nmkdir -p \"$OUTPUT_DIR\" \"$GEN_DOC_DIR\"\n\n# Create config flag references for each of the binaries below\nbinaries=(\"kudu-master\" \\\n          \"kudu-tserver\")\n\nfor binary in ${binaries[@]}; do\n  echo \"Running $binary --helpxml\"\n\n  (\n    # Reset environment to avoid affecting the default flag values.\n    for var in $(env | awk -F= '{print $1}' | egrep -i 'KUDU|GLOG'); do\n      echo \"unset $var\"\n      eval \"unset $var\"\n    done\n\n    # Create the XML file.\n    # This command exits with a nonzero value.\n    $BUILD_ROOT/bin/$binary --helpxml > ${GEN_DOC_DIR}/$(basename $binary).xml || true\n  )\n\n  # Create the supported config reference\n  xsltproc \\\n    --stringparam binary $binary \\\n    --stringparam support-level supported \\\n    -o $GEN_DOC_DIR/${binary}_configuration_reference.adoc \\\n      $SOURCE_ROOT/docs/support/xsl/gflags_to_asciidoc.xsl \\\n    ${GEN_DOC_DIR}/$binary.xml\n  INCLUSIONS_SUPPORTED+=\"include::${binary}_configuration_reference.adoc[leveloffset=+1]\\n\"\n\n  # Create the unsupported config reference\n  xsltproc \\\n    --stringparam binary $binary \\\n    --stringparam support-level unsupported \\\n    -o $GEN_DOC_DIR/${binary}_configuration_reference_unsupported.adoc \\\n      $SOURCE_ROOT/docs/support/xsl/gflags_to_asciidoc.xsl \\\n    ${GEN_DOC_DIR}/$binary.xml\n  INCLUSIONS_UNSUPPORTED+=\"include::${binary}_configuration_reference_unsupported.adoc[leveloffset=+1]\\n\"\ndone\n\n# Add the includes to the configuration reference files, replacing the template lines\ncp $SOURCE_ROOT/docs/configuration_reference* $GEN_DOC_DIR/\nsed -i \"s#@@CONFIGURATION_REFERENCE@@#${INCLUSIONS_SUPPORTED}#\" ${GEN_DOC_DIR}/configuration_reference.adoc\nsed -i \"s#@@CONFIGURATION_REFERENCE@@#${INCLUSIONS_UNSUPPORTED}#\" ${GEN_DOC_DIR}/configuration_reference_unsupported.adoc\n\n# Create tool references\necho \"Running kudu --helpxml\"\n(\n  # Reset environment to avoid affecting the default flag values.\n  for var in $(env | awk -F= '{print $1}' | egrep -i 'KUDU|GLOG'); do\n    echo \"unset $var\"\n    eval \"unset $var\"\n  done\n\n  # Create the XML file.\n  # This command exits with a nonzero value.\n  $BUILD_ROOT/bin/kudu --helpxml > ${GEN_DOC_DIR}/kudu.xml || true\n)\n\n# Create the supported config reference\nxsltproc \\\n-o $GEN_DOC_DIR/command_line_tools.adoc \\\n  $SOURCE_ROOT/docs/support/xsl/tool_to_asciidoc.xsl \\\n${GEN_DOC_DIR}/kudu.xml\n\n# Add the includes to the cli tools reference files, replacing the template lines\ncp $SOURCE_ROOT/docs/command_line_tools_reference.adoc $GEN_DOC_DIR/\nsed -i \"s#@@TOOLS_REFERENCE@@#include::command_line_tools.adoc[leveloffset=+1]\\n#\" ${GEN_DOC_DIR}/command_line_tools_reference.adoc\n\n# If we're generating the web site, pass the template which causes us\n# to generate Jekyll templates instead of full HTML.\nif [ -n \"$SITE\" ]; then\n    TEMPLATE_FLAG=\"-T $SOURCE_ROOT/docs/support/jekyll-templates\"\nelse\n    TEMPLATE_FLAG=\"\"\nfi\n\nbundle exec asciidoctor -d book $TEMPLATE_FLAG \\\n    $SOURCE_ROOT/docs/*.adoc ${GEN_DOC_DIR}/*.adoc -D \"$OUTPUT_DIR\"\n\nmkdir -p \"$OUTPUT_DIR/images\"\ncp $SOURCE_ROOT/docs/images/* \"$OUTPUT_DIR/images/\"\n\n\necho\necho ----------------------------\necho \"Docs built in $OUTPUT_DIR\"\n\n# If we're building the site, try to run Jekyll for them to make\n# it a bit easier to quickly preview the results.\nif [ -n \"$SITE\" ] && [ -z \"$NO_JEKYLL\" ]; then\n  # We need to generate a config file which fakes the \"github.url\" property\n  # so that relative links within the site work.\n  BASE_URL=\"file://$SITE/_site/\"\n  TMP_CONFIG=$(mktemp -t config.XXXXXX)\n  # Rename the config file. The template adds the random section\n  # to the end of the file to be compatible with Mac OS. However,\n  # Jekyll expects the file to end in yml.\n  mv \"$TMP_CONFIG\" \"$TMP_CONFIG.yml\"\n  TMP_CONFIG=\"$TMP_CONFIG.yml\"\n  trap \"rm $TMP_CONFIG\" EXIT\n  printf \"github:\\n  url: %s\" \"$BASE_URL\" > $TMP_CONFIG\n\n  # Now rebuild the site itself.\n  echo Attempting to re-build via Jekyll...\n  bundle exec jekyll build --source \"$SITE\" --config \"$TMP_CONFIG\"\n\n  # Output the URL so it's easy to click on from the terminal.\n  echo ----------------------\n  echo Rebuild successful. View your site at\n  echo $BASE_URL/index.html\n  echo ----------------------\nfi\n", "num_lines": 238}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n########################################################################\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This script generates site documentation and Javadocs.\n########################################################################\nset -e\n\nBUILD_TYPE=release\nSOURCE_ROOT=$(cd $(dirname $0)/../../..; pwd)\nBUILD_ROOT=\"$SOURCE_ROOT/build/$BUILD_TYPE\"\nSITE_OUTPUT_DIR=\"$BUILD_ROOT/site\"\n\nOPT_DOXYGEN=1 # By default, build doxygen docs.\nOPT_JAVADOC=1 # By default, build javadocs.\nOPT_FORCE='' # By default, don't overwrite the destination directory.\n\nusage() {\n  echo \"Usage: $0 [--no-doxygen] [--no-javadoc] [--force]\"\n  echo \"Specify --no-doxygen to skip generation of the C++ client API docs\"\n  echo \"Specify --no-javadoc to skip generation of the Java API docs\"\n  echo \"Specify --force to overwrite the destination directory, if it exists\"\n  exit 1\n}\n\nif [ $# -gt 0 ]; then\n  for arg in $*; do\n    case $arg in\n      \"--no-doxygen\")  OPT_DOXYGEN='' ;;\n      \"--no-javadoc\")  OPT_JAVADOC='' ;;\n      \"--force\")       OPT_FORCE=1 ;;\n      \"--help\")        usage ;;\n      \"-h\")            usage ;;\n      *)               echo \"$0: Unknown command-line option: $arg\"; usage ;;\n    esac\n  done\nfi\n\nif [ -n \"$OPT_DOXYGEN\" ] && ! which doxygen >/dev/null 2>&1; then\n  echo \"Error: doxygen not found.\"\n  usage\nfi\n\nset -x\n\ncd \"$SOURCE_ROOT\"\n\nGIT_REMOTE=$(git config --get remote.origin.url)\nif [ -z \"$GIT_REMOTE\" ]; then\n  echo \"Error: The 'origin' git remote is expected but is not defined\"\n  usage\nfi\n\n# Build Kudu thirdparty\n$SOURCE_ROOT/build-support/enable_devtoolset.sh $SOURCE_ROOT/thirdparty/build-if-necessary.sh\necho \"Successfully built third-party dependencies.\"\n\n# Build the binaries so we can auto-generate the command-line references\nmkdir -p \"$BUILD_ROOT\"\ncd \"$BUILD_ROOT\"\nrm -rf CMakeCache CMakeFiles/\n$SOURCE_ROOT/build-support/enable_devtoolset.sh \\\n    $SOURCE_ROOT/thirdparty/installed/common/bin/cmake \\\n    -DNO_TESTS=1 \\\n    -DCMAKE_BUILD_TYPE=$BUILD_TYPE \\\n    $SOURCE_ROOT\nMAKE_TARGETS=\"kudu kudu-tserver kudu-master\"\nif [ -n \"$OPT_DOXYGEN\" ]; then\n  MAKE_TARGETS=\"$MAKE_TARGETS doxygen\"\nfi\nmake -j$(getconf _NPROCESSORS_ONLN) $MAKE_TARGETS\n\n# Check out the gh-pages repo into $SITE_OUTPUT_DIR\nif [ -d \"$SITE_OUTPUT_DIR\" -a -n \"$OPT_FORCE\" ]; then\n  rm -rf \"$SITE_OUTPUT_DIR\"\nfi\ngit clone -q \"$GIT_REMOTE\" --reference \"$SOURCE_ROOT\" -b gh-pages --depth 1 \"$SITE_OUTPUT_DIR\"\n\n# Build the docs using the styles from the Jekyll site\nrm -Rf \"$SITE_OUTPUT_DIR/docs\"\n$SOURCE_ROOT/docs/support/scripts/make_docs.sh --build_root $BUILD_ROOT --site \"$SITE_OUTPUT_DIR\"\nif [ -f \"$SITE_OUTPUT_DIR/docs/index.html\" ]; then\n  echo \"Successfully built docs.\"\nelse\n  echo \"Docs failed to build.\"\n  exit 1\nfi\n\nif [ -n \"$OPT_JAVADOC\" ]; then\n  JAVADOC_SUBDIR=\"apidocs\"\n  cd \"$SOURCE_ROOT/java\"\n  mvn clean install -DskipTests\n  if mvn clean javadoc:aggregate | tee /dev/stdout | fgrep -q \"Javadoc Warnings\"; then\n    echo \"There are Javadoc warnings. Please fix them.\"\n    exit 1\n  fi\n\n  if [ -f \"$SOURCE_ROOT/java/target/site/$JAVADOC_SUBDIR/index.html\" ]; then\n    echo \"Successfully built Javadocs.\"\n  else\n    echo \"Javadocs failed to build.\"\n    exit 1\n  fi\n\n  rm -Rf \"$SITE_OUTPUT_DIR/$JAVADOC_SUBDIR\"\n  cp -a \"$SOURCE_ROOT/java/target/site/$JAVADOC_SUBDIR\" \"$SITE_OUTPUT_DIR/\"\nfi\n\nif [ -n \"$OPT_DOXYGEN\" ]; then\n  CPP_CLIENT_API_SUBDIR=\"cpp-client-api\"\n  rm -Rf \"$SITE_OUTPUT_DIR/$CPP_CLIENT_API_SUBDIR\"\n  cp -a \"$BUILD_ROOT/docs/doxygen/client_api/html\" \"$SITE_OUTPUT_DIR/$CPP_CLIENT_API_SUBDIR\"\nfi\n\nSITE_SUBDIRS=\"docs\"\nif [ -n \"$OPT_JAVADOC\" ]; then\n  SITE_SUBDIRS=\"$SITE_SUBDIRS $JAVADOC_SUBDIR\"\nfi\nif [ -n \"$OPT_DOXYGEN\" ]; then\n  SITE_SUBDIRS=\"$SITE_SUBDIRS $CPP_CLIENT_API_SUBDIR\"\nfi\n\ncd \"$SITE_OUTPUT_DIR\"\nSITE_ARCHIVE=\"$SITE_OUTPUT_DIR/website_archive.zip\"\nzip -rq \"$SITE_ARCHIVE\" $SITE_SUBDIRS\n\nset +x\necho \"Generated web site at $SITE_OUTPUT_DIR\"\necho \"Docs zip generated at $SITE_ARCHIVE\"\necho \"To view live site locally, run: (cd $SITE_OUTPUT_DIR && ./site_tool jekyll serve)\"\n", "num_lines": 147}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nprepend_lines() {\n  tail --lines=+2 $1 | perl -p -e \"s,^,$2,g;\"\n}\n\nprintf \"dist\\tsys\\tworkload\\ttime\\ttput\\n\"\nfor dist in zipfian uniform ; do\n  for sys in hbase kudu ; do\n    prepend_lines $dist-$sys/load-100M.log.tsv \"${dist}\\t${sys}\\tload\\t\"\n    prepend_lines $dist-$sys/run-workloada.log.tsv \"${dist}\\t${sys}\\ta\\t\"\n    prepend_lines $dist-$sys/run-workloadb.log.tsv \"${dist}\\t${sys}\\tb\\t\"\n    prepend_lines $dist-$sys/run-workloadc.log.tsv \"${dist}\\t${sys}\\tc\\t\"\n    prepend_lines $dist-$sys/run-workloadd.log.tsv \"latest\\t${sys}\\td\\t\"\n  done\ndone\n", "num_lines": 34}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nEXPORTER=\"com.yahoo.ycsb.measurements.exporter.JSONArrayMeasurementsExporter\"\nCOMMON_FLAGS=\"-p recordcount=100000000 -p columnfamily=family -cp /etc/hbase/conf -p exporter=$EXPORTER -p table=ycsb_100m\"\nOUT_DIR=uniform-hbase\n\nmkdir -p $OUT_DIR\nif true ; then\n\t./bin/ycsb load hbase10 $COMMON_FLAGS  -p exportfile=$OUT_DIR/load.json -p clientbuffering=true \\\n\t  -P workloads/workloada -p recordcount=100000000 -threads 16 -s 2>&1 | tee $OUT_DIR/load-100M.log\nfi\nfor x in a b c d ; do\n  dist_param=\n  if [ \"$x\" != \"d\" ]; then\n    dist_param=\"-p requestdistribution=uniform\"\n  fi\n  ./bin/ycsb run hbase10 -P workloads/workload$x -p recordcount=100000000 -p operationcount=10000000 \\\n      $COMMON_FLAGS -p exportfile=$OUT_DIR/$x.json \\\n      $dist_param \\\n      -threads 64 -s 2>&1 | tee $OUT_DIR/run-workload$x.log\ndone\n\n", "num_lines": 40}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nEXPORTER=\"com.yahoo.ycsb.measurements.exporter.JSONArrayMeasurementsExporter\"\nCOMMON_FLAGS=\"-p recordcount=100000000 -p exporter=$EXPORTER -p table_name=ycsb_100m -p masterQuorum=a1216\"\nOUT_DIR=uniform-kudu\n\nmkdir -p $OUT_DIR\nif true ; then\n\t./bin/ycsb load kudu $COMMON_FLAGS  -p exportfile=$OUT_DIR/load.json -p sync_ops=false \\\n\t  -p pre_split_num_tablets=100 \\\n\t  -P workloads/workloada -p recordcount=100000000 -threads 16 -s 2>&1 | tee $OUT_DIR/load-100M.log\nfi\nfor x in a b c d ; do\n  dist_param=\n  if [ \"$x\" != \"d\" ]; then\n    dist_param=\"-p requestdistribution=uniform\"\n  fi\n  ./bin/ycsb run kudu -P workloads/workload$x -p recordcount=100000000 -p operationcount=10000000 -p sync_ops=true \\\n      $COMMON_FLAGS -p exportfile=$OUT_DIR/$x.json \\\n      $dist_param \\\n      -threads 64 -s 2>&1 | tee $OUT_DIR/run-workload$x.log\ndone\n\n", "num_lines": 41}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nEXPORTER=\"com.yahoo.ycsb.measurements.exporter.JSONArrayMeasurementsExporter\"\nCOMMON_FLAGS=\"-p recordcount=100000000 -p columnfamily=family -cp /etc/hbase/conf -p exporter=$EXPORTER -p table=ycsb_100m\"\nOUT_DIR=zipfian-hbase\n\nmkdir -p $OUT_DIR\nif true ; then\n\t./bin/ycsb load hbase10 $COMMON_FLAGS  -p exportfile=$OUT_DIR/load.json -p clientbuffering=true \\\n\t  -P workloads/workloada -p recordcount=100000000 -threads 16 -s 2>&1 | tee $OUT_DIR/load-100M.log\nfi\nfor x in a b c d ; do\n  dist_param=\n  if [ \"$x\" != \"d\" ]; then\n    dist_param=\"-p requestdistribution=zipfian\"\n  fi\n  ./bin/ycsb run hbase10 -P workloads/workload$x -p recordcount=100000000 -p operationcount=10000000 \\\n      $COMMON_FLAGS -p exportfile=$OUT_DIR/$x.json \\\n      $dist_param \\\n      -threads 64 -s 2>&1 | tee $OUT_DIR/run-workload$x.log\ndone\n\n", "num_lines": 40}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nEXPORTER=\"com.yahoo.ycsb.measurements.exporter.JSONArrayMeasurementsExporter\"\nCOMMON_FLAGS=\"-p recordcount=100000000 -p exporter=$EXPORTER -p table_name=ycsb_100m -p masterQuorum=a1216\"\nOUT_DIR=zipfian-kudu\n\nmkdir -p $OUT_DIR\nif true ; then\n\t./bin/ycsb load kudu $COMMON_FLAGS  -p exportfile=$OUT_DIR/load.json -p sync_ops=false \\\n\t  -p pre_split_num_tablets=100 \\\n\t  -P workloads/workloada -p recordcount=100000000 -threads 16 -s 2>&1 | tee $OUT_DIR/load-100M.log\nfi\nfor x in a b c d ; do\n  dist_param=\n  if [ \"$x\" != \"d\" ]; then\n    dist_param=\"-p requestdistribution=zipfian\"\n  fi\n  ./bin/ycsb run kudu -P workloads/workload$x -p recordcount=100000000 -p operationcount=10000000 -p sync_ops=true \\\n      $COMMON_FLAGS -p exportfile=$OUT_DIR/$x.json \\\n      $dist_param \\\n      -threads 64 -s 2>&1 | tee $OUT_DIR/run-workload$x.log\ndone\n\n", "num_lines": 41}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# This script tests for KUDU-1508 in the local kernel's implementation of ext4.\n# To use it, you must compile hole_punch_range.c and make it available in the\n# current working directory.\n#\n# This script must either be run as root, or as a user with sudo.\n\n# Configurable options.\nBLOCK_DEVICE_FILE=block\nMOUNT_DIR=mnt\nTEST_FILE=test\nBLOCK_SIZES=\"1024 2048 4096\"\n\n# Run a command given in the first argument.\n#\n# If the second argument is set and the command fails, the exit code is\n# returned and the command output is squelched.\n#\n# If the second argument is unset and the command fails, the command output is\n# emitted and the script exits.\nfunction run() {\n  local CMD=\"$1\"\n  local FAIL_OK=\"$2\"\n  local OUT RETVAL\n\n  OUT=$($CMD 2>&1)\n  RETVAL=$?\n  if [ $RETVAL -ne 0 ]; then\n    if [ -n \"$FAIL_OK\" ]; then\n      return $RETVAL\n    fi\n\n    echo \"Command failed: $CMD\"\n    echo \"Result: $OUT\"\n    exit $RETVAL\n  fi\n}\n\n# Run an iteration of the test in a local test-only filesystem.\n#\n# Returns whether the filesystem was corrupted.\nfunction run_test() {\n  local BLOCK_SIZE=$1\n  local BLOCK_NUM=$2\n\n  local FILESYSTEM_SIZE=$(($BLOCK_SIZE * $BLOCK_NUM * 4))\n  local TEST_PATH=$MOUNT_DIR/$TEST_FILE\n  local FSCK_RESULT\n  local INTERIOR_NODE_LAST_BLOCK\n\n  # Clean up in preparation.\n  run \"sudo umount $MOUNT_DIR\" fail_ok\n  run \"mkdir -p $MOUNT_DIR\"\n  run \"rm -f $BLOCK_DEVICE_FILE\"\n\n  # Create the test filesystem and file.\n  #\n  # Note that 'fallocate --length <bytes>' doesn't appear to be recognized on\n  # el6.6, despite what the help says.\n  #\n  # The 'sync' at the end speeds up subsequent hole punching.\n  run \"fallocate -l $FILESYSTEM_SIZE $BLOCK_DEVICE_FILE\"\n  run \"mkfs -F -t ext4 -b $BLOCK_SIZE $BLOCK_DEVICE_FILE\"\n  run \"sudo mount -o loop $BLOCK_DEVICE_FILE $MOUNT_DIR\"\n  run \"sudo chown $EUID $MOUNT_DIR\"\n  run \"dd if=/dev/zero of=$TEST_PATH conv=notrunc bs=$BLOCK_SIZE count=$BLOCK_NUM\"\n  run \"sync\"\n\n  # Maximize the number of extents in the file by punching holes in every other\n  # block.\n  #\n  # The 'sync' at the end makes the extent tree visible to debugfs.\n  run \"./hole_punch_range $TEST_PATH 0 $BLOCK_SIZE 2\"\n  run \"sync\"\n\n  # Determine the block number of the last block in the first level 1 interior\n  # node in the file's extent tree.\n  while read LINE; do\n    # Find the node. Its debugfs line will look something like this:\n    #\n    #  1/ 2   1/340      1 -    680 163969             680\n    #\n    # The last number in the line is the number of blocks pointed to by the\n    # node, and since we're looking at the first level 1 interior node, it's\n    # also the last block number pointed to by that node.\n    if echo $LINE | grep -q \"[[:space:]]*1/[[:space:]]*[[:digit:]]*[[:space:]]*1/\"; then\n      INTERIOR_NODE_LAST_BLOCK=$(echo $LINE | awk '{ print $NF }')\n      break\n    fi\n  done < <(debugfs -R \"dump_extents -n $TEST_FILE\" $BLOCK_DEVICE_FILE 2> /dev/null)\n\n  # If we can't find the last block number, the file does not have an extent\n  # tree with at least two interior levels, and the subsequent corruption test\n  # can be skipped.\n  if [ -n \"$INTERIOR_NODE_LAST_BLOCK\" ]; then\n    # Try to corrupt the filesystem by punching out all of the remaining blocks\n    # belonging to this interior node.\n    #\n    # If the filesystem is vulnerable to KUDU-1508, it'll fail to update the\n    # interior node's parent, corrupting the filesystem until the next fsck.\n    run \"./hole_punch_range $TEST_PATH 1 $INTERIOR_NODE_LAST_BLOCK 2\"\n  fi\n\n  run \"sudo umount $MOUNT_DIR\"\n\n  # Test the filesystem for corruption and return the result.\n  run \"fsck.ext4 $BLOCK_DEVICE_FILE -f -n\" fail_ok\n  FSCK_RESULT=$?\n\n  # Clean up after the test.\n  run \"rmdir $MOUNT_DIR\"\n  run \"rm -f $BLOCK_DEVICE_FILE\"\n\n  return $FSCK_RESULT\n}\n\n# Run the test with known bad parameters to see if this kernel is worth testing.\nrun_test 4096 $((16 * 1024))\nif [[ $? -eq 0 ]]; then\n  echo \"This kernel is not vulnerable to KUDU-1508, skipping test\"\n  exit 0\nfi\n\necho \"This kernel is vulnerable to KUDU-1508, finding per-block size upper bounds\"\n\n# Now figure out, for each block size, what the max number of blocks is.\nfor BLOCK_SIZE in $BLOCK_SIZES; do\n  MIN=0\n  MAX=$((1024 * 16))\n  CUR=\n  echo \"Block size $BLOCK_SIZE: searching for block number upper bound (MIN=$MIN,MAX=$MAX)\"\n  while [[ $MIN -lt $MAX ]] ; do\n    CUR=$((($MAX + $MIN) / 2))\n    run_test $BLOCK_SIZE $CUR\n    if [[ $? -eq 0 ]]; then\n      echo \"Block size $BLOCK_SIZE: $CUR good (MIN=$MIN,MAX=$MAX)\"\n      MIN=$(($CUR + 1))\n    else\n      echo \"Block size $BLOCK_SIZE: $CUR bad (MIN=$MIN,MAX=$MAX)\"\n      MAX=$(($CUR - 1))\n    fi\n  done\n\n  echo \"Block size $BLOCK_SIZE: upper bound found at $CUR\"\ndone\n", "num_lines": 164}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -xe\n########################################################################\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Run and compare benchmarks.\n#\n# Allows for running comparisons either locally or as part of a\n# Jenkins job which integrates with a historical stats DB.\n# Run this script with -help for usage information.\n########################################################################\n\n# Fail the job if any part fails, even when piping through 'tee', etc.\nset -o pipefail\n\n################################################################\n# Constants\n################################################################\n\nMODE_JENKINS=\"jenkins\"\nMODE_LOCAL=\"local\"\n\nLOCAL_STATS_BASE=\"local-stats\"\n\nNUM_MT_TABLET_TESTS=5\nMT_TABLET_TEST=mt-tablet-test\nRPC_BENCH_TEST=RpcBenchBenchmark\nCBTREE_TEST=cbtree-test\nBLOOM_TEST=BloomfileBenchmark\nMT_BLOOM_TEST=MultithreadedBloomfileBenchmark\nWIRE_PROTOCOL_TEST=WireProtocolBenchmark\nCOMPACT_MERGE_BENCH=CompactBenchMerge\nWITH_OVERLAP=Overlap\nNO_OVERLAP=NoOverlap\n\nMEMROWSET_BENCH=MemRowSetBenchmark\nTS_INSERT_LATENCY=TabletServerInsertLatency\nTS_8THREAD_BENCH=TabletServer8Threads\nINSERT=Insert\nSCAN_NONE_COMMITTED=ScanNoneCommitted\nSCAN_ALL_COMMITTED=ScanAllCommitted\n\nFS_SCANINSERT_MRS=FullStackScanInsertMRSOnly\nFS_SCANINSERT_DISK=FullStackScanInsertWithDisk\n\nDENSE_NODE_ITEST=DenseNodeItest\n\nLOG_DIR_NAME=build/latest/bench-logs\nOUT_DIR_NAME=build/latest/bench-out\nHTML_FILE=\"benchmarks.html\"\n\n# Most tests will run this many times.\nNUM_SAMPLES=${NUM_SAMPLES:-10}\n\n################################################################\n# Global variables\n################################################################\n\nBENCHMARK_MODE=$MODE_JENKINS # we default to \"jenkins mode\"\nBASE_DIR=$(pwd)\nLOGDIR=\"\"\nOUTDIR=\"\"\n\n################################################################\n# Functions\n################################################################\n\nusage_and_die() {\n  set +x\n  echo \"Usage: $0 [-local [git-hash-1 [git-hash-2 ...]]]\"\n  echo \"       When -local is specified, perf of 1 or more git hashes are plotted.\"\n  echo \"       Otherwise, the script is run in 'Jenkins' mode and expects the\"\n  echo \"       usual Jenkins environment variables to be defined, such as\"\n  echo \"       BUILD_NUMBER and JOB_NAME.\"\n  exit 1\n}\n\nensure_cpu_scaling() {\n  $BASE_DIR/src/kudu/scripts/ensure_cpu_scaling.sh \"$@\"\n}\n\nrecord_result() {\n  local BUILD_IDENTIFIER=$1\n  local TEST_NAME=$2\n  local ITER=$3\n  local VALUE=$4\n  if [ $BENCHMARK_MODE = $MODE_JENKINS ]; then\n    python write-jobs-stats-to-mysql.py $JOB_NAME $BUILD_IDENTIFIER $TEST_NAME $ITER $VALUE\n  else\n    local STATS_FILE=\"$OUTDIR/$LOCAL_STATS_BASE-$TEST_NAME.tsv\"\n    # Note: literal tabs in below string.\n    echo \"${TEST_NAME}\t${VALUE}\t${BUILD_IDENTIFIER}\" >> \"$STATS_FILE\"\n  fi\n}\n\nload_stats() {\n  local TEST_NAME=\"$1\"\n  if [ \"$BENCHMARK_MODE\" = \"$MODE_JENKINS\" ]; then\n    # Get last 4 weeks of stats\n    python get-job-stats-from-mysql.py $TEST_NAME 28\n  else\n    # Convert MySQL wildcards to shell wildcards.\n    local TEST_NAME=$(echo $TEST_NAME | perl -pe 's/%/*/g')\n    local STATS_FILES=$(ls $OUTDIR/$LOCAL_STATS_BASE-$TEST_NAME.tsv)\n    # Note: literal tabs in below string.\n    echo \"workload\truntime\tbuild_number\"\n    for f in $STATS_FILES; do\n      cat $f\n    done\n  fi\n}\n\nwrite_img_plot() {\n  local INPUT_FILE=$1\n  local TEST_NAME=$2\n  # Rscript fails when there's only a header, so just skip\n  if [ `wc -l $INPUT_FILE | cut -d ' ' -f1` -gt 1 ]; then\n    Rscript jobs_runtime.R $INPUT_FILE $TEST_NAME\n  fi\n}\n\nwrite_mttablet_img_plots() {\n  local INPUT_FILE=$1\n  local TEST_NAME=$2\n  xvfb-run Rscript mt-tablet-test-graph.R $INPUT_FILE $TEST_NAME\n}\n\nbuild_kudu() {\n  # PATH=<toolchain_stuff>:$PATH\n  export TOOLCHAIN=/mnt/toolchain/toolchain.sh\n  if [ -f \"$TOOLCHAIN\" ]; then\n    source $TOOLCHAIN\n  fi\n\n  # Build thirdparty\n  $BASE_DIR/build-support/enable_devtoolset.sh thirdparty/build-if-necessary.sh\n\n  # PATH=<thirdparty_stuff>:<toolchain_stuff>:$PATH\n  THIRDPARTY_BIN=$BASE_DIR/thirdparty/installed/common/bin\n  export PPROF_PATH=$THIRDPARTY_BIN/pprof\n\n  BUILD_TYPE=release\n\n  # Build Kudu\n  mkdir -p build/$BUILD_TYPE\n  pushd build/$BUILD_TYPE\n  rm -rf CMakeCache.txt CMakeFiles/\n\n  $BASE_DIR/build-support/enable_devtoolset.sh $THIRDPARTY_BIN/cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} ../..\n\n  # clean up before we run\n  rm -Rf /tmp/kudutpch1-$UID\n  mkdir -p /tmp/kudutpch1-$UID\n\n  NUM_PROCS=$(cat /proc/cpuinfo | grep processor | wc -l)\n  make -j${NUM_PROCS} 2>&1 | tee build.log\n  popd\n\n}\n\nrun_benchmarks() {\n  # Create output directories if needed.\n  mkdir -p \"$LOGDIR\"\n  mkdir -p \"$OUTDIR\"\n\n  # run all of the variations of mt-tablet-test\n  ./build/latest/bin/mt-tablet-test \\\n    --gtest_filter=\\*DoTestAllAtOnce\\* \\\n    --num_counter_threads=0 \\\n    --tablet_test_flush_threshold_mb=32 \\\n    --num_slowreader_threads=0 \\\n    --flusher_backoff=1.0 \\\n    --flusher_initial_frequency_ms=1000 \\\n    --inserts_per_thread=1000000 \\\n    &> $LOGDIR/${MT_TABLET_TEST}.log\n\n  # run rpc-bench test 5 times. 10 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES); do\n    KUDU_ALLOW_SLOW_TESTS=true ./build/latest/bin/rpc-bench \\\n      --gtest_filter=*BenchmarkCalls &> $LOGDIR/$RPC_BENCH_TEST$i.log\n  done\n\n  # run cbtree-test 5 times. 20 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES); do\n    KUDU_ALLOW_SLOW_TESTS=true ./build/latest/bin/cbtree-test \\\n      --gtest_filter=TestCBTree.TestScanPerformance &> $LOGDIR/${CBTREE_TEST}$i.log\n  done\n\n  # run bloomfile-test 5 times. ~3.3 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES); do\n    ./build/latest/bin/bloomfile-test --benchmark_queries=10000000 --bloom_size_bytes=32768 \\\n      --n_keys=100000 --gtest_filter=*Benchmark &> $LOGDIR/$BLOOM_TEST$i.log\n  done\n\n  # run mt-bloomfile-test 5 times. 20-30 seconds per run.\n  # We use 150M keys so the total bloom space is >150MB, and then\n  # set the cache capacity to be only 100M to ensure that the cache\n  # churns a lot.\n  for i in $(seq 1 $NUM_SAMPLES); do\n    ./build/latest/bin/mt-bloomfile-test --benchmark_queries=2000000 --bloom_size_bytes=4096 \\\n      --n_keys=150000000 --block_cache_capacity_mb=100 &> $LOGDIR/$MT_BLOOM_TEST$i.log\n  done\n\n  # run wire_protocol-test 5 times. 6 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES); do\n    KUDU_ALLOW_SLOW_TESTS=true ./build/latest/bin/wire_protocol-test --gtest_filter=*Benchmark \\\n      &> $LOGDIR/$WIRE_PROTOCOL_TEST$i.log\n  done\n\n  # run compaction-test 5 times, 6 seconds each\n  for i in $(seq 1 $NUM_SAMPLES); do\n    KUDU_ALLOW_SLOW_TESTS=true ./build/latest/bin/compaction-test \\\n      --gtest_filter=TestCompaction.BenchmarkMerge* &> $LOGDIR/${COMPACT_MERGE_BENCH}$i.log\n  done\n\n  # run memrowset benchmark 5 times, ~10 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    ./build/latest/bin/memrowset-test --roundtrip_num_rows=10000000 \\\n        --gtest_filter=\\*InsertCount\\* &> $LOGDIR/${MEMROWSET_BENCH}$i.log\n  done\n\n  # Run single-threaded TS insert latency benchmark, 5-6 seconds per run\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    KUDU_ALLOW_SLOW_TESTS=true ./build/latest/bin/tablet_server-test \\\n      --gtest_filter=*MicroBench* \\\n      --single_threaded_insert_latency_bench_warmup_rows=1000 \\\n      --single_threaded_insert_latency_bench_insert_rows=10000 &> $LOGDIR/${TS_INSERT_LATENCY}$i.log\n  done\n\n  # Run multi-threaded TS insert benchmark\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    KUDU_ALLOW_SLOW_TESTS=1 build/latest/bin/tablet_server-stress-test \\\n      --num_inserts_per_thread=30000 -runtime_secs=0 &> $LOGDIR/${TS_8THREAD_BENCH}$i.log\n  done\n\n  # Run full stack scan/insert test using MRS only, ~26s each\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    ./build/latest/bin/full_stack-insert-scan-test \\\n      --gtest_filter=FullStackInsertScanTest.MRSOnlyStressTest \\\n      --concurrent_inserts=50 \\\n      --inserts_per_client=200000 \\\n      --rows_per_batch=10000 \\\n      &> $LOGDIR/${FS_SCANINSERT_MRS}$i.log\n  done\n\n  # Run full stack scan/insert test with disk, ~50s each\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    ./build/latest/bin/full_stack-insert-scan-test \\\n      --gtest_filter=FullStackInsertScanTest.WithDiskStressTest \\\n      --concurrent_inserts=50 \\\n      --inserts_per_client=200000 \\\n      --rows_per_batch=10000 \\\n      &> $LOGDIR/${FS_SCANINSERT_DISK}$i.log\n  done\n\n  # Run dense storage node test, ~150s each.\n  #\n  # Needs to run as root for measure_startup_drop_caches.\n  for i in $(seq 1 $NUM_SAMPLES) ; do\n    sudo ./build/latest/bin/dense_node-itest \\\n      --num_seconds=60 \\\n      --num_tablets=1000 \\\n      --measure_startup_sync \\\n      --measure_startup_drop_caches \\\n      --measure_startup_wait_for_bootstrap \\\n      &> $LOGDIR/${DENSE_NODE_ITEST}$i.log\n  done\n}\n\nparse_and_record_all_results() {\n  local BUILD_IDENTIFIER=\"$1\"\n\n  if [ -z \"$BUILD_IDENTIFIER\" ]; then\n    echo \"ERROR: BUILD_IDENTIFIER not defined\"\n    exit 1\n  fi\n\n  pushd src\n  pushd kudu\n  pushd scripts\n\n  # parse the number of ms out of \"[       OK ] MultiThreadedTabletTest/5.DoTestAllAtOnce (14966 ms)\"\n  local MT_TABLET_TEST_TIMINGS=\"${MT_TABLET_TEST}-timings\"\n  grep OK $LOGDIR/${MT_TABLET_TEST}.log | cut -d \"(\" -f2 | cut -d \")\" -f1 | cut -d \" \" -f1 \\\n    > $LOGDIR/${MT_TABLET_TEST_TIMINGS}.txt\n\n  # The tests go from 0 to NUM_MT_TABLET_TEST, but files start at line one so we add +1 to the line number.\n  # Then using the timing we found, we multiply it by 1000 to gets seconds in float, then send it to MySQL\n  for i in $(seq 0 $NUM_MT_TABLET_TESTS); do\n    linenumber=$[ $i + 1 ]\n    timing=`sed -n \"${linenumber}p\" $LOGDIR/${MT_TABLET_TEST_TIMINGS}.txt`\n    record_result $BUILD_IDENTIFIER MultiThreadedTabletTest_$i 1 `echo $timing / 1000 | bc -l`\n  done\n\n  # parse out the real time from: \"Time spent Insert 10000000 keys: real 16.438s user 16.164s  sys 0.229s\"\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"Time spent Insert\" $LOGDIR/${CBTREE_TEST}$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ConcurrentBTreeScanInsert $i $real\n  done\n\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"not frozen\" $LOGDIR/${CBTREE_TEST}$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ConcurrentBTreeScanNotFrozen $i $real\n  done\n\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"(frozen\" $LOGDIR/${CBTREE_TEST}$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ConcurrentBTreeScanFrozen $i $real\n  done\n\n  # parse out the real time from \"Time spent with overlap: real 0.557s user 0.546s sys 0.010s\"\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"with overlap\" $LOGDIR/${COMPACT_MERGE_BENCH}$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${COMPACT_MERGE_BENCH}${WITH_OVERLAP} $i $real\n  done\n\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"without overlap\" $LOGDIR/${COMPACT_MERGE_BENCH}$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${COMPACT_MERGE_BENCH}${NO_OVERLAP} $i $real\n  done\n\n  # parse out time from MRS benchmarks\n  for i in $(seq 1 $NUM_SAMPLES); do\n    log=$LOGDIR/${MEMROWSET_BENCH}$i.log\n    real=`grep \"Time spent Inserting\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${MEMROWSET_BENCH}${INSERT} $i $real\n    real=`grep \"Time spent Scanning rows where none\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${MEMROWSET_BENCH}${SCAN_NONE_COMMITTED} $i $real\n    real=`grep \"Time spent Scanning rows where all\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${MEMROWSET_BENCH}${SCAN_ALL_COMMITTED} $i $real\n  done\n\n  # Parse out the real time from: \"Time spent Running 10000000 queries: real 3.281s  user 3.273s sys 0.000s\"\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"Time spent Running\" $LOGDIR/$BLOOM_TEST$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER $BLOOM_TEST $i $real\n  done\n\n  # Parse out the real time from: \"Time spent Running 2000000 queries: real 28.193s user 26.903s sys 1.032s\"\n  # Many threads output their value, we keep the last;\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"Time spent Running\" $LOGDIR/$MT_BLOOM_TEST$i.log | tail -n1 | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER $MT_BLOOM_TEST $i $real\n  done\n\n  # Parse out the real time from: \"Time spent Converting to PB: real 5.962s  user 5.918s sys 0.025s\"\n  for i in $(seq 1 $NUM_SAMPLES); do\n    real=`grep \"Time spent Converting\" $LOGDIR/$WIRE_PROTOCOL_TEST$i.log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER $WIRE_PROTOCOL_TEST $i $real\n  done\n\n  # parse the rate out of: \"I1009 15:00:30.023576 27043 rpc-bench.cc:108] Reqs/sec:         84404.4\"\n  for i in $(seq 1 $NUM_SAMPLES); do\n    rate=`grep Reqs $LOGDIR/$RPC_BENCH_TEST$i.log | cut -d \":\" -f 5 | tr -d ' '`\n    record_result $BUILD_IDENTIFIER $RPC_BENCH_TEST $i $rate\n  done\n\n  # parse latency numbers from single-threaded tserver benchmark\n  for i in $(seq 1 $NUM_SAMPLES); do\n    for metric in min mean percentile_95 percentile_99 percentile_99_9 ; do\n      val=$(grep \"\\\"$metric\\\": \" $LOGDIR/${TS_INSERT_LATENCY}$i.log | awk '{print $2}' | sed -e 's/,//')\n      record_result $BUILD_IDENTIFIER ${TS_INSERT_LATENCY}_$metric $i $val\n    done\n  done\n\n  # parse latency and throughput numbers from multi-threaded tserver benchmark\n  for i in $(seq 1 $NUM_SAMPLES); do\n    local log=$LOGDIR/${TS_8THREAD_BENCH}$i.log\n    for metric in min mean percentile_95 percentile_99 percentile_99_9 ; do\n      val=$(grep \"\\\"$metric\\\": \" $log | awk '{print $2}' | sed -e 's/,//')\n      record_result $BUILD_IDENTIFIER ${TS_8THREAD_BENCH}_${metric}_latency $i $val\n    done\n    rate=$(grep -o 'Throughput.*' $log | awk '{print $2}')\n    record_result $BUILD_IDENTIFIER ${TS_8THREAD_BENCH}_throughput_wall $i $rate\n    rate=$(grep -o 'CPU efficiency.*' $log | awk '{print $3}')\n    record_result $BUILD_IDENTIFIER ${TS_8THREAD_BENCH}_throughput_cpu $i $rate\n  done\n\n  # parse scan timings for scans and inserts with MRS only\n  for i in $(seq 1 $NUM_SAMPLES); do\n    local log=$LOGDIR/${FS_SCANINSERT_MRS}$i.log\n    insert=`grep \"Time spent concurrent inserts\" $log | ./parse_real_out.sh`\n    scan_full=`grep \"Time spent full schema scan\" $log | ./parse_real_out.sh`\n    scan_str=`grep \"Time spent String projection\" $log | ./parse_real_out.sh`\n    scan_int32=`grep \"Time spent Int32 projection\" $log | ./parse_real_out.sh`\n    scan_int64=`grep \"Time spent Int64 projection\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_MRS}_insert $i $insert\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_MRS}_scan_full $i $scan_full\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_MRS}_scan_str $i $scan_str\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_MRS}_scan_int32 $i $scan_int32\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_MRS}_scan_int64 $i $scan_int64\n  done\n\n  # parse scan timings for scans and inserts with disk\n  for i in $(seq 1 $NUM_SAMPLES); do\n    local log=$LOGDIR/${FS_SCANINSERT_DISK}$i.log\n    insert=`grep \"Time spent concurrent inserts\" $log | ./parse_real_out.sh`\n    scan_full=`grep \"Time spent full schema scan\" $log | ./parse_real_out.sh`\n    scan_str=`grep \"Time spent String projection\" $log | ./parse_real_out.sh`\n    scan_int32=`grep \"Time spent Int32 projection\" $log | ./parse_real_out.sh`\n    scan_int64=`grep \"Time spent Int64 projection\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_DISK}_insert $i $insert\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_DISK}_scan_full $i $scan_full\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_DISK}_scan_str $i $scan_str\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_DISK}_scan_int32 $i $scan_int32\n    record_result $BUILD_IDENTIFIER ${FS_SCANINSERT_DISK}_scan_int64 $i $scan_int64\n  done\n\n  # Parse timings and thread count\n  for i in $(seq 1 $NUM_SAMPLES); do\n    local log=$LOGDIR/${DENSE_NODE_ITEST}$i.log\n    num_threads=`grep threads_running $log | cut -d \":\" -f 5 | tr -d ' '`\n    num_blocks=`grep log_block_manager_blocks_under_management $log | cut -d \":\" -f 5 | tr -d ' '`\n    num_bytes=`grep log_block_manager_bytes_under_management $log | cut -d \":\" -f 5 | tr -d ' '`\n    num_containers=`grep log_block_manager_containers $log | cut -d \":\" -f 5 | tr -d ' '`\n    num_full_containers=`grep log_block_manager_full_containers $log | cut -d \":\" -f 5 | tr -d ' '`\n    time_restarting_tserver=`grep \"Time spent restarting tserver\" $log | ./parse_real_out.sh`\n    time_bootstrapping_tablets=`grep \"Time spent bootstrapping tablets\" $log | ./parse_real_out.sh`\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_num_threads $i $num_threads\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_num_blocks $i $num_blocks\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_num_bytes $i $num_bytes\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_num_containers $i $num_containers\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_num_full_containers $i $num_full_containers\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_time_restarting_tserver $i $time_restarting_tserver\n    record_result $BUILD_IDENTIFIER ${DENSE_NODE_ITEST}_time_bootstrapping_tablets $i $time_bootstrapping_tablets\n  done\n\n  popd\n  popd\n  popd\n}\n\ngenerate_ycsb_plots() {\n  local WORKLOAD=$1\n  local PHASE=$2\n  METRIC_NAME=ycsb-$PHASE-$WORKLOAD\n\n  # first plot the overall stats for that phase\n  OVERALL_FILENAME=$METRIC_NAME-OVERALL\n  load_stats $OVERALL_FILENAME-runtime_ms > $OUTDIR/$OVERALL_FILENAME-runtime_ms.tsv\n  write_img_plot $OUTDIR/$OVERALL_FILENAME-runtime_ms.tsv $OVERALL_FILENAME-runtime_ms\n  load_stats $OVERALL_FILENAME-throughput_ops_sec > $OUTDIR/$OVERALL_FILENAME-throughput_ops_sec.tsv\n  write_img_plot $OUTDIR/$OVERALL_FILENAME-throughput_ops_sec.tsv $OVERALL_FILENAME-throughput_ops_sec\n\n  # now plot the individual operations\n  OPS=\"INSERT UPDATE READ\"\n\n  for op in $OPS; do\n    OP_FILENAME=$METRIC_NAME-$op\n    load_stats $OP_FILENAME-average_latency_us > $OUTDIR/$OP_FILENAME-average_latency_us.tsv\n    write_img_plot $OUTDIR/$OP_FILENAME-average_latency_us.tsv $OP_FILENAME-average_latency_us\n\n    load_stats $OP_FILENAME-95th_latency_ms > $OUTDIR/$OP_FILENAME-95th_latency_ms.tsv\n    write_img_plot $OUTDIR/$OP_FILENAME-95th_latency_ms.tsv $OP_FILENAME-95th_latency_ms\n\n    load_stats $OP_FILENAME-99th_latency_ms > $OUTDIR/$OP_FILENAME-99th_latency_ms.tsv\n    write_img_plot $OUTDIR/$OP_FILENAME-99th_latency_ms.tsv $OP_FILENAME-99th_latency_ms\n  done\n}\n\nload_and_generate_plot() {\n  local TEST_NAME=$1\n  local PLOT_NAME=$2\n  load_stats \"$TEST_NAME\" > $OUTDIR/$PLOT_NAME.tsv\n  write_img_plot $OUTDIR/$PLOT_NAME.tsv $PLOT_NAME\n}\n\nload_stats_and_generate_plots() {\n  pushd src\n  pushd kudu\n  pushd scripts\n\n  load_and_generate_plot \"%MultiThreadedTabletTest%\" mt-tablet-test-runtime\n\n  load_and_generate_plot ConcurrentBTreeScanInsert cb-tree-insert\n  load_and_generate_plot ConcurrentBTreeScanNotFrozen cb-ctree-not-frozen\n  load_and_generate_plot ConcurrentBTreeScanFrozen cb-ctree-frozen\n\n  load_and_generate_plot \"${COMPACT_MERGE_BENCH}%\" compact-merge-bench\n\n  load_and_generate_plot \"${MEMROWSET_BENCH}${INSERT}\" memrowset-bench-insert\n  load_and_generate_plot \"${MEMROWSET_BENCH}Scan%\" memrowset-bench-scan\n\n  load_and_generate_plot $BLOOM_TEST bloom-test\n  load_and_generate_plot $MT_BLOOM_TEST mt-bloom-test\n\n  load_and_generate_plot $WIRE_PROTOCOL_TEST wire-protocol-test\n\n  load_and_generate_plot $RPC_BENCH_TEST rpc-bench-test\n\n  load_and_generate_plot \"${TS_INSERT_LATENCY}%\" ts-insert-latency\n\n  load_and_generate_plot \"${TS_8THREAD_BENCH}%_latency\" ts-8thread-insert-latency\n  load_and_generate_plot \"${TS_8THREAD_BENCH}%_throughput_%\" ts-8thread-insert-throughput\n\n  load_and_generate_plot \"${FS_SCANINSERT_MRS}%_insert\" fs-mrsonly-insert\n  load_and_generate_plot \"${FS_SCANINSERT_MRS}%_scan%\" fs-mrsonly-scan\n  load_and_generate_plot \"${FS_SCANINSERT_DISK}%_insert\" fs-withdisk-insert\n  load_and_generate_plot \"${FS_SCANINSERT_DISK}%_scan%\" fs-withdisk-scan\n\n  load_and_generate_plot \"${DENSE_NODE_ITEST}_time%\" dense-node-bench-times\n  load_and_generate_plot \"${DENSE_NODE_ITEST}_num%containers%\" dense-node-bench-containers\n  load_and_generate_plot \"${DENSE_NODE_ITEST}_num_blocks%\" dense-node-bench-blocks\n  load_and_generate_plot \"${DENSE_NODE_ITEST}_num_threads%\" dense-node-bench-threads\n  load_and_generate_plot \"${DENSE_NODE_ITEST}_num_bytes%\" dense-node-bench-bytes\n\n  # Generate all the pngs for all the mt-tablet tests\n  for i in $(seq 0 $NUM_MT_TABLET_TESTS); do\n    cat $LOGDIR/${MT_TABLET_TEST}.log | ./graph-metrics.py MultiThreadedTabletTest/$i > $OUTDIR/test$i.tsv\n    # Don't bail on failure (why not?)\n    write_mttablet_img_plots $OUTDIR/test$i.tsv test$i || true\n  done\n\n  if [ \"${BENCHMARK_MODE}\" = \"${MODE_JENKINS}\" ]; then\n    ################################################################\n    # Plot the separately-recorded TPCH and YCSB graphs as well\n    # (only for Jenkins)\n    ################################################################\n\n    # TPC-H 1 runs separately, let's just get those graphs\n    load_and_generate_plot query_1_1gb tpch1-query\n    load_and_generate_plot insert_1gb tpch1-insert\n\n    # YCSB which runs the 5nodes_workload on a cluster\n    # First we process the loading phase\n    generate_ycsb_plots 5nodes_workload load\n\n    # Then the running phase\n    generate_ycsb_plots 5nodes_workload run\n  fi\n\n  # Move all the pngs to OUT_DIR.\n  mv *.png $OUTDIR/\n\n  # Generate an HTML file aggregating the PNGs.\n  # Mostly for local usage, but somewhat useful to check the Jenkins runs too.\n  pushd $OUTDIR/\n  PNGS=$(ls *.png)\n  echo -n > \"$OUTDIR/$HTML_FILE\"\n  echo \"<title>Kudu Benchmarks</title>\" >> \"$OUTDIR/$HTML_FILE\"\n  echo \"<h1 align=center>Kudu Benchmarks</h1>\" >> \"$OUTDIR/$HTML_FILE\"\n  for png in $PNGS; do\n    echo \"<img src=$png><br>\" >> \"$OUTDIR/$HTML_FILE\"\n  done\n  popd\n\n  popd\n  popd\n  popd\n}\n\nbuild_run_record() {\n  local BUILD_IDENTIFIER=$1\n  build_kudu\n  run_benchmarks\n  parse_and_record_all_results \"$BUILD_IDENTIFIER\"\n}\n\ngit_checkout() {\n  local GIT_HASH=$1\n  git checkout $GIT_HASH\n}\n\nrun() {\n\n  # Parse command-line options.\n  if [ -n \"$1\" ]; then\n    [ \"$1\" = \"-local\" ] || usage_and_die\n    shift\n\n    BENCHMARK_MODE=$MODE_LOCAL\n\n    # If no hashes are provided, run against the current HEAD.\n    if [ -z \"$1\" ]; then\n      build_run_record \"working_tree\"\n    else\n      # Convert the passed-in git refs into their hashes.\n      # This allows you to use \"HEAD~3 HEAD\" as arguments\n      # and end up with those being evaluated with regard to\n      # the _current_ branch, instead of evaluating the second\n      # \"HEAD\" after checking out the first.\n      local ref\n      local hashes\n      for ref in \"$@\" ; do\n        hashes=\"$hashes $(git rev-parse \"$ref\")\"\n      done\n      set $hashes\n      while [ -n \"$1\" ]; do\n        local GIT_HASH=\"$1\"\n        shift\n        git_checkout \"$GIT_HASH\"\n        build_run_record \"$GIT_HASH\"\n      done\n    fi\n\n  else\n    [ -n \"$BUILD_NUMBER\" ] || usage_and_die\n    build_run_record \"$BUILD_NUMBER\"\n  fi\n\n  # The last step is the same for both modes.\n  load_stats_and_generate_plots\n}\n\n################################################################\n# main\n################################################################\n\n# Figure out where we are, store in global variables.\nLOGDIR=\"$BASE_DIR/$LOG_DIR_NAME\"\nOUTDIR=\"$BASE_DIR/$OUT_DIR_NAME\"\n\n# Ensure we are in KUDU_HOME\nif [ ! -f \"$BASE_DIR/LICENSE.txt\" ]; then\n  set +x\n  echo \"Error: must run from top of Kudu source tree\"\n  usage_and_die\nfi\n\n# Set up environment.\nulimit -m $[3000*1000]\nulimit -c unlimited   # gather core dumps\n\n# Set CPU governor, and restore it on exit.\nold_governor=$(ensure_cpu_scaling performance)\nrestore_governor() {\n  ensure_cpu_scaling $old_governor >/dev/null\n}\ntrap restore_governor EXIT\n\n# Kick off the benchmark script.\nrun $*\n\nexit 0\n", "num_lines": 650}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Ensure that the CPU governor is set to a particular governor, outputting\n# the prior governor on stdout.\n#\n# Without this, some of our tests end up having higher variance due to\n# changing CPU speed during the test.\n#\n# Assumes that all CPUs are set to the same governor.\ntarget_governor=$1\nold_governor=$(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor)\nfor cpu_dir in /sys/devices/system/cpu/cpu[0-9]*/ ; do\n    governor_file=$cpu_dir/cpufreq/scaling_governor\n    governor=$(cat $governor_file)\n    if [ \"$governor\" != \"$target_governor\" ]; then\n        >&2 echo \"CPU $cpu_dir not in '$target_governor' mode. Attempting to change\"\n        echo $target_governor | sudo tee $governor_file > /dev/null\n        if [ $? -ne 0 ]; then\n            >&2 echo Could not set $target_governor governor!\n            >&2 echo Perhaps you need passwordless sudo for this user\n            exit 1\n        fi\n    fi\ndone\necho $old_governor\n", "num_lines": 43}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This script is invoked from a Jenkins job to build Kudu C++ components,\n# Kudu Java client, kudu-jepsen, and run kudu-jepsen consistency tests\n# against the freshly built Kudu binaries.\n#\n# The following environment variables may be used to customize the operation:\n#   JAVA8_HOME          Default: /usr/lib/jvm/java-8-openjdk-amd64\n#     Path to the JDK8 installation root.  Expecting to find 'java'\n#     in the 'bin' sub-directory.  Java 8 or higher is required for the\n#     maven-clojure-plugin.\n#\n#   M2_HOME             Default: /usr/share/maven\n#     Path to the maven (3.3.6 and newer is required).\n#\n#   MVN_FLAGS           Default: \"\"\n#     Extra flags which are passed to 'mvn' when building and running Java\n#     tests. This can be useful, for example, to choose a different maven\n#     repository location.\n#\n#   KUDU_MASTER_NODES   Default: \"\"\n#     Set of master nodes for the Kudu cluster to run the Jepsen consistency\n#     test. Those should be the same architecture and OS type as the\n#     Jenkins machine where this build script is run.\n#     NOTE: currently, the Jepsen test can run only at Debian nodes.\n#\n#   KUDU_TSERVER_NODES  Default: \"\"\n#     Set of tablet server nodes for the Kudu cluster to run the Jepsen\n#     consistency test. Those should be the same architecture and OS type\n#     as the Jenkins machine where this build script is run.\n#     NOTE: currently, the Jepsen test can run only at Debian nodes.\n#\n#   SSH_KEY             Default: \"\"\n#     The absolute path to the file containing the private SSH key\n#     for the root user at the master and tablet server nodes\n#     (DB nodes in Jepsen terminology).\n#     NOTE: the key should be in plain (i.e. non-encrypted) format.\n#\n\n#############################################################################\n# Constants\n#############################################################################\n\n# Require Kudu binaries to be statically linked with the Kudu-specific libs:\n# the kudu-jepsen does not distribute Kudu libraries.\nKUDU_LINK=static\n\nSRC_ROOT=$(readlink -f $(dirname $0)/../../..)\nTHIRDPARTY_BIN=$SRC_ROOT/thirdparty/installed/common/bin\nNUM_PROCS=$(getconf _NPROCESSORS_ONLN)\n\n#############################################################################\n# Customizable parameters\n#############################################################################\n\nBUILD_TYPE=${BUILD_TYPE:-debug}\nJAVA8_HOME=${JAVA8_HOME:-/usr/lib/jvm/java-8-openjdk-amd64}\nM2_HOME=${M2_HOME:-/usr/share/maven}\nMVN_FLAGS=${MVN_FLAGS:-}\nKUDU_MASTER_NODES=${KUDU_MASTER_NODES:-}\nKUDU_TSERVER_NODES=${KUDU_TSERVER_NODES:-}\nSSH_KEY=${SSH_KEY:-}\nITER_NUM=${ITER_NUM:-1}\n\n#############################################################################\n# Main\n#############################################################################\n\nset -e\nset -o pipefail\nulimit -c unlimited\n\ncd $SRC_ROOT\n\necho\necho \"Removing logs from prior runs\"\necho \"--------------------------------------------------------------------\"\nrm -rf java/kudu-jepsen/store\n\necho\necho \"Building third-party components\"\necho \"--------------------------------------------------------------------\"\n$SRC_ROOT/build-support/enable_devtoolset.sh \\\n  $SRC_ROOT/thirdparty/build-if-necessary.sh\n\nmkdir -p build/$BUILD_TYPE\npushd build\nln -sf $SRC_ROOT/build/$BUILD_TYPE latest\npushd $BUILD_TYPE\n\necho\necho \"Building Kudu C++ components (no tests)\"\necho \"--------------------------------------------------------------------\"\n$SRC_ROOT/build-support/enable_devtoolset.sh $THIRDPARTY_BIN/cmake \\\n  -DCMAKE_BUILD_TYPE=$BUILD_TYPE \\\n  -DKUDU_LINK=$KUDU_LINK \\\n  -DNO_TESTS=1 \\\n  ../..\nmake -j$NUM_PROCS 2>&1 | tee build.log\n\nexport JAVA_HOME=$JAVA8_HOME\nexport PATH=$JAVA_HOME/bin:$M2_HOME/bin:$PATH\nset -x\n\npushd $SRC_ROOT/java\necho\necho \"Building Kudu Java packages and installing into local mvn repository\"\necho \"--------------------------------------------------------------------\"\nmvn $MVN_FLAGS -Pjepsen -DskipTests clean install\n\necho\necho \"Building and running kudu-jepsen consistency tests\"\necho \"--------------------------------------------------------------------\"\npushd kudu-jepsen\nmvn $MVN_FLAGS clojure:run \\\n  -DmasterNodes=\"$KUDU_MASTER_NODES\" \\\n  -DtserverNodes=\"$KUDU_TSERVER_NODES\" \\\n  -DsshKeyPath=\"$SSH_KEY\" \\\n  -DiterNum=\"$ITER_NUM\"\npopd\npopd\n\nset +x\n", "num_lines": 141}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# This script takes a line in stdin and parses the real time out of it.\n# Input example:\n#  \"Times for Insert 10000000 keys: real 16.438s\tuser 16.164s\tsys 0.229s\"\n# Output:\n#  16.438\n\nawk -F 'real ' '{ print $2 }' | awk -F s '{ print $1 }'\n", "num_lines": 27}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -xe\n########################################################################\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n# Run tpch benchmark and write results to the DB.\n#\n# Expects to find the following Jenkins environment variables set:\n# - JOB_NAME\n# - BUILD_NUMBER\n# If these are not set, the script will still run but will not record\n# the results in the MySQL database. Instead, it will output results\n# into .tsv files in the kudu source root directory. This is useful for\n# running this benchmark locally for testing / dev purposes.\n#\n# Optional environment variables to override (defaults set for Jenkins):\n# - LINEITEM_TBL_PATH: Path to lineitem.tbl from the TPC-H suite.\n# - KUDU_DATA_DIR: Directory to use for data storage.\n# - TPCH_NUM_QUERY_ITERS: Number of TPC-H query iterations to run.\n#########################################################################\n\n##########################################################\n# Constants\n##########################################################\nROOT=$(readlink -f $(dirname $0)/../../..)\n\n##########################################################\n# Overridable params\n##########################################################\nLINEITEM_TBL_PATH=${LINEITEM_TBL_PATH:-/home/jdcryans/lineitem.tbl}\nKUDU_DATA_DIR=${KUDU_DATA_DIR:-/data/2/tmp/kudutpch1-jenkins}\nTPCH_NUM_QUERY_ITERS=${TPCH_NUM_QUERY_ITERS:-5}\n\n##########################################################\n# Functions\n##########################################################\nrecord_result() {\n  local RECORD_STATS_SCRIPT=$ROOT/src/kudu/scripts/write-jobs-stats-to-mysql.py\n  local TEST_NAME=$1\n  local ITER=$2\n  local VALUE=$3\n  if [ -n \"$JOB_NAME\" ]; then\n    # Jenkins.\n    python $RECORD_STATS_SCRIPT $JOB_NAME $BUILD_NUMBER $TEST_NAME $ITER $VALUE\n  else\n    # Running locally.\n    local STATS_FILE=\"$OUTDIR/tpch-$TEST_NAME.tsv\"\n    echo -e \"${TEST_NAME}\\t${ITER}\\t${VALUE}\" >> \"$STATS_FILE\"\n  fi\n}\n\nensure_cpu_scaling() {\n  $ROOT/src/kudu/scripts/ensure_cpu_scaling.sh \"$@\"\n}\n\n##########################################################\n# Main\n##########################################################\nif [ $TPCH_NUM_QUERY_ITERS -lt 2 ]; then\n  echo \"Error: TPCH_NUM_QUERY_ITERS must be 2 or greater\"\n  exit 1\nfi\n\ncd $ROOT\n\n# Set up environment\nset -o pipefail\nulimit -m $[3000*1000]\nulimit -c unlimited # gather core dumps\n\n# Set CPU governor, and restore it on exit.\nold_governor=$(ensure_cpu_scaling performance)\nrestore_governor() {\n  ensure_cpu_scaling $old_governor >/dev/null\n}\ntrap restore_governor EXIT\n\n# PATH=<toolchain_stuff>:$PATH\nexport TOOLCHAIN=/mnt/toolchain/toolchain.sh\nif [ -f \"$TOOLCHAIN\" ]; then\n  source $TOOLCHAIN\nfi\n\n# Build thirdparty\n$ROOT/build-support/enable_devtoolset.sh $ROOT/thirdparty/build-if-necessary.sh\n\n# PATH=<thirdparty_stuff>:<toolchain_stuff>:$PATH\nTHIRDPARTY_BIN=$(pwd)/thirdparty/installed/common/bin\nexport PPROF_PATH=$THIRDPARTY_BIN/pprof\n\nBUILD_TYPE=release\n\n# Build Kudu\nmkdir -p build/$BUILD_TYPE\npushd build/$BUILD_TYPE\nrm -rf CMakeCache CMakeFiles/\n\n$ROOT/build-support/enable_devtoolset.sh $THIRDPARTY_BIN/cmake -DCMAKE_BUILD_TYPE=${BUILD_TYPE} ../..\n\nNUM_PROCS=$(cat /proc/cpuinfo | grep processor | wc -l)\nmake -j${NUM_PROCS} tpch1 2>&1 | tee build.log\npopd\n\n# Warming up the OS buffer.\ncat $LINEITEM_TBL_PATH > /dev/null\ncat $LINEITEM_TBL_PATH > /dev/null\n\nOUTDIR=$ROOT/build/$BUILD_TYPE/tpch\nrm -Rf $KUDU_DATA_DIR   # Clean up data dir.\nmkdir -p $OUTDIR        # Create log file output dir.\n\n$ROOT/build/$BUILD_TYPE/bin/tpch1 -logtostderr=1 \\\n                                  -tpch_path_to_data=$LINEITEM_TBL_PATH \\\n                                  -mini_cluster_base_dir=$KUDU_DATA_DIR \\\n                                  -tpch_num_query_iterations=$TPCH_NUM_QUERY_ITERS \\\n                                  $* \\\n                                  >$OUTDIR/benchmark.log 2>&1\n\ncat $OUTDIR/benchmark.log\nINSERT_TIME=$(grep \"Time spent loading\" $OUTDIR/benchmark.log | \\\n    perl -pe 's/.*Time spent loading: real ([0-9\\.]+)s.*/\\1/')\nrecord_result insert_1gb 1 $INSERT_TIME\n\n# We do not record the first iteration (#0) because we want to record the\n# in-cache performance.\nfor iter in $(seq 1 $(expr $TPCH_NUM_QUERY_ITERS - 1)); do\n  QUERY_TIME=$(grep \"iteration # $iter\" $OUTDIR/benchmark.log | \\\n      perl -pe \"s/.*iteration # $iter: real ([0-9\\.]+)s.*/\\1/\")\n  record_result query_1_1gb $iter $QUERY_TIME\ndone\n", "num_lines": 146}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# A script that prints the first argument and ignores all the others.\necho \"$1\"\n", "num_lines": 21}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# build-definitions.sh provides functions to build thirdparty dependencies.\n# These functions do not take positional arguments, but individual builds may\n# be influenced by setting environment variables:\n#\n# * PREFIX - the install destination directory.\n# * MODE_SUFFIX - an optional suffix to add to each build directory's name.\n# * EXTRA_CFLAGS - additional flags to pass to the C compiler.\n# * EXTRA_CXXFLAGS - additional flags to pass to the C++ compiler.\n# * EXTRA_LDFLAGS - additional flags to pass to the linker.\n# * EXTRA_LIBS - additional libraries to link.\n# * NINJA - if set, uses this instead of 'make' for cmake-configured libraries.\n#           note that 'EXTRA_CMAKE_FLAGS\" should be set to include -GNinja as\n#           well to generate the proper build files.\n# * EXTRA_CMAKE_FLAGS - extra flags to pass to cmake\n#\n# build-definitions.sh is meant to be sourced from build-thirdparty.sh, and\n# relies on environment variables defined there and in vars.sh.\n\n# Save the current build environment.\nsave_env() {\n  _PREFIX=${PREFIX}\n  _MODE_SUFFIX=${MODE_SUFFIX}\n  _EXTRA_CFLAGS=${EXTRA_CFLAGS}\n  _EXTRA_CXXFLAGS=${EXTRA_CXXFLAGS}\n  _EXTRA_LDFLAGS=${EXTRA_LDFLAGS}\n  _EXTRA_LIBS=${EXTRA_LIBS}\n}\n\n# Restore the most recently saved build environment.\nrestore_env() {\n  PREFIX=${_PREFIX}\n  MODE_SUFFIX=${_MODE_SUFFIX}\n  EXTRA_CFLAGS=${_EXTRA_CFLAGS}\n  EXTRA_CXXFLAGS=${_EXTRA_CXXFLAGS}\n  EXTRA_LDFLAGS=${_EXTRA_LDFLAGS}\n  EXTRA_LIBS=${_EXTRA_LIBS}\n}\n\n# Some versions of libtool are vulnerable to a bug[1] wherein clang's -stdlib\n# parameter isn't passed through to the link command line. This causes the\n# libtool to link the shared object against libstdc++ instead of libc++.\n#\n# The bug was only fixed in version 2.4.2 of libtool and el6 carries version\n# 2.2.6, so we work around it here.\n#\n# 1. https://debbugs.gnu.org/db/10/10579.html\nfixup_libtool() {\n  if [[ ! \"$EXTRA_LDFLAGS\" =~ \"-stdlib=libc++\" ]]; then\n    echo \"libtool does not need to be fixed up: not using libc++\"\n    return\n  fi\n  if [ ! -f libtool ]; then\n    echo \"libtool not found\"\n    exit 1\n  fi\n  if ! grep -q -e 'postdeps=.*-lstdc++' libtool; then\n    echo \"libtool does not need to be fixed up: already configured for libc++\"\n    return\n  fi\n\n  # Modify a line like:\n  #\n  #   postdeps=\"-lfoo -lstdc++ -lbar -lstdc++ -lbaz\"\n  #\n  # To become:\n  #\n  #   postdeps=\"-lfoo -lc++ -lbar -lc++ -lbaz\"\n  sed -i.before_fixup -e '/postdeps=/s/-lstdc++/-lc++/g' libtool\n  echo \"libtool has been fixed up\"\n}\n\nbuild_cmake() {\n  CMAKE_BDIR=$TP_BUILD_DIR/$CMAKE_NAME$MODE_SUFFIX\n  mkdir -p $CMAKE_BDIR\n  pushd $CMAKE_BDIR\n  $CMAKE_SOURCE/bootstrap \\\n    --prefix=$PREFIX \\\n    --parallel=$PARALLEL\n  # Unfortunately, cmake's bootstrap always uses Makefiles\n  # and can't be configured to build with ninja.\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_libcxxabi() {\n  LIBCXXABI_BDIR=$TP_BUILD_DIR/llvm-$LLVM_VERSION.libcxxabi$MODE_SUFFIX\n  mkdir -p $LIBCXXABI_BDIR\n  pushd $LIBCXXABI_BDIR\n  rm -Rf CMakeCache.txt CMakeFiles/\n  cmake \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DCMAKE_INSTALL_PREFIX=$PREFIX \\\n    -DCMAKE_CXX_FLAGS=\"$EXTRA_CXXFLAGS $EXTRA_LDFLAGS\" \\\n    -DLLVM_PATH=$LLVM_SOURCE \\\n    $EXTRA_CMAKE_FLAGS \\\n    $LLVM_SOURCE/projects/libcxxabi\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_libcxx() {\n  local BUILD_TYPE=$1\n  case $BUILD_TYPE in\n    \"tsan\")\n      SANITIZER_TYPE=Thread\n      ;;\n    *)\n      echo \"Unknown build type: $BUILD_TYPE\"\n      exit 1\n      ;;\n  esac\n\n  LIBCXX_BDIR=$TP_BUILD_DIR/llvm-$LLVM_VERSION.libcxx$MODE_SUFFIX\n  mkdir -p $LIBCXX_BDIR\n  pushd $LIBCXX_BDIR\n  rm -Rf CMakeCache.txt CMakeFiles/\n  cmake \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DCMAKE_INSTALL_PREFIX=$PREFIX \\\n    -DCMAKE_CXX_FLAGS=\"$EXTRA_CXXFLAGS\" \\\n    -DCMAKE_EXE_LINKER_FLAGS=\"$EXTRA_LDFLAGS\" \\\n    -DCMAKE_MODULE_LINKER_FLAGS=\"$EXTRA_LDFLAGS\" \\\n    -DCMAKE_SHARED_LINKER_FLAGS=\"$EXTRA_LDFLAGS\" \\\n    -DLLVM_PATH=$LLVM_SOURCE \\\n    -DLIBCXX_CXX_ABI=libcxxabi \\\n    -DLIBCXX_CXX_ABI_INCLUDE_PATHS=$LLVM_SOURCE/projects/libcxxabi/include \\\n    -DLIBCXX_CXX_ABI_LIBRARY_PATH=$PREFIX/lib \\\n    -DLLVM_USE_SANITIZER=$SANITIZER_TYPE \\\n    $EXTRA_CMAKE_FLAGS \\\n    $LLVM_SOURCE/projects/libcxx\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_or_find_python() {\n  if [ -n \"$PYTHON_EXECUTABLE\" ]; then\n    return\n  fi\n\n  # Build Python only if necessary.\n  if [[ $(python2.7 -V 2>&1) =~ \"Python 2.7.\" ]]; then\n    PYTHON_EXECUTABLE=$(which python2.7)\n  elif [[ $(python -V 2>&1) =~ \"Python 2.7.\" ]]; then\n    PYTHON_EXECUTABLE=$(which python)\n  else\n    PYTHON_BDIR=$TP_BUILD_DIR/$PYTHON_NAME$MODE_SUFFIX\n    mkdir -p $PYTHON_BDIR\n    pushd $PYTHON_BDIR\n    $PYTHON_SOURCE/configure\n    make -j$PARALLEL $EXTRA_MAKEFLAGS\n    PYTHON_EXECUTABLE=\"$PYTHON_BDIR/python\"\n    popd\n  fi\n}\n\nbuild_llvm() {\n  local TOOLS_ARGS=\n  local BUILD_TYPE=$1\n\n  build_or_find_python\n\n  # Always disabled; these subprojects are built standalone.\n  TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_TOOL_LIBCXX_BUILD=OFF\"\n  TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_TOOL_LIBCXXABI_BUILD=OFF\"\n\n\n  # Disable some builds we don't care about.\n  for arg in \\\n      CLANG_ENABLE_ARCMT \\\n      CLANG_TOOL_ARCMT_TEST_BUILD \\\n      CLANG_TOOL_C_ARCMT_TEST_BUILD \\\n      CLANG_TOOL_C_INDEX_TEST_BUILD \\\n      CLANG_TOOL_CLANG_CHECK_BUILD \\\n      CLANG_TOOL_CLANG_DIFF_BUILD \\\n      CLANG_TOOL_CLANG_FORMAT_VS_BUILD \\\n      CLANG_TOOL_CLANG_FUNC_MAPPING_BUILD \\\n      CLANG_TOOL_CLANG_FUZZER_BUILD \\\n      CLANG_TOOL_CLANG_IMPORT_TEST_BUILD \\\n      CLANG_TOOL_CLANG_OFFLOAD_BUNDLER_BUILD \\\n      CLANG_TOOL_CLANG_REFACTOR_BUILD \\\n      CLANG_TOOL_CLANG_RENAME_BUILD \\\n      CLANG_TOOL_DIAGTOOL_BUILD \\\n      COMPILER_RT_BUILD_LIBFUZZER \\\n      LLVM_INCLUDE_GO_TESTS \\\n      LLVM_POLLY_BUILD \\\n      LLVM_TOOL_BUGPOINT_BUILD \\\n      LLVM_TOOL_BUGPOINT_PASSES_BUILD \\\n      LLVM_TOOL_DSYMUTIL_BUILD \\\n      LLVM_TOOL_LLI_BUILD \\\n      LLVM_TOOL_LLVM_AS_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_BCANALYZER_BUILD \\\n      LLVM_TOOL_LLVM_CAT_BUILD \\\n      LLVM_TOOL_LLVM_CFI_VERIFY_BUILD \\\n      LLVM_TOOL_LLVM_C_TEST_BUILD \\\n      LLVM_TOOL_LLVM_CVTRES_BUILD \\\n      LLVM_TOOL_LLVM_CXXDUMP_BUILD \\\n      LLVM_TOOL_LLVM_CXXFILT_BUILD \\\n      LLVM_TOOL_LLVM_DEMANGLE_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_DIFF_BUILD \\\n      LLVM_TOOL_LLVM_DIS_BUILD \\\n      LLVM_TOOL_LLVM_DWARFDUMP_BUILD \\\n      LLVM_TOOL_LLVM_DWP_BUILD \\\n      LLVM_TOOL_LLVM_EXTRACT_BUILD \\\n      LLVM_TOOL_LLVM_GO_BUILD \\\n      LLVM_TOOL_LLVM_ISEL_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_JITLISTENER_BUILD \\\n      LLVM_TOOL_LLVM_MC_ASSEMBLE_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_MC_BUILD \\\n      LLVM_TOOL_LLVM_MC_DISASSEMBLE_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_MCMARKUP_BUILD \\\n      LLVM_TOOL_LLVM_MODEXTRACT_BUILD \\\n      LLVM_TOOL_LLVM_MT_BUILD \\\n      LLVM_TOOL_LLVM_NM_BUILD \\\n      LLVM_TOOL_LLVM_OBJCOPY_BUILD \\\n      LLVM_TOOL_LLVM_OBJDUMP_BUILD \\\n      LLVM_TOOL_LLVM_OPT_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_OPT_REPORT_BUILD \\\n      LLVM_TOOL_LLVM_PDBUTIL_BUILD \\\n      LLVM_TOOL_LLVM_PROFDATA_BUILD \\\n      LLVM_TOOL_LLVM_RC_BUILD \\\n      LLVM_TOOL_LLVM_READOBJ_BUILD \\\n      LLVM_TOOL_LLVM_RTDYLD_BUILD \\\n      LLVM_TOOL_LLVM_SHLIB_BUILD \\\n      LLVM_TOOL_LLVM_SIZE_BUILD \\\n      LLVM_TOOL_LLVM_SPECIAL_CASE_LIST_FUZZER_BUILD \\\n      LLVM_TOOL_LLVM_SPLIT_BUILD \\\n      LLVM_TOOL_LLVM_STRESS_BUILD \\\n      LLVM_TOOL_LLVM_STRINGS_BUILD \\\n      LLVM_TOOL_MSBUILD_BUILD \\\n      LLVM_TOOL_OBJ2YAML_BUILD \\\n      LLVM_TOOL_OPT_BUILD \\\n      LLVM_TOOL_OPT_VIEWER_BUILD \\\n      LLVM_TOOL_VERIFY_USELISTORDER_BUILD \\\n      LLVM_TOOL_XCODE_TOOLCHAIN_BUILD \\\n      LLVM_TOOL_YAML2OBJ_BUILD \\\n      ; do\n    TOOLS_ARGS=\"$TOOLS_ARGS -D${arg}=OFF\"\n  done\n\n  CLANG_CXXFLAGS=\"$EXTRA_CXXFLAGS\"\n  CLANG_LDFLAGS=\"$EXTRA_LDFLAGS\"\n  case $BUILD_TYPE in\n    \"normal\")\n      # Default build: core LLVM libraries, clang, compiler-rt, and all tools.\n\n      # Set the gcc prefix based on the gcc that's on the path. Otherwise,\n      # clang will auto-detect the newest devtoolset that is installed even\n      # if it's not the current one on the path. This results in link errors\n      # like:\n      #   /opt/rh/devtoolset-3/root/usr/bin/ld:\n      #     /opt/rh/devtoolset-6/root/usr/lib/gcc/x86_64-redhat-linux/6.2.1/crtbeginS.o:\n      #     unrecognized relocation (0x2a) in section `.text'\n      # ...as it tries to use the 'ld' from devtoolset-3 (on the path) to link libraries\n      # coming from devtoolset-6.\n      GCC_INSTALL_PREFIX=$(gcc -v 2>&1 | grep -o -- '--prefix=[^ ]*' | cut -f2 -d=)\n      if [ -n \"$GCC_INSTALL_PREFIX\" ]; then\n        TOOLS_ARGS=\"$TOOLS_ARGS -DGCC_INSTALL_PREFIX=$GCC_INSTALL_PREFIX\"\n      fi\n\n      # Depend on zlib from the thirdparty tree. It's an optional dependency for\n      # LLVM, but a required [1] one for IWYU. When TSAN is enabled these flags\n      # are already set by build-thirdparty.sh in order to support the\n      # thirdparty libc++, so it's not necessary to set them again.\n      #\n      # 1. https://github.com/include-what-you-use/include-what-you-use/issues/539\n      CLANG_CXXFLAGS=\"$CLANG_CXXFLAGS -I$PREFIX/include\"\n      CLANG_LDFLAGS=\"$CLANG_LDFLAGS -L$PREFIX/lib -Wl,-rpath,$PREFIX/lib\"\n      ;;\n    \"tsan\")\n      # Build just the core LLVM libraries, dependent on libc++.\n      TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_ENABLE_LIBCXX=ON\"\n      TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_INCLUDE_TOOLS=OFF\"\n      TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_TOOL_COMPILER_RT_BUILD=OFF\"\n\n      # Configure for TSAN.\n      TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_USE_SANITIZER=Thread\"\n      # Use the 'tblgen' from the non-TSAN build when building the TSAN\n      # build, since it runs much faster.\n      TOOLS_ARGS=\"$TOOLS_ARGS -DLLVM_TABLEGEN=$PREFIX_DEPS/bin/llvm-tblgen\"\n      ;;\n    *)\n      echo \"Unknown LLVM build type: $BUILD_TYPE\"\n      exit 1\n      ;;\n  esac\n\n  LLVM_BDIR=$TP_BUILD_DIR/llvm-$LLVM_VERSION$MODE_SUFFIX\n  mkdir -p $LLVM_BDIR\n  pushd $LLVM_BDIR\n\n  # Rebuild the CMake cache every time.\n  rm -Rf CMakeCache.txt CMakeFiles/\n\n  # The LLVM build can fail if a different version is already installed\n  # in the install prefix. It will try to link against that version instead\n  # of the one being built.\n  rm -Rf $PREFIX/include/{llvm*,clang*} \\\n         $PREFIX/lib/lib{LLVM,LTO,clang}* \\\n         $PREFIX/lib/clang/ \\\n         $PREFIX/lib/cmake/{llvm,clang}\n\n  cmake \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DCMAKE_INSTALL_PREFIX=$PREFIX \\\n    -DLLVM_INCLUDE_DOCS=OFF \\\n    -DLLVM_INCLUDE_EXAMPLES=OFF \\\n    -DLLVM_INCLUDE_TESTS=OFF \\\n    -DLLVM_INCLUDE_UTILS=OFF \\\n    -DLLVM_TARGETS_TO_BUILD=X86 \\\n    -DLLVM_ENABLE_RTTI=ON \\\n    -DCMAKE_CXX_FLAGS=\"$CLANG_CXXFLAGS\" \\\n    -DCMAKE_EXE_LINKER_FLAGS=\"$CLANG_LDFLAGS\" \\\n    -DCMAKE_MODULE_LINKER_FLAGS=\"$CLANG_LDFLAGS\" \\\n    -DCMAKE_SHARED_LINKER_FLAGS=\"$CLANG_LDFLAGS\" \\\n    -DPYTHON_EXECUTABLE=$PYTHON_EXECUTABLE \\\n    $TOOLS_ARGS \\\n    $EXTRA_CMAKE_FLAGS \\\n    $LLVM_SOURCE\n\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n\n  if [[ \"$BUILD_TYPE\" == \"normal\" ]]; then\n    # Create a link from Clang to thirdparty/clang-toolchain. This path is used\n    # for all Clang invocations. The link can't point to the Clang installed in\n    # the prefix directory, since this confuses CMake into believing the\n    # thirdparty prefix directory is the system-wide prefix, and it omits the\n    # thirdparty prefix directory from the rpath of built binaries.\n    ln -sfn $LLVM_BDIR $TP_DIR/clang-toolchain\n  fi\n  popd\n}\n\nbuild_gflags() {\n  GFLAGS_BDIR=$TP_BUILD_DIR/$GFLAGS_NAME$MODE_SUFFIX\n  mkdir -p $GFLAGS_BDIR\n  pushd $GFLAGS_BDIR\n  rm -rf CMakeCache.txt CMakeFiles/\n  cmake \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n    -DGFLAGS_NAMESPACE=gflags \\\n    -DCMAKE_INSTALL_PREFIX=$PREFIX \\\n    -DCMAKE_CXX_FLAGS=\"$EXTRA_CXXFLAGS\" \\\n    -DCMAKE_EXE_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n    -DCMAKE_MODULE_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n    -DCMAKE_SHARED_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n    -DBUILD_SHARED_LIBS=On \\\n    -DBUILD_STATIC_LIBS=On \\\n    -DREGISTER_INSTALL_PREFIX=Off \\\n    $EXTRA_CMAKE_FLAGS \\\n    $GFLAGS_SOURCE\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_libunwind() {\n  LIBUNWIND_BDIR=$TP_BUILD_DIR/$LIBUNWIND_NAME$MODE_SUFFIX\n  mkdir -p $LIBUNWIND_BDIR\n  pushd $LIBUNWIND_BDIR\n  # Disable minidebuginfo, which depends on liblzma, until/unless we decide to\n  # add liblzma to thirdparty.\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    $LIBUNWIND_SOURCE/configure \\\n    --disable-minidebuginfo \\\n    --with-pic \\\n    --prefix=$PREFIX\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_glog() {\n  GLOG_BDIR=$TP_BUILD_DIR/$GLOG_NAME$MODE_SUFFIX\n  mkdir -p $GLOG_BDIR\n  pushd $GLOG_BDIR\n\n  # glog depends on libunwind and gflags.\n  #\n  # Specifying -Wl,-rpath has different default behavior on GNU binutils ld vs.\n  # the GNU gold linker. ld sets RPATH (due to defaulting to --disable-new-dtags)\n  # and gold sets RUNPATH (due to defaulting to --enable-new-dtags). At the time\n  # of this writing, contrary to the way RPATH is treated, when RUNPATH is\n  # specified on a binary, glibc doesn't respect it for transitive (non-direct)\n  # library dependencies (see https://sourceware.org/bugzilla/show_bug.cgi?id=13945).\n  # So we must set RUNPATH for all deps-of-deps on the dep libraries themselves.\n  #\n  # This comment applies both here and the locations elsewhere in this script\n  # where we add something to -Wl,-rpath.\n  CXXFLAGS=\"$EXTRA_CXXFLAGS -I$PREFIX/include\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS -L$PREFIX/lib -Wl,-rpath,$PREFIX/lib\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $GLOG_SOURCE/configure \\\n    --with-pic \\\n    --prefix=$PREFIX \\\n    --with-gflags=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_gperftools() {\n  GPERFTOOLS_BDIR=$TP_BUILD_DIR/$GPERFTOOLS_NAME$MODE_SUFFIX\n  mkdir -p $GPERFTOOLS_BDIR\n  pushd $GPERFTOOLS_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $GPERFTOOLS_SOURCE/configure \\\n    --enable-frame-pointers \\\n    --with-pic \\\n    --prefix=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_gmock() {\n  GMOCK_SHARED_BDIR=$TP_BUILD_DIR/$GMOCK_NAME.shared$MODE_SUFFIX\n  GMOCK_STATIC_BDIR=$TP_BUILD_DIR/$GMOCK_NAME.static$MODE_SUFFIX\n  for SHARED in ON OFF; do\n    if [ $SHARED = \"ON\" ]; then\n      GMOCK_BDIR=$GMOCK_SHARED_BDIR\n    else\n      GMOCK_BDIR=$GMOCK_STATIC_BDIR\n    fi\n    mkdir -p $GMOCK_BDIR\n    pushd $GMOCK_BDIR\n    rm -rf CMakeCache.txt CMakeFiles/\n    cmake \\\n      -DCMAKE_BUILD_TYPE=Debug \\\n      -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n      -DCMAKE_CXX_FLAGS=\"$EXTRA_CXXFLAGS\" \\\n      -DCMAKE_EXE_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n      -DCMAKE_MODULE_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n      -DCMAKE_SHARED_LINKER_FLAGS=\"$EXTRA_LDFLAGS $EXTRA_LIBS\" \\\n      -DBUILD_SHARED_LIBS=$SHARED \\\n      $EXTRA_CMAKE_FLAGS \\\n      $GMOCK_SOURCE/googlemock\n    ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS\n    popd\n  done\n\n  # Install gmock/gtest libraries and headers manually instead of using make\n  # install. Make install results in libraries with a malformed lib name on\n  # macOS.\n  echo Installing gmock...\n  cp -a $GMOCK_SHARED_BDIR/libgmock.$DYLIB_SUFFIX $PREFIX/lib/\n  cp -a $GMOCK_STATIC_BDIR/libgmock.a $PREFIX/lib/\n  rsync -av $GMOCK_SOURCE/googlemock/include/ $PREFIX/include/\n  rsync -av $GMOCK_SOURCE/googletest/include/ $PREFIX/include/\n}\n\nbuild_protobuf() {\n  PROTOBUF_BDIR=$TP_BUILD_DIR/$PROTOBUF_NAME$MODE_SUFFIX\n  mkdir -p $PROTOBUF_BDIR\n  pushd $PROTOBUF_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $PROTOBUF_SOURCE/configure \\\n    --with-pic \\\n    --enable-shared \\\n    --enable-static \\\n    --prefix=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_snappy() {\n  SNAPPY_BDIR=$TP_BUILD_DIR/$SNAPPY_NAME$MODE_SUFFIX\n  mkdir -p $SNAPPY_BDIR\n  pushd $SNAPPY_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $SNAPPY_SOURCE/configure \\\n    --with-pic \\\n    --prefix=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_zlib() {\n  ZLIB_BDIR=$TP_BUILD_DIR/$ZLIB_NAME$MODE_SUFFIX\n  mkdir -p $ZLIB_BDIR\n  pushd $ZLIB_BDIR\n\n  # It doesn't appear possible to isolate source and build directories, so just\n  # prepopulate the latter using the former.\n  rsync -av --delete $ZLIB_SOURCE/ .\n\n  CFLAGS=\"$EXTRA_CFLAGS -fPIC\" \\\n    ./configure \\\n    --prefix=$PREFIX\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_lz4() {\n  LZ4_BDIR=$TP_BUILD_DIR/$LZ4_NAME$MODE_SUFFIX\n  mkdir -p $LZ4_BDIR\n  pushd $LZ4_BDIR\n  rm -Rf CMakeCache.txt CMakeFiles/\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    cmake \\\n    -DCMAKE_BUILD_TYPE=release \\\n    -DBUILD_TOOLS=0 \\\n    -DCMAKE_INSTALL_PREFIX:PATH=$PREFIX \\\n    $EXTRA_CMAKE_FLAGS \\\n    $LZ4_SOURCE/cmake_unofficial\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_bitshuffle() {\n  BITSHUFFLE_BDIR=$TP_BUILD_DIR/$BITSHUFFLE_NAME$MODE_SUFFIX\n  mkdir -p $BITSHUFFLE_BDIR\n  pushd $BITSHUFFLE_BDIR\n  # bitshuffle depends on lz4, therefore set the flag I$PREFIX/include\n\n  # This library has significant optimizations when built with -mavx2. However,\n  # we still need to support non-AVX2-capable hardware. So, we build it twice,\n  # once with the flag and once without, and use some linker tricks to\n  # suffix the AVX2 symbols with '_avx2'. OSX doesn't have objcopy, so we only\n  # do this trick on Linux.\n  if [ -n \"$OS_LINUX\" ]; then\n    arches=\"default avx2\"\n  else\n    arches=\"default\"\n  fi\n  to_link=\"\"\n  for arch in $arches ; do\n    arch_flag=\"\"\n    if [ \"$arch\" == \"avx2\" ]; then\n      arch_flag=\"-mavx2\"\n    fi\n    tmp_obj=bitshuffle_${arch}_tmp.o\n    dst_obj=bitshuffle_${arch}.o\n    ${CC:-gcc} $EXTRA_CFLAGS $arch_flag -std=c99 -I$PREFIX/include -O3 -DNDEBUG -fPIC -c \\\n      \"$BITSHUFFLE_SOURCE/src/bitshuffle_core.c\" \\\n      \"$BITSHUFFLE_SOURCE/src/bitshuffle.c\" \\\n      \"$BITSHUFFLE_SOURCE/src/iochain.c\"\n    # Merge the object files together to produce a combined .o file.\n    ld -r -o $tmp_obj bitshuffle_core.o bitshuffle.o iochain.o\n    # For the AVX2 symbols, suffix them.\n    if [ \"$arch\" == \"avx2\" ]; then\n      # Create a mapping file with '<old_sym> <suffixed_sym>' on each line.\n      nm --defined-only --extern-only $tmp_obj | while read addr type sym ; do\n        echo ${sym} ${sym}_${arch}\n      done > renames.txt\n      objcopy --redefine-syms=renames.txt $tmp_obj $dst_obj\n    else\n      mv $tmp_obj $dst_obj\n    fi\n    to_link=\"$to_link $dst_obj\"\n  done\n\n  rm -f bitshuffle.a\n  ar rs bitshuffle.a $to_link\n  cp bitshuffle.a $PREFIX/lib/\n  cp $BITSHUFFLE_SOURCE/src/bitshuffle.h $PREFIX/include/bitshuffle.h\n  cp $BITSHUFFLE_SOURCE/src/bitshuffle_core.h $PREFIX/include/bitshuffle_core.h\n  popd\n}\n\nbuild_libev() {\n  LIBEV_BDIR=$TP_BUILD_DIR/$LIBEV_NAME$MODE_SUFFIX\n  mkdir -p $LIBEV_BDIR\n  pushd $LIBEV_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    $LIBEV_SOURCE/configure \\\n    --with-pic \\\n    --prefix=$PREFIX\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_rapidjson() {\n  # just installing it into our prefix\n  pushd $RAPIDJSON_SOURCE\n  rsync -av --delete $RAPIDJSON_SOURCE/include/rapidjson/ $PREFIX/include/rapidjson/\n  popd\n}\n\nbuild_squeasel() {\n  # Mongoose's Makefile builds a standalone web server, whereas we just want\n  # a static lib\n  SQUEASEL_BDIR=$TP_BUILD_DIR/$SQUEASEL_NAME$MODE_SUFFIX\n  mkdir -p $SQUEASEL_BDIR\n  pushd $SQUEASEL_BDIR\n  ${CC:-gcc} $EXTRA_CFLAGS $OPENSSL_CFLAGS $OPENSSL_LDFLAGS -std=c99 -O3 -DNDEBUG -fPIC -c \"$SQUEASEL_SOURCE/squeasel.c\"\n  ar rs libsqueasel.a squeasel.o\n  cp libsqueasel.a $PREFIX/lib/\n  cp $SQUEASEL_SOURCE/squeasel.h $PREFIX/include/\n  popd\n}\n\nbuild_mustache() {\n  MUSTACHE_BDIR=$TP_BUILD_DIR/$MUSTACHE_NAME$MODE_SUFFIX\n  mkdir -p $MUSTACHE_BDIR\n  pushd $MUSTACHE_BDIR\n  # We add $PREFIX/include for boost and $PREFIX_COMMON/include for rapidjson.\n  ${CXX:-g++} $EXTRA_CXXFLAGS -I$PREFIX/include -I$PREFIX_COMMON/include -O3 -DNDEBUG -fPIC -c \"$MUSTACHE_SOURCE/mustache.cc\"\n  ar rs libmustache.a mustache.o\n  cp libmustache.a $PREFIX/lib/\n  cp $MUSTACHE_SOURCE/mustache.h $PREFIX/include/\n  popd\n}\n\nbuild_curl() {\n  # Configure for a very minimal install - basically only HTTP(S), since we only\n  # use this for testing our own HTTP/HTTPS endpoints at this point in time.\n  CURL_BDIR=$TP_BUILD_DIR/$CURL_NAME$MODE_SUFFIX\n  mkdir -p $CURL_BDIR\n  pushd $CURL_BDIR\n\n  # Note: curl shows a message asking for CPPFLAGS to be used for include\n  # directories, not CFLAGS.\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CPPFLAGS=\"$EXTRA_CPPFLAGS $OPENSSL_CFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS $OPENSSL_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $CURL_SOURCE/configure \\\n    --prefix=$PREFIX \\\n    --disable-dict \\\n    --disable-file \\\n    --disable-ftp \\\n    --disable-gopher \\\n    --disable-imap \\\n    --disable-ipv6 \\\n    --disable-ldap \\\n    --disable-ldaps \\\n    --disable-manual \\\n    --disable-pop3 \\\n    --disable-rtsp \\\n    --disable-smtp \\\n    --disable-telnet \\\n    --disable-tftp \\\n    --without-librtmp \\\n    --without-libssh2\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_crcutil() {\n  CRCUTIL_BDIR=$TP_BUILD_DIR/$CRCUTIL_NAME$MODE_SUFFIX\n  mkdir -p $CRCUTIL_BDIR\n  pushd $CRCUTIL_BDIR\n\n  # The autogen.sh script makes it difficult to isolate source and build\n  # directories, so just prepopulate the latter using the former.\n  rsync -av --delete $CRCUTIL_SOURCE/ .\n  ./autogen.sh\n\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    ./configure \\\n    --prefix=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_breakpad() {\n  BREAKPAD_BDIR=$TP_BUILD_DIR/$BREAKPAD_NAME$MODE_SUFFIX\n  mkdir -p $BREAKPAD_BDIR\n  pushd $BREAKPAD_BDIR\n\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $BREAKPAD_SOURCE/configure --prefix=$PREFIX\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n\n  # Here we run a script to munge breakpad #include statements in-place. Sadly,\n  # breakpad does not prefix its header file paths. Until we can solve that\n  # issue upstream we use this \"hack\" to add breakpad/ as a prefix for all the\n  # breakpad-related includes in the breakpad header files ourselves. See also\n  # https://bugs.chromium.org/p/google-breakpad/issues/detail?id=721\n  local BREAKPAD_INCLUDE_DIR=$PREFIX/include/breakpad\n  pushd \"$BREAKPAD_INCLUDE_DIR\"\n  find . -type f | xargs grep -l \"#include\" | \\\n    xargs perl -p -i -e '@pre = qw(client common google_breakpad processor third_party); for $p (@pre) { s{#include \"$p/}{#include \"breakpad/$p/}; }'\n  popd\n\n  popd\n}\n\nbuild_cpplint() {\n  # Copy cpplint tool into bin directory\n  cp $GSG_SOURCE/cpplint/cpplint.py $PREFIX/bin/cpplint.py\n}\n\nbuild_gcovr() {\n  # Copy gcovr tool into bin directory\n  cp -a $GCOVR_SOURCE/scripts/gcovr $PREFIX/bin/gcovr\n}\n\nbuild_trace_viewer() {\n  echo Installing trace-viewer into the www directory\n  cp -a $TRACE_VIEWER_SOURCE/tracing.* $TP_DIR/../www/\n}\n\nbuild_nvml() {\n  NVML_BDIR=$TP_BUILD_DIR/$NVML_NAME$MODE_SUFFIX\n  mkdir -p $NVML_BDIR\n  pushd $NVML_BDIR\n\n  # It doesn't appear possible to isolate source and build directories, so just\n  # prepopulate the latter using the former.\n  rsync -av --delete $NVML_SOURCE/ .\n  cd src/\n\n  # The embedded jemalloc build doesn't pick up the EXTRA_CFLAGS environment\n  # variable, so we have to stick our flags into this config file.\n  if ! grep -q -e \"$EXTRA_CFLAGS\" jemalloc/jemalloc.cfg ; then\n    perl -p -i -e \"s,(EXTRA_CFLAGS=\\\"),\\$1$EXTRA_CFLAGS ,\" jemalloc/jemalloc.cfg\n  fi\n  for LIB in libvmem libpmem libpmemobj; do\n    # Disable -Werror; it prevents jemalloc from building via clang.\n    #\n    # Add PREFIX/lib to the rpath; libpmemobj depends on libpmem at runtime.\n    EXTRA_CFLAGS=\"$EXTRA_CFLAGS -Wno-error\" \\\n      EXTRA_LDFLAGS=\"$EXTRA_LDFLAGS -Wl,-rpath,$PREFIX/lib\" \\\n      make -j$PARALLEL $EXTRA_MAKEFLAGS DEBUG=0 $LIB\n\n    # NVML doesn't allow configuring PREFIX -- it always installs into\n    # DESTDIR/usr/lib. Additionally, the 'install' target builds all of\n    # the NVML libraries, even though we only need the three libraries above.\n    # So, we manually install the built artifacts.\n    cp -a $NVML_BDIR/src/include/$LIB.h $PREFIX/include\n    cp -a $NVML_BDIR/src/nondebug/$LIB.{so*,a} $PREFIX/lib\n  done\n  popd\n}\n\nbuild_boost() {\n  local BUILD_TYPE=$1\n  pushd $BOOST_SOURCE\n  local TOOLSET=\"\" # By default, use default toolset.\n  # Boost only looks for this file here and in the user's $HOME directory.\n  # To avoid adding this file to the source tree we would have to patch the auto-generated\n  # project-config.jam that is generated by ./bootstrap which is a worse option.\n  # This file is cleaned up before and after the build as to reduce the risk of polluting\n  # the source tree.\n  local USER_JAMFILE=./tools/build/src/user-config.jam\n\n  if [ -e \"$USER_JAMFILE\" ]; then\n    rm $USER_JAMFILE\n  fi\n\n  BOOST_BDIR=$TP_BUILD_DIR/boost-$BOOST_VERSION$MODE_SUFFIX\n\n  # Compile with PIC and set nanosecond resolution for impala compatibility.\n  BOOST_CFLAGS=\"$EXTRA_CFLAGS -fPIC -DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG\"\n  BOOST_CXXFLAGS=\"$EXTRA_CXXFLAGS -fPIC -DBOOST_DATE_TIME_POSIX_TIME_STD_CONFIG\"\n  BOOST_LDFLAGS=\"$EXTRA_LDFLAGS\"\n\n  case $BUILD_TYPE in\n    \"normal\")\n      ;;\n    \"tsan\")\n      BOOST_LDFLAGS=\"-stdlib=libc++ $BOOST_LDFLAGS\"\n      ;;\n    *)\n      echo \"Unknown Boost build type: $BUILD_TYPE\"\n      exit 1\n      ;;\n  esac\n\n  # If CC and CXX are set, set the compiler in user-config.jam.\n  if [ -n \"$CC\" -a -n \"$CXX\" ]; then\n    # Determine the name of the compiler referenced in $CC. This assumes the compiler\n    # prints its name as the first word of the first line, which appears to work for gcc\n    # and clang, even when they're called through ccache.\n    local COMPILER=$($CC --version | awk 'NR==1 {print $1;}')\n\n    # If the compiler binary used was 'cc' and not 'gcc', it will also report\n    # itself as 'cc'. Coerce it to gcc.\n    if [ \"$COMPILER\" = \"cc\" ]; then\n      COMPILER=gcc\n    fi\n\n    TOOLSET=\"toolset=${COMPILER}\"\n    echo \"Using $TOOLSET\"\n    echo \"using ${COMPILER} : : $CXX ;\" > $USER_JAMFILE\n    echo \"User jamfile location: $USER_JAMFILE\"\n    echo \"User jamfile contents:\"\n    cat $USER_JAMFILE\n  fi\n\n  # Build the date_time boost lib.\n  ./bootstrap.sh --prefix=$PREFIX threading=multi --with-libraries=date_time\n  ./b2 clean $TOOLSET --build-dir=\"$BOOST_BDIR\"\n  ./b2 install variant=release link=static,shared --build-dir=\"$BOOST_BDIR\" $TOOLSET -q -d0 \\\n    --debug-configuration \\\n    cflags=\"$BOOST_CFLAGS\" \\\n    cxxflags=\"$BOOST_CXXFLAGS\" \\\n    linkflags=\"$BOOST_LDFLAGS\"\n\n  if [ -e \"$USER_JAMFILE\" ]; then\n    rm $USER_JAMFILE\n  fi\n  popd\n}\n\nbuild_sparsehash() {\n  # This library is header-only, so we just copy the headers\n  pushd $SPARSEHASH_SOURCE\n  rsync -av --delete sparsehash/ $PREFIX/include/sparsehash/\n  popd\n}\n\nbuild_sparsepp() {\n  # This library is header-only, so we just copy the headers\n  pushd $SPARSEPP_SOURCE\n  rsync -av --delete sparsepp/ $PREFIX/include/sparsepp/\n  popd\n}\n\nbuild_thrift() {\n  THRIFT_BDIR=$TP_BUILD_DIR/$THRIFT_NAME$MODE_SUFFIX\n  mkdir -p $THRIFT_BDIR\n  pushd $THRIFT_BDIR\n  rm -Rf CMakeCache.txt CMakeFiles/\n\n  # Thrift depends on bison.\n  #\n  # Configure for a very minimal install - only the C++ client libraries are needed.\n  # Thrift requires C++11 when compiled on Linux against libc++ (see cxxfunctional.h).\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS -std=c++11\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    cmake \\\n    -DBOOST_ROOT=$PREFIX \\\n    -DBUILD_C_GLIB=OFF \\\n    -DBUILD_COMPILER=ON \\\n    -DBUILD_CPP=ON \\\n    -DBUILD_EXAMPLES=OFF \\\n    -DBUILD_HASKELL=OFF \\\n    -DBUILD_JAVA=OFF \\\n    -DBUILD_PYTHON=OFF \\\n    -DBUILD_TESTING=OFF \\\n    -DBUILD_TUTORIALS=OFF \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DCMAKE_INSTALL_PREFIX=$PREFIX \\\n    -DWITH_BOOSTTHREADS=OFF \\\n    -DWITH_LIBEVENT=OFF \\\n    -DWITH_OPENSSL=OFF \\\n    -DWITH_PLUGIN=OFF \\\n    $EXTRA_CMAKE_FLAGS \\\n    $THRIFT_SOURCE\n\n  ${NINJA:-make} -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n\n  # Install fb303.thrift into the share directory.\n  mkdir -p $PREFIX/share/fb303/if\n  cp $THRIFT_SOURCE/contrib/fb303/if/fb303.thrift $PREFIX/share/fb303/if\n}\n\nbuild_bison() {\n  BISON_BDIR=$TP_BUILD_DIR/$BISON_NAME$MODE_SUFFIX\n  mkdir -p $BISON_BDIR\n  pushd $BISON_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $BISON_SOURCE/configure \\\n    --prefix=$PREFIX\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n\nbuild_coredumper() {\n  COREDUMPER_BDIR=$TP_BUILD_DIR/$COREDUMPER_NAME$MODE_SUFFIX\n  mkdir -p $COREDUMPER_BDIR\n  pushd $COREDUMPER_BDIR\n  CFLAGS=\"$EXTRA_CFLAGS\" \\\n    CXXFLAGS=\"$EXTRA_CXXFLAGS\" \\\n    LDFLAGS=\"$EXTRA_LDFLAGS\" \\\n    LIBS=\"$EXTRA_LIBS\" \\\n    $COREDUMPER_SOURCE/configure \\\n    --with-pic \\\n    --prefix=$PREFIX\n  fixup_libtool\n  make -j$PARALLEL $EXTRA_MAKEFLAGS install\n  popd\n}\n", "num_lines": 919}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Script which downloads and builds the thirdparty dependencies\n# only if necessary.\n#\n# In a git repo, this uses git checksum information on the thirdparty\n# tree. Otherwise, it uses a 'stamp file' approach.\n\nset -e\nset -o pipefail\n\nDEPENDENCY_GROUPS=\ncase $1 in\n  \"\")\n    DEPENDENCY_GROUPS=\"common uninstrumented\"\n    ;;\n  \"tsan\")\n    DEPENDENCY_GROUPS=\"common tsan\"\n    ;;\n  \"all\")\n    DEPENDENCY_GROUPS=\"common uninstrumented tsan\"\n    ;;\n  *)\n    echo \"Unknown build configuration: $1\"\n    exit 1\n    ;;\nesac\n\n\nTP_DIR=$(dirname $BASH_SOURCE)\ncd $TP_DIR\n\nNEEDS_BUILD=\nNEEDS_REHASH=\n\nIS_IN_GIT=$(test -e ../.git && echo true || :)\n\nif [ -n \"$IS_IN_GIT\" ]; then\n  # Determine whether this subtree in the git repo has changed since thirdparty\n  # was last built.\n  CUR_THIRDPARTY_HASH=$(cd .. && git ls-tree -d HEAD thirdparty | awk '{print $3}')\n\n  for GROUP in $DEPENDENCY_GROUPS; do\n    LAST_BUILD_HASH=$(cat .build-hash.$GROUP || :)\n    if [ \"$CUR_THIRDPARTY_HASH\" != \"$LAST_BUILD_HASH\" ]; then\n      echo \"Rebuilding thirdparty dependency group '$GROUP': the repository has changed since it was last built.\"\n      echo \"Old git hash: $LAST_BUILD_HASH\"\n      echo \"New build hash: $CUR_THIRDPARTY_HASH\"\n      NEEDS_BUILD=\"$NEEDS_BUILD $GROUP\"\n      NEEDS_REHASH=\"$NEEDS_REHASH $GROUP\"\n    fi\n  done\n\n  if [ -z \"$NEEDS_BUILD\" ]; then\n    # All the hashes matched. Determine whether the developer has any local changes.\n    if ! ( git diff --quiet .  && git diff --cached --quiet . ) ; then\n      echo \"Rebuilding thirdparty dependency groups '$DEPENDENCY_GROUPS': there are local changes in the repository.\"\n      NEEDS_BUILD=\"$DEPENDENCY_GROUPS\"\n    fi\n  fi\n\nelse\n  # If we aren't inside running inside a git repository (e.g. we are\n  # part of a source distribution tarball) then we can't use git to find\n  # out whether the build is clean. Instead, look at the ctimes of special\n  # stamp files, and see if any files inside this directory have been\n  # modified since then.\n  for GROUP in $DEPENDENCY_GROUPS; do\n    STAMP_FILE=.build-stamp.$GROUP\n    if [ -f $STAMP_FILE ]; then\n      CHANGED_FILE_COUNT=$(find . -cnewer $STAMP_FILE | wc -l)\n      echo \"$CHANGED_FILE_COUNT file(s) been modified since thirdparty dependency group '$GROUP' was last built.\"\n      if [ $CHANGED_FILE_COUNT -gt 0 ]; then\n        echo \"Rebuilding.\"\n        NEEDS_BUILD=\"$NEEDS_BUILD $GROUP\"\n      fi\n    else\n      echo \"It appears that thirdparty dependency group '$GROUP' was never built. Building.\"\n      NEEDS_BUILD=\"$NEEDS_BUILD $GROUP\"\n    fi\n  done\nfi\n\nif [ -z \"$NEEDS_BUILD\" ]; then\n  echo \"Not rebuilding thirdparty. No changes since last build.\"\n  exit 0\nfi\n\n# Remove the old hashes/stamps before building so that if the build is aborted\n# and the repository is taken backwards in time to the point where the old\n# hashes/stamps matched, the repository would still be rebuilt.\nfor GROUP in $NEEDS_BUILD; do\n  rm -f .build-hash.$GROUP .build-stamp.$GROUP\ndone\n\n# Download and build the necessary dependency groups.\n./download-thirdparty.sh\n./build-thirdparty.sh $NEEDS_BUILD\n\n# The build succeeded. Update the appropriate hashes/stamps.\nif [ -n \"$IS_IN_GIT\" ]; then\n  for GROUP in $NEEDS_REHASH; do\n    echo $CUR_THIRDPARTY_HASH > .build-hash.$GROUP\n  done\nelse\n  for GROUP in $NEEDS_BUILD; do\n    touch .build-stamp.$GROUP\n  done\nfi\n", "num_lines": 127}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# build-thirdparty.sh builds and installs thirdparty dependencies into prefix\n# directories within the thirdparty directory. Three prefix directories are\n# used, corresponding to build type:\n#\n#   * /thirdparty/installed/common - prefix directory for libraries and binary tools\n#                                    common to all build types, e.g. CMake, C dependencies.\n#   * /thirdparty/installed/uninstrumented - prefix directory for libraries built with\n#                                            normal options (no sanitizer instrumentation).\n#   * /thirdparty/installed/tsan - prefix directory for libraries built\n#                                  with thread sanitizer instrumentation.\n#\n# Environment variables which can be set when calling build-thirdparty.sh:\n#   * EXTRA_CFLAGS - additional flags passed to the C compiler.\n#   * EXTRA_CXXFLAGS - additional flags passed to the C++ compiler.\n#   * EXTRA_LDFLAGS - additional flags passed to the linker.\n#   * EXTRA_LIBS - additional libraries to link.\n#   * EXTRA_MAKEFLAGS - additional flags passed to make.\n#   * PARALLEL - parallelism to use when compiling (defaults to number of cores).\n\nset -ex\n\nTP_DIR=$(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd)\n\nsource $TP_DIR/vars.sh\nsource $TP_DIR/build-definitions.sh\n\n# Before doing anything, run the pre-flight check for missing dependencies.\n# This avoids the most common issues people have with building (if they don't\n# read the docs)\n$TP_DIR/preflight.py\n\n################################################################################\n\nif [ \"$#\" = \"0\" ]; then\n  ARGS_TO_PRINT=\"common uninstrumented tsan\"\n\n  F_COMMON=1\n  F_UNINSTRUMENTED=1\n  F_TSAN=1\nelse\n  ARGS_TO_PRINT=\"$*\"\n  REQUESTED_EXPLICIT_DEPENDENCIES=1\n\n  # Parse the command line for specific dependencies or dependency groups.\n  for arg in $*; do\n    case $arg in\n      # Dependency groups.\n      \"common\")         F_COMMON=1 ;;\n      \"uninstrumented\") F_UNINSTRUMENTED=1 ;;\n      \"tsan\")           F_TSAN=1 ;;\n\n      # Dependencies.\n      \"cmake\")        F_CMAKE=1 ;;\n      \"gflags\")       F_GFLAGS=1 ;;\n      \"glog\")         F_GLOG=1 ;;\n      \"gmock\")        F_GMOCK=1 ;;\n      \"gperftools\")   F_GPERFTOOLS=1 ;;\n      \"libev\")        F_LIBEV=1 ;;\n      \"lz4\")          F_LZ4=1 ;;\n      \"bitshuffle\")   F_BITSHUFFLE=1 ;;\n      \"protobuf\")     F_PROTOBUF=1 ;;\n      \"rapidjson\")    F_RAPIDJSON=1 ;;\n      \"snappy\")       F_SNAPPY=1 ;;\n      \"zlib\")         F_ZLIB=1 ;;\n      \"squeasel\")     F_SQUEASEL=1 ;;\n      \"mustache\")     F_MUSTACHE=1 ;;\n      \"gsg\")          F_GSG=1 ;;\n      \"gcovr\")        F_GCOVR=1 ;;\n      \"curl\")         F_CURL=1 ;;\n      \"crcutil\")      F_CRCUTIL=1 ;;\n      \"libunwind\")    F_LIBUNWIND=1 ;;\n      \"llvm\")         F_LLVM=1 ;;\n      \"trace-viewer\") F_TRACE_VIEWER=1 ;;\n      \"nvml\")         F_NVML=1 ;;\n      \"boost\")        F_BOOST=1 ;;\n      \"breakpad\")     F_BREAKPAD=1 ;;\n      \"sparsehash\")   F_SPARSEHASH=1 ;;\n      \"sparsepp\")     F_SPARSEPP=1 ;;\n      \"thrift\")       F_THRIFT=1 ;;\n      \"bison\")        F_BISON=1 ;;\n      \"hadoop\")       F_HADOOP=1 ;;\n      \"hive\")         F_HIVE=1 ;;\n      \"sentry\")       F_SENTRY=1 ;;\n      \"coredumper\")   F_COREDUMPER=1 ;;\n      *)              echo \"Unknown module: $arg\"; exit 1 ;;\n    esac\n  done\nfi\n\n################################################################################\n\nfinish() {\n  # Run the post-flight checks.\n  $TP_DIR/postflight.py\n\n  echo \"---------------------\"\n  echo \"Thirdparty dependencies '$ARGS_TO_PRINT' built and installed successfully\"\n  exit 0\n}\n\nfor PREFIX_DIR in $PREFIX_COMMON $PREFIX_DEPS $PREFIX_DEPS_TSAN; do\n  mkdir -p $PREFIX_DIR/include\n\n  # PREFIX_COMMON is for header-only libraries.\n  if [ \"$PREFIX_DIR\" != \"$PREFIX_COMMON\" ]; then\n    mkdir -p $PREFIX_DIR/lib\n\n    # On some systems, autotools installs libraries to lib64 rather than lib.  Fix\n    # this by setting up lib64 as a symlink to lib.  We have to do this step first\n    # to handle cases where one third-party library depends on another.\n    ln -nsf \"$PREFIX_DIR/lib\" \"$PREFIX_DIR/lib64\"\n  fi\ndone\n\n# Incorporate the value of these standard compilation environment variables into\n# the EXTRA_* environment variables.\nEXTRA_CFLAGS=\"$CFLAGS $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"$CXXFLAGS $EXTRA_CXXFLAGS\"\nEXTRA_LDFLAGS=\"$LDFLAGS $EXTRA_LDFLAGS\"\nEXTRA_LIBS=\"$LIBS $EXTRA_LIBS\"\n\n# We use -O2 instead of -O3 for thirdparty since benchmarks indicate\n# that the benefits of a smaller code size outweight the benefits of\n# more inlining.\n#\n# We also enable -fno-omit-frame-pointer so that profiling tools which\n# use frame-pointer based stack unwinding can function correctly.\nEXTRA_CFLAGS=\"-fno-omit-frame-pointer $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-fno-omit-frame-pointer -O2 $EXTRA_CXXFLAGS\"\n\nif [[ \"$OSTYPE\" =~ ^linux ]]; then\n  OS_LINUX=1\n  DYLIB_SUFFIX=\"so\"\n  PARALLEL=${PARALLEL:-$(grep -c processor /proc/cpuinfo)}\n\n  if [ -d \"$OPENSSL_WORKAROUND_DIR\" ]; then\n    # If the el6 workaround openssl is present, we must build dependencies\n    # against that version of openssl, not the system version, because at test\n    # runtime we use the workaround openssl.\n    OPENSSL_CFLAGS=\"-I$OPENSSL_WORKAROUND_DIR/usr/include\"\n    OPENSSL_LDFLAGS=\"-L$OPENSSL_WORKAROUND_DIR/usr/lib64 -Wl,-rpath,$OPENSSL_WORKAROUND_DIR/usr/lib64\"\n  fi\nelif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  OS_OSX=1\n  DYLIB_SUFFIX=\"dylib\"\n  PARALLEL=${PARALLEL:-$(sysctl -n hw.ncpu)}\n\n  # Kudu builds with C++11, which on OS X requires using libc++ as the standard\n  # library implementation. Some of the dependencies do not compile against\n  # libc++ by default, so we specify it explicitly.\n  EXTRA_CXXFLAGS=\"$EXTRA_CXXFLAGS -stdlib=libc++\"\n  EXTRA_LDFLAGS=\"$EXTRA_LDFLAGS -stdlib=libc++\"\n  EXTRA_LIBS=\"$EXTRA_LIBS -lc++ -lc++abi\"\n\n  # Build against the Macports or Homebrew OpenSSL versions, in order to match\n  # the Kudu build.\n  if ! OPENSSL_CFLAGS=$(pkg-config --cflags openssl); then\n    # If OpenSSL is built via Homebrew, pkg-config does not report on cflags.\n    homebrew_openssl_dir=/usr/local/opt/openssl\n    if [ -d $homebrew_openssl_dir ]; then\n      OPENSSL_CFLAGS=\"-I$homebrew_openssl_dir/include\"\n      OPENSSL_LDFLAGS=\"-L$homebrew_openssl_dir/lib\"\n    fi\n  fi\n\n  # TSAN doesn't work on macOS. If it was explicitly asked for, respond with an\n  # error. Otherwise, just disable it silently.\n  if [ -n \"$F_TSAN\" ]; then\n    if [ -n \"$REQUESTED_EXPLICIT_DEPENDENCIES\" ]; then\n      echo TSAN does not work on macOS\n      exit 1\n    else\n      unset F_TSAN\n    fi\n  fi\nelse\n  echo Unsupported platform $OSTYPE\n  exit 1\nfi\n\n### Detect and enable 'ninja' instead of 'make' for faster builds.\nif which ninja-build > /dev/null ; then\n  NINJA=ninja-build\n  EXTRA_CMAKE_FLAGS=-GNinja\nelif which ninja > /dev/null ; then\n  NINJA=ninja\n  EXTRA_CMAKE_FLAGS=-GNinja\nfi\n\n### Build common tools and header-only libraries\n\nPREFIX=$PREFIX_COMMON\nMODE_SUFFIX=\"\"\n\n# Add tools to path\nexport PATH=$PREFIX/bin:$PATH\n\n: '\nif [ -n \"$F_COMMON\" -o -n \"$F_CMAKE\" ]; then\n  build_cmake\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_RAPIDJSON\" ]; then\n  build_rapidjson\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_GSG\" ]; then\n  build_cpplint\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_GCOVR\" ]; then\n  build_gcovr\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_TRACE_VIEWER\" ]; then\n  build_trace_viewer\nfi\n'\n\nif [ -n \"$F_COMMON\" -o -n \"$F_SPARSEHASH\" ]; then\n  build_sparsehash\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_SPARSEPP\" ]; then\n  build_sparsepp\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_BISON\" ]; then\n  build_bison\nfi\n\n: '\n# Install Hadoop, Hive, and Sentry by symlinking their source directories (which\n# are pre-built) into $PREFIX/opt.\nif [ -n \"$F_COMMON\" -o -n \"$F_HADOOP\" ]; then\n  mkdir -p $PREFIX/opt\n  ln -nsf $HADOOP_SOURCE $PREFIX/opt/hadoop\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_HIVE\" ]; then\n  mkdir -p $PREFIX/opt\n  ln -nsf $HIVE_SOURCE $PREFIX/opt/hive\nfi\n\nif [ -n \"$F_COMMON\" -o -n \"$F_SENTRY\" ]; then\n  mkdir -p $PREFIX/opt\n  ln -nsf $SENTRY_SOURCE $PREFIX/opt/sentry\nfi\n'\n\n### Build C dependencies without instrumentation\n\nPREFIX=$PREFIX_DEPS\nMODE_SUFFIX=\"\"\n\nsave_env\n\n# Enable debug symbols so that stacktraces and linenumbers are available at runtime.\nEXTRA_CFLAGS=\"-g $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-g $EXTRA_CXXFLAGS\"\n\nif [ -n \"$OS_LINUX\" ] && [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_LIBUNWIND\" ]; then\n  build_libunwind\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_ZLIB\" ]; then\n  build_zlib\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_LZ4\" ]; then\n  build_lz4\nfi\n\n: '\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_BITSHUFFLE\" ]; then\n  build_bitshuffle\nfi\n'\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_LIBEV\" ]; then\n  build_libev\nfi\n\n: '\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_SQUEASEL\" ]; then\n  build_squeasel\nfi\n'\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_CURL\" ]; then\n  build_curl\nfi\n\n: '\nif [ -n \"$OS_LINUX\" ] && [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_NVML\" ]; then\n  build_nvml\nfi\n'\n\nrestore_env\n\n### Build C++ dependencies without instrumentation\n: '\n# Clang is used by all builds so it is part of the 'common' library group even\n# though its LLVM libraries are installed to $PREFIX_DEPS.\nif [ -n \"$F_COMMON\" -o -n \"$F_LLVM\" ]; then\n  build_llvm normal\nfi\n'\n\nsave_env\n\n# Enable debug symbols so that stacktraces and linenumbers are available at\n# runtime. LLVM is compiled without debug symbols as they take up more than\n# 20GiB of disk space.\nEXTRA_CFLAGS=\"-g $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-g $EXTRA_CXXFLAGS\"\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_GFLAGS\" ]; then\n  build_gflags\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_GLOG\" ]; then\n  build_glog\nfi\n\n: '\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_GPERFTOOLS\" ]; then\n  build_gperftools\nfi\n'\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_GMOCK\" ]; then\n  build_gmock\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_PROTOBUF\" ]; then\n  build_protobuf\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_SNAPPY\" ]; then\n  build_snappy\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_CRCUTIL\" ]; then\n  build_crcutil\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_BOOST\" ]; then\n  build_boost normal\nfi\n\n: '\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_MUSTACHE\" ]; then\n  build_mustache\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_BREAKPAD\" ]; then\n  build_breakpad\nfi\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_THRIFT\" ]; then\n  build_thrift\nfi\n'\n\nif [ -n \"$F_UNINSTRUMENTED\" -o -n \"$F_COREDUMPER\" ]; then\n  build_coredumper\nfi\n\nrestore_env\n\n# If we're on macOS best to exit here, otherwise single dependency builds will try to\n# build the tsan version of the dependency (and fail).\n\nif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  echo \"Not building tsan dependencies on macOS.\"\n  finish\nfi\n\n### Build dependencies with TSAN instrumentation\n\n# Achieving good results with TSAN requires that:\n# 1. The C++ standard library should be instrumented with TSAN.\n# 2. Dependencies which internally use threads or synchronization be\n#    instrumented with TSAN.\n# 3. As a corollary to 1, the C++ standard library requires that all shared\n#    objects linked into an executable be built against the same version of the\n#    C++ standard library version.\n#\n# At the very least, we must build our own C++ standard library. We use libc++\n# because it's easy to build with clang, which has better TSAN support than gcc.\n#\n# To satisfy all of the above requirements, we first build libc++ instrumented\n# with TSAN, then build a second copy of every C++ dependency against that\n# libc++. Later on in the build process, Kudu is also built against libc++.\n#\n# Special flags for TSAN builds:\n#   * -fsanitize=thread -  enable the thread sanitizer during compilation.\n#   * -L ... - add the instrumented libc++ to the library search paths.\n#   * -isystem ... - Add libc++ headers to the system header search paths.\n#   * -nostdinc++ - Do not automatically link the system C++ standard library.\n#   * -Wl,-rpath,... - Add instrumented libc++ location to the rpath so that it\n#                      can be found at runtime.\n\nif which ccache >/dev/null ; then\n  CLANG=\"$TP_DIR/../build-support/ccache-clang/clang\"\n  CLANGXX=\"$TP_DIR/../build-support/ccache-clang/clang++\"\nelse\n  CLANG=\"$TP_DIR/clang-toolchain/bin/clang\"\n  CLANGXX=\"$TP_DIR/clang-toolchain/bin/clang++\"\nfi\nexport CC=$CLANG\nexport CXX=$CLANGXX\n\nPREFIX=$PREFIX_DEPS_TSAN\nMODE_SUFFIX=\".tsan\"\n\nsave_env\n\n# Build the C (non-C++) dependencies with TSAN instrumentation.\nEXTRA_CFLAGS=\"-fsanitize=thread $EXTRA_CFLAGS\"\n\n# Enable debug symbols so that stacktraces and linenumbers are available at runtime.\nEXTRA_CFLAGS=\"-g $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-g $EXTRA_CXXFLAGS\"\n\nif [ -n \"$F_TSAN\" -o -n \"$F_ZLIB\" ]; then\n  build_zlib\nfi\n\nif [ -n \"$OS_LINUX\" ] && [ -n \"$F_TSAN\" -o -n \"$F_LIBUNWIND\" ]; then\n  build_libunwind\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_LZ4\" ]; then\n  build_lz4\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_BITSHUFFLE\" ]; then\n  build_bitshuffle\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_LIBEV\" ]; then\n  build_libev\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_SQUEASEL\" ]; then\n  build_squeasel\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_CURL\" ]; then\n  build_curl\nfi\n\nif [ -n \"$OS_LINUX\" ] && [ -n \"$F_TSAN\" -o -n \"$F_NVML\" ]; then\n  build_nvml\nfi\n\nrestore_env\n\n### Build C++ dependencies with TSAN instrumentation\n\n# Build libc++abi first as it is a dependency for libc++. Its build has no\n# built-in support for sanitizers, so we build it regularly.\nif [ -n \"$F_TSAN\" -o -n \"$F_LLVM\" ]; then\n  build_libcxxabi\nfi\n\nsave_env\n\n# Build libc++ with TSAN enabled.\nif [ -n \"$F_TSAN\" -o -n \"$F_LLVM\" ]; then\n  build_libcxx tsan\nfi\n\n# Build the rest of the dependencies against the TSAN-instrumented libc++\n# instead of the system's C++ standard library.\nEXTRA_CXXFLAGS=\"-isystem $PREFIX/include/c++/v1 $EXTRA_CXXFLAGS\"\nEXTRA_LDFLAGS=\"-L$PREFIX/lib $EXTRA_LDFLAGS\"\nEXTRA_LDFLAGS=\"-Wl,-rpath,$PREFIX/lib $EXTRA_LDFLAGS\"\n\n# Build the rest of the dependencies with TSAN instrumentation.\nEXTRA_CFLAGS=\"-fsanitize=thread $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-fsanitize=thread $EXTRA_CXXFLAGS\"\nEXTRA_CXXFLAGS=\"-DTHREAD_SANITIZER $EXTRA_CXXFLAGS\"\n\nif [ -n \"$F_TSAN\" -o -n \"$F_LLVM\" ]; then\n  build_llvm tsan\nfi\n\n# LLVM is told to use libc++ explicitly and thus doesn't need these, but the\n# rest of the dependencies need them.\n#\n# Note: -nostdinc++ is necessary to prevent C++ headers from using #include_next\n# to chain the host's C++ headers. However, using it means we need to also use\n# -Qunused-arguments because clang raises an unused argument warning when it\n# detects -nostdinc++ on a link line, and there's no way to prevent that when\n# passing -nostdinc++ to cmake via -DCMAKE_CXX_FLAGS [1].\n#\n# 1. https://gitlab.kitware.com/cmake/cmake/issues/12652\nEXTRA_CXXFLAGS=\"-Qunused-arguments -nostdinc++ $EXTRA_CXXFLAGS\"\nEXTRA_LDFLAGS=\"-stdlib=libc++ $EXTRA_LDFLAGS\"\n\n# Enable debug symbols so that stacktraces and linenumbers are available at\n# runtime. LLVM is compiled without debug symbols because the LLVM debug symbols\n# take up more than 20GiB of disk space.\nEXTRA_CFLAGS=\"-g $EXTRA_CFLAGS\"\nEXTRA_CXXFLAGS=\"-g $EXTRA_CXXFLAGS\"\n\nif [ -n \"$F_TSAN\" -o -n \"$F_PROTOBUF\" ]; then\n  build_protobuf\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_GFLAGS\" ]; then\n  build_gflags\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_GLOG\" ]; then\n  build_glog\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_GMOCK\" ]; then\n  build_gmock\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_SNAPPY\" ]; then\n  build_snappy\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_CRCUTIL\" ]; then\n  build_crcutil\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_BOOST\" ]; then\n  build_boost tsan\nfi\n\n: '\nif [ -n \"$F_TSAN\" -o -n \"$F_MUSTACHE\" ]; then\n  build_mustache\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_BREAKPAD\" ]; then\n  build_breakpad\nfi\n\nif [ -n \"$F_TSAN\" -o -n \"$F_THRIFT\" ]; then\n  build_thrift\nfi\n'\n\nif [ -n \"$F_TSAN\" -o -n \"$F_COREDUMPER\" ]; then\n  build_coredumper\nfi\n\nrestore_env\n\nfinish\n", "num_lines": 579}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# autoreconf calls are necessary to fix hard-coded aclocal versions in the\n# configure scripts that ship with the projects.\n\nset -e\n\nTP_DIR=$(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd)\n\nsource $TP_DIR/vars.sh\n\nif [[ \"$OSTYPE\" =~ ^linux ]]; then\n  OS_LINUX=1\nfi\n\ndelete_if_wrong_patchlevel() {\n  local DIR=$1\n  local PATCHLEVEL=$2\n  if [ ! -f $DIR/patchlevel-$PATCHLEVEL ]; then\n    echo It appears that $DIR is missing the latest local patches.\n    echo Removing it so we re-download it.\n    rm -Rf $DIR\n  fi\n}\n\nunzip_to_source() {\n  local FILENAME=$1\n  local SOURCE=$2\n  unzip -q \"$FILENAME\"\n  # Parse out the unzipped top directory\n  DIR_NAME=`unzip -qql \"$FILENAME\" | awk 'NR==1 {print $4}' | sed -e 's|^[/]*\\([^/]*\\).*|\\1|'`\n  # If the unzipped directory is the wrong name, move it.\n  if [ \"$SOURCE\" != \"$TP_SOURCE_DIR/$DIR_NAME\" ]; then\n    mv \"$TP_SOURCE_DIR/$DIR_NAME\" \"$SOURCE\"\n  fi\n}\n\nfetch_and_expand() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local URL_PREFIX=$3\n\n  if [ -z \"$FILENAME\" ]; then\n    echo \"Error: Must specify file to fetch\"\n    exit 1\n  fi\n\n  if [ -z \"$URL_PREFIX\" ]; then\n    echo \"Error: Must specify url prefix to fetch\"\n    exit 1\n  fi\n\n  TAR_CMD=tar\n  if [[ \"$OSTYPE\" == \"darwin\"* ]] && which gtar &>/dev/null; then\n    TAR_CMD=gtar\n  fi\n\n  FULL_URL=\"${URL_PREFIX}/${FILENAME}\"\n\n  SUCCESS=0\n  # Loop in case we encounter an error.\n  for attempt in 1 2 3; do\n    if [ -r \"$FILENAME\" ]; then\n      echo \"Archive $FILENAME already exists. Not re-downloading archive.\"\n    else\n      echo \"Fetching $FILENAME from $FULL_URL\"\n      if ! curl --retry 3 -L -O \"$FULL_URL\"; then\n        echo \"Error downloading $FILENAME\"\n        rm -f \"$FILENAME\"\n\n        # Pause for a bit before looping in case the server throttled us.\n        sleep 5\n        continue\n      fi\n    fi\n\n    echo \"Unpacking $FILENAME to $SOURCE\"\n    if [[ \"$FILENAME\" =~ \\.zip$ ]]; then\n      if ! unzip_to_source \"$FILENAME\" \"$SOURCE\"; then\n        echo \"Error unzipping $FILENAME, removing file\"\n        rm \"$FILENAME\"\n        continue\n      fi\n    elif [[ \"$FILENAME\" =~ \\.(tar\\.gz|tgz)$ ]]; then\n      if ! $TAR_CMD xf \"$FILENAME\"; then\n        echo \"Error untarring $FILENAME, removing file\"\n        rm \"$FILENAME\"\n        continue\n      fi\n    else\n      echo \"Error: unknown file format: $FILENAME\"\n      exit 1\n    fi\n\n    SUCCESS=1\n    break\n  done\n\n  if [ $SUCCESS -ne 1 ]; then\n    echo \"Error: failed to fetch and unpack $FILENAME\"\n    exit 1\n  fi\n\n  # Allow for not removing previously-downloaded artifacts.\n  # Useful on a low-bandwidth connection.\n  if [ -z \"$NO_REMOVE_THIRDPARTY_ARCHIVES\" ]; then\n    echo \"Removing $FILENAME\"\n    rm $FILENAME\n  fi\n  echo\n}\n\nfetch_with_url_and_patch() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local PATCH_LEVEL=$3\n  local URL_PREFIX=$4\n  # Remaining args are expected to be a list of patch commands\n\n  delete_if_wrong_patchlevel $SOURCE $PATCH_LEVEL\n  if [ ! -d $SOURCE ]; then\n    fetch_and_expand $FILENAME $SOURCE $URL_PREFIX\n    pushd $SOURCE\n    shift 4\n    # Run the patch commands\n    for f in \"$@\"; do\n      eval \"$f\"\n    done\n    touch patchlevel-$PATCH_LEVEL\n    popd\n    echo\n  fi\n}\n\n# Call fetch_with_url_and_patch with the default dependency URL source.\nfetch_and_patch() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local PATCH_LEVEL=$3\n\n  shift 3\n  fetch_with_url_and_patch \\\n    $FILENAME \\\n    $SOURCE \\\n    $PATCH_LEVEL \\\n    $DEPENDENCY_URL \\\n    \"$@\"\n}\n\nmkdir -p $TP_SOURCE_DIR\ncd $TP_SOURCE_DIR\n\n#GPERFTOOLS_PATCHLEVEL=2\n#fetch_and_patch \\\n# gperftools-${GPERFTOOLS_VERSION}.tar.gz \\\n# $GPERFTOOLS_SOURCE \\\n# $GPERFTOOLS_PATCHLEVEL \\\n# \"patch -p1 < $TP_DIR/patches/gperftools-Replace-namespace-base-with-namespace-tcmalloc.patch\" \\\n# \"patch -p1 < $TP_DIR/patches/gperftools-unbreak-memz.patch\" \\\n# \"autoreconf -fvi\"\n\nRAPIDJSON_PATCHLEVEL=0\nfetch_and_patch \\\n rapidjson-${RAPIDJSON_VERSION}.zip \\\n $RAPIDJSON_SOURCE \\\n $RAPIDJSON_PATCHLEVEL\n\necho \"---------------\"\necho \"Thirdparty dependencies downloaded successfully\"\n", "num_lines": 187}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# autoreconf calls are necessary to fix hard-coded aclocal versions in the\n# configure scripts that ship with the projects.\n\nset -e\n\nTP_DIR=$(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd)\n\nsource $TP_DIR/vars.sh\n\nif [[ \"$OSTYPE\" =~ ^linux ]]; then\n  OS_LINUX=1\nfi\n\ndelete_if_wrong_patchlevel() {\n  local DIR=$1\n  local PATCHLEVEL=$2\n  if [ ! -f $DIR/patchlevel-$PATCHLEVEL ]; then\n    echo It appears that $DIR is missing the latest local patches.\n    echo Removing it so we re-download it.\n    rm -Rf $DIR\n  fi\n}\n\nunzip_to_source() {\n  local FILENAME=$1\n  local SOURCE=$2\n  unzip -q \"$FILENAME\"\n  # Parse out the unzipped top directory\n  DIR_NAME=`unzip -qql \"$FILENAME\" | awk 'NR==1 {print $4}' | sed -e 's|^[/]*\\([^/]*\\).*|\\1|'`\n  # If the unzipped directory is the wrong name, move it.\n  if [ \"$SOURCE\" != \"$TP_SOURCE_DIR/$DIR_NAME\" ]; then\n    mv \"$TP_SOURCE_DIR/$DIR_NAME\" \"$SOURCE\"\n  fi\n}\n\nfetch_and_expand() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local URL_PREFIX=$3\n\n  if [ -z \"$FILENAME\" ]; then\n    echo \"Error: Must specify file to fetch\"\n    exit 1\n  fi\n\n  if [ -z \"$URL_PREFIX\" ]; then\n    echo \"Error: Must specify url prefix to fetch\"\n    exit 1\n  fi\n\n  TAR_CMD=tar\n  if [[ \"$OSTYPE\" == \"darwin\"* ]] && which gtar &>/dev/null; then\n    TAR_CMD=gtar\n  fi\n\n  FULL_URL=\"${URL_PREFIX}/${FILENAME}\"\n\n  SUCCESS=0\n  # Loop in case we encounter an error.\n  for attempt in 1 2 3; do\n    if [ -r \"$FILENAME\" ]; then\n      echo \"Archive $FILENAME already exists. Not re-downloading archive.\"\n    else\n      echo \"Fetching $FILENAME from $FULL_URL\"\n      if ! curl --retry 3 -L -O \"$FULL_URL\"; then\n        echo \"Error downloading $FILENAME\"\n        rm -f \"$FILENAME\"\n\n        # Pause for a bit before looping in case the server throttled us.\n        sleep 5\n        continue\n      fi\n    fi\n\n    echo \"Unpacking $FILENAME to $SOURCE\"\n    if [[ \"$FILENAME\" =~ \\.zip$ ]]; then\n      if ! unzip_to_source \"$FILENAME\" \"$SOURCE\"; then\n        echo \"Error unzipping $FILENAME, removing file\"\n        rm \"$FILENAME\"\n        continue\n      fi\n    elif [[ \"$FILENAME\" =~ \\.(tar\\.gz|tgz)$ ]]; then\n      if ! $TAR_CMD xf \"$FILENAME\"; then\n        echo \"Error untarring $FILENAME, removing file\"\n        rm \"$FILENAME\"\n        continue\n      fi\n    else\n      echo \"Error: unknown file format: $FILENAME\"\n      exit 1\n    fi\n\n    SUCCESS=1\n    break\n  done\n\n  if [ $SUCCESS -ne 1 ]; then\n    echo \"Error: failed to fetch and unpack $FILENAME\"\n    exit 1\n  fi\n\n  # Allow for not removing previously-downloaded artifacts.\n  # Useful on a low-bandwidth connection.\n  if [ -z \"$NO_REMOVE_THIRDPARTY_ARCHIVES\" ]; then\n    echo \"Removing $FILENAME\"\n    rm $FILENAME\n  fi\n  echo\n}\n\nfetch_with_url_and_patch() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local PATCH_LEVEL=$3\n  local URL_PREFIX=$4\n  # Remaining args are expected to be a list of patch commands\n\n  delete_if_wrong_patchlevel $SOURCE $PATCH_LEVEL\n  if [ ! -d $SOURCE ]; then\n    fetch_and_expand $FILENAME $SOURCE $URL_PREFIX\n    pushd $SOURCE\n    shift 4\n    # Run the patch commands\n    for f in \"$@\"; do\n      eval \"$f\"\n    done\n    touch patchlevel-$PATCH_LEVEL\n    popd\n    echo\n  fi\n}\n\n# Call fetch_with_url_and_patch with the default dependency URL source.\nfetch_and_patch() {\n  local FILENAME=$1\n  local SOURCE=$2\n  local PATCH_LEVEL=$3\n\n  shift 3\n  fetch_with_url_and_patch \\\n    $FILENAME \\\n    $SOURCE \\\n    $PATCH_LEVEL \\\n    $DEPENDENCY_URL \\\n    \"$@\"\n}\n\nmkdir -p $TP_SOURCE_DIR\ncd $TP_SOURCE_DIR\n\nGLOG_PATCHLEVEL=3\nfetch_and_patch \\\n glog-${GLOG_VERSION}.tar.gz \\\n $GLOG_SOURCE \\\n $GLOG_PATCHLEVEL \\\n \"patch -p0 < $TP_DIR/patches/glog-issue-198-fix-unused-warnings.patch\" \\\n \"patch -p0 < $TP_DIR/patches/glog-issue-54-dont-build-tests.patch\" \\\n \"patch -p1 < $TP_DIR/patches/glog-fix-symbolization.patch\" \\\n \"autoreconf -fvi\"\n\nGMOCK_PATCHLEVEL=0\nfetch_and_patch \\\n googletest-release-${GMOCK_VERSION}.tar.gz \\\n $GMOCK_SOURCE \\\n $GMOCK_PATCHLEVEL\n\nGFLAGS_PATCHLEVEL=0\nfetch_and_patch \\\n gflags-${GFLAGS_VERSION}.tar.gz \\\n $GFLAGS_SOURCE \\\n $GFLAGS_PATCHLEVEL\n\n: '\nGPERFTOOLS_PATCHLEVEL=2\nfetch_and_patch \\\n gperftools-${GPERFTOOLS_VERSION}.tar.gz \\\n $GPERFTOOLS_SOURCE \\\n $GPERFTOOLS_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/gperftools-Replace-namespace-base-with-namespace-tcmalloc.patch\" \\\n \"patch -p1 < $TP_DIR/patches/gperftools-unbreak-memz.patch\" \\\n \"autoreconf -fvi\"\n'\n\nPROTOBUF_PATCHLEVEL=0\nfetch_and_patch \\\n protobuf-${PROTOBUF_VERSION}.tar.gz \\\n $PROTOBUF_SOURCE \\\n $PROTOBUF_PATCHLEVEL \\\n \"autoreconf -fvi\"\n\n# Returns 0 if cmake should be patched to work around this bug [1].\n#\n# Currently only SLES 12 SP0 is known to be vulnerable, and since the workaround\n# hurts cmake performance, we apply it only if absolutely necessary.\n#\n# 1. https://gitlab.kitware.com/cmake/cmake/issues/15873.\nneeds_patched_cmake() {\n  if [ ! -e /etc/SuSE-release ]; then\n    # Not a SUSE distro.\n    return 1\n  fi\n  if ! grep -q \"SUSE Linux Enterprise Server 12\" /etc/SuSE-release; then\n    # Not SLES 12.\n    return 1\n  fi\n  if ! grep -q \"PATCHLEVEL = 0\" /etc/SuSE-release; then\n    # Not SLES 12 SP0.\n    return 1\n  fi\n  return 0\n}\n\n: '\nCMAKE_PATCHLEVEL=1\nCMAKE_PATCHES=\"\"\nif needs_patched_cmake; then \\\n CMAKE_PATCHES=\"patch -p1 < $TP_DIR/patches/cmake-issue-15873-dont-use-select.patch\"\nfi\n\nfetch_and_patch \\\n cmake-${CMAKE_VERSION}.tar.gz \\\n $CMAKE_SOURCE \\\n $CMAKE_PATCHLEVEL \\\n \"$CMAKE_PATCHES\"\n'\n\nSNAPPY_PATCHLEVEL=0\nfetch_and_patch \\\n snappy-${SNAPPY_VERSION}.tar.gz \\\n $SNAPPY_SOURCE \\\n $SNAPPY_PATCHLEVEL \\\n \"autoreconf -fvi\"\n\nZLIB_PATCHLEVEL=0\nfetch_and_patch \\\n zlib-${ZLIB_VERSION}.tar.gz \\\n $ZLIB_SOURCE \\\n $ZLIB_PATCHLEVEL\n\nLIBEV_PATCHLEVEL=0\nfetch_and_patch \\\n libev-${LIBEV_VERSION}.tar.gz \\\n $LIBEV_SOURCE \\\n $LIBEV_PATCHLEVEL\n\n: '\nRAPIDJSON_PATCHLEVEL=0\nfetch_and_patch \\\n rapidjson-${RAPIDJSON_VERSION}.zip \\\n $RAPIDJSON_SOURCE \\\n $RAPIDJSON_PATCHLEVEL\n\nSQUEASEL_PATCHLEVEL=0\nfetch_and_patch \\\n squeasel-${SQUEASEL_VERSION}.tar.gz \\\n $SQUEASEL_SOURCE \\\n $SQUEASEL_PATCHLEVEL\n\nMUSTACHE_PATCHLEVEL=0\nfetch_and_patch \\\n mustache-${MUSTACHE_VERSION}.tar.gz \\\n $MUSTACHE_SOURCE \\\n $MUSTACHE_PATCHLEVEL\n\nGSG_PATCHLEVEL=1\nfetch_and_patch \\\n google-styleguide-${GSG_VERSION}.tar.gz \\\n $GSG_SOURCE \\\n $GSG_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/google-styleguide-cpplint.patch\"\n\nGCOVR_PATCHLEVEL=0\nfetch_and_patch \\\n gcovr-${GCOVR_VERSION}.tar.gz \\\n $GCOVR_SOURCE \\\n $GCOVR_PATCHLEVEL\n'\n\nCURL_PATCHLEVEL=0\nfetch_and_patch \\\n curl-${CURL_VERSION}.tar.gz \\\n $CURL_SOURCE \\\n $CURL_PATCHLEVEL \\\n \"autoreconf -fvi\"\n\nCRCUTIL_PATCHLEVEL=1\nfetch_and_patch \\\n crcutil-${CRCUTIL_VERSION}.tar.gz \\\n $CRCUTIL_SOURCE \\\n $CRCUTIL_PATCHLEVEL \\\n \"patch -p0 < $TP_DIR/patches/crcutil-fix-libtoolize-on-osx.patch\"\n\nLIBUNWIND_PATCHLEVEL=1\nfetch_and_patch \\\n libunwind-${LIBUNWIND_VERSION}.tar.gz \\\n $LIBUNWIND_SOURCE \\\n $LIBUNWIND_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/libunwind-trace-cache-destructor.patch\"\n\n: '\nPYTHON_PATCHLEVEL=0\nfetch_and_patch \\\n python-${PYTHON_VERSION}.tar.gz \\\n $PYTHON_SOURCE \\\n $PYTHON_PATCHLEVEL\n\nLLVM_PATCHLEVEL=2\nfetch_and_patch \\\n llvm-${LLVM_VERSION}-iwyu-${IWYU_VERSION}.src.tar.gz \\\n $LLVM_SOURCE \\\n $LLVM_PATCHLEVEL \\\n  \"patch -p1 < $TP_DIR/patches/llvm-fix-amazon-linux.patch\" \\\n  \"patch -p1 < $TP_DIR/patches/llvm-add-iwyu.patch\" \\\n  \"patch -p1 < $TP_DIR/patches/llvm-iwyu-nocurses.patch\" \\\n  \"patch -p1 < $TP_DIR/patches/llvm-iwyu-include-picker.patch\" \\\n  \"patch -d tools/clang/tools/include-what-you-use -p1 < $TP_DIR/patches/llvm-iwyu-llvm-6-compat.patch\" \\\n  \"patch -d projects/compiler-rt -p1 < $TP_DIR/patches/llvm-tsan-disable-trace-switching-after-multithreaded-for.patch\"\n'\n\nLZ4_PATCHLEVEL=1\nfetch_and_patch \\\n lz4-lz4-$LZ4_VERSION.tar.gz \\\n $LZ4_SOURCE \\\n $LZ4_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/lz4-0001-Fix-cmake-build-to-use-gnu-flags-on-clang.patch\"\n\n: '\nBITSHUFFLE_PATCHLEVEL=0\nfetch_and_patch \\\n bitshuffle-${BITSHUFFLE_VERSION}.tar.gz \\\n $BITSHUFFLE_SOURCE \\\n $BITSHUFFLE_PATCHLEVEL\n\nTRACE_VIEWER_PATCHLEVEL=0\nfetch_and_patch \\\n kudu-trace-viewer-${TRACE_VIEWER_VERSION}.tar.gz \\\n $TRACE_VIEWER_SOURCE \\\n $TRACE_VIEWER_PATCHLEVEL\n\nNVML_PATCHLEVEL=0\nfetch_and_patch \\\n nvml-${NVML_VERSION}.tar.gz \\\n $NVML_SOURCE \\\n $NVML_PATCHLEVEL\n'\n\nBOOST_PATCHLEVEL=1\nfetch_and_patch \\\n boost_${BOOST_VERSION}.tar.gz \\\n $BOOST_SOURCE \\\n $BOOST_PATCHLEVEL \\\n \"patch -p0 < $TP_DIR/patches/boost-issue-12179-fix-compilation-errors.patch\"\n\n# Return 0 if the current system appears to be el6 (either CentOS or proper RHEL)\nneeds_openssl_workaround() {\n  test -f /etc/redhat-release || return 1\n  rel=\"$(cat /etc/redhat-release)\"\n  pat=\"(CentOS|Red Hat Enterprise).* release 6.*\"\n  [[ \"$rel\" =~ $pat ]]\n  return $?\n}\nif needs_openssl_workaround && [ ! -d \"$OPENSSL_WORKAROUND_DIR\" ] ; then\n  echo Building on el6: installing OpenSSL from CentOS 6.4.\n  $TP_DIR/install-openssl-el6-workaround.sh\nfi\n\nBREAKPAD_PATCHLEVEL=1\nfetch_and_patch \\\n breakpad-${BREAKPAD_VERSION}.tar.gz \\\n $BREAKPAD_SOURCE \\\n $BREAKPAD_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/breakpad-add-basic-support-for-dwz-dwarf-extension.patch\"\n\nSPARSEHASH_PATCHLEVEL=2\nfetch_and_patch \\\n sparsehash-c11-${SPARSEHASH_VERSION}.tar.gz \\\n $SPARSEHASH_SOURCE \\\n $SPARSEHASH_PATCHLEVEL \\\n \"patch -p1 < $TP_DIR/patches/sparsehash-0001-Add-compatibily-for-gcc-4.x-in-traits.patch\"\n\nSPARSEPP_PATCHLEVEL=0\nfetch_and_patch \\\n sparsepp-${SPARSEPP_VERSION}.tar.gz \\\n $SPARSEPP_SOURCE \\\n $SPARSEPP_PATCHLEVEL\n\nTHRIFT_PATCHLEVEL=0\nfetch_and_patch \\\n $THRIFT_NAME.tar.gz \\\n $THRIFT_SOURCE \\\n $THRIFT_PATCHLEVEL\n\nBISON_PATCHLEVEL=0\nfetch_and_patch \\\n $BISON_NAME.tar.gz \\\n $BISON_SOURCE \\\n $BISON_PATCHLEVEL\n # This would normally call autoreconf, but it does not succeed with\n # autoreconf 2.69-11 (RHEL 7): \"autoreconf: 'configure.ac' or 'configure.in' is required\".\n\nHIVE_PATCHLEVEL=0\nfetch_and_patch \\\n $HIVE_NAME-stripped.tar.gz \\\n $HIVE_SOURCE \\\n $HIVE_PATCHLEVEL\n\nHADOOP_PATCHLEVEL=0\nfetch_and_patch \\\n $HADOOP_NAME-stripped.tar.gz \\\n $HADOOP_SOURCE \\\n $HADOOP_PATCHLEVEL\n\nSENTRY_PATCHLEVEL=0\nfetch_and_patch \\\n $SENTRY_NAME.tar.gz \\\n $SENTRY_SOURCE \\\n $SENTRY_PATCHLEVEL\n\nCOREDUMPER_PATCHLEVEL=3\nfetch_with_url_and_patch \\\n $COREDUMPER_NAME.tar.gz \\\n $COREDUMPER_SOURCE \\\n $COREDUMPER_PATCHLEVEL \\\n https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/google-coredumper \\\n \"patch -p0 < $TP_DIR/patches/coredumper_p0.patch\" \\\n \"patch -p0 < $TP_DIR/patches/coredumper_p1.patch\" \\\n \"patch -p0 < $TP_DIR/patches/coredumper_p2.patch\"\n\necho \"---------------\"\necho \"Thirdparty dependencies downloaded successfully\"\n", "num_lines": 450}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# This script serves to workaround a problematic OpenSSL ABI change\n# made between RHEL 6.4 and 6.5. Namely:\n#\n#  RHEL 6.4's OpenSSL library is built with no symbol versioning. For example:\n#  $ objdump -T libssl.so | grep SSL_CTX_new\n#    0000000000037110 g    DF .text  0000000000000577  Base        SSL_CTX_new\n#\n#  RHEL 6.5's OpenSSL library has symbol versions. For example:\n#  $ objdump -T /usr/lib64/libssl.so | grep SSL_CTX_new\n#    0000003ae8243610 g    DF .text  0000000000000597  libssl.so.10 SSL_CTX_new\n#\n# Thus, if we build Kudu on RHEL 6.5 or later, the resulting binaries expect\n# the versioned symbols in libssl and will not run on RHEL 6.4 or earlier:\n#\n#  $ objdump -T kudu-tserver | grep SSL_CTX_new\n#    0000000000000000      DF *UND*     0000000000000000  libssl.so.10 SSL_CTX_new\n#\n# In contrast, if a binary is built not expecting versioned symbols, the runtime\n# linker can still resolve those symbols by choosing the versioned ones. Thus,\n# binaries built against RHEL 6.4 are forward-compatible to later versions, but\n# not vice versa.\n#\n# Note that Kudu cannot simply be built on RHEL 6.4 because the devtoolset toolchain is\n# not available. So, given that we want to produce binaries that run on RHEL 6.4,\n# we need to perform a workaround such that our binaries built on 6.6 don't depend\n# on the versioned symbols in OpenSSL. This script provides such a workaround.\n#\n# The workaround itself is quite simple: we download the OpenSSL RPMs from CentOS 6.4\n# and unpack them into a directory in thirdparty/. If we then build against those\n# the resulting binaries can run on either el6.4 or el6.6.\n\nset -e\n\nTP_DIR=$(cd \"$(dirname \"$BASH_SOURCE\")\"; pwd)\nsource $TP_DIR/vars.sh\n\nmkdir -p $OPENSSL_WORKAROUND_DIR\ncd $OPENSSL_WORKAROUND_DIR\n\n# Clean up any previous leftovers.\nrm -Rf usr etc\n\n# Download and unpack OpenSSL RPMs from CentOS 6.4.\n#\n# We have mirrored these in our S3 bucket, but the original sources are in\n# http://vault.centos.org/6.4/os/x86_64/Packages/ .\nfor FILENAME in openssl-1.0.0-27.el6.x86_64.rpm openssl-devel-1.0.0-27.el6.x86_64.rpm ; do\n  FULL_URL=\"${CLOUDFRONT_URL_PREFIX}/${FILENAME}\"\n  if [ -r \"$FILENAME\" ]; then\n    echo $FILENAME already exists. Not re-downloading.\n  else\n    echo \"Fetching $FILENAME from $FULL_URL\"\n    curl -L -O \"${FULL_URL}\"\n  fi\n\n  echo \"Unpacking $FILENAME\"\n  rpm2cpio $FILENAME | cpio -idm\ndone\n\n", "num_lines": 79}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Packages Hadoop for inclusion in the Kudu thirdparty build.\n#\n# Strips jars and unecessary documentation. This makes the download smaller, and\n# improves HMS startup time.\n#\n# Summary:\n# 1. Download and unpack the Hadoop binary tarball (optional)\n# 2. Strip out unnecessary jars\n# 3. Repackage the tarball (optional)\n\nset -ex\n\nfunction usage() {\n  cat <<EOF\n  Usage:\n    ${0} -h | --help\n    ${0} [-d] [-r] <ARTIFACT>\n    -h | --help - This message\n    -d | --download - Optional\n      Download and unpack the binary tarball.\n    -r | --repackage - Optional\n      Repackage the tarball.\n    <ARTIFACT> - Required\n      The artifact name.\nEOF\n}\n\nOPTS=`getopt -o hdr -l \"help,download,repackage\" -n 'parse-options' -- \"$@\"`\nOPTS_RESULT=$?\nif [ ${OPTS_RESULT} != 0 ]; then\n  echo \"Failed parsing options.\" >&2\n  exit ${OPTS_RESULT}\nfi\n\nwhile true; do\n  case \"$1\" in\n    -d | --download) DOWNLOAD=True; shift;;\n    -r | --repackage) REPACKAGE=True; shift;;\n    -h | --help) usage; exit;;\n    --) shift; break;;\n    *) break ;;\n  esac\ndone\n\nARTIFACT=\"${1}\"\n\nif [ -z \"${ARTIFACT}\" ]; then\n  usage\n  exit\nfi\n\nif [ -n \"${DOWNLOAD}\" ]; then\n  curl --retry 3 -L -O https://archive.apache.org/dist/hadoop/common/$ARTIFACT/$ARTIFACT.tar.gz\n  tar xf $ARTIFACT.tar.gz\nfi\n\nDIRS=\"client\"\nDIRS=\"$DIRS common/jdiff\"\nDIRS=\"$DIRS common/sources\"\nDIRS=\"$DIRS hdfs/sources\"\nDIRS=\"$DIRS httpfs\"\nDIRS=\"$DIRS kms\"\nDIRS=\"$DIRS mapreduce/lib-examples\"\nDIRS=\"$DIRS mapreduce/sources\"\nDIRS=\"$DIRS tools\"\n\nfor DIR in $DIRS; do\n  rm -rf $ARTIFACT/share/hadoop/$DIR\ndone\n\nfor PROJECT in avro commons-math3 snappy; do\n  rm -f $ARTIFACT/share/hadoop/common/lib/*$PROJECT*.jar\n  rm -f $ARTIFACT/share/hadoop/hdfs/lib/*$PROJECT*.jar\ndone\n\nrm -f $ARTIFACT/share/hadoop/yarn/*.jar\nrm -rf $ARTIFACT/share/hadoop/yarn/lib\nrm -rf $ARTIFACT/share/hadoop/yarn/sources\nrm -rf $ARTIFACT/share/hadoop/yarn/timelineservice\nrm -rf $ARTIFACT/share/doc\n\nif [ -n \"${REPACKAGE}\" ]; then\n  tar czf $ARTIFACT-stripped.tar.gz $ARTIFACT\nfi\n", "num_lines": 104}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Packages Hive for inclusion in the Kudu thirdparty build.\n#\n# Strips jars unnecessary for running the Hive Metastore. This makes the download\n# smaller, and improves HMS startup time.\n#\n# Summary:\n# 1. Download and unpack the Hive binary tarball (optional)\n# 2. Strip out unnecessary jars\n# 3. Repackage the tarball (optional)\n\nset -ex\n\nfunction usage() {\n  cat <<EOF\n  Usage:\n    ${0} -h | --help\n    ${0} [-d] [-r] <ARTIFACT>\n    -h | --help - This message\n    -d | --download - Optional\n      Download and unpack the binary tarball.\n    -r | --repackage - Optional\n      Repackage the tarball.\n    -v | --version VERSION - Optional\n      The Hive version.\n    <ARTIFACT> - Required\n      The artifact name.\nEOF\n}\n\nOPTS=`getopt -o hdrv: -l \"help,download,repackage,version:\" -n 'parse-options' -- \"$@\"`\nOPTS_RESULT=$?\nif [ ${OPTS_RESULT} != 0 ]; then\n  echo \"Failed parsing options.\" >&2\n  exit ${OPTS_RESULT}\nfi\n\nwhile true; do\n  case \"$1\" in\n    -d | --download) DOWNLOAD=True; shift;;\n    -r | --repackage) REPACKAGE=True; shift;;\n    -v | --version) VERSION=$2; shift; shift;;\n    -h | --help) usage; exit;;\n    --) shift; break;;\n    *) break ;;\n  esac\ndone\n\nARTIFACT=\"${1}\"\n\nif [ -z \"${ARTIFACT}\" ]; then\n  usage\n  exit\nfi\n\nif [ -n \"${DOWNLOAD}\" ]; then\n  curl --retry 3 -L -O https://archive.apache.org/dist/hive/hive-$VERSION/$ARTIFACT.tar.gz\n  tar xf $ARTIFACT.tar.gz\nfi\n\nPROJECTS=\"accumulo\"\nPROJECTS=\"$PROJECTS aether\"\nPROJECTS=\"$PROJECTS avatica\"\nPROJECTS=\"$PROJECTS avro\"\nPROJECTS=\"$PROJECTS calcite\"\nPROJECTS=\"$PROJECTS curator\"\nPROJECTS=\"$PROJECTS druid\"\nPROJECTS=\"$PROJECTS ecj\"\nPROJECTS=\"$PROJECTS fastutil\"\nPROJECTS=\"$PROJECTS groovy\"\nPROJECTS=\"$PROJECTS hbase\"\nPROJECTS=\"$PROJECTS htrace\"\nPROJECTS=\"$PROJECTS icu4j\"\nPROJECTS=\"$PROJECTS jcodings\"\nPROJECTS=\"$PROJECTS jersey\"\nPROJECTS=\"$PROJECTS jetty\"\nPROJECTS=\"$PROJECTS jsp\"\nPROJECTS=\"$PROJECTS maven\"\nPROJECTS=\"$PROJECTS parquet\"\nPROJECTS=\"$PROJECTS slider\"\nPROJECTS=\"$PROJECTS snappy\"\nPROJECTS=\"$PROJECTS zookeeper\"\n\nfor PROJECT in $PROJECTS; do\n  rm -f $ARTIFACT/lib/*$PROJECT*.jar\ndone\n\nrm -rf $ARTIFACT/auxlib\nrm -rf $ARTIFACT/hcatalog/bin\nrm -rf $ARTIFACT/hcatalog/etc\nrm -rf $ARTIFACT/hcatalog/libexec\nrm -rf $ARTIFACT/hcatalog/sbin\nrm -rf $ARTIFACT/hcatalog/share/doc\nrm -rf $ARTIFACT/hcatalog/share/webhcat\nrm -rf $ARTIFACT/jdbc\nrm -rf $ARTIFACT/lib/php\nrm -rf $ARTIFACT/lib/python\nrm -rf $ARTIFACT/lib/py\n\nif [ -n \"${REPACKAGE}\" ]; then\n  # Remove the 'apache-' prefix and '-bin' suffix in order to normalize the\n  # tarball with Hadoop and the rest of our thirdparty dependencies.\n  mv $ARTIFACT hive-$VERSION\n  tar czf hive-$VERSION-stripped.tar.gz hive-$VERSION\nfi\n", "num_lines": 124}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\n# Packages LLVM for inclusing in the Kudu thirdparty build.\n#\n# Our llvm tarball includes clang, extra clang tools, lld, and compiler-rt.\n#\n# See http://clang.llvm.org/get_started.html and http://lld.llvm.org/ for\n# details on how they're laid out in the llvm tarball.\n#\n# Summary:\n# 1.  Unpack the llvm tarball\n# 2.  Unpack the clang tarball as tools/clang (rename from cfe-<version> to clang)\n# 3.  Unpack the extra clang tools tarball as tools/clang/tools/extra\n# 4.  Unpack the lld tarball as tools/lld\n# 5.  Unpack the compiler-rt tarball as projects/compiler-rt\n# 6.  Unpack the libc++ tarball as projects/libcxx\n# 7.  Unpack the libc++abi tarball as projects/libcxxabi\n# 9.  Unpack the IWYU tarball in tools/clang/tools/include-what-you-use\n# 10. Create new tarball from the resulting source tree\n#\n# Usage:\n#  $ env VERSION=6.0.0 IWYU_VERSION=0.9 thirdparty/package-llvm.sh\n\nset -eux\n\nfor ARTIFACT in llvm cfe compiler-rt libcxx libcxxabi lld clang-tools-extra; do\n  wget http://releases.llvm.org/$VERSION/$ARTIFACT-$VERSION.src.tar.xz\n  tar xf $ARTIFACT-$VERSION.src.tar.xz\n  rm $ARTIFACT-$VERSION.src.tar.xz\ndone\n\nIWYU_TAR=include-what-you-use-${IWYU_VERSION}.src.tar.gz\nwget https://include-what-you-use.org/downloads/$IWYU_TAR\ntar xf $IWYU_TAR\nrm $IWYU_TAR\n\nmv cfe-$VERSION.src llvm-$VERSION.src/tools/clang\nmv clang-tools-extra-$VERSION.src llvm-$VERSION.src/tools/clang/tools/extra\nmv lld-$VERSION.src llvm-$VERSION.src/tools/lld\nmv compiler-rt-$VERSION.src llvm-$VERSION.src/projects/compiler-rt\nmv libcxx-$VERSION.src llvm-$VERSION.src/projects/libcxx\nmv libcxxabi-$VERSION.src llvm-$VERSION.src/projects/libcxxabi\nmv include-what-you-use llvm-$VERSION.src/tools/clang/tools/\n\ntar czf llvm-$VERSION-iwyu-$IWYU_VERSION.src.tar.gz llvm-$VERSION.src\n", "num_lines": 63}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n\nif [ -z \"$TP_DIR\" ]; then\n   echo \"TP_DIR variable not set, check your scripts\"\n   exit 1\nfi\n\nTP_SOURCE_DIR=\"$TP_DIR/src\"\nTP_BUILD_DIR=\"$TP_DIR/build\"\n\n# This URL corresponds to the CloudFront Distribution for the S3\n# bucket cloudera-thirdparty-libs which is directly accessible at\n# http://cloudera-thirdparty-libs.s3.amazonaws.com/\nCLOUDFRONT_URL_PREFIX=http://d3dr9sfxru4sde.cloudfront.net\n\n# Third party dependency downloading URL, default to the CloudFront\n# Distribution URL.\nDEPENDENCY_URL=${DEPENDENCY_URL:-$CLOUDFRONT_URL_PREFIX}\n\nPREFIX_COMMON=$TP_DIR/installed/common\nPREFIX_DEPS=$TP_DIR/installed/uninstrumented\nPREFIX_DEPS_TSAN=$TP_DIR/installed/tsan\n\nGFLAGS_VERSION=2.2.0\nGFLAGS_NAME=gflags-$GFLAGS_VERSION\nGFLAGS_SOURCE=$TP_SOURCE_DIR/$GFLAGS_NAME\n\nGLOG_VERSION=0.3.5\nGLOG_NAME=glog-$GLOG_VERSION\nGLOG_SOURCE=$TP_SOURCE_DIR/$GLOG_NAME\n\nGMOCK_VERSION=1.8.0\nGMOCK_NAME=googletest-release-$GMOCK_VERSION\nGMOCK_SOURCE=$TP_SOURCE_DIR/$GMOCK_NAME\n\nGPERFTOOLS_VERSION=2.6.90\nGPERFTOOLS_NAME=gperftools-$GPERFTOOLS_VERSION\nGPERFTOOLS_SOURCE=$TP_SOURCE_DIR/$GPERFTOOLS_NAME\n\nPROTOBUF_VERSION=3.4.1\nPROTOBUF_NAME=protobuf-$PROTOBUF_VERSION\nPROTOBUF_SOURCE=$TP_SOURCE_DIR/$PROTOBUF_NAME\n\n# Note: CMake gets patched on SLES12SP0. When changing the CMake version, please check if\n# cmake-issue-15873-dont-use-select.patch needs to be updated.\nCMAKE_VERSION=3.9.0\nCMAKE_NAME=cmake-$CMAKE_VERSION\nCMAKE_SOURCE=$TP_SOURCE_DIR/$CMAKE_NAME\n\nSNAPPY_VERSION=1.1.4\nSNAPPY_NAME=snappy-$SNAPPY_VERSION\nSNAPPY_SOURCE=$TP_SOURCE_DIR/$SNAPPY_NAME\n\nLZ4_VERSION=r130\nLZ4_NAME=lz4-lz4-$LZ4_VERSION\nLZ4_SOURCE=$TP_SOURCE_DIR/$LZ4_NAME\n\n# from https://github.com/kiyo-masui/bitshuffle\n# Hash of git: 55f9b4caec73fa21d13947cacea1295926781440\nBITSHUFFLE_VERSION=55f9b4c\nBITSHUFFLE_NAME=bitshuffle-$BITSHUFFLE_VERSION\nBITSHUFFLE_SOURCE=$TP_SOURCE_DIR/$BITSHUFFLE_NAME\n\nZLIB_VERSION=1.2.8\nZLIB_NAME=zlib-$ZLIB_VERSION\nZLIB_SOURCE=$TP_SOURCE_DIR/$ZLIB_NAME\n\nLIBEV_VERSION=4.20\nLIBEV_NAME=libev-$LIBEV_VERSION\nLIBEV_SOURCE=$TP_SOURCE_DIR/$LIBEV_NAME\n\nRAPIDJSON_VERSION=0.11\nRAPIDJSON_NAME=rapidjson-$RAPIDJSON_VERSION\nRAPIDJSON_SOURCE=$TP_SOURCE_DIR/$RAPIDJSON_NAME\n\n# Hash of the squeasel git revision to use.\n# (from http://github.com/cloudera/squeasel)\n#\n# To re-build this tarball use the following in the squeasel repo:\n#  export NAME=squeasel-$(git rev-parse HEAD)\n#  git archive HEAD --prefix=$NAME/ -o /tmp/$NAME.tar.gz\n#  s3cmd put -P /tmp/$NAME.tar.gz s3://cloudera-thirdparty-libs/$NAME.tar.gz\nSQUEASEL_VERSION=9335b81317a6451d5a37c5dc7ec088eecbf68c82\nSQUEASEL_NAME=squeasel-$SQUEASEL_VERSION\nSQUEASEL_SOURCE=$TP_SOURCE_DIR/$SQUEASEL_NAME\n\n# Hash of the mustache git revision to use.\n# (from https://github.com/henryr/cpp-mustache)\n#\n# To re-build this tarball use the following in the mustache repo:\n#  export NAME=mustache-$(git rev-parse HEAD)\n#  git archive HEAD --prefix=$NAME/ -o /tmp/$NAME.tar.gz\n#  s3cmd put -P /tmp/$NAME.tar.gz s3://cloudera-thirdparty-libs/$NAME.tar.gz\nMUSTACHE_VERSION=87a592e8aa04497764c533acd6e887618ca7b8a8\nMUSTACHE_NAME=mustache-$MUSTACHE_VERSION\nMUSTACHE_SOURCE=$TP_SOURCE_DIR/$MUSTACHE_NAME\n\n# git revision of google style guide:\n# https://github.com/google/styleguide\n# git archive --prefix=google-styleguide-$(git rev-parse HEAD)/ -o /tmp/google-styleguide-$(git rev-parse HEAD).tgz HEAD\nGSG_VERSION=7a179d1ac2e08a5cc1622bec900d1e0452776713\nGSG_NAME=google-styleguide-$GSG_VERSION\nGSG_SOURCE=$TP_SOURCE_DIR/$GSG_NAME\n\nGCOVR_VERSION=3.0\nGCOVR_NAME=gcovr-$GCOVR_VERSION\nGCOVR_SOURCE=$TP_SOURCE_DIR/$GCOVR_NAME\n\nCURL_VERSION=7.59.0\nCURL_NAME=curl-$CURL_VERSION\nCURL_SOURCE=$TP_SOURCE_DIR/$CURL_NAME\n\n# Hash of the crcutil git revision to use.\n# (from http://github.com/adembo/crcutil)\n#\n# To re-build this tarball use the following in the crcutil repo:\n#  export NAME=crcutil-$(git rev-parse HEAD)\n#  git archive HEAD --prefix=$NAME/ -o /tmp/$NAME.tar.gz\n#  s3cmd put -P /tmp/$NAME.tar.gz s3://cloudera-thirdparty-libs/$NAME.tar.gz\nCRCUTIL_VERSION=42148a6df6986a257ab21c80f8eca2e54544ac4d\nCRCUTIL_NAME=crcutil-$CRCUTIL_VERSION\nCRCUTIL_SOURCE=$TP_SOURCE_DIR/$CRCUTIL_NAME\n\nLIBUNWIND_VERSION=1.5.0\nLIBUNWIND_NAME=libunwind-$LIBUNWIND_VERSION\nLIBUNWIND_SOURCE=$TP_SOURCE_DIR/$LIBUNWIND_NAME\n\n# See package-llvm.sh for details on the LLVM tarball.\nLLVM_VERSION=6.0.0\nLLVM_NAME=llvm-$LLVM_VERSION.src\nLLVM_SOURCE=$TP_SOURCE_DIR/$LLVM_NAME\n\n# The include-what-you-use is built along with LLVM in its source tree.\nIWYU_VERSION=0.9\n\n# Python 2.7 is required to build LLVM 3.6+. It is only built and installed if\n# the system Python version is not 2.7.\nPYTHON_VERSION=2.7.13\nPYTHON_NAME=python-$PYTHON_VERSION\nPYTHON_SOURCE=$TP_SOURCE_DIR/$PYTHON_NAME\n\n# Our trace-viewer repository is separate since it's quite large and\n# shouldn't change frequently. We upload the built artifacts (HTML/JS)\n# when we need to roll to a new revision.\n#\n# The source can be found in the 'kudu' branch of https://github.com/cloudera/catapult\n# and built with \"tracing/kudu-build.sh\" included within the repository.\nTRACE_VIEWER_VERSION=21d76f8350fea2da2aa25cb6fd512703497d0c11\nTRACE_VIEWER_NAME=kudu-trace-viewer-$TRACE_VIEWER_VERSION\nTRACE_VIEWER_SOURCE=$TP_SOURCE_DIR/$TRACE_VIEWER_NAME\n\nNVML_VERSION=1.1\nNVML_NAME=nvml-$NVML_VERSION\nNVML_SOURCE=$TP_SOURCE_DIR/$NVML_NAME\n\nBOOST_VERSION=1_61_0\nBOOST_NAME=boost_$BOOST_VERSION\nBOOST_SOURCE=$TP_SOURCE_DIR/$BOOST_NAME\n\nOPENSSL_WORKAROUND_DIR=\"$TP_DIR/installed/openssl-el6-workaround\"\n\n# The breakpad source artifact is created using the script found in\n# scripts/make-breakpad-src-archive.sh\nBREAKPAD_VERSION=9eac2058b70615519b2c4d8c6bdbfca1bd079e39\nBREAKPAD_NAME=breakpad-$BREAKPAD_VERSION\nBREAKPAD_SOURCE=$TP_SOURCE_DIR/$BREAKPAD_NAME\n\n# Hash of the sparsehash-c11 git revision to use.\n# (from http://github.com/sparsehash/sparsehash-c11)\n#\n# To re-build this tarball use the following in the sparsehash-c11 repo:\n#  export NAME=sparsehash-c11-$(git rev-parse HEAD)\n#  git archive HEAD --prefix=$NAME/ -o /tmp/$NAME.tar.gz\n#  s3cmd put -P /tmp/$NAME.tar.gz s3://cloudera-thirdparty-libs/$NAME.tar.gz\nSPARSEHASH_VERSION=47a55825ca3b35eab1ca22b7ab82b9544e32a9af\nSPARSEHASH_NAME=sparsehash-c11-$SPARSEHASH_VERSION\nSPARSEHASH_SOURCE=$TP_SOURCE_DIR/$SPARSEHASH_NAME\n\n# Hash of the sparsepp git revision to use.\n# (from https://github.com/greg7mdp/sparsepp)\n#\n# To re-build this tarball use the following in the sparsepp repo:\n#  export NAME=sparsepp-$(git rev-parse HEAD)\n#  git archive HEAD --prefix=$NAME/ -o /tmp/$NAME.tar.gz\n#  s3cmd put -P /tmp/$NAME.tar.gz s3://cloudera-thirdparty-libs/$NAME.tar.gz\nSPARSEPP_VERSION=824860bb76893d163efbcff330734b9f62eecb17\nSPARSEPP_NAME=sparsepp-$SPARSEPP_VERSION\nSPARSEPP_SOURCE=$TP_SOURCE_DIR/$SPARSEPP_NAME\n\nTHRIFT_VERSION=0.11.0\nTHRIFT_NAME=thrift-$THRIFT_VERSION\nTHRIFT_SOURCE=$TP_SOURCE_DIR/$THRIFT_NAME\n\nBISON_VERSION=3.0.5\nBISON_NAME=bison-$BISON_VERSION\nBISON_SOURCE=$TP_SOURCE_DIR/$BISON_NAME\n\n# TODO(dan): bump to a release version once HIVE-17747 and HIVE-16886/HIVE-18526\n# are published. The SHA below is the current head of branch-2.\n# Note: The Hive release binary tarball is stripped of unnecessary jars before\n# being uploaded. See thirdparty/package-hive.sh for details.\nHIVE_VERSION=498021fa15186aee8b282d3c032fbd2cede6bec4\nHIVE_NAME=hive-$HIVE_VERSION\nHIVE_SOURCE=$TP_SOURCE_DIR/$HIVE_NAME\n\n# Note: The Hadoop release tarball is stripped of unnecessary jars before being\n# uploaded. See thirdparty/package-hadoop.sh for details.\nHADOOP_VERSION=2.8.5\nHADOOP_NAME=hadoop-$HADOOP_VERSION\nHADOOP_SOURCE=$TP_SOURCE_DIR/$HADOOP_NAME\n\n# TODO(dan): bump to a release version once SENTRY-2371 is published. The SHA\n# below is the current head of the master branch.\nSENTRY_VERSION=2c9a927a9e87cba0e4c0f34fc0b55887c6636927\nSENTRY_NAME=apache-sentry-$SENTRY_VERSION-bin\nSENTRY_SOURCE=$TP_SOURCE_DIR/$SENTRY_NAME\n\nCOREDUMPER_VERSION=1.2.1\nCOREDUMPER_NAME=coredumper-$COREDUMPER_VERSION\nCOREDUMPER_SOURCE=$TP_SOURCE_DIR/$COREDUMPER_NAME\n", "num_lines": 238}
{"repo_name": "kuduraft", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n################################################################################\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n################################################################################\n# Script to make a source archive from the Breakpad project, which does not run\n# releases.\n#\n# We export only checked-in files, without the git metadata, and construct\n# the expected directory structure to compile it. Then we tar it up.\n\nBREAKPAD_REPO=https://chromium.googlesource.com/breakpad/breakpad\nLSS_REPO=https://chromium.googlesource.com/linux-syscall-support\nLSS_REVISION=3f6478ac95edf86cd3da300c2c0d34a438f5dbeb\n\nTOPDIR=breakpad-repos\n\nrm -rf \"$TOPDIR\"\nmkdir $TOPDIR\npushd $TOPDIR\n\nBREAKPAD_DIR=breakpad.git\ngit clone $BREAKPAD_REPO $BREAKPAD_DIR\npushd $BREAKPAD_DIR\n\nREVISION=${1:-$(git rev-parse HEAD)}\nNAME=breakpad-$REVISION\n\ngit checkout $REVISION\n# Export the checked-in files, without .git metadata, into \"../$NAME/\".\ngit archive --format=tar --prefix=$NAME/ $REVISION | (cd .. && tar xf -)\npopd\n\nLSS_DIR=lss.git\ngit clone $LSS_REPO $LSS_DIR\npushd $LSS_DIR\n# Export into the thirdparty directory under \"../$NAME/\".\ngit archive --format=tar --prefix=$NAME/src/third_party/lss/ $LSS_REVISION | (cd .. && tar xf -)\npopd\n\nFILENAME=\"$NAME.tar.gz\"\ntar czvf \"$FILENAME\" \"$NAME/\"\nmv \"$FILENAME\" ..\npopd\necho \"Archive created at $(pwd)/$FILENAME\"\n\nexit 0\n", "num_lines": 62}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "export NOVNC_REF='1.3.0'\nexport WEBSOCKIFY_REF='0.10.0'\nexport DEBIAN_FRONTEND=noninteractive\n\n# Install FluxBox, VNC & noVNC\nmkdir -p /opt/bin && chmod +x /dev/shm \\\n    && apt-get update && apt-get install -y unzip fluxbox x11vnc \\\n    && curl -L -o noVNC.zip \"https://github.com/novnc/noVNC/archive/v${NOVNC_REF}.zip\" \\\n    && unzip -x noVNC.zip \\\n    && rm -rf noVNC-${NOVNC_REF}/{docs,tests} \\\n    && mv noVNC-${NOVNC_REF} /opt/bin/noVNC \\\n    && cp /opt/bin/noVNC/vnc.html /opt/bin/noVNC/index.html \\\n    && rm noVNC.zip \\\n    && curl -L -o websockify.zip \"https://github.com/novnc/websockify/archive/v${WEBSOCKIFY_REF}.zip\" \\\n    && unzip -x websockify.zip \\\n    && rm websockify.zip \\\n    && rm -rf websockify-${WEBSOCKIFY_REF}/{docs,tests} \\\n    && mv websockify-${WEBSOCKIFY_REF} /opt/bin/noVNC/utils/websockify\n\n# Patch noVNC\n\ncat <<'EOF' > /opt/bin/noVNC/clip.patch\ndiff --git a/app/ui.js b/app/ui.js\nindex cb6a9fd..dbe42e0 100644\n--- a/app/ui.js\n+++ b/app/ui.js\n@@ -951,6 +951,7 @@ const UI = {\n     clipboardReceive(e) {\n         Log.Debug(\">> UI.clipboardReceive: \" + e.detail.text.substr(0, 40) + \"...\");\n         document.getElementById('noVNC_clipboard_text').value = e.detail.text;\n+        navigator.clipboard.writeText(e.detail.text).catch(() => {});\n         Log.Debug(\"<< UI.clipboardReceive\");\n     },\n \ndiff --git a/core/rfb.js b/core/rfb.js\nindex ea3bf58..fad57bc 100644\n--- a/core/rfb.js\n+++ b/core/rfb.js\n@@ -176,6 +176,7 @@ export default class RFB extends EventTargetMixin {\n             handleMouse: this._handleMouse.bind(this),\n             handleWheel: this._handleWheel.bind(this),\n             handleGesture: this._handleGesture.bind(this),\n+            handleFocus: () => navigator.clipboard.readText().then(this.clipboardPasteFrom.bind(this)).catch(() => {})\n         };\n \n         // main setup\n@@ -515,6 +516,7 @@ export default class RFB extends EventTargetMixin {\n         this._canvas.addEventListener(\"gesturestart\", this._eventHandlers.handleGesture);\n         this._canvas.addEventListener(\"gesturemove\", this._eventHandlers.handleGesture);\n         this._canvas.addEventListener(\"gestureend\", this._eventHandlers.handleGesture);\n+        window.addEventListener('focus', this._eventHandlers.handleFocus);\n \n         Log.Debug(\"<< RFB.connect\");\n     }\n@@ -522,6 +524,7 @@ export default class RFB extends EventTargetMixin {\n     _disconnect() {\n         Log.Debug(\">> RFB.disconnect\");\n         this._cursor.detach();\n+        window.removeEventListener('focus', this._eventHandlers.handleFocus);\n         this._canvas.removeEventListener(\"gesturestart\", this._eventHandlers.handleGesture);\n         this._canvas.removeEventListener(\"gesturemove\", this._eventHandlers.handleGesture);\n         this._canvas.removeEventListener(\"gestureend\", this._eventHandlers.handleGesture);\nEOF\n\ncd /opt/bin/noVNC\ngit apply clip.patch\n\n# Configure FluxBox menus\nmkdir /root/.fluxbox\ncat <<'EOF' > /root/.fluxbox/menu\n  [begin] (fluxbox)\n    [submenu] (Browsers) {}\n      [exec] (Chromium) { /ms-playwright-agent/node_modules/.bin/playwright docker launch --endpoint http://127.0.0.1:5400 --browser chromium } <>\n      [exec] (Firefox) { /ms-playwright-agent/node_modules/.bin/playwright docker launch --endpoint http://127.0.0.1:5400 --browser firefox  } <>\n      [exec] (WebKit) { /ms-playwright-agent/node_modules/.bin/playwright docker launch --endpoint http://127.0.0.1:5400 --browser webkit  } <>\n    [end]\n    [include] (/etc/X11/fluxbox/fluxbox-menu)\n  [end]\nEOF\n\ncat <<'EOF' > /root/.fluxbox/lastwallpaper\n$center $full|/ms-playwright-agent/node_modules/playwright-core/lib/server/chromium/appIcon.png||:99\n$center $full|/ms-playwright-agent/node_modules/playwright-core/lib/server/chromium/appIcon.png||:99.0\nEOF\n\n", "num_lines": 86}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nSCREEN_WIDTH=1360\nSCREEN_HEIGHT=1020\nSCREEN_DEPTH=24\nSCREEN_DPI=96\nGEOMETRY=\"$SCREEN_WIDTH\"\"x\"\"$SCREEN_HEIGHT\"\"x\"\"$SCREEN_DEPTH\"\n\nnohup /usr/bin/xvfb-run --server-num=$DISPLAY_NUM \\\n     --listen-tcp \\\n     --server-args=\"-screen 0 \"$GEOMETRY\" -fbdir /var/tmp -dpi \"$SCREEN_DPI\" -listen tcp -noreset -ac +extension RANDR\" \\\n     /usr/bin/fluxbox -display \"$DISPLAY\" >/dev/null 2>&1 &\n\nfor i in $(seq 1 500); do\n  if xdpyinfo -display $DISPLAY >/dev/null 2>&1; then\n    break\n  fi\n  echo \"Waiting for Xvfb...\"\n  sleep 0.2\ndone\n\nnohup x11vnc -noprimary -nosetprimary -forever -shared -rfbport 5900 -rfbportv6 5900 -display \"$DISPLAY\" >/dev/null 2>&1 &\nnohup /opt/bin/noVNC/utils/novnc_proxy --listen 7900 --vnc localhost:5900 >/dev/null 2>&1 &\n\ncd /ms-playwright-agent\n\nNOVNC_UUID=$(cat /proc/sys/kernel/random/uuid)\necho \"novnc is listening on http://127.0.0.1:7900?path=$NOVNC_UUID&resize=scale&autoconnect=1\"\n\nPW_UUID=$(cat /proc/sys/kernel/random/uuid)\n\n# Make sure to re-start playwright server if something goes wrong.\n# The approach taken from: https://stackoverflow.com/a/697064/314883\n\nuntil npx playwright run-server --port=5400 --path=/$PW_UUID --proxy-mode=tether; do\n  echo \"Server crashed with exit code $?. Respawning..\" >&2\n  sleep 1\ndone\n\n", "num_lines": 40}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [[ $(arch) == \"aarch64\" ]]; then\n  echo \"ERROR: not supported on Linux Arm64\"\n  exit 1\nfi\n\nif [[ ! -f \"/etc/os-release\" ]]; then\n  echo \"ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)\"\n  exit 1\nfi\n\nID=$(bash -c 'source /etc/os-release && echo $ID')\nif [[ \"${ID}\" != \"ubuntu\" ]]; then\n  echo \"ERROR: cannot install on $ID distribution - only Ubuntu is supported\"\n  exit 1\nfi\n\n# 1. make sure to remove old beta if any.\nif dpkg --get-selections | grep -q \"^google-chrome-beta[[:space:]]*install$\" >/dev/null; then\n  apt-get remove -y google-chrome-beta\nfi\n\n# 2. Update apt lists (needed to install curl and chrome dependencies)\napt-get update\n\n# 3. Install curl to download chrome\nif ! command -v curl >/dev/null; then\n  apt-get install -y curl\nfi\n\n# 4. download chrome beta from dl.google.com and install it.\ncd /tmp\ncurl -O https://dl.google.com/linux/direct/google-chrome-beta_current_amd64.deb\napt-get install -y ./google-chrome-beta_current_amd64.deb\nrm -rf ./google-chrome-beta_current_amd64.deb\ncd -\ngoogle-chrome-beta --version\n", "num_lines": 41}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nrm -rf \"/Applications/Google Chrome Beta.app\"\ncd /tmp\ncurl -o ./googlechromebeta.dmg -k https://dl.google.com/chrome/mac/universal/beta/googlechromebeta.dmg\nhdiutil attach -nobrowse -quiet -noautofsck -noautoopen -mountpoint /Volumes/googlechromebeta.dmg ./googlechromebeta.dmg\ncp -rf \"/Volumes/googlechromebeta.dmg/Google Chrome Beta.app\" /Applications\nhdiutil detach /Volumes/googlechromebeta.dmg\nrm -rf /tmp/googlechromebeta.dmg\n\n/Applications/Google\\ Chrome\\ Beta.app/Contents/MacOS/Google\\ Chrome\\ Beta --version\n", "num_lines": 14}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [[ $(arch) == \"aarch64\" ]]; then\n  echo \"ERROR: not supported on Linux Arm64\"\n  exit 1\nfi\n\nif [[ ! -f \"/etc/os-release\" ]]; then\n  echo \"ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)\"\n  exit 1\nfi\n\nID=$(bash -c 'source /etc/os-release && echo $ID')\nif [[ \"${ID}\" != \"ubuntu\" ]]; then\n  echo \"ERROR: cannot install on $ID distribution - only Ubuntu is supported\"\n  exit 1\nfi\n\n# 1. make sure to remove old stable if any.\nif dpkg --get-selections | grep -q \"^google-chrome[[:space:]]*install$\" >/dev/null; then\n  apt-get remove -y google-chrome\nfi\n\n# 2. Update apt lists (needed to install curl and chrome dependencies)\napt-get update\n\n# 3. Install curl to download chrome\nif ! command -v curl >/dev/null; then\n  apt-get install -y curl\nfi\n\n# 4. download chrome stable from dl.google.com and install it.\ncd /tmp\ncurl -O https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb\napt-get install -y ./google-chrome-stable_current_amd64.deb\nrm -rf ./google-chrome-stable_current_amd64.deb\ncd -\ngoogle-chrome --version\n", "num_lines": 41}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nrm -rf \"/Applications/Google Chrome.app\"\ncd /tmp\ncurl -o ./googlechrome.dmg -k https://dl.google.com/chrome/mac/universal/stable/GGRO/googlechrome.dmg\nhdiutil attach -nobrowse -quiet -noautofsck -noautoopen -mountpoint /Volumes/googlechrome.dmg ./googlechrome.dmg\ncp -rf \"/Volumes/googlechrome.dmg/Google Chrome.app\" /Applications\nhdiutil detach /Volumes/googlechrome.dmg\nrm -rf /tmp/googlechrome.dmg\n/Applications/Google\\ Chrome.app/Contents/MacOS/Google\\ Chrome --version\n", "num_lines": 13}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -x\n\nif [[ $(arch) == \"aarch64\" ]]; then\n  echo \"ERROR: not supported on Linux Arm64\"\n  exit 1\nfi\n\nif [[ ! -f \"/etc/os-release\" ]]; then\n  echo \"ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)\"\n  exit 1\nfi\n\nID=$(bash -c 'source /etc/os-release && echo $ID')\nif [[ \"${ID}\" != \"ubuntu\" ]]; then\n  echo \"ERROR: cannot install on $ID distribution - only Ubuntu is supported\"\n  exit 1\nfi\n\n# 1. make sure to remove old beta if any.\nif dpkg --get-selections | grep -q \"^microsoft-edge-beta[[:space:]]*install$\" >/dev/null; then\n  apt-get remove -y microsoft-edge-beta\nfi\n\n# 2. Install curl to download Microsoft gpg key\nif ! command -v curl >/dev/null; then\n  apt-get update\n  apt-get install -y curl\nfi\n\n# 3. Add the GPG key, the apt repo, update the apt cache, and install the package\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg\ninstall -o root -g root -m 644 /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/\nsh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/edge stable main\" > /etc/apt/sources.list.d/microsoft-edge-dev.list'\nrm /tmp/microsoft.gpg\napt-get update && apt-get install -y microsoft-edge-beta\n\nmicrosoft-edge-beta --version\n", "num_lines": 41}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\ncd /tmp\ncurl -o ./msedge_beta.pkg -k \"$1\"\n# Note: there's no way to uninstall previously installed MSEdge.\n# However, running PKG again seems to update installation.\nsudo installer -pkg /tmp/msedge_beta.pkg -target /\nrm -rf /tmp/msedge_beta.pkg\n/Applications/Microsoft\\ Edge\\ Beta.app/Contents/MacOS/Microsoft\\ Edge\\ Beta --version\n", "num_lines": 12}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -x\n\nif [[ $(arch) == \"aarch64\" ]]; then\n  echo \"ERROR: not supported on Linux Arm64\"\n  exit 1\nfi\n\nif [[ ! -f \"/etc/os-release\" ]]; then\n  echo \"ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)\"\n  exit 1\nfi\n\nID=$(bash -c 'source /etc/os-release && echo $ID')\nif [[ \"${ID}\" != \"ubuntu\" ]]; then\n  echo \"ERROR: cannot install on $ID distribution - only Ubuntu is supported\"\n  exit 1\nfi\n\n# 1. make sure to remove old dev if any.\nif dpkg --get-selections | grep -q \"^microsoft-edge-dev[[:space:]]*install$\" >/dev/null; then\n  apt-get remove -y microsoft-edge-dev\nfi\n\n# 2. Install curl to download Microsoft gpg key\nif ! command -v curl >/dev/null; then\n  apt-get update\n  apt-get install -y curl\nfi\n\n# 3. Add the GPG key, the apt repo, update the apt cache, and install the package\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg\ninstall -o root -g root -m 644 /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/\nsh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/edge stable main\" > /etc/apt/sources.list.d/microsoft-edge-dev.list'\nrm /tmp/microsoft.gpg\napt-get update && apt-get install -y microsoft-edge-dev\n\nmicrosoft-edge-dev --version\n", "num_lines": 41}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\ncd /tmp\ncurl -o ./msedge_dev.pkg -k \"$1\"\n# Note: there's no way to uninstall previously installed MSEdge.\n# However, running PKG again seems to update installation.\nsudo installer -pkg /tmp/msedge_dev.pkg -target /\nrm -rf /tmp/msedge_dev.pkg\n/Applications/Microsoft\\ Edge\\ Dev.app/Contents/MacOS/Microsoft\\ Edge\\ Dev --version\n", "num_lines": 12}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -x\n\nif [[ $(arch) == \"aarch64\" ]]; then\n  echo \"ERROR: not supported on Linux Arm64\"\n  exit 1\nfi\n\nif [[ ! -f \"/etc/os-release\" ]]; then\n  echo \"ERROR: cannot install on unknown linux distribution (/etc/os-release is missing)\"\n  exit 1\nfi\n\nID=$(bash -c 'source /etc/os-release && echo $ID')\nif [[ \"${ID}\" != \"ubuntu\" ]]; then\n  echo \"ERROR: cannot install on $ID distribution - only Ubuntu is supported\"\n  exit 1\nfi\n\n# 1. make sure to remove old stable if any.\nif dpkg --get-selections | grep -q \"^microsoft-edge-stable[[:space:]]*install$\" >/dev/null; then\n  apt-get remove -y microsoft-edge-stable\nfi\n\n# 2. Install curl to download Microsoft gpg key\nif ! command -v curl >/dev/null; then\n  apt-get update\n  apt-get install -y curl\nfi\n\n# 3. Add the GPG key, the apt repo, update the apt cache, and install the package\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg\ninstall -o root -g root -m 644 /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/\nsh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/edge stable main\" > /etc/apt/sources.list.d/microsoft-edge-stable.list'\nrm /tmp/microsoft.gpg\napt-get update && apt-get install -y microsoft-edge-stable\n\nmicrosoft-edge-stable --version\n", "num_lines": 41}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\ncd /tmp\ncurl -o ./msedge_stable.pkg -k \"$1\"\n# Note: there's no way to uninstall previously installed MSEdge.\n# However, running PKG again seems to update installation.\nsudo installer -pkg /tmp/msedge_stable.pkg -target /\nrm -rf /tmp/msedge_stable.pkg\n/Applications/Microsoft\\ Edge.app/Contents/MacOS/Microsoft\\ Edge --version\n", "num_lines": 12}
{"repo_name": "lexical", "repo_creator": "facebook", "programming_language": "Shell", "code": "for package in  'lexical' \\\n                'lexical-react' \\\n                'lexical-yjs' \\\n                'lexical-list' \\\n                'lexical-table' \\\n                'lexical-file' \\\n                'lexical-clipboard' \\\n                'lexical-hashtag' \\\n                'lexical-history' \\\n                'lexical-selection' \\\n                'lexical-offset' \\\n                'lexical-code' \\\n                'lexical-plain-text' \\\n                'lexical-rich-text' \\\n                'lexical-utils' \\\n                'lexical-dragon' \\\n                'lexical-overflow' \\\n                'lexical-link' \\\n                'lexical-text' \\\n                'lexical-markdown' \\\n                'lexical-mark'\ndo\n  gen-flow-files \"./packages/${package}/src\" --out-dir \"./packages/${package}/dist\"\ndone", "num_lines": 24}
{"repo_name": "litho", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\n# litho-intellij-plugin\nDIR=$(dirname \"$0\")\ncd \"$DIR\"\nrm -rf build\necho \"./gradlew :litho-intellij-plugin:buildPlugin\"\n../gradlew :litho-intellij-plugin:buildPlugin &> /dev/null\n\ncd build/distributions\nmkdir tmp\nunzip -uoq litho-intellij-plugin.zip -d tmp\ncd tmp/litho-intellij-plugin/lib\nmkdir tmp\n\nfor filename in ./*.jar; do\n    [ -e \"$filename\" ] || continue\n    unzip -uoq \"$filename\" -d tmp\ndone\n\nrm ./*.jar\n\n_JAR=\"litho-intellij-plugin.jar\"\njar -cf \"$_JAR\" -C tmp .\n\necho \"$(pwd)/$_JAR\"\n\nwhile getopts \"p:\" opt; do\n  case $opt in\n    p)\n      cp \"$_JAR\" \"$OPTARG\"\n    ;;\n    \\?)\n      exit 1\n    ;;\n  esac\ndone\n", "num_lines": 54}
{"repo_name": "litho", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# litho-intellij-plugin\nDIR=$(dirname \"$0\")\ncd \"$DIR\" || exit 1\necho \"./gradlew :litho-intellij-plugin:test\"\n../gradlew :litho-intellij-plugin:test &> /dev/null\n", "num_lines": 21}
{"repo_name": "litho", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n[ -z \"$ANDROID_HOME\" ] && ANDROID_HOME=\"/opt/android_sdk\"\n\nif env | grep -q ^ANDROID_HOME=\nthen\n  echo \"ANDROID_HOME env variable is already exported\"\nelse\n  echo \"ANDROID_HOME env variable was not exported. setting it now\"\n  export ANDROID_HOME\nfi\n\n# New environment variables required\nexport ANDROID_SDK_ROOT=$ANDROID_HOME\n\nfunction download() {\n  if hash curl 2>/dev/null; then\n    curl -s -L -o \"$2\" \"$1\"\n  elif hash wget 2>/dev/null; then\n    wget -O \"$2\" \"$1\"\n  else\n    echo >&2 \"No supported download tool installed. Please get either wget or curl.\"\n    exit\n  fi\n}\n\nfunction installsdk() {\n  getAndroidSDK\n\n  PROXY_ARGS=\"\"\n  if [[ ! -z \"$HTTPS_PROXY\" ]]; then\n    PROXY_HOST=\"$(echo \"$HTTPS_PROXY\" | cut -d : -f 1,1)\"\n    PROXY_PORT=\"$(echo \"$HTTPS_PROXY\" | cut -d : -f 2,2)\"\n    PROXY_ARGS=\"--proxy=http --proxy_host=$PROXY_HOST --proxy_port=$PROXY_PORT\"\n  fi\n\n  echo y | \"$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager\" $PROXY_ARGS \"$@\"\n}\n\nfunction getAndroidSDK {\n  TMP=/tmp/sdk$$.zip\n\n  echo \"downloading sdk command line tools\"\n  download 'https://dl.google.com/android/repository/commandlinetools-linux-7302050_latest.zip' $TMP\n\n  echo \"clean $ANDROID_HOME\"\n  rm -r $ANDROID_HOME/*\n\n  echo \"unzipping to $ANDROID_HOME\"\n  unzip -qod $ANDROID_HOME/cmdline-tools/ $TMP\n\n  echo \"rename dir\"\n  mv $ANDROID_HOME/cmdline-tools/cmdline-tools $ANDROID_HOME/cmdline-tools/latest\n\n  echo \"deleting $TMP\"\n  rm $TMP\n}\n\nfunction installAndroidSDK {\n  export PATH=\"$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$PATH\"\n\n  mkdir -p \"$ANDROID_HOME/licenses/\"\n  echo > \"$ANDROID_HOME/licenses/android-sdk-license\"\n  echo -n 24333f8a63b6825ea9c5514f83c2829b004d1fee > \"$ANDROID_HOME/licenses/android-sdk-license\"\n\n  installsdk 'platforms;android-30' 'cmake;3.6.4111459' 'build-tools;30.0.2'\n}\n", "num_lines": 83}
{"repo_name": "litho", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to codemod all default state update calls to the sync variant\n# via a list of all specs. This is useful to keep current behavior, and then adopt\n# async behavior with new callsites.\n#\n# NOTE: This script is not perfect, and will 1) convert calls that match state\n# update calls in the same file 2) will miss state updates called from outside the\n# particular ComponentrSpec.\n\nall_specs=$1\n\nif [[ -z $all_specs ]]; then\n  # to generate this, you can run something like\n  # egrep -lir --include=*Spec.{java,kt} --exclude=./buck* \"@OnUpdateState\\b\" [directory_to_search] > all_specs_with_update_state.txt\n  echo \"Usage: $0 <all_specs_with_update_state.txt>\"\n  exit 1\nfi\n\nwhile read -r file; do\n  echo \"$file:\"\n\n  if ! matches=$(grep -A 1 \"@OnUpdateState\\b\" \"$file\" | grep void) || [[ -z $matches ]]; then\n    echo \"! No matches for $file.\"\n    continue\n  fi\n\n  while read -r m; do\n    if [[ $m =~ static\\ (<[a-zA-Z0-9\\ ]+>\\ )?void\\ ([a-zA-Z0-9]+)\\( ]]; then\n      method=${BASH_REMATCH[2]}\n      echo \"  ${BASH_REMATCH[2]}\"\n    else\n      echo \"! Failed match for $m\"\n      continue\n    fi\n\n    # Replace callsites with sync variant\n    sed -i \"\" -e 's/\\(\\.\\s*\\)'\"$method\"'(/\\1'\"$method\"'Sync(/g' \"$file\"\n\n  done <<< \"$matches\"\ndone < \"$all_specs\"\n", "num_lines": 55}
{"repo_name": "litho", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -ex\nshopt -s globstar\n\n# Deploys build artifacts to your local m2 repository.\nVERSION=\"0.1.0-SNAPSHOT\"\nTMPDIR=/tmp/m2tmp\n\n./gradlew assemble\n\nmkdir -p $TMPDIR\n\nfor file in **/build/libs/*.jar; do\n  ARTIFACT=$(basename \"$file\" | sed 's/\\.jar$//')\n\n  mvn install:install-file \\\n    -Dfile=$file \\\n    -DgroupId=com.facebook.litho \\\n    -DartifactId=$ARTIFACT \\\n    -Dversion=$VERSION \\\n    -Dpackaging=jar \\\n    -DcreateChecksum=true \\\n    -DlocalRepositoryPath=$TMPDIR\ndone\n\nfor file in **/build/outputs/**/*-release.aar; do\n  ARTIFACT=$(basename \"$file\" | sed 's/-release\\.aar$//')\n\n  mvn install:install-file \\\n    -Dfile=$file \\\n    -DgroupId=com.facebook.litho \\\n    -DartifactId=$ARTIFACT \\\n    -Dversion=$VERSION \\\n    -Dpackaging=aar \\\n    -DcreateChecksum=true \\\n    -DlocalRepositoryPath=$TMPDIR\ndone\n\nfor file in $TMPDIR/**/maven-metadata-local.xml*; do\n  RENAMED=$(echo $file | sed 's/-local\\.xml/.xml/')\n  mv $file $RENAMED\ndone\n\necho \"Local artifact deployment complete.\"\necho \"You can now upload you stuff, e.g. with \"\necho \"rsync --delete -avP /tmp/m2tmp/ $USER@remotehost:www/html/m2repo/\"\n", "num_lines": 61}
{"repo_name": "mariana-trench", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nD8=/opt/android/sdk_D37111790/build-tools/29.0.2/d8\n$D8 --min-api 24 --output classes_for_analysis.zip \"$@\"\n", "num_lines": 9}
{"repo_name": "mariana-trench", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Removes all `*.actual` suffixes from files in the directory above this.\n\nset -e\nset -x\n\nTHIS_DIRECTORY=$(cd -P \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\n\nfor file in $(find \"${THIS_DIRECTORY}/../\" -name \"*.actual\"); do\n  mv \"$file\" \"${file%.actual}\"\ndone\n", "num_lines": 17}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nautoreconf --install\n", "num_lines": 10}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script exists to generate the SSL certs used in unit tests.\n# It shouldn't really ever be run again until the year 2041\n# (when these certs expire)., unless you need to change\n# or update attributes of the certificate (Common Name, Organization,\n# whatever).\n\nset -e\n\nDAYS=10000\nCA_KEY=ca_key.pem\nCA_CERT=ca_cert.pem\nCA_CERT_SRL=ca_cert.srl\n\n# Generate Certificate Authority Key\nopenssl genrsa -out \"${CA_KEY}\" 2048\n\n# Generate Self-Signed Certificate Authority Cert\nopenssl req -x509 -new -nodes \\\n    -key \"${CA_KEY}\" \\\n    -days \"${DAYS}\" \\\n    -out \"${CA_CERT}\" \\\n    -subj '/C=US/O=Asox/CN=Asox Certification Authority'\n\n# CA serial number\necho 00000009 > ${CA_CERT_SRL}\n\nfunction generateCert() {\n    local KEYPREFIX=\"$1\"\n    local CN=$2\n    local TEST_KEY=\"${KEYPREFIX}_key.pem\"\n    local TEST_CERT=\"${KEYPREFIX}_cert.pem\"\n    local TEST_CERT_CSR=\"${KEYPREFIX}_cert.csr\"\n\n    cat > conf.tmp <<EOF\nprompt = no\n[req]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n\n[req_distinguished_name]\ncountryName = US\nstateOrProvinceName = Ohio\nlocalityName = Hilliard\ncommonName = $CN\n\n[v3_req]\n# Extensions to add to a certificate request\n# basicConstraints = CA:FALSE\n# keyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName = IP:$3, IP:$4\nEOF\n\n    # Generate the test key\n    openssl genrsa -out \"${TEST_KEY}\" 2048\n\n    # Generate the test key certificate request\n    openssl req -new -nodes \\\n\t-config conf.tmp \\\n\t-key \"${TEST_KEY}\" \\\n\t-days \"${DAYS}\" \\\n\t-out \"${TEST_CERT_CSR}\" \\\n\t-subj '/C=US/O=Asox/CN=Asox Town Limited'\n\n    # Sign the test key\n    openssl x509 -req \\\n\t-extensions v3_req \\\n\t-extfile conf.tmp \\\n\t-days \"${DAYS}\" \\\n\t-in \"${TEST_CERT_CSR}\" \\\n\t-CA \"${CA_CERT}\" \\\n\t-CAkey \"${CA_KEY}\" \\\n\t-out \"${TEST_CERT}\"\n\n    # Clean up the signing request\n    rm \"${TEST_CERT_CSR}\" conf.tmp\n}\n", "num_lines": 83}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# we assume the generate_key-inl.sh is in the same dir as this script\nROOT=$(dirname \"$0\")\n. \"$ROOT/generate_keys-inl.sh\"\n\ngenerateCert test Asox 127.0.0.1 ::1\ngenerateCert broken Asox 0.0.0.0 ::0\n\n# Clean up serial number\nrm \"${CA_CERT_SRL}\"\n", "num_lines": 16}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nsudo apt-get install -y libdouble-conversion1 libgflags2 \\\n    libboost-program-options1.54.0 libboost-filesystem1.54.0 \\\n    libboost-system1.54.0 libboost-regex1.54.0 libboost-thread1.54.0 \\\n    libboost-context1.54.0 libgoogle-glog0 libevent-2.0-5 libjemalloc1\n\nsudo apt-get purge -y gcc g++ ragel autoconf \\\n    git libtool python-dev libssl-dev libevent-dev \\\n    binutils-dev make libdouble-conversion-dev libgflags-dev \\\n    libgoogle-glog-dev libjemalloc-dev\n\nsudo apt-get purge -y 'libboost.*-dev'\nsudo apt-get autoremove --purge -y\nsudo apt-get autoclean -y\nsudo apt-get clean -y\n\nif [[ \"x$1\" != \"x\" ]]; then\n    PKG_DIR=$1/pkgs\n    INSTALL_DIR=$1/install\n    strip \"$INSTALL_DIR\"/bin/mcrouter\n    rm -rf \"$PKG_DIR\"\n    rm -rf \"$INSTALL_DIR\"/lib/*.a\n    rm -rf \"$INSTALL_DIR\"/include\nfi\n", "num_lines": 32}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nfunction die { printf \"%s: %s\\n\" \"$0\" \"$@\"; exit 1; }\n\n[ -n \"$1\" ] || die \"PKG_DIR missing\"\n[ -n \"$2\" ] || die \"INSTALL_DIR missing\"\n\nPKG_DIR=\"$1\"\nINSTALL_DIR=\"$2\"\nINSTALL_AUX_DIR=\"$3\"\nshift $#\nMAKE_ARGS=\"$@ -j$(nproc)\"\nSCRIPT_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\n\nmkdir -p \"$PKG_DIR\" \"$INSTALL_DIR\" \n\nif [ -n \"$3\" ]; then\n  mkdir -p \"$INSTALL_AUX_DIR\"\nfi\n\ncd \"$PKG_DIR\" || die \"cd fail\"\n", "num_lines": 27}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nMAKE_FILE=\"$1\"\nTARGET=\"$2\"\nPKG_DIR=\"${3%/}\"/pkgs\nINSTALL_DIR=\"${3%/}\"/install\nINSTALL_AUX_DIR=\"${3%/}\"/install/aux\n\n[ -n \"$MAKE_FILE\" ] || ( echo \"Make file missing\"; exit 1 )\n[ -n \"$TARGET\" ] || ( echo \"Target missing\"; exit 1 )\n\nmkdir -p \"$PKG_DIR\" \"$INSTALL_DIR\" \"$INSTALL_AUX_DIR\"\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\nREPO_BASE_DIR=\"$(cd ../../ && pwd)\" || die \"Couldn't determine repo top dir\"\nexport REPO_BASE_DIR\n\nexport LDFLAGS=\"-ljemalloc $LDFLAGS\"\n\nmake \"$TARGET\" -j3 -f \"$MAKE_FILE\" PKG_DIR=\"$PKG_DIR\" INSTALL_DIR=\"$INSTALL_DIR\" INSTALL_AUX_DIR=\"$INSTALL_AUX_DIR\"\n\nprintf \"%s\\n\" \"make $TARGET for $MAKE_FILE done\"\n", "num_lines": 30}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nORDER=\"$1\"\nPKG_DIR=\"${2%/}\"/pkgs\nINSTALL_DIR=\"${2%/}\"/install\nINSTALL_AUX_DIR=\"${2%/}\"/install/aux\nshift 2\n\nmkdir -p \"$PKG_DIR\" \"$INSTALL_DIR\" \"$INSTALL_AUX_DIR\"\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\nREPO_BASE_DIR=\"$(cd ../../ && pwd)\" || die \"Couldn't determine repo top dir\"\nexport REPO_BASE_DIR\n\nexport LDFLAGS=\"-ljemalloc $LDFLAGS\"\n\nfor script in $(ls \"order_$ORDER/\" | egrep '^[0-9]+_.*[^~]$' | sort -n); do\n  \"./order_$ORDER/$script\" \"$PKG_DIR\" \"$INSTALL_DIR\" \"$INSTALL_AUX_DIR\" \"$@\"\ndone\n\nprintf \"%s\\n\" \"Mcrouter installed in $INSTALL_DIR/bin/mcrouter\"\n", "num_lines": 29}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n[ -n \"$1\" ] || ( echo \"Install dir missing\"; exit 1 )\n\nsudo yum install -y epel-release\nsudo yum install -y centos-release-scl\n\n# Install devtoolset version 4 for GCC 5.x\nsudo yum install -y devtoolset-4-gcc devtoolset-4-gcc-c++\n\nexport CC=/opt/rh/devtoolset-4/root/usr/bin/gcc\nexport CXX=/opt/rh/devtoolset-4/root/usr/bin/c++\n\nsudo yum install -y \\\n    autoconf \\\n    binutils-devel \\\n    bison \\\n    boost-devel \\\n    cmake \\\n    double-conversion-devel \\\n    flex \\\n    git \\\n    gflags-devel \\\n    glog-devel \\\n    gtest-devel \\\n    jemalloc-devel \\\n    libtool \\\n    libevent-devel \\\n    make \\\n    openssl-devel \\\n    python-devel \\\n    ragel\n\n# Install automake-1.15 from Fedora\nyum info automake-1.15-4.fc23 || sudo yum install -y \"http://archives.fedoraproject.org/pub/archive/fedora/linux/releases/23/Everything/x86_64/os/Packages/a/automake-1.15-4.fc23.noarch.rpm\"\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\n./get_and_build_everything.sh centos-7.2 \"$@\"\n", "num_lines": 46}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n[ -n \"$1\" ] || ( echo \"Install dir missing\"; exit 1 )\n\nsudo add-apt-repository -y ppa:ubuntu-toolchain-r/test\nsudo add-apt-repository -y ppa:george-edison55/cmake-3.x\nsudo add-apt-repository -y ppa:chris-lea/libsodium\nsudo add-apt-repository -y ppa:sickpig/boost\n\nsudo apt-get update\n\nsudo apt-get install -y \\\n    autoconf \\\n    binutils-dev \\\n    bison \\\n    cmake \\\n    flex \\\n    g++ \\\n    g++-5 \\\n    gcc \\\n    git \\\n    libboost1.58-dev \\\n    libboost-thread1.58-dev \\\n    libboost-filesystem1.58-dev \\\n    libboost-context1.58-dev \\\n    libboost-regex1.58-dev \\\n    libboost-program-options1.58-dev \\\n    libbz2-dev \\\n    libdouble-conversion-dev \\\n    libevent-dev \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libjemalloc-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    liblzma5 \\\n    libsnappy-dev \\\n    libsodium-dev \\\n    libssl-dev \\\n    libtool \\\n    make \\\n    pkg-config \\\n    python-dev \\\n    ragel \\\n    software-properties-common\n\n# sudo apt-get upgrade -yq cmake\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\nexport CC=\"gcc-5\"\nexport CXX=\"g++-5\"\n\n./get_and_build_everything.sh ubuntu-14.04 \"$@\"\n", "num_lines": 61}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n[ -n \"$1\" ] || ( echo \"Install dir missing\"; exit 1 )\n\nsudo apt-get update\n\nsudo apt-get install -y \\\n    autoconf \\\n    binutils-dev \\\n    bison \\\n    cmake \\\n    flex \\\n    g++ \\\n    gcc \\\n    git \\\n    libboost1.55-all-dev \\\n    libbz2-dev \\\n    libdouble-conversion-dev \\\n    libevent-dev \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libjemalloc-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    liblzma5 \\\n    libsnappy-dev \\\n    libsodium-dev \\\n    libssl-dev \\\n    libtool \\\n    make \\\n    pkg-config \\\n    python-dev \\\n    ragel\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\n./get_and_build_everything.sh ubuntu-15.04 \"$@\"\n", "num_lines": 44}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n[ -n \"$1\" ] || ( echo \"Install dir missing\"; exit 1 )\n\nsudo apt-get update\n\n# Note libzstd-dev is not available on stock Ubuntu 14.04 or 15.04.\nsudo apt-get install -y \\\n    autoconf \\\n    binutils-dev \\\n    bison \\\n    cmake \\\n    flex \\\n    g++ \\\n    gcc \\\n    git \\\n    libboost1.58-all-dev \\\n    libbz2-dev \\\n    libdouble-conversion-dev \\\n    libevent-dev \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libjemalloc-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    liblzma5 \\\n    libsnappy-dev \\\n    libsodium-dev \\\n    libssl-dev \\\n    libtool \\\n    libunwind8-dev \\\n    make \\\n    pkg-config \\\n    python-dev \\\n    ragel\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\n./get_and_build_everything.sh ubuntu-16.04 \"$@\"\n", "num_lines": 46}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nBASE_DIR=\"$1\"\nTARGET=\"${2:-all}\"\n\n[ -n \"$BASE_DIR\" ] || ( echo \"Base dir missing\"; exit 1 )\n\nsudo apt-get update\n\n# Note libzstd-dev is not available on stock Ubuntu 14.04 or 15.04.\nsudo apt-get install -y \\\n    autoconf \\\n    binutils-dev \\\n    bison \\\n    cmake \\\n    flex \\\n    g++ \\\n    gcc \\\n    git \\\n    libboost1.65-all-dev \\\n    libbz2-dev \\\n    libdouble-conversion-dev \\\n    libevent-dev \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libjemalloc-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    liblzma5 \\\n    libsnappy-dev \\\n    libsodium-dev \\\n    libssl-dev \\\n    libtool \\\n    libunwind8-dev \\\n    make \\\n    pkg-config \\\n    python-dev \\\n    ragel\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\n./get_and_build_by_make.sh \"Makefile_ubuntu-18.04\" \"$TARGET\" \"$BASE_DIR\"\n", "num_lines": 49}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nBASE_DIR=\"$1\"\nTARGET=\"${2:-all}\"\n\n[ -n \"$BASE_DIR\" ] || ( echo \"Base dir missing\"; exit 1 )\n\nsudo apt-get update\n\n# Note libzstd-dev is not available on stock Ubuntu 14.04 or 15.04.\nsudo apt-get install -y \\\n    autoconf \\\n    binutils-dev \\\n    bison \\\n    cmake \\\n    flex \\\n    g++ \\\n    gcc \\\n    git \\\n    libboost1.71-all-dev \\\n    libbz2-dev \\\n    libdouble-conversion-dev \\\n    libevent-dev \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libjemalloc-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    liblzma5 \\\n    libsnappy-dev \\\n    libsodium-dev \\\n    libssl-dev \\\n    libtool \\\n    libunwind8-dev \\\n    make \\\n    pkg-config \\\n    python-dev \\\n    ragel \\\n    sudo\n\ncd \"$(dirname \"$0\")\" || ( echo \"cd fail\"; exit 1 )\n\n./get_and_build_by_make.sh \"Makefile_ubuntu-20.04\" \"$TARGET\" \"$BASE_DIR\"\n", "num_lines": 50}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ $# -lt 2 ]; then\n  echo -e \\\n    \"Usage: ./$(basename \"$0\") package_dir install_dir [install_aux_dir]\\n\" \\\n    \"  where\\n\" \\\n    \"    package_dir - location where all packages should be download.\\n\" \\\n    \"    install_dir - location where all packages should be installed.\\n\" \\\n    \"                  Note: it should already contain a built version of mcrouter in it.\\n\" \\\n    \"                        i.e. there should be a binary install_dir/bin/mcrouter\\n\\n\" \\\n    \"    install_aux_dir - aux location where all packages should be installed  \\n\\n\" \\\n    \"You can also alter script behavior by setting next environment variables:\\n\" \\\n    \"  MEMCACHED_PORT - port that would be used by memcached (default: 15000)\\n\" \\\n    \"  MCROUTER_PORT - port that would be used by mcrouter (default: 15001)\\n\" \\\n    \"  RUN_DURATION - duration of each individual run in seconds (time during which we \\n\" \\\n    \"                 collect performance measurements).\\n\" \\\n    \"                 Note: it doesn't include startup, warmup and cleanup time.\\n\" \\\n    \"                 (default: 30)\\n\" \\\n    \"  TWEMPERF_BIN - path to twemperf binary.\\n\" \\\n    \"                 By default we would download and build a version from github.\\n\" \\\n    \"  MEMCACHED_BIN - path to memcached binary.\\n\" \\\n    \"                  By default we would lookup up for installed memcached, if none \\n\" \\\n    \"                  found, we would download and build it on our own.\"\n  exit 0\nfi\n\n# This port will be used for running our own memcached instance.\nMEMCACHED_PORT=${MEMCACHED_PORT:-15000}\n\n# This port will be used for running mcrouter instance.\nMCROUTER_PORT=${MCROUTER_PORT:-15001}\n\n# Duration of individual workload run.\nRUN_DURATION=${RUN_DURATION:-30}\n\nsudo apt-get install -y wget gcc g++ libevent-dev make build-essential\n\nsource common.sh\n\n# Disable verbose logging.\nset +x\n\nif [ ! -d \"$INSTALL_DIR/bin\" ]; then\n  mkdir \"$INSTALL_DIR/bin\"\nfi\n\n# Ensure that we have twemperf installed.\nif [ -z \"$TWEMPERF_BIN\" ]; then\n  echo -n \"TWEMPERF_BIN is not set...\"\n  TWEMPERF_BIN=$INSTALL_DIR/bin/mcperf\n  if [ ! -e \"$TWEMPERF_BIN\" ]; then\n    if [ ! -d twemperf ]; then\n      echo -n \"Downloading source code...\"\n      git clone https://github.com/twitter/twemperf || die \"Failed to clone twemperf\"\n    else\n      echo -n \"Found cloned repo...\"\n    fi\n\n    echo -n \"Building it...\"\n\n    cd twemperf && autoreconf -i && ./configure && make -j 4 && cd .. || die \"Failed to build twemperf\"\n    ln -s \"$PKG_DIR/twemperf/src/mcperf\" \"$TWEMPERF_BIN\" || die \"Couldn't install twemperf into $TWEMPERF_BIN\"\n\n    echo \"Twemperf was installed to $TWEMPERF_BIN\"\n  else\n    echo \"Found existing installation of twemperf in $TWEMPERF_BIN\"\n  fi\nelse\n  echo \"TWEMPERF_BIN is set to $TWEMPERF_BIN\"\nfi\n\n# Ensure that we have memcached installed.\necho -n \"Looking for memcached installation...\"\nif [ -z \"$MEMCACHED_BIN\" ]; then\n  echo -n \"MEMCACHED_BIN is not defined...\"\n  if MEMCACHED_BIN=$(which memcached); then\n    echo \"Found memcached: $MEMCACHED_BIN\"\n  else\n    MEMCACHED_BIN=$INSTALL_DIR/bin/memcached\n    if [ ! -e \"$MEMCACHED_BIN\" ]; then\n      if [ ! -d memcached-1.4.24 ]; then\n        echo -n \"Downloading source code...\"\n        wget http://www.memcached.org/files/memcached-1.4.24.tar.gz &> /dev/null || die \"Failed to download memcached source code!\"\n        tar -xvf memcached-1.4.24.tar.gz || die \"Failed to extract memcached source code\"\n      fi\n      echo -n \"Building it...\"\n\n      cd memcached-1.4.24 && ./configure && make all && cd .. || die \"Failed to build memcached!\"\n      ln -s \"$PKG_DIR/memcached-1.4.24/memcached\" \"$MEMCACHED_BIN\" || die \"Couldn't install memcached into $MEMCACHED_BIN\"\n\n      echo \"Memcached was installed to $MEMCACHED_BIN\"\n    else\n      echo \"Found existing installation of memcached in $MEMCACHED_BIN\"\n    fi\n  fi\nelse\n  echo \"MEMCACHED_BIN is set to $MEMCACHED_BIN\"\nfi\n\n# Check that we have mcrouter.\nMCROUTER_BIN=$INSTALL_DIR/bin/mcrouter\nif [ ! -e \"$MCROUTER_BIN\" ]; then\n  die \"Cannot find mcrouter in install dir, please build and install it before running loadtest!\"\nfi\n\n# Workload runner, accepts next arguments, runs it for 30 seconds\n#  $1 - number of connections.\n#  $2 - qps.\n#  $3 - method (e.g. get, set, gets, cas, etc.)\nfunction run_workload() {\n  # We're goin to start spawning child processes, set up a trap to properly clean them up.\n  function cleanup() {\n    kill \"$MEMCACHED_PID\" \"$MCROUTER_PID\" \"$TWEMPERF_PID\" &> /dev/null\n\n    # Allow everything to shutdown.\n    sleep 2\n  }\n\n  trap cleanup EXIT\n\n  # Start memcached.\n  \"$MEMCACHED_BIN\" -t 1 -p \"$MEMCACHED_PORT\" &> /dev/null &\n  MEMCACHED_PID=$!\n\n  # Allow memcached some time to startup.\n  sleep 1\n\n  # Check that memcached is running.\n  echo version | nc 0 \"$MEMCACHED_PORT\" | grep \"VERSION\" &> /dev/null || die \"Failed to start memcached!\"\n\n  \"$MCROUTER_BIN\" --config-str=\"{\\\"pools\\\":{\\\"A\\\":{\\\"servers\\\":[\\\"localhost:$MEMCACHED_PORT\\\"],\\\"server_timeout\\\":1000}},\\\"route\\\":\\\"Pool|A\\\"}\" -p \"$MCROUTER_PORT\" &> /dev/null &\n  MCROUTER_PID=$!\n\n  # Allow mcrouter some time to startup.\n  sleep 1\n\n  # Check that mcrouter is running.\n  echo version | nc 0 \"$MCROUTER_PORT\" | grep \"mcrouter\" &> /dev/null || die \"Failed to start mcrouter!\"\n\n  # Calculate total number of calls to do.\n  let \"NUM_CALLS = $2 * ($RUN_DURATION + 6) / $1\"\n\n  \"$TWEMPERF_BIN\" --server=localhost --port=\"$MCROUTER_PORT\" --num-conns=\"$1\" --call-rate=\"$2\" --num-calls=\"$NUM_CALLS\" --method=\"$3\" &> /dev/null &\n  TWEMPERF_PID=$!\n\n  # Wait for a couple of seconds.\n  sleep 3\n\n  # Collect CPU usage of mcrouter.\n  PIDSTAT_OUT=$(pidstat -h -p \"$MCROUTER_PID\" \"$RUN_DURATION\" 1 | grep -v Linux | grep -v '#' | grep -v -e '^$' | awk '{print $7}')\n\n  echo \"$PIDSTAT_OUT\"\n}\n\necho \"**************************************************************************\"\necho \"**************************************************************************\"\n\necho -n \"Running workload (num connections = 100, qps = 20000, method = set)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 20000 set)%\"\n\necho -n \"Running workload (num connections = 100, qps = 40000, method = set)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 40000 set)%\"\n\necho -n \"Running workload (num connections = 100, qps = 80000, method = set)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 80000 set)%\"\n\necho -n \"Running workload (num connections = 100, qps = 20000, method = get)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 20000 get)%\"\n\necho -n \"Running workload (num connections = 100, qps = 40000, method = get)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 40000 get)%\"\n\necho -n \"Running workload (num connections = 100, qps = 80000, method = get)... \"\necho \" Mcrouter CPU usage: $(run_workload 100 80000 get)%\"\n", "num_lines": 179}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n## Set version\ncd \"$SCRIPT_DIR\"/../\necho -n $(git tag|tail -1) > \"$SCRIPT_DIR\"/../VERSION\n\n## Build\nsource /opt/rh/gcc-toolset-9/enable\nsed -i '/m4_append.*mcrouter_version.*/d' \"$SCRIPT_DIR\"/../configure.ac\n\"$SCRIPT_DIR\"/get_and_build_everything.sh centos-7.2 \"$MCROUTER_DIR\"\n\n## Cleanup\nrm -rf \"$MCROUTER_DIR/pkgs\"\nrm -rf \"$INSTALL_DIR/lib/*.a\"\nrm -rf \"$INSTALL_DIR/include\"\n\ndnf remove -y   git \\\n                cmake \\\n                gcc-toolset* \\\n                autoconf \\\n                which \\\n                make \\\n                automake \\\n                wget \\\n                file \\\n                binutils-devel \\\n                glibc-devel \\\n                bzip2-devel \\\n                xz-devel \\\n                openssl-devel \\\n                python3-devel \\\n                gtest-devel \\\n                python3-pkgconfig\n\nrm -rf \"$MCROUTER_DIR/repo\"\n", "num_lines": 40}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n## Install deps\ndnf -y install epel-release \\\n                dnf-plugins-core \\\n                https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm\ndnf config-manager --set-enabled powertools\ndnf update -y\n\ndnf install -y \\\n    git \\\n    gcc-toolset-9-gcc \\\n    gcc-toolset-9-gcc-c++ \\\n    autoconf \\\n    binutils-devel \\\n    glibc-devel \\\n    file \\\n    cmake \\\n    wget \\\n    which \\\n    double-conversion-devel \\\n    flex \\\n    zstd \\\n    libzstd-devel \\\n    bzip2-devel \\\n    glog-devel \\\n    gtest-devel \\\n    jemalloc-devel \\\n    libtool \\\n    libunwind \\\n    libunwind-devel \\\n    pkgconf-pkg-config \\\n    python3-pkgconfig \\\n    lz4-devel \\\n    xz-devel \\\n    xz-libs \\\n    libevent-devel \\\n    make \\\n    openssl-devel \\\n    python3-devel \\\n    snappy-devel \\\n    libsodium-devel \\\n    ragel \\\n    automake.noarch \\\n    libicu \\\n    libicu-devel\n\n## Download the mcrouter project\nmkdir -p \"$MCROUTER_DIR/repo\" && \\\ncd \"$MCROUTER_DIR/repo\" && git clone --branch \"$MCROUTER_VERSION\" \"$MCROUTER_REPO\"\n\n## Enable gcc toolset\nsource /opt/rh/gcc-toolset-9/enable\n\n## Boost\ndnf remove -y boost-devel\nBOOST_VERSION_MOD=\"boost_$(echo $BOOST_VERSION | tr '.' '_')\"\nwget \"https://boostorg.jfrog.io/artifactory/main/release/$BOOST_VERSION/source/$BOOST_VERSION_MOD.tar.gz\"\ntar -xzf \"$BOOST_VERSION_MOD.tar.gz\" && cd \"$BOOST_VERSION_MOD\"\n./bootstrap.sh \"--prefix=$INSTALL_DIR\"\n./b2 install \"--prefix=$INSTALL_DIR\"\ncd - && rm -rf ./boost\n\n## Fmt\ngit clone --branch \"$FMT_VERSION\" https://github.com/fmtlib/fmt.git fmt_lib\ncd fmt_lib && cmake -DBUILD_SHARED_LIBS=TRUE -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\"\nmake -j$(nproc) && make -j$(nproc) install\ncd - && rm -rf fmt_lib\n\n## Snappy\ngit clone --branch \"$SNAPPY_VERSION\" https://github.com/google/snappy.git snappy_lib\ncd snappy_lib && git submodule update --init\nmkdir build && cd build && cmake ../\nmake -j$(nproc) && make -j$(nproc) install\ncd \"$SCRIPT_DIR\"\nrm -rf snappy_lib\n\n## Gflags\ndnf remove -y gflags gflags-devel\ngit clone --branch \"$GFLAGS_VERSION\" https://github.com/gflags/gflags.git gflags\nmkdir gflags/build && cd gflags/build\nexport LDFLAGS=\"-Wl,-rpath=$INSTALL_DIR/lib,--enable-new-dtags -L$INSTALL_DIR/lib $LDFLAGS\"\nexport CPPFLAGS=\"-I$INSTALL_DIR/include -DGFLAGS_DLL_DECL='' $CPPFLAGS\"\ncmake ../ -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" -DBUILD_SHARED_LIBS=ON\nmake -j$(nproc) && make -j$(nproc) install\ncd - && rm -rf gflags\n\n## Bison\nBISON_VERION_MOD=\"$(echo $BISON_VERSION | egrep -o '[0-9]\\.[0-9]\\.[0-9]')\"\nwget \"https://ftp.gnu.org/gnu/bison/bison-$BISON_VERION_MOD.tar.xz\"\ntar -xf \"./bison-$BISON_VERION_MOD.tar.xz\"\ncd \"bison-$BISON_VERION_MOD\" && ./configure\nmake -j$(nproc) && make -j$(nproc) install\ncd - && rm -rf ./\"bison-$BISON_VERION_MOD\"\n\n## Install Folly deps before building folly\nsed -i '/cd \\\"\\$PKG_DIR\\/folly\\\".*/a ./build/fbcode_builder/getdeps.py install-system-deps --recursive' \"$SCRIPT_DIR/recipes/folly.sh\"\n\n## Use dnf instead of yum in fbthrift\nsed -i '/dnf.*/a ./build/fbcode_builder/getdeps.py install-system-deps --recursive fbthrift' \"$SCRIPT_DIR/recipes/fbthrift.sh\"\n\n## Glog\nsed -i 's/git clone.*/wget https:\\/\\/github.com\\/google\\/glog\\/archive\\/refs\\/tags\\/v0.4.0.tar.gz/g' \"$SCRIPT_DIR/recipes/glog.sh\"\nsed -i '/wget.*/a\\ \\ \\ \\ tar -zxf .\\/v0.4.0.tar.gz' \"$SCRIPT_DIR/recipes/glog.sh\"\nsed -i '/if/! s/DIR\\/glog/DIR\\/glog-0.4.0/g' \"$SCRIPT_DIR/recipes/glog.sh\"\nln -s \"$SCRIPT_DIR/recipes/glog.sh\" \"$SCRIPT_DIR/order_centos-7.2/01_glog\"\n\n## Patching mcrouter scripts to build with new libs\nsed -i '/AC_HAVE_LIBRARY.*gflags/,+1d' \"${MCROUTER_DIR}/repo/mcrouter/mcrouter/configure.ac\"\nsed -i '/if.*mcrouter_cv_prog_cc_gflags/,+2d' \"${MCROUTER_DIR}/repo/mcrouter/mcrouter/configure.ac\"\nsed -i 's/lib\\ $LDFLAGS/lib64 -L$INSTALL_DIR\\/lib $LDFLAGS/g' \"$SCRIPT_DIR/recipes/mcrouter.sh\"\nsed -i 's/configure.*/& --with-boost-libdir=\\/usr\\/local\\/mcrouter\\/install\\/lib/g' \"$SCRIPT_DIR/recipes/mcrouter.sh\"\nsed -i 's/LD_LIBRARY_PATH=\"/&$INSTALL_DIR\\/lib64\\:/g' \"$SCRIPT_DIR/recipes/mcrouter.sh\"\n\n## Pretend python 3 is installed (required for build)\nln -s /usr/bin/python3.6 /usr/bin/python\n", "num_lines": 123}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\n## Install runtime dependencies\ndnf update -y\ndnf install -y \\\n            double-conversion-devel \\\n            jemalloc-devel \\\n            libunwind \\\n            pkgconf-pkg-config \\\n            lz4-devel \\\n            xz-libs \\\n            libevent-devel \\\n            snappy-devel \\\n            libsodium-devel \\\n            libicu\n\n## Create mcrouter default dirs\nmkdir -p /var/mcrouter/stats\nmkdir -p /var/mcrouter/fifos\nmkdir -p /var/mcrouter/config\nchgrp -R 0 /var/mcrouter\nchmod -R g=u /var/mcrouter\n\n## Create spooldir\nmkdir -p /var/spool/mcrouter\nchgrp -R 0 /var/spool/mcrouter\nchmod -R g=u /var/spool/mcrouter\n\n## Make runnable from any context\nln -s \"$INSTALL_DIR/bin/mcrouter\" /usr/bin/mcrouter\necho \"export LD_LIBRARY_PATH=\\\"$INSTALL_DIR/lib64:$INSTALL_DIR/lib:$LD_LIBRARY_PATH\\\"\" >> /etc/profile.d/mcrouter_libs.sh\nchmod +x /etc/profile.d/mcrouter_libs.sh\necho \"export LD_PRELOAD=/usr/lib64/libjemalloc.so.2\" >> ~/.bashrc\n", "num_lines": 40}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n## Build\nmkdir -p $MCROUTER_DIR/repo\ncd $MCROUTER_DIR/repo && git clone $MCROUTER_REPO\ncd $MCROUTER_DIR/repo/mcrouter/mcrouter/scripts\nsed -i 's/sudo //g' ./install_ubuntu_20.04.sh\nsed -i 's/MAKE_ARGS=\\\"\\$@\\\"/MAKE_ARGS=\\\"-j$(nproc)\\\"/g' ./common.sh\n./install_ubuntu_20.04.sh $MCROUTER_DIR\n\n## Cleanup\napt-get purge -y pkg-config cmake\nsed -i 's/sudo //g' ./clean_ubuntu_14.04.sh\nsed -i 's/libdouble-conversion1/libdouble-conversion3/g' ./clean_ubuntu_14.04.sh\nsed -i 's/libgflags2/libgflags2.2/g' ./clean_ubuntu_14.04.sh\nsed -i 's/1\\.54\\.0/1.71.0/g' ./clean_ubuntu_14.04.sh\nsed -i 's/libevent-2.0-5/libevent-2.1-7/g' ./clean_ubuntu_14.04.sh\nsed -i 's/libjemalloc1/libjemalloc2/g' ./clean_ubuntu_14.04.sh\nsed -i 's/libgoogle-glog0/libgoogle-glog0v5/g' ./clean_ubuntu_14.04.sh\n./clean_ubuntu_14.04.sh $MCROUTER_DIR && rm -rf $MCROUTER_DIR/repo\n\n## Prepare for use\nln -s $MCROUTER_DIR/install/bin/mcrouter /usr/local/bin/mcrouter\n", "num_lines": 28}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\napt -y update\napt -y install apt-transport-https \\\n                ca-certificates \\\n                tzdata \\\n                git\napt clean all\n", "num_lines": 13}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [[ ! -d \"$PKG_DIR/fbthrift\" ]]; then\n  git clone https://github.com/facebook/fbthrift\n  cd \"$PKG_DIR/fbthrift\" || die \"cd fail\"\n  if [[ -f \"$REPO_BASE_DIR/mcrouter/FBTHRIFT_COMMIT\" ]]; then\n    FBTHRIFT_COMMIT=\"$(head -n 1 \"$REPO_BASE_DIR/mcrouter/FBTHRIFT_COMMIT\")\"\n    echo \"FBTHRIFT_COMMIT file found: using fbthrift commit $FBTHRIFT_COMMIT\"\n    git checkout \"$FBTHRIFT_COMMIT\"\n  else\n    echo \"No FBTHRIFT_COMMIT file, using fbthrift HEAD=$(git rev-parse HEAD)\"\n  fi\nfi\n\ncd \"$PKG_DIR/fbthrift/build\" || die \"cd fbthrift failed\"\n\nCXXFLAGS=\"$CXXFLAGS -fPIC\" \\\ncmake .. -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\"\nmake $MAKE_ARGS && make install $MAKE_ARGS\n", "num_lines": 26}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [[ ! -d fizz ]]; then\n  git clone https://github.com/facebookincubator/fizz\n  cd \"$PKG_DIR/fizz\" || die \"cd fail\"\n  if [[ -f \"$REPO_BASE_DIR/mcrouter/FIZZ_COMMIT\" ]]; then\n    FIZZ_COMMIT=\"$(head -n 1 \"$REPO_BASE_DIR/mcrouter/FIZZ_COMMIT\")\"\n    echo \"FIZZ_COMMIT file found: using fizz commit $FIZZ_COMMIT\"\n    git checkout \"$FIZZ_COMMIT\"\n  else\n    echo \"No FIZZ_COMMIT file, using fizz HEAD=$(git rev-parse HEAD)\"\n  fi\nfi\n\ncd \"$PKG_DIR/fizz/fizz/\" || die \"cd fail\"\n\ncmake . -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" -DBUILD_TESTS=OFF\nmake $MAKE_ARGS && make install $MAKE_ARGS\n", "num_lines": 25}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [[ ! -d \"$PKG_DIR/fmt\" ]]; then\n  git clone https://github.com/fmtlib/fmt\n  cd \"$PKG_DIR/fmt\" || die \"cd failed\"\n  mkdir \"$PKG_DIR/fmt/build\"\nfi\n\ncd \"$PKG_DIR/fmt/build\" || die \"cd fmt failed\"\n\nCXXFLAGS=\"$CXXFLAGS -fPIC\" \\\n  cmake .. -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\"\nmake $MAKE_ARGS && make install $MAKE_ARGS\n\n", "num_lines": 21}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [[ ! -d folly ]]; then\n  git clone https://github.com/facebook/folly\n  cd \"$PKG_DIR/folly\" || die \"cd fail\"\n  if [[ -f \"$REPO_BASE_DIR/mcrouter/FOLLY_COMMIT\" ]]; then\n    FOLLY_COMMIT=\"$(head -n 1 \"$REPO_BASE_DIR/mcrouter/FOLLY_COMMIT\")\"\n    echo \"FOLLY_COMMIT file found: using folly commit $FOLLY_COMMIT\"\n    git checkout \"$FOLLY_COMMIT\"\n  else\n    echo \"No FOLLY_COMMIT file, using folly HEAD=$(git rev-parse HEAD)\"\n  fi\nfi\n\nif [ ! -d /usr/include/double-conversion ]; then\n  if [ ! -d \"$PKG_DIR/double-conversion\" ]; then\n    cd \"$PKG_DIR\" || die \"cd fail\"\n    git clone https://github.com/google/double-conversion.git\n  fi\n  cd \"$PKG_DIR/double-conversion\" || die \"cd fail\"\n\n  # Workaround double-conversion CMakeLists.txt changes that\n  # are incompatible with cmake-2.8\n  git checkout ea970f69edacf66bd3cba2892be284b76e9599b0\n  cmake . -DBUILD_SHARED_LIBS=ON -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\"\n  make $MAKE_ARGS && make install $MAKE_ARGS\n\n  export LDFLAGS=\"-L$INSTALL_DIR/lib -ldl $LDFLAGS\"\n  export CPPFLAGS=\"-I$INSTALL_DIR/include $CPPFLAGS\"\nfi\n\nif [ ! -d \"$PKG_DIR/zstd\" ]; then\n  cd \"$PKG_DIR\" || die \"cd fail\"\n  git clone https://github.com/facebook/zstd\n\n  cd \"$PKG_DIR/zstd\" || die \"cd fail\"\n\n  # Checkout zstd-1.4.9 release\n  git checkout e4558ffd1dc49399faf4ee5d85abed4386b4dcf5\n  cmake -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" build/cmake/\n  make $MAKE_ARGS && make install $MAKE_ARGS\nfi\n\ncd \"$PKG_DIR/folly/folly/\" || die \"cd fail\"\n\nCXXFLAGS=\"$CXXFLAGS -fPIC\" \\\n    LD_LIBRARY_PATH=\"$INSTALL_DIR/lib:$LD_LIBRARY_PATH\" \\\n    LD_RUN_PATH=\"$INSTALL_DIR/lib:$LD_RUN_PATH\" \\\n    cmake .. \\\n    -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" \\\n    -DCMAKE_INCLUDE_PATH=\"$INSTALL_DIR/lib\" \\\n    -DCMAKE_LIBRARY_PATH=\"$INSTALL_DIR/lib\"\nmake $MAKE_ARGS && make install $MAKE_ARGS\n", "num_lines": 60}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [ ! -d \"$PKG_DIR/glog\" ]; then\n    git clone https://github.com/google/glog.git\n    cd \"$PKG_DIR/glog\" || die \"cd fail\"\n\n    autoreconf --install\n    LDFLAGS=\"-Wl,-rpath=$INSTALL_DIR/lib,--enable-new-dtags \\\n             -L$INSTALL_DIR/lib $LDFLAGS\" \\\n        CPPFLAGS=\"-I$INSTALL_DIR/include -DGOOGLE_GLOG_DLL_DECL='' $CPPFLAGS\" \\\n        ./configure --prefix=\"$INSTALL_DIR\" && \\\n        make $MAKE_ARGS && make install $MAKE_ARGS\nfi\n", "num_lines": 20}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [ ! -d \"$PKG_DIR/glog\" ]; then\n    git clone https://github.com/google/googletest.git \"$PKG_DIR/gtest\" \\\n        --branch v1.10.x --depth 1\n    cd \"$PKG_DIR/gtest\" || die \"cd fail\"\n\n    cmake . \\\n        -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" \\\n        -DCMAKE_INSTALL_LIBDIR=\"lib\"\n    make $MAKE_ARGS && make install $MAKE_ARGS\nfi\n", "num_lines": 19}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\ncd \"$SCRIPT_DIR/../..\" || die \"cd fail\"\n\nautoreconf --install\nLD_LIBRARY_PATH=\"$INSTALL_DIR/lib:$LD_LIBRARY_PATH\" \\\n    LD_RUN_PATH=\"$INSTALL_DIR/lib:$LD_RUN_PATH\" \\\n    LDFLAGS=\"-L$INSTALL_DIR/lib $LDFLAGS\" \\\n    CPPFLAGS=\"-I$INSTALL_DIR/include $CPPFLAGS\" \\\n    FBTHRIFT_BIN=\"$INSTALL_DIR/bin/\" \\\n    ./configure --prefix=\"$INSTALL_DIR\"\nmake $MAKE_ARGS && make install $MAKE_ARGS\n", "num_lines": 19}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\ngrab http://python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz\ntar xf Python-2.7.6.tar.xz\ncd Python-2.7.6\n./configure --prefix=\"$INSTALL_DIR\" --enable-unicode=ucs4 --enable-shared \\\n    LDFLAGS=\"-Wl,-rpath /usr/local/lib\" && make $MAKE_ARGS && make altinstall $MAKE_ARGS\n", "num_lines": 14}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nsource common.sh\n\nif [[ ! -d wangle ]]; then\n  git clone https://github.com/facebook/wangle\n  cd \"$PKG_DIR/wangle\" || die \"cd fail\"\n  if [[ -f \"$REPO_BASE_DIR/mcrouter/WANGLE_COMMIT\" ]]; then\n    WANGLE_COMMIT=\"$(head -n 1 \"$REPO_BASE_DIR/mcrouter/WANGLE_COMMIT\")\"\n    echo \"WANGLE_COMMIT file found: using wangle commit $WANGLE_COMMIT\"\n    git checkout \"$WANGLE_COMMIT\"\n  else\n    echo \"No WANGLE_COMMIT file, using wangle HEAD=$(git rev-parse HEAD)\"\n  fi\nfi\n\ncd \"$PKG_DIR/wangle/wangle/\" || die \"cd fail\"\n\ncmake . -DCMAKE_INSTALL_PREFIX=\"$INSTALL_DIR\" -DBUILD_TESTS=OFF\nmake $MAKE_ARGS && make install $MAKE_ARGS\n", "num_lines": 25}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nROOT_PATH=\"$(pwd)\"\nSCRIPT_PATH=\"$(dirname \"$0\")\"\ncd \"$SCRIPT_PATH\"/../.. && \"$ROOT_PATH/$1\"\n", "num_lines": 10}
{"repo_name": "mcrouter", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nPYTHON_PATH=\"$1\"\nTEST_NAME=\"$(basename \"$2\")\"\nTEST_MODULE=\"${TEST_NAME%.*}\"\nSCRIPT_PATH=\"$(dirname \"$0\")\"\ncd \"$SCRIPT_PATH\"/../.. && $PYTHON_PATH -B -m unittest -q mcrouter.test.\"$TEST_MODULE\"\n", "num_lines": 12}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# Create MySQL cmake configure wrapper\n\ndie() { echo \"$@\"; exit 1; }\n\n# Use a configure script that will call CMake.\npath=`dirname $0`\ncp $path/cmake_configure.sh $path/../configure\nchmod +x $path/../configure\n", "num_lines": 28}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\ndie()\n{\n  echo \"ERROR: $@\"; exit 1;\n}\n\nget_key_value()\n{\n  echo \"$1\" | sed 's/^--[a-zA-Z_-]*=//'\n}\n\ndeveloper_usage()\n{\ncat <<EOF\n\n  This script can be used by developers of MySQL, early adopters wanting \n  to try out early versions of MySQL before binary versions are \n  available, anyone needing a version with a special patch included that \n  needs to be built from source code, or anyone else wanting to exercise \n  full control over the MySQL build process.\n\n  This help text is targeted towards those that want to debug and test \n  MySQL using source code releases. If you have downloaded a source code \n  release and simply want to build a usable binary, you should read the \n  --sysadmin-help instead.\n\n  The script is also designed to be used by anyone receiving a source \n  code release of MySQL Cluster Carrier Grade Edition. The default\n  behaviour is to build the standard MySQL Cluster Carrier Grade Edition\n  package. Three environment variables can be used to change the \n  default behaviour:\n\n  MYSQL_DEVELOPER\n    Defining this variable is similar to setting the --developer flag\n  MYSQL_DEVELOPER_PACKAGE=package\n    Defining this variable is similar to setting the --package=* \n    variable\n  MYSQL_DEVELOPER_DEBUG\n    Defining this variable sets the --with-debug flag\n\n  Options used with this script always override any default behaviour. \n  The default package is MySQL Cluster Carrier Grade (standard) Edition. \n  For developers, the default package is MySQL Cluster Carrier Grade \n  Extended Edition.\n\n  More information for developers can be found in --help, \n  --sysadmin-help, and --extended-help.\n\n  The most common usage for developers is to set the three variables \n  mentioned previously and then simply to run the script without any \n  additional parameters, using them only when needing to change some \n  things like not requiring debug build. If some of these environment \n  variables have already been set, you can use the corresponding options \n  to unset them and reverse their effects.\nEOF\n}\n\nsysadmin_usage()\n{\ncat <<EOF\n\n  This script can be used to build MySQL Cluster Carrier Grade Edition\n  based on a source code release you received from MySQL. It can also\n  be used to build many variants other variants of MySQL, in particular\n  various performance-optimised versions of MySQL.\n\n  It is assumed that you are building on a computer which is of the \n  same type as that on which you intend to run MySQL/MySQL Cluster.\n\n  The simplest possible way to run this script is to allow it to use the \n  built-in defaults everywhere, invoking it simply as (from top-level\n  MySQL directory):\n\n  shell> BUILD/build_mccge.sh\n\n  This performs the following operations:\n    1) Detects the operating system. Currently, Linux, FreeBSD, Solaris \n      8/9/10/11, and Mac OS X are supported by this script.\n    2) Detect the type of CPU being used. Currently supported processors \n      are: x86 for all supported operating systems, Itanium for Linux \n      with GCC, and x86 + SPARC for Solaris using the Forte compiler and\n      finally x86 on Linux using the Intel compiler.\n    3) Invokes the GCC compiler.\n    4) Builds a set of MySQL/MySQL Cluster binaries; for\n      more information about these, see --extended-help.\n    5) Default compiler is always gcc.\n  \n  The default version assumes that you have a source code tarball from \n  which you are building, and thus autoconf and automake do not need to \n  be run. If you have downloaded a BitKeeper tree then you should read \n  --developer-help.\n\n  If you are building MySQL/MySQL Cluster for commercial \n  use then you need to set the --commercial flag to ensure that the \n  commercial libraries are compiled in, rather than the GPL-only \n  libraries. The default is to build a GPL version of MySQL Cluster \n  Carrier Grade Edition.\n\n  If your building on a Solaris SPARC machine and you want to compile\n  using SunStudio you must set \n  --compiler=forte; if you want to build using the Intel compiler on \n  Linux, you need to set --compiler=icc. If you want to use the AMD\n  compiler Open64 set --compiler=open64.\n\n  A synonym for forte is SunStudio, so one can also use\n  --compiler=SunStudio.\n\n  If you want to make sure that a 64-bit version is built then you \n  should add the flag --64. This is always set on Solaris machines and \n  when check-cpu is able to discover that a 64-bit CPU is being used. If \n  you want to ensure that a 32-bit binary is produced, use --32 instead.\n\n  If you need the binaries to be installed in a different location from \n  /usr/local/mysql, then you should set --prefix to point to where you\n  want the binaries installed.\n\n  Using a data directory other than the default (PREFIX/data) can be \n  done when starting the MySQL Server, or by invoking this script with \n  the --datadir option.\n\n  If you want your binaries stripped of surplus debug or other \n  information, use the --strip option.\n\n  If you want debug information in the binary (for example, to be\n  able to send gdb core dumps to MySQL Support), then you should add the \n  flag --with-debug; if you want a production build with only debugging \n  information in the binary then use --debug.\n\n  If your aim is not to build MySQL Cluster Carrier Grade Edition, you \n  can also use this script to build MySQL Classic and MySQL Enterprise Pro \n  versions; see the --extended-help for descriptions of these packages.\nEOF\n}\n\nusage()\n{\ncat <<EOF\n\nUsage: $0 [options]\n  --help                  Show this help message.\n  --sysadmin-help         Show help for system administrators wishing \n                          to build MySQL Cluster Carrier Grade Edition\n                          or other MySQL versions.\n  --developer-help        Show help for developers trying to build MySQL\n  --with-help             Show extended help on --with-xxx options to \n                          configure\n  --extended-help         Show extended help message\n  --without-debug         Build non-debug version\n  --use-comment           Set the comment in the build\n  --with-fast-mutexes     Use try/retry method of acquiring mutex\n  --without-fast-mutexes  Don't use try/retry method of acquiring mutex\n  --without-perfschema    Don't build with performance schema\n  --generate-feedback path Compile with feedback using the specified directory\n                          to store the feedback files\n  --use-feedback path     Compile using feedback information from the specified\n                          directory\n  --with-debug            Build debug version\n  --extra-debug-flag flag Add -Dflag to compiler flags\n                          InnoDB supports the following debug flags,\n                          UNIV_DEBUG, UNIV_SYNC_DEBUG, UNIV_MEM_DEBUG,\n                          UNIV_DEBUG_THREAD_CREATION, UNIV_DEBUG_LOCK_VALIDATE,\n                          UNIV_DEBUG_PRINT, UNIV_DEBUG_FILE_ACCESS,\n                          UNIV_LIGHT_MEM_DEBUG, UNIV_LOG_DEBUG,\n                          UNIV_IBUF_COUNT_DEBUG, UNIV_SEARCH_DEBUG,\n                          UNIV_LOG_LSN_DEBUG, UNIV_ZIP_DEBUG, UNIV_AHI_DEBUG,\n                          UNIV_DEBUG_VALGRIND, UNIV_SQL_DEBUG, UNIV_AIO_DEBUG,\n                          UNIV_BTR_DEBUG, UNIV_LRU_DEBUG, UNIV_BUF_DEBUG,\n                          UNIV_HASH_DEBUG, UNIV_LIST_DEBUG, UNIV_IBUF_DEBUG\n  --with-link-time-optimizer\n                          Link time optimizations enabled (Requires GCC 4.5\n                          if GCC used), available for icc as well. This flag\n                          is only considered if also fast is set.\n  --with-mso              Special flag used by Open64 compiler (requres at\n                          least version 4.2.3) that enables optimisations\n                          for multi-core scalability.\n  --configure-only        Stop after running configure.\n  --print-only            Print commands that the script will execute, \n                          but do not actually execute\n  --prefix=path           Build with prefix 'path'\n  --datadir=path          Build with data directory set to non-standard \n                          'path'\n  --debug                 Build normal version, but add debug \n                          information to binary\n  --developer             Use extensions that most MySQL developers use\n  --no-developer          Do not use extensions that most developers of \n                          MySQL use\n  --commercial            Use commercial libraries\n  --gpl                   Use gpl libraries\n  --compiler=[gcc|icc|forte|SunStudio|open64] Select compiler\n  --cpu=[x86|x86_64|sparc|itanium]            Select CPU type\n                          x86 => x86 and 32-bit binary\n                          x86_64 => x86 and 64 bit binary\n  --warning-mode=[extra|pedantic|normal|no]   Set warning mode level\n  --warnings              Set warning mode to normal\n  --32                    Build a 32-bit binary even if CPU is 64-bit\n  --64                    Build a 64-bit binary even if not sure a\n                          64-bit CPU is being used\n  --package=[cge|extended|pro|classic]        Select package to build\n  --parallelism=number    Define parallelism in make\n  --strip                 Strip binaries\n  --error-inject          Enable error injection into MySQL Server and \n                          data nodes\n  --valgrind              Build with valgrind\n  --fast                  Optimise for CPU architecture built on\n  --static-linking        Statically link system libraries into binaries\n  --use-tcmalloc          Link with tcmalloc instead of standard malloc (Linux only)\n  --with-flags *          Pass extra --with-xxx options to configure\nEOF\n  if test \"x$1\" != \"x\" ; then\n    echo \"Failure Message: $1\"\n  fi\n}\n\nextended_usage()\n{\n  cat <<EOF\n\n  Extended help text for this script:\n  -----------------------------------\n  This script is intended to make it easier for customers using MySQL\n  Cluster Carrier Grade Edition, customers using performance-optimised\n  MySQL versions and developers to build the product from source on \n  these platforms/compilers: Linux/x86 (32-bit and 64-bit) (either using\n  gcc or icc), Linux Itanium, Solaris 8,9,10 and 11 x86 and SPARC using\n  gcc or SunStudio and MacOSX/x86/gcc.\n\n  The script automatically detects CPU type and operating system; The\n  default compiler is always gcc.\n\n  To build on other platforms you can use the --print-only option on a\n  supported platform and edit the output for a proper set of commands on\n  the specific platform you are using. MySQL also provides custom builds\n  for any type of platform that is officially supported for MySQL\n  Cluster. For a list of supported platforms, see\n  http://www.mysql.com/support/supportedplatforms/cluster.html.\n\n  Using the --package option, it is also possible to build a \"classic\"\n  version of MySQL having only the MyISAM storage engine, a \"Pro\"\n  package including all storage engines and other features except MySQL\n  Cluster, and an \"extended\" package including these features plus MySQL\n  Cluster (this is the default if the --developer option is used).\n\n  Different MySQL storage engines are included in the build, depending\n  on which --package option is used. The comment and version strong\n  suffix are also set according to the package selected.\n\n  --package=cge\n    storage engines:\n      ARCHIVE, BLACKHOLE, CSV, FEDERATED, MYISAM, NDB\n      (All storage engines except InnoDB)\n    comment: MySQL Cluster Carrier Grade Edition GPL/Commercial version \n             built from source\n    version string suffix: -cge\n\n  --package=extended\n    storage engines:\n      ARCHIVE, BLACKHOLE, CSV, FEDERATED, MYISAM, INNODB, NDB\n      (All storage engines)\n    comment: MySQL Cluster Carrier Grade Extended Edition GPL/Commercial \n             version built from source\n    version string suffix: -cge-extended\n\n  --package=pro\n    storage engines:\n      ARCHIVE, BLACKHOLE, CSV, FEDERATED, INNODB, MYISAM\n      (All storage engines except NDB)\n    comment: MySQL Pro GPL/Commercial version built from \n             source\n    version string suffix: [none]\n\n  --package=classic\n    storage engines: CSV, MYISAM\n    comment: MySQL Classic GPL/Commercial version built \n             from source\n    version string suffix: [none]\n\n  All packages except Classic include support for user-defined\n  partitioning. All packages include support for Performance\n  Schema.\n\n  If --with-debug is used, an additional \"-debug\" is appended to the\n  version string.\n\n  --commercial\n    This flag prevents the use of GPL libraries which cannot be used\n    under a commercial license, such as the readline library.\n\n  --developer\n    This option changes a number of things to make the version built\n    more appropriate to the debugging and testing needs of developers. \n    It changes the default package to \"extended\". It also changes the \n    default warning mode from \"none\" to \"normal\", which allows an \n    extensive list of warnings to be generated.\n\n  --error-inject\n    This flag is used only when the --developer option is also used, and\n    enables error injection in both the MySQL Server and in MySQL\n    Cluster data nodes.\n\n  The following is a list of the default configure options used for all\n  packages:\n\n  --prefix: /usr/local/mysql (can be overridden)\n\n  --libexecdir: <prefix>/bin (can be overridden)\n\n  --localstatedir: <prefix>/data, unless --datadir is used, in which\n    case it defaults to <datadir>/data (can be overridden by setting\n    --localstatedir explicitly).\n\n  --enable-local-infile: Enable use of the LOAD DATA FROM  LOCAL INFILE\n    command (cannot be overridden).\n\n  --enable-thread-safe-client: Enable the multi-threaded mysql client\n    library (cannot be overridden).\n\n  --with-big-tables: Enable use of tables with more than 4G rows (cannot\n    be overridden).\n\n  --with-extra-charsets=all: Enable use of all character sets supported\n    by MySQL (cannot be overridden).\n\n  --with-ssl: Enable use of yaSSL library included in the MySQL source\n    if possible (GCC and same CC and CXX).\n    (cannot be overridden).\n\n  --with-pic: Build all binaries using position independent assembler\n    to avoid problems with dynamic linkers (cannot be overridden).\n\n  --without-example-engine: Ensure that the example engine isn't built,\n    it cannot do any useful things, it's merely intended as documentation.\n    (cannot be overridden)\n\n  --with-csv-storage-engine: Ensure that the CSV storage engine is\n    included in all builds. Since CSV is required for log tables in\n    MySQL 5.1, this option cannot be overridden.\n\n    (Note that MyISAM support is always built into the MySQL Server; the\n    server *cannot* be built without MyISAM.)\n\n  --with-mysqld-ldflags=-static\n  --with-client-ldflags=-static\n    Ensures that binaries for, respectively, the MySQL server and client\n    are built with static libraries except for the system libraries,\n    which use dynamically loaded libraries provided by the operating\n    system. Building with --developer sets these to all-static instead, \n    to build everything statically.\n\n  In addition there are some configure options that are specific to\n  Linux operating systems:\n\n  --enable-assembler\n    Include assembler code optimisations for a number of mostly string\n    methods. Used for x86 processors only.\n\n  Neither of the preceding options can be disabled.\n\n  MySQL Cluster Carrier Grade edition also adds the following options\n  (also used by the extended package):\n\n  --with-ndbcluster\n    Include the NDB Cluster storage engine, its kernel, management\n    server, and client, as well as support for the NDB and MGM APIs.\n\n  --without-ndb-debug\n    Do not include specific NDB debug code, not even in debug versions\n    (cannot be overridden).\n\n  Package-specific options:\n  -------------------------\n  --with-innodb\n    Specifically included in the \"pro\" and \"extended\" packages, and not \n    in any of the others.\n\n  --with-comment\n    Sets the comment for the MySQL version, by package, as described\n    above.\n\n  --with-server-suffix\n    Sets the server suffix on the MySQL version, by package, as\n    described above.\n\n  Other options used:\n  -------------------\n  --with-readline\n    Use the GPL readline library for command editing functions; not\n    available with commercial packages.\n\n  --with-libedit\n    Use the BSD licensed library for command editing functions; used for\n    commercial packages.\n\n  --with-zlib-dir=bundled\n    Use the zlib package bundled with MySQL.\n\n  --with-mysqld-libs=-lmtmalloc\n    Used on Solaris to ensure that the proper malloc library is used.\n    Investigations have shown mtmalloc to be the best choice on Solaris,\n    also umem has good performance on Solaris but better debugging\n    capabilities.\n\n  Compiler options:\n  -----------------\n\n    This section describes the compiler options for each of the different\n    platforms supported by this script.\n\n    The --fast option adds -mtune=cpu_arg to the C/C++ flags (provides\n    support for Nocona, K8, and other processors), this option is valid\n    when gcc is the compiler.\n\n    Use of the --debug option adds -g to the C/C++ flags.\n\n    In all cases it is possible to override the definition of CC and CXX\n    by calling the script as follows:\n    CC=\"/usr/local/bin/gcc\" CXX=\"/usr/local/bin/g++\" BUILD/build_mccge.sh\n\n  Feedback profiler on gcc\n  ------------------------\n  Using gcc --generate-feedback=path causes the following flags to be added\n  to the compiler flags.\n\n  --fprofile-generate\n  --fprofile-dir=path\n\n  Using gcc with --use-feedback=path causes the following flags to be added\n  to the compiler flags. --fprofile-correction indicates MySQL is a multi-\n  threaded application and thus counters can be inconsistent with each other\n  and the compiler should take this into account.\n\n  --fprofile-use\n  --fprofile-dir=path\n  --fprofile-correction\n\n  Feedback compilation using Open64\n  ---------------------------------\n\n  Using Open64 with --generate-feedback=path causes the following flags to\n  be added to the compiler flags.\n\n  -fb-create path/feedback\n\n  Using Open64 with --use-feedback=path causes the following flags to be\n  added to the compiler flags.\n\n  --fb-opt path/feedback\n\n  Linux/x86+Itanium/gcc\n  -------------\n    For debug builds -O is used and otherwise -O3 is used.Discovery of a\n    Nocona or Core 2 Duo CPU causes a 64-bit binary to be built;\n    otherwise, the binary is 32-bit. To build a 64-bit binary, -m64 is\n    added to the C/C++ flags. (To build a 32-bit binary on a 64-bit CPU,\n    use the --32 option as described previously.)\n\n    When gcc 4.5 is used and the user set --with-link-time-optimizer then\n    also --flto is added to compiler flags and linker flags.\n\n  Linux/x86+Itanium/icc\n  -------------\n    Flags used:\n    CC  = icc -static-libgcc -static-intel\n    C++ = icpc -static-libgcc -static-intel\n    C/C++ flags = -mp -restrict\n\n    On Itanium we also add -no-ftz and to CC and C++ flags.\n\n    Note that if the user of this script sets CC or CXX explicitly then\n    also -static-libgcc and -static-intel needs to be set in the CC and\n    CXX.\n\n    The non-debug versions also add the following:\n      C/C++ flags += -O3 unroll2 -ip\n\n    The fast version adds (if --with-link-time-optimizer is used):\n      C/C++ flags += -ipo\n\n    On discovery of a Core 2 Duo architecture while using icc, -xT is also \n    added to the C/C++ flags; this provides optimisations specific to Core \n    2 Duo. This is added only when the --fast flag is set.\n\n  Linux/x86/Open64\n  ----------------\n    For normal builds use -O3, when fast flag is set one also adds\n    --march=auto to generate optimized builds for the CPU used. If\n    --with-link-time-optimizer is set also -ipa is set. There is also\n    a special flag --with-mso which can be set to get --mso set which\n    activates optimisation for multi-core scalability.\n\n  FreeBSD/x86/gcc\n  ---------------\n    No flags are used. Instead, configure determines the proper flags to \n    use.\n\n  Solaris/x86/gcc\n  ---------------\n    All builds on Solaris are by default 64-bit, so -m64 is always used in\n    the C/C++ flags. LDFLAGS is set to -m64 -O/-O2/-O3. If for\n    some reason a 32-bit Solaris is used it is necessary to add the flag\n    --32 to the script invocation. Due to bugs in compiling with -O3 on\n    Solaris only -O2 is used by default, when --fast flag is used -O3 will\n    be used instead.\n\n    Sets -m64 (default) or -m32 (if specifically set) in LDFLAGS and\n    C/C++ flags.\n\n  Solaris/Sparc/Forte\n  -------------------\n    Uses cc as CC and CC as CXX\n    Note that SunStudio uses different binaries for C and C++ compilers.\n\n    Set -m64 (default) or -m32 (if specifically set) in ASFLAGS,\n    LDFLAGS and C/C++ flags.\n\n    Sets ASFLAGS=LDFLAGS=compiler flags=xarch=sparc, so that we compile\n    Sparc v9 binaries, also -mt is set in all those since we're always\n    building a multithreaded program.\n\n    C flags   = -xstrconst    This flag is set only on SPARC\n    C++ flags = -noex\n\n    Set the following C/C++ flags:\n    -fsimple=1\n    -ftrap=%none\n    -nofstore          This flag is set only on x86\n    -xbuiltin=%all\n    -xlibmil\n    -xlibmopt\n\n    Set the C++ flag:\n    -noex\n    -features=no%except    This flag is set only on x86\n\n    When compiling with fast we set (-ipo only used if we have\n    set --with-link-time-optimizer):\n    C/C++ flags: -xtarget=native -xunroll=3 -xipo\n    LDFLAGS: -xipo\n\n    When not compiling with fast we always set -xtarget=generic\n\n    When compiling with fast on SPARC we also set:\n    C/C++ flags: -xbinopt=prepare\n    LDFLAGS: -xbinopt=prepare\n\n    When compiling with fast on x86 we also set:\n    C/C++ flags: -xregs=frameptr\n    When not compiling with fast we set on x86\n    C/C++ flags: -xregs=no%frameptr\n\n    On SPARC we set\n    ASFLAGS = LDFLAGS = C/C++ flags = -xarch=sparc\n\n    The optimisation level is\n    -xO         Debug builds\n    -xO2        Production build on SPARC\n    -xO3        Production build on x86\n    -xO4        Fast builds on SPARC/x86\n\n  MacOSX/x86/gcc\n  --------------\n    C/C++ flags include -fno-common -arch i386.\n    When 64-bits builds then i386 is replaced by x86_64.\n\n    Non-debug versions also add -Os -felide-constructors, where \"-Os\"\n    means the build is space-optimised as long as the space optimisations\n    do not negatively affect performance. Debug versions use -O.\n  \n    Mac OS X builds will always be 32-bit by default, when --64 is added\n    the build will be 64 bit instead. Thus the flag --m64 is added only\n    when specifically given as an option.\nEOF\n}\n\nwith_usage()\n{\n  cat <<EOF\n\n  To obtain extended help on the --with-* options available, run this\n  script with --configure-only to create a configuration file. Then\n  issue the command ./configure --help to get an extensive list of\n  possible configure options.\n\n  The remainder of this text focuses on those options which are useful\n  in building binaries for MySQL Cluster Carrier Grade Edition.\n\n  --with-ndb-sci=/opt/DIS\n    Used to build a MySQL Cluster Carrier Grade Edition that can use the\n    SCI Transporter. The Dolphin SCI installation must be completed\n    first (see \n    http://dev.mysql.com/doc/refman/5.1/en/mysql-cluster-interconnects.html\n    for more information).\n\n  --with-ndb-test\n    Compile the MySQL Cluster test programs.\n\n  --with-ndb-port=PORT\n    Change the default port for the MySQL Cluster management server.\n\n  --with-ndb-port-base=PORT\n    Change the default port base for MySQL Cluster data nodes.\n\n  --without-query-cache\n    Build the MySQL Server without the query cache, which is often not\n    of value in MySQL Cluster applications.\n\n  --with-atomic-ops=rwlocks|smp|up\n                          Implement atomic operations using pthread\n                          rwlocks or atomic CPU instructions for\n                          multi-processor (default) or single-processor\n                          configurations.\n\n  --without-geometry      Do not build geometry-related portions of the\n                          MySQL Server. Seldom used in MySQL Cluster\n                          applications.\n\n  --with-ndb-cc-flags=FLAGS\n    This option can be used to build MySQL Cluster with error injection\n    on the data nodes. It can be used to pass special options to\n    programs in the NDB kernel for special test builds.\n    The option for enabling data node error injection is -DERROR_INSERT.\nEOF\n}\n\nparse_package()\n{\n  case \"$package\" in\n    classic )\n      package=\"classic\"\n      ;;\n    pro )\n      package=\"pro\"\n      ;;\n    extended )\n      package=\"extended\"\n      ;;\n    cge )\n      package=\"cge\"\n      ;;\n    *)\n      echo \"Unknown package '$package'\"\n      exit 1\n      ;;\n  esac\n}\n\nparse_warning_mode()\n{\n  case \"$warning_mode\" in\n    pedantic )\n      warning_mode=\"pedantic\"\n      ;;\n    extra_warnings | extra-warnings | extra )\n      warning_mode=\"extra\"\n      ;;\n    no )\n      warning_mode=\n      ;;\n    normal )\n      warning_mode=\"normal\"\n      ;;\n    *)\n      echo \"Unknown warning mode '$warning_mode'\"\n      exit 1\n      ;;\n  esac\n}\n\n#\n# We currently only support x86, Itanium and UltraSparc processors.\n#\nparse_cpu_type()\n{\n  case \"$cpu_type\" in\n    x86 )\n      cpu_type=\"x86\"\n      if test \"x$m64\" = \"x\" ; then\n        m64=\"no\"\n      fi\n      ;;\n    x86_64 )\n      cpu_type=\"x86\"\n      if test \"x$m64\" = \"x\" ; then\n        m64=\"yes\"\n      fi\n      ;;\n    itanium )\n      cpu_type=\"itanium\"\n      ;;\n    sparc )\n      cpu_type=\"sparc\"\n      ;;\n    * )\n      echo \"Unknown CPU type $cpu_type\"\n      exit 1\n      ;;\n  esac\n  return\n}\n\n#\n# We currently only support gcc, icc and Forte.\n#\nparse_compiler()\n{\n  case \"$compiler\" in\n    gcc )\n      compiler=\"gcc\"\n      ;;\n    icc )\n      compiler=\"icc\"\n      ;;\n    forte | SunStudio | sunstudio )\n      compiler=\"forte\"\n      ;;\n    open64 | Open64 )\n      compiler=\"open64\"\n      ;;\n    *)\n      echo \"Unknown compiler '$compiler'\"\n      exit 1\n      ;;\n  esac\n}\n\nparse_options()\n{\n  while test $# -gt 0\n  do\n    case \"$1\" in\n    --prefix=*)\n      prefix=`get_key_value \"$1\"`\n      ;;\n    --datadir=*)\n      datadir=`get_key_value \"$1\"`\n      ;;\n    --with-link-time-optimizer)\n      with_link_time_optimizer=\"yes\"\n      ;;\n    --without-debug)\n      with_debug_flag=\"no\"\n      if test \"x$fast_flag\" != \"xyes\" ; then\n        fast_flag=\"generic\"\n      fi\n      ;;\n    --use-comment)\n      without_comment=\"no\"\n      ;;\n    --with-fast-mutexes)\n      with_fast_mutexes=\"yes\"\n      ;;\n    --without-fast-mutexes)\n      with_fast_mutexes=\"no\"\n      ;;\n    --without-perfschema)\n      with_perfschema=\"no\"\n      ;;\n    --with-mso)\n      with_mso=\"yes\"\n      ;;\n    --use-tcmalloc)\n      use_tcmalloc=\"yes\"\n      ;;\n    --with-debug)\n      with_debug_flag=\"yes\"\n      fast_flag=\"no\"\n      ;;\n    --extra-debug-flag)\n      shift\n      extra_debug_flags=\"$extra_debug_flags -D$1\"\n      ;;\n    --debug)\n      compile_debug_flag=\"yes\"\n      ;;\n    --no-developer)\n      developer_flag=\"no\"\n      ;;\n    --developer)\n      developer_flag=\"yes\"\n      ;;\n    --commercial)\n      gpl=\"no\"\n      ;;\n    --gpl)\n      gpl=\"yes\"\n      ;;\n    --compiler=*)\n      compiler=`get_key_value \"$1\"`\n      parse_compiler\n      ;;\n    --generate-feedback)\n      shift\n      GENERATE_FEEDBACK_PATH=\"$1\"\n      ;;\n    --use-feedback)\n      shift\n      USE_FEEDBACK_PATH=\"$1\"\n      ;;\n    --cpu=*)\n      cpu_type=`get_key_value \"$1\"`\n      parse_cpu_type\n      ;;\n    --warning-mode=*)\n      warning_mode=`get_key_value \"$1\"`\n      parse_warning_mode\n      ;;\n    --warnings)\n      warning_mode=\"normal\"\n      ;;\n    --32)\n      if test \"x$explicit_size_set\" != \"x\" ; then\n        echo \"Cannot set both --32 and --64\"\n        exit 1\n      fi\n      explicit_size_set=\"yes\"\n      m64=\"no\"\n      ;;\n    --64)\n      if test \"x$explicit_size_set\" != \"x\" ; then\n        echo \"Cannot set both --32 and --64\"\n        exit 1\n      fi\n      explicit_size_set=\"yes\"\n      m64=\"yes\"\n      ;;\n    --package=*)\n      package=`get_key_value \"$1\"`\n      parse_package\n      ;;\n    --parallelism=*)\n      parallelism=`get_key_value \"$1\"`\n      ;;\n    --configure-only)\n      just_configure=\"yes\"\n      ;;\n    --print-only)\n      just_print=\"yes\"\n      ;;\n    --static-linking)\n      static_linking_flag=\"yes\"\n      ;;\n    --strip)\n      strip_flag=\"yes\"\n      ;;\n    --error-inject)\n      error_inject_flag=\"yes\"\n      ;;\n    --valgrind)\n      valgrind=\"yes\"\n      ;;\n    --fast)\n      fast_flag=\"yes\"\n      ;;\n    --with-flags)\n      shift\n      break\n      ;;\n    --with-help)\n      with_usage\n      exit 0\n      ;;\n    --sysadmin-help)\n      sysadmin_usage\n      exit 0\n      ;;\n    --developer-help)\n      developer_usage\n      exit 0\n      ;;\n    --extended-help)\n      extended_usage\n      exit 0\n      ;;\n    --help)\n      usage\n      exit 0\n      ;;\n    *)\n      echo \"Unknown option '$1'\"\n      exit 1\n      ;;\n    esac\n    shift\n  done\n  for flag in $@\n  do\n    with_flags=\"$with_flags $flag\"\n  done\n}\n\n#\n# We currently only support Linux, FreeBSD/OpenBSD, Mac OS X and Solaris\n#\ncheck_os()\n{\n  case \"`uname -s`\" in\n    Linux)\n      os=\"linux\"\n      ;;\n    FreeBSD|OpenBSD)\n      os=\"bsd\"\n      ;;\n    Darwin)\n      os=\"MacOSX\"\n      ;;\n    SunOS)\n      os=\"Solaris\"\n      ;;\n    *)\n      os=\"Unknown\"\n      ;;\n  esac\n\n}\n\nset_cpu_base()\n{\n  if test \"x$cpu_type\" = \"x\" ; then\n    if test \"x$cpu_arg\" = \"x\" ; then\n      usage \"CPU type not discovered, cannot proceed\"\n      exit 1\n    fi\n    case \"$cpu_arg\" in\n      core2 | nocona | prescott | pentium* | i*86 )\n        # Intel CPU\n        cpu_base_type=\"x86\"\n        ;;\n      athlon* | opteron* | k6 | k8 )\n        # AMD CPU\n        cpu_base_type=\"x86\"\n        ;;\n      sparc )\n        cpu_base_type=\"sparc\"\n        ;;\n      itanium )\n        cpu_base_type=\"itanium\"\n        ;;\n      * )\n        usage \"CPU type $cpu_arg not handled by this script\"\n        exit 1\n        ;;\n    esac\n  else\n    cpu_base_type=\"$cpu_type\"\n    check_cpu_cflags=\"\"\n  fi\n  if test \"x$os\" = \"xMacOSX\" ; then\n    if test \"x$m64\" = \"x\" ; then\n      m64=\"no\"\n    fi\n  elif test \"x$os\" = \"xSolaris\" ; then\n    if test \"x$m64\" = \"x\" ; then\n      m64=\"yes\"\n    fi\n  elif test \"x$m64\" = \"x\" ; then\n    if test \"x$cpu_arg\" = \"xnocona\" || test \"x$cpu_arg\" = \"xcore2\" || \\\n       test \"x$cpu_arg\" = \"xathlon64\" || test \"x$cpu_arg\" = \"xopteron\" ; then\n      m64=\"yes\"\n    else\n      m64=\"no\"\n    fi\n  fi\n  echo \"Discovered CPU of type $cpu_base_type ($cpu_arg) on $os\"\n  if test \"x$m64\" = \"xyes\" ; then\n    echo \"Will compile 64-bit binaries\"\n  else\n    echo \"Will compile 32-bit binaries\"\n  fi\n  return 0\n}\n\n#\n# Add to the variable commands with the configure command\n# \ninit_configure_commands()\n{\n  path=`dirname $0`\n  cp $path/cmake_configure.sh $path/../configure\n  chmod +x $path/../configure\n  cflags=\"$c_warnings $base_cflags $compiler_flags\"\n  cxxflags=\"$cxx_warnings $base_cxxflags $compiler_flags\"\n  configure=\"./configure $base_configs $with_flags\"\n\n  env_flags=\"CC=\\\"$CC\\\" CFLAGS=\\\"$cflags\\\" CXX=\\\"$CXX\\\" CXXFLAGS=\\\"$cxxflags\\\"\"\n  if test \"x$LDFLAGS\" != \"x\" ; then\n    env_flags=\"$env_flags LDFLAGS=\\\"$LDFLAGS\\\"\"\n  fi\n  if test \"x$ASFLAGS\" != \"x\" ; then\n    env_flags=\"$env_flags ASFLAGS=\\\"$ASFLAGS\\\"\"\n  fi\n  commands=\"$commands\n    $env_flags $configure\"\n} \n\n#\n# Initialise the variable commands with the commands needed to generate\n# the configure script.\n#\ninit_auto_commands()\n{\n  set_libtoolize_version\n  commands=\"\\\n  $make -k maintainer-clean || true\n  /bin/rm -rf */.deps/*.P configure config.cache\n  /bin/rm -rf  storage/*/configure storage/*/config.cache autom4te.cache\n  /bin/rm -rf storage/*/autom4te.cache;\"\n#\n# --add-missing instructs automake to install missing auxiliary files\n# and --force to overwrite them if they already exist\n#\n  commands=\"$commands\n  aclocal || die \\\"Can't execute aclocal\\\"\n  autoheader || die \\\"Can't execute autoheader\\\"\n  $LIBTOOLIZE --automake --copy --force || die \\\"Can't execute libtoolize\\\"\n  automake --add-missing --copy --force || die \\\"Can't execute automake\\\"\n  autoconf || die \\\"Can't execute autoconf\\\"\"\n}\n\n#\n# Add to the variable commands the make command and possibly also\n# strip commands\n#\nadd_make_commands()\n{\n  AM_MAKEFLAGS=\"-j $parallelism\"\n  commands=\"$commands\n  $make $AM_MAKEFLAGS\"\n\n  if test \"x$strip_flag\" = \"xyes\" ; then\n    commands=\"$commands\n    mkdir -p tmp\n    nm --numeric-sort sql/mysqld  > tmp/mysqld.sym\n    objdump -d sql/mysqld > tmp/mysqld.S\n    strip sql/mysqld\n    strip storage/ndb/src/kernel/ndbd\n    strip storage/ndb/src/mgmsrv/ndb_mgmd\n    strip storage/ndb/src/mgmclient/ndb_mgm\"\n  fi\n}\n\n#\n# Set make version, but only gmake is supported :)\n#\nset_make_version()\n{\n  if gmake --version > /dev/null 2>&1\n  then\n    make=gmake\n  else\n    make=make\n  fi\n  if test \"x`$make --version | grep GNU`\" = \"x\" ; then\n    die \"Only gmake is supported\"\n  fi\n}\n\n#\n# Find a libtoolize binary, both libtoolize and glibtoolize are\n# ok, use first found.\n#\nset_libtoolize_version()\n{\n  LIBTOOLIZE=not_found\n  save_ifs=\"$IFS\"; IFS=':'\n  for dir in $PATH\n  do\n    if test -x $dir/libtoolize\n    then\n      LIBTOOLIZE=libtoolize\n      echo \"Found libtoolize in $dir\"\n      break\n    fi\n    if test -x $dir/glibtoolize\n    then\n      LIBTOOLIZE=glibtoolize\n      echo \"Found glibtoolize in $dir\"\n      break\n    fi\n  done\n  IFS=\"$save_ifs\"\n  if test \"x$LIBTOOLIZE\" = \"xnot_found\" ; then\n    die \"Found no libtoolize version, quitting here\"\n  fi\n  return\n}\n\n#\n# If ccache (a compiler cache which reduces build time)\n# (http://samba.org/ccache) is installed, use it.\n# We use 'grep' and hope that 'grep' works as expected\n# (returns 0 if finds lines)\n# We do not use ccache when gcov is used. Also only when\n# gcc is used.\n#\nset_ccache_usage()\n{\n  if test \"x$compiler\" = \"xgcc\" ; then\n    if ccache -V > /dev/null 2>&1 && test \"$USING_GCOV\" != \"1\"\n    then\n      echo \"$CC\" | grep \"ccache\" > /dev/null || CC=\"ccache $CC\"\n      echo \"$CXX\" | grep \"ccache\" > /dev/null || CXX=\"ccache $CXX\"\n    fi\n  fi\n}\n\n#\n# Set flags for various build configurations.\n# Used in -valgrind builds\n#\nset_valgrind_flags()\n{\n  if test \"x$valgrind_flag\" = \"xyes\" ; then\n    loc_valgrind_flags=\"-UFORCE_INIT_OF_VARS -DHAVE_purify \"\n    loc_valgrind_flags=\"$loc_valgrind_flags -DMYSQL_SERVER_SUFFIX=-valgrind-max\"\n    compiler_flags=\"$compiler_flags $loc_valgrind_flags\"\n    with_flags=\"$with_flags --with-valgrind\"\n  fi\n}\n\n#\n# Set up warnings; default is to use no warnings, but if warning_mode\n# is used a lot of warning flags are set up. These flags are valid only\n# for gcc, so for other compilers we ignore the warning_mode.\n#\nset_warning_flags()\n{\n  if test \"x$developer_flag\" = \"xyes\" && test \"x$warning_mode\" = \"x\" ; then\n    warning_mode=\"normal\"\n  fi\n  if test \"x$compiler\" = \"xgcc\" ; then\n    if test \"x$warning_mode\" = \"normal\" || test \"x$warning_mode\" = \"extra\" ; then\n# Both C and C++ warnings\n      warnings=\"$warnings -Wimplicit -Wreturn-type -Wswitch -Wtrigraphs\"\n      warnings=\"$warnings -Wcomment -W\"\n      warnings=\"$warnings -Wchar-subscripts -Wformat -Wparentheses -Wsign-compare\"\n      warnings=\"$warnings -Wwrite-strings -Wunused-function -Wunused-label\"\n      warnings=\"$warnings -Wunused-value -Wunused-variable\"\n\n      if test \"x$warning_mode\" = \"extra\" ; then\n        warnings=\"$warnings -Wshadow\"\n      fi\n# C warnings\n      c_warnings=\"$warnings -Wunused-parameter\"\n# C++ warnings\n      cxx_warnings=\"$warnings -Woverloaded-virtual -Wsign-promo -Wreorder\"\n      cxx_warnings=\"$warnings -Wctor-dtor-privacy -Wnon-virtual-dtor\"\n      compiler_flags=\"$compiler_flags -Wuninitialized\"\n    elif test \"x$warning_mode\" = \"xpedantic\" ; then\n      warnings=\"-W -Wall -ansi -pedantic -Wno-long-long -D_POSIX_SOURCE\"\n      c_warnings=\"$warnings\"\n      cxx_warnings=\"$warnings -std=c++98\"\n# Reset CPU flags (-mtune), they don't work in -pedantic mode\n     check_cpu_cflags=\"\"\n    fi\n  fi\n}\n\n#\n# Used in -debug builds\n#\nset_with_debug_flags()\n{\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    if test \"x$developer_flag\" = \"xyes\" ; then\n      loc_debug_flags=\"-DEXTRA_DEBUG -DFORCE_INIT_OF_VARS \"\n      compiler_flags=\"$compiler_flags $loc_debug_flags\"\n    fi\n    compiler_flags=\"$compiler_flags $extra_debug_flags\"\n  fi\n}\n\n#\n# Flag for optimizing builds for developers.\n#\nset_no_omit_frame_pointer_for_developers()\n{\n  if test \"x$fast_flag\" != \"xno\" ; then\n    if test \"x$developer_flag\" = \"xyes\" && test \"x$compiler\" = \"xgcc\" ; then\n# Be as fast as we can be without losing our ability to backtrace.\n      compiler_flags=\"$compiler_flags -fno-omit-frame-pointer\"\n    fi\n  fi\n}\n\n#\n# Add -g to all builds that requested debug information in build\n#\nset_debug_flag()\n{\n  if test \"x$compile_debug_flag\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -g\"\n  fi\n}\n\n#\n# We compile in SSL support if we can, this isn't possible if CXX\n# and CC aren't the same and we're not using GCC.\n# \nset_ssl()\n{\n  if test \"x$compiler\" = \"xgcc\" && \\\n     test \"x$CC\" = \"x$CXX\" ; then\n    base_configs=\"$base_configs --with-ssl\"\n  fi\n}\n\n#\n# Base options used by all packages\n#\n# SSL library to use. --with-ssl selects the bundled yaSSL\n# implementation of SSL. To use openSSL, you must point out the location\n# of the openSSL headers and libs on your system.\n# For example: --with-ssl=/usr\n#\nset_base_configs()\n{\n  base_configs=\"$base_configs --prefix=$prefix\"\n  base_configs=\"$base_configs --libexecdir=$prefix/bin\"\n  base_configs=\"$base_configs --with-zlib-dir=bundled\"\n  if test \"x$datadir\" = \"x\" ; then\n    base_configs=\"$base_configs --localstatedir=$prefix/data\"\n  else\n    base_configs=\"$base_configs --localstatedir=$datadir\"\n  fi\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-debug\"\n  fi\n  base_configs=\"$base_configs --enable-local-infile\"\n  base_configs=\"$base_configs --enable-thread-safe-client\"\n  base_configs=\"$base_configs --with-big-tables\"\n  base_configs=\"$base_configs --with-extra-charsets=all\"\n  if test \"x$with_fast_mutexes\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-fast-mutexes\"\n  fi\n  base_configs=\"$base_configs --with-pic\"\n  base_configs=\"$base_configs --with-csv-storage-engine\"\n  if test \"x$with_perfschema\" != \"xno\" ; then\n    base_configs=\"$base_configs --with-perfschema\"\n  fi\n}\n\n#\n# Add all standard engines and partitioning (included as part of MySQL\n# Cluster storage engine as well) as part of MySQL Server. These are \n# added in all packages except the classic package.\n#\nset_base_engines()\n{\n  engine_configs=\"--with-archive-storage-engine\"\n  engine_configs=\"$engine_configs --with-blackhole-storage-engine\"\n  engine_configs=\"$engine_configs --without-example-storage-engine\"\n  engine_configs=\"$engine_configs --with-federated-storage-engine\"\n  engine_configs=\"$engine_configs --with-partition\"\n  base_configs=\"$base_configs $engine_configs\"\n}\n\nset_innodb_engine()\n{\n  base_configs=\"$base_configs --with-innodb\"\n}\n\nset_ndb_engine()\n{\n  base_configs=\"$base_configs --with-ndbcluster\"\n  base_configs=\"$base_configs --without-ndb-debug\"\n}\n\nset_pro_package()\n{\n  if test \"x$without_comment\" != \"xyes\" ; then\n    base_configs=\"$base_configs --with-comment=\\\"MySQL Enterprise Pro $version_text built from source\\\"\"\n  fi\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-server-suffix=\\\"-debug\\\"\"\n  fi\n}\n\nset_cge_extended_package()\n{\n  if test \"x$without_comment\" != \"xyes\" ; then\n    base_configs=\"$base_configs --with-comment=\\\"MySQL Cluster Carrier Grade Extended Edition $version_text built from source\\\"\"\n  fi\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-server-suffix=\\\"-cge-extended-debug\\\"\"\n  else\n    base_configs=\"$base_configs --with-server-suffix=\\\"-cge-extended\\\"\"\n  fi\n}\n\nset_cge_package()\n{\n  if test \"x$without_comment\" != \"xyes\" ; then\n    base_configs=\"$base_configs --with-comment=\\\"MySQL Cluster Carrier Grade Edition $version_text built from source\\\"\"\n  fi\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-server-suffix=\\\"-cge-debug\\\"\"\n  else\n    base_configs=\"$base_configs --with-server-suffix=\\\"-cge\\\"\"\n  fi\n}\n\nset_classic_package()\n{\n  if test \"x$without_comment\" != \"xyes\" ; then\n    base_configs=\"$base_configs --with-comment=\\\"MySQL Classic $version_text built from source\\\"\"\n  fi\n  if test \"x$with_debug_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-server-suffix=\\\"-debug\\\"\"\n  fi\n  base_configs=\"$base_configs --without-example-storage-engine\"\n}\n\n#\n# Special handling of readline; use readline from the MySQL\n# distribution if building a GPL version, otherwise use libedit.\n#\nset_readline_package()\n{\n   if test -d \"$path/../cmd-line-utils/libedit\" ; then\n    base_configs=\"$base_configs --with-libedit\"\n  fi\n}\n\n#\n# If fast flag set by user we also add architecture as discovered to \n# compiler flags to make binary optimised for architecture at hand. \n# We use this feature on gcc compilers.\n#\nset_gcc_special_options()\n{\n  if test \"x$fast_flag\" = \"xyes\" && test \"x$compiler\" = \"xgcc\" ; then\n    compiler_flags=\"$compiler_flags $check_cpu_cflags\"\n  fi\n}\n\n#\n# If we discover a Core 2 Duo architecture and we have enabled the fast\n# flag, we enable a compile especially optimised for Core 2 Duo. This\n# feature is currently available on Intel's icc compiler only.\n#\nset_icc_special_options()\n{\n  if test \"x$fast_flag\" = \"xyes\" && test \"x$cpu_arg\" = \"xcore2\" && \\\n     test \"x$compiler\" = \"xicc\" ; then\n    compiler_flags=\"$compiler_flags -xT\"\n  fi\n}\n\nset_cc_and_cxx_for_gcc()\n{\n  if test \"x$CC\" = \"x\" ; then\n    CC=\"gcc -static-libgcc\"\n  fi\n  if test \"x$CXX\" = \"x\" ; then\n    CXX=\"g++ -static-libgcc\"\n  fi\n}\n\nset_cc_and_cxx_for_icc()\n{\n  if test \"x$CC\" = \"x\" ; then\n    CC=\"icc -static-intel -static-libgcc\"\n  fi\n  if test \"x$CXX\" = \"x\" ; then\n    CXX=\"icpc -static-intel -static-libgcc\"\n  fi\n}\n\nset_cc_and_cxx_for_open64()\n{\n  if test \"x$CC\" = \"x\" ; then\n    CC=\"opencc -static-libgcc\"\n  fi\n  if test \"x$CXX\" = \"x\" ; then\n    CXX=\"openCC -static-libgcc\"\n  fi\n}\n\nset_cc_and_cxx_for_forte()\n{\n  if test \"x$CC\" = \"x\" ; then\n    CC=\"cc\"\n  fi\n  if test \"x$CXX\" = \"x\" ; then\n    CXX=\"CC\"\n  fi\n}\n\n#\n# FreeBSD Section\n#\nset_bsd_configs()\n{\n  if test \"x$cpu_base_type\" != \"xx86\" ; then\n    usage \"Only x86 CPUs supported for FreeBSD\"\n    exit 1\n  fi\n  if test \"x$compiler\" != \"xgcc\" ; then\n    usage \"Only gcc supported for FreeBSD\"\n    exit 1\n  fi\n  base_configs=\"$base_configs --enable-assembler\"\n  if test \"x$fast_flag\" != \"xno\" ; then\n    compiler_flags=\"$compiler_flags -O3\"\n  else\n    compiler_flags=\"$compiler_flags -O0\"\n  fi\n  set_cc_and_cxx_for_gcc\n}\n\ncheck_64_bits()\n{\n  echo \"Checking for 32/64-bits compilation\"\n  echo \"int main() { return 0; }\" > temp_test.c\n  if test \"x$m64\" = \"xyes\" ; then\n    cmd=\"$CC $compile_flags -m64 temp_test.c\"\n    if ! $cmd 2>1 ; then\n      m64=\"no\"\n      echo \"Changing to 32-bits since 64-bits didn't work\"\n    else\n      echo \"Will use 64-bits\"\n    fi\n  else\n    cmd=\"$CC $compile_flags -m32 temp_test.c\"\n    if ! $cmd 2>1 ; then\n      m64=\"yes\"\n      echo \"Changing to 64-bits since 32-bits didn't work\"\n    else\n      echo \"Will use 32-bits\"\n    fi\n  fi\n  rm temp_test.c\n}\n\n#\n# Get GCC version\n#\nget_gcc_version()\n{\n  # check if compiler is gcc and dump its version\n  cc_verno=`$cc -dumpversion 2>/dev/null`\n  if test \"x$?\" = \"x0\" ; then\n    set -- `echo $cc_verno | tr '.' ' '`\n    cc_ver=\"GCC\"\n    cc_major=$1\n    cc_minor=$2\n    cc_patch=$3\n    gcc_version=`expr $cc_major '*' 100 '+' $cc_minor`\n  fi\n}\n\n#\n# Link time optimizer (interprocedural optimizations) for Open64\n#\ncheck_for_open64_link_time_optimizer()\n{\n  if test \"x$with_link_time_optimizer\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -ipa\"\n    LDFLAGS=\"$LDFLAGS -ipa\"\n  fi\n}\n\n#\n# Link time optimizer (interprocedural optimizations) for icc\n#\ncheck_for_icc_link_time_optimizer()\n{\n  if test \"x$with_link_time_optimizer\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -ipo\"\n    LDFLAGS=\"$LDFLAGS -ipo\"\n  fi\n}\n\n#\n# Link time optimizer (interprocedural optimizations) for forte\n#\ncheck_for_forte_link_time_optimizer()\n{\n  if test \"x$with_link_time_optimizer\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -ipo\"\n    LDFLAGS=\"$LDFLAGS -ipo\"\n  fi\n}\n\n#\n# Link Time Optimizer in GCC (LTO) uses a parameter -flto\n# which was added to GCC 4.5, if --with-link-time-optimizer\n# is set then use this feature\n#\ncheck_for_gcc_link_time_optimizer()\n{\n  get_gcc_version\n  if test \"$gcc_version\" -ge 405 && \\\n     test \"x$with_link_time_optimizer\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -flto\"\n    LDFLAGS=\"$LDFLAGS -flto\"\n  fi\n}\n\nset_feedback_for_gcc()\n{\n  if test \"x$GENERATE_FEEDBACK_PATH\" != \"x\" ; then\n    compiler_flags=\"$compiler_flags -fprofile-generate\"\n    compiler_flags=\"$compiler_flags -fprofile-dir=$GENERATE_FEEDBACK_PATH\"\n  elif test \"x$USE_FEEDBACK_PATH\" != \"x\" ; then\n    compiler_flags=\"$compiler_flags -fprofile-use\"\n    compiler_flags=\"$compiler_flags -fprofile-correction\"\n    compiler_flags=\"$compiler_flags -fprofile-dir=$USE_FEEDBACK_PATH\"\n  fi\n}\n\nset_feedback_for_open64()\n{\n  if test \"x$GENERATE_FEEDBACK_PATH\" != \"x\" ; then\n    compiler_flags=\"$compiler_flags --fb-create=$GENERATE_FEEDBACK_PATH/feedback\"\n  elif test \"x$USE_FEEDBACK_PATH\" != \"x\" ; then\n    compiler_flags=\"$compiler_flags --fb-opt=$USE_FEEDBACK_PATH/feedback\"\n  fi\n}\n\n#\n# Linux Section\n#\nset_linux_configs()\n{\n# Default to use --with-fast-mutexes on Linux\n  if test \"x$with_fast_mutexes\" = \"x\" ; then\n    base_configs=\"$base_configs --with-fast-mutexes\"\n  fi\n  if test \"x$cpu_base_type\" != \"xx86\" && \\\n     test \"x$cpu_base_type\" != \"xitanium\" ; then\n    usage \"Only x86 and Itanium CPUs supported for Linux\"\n    exit 1\n  fi\n  if test \"x$use_tcmalloc\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-mysqld-libs=-ltcmalloc_minimal\"\n  fi\n  if test \"x$cpu_base_type\" = \"xx86\" ; then\n    base_configs=\"$base_configs --enable-assembler\"\n  fi\n  if test \"x$compiler\" = \"xgcc\" ; then\n    set_cc_and_cxx_for_gcc\n    if test \"x$fast_flag\" != \"xno\" ; then\n      if test \"x$fast_flag\" = \"xyes\" ; then\n        compiler_flags=\"$compiler_flags -O3\"\n        check_for_gcc_link_time_optimizer\n      else\n        compiler_flags=\"$compiler_flags -O3\"\n      fi\n    else\n      compiler_flags=\"$compiler_flags -O0\"\n    fi\n    set_feedback_for_gcc\n# configure will set proper compiler flags for gcc on Linux\n  elif test \"x$compiler\" = \"xicc\" ; then\n    compiler_flags=\"$compiler_flags -mp -restrict\"\n    set_cc_and_cxx_for_icc\n    if test \"x$cpu_base_type\" = \"xitanium\" ; then\n      compiler_flags=\"$compiler_flags -no-ftz\"\n    fi\n    if test \"x$fast_flag\" != \"xno\" ; then\n      compiler_flags=\"$compiler_flags -O3 -unroll2 -ip\"\n      if test \"x$fast_flag\" = \"xyes\" ; then\n        check_for_icc_link_time_optimizer\n      fi\n    fi\n  elif test \"x$compiler\" = \"xopen64\" ; then\n    set_cc_and_cxx_for_open64\n    if test \"x$fast_flag\" != \"xno\" ; then\n      if test \"x$fast_flag\" = \"xyes\" ; then\n        compiler_flags=\"$compiler_flags -O3\"\n#       Generate code specific for the machine you run on\n        compiler_flags=\"$compiler_flags -march=auto\"\n        check_for_open64_link_time_optimizer\n        if test \"x$with_mso\" = \"xyes\" ; then\n          compiler_flags=\"$compiler_flags -mso\"\n        fi\n      else\n        compiler_flags=\"$compiler_flags -O3\"\n      fi\n    fi\n    set_feedback_for_open64\n  else\n    usage \"Only gcc,icc and Open64 compilers supported for Linux\"\n    exit 1\n  fi\n  check_64_bits\n  if test \"x$m64\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -m64\"\n  else\n    compiler_flags=\"$compiler_flags -m32\"\n  fi\n}\n\n#\n# Solaris Section\n#\nset_solaris_configs()\n{\n# Use mtmalloc as malloc, see Tim Cook blog\n# For information on optimal compiler settings, see article at\n# http://developers.sun.com/solaris/articles/mysql_perf_tune.html\n# by Luojia Chen at Sun.\n  base_configs=\"$base_configs --with-named-curses=-lcurses\"\n  case \"`uname -a`\" in\n    *5.8* | *5.9* )\n      ;;\n\n    *5.10* | *5.11*)\n      base_configs=\"$base_configs --with-mysqld-libs=-lmtmalloc\"\n      ;;\n    *)\n      usage \"Only versions 8,9, 10 and 11 supported for Solaris\"\n      exit 1\n  esac\n  if test \"x$cpu_base_type\" != \"xx86\" && \\\n     test \"x$cpu_base_type\" != \"xsparc\" ; then\n    usage \"Only x86 and Sparc CPUs supported for Solaris\"\n    exit 1\n  fi\n  if test \"x$compiler\" != \"xgcc\" && \\\n     test \"x$compiler\" != \"xforte\" ; then\n    usage \"Only gcc and Forte compilers supported for Solaris\"\n    exit 1\n  fi\n  if test \"x$m64\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -m64\"\n    LDFLAGS=\"-m64\"\n    ASFLAGS=\"$ASFLAGS -m64\"\n  else\n    compiler_flags=\"$compiler_flags -m32\"\n    LDFLAGS=\"-m32\"\n    ASFLAGS=\"$ASFLAGS -m32\"\n  fi\n  if test \"x$compiler\" = \"xgcc\" ; then\n    set_cc_and_cxx_for_gcc\n    if test \"x$cpu_base_type\" != \"xx86\" ; then\n      usage \"gcc currently not supported for Solaris on SPARC\"\n      exit 1\n    fi\n    if test \"x$fast_flag\" = \"xyes\" ; then\n      LDFLAGS=\"$LDFLAGS -O3\"\n      compiler_flags=\"$compiler_flags -O3\"\n      check_for_gcc_link_time_optimizer\n    else\n      if test \"x$fast_flag\" = \"xgeneric\" ; then\n        LDFLAGS=\"$LDFLAGS -O2\"\n        compiler_flags=\"$compiler_flags -O2\"\n      else\n        LDFLAGS=\"$LDFLAGS -O0\"\n        compiler_flags=\"$compiler_flags -O0\"\n      fi\n    fi\n  else\n#Using Forte compiler (SunStudio)\n    set_cc_and_cxx_for_forte\n    compiler_flags=\"$compiler_flags -mt\"\n    LDFLAGS=\"$LDFLAGS -mt\"\n    compiler_flags=\"$compiler_flags -fsimple=1\"\n    compiler_flags=\"$compiler_flags -ftrap=%none\"\n    compiler_flags=\"$compiler_flags -xbuiltin=%all\"\n    compiler_flags=\"$compiler_flags -xlibmil\"\n    compiler_flags=\"$compiler_flags -xlibmopt\"\n    if test \"x$fast_flag\" = \"xyes\" ; then\n      compiler_flags=\"$compiler_flags -xtarget=native\"\n      compiler_flags=\"$compiler_flags -xunroll=3\"\n      check_for_forte_link_time_optimizer\n    else\n      compiler_flags=\"$compiler_flags -xtarget=generic\"\n    fi\n    if test \"x$cpu_base_type\" = \"xx86\" ; then\n      compiler_flags=\"$compiler_flags -nofstore\"\n      if test \"x$fast_flag\" = \"xyes\" ; then\n        compiler_flags=\"$compiler_flags -xregs=frameptr\"\n        compiler_flags=\"$compiler_flags -xO4\"\n      else\n        compiler_flags=\"$compiler_flags -xregs=no%frameptr\"\n        if test \"x$fast_flag\" = \"xgeneric\" ; then\n          compiler_flags=\"$compiler_flags -xO2\"\n        else\n          compiler_flags=\"$compiler_flags -xO0\"\n        fi\n      fi\n    else\n#Using SPARC cpu with SunStudio (Forte) compiler\n      ASFLAGS=\"$ASFLAGS -xarch=sparc\"\n      LDFLAGS=\"$LDFLAGS -xarch=sparc\"\n      base_cflags=\"$base_cflags -xstrconst\"\n      compiler_flags=\"$compiler_flags -xarch=sparc\"\n      if test \"x$fast_flag\" = \"xyes\" ; then\n        compiler_flags=\"$compiler_flags -xbinopt=prepare\"\n        LDFLAGS=\"$LDFLAGS -xbinopt=prepare\"\n        compiler_flags=\"$compiler_flags -xO4\"\n      elif test \"x$fast_flag\" = \"xgeneric\" ; then\n        compiler_flags=\"$compiler_flags -xO3\"\n      else\n        compiler_flags=\"$compiler_flags -xO0\"\n      fi\n    fi\n  fi\n}\n\n#\n# Mac OS X Section\n#\nset_macosx_configs()\n{\n  if test \"x$cpu_base_type\" != \"xx86\" || test \"x$compiler\" != \"xgcc\" ; then\n    usage \"Only gcc/x86 supported for Mac OS X\"\n    exit 1\n  fi\n#\n# Optimize for space as long as it doesn't affect performance, use some\n# optimisations also when not in fast mode.\n#\n  base_cxxflags=\"$base_cxxflags -felide-constructors\"\n  compiler_flags=\"$compiler_flags -fno-common\"\n  if test \"x$m64\" = \"xyes\" ; then\n    compiler_flags=\"$compiler_flags -m64\"\n    compiler_flags=\"$compiler_flags -arch x86_64\"\n  else\n    compiler_flags=\"$compiler_flags -m32\"\n    compiler_flags=\"$compiler_flags -arch i386\"\n  fi\n  if test \"x$fast_flag\" != \"xno\" ; then\n    compiler_flags=\"$compiler_flags -Os\"\n  else\n    compiler_flags=\"$compiler_flags -O0\"\n  fi\n  set_cc_and_cxx_for_gcc\n}\n\n#\n# Use static linking for own modules and dynamic linking for system\n# modules unless specifically requested to do everything statically.\n# Should normally not be used; static_linking_flag kept in case someone \n# really needs it. Available only if developer flag is also set.\n#\nset_static_link_configs()\n{\n  if test \"x$static_linking_flag\" = \"xyes\" && test \"x$developer_flag\" = \"xyes\" ; then\n    loc_static_link=\"--with-mysqld-ldflags=\\\"-all-static\\\"\"\n    loc_static_link=\"$loc_static_link --with-client-ldflags=\\\"-all-static\\\"\"\n  else\n    loc_static_link=\"--with-mysqld-ldflags=\\\"-static\\\"\"\n    loc_static_link=\"$loc_static_link --with-client-ldflags=\\\"-static\\\"\"\n  fi\n  base_configs=\"$base_configs $loc_static_link\"\n}\n\n#\n# Enable error injection in MySQL Server (for developer build only -\n# extra check for developer flag required).\n#\nset_error_inject_configs()\n{\n  if test \"x$error_inject_flag\" = \"xyes\" && test \"x$developer_flag\" = \"xyes\" ; then\n    base_configs=\"$base_configs --with-error-inject\"\n    if test \"x$package\" = \"xndb\" || test \"x$package\" = \"xextended\" ; then\n      base_configs=\"$base_configs --with-ndb-ccflags='-DERROR_INSERT'\"\n    fi\n  fi\n}\n\nset_default_package()\n{\n  if test \"x$package\" = \"x\" ; then\n    if test \"x$developer_flag\" = \"xyes\" ; then\n      package=\"extended\"\n    else\n      package=\"cge\"\n    fi\n  fi\n}\n\nset_defaults_based_on_environment()\n{\n  if test ! -z \"$MYSQL_DEVELOPER\" ; then\n    developer_flag=\"yes\"\n  fi\n  if test ! -z \"$MYSQL_DEVELOPER_DEBUG\" ; then\n    with_debug_flag=\"yes\"\n    fast_flag=\"no\"\n  fi\n  if test ! -z \"$MYSQL_DEVELOPER_PACKAGE\" ; then\n    package=\"$MYSQL_DEVELOPER_PACKAGE\"\n    parse_package\n  fi\n}\n\n########################################################################\n\nif test ! -f sql/mysqld.cc ; then\n  die \"You must run this script from the MySQL top-level directory\"\nfi\n\ncpu_type=\npackage=\nprefix=\"/usr/local/mysql\"\nparallelism=\"8\"\nfast_flag=\"generic\"\ncompiler=\"gcc\"\ngpl=\"yes\"\nversion_text=\ndeveloper_flag=\"no\"\njust_configure=\nwarning_mode=\nwith_flags=\nerror_inject_flag=\nwith_debug_flag=\ncompile_debug_flag=\nstrip_flag=\nvalgrind_flag=\nstatic_linking_flag=\ncompiler_flags=\nos=\ncpu_base_type=\nwarnings=\nc_warnings=\ncflags=\nbase_cflags=\ncxx_warnings=\nbase_cxxflags=\nbase_configs=\ndebug_flags=\ncxxflags=\nextra_debug_flags=\nm64=\nexplicit_size_set=\ndatadir=\ncommands=\nengine_configs=\nASFLAGS=\nLDFLAGS=\nuse_tcmalloc=\nwithout_comment=\"yes\"\nwith_fast_mutexes=\nwith_perfschema=\"yes\"\nwith_link_time_optimizer=\nwith_mso=\ngcc_version=\"0\"\ngenerate_feedback_path=\nuse_feedback_path=\n\nset_defaults_based_on_environment\n\nparse_options \"$@\"\n\nset_default_package\n\nset -e\n\n#\n# Check for the CPU and set up CPU specific flags. We may reset them\n# later.\n# This call sets the cpu_arg and check_cpu_args parameters\n#\npath=`dirname $0`\nif test \"x$compiler\" = \"xgcc\" ; then\n  compiler=\nfi\n. \"$path/check-cpu\"\nif test \"x$compiler\" = \"x\" ; then\n  compiler=\"gcc\"\nfi\ncheck_os\nset_cpu_base\nif test \"x$?\" = \"x1\" ; then\n  exit 1\nfi\n\n#\n# Set up c_warnings and cxx_warnings; add to compiler_flags.\n# Possibly reset check_cpu_flags.\n#\nset_warning_flags\n\n#\n# Add to compiler_flags.\n#\nset_valgrind_flags\nset_with_debug_flags\nset_no_omit_frame_pointer_for_developers\nset_debug_flag\nset_gcc_special_options\nset_icc_special_options\n\n#\n# Definitions of various packages possible to compile. The default is to\n# build a source variant of MySQL Cluster Carrier Grade Edition \n# including all storage engines except InnoDB, and to use GPL libraries.\n#\nset_base_configs\nif test \"x$gpl\" = \"xyes\" ; then\n  version_text=\"GPL version\"\nelse\n  version_text=\"Commercial version\"\nfi\nif test \"x$package\" = \"xpro\" ; then\n  set_base_engines\n  set_innodb_engine\n  set_pro_package\nelif test \"x$package\" = \"xextended\" ; then\n  set_base_engines\n  set_ndb_engine\n  set_innodb_engine\n  set_cge_extended_package\nelif test \"x$package\" = \"xcge\" ; then\n  set_base_engines\n  set_ndb_engine\n  set_cge_package\nelif test \"x$package\" = \"xclassic\" ; then\n  set_classic_package\nelse\n  die \"No supported package was used, internal error\"\nfi\nset_readline_package\nset_static_link_configs\nset_error_inject_configs\n\n#\n# This section handles flags for specific combinations of compilers,\n# operating systems, and processors.\n#\n\nif test \"x$os\" = \"xlinux\" ; then\n  set_linux_configs\nelif test \"x$os\" = \"xSolaris\" ; then\n  set_solaris_configs\nelif test \"x$os\" = \"xMacOSX\" ; then\n  set_macosx_configs\nelif test \"x$os\" = \"xbsd\" ; then\n  set_bsd_configs\nelse\n  die \"Operating system not supported by this script\"\nfi\nset_ssl\n#\n# Final step before setting up commands is to set up proper make and\n# proper libtoolize versions, and to determine whether to use ccache.\n#\nset_make_version\nset_ccache_usage\n\n#\n# Set up commands variable from variables prepared for base \n# configurations, compiler flags, and warnings flags.\n# \ninit_configure_commands\n\nif test \"x$just_configure\" != \"xyes\" ; then\n  add_make_commands\nfi\n\n#\n# The commands variable now contains the entire command to be run for\n# the build; we either execute it, or merely print it out.\n#\necho \"Running command:\"\necho \"$commands\"\nif test \"x$just_print\" != \"xyes\" ; then\n  eval \"set -x; $commands\"\nfi\n", "num_lines": 1981}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# Ensure cmake and perl are there\ncmake -P cmake/check_minimal_version.cmake >/dev/null 2>&1 || HAVE_CMAKE=no\nperl --version >/dev/null 2>&1 || HAVE_PERL=no\nscriptdir=`dirname $0`\nif test \"$HAVE_CMAKE\" = \"no\"\nthen\n  echo \"CMake is required to build MySQL.\"\n  exit 1\nelif test \"$HAVE_PERL\" = \"no\"\nthen\n  echo \"Perl is required to build MySQL using the configure to CMake translator.\"\n  exit 1\nelse\n  perl $scriptdir/cmake/configure.pl \"$@\"\nfi\n\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n########################################################################\n\nget_key_value()\n{\n  echo \"$1\" | sed 's/^--[a-zA-Z_-]*=//'\n}\n\nusage()\n{\ncat <<EOF \nUsage: $0 [-h|-n] [configure-options]\n  -h, --help              Show this help message.\n  -n, --just-print        Don't actually run any commands; just print them.\n  -c, --just-configure    Stop after running configure.\n  --with-debug=full       Build with full debug(no optimizations, keep call stack).\n  --warning-mode=[old|pedantic|maintainer]\n                          Influences the debug flags. Old is default.\n  --prefix=path           Build with prefix 'path'.\n\nNote: this script is intended for internal use by MySQL developers.\nEOF\n}\n\nparse_options()\n{\n  while test $# -gt 0\n  do\n    case \"$1\" in\n    --prefix=*)\n      prefix=`get_key_value \"$1\"`;;\n    --with-debug=full)\n      full_debug=\"=full\";;\n    --warning-mode=*)\n      warning_mode=`get_key_value \"$1\"`;;\n    -c | --just-configure)\n      just_configure=1;;\n    -n | --just-print | --print)\n      just_print=1;;\n    -h | --help)\n      usage\n      exit 0;;\n    *)\n      echo \"Unknown option '$1'\"\n      exit 1;;\n    esac\n    shift\n  done\n}\n\n########################################################################\n\nif test ! -f sql/mysqld.cc\nthen\n  echo \"You must run this script from the MySQL top-level directory\"\n  exit 1\nfi\n\nprefix=\"/usr/local/mysql\"\njust_print=\njust_configure=\nwarning_mode=\nmaintainer_mode=\nfull_debug=\n\nparse_options \"$@\"\n\nif test -n \"$MYSQL_BUILD_PREFIX\"\nthen\n  prefix=\"$MYSQL_BUILD_PREFIX\"\nfi\n\nset -e\n\n#\n# Check for the CPU and set up CPU specific flags. We may reset them\n# later.\n# \npath=`dirname $0`\n. \"$path/check-cpu\"\n\nexport AM_MAKEFLAGS\nAM_MAKEFLAGS=\"-j 6\"\n\n# SSL library to use.--with-ssl will select our bundled yaSSL\n# implementation of SSL. To use openSSl you will nee too point out\n# the location of openSSL headers and lbs on your system.\n# Ex --with-ssl=/usr\nSSL_LIBRARY=--with-ssl\n\nif [ \"x$warning_mode\" = \"xpedantic\" ]; then\n  warnings=\"-W -Wall -ansi -pedantic -Wno-long-long -Wno-unused -D_POSIX_SOURCE\"\n  c_warnings=\"$warnings\"\n  cxx_warnings=\"$warnings -std=c++98\"\n# NOTE: warning mode should not influence optimize/debug mode.\n# Please feel free to add a separate option if you don't feel it's an overkill.\n  debug_extra_cflags=\"-O0\"\n# Reset CPU flags (-mtune), they don't work in -pedantic mode\n  check_cpu_cflags=\"\"\nelif [ \"x$warning_mode\" = \"xmaintainer\" ]; then\n  c_warnings=\"-Wall -Wextra\"\n  cxx_warnings=\"$c_warnings -Wno-unused-parameter\"\n  maintainer_mode=\"--enable-mysql-maintainer-mode\"\n  debug_extra_cflags=\"-g3\"\nelse\n# Both C and C++ warnings\n  warnings=\"-Wall -Wextra -Wunused -Wwrite-strings\"\n\n# For more warnings, uncomment the following line\n# warnings=\"$warnings -Wshadow\"\n\n# C warnings\n  c_warnings=\"$warnings\"\n# C++ warnings\n  cxx_warnings=\"$warnings -Wno-unused-parameter\"\n# cxx_warnings=\"$cxx_warnings -Woverloaded-virtual -Wsign-promo\"\n  cxx_warnings=\"$cxx_warnings -Wnon-virtual-dtor\"\n  debug_extra_cflags=\"-O0 -g3 -gdwarf-2\"\nfi\n\n# Set flags for various build configurations.\n# Used in -valgrind builds\n# Override -DFORCE_INIT_OF_VARS from debug_cflags. It enables the macro\n# LINT_INIT(), which is only useful for silencing spurious warnings\n# of static analysis tools. We want LINT_INIT() to be a no-op in Valgrind.\nvalgrind_flags=\"-UFORCE_INIT_OF_VARS -DHAVE_purify \"\nvalgrind_flags=\"$valgrind_flags -DMYSQL_SERVER_SUFFIX=-valgrind-max\"\nvalgrind_configs=\"--with-valgrind\"\n#\n# Used in -debug builds\ndebug_cflags=\"-DEXTRA_DEBUG -DFORCE_INIT_OF_VARS \"\ndebug_cflags=\"$debug_cflags -DSAFE_MUTEX\"\nerror_inject=\"--with-error-inject \"\n#\n# Base C++ flags for all builds\nbase_cxxflags=\"-felide-constructors\"\n#\n# Flags for optimizing builds.\n# Be as fast as we can be without losing our ability to backtrace.\nfast_cflags=\"-O3 -fno-omit-frame-pointer\"\n\ndebug_configs=\"--with-debug\"\nif [ -z \"$full_debug\" ]\nthen\n  debug_cflags=\"$debug_cflags $debug_extra_cflags\"\nfi\n\n\n#\n# Configuration options.\n#\nbase_configs=\"--prefix=$prefix --enable-assembler \"\nbase_configs=\"$base_configs --with-extra-charsets=complex \"\nbase_configs=\"$base_configs --enable-thread-safe-client \"\nbase_configs=\"$base_configs --with-big-tables $maintainer_mode\"\n\n\nif test -d \"$path/../cmd-line-utils/libedit\"\nthen\n    base_configs=\"$base_configs --with-libedit\"\nfi\n\nstatic_link=\"--with-mysqld-ldflags=-all-static \"\nstatic_link=\"$static_link --with-client-ldflags=-all-static\"\n# we need local-infile in all binaries for rpl000001\n# if you need to disable local-infile in the client, write a build script\n# and unset local_infile_configs\nlocal_infile_configs=\"--enable-local-infile\"\n\n\nmax_no_embedded_configs=\"$SSL_LIBRARY --with-plugins=max\"\nmax_no_ndb_configs=\"$SSL_LIBRARY --with-plugins=max-no-ndb --with-embedded-server\"\nmax_configs=\"$SSL_LIBRARY --with-plugins=max --with-embedded-server\"\n\n#\n# CPU and platform specific compilation flags.\n#\nalpha_cflags=\"$check_cpu_cflags -Wa,-m$cpu_flag\"\namd64_cflags=\"$check_cpu_cflags\"\namd64_cxxflags=\"\"  # If dropping '--with-big-tables', add here  \"-DBIG_TABLES\"\npentium_cflags=\"$check_cpu_cflags\"\npentium64_cflags=\"$check_cpu_cflags -m64\"\nppc_cflags=\"$check_cpu_cflags\"\nsparc_cflags=\"\"\n\nif gmake --version > /dev/null 2>&1\nthen\n  make=gmake\nelse\n  make=make\nfi\n\nif test -z \"$CC\" ; then\n  CC=gcc\nfi\n\nif test -z \"$CXX\" ; then\n  CXX=g++\nfi\n\n# If ccache (a compiler cache which reduces build time)\n# (http://samba.org/ccache) is installed, use it.\n# We use 'grep' and hope 'grep' will work as expected\n# (returns 0 if finds lines)\nif test \"$USING_GCOV\" != \"1\"\nthen\n  # Not using gcov; Safe to use ccache\n  CCACHE_GCOV_VERSION_ENABLED=1\nfi\n\nif ccache -V > /dev/null 2>&1 && test \"$CCACHE_GCOV_VERSION_ENABLED\" = \"1\"\nthen\n  echo \"$CC\" | grep \"ccache\" > /dev/null || CC=\"ccache $CC\"\n  echo \"$CXX\" | grep \"ccache\" > /dev/null || CXX=\"ccache $CXX\"\nfi\n\n# gcov\n\n# The  -fprofile-arcs and -ftest-coverage options cause GCC to instrument the\n# code with profiling information used by gcov.\n# The -DDISABLE_TAO_ASM is needed to avoid build failures in Yassl.\n# The -DHAVE_gcov enables code to write out coverage info even when crashing.\n\ngcov_compile_flags=\"-fprofile-arcs -ftest-coverage\"\ngcov_compile_flags=\"$gcov_compile_flags -DDISABLE_TAO_ASM\"\ngcov_compile_flags=\"$gcov_compile_flags -DMYSQL_SERVER_SUFFIX=-gcov -DHAVE_gcov\"\n\n# GCC4 needs -fprofile-arcs -ftest-coverage on the linker command line (as well\n# as on the compiler command line), and this requires setting LDFLAGS for BDB.\n\ngcov_link_flags=\"-fprofile-arcs -ftest-coverage\"\n\ngcov_configs=\"--with-gcov\"\n\n# gprof\n\ngprof_compile_flags=\"-O2 -pg -g\"\n\ngprof_link_flags=\"--disable-shared $static_link\"\n\n", "num_lines": 259}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# test all yassl cipher suties \n# \n\n\nno_pid=-1\nserver_pid=$no_pid\n\n\ndo_cleanup() {\n    echo \"in cleanup\"\n\n    if [[ $server_pid != $no_pid ]]\n    then\n        echo \"killing server\"\n        kill -9 $server_pid\n    fi\n}\n\ndo_trap() {\n    echo \"got trap\"\n    do_cleanup\n    exit -1\n}\n\ntrap do_trap INT TERM\n\n\n# make sure example server and client are built\nif test ! -s ../examples/server/server; then\n    echo \"Please build yaSSL first, example server missing\"\n    exit -1\nfi\n\nif test ! -s ../examples/client/client; then\n    echo \"Please build yaSSL first, example client missing\"\n    exit -1\nfi\n\n\n# non DSA suites\nfor suite in {\"DHE-RSA-AES256-SHA\",\"AES256-SHA\",\"DHE-RSA-AES128-SHA\",\"AES128-SHA\",\"AES256-RMD\",\"AES128-RMD\",\"DES-CBC3-RMD\",\"DHE-RSA-AES256-RMD\",\"DHE-RSA-AES128-RMD\",\"DHE-RSA-DES-CBC3-RMD\",\"RC4-SHA\",\"RC4-MD5\",\"DES-CBC3-SHA\",\"DES-CBC-SHA\",\"EDH-RSA-DES-CBC3-SHA\",\"EDH-RSA-DES-CBC-SHA\"}\ndo\n  for client_auth in {y,n}\n  do\n    echo \"Trying $suite client auth = $client_auth ...\"\n\n    if test -e server_ready; then\n        echo -e \"removing exisitng server_ready file\"\n        rm server_ready\n    fi\n    ../examples/server/server $client_auth &\n    server_pid=$!\n\n    while [ ! -s server_ready ]; do\n        echo -e \"waiting for server_ready file...\"\n        sleep 0.1\n    done\n\n    ../examples/client/client $suite\n    client_result=$?\n\n    wait $server_pid\n    server_result=$?\n\n    server_pid=$no_pid\n\n    if [[ $client_result != 0 ]]\n    then\n        echo \"Client Error\"\n        exit $client_result\n    fi\n\n    if [[ $server_result != 0 ]]\n    then\n        echo \"Server Error\"\n        exit $server_result\n    fi\n\n  done   # end client auth loop\ndone  # end non dsa suite list\necho -e \"Non DSA Loop SUCCESS\"\n\n\n\n# DSA suites\nfor suite in {\"DHE-DSS-AES256-SHA\",\"DHE-DSS-AES128-SHA\",\"DHE-DSS-AES256-RMD\",\"DHE-DSS-AES128-RMD\",\"DHE-DSS-DES-CBC3-RMD\",\"EDH-DSS-DES-CBC3-SHA\",\"EDH-DSS-DES-CBC-SHA\"}\ndo\n  for client_auth in {y,n}\n  do\n    echo \"Trying $suite client auth = $client_auth ...\"\n\n    if test -e server_ready; then\n        echo -e \"removing exisitng server_ready file\"\n        rm server_ready\n    fi\n    # d signifies DSA\n    ../examples/server/server $client_auth d &\n    server_pid=$!\n\n    while [ ! -s server_ready ]; do\n        echo -e \"waiting for server_ready file...\"\n        sleep 0.1\n    done\n\n    ../examples/client/client $suite\n    client_result=$?\n\n    wait $server_pid\n    server_result=$?\n\n    server_pid=$no_pid\n\n    if [[ $client_result != 0 ]]\n    then\n        echo \"Client Error\"\n        exit $client_result\n    fi\n\n    if [[ $server_result != 0 ]]\n    then\n        echo \"Server Error\"\n        exit $server_result\n    fi\n\n  done   # end client auth loop\ndone  # end dsa suite list\necho -e \"DSA Loop SUCCESS\"\n\nexit 0\n", "num_lines": 132}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nLIBTOOLIZE=libtoolize\nSYSNAME=`uname`\nif [ \"x$SYSNAME\" = \"xDarwin\" ] ; then\n  LIBTOOLIZE=glibtoolize\nfi\naclocal && \\\n\tautoheader && \\\n\t$LIBTOOLIZE && \\\n\tautoconf && \\\n\tautomake --add-missing --copy\n", "num_lines": 12}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nsetup () {\n\t EVENT_NOKQUEUE=yes; export EVENT_NOKQUEUE\n\t EVENT_NODEVPOLL=yes; export EVENT_NODEVPOLL\n\t EVENT_NOPOLL=yes; export EVENT_NOPOLL\n\t EVENT_NOSELECT=yes; export EVENT_NOSELECT\n\t EVENT_NOEPOLL=yes; export EVENT_NOEPOLL\n\t EVENT_NOEVPORT=yes; export EVENT_NOEVPORT\n}\n\ntest () {\n\tif ./test-init 2>/dev/null ;\n\tthen\n\t        true\n\telse\n\t\techo Skipping test\n\t\treturn\n\tfi\t\n\necho -n \" test-eof: \"\nif ./test-eof >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" test-weof: \"\nif ./test-weof >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" test-time: \"\nif ./test-time >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" regress: \"\nif ./regress >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\n}\n\necho \"Running tests:\"\n\n# Need to do this by hand?\nsetup\nunset EVENT_NOKQUEUE\nexport EVENT_NOKQUEUE\necho \"KQUEUE\"\ntest\n\nsetup\nunset EVENT_NODEVPOLL\nexport EVENT_NODEVPOLL\necho \"DEVPOLL\"\ntest\n\nsetup\nunset EVENT_NOPOLL\nexport EVENT_NOPOLL\necho \"POLL\"\ntest\n\nsetup\nunset EVENT_NOSELECT\nexport EVENT_NOSELECT\necho \"SELECT\"\ntest\n\nsetup\nunset EVENT_NOEPOLL\nexport EVENT_NOEPOLL\necho \"EPOLL\"\ntest\n\nsetup\nunset EVENT_NOEVPORT\nexport EVENT_NOEVPORT\necho \"EVPORT\"\ntest\n\n\n\n", "num_lines": 92}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -eu\n\n# A very simple proto-script for generating a new CA, and using it to\n# sign the server and client certificates.\n\nCADIR=/tmp/ca\nrm -rf $CADIR\nmkdir $CADIR\n> $CADIR/index.txt\necho \"01\" > $CADIR/serial\ncp /etc/pki/tls/openssl.cnf $CADIR\nreplace /etc/pki/CA $CADIR -- $CADIR/openssl.cnf\n\n\nopenssl genrsa 2048 > $CADIR/cakey.pem\nopenssl req -new -x509 -nodes -days 3600 -key $CADIR/cakey.pem -out cacert.pem -subj '/C=SE/ST=Uppsala/L=Uppsala/O=MySQL AB'\n\nopenssl req -newkey rsa:2048 -days 3600 -nodes -keyout server-key.pem -out $CADIR/server-req.pem -subj '/C=SE/ST=Uppsala/O=MySQL AB/CN=localhost'\nopenssl ca -batch -config $CADIR/openssl.cnf -days 3650 -policy policy_anything -cert cacert.pem -keyfile $CADIR/cakey.pem -outdir $CADIR -out server-cert.pem -infiles $CADIR/server-req.pem\n\nopenssl req -newkey rsa:2048 -days 3600 -nodes -keyout client-key.pem -out $CADIR/client-req.pem -subj '/C=SE/ST=Uppsala/O=MySQL AB/CN=client'\nopenssl ca -batch -config $CADIR/openssl.cnf -days 3650 -policy policy_anything -cert cacert.pem -keyfile $CADIR/cakey.pem -outdir $CADIR -out client-cert.pem -infiles $CADIR/client-req.pem\n", "num_lines": 23}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\ncat > $MYSQL_TMP_DIR/cf_configs.cnf <<EOL\n\nEOL\n", "num_lines": 6}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nsst_dump=$2\nwait_for_no_more_deletes=$3\nwait_for_no_more_rows=$4\nnum_retries=240\nretry=0\n\necho \"wait_for_delete: $wait_for_no_more_deletes\"\n\nwhile : ; do\n  TOTAL_D=0\n  TOTAL_E=0\n  for f in `ls $1/mysqld.1/data/.rocksdb/*.sst`\n  do\n    # excluding system cf\n    DELETED=`$sst_dump --command=scan --output_hex --file=$f | \\\n      perl -ne 'print  if(/''(\\d\\d\\d\\d\\d\\d\\d\\d)/ && $1 >= 11)' | \\\n      grep -e \", type:0\" -e \", type:7\" | wc -l`\n    EXISTS=`$sst_dump --command=scan --output_hex --file=$f | \\\n      perl -ne 'print  if(/''(\\d\\d\\d\\d\\d\\d\\d\\d)/ && $1 >= 11)' | \\\n      grep \", type:1\" | wc -l`\n    TOTAL_D=$(($TOTAL_D+$DELETED))\n    TOTAL_E=$(($TOTAL_E+$EXISTS))\n    # echo \"${f##*/} $DELETED $EXISTS\"\n  done\n  if [ $TOTAL_E != \"0\" ] || ([ $wait_for_no_more_rows = \"1\" ] && [ $TOTAL_E = \"0\" ])\n  then\n    if [ $TOTAL_D = \"0\" ] || [ $wait_for_no_more_deletes = \"0\" ]\n    then\n      break\n    fi\n  fi\n  if [ $retry -ge $num_retries ]\n  then\n    break\n  fi\n  sleep 1\n  retry=$(($retry + 1))\ndone\n\nif [ \"$TOTAL_E\" = \"0\" ]\nthen\n  echo \"No records in the database\"\n  exit\nfi\n\nif [ \"$TOTAL_D\" = \"0\" ]\nthen\n  echo \"No more deletes left\"\nelse\n  echo \"There are deletes left\"\nfi\n", "num_lines": 54}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\ncat > $MYSQL_TMP_DIR/use_default_sk_cf.cnf <<EOL\n\nEOL\n", "num_lines": 6}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nCOPY_LOG=\"${MYSQL_TMP_DIR}/myrocks_hotbackup_copy_log\"\nSIGNAL_FILE=${MYSQL_TMP_DIR}/myrocks_hotbackup_signal\nMOVEBACK_LOG=\"${MYSQL_TMP_DIR}/myrocks_hotbackup_moveback_log\"\nrm -f $COPY_LOG\nrm -f $SIGNAL_FILE\nrm -f $MOVEBACK_LOG\n", "num_lines": 9}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "src_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.1/data/\"\npython2 -c \"import socket as s; sock = s.socket(s.AF_UNIX); sock.bind('${src_data_dir}/slocket')\"\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nCOPY_LOG=$1\nSIGNAL_FILE=$2\n# Creating a table after myrocks_hotbackup reaches waiting loop\n\ndone=0\nwhile : ; do\n  wait=`tail -1 $COPY_LOG | grep 'Waiting until' | wc -l`\n  if [ \"$wait\" -eq \"1\" ]; then\n    break\n  fi\n  sleep 1\ndone\n$MYSQL --defaults-group-suffix=.1 db1 -e \"create table r10 (id int primary key ) engine=rocksdb\"\ntouch $SIGNAL_FILE\n", "num_lines": 17}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Insert 100 batches of 100 records each to a table with following schema:\n# create table db1.t1 (\n#   `id` int(10) not null auto_increment,\n#   `k` int(10),\n#   `data` varchar(2048),\n#   primary key (`id`),\n#   key (`k`)\n# ) engine=innodb;\n\nMAX_INSERTS=100\nMAX_ROWS_PER_INSERT=100\n\ninsertData() {\n  for ((i=1; i<=$MAX_INSERTS; i++));\n  do\n      stmt='INSERT INTO db1.t1 values'\n      for ((j=1; j<=$MAX_ROWS_PER_INSERT; j++));\n      do\n          k=$RANDOM\n          data=$(head -c 2048 /dev/urandom|tr -cd 'a-zA-Z0-9')\n          stmt=$stmt' (NULL, '$k', \"'$data'\")'\n          if [ $j -lt $MAX_ROWS_PER_INSERT ]; then\n              stmt=$stmt','\n          fi\n      done\n      stmt=$stmt';'\n      $MYSQL --defaults-group-suffix=.1 -e \"$stmt\"\n  done\n}\n\nNUM_PARALLEL_INSERTS=25\npids=()\nfor ((k=1; k<=$NUM_PARALLEL_INSERTS; k++));\ndo\n  insertData &\n  pids+=($!)\ndone\nfor ((k=1; k<=$NUM_PARALLEL_INSERTS; k++));\ndo\n  wait ${pids[k]}\ndone\n", "num_lines": 44}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Initially loads a chunk of data.\n# Then start loading another chunk of data,\n# while simultaneously running a backup\n\nsuite/rocksdb_hotbackup/include/load_data.sh 2>&1\nsuite/rocksdb_hotbackup/include/load_data.sh 2>&1 &\nsuite/rocksdb_hotbackup/include/stream_run.sh 2>&1\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Insert 10 batches of 10 records each to a table with following schema:\n# create table slocket.t1 (\n#   `id` int(10) not null auto_increment,\n#   `k` int(10),\n#   `data` varchar(2048),\n#   primary key (`id`),\n#   key (`k`)\n# ) engine=innodb;\n\nMAX_INSERTS=10\nMAX_ROWS_PER_INSERT=10\n\ninsertData() {\n  for ((i=1; i<=$MAX_INSERTS; i++));\n  do\n      stmt='INSERT INTO slocket.t1 values'\n      for ((j=1; j<=$MAX_ROWS_PER_INSERT; j++));\n      do\n          k=$RANDOM\n          data=$(head -c 2048 /dev/urandom|tr -cd 'a-zA-Z0-9')\n          stmt=$stmt' (NULL, '$k', \"'$data'\")'\n          if [ $j -lt $MAX_ROWS_PER_INSERT ]; then\n              stmt=$stmt','\n          fi\n      done\n      stmt=$stmt';'\n      $MYSQL --defaults-group-suffix=.1 -e \"$stmt\"\n  done\n}\n\nNUM_PARALLEL_INSERTS=25\npids=()\nfor ((k=1; k<=$NUM_PARALLEL_INSERTS; k++));\ndo\n  insertData &\n  pids+=($!)\ndone\nfor ((k=1; k<=$NUM_PARALLEL_INSERTS; k++));\ndo\n  wait ${pids[k]}\ndone\n", "num_lines": 44}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "src_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.1/data/\"\nrm \"${src_data_dir}/slocket\"\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nbinlog_line=($(grep -o \"Last binlog file position [0-9]*, file name .*\\.[0-9]*\" ${MYSQLTEST_VARDIR}/log/mysqld.2.err | tail -1))\nbinlog_pos=${binlog_line[4]%?}\nbinlog_file=${binlog_line[7]}\n\nsql=\"show gtid_executed in '$binlog_file' from $binlog_pos\"\nresult=($($MYSQL --defaults-group-suffix=.1 -e \"$sql\"))\ngtid_executed=${result[1]}\n\nsql=\"reset master;\"\nsql=\"$sql reset slave;\"\nsql=\"$sql change master to master_host='127.0.0.1', master_port=${MASTER_MYPORT}, master_user='root', master_auto_position=1, master_connect_retry=1;\"\nsql=\"$sql set global gtid_purged='$gtid_executed';\"\nsql=\"$sql start slave;\"\nsql=\"$sql stop slave;\"\nsql=\"$sql change master to master_auto_position=0;\"\nsql=\"$sql start slave;\"\n$MYSQL --defaults-group-suffix=.2 -e \"$sql\"\necho \"$sql\" > ${MYSQL_TMP_DIR}/gtid_stmt\n", "num_lines": 21}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. suite/rocksdb_hotbackup/include/clean_tmpfiles.sh\n\nif [ \"$STREAM_TYPE\" == 'wdt' ]; then\n  which wdt >/dev/null 2>&1\n  if [ $? -ne 0 ]; then\n    # change to tar if wdt is not installed\n    STREAM_TYPE='tar'\n  fi\nfi\n\nset -e\nset -o pipefail\n\n# Takes a full backup from server_1 to server_2\n# using myrocks_hotbackup streaming\n\ncheckpoint_dir=\"${MYSQLTEST_VARDIR}/checkpoint\"\nbackup_dir=\"${MYSQLTEST_VARDIR}/backup\"\ndest_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.2/data/\"\n\nmysql_dir=$(echo $MYSQL | awk '{print $1}' | xargs dirname)\nPATH=$mysql_dir:$PATH\n\nmkdir -p $checkpoint_dir\nrm -rf $checkpoint_dir/*\n\nmkdir -p $backup_dir\nrm -rf $backup_dir/*\n# delete and recreate the dest dir to make sure all hidden files\n# and directories (such as .rocksdb) are blown away\nrm -rf $dest_data_dir/\nmkdir $dest_data_dir\n\n\nSIGNAL_CONDITION=\"\"\n\nif [ \"$FRM\" == '1' ]; then\n  suite/rocksdb_hotbackup/include/create_table.sh $COPY_LOG $SIGNAL_FILE 2>&1 &\nfi\n\nif [ \"$DEBUG_SIGNAL\" == '1' ]; then\n  SIGNAL_CONDITION=\"--debug_signal_file=$SIGNAL_FILE\"\nfi\n\nif [ \"$STREAM_TYPE\" == 'tar' ]; then\n  BACKUP_CMD=\"$MYSQL_MYROCKS_HOTBACKUP --user='root' --port=${MASTER_MYPORT} \\\n    --stream=tar --checkpoint_dir=$checkpoint_dir $SIGNAL_CONDITION 2> \\\n    $COPY_LOG | tar -xi -C $backup_dir\"\nelif [ \"$STREAM_TYPE\" == 'wdt' ]; then\n  BACKUP_CMD=\"$MYSQL_MYROCKS_HOTBACKUP --user='root' --stream=wdt \\\n    --port=${MASTER_MYPORT} --destination=localhost --backup_dir=$backup_dir \\\n    --avg_mbytes_per_sec=10 --interval=5 $SIGNAL_CONDITION \\\n    --extra_wdt_sender_options='--block_size_mbytes=1' \\\n    --checkpoint_dir=$checkpoint_dir 2> \\\n    $COPY_LOG\"\nelif [ \"$STREAM_TYPE\" == \"xbstream_socket\" ]; then\n  BACKUP_CMD=\"$MYSQL_MYROCKS_HOTBACKUP --user='root' --socket=${MASTER_MYSOCK} \\\n    --stream=xbstream --checkpoint_dir=$checkpoint_dir $SIGNAL_CONDITION 2> \\\n    $COPY_LOG | xbstream -x \\\n    --directory=$backup_dir\"\nelse\n  BACKUP_CMD=\"$MYSQL_MYROCKS_HOTBACKUP --user='root' --port=${MASTER_MYPORT} \\\n    --stream=xbstream --checkpoint_dir=$checkpoint_dir $SIGNAL_CONDITION 2> \\\n    $COPY_LOG | xbstream -x \\\n    --directory=$backup_dir\"\nfi\n\necho \"myrocks_hotbackup copy phase\"\neval \"$BACKUP_CMD\"\n\nmkdir ${backup_dir}/test      # TODO: Fix skipping empty directories\n\n\necho \"myrocks_hotbackup move-back phase\"\n$MYSQL_MYROCKS_HOTBACKUP --move_back --datadir=$dest_data_dir \\\n  --rocksdb_datadir=$dest_data_dir/.rocksdb \\\n  --rocksdb_waldir=$dest_data_dir/.rocksdb \\\n  --backup_dir=$backup_dir > $MOVEBACK_LOG 2>&1\n\n", "num_lines": 82}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/std_data_master_link\nln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_master_link\n", "num_lines": 5}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/std_data_slave_link\nln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_slave_link\n", "num_lines": 5}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/master-data/test/rpl_misc_functions.outfile\n", "num_lines": 4}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nNUMTABLES=100\nfor ((i=0; i<$NUMTABLES; i++));\ndo\n    stmt='create table db1.t_'$i' (i int primary key) engine=innodb';\n    stmt=$stmt'; insert into db1.t_'$i' values (0), (1), (2), (3), (4)';\n    $MYSQL --defaults-group-suffix=.1 -e \"$stmt\"\ndone\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Initially creates a lot of tables.\n# Then start modifying and dropping those tables\n# while simultaneously running a backup\n\nsuite/xtrabackup/include/xb_create_tables.sh 2>&1\nsuite/xtrabackup/include/xb_modify_and_drop_tables.sh 2>&1 &\nsuite/xtrabackup/include/xb_run.sh 2>&1\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Insert 100 batches of 100 records each to a table with following schema:\n# create table db1.t1 (\n#   `id` int(10) not null auto_increment,\n#   `k` int(10),\n#   `data` varchar(255),\n#   primary key (`id`),\n#   key (`k`)\n# ) engine=innodb;\n\nMAX_INSERTS=100\nMAX_ROWS_PER_INSERT=100\nfor ((i=1; i<=$MAX_INSERTS; i++));\ndo\n    stmt='INSERT INTO db1.t1 values'\n    for ((j=1; j<=$MAX_ROWS_PER_INSERT; j++));\n    do\n        k=$RANDOM\n        data=$(head -c 255 /dev/urandom|tr -cd 'a-zA-Z0-9')\n        stmt=$stmt' (NULL, '$k', \"'$data'\")'\n        if [ $j -lt $MAX_ROWS_PER_INSERT ]; then\n            stmt=$stmt','\n        fi\n    done\n    stmt=$stmt';'\n    $MYSQL --defaults-group-suffix=.1 -e \"$stmt\"\ndone\n", "num_lines": 29}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Initially loads a chunk of data.\n# Then start loading another chunk of data,\n# while simultaneously running a backup\n\nsuite/xtrabackup/include/xb_load_data.sh 2>&1\nsuite/xtrabackup/include/xb_load_data_background.sh 2>&1 &\nsuite/xtrabackup/include/xb_run.sh 2>&1\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Remove file for safety\nif [ -f $LOAD_DONE_INDICATOR_FILE ]; then\n  rm $LOAD_DONE_INDICATOR_FILE\nfi\n\n# Execute the 10000 inserts and then create a file to indicate we are done\nsuite/xtrabackup/include/xb_load_data.sh 2>&1\necho \"done\" >$LOAD_DONE_INDICATOR_FILE\n", "num_lines": 11}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nstmt='insert into db1.t_99 values (100)';\nstmt='drop table db1.t_99';\n$MYSQL --defaults-group-suffix=.1 -e \"$stmt\"\n", "num_lines": 6}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Takes a full backup from server_1 to server_2\n\nibbackup_opt=\"--ibbackup=${MYSQL_XTRABACKUP}\"\ndefaults_file_opt=\"--defaults-file=${MYSQLTEST_VARDIR}/my.cnf\"\nbackup_dir=\"${MYSQLTEST_VARDIR}/backup\"\ndest_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.2/data/\"\nlog_dir=\"${MYSQLTEST_VARDIR}/log\"\n\nmkdir -p $backup_dir\nrm -rf $backup_dir/*\n# delete and recreate the dest dir to make sure all hidden files and directories (such as .rocksdb) are blown away\nrm -rf $dest_data_dir/\nmkdir $dest_data_dir\n\nmysql_dir=$(echo $MYSQL | awk '{print $1}' | xargs dirname)\nPATH=$mysql_dir:$PATH\n\necho \"innobackupex copy phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.1 $ibbackup_opt $backup_dir > $log_dir/xtrabackup_copy_log 2>&1\nthen\n  tail $log_dir/xtrabackup_copy_log\n  exit 1\nfi\nbackup_dir=($(grep \"innobackupex: Backup created in directory\" $log_dir/xtrabackup_copy_log | awk -F\\' '{ print $2}'))\n\necho \"innobackupex apply-log phase\"\nif ! $MYSQL_INNOBACKUPEX $ibbackup_opt $backup_dir --apply-log > $log_dir/xtrabackup_restore_log 2>&1\nthen\n  tail $log_dir/xtrabackup_restore_log\n  exit 1\nfi\n\necho \"innobackupex move-back phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.2 $ibbackup_opt $backup_dir --move-back > $log_dir/xtrabackup_moveback_log 2>&1\nthen\n  tail $log_dir/xtrabackup_moveback_log\n  exit 1\nfi\ncp $backup_dir/ib_logfile* $dest_data_dir\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nbinlog_line=($(grep -m 1 -o \"Last MySQL binlog file position 0 [0-9]*, file name .*\\.[0-9]*\" ${MYSQLTEST_VARDIR}/log/xtrabackup_restore_log))\nbinlog_pos=${binlog_line[6]%?}\nbinlog_file=${binlog_line[9]}\nsql=\"change master to master_host='127.0.0.1', master_port=${MASTER_MYPORT}, master_user='root', master_log_file='$binlog_file', master_log_pos=$binlog_pos, master_connect_retry=1; start slave\"\n$MYSQL --defaults-group-suffix=.2 -e \"$sql\"\n", "num_lines": 8}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\nbinlog_line=($(grep -m 1 -o \"Last MySQL binlog file position 0 [0-9]*, file name .*\\.[0-9]*\" ${MYSQLTEST_VARDIR}/log/xtrabackup_restore_log))\nbinlog_pos=${binlog_line[6]%?}\nbinlog_file=${binlog_line[9]}\n\nsql=\"show gtid_executed in '$binlog_file' from $binlog_pos\"\nresult=($($MYSQL --defaults-group-suffix=.1 -e \"$sql\"))\ngtid_executed=${result[1]}\n\nsql=\"reset master;\"\nsql=\"$sql reset slave;\"\nsql=\"$sql change master to master_host='127.0.0.1', master_port=${MASTER_MYPORT}, master_user='root', master_auto_position=1, master_connect_retry=1;\"\nsql=\"$sql set global gtid_purged='$gtid_executed';\"\nsql=\"$sql start slave;\"\nsql=\"$sql stop slave;\"\nsql=\"$sql change master to master_auto_position=0;\"\nsql=\"$sql start slave;\"\n$MYSQL --defaults-group-suffix=.2 -e \"$sql\"\necho \"$sql\" > ${MYSQLTEST_VARDIR}/log/gtid_stmt\n", "num_lines": 21}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\npage_size_cnf=\"innodb_page_size=$1\"\ncnf_file=\"${MYSQLTEST_VARDIR}/my.cnf\"\ntmp_file=\"${MYSQL_TMP_DIR}/tmp.cnf\"\ncat $cnf_file | awk  -v page_size_cnf=$page_size_cnf '{print;} /\\[mysqld\\]/ {print page_size_cnf;}' > $tmp_file\nmv $tmp_file $cnf_file\n", "num_lines": 8}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Wait for file indicating the background load is finished\nwhile ! [ -f $LOAD_DONE_INDICATOR_FILE ];\ndo\n  sleep 1\ndone\n# Remove the file now that we are done with it\nrm $LOAD_DONE_INDICATOR_FILE\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Takes a full backup from server_1 to server_2 using xbstream\n\nibbackup_opt=\"--ibbackup=${MYSQL_XTRABACKUP}\"\ndefaults_file_opt=\"--defaults-file=${MYSQLTEST_VARDIR}/my.cnf\"\nbackup_dir=\"${MYSQLTEST_VARDIR}/backup\"\ndest_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.2/data/\"\nxbstream_opt=\"--stream=${MYSQL_XBSTREAM}\"\nlog_dir=\"${MYSQLTEST_VARDIR}/log\"\n\nmysql_dir=$(echo $MYSQL | awk '{print $1}' | xargs dirname)\nPATH=$mysql_dir:$PATH\n\nmkdir -p $backup_dir\nrm -rf $backup_dir/*\n# delete and recreate the dest dir to make sure all hidden files and directories (such as .rocksdb) are blown away\nrm -rf $dest_data_dir/\nmkdir $dest_data_dir\n\necho \"innobackupex copy phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.1 $ibbackup_opt $xbstream_opt $backup_dir 2> $log_dir/xtrabackup_copy_log | $MYSQL_XBSTREAM -x --directory=$backup_dir\nthen\n  tail $log_dir/xtrabackup_copy_log\n  exit 1\nfi\n\necho \"innobackupex apply-log phase\"\nif ! $MYSQL_INNOBACKUPEX $ibbackup_opt $backup_dir --apply-log > $log_dir/xtrabackup_restore_log 2>&1\nthen\n  tail $log_dir/xtrabackup_restore_log\n  exit 1\nfi\n\necho \"innobackupex move-back phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.2 $ibbackup_opt $backup_dir --move-back > $log_dir/xtrabackup_moveback_log 2>&1\nthen\n  tail $log_dir/xtrabackup_moveback_log\n  exit 1\nfi\ncp $backup_dir/ib_logfile* $dest_data_dir\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -e\n\n# Takes a full backup from server_1 to server_2 using xbstream\n\nibbackup_opt=\"--ibbackup=${MYSQL_XTRABACKUP}\"\ndefaults_file_opt=\"--defaults-file=${MYSQLTEST_VARDIR}/my.cnf\"\nbackup_dir=\"${MYSQLTEST_VARDIR}/backup\"\ndest_data_dir=\"${MYSQLTEST_VARDIR}/mysqld.2/data/\"\nxbstream_opt=\"--stream=${MYSQL_XBSTREAM} --slow_rm_chunk_delay=2 --slow_rm_chunk_percentage=20\"\nlog_dir=\"${MYSQLTEST_VARDIR}/log\"\n\nmysql_dir=$(echo $MYSQL | awk '{print $1}' | xargs dirname)\nPATH=$mysql_dir:$PATH\n\nmkdir -p $backup_dir\nrm -rf $backup_dir/*\n# delete and recreate the dest dir to make sure all hidden files and directories (such as .rocksdb) are blown away\nrm -rf $dest_data_dir/\nmkdir $dest_data_dir\n\necho \"innobackupex copy phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.1 $ibbackup_opt $xbstream_opt $backup_dir 2> $log_dir/xtrabackup_copy_log | $MYSQL_XBSTREAM -x --directory=$backup_dir\nthen\n  tail $log_dir/xtrabackup_copy_log\n  exit 1\nfi\n\necho \"innobackupex apply-log phase\"\nif ! $MYSQL_INNOBACKUPEX $ibbackup_opt $backup_dir --apply-log > $log_dir/xtrabackup_restore_log 2>&1\nthen\n  tail $log_dir/xtrabackup_restore_log\n  exit 1\nfi\n\necho \"innobackupex move-back phase\"\nif ! $MYSQL_INNOBACKUPEX $defaults_file_opt --defaults-group=mysqld.2 $ibbackup_opt $backup_dir --move-back > $log_dir/xtrabackup_moveback_log 2>&1\nthen\n  tail $log_dir/xtrabackup_moveback_log\n  exit 1\nfi\ncp $backup_dir/ib_logfile* $dest_data_dir\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\ntouch $1/slocket_listen_kill_flag\nsleep 3\nrm $1/slocket_listen_kill_flag\n", "num_lines": 5}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nd=\"$MYSQLTEST_VARDIR/tmp/long_temporary_directory_path_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 6}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# This test requires a non-lowercase tmpdir directory on a case-sensitive\n# filesystem.\n\nd=\"$MYSQLTEST_VARDIR/tmp/MixedCase\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 9}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# This test requires a non-lowercase tmpdir directory on a case-sensitive\n# filesystem.\n\nd=\"$MYSQLTEST_VARDIR/tmp/MixedCase\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 9}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n###########################################################################\n\n# NOTE: this script returns 0 (success) even in case of failure (except for\n# usage-error). This is because this script is executed under\n# mysql-test-run[.pl] and it's better to examine particular problem in log\n# file, than just having said that the test case has failed.\n\n###########################################################################\n\nbasename=`basename \"$0\"`\ndirname=`dirname \"$0\"`\n\n###########################################################################\n\nlog_debug() {\n  echo $1 >> $log_file\n}\n\n###########################################################################\n\nif [ $# -ne 3 ]; then\n  echo \"Usage: $0 <client> <socket path> <test id>\"\n  exit 1\nfi\n\nclient_exe=\"$1\"\ndatadir_path=\"$2\"\ntest_id=\"$3\"\nlog_file=\"$MYSQLTEST_VARDIR/log/$test_id.script.log\"\nout_file=\"$MYSQLTEST_VARDIR/log/$test_id.listen.log\"\n\nlog_debug \"-- $basename: starting --\"\nlog_debug \"client_exe: '$client_exe'\"\nlog_debug \"datadir_path: '$datadir_path'\"\nlog_debug \"test_id: '$test_id'\"\nlog_debug \"log_file: '$log_file'\"\nlog_debug \"out_file: '$out_file'\"\n\n###########################################################################\n\nif [ -z \"$client_exe\" ]; then\n  log_debug \"Invalid path to client executable ($client_exe).\"\n  exit 0;\nfi\n\nif [ ! -x \"$client_exe\" ]; then\n  log_debug \"Client by path '$client_exe' is not available.\"\n  exit 0;\nfi\n\n###########################################################################\n\nlog_debug \"--- running slocket listener --- \"\npython3 $client_exe $datadir_path > $out_file &\n\n# perhaps the most important sleep of my life... without this, the test\n# fails because the socket isn't opened before the test continues\nsleep 1\n", "num_lines": 61}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Wrapper script for mysql_config to support multilib\n#\n#\n\n# This command respects setarch, works on OL6/RHEL6 and later\nbits=$(rpm --eval %__isa_bits)\n\ncase $bits in\n    32|64) ;;\n        *) bits=unknown ;;\nesac\n\n# Try mapping by uname if rpm command failed\nif [ \"$bits\" = \"unknown\" ] ; then\n    arch=$(uname -m)\n    case $arch in\n\tx86_64|ppc64|ppc64le|aarch64|s390x|sparc64) bits=64 ;;\n\ti386|i486|i586|i686|pentium3|pentium4|athlon|ppc|s390|sparc) bits=32 ;;\n\t*) bits=unknown ;;\n    esac\nfi\n\nif [ \"$bits\" == \"unknown\" ] ; then\n    echo \"$0: error: failed to determine isa bits on your arch.\"\n    exit 1\nfi\n\nif [ -x /usr/bin/mysql_config-$bits ] ; then\n    /usr/bin/mysql_config-$bits \"$@\"\nelse\n    echo \"$0: error: needed binary: /usr/bin/mysql_config-$bits is missing. Please check your MySQL installation.\"\n    exit 1\nfi\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.prov $* |\nsed -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.req $* |\nsed -e '/perl(GD)/d' -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Wrapper script for mysql_config to support multilib\n#\n#\n\n# This command respects setarch, works on OL6/RHEL6 and later\nbits=$(rpm --eval %__isa_bits)\n\ncase $bits in\n    32|64) ;;\n        *) bits=unknown ;;\nesac\n\n# Try mapping by uname if rpm command failed\nif [ \"$bits\" = \"unknown\" ] ; then\n    arch=$(uname -m)\n    case $arch in\n\tx86_64|ppc64|ppc64le|aarch64|s390x|sparc64) bits=64 ;;\n\ti386|i486|i586|i686|pentium3|pentium4|athlon|ppc|s390|sparc) bits=32 ;;\n\t*) bits=unknown ;;\n    esac\nfi\n\nif [ \"$bits\" == \"unknown\" ] ; then\n    echo \"$0: error: failed to determine isa bits on your arch.\"\n    exit 1\nfi\n\nif [ -x /usr/bin/mysql_config-$bits ] ; then\n    /usr/bin/mysql_config-$bits \"$@\"\nelse\n    echo \"$0: error: needed binary: /usr/bin/mysql_config-$bits is missing. Please check your MySQL installation.\"\n    exit 1\nfi\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.prov $* |\nsed -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.req $* |\nsed -e '/perl(GD)/d' -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA\n#\n# Solaris post install script\n#\n\n#if [ /usr/man/bin/makewhatis ] ; then\n#  /usr/man/bin/makewhatis \"$BASEDIR/mysql/man\"\n#fi\n\nmygroup=mysql\nmyuser=mysql\nmydatadir=/var/lib/mysql\nbasedir=@@basedir@@\nmysecurefiledir=/var/lib/mysql-files\n\nif [ -n \"$BASEDIR\" ] ; then\n  basedir=\"$BASEDIR\"\nfi\n\n# What MySQL calls \"basedir\" and what pkgadd tools calls \"basedir\"\n# is not the same thing. The default pkgadd base directory is /opt/mysql,\n# the MySQL one \"/opt/mysql/mysql\".\n\nmybasedir=\"$basedir/@@instdir@@\"\nmystart1=\"$mybasedir/support-files/mysql.server\"\nmyinstdb=\"$mybasedir/scripts/mysql_install_db\"\nmystart=/etc/init.d/mysql\n\n# Check: Is this a first installation, or an upgrade ?\n\nif [ -d \"$mydatadir/mysql\" ] ; then\n  :   # If the directory for system table files exists, we assume an upgrade.\nelse\n  INSTALL=new  # This is a new installation, the directory will soon be created.\nfi\n\n# Create data directory if needed\n\n[ -d \"$mydatadir\"       ] || mkdir -p -m 755 \"$mydatadir\" || exit 1\n[ -d \"$mydatadir/mysql\" ] || mkdir \"$mydatadir/mysql\"     || exit 1\n[ -d \"$mydatadir/test\"  ] || mkdir \"$mydatadir/test\"      || exit 1\n\n# Set the data directory to the right user/group\n\nchown -R $myuser:$mygroup $mydatadir\n\n# Create securefile directory\n[ -d \"$mysecurefiledir\"  ] || mkdir -p -m 770 \"$mysecurefiledir\"      || exit 1\nchown -R $myuser:$mygroup $mysecurefiledir\n\n# Solaris patch 119255 (somewhere around revision 42) changes the behaviour\n# of pkgadd to set TMPDIR internally to a root-owned install directory.  This\n# has the unfortunate side effect of breaking running mysql_install_db with\n# the --user=mysql argument as mysqld uses TMPDIR if set, and is unable to\n# write temporary tables to that directory.  To work around this issue, we\n# create a subdirectory inside TMPDIR (if set) for mysqld to write to.\n#\n# Idea from Ben Hekster <heksterb@gmail.com> in bug#31164\n\nif [ -n \"$TMPDIR\" ] ; then\n  savetmpdir=\"$TMPDIR\"\n  TMPDIR=\"$TMPDIR/mysql.$$\"\n  export TMPDIR\n  mkdir \"$TMPDIR\"\n  chown $myuser:$mygroup \"$TMPDIR\"\nfi\n\nif [ -n \"$INSTALL\" ] ; then\n  # We install/update the system tables\n  (\n    cd \"$mybasedir\"\n    scripts/mysql_install_db \\\n\t  --rpm \\\n\t  --random-passwords \\\n\t  --user=mysql \\\n\t  --basedir=\"$mybasedir\" \\\n\t  --datadir=$mydatadir\n  )\nfi\n\nif [ -n \"$savetmpdir\" ] ; then\n  TMPDIR=\"$savetmpdir\"\nfi\n\n# ----------------------------------------------------------------------\n\n# Handle situation there is old start script installed already\n\n# If old start script is a soft link, we just remove it\n[ -h \"$mystart\" ] && rm -f \"$mystart\"\n\n# If old start script is a file, we rename it\n[ -f \"$mystart\" ] && mv -f \"$mystart\" \"$mystart.old.$$\"\n\n# ----------------------------------------------------------------------\n\n# We create a copy of an unmodified start script,\n# as a reference for the one maybe modifying it\n\ncp -f \"$mystart1.in\" \"$mystart.in\" || exit 1\n\n# We rewrite some scripts\n\nfor script in \"$mystart\" \"$mystart1\" \"$myinstdb\" ; do\n  script_in=\"$script.in\"\n  sed -e \"s,@basedir@,$mybasedir,g\" \\\n      -e \"s,@datadir@,$mydatadir,g\" \"$script_in\" > \"$script\"\n  chmod u+x $script\ndone\n\nrm -f \"$mystart.in\"\n\nexit 0\n\n", "num_lines": 130}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\nMEMC_VERSION=`git describe | tr '-' '_'`;\ncat > .libs/config_version.h << EOF\n#ifndef CONFIG_VERSION_H\n#define CONFIG_VERSION_H\n\n/* Define to the full name and version of this package. */\n#define PACKAGE_STRING \"memcached $MEMC_VERSION\"\n\n/* Define to the version of this package. */\n#define PACKAGE_VERSION \"$MEMC_VERSION\"\n\n/* Version number of package */\n#define VERSION \"$MEMC_VERSION\"\n\n#endif // CONFIG_VERSION_H\nEOF\n", "num_lines": 18}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 1979, 2014, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; see the file COPYING. If not, write to the\n# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston\n# MA  02110-1301  USA.\n\necho \"Warning: $0 is deprecated and will be removed in a future version.\\n\" 1>&2;\n\n@bindir@/replace msqlConnect mysql_connect msqlListDBs  mysql_list_dbs msqlNumRows mysql_num_rows msqlFetchRow mysql_fetch_row msqlFetchField mysql_fetch_field msqlFreeResult mysql_free_result msqlListFields mysql_list_fields msqlListTables mysql_list_tables msqlErrMsg 'mysql_error(mysql)' msqlStoreResult mysql_store_result msqlQuery mysql_query msqlField mysql_field msqlSelect mysql_select msqlSelectDB mysql_select_db msqlNumFields mysql_num_fields msqlClose mysql_close msqlDataSeek mysql_data_seek m_field MYSQL_FIELD m_result MYSQL_RES m_row MYSQL_ROW msql mysql mSQL mySQL MSQL MYSQL msqlCreateDB mysql_create_db msqlDropDB mysql_drop_db msqlFieldSeek mysql_field_seek -- $*\n", "num_lines": 21}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n\n# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# ****************************\npackage MySQLaccess;\n#use strict;\nuse File::Temp qw(tempfile tmpnam);\nuse Fcntl;\n\nBEGIN {\n\t# ****************************\n\t# static information...\n\t$VERSION     = \"2.06, 20 Dec 2000\";\n\t$0           =~ m%/([^/]+)$%o;\n\t$script      = $1;\n        $script      = 'MySQLAccess' unless $script;\n\t$script_conf = \"$script.conf\";\n\t$script_log  = $ENV{'HOME'}.\"/$script.log\";\n\n\t# ****************************\n\t# information on MySQL\n\t$MYSQL     = '@bindir@/mysql';    # path to mysql executable\n\t$SERVER    = '3.21';\n\t$MYSQL_OPT = ' --batch --unbuffered';\n\t$ACCESS_DB = 'mysql';\t\t # name of DB with grant-tables\n\t$ACCESS_H  = 'host';\t\t # \n\t$ACCESS_U  = 'user';\t         # \n\t$ACCESS_D  = 'db';               #\n\t# Add/Edit privileges\n\t$ACCESS_H_TMP = 'host_tmp';      \n\t$ACCESS_U_TMP = 'user_tmp';      \n\t$ACCESS_D_TMP = 'db_tmp';        \n\t$ACCESS_H_BCK = 'host_backup';   \n\t$ACCESS_U_BCK = 'user_backup';   \n\t$ACCESS_D_BCK = 'db_backup';     \n        $DIFF      = '/usr/bin/diff'; \n        $MYSQLDUMP = '@bindir@/mysqldump';\n                                         #path to mysqldump executable\n\n        $MYSQLADMIN= 'http://example.com/MySQLadmin';\n                                         #URL of CGI for manipulating\n                                         #the temporary grant-tables\n}\n\nEND {\n\tunlink $MYSQL_CNF if defined $MYSQL_CNF and not $DEBUG;\n}\n\n$INFO = <<\"_INFO\";\n--------------------------------------------------------------------------\n   mysqlaccess (Version $VERSION)\n   ~~~~~~~~~~~\n   Copyright (C) 1997,1998 Yves.Carlier\\@rug.ac.be\n                           University of Ghent (RUG), Belgium\n                           Administratieve Informatieverwerking (AIV)\n\n   report the access-privileges for a USER from a HOST to a DB\n\n   Many thanks go to <monty\\@mysql.com> and <psmith\\@BayNetworks.COM>\n   for their suggestions, debugging and patches. \n\n   use `$script -?' to get more information on available options.\n\n   From version 2.0x, $script can also be used through a WEB-browser\n   if it is ran as a CGI-script.  (See the release-notes)\n\n--------------------------------------------------------------------------\n_INFO\n\n$OPTIONS = <<_OPTIONS;\n\nUsage: $script [host [user [db]]] OPTIONS\n\n  -?, --help           display this helpscreen and exit\n  -v, --version        print information on the program `$script'\n\n  -u, --user=#         username for logging in to the db\n  -p, --password=#     validate password for user\n  -h, --host=#         name or IP-number of the host\n  -d, --db=#           name of the database\n\n  -U, --superuser=#    connect as superuser\n  -P, --spassword=#    password for superuser\n  -H, --rhost=#        remote MySQL-server to connect to\n      --old_server     connect to old MySQL-server (before v3.21) which \n                       does not yet know how to handle full where clauses.\n\n  -b, --brief          single-line tabular report\n  -t, --table          report in table-format\n\n  --relnotes           print release-notes\n  --plan               print suggestions/ideas for future releases\n  --howto              some examples of how to run `$script'\n  --debug=N            enter debuglevel N (0..3)\n\n  --copy               reload temporary grant-tables from original ones\n  --preview            show differences in privileges after making\n                       changes in (temporary) grant-tables\n  --commit             copy grant-rules from temporary tables to grant-tables\n                       (!don't forget to do an mysqladmin reload)\n  --rollback           undo the last changes to the grant-tables.\n\n  Note:\n    + At least the user and the db must be given (even with wildcards)\n    + If no host is given, `localhost' is assumed\n    + Wilcards (*,?,%,_) are allowed for host, user and db, but be sure \n      to escape them from your shell!! (ie type \\\\* or '*')\n_OPTIONS\n\n$RELEASE = <<'_RELEASE';\n \nRelease Notes:\n-------------\n  0.1-beta1: internal\n  - first trial.\n \n  0.1-beta2: (1997-02-27)\n  - complete rewrite of the granting-rules, based on the documentation\n    found in de FAQ.\n  - IP-number and name for a host are equiv.\n \n  0.1-beta3: (1997-03-10)\n  - more information\n  - 'localhost' and the name/ip of the local machine are now equiv.\n\n  0.1-beta4: (1997-03-11)\n  - inform the user if he has not enough priv. to read the mysql db\n\n  1.0-beta1: (1997-03-12)\n  suggestions by Monty:\n  - connect as superuser with superpassword.\n  - mysqlaccess could also notice if all tables are empty. This means\n    that all user have full access!\n  - It would be nice if one could optionally start mysqlaccess without\n    any options just the arguments 'user db' or 'host user db', where\n    host is 'localhost' if one uses only two arguments.\n\n  1.0-beta2: (1997-03-14)\n  - bugfix: translation to reg.expr of \\_ and \\%.\n  - bugfix: error in matching regular expression and string given\n            by user which resulted in\n            'test_123' being matched with 'test'\n\n  1.0-beta3: (1997-03-14)\n  - bugfix: the user-field should not be treated as a sql-regexpr,\n            but as a plain string.\n  - bugfix: the host-table should not be used if the host isn't empty in db\n                                          or  if the host isn't emty in user\n            (Monty)\n \n  1.0-beta4: (1997-03-14)\n  - bugfix: in an expression \"$i = $j or $k\", the '=' binds tighter than the or\n            which results in problems...\n            (by Monty)\n  - running mysqlaccess with \"perl -w\" gives less warnings...   ;-)\n\n  1.0-beta5: (1997-04-04)\n  - bugfix: The table sorting was only being applied to the \"user\" table; all\n            the tables need to be sorted.  Rewrote the sort algorithm, and\n            the table walk algorithm (no temp file anymore), and various\n            other cleanups.  I believe the access calculation is 100% correct.\n            (by Paul D. Smith <psmith\\@baynetworks.com>)\n  - Allow the debug level to be set on the cmd line with --debug=N.\n            (by Paul D. Smith <psmith\\@baynetworks.com>)\n  - More -w cleanups; should be totally -w-clean.\n            (by Paul D. Smith <psmith\\@baynetworks.com>)\n \n  1.1-beta1: (1997-04-xx) \n  1.1-beta2: (1997-04-11)\n  - new options:\n             --all_users : report access-rights for all possible users\n             --all_dbs   : report access-rights for all possible dbs\n             --all_hosts : report access-rights for all possible hosts\n             --brief     : as brief as possible, don't mention notes,warnings and rules\n             --password  : validate password for user \n  - layout: long messages are wrapped on the report.\n  - functionality:\n            more descriptive notes and warnings\n            wildcards (*,?) are allowed in the user,host and db options\n            setting xxxx=* is equiv to using option --all_xxxx\n            note: make sure you escape your wildcards, so they don't get\n                  interpreted by the shell.  use \\* or '*'\n  - bugfix: Fieldnames which should be skipped on the output can now have\n            a first capital letter.\n  - bugfix: any option with a '.' (eg ip-number) was interpreted as\n            a wildcard-expression.\n  - bugfix: When no entry was found in the db-table, the default accessrights are\n            N, instead of the faulty Y in a previous version.\n \n  1.1-beta-3  : (1997-04-xx)\n  1.1-beta-4  : (1997-04-xx)\n  1.1-beta-5  : (1997-04-xx)\n  1.1         : (1997-04-28)\n  - new options:\n            --rhost     : name of mysql-server to connect to\n            --plan      : print suggestions/ideas for future releases\n            --relnotes  : display release-notes\n            --howto     : display examples on how to use mysqlaccess\n            --brief     : single-line tabular output\n  - functionality/bugfix:\n    *      removed options --all_users,--all_dbs,--all_hosts, which \n           were redundant with the wildcard-expressions for the corresponding\n           options. They made the processing of the commandline too painful \n           and confusing ;-)\n           (suggested by psmith)\n    *      redefined the option --brief, which now gives a single-line \n           tabular output\n    *      Now we check if the right version of the mysql-client is used,\n           since we might use an option not yet implemented in an\n           older version (--unbuffered, since 3.0.18)\n           Also the error-messages the mysql-client reports are \n           better interpreted ;-)  \n    *      Wildcards can now be given following the SQL-expression \n           (%,_) and the Regular-expression (*,?) syntax.\n  - speed: we now open a bidirectional pipe to the mysql-client, and keep \n           it open throughout the whole run. Queries are written to,\n           and the answers read from the pipe.\n           (suggested by monty)\n  - bugfixes:\n    *      the Rules were not properly reset over iterations \n    *      when in different tables the field-names were not identical, \n           eg. Select_priv and select_priv, they were considered as \n           definitions of 2 different access-rights.\n    *      the IP-number of a host with a name containing wildcards should\n           not be searched for in Name2IP and IP2Name.\n    *      various other small things, pointed out by <monty> and <psmith>\n\n  1.2         : (1997-05-13)\n  - bugfix:\n    * Fixed bug in acl with anonymous user:  Now if one gets accepted by the\n      user table as a empty user name, the user name is set to '' when \n      checking against the 'db' and 'host' tables. (Bug fixed in MySQL3.20.19)\n\n  1.2-1       : (1997-xx-xx)\n  - bugfix:\n    * hashes should  be initialized with () instead of {} <psmith>\n    * \"my\" variable $name masks earlier declaration in same scope,\n      using perl 5.004 <????>\n\n  1.2-2       : (1997-06-10)\n    \n  2.0p1-3     : (1997-10-xx)\n  - new\n    * packages\n    * log-file for debug-output : /tmp/mysqlaccess.log\n    * default values are read from a configuration file $script.conf\n      first this file is looked for in the current directory; if not\n      found it is looked for in /etc/\n      Note that when default-values are given, these can't get overriden\n      by empty (blanc) values!\n    * CGI-BIN version with HTML and forms interface.  Simply place the\n      script in an ScriptAliased directory, make the configuration file\n      available in the that directory or in /etc, and point your browser\n      to the right URL. \n    * copy the grant-rules to temporary tables, where you are safe to\n      play with them.\n    * preview changes in privileges after changing grant-rules,\n      before taking them into production\n    * copy the new grant-rules from the temporary tables back to the\n      grant-tables.\n    * Undo all changes made in the grant-tables (1-level undo).\n  -new options:\n    * --table   : as opposite of the --brief option.\n    * --copy    : (re)load temporary grant-tables from original ones.\n    * --preview : preview changes in privileges after changing\n                  some or more entries in the grant-tables.\n    * --commit  : copy grant-rules from temporary tables to grant-tables\n                  (!don't forget to do an mysqladmin reload)\n    * --rollback: undo the last changes to the grant-tables.\n\n  - bugfix:\n    * if the table db is empty, mysqlaccess freezed \n      (by X Zhu <X.Zhu@Bradford.ac.uk>)\n\n  2.0         : (1997-10-09)\n  - fixed some \"-w\" warnings.\n  - complain when certain programs and paths can't be found.\n\n  2.01        : (1997-12-12)\n  - bugfix:\n    * rules for db-table where not calculated and reported correctly.\n  2.02        : (1998-01-xx)\n  - bugfix:\n    * Privileges of the user-table were not AND-ed properly with the\n      other privileges. (reported by monty)\n  - new option:\n    * --old_server: mysqlaccess will now use a full where clause when\n                    retrieving information from the MySQL-server.  If\n                    you are connecting to an old server (before v3.21)\n                    then use the option --old_server.\n  2.03         : (1998-02-27)\n  - bugfix:\n    * in Host::MatchTemplate: incorrect match if host-field was left empty.\n\n  2.04-alpha1  : (2000-02-11)\n  Closes vulnerability due to former implementation requiring passwords\n  to be passed on the command line.\n  - functionality\n    Option values for --password -p -spassword -P  may now be omitted from\n    command line, in which case the values will be prompted for.\n      (fix supplied by Steve Harvey <sgh@vex.net>)\n\n   2.05: (2000-02-17)   Monty\n   Moved the log file from /tmp to ~\n\n   2.06:  Don't print '+++USING FULL WHERE CLAUSE+++'\n\n_RELEASE\n\n$TODO = <<_TODO;\n\n Plans:\n -----\n  -a full where clause is use now.  How can we handle older servers?\n  -add some more functionality for DNS.\n  -select the warnings more carefuly.\n  >>  I think that the warnings should either be enhanced to _really_\n  >>  understand and report real problems accurately, or restricted to\n  >>  only printing things that it knows with 100% certainty. <psmith)\n  >>  Why do I have both '%' and 'any_other_host' in there?  Isn't that\n  >>  the same thing?  I think it's because I have an actual host '%' in\n  >>  one of my tables.  Probably the script should catch that and not\n  >>  duplicate output. <psmith>\n\n_TODO\n\n# From the FAQ: the Grant-algorithm\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# The host table is mainly to maintain a list of \"secure\" servers.\n# At TCX hosts contain a list of all machines on local network. These are granted\n# all privileges.\n# Technically the user grant is calculated by:\n#\n#    1.First sort all entries by host by putting host without wildcards first,\n#      after this host with wildcards and entries with host = \".\n#      Under each host sort user by the same criterias.\n#    2.Get grant for user from the \"db\" table.\n#    3.If hostname is \"empty\" for the found entry, AND the privileges with\n#      the privileges for the host in \"host\" table.\n#      (Remove all which is not \"Y\" in both)\n#    4.OR (add) the privileges for the user from the \"user\" table.\n#     (add all privileges which is \"Y\" in \"user\")\n#\n#    When matching, use the first found match.\n#\n# -----------------------------------------------------------------------------------\n\n$HOWTO = <<_HOWTO;\n\nExamples of how to call $script:\n~~~~~~~~\n1)Calling $script with 2 arguments:\n\n  \\$ $script root mysql\n     ->report rights of user root logged on at the local host in db mysql\n\n  Access-rights\n  for USER 'root', from HOST 'localhost', to DB 'mysql'\n          +-----------------+---+ +-----------------+---+\n          | select_priv     | Y | | drop_priv       | Y |\n          | insert_priv     | Y | | reload_priv     | Y |\n          | update_priv     | Y | | shutdown_priv   | Y |\n          | delete_priv     | Y | | process_priv    | Y |\n          | create_priv     | Y | | file_priv       | Y |\n          +-----------------+---+ +-----------------+---+\n  BEWARE:  Everybody can access your DB as user 'root'\n        :  WITHOUT supplying a password.  Be very careful about it!!\n\n  The following rules are used:\n   db    : 'No matching rule'\n   host  : 'Not processed: host-field is not empty in db-table.'\n   user  : 'localhost','root','','Y','Y','Y','Y','Y','Y','Y','Y','Y','Y'\n\n2)Calling $script with 3 arguments:\n\n  \\$ $script foo.bar nobody Foo \n     ->report rights of user root logged in at machine foobar to db Foo\n\n  Access-rights\n  for USER 'nobody', from HOST 'foo.bar', to DB 'Foo'\n          +-----------------+---+ +-----------------+---+\n          | select_priv     | Y | | drop_priv       | N |\n          | insert_priv     | Y | | reload_priv     | N |\n          | update_priv     | Y | | shutdown_priv   | N |\n          | delete_priv     | Y | | process_priv    | N |\n          | create_priv     | N | | file_priv       | N |\n          +-----------------+---+ +-----------------+---+\n  BEWARE:  Everybody can access your DB as user 'nobody'\n        :  WITHOUT supplying a password.  Be very careful about it!!\n\n  The following rules are used:\n   db    : 'foo.bar','Foo','nobody','Y','Y','Y','N','N','N'\n   host  : 'Not processed: host-field is not empty in db-table.'\n   user  : 'foo.bar','nobody','','N','N','N','Y','N','N','N','N','N','N'\n\n3)Using wildcards:\n\n  \\$ $script  \\\\* nobody Foo --brief\n     ->report access-rights of user nobody from all machines to db Foo,\n       and use a matrix-report.\n\n  Sel  Ins  Upd  Del  Crea Drop Reld Shut Proc File Host,User,DB        \n  ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- --------------------\n   Y    Y    Y    Y    N    N    N    N    N    N   localhost,nobody,Foo\n   N    N    N    N    N    N    N    N    N    N   %,nobody,Foo  \n   N    N    N    N    N    N    N    N    N    N   any_other_host,nobody,Foo\n\n_HOWTO\n\n\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #\n#                       START OF THE PROGRAM                            #\n# +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ #\n\nuse Getopt::Long;\nuse Sys::Hostname;\nuse IPC::Open3;\n\n\n# ****************************\n# debugging flag\n# can be set to 0,1,2,3\n# a higher value gives more info\n# ! this can also be set on the command-line\n\t$DEBUG   = 0;\n\n# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++>8\n#  Normaly nothing should be changed beneeth this line\n\n\n# ****************************\n# no caching on STDOUT\n\t$|=1;\n\n\t$MYSQL_CNF = tmpnam();\n\t%MYSQL_CNF = (client    => { },\n                      mysql     => { },\n                      mysqldump => { },\n\t);\n\n\n\n$NEW_USER = 'ANY_NEW_USER';\n$NEW_DB   = 'ANY_NEW_DB'  ;\n\n\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #\n#  mysqlaccess:                                              #\n#  ~~~~~~~~~~~                                               #\n#  Lets get to it,                                           #\n#  and start the program by processing the parameters        #\n# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #\n\n($CMD,$CGI) = GetMode();\n\n# ****************************\n# the copyright message should\n# always be printed (once)\nMySQLaccess::Report::Print_Header();\n\n# *****************************\n# Read configuration-file\n  MySQLaccess::Debug::Print(1, \"Reading configuration file...\");\n  if (-f \"./$script_conf\") {\n     require \"./$script_conf\";\n  }\n  elsif (-f \"@sysconfdir@/$script_conf\") {\n     require \"@sysconfdir@/$script_conf\";\n  }\n  elsif (-f \"/etc/$script_conf\") {\n     require \"/etc/$script_conf\";\n  }\n\n# ****************************\n# Read in all parameters\nif ($MySQLaccess::CMD) { #command-line version\n\t# ----------------------------\n\t# Get options from commandline\n\t$Getopt::Long::ignorecase=0; #case sensitive options\n\tif ( grep(/\\-\\?/,@ARGV) ) { MySQLaccess::Report::Print_Usage(); exit 0; }\n\tGetOptions(\"help\"          => \\$Param{'help'}\n\t          ,\"host|h=s\"      => \\$Param{'host'}\n\t          ,\"user|u=s\"      => \\$Param{'user'}\n\t          ,\"password|p:s\"  => \\$Param{'password'}\n\t          ,\"db|d=s\"        => \\$Param{'db'}\n\t          ,\"superuser|U=s\" => \\$Param{'superuser'}\n\t          ,\"spassword|P:s\" => \\$Param{'spassword'}\n\t          ,\"rhost|H=s\"     => \\$Param{'rhost'}\n                  ,\"old_server\"    => \\$Param{'old_server'}\n\t          ,\"debug=i\"       => \\$Param{'DEBUG'}\n\t          ,\"brief|b\"       => \\$Param{'brief'}\n\t          ,\"table|t\"       => \\$Param{'table'}\n\t          ,\"relnotes\"      => \\$Param{'relnotes'}\n\t          ,\"plan\"          => \\$Param{'plan'}\n\t          ,\"howto\"         => \\$Param{'howto'}\n\t          ,\"version|v\"     => \\$Param{'version'}\n                  ,\"preview\"       => \\$Param{'preview'}\n                  ,\"copy\"          => \\$Param{'copy'}\n                  ,\"commit\"        => \\$Param{'commit'}\n                  ,'rollback'      => \\$Param{'rollback'}\n\t\t  );\n\n        # -----------------------------\n        # set DEBUG\n        $DEBUG = $Param{'DEBUG'} if ($Param{'DEBUG'}>=$DEBUG);\n\n\t# -----------------------------\n\t# check for things which aren't\n\t# declared as options:\n\t# 2 arguments: (user,db) -> ('localhost','user','db')\n\tif ($#ARGV == 1) {\n\t   MySQLaccess::Debug::Print(2,\"$script called with 2 arguments:\");\n\t   $Param{'host'} = $Param{'host'} || 'localhost'; \n\t   $Param{'user'} = $ARGV[0] || $Param{'user'};\n           $Param{'db'}   = $ARGV[1] || $Param{'db'}; \n\t}\n\t# 3 arguments: (host,user,db)\n\tif ($#ARGV == 2) {\n\t   MySQLaccess::Debug::Print(2,\"$script called with 3 arguments:\");\n\t   $Param{'host'} = $ARGV[0] || $Param{'host'};\n\t   $Param{'user'} = $ARGV[1] || $Param{'user'};\n\t   $Param{'db'}   = $ARGV[2] || $Param{'db'};\n\t}\n\n\t# -------------------------------------\n\t# prompt for user password if requested\n\tif ( defined($Param{'password'}) && length($Param{'password'}) == 0 ) {\n           $Param{'password'} = PromptPass(\n\t                        \"Password for MySQL user $Param{'user'}: \");\n\t}\n}\nif ($MySQLaccess::CGI) { #CGI-version\n\trequire CGI;\n \t$Q = new CGI;\n\t$Param{'help'} = $Q->param('help') ;\n\t$Param{'host'} = $Q->param('host') || $Q->param('h') || $Param{'host'};\n\t$Param{'user'} = $Q->param('user') || $Q->param('u') || $Param{'user'};\n\t$Param{'db'}   = $Q->param('db')   || $Q->param('d') || $Param{'db'};\n\t$Param{'password'}  = $Q->param('password')  || $Q->param('p') || $Param{'password'};\n\t$Param{'superuser'} = $Q->param('superuser') || $Q->param('U') || $Param{'superuser'};\n\t$Param{'spassword'} = $Q->param('spassword') || $Q->param('P') || $Param{'spassword'};\n\t$Param{'rhost'}     = $Q->param('rhost')     || $Q->param('H') || $Param{'rhost'};\n\t$Param{'old_server'}= $Q->param('old_server')|| $Param{'old_server'};\n\t$Param{'debug'}     = $Q->param('debug')     || $Param{'debug'};\n\t$Param{'brief'}     = $Q->param('brief')     || $Param{'brief'}; \n\t$Param{'table'}     = $Q->param('table')     || $Param{'table'}; \n\t$Param{'relnotes'}  = $Q->param('relnotes');\n\t$Param{'plan'}      = $Q->param('plan');\n\t$Param{'howto'}     = $Q->param('howto'); \n\t$Param{'version'}   = $Q->param('version') ? $Q->param('version') : $Q->param('v');\n\t$Param{'edit'}      = $Q->param('edit'); \n\t$Param{'preview'}   = $Q->param('preview'); \n\t$Param{'copy'}      = $Q->param('copy'); \n\t$Param{'commit'}    = $Q->param('commit'); \n\t$Param{'rollback'}  = $Q->param('rollback'); \n        # -----------------------------\n        # set DEBUG\n        $DEBUG = $Q->param('debug') if ($Q->param('debug')>=$DEBUG);\n}\n\n# ----------------------\n# brief and table-format \n# exclude each-other\n# table-format is prefered\nif (defined($Param{'table'})) { undef($Param{'brief'}); }\nif (defined($Param{'preview'}) or\n    defined($Param{'copy'}) or\n    defined($Param{'commit'}) or\n    defined($Param{'rollback'}) ) { $Param{'edit'}='on'; }\n\n\n# ----------------------\n# if no host is given\n# assume we mean 'localhost'\nif (!defined($Param{'host'}))      { $Param{'host'}='localhost'; }\n\n# ----------------------\n# perform some checks\n# -> eliminate 'broken pipe' error\npush(@MySQLaccess::Grant::Error,'not_found_mysql')     if !(-x $MYSQL);\npush(@MySQLaccess::Grant::Error,'not_found_diff')      if !(-x $DIFF);\npush(@MySQLaccess::Grant::Error,'not_found_mysqldump') if !(-x $MYSQLDUMP);\nif (@MySQLaccess::Grant::Error) {\n   MySQLaccess::Report::Print_Error_Messages() ;\n   exit 0;\n}\n\n#-----------------------\n# get info/help if necc.\n$print_usage=1;\nif ( defined($Param{'version'}) ) {\n   MySQLaccess::Report::Print_Version();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n#   exit 0;\n}\nif ( defined($Param{'relnotes'}) ) {\n   MySQLaccess::Report::Print_Relnotes();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n#   exit 0;\n}\nif ( defined($Param{'plan'}) ) {\n   MySQLaccess::Report::Print_Plans();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n#   exit 0;\n}\nif ( defined($Param{'howto'}) ) {\n   MySQLaccess::Report::Print_HowTo();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n#   exit 0;\n}\n\n# -----------------------------\n# generate a help-screen in CMD-mode\n# or a blanc form in CGI-mode \nif ( defined($Param{'help'}) \n     or !defined($Param{'user'}) \n     or !defined($Param{'host'})\n     or !defined($Param{'db'}) \n   ) {\n   push(@MySQLaccess::Grant::Error,'user_required') unless defined($Param{'user'});\n   push(@MySQLaccess::Grant::Error,'db_required') unless defined($Param{'db'});\n   push(@MySQLaccess::Grant::Error,'host_required') unless defined($Param{'host'});\n   MySQLaccess::Report::Print_Usage() if $print_usage;\n   exit 0;\n}\n\n\n# ----------------------------\n# get hostname and local-ip\n# for localhost\n$localhost = MySQLaccess::Host::LocalHost();\n$local_ip  = MySQLaccess::Host::Name2IP($localhost);\n$MySQLaccess::Host::localhost = MySQLaccess::Host::LocalHost();\n$MySQLaccess::Host::local_ip  = MySQLaccess::Host::Name2IP($localhost);\nMySQLaccess::Debug::Print(3, \"localhost name=$localhost, ip=$local_ip\");\n\n#-----------------------------------\n# version of MySQL-server to connect\n# to determine use of full where clause\n$MySQLaccess::Host::SERVER = $Param{'old_server'} ? '3.20' : $SERVER;\n\n#---------------------------------\n# create the config file for mysql and mysqldump\n# to avoid passing authentication info on the command line\n#\nMergeConfigFiles();\ndie \"Unsafe config file found: $unsafeConfig\\n\"  if $unsafeConfig;\nif (defined($Param{'superuser'})) {\n   $MYSQL_CNF{'mysql'}{'user'} = $Param{'superuser'};\n   $MYSQL_CNF{'mysqldump'}{'user'} = $Param{'superuser'};\n}\nif (defined($Param{'spassword'})) {\n   if ( $CMD && length($Param{'spassword'}) == 0 ) {\n      $Param{'spassword'} =\n           PromptPass(\"Password for MySQL superuser $Param{'superuser'}: \");\n   }\n   if ( length($Param{'spassword'}) > 0 ) {\n      $MYSQL_CNF{'mysql'}{'password'} = $Param{'spassword'};\n      $MYSQL_CNF{'mysqldump'}{'password'} = $Param{'spassword'};\n   }\n}\nWriteTempConfigFile();\n\n#---------------------------------\n# Inform user if he has not enough\n# privileges to read the access-db\nif ( $nerror=MySQLaccess::DB::OpenConnection() ) {\n    MySQLaccess::Report::Print_Error_Access($nerror);\n    exit 0;\n}\n\n# -----------------------\n# Read MySQL ACL-files\nif ($nerror=MySQLaccess::Grant::ReadTables()) {\n    MySQLaccess::Report::Print_Error_Access($nerror);\n    exit 0;\n};\nif ($Param{'edit'} and $nerror=MySQLaccess::Grant::ReadTables('tmp')) {\n    MySQLaccess::Report::Print_Error_Access($nerror);\n    exit 0;\n}\n\n#---------------------------------\n# reload temporay grant-tables \n# with data from original ones\nif ( defined($Param{'copy'}) ) {\n   $nerror=MySQLaccess::DB::LoadTmpTables();\n   if ($nerror) {\n      MySQLaccess::Report::Print_Error_Access($nerror);\n      exit 0;\n   }\n   my $msg = \"The grant-rules are copied from the grant-tables to\\n\"\n           . \"the temporary tables.\";\n   MySQLaccess::Report::Print_Message([$msg]);\n#   MySQLaccess::Report::Print_Footer();\n#   MySQLaccess::DB::CloseConnection();\n#   exit 0;\n}\n\n\n#---------------------------------\n# preview result of changes in the \n# grant-tables\nif ( defined($Param{'preview'}) ) {\n   $aref=MySQLaccess::Grant::Diff_Privileges();\n   MySQLaccess::Report::Print_Diff_ACL($aref);\n#   MySQLaccess::Report::Print_Footer();\n#   MySQLaccess::DB::CloseConnection();\n#   exit 0;\n}\n\n\n#---------------------------------\n# reload grant-tables \n# with data from temporary tables\nif ( defined($Param{'commit'}) ) {\n   if ($nerror = MySQLaccess::DB::CommitGrantTables()) {\n      MySQLaccess::Report::Print_Error_Access($nerror);\n      exit 0;\n   }\n   my $msg = \"The grant-rules have been copied from the temporary tables\\n\"\n           . \"to the grant-tables.\";\n   my $msg1= \"Don't forget to do an 'mysqladmin reload' before these\\n\"\n           . \"changes take effect.\";\n   my $msg2= \"A backup-version of your original grant-rules are saved in the\\n\"\n           . \"backup-tables, so you can always perform a 1-level rollback.\";\n   MySQLaccess::Report::Print_Message([$msg,$msg1,$msg2]);\n#   MySQLaccess::Report::Print_Footer();\n#   MySQLaccess::DB::CloseConnection();\n#   exit 0;\n}\n\n#---------------------------------\n# restore previous grant-rules\n# with data from backup tables\nif ( defined($Param{'rollback'}) ) {\n   if ($nerror = MySQLaccess::DB::RollbackGrantTables()) {\n      MySQLaccess::Report::Print_Error_Access($nerror);\n      exit 0;\n   }\n   my $msg = \"The old grant-rules have been copied back from the backup tables\\n\"\n           . \"to the grant-tables.\";\n   my $msg1= \"Don't forget to do an 'mysqladmin reload' before these\\n\"\n           . \"changes take effect.\";\n   MySQLaccess::Report::Print_Message([$msg,$msg1]);\n#   MySQLaccess::Report::Print_Footer();\n#   MySQLaccess::DB::CloseConnection();\n#   exit 0;\n}\n#----------------------------------\n# show edit-taskbar\nif ( defined($Param{'edit'})) {\n   if ($MySQLaccess::CGI ) {\n   MySQLaccess::Report::Print_Edit();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n   }\n   else {\n   MySQLaccess::Report::Print_Edit();\n   $print_usage=0;\n   MySQLaccess::Report::Print_Footer();\n   MySQLaccess::DB::CloseConnection();\n   exit 0;\n   }\n}\n\n\n# -----------------------------\n# Build list of users,dbs,hosts\n# to process...\n@all_dbs   = @{MySQLaccess::DB::Get_All_dbs($Param{'db'})};\n@all_users = @{MySQLaccess::DB::Get_All_users($Param{'user'})};\n@all_hosts = @{MySQLaccess::DB::Get_All_hosts($Param{'host'})};\n#if EDIT-mode\n#@all_dbs_tmp   = @{MySQLaccess::DB::Get_All_dbs($Param{'db'},'tmp')};\n#@all_users_tmp = @{MySQLaccess::DB::Get_All_users($Param{'user'},'tmp')};\n#@all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts($Param{'host'},'tmp')};\n\n# -----------------------------\n# Report access-rights for each\n# tuple (host,user,db)\n#$headers=0;\nmy %Access = ();\nforeach $host (@all_hosts) {\n  foreach $user (@all_users) {\n    foreach $db (@all_dbs) {\n      MySQLaccess::Grant::Initialize();\n      %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);\t\n      MySQLaccess::Report::Print_Access_rights($host,$user,$db,\\%Access);\n    }\n  }\n}\n\n# -----------------------------\n# End script\nMySQLaccess::Report::Print_Footer();\nMySQLaccess::DB::CloseConnection();\nexit 0;\n\n#############################################################\n#  FUNCTIONS  #\n###############\nsub GetMode {\n   my $cmd=0;\n   my $cgi=0;\n   if (defined($ENV{'HTTP_HOST'})) { $cmd=0; $cgi=1; }\n   else                            { $cmd=1; $cgi=0; } \n   return ($cmd,$cgi);\n}\n\n# ================================\n# sub PromptPass\n#  prompt tty for a password\n# ================================\nsub PromptPass {\n    my ($prompt) = @_;\n    my $password;\n    $ENV{PATH} = \"/bin:/usr/bin\";\n    $ENV{IFS} = \" \\t\\n\";\n    $ENV{SHELL} = \"/bin/sh\";\n    system \"stty -echo\";\n    print $prompt;\n    chomp($password = <STDIN>);\n    print \"\\n\";\n    system \"stty echo\";\n    $password;\n}\n\n# =================================\n# sub CheckUnsafeFile\n#  tell if a config file containing a password is unsafe\n# =================================\nsub CheckUnsafeFile {\n    my ($fname) = @_;\n    my ($dev, $ino, $mode, $nlink,\n        $uid, $gid, $rdev, $size,\n        $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);\n\n    if ( $uid != $< ) {   # unsafe if owned by other than current user\n        return 1;\n    }\n    if ( $mode & 066 ) {  # unsafe if accessible by other\n        return 1;\n    }\n    $fname =~ s#/[^/]+$##;\n    if ( (length $fname) > 0 ) {\n        return CheckUnsafeDir($fname);\n    }\n    return 0;\n}\n\n# =================================\n# sub CheckUnsafeDir\n#  tell if a directory is unsafe\n# =================================\nsub CheckUnsafeDir {\n    my ($fname) = @_;\n    my ($dev, $ino, $mode, $nlink,\n        $uid, $gid, $rdev, $size,\n        $atime, $mtime, $ctime, $blksize, $blocks) = stat($fname);\n\n    # not owned by me or root\n    if ( ($uid != $<) && ($uid != 0) ) {\n        return 1;\n    }\n    if ( $mode & 022 ) {  # unsafe if writable by other\n        return 1  unless $mode & 01000;  # but sticky bit ok\n    }\n    $fname =~ s#/[^/]+$##;\n    if ( (length $fname) > 0 ) {\n        return CheckUnsafeDir($fname);\n    }\n    return 0;\n}\n\n# =================================\n# sub MergeConfigFile\n#  merge data from .cnf file\n# =================================\nsub MergeConfigFile {\n    my ($fname) = @_;\n    my ($group, $item, $value);\n    if ( open CNF, $fname ) {\n         while (<CNF>) {\n             s/^\\s+//;\n             next if /^[#;]/;\n             if ( /\\[\\s*(\\w+)\\s*]/ ) {\n                 $group = $1;\n                 $group =~ tr/A-Z/a-z/;\n                 if ( !exists $MYSQL_CNF{$group} ) {\n                     undef $group;\n                 }\n             } elsif ( defined $group ) {\n                 ($item, $value) = /((?:\\w|-)+)\\s*=\\s*(\\S+)/;\n                 # don't unquote backslashes as we just write it back out\n                 if ( defined $item ) {\n                     if ( $item =~ /^password$/ ) {\n                         if ( CheckUnsafeFile($fname) ) {\n                             $unsafeConfig = $fname;\n                         }\n                     }\n                     if ( $group eq 'client' ) {\n                         $MYSQL_CNF{'mysql'}{$item} = $value;\n                         $MYSQL_CNF{'mysqldump'}{$item} = $value;\n                     } else {\n                         $MYSQL_CNF{$group}{$item} = $value;\n                     }\n                 }\n             }\n         }\n         close(CNF);\n    }\n}\n\n# =================================\n# sub MergeConfigFiles\n#  merge options from config files\n#  NOTE: really should do two separate merges for each\n#    client to exactly duplicate order of resulting argument lists\n# =================================\nsub MergeConfigFiles {\n    my ($name,$pass,$uid,$gid,$quota,$comment,$gcos,$dir,$shell) = getpwuid $<;\n    MergeConfigFile(\"@sysconfdir@/my.cnf\");\n    MergeConfigFile(\"/etc/my.cnf\");\n    MergeConfigFile(\"$dir/.my.cnf\");\n}\n\n# =================================\n# sub WriteTempConfigFile\n#  write \n# =================================\nsub WriteTempConfigFile {\n   sysopen CNFFILE, $MYSQL_CNF, O_RDWR|O_CREAT|O_EXCL, 0700\n      or die \"sysopen $MYSQL_CNF: $!\";\n   \n   # groups may be in any order, generic groups such as [client] assumed\n   # here to be empty\n   foreach $group (keys %MYSQL_CNF) {\n      print CNFFILE \"[$group]\\n\";\n      foreach $item (keys %{$MYSQL_CNF{$group}}) {\n         if ( defined $MYSQL_CNF{$group}{$item} ) {\n            print CNFFILE \"$item=$MYSQL_CNF{$group}{$item}\\n\";\n         } else {\n            print CNFFILE \"$item\\n\";\n         }\n      }\n      print CNFFILE \"\\n\";\n   }\n   close(CNFFILE);\n}\n\n######################################################################\npackage MySQLaccess::DB;\n###########\nBEGIN {\n    $DEBUG     = 2;\n    $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);\n    # Error-messages from the MySQL client\n    %ACCESS_ERR= ('Access_denied'       => 'Access denied' \n                 ,'Dbaccess_denied'     => 'Access to database denied'\n                 ,'Unrecognized_option' => 'unrecognized option' \n                 ,'Unknown_table'       => \"Can't find file:\"\n                 ,'unknown_error'       => '^ERROR:'\n                 );\n}\n# ######################################\n#  Connecting to the MYSQL DB\n# ======================================\n# sub OpenConnection\n#  Open an connection to the mysql-db\n#  questions to MYSQL_Q\n#  answers from MYSQL_A\n# ======================================\nsub OpenConnection {\n    my $pid;\n    MySQLaccess::Debug::Print(2,\"OpenConnection:\");\n\n    # check path to mysql-client executable\n    if (! -f $MySQLaccess::MYSQL) {\n       if ($MySQLaccess::CMD) { die \"Could not find MySQL-client '$MySQLaccess::MYSQL'\"; }\n       if ($MySQLaccess::CGI) { \n          print \"<center>\\n<font color=Red>\\n\";\n          print \"ERROR: Could not find MySQL-client '$MySQLaccess::MYSQL'\";\n          print \"</center>\\n</font>\\n\";\n          exit 0;\n       }\n    }\n\n    # path to mysql executable\n    my $connect = \"$MySQLaccess::MYSQL --defaults-file=$MySQLaccess::MYSQL_CNF\";\n    $connect .= \" $MySQLaccess::MYSQL_OPT\";\n    # superuser, spassword transmitted via defaults-file\n    if (defined($MySQLaccess::Param{'rhost'}))     { $connect .= \" --host=$MySQLaccess::Param{'rhost'}\"; }\n    # other options??\n\n    # grant-database\n    $connect .= \" $MySQLaccess::ACCESS_DB\";\n\n    # open connection (not using /bin/sh -c)\n    MySQLaccess::Debug::Print(2,\"Connecting to: $connect\");\n    $pid=IPC::Open3::open3(\\*MYSQL_Q,\\*MYSQL_A,\"\",split /\\s+/,$connect);\n    MySQLaccess::Debug::Print(2,\"PID of open pipe: $pid\");\n    \n    # check connection \n    print MYSQL_Q \"select 'ok';\\n\";\n    $answer = <MYSQL_A>; #answer from mysql\n    MySQLaccess::Debug::Print(2,\"Answer: $answer\\n\");\n    foreach $nerror (sort(keys(%ACCESS_ERR))) {\n      MySQLaccess::Debug::Print(3,\"check answer for error $ACCESS_ERR{$nerror}\");\n      if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { \n         MySQLaccess::Debug::Print(2,\"Answer contain error [$nerror]\");\n         return $nerror; \n      }\n    }\n\nif (0) {\n    # check server-version \n    print MYSQL_Q \"select 'ok';\\n\";\n    $answer = <MYSQL_A>; #answer from mysql\n    MySQLaccess::Debug::Print(2,\"Answer: $answer\\n\");\n    foreach $nerror (sort(keys(%ACCESS_ERR))) {\n      MySQLaccess::Debug::Print(3,\"check answer for error $ACCESS_ERR{$nerror}\");\n      if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { \n         MySQLaccess::Debug::Print(2,\"Answer contain error [$nerror]\");\n         return $nerror; \n      }\n    }\n}\n\n    my $skip=<MYSQL_A>; \n    return 0; \n}\n\n# ======================================\n# sub CloseConnection\n#  Close the connection to the mysql-db\n# ======================================\nsub CloseConnection {\n    close MYSQL_Q;\n    close MYSQL_A;\n}\n\n# ===========================================================\n# sub CreateTable($table)\n#  Create temporary/backup table\n# ===========================================================\nsub CreateTable {\n    my $pid;\n    my ($table,$force) = @_;\n    my %tables = ( $MySQLaccess::ACCESS_U_TMP => $MySQLaccess::ACCESS_U,\n                   $MySQLaccess::ACCESS_H_TMP => $MySQLaccess::ACCESS_H,\n                   $MySQLaccess::ACCESS_D_TMP => $MySQLaccess::ACCESS_D,\n                   $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,\n                   $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,\n                   $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,\n                   $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,\n                   $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,\n                   $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,\n                 ); \n    my $tbl;\n    my $query=\"\";\n    my $delim;\n    my $skip;\n    my $create;\n    my @known_tables=();\n\n#    print STDERR \"CreateTable($table)\\n\";\n    MySQLaccess::Debug::Print(1,\"CreateTable($table):\");\n\n    ## error-handling\n    return 'Unknown_table' unless defined($tables{$table});\n\n    ## build list of known/existing tables;\n    ## if 'force' existing table is dropped first\n    if (defined($force) and $force) {\n       @known_tables = Show_Tables();\n       if (grep(/^$table$/,@known_tables)) {\n       $query = \"DROP TABLE $table;\";\n       }\n    }\n\n    ## path to mysqldump executable\n    my $connect = $MySQLaccess::MYSQLDUMP;\n    $connect .= \" --defaults-file=$MySQLaccess::MYSQL_CNF --no-data\";\n    # superuser, spassword transmitted via defaults-file\n    if (defined($MySQLaccess::Param{'rhost'}))     { $connect .= \" --host=$MySQLaccess::Param{'rhost'}\"; }\n    $connect .= \" $MySQLaccess::ACCESS_DB\";\n    $connect .= \" $tables{$table}\";\n\n\n    ## get creation-data for original table\n    $create = '';\n    my $mysqldump = $connect;\n    $mysqldump =~ s/ \\$TABLE / $tbl /;\n\n    # open connection (not using /bin/sh -c)\n    MySQLaccess::Debug::Print(2,\"Connecting to: $connect\");\n    $pid=IPC::Open3::open3(\\*DONTCARE,\\*CREATE,\"\",split /\\s+/,$mysqldump);\n    MySQLaccess::Debug::Print(2,\"PID of open pipe: $pid\");\n    #open(CREATE,\"$mysqldump\");\n    @create = <CREATE>;\n    $create = \"@create\";\n    foreach $nerror (sort(keys(%ACCESS_ERR))) {\n       MySQLaccess::Debug::Print(3,\"check answer for error $ACCESS_ERR{$nerror}\");\n       if (grep(/$ACCESS_ERR{$nerror}/i,$create)) { \n          MySQLaccess::Debug::Print(2,\"Answer contain error [$nerror]\");\n          return $nerror; \n       }\n    }\n    close(CREATE);\n    close(DONTCARE);\n\n    ## manipulate result for creation-data for temporary table\n    $create =~ s/CREATE TABLE $tables{$table} \\(/CREATE TABLE $table \\(/;\n\n    ## recreate temporary table\n    $query .= \"$create\\n\";\n    $query .= \"select 'ok';\";\n\n    ## execute query\n    print MYSQL_Q \"$query\\n\";\n#    print STDERR $query;\n\n    $answer = <MYSQL_A>; #answer from mysql\n#    print STDERR \"A>\",$answer;\n    MySQLaccess::Debug::Print(2,\"Answer: $answer\\n\");\n    foreach $nerror (sort(keys(%ACCESS_ERR))) {\n#       print STDERR \"->$nerror?\";\n       MySQLaccess::Debug::Print(3,\"check answer for error $ACCESS_ERR{$nerror}\");\n       if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { \n#          print STDERR \"Yes!\";\n          MySQLaccess::Debug::Print(2,\"Answer contain error [$nerror]\");\n          return $nerror; \n       }\n    }\n\n    $delim = <MYSQL_A>; # read header\n    if ($delim ne \"ok\\n\") {\n       while (($line=<MYSQL_A>) ne \"ok\\n\")\n       { MySQLaccess::Debug::Print(3,\" A> $line\"); }\n        $skip = <MYSQL_A>; # skip result 'ok'\n    }\n#    print STDERR \"CreateTable done\\n\";\n    return 0;\n}\n\n\n# ===========================================================\n# sub CopyTable()\n#  Copy the structure and the data of a table to another table\n# ===========================================================\nsub CopyTable {\n    my ($from,$to,$force) = @_;\n    my @known_tables  = Show_Tables();    \n    my $query = \"\";\n    my $nerror= 0;\n    my $skip;\n\n#    print STDERR \"CopyTable($from,$to)\\n\";\n    MySQLaccess::Debug::Print(1,\"MySQLaccess::DB::CopyTable($from,$to)\");\n\n    ## error-handling\n    if (!grep(/^$from$/,@known_tables)) { return 'Unknown_table'; }\n\n    ## copy structure \n    ## if forced\n    if (defined($force) and $force) {\n       return $nerror if ($nerror=CreateTable($to,$force)); \n#       print STDERR \"Structure copied\\n\";\n    }\n\n    ## copy data\n    $query .= \"DELETE FROM $to;\";\n    $query .= \"INSERT INTO $to SELECT * FROM $from;\";\n    $query .= \"SELECT 'ok';\\n\";\n    MySQLaccess::Debug::Print(2,\"Query: $query\");\n       \n    ## execute query\n    print MYSQL_Q \"$query\\n\";\n#    print STDERR $query;\n\n    ## check for errors...\n    my $answer = <MYSQL_A>; #answer from mysql\n#    print STDERR $answer;\n    MySQLaccess::Debug::Print(2,\"Answer: $answer\\n\");\n    foreach $nerror (sort(keys(%ACCESS_ERR))) {\n       MySQLaccess::Debug::Print(3,\"check answer for error $ACCESS_ERR{$nerror}\");\n       if (grep(/$ACCESS_ERR{$nerror}/i,$answer)) { \n          MySQLaccess::Debug::Print(2,\"Answer contain error [$nerror]\");\n          return $nerror; \n       }\n    }\n\n    my $delim = <MYSQL_A>; # read header\n#    print STDERR $delim;\n    if ($delim ne \"ok\\n\") {\n       while (($line=<MYSQL_A>) ne \"ok\\n\")\n       { MySQLaccess::Debug::Print(3,\" A> $line\"); }\n       $skip = <MYSQL_A>; # skip result 'ok'\n    }\n\n    return 0;\n}\n\n# ===========================================================\n# sub LoadTmpTables()\n#  (Re)load temporary tables with entries of ACL-tables\n# ===========================================================\nsub LoadTmpTables {\n    my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,\n                   $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,\n                   $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,\n                 ); \n    my $tbl;\n    my $nerror;\n    \n#    print STDERR \"LoadTmpTables:\\n\";\n    MySQLaccess::Debug::Print(1,\"LoadTmpTables():\");\n    foreach $tbl (keys(%tables)) {\n#       print STDERR \"$tbl -> $tables{$tbl}\\n\";\n       MySQLaccess::Debug::Print(2,\"Loading table $tbl -> $tables{$tbl}.\");\n       return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));\n    }\n    return 0;\n}\n\n# ===========================================================\n# sub BackupGrantTables()\n#  Make a backup of the original grant-tables\n# ===========================================================\nsub BackupGrantTables {\n    my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_BCK,\n                   $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_BCK,\n                   $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_BCK,\n                 ); \n    my $tbl;\n    my $nerror;\n    \n#    print STDERR \"BackupGrantTables:\\n\";\n    MySQLaccess::Debug::Print(1,\"BackupGrantTables():\");\n    foreach $tbl (keys(%tables)) {\n#       print STDERR \"$tbl -> $tables{$tbl}\\n\";\n       MySQLaccess::Debug::Print(2,\"Backup table $tbl -> $tables{$tbl}.\");\n       return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));\n    }\n    return 0;\n}\n\n# ===========================================================\n# sub RollbackGrantTables()\n#  Rollback the backup of the grant-tables\n# ===========================================================\nsub RollbackGrantTables {\n    my %tables = ( $MySQLaccess::ACCESS_U_BCK => $MySQLaccess::ACCESS_U,\n                   $MySQLaccess::ACCESS_H_BCK => $MySQLaccess::ACCESS_H,\n                   $MySQLaccess::ACCESS_D_BCK => $MySQLaccess::ACCESS_D,\n                 ); \n    my $tbl;\n    my $nerror;\n    \n#    print STDERR \"RollbackGrantTables:\\n\";\n    MySQLaccess::Debug::Print(1,\"RollbackGrantTables():\");\n    foreach $tbl (keys(%tables)) {\n#       print STDERR \"$tbl -> $tables{$tbl}\\n\";\n       MySQLaccess::Debug::Print(2,\"Rollback table $tbl -> $tables{$tbl}.\");\n       return $nerror if ($nerror=CopyTable($tbl,$tables{$tbl},'force'));\n    }\n    return 0;\n}\n\n\n# ===========================================================\n# sub CommitGrantTables()\n#  Copy grant-rules from temporary tables to the ACL-tables\n# ===========================================================\nsub CommitGrantTables {\n    my %tables = ( $MySQLaccess::ACCESS_U => $MySQLaccess::ACCESS_U_TMP,\n                   $MySQLaccess::ACCESS_H => $MySQLaccess::ACCESS_H_TMP,\n                   $MySQLaccess::ACCESS_D => $MySQLaccess::ACCESS_D_TMP,\n                 ); \n    my $tbl;\n    my $query;\n    my $delim;\n    my $skip;\n    my $create;\n\n    print STDERR \"CommitGrantTables()\\n\";\n    MySQLaccess::Debug::Print(1,\"CommitGrantTables():\");\n    \n    ## Make backup of original grant-tables\n    MySQLaccess::Debug::Print(2,\"Making backup of original grant-tables...\");\n    BackupGrantTables();\n\n    ## Copy data from temporay tables to grant-tables\n    foreach $tbl (keys(%tables)) {\n       print STDERR \"$tbl -> $tables{$tbl}\\n\";\n       MySQLaccess::Debug::Print(2,\"Loading data $tables{$tbl} -> $tbl.\");\n       return $nerror if ($nerror=CopyTable($tables{$tbl},$tbl));\n    }\n    return 0;\n}\n\n\n# ===========================================================\n# sub Show_Fields($table): \n#  return (a reference to) a hash which holds the names\n#  of all relevant grant-fields, with their index in the record,\n#  and (a reference to) an array which holds the fieldnames.\n# ===========================================================\nsub Show_Fields {\n    my ($table) = @_;\n    my %skip = ('host' => [0,1]\n               ,'user' => [0,1,2]\n               ,'db'   => [0,1,2]\n               );\n    my %Struct = ();\n    my @Struct = ();\n    my $query = \"show fields from $table;select 'ok';\\n\";\n    my $i=0;\n    my $line;\n\n#print STDERR $query;\n    MySQLaccess::Debug::Print(1,\"Show_Fields($table):\");\n    MySQLaccess::Debug::Print(2,\"SQL: $query\");\n\n    print MYSQL_Q \"$query\";\n    my $skip = <MYSQL_A>;  #skip header\n    while (($line=<MYSQL_A>) ne \"ok\\n\")\n    {\n#print STDERR \">\",$line;\n\tchop($line);\n\tMySQLaccess::Debug::Print(2,\" $table>: $line\");\n\tmy ($field,$type,$null,$key,$default,$extra) = split(' ',$line);\n        $field = ucfirst($field); \n\tMySQLaccess::Debug::Print(3, \" <split: $field - $type - $null - $key - $default - $extra\");\n\tif (! grep(/$i/,@{$skip{$table}}) ){\n\t   $Struct{$field} = $i; #hash\n\t   push(@Struct,$field); #array\n\t   MySQLaccess::Debug::Print(3,\" ==> added column[$i]: $field ($Struct{$field})\");\n\t} \n        else {\n           MySQLaccess::Debug::Print(3,\" ==> skipped column[$i], value=[$field]\");\n        }\n\t$i++;\n    }\n\n    $skip=<MYSQL_A>;  # Get ok row (found already ok header)\n\n    MySQLaccess::Debug::Print(2, \"Array:\");\n    foreach $field (@Struct) { MySQLaccess::Debug::Print(2,\"+ $field\"); }\n    MySQLaccess::Debug::Print(2,\"Hash:\");\n    foreach $field (keys(%Struct)) { MySQLaccess::Debug::Print(2,\"+ $field -> $Struct{$field}\"); }\n\n    return  (\\%Struct,\\@Struct); \n}\n\n# ===========================================================\n# sub Show_Tables(): \n#  return (a reference to) an array which holds all \n#  known tables.\n# ===========================================================\nsub Show_Tables {\n    my @Tables = ();\n    my $query = \"show tables;select 'ok';\\n\";\n    my $i=0;\n    my $line;\n\n    MySQLaccess::Debug::Print(1,\"Show_Tables():\");\n    MySQLaccess::Debug::Print(2,\"SQL: $query\");\n\n    print MYSQL_Q \"$query\";\n    my $skip = <MYSQL_A>;  #skip header\n    while (($line=<MYSQL_A>) ne \"ok\\n\")\n    {\n\tchop($line);\n\tpush(@Tables,$line); #array\n\tMySQLaccess::Debug::Print(3,\" ==> added table: $line\");\n    }\n\n    $skip=<MYSQL_A>;  # Get ok row (found already ok header)\n\n    MySQLaccess::Debug::Print(2, \"Array:\");\n    foreach $tbl (@Tables) { MySQLaccess::Debug::Print(2,\"+ $tbl\"); }\n\n    return @Tables; \n}\n\n# ======================================\n# sub Validate_Password($passwd,$host,$user,$encpw)\n#  Validate the given password \n#  for user '$user' \n#  connecting from host '$host'\n# ======================================\nsub Validate_Password {\n    my ($password,$host,$user,$encpw) = @_;\n    my $valid=0;\n\n    MySQLaccess::Debug::Print(1,\"Validate_Password($password,$host,$user,$encpw)\");\n    my $sql = \"select host,user,password from user having \"\n             .\"host='$host' and user='$user' and password='$encpw' \"\n             .\"and password=PASSWORD('$password');\\n\";\n    $sql .= \"select 'ok';\\n\";\n    MySQLaccess::Debug::Print(2,\"SQL = $sql\");\n    print MYSQL_Q \"$sql\";\n    \n    # if password is valid, at least 1 row returns before we read 'ok'\n    while ( ($line=<MYSQL_A>) ne \"ok\\n\") {\n      MySQLaccess::Debug::Print(2,\" A> $line\");\n      $valid = defined($line); \n    }\n    my $skip = <MYSQL_A>; # read 'ok'\n\n    return $valid;\n}\n\n\n# ==========================================================\n# sub Sort_fields: (rewritten by psmith)\n#  Build the query for an ordered list of entries\n# ==========================================================\nsub Sort_fields {\n  my ($start, $end, $sofar, $this, @rest) = (@_);\n  my @where = (\"((FIELD not like '\\\\%') AND (FIELD <> ''))\",\n               \"((FIELD like '%\\\\%%') OR (FIELD like '%\\\\_%'))\",\n               \"(FIELD = '')\");\n  my $res = '';\n\n  $this or return (\"$start $sofar $end\");\n\n  $sofar .= ' AND ' if $sofar;\n\n  foreach $w (@where) {\n    my $f = $w;\n    $f =~ s/FIELD/$this/g;\n\n    $res .= Sort_fields($start, $end, \"$sofar$f\", @rest);\n  }\n\n  return ($res);\n}\n\n# ===========================================================\n# sub Sort_table: (rewritten by psmith)\n#  return all entries in the given table,\n#  in an ordered fashion\n# ===========================================================\nsub Sort_table {\n    my ($tbl, @order) = @_;\n    my @res=();\n\n    # as long as there's no full where clause (Distrib 3.20)...\n    # use having :-(\n    # NOTE: this clause WILL NOT work on 3.21, because of the\n    # order of 'ORDER BY' and 'HAVING'\n    my $start = \"SELECT *,UCASE(host) as ucase_host FROM $tbl \";\n    $start   .= 'ORDER BY ' . join(',', @order) .\" HAVING \";\n    my $end   = \";\\n\";\n\n    # server version 3.21 has a full where clause :-)\n    if ($MySQLaccess::Host::SERVER >= '3.21') {\n    # print \"+++USING FULL WHERE CLAUSE+++\\n\";\n       $start = \"SELECT *,UCASE(host) as ucase_host FROM $tbl WHERE \";\n       $end = ' ORDER BY ' . join(',', @order) . \";\\n\";\n    }\n\n    MySQLaccess::Debug::Print(1,\"Sort_table():\");\n    MySQLaccess::Debug::Print(2,\"Sorting table $tbl by `@order'\");\n\n    my $tmp;\n    foreach $tmp (@order)\n    {\n      $tmp=\"UCASE(host)\" if ($tmp eq \"ucase_host\");\n    }\n    my $query  = Sort_fields($start, $end, '', @order);\n    $query    .= \"select 'ok';\\n\";\n    MySQLaccess::Debug::Print(2,\"Query: $query\");\n\n    print MYSQL_Q \"$query\\n\";\n\n    my $delim = <MYSQL_A>; # read header\n    MySQLaccess::Debug::Print(3,\" A> $delim\");\n    if ($delim ne \"ok\\n\") {\n       if ($delim =~ /^ERROR/) {\n       push(@MySQLaccess::Grant::Error,'use_old_server');\n       MySQLaccess::Report::Print_Error_Messages() ;\n       exit 1;\n       }\n       while (($line=<MYSQL_A>) ne \"ok\\n\")\n       {\n           MySQLaccess::Debug::Print(3,\" A> $line\");\n           push(@res,$line);\n       }\n    }\n    my $skip = <MYSQL_A>; # skip result 'ok'\n\n    # remove columnheaders from output\n    @res = grep(!/^\\Q$delim\\E$/, @res);\n    # remove trailing \\n from each returned record\n    chomp(@res); \n    # each record has 1 field to much : ucase_host\n    @res = grep { /(.*)\\t.*$/; $_ = $1; } @res;\n\n    MySQLaccess::Debug::Print(2,\"Result of sorted table $tbl:\");\n    foreach $line (@res) { MySQLaccess::Debug::Print(2,\" >>$line\"); }\n    return @res;\n}\n\n# ===========================================================\n# sub Get_All_db(template): \n#  return all db the grant-tables are working on,\n#  which conform to the template\n# ===========================================================\nsub Get_All_dbs {\n   my ($template,$tmp) = @_;\n   my @db=();\n   my $aref;\n\n   # working with  temporary tables or production tables\n   if (defined($tmp) and $tmp) {\n      $aref = \\@MySQLaccess::Grant::sorted_db_tmp_table ;\n   }\n   else {\n      $aref = \\@MySQLaccess::Grant::sorted_db_table;\n   }\n\n   MySQLaccess::Debug::Print(1,\" template=[$template]\");\n\n   # get all db for which access-rights can be calculated,\n   # which conform to the template.\n   # !! these db's don't have to exist yet, so it's not\n   #    enough to look which db already exist on the system\n   $reg_expr = $template;\n   if ($template =~ /[\\*\\?]/) {\n      $reg_expr =~ tr/*?/%_/;\n      #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);\n   }\n   $reg_expr = MySQLaccess::Wildcards::SQL2Reg(\"$reg_expr\");\n\n   if ( ! ($template =~ /[\\*\\?%_]/) ) {\n      push(@db,$template);\n      return \\@db;\n   }\n\n   MySQLaccess::Debug::Print(2,\"#Reading db-table...\");\n   foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_db_table) {\n    my @record=split(/\\t/,$record);\n    my $db = $record[1];\n    MySQLaccess::Debug::Print(2,\"> $db \");\n    if ( (!grep(/$db/i,@db)) and ($db =~/$reg_expr/i) ) {\n       push(@db,$db);\n       MySQLaccess::Debug::Print(2,\"added\");\n    } \n    else {\n       MySQLaccess::Debug::Print(2,\"skipped\");\n    }\n   }\n   # if no rule is found for a certain db in the db-table,\n   # the rights of the user are used, so we should inform\n   # the user for\n   if (!grep(/^%$/,@db)) { push(@db,\"$MySQLaccess::NEW_DB\"); }\n   return \\@db;\n}\n\n# ===========================================================\n# sub Get_All_users(template): \n#  return all users the grant-tables are working on,\n#  which conform to the template\n# ===========================================================\nsub Get_All_users {\n   ($template,$tmp) = @_; # nog verder uitwerken!!!\n   my @user=();\n   my $aref;\n\n   # working with  temporary tables or production tables\n   if (defined($tmp) and $tmp) {\n      $aref = \\@MySQLaccess::Grant::sorted_user_tmp_table ;\n   }\n   else {\n      $aref = \\@MySQLaccess::Grant::sorted_user_table;\n   }\n\n   MySQLaccess::Debug::Print(1,\"Debug Get_All_users:\");\n   # get all db for which access-rights can be calculated.\n   # !! these db's don't have to exist yet, so it's not\n   #    enough to look which db already exist on the system\n   $reg_expr = $template;\n   if ($template =~ /[\\*\\?]/) {\n      $reg_expr =~ tr/*?/%_/;\n      #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);\n   }\n   $reg_expr = MySQLaccess::Wildcards::SQL2Reg(\"$reg_expr\");\n\n   if ( ! ($template =~ /[\\*\\?%_]/) ) {\n      push(@user,$template);\n      return \\@user;\n   }\n\n   MySQLaccess::Debug::Print(2,\"#Reading user-table...\");\n   foreach $record (@{$aref}) { #MySQLaccess::Grant::sorted_user_table) {\n    my @record=split(/\\t/,$record);\n    my $user = $record[1];\n    MySQLaccess::Debug::Print(2,\"> $user \");\n    if ( (!grep(/$user/,@user)) and ($user=~/$reg_expr/)) {\n       push(@user,$user);\n       MySQLaccess::Debug::Print(2, \"added\");\n    } \n    else {\n       MySQLaccess::Debug::Print(2, \"skipped\");\n    }\n   }\n   # Any user means also:\n   # - the 'empty' user, ie without supplying a username\n   # - any user still to be defined/created\n   #push(@user,'');               #without_suplying_a_username\n   push(@user,\"$MySQLaccess::NEW_USER\");\n   #push(@Warnings,'minimum_priv');\n   return \\@user;\n}\n\n# ===========================================================\n# sub Get_All_hosts(template): \n#  return all hosts the grant-tables are working on,\n#  which conform to the template\n# ===========================================================\nsub Get_All_hosts {\n   my ($template,$tmp) = @_;\n   my @host=();\n   my $aref;\n   my $aref1;\n\n   # working with  temporary tables or production tables\n   if (defined($tmp) and $tmp) {\n      $aref = \\@MySQLaccess::Grant::sorted_host_tmp_table ;\n      $aref1= \\@MySQLaccess::Grant::sorted_db_tmp_table ;\n   }\n   else {\n      $aref = \\@MySQLaccess::Grant::sorted_host_table;\n      $aref1= \\@MySQLaccess::Grant::sorted_db_table ;\n   }\n\n   MySQLaccess::Debug::Print(1, \"Debug Get_All_hosts:\");\n   # get all db for which access-rights can be calculated.\n   # !! these db's don't have to exist yet, so it's not\n   #    enough to look which db already exist on the system\n   $reg_expr = $template;\n   if ($template =~ /[\\*\\?]/) {\n      $reg_expr =~ tr/*?/%_/;\n      #$reg_expr = MySQLaccess::Wildcards::Wild2Reg($template);\n   }\n   $reg_expr = MySQLaccess::Wildcards::SQL2Reg(\"$reg_expr\");\n\n   if ( ! ($template =~ /[\\*\\?%_]/) ) {\n      push(@host,$template);\n      return \\@host;\n   }\n\n   MySQLaccess::Debug::Print(1, \"#Reading db-table...\");\n   foreach $record (@{$aref1}) { #MySQLaccess::Grant::sorted_db_table) {\n    my @record=split(/\\t/,$record);\n    my $host = $record[0];\n    MySQLaccess::Debug::Print(2, \"> $host \");\n    if (! grep(/$host/i,@host)) {\n       push(@host,$host);\n       MySQLaccess::Debug::Print(2, \"added\");\n    } \n    else {\n       MySQLaccess::Debug::Print(2, \"skipped\");\n    }\n   }\n   MySQLaccess::Debug::Print(1, \"#Reading host-table...\");\n   foreach $record (@{$aref}) {\n    my @record=split(/\\t/,$record);\n    my $host = $record[0];\n    MySQLaccess::Debug::Print(2, \"> $host \");\n    if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {\n       push(@host,$host);\n       MySQLaccess::Debug::Print(2, \"added\");\n    } \n    else {\n       MySQLaccess::Debug::Print(2, \"skipped\");\n    }\n   }\n   # DOUBT:\n   #print \"#Reading user-table...\\n\" if ($DEBUG>1);\n   #foreach $record (@MySQLaccess::Grant::sorted_user_table) {\n   # my @record=split(/\\t/,$record);\n   # my $host = $record[0];\n   # print \"> $host \" if ($DEBUG>2);\n   # if ( (!grep(/$host/,@host)) and ($host=~/$reg_expr/)) {\n   #    push(@host,$host);\n   #    print \"added\\n\" if ($DEBUG>2);\n   # } \n   # else {\n   #    print \"skipped\\n\" if ($DEBUG>2);\n   # }\n   #}\n   # Any host also means:\n   # - any host still to be defined/created\n   #push(@host,\"any_other_host\");\n\n   @host = sort(@host);\n   return \\@host;\n}\n\n\n##########################################################################\npackage MySQLaccess::Grant;\n##############\nBEGIN {\n    $DEBUG     = 0;\n    $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);\n}\n\n\n\n# ===========================================================\n# sub Diff_Privileges()\n#  Calculate diff between temporary and original grant-tables\n# ===========================================================\nsub Diff_Privileges {\n   my @before=();\n   my @after =();\n   my @diffs =();\n\n   # -----------------------------\n   # Build list of users,dbs,hosts\n   # to process...\n   my @all_dbs   = @{MySQLaccess::DB::Get_All_dbs('*')};\n   my @all_users = @{MySQLaccess::DB::Get_All_users('*')};\n   my @all_hosts = @{MySQLaccess::DB::Get_All_hosts('*')};\n   #if EDIT-mode\n   my @all_dbs_tmp   = @{MySQLaccess::DB::Get_All_dbs('*','tmp')};\n   my @all_users_tmp = @{MySQLaccess::DB::Get_All_users('*','tmp')};\n   my @all_hosts_tmp = @{MySQLaccess::DB::Get_All_hosts('*','tmp')};\n\n\n   my %Access;\n   # ------------------------------------\n   # Build list of priv. for grant-tables\n   foreach $host (@all_hosts) {\n     foreach $user (@all_users) {\n       foreach $db (@all_dbs) {\n         MySQLaccess::Grant::Initialize();\n         %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db);\t\n         push(@before,MySQLaccess::Report::Raw_Report($host,$user,$db,\\%Access));\n       }\n     }\n   }\n\n   # ----------------------------------\n   # Build list of priv. for tmp-tables\n   foreach $host (@all_hosts_tmp) {\n     foreach $user (@all_users_tmp) {\n       foreach $db (@all_dbs_tmp) {\n         MySQLaccess::Grant::Initialize('tmp');\n         %Access = MySQLaccess::Grant::Get_Access_Rights($host,$user,$db,'tmp');\t\n         push(@after,MySQLaccess::Report::Raw_Report($host,$user,$db,\\%Access));\n       }\n     }\n   }\n\n   # ----------------------------------\n   # Write results to temp-file to make\n   # DIFF\n   @before = sort(@before);\n   @after  = sort(@after);\n\n   ($hb, $before) = tempfile(\"$MySQLaccess::script.XXXXXX\") or\n    push(@MySQLaccess::Report::Errors,\"Can't create temporary file: $!\");\n   ($ha, $after)  = tempfile(\"$MySQLaccess::script.XXXXXX\") or\n    push(@MySQLaccess::Report::Errors,\"Can't create temporary file: $!\");\n\n   print $hb join(\"\\n\",@before);\n   print $ha join(\"\\n\",@after);\n   close $hb;\n   close $ha;\n\n   # ----------------------------------\n   # compute difference\n   my $cmd=\"$MySQLaccess::DIFF $before $after |\";\n   open(DIFF,\"$cmd\");\n   @diffs = <DIFF>;\n   @diffs = grep(/[<>]/,@diffs);\n   chomp(@diffs);\n   close(DIFF);\n\n   # ----------------------------------\n   # cleanup temp. files\n   unlink($before);\n   unlink($after);\n\n   return \\@diffs;\n}\n\n# ===========================================================\n# sub Initialize()\n#\n# ===========================================================\nsub Initialize {\n    %MySQLaccess::Grant::Access       = %{Default_Access_Rights()};\n    @MySQLaccess::Grant::Errors       = ();\n    @MySQLaccess::Grant::Warnings     = ();\n    @MySQLaccess::Grant::Notes        = ();\n    # -----\n    # rules\n    $MySQLaccess::Grant::Rules{'user'} = 'no_rule_found';\n    $MySQLaccess::Grant::Rules{'db'}   = 'no_rule_found';\n    $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';\n    $MySQLaccess::Grant::full_access   = 1;\n\n    $MySQLaccess::Grant::process_host_table = 0;\n    return 1;\n}\n\n# ===========================================================\n# sub ReadTables()\n#  \n# ===========================================================\nsub ReadTables {\n    my ($tmp) = @_;\n    my ($HOST,$DB,$USER);\n    my @tables;\n\n    # build list of available tables\n    @tables = MySQLaccess::DB::Show_Tables();\n\n    # reading production grant-tables or temporary tables?\n    $tmp = (defined($tmp) and $tmp) ? 1 : 0;\n    if ($tmp) { #reading temporary tables\n       $HOST=$MySQLaccess::ACCESS_H_TMP;\n       $DB  =$MySQLaccess::ACCESS_D_TMP;\n       $USER=$MySQLaccess::ACCESS_U_TMP;\n\n       # ----------------------------\n       # do tables exist?\n       if (!grep(/$HOST/,@tables)) { MySQLaccess::DB::CreateTable($HOST); }\n       if (!grep(/$USER/,@tables)) { MySQLaccess::DB::CreateTable($USER); }\n       if (!grep(/$DB/,@tables))   { MySQLaccess::DB::CreateTable($DB); }\n\n       MySQLaccess::Debug::Print(1,\"Finding fields in tmp-ACL files:\");\n       # -----------------------------\n       # Get record-layout \n       my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);\n       my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);\n       my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);\n       %MySQLaccess::Grant::H_tmp = %{$h1}; @MySQLaccess::Grant::H_tmp = @{$h2};\n       %MySQLaccess::Grant::D_tmp = %{$d1}; @MySQLaccess::Grant::D_tmp = @{$d2};\n       %MySQLaccess::Grant::U_tmp = %{$u1}; @MySQLaccess::Grant::U_tmp = @{$u2};\n\n#       @MySQLaccess::Grant::Privileges_tmp=@{Make_Privlist()};\n#\n       MySQLaccess::Debug::Print(1, \"Reading sorted temp-tables:\");\n       @MySQLaccess::Grant::sorted_db_tmp_table  = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');\n       @MySQLaccess::Grant::sorted_host_tmp_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');\n       @MySQLaccess::Grant::sorted_user_tmp_table= defined($MySQLaccess::Param{'password'}) ?\n                           MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):\n                           MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');\n    }\n    else {      #reading production grant-tables\n       $HOST=$MySQLaccess::ACCESS_H;\n       $DB  =$MySQLaccess::ACCESS_D;\n       $USER=$MySQLaccess::ACCESS_U;\n\n       MySQLaccess::Debug::Print(1,\"Finding fields in ACL files:\");\n       # -----------------------------\n       # Get record-layout \n       my ($h1,$h2) = MySQLaccess::DB::Show_Fields($HOST);\n       my ($d1,$d2) = MySQLaccess::DB::Show_Fields($DB);\n       my ($u1,$u2) = MySQLaccess::DB::Show_Fields($USER);\n       %MySQLaccess::Grant::H = %{$h1}; @MySQLaccess::Grant::H = @{$h2};\n       %MySQLaccess::Grant::D = %{$d1}; @MySQLaccess::Grant::D = @{$d2};\n       %MySQLaccess::Grant::U = %{$u1}; @MySQLaccess::Grant::U = @{$u2};\n\n       @MySQLaccess::Grant::Privileges=@{Make_Privlist()};\n\n       MySQLaccess::Debug::Print(1, \"Reading sorted tables:\");\n       @MySQLaccess::Grant::sorted_db_table  = MySQLaccess::DB::Sort_table($DB, 'ucase_host', 'user', 'db');\n       @MySQLaccess::Grant::sorted_host_table= MySQLaccess::DB::Sort_table($HOST, 'ucase_host', 'db');\n       @MySQLaccess::Grant::sorted_user_table= defined($MySQLaccess::Param{'password'}) ?\n                           MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user', 'password'):\n                           MySQLaccess::DB::Sort_table($USER, 'ucase_host', 'user');\n    }\n\n    return 0;\n}\n\n# ===========================================================\n# sub Get_Access_Rights(host,user,db)\n#  report the access_rights for the tuple ($host,$user,$db).\n# ===========================================================\nsub Get_Access_Rights {\n  local ($host,$user,$db,$tmp) = @_;\n\n   my $aref_user;\n   my $aref_host;\n   my $aref_db;\n   # working with  temporary tables or production tables\n   if (defined($tmp) and $tmp) {\n      $aref_user = \\@MySQLaccess::Grant::sorted_user_tmp_table;\n      $aref_host = \\@MySQLaccess::Grant::sorted_host_tmp_table;\n      $aref_db   = \\@MySQLaccess::Grant::sorted_db_tmp_table;   \n   }\n   else {\n      $aref_user = \\@MySQLaccess::Grant::sorted_user_table;\n      $aref_host = \\@MySQLaccess::Grant::sorted_host_table;\n      $aref_db   = \\@MySQLaccess::Grant::sorted_db_table; \n   }\n\n\n  my ($refrecord,$refgrant);\n  my ($_host_,$_user_,$encpw_);\n  my %_Access_;\n\n  MySQLaccess::Debug::Print(1, \"for ($host,$user,$db):\");  \n\n  # ******************************************************************************\n  # Create default access-rights\n  #   default access-rights are no access at all!!\n\n\n  # ******************************************************************************\n  # get hostname for IP-address\n  # get IP-address for hostname\n  local $host_name = MySQLaccess::Host::IP2Name($host);\n  local $host_ip   = MySQLaccess::Host::Name2IP($host);\n\n  MySQLaccess::Debug::Print(3,\"host=$host, hostname=$host_name, host-ip =$host_ip\");\n  MySQLaccess::Debug::Print(3,\"user=$user\");\n  MySQLaccess::Debug::Print(3,\"db  =$db\");\n\n  # ***********************************************************************\n  # retrieve information on USER\n  #  check all records in mysql::user for matches with the tuple (host,user)\n  # ***********************************************************************\n  #    4.OR (add) the privileges for the user from the \"user\" table.\n  #     (add all privileges which is \"Y\" in \"user\")\n  ($refrecord,$refgrant)    = Get_grant_from_user($host,$user,$aref_user);\n  ($_host_,$_user_,$encpw_) = @{$refrecord};\n  %_access_                 = %{$refgrant};\n\n  foreach $field (keys(%U)) { ##only priv. set in user-table\n    $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});\n  }\n\n  if ($_user_ eq $MySQLaccess::NEW_USER) { \n     push(@Warnings,'minimum_priv');\n  }\n  if ($_user_ ne $user) {\n     $user=$_user_;\n     push(@Warnings,'anonymous_access');\n  }\n\n  # *******************************************************\n  #  Validate password if this has been asked to do\n  # *******************************************************\n  if (defined($password)) {\n     $valid = Validate_Password($password,$_host_,$_user_,$_encpw_,$aref_user);\n     if (!$valid) { push(@Errors,'invalid_password'); }\n     else         { push(@Notes,'valid_password'); }\n  }\n\n  # ******************************************************************************\n  # retrieve information on DB\n  #  check all records in mysql::db for matches with the triple (host,db,user)\n  #  first match is used.\n  # ******************************************************************************\n  #    2.Get grant for user from the \"db\" table.\n\n  ($refrecord,$refgrant)=Get_grant_from_db($host,$db,$user,$aref_db); #set process_host_table\n  ($_host_,$_user_,$encpw_) = @{$refrecord};\n  %_access_                 = %{$refgrant};\n\n  foreach $field (keys(%D)) { ##only priv. set in db-table\n    $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} or $_access_{$field});\n  }\n\n  # ***********************************************************************\n  # retrieve information on HOST\n  #  check all records in mysql::host for matches with the tuple (host,db)\n  #\n  #  ' The host table is mainly to maintain a list of \"secure\" servers. '\n  # ***********************************************************************\n  #    3.If hostname is \"empty\" for the found entry, AND the privileges with\n  #      the privileges for the host in \"host\" table.\n  #      (Remove all which is not \"Y\" in both)\n\n  if ($MySQLaccess::Grant::process_host_table) {\n     ($refrecord,$refgrant)=Get_grant_from_host($host,$db,$aref_host);\n     ($_host_,$_user_,$encpw_) = @{$refrecord};\n     %_access_                 = %{$refgrant};\n\n     foreach $field (keys(%H)) {  ##only priv. set in host-table \n       $MySQLaccess::Grant::Access{$field} = ($MySQLaccess::Grant::Access{$field} and $_access_{$field});\n     } \n  }\n\n  MySQLaccess::Debug::Print(1,\"done for ($host,$user,$db)\");\n  return %MySQLaccess::Grant::Access;\n}\n\n# ####################################\n# FINDING THE RIGHT GRANT-RULE\n# ==========================================================\n# sub Get_grant_from_user:\n# ==========================================================\nsub Get_grant_from_user {\n  my ($host,$user,$aref) = @_;\n\n  MySQLaccess::Debug::Print(1, \"\");\n  MySQLaccess::Debug::Print(1, \"(host=$host,user=$user)\");\n\n  my %Access_user = %{Default_Access_Rights()}; \n\n  my $rule_found=0;\n  my @record = ();\n  my $record;\n\n  foreach $record (@{$aref}) {\n    $MySQLaccess::Grant::full_access=0;\n    MySQLaccess::Debug::Print(3, \"Record= $record\");\n    @record=split(/\\t/,$record);\n\n    # check host and db\n    # with possible wildcards in field\n    # replace mysql-wildcards by reg-wildcards\n    my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);\n    my $user_tpl = $record[1]; #user field isn't pattern-matched!!\n    my $passwd   = $record[2];\n\n    MySQLaccess::Debug::Print(3, \"=>host_tpl : read=$record[0] -> converted=$host_tpl\");\n    MySQLaccess::Debug::Print(3, \"=>user_tpl : read=$record[1] -> $user_tpl\");\n    MySQLaccess::Debug::Print(3, \"=>password : read=$record[2] -> $passwd\");\n\n\n    if ( MySQLaccess::Host::MatchTemplate($host,$host_tpl) and\n         MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user)\n       ) \n    {\n  MySQLaccess::Debug::Print(2, \"FOUND!!\");\n        if ($passwd eq '') { push(@Warnings,'insecure_user');  }\n        else               { push(@Notes,'password_required'); }\n\n        foreach $field (keys(%U)) {\n          $Access_user{$field} = $MySQLaccess::Report::Answer{$record[$U{$field}]};\n        }\n        #print \"\\n\" if $DEBUG;\n        $MySQLaccess::Grant::Rules{'user'} = $record;\n        $rule_found=1;\n        last;\n    }\n  }\n\n  # -------------------------------\n  #  setting privileges to user-priv\n  MySQLaccess::Debug::Print(2, \"Rights after parsing user-table..:\");\n  if (! $rule_found ) {\n     @record=();\n     MySQLaccess::Debug::Print(2, \"NO record found in the user-table!!\");\n  }\n  else {\n     MySQLaccess::Debug::Print(2, \"Selected record=@record\");\n     MySQLaccess::Debug::Print(2, \"<=?=> $record\");\n  }\n \n  MySQLaccess::Debug::Print(1, \"returning @record\");\n\n  return (\\@record,\\%Access_user); #matching record in user-table\n}\n\n# ==========================================================\n# sub Get_grant_from_db:\n# ==========================================================\nsub Get_grant_from_db {\n  my ($host,$db,$user,$aref) = @_;\n\n  MySQLaccess::Debug::Print(1, \"(host=$host,user=$user,db=$db)\");\n\n  my %Access_db    = %{Default_Access_Rights()};\n  my $rule_found=0;\n\n  foreach $record (@{$aref}) {\n    $full_access=0;\n    MySQLaccess::Debug::Print(2, \"Read db: $record\");\n    @record=split(/\\t/,$record);\n\n    # check host and db\n    # with possible wildcards in field\n    # replace mysql-wildcards by reg-wildcards\n    my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);\n    my $db_tpl   = MySQLaccess::Wildcards::SQL2Reg($record[1]);\n    my $user_tpl = $record[2]; #user field isn't pattern matched!!\n    MySQLaccess::Debug::Print(3, \"=>host_tpl : read=$record[0] -> converted=$host_tpl\");\n    MySQLaccess::Debug::Print(3, \"=>db_tpl   : read=$record[1] -> $db_tpl\");\n    MySQLaccess::Debug::Print(3, \"=>user_tpl : read=$record[2] -> $user_tpl\");\n\n    if ( ( MySQLaccess::Host::Is_localhost($host_tpl)\n           or  MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)\n           or  MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )\n         and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) )\n         and ( MySQLaccess::Wildcards::MatchTemplate($user_tpl,$user) ) ) {\n \n      $MySQLaccess::Grant::process_host_table = ($record[0] eq '');\n\n      if ($user_tpl eq '') { push(@Warnings,'public_database'); }\n\n      foreach $field (keys(%D)) {\n        $Access_db{$field} = $MySQLaccess::Report::Answer{$record[$D{$field}]};\n      }\n      $rule_found=1;\n      $MySQLaccess::Grant::Rules{'db'} = $record;\n      last;\n    }\n  }\n\n  # -------------------------------\n  #  setting privileges to db-priv\n  MySQLaccess::Debug::Print(2, \"Rights after parsing db-table..:\");\n  if (! $rule_found ) {\n    MySQLaccess::Debug::Print(2, \"NO rule found in db-table => no access granted!!\");\n  }\n\n  return (\\@record,\\%Access_db);\n}\n\n# ==========================================================\n# sub Get_grant_from_host:\n# ==========================================================\nsub Get_grant_from_host {\n  my ($host,$db,$aref) = @_;\n\n  MySQLaccess::Debug::Print(1, \"Get_grant_from_host()\");\n\n  my %Access_host = %{Default_Access_Rights()};\n\n  # the host-table doesn't have to be processed if the host-field\n  # in the db-table isn't empty\n  if (!$MySQLaccess::Grant::process_host_table) {\n    MySQLaccess::Debug::Print(2, \">> Host-table doesn't have to be processed!!\");\n    $MySQLaccess::Grant::Rules{'host'} = 'no_equiv_host';\n    return ([],\\%Access_host);\n  }\n\n  my $rule_found=0;\n  my @record = ();\n\n  foreach $record (@{$aref}) {\n    $full_access=0;\n    MySQLaccess::Debug::Print(2, \"host: $record\");\n    @record=split(/\\t/,$record);\n\n    # check host and db\n    # with possible wildcards in field\n    # replace mysql-wildcards by reg-wildcards\n    my $host_tpl = MySQLaccess::Wildcards::SQL2Reg($record[0]);\n    my $db_tpl   = MySQLaccess::Wildcards::SQL2Reg($record[1]);\n    MySQLaccess::Debug::Print(3, \"=>host_tpl : $record[0] -> $host_tpl\");\n    MySQLaccess::Debug::Print(3, \"=>db_tpl   : $record[1] -> $db_tpl\");\n\n    if ( ( MySQLaccess::Host::Is_localhost($host_tpl)\n           or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_name)\n           or MySQLaccess::Wildcards::MatchTemplate($host_tpl,$host_ip) )\n         and ( MySQLaccess::Wildcards::MatchTemplate($db_tpl,$db) ) ) {\n\n      $MySQLaccess::Grant::Rules{'host'} = $record;\n      $rule_found=1;\n      foreach $field (keys(%H)) {\n        $Access_host{$field} = $MySQLaccess::Report::Answer{$record[$H{$field}]};\n      }\n      last;\n    }\n  }\n\n  # -------------------------------\n  #  setting privileges to host-priv\n  MySQLaccess::Debug::Print(2, \"Rights after parsing host-table..:\");\n  if (! $rule_found ) {\n     @record=();\n     MySQLaccess::Debug::Print(2, \"NO restrictions found in the host-table!!\");\n  }\n\n  # --------------------------------\n  # debugging access-rights in db \n\n  return (\\@record,\\%Access_host); #matching record in host-table\n}\n\n\n\n# ===========================================================\n# sub Default_Access_Rights():\n#  return (a reference to) a hash which holds all default\n#  priviliges currently defined in the grant-tables.\n# ===========================================================\nsub Default_Access_Rights {\n    my %right = ();\n\n    MySQLaccess::Debug::Print(2, \"Debug Default_Access_Rights():\");\n    # add entry for all fields in the HOST-table\n    foreach $field (keys(%MySQLaccess::Grant::H)) {\n\t$right{$field}='0' unless (defined($right{$field}));\n    }\n    # add entry for all fields in the DB-table\n    foreach $field (keys(%MySQLaccess::Grant::D)) {\n\t$right{$field}='0' unless (defined($right{$field}));\n    }\n    # add entry for all fields in the USER-table\n    foreach $field (keys(%MySQLaccess::Grant::U)) {\n\t$right{$field}='0' unless (defined($right{$field}));\n    }\n    # --------------\n    # debugging info\n    foreach $field (keys(%right)) { MySQLaccess::Debug::Print(3, sprintf(\"> %15s : %1s\",$field,$right{$field})); }\n\n    return \\%right;\n}\n\n# ======================================\n# sub Make_Privlist\n#  Make an ordered list of the privileges\n#  that should be reported\n# ======================================\nsub Make_Privlist {\n    # layout:\n    #'select_priv',     'create_priv',\n    #'insert_priv',     'drop_priv',\n    #'update_priv',     'reload_priv',\n    #'delete_priv',     'process_priv',\n    #'file_priv',       'shutdown_priv');\n    my $right;\n    my @privlist=();\n    foreach $right (@U) {\n\tif (! grep(/$right/,@privlist)) { push(@privlist,$right); }\n    };\n    foreach $right (@D) {\n\tif (! grep(/$right/,@privlist)) { push(@privlist,$right); }\n    };\n    foreach $right (@H) {\n\tif (! grep(/$right/,@privlist)) { push(@privlist,$right); }\n    };\n#       print \"Privileges:\\n\";\n#       foreach $field (@privlist) { print \" > $field\\n\"; }\n    return \\@privlist;\n}\n\n\n\n########################################################################\npackage MySQLaccess::Report;\nuse Exporter ();\n@EXPORT = qw(&Print_Header());\nBEGIN {\n    $FORM = $ENV{'SCRIPT_NAME'};\n    $DEBUG     = 0;\n    $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);\n\n    # translation-table for poss. answers\n    %Answer =  ('Y' =>  1 , 'N' =>  0\n               , 1  => 'Y',  0  => 'N'\n               ,'?' => '?', ''  => '?'\n               );\n    $headers   = 0;\n    $separator = 0;\n\n# ****************************\n# Notes and warnings\n%MESSAGES = ( \n  'insecure_user' \n   => \"Everybody can access your DB as user `\\$user' from host `\\$host'\\n\"\n     .\"WITHOUT supplying a password.\\n\"\n     .\"Be very careful about it!!\"\n ,'password_required' \n   => \"A password is required for user `\\$user' :-(\"\n ,'invalid_password'\n   => \"The password '\\$password' for user `\\$user' is invalid :-P\"\n , 'valid_password'\n   => \"You supplied the right password for user `\\$user' :-)\"\n ,'public_database' \n   => \"Any user with the appropriate permissions has access to your DB!\\n\"\n     .\"Check your users!\"\n ,'full_access' \n   => \"All grant-tables are empty, which gives full access to ALL users !!\"\n ,'no_rule_found'\n   => \"No matching rule\"\n ,'no_equiv_host' \n   => \"Not processed: host-field is not empty in db-table.\"\n ,'least_priv'\n   => \"If the final priveliges of the user are more then you gave the user,\\n\"\n     .\"check the priveliges in the db-table `\\$db'.\"\n ,'minimum_priv'\n   => \"The privileges for any new user are AT LEAST\\n\"\n     .\"the ones shown in the table above,\\n\"\n     .\"since these are the privileges of the db `\\$db'.\\n\"\n ,'not_found_mysql'\n   => \"The MySQL client program <$MySQLaccess::MYSQL> could not be found.\\n\"\n     .\"+ Check your path, or\\n\"\n     .\"+ edit the source of this script to point \\$MYSQL to the mysql client.\\n\"\n ,'not_found_mysqldump'\n   => \"The MySQL dump program <$MySQLaccess::MYSQLDUMP> could not be found.\\n\"\n     .\"+ Check your path, or\\n\"\n     .\"+ edit the source of this script to point \\$MYSQLDUMP to the mysqldump program.\\n\"\n ,'not_found_diff'\n   => \"The diff program <$MySQLaccess::DIFF> could not be found.\\n\"\n     .\"+ Check your path, or\\n\"\n     .\"+ edit the source of this script to point \\$DIFF to the diff program.\\n\"\n ,'Unrecognized_option'\n   => \"Sorry,\\n\"\n     .\"You are using an old version of the mysql-program,\\n\"\n     .\"which does not yet implement a neccessary option.\\n\"\n     .\"\\n\"\n     .\"You need at least Version 6.2 of the mysql-client,\\n\"\n     .\"which was build in MySQL v3.0.18, to use this version\\n\"\n     .\"of `$MySQLaccess::script'.\"\n ,'Access_denied'\n   => \"Sorry,\\n\"\n     .\"An error occured when trying to connect to the database\\n\"\n     .\"with the grant-tables:\\n\"\n     .\"* Maybe YOU do not have READ-access to this database?\\n\"\n     .\"* If you used the -U option, you may have supplied an invalid username?\\n\"\n     .\"  for the superuser?\\n\"\n     .\"* If you used the -U option, it may be possible you have to supply\\n\"\n     .\"  a superuser-password to, with the -P option?\\n\"\n     .\"* If you used the -P option, you may have supplied an invalid password?\\n\"\n ,'Dbaccess_denied'\n   => \"Sorry,\\n\"\n     .\"An error occured when trying to connect to the database\\n\"\n     .\"with the grant-tables. (dbaccess denied)\\n\"\n ,'Unknown_tmp_table'\n   => \"Sorry,\\n\"\n     .\"An error occured when trying to work with the temporary tables in the database\\n\"\n     .\"with the grant-tables. (One of the temporary tables does not exist)\\n\"\n ,'Unknown_table'\n   => \"Sorry,\\n\"\n     .\"An error occured when trying to work with some tables in the database\\n\"\n     .\"with the grant-tables. (table does not exist)\\n\"\n ,'use_old_server'\n   => \"Sorry,\\n\"\n     .\"An error occured when executing an SQL statement.\\n\"\n     .\"You might consider altering the use of the parameter `--old_server' when \\n\"\n     .\"calling `$MySQLaccess::script'.\"\n ,'unknown_error'\n   => \"Sorry,\\n\"\n     .\"An error occured when trying to connect to the database\\n\"\n     .\"with the grant-tables. (unknown error)\\n\"\n ,'anonymous_access'\n   => \"Accessing the db as an anonymous user.\\n\"\n     .\"Your username has no relevance\\n\"\n ,'user_required'\n   => \"You have to supply a userid.\"\n ,'db_required'\n   => \"You have to supply the name of a database.\"\n ,'host_required'\n   => \"You have to supply the name of a host.\"\n );\n\n\n} \n# =====================================\n# sub Print_Header:\n#  print header info\n# =====================================\nsub Print_Header {\n    if ($MySQLaccess::CMD) { #command-line mode\n    print \"$MySQLaccess::script Version $MySQLaccess::VERSION\\n\"\n         .\"By RUG-AIV, by Yves Carlier (Yves.Carlier\\@rug.ac.be)\\n\"\n         .\"Changes by Steve Harvey (sgh\\@vex.net)\\n\"\n         .\"This software comes with ABSOLUTELY NO WARRANTY.\\n\"\n\t .\"\\nWarning: $MySQLaccess::script is deprecated and will be removed in a future version.\\n\";\n    }\n    if ($MySQLaccess::CGI) { #CGI-BIN mode\n    print \"content-type: text/html\\n\\n\" \n       . \"<HTML>\\n\"\n         .\"<HEAD>\\n\"\n         .\"<TITLE>MySQLaccess</TITLE>\\n\"\n         .\"</HEAD>\\n\"\n         .\"<BODY>\\n\"\n         .\"<H1>$MySQLaccess::script Version $MySQLaccess::VERSION</H1>\\n\" \n         .\"<CENTER>\\n<ADDRESS>\\n\"\n         .\"By RUG-AIV, by Yves Carlier (<a href=mailto:Yves.Carlier\\@rug.ac.be>Yves.Carlier\\@rug.ac.be</a>)<BR>\\n\"\n         .\"Changes by Steve Harvey (<a href=mailto:sgh\\@vex.net>sgh\\@vex.net</a>)<BR>\\n\"\n         .\"This software comes with ABSOLUTELY NO WARRANTY.<BR>\\n\"\n         .\"<BR>\\nWarning: $MySQLaccess::script is deprecated and will be removed in a future version.<BR>\\n\"\n         .\"</ADDRESS>\\n</CENTER>\\n\"\n         .\"<HR>\\n\";\n    Print_Taskbar();\n    print \"<HR>\\n\";\n    }\n    return 1;\n}\n\n# =====================================\n# sub Print_Footer:\n#  print footer info\n# =====================================\nsub Print_Footer {\n    if ($MySQLaccess::CMD) { #command-line mode\n    print \"\\n\"\n         .\"BUGs can be reported at http://bugs.mysql.com/\\n\";\n    }\n    if ($MySQLaccess::CGI) { #CGI-BIN mode\n    if ($MySQLaccess::Param{'brief'}) {\n    print \"</table>\\n\";  #close table in brief-output\n    }\n    print \"<HR>\\n\"\n         .\"<ADDRESS>\\n\"\n         .\"BUGs can be reported at <a href=\\\"http://bugs.mysql.com/\\\">http://bugs.mysql.com/</a><BR>\\n\"\n#         .\"Don't forget to mention the version $VERSION!<BR>\\n\"\n         .\"</ADDRESS>\\n\"\n         .\"</BODY>\\n\"\n         .\"</HTML>\\n\";\n    }\n    return 1;\n}\n\n# =====================================\n# sub Print_Taskbar:\n#  print taskbar on STDOUT\n# =====================================\nsub Print_Taskbar {\n    print \"<CENTER>\\n\"\n         .\"[<a href=$FORM?relnotes=on>Release&nbsp;Notes</a>] \\n\"\n         .\"[<a href=$FORM?version=on>Version</a>] \\n\"\n         .\"[<a href=$FORM?plan=on>Future&nbsp;Plans</a>] \\n\"\n         .\"[<a href=$FORM?howto=on>Examples</a>] \\n\"\n         .\"[<a href=$FORM?help=on>New check</a>] \\n\"\n         .\"[<a href=$FORM?edit=on>Change/edit ACL</a>] \\n\"\n         .\"</CENTER>\\n\";\n    return 1;\n}\n\n# =====================================\n# sub Print_Form:\n#  print CGI-form\n# =====================================\nsub Print_Form {\nprint <<EOForm;\n<center>\n<!-- Quering -->\n<FORM method=POST action=$FORM>\n\n<table border width=\"100%\" >\n<tr>\n  <th>MySQL server</th>\n  <th>User information</th>\n  <th>Reports</th>\n  </tr>\n\n<tr>\n  <td valign=top>\n  <table>\n  <tr>\n    <td halign=right><b>Host</b><br><font size=-2>(Host on which MySQL-server resides.)</font></td>\n    <td valign=top><INPUT name=rhost type=text size=15 maxlength=15 value=\"$MySQLaccess::Param{'rhost'}\"></td>\n    </tr>\n  <tr>\n    <td halign=right><b>Superuser</b><br><font size=-2>(User which has <font color=\"Red\">read-access</font> to grant-tables.)</font></td>\n    <td valign=top><INPUT name=superuser type=text size=15 maxlength=15 value=\"$MySQLaccess::Param{'superuser'}\"></td>\n    </tr>\n  <tr>\n    <td halign=right><b>Password</b><br><font size=-2>(of Superuser.)</font></td>\n    <td valign=top><INPUT name=spassword type=password size=15 maxlength=15 value=\"$MySQLaccess::Param{'spassword'}\"></td>\n    </tr>\n  </table>\n  </td>\n\n  <td valign=top>\n  <table>\n  <tr>\n    <td halign=right><b><font color=Red>User</font></b><br><font size=-2>(Userid used to connect to MySQL-database.)</font></td>\n    <td halign=top><INPUT name=user type=text size=15 maxlength=15 value=\"$MySQLaccess::Param{'user'}\"></td>\n    </tr>\n  <tr>\n    <td halign=right><b>Password</b><br><font size=-2>(Password user has to give to get access to MySQL-database.)</font></td>\n    <td valign=top><INPUT name=password type=password size=15 maxlength=15 value=\"$MySQLaccess::Param{'password'}\"></td>\n    </tr>\n  <tr>\n    <td halign=right><b><font color=Red>Database</font></b><br><font size=-2>(Name of MySQL-database user tries to connect to.</font><br><font size=-2>Wildcards <font color=\"Green\">(*,?,%,_)</font> are allowed.)</font></td>\n    <td valign=top><INPUT name=db type=text size=15 maxlength=15 value=\"$MySQLaccess::Param{'db'}\"></td>\n    </tr>\n  <tr>\n    <td halign=right><b>Host</b><br><font size=-2>(Host from where the user is trying to connect to MySQL-database.</font><br><font size=-2>Wildcards <font color=\"Green\">(*,?,%,_)</font> are allowed.)</font></td>\n    <td valign=top><INPUT name=host type=text size=15 maxlength=15 value=\"$MySQLaccess::Param{'host'}\"></td>\n    </tr>\n  </table>\n  </td>\n\n  <td valign=center>\n  <table cellspacing=5 cellpadding=2 cols=1 height=\"100%\">\n  <tr align=center>\n    <td halign=right><INPUT type=submit name=brief value=\"Brief\"><br>\n                     <INPUT type=submit name=table value=\"Tabular\"></td>\n    </tr>\n  <tr align=center>\n    <td></td>\n    </tr>\n  <tr align=center>\n    <td halign=right><INPUT type=reset value=\"Clear\"></td>\n    </tr>\n  </table>\n  </td>\n  </tr>\n\n</table>\n</form>\n\n\n</BODY>\n</HTML>\nEOForm\n    return 1;\n}\n\n# =====================================\n# sub Print_Usage:\n#  print some information on STDOUT\n# =====================================\nsub Print_Usage {\n    Print_Error_Messages();\n    if ($MySQLaccess::CMD) { #command-line mode\n        Print_Options();\n    }\n    if ($MySQLaccess::CGI) { #CGI-BIN mode\n        Print_Form();\n    }    \n    return 1;\n}\n\n# ======================================\n# sub Print_Version:\n# ======================================\nsub Print_Version {\n    if ($MySQLaccess::CMD) {\n       print $MySQLaccess::INFO;\n    }\n    if ($MySQLaccess::CGI) { \n       print \"<PRE>\\n\"; \n       print $MySQLaccess::INFO;\n       print \"</PRE>\\n\"; \n    }\n    return 1;\n}\n\n# ======================================\n# sub Print_Relnotes:\n# ======================================\nsub Print_Relnotes {\n    if ($MySQLaccess::CMD) {\n       print $MySQLaccess::RELEASE;\n    }\n    if ($MySQLaccess::CGI) { \n       print \"<PRE>\\n\";\n       print $MySQLaccess::RELEASE;\n       print \"</PRE>\\n\"; \n    }\n    return 1;\n}\n\n# ======================================\n# sub Print_Plans:\n# ======================================\nsub Print_Plans {\n    if ($MySQLaccess::CMD) {\n       print $MySQLaccess::TODO;\n    }\n    if ($MySQLaccess::CGI) { \n       print \"<PRE>\\n\";\n       print $MySQLaccess::TODO;\n       print \"</PRE>\\n\"; \n    }\n    return 1;\n}\n\n# ======================================\n# sub Print_HowTo:\n# ======================================\nsub Print_HowTo {\n    if ($MySQLaccess::CMD) {\n       print $MySQLaccess::HOWTO;\n    }\n    if ($MySQLaccess::CGI) { \n       print \"<PRE>\\n\"; \n       print $MySQLaccess::HOWTO;\n       print \"</PRE>\\n\"; \n    }\n    return 1;\n}\n\n# ======================================\n# sub Print_Options:\n# ======================================\nsub Print_Options {\n    if ($MySQLaccess::CGI) { print \"<PRE>\\n\"; }\n    print $MySQLaccess::OPTIONS;\n    if ($MySQLaccess::CGI) { print \"</PRE>\\n\"; }\n    return 1;\n}\n\n# ======================================\n# sub Print_Error_Access:\n# ======================================\nsub Print_Error_Access {\n    my ($error) = @_;\n    print \"\\n\";\n    if ($MySQLaccess::CGI) { print \"<font color=Red>\\n<PRE>\\n\"; }\n    print $MESSAGES{$error};\n    if ($MySQLaccess::CGI) { print \"</PRE>\\n</font>\\n\"; }\n    print \"\\n\";\n    return 1;\n}\n\n# ======================================\n# sub Print_Error_Messages:\n# ======================================\nsub Print_Error_Messages {\n#    my ($error) = @_;\n    print \"\\n\";\n    if ($MySQLaccess::CGI) { print \"<font color=Red>\\n<center>\\n\"; }\n    foreach $error (@MySQLaccess::Grant::Error) {\n       print $MESSAGES{$error};\n       print $MySQLaccess::CGI ? \"<br>\\n\" : \"\\n\";\n    }\n    if ($MySQLaccess::CGI) { print \"</center>\\n</font>\\n\"; }\n    print \"\\n\";\n    return 1;\n}\n\n# ======================================\n# sub Print_Message:\n# ======================================\nsub Print_Message {\n    my ($aref) = @_;\n    my @messages = @{$aref};\n    print \"\\n\";\n    if ($MySQLaccess::CGI) { print \"<font color=DarkGreen>\\n<center>\\n\"; }\n    foreach $msg (@messages) {\n       print $msg;\n       print $MySQLaccess::CGI ? \"<br>\\n\" : \"\\n\";\n    }\n    if ($MySQLaccess::CGI) { print \"</center>\\n</font>\\n\"; }\n    print \"\\n\";\n    return 1;\n}\n\n# ======================================\n# sub Print_Edit:\n# ======================================\nsub Print_Edit {\n    print \"\\n\";\n    if (!$MySQLaccess::CGI) { \n       print \"Note: Editing the temporary tables is NOT supported in CMD-line mode!\\n\";\n       return 0;\n    }\n    print \"<CENTER>\\n\"\n         .\"<form action=$FORM method=GET>\\n\"\n         .\"<table width=90% border>\\n\"\n         .\"<tr>\\n\"\n         .\" <td><input type=checkbox name=copy value=on> Copy grant-rules to temporary tables<br></td>\\n\"\n         .\" <td rowspan=5 align=center valign=center><input type=submit value=Go></td>\\n\"\n         .\"</tr>\\n\"\n         .\"<tr>\\n\"\n         .\" <td> Edit temporary tables with external application:<br>\"\n         .\" <a href=\\\"$MySQLaccess::MYSQLADMIN\\\">$MySQLaccess::MYSQLADMIN</a></td>\\n\"\n         .\"</tr>\\n\"\n         .\"<tr>\\n\"\n         .\" <td><input type=checkbox name=preview value=on> Preview changes made in temporary tables</td>\\n\"\n         .\"</tr>\\n\"\n         .\"<tr>\\n\"\n         .\" <td><input type=checkbox name=commit value=on> Make changes permanent</td>\\n\"\n         .\"</tr>\\n\"\n         .\"<tr>\\n\"\n         .\" <td><input type=checkbox name=rollback value=on> Restore previous grand-rules</td>\\n\"\n         .\"</tr>\\n\"\n         .\"<tr>\\n\"\n         .\" <td colspan=2 align=center><font size=-2 color=Red>You need write,delete and drop-privileges to perform the above actions</font></td>\\n\"\n         .\"</tr>\\n\"\n         .\"</table>\\n\"\n         .\"</form>\\n\"\n         .\"</CENTER>\\n\";\n\n    return 1;\n}\n\n\n# ======================================\n# sub Print_Access_rights:\n#  print the access-rights on STDOUT\n# ======================================\nsub Print_Access_rights {\n    my ($host,$user,$db,$refhash) = @_;\n\n    if (defined($MySQLaccess::Param{'brief'})) { \n#       if ($MySQLaccess::CGI) { print \"<PRE>\\n\"; }\n       Matrix_Report($host,$user,$db,$refhash);  \n#       if ($MySQLaccess::CGI) { print \"</PRE>\\n\"; }\n    }\n    else { \n       Tabular_Report($host,$user,$db,$refhash); \n       $MySQLaccess::Report::separator = $MySQLaccess::CGI ? \"<hr>\" : \"-\"x80;\n    }\n    return 1;\n}\n\n# ======================================\n# sub Print_Diff_ACL:\n#  print the diff. in the grants before and after\n# ======================================\nsub Print_Diff_ACL {\n    my ($aref) = @_;\n    my @diffs = @{$aref};\n    my %block = ( '<' => 'Before',\n                  '>' => 'After',\n                );\n    my %color = ( '<' => 'Green',\n                  '>' => 'Red',\n                ); \n    my $curblock = '';\n\n    # -----------------------------\n    # create column-headers\n    foreach $field (@MySQLaccess::Grant::Privileges) {\n      push(@headers,substr($field,0,4));\n    }\n\n    if ($MySQLaccess::CMD) {\n    print \"\\n\";\n    print \"Differences in access-rights BEFORE and AFTER changes in grant-tables\\n\";\n#    print \"---------------------------------------------------------------------\\n\";\n      my $line1=\"\";\n      my $line2=\"\";\n      $line1 .= sprintf(\"| %-30s|\",'Host,User,DB');\n      $line2 .= sprintf(\"+-%-30s+\",'-' x 30);\n      foreach $header (@headers) {\n        $line1 .= sprintf(\"%-4s|\",$header);\n        $line2 .= sprintf(\"%s+\",'----');\n      }\n      print \"$line2\\n\";\n      print \"$line1\\n\";\n      print \"$line2\\n\";\n\n      $format = \"format STDOUT = \\n\"\n              . \"^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< \" . \" @|||\" x 10 .\"\\n\"\n              . '$host_user_db,@priv' . \"\\n\"\n              . \".\\n\";\n#print $format;\n      eval $format;\n    }\n    if ($MySQLaccess::CGI) {\n    print \"<table border width=100%>\\n\";\n    print \"<tr>\\n\";\n    print \"<th colspan=11>\";\n    print \"Differences in access-rights <font color=$color{'<'}>BEFORE</font> \"\n         .\"and <font color=$color{'>'}>AFTER</font> changes to grant-tables</font>\\n\";\n    print \"</th>\";\n    print \"</tr>\\n\";\n    print \"<tr>\\n\";    \n    $line1 .= sprintf(\"<th>%-20s</th>\",'Host, User, DB');\n    foreach $header (@headers) {\n      $line1 .= sprintf(\"<th>%-4s</th>\",$header);\n    }\n    print \"$line1</tr>\\n\";\n    }\n\n    foreach $line (@diffs) {\n        $type = substr($line,0,1);\n        $line = substr($line,1);\n        ($host,$user,$db,@priv) = split(/,/,$line);\n        if ($MySQLaccess::CMD) {\n           if ($type ne $curblock) {\n              $curblock = $type;\n              print $block{$curblock},\":\\n\";\n           }\n           #print \"$line\\n\";\n           write;\n        }\n        if ($MySQLaccess::CGI) {\n           if ($type ne $curblock) {\n              $curblock = $type;\n              print \"<tr><td><b>$block{$curblock}<b></td></tr>\\n\";\n           }\n           $line1=\"<td><font color=$color{$type}>$host, $user, $db</font></td>\";\n           foreach $field (@priv) {\n              $line1 .= sprintf(\"<td align=center><font color=$color{$type}>%-4s</font></td>\",$field);\n           }\n           print \"<tr>$line1</tr>\\n\";\n        }\n    }\n    print      \"\\n\";\n    if ($MySQLaccess::CMD) {\n    print \"---------------------------------------------------------------------\\n\";\n    }\n    if ($MySQLaccess::CGI) {\n    print      \"</table><br>\";\n    }\n\n\n    return 1;\n}\n\n# ======================================\n# sub Tabular_Report\n#  Tabular report,\n#  suitable for 1 triple (host,db,user)\n# ======================================\nsub Tabular_Report {\n    my ($host,$user,$db,$a) = @_;\n    my $column=2;\n\n    # -----------------------------\n    # separator\n    if ($MySQLaccess::Report::separator) { print \"$MySQLaccess::Report::separator\\n\"; }\n    \n    # -----------------------------\n    # print table of access-rights\n    my $rows = int(@MySQLaccess::Grant::Privileges/2);  #round up\n    my @table=();\n    $j=0;\n    for $i (0 .. $rows-1) {\n      $table[$j]=$MySQLaccess::Grant::Privileges[$i];\n      $j = $j+2;\n    }\n    $j=1;\n    for $i ($rows .. $#MySQLaccess::Grant::Privileges) {\n      $table[$j]=$MySQLaccess::Grant::Privileges[$i];\n      $j = $j+2;\n    }\n    if ($MySQLaccess::CMD) {\n    print \"\\n\";\n    print \"Access-rights\\n\";\n    print \"for USER '$user', from HOST '$host', to DB '$db'\\n\";\n    }\n    if ($MySQLaccess::CGI) {\n    print \"<table border width=100%>\\n\";\n    print \"<tr>\\n\";\n    }\n    if ($MySQLaccess::CGI) {\n    print \"<th colspan=5>\";\n    print \"<font color=Red>Access-rights</font>\\n\";\n    print \"for USER '<font color=Green>$user</font>', from HOST '<font color=Green>$host</font>', to DB '<font color=Green>$db</font>'\\n\";\n    print \"</th>\";\n    print \"</tr>\\n\";\n    print \"<tr>\\n\";\n    }\n    if ($MySQLaccess::CMD) {\n    print      \"\\t+-----------------+---+\\t+-----------------+---+\";\n    }\n    foreach $field (@table) {\n        if ($MySQLaccess::CMD) {\n          if ($column==2) { print \"\\n\\t\"; $column=1;}\n          else            { print \"\\t\";   $column=2;}\n          printf \"| %-15s | %s |\",$field,$Answer{$a->{$field}}; \n        }\n        if ($MySQLaccess::CGI) {\n          if ($column==2) { print \"</tr>\\n<tr>\\n\"; $column=1;}\n          else            { print \"<td width=10%></td>\";   $column=2;}\n          printf \" <td width=35%><b>%-15s</b></td><td width=10%>%s</td>\\n\",$field,$Answer{$a->{$field}}; \n        }\n    }\n    print      \"\\n\";\n    if ($MySQLaccess::CMD) {\n    print      \"\\t+-----------------+---+\\t+-----------------+---+\\n\";\n    }\n    if ($MySQLaccess::CGI) {\n    print      \"</tr>\\n</table><br>\";\n    }\n\n    # ---------------\n    # print notes:\n    foreach $note (@MySQLaccess::Grant::Notes) {\n      my $message = $MESSAGES{$note};\n      $message =~ s/\\$user/$user/g; \n      $message =~ s/\\$db/$db/g;\n      $message =~ s/\\$host/$host/g;\n      $message =~ s/\\$password/$password/g;\n      $PREFIX='NOTE';\n      if ($MySQLaccess::CMD) {\n      my @lines = split(/\\n/,$message);\n      foreach $line (@lines) { \n        print \"$PREFIX:\\t $line\\n\"; \n        $PREFIX='    ';\n      }\n      }\n      if ($MySQLaccess::CGI) {\n      print \"<b>$PREFIX:</b> $message<br>\\n\";\n      }\n    } \n\n    # ---------------\n    # print warnings:\n    foreach $warning (@MySQLaccess::Grant::Warnings) {\n      my $message = $MESSAGES{$warning};\n      $message =~ s/\\$user/$user/g;\n      $message =~ s/\\$db/$db/g;\n      $message =~ s/\\$host/$host/g;\n      $message =~ s/\\$password/$password/g;\n      $PREFIX='BEWARE';\n      if ($MySQLaccess::CMD) {\n      my @lines = split(/\\n/,$message);\n      foreach $line (@lines) { \n        print \"$PREFIX:\\t $line\\n\"; \n        $PREFIX='      ';\n      }\n      }\n      if ($MySQLaccess::CGI) {\n      print \"<b>$PREFIX:</b> $message<br>\\n\";\n      }\n    }\n\n    # ---------------\n    # print errors:\n    foreach $error (@MySQLaccess::Grant::Errors) {\n      my $message = $MESSAGES{$error};\n      $message =~ s/\\$user/$user/g;\n      $message =~ s/\\$db/$db/g;\n      $message =~ s/\\$host/$host/g;\n      $message =~ s/\\$password/$password/g;\n      $PREFIX='ERROR';\n      if ($MySQLaccess::CMD) {\n      my @lines = split(/\\n/,$message);\n      foreach $line (@lines) { \n        print \"$PREFIX:\\t $line\\n\"; \n        $PREFIX='    ';\n      }\n      }\n      if ($MySQLaccess::CGI) {\n      print \"<b>$PREFIX:</b> $message<br>\\n\";\n      }\n    }\n\n    # ---------------\n    # inform if there are no rules ==> full access for everyone.\n    if ($MySQLaccess::Grant::full_access) { print \"$MESSAGES{'full_access'}\\n\"; }\n\n    # ---------------\n    # print the rules used\n    print \"\\n\";\n    if ($MySQLaccess::CMD) {\n    print \"The following rules are used:\\n\";\n    foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {\n      my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});\n      $rule =~ s/\\t/','/g;\n      printf \" %-5s : '%s'\\n\",$field,$rule;\n    }\n    }\n    if ($MySQLaccess::CGI) {\n    print \"<br>\\n\";\n    print \"<table border width=100%>\\n\";\n    print \"<tr><th colspan=2>The following rules are used:</th></tr>\\n\";\n    foreach $field (sort(keys(%MySQLaccess::Grant::Rules))) {\n      my $rule = (defined($MESSAGES{$MySQLaccess::Grant::Rules{$field}}) ? $MESSAGES{$MySQLaccess::Grant::Rules{$field}} : $MySQLaccess::Grant::Rules{$field});\n      $rule =~ s/\\t/','/g;\n      printf \"<tr><th>%-5s</th><td>'%s'</td></tr>\\n\",$field,$rule;\n    }\n    print \"</table>\\n\";\n    }\n \n    return 1;\n}\n\n# ======================================\n# sub Matrix_Report:\n#  single-line output foreach triple,\n#  no notes,warnings,...\n# ======================================\nsub Matrix_Report {\n    my ($host,$user,$db,$a) = @_;\n    my @headers = ();\n    \n    if (! $headers) {\n       # -----------------------------\n       # create column-headers\n       foreach $field (@MySQLaccess::Grant::Privileges) {\n         push(@headers,substr($field,0,4));\n       }\n    \n       # -----------------------------\n       # print column-headers\n       print \"\\n\";\n       if ($MySQLaccess::CMD) {\n         my $line1=\"\";\n         my $line2=\"\";\n         foreach $header (@headers) {\n           $line1 .= sprintf(\"%-4s \",$header);\n           $line2 .= sprintf(\"%s \",'----');\n         }\n         $line1 .= sprintf(\"| %-20s\",'Host,User,DB');\n         $line2 .= sprintf(\"+ %-20s\",'-' x 20);\n         print \"$line1\\n\";\n         print \"$line2\\n\";\n       }\n       if ($MySQLaccess::CGI) {\n         print \"<table width=100% border>\\n\";\n         my $line1=\"<tr>\";\n         foreach $header (@headers) {\n           $line1 .= sprintf(\"<th>%-4s</th>\",$header);\n         }\n         $line1 .= sprintf(\"<th>%-20s</th>\",'Host, User, DB');\n         print \"$line1</tr>\\n\";\n       }\n\n       # ----------------------------\n       # column-headers should only be \n       # printed once.\n       $MySQLaccess::Report::headers=1;\n    }\n\n    # ------------------------\n    # print access-information\n    if ($MySQLaccess::CMD) {\n      foreach $field (@MySQLaccess::Grant::Privileges) {\n  \t  printf \" %-2s  \",$Answer{$a->{$field}}; \n      }\n      printf \"| %-20s\",join(',',$host,$user,$db);\n      print \"\\n\";\n    }\n    if ($MySQLaccess::CGI) {\n      print \"<tr>\";\n      foreach $field (@MySQLaccess::Grant::Privileges) {\n  \t  printf \"<td align=center>%-2s</td>\",$Answer{$a->{$field}}; \n      }\n      printf \"<td><b>%-20s</b></td>\",join(', ',$host,$user,$db);\n      print \"</tr>\\n\";\n    }\n\n    return 1;\n}\n\n\n# ======================================\n# sub Raw_Report:\n#  single-line output foreach triple,\n#  no notes,warnings,...\n# ======================================\nsub Raw_Report {\n    my ($host,$user,$db,$a) = @_;\n    my @headers = ();\n    my $string = \"\";\n    \n    # ------------------------\n    # print access-information\n    $string = \"$host,$user,$db,\";\n    foreach $field (@MySQLaccess::Grant::Privileges) {\n\t  $string .= $Answer{$a->{$field}} . \",\"; \n    }\n    return $string;\n}\n\n\n#######################################################################\npackage MySQLaccess::Wildcards;\nBEGIN {\n    $DEBUG     = 0;\n    $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);\n}\n# ############################################\n# SQL, WILDCARDS and REGULAR EXPRESSIONS \n# ============================================\n# translage SQL-expressions to Reg-expressions\n# ============================================\nsub SQL2Reg {\n    my ($expr) = @_;\n    my $expr_o = $expr;\n    $expr  =~ s/\\./\\\\./g;\n    $expr  =~ s/\\\\%/\\002/g;\n    $expr  =~ s/%/.*/g;\n    $expr  =~ s/\\002/%/g;\n    $expr  =~ s/\\\\_/\\002/g;\n    $expr  =~ s/_/.+/g;\n    $expr  =~ s/\\002/_/g;\n    MySQLaccess::Debug::Print(2,\"$expr_o --> $expr\");\n    return $expr;\n}\n\n# translage WILDcards to Reg-expressions\n# ============================================\nsub Wild2Reg {\n    my ($expr) = @_;\n    my $expr_o = $expr;\n    $expr  =~ s/\\./\\\\./g;\n    $expr  =~ s/\\\\\\*/\\002/g;\n    $expr  =~ s/\\*/.*/g;\n    $expr  =~ s/\\002/*/g;\n    $expr  =~ s/\\\\\\?/\\002/g;\n    $expr  =~ s/\\?/.+/g;\n    $expr  =~ s/\\002/?/g;\n    MySQLaccess::Debug::Print(2,\"$expr_o --> $expr\");\n    return $expr;\n}\n\n# =============================================\n# match a given string with a template\n# =============================================\nsub MatchTemplate {\n    my ($tpl,$string) = @_;\n    my $match=0;\n    if ($string=~ /^$tpl$/ or $tpl eq '') { $match=1; }\n    else                                  { $match=0;}\n    MySQLaccess::Debug::Print(2,\"($tpl,$string) --> $match\");\n    return $match;\n}\n\n#######################################################################\npackage MySQLaccess::Host;\nBEGIN {\n    $localhost = undef;\n    $DEBUG     = 2;\n    $DEBUG     = $MySQLaccess::DEBUG unless ($DEBUG);\n}\n# ======================================\n# sub IP2Name\n#  return the Name with the corr. IP-nmbr\n#  (no aliases yet!!)\n# ======================================\nsub IP2Name {\n    my ($ip) = @_;\n    my $ip_o = $ip;\n    if ($ip !~ /([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)/o) {\n       MySQLaccess::Debug::Print(3,\"'$ip' is not an ip-number, returning IP=$ip\");\n       return $ip;\n    }\n    MySQLaccess::Debug::Print(4,\"IP=$ip split up => $1.$2.$3.$4\");\n    $ip = pack \"C4\",$1,$2,$3,$4;\n    MySQLaccess::Debug::Print(4,\"IP packed -> >>$ip<<\\n\");\n    my ($name,$aliases,$addrtype,$length,@addrs) = gethostbyaddr($ip, AF_INET);\n    MySQLaccess::Debug::Print(3,\"IP=$ip_o => hostname=$name\");\n    MySQLaccess::Debug::Print(4,\"aliases=$aliases\");\n    MySQLaccess::Debug::Print(4,\"addrtype=$addrtype - length=$length\");\n    return ($name || $ip);\n    #return ($name || undef);\n}\n\n# ======================================\n# sub Name2IP\n#  return the IP-number of the host\n# ======================================\nsub Name2IP {\n    my ($name) = @_;\n    if ($name =~ /[%_]/) { \n       MySQLaccess::Debug::Print(3,\"'$name' contains SQL-wildcards, returning name=$name\");\n       return $name; \n    }\n    my ($_name,$aliases,$addrtype,$length,@addrs) = gethostbyname($name);\n    my ($a,$b,$c,$d) = unpack('C4',$addrs[0]);\n    my $ip = \"$a.$b.$c.$d\";\n    MySQLaccess::Debug::Print(3,\"hostname=$name => IP=$ip\");\n    MySQLaccess::Debug::Print(4,\"aliases=$aliases\");\n    MySQLaccess::Debug::Print(4,\"addrtype=$addrtype - length=$length\");\n    #if ($ip ne \"\") { return \"$ip\"; }\n    #else           { return undef; }\n    return ($ip || $name);\n}\n\n# ========================================\n# sub LocalHost\n#  some special action has to be taken for\n#  the localhost\n# ========================================\nsub LocalHost {\n    if (!defined($MySQLaccess::Host::localhost)) {\n       $MySQLaccess::Host::localhost = Sys::Hostname::hostname();\n       MySQLaccess::Debug::Print(3,\"Setting package variable \\$localhost=$MySQLaccess::Host::localhost\");\n    }\n    my $host = $localhost;\n    MySQLaccess::Debug::Print(3,\"localhost = $host\");\n    return $host;\n}\n\n# ========================================\n# check if the given hostname (or ip)\n# corresponds with the localhost\n# ========================================\nsub Is_localhost {\n    my ($host_tpl) = @_;\n    my $isit = 0;\n    if (($MySQLaccess::host_name eq $localhost) or ($MySQLaccess::host_ip eq $local_ip)) {\n\tMySQLaccess::Debug::Print(2,\"Checking for localhost\");\n      MySQLaccess::Debug::Print(3,\"because ($MySQLaccess::host_name EQ $localhost) AND ($MySQLaccess::host_ip EQ $local_ip)\");\n      $isit = ( 'localhost' =~ /$host_tpl/ ) ? 1 : 0;\n      MySQLaccess::Debug::Print(3,\" 'localhost' =?= $host_tpl  -> $isit\");\n      return $isit;\n    }\n    else {\n      MySQLaccess::Debug::Print(4,\"Not checking for localhost\");\n      MySQLaccess::Debug::Print(4,\"because ($MySQLaccess::host_name != $localhost) AND ($MySQLaccess::host_ip != $local_ip)\");\n      return 0;\n    }\n}\n\n\n# =========================================\n# check if host (IP or name) can be matched\n# on the template.\n# =========================================\nsub MatchTemplate {\n    my ($host,$tpl) = @_;\n    my $match = 0;\n   \n    MySQLaccess::Debug::Print(1, \"($host) =?= ($tpl)\");\n\n    my $host_name = IP2Name($host);\n    my $host_ip   = Name2IP($host);\n\n    MySQLaccess::Debug::Print(2, \"name=$host_name ; ip=$host_ip\");\n    $match = (MySQLaccess::Wildcards::MatchTemplate($tpl,$host_name) or\n             MySQLaccess::Wildcards::MatchTemplate($tpl,$host_ip));\n\n    MySQLaccess::Debug::Print(2, \"($host_name,$host_ip) =?= ($tpl): $ncount\");\n\n    return $match;\n}\n\n########################################################################\npackage MySQLaccess::Debug;\nBEGIN {\n   my $dbg_file = \"$MySQLaccess::script_log\";\n   open(DEBUG,\"> $dbg_file\") or warn \"Could not open outputfile $dbg_file for debugging-info\\n\";\n   select DEBUG;\n   $| = 1;\n   select STDOUT;\n}\n# =========================================\n# Print debugging information on STDERR\n# =========================================\nsub Print {\n    my ($level,$mesg) = @_;\n    my ($pack,$file,$line,$subname,$hasargs,$wantarray) = caller(1);\n    my ($PACK)  = split('::',$subname); \n    my $DEBUG = ${$PACK.\"::DEBUG\"} ? ${$PACK.\"::DEBUG\"} : $MySQLaccess::DEBUG ;\n    my ($sec,$min,$hour) = localtime();\n    print DEBUG \"[$hour:$min:$sec $subname] $mesg\\n\" if ($DEBUG>=$level);\n}\n\n", "num_lines": 3261}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2000, 2014 Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# Create a bug report and mail it to the mysql mailing list\n# Based on glibc bug reporting script.\n\necho \"Warning: $0 is deprecated and will be removed in a future version.\" 1>&2\necho \"Finding system information for a MySQL bug report\"\n\nVERSION=\"@VERSION@@MYSQL_SERVER_SUFFIX@\"\nCOMPILATION_COMMENT=\"@COMPILATION_COMMENT@\"\nBUGmysql=\"mysql@lists.mysql.com\"\n# This is set by configure\nCOMP_CALL_INFO=\"CC='@SAVE_CC@'  CFLAGS='@SAVE_CFLAGS@'  CXX='@SAVE_CXX@'  CXXFLAGS='@SAVE_CXXFLAGS@'  LDFLAGS='@SAVE_LDFLAGS@'  ASFLAGS='@SAVE_ASFLAGS@'\"\nCOMP_RUN_INFO=\"CC='@CC@'  CFLAGS='@CFLAGS@'  CXX='@CXX@'  CXXFLAGS='@CXXFLAGS@'  LDFLAGS='@LDFLAGS@'  ASFLAGS='@ASFLAGS@'\"\nCONFIGURE_LINE=\"@CONF_COMMAND@\"\n\nLIBC_INFO=\"\"\nfor pat in /lib/libc.* /lib/libc-* /usr/lib/libc.* /usr/lib/libc-*\ndo\n    TMP=`ls -l $pat 2>/dev/null`\n    if test $? = 0\n    then\n      LIBC_INFO=\"$LIBC_INFO\n$TMP\"\n    fi\ndone\n\nPATH=../client:$PATH:/bin:/usr/bin:/usr/local/bin\nexport PATH\n\nBUGADDR=${1-$BUGmysql}\nENVIRONMENT=`uname -a`\n\n: ${USER=${LOGNAME-`whoami`}}\n\nCOMMAND=`echo $0|sed 's%.*/\\([^/]*\\)%\\1%'`\n\n# Try to create a secure tmpfile\numask 077\nTEMPDIR=/tmp/mysqlbug-$$\nmkdir $TEMPDIR || (echo \"can not create directory in /tmp, aborting\"; exit 1;)\nTEMP=${TEMPDIR}/mysqlbug\n\ntrap 'rm -f $TEMP $TEMP.x; rmdir $TEMPDIR; exit 1' 1 2 3 13 15\ntrap 'rm -f $TEMP $TEMP.x; rmdir $TEMPDIR' 0\n\n# How to read the passwd database.\nPASSWD=\"cat /etc/passwd\"\n\nif test -f /usr/lib/sendmail\nthen\n  MAIL_AGENT=\"/usr/lib/sendmail -oi -t\"\nelif test -f /usr/sbin/sendmail\nthen\n  MAIL_AGENT=\"/usr/sbin/sendmail -oi -t\"\nelse\n  MAIL_AGENT=\"rmail $BUGmysql\"\nfi\n\n# Figure out how to echo a string without a trailing newline\nN=`echo 'hi there\\c'`\ncase \"$N\" in\n  *c)\tECHON1='echo -n' ECHON2= ;;\n  *)\tECHON1=echo ECHON2='\\c' ;;\nesac\n\n# Find out the name of the originator of this PR.\nif test -n \"$NAME\" \nthen\n  ORIGINATOR=\"$NAME\"\nelif test -f $HOME/.fullname\nthen\n  ORIGINATOR=\"`sed -e '1q' $HOME/.fullname`\"\nelse\n  # Must use temp file due to incompatibilities in quoting behavior\n  # and to protect shell metacharacters in the expansion of $LOGNAME\n  $PASSWD | grep \"^$LOGNAME:\" | awk -F: '{print $5}' | sed -e 's/,.*//' > $TEMP\n  ORIGINATOR=\"`cat $TEMP`\"\n  rm -f $TEMP\nfi\n\nif test -n \"$ORGANIZATION\"\nthen\n  if test -f \"$ORGANIZATION\"\n  then\n    ORGANIZATION=\"`cat $ORGANIZATION`\"\n  fi\nelse\n  if test -f $HOME/.organization\n  then\n    ORGANIZATION=\"`cat $HOME/.organization`\"\n  elif test -f $HOME/.signature\n  then\n    ORGANIZATION=`sed -e \"s/^/  /\" $HOME/.signature; echo \">\"`\n  fi\nfi\n\nPATH_DIRS=`echo $PATH | sed -e 's/^:/. /' -e 's/:$/ ./' -e 's/::/ . /g' -e 's/:/ /g' `\n\nwhich_1 ()\n{\n  for cmd\n  do\n    # Absolute path ?. \n    if expr \"x$cmd\" : \"x/\" > /dev/null\n    then\n      echo \"$cmd\"\n      exit 0\n    else\n      for d in $PATH_DIRS\n      do\n\tfile=\"$d/$cmd\"\n\tif test -x \"$file\" -a ! -d \"$file\"\n\tthen\n\t  echo \"$file\"\n\t  exit 0\n\tfi\n      done\n    fi\n  done\n  exit 1\n}\n\nchange_editor ()\n{\n  echo \"You can change editor by setting the environment variable VISUAL.\"\n  echo \"If your shell is a bourne shell (sh) do\"\n  echo \"VISUAL=your_editors_name; export VISUAL\"\n  echo \"If your shell is a C shell (csh) do\"\n  echo \"setenv VISUAL your_editors_name\"\n}\n\n# If they don't have a preferred editor set, then use emacs\nif test -z \"$VISUAL\"\nthen\n  if test -z \"$EDITOR\"\n  then\n    # Honor debian sensible-editor\n    if test -x \"/usr/bin/sensible-editor\"\n    then\n      EDIT=/usr/bin/sensible-editor\n    else\n      EDIT=emacs\n    fi\n  else\n    EDIT=\"$EDITOR\"\n  fi\nelse\n  EDIT=\"$VISUAL\"\nfi\n\n#which_1 $EDIT\nused_editor=`which_1 $EDIT`\n\necho \"test -x $used_editor\"\nif test -x \"$used_editor\"\nthen\n  echo \"Using editor $used_editor\";\n  change_editor\n  sleep 2\nelse\n  echo \"Could not find a text editor. (tried $EDIT)\"\n  change_editor\n  exit 1\nfi\n\n# Find out some information.\nSYSTEM=`( test -f /bin/uname  && /bin/uname -a ) || \\\n        ( test -f /usr/bin/uname  && /usr/bin/uname -a ) || echo \"\"`\nARCH=`test -f /bin/arch  && /bin/arch`\nMACHINE=`test -f /bin/machine  && /bin/machine`\nFILE_PATHS=\n\nfor cmd in perl make gmake gcc cc\ndo\n  file=`which_1 $cmd`\n  if test $? = 0\n  then\n    if test $cmd = \"gcc\"\n    then\n      GCC_INFO=`$file -v 2>&1`\n    elif test $cmd = \"perl\"\n    then\n      PERL_INFO=`$file -v | grep -i version 2>&1`\n    fi\n    FILE_PATHS=\"$FILE_PATHS $file\"\n  fi\ndone\n\nadmin=`which_1 mysqladmin`\nMYSQL_SERVER=\nif test -x \"$admin\"\nthen\n  MYSQL_SERVER=`$admin version 2> /dev/null`\n  if test \"$?\" = \"1\"\n  then\n    MYSQL_SERVER=\"\"\n  fi\nfi\n\nSUBJECT_C=\"[50 character or so descriptive subject here (for reference)]\"\nORGANIZATION_C='<organization of PR author (multiple lines)>'\nLICENCE_C='[none | licence | email support | extended email support ]'\nSYNOPSIS_C='<synopsis of the problem (one line)>'\nSEVERITY_C='<[ non-critical | serious | critical ] (one line)>'\nPRIORITY_C='<[ low | medium | high ] (one line)>'\nCLASS_C='<[ sw-bug | doc-bug | change-request | support ] (one line)>'\nRELEASE_C='<release number or tag (one line)>'\nENVIRONMENT_C='<machine, os, target, libraries (multiple lines)>'\nDESCRIPTION_C='<precise description of the problem (multiple lines)>'\nHOW_TO_REPEAT_C='<code/input/activities to reproduce the problem (multiple lines)>'\nFIX_C='<how to correct or work around the problem, if known (multiple lines)>'\n\n\ncat > $TEMP <<EOF\nSEND-PR: -*- send-pr -*-\nSEND-PR: Lines starting with \\`SEND-PR' will be removed automatically, as\nSEND-PR: will all comments (text enclosed in \\`<' and \\`>').\nSEND-PR:\nFrom: ${USER}\nTo: ${BUGADDR}\nSubject: $SUBJECT_C\n\n>Description:\n\t$DESCRIPTION_C\n>How-To-Repeat:\n\t$HOW_TO_REPEAT_C\n>Fix:\n\t$FIX_C\n\n>Submitter-Id:\t<submitter ID>\n>Originator:\t${ORIGINATOR}\n>Organization:\n${ORGANIZATION- $ORGANIZATION_C}\n>MySQL support: $LICENCE_C\n>Synopsis:\t$SYNOPSIS_C\n>Severity:\t$SEVERITY_C\n>Priority:\t$PRIORITY_C\n>Category:\tmysql\n>Class:\t\t$CLASS_C\n>Release:\tmysql-${VERSION} ($COMPILATION_COMMENT)\n`test -n \"$MYSQL_SERVER\" && echo \">Server: $MYSQL_SERVER\"`\n>C compiler:    @CC_VERSION@\n>C++ compiler:  @CXX_VERSION@\n>Environment:\n\t$ENVIRONMENT_C\n`test -n \"$SYSTEM\"  && echo \"System: $SYSTEM\"`\n`test -n \"$ARCH\"  && echo \"Architecture: $ARCH\"`\n`test -n \"$MACHINE\"  && echo \"Machine: $MACHINE\"`\n`test -n \"$FILE_PATHS\"  && echo \"Some paths: $FILE_PATHS\"`\n`test -n \"$GCC_INFO\"  && echo \"GCC: $GCC_INFO\"`\n`test -n \"$COMP_CALL_INFO\"  && echo \"Compilation info (call): $COMP_CALL_INFO\"`\n`test -n \"$COMP_RUN_INFO\"   && echo \"Compilation info (used): $COMP_RUN_INFO\"`\n`test -n \"$LIBC_INFO\"  && echo \"LIBC: $LIBC_INFO\"`\n`test -n \"$CONFIGURE_LINE\"  && echo \"Configure command: $CONFIGURE_LINE\"`\n`test -n \"$PERL_INFO\"  && echo \"Perl: $PERL_INFO\"`\nEOF\n\nchmod u+w $TEMP\ncp $TEMP $TEMP.x\n\neval $EDIT $TEMP\n\nif cmp -s $TEMP $TEMP.x\nthen\n  echo \"File not changed, no bug report submitted.\"\n  mv -f $TEMP /tmp/failed-mysql-bugreport\n  echo \"The raw bug report exists in /tmp/failed-mysql-bugreport\"\n  echo \"If you use this remember that the first lines of the report are now a lie..\"\n  exit 1\nfi\n\n#\f\n#       Check the enumeration fields\n\n# This is a \"sed-subroutine\" with one keyword parameter\n# (with workaround for Sun sed bug)\n#\nSED_CMD='\n/$PATTERN/{\ns|||\ns|<.*>||\ns|^[ \t]*||\ns|[ \t]*$||\np\nq\n}'\n\n\nwhile :; do\n  CNT=0\n\n  #\n  # 1) Severity\n  #\n  PATTERN=\">Severity:\"\n  SEVERITY=`eval sed -n -e \"\\\"$SED_CMD\\\"\" $TEMP`\n  case \"$SEVERITY\" in\n    \"\"|non-critical|serious|critical) CNT=`expr $CNT + 1` ;;\n    *)  echo \"$COMMAND: \\`$SEVERITY' is not a valid value for \\`Severity'.\"\n  esac\n  #\n  # 2) Priority\n  #\n  PATTERN=\">Priority:\"\n  PRIORITY=`eval sed -n -e \"\\\"$SED_CMD\\\"\" $TEMP`\n  case \"$PRIORITY\" in\n    \"\"|low|medium|high) CNT=`expr $CNT + 1` ;;\n    *)  echo \"$COMMAND: \\`$PRIORITY' is not a valid value for \\`Priority'.\"\n  esac\n  #\n  # 3) Class\n  #\n  PATTERN=\">Class:\"\n  CLASS=`eval sed -n -e \"\\\"$SED_CMD\\\"\" $TEMP`\n  case \"$CLASS\" in\n    \"\"|sw-bug|doc-bug|change-request|support) CNT=`expr $CNT + 1` ;;\n    *)  echo \"$COMMAND: \\`$CLASS' is not a valid value for \\`Class'.\"\n  esac\n\n  #\n  # 4) Synopsis\n  #\n  VALUE=`grep \"^>Synopsis:\" $TEMP | sed 's/>Synopsis:[ \t]*//'`\n  case \"$VALUE\" in\n    \"$SYNOPSIS_C\")  echo \"$COMMAND: \\`$VALUE' is not a valid value for \\`Synopsis'.\" ;;\n    *) CNT=`expr $CNT + 1` \n  esac\n\n  test $CNT -lt 4  &&\n    echo \"Errors were found with the problem report.\"\n\n\n  #       Check if subject of mail was changed, if not, use Synopsis field\n  #\n  subject=`grep \"^Subject\" $TEMP| sed 's/^Subject:[ \t]*//'`\n  if [ X\"$subject\" = X\"$SUBJECT_C\" -o X\"$subject\" = X\"$SYNOPSIS_C\" ]; then\n    subject=`grep Synopsis $TEMP | sed 's/>Synopsis:[     ]*//'`\n    sed \"s/^Subject:[ \t]*.*/Subject: $subject/\" $TEMP > $TEMP.tmp\n    mv -f $TEMP.tmp $TEMP\n  fi\n\n  while :; do\n    $ECHON1 \"a)bort, e)dit or s)end? $ECHON2\"\n    read input\n    case \"$input\" in\n      a*)\n\techo \"$COMMAND: problem report saved in $HOME/dead.mysqlbug.\"\n\tcat $TEMP >> $HOME/dead.mysqlbug\n        xs=1; exit\n        ;;\n      e*)\n        eval $EDIT $TEMP\n        continue 2\n        ;;\n      s*)\n        break 2\n        ;;\n    esac\n  done\ndone\n#\n#       Remove comments and send the problem report\n#       (we have to use patterns, where the comment contains regex chars)\n#\n# /^>Originator:/s;$ORIGINATOR;;\nsed  -e \"\n/^SEND-PR:/d\n/^>Organization:/,/^>[A-Za-z-]*:/s;$ORGANIZATION_C;;\n/^>Confidential:/s;<.*>;;\n/^>Synopsis:/s;$SYNOPSIS_C;;\n/^>Severity:/s;<.*>;;\n/^>Priority:/s;<.*>;;\n/^>Class:/s;<.*>;;\n/^>Release:/,/^>[A-Za-z-]*:/s;$RELEASE_C;;\n/^>Environment:/,/^>[A-Za-z-]*:/s;$ENVIRONMENT_C;;\n/^>Description:/,/^>[A-Za-z-]*:/s;$DESCRIPTION_C;;\n/^>How-To-Repeat:/,/^>[A-Za-z-]*:/s;$HOW_TO_REPEAT_C;;\n/^>Fix:/,/^>[A-Za-z-]*:/s;$FIX_C;;\n\" $TEMP > $TEMP.x\n\nif $MAIL_AGENT < $TEMP.x\nthen\n  echo \"$COMMAND: problem report sent\"\n  xs=0; exit\nelse\n  echo \"$COMMAND: mysterious mail failure, report not sent.\"\n  echo \"$COMMAND: problem report saved in $HOME/dead.mysqlbug.\"\n  cat $TEMP >> $HOME/dead.mysqlbug\nfi\n\nexit 0\n", "num_lines": 408}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n\n# Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# mysqldumpslow - parse and summarize the MySQL slow query log\n\n# Original version by Tim Bunce, sometime in 2000.\n# Further changes by Tim Bunce, 8th March 2001.\n# Handling of strings with \\ and double '' by Monty 11 Aug 2001.\n\nuse strict;\nuse Getopt::Long;\n\n# t=time, l=lock time, r=rows\n# at, al, and ar are the corresponding averages\n\nmy %opt = (\n    s => 'at',\n    h => '*',\n);\n\nGetOptions(\\%opt,\n    'v|verbose+',# verbose\n    'help+',\t# write usage info\n    'd|debug+',\t# debug\n    's=s',\t# what to sort by (al, at, ar, c, t, l, r)\n    'r!',\t# reverse the sort order (largest last instead of first)\n    't=i',\t# just show the top n queries\n    'a!',\t# don't abstract all numbers to N and strings to 'S'\n    'n=i',\t# abstract numbers with at least n digits within names\n    'g=s',\t# grep: only consider stmts that include this string\n    'h=s',\t# hostname of db server for *-slow.log filename (can be wildcard)\n    'i=s',\t# name of server instance (if using mysql.server startup script)\n    'l!',\t# don't subtract lock time from total time\n) or usage(\"bad option\");\n\n$opt{'help'} and usage();\n\nunless (@ARGV) {\n    my $defaults   = `my_print_defaults mysqld`;\n    my $basedir = ($defaults =~ m/--basedir=(.*)/)[0]\n\tor die \"Can't determine basedir from 'my_print_defaults mysqld' output: $defaults\";\n    warn \"basedir=$basedir\\n\" if $opt{v};\n\n    my $datadir = ($defaults =~ m/--datadir=(.*)/)[0];\n    my $slowlog = ($defaults =~ m/--slow-query-log-file=(.*)/)[0];\n    if (!$datadir or $opt{i}) {\n\t# determine the datadir from the instances section of /etc/my.cnf, if any\n\tmy $instances  = `my_print_defaults instances`;\n\tdie \"Can't determine datadir from 'my_print_defaults mysqld' output: $defaults\"\n\t    unless $instances;\n\tmy @instances = ($instances =~ m/^--(\\w+)-/mg);\n\tdie \"No -i 'instance_name' specified to select among known instances: @instances.\\n\"\n\t    unless $opt{i};\n\tdie \"Instance '$opt{i}' is unknown (known instances: @instances)\\n\"\n\t    unless grep { $_ eq $opt{i} } @instances;\n\t$datadir = ($instances =~ m/--$opt{i}-datadir=(.*)/)[0]\n\t    or die \"Can't determine --$opt{i}-datadir from 'my_print_defaults instances' output: $instances\";\n\twarn \"datadir=$datadir\\n\" if $opt{v};\n    }\n\n    if ( -f $slowlog ) {\n        @ARGV = ($slowlog);\n        die \"Can't find '$slowlog'\\n\" unless @ARGV;\n    } else {\n        @ARGV = <$datadir/$opt{h}-slow.log>;\n        die \"Can't find '$datadir/$opt{h}-slow.log'\\n\" unless @ARGV;\n    }\n}\n\nwarn \"\\nReading mysql slow query log from @ARGV\\n\";\n\nmy @pending;\nmy %stmt;\n$/ = \";\\n#\";\t\t# read entire statements using paragraph mode\nwhile ( defined($_ = shift @pending) or defined($_ = <>) ) {\n    warn \"[[$_]]\\n\" if $opt{d};\t# show raw paragraph being read\n\n    my @chunks = split /^\\/.*Version.*started with[\\000-\\377]*?Time.*Id.*Command.*Argument.*\\n/m;\n    if (@chunks > 1) {\n\tunshift @pending, map { length($_) ? $_ : () } @chunks;\n\twarn \"<<\".join(\">>\\n<<\",@chunks).\">>\" if $opt{d};\n\tnext;\n    }\n\n    s/^#? Time: \\d{6}\\s+\\d+:\\d+:\\d+.*\\n//;\n    my ($user,$host,$dummy,$thread_id) = s/^#? User\\@Host:\\s+(\\S+)\\s+\\@\\s+(\\S+)\\s+\\S+(\\s+Id:\\s+(\\d+))?.*\\n// ? ($1,$2,$3,$4) : ('','','','','');\n\n    s/^# Query_time: ([0-9.]+)\\s+Lock_time: ([0-9.]+)\\s+Rows_sent: ([0-9.]+).*\\n//;\n    my ($t, $l, $r) = ($1, $2, $3);\n    $t -= $l unless $opt{l};\n\n    # remove fluff that mysqld writes to log when it (re)starts:\n    s!^/.*Version.*started with:.*\\n!!mg;\n    s!^Tcp port: \\d+  Unix socket: \\S+\\n!!mg;\n    s!^Time.*Id.*Command.*Argument.*\\n!!mg;\n\n    s/^use \\w+;\\n//;\t# not consistently added\n    s/^SET timestamp=\\d+;\\n//;\n\n    s/^[ \t]*\\n//mg;\t# delete blank lines\n    s/^[ \t]*/  /mg;\t# normalize leading whitespace\n    s/\\s*;\\s*(#\\s*)?$//;\t# remove trailing semicolon(+newline-hash)\n\n    next if $opt{g} and !m/$opt{g}/io;\n\n    unless ($opt{a}) {\n\ts/\\b\\d+\\b/N/g;\n\ts/\\b0x[0-9A-Fa-f]+\\b/N/g;\n        s/''/'S'/g;\n        s/\"\"/\"S\"/g;\n        s/(\\\\')//g;\n        s/(\\\\\")//g;\n        s/'[^']+'/'S'/g;\n        s/\"[^\"]+\"/\"S\"/g;\n\t# -n=8: turn log_20001231 into log_NNNNNNNN\n\ts/([a-z_]+)(\\d{$opt{n},})/$1.('N' x length($2))/ieg if $opt{n};\n\t# abbreviate massive \"in (...)\" statements and similar\n\ts!(([NS],){100,})!sprintf(\"$2,{repeated %d times}\",length($1)/2)!eg;\n    }\n\n    my $s = $stmt{$_} ||= { users=>{}, hosts=>{} };\n    $s->{c} += 1;\n    $s->{t} += $t;\n    $s->{l} += $l;\n    $s->{r} += $r;\n    $s->{users}->{$user}++ if $user;\n    $s->{hosts}->{$host}++ if $host;\n\n    warn \"{{$_}}\\n\\n\" if $opt{d};\t# show processed statement string\n}\n\nforeach (keys %stmt) {\n    my $v = $stmt{$_} || die;\n    my ($c, $t, $l, $r) = @{ $v }{qw(c t l r)};\n    $v->{at} = $t / $c;\n    $v->{al} = $l / $c;\n    $v->{ar} = $r / $c;\n}\n\nmy @sorted = sort { $stmt{$b}->{$opt{s}} <=> $stmt{$a}->{$opt{s}} } keys %stmt;\n@sorted = @sorted[0 .. $opt{t}-1] if $opt{t};\n@sorted = reverse @sorted         if $opt{r};\n\nforeach (@sorted) {\n    my $v = $stmt{$_} || die;\n    my ($c, $t,$at, $l,$al, $r,$ar) = @{ $v }{qw(c t at l al r ar)};\n    my @users = keys %{$v->{users}};\n    my $user  = (@users==1) ? $users[0] : sprintf \"%dusers\",scalar @users;\n    my @hosts = keys %{$v->{hosts}};\n    my $host  = (@hosts==1) ? $hosts[0] : sprintf \"%dhosts\",scalar @hosts;\n    printf \"Count: %d  Time=%.2fs (%ds)  Lock=%.2fs (%ds)  Rows=%.1f (%d), $user\\@$host\\n%s\\n\\n\",\n\t    $c, $at,$t, $al,$l, $ar,$r, $_;\n}\n\nsub usage {\n    my $str= shift;\n    my $text= <<HERE;\nUsage: mysqldumpslow [ OPTS... ] [ LOGS... ]\n\nParse and summarize the MySQL slow query log. Options are\n\n  --verbose    verbose\n  --debug      debug\n  --help       write this text to standard output\n\n  -v           verbose\n  -d           debug\n  -s ORDER     what to sort by (al, at, ar, c, l, r, t), 'at' is default\n                al: average lock time\n                ar: average rows sent\n                at: average query time\n                 c: count\n                 l: lock time\n                 r: rows sent\n                 t: query time  \n  -r           reverse the sort order (largest last instead of first)\n  -t NUM       just show the top n queries\n  -a           don't abstract all numbers to N and strings to 'S'\n  -n NUM       abstract numbers with at least n digits within names\n  -g PATTERN   grep: only consider stmts that include this string\n  -h HOSTNAME  hostname of db server for *-slow.log filename (can be wildcard),\n               default is '*', i.e. match all\n  -i NAME      name of server instance (if using mysql.server startup script)\n  -l           don't subtract lock time from total time\n\nHERE\n    if ($str) {\n      print STDERR \"ERROR: $str\\n\\n\";\n      print STDERR $text;\n      exit 1;\n    } else {\n      print $text;\n      exit 0;\n    }\n}\n", "num_lines": 212}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n\n# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\nuse Getopt::Long;\nuse POSIX qw(strftime getcwd);\nuse File::Path qw(mkpath);\n\n$|=1;\n$VER=\"2.16\";\n\nmy @defaults_options;   #  Leading --no-defaults, --defaults-file, etc.\n\n$opt_example       = 0;\n$opt_help          = 0;\n$opt_log           = undef();\n$opt_mysqladmin    = \"@bindir@/mysqladmin\";\n$opt_mysqld        = \"@libexecdir@/mysqld\";\n$opt_no_log        = 0;\n$opt_password      = undef();\n$opt_tcp_ip        = 0;\n$opt_user          = \"root\";\n$opt_version       = 0;\n$opt_silent        = 0;\n$opt_verbose       = 0;\n\nmy $my_print_defaults_exists= 1;\nmy $logdir= undef();\n\nmy ($mysqld, $mysqladmin, $groupids, $homedir, $my_progname);\n\n$homedir = $ENV{HOME};\n$my_progname = $0;\n$my_progname =~ s/.*[\\/]//;\n\n\nif (defined($ENV{UMASK})) {\n  my $UMASK = $ENV{UMASK};\n  my $m;\n  my $fmode = \"0640\";\n\n  if(($UMASK =~ m/[^0246]/) || ($UMASK =~ m/^[^0]/) || (length($UMASK) != 4)) {\n    printf(\"UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\\n\");\n    printf(\"The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\\n\"); }\n  else {\n    $fmode= substr $UMASK, 2, 2;\n    $fmode= \"06${fmode}\"; }\n\n  if($fmode != $UMASK) {\n    printf(\"UMASK corrected from $UMASK to $fmode ...\\n\"); }\n\n  $fmode= oct($fmode);\n\n  umask($fmode);\n}\n\n\nmain();\n\n####\n#### main sub routine\n####\n\nsub main\n{\n  my $flag_exit= 0;\n\n  if (!defined(my_which(my_print_defaults)))\n  {\n    # We can't throw out yet, since --version, --help, or --example may\n    # have been given\n    print \"WARNING: my_print_defaults command not found.\\n\";\n    print \"Please make sure you have this command available and\\n\";\n    print \"in your path. The command is available from the latest\\n\";\n    print \"MySQL distribution.\\n\";\n    $my_print_defaults_exists= 0;\n  }\n\n  # Remove leading defaults options from @ARGV\n  while (@ARGV > 0)\n  {\n    last unless $ARGV[0] =~\n      /^--(?:no-defaults$|(?:defaults-file|defaults-extra-file)=)/;\n    push @defaults_options, (shift @ARGV);\n  }\n\n  foreach (@defaults_options)\n  {\n    $_ = quote_shell_word($_);\n  }\n\n  # Add [mysqld_multi] options to front of @ARGV, ready for GetOptions()\n  unshift @ARGV, defaults_for_group('mysqld_multi');\n\n  # We've already handled --no-defaults, --defaults-file, etc.\n  if (!GetOptions(\"help\", \"example\", \"version\", \"mysqld=s\", \"mysqladmin=s\",\n                  \"user=s\", \"password=s\", \"log=s\", \"no-log\",\n                  \"tcp-ip\",  \"silent\", \"verbose\"))\n  {\n    $flag_exit= 1;\n  }\n  usage() if ($opt_help);\n\n  if ($opt_verbose && $opt_silent)\n  {\n    print \"Both --verbose and --silent have been given. Some of the warnings \";\n    print \"will be disabled\\nand some will be enabled.\\n\\n\";\n  }\n\n  init_log() if (!defined($opt_log));\n  $groupids = $ARGV[1];\n  if ($opt_version)\n  {\n    print \"$my_progname version $VER by Jani Tolonen\\n\";\n    exit(0);\n  }\n  example() if ($opt_example);\n  if ($flag_exit)\n  {\n    print \"Error with an option, see $my_progname --help for more info.\\n\";\n    exit(1);\n  }\n  if (!defined(my_which(my_print_defaults)))\n  {\n    print \"ABORT: Can't find command 'my_print_defaults'.\\n\";\n    print \"This command is available from the latest MySQL\\n\";\n    print \"distribution. Please make sure you have the command\\n\";\n    print \"in your PATH.\\n\";\n    exit(1);\n  }\n  usage() if (!defined($ARGV[0]) ||\n\t      (!($ARGV[0] =~ m/^start$/i) &&\n\t       !($ARGV[0] =~ m/^stop$/i) &&\n\t       !($ARGV[0] =~ m/^reload$/i) &&\n\t       !($ARGV[0] =~ m/^report$/i)));\n\n  if (!$opt_no_log)\n  {\n    w2log(\"$my_progname log file version $VER; run: \",\n\t  \"$opt_log\", 1, 0);\n  }\n  else\n  {\n    print \"$my_progname log file version $VER; run: \";\n    print strftime \"%a %b %e %H:%M:%S %Y\", localtime;\n    print \"\\n\";\n  }\n  if (($ARGV[0] =~ m/^start$/i) || ($ARGV[0] =~ m/^reload$/i))\n  {\n    if (!defined(($mysqld= my_which($opt_mysqld))) && $opt_verbose)\n    {\n      print \"WARNING: Couldn't find the default mysqld binary.\\n\";\n      print \"Tried: $opt_mysqld\\n\";\n      print \"This is OK, if you are using option \\\"mysqld=...\\\" in \";\n      print \"groups [mysqldN] separately for each.\\n\\n\";\n    }\n    if ($ARGV[0] =~ m/^start$/i) {\n      start_mysqlds();\n    } elsif ($ARGV[0] =~ m/^reload$/i) {\n      reload_mysqlds();\n    }\n  }\n  else\n  {\n    if (!defined(($mysqladmin= my_which($opt_mysqladmin))) && $opt_verbose)\n    {\n      print \"WARNING: Couldn't find the default mysqladmin binary.\\n\";\n      print \"Tried: $opt_mysqladmin\\n\";\n      print \"This is OK, if you are using option \\\"mysqladmin=...\\\" in \";\n      print \"groups [mysqldN] separately for each.\\n\\n\";\n    }\n    if ($ARGV[0] =~ m/^report$/i)\n    {\n      report_mysqlds();\n    }\n    else\n    {\n      stop_mysqlds();\n    }\n  }\n}\n\n#\n# Quote word for shell\n#\n\nsub quote_shell_word\n{\n  my ($option)= @_;\n\n  $option =~ s!([^\\w=./-])!\\\\$1!g;\n  return $option;\n}\n\nsub defaults_for_group\n{\n  my ($group) = @_;\n\n  return () unless $my_print_defaults_exists;\n\n  my $com= join ' ', 'my_print_defaults', @defaults_options, $group;\n  my @defaults = `$com`;\n  chomp @defaults;\n  return @defaults;\n}\n\n####\n#### Init log file. Check for appropriate place for log file, in the following\n#### order:  my_print_defaults mysqld datadir, @datadir@\n####\n\nsub init_log\n{\n  foreach my $opt (defaults_for_group('mysqld'))\n  {\n    if ($opt =~ m/^--datadir=(.*)/ && -d \"$1\" && -w \"$1\")\n    {\n      $logdir= $1;\n    }\n  }\n  if (!defined($logdir))\n  {\n    $logdir= \"@datadir@\" if (-d \"@datadir@\" && -w \"@datadir@\");\n  }\n  if (!defined($logdir))\n  {\n    # Log file was not specified and we could not log to a standard place,\n    # so log file be disabled for now.\n    if (!$opt_silent)\n    {\n      print \"WARNING: Log file disabled. Maybe directory or file isn't writable?\\n\";\n    }\n    $opt_no_log= 1;\n  }\n  else\n  {\n    $opt_log= \"$logdir/mysqld_multi.log\";\n  }\n}\n\n####\n#### Report living and not running MySQL servers\n####\n\nsub report_mysqlds\n{\n  my (@groups, $com, $i, @options, $pec);\n\n  print \"Reporting MySQL servers\\n\";\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nReporting MySQL servers\",\"$opt_log\",0,0);\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $com= get_mysqladmin_options($i, @groups);\n    $com.= \" ping >> /dev/null 2>&1\";\n    system($com);\n    $pec = $? >> 8;\n    if ($pec)\n    {\n      print \"MySQL server from group: $groups[$i] is not running\\n\";\n      if (!$opt_no_log)\n      {\n\tw2log(\"MySQL server from group: $groups[$i] is not running\",\n\t      \"$opt_log\", 0, 0);\n      }\n    }\n    else\n    {\n      print \"MySQL server from group: $groups[$i] is running\\n\";\n      if (!$opt_no_log)\n      {\n\tw2log(\"MySQL server from group: $groups[$i] is running\",\n\t      \"$opt_log\", 0, 0);\n      }\n    }\n  }\n  if (!$i)\n  {\n    print \"No groups to be reported (check your GNRs)\\n\";\n    if (!$opt_no_log)\n    {\n      w2log(\"No groups to be reported (check your GNRs)\", \"$opt_log\", 0, 0);\n    }\n  }\n}\n\n####\n#### start multiple servers\n####\n\nsub start_mysqlds()\n{\n  my (@groups, $com, $tmp, $i, @options, $j, $mysqld_found, $info_sent);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nStarting MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nStarting MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    @options = defaults_for_group($groups[$i]);\n\n    $basedir_found= 0; # The default\n    $mysqld_found= 1; # The default\n    $mysqld_found= 0 if (!length($mysqld));\n    $com= \"$mysqld\";\n    for ($j = 0, $tmp= \"\"; defined($options[$j]); $j++)\n    {\n      if (\"--datadir=\" eq substr($options[$j], 0, 10)) {\n        $datadir = $options[$j];\n        $datadir =~ s/\\-\\-datadir\\=//;\n        eval { mkpath($datadir) };\n        if ($@) {\n          print \"FATAL ERROR: Cannot create data directory $datadir: $!\\n\";\n          exit(1);\n        }\n        if (! -d $datadir.\"/mysql\") {\n          if (-w $datadir) {\n            print \"\\n\\nInstalling new database in $datadir\\n\\n\";\n            $install_cmd=\"@bindir@/mysql_install_db \";\n            $install_cmd.=\"--user=mysql \";\n            $install_cmd.=\"--datadir=$datadir\";\n            system($install_cmd);\n          } else {\n            print \"\\n\";\n            print \"FATAL ERROR: Tried to create mysqld under group [$groups[$i]],\\n\";\n            print \"but the data directory is not writable.\\n\";\n            print \"data directory used: $datadir\\n\";\n            exit(1);\n          }\n        }\n\n        if (! -d $datadir.\"/mysql\") {\n          print \"\\n\";\n          print \"FATAL ERROR: Tried to start mysqld under group [$groups[$i]],\\n\";\n          print \"but no data directory was found or could be created.\\n\";\n          print \"data directory used: $datadir\\n\";\n          exit(1);\n        }\n      }\n\n      if (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n      {\n\t# catch this and ignore\n      }\n      elsif (\"--mysqld=\" eq substr($options[$j], 0, 9))\n      {\n\t$options[$j]=~ s/\\-\\-mysqld\\=//;\n\t$com= $options[$j];\n        $mysqld_found= 1;\n      }\n      elsif (\"--basedir=\" eq substr($options[$j], 0, 10))\n      {\n        $basedir= $options[$j];\n        $basedir =~ s/^--basedir=//;\n        $basedir_found= 1;\n        $options[$j]= quote_shell_word($options[$j]);\n        $tmp.= \" $options[$j]\";\n      }\n      else\n      {\n\t$options[$j]= quote_shell_word($options[$j]);\n\t$tmp.= \" $options[$j]\";\n      }\n    }\n    if ($opt_verbose && $com =~ m/\\/(safe_mysqld|mysqld_safe)$/ && !$info_sent)\n    {\n      print \"WARNING: $1 is being used to start mysqld. In this case you \";\n      print \"may need to pass\\n\\\"ledir=...\\\" under groups [mysqldN] to \";\n      print \"$1 in order to find the actual mysqld binary.\\n\";\n      print \"ledir (library executable directory) should be the path to the \";\n      print \"wanted mysqld binary.\\n\\n\";\n      $info_sent= 1;\n    }\n    $com.= $tmp;\n    $com.= \" >> $opt_log 2>&1\" if (!$opt_no_log);\n    $com.= \" &\";\n    if (!$mysqld_found)\n    {\n      print \"\\n\";\n      print \"FATAL ERROR: Tried to start mysqld under group [$groups[$i]], \";\n      print \"but no mysqld binary was found.\\n\";\n      print \"Please add \\\"mysqld=...\\\" in group [mysqld_multi], or add it to \";\n      print \"group [$groups[$i]] separately.\\n\";\n      exit(1);\n    }\n    if ($basedir_found)\n    {\n      $curdir=getcwd();\n      chdir($basedir) or die \"Can't change to datadir $basedir\";\n    }\n    system($com);\n    if ($basedir_found)\n    {\n      chdir($curdir) or die \"Can't change back to original dir $curdir\";\n    }\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be started (check your GNRs)\",\n\t  \"$opt_log\", 0, 0);\n  }\n}\n\n####\n#### reload multiple servers\n####\n\nsub reload_mysqlds()\n{\n  my (@groups, $com, $tmp, $i, @options, $j);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nReloading MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nReloading MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $mysqld_server = $mysqld;\n    @options = defaults_for_group($groups[$i]);\n\n    for ($j = 0, $tmp= \"\"; defined($options[$j]); $j++)\n    {\n      if (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n      {\n        # catch this and ignore\n      }\n      elsif (\"--mysqld=\" eq substr($options[$j], 0, 9))\n      {\n        $options[$j] =~ s/\\-\\-mysqld\\=//;\n        $mysqld_server = $options[$j];\n      }\n      elsif (\"--pid-file=\" eq substr($options[$j], 0, 11))\n      {\n        $options[$j] =~ s/\\-\\-pid-file\\=//;\n        $pid_file = $options[$j];\n      }\n    }\n    $com = \"killproc -p $pid_file -HUP $mysqld_server\";\n    system($com);\n\n    $com = \"touch $pid_file\";\n    system($com);\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be reloaded (check your GNRs)\",\n         \"$opt_log\", 0, 0);\n  }\n}\n\n###\n#### stop multiple servers\n####\n\nsub stop_mysqlds()\n{\n  my (@groups, $com, $i, @options);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nStopping MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nStopping MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $com= get_mysqladmin_options($i, @groups);\n    $com.= \" shutdown\";\n    $com.= \" >> $opt_log 2>&1\" if (!$opt_no_log);\n    $com.= \" &\";\n    system($com);\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be stopped (check your GNRs)\",\n\t  \"$opt_log\", 0, 0);\n  }\n}\n\n####\n#### Sub function for mysqladmin option parsing\n####\n\nsub get_mysqladmin_options\n{\n  my ($i, @groups)= @_;\n  my ($mysqladmin_found, $com, $tmp, $j);\n\n  @options = defaults_for_group($groups[$i]);\n\n  $mysqladmin_found= 1; # The default\n  $mysqladmin_found= 0 if (!length($mysqladmin));\n  $com = \"$mysqladmin\";\n  $tmp = \" -u $opt_user\";\n  if (defined($opt_password)) {\n    my $pw= $opt_password;\n    # Protect single quotes in password\n    $pw =~ s/'/'\"'\"'/g;\n    $tmp.= \" -p'$pw'\";\n  }\n  $tmp.= $opt_tcp_ip ? \" -h 127.0.0.1\" : \"\";\n  for ($j = 0; defined($options[$j]); $j++)\n  {\n    if (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n    {\n      $options[$j]=~ s/\\-\\-mysqladmin\\=//;\n      $com= $options[$j];\n      $mysqladmin_found= 1;\n    }\n    elsif ((($options[$j] =~ m/^(\\-\\-socket\\=)(.*)$/) && !$opt_tcp_ip) ||\n\t   ($options[$j] =~ m/^(\\-\\-port\\=)(.*)$/))\n    {\n      $tmp.= \" $options[$j]\";\n    }\n  }\n  if (!$mysqladmin_found)\n  {\n    print \"\\n\";\n    print \"FATAL ERROR: Tried to use mysqladmin in group [$groups[$i]], \";\n    print \"but no mysqladmin binary was found.\\n\";\n    print \"Please add \\\"mysqladmin=...\\\" in group [mysqld_multi], or \";\n    print \"in group [$groups[$i]].\\n\";\n    exit(1);\n  }\n  $com.= $tmp;\n  return $com;\n}\n\n# Return a list of option files which can be opened.  Similar, but not\n# identical, to behavior of my_search_option_files()\nsub list_defaults_files\n{\n  my %opt;\n  foreach (@defaults_options)\n  {\n    return () if /^--no-defaults$/;\n    $opt{$1} = $2 if /^--defaults-(extra-file|file)=(.*)$/;\n  }\n\n  return ($opt{file}) if exists $opt{file};\n\n  my %seen;  # Don't list the same file more than once\n  return grep { defined $_ and not $seen{$_}++ and -f $_ and -r $_ }\n              ('/etc/my.cnf',\n               '/etc/mysql/my.cnf',\n               '@sysconfdir@/my.cnf',\n               ($ENV{MYSQL_HOME} ? \"$ENV{MYSQL_HOME}/my.cnf\" : undef),\n               $opt{'extra-file'},\n               ($ENV{HOME} ? \"$ENV{HOME}/.my.cnf\" : undef));\n}\n\n\n# Takes a specification of GNRs (see --help), and returns a list of matching\n# groups which actually are mentioned in a relevant config file\nsub find_groups\n{\n  my ($raw_gids) = @_;\n\n  my %gids;\n  my @groups;\n\n  if (defined($raw_gids))\n  {\n    # Make a hash of the wanted group ids\n    foreach my $raw_gid (split ',', $raw_gids)\n    {\n      # Match 123 or 123-456\n      my ($start, $end) = ($raw_gid =~ /^\\s*(\\d+)(?:\\s*-\\s*(\\d+))?\\s*$/);\n      $end = $start if not defined $end;\n      if (not defined $start or $end < $start or $start < 0)\n      {\n        print \"ABORT: Bad GNR: $raw_gid; see $my_progname --help\\n\";\n        exit(1);\n      }\n\n      foreach my $i ($start .. $end)\n      {\n        # Use $i + 0 to normalize numbers (002 + 0 -> 2)\n        $gids{$i + 0}= 1;\n      }\n    }\n  }\n\n  my @defaults_files = list_defaults_files();\n  #warn \"@{[sort keys %gids]} -> @defaults_files\\n\";\n  foreach my $file (@defaults_files)\n  {\n    next unless open CONF, \"< $file\";\n\n    while (<CONF>)\n    {\n      if (/^\\s*\\[\\s*(mysqld)(\\d+)\\s*\\]\\s*$/)\n      {\n        #warn \"Found a group: $1$2\\n\";\n        # Use $2 + 0 to normalize numbers (002 + 0 -> 2)\n        if (not defined($raw_gids) or $gids{$2 + 0})\n        {\n          push @groups, \"$1$2\";\n        }\n      }\n    }\n\n    close CONF;\n  }\n  return @groups;\n}\n\n####\n#### w2log: Write to a logfile.\n#### 1.arg: append to the log file (given string, or from a file. if a file,\n####        file will be read from $opt_logdir)\n#### 2.arg: logfile -name (w2log assumes that the logfile is in $opt_logdir).\n#### 3.arg. 0 | 1, if true, print current date to the logfile. 3. arg will\n####        be ignored, if 1. arg is a file.\n#### 4.arg. 0 | 1, if true, first argument is a file, else a string\n####\n\nsub w2log\n{\n  my ($msg, $file, $date_flag, $is_file)= @_;\n  my (@data);\n\n  open (LOGFILE, \">>$opt_log\")\n    or die \"FATAL: w2log: Couldn't open log file: $opt_log\\n\";\n\n  if ($is_file)\n  {\n    open (FROMFILE, \"<$msg\") && (@data=<FROMFILE>) &&\n      close(FROMFILE)\n\tor die \"FATAL: w2log: Couldn't open file: $msg\\n\";\n    foreach my $line (@data)\n    {\n      print LOGFILE \"$line\";\n    }\n  }\n  else\n  {\n    print LOGFILE \"$msg\";\n    print LOGFILE strftime \"%a %b %e %H:%M:%S %Y\", localtime if ($date_flag);\n    print LOGFILE \"\\n\";\n  }\n  close (LOGFILE);\n  return;\n}\n\n####\n#### my_which is used, because we can't assume that every system has the\n#### which -command. my_which can take only one argument at a time.\n#### Return values: requested system command with the first found path,\n#### or undefined, if not found.\n####\n\nsub my_which\n{\n  my ($command) = @_;\n  my (@paths, $path);\n\n # If the argument is not 'my_print_defaults' then it would be of the format\n # <absolute_path>/<program>\n return $command if ($command ne 'my_print_defaults' && -f $command &&\n                     -x $command);\n\n  @paths = split(':', $ENV{'PATH'});\n  foreach $path (@paths)\n  {\n    $path .= \"/$command\";\n    return $path if (-f $path && -x $path);\n  }\n  return undef();\n}\n\n\n####\n#### example\n####\n\nsub example\n{\n  print <<EOF;\n# This is an example of a my.cnf file for $my_progname.\n# Usually this file is located in home dir ~/.my.cnf or /etc/my.cnf\n#\n# SOME IMPORTANT NOTES FOLLOW:\n#\n# 1.COMMON USER\n#\n#   Make sure that the MySQL user, who is stopping the mysqld services, has\n#   the same password to all MySQL servers being accessed by $my_progname.\n#   This user needs to have the 'Shutdown_priv' -privilege, but for security\n#   reasons should have no other privileges. It is advised that you create a\n#   common 'multi_admin' user for all MySQL servers being controlled by\n#   $my_progname. Here is an example how to do it:\n#\n#   GRANT SHUTDOWN ON *.* TO multi_admin\\@localhost IDENTIFIED BY 'password'\n#\n#   You will need to apply the above to all MySQL servers that are being\n#   controlled by $my_progname. 'multi_admin' will shutdown the servers\n#   using 'mysqladmin' -binary, when '$my_progname stop' is being called.\n#\n# 2.PID-FILE\n#\n#   If you are using mysqld_safe to start mysqld, make sure that every\n#   MySQL server has a separate pid-file. In order to use mysqld_safe\n#   via $my_progname, you need to use two options:\n#\n#   mysqld=/path/to/mysqld_safe\n#   ledir=/path/to/mysqld-binary/\n#\n#   ledir (library executable directory), is an option that only mysqld_safe\n#   accepts, so you will get an error if you try to pass it to mysqld directly.\n#   For this reason you might want to use the above options within [mysqld#]\n#   group directly.\n#\n# 3.DATA DIRECTORY\n#\n#   It is NOT advised to run many MySQL servers within the same data directory.\n#   You can do so, but please make sure to understand and deal with the\n#   underlying caveats. In short they are:\n#   - Speed penalty\n#   - Risk of table/data corruption\n#   - Data synchronising problems between the running servers\n#   - Heavily media (disk) bound\n#   - Relies on the system (external) file locking\n#   - Is not applicable with all table types. (Such as InnoDB)\n#     Trying so will end up with undesirable results.\n#\n# 4.TCP/IP Port\n#\n#   Every server requires one and it must be unique.\n#\n# 5.[mysqld#] Groups\n#\n#   In the example below the first and the fifth mysqld group was\n#   intentionally left out. You may have 'gaps' in the config file. This\n#   gives you more flexibility.\n#\n# 6.MySQL Server User\n#\n#   You can pass the user=... option inside [mysqld#] groups. This\n#   can be very handy in some cases, but then you need to run $my_progname\n#   as UNIX root.\n#\n# 7.A Start-up Manage Script for $my_progname\n#\n#   In the recent MySQL distributions you can find a file called\n#   mysqld_multi.server.sh. It is a wrapper for $my_progname. This can\n#   be used to start and stop multiple servers during boot and shutdown.\n#\n#   You can place the file in /etc/init.d/mysqld_multi.server.sh and\n#   make the needed symbolic links to it from various run levels\n#   (as per Linux/Unix standard). You may even replace the\n#   /etc/init.d/mysql.server script with it.\n#\n#   Before using, you must create a my.cnf file either in @sysconfdir@/my.cnf\n#   or /root/.my.cnf and add the [mysqld_multi] and [mysqld#] groups.\n#\n#   The script can be found from support-files/mysqld_multi.server.sh\n#   in MySQL distribution. (Verify the script before using)\n#\n\n[mysqld_multi]\nmysqld     = @bindir@/mysqld_safe\nmysqladmin = @bindir@/mysqladmin\nuser       = multi_admin\npassword   = my_password\n\n[mysqld2]\nsocket     = /tmp/mysql.sock2\nport       = 3307\npid-file   = @localstatedir@2/hostname.pid2\ndatadir    = @localstatedir@2\nlanguage   = @datadir@/mysql/english\nuser       = unix_user1\n\n[mysqld3]\nmysqld     = /path/to/mysqld_safe\nledir      = /path/to/mysqld-binary/\nmysqladmin = /path/to/mysqladmin\nsocket     = /tmp/mysql.sock3\nport       = 3308\npid-file   = @localstatedir@3/hostname.pid3\ndatadir    = @localstatedir@3\nlanguage   = @datadir@/mysql/swedish\nuser       = unix_user2\n\n[mysqld4]\nsocket     = /tmp/mysql.sock4\nport       = 3309\npid-file   = @localstatedir@4/hostname.pid4\ndatadir    = @localstatedir@4\nlanguage   = @datadir@/mysql/estonia\nuser       = unix_user3\n \n[mysqld6]\nsocket     = /tmp/mysql.sock6\nport       = 3311\npid-file   = @localstatedir@6/hostname.pid6\ndatadir    = @localstatedir@6\nlanguage   = @datadir@/mysql/japanese\nuser       = unix_user4\nEOF\n  exit(0);\n}\n\n####\n#### usage\n####\n\nsub usage\n{\n  print <<EOF;\n$my_progname version $VER by Jani Tolonen\n\nDescription:\n$my_progname can be used to start, reload, or stop any number of separate\nmysqld processes running in different TCP/IP ports and UNIX sockets.\n\n$my_progname can read group [mysqld_multi] from my.cnf file. You may\nwant to put options mysqld=... and mysqladmin=... there.  Since\nversion 2.10 these options can also be given under groups [mysqld#],\nwhich gives more control over different versions.  One can have the\ndefault mysqld and mysqladmin under group [mysqld_multi], but this is\nnot mandatory. Please note that if mysqld or mysqladmin is missing\nfrom both [mysqld_multi] and [mysqld#], a group that is tried to be\nused, $my_progname will abort with an error.\n\n$my_progname will search for groups named [mysqld#] from my.cnf (or\nthe given --defaults-extra-file=...), where '#' can be any positive \ninteger starting from 1. These groups should be the same as the regular\n[mysqld] group, but with those port, socket and any other options\nthat are to be used with each separate mysqld process. The number\nin the group name has another function; it can be used for starting,\nreloading, stopping, or reporting any specific mysqld server.\n\nUsage: $my_progname [OPTIONS] {start|reload|stop|report} [GNR,GNR,GNR...]\nor     $my_progname [OPTIONS] {start|reload|stop|report} [GNR-GNR,GNR,GNR-GNR,...]\n\nThe GNR means the group number. You can start, reload, stop or report any GNR,\nor several of them at the same time. (See --example) The GNRs list can\nbe comma separated or a dash combined. The latter means that all the\nGNRs between GNR1-GNR2 will be affected. Without GNR argument all the\ngroups found will either be started, reloaded, stopped, or reported. Note that\nsyntax for specifying GNRs must appear without spaces.\n\nOptions:\n\nThese options must be given before any others:\n--no-defaults      Do not read any defaults file\n--defaults-file=...  Read only this configuration file, do not read the\n                   standard system-wide and user-specific files\n--defaults-extra-file=...  Read this configuration file in addition to the\n                   standard system-wide and user-specific files\nUsing:  @{[join ' ', @defaults_options]}\n\n--example          Give an example of a config file with extra information.\n--help             Print this help and exit.\n--log=...          Log file. Full path to and the name for the log file. NOTE:\n                   If the file exists, everything will be appended.\n                   Using: $opt_log\n--mysqladmin=...   mysqladmin binary to be used for a server shutdown.\n                   Since version 2.10 this can be given within groups [mysqld#]\n                   Using: $mysqladmin\n--mysqld=...       mysqld binary to be used. Note that you can give mysqld_safe\n                   to this option also. The options are passed to mysqld. Just\n                   make sure you have mysqld in your PATH or fix mysqld_safe.\n                   Using: $mysqld\n                   Please note: Since mysqld_multi version 2.3 you can also\n                   give this option inside groups [mysqld#] in ~/.my.cnf,\n                   where '#' stands for an integer (number) of the group in\n                   question. This will be recognised as a special option and\n                   will not be passed to the mysqld. This will allow one to\n                   start different mysqld versions with mysqld_multi.\n--no-log           Print to stdout instead of the log file. By default the log\n                   file is turned on.\n--password=...     Password for mysqladmin user.\n--silent           Disable warnings.\n--tcp-ip           Connect to the MySQL server(s) via the TCP/IP port instead\n                   of the UNIX socket. This affects stopping and reporting.\n                   If a socket file is missing, the server may still be\n                   running, but can be accessed only via the TCP/IP port.\n                   By default connecting is done via the UNIX socket.\n--user=...         mysqladmin user. Using: $opt_user\n--verbose          Be more verbose.\n--version          Print the version number and exit.\nEOF\n  exit(0);\n}\n", "num_lines": 920}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!@SHELL_PATH@\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n#\n# Script to start the MySQL daemon and restart it if it dies unexpectedly\n#\n# This should be executed in the MySQL base directory if you are using a\n# binary installation that is not installed in its compile-time default\n# location\n#\n# mysql.server works by first doing a cd to the base directory and from there\n# executing mysqld_safe\n\n# Initialize script globals\nKILL_MYSQLD=1;\nMYSQLD=\nniceness=0\nmysqld_ld_preload=\nmysqld_ld_library_path=\nflush_caches=0\nnuma_interleave=0\nnuma_nodebind=\n\n# Initial logging status: error log is not open, and not using syslog\nlogging=init\nwant_syslog=0\nsyslog_tag=\nuser='@MYSQLD_USER@'\npid_file=\nerr_log=\n\nsyslog_tag_mysqld=mysqld\nsyslog_tag_mysqld_safe=mysqld_safe\n\ntrap '' 1 2 3 15\t\t\t# we shouldn't let anyone kill us\ntrap '' 13                              # not even SIGPIPE\n\n# MySQL-specific environment variable. First off, it's not really a umask,\n# it's the desired mode. Second, it follows umask(2), not umask(3) in that\n# octal needs to be explicit. Our shell might be a proper sh without printf,\n# multiple-base arithmetic, and binary arithmetic, so this will get ugly.\n# We reject decimal values to keep things at least half-sane.\numask 007                               # fallback\nUMASK=\"${UMASK-0640}\"\nfmode=`echo \"$UMASK\" | sed -e 's/[^0246]//g'`\noctalp=`echo \"$fmode\"|cut -c1`\nfmlen=`echo \"$fmode\"|wc -c|sed -e 's/ //g'`\nif [ \"x$octalp\" != \"x0\" -o \"x$UMASK\" != \"x$fmode\" -o \"x$fmlen\" != \"x5\" ]\nthen\n  fmode=0640\n  echo \"UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\" >&2\n  echo \"The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\" >&2\nfi\nfmode=`echo \"$fmode\"|cut -c3-4`\nfmode=\"6$fmode\"\nif [ \"x$UMASK\" != \"x0$fmode\" ]\nthen\n  echo \"UMASK corrected from $UMASK to 0$fmode ...\"\nfi\n\ndefaults=\ncase \"$1\" in\n    --no-defaults|--defaults-file=*|--defaults-extra-file=*)\n      defaults=\"$1\"; shift\n      ;;\nesac\n\nusage () {\n        cat <<EOF\nUsage: $0 [OPTIONS]\n  --no-defaults              Don't read the system defaults file\n  --defaults-file=FILE       Use the specified defaults file\n  --defaults-extra-file=FILE Also use defaults from the specified file\n  --ledir=DIRECTORY          Look for mysqld in the specified directory\n  --open-files-limit=LIMIT   Limit the number of open files\n  --core-file-size=LIMIT     Limit core files to the specified size\n  --timezone=TZ              Set the system timezone\n  --malloc-lib=LIB           Preload shared library LIB if available\n  --malloc-conf=OPTIONS      MALLOC_CONF env options\n  --ld-preload-lib=LIB       Preload shared library LIB\n  --mysqld=FILE              Use the specified file as mysqld\n  --mysqld-version=VERSION   Use \"mysqld-VERSION\" as mysqld\n  --nice=NICE                Set the scheduling priority of mysqld\n  --plugin-dir=DIR           Plugins are under DIR or DIR/VERSION, if\n                             VERSION is given\n  --skip-kill-mysqld         Don't try to kill stray mysqld processes\n  --syslog                   Log messages to syslog with 'logger'\n  --skip-syslog              Log messages to error log (default)\n  --syslog-tag=TAG           Pass -t \"mysqld-TAG\" to 'logger'\n  --flush-caches             Flush and purge buffers/caches\n  --numa-interleave          Run mysqld with its memory interleaved\n                             on all CPUs\n  --numa-nodebind            Run mysqld with numa binding to one socket\n\nAll other options are passed to the mysqld program.\n\nEOF\n        exit 1\n}\n\nmy_which ()\n{\n  save_ifs=\"${IFS-UNSET}\"\n  IFS=:\n  ret=0\n  for file\n  do\n    for dir in $PATH\n    do\n      if [ -f \"$dir/$file\" ]\n      then\n        echo \"$dir/$file\"\n        continue 2\n      fi\n    done\n\n\tret=1  #signal an error\n\tbreak\n  done\n\n  if [ \"$save_ifs\" = UNSET ]\n  then\n    unset IFS\n  else\n    IFS=\"$save_ifs\"\n  fi\n  return $ret  # Success\n}\n\nlog_generic () {\n  priority=\"$1\"\n  shift\n\n  msg=\"`date +'%y%m%d %H:%M:%S'` mysqld_safe $*\"\n  echo \"$msg\"\n  case $logging in\n    init) ;;  # Just echo the message, don't save it anywhere\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        true\n      else\n        echo \"$msg\" >> \"$err_log\"\n      fi\n      ;;\n    syslog) logger -t \"$syslog_tag_mysqld_safe\" -p \"$priority\" \"$*\" ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n}\n\nlog_error () {\n  log_generic daemon.error \"$@\" >&2\n}\n\nlog_notice () {\n  log_generic daemon.notice \"$@\"\n}\n\neval_log_error () {\n  local cmd=\"$1\"\n  case $logging in\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        cmd=\"$cmd > /dev/null 2>&1\"\n      else\n        cmd=\"$cmd >> \"`shell_quote_string \"$err_log\"`\" 2>&1\"\n      fi\n      ;;\n    syslog)\n      # mysqld often prefixes its messages with a timestamp, which is\n      # redundant when logging to syslog (which adds its own timestamp)\n      # However, we don't strip the timestamp with sed here, because\n      # sed buffers output (only GNU sed supports a -u (unbuffered) option)\n      # which means that messages may not get sent to syslog until the\n      # mysqld process quits.\n      cmd=\"$cmd 2>&1 | logger -t '$syslog_tag_mysqld' -p daemon.error\"\n      ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n\n  #echo \"Running mysqld: [$cmd]\"\n  eval \"$cmd\"\n}\n\nshell_quote_string() {\n  # This sed command makes sure that any special chars are quoted,\n  # so the arg gets passed exactly to the server.\n  echo \"$1\" | sed -e 's,\\([^a-zA-Z0-9/_.=-]\\),\\\\\\1,g'\n}\n\nparse_arguments() {\n  # We only need to pass arguments through to the server if we don't\n  # handle them here.  So, we collect unrecognized options (passed on\n  # the command line) into the args variable.\n  pick_args=\n  if test \"$1\" = PICK-ARGS-FROM-ARGV\n  then\n    pick_args=1\n    shift\n  fi\n\n  for arg do\n    # the parameter after \"=\", or the whole $arg if no match\n    val=`echo \"$arg\" | sed -e 's;^--[^=]*=;;'`\n    # what's before \"=\", or the whole $arg if no match\n    optname=`echo \"$arg\" | sed -e 's/^\\(--[^=]*\\)=.*$/\\1/'`\n    # replace \"_\" by \"-\" ; mysqld_safe must accept \"_\" like mysqld does.\n    optname_subst=`echo \"$optname\" | sed 's/_/-/g'`\n    arg=`echo $arg | sed \"s/^$optname/$optname_subst/\"`\n    case \"$arg\" in\n      # these get passed explicitly to mysqld\n      --basedir=*) MY_BASEDIR_VERSION=\"$val\" ;;\n      --datadir=*) DATADIR=\"$val\" ;;\n      --pid-file=*) pid_file=\"$val\" ;;\n      --plugin-dir=*) PLUGIN_DIR=\"$val\" ;;\n      --user=*) user=\"$val\"; SET_USER=1 ;;\n\n      # these might have been set in a [mysqld_safe] section of my.cnf\n      # they are added to mysqld command line to override settings from my.cnf\n      --log-error=*) err_log=\"$val\" ;;\n      --port=*) mysql_tcp_port=\"$val\" ;;\n      --socket=*) mysql_unix_port=\"$val\" ;;\n\n      # mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])!\n      --core-file-size=*) core_file_size=\"$val\" ;;\n      --ledir=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--ledir option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        ledir=\"$val\"\n        ;;\n      --malloc-lib=*) set_malloc_lib \"$val\" ;;\n      --ld-preload-lib=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--ld-preload-lib option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        add_mysqld_ld_preload \"$val\" ;;\n      --malloc-conf=*) malloc_conf_options=\"$val\" ;;\n      --mysqld=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        MYSQLD=\"$val\" ;;\n      --mysqld-version=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld-version option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        if test -n \"$val\"\n        then\n          MYSQLD=\"mysqld-$val\"\n          PLUGIN_VARIANT=\"/$val\"\n        else\n          MYSQLD=\"mysqld\"\n        fi\n        ;;\n      --nice=*) niceness=\"$val\" ;;\n      --open-files-limit=*) open_files=\"$val\" ;;\n      --open_files_limit=*) open_files=\"$val\" ;;\n      --skip-kill-mysqld*) KILL_MYSQLD=0 ;;\n      --syslog) want_syslog=1 ;;\n      --skip-syslog) want_syslog=0 ;;\n      --syslog-tag=*) syslog_tag=\"$val\" ;;\n      --timezone=*) TZ=\"$val\"; export TZ; ;;\n      --flush-caches) flush_caches=1 ;;\n      --numa-interleave) numa_interleave=1 ;;\n      --numa-nodebind=*) numa_nodebind=\"$val\" ;;\n\n      --help) usage ;;\n\n      *)\n        if test -n \"$pick_args\"\n        then\n          append_arg_to_args \"$arg\"\n        fi\n        ;;\n    esac\n  done\n}\n\n\n# Add a single shared library to the list of libraries which will be added to\n# LD_PRELOAD for mysqld\n#\n# Since LD_PRELOAD is a space-separated value (for historical reasons), if a\n# shared lib's path contains spaces, that path will be prepended to\n# LD_LIBRARY_PATH and stripped from the lib value.\nadd_mysqld_ld_preload() {\n  lib_to_add=\"$1\"\n  log_notice \"Adding '$lib_to_add' to LD_PRELOAD for mysqld\"\n\n  case \"$lib_to_add\" in\n    *' '*)\n      # Must strip path from lib, and add it to LD_LIBRARY_PATH\n      lib_file=`basename \"$lib_to_add\"`\n      case \"$lib_file\" in\n        *' '*)\n          # The lib file itself has a space in its name, and can't\n          # be used in LD_PRELOAD\n          log_error \"library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD\"\n          exit 1\n          ;;\n      esac\n      lib_path=`dirname \"$lib_to_add\"`\n      lib_to_add=\"$lib_file\"\n      [ -n \"$mysqld_ld_library_path\" ] && mysqld_ld_library_path=\"$mysqld_ld_library_path:\"\n      mysqld_ld_library_path=\"$mysqld_ld_library_path$lib_path\"\n      ;;\n  esac\n\n  # Do not add if file does not exist.\n  if [ ! -f  \"$lib_to_add\" ]; then\n    log_error \"no shared library found for $lib_to_add\"\n    return\n  fi\n\n  # LD_PRELOAD is a space-separated\n  [ -n \"$mysqld_ld_preload\" ] && mysqld_ld_preload=\"$mysqld_ld_preload \"\n  mysqld_ld_preload=\"${mysqld_ld_preload}$lib_to_add\"\n}\n\n\n# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be\n# suitable for use in the eval that calls mysqld.\n#\n# All values in mysqld_ld_preload are prepended to LD_PRELOAD.\nmysqld_ld_preload_text() {\n  text=\n\n  if [ -n \"$mysqld_ld_preload\" ]; then\n    new_text=\"$mysqld_ld_preload\"\n    [ -n \"$LD_PRELOAD\" ] && new_text=\"$new_text $LD_PRELOAD\"\n    text=\"${text}LD_PRELOAD=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  if [ -n \"$mysqld_ld_library_path\" ]; then\n    new_text=\"$mysqld_ld_library_path\"\n    [ -n \"$LD_LIBRARY_PATH\" ] && new_text=\"$new_text:$LD_LIBRARY_PATH\"\n    text=\"${text}LD_LIBRARY_PATH=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  echo \"$text\"\n}\n\n# set_malloc_lib LIB\n# - If LIB is empty, do nothing and return\n# - If LIB is 'tcmalloc', look for tcmalloc shared library in $malloc_dirs.\n#   tcmalloc is part of the Google perftools project.\n# - If LIB is an absolute path, assume it is a malloc shared library\n#\n# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when\n# running mysqld.  See ld.so for details.\nset_malloc_lib() {\n  # This list is kept intentionally simple.\n  malloc_dirs=\"/usr/lib /usr/lib64 /usr/lib/i386-linux-gnu /usr/lib/x86_64-linux-gnu\"\n  malloc_lib=\"$1\"\n\n  if [ \"$malloc_lib\" = tcmalloc ]; then\n    malloc_lib=\n    for libdir in `echo $malloc_dirs`; do\n      for flavor in _minimal '' _and_profiler _debug; do\n        tmp=\"$libdir/libtcmalloc$flavor.so\"\n        #log_notice \"DEBUG: Checking for malloc lib '$tmp'\"\n        [ -r \"$tmp\" ] || continue\n        malloc_lib=\"$tmp\"\n        break 2\n      done\n    done\n\n    if [ -z \"$malloc_lib\" ]; then\n      log_error \"no shared library for --malloc-lib=tcmalloc found in $malloc_dirs\"\n      exit 1\n    fi\n  fi\n\n  # Allow --malloc-lib='' to override other settings\n  [ -z  \"$malloc_lib\" ] && return\n\n  case \"$malloc_lib\" in\n    /*)\n      if [ ! -r \"$malloc_lib\" ]; then\n        log_error \"--malloc-lib can not be read and will not be used\"\n        exit 1\n      fi\n\n      # Restrict to a the list in $malloc_dirs above\n      case \"`dirname \"$malloc_lib\"`\" in\n        /usr/lib) ;;\n        /usr/lib64) ;;\n        /usr/lib/i386-linux-gnu) ;;\n        /usr/lib/x86_64-linux-gnu) ;;\n        *)\n          log_error \"--malloc-lib must be located in one of the directories: $malloc_dirs\"\n          exit 1\n          ;;\n      esac\n      ;;\n    *)\n      log_error \"--malloc-lib must be an absolute path or 'tcmalloc'; \" \\\n        \"ignoring value '$malloc_lib'\"\n      exit 1\n      ;;\n  esac\n\n  add_mysqld_ld_preload \"$malloc_lib\"\n}\n\n\n#\n# First, try to find BASEDIR and ledir (where mysqld is)\n#\n\nif echo '@pkgdatadir@' | grep '^@prefix@' > /dev/null\nthen\n  relpkgdata=`echo '@pkgdatadir@' | sed -e 's,^@prefix@,,' -e 's,^/,,' -e 's,^,./,'`\nelse\n  # pkgdatadir is not relative to prefix\n  relpkgdata='@pkgdatadir@'\nfi\n\ncase \"$0\" in\n  /*)\n  MY_PWD='@prefix@'\n  ;;\n  *)\n  MY_PWD=`dirname $0`\n  MY_PWD=`dirname $MY_PWD`\n  ;;\nesac\n# Check for the directories we would expect from a binary release install\nif test -n \"$MY_BASEDIR_VERSION\" -a -d \"$MY_BASEDIR_VERSION\"\nthen\n  # BASEDIR is already overridden on command line.  Do not re-set.\n\n  # Use BASEDIR to discover le.\n  if test -x \"$MY_BASEDIR_VERSION/libexec/mysqld\"\n  then\n    ledir=\"$MY_BASEDIR_VERSION/libexec\"\n  elif test -x \"$MY_BASEDIR_VERSION/sbin/mysqld\"\n  then\n    ledir=\"$MY_BASEDIR_VERSION/sbin\"\n  else\n    ledir=\"$MY_BASEDIR_VERSION/bin\"\n  fi\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/bin/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where bin, share and data are\n  ledir=\"$MY_PWD/bin\"\t\t\t# Where mysqld is\n# Check for the directories we would expect from a source install\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/libexec/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where libexec, share and var are\n  ledir=\"$MY_PWD/libexec\"\t\t# Where mysqld is\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/sbin/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where sbin, share and var are\n  ledir=\"$MY_PWD/sbin\"\t\t\t# Where mysqld is\n# Since we didn't find anything, used the compiled-in defaults\nelse\n  MY_BASEDIR_VERSION='@prefix@'\n  ledir='@libexecdir@'\nfi\n\n\n#\n# Second, try to find the data directory\n#\n\n# Try where the binary installs put it\nif test -d $MY_BASEDIR_VERSION/data/mysql\nthen\n  DATADIR=$MY_BASEDIR_VERSION/data\n  if test -z \"$defaults\" -a -r \"$DATADIR/my.cnf\"\n  then\n    defaults=\"--defaults-extra-file=$DATADIR/my.cnf\"\n  fi\n# Next try where the source installs put it\nelif test -d $MY_BASEDIR_VERSION/var/mysql\nthen\n  DATADIR=$MY_BASEDIR_VERSION/var\n# Or just give up and use our compiled-in default\nelse\n  DATADIR=@localstatedir@\nfi\n\nif test -z \"$MYSQL_HOME\"\nthen\n  if test -r \"$MY_BASEDIR_VERSION/my.cnf\" && test -r \"$DATADIR/my.cnf\"\n  then\n    log_error \"WARNING: Found two instances of my.cnf -\n$MY_BASEDIR_VERSION/my.cnf and\n$DATADIR/my.cnf\nIGNORING $DATADIR/my.cnf\"\n\n    MYSQL_HOME=$MY_BASEDIR_VERSION\n  elif test -r \"$DATADIR/my.cnf\"\n  then\n    log_error \"WARNING: Found $DATADIR/my.cnf\nThe data directory is a deprecated location for my.cnf, please move it to\n$MY_BASEDIR_VERSION/my.cnf\"\n    MYSQL_HOME=$DATADIR\n  else\n    MYSQL_HOME=$MY_BASEDIR_VERSION\n  fi\nfi\nexport MYSQL_HOME\n\n\n# Get first arguments from the my.cnf file, groups [mysqld] and [mysqld_safe]\n# and then merge with the command line arguments\nif test -x \"$MY_BASEDIR_VERSION/bin/my_print_defaults\"\nthen\n  print_defaults=\"$MY_BASEDIR_VERSION/bin/my_print_defaults\"\nelif test -x `dirname $0`/my_print_defaults\nthen\n  print_defaults=\"`dirname $0`/my_print_defaults\"\nelif test -x ./bin/my_print_defaults\nthen\n  print_defaults=\"./bin/my_print_defaults\"\nelif test -x @bindir@/my_print_defaults\nthen\n  print_defaults=\"@bindir@/my_print_defaults\"\nelif test -x @bindir@/mysql_print_defaults\nthen\n  print_defaults=\"@bindir@/mysql_print_defaults\"\nelse\n  print_defaults=\"my_print_defaults\"\nfi\n\nappend_arg_to_args () {\n  args=\"$args \"`shell_quote_string \"$1\"`\n}\n\nargs=\n\nSET_USER=2\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld server`\nif test $SET_USER -eq 2\nthen\n  SET_USER=0\nfi\n\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld`\nparse_arguments PICK-ARGS-FROM-ARGV \"$@\"\n\n#\n# Try to find the plugin directory\n#\n\n# Use user-supplied argument\nif [ -n \"${PLUGIN_DIR}\" ]; then\n  plugin_dir=\"${PLUGIN_DIR}\"\nelse\n  # Try to find plugin dir relative to basedir\n  for dir in lib64/mysql/plugin lib64/plugin lib/mysql/plugin lib/plugin\n  do\n    if [ -d \"${MY_BASEDIR_VERSION}/${dir}\" ]; then\n      plugin_dir=\"${MY_BASEDIR_VERSION}/${dir}\"\n      break\n    fi\n  done\n  # Give up and use compiled-in default\n  if [ -z \"${plugin_dir}\" ]; then\n    plugin_dir='@pkgplugindir@'\n  fi\nfi\nplugin_dir=\"${plugin_dir}${PLUGIN_VARIANT}\"\n\n# Determine what logging facility to use\n\n# Ensure that 'logger' exists, if it's requested\nif [ $want_syslog -eq 1 ]\nthen\n  my_which logger > /dev/null 2>&1\n  if [ $? -ne 0 ]\n  then\n    log_error \"--syslog requested, but no 'logger' program found.  Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe.\"\n    exit 1\n  fi\nfi\n\nif [ -n \"$err_log\" -o $want_syslog -eq 0 ]\nthen\n  if [ -n \"$err_log\" ]\n  then\n    # mysqld adds \".err\" if there is no extension on the --log-error\n    # argument; must match that here, or mysqld_safe will write to a\n    # different log file than mysqld\n\n    # mysqld does not add \".err\" to \"--log-error=foo.\"; it considers a\n    # trailing \".\" as an extension\n\n    if expr \"$err_log\" : '.*\\.[^/]*$' > /dev/null\n    then\n        :\n    else\n      err_log=\"$err_log\".err\n    fi\n\n    case \"$err_log\" in\n      /* ) ;;\n      * ) err_log=\"$DATADIR/$err_log\" ;;\n    esac\n  else\n    err_log=$DATADIR/`@HOSTNAME@`.err\n  fi\n\n  append_arg_to_args \"--log-error=$err_log\"\n\n  if [ $want_syslog -eq 1 ]\n  then\n    # User explicitly asked for syslog, so warn that it isn't used\n    log_error \"Can't log to error log and syslog at the same time.  Remove all --log-error configuration options for --syslog to take effect.\"\n  fi\n\n  # Log to err_log file\n  logging=file\nelse\n  if [ -n \"$syslog_tag\" ]\n  then\n    # Sanitize the syslog tag\n    syslog_tag=`echo \"$syslog_tag\" | sed -e 's/[^a-zA-Z0-9_-]/_/g'`\n    syslog_tag_mysqld_safe=\"${syslog_tag_mysqld_safe}-$syslog_tag\"\n    syslog_tag_mysqld=\"${syslog_tag_mysqld}-$syslog_tag\"\n  fi\n  log_notice \"Logging to syslog.\"\n  logging=syslog\nfi\n\nlogdir=`dirname \"$err_log\"`\n# Change the err log to the right user, if possible and it is in use\nif [ $logging = \"file\" -o $logging = \"both\" ]; then\n  if [ ! -f \"$err_log\" -a ! -h \"$err_log\" ]; then\n    if test -w / -o \"$USER\" = \"root\"; then\n      case $logdir in\n        /var/log)\n          (\n            umask 0137\n            set -o noclobber\n            > \"$err_log\" && chown $user \"$err_log\"\n          ) ;;\n        *) ;;\n      esac\n    else\n      (\n        umask 0137\n        set -o noclobber\n        > \"$err_log\"\n      )\n    fi\n  fi\n\n  if [ -f \"$err_log\" ]; then        # Log to err_log file\n    log_notice \"Logging to '$err_log'.\"\n  elif [ \"x$user\" = \"xroot\" ]; then # running as root, mysqld can create log file; continue\n    echo \"Logging to '$err_log'.\" >&2\n  else\n    case $logdir in\n      # We can't create $err_log, however mysqld can; continue\n      /tmp|/var/tmp|/var/log/mysql|$DATADIR)\n        echo \"Logging to '$err_log'.\" >&2\n        ;;\n      # We can't create $err_log and don't know if mysqld can; error out\n      *)\n        log_error \"error: log-error set to '$err_log', however file don't exists. Create writable for user '$user'.\"\n        exit 1\n        ;;\n    esac\n  fi\nfi\n\nUSER_OPTION=\"\"\nif test -w / -o \"$USER\" = \"root\"\nthen\n  if test \"$user\" != \"root\" -o $SET_USER = 1\n  then\n    USER_OPTION=\"--user=$user\"\n  fi\n  if test -n \"$open_files\"\n  then\n    ulimit -n $open_files\n  fi\nfi\n\nif test -n \"$open_files\"\nthen\n  append_arg_to_args \"--open-files-limit=$open_files\"\nfi\n\nsafe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}}\n# Check that directory for $safe_mysql_unix_port exists\nmysql_unix_port_dir=`dirname $safe_mysql_unix_port`\nif [ ! -d $mysql_unix_port_dir ]\nthen\n  log_error \"Directory '$mysql_unix_port_dir' for UNIX socket file don't exists.\"\n  exit 1\nfi\n\n# If the user doesn't specify a binary, we assume name \"mysqld\"\nif test -z \"$MYSQLD\"\nthen\n  MYSQLD=mysqld\nfi\n\nif test ! -x \"$ledir/$MYSQLD\"\nthen\n  log_error \"The file $ledir/$MYSQLD\ndoes not exist or is not executable. Please cd to the mysql installation\ndirectory and restart this script from there as follows:\n./bin/mysqld_safe&\nSee http://dev.mysql.com/doc/mysql/en/mysqld-safe.html for more information\"\n  exit 1\nfi\nsetcap 'cap_sys_nice=eip' $ledir/$MYSQLD\nif [ $? -ne 0 ]\nthen\n  echo \"Failed to set capabilities\"\nfi\n\nif test -z \"$pid_file\"\nthen\n  pid_file=\"$DATADIR/`@HOSTNAME@`.pid\"\nelse\n  case \"$pid_file\" in\n    /* ) ;;\n    * )  pid_file=\"$DATADIR/$pid_file\" ;;\n  esac\nfi\nappend_arg_to_args \"--pid-file=$pid_file\"\n\nif test -n \"$mysql_unix_port\"\nthen\n  append_arg_to_args \"--socket=$mysql_unix_port\"\nfi\nif test -n \"$mysql_tcp_port\"\nthen\n  append_arg_to_args \"--port=$mysql_tcp_port\"\nfi\n\nif test $niceness -eq 0\nthen\n  NOHUP_NICENESS=\"nohup\"\nelse\n  NOHUP_NICENESS=\"nohup nice -$niceness\"\nfi\n\n# Using nice with no args to get the niceness level is GNU-specific.\n# This check could be extended for other operating systems (e.g.,\n# BSD could use \"nohup sh -c 'ps -o nice -p $$' | tail -1\").\n# But, it also seems that GNU nohup is the only one which messes\n# with the priority, so this is okay.\nif nohup nice > /dev/null 2>&1\nthen\n    normal_niceness=`nice`\n    nohup_niceness=`nohup nice 2>/dev/null`\n\n    numeric_nice_values=1\n    for val in $normal_niceness $nohup_niceness\n    do\n        case \"$val\" in\n            -[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \\\n             [0-9] |  [0-9][0-9] |  [0-9][0-9][0-9] )\n                ;;\n            * )\n                numeric_nice_values=0 ;;\n        esac\n    done\n\n    if test $numeric_nice_values -eq 1\n    then\n        nice_value_diff=`expr $nohup_niceness - $normal_niceness`\n        if test $? -eq 0 && test $nice_value_diff -gt 0 && \\\n            nice --$nice_value_diff echo testing > /dev/null 2>&1\n        then\n            # nohup increases the priority (bad), and we are permitted\n            # to lower the priority with respect to the value the user\n            # might have been given\n            niceness=`expr $niceness - $nice_value_diff`\n            NOHUP_NICENESS=\"nice -$niceness nohup\"\n        fi\n    fi\nelse\n    if nohup echo testing > /dev/null 2>&1\n    then\n        :\n    else\n        # nohup doesn't work on this system\n        NOHUP_NICENESS=\"\"\n    fi\nfi\n\n# Try to set the core file size (even if we aren't root) because many systems\n# don't specify a hard limit on core file size.\nif test -n \"$core_file_size\"\nthen\n  ulimit -c $core_file_size\nfi\n\n#\n# If there exists an old pid file, check if the daemon is already running\n# Note: The switches to 'ps' may depend on your operating system\nif test -f \"$pid_file\"\nthen\n  PID=`cat \"$pid_file\"`\n  if @CHECK_PID@\n  then\n    if @FIND_PROC@\n    then    # The pid contains a mysqld process\n      log_error \"A mysqld process already exists\"\n      exit 1\n    fi\n  fi\n  if [ ! -h \"$pid_file\" ]; then\n      rm -f \"$pid_file\"\n  fi\n  if test -f \"$pid_file\"\n  then\n    log_error \"Fatal error: Can't remove the pid file:\n$pid_file\nPlease remove it manually and start $0 again;\nmysqld daemon not started\"\n    exit 1\n  fi\nfi\n\n#\n# Flush and purge buffers/caches.\n#\n\nif @TARGET_LINUX@ && test $flush_caches -eq 1\nthen\n  # Locate sync, ensure it exists.\n  if ! my_which sync > /dev/null 2>&1\n  then\n    log_error \"sync command not found, required for --flush-caches\"\n    exit 1\n  # Flush file system buffers.\n  elif ! sync\n  then\n    # Huh, the sync() function is always successful...\n    log_error \"sync failed, check if sync is properly installed\"\n  fi\n\n  # Locate sysctl, ensure it exists.\n  if ! my_which sysctl > /dev/null 2>&1\n  then\n    log_error \"sysctl command not found, required for --flush-caches\"\n    exit 1\n  # Purge page cache, dentries and inodes.\n  elif ! sysctl -q -w vm.drop_caches=3\n  then\n    log_error \"sysctl failed, check the error message for details\"\n    exit 1\n  fi\nelif test $flush_caches -eq 1\nthen\n  log_error \"--flush-caches is not supported on this platform\"\n  exit 1\nfi\n\n#\n# Uncomment the following lines if you want all tables to be automatically\n# checked and repaired during startup. You should add sensible key_buffer\n# and sort_buffer values to my.cnf to improve check performance or require\n# less disk space.\n# Alternatively, you can start mysqld with the \"myisam-recover\" option. See\n# the manual for details.\n#\n# echo \"Checking tables in $DATADIR\"\n# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI\n# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM\n\n# Does this work on all systems?\n#if type ulimit | grep \"shell builtin\" > /dev/null\n#then\n#  ulimit -n 256 > /dev/null 2>&1\t\t# Fix for BSD and FreeBSD systems\n#fi\n\ncmd=\"$NOHUP_NICENESS\"\n\n#\n# Set mysqld's memory interleave policy.\n#\n\nif @TARGET_LINUX@ && test $numa_interleave -eq 1\nthen\n  # Locate numactl, ensure it exists.\n  if ! my_which numactl > /dev/null 2>&1\n  then\n    log_error \"numactl command not found, required for --numa-interleave\"\n    exit 1\n  # Attempt to run a command, ensure it works.\n  elif ! numactl --interleave=all true\n  then\n    log_error \"numactl failed, check if numactl is properly installed\"\n  fi\n\n  # Launch mysqld with numactl.\n  cmd=\"$cmd numactl --interleave=all\"\nelif test $numa_interleave -eq 1\nthen\n  log_error \"--numa-interleave is not supported on this platform\"\n  exit 1\nfi\n\nif @TARGET_LINUX@ && test ! -z \"$numa_nodebind\"\nthen\n  # Locate numactl, ensure it exists.\n  if ! my_which numactl > /dev/null 2>&1\n  then\n    log_error \"numactl command not found, required for --numa-nodebind\"\n    exit 1\n  fi\n\n  # Attempt to run a command, ensure it works.\n  if ! numactl --cpunodebind=$numa_nodebind --preferred=$numa_nodebind true\n  then\n    log_error \"numactl failed, check if numa-nodebind value is correct\"\n    exit 1\n  fi\n\n  # Launch mysqld with numactl.\n  cmd=\"$cmd numactl --cpunodebind=$numa_nodebind --preferred=$numa_nodebind\"\nelif test ! -z \"$numa_nodebind\"\nthen\n  log_error \"--numa-nodebind is not supported on this platform\"\n  exit 1\nfi\n\nif [ ! -z \"`mysqld_ld_preload_text`\" ]; then\n  cmd=\"$cmd env `mysqld_ld_preload_text`\"\nfi\n\nfor i in  \"$ledir/$MYSQLD\" \"$defaults\" \"--basedir=$MY_BASEDIR_VERSION\" \\\n  \"--datadir=$DATADIR\" \"--plugin-dir=$plugin_dir\" \"$USER_OPTION\"\ndo\n  cmd=\"$cmd \"`shell_quote_string \"$i\"`\ndone\ncmd=\"$cmd $args\"\n\nif [ -n \"$malloc_conf_options\" ]\nthen\n  cmd=\"MALLOC_CONF=$malloc_conf_options $cmd\"\nfi\n\ncmd_skip_core=\"$cmd --skip-core-file\"\n# Avoid 'nohup: ignoring input' warning\ntest -n \"$NOHUP_NICENESS\" && cmd=\"$cmd < /dev/null\" \\\n                          && cmd_skip_core=\"$cmd_skip_core < /dev/null\"\ncmd_saved=\"$cmd\"\n\nlog_notice \"Starting $MYSQLD daemon with databases from $DATADIR\"\n\n# variable to track the current number of \"fast\" (a.k.a. subsecond) restarts\nfast_restart=0\n# maximum number of restarts before trottling kicks in\nmax_fast_restarts=5\n# flag whether a usable sleep command exists\nhave_sleep=1\n\nskip_core=0\nlast_crash=0\n\ncur_retry_times=0\nmax_restart_a_day=10\nprev_date=`date +%D`\n\nwhile true\ndo\n  # Some extra safety\n  if [ ! -h \"$safe_mysql_unix_port\" ]; then\n    rm -f \"$safe_mysql_unix_port\"\n  fi\n  if [ ! -h \"$pid_file\" ]; then\n    rm -f \"$pid_file\"\n  fi\n  if [ ! -h \"$pid_file.shutdown\" ]; then\n    rm -f \"$pid_file.shutdown\"\n  fi\n\n  start_time=`date +%M%S`\n\n  # We need to add these paths, so that we can place our\n  # compiled sasl plugins in the directory.\n  # This is temporary till we figure out why some plugins\n  # although present in installed paths are not discovered\n  if [ -d \"/usr/local/fbprojects/packages/mysql_raft.sasl_plain/latest/sasl2\" ]; then\n    export SASL_PATH=/usr/local/fbprojects/packages/mysql_raft.sasl_plain/latest/sasl2\n  fi\n  eval_log_error \"$cmd\"\n\n  # hypothetical: log was renamed but not\n  # flushed yet. we'd recreate it with\n  # wrong owner next time we log, so set\n  # it up correctly while we can!\n\n  if [ $want_syslog -eq 0 -a ! -f \"$err_log\" -a ! -h \"$err_log\" ]; then\n    if test -w / -o \"$USER\" = \"root\"; then\n      logdir=`dirname \"$err_log\"`\n      case $logdir in\n        /var/log)\n          (\n            umask 0137\n            set -o noclobber\n            > \"$err_log\" && chown $user \"$err_log\"\n          ) ;;\n        *) ;;\n      esac\n    else\n      (\n        umask 0137\n        set -o noclobber\n        > \"$err_log\"\n      )\n    fi\n  fi\n\n  end_time=`date +%M%S`\n\n  # pid file is removed and shutdown file is created for normal shutdown\n  if test ! -f \"$pid_file\" || test -f \"$pid_file.shutdown\"\n  then\n    break\n  fi\n\n  # The current time in seconds since Epoch\n  cur_crash=`date +%s`\n  interval=`expr $cur_crash - $last_crash`\n  if test $skip_core -eq 0\n  then\n      if test $interval -lt 86400\n      then\n          # Make sure no more than two cores dumped within 24 hours\n          skip_core=1\n          cmd_saved=\"$cmd\"\n          cmd=\"$cmd_skip_core\"\n          log_notice \"mysqld will be restarted with --skip-core-file\"\n      fi\n  else\n      if test $interval -gt 86400\n      then\n          # Allow core dump\n          skip_core=0\n          cur_crash=0\n          cmd_skip_core=\"$cmd\"\n          cmd=\"$cmd_saved\"\n          log_notice \"mysqld will be restarted without --skip-core-file\"\n      fi\n  fi\n  last_crash=$cur_crash\n\n  # stop retrying too ofen and rocksdb filling up txlogs\n  #\n  # 1. Reset current retry times in a new day\n  cur_date=`date +%D`\n  if test $cur_date != $prev_date\n  then\n    cur_retry_times=0\n    prev_date=`date +%D`\n  fi\n\n  # 2. Sleep 2,4,8,16... seconds between restart\n  #    Sleep 24 hours if reaching 10 retries in a day\n  cur_retry_times=`expr $cur_retry_times + 1`\n  if test ! -f /tmp/disable_mysqld_restart_throttle \\\n    && test \"$cur_retry_times\" -gt \"$max_restart_a_day\"\n  then\n    log_notice \"Throttling restart after 10 restarts: Sleep 1 day\"\n    sleep 86400\n    if [ $? == 137 ];\n    then\n      log_notice \"Sleep was likely interrupted from outside. Will exit loop\"\n      break\n    fi\n  else\n    sleep_time=$((2**${cur_retry_times}))\n    log_notice \"Throttling restart after $cur_retry_times restarts: Sleep $sleep_time seconds\"\n    sleep $sleep_time\n    if [ $? == 137 ];\n    then\n      log_notice \"Sleep was likely interrupted from outside. Will exit loop\"\n      break\n    fi\n  fi\n\n  # Note: the following code is not needed after exponential backoff\n  # sanity check if time reading is sane and there's sleep\n  if test $end_time -gt 0 -a $have_sleep -gt 0\n  then\n    # throttle down the fast restarts\n    if test $end_time -eq $start_time\n    then\n      fast_restart=`expr $fast_restart + 1`\n      if test $fast_restart -ge $max_fast_restarts\n      then\n        log_notice \"The server is respawning too fast. Sleeping for 1 second.\"\n        sleep 1\n        sleep_state=$?\n        if test $sleep_state -gt 0\n        then\n          log_notice \"The server is respawning too fast and no working sleep command. Turning off trottling.\"\n          have_sleep=0\n        fi\n\n        fast_restart=0\n      fi\n    else\n      fast_restart=0\n    fi\n  fi\n\n  if @TARGET_LINUX@ && test $KILL_MYSQLD -eq 1\n  then\n    # Test if one process was hanging.\n    # This is only a fix for Linux (running as base 3 mysqld processes)\n    # but should work for the rest of the servers.\n    # The only thing is ps x => redhat 5 gives warnings when using ps -x.\n    # kill -9 is used or the process won't react on the kill.\n    numofproces=`ps xaww | grep -v \"grep\" | grep \"$ledir/$MYSQLD\\>\" | grep -c \"pid-file=$pid_file\"`\n\n    log_notice \"Number of processes running now: $numofproces\"\n    I=1\n    while test \"$I\" -le \"$numofproces\"\n    do\n      PROC=`ps xaww | grep \"$ledir/$MYSQLD\\>\" | grep -v \"grep\" | grep \"pid-file=$pid_file\" | sed -n '$p'`\n\n      for T in $PROC\n      do\n        break\n      done\n      #    echo \"TEST $I - $T **\"\n      if kill -9 $T\n      then\n        log_error \"$MYSQLD process hanging, pid $T - killed\"\n      else\n        break\n      fi\n      I=`expr $I + 1`\n    done\n  fi\n  log_notice \"mysqld restarted\"\ndone\n\nlog_notice \"mysqld from pid file $pid_file ended\"\n", "num_lines": 1153}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!@SHELL_PATH@\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n#\n# Script to start the MySQL daemon and restart it if it dies unexpectedly\n#\n# This should be executed in the MySQL base directory if you are using a\n# binary installation that is not installed in its compile-time default\n# location\n#\n# mysql.server works by first doing a cd to the base directory and from there\n# executing mysqld_starter\n\n# Initialize script globals\nKILL_MYSQLD=1;\nMYSQLD=\nniceness=0\nmysqld_ld_preload=\nmysqld_ld_library_path=\nflush_caches=0\nnuma_interleave=0\nnuma_nodebind=\n\n# Initial logging status: error log is not open, and not using syslog\nlogging=init\nwant_syslog=0\nsyslog_tag=\nuser='@MYSQLD_USER@'\npid_file=\nerr_log=\n\nsyslog_tag_mysqld=mysqld\nsyslog_tag_mysqld_safe=mysqld_safe\n\nexit_code=0\n\ntrap '' 1 2 3 15\t\t\t# we shouldn't let anyone kill us\ntrap '' 13                              # not even SIGPIPE\n\n# MySQL-specific environment variable. First off, it's not really a umask,\n# it's the desired mode. Second, it follows umask(2), not umask(3) in that\n# octal needs to be explicit. Our shell might be a proper sh without printf,\n# multiple-base arithmetic, and binary arithmetic, so this will get ugly.\n# We reject decimal values to keep things at least half-sane.\numask 007                               # fallback\nUMASK=\"${UMASK-0640}\"\nfmode=`echo \"$UMASK\" | sed -e 's/[^0246]//g'`\noctalp=`echo \"$fmode\"|cut -c1`\nfmlen=`echo \"$fmode\"|wc -c|sed -e 's/ //g'`\nif [ \"x$octalp\" != \"x0\" -o \"x$UMASK\" != \"x$fmode\" -o \"x$fmlen\" != \"x5\" ]\nthen\n  fmode=0640\n  echo \"UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\" >&2\n  echo \"The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\" >&2\nfi\nfmode=`echo \"$fmode\"|cut -c3-4`\nfmode=\"6$fmode\"\nif [ \"x$UMASK\" != \"x0$fmode\" ]\nthen\n  echo \"UMASK corrected from $UMASK to 0$fmode ...\"\nfi\n\ndefaults=\ncase \"$1\" in\n    --no-defaults|--defaults-file=*|--defaults-extra-file=*)\n      defaults=\"$1\"; shift\n      ;;\nesac\n\nusage () {\n        cat <<EOF\nUsage: $0 [OPTIONS]\n  --no-defaults              Don't read the system defaults file\n  --defaults-file=FILE       Use the specified defaults file\n  --defaults-extra-file=FILE Also use defaults from the specified file\n  --ledir=DIRECTORY          Look for mysqld in the specified directory\n  --open-files-limit=LIMIT   Limit the number of open files\n  --core-file-size=LIMIT     Limit core files to the specified size\n  --timezone=TZ              Set the system timezone\n  --malloc-lib=LIB           Preload shared library LIB if available\n  --ld-preload-lib=LIB       Preload shared library LIB\n  --mysqld=FILE              Use the specified file as mysqld\n  --mysqld-version=VERSION   Use \"mysqld-VERSION\" as mysqld\n  --nice=NICE                Set the scheduling priority of mysqld\n  --plugin-dir=DIR           Plugins are under DIR or DIR/VERSION, if\n                             VERSION is given\n  --skip-kill-mysqld         Don't try to kill stray mysqld processes\n  --syslog                   Log messages to syslog with 'logger'\n  --skip-syslog              Log messages to error log (default)\n  --syslog-tag=TAG           Pass -t \"mysqld-TAG\" to 'logger'\n  --flush-caches             Flush and purge buffers/caches\n  --numa-interleave          Run mysqld with its memory interleaved\n                             on all CPUs\n  --numa-nodebind            Run mysqld with numa binding to one socket\n\nAll other options are passed to the mysqld program.\n\nEOF\n        exit 1\n}\n\nmy_which ()\n{\n  save_ifs=\"${IFS-UNSET}\"\n  IFS=:\n  ret=0\n  for file\n  do\n    for dir in $PATH\n    do\n      if [ -f \"$dir/$file\" ]\n      then\n        echo \"$dir/$file\"\n        continue 2\n      fi\n    done\n\n\tret=1  #signal an error\n\tbreak\n  done\n\n  if [ \"$save_ifs\" = UNSET ]\n  then\n    unset IFS\n  else\n    IFS=\"$save_ifs\"\n  fi\n  return $ret  # Success\n}\n\nlog_generic () {\n  priority=\"$1\"\n  shift\n\n  msg=\"`date +'%y%m%d %H:%M:%S'` mysqld_safe $*\"\n  echo \"$msg\"\n  case $logging in\n    init) ;;  # Just echo the message, don't save it anywhere\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        true\n      else\n        echo \"$msg\" >> \"$err_log\"\n      fi\n      ;;\n    syslog) logger -t \"$syslog_tag_mysqld_safe\" -p \"$priority\" \"$*\" ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n}\n\nlog_error () {\n  log_generic daemon.error \"$@\" >&2\n}\n\nlog_notice () {\n  log_generic daemon.notice \"$@\"\n}\n\neval_log_error () {\n  local cmd=\"$1\"\n  case $logging in\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        cmd=\"$cmd > /dev/null 2>&1\"\n      else\n        cmd=\"$cmd >> \"`shell_quote_string \"$err_log\"`\" 2>&1\"\n      fi\n      ;;\n    syslog)\n      # mysqld often prefixes its messages with a timestamp, which is\n      # redundant when logging to syslog (which adds its own timestamp)\n      # However, we don't strip the timestamp with sed here, because\n      # sed buffers output (only GNU sed supports a -u (unbuffered) option)\n      # which means that messages may not get sent to syslog until the\n      # mysqld process quits.\n      #\n      # Adding pipefail to return non zero exit code on mysqld failure.\n      cmd=\"set -o pipefail; $cmd 2>&1 | logger -t '$syslog_tag_mysqld' -p daemon.error\"\n      ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n\n  #echo \"Running mysqld: [$cmd]\"\n  #set mysqld exit code into $exit_code\n  #both stdout/stderr are redirected in $cmd. so\n  #exit_code is a return code (not output) of of $cmd\n  #which is the same as mysqld's exit code.\n  cmd=\"$cmd; echo \\$?\"\n  exit_code=`eval \"$cmd\"`\n}\n\nshell_quote_string() {\n  # This sed command makes sure that any special chars are quoted,\n  # so the arg gets passed exactly to the server.\n  echo \"$1\" | sed -e 's,\\([^a-zA-Z0-9/_.=-]\\),\\\\\\1,g'\n}\n\nparse_arguments() {\n  # We only need to pass arguments through to the server if we don't\n  # handle them here.  So, we collect unrecognized options (passed on\n  # the command line) into the args variable.\n  pick_args=\n  if test \"$1\" = PICK-ARGS-FROM-ARGV\n  then\n    pick_args=1\n    shift\n  fi\n\n  for arg do\n    # the parameter after \"=\", or the whole $arg if no match\n    val=`echo \"$arg\" | sed -e 's;^--[^=]*=;;'`\n    # what's before \"=\", or the whole $arg if no match\n    optname=`echo \"$arg\" | sed -e 's/^\\(--[^=]*\\)=.*$/\\1/'`\n    # replace \"_\" by \"-\" ; mysqld_safe must accept \"_\" like mysqld does.\n    optname_subst=`echo \"$optname\" | sed 's/_/-/g'`\n    arg=`echo $arg | sed \"s/^$optname/$optname_subst/\"`\n    case \"$arg\" in\n      # these get passed explicitly to mysqld\n      --basedir=*) MY_BASEDIR_VERSION=\"$val\" ;;\n      --datadir=*) DATADIR=\"$val\" ;;\n      --pid-file=*) pid_file=\"$val\" ;;\n      --plugin-dir=*) PLUGIN_DIR=\"$val\" ;;\n      --user=*) user=\"$val\"; SET_USER=1 ;;\n\n      # these might have been set in a [mysqld_safe] section of my.cnf\n      # they are added to mysqld command line to override settings from my.cnf\n      --log-error=*) err_log=\"$val\" ;;\n      --port=*) mysql_tcp_port=\"$val\" ;;\n      --socket=*) mysql_unix_port=\"$val\" ;;\n\n      # mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])!\n      --core-file-size=*) core_file_size=\"$val\" ;;\n      --ledir=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--ledir option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        ledir=\"$val\"\n        ;;\n      --malloc-lib=*) set_malloc_lib \"$val\" ;;\n      --ld-preload-lib=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--ld-preload-lib option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        add_mysqld_ld_preload \"$val\" ;;\n      --mysqld=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        MYSQLD=\"$val\" ;;\n      --mysqld-version=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld-version option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        if test -n \"$val\"\n        then\n          MYSQLD=\"mysqld-$val\"\n          PLUGIN_VARIANT=\"/$val\"\n        else\n          MYSQLD=\"mysqld\"\n        fi\n        ;;\n      --nice=*) niceness=\"$val\" ;;\n      --open-files-limit=*) open_files=\"$val\" ;;\n      --open_files_limit=*) open_files=\"$val\" ;;\n      --skip-kill-mysqld*) KILL_MYSQLD=0 ;;\n      --syslog) want_syslog=1 ;;\n      --skip-syslog) want_syslog=0 ;;\n      --syslog-tag=*) syslog_tag=\"$val\" ;;\n      --timezone=*) TZ=\"$val\"; export TZ; ;;\n      --flush-caches) flush_caches=1 ;;\n      --numa-interleave) numa_interleave=1 ;;\n      --numa-nodebind=*) numa_nodebind=\"$val\" ;;\n\n      --help) usage ;;\n\n      *)\n        if test -n \"$pick_args\"\n        then\n          append_arg_to_args \"$arg\"\n        fi\n        ;;\n    esac\n  done\n}\n\n\n# Add a single shared library to the list of libraries which will be added to\n# LD_PRELOAD for mysqld\n#\n# Since LD_PRELOAD is a space-separated value (for historical reasons), if a\n# shared lib's path contains spaces, that path will be prepended to\n# LD_LIBRARY_PATH and stripped from the lib value.\nadd_mysqld_ld_preload() {\n  lib_to_add=\"$1\"\n  log_notice \"Adding '$lib_to_add' to LD_PRELOAD for mysqld\"\n\n  case \"$lib_to_add\" in\n    *' '*)\n      # Must strip path from lib, and add it to LD_LIBRARY_PATH\n      lib_file=`basename \"$lib_to_add\"`\n      case \"$lib_file\" in\n        *' '*)\n          # The lib file itself has a space in its name, and can't\n          # be used in LD_PRELOAD\n          log_error \"library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD\"\n          exit 1\n          ;;\n      esac\n      lib_path=`dirname \"$lib_to_add\"`\n      lib_to_add=\"$lib_file\"\n      [ -n \"$mysqld_ld_library_path\" ] && mysqld_ld_library_path=\"$mysqld_ld_library_path:\"\n      mysqld_ld_library_path=\"$mysqld_ld_library_path$lib_path\"\n      ;;\n  esac\n\n  # Do not add if file does not exist.\n  if [ ! -f  \"$lib_to_add\" ]; then\n    log_error \"no shared library found for $lib_to_add\"\n    return\n  fi\n\n  # LD_PRELOAD is a space-separated\n  [ -n \"$mysqld_ld_preload\" ] && mysqld_ld_preload=\"$mysqld_ld_preload \"\n  mysqld_ld_preload=\"${mysqld_ld_preload}$lib_to_add\"\n}\n\n\n# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be\n# suitable for use in the eval that calls mysqld.\n#\n# All values in mysqld_ld_preload are prepended to LD_PRELOAD.\nmysqld_ld_preload_text() {\n  text=\n\n  if [ -n \"$mysqld_ld_preload\" ]; then\n    new_text=\"$mysqld_ld_preload\"\n    [ -n \"$LD_PRELOAD\" ] && new_text=\"$new_text $LD_PRELOAD\"\n    text=\"${text}LD_PRELOAD=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  if [ -n \"$mysqld_ld_library_path\" ]; then\n    new_text=\"$mysqld_ld_library_path\"\n    [ -n \"$LD_LIBRARY_PATH\" ] && new_text=\"$new_text:$LD_LIBRARY_PATH\"\n    text=\"${text}LD_LIBRARY_PATH=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  echo \"$text\"\n}\n\n# set_malloc_lib LIB\n# - If LIB is empty, do nothing and return\n# - If LIB is 'tcmalloc', look for tcmalloc shared library in $malloc_dirs.\n#   tcmalloc is part of the Google perftools project.\n# - If LIB is an absolute path, assume it is a malloc shared library\n#\n# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when\n# running mysqld.  See ld.so for details.\nset_malloc_lib() {\n  # This list is kept intentionally simple.\n  malloc_dirs=\"/usr/lib /usr/lib64 /usr/lib/i386-linux-gnu /usr/lib/x86_64-linux-gnu\"\n  malloc_lib=\"$1\"\n\n  if [ \"$malloc_lib\" = tcmalloc ]; then\n    malloc_lib=\n    for libdir in `echo $malloc_dirs`; do\n      for flavor in _minimal '' _and_profiler _debug; do\n        tmp=\"$libdir/libtcmalloc$flavor.so\"\n        #log_notice \"DEBUG: Checking for malloc lib '$tmp'\"\n        [ -r \"$tmp\" ] || continue\n        malloc_lib=\"$tmp\"\n        break 2\n      done\n    done\n\n    if [ -z \"$malloc_lib\" ]; then\n      log_error \"no shared library for --malloc-lib=tcmalloc found in $malloc_dirs\"\n      exit 1\n    fi\n  fi\n\n  # Allow --malloc-lib='' to override other settings\n  [ -z  \"$malloc_lib\" ] && return\n\n  case \"$malloc_lib\" in\n    /*)\n      if [ ! -r \"$malloc_lib\" ]; then\n        log_error \"--malloc-lib can not be read and will not be used\"\n        exit 1\n      fi\n\n      # Restrict to a the list in $malloc_dirs above\n      case \"`dirname \"$malloc_lib\"`\" in\n        /usr/lib) ;;\n        /usr/lib64) ;;\n        /usr/lib/i386-linux-gnu) ;;\n        /usr/lib/x86_64-linux-gnu) ;;\n        *)\n          log_error \"--malloc-lib must be located in one of the directories: $malloc_dirs\"\n          exit 1\n          ;;\n      esac\n      ;;\n    *)\n      log_error \"--malloc-lib must be an absolute path or 'tcmalloc'; \" \\\n        \"ignoring value '$malloc_lib'\"\n      exit 1\n      ;;\n  esac\n\n  add_mysqld_ld_preload \"$malloc_lib\"\n}\n\n\n#\n# First, try to find BASEDIR and ledir (where mysqld is)\n#\n\nif echo '@pkgdatadir@' | grep '^@prefix@' > /dev/null\nthen\n  relpkgdata=`echo '@pkgdatadir@' | sed -e 's,^@prefix@,,' -e 's,^/,,' -e 's,^,./,'`\nelse\n  # pkgdatadir is not relative to prefix\n  relpkgdata='@pkgdatadir@'\nfi\n\ncase \"$0\" in\n  /*)\n  MY_PWD='@prefix@'\n  ;;\n  *)\n  MY_PWD=`dirname $0`\n  MY_PWD=`dirname $MY_PWD`\n  ;;\nesac\n# Check for the directories we would expect from a binary release install\nif test -n \"$MY_BASEDIR_VERSION\" -a -d \"$MY_BASEDIR_VERSION\"\nthen\n  # BASEDIR is already overridden on command line.  Do not re-set.\n\n  # Use BASEDIR to discover le.\n  if test -x \"$MY_BASEDIR_VERSION/libexec/mysqld\"\n  then\n    ledir=\"$MY_BASEDIR_VERSION/libexec\"\n  elif test -x \"$MY_BASEDIR_VERSION/sbin/mysqld\"\n  then\n    ledir=\"$MY_BASEDIR_VERSION/sbin\"\n  else\n    ledir=\"$MY_BASEDIR_VERSION/bin\"\n  fi\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/bin/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where bin, share and data are\n  ledir=\"$MY_PWD/bin\"\t\t\t# Where mysqld is\n# Check for the directories we would expect from a source install\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/libexec/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where libexec, share and var are\n  ledir=\"$MY_PWD/libexec\"\t\t# Where mysqld is\nelif test -f \"$relpkgdata\"/english/errmsg.sys -a -x \"$MY_PWD/sbin/mysqld\"\nthen\n  MY_BASEDIR_VERSION=\"$MY_PWD\"\t\t# Where sbin, share and var are\n  ledir=\"$MY_PWD/sbin\"\t\t\t# Where mysqld is\n# Since we didn't find anything, used the compiled-in defaults\nelse\n  MY_BASEDIR_VERSION='@prefix@'\n  ledir='@libexecdir@'\nfi\n\n\n#\n# Second, try to find the data directory\n#\n\n# Try where the binary installs put it\nif test -d $MY_BASEDIR_VERSION/data/mysql\nthen\n  DATADIR=$MY_BASEDIR_VERSION/data\n  if test -z \"$defaults\" -a -r \"$DATADIR/my.cnf\"\n  then\n    defaults=\"--defaults-extra-file=$DATADIR/my.cnf\"\n  fi\n# Next try where the source installs put it\nelif test -d $MY_BASEDIR_VERSION/var/mysql\nthen\n  DATADIR=$MY_BASEDIR_VERSION/var\n# Or just give up and use our compiled-in default\nelse\n  DATADIR=@localstatedir@\nfi\n\nif test -z \"$MYSQL_HOME\"\nthen \n  if test -r \"$MY_BASEDIR_VERSION/my.cnf\" && test -r \"$DATADIR/my.cnf\"\n  then\n    log_error \"WARNING: Found two instances of my.cnf -\n$MY_BASEDIR_VERSION/my.cnf and\n$DATADIR/my.cnf\nIGNORING $DATADIR/my.cnf\"\n\n    MYSQL_HOME=$MY_BASEDIR_VERSION\n  elif test -r \"$DATADIR/my.cnf\"\n  then\n    log_error \"WARNING: Found $DATADIR/my.cnf\nThe data directory is a deprecated location for my.cnf, please move it to\n$MY_BASEDIR_VERSION/my.cnf\"\n    MYSQL_HOME=$DATADIR\n  else\n    MYSQL_HOME=$MY_BASEDIR_VERSION\n  fi\nfi\nexport MYSQL_HOME\n\n\n# Get first arguments from the my.cnf file, groups [mysqld] and [mysqld_safe]\n# and then merge with the command line arguments\nif test -x \"$MY_BASEDIR_VERSION/bin/my_print_defaults\"\nthen\n  print_defaults=\"$MY_BASEDIR_VERSION/bin/my_print_defaults\"\nelif test -x `dirname $0`/my_print_defaults\nthen\n  print_defaults=\"`dirname $0`/my_print_defaults\"\nelif test -x ./bin/my_print_defaults\nthen\n  print_defaults=\"./bin/my_print_defaults\"\nelif test -x @bindir@/my_print_defaults\nthen\n  print_defaults=\"@bindir@/my_print_defaults\"\nelif test -x @bindir@/mysql_print_defaults\nthen\n  print_defaults=\"@bindir@/mysql_print_defaults\"\nelse\n  print_defaults=\"my_print_defaults\"\nfi\n\nappend_arg_to_args () {\n  args=\"$args \"`shell_quote_string \"$1\"`\n}\n\nargs=\n\nSET_USER=2\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld server`\nif test $SET_USER -eq 2\nthen\n  SET_USER=0\nfi\n\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld`\nparse_arguments PICK-ARGS-FROM-ARGV \"$@\"\n\n#\n# Try to find the plugin directory\n#\n\n# Use user-supplied argument\nif [ -n \"${PLUGIN_DIR}\" ]; then\n  plugin_dir=\"${PLUGIN_DIR}\"\nelse\n  # Try to find plugin dir relative to basedir\n  for dir in lib64/mysql/plugin lib64/plugin lib/mysql/plugin lib/plugin\n  do\n    if [ -d \"${MY_BASEDIR_VERSION}/${dir}\" ]; then\n      plugin_dir=\"${MY_BASEDIR_VERSION}/${dir}\"\n      break\n    fi\n  done\n  # Give up and use compiled-in default\n  if [ -z \"${plugin_dir}\" ]; then\n    plugin_dir='@pkgplugindir@'\n  fi\nfi\nplugin_dir=\"${plugin_dir}${PLUGIN_VARIANT}\"\n\n# Determine what logging facility to use\n\n# Ensure that 'logger' exists, if it's requested\nif [ $want_syslog -eq 1 ]\nthen\n  my_which logger > /dev/null 2>&1\n  if [ $? -ne 0 ]\n  then\n    log_error \"--syslog requested, but no 'logger' program found.  Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe.\"\n    exit 1\n  fi\nfi\n\nif [ -n \"$err_log\" -o $want_syslog -eq 0 ]\nthen\n  if [ -n \"$err_log\" ]\n  then\n    # mysqld adds \".err\" if there is no extension on the --log-error\n    # argument; must match that here, or mysqld_safe will write to a\n    # different log file than mysqld\n\n    # mysqld does not add \".err\" to \"--log-error=foo.\"; it considers a\n    # trailing \".\" as an extension\n    \n    if expr \"$err_log\" : '.*\\.[^/]*$' > /dev/null\n    then\n        :\n    else\n      err_log=\"$err_log\".err\n    fi\n\n    case \"$err_log\" in\n      /* ) ;;\n      * ) err_log=\"$DATADIR/$err_log\" ;;\n    esac\n  else\n    err_log=$DATADIR/`@HOSTNAME@`.err\n  fi\n\n  append_arg_to_args \"--log-error=$err_log\"\n\n  if [ $want_syslog -eq 1 ]\n  then\n    # User explicitly asked for syslog, so warn that it isn't used\n    log_error \"Can't log to error log and syslog at the same time.  Remove all --log-error configuration options for --syslog to take effect.\"\n  fi\n\n  # Log to err_log file\n  logging=file\nelse\n  if [ -n \"$syslog_tag\" ]\n  then\n    # Sanitize the syslog tag\n    syslog_tag=`echo \"$syslog_tag\" | sed -e 's/[^a-zA-Z0-9_-]/_/g'`\n    syslog_tag_mysqld_safe=\"${syslog_tag_mysqld_safe}-$syslog_tag\"\n    syslog_tag_mysqld=\"${syslog_tag_mysqld}-$syslog_tag\"\n  fi\n  log_notice \"Logging to syslog.\"\n  logging=syslog\nfi\n\nlogdir=`dirname \"$err_log\"`\n# Change the err log to the right user, if possible and it is in use\nif [ $logging = \"file\" -o $logging = \"both\" ]; then\n  if [ ! -f \"$err_log\" -a ! -h \"$err_log\" ]; then\n    if test -w / -o \"$USER\" = \"root\"; then\n      case $logdir in\n        /var/log)\n          (\n            umask 0137\n            set -o noclobber\n            > \"$err_log\" && chown $user \"$err_log\"\n          ) ;;\n        *) ;;\n      esac\n    else\n      (\n        umask 0137\n        set -o noclobber\n        > \"$err_log\"\n      )\n    fi\n  fi\n\n  if [ -f \"$err_log\" ]; then        # Log to err_log file\n    log_notice \"Logging to '$err_log'.\"\n  elif [ \"x$user\" = \"xroot\" ]; then # running as root, mysqld can create log file; continue\n    echo \"Logging to '$err_log'.\" >&2\n  else\n    case $logdir in\n      # We can't create $err_log, however mysqld can; continue\n      /tmp|/var/tmp|/var/log/mysql|$DATADIR)\n        echo \"Logging to '$err_log'.\" >&2\n        ;;\n      # We can't create $err_log and don't know if mysqld can; error out\n      *)\n        log_error \"error: log-error set to '$err_log', however file don't exists. Create writable for user '$user'.\"\n        exit 1\n        ;;\n    esac\n  fi\nfi\n\nUSER_OPTION=\"\"\nif test -w / -o \"$USER\" = \"root\"\nthen\n  if test \"$user\" != \"root\" -o $SET_USER = 1\n  then\n    USER_OPTION=\"--user=$user\"\n  fi\n  if test -n \"$open_files\"\n  then\n    ulimit -n $open_files\n  fi\nfi\n\nif test -n \"$open_files\"\nthen\n  append_arg_to_args \"--open-files-limit=$open_files\"\nfi\n\nsafe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}}\n# Check that directory for $safe_mysql_unix_port exists\nmysql_unix_port_dir=`dirname $safe_mysql_unix_port`\nif [ ! -d $mysql_unix_port_dir ]\nthen\n  log_error \"Directory '$mysql_unix_port_dir' for UNIX socket file don't exists.\"\n  exit 1\nfi\n\n# If the user doesn't specify a binary, we assume name \"mysqld\"\nif test -z \"$MYSQLD\"\nthen\n  MYSQLD=mysqld\nfi\n\nif test ! -x \"$ledir/$MYSQLD\"\nthen\n  log_error \"The file $ledir/$MYSQLD\ndoes not exist or is not executable. Please cd to the mysql installation\ndirectory and restart this script from there as follows:\n./bin/mysqld_starter&\nSee http://dev.mysql.com/doc/mysql/en/mysqld-safe.html for more information\"\n  exit 1\nfi\nsetcap 'cap_sys_nice=eip' $ledir/$MYSQLD\nif [ $? -ne 0 ]\nthen\n  echo \"Failed to set capabilities\"\nfi\n\nif test -z \"$pid_file\"\nthen\n  pid_file=\"$DATADIR/`@HOSTNAME@`.pid\"\nelse\n  case \"$pid_file\" in\n    /* ) ;;\n    * )  pid_file=\"$DATADIR/$pid_file\" ;;\n  esac\nfi\nappend_arg_to_args \"--pid-file=$pid_file\"\n\nif test -n \"$mysql_unix_port\"\nthen\n  append_arg_to_args \"--socket=$mysql_unix_port\"\nfi\nif test -n \"$mysql_tcp_port\"\nthen\n  append_arg_to_args \"--port=$mysql_tcp_port\"\nfi\n\nif test $niceness -eq 0\nthen\n  NOHUP_NICENESS=\"nohup\"\nelse\n  NOHUP_NICENESS=\"nohup nice -$niceness\"\nfi\n\n# Using nice with no args to get the niceness level is GNU-specific.\n# This check could be extended for other operating systems (e.g.,\n# BSD could use \"nohup sh -c 'ps -o nice -p $$' | tail -1\").\n# But, it also seems that GNU nohup is the only one which messes\n# with the priority, so this is okay.\nif nohup nice > /dev/null 2>&1\nthen\n    normal_niceness=`nice`\n    nohup_niceness=`nohup nice 2>/dev/null`\n\n    numeric_nice_values=1\n    for val in $normal_niceness $nohup_niceness\n    do\n        case \"$val\" in\n            -[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \\\n             [0-9] |  [0-9][0-9] |  [0-9][0-9][0-9] )\n                ;;\n            * )\n                numeric_nice_values=0 ;;\n        esac\n    done\n\n    if test $numeric_nice_values -eq 1\n    then\n        nice_value_diff=`expr $nohup_niceness - $normal_niceness`\n        if test $? -eq 0 && test $nice_value_diff -gt 0 && \\\n            nice --$nice_value_diff echo testing > /dev/null 2>&1\n        then\n            # nohup increases the priority (bad), and we are permitted\n            # to lower the priority with respect to the value the user\n            # might have been given\n            niceness=`expr $niceness - $nice_value_diff`\n            NOHUP_NICENESS=\"nice -$niceness nohup\"\n        fi\n    fi\nelse\n    if nohup echo testing > /dev/null 2>&1\n    then\n        :\n    else\n        # nohup doesn't work on this system\n        NOHUP_NICENESS=\"\"\n    fi\nfi\n\n# Try to set the core file size (even if we aren't root) because many systems\n# don't specify a hard limit on core file size.\nif test -n \"$core_file_size\"\nthen\n  ulimit -c $core_file_size\nfi\n\n#\n# If there exists an old pid file, check if the daemon is already running\n# Note: The switches to 'ps' may depend on your operating system\nif test -f \"$pid_file\"\nthen\n  PID=`cat \"$pid_file\"`\n  if @CHECK_PID@\n  then\n    if @FIND_PROC@\n    then    # The pid contains a mysqld process\n      log_error \"A mysqld process already exists\"\n      exit 1\n    fi\n  fi\n  if [ ! -h \"$pid_file\" ]; then\n      rm -f \"$pid_file\"\n  fi\n  if test -f \"$pid_file\"\n  then\n    log_error \"Fatal error: Can't remove the pid file:\n$pid_file\nPlease remove it manually and start $0 again;\nmysqld daemon not started\"\n    exit 1\n  fi\nfi\n\n#\n# Flush and purge buffers/caches.\n#\n\nif @TARGET_LINUX@ && test $flush_caches -eq 1\nthen\n  # Locate sync, ensure it exists.\n  if ! my_which sync > /dev/null 2>&1\n  then\n    log_error \"sync command not found, required for --flush-caches\"\n    exit 1\n  # Flush file system buffers.\n  elif ! sync\n  then\n    # Huh, the sync() function is always successful...\n    log_error \"sync failed, check if sync is properly installed\"\n  fi\n\n  # Locate sysctl, ensure it exists.\n  if ! my_which sysctl > /dev/null 2>&1\n  then\n    log_error \"sysctl command not found, required for --flush-caches\"\n    exit 1\n  # Purge page cache, dentries and inodes.\n  elif ! sysctl -q -w vm.drop_caches=3\n  then\n    log_error \"sysctl failed, check the error message for details\"\n    exit 1\n  fi\nelif test $flush_caches -eq 1\nthen\n  log_error \"--flush-caches is not supported on this platform\"\n  exit 1\nfi\n\n#\n# Uncomment the following lines if you want all tables to be automatically\n# checked and repaired during startup. You should add sensible key_buffer\n# and sort_buffer values to my.cnf to improve check performance or require\n# less disk space.\n# Alternatively, you can start mysqld with the \"myisam-recover\" option. See\n# the manual for details.\n#\n# echo \"Checking tables in $DATADIR\"\n# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI\n# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM\n\n# Does this work on all systems?\n#if type ulimit | grep \"shell builtin\" > /dev/null\n#then\n#  ulimit -n 256 > /dev/null 2>&1\t\t# Fix for BSD and FreeBSD systems\n#fi\n\ncmd=\"$NOHUP_NICENESS\"\n\n#\n# Set mysqld's memory interleave policy.\n#\n\nif @TARGET_LINUX@ && test $numa_interleave -eq 1\nthen\n  # Locate numactl, ensure it exists.\n  if ! my_which numactl > /dev/null 2>&1\n  then\n    log_error \"numactl command not found, required for --numa-interleave\"\n    exit 1\n  # Attempt to run a command, ensure it works.\n  elif ! numactl --interleave=all true\n  then\n    log_error \"numactl failed, check if numactl is properly installed\"\n  fi\n\n  # Launch mysqld with numactl.\n  cmd=\"$cmd numactl --interleave=all\"\nelif test $numa_interleave -eq 1\nthen\n  log_error \"--numa-interleave is not supported on this platform\"\n  exit 1\nfi\n\nif @TARGET_LINUX@ && test ! -z \"$numa_nodebind\"\nthen\n  # Locate numactl, ensure it exists.\n  if ! my_which numactl > /dev/null 2>&1\n  then\n    log_error \"numactl command not found, required for --numa-nodebind\"\n    exit 1\n  fi\n\n  # Attempt to run a command, ensure it works.\n  if ! numactl --cpunodebind=$numa_nodebind --preferred=$numa_nodebind true\n  then\n    log_error \"numactl failed, check if numa-nodebind value is correct\"\n    exit 1\n  fi\n\n  # Launch mysqld with numactl.\n  cmd=\"$cmd numactl --cpunodebind=$numa_nodebind --preferred=$numa_nodebind\"\nelif test ! -z \"$numa_nodebind\"\nthen\n  log_error \"--numa-nodebind is not supported on this platform\"\n  exit 1\nfi\n\nif [ ! -z \"`mysqld_ld_preload_text`\" ]; then\n  cmd=\"$cmd env `mysqld_ld_preload_text`\"\nfi\n\nfor i in  \"$ledir/$MYSQLD\" \"$defaults\" \"--basedir=$MY_BASEDIR_VERSION\" \\\n  \"--datadir=$DATADIR\" \"--plugin-dir=$plugin_dir\" \"$USER_OPTION\"\ndo\n  cmd=\"$cmd \"`shell_quote_string \"$i\"`\ndone\ncmd=\"$cmd $args\"\ncmd_skip_core=\"$cmd --skip-core-file\"\n# Avoid 'nohup: ignoring input' warning\ntest -n \"$NOHUP_NICENESS\" && cmd=\"$cmd < /dev/null\" \\\n                          && cmd_skip_core=\"$cmd_skip_core < /dev/null\"\ncmd_saved=\"$cmd\"\n\nlog_notice \"Starting $MYSQLD daemon with databases from $DATADIR\"\n\n# Some extra safety\nif [ ! -h \"$safe_mysql_unix_port\" ]; then\n  rm -f \"$safe_mysql_unix_port\"\nfi\nif [ ! -h \"$pid_file\" ]; then\n  rm -f \"$pid_file\"\nfi\nif [ ! -h \"$pid_file.shutdown\" ]; then\n  rm -f \"$pid_file.shutdown\"\nfi\n\neval_log_error \"$cmd\"\n\n# hypothetical: log was renamed but not\n# flushed yet. we'd recreate it with\n# wrong owner next time we log, so set\n# it up correctly while we can!\n\nif [ $want_syslog -eq 0 -a ! -f \"$err_log\" -a ! -h \"$err_log\" ]; then\n  if test -w / -o \"$USER\" = \"root\"; then\n    logdir=`dirname \"$err_log\"`\n    case $logdir in\n      /var/log)\n        (\n          umask 0137\n          set -o noclobber\n          > \"$err_log\" && chown $user \"$err_log\"\n        ) ;;\n      *) ;;\n    esac\n  else\n    (\n      umask 0137\n      set -o noclobber\n      > \"$err_log\"\n    )\n  fi\nfi\n\nlog_notice \"mysqld from pid file $pid_file ended\"\n\nexit $exit_code\n", "num_lines": 1005}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# This script reports various configuration settings that may be needed\n# when using the MySQL client library.\n\nwhich ()\n{\n  IFS=\"${IFS=   }\"; save_ifs=\"$IFS\"; IFS=':'\n  for file\n  do\n    for dir in $PATH\n    do\n      if test -f $dir/$file\n      then\n        echo \"$dir/$file\"\n        continue 2\n      fi\n    done\n    echo \"which: no $file in ($PATH)\"\n    exit 1\n  done\n  IFS=\"$save_ifs\"\n}\n\n#\n# If we can find the given directory relatively to where mysql_config is\n# we should use this instead of the incompiled one.\n# This is to ensure that this script also works with the binary MySQL\n# version\n\nfix_path ()\n{\n  var=$1\n  shift\n  for filename\n  do\n    path=$basedir/$filename\n    if [ -d \"$path\" ] ;\n    then\n      eval \"$var\"=$path\n      return\n    fi\n  done\n}\n\nget_full_path ()\n{\n  file=$1\n\n  # if the file is a symlink, try to resolve it\n  if [ -h $file ];\n  then\n    file=`ls -l $file | awk '{ print $NF }'`\n  fi\n\n  case $file in\n    /*) echo \"$file\";;\n    */*) tmp=`pwd`/$file; echo $tmp | sed -e 's;/\\./;/;' ;;\n    *) which $file ;;\n  esac\n}\n\nme=`get_full_path $0`\n\n# Script might have been renamed but assume mysql_<something>config<something>\nbasedir=`echo $me | sed -e 's;/bin/mysql_.*config.*;;'`\n\nldata='@localstatedir@'\nexecdir='@libexecdir@'\nbindir='@bindir@'\n\n# If installed, search for the compiled in directory first (might be \"lib64\")\npkglibdir='@pkglibdir@'\npkglibdir_rel=`echo $pkglibdir | sed -e \"s;^$basedir/;;\"`\nfix_path pkglibdir $pkglibdir_rel @libsubdir@/mysql @libsubdir@\n\nplugindir='@pkgplugindir@'\nplugindir_rel=`echo $plugindir | sed -e \"s;^$basedir/;;\"`\nfix_path plugindir $plugindir_rel @libsubdir@/mysql/plugin @libsubdir@/plugin\n\npkgincludedir='@pkgincludedir@'\nif [ -f \"$basedir/include/mysql/mysql.h\" ]; then\n  pkgincludedir=\"$basedir/include/mysql\"\nelif [ -f \"$basedir/include/mysql.h\" ]; then\n  pkgincludedir=\"$basedir/include\"\nfi\n\nversion='@VERSION@'\nsocket='@MYSQL_UNIX_ADDR@'\nldflags='@LDFLAGS@'\n\nif [ @MYSQL_TCP_PORT_DEFAULT@ -eq 0 ]; then\n  port=0\nelse\n  port=@MYSQL_TCP_PORT@\nfi\n\n# Create options \n# We intentionally add a space to the beginning and end of lib strings, simplifies replace later\nlibs=\" $ldflags -L$pkglibdir @RPATH_OPTION@ \"\nlibs=\"$libs -lfbmysqlclient @ZLIB_DEPS@ @NON_THREADED_LIBS@ \"\nlibs=\"$libs @openssl_libs@ @STATIC_NSS_FLAGS@ \"\nlibs=\"$libs @QUOTED_CMAKE_C_LINK_FLAGS@\"\nlibs_r=\" $ldflags -L$pkglibdir @RPATH_OPTION@ \"\nlibs_r=\"$libs_r -lfbmysqlclient @ZLIB_DEPS@ @CLIENT_LIBS@ @openssl_libs@ \"\nlibs_r=\"$libs_r @QUOTED_CMAKE_C_LINK_FLAGS@\"\nembedded_libs=\" $ldflags -L$pkglibdir @RPATH_OPTION@ -lmysqld @LIBDL@ @ZLIB_DEPS@ @LIBS@ @WRAPLIBS@ @openssl_libs@ \"\nembedded_libs=\"$embedded_libs @QUOTED_CMAKE_CXX_LINK_FLAGS@\"\n\ncflags=\"-I$pkgincludedir @CFLAGS@ \" #note: end space!\ncxxflags=\"-I$pkgincludedir @CXXFLAGS@ \" #note: end space!\ninclude=\"-I$pkgincludedir\"\n\n# Remove some options that a client doesn't have to care about\nfor remove in DDBUG_OFF DSAFE_MUTEX DFORCE_INIT_OF_VARS \\\n              DEXTRA_DEBUG DHAVE_purify O 'O[0-9]' 'xO[0-9]' 'W[-A-Za-z]*' \\\n              'mtune=[-A-Za-z0-9]*' 'mcpu=[-A-Za-z0-9]*' 'march=[-A-Za-z0-9]*' \\\n              unroll2 ip mp restrict 'specs=[A-Za-z0-9/]*\\.spec'\ndo\n  # The first option we might strip will always have a space before it because\n  # we set -I$pkgincludedir as the first option\n  cflags=`echo \"$cflags\"|sed -e \"s/ -$remove  */ /g\"` \n  cxxflags=`echo \"$cxxflags\"|sed -e \"s/ -$remove  */ /g\"` \ndone\ncflags=`echo \"$cflags\"|sed -e 's/ *\\$//'` \ncxxflags=`echo \"$cxxflags\"|sed -e 's/ *\\$//'` \n\n# Same for --libs(_r)\nfor remove in lmtmalloc static-libcxa i-static static-intel\ndo\n  # We know the strings starts with a space\n  libs=`echo \"$libs\"|sed -e \"s/ -$remove  */ /g\"` \n  libs_r=`echo \"$libs_r\"|sed -e \"s/ -$remove  */ /g\"` \n  embedded_libs=`echo \"$embedded_libs\"|sed -e \"s/ -$remove  */ /g\"` \ndone\n\n# Strip trailing and ending space if any, and '+' (FIXME why?)\nlibs=`echo \"$libs\" | sed -e 's;  \\+; ;g' | sed -e 's;^ *;;' | sed -e 's; *\\$;;'`\nlibs_r=`echo \"$libs_r\" | sed -e 's;  \\+; ;g' | sed -e 's;^ *;;' | sed -e 's; *\\$;;'`\nembedded_libs=`echo \"$embedded_libs\" | sed -e 's;  \\+; ;g' | sed -e 's;^ *;;' | sed -e 's; *\\$;;'`\n\nusage () {\n        cat <<EOF\nUsage: $0 [OPTIONS]\nOptions:\n        --cflags         [$cflags]\n        --cxxflags       [$cxxflags]\n        --include        [$include]\n        --libs           [$libs]\n        --libs_r         [$libs_r]\n        --plugindir      [$plugindir]\n        --socket         [$socket]\n        --port           [$port]\n        --version        [$version]\n        --libmysqld-libs [$embedded_libs]\n        --variable=VAR   VAR is one of:\n                pkgincludedir [$pkgincludedir]\n                pkglibdir     [$pkglibdir]\n                plugindir     [$plugindir]\nEOF\n        exit 1\n}\n\nif test $# -le 0; then usage; fi\n\nwhile test $# -gt 0; do\n        case $1 in\n        --cflags)  echo \"$cflags\" ;;\n        --cxxflags)echo \"$cxxflags\";;\n        --include) echo \"$include\" ;;\n        --libs)    echo \"$libs\" ;;\n        --libs_r)  echo \"$libs_r\" ;;\n        --plugindir) echo \"$plugindir\" ;;\n        --socket)  echo \"$socket\" ;;\n        --port)    echo \"$port\" ;;\n        --version) echo \"$version\" ;;\n        --embedded-libs | --embedded | --libmysqld-libs) echo \"$embedded_libs\" ;;\n        --variable=*)\n          var=`echo \"$1\" | sed 's,^[^=]*=,,'`\n          case \"$var\" in\n            pkgincludedir) echo \"$pkgincludedir\" ;;\n            pkglibdir) echo \"$pkglibdir\" ;;\n            plugindir) echo \"$plugindir\" ;;\n            *) usage ;;\n          esac\n          ;;\n        *)         usage ;;\n        esac\n\n        shift\ndone\n\n#echo \"ldata: '\"$ldata\"'\"\n#echo \"execdir: '\"$execdir\"'\"\n#echo \"bindir: '\"$bindir\"'\"\n#echo \"pkglibdir: '\"$pkglibdir\"'\"\n#echo \"pkgincludedir: '\"$pkgincludedir\"'\"\n#echo \"version: '\"$version\"'\"\n#echo \"socket: '\"$socket\"'\"\n#echo \"port: '\"$port\"'\"\n#echo \"ldflags: '\"$ldflags\"'\"\n#echo \"client_libs: '\"$client_libs\"'\"\n\nexit 0\n", "num_lines": 219}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# Convert given tables in a database to MYISAM\n\nuse DBI;\nuse Getopt::Long;\n\n$opt_help=$opt_version=$opt_verbose=$opt_force=0;\n$opt_user=$opt_database=$opt_password=undef;\n$opt_host=\"localhost\";\n$opt_socket=\"\";\n$opt_engine=\"MYISAM\";\n$opt_port=0;\n$exit_status=0;\n\nGetOptions(\n  \"e|engine|type=s\"       => \\$opt_type,\n  \"f|force\"               => \\$opt_force,\n  \"help|?\"               => \\$opt_help,\n  \"h|host=s\"              => \\$opt_host,\n  \"p|password=s\"          => \\$opt_password,\n  \"u|user=s\"              => \\$opt_user,\n  \"v|verbose\"             => \\$opt_verbose,\n  \"V|version\"             => \\$opt_version,\n  \"S|socket=s\"            => \\$opt_socket, \n  \"P|port=i\"              => \\$opt_port\n) || usage(0);\n\nprint STDERR \"Warning: $0 is deprecated and will be removed in a future version.\\n\";\n\nusage($opt_version) if ($#ARGV < 0 || $opt_help || $opt_version);\n\n$opt_database=shift(@ARGV);\n\nif (grep { /^$opt_engine$/i } qw(HEAP MEMORY BLACKHOLE))\n{\n  print \"Converting to '$opt_engine' would delete your data; aborting\\n\";\n  exit(1);\n}\n\n$connect_opt=\"\";\nif ($opt_port)\n{\n  $connect_opt.= \";port=$opt_port\";\n}\nif (length($opt_socket))\n{\n  $connect_opt.=\";mysql_socket=$opt_socket\";\n}\n\n$dbh = DBI->connect(\"DBI:mysql:$opt_database:${opt_host}$connect_opt\",\n\t\t    $opt_user,\n\t\t    $opt_password,\n\t\t    { PrintError => 0})\n  || die \"Can't connect to database $opt_database: $DBI::errstr\\n\";\n\nmy @tables;\n\npush(@ARGV, \"%\") if(!@ARGV);\n\nforeach $pattern (@ARGV)\n{\n  my ($sth,$row);\n  $sth=$dbh->prepare(\"SHOW TABLES LIKE ?\");\n  $rv= $sth->execute($pattern);\n  if(!int($rv))\n  {\n    warn \"Can't get tables matching '$pattern' from $opt_database; $DBI::errstr\\n\"; \n    exit(1) unless $opt_force;\n  }\n  while (($row = $sth->fetchrow_arrayref))\n  {\n    push(@tables, $row->[0]);\n  }\n  $sth->finish;\n}\n\nprint \"Converting tables:\\n\" if ($opt_verbose);\nforeach $table (@tables)\n{\n  my ($sth,$row);\n\n  # Check if table is already converted\n  $sth=$dbh->prepare(\"show table status like '$table'\");  \n  if ($sth->execute && ($row = $sth->fetchrow_arrayref))\n  {\n    if (uc($row->[1]) eq uc($opt_engine))\n    {\n      print \"$table already uses the '$opt_engine' engine;  Ignored\\n\";\n      next;\n    }\n  }\n  print \"converting $table\\n\" if ($opt_verbose);\n  $table=~ s/`/``/g;\n  if (!$dbh->do(\"ALTER TABLE `$table` ENGINE=$opt_engine\"))\n  {\n    print STDERR \"Can't convert $table: Error $DBI::errstr\\n\";\n    exit(1) if (!$opt_force);\n    $exit_status=1;\n  }\n}\n\n$dbh->disconnect;\nexit($exit_status);\n\n\nsub usage\n{\n  my($version)=shift;\n  print \"$0  version 1.1\\n\";\n  exit(0) if ($version);\n\n  print <<EOF;\n\nConversion of a MySQL tables to other storage engines\n\n Usage: $0 database [table[ table ...]]\n If no tables has been specifed, all tables in the database will be converted.\n You can also use wildcards, ie \"my%\"\n\n The following options are available:\n\n-f, --force\n  Continue even if there is some error.\n\n-?, --help\n  Shows this help\n\n-e, --engine=ENGINE\n  Converts tables to the given storage engine (Default: $opt_engine)\n\n-h, --host=HOST\n  Host name where the database server is located. (Default: $opt_host)\n\n-p, --password=PASSWORD\n  Password for the current user.\n\n-P, --port=PORT\n  TCP/IP port to connect to if host is not \"localhost\".\n\n-S, --socket=SOCKET\n  Socket to connect with.\n\n-u, --user=USER\n  User name to log into the SQL server.\n\n-v, --verbose\n  This is a test specific option that is only used when debugging a test.\n  Print more information about what is going on.\n\n-V, --version\n  Shows the version of this program.\nEOF\n  exit(1);\n}\n", "num_lines": 171}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n$version=\"1.02\";\n\nuse Getopt::Long;\n\n$opt_help=$opt_Information=$opt_skip_use_db=0;\n$opt_regexp=$opt_dbregexp=\".*\";\n$opt_start_row=1; $opt_rows=9999999999;\n\nprint STDERR \"Warning: $0 is deprecated and will be removed in a future version.\\n\";\n\nGetOptions(\"Information\",\"help\",\"regexp=s\",\"start_row=i\",\"rows=i\",\n\t   \"dbregexp=s\", \"skip-use-db\")\n  || usage();\nusage() if ($opt_help || $opt_Information);\n\n$query=$search=$database=$set=\"\"; $eoq=0;\nwhile (<>)\n{\n  next if (length($query) == 0 && /^\\#/); # Skip comments\n  $query.=search($_);\n  if ($eoq)\n  {\n    if ($query =~ /^use /i || $query =~ /^SET / ||\n\t($query =~ /$opt_regexp/o && $database =~ /$opt_dbregexp/o))\n    {\n      if ($opt_skip_use_db && $query =~ /^use /i)\n      {\n\t$query=\"\";\n\tnext;\n      }\n      if ($opt_start_row <= 1)\n      {\n\tif ($database)\n\t{\n\t  print $database, $set;\n\t  $database=$set=\"\";\n\t}\n\tprint $query;\n\tlast if (--$opt_rows == 0);\n      }\n      else\n      {\n\t$opt_start_row--;\n\tif ($query =~ /^use /)\n\t{\n\t  $database=$query;\n\t  $set=\"\";\n\t}\n\telsif ($query =~ /^SET/)\n\t{\n\t  $set=$query;\n\t}\n\telse\n\t{\n\t  $set=\"\";\n\t}\n      }\n    }\n    $query=\"\"; $search=\"\"; $eoq=0;\n  }\n}\n\nexit 0;\n\nsub search\n{\n  my($row)=shift;\n  my($i);\n\n  for ($i=0 ; $i < length($row) ; $i++)\n  {\n    if (length($search))\n    {\n      if (length($search) > 1)\n      {\t\t\t\t# Comment\n\tnext if (substr($row,$i,length($search)) ne $search);\n\t$i+=length($search)-1;\n\t$search=\"\";\n      }\n      elsif (substr($row,$i,1) eq '\\\\') # Escaped char in string\n      {\n\t$i++;\n      }\n      elsif (substr($row,$i,1) eq $search)\n      {\n\tif (substr($row,$i+1,1) eq $search)\t# Double \" or '\n\t{\n\t  $i++;\n\t}\n\telse\n\t{\n\t  $search=\"\";\n\t}\n      }\n      next;\t\n    }\n    if (substr($row,$i,2) eq '/*')\t# Comment\n    {\n      $search=\"*/\";\n      $i++;\n    }\n    elsif (substr($row,$i,1) eq \"'\" || substr($row,$i,1) eq '\"')\n    {\n      $search=substr($row,$i,1);\n     }\n  }\n  $eoq=1 if (!length($search) && $row =~ /;\\s*$/);\n  return $row;\n}\n\n\nsub usage\n{\n    print <<EOF;\n$0  Ver $version\n\nPrints all SQL queries that matches a regexp or contains a 'use\ndatabase' or 'set ..' command to stdout.  A SQL query may contain\nnewlines.  This is useful to find things in a MySQL update log.\n\n$0 takes the following options:\n\n--help or --Information\n  Shows this help\n\n--regexp=#\n  Print queries that matches this.\n\n--start_row=#\n  Start output from this row (first row = 1)\n\n--skip-use-db\n  Don\\'t include \\'use database\\' commands in the output.\n\n--rows=#\n  Quit after this many rows.\n\nExample:\n\n$0 --regexp \"problem_table\" < update.log\n\n$0 --regexp \"problem_table\" update-log.1 update-log.2\nEOF\n  exit(0);\n}\n", "num_lines": 163}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n\n# Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# This is a utility for MySQL. It is not needed by any standard part\n# of MySQL.\n\n# Usage: mysql_fix_extentions datadir\n# does not work with RAID, with InnoDB or BDB tables\n# makes .frm lowercase and .MYI/MYD/ISM/ISD uppercase\n# useful when datafiles are copied from windows\n\nprint STDERR \"Warning: $0 is deprecated and will be removed in a future version.\\n\";\ndie \"Usage: $0 datadir\\n\" unless -d $ARGV[0];\n\nfor $a (<$ARGV[0]/*/*.*>) { $_=$a;\n  s/\\.frm$/.frm/i;\n  s/\\.(is[md]|my[id])$/\\U$&/i;\n  rename ($a, $_) || warn \"Cannot rename $a => $_ : $!\";\n}\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# This scripts creates the MySQL Server system tables\n#\n# All unrecognized arguments to this script are passed to mysqld.\n\nbasedir=\"\"\nbuilddir=\"\"\nldata=\"@localstatedir@\"\nlangdir=\"\"\nsrcdir=\"\"\n\nargs=\"\"\ndefaults=\"\"\nmysqld_opt=\"\"\nuser=\"\"\n\nforce=0\nin_rpm=0\nip_only=0\ncross_bootstrap=0\n\nusage()\n{\n  cat <<EOF\nUsage: $0 [OPTIONS]\n  --basedir=path       The path to the MySQL installation directory.\n  --builddir=path      If using --srcdir with out-of-directory builds, you\n                       will need to set this to the location of the build\n                       directory where built files reside.\n  --cross-bootstrap    For internal use.  Used when building the MySQL system\n                       tables on a different host than the target.\n  --datadir=path       The path to the MySQL data directory.\n  --defaults-extra-file=name\n                       Read this file after the global files are read.\n  --defaults-file=name Only read default options from the given file name.\n  --force              Causes mysql_install_db to run even if DNS does not\n                       work.  In that case, grant table entries that\n                       normally use hostnames will use IP addresses.\n  --help               Display this help and exit.                     \n  --ldata=path         The path to the MySQL data directory. Same as --datadir.\n  --no-defaults        Don't read default options from any option file.\n  --rpm                For internal use.  This option is used by RPM files\n                       during the MySQL installation process.\n  --skip-name-resolve  Use IP addresses rather than hostnames when creating\n                       grant table entries.  This option can be useful if\n                       your DNS does not work.\n  --srcdir=path        The path to the MySQL source directory.  This option\n                       uses the compiled binaries and support files within the\n                       source tree, useful for if you don't want to install\n                       MySQL yet and just want to create the system tables.\n  --user=user_name     The login username to use for running mysqld.  Files\n                       and directories created by mysqld will be owned by this\n                       user.  You must be root to use this option.  By default\n                       mysqld runs using your current login name and files and\n                       directories that it creates will be owned by you.\n\nAll other options are passed to the mysqld program\n\nEOF\n  exit 1\n}\n\ns_echo()\n{\n  if test \"$in_rpm\" -eq 0 -a \"$cross_bootstrap\" -eq 0\n  then\n    echo \"$1\"\n  fi\n}\n\nparse_arg()\n{\n  echo \"$1\" | sed -e 's/^[^=]*=//'\n}\n\nparse_arguments()\n{\n  # We only need to pass arguments through to the server if we don't\n  # handle them here.  So, we collect unrecognized options (passed on\n  # the command line) into the args variable.\n  pick_args=\n  if test \"$1\" = PICK-ARGS-FROM-ARGV\n  then\n    pick_args=1\n    shift\n  fi\n\n  for arg\n  do\n    case \"$arg\" in\n      --force) force=1 ;;\n      --basedir=*) basedir=`parse_arg \"$arg\"` ;;\n      --builddir=*) builddir=`parse_arg \"$arg\"` ;;\n      --srcdir=*)  srcdir=`parse_arg \"$arg\"` ;;\n      --ldata=*|--datadir=*) ldata=`parse_arg \"$arg\"` ;;\n      --user=*)\n        # Note that the user will be passed to mysqld so that it runs\n        # as 'user' (crucial e.g. if log-bin=/some_other_path/\n        # where a chown of datadir won't help)\n        user=`parse_arg \"$arg\"` ;;\n      --skip-name-resolve) ip_only=1 ;;\n      --verbose) verbose=1 ;; # Obsolete\n      --rpm) in_rpm=1 ;;\n      --help) usage ;;\n      --no-defaults|--defaults-file=*|--defaults-extra-file=*)\n        defaults=\"$arg\" ;;\n\n      --cross-bootstrap|--windows)\n        # Used when building the MySQL system tables on a different host than\n        # the target. The platform-independent files that are created in\n        # --datadir on the host can be copied to the target system.\n        #\n        # The most common use for this feature is in the Windows installer\n        # which will take the files from datadir and include them as part of\n        # the install package.  See top-level 'dist-hook' make target.\n        #\n        # --windows is a deprecated alias\n        cross_bootstrap=1 ;;\n\n      *)\n        if test -n \"$pick_args\"\n        then\n          # This sed command makes sure that any special chars are quoted,\n          # so the arg gets passed exactly to the server.\n          # XXX: This is broken; true fix requires using eval and proper\n          # quoting of every single arg ($basedir, $ldata, etc.)\n          #args=\"$args \"`echo \"$arg\" | sed -e 's,\\([^a-zA-Z0-9_.-]\\),\\\\\\\\\\1,g'`\n          args=\"$args $arg\"\n        fi\n        ;;\n    esac\n  done\n}\n\n# Try to find a specific file within --basedir which can either be a binary\n# release or installed source directory and return the path.\nfind_in_basedir()\n{\n  case \"$1\" in\n    --dir)\n      return_dir=1; shift\n      ;;\n  esac\n\n  file=$1; shift\n\n  for dir in \"$@\"\n  do\n    if test -f \"$basedir/$dir/$file\"\n    then\n      if test -n \"$return_dir\"\n      then\n        echo \"$basedir/$dir\"\n      else\n        echo \"$basedir/$dir/$file\"\n      fi\n      break\n    fi\n  done\n}\n\ncannot_find_file()\n{\n  echo\n  echo \"FATAL ERROR: Could not find $1\"\n\n  shift\n  if test $# -ne 0\n  then\n    echo\n    echo \"The following directories were searched:\"\n    echo\n    for dir in \"$@\"\n    do\n      echo \"    $dir\"\n    done\n  fi\n\n  echo\n  echo \"If you compiled from source, you need to run 'make install' to\"\n  echo \"copy the software into the correct location ready for operation.\"\n  echo\n  echo \"If you are using a binary release, you must either be at the top\"\n  echo \"level of the extracted archive, or pass the --basedir option\"\n  echo \"pointing to that location.\"\n  echo\n}\n\n# Ok, let's go.  We first need to parse arguments which are required by\n# my_print_defaults so that we can execute it first, then later re-parse\n# the command line to add any extra bits that we need.\nparse_arguments PICK-ARGS-FROM-ARGV \"$@\"\n\n#\n# We can now find my_print_defaults.  This script supports:\n#\n#   --srcdir=path pointing to compiled source tree\n#   --basedir=path pointing to installed binary location\n#\n# or default to compiled-in locations.\n#\nif test -n \"$srcdir\" && test -n \"$basedir\"\nthen\n  echo \"ERROR: Specify either --basedir or --srcdir, not both.\"\n  exit 1\nfi\nif test -n \"$srcdir\"\nthen\n  if test -z \"$builddir\"\n  then\n    builddir=\"$srcdir\"\n  fi\n  print_defaults=\"$builddir/extra/my_print_defaults\"\nelif test -n \"$basedir\"\nthen\n  print_defaults=`find_in_basedir my_print_defaults bin extra`\n  if test -z \"$print_defaults\"\n  then\n    cannot_find_file my_print_defaults $basedir/bin $basedir/extra\n    exit 1\n  fi\nelse\n  print_defaults=\"@bindir@/my_print_defaults\"\nfi\n\nif test ! -x \"$print_defaults\"\nthen\n  cannot_find_file \"$print_defaults\"\n  exit 1\nfi\n\n# Now we can get arguments from the groups [mysqld] and [mysql_install_db]\n# in the my.cfg file, then re-run to merge with command line arguments.\nparse_arguments `$print_defaults $defaults mysqld mysql_install_db`\nparse_arguments PICK-ARGS-FROM-ARGV \"$@\"\n\n# Configure paths to support files\nif test -n \"$srcdir\"\nthen\n  basedir=\"$builddir\"\n  bindir=\"$basedir/client\"\n  extra_bindir=\"$basedir/extra\"\n  mysqld=\"$basedir/sql/mysqld\"\n  langdir=\"$srcdir/sql/share/english\"\n  pkgdatadir=\"$srcdir/scripts\"\n  scriptdir=\"$srcdir/scripts\"\nelif test -n \"$basedir\"\nthen\n  bindir=\"$basedir/bin\"\n  extra_bindir=\"$bindir\"\n  mysqld=`find_in_basedir mysqld libexec sbin bin`\n  if test -z \"$mysqld\"\n  then\n    cannot_find_file mysqld $basedir/libexec $basedir/sbin $basedir/bin\n    exit 1\n  fi\n  langdir=`find_in_basedir --dir errmsg.sys share/english share/mysql/english`\n  if test -z \"$langdir\"\n  then\n    cannot_find_file errmsg.sys $basedir/share/english $basedir/share/mysql/english\n    exit 1\n  fi\n  pkgdatadir=`find_in_basedir --dir fill_help_tables.sql share share/mysql`\n  if test -z \"$pkgdatadir\"\n  then\n    cannot_find_file fill_help_tables.sql $basedir/share $basedir/share/mysql\n    exit 1\n  fi\n  scriptdir=\"$basedir/scripts\"\nelse\n  basedir=\"@prefix@\"\n  bindir=\"@bindir@\"\n  extra_bindir=\"$bindir\"\n  mysqld=\"@libexecdir@/mysqld\"\n  pkgdatadir=\"@pkgdatadir@\"\n  scriptdir=\"@scriptdir@\"\nfi\n\n# Set up paths to SQL scripts required for bootstrap\nfill_help_tables=\"$pkgdatadir/fill_help_tables.sql\"\ncreate_system_tables=\"$pkgdatadir/mysql_system_tables.sql\"\nfill_system_tables=\"$pkgdatadir/mysql_system_tables_data.sql\"\n\nfor f in $fill_help_tables $create_system_tables $fill_system_tables\ndo\n  if test ! -f \"$f\"\n  then\n    cannot_find_file \"$f\"\n    exit 1\n  fi\ndone\n\nif test ! -x \"$mysqld\"\nthen\n  cannot_find_file \"$mysqld\"\n  exit 1\nfi\n\nif test -n \"$langdir\"\nthen\n  if test ! -f \"$langdir/errmsg.sys\"\n  then\n    cannot_find_file \"$langdir/errmsg.sys\"\n    exit 1\n  fi\n  mysqld_opt=\"--lc-messages-dir=$langdir/..\"\nfi\n\n# Try to determine the hostname\nhostname=`@HOSTNAME@`\n\n# Check if hostname is valid\nif test \"$cross_bootstrap\" -eq 0 -a \"$in_rpm\" -eq 0 -a \"$force\" -eq 0\nthen\n  resolved=`$extra_bindir/resolveip $hostname 2>&1`\n  if test $? -ne 0\n  then\n    resolved=`$extra_bindir/resolveip localhost 2>&1`\n    if test $? -ne 0\n    then\n      echo \"Neither host '$hostname' nor 'localhost' could be looked up with\"\n      echo \"$extra_bindir/resolveip\"\n      echo \"Please configure the 'hostname' command to return a correct\"\n      echo \"hostname.\"\n      echo \"If you want to solve this at a later stage, restart this script\"\n      echo \"with the --force option\"\n      exit 1\n    fi\n    echo \"WARNING: The host '$hostname' could not be looked up with resolveip.\"\n    echo \"This probably means that your libc libraries are not 100 % compatible\"\n    echo \"with this binary MySQL version. The MySQL daemon, mysqld, should work\"\n    echo \"normally with the exception that host name resolving will not work.\"\n    echo \"This means that you should use IP addresses instead of hostnames\"\n    echo \"when specifying MySQL privileges !\"\n  fi\nfi\n\nif test \"$ip_only\" -eq 1\nthen\n  hostname=`echo \"$resolved\" | awk '/ /{print $6}'`\nfi\n\n# Create database directories\nfor dir in $ldata $ldata/mysql $ldata/test\ndo\n  if test ! -d $dir\n  then\n    mkdir -p $dir\n    chmod 700 $dir\n  fi\n  if test -n \"$user\"\n  then\n    chown $user $dir\n    if test $? -ne 0\n    then\n      echo \"Cannot change ownership of the database directories to the '$user'\"\n      echo \"user.  Check that you have the necessary permissions and try again.\"\n      exit 1\n    fi\n  fi\ndone\n\nif test -n \"$user\"\nthen\n  args=\"$args --user=$user\"\nfi\n\n# When doing a \"cross bootstrap\" install, no reference to the current\n# host should be added to the system tables.  So we filter out any\n# lines which contain the current host name.\nif test $cross_bootstrap -eq 1\nthen\n  filter_cmd_line=\"sed -e '/@current_hostname/d'\"\nelse\n  filter_cmd_line=\"cat\"\nfi\n\n# Configure mysqld command line\nmysqld_bootstrap=\"${MYSQLD_BOOTSTRAP-$mysqld}\"\nmysqld_install_cmd_line=\"$mysqld_bootstrap $defaults $mysqld_opt --bootstrap \\\n  --basedir=$basedir --datadir=$ldata --log-warnings=0 \\\n  --loose-skip-ndbcluster $args --max_allowed_packet=8M \\\n  --net_buffer_length=16K\"\n\n# Create the system and help tables by passing them to \"mysqld --bootstrap\"\ns_echo \"Installing MySQL system tables...\"\nif { echo \"use mysql;\"; cat $create_system_tables $fill_system_tables; } | eval \"$filter_cmd_line\" | $mysqld_install_cmd_line > /dev/null\nthen\n  s_echo \"OK\"\nelse\n  echo\n  echo \"Installation of system tables failed!  Examine the logs in\"\n  echo \"$ldata for more information.\"\n  echo\n  echo \"You can try to start the mysqld daemon with:\"\n  echo\n  echo \"    shell> $mysqld --skip-grant-tables &\"\n  echo\n  echo \"and use the command line tool $bindir/mysql\"\n  echo \"to connect to the mysql database and look at the grant tables:\"\n  echo\n  echo \"    shell> $bindir/mysql -u root mysql\"\n  echo \"    mysql> show tables\"\n  echo\n  echo \"Try 'mysqld --help' if you have problems with paths.  Using --log\"\n  echo \"gives you a log in $ldata that may be helpful.\"\n  echo\n  echo \"Please consult the MySQL manual section\"\n  echo \"'Problems running mysql_install_db', and the manual section that\"\n  echo \"describes problems on your OS.  Another information source are the\"\n  echo \"MySQL email archives available at http://lists.mysql.com/.\"\n  echo\n  echo \"Please check all of the above before submitting a bug report\"\n  echo \"at http://bugs.mysql.com/\"\n  echo\n  exit 1\nfi\n\ns_echo \"Filling help tables...\"\nif { echo \"use mysql;\"; cat $fill_help_tables; } | $mysqld_install_cmd_line > /dev/null\nthen\n  s_echo \"OK\"\nelse\n  echo\n  echo \"WARNING: HELP FILES ARE NOT COMPLETELY INSTALLED!\"\n  echo \"The \\\"HELP\\\" command might not work properly.\"\nfi\n\n# Don't output verbose information if running inside bootstrap or using\n# --srcdir for testing.  In such cases, there's no end user looking at\n# the screen.\nif test \"$cross_bootstrap\" -eq 0 && test -z \"$srcdir\"\nthen\n  s_echo\n  s_echo \"To start mysqld at boot time you have to copy\"\n  s_echo \"support-files/mysql.server to the right place for your system\"\n\n  echo\n  echo \"PLEASE REMEMBER TO SET A PASSWORD FOR THE MySQL root USER !\"\n  echo \"To do so, start the server, then issue the following commands:\"\n  echo\n  echo \"$bindir/mysqladmin -u root password 'new-password'\"\n  echo \"$bindir/mysqladmin -u root -h $hostname password 'new-password'\"\n  echo\n  echo \"Alternatively you can run:\"\n  echo \"$bindir/mysql_secure_installation\"\n  echo\n  echo \"which will also give you the option of removing the test\"\n  echo \"databases and anonymous user created by default.  This is\"\n  echo \"strongly recommended for production servers.\"\n  echo\n  echo \"See the manual for more instructions.\"\n\n  if test \"$in_rpm\" -eq 0\n  then\n    echo\n    echo \"You can start the MySQL daemon with:\"\n    echo \"cd $basedir ; $bindir/mysqld_safe &\"\n    echo\n    echo \"You can test the MySQL daemon with mysql-test-run.pl\"\n    echo \"cd $basedir/mysql-test ; perl mysql-test-run.pl\"\n  fi\n\n  echo\n  echo \"Please report any problems at http://bugs.mysql.com/\"\n  echo\nfi\n\nexit 0\n", "num_lines": 485}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nconfig=\".my.cnf.$$\"\ncommand=\".mysql.$$\"\nmysql_client=\"\"\n\ntrap \"interrupt\" 1 2 3 6 15\n\nrootpass=\"\"\necho_n=\necho_c=\n\nset_echo_compat() {\n    case `echo \"testing\\c\"`,`echo -n testing` in\n\t*c*,-n*) echo_n=   echo_c=     ;;\n\t*c*,*)   echo_n=-n echo_c=     ;;\n\t*)       echo_n=   echo_c='\\c' ;;\n    esac\n}\n\nprepare() {\n    touch $config $command\n    chmod 600 $config $command\n}\n\nfind_mysql_client()\n{\n  for n in ./bin/mysql mysql\n  do  \n    $n --no-defaults --help > /dev/null 2>&1\n    status=$?\n    if test $status -eq 0\n    then\n      mysql_client=$n\n      return\n    fi  \n  done\n  echo \"Can't find a 'mysql' client in PATH or ./bin\"\n  exit 1\n}\n\ndo_query() {\n    echo \"$1\" >$command\n    #sed 's,^,> ,' < $command  # Debugging\n    $mysql_client --defaults-file=$config <$command\n    return $?\n}\n\n# Simple escape mechanism (\\-escape any ' and \\), suitable for two contexts:\n# - single-quoted SQL strings\n# - single-quoted option values on the right hand side of = in my.cnf\n#\n# These two contexts don't handle escapes identically.  SQL strings allow\n# quoting any character (\\C => C, for any C), but my.cnf parsing allows\n# quoting only \\, ' or \".  For example, password='a\\b' quotes a 3-character\n# string in my.cnf, but a 2-character string in SQL.\n#\n# This simple escape works correctly in both places.\nbasic_single_escape () {\n    # The quoting on this sed command is a bit complex.  Single-quoted strings\n    # don't allow *any* escape mechanism, so they cannot contain a single\n    # quote.  The string sed gets (as argv[1]) is:  s/\\(['\\]\\)/\\\\\\1/g\n    #\n    # Inside a character class, \\ and ' are not special, so the ['\\] character\n    # class is balanced and contains two characters.\n    echo \"$1\" | sed 's/\\(['\"'\"'\\]\\)/\\\\\\1/g'\n}\n\nmake_config() {\n    echo \"# mysql_secure_installation config file\" >$config\n    echo \"[mysql]\" >>$config\n    echo \"user=root\" >>$config\n    esc_pass=`basic_single_escape \"$rootpass\"`\n    echo \"password='$esc_pass'\" >>$config\n    #sed 's,^,> ,' < $config  # Debugging\n}\n\nget_root_password() {\n    status=1\n    while [ $status -eq 1 ]; do\n\tstty -echo\n\techo $echo_n \"Enter current password for root (enter for none): $echo_c\"\n\tread password\n\techo\n\tstty echo\n\tif [ \"x$password\" = \"x\" ]; then\n\t    hadpass=0\n\telse\n\t    hadpass=1\n\tfi\n\trootpass=$password\n\tmake_config\n\tdo_query \"\"\n\tstatus=$?\n    done\n    echo \"OK, successfully used password, moving on...\"\n    echo\n}\n\nset_root_password() {\n    stty -echo\n    echo $echo_n \"New password: $echo_c\"\n    read password1\n    echo\n    echo $echo_n \"Re-enter new password: $echo_c\"\n    read password2\n    echo\n    stty echo\n\n    if [ \"$password1\" != \"$password2\" ]; then\n\techo \"Sorry, passwords do not match.\"\n\techo\n\treturn 1\n    fi\n\n    if [ \"$password1\" = \"\" ]; then\n\techo \"Sorry, you can't use an empty password here.\"\n\techo\n\treturn 1\n    fi\n\n    esc_pass=`basic_single_escape \"$password1\"`\n\n    # attempt to lift the password expiration flag for root first\n    do_query \"SET PASSWORD=PASSWORD('$esc_pass');\"\n    if [ $? -ne 0 ]; then\n\techo \"root password update failed!\"\n\tclean_and_exit\n    fi\n\n    # now since the password has changed, lets use the new one.\n    rootpass=$password1\n    make_config\n\n    # set password for all root users\n    # do the old password\n    do_query \"SET @@old_passwords=1; UPDATE mysql.user SET Password=PASSWORD('$esc_pass'), password_expired='N' WHERE User='root' and plugin = 'mysql_old_password';\"\n    if [ $? -ne 0 ]; then\n\techo \"old password update failed!\"\n\tclean_and_exit\n    fi\n\n    # do the native password\n    do_query \"SET @@old_passwords=0; UPDATE mysql.user SET Password=PASSWORD('$esc_pass'), password_expired='N' WHERE User='root' and plugin in ('', 'mysql_native_password');\"\n    if [ $? -ne 0 ]; then\n\techo \"native password update failed!\"\n\tclean_and_exit\n    fi\n\n    # do the sha256 password\n    do_query \"SET @@old_passwords=2; UPDATE mysql.user SET authentication_string=PASSWORD('$esc_pass'), password_expired='N' WHERE User='root' and plugin = 'sha256_password';\"\n    if [ $? -ne 0 ]; then\n\techo \"sha256 password update failed!\"\n\tclean_and_exit\n    fi\n\n    echo \"Password updated successfully!\"\n    echo \"Reloading privilege tables..\"\n    reload_privilege_tables\n    if [ $? -eq 1 ]; then\n            clean_and_exit\n    fi\n    echo\n\n    return 0\n}\n\nremove_anonymous_users() {\n    do_query \"DELETE FROM mysql.user WHERE User='';\"\n    if [ $? -eq 0 ]; then\n\techo \" ... Success!\"\n    else\n\techo \" ... Failed!\"\n\tclean_and_exit\n    fi\n\n    return 0\n}\n\nremove_remote_root() {\n    do_query \"DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');\"\n    if [ $? -eq 0 ]; then\n\techo \" ... Success!\"\n    else\n\techo \" ... Failed!\"\n    fi\n}\n\nremove_test_database() {\n    echo \" - Dropping test database...\"\n    do_query \"DROP DATABASE test;\"\n    if [ $? -eq 0 ]; then\n\techo \" ... Success!\"\n    else\n\techo \" ... Failed!  Not critical, keep moving...\"\n    fi\n\n    echo \" - Removing privileges on test database...\"\n    do_query \"DELETE FROM mysql.db WHERE Db='test' OR Db='test\\\\_%'\"\n    if [ $? -eq 0 ]; then\n\techo \" ... Success!\"\n    else\n\techo \" ... Failed!  Not critical, keep moving...\"\n    fi\n\n    return 0\n}\n\nreload_privilege_tables() {\n    do_query \"FLUSH PRIVILEGES;\"\n    if [ $? -eq 0 ]; then\n\techo \" ... Success!\"\n\treturn 0\n    else\n\techo \" ... Failed!\"\n\treturn 1\n    fi\n}\n\ninterrupt() {\n    echo\n    echo \"Aborting!\"\n    echo\n    cleanup\n    stty echo\n    exit 1\n}\n\ncleanup() {\n    echo \"Cleaning up...\"\n    rm -f $config $command\n}\n\n# Remove the files before exiting.\nclean_and_exit() {\n\tcleanup\n\texit 1\n}\n\n# The actual script starts here\n\nprepare\nfind_mysql_client\nset_echo_compat\n\necho\necho\necho\necho\necho \"NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MySQL\"\necho \"      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!\"\necho\necho\n\necho \"In order to log into MySQL to secure it, we'll need the current\"\necho \"password for the root user.  If you've just installed MySQL, and\"\necho \"you haven't set the root password yet, the password will be blank,\"\necho \"so you should just press enter here.\"\necho\n\nget_root_password\n\n\n#\n# Set the root password\n#\n\necho \"Setting the root password ensures that nobody can log into the MySQL\"\necho \"root user without the proper authorisation.\"\necho\n\nif [ $hadpass -eq 0 ]; then\n    echo $echo_n \"Set root password? [Y/n] $echo_c\"\nelse\n    echo \"You already have a root password set, so you can safely answer 'n'.\"\n    echo\n    echo $echo_n \"Change the root password? [Y/n] $echo_c\"\nfi\n\nread reply\nif [ \"$reply\" = \"n\" ]; then\n    echo \" ... skipping.\"\nelse\n    status=1\n    while [ $status -eq 1 ]; do\n\tset_root_password\n\tstatus=$?\n    done\nfi\necho\n\n\n#\n# Remove anonymous users\n#\n\necho \"By default, a MySQL installation has an anonymous user, allowing anyone\"\necho \"to log into MySQL without having to have a user account created for\"\necho \"them.  This is intended only for testing, and to make the installation\"\necho \"go a bit smoother.  You should remove them before moving into a\"\necho \"production environment.\"\necho\n\necho $echo_n \"Remove anonymous users? [Y/n] $echo_c\"\n\nread reply\nif [ \"$reply\" = \"n\" ]; then\n    echo \" ... skipping.\"\nelse\n    remove_anonymous_users\nfi\necho\n\n\n#\n# Disallow remote root login\n#\n\necho \"Normally, root should only be allowed to connect from 'localhost'.  This\"\necho \"ensures that someone cannot guess at the root password from the network.\"\necho\n\necho $echo_n \"Disallow root login remotely? [Y/n] $echo_c\"\nread reply\nif [ \"$reply\" = \"n\" ]; then\n    echo \" ... skipping.\"\nelse\n    remove_remote_root\nfi\necho\n\n\n#\n# Remove test database\n#\n\necho \"By default, MySQL comes with a database named 'test' that anyone can\"\necho \"access.  This is also intended only for testing, and should be removed\"\necho \"before moving into a production environment.\"\necho\n\necho $echo_n \"Remove test database and access to it? [Y/n] $echo_c\"\nread reply\nif [ \"$reply\" = \"n\" ]; then\n    echo \" ... skipping.\"\nelse\n    remove_test_database\nfi\necho\n\n\n#\n# Reload privilege tables\n#\n\necho \"Reloading the privilege tables will ensure that all changes made so far\"\necho \"will take effect immediately.\"\necho\n\necho $echo_n \"Reload privilege tables now? [Y/n] $echo_c\"\nread reply\nif [ \"$reply\" = \"n\" ]; then\n    echo \" ... skipping.\"\nelse\n    reload_privilege_tables\nfi\necho\n\ncleanup\n\necho\necho\necho\necho \"All done!  If you've completed all of the above steps, your MySQL\"\necho \"installation should now be secure.\"\necho\necho \"Thanks for using MySQL!\"\necho\necho\n\n\n", "num_lines": 397}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n## Emacs, this is -*- perl -*- mode? :-)\n\n# Copyright (c) 2000, 2014 Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n##\n##        Permission setter for MySQL\n##\n##        mady by Luuk de Boer (luuk@wxs.nl) 1998.\n##        it's made under GPL ...:-))\n##\n##\n############################################################################\n## History\n##\n## 1.0 first start of the program\n## 1.1 some changes from monty and after that\n##     initial release in mysql 3.22.10 (nov 1998)\n## 1.2 begin screen now in a loop + quit is using 0 instead of 9\n##     after ideas of Paul DuBois.\n## 1.2a Add Grant, References, Index and Alter privilege handling (Monty)\n## 1.3 Applied patch provided by Martin Mokrejs <mmokrejs@natur.cuni.cz>\n##     (General code cleanup, use the GRANT statement instead of updating\n##     the privilege tables directly, added option to revoke privileges)\n## 1.4 Remove option 6 which attempted to erroneously grant global privileges\n\n#### TODO\n#\n# empty ... suggestions ... mail them to me ...\n\n\n$version=\"1.4\";\n\nuse DBI;\nuse Getopt::Long;\nuse strict;\nuse vars qw($dbh $sth $hostname $opt_user $opt_password $opt_help $opt_host\n\t    $opt_socket $opt_port $host $version);\n\nmy $sqlhost = \"\";\nmy $user = \"\";\n\n$dbh=$host=$opt_user= $opt_password= $opt_help= $opt_host= $opt_socket= \"\";\n$opt_port=0;\n\nprint STDERR \"Warning: $0 is deprecated and will be removed in a future version.\\n\";\n\nread_my_cnf();\t\t# Read options from ~/.my.cnf\n\nGetOptions(\"user=s\",\"password=s\",\"help\",\"host=s\",\"socket=s\",\"port=i\");\n\nusage() if ($opt_help); # the help function\n\nif ($opt_host eq '')\n{\n  $sqlhost = \"localhost\";\n}\nelse\n{\n  $sqlhost = $opt_host;\n}\n\n# ask for a password if no password is set already\nif ($opt_password eq '')\n{\n  system \"stty -echo\";\n  print \"Password for user $opt_user to connect to MySQL: \";\n  $opt_password = <STDIN>;\n  chomp($opt_password);\n  system \"stty echo\";\n  print \"\\n\";\n}\n\n\n# make the connection to MySQL\n$dbh= DBI->connect(\"DBI:mysql:mysql:host=$sqlhost:port=$opt_port:mysql_socket=$opt_socket\",$opt_user,$opt_password, {PrintError => 0}) ||\n  die(\"Can't make a connection to the mysql server.\\n The error: $DBI::errstr\");\n\n# the start of the program\n&q1();\nexit(0); # the end...\n\n#####\n# below all subroutines of the program\n#####\n\n###\n# the beginning of the program\n###\nsub q1 { # first question ...\n  my ($answer,$end);\n  while (! $end) {\n    print \"#\"x70;\n    print \"\\n\";\n    print \"## Welcome to the permission setter $version for MySQL.\\n\";\n    print \"## made by Luuk de Boer\\n\";\n    print \"#\"x70;\n    print \"\\n\";\n    print \"What would you like to do:\\n\";\n    print \"  1. Set password for an existing user.\\n\";\n    print \"  2. Create a database + user privilege for that database\\n\";\n\t\tprint \"     and host combination (user can only do SELECT)\\n\";\n    print \"  3. Create/append user privilege for an existing database\\n\";\n\t\tprint \"     and host combination (user can only do SELECT)\\n\";\n    print \"  4. Create/append broader user privileges for an existing\\n\";\n\t\tprint \"     database and host combination\\n\";\n\t\tprint \"     (user can do SELECT,INSERT,UPDATE,DELETE)\\n\";\n    print \"  5. Create/append quite extended user privileges for an\\n\";\n\t\tprint \"     existing database and host combination (user can do\\n\";\n\t\tprint \"     SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,\\n\";\n\t\tprint \"     LOCK TABLES,CREATE TEMPORARY TABLES)\\n\";\n    print \"  6. Create/append full privileges for an existing database\\n\";\n\t\tprint \"     and host combination (user has FULL privilege)\\n\";\n    print \"  7. Remove all privileges for for an existing database and\\n\";\n\t\tprint \"     host combination.\\n\";\n    print \"     (user will have all permission fields set to N)\\n\";\n    print \"  0. exit this program\\n\";\n    print \"\\nMake your choice [1,2,3,4,5,6,7,0]: \";\n    while (<STDIN>) {\n      $answer = $_;\n      chomp($answer);\n      if ($answer =~ /^[1234567]$/) {\n        if ($answer == 1) {\n\t   setpwd();\n        } elsif ($answer =~ /^[234567]$/) {\n\t   addall($answer);\n\t} else {\n          print \"Sorry, something went wrong. With such option number you should not get here.\\n\\n\";\n          $end = 1;\n        }\n      } elsif ($answer == 0) {\n        print \"We hope we can help you next time \\n\\n\";\n\t$end = 1;\n      } else {\n        print \"Your answer was $answer\\n\";\n        print \"and that's wrong .... Try again\\n\";\n      }\n      last;\n    }\n  }\n}\n\n###\n# set a password for a user\n###\nsub setpwd\n{\n  my ($user,$pass,$host) = \"\";\n  print \"\\n\\nSetting a (new) password for a user.\\n\";\n\n  $user = user();\n  $pass = newpass($user);\n  $host = hosts($user);\n\n  print \"#\"x70;\n  print \"\\n\\n\";\n  print \"That was it ... here is an overview of what you gave to me:\\n\";\n  print \"The username \t\t: $user\\n\";\n#  print \"The password\t\t: $pass\\n\";\n  print \"The host\t\t: $host\\n\";\n  print \"#\"x70;\n  print \"\\n\\n\";\n  print \"Are you pretty sure you would like to implement this [yes/no]: \";\n  my $no = <STDIN>;\n  chomp($no);\n  if ($no =~ /n/i)\n  {\n    print \"Okay .. that was it then ... See ya\\n\\n\";\n    return(0);\n  }\n  else\n  {\n    print \"Okay ... let's go then ...\\n\\n\";\n  }\n  $user = $dbh->quote($user);\n  $host = $dbh->quote($host);\n  if ($pass eq '')\n  {\n    $pass = \"''\";\n  }\n  else\n  {\n    $pass = \"PASSWORD(\". $dbh->quote($pass) . \")\";\n  }\n  my $sth = $dbh->prepare(\"update user set Password=$pass where User = $user and Host = $host\") || die $dbh->errstr;\n  $sth->execute || die $dbh->errstr;\n  $sth->finish;\n  print \"The password is set for user $user.\\n\\n\";\n\n}\n\n###\n# all things which will be added are done here\n###\nsub addall {\n  my ($todo) = @_;\n  my ($answer,$good,$db,$user,$pass,$host,$priv);\n\n  if ($todo == 2) {\n    $db = newdatabase();\n  } else {\n    $db = database();\n  }\n\n  $user = newuser();\n  $pass = newpass(\"$user\");\n  $host = newhosts();\n\n  print \"#\"x70;\n  print \"\\n\\n\";\n  print \"That was it ... here is an overview of what you gave to me:\\n\";\n  print \"The database name\t: $db\\n\";\n  print \"The username \t\t: $user\\n\";\n#  print \"The password\t\t: $pass\\n\";\n  print \"The host(s)\t\t: $host\\n\";\n  print \"#\"x70;\n  print \"\\n\\n\";\n  print \"Are you pretty sure you would like to implement this [yes/no]: \";\n  my $no = <STDIN>;\n  chomp($no);\n  if ($no =~ /n/i) {\n    print \"Okay .. that was it then ... See ya\\n\\n\";\n    return(0);\n  } else {\n    print \"Okay ... let's go then ...\\n\\n\";\n  }\n\n  if ($todo == 2) {\n    # create the database\n    if ($db) {\n    my $sth = $dbh->do(\"CREATE DATABASE $db\") || $dbh->errstr;\n    } else {\n      print STDERR \"What do you want? You wanted to create new database and add new user, right?\\n\";\n      die \"But then specify databasename, please\\n\";\n  }\n  }\n\n  if ( ( !$todo ) or not ( $todo =~ m/^[2-7]$/ ) ) {\n    print STDERR \"Sorry, select option $todo isn't known inside the program .. See ya\\n\";\n    quit();\n  }\n\n  my @hosts = split(/,/,$host);\n  if (!$user) {\n     die \"username not specified: $user\\n\";\n  }\n  if (!$db) {\n     die \"databasename is not specified nor *\\n\";\n  }\n  foreach $host (@hosts) {\n    # user privileges: SELECT\n    if (($todo == 2) || ($todo == 3)) {\n      $sth = $dbh->do(\"GRANT SELECT ON $db.* TO \\'$user\\'@\\'$host\\' IDENTIFIED BY \\'$pass\\'\") || die $dbh->errstr;\n    } elsif ($todo == 4) {\n      # user privileges: SELECT,INSERT,UPDATE,DELETE\n      $sth = $dbh->do(\"GRANT SELECT,INSERT,UPDATE,DELETE ON $db.* TO \\'$user\\'@\\'$host\\' IDENTIFIED BY \\'$pass\\'\") || die $dbh->errstr;\n    } elsif ($todo == 5) {\n      # user privileges: SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,LOCK TABLES,CREATE TEMPORARY TABLES\n      $sth = $dbh->do(\"GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP,INDEX,LOCK TABLES,CREATE TEMPORARY TABLES ON $db.* TO \\'$user\\'@\\'$host\\' IDENTIFIED BY \\'$pass\\'\") || die $dbh->errstr;\n    } elsif ($todo == 6) {\n       # all privileges\n       $sth = $dbh->do(\"GRANT ALL ON $db.* TO \\'$user\\'\\@\\'$host\\' IDENTIFIED BY \\'$pass\\'\") || die $dbh->errstr;\n    } elsif ($todo == 7) {\n       # all privileges set to N\n       $sth = $dbh->do(\"REVOKE ALL ON $db.* FROM \\'$user\\'\\@\\'$host\\'\") || die $dbh->errstr;\n    }\n    }\n  $dbh->do(\"FLUSH PRIVILEGES\") || print STDERR \"Can't flush privileges\\n\";\n  print \"Everything is inserted and mysql privileges have been reloaded.\\n\\n\";\n}\n\n###\n# ask for a new database name\n###\nsub newdatabase {\n  my ($answer,$good,$db);\n  print \"\\n\\nWhich database would you like to add: \";\n  while (<STDIN>) {\n    $answer = $_;\n    $good = 0;\n    chomp($answer);\n    if ($answer) {\n      my $sth = $dbh->prepare(\"SHOW DATABASES\") || die $dbh->errstr;\n      $sth->execute || die $dbh->errstr;\n      while (my @r = $sth->fetchrow_array) {\n        if ($r[0] eq $answer) {\n          print \"\\n\\nSorry, this database name is already in use; try something else: \";\n          $good = 1;\n        }\n      }\n    } else {\n      print \"You must type something ...\\nTry again: \";\n      next;\n    }\n    last if ($good == 0);\n  }\n  $db = $answer;\n  print \"The new database $db will be created\\n\";\n  return($db);\n}\n\n###\n# select a database\n###\nsub database {\n  my ($answer,$good,$db);\n  print \"\\n\\nWhich database from existing databases would you like to select: \\n\";\n  print \"You can choose from: \\n\";\n  my $sth = $dbh->prepare(\"show databases\") || die $dbh->errstr;\n  $sth->execute || die $dbh->errstr;\n  while (my @r = $sth->fetchrow_array) {\n    print \"  - $r[0] \\n\";\n  }\n  print \"Which database will it be (case sensitive). Type * for any: \\n\";\n  while (<STDIN>) {\n    $answer = $_;\n    $good = 0;\n    chomp($answer);\n    if ($answer) {\n      if ($answer eq \"*\") {\n        print \"OK, the user entry will NOT be limited to any database\";\n        return(\"*\");\n      }\n      my $sth = $dbh->prepare(\"show databases\") || die $dbh->errstr;\n      $sth->execute || die $dbh->errstr;\n      while (my @r = $sth->fetchrow_array) {\n        if ($r[0] eq $answer) {\n          $good = 1;\n          $db = $r[0];\n          last;\n        }\n      }\n    } else {\n        print \"Type either database name or * meaning any databasename. That means\";\n        print \" any of those above but also any which will be created in future!\";\n        print \" This option gives a user chance to operate on databse mysql, which\";\n        print \" contains privilege settings. That is really risky!\\n\";\n      next;\n    }\n    if ($good == 1) {\n      last;\n    } else {\n      print \"You must select one from the list.\\nTry again: \";\n      next;\n    }\n  }\n  print \"The database $db will be used.\\n\";\n  return($db);\n}\n\n###\n# ask for a new username\n###\nsub newuser\n{\n  my $user = \"\";\n  my $answer = \"\";\n\n  print \"\\nWhat username is to be created: \";\n  while(<STDIN>)\n  {\n    $answer = $_;\n    chomp($answer);\n    if ($answer)\n    {\n      $user = $answer;\n    }\n    else\n    {\n      print \"You must type something ...\\nTry again: \";\n      next;\n    }\n    last;\n  }\n  print \"Username = $user\\n\";\n  return($user);\n}\n\n###\n# ask for a user which is already in the user table\n###\nsub user\n{\n  my ($answer,$user);\n\n  print \"\\nFor which user do you want to specify a password: \";\n  while(<STDIN>)\n  {\n    $answer = $_;\n    chomp($answer);\n    if ($answer)\n    {\n      my $sth = $dbh->prepare(\"select User from user where User = '$answer'\") || die $dbh->errstr;\n      $sth->execute || die $dbh->errstr;\n      my @r = $sth->fetchrow_array;\n      if ($r[0])\n      {\n        $user = $r[0];\n      }\n      else\n      {\n       print \"Sorry, user $answer isn't known in the user table.\\nTry again: \";\n       next;\n     }\n    }\n    else\n    {\n      print \"You must type something ...\\nTry again: \";\n      next;\n    }\n    last;\n  }\n  print \"Username = $user\\n\";\n  return($user);\n}\n\n###\n# ask for a new password\n###\nsub newpass\n{\n  my ($user) = @_;\n  my ($pass,$answer,$good,$yes);\n\n  print \"Would you like to set a password for $user [y/n]: \";\n  $yes = <STDIN>;\n  chomp($yes);\n  if ($yes =~ /y/)\n  {\n    system \"stty -echo\";\n    print \"What password do you want to specify for $user: \";\n    while(<STDIN>)\n    {\n      $answer = $_;\n      chomp($answer);\n      system \"stty echo\";\n      print \"\\n\";\n      if ($answer)\n      {\n        system \"stty -echo\";\n        print \"Type the password again: \";\n        my $second = <STDIN>;\n        chomp($second);\n        system \"stty echo\";\n        print \"\\n\";\n        if ($answer ne $second)\n        {\n          print \"Passwords aren't the same; we begin from scratch again.\\n\";\n          system \"stty -echo\";\n          print \"Password please: \";\n          next;\n        }\n        else\n        {\n          $pass = $answer;\n        }\n      }\n      else\n      {\n        print \"You must type something ...\\nTry again: \";\n        next;\n      }\n      last;\n    }\n#    print \"The password for $user is $pass.\\n\";\n  }\n  else\n  {\n    print \"We won't set a password so the user doesn't have to use it\\n\";\n    $pass = \"\";\n  }\n  return($pass);\n}\n\n###\n# ask for new hosts\n###\nsub newhosts\n{\n  my ($host,$answer,$good);\n\n  print \"We now need to know from what host(s) the user will connect.\\n\";\n  print \"Keep in mind that % means 'from any host' ...\\n\";\n  print \"The host please: \";\n  while(<STDIN>)\n  {\n    $answer = $_;\n    chomp($answer);\n    if ($answer)\n    {\n      $host .= \",$answer\";\n      print \"Would you like to add another host [yes/no]: \";\n      my $yes = <STDIN>;\n      chomp($yes);\n      if ($yes =~ /y/i)\n      {\n        print \"Okay, give us the host please: \";\n        next;\n      }\n      else\n      {\n        print \"Okay we keep it with this ...\\n\";\n      }\n    }\n    else\n    {\n      print \"You must type something ...\\nTry again: \";\n      next;\n    }\n    last;\n  }\n  $host =~ s/^,//;\n  print \"The following host(s) will be used: $host.\\n\";\n  return($host);\n}\n\n###\n# ask for a host which is already in the user table\n###\nsub hosts\n{\n  my ($user) = @_;\n  my ($answer,$good,$host);\n\n  print \"We now need to know which host for $user we have to change.\\n\";\n  print \"Choose from the following hosts: \\n\";\n  $user = $dbh->quote($user);\n  my $sth = $dbh->prepare(\"select Host,User from user where User = $user\") || die $dbh->errstr;\n  $sth->execute || die $dbh->errstr;\n  while (my @r = $sth->fetchrow_array)\n  {\n    print \"  - $r[0] \\n\";\n  }\n  print \"The host please (case sensitive): \";\n  while(<STDIN>)\n  {\n    $answer = $_;\n    chomp($answer);\n    if ($answer)\n    {\n      $sth = $dbh->prepare(\"select Host,User from user where Host = '$answer' and User = $user\") || die $dbh->errstr;\n      $sth->execute || die $dbh->errstr;\n      my @r = $sth->fetchrow_array;\n      if ($r[0])\n      {\n        $host = $answer;\n        last;\n      }\n      else\n      {\n        print \"You have to select a host from the list ...\\nTry again: \";\n        next;\n      }\n    }\n    else\n    {\n      print \"You have to type something ...\\nTry again: \";\n      next;\n    }\n    last;\n  }\n  print \"The following host will be used: $host.\\n\";\n  return($host);\n}\n\n###\n# a nice quit (first disconnect and then exit\n###\nsub quit\n{\n  $dbh->disconnect;\n  exit(0);\n}\n\n###\n# Read variables password, port and socket from .my.cnf under the client\n# or perl groups\n###\n\nsub read_my_cnf\n{\n  open(TMP,$ENV{'HOME'} . \"/.my.cnf\") || return 1;\n  while (<TMP>)\n  {\n    if (/^\\[(client|perl)\\]/i)\n    {\n      while ((defined($_=<TMP>)) && !/^\\[\\w+\\]/)\n      {\n\tprint $_;\n\tif (/^host\\s*=\\s*(\\S+)/i)\n\t{\n\t  $opt_host = $1;\n\t}\n\telsif (/^user\\s*=\\s*(\\S+)/i)\n\t{\n\t  $opt_user = $1;\n\t}\n\telsif (/^password\\s*=\\s*(\\S+)/i)\n\t{\n\t  $opt_password = $1;\n\t}\n\telsif (/^port\\s*=\\s*(\\S+)/i)\n\t{\n\t  $opt_port = $1;\n\t}\n\telsif (/^socket\\s*=\\s*(\\S+)/i)\n\t{\n\t  $opt_socket = $1;\n\t}\n      }\n    }\n  }\n  close(TMP);\n}\n\n###\n# the help text\n###\nsub usage\n{\n  print <<EOL;\n----------------------------------------------------------------------\n                 The permission setter for MySQL.\n                      version: $version\n\n                 made by: Luuk de Boer <luuk\\@wxs.nl>\n----------------------------------------------------------------------\n\nThe permission setter is a little program which can help you add users\nor databases or change passwords in MySQL. Keep in mind that we don't\ncheck permissions which already been set in MySQL. So if you can't\nconnect to MySQL using the permission you just added, take a look at\nthe permissions which have already been set in MySQL.\n\nThe permission setter first reads your .my.cnf file in your Home\ndirectory if it exists.\n\nOptions for the permission setter:\n\n--help\t\t: print this help message and exit.\n\nThe options shown below are used for making the connection to the MySQL\nserver. Keep in mind that the permissions for the user specified via\nthese options must be sufficient to add users / create databases / set\npasswords.\n\n--user\t\t: is the username to connect with.\n--password\t: the password of the username.\n--host\t\t: the host to connect to.\n--socket\t: the socket to connect to.\n--port\t\t: the port number of the host to connect to.\n\nIf you don't give a password and no password is set in your .my.cnf\nfile, then the permission setter will ask for a password.\n\n\nEOL\nexit(0);\n}\n", "num_lines": 676}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2014 Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# This is a utility for MySQL. It is not needed by any standard part\n# of MySQL.\n\n# Usage: mysql_zap [-signal] [-f] [-t] pattern\n\nprint STDERR \"Warning: $0 is deprecated and will be removed in a future version.\\n\";\n\n# Configuration parameters.\n\n$sig = \"\";\t\t\t# Default to try all signals\n$ans = \"y\";\n$opt_f= 0;\n$opt_t= 0;\n$opt_a = \"\";\n\n$BSD = -f '/vmunix' || $ENV{\"OS\"} eq \"SunOS4\";\n$LINUX = $^O eq 'linux' || $^O eq 'darwin';\n$pscmd = $BSD ? \"/bin/ps -auxww\" : $LINUX ? \"/bin/ps axuw\" : \"/bin/ps -ef\";\n\nopen(TTYIN, \"</dev/tty\") || die \"can't read /dev/tty: $!\";\nopen(TTYOUT, \">/dev/tty\") || die \"can't write /dev/tty: $!\";\nselect(TTYOUT);\n$| = 1;\nselect(STDOUT);\n$SIG{'INT'} = 'cleanup';\n\nwhile ($#ARGV >= $[ && $ARGV[0] =~ /^-/) {\n    if ($ARGV[0] =~ /(ZERO|HUP|INT|QUIT|ILL|TRAP|ABRT|EMT|FPE|KILL|BUS|SEGV|SYS|PIPE|ALRM|TERM|URG|STOP|TSTP|CONT|CLD|TTIN|TTOU|IO|XCPU|XFSZ|VTALRM|PROF|WINCH|LOST|USR1|USR2)/ || $ARGV[0] =~ /-(\\d+)$/) {\n\t$sig = $1;\n    } elsif ($ARGV[0] eq \"-f\") {\n\t$opt_f=1;\n    } elsif ($ARGV[0] eq \"-t\") {\n\t$opt_t=1;\n\t$ans = \"n\";\n    }\n    elsif ($ARGV[0] eq \"-a\")\n    {\n\t$opt_a = 1;\n    }\n    elsif ($ARGV[0] eq \"-?\" || $ARGV[0] eq \"-I\" || $ARGV[0] eq \"--help\")\n    {\n\t&usage;\n    }\n    else {\n\tprint STDERR \"$0: illegal argument $ARGV[0] ignored\\n\";\n    }\n    shift;\n}\n\n&usage if $#ARGV < 0;\n\nif (!$opt_f)\n{\n    if ($BSD) {\n\tsystem \"stty cbreak </dev/tty >/dev/tty 2>&1\";\n    }\n    else {\n\tsystem \"stty\", 'cbreak',\n\tsystem \"stty\", 'eol', '^A';\n    }\n}\n\nopen(PS, \"$pscmd|\") || die \"can't run $pscmd: $!\";\n$title = <PS>;\nprint TTYOUT $title;\n\n# Catch any errors with eval.  A bad pattern, for instance.\neval <<'EOF';\nprocess: while ($cand = <PS>)\n{\n    chop($cand);\n    ($user, $pid) = split(' ', $cand);\n    next if $pid == $$;\n    $found = !@ARGV;\n    if ($opt_a) { $found = 1; }\n    foreach $pat (@ARGV)\n    {\n\tif ($opt_a)\n\t{\n\t    if (! ($cand =~ $pat))\n\t    {\n\t\tnext process;\n\t    }\n\t}\n\telse\n\t{\n\t    $found = 1 if $cand =~ $pat;\n\t}\n    }\n    next if (!$found);\n    if (! $opt_f && ! $opt_t)\n    {\n\tprint TTYOUT \"$cand? \";\n\tread(TTYIN, $ans, 1);\n\tprint TTYOUT \"\\n\" if ($ans ne \"\\n\");\n    }\n    else\n    {\n\tprint TTYOUT \"$cand\\n\";\n    }\n    if ($ans =~ /^y/i) { &killpid($sig, $pid); }\n    if ($ans =~ /^q/i) { last; }\n}\nEOF\n\n&cleanup;\n\n\nsub usage {\n    print <<EOF;\nUsage:   $0 [-signal] [-?Ift] [--help] pattern\nOptions: -I or -? \"info\"  -f \"force\" -t \"test\".\n\nVersion 1.0\nKill processes that match the pattern.\nIf -f isn't given, ask user for confirmation for each process to kill.\nIf signal isn't given, try first with signal 15, then with signal 9.\nIf -t is given, the processes are only shown on stdout.\nEOF\n    exit(1);\n}\n\nsub cleanup {\n    if ($BSD) {\n\tsystem \"stty -cbreak </dev/tty >/dev/tty 2>&1\";\n    }\n    else {\n\tsystem \"stty\", 'icanon';\n\tsystem \"stty\", 'eol', '^@';\n    }\n    print \"\\n\";\n    exit;\n}\n\nsub killpid {\n    local($signal,$pid) = @_;\n    if ($signal)\n    {\n\tkill $signal,$pid;\n    }\n    else\n    {\n\tprint \"kill -15\\n\";\n\tkill 15, $pid;\n\tfor (1..5) {\n\t    sleep 2;\n\t    return if kill(0, $pid) == 0;\n\t}\n\tprint \"kill -9\\n\";\n\tkill 9, $pid;\n\tfor (1..5) {\n\t    sleep 2;\n\t    return if kill(0, $pid) == 0;\n\t}\n\tprint \"$pid will not die!\\n\";\n    }\n}\n", "num_lines": 175}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# AS3AP single-user benchmark.\n#\n\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$opt_loop_count=1;\n\n#Create tables \n\n$dbh = $server->connect();\n\n#Create Table\n$sth = $dbh->do(\"drop table uniques\");\n$sth = $dbh->do(\"drop table updates\");\n$sth = $dbh->do(\"drop table hundred\");\n$sth = $dbh->do(\"drop table tenpct\");\n$sth = $dbh->do(\"drop table tiny\");\n\n#Temporary table\n$sth = $dbh->do(\"drop table saveupdates\");\n\n@fields=(\"col_key     int             not null\",\n\t \"col_int     int             not null\",\n\t \"col_signed  int             not null\",\n\t \"col_float   float           not null\",\n\t \"col_double  float           not null\",\n\t \"col_decim   numeric(18,2)   not null\",\n\t \"col_date    char(20)        not null\",\n\t \"col_code    char(10)        not null\",\n\t \"col_name    char(20)        not null\",\n\t \"col_address varchar(80)     not null\");\n\ndo_many($dbh,$server->create(\"uniques\",\\@fields,[]));\ndo_many($dbh,$server->create(\"updates\",\\@fields,[]));\ndo_many($dbh,$server->create(\"hundred\",\\@fields,[]));\ndo_many($dbh,$server->create(\"tenpct\",\\@fields,[]));\ndo_many($dbh,$server->create(\"tiny\",[\"col_key int not null\"],[]));\n\nprint \"Start AS3AP benchmark\\n\\n\";\n\n$start_time=new Benchmark;\n\nprint \"Load DATA\\n\";\n#Load DATA\n\n@table_names=(\"uniques\",\"updates\",\"hundred\",\"tenpct\",\"tiny\");\n\n$loop_time=new Benchmark;\n\nif ($opt_fast && $server->{'limits'}->{'load_data_infile'})\n{\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    my $file = \"$pwd/Data/AS3AP/${table_name}\\.new\";\n    print \"$table_name - $file\\n\" if ($opt_debug);\n    $row_count += $server->insert_file($table_name,$file,$dbh);\n  }\n}\nelse\n{\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    print \"$table_name - $file\\n\" if ($opt_debug);\n    my $insert_start = \"insert into $table_name values (\";\n    open(DATA, \"$pwd/Data/AS3AP/${table_name}\\.new\") || die \"Can't open text file: $pwd/Data/AS3AP/${table_name}\\.new\\n\";\n    while(<DATA>)\n    {\n      chomp;\n      next unless ( $_ =~ /\\w/ );     # skip blank lines\n      $command = $insert_start.\"$_\".\")\";\n      $command =~ $server->fix_to_insert($command);\n      print \"$command\\n\" if ($opt_debug);\n      $sth = $dbh->do($command) or die \"Got error: $DBI::errstr when executing '$command'\\n\";\n\t  $row_count++;\n    }\n    close(DATA);\n  }\n}\n\n$end_time=new Benchmark;\nprint \"Time for Load Data - \" . \"($row_count): \" .\ntimestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n\nprint \"Create Index\\n\";\n\ntest_command(\"create_idx_uniques_key_bt\",\n\t     \"time for create_idx_uniques_key_bt\",\n\t     \"create unique index uniques_key_bt on uniques (col_key)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_key_bt\",\n\t     \"time for create_idx_updates_key_bt\",\n\t     \"create unique index updates_key_bt on updates (col_key)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_hundred_key_bt\",\n\t     \"time for create_idx_hundred_key_bt\",\n\t     \"create unique index hundred_key_bt on hundred (col_key)\",\n\t     $dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_key_bt\",\n\t     \"time for create_idx_tenpct_key_bt\",\n\t     \"create unique index tenpct_key_bt on tenpct (col_key)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_key_code_bt\",\n\t     \"time for create_idx_tenpct_key_code_bt\",\n\t     \"create index tenpct_key_code_bt on tenpct (col_key,col_code)\",\n\t     $dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tiny_key_bt\",\n\t     \"time for create_idx_tiny_key_bt\",\n\t     \"create index tiny_key_bt on tiny (col_key)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_int_bt\",\n\t     \"time for create_idx_tenpct_int_bt\",\n\t     \"create index tenpct_int_bt on tenpct (col_int)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_signed_bt\",\n\t     \"time for create_idx_tenpct_signed_bt\",\n\t     \"create index tenpct_signed_bt on tenpct (col_signed)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_uniques_code_h\",\n\t     \"time for create_idx_uniques_code_h\",\n\t     \"create index uniques_code_h on uniques (col_code)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_double_bt\",\n\t     \"time for create_idx_tenpct_double_bt\",\n\t     \"create index tenpct_double_bt on tenpct (col_double)\",$dbh,$opt_loop_count);\n\n\ntest_command(\"create_idx_updates_decim_bt\",\n\t     \"time for create_idx_updates_decim_bt\",\n\t     \"create index updates_decim_bt on updates (col_decim)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_float_bt\",\n\t     \"time for create_idx_tenpct_float_bt\",\n\t     \"create index tenpct_float_bt on tenpct (col_float)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_int_bt\",\n\t     \"time for create_idx_updates_int_bt\",\n\t     \"create index updates_int_bt on updates (col_int)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_decim_bt\",\n\t     \"time for create_idx_tenpct_decim_bt\",\n\t     \"create index tenpct_decim_bt on tenpct (col_decim)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_hundred_code_h\",\n\t     \"time for create_idx_hundred_code_h\",\n\t     \"create index hundred_code_h on hundred (col_code)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_name_h\",\n\t     \"time for create_idx_tenpct_name_h\",\n\t     \"create index tenpct_name_h on tenpct (col_name)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_code_h\",\n\t     \"time for create_idx_updates_code_h\",\n\t     \"create index updates_code_h on updates (col_code)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_tenpct_code_h\",\n\t     \"time for create_idx_tenpct_code_h\",\n\t     \"create index tenpct_code_h on tenpct (col_code)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_double_bt\",\n\t     \"time for create_idx_updates_double_bt\",\n\t     \"create index updates_double_bt on updates (col_double)\",$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_hundred_foreign\",\n\t     \"time for create_idx_hundred_foreign\",\n\t     \"alter table hundred add constraint fk_hundred_updates foreign key (col_signed) \n\t\t\t\t      references updates (col_key)\",$dbh,$opt_loop_count);\n\ntest_query(\"sel_1_cl\",\n\t   \"Time to sel_1_cl\",\n\t   \"select col_key, col_int, col_signed, col_code, col_double, col_name \n \t    from updates where col_key = 1000\",$dbh,$opt_loop_count);\n\ntest_query(\"join_3_cl\",\n\t   \"Time to join_3_cl\",\n\t   \"select uniques.col_signed, uniques.col_date, \n\t\t   hundred.col_signed, hundred.col_date, \n\t\t   tenpct.col_signed, tenpct.col_date \n\t    from uniques, hundred, tenpct \n\t    where uniques.col_key = hundred.col_key \n\t\t  and uniques.col_key = tenpct.col_key \n\t\t  and uniques.col_key = 1000\",$dbh,$opt_loop_count);\n\ntest_query(\"sel_100_ncl\",\n\t   \"Time to sel_100_ncl\",\n\t   \"select col_key, col_int, col_signed, col_code,col_double, col_name\n\t    from updates where col_int <= 100\",$dbh,$opt_loop_count);\n\ntest_query(\"table_scan\",\n\t   \"Time to table_scan\",\n\t   \"select * from uniques where col_int = 1\",$dbh,$opt_loop_count);\n\ntest_query(\"agg_func\",\n\t   \"Time for agg_func\",\n\t   \"select min(col_key) from hundred group by col_name\",$dbh,$opt_loop_count);\n\ntest_query(\"agg_scal\",\n\t   \"Time for agg_scal\",\n\t   \"select min(col_key) from uniques\",$dbh,$opt_loop_count);\n\ntest_query(\"sel_100_cl\",\n\t  \"Time for sel_100_cl\",\n\t  \"select col_key, col_int, col_signed, col_code, \n\t\t  col_double, col_name \n\t   from updates where col_key <= 100\",$dbh,$opt_loop_count);\n\ntest_query(\"join_3_ncl\",\n\t   \"Time for join_3_ncl\",\n\t   \"select uniques.col_signed, uniques.col_date, \n\t\t   hundred.col_signed, hundred.col_date, \n\t\t   tenpct.col_signed, tenpct.col_date \n\t    from uniques, hundred, tenpct \n\t    where uniques.col_code = hundred.col_code \n\t\t  and uniques.col_code = tenpct.col_code \n\t\t  and uniques.col_code = 'BENCHMARKS'\",$dbh,$opt_loop_count);\n\ntest_query(\"sel_10pct_ncl\",\n\t   \"Time for sel_10pct_ncl\",\n\t   \"select col_key, col_int, col_signed, col_code, \n\t\t   col_double, col_name \n\t    from tenpct \n\t    where col_name = 'THE+ASAP+BENCHMARKS+'\",$dbh,$opt_loop_count);\n\nif ($limits->{'subqueries'}){\n  test_query(\"agg_simple_report\",\n\t     \"Time for agg_simple_report\",\n\t     \"select avg(updates.col_decim) \n\t      from updates \n\t      where updates.col_key in \n\t\t\t(select updates.col_key \n\t\t\t from updates, hundred \n\t\t\t where hundred.col_key = updates.col_key \n\t\t\t       and updates.col_decim > 980000000)\",$dbh,$opt_loop_count);\n}else{\n print \"agg_simple_report - Failed\\n\\n\";\n}\n\ntest_query(\"agg_info_retrieval\",\n\t   \"Time for agg_info_retrieval\",\n\t   \"select count(col_key) \n\t    from tenpct \n\t    where col_name = 'THE+ASAP+BENCHMARKS' \n\t\t  and col_int <= 100000000 \n\t\t  and col_signed between 1 and 99999999 \n\t\t  and not (col_float between -450000000 and 450000000) \n\t\t  and col_double > 600000000 \n\t\t  and col_decim < -600000000\",$dbh,$opt_loop_count);\n\nif ($limits->{'views'}){\n  test_query(\"agg_create_view\",\n\t     \"Time for agg_create_view\",\n\t     \"create view \n\t\treportview(col_key,col_signed,col_date,col_decim, \n\t\t\t\tcol_name,col_code,col_int) as \n\t\t\t   select updates.col_key, updates.col_signed, \n\t\t\t   updates.col_date, updates.col_decim, \n\t\t\t   hundred.col_name, hundred.col_code, \n\t\t\t   hundred.col_int \n\t\t\t   from updates, hundred \n\t\t\t   where updates.col_key = hundred.col_key\",$dbh,$opt_loop_count);\n\n  test_query(\"agg_subtotal_report\",\n\t     \"Time for agg_subtotal_report\",\n\t     \"select avg(col_signed), min(col_signed), max(col_signed), \n\t\t     max(col_date), min(col_date), \n\t\t     count(distinct col_name), count(col_name), \n\t\t     col_code, col_int \n\t      from reportview \n\t      where col_decim >980000000 \n\t      group by col_code, col_int\",$dbh,$opt_loop_count);\n\n\n  test_query(\"agg_total_report\",\n\t     \"Time for agg_total_report\",\n\t     \"select avg(col_signed), min(col_signed), max(col_signed), \n\t\t     max(col_date), min(col_date), \n\t\t     count(distinct col_name), count(col_name), \n\t\t     count(col_code), count(col_int) \n\t      from reportview \n\t      where col_decim >980000000\",$dbh,$opt_loop_count);\n}else{\n  print \"agg_create_view - Failed\\n\\n\";\n  print \"agg_subtotal_report - Failed\\n\\n\";\n  print \"agg_total_report - Failed\\n\\n\";\n}\n\n#fix from here\ntest_query(\"join_2_cl\",\n           \"Time for join_2_cl\",\n           \"select uniques.col_signed, uniques.col_name, \n                    hundred.col_signed, hundred.col_name \n             from uniques, hundred \n             where uniques.col_key = hundred.col_key \n              and uniques.col_key =1000\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"join_2\",\n           \"Time for join_2\",\n           \"select uniques.col_signed, uniques.col_name, \n                     hundred.col_signed, hundred.col_name \n                from uniques, hundred \n               where uniques.col_address = hundred.col_address \n                 and uniques.col_address = 'SILICON VALLEY'\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"sel_variable_select_low\",\n           \"Time for sel_variable_select_low\",\n           \"select col_key, col_int, col_signed, col_code, \n                    col_double, col_name \n                    from tenpct \n                    where col_signed < -500000000\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"sel_variable_select_high\",\n           \"Time for sel_variable_select_high\",\n           \"select col_key, col_int, col_signed, col_code,\n                    col_double, col_name\n                    from tenpct\n                    where col_signed < -250000000\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"join_4_cl\",\n           \"Time for join_4_cl\",\n           \"select uniques.col_date, hundred.col_date, \n                    tenpct.col_date, updates.col_date \n             from uniques, hundred, tenpct, updates \n             where uniques.col_key = hundred.col_key \n               and uniques.col_key = tenpct.col_key \n               and uniques.col_key = updates.col_key \n               and uniques.col_key = 1000\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"proj_100\",\n           \"Time for proj_100\",\n           \"select distinct col_address, col_signed from hundred\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"join_4_ncl\",\n           \"Time for join_4_ncl\",\n           \"select uniques.col_date, hundred.col_date, \n                        tenpct.col_date, updates.col_date \n                from uniques, hundred, tenpct, updates \n                where uniques.col_code = hundred.col_code \n                    and uniques.col_code = tenpct.col_code \n                    and uniques.col_code = updates.col_code \n                    and uniques.col_code = 'BENCHMARKS'\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"proj_10pct\",\n           \"Time for proj_10pct\",\n           \"select distinct col_signed from tenpct\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"sel_1_ncl\",\n           \"Time for sel_1_ncl\",\n           \"select col_key, col_int, col_signed, col_code, \n                    col_double, col_name \n                    from updates where col_code = 'BENCHMARKS'\"\n           ,$dbh,$opt_loop_count);\n\ntest_query(\"join_2_ncl\",\n           \"Time for join_2_ncl\",\n           \"select uniques.col_signed, uniques.col_name, \n                         hundred.col_signed, hundred.col_name \n                    from uniques, hundred \n                    where uniques.col_code = hundred.col_code \n                    and uniques.col_code = 'BENCHMARKS'\"\n           ,$dbh,$opt_loop_count);\n\nif ($limits->{'foreign_key'}){ \n  do_many($dbh,$server->create(\"integrity_temp\",\\@fields,[]));\n\n  test_query(\"integrity_test_1\",\n\t     \"Time for integrity_test\",\n\t     \"insert into integrity_temp select * \n\t      from hundred where col_int=0\",$dbh,$opt_loop_count);\n\n  test_query(\"integrity_test_2\",\n\t     \"Time for integrity_test\",\n\t     \"update hundred set col_signed = '-500000000' \n\t      where col_int = 0\",$dbh,$opt_loop_count);\n\n  test_query(\"integrity_test_3\",\n\t     \"Time for integrity_test\",\n\t     \"update hundred set col_signed = '-500000000' \n\t      where col_int = 0\",$dbh,$opt_loop_count);\n\n\n}else{\n\tprint \"integrity_test  - Failed\\n\\n\";\n}\n\npush @drop_seq_command,$server->drop_index(\"updates\",\"updates_int_bt\");\npush @drop_seq_command,$server->drop_index(\"updates\",\"updates_double_bt\");\npush @drop_seq_command,$server->drop_index(\"updates\",\"updates_decim_bt\");\npush @drop_seq_command,$server->drop_index(\"updates\",\"updates_code_h\");\n\ntest_many_command(\"Drop updates keys\",\n           \"Time for drop_updates_keys\",\n           \\@drop_seq_command,$dbh,$opt_loop_count);\n\ndo_many($dbh,$server->create(\"saveupdates\",\\@fields,[]));\n\t\t\ntest_command(\"bulk_save\",\n           \"Time for bulk_save\",\n           \"insert into saveupdates select * \n                    from updates where col_key between 5000 and 5999\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"bulk_modify\",\n           \"Time for bulk_modify\",\n           \"update updates \n                    set col_key = col_key - 100000 \n                    where col_key between 5000 and 5999\"\n           ,$dbh,$opt_loop_count);\n\nsafe_command(\"upd_append_duplicate\",\n           \"Time for upd_append_duplicate\",\n           \"insert into updates  \n                 values (6000, 0, 60000, 39997.90, \n                          50005.00, 50005.00, \n                          '11/10/1985', 'CONTROLLER', \n                          'ALICE IN WONDERLAND', \n                          'UNIVERSITY OF ILLINOIS AT CHICAGO')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_remove_duplicate\",\n           \"Time for upd_remove_duplicate\",\n           \"delete from updates where col_key = 6000 and col_int = 0\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_app_t_mid\",\n           \"Time for upd_app_t_mid\",\n           \"insert into updates \n              values (5005, 5005, 50005, 50005.00, 50005.00, \n                      50005.00, '1/1/1988', 'CONTROLLER', \n                      'ALICE IN WONDERLAND', \n                      'UNIVERSITY OF ILLINOIS AT CHICAGO')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_mod_t_mid\",\n           \"Time for upd_mod_t_mid\",\n           \"update updates set col_key = '-5000' \n                where col_key = 5005\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_del_t_mid\",\n           \"Time for upd_del_t_mid\",\n           \"delete from updates \n               where (col_key='5005') or (col_key='-5000')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_app_t_end\",\n           \"Time for upd_app_t_end\",\n           \"delete from updates \n               where (col_key='5005') or (col_key='-5000')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_mod_t_end\",\n           \"Time for upd_mod_t_end\",\n           \"update updates \n                set col_key = -1000 \n                where col_key = 1000000001\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_del_t_end\",\n           \"Time for upd_del_t_end\",\n           \"delete from updates where col_key = -1000\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_code_h\",\n\t     \"time for create_idx_updates_code_h\",\n\t     \"create index updates_code_h on updates (col_code)\",\n\t     $dbh,$opt_loop_count);\n\ntest_command(\"upd_app_t_mid\",\n           \"Time for upd_app_t_mid\",\n           \"insert into updates \n              values (5005, 5005, 50005, 50005.00, 50005.00, \n                      50005.00, '1/1/1988', 'CONTROLLER', \n                      'ALICE IN WONDERLAND', \n                      'UNIVERSITY OF ILLINOIS AT CHICAGO')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_mod_t_cod\",\n           \"Time for upd_mod_t_cod\",\n           \"update updates \n                set col_code = 'SQL+GROUPS' \n                where col_key = 5005\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_del_t_mid\",\n           \"Time for upd_del_t_mid\",\n           \"delete from updates \n               where (col_key='5005') or (col_key='-5000')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"create_idx_updates_int_bt\",\n\t     \"time for create_idx_updates_int_bt\",\n\t     \"create index updates_int_bt on updates (col_int)\",\n\t     $dbh,$opt_loop_count);\n\ntest_command(\"upd_app_t_mid\",\n           \"Time for upd_app_t_mid\",\n           \"insert into updates \n              values (5005, 5005, 50005, 50005.00, 50005.00, \n                      50005.00, '1/1/1988', 'CONTROLLER', \n                      'ALICE IN WONDERLAND', \n                      'UNIVERSITY OF ILLINOIS AT CHICAGO')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_mod_t_int\",\n           \"Time for upd_mod_t_int\",\n           \"update updates set col_int = 50015 where col_key = 5005\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"upd_del_t_mid\",\n           \"Time for upd_del_t_mid\",\n           \"delete from updates \n               where (col_key='5005') or (col_key='-5000')\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"bulk_append\",\n           \"Time for bulk_append\",\n           \"insert into updates select * from saveupdates\"\n           ,$dbh,$opt_loop_count);\n\ntest_command(\"bulk_delete\",\n           \"Time for bulk_delete\",\n           \"delete from updates where col_key < 0\"\n           ,$dbh,$opt_loop_count);\n\n################################ END ###################################\n####\n#### End of the test...Finally print time used to execute the\n#### whole test.\n\n$dbh->disconnect;\n\nend_benchmark($start_time);\n\n############################ HELP FUNCTIONS ##############################\n\nsub test_query\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time);\n\n  print $test_text . \"\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    defined(fetch_all_rows($dbh,$query)) or warn $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\nsub test_command\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time);\n\n  print $test_text . \"\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    $dbh->do($query) or die $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\nsub safe_command\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time);\n\n  print $test_text . \"\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    safe_do_many($dbh,$query); \n  }\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\nsub test_many_command\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time);\n\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    safe_do_many($dbh, @$query);\n  }\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\n", "num_lines": 639}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of selecting on keys that consist of many parts\n#\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Getopt::Long;\nuse Benchmark;\n\n$opt_loop_count=10000;\n$opt_medium_loop_count=200;\n$opt_small_loop_count=10;\n$opt_regions=6;\n$opt_groups=100;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$columns=min($limits->{'max_columns'},500,($limits->{'query_size'}-50)/24,\n\t     $limits->{'max_conditions'}/2-3);\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=10;\n  $opt_medium_loop_count/=10;\n  $opt_small_loop_count/=10;\n  $opt_groups/=10;\n}\n\nprint \"Testing the speed of selecting on keys that consist of many parts\\n\";\nprint \"The test-table has $opt_loop_count rows and the test is done with $columns ranges.\\n\\n\";\n\n####\n####  Connect and start timeing\n####\n\n$dbh = $server->connect();\n$start_time=new Benchmark;\n\n####\n#### Create needed tables\n####\n\ngoto select_test if ($opt_skip_create);\n\nprint \"Creating table\\n\";\n$dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\n\ndo_many($dbh,$server->create(\"bench1\",\n\t\t\t     [\"region char(1) NOT NULL\",\n\t\t\t      \"idn integer(6) NOT NULL\",\n\t\t\t      \"rev_idn integer(6) NOT NULL\",\n\t\t\t      \"grp integer(6) NOT NULL\"],\n\t\t\t     [\"primary key (region,idn)\",\n\t\t\t      \"unique (region,rev_idn)\",\n\t\t\t      \"unique (region,grp,idn)\"]));\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"LOCK TABLES bench1 WRITE\");\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n####\n#### Insert $opt_loop_count records with\n#### region:\t\"A\" -> \"E\"\n#### idn: \t0 -> count\n#### rev_idn:\tcount -> 0,\n#### grp:\tdistributed values 0 - > count/100\n####\n\nprint \"Inserting $opt_loop_count rows\\n\";\n\n$loop_time=new Benchmark;\n$query=\"insert into bench1 values (\";\n$half_done=$opt_loop_count/2;\nfor ($id=0,$rev_id=$opt_loop_count-1 ; $id < $opt_loop_count ; $id++,$rev_id--)\n{\n  $grp=$id*3 % $opt_groups;\n  $region=chr(65+$id%$opt_regions);\n  do_query($dbh,\"$query'$region',$id,$rev_id,$grp)\");\n  if ($id == $half_done)\n  {\t\t\t\t# Test with different insert\n    $query=\"insert into bench1 (region,idn,rev_idn,grp) values (\";\n  }\n}\n\n$end_time=new Benchmark;\nprint \"Time to insert ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"UNLOCK TABLES\");\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh,\"bench1\");\n}\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"LOCK TABLES bench1 WRITE\");\n}\n\n####\n#### Do some selects on the table\n####\n\nselect_test:\n\n\n\nif ($limits->{'group_distinct_functions'})\n{\n  print \"Testing count(distinct) on the table\\n\";\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select count(distinct region) from bench1\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_key_prefix ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select count(distinct grp) from bench1\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select count(distinct grp),count(distinct rev_idn) from bench1\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_2 ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select region,count(distinct idn) from bench1 group by region\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group_on_key ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select grp,count(distinct idn) from bench1 group by grp\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group_on_key_parts ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select grp,count(distinct rev_idn) from bench1 group by grp\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  $test_count=$opt_medium_loop_count/10;\n  for ($i=0 ; $i < $test_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select idn,count(distinct region) from bench1 group by idn\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $test_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_big ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n####\n#### End of benchmark\n####\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"UNLOCK TABLES\");\n}\nif (!$opt_skip_delete)\n{\n  do_query($dbh,\"drop table bench1\" . $server->{'drop_attr'});\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n$dbh->disconnect;\t\t\t\t# close connection\n\nend_benchmark($start_time);\n", "num_lines": 261}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000-2003, 2005-2007 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n##########################################################\n# this is the base file every test is using ....\n# this is made for not changing every file if we want to\n# add an option or just want to change something in\n# code what is the same in every file ...\n##########################################################\n\n#\n# The exported values are:\n\n# $opt_...\tVarious options\n# $date\t\tCurrent date in ISO format\n# $server\tObject for current server\n# $limits\tHash reference to limits for benchmark\n\n$benchmark_version=\"2.15\";\nuse Getopt::Long;\nuse POSIX;\n\nrequire \"$pwd/server-cfg\" || die \"Can't read Configuration file: $!\\n\";\n\n$|=1;\t\t\t\t# Output data immediately\n\n$opt_skip_test=$opt_skip_create=$opt_skip_delete=$opt_verbose=$opt_fast_insert=$opt_lock_tables=$opt_debug=$opt_skip_delete=$opt_fast=$opt_force=$opt_log=$opt_use_old_results=$opt_help=$opt_odbc=$opt_small_test=$opt_small_tables=$opt_samll_key_tables=$opt_stage=$opt_old_headers=$opt_die_on_errors=$opt_tcpip=$opt_random=$opt_only_missing_tests=0;\n$opt_cmp=$opt_user=$opt_password=$opt_connect_options=\"\";\n$opt_server=\"mysql\"; $opt_dir=\"output\";\n$opt_host=\"localhost\";$opt_database=\"test\";\n$opt_machine=\"\"; $opt_suffix=\"\";\n$opt_create_options=undef;\n$opt_optimization=\"None\";\n$opt_hw=\"\";\n$opt_threads=-1;\n\nif (!defined($opt_time_limit))\n{\n  $opt_time_limit=10*60;\t# Don't wait more than 10 min for some tests\n}\n\n$log_prog_args=join(\" \", skip_arguments(\\@ARGV,\"comments\",\"cmp\",\"server\",\n\t\t\t\t\t\"user\", \"host\", \"database\", \"password\",\n\t\t\t\t\t\"use-old-results\",\"skip-test\",\n\t\t\t\t\t\"optimization\",\"hw\",\n\t\t\t\t\t\"machine\", \"dir\", \"suffix\", \"log\"));\nGetOptions(\"skip-test=s\",\"comments=s\",\"cmp=s\",\"server=s\",\"user=s\",\"host=s\",\"database=s\",\"password=s\",\"loop-count=i\",\"row-count=i\",\"skip-create\",\"skip-delete\",\"verbose\",\"fast-insert\",\"lock-tables\",\"debug\",\"fast\",\"force\",\"field-count=i\",\"regions=i\",\"groups=i\",\"time-limit=i\",\"log\",\"use-old-results\",\"machine=s\",\"dir=s\",\"suffix=s\",\"help\",\"odbc\",\"small-test\",\"small-tables\",\"small-key-tables\",\"stage=i\",\"threads=i\",\"random\",\"old-headers\",\"die-on-errors\",\"create-options=s\",\"hires\",\"tcpip\",\"silent\",\"optimization=s\",\"hw=s\",\"socket=s\",\"connect-options=s\",\"only-missing-tests\") || usage();\n\nusage() if ($opt_help);\n$server=get_server($opt_server,$opt_host,$opt_database,$opt_odbc,\n                   machine_part(), $opt_socket, $opt_connect_options);\n$limits=merge_limits($server,$opt_cmp);\n$date=date();\n@estimated=(0.0,0.0,0.0);\t\t# For estimated time support\n\nif ($opt_threads != -1)\n{\n    print \"WARNING: Option --threads is deprecated and has no effect\\n\"\n}\n\nif ($opt_hires)\n{\n  eval \"use Time::HiRes;\";\n}\n\n{\n  my $tmp= $opt_server;\n  $tmp =~ s/_odbc$//;\n  if (length($opt_cmp) && index($opt_cmp,$tmp) < 0)\n  {\n    $opt_cmp.=\",$tmp\";\n  }\n}\n$opt_cmp=lc(join(\",\",sort(split(',',$opt_cmp))));\n\n#\n# set opt_lock_tables if one uses --fast and drivers supports it\n#\n\nif (($opt_lock_tables || $opt_fast) && $server->{'limits'}->{'lock_tables'})\n{\n  $opt_lock_tables=1;\n}\nelse\n{\n  $opt_lock_tables=0;\n}\nif ($opt_fast)\n{\n  $opt_fast_insert=1;\n  $opt_suffix=\"_fast\" if (!length($opt_suffix));\n}\n\nif ($opt_odbc)\n{\n   $opt_suffix=\"_odbc\" if (!length($opt_suffix));\n}\n\nif (!$opt_silent)\n{\n  print \"Testing server '\" . $server->version() . \"' at $date\\n\\n\";\n}\n\nif ($opt_debug)\n{\n  print \"\\nCurrent limits: \\n\";\n  foreach $key (sort keys %$limits)\n  {\n    print $key . \" \" x (30-length($key)) . $limits->{$key} . \"\\n\";\n  }\n  print \"\\n\";\n}\n\n#\n# Some help functions\n#\n\nsub skip_arguments\n{\n  my($argv,@skip_args)=@_;\n  my($skip,$arg,$name,@res);\n\n  foreach $arg (@$argv)\n  {\n    if ($arg =~ /^\\-+([^=]*)/)\n    {\n      $name=$1;\n      foreach $skip (@skip_args)\n      {\n\tif (index($skip,$name) == 0)\n\t{\n\t  $name=\"\";\t\t# Don't use this parameters\n\t  last;\n\t}\n      }\n      push (@res,$arg) if (length($name));\n    }\n  }\n  return @res;\n}\n\n\nsub merge_limits\n{\n  my ($server,$cmp)= @_;\n  my ($name,$tmp_server,$limits,$res_limits,$limit,$tmp_limits);\n\n  $res_limits=$server->{'limits'};\n  if ($cmp)\n  {\n    foreach $name (split(\",\",$cmp))\n    {\n      $tmp_server= (get_server($name,$opt_host, $opt_database,\n\t\t\t       $opt_odbc,machine_part())\n\t\t    || die \"Unknown SQL server: $name\\n\");\n      $limits=$tmp_server->{'limits'};\n      %new_limits=();\n      foreach $limit (keys(%$limits))\n      {\n\tif (defined($res_limits->{$limit}) && defined($limits->{$limit}))\n\t{\n\t  $new_limits{$limit}=min($res_limits->{$limit},$limits->{$limit});\n\t}\n      }\n      %tmp_limits=%new_limits;\n      $res_limits=\\%tmp_limits;\n    }\n  }\n  return $res_limits;\n}\n\nsub date\n{\n  my ($sec, $min, $hour, $mday, $mon, $year) = localtime(time());\n  sprintf(\"%04d-%02d-%02d %2d:%02d:%02d\",\n\t  1900+$year,$mon+1,$mday,$hour,$min,$sec);\n}\n\nsub min\n{\n  my($min)=$_[0];\n  my($i);\n  for ($i=1 ; $i <= $#_; $i++)\n  {\n    $min=$_[$i] if ($min > $_[$i]);\n  }\n  return $min;\n}\n\nsub max\n{\n  my($max)=$_[0];\n  my($i);\n  for ($i=1 ; $i <= $#_; $i++)\n  {\n    $max=$_[$i] if ($max < $_[$i]);\n  }\n  return $max;\n}\n\n\n#\n# Execute many statements in a row\n#\n\nsub do_many\n{\n  my ($dbh,@statements)=@_;\n  my ($statement,$sth);\n\n  foreach $statement (@statements)\n  {\n    if (!($sth=$dbh->do($statement)))\n    {\n      die \"Can't execute command '$statement'\\nError: $DBI::errstr\\n\";\n    }\n  }\n}\n\nsub safe_do_many\n{\n  my ($dbh,@statements)=@_;\n  my ($statement,$sth);\n\n  foreach $statement (@statements)\n  {\n    if (!($sth=$dbh->do($statement)))\n    {\n      print STDERR \"Can't execute command '$statement'\\nError: $DBI::errstr\\n\";\n      return 1;\n    }\n  }\n  return 0;\n}\n\n\n\n#\n# Do a query and fetch all rows from a statement and return the number of rows\n#\n\nsub fetch_all_rows\n{\n  my ($dbh,$query,$must_get_result)=@_;\n  my ($count,$sth);\n  $count=0;\n\n  print \"$query: \" if ($opt_debug);\n  if (!($sth= $dbh->prepare($query)))\n  {\n    print \"\\n\" if ($opt_debug);\n    die \"Error occured with prepare($query)\\n -> $DBI::errstr\\n\";\n    return undef;\n  }\n  if (!$sth->execute)\n  {\n    print \"\\n\" if ($opt_debug);\n    if (defined($server->{'error_on_execute_means_zero_rows'}) &&\n       !$server->abort_if_fatal_error())\n    {\n      if (defined($must_get_result) && $must_get_result)\n      {\n\tdie \"Error: Query $query didn't return any rows\\n\";\n      }\n      $sth->finish;\n      print \"0\\n\" if ($opt_debug);\n      return 0;\n    }\n    die \"Error occured with execute($query)\\n -> $DBI::errstr\\n\";\n    $sth->finish;\n    return undef;\n  }\n  while ($sth->fetchrow_arrayref)\n  {\n    $count++;\n  }\n  print \"$count\\n\" if ($opt_debug);\n  if (defined($must_get_result) && $must_get_result && !$count)\n  {\n    die \"Error: Query $query didn't return any rows\\n\";\n  }\n  $sth->finish;\n  undef($sth);\n  return $count;\n}\n\nsub do_query\n{\n  my($dbh,$query)=@_;\n  print \"$query\\n\" if ($opt_debug);\n  $dbh->do($query) or\n    die \"\\nError executing '$query':\\n$DBI::errstr\\n\";\n}\n\n#\n# Run a query X times\n#\n\nsub time_fetch_all_rows\n{\n  my($test_text,$result_text,$query,$dbh,$test_count)=@_;\n  my($i,$loop_time,$end_time,$count,$rows,$estimated);\n\n  print $test_text . \"\\n\"   if (defined($test_text));\n  $count=$rows=0;\n  $loop_time=new Benchmark;\n  for ($i=1 ; $i <= $test_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,$query) or die $DBI::errstr;\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i,\n\t\t\t\t\t   $test_count));\n  }\n  $end_time=new Benchmark;\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for $result_text ($count:$rows) \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\n#\n# Handle estimated time of the server is too slow\n# Returns 0 if one should continue as normal\n#\n\nsub predict_query_time\n{\n  my ($loop_time,$end_time,$count_ref,$loop,$loop_count)= @_;\n  my ($k,$tmp);\n\n  if (($end_time->[0] - $loop_time->[0]) > $opt_time_limit)\n  {\n    # We can't wait until the SUN dies.  Try to predict the end time\n    if ($loop != $loop_count)\n    {\n      $tmp=($end_time->[0] - $loop_time->[0]);\n      print \"Note: Query took longer then time-limit: $opt_time_limit\\nEstimating end time based on:\\n\";\n      print \"$$count_ref queries in $loop loops of $loop_count loops took $tmp seconds\\n\";\n      for ($k=0; $k < 3; $k++)\n      {\n\t$tmp=$loop_time->[$k]+($end_time->[$k]-$loop_time->[$k])/$loop*\n\t  $loop_count;\n\t$estimated[$k]+=($tmp-$end_time->[$k]);\n\t$end_time->[$k]=$tmp;\n      }\n      $$count_ref= int($$count_ref/$loop*$loop_count);\n      return 1;\n    }\n  }\n  return 0;\n}\n\n#\n# standard end of benchmark\n#\n\nsub end_benchmark\n{\n  my ($start_time)=@_;\n\n  $end_time=new Benchmark;\n  if ($estimated[0])\n  {\n    print \"Estimated total time: \";\n    $end_time->[0]+=$estimated[0];\n    $end_time->[1]+=$estimated[1];\n    $end_time->[2]+=$estimated[2];\n  }\n  else\n  {\n    print \"Total time: \"\n    }\n  print timestr(timediff($end_time, $start_time),\"all\") . \"\\n\";\n  exit 0;\n}\n\nsub print_time\n{\n  my ($estimated)=@_;\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n}\n\n#\n# Create a filename part for the machine that can be used for log file.\n#\n\nsub machine_part\n{\n  my ($name,$orig);\n  return $opt_machine if (length($opt_machine)); # Specified by user\n# Specified by user\n  $orig=$name=machine();\n  $name=\"win9$1\" if ($orig =~ /win.*9(\\d)/i);\n  $name=\"NT_$1\" if ($orig =~ /Windows NT.*(\\d+\\.\\d+)/i);\n  $name=\"win2k\" if ($orig =~ /Windows 2000/i);\n  $name =~ s/\\s+/_/g;\t\t# Make the filenames easier to parse\n  $name =~ s/-/_/g;\n  $name =~ s/\\//_/g;\n  return $name;\n}\n\nsub machine\n{\n  my @name = POSIX::uname();\n  my $name= $name[0] . \" \" . $name[2] . \" \" . $name[4];\n  return $name;\n}\n\n#\n# Usage\n#\n\nsub usage\n{\n    print <<EOF;\nThe MySQL benchmarks Ver $benchmark_version\n\nAll benchmarks takes the following options:\n\n--comments\n  Add a comment to the benchmark output.  Comments should contain\n  extra information that 'uname -a' doesn\\'t give and if the database was\n  stared with some specific, non default, options.\n\n--cmp=server[,server...]\n  Run the test with limits from the given servers.  If you run all servers\n  with the same --cmp, you will get a test that is comparable between\n  the different sql servers.\n\n--create-options=#\n  Extra argument to all create statements.  If you for example want to\n  create all MySQL tables as InnoDB tables use:\n  --create-options=ENGINE=InnoDB\n\n--database (Default $opt_database)\n  In which database the test tables are created.\n\n--debug\n  This is a test specific option that is only used when debugging a test.\n  Print out debugging information.\n\n--dir (Default $opt_dir)\n  Option to 'run-all-tests' to where the test results should be stored.\n\n--fast\n  Allow the database to use non standard ANSI SQL commands to make the\n  test go faster.\n\n--fast-insert\n  Use \"insert into table_name values(...)\" instead of\n  \"insert into table_name (....) values(...)\"\n  If the database supports it, some tests uses multiple value lists.\n\n--field-count\n  This is a test specific option that is only used when debugging a test.\n  This usually means how many fields there should be in the test table.\n\n--force\n  This is a test specific option that is only used when debugging a test.\n  Continue the test even if there is some error.\n  Delete tables before creating new ones.\n\n--groups (Default $opt_groups)\n  This is a test specific option that is only used when debugging a test.\n  This usually means how many different groups there should be in the test.\n\n--lock-tables\n  Allow the database to use table locking to get more speed.\n\n--log\n  Option to 'run-all-tests' to save the result to the '--dir' directory.\n\n--loop-count (Default $opt_loop_count)\n  This is a test specific option that is only used when debugging a test.\n  This usually means how many times times each test loop is executed.\n\n--help\n  Shows this help\n\n--host='host name' (Default $opt_host)\n  Host name where the database server is located.\n\n--machine=\"machine or os_name\"\n  The machine/os name that is added to the benchmark output filename.\n  The default is the OS name + version.\n\n--odbc\n  Use the ODBC DBI driver to connect to the database.\n\n--only-missing-tests\n  Only run test that don\\'t have an old test result.\n  This is useful when you want to do a re-run of tests that failed in last run.\n\n--optimization='some comments'\n Add coments about optimization of DBMS, which was done before the test.\n\n--password='password'\n  Password for the current user.\n\n--socket='socket'\n  If the database supports connecting through a Unix socket,\n  then use this socket to connect\n\n--regions\n  This is a test specific option that is only used when debugging a test.\n  This usually means how AND levels should be tested.\n\n--old-headers\n  Get the old benchmark headers from the old RUN- file.\n\n--server='server name'  (Default $opt_server)\n  Run the test on the given SQL server.\n  Known servers names are: Access, Adabas, AdabasD, Empress, Oracle,\n  Informix, DB2, mSQL, MS-SQL, MySQL, Pg, Solid and Sybase\n\n--silent\n  Don't print info about the server when starting test.\n\n--skip-delete\n  This is a test specific option that is only used when debugging a test.\n  This will keep the test tables after the test is run.\n\n--skip-test=test1[,test2,...]\n  For run-all-programs;  Don\\'t execute the named tests.\n\n--small-test\n  This runs some tests with smaller limits to get a faster test.\n  Can be used if you just want to verify that the database works, but\n  don't have time to run a full test.\n\n--small-tables\n  This runs some tests that generate big tables with fewer rows.\n  This can be used with databases that can\\'t handle that many rows\n  because of pre-sized partitions.\n\n--suffix (Default $opt_suffix)\n  The suffix that is added to the database name in the benchmark output\n  filename.  This can be used to run the benchmark multiple times with\n  different server options without overwritten old files.\n  When using --fast the suffix is automaticly set to '_fast'.\n\n--random\n  Inform test suite that we are generate random inital values for sequence of\n  test executions. It should be used for imitation of real conditions.\n\n--threads=#  **DEPRECATED**\n  This option has no effect, and will be removed in a future version.\n\n--tcpip\n  Inform test suite that we are using TCP/IP to connect to the server. In\n  this case we can\\t do many new connections in a row as we in this case may\n  fill the TCP/IP stack\n\n--time-limit (Default $opt_time_limit)\n  How long a test loop is allowed to take, in seconds, before the end result\n  is 'estimated'.\n\n--use-old-results\n  Option to 'run-all-tests' to use the old results from the  '--dir' directory\n  instead of running the tests.\n\n--user='user_name'\n  User name to log into the SQL server.\n\n--verbose\n  This is a test specific option that is only used when debugging a test.\n  Print more information about what is going on.\n\n--hw='some comments'\n Add coments about hardware used for this test.\n\n--connect-options='some connect options'\n  Add options, which uses at DBI connect.\n  For example --connect-options=mysql_read_default_file=/etc/my.cnf.\n\nEOF\n  exit(0);\n}\n\n\n\n####\n#### The end of the base file ...\n####\n1;\n", "num_lines": 609}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# a little program to generate a table of results\n# just read all the RUN-*.log files and format them nicely\n# Made by Luuk de Boer\n# Patched by Monty\n\nuse Getopt::Long;\n\n$opt_server=\"mysql\";\n$opt_dir=\"output\";\n$opt_machine=$opt_cmp=\"\";\n$opt_relative=$opt_same_server=$opt_help=$opt_Information=$opt_skip_count=$opt_no_bars=$opt_verbose=0;\n\nGetOptions(\"Information\",\"help\",\"server=s\",\"cmp=s\",\"machine=s\",\"relative\",\"same-server\",\"dir=s\",\"skip-count\",\"no-bars\",\"html\",\"verbose\") || usage();\n\nusage() if ($opt_help || $opt_Information);\n\n$opt_cmp=lc(join(\",\",sort(split(',',$opt_cmp))));\n\nif ($opt_same_server)\n{\n  $files=\"$opt_dir/RUN-$opt_server*$opt_machine\";\n}\nelse\n{\n  $files=\"$opt_dir/RUN-*$opt_machine\";\n}\n$files.= \"-cmp-$opt_cmp\" if (length($opt_cmp));\n\n#\n# Go trough all RUN files and gather statistics.\n#\n\nif ($#ARGV == -1)\n{\n  @ARGV=glob($files);\n  $automatic_files=1;\n}\n\nforeach (@ARGV)\n{\n  next if (!$opt_cmp && /-cmp-/ && $automatic_files || defined($found{$_}));\n  $prog=$filename = $_;\n  $found{$_}=1;\t\t\t# Remove dupplicates\n  /RUN-(.*)$/;\n  $tot{$prog}{'version'}=$1;\n  push(@key_order,$prog);\n  $next = 0;\n  open(TMP, \"<$filename\") || die \"Can't open $filename: $!\\n\";\n  while (<TMP>)\n  {\n    chomp;\n    if ($next == 0) {\n      if (/Server version:\\s+(\\S+.*)/i)\n      {\n\t$tot{$prog}{'server'} = $1;\n      }\n      elsif (/Arguments:\\s+(.+)/i)\n      {\n\t$arguments= $1;\n\t# Remove some standard, not informative arguments\n\t$arguments =~ s/--force|--log|--use-old\\S*|--server=\\S+|--cmp=\\S+|--user=\\S+|--pass=\\S+|--machine=\\S+|--dir=\\S+//g;\n\tif (($tmp=index($arguments,\"--comment\")) >= 0)\n\t{\n\t  if (($end=index($arguments,$tmp+2,\"--\")) >= 0)\n\t  {\n\t    substr($arguments,$tmp,($end-$tmp))=\"\";\n\t  }\n\t  else\n\t  {\n\t    $arguments=substr($arguments,0,$tmp);\n\t  }\n\t}\n\t$arguments =~ s/\\s+/ /g;\n\t$tot{$prog}{'arguments'}=$arguments;\n      }\n      elsif (/Comments:\\s+(.+)/i) {\n\t$tot{$prog}{'comments'} = $1;\n      } elsif (/^(\\S+):.*(estimated\\s|)total\\stime:\\s+([\\d.]+)\\s+(wallclock\\s|)secs/i)\n      {\n\t$tmp = $1; $tmp =~ s/://;\n\t$tot{$prog}{$tmp} = [ $3, (length($2) ? \"+\" : \"\")];\n\t$op1{$tmp} = $tmp;\n      } elsif (/Totals per operation:/i) {\n\t$next = 1;\n\tnext;\n      }\n    }\n    elsif ($next == 1)\n    {\n      if (/^(\\S+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s*([+|?])*/)\n      {\n\t$tot1{$prog}{$1} = [$2,$6,$7];\n\t$op{$1} = $1;\n      }\n    }\n  }\n}\n\nif (!%op)\n{\n  print \"Didn't find any files matching: '$files'\\n\";\n  print \"Use the --cmp=server,server option to compare benchmarks\\n\";\n  exit 1;\n}\n\n\n# everything is loaded ...\n# now we have to create a fancy output :-)\n\n# I prefer to redirect scripts instead to force it to file ; Monty\n#\n# open(RES, \">$resultfile\") || die \"Can't write to $resultfile: $!\\n\";\n# select(RES)\n#\n\nif ($opt_html) {\n  html_output();\n} else {\n  ascii_output();\n}\nexit 0;\n\n#\n# some output + format functions;\n#\n\nsub ascii_output {\n  print <<EOF;\nThis is the result file of the different benchmark tests.\n\nThe number in () after each tests shows how many SQL commands the particular\ntest did.  As one test may have many different parameters this gives only\na rough picture of what was done.  Check the source for more information :)\n\nKeep in mind that one can\\'t compare benchmarks run with different --cmp\noptions. The --cmp options sets the all limits according to the worst\nlimit for all server in the benchmark.\n\nNumbers marked with '+' are estimated according to previous runs because\nthe query took longer than a given time-limit to finish. The estimation\nshouldn\\'t be far from the real result thought.\n\nNumbers marked with '?' contains results that gave wrong result. This can only\nbe used as an indication of how long it took for the server to produce a wrong\nresult :)\n\nNumbers marked with '*' are tests that was run a different number times\nthan the test in the first column.  The reason for this is normally that the\nmarked test was run with different options that affects the number of tests\nor that the test was from another version of the MySQL benchmarks.\n\nHope this will give you some idea how each db is performing at what thing ....\nHope you like it .... Luuk & Monty (1997)\n\nEOF\n\n  if ($opt_relative)\n  {\n    print \"Column 1 is in seconds. All other columns are presented relative\\n\";\n    print \"to this. 1.00 is the same, bigger numbers indicates slower\\n\\n\";\n  }\n\n  if ($opt_verbose)\n  {\n    print \"The test values is printed in the format 'time:number of tests'\\n\";\n  }\n\n  if (length($opt_cmp))\n  {\n    print \"The test was run with limits from: $opt_cmp\\n\\n\";\n  }\n  print \"The result logs which where found and the options:\\n\";\n  $bar= $opt_no_bars ? \" \" : \"|\";\n\n  # Move $opt_server first in array if not filename on command line\n  if ($automatic_files)\n  {\n    @key_order=sort {$a cmp $b} keys %tot;\n    for ($i=0; $i <= $#key_order; $i++)\n    {\n      if ($tot{$key_order[$i]}{'version'} =~ /^$opt_server-/)\n      {\n\tunshift(@key_order,$key_order[$i]);\n\tsplice(@key_order,$i+1,1);\n\tlast;\n      }\n    }\n  }\n  # Print header\n\n  $column_count=0;\n  foreach $key (@key_order)\n  {\n    $tmp=$tmp=$tot{$key}{'version'};\n    $tmp =~ s/-cmp-$opt_cmp// if (length($opt_cmp));\n    $column_count++;\n    printf \"%2d %-40.40s: %s %s\\n\", $column_count, $tmp,\n    $tot{$key}{'server'}, $tot{$key}{'arguments'};\n    print \"  $tot{$key}{'comments'}\\n\"\n      if ($tot{$key}{'comments'} =~ /\\w+/);\n  }\n\n  print \"\\n\";\n\n  $namewidth=($opt_skip_count && !$opt_verbose) ? 29 : 36;\n  $colwidth= $opt_relative ? 10 : 7;\n  $count_width=7;\n  $colwidth+=$count_width if ($opt_verbose);\n\n  print_sep(\"=\");\n  printf \"%-$namewidth.${namewidth}s${bar}\", \"Operation\";\n  $count = 1;\n  foreach $key (@key_order)\n  {\n    printf \"%${colwidth}d${bar}\", $count;\n    $count++;\n  }\n  printf \"\\n%-$namewidth.${namewidth}s${bar}\", \"\";\n  foreach $key (@key_order)\n  {\n    $ver=$tot{$key}{'version'};\n    $ver =~ s/-[a-zA-Z0-9_\\.]+-cmp-$opt-cmp$//;\n    printf \"%${colwidth}.${colwidth}s${bar}\", $ver;\n  }\n  print \"\\n\";\n  print_sep(\"-\");\n  print_string($opt_relative ? \"Relative results per test (First column is in seconds):\" : \"Results per test in seconds:\");\n  print_sep(\"-\");\n\n  foreach $key (sort {$a cmp $b} keys %op1)\n  {\n    printf \"%-$namewidth.${namewidth}s${bar}\", $key;\n    $first=undef();\n    foreach $server (@key_order)\n    {\n      print_value($first,$tot{$server}{$key}->[0],undef(),$tot{$server}{$key}->[1]);\n      $first=$tot{$server}{$key}->[0] if (!defined($first));\n    }\n    print \"\\n\";\n  }\n\n  print_sep(\"-\");\n  print_string(\"The results per operation:\");\n  print_sep(\"-\");\n\n  foreach $key (sort {$a cmp $b} keys %op)\n  {\n    next if ($key =~ /TOTALS/i);\n    $tmp=$key;\n    $count=$tot1{$key_order[0]}{$key}->[1];\n    $tmp.= \" (\" . $count .  \")\" if (!$skip_count);\n    printf \"%-$namewidth.${namewidth}s${bar}\", $tmp;\n    $first=undef();\n    foreach $server (@key_order)\n    {\n      $tmp= $count != $tot1{$server}{$key}->[1] ? \"*\" : \"\";\n      print_value($first,$tot1{$server}{$key}->[0],$tot1{$server}{$key}->[1],\n\t\t  $tot1{$server}{$key}->[2] . $tmp);\n      $first=$tot1{$server}{$key}->[0] if (!defined($first));\n    }\n    print \"\\n\";\n  }\n\n  print_sep(\"-\");\n  $key=\"TOTALS\";\n  printf \"%-$namewidth.${namewidth}s${bar}\", $key;\n  $first=undef();\n  foreach $server (@key_order)\n  {\n    print_value($first,$tot1{$server}{$key}->[0],undef(),\n\t\t$tot1{$server}{$key}->[2]);\n    $first=$tot1{$server}{$key}->[0] if (!defined($first));\n  }\n  print \"\\n\";\n  print_sep(\"=\");\n}\n\n\nsub html_output\n{\n  my $template=\"template.html\";\n  my $title=\"MySQL | | Information | Benchmarks | Compare with $opt_cmp\";\n  my $image=\"info.gif\";\n  $bar=\"\";\n\n  open(TEMPLATE, $template) || die;\n  while (<TEMPLATE>)\n  {\n    if (/<center>/)\n    {\n      print $_;\n      print \"<!---- This is AUTOMATICALLY Generated. Do not edit here! ---->\\n\";\n    }\n    elsif (/TITLE:SUBTITLE/)\n    {\n      s|TITLE:SUBTITLE|$title|;\n      print $_;\n    }\n    elsif (/TITLE:COMPARE/)\n    {\n      s|TITLE:COMPARE|$opt_cmp|;\n      print $_;\n    }\n    elsif (/ subchapter name /)\n    {\n      # Nothing here for now\n      print $_;\n    }\n    elsif (/ text of chapter /)\n    {\n      print $_;\n      print_html_body();\n    }\n    else\n    {\n      print $_;\n    }\n  }\n  close(TEMPLATE);\n}\n\n\nsub print_html_body\n{\n  my ($title,$count,$key);\n  print <<EOF;\n<center>\n<font size=+4><b>MySQL Benchmark Results</b></font><br>\n<font size=+1><b>Compare with $opt_cmp</b></font><p><p>\n</center>\nThis is the result file of the different benchmark tests.\n<p>\n\nThe number in () after each tests shows how many SQL commands the particular\ntest did.  As one test may have many different parameters this gives only\na rough picture of what was done.  Check the source for more information.\n<p>\nKeep in mind that one can\\'t compare benchmarks run with different --cmp\noptions. The --cmp options sets the all limits according to the worst\nlimit for all server in the benchmark.\n<p>\nNumbers marked with '+' are estimated according to previous runs because\nthe query took longer than a given time-limit to finish. The estimation\nshouldn\\'t be far from the real result thought.\n<p>\nNumbers marked with '?' contains results that gave wrong result. This can only\nbe used as an indication of how long it took for the server to produce a wrong\nresult :)\n<p>\nHope this will give you some idea how each db is performing at what thing ....\n<br>\nHope you like it .... Luuk & Monty (1997)\n<p><p>\nEOF\n\n  if ($opt_relative)\n  {\n    print \"Column 1 is in seconds. All other columns are presented relative<br>\\n\";\n    print \"to this. 1.00 is the same, bigger numbers indicates slower<p>\\n\\n\";\n  }\n\n  if (length($opt_cmp))\n  {\n    print \"The test was run with limits from: $opt_cmp\\n\\n\";\n  }\n  print \"The result logs which where found and the options:<br>\\n\";\n\n  # Move $opt_server first in array\n  if ($automatic_files)\n  {\n    @key_order=sort {$a cmp $b} keys %tot;\n    for ($i=0; $i <= $#key_order; $i++)\n    {\n      if ($tot{$key_order[$i]}{'version'} =~ /^$opt_server-/)\n      {\n\tunshift(@key_order,$key_order[$i]);\n\tsplice(@key_order,$i+1,1);\n\tlast;\n      }\n    }\n  }\n  # Print header\n  print \"<p><center><table border=1 width=100%>\\n\";\n  $column_count=0;\n  foreach $key (@key_order)\n  {\n    $tmp=$tot{$key}{'version'};\n    $tmp =~ s/-cmp-$opt_cmp// if (length($opt_cmp));\n    $column_count++;\n#    printf \"<tr><td>%2d<td>%-36.36s<td>%s %s</tr>\\n\", $column_count, $tmp,\n    printf \"<tr><td>%2d</td><td>%s</td><td>%s %s</td></tr>\\n\",\n    $column_count, $tmp, $tot{$key}{'server'}, $tot{$key}{'arguments'};\n    print \"<tr><td colspan=3>$tot{$key}{'comments'}</td></tr>\\n\"\n      if ($tot{$key}{'comments'} =~ /\\w+/);\n  }\n\n  print \"</table></center><p><center><table border=1 width=100%>\\n\";\n\n  $namewidth=$opt_skip_count ? 22 :29;\n  $colwidth= $opt_relative ? 10 : 7;\n  $count_width=7;\n\n  printf \"<tr><td><b>%s</b></td>\\n\", \"Operation\";\n  $count = 1;\n  foreach $key (@key_order)\n  {\n    $ver=$tot{$key}{'version'};\n    printf \"<td align=center><b>%d\", $count;\n    printf \"<br>%${colwidth}.${colwidth}s</b></td>\\n\", substr($ver,0,index($ver,\"-\"));\n    $count++;\n  }\n  print \"</tr>\\n\";\n  $title = $opt_relative ? \"Relative results per test (First column is in seconds):\" : \"Results per test in seconds:\";\n  printf \"<tr><td colspan=%d><b>%s</b></td></tr>\\n\", $count, $title;\n\n  foreach $key (sort {$a cmp $b} keys %op1)\n  {\n    if (!$opt_html)\n    {\n      printf \"<tr><td>%-$namewidth.${namewidth}s</td>\", $key;\n    }\n    else\n    {\n      print \"<tr><td>$key</td>\";\n    }\n    $first=undef();\n    foreach $server (@key_order)\n    {\n      print_value($first,$tot{$server}{$key}->[0],undef(),\n\t\t  $tot{$server}{$key}->[1]);\n      $first=$tot{$server}{$key}->[0] if (!defined($first));\n    }\n    print \"</tr>\\n\";\n  }\n\n  $title = \"The results per operation:\";\n  printf \"<tr><td colspan=%d><b>%s</b></td></tr>\\n\", $count, $title;\n\n  foreach $key (sort {$a cmp $b} keys %op)\n  {\n    next if ($key =~ /TOTALS/i);\n    $tmp=$key;\n    $tmp.= \" (\" . $tot1{$key_order[0]}{$key}->[1] . \")\" if (!$skip_count);\n    if (!$opt_html)\n    {\n      printf \"<tr><td>%-$namewidth.${namewidth}s</td>\", $tmp;\n    }\n    else\n    {\n      print \"<tr><td>$tmp</td>\";\n    }\n    $first=undef();\n    foreach $server (@key_order)\n    {\n      print_value($first,$tot1{$server}{$key}->[0],\n\t\t  $tot1{$server}{$key}->[1],\n\t\t  $tot1{$server}{$key}->[2]);\n      $first=$tot1{$server}{$key}->[0] if (!defined($first));\n    }\n    print \"</tr>\\n\";\n  }\n\n  $key=\"TOTALS\";\n  printf \"<tr><td><b>%-$namewidth.${namewidth}s</b></td>\", $key;\n  $first=undef();\n  foreach $server (@key_order)\n  {\n    print_value($first,$tot1{$server}{$key}->[0],undef(),\n\t\t$tot1{$server}{$key}->[2]);\n    $first=$tot1{$server}{$key}->[0] if (!defined($first));\n  }\n  print \"</tr>\\n</table>\\n\";\n}\n\n\nsub print_sep\n{\n  my ($sep)=@_;\n  print $sep x ($namewidth + (($colwidth+1) * $column_count)+1),\"\\n\";\n}\n\n\nsub print_value\n{\n  my ($first,$value,$count,$flags)=@_;\n  my ($tmp,$width);\n\n  if (defined($value))\n  {\n    if (!defined($first) || !$opt_relative)\n    {\n      $tmp=sprintf(\"%.2f\",$value);\n    }\n    else\n    {\n      $first=1 if ($first == 0); # Assume that it took one second instead of 0\n      $tmp= sprintf(\"%.2f\",$value/$first);\n    }\n    if (defined($flags))\n    {\n      $tmp=\"+\".$tmp if ($flags =~ /\\+/);\n      $tmp=\"?\".$tmp if ($flags =~ /\\?/);\n      $tmp=\"*\".$tmp if ($flags =~ /\\*/);\n    }\n  }\n  else\n  {\n    $tmp=\"\";\n  }\n  $width= ($opt_verbose ? $colwidth - $count_width : $colwidth);\n  if (!$opt_html)\n  {\n    $tmp= \" \" x ($width-length($tmp)) . $tmp if (length($tmp) < $width);\n  }\n  if ($opt_verbose)\n  {\n    if ($count)\n    {\n      $tmp.= \":\" . \" \" x ($count_width-1-length($count)) . $count;\n    }\n    else\n    {\n      $tmp.= \" \" x ($count_width);\n    }\n  }\n\n  if (!$opt_html) {\n    print $tmp . \"${bar}\";\n  } else {\n    print \"<td align=right>$tmp</td>\";\n  }\n}\n\n\nsub print_string\n{\n  my ($str)=@_;\n  if (!$opt_html)\n  {\n    my ($width);\n    $width=$namewidth + ($colwidth+1)*$column_count;\n    $str=substr($str,1,$width) if (length($str) > $width);\n    print($str,\" \" x ($width - length($str)),\"${bar}\\n\");\n  }\n  else\n  {\n    print $str,\"\\n\";\n  }\n}\n\n\nsub usage\n{\n    print <<EOF;\n$0  Ver 1.2\n\nThis program parses all RUN files from old 'run-all-tests --log' scripts\nand makes a nice comparable table.\n\n$0 takes currently the following options:\n\n--help or --Information\t\t\n  Shows this help\n\n--cmp=server,server,server (Default $opt_cmp)\nCompares all runs that are done with the same --cmp options to run-all-tests.\nThe most normal options are '--cmp=mysql,pg,solid' and '--cmp \"\"'\n\n--dir=...  (Default $opt_dir)\nFrom which directory one should get the runs.  All runs made by\nrun-all-tests --log is saved in the 'output' directory.\nIn the 'results' directory you may have some example runs from different\ndatabases.\n\n--html\n  Print the table in html format.\n\n--machine='full-machine-name' (Default $opt_machine)\nUse only runs that match this machine.\n\n--relative\nShow all numbers in times of the first server where the time for the\nfirst server is 1.0\n\n--same-server\nCompare all runs for --server=....  The --machine is not used in this case\nThis is nice to compare how the same server runs on different machines.\n\n--server='server name'  (Default $opt_server)\nPut this server in the first result column.\n\n--skip-count\nDo not write the number of tests after the test-name.\n\n--verbose\nWrite the number of tests in each column. This is useful when some column\nis marked with '*'.\nEOF\n\n  exit(0);\n}\n", "num_lines": 621}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# start initialition\n#\n\n$VER = \"1.0\";\n\nuse Getopt::Long;\nuse Cwd;\nuse DBI;\n\n$max_row_length=500000;\t\t# Don't create bigger SQL rows that this\n$opt_lock=1;\t\t\t# lock tables\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\n\nrequire \"$pwd/server-cfg\" || die \"Can't read Configuration file: $!\\n\";\n\n$|=1;\n\n$opt_from_server= $opt_to_server= \"mysql\";\n$opt_from_host= $opt_to_host=     \"localhost\";\n$opt_from_db= $opt_to_db=         \"test\";\n$opt_from_user=$opt_from_password=$opt_to_user=$opt_to_password=\"\";\n$opt_help=$opt_verbose=$opt_debug=0;\n\n\nGetOptions(\"from-server=s\",\"to-server=s\",\"from-host=s\",\"to-host=s\",\"from-db=s\",\n\t   \"to-db=s\", \"help\", \"verbose\",\"debug\") || usage();\n\nusage() if ($opt_help || \n\t    ($opt_from_server eq $opt_to_server && \n\t     $opt_from_db eq $opt_to_db &&\n\t     $opt_from_host eq $opt_to_host));\n\n####\n#### Usage\n####\n\n\nsub usage\n{\n  print <<EOF;\n\n$0 version $VER by Monty\n\n Copies tables between two database servers. If the destination table doesn\\'t\n exist it\\'s autoamticly created.  If the destination table exists, it\n should be compatible with the source table.\n\n Because DBI doesn\\'t provide full information about the columns in a table,\n some columns may not have optimal types in a create tables.  Any created\n tables will also not have any keys!\n\n  Usage: $0 [options] tables...\n\n  Options:\n  --help         Show this help and exit\n  --from-server\t  Source server\t\t\t(Default: $opt_from_server)\n  --from-host     Source hostname\t\t(Default: $opt_from_host)\n  --from-db       Source database name\t\t(Default: $opt_from_db)\n  --from-user\t  Source user\t\t\t(Default: $opt_from_password)\n  --from-password Source password\t\t(Default: $opt_from_password)\n  --to-server     Destination server\t\t(Default: $opt_to_server)\n  --to-host       Destination hostname\t\t(Default: $opt_to_host)\n  --to-db         Destination database name\t(Default: $opt_to_db)\n  --to-user\t  Destination user\t\t(Default: $opt_to_user)\n  --to-password\t  Destination password\t\t(Default: $opt_to_password)\n  --verbose\t  Be more verbose\n\n  If you the server names ends with _ODBC, then this program will connect\n  through ODBC instead of using a native driver.\nEOF\n   exit(0);\n}\n\n####\n#### Connect\n####\n\n$from_server=get_server($opt_from_server,$opt_from_host,$opt_from_db);\n$to_server=get_server($opt_to_server,$opt_to_host,$opt_to_db);\n\n$opt_user=$opt_from_user; $opt_password=$opt_from_password;\nprint \"- connecting to SQL servers\\n\" if ($opt_verbose);\n$from_dbh=$from_server->connect() || die \"Can't connect to source server $opt_from_server on host $opt_from_host using db $opt_from_db\";\n$opt_user=$opt_to_user; $opt_password=$opt_to_password;\n$to_dbh=$to_server->connect() || die \"Can't connect to source server $opt_to_server on host $opt_to_host using db $opt_to_db\";\n\n####\n#### Copy data\n####\n\nforeach $table (@ARGV)\n{\n\n  print \"- querying $table\\n\" if ($opt_verbose);\n  $sth=$from_dbh->prepare(\"select * from $table\") || die \"Can't prepare query to get $table; $DBI::errstr\";\n  $sth->execute || die \"Can't execute query to get data from $table; $DBI::errstr\";\n\n  if (!table_exists($to_server,$to_dbh,$table))\n  {\n    print \"- creating $table\\n\" if ($opt_verbose);\n    $table_def=get_table_definition($from_server,$from_dbh,$sth);\n    do_many($to_dbh,$to_server->create($table,$table_def,[]));\n  }\n  if ($opt_lock && $to_server->{'lock_tables'})\n  {\n    print \"- locking $table\\n\" if ($opt_verbose);\n    $to_dbh->do(\"lock tables $table WRITE\");\n  }\n\n  $columns=$sth->{NUM_OF_FIELDS};\n  $columns_to_quote=get_columns_to_quote($sth);\n  $insert_multi_value=$sth->{'insert_multi_value'};\n  $query=\"insert into $table values\"; $result=\"\";\n\n  print \"- copying $table\\n\" if ($opt_verbose);\n  while (($row = $sth->fetchrow_arrayref))\n  {\n    $tmp=\"(\";\n    for ($i=0 ; $i < $columns ; $i++)\n    {\n      if ($columns_to_quote->[$i])\n      {\n\t$tmp.= $to_dbh->quote($row->[$i]) . \",\";\n      }\n      else\n      {\n\t$tmp.= $row->[$i] . \",\";\t\n      }\n    }\n    substr($tmp,-1)=\")\";\t\t# Remove last ','\n    if ($insert_multi_value)\n    {\n      $to_dbh->do($query . $tmp) || die \"Can't insert row: $DBI::errstr\";\n    }\n    elsif (length($result)+length($tmp) >= $max_row_length && $result)\n    {\n      $to_dbh->do($query . $result) || die \"Can't insert row: $DBI::errstr\";\n      $result=\"\";\n    }\n    elsif (length($result))\n    {\n      $result.= \",$tmp\";\n    }\n    else\n    {\n      $result=$tmp;\n    }\n  }\n  if (length($result))\n  {\n    $to_dbh->do($query . $result) || die \"Can't insert row: $DBI::errstr\";\n  }\n  if ($opt_lock && $to_server->{'lock_tables'})\n  {\n    $to_dbh->do(\"unlock tables\");\n  }\n}\n\n\nsub get_table_definition\n{\n  my ($server,$dbh,$sth)=@_;\n  my ($i,$names,$types,$scale,$precision,$nullable,@res);\n\n  $names=$sth->{NAME};\n  $types=$sth->{TYPE};\n  $nullable=$sth->{NULLABLE};\n  if (0)\n  {\n    # The following doesn't yet work\n    $scale=$sth->{SCALE};\n    $precision=$sth->{PRECISION};\n  }\n  else\n  {\n    my (@tmp);\n    @tmp= (undef()) x $sth->{NUM_OF_FIELDS};\n    $precision= $scale= \\@tmp;\n  }\n  for ($i = 0; $i < $sth->{NUM_OF_FIELDS} ; $i++)\n  {\n    push(@res,$names->[$i] . \" \" .\n\t odbc_to_sql($server,$types->[$i],$precision->[$i],$scale->[$i]) .\n\t ($nullable->[$i] ? \"\" : \" NOT NULL\"));\n  }\n  return \\@res;\n}\n\n\nsub odbc_to_sql\n{\n  my ($server,$type,$precision,$scale)=@_;\n\n  if ($type == DBI::SQL_CHAR())\n  {\n    return defined($precision) ? \"char($precision)\" : \"varchar(255)\";\n  }\n\n  if ($type == DBI::SQL_NUMERIC())\n  {\n    $precision=15 if (!defined($precision));\n    $scale=6 if (!defined($scale));\n    return \"numeric($precision,$scale)\";\n  }\n  if ($type == DBI::SQL_DECIMAL())\n  {\n    $precision=15 if (!defined($precision));\n    $scale=6 if (!defined($scale));\n    return \"decimal($precision,$scale)\";\n  }\n  if ($type == DBI::SQL_INTEGER())\n  {\n    return \"integer\" if (!defined($precision));\n    return \"integer($precision)\";\n  }\n  if ($type == DBI::SQL_SMALLINT())\n  {\n    return \"smallint\" if (!defined($precision));\n    return \"smallint($precision)\";\n  }\n  if ($type == DBI::SQL_FLOAT())\n  {\n    $precision=12 if (!defined($precision));\n    $scale=2 if (!defined($scale));\n    return \"float($precision,$scale)\";\n  }\n  if ($type == DBI::SQL_REAL())\n  {\n    $precision=12 if (!defined($precision));\n    $scale=2 if (!defined($scale));\n    return \"float($precision,$scale)\";\n  }\n  if ($type == DBI::SQL_DOUBLE())\n  {\n    $precision=22 if (!defined($precision));\n    $scale=2 if (!defined($scale));\n    return \"double($precision,$scale)\";\n  }\n  if ($type == DBI::SQL_VARCHAR())\n  {\n    $precision=255 if (!defined($precision));\n    return \"varchar($precision)\";\n  }\n  return \"date\"\t\t\t\tif ($type == DBI::SQL_DATE());\n  return \"time\"\t\t\t\tif ($type == DBI::SQL_TIME());\n  return \"timestamp\"\t\t\tif ($type == DBI::SQL_TIMESTAMP());\n  return $server->{'text'}\t\tif ($type == DBI::SQL_LONGVARCHAR());\n  return $server->{'blob'}\t\tif ($type == DBI::SQL_LONGVARBINARY());\n  if ($type == DBI::SQL_BIGINT())\n  {\n    return \"bigint\" if (!defined($precision));\n    return \"bigint($precision)\";\n  }\n  if ($type == DBI::SQL_TINYINT())\n  {\n    return \"tinyint\" if (!defined($precision));\n    return \"tinyint($precision)\";\n  }\n  die \"Can't covert type '$type' to a ODBC type\\n\";\n}\n\n#\n# return an array with 1 for all coumns that we have to quote\n#\n\t\t\t\t\t      \nsub get_columns_to_quote($sth)\n{\n  my ($sth)=@_;\n  my ($i,@res,$type,$tmp);\n\n  @res=();\n  for ($i = 0; $i < $sth->{NUM_OF_FIELDS} ; $i++)\n  {\n    $type=$sth->{TYPE}->[$i];\n    $tmp=1;\t\t\t# String by default\n    if ($type == DBI::SQL_NUMERIC()\t|| $type == DBI::SQL_DECIMAL() ||\n\t$type == DBI::SQL_INTEGER()\t|| $type == DBI::SQL_SMALLINT() ||\n\t$type == DBI::SQL_SMALLINT()\t|| $type == DBI::SQL_FLOAT() ||\n\t$type == DBI::SQL_REAL() \t|| $type == DBI::SQL_DOUBLE() ||\n\t$type == DBI::SQL_BIGINT()\t|| $type == DBI::SQL_TINYINT())\n    {\n      $tmp=0;\n    }\n    push (@res,$tmp);\n  }\n  return \\@res;\n}\n\n#\n# Check if table exists;  Return 1 if table exists\n#\n\nsub table_exists\n{\n  my ($server,$dbh,$table)=@_;\n  if ($server->{'limits'}->{'group_functions'})\n  {\n    return !safe_query($dbh,\"select count(*) from $table\");\n  }\n  if ($server->{'limits'}->{'limit'})\n  {\n    return !safe_query($dbh,\"select * from $table limit 1\");\n  }\n  die \"Don't know how to check if table '$table' exists in destination server\\n\";\n}\n\n\n#\n# execute query;  return 0 if query is ok\n#\n\nsub safe_query\n{\n  my ($dbh,$query)=@_;\n  my ($sth);\n\n  print \"query: $query\\n\" if ($opt_debug);\n  if (!($sth= $dbh->prepare($query)))\n  {\n    print \"error: $DBI::errstr\\n\" if ($opt_debug);\n    return 1;\n  }\n  if (!$sth->execute)\n  {\n    print \"error: $DBI::errstr\\n\" if ($opt_debug);\n    return 1\n  }\n  while ($sth->fetchrow_arrayref)\n  {\n  }\n  $sth->finish;\n  undef($sth);\n  return 0;\n}\n\n#\n# execute an array of queries\n#\n\nsub do_many\n{\n  my ($dbh,@statements)=@_;\n  my ($statement,$sth);\n\n  foreach $statement (@statements)\n  {\n    print \"query: $statement\\n\" if ($opt_debug);\n    if (!($sth=$dbh->do($statement)))\n    {\n      die \"Can't execute command '$statement'\\nError: $DBI::errstr\\n\";\n    }\n  }\n}\n", "num_lines": 374}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# -*- perl -*-\n# Copyright (c) 2000-2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# Written by Monty for the TCX/Monty Program/Detron benchmark suite.\n# Empress and PostgreSQL patches by Luuk de Boer\n# Extensions for ANSI SQL and Mimer by Bengt Gunne\n# Some additions and corrections by Matthias Urlich\n#\n# This programs tries to find all limits for a sql server\n# It gets the name from what it does to most servers :)\n#\n# Be sure to use --help before running this!\n#\n# If you want to add support for another server, add a new package for the\n# server in server-cfg.  You only have to support the 'new' and 'version'\n# functions. new doesn't need to have any limits if one doesn't want to\n# use the benchmarks.\n#\n\n# TODO:\n# CMT includes types and functions which are synonyms for other types\n# and functions, including those in SQL9x. It should label those synonyms\n# as such, and clarify ones such as \"mediumint\" with comments such as\n# \"3-byte int\" or \"same as xxx\".\n\n$version=\"1.61\";\n\nuse Cwd;\nuse DBI;\nuse Getopt::Long;\nuse POSIX;\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/server-cfg\" || die \"Can't read Configuration file: $!\\n\";\n\n$opt_server=\"mysql\"; $opt_host=\"localhost\"; $opt_database=\"test\";\n$opt_dir=\"limits\";\n$opt_user=$opt_password=\"\";$opt_verbose=1;\n$opt_debug=$opt_help=$opt_Information=$opt_restart=$opt_force=$opt_quick=0;\n$opt_log_all_queries=$opt_fix_limit_file=$opt_batch_mode=$opt_version=0;\n$opt_db_start_cmd=\"\";           # the db server start command\n$opt_check_server=0;\t\t# Check if server is alive before each query\n$opt_sleep=10;                  # time to sleep while starting the db server\n$limit_changed=0;               # For configure file\n$reconnect_count=0;\n$opt_suffix=\"\";\n$opt_comment=$opt_config_file=$opt_log_queries_to_file=\"\";\n$limits{'crash_me_safe'}='yes';\n$prompts{'crash_me_safe'}='crash me safe';\n$limits{'operating_system'}= machine();\n$prompts{'operating_system'}='crash-me tested on';\n$retry_limit=3;\n\nGetOptions(\"Information\",\"help\",\"server=s\",\"debug\",\"user=s\",\"password=s\",\n\"database=s\",\"restart\",\"force\",\"quick\",\"log-all-queries\",\"comment=s\",\n\"host=s\",\"fix-limit-file\",\"dir=s\",\"db-start-cmd=s\",\"sleep=s\",\"suffix=s\",\n\"batch-mode\",\"config-file=s\",\"log-queries-to-file=s\",\"check-server\",\n\"version\",\n\"verbose!\" => \\$opt_verbose) || usage();\nusage() if ($opt_help || $opt_Information);\nversion() && exit(0) if ($opt_version);\n\n$opt_suffix = '-'.$opt_suffix if (length($opt_suffix) != 0);\n$opt_config_file = \"$pwd/$opt_dir/$opt_server$opt_suffix.cfg\"\n  if (length($opt_config_file) == 0);\n$log_prefix='   ###';  # prefix for log lines in result file\n$safe_query_log='';\n$safe_query_result_log='';\n$log{\"crash-me\"}=\"\";\n\n#!!!\n\nif ($opt_fix_limit_file)\n{\n  print \"Fixing limit file for $opt_server\\n\";\n  read_config_data();\n  $limit_changed=1;\n  save_all_config_data();\n  exit 0;\n}\n\n$server=get_server($opt_server,$opt_host,$opt_database);\n$opt_server=$server->{'cmp_name'};\n\n$|=1;                           # For debugging\n\nprint \"Running $0 $version on '\",($server_version=$server->version()),\"'\\n\\n\";\nprint \"I hope you didn't have anything important running on this server....\\n\";\nread_config_data();\nif ($limit_changed)             # Must have been restarted\n{\n  save_config_data('crash_me_safe','no',\"crash me safe\");\n}\n\nif (!$opt_force && !$opt_batch_mode)\n{\n  server_info();\n}\nelse\n{\n  print \"Using --force.  I assume you know what you are doing...\\n\";\n}\nprint \"\\n\";\n\nsave_config_data('crash_me_version',$version,\"crash me version\");\nif ($server_version)\n{\n  save_config_data('server_version',$server_version,\"server version\");\n}\nif (length($opt_comment))\n{\n  save_config_data('user_comment',$opt_comment,\"comment\");\n}\n\n$opt_log=0;\nif (length($opt_log_queries_to_file))\n{\n  open(LOG,\">$opt_log_queries_to_file\") || \n    die \"Can't open file $opt_log_queries_to_file\\n\";\n  $opt_log=1;\n}\n\n#\n# Set up some limits that's regared as unlimited\n# We don't want to take up all resources from the server...\n#\n\n$max_connections=\"+1000\";       # Number of simultaneous connections\n$max_buffer_size=\"+16000000\";   # size of communication buffer.\n$max_string_size=\"+8000000\";    # Enough for this test\n$max_name_length=\"+512\";        # Actually 256, but ...\n$max_keys=\"+64\";                # Probably too big.\n$max_join_tables=\"+64\";         # Probably too big.\n$max_columns=\"+8192\";           # Probably too big.\n$max_row_length=$max_string_size;\n$max_key_length=\"+8192\";        # Big enough\n$max_order_by=\"+64\";\t\t# Big enough\n$max_expressions=\"+10000\";\n$max_big_expressions=\"+100\";\n$max_stacked_expressions=\"+2000\";\n$query_size=$max_buffer_size;\n$longreadlen=16000000;\t\t# For retrieval buffer\n\n\n#\n# First do some checks that needed for the rest of the benchmark\n#\nuse sigtrap;\t\t       # Must be removed with perl5.005_2 on Win98\n$SIG{PIPE} = 'IGNORE';\n$problem_counter=0;\n$SIG{SEGV} = sub {\n  $problem_counter +=1;\n  if ($problem_counter >= 100) {\n    die(\"Too many problems, try to restart\");\n  } else {\n    warn('SEGFAULT');\n  };    \n};\n$dbh=safe_connect();\n\n#\n# Test if the database require RESTRICT/CASCADE after DROP TABLE\n#\n\n# Really remove the crash_me table\n$prompt=\"drop table require cascade/restrict\";\n$drop_attr=\"\";\n$dbh->do(\"drop table crash_me\");\n$dbh->do(\"drop table crash_me cascade\");\nif (!safe_query_l('drop_requires_cascade',\n         [\"create table crash_me (a integer not null)\",\n\t\t \"drop table crash_me\"]))\n{\n  $dbh->do(\"drop table crash_me cascade\");  \n  if (safe_query_l('drop_requires_cascade',\n        [\"create table crash_me (a integer not null)\",\n\t\t  \"drop table crash_me cascade\"]))\n  {\n    save_config_data('drop_requires_cascade',\"yes\",\"$prompt\");\n    $drop_attr=\"cascade\";\n  }\n  else\n  {\n    die \"Can't create and drop table 'crash_me'\\n\";\n  }\n}\nelse\n{\n  save_config_data('drop_requires_cascade',\"no\",\"$prompt\");\n  $drop_attr=\"\";\n}\n\n# Remove tables from old runs\n$dbh->do(\"drop table crash_me $drop_attr\");\n$dbh->do(\"drop table crash_me2 $drop_attr\");\n$dbh->do(\"drop table crash_me3 $drop_attr\");\n$dbh->do(\"drop table crash_q $drop_attr\");\n$dbh->do(\"drop table crash_q1 $drop_attr\");\n\n$prompt=\"Tables without primary key\";\nif (!safe_query_l('no_primary_key',\n      [\"create table crash_me (a integer not null,b char(10) not null)\",\n\t\t \"insert into crash_me (a,b) values (1,'a')\"]))\n{\n  if (!safe_query_l('no_primary_key',\n      [\"create table crash_me (a integer not null,b char(10) not null\".\n        \", primary key (a))\",\n\t \"insert into crash_me (a,b) values (1,'a')\"]))\n  {\n    die \"Can't create table 'crash_me' with one record: $DBI::errstr\\n\";\n  }\n  save_config_data('no_primary_key',\"no\",$prompt);\n}\nelse\n{\n  save_config_data('no_primary_key',\"yes\",$prompt);\n}\n\n#\n#  Define strings for character NULL and numeric NULL used in expressions\n#\n$char_null=$server->{'char_null'};\n$numeric_null=$server->{'numeric_null'};\nif ($char_null eq '')\n{\n  $char_null=\"NULL\";\n}\nif ($numeric_null eq '')\n{\n  $numeric_null=\"NULL\";\n}\n\nprint \"$prompt: $limits{'no_primary_key'}\\n\";\n\nreport(\"SELECT without FROM\",'select_without_from',\"select 1\");\nif ($limits{'select_without_from'} ne \"yes\")\n{\n  $end_query=\" from crash_me\";\n  $check_connect=\"select a from crash_me\";\n}\nelse\n{\n  $end_query=\"\";\n  $check_connect=\"select 1\";\n}\n\nassert($check_connect);\nassert(\"select a from crash_me where b<'b'\");\n\nreport(\"Select constants\",'select_constants',\"select 1 $end_query\");\nreport(\"Select table_name.*\",'table_wildcard',\n       \"select crash_me.* from crash_me\");\nreport(\"Allows \\' and \\\" as string markers\",'quote_with_\"',\n       'select a from crash_me where b<\"c\"');\ncheck_and_report(\"Double '' as ' in strings\",'double_quotes',[],\n\t\t \"select 'Walker''s' $end_query\",[],\"Walker's\",1);\ncheck_and_report(\"Multiple line strings\",\"multi_strings\",[],\n\t\t \"select a from crash_me where b < 'a'\\n'b'\",[],\"1\",0);\ncheck_and_report(\"\\\" as identifier quote (ANSI SQL)\",'quote_ident_with_\"',[],\n\t\t 'select \"A\" from crash_me',[],\"1\",0);\ncheck_and_report(\"\\` as identifier quote\",'quote_ident_with_`',[],\n\t\t 'select `A` from crash_me',[],\"1\",0);\ncheck_and_report(\"[] as identifier quote\",'quote_ident_with_[',[],\n\t\t 'select [A] from crash_me',[],\"1\",0);\nreport('Double \"\" in identifiers as \"','quote_ident_with_dbl_\"',\n        'create table crash_me1 (\"abc\"\"d\" integer)',\n\t'drop table crash_me1');\t\t \n\nreport(\"Column alias\",\"column_alias\",\"select a as ab from crash_me\");\nreport(\"Table alias\",\"table_alias\",\"select b.a from crash_me as b\");\nreport(\"Functions\",'functions',\"select 1+1 $end_query\");\nreport(\"Group functions\",'group_functions',\"select count(*) from crash_me\");\nreport(\"Group functions with distinct\",'group_distinct_functions',\n       \"select count(distinct a) from crash_me\");\nreport(\"Group functions with several distinct\",'group_many_distinct_functions',\n       \"select count(distinct a), count(distinct b) from crash_me\");\nreport(\"Group by\",'group_by',\"select a from crash_me group by a\");\nreport(\"Group by position\",'group_by_position',\n       \"select a from crash_me group by 1\");\nreport(\"Group by alias\",'group_by_alias',\n       \"select a as ab from crash_me group by ab\");\nreport(\"Group on unused column\",'group_on_unused',\n       \"select count(*) from crash_me group by a\");\n\nreport(\"Order by\",'order_by',\"select a from crash_me order by a\");\nreport(\"Order by position\",'order_by_position',\n       \"select a from crash_me order by 1\");\nreport(\"Order by function\",\"order_by_function\",\n       \"select a from crash_me order by a+1\");\nreport(\"Order by on unused column\",'order_on_unused',\n       \"select b from crash_me order by a\");\n# little bit deprecated\n#check_and_report(\"Order by DESC is remembered\",'order_by_remember_desc',\n#\t\t [\"create table crash_q (s int,s1 int)\",\n#\t\t  \"insert into crash_q values(1,1)\",\n#\t\t  \"insert into crash_q values(3,1)\",\n#\t\t  \"insert into crash_q values(2,1)\"],\n#\t\t \"select s,s1 from crash_q order by s1 DESC,s\",\n#\t\t [\"drop table crash_q $drop_attr\"],[3,2,1],7,undef(),3);\nreport(\"Compute\",'compute',\n       \"select a from crash_me order by a compute sum(a) by a\");\nreport(\"INSERT with Value lists\",'insert_multi_value',\n       \"create table crash_q (s char(10))\",\n       \"insert into crash_q values ('a'),('b')\",\n       \"drop table crash_q $drop_attr\");\nreport(\"INSERT with set syntax\",'insert_with_set',\n       \"create table crash_q (a integer)\",\n       \"insert into crash_q SET a=1\",\n       \"drop table crash_q $drop_attr\");\nreport(\"INSERT with DEFAULT\",\"insert_with_default\",\n       \"create table crash_me_q (a int)\",\n       \"insert into crash_me_q (a) values (DEFAULT)\",\n       \"drop table crash_me_q $drop_attr\");\n\nreport(\"INSERT with empty value list\",\"insert_with_empty_value_list\",\n       \"create table crash_me_q (a int)\",\n       \"insert into crash_me_q (a) values ()\",\n       \"drop table crash_me_q $drop_attr\");\n\nreport(\"INSERT DEFAULT VALUES\",\"insert_default_values\",\n       \"create table crash_me_q (a int)\",\n       \"insert into crash_me_q  DEFAULT VALUES\",\n       \"drop table crash_me_q $drop_attr\");\n       \nreport(\"allows end ';'\",\"end_colon\", \"select * from crash_me;\");\ntry_and_report(\"LIMIT number of rows\",\"select_limit\",\n\t       [\"with LIMIT\",\n\t\t\"select * from crash_me limit 1\"],\n\t       [\"with TOP\",\n\t\t\"select TOP 1 * from crash_me\"]);\nreport(\"SELECT with LIMIT #,#\",\"select_limit2\", \n      \"select * from crash_me limit 1,1\");\nreport(\"SELECT with LIMIT # OFFSET #\",\n      \"select_limit3\", \"select * from crash_me limit 1 offset 1\");\n\n# The following alter table commands MUST be kept together!\nif ($dbh->do(\"create table crash_q (a integer, b integer,c1 CHAR(10))\"))\n{\n  report(\"Alter table add column\",'alter_add_col',\n\t \"alter table crash_q add d integer\");\n  report_one(\"Alter table add many columns\",'alter_add_multi_col',\n\t     [[\"alter table crash_q add (f integer,g integer)\",\"yes\"],\n\t      [\"alter table crash_q add f integer, add g integer\",\"with add\"],\n\t      [\"alter table crash_q add f integer,g integer\",\"without add\"]] );\n  report(\"Alter table change column\",'alter_change_col',\n\t \"alter table crash_q change a e char(50)\");\n\n  # informix can only change data type with modify\n  report_one(\"Alter table modify column\",'alter_modify_col',\n\t     [[\"alter table crash_q modify c1 CHAR(20)\",\"yes\"],\n\t      [\"alter table crash_q alter c1 CHAR(20)\",\"with alter\"]]);\n  report(\"Alter table alter column default\",'alter_alter_col',\n\t \"alter table crash_q alter b set default 10\");\n  report_one(\"Alter table drop column\",'alter_drop_col',\n\t     [[\"alter table crash_q drop column b\",\"yes\"],\n\t      [\"alter table crash_q drop column b restrict\",\n\t      \"with restrict/cascade\"]]);\n  report(\"Alter table rename table\",'alter_rename_table',\n\t \"alter table crash_q rename to crash_q1\");\n}\n# Make sure both tables will be dropped, even if rename fails.\n$dbh->do(\"drop table crash_q1 $drop_attr\");\n$dbh->do(\"drop table crash_q $drop_attr\");\n\nreport(\"rename table\",\"rename_table\",\n       \"create table crash_q (a integer, b integer,c1 CHAR(10))\",\n       \"rename table crash_q to crash_q1\",\n       \"drop table crash_q1 $drop_attr\");\n# Make sure both tables will be dropped, even if rename fails.\n$dbh->do(\"drop table crash_q1 $drop_attr\");\n$dbh->do(\"drop table crash_q $drop_attr\");\n\nreport(\"truncate\",\"truncate_table\",\n       \"create table crash_q (a integer, b integer,c1 CHAR(10))\",\n       \"truncate table crash_q\",\n       \"drop table crash_q $drop_attr\");\n\nif ($dbh->do(\"create table crash_q (a integer, b integer,c1 CHAR(10))\") &&\n $dbh->do(\"create table crash_q1 (a integer, b integer,c1 CHAR(10) not null)\"))\n{\n  report(\"Alter table add constraint\",'alter_add_constraint',\n\t \"alter table crash_q add constraint c2 check(a > b)\");\n  report_one(\"Alter table drop constraint\",'alter_drop_constraint',\n\t     [[\"alter table crash_q drop constraint c2\",\"yes\"],\n\t      [\"alter table crash_q drop constraint c2 restrict\",\n\t      \"with restrict/cascade\"]]);\n  report(\"Alter table add unique\",'alter_add_unique',\n\t \"alter table crash_q add constraint u1 unique(c1)\");\n  try_and_report(\"Alter table drop unique\",'alter_drop_unique',\n\t\t [\"with constraint\",\n\t\t  \"alter table crash_q drop constraint u1\"],\n\t\t [\"with constraint and restrict/cascade\",\n\t\t  \"alter table crash_q drop constraint u1 restrict\"],\n\t\t [\"with drop key\",\n\t\t  \"alter table crash_q drop key u1\"]);\n  try_and_report(\"Alter table add primary key\",'alter_add_primary_key',\n\t\t [\"with constraint\",\n\t\t  \"alter table crash_q1 add constraint p1 primary key(c1)\"],\n\t\t [\"with add primary key\",\n\t\t  \"alter table crash_q1 add primary key(c1)\"]);\n  report(\"Alter table add foreign key\",'alter_add_foreign_key',\n\t \"alter table crash_q add constraint f1 foreign key(c1) references crash_q1(c1)\");\n  try_and_report(\"Alter table drop foreign key\",'alter_drop_foreign_key',\n\t\t [\"with drop constraint\",\n\t\t  \"alter table crash_q drop constraint f1\"],\n\t\t [\"with drop constraint and restrict/cascade\",\n\t\t  \"alter table crash_q drop constraint f1 restrict\"],\n\t\t [\"with drop foreign key\",\n\t\t  \"alter table crash_q drop foreign key f1\"]);\n  try_and_report(\"Alter table drop primary key\",'alter_drop_primary_key',\n\t\t [\"drop constraint\",\n\t\t  \"alter table crash_q1 drop constraint p1 restrict\"],\n\t\t [\"drop primary key\",\n\t\t  \"alter table crash_q1 drop primary key\"]);\n}\n$dbh->do(\"drop table crash_q $drop_attr\");\n$dbh->do(\"drop table crash_q1 $drop_attr\");\n\ncheck_and_report(\"Case insensitive compare\",\"case_insensitive_strings\",\n\t\t [],\"select b from crash_me where b = 'A'\",[],'a',1);\ncheck_and_report(\"Ignore end space in compare\",\"ignore_end_space\",\n\t\t [],\"select b from crash_me where b = 'a '\",[],'a',1);\ncheck_and_report(\"Group on column with null values\",'group_by_null',\n\t\t [\"create table crash_q (s char(10))\",\n\t\t  \"insert into crash_q values(null)\",\n\t\t  \"insert into crash_q values(null)\"],\n\t\t \"select count(*),s from crash_q group by s\",\n\t\t [\"drop table crash_q $drop_attr\"],2,0);\n\n$prompt=\"Having\";\nif (!defined($limits{'having'}))\n{                               # Complicated because of postgreSQL\n  if (!safe_query_result_l(\"having\",\n      \"select a from crash_me group by a having a > 0\",1,0))\n  {\n    if (!safe_query_result_l(\"having\",\n           \"select a from crash_me group by a having a < 0\",\n\t    1,0))\n    { save_config_data(\"having\",\"error\",$prompt); }\n    else\n    { save_config_data(\"having\",\"yes\",$prompt); }\n  }\n  else\n  { save_config_data(\"having\",\"no\",$prompt); }\n}\nprint \"$prompt: $limits{'having'}\\n\";\n\nif ($limits{'having'} eq 'yes')\n{\n  report(\"Having with group function\",\"having_with_group\",\n\t \"select a from crash_me group by a having count(*) = 1\");\n}\n\nif ($limits{'column_alias'} eq 'yes')\n{\n  report(\"Order by alias\",'order_by_alias',\n\t \"select a as ab from crash_me order by ab\");\n  if ($limits{'having'} eq 'yes')\n  {\n    report(\"Having on alias\",\"having_with_alias\",\n\t   \"select a as ab from crash_me group by a having ab > 0\");\n  }\n}\nreport(\"binary numbers (0b1001)\",\"binary_numbers\",\"select 0b1001 $end_query\");\nreport(\"hex numbers (0x41)\",\"hex_numbers\",\"select 0x41 $end_query\");\nreport(\"binary strings (b'0110')\",\"binary_strings\",\"select b'0110' $end_query\");\nreport(\"hex strings (x'1ace')\",\"hex_strings\",\"select x'1ace' $end_query\");\n\nreport_result(\"Value of logical operation (1=1)\",\"logical_value\",\n\t      \"select (1=1) $end_query\");\n\nreport_result(\"Value of TRUE\",\"value_of_true\",\"select TRUE $end_query\");\nreport_result(\"Value of FALSE\",\"value_of_false\",\"select FALSE $end_query\");\n\n$logical_value= $limits{'logical_value'};\n\n$false=0;\n$result=\"no\";\nif ($res=safe_query_l('has_true_false',\"select (1=1)=true $end_query\")) {\n  $false=\"false\";\n  $result=\"yes\";\n}\nsave_config_data('has_true_false',$result,\"TRUE and FALSE\");\n\n#\n# Check how many connections the server can handle:\n# We can't test unlimited connections, because this may take down the\n# server...\n#\n\n$prompt=\"Simultaneous connections (installation default)\";\nprint \"$prompt: \";\nif (defined($limits{'connections'}))\n{\n  print \"$limits{'connections'}\\n\";\n}\nelse\n{\n  @connect=($dbh);\n\n  for ($i=1; $i < $max_connections ; $i++)\n  {\n    if (!($dbh=DBI->connect($server->{'data_source'},$opt_user,$opt_password,\n\t\t\t  { PrintError => 0})))\n    {\n      print \"Last connect error: $DBI::errstr\\n\" if ($opt_debug);\n      last;\n    }\n    $dbh->{LongReadLen}= $longreadlen; # Set retrieval buffer\n    print \".\" if ($opt_debug);\n    push(@connect,$dbh);\n  }\n  print \"$i\\n\";\n  save_config_data('connections',$i,$prompt);\n  foreach $dbh (@connect)\n  {\n    print \"#\" if ($opt_debug);\n    $dbh->disconnect || warn $dbh->errstr;           # close connection\n  }\n\n  $#connect=-1;                 # Free connections\n\n  if ($i == 0)\n  {\n    print \"Can't connect to server: $DBI::errstr.\".\n          \"  Please start it and try again\\n\";\n    exit 1;\n  }\n  $dbh=retry_connect();\n}\n\n\n#\n# Check size of communication buffer, strings...\n#\n\n$prompt=\"query size\";\nprint \"$prompt: \";\nif (!defined($limits{'query_size'}))\n{\n  $query=\"select \";\n  $first=64;\n  $end=$max_buffer_size;\n  $select= $limits{'select_without_from'} eq 'yes' ? 1 : 'a';\n\n  assert($query . \"$select$end_query\");\n\n  $first=$limits{'restart'}{'low'} if ($limits{'restart'}{'low'});\n\n  if ($limits{'restart'}{'tohigh'})\n  {\n    $end = $limits{'restart'}{'tohigh'} - 1;\n    print \"\\nRestarting this with low limit: $first and high limit: $end\\n\";\n    delete $limits{'restart'};\n    $first=$first+int(($end-$first+4)/5);           # Prefere lower on errors\n  }\n  for ($i=$first ; $i < $end ; $i*=2)\n  {\n    last if (!safe_query($query . \n            (\" \" x ($i - length($query)-length($end_query) -1)) \n\t      . \"$select$end_query\"));\n    $first=$i;\n    save_config_data(\"restart\",$i,\"\") if ($opt_restart);\n  }\n  $end=$i;\n\n  if ($i < $max_buffer_size)\n  {\n    while ($first != $end)\n    {\n      $i=int(($first+$end+1)/2);\n      if (safe_query($query .\n\t\t     (\" \" x ($i - length($query)-length($end_query) -1)) .\n\t\t     \"$select$end_query\"))\n      {\n\t$first=$i;\n      }\n      else\n      {\n\t$end=$i-1;\n      }\n    }\n  }\n  save_config_data('query_size',$end,$prompt);\n}\n$query_size=$limits{'query_size'};\n\nprint \"$limits{'query_size'}\\n\";\n\n#\n# Check for reserved words\n#\n\ncheck_reserved_words($dbh);\n\n#\n# Test database types\n#\n\n@sql_types=(\"character(1)\",\"char(1)\",\"char varying(1)\", \"character varying(1)\",\n\t    \"boolean\",\n\t    \"varchar(1)\",\n\t    \"integer\",\"int\",\"smallint\",\n\t    \"numeric(9,2)\",\"decimal(6,2)\",\"dec(6,2)\",\n\t    \"bit\", \"bit(2)\",\"bit varying(2)\",\"float\",\"float(8)\",\"real\",\n\t    \"double precision\", \"date\",\"time\",\"timestamp\",\n\t    \"interval year\", \"interval year to month\",\n            \"interval month\",\n            \"interval day\", \"interval day to hour\", \"interval day to minute\",\n            \"interval day to second\",\n            \"interval hour\", \"interval hour to minute\",\n\t    \"interval hour to second\",\n            \"interval minute\", \"interval minute to second\",\n            \"interval second\",\n\t    \"national character varying(20)\",\n\t    \"national character(20)\",\"nchar(1)\",\n\t    \"national char varying(20)\",\"nchar varying(20)\",\n\t    \"national character varying(20)\",\n\t    \"timestamp with time zone\");\n@odbc_types=(\"binary(1)\",\"varbinary(1)\",\"tinyint\",\"bigint\",\n\t     \"datetime\");\n@extra_types=(\"blob\",\"byte\",\"long varbinary\",\"image\",\"text\",\"text(10)\",\n\t      \"mediumtext\",\n\t      \"long varchar(1)\", \"varchar2(257)\",\n\t      \"mediumint\",\"middleint\",\"int unsigned\",\n\t      \"int1\",\"int2\",\"int3\",\"int4\",\"int8\",\"uint\",\n\t      \"money\",\"smallmoney\",\"float4\",\"float8\",\"smallfloat\",\n\t      \"float(6,2)\",\"double\",\n\t      \"enum('red')\",\"set('red')\", \"int(5) zerofill\", \"serial\",\n\t      \"char(10) binary\",\"int not null auto_increment,unique(q)\",\n\t      \"abstime\",\"year\",\"datetime\",\"smalldatetime\",\"timespan\",\"reltime\",\n\t      # Sybase types\n\t      \"int not null identity,unique(q)\",\n\t      # postgres types\n\t      \"box\",\"bool\",\"circle\",\"polygon\",\"point\",\"line\",\"lseg\",\"path\",\n\t      \"interval\", \"inet\", \"cidr\", \"macaddr\",\n\n\t      # oracle types\n\t      \"varchar2(16)\",\"nvarchar2(16)\",\"number(9,2)\",\"number(9)\",\n\t      \"number\", \"long\",\"raw(16)\",\"long raw\",\"rowid\",\"mlslabel\",\"clob\",\n\t      \"nclob\",\"bfile\"\n\t      );\n\n@types=([\"sql\",\\@sql_types],\n\t[\"odbc\",\\@odbc_types],\n\t[\"extra\",\\@extra_types]);\n\nforeach $types (@types)\n{\n  print \"\\nSupported $types->[0] types\\n\";\n  $tmp=@$types->[1];\n  foreach $use_type (@$tmp)\n  {\n    $type=$use_type;\n    $type =~ s/\\(.*\\)/(1 arg)/;\n    if (index($use_type,\",\")>= 0)\n    {\n      $type =~ s/\\(1 arg\\)/(2 arg)/;\n    }\n    if (($tmp2=index($type,\",unique\")) >= 0)\n    {\n      $type=substr($type,0,$tmp2);\n    }\n    $tmp2=$type;\n    $tmp2 =~ s/ /_/g;\n    $tmp2 =~ s/_not_null//g;\n    report(\"Type $type\",\"type_$types->[0]_$tmp2\",\n\t   \"create table crash_q (q $use_type)\",\n\t   \"drop table crash_q $drop_attr\");\n  }\n}\n\n#\n# Test some type limits\n#\n\n\ncheck_and_report(\"Remembers end space in char()\",\"remember_end_space\",\n\t\t [\"create table crash_q (a char(10))\",\n\t\t  \"insert into crash_q values('hello ')\"],\n\t\t \"select a from crash_q where a = 'hello '\",\n\t\t [\"drop table crash_q $drop_attr\"],\n\t\t 'hello ',6);\n\ncheck_and_report(\"Remembers end space in varchar()\",\n\t\t \"remember_end_space_varchar\",\n\t\t [\"create table crash_q (a varchar(10))\",\n\t\t  \"insert into crash_q values('hello ')\"],\n\t\t \"select a from crash_q where a = 'hello '\",\n\t\t [\"drop table crash_q $drop_attr\"],\n\t\t 'hello ',6);\n\nif (($limits{'type_extra_float(2_arg)'} eq \"yes\" ||\n    $limits{'type_sql_decimal(2_arg)'} eq \"yes\") &&\n    (!defined($limits{'storage_of_float'})))\n{\n  my $type=$limits{'type_extra_float(2_arg)'} eq \"yes\" ? \"float(4,1)\" :\n    \"decimal(4,1)\";\n  my $result=\"undefined\";\n  if (execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t \"insert into crash_q values(1.14)\"],\n\t\t\t\"select q1 from crash_q\",\n\t\t\t[\"drop table crash_q $drop_attr\"],1.1,0) &&\n      execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t \"insert into crash_q values(1.16)\"],\n\t\t\t\"select q1 from crash_q\",\n\t\t\t[\"drop table crash_q $drop_attr\"],1.1,0))\n  {\n    $result=\"truncate\";\n  }\n  elsif (execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t    \"insert into crash_q values(1.14)\"],\n\t\t\t   \"select q1 from crash_q\",\n\t\t\t   [\"drop table crash_q $drop_attr\"],1.1,0) &&\n\t execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t    \"insert into crash_q values(1.16)\"],\n\t\t\t   \"select q1 from crash_q\",\n\t\t\t   [\"drop table crash_q $drop_attr\"],1.2,0))\n  {\n    $result=\"round\";\n  }\n  elsif (execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t    \"insert into crash_q values(1.14)\"],\n\t\t\t   \"select q1 from crash_q\",\n\t\t\t   [\"drop table crash_q $drop_attr\"],1.14,0) &&\n\t execute_and_check(\"storage_of_float\",[\"create table crash_q (q1 $type)\",\n\t\t\t    \"insert into crash_q values(1.16)\"],\n\t\t\t   \"select q1 from crash_q\",\n\t\t\t   [\"drop table crash_q $drop_attr\"],1.16,0))\n  {\n    $result=\"exact\";\n  }\n  $prompt=\"Storage of float values\";\n  print \"$prompt: $result\\n\";\n  save_config_data(\"storage_of_float\", $result, $prompt);\n}\n\ntry_and_report(\"Type for row id\", \"rowid\",\n\t       [\"rowid\",\n\t\t\"create table crash_q (a rowid)\",\n\t\t\"drop table crash_q $drop_attr\"],\n\t       [\"auto_increment\",\n\t\t\"create table crash_q (a int not null auto_increment\".\n\t\t\", primary key(a))\",\"drop table crash_q $drop_attr\"],\n\t       [\"oid\",\n\t\t\"create table crash_q (a oid, primary key(a))\",\n\t\t\"drop table crash_q $drop_attr\"],\n\t       [\"serial\",\n\t\t\"create table crash_q (a serial, primary key(a))\",\n\t\t\"drop table crash_q $drop_attr\"]);\n\ntry_and_report(\"Automatic row id\", \"automatic_rowid\",\n\t       [\"_rowid\",\n\t\t\"create table crash_q (a int not null, primary key(a))\",\n\t\t\"insert into crash_q values (1)\",\n\t\t\"select _rowid from crash_q\",\n\t\t\"drop table crash_q $drop_attr\"]);\n\n#\n# Test functions\n#\n\n@sql_functions=\n  ([\"+, -, * and /\",\"+\",\"5*3-4/2+1\",14,0],\n   [\"ANSI SQL SUBSTRING\",\"substring\",\"substring('abcd' from 2 for 2)\",\"bc\",1],\n   [\"BIT_LENGTH\",\"bit_length\",\"bit_length('abc')\",24,0],\n   [\"searched CASE\",\"searched_case\",\n     \"case when 1 > 2 then 'false' when 2 > 1 then 'true' end\", \"true\",1],\n   [\"simple CASE\",\"simple_case\",\n     \"case 2 when 1 then 'false' when 2 then 'true' end\", \"true\",1],\n   [\"CAST\",\"cast\",\"CAST(1 as CHAR)\",\"1\",1],\n   [\"CHARACTER_LENGTH\",\"character_length\",\"character_length('abcd')\",\"4\",0],\n   [\"CHAR_LENGTH\",\"char_length\",\"char_length(b)\",\"10\",0],\n   [\"CHAR_LENGTH(constant)\",\"char_length(constant)\",\n     \"char_length('abcd')\",\"4\",0],\n   [\"COALESCE\",\"coalesce\",\"coalesce($char_null,'bcd','qwe')\",\"bcd\",1],\n   [\"CURRENT_DATE\",\"current_date\",\"current_date\",0,2],\n   [\"CURRENT_TIME\",\"current_time\",\"current_time\",0,2],\n   [\"CURRENT_TIMESTAMP\",\"current_timestamp\",\"current_timestamp\",0,2],\n   [\"EXTRACT\",\"extract_sql\",\n     \"extract(minute from timestamp '2000-02-23 18:43:12.987')\",43,0],\n   [\"LOCALTIME\",\"localtime\",\"localtime\",0,2],\n   [\"LOCALTIMESTAMP\",\"localtimestamp\",\"localtimestamp\",0,2],\n   [\"LOWER\",\"lower\",\"LOWER('ABC')\",\"abc\",1],\n   [\"NULLIF with strings\",\"nullif_string\",\n       \"NULLIF(NULLIF('first','second'),'first')\",undef(),4],\n   [\"NULLIF with numbers\",\"nullif_num\",\"NULLIF(NULLIF(1,2),1)\",undef(),4],\n   [\"OCTET_LENGTH\",\"octet_length\",\"octet_length('abc')\",3,0],\n   [\"POSITION\",\"position\",\"position('ll' in 'hello')\",3,0],\n   [\"TRIM\",\"trim\",\"trim(trailing from trim(LEADING FROM ' abc '))\",\"abc\",3],\n   [\"UPPER\",\"upper\",\"UPPER('abc')\",\"ABC\",1],\n   [\"concatenation with ||\",\"concat_as_||\",\"'abc' || 'def'\",\"abcdef\",1],\n   );\n\n@odbc_functions=\n  ([\"ASCII\", \"ascii\", \"ASCII('A')\",\"65\",0],\n   [\"CHAR\", \"char\", \"CHAR(65)\"  ,\"A\",1],\n   [\"CONCAT(2 arg)\",\"concat\", \"concat('a','b')\",\"ab\",1],\n   [\"DIFFERENCE()\",\"difference\",\"difference('abc','abe')\",3,0],\n   [\"INSERT\",\"insert\",\"insert('abcd',2,2,'ef')\",\"aefd\",1],\n   [\"LEFT\",\"left\",\"left('abcd',2)\",\"ab\",1],\n   [\"LTRIM\",\"ltrim\",\"ltrim('   abcd')\",\"abcd\",1],\n   [\"REAL LENGTH\",\"length\",\"length('abcd ')\",\"5\",0],\n   [\"ODBC LENGTH\",\"length_without_space\",\"length('abcd ')\",\"4\",0],\n   [\"LOCATE(2 arg)\",\"locate_2\",\"locate('bcd','abcd')\",\"2\",0],\n   [\"LOCATE(3 arg)\",\"locate_3\",\"locate('bcd','abcd',3)\",\"0\",0],\n   [\"LCASE\",\"lcase\",\"lcase('ABC')\",\"abc\",1],\n   [\"REPEAT\",\"repeat\",\"repeat('ab',3)\",\"ababab\",1],\n   [\"REPLACE\",\"replace\",\"replace('abbaab','ab','ba')\",\"bababa\",1],\n   [\"RIGHT\",\"right\",\"right('abcd',2)\",\"cd\",1],\n   [\"RTRIM\",\"rtrim\",\"rtrim(' abcd  ')\",\" abcd\",1],\n   [\"SPACE\",\"space\",\"space(5)\",\"     \",3],\n   [\"SOUNDEX\",\"soundex\",\"soundex('hello')\",0,2],\n   [\"ODBC SUBSTRING\",\"substring\",\"substring('abcd',3,2)\",\"cd\",1],\n   [\"UCASE\",\"ucase\",\"ucase('abc')\",\"ABC\",1],\n\n   [\"ABS\",\"abs\",\"abs(-5)\",5,0],\n   [\"ACOS\",\"acos\",\"acos(0)\",\"1.570796\",0],\n   [\"ASIN\",\"asin\",\"asin(1)\",\"1.570796\",0],\n   [\"ATAN\",\"atan\",\"atan(1)\",\"0.785398\",0],\n   [\"ATAN2\",\"atan2\",\"atan2(1,0)\",\"1.570796\",0],\n   [\"CEILING\",\"ceiling\",\"ceiling(-4.5)\",-4,0],\n   [\"COS\",\"cos\",\"cos(0)\",\"1.00000\",0],\n   [\"COT\",\"cot\",\"cot(1)\",\"0.64209262\",0],\n   [\"DEGREES\",\"degrees\",\"degrees(6.283185)\",\"360\",0],\n   [\"EXP\",\"exp\",\"exp(1.0)\",\"2.718282\",0],\n   [\"FLOOR\",\"floor\",\"floor(2.5)\",\"2\",0],\n   [\"LOG\",\"log\",\"log(2)\",\"0.693147\",0],\n   [\"LOG10\",\"log10\",\"log10(10)\",\"1\",0],\n   [\"MOD\",\"mod\",\"mod(11,7)\",\"4\",0],\n   [\"PI\",\"pi\",\"pi()\",\"3.141593\",0],\n   [\"POWER\",\"power\",\"power(2,4)\",\"16\",0],\n   [\"RAND\",\"rand\",\"rand(1)\",0,2],       # Any value is acceptable\n   [\"RADIANS\",\"radians\",\"radians(360)\",\"6.283185\",0],\n   [\"ROUND(2 arg)\",\"round\",\"round(5.63,2)\",\"5.6\",0],\n   [\"SIGN\",\"sign\",\"sign(-5)\",-1,0],\n   [\"SIN\",\"sin\",\"sin(1)\",\"0.841471\",0],\n   [\"SQRT\",\"sqrt\",\"sqrt(4)\",2,0],\n   [\"TAN\",\"tan\",\"tan(1)\",\"1.557408\",0],\n   [\"TRUNCATE\",\"truncate\",\"truncate(18.18,-1)\",10,0],\n   [\"NOW\",\"now\",\"now()\",0,2],           # Any value is acceptable\n   [\"CURDATE\",\"curdate\",\"curdate()\",0,2],\n   [\"CURTIME\",\"curtime\",\"curtime()\",0,2],\n   [\"TIMESTAMPADD\",\"timestampadd\",\n    \"timestampadd(SQL_TSI_SECOND,1,'1997-01-01 00:00:00')\",\n    \"1997-01-01 00:00:01\",1],\n   [\"TIMESTAMPDIFF\",\"timestampdiff\",\n    \"timestampdiff(SQL_TSI_SECOND,'1997-01-01 00:00:02',\".\n     \" '1997-01-01 00:00:01')\",\"1\",0],\n   [\"USER()\",\"user()\",\"user()\",0,2],\n   [\"DATABASE\",\"database\",\"database()\",0,2],\n   [\"IFNULL\",\"ifnull\",\"ifnull(2,3)\",2,0],\n   [\"ODBC syntax LEFT & RIGHT\", \"fn_left\",\n    \"{ fn LEFT( { fn RIGHT('abcd',2) },1) }\",\"c\",1],\n   );\n\n@extra_functions=\n  (\n   [\"& (bitwise and)\",'&',\"5 & 3\",1,0],\n   [\"| (bitwise or)\",'|',\"1 | 2\",3,0],\n   [\"<< and >> (bitwise shifts)\",'binary_shifts',\"(1 << 4) >> 2\",4,0],\n   [\"<> in SELECT\",\"<>\",\"1<>1\",\"0\",0],\n   [\"=\",\"=\",\"(1=1)\",1,$logical_value],\n   [\"~* (case insensitive compare)\",\"~*\",\"'hi' ~* 'HI'\",1,$logical_value],\n   [\"AND and OR in SELECT\",\"and_or\",\"1=1 AND 2=2\",$logical_value,0],\n   [\"AND as '&&'\",'&&',\"1=1 && 2=2\",$logical_value,0],\n   [\"ASCII_CHAR\", \"ascii_char\", \"ASCII_CHAR(65)\",\"A\",1],\n   [\"ASCII_CODE\", \"ascii_code\", \"ASCII_CODE('A')\",\"65\",0],\n   [\"ATN2\",\"atn2\",\"atn2(1,0)\",\"1.570796\",0],\n   [\"BETWEEN in SELECT\",\"between\",\"5 between 4 and 6\",$logical_value,0],\n   [\"BIT_COUNT\",\"bit_count\",\"bit_count(5)\",2,0],\n   [\"CEIL\",\"ceil\",\"ceil(-4.5)\",-4,0], # oracle\n   [\"CHARINDEX\",\"charindex\",\"charindex('a','crash')\",3,0],\n   [\"CHR\", \"chr\", \"CHR(65)\"  ,\"A\",1], # oracle\n   [\"CONCAT(list)\",\"concat_list\", \"concat('a','b','c','d')\",\"abcd\",1],\n   [\"CONVERT\",\"convert\",\"convert(CHAR,5)\",\"5\",1],\n   [\"COSH\",\"cosh\",\"cosh(0)\",\"1\",0], # oracle hyperbolic cosine of n.\n   [\"ELT\",\"elt\",\"elt(2,'ONE','TWO','THREE')\",\"TWO\",1],\n   [\"ENCRYPT\",\"encrypt\",\"encrypt('hello')\",0,2],\n   [\"FIELD\",\"field\",\"field('IBM','NCA','ICL','SUN','IBM','DIGITAL')\",4,0],\n   [\"FORMAT\",\"format\",\"format(1234.5555,2)\",\"1,234.56\",1],\n   [\"GETDATE\",\"getdate\",\"getdate()\",0,2],\n   [\"GREATEST\",\"greatest\",\"greatest('HARRY','HARRIOT','HAROLD')\",\"HARRY\",1],\n   [\"IF\",\"if\", \"if(5,6,7)\",6,0],\n   [\"IN on numbers in SELECT\",\"in_num\",\"2 in (3,2,5,9,5,1)\",$logical_value,0],\n   [\"IN on strings in SELECT\",\"in_str\",\"'monty' in ('david','monty','allan')\", $logical_value,0],\n   [\"INITCAP\",\"initcap\",\"initcap('the soap')\",\"The Soap\",1], \n       # oracle Returns char, with the first letter of each word in uppercase\n   [\"INSTR (Oracle syntax)\", \"instr_oracle\", \"INSTR('CORPORATE FLOOR','OR',3,2)\"  ,\"14\",0], # oracle instring\n   [\"INSTRB\", \"instrb\", \"INSTRB('CORPORATE FLOOR','OR',5,2)\"  ,\"27\",0], \n      # oracle instring in bytes\n   [\"INTERVAL\",\"interval\",\"interval(55,10,20,30,40,50,60,70,80,90,100)\",5,0],\n   [\"LAST_INSERT_ID\",\"last_insert_id\",\"last_insert_id()\",0,2],\n   [\"LEAST\",\"least\",\"least('HARRY','HARRIOT','HAROLD')\",\"HAROLD\",1], \n      # oracle\n   [\"LENGTHB\",\"lengthb\",\"lengthb('CANDIDE')\",\"14\",0], \n      # oracle length in bytes\n   [\"LIKE ESCAPE in SELECT\",\"like_escape\",\n     \"'%' like 'a%' escape 'a'\",$logical_value,0],\n   [\"LIKE in SELECT\",\"like\",\"'a' like 'a%'\",$logical_value,0],\n   [\"LN\",\"ln\",\"ln(95)\",\"4.55387689\",0], \n      # oracle natural logarithm of n\n   [\"LOCATE as INSTR\",\"instr\",\"instr('hello','ll')\",3,0],\n   [\"LOG(m,n)\",\"log(m_n)\",\"log(10,100)\",\"2\",0], \n      # oracle logarithm, base m, of n\n   [\"LOGN\",\"logn\",\"logn(2)\",\"0.693147\",0], \n      # informix\n   [\"LPAD\",\"lpad\",\"lpad('hi',4,'??')\",'??hi',3],\n   [\"MOD as %\",\"%\",\"10%7\",\"3\",0],\n   [\"NOT BETWEEN in SELECT\",\"not_between\",\"5 not between 4 and 6\",0,0],\n   [\"NOT LIKE in SELECT\",\"not_like\",\"'a' not like 'a%'\",0,0],\n   [\"NOT as '!' in SELECT\",\"!\",\"! 1\",0,0],\n   [\"NOT in SELECT\",\"not\",\"not $false\",$logical_value,0],\n   [\"ODBC CONVERT\",\"odbc_convert\",\"convert(5,SQL_CHAR)\",\"5\",1],\n   [\"OR as '||'\",'||',\"1=0 || 1=1\",$logical_value,0],\n   [\"PASSWORD\",\"password\",\"password('hello')\",0,2],\n   [\"PASTE\", \"paste\", \"paste('ABCDEFG',3,2,'1234')\",\"AB1234EFG\",1],\n   [\"PATINDEX\",\"patindex\",\"patindex('%a%','crash')\",3,0],\n   [\"POW\",\"pow\",\"pow(3,2)\",9,0],\n   [\"RANGE\",\"range\",\"range(a)\",\"0.0\",0], \n       # informix range(a) = max(a) - min(a)\n   [\"REGEXP in SELECT\",\"regexp\",\"'a' regexp '^(a|b)*\\$'\",$logical_value,0],\n   [\"REPLICATE\",\"replicate\",\"replicate('a',5)\",\"aaaaa\",1],\n   [\"REVERSE\",\"reverse\",\"reverse('abcd')\",\"dcba\",1],\n   [\"ROOT\",\"root\",\"root(4)\",2,0], # informix\n   [\"ROUND(1 arg)\",\"round1\",\"round(5.63)\",\"6\",0],\n   [\"RPAD\",\"rpad\",\"rpad('hi',4,'??')\",'hi??',3],\n   [\"SINH\",\"sinh\",\"sinh(1)\",\"1.17520119\",0], # oracle hyperbolic sine of n\n   [\"STR\",\"str\",\"str(123.45,5,1)\",123.5,3],\n   [\"STRCMP\",\"strcmp\",\"strcmp('abc','adc')\",-1,0],\n   [\"STUFF\",\"stuff\",\"stuff('abc',2,3,'xyz')\",'axyz',3],\n   [\"SUBSTRB\", \"substrb\", \"SUBSTRB('ABCDEFG',5,4.2)\"  ,\"CD\",1], \n      # oracle substring with bytes\n   [\"SUBSTRING as MID\",\"mid\",\"mid('hello',3,2)\",\"ll\",1],\n   [\"SUBSTRING_INDEX\",\"substring_index\",\n     \"substring_index('www.tcx.se','.',-2)\", \"tcx.se\",1],\n   [\"SYSDATE\",\"sysdate\",\"sysdate()\",0,2],\n   [\"TAIL\",\"tail\",\"tail('ABCDEFG',3)\",\"EFG\",0],\n   [\"TANH\",\"tanh\",\"tanh(1)\",\"0.462117157\",0], \n      # oracle hyperbolic tangent of n\n   [\"TRANSLATE\",\"translate\",\"translate('abc','bc','de')\",'ade',3],\n   [\"TRIM; Many char extension\",\n     \"trim_many_char\",\"trim(':!' FROM ':abc!')\",\"abc\",3],\n   [\"TRIM; Substring extension\",\n     \"trim_substring\",\"trim('cb' FROM 'abccb')\",\"abc\",3],\n   [\"TRUNC\",\"trunc\",\"trunc(18.18,-1)\",10,0], # oracle\n   [\"UID\",\"uid\",\"uid\",0,2], # oracle uid from user\n   [\"UNIX_TIMESTAMP\",\"unix_timestamp\",\"unix_timestamp()\",0,2],\n   [\"USERENV\",\"userenv\",\"userenv\",0,2], # oracle user enviroment\n   [\"VERSION\",\"version\",\"version()\",0,2],\n   [\"automatic num->string convert\",\"auto_num2string\",\"concat('a',2)\",\"a2\",1],\n   [\"automatic string->num convert\",\"auto_string2num\",\"'1'+2\",3,0],\n   [\"concatenation with +\",\"concat_as_+\",\"'abc' + 'def'\",\"abcdef\",1],\n   [\"SUBSTR (2 arg)\",'substr2arg',\"substr('abcd',2)\",'bcd',1],  #sapdb func\n   [\"SUBSTR (3 arg)\",'substr3arg',\"substr('abcd',2,2)\",'bc',1],\n   [\"LFILL (3 arg)\",'lfill3arg',\"lfill('abcd','.',6)\",'..abcd',1],\n   [\"RFILL (3 arg)\",'rfill3arg',\"rfill('abcd','.',6)\",'abcd..',1],\n   [\"RPAD (4 arg)\",'rpad4arg',\"rpad('abcd',2,'+-',8)\",'abcd+-+-',1],\n   [\"LPAD (4 arg)\",'rpad4arg',\"lpad('abcd',2,'+-',8)\",'+-+-abcd',1],\n   [\"TRIM (1 arg)\",'trim1arg',\"trim(' abcd ')\",'abcd',1],\n   [\"TRIM (2 arg)\",'trim2arg',\"trim('..abcd..','.')\",'abcd',1],\n   [\"LTRIM (2 arg)\",'ltrim2arg',\"ltrim('..abcd..','.')\",'abcd..',1],\n   [\"RTRIM (2 arg)\",'rtrim2arg',\"rtrim('..abcd..','.')\",'..abcd',1],\n   [\"EXPAND\",'expand2arg',\"expand('abcd',6)\",'abcd  ',0],\n   [\"REPLACE (2 arg) \",'replace2arg',\"replace('AbCd','bC')\",'Ad',1],\n   [\"MAPCHAR\",'mapchar',\"mapchar('A\u00e2')\",'Aa',1],\n   [\"ALPHA\",'alpha',\"alpha('A\u00e2',2)\",'AA',1],\n   [\"ASCII in string cast\",'ascii_string',\"ascii('a')\",'a',1],\n   [\"EBCDIC in string cast\",'ebcdic_string',\"ebcdic('a')\",'a',1],\n   [\"TRUNC (1 arg)\",'trunc1arg',\"trunc(222.6)\",222,0],\n   [\"FIXED\",'fixed',\"fixed(222.6666,10,2)\",'222.67',0],\n   [\"FLOAT\",'float',\"float(6666.66,4)\",6667,0],\n   [\"LENGTH\",'length',\"length(1)\",2,0],\n   [\"INDEX\",'index',\"index('abcdefg','cd',1,1)\",3,0],\n   [\"MICROSECOND\",'microsecond',\n      \"MICROSECOND('19630816200212111111')\",'111111',0],\n   [\"TIMESTAMP\",'timestamp',\n      \"timestamp('19630816','00200212')\",'19630816200212000000',0],\n   [\"VALUE\",'value',\"value(NULL,'WALRUS')\",'WALRUS',0],\n   [\"DECODE\",'decode',\"DECODE('S-103','T72',1,'S-103',2,'Leopard',3)\",2,0],\n   [\"NUM\",'num',\"NUM('2123')\",2123,0],\n   [\"CHR (any type to string)\",'chr_str',\"CHR(67)\",'67',0],\n   [\"HEX\",'hex',\"HEX('A')\",41,0],\n   );\n\n\n@sql_group_functions=\n  (\n   [\"AVG\",\"avg\",\"avg(a)\",1,0],\n   [\"COUNT (*)\",\"count_*\",\"count(*)\",1,0],\n   [\"COUNT column name\",\"count_column\",\"count(a)\",1,0],\n   [\"COUNT(DISTINCT expr)\",\"count_distinct\",\"count(distinct a)\",1,0],\n   [\"MAX on numbers\",\"max\",\"max(a)\",1,0],\n   [\"MAX on strings\",\"max_str\",\"max(b)\",\"a\",1],\n   [\"MIN on numbers\",\"min\",\"min(a)\",1,0],\n   [\"MIN on strings\",\"min_str\",\"min(b)\",\"a\",1],\n   [\"SUM\",\"sum\",\"sum(a)\",1,0],\n   [\"ANY\",\"any\",\"any(a)\",$logical_value,0],\n   [\"EVERY\",\"every\",\"every(a)\",$logical_value,0],\n   [\"SOME\",\"some\",\"some(a)\",$logical_value,0],\n   );\n\n@extra_group_functions=\n  (\n   [\"BIT_AND\",'bit_and',\"bit_and(a)\",1,0],\n   [\"BIT_OR\", 'bit_or', \"bit_or(a)\",1,0],\n   [\"COUNT(DISTINCT expr,expr,...)\",\n     \"count_distinct_list\",\"count(distinct a,b)\",1,0],\n   [\"STD\",\"std\",\"std(a)\",0,0],\n   [\"STDDEV\",\"stddev\",\"stddev(a)\",0,0],\n   [\"VARIANCE\",\"variance\",\"variance(a)\",0,0],\n   );\n\n@where_functions=\n(\n [\"= ALL\",\"eq_all\",\"b =all (select b from crash_me)\",1,0],\n [\"= ANY\",\"eq_any\",\"b =any (select b from crash_me)\",1,0],\n [\"= SOME\",\"eq_some\",\"b =some (select b from crash_me)\",1,0],\n [\"BETWEEN\",\"between\",\"5 between 4 and 6\",1,0],\n [\"EXISTS\",\"exists\",\"exists (select * from crash_me)\",1,0],\n [\"IN on numbers\",\"in_num\",\"2 in (3,2,5,9,5,1)\",1,0],\n [\"LIKE ESCAPE\",\"like_escape\",\"b like '%' escape 'a'\",1,0],\n [\"LIKE\",\"like\",\"b like 'a%'\",1,0],\n [\"MATCH UNIQUE\",\"match_unique\",\n   \"1 match unique (select a from crash_me)\",1,0],\n [\"MATCH\",\"match\",\"1 match (select a from crash_me)\",1,0],\n [\"MATCHES\",\"matches\",\"b matches 'a*'\",1,0],\n [\"NOT BETWEEN\",\"not_between\",\"7 not between 4 and 6\",1,0],\n [\"NOT EXISTS\",\"not_exists\",\n   \"not exists (select * from crash_me where a = 2)\",1,0],\n [\"NOT LIKE\",\"not_like\",\"b not like 'b%'\",1,0],\n [\"NOT UNIQUE\",\"not_unique\",\n   \"not unique (select * from crash_me where a = 2)\",1,0],\n [\"UNIQUE\",\"unique\",\"unique (select * from crash_me)\",1,0],\n );\n\n@types=([\"sql\",\\@sql_functions,0],\n\t[\"odbc\",\\@odbc_functions,0],\n\t[\"extra\",\\@extra_functions,0],\n\t[\"where\",\\@where_functions,0]);\n\n@group_types=([\"sql\",\\@sql_group_functions,0],\n\t      [\"extra\",\\@extra_group_functions,0]);\n\n\nforeach $types (@types)\n{\n  print \"\\nSupported $types->[0] functions\\n\";\n  $tmp=@$types->[1];\n  foreach $type (@$tmp)\n  {\n    if (defined($limits{\"func_$types->[0]_$type->[1]\"}))\n    {\n      next;\n    }\n    if ($types->[0] eq \"where\")\n    {\n      check_and_report(\"Function $type->[0]\",\"func_$types->[0]_$type->[1]\",\n\t\t       [],\"select a from crash_me where $type->[2]\",[],\n\t\t       $type->[3],$type->[4]);\n    }\n    elsif ($limits{'functions'} eq 'yes')\n    {\n      if (($type->[2] =~ /char_length\\(b\\)/) && (!$end_query))\n      {\n\tmy $tmp= $type->[2];\n\t$tmp .= \" from crash_me \";\n\tundef($limits{\"func_$types->[0]_$type->[1]\"});\n\tcheck_and_report(\"Function $type->[0]\",\n\t\t\t \"func_$types->[0]_$type->[1]\",\n\t\t\t [],\"select $tmp \",[],\n\t\t\t $type->[3],$type->[4]);\n      }\n      else\n      {\n\tundef($limits{\"func_$types->[0]_$type->[1]\"});\n\t$result = check_and_report(\"Function $type->[0]\",\n\t\t\t    \"func_$types->[0]_$type->[1]\",\n\t\t\t    [],\"select $type->[2] $end_query\",[],\n\t\t\t    $type->[3],$type->[4]);\n\tif (!$result)\n\t{\n\t  # check without type specifyer\n\t  if ($type->[2] =~ /DATE /)\n\t  {\n\t    my $tmp= $type->[2];\n\t    $tmp =~ s/DATE //;\n\t    undef($limits{\"func_$types->[0]_$type->[1]\"});\n\t    $result = check_and_report(\"Function $type->[0]\",\n\t\t\t\t  \"func_$types->[0]_$type->[1]\",\n\t\t\t\t  [],\"select $tmp $end_query\",[],\n\t\t\t\t  $type->[3],$type->[4]);\n\t  }\n\t  if (!$result)\n\t  {\n\t    if ($types->[0] eq \"odbc\" && ! ($type->[2] =~ /\\{fn/))\n\t    {\n\t     my $tmp= $type->[2];\n\t     # Check by converting to ODBC format\n\t     undef($limits{\"func_$types->[0]_$type->[1]\"});\n\t     $tmp= \"{fn $tmp }\";\n\t     $tmp =~ s/('1997-\\d\\d-\\d\\d \\d\\d:\\d\\d:\\d\\d')/{ts $1}/g;\n\t     $tmp =~ s/(DATE '1997-\\d\\d-\\d\\d')/{d $1}/g;\n\t     $tmp =~ s/(TIME '12:13:14')/{t $1}/g;\n\t     $tmp =~ s/DATE //;\n\t     $tmp =~ s/TIME //;\n\t     check_and_report(\"Function $type->[0]\",\n\t\t\t      \"func_$types->[0]_$type->[1]\",\n\t\t\t      [],\"select $tmp $end_query\",[],\n\t\t\t      $type->[3],$type->[4]);\n\t    }\n\t  }\n        }\n      }\n    }\n  }\n}\n\nif ($limits{'functions'} eq 'yes')\n{\n  foreach $types (@group_types)\n  {\n    print \"\\nSupported $types->[0] group functions\\n\";\n    $tmp=@$types->[1];\n    foreach $type (@$tmp)\n    {\n      check_and_report(\"Group function $type->[0]\",\n\t\t       \"group_func_$types->[0]_$type->[1]\",\n\t\t       [],\"select $type->[2],a from crash_me group by a\",[],\n\t\t       $type->[3],$type->[4]);\n    }\n  }\n  print \"\\n\";\n  report(\"mixing of integer and float in expression\",\"float_int_expr\",\n\t \"select 1+1.0 $end_query\");\n  if ($limits{'func_odbc_exp'} eq 'yes')\n  {\n    report(\"No need to cast from integer to float\",\n\t   \"dont_require_cast_to_float\", \"select exp(1) $end_query\");\n  }\n  check_and_report(\"Is 1+NULL = NULL\",\"null_num_expr\",\n\t\t   [],\"select 1+$numeric_null $end_query\",[],undef(),4);\n  $tmp=sql_concat(\"'a'\",$char_null);\n  if (defined($tmp))\n  {\n    check_and_report(\"Is $tmp = NULL\", \"null_concat_expr\", [],\n\t\t     \"select $tmp $end_query\",[], undef(),4);\n  }\n  $prompt=\"Need to cast NULL for arithmetic\";\n  add_log(\"Need_cast_for_null\",\n    \" Check if numeric_null ($numeric_null) is 'NULL'\");\n  save_config_data(\"Need_cast_for_null\",\n\t\t   ($numeric_null eq \"NULL\") ? \"no\" : \"yes\",\n\t\t   $prompt);\n}\nelse\n{\n  print \"\\n\";\n}\n\n\n#  Test: NOROUND \n{\n my $result = 'undefined';\n my $error;\n print \"NOROUND: \";\n save_incomplete('func_extra_noround','Function NOROUND');\n\n# 1) check if noround() function is supported\n $error = safe_query_l('func_extra_noround',\"select noround(22.6) $end_query\");\n if ($error ne 1)         # syntax error -- noround is not supported \n {\n   $result = 'no'\n }\n else                   # Ok, now check if it really works\n {\n   $error=safe_query_l('func_extra_noround', \n     [\"create table crash_me_nr (a int)\",\n    \"insert into crash_me_nr values(noround(10.2))\",\n    \"drop table crash_me_nr $drop_attr\"]);\n   if ($error == 1)\n   {\n     $result= \"syntax only\";\n   }\n   else\n   {\n     $result= 'yes';\n   }\n }\n print \"$result\\n\";\n save_config_data('func_extra_noround',$result,\"Function NOROUND\");\n}\n\ncheck_parenthesis(\"func_sql_\",\"CURRENT_USER\");\ncheck_parenthesis(\"func_sql_\",\"SESSION_USER\");\ncheck_parenthesis(\"func_sql_\",\"SYSTEM_USER\");\ncheck_parenthesis(\"func_sql_\",\"USER\");\n\n\nif ($limits{'type_sql_date'} eq 'yes')\n{  # \n   # Checking the format of date in result. \n   \n    safe_query(\"drop table crash_me_d $drop_attr\");\n    assert(\"create table crash_me_d (a date)\");\n    # find the example of date\n    my $dateexample;\n    if ($limits{'func_extra_sysdate'} eq 'yes') {\n     $dateexample=' sysdate() ';\n    } \n    elsif ($limits{'func_sql_current_date'} eq 'yes') {\n     $dateexample='CURRENT_DATE';\n    } \n    elsif ($limits{'func_odbc_curdate'} eq 'yes') {\n     $dateexample='curdate()';\n    } \n    elsif ($limits{'func_extra_getdate'} eq 'yes') {\n\t$dateexample='getdate()';\n    }\n    elsif ($limits{'func_odbc_now'} eq 'yes') {\n\t$dateexample='now()';\n    } else {\n\t#try to guess \n\t$dateexample=\"DATE '1963-08-16'\";\n    } ;\n    \n    my $key = 'date_format_inresult';\n    my $prompt = \"Date format in result\";\n    if (! safe_query_l('date_format_inresult',\n       \"insert into crash_me_d values($dateexample) \"))\n    { \n\tdie \"Cannot insert date ($dateexample):\".$last_error; \n    };\n    my $sth= $dbh->prepare(\"select a from crash_me_d\");\n    add_log('date_format_inresult',\"< select a from crash_me_d\");\n    $sth->execute;\n    $_= $sth->fetchrow_array;\n    add_log('date_format_inresult',\"> $_\");\n    safe_query_l($key,\"delete from crash_me_d\");   \n    if (/\\d{4}-\\d{2}-\\d{2}/){ save_config_data($key,\"iso\",$prompt);} \n    elsif (/\\d{2}-\\d{2}-\\d{2}/){ save_config_data($key,\"short iso\",$prompt);}\n    elsif (/\\d{2}\\.\\d{2}\\.\\d{4}/){ save_config_data($key,\"euro\",$prompt);}\n    elsif (/\\d{2}\\.\\d{2}\\.\\d{2}/){ save_config_data($key,\"short euro\",$prompt);}\n    elsif (/\\d{2}\\/\\d{2}\\/\\d{4}/){ save_config_data($key,\"usa\",$prompt);}\n    elsif (/\\d{2}\\/\\d{2}\\/\\d{2}/){ save_config_data($key,\"short usa\",$prompt);}\n    elsif (/\\d*/){ save_config_data($key,\"YYYYMMDD\",$prompt);}\n    else  { save_config_data($key,\"unknown\",$prompt);};\n    $sth->finish;\n\n    check_and_report(\"Supports YYYY-MM-DD (ISO) format\",\"date_format_ISO\",\n\t\t     [ \"insert into crash_me_d(a)  values ('1963-08-16')\"],\n\t\t     \"select a from crash_me_d\",\n\t\t     [\"delete from crash_me_d\"],\n\t\t     make_date_r(1963,8,16),1);\n\n    check_and_report(\"Supports DATE 'YYYY-MM-DD' (ISO) format\",\n\t\t     \"date_format_ISO_with_date\",\n\t\t     [ \"insert into crash_me_d(a) values (DATE '1963-08-16')\"],\n\t\t     \"select a from crash_me_d\",\n\t\t     [\"delete from crash_me_d\"],\n\t\t     make_date_r(1963,8,16),1);\n\n    check_and_report(\"Supports DD.MM.YYYY (EUR) format\",\"date_format_EUR\",\n\t\t     [ \"insert into crash_me_d(a) values ('16.08.1963')\"],\n\t\t     \"select a from crash_me_d\",\n\t\t     [\"delete from crash_me_d\"],\n\t\t     make_date_r(1963,8,16),1);\n    check_and_report(\"Supports DATE 'DD.MM.YYYY' (EUR) format\",\n\t\t     \"date_format_EUR_with_date\",\n\t\t     [ \"insert into crash_me_d(a) values (DATE '16.08.1963')\"],\n\t\t     \"select a from crash_me_d\",\n\t\t     [\"delete from crash_me_d\"],\n\t\t     make_date_r(1963,8,16),1);\n\n    check_and_report(\"Supports YYYYMMDD format\",\n\t \"date_format_YYYYMMDD\",\n\t [ \"insert into crash_me_d(a) values ('19630816')\"],\n\t \"select a from crash_me_d\",\n\t [\"delete from crash_me_d\"],\n\t make_date_r(1963,8,16),1);\n    check_and_report(\"Supports DATE 'YYYYMMDD' format\",\n\t \"date_format_YYYYMMDD_with_date\",\n\t [ \"insert into crash_me_d(a) values (DATE '19630816')\"],\n\t \"select a from crash_me_d\",\n\t [\"delete from crash_me_d\"],\n\t make_date_r(1963,8,16),1);\n\n    check_and_report(\"Supports MM/DD/YYYY format\",\n\t \"date_format_USA\",\n\t [ \"insert into crash_me_d(a) values ('08/16/1963')\"],\n\t \"select a from crash_me_d\",\n\t [\"delete from crash_me_d\"],\n\t make_date_r(1963,8,16),1);\n    check_and_report(\"Supports DATE 'MM/DD/YYYY' format\",\n\t \"date_format_USA_with_date\",\n\t [ \"insert into crash_me_d(a) values (DATE '08/16/1963')\"],\n\t \"select a from crash_me_d\",\n\t [\"delete from crash_me_d\"],\n\t make_date_r(1963,8,16),1);\n\n\n \n\n    check_and_report(\"Supports 0000-00-00 dates\",\"date_zero\",\n\t [\"create table crash_me2 (a date not null)\",\n\t  \"insert into crash_me2 values (\".make_date(0,0,0).\")\"],\n\t \"select a from crash_me2\",\n\t [\"drop table crash_me2 $drop_attr\"],\n\t make_date_r(0,0,0),1);\n\n    check_and_report(\"Supports 0001-01-01 dates\",\"date_one\",\n\t [\"create table crash_me2 (a date not null)\",\n\t  \"insert into crash_me2 values (\".make_date(1,1,1).\")\"],\n\t \"select a from crash_me2\",\n\t [\"drop table crash_me2 $drop_attr\"],\n\t make_date_r(1,1,1),1);\n    \n    check_and_report(\"Supports 9999-12-31 dates\",\"date_last\",\n\t[\"create table crash_me2 (a date not null)\",\n        \"insert into crash_me2 values (\".make_date(9999,12,31).\")\"],\n        \"select a from crash_me2\",\n\t[\"drop table crash_me2 $drop_attr\"],\n\tmake_date_r(9999,12,31),1);\n    \n    check_and_report(\"Supports 'infinity dates\",\"date_infinity\",\n\t [\"create table crash_me2 (a date not null)\",\n\t \"insert into crash_me2 values ('infinity')\"],\n\t \"select a from crash_me2\",\n\t [\"drop table crash_me2 $drop_attr\"],\n\t \"infinity\",1);\n    \n    if (!defined($limits{'date_with_YY'}))\n    {\n\tcheck_and_report(\"Supports YY-MM-DD dates\",\"date_with_YY\",\n\t   [\"create table crash_me2 (a date not null)\",\n\t   \"insert into crash_me2 values ('98-03-03')\"],\n\t   \"select a from crash_me2\",\n\t   [\"drop table crash_me2 $drop_attr\"],\n\t   make_date_r(1998,3,3),5);\n\tif ($limits{'date_with_YY'} eq \"yes\")\n\t{\n\t    undef($limits{'date_with_YY'});\n\t    check_and_report(\"Supports YY-MM-DD 2000 compilant dates\",\n\t       \"date_with_YY\",\n\t       [\"create table crash_me2 (a date not null)\",\n\t       \"insert into crash_me2 values ('10-03-03')\"],\n\t       \"select a from crash_me2\",\n\t       [\"drop table crash_me2 $drop_attr\"],\n\t       make_date_r(2010,3,3),5);\n\t}\n    }\n    \n# Test: WEEK()\n    {\n\tmy $result=\"no\";\n\tmy $error;\n\tprint \"WEEK:\";\n\tsave_incomplete('func_odbc_week','WEEK');\n\t$error = safe_query_result_l('func_odbc_week',\n\t     \"select week(\".make_date(1997,2,1).\") $end_query\",5,0);\n\t# actually this query must return 4 or 5 in the $last_result,\n\t# $error can be 1 (not supported at all) , -1 ( probably USA weeks)\n\t# and 0 - EURO weeks\n\tif ($error == -1) { \n\t    if ($last_result == 4) {\n\t\t$result = 'USA';\n\t    } else {\n\t\t$result='error';\n\t\tadd_log('func_odbc_week',\n\t\t  \" must return 4 or 5, but $last_result\");\n\t    }\n\t} elsif ($error == 0) {\n\t    $result = 'EURO';\n\t}\n\tprint \" $result\\n\";\n\tsave_config_data('func_odbc_week',$result,\"WEEK\");\n    }\n    \n    my $insert_query ='insert into crash_me_d values('.\n        make_date(1997,2,1).')';\n    safe_query($insert_query);\n    \n    foreach $fn ( (\n\t\t   [\"DAYNAME\",\"dayname\",\"dayname(a)\",\"\",2],\n\t\t   [\"MONTH\",\"month\",\"month(a)\",\"\",2],\n\t\t   [\"MONTHNAME\",\"monthname\",\"monthname(a)\",\"\",2],\n\t\t   [\"DAYOFMONTH\",\"dayofmonth\",\"dayofmonth(a)\",1,0],\n\t\t   [\"DAYOFWEEK\",\"dayofweek\",\"dayofweek(a)\",7,0],\n\t\t   [\"DAYOFYEAR\",\"dayofyear\",\"dayofyear(a)\",32,0],\n\t\t   [\"QUARTER\",\"quarter\",\"quarter(a)\",1,0],\n\t\t   [\"YEAR\",\"year\",\"year(a)\",1997,0]))\n    {\n\t$prompt='Function '.$fn->[0];\n\t$key='func_odbc_'.$fn->[1];\n\tadd_log($key,\"< \".$insert_query);\n\tcheck_and_report($prompt,$key,\n\t\t\t [],\"select \".$fn->[2].\" from crash_me_d\",[],\n\t\t\t $fn->[3],$fn->[4]\n\t\t\t );\n\t\n    };\n    safe_query(['delete from crash_me_d', \n\t\t'insert into crash_me_d values('.make_date(1963,8,16).')']);\n    foreach $fn ((\n\t  [\"DATEADD\",\"dateadd\",\"dateadd(day,3,make_date(1997,11,30))\",0,2],\n\t  [\"MDY\",\"mdy\",\"mdy(7,1,1998)\",\"make_date_r(1998,07,01)\",0], # informix\n\t  [\"DATEDIFF\",\"datediff\",\n\t     \"datediff(month,'Oct 21 1997','Nov 30 1997')\",0,2],\n\t  [\"DATENAME\",\"datename\",\"datename(month,'Nov 30 1997')\",0,2],\n\t  [\"DATEPART\",\"datepart\",\"datepart(month,'July 20 1997')\",0,2],\n\t  [\"DATE_FORMAT\",\"date_format\", \n\t    \"date_format('1997-01-02 03:04:05','M W D Y y m d h i s w')\", 0,2],\n\t  [\"FROM_DAYS\",\"from_days\",\n\t    \"from_days(729024)\",\"make_date_r(1996,1,1)\",1],\n\t  [\"FROM_UNIXTIME\",\"from_unixtime\",\"from_unixtime(0)\",0,2],\n\t  [\"MONTHS_BETWEEN\",\"months_between\",\n\t   \"months_between(make_date(1997,2,2),make_date(1997,1,1))\",\n\t   \"1.03225806\",0], # oracle number of months between 2 dates\n\t  [\"PERIOD_ADD\",\"period_add\",\"period_add(9602,-12)\",199502,0],\n\t  [\"PERIOD_DIFF\",\"period_diff\",\"period_diff(199505,199404)\",13,0],\n\t  [\"WEEKDAY\",\"weekday\",\"weekday(make_date(1997,11,29))\",5,0],\n\t  [\"ADDDATE\",'adddate',\n\t   \"ADDDATE(make_date(2002,12,01),3)\",'make_date_r(2002,12,04)',0],\n\t  [\"SUBDATE\",'subdate',\n\t   \"SUBDATE(make_date(2002,12,04),3)\",'make_date_r(2002,12,01)',0],\n\t  [\"DATEDIFF (2 arg)\",'datediff2arg',\n\t   \"DATEDIFF(make_date(2002,12,04),make_date(2002,12,01))\",'3',0],\n\t  [\"WEEKOFYEAR\",'weekofyear',\n\t   \"WEEKOFYEAR(make_date(1963,08,16))\",'33',0],\n# table crash_me_d must contain  record with 1963-08-16 (for CHAR)\n\t  [\"CHAR (conversation date)\",'char_date',\n\t   \"CHAR(a,EUR)\",'16.08.1963',0],\n\t  [\"MAKEDATE\",'makedate',\"MAKEDATE(1963,228)\"\n\t   ,'make_date_r(1963,08,16)',0],\n\t  [\"TO_DAYS\",\"to_days\",\n\t   \"to_days(make_date(1996,01,01))\",729024,0],\n\t  [\"ADD_MONTHS\",\"add_months\",\n\t   \"add_months(make_date(1997,01,01),1)\",\"make_date_r(1997,02,01)\",0], \n\t      # oracle the date plus n months\n\t  [\"LAST_DAY\",\"last_day\",\n\t  \"last_day(make_date(1997,04,01))\",\"make_date_r(1997,04,30)\",0], \n\t      # oracle last day of month of date\n\t  [\"DATE\",'date',\"date(make_date(1963,8,16))\",\n\t     'make_date_r(1963,8,16)',0],\n\t  [\"DAY\",'day',\"DAY(make_date(2002,12,01))\",1,0]))\n    {\n\t$prompt='Function '.$fn->[0];\n\t$key='func_extra_'.$fn->[1];\n\tmy $qry=\"select \".$fn->[2].\" from crash_me_d\";\n\twhile( $qry =~ /^(.*)make_date\\((\\d+),(\\d+),(\\d+)\\)(.*)$/)\n\t{\n\t    my $dt= &make_date($2,$3,$4);\n\t    $qry=$1.$dt.$5;\n\t};\n\tmy $result=$fn->[3];\n\twhile( $result =~ /^(.*)make_date_r\\((\\d+),(\\d+),(\\d+)\\)(.*)$/)\n\t{\n\t    my $dt= &make_date_r($2,$3,$4);\n\t    $result=$1.$dt.$5;\n\t};\n\tcheck_and_report($prompt,$key,\n\t\t\t [],$qry,[],\n\t\t\t $result,$fn->[4]\n\t\t\t );\n\t\n    }\n    \n    safe_query(\"drop table crash_me_d $drop_attr\");    \n    \n}\n\nif ($limits{'type_sql_time'} eq 'yes')\n{  # \n   # Checking the format of date in result. \n   \n    safe_query(\"drop table crash_me_t $drop_attr\");\n    assert(\"create table crash_me_t (a time)\");\n    # find the example of time\n    my $timeexample;\n    if ($limits{'func_sql_current_time'} eq 'yes') {\n     $timeexample='CURRENT_TIME';\n    } \n    elsif ($limits{'func_odbc_curtime'} eq 'yes') {\n     $timeexample='curtime()';\n    } \n    elsif ($limits{'func_sql_localtime'} eq 'yes') {\n\t$timeexample='localtime';\n    }\n    elsif ($limits{'func_odbc_now'} eq 'yes') {\n\t$timeexample='now()';\n    } else {\n\t#try to guess \n\t$timeexample=\"'02:55:12'\";\n    } ;\n    \n    my $key = 'time_format_inresult';\n    my $prompt = \"Time format in result\";\n    if (! safe_query_l('time_format_inresult',\n       \"insert into crash_me_t values($timeexample) \"))\n    { \n\tdie \"Cannot insert time ($timeexample):\".$last_error; \n    };\n    my $sth= $dbh->prepare(\"select a from crash_me_t\");\n    add_log('time_format_inresult',\"< select a from crash_me_t\");\n    $sth->execute;\n    $_= $sth->fetchrow_array;\n    add_log('time_format_inresult',\"> $_\");\n    safe_query_l($key,\"delete from crash_me_t\");   \n    if (/\\d{2}:\\d{2}:\\d{2}/){ save_config_data($key,\"iso\",$prompt);} \n    elsif (/\\d{2}\\.\\d{2}\\.\\d{2}/){ save_config_data($key,\"euro\",$prompt);}\n    elsif (/\\d{2}:\\d{2}\\s+(AM|PM)/i){ save_config_data($key,\"usa\",$prompt);}\n    elsif (/\\d{8}$/){ save_config_data($key,\"HHHHMMSS\",$prompt);}\n    elsif (/\\d{4}$/){ save_config_data($key,\"HHMMSS\",$prompt);}\n    else  { save_config_data($key,\"unknown\",$prompt);};\n    $sth->finish;\n\n    check_and_report(\"Supports HH:MM:SS (ISO) time format\",\"time_format_ISO\",\n\t\t     [ \"insert into crash_me_t(a)  values ('20:08:16')\"],\n\t\t     \"select a from crash_me_t\",\n\t\t     [\"delete from crash_me_t\"],\n\t\t     make_time_r(20,8,16),1);\n\n    check_and_report(\"Supports HH.MM.SS (EUR) time format\",\"time_format_EUR\",\n\t\t     [ \"insert into crash_me_t(a) values ('20.08.16')\"],\n\t\t     \"select a from crash_me_t\",\n\t\t     [\"delete from crash_me_t\"],\n\t\t     make_time_r(20,8,16),1);\n\n    check_and_report(\"Supports HHHHmmSS time format\",\n\t \"time_format_HHHHMMSS\",\n\t [ \"insert into crash_me_t(a) values ('00200816')\"],\n\t \"select a from crash_me_t\",\n\t [\"delete from crash_me_t\"],\n\t make_time_r(20,8,16),1);\n\n    check_and_report(\"Supports HHmmSS time format\",\n\t \"time_format_HHHHMMSS\",\n\t [ \"insert into crash_me_t(a) values ('200816')\"],\n\t \"select a from crash_me_t\",\n\t [\"delete from crash_me_t\"],\n\t make_time_r(20,8,16),1);\n\t \n    check_and_report(\"Supports HH:MM:SS (AM|PM) time format\",\n\t \"time_format_USA\",\n\t [ \"insert into crash_me_t(a) values ('08:08:16 PM')\"],\n\t \"select a from crash_me_t\",\n\t [\"delete from crash_me_t\"],\n\t make_time_r(20,8,16),1);\t \n    \n    my $insert_query ='insert into crash_me_t values('.\n        make_time(20,8,16).')';\n    safe_query($insert_query);\n    \n    foreach $fn ( (\n            [\"HOUR\",\"hour\",\"hour('\".make_time(12,13,14).\"')\",12,0],\n            [\"ANSI HOUR\",\"hour_time\",\"hour(TIME '\".make_time(12,13,14).\"')\",12,0],\n            [\"MINUTE\",\"minute\",\"minute('\".make_time(12,13,14).\"')\",13,0],\n            [\"SECOND\",\"second\",\"second('\".make_time(12,13,14).\"')\",14,0]\n\n    ))\n    {\n\t$prompt='Function '.$fn->[0];\n\t$key='func_odbc_'.$fn->[1];\n\tadd_log($key,\"< \".$insert_query);\n\tcheck_and_report($prompt,$key,\n\t\t\t [],\"select \".$fn->[2].\" $end_query\",[],\n\t\t\t $fn->[3],$fn->[4]\n\t\t\t );\n\t\n    };\n#    safe_query(['delete from crash_me_t', \n#\t\t'insert into crash_me_t values('.make_time(20,8,16).')']);\n    foreach $fn ((\n         [\"TIME_TO_SEC\",\"time_to_sec\",\"time_to_sec('\".\n\t          make_time(1,23,21).\"')\",\"5001\",0],\n         [\"SEC_TO_TIME\",\"sec_to_time\",\"sec_to_time(5001)\",\n\t      make_time_r(01,23,21),1],\n         [\"ADDTIME\",'addtime',\"ADDTIME('\".make_time(20,2,12).\n\t    \"','\".make_time(0,0,3).\"')\",make_time_r(20,2,15),0],\n         [\"SUBTIME\",'subtime',\"SUBTIME('\".make_time(20,2,15)\n\t          .\"','\".make_time(0,0,3).\"')\",make_time_r(20,2,12),0],\n         [\"TIMEDIFF\",'timediff',\"TIMEDIFF('\".make_time(20,2,15).\"','\".\n\t make_time(20,2,12).\"')\",make_time_r(0,0,3),0],\n         [\"MAKETIME\",'maketime',\"MAKETIME(20,02,12)\",make_time_r(20,2,12),0],\n         [\"TIME\",'time',\"time('\".make_time(20,2,12).\"')\",make_time_r(20,2,12),0]\n    ))\n    {\n\t$prompt='Function '.$fn->[0];\n\t$key='func_extra_'.$fn->[1];\n\tmy $qry=\"select \".$fn->[2].\" $end_query\";\n\tmy $result=$fn->[3];\n\tcheck_and_report($prompt,$key,\n\t\t\t [],$qry,[],\n\t\t\t $result,$fn->[4]\n\t\t\t );\n\t\n    }\n    \n    safe_query(\"drop table crash_me_t $drop_attr\");    \n    \n}\n\n\n# NOT id BETWEEN a and b\nif ($limits{'func_where_not_between'} eq 'yes')\n{\n   my $result = 'error';\n   my $err;\n   my $key='not_id_between';\n   my $prompt='NOT ID BETWEEN interprets as ID NOT BETWEEN';\n   print \"$prompt:\";\n   save_incomplete($key,$prompt);\n   safe_query_l($key,[\"create table crash_me_b (i int)\",\n         \"insert into crash_me_b values(2)\",\n         \"insert into crash_me_b values(5)\"]);\n   $err =safe_query_result_l($key,\n    \"select i from crash_me_b where not i between 1 and 3\",\n     5,0);\n   if ($err eq 1) {\n      if (not defined($last_result)) {\n        $result='no';\n      };\n   };\n   if ( $err eq 0) {\n      $result = 'yes';\n   };\n   safe_query_l($key,[\"drop table crash_me_b\"]);\n   save_config_data($key,$result,$prompt);\n   print \"$result\\n\";\n};\n\n\n\n\nreport(\"LIKE on numbers\",\"like_with_number\",\n       \"create table crash_q (a int,b int)\",\n       \"insert into crash_q values(10,10)\",\n       \"select * from crash_q where a like '10'\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"column LIKE column\",\"like_with_column\",\n       \"create table crash_q (a char(10),b char(10))\",\n       \"insert into crash_q values('abc','abc')\",\n       \"select * from crash_q where a like b\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"update of column= -column\",\"NEG\",\n       \"create table crash_q (a integer)\",\n       \"insert into crash_q values(10)\",\n       \"update crash_q set a=-a\",\n       \"drop table crash_q $drop_attr\");\n\nif ($limits{'func_odbc_left'} eq 'yes' ||\n    $limits{'func_odbc_substring'} eq 'yes')\n{\n  my $type= ($limits{'func_odbc_left'} eq 'yes' ?\n\t     \"left(a,4)\" : \"substring(a for 4)\");\n\n    check_and_report(\"String functions on date columns\",\"date_as_string\",\n\t\t     [\"create table crash_me2 (a date not null)\",\n\t\t      \"insert into crash_me2 values ('1998-03-03')\"],\n\t\t     \"select $type from crash_me2\",\n\t\t     [\"drop table crash_me2 $drop_attr\"],\n\t\t     \"1998\",1);\n}\n\n\n$tmp=sql_concat(\"b\",\"b\");\nif (defined($tmp))\n{\n  check_and_report(\"char are space filled\",\"char_is_space_filled\",\n\t\t   [],\"select $tmp from crash_me where b = 'a         '\",[],\n\t\t   'a         a         ',6);\n}\n\nif (!defined($limits{'multi_table_update'}))\n{\n  if (check_and_report(\"Update with many tables\",\"multi_table_update\",\n\t   [\"create table crash_q (a integer,b char(10))\",\n\t    \"insert into crash_q values(1,'c')\",\n\t    \"update crash_q left join crash_me on crash_q.a=crash_me.a set crash_q.b=crash_me.b\"],\n            \"select b from crash_q\",\n\t   [\"drop table crash_q $drop_attr\"],\n\t   \"a\",1,undef(),2))\n  {\n    check_and_report(\"Update with many tables\",\"multi_table_update\",\n\t     [\"create table crash_q (a integer,b char(10))\",\n\t      \"insert into crash_q values(1,'c')\",\n\t      \"update crash_q,crash_me set crash_q.b=crash_me.b \".\n\t      \"where crash_q.a=crash_me.a\"],\n\t     \"select b from crash_q\",\n\t     [\"drop table crash_q $drop_attr\"],\n\t\t     \"a\",1,\n\t\t    1);\n  }\n}\n\nreport(\"DELETE FROM table1,table2...\",\"multi_table_delete\",\n       \"create table crash_q (a integer,b char(10))\",\n       \"insert into crash_q values(1,'c')\",\n       \"delete crash_q.* from crash_q,crash_me where crash_q.a=crash_me.a\",\n       \"drop table crash_q $drop_attr\");\n\ncheck_and_report(\"Update with sub select\",\"select_table_update\",\n\t\t [\"create table crash_q (a integer,b char(10))\",\n\t\t  \"insert into crash_q values(1,'c')\",\n\t\t  \"update crash_q set b= \".\n\t\t  \"(select b from crash_me where crash_q.a = crash_me.a)\"],\n\t\t \"select b from crash_q\",\n\t\t [\"drop table crash_q $drop_attr\"],\n\t\t \"a\",1);\n\ncheck_and_report(\"Calculate 1--1\",\"minus_neg\",[],\n\t\t \"select a--1 from crash_me\",[],0,2);\n\nreport(\"ANSI SQL simple joins\",\"simple_joins\",\n       \"select crash_me.a from crash_me, crash_me t0\");\n\n#\n# Check max string size, and expression limits\n#\n$found=undef;\nforeach $type (('mediumtext','text','text()','blob','long'))\n{\n  if ($limits{\"type_extra_$type\"} eq 'yes')\n  {\n    $found=$type;\n    last;\n  }\n}\nif (defined($found))\n{\n  $found =~ s/\\(\\)/\\(%d\\)/;\n  find_limit(\"max text or blob size\",\"max_text_size\",\n\t     new query_many([\"create table crash_q (q $found)\",\n\t\t\t     \"insert into crash_q values ('%s')\"],\n\t\t\t    \"select * from crash_q\",\"%s\",\n\t\t\t    [\"drop table crash_q $drop_attr\"],\n\t\t\t    min($max_string_size,$limits{'query_size'}-30)));\n\n}\n\n# It doesn't make lots of sense to check for string lengths much bigger than\n# what can be stored...\n\nfind_limit(($prompt=\"constant string size in where\"),\"where_string_size\",\n\t   new query_repeat([],\"select a from crash_me where b >='\",\n\t\t\t    \"\",\"\",\"1\",\"\",\"'\"));\nif ($limits{'where_string_size'} == 10)\n{\n  save_config_data('where_string_size','nonstandard',$prompt);\n}\n\nif ($limits{'select_constants'} eq 'yes')\n{\n  find_limit(\"constant string size in SELECT\",\"select_string_size\",\n\t     new query_repeat([],\"select '\",\"\",\"\",\"a\",\"\",\"'$end_query\"));\n}\n\ngoto no_functions if ($limits{'functions'} ne \"yes\");\n\nif ($limits{'func_odbc_repeat'} eq 'yes')\n{\n  find_limit(\"return string size from function\",\"repeat_string_size\",\n\t     new query_many([],\n\t\t\t    \"select repeat('a',%d) $end_query\",\"%s\",\n\t\t\t    [],\n\t\t\t    $max_string_size,0));\n}\n\n$tmp=find_limit(\"simple expressions\",\"max_expressions\",\n\t\tnew query_repeat([],\"select 1\",\"\",\"\",\"+1\",\"\",$end_query,\n\t\t\t\t undef(),$max_expressions));\n\nif ($tmp > 10)\n{\n  $tmp= \"(1\" . ( '+1' x ($tmp-10) ) . \")\";\n  find_limit(\"big expressions\", \"max_big_expressions\",\n\t     new query_repeat([],\"select 0\",\"\",\"\",\"+$tmp\",\"\",$end_query,\n\t\t\t      undef(),$max_big_expressions));\n}\n\nfind_limit(\"stacked expressions\", \"max_stack_expression\",\n\t   new query_repeat([],\"select 1\",\"\",\"\",\"+(1\",\")\",$end_query,\n\t\t\t\tundef(),$max_stacked_expressions));\n\nno_functions:\n\nif (!defined($limits{'max_conditions'}))\n{\n  find_limit(\"OR and AND in WHERE\",\"max_conditions\",\n\t     new query_repeat([],\n\t\t\t      \"select a from crash_me where a=1 and b='a'\",\"\",\n\t\t\t      \"\", \" or a=%d and b='%d'\",\"\",\"\",\"\",\n\t\t\t      [],($query_size-42)/29,undef,2));\n  $limits{'max_conditions'}*=2;\n}\n# The 42 is the length of the constant part.\n# The 29 is the length of the variable part, plus two seven-digit numbers.\n\nfind_limit(\"tables in join\", \"join_tables\",\n\t   new query_repeat([],\n\t\t\t    \"select crash_me.a\",\",t%d.a\",\"from crash_me\",\n\t\t\t    \",crash_me t%d\",\"\",\"\",[],$max_join_tables,undef,\n\t\t\t    1));\n\n# Different CREATE TABLE options\n\nreport(\"primary key in create table\",'primary_key_in_create',\n       \"create table crash_q (q integer not null,primary key (q))\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"unique in create table\",'unique_in_create',\n       \"create table crash_q (q integer not null,unique (q))\",\n       \"drop table crash_q $drop_attr\");\n\nif ($limits{'unique_in_create'} eq 'yes')\n{\n  report(\"unique null in create\",'unique_null_in_create',\n\t \"create table crash_q (q integer,unique (q))\",\n\t \"insert into crash_q (q) values (NULL)\",\n\t \"insert into crash_q (q) values (NULL)\",\n\t \"insert into crash_q (q) values (1)\",\n\t \"drop table crash_q $drop_attr\");\n}\n\nreport(\"default value for column\",'create_default',\n       \"create table crash_q (q integer default 10 not null)\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"default value function for column\",'create_default_func',\n       \"create table crash_q (q integer not null,q1 integer default (1+1))\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"temporary tables\",'temporary_table',\n       \"create temporary table crash_q (q integer not null)\",\n       \"drop table crash_q $drop_attr\");\n\nreport_one(\"create table from select\",'create_table_select',\n\t   [[\"create table crash_q SELECT * from crash_me\",\"yes\"],\n\t    [\"create table crash_q AS SELECT * from crash_me\",\"with AS\"]]);\n$dbh->do(\"drop table crash_q $drop_attr\");\n\nreport(\"index in create table\",'index_in_create',\n       \"create table crash_q (q integer not null,index (q))\",\n       \"drop table crash_q $drop_attr\");\n\n# The following must be executed as we need the value of end_drop_keyword\n# later\nif (!(defined($limits{'create_index'}) && defined($limits{'drop_index'})))\n{\n  if ($res=safe_query_l('create_index',\"create index crash_q on crash_me (a)\"))\n  {\n    $res=\"yes\";\n    $drop_res=\"yes\";\n    $end_drop_keyword=\"\";\n    if (!safe_query_l('drop_index',\"drop index crash_q\"))\n    {\n      # Can't drop the standard way; Check if mSQL\n      if (safe_query_l('drop_index',\"drop index crash_q from crash_me\"))\n      {\n        $drop_res=\"with 'FROM'\";\t# Drop is not ANSI SQL\n        $end_drop_keyword=\"drop index %i from %t\";\n      }\n      # else check if Access or MySQL\n      elsif (safe_query_l('drop_index',\"drop index crash_q on crash_me\"))\n      {\n        $drop_res=\"with 'ON'\";\t# Drop is not ANSI SQL\n        $end_drop_keyword=\"drop index %i on %t\";\n      }\n      # else check if MS-SQL\n      elsif (safe_query_l('drop_index',\"drop index crash_me.crash_q\"))\n      {\n        $drop_res=\"with 'table.index'\"; # Drop is not ANSI SQL\n        $end_drop_keyword=\"drop index %t.%i\";\n      }\n    }\n    else\n    {\n      # Old MySQL 3.21 supports only the create index syntax\n      # This means that the second create doesn't give an error.\n      $res=safe_query_l('create_index',[\"create index crash_q on crash_me (a)\",\n      \t\t     \"create index crash_q on crash_me (a)\",\n      \t\t     \"drop index crash_q\"]);\n      $res= $res ? 'ignored' : 'yes';\n    }\n  }\n  else\n  {\n    $drop_res=$res='no';\n  }\n  save_config_data('create_index',$res,\"create index\");\n  save_config_data('drop_index',$drop_res,\"drop index\");\n\n  print \"create index: $limits{'create_index'}\\n\";\n  print \"drop index: $limits{'drop_index'}\\n\";\n}\n\n# check if we can have 'NULL' as a key\ncheck_and_report(\"null in index\",\"null_in_index\",\n\t\t [create_table(\"crash_q\",[\"a char(10)\"],[\"(a)\"]),\n\t\t  \"insert into crash_q values (NULL)\"],\n\t\t \"select * from crash_q\",\n\t\t [\"drop table crash_q $drop_attr\"],\n\t\t undef(),4);\n\nif ($limits{'unique_in_create'} eq 'yes')\n{\n  report(\"null in unique index\",'null_in_unique',\n          create_table(\"crash_q\",[\"q integer\"],[\"unique(q)\"]),\n\t \"insert into crash_q (q) values(NULL)\",\n\t \"insert into crash_q (q) values(NULL)\",\n\t \"drop table crash_q $drop_attr\");\n  report(\"null combination in unique index\",'nulls_in_unique',\n          create_table(\"crash_q\",[\"q integer,q1 integer\"],[\"unique(q,q1)\"]),\n\t \"insert into crash_q (q,q1) values(1,NULL)\",\n\t \"insert into crash_q (q,q1) values(1,NULL)\",\n\t \"drop table crash_q $drop_attr\");\n}\n\nif ($limits{'null_in_unique'} eq 'yes')\n{\n  report(\"null in unique index\",'multi_null_in_unique',\n          create_table(\"crash_q\",[\"q integer, x integer\"],[\"unique(q)\"]),\n\t \"insert into crash_q(x) values(1)\",\n\t \"insert into crash_q(x) values(2)\",\n\t \"drop table crash_q $drop_attr\");\n}\n\nif ($limits{'create_index'} ne 'no')\n{\n  $end_drop=$end_drop_keyword;\n  $end_drop =~ s/%i/crash_q/;\n  $end_drop =~ s/%t/crash_me/;\n  report(\"index on column part (extension)\",\"index_parts\",,\n\t \"create index crash_q on crash_me (b(5))\",\n\t $end_drop);\n  $end_drop=$end_drop_keyword;\n  $end_drop =~ s/%i/crash_me/;\n  $end_drop =~ s/%t/crash_me/;\n  report(\"different namespace for index\",\n\t \"index_namespace\",\n\t \"create index crash_me on crash_me (b)\",\n\t $end_drop);\n}\n\nif (!report(\"case independent table names\",\"table_name_case\",\n\t    \"create table crash_q (q integer)\",\n\t    \"drop table CRASH_Q $drop_attr\"))\n{\n  safe_query(\"drop table crash_q $drop_attr\");\n}\n\nif (!report(\"case independent field names\",\"field_name_case\",\n\t    \"create table crash_q (q integer)\",\n\t    \"insert into crash_q(Q) values (1)\",\n\t    \"drop table crash_q $drop_attr\"))\n{\n  safe_query(\"drop table crash_q $drop_attr\");\n}\n\nif (!report(\"drop table if exists\",\"drop_if_exists\",\n\t    \"create table crash_q (q integer)\",\n\t    \"drop table if exists crash_q $drop_attr\"))\n{\n  safe_query(\"drop table crash_q $drop_attr\");\n}\n\nreport(\"create table if not exists\",\"create_if_not_exists\",\n       \"create table crash_q (q integer)\",\n       \"create table if not exists crash_q (q integer)\");\nsafe_query(\"drop table crash_q $drop_attr\");\n\n#\n# test of different join types\n#\n\nassert(\"create table crash_me2 (a integer not null,b char(10) not null,\".\n       \" c1 integer)\");\nassert(\"insert into crash_me2 (a,b,c1) values (1,'b',1)\");\nassert(\"create table crash_me3 (a integer not null,b char(10) not null)\");\nassert(\"insert into crash_me3 (a,b) values (1,'b')\");\n\nreport(\"inner join\",\"inner_join\",\n       \"select crash_me.a from crash_me inner join crash_me2 ON \".\n       \"crash_me.a=crash_me2.a\");\nreport(\"left outer join\",\"left_outer_join\",\n       \"select crash_me.a from crash_me left join crash_me2 ON \".\n       \"crash_me.a=crash_me2.a\");\nreport(\"natural left outer join\",\"natural_left_outer_join\",\n       \"select c1 from crash_me natural left join crash_me2\");\nreport(\"left outer join using\",\"left_outer_join_using\",\n       \"select c1 from crash_me left join crash_me2 using (a)\");\nreport(\"left outer join odbc style\",\"odbc_left_outer_join\",\n       \"select crash_me.a from { oj crash_me left outer join crash_me2 ON\".\n       \" crash_me.a=crash_me2.a }\");\nreport(\"right outer join\",\"right_outer_join\",\n       \"select crash_me.a from crash_me right join crash_me2 ON \".\n       \"crash_me.a=crash_me2.a\");\nreport(\"full outer join\",\"full_outer_join\",\n       \"select crash_me.a from crash_me full join crash_me2 ON \".\"\n       crash_me.a=crash_me2.a\");\nreport(\"cross join (same as from a,b)\",\"cross_join\",\n       \"select crash_me.a from crash_me cross join crash_me3\");\nreport(\"natural join\",\"natural_join\",\n       \"select * from crash_me natural join crash_me3\");\nreport(\"union\",\"union\",\n       \"select * from crash_me union select a,b from crash_me3\");\nreport(\"union all\",\"union_all\",\n       \"select * from crash_me union all select a,b from crash_me3\");\nreport(\"intersect\",\"intersect\",\n       \"select * from crash_me intersect select * from crash_me3\");\nreport(\"intersect all\",\"intersect_all\",\n       \"select * from crash_me intersect all select * from crash_me3\");\nreport(\"except\",\"except\",\n       \"select * from crash_me except select * from crash_me3\");\nreport(\"except all\",\"except_all\",\n       \"select * from crash_me except all select * from crash_me3\");\nreport(\"except\",\"except\",\n       \"select * from crash_me except select * from crash_me3\");\nreport(\"except all\",\"except_all\",\n       \"select * from crash_me except all select * from crash_me3\");\nreport(\"minus\",\"minus\",\n       \"select * from crash_me minus select * from crash_me3\"); # oracle ...\n\nreport(\"natural join (incompatible lists)\",\"natural_join_incompat\",\n       \"select c1 from crash_me natural join crash_me2\");\nreport(\"union (incompatible lists)\",\"union_incompat\",\n       \"select * from crash_me union select a,b from crash_me2\");\nreport(\"union all (incompatible lists)\",\"union_all_incompat\",\n       \"select * from crash_me union all select a,b from crash_me2\");\nreport(\"intersect (incompatible lists)\",\"intersect_incompat\",\n       \"select * from crash_me intersect select * from crash_me2\");\nreport(\"intersect all (incompatible lists)\",\"intersect_all_incompat\",\n       \"select * from crash_me intersect all select * from crash_me2\");\nreport(\"except (incompatible lists)\",\"except_incompat\",\n       \"select * from crash_me except select * from crash_me2\");\nreport(\"except all (incompatible lists)\",\"except_all_incompat\",\n       \"select * from crash_me except all select * from crash_me2\");\nreport(\"except (incompatible lists)\",\"except_incompat\",\n       \"select * from crash_me except select * from crash_me2\");\nreport(\"except all (incompatible lists)\",\"except_all_incompat\",\n       \"select * from crash_me except all select * from crash_me2\");\nreport(\"minus (incompatible lists)\",\"minus_incompat\",\n       \"select * from crash_me minus select * from crash_me2\"); # oracle ...\n\nassert(\"drop table crash_me2 $drop_attr\");\nassert(\"drop table crash_me3 $drop_attr\");\n\n# somethings to be added here ....\n# FOR UNION - INTERSECT - EXCEPT -> CORRESPONDING [ BY ]\n# after subqueries:\n# >ALL | ANY | SOME - EXISTS - UNIQUE\n\nif (report(\"subqueries\",\"subqueries\",\n\t   \"select a from crash_me where crash_me.a in \".\n\t   \"(select max(a) from crash_me)\"))\n{\n    $tmp=new query_repeat([],\"select a from crash_me\",\"\",\"\",\n\t\t\t  \" where a in (select a from crash_me\",\")\",\n\t\t\t  \"\",[],$max_join_tables);\n    find_limit(\"recursive subqueries\", \"recursive_subqueries\",$tmp);\n}\n\nreport(\"insert INTO ... SELECT ...\",\"insert_select\",\n       \"create table crash_q (a int)\",\n       \"insert into crash_q (a) SELECT crash_me.a from crash_me\",\n       \"drop table crash_q $drop_attr\");\n\nif (!defined($limits{\"transactions\"}))\n{\n  my ($limit,$type);\n  $limit=\"transactions\";\n  $limit_r=\"rollback_metadata\";\n  print \"$limit: \";\n  foreach $type (('', 'type=bdb', 'type=innodb', 'type=gemini'))\n  {\n    undef($limits{$limit});\n    if (!report_trans($limit,\n\t\t\t   [create_table(\"crash_q\",[\"a integer not null\"],[],\n\t\t\t\t\t $type),\n\t\t\t    \"insert into crash_q values (1)\"],\n\t\t\t   \"select * from crash_q\",\n\t\t\t   \"drop table crash_q $drop_attr\"\n\t\t\t  ))\n     {\n       report_rollback($limit_r,\n              [create_table(\"crash_q\",[\"a integer not null\"],[],\n\t\t\t\t $type)],\n\t\t\t    \"insert into crash_q values (1)\",\n\t\t\t   \"drop table crash_q $drop_attr\" );\n     last;\n     };\n  }\n  print \"$limits{$limit}\\n\";\n  print \"$limit_r: $limits{$limit_r}\\n\";\n}\n\nreport(\"atomic updates\",\"atomic_updates\",\n       create_table(\"crash_q\",[\"a integer not null\"],[\"primary key (a)\"]),\n       \"insert into crash_q values (2)\",\n       \"insert into crash_q values (3)\",\n       \"insert into crash_q values (1)\",\n       \"update crash_q set a=a+1\",\n       \"drop table crash_q $drop_attr\");\n\nif ($limits{'atomic_updates'} eq 'yes')\n{\n  report_fail(\"atomic_updates_with_rollback\",\"atomic_updates_with_rollback\",\n\t      create_table(\"crash_q\",[\"a integer not null\"],\n\t\t\t   [\"primary key (a)\"]),\n\t      \"insert into crash_q values (2)\",\n\t      \"insert into crash_q values (3)\",\n\t      \"insert into crash_q values (1)\",\n\t      \"update crash_q set a=a+1 where a < 3\",\n\t      \"drop table crash_q $drop_attr\");\n}\n\n# To add with the views:\n# DROP VIEW - CREAT VIEW *** [ WITH [ CASCADE | LOCAL ] CHECK OPTION ]\nreport(\"views\",\"views\",\n       \"create view crash_q as select a from crash_me\",\n       \"drop view crash_q $drop_attr\");\n\n#  Test: foreign key\n{\n my $result = 'undefined';\n my $error;\n print \"foreign keys: \";\n save_incomplete('foreign_key','foreign keys');\n\n# 1) check if foreign keys are supported\n safe_query_l('foreign_key',\n\t      create_table(\"crash_me_qf\",\n\t\t\t   [\"a integer not null\"],\n\t\t\t   [\"primary key (a)\"]));\n $error= safe_query_l('foreign_key',\n\t\t      create_table(\"crash_me_qf2\",\n\t\t\t\t   [\"a integer not null\",\n\t\t\t\t    \"foreign key (a) references crash_me_qf (a)\"],\n\t\t\t\t   []));\n\n if ($error == 1)         # OK  -- syntax is supported \n {\n   $result = 'error';\n   # now check if foreign key really works\n   safe_query_l('foreign_key', \"insert into crash_me_qf values (1)\");\n   if (safe_query_l('foreign_key', \"insert into crash_me_qf2 values (2)\") eq 1)\n   {\n     $result = 'syntax only';\n   }\n   else\n   {\n     $result = 'yes';\n   }\n }\n else\n {\n   $result = \"no\";\n }\n safe_query_l('foreign_key', \"drop table crash_me_qf2 $drop_attr\");\n safe_query_l('foreign_key', \"drop table crash_me_qf $drop_attr\");\n print \"$result\\n\";\n save_config_data('foreign_key',$result,\"foreign keys\");\n}\n\nif ($limits{'foreign_key'} eq 'yes')\n{\n  report(\"allows to update of foreign key values\",'foreign_update',\n   \"create table crash_me1 (a int not null primary key)\",\n   \"create table crash_me2 (a int not null,\" .\n      \" foreign key (a) references crash_me1 (a))\",\n   \"insert into crash_me1 values (1)\",\n   \"insert into crash_me2 values (1)\",\n   \"update crash_me1 set a = 2\",       ## <- must fail \n   \"drop table crash_me2 $drop_attr\", \n   \"drop table crash_me1 $drop_attr\" \n  );\n}\n\nreport(\"Create SCHEMA\",\"create_schema\",\n       \"create schema crash_schema create table crash_q (a int) \".\n       \"create table crash_q2(b int)\",\n       \"drop schema crash_schema cascade\");\n\nif ($limits{'foreign_key'} eq 'yes')\n{\n  if ($limits{'create_schema'} eq 'yes')\n  {\n    report(\"Circular foreign keys\",\"foreign_key_circular\",\n           \"create schema crash_schema create table crash_q \".\n\t   \"(a int primary key, b int, foreign key (b) references \".\n\t   \"crash_q2(a)) create table crash_q2(a int, b int, \".\n\t   \"primary key(a), foreign key (b) references crash_q(a))\",\n           \"drop schema crash_schema cascade\");\n  }\n}\n\nif ($limits{'func_sql_character_length'} eq 'yes')\n{\n  my $result = 'error';\n  my ($resultset);\n  my $key = 'length_of_varchar_field';\n  my $prompt='CHARACTER_LENGTH(varchar_field)';\n  print $prompt,\" = \";\n  if (!defined($limits{$key})) {\n    save_incomplete($key,$prompt);\n    safe_query_l($key,[\n\t\t       \"CREATE TABLE crash_me1 (S1 VARCHAR(100))\",\n\t\t       \"INSERT INTO crash_me1 VALUES ('X')\"\n\t\t       ]);\n    my $recset = get_recordset($key,\n\t\t\t       \"SELECT CHARACTER_LENGTH(S1) FROM crash_me1\");\n    print_recordset($key,$recset);\n    if (defined($recset)){\n      if ( $recset->[0][0] eq 1 ) {\n\t\t$result = 'actual length';\n\t      } elsif( $recset->[0][0] eq 100 ) {\n\t\t$result = 'defined length';\n\t      };\n    } else {\n      add_log($key,$DBI::errstr);\n    }\n    safe_query_l($key, \"drop table crash_me1 $drop_attr\");\n    save_config_data($key,$result,$prompt);\n  } else {\n    $result = $limits{$key};\n  };\n  print \"$result\\n\";\n}\n\n\ncheck_constraint(\"Column constraints\",\"constraint_check\",\n           \"create table crash_q (a int check (a>0))\",\n           \"insert into crash_q values(0)\",\n           \"drop table crash_q $drop_attr\");\n\n\ncheck_constraint(\"Table constraints\",\"constraint_check_table\",\n       \"create table crash_q (a int ,b int, check (a>b))\",\n       \"insert into crash_q values(0,0)\",\n       \"drop table crash_q $drop_attr\");\n\ncheck_constraint(\"Named constraints\",\"constraint_check_named\",\n       \"create table crash_q (a int ,b int, constraint abc check (a>b))\",\n       \"insert into crash_q values(0,0)\",\n       \"drop table crash_q $drop_attr\");\n\n\nreport(\"NULL constraint (SyBase style)\",\"constraint_null\",\n       \"create table crash_q (a int null)\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"Triggers (ANSI SQL)\",\"psm_trigger\",\n       \"create table crash_q (a int ,b int)\",\n       \"create trigger crash_trigger after insert on crash_q referencing \".\n       \"new table as new_a when (localtime > time '18:00:00') \".\n       \"begin atomic end\",\n       \"insert into crash_q values(1,2)\",\n       \"drop trigger crash_trigger\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"PSM procedures (ANSI SQL)\",\"psm_procedures\",\n       \"create table crash_q (a int,b int)\",\n       \"create procedure crash_proc(in a1 int, in b1 int) language \".\n       \"sql modifies sql data begin declare c1 int; set c1 = a1 + b1;\".\n       \" insert into crash_q(a,b) values (a1,c1); end\",\n       \"call crash_proc(1,10)\",\n       \"drop procedure crash_proc\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"PSM modules (ANSI SQL)\",\"psm_modules\",\n       \"create table crash_q (a int,b int)\",\n       \"create module crash_m declare procedure \".\n         \"crash_proc(in a1 int, in b1 int) language sql modifies sql \".\n         \"data begin declare c1 int; set c1 = a1 + b1; \".\n         \"insert into crash_q(a,b) values (a1,c1); end; \".\n         \"declare procedure crash_proc2(INOUT a int, in b int) \".\n         \"contains sql set a = b + 10; end module\",\n       \"call crash_proc(1,10)\",\n       \"drop module crash_m cascade\",\n       \"drop table crash_q cascade $drop_attr\");\n\nreport(\"PSM functions (ANSI SQL)\",\"psm_functions\",\n       \"create table crash_q (a int)\",\n       \"create function crash_func(in a1 int, in b1 int) returns int\".\n         \" language sql deterministic contains sql \".\n\t \" begin return a1 * b1; end\",\n       \"insert into crash_q values(crash_func(2,4))\",\n       \"select a,crash_func(a,2) from crash_q\",\n       \"drop function crash_func cascade\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"Domains (ANSI SQL)\",\"domains\",\n       \"create domain crash_d as varchar(10) default 'Empty' \".\n         \"check (value <> 'abcd')\",\n       \"create table crash_q(a crash_d, b int)\",\n       \"insert into crash_q(a,b) values('xyz',10)\",\n       \"insert into crash_q(b) values(10)\",\n       \"drop table crash_q $drop_attr\",\n       \"drop domain crash_d\");\n\n\nif (!defined($limits{'lock_tables'}))\n{\n  report(\"lock table\",\"lock_tables\",\n\t \"lock table crash_me READ\",\n\t \"unlock tables\");\n  if ($limits{'lock_tables'} eq 'no')\n  {\n    delete $limits{'lock_tables'};\n    report(\"lock table\",\"lock_tables\",\n\t   \"lock table crash_me IN SHARE MODE\");\n  }\n}\n\nif (!report(\"many tables to drop table\",\"multi_drop\",\n\t   \"create table crash_q (a int)\",\n\t   \"create table crash_q2 (a int)\",\n\t   \"drop table crash_q,crash_q2 $drop_attr\"))\n{\n  $dbh->do(\"drop table crash_q $drop_attr\");\n  $dbh->do(\"drop table crash_q2 $drop_attr\");\n}\n\nif (!report(\"drop table with cascade/restrict\",\"drop_restrict\",\n\t   \"create table crash_q (a int)\",\n\t   \"drop table crash_q restrict\"))\n{\n  $dbh->do(\"drop table crash_q $drop_attr\");\n}\n\n\nreport(\"-- as comment (ANSI)\",\"comment_--\",\n       \"select * from crash_me -- Testing of comments\");\nreport(\"// as comment\",\"comment_//\",\n       \"select * from crash_me // Testing of comments\");\nreport(\"# as comment\",\"comment_#\",\n       \"select * from crash_me # Testing of comments\");\nreport(\"/* */ as comment\",\"comment_/**/\",\n       \"select * from crash_me /* Testing of comments */\");\n\n#\n# Check things that fails one some servers\n#\n\n# Empress can't insert empty strings in a char() field\nreport(\"insert empty string\",\"insert_empty_string\",\n       create_table(\"crash_q\",[\"a char(10) not null,b char(10)\"],[]),\n       \"insert into crash_q values ('','')\",\n       \"drop table crash_q $drop_attr\");\n\nreport(\"Having with alias\",\"having_with_alias\",\n       create_table(\"crash_q\",[\"a integer\"],[]),\n       \"insert into crash_q values (10)\",\n       \"select sum(a) as b from crash_q group by a having b > 0\",\n       \"drop table crash_q $drop_attr\");\n\n#\n# test name limits\n#\n\nfind_limit(\"table name length\",\"max_table_name\",\n\t   new query_many([\"create table crash_q%s (q integer)\",\n\t\t\t   \"insert into crash_q%s values(1)\"],\n\t\t\t   \"select * from crash_q%s\",1,\n\t\t\t   [\"drop table crash_q%s $drop_attr\"],\n\t\t\t   $max_name_length,7,1));\n\nfind_limit(\"column name length\",\"max_column_name\",\n\t   new query_many([\"create table crash_q (q%s integer)\",\n\t\t\t  \"insert into crash_q (q%s) values(1)\"],\n\t\t\t  \"select q%s from crash_q\",1,\n\t\t\t  [\"drop table crash_q $drop_attr\"],\n\t\t\t   $max_name_length,1));\n\nif ($limits{'column_alias'} eq 'yes')\n{\n  find_limit(\"select alias name length\",\"max_select_alias_name\",\n\t   new query_many(undef,\n\t\t\t  \"select b as %s from crash_me\",undef,\n\t\t\t  undef, $max_name_length));\n}\n\nfind_limit(\"table alias name length\",\"max_table_alias_name\",\n\t   new query_many(undef,\n\t\t\t  \"select %s.b from crash_me %s\",\n\t\t\t  undef,\n\t\t\t  undef, $max_name_length));\n\n$end_drop_keyword = \"drop index %i\" if (!$end_drop_keyword);\n$end_drop=$end_drop_keyword;\n$end_drop =~ s/%i/crash_q%s/;\n$end_drop =~ s/%t/crash_me/;\n\nif ($limits{'create_index'} ne 'no')\n{\n  find_limit(\"index name length\",\"max_index_name\",\n\t     new query_many([\"create index crash_q%s on crash_me (a)\"],\n\t\t\t    undef,undef,\n\t\t\t    [$end_drop],\n\t\t\t    $max_name_length,7));\n}\n\nfind_limit(\"max char() size\",\"max_char_size\",\n\t   new query_many([\"create table crash_q (q char(%d))\",\n\t\t\t   \"insert into crash_q values ('%s')\"],\n\t\t\t  \"select * from crash_q\",\"%s\",\n\t\t\t  [\"drop table crash_q $drop_attr\"],\n\t\t\t  min($max_string_size,$limits{'query_size'})));\n\nif ($limits{'type_sql_varchar(1_arg)'} eq 'yes')\n{\n  find_limit(\"max varchar() size\",\"max_varchar_size\",\n\t     new query_many([\"create table crash_q (q varchar(%d))\",\n\t\t\t     \"insert into crash_q values ('%s')\"],\n\t\t\t    \"select * from crash_q\",\"%s\",\n\t\t\t    [\"drop table crash_q $drop_attr\"],\n\t\t\t    min($max_string_size,$limits{'query_size'})));\n}\n\n$found=undef;\nforeach $type (('mediumtext','text','text()','blob','long'))\n{\n  if ($limits{\"type_extra_$type\"} eq 'yes')\n  {\n    $found=$type;\n    last;\n  }\n}\nif (defined($found))\n{\n  $found =~ s/\\(\\)/\\(%d\\)/;\n  find_limit(\"max text or blob size\",\"max_text_size\",\n\t     new query_many([\"create table crash_q (q $found)\",\n\t\t\t     \"insert into crash_q values ('%s')\"],\n\t\t\t    \"select * from crash_q\",\"%s\",\n\t\t\t    [\"drop table crash_q $drop_attr\"],\n\t\t\t    min($max_string_size,$limits{'query_size'}-30)));\n\n}\n\n$tmp=new query_repeat([],\"create table crash_q (a integer\",\"\",\"\",\n\t\t      \",a%d integer\",\"\",\")\",[\"drop table crash_q $drop_attr\"],\n\t\t      $max_columns);\n$tmp->{'offset'}=1;\nfind_limit(\"Columns in table\",\"max_columns\",$tmp);\n\n# Make a field definition to be used when testing keys\n\n$key_definitions=\"q0 integer not null\";\n$key_fields=\"q0\";\nfor ($i=1; $i < min($limits{'max_columns'},$max_keys) ; $i++)\n{\n  $key_definitions.=\",q$i integer not null\";\n  $key_fields.=\",q$i\";\n}\n$key_values=\"1,\" x $i;\nchop($key_values);\n\nif ($limits{'unique_in_create'} eq 'yes')\n{\n  find_limit(\"unique indexes\",\"max_unique_index\",\n\t     new query_table(\"create table crash_q (q integer\",\n\t\t\t     \",q%d integer not null,unique (q%d)\",\")\",\n\t\t\t     [\"insert into crash_q (q,%f) values (1,%v)\"],\n\t\t\t     \"select q from crash_q\",1,\n\t\t\t     \"drop table crash_q $drop_attr\",\n\t\t\t     $max_keys,0));\n\n  find_limit(\"index parts\",\"max_index_parts\",\n\t     new query_table(\"create table crash_q \".\n\t         \"($key_definitions,unique (q0\",\n\t\t\t     \",q%d\",\"))\",\n \t     [\"insert into crash_q ($key_fields) values ($key_values)\"],\n\t     \"select q0 from crash_q\",1,\n\t     \"drop table crash_q $drop_attr\",\n\t     $max_keys,1));\n\n  find_limit(\"max index part length\",\"max_index_part_length\",\n\t     new query_many([\"create table crash_q (q char(%d) not null,\".\n\t           \"unique(q))\",\n\t\t     \"insert into crash_q (q) values ('%s')\"],\n\t\t    \"select q from crash_q\",\"%s\",\n\t\t    [\"drop table crash_q $drop_attr\"],\n\t\t    $limits{'max_char_size'},0));\n\n  if ($limits{'type_sql_varchar(1_arg)'} eq 'yes')\n  {\n    find_limit(\"index varchar part length\",\"max_index_varchar_part_length\",\n\t     new query_many([\"create table crash_q (q varchar(%d) not null,\".\n\t                \"unique(q))\",\n\t\t\t \"insert into crash_q (q) values ('%s')\"],\n\t\t\t\"select q from crash_q\",\"%s\",\n\t\t\t[\"drop table crash_q $drop_attr\"],\n\t\t\t$limits{'max_varchar_size'},0));\n  }\n}\n\n\nif ($limits{'create_index'} ne 'no')\n{\n  if ($limits{'create_index'} eq 'ignored' ||\n      $limits{'unique_in_create'} eq 'yes')\n  {                                     # This should be true\n    add_log('max_index',\n     \" max_unique_index=$limits{'max_unique_index'} ,\".\n     \"so max_index must be same\");\n    save_config_data('max_index',$limits{'max_unique_index'},\"max index\");\n    print \"indexes: $limits{'max_index'}\\n\";\n  }\n  else\n  {\n    if (!defined($limits{'max_index'}))\n    {\n      safe_query_l('max_index',\"create table crash_q ($key_definitions)\");\n      for ($i=1; $i <= min($limits{'max_columns'},$max_keys) ; $i++)\n      {\n\tlast if (!safe_query_l('max_index',\n\t     \"create index crash_q$i on crash_q (q$i)\"));\n      }\n      save_config_data('max_index',$i == $max_keys ? $max_keys : $i,\n\t\t       \"max index\");\n      while ( --$i > 0)\n      {\n\t$end_drop=$end_drop_keyword;\n\t$end_drop =~ s/%i/crash_q$i/;\n\t$end_drop =~ s/%t/crash_q/;\n\tassert($end_drop);\n      }\n      assert(\"drop table crash_q $drop_attr\");\n    }\n    print \"indexs: $limits{'max_index'}\\n\";\n    if (!defined($limits{'max_unique_index'}))\n    {\n      safe_query_l('max_unique_index',\n           \"create table crash_q ($key_definitions)\");\n      for ($i=0; $i < min($limits{'max_columns'},$max_keys) ; $i++)\n      {\n\tlast if (!safe_query_l('max_unique_index',\n\t    \"create unique index crash_q$i on crash_q (q$i)\"));\n      }\n      save_config_data('max_unique_index',$i == $max_keys ? $max_keys : $i,\n\t\t       \"max unique index\");\n      while ( --$i >= 0)\n      {\n\t$end_drop=$end_drop_keyword;\n\t$end_drop =~ s/%i/crash_q$i/;\n\t$end_drop =~ s/%t/crash_q/;\n\tassert($end_drop);\n      }\n      assert(\"drop table crash_q $drop_attr\");\n    }\n    print \"unique indexes: $limits{'max_unique_index'}\\n\";\n    if (!defined($limits{'max_index_parts'}))\n    {\n      safe_query_l('max_index_parts',\n            \"create table crash_q ($key_definitions)\");\n      $end_drop=$end_drop_keyword;\n      $end_drop =~ s/%i/crash_q1%d/;\n      $end_drop =~ s/%t/crash_q/;\n      find_limit(\"index parts\",\"max_index_parts\",\n\t\t new query_table(\"create index crash_q1%d on crash_q (q0\",\n\t\t\t\t \",q%d\",\")\",\n\t\t\t\t [],\n\t\t\t\t undef,undef,\n\t\t\t\t $end_drop,\n\t\t\t\t $max_keys,1));\n      assert(\"drop table crash_q $drop_attr\");\n    }\n    else\n    {\n      print \"index parts: $limits{'max_index_parts'}\\n\";\n    }\n    $end_drop=$end_drop_keyword;\n    $end_drop =~ s/%i/crash_q2%d/;\n    $end_drop =~ s/%t/crash_me/;\n\n    find_limit(\"index part length\",\"max_index_part_length\",\n\t       new query_many([\"create table crash_q (q char(%d))\",\n\t\t\t       \"create index crash_q2%d on crash_q (q)\",\n\t\t\t       \"insert into crash_q values('%s')\"],\n\t\t\t      \"select q from crash_q\",\n\t\t\t      \"%s\",\n\t\t\t      [ $end_drop,\n\t\t\t       \"drop table crash_q $drop_attr\"],\n\t\t\t      min($limits{'max_char_size'},\"+8192\")));\n  }\n}\n\nfind_limit(\"index length\",\"max_index_length\",\n\t   new query_index_length(\"create table crash_q \",\n\t\t\t\t  \"drop table crash_q $drop_attr\",\n\t\t\t\t  $max_key_length));\n\nfind_limit(\"max table row length (without blobs)\",\"max_row_length\",\n\t   new query_row_length(\"crash_q \",\n\t\t\t\t\"not null\",\n\t\t\t\t\"drop table crash_q $drop_attr\",\n\t\t\t\tmin($max_row_length,\n\t\t\t\t    $limits{'max_columns'}*\n\t\t\t\t    min($limits{'max_char_size'},255))));\n\nfind_limit(\"table row length with nulls (without blobs)\",\n\t   \"max_row_length_with_null\",\n\t   new query_row_length(\"crash_q \",\n\t\t\t\t\"\",\n\t\t\t\t\"drop table crash_q $drop_attr\",\n\t\t\t\t$limits{'max_row_length'}*2));\n\nfind_limit(\"number of columns in order by\",\"columns_in_order_by\",\n\t   new query_many([\"create table crash_q (%F)\",\n\t\t\t   \"insert into crash_q values(%v)\",\n\t\t\t   \"insert into crash_q values(%v)\"],\n\t\t\t  \"select * from crash_q order by %f\",\n\t\t\t  undef(),\n\t\t\t  [\"drop table crash_q $drop_attr\"],\n\t\t\t  $max_order_by));\n\nfind_limit(\"number of columns in group by\",\"columns_in_group_by\",\n\t   new query_many([\"create table crash_q (%F)\",\n\t\t\t   \"insert into crash_q values(%v)\",\n\t\t\t   \"insert into crash_q values(%v)\"],\n\t\t\t  \"select %f from crash_q group by %f\",\n\t\t\t  undef(),\n\t\t\t  [\"drop table crash_q $drop_attr\"],\n\t\t\t  $max_order_by));\n\n\n\n# Safe arithmetic test\n\n$prompt=\"safe decimal arithmetic\";\n$key=\"safe_decimal_arithmetic\";\nif (!defined($limits{$key}))\n{\n   print \"$prompt=\";\n   save_incomplete($key,$prompt);\t\n   if (!safe_query_l($key,$server->create(\"crash_me_a\",\n         [\"a decimal(10,2)\",\"b decimal(10,2)\"]))) \n     {\n       print DBI->errstr();\n       die \"Can't create table 'crash_me_a' $DBI::errstr\\n\";\n     };\n   \n   if (!safe_query_l($key,\n       [\"insert into crash_me_a (a,b) values (11.4,18.9)\"]))\n     {\n       die \"Can't insert into table 'crash_me_a' a  record: $DBI::errstr\\n\";\n     };\n     \n   $arithmetic_safe = 'no'; \n   $arithmetic_safe = 'yes' \n   if ( (safe_query_result_l($key,\n            'select count(*) from crash_me_a where a+b=30.3',1,0) == 0) \n      and (safe_query_result_l($key,\n            'select count(*) from crash_me_a where a+b-30.3 = 0',1,0) == 0)  \n      and (safe_query_result_l($key,\n            'select count(*) from crash_me_a where a+b-30.3 < 0',0,0) == 0)\n      and (safe_query_result_l($key,\n            'select count(*) from crash_me_a where a+b-30.3 > 0',0,0) == 0));\n   save_config_data($key,$arithmetic_safe,$prompt);\n   print \"$arithmetic_safe\\n\";\n   assert(\"drop table crash_me_a $drop_attr\");\n}\n else\n{\n  print \"$prompt=$limits{$key} (cached)\\n\";\n}\n\n# Check where is null values in sorted recordset\nif (!safe_query($server->create(\"crash_me_n\",[\"i integer\",\"r integer\"]))) \n {\n   print DBI->errstr();\n   die \"Can't create table 'crash_me_n' $DBI::errstr\\n\";\n };\n \nsafe_query_l(\"position_of_null\",[\"insert into crash_me_n (i) values(1)\",\n\"insert into crash_me_n values(2,2)\",\n\"insert into crash_me_n values(3,3)\",\n\"insert into crash_me_n values(4,4)\",\n\"insert into crash_me_n (i) values(5)\"]);\n\n$key = \"position_of_null\";\n$prompt =\"Where is null values in sorted recordset\";\nif (!defined($limits{$key}))\n{\n save_incomplete($key,$prompt);\t\n print \"$prompt=\";\n $sth=$dbh->prepare(\"select r from crash_me_n order by r \");\n $sth->execute;\n add_log($key,\"< select r from crash_me_n order by r \");\n $limit= detect_null_position($key,$sth);\n $sth->finish;\n print \"$limit\\n\";\n save_config_data($key,$limit,$prompt);\n} else {\n  print \"$prompt=$limits{$key} (cache)\\n\";\n}\n\n$key = \"position_of_null_desc\";\n$prompt =\"Where is null values in sorted recordset (DESC)\";\nif (!defined($limits{$key}))\n{\n save_incomplete($key,$prompt);\t\n print \"$prompt=\";\n $sth=$dbh->prepare(\"select r from crash_me_n order by r desc\");\n $sth->execute;\n add_log($key,\"< select r from crash_me_n order by r  desc\");\n $limit= detect_null_position($key,$sth);\n $sth->finish;\n print \"$limit\\n\";\n save_config_data($key,$limit,$prompt);\n} else {\n  print \"$prompt=$limits{$key} (cache)\\n\";\n}\n\n\nassert(\"drop table  crash_me_n $drop_attr\");\n\n\n\n$key = 'sorted_group_by';\n$prompt = 'Group by always sorted';\nif (!defined($limits{$key}))\n{\n save_incomplete($key,$prompt);\n print \"$prompt=\";\n safe_query_l($key,[  \n\t\t\t \"create table crash_me_t1 (a int not null, b int not null)\",\n\t\t\t \"insert into crash_me_t1 values (1,1)\",\n\t\t\t \"insert into crash_me_t1 values (1,2)\",\n\t\t\t \"insert into crash_me_t1 values (3,1)\",\n\t\t\t \"insert into crash_me_t1 values (3,2)\",\n\t\t\t \"insert into crash_me_t1 values (2,2)\",\n\t\t\t \"insert into crash_me_t1 values (2,1)\",\n\t\t\t \"create table crash_me_t2 (a int not null, b int not null)\",\n\t\t\t \"create index crash_me_t2_ind on crash_me_t2 (a)\",\n\t\t\t \"insert into crash_me_t2 values (1,3)\",\n\t\t\t \"insert into crash_me_t2 values (3,1)\",\n\t\t\t \"insert into crash_me_t2 values (2,2)\",\n\t\t\t \"insert into crash_me_t2 values (1,1)\"]);\n\n my $bigqry = \"select crash_me_t1.a,crash_me_t2.b from \".\n\t     \"crash_me_t1,crash_me_t2 where crash_me_t1.a=crash_me_t2.a \".\n\t     \"group by crash_me_t1.a,crash_me_t2.b\";\n\n my $limit='no';\n my $rs = get_recordset($key,$bigqry);\n print_recordset($key,$rs); \n if ( defined ($rs)) { \n   if (compare_recordset($key,$rs,[[1,1],[1,3],[2,2],[3,1]]) eq 0)\n   {\n     $limit='yes'\n   }\n } else {\n  add_log($key,\"error: \".$DBI::errstr);\n } \n\n print \"$limit\\n\";\n safe_query_l($key,[\"drop table crash_me_t1\",\n\t\t       \"drop table crash_me_t2\"]);\n save_config_data($key,$limit,$prompt);\t        \n \n} else {\n print \"$prompt=$limits{$key} (cashed)\\n\";\n}\n\n\n#\n# End of test\n#\n\n$dbh->do(\"drop table crash_me $drop_attr\");        # Remove temporary table\n\nprint \"crash-me safe: $limits{'crash_me_safe'}\\n\";\nprint \"reconnected $reconnect_count times\\n\";\n\n$dbh->disconnect || warn $dbh->errstr;\nsave_all_config_data();\nexit 0;\n\n# End of test\n#\n\n$dbh->do(\"drop table crash_me $drop_attr\");        # Remove temporary table\n\nprint \"crash-me safe: $limits{'crash_me_safe'}\\n\";\nprint \"reconnected $reconnect_count times\\n\";\n\n$dbh->disconnect || warn $dbh->errstr;\nsave_all_config_data();\nexit 0;\n\n# Check where is nulls in the sorted result (for)\n# it expects exactly 5 rows in the result\n\nsub detect_null_position\n{\n  my $key = shift;\n  my $sth = shift;\n  my ($z,$r1,$r2,$r3,$r4,$r5);\n $r1 = $sth->fetchrow_array; add_log($key,\"> $r1\");\n $r2 = $sth->fetchrow_array; add_log($key,\"> $r2\");\n $r3 = $sth->fetchrow_array; add_log($key,\"> $r3\");\n $r4 = $sth->fetchrow_array; add_log($key,\"> $r4\");\n $r5 = $sth->fetchrow_array; add_log($key,\"> $r5\");\n return \"first\" if ( !defined($r1) && !defined($r2) && defined($r3));\n return \"last\" if ( !defined($r5) && !defined($r4) && defined($r3));\n return \"random\";\n}\n\nsub check_parenthesis {\n my $prefix=shift;\n my $fn=shift;\n my $result='no';\n my $param_name=$prefix.lc($fn);\n my $r;\n \n save_incomplete($param_name,$fn);\n $r = safe_query(\"select $fn $end_query\"); \n add_log($param_name,$safe_query_log);\n if ($r == 1)\n  {\n    $result=\"yes\";\n  } \n  else{\n   $r = safe_query(\"select $fn() $end_query\");\n   add_log($param_name,$safe_query_log);\n   if ( $r  == 1)   \n    {    \n       $result=\"with_parenthesis\";\n    }\n  }\n\n  save_config_data($param_name,$result,$fn);\n}\n\nsub check_constraint {\n my $prompt = shift;\n my $key = shift;\n my $create = shift;\n my $check = shift;\n my $drop = shift;\n save_incomplete($key,$prompt);\n print \"$prompt=\";\n my $res = 'no';\n my $t;\n $t=safe_query($create);\n add_log($key,$safe_query_log);\n if ( $t == 1)\n {\n   $res='yes';\n   $t= safe_query($check);\n   add_log($key,$safe_query_log);\n   if ($t == 1)\n   {\n     $res='syntax only';\n   }\n }        \n safe_query($drop);\n add_log($key,$safe_query_log);\n \n save_config_data($key,$res,$prompt);\n print \"$res\\n\";\n}\n\nsub make_time_r {\n  my $hour=shift;\n  my $minute=shift;\n  my $second=shift;\n  $_ = $limits{'time_format_inresult'};\n  return sprintf \"%02d:%02d:%02d\", ($hour%24),$minute,$second if (/^iso$/);\n  return sprintf \"%02d.%02d.%02d\", ($hour%24),$minute,$second if (/^euro/);\n  return sprintf \"%02d:%02d %s\", \n        ($hour >= 13? ($hour-12) : $hour),$minute,($hour >=13 ? 'PM':'AM') \n\t                if (/^usa/);\n  return sprintf \"%02d%02d%02d\", ($hour%24),$minute,$second if (/^HHMMSS/);\n  return sprintf \"%04d%02d%02d\", ($hour%24),$minute,$second if (/^HHHHMMSS/);\n  return \"UNKNOWN FORMAT\";\n}\n\nsub make_time {\n  my $hour=shift;\n  my $minute=shift;\n  my $second=shift;\n  return sprintf \"%02d:%02d:%02d\", ($hour%24),$minute,$second \n      if ($limits{'time_format_ISO'} eq \"yes\");\n  return sprintf \"%02d.%02d.%02d\", ($hour%24),$minute,$second \n      if ($limits{'time_format_EUR'} eq \"yes\");\n  return sprintf \"%02d:%02d %s\", \n        ($hour >= 13? ($hour-12) : $hour),$minute,($hour >=13 ? 'PM':'AM') \n      if ($limits{'time_format_USA'} eq \"yes\");\n  return sprintf \"%02d%02d%02d\", ($hour%24),$minute,$second \n      if ($limits{'time_format_HHMMSS'} eq \"yes\");\n  return sprintf \"%04d%02d%02d\", ($hour%24),$minute,$second \n      if ($limits{'time_format_HHHHMMSS'} eq \"yes\");\n  return \"UNKNOWN FORMAT\";\n}\n\nsub make_date_r {\n  my $year=shift;\n  my $month=shift;\n  my $day=shift;\n  $_ = $limits{'date_format_inresult'};\n  return sprintf \"%02d-%02d-%02d\", ($year%100),$month,$day if (/^short iso$/);\n  return sprintf \"%04d-%02d-%02d\", $year,$month,$day if (/^iso/);\n  return sprintf \"%02d.%02d.%02d\", $day,$month,($year%100) if (/^short euro/);\n  return sprintf \"%02d.%02d.%04d\", $day,$month,$year if (/^euro/);\n  return sprintf \"%02d/%02d/%02d\", $month,$day,($year%100) if (/^short usa/);\n  return sprintf \"%02d/%02d/%04d\", $month,$day,$year if (/^usa/);\n  return sprintf \"%04d%02d%02d\", $year,$month,$day if (/^YYYYMMDD/);\n  return \"UNKNOWN FORMAT\";\n}\n\n\nsub make_date {\n  my $year=shift;\n  my $month=shift;\n  my $day=shift;\n  return sprintf \"'%04d-%02d-%02d'\", $year,$month,$day \n      if ($limits{'date_format_ISO'} eq yes);\n  return sprintf \"DATE '%04d-%02d-%02d'\", $year,$month,$day \n      if ($limits{'date_format_ISO_with_date'} eq yes);\n  return sprintf \"'%02d.%02d.%04d'\", $day,$month,$year \n      if ($limits{'date_format_EUR'} eq 'yes');\n  return sprintf \"DATE '%02d.%02d.%04d'\", $day,$month,$year \n      if ($limits{'date_format_EUR_with_date'} eq 'yes');\n  return sprintf \"'%02d/%02d/%04d'\", $month,$day,$year \n      if ($limits{'date_format_USA'} eq 'yes');\n  return sprintf \"DATE '%02d/%02d/%04d'\", $month,$day,$year \n      if ($limits{'date_format_USA_with_date'} eq 'yes');\n  return sprintf \"'%04d%02d%02d'\", $year,$month,$day \n      if ($limits{'date_format_YYYYMMDD'} eq 'yes');\n  return sprintf \"DATE '%04d%02d%02d'\", $year,$month,$day \n      if ($limits{'date_format_YYYYMMDD_with_date'} eq 'yes');\n  return \"UNKNOWN FORMAT\";\n}\n\n\nsub print_recordset{\n  my ($key,$recset) = @_;\n  my $rec;\n  foreach $rec (@$recset)\n  {\n    add_log($key, \" > \".join(',', map(repr($_), @$rec)));\n  }\n}\n\n#\n# read result recordset from sql server. \n# returns arrayref to (arrayref to) values\n# or undef (in case of sql errors)\n#\nsub get_recordset{\n  my ($key,$query) = @_;\n  add_log($key, \"< $query\");\n  return $dbh->selectall_arrayref($query);\n}\n\n# function for comparing recordset (that was returned by get_recordset)\n# and arrayref of (arrayref of) values.\n#\n# returns : zero if recordset equal that array, 1 if it doesn't equal\n#\n# parameters:\n# $key - current operation (for logging)\n# $recset - recordset\n# $mustbe - array of values that we expect\n#\n# example: $a=get_recordset('some_parameter','select a,b from c');\n# if (compare_recordset('some_parameter',$a,[[1,1],[1,2],[1,3]]) neq 0) \n# {\n#   print \"unexpected result\\n\";\n# } ;\n#\nsub compare_recordset {\n  my ($key,$recset,$mustbe) = @_;\n  my $rec,$recno,$fld,$fldno,$fcount;\n  add_log($key,\"\\n Check recordset:\");\n  $recno=0;\n  foreach $rec (@$recset)\n  {\n    add_log($key,\" \" . join(',', map(repr($_),@$rec)) . \" expected: \" .\n\t    join(',', map(repr($_), @{$mustbe->[$recno]} ) ));\n    $fcount = @$rec;\n    $fcount--;\n    foreach $fldno (0 .. $fcount )\n    {\n      if ($mustbe->[$recno][$fldno] ne $rec->[$fldno])\n      {\n\tadd_log($key,\" Recordset doesn't correspond with template\");\n\treturn 1;\n      };\n    }\n    $recno++;\n  }\n  add_log($key,\" Recordset corresponds with template\");\n  return 0;\n}\n\n#\n# converts inner perl value to printable representation\n# for example: undef maps to 'NULL',\n# string -> 'string'\n# int -> int\n# \nsub repr {\n  my $s = shift;\n  return \"'$s'\"if ($s =~ /\\D/);\n  return 'NULL'if ( not defined($s));\n  return $s;\n}\n\n\nsub version\n{\n  print \"$0  Ver $version\\n\";\n}\n\n\nsub usage\n{\n  version();\n    print <<EOF;\n\nThis program tries to find all limits and capabilities for a SQL\nserver.  As it will use the server in some 'unexpected' ways, one\nshouldn\\'t have anything important running on it at the same time this\nprogram runs!  There is a slight chance that something unexpected may\nhappen....\n\nAs all used queries are legal according to some SQL standard. any\nreasonable SQL server should be able to run this test without any\nproblems.\n\nAll questions is cached in $opt_dir/'server_name'[-suffix].cfg that\nfuture runs will use limits found in previous runs. Remove this file\nif you want to find the current limits for your version of the\ndatabase server.\n\nThis program uses some table names while testing things. If you have any\ntables with the name of 'crash_me' or 'crash_qxxxx' where 'x' is a number,\nthey will be deleted by this test!\n\n$0 takes the following options:\n\n--help or --Information\n  Shows this help\n\n--batch-mode\n  Don\\'t ask any questions, quit on errors.\n\n--config-file='filename'\n  Read limit results from specific file\n\n--comment='some comment'\n  Add this comment to the crash-me limit file\n\n--check-server\n  Do a new connection to the server every time crash-me checks if the server\n  is alive.  This can help in cases where the server starts returning wrong\n  data because of an earlier select.\n\n--database='database' (Default $opt_database)\n  Create test tables in this database.\n\n--dir='limits'\n  Save crash-me output in this directory\n\n--debug\n  Lots of printing to help debugging if something goes wrong.\n\n--fix-limit-file\n  Reformat the crash-me limit file.  crash-me is not run!\n\n--force\n  Start test at once, without a warning screen and without questions.\n  This is a option for the very brave.\n  Use this in your cron scripts to test your database every night.\n\n--log-all-queries\n  Prints all queries that are executed. Mostly used for debugging crash-me.\n\n--log-queries-to-file='filename'\n  Log full queries to file.\n\n--host='hostname' (Default $opt_host)\n  Run tests on this host.\n\n--password='password'\n  Password for the current user.\n   \n--restart\n  Save states during each limit tests. This will make it possible to continue\n  by restarting with the same options if there is some bug in the DBI or\n  DBD driver that caused $0 to die!\n\n--server='server name'  (Default $opt_server)\n  Run the test on the given server.\n  Known servers names are: Access, Adabas, AdabasD, Empress, Oracle, \n  Informix, DB2, Mimer, mSQL, MS-SQL, MySQL, Pg, Solid or Sybase.\n  For others $0 can\\'t report the server version.\n\n--suffix='suffix' (Default '')\n  Add suffix to the output filename. For instance if you run crash-me like\n  \"crash-me --suffix=\"myisam\",\n  then output filename will look \"mysql-myisam.cfg\".\n\n--user='user_name'\n  User name to log into the SQL server.\n\n--db-start-cmd='command to restart server'\n  Automaticly restarts server with this command if the database server dies.\n\n--sleep='time in seconds' (Default $opt_sleep)\n  Wait this long before restarting server.\n\n--verbose\n--noverbose\n  Log into the result file queries performed for determination parameter value\n\nEOF\n  exit(0);\n}\n\n\nsub server_info\n{\n  my ($ok,$tmp);\n  $ok=0;\n  print \"\\nNOTE: You should be familiar with '$0 --help' before continuing!\\n\\n\";\n  if (lc($opt_server) eq \"mysql\")\n  {\n    $ok=1;\n    print <<EOF;\nThis test should not crash MySQL if it was distributed together with the\nrunning MySQL version.\nIf this is the case you can probably continue without having to worry about\ndestroying something.\nEOF\n  }\n  elsif (lc($opt_server) eq \"msql\")\n  {\n    print <<EOF;\nThis test will take down mSQL repeatedly while finding limits.\nTo make this test easier, start mSQL in another terminal with something like:\n\nwhile (true); do /usr/local/mSQL/bin/msql2d ; done\n\nYou should be sure that no one is doing anything important with mSQL and that\nyou have privileges to restart it!\nIt may take awhile to determinate the number of joinable tables, so prepare to\nwait!\nEOF\n  }\n  elsif (lc($opt_server) eq \"solid\")\n  {\n    print <<EOF;\nThis test will take down Solid server repeatedly while finding limits.\nYou should be sure that no one is doing anything important with Solid\nand that you have privileges to restart it!\n\nIf you are running Solid without logging and/or backup YOU WILL LOSE!\nSolid does not write data from the cache often enough. So if you continue\nyou may lose tables and data that you entered hours ago!\n\nSolid will also take a lot of memory running this test. You will nead\nat least 234M free!\n\nWhen doing the connect test Solid server or the perl api will hang when\nfreeing connections. Kill this program and restart it to continue with the\ntest. You don\\'t have to use --restart for this case.\nEOF\n    if (!$opt_restart)\n    {\n      print \"\\nWhen DBI/Solid dies you should run this program repeatedly\\n\";\n      print \"with --restart until all tests have completed\\n\";\n    }\n  }\n  elsif (lc($opt_server) eq \"pg\")\n  {\n    print <<EOF;\nThis test will crash postgreSQL when calculating the number of joinable tables!\nYou should be sure that no one is doing anything important with postgreSQL\nand that you have privileges to restart it!\nEOF\n  }\n  else\n  {\n    print <<EOF;\nThis test may crash $opt_server repeatedly while finding limits!\nYou should be sure that no one is doing anything important with $opt_server\nand that you have privileges to restart it!\nEOF\n  }\n  print <<EOF;\n\nSome of the tests you are about to execute may require a lot of\nmemory.  Your tests WILL adversely affect system performance. It\\'s\nnot uncommon that either this crash-me test program, or the actual\ndatabase back-end, will DIE with an out-of-memory error. So might\nany other program on your system if it requests more memory at the\nwrong time.\n\nNote also that while crash-me tries to find limits for the database server\nit will make a lot of queries that can\\'t be categorized as \\'normal\\'.  It\\'s\nnot unlikely that crash-me finds some limit bug in your server so if you\nrun this test you have to be prepared that your server may die during it!\n\nWe, the creators of this utility, are not responsible in any way if your\ndatabase server unexpectedly crashes while this program tries to find the\nlimitations of your server. By accepting the following question with \\'yes\\',\nyou agree to the above!\n\nYou have been warned!\n\nEOF\n\n  #\n  # No default reply here so no one can blame us for starting the test\n  # automaticly.\n  #\n  for (;;)\n  {\n    print \"Start test (yes/no) ? \";\n    $tmp=<STDIN>; chomp($tmp); $tmp=lc($tmp);\n    last if ($tmp =~ /^yes$/i);\n    exit 1 if ($tmp =~ /^n/i);\n    print \"\\n\";\n  }\n}\n\nsub machine\n{\n  my @name = POSIX::uname();\n  my $name= $name[0] . \" \" . $name[2] . \" \" . $name[4];\n  return $name;\n}\n\n\n#\n# Help functions that we need\n#\n\nsub safe_connect\n{\n  my ($object)=@_;\n  my ($dbh,$tmp);\n\n  for (;;)\n  {\n    if (($dbh=DBI->connect($server->{'data_source'},$opt_user,$opt_password,\n\t\t\t   { PrintError => 0, AutoCommit => 1})))\n    {\n      $dbh->{LongReadLen}= 16000000; # Set max retrieval buffer\n      return $dbh;\n    }\n    print \"Error: $DBI::errstr;  $server->{'data_source'} \".\n        \" - '$opt_user' - '$opt_password'\\n\";\n    print \"I got the above error when connecting to $opt_server\\n\";\n    if (defined($object) && defined($object->{'limit'}))\n    {\n      print \"This check was done with limit: $object->{'limit'}.\".\n          \"\\nNext check will be done with a smaller limit!\\n\";\n      $object=undef();\n    }\n    save_config_data('crash_me_safe','no',\"crash me safe\");\n    if ($opt_db_start_cmd)\n    {\n      print \"Restarting the db server with:\\n'$opt_db_start_cmd'\\n\";\n      system(\"$opt_db_start_cmd\");\n      print \"Waiting $opt_sleep seconds so the server can initialize\\n\";\n      sleep $opt_sleep;\n    }\n    else\n    {\n      exit(1) if ($opt_batch_mode);\n      print \"Can you check/restart it so I can continue testing?\\n\";\n      for (;;)\n      {\n\tprint \"Continue test (yes/no) ? [yes] \";\n\t$tmp=<STDIN>; chomp($tmp); $tmp=lc($tmp);\n\t$tmp = \"yes\" if ($tmp eq \"\");\n\tlast if (index(\"yes\",$tmp) >= 0);\n\texit 1 if (index(\"no\",$tmp) >= 0);\n\tprint \"\\n\";\n      }\n    }\n  }\n}\n\n#\n# Test connecting a couple of times before giving an error\n# This is needed to get the server time to free old connections\n# after the connect test\n#\n\nsub retry_connect\n{\n  my ($dbh, $i);\n  for ($i=0 ; $i < 10 ; $i++)\n  {\n    if (($dbh=DBI->connect($server->{'data_source'},$opt_user,$opt_password,\n\t\t\t { PrintError => 0, AutoCommit => 1})))\n    {\n      $dbh->{LongReadLen}= 16000000; # Set max retrieval buffer\n      return $dbh;\n    }\n    sleep(1);\n  }\n  return safe_connect();\n}\n\n#\n# Check if the server is up and running. If not, ask the user to restart it\n#\n\nsub check_connect\n{\n  my ($object)=@_;\n  my ($sth);\n  print \"Checking connection\\n\" if ($opt_log_all_queries);\n  # The following line will not work properly with interbase\n  if ($opt_check_server && defined($check_connect) && $dbh->{AutoCommit} != 0)\n  {\n    \n    $dbh->disconnect;\n    $dbh=safe_connect($object);\n    return;\n  }\n  return if (defined($check_connect) && defined($dbh->do($check_connect)));\n  $dbh->disconnect || warn $dbh->errstr;\n  print \"\\nreconnecting\\n\" if ($opt_debug);\n  $reconnect_count++;\n  undef($dbh);\n  $dbh=safe_connect($object);\n}\n\n#\n# print query if debugging\n#\nsub repr_query {\n  my $query=shift;\n if (length($query) > 130)\n {\n   $query=substr($query,0,120) . \"...(\" . (length($query)-120) . \")\";\n }\n return $query;\n}  \n\nsub print_query\n{\n  my ($query)=@_;\n  $last_error=$DBI::errstr;\n  if ($opt_debug)\n  {\n    if (length($query) > 130)\n    {\n      $query=substr($query,0,120) . \"...(\" . (length($query)-120) . \")\";\n    }\n    printf \"\\nGot error from query: '%s'\\n%s\\n\",$query,$DBI::errstr;\n  }\n}\n\n#\n# Do one or many queries. Return 1 if all was ok\n# Note that all rows are executed \n# (to ensure that we execute drop table commands)\n#\n\nsub safe_query_l {\n  my $key = shift;\n  my $q = shift;\n  my $r = safe_query($q);\n  add_log($key,$safe_query_log);\n  return $r;\n}\n\nsub safe_query\n{\n  my($queries)=@_;\n  my($query,$ok,$retry_ok,$retry,@tmp,$sth);\n  $safe_query_log=\"\";\n  $ok=1;\n  if (ref($queries) ne \"ARRAY\")\n  {\n    push(@tmp,$queries);\n    $queries= \\@tmp;\n  }\n  foreach $query (@$queries)\n  {\n    printf \"query1: %-80.80s ...(%d - %d)\\n\",$query,\n          length($query),$retry_limit  if ($opt_log_all_queries);\n    print LOG \"$query;\\n\" if ($opt_log);\n    $safe_query_log .= \"< $query\\n\";\n    if (length($query) > $query_size)\n    {\n      $ok=0;\n      $safe_query_log .= \"Query is too long\\n\";\n      next;\n    }\n\n    $retry_ok=0;\n    for ($retry=0; $retry < $retry_limit ; $retry++)\n    {\n      if (! ($sth=$dbh->prepare($query)))\n      {\n\tprint_query($query);\n        $safe_query_log .= \"> couldn't prepare:\". $dbh->errstr. \"\\n\";\n\t$retry=100 if (!$server->abort_if_fatal_error());\n\t# Force a reconnect because of Access drop table bug!\n\tif ($retry == $retry_limit-2)\n\t{\n\t  print \"Forcing disconnect to retry query\\n\" if ($opt_debug);\n\t  $dbh->disconnect || warn $dbh->errstr;\n\t}\n\tcheck_connect();        # Check that server is still up\n      }\n      else\n      {\n        if (!$sth->execute())\n        {\n \t  print_query($query);\n          $safe_query_log .= \"> execute error:\". $dbh->errstr. \"\\n\";\n\t  $retry=100 if (!$server->abort_if_fatal_error());\n\t  # Force a reconnect because of Access drop table bug!\n\t  if ($retry == $retry_limit-2)\n\t  {\n\t    print \"Forcing disconnect to retry query\\n\" if ($opt_debug);\n\t    $dbh->disconnect || warn $dbh->errstr;\n\t  }\n\t  check_connect();        # Check that server is still up\n        }\n        else\n        {\n\t  $retry = $retry_limit;\n\t  $retry_ok = 1;\n          $safe_query_log .= \"> OK\\n\";\n        }\n        $sth->finish;\n      }\n    }\n    $ok=0 if (!$retry_ok);\n    if ($query =~ /create/i && $server->reconnect_on_errors())\n    {\n      print \"Forcing disconnect to retry query\\n\" if ($opt_debug);\n      $dbh->disconnect || warn $dbh->errstr;\n      $dbh=safe_connect();\n    }\n  }\n  return $ok;\n}\n\nsub check_reserved_words\n{\n  my ($dbh)= @_;\n\n  my $answer, $prompt, $config, $keyword_type;\n\n  my @keywords_ext  = ( \"ansi-92/99\", \"ansi92\", \"ansi99\", \"extra\");\n\n  my %reserved_words = (\n        'ABSOLUTE' =>  0,          'ACTION' =>  0,             'ADD' =>  0,\n           'AFTER' =>  0,           'ALIAS' =>  0,             'ALL' =>  0,\n        'ALLOCATE' =>  0,           'ALTER' =>  0,             'AND' =>  0,\n             'ANY' =>  0,             'ARE' =>  0,              'AS' =>  0,\n             'ASC' =>  0,       'ASSERTION' =>  0,              'AT' =>  0,\n   'AUTHORIZATION' =>  0,          'BEFORE' =>  0,           'BEGIN' =>  0,\n             'BIT' =>  0,         'BOOLEAN' =>  0,            'BOTH' =>  0,\n         'BREADTH' =>  0,              'BY' =>  0,            'CALL' =>  0,\n         'CASCADE' =>  0,        'CASCADED' =>  0,            'CASE' =>  0,\n            'CAST' =>  0,         'CATALOG' =>  0,            'CHAR' =>  0,\n       'CHARACTER' =>  0,           'CHECK' =>  0,           'CLOSE' =>  0,\n         'COLLATE' =>  0,       'COLLATION' =>  0,          'COLUMN' =>  0,\n          'COMMIT' =>  0,      'COMPLETION' =>  0,         'CONNECT' =>  0,\n      'CONNECTION' =>  0,      'CONSTRAINT' =>  0,     'CONSTRAINTS' =>  0,\n        'CONTINUE' =>  0,   'CORRESPONDING' =>  0,          'CREATE' =>  0,\n           'CROSS' =>  0,         'CURRENT' =>  0,    'CURRENT_DATE' =>  0,\n    'CURRENT_TIME' =>  0,'CURRENT_TIMESTAMP' =>  0,   'CURRENT_USER' =>  0,\n          'CURSOR' =>  0,           'CYCLE' =>  0,            'DATA' =>  0,\n            'DATE' =>  0,             'DAY' =>  0,      'DEALLOCATE' =>  0,\n             'DEC' =>  0,         'DECIMAL' =>  0,         'DECLARE' =>  0,\n         'DEFAULT' =>  0,      'DEFERRABLE' =>  0,        'DEFERRED' =>  0,\n          'DELETE' =>  0,           'DEPTH' =>  0,            'DESC' =>  0,\n        'DESCRIBE' =>  0,      'DESCRIPTOR' =>  0,     'DIAGNOSTICS' =>  0,\n      'DICTIONARY' =>  0,      'DISCONNECT' =>  0,        'DISTINCT' =>  0,\n          'DOMAIN' =>  0,          'DOUBLE' =>  0,            'DROP' =>  0,\n            'EACH' =>  0,            'ELSE' =>  0,          'ELSEIF' =>  0,\n             'END' =>  0,        'END-EXEC' =>  0,          'EQUALS' =>  0,\n          'ESCAPE' =>  0,          'EXCEPT' =>  0,       'EXCEPTION' =>  0,\n            'EXEC' =>  0,         'EXECUTE' =>  0,        'EXTERNAL' =>  0,\n           'FALSE' =>  0,           'FETCH' =>  0,           'FIRST' =>  0,\n           'FLOAT' =>  0,             'FOR' =>  0,         'FOREIGN' =>  0,\n           'FOUND' =>  0,            'FROM' =>  0,            'FULL' =>  0,\n         'GENERAL' =>  0,             'GET' =>  0,          'GLOBAL' =>  0,\n              'GO' =>  0,            'GOTO' =>  0,           'GRANT' =>  0,\n           'GROUP' =>  0,          'HAVING' =>  0,            'HOUR' =>  0,\n        'IDENTITY' =>  0,              'IF' =>  0,          'IGNORE' =>  0,\n       'IMMEDIATE' =>  0,              'IN' =>  0,       'INDICATOR' =>  0,\n       'INITIALLY' =>  0,           'INNER' =>  0,           'INPUT' =>  0,\n          'INSERT' =>  0,             'INT' =>  0,         'INTEGER' =>  0,\n       'INTERSECT' =>  0,        'INTERVAL' =>  0,            'INTO' =>  0,\n              'IS' =>  0,       'ISOLATION' =>  0,            'JOIN' =>  0,\n             'KEY' =>  0,        'LANGUAGE' =>  0,            'LAST' =>  0,\n         'LEADING' =>  0,           'LEAVE' =>  0,            'LEFT' =>  0,\n            'LESS' =>  0,           'LEVEL' =>  0,            'LIKE' =>  0,\n           'LIMIT' =>  0,           'LOCAL' =>  0,            'LOOP' =>  0,\n           'MATCH' =>  0,          'MINUTE' =>  0,          'MODIFY' =>  0,\n          'MODULE' =>  0,           'MONTH' =>  0,           'NAMES' =>  0,\n        'NATIONAL' =>  0,         'NATURAL' =>  0,           'NCHAR' =>  0,\n             'NEW' =>  0,            'NEXT' =>  0,              'NO' =>  0,\n            'NONE' =>  0,             'NOT' =>  0,            'NULL' =>  0,\n         'NUMERIC' =>  0,          'OBJECT' =>  0,              'OF' =>  0,\n             'OFF' =>  0,             'OLD' =>  0,              'ON' =>  0,\n            'ONLY' =>  0,            'OPEN' =>  0,       'OPERATION' =>  0,\n          'OPTION' =>  0,              'OR' =>  0,           'ORDER' =>  0,\n           'OUTER' =>  0,          'OUTPUT' =>  0,             'PAD' =>  0,\n      'PARAMETERS' =>  0,         'PARTIAL' =>  0,       'PRECISION' =>  0,\n        'PREORDER' =>  0,         'PREPARE' =>  0,        'PRESERVE' =>  0,\n         'PRIMARY' =>  0,           'PRIOR' =>  0,      'PRIVILEGES' =>  0,\n       'PROCEDURE' =>  0,          'PUBLIC' =>  0,            'READ' =>  0,\n            'REAL' =>  0,       'RECURSIVE' =>  0,             'REF' =>  0,\n      'REFERENCES' =>  0,     'REFERENCING' =>  0,        'RELATIVE' =>  0,\n        'RESIGNAL' =>  0,        'RESTRICT' =>  0,          'RETURN' =>  0,\n         'RETURNS' =>  0,          'REVOKE' =>  0,           'RIGHT' =>  0,\n            'ROLE' =>  0,        'ROLLBACK' =>  0,         'ROUTINE' =>  0,\n             'ROW' =>  0,            'ROWS' =>  0,       'SAVEPOINT' =>  0,\n          'SCHEMA' =>  0,          'SCROLL' =>  0,          'SEARCH' =>  0,\n          'SECOND' =>  0,         'SECTION' =>  0,          'SELECT' =>  0,\n        'SEQUENCE' =>  0,         'SESSION' =>  0,    'SESSION_USER' =>  0,\n             'SET' =>  0,          'SIGNAL' =>  0,            'SIZE' =>  0,\n        'SMALLINT' =>  0,            'SOME' =>  0,           'SPACE' =>  0,\n             'SQL' =>  0,    'SQLEXCEPTION' =>  0,        'SQLSTATE' =>  0,\n      'SQLWARNING' =>  0,       'STRUCTURE' =>  0,     'SYSTEM_USER' =>  0,\n           'TABLE' =>  0,       'TEMPORARY' =>  0,            'THEN' =>  0,\n            'TIME' =>  0,       'TIMESTAMP' =>  0,   'TIMEZONE_HOUR' =>  0,\n 'TIMEZONE_MINUTE' =>  0,              'TO' =>  0,        'TRAILING' =>  0,\n     'TRANSACTION' =>  0,     'TRANSLATION' =>  0,         'TRIGGER' =>  0,\n            'TRUE' =>  0,           'UNDER' =>  0,           'UNION' =>  0,\n          'UNIQUE' =>  0,         'UNKNOWN' =>  0,          'UPDATE' =>  0,\n           'USAGE' =>  0,            'USER' =>  0,           'USING' =>  0,\n           'VALUE' =>  0,          'VALUES' =>  0,         'VARCHAR' =>  0,\n        'VARIABLE' =>  0,         'VARYING' =>  0,            'VIEW' =>  0,\n            'WHEN' =>  0,        'WHENEVER' =>  0,           'WHERE' =>  0,\n           'WHILE' =>  0,            'WITH' =>  0,         'WITHOUT' =>  0,\n            'WORK' =>  0,           'WRITE' =>  0,            'YEAR' =>  0,\n            'ZONE' =>  0,\n\n           'ASYNC' =>  1,             'AVG' =>  1,         'BETWEEN' =>  1,\n      'BIT_LENGTH' =>  1,'CHARACTER_LENGTH' =>  1,     'CHAR_LENGTH' =>  1,\n        'COALESCE' =>  1,         'CONVERT' =>  1,           'COUNT' =>  1,\n          'EXISTS' =>  1,         'EXTRACT' =>  1,     'INSENSITIVE' =>  1,\n           'LOWER' =>  1,             'MAX' =>  1,             'MIN' =>  1,\n          'NULLIF' =>  1,    'OCTET_LENGTH' =>  1,             'OID' =>  1,\n       'OPERATORS' =>  1,          'OTHERS' =>  1,        'OVERLAPS' =>  1,\n         'PENDANT' =>  1,        'POSITION' =>  1,         'PRIVATE' =>  1,\n       'PROTECTED' =>  1,         'REPLACE' =>  1,       'SENSITIVE' =>  1,\n         'SIMILAR' =>  1,         'SQLCODE' =>  1,        'SQLERROR' =>  1,\n       'SUBSTRING' =>  1,             'SUM' =>  1,            'TEST' =>  1,\n           'THERE' =>  1,       'TRANSLATE' =>  1,            'TRIM' =>  1,\n            'TYPE' =>  1,           'UPPER' =>  1,         'VIRTUAL' =>  1,\n         'VISIBLE' =>  1,            'WAIT' =>  1,\n\n           'ADMIN' =>  2,       'AGGREGATE' =>  2,           'ARRAY' =>  2,\n          'BINARY' =>  2,            'BLOB' =>  2,           'CLASS' =>  2,\n            'CLOB' =>  2,       'CONDITION' =>  2,     'CONSTRUCTOR' =>  2,\n        'CONTAINS' =>  2,            'CUBE' =>  2,    'CURRENT_PATH' =>  2,\n    'CURRENT_ROLE' =>  2,        'DATALINK' =>  2,           'DEREF' =>  2,\n         'DESTROY' =>  2,      'DESTRUCTOR' =>  2,   'DETERMINISTIC' =>  2,\n              'DO' =>  2,         'DYNAMIC' =>  2,           'EVERY' =>  2,\n            'EXIT' =>  2,          'EXPAND' =>  2,       'EXPANDING' =>  2,\n            'FREE' =>  2,        'FUNCTION' =>  2,        'GROUPING' =>  2,\n         'HANDLER' =>  2,            'HAST' =>  2,            'HOST' =>  2,\n      'INITIALIZE' =>  2,           'INOUT' =>  2,         'ITERATE' =>  2,\n           'LARGE' =>  2,         'LATERAL' =>  2,       'LOCALTIME' =>  2,\n  'LOCALTIMESTAMP' =>  2,         'LOCATOR' =>  2,           'MEETS' =>  2,\n        'MODIFIES' =>  2,           'NCLOB' =>  2,       'NORMALIZE' =>  2,\n      'ORDINALITY' =>  2,             'OUT' =>  2,       'PARAMETER' =>  2,\n            'PATH' =>  2,          'PERIOD' =>  2,         'POSTFIX' =>  2,\n        'PRECEDES' =>  2,          'PREFIX' =>  2,           'READS' =>  2,\n            'REDO' =>  2,          'REPEAT' =>  2,          'RESULT' =>  2,\n          'ROLLUP' =>  2,            'SETS' =>  2,        'SPECIFIC' =>  2,\n    'SPECIFICTYPE' =>  2,           'START' =>  2,           'STATE' =>  2,\n          'STATIC' =>  2,        'SUCCEEDS' =>  2,       'TERMINATE' =>  2,\n            'THAN' =>  2,           'TREAT' =>  2,            'UNDO' =>  2,\n           'UNTIL' =>  2,\n\n          'ACCESS' =>  3,         'ANALYZE' =>  3,           'AUDIT' =>  3,\n  'AUTO_INCREMENT' =>  3,          'BACKUP' =>  3,             'BDB' =>  3,\n      'BERKELEYDB' =>  3,          'BIGINT' =>  3,           'BREAK' =>  3,\n          'BROWSE' =>  3,           'BTREE' =>  3,            'BULK' =>  3,\n          'CHANGE' =>  3,      'CHECKPOINT' =>  3,         'CLUSTER' =>  3,\n       'CLUSTERED' =>  3,         'COLUMNS' =>  3,         'COMMENT' =>  3,\n        'COMPRESS' =>  3,         'COMPUTE' =>  3,   'CONTAINSTABLE' =>  3,\n        'DATABASE' =>  3,       'DATABASES' =>  3,        'DAY_HOUR' =>  3,\n      'DAY_MINUTE' =>  3,      'DAY_SECOND' =>  3,            'DBCC' =>  3,\n         'DELAYED' =>  3,            'DENY' =>  3,            'DISK' =>  3,\n     'DISTINCTROW' =>  3,     'DISTRIBUTED' =>  3,           'DUMMY' =>  3,\n            'DUMP' =>  3,        'ENCLOSED' =>  3,          'ERRLVL' =>  3,\n          'ERRORS' =>  3,         'ESCAPED' =>  3,       'EXCLUSIVE' =>  3,\n         'EXPLAIN' =>  3,          'FIELDS' =>  3,            'FILE' =>  3,\n      'FILLFACTOR' =>  3,        'FREETEXT' =>  3,   'FREETEXTTABLE' =>  3,\n        'FULLTEXT' =>  3,        'GEOMETRY' =>  3,            'HASH' =>  3,\n   'HIGH_PRIORITY' =>  3,        'HOLDLOCK' =>  3,     'HOUR_MINUTE' =>  3,\n     'HOUR_SECOND' =>  3,      'IDENTIFIED' =>  3,     'IDENTITYCOL' =>  3,\n 'IDENTITY_INSERT' =>  3,       'INCREMENT' =>  3,           'INDEX' =>  3,\n          'INFILE' =>  3,         'INITIAL' =>  3,          'INNODB' =>  3,\n            'KEYS' =>  3,            'KILL' =>  3,          'LINENO' =>  3,\n           'LINES' =>  3,            'LOAD' =>  3,            'LOCK' =>  3,\n            'LONG' =>  3,        'LONGBLOB' =>  3,        'LONGTEXT' =>  3,\n    'LOW_PRIORITY' =>  3, 'MASTER_SERVER_ID' =>  3,      'MAXEXTENTS' =>  3,\n      'MEDIUMBLOB' =>  3,       'MEDIUMINT' =>  3,      'MEDIUMTEXT' =>  3,\n       'MIDDLEINT' =>  3,           'MINUS' =>  3,   'MINUTE_SECOND' =>  3,\n        'MLSLABEL' =>  3,            'MODE' =>  3,      'MRG_MYISAM' =>  3,\n         'NOAUDIT' =>  3,         'NOCHECK' =>  3,      'NOCOMPRESS' =>  3,\n    'NONCLUSTERED' =>  3,          'NOWAIT' =>  3,          'NUMBER' =>  3,\n         'OFFLINE' =>  3,         'OFFSETS' =>  3,          'ONLINE' =>  3,\n  'OPENDATASOURCE' =>  3,       'OPENQUERY' =>  3,      'OPENROWSET' =>  3,\n         'OPENXML' =>  3,        'OPTIMIZE' =>  3,      'OPTIONALLY' =>  3,\n         'OUTFILE' =>  3,            'OVER' =>  3,         'PCTFREE' =>  3,\n         'PERCENT' =>  3,            'PLAN' =>  3,           'PRINT' =>  3,\n            'PROC' =>  3,           'PURGE' =>  3,       'RAISERROR' =>  3,\n             'RAW' =>  3,        'READTEXT' =>  3,     'RECONFIGURE' =>  3,\n          'REGEXP' =>  3,          'RENAME' =>  3,     'REPLICATION' =>  3,\n         'REQUIRE' =>  3,        'RESOURCE' =>  3,         'RESTORE' =>  3,\n           'RLIKE' =>  3,        'ROWCOUNT' =>  3,      'ROWGUIDCOL' =>  3,\n           'ROWID' =>  3,          'ROWNUM' =>  3,           'RTREE' =>  3,\n            'RULE' =>  3,            'SAVE' =>  3,         'SETUSER' =>  3,\n           'SHARE' =>  3,            'SHOW' =>  3,        'SHUTDOWN' =>  3,\n          'SONAME' =>  3,         'SPATIAL' =>  3,  'SQL_BIG_RESULT' =>  3,\n'SQL_CALC_FOUND_ROWS' =>  3,'SQL_SMALL_RESULT' =>  3,        'SSL' =>  3,\n        'STARTING' =>  3,      'STATISTICS' =>  3,   'STRAIGHT_JOIN' =>  3,\n         'STRIPED' =>  3,      'SUCCESSFUL' =>  3,         'SYNONYM' =>  3,\n         'SYSDATE' =>  3,          'TABLES' =>  3,      'TERMINATED' =>  3,\n        'TEXTSIZE' =>  3,        'TINYBLOB' =>  3,         'TINYINT' =>  3,\n        'TINYTEXT' =>  3,             'TOP' =>  3,            'TRAN' =>  3,\n        'TRUNCATE' =>  3,         'TSEQUAL' =>  3,           'TYPES' =>  3,\n             'UID' =>  3,          'UNLOCK' =>  3,        'UNSIGNED' =>  3,\n      'UPDATETEXT' =>  3,             'USE' =>  3,  'USER_RESOURCES' =>  3,\n        'VALIDATE' =>  3,       'VARBINARY' =>  3,        'VARCHAR2' =>  3,\n         'WAITFOR' =>  3,        'WARNINGS' =>  3,       'WRITETEXT' =>  3,\n             'XOR' =>  3,      'YEAR_MONTH' =>  3,        'ZEROFILL' =>  3\n);\n\n\n  safe_query(\"drop table crash_me10 $drop_attr\");\n\n  foreach my $keyword (sort {$a cmp $b} keys %reserved_words)\n  {\n    $keyword_type= $reserved_words{$keyword};\n\n    $prompt= \"Keyword \".$keyword;\n    $config= \"reserved_word_\".$keywords_ext[$keyword_type].\"_\".lc($keyword);\n\n    report_fail($prompt,$config,\n      \"create table crash_me10 ($keyword int not null)\",\n      \"drop table crash_me10 $drop_attr\"\n    );\n  }\n}\n\n#\n# Do a query on a query package object.\n#\n\nsub limit_query\n{\n  my($object,$limit)=@_;\n  my ($query,$result,$retry,$sth);\n\n  $query=$object->query($limit);\n  $result=safe_query($query);\n  if (!$result)\n  {\n    $object->cleanup();\n    return 0;\n  }\n  if (defined($query=$object->check_query()))\n  {\n    for ($retry=0 ; $retry < $retry_limit ; $retry++)\n    {\n      printf \"query2: %-80.80s\\n\",$query if ($opt_log_all_queries);\n      print LOG \"$query;\\n\" if ($opt_log);\n      if (($sth= $dbh->prepare($query)))\n      {\n\tif ($sth->execute)\n\t{\n\t  $result= $object->check($sth);\n\t  $sth->finish;\n\t  $object->cleanup();\n\t  return $result;\n\t}\n\tprint_query($query);\n\t$sth->finish;\n      }\n      else\n      {\n\tprint_query($query);\n      }\n      $retry=100 if (!$server->abort_if_fatal_error()); # No need to continue\n      if ($retry == $retry_limit-2)\n      {\n\tprint \"Forcing discoennect to retry query\\n\" if ($opt_debug);\n\t$dbh->disconnect || warn $dbh->errstr;\n      }\n      check_connect($object);   # Check that server is still up\n    }\n    $result=0;                  # Query failed\n  }\n  $object->cleanup();\n  return $result;               # Server couldn't handle the query\n}\n\n\nsub report\n{\n  my ($prompt,$limit,@queries)=@_;\n  print \"$prompt: \";\n  if (!defined($limits{$limit}))\n  {\n    my $queries_result = safe_query(\\@queries);\n    add_log($limit, $safe_query_log);\n    my $report_result;\n    if ( $queries_result) {\n      $report_result= \"yes\";\n      add_log($limit,\"As far as all queries returned OK, result is YES\");\n    } else {\n      $report_result= \"no\";\n      add_log($limit,\"As far as some queries didnt return OK, result is NO\");\n    } \n    save_config_data($limit,$report_result,$prompt);\n  }\n  print \"$limits{$limit}\\n\";\n  return $limits{$limit} ne \"no\";\n}\n\nsub report_fail\n{\n  my ($prompt,$limit,@queries)=@_;\n  print \"$prompt: \";\n  if (!defined($limits{$limit}))\n  {\n    my $queries_result = safe_query(\\@queries);\n    add_log($limit, $safe_query_log);\n    my $report_result;\n    if ( $queries_result) {\n      $report_result= \"no\";\n      add_log($limit,\"As far as all queries returned OK, result is NO\");\n    } else {\n      $report_result= \"yes\";\n      add_log($limit,\"As far as some queries didnt return OK, result is YES\");\n    } \n    save_config_data($limit,$report_result,$prompt);\n  }\n  print \"$limits{$limit}\\n\";\n  return $limits{$limit} ne \"no\";\n}\n\n\n# Return true if one of the queries is ok\n\nsub report_one\n{\n  my ($prompt,$limit,$queries)=@_;\n  my ($query,$res,$result);\n  print \"$prompt: \";\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    $result=\"no\";\n    foreach $query (@$queries)\n    {\n      if (safe_query_l($limit,$query->[0]))\n      {\n\t$result= $query->[1];\n\tlast;\n      }\n    }\n    save_config_data($limit,$result,$prompt);\n  }\n  print \"$limits{$limit}\\n\";\n  return $limits{$limit} ne \"no\";\n}\n\n\n# Execute query and save result as limit value.\n\nsub report_result\n{\n  my ($prompt,$limit,$query)=@_;\n  my($error);\n  print \"$prompt: \";\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    $error=safe_query_result($query,\"1\",2);\n    add_log($limit,$safe_query_result_log);\n    save_config_data($limit,$error ? \"not supported\" :$last_result,$prompt);\n  }\n  print \"$limits{$limit}\\n\";\n  return $limits{$limit} ne \"not supported\";\n}\n\nsub report_trans\n{\n  my ($limit,$queries,$check,$clear)=@_;\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    eval {undef($dbh->{AutoCommit})};\n    if (!$@)\n    {\n      if (safe_query(\\@$queries))\n      {\n\t  $dbh->rollback;\n          $dbh->{AutoCommit} = 1;\n\t    if (safe_query_result($check,\"\",\"\")) {\n              add_log($limit,$safe_query_result_log);\t    \n\t      save_config_data($limit,\"yes\",$limit);\n\t    }\n\t    safe_query($clear);\n      } else {\n        add_log($limit,$safe_query_log);\n        save_config_data($limit,\"error\",$limit);\n      }\n      $dbh->{AutoCommit} = 1;\n    }\n    else\n    {\n      add_log($limit,\"Couldnt undef autocommit ?? \");\n      save_config_data($limit,\"no\",$limit);\n    }\n    safe_query($clear);\n  }\n  return $limits{$limit} ne \"yes\";\n}\n\nsub report_rollback\n{\n  my ($limit,$queries,$check,$clear)=@_;\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    eval {undef($dbh->{AutoCommit})};\n    if (!$@)\n    {\n      if (safe_query(\\@$queries))\n      {\n          add_log($limit,$safe_query_log);\n\n\t  $dbh->rollback;\n           $dbh->{AutoCommit} = 1;\n           if (safe_query($check)) {\n\t      add_log($limit,$safe_query_log);\n\t      save_config_data($limit,\"no\",$limit);\n\t    }  else  {\n\t      add_log($limit,$safe_query_log);\n\t      save_config_data($limit,\"yes\",$limit);\n\t    };\n\t    safe_query($clear);\n      } else {\n        add_log($limit,$safe_query_log);\n        save_config_data($limit,\"error\",$limit);\n      }\n    }\n    else\n    {\n      add_log($limit,'Couldnt undef Autocommit??');\n      save_config_data($limit,\"error\",$limit);\n    }\n    safe_query($clear);\n  }\n  $dbh->{AutoCommit} = 1;\n  return $limits{$limit} ne \"yes\";\n}\n\n\nsub check_and_report\n{\n  my ($prompt,$limit,$pre,$query,$post,$answer,$string_type,$skip_prompt,\n      $function)=@_;\n  my ($tmp);\n  $function=0 if (!defined($function));\n\n  print \"$prompt: \" if (!defined($skip_prompt));\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    $tmp=1-safe_query(\\@$pre);\n    add_log($limit,$safe_query_log);\n    if (!$tmp) \n    {\n        $tmp=safe_query_result($query,$answer,$string_type) ;\n        add_log($limit,$safe_query_result_log);\n    };\t\n    safe_query(\\@$post);\n    add_log($limit,$safe_query_log);\n    delete $limits{$limit};\n    if ($function == 3)\t\t# Report error as 'no'.\n    {\n      $function=0;\n      $tmp= -$tmp;\n    }\n    if ($function == 0 ||\n\t$tmp != 0 && $function == 1 ||\n\t$tmp == 0 && $function== 2)\n    {\n      save_config_data($limit, $tmp == 0 ? \"yes\" : $tmp == 1 ? \"no\" : \"error\",\n\t\t       $prompt);\n      print \"$limits{$limit}\\n\";\n      return $function == 0 ? $limits{$limit} eq \"yes\" : 0;\n    }\n    return 1;\t\t\t# more things to check\n  }\n  print \"$limits{$limit}\\n\";\n  return 0 if ($function);\n  return $limits{$limit} eq \"yes\";\n}\n\n\nsub try_and_report\n{\n  my ($prompt,$limit,@tests)=@_;\n  my ($tmp,$test,$type);\n\n  print \"$prompt: \";\n\n  if (!defined($limits{$limit}))\n  {\n    save_incomplete($limit,$prompt);\n    $type=\"no\";\t\t\t# Not supported\n    foreach $test (@tests)\n    {\n      my $tmp_type= shift(@$test);\n      if (safe_query_l($limit,\\@$test))\n      {\n\t$type=$tmp_type;\n\tgoto outer;\n      }\n    }\n  outer:\n    save_config_data($limit, $type, $prompt);\n  }\n  print \"$limits{$limit}\\n\";\n  return $limits{$limit} ne \"no\";\n}\n\n#\n# Just execute the query and check values;  Returns 1 if ok\n#\n\nsub execute_and_check\n{\n  my ($key,$pre,$query,$post,$answer,$string_type)=@_;\n  my ($tmp);\n\n  $tmp=safe_query_l($key,\\@$pre);\n\n  $tmp=safe_query_result_l($key,$query,$answer,$string_type) == 0 if ($tmp);\n  safe_query_l($key,\\@$post);\n  return $tmp;\n}\n\n\n# returns 0 if ok, 1 if error, -1 if wrong answer\n# Sets $last_result to value of query\nsub safe_query_result_l{\n  my ($key,$query,$answer,$result_type)=@_;\n  my $r = safe_query_result($query,$answer,$result_type);\n  add_log($key,$safe_query_result_log);\n  return $r;\n}  \n\nsub safe_query_result\n{\n# result type can be \n#  8 (must be empty), 2 (Any value), 0 (number)\n#  1 (char, endspaces can differ), 3 (exact char), 4 (NULL)\n#  5 (char with prefix), 6 (exact, errors are ignored)\n#  7 (array of numbers)\n  my ($query,$answer,$result_type)=@_;\n  my ($sth,$row,$result,$retry);\n  undef($last_result);\n  $safe_query_result_log=\"\";\n  \n  printf \"\\nquery3: %-80.80s\\n\",$query  if ($opt_log_all_queries);\n  print LOG \"$query;\\n\" if ($opt_log);\n  $safe_query_result_log=\"<\".$query.\"\\n\";\n\n  for ($retry=0; $retry < $retry_limit ; $retry++)\n  {\n    if (!($sth=$dbh->prepare($query)))\n    {\n      print_query($query);\n      $safe_query_result_log .= \"> prepare failed:\".$dbh->errstr.\"\\n\";\n      \n      if ($server->abort_if_fatal_error())\n      {\n\tcheck_connect();\t# Check that server is still up\n\tnext;\t\t\t# Retry again\n      }\n      check_connect();\t\t# Check that server is still up\n      return 1;\n    }\n    if (!$sth->execute)\n    {\n      print_query($query);\n      $safe_query_result_log .= \"> execute failed:\".$dbh->errstr.\"\\n\";\n      if ($server->abort_if_fatal_error())\n      {\n\tcheck_connect();\t# Check that server is still up\n\tnext;\t\t\t# Retry again\n      }\n      check_connect();\t\t# Check that server is still up\n      return 1;\n    }\n    else\n    {\n      last;\n    }\n  }\n  if (!($row=$sth->fetchrow_arrayref))\n  {\n    print \"\\nquery: $query didn't return any result\\n\" if ($opt_debug);\n    $safe_query_result_log .= \"> didn't return any result:\".$dbh->errstr.\"\\n\";    \n    $sth->finish;\n    return ($result_type == 8) ? 0 : 1;\n  }\n  if ($result_type == 8)\n  {\n    $sth->finish;\n    return 1;\n  }\n  $result=0;                  \t# Ok\n  $last_result= $row->[0];\t# Save for report_result;\n  $safe_query_result_log .= \">\".$last_result.\"\\n\";    \n  # Note:\n  # if ($result_type == 2)        We accept any return value as answer\n\n  if ($result_type == 0)\t# Compare numbers\n  {\n    $row->[0] =~ s/,/./;\t# Fix if ',' is used instead of '.'\n    if ($row->[0] != $answer && (abs($row->[0]- $answer)/\n\t\t\t\t (abs($row->[0]) + abs($answer))) > 0.01)\n    {\n      $result=-1;\n      $safe_query_result_log .= \n          \"We expected '$answer' but got '$last_result' \\n\";    \n    }\n  }\n  elsif ($result_type == 1)\t# Compare where end space may differ\n  {\n    $row->[0] =~ s/\\s+$//;\n    if ($row->[0] ne $answer)\n    {\n     $result=-1;\n     $safe_query_result_log .= \n         \"We expected '$answer' but got '$last_result' \\n\";    \n    } ;\n  }\n  elsif ($result_type == 3)\t# This should be a exact match\n  {\n     if ($row->[0] ne $answer)\n     { \n      $result= -1; \n      $safe_query_result_log .= \n          \"We expected '$answer' but got '$last_result' \\n\";    \n    };\n  }\n  elsif ($result_type == 4)\t# If results should be NULL\n  {\n    if (defined($row->[0]))\n    { \n     $result= -1; \n     $safe_query_result_log .= \n         \"We expected NULL but got '$last_result' \\n\";    \n    };\n  }\n  elsif ($result_type == 5)\t# Result should have given prefix\n  {\n     if (length($row->[0]) < length($answer) &&\n\t\t    substr($row->[0],1,length($answer)) ne $answer)\n     { \n      $result= -1 ;\n      $safe_query_result_log .= \n        \"Result must have prefix '$answer', but  '$last_result' \\n\";    \n     };\n  }\n  elsif ($result_type == 6)\t# Exact match but ignore errors\n  {\n    if ($row->[0] ne $answer)    \n    { $result= 1;\n      $safe_query_result_log .= \n          \"We expected '$answer' but got '$last_result' \\n\";    \n    } ;\n  }\n  elsif ($result_type == 7)\t# Compare against array of numbers\n  {\n    if ($row->[0] != $answer->[0])\n    {\n      $safe_query_result_log .= \"must be '$answer->[0]' \\n\";    \n      $result= -1;\n    }\n    else\n    {\n      my ($value);\n      shift @$answer;\n      while (($row=$sth->fetchrow_arrayref))\n      {\n       $safe_query_result_log .= \">$row\\n\";    \n\n\t$value=shift(@$answer);\n\tif (!defined($value))\n\t{\n\t  print \"\\nquery: $query returned to many results\\n\"\n\t    if ($opt_debug);\n          $safe_query_result_log .= \"It returned to many results \\n\";    \t    \n\t  $result= 1;\n\t  last;\n\t}\n\tif ($row->[0] != $value)\n\t{\n          $safe_query_result_log .= \"Must return $value here \\n\";    \t    \n\t  $result= -1;\n\t  last;\n\t}\n      }\n      if ($#$answer != -1)\n      {\n\tprint \"\\nquery: $query returned too few results\\n\"\n\t  if ($opt_debug);\n        $safe_query_result_log .= \"It returned too few results \\n\";    \t    \n\t$result= 1;\n      }\n    }\n  }\n  $sth->finish;\n  print \"\\nquery: '$query' returned '$row->[0]' instead of '$answer'\\n\"\n    if ($opt_debug && $result && $result_type != 7);\n  return $result;\n}\n\n#\n# Find limit using binary search.  This is a weighed binary search that\n# will prefere lower limits to get the server to crash as \n# few times as possible\n\n\nsub find_limit()\n{\n  my ($prompt,$limit,$query)=@_;\n  my ($first,$end,$i,$tmp,@tmp_array, $queries);\n  print \"$prompt: \";\n  if (defined($end=$limits{$limit}))\n  {\n    print \"$end (cache)\\n\";\n    return $end;\n  }\n  save_incomplete($limit,$prompt);\n  add_log($limit,\"We are trying (example with N=5):\");\n  $queries = $query->query(5);\n  if (ref($queries) ne \"ARRAY\")\n  {\n    push(@tmp_array,$queries);\n    $queries= \\@tmp_array;\n  }\n  foreach $tmp (@$queries)\n  {   add_log($limit,repr_query($tmp));  }    \n\n  if (defined($queries = $query->check_query()))\n  { \n    if (ref($queries) ne \"ARRAY\")\n    {\n      @tmp_array=();\n      push(@tmp_array,$queries); \n      $queries= \\@tmp_array;\n    }\n    foreach $tmp (@$queries)\n      {   add_log($limit,repr_query($tmp));  }    \n  }\n  if (defined($query->{'init'}) && !defined($end=$limits{'restart'}{'tohigh'}))\n  {\n    if (!safe_query_l($limit,$query->{'init'}))\n    {\n      $query->cleanup();\n      return \"error\";\n    }\n  }\n\n  if (!limit_query($query,1))           # This must work\n  {\n    print \"\\nMaybe fatal error: Can't check '$prompt' for limit=1\\n\".\n    \"error: $last_error\\n\";\n    return \"error\";\n  }\n\n  $first=0;\n  $first=$limits{'restart'}{'low'} if ($limits{'restart'}{'low'});\n\n  if (defined($end=$limits{'restart'}{'tohigh'}))\n  {\n    $end--;\n    print \"\\nRestarting this with low limit: $first and high limit: $end\\n\";\n    delete $limits{'restart'};\n    $i=$first+int(($end-$first+4)/5);           # Prefere lower on errors\n  }\n  else\n  {\n    $end= $query->max_limit();\n    $i=int(($end+$first)/2);\n  }\n  my $log_str = \"\";\n  unless(limit_query($query,0+$end)) {\n    while ($first < $end)\n    {\n      print \".\" if ($opt_debug);\n      save_config_data(\"restart\",$i,\"\") if ($opt_restart);\n      if (limit_query($query,$i))\n      {\n        $first=$i;\n\t$log_str .= \" $i:OK\";\n        $i=$first+int(($end-$first+1)/2); # to be a bit faster to go up\n      }\n      else\n      { \n        $end=$i-1;\n\t$log_str .= \" $i:FAIL\";\n        $i=$first+int(($end-$first+4)/5); # Prefere lower on errors\n      }\n    }\n  }\n  $end+=$query->{'offset'} if ($end && defined($query->{'offset'}));\n  if ($end >= $query->{'max_limit'} &&\n      substr($query->{'max_limit'},0,1) eq '+')\n  {\n    $end= $query->{'max_limit'};\n  }\n  print \"$end\\n\";\n  add_log($limit,$log_str);\n  save_config_data($limit,$end,$prompt);\n  delete $limits{'restart'};\n  return $end;\n}\n\n#\n# Check that the query works!\n#\n\nsub assert\n{\n  my($query)=@_;\n\n  if (!safe_query($query))\n  {\n    $query=join(\"; \",@$query) if (ref($query) eq \"ARRAY\");\n    print \"\\nFatal error:\\nquery: '$query'\\nerror: $DBI::errstr\\n\";\n    exit 1;\n  }\n}\n\n\nsub read_config_data\n{\n  my ($key,$limit,$prompt);\n  if (-e $opt_config_file)\n  {\n    open(CONFIG_FILE,\"+<$opt_config_file\") ||\n      die \"Can't open configure file $opt_config_file\\n\";\n    print \"Reading old values from cache: $opt_config_file\\n\";\n  }\n  else\n  {\n    open(CONFIG_FILE,\"+>>$opt_config_file\") ||\n      die \"Can't create configure file $opt_config_file: $!\\n\";\n  }\n  select CONFIG_FILE;\n  $|=1;\n  select STDOUT;\n  while (<CONFIG_FILE>)\n  {\n    chomp;\n    if (/^(\\S+)=([^\\#]*[^\\#\\s])\\s*(\\# .*)*$/)\n    {\n      $key=$1; $limit=$2 ; $prompt=$3;\n      if (!$opt_quick || $limit =~ /\\d/ || $key =~ /crash_me/)\n      {\n\tif ($key !~ /restart/i)\n\t{\n\t  $limits{$key}=$limit eq \"null\"? undef : $limit;\n\t  $prompts{$key}=length($prompt) ? substr($prompt,2) : \"\";\n\t  $last_read=$key;\n\t  delete $limits{'restart'};\n\t}\n\telse\n\t{\n\t  $limit_changed=1;\n\t  if ($limit > $limits{'restart'}{'tohigh'})\n\t  {\n\t    $limits{'restart'}{'low'} = $limits{'restart'}{'tohigh'};\n\t  }\n\t  $limits{'restart'}{'tohigh'} = $limit;\n\t}\n      }\n    }\n    elsif (/\\s*###(.*)$/)    # log line\n    {\n       # add log line for previously read key\n       $log{$last_read} .= \"$1\\n\";\n    }\n    elsif (!/^\\s*$/ && !/^\\#/)\n    {\n      die \"Wrong config row: $_\\n\";\n    }\n  }\n}\n\n\nsub save_config_data\n{\n  my ($key,$limit,$prompt)=@_;\n  $prompts{$key}=$prompt;\n  return if (defined($limits{$key}) && $limits{$key} eq $limit);\n  if (!defined($limit) || $limit eq \"\")\n  {\n#    die \"Undefined limit for $key\\n\";\n     $limit = 'null'; \n  }\n  print CONFIG_FILE \"$key=$limit\\t# $prompt\\n\";\n  $limits{$key}=$limit;\n  $limit_changed=1;\n# now write log lines (immediatelly after limits)\n  my $line;\n  my $last_line_was_empty=0;\n  foreach $line (split /\\n/, $log{$key})\n  {\n    print CONFIG_FILE \"   ###$line\\n\" \n\tunless ( ($last_line_was_empty eq 1)  \n\t         && ($line =~ /^\\s+$/)  );\n    $last_line_was_empty= ($line =~ /^\\s+$/)?1:0;\n  };     \n\n  if (($opt_restart && $limits{'operating_system'} =~ /windows/i) ||\n\t\t       ($limits{'operating_system'} =~ /NT/))\n  {\n    # If perl crashes in windows, everything is lost (Wonder why? :)\n    close CONFIG_FILE;\n    open(CONFIG_FILE,\"+>>$opt_config_file\") ||\n      die \"Can't reopen configure file $opt_config_file: $!\\n\";\n  }\n}\n\nsub add_log\n{\n  my $key = shift;\n  my $line = shift;\n  $log{$key} .= $line . \"\\n\" if ($opt_verbose);;  \n}\n\nsub save_all_config_data\n{\n  my ($key,$tmp);\n  close CONFIG_FILE;\n  return if (!$limit_changed);\n  open(CONFIG_FILE,\">$opt_config_file\") ||\n    die \"Can't create configure file $opt_config_file: $!\\n\";\n  select CONFIG_FILE;\n  $|=1;\n  select STDOUT;\n  delete $limits{'restart'};\n\n  print CONFIG_FILE \n       \"#This file is automaticly generated by crash-me $version\\n\\n\";\n  foreach $key (sort keys %limits)\n  {\n    $tmp=\"$key=$limits{$key}\";\n    print CONFIG_FILE $tmp . (\"\\t\" x (int((32-min(length($tmp),32)+7)/8)+1)) .\n      \"# $prompts{$key}\\n\";\n     my $line;\n     my $last_line_was_empty=0;\n     foreach $line (split /\\n/, $log{$key})\n     {\n        print CONFIG_FILE \"   ###$line\\n\" unless \n\t      ( ($last_line_was_empty eq 1) && ($line =~ /^\\s*$/));\n        $last_line_was_empty= ($line =~ /^\\s*$/)?1:0;\n     };     \n  }\n  close CONFIG_FILE;\n}\n\n#\n# Save 'incomplete' in the limits file to be able to continue if\n# crash-me dies because of a bug in perl/DBI\n\nsub save_incomplete\n{\n  my ($limit,$prompt)= @_;\n  save_config_data($limit,\"incompleted\",$prompt) if ($opt_restart);\n}\n\n\nsub check_repeat\n{\n  my ($sth,$limit)=@_;\n  my ($row);\n\n  return 0 if (!($row=$sth->fetchrow_arrayref));\n  return (defined($row->[0]) && ('a' x $limit) eq $row->[0]) ? 1 : 0;\n}\n\n\nsub min\n{\n  my($min)=$_[0];\n  my($i);\n  for ($i=1 ; $i <= $#_; $i++)\n  {\n    $min=$_[$i] if ($min > $_[$i]);\n  }\n  return $min;\n}\n\nsub sql_concat\n{\n  my ($a,$b)= @_;\n  return \"$a || $b\" if ($limits{'func_sql_concat_as_||'} eq 'yes');\n  return \"concat($a,$b)\" if ($limits{'func_odbc_concat'} eq 'yes');\n  return \"$a + $b\" if ($limits{'func_extra_concat_as_+'} eq 'yes');\n  return undef;\n}\n\n#\n# Returns a list of statements to create a table in a portable manner\n# but still utilizing features in the databases.\n#\n\nsub create_table\n{\n  my($table_name,$fields,$index,$extra) = @_;\n  my($query,$nr,$parts,@queries,@index);\n\n  $extra=\"\" if (!defined($extra));\n\n  $query=\"create table $table_name (\";\n  $nr=0;\n  foreach $field (@$fields)\n  {\n    $query.= $field . ',';\n  }\n  foreach $index (@$index)\n  {\n    $index =~ /\\(([^\\(]*)\\)$/i;\n    $parts=$1;\n    if ($index =~ /^primary key/)\n    {\n      if ($limits{'primary_key_in_create'} eq 'yes')\n      {\n\t$query.= $index . ',';\n      }\n      else\n      {\n\tpush(@queries,\n\t     \"create unique index ${table_name}_prim on $table_name ($parts)\");\n      }\n    }\n    elsif ($index =~ /^unique/)\n    {\n      if ($limits{'unique_in_create'} eq 'yes')\n      {\n\t$query.= \"unique ($parts),\";\n      }\n      else\n      {\n\t$nr++;\n\tpush(@queries,\n\t     \"create unique index ${table_name}_$nr on $table_name ($parts)\");\n\n      }\n    }\n    else\n    {\n      if ($limits{'index_in_create'} eq 'yes')\n      {\n\t$query.= \"index ($parts),\";\n      }\n      else\n      {\n\t$nr++;\n\tpush(@queries,\n\t     \"create index ${table_name}_$nr on $table_name ($1)\");\n      }\n    }\n  }\n  chop($query);\n  $query.= \") $extra\";\n  unshift(@queries,$query);\n  return @queries;\n}\n\n\n#\n# This is used by some query packages to change:\n# %d -> limit\n# %s -> 'a' x limit\n# %v -> \"1,1,1,1,1\" where there are 'limit' number of ones\n# %f -> q1,q2,q3....\n# %F -> q1 integer,q2 integer,q3 integer....\n\nsub fix_query\n{\n  my ($query,$limit)=@_;\n  my ($repeat,$i);\n\n  return $query if !(defined($query));\n  $query =~ s/%d/$limit/g;\n  if ($query =~ /%s/)\n  {\n    $repeat= 'a' x $limit;\n    $query =~ s/%s/$repeat/g;\n  }\n  if ($query =~ /%v/)\n  {\n    $repeat= '1,' x $limit;\n    chop($repeat);\n    $query =~ s/%v/$repeat/g;\n  }\n  if ($query =~ /%f/)\n  {\n    $repeat=\"\";\n    for ($i=1 ; $i <= $limit ; $i++)\n    {\n      $repeat.=\"q$i,\";\n    }\n    chop($repeat);\n    $query =~ s/%f/$repeat/g;\n  }\n  if ($query =~ /%F/)\n  {\n    $repeat=\"\";\n    for ($i=1 ; $i <= $limit ; $i++)\n    {\n      $repeat.=\"q$i integer,\";\n    }\n    chop($repeat);\n    $query =~ s/%F/$repeat/g;\n  }\n  return $query;\n}\n\n\n#\n# Different query packages\n#\n\npackage query_repeat;\n\nsub new\n{\n  my ($type,$init,$query,$add1,$add_mid,$add,$add_end,$end_query,$cleanup,\n      $max_limit, $check, $offset)=@_;\n  my $self={};\n  if (defined($init) && $#$init != -1)\n  {\n    $self->{'init'}=$init;\n  }\n  $self->{'query'}=$query;\n  $self->{'add1'}=$add1;\n  $self->{'add_mid'}=$add_mid;\n  $self->{'add'}=$add;\n  $self->{'add_end'}=$add_end;\n  $self->{'end_query'}=$end_query;\n  $self->{'cleanup'}=$cleanup;\n  $self->{'max_limit'}=(defined($max_limit) ? $max_limit : $main::query_size);\n  $self->{'check'}=$check;\n  $self->{'offset'}=$offset;\n  $self->{'printf'}= ($add =~ /%d/);\n  bless $self;\n}\n\nsub query\n{\n  my ($self,$limit)=@_;\n  if (!$self->{'printf'})\n  {\n    return $self->{'query'} . ($self->{'add'} x $limit) .\n      ($self->{'add_end'} x $limit) . $self->{'end_query'};\n  }\n  my ($tmp,$tmp2,$tmp3,$i);\n  $tmp=$self->{'query'};\n  if ($self->{'add1'})\n  {\n    for ($i=0; $i < $limit ; $i++)\n    {\n      $tmp3 = $self->{'add1'};\n      $tmp3 =~ s/%d/$i/g;\n      $tmp  .= $tmp3;\n    }\n  }\n  $tmp .= \" \".$self->{'add_mid'};\n  if ($self->{'add'})\n  {\n    for ($i=0; $i < $limit ; $i++)\n    {\n      $tmp2 = $self->{'add'};\n      $tmp2 =~ s/%d/$i/g;\n      $tmp  .= $tmp2;\n    }\n  }\n  return ($tmp .\n\t  ($self->{'add_end'} x $limit) . $self->{'end_query'});\n}\n\nsub max_limit\n{\n  my ($self)=@_;\n  my $tmp;\n  $tmp=int(($main::limits{\"query_size\"}-length($self->{'query'})\n\t    -length($self->{'add_mid'})-length($self->{'end_query'}))/\n\t   (length($self->{'add1'})+\n\t   length($self->{'add'})+length($self->{'add_end'})));\n  return main::min($self->{'max_limit'},$tmp);\n}\n\n\nsub cleanup\n{\n  my ($self)=@_;\n  my($tmp,$statement);\n  $tmp=$self->{'cleanup'};\n  foreach $statement (@$tmp)\n  {\n    main::safe_query($statement) if (defined($statement) && length($statement));\n  }\n}\n\nsub check\n{\n  my ($self,$sth)=@_;\n  my $check=$self->{'check'};\n  return &$check($sth,$self->{'limit'}) if (defined($check));\n  return 1;\n}\n\nsub check_query\n{\n  return undef;\n}\n\n\npackage query_num;\n\nsub new\n{\n  my ($type,$query,$end_query,$cleanup,$max_limit,$check)=@_;\n  my $self={};\n  $self->{'query'}=$query;\n  $self->{'end_query'}=$end_query;\n  $self->{'cleanup'}=$cleanup;\n  $self->{'max_limit'}=$max_limit;\n  $self->{'check'}=$check;\n  bless $self;\n}\n\nsub query\n{\n  my ($self,$i)=@_;\n  $self->{'limit'}=$i;\n  return \"$self->{'query'}$i$self->{'end_query'}\";\n}\n\nsub max_limit\n{\n  my ($self)=@_;\n  return $self->{'max_limit'};\n}\n\nsub cleanup\n{\n  my ($self)=@_;\n  my($statement);\n  foreach $statement ($self->{'$cleanup'})\n  {\n    main::safe_query($statement) if (defined($statement) && length($statement));\n  }\n}\n\n\nsub check\n{\n  my ($self,$sth)=@_;\n  my $check=$self->{'check'};\n  return &$check($sth,$self->{'limit'}) if (defined($check));\n  return 1;\n}\n\nsub check_query\n{\n  return undef;\n}\n\n#\n# This package is used when testing CREATE TABLE!\n#\n\npackage query_table;\n\nsub new\n{\n  my ($type,$query, $add, $end_query, $extra_init, $safe_query, $check,\n      $cleanup, $max_limit, $offset)=@_;\n  my $self={};\n  $self->{'query'}=$query;\n  $self->{'add'}=$add;\n  $self->{'end_query'}=$end_query;\n  $self->{'extra_init'}=$extra_init;\n  $self->{'safe_query'}=$safe_query;\n  $self->{'check'}=$check;\n  $self->{'cleanup'}=$cleanup;\n  $self->{'max_limit'}=$max_limit;\n  $self->{'offset'}=$offset;\n  bless $self;\n}\n\n\nsub query\n{\n  my ($self,$limit)=@_;\n  $self->{'limit'}=$limit;\n  $self->cleanup();     # Drop table before create\n\n  my ($tmp,$tmp2,$i,$query,@res);\n  $tmp =$self->{'query'};\n  $tmp =~ s/%d/$limit/g;\n  for ($i=1; $i <= $limit ; $i++)\n  {\n    $tmp2 = $self->{'add'};\n    $tmp2 =~ s/%d/$i/g;\n    $tmp  .= $tmp2;\n  }\n  push(@res,$tmp . $self->{'end_query'});\n  $tmp=$self->{'extra_init'};\n  foreach $query (@$tmp)\n  {\n    push(@res,main::fix_query($query,$limit));\n  }\n  return \\@res;\n}\n\n\nsub max_limit\n{\n  my ($self)=@_;\n  return $self->{'max_limit'};\n}\n\n\nsub check_query\n{\n  my ($self)=@_;\n  return main::fix_query($self->{'safe_query'},$self->{'limit'});\n}\n\nsub check\n{\n  my ($self,$sth)=@_;\n  my $check=$self->{'check'};\n  return 0 if (!($row=$sth->fetchrow_arrayref));\n  if (defined($check))\n  {\n    return (defined($row->[0]) &&\n\t    $row->[0] eq main::fix_query($check,$self->{'limit'})) ? 1 : 0;\n  }\n  return 1;\n}\n\n\n# Remove table before and after create table query\n\nsub cleanup()\n{\n  my ($self)=@_;\n  main::safe_query(main::fix_query($self->{'cleanup'},$self->{'limit'}));\n}\n\n#\n# Package to do many queries with %d, and %s substitution\n#\n\npackage query_many;\n\nsub new\n{\n  my ($type,$query,$safe_query,$check_result,$cleanup,$max_limit,$offset,\n      $safe_cleanup)=@_;\n  my $self={};\n  $self->{'query'}=$query;\n  $self->{'safe_query'}=$safe_query;\n  $self->{'check'}=$check_result;\n  $self->{'cleanup'}=$cleanup;\n  $self->{'max_limit'}=$max_limit;\n  $self->{'offset'}=$offset;\n  $self->{'safe_cleanup'}=$safe_cleanup;\n  bless $self;\n}\n\n\nsub query\n{\n  my ($self,$limit)=@_;\n  my ($queries,$query,@res);\n  $self->{'limit'}=$limit;\n  $self->cleanup() if (defined($self->{'safe_cleanup'}));\n  $queries=$self->{'query'};\n  foreach $query (@$queries)\n  {\n    push(@res,main::fix_query($query,$limit));\n  }\n  return \\@res;\n}\n\nsub check_query\n{\n  my ($self)=@_;\n  return main::fix_query($self->{'safe_query'},$self->{'limit'});\n}\n\nsub cleanup\n{\n  my ($self)=@_;\n  my($tmp,$statement);\n  return if (!defined($self->{'cleanup'}));\n  $tmp=$self->{'cleanup'};\n  foreach $statement (@$tmp)\n  {\n    if (defined($statement) && length($statement))\n    {\n      main::safe_query(main::fix_query($statement,$self->{'limit'}));\n    }\n  }\n}\n\n\nsub check\n{\n  my ($self,$sth)=@_;\n  my ($check,$row);\n  return 0 if (!($row=$sth->fetchrow_arrayref));\n  $check=$self->{'check'};\n  if (defined($check))\n  {\n    return (defined($row->[0]) &&\n\t    $row->[0] eq main::fix_query($check,$self->{'limit'})) ? 1 : 0;\n  }\n  return 1;\n}\n\nsub max_limit\n{\n  my ($self)=@_;\n  return $self->{'max_limit'};\n}\n\n#\n# Used to find max supported row length\n#\n\npackage query_row_length;\n\nsub new\n{\n  my ($type,$create,$null,$drop,$max_limit)=@_;\n  my $self={};\n  $self->{'table_name'}=$create;\n  $self->{'null'}=$null;\n  $self->{'cleanup'}=$drop;\n  $self->{'max_limit'}=$max_limit;\n  bless $self;\n}\n\n\nsub query\n{\n  my ($self,$limit)=@_;\n  my ($res,$values,$size,$length,$i);\n  $self->{'limit'}=$limit;\n\n  $res=\"\";\n  $size=main::min($main::limits{'max_char_size'},255);\n  $size = 255 if (!$size); # Safety\n  for ($length=$i=0; $length + $size <= $limit ; $length+=$size, $i++)\n  {\n    $res.= \"q$i char($size) $self->{'null'},\";\n    $values.=\"'\" . ('a' x $size) . \"',\";\n  }\n  if ($length < $limit)\n  {\n    $size=$limit-$length;\n    $res.= \"q$i char($size) $self->{'null'},\";\n    $values.=\"'\" . ('a' x $size) . \"',\";\n  }\n  chop($res);\n  chop($values);\n  return [\"create table \" . $self->{'table_name'} . \" ($res)\",\n\t  \"insert into \" . $self->{'table_name'} . \" values ($values)\"];\n}\n\nsub max_limit\n{\n  my ($self)=@_;\n  return $self->{'max_limit'};\n}\n\nsub cleanup\n{\n  my ($self)=@_;\n  main::safe_query($self->{'cleanup'});\n}\n\n\nsub check\n{\n  return 1;\n}\n\nsub check_query\n{\n  return undef;\n}\n\n#\n# Used to find max supported index length\n#\n\npackage query_index_length;\n\nsub new\n{\n  my ($type,$create,$drop,$max_limit)=@_;\n  my $self={};\n  $self->{'create'}=$create;\n  $self->{'cleanup'}=$drop;\n  $self->{'max_limit'}=$max_limit;\n  bless $self;\n}\n\n\nsub query\n{\n  my ($self,$limit)=@_;\n  my ($res,$size,$length,$i,$parts,$values);\n  $self->{'limit'}=$limit;\n\n  $res=$parts=$values=\"\";\n  $size=main::min($main::limits{'max_index_part_length'},\n       $main::limits{'max_char_size'});\n  $size=1 if ($size == 0);\t# Avoid infinite loop errors\n  for ($length=$i=0; $length + $size <= $limit ; $length+=$size, $i++)\n  {\n    $res.= \"q$i char($size) not null,\";\n    $parts.= \"q$i,\";\n    $values.= \"'\" . ('a' x $size) . \"',\";\n  }\n  if ($length < $limit)\n  {\n    $size=$limit-$length;\n    $res.= \"q$i char($size) not null,\";\n    $parts.=\"q$i,\";\n    $values.= \"'\" . ('a' x $size) . \"',\";\n  }\n  chop($parts);\n  chop($res);\n  chop($values);\n  if ($main::limits{'unique_in_create'} eq 'yes')\n  {\n    return [$self->{'create'} . \"($res,unique ($parts))\",\n\t    \"insert into crash_q values($values)\"];\n  }\n  return [$self->{'create'} . \"($res)\",\n\t  \"create index crash_q_index on crash_q ($parts)\",\n\t  \"insert into crash_q values($values)\"];\n}\n\nsub max_limit\n{\n  my ($self)=@_;\n  return $self->{'max_limit'};\n}\n\nsub cleanup\n{\n  my ($self)=@_;\n  main::safe_query($self->{'cleanup'});\n}\n\n\nsub check\n{\n  return 1;\n}\n\nsub check_query\n{\n  return undef;\n}\n\n\n\n### TODO:\n# OID test instead of / in addition to _rowid\n", "num_lines": 5026}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /usr/bin/perl\n\n####\n#### Hello ... this is a heavily hacked script by Luuk \n#### instead of printing the result it makes a nice gif\n#### when you want to look at the code ... beware of the \n#### ugliest code ever seen .... but it works ...\n#### and that's sometimes the only thing you want ... isn't it ...\n#### as the original script ... Hope you like it\n####\n#### Greetz..... Luuk de Boer 1997.\n####\n\n## if you want the seconds behind the bar printed or not ...\n## or only the one where the bar is too big for the graph ...\n## look at line 535 of this program and below ...\n## look in sub calculate for allmost all hard/soft settings :-)\n\n# a little program to generate a table of results\n# just read all the RUN-*.log files and format them nicely\n# Made by Luuk de Boer\n# Patched by Monty\n\nuse Getopt::Long;\nuse GD;\n\n$opt_server=\"mysql\";\n$opt_cmp=\"mysql,pg,solid\";\n$opt_cmp=\"msql,mysql,pg,solid\";\n$opt_cmp=\"empress,mysql,pg,solid\";\n$opt_dir=\"output\";\n$opt_machine=\"\";\n$opt_relative=$opt_same_server=$opt_help=$opt_Information=$opt_skip_count=0;\n\nGetOptions(\"Information\",\"help\",\"server=s\",\"cmp=s\",\"machine=s\",\"relative\",\"same-server\",\"dir=s\",\"skip-count\") || usage();\n\nusage() if ($opt_help || $opt_Information);\n\nif ($opt_same_server)\n{\n  $files=\"$opt_dir/RUN-$opt_server-*$opt_machine\";\n}\nelse\n{\n  $files=\"$opt_dir/RUN-*$opt_machine\";\n}\n$files.= \"-cmp-$opt_cmp\" if (length($opt_cmp));\n\n$automatic_files=0;\nif ($#ARGV == -1)\n{\n  @ARGV=glob($files);\n  $automatic_files=1;\n}\n\n\n#\n# Go trough all RUN files and gather statistics.\n#\n\nforeach (@ARGV)\n{\n  $filename = $_;\n  next if (defined($found{$_})); # remove duplicates\n  $found{$_}=1;\n  /RUN-(.*)$/;\n  $prog = $1;\n  push(@key_order,$prog);\n  $next = 0;\n  open(TMP, \"<$filename\") || die \"Can't open $filename: $!\\n\";\n  while (<TMP>)\n  {\n    chomp;\n    if ($next == 0) {\n      if (/Server version:\\s+(\\S+.*)/i)\n      {\n\t$tot{$prog}{'server'} = $1;\n      }\n      elsif (/Arguments:\\s+(.+)/i)\n      {\n\t$tot{$prog}{'arguments'} = $1;\n\t# Remove some standard, not informative arguments\n\t$tot{$prog}{'arguments'} =~ s/--log|--use-old-results|--server=\\S+|--cmp=\\S+|--user=\\S+|--pass=\\S+|--machine=\\S+//g;\n\t$tot{$prog}{'arguments'} =~ s/\\s+/ /g;\n      }\n      elsif (/Comments:\\s+(.+)/i) {\n\t$tot{$prog}{'comments'} = $1;\n      } elsif (/^(\\S+):\\s*(estimated\\s|)total\\stime:\\s+(\\d+)\\s+secs/i)\n      {\n\t$tmp = $1; $tmp =~ s/://;\n\t$tot{$prog}{$tmp} = [ $3, (length($2) ? \"+\" : \"\")];\n\t$op1{$tmp} = $tmp;\n      } elsif (/Totals per operation:/i) {\n\t$next = 1;\n\tnext;\n      }\n    }\n    elsif ($next == 1)\n    {\n      if (/^(\\S+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s+([\\d.]+)\\s*([+|?])*/)\n      {\n\t$tot1{$prog}{$1} = [$2,$6,$7];\n\t$op{$1} = $1;\n#print \"TEST - $_ \\n * $prog - $1 - $2 - $6 - $7 ****\\n\";\n# $prog - filename\n# $1 - operation\n# $2 - time in secs\n# $6 - number of loops\n# $7 - nothing / + / ? / * => estimated time ...\n      # get the highest value ....\n      $highest = ($2/$6) if (($highest < ($2/$6)) && ($1 !~/TOTALS/i));\n      $gifcount++;\n      $giftotal += ($2/$6);\n      }\n    }\n  }\n}\n\nif (!%op)\n{\n  print \"Didn't find any files matching: '$files'\\n\";\n  print \"Use the --cmp=server,server option to compare benchmarks\\n\";\n  exit 1;\n}\n\n\n# everything is loaded ...\n# now we have to create a fancy output :-)\n\n# I prefer to redirect scripts instead to force it to file ; Monty\n#\n# open(RES, \">$resultfile\") || die \"Can't write to $resultfile: $!\\n\";\n# select(RES)\n#\n\n#print <<EOF;\n#<cut for this moment>\n#\n#EOF\n\nif ($opt_relative)\n{\n#  print \"Column 1 is in seconds. All other columns are presented relative\\n\";\n#  print \"to this. 1.00 is the same, bigger numbers indicates slower\\n\\n\";\n}\n\n#print \"The result logs which where found and the options:\\n\";\n\nif ($automatic_files)\n{\n  if ($key_order[$i] =~ /^$opt_server/)\n  {\n    if ($key_order[$i] =~ /^$opt_server/)\n    {\n      unshift(@key_order,$key_order[$i]);\n      splice(@key_order,$i+1,1);\n    }\n  }\n}\n# extra for mysql and mysql_pgcc\n#$number1 = shift(@key_order);\n#$number2 = shift(@key_order);\n#unshift(@key_order,$number1);\n#unshift(@key_order,$number2);\n\n# Print header\n\n$column_count=0;\nforeach $key (@key_order)\n{\n  $column_count++;\n#  printf \"%2d %-40.40s: %s %s\\n\", $column_count, $key,\n#  $tot{$key}{'server'}, $tot{$key}{'arguments'};\n#  print \"Comments: $tot{$key}{'comments'}\\n\"\n#    if ($tot{$key}{'comments'} =~ /\\w+/);\n}\n\n#print \"\\n\";\n\n$namewidth=$opt_skip_count ? 20 :25;\n$colwidth= $opt_relative ? 9 : 6;\n\nprint_sep(\"=\");\n#printf \"%-$namewidth.${namewidth}s|\", \"Operation\";\n$count = 1;\nforeach $key (@key_order)\n{\n#  printf \"%${colwidth}d|\", $count;\n  $count++;\n}\n#print \"\\n\";\n#print_sep(\"-\");\n#print_string(\"Results per test:\");\n#print_sep(\"-\");\n\nforeach $key (sort {$a cmp $b} keys %op1)\n{\n#  printf \"%-$namewidth.${namewidth}s|\", $key;\n  $first=undef();\n  foreach $server (@key_order)\n  {\n    print_value($first,$tot{$server}{$key}->[0],$tot{$server}{$key}->[1]);\n    $first=$tot{$server}{$key}->[0] if (!defined($first));\n  }\n#  print \"\\n\";\n}\n\nprint_sep(\"-\");\nprint_string(\"The results per operation:\");\nprint_sep(\"-\");\n$luukcounter = 1;\nforeach $key (sort {$a cmp $b} keys %op)\n{\n  next if ($key =~ /TOTALS/i);\n  $tmp=$key;\n  $tmp.= \" (\" . $tot1{$key_order[0]}{$key}->[1] . \")\" if (!$skip_count);\n#  printf \"%-$namewidth.${namewidth}s|\", $tmp;\n  $first=undef();\n  foreach $server (@key_order)\n  {\n    print_value($first,$tot1{$server}{$key}->[0],$tot1{$server}{$key}->[2]);\n    $first=$tot1{$server}{$key}->[0] if (!defined($first));\n  }\n#  print \"\\n\";\n  $luukcounter++;\n}\n\n#print_sep(\"-\");\n$key=\"TOTALS\";\n#printf \"%-$namewidth.${namewidth}s|\", $key;\n$first=undef();\nforeach $server (@key_order)\n{\n#  print_value($first,$tot1{$server}{$key}->[0],$tot1{$server}{$key}->[2]);\n  $first=$tot1{$server}{$key}->[0] if (!defined($first));\n}\n#print \"\\n\";\n#print_sep(\"=\");\n&make_gif;\n\nexit 0;\n\n#\n# some format functions;\n#\n\nsub print_sep\n{\n  my ($sep)=@_;\n#  print $sep x ($namewidth + (($colwidth+1) * $column_count)+1),\"\\n\";\n}\n\n\nsub print_value\n{\n  my ($first,$value,$flags)=@_;\n  my ($tmp);\n\n  if (defined($value))\n  {\n    if (!defined($first) || !$opt_relative)\n    {\n      $tmp=sprintf(\"%d\",$value);\n    }\n    else\n    {\n      $first=1 if (!$first);\t# Assume that it took one second instead of 0\n      $tmp= sprintf(\"%.2f\",$value/$first);\n    }\n    if (defined($flags))\n    {\n      $tmp=\"+\".$tmp if ($flags =~ /\\+/);\n      $tmp=\"?\".$tmp if ($flags =~ /\\?/);\n    }\n  }\n  else\n  {\n    $tmp=\"\";\n  }\n  $tmp= \" \" x ($colwidth-length($tmp)) . $tmp if (length($tmp) < $colwidth);\n#  print $tmp . \"|\";\n}\n\n\nsub print_string\n{\n  my ($str)=@_;\n  my ($width);\n  $width=$namewidth + ($colwidth+1)*$column_count;\n\n  $str=substr($str,1,$width) if (length($str) > $width);\n#  print($str,\" \" x ($width - length($str)),\"|\\n\");\n}\n\nsub usage\n{\n  exit(0);\n}\n\n\n\n###########################################\n###########################################\n###########################################\n# making here a gif of the results ... (lets try it :-))\n# luuk .... 1997\n###########################################\n## take care that $highest / $giftotal / $gifcount / $luukcounter \n## are getting there value above ... so don't forget them while \n## copying the code to some other program ....\n\nsub make_gif {\n  &gd; # some base things ....\n  &legend; # make the nice legend\n  &lines; # yep sometimes you have to print some lines\n  &gif(\"gif/benchmark2-\".$opt_cmp); # and finally we can print all to a gif file ...\n}\n##### mmm we are finished now ... \n\n\n# first we have to calculate some limits and some other stuff\nsub calculate {\n# here is the list which I have to know to make everything .....\n# the small border width ... \t\t\t\t\t$sm_border = \n# the border default\t\t\t\t\t\t$border = \n# the step default ... if it must be calculated then no value\t$step =\n# the highest number\t\t\t\t\t\t$highest = \n# the max length of the text of the x borders\t\t\t$max_len_lb=\n# the max length of a legend entry\t\t\t\t$max_len_le=\n# number of entries in the legend\t\t\t\t$num_legen =\n# the length of the color blocks for the legend\t\t\t$legend_block=\n# the width of the gif ...if it must be calculated - no value   $width =\n# the height of the gif .. if it must be calculated - no value\t$height =\n# the width of the grey field ' \t'\t'\t'\t$width_grey=\n# the height of the grey field '\t'\t'\t'\t$height_grey=\n# number of dashed lines\t\t\t\t\t$lines=\n# if bars must overlap how much they must be overlapped\t\t$overlap=\n# titlebar title of graph in two colors big\t\t\t$titlebar=\n# titlebar1 sub title of graph in small font in black\t\t$titlebar1=\n# xlabel\t\t\t\t\t\t\t$xlabel=\n# ylabel\t\t\t\t\t\t\t$ylabel=\n# the name of the gif ...\t\t\t\t\t$name=\n# then the following things must be knows .....\n# xlabel below or on the left side ?\n# legend yes/no?\n# where must the legend be placed?\n# must the xlabel be printed horizontal or vertical?\n# must the ylabel be printed horizontal or vertical?\n# must the graph be a line or a bar graph?\n# is a xlabel several different entries or some sub entries of one?\n#    so xlabel 1 => test1=10, test2=15, test3=7 etc\n#    or xlabel 1 => test1a=12, test1b=10, test1c=7 etc\n# must the bars overlap (only with the second example I think)\n# must the number be printed above or next to the bar?\n# when must the number be printed .... only when it extends the graph ...???\n# the space between the bars .... are that the same width of the bars ...\n#    or is it a separate space ... defined ???\n# must the date printed below or some where else ....\n\n#calculate all space for text and other things ....\n  $sm_border = 8; # the grey border around ...\n  $border = 40; #default ...\n  $left_border = 2.75 * $border; #default ...\n  $right_border = $border; #default ...\n  $up_border = $border; #default ...\n  $down_border = $border; # default ...\n  $step = ($height - $up_border - $down_border)/ ($luukcounter + (($#key_order + 1) * $luukcounter));\n  # can set $step to get nice graphs ... and change the format ...\n  $step = 8; # set hard the step value\n  \n  $gifavg = ($giftotal/$gifcount);\n  $highest = 2 * $gifavg;\n  $highest = 1; # set hard the highest value ...\n  $xhigh = int($highest + .5 * $highest);\n  \n  # here to get the max lenght of the test entries ...\n  # so we can calculate the with of the left border\n  foreach $oper (sort keys (%op)) {\n    $max_len_lb = length($oper) if (length($oper) > $max_len_lb);\n#    print \"oper = $oper - $max_len_lb\\n\";\n  }\n  $max_len_lb = $max_len_lb * gdSmallFont->width;\n  $left_border = (3*$sm_border) + $max_len_lb;\n  $down_border = (4*$sm_border) + (gdSmallFont->width*(length($xhigh)+3)) + (gdSmallFont->height *2); \n  $right_border = (3*$sm_border) + 3 + (gdSmallFont->width*(length($highest)+5));\n\n  # calculate the space for the legend .....\n  foreach $key (@key_order) {\n    $tmp = $key;\n    $tmp =~ s/-cmp-$opt_cmp//i;\n    $giflegend = sprintf \"%-24.24s: %-40.40s\",$tmp,$tot{$key}{'server'};\n    $max_len_le = length($giflegend) if (length($giflegend) > $max_len_le);\n  }\n  $max_len_le = $max_len_le * gdSmallFont->width;\n  $legend_block = 10; # the length of the block in the legend\n  $max_high_le = (($#key_order + 1)*(gdSmallFont->height+2)) + (2*$legend_block);\n  $down_border += $max_high_le;\n  $up_border = (5 * $sm_border) + gdSmallFont->height + gdLargeFont->height;\n  \n  print \"Here some things we already know ....\\n\";\n#  print \"luukcounter = $luukcounter (number of tests)\\n\";\n#  print \"gifcount = $gifcount (number of total entries)\\n\";\n#  print \"giftotal = $giftotal (total secs)\\n\";\n#  print \"gifavg = $gifavg\\n\";\n#  print \"highest = $highest\\n\";\n#  print \"xhigh = $xhigh\\n\";\n#  print \"step = $step -- $#key_order\\n\";\n#  print \"max_len_lb = $max_len_lb\\n\";\n#  printf \"Small- width %d - height %s\\n\",gdSmallFont->width,gdSmallFont->height;\n#  printf \"Tiny- width %d - height %s\\n\",gdTinyFont->width,gdTinyFont->height;\n}\n\nsub gd {\n  &calculate;\n  $width = 600; # the width ....\n  $height = 500; # the height ... \n  $width_greyfield = 430;\n  # when $step is set ... count the height ....????\n  $width = $width_greyfield + $left_border + $right_border;\n  $height = ($step * ($luukcounter + ($luukcounter * ($#key_order + 1)))) + $down_border + $up_border;\n  $b_width = $width - ($left_border + $right_border); # width within the grey field\n  $overlap = 0; # how far each colum can fall over each other ...nice :-)\n\n  # make the gif image ....\n  $im = new GD::Image($width,$height);\n\n  # allocate the colors to use ...\n  $white \t\t= $im->colorAllocate(255,255,255);\n  $black \t\t= $im->colorAllocate(0,0,0);\n  $paper_white \t\t= $im->colorAllocate(220, 220, 220);\n  $grey1 \t\t= $im->colorAllocate(240, 240, 240);\n  $grey4 \t\t= $im->colorAllocate(229, 229, 229);\n  $grey2 \t\t= $im->colorAllocate(102, 102, 102);\n  $grey3 \t\t= $im->colorAllocate(153, 153, 153);\n  \n  $red \t\t\t= $im->colorAllocate(205,0,0); # msql\n  $lred \t\t= $im->colorAllocate(255,0,0);\n  $blue \t\t= $im->colorAllocate(0,0,205); # mysql\n  $lblue \t\t= $im->colorAllocate(0,0,255); # mysql_pgcc\n  $green \t\t= $im->colorAllocate(0, 205, 0); # postgres\n  $lgreen \t\t= $im->colorAllocate(0, 255, 0); # pg_fast\n  $orange \t\t= $im->colorAllocate(205,133, 0); # solid\n  $lorange \t\t= $im->colorAllocate(255, 165, 0); # Adabas\n  $yellow \t\t= $im->colorAllocate(205,205,0);  # empress\n  $lyellow \t\t= $im->colorAllocate(255,255,0);\n  $magenta \t\t= $im->colorAllocate(255,0,255); # oracle\n  $lmagenta \t\t= $im->colorAllocate(255,200,255);\n  $cyan \t\t= $im->colorAllocate(0,205,205); # sybase\n  $lcyan \t\t= $im->colorAllocate(0,255,255);\n  $sienna \t\t= $im->colorAllocate(139,71,38); # db2\n  $lsienna \t\t= $im->colorAllocate(160,82,45);\n  $coral \t\t= $im->colorAllocate(205,91,69); # Informix\n  $lcoral \t\t= $im->colorAllocate(255,114,86);\n  $peach\t\t= $im->colorAllocate(205,175,149);\n  $lpeach\t\t= $im->colorAllocate(255,218,185);\n  \n  @colors = ($red, $blue, $green, $orange, $yellow, $magenta, $cyan, $sienna, $coral, $peach);\n  @lcolors = ($lred, $lblue, $lgreen, $lorange, $lyellow, $lmagenta, $lcyan, $lsienna, $lcoral, $lpeach);\n\n  # set a color per server so in every result it has the same color ....\n  foreach $key (@key_order) {\n    if ($tot{$key}{'server'} =~ /mysql/i) {\n      if ($key =~ /mysql_pgcc/i || $key =~ /mysql_odbc/i || $key =~ /mysql_fast/i) {\n        $tot{$key}{'color'} = $lblue;\n      } else {\n        $tot{$key}{'color'} = $blue;\n      }\n    } elsif ($tot{$key}{'server'} =~ /msql/i) {\n      $tot{$key}{'color'} = $lred;\n    } elsif ($tot{$key}{'server'} =~ /postgres/i) {\n      if ($key =~ /pg_fast/i) {\n        $tot{$key}{'color'} = $lgreen;\n      } else {\n        $tot{$key}{'color'} = $green;\n      }\n    } elsif ($tot{$key}{'server'} =~ /solid/i) {\n      $tot{$key}{'color'} = $lorange;\n    } elsif ($tot{$key}{'server'} =~ /empress/i) {\n      $tot{$key}{'color'} = $lyellow;\n    } elsif ($tot{$key}{'server'} =~ /oracle/i) {\n      $tot{$key}{'color'} = $magenta;\n    } elsif ($tot{$key}{'server'} =~ /sybase/i) {\n      $tot{$key}{'color'} = $cyan;\n    } elsif ($tot{$key}{'server'} =~ /db2/i) {\n      $tot{$key}{'color'} = $sienna;\n    } elsif ($tot{$key}{'server'} =~ /informix/i) {\n      $tot{$key}{'color'} = $coral;\n    } elsif ($tot{$key}{'server'} =~ /microsoft/i) {\n      $tot{$key}{'color'} = $peach;\n    } elsif ($tot{$key}{'server'} =~ /access/i) {\n      $tot{$key}{'color'} = $lpeach;\n    } elsif ($tot{$key}{'server'} =~ /adabas/i) {\n      $tot{$key}{'color'} = $lorange;\n    }\n  }\n\n  # make the nice little borders\n  # left bar\n  $poly0 = new GD::Polygon;\n  $poly0->addPt(0,0);\n  $poly0->addPt($sm_border,$sm_border);\n  $poly0->addPt($sm_border,($height - $sm_border));\n  $poly0->addPt(0,$height);\n  $im->filledPolygon($poly0,$grey1);\n  $im->polygon($poly0, $grey4);\n  # upper bar\n  $poly3 = new GD::Polygon;\n  $poly3->addPt(0,0);\n  $poly3->addPt($sm_border,$sm_border);\n  $poly3->addPt(($width - $sm_border),$sm_border);\n  $poly3->addPt($width,0);\n  $im->polygon($poly3, $grey4);\n  $tmptime = localtime(time);\n  $im->string(gdSmallFont,($width - $sm_border - (gdSmallFont->width * length($tmptime))),($height - ($sm_border) - gdSmallFont->height), $tmptime, $grey3);\n  \n  # right bar\n  $poly1 = new GD::Polygon;\n  $poly1->addPt($width,0);\n  $poly1->addPt(($width - $sm_border),$sm_border);\n  $poly1->addPt(($width - $sm_border),($height - $sm_border));\n  $poly1->addPt($width,$height);\n  $im->filledPolygon($poly1, $grey3);\n  $im->stringUp(gdSmallFont,($width - 10),($height - (2 * $sm_border)), \"Made by Luuk de Boer - 1997 (c)\", $blue);\n  #below bar\n  $poly2 = new GD::Polygon;\n  $poly2->addPt(0,$height);\n  $poly2->addPt($sm_border,($height - $sm_border));\n  $poly2->addPt(($width - $sm_border),($height - $sm_border));\n  $poly2->addPt($width,$height);\n  $im->filledPolygon($poly2, $grey2);\n  \n  # do the black line around where in you will print ... (must be done at last\n  # but is hard to develop with ... but the filled grey must be done first :-)\n  $im->filledRectangle($left_border,$up_border,($width - ($right_border)),($height-$down_border),$grey4);\n\n\n  # print the nice title ...\n  $titlebar = \"MySQL Benchmark results\"; # head title ...\n  $titlebar1 = \"Compare $opt_cmp \"; # sub title\n  $header2 = \"seconds/test\"; # header value\n  $center = ($width / 2) - ((gdLargeFont->width * length($titlebar)) / 2);\n  $center1 = ($width / 2) - ((gdSmallFont->width * length($titlebar1)) / 2);\n  $center2 = ($width_greyfield/2) - ((gdSmallFont->width*length($header2))/2);\n  $bovenkant = $sm_border * 3;\n  $bovenkant1 = $bovenkant + gdLargeFont->height + (.5*$sm_border);\n  $bovenkant2 = $height - $down_border + (1*$sm_border) + (gdSmallFont->width*(length($xhigh)+3)); \n  $im->string(gdLargeFont,($center),($bovenkant + 1), $titlebar, $grey3);\n  $im->string(gdLargeFont,($center),($bovenkant), $titlebar, $red);\n  $im->string(gdSmallFont,($center1),($bovenkant1), $titlebar1, $black);\n  $im->string(gdSmallFont,($left_border + $center2),($bovenkant2), $header2, $black);\n\n  $xlength = $width - $left_border - $right_border;\n  $lines = 10; # hard coded number of dashed lines\n  $xverh = $xlength / $xhigh;\n#  print \" de verhouding ===> $xverh --- $xlength -- $xhigh \\n\";\n\n  $xstep = ($xhigh / $lines) * $xverh;\n  $teller = 0;\n  # make the nice dashed lines and print the values ...\n  for ($i = 0; $i <= $lines; $i++) {\n    $st2 = ($left_border) + ($i * $xstep);\n    $im->dashedLine($st2,($height-$down_border),$st2,($up_border), $grey3);\n    if (($i != 0) && ($teller == 2)) {\n      $st3 = sprintf(\"%.2f\", $i*($xhigh/$lines));\n      $im->stringUp(gdTinyFont,($st2 - (gdSmallFont->height/2)),($height - $down_border +(.5*$sm_border) + (gdSmallFont->width*(length($xhigh)+3))), $st3, $black);\n      $teller = 0;\n    }\n    $teller++;\n  }\n  $im->rectangle($left_border,$up_border,($width - ($right_border)),($height-$down_border),$black);\n}\n\nsub legend {\n  # make the legend ...\n  $legxbegin = $left_border;\n\n  $legybegin = $height - $down_border + (2*$sm_border) + (gdSmallFont->width * (length($xhigh) + 3)) + gdSmallFont->height;\n  $legxend = $legxbegin + $max_len_le + (4*$legend_block);\n  $legxend = $legxbegin + $width_greyfield;\n  $legyend = $legybegin + $max_high_le;\n  $im->filledRectangle($legxbegin,$legybegin,$legxend,$legyend,$grey4);\n  $im->rectangle($legxbegin,$legybegin,$legxend,$legyend,$black);\n  # calculate the space for the legend .....\n  $c = 0; $i = 1;\n  $legybegin += $legend_block;\n  foreach $key (@key_order) {\n    $xtmp = $legxbegin + $legend_block;\n    $ytmp = $legybegin + ($c * (gdSmallFont->height +2));\n    $xtmp1 = $xtmp + $legend_block;\n    $ytmp1 = $ytmp + gdSmallFont->height;\n    $im->filledRectangle($xtmp,$ytmp,$xtmp1,$ytmp1,$tot{$key}{'color'});\n    $im->rectangle($xtmp,$ytmp,$xtmp1,$ytmp1,$black);\n    $tmp = $key;\n    $tmp =~ s/-cmp-$opt_cmp//i;\n    $giflegend = sprintf \"%-24.24s: %-40.40s\",$tmp,$tot{$key}{'server'};\n    $xtmp2 = $xtmp1 + $legend_block;\n    $im->string(gdSmallFont,$xtmp2,$ytmp,\"$giflegend\",$black);\n    $c++;\n    $i++;\n#    print \"$c $i -> $giflegend\\n\";\n  }\n  \n}\n\nsub lines {\n\n  $g = 0;\n  $i = 0;\n  $ybegin = $up_border + ((($#key_order + 2)/2)*$step);\n  $xbegin = $left_border;\n  foreach $key (sort {$a cmp $b} keys %op) {\n    next if ($key =~ /TOTALS/i);\n    $c = 0;\n#    print \"key - $key\\n\";\n    foreach $server (@key_order) {\n      $tot1{$server}{$key}->[1] = 1 if ($tot1{$server}{$key}->[1] == 0);\n      $entry = $tot1{$server}{$key}->[0]/$tot1{$server}{$key}->[1];\n      $ytmp = $ybegin + ($i * $step) ;\n      $xtmp = $xbegin + ($entry * $xverh) ;\n      $ytmp1 = $ytmp + $step;\n#      print \"$server -- $entry --x $xtmp -- y $ytmp - $c\\n\";\n      $entry1 = sprintf(\"%.2f\", $entry);\n      if ($entry < $xhigh) {\n        $im->filledRectangle($xbegin, $ytmp, $xtmp, $ytmp1, $tot{$server}{'color'});\n        $im->rectangle($xbegin, $ytmp, $xtmp, $ytmp1, $black);\n# print the seconds behind the bar (look below for another entry)\n# this entry is for the bars that are not greater then the max width\n# of the grey field ...\n#        $im->string(gdTinyFont,(($xtmp+3),($ytmp),\"$entry1\",$black));\n# if you want the seconds in the color of the bar just uncomment it (below)\n#        $im->string(gdTinyFont,(($xtmp+3),($ytmp),\"$entry1\",$tot{$server}{'color'}));\n      } else {\n        $im->filledRectangle($xbegin, $ytmp, ($xbegin + ($xhigh*$xverh)), $ytmp1, $tot{$server}{'color'});\n        $im->rectangle($xbegin, $ytmp, ($xbegin + ($xhigh*$xverh)), $ytmp1, $black);\n\n# print the seconds behind the bar (look below for another entry)\n# here is the seconds printed behind the bar is the bar is too big for \n# the graph ... (seconds is greater then xhigh ...)\n        $im->string(gdTinyFont, ($xbegin + ($xhigh*$xverh)+3),($ytmp),\"$entry1\",$black);\n# if you want the seconds in the color of the bar just uncomment it (below)\n#        $im->string(gdTinyFont, ($xbegin + ($xhigh*$xverh)+3),($ytmp),\"$entry1\",$colors[$c]);\n      }\n      $c++;\n      $i++;\n    }\n    # see if we can center the text between the bars ...\n    $ytmp2 = $ytmp1 - (((($c)*$step) + gdSmallFont->height)/2);\n    $im->string(gdSmallFont,($sm_border*2),$ytmp2,$key, $black);\n    $i++;\n  }\n}\n\n\nsub gif {\n  my ($name) = @_;\n  $name_gif = $name . \".gif\";\n  print \"name --> $name_gif\\n\";\n  open (GIF, \"> $name_gif\") || die \"Can't open $name_gif: $!\\n\";\n  print GIF $im->gif;\n  close (GIF);\n}\n\n", "num_lines": 663}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/InnoDB combined database\n#     (c) 2002 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 100000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest1: MySQL/InnoDB stress test in Perl\\n\";\nprint \"-------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest1, innotest1a, and innotest1b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on table innotest1 in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest1 > out1\\n\\n\";\n     \nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 63857) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"kjgclgrtfuylfluyfyufyulfulfyyulofuyolfyufyufuyfyufyufyufyufyyufujhfghd\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kh\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 20); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect()\n|| die $dbh->errstr;\n\n$dbh->do(\"set autocommit = 0\");\n\n$n = 0;\n\nfor ($i = 0; $i < 1; $i++) {\n\n\tprint \"Dropping table innotest1\\n\";\n\n\t$dbh->do(\"drop table innotest1\");\n\n\tprint \"Creating table innotest1\\n\";\n\n\t$dbh->do(\n\t\"create table innotest1 (A INT NOT NULL AUTO_INCREMENT, D INT NOT NULL, B VARCHAR(200) NOT NULL, C VARCHAR(175), E TIMESTAMP, F TIMESTAMP, G DATETIME, PRIMARY KEY (A, D), INDEX\n(B, C), INDEX (C), INDEX (D), INDEX(E), INDEX(G)) TYPE = INNODB\")\n\t|| die $dbh->errstr;\n\n\tfor ($j = 2; $j < $opt_loop_count - 10; $j = $j + 2) {\n\n\t\tif ($j % 10 == 0) {\n\t\t\t$dbh->do(\n\t\t\"insert into innotest1 (D, B, C, F, G) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"', NULL, NULL)\");\n\t\t} else {\n\t\t\t$dbh->do(\n\t\t\"insert into innotest1 (D, B, C, F, G) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"', NOW(), NOW())\");\n\t\t}\n\n\t\t$dbh->do(\"update innotest1 set B = '\".$rnd_str[$j + 7].\"' where A = \".$random[$j + 5]);\n\n\t\t$dbh->do(\"update innotest1 SET D = D + 1 where A =\".($j / 2 - 500));\n\n\t\t$dbh->do(\"update innotest1 set B = '\".$rnd_str[$j + 1].\"' where A =\".($j / 2 - 505));\n\n\t\t$dbh->do(\"delete from innotest1 where A = \".$random[$random[$j]]);\n\t\t\n\t\tfetch_all_rows($dbh, \"select b, c from innotest1 where a > \".$random[$j].\" and a < \".($random[$j] + 7));\n\t\t\n\t\tif (0 == ($j % 10)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 97)) {\n\t\tfetch_all_rows($dbh, \"select c, e, f, g from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tfetch_all_rows($dbh, \"select b, e, f, g from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\t\tfetch_all_rows($dbh, \"select b, c, e, f, g from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tfetch_all_rows($dbh, \"select b, c, g from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\t\tfetch_all_rows($dbh, \"select a, b, c, e, f, g from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tfetch_all_rows($dbh, \"select a, b, c, e, f, g from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\t\tfetch_all_rows($dbh, \"select d, b, c from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tfetch_all_rows($dbh, \"select d, b, c, g from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n        \tfor ($k = 1; $k < 10; $k++) {\n\n                \t$n += fetch_all_rows($dbh,\n\"SELECT a, d from innotest1 where a = \".(($k * 1764767) % $j));\n\n                \t$n += fetch_all_rows($dbh,\n\"SELECT * from innotest1 where a = \".(($k * 187567) % $j));\n\n        \t}\n\n\t\tif (0 == ($j % 1000)) {\n\t\t\tprint \"round $j, $n rows fetched\\n\";\n\t\t}\n\n\t\tif (0 == ($j % 20000)) {\n\t\t\tprint \"Checking table innotest1...\\n\";\n\t\t\t$dbh->do(\"check table innotest1\");\n\t\t\tprint \"Table checked.\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 143}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/InnoDB combined database\n#     (c) 2002 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 200000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest1a: MySQL/InnoDB stress test in Perl\\n\";\nprint \"-------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest1, innotest1a, and innotest1b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on table innotest1 in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest1 > out1\\n\\n\";\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 63857) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"kjgclgrtfuylfluyfyufyulfulfyyulofuyolfyufyufuyfyufyufyufyufyyufujhfghd\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kh\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 20); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect()\n|| die $dbh->errstr;\n\n\n$dbh->do(\"set autocommit = 0\");\n\nfor ($i = 0; $i < 1; $i++) {\n\tprint \"loop $i\\n\";\n\n\tfor ($j = 1; $j < $opt_loop_count - 10; $j = $j + 2) {\n\t\t$dbh->do(\n\t\t\"insert into innotest1 (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\");\n\t\t$dbh->do(\"update innotest1 set B = '\".$rnd_str[$j + 2].\"' where A = \".$random[$j + 5]);\n\t\t$dbh->do(\"update innotest1 SET D = D + 1 where A =\".(($j - 1) / 2 - 777));\n\t\t$dbh->do(\"update innotest1 set B = '\".$rnd_str[$j + 8].\"' where A =\".(($j - 1) / 2 - 770));\n\t\t$dbh->do(\"delete from innotest1 where A = \".$random[$random[$j]]);\n\n\t\tfetch_all_rows($dbh, \"select b, c from innotest1 where a > \".$random[$j].\" and a < \".($random[$j] + 7));\n\t\t\n\t\tif (0 == ($j % 37)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 533)) {\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n\t\tif (0 == ($j % 537)) {\n\t\tprint fetch_all_rows($dbh, \"select c from innotest1 where c = '\".$rnd_str[$j - 67].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b from innotest1 where b = '\".$rnd_str[$j - 688].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b, c from innotest1 where c = '\".$rnd_str[$j - 67].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b, c from innotest1 where b = '\".$rnd_str[$j - 622].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select a, b, c from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select a, b, c from innotest1 where b = '\".$rnd_str[$j - 644].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select d, b, c from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select d, b, c from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\t\tprint \"\\n\";\n\t\t}\n\n\t\tif (0 == (($j - 1) % 1000)) {\n\t\t\tprint \"round $j\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 109}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/InnoDB combined database\n#     (c) 2002 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 200000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest1b: MySQL/InnoDB stress test in Perl\\n\";\nprint \"-------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest1, innotest1a, and innotest1b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on table innotest1 in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest1 > out1\\n\\n\";\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 63857) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"kjgclgrtfuylfluyfyufyulfulfyyulofuyolfyufyufuyfyufyufyufyufyyufujhfghd\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kh\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 20); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect()\n|| die $dbh->errstr;\n\n$dbh->do(\"set autocommit = 0\");\n\nfor ($i = 0; $i < 5; $i++) {\n\tprint \"loop $i\\n\";\n\n\tfor ($j = 1; $j < $opt_loop_count - 10; $j = $j + 2) {\n\n\t\tfetch_all_rows($dbh, \"select b, c from innotest1 where a > \".$random[$j].\" and a < \".($random[$j] + 7));\n\t\t\n\t\tif (0 == ($j % 37)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 533)) {\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n\t\tif (0 == ($j % 537)) {\n\t\tprint fetch_all_rows($dbh, \"select c from innotest1 where c = '\".$rnd_str[$j - 67].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b from innotest1 where b = '\".$rnd_str[$j - 688].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b, c from innotest1 where c = '\".$rnd_str[$j - 67].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select b, c from innotest1 where b = '\".$rnd_str[$j - 622].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select a, b, c from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select a, b, c from innotest1 where b = '\".$rnd_str[$j - 644].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select d, b, c from innotest1 where c = '\".$rnd_str[$j - 68].\"'\");\n\t\tprint fetch_all_rows($dbh, \"select d, b, c from innotest1 where b = '\".$rnd_str[$j - 677].\"'\");\n\t\tprint \"\\n\";\n\t\t}\n\n\t\tif (0 == (($j - 1) % 1000)) {\n\t\t\tprint \"round $j\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 102}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/InnoDB combined database\n#     (c) 2002 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 100000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest2: MySQL/InnoDB stress test in Perl for FOREIGN keys\\n\";\nprint \"------------------------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks with foreign keys with\\n\";\nprint \"the ON DELETE ... clause. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest2, innotest2a, and innotest2b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on tables innotest2a, b, c, d in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest2 > out2\\n\\n\";\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 63857) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"khD\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kHd\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 10); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect()\n|| die $dbh->errstr;\n\n$dbh->do(\"set autocommit = 0\");\n\nfor ($i = 0; $i < 1; $i++) {\n\tprint \"loop $i\\n\";\n\n\tprint \"dropping table innotest2a\\n\";\n\t$dbh->do(\"drop table innotest2a\");\n\n\tprint \"dropping table innotest2b\\n\";\n\t$dbh->do(\"drop table innotest2b\");\n\n\tprint \"dropping table innotest2c\\n\";\n\t$dbh->do(\"drop table innotest2c\");\n\n\tprint \"dropping table innotest2d\\n\";\n\t$dbh->do(\"drop table innotest2d\");\n\n\tprint \"creating table innotest2b\\n\";\n\t$dbh->do(\n\t\"create table innotest2b (A INT NOT NULL AUTO_INCREMENT, D INT NOT NULL, B VARCHAR(200) NOT NULL, C VARCHAR(175), PRIMARY KEY (A, D, B), INDEX (B, C), INDEX (C)) TYPE = INNODB\")\n\t|| die $dbh->errstr;\t\n\n\tprint \"creating table innotest2a\\n\";\n\n\t$dbh->do(\n\t\"create table innotest2a (A INT NOT NULL AUTO_INCREMENT, D INT NOT NULL, B VARCHAR(200) NOT NULL, C VARCHAR(175), PRIMARY KEY (A, D, B), INDEX (B, C), INDEX (C), FOREIGN KEY (A, D) REFERENCES innotest2b (A, D) ON DELETE CASCADE) TYPE = INNODB\")\n\t|| die $dbh->errstr;\n\n\tprint \"creating table innotest2c\\n\";\n\n\t$dbh->do(\n\t\"create table innotest2c (A INT NOT NULL AUTO_INCREMENT, D INT NOT NULL, B VARCHAR(200) NOT NULL, C VARCHAR(175), PRIMARY KEY (A, D, B), INDEX (B, C), INDEX (C), FOREIGN KEY (A, D) REFERENCES innotest2a (A, D) ON DELETE CASCADE, FOREIGN KEY (B, C) REFERENCES innotest2a (B, C) ON DELETE CASCADE) TYPE = INNODB\")\n\t|| die $dbh->errstr;\t\n\n\tprint \"creating table innotest2d\\n\";\n\n\t$dbh->do(\n\t\"create table innotest2d (A INT AUTO_INCREMENT, D INT, B VARCHAR(200), C VARCHAR(175), UNIQUE KEY (A, D, B), INDEX (B, C), INDEX (C), FOREIGN KEY (C) REFERENCES innotest2c (C) ON DELETE SET NULL, FOREIGN KEY (B, C) REFERENCES innotest2c (B, C) ON DELETE SET NULL) TYPE = INNODB\")\n\t|| die $dbh->errstr;\t\n\tprint \"created\\n\";\n\n\tfor ($j = 0; $j < $opt_loop_count - 10; $j = $j + 2) {\n\t\t$dbh->do(\n\t\t\"insert into innotest2b (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\n\t\t\"insert into innotest2a (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\t\t\n\t\t$dbh->do(\n\t\t\"insert into innotest2c (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\n\t\t\"insert into innotest2d (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\"delete from innotest2b where A = \".$random[$random[$j]])\n\t\t|| print $dbh->errstr;\n\t\t\n\t\tif (0 == ($j % 10)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 39)) {\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n\t\tif (0 == ($j % 1000)) {\n\t\t\tprint \"round $j\\n\";\n\t\t}\n\t\tif (0 == ($j % 20000)) {\n\t\t\tprint \"Checking tables...\\n\";\n\t\t\t$dbh->do(\"check table innotest2a\");\n\t\t\t$dbh->do(\"check table innotest2b\");\n\t\t\t$dbh->do(\"check table innotest2c\");\n\t\t\t$dbh->do(\"check table innotest2d\");\n\t\t\tprint \"Tables checked.\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 151}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/Innobase combined database\n#     (c) 2000 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 100000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest2a: MySQL/InnoDB stress test in Perl for FOREIGN keys\\n\";\nprint \"------------------------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks with foreign keys with\\n\";\nprint \"the ON DELETE ... clause. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest2, innotest2a, and innotest2b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on tables innotest2a, b, c, d in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest2 > out2\\n\\n\";\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 63857) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"khD\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kHd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 20); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect()\n|| die $dbh->errstr;\n\n$dbh->do(\"set autocommit = 0\");\n\nfor ($i = 0; $i < 5; $i++) {\n\tprint \"loop $i\\n\";\n\n\tfor ($j = 0; $j < $opt_loop_count - 10; $j = $j + 1) {\n\t\t\n\t\t$dbh->do(\"update innotest2a set B = '\".$rnd_str[$j + 1].\"' where A = \".$random[$j + 5])\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\"delete from innotest2a where A = \".$random[$random[$j]])\n\t\t|| print $dbh->errstr;\n\t\t\n\t\tif (0 == ($j % 10)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 39)) {\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n\t\tif (0 == ($j % 1000)) {\n\t\t\tprint \"round $j\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 95}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n############################################################################\n#     Stress test for MySQL/Innobase combined database\n#     (c) 2000 Innobase Oy & MySQL AB\n#\n############################################################################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count = 100000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nprint \"Innotest2b: MySQL/InnoDB stress test in Perl for FOREIGN keys\\n\";\nprint \"------------------------------------------------------------\\n\";\nprint \"This is a randomized stress test for concurrent inserts,\\n\";\nprint \"updates, deletes, commits and rollbacks with foreign keys with\\n\";\nprint \"the ON DELETE ... clause. The test will generate\\n\";\nprint \"also a lot of deadlocks, duplicate key errors, and other SQL errors.\\n\";\nprint \"\\n\";\nprint \"You should run innotest2, innotest2a, and innotest2b concurrently.\\n\";\nprint \"The thing to watch is that the server does not crash or does not\\n\";\nprint \"print to the .err log anything. Currently, due to a buglet in MySQL,\\n\";\nprint \"warnings about MySQL lock reservations can appear in the .err log.\\n\";\nprint \"The test will run very long, even several hours. You can kill\\n\";\nprint \"the perl processes running this test at any time and do CHECK\\n\";\nprint \"TABLE on tables innotest2a, b, c, d in the 'test' database.\\n\";\nprint \"\\n\";\nprint \"Some of these stress tests will print a lot of SQL errors\\n\";\nprint \"to the standard output. That is not to be worried about.\\n\";\nprint \"You can direct the output to a file like this:\\n\";\nprint \"perl innotest2 > out2\\n\\n\";\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count] = 0;\n$rnd_str[$opt_loop_count] = \"a\";\n\nfor ($i = 0; $i < $opt_loop_count; $i++) {\n\n\t$random[$i] = ($i * 98641) % $opt_loop_count;\n\n  \tif (0 == ($random[$i] % 3)) {\n  \t\t$rnd_str[$i] = \"khD\";\n\t} else { if (1 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"khd\";\n\t} else { if (2 == ($random[$i] % 3)) {\n\t\t$rnd_str[$i] = \"kHd\";\n\t}}}\n\n\tfor ($j = 0; $j < (($i * 764877) % 10); $j++) {\n\t\t$rnd_str[$i] = $rnd_str[$i].\"k\";\n\t}\t\n}\n\n####\n####  Connect\n####\n\n$dbh = $server->connect();\n\n$dbh->do(\"set autocommit = 0\");\n\nfor ($i = 0; $i < 1; $i++) {\n\tprint \"loop $i\\n\";\n\n\tfor ($j = 0; $j < $opt_loop_count - 10; $j = $j + 2) {\n\t\t$dbh->do(\n\t\t\"insert into innotest2b (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\n\t\t\"insert into innotest2a (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\t\t\n\t\t$dbh->do(\n\t\t\"insert into innotest2c (D, B, C) values (5, '\".$rnd_str[$j].\"' ,'\".$rnd_str[$j].\"')\")\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\"delete from innotest2b where A = \".$random[$random[$j]])\n\t\t|| print $dbh->errstr;\n\n\t\t$dbh->do(\"update innotest2b set A = A + 1 where A = \".$random[$j])\n\t\t|| print $dbh->errstr;\n\n\t\tif (0 == ($j % 10)) {\n\t\t\t$dbh->do(\"commit\");\n\t\t}\n\n\t\tif (0 == ($j % 39)) {\n\t\t\t$dbh->do(\"rollback\");\n\t\t}\t\t\n\n\t\tif (0 == ($j % 1000)) {\n\t\t\tprint \"round $j\\n\";\n\t\t}\n\t}\t\n\t\n\t$dbh->do(\"commit\");\n}\t\t\t\t\n\n$dbh->disconnect;\t\t\t\t# close connection\n", "num_lines": 105}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# This program runs all test that starts with 'test-' and sums\n# the results that the program prints.\n# Each time result should be of the form:\n# Time for|to KEYWORD (number_of_runs) 'other info': timestr()\n#\n# All options to this script is passed to all test program.\n# useful options:\n# --fast --force --lock-tables\n# --server   ==> mysql (default) / mSQL / Pg (postgres) / Solid\n# --user     ==> the user with permission to create / drop / select\n# --pass     ==> password for the user\n# --cmp      ==> Compare --server with one of the others (mysql/mSQL/Pg/Solid)\n# --comments ==> everything you want to say such as the extra options you\n#                gave to the db server. (use --comments=\"xxx xxx xxx\"\n# --machine  ==> Give a OS/machine id for your logfiles.\n# --log\t     ==> puts output in output/RUN-server-machine-cmp-$opt_cmp\n\nuse DBI;\nuse Cwd;\n\n$opt_silent=1;\t\t\t# Don't write header\n\n@ORG_ARGV=@ARGV;\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n$opt_silent=0;\n$perl=$^X;\n$machine=machine();\n$redirect= !($machine =~ /windows/i || $machine =~ \"^NT\\s\") ? \"2>&1\" : \"\";\n$dir= ($pwd =~ /\\\\/) ? '\\\\' : '/';\t# directory symbol for shell\n\n$prog_args=\"\";\nforeach $arg (@ORG_ARGV)\n{\n  if ($redirect)\n  {\n    $prog_args.=\"'\" . $arg . \"' \";\n  }\n  else\n  {\n    # Windows/NT can't handle ' around arguments\n    $prog_args.=$arg . \" \";    \n  }\n}\n\n$prog_count=$errors=0;\n\nif ($opt_cmp) {\n\t$filename = \"$opt_server$opt_suffix-\" . machine_part() . \"-cmp-$opt_cmp\";\n} else {\n\t$filename = \"$opt_server$opt_suffix-\" . machine_part();\n}\n\nif (! -d $opt_dir)\n{\n  if (-e $opt_dir)\n  {\n    die \"$opt_dir isn't a directory\\n\";\n  }\n  mkdir $opt_dir,0777 || die \"Can't create directory: $opt_dir\\n\";\n}\n\nif ($opt_skip_test) {\n  (@skip_tests) = split(/,\\s*/, $opt_skip_test);\n}\n\nif ($opt_old_headers)\n{\n  read_headers(\"$opt_dir/RUN-$filename\");\n}\nelse\n{\n  $server_version=$server->version();\n}\n\nif (!$opt_log)\n{\n  open(LOG,\">&STDOUT\");\n}\nelse\n{\n  open(LOG, \"> $opt_dir/RUN-$filename\") ||\n    die \"Can't write to $opt_dir/RUN-$filename: $!\\n\";\n}\n\nselect(LOG);\n$|=1;\n\nprint \"Benchmark DBD suite: $benchmark_version\\n\";\nprint \"Date of test:        $date\\n\";\nprint \"Running tests on:    $machine\\n\";\nprint \"Arguments:           $log_prog_args\\n\";\nprint \"Comments:            $opt_comments\\n\";\nprint \"Limits from:         $opt_cmp\\n\";\nprint \"Server version:      $server_version\\n\";\nprint \"Optimization:        $opt_optimization\\n\";\nprint \"Hardware:            $opt_hw\\n\\n\";\n\n$estimated=$warning=$got_warning=0;\nwhile (<test-*>)\n{\n  next if (/\\.sh$/);\t\t# configure script\n  next if (/\\-fork$/);\t\t# test script\n  $prog_count++;\n  /test-(.*)$/;\t\t\t# Remove test from name\n  $prog=$1;\n  $skip_prog = 0;\n  foreach $skip_this (@skip_tests) {\n    if ($prog =~ /$skip_this/i) {\n      $skip_prog = 1;\n      last;\n    }\n  }\n  if ($opt_only_missing_tests && -f \"$opt_dir$dir$prog-$filename\")\n  {\n    # Test already run, skip it\n    $skip_prog= 1;\n  }\n  print \"$prog: \";\n  if ((!$opt_use_old_results) && (!$skip_prog))\n  {\n    if (system(\"$perl ./test-$prog $prog_args > \\\"$opt_dir$dir$prog-$filename\\\" $redirect\"))\n    {\n      printf STDERR \"Warning: Can't execute $prog.  Check the file '$opt_dir$dir$prog-$filename'\\n\";\n      die \"aborted\" if ($opt_die_on_errors);\n    }\n  }\n  open(TEST,\"$opt_dir/$prog-$filename\");\n  $last_line=\"\";\n  while(<TEST>)\n  {\n    chomp;\n    $last_line=$_ if (!(/^\\s*$/));\t\t# Search after last line\n  }\n  if ($last_line =~ /Total time:/i)\n  {\n    print $last_line . \"\\n\";\n    open(TEST,\"$opt_dir/$prog-$filename\");\n    while (<TEST>)\n    {\n      if (/^(estimated |)time (to|for) ([^\\s:]*)\\s*\\((\\d*)(:\\d*)*\\)[^:]*:\\s*([\\d.]+) .*secs \\(\\s*([^\\s]*) usr\\s*\\+*\\s*([^\\s]*) sys.*=\\s+([\\d.]*)\\s+cpu/i)\n      {\n\t$arg=$summa{$3};\n\tif (!defined($arg))\n\t{\n\t  $summa{$3}= [ $4,$6,$7,$8,$9,\"\"];\n\t}\n\telse\n\t{\n\t  $arg->[0]+=$4;\n\t  $arg->[1]+=$6;\n\t  $arg->[2]+=$7;\n\t  $arg->[3]+=$8;\n\t  $arg->[4]+=$9;\n\t}\n\t$prog_sum[0]+=$4;\n\t$prog_sum[1]+=$6;\n\t$prog_sum[2]+=$7;\n\t$prog_sum[3]+=$8;\n\t$prog_sum[4]+=$9;\n\tif (length($1))\n\t{\n\t  $summa{$3}->[5].=\"+\";\n\t  $estimated=1;\n\t}\n\tif ($got_warning)\n\t{\n\t  $summa{$3}->[5].=\"?\";\n\t  $warning=1;\n\t  $got_warning=0;\n\t}\n      }\n      elsif (/^warning/i)\n      {\n\t$got_warning=1;\n      }\n      else\n      {\n\t$got_warning=0;\n      }\n    }\n    if ($opt_debug)\n    {\n      print \"Summary for $prog: \", join(\" \",@prog_sum), \"\\n\";\n    }\n  }\n  elsif ($last_line =~ /^Test skipped/i)\n  {\n    print \"$last_line\\n\";\n  }\n  else\n  {\n    $errors++;\n    print \"Failed ($opt_dir/$prog-$filename)\\n\";\n  }\n}\n\nprint \"\\n\";\nif (!$errors)\n{\n  print \"All $prog_count test executed successfully\\n\";\n}\nelse\n{\n  print \"Of $prog_count tests, $errors tests didn't work\\n\";\n}\nif ($estimated)\n{\n  print \"Tests with estimated time have a + at end of line\\n\"\n}\nif ($warning)\n{\n  print \"Tests with didn't return the correct result have a ? at end of line\\n\";\n}\n\nif (%summa)\n{\n  @total=(0,0,0,0,0,\"\");\n  print \"\\nTotals per operation:\\n\";\n  print \"Operation             seconds     usr     sys     cpu   tests\\n\";\n  foreach $key (sort(keys %summa))\n  {\n    $arg=$summa{$key};\n    printf(\"%-35.35s %7.2f %7.2f %7.2f %7.2f %7d %s\\n\",\n\t   $key,$arg->[1],$arg->[2],$arg->[3],$arg->[4],$arg->[0],\n\t   $arg->[5]);\n\n    for ($i=0 ; $i < 5 ; $i++)\n    {\n      $total[$i]+=$arg->[$i];\n    }\n    $total[5].=$arg->[$i];\n  }\n  printf(\"%-35.35s %7.2f %7.2f %7.2f %7.2f %7d %s\\n\",\n\t \"TOTALS\",$total[1],$total[2],$total[3],$total[4],$total[0],\n\t $total[5]);\n}\n\nselect(STDOUT);\nif ($opt_log)\n{\n  print \"Test finished. You can find the result in:\\n$opt_dir/RUN-$filename\\n\";\n}\n\n\n#\n# Read headers from an old benchmark run\n#\n\nsub read_headers\n{\n  my ($filename)=@_;\n\n  # Clear current values\n  $benchmark_version=$date=$machine=$server_version=\"\";\n\n  open(TMP, \"<$filename\") || die \"Can't open $filename\\n\";\n  while (<TMP>)\n  {\n    chop;\n    if (/^Benchmark DBD.*:\\s+(.*)$/)\n    {\n      $benchmark_version=$1;\n    }\n    elsif (/^Date of.*:\\s+(.*)/)\n    {\n      $date=$1;\n    }\n    elsif (/^Running.*:\\s+(.*)$/)\n    {\n      $machine=$1;\n    }\n    elsif (/^Arguments.*:\\s+(.*)$/)\n    {\n      $log_prog_args=$1;\n    }\n    elsif (/^Limits.*:\\s+(.*)$/)\n    {\n      $opt_cmp=$1;\n    }\n    elsif (/^Server ver.*:\\s+(.*)$/)\n    {\n      $server_version=$1;\n    }\n    elsif (/^Optimiz.*:\\s+(.*)$/)\n    {\n      $opt_optimization=$1;\n    }\n    elsif (/^Hardwar.*:\\s+(.*)$/)\n    {\n      $opt_hw=$1;\n    }\n  }\n  close(TMP);\n}\n", "num_lines": 315}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# -*- perl -*-\n# Copyright (c) 2000-2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# The configuration file for the DBI/DBD tests on different databases ....\n# You will need the DBD module for the database you are running.\n# Monty made this bench script and I (Luuk de Boer) rewrote it to DBI/DBD.\n# Monty rewrote this again to use packages.\n#\n# Each database has a different package that has 3 functions:\n# new\t\tCreates a object with some standard slot\n# version\tVersion number of the server\n# create\tGenerates commands to create a table\n#\n\n#\n# First some global functions that help use the packages:\n#\n\nsub get_server\n{\n  my ($name,$host,$database,$odbc,$machine,$socket,$connect_options)=@_;\n  my ($server);\n  if ($name =~ /mysql/i)\n  { $server=new db_MySQL($host, $database, $machine, $socket,$connect_options); }\n  elsif ($name =~ /pg/i)\n  { $server= new db_Pg($host,$database); }\n  elsif ($name =~ /msql/i)\n  { $server= new db_mSQL($host,$database); }\n  elsif ($name =~ /solid/i)\n  { $server= new db_Solid($host,$database); }\n  elsif ($name =~ /Empress/i)\n  { $server= new db_Empress($host,$database); }\n  elsif ($name =~ /FrontBase/i)\n  { $server= new db_FrontBase($host,$database); }\n  elsif ($name =~ /Oracle/i)\n  { $server= new db_Oracle($host,$database); }\n  elsif ($name =~ /Access/i)\n  { $server= new db_access($host,$database); }\n  elsif ($name =~ /Informix/i)\n  { $server= new db_Informix($host,$database); }\n  elsif ($name =~ /ms-sql/i)\n  { $server= new db_ms_sql($host,$database); }\n  elsif ($name =~ /sybase/i)\n  { $server= new db_sybase($host,$database); }\n  elsif ($name =~ /Adabas/i)\t\t\t# Adabas has two drivers\n  {\n    $server= new db_Adabas($host,$database);\n    if ($name =~ /AdabasD/i)\n    {\n      $server->{'data_source'} =~ s/:Adabas:/:AdabasD:/;\n    }\n  }\n  elsif ($name =~ /DB2/i)\n  { $server= new db_db2($host,$database); }\n  elsif ($name =~ /Mimer/i)\n  { $server= new db_Mimer($host,$database); }\n  elsif ($name =~ /Sapdb/i)\n  { $server= new db_sapdb($host,$database); }\n  elsif ($name =~ /interBase/i)\n  { $server= new db_interbase($host,$database); }\n  else\n  {\n      die \"Unknown sql server name used: $name\\nUse one of: Access, Adabas, AdabasD, Empress, FrontBase, Oracle, Informix, InterBase, DB2, mSQL, Mimer, MS-SQL, MySQL, Pg, Solid, SAPDB or Sybase.\\nIf the connection is done trough ODBC the name must end with _ODBC\\n\";\n  }\n  if ($name =~ /_ODBC$/i || defined($odbc) && $odbc)\n  {\n    if (! ($server->{'data_source'} =~ /^([^:]*):([^:]+):([^:]*)/ ))\n    {\n      die \"Can't find databasename in data_source: '\" .\n\t  $server->{'data_source'}. \"'\\n\";\n    }\n    if ($3) {\n      $server->{'data_source'} = \"$1:ODBC:$3\";\n    } else {\n      $server->{'data_source'} = \"$1:ODBC:$database\";\n    }\n  }\n  return $server;\n}\n\nsub all_servers\n{\n  return [\"Access\", \"Adabas\", \"DB2\", \"Empress\", \"FrontBase\", \"Oracle\",\n\t  \"Informix\", \"InterBase\", \"Mimer\", \"mSQL\", \"MS-SQL\", \"MySQL\", \"Pg\",\"SAPDB\",\n\t  \"Solid\", \"Sybase\"];\n}\n\n#############################################################################\n#\t     First the configuration for MySQL off course :-)\n#############################################################################\n\npackage db_MySQL;\n\nsub new\n{\n  my ($type,$host,$database,$machine,$socket,$connect_options)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"mysql\";\n  $self->{'data_source'}\t= \"DBI:mysql:database=$database;host=$host\";\n  $self->{'data_source'} .= \";mysql_socket=$socket\" if($socket);\n  $self->{'data_source'} .= \";$connect_options\" if($connect_options);\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"blob\";\n  $self->{'text'}\t\t= \"text\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'vacuum'}\t\t= 1; # When using with --fast\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 0; # Transactions disabled by default\n\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'alter_add_multi_col'}= 1; #Have ALTER TABLE t add a int,add b int;\n  $limits{'alter_table'}\t= 1; # Have ALTER TABLE\n  $limits{'alter_table_dropcol'}= 1; # Have ALTER TABLE DROP column\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'func_extra_%'}\t= 1; # Has % as alias for mod()\n  $limits{'func_extra_if'}\t= 1; # Have function if.\n  $limits{'func_extra_in_num'}\t= 1; # Has function in\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_odbc_mod'}\t= 1; # Have function mod.\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_by_position'}  = 1; # Can use 'GROUP BY 1'\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'group_func_extra_std'} = 1; # Have group function std().\n  $limits{'group_func_sql_min_str'} = 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'having_with_alias'}  = 1; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can use group functions in HAVING\n  $limits{'insert_multi_value'} = 1; # Have INSERT ... values (1,2),(3,4)\n  $limits{'insert_select'}\t= 1;\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'limit'}\t\t= 1; # supports the limit attribute\n  $limits{'truncate_table'}\t= 1;\n  $limits{'load_data_infile'}\t= 1; # Has load data infile\n  $limits{'lock_tables'}\t= 1; # Has lock tables\n  $limits{'max_column_name'}\t= 64; # max table and column name\n  $limits{'max_columns'}\t= 2000;\t# Max number of columns in table\n  $limits{'max_conditions'}\t= 9999; # (Actually not a limit)\n  $limits{'max_index'}\t\t= 16; # Max number of keys\n  $limits{'max_index_parts'}\t= 16; # Max segments/key\n  $limits{'max_tables'}\t\t= (($machine || '') =~ \"^win\") ? 5000 : 65000;\n  $limits{'max_text_size'}\t= 1000000; # Good enough for tests\n  $limits{'multi_drop'}\t\t= 1; # Drop table can take many tables\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'query_size'}\t\t= 1000000; # Max size with default buffers.\n  $limits{'select_without_from'}= 1; # Can do 'select 1';\n  $limits{'subqueries'}\t\t= 0; # Doesn't support sub-queries.\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'working_all_fields'} = 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  # Some fixes that depends on the environment\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=heap/i)\n  {\n    $limits{'working_blobs'}\t= 0; # HEAP tables can't handle BLOB's\n  }\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=innodb/i)\n  {\n    $self->{'transactions'}\t= 1;\t# Transactions enabled\n  }\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=rocksdb/i)\n  {\n    $self->{'transactions'}     = 1;    # Transactions enabled\n  }\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=ndb/i)\n  {\n    $self->{'transactions'}\t= 1;\t# Transactions enabled\n    $limits{'max_columns'}\t= 90;\t# Max number of columns in table\n    $limits{'max_tables'}\t= 32;   # No comments\n  }\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=bdb/i)\n  {\n    $self->{'transactions'}\t= 1;\t# Transactions enabled\n  }\n  if (defined($main::opt_create_options) &&\n      $main::opt_create_options =~ /engine=gemini/i)\n  {\n    $limits{'working_blobs'}\t= 0; # Blobs not implemented yet\n    $limits{'max_tables'}\t= 500;\n    $self->{'transactions'}\t= 1;\t# Transactions enabled\n  }\n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"select VERSION()\") or die $DBI::errstr;\n  $version=\"MySQL 3.20.?\";\n  if ($sth->execute && (@row = $sth->fetchrow_array))\n  {\n    $row[0] =~ s/-/ /g;\t\t\t# To get better tables with long names\n    $version=\"MySQL $row[0]\";\n  }\n  $sth->finish;\n\n  $sth = $dbh->prepare(\"show status like 'ssl_version'\") or die $DBI::errstr;\n  if ($sth->execute && (@row = $sth->fetchrow_array) && $row[1])\n  {\n    $version .= \"/$row[1]\";\n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\n#\n# Connection with optional disabling of logging\n#\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n\n  $dbh->do(\"SET OPTION LOG_OFF=1,UPDATE_LOG=0\");\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index,$options) = @_;\n  my($query,@queries);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n#    $field =~ s/ decimal/ double(10,2)/i;\n    $field =~ s/ big_decimal/ double(10,2)/i;\n    $query.= $field . ',';\n  }\n  foreach $index (@$index)\n  {\n    $query.= $index . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  $query.=\" $options\" if (defined($options));\n  $query.=\" $main::opt_create_options\" if (defined($main::opt_create_options));\n  push(@queries,$query);\n  return @queries;\n}\n\nsub insert_file {\n  my ($self,$dbname, $file, $dbh) = @_;\n  my ($command, $sth);\n\n  $file =~ s|\\\\|/|g;\t\t\t# Change Win32 names to Unix syntax\n  $command = \"load data infile '$file' into table $dbname columns optionally enclosed by '\\\\'' terminated by ','\";\n#  print \"$command\\n\";\n  $sth = $dbh->do($command) or die $DBI::errstr;\n  return $sth;\t\t\t# Contains number of rows\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index {\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index ON $table\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\n#\n# This should return 1 if we to do disconnect / connect when doing\n# big batches\n#\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\n#\n# reconnect on errors (needed mainly be crash-me)\n#\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#\n# Optimize tables for better performance\n#\n\nsub vacuum\n{\n  my ($self,$full_vacuum,$dbh_ref,@tables)=@_;\n  my ($loop_time,$end_time,$dbh);\n  if ($#tables >= 0)\n  {\n    $dbh=$$dbh_ref;\n    $loop_time=new Benchmark;\n    $dbh->do(\"OPTIMIZE TABLE \" . join(',',@tables)) || die \"Got error: $DBI::errstr when executing 'OPTIMIZE TABLE'\\n\";\n    $end_time=new Benchmark;\n    print \"Time for book-keeping (1): \" .\n      Benchmark::timestr(Benchmark::timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n  }\n}\n\n#############################################################################\n#\t\t     Definitions for mSQL\n#############################################################################\n\npackage db_mSQL;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"msql\";\n  $self->{'data_source'}\t= \"DBI:mSQL:$database:$host\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'double_quotes'}\t= 0;\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 0;  # No transactions\n  $self->{'blob'}\t\t= \"text(\" . $limits{'max_text_size'} .\")\";\n  $self->{'text'}\t\t= \"text(\" . $limits{'max_text_size'} .\")\";\n\n  $limits{'max_conditions'}\t= 74;\n  $limits{'max_columns'}\t= 75;\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 32000;\n  $limits{'query_size'}\t\t= 65535;\n  $limits{'max_index'}\t\t= 5;\n  $limits{'max_index_parts'}\t= 10;\n  $limits{'max_column_name'} = 35;\n\n  $limits{'join_optimizer'}\t= 0;\t\t# Can't optimize FROM tables\n  $limits{'load_data_infile'}\t= 0;\n  $limits{'lock_tables'}\t= 0;\n  $limits{'functions'}\t\t= 0;\n  $limits{'group_functions'}\t= 0;\n  $limits{'group_distinct_functions'}= 0;\t # Have count(distinct)\n  $limits{'multi_drop'}\t\t= 0;\n  $limits{'select_without_from'}= 0;\n  $limits{'subqueries'}\t\t= 0;\n  $limits{'left_outer_join'}\t= 0;\n  $limits{'table_wildcard'}\t= 0;\n  $limits{'having_with_alias'}  = 0;\n  $limits{'having_with_group'}\t= 0;\n  $limits{'like_with_column'}\t= 1;\n  $limits{'order_by_position'}  = 1;\n  $limits{'group_by_position'}  = 1;\n  $limits{'alter_table'}\t= 0;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n  $limits{'group_func_extra_std'} = 0;\n  $limits{'limit'}\t\t= 1;\t\t# supports the limit attribute\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 0;\n\n  $limits{'func_odbc_mod'}\t= 0;\n  $limits{'func_extra_%'}\t= 0;\n  $limits{'func_odbc_floor'}\t= 0;\n  $limits{'func_extra_if'}\t= 0;\n  $limits{'column_alias'}\t= 0;\n  $limits{'NEG'}\t\t= 0;\n  $limits{'func_extra_in_num'}\t= 0;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($tmp,$dir);\n  foreach $dir (\"/usr/local/Hughes\", \"/usr/local/mSQL\",\"/my/local/mSQL\",\n\t\t\"/usr/local\")\n  {\n    if (-x \"$dir/bin/msqladmin\")\n    {\n      $tmp=`$dir/bin/msqladmin version | grep server`;\n      if ($tmp =~ /^\\s*(.*\\w)\\s*$/)\n      {\t\t\t\t# Strip pre- and endspace\n\t$tmp=$1;\n\t$tmp =~ s/\\s+/ /g;\t# Remove unnecessary spaces\n\t$tmp .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n\n\treturn $tmp;\n      }\n    }\n  }\n  return \"mSQL version ???\";\n}\n\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Can't handle many field types, so we map everything to int and real.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$name,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/varchar/char/i;\t\t# mSQL doesn't have VARCHAR()\n    # mSQL can't handle more than the real basic int types\n    $field =~ s/tinyint|smallint|mediumint|integer/int/i;\n    # mSQL can't handle different visual lengths\n    $field =~ s/int\\(\\d*\\)/int/i;\n    # mSQL doesn't have float, change it to real\n    $field =~ s/float(\\(\\d*,\\d*\\)){0,1}/real/i;\n    $field =~ s/double(\\(\\d*,\\d*\\)){0,1}/real/i;\n    # mSQL doesn't have blob, it has text instead\n    if ($field =~ / blob/i)\n    {\n      $name=$self->{'blob'};\n      $field =~ s/ blob/ $name/;\n    }\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n\n  # Prepend table_name to index name because the the name may clash with\n  # a field name. (Should be diffent name space, but this is mSQL...)\n\n  foreach $index (@$index)\n  {\n    # Primary key is unique index in mSQL\n    $index =~ s/primary key/unique index primary/i;\n    if ($index =~ /^unique\\s*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      push(@queries,\"create unique index ${table_name}_$nr on $table_name ($1)\");\n    }\n    else\n    {\n      if (!($index =~ /^(.*index)\\s+(\\w*)\\s+(\\(.*\\))$/i))\n      {\n\tdie \"Can't parse index information in '$index'\\n\";\n      }\n      push(@queries,\"create $1 ${table_name}_$2 on $table_name $3\");\n    }\n  }\n  return @queries;\n}\n\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert an ascii file isn't supported by mSQL\\n\";\n  return 0;\n}\n\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index FROM $table\";\n}\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t\t     Definitions for PostgreSQL\t\t\t\t    #\n#############################################################################\n\npackage db_Pg;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"pg\";\n  $self->{'data_source'}\t= \"DBI:Pg:dbname=$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"text\";\n  $self->{'text'}\t\t= \"text\";\n  $self->{'double_quotes'}\t= 1;\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{\"vacuum\"}\t\t= 1;\n  $limits{'join_optimizer'}\t= 1;\t\t# Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0;\n\n  $limits{'NEG'}\t\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\t\t# alter_add_multi_col ?\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_table_dropcol'}= 0;\n  $limits{'column_alias'}\t= 1;\n  $limits{'func_extra_%'}\t= 1;\n  $limits{'func_extra_if'}\t= 0;\n  $limits{'func_extra_in_num'}\t= 1;\n  $limits{'func_odbc_floor'}\t= 1;\n  $limits{'func_odbc_mod'}\t= 1;\t\t# Has %\n  $limits{'functions'}\t\t= 1;\n  $limits{'group_by_position'}  = 1;\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'group_func_extra_std'} = 0;\n  $limits{'group_func_sql_min_str'}= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_functions'}\t= 1;\n  $limits{'having_with_alias'}  = 0;\n  $limits{'having_with_group'}\t= 1;\n  $limits{'insert_select'}\t= 1;\n  $limits{'left_outer_join'}\t= 1;\n  $limits{'like_with_column'}\t= 1;\n  $limits{'lock_tables'}\t= 0;\t\t# in ATIS gives this a problem\n  $limits{'max_column_name'} \t= 128;\n  $limits{'max_columns'}\t= 1000;\t\t# 500 crashes pg 6.3\n  $limits{'max_conditions'}\t= 9999;\t\t# This makes Pg real slow\n  $limits{'max_index'}\t\t= 64;\t\t# Big enough\n  $limits{'max_index_parts'}\t= 16;\n  $limits{'max_tables'}\t\t= 5000;\t\t# 10000 crashes pg 7.0.2\n  $limits{'max_text_size'}\t= 65000;\t# Good enough for test\n  $limits{'multi_drop'}\t\t= 1;\n  $limits{'order_by_position'}  = 1;\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'query_size'}\t\t= 16777216;\n  $limits{'select_without_from'}= 1;\n  $limits{'subqueries'}\t\t= 1;\n  $limits{'table_wildcard'}\t= 1;\n  $limits{'truncate_table'}\t= 1;\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'working_all_fields'} = 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n# couldn't find the option to get the version number\n\nsub version\n{\n  my ($version,$dir);\n  $version = \"PostgreSQL version ???\";\n  foreach $dir ($ENV{'PGDATA'},\"/usr/local/pgsql/data\", \"/usr/local/pg/data\")\n  {\n    if ($dir && -e \"$dir/PG_VERSION\")\n    {\n      $version= `cat $dir/PG_VERSION`;\n      if ($? == 0)\n      {\n\tchomp($version);\n\t$version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n\treturn \"PostgreSQL $version\";\n      }\n    }\n  }\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$name,$in,$indfield,$table,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    if ($main::opt_fast)\n    {\n      # Allow use of char2, char4, char8 or char16\n      $field =~ s/char(2|4|8|16)/char$1/;\n    }\n    # Pg can't handle more than the real basic int types\n    $field =~ s/tinyint|smallint|mediumint|integer/int/;\n    # Pg can't handle different visual lengths\n    $field =~ s/int\\(\\d*\\)/int/;\n    $field =~ s/float\\(\\d*,\\d*\\)/float/;\n    $field =~ s/ double/ float/;\n#    $field =~ s/ decimal/ float/i;\n#    $field =~ s/ big_decimal/ float/i;\n#    $field =~ s/ date/ int/i;\n    # Pg doesn't have blob, it has text instead\n    $field =~ s/ blob/ text/;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  foreach $index (@$index)\n  {\n    $index =~ s/primary key/unique index primary_key/i;\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      # original: $indfield=\"using btree (\" .$1.\")\";\n      # using btree doesn\u00b4t seem to work with Postgres anymore; it creates\n      # the table and adds the index, but it isn\u00b4t unique\n      $indfield=\" (\" .$1.\")\";\t\n      $in=\"unique index\";\n      $table=\"index_$nr\"; $nr++;\n    }\n    elsif ($index =~ /^(.*index)\\s+(\\w*)\\s+(\\(.*\\))$/i)\n    {\n      # original: $indfield=\"using btree (\" .$1.\")\";\n      $indfield=\" \" .$3;\n      $in=\"index\";\n      $table=\"index_$nr\"; $nr++;\n    }\n    else\n    {\n      die \"Can't parse index information in '$index'\\n\";\n    }\n    push(@queries,\"create $in ${table_name}_$table on $table_name $indfield\");\n  }\n  $queries[0]=$query;\n  return @queries;\n}\n\nsub insert_file {\n  my ($self,$dbname, $file, $dbh) = @_;\n  my ($command, $sth);\n\n# Syntax:\n# copy [binary] <class_name> [with oids]\n#      {to|from} {<filename>|stdin|stdout} [using delimiters <delim>]\n  print \"The ascii files aren't correct for postgres ....!!!\\n\";\n  $command = \"copy $dbname from '$file' using delimiters ','\";\n  print \"$command\\n\";\n  $sth = $dbh->do($command) or die $DBI::errstr;\n  return $sth;\n}\n\n#\n# As postgreSQL wants A % B instead of standard mod(A,B) we have to map\n# This will not handle all cases, but as the benchmarks doesn't use functions\n# inside MOD() the following should work\n#\n# PostgreSQL cant handle count(*) or even count(1), but it can handle\n# count(1+1) sometimes. ==> this is solved in PostgreSQL 6.3\n#\n# PostgreSQL 6.5 is supporting MOD.\n\nsub query {\n  my($self,$sql) = @_;\n  my(@select,$change);\n# if you use PostgreSQL 6.x and x is lower as 5 then uncomment the line below.\n#  $sql =~ s/mod\\(([^,]*),([^\\)]*)\\)/\\($1 % $2\\)/gi;\n#\n# if you use PostgreSQL 6.1.x uncomment the lines below\n#  if ($sql =~ /select\\s+count\\(\\*\\)\\s+from/i) {\n#  }\n#  elsif ($sql =~ /count\\(\\*\\)/i)\n#  {\n#    if ($sql =~ /select\\s+(.*)\\s+from/i)\n#    {\n#      @select = split(/,/,$1);\n#      if ($select[0] =~ /(.*)\\s+as\\s+\\w+$/i)\n#      {\n# \t$change = $1;\n#      }\n#      else\n#      {\n#\t$change = $select[0];\n#      }\n#    }\n#    if (($change =~ /count/i) || ($change eq \"\")) {\n#      $change = \"1+1\";\n#    }\n#    $sql =~ s/count\\(\\*\\)/count($change)/gi;\n#  }\n# till here.\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\nsub abort_if_fatal_error\n{\n  return 1 if ($DBI::errstr =~ /sent to backend, but backend closed/i);\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\nsub vacuum\n{\n  my ($self,$full_vacuum,$dbh_ref,@tables)=@_;\n  my ($loop_time,$end_time,$dbh,$table);\n  if (defined($full_vacuum))\n  {\n    $$dbh_ref->disconnect;  $$dbh_ref= $self->connect();\n  }\n  $dbh=$$dbh_ref;\n  $loop_time=new Benchmark;\n  if ($#tables >= 0)\n  {\n    foreach $table (@tables)\n    {\n      $dbh->do(\"vacuum analyze $table\") || die \"Got error: $DBI::errstr when executing 'vacuum analyze $table'\\n\";\n      $dbh->do(\"vacuum $table\") || die \"Got error: $DBI::errstr when executing 'vacuum'\\n\";\n    }\n  }\n  else\n  {\n#    $dbh->do(\"vacuum pg_attributes\") || die \"Got error: $DBI::errstr when executing 'vacuum'\\n\";\n#    $dbh->do(\"vacuum pg_index\") || die \"Got error: $DBI::errstr when executing 'vacuum'\\n\";\n    $dbh->do(\"vacuum analyze\") || die \"Got error: $DBI::errstr when executing 'vacuum analyze'\\n\";\n    $dbh->do(\"vacuum\") || die \"Got error: $DBI::errstr when executing 'vacuum'\\n\";\n  }\n  $end_time=new Benchmark;\n  print \"Time for book-keeping (1): \" .\n  Benchmark::timestr(Benchmark::timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n  $dbh->disconnect;  $$dbh_ref= $self->connect();\n}\n\n\n#############################################################################\n#\t\t     Definitions for Solid\n#############################################################################\n\npackage db_Solid;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"solid\";\n  $self->{'data_source'}\t= \"DBI:Solid:\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"long varchar\";\n  $self->{'text'}\t\t= \"long varchar\";\n  $self->{'double_quotes'}\t= 1;\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 9999;\t\t# Probably big enough\n  $limits{'max_columns'}\t= 2000;\t\t# From crash-me\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 65492;\t# According to tests\n  $limits{'query_size'}\t\t= 65535;\t# Probably a limit\n  $limits{'max_index'}\t\t= 64;\t\t# Probably big enough\n  $limits{'max_index_parts'}\t= 64;\n  $limits{'max_column_name'} = 80;\n\n  $limits{'join_optimizer'}\t= 1;\n  $limits{'load_data_infile'}\t= 0;\n  $limits{'lock_tables'}\t= 0;\n  $limits{'functions'}\t\t= 1;\n  $limits{'group_functions'}\t= 1;\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0;\t\t# Can do 'select 1' ?;\n  $limits{'multi_drop'}\t\t= 0;\n  $limits{'subqueries'}\t\t= 1;\n  $limits{'left_outer_join'}\t= 1;\n  $limits{'table_wildcard'}\t= 1;\n  $limits{'having_with_alias'}  = 0;\n  $limits{'having_with_group'}\t= 1;\n  $limits{'like_with_column'}\t= 1;\n  $limits{'order_by_position'}  = 0;\t\t# 2.30.0018 can this\n  $limits{'group_by_position'}  = 0;\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'}\t= 0;\t# Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 1;\n  $limits{'func_extra_%'}\t= 0;\n  $limits{'func_odbc_floor'}\t= 1;\n  $limits{'column_alias'}\t= 1;\n  $limits{'NEG'}\t\t= 1;\n  $limits{'func_extra_in_num'}\t= 1;\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($version,$dir);\n  $version=\"Solid version ??\";\n  foreach $dir ($ENV{'SOLIDDIR'},\"/usr/local/solid\", \"/my/local/solid\")\n  {\n    if ($dir && -e \"$dir/bin/solcon\")\n    {\n      $version=`$dir/bin/solcon -e\"ver\" $main::opt_user $main::opt_password | grep Server | sed q`;\n      if ($? == 0)\n      {\n\tchomp($version);\n\t$version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n\treturn $version;\n      }\n    }\n  }\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/ double/ float/i;\n    # Solid doesn't have blob, it has long varchar\n    $field =~ s/ blob/ long varchar/;\n#    $field =~ s/ decimal/ float/i;\n#    $field =~ s/ big_decimal/ float/i;\n#    $field =~ s/ date/ int/i;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n  foreach $index (@$index)\n  {\n    if ($index =~ /^primary key/i || $index =~ /^unique/i)\n    {\t\t\t\t\t# Add to create statement\n      substr($queries[0],-1,0)=\",\" . $index;\n    }\n    else\n    {\n      $index =~ /^(.*)\\s+(\\(.*\\))$/;\n      push(@queries,\"create ${1}$nr on $table_name $2\");\n      $nr++;\n    }\n  }\n  return @queries;\n}\n\n# there is no sql statement in solid which can do the load from\n# an ascii file in the db ... but there is the speedloader program\n# an external program which can load the ascii file in the db ...\n# the server must be down before using speedloader !!!!\n# (in the standalone version)\n# it works also with a control file ... that one must be made ....\nsub insert_file {\n  my ($self, $dbname, $file) = @_;\n  my ($speedcmd);\n  $speedcmd = '/usr/local/solid/bin/solload';\n  print \"At this moment not supported - solid server must go down \\n\";\n  return 0;\n}\n\n# solid can't handle an alias in a having statement so\n# select test as foo from tmp group by foo having foor > 2\n# becomes\n# select test as foo from tmp group by foo having test > 2\n#\nsub query {\n  my($self,$sql) = @_;\n  my(@select,$tmp,$newhaving,$key,%change);\n\n  if ($sql =~ /having\\s+/i)\n  {\n    if ($sql =~ /select (.*) from/i)\n    {\n      (@select) = split(/,\\s*/, $1);\n      foreach $tmp (@select)\n      {\n\tif ($tmp =~ /(.*)\\s+as\\s+(\\w+)/)\n\t{\n\t  $change{$2} = $1;\n\t}\n      }\n    }\n    if ($sql =~ /having\\s+(\\w+)/i)\n    {\n      $newhaving = $1;\n      foreach $key (sort {$a cmp $b} keys %change)\n      {\n\tif ($newhaving eq $key)\n\t{\n\t  $newhaving =~ s/$key/$change{$key}/g;\n\t}\n      }\n    }\n    $sql =~ s/(having)\\s+(\\w+)/$1 $newhaving/i;\n  }\n  return $sql;\n}\n\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\n#############################################################################\n#\t\t     Definitions for Empress\n#\n# at this moment DBI:Empress can only handle 200 prepare statements ...\n# so Empress can't be tested with the benchmark test :(\n#############################################################################\n\npackage db_Empress;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"empress\";\n  $self->{'data_source'}        = \"DBI:EmpressNet:SERVER=$host;Database=/usr/local/empress/rdbms/bin/$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"text\";\n  $self->{'text'}\t\t= \"text\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 1258;\n  $limits{'max_columns'}\t= 226;\t\t# server is disconnecting????\n\t\t\t# above this value .... but can handle 2419 columns\n\t\t\t# maybe something for crash-me ... but how to check ???\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 4095;\t\t# max returned ....\n  $limits{'query_size'}\t\t= 65535;\t# Not a limit, big enough\n  $limits{'max_index'}\t\t= 64;\t\t# Big enough\n  $limits{'max_index_parts'}\t= 64;\t\t# Big enough\n  $limits{'max_column_name'} \t= 31;\n\n  $limits{'join_optimizer'}\t= 1;\n  $limits{'load_data_infile'}\t= 0;\n  $limits{'lock_tables'}\t= 1;\n  $limits{'functions'}\t\t= 1;\n  $limits{'group_functions'}\t= 1;\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0;\n  $limits{'multi_drop'}\t\t= 0;\n  $limits{'subqueries'}\t\t= 1;\n  $limits{'table_wildcard'}\t= 0;\n  $limits{'having_with_alias'}  = 0; \t# AS isn't supported in a select\n  $limits{'having_with_group'}\t= 1;\n  $limits{'like_with_column'}\t= 1;\n  $limits{'order_by_position'}  = 1;\n  $limits{'group_by_position'}  = 0;\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'}= 0;\t# Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0;\n  $limits{'func_extra_%'}\t= 1;\n  $limits{'func_odbc_floor'}\t= 1;\n  $limits{'func_extra_if'}\t= 0;\n  $limits{'column_alias'}\t= 0;\n  $limits{'NEG'}\t\t= 1;\n  $limits{'func_extra_in_num'}\t= 0;\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self,$dbh)=@_;\n  my ($version);\n  $version=\"\";\n  if (-x \"/usr/local/empress/rdbms/bin/empvers\")\n  {\n    $version=`/usr/local/empress/rdbms/bin/empvers | grep Version`;\n  }\n  if ($version)\n  {\n    chomp($version);\n  }\n  else\n  {\n    $version=\"Empress version ???\";\n  }\n\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  my($command,$sth);\n  $command = \"insert into $dbname from '$file'\";\n  print \"$command\\n\" if ($opt_debug);\n  $sth = $dbh->do($command) or die $DBI::errstr;\n\n  return $sth;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/int/i;\n    $field =~ s/tinyint/int/i;\n    $field =~ s/smallint/int/i;\n    $field =~ s/longint/int/i;\n    $field =~ s/integer/int/i;\n    $field =~ s/ double/ longfloat/i;\n    # Solid doesn't have blob, it has long varchar\n#    $field =~ s/ blob/ text(65535,65535,65535,65535)/;\n    $field =~ s/ blob/ text/;\n    $field =~ s/ varchar\\((\\d+)\\)/ char($1,3)/;\n    $field =~ s/ char\\((\\d+)\\)/ char($1,3)/;\n#    $field =~ s/ decimal/ float/i;\n#    $field =~ s/ big_decimal/ longfloat/i;\n#    $field =~ s/ date/ int/i;\n    $field =~ s/ float(.*)/ float/i;\n    if ($field =~ / int\\((\\d+)\\)/) {\n      if ($1 > 4) {\n        $field =~ s/ int\\(\\d+\\)/ longinteger/i;\n      } else {\n        $field =~ s/ int\\(\\d+\\)/ longinteger/i;\n      }\n    } else {\n      $field =~ s/ int/ longinteger/i;\n    }\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=1;\n  foreach $index (@$index)\n  {\n    # Primary key is unique index in Empress\n    $index =~ s/primary key/unique index/i;\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      push(@queries,\"create unique index ${table_name}_$nr on $table_name ($1)\");\n    }\n    else\n    {\n      if (!($index =~ /^(.*index)\\s+(\\w*)\\s+(\\(.*\\))$/i))\n      {\n\tdie \"Can't parse index information in '$index'\\n\";\n      }\n      push(@queries,\"create $1 ${table_name}_$2 on $table_name $3\");\n    }\n  }\n  return @queries;\n}\n\n# empress can't handle an alias and but can handle the number of the\n# columname - so\n# select test as foo from tmp order by foo\n# becomes\n# select test from tmp order by 1\n#\nsub query {\n  my($self,$sql) = @_;\n  my(@select,$i,$tmp,$newselect,$neworder,@order,$key,%change);\n  my($tmp1,$otmp,$tmp2);\n\n  if ($sql =~ /\\s+as\\s+/i)\n  {\n    if ($sql =~ /select\\s+(.*)\\s+from/i) {\n      $newselect = $1;\n      (@select) = split(/,\\s*/, $1);\n      $i = 1;\n      foreach $tmp (@select) {\n\tif ($tmp =~ /\\s+as\\s+(\\w+)/) {\n\t  $change{$1} = $i;\n\t}\n\t$i++;\n      }\n    }\n    $newselect =~ s/\\s+as\\s+(\\w+)//gi;\n    $tmp2 = 0;\n    if ($sql =~ /order\\s+by\\s+(.*)$/i) {\n      (@order) = split(/,\\s*/, $1);\n      foreach $otmp (@order) {\n\tforeach $key (sort {$a cmp $b} keys %change) {\n\t  if ($otmp eq $key) {\n\t    $neworder .= \"$tmp1\".\"$change{$key}\";\n\t    $tmp1 = \", \";\n\t    $tmp2 = 1;\n\t  } elsif ($otmp =~ /(\\w+)\\s+(.+)$/) {\n\t    if ($key eq $1) {\n\t      $neworder .= \"$tmp1\".\"$change{$key} $2\";\n\t      $tmp2 = 1;\n\t    }\n\t  }\n\t}\n\tif ($tmp2 == 0) {\n\t  $neworder .= \"$tmp1\".\"$otmp\";\n\t}\n\t$tmp2 = 0;\n\t$tmp1 = \", \";\n      }\n    }\n    $sql =~ s/(select)\\s+(.*)\\s+(from)/$1 $newselect $3/i;\n    $sql =~ s/(order\\s+by)\\s+(.*)$/$1 $neworder/i;\n  }\n  return $sql;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  $cmd =~ s/\\'\\'/\\' \\'/g;\n  return $cmd;\n}\n\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n# This is a because of the 200 statement problem with DBI-Empress\n\nsub abort_if_fatal_error\n{\n  if ($DBI::errstr =~ /Overflow of table of prepared statements/i)\n  {\n    print \"Overflow of prepared statements ... killing the process\\n\";\n    exit 1;\n  }\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\n#############################################################################\n#\t                 Definitions for Oracle\n#############################################################################\n\npackage db_Oracle;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"Oracle\";\n  $self->{'data_source'}\t= \"DBI:Oracle:$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"long\";\n  $self->{'text'}\t\t= \"long\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{\"vacuum\"}\t\t= 1;\n\n  $limits{'max_conditions'}\t= 9999; # (Actually not a limit)\n  $limits{'max_columns'}\t= 254;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000; # Should be big enough\n  $limits{'max_text_size'}\t= 2000; # Limit for blob test-connect\n  $limits{'query_size'}\t\t= 65525; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 16; # Max number of keys\n  $limits{'max_index_parts'}\t= 16; # Max segments/key\n  $limits{'max_column_name'} = 32; # max table and column name\n\n  $limits{'truncate_table'}\t= 1;\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0;\n  $limits{'multi_drop'}\t\t= 0;\n  $limits{'subqueries'}\t\t= 1;\n  $limits{'left_outer_join'}\t= 0; # This may be fixed in the query module\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can't use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0;\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'}\t= 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Oracle has problem with mod()\n  $limits{'func_extra_%'}\t= 0; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 1; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"select VERSION from product_component_version WHERE PRODUCT like 'Oracle%'\") or die $DBI::errstr;\n  $version=\"Oracle 7.x\";\n  if ($sth->execute && (@row = $sth->fetchrow_array))\n  {\n    $version=\"Oracle $row[0]\";\n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$ind,@keys);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/ character\\((\\d+)\\)/ char\\($1\\)/i;\n    $field =~ s/ character varying\\((\\d+)\\)/ varchar\\($1\\)/i;\n    $field =~ s/ char varying\\((\\d+)\\)/ varchar\\($1\\)/i;\n    $field =~ s/ integer/ number\\(38\\)/i;\n    $field =~ s/ int/ number\\(38\\)/i;\n    $field =~ s/ tinyint/ number\\(38\\)/i;\n    $field =~ s/ smallint/ number\\(38\\)/i;\n    $field =~ s/ mediumint/ number\\(38\\)/i;\n    $field =~ s/ tinynumber\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ smallnumber\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ mediumnumber\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ number\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ numeric\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ decimal\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ dec\\((\\d+)\\)\\((\\d+)\\)/ number\\($1,$2\\)/i;\n    $field =~ s/ float/ number/;\n    $field =~ s/ real/ number/;\n    $field =~ s/ double precision/ number/;\n    $field =~ s/ double/ number/;\n    $field =~ s/ blob/ long/;\n    $query.= $field . ',';\n  }\n\n  foreach $ind (@$index)\n  {\n    my @index;\n    if ( $ind =~ /\\bKEY\\b/i ){\n      push(@keys,\"ALTER TABLE $table_name ADD $ind\");\n    }else{\n      my @fields = split(' ',$index);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@index,$query);\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query,@keys,@index);\n#print \"query:$query\\n\";\n\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert an ascii file isn't supported by Oracle (?)\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  $cmd =~ s/\\'\\'/\\' \\'/g;\n  return $cmd;\n}\n\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 1;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\n#\n# optimize the tables ....\n#\nsub vacuum\n{\n  my ($self,$full_vacuum,$dbh_ref)=@_;\n  my ($loop_time,$end_time,$sth,$dbh);\n\n  if (defined($full_vacuum))\n  {\n    $$dbh_ref->disconnect;  $$dbh_ref= $self->connect();\n  }\n  $dbh=$$dbh_ref;\n  $loop_time=new Benchmark;\n  # first analyze all tables\n  $sth = $dbh->prepare(\"select table_name from user_tables\") || die \"Got error: $DBI::errstr\";\n  $sth->execute || die \"Got error: $DBI::errstr when select user_tables\";\n  while (my @r = $sth->fetchrow_array)\n  {\n    $dbh->do(\"analyze table $r[0] compute statistics\") || die \"Got error: $DBI::errstr when executing 'analyze table'\\n\";\n  }\n  # now analyze all indexes ...\n  $sth = $dbh->prepare(\"select index_name from user_indexes\") || die \"Got error: $DBI::errstr\";\n  $sth->execute || die \"Got error: $DBI::errstr when select user_indexes\";\n  while (my @r1 = $sth->fetchrow_array)\n  {\n    $dbh->do(\"analyze index $r1[0] compute statistics\") || die \"Got error: $DBI::errstr when executing 'analyze index $r1[0]'\\n\";\n  }\n  $end_time=new Benchmark;\n  print \"Time for book-keeping (1): \" .\n  Benchmark::timestr(Benchmark::timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n  $dbh->disconnect;  $$dbh_ref= $self->connect();\n}\n\n\n#############################################################################\n#\t                 Definitions for Informix\n#############################################################################\n\npackage db_Informix;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"Informix\";\n  $self->{'data_source'}\t= \"DBI:Informix:$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"byte in table\";\n  $self->{'text'}\t\t= \"byte in table\";\n  $self->{'double_quotes'}\t= 0; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{'host'}\t\t= $host;\n\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 1;\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'func_extra_%'}\t= 0; # Has % as alias for mod()\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'func_extra_in_num'}= 0; # Has function in\n  $limits{'func_odbc_floor'}\t= 0; # Has func_odbc_floor function\n  $limits{'func_odbc_mod'}\t= 1; # Have function mod.\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_by_position'}  = 1; # Can use 'GROUP BY 1'\n  $limits{'group_by_alias'}  = 0; # Can use 'select a as ab from x GROUP BY ab'\n  $limits{'group_func_extra_std'} = 0; # Have group function std().\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}= 1; # Can't use group functions in HAVING\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables (always 1 only for msql)\n  $limits{'left_outer_join'}\t= 0; # Supports left outer joins (ANSI)\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 1; # Has lock tables\n  $limits{'max_conditions'}\t= 1214; # (Actually not a limit)\n  $limits{'max_column_name'}\t= 18; # max table and column name\n  $limits{'max_columns'}\t= 994;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_index'}\t\t= 64; # Max number of keys\n  $limits{'max_index_parts'}\t= 15; # Max segments/key\n  $limits{'max_text_size'}\t= 65535;  # Max size with default buffers. ??\n  $limits{'multi_drop'}\t\t= 0; # Drop table can take many tables\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'query_size'}\t\t= 32766; # Max size with default buffers.\n  $limits{'select_without_from'}= 0; # Can do 'select 1';\n  $limits{'subqueries'}\t\t= 1; # Doesn't support sub-queries.\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $ENV{'INFORMIXSERVER'} = $self->{'host'};\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"SELECT owner FROM systables WHERE tabname = ' VERSION'\")\n\t\t\t\t\t\t      or die $DBI::errstr;\n  $version='Informix unknown';\n  if ($sth->execute && (@row = $sth->fetchrow_array))\n  {\n    $version=\"Informix $row[0]\";\n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n\n#\n# Create table\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$name,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n#    $field =~ s/\\btransport_description\\b/transport_desc/;\n\t\t\t\t# to overcome limit 18 chars\n    $field =~ s/tinyint/smallint/i;\n    $field =~ s/tinyint\\(\\d+\\)/smallint/i;\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/mediumint\\(\\d+\\)/integer/i;\n    $field =~ s/smallint\\(\\d+\\)/smallint/i;\n    $field =~ s/integer\\(\\d+\\)/integer/i;\n    $field =~ s/int\\(\\d+\\)/integer/i;\n#    $field =~ s/\\b(?:small)?int(?:eger)?\\((\\d+)\\)/decimal($1)/i;\n#    $field =~ s/float(\\(\\d*,\\d*\\)){0,1}/real/i;\n    $field =~ s/(float|double)(\\(.*?\\))?/float/i;\n\n    if ($field =~ / blob/i)\n    {\n      $name=$self->{'blob'};\n      $field =~ s/ blob/ $name/;\n    }\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n\n  foreach $index (@$index)\n  {\n    # Primary key is unique index in Informix\n    $index =~ s/primary key/unique index primary/i;\n    if ($index =~ /^unique\\s*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      push(@queries,\"create unique index ${table_name}_$nr on $table_name ($1)\");\n    }\n    else\n    {\n      if (!($index =~ /^(.*index)\\s+(\\w*)\\s+(\\(.*\\))$/i))\n      {\n\tdie \"Can't parse index information in '$index'\\n\";\n      }\n      ### push(@queries,\"create $1 ${table_name}_$2 on $table_name $3\");\n      $nr++;\n      push(@queries,\"create $1 ${table_name}_$nr on $table_name $3\");\n    }\n  }\n  return @queries;\n}\n#\n# Some test needed this\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  $cmd =~ s/\\\\\\'//g;\n  return $cmd;\n}\n\n\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\n\n#############################################################################\n#\t     Configuration for Access\n#############################################################################\n\npackage db_access;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"access\";\n  $self->{'data_source'}\t= \"DBI:ODBC:$database\";\n  if (defined($host) && $host ne \"\")\n  {\n    $self->{'data_source'}\t.= \":$host\";\n  }\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"blob\";\n  $self->{'text'}\t\t= \"blob\"; # text ? \n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 97; # We get 'Query is too complex'\n  $limits{'max_columns'}\t= 255;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 255;  # Max size with default buffers.\n  $limits{'query_size'}\t\t= 65535; # Not a limit, big enough\n  $limits{'max_index'}\t\t= 32; # Max number of keys\n  $limits{'max_index_parts'}\t= 10; # Max segments/key\n  $limits{'max_column_name'}\t= 64; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 0; # Have count(distinct)\n  $limits{'select_without_from'}= 1; # Can do 'select 1';\n  $limits{'multi_drop'}\t\t= 0; # Drop table can take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Can use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 2; #Have ALTER TABLE t add a int, b int;\n  $limits{'alter_table_dropcol'}= 1;\n\n  $limits{'group_func_extra_std'} = 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod.\n  $limits{'func_extra_%'}\t= 0; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 0; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 1; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my $version=\"Access 2000\";\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\t\t#DBI/ODBC can't return the server version\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/tinyint/smallint/i;\n    $field =~ s/float\\(\\d+,\\d+\\)/float/i;\n    $field =~ s/integer\\(\\d+\\)/integer/i;\n    $field =~ s/smallint\\(\\d+\\)/smallint/i;\n    $field =~ s/int\\(\\d+\\)/integer/i;\n    $field =~ s/blob/text/i;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n  foreach $index (@$index)\n  {\n    $ext=\"WITH DISALLOW NULL\";\n    if (($index =~ s/primary key/unique index primary_key/i))\n    {\n      $ext=\"WITH PRIMARY;\"\n    }\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      $index=\"unique index ${table_name}_$nr ($1)\";\n    }\n    $index =~ /^(.*)\\s+(\\(.*\\))$/;\n    push(@queries,\"create ${1} on $table_name $2\");\n  }\n  return @queries;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index ON $table\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 1 if (($DBI::errstr =~ /The database engine couldn\\'t lock table/i) ||\n               ($DBI::errstr =~ /niet vergrendelen. De tabel is momenteel in gebruik /i) ||\n\t       ($DBI::errstr =~ /Den anv.* redan av en annan/i) ||\n\t       ($DBI::errstr =~ /non-exclusive access/));\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 1;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for Microsoft SQL server\n#############################################################################\n\npackage db_ms_sql;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"ms-sql\";\n  $self->{'data_source'}\t= \"DBI:ODBC:$database\";\n  if (defined($host) && $host ne \"\")\n  {\n    $self->{'data_source'}\t.= \":$host\";\n  }\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"text\";\n  $self->{'text'}\t\t= \"text\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 1030; # We get 'Query is too complex'\n  $limits{'max_columns'}\t= 250;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 9830;  # Max size with default buffers.\n  $limits{'query_size'}\t\t= 9830; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 64; # Max number of keys\n  $limits{'max_index_parts'}\t= 15; # Max segments/key\n  $limits{'max_column_name'}\t= 30; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 1; # Can do 'select 1';\n  $limits{'multi_drop'}\t\t= 1; # Drop table can take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can't use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Can use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'} = 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod.\n  $limits{'func_extra_%'}\t= 1; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 0; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my($sth,@row, $version);\n  $version='MS SQL server ?';\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"SELECT \\@\\@VERSION\") or die $DBI::errstr;\n  $sth->execute or die $DBI::errstr;\n  @row = $sth->fetchrow_array;\n  if ($row[0]) {\n     @server = split(/\\n/,$row[0]);\n     chomp(@server);\n     $version= \"$server[0]\";\n  } \n  $sth->finish;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/float\\(\\d+,\\d+\\)/float/i;\n    $field =~ s/double\\(\\d+,\\d+\\)/float/i;\n    $field =~ s/double/float/i;\n    $field =~ s/integer\\(\\d+\\)/integer/i;\n    $field =~ s/int\\(\\d+\\)/integer/i;\n    $field =~ s/smallint\\(\\d+\\)/smallint/i;\n    $field =~ s/smallinteger/smallint/i;\n    $field =~ s/tinyint\\(\\d+\\)/tinyint/i;\n    $field =~ s/tinyinteger/tinyint/i;\n    $field =~ s/blob/text/i;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n  foreach $index (@$index)\n  {\n    $ext=\"WITH DISALLOW NULL\";\n    if (($index =~ s/primary key/unique index primary_key/i))\n    {\n      $ext=\"WITH PRIMARY;\"\n    }\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      $index=\"unique index ${table_name}_$nr ($1)\";\n    }\n    $index =~ /^(.*)\\s+(\\(.*\\))$/;\n    push(@queries,\"create ${1} on $table_name $2\");\n  }\n  return @queries;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $table.$index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for Sybase\n#############################################################################\npackage db_sybase;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"sybase\";\n  $self->{'data_source'}\t= \"DBI:Sybase:database=$database\";\n  if (defined($host) && $host ne \"\")\n  {\n    $self->{'data_source'}\t.= \";hostname=$host\";\n  }\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"text\";\n  $self->{'text'}\t\t= \"text\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{\"vacuum\"}\t\t= 1;\n\n  $limits{'max_conditions'}\t= 1030; # We get 'Query is too complex'\n  $limits{'max_columns'}\t= 250;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 9830;  # Max size with default buffers.\n  $limits{'query_size'}\t\t= 9830; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 64; # Max number of keys\n  $limits{'max_index_parts'}\t= 15; # Max segments/key\n  $limits{'max_column_name'}\t= 30; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 1; # Can do 'select 1';\n  $limits{'multi_drop'}\t\t= 1; # Drop table can take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can't use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Can use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'} = 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod.\n  $limits{'func_extra_%'}\t= 1; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 0; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n  $sth = $dbh->prepare('SELECT @@version') or die $DBI::errstr;\n  $version=\"Sybase (unknown)\";\n  if ($sth->execute && (@row = $sth->fetchrow_array))\n  {\n    $version=$row[0];\n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0 , AutoCommit => 1}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/float\\(\\d+,\\d+\\)/float/i;\n    $field =~ s/int\\(\\d+\\)/int/i;\n    $field =~ s/double/float/i;\n    $field =~ s/integer\\(\\d+\\)/integer/i;\n    $field =~ s/smallint\\(\\d+\\)/smallint/i;\n    $field =~ s/tinyint\\(\\d+\\)/tinyint/i;\n    $field =~ s/blob/text/i;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n  foreach $index (@$index)\n  {\n#    $ext=\"WITH DISALLOW NULL\";\n    if (($index =~ s/primary key/unique index primary_key/i))\n    {\n#      $ext=\"WITH PRIMARY;\"\n    }\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      $index=\"unique index ${table_name}_$nr ($1)\";\n    }\n    $index =~ /^(.*)\\s+(\\(.*\\))$/;\n    push(@queries,\"create ${1} on $table_name $2\");\n  }\n  return @queries;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $table.$index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#\n# optimize the tables ....\n#  WARNING (from walrus)! This sub will work only from DBD:sybase\n# driver. Because if we use ODBC we don't know actual database name\n# (but DSN name only)\nsub vacuum\n{\n  my ($self,$full_vacuum,$dbh_ref)=@_;\n  my ($loop_time,$end_time,$dbh);\n\n  if (defined($full_vacuum))\n  {\n    $$dbh_ref->disconnect;  $$dbh_ref= $self->connect();\n  }\n  $dbh=$$dbh_ref;\n  $loop_time=new Benchmark;\n  my (@tables,$sth,$current_table,$current_base);\n  $dbh->do(\"dump tran $database with truncate_only\");\n  $sth=$dbh->prepare(\"sp_tables\" ) or die \"prepere\";\n  $sth->execute() or die \"execute\";\n  while (@row = $sth->fetchrow_array()) {\n    $current_table = $row[2];\n    $current_base = $row[0];\n    next if ($current_table =~ /^sys/); \n    push(@tables,$current_table) if ($database == $current_base);    \n   }\n\n  $sth->finish();\n\n  foreach $table (@tables) {\n#    print \"$table: \\n\";\n    $dbh->do(\"update statistics $table\") or print \"Oops!\"; \n  }\n \n#  $dbh->do(\"analyze table ?? compute statistics\") || die \"Got error: $DBI::errstr when executing 'vacuum'\\n\";\n  $end_time=new Benchmark;\n  print \"Time for book-keeping (1): \" .\n  Benchmark::timestr(Benchmark::timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n  $dbh->disconnect;  $$dbh_ref= $self->connect();\n}\n\n\n\n\n#############################################################################\n#\t                 Definitions for Adabas\n#############################################################################\n\npackage db_Adabas;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"Adabas\";\n  $self->{'data_source'}\t= \"DBI:Adabas:$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"long\";\n  $self->{'text'}\t\t= \"long\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 50; # (Actually not a limit)\n  $limits{'max_columns'}\t= 254;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 2000; # Limit for blob test-connect\n  $limits{'query_size'}\t\t= 65525; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 16; # Max number of keys\n  $limits{'max_index_parts'}\t= 16; # Max segments/key\n  $limits{'max_column_name'} = 32; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}\t= 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0;\n  $limits{'multi_drop'}\t\t= 0;\n  $limits{'subqueries'}\t\t= 1;\n  $limits{'left_outer_join'}\t= 0; # This may be fixed in the query module\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can't use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 1;\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 2; #Have ALTER TABLE t add a int, b int;\n  $limits{'alter_table_dropcol'}= 1;\n\n  $limits{'group_func_extra_std'}\t= 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Oracle has problem with mod()\n  $limits{'func_extra_%'}\t= 0; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 1; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"SELECT KERNEL FROM VERSIONS\") or die $DBI::errstr;\n  $version=\"Adabas (unknown)\";\n  if ($sth->execute && (@row = $sth->fetchrow_array)\n      && $row[0] =~ /([\\d\\.]+)/)\n  {\n    $version=\"Adabas $1\";\n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$ind,@keys);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/CHARACTER\\s+VARYING/VARCHAR/i;\n    $field =~ s/TINYINT/SMALLINT/i;\n    $field =~ s/MEDIUMINT/INT/i;\n    $field =~ s/SMALLINT\\s*\\(\\d+\\)/SMALLINT/i;\n    $field =~ s/INT\\s*\\(\\d+\\)/INT/i;\n    $field =~ s/BLOB/LONG/i;\n    $field =~ s/INTEGER\\s*\\(\\d+\\)/INTEGER/i;\n    $field =~ s/FLOAT\\s*\\((\\d+),\\d+\\)/FLOAT\\($1\\)/i;\n    $field =~ s/DOUBLE/FLOAT\\(38\\)/i;\n    $field =~ s/DOUBLE\\s+PRECISION/FLOAT\\(38\\)/i;\n    $query.= $field . ',';\n  }\n\n  foreach $ind (@$index)\n  {\n    my @index;\n    if ( $ind =~ /\\bKEY\\b/i ){\n      push(@keys,\"ALTER TABLE $table_name ADD $ind\");\n    }else{\n      my @fields = split(' ',$index);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@index,$query);\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query,@keys,@index);\n#print \"query:$query\\n\";\n\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert an ascii file isn't supported by Oracle (?)\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for IBM DB2\n#############################################################################\n\npackage db_db2;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"DB2\";\n  $self->{'data_source'}\t= \"DBI:ODBC:$database\";\n  if (defined($host) && $host ne \"\")\n  {\n    $self->{'data_source'}\t.= \":$host\";\n  }\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"varchar(255)\";\n  $self->{'text'}\t\t= \"varchar(255)\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n\n  $limits{'max_conditions'}\t= 418; # We get 'Query is too complex'\n  $limits{'max_columns'}\t= 500;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 254;  # Max size with default buffers.\n  $limits{'query_size'}\t\t= 254; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 48; # Max number of keys\n  $limits{'max_index_parts'}\t= 15; # Max segments/key\n  $limits{'max_column_name'}\t= 18; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'}= 1;\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0; # Can do 'select 1';\n  $limits{'multi_drop'}\t\t= 0; # Drop table can take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can't use group functions in HAVING\n  $limits{'like_with_column'}\t= 0; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Can use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1;\n  $limits{'alter_add_multi_col'}= 0;\n  $limits{'alter_table_dropcol'}= 0;\n\n  $limits{'group_func_extra_std'} = 0; # Have group function std().\n\n  $limits{'func_odbc_mod'}\t= 1; # Have function mod.\n  $limits{'func_extra_%'}\t= 0; # Has % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 0; # Has function in\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  return \"IBM DB2 5\";\t\t#DBI/ODBC can't return the server version\n}\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user, $main::opt_password) ||\n    die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index) = @_;\n  my($query,@queries,$nr);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/mediumint/integer/i;\n    $field =~ s/float\\(\\d+,\\d+\\)/float/i;\n    $field =~ s/integer\\(\\d+\\)/integer/i;\n    $field =~ s/int\\(\\d+\\)/integer/i;\n    $field =~ s/tinyint\\(\\d+\\)/smallint/i;\n    $field =~ s/tinyint/smallint/i;\n    $field =~ s/smallint\\(\\d+\\)/smallint/i;\n    $field =~ s/smallinteger/smallint/i;\n    $field =~ s/blob/varchar(256)/i;\n    $query.= $field . ',';\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  push(@queries,$query);\n  $nr=0;\n  foreach $index (@$index)\n  {\n    $ext=\"WITH DISALLOW NULL\";\n    if (($index =~ s/primary key/unique index primary_key/i))\n    {\n      $ext=\"WITH PRIMARY;\"\n    }\n    if ($index =~ /^unique.*\\(([^\\(]*)\\)$/i)\n    {\n      $nr++;\n      $index=\"unique index ${table_name}_$nr ($1)\";\n    }\n    $index =~ /^(.*)\\s+(\\(.*\\))$/;\n    push(@queries,\"create ${1} on $table_name $2\");\n  }\n  return @queries;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index\n{\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $table.$index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 1;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for MIMER \n#############################################################################\n\npackage db_Mimer;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"mimer\";\n  $self->{'data_source'}\t= \"DBI:mimer:$database:$host\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"binary varying(15000)\";\n  $self->{'text'}\t\t= \"character varying(15000)\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{'char_null'}          = \"cast(NULL as char(1))\";\n  $self->{'numeric_null'}       = \"cast(NULL as int)\";\n\n  $limits{'max_conditions'}\t= 9999; # (Actually not a limit)\n  $limits{'max_columns'}\t= 252;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 15000; # Max size with default buffers.\n  $limits{'query_size'}\t\t= 1000000; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 32; # Max number of keys\n  $limits{'max_index_parts'}\t= 16; # Max segments/key\n  $limits{'max_column_name'}\t= 128; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 1; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'} = 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0; # Cannot do 'select 1';\n  $limits{'multi_drop'}\t\t= 0; # Drop table cannot take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Cannot use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1; # Have ALTER TABLE\n  $limits{'alter_add_multi_col'}= 0; # Have ALTER TABLE t add a int,add b int;\n  $limits{'alter_table_dropcol'}= 1; # Have ALTER TABLE DROP column\n  $limits{'insert_multi_value'} = 0; # Does not have INSERT ... values (1,2),(3,4)\n  $limits{'multi_distinct'}     = 0; # Does not allow select count(distinct a),count(distinct b).. \n\n  $limits{'group_func_extra_std'} = 0; # Does not have group function std().\n\n  $limits{'func_odbc_mod'}\t= 1; # Have function mod.\n  $limits{'func_extra_%'}\t= 0; # Does not have % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Does not have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 1; # Has function in\n  $limits{'limit'}\t\t= 0; # Does not support the limit attribute\n  $limits{'unique_index'}\t= 1; # Unique index works or not\n  $limits{'insert_select'}\t= 1;\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 0;\n  $limits{'working_all_fields'} = 1;\n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n#\n#  Pick up SQLGetInfo option SQL_DBMS_VER (18)\n#\n  $version = $dbh->func(18, GetInfo);\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);  \n  return $version;\n}\n\n#\n# Connection with optional disabling of logging\n#\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n\n  $dbh->do(\"SET OPTION LOG_OFF=1,UPDATE_LOG=0\");\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index,$options) = @_;\n  my($query,@queries,@indexes);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n#    $field =~ s/ decimal/ double(10,2)/i;\n#    $field =~ s/ big_decimal/ double(10,2)/i;\n    $field =~ s/ double/ double precision/i;  \n    $field =~ s/ tinyint\\(.*\\)/ smallint/i;\n    $field =~ s/ smallint\\(.*\\)/ smallint/i;\n    $field =~ s/ mediumint/ integer/i;\n    $field =~ s/ float\\(.*\\)/ float/i;\n#    $field =~ s/ date/ int/i;\t\t# Because of tcp ?\n    $query.= $field . ',';\n  }\n  foreach $index (@$index)\n  {\n    if ( $index =~ /\\bINDEX\\b/i )\n    {\n      my @fields = split(' ',$index);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@indexes,$query);\n    \n    } else {\n      $query.= $index . ',';\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  $query.=\" $options\" if (defined($options));\n  push(@queries,$query,@indexes);\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert of an ascii file isn't supported by Mimer\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index {\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 1 if ($DBI::errstr =~ /Table locked by another cursor/);\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for InterBase\n#############################################################################\n\npackage db_interbase;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"interbase\";\n  $self->{'data_source'}\t= \"DBI:InterBase:database=$database;ib_dialect=3\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"blob\";\n  $self->{'text'}\t\t= \"\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{'char_null'}          = \"\";\n  $self->{'numeric_null'}       = \"\";\n\n  $limits{'max_conditions'}\t= 9999; # (Actually not a limit)\n  $limits{'max_columns'}\t= 252;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough\n  $limits{'max_text_size'}\t= 15000; # Max size with default buffers.\n  $limits{'query_size'}\t\t= 1000000; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 65000; # Max number of keys\n  $limits{'max_index_parts'}\t= 8; # Max segments/key\n  $limits{'max_column_name'}\t= 128; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 0; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_func_sql_min_str'} = 1; # Can execute MIN() and MAX() on strings\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)\n  $limits{'select_without_from'}= 0; # Cannot do 'select 1';\n  $limits{'multi_drop'}\t\t= 0; # Drop table cannot take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 1; # Can use group functions in HAVING\n  $limits{'like_with_column'}\t= 0; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Cannot use 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1; # Have ALTER TABLE\n  $limits{'alter_add_multi_col'}= 1; # Have ALTER TABLE t add a int,add b int;\n  $limits{'alter_table_dropcol'}= 1; # Have ALTER TABLE DROP column\n  $limits{'insert_multi_value'} = 0; # Does not have INSERT ... values (1,2),(3,4)\n\n  $limits{'group_func_extra_std'} = 0; # Does not have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod.\n  $limits{'func_extra_%'}\t= 0; # Does not have % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 0; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Does not have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 0; # Supports -id\n  $limits{'func_extra_in_num'}\t= 0; # Has function in\n  $limits{'limit'}\t\t= 0; # Does not support the limit attribute\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works\n  $limits{'order_by_unused'}\t= 1;\n  $limits{'working_all_fields'} = 1;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$version);\n  \n  $version='Interbase ?';\n  \n  $dbh=$self->connect();\n  eval { $version =   $dbh->func('version','ib_database_info')->{'version'}; }; \n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\n#\n# Connection with optional disabling of logging\n#\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0, AutoCommit => 1}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index,$options) = @_;\n  my($query,@queries,@keys,@indexes);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n#    $field =~ s/ big_decimal/ decimal/i;\n    $field =~ s/ double/ double precision/i;\n    $field =~ s/ tinyint/ smallint/i;\n    $field =~ s/ mediumint/ integer/i;\n    $field =~ s/\\bint\\b/integer/i;\n    $field =~ s/ float\\(\\d,\\d\\)/ float/i;\n    $field =~ s/ smallint\\(\\d\\)/ smallint/i;\n    $field =~ s/ integer\\(\\d\\)/ integer/i;\n    $query.= $field . ',';\n  }\n  foreach $ind (@$index)\n  {\n    if ( $ind =~ /(\\bKEY\\b)|(\\bUNIQUE\\b)/i ){\n      push(@keys,\"ALTER TABLE $table_name ADD $ind\");\n    }else{\n      my @fields = split(' ',$ind);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@indexes,$query);\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  $query.=\" $options\" if (defined($options));\n  push(@queries,$query,@keys,@indexes);\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert of an ascii file isn't supported by InterBase\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index {\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 1 if ($DBI::errstr =~ /Table locked by another cursor/);\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 1;\n}\n\nsub reconnect_on_errors\n{\n  return 1;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for FrontBase \n#############################################################################\n\npackage db_FrontBase;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"FrontBase\";\n  $self->{'data_source'}\t= \"DBI:FB:dbname=$database;host=$host\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"varchar(8000000)\";\n  $self->{'text'}\t\t= \"varchar(8000000)\";\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= ' restrict';\n  $self->{'transactions'}\t= 1; # Transactions enabled\n  $self->{'error_on_execute_means_zero_rows'}=1;\n\n  $limits{'max_conditions'}\t= 5427; # (Actually not a limit)\n  # The following should be 8192, but is smaller because Frontbase crashes..\n  $limits{'max_columns'}\t= 150;\t# Max number of columns in table\n  $limits{'max_tables'}\t\t= 5000;\t# 10000 crashed FrontBase\n  $limits{'max_text_size'}\t= 65000; # Max size with default buffers.\n  $limits{'query_size'}\t\t= 8000000; # Max size with default buffers.\n  $limits{'max_index'}\t\t= 38; # Max number of keys\n  $limits{'max_index_parts'}\t= 20; # Max segments/key\n  $limits{'max_column_name'}\t= 128; # max table and column name\n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables\n  $limits{'load_data_infile'}\t= 1; # Has load data infile\n  $limits{'lock_tables'}\t= 0; # Has lock tables\n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-)\n  $limits{'group_functions'}\t= 1; # Have group functions\n  $limits{'group_distinct_functions'}= 0; # Have count(distinct)\n  $limits{'select_without_from'}= 0;\n  $limits{'multi_drop'}\t\t= 0; # Drop table cannot take many tables\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries.\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING\n  $limits{'having_with_group'}\t= 0; # Can use group functions in HAVING\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1'\n  $limits{'group_by_position'}  = 0; # Use of 'GROUP BY 1'\n  $limits{'alter_table'}\t= 1; # Have ALTER TABLE\n  $limits{'alter_add_multi_col'}= 0; # Have ALTER TABLE t add a int,add b int;\n  $limits{'alter_table_dropcol'}= 0; # Have ALTER TABLE DROP column\n  $limits{'insert_multi_value'} = 1;\n\n  $limits{'group_func_extra_std'} = 0; # Does not have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod.\n  $limits{'func_extra_%'}\t= 0; # Does not have % as alias for mod()\n  $limits{'func_odbc_floor'}\t= 0; # Has func_odbc_floor function\n  $limits{'func_extra_if'}\t= 0; # Does not have function if.\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement.\n  $limits{'NEG'}\t\t= 1; # Supports -id\n  $limits{'func_extra_in_num'}\t= 0; # Has function in\n  $limits{'limit'}\t\t= 0; # Does not support the limit attribute\n  $limits{'insert_select'}\t= 0;\n  $limits{'order_by_unused'}\t= 0;\n\n  # We don't get an error for duplicate row in 'test-insert'\n  $limits{'unique_index'}\t= 0; # Unique index works or not\n  # We can't use a blob as a normal string (we got a wierd error)\n  $limits{'working_blobs'}\t= 0;\n  # 'select min(region),max(region) from bench1' kills the server after a while\n  $limits{'group_func_sql_min_str'} = 0;\n  # If you do select f1,f2,f3...f200 from table, Frontbase dies.\n  $limits{'working_all_fields'} = 0;\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n#  $dbh=$self->connect();\n#\n#  Pick up SQLGetInfo option SQL_DBMS_VER (18)\n#\n  #$version = $dbh->func(18, GetInfo);\n  $version=\"FrontBase 3.3\";\n#  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\n#\n# Connection with optional disabling of logging\n#\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, \n\t\t    $main::opt_user,\n\t\t    $main::opt_password,\n\t\t    { PrintError => 0 , \n\t\t      'fb_host'=>$main::opt_host\n\t\t    }) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n  $db->{AutoCommit}=1;\n  # $dbh->do(\"SET OPTION LOG_OFF=1,UPDATE_LOG=0\");\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n# If one uses $main::opt_fast then one is allowed to use\n# non standard types to get better speed.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index,$options) = @_;\n  my($query,@queries,@indexes,@keys);\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/ blob/ varchar(32000)/i;\n    $field =~ s/ big_decimal/ float/i;\n    $field =~ s/ double/ float/i;\n    $field =~ s/ tinyint/ smallint/i;\n    $field =~ s/ mediumint/ int/i;\n    $field =~ s/ integer/ int/i;\n    $field =~ s/ float\\(\\d,\\d\\)/ float/i;\n    $field =~ s/ smallint\\(\\d\\)/ smallint/i;\n    $field =~ s/ int\\(\\d\\)/ int/i;\n    $query.= $field . ',';\n  }\n  foreach $ind (@$index)\n  {\n#    my @index;\n    if ( $ind =~ /(\\bKEY\\b)|(\\bUNIQUE\\b)/i ){\n      push(@keys,\"ALTER TABLE $table_name ADD $ind\");\n    }else{\n      my @fields = split(' ',$ind);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@indexes,$query);\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  $query.=\" $options\" if (defined($options));\n  push(@queries,$query,@keys,@indexes);\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert of an ascii file isn't supported by InterBase\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index {\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0 if ($DBI::errstr =~ /No raw data handle/);\n  return 1;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 1;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n#############################################################################\n#\t     Configuration for SAPDB \n#############################################################################\n\npackage db_sapdb;\n\nsub new\n{\n  my ($type,$host,$database)= @_;\n  my $self= {};\n  my %limits;\n  bless $self;\n\n  $self->{'cmp_name'}\t\t= \"sapdb\";\n  $self->{'data_source'}\t= \"DBI:SAP_DB:$database\";\n  $self->{'limits'}\t\t= \\%limits;\n  $self->{'blob'}\t\t= \"LONG\"; # *\n  $self->{'text'}\t\t= \"LONG\"; # *\n  $self->{'double_quotes'}\t= 1; # Can handle:  'Walker''s'\n  $self->{'drop_attr'}\t\t= \"\";\n  $self->{'transactions'}\t= 1; # Transactions enabled *\n  $self->{'char_null'}          = \"\";\n  $self->{'numeric_null'}       = \"\";\n\n  $limits{'max_conditions'}\t= 9999; # (Actually not a limit) *\n  $limits{'max_columns'}\t= 1023;\t# Max number of columns in table *\n  $limits{'max_tables'}\t\t= 65000;\t# Should be big enough * unlimited actually\n  $limits{'max_text_size'}\t= 15000; # Max size with default buffers. \n  $limits{'query_size'}\t\t= 64*1024; # Max size with default buffers. *64 kb by default. May be set by system variable \n  $limits{'max_index'}\t\t= 510; # Max number of keys *\n  $limits{'max_index_parts'}\t= 16; # Max segments/key *\n  $limits{'max_column_name'}\t= 32; # max table and column name * \n\n  $limits{'join_optimizer'}\t= 1; # Can optimize FROM tables *\n  $limits{'load_data_infile'}\t= 0; # Has load data infile *\n  $limits{'lock_tables'}\t= 1; # Has lock tables \n  $limits{'functions'}\t\t= 1; # Has simple functions (+/-) *\n  $limits{'group_functions'}\t= 1; # Have group functions *\n  $limits{'group_func_sql_min_str'} = 1; # Can execute MIN() and MAX() on strings *\n  $limits{'group_distinct_functions'}= 1; # Have count(distinct)  *\n  $limits{'select_without_from'}= 0; # Cannot do 'select 1';  *\n  $limits{'multi_drop'}\t\t= 0; # Drop table cannot take many tables *\n  $limits{'subqueries'}\t\t= 1; # Supports sub-queries. *\n  $limits{'left_outer_join'}\t= 1; # Supports left outer joins *\n  $limits{'table_wildcard'}\t= 1; # Has SELECT table_name.*\n  $limits{'having_with_alias'}  = 0; # Can use aliases in HAVING *\n  $limits{'having_with_group'}\t= 1; # Can use group functions in HAVING *\n  $limits{'like_with_column'}\t= 1; # Can use column1 LIKE column2 *\n  $limits{'order_by_position'}  = 1; # Can use 'ORDER BY 1' *\n  $limits{'group_by_position'}  = 0; # Cannot use 'GROUP BY 1' *\n  $limits{'alter_table'}\t= 1; # Have ALTER TABLE *\n  $limits{'alter_add_multi_col'}= 1; # Have ALTER TABLE t add a int,add b int; *\n  $limits{'alter_table_dropcol'}= 1; # Have ALTER TABLE DROP column  *\n  $limits{'insert_multi_value'} = 0; # INSERT ... values (1,2),(3,4) *\n\n  $limits{'group_func_extra_std'} = 0; # Does not have group function std().\n\n  $limits{'func_odbc_mod'}\t= 0; # Have function mod. *\n  $limits{'func_extra_%'}\t= 0; # Does not have % as alias for mod() *\n  $limits{'func_odbc_floor'}\t= 1; # Has func_odbc_floor function *\n  $limits{'func_extra_if'}\t= 0; # Does not have function if. *\n  $limits{'column_alias'}\t= 1; # Alias for fields in select statement. *\n  $limits{'NEG'}\t\t= 1; # Supports -id *\n  $limits{'func_extra_in_num'}\t= 0; # Has function in *\n  $limits{'limit'}\t\t= 0; # Does not support the limit attribute *\n  $limits{'working_blobs'}\t= 1; # If big varchar/blobs works *\n  $limits{'order_by_unused'}\t= 1; # \n  $limits{'working_all_fields'} = 1; #\n  $limits{'multi_distinct'}     = 1; # allows select count(distinct a),count(distinct b).. \n\n\n  return $self;\n}\n\n#\n# Get the version number of the database\n#\n\nsub version\n{\n  my ($self)=@_;\n  my ($dbh,$sth,$version,@row);\n\n  $dbh=$self->connect();\n  $sth = $dbh->prepare(\"SELECT KERNEL FROM VERSIONS\") or die $DBI::errstr;\n  $version=\"SAP DB (unknown)\";\n  if ($sth->execute && (@row = $sth->fetchrow_array)\n      && $row[0] =~ /([\\d\\.]+)/)\n  {\n    $version=$row[0];\n    $version =~ s/KERNEL/SAP DB/i; \n  }\n  $sth->finish;\n  $dbh->disconnect;\n  $version .= \"/ODBC\" if ($self->{'data_source'} =~ /:ODBC:/);\n  return $version;\n}\n\n#\n# Connection with optional disabling of logging\n#\n\nsub connect\n{\n  my ($self)=@_;\n  my ($dbh);\n  $dbh=DBI->connect($self->{'data_source'}, $main::opt_user,\n\t\t    $main::opt_password,{ PrintError => 0, AutoCommit => 1}) ||\n\t\t      die \"Got error: '$DBI::errstr' when connecting to \" . $self->{'data_source'} .\" with user: '$main::opt_user' password: '$main::opt_password'\\n\";\n\n  return $dbh;\n}\n\n#\n# Returns a list of statements to create a table\n# The field types are in ANSI SQL format.\n#\n\nsub create\n{\n  my($self,$table_name,$fields,$index,$options) = @_;\n  my($query,@queries,$nr);\n  my @index;\n  my @keys;\n\n  $query=\"create table $table_name (\";\n  foreach $field (@$fields)\n  {\n    $field =~ s/\\bmediumint\\b/int/i;\n    $field =~ s/\\btinyint\\b/int/i;\n    $field =~ s/ int\\(\\d\\)/ int/i;\n    $field =~ s/BLOB/LONG/i;\n    $field =~ s/INTEGER\\s*\\(\\d+\\)/INTEGER/i;\n    $field =~ s/SMALLINT\\s*\\(\\d+\\)/SMALLINT/i;\n    $field =~ s/FLOAT\\s*\\((\\d+),\\d+\\)/FLOAT\\($1\\)/i;\n    $field =~ s/DOUBLE/FLOAT\\(38\\)/i;\n    $field =~ s/DOUBLE\\s+PRECISION/FLOAT\\(38\\)/i;\n    $query.= $field . ',';\n  }\n  $nr=0;\n  foreach $ind (@$index)\n  {\n    if ( $ind =~ /\\bKEY\\b/i ){\n      push(@keys,\"ALTER TABLE $table_name ADD $ind\");\n    } elsif ($ind =~ /^unique.*\\(([^\\(]*)\\)$/i)  {\n      $nr++;\n      my $query=\"create unique index ${table_name}_$nr on $table_name ($1)\";\n      push(@index,$query);\n    }else{\n      my @fields = split(' ',$ind);\n      my $query=\"CREATE INDEX $fields[1] ON $table_name $fields[2]\";\n      push(@index,$query);\n    }\n  }\n  substr($query,-1)=\")\";\t\t# Remove last ',';\n  $query.=\" $options\" if (defined($options));\n  push(@queries,$query);\n  push(@queries,@keys);\n  push(@queries,@index);\n  return @queries;\n}\n\nsub insert_file {\n  my($self,$dbname, $file) = @_;\n  print \"insert of an ascii file isn't supported by SAPDB\\n\";\n  return 0;\n}\n\n#\n# Do any conversions to the ANSI SQL query so that the database can handle it\n#\n\nsub query {\n  my($self,$sql) = @_;\n  return $sql;\n}\n\nsub drop_index {\n  my ($self,$table,$index) = @_;\n  return \"DROP INDEX $index\";\n}\n\n#\n# Abort if the server has crashed\n# return: 0 if ok\n#\t  1 question should be retried\n#\n\nsub abort_if_fatal_error\n{\n  return 0;\n}\n\nsub small_rollback_segment\n{\n  return 0;\n}\n\nsub reconnect_on_errors\n{\n  return 0;\n}\n\nsub fix_for_insert\n{\n  my ($self,$cmd) = @_;\n  return $cmd;\n}\n\n1;\n", "num_lines": 3627}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of alter table\n#\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_start_field_count=8;\t# start with this many fields\n$opt_loop_count=100;\t\t# How many tests to do\n$opt_row_count=1000; \t\t# Rows in the table\n$opt_field_count=1000;\t\t# Add until this many fields.\n$opt_time_limit=10*60;\t\t# Don't wait more than 10 min for some tests\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$opt_field_count=min($opt_field_count,$limits->{'max_columns'},\n\t\t     ($limits->{'query_size'}-30)/14);\n$opt_start_field_count=min($opt_start_field_count,$limits->{'max_index'});\n\nif ($opt_small_test)\n{\n  $opt_row_count/=10;\n  $opt_field_count/=10;\n}\n\nif (!$limits->{'alter_table'})\n{\n  print(\"Some of the servers given with --cmp or --server doesn't support ALTER TABLE\\nTest aborted\\n\\n\");\n  $start_time=new Benchmark;\n  end_benchmark($start_time);\n  exit 0;\n}\n\nprint \"Testing of ALTER TABLE\\n\";\nprint \"Testing with $opt_field_count columns and $opt_row_count rows in $opt_loop_count steps\\n\";\n\n####\n#### Create a table and fill it with data\n####\n\n$dbh = $server->connect();\n@fields=();\n@index=();\npush(@fields,\"i1 int not null\");\nfor ($i=2 ; $i <= $opt_start_field_count ; $i++)\n{\n  push(@fields,\"i${i} int not null\");\n}\n$field_count= $opt_start_field_count;\n\n$start_time=new Benchmark;\n\n$dbh->do(\"drop table bench\" . $server->{'drop_attr'});\ndo_many($dbh,$server->create(\"bench\",\\@fields,\\@index));\n\nprint \"Insert data into the table\\n\";\n\n$loop_time=new Benchmark;\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->{AutoCommit} = 0;\n  print \"Transactions enabled\\n\" if ($opt_debug);\n}\n\nfor ($i=0 ; $i < $opt_row_count ; $i++)\n{\n  $query=\"insert into bench values ( \" . (\"$i,\" x ($opt_start_field_count-1)) . \"$i)\";\n  $dbh->do($query) or die $DBI::errstr;\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\n\nprint \"Time for insert ($opt_row_count)\",\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n\n####\n#### Add fields to the table.\n####\n\n$loop_time=new Benchmark;\n$add= int(($opt_field_count-$opt_start_field_count)/$opt_loop_count)+1;\n\n$multi_add=$server->{'limits'}->{'alter_add_multi_col'} == 1;\nif ($opt_fast)\n{\n  $add=1 if (!$server->{'limits'}->{'alter_add_multi_col'});\n}\nelse\n{\n  $add=1 if (!$limits->{'alter_add_multi_col'});\n}\n\n$count=0;\nwhile ($field_count < $opt_field_count)\n{\n  $count++;\n  $end=min($field_count+$add,$opt_field_count);\n  $fields=\"\";\n  $tmp=\"ADD \";\n  while ($field_count < $end)\n  {\n    $field_count++;\n    $fields.=\",$tmp i${field_count} integer\";\n    $tmp=\"\" if (!$multi_add);\t\t\t# Adabas\n  }\n  do_query($dbh,\"ALTER TABLE bench \" . substr($fields,1));\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$count,\n\t\t\t\t\t $opt_field_count/$add+1));\n}\n\n$end_time=new Benchmark;\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for alter_table_add ($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n#\n# If estimated, fix table to have known number of fields\n#\nif ($estimated && $field_count < $opt_field_count)\n{\n  $fields=\"\";\n  $tmp=\"ADD \";\n  while ($field_count < $opt_field_count)\n  {\n    $field_count++;\n    $fields.=\",$tmp i${field_count} integer\";\n    $tmp=\"\" if (!$multi_add);\t\t\t# Adabas\n  }\n  do_query($dbh,\"ALTER TABLE bench \" . substr($fields,1));\n}\n\n####\n#### Test adding and deleting index on the first $opt_start_fields\n####\n\n$loop_time=new Benchmark;\n\n$count= 0;\nfor ($i=1; $i <= $opt_start_field_count ; $i++)\n{\n  $dbh->do(\"CREATE INDEX bench_ind$i ON bench (i${i})\") || die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for create_index ($opt_start_field_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n$loop_time=new Benchmark;\nfor ($i=1; $i <= $opt_start_field_count ; $i++)\n{\n  $dbh->do($server->drop_index(\"bench\",\"bench_ind$i\")) || die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for drop_index ($opt_start_field_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n####\n#### Delete fields from the table\n####\n\ngoto skip_dropcol if (!$limits->{'alter_table_dropcol'});\n\n$loop_time=new Benchmark;\n\n$count=0;\nwhile ($field_count > $opt_start_field_count)\n{\n  $count++;\n  $end=max($field_count-$add,$opt_start_field_count);\n  $fields=\"\";\n  while(--$field_count >= $end)\n  {\n    $fields.=\",DROP i${field_count}\";\n  }\n  $dbh->do(\"ALTER TABLE bench \" . substr($fields,1) . $server->{'drop_attr'})\n  || die $DBI::errstr;\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$count,\n\t\t\t\t\t $opt_field_count/$add+1));\n}\n\n$end_time=new Benchmark;\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for alter_table_drop ($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nskip_dropcol:\n\n################################ END ###################################\n####\n#### End of the test...Finally print time used to execute the\n#### whole test.\n\n$dbh->do(\"drop table bench\" . $server->{'drop_attr'});\n\n$dbh->disconnect;\n\nend_benchmark($start_time);\n", "num_lines": 236}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of creating the ATIS database and doing many different selects on it\n#\n# changes made for Oracle compatibility\n# - added Oracle to the '' to ' ' translation\n# - skip blank lines from the datafiles\n# - skip a couple of the tests in Q4 that Oracle doesn't understand\n################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count=100;\t\t# Run selects this many times\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=10;\n}\n\nprint \"ATIS table test\\n\\n\";\n\n####\n####  Connect and start timeing\n####\n\n$dbh = $server->connect();\n$start_time=new Benchmark;\n\n####\n#### Create needed tables\n####\n\ninit_data();\t\t\t# Get table definitions\n\nif (!$opt_skip_create)\n{\n  print \"Creating tables\\n\";\n  $loop_time= new Benchmark;\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    my $array_ref = $tables[$ti];\n\n    # This may fail if we have no table so do not check answer\n    $sth = $dbh->do(\"drop table $table_name\" . $server->{'drop_attr'});\n\n    print \"Creating table $table_name\\n\" if ($opt_verbose);\n    do_many($dbh,@$array_ref);\n  }\n  $end_time=new Benchmark;\n  print \"Time for create_table (\" . ($#tables+1) .\"): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n  if ($opt_fast && defined($server->{vacuum}))\n  {\n    $server->vacuum(0,\\$dbh);\n  }\n\n####\n#### Insert data\n####\n\n  print \"Inserting data\\n\";\n\n  $loop_time= new Benchmark;\n  $row_count=0;\n  $double_quotes=$server->{'double_quotes'};\n\n  if ($opt_lock_tables)\n  {\n    @tmp=@table_names; push(@tmp,@extra_names);\n    print \"LOCK TABLES @tmp\\n\" if ($opt_debug);\n    $sth = $dbh->do(\"LOCK TABLES \" . join(\" WRITE,\", @tmp) . \" WRITE\") ||\n      die $DBI::errstr;\n  }\n\n  if ($opt_fast && $server->{'limits'}->{'load_data_infile'})\n  {\n    for ($ti = 0; $ti <= $#table_names; $ti++)\n    {\n      my $table_name = $table_names[$ti];\n      my $file = \"$pwd/Data/ATIS/${table_name}.txt\";\n      print \"$table_name - $file\\n\" if ($opt_debug);\n      $row_count += $server->insert_file($table_name,$file,$dbh);\n    }\n  }\n  else\n  {\n    if ($opt_fast && $server->{transactions})\n    {\n      $dbh->{AutoCommit} = 0;\n      print \"Transactions enabled\\n\" if ($opt_debug);\n    }\n\n    for ($ti = 0; $ti <= $#table_names; $ti++)\n    {\n      my $table_name = $table_names[$ti];\n      my $array_ref = $tables[$ti];\n      my @table = @$array_ref;\n      my $insert_start = \"insert into $table_name values (\";\n\n      open(DATA, \"$pwd/Data/ATIS/${table_name}.txt\") || die \"Can't open text file: $pwd/Data/ATIS/${table_name}.txt\\n\";\n      while(<DATA>)\n      {\n\tchomp;\n\tnext unless ( $_ =~ /\\w/ );\t# skip blank lines\n\tmy $command = $insert_start . $_ . \")\";\n        $command = $server->fix_for_insert($command);\n\tprint \"$command\\n\" if ($opt_debug);\n        $command =~ s/\\\\'/\\'\\'/g if ($double_quotes);\n\n\t$sth = $dbh->do($command) or die \"Got error: $DBI::errstr when executing '$command'\\n\";\n\t$row_count++;\n      }\n    }\n    if ($opt_fast && $server->{transactions})\n    {\n      $dbh->commit;\n      $dbh->{AutoCommit} = 1;\n    }\n    close(DATA);\n  }\n\n  if ($opt_lock_tables)\n  {\n    $dbh->do(\"UNLOCK TABLES\");\n  }\n  $end_time=new Benchmark;\n  print \"Time to insert ($row_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh,@table_names);\n}\n\nif ($opt_lock_tables)\n{\n  @tmp=@table_names; push(@tmp,@extra_names);\n  $sth = $dbh->do(\"LOCK TABLES \" . join(\" READ,\", @tmp) . \" READ\") ||\n    die $DBI::errstr;\n}\n#\n# Now the fun begins.  Let's do some simple queries on the result\n#\n# The query array is defined as:\n# query, number of rows in result, 0|1 where 1 means that the query is possible\n#\n\nprint \"Retrieving data\\n\";\n@Q1=(\"select_simple_join\",\n     \"select city.city_name,state.state_name,city.city_code from city,state where city.city_code='MATL' and city.state_code=state.state_code\",1,1,\n     \"select city.city_name,state.state_name,city.city_code from state,city where city.state_code=state.state_code\",11,1,\n     \"select month_name.month_name,day_name.day_name from month_name,day_name where month_name.month_number=day_name.day_code\",7,1,\n     \"select month_name.month_name,day_name.day_name from month_name,day_name where month_name.month_number=day_name.day_code and day_name.day_code >= 4\",4,1,\n     \"select flight.flight_code,aircraft.aircraft_type from flight,aircraft where flight.aircraft_code=aircraft.aircraft_code\",579,1,\n     );\n\n@Q2=(\"select_join\",\n     \"select airline.airline_name,aircraft.aircraft_type from aircraft,airline,flight where flight.aircraft_code=aircraft.aircraft_code and flight.airline_code=airline.airline_code\",579,1);\n\n@Q21=(\"select_key_prefix_join\",\n     \"select fare.fare_code from restrict_carrier,airline,fare where restrict_carrier.airline_code=airline.airline_code and fare.restrict_code=restrict_carrier.restrict_code\",5692,1,\n    );\n\n@Q3=(\"select_distinct\",\n     \"select distinct category from aircraft\",6,1,\n     \"select distinct from_airport from flight\",9,1,\n     \"select distinct aircraft_code from flight\",22,1,\n     \"select distinct * from fare\",534,1,\n     \"select distinct flight_code from flight_fare\",579,1,\n     \"select distinct flight.flight_code,aircraft.aircraft_type from flight,aircraft where flight.aircraft_code=aircraft.aircraft_code\",579,1,\n     \"select distinct airline.airline_name,aircraft.aircraft_type from aircraft,airline,flight where flight.aircraft_code=aircraft.aircraft_code and flight.airline_code=airline.airline_code\",44,$limits->{'join_optimizer'},\n     \"select distinct airline.airline_name,aircraft.aircraft_type from flight,aircraft,airline where flight.aircraft_code=aircraft.aircraft_code and flight.airline_code=airline.airline_code\",44,1,\n     );\n\n@Q4=(\"select_group\",\n     \"select day_name.day_name,day_name.day_code,count(*) from flight_day,day_name where day_name.day_code=flight_day.day_code group by day_name.day_name,day_name.day_code order by day_name.day_code\",7,$limits->{'group_functions'},\n     \"select day_name.day_name,count(*) from flight_day,day_name where day_name.day_code=flight_day.day_code group by day_name.day_name\",7,$limits->{'group_functions'},\n     \"select month_name,day_name from month_name,day_name where month_number=day_code and day_code>3 group by month_name,day_name\",4,$limits->{'group_functions'},\n     \"select day_name.day_name,flight_day.day_code,count(*) from flight_day,day_name where day_name.day_code=flight_day.day_code group by flight_day.day_code,day_name.day_name order by flight_day.day_code\",7,$limits->{'group_functions'},\n     \"select sum(engines) from aircraft\",1,$limits->{'group_functions'},\n     \"select avg(engines) from aircraft\",1,$limits->{'group_functions'},\n     \"select avg(engines) from aircraft where engines>0\",1,$limits->{'group_functions'},\n     \"select count(*),min(pay_load),max(pay_load) from aircraft where pay_load>0\",1,$limits->{'group_functions'},\n     \"select min(flight_code),min(flight_code) from flight\",1,$limits->{'group_functions'},\n     \"select min(from_airport),min(to_airport) from flight\",1,$limits->{'group_functions'} && $limits->{'group_func_sql_min_str'},\n     \"select count(*) from aircraft where pay_load>10000\",1,$limits->{'group_functions'},\n     \"select count(*) from aircraft where pay_load<>0\",1,$limits->{'group_functions'},\n     \"select count(*) from flight where flight_code >= 112793\",1,$limits->{'group_functions'},\n     \"select count(if(pay_load,1,NULL)) from aircraft\",1,$limits->{'if'} && $limits->{'group_functions'},\n     \"select std(engines) from aircraft\",1,$limits->{'group_func_extra_std'},\n     \"SELECT from_airport,to_airport,avg(time_elapsed) FROM flight WHERE from_airport='ATL' AND to_airport='BOS' group by from_airport,to_airport\",1,$limits->{'group_functions'},\n     \"select city_code, avg(ground_fare) from ground_service where ground_fare<>0 group by city_code\",11,$limits->{'group_functions'},\n     \"select count(*), ground_service.city_code from ground_service group by ground_service.city_code\",12,$limits->{'group_functions'},\n     \"select category,count(*) as totalnr from aircraft where engines=2 group by category having totalnr>4\",3,$limits->{'group_functions'} && $limits->{'having_with_alias'},\n     \"select category,count(*) from aircraft where engines=2 group by category having count(*)>4\",3,$limits->{'group_functions'} && $limits->{'having_with_group'},\n     \"select flight_number,range_miles,fare_class FROM aircraft,flight,flight_class WHERE flight.flight_code=flight_class.flight_code AND flight.aircraft_code=aircraft.aircraft_code AND range_miles<>0 AND (stops=1 OR stops=2) GROUP BY flight_number,range_miles,fare_class\",150,$limits->{'group_functions'},\n     \"select distinct from_airport.time_zone_code,to_airport.time_zone_code,(FLOOR(arrival_time/100)*60+MOD(arrival_time,100)-FLOOR(departure_time/100)*60-MOD(departure_time,100)-time_elapsed)/60 AS time_zone_diff FROM flight,airport AS from_airport,airport AS to_airport WHERE flight.from_airport=from_airport.airport_code AND flight.to_airport=to_airport.airport_code GROUP BY from_airport.time_zone_code,to_airport.time_zone_code,arrival_time,departure_time,time_elapsed\",21,$limits->{'func_odbc_mod'} && $limits->{'func_odbc_floor'} && $limits->{'group_functions'},\n     \"select DISTINCT from_airport.time_zone_code,to_airport.time_zone_code,MOD((FLOOR(arrival_time/100)*60+MOD(arrival_time,100)-FLOOR(departure_time/100)*60-MOD(departure_time,100)-time_elapsed)/60+36,24)-12 AS time_zone_diff FROM flight,airport AS from_airport,airport AS to_airport WHERE flight.from_airport=from_airport.airport_code AND flight.to_airport=to_airport.airport_code and MOD((FLOOR(arrival_time/100)*60+MOD(arrival_time,100)-FLOOR(departure_time/100)*60-MOD(departure_time,100)-time_elapsed)/60+36,24)-12 < 10\",14,$limits->{'func_odbc_mod'} && $limits->{'func_odbc_floor'} && $limits->{'group_functions'},\n     \"select from_airport,to_airport,range_miles,time_elapsed FROM aircraft,flight WHERE aircraft.aircraft_code=flight.aircraft_code AND to_airport NOT LIKE from_airport AND range_miles<>0 AND time_elapsed<>0 GROUP BY from_airport,to_airport,range_miles,time_elapsed\",409,$limits->{'group_functions'} && $limits->{'like_with_column'},\n     \"SELECT airport.country_name,state.state_name,city.city_name,airport_service.direction FROM airport_service,state,airport,city WHERE airport_service.city_code=city.city_code AND airport_service.airport_code=airport.airport_code AND state.state_code=airport.state_code AND state.state_code=city.state_code AND airport.state_code=city.state_code AND airport.country_name=city.country_name AND airport.country_name=state.country_name AND city.time_zone_code=airport.time_zone_code GROUP BY airport.country_name,state.state_name,city.city_name,airport_service.direction ORDER BY state_name\",11,$limits->{'group_functions'},\n     \"SELECT airport.country_name,state.state_name,city.city_name,airport_service.direction FROM airport_service,state,airport,city WHERE airport_service.city_code=city.city_code AND airport_service.airport_code=airport.airport_code AND state.state_code=airport.state_code AND state.state_code=city.state_code AND airport.state_code=city.state_code AND airport.country_name=city.country_name AND airport.country_name=state.country_name AND city.time_zone_code=airport.time_zone_code GROUP BY airport.country_name,state.state_name,city.city_name,airport_service.direction ORDER BY state_name DESC\",11,$limits->{'group_functions'},\n     \"SELECT airport.country_name,state.state_name,city.city_name,airport_service.direction FROM airport_service,state,airport,city WHERE airport_service.city_code=city.city_code AND airport_service.airport_code=airport.airport_code AND state.state_code=airport.state_code AND state.state_code=city.state_code AND airport.state_code=city.state_code AND airport.country_name=city.country_name AND airport.country_name=state.country_name AND city.time_zone_code=airport.time_zone_code GROUP BY airport.country_name,state.state_name,city.city_name,airport_service.direction ORDER BY state_name\",11,$limits->{'group_functions'},\n     \"SELECT from_airport,to_airport,fare.fare_class,night,one_way_cost,rnd_trip_cost,class_days FROM compound_class,fare WHERE compound_class.fare_class=fare.fare_class AND one_way_cost <= 825 AND one_way_cost >= 280 AND from_airport='SFO' AND to_airport='DFW' GROUP BY from_airport,to_airport,fare.fare_class,night,one_way_cost,rnd_trip_cost,class_days ORDER BY one_way_cost\",10,$limits->{'group_functions'},\n     \"select engines,category,cruising_speed,from_airport,to_airport FROM aircraft,flight WHERE category='JET' AND engines >= 1 AND aircraft.aircraft_code=flight.aircraft_code AND to_airport NOT LIKE from_airport AND stops>0 GROUP BY engines,category,cruising_speed,from_airport,to_airport ORDER BY engines DESC\",29,$limits->{'group_functions'} && $limits->{'like_with_column'},\n     );\n\n@Q=(\\@Q1,\\@Q2,\\@Q21,\\@Q3,\\@Q4);\n\n\nforeach $Q (@Q)\n{\n  $count=$estimated=0;\n  $loop_time= new Benchmark;\n  for ($i=1 ; $i <= $opt_loop_count; $i++)\n  {\n    for ($j=1 ; $j < $#$Q ; $j+=3)\n    {\n      if ($Q->[$j+2])\n      {\t\t\t\t# We can do it with current limits\n\t$count++;\n\tif ($i == 100)\t\t# Do something different\n\t{\n\t  if (($row_count=fetch_all_rows($dbh,$server->query($Q->[$j]))) !=\n\t      $Q->[$j+1])\n\t  {\n\t    if ($row_count == undef())\n\t    {\n\t      die \"Got error: $DBI::errstr when executing \" . $Q->[$j] .\"\\n\".\"got $row_count instead of $Q->[$j+1] *** \\n\";\n\t    }\n\t    print \"Warning: Query '\" . $Q->[$j] . \"' returned $row_count rows when it should have returned \" . $Q->[$j+1] . \" rows\\n\";\n\t  }\n\t}\n\telse\n\t{\n\t  defined(fetch_all_rows($dbh,$server->query($Q->[$j])))\n\t    or die \"ERROR: $DBI::errstr executing '$Q->[$j]'\\n\";\n\t}\n      }\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i,\n\t\t\t\t\t   $opt_loop_count));\n    print \"Loop $i\\n\" if ($opt_verbose);\n  }\n  if ($count)\n  {\n    if ($estimated)\n    { print \"Estimated time\"; }\n    else\n    { print \"Time\"; }\n    print  \" for \" . $Q->[0] . \" ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n  }\n}\n\nprint \"\\n\";\n\n####\n#### Delete the tables\n####\n\nif (!$opt_skip_delete)\t\t\t\t# Only used when testing\n{\n  print \"Removing tables\\n\";\n  $loop_time= new Benchmark;\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n  }\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    $sth = $dbh->do(\"drop table $table_name\" . $server->{'drop_attr'});\n  }\n\n  $end_time=new Benchmark;\n  print \"Time to drop_table (\" .($#table_names+1) . \"): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n####\n#### End of benchmark\n####\n\n$dbh->disconnect;\t\t\t\t# close connection\n\nend_benchmark($start_time);\n\n\nsub init_data\n{\n  @aircraft=\n    $server->create(\"aircraft\",\n\t\t    [\"aircraft_code char(3) NOT NULL\",\n\t\t     \"aircraft_type char(64) NOT NULL\",\n\t\t     \"engines tinyint(1) NOT NULL\",\n\t\t     \"category char(10) NOT NULL\",\n\t\t     \"wide_body char(3) NOT NULL\",\n\t\t     \"wing_span float(6,2) NOT NULL\",\n\t\t     \"length1 float(6,2) NOT NULL\",\n\t\t     \"weight integer(7) NOT NULL\",\n\t\t     \"capacity smallint(3) NOT NULL\",\n\t\t     \"pay_load integer(7) NOT NULL\",\n\t\t     \"cruising_speed mediumint(5) NOT NULL\",\n\t\t     \"range_miles mediumint(5) NOT NULL\",\n\t\t     \"pressurized char(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (aircraft_code)\"]);\n  @airline=\n    $server->create(\"airline\",\n\t\t    [\"airline_code char(2) NOT NULL\",\n\t\t     \"airline_name char(64) NOT NULL\",\n\t\t     \"notes char(38) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (airline_code)\"]);\n  @airport=\n    $server->create(\"airport\",\n\t\t    [\"airport_code char(3) NOT NULL\",\n\t\t     \"airport_name char(40) NOT NULL\",\n\t\t     \"location char(36) NOT NULL\",\n\t\t     \"state_code char(2) NOT NULL\",\n\t\t     \"country_name char(25) NOT NULL\",\n\t\t     \"time_zone_code char(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (airport_code)\"]);\n  @airport_service=\n    $server->create(\"airport_service\",\n\t\t    [\"city_code char(4) NOT NULL\",\n\t\t     \"airport_code char(3) NOT NULL\",\n\t\t     \"miles_distant float(4,1) NOT NULL\",\n\t\t     \"direction char(3) NOT NULL\",\n\t\t     \"minutes_distant smallint(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (city_code, airport_code)\"]);\n  @city=\n    $server->create(\"city\",\n\t\t    [\"city_code char(4) NOT NULL\",\n\t\t     \"city_name char(25) NOT NULL\",\n\t\t     \"state_code char(2) NOT NULL\",\n\t\t     \"country_name char(25) NOT NULL\",\n\t\t     \"time_zone_code char(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (city_code)\"]);\n  @class_of_service=\n    $server->create(\"class_of_service\",\n\t\t    [\"class_code char(2) NOT NULL\",\n\t\t     \"rank tinyint(2) NOT NULL\",\n\t\t     \"class_description char(80) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (class_code)\"]);\n  @code_description=\n    $server->create(\"code_description\",\n\t\t    [\"code char(5) NOT NULL\",\n\t\t     \"description char(110) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (code)\"]);\n  @compound_class=\n    $server->create(\"compound_class\",\n\t\t    [\"fare_class char(3) NOT NULL\",\n\t\t     \"base_class char(2) NOT NULL\",\n\t\t     \"class_type char(10) NOT NULL\",\n\t\t     \"premium char(3) NOT NULL\",\n\t\t     \"economy char(3) NOT NULL\",\n\t\t     \"discounted char(3) NOT NULL\",\n\t\t     \"night char(3) NOT NULL\",\n\t\t     \"season_fare char(4) NOT NULL\",\n\t\t     \"class_days char(7) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (fare_class)\"]);\n  @connect_leg=\n    $server->create(\"connect_leg\",\n\t\t    [\"connect_code integer(8) NOT NULL\",\n\t\t     \"leg_number tinyint(1) NOT NULL\",\n\t\t     \"flight_code integer(8) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (connect_code, leg_number, flight_code)\"]);\n  @connection=\n    $server->create(\"fconnection\",\n\t\t    [\"connect_code integer(8) NOT NULL\",\n\t\t     \"from_airport char(3) NOT NULL\",\n\t\t     \"to_airport char(3) NOT NULL\",\n\t\t     \"departure_time smallint(4) NOT NULL\",\n\t\t     \"arrival_time smallint(4) NOT NULL\",\n\t\t     \"flight_days char(7) NOT NULL\",\n\t\t     \"stops tinyint(1) NOT NULL\",\n\t\t     \"connections tinyint(1) NOT NULL\",\n\t\t     \"time_elapsed smallint(4) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (connect_code)\",\n\t\t     \"INDEX from_airport1 (from_airport)\",\n\t\t     \"INDEX to_airport1 (to_airport)\"]);\n  @day_name=\n    $server->create(\"day_name\",\n\t\t    [\"day_code tinyint(1) NOT NULL\",\n\t\t     \"day_name char(9) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (day_code)\"]);\n  @dual_carrier=\n    $server->create(\"dual_carrier\",\n\t\t    [\"main_airline char(2) NOT NULL\",\n\t\t     \"dual_airline char(2) NOT NULL\",\n\t\t     \"low_flight smallint(4) NOT NULL\",\n\t\t     \"high_flight smallint(4) NOT NULL\",\n\t\t     \"fconnection_name char(64) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (main_airline, dual_airline, low_flight)\",\n\t\t     \"INDEX main_airline1 (main_airline)\"]);\n\n  @fare=\n    $server->create(\"fare\",\n\t\t    [\"fare_code char(8) NOT NULL\",\n\t\t     \"from_airport char(3) NOT NULL\",\n\t\t     \"to_airport char(3) NOT NULL\",\n\t\t     \"fare_class char(3) NOT NULL\",\n\t\t     \"fare_airline char(2) NOT NULL\",\n\t\t     \"restrict_code char(5) NOT NULL\",\n\t\t     \"one_way_cost float(7,2) NOT NULL\",\n\t\t     \"rnd_trip_cost float(8,2) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (fare_code)\",\n\t\t     \"INDEX from_airport2 (from_airport)\",\n\t\t     \"INDEX to_airport2 (to_airport)\"]);\n  @flight=\n    $server->create(\"flight\",\n\t\t    [\"flight_code integer(8) NOT NULL\",\n\t\t     \"flight_days char(7) NOT NULL\",\n\t\t     \"from_airport char(3) NOT NULL\",\n\t\t     \"to_airport char(3) NOT NULL\",\n\t\t     \"departure_time smallint(4) NOT NULL\",\n\t\t     \"arrival_time smallint(4) NOT NULL\",\n\t\t     \"airline_code char(2) NOT NULL\",\n\t\t     \"flight_number smallint(4) NOT NULL\",\n\t\t     \"class_string char(8) NOT NULL\",\n\t\t     \"aircraft_code char(3) NOT NULL\",\n\t\t     \"meal_code char(7) NOT NULL\",\n\t\t     \"stops tinyint(1) NOT NULL\",\n\t\t     \"dual_carrier char(1) NOT NULL\",\n\t\t     \"time_elapsed smallint(4) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (flight_code)\",\n\t\t     \"INDEX from_airport3 (from_airport)\",\n\t\t     \"INDEX to_airport3 (to_airport)\"]);\n  @flight_class=\n    $server->create(\"flight_class\",\n\t\t    [\"flight_code integer(8) NOT NULL\",\n\t\t     \"fare_class char(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (flight_code, fare_class)\"]);\n  @flight_day=\n    $server->create(\"flight_day\",\n\t\t    [\"day_mask char(7) NOT NULL\",\n\t\t     \"day_code tinyint(1) NOT NULL\",\n\t\t     \"day_name char(9) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (day_mask, day_code)\"]);\n  @flight_fare=\n    $server->create(\"flight_fare\",\n\t\t    [\"flight_code integer(8) NOT NULL\",\n\t\t     \"fare_code char(8) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (flight_code, fare_code)\"]);\n  @food_service=\n    $server->create(\"food_service\",\n\t\t    [\"meal_code char(4) NOT NULL\",\n\t\t     \"meal_number tinyint(1) NOT NULL\",\n\t\t     \"meal_class char(10) NOT NULL\",\n\t\t     \"meal_description char(10) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (meal_code, meal_number, meal_class)\"]);\n  @ground_service=\n    $server->create(\"ground_service\",\n\t\t    [\"city_code char(4) NOT NULL\",\n\t\t     \"airport_code char(3) NOT NULL\",\n\t\t     \"transport_code char(1) NOT NULL\",\n\t\t     \"ground_fare float(6,2) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (city_code, airport_code, transport_code)\"]);\n  @time_interval=\n    $server->create(\"time_interval\",\n\t\t    [\"period char(20) NOT NULL\",\n\t\t     \"begin_time smallint(4) NOT NULL\",\n\t\t     \"end_time smallint(4) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (period, begin_time)\"]);\n  @month_name=\n    $server->create(\"month_name\",\n\t\t    [\"month_number tinyint(2) NOT NULL\",\n\t\t     \"month_name char(9) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (month_number)\"]);\n  @restrict_carrier=\n    $server->create(\"restrict_carrier\",\n\t\t    [\"restrict_code char(5) NOT NULL\",\n\t\t     \"airline_code char(2) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (restrict_code, airline_code)\"]);\n  @restrict_class=\n    $server->create(\"restrict_class\",\n\t\t    [\"restrict_code char(5) NOT NULL\",\n\t\t     \"ex_fare_class char(12) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (restrict_code, ex_fare_class)\"]);\n  @restriction=\n    $server->create(\"restriction\",\n\t\t    [\"restrict_code char(5) NOT NULL\",\n\t\t     \"application char(80) NOT NULL\",\n\t\t     \"no_discounts char(80) NOT NULL\",\n\t\t     \"reserve_ticket smallint(3) NOT NULL\",\n\t\t     \"stopovers char(1) NOT NULL\",\n\t\t     \"return_min smallint(3) NOT NULL\",\n\t\t     \"return_max smallint(3) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (restrict_code)\"]);\n  @state=\n    $server->create(\"state\",\n\t\t    [\"state_code char(2) NOT NULL\",\n\t\t     \"state_name char(25) NOT NULL\",\n\t\t     \"country_name char(25) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (state_code)\"]);\n  @stop=\n    $server->create(\"stop1\",\n\t\t    [\"flight_code integer(8) NOT NULL\",\n\t\t     \"stop_number tinyint(1) NOT NULL\",\n\t\t     \"stop_flight integer(8) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (flight_code, stop_number)\"]);\n  @time_zone=\n    $server->create(\"time_zone\",\n\t\t    [\"time_zone_code char(3) NOT NULL\",\n\t\t     \"time_zone_name char(32) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (time_zone_code, time_zone_name)\"]);\n  @transport=\n    $server->create(\"transport\",\n\t\t    [\"transport_code char(1) NOT NULL\",\n\t\t     \"transport_desc char(32) NOT NULL\"],\n\t\t    [\"PRIMARY KEY (transport_code)\"]);\n\n# Avoid not used warnings\n\n  @tables =\n    (\\@aircraft, \\@airline, \\@airport, \\@airport_service,\n     \\@city, \\@class_of_service, \\@code_description,\n     \\@compound_class, \\@connect_leg, \\@connection, \\@day_name,\n     \\@dual_carrier, \\@fare, \\@flight, \\@flight_class, \\@flight_day,\n     \\@flight_fare, \\@food_service, \\@ground_service, \\@time_interval,\n     \\@month_name,\n     \\@restrict_carrier, \\@restrict_class, \\@restriction, \\@state, \\@stop,\n     \\@time_zone, \\@transport);\n\n  @table_names =\n    (\"aircraft\", \"airline\", \"airport\", \"airport_service\",\n     \"city\", \"class_of_service\", \"code_description\",\n     \"compound_class\", \"connect_leg\", \"fconnection\", \"day_name\",\n     \"dual_carrier\", \"fare\", \"flight\", \"flight_class\", \"flight_day\",\n     \"flight_fare\", \"food_service\", \"ground_service\", \"time_interval\",\n     \"month_name\",\n     \"restrict_carrier\", \"restrict_class\", \"restriction\", \"state\", \"stop1\",\n     \"time_zone\", \"transport\");\n\n# Alias used in joins\n  @extra_names=(\"airport as from_airport\",\"airport as to_airport\");\n}\n", "num_lines": 568}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of extreme tables.\n#\n\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count=1000; # Change this to make test harder/easier\n$opt_field_count=1000;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$opt_field_count=min($opt_field_count,$limits->{'max_columns'},\n\t\t     ($limits->{'query_size'}-30)/14);\n\n$opt_loop_count*=10 if ($opt_field_count<100);\t# mSQL has so few fields...\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=10;\n  $opt_field_count/=10;\n}\n\n\nprint \"Testing of some unusual tables\\n\";\nprint \"All tests are done $opt_loop_count times with $opt_field_count fields\\n\\n\";\n\n\n####\n####  Testing many fields\n####\n\n$dbh = $server->connect();\nprint \"Testing table with $opt_field_count fields\\n\";\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\n\nmy @fields=();\nmy @index=();\nmy $fields=\"i1\";\npush(@fields,\"$fields int\");\n$values= \"1,\" x ($opt_field_count-1) . \"1\";\nfor ($i=2 ; $i <= $opt_field_count ; $i++)\n{\n  push(@fields,\"i${i} int\");\n  $fields.=\",i${i}\";\n}\n\n$start_time=new Benchmark;\n\ndo_many($dbh,$server->create(\"bench1\",\\@fields,\\@index));\n$sth = $dbh->do(\"insert into bench1 values ($values)\") or die $DBI::errstr;\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\ntest_query(\"Testing select * from table with 1 record\",\n\t   \"Time to select_many_fields\",\n\t   \"select * from bench1\",\n\t   $dbh,$opt_loop_count);\n\n\nif ($limits->{'working_all_fields'})\n{\n  test_query(\"Testing select all_fields from table with 1 record\",\n\t     \"Time to select_many_fields\",\n\t     \"select $fields from bench1\",\n\t     $dbh,$opt_loop_count);\n}\n\ntest_query(\"Testing insert VALUES()\",\n\t   \"Time to insert_many_fields\",\n\t   \"insert into bench1 values($values)\",\n\t   $dbh,$opt_loop_count);\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\ntest_command(\"Testing insert (all_fields) VALUES()\",\n\t     \"Time to insert_many_fields\",\n\t     \"insert into bench1 ($fields) values($values)\",\n\t     $dbh,$opt_loop_count);\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'}) or die $DBI::errstr;\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n################################ END ###################################\n####\n#### End of the test...Finally print time used to execute the\n#### whole test.\n\n$dbh->disconnect;\n\nend_benchmark($start_time);\n\n\n############################ HELP FUNCTIONS ##############################\n\nsub test_query\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time, $using_transactions);\n\n  print $test_text . \"\\n\";\n  $loop_time=new Benchmark;\n\n  $using_transactions=0;\n  if ($opt_fast && server->{transactions} && $query=~ /^insert /i)\n  {\n    $using_transactions=1;\n    $dbh->{AutoCommit} = 0;\n    print \"Transactions enabled\\n\" if ($opt_debug);\n  }\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    defined(fetch_all_rows($dbh,$query)) or die $DBI::errstr;\n  }\n  if ($using_transactions)\n  {\n    $dbh->commit;\n    $dbh->{AutoCommit} = 1;\n  }\n\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\nsub test_command\n{\n  my($test_text,$result_text,$query,$dbh,$count)=@_;\n  my($i,$loop_time,$end_time);\n\n  print $test_text . \"\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $count ; $i++)\n  {\n    $dbh->do($query) or die $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print $result_text . \"($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n", "num_lines": 175}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# This test is for testing the speed of connections and sending\n# data to the client.\n#\n# By changing the variable '$opt_loop_count' value you can make this test\n# easier/harderto your computer to execute. You can also change this value\n# by using option --loop_value='what_ever_you_like'.\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count=100000;\t# Change this to make test harder/easier\n$str_length=65000;\t# This is the length of blob strings in PART:5\n$max_test=20;\t\t# How many times to test if the server is busy\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n# This is the length of blob strings in PART:5\n$str_length=min($limits->{'max_text_size'},$limits->{'query_size'}-30,$str_length);\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=100;\n}\n\n$opt_loop_count=min(1000, $opt_loop_count) if ($opt_tcpip);\n$small_loop_count=$opt_loop_count/10; # For connect tests\n\nprint \"Testing the speed of connecting to the server and sending of data\\n\";\nprint \"Connect tests are done $small_loop_count times and other tests $opt_loop_count times\\n\\n\";\n\n################################# PART:1 ###################################\n####\n####  Start timeing and start connect test..\n####\n\n$start_time=new Benchmark;\n\nprint \"Testing connection/disconnect\\n\";\n\n$loop_time=new Benchmark;\n$errors=0;\n\nfor ($i=0 ; $i < $small_loop_count ; $i++)\n{\n  print \"$i \" if (($opt_debug));\n  for ($j=0; $j < $max_test ; $j++)\n  {\n    if ($dbh = DBI->connect($server->{'data_source'}, $opt_user,\n\t\t\t    $opt_password))\n    {\n      $dbh->disconnect;\n      last;\n    }\n    select(undef, undef, undef, 0.01*$j);\n    print \"$errors \" if (($opt_debug));\n    $errors++;\n  }\n  die \"Got error '$DBI::errstr' after $i connects\" if ($j == $max_test);\n  $dbh->disconnect;\n  undef($dbh);\n}\n$end_time=new Benchmark;\nprint \"Warning: $errors connections didn't work without a time delay\\n\" if ($errors);\nprint \"Time to connect ($small_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n################################# PART:2 ###################################\n#### Now we shall do first one connect, then simple select\n#### (select 1..) and then close connection. This will be\n#### done $small_loop_count times.\n\nif ($limits->{'select_without_from'})\n{\n  print \"Test connect/simple select/disconnect\\n\";\n  $loop_time=new Benchmark;\n\n  for ($i=0; $i < $small_loop_count; $i++)\n  {\n    $dbh = DBI->connect($server->{'data_source'}, $opt_user, $opt_password) || die $DBI::errstr;\n    $sth = $dbh->do(\"select $i\") or die $DBI::errstr;\n    $dbh->disconnect;\n  }\n  $end_time=new Benchmark;\n  print \"Time for connect+select_simple ($small_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n################################# PART:3 ###################################\n####\n#### Okay..Next thing we'll do is a simple select $opt_loop_count times.\n####\n\n$dbh = DBI->connect($server->{'data_source'}, $opt_user, $opt_password,\n\t\t    { PrintError => 0}) || die $DBI::errstr;\n\nif ($limits->{'select_without_from'})\n{\n  print \"Test simple select\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $sth = $dbh->do(\"select $i\") or die $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print \"Time for select_simple ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n###########################################################################\n#### The same as the previous test, but always execute the same select\n#### This is done to test the query cache for real simple selects.\n\nif ($limits->{'select_without_from'})\n{\n  print \"Test simple select\\n\";\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $sth = $dbh->do(\"select 10000\") or die $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print \"Time for select_simple_cache ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n##########################################################################\n#### First, we'll create a simple table 'bench1'\n#### Then we shall do $opt_loop_count selects from this table.\n#### Table will contain very simple data.\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\ndo_many($dbh,$server->create(\"bench1\",\n\t\t\t     [\"a int NOT NULL\",\n\t\t\t      \"i int\",\n\t\t\t      \"s char(10)\"],\n\t\t\t     [\"primary key (a)\"]));\n$sth = $dbh->do(\"insert into bench1 values(1,100,'AAA')\") or die $DBI::errstr;\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n$dbh->disconnect;\n\n#\n# First test connect/select/disconnect\n#\nprint \"Testing connect/select 1 row from table/disconnect\\n\";\n\n$loop_time=new Benchmark;\n$errors=0;\n\nfor ($i=0 ; $i < $small_loop_count ; $i++)\n{\n  for ($j=0; $j < $max_test ; $j++)\n  {\n    last if ($dbh = DBI->connect($server->{'data_source'}, $opt_user, $opt_password));\n    $errors++;\n  }\n  die $DBI::errstr if ($j == $max_test);\n\n  $sth = $dbh->do(\"select a,i,s,$i from bench1\") # Select * from table with 1 record\n    or die $DBI::errstr;\n  $dbh->disconnect;\n}\n\n$end_time=new Benchmark;\nprint \"Warning: $errors connections didn't work without a time delay\\n\" if ($errors);\nprint \"Time to connect+select_1_row ($small_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n#\n# The same test, but without connect/disconnect\n#\nprint \"Testing select 1 row from table\\n\";\n\n$dbh = $server->connect();\n$loop_time=new Benchmark;\n\nfor ($i=0 ; $i < $opt_loop_count ; $i++)\n{\n  $sth = $dbh->do(\"select a,i,s,$i from bench1\") # Select * from table with 1 record\n    or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time to select_1_row ($opt_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n#\n# Same test (as with one row) but now with a cacheable query\n#\n\n$loop_time=new Benchmark;\n\nfor ($i=0 ; $i < $opt_loop_count ; $i++)\n{\n  $sth = $dbh->do(\"select a,i,s from bench1\") # Select * from table with 1 record\n    or die $DBI::errstr;\n}\n$end_time=new Benchmark;\nprint \"Time to select_1_row_cache ($opt_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n#\n# The same test, but with 2 rows (not cacheable).\n#\n\nprint \"Testing select 2 rows from table\\n\";\n\n$sth = $dbh->do(\"insert into bench1 values(2,200,'BBB')\")\n  or die $DBI::errstr;\n\n$loop_time=new Benchmark;\n\nfor ($i=0 ; $i < $opt_loop_count ; $i++)\n{\n  $sth = $dbh->do(\"select a,i,s,$i from bench1\") # Select * from table with 2 record\n    or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time to select_2_rows ($opt_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n#\n# Simple test to test speed of functions.\n#\n\nif ($limits->{'functions'})\n{\n  print \"Test select with aritmetic (+)\\n\";\n  $loop_time=new Benchmark;\n\n  for ($i=0; $i < $opt_loop_count; $i++)\n  {\n    $sth = $dbh->do(\"select a+a+a+a+a+a+a+a+a+$i from bench1\") or die $DBI::errstr;\n  }\n  $end_time=new Benchmark;\n  print \"Time for select_column+column ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'})\n  or die $DBI::errstr;\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n################################# PART:5 ###################################\n#### We'll create one table with a single blob field,but with a\n#### huge record in it and then we'll do $opt_loop_count selects\n#### from it.\n\ngoto skip_blob_test if (!$limits->{'working_blobs'});\n\nprint \"Testing retrieval of big records ($str_length bytes)\\n\";\n\ndo_many($dbh,$server->create(\"bench1\", [\"b blob\"], []));\n$dbh->{LongReadLen}= $str_length; # Set retrieval buffer\n\nmy $string=(A) x ($str_length); # This will make a string $str_length long.\n$sth = $dbh->prepare(\"insert into bench1 values(?)\") or die $dbh->errstr;\n$sth->execute($string) or die $sth->errstr;\nundef($string);\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n$loop_time=new Benchmark;\n\nfor ($i=0 ; $i < $small_loop_count ; $i++)\n{\n  $sth = $dbh->prepare(\"select b,$i from bench1\");\n  if (!$sth->execute || !(@row = $sth->fetchrow_array) ||\n      length($row[0]) != $str_length)\n  {\n    warn \"$DBI::errstr - \".length($row[0]).\" - $str_length **\\n\";\n  }\n  $sth->finish;\n}\n\n$end_time=new Benchmark;\nprint \"Time to select_big_str ($small_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'})\n  or do\n{\n    # Fix for Access 2000\n    die $dbh->errstr if (!$server->abort_if_fatal_error());\n};\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\nskip_blob_test:\n\n################################ END ###################################\n####\n#### End of the test...Finally print time used to execute the\n#### whole test.\n\n$dbh->disconnect;\nend_benchmark($start_time);\n", "num_lines": 333}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000-2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# This test is for testing how long it takes to create tables,\n# make a count(*) from them and finally drop the tables. These\n# commands will be done in different ways in this test.\n# Using option --fast will drop all the tables in the end\n# of this test with one command instead of making own\n# 'drop' command for each and every table.\n# By changing the variable '$table_amount' value you can make\n# this test a lot harder/easier for your computer to drive.\n# Note that when using value bigger than 64 for this variable\n# will do 'drop table'-command\tin totally different way because of that\n# how MySQL handles these commands.\n\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count=10000; # Change this to make test harder/easier\n# This is the default value for the amount of tables used in this test.\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$create_loop_count=$opt_loop_count;\nif ($opt_small_test)\n{\n  $opt_loop_count/=100;\n  $create_loop_count/=1000;\n}\n\n$max_tables=min($limits->{'max_tables'},$opt_loop_count);\n\nif ($opt_small_test)\n{\n  $max_tables=10;\n}\n\n\nprint \"Testing the speed of creating and dropping tables\\n\";\nprint \"Testing with $max_tables tables and $opt_loop_count loop count\\n\\n\";\n\n####\n####  Connect and start timeing\n####\n\n$dbh = $server->connect();\n\n### Test how the database can handle many tables\n### Create $max_tables ; Access all off them with a simple query\n### and then drop the tables\n\nif ($opt_force) # If tables used in this test exist, drop 'em\n{\n  print \"Okay..Let's make sure that our tables don't exist yet.\\n\\n\";\n  for ($i=1 ; $i <= $max_tables ; $i++)\n  {\n    $dbh->do(\"drop table bench_$i\" . $server->{'drop_attr'});\n  }\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\nprint \"Testing create of tables\\n\";\n\n$loop_time=$start_time=new Benchmark;\n\nfor ($i=1 ; $i <= $max_tables ; $i++)\n{\n  if (do_many($dbh,$server->create(\"bench_$i\",\n\t\t\t\t   [\"i int NOT NULL\",\n\t\t\t\t    \"d double\",\n\t\t\t\t    \"f float\",\n\t\t\t\t    \"s char(10)\",\n\t\t\t\t    \"v varchar(100)\"],\n\t\t\t\t   [\"primary key (i)\"])))\n  {\n    # Got an error; Do cleanup\n    for ($i=1 ; $i <= $max_tables ; $i++)\n    {\n      $dbh->do(\"drop table bench_$i\" . $server->{'drop_attr'});\n    }\n    die \"Test aborted\";\n  }\n}\n\n$end_time=new Benchmark;\nprint \"Time for create_MANY_tables ($max_tables): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n#### Here comes $max_tables couples of cont(*) to the tables.\n#### We'll check how long it will take...\n####\n\nprint \"Accessing tables\\n\";\n\nif ($limits->{'group_functions'})\n{\n  $query=\"select count(*) from \";\n  $type=\"select_group_when_MANY_tables\";\n}\nelse\n{\n  $query=\"select * from \";\n  $type=\"select_when_MANY_tables\";\n}\n\n$loop_time=new Benchmark;\nfor ($i=1 ; $i <= $max_tables ; $i++)\n{\n  $sth = $dbh->do(\"$query bench_$i\") or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time to $type ($max_tables): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n####\n#### Now we are going to drop $max_tables tables;\n####\n\nprint \"Testing drop\\n\";\n\n$loop_time=new Benchmark;\n\nif ($opt_fast && $server->{'limits'}->{'multi_drop'} &&\n    $server->{'limits'}->{'query_size'} > 11+$max_tables*10)\n{\n  my $query=\"drop table bench_1\";\n  for ($i=2 ; $i <= $max_tables ; $i++)\n  {\n    $query.=\",bench_$i\";\n  }\n  $sth = $dbh->do($query . $server->{'drop_attr'}) or die $DBI::errstr;\n}\nelse\n{\n  for ($i=1 ; $i <= $max_tables ; $i++)\n  {\n    $sth = $dbh->do(\"drop table bench_$i\" . $server->{'drop_attr'})\n      or die $DBI::errstr;\n  }\n}\n\n\n$end_time=new Benchmark;\nprint \"Time for drop_table_when_MANY_tables ($max_tables): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n#### We'll do first one 'create table' and then we'll drop it\n#### away immediately. This loop shall be executed $opt_loop_count\n#### times.\n\nprint \"Testing create+drop\\n\";\n\n$loop_time=new Benchmark;\n\nfor ($i=1 ; $i <= $create_loop_count ; $i++)\n{\n  do_many($dbh,$server->create(\"bench_$i\",\n\t\t\t       [\"i int NOT NULL\",\n\t\t\t\t\"d double\",\n\t\t\t\t\"f float\",\n\t\t\t\t\"s char(10)\",\n\t\t\t\t\"v varchar(100)\"],\n\t\t\t       [\"primary key (i)\"]));\n  $sth = $dbh->do(\"drop table bench_$i\" . $server->{'drop_attr'}) or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for create+drop ($create_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n#\n# Same test, but with a table with many keys\n#\n\nmy @fields=(); my @keys=();\n$keys=min($limits->{'max_index'},16);\t\t# 16 is more than enough\n$seg= min($limits->{'max_index_parts'},$keys,16);\t# 16 is more than enough\n\n# Make keys on the most important types\n@types=(0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1);\t# A 1 for each char field\npush(@fields,\"field1 tinyint not null\");\npush(@fields,\"field2 mediumint not null\");\npush(@fields,\"field3 smallint not null\");\npush(@fields,\"field4 char(16) not null\");\npush(@fields,\"field5 integer not null\");\npush(@fields,\"field6 float not null\");\npush(@fields,\"field7 double not null\");\nfor ($i=8 ; $i <= $keys ; $i++)\n{\n  push(@fields,\"field$i char(5) not null\");\t# Should be relatively fair\n}\n\n# Let first key contain many segments\nmy $query=\"primary key (\";\nfor ($i= 1 ; $i <= $seg ; $i++)\n{\n  $query.= \"field$i,\";\n}\nsubstr($query,-1)=\")\";\npush (@keys,$query);\n\n#Create other keys\nfor ($i=2 ; $i <= $keys ; $i++)\n{\n  push(@keys,\"index index$i (field$i)\");\n}\n\n$loop_time=new Benchmark;\nfor ($i=1 ; $i <= $opt_loop_count ; $i++)\n{\n  do_many($dbh,$server->create(\"bench_$i\", \\@fields, \\@keys));\n  $dbh->do(\"drop table bench_$i\" . $server->{'drop_attr'}) or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for create_key+drop ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n####\n#### End of benchmark\n####\n\n$dbh->disconnect;\t\t\t\t# close connection\nend_benchmark($start_time);\n", "num_lines": 270}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000-2003, 2006, 2007 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of creating a simple table and inserting $record_count records in it,\n# $opt_loop_count rows in order, $opt_loop_count rows in reverse order and\n# $opt_loop_count rows in random order\n#\n# changes made for Oracle compatibility\n# - $limits->{'func_odbc_mod'} is OK from crash-me, but it fails here so set we\n#   set it to 0 in server-cfg\n# - the default server config runs out of rollback segments, so we added a\n#   couple of disconnect/connects to reset\n#\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\nuse Data::Dumper;\n\n$opt_loop_count=100000;\t\t# number of rows/3\n$small_loop_count=10;\t\t# Loop for full table retrieval\n$range_loop_count=$small_loop_count*50;\n$many_keys_loop_count=$opt_loop_count;\n$opt_read_key_loop_count=$opt_loop_count;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=100;\n  $many_keys_loop_count=$opt_loop_count/10;\n  $range_loop_count=10;\n  $opt_read_key_loop_count=10;\n}\nelsif ($opt_small_tables)\n{\n  $opt_loop_count=10000;\t\t# number of rows/3\n  $many_keys_loop_count=$opt_loop_count;\n  $opt_read_key_loop_count=10;\n}\nelsif ($opt_small_key_tables)\n{\n  $many_keys_loop_count/=10;\n}\n\nif ($opt_loop_count < 100)\n{\n  $opt_loop_count=100;\t\t# Some tests must have some data to work!\n}\n$range_loop_count=min($opt_loop_count,$range_loop_count);\n\n\nprint \"Testing the speed of inserting data into 1 table and do some selects on it.\\n\";\nprint \"The tests are done with a table that has $opt_loop_count rows.\\n\\n\";\n\n####\n#### Generating random keys\n####\n\nprint \"Generating random keys\\n\";\n$random[$opt_loop_count]=0;\nfor ($i=0 ; $i < $opt_loop_count ; $i++)\n{\n  $random[$i]=$i+$opt_loop_count;\n}\n\nmy $tmpvar=1;\nfor ($i=0 ; $i < $opt_loop_count ; $i++)\n{\n  $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count);\n  $swap=$tmpvar % $opt_loop_count;\n  $tmp=$random[$i]; $random[$i]=$random[$swap]; $random[$swap]=$tmp;\n}\n\n$total_rows=$opt_loop_count*3;\n\n####\n####  Connect and start timeing\n####\n$start_time=new Benchmark;\n$dbh = $server->connect();\n####\n#### Create needed tables\n####\n\ngoto keys_test if ($opt_stage == 2);\ngoto select_test if ($opt_skip_create);\n\nprint \"Creating tables\\n\";\n$dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\n$dbh->do(\"drop table bench2\" . $server->{'drop_attr'});\n$dbh->do(\"drop table bench3\" . $server->{'drop_attr'});\ndo_many($dbh,$server->create(\"bench1\",\n\t\t\t     [\"id int NOT NULL\",\n\t\t\t      \"id2 int NOT NULL\",\n\t\t\t      \"id3 int NOT NULL\",\n\t\t\t      \"dummy1 char(30)\"],\n\t\t\t     [\"primary key (id,id2)\",\n\t\t\t     \"index ix_id3 (id3)\"]));\n\nif ($opt_lock_tables)\n{\n  $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n}\n\n####\n#### Insert $total_rows records in order, in reverse order and random.\n####\n\n$loop_time=new Benchmark;\n\nif ($opt_fast_insert)\n{\n  $query=\"insert into bench1 values \";\n}\nelse\n{\n  $query=\"insert into bench1 (id,id2,id3,dummy1) values \";\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->{AutoCommit} = 0;\n  print \"Transactions enabled\\n\" if ($opt_debug);\n}\n\nif (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'})\n{\n  $query_size=$server->{'limits'}->{'query_size'};\n\n  print \"Inserting $opt_loop_count multiple-value rows in order\\n\";\n  $res=$query;\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $tmp= \"($i,$i,$i,'ABCDEFGHIJ'),\";\n    if (length($tmp)+length($res) < $query_size)\n    {\n      $res.= $tmp;\n    }\n    else\n    {\n      $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n      $res=$query . $tmp;\n    }\n  }\n  print \"Inserting $opt_loop_count multiple-value rows in reverse order\\n\";\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $tmp= \"(\" . ($total_rows-1-$i) . \",\" .($total_rows-1-$i) .\n      \",\" .($total_rows-1-$i) . \",'BCDEFGHIJK'),\";\n    if (length($tmp)+length($res) < $query_size)\n    {\n      $res.= $tmp;\n    }\n    else\n    {\n      $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n      $res=$query . $tmp;\n    }\n  }\n  print \"Inserting $opt_loop_count multiple-value rows in random order\\n\";\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $tmp= \"(\" . $random[$i] . \",\" . $random[$i] . \",\" . $random[$i] .\n      \",'CDEFGHIJKL'),\" or die $DBI::errstr;\n    if (length($tmp)+length($res) < $query_size)\n    {\n      $res.= $tmp;\n    }\n    else\n    {\n      $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n      $res=$query . $tmp;\n    }\n  }\n  $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n}\nelse\n{\n  print \"Inserting $opt_loop_count rows in order\\n\";\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $sth = $dbh->do($query . \"($i,$i,$i,'ABCDEFGHIJ')\") or die $DBI::errstr;\n  }\n\n  print \"Inserting $opt_loop_count rows in reverse order\\n\";\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $sth = $dbh->do($query . \"(\" . ($total_rows-1-$i) . \",\" .\n\t\t    ($total_rows-1-$i) . \",\" .\n\t\t    ($total_rows-1-$i) . \",'BCDEFGHIJK')\")\n      or die $DBI::errstr;\n  }\n\n  print \"Inserting $opt_loop_count rows in random order\\n\";\n\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $sth = $dbh->do($query . \"(\". $random[$i] . \",\" . $random[$i] .\n\t\t    \",\" . $random[$i] . \",'CDEFGHIJKL')\") or die $DBI::errstr;\n  }\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\nprint \"Time for insert (\" . ($total_rows) . \"): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_lock_tables)\n{\n  $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n}\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh,\"bench1\");\n}\nif ($opt_lock_tables)\n{\n  $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n}\n\n####\n#### insert $opt_loop_count records with duplicate id\n####\n\nif ($limits->{'unique_index'})\n{\n  print \"Testing insert of duplicates\\n\";\n  $loop_time=new Benchmark;\n\n  if ($opt_fast && $server->{transactions})\n  {\n    $dbh->{AutoCommit} = 0;\n  }\n\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count);\n    $tmp=$tmpvar % ($total_rows);\n    $tmpquery = \"$query ($tmp,$tmp,2,'D')\";\n    if ($dbh->do($tmpquery))\n    {\n      die \"Didn't get an error when inserting duplicate record $tmp\\n\";\n    }\n  }\n  if ($opt_fast && $server->{transactions})\n  {\n    $dbh->commit;\n    $dbh->{AutoCommit} = 1;\n  }\n\n  $end_time=new Benchmark;\n  print \"Time for insert_duplicates (\" . ($opt_loop_count) . \"): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\n####\n#### Do some selects on the table\n####\n\nselect_test:\n\n# ----------------- prepared+executed/prepared*executed tests\n\nprint \"Test of prepared+execute/once prepared many execute selects\\n\";\n$loop_time=new Benchmark;\n\nfor ($i=1 ; $i <= $opt_loop_count ; $i++)\n{\n  my ($key_value)=$random[$i];\n  my ($query)= \"select * from bench1 where id=$key_value\";  \n  print \"$query\\n\" if ($opt_debug);\n  $sth = $dbh->prepare($query);\n  if (! $sth)\n    {\n      die \"error in prepare select with id = $key_value : $DBI::errstr\";\n    };\n  if (! $sth->execute)  \n   {\n      die \"cannot execute prepare select with id = $key_value : $DBI::errstr\";      \n   }\n  while ($sth->fetchrow_arrayref) { };      \n  $sth->finish;\n};\n$end_time=new Benchmark;\nprint \"Time for prepared_select ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n$loop_time=new Benchmark;\n$query= \"select * from bench1 where id=?\";  \n$sth = $dbh->prepare($query);\nif (! $sth)\n{\n  die \"cannot prepare select: $DBI::errstr\";\n};\n\nfor ($i=1 ; $i <= $opt_loop_count ; $i++)\n{\n  my ($key_value)=$random[$i];\n  $sth->bind_param(1,$key_value);\n  print \"$query , id = $key_value\\n\" if ($opt_debug);\n  if (! $sth->execute)  \n   {\n      die \"cannot execute prepare select with id = $key_value : $DBI::errstr\";      \n   }\n  while ($sth->fetchrow_arrayref) { };      \n};\n$sth->finish;\n$end_time=new Benchmark;\nprint \"Time for once_prepared_select ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\nprint \"Retrieving data from the table\\n\";\n$loop_time=new Benchmark;\n$error=0;\n\n# It's really a small table, so we can try a select on everything\n\n$count=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  if (($found_rows=fetch_all_rows($dbh,\"select id from bench1\")) !=\n      $total_rows)\n  {\n    if (!$error++)\n    {\n      print \"Warning: Got $found_rows rows when selecting a whole table of \" . ($total_rows) . \" rows\\nContact the database or DBD author!\\n\";\n    }\n  }\n  $count+=$found_rows;\n}\n\n$end_time=new Benchmark;\nprint \"Time for select_big ($small_loop_count:$count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n#\n# Do a lot of different ORDER BY queries\n#\n\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select id,id2 from bench1 order by id,id2\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big_key ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select id,id2 from bench1 order by id desc, id2 desc\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big_key_desc ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select id from bench1 order by id desc\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big_key_prefix ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select id3 from bench1 order by id3\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big_key2 ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$sel=$limits->{'order_by_unused'} ? \"id2\" : \"*\";\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select $sel from bench1 order by id3\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big_key_diff ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$sel=$limits->{'order_by_unused'} ? \"id\" : \"*\";\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $small_loop_count ; $i++)\n{\n  $rows+=fetch_all_rows($dbh,\"select $sel from bench1 order by id2,id3\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $small_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_big ($small_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n$sel=$limits->{'order_by_unused'} ? \"dummy1\" : \"dummy1,id3\";\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $range_loop_count ; $i++)\n{\n  $start=$opt_loop_count/$range_loop_count*$i;\n  $end=$start+$i;\n  $rows+=fetch_all_rows($dbh,\"select $sel from bench1 where id>=$start and id <= $end order by id3\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $range_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_range ($range_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n$sel=$limits->{'order_by_unused'} ? \"dummy1\" : \"dummy1,id\";\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $range_loop_count ; $i++)\n{\n  $start=$opt_loop_count/$range_loop_count*$i;\n  $end=$start+$i;\n  $rows+=fetch_all_rows($dbh,\"select $sel from bench1 where id>=$start and id <= $end order by id\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $range_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_key_prefix ($range_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n$sel=$limits->{'order_by_unused'} ? \"id2\" : \"id2,id3\";\n$loop_time=new Benchmark;\n$estimated=$rows=0;\nfor ($i=1 ; $i <= $range_loop_count ; $i++)\n{\n  $start=$opt_loop_count/$range_loop_count*$i;\n  $end=$start+$range_loop_count;\n  $rows+=fetch_all_rows($dbh,\"select $sel from bench1 where id3>=$start and id3 <= $end order by id3\",1);\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,$i,\n\t\t\t\t\t $range_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for order_by_key2_diff ($range_loop_count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n#\n# Test of select on 2 different keys with or\n# (In this case database can only use keys if they do an automatic union).\n#\n\n$loop_time=new Benchmark;\n$estimated=0;\n$rows=0;\n$count=0;\nfor ($i=1 ; $i <= $range_loop_count ; $i++)\n{\n  my $rnd=$i;\n  my $rnd2=$random[$i];\n  $rows+=fetch_all_rows($dbh,\"select id2 from bench1 where id=$rnd or id3=$rnd2\",1);\n  $count++;\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$count,\n\t\t\t\t\t $range_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for select_diff_key ($count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n# Test select that is very popular when using ODBC\n\ncheck_or_range(\"id\",\"select_range_prefix\");\ncheck_or_range(\"id3\",\"select_range_key2\");\n\n# Check reading on direct key on id and id3\n\ncheck_select_key(\"*\",\"id\",\"select_key_prefix\");\ncheck_select_key2(\"*\",\"id\",\"id2\",\"select_key\");\ncheck_select_key2(\"id,id2\",\"id\",\"id2\",\"select_key_return_key\");\ncheck_select_key(\"*\",\"id3\",\"select_key2\");\ncheck_select_key(\"id3\",\"id3\",\"select_key2_return_key\");\ncheck_select_key(\"id,id2\",\"id3\",\"select_key2_return_prim\");\n\n####\n#### A lot of simple selects on ranges\n####\n\n@Q=(\"select * from bench1 where !id!=3 or !id!=2 or !id!=1 or !id!=4 or !id!=16 or !id!=10\",\n    6,\n    \"select * from bench1 where !id!>=\" . ($total_rows-1) .\" or !id!<1\",\n    2,\n    \"select * from bench1 where !id!>=1 and !id!<=2\",\n    2,\n    \"select * from bench1 where (!id!>=1 and !id!<=2) or (!id!>=1 and !id!<=2)\",\n    2,\n    \"select * from bench1 where !id!>=1 and !id!<=10 and !id!<=5\",\n    5,\n    \"select * from bench1 where (!id!>0 and !id!<2) or !id!>=\" . ($total_rows-1),\n    2,\n    \"select * from bench1 where (!id!>0 and !id!<2) or (!id!>= \" . ($opt_loop_count/2) . \" and !id! <= \" . ($opt_loop_count/2+2) . \") or !id! = \" . ($opt_loop_count/2-1),\n    5,\n    \"select * from bench1 where (!id!>=5 and !id!<=10) or (!id!>=1 and !id!<=4)\",\n    10,\n    \"select * from bench1 where (!id!=1 or !id!=2) and (!id!=3 or !id!=4)\",\n    0,\n    \"select * from bench1 where (!id!=1 or !id!=2) and (!id!=2 or !id!=3)\",\n    1,\n    \"select * from bench1 where (!id!=1 or !id!=5 or !id!=20 or !id!=40) and (!id!=1 or !id!>=20 or !id!=4)\",\n    3,\n    \"select * from bench1 where ((!id!=1 or !id!=3) or (!id!>1 and !id!<3)) and !id!<=2\",\n    2,\n    \"select * from bench1 where (!id! >= 0 and !id! < 4) or (!id! >=4 and !id! < 6)\",\n    6,\n    \"select * from bench1 where !id! <= -1 or (!id! >= 0 and !id! <= 5) or (!id! >=4 and !id! < 6) or (!id! >=6 and !id! <=7) or (!id!>7 and !id! <= 8)\",\n    9,\n    \"select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>=0 and !id! <=10)\",\n    11,\n    \"select * from bench1 where (!id!>=1 and !id!<=2 or !id!>=4 and !id!<=5) or (!id!>2 and !id! <=10)\",\n    10,\n    \"select * from bench1 where (!id!>1 or !id! <1) and !id!<=2\",\n    2,\n    \"select * from bench1 where !id! <= 2 and (!id!>1 or !id! <=1)\",\n    3,\n    \"select * from bench1 where (!id!>=1 or !id! <1) and !id!<=2\",\n    3,\n    \"select * from bench1 where (!id!>=1 or !id! <=2) and !id!<=2\",\n    3\n    );\n\nprint \"\\nTest of compares with simple ranges\\n\";\ncheck_select_range(\"id\",\"select_range_prefix\");\ncheck_select_range(\"id3\",\"select_range_key2\");\n\n####\n#### Some group queries\n####\n\nif ($limits->{'group_functions'})\n{\n  $loop_time=new Benchmark;\n  $count=1;\n\n  $estimated=0;\n  for ($tests=0 ; $tests < $small_loop_count ; $tests++)\n  {\n    $sth=$dbh->prepare($query=\"select count(*) from bench1\") or die $DBI::errstr;\n    $sth->execute or die $sth->errstr;\n    if (($sth->fetchrow_array)[0] != $total_rows)\n    {\n      print \"Warning: '$query' returned wrong result\\n\";\n    }\n    $sth->finish;\n\n    # min, max in keys are very normal\n    $count+=7;\n    fetch_all_rows($dbh,\"select min(id) from bench1\");\n    fetch_all_rows($dbh,\"select max(id) from bench1\");\n    fetch_all_rows($dbh,\"select sum(id+0.0) from bench1\");\n    fetch_all_rows($dbh,\"select min(id3),max(id3),sum(id3-0.0) from bench1\");\n    if ($limits->{'group_func_sql_min_str'})\n    {\n      fetch_all_rows($dbh,\"select min(dummy1),max(dummy1) from bench1\");\n    }\n    $count++;\n    $sth=$dbh->prepare($query=\"select count(*) from bench1 where id >= \" .\n\t\t       ($opt_loop_count*2)) or die $DBI::errstr;\n    $sth->execute or die $DBI::errstr;\n    if (($sth->fetchrow_array)[0] != $opt_loop_count)\n    {\n      print \"Warning: '$query' returned wrong result\\n\";\n    }\n    $sth->finish;\n\n    $count++;\n    $sth=$dbh->prepare($query=\"select count(*),sum(id+0.0),min(id),max(id),avg(id-0.0) from bench1\") or die $DBI::errstr;\n    $sth->execute or die $DBI::errstr;\n    @row=$sth->fetchrow_array;\n    if ($row[0] != $total_rows ||\n\tint($row[1]+0.5) != int((($total_rows-1)/2*$total_rows)+0.5) ||\n\t$row[2] != 0 ||\n\t$row[3] != $total_rows-1 ||\n\t1-$row[4]/(($total_rows-1)/2) > 0.001)\n    {\n      # PostgreSQL 6.3 fails here\n      print \"Warning: '$query' returned wrong result: @row\\n\";\n    }\n    $sth->finish;\n\n    if ($limits->{'func_odbc_mod'})\n    {\n      $tmp=\"mod(id,10)\";\n      if ($limits->{'func_extra_%'})\n      {\n\t$tmp=\"id % 10\";\t\t# For postgreSQL\n      }\n      $count++;\n      if ($limits->{'group_by_alias'}) {\n\tif (fetch_all_rows($dbh,$query=$server->query(\"select $tmp as last_digit,count(*) from bench1 group by last_digit\")) != 10)\n\t{\n\t  print \"Warning: '$query' returned wrong number of rows\\n\";\n\t}\n      } elsif ($limits->{'group_by_position'}) {\n\tif (fetch_all_rows($dbh,$query=$server->query(\"select $tmp,count(*) from bench1 group by 1\")) != 10)\n\t{\n\t  print \"Warning: '$query' returned wrong number of rows\\n\";\n\t}\n      }\n    }\n\n    if ($limits->{'order_by_position'} && $limits->{'group_by_position'})\n    {\n      $count++;\n      if (fetch_all_rows($dbh, $query=\"select id,id3,dummy1 from bench1 where id < 100+$count-$count group by id,id3,dummy1 order by id desc,id3,dummy1\") != 100)\n      {\n\tprint \"Warning: '$query' returned wrong number of rows\\n\";\n      }\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$tests,\n\t\t\t\t\t   $small_loop_count));\n  }\n  print_time($estimated);\n  print \" for select_group ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=$estimated=0;\n  for ($tests=1 ; $tests <= $range_loop_count*5 ; $tests++)\n  {\n    $count+=6;\n    fetch_all_rows($dbh,\"select min(id) from bench1\");\n    fetch_all_rows($dbh,\"select max(id) from bench1\");\n    fetch_all_rows($dbh,\"select min(id2) from bench1 where id=$tests\");\n    fetch_all_rows($dbh,\"select max(id2) from bench1 where id=$tests\");\n    if ($limits->{'group_func_sql_min_str'})\n    {\n      fetch_all_rows($dbh,\"select min(dummy1) from bench1 where id=$tests\");\n      fetch_all_rows($dbh,\"select max(dummy1) from bench1 where id=$tests\");\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$tests,\n\t\t\t\t\t   $range_loop_count*5));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for min_max_on_key ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=$estimated=0;\n  for ($tests=1 ; $tests <= $small_loop_count ; $tests++)\n  {\n    $count+=6;\n    fetch_all_rows($dbh,\"select min(id2) from bench1\");\n    fetch_all_rows($dbh,\"select max(id2) from bench1\");\n    fetch_all_rows($dbh,\"select min(id3) from bench1 where id2=$tests\");\n    fetch_all_rows($dbh,\"select max(id3) from bench1 where id2=$tests\");\n    if ($limits->{'group_func_sql_min_str'})\n    {\n      fetch_all_rows($dbh,\"select min(dummy1) from bench1 where id2=$tests\");\n      fetch_all_rows($dbh,\"select max(dummy1) from bench1 where id2=$tests\");\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$tests,\n\t\t\t\t\t   $range_loop_count));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for min_max ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=0;\n  $total=$opt_loop_count*3;\n  for ($tests=0 ; $tests < $total ; $tests+=$total/100)\n  {\n    $count+=1;\n    fetch_all_rows($dbh,\"select count(id) from bench1 where id < $tests\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for count_on_key ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($tests=0 ; $tests < $total ; $tests+=$total/100)\n  {\n    $count+=1;\n    fetch_all_rows($dbh,\"select count(dummy1) from bench1 where id2 < $tests\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for count ($count): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  if ($limits->{'group_distinct_functions'})\n  {\n    $loop_time=new Benchmark;\n    $count=$estimated=0;\n    for ($tests=1 ; $tests <= $small_loop_count ; $tests++)\n    {\n      $count+=2;\n      fetch_all_rows($dbh,\"select count(distinct dummy1) from bench1\");\n      fetch_all_rows($dbh,\"select dummy1,count(distinct id) from bench1 group by dummy1\");\n      $end_time=new Benchmark;\n      last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$tests,\n\t\t\t\t\t     $small_loop_count));\n    }\n    if ($estimated)\n    { print \"Estimated time\"; }\n    else\n    { print \"Time\"; }\n    print \" for count_distinct_big ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n  }\n}\n\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\n\n####\n#### Some updates on the table\n####\n\n$loop_time=new Benchmark;\n\nif ($limits->{'functions'})\n{\n  print \"\\nTesting update of keys with functions\\n\";\n  my $update_loop_count=$opt_loop_count/2;\n  for ($i=0 ; $i < $update_loop_count ; $i++)\n  {\n    my $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows\n    $sth = $dbh->do(\"update bench1 set id3=-$tmp where id3=$tmp\") or die $DBI::errstr;\n  }\n\n  $end_time=new Benchmark;\n  print \"Time for update_of_key ($update_loop_count):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  if ($opt_lock_tables)\n  {\n    do_query($dbh,\"UNLOCK TABLES\");\n  }\n  if ($opt_fast && defined($server->{vacuum}))\n  {\n    $server->vacuum(1,\\$dbh,\"bench1\");\n  }\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n\n  $loop_time=new Benchmark;\n  $count=0;\n  $step=int($opt_loop_count/$range_loop_count+1);\n  for ($i= 0 ; $i < $opt_loop_count ; $i+= $step)\n  {\n    $count++;\n    $sth=$dbh->do(\"update bench1 set id3= 0-id3 where id3 >= 0 and id3 <= $i\") or die $DBI::errstr;\n  }\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  $count++;\n  $sth=$dbh->do(\"update bench1 set id3= 0-id3 where id3 >= 0 and id3 < $opt_loop_count\") or die $DBI::errstr;\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  $count++;\n  $sth=$dbh->do(\"update bench1 set id3= 0-id3 where id3 >= $opt_loop_count and id3 < \". ($opt_loop_count*2)) or die $DBI::errstr;\n\n  #\n  # Check that everything was updated\n  # In principle we shouldn't time this in the update loop..\n  #\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  $row_count=0;\n  if (($sth=$dbh->prepare(\"select count(*) from bench1 where id3>=0\"))\n      && $sth->execute)\n  {\n    ($row_count)=$sth->fetchrow;\n  }\n  $result=1 + $opt_loop_count-$update_loop_count;\n  if ($row_count != $result)\n  {\n    print \"Warning: Update check returned $row_count instead of $result\\n\";\n  }\n\n  $sth->finish;\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  #restore id3 to 0 <= id3 < $total_rows/10 or 0<= id3 < $total_rows\n\n  my $func=($limits->{'func_odbc_floor'}) ? \"floor((0-id3)/20)\" : \"0-id3\";\n  $count++;\n  $sth=$dbh->do($query=\"update bench1 set id3=$func where id3<0\") or die $DBI::errstr;\n\n  $end_time=new Benchmark;\n  print \"Time for update_of_key_big ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\nelse\n{\n  print \"\\nTesting update of keys in loops\\n\";\n  #\n  # This is for mSQL that doesn't have functions. Do we really need this ????\n  #\n\n  $sth=$dbh->prepare(\"select id3 from bench1 where id3 >= 0\") or die $DBI::errstr;\n  $sth->execute or die $DBI::errstr;\n  $count=0;\n  while (@tmp = $sth->fetchrow_array)\n  {\n    my $tmp1 = \"-$tmp[0]\";\n    my $sth1 = $dbh->do(\"update bench1 set id3 = $tmp1 where id3 = $tmp[0]\");\n    $count++;\n    $end_time=new Benchmark;\n    if (($end_time->[0] - $loop_time->[0]) > $opt_time_limit)\n    {\n      print \"note: Aborting update loop because of timeout\\n\";\n      last;\n    }\n  }\n  $sth->finish;\n  # Check that everything except id3=0 was updated\n  # In principle we shouldn't time this in the update loop..\n  #\n  if (fetch_all_rows($dbh,$query=\"select * from bench1 where id3>=0\") != 1)\n  {\n    if ($count == $total_rows)\n    {\n      print \"Warning: Wrong information after update: Found '$row_count' rows, but should have been: 1\\n\";\n    }\n  }\n  #restore id3 to 0 <= id3 < $total_rows\n  $sth=$dbh->prepare(\"select id3 from bench1 where id3 < 0\") or die $DBI::errstr;\n  $sth->execute or die $DBI::errstr;\n  while (@tmp = $sth->fetchrow_array)\n  {\n    $count++;\n    my $tmp1 = floor((0-$tmp[0])/10);\n    my $sth1 = $dbh->do(\"update bench1 set id3 = $tmp1 where id3 = $tmp[0]\");\n  }\n  $sth->finish;\n  $end_time=new Benchmark;\n  $estimated=predict_query_time($loop_time,$end_time,\\$count,$count,\n\t\t\t\t$opt_loop_count*6);\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for update_of_key ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  if ($opt_lock_tables)\n  {\n    do_query($dbh,\"UNLOCK TABLES\");\n  }\n  $server->vacuum(1,\\$dbh,\"bench1\");\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\n#\n# Testing some simple updates\n#\n\nprint \"Testing update with key\\n\";\n$loop_time=new Benchmark;\nfor ($i=0 ; $i < $opt_loop_count*3 ; $i++)\n{\n  $sth = $dbh->do(\"update bench1 set dummy1='updated' where id=$i and id2=$i\") or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for update_with_key (\" . ($opt_loop_count*3) . \"):  \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n$loop_time=new Benchmark;\n$count=0;\nfor ($i=1 ; $i < $opt_loop_count*3 ; $i+=3)\n{\n  $sth = $dbh->do(\"update bench1 set dummy1='updated' where id=$i\") or die $DBI::errstr;\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$i,($i-1)/3,\n\t\t\t\t\t $opt_loop_count));\n}\nif ($estimated)\n{ print \"Estimated time\"; }\nelse\n{ print \"Time\"; }\nprint \" for update_with_key_prefix (\" . ($opt_loop_count) . \"):  \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\nprint \"\\nTesting update of all rows\\n\";\n$loop_time=new Benchmark;\nfor ($i=0 ; $i < $small_loop_count ; $i++)\n{\n  $sth = $dbh->do(\"update bench1 set dummy1='updated $i'\") or die $DBI::errstr;\n}\n$end_time=new Benchmark;\nprint \"Time for update_big ($small_loop_count):  \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n\n#\n# Testing left outer join\n#\n\nif ($limits->{'func_odbc_floor'} && $limits->{'left_outer_join'})\n{\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 a READ, bench1 b READ\") || die $DBI::errstr;\n  }\n  print \"\\nTesting left outer join\\n\";\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($i=0 ; $i < $small_loop_count ; $i++)\n  {\n    $count+=fetch_all_rows($dbh,\"select count(*) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for outer_join_on_key ($small_loop_count:$count):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($i=0 ; $i < $small_loop_count ; $i++)\n  {\n    $count+=fetch_all_rows($dbh,\"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3)\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for outer_join ($small_loop_count:$count):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $count=0;\n  $loop_time=new Benchmark;\n  for ($i=0 ; $i < $small_loop_count ; $i++)\n  {\n    $count+=fetch_all_rows($dbh,\"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is not null\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for outer_join_found ($small_loop_count:$count):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $count=$estimated=0;\n  $loop_time=new Benchmark;\n  for ($i=1 ; $i <= $small_loop_count ; $i++)\n  {\n    $count+=fetch_all_rows($dbh,\"select count(a.dummy1),count(b.dummy1) from bench1 as a left outer join bench1 as b on (a.id2=b.id3) where b.id3 is null\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\n\t\t\t\t\t   \\$count,$i,\n\t\t\t\t\t   $range_loop_count));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for outer_join_not_found ($range_loop_count:$count):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\n\n###\n### Test speed of IN( value list)\n###\n\nif ($limits->{'left_outer_join'})\n{\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n  }\n  print \"\\n\";\n  do_many($dbh,$server->create(\"bench2\",\n\t\t\t       [\"id int NOT NULL\"],\n\t\t\t       [\"primary key (id)\"]));\n\n  $max_tests=min(($limits->{'query_size'}-50)/6, $opt_loop_count);\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 READ, bench2 WRITE\") ||\n      die $DBI::errstr;\n  }\n  test_where_in(\"bench1\",\"bench2\",\"id\",1,10);\n  test_where_in(\"bench1\",\"bench2\",\"id\",11,min(100,$max_tests));\n  test_where_in(\"bench1\",\"bench2\",\"id\",101,min(1000,$max_tests));\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n  }\n  $sth = $dbh->do(\"DROP TABLE bench2\" . $server->{'drop_attr'}) ||\n    die $DBI::errstr;\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\n####\n#### Test INSERT INTO ... SELECT\n####\n\nif ($limits->{'insert_select'})\n{\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n  }\n  print \"\\nTesting INSERT INTO ... SELECT\\n\";\n  do_many($dbh,$server->create(\"bench2\",\n\t\t\t       [\"id int NOT NULL\",\n\t\t\t\t\"id2 int NOT NULL\",\n\t\t\t\t\"id3 int NOT NULL\",\n\t\t\t\t\"dummy1 char(30)\"],\n\t\t\t       [\"primary key (id,id2)\"]));\n  do_many($dbh,$server->create(\"bench3\",\n\t\t\t       [\"id int NOT NULL\",\n\t\t\t\t\"id2 int NOT NULL\",\n\t\t\t\t\"id3 int NOT NULL\",\n\t\t\t\t\"dummy1 char(30)\"],\n\t\t\t       [\"primary key (id,id2)\",\n\t\t\t\t\"index index_id3 (id3)\"]));\n  $loop_time=new Benchmark;\n  $sth = $dbh->do(\"INSERT INTO bench2 SELECT * from bench1\") ||\n    die $DBI::errstr;\n  $end_time=new Benchmark;\n  print \"Time for insert_select_1_key (1):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n  $loop_time=new Benchmark;\n  $sth = $dbh->do(\"INSERT INTO bench3 SELECT * from bench1\") ||\n    die $DBI::errstr;\n  $end_time=new Benchmark;\n  print \"Time for insert_select_2_keys (1):  \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n  $loop_time=new Benchmark;\n  $sth = $dbh->do(\"DROP TABLE bench2\" . $server->{'drop_attr'}) ||\n    die $DBI::errstr;\n  $sth = $dbh->do(\"DROP TABLE bench3\" . $server->{'drop_attr'}) ||\n    die $DBI::errstr;\n  $end_time=new Benchmark;\n  print \"Time for drop table(2): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  if ($opt_fast && defined($server->{vacuum}))\n  {\n    $server->vacuum(1,\\$dbh);\n  }\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\n####\n#### Do some deletes on the table\n####\n\nif (!$opt_skip_delete)\n{\n  print \"\\nTesting delete\\n\";\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($i=0 ; $i < $opt_loop_count ; $i+=10)\n  {\n    $count++;\n    $tmp=$opt_loop_count+$random[$i]; # $opt_loop_count*2 <= $tmp < $total_rows\n    $dbh->do(\"delete from bench1 where id3=$tmp\") or die $DBI::errstr;\n  }\n\n  $end_time=new Benchmark;\n  print \"Time for delete_key ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n\n  $count=0;\n  $loop_time=new Benchmark;\n  for ($i= 0 ; $i < $opt_loop_count ; $i+=$opt_loop_count/10)\n  {\n    $sth=$dbh->do(\"delete from bench1 where id3 >= 0 and id3 <= $i\") or die $DBI::errstr;\n    $count++;\n  }\n  $count+=2;\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  $sth=$dbh->do(\"delete from bench1 where id3 >= 0 and id3 <= $opt_loop_count\") or die $DBI::errstr;\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n\n  $sth=$dbh->do(\"delete from bench1 where id >= $opt_loop_count and id <= \" . ($opt_loop_count*2) ) or die $DBI::errstr;\n\n  if ($server->small_rollback_segment())\n  {\n    $dbh->disconnect;\t\t\t\t# close connection\n    $dbh = $server->connect();\n  }\n  if ($opt_fast)\n  {\n    $sth=$dbh->do(\"delete from bench1\") or die $DBI::errstr;\n  }\n  else\n  {\n    $sth = $dbh->do(\"delete from bench1 where id3 < \" . ($total_rows)) or die $DBI::errstr;\n  }\n\n  $end_time=new Benchmark;\n  print \"Time for delete_range ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n  }\n  $sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'}) or die $DBI::errstr;\n}\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n\nkeys_test:\n#\n# Test of insert in table with many keys\n# This test assumes that the server really create the keys!\n#\n\nmy @fields=(); my @keys=();\n$keys=min($limits->{'max_index'},16);\t\t  # 16 is more than enough\n$seg= min($limits->{'max_index_parts'},$keys,16); # 16 is more than enough\n\nprint \"Insert into table with $keys keys and with a primary key with $seg parts\\n\";\n\n# Make keys on the most important types\n@types=(0,0,0,1,0,0,0,1,1,1,1,1,1,1,1,1,1);\t# A 1 for each char field\npush(@fields,\"field1 tinyint not null\");\npush(@fields,\"field_search tinyint not null\");\npush(@fields,\"field2 mediumint not null\");\npush(@fields,\"field3 smallint not null\");\npush(@fields,\"field4 char(16) not null\");\npush(@fields,\"field5 integer not null\");\npush(@fields,\"field6 float not null\");\npush(@fields,\"field7 double not null\");\nfor ($i=8 ; $i <= $keys ; $i++)\n{\n  push(@fields,\"field$i char(6) not null\");\t# Should be relatively fair\n}\n\n# First key contains many segments\n$query=\"primary key (\";\nfor ($i= 1 ; $i <= $seg ; $i++)\n{\n  $query.= \"field$i,\";\n}\nsubstr($query,-1)=\")\";\npush (@keys,$query);\npush (@keys,\"index index2 (field_search)\");\n\n#Create other keys\nfor ($i=3 ; $i <= $keys ; $i++)\n{\n  push(@keys,\"index index$i (field$i)\");\n}\n\ndo_many($dbh,$server->create(\"bench1\",\\@fields,\\@keys));\nif ($opt_lock_tables)\n{\n  $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n}\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\n\n$loop_time=new Benchmark;\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->{AutoCommit} = 0;\n}\n\n$fields=$#fields;\nif (($opt_fast || $opt_fast_insert) && $server->{'limits'}->{'insert_multi_value'})\n{\n  $query_size=$server->{'limits'}->{'query_size'};\n  $query=\"insert into bench1 values \";\n  $res=$query;\n  for ($i=0; $i < $many_keys_loop_count; $i++)\n  {\n    $id= $i & 127;\n    $rand=$random[$i];\n    $tmp=\"($id,$id,$rand,\" . ($i & 32766) . \",'ABCDEF$rand',0,$rand,$rand.0,\";\n\n    for ($j=8; $j <= $fields ; $j++)\n    {\n      $tmp.= ($types[$j] == 0) ? \"$rand,\" : \"'$rand',\";\n    }\n    substr($tmp,-1)=\")\";\n    if (length($tmp)+length($res) < $query_size)\n    {\n      $res.= $tmp . \",\";\n    }\n    else\n    {\n      $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n      $res=$query . $tmp . \",\";\n    }\n  }\n  $sth = $dbh->do(substr($res,0,length($res)-1)) or die $DBI::errstr;\n}\nelse\n{\n  for ($i=0; $i < $many_keys_loop_count; $i++)\n  {\n    $id= $i & 127;\n    $rand=$random[$i];\n    $query=\"insert into bench1 values ($id,$id,$rand,\" . ($i & 32767) .\n      \",'ABCDEF$rand',0,$rand,$rand.0,\";\n\n    for ($j=8; $j <= $fields ; $j++)\n    {\n      $query.= ($types[$j] == 0) ? \"$rand,\" : \"'$rand',\";\n    }\n    substr($query,-1)=\")\";\n    print \"query1: $query\\n\" if ($opt_debug);\n    $dbh->do($query) or die \"Got error $DBI::errstr with query: $query\\n\";\n  }\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\nprint \"Time for insert_key ($many_keys_loop_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\nif ($opt_fast && defined($server->{vacuum}))\n{\n  if ($opt_lock_tables)\n  {\n    do_query($dbh,\"UNLOCK TABLES\");\n  }\n  $server->vacuum(1,\\$dbh,\"bench1\");\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\n#\n# update one key of the above\n#\n\nprint \"Testing update of keys\\n\";\n$loop_time=new Benchmark;\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->{AutoCommit} = 0;\n}\n\nfor ($i=0 ; $i< 256; $i++)\n{\n  $dbh->do(\"update bench1 set field5=1 where field_search=$i\")\n    or die \"Got error $DBI::errstr with query: update bench1 set field5=1 where field_search=$i\\n\";\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\nprint \"Time for update_of_primary_key_many_keys (256): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\nif ($opt_fast && defined($server->{vacuum}))\n{\n  if ($opt_lock_tables)\n  {\n    do_query($dbh,\"UNLOCK TABLES\");\n  }\n  $server->vacuum(1,\\$dbh,\"bench1\");\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 WRITE\") || die $DBI::errstr;\n  }\n}\n\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh = $server->connect();\n}\n\n#\n# Delete everything from table\n#\n\nprint \"Deleting rows from the table\\n\";\n$loop_time=new Benchmark;\n$count=0;\n\nfor ($i=0 ; $i < 128 ; $i++)\n{\n  $count++;\n  $dbh->do(\"delete from bench1 where field_search = $i\") or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for delete_big_many_keys ($count): \" .\ntimestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_lock_tables)\n{\n  $sth = $dbh->do(\"UNLOCK TABLES\") || die $DBI::errstr;\n}\n\nprint \"Deleting everything from table\\n\";\n$count=1;\nif ($opt_fast)\n{\n  $query= ($limits->{'truncate_table'} ? \"truncate table bench1\" :\n\t     \"delete from bench1\");\n  $dbh->do($query) or die $DBI::errstr;\n}\nelse\n{\n  $dbh->do(\"delete from bench1 where field1 > 0\") or die $DBI::errstr;\n}\n\n$end_time=new Benchmark;\nprint \"Time for delete_all_many_keys ($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'}) or die $DBI::errstr;\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n#\n# Test multi value inserts if the server supports it\n#\n\nif ($limits->{'insert_multi_value'})\n{\n  $query_size=$limits->{'query_size'}; # Same limit for all databases\n\n  $sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\n  do_many($dbh,$server->create(\"bench1\",\n\t\t\t       [\"id int NOT NULL\",\n\t\t\t\t\"id2 int NOT NULL\",\n\t\t\t\t\"id3 int NOT NULL\",\n\t\t\t\t\"dummy1 char(30)\"],\n\t\t\t       [\"primary key (id,id2)\",\n\t\t\t       \"index index_id3 (id3)\"]));\n\n  $loop_time=new Benchmark;\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"LOCK TABLES bench1 write\") || die $DBI::errstr;\n  }\n  if ($opt_fast && $server->{transactions})\n  {\n    $dbh->{AutoCommit} = 0;\n  }\n\n  print \"Inserting $opt_loop_count rows with multiple values\\n\";\n  $query=\"insert into bench1 values \";\n  $res=$query;\n  for ($i=0 ; $i < $opt_loop_count ; $i++)\n  {\n    my $tmp= \"($i,$i,$i,'EFGHIJKLM'),\";\n    if (length($i)+length($res) < $query_size)\n    {\n      $res.= $tmp;\n    }\n    else\n    {\n      do_query($dbh,substr($res,0,length($res)-1));\n      $res=$query .$tmp;\n    }\n  }\n  do_query($dbh,substr($res,0,length($res)-1));\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES \") || die $DBI::errstr;\n  }\n  if ($opt_fast && $server->{transactions})\n  {\n    $dbh->commit;\n    $dbh->{AutoCommit} = 1;\n  }\n\n  $end_time=new Benchmark;\n  print \"Time for multiple_value_insert (\" . ($opt_loop_count) . \"): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n  if ($opt_lock_tables)\n  {\n    $sth = $dbh->do(\"UNLOCK TABLES \") || die $DBI::errstr;\n  }\n\n  # A big table may take a while to drop\n  $loop_time=new Benchmark;\n  $sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'}) or die $DBI::errstr;\n  $end_time=new Benchmark;\n  print \"Time for drop table(1): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n####\n#### End of benchmark\n####\n\n$dbh->disconnect;\t\t\t\t# close connection\n\nend_benchmark($start_time);\n\n###\n### Some help functions\n###\n\n\n# Do some sample selects on direct key\n# First select finds a row, the second one doesn't find.\n\nsub check_select_key\n{\n  my ($sel_columns,$column,$check)= @_;\n  my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated);\n\n  $estimated=0;\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($i=1 ; $i <= $opt_read_key_loop_count; $i++)\n  {\n    $count+=2;\n    $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count);\n    $tmp=$tmpvar % ($total_rows);\n    fetch_all_rows($dbh,\"select $sel_columns from bench1 where $column=$tmp\")\n      or die $DBI::errstr;\n    $tmp+=$total_rows;\n    defined($row_count=fetch_all_rows($dbh,\"select $sel_columns from bench1 where $column=$tmp\")) or die $DBI::errstr;\n    die \"Found $row_count rows on impossible id: $tmp\\n\" if ($row_count);\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i,\n\t\t\t\t\t   $opt_loop_count));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for $check ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n# Same as above, but select on 2 columns\n\nsub check_select_key2\n{\n  my ($sel_columns,$column,$column2,$check)= @_;\n  my ($loop_time,$end_time,$i,$tmp_var,$tmp,$count,$row_count,$estimated);\n\n  $estimated=0;\n  $loop_time=new Benchmark;\n  $count=0;\n  for ($i=1 ; $i <= $opt_read_key_loop_count; $i++)\n  {\n    $count+=2;\n    $tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count);\n    $tmp=$tmpvar % ($total_rows);\n    fetch_all_rows($dbh,\"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp\")\n      or die $DBI::errstr;\n    $tmp+=$total_rows;\n    defined($row_count=fetch_all_rows($dbh,\"select $sel_columns from bench1 where $column=$tmp and $column2=$tmp\")) or die $DBI::errstr;\n    die \"Found $row_count rows on impossible id: $tmp\\n\" if ($row_count);\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i,\n\t\t\t\t\t   $opt_loop_count));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for $check ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n#\n# Search using some very simple queries\n#\n\nsub check_select_range\n{\n  my ($column,$check)= @_;\n  my ($loop_time,$end_time,$i,$tmp_var,$tmp,$query,$rows,$estimated);\n\n  $estimated=0;\n  $loop_time=new Benchmark;\n  $found=$count=0;\n  for ($test=1 ; $test <= $range_loop_count; $test++)\n  {\n    $count+=$#Q+1;\n    for ($i=0 ; $i < $#Q ; $i+=2)\n    {\n      $query=$Q[$i];\n      $rows=$Q[$i+1];\n      $query =~ s/!id!/$column/g;\n      if (($row_count=fetch_all_rows($dbh,$query)) != $rows)\n      {\n\tif ($row_count == undef())\n\t{\n\t  die \"Got error: $DBI::errstr when executing $query\\n\";\n\t}\n\tdie \"'$query' returned wrong number of rows: $row_count instead of $rows\\n\";\n      }\n      $found+=$row_count;\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$test,\n\t\t\t\t\t   $range_loop_count));\n  }\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for $check ($count:$found): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n\n#\n# SELECT * from bench where col=x or col=x or col=x ...\n\n\nsub check_or_range\n{\n  my ($column,$check)= @_;\n  my ($loop_time,$end_time,$i,$tmp_var,$tmp,$columns,$estimated,$found,\n      $or_part,$count,$loop_count);\n\n  $columns=min($limits->{'max_columns'},50,($limits->{'query_size'}-50)/13);\n  $columns=$columns- ($columns % 4); # Make Divisible by 4\n\n  $estimated=0;\n  $loop_time=new Benchmark;\n  $found=0;\n  # The number of tests must be divisible by the following\n  $tmp= $limits->{'func_extra_in_num'} ? 15 : 10; \n  # We need to calculate the exact number of test to make 'Estimated' right\n  $loop_count=$range_loop_count*10+$tmp-1;\n  $loop_count=$loop_count- ($loop_count % $tmp);\n  \n  for ($count=0 ; $count < $loop_count ; )\n  {\n    for ($rowcnt=0; $rowcnt <= $columns; $rowcnt+= $columns/4)\n    {\n      my $query=\"select * from bench1 where \";\n      my $or_part= \"$column = 1\";\n      $count+=2;\n\n      for ($i=1 ; $i < $rowcnt ; $i++)\n      {\n\t$tmpvar^= ((($tmpvar + 63) + $i)*3 % $opt_loop_count);\n\t$tmp=$tmpvar % ($opt_loop_count*4);\n\t$or_part.=\" or $column=$tmp\";\n      }\n      print $query . $or_part . \"\\n\" if ($opt_debug);\n      ($rows=fetch_all_rows($dbh,$query . $or_part)) or die $DBI::errstr;\n      $found+=$rows;\n\n      if ($limits->{'func_extra_in_num'})\n      {\n\tmy $in_part=$or_part;\t# Same query, but use 'func_extra_in_num' instead.\n\t$in_part=~ s/ = / IN \\(/;\n\t$in_part=~ s/ or $column=/,/g;\n\t$in_part.= \")\";\n\tfetch_all_rows($dbh,$query . $in_part) or die $DBI::errstr;\n\t$count++;\n      }\n      # Do it a little harder by setting a extra range\n      defined(($rows=fetch_all_rows($dbh,\"$query($or_part) and $column < 10\"))) or die $DBI::errstr;\n      $found+=$rows;\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$count,\n\t\t\t\t\t   $loop_count));\n  }\n\n  if ($estimated)\n  { print \"Estimated time\"; }\n  else\n  { print \"Time\"; }\n  print \" for $check ($count:$found): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n#\n# General test of SELECT ... WHERE id in(value-list)\n#\n\nsub test_where_in\n{\n  my ($t1,$t2,$id,$from,$to)= @_;\n\n  return if ($from >= $to);\n\n  $query=\"SELECT $t1.* FROM $t1 WHERE $id IN (\";\n  for ($i=1 ; $i <= $to ; $i++)\n  {\n    $query.=\"$i,\";\n  }\n  $query=substr($query,0,length($query)-1) . \")\";\n\n  # Fill join table to have the same id's as 'query'\n  for ($i= $from ; $i <= $to ; $i++)\n  {\n    $dbh->do(\"insert into $t2 values($i)\") or die $DBI::errstr;\n  }\n  if ($opt_fast && defined($server->{vacuum}))\n  {\n    $server->vacuum(1,\\$dbh,\"bench1\");\n  }\n\n  time_fetch_all_rows(\"Testing SELECT ... WHERE id in ($to values)\",\n\t\t      \"select_in\", $query, $dbh,\n\t\t      $range_loop_count);\n  time_fetch_all_rows(undef, \"select_join_in\",\n\t\t      \"SELECT $t1.* FROM $t2 left outer join $t1 on ($t1.$id=$t2.$id)\",\n\t\t       $dbh, $range_loop_count);\n}\n", "num_lines": 1803}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of selecting on keys that consist of many parts\n#\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Getopt::Long;\nuse Benchmark;\n\n$opt_loop_count=10000;\n$opt_medium_loop_count=1000;\n$opt_small_loop_count=10;\n$opt_regions=6;\n$opt_groups=100;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$columns=min($limits->{'max_columns'},500,($limits->{'query_size'}-50)/24,\n\t     $limits->{'max_conditions'}/2-3);\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=10;\n  $opt_medium_loop_count/=10;\n  $opt_small_loop_count/=10;\n  $opt_groups/=10;\n}\n\nprint \"Testing the speed of selecting on keys that consist of many parts\\n\";\nprint \"The test-table has $opt_loop_count rows and the test is done with $columns ranges.\\n\\n\";\n\n####\n####  Connect and start timeing\n####\n\n$dbh = $server->connect();\n$start_time=new Benchmark;\n\n####\n#### Create needed tables\n####\n\ngoto select_test if ($opt_skip_create);\n\nprint \"Creating table\\n\";\n$dbh->do(\"drop table bench1\" . $server->{'drop_attr'});\n\ndo_many($dbh,$server->create(\"bench1\",\n\t\t\t     [\"region char(1) NOT NULL\",\n\t\t\t      \"idn integer(6) NOT NULL\",\n\t\t\t      \"rev_idn integer(6) NOT NULL\",\n\t\t\t      \"grp integer(6) NOT NULL\"],\n\t\t\t     [\"primary key (region,idn)\",\n\t\t\t      \"unique (region,rev_idn)\",\n\t\t\t      \"unique (region,grp,idn)\"]));\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"LOCK TABLES bench1 WRITE\");\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n####\n#### Insert $opt_loop_count records with\n#### region:\t\"A\" -> \"E\"\n#### idn: \t0 -> count\n#### rev_idn:\tcount -> 0,\n#### grp:\tdistributed values 0 - > count/100\n####\n\nprint \"Inserting $opt_loop_count rows\\n\";\n\n$loop_time=new Benchmark;\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->{AutoCommit} = 0;\n}\n\n$query=\"insert into bench1 values (\";\n$half_done=$opt_loop_count/2;\nfor ($id=0,$rev_id=$opt_loop_count-1 ; $id < $opt_loop_count ; $id++,$rev_id--)\n{\n  $grp=$id*3 % $opt_groups;\n  $region=chr(65+$id%$opt_regions);\n  do_query($dbh,\"$query'$region',$id,$rev_id,$grp)\");\n  if ($id == $half_done)\n  {\t\t\t\t# Test with different insert\n    $query=\"insert into bench1 (region,idn,rev_idn,grp) values (\";\n  }\n}\n\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\nprint \"Time to insert ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"UNLOCK TABLES\");\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh,\"bench1\");\n}\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"LOCK TABLES bench1 WRITE\");\n}\n\n####\n#### Do some selects on the table\n####\n\nselect_test:\n\nif ($limits->{'group_functions'})\n{\n  my ($tmp); $tmp=1000;\n  print \"Test if the database has a query cache\\n\";\n\n  # First ensure that the table is read into memory\n  fetch_all_rows($dbh,\"select sum(idn+$tmp),sum(rev_idn-$tmp) from bench1\");\n\n  $loop_time=new Benchmark;\n  for ($tests=0 ; $tests < $opt_loop_count ; $tests++)\n  {\n    fetch_all_rows($dbh,\"select sum(idn+100),sum(rev_idn-100) from bench1\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for select_cache ($opt_loop_count): \" .\n     timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\n  # If the database has a query cache, the following loop should be much\n  # slower than the previous loop\n\n  $loop_time=new Benchmark;\n  for ($tests=0 ; $tests < $opt_loop_count ; $tests++)\n  {\n    fetch_all_rows($dbh,\"select sum(idn+$tests),sum(rev_idn-$tests) from bench1\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for select_cache2 ($opt_loop_count): \" .\n     timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\nprint \"Testing big selects on the table\\n\";\n$loop_time=new Benchmark;\n$rows=0;\nfor ($i=0 ; $i < $opt_small_loop_count ; $i++)\n{\n  $grp=$i*11 % $opt_groups;\n  $region=chr(65+$i%($opt_regions+1));\t# One larger to test misses\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region='$region'\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region='$region' and idn=$i\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region='$region' and rev_idn=$i\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region='$region' and grp=$grp\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region>='B' and region<='C' and grp=$grp\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where region>='B' and region<='E' and grp=$grp\");\n  $rows+=fetch_all_rows($dbh,\"select idn from bench1 where grp=$grp\"); # This is hard\n}\n$count=$opt_small_loop_count*7;\n\n$end_time=new Benchmark;\nprint \"Time for select_big ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n# Test select with many OR's\n\n$loop_time=new Benchmark;\n$tmpvar=0;\n$count=0;\n$estimated=0;\n$max_and_conditions=$limits->{'max_conditions'}/2;\n$rows=0;\n\nfor ($i=0 ; $i < $opt_small_loop_count ; $i++)\n{\n  $region=chr(65+$i%($opt_regions+1));\t# One larger to test out-of-regions\n  $query=\"select * from bench1 where \";\n  $or_part=\"grp = 1\";\n  $or_part2=\"region='A' and grp=1\";\n\n  for ($j=1 ; $j < $columns; $j++)\n  {\n    $tmpvar^= ((($tmpvar + 63) + $j)*3 % 100000);\n    $tmp=$tmpvar % $opt_groups;\n    $tmp_region=chr(65+$tmpvar%$opt_regions);\n    $or_part.=\" or grp=$tmp\";\n    if ($j < $max_and_conditions)\n    {\n      $or_part2.=\" or region='$tmp_region' and grp=$tmp\";\n    }\n  }\n  $or_part=\"region='$region' and ($or_part)\";\n\n# Same query, but use 'func_extra_in_num' instead.\n  if ($limits->{'func_extra_in_num'})\n  {\n    $in_part=$or_part;\n    $in_part=~ s/ = / IN \\(/;\n    $in_part=~ s/ or grp=/,/g;\n    $in_part.= \")\";\n    defined($found=fetch_all_rows($dbh,$query . $in_part)) || die $DBI::errstr;\n    $rows+=$found;\n    $count++;\n  }\n  for ($j=0; $j < 10 ; $j++)\n  {\n    $rows+=fetch_all_rows($dbh,$query . $or_part);\n    $rows+=fetch_all_rows($dbh,$query . $or_part2);\n# Do it a little harder by setting a extra range\n    $rows+=fetch_all_rows($dbh,\"$query ($or_part) and idn < 50\");\n    $rows+=fetch_all_rows($dbh,\"$query (($or_part) or (region='A' and grp < 10)) and region <='B'\")\n  }\n  $count+=$j*4;\n  $end_time=new Benchmark;\n  last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t $opt_small_loop_count));\n}\n\nprint_time($estimated);\nprint \" for select_range ($count:$rows): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n#\n# Testing MIN() and MAX() on keys\n#\n\nif ($limits->{'group_functions'} && $limits->{'order_by_unused'})\n{\n  $loop_time=new Benchmark;\n  $count=0;\n  $estimated=0;\n  for ($tests=0 ; $tests < $opt_loop_count ; $tests++)\n  {\n    $count+=7;\n    $grp=$tests*3 % $opt_groups;\n    $region=chr(65+$tests % $opt_regions);\n    if ($limits->{'group_func_sql_min_str'})\n    {\n      fetch_all_rows($dbh,\"select min(region) from bench1\");\n      fetch_all_rows($dbh,\"select max(region) from bench1\");\n      fetch_all_rows($dbh,\"select min(region),max(region) from bench1\");\n    }\n    fetch_all_rows($dbh,\"select min(rev_idn) from bench1 where region='$region'\");\n\n    fetch_all_rows($dbh,\"select max(grp) from bench1 where region='$region'\");\n    fetch_all_rows($dbh,\"select max(idn) from bench1 where region='$region' and grp=$grp\");\n    if ($limits->{'group_func_sql_min_str'})\n    {\n      fetch_all_rows($dbh,\"select max(region) from bench1 where region<'$region'\");\n    }\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,\n\t\t\t\t\t   $tests+1, $opt_loop_count));\n  }\n  print_time($estimated);\n  print \" for min_max_on_key ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $count=0;\n  $estimated=0;\n  for ($tests=0 ; $tests < $opt_loop_count ; $tests++)\n  {\n    $count+=5;\n    $grp=$tests*3 % $opt_groups;\n    $region=chr(65+$tests % $opt_regions);\n    fetch_all_rows($dbh,\"select count(*) from bench1 where region='$region'\");\n    fetch_all_rows($dbh,\"select count(*) from bench1 where region='$region' and grp=$grp\");\n    fetch_all_rows($dbh,\"select count(*) from bench1 where region>'$region'\");\n    fetch_all_rows($dbh,\"select count(*) from bench1 where region<='$region'\");\n    fetch_all_rows($dbh,\"select count(*) from bench1 where region='$region' and grp>$grp\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,\n\t\t\t\t\t   $tests+1, $opt_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_on_key ($count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n  \n}\n\nif ($limits->{'group_functions'})\n{\n  $loop_time=new Benchmark;\n  $rows=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $rows+=fetch_all_rows($dbh,\"select grp,count(*) from bench1 group by grp\");\n  }\n  $end_time=new Benchmark;\n  print \"Time for count_group_on_key_parts ($i:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\nif ($limits->{'group_distinct_functions'})\n{\n  print \"Testing count(distinct) on the table\\n\";\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select count(distinct region) from bench1\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_key_prefix ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select count(distinct grp) from bench1\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n#  Workaround mimer's behavior\n  if ($limits->{'multi_distinct'})\n  {\n    $loop_time=new Benchmark;\n    $rows=$estimated=$count=0;\n    for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n    {\n      $count++;\n      $rows+=fetch_all_rows($dbh,\"select count(distinct grp),count(distinct rev_idn) from bench1\");\n      $end_time=new Benchmark;\n      last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n    } \n    print_time($estimated);\n    print \" for count_distinct_2 ($count:$rows): \" .\n      timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n  }\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select region,count(distinct idn) from bench1 group by region\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group_on_key ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select grp,count(distinct idn) from bench1 group by grp\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group_on_key_parts ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  for ($i=0 ; $i < $opt_medium_loop_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select grp,count(distinct rev_idn) from bench1 group by grp\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $opt_medium_loop_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_group ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n  $loop_time=new Benchmark;\n  $rows=$estimated=$count=0;\n  $test_count=$opt_medium_loop_count/10;\n  for ($i=0 ; $i < $test_count ; $i++)\n  {\n    $count++;\n    $rows+=fetch_all_rows($dbh,\"select idn,count(distinct region) from bench1 group by idn\");\n    $end_time=new Benchmark;\n    last if ($estimated=predict_query_time($loop_time,$end_time,\\$count,$i+1,\n\t\t\t\t\t   $test_count));\n  }\n  print_time($estimated);\n  print \" for count_distinct_big ($count:$rows): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n}\n\n####\n#### End of benchmark\n####\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"UNLOCK TABLES\");\n}\nif (!$opt_skip_delete)\n{\n  do_query($dbh,\"drop table bench1\" . $server->{'drop_attr'});\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n$dbh->disconnect;\t\t\t\t# close connection\n\nend_benchmark($start_time);\n", "num_lines": 457}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\tSee the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n# Test of transactions performance.\n#\n\n##################### Standard benchmark inits ##############################\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n#use warnings;\n\n$opt_groups=27;\t\t    # Characters are 'A' -> Z\n\n$opt_loop_count=10000;\t    # Change this to make test harder/easier\n$opt_medium_loop_count=100; # Change this to make test harder/easier\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n# Avoid warnings for variables in bench-init.pl\n# (Only works with perl 5.6)\n#our ($opt_small_test, $opt_small_tables, $opt_debug, $opt_force);\n\nif ($opt_small_test || $opt_small_tables)\n{\n  $opt_loop_count/=100;\n  $opt_medium_loop_count/=10;\n}\n\n\nif (!$server->{transactions} && !$opt_force)\n{\n  print \"Test skipped because the database doesn't support transactions\\n\";\n  exit(0);\n}\n\n####\n####  Connect and start timeing\n####\n\n$start_time=new Benchmark;\n$dbh = $server->connect();\n\n###\n### Create Table\n###\n\nprint \"Creating tables\\n\";\n$dbh->do(\"drop table bench1\");\n$dbh->do(\"drop table bench2\");\n\ndo_many($dbh,$server->create(\"bench1\",\n\t\t\t     [\"idn int NOT NULL\",\n\t\t\t      \"rev_idn int NOT NULL\",\n\t\t\t      \"region char(1) NOT NULL\",\n\t\t\t      \"grp int NOT NULL\",\n\t\t\t      \"updated tinyint NOT NULL\"],\n\t\t\t     [\"primary key (idn)\",\n\t\t\t      \"unique (region,grp)\"]));\ndo_many($dbh,$server->create(\"bench2\",\n\t\t\t     [\"idn int NOT NULL\",\n\t\t\t      \"rev_idn int NOT NULL\",\n\t\t\t      \"region char(1) NOT NULL\",\n\t\t\t      \"grp int NOT NULL\",\n\t\t\t      \"updated tinyint NOT NULL\"],\n\t\t\t     [\"primary key (idn)\",\n\t\t\t      \"unique (region,grp)\"]));\n\n$dbh->{AutoCommit} = 0;\n\n###\n### Test insert perfomance\n###\n\ntest_insert(\"bench1\",\"insert_commit\",0);\ntest_insert(\"bench2\",\"insert_autocommit\",1);\n\nsub test_insert\n{\n  my ($table, $test_name, $auto_commit)= @_;\n  my ($loop_time,$end_time,$id,$rev_id,$grp,$region);\n\n  $dbh->{AutoCommit}= $auto_commit;\n  $loop_time=new Benchmark;\n\n  for ($id=0,$rev_id=$opt_loop_count-1 ; $id < $opt_loop_count ;\n       $id++,$rev_id--)\n  {\n    $grp=$id/$opt_groups;\n    $region=chr(65+$id%$opt_groups);\n    do_query($dbh,\"insert into $table values ($id,$rev_id,'$region',$grp,0)\");\n  }\n\n  $dbh->commit if (!$auto_commit);\n  $end_time=new Benchmark;\n  print \"Time for $test_name  ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n###\n### Test rollback performance\n###\n\nprint \"Test transactions rollback performance\\n\" if($opt_debug);\n\n##\n## Insert rollback test\n##\n\n#\n# Test is done by inserting 100 rows in a table with lots of rows and\n# then doing a rollback on these\n#\n\n{\n  my ($id,$rev_id,$grp,$region,$end,$loop_time,$end_time,$commit_loop,$count);\n\n  $dbh->{AutoCommit} = 0;\n  $loop_time=new Benchmark;\n  $end=$opt_loop_count*2;\n  $count=0;\n\n  for ($commit_loop=1, $id=$opt_loop_count ; $id < $end ;\n       $id++, $commit_loop++)\n  {\n    $rev_id=$end-$id;\n    $grp=$id/$opt_groups;\n    $region=chr(65+$id%$opt_groups);\n    do_query($dbh,\"insert into bench1 values ($id,$rev_id,'$region',$grp,0)\");\n    if ($commit_loop >= $opt_medium_loop_count)\n    {\n      $dbh->rollback;\n      $commit_loop=0;\n      $count++;\n    }\n  }\n  if ($commit_loop > 1)\n  {\n    $dbh->rollback;\n    $count++;\n  }\n  $end_time=new Benchmark;\n  print \"Time for insert_rollback ($count:$opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n##\n## Update rollback test\n##\n\n#\n# Test is done by updating 100 rows in a table with lots of rows and\n# then doing a rollback on these\n#\n\n{\n  my ($id,$loop_time,$end_time,$commit_loop,$count);\n\n  $dbh->{AutoCommit} = 0;\n  $loop_time=new Benchmark;\n  $end=$opt_loop_count*2;\n  $count=0;\n\n  for ($commit_loop=1, $id=0 ; $id < $opt_loop_count ; $id++, $commit_loop++)\n  {\n    do_query($dbh,\"update bench1 set updated=2 where idn=$id\");\n    if ($commit_loop >= $opt_medium_loop_count)\n    {\n      $dbh->rollback;\n      $commit_loop=0;\n      $count++;\n    }\n  }\n  if ($commit_loop > 1)\n  {\n    $dbh->rollback;\n    $count++;\n  }\n  $end_time=new Benchmark;\n  print \"Time for update_rollback ($count:$opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n##\n## Delete rollback test\n##\n\n#\n# Test is done by deleting 100 rows in a table with lots of rows and\n# then doing a rollback on these\n#\n\n{\n  my ($id,$loop_time,$end_time,$commit_loop,$count);\n\n  $dbh->{AutoCommit} = 0;\n  $loop_time=new Benchmark;\n  $end=$opt_loop_count*2;\n  $count=0;\n\n  for ($commit_loop=1, $id=0 ; $id < $opt_loop_count ; $id++, $commit_loop++)\n  {\n    do_query($dbh,\"delete from bench1 where idn=$id\");\n    if ($commit_loop >= $opt_medium_loop_count)\n    {\n      $dbh->rollback;\n      $commit_loop=0;\n      $count++;\n    }\n  }\n  if ($commit_loop > 1)\n  {\n    $dbh->rollback;\n    $count++;\n  }\n  $end_time=new Benchmark;\n  print \"Time for delete_rollback ($count:$opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n\n###\n### Test update perfomance\n###\n\ntest_update(\"bench1\",\"update_commit\",0);\ntest_update(\"bench2\",\"update_autocommit\",1);\n\nsub test_update\n{\n  my ($table, $test_name, $auto_commit)= @_;\n  my ($loop_time,$end_time,$id);\n\n  $dbh->{AutoCommit}= $auto_commit;\n  $loop_time=new Benchmark;\n\n  for ($id=0 ; $id < $opt_loop_count ; $id++)\n  {\n    do_query($dbh,\"update $table set updated=1 where idn=$id\");\n  }\n\n  $dbh->commit if (!$auto_commit);\n  $end_time=new Benchmark;\n  print \"Time for $test_name  ($opt_loop_count): \" .\n    timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n###\n### Test delete perfomance\n###\n\ntest_delete(\"bench1\",\"delete_commit\",0);\ntest_delete(\"bench2\",\"delete_autocommit\",1);\n\nsub test_delete\n{\n  my ($table, $test_name, $auto_commit)= @_;\n  my ($loop_time,$end_time,$id);\n\n  $dbh->{AutoCommit}= $auto_commit;\n  $loop_time=new Benchmark;\n\n  for ($id=0 ; $id < $opt_loop_count ; $id++)\n {\n    do_query($dbh,\"delete from $table where idn=$id\");\n  }\n  $dbh->commit if (!$auto_commit);\n  $end_time=new Benchmark;\n  print \"Time for $test_name  ($opt_loop_count): \" .\n   timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n}\n\n####\n#### End of benchmark\n####\n\n$sth = $dbh->do(\"drop table bench1\" . $server->{'drop_attr'}) or die $DBI::errstr;\n$sth = $dbh->do(\"drop table bench2\" . $server->{'drop_attr'}) or die $DBI::errstr;\n\n$dbh->disconnect;\t\t\t\t# close connection\nend_benchmark($start_time);\n", "num_lines": 300}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/perl\n# Copyright (c) 2000, 2001, 2003, 2006 MySQL AB, 2009 Sun Microsystems, Inc.\n# Use is subject to license terms.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n#\n\nuse Cwd;\nuse DBI;\nuse Benchmark;\n\n$opt_loop_count=10;\n\n$pwd = cwd(); $pwd = \".\" if ($pwd eq '');\nrequire \"$pwd/bench-init.pl\" || die \"Can't read Configuration file: $!\\n\";\n\n$into_table = \"\";\n\nif ($opt_small_test)\n{\n  $opt_loop_count/=5;\n}\n\n####\n####  Connect and start timeing\n####\n\n$dbh = $server->connect();\n$start_time=new Benchmark;\n\n####\n#### Create needed tables\n####\n\ninit_data();\ninit_query();\n\nprint \"Wisconsin benchmark test\\n\\n\";\n\nif ($opt_skip_create)\n{\n  if ($opt_lock_tables)\n  {\n    @tmp=@table_names; push(@tmp,@extra_names);\n    $sth = $dbh->do(\"LOCK TABLES \" . join(\" WRITE,\", @tmp) . \" WRITE\") ||\n      die $DBI::errstr;\n  }\n  goto start_benchmark;\n}\n\n$loop_time= new Benchmark;\nfor($ti = 0; $ti <= $#table_names; $ti++)\n{\n  my $table_name = $table_names[$ti];\n  my $array_ref = $tables[$ti];\n  \n  # This may fail if we have no table so do not check answer\n  $sth = $dbh->do(\"drop table $table_name\" . $server->{'drop_attr'});\n  print \"Creating table $table_name\\n\" if ($opt_verbose);\n  do_many($dbh,@$array_ref);\n}\n$end_time=new Benchmark;\nprint \"Time for create_table ($#tables): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(1,\\$dbh);\n}\n\n\n####\n#### Insert data\n####\n\nprint \"Inserting data\\n\";\n$loop_time= new Benchmark;\n$row_count=0;\nif ($opt_lock_tables)\n{\n  @tmp=@table_names; push(@tmp,@extra_names);\n  $sth = $dbh->do(\"LOCK TABLES \" . join(\" WRITE,\", @tmp) . \" WRITE\") ||\n    die $DBI::errstr;\n}\n\nif ($opt_fast && $server->{'limits'}->{'load_data_infile'})\n{\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    if ($table_name =~ /tenk|Bprime/i) {\n      $filename = \"$pwd/Data/Wisconsin/tenk.data\";\n    } else {\n      $filename = \"$pwd/Data/Wisconsin/$table_name.data\";\n    }\n    $row_count+=$server->insert_file($table_name,$filename,$dbh);\n  }\n}\nelse\n{\n  if ($opt_fast && $server->{transactions})\n  {\n    $dbh->{AutoCommit} = 0;\n  }\n\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    my $array_ref = $tables[$ti];\n    my @table = @$array_ref;\n    my $insert_start = \"insert into $table_name values (\";\n\n    if ($table_name =~ /tenk|Bprime/i) {\n      $filename = \"$pwd/Data/Wisconsin/tenk.data\";\n    } else {\n      $filename = \"$pwd/Data/Wisconsin/$table_name.data\";\n    }\n    open(DATA, \"$filename\") || die \"Can't open text file: $filename\\n\";\n    while(<DATA>)\n    {\n      chomp;\n      $command = $insert_start . $_ . \")\";\n      print \"$command\\n\" if ($opt_debug);\n      $sth = $dbh->do($command) or die $DBI::errstr;\n      $row_count++;\n    }\n  }\n  close(DATA);\n}\n\nif ($opt_lock_tables)\n{\n  do_query($dbh,\"UNLOCK TABLES\");\n}\nif ($opt_fast && $server->{transactions})\n{\n  $dbh->commit;\n  $dbh->{AutoCommit} = 1;\n}\n\n$end_time=new Benchmark;\nprint \"Time to insert ($row_count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\";\n\n## Oracle runs out of rollback segments here if using the default \"small\"\n## configuration so disconnect and reconnect to use a new segment\nif ($server->small_rollback_segment())\n{\n  $dbh->disconnect;\t\t\t\t# close connection\n  $dbh=$server->connect();\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh,@table_names);\n}\n\nif ($opt_lock_tables)\n{\n  @tmp=@table_names; push(@tmp,@extra_names);\n  $sth = $dbh->do(\"LOCK TABLES \" . join(\" WRITE,\", @tmp) . \" WRITE\") ||\n  die $DBI::errstr;\n}\n\n$loop_time= $end_time;\nprint \"Delete from Bprime where unique2 >= 1000\\n\" if ($opt_debug);\n$sth = $dbh->do(\"delete from Bprime where Bprime.unique2 >= 1000\") or\n  die $DBI::errstr;\n$end_time=new Benchmark;\nprint \"Time to delete_big (1): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n####\n#### Running the benchmark\n####\n\nstart_benchmark:\n\nprint \"Running the actual benchmark\\n\";\n\n$loop_time= new Benchmark;\n$count=0;\nfor ($i = 0; $i <= $#query; $i+=2)\n{\n  if ($query[$i+1])\t\t\t\t# If the server can handle it\n  {\n    $loop_count = 1;\n    $loop_count = $opt_loop_count if ($query[$i] =~ /^select/i);\n    $query[$i] =~ s/\\sAS\\s+[^\\s,]+//ig if (!$limits->{'column_alias'});\n    timeit($loop_count, \"fetch_all_rows(\\$dbh,\\\"$query[$i]\\\")\");\n    $count+=$loop_count;\n  }\n}\n\n$end_time=new Benchmark;\nprint \"Time for wisc_benchmark ($count): \" .\n  timestr(timediff($end_time, $loop_time),\"all\") . \"\\n\\n\";\n\nif (!$opt_skip_delete)\n{\n  for ($ti = 0; $ti <= $#table_names; $ti++)\n  {\n    my $table_name = $table_names[$ti];\n    $sth = $dbh->do(\"drop table $table_name\" . $server->{'drop_attr'});\n  }\n}\n\nif ($opt_fast && defined($server->{vacuum}))\n{\n  $server->vacuum(0,\\$dbh);\n}\n\n####\n#### The END\n####\n\n$dbh->disconnect;                               # close connection\nend_benchmark($start_time);\n\n\n################################\n###### subroutine for database structure\n################################\n\nsub init_data\n{\n  @onek=\n    $server->create(\"onek\",\n\t\t    [\"unique1 int(5) NOT NULL\",\n\t\t     \"unique2 int(4) NOT NULL\",\n\t\t     \"two int(4)\",\n\t\t     \"four int(4)\",\n\t\t     \"ten int(4)\",\n\t\t     \"twenty int(4)\",\n\t\t     \"hundred int(4) NOT NULL\",\n\t\t     \"thousand int(4)\",\n\t\t     \"twothousand int(4)\",\n\t\t     \"fivethous int(4)\",\n\t\t     \"tenthous int(4)\",\n\t\t     \"odd int(4)\",\n\t\t     \"even int(4)\",\n\t\t     \"stringu1 char(16)\",\n\t\t     \"stringu2 char(16)\",\n\t\t     \"string4 char(16)\"],\n\t\t    [\"UNIQUE (unique1)\",\n\t\t     \"UNIQUE (unique2)\",\n\t\t     \"INDEX hundred1 (hundred)\"]);\n\n  @tenk1=\n    $server->create(\"tenk1\",\n\t\t    [\"unique1 int(4) NOT NULL\",\n\t\t     \"unique2 int(4) NOT NULL\",\n\t\t     \"two int(4)\",\n\t\t     \"four int(4)\",\n\t\t     \"ten int(4)\",\n\t\t     \"twenty int(4)\",\n\t\t     \"hundred int(4) NOT NULL\",\n\t\t     \"thousand int(4)\",\n\t\t     \"twothousand int(4)\",\n\t\t     \"fivethous int(4)\",\n\t\t     \"tenthous int(4)\",\n\t\t     \"odd int(4)\",\n\t\t     \"even int(4)\",\n\t\t     \"stringu1 char(16)\",\n\t\t     \"stringu2 char(16)\",\n\t\t     \"string4 char(16)\"],\n\t\t    [\"UNIQUE (unique1)\",\n\t\t     \"UNIQUE (unique2)\",\n\t\t     \"INDEX hundred2 (hundred)\"]);\n\n  @tenk2=\n    $server->create(\"tenk2\",\n\t\t    [\"unique1 int(4) NOT NULL\",\n\t\t     \"unique2 int(4) NOT NULL\",\n\t\t     \"two int(4)\",\n\t\t     \"four int(4)\",\n\t\t     \"ten int(4)\",\n\t\t     \"twenty int(4)\",\n\t\t     \"hundred int(4) NOT NULL\",\n\t\t     \"thousand int(4)\",\n\t\t     \"twothousand int(4)\",\n\t\t     \"fivethous int(4)\",\n\t\t     \"tenthous int(4)\",\n\t\t     \"odd int(4)\",\n\t\t     \"even int(4)\",\n\t\t     \"stringu1 char(16)\",\n\t\t     \"stringu2 char(16)\",\n\t\t     \"string4 char(16)\"],\n\t\t    [\"UNIQUE (unique1)\",\n\t\t     \"UNIQUE (unique2)\",\n\t\t     \"INDEX hundred3 (hundred)\"]);\n\n  @Bprime=\n    $server->create(\"Bprime\",\n\t\t    [\"unique1 int(4) NOT NULL\",\n\t\t     \"unique2 int(4) NOT NULL\",\n\t\t     \"two int(4)\",\n\t\t     \"four int(4)\",\n\t\t     \"ten int(4)\",\n\t\t     \"twenty int(4)\",\n\t\t     \"hundred int(4) NOT NULL\",\n\t\t     \"thousand int(4)\",\n\t\t     \"twothousand int(4)\",\n\t\t     \"fivethous int(4)\",\n\t\t     \"tenthous int(4)\",\n\t\t     \"odd int(4)\",\n\t\t     \"even int(4)\",\n\t\t     \"stringu1 char(16)\",\n\t\t     \"stringu2 char(16)\",\n\t\t     \"string4 char(16)\"],\n\t\t    [\"UNIQUE (unique1)\",\n\t\t     \"UNIQUE (unique2)\",\n\t\t     \"INDEX hundred4 (hundred)\"]);\n\n  @tables =\n    (\\@onek, \\@tenk1, \\@tenk2, \\@Bprime);\n\n  @table_names =\n    (\"onek\", \"tenk1\", \"tenk2\", \"Bprime\");\n\n# Alias used in joins\n  @extra_names=\n    (\"tenk1 as t\", \"tenk1 as t1\",\"tenk1 as t2\", \"Bprime as B\",\"onek as o\");\n}\n\n\nsub init_query\n{\n  @query=\n    (\"select * $into_table from tenk1 where (unique2 > 301) and (unique2 < 402)\",1,\n     \"select * $into_table from tenk1 where (unique1 > 647) and (unique1 < 1648)\",1,\n     \"select * from tenk1 where unique2 = 2001\",1,\n     \"select * from tenk1 where (unique2 > 301) and (unique2 < 402)\",1,\n     \"select t1.*, t2.unique1 AS t2unique1, t2.unique2 AS t2unique2, t2.two AS t2two, t2.four AS t2four, t2.ten AS t2ten, t2.twenty AS t2twenty, t2.hundred AS t2hundred, t2.thousand AS t2thousand, t2.twothousand AS t2twothousand, t2.fivethous AS t2fivethous, t2.tenthous AS t2tenthous, t2.odd AS t2odd, t2.even AS t2even, t2.stringu1 AS t2stringu1, t2.stringu2 AS t2stringu2, t2.string4 AS t2string4 $into_table from tenk1 t1, tenk1 t2 where (t1.unique2 = t2.unique2) and (t2.unique2 < 1000)\",$limits->{'table_wildcard'},\n     \"select t.*,B.unique1 AS Bunique1,B.unique2 AS Bunique2,B.two AS Btwo,B.four AS Bfour,B.ten AS Bten,B.twenty AS Btwenty,B.hundred AS Bhundred,B.thousand AS Bthousand,B.twothousand AS Btwothousand,B.fivethous AS Bfivethous,B.tenthous AS Btenthous,B.odd AS Bodd,B.even AS Beven,B.stringu1 AS Bstringu1,B.stringu2 AS Bstringu2,B.string4 AS Bstring4 $into_table from tenk1 t, Bprime B where t.unique2 = B.unique2\",$limits->{'table_wildcard'},\n     \"select t1.*,o.unique1 AS ounique1,o.unique2 AS ounique2,o.two AS otwo,o.four AS ofour,o.ten AS oten,o.twenty AS otwenty,o.hundred AS ohundred,o.thousand AS othousand,o.twothousand AS otwothousand,o.fivethous AS ofivethous,o.tenthous AS otenthous,o.odd AS oodd, o.even AS oeven,o.stringu1 AS ostringu1,o.stringu2 AS ostringu2,o.string4 AS ostring4 $into_table from onek o, tenk1 t1, tenk1 t2 where (o.unique2 = t1.unique2) and (t1.unique2 = t2.unique2) and (t1.unique2 < 1000) and (t2.unique2 < 1000)\",$limits->{'table_wildcard'},\n     \"select two, four, ten, twenty, hundred, string4 $into_table from tenk1\",1,\n     \"select * $into_table from onek\",1,\n     \"select MIN(unique2) as x $into_table from tenk1\",$limits->{'group_functions'},\n     \"insert into tenk1 (unique1, unique2, two, four, ten, twenty, hundred, thousand, twothousand, fivethous, tenthous, odd, even,stringu1,stringu2, string4) values (10001, 74001, 0, 2, 0, 10, 50, 688, 1950, 4950, 9950, 1, 100, 'ron may choi','jae kwang choi', 'u. c. berkeley')\",1,\n     \"insert into tenk1 (unique1, unique2, two, four, ten, twenty, hundred, thousand, twothousand, fivethous, tenthous, odd, even,stringu1,stringu2, string4) values (19991, 60001, 0, 2, 0, 10, 50, 688, 1950, 4950, 9950, 1, 100, 'ron may choi','jae kwang choi', 'u. c. berkeley')\",1,\n     \"delete from tenk1 where tenk1.unique2 = 877\",1,\n     \"delete from tenk1 where tenk1.unique2 = 876\",1,\n     \"update tenk1 set unique2 = 10001 where tenk1.unique2 =1491\",1,\n     \"update tenk1 set unique2 = 10023 where tenk1.unique2 =1480\",1,\n     \"insert into tenk1 (unique1, unique2, two, four, ten, twenty, hundred, thousand, twothousand, fivethous, tenthous, odd, even, stringu1, stringu2, string4) values (20002, 70002, 0, 2, 0, 10, 50, 688, 1950, 4950, 9950, 1, 100, 'ron may choi', 'jae kwang choi', 'u. c. berkeley')\",1,\n     \"insert into tenk1 (unique1, unique2, two, four, ten, twenty, hundred, thousand, twothousand, fivethous, tenthous, odd, even, stringu1, stringu2, string4) values (50002, 40002, 0, 2, 0, 10, 50, 688, 1950, 4950, 9950, 1, 100, 'ron may choi', 'jae kwang choi', 'u. c. berkeley')\",1,\n     \"delete from tenk1 where tenk1.unique2 = 10001\",1,\n     \"delete from tenk1 where tenk1.unique2 = 900\",1,\n     \"update tenk1 set unique2 = 10088 where tenk1.unique2 =187\",1,\n     \"update tenk1 set unique2 = 10003 where tenk1.unique2 =2000\",1,\n     \"update tenk1 set unique2 = 10020 where tenk1.unique2 =1974\",1,\n     \"update tenk1 set unique2 = 16001 where tenk1.unique2 =1140\",1,\n     );\n}\n", "num_lines": 374}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2007, 2016, Oracle and/or its affiliates. All Rights Reserved.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA\n\n\nTMPF=t.$$\n\nmake -f Makefile.query\n\necho '#include \"univ.i\"' > $TMPF\n\n# This is to avoid compiler warning about unused parameters.\n# FIXME: gcc extension \"MY_ATTRIBUTE\" causing compilation errors on windows\n# platform. Quote them out for now.\nsed -e '\ns/^\\(static.*void.*yy_fatal_error.*msg.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(static.*void.*yy_flex_strncpy.*n.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(static.*int.*yy_flex_strlen.*s.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]alloc.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]realloc.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]free.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\n' < fts0blex.cc >> $TMPF\n\nmv $TMPF fts0blex.cc\n\necho '#include \"univ.i\"' > $TMPF\n\nsed -e '\ns/^\\(static.*void.*yy_fatal_error.*msg.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(static.*void.*yy_flex_strncpy.*n.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(static.*int.*yy_flex_strlen.*s.*,\\)\\(.*yyscanner\\)/\\1 \\2 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]alloc.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]realloc.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\ns/^\\(\\(static\\|void\\).*fts0[bt]free.*,\\)\\(.*yyscanner\\)/\\1 \\3 MY_ATTRIBUTE((unused))/;\n' < fts0tlex.cc >> $TMPF\n\nmv $TMPF fts0tlex.cc\n", "num_lines": 50}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 1994, 2011, Oracle and/or its affiliates. All Rights Reserved.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA\n#\n# generate parser files from bison input files.\n\nset -eu\nTMPFILE=pars0grm.tab.c\nOUTFILE=pars0grm.cc\n\nbison -d pars0grm.y\nmv pars0grm.tab.h ../include/pars0grm.h\n\nsed -e '\ns/'\"$TMPFILE\"'/'\"$OUTFILE\"'/;\ns/^\\(\\(YYSTYPE\\|int\\) yy\\(char\\|nerrs\\)\\)/static \\1/;\ns/\\(\\(YYSTYPE\\|int\\) yy\\(lval\\|parse\\)\\)/UNIV_INTERN \\1/;\n' < \"$TMPFILE\" > \"$OUTFILE\"\n\nrm \"$TMPFILE\"\n", "num_lines": 33}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA\n#\n# generate lexer files from flex input files.\n\nset -eu\n\nTMPFILE=_flex_tmp.cc\nOUTFILE=lexyy.cc\n\nflex -o $TMPFILE pars0lex.l\n\n# AIX needs its includes done in a certain order, so include \"univ.i\" first\n# to be sure we get it right.\necho '#include \"univ.i\"' > $OUTFILE\n\n# flex assigns a pointer to an int in one place without a cast, resulting in\n# a warning on Win64.  Add the cast.  Also define some symbols as static.\nsed -e '\ns/'\"$TMPFILE\"'/'\"$OUTFILE\"'/;\ns/\\(int offset = \\)\\((yy_c_buf_p) - (yytext_ptr)\\);/\\1(int)(\\2);/;\ns/\\(void yy\\(restart\\|_\\(delete\\|flush\\)_buffer\\)\\)/static \\1/;\ns/\\(void yy_switch_to_buffer\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(void yy\\(push\\|pop\\)_buffer_state\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(YY_BUFFER_STATE yy_create_buffer\\)/static \\1/;\ns/\\(\\(int\\|void\\) yy[gs]et_\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(void \\*\\?yy\\(\\(re\\)\\?alloc\\|free\\)\\)/static \\1/;\ns/\\(extern \\)\\?\\(int yy\\(leng\\|lineno\\|_flex_debug\\)\\)/static \\2/;\ns/\\(int yylex_destroy\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(extern \\)\\?\\(int yylex \\)/UNIV_INTERN \\2/;\ns/^\\(\\(FILE\\|char\\) *\\* *yyget\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/^\\(extern \\)\\?\\(\\(FILE\\|char\\) *\\* *yy\\)/static \\2/;\n' < $TMPFILE >> $OUTFILE\n\nrm $TMPFILE\n", "num_lines": 49}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2000, 2007 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# Execute some simple basic test on MyISAM libary to check if things\n# works at all.\n\nvalgrind=\"valgrind --alignment=8 --leak-check=yes\"\nsilent=\"-s\"\n\nif test -f mi_test1$MACH ; then suffix=$MACH ; else suffix=\"\"; fi\n./mi_test1$suffix $silent\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -N -S\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -P --checksum\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -P -N -S\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -B -N -R2\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -k 480 --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -N -S -R1\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --key_length=127 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --key_length=128\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B --key_length=64  --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B -k 480 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B -k 480 -N  --unique --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m -P --unique --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m -P --key_length=480 --key_cache\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -m -p\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -w -S --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w --key_length=64 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w -N --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w -S --key_length=480 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -b -N\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -b --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -B --key_length=480\n./myisamchk$suffix -sm test1\n\n./mi_test1$suffix $silent --checksum\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rs test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rs --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqs --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -ros --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqos --correct-checksum test1\n./myisamchk$suffix -se test1\n\n# check of myisampack / myisamchk\n./myisampack$suffix --force -s test1\n# Ignore error for index file\n./myisamchk$suffix -es test1 2>&1 >& /dev/null\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rus test1\n./myisamchk$suffix -es test1\n\n./mi_test1$suffix $silent --checksum -S\n./myisamchk$suffix -se test1\n./myisamchk$suffix -ros test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -se test1\n\n./myisampack$suffix --force -s test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rus test1\n./myisamchk$suffix -es test1\n\n./mi_test1$suffix $silent --checksum --unique\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent --unique -S\n./myisamchk$suffix -se test1\n\n\n./mi_test1$suffix $silent --key_multiple -N -S\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -a -p --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -a -B --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -P -S\n./myisamchk$suffix -sm test1\n\n./mi_test2$suffix $silent -L -K -W -P\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -W -P -A\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -W -P -S -R1 -m500\necho \"mi_test2$suffix $silent -L -K -R1 -m2000 ;  Should give error 135\"\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -R1 -m2000\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -P -S -R3 -m50 -b1000000\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -B\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -D -B -c\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -m10000 -e8192 -K\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -m10000 -e16384 -E16384 -K -L\n./myisamchk$suffix -sm test2\n\n./mi_test2$suffix $silent -L -K -W -P -m50 -l\n./myisamlog$suffix\n./mi_test2$suffix $silent -L -K -W -P -m50 -l -b100\n./myisamlog$suffix\ntime ./mi_test2$suffix $silent\ntime ./mi_test2$suffix $silent -K -B\ntime ./mi_test2$suffix $silent -L -B\ntime ./mi_test2$suffix $silent -L -K -B\ntime ./mi_test2$suffix $silent -L -K -W -B\ntime ./mi_test2$suffix $silent -L -K -W -S -B\ntime ./mi_test2$suffix $silent -D -K -W -S -B\n", "num_lines": 168}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2005, 2006 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\nif [ ! -x ./ft-test-run.sh ] ; then\n  echo \"Usage: ./ft-test-run.sh\"\n  exit 1\nfi\n\nBASE=`pwd`\nDATA=$BASE/var\nROOT=`cd ../..; pwd`\nMYSQLD=$ROOT/sql/mysqld\nMYSQL=$ROOT/client/mysql\nMYSQLADMIN=$ROOT/client/mysqladmin\nSOCK=$DATA/mysql.sock\nPID=$DATA/mysql.pid\nH=../ftdefs.h\nOPTS=\"--no-defaults --socket=$SOCK --character-sets-dir=$ROOT/sql/share/charsets\"\nDELAY=10\n\nstop_myslqd()\n{\n  [ -S $SOCK ] && $MYSQLADMIN $OPTS shutdown\n  [ -f $PID ] && kill `cat $PID` && sleep 15 && [ -f $PID ] && kill -9 `cat $PID`\n}\n\nif [ ! -d t/BEST ] ; then\n  echo \"No ./t/BEST directory! Aborting...\"\n  exit 1\nfi\nrm -f t/BEST/report.txt\nif [ -w $H ] ; then\n  echo \"$H is writeable! Aborting...\"\n  exit 1\nfi\n\nstop_myslqd\nrm -rf var > /dev/null 2>&1\nmkdir var\nmkdir var/test\n\nfor batch in t/* ; do\n  [ ! -d $batch ] && continue\n  [ $batch -ef t/BEST -a $batch != t/BEST ] && continue\n\n  rm -rf var/test/* > /dev/null 2>&1\n  rm -f $H\n  if [ -f $BASE/$batch/ftdefs.h ] ; then\n    cat $BASE/$batch/ftdefs.h > $H\n    chmod a-wx $H\n  else\n    bk get -q $H\n  fi\n  OPTS=\"--defaults-file=$BASE/$batch/my.cnf --socket=$SOCK --character-sets-dir=$ROOT/sql/share/charsets\"\n  stop_myslqd\n  rm -f $MYSQLD\n  echo \"building $batch\"\n  echo \"============== $batch ===============\" >> var/ft_test.log\n  (cd $ROOT; gmake) >> var/ft_test.log 2>&1\n\n  for prog in $MYSQLD $MYSQL $MYSQLADMIN ; do\n    if [ ! -x $prog ] ; then\n      echo \"build failed: no $prog\"\n      exit 1\n    fi\n  done\n\n  echo \"=====================================\" >> var/ft_test.log\n  $MYSQLD $OPTS --basedir=$BASE --pid-file=$PID \\\n                --language=$ROOT/sql/share/english \\\n                --skip-grant-tables --skip-innodb \\\n                --skip-networking --tmpdir=$DATA >> var/ft_test.log 2>&1 &\n\n  sleep $DELAY\n  $MYSQLADMIN $OPTS ping\n  if [ $? != 0 ] ; then\n    echo \"$MYSQLD refused to start\"\n    exit 1\n  fi\n  for test in `cd data; echo *.r|sed \"s/\\.r//g\"` ; do\n    if [ -f $batch/$test.out ] ; then\n      echo \"skipping $batch/$test.out\"\n      continue\n    fi\n    echo \"testing $batch/$test\"\n    FT_MODE=`cat $batch/ft_mode 2>/dev/null`\n    ./Ecreate.pl $test \"$FT_MODE\" | $MYSQL $OPTS --skip-column-names test >var/$test.eval\n    echo \"reporting $batch/$test\"\n    ./Ereport.pl var/$test.eval data/$test.r > $batch/$test.out || exit\n  done\n  stop_myslqd\n  rm -f $H\n  bk get -q $H\n  if [ ! $batch -ef t/BEST ] ; then\n    echo \"comparing $batch\"\n    ./Ecompare.pl t/BEST $batch >> t/BEST/report.txt\n  fi\ndone\n\n", "num_lines": 117}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "echo $NDB_HOST $NDB_EXTHOST\n\nNDB_PORT=$NDB_PORT_BASE\"00\"\nNDB_CONNECTSTRING_BASE=\"host=$NDB_HOST:$NDB_PORT;nodeid=\"\n\n# Edit file system path\n\ncd $NDB_DEMO\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$NDB_DEMO/filesystem,g \\\n    -e s,\"CHOOSE_HOSTNAME\",$NDB_HOST,g\\\n    -e s,\"CHOOSE_EXTHOSTNAME\",$NDB_EXTHOST,g\\\n    -e s,\"CHOOSE_PORT_BASE\",$NDB_PORT_BASE,g\\\n    -e s,\"CHOOSE_REP_ID\",$NDB_REP_ID,g\\\n    -e s,\"CHOOSE_EXTREP_ID\",$NDB_EXTREP_ID,g\\\n    < ../config-templates/config_template-1-REP.ini > config.ini\n\n# Start management server as deamon\n\nNDB_ID=\"1\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n# Start database node \n\nNDB_ID=\"2\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME DB Node $NDB_ID\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\nNDB_ID=\"3\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME API Node $NDB_ID\" -geometry 80x10 &\n\n# Start xterm for rep node\n\nNDB_ID=$NDB_REP_ID\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME REP Node $NDB_ID\" -geometry 80x10 -xrm *.hold:true -e ndb_rep &\n\n# Start management client\n\nxterm -T \"$NDB_DEMO_NAME Mgmt Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient $NDB_HOST $NDB_PORT &\n", "num_lines": 51}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nNDB_DEMO=$MYSQLCLUSTER_TOP/ndb/demos/1-node-PS\n\nNDB_PORT_BASE=\"102\"\nNDB_REP_ID=\"5\"\nNDB_EXTREP_ID=\"4\"\n\nNDB_DEMO_NAME=\"Demo 1-PS MySQL Cluster\"\nNDB_HOST1=$1\nNDB_HOST2=$2\nif [ -z \"$NDB_HOST1\" ]; then\n  NDB_HOST1=localhost\nfi\nif [ -z \"$NDB_HOST2\" ]; then\n  NDB_HOST2=localhost\nfi\nNDB_HOST=$NDB_HOST1\nNDB_EXTHOST=$NDB_HOST2\n\nsource $MYSQLCLUSTER_TOP/ndb/demos/run_demo1-PS-SS_common.sh\n", "num_lines": 31}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nNDB_DEMO=$MYSQLCLUSTER_TOP/ndb/demos/1-node-SS\n\nNDB_PORT_BASE=\"101\"\nNDB_REP_ID=\"4\"\nNDB_EXTREP_ID=\"5\"\n\nNDB_DEMO_NAME=\"Demo 1-SS MySQL Cluster\"\nNDB_HOST1=$1\nNDB_HOST2=$2\nif [ -z \"$NDB_HOST1\" ]; then\n  NDB_HOST1=localhost\nfi\nif [ -z \"$NDB_HOST2\" ]; then\n  NDB_HOST2=localhost\nfi\nNDB_HOST=$NDB_HOST2\nNDB_EXTHOST=$NDB_HOST1\n\nsource $MYSQLCLUSTER_TOP/ndb/demos/run_demo1-PS-SS_common.sh\n", "num_lines": 31}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nndb_demo=$MYSQLCLUSTER_TOP/ndb/demos\n\n# Edit file system path\n\ncd $ndb_demo/1-node/1-mgm-1\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$ndb_demo/1-node/1-db-2/filesystem,g \\\n    < template_config.ini > config.ini\n\n# Start management server as deamon\n\ncd $ndb_demo/1-node/1-mgm-1\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n# Start database node \n\ncd $ndb_demo/1-node/1-db-2\nxterm -T \"Demo 1 NDB Cluster DB Node 2\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\ncd $ndb_demo/1-node/1-api-3\nxterm -T \"Demo 1 NDB Cluster API Node 3\" -geometry 80x10 &\n\n# Start management client\n\ncd $ndb_demo\nxterm -T \"Demo 1 NDB Management Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient localhost 10000 &\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nndb_demo=$MYSQLCLUSTER_TOP/ndb/demos\n\n# Edit file system path\n\ncd $ndb_demo/2-node/2-mgm-1\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$ndb_demo/2-node/2-db-2/filesystem,g \\\n    -e s,\"WRITE_PATH_TO_FILESYSTEM_3_HERE\",$ndb_demo/2-node/2-db-3/filesystem,g \\\n    < template_config.ini > config.ini\n\n# Start management server as deamon\n\ncd $ndb_demo/2-node/2-mgm-1\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n#xterm -T \"Demo 2 NDB Management Server\" -geometry 80x10 -xrm *.hold:true -e mgmtsrvr -c config.ini &\n\n# Start database node \n\ncd $ndb_demo/2-node/2-db-2\nxterm -T \"Demo 2 NDB Cluster DB Node 2\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start database node \n\ncd $ndb_demo/2-node/2-db-3\nxterm -T \"Demo 2 NDB Cluster DB Node 3\"  -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\ncd $ndb_demo/2-node/2-api-4\nxterm -T \"Demo 2 NDB Cluster API Node 4\" -geometry 80x10 &\n\n# Start xterm for application programs\n\ncd $ndb_demo/2-node/2-api-5\nxterm -T \"Demo 2 NDB Cluster API Node 5\" -geometry 80x10 &\n\n# Start management client\n\ncd $ndb_demo\nxterm -T \"Demo 2 NDB Management Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient localhost 10000 &\n", "num_lines": 55}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\necho \"running result processor...\"\njava -classpath build com.mysql.cluster.crund.ResultProcessor $*\necho \"done.\"\n", "num_lines": 21}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nsource ../env.properties\necho MYSQL_HOME=$MYSQL_HOME\n\necho\n\"$MYSQL_BIN/ndb_mgm\" -e show\n\n# retry reloading the schema\n# seems that dropping the tables fails if\n# - the data nodes haven't fully come up yet\n# - ndb and mysqld have gotten out of sync (e.g., may happen when ndb was\n#   (re)started with option \"--initial\", see bug.php?id=42107)\nfor ((i=3; i>=0; i--)) ; do\n\n  user=\"`whoami`\"\n  echo\n  echo \"grant privileges to users...\"\n  # MySQL does not support wildcards in user names, only anonymous users\n  # specified by the empty user name ''; any user who connects from the\n  # local host with the correct password for the anonymous user will be\n  # allowed access then. \n  echo \"GRANT ALL ON *.* TO ''@localhost;\" \\\n       \"GRANT ALL ON *.* TO $user@localhost;\" \\\n       | \"$MYSQL_BIN/mysql\" -v -u root\n  s=$?\n  echo \"mysql exit status: $s\"\n\n  if [[ $s == 0 ]]; then\n    echo \"successfully granted privileges\"\n  else\n    echo\n    echo \"failed granting privileges; retrying up to $i times...\"\n    for ((j=0; j<3; j++)) ; do echo \".\" ; sleep 1; done\n    continue\n  fi\n\n  echo\n  echo \"load crund schema...\"\n  \"$MYSQL_BIN/mysql\" -v < ../src/tables_mysql.sql\n  s=$?\n  echo \"mysql exit status: $s\"\n\n  if [[ $s == 0 ]]; then\n    echo \"successfully loaded crunddb schema\"\n  else\n    echo\n    echo \"failed loading schema; retrying up to $i times...\"\n    for ((j=0; j<3; j++)) ; do echo \".\" ; sleep 1; done\n    continue\n  fi\n\n  echo\n  echo \"load tws schema...\"\n  \"$MYSQL_BIN/mysql\" -v < ../tws/schema.sql\n  s=$?\n  echo \"mysql exit status: $s\"\n\n  if [[ $s == 0 ]]; then\n    echo \"successfully loaded testdb schema\"\n  else\n    echo\n    echo \"failed loading schema; retrying up to $i times...\"\n    for ((j=0; j<3; j++)) ; do echo \".\" ; sleep 1; done\n    continue\n  fi\n\n  break\n\ndone\n\necho\necho \"show tables...\"\n\"$MYSQL_BIN/mysql\" -e \"USE crunddb; SHOW TABLES;\"\n\"$MYSQL_BIN/mysql\" -e \"USE testdb; SHOW TABLES;\"\n\necho\necho done.\n", "num_lines": 94}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n#for f in run.ndbapi.opt run.ndbjtie.opt run.clusterj.opt run.mysql.opt run.openjpa.mysql.opt run.openjpa.clusterj.opt ; do\n#for f in run.ndbapi.opt run.ndbjtie.opt run.clusterj.opt run.mysql.opt ; do\n#for f in run.ndbjtie.opt ; do\n#for f in run.ndbapi.opt ; do\nfor f in run.clusterj.opt ; do\n  echo testing $f\n  ./mycrundjava.sh $f\n  mv -v results/xxx  results/xxx_$f\ndone\n", "num_lines": 27}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\ntouch out.txt\necho \"\" >> out.txt 2>&1\n./restart_cluster.sh >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./load_shema.sh >> out.txt 2>&1\nvmstat 5 > vmstat5.txt 2>&1 &\npid=$!\necho \"\" >> out.txt 2>&1\n( cd .. ; make run.driver ) >> out.txt 2>&1\nmkdir -p results/xxx\nmv -v [a-z]*.txt results/xxx\ncp -v ../*.properties results/xxx\ncp -v ../build.xml results/xxx\ncp -v ../config.ini results/xxx\ncp -v ../my.cnf results/xxx\nsleep 6\nkill -9 $pid\nmv results/xxx results/xxx_cxxdriver\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# usage: <run.ndbapi.opt|...>\n\ntouch out.txt\necho \"\" >> out.txt 2>&1\nhwprefs -v cpu_count >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./restart_cluster.sh >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./load_shema.sh >> out.txt 2>&1\n#ant load.schema.derby >> out.txt 2>&1\niostat 5 > iostat5.txt 2>&1 &\n#vmstat 5 > vmstat5.txt 2>&1 &\npid=$!\necho \"\" >> out.txt 2>&1\n( cd .. ; ant $1 ) >> out.txt 2>&1\nmkdir -p results/xxx\nmv -v [a-z]*.txt results/xxx\nmv -v ../log*.txt results/xxx\ncp -v ../*.properties results/xxx\ncp -v ../build.xml results/xxx\ncp -v ../config.ini results/xxx\ncp -v ../my.cnf results/xxx\nsleep 6\nkill -9 $pid\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# usage: no args/options\n\ntouch out.txt\necho \"\" >> out.txt 2>&1\nhwprefs -v cpu_count >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./restart_cluster.sh >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./load_shema.sh >> out.txt 2>&1\niostat 5 > iostat5.txt 2>&1 &\n#vmstat 5 > vmstat5.txt 2>&1 &\npid=$!\necho \"\" >> out.txt 2>&1\n( cd ../tws/tws_cpp/ ; make run.driver ) >> out.txt 2>&1\nmkdir -p results/xxx\nmv -v [a-z]*.txt results/xxx\nmv -v ../tws/tws_cpp/log*.txt results/xxx\ncp -v ../tws/*.properties results/xxx\ncp -v ../config.ini results/xxx\ncp -v ../my.cnf results/xxx\nmv -v results/xxx  results/xxx_tws_cpp\nsleep 6\nkill -9 $pid\n", "num_lines": 41}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n# usage: no args/options\n\ntouch out.txt\necho \"\" >> out.txt 2>&1\nhwprefs -v cpu_count >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./restart_cluster.sh >> out.txt 2>&1\necho \"\" >> out.txt 2>&1\n./load_shema.sh >> out.txt 2>&1\niostat 5 > iostat5.txt 2>&1 &\n#vmstat 5 > vmstat5.txt 2>&1 &\npid=$!\necho \"\" >> out.txt 2>&1\n( cd ../tws/tws_java/ ; ant run ) >> out.txt 2>&1\nmkdir -p results/xxx\nmv -v [a-z]*.txt results/xxx\nmv -v ../tws/tws_java/log*.txt results/xxx\ncp -v ../tws/tws_java/nbproject/configs/*.properties results/xxx\ncp -v ../tws/tws_java/nbproject/private/*.properties results/xxx\ncp -v ../tws/*.properties results/xxx\ncp -v ../config.ini results/xxx\ncp -v ../my.cnf results/xxx\nmv -v results/xxx  results/xxx_tws_java\nsleep 6\nkill -9 $pid\n", "num_lines": 43}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n./stop_cluster.sh\n\n#for ((i=0; i<2; i++)) ; do echo \".\" ; sleep 1; done\n\n./start_cluster.sh\n", "num_lines": 23}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n./stop_mysqld.sh\n\n#for ((i=0; i<2; i++)) ; do echo \".\" ; sleep 1; done\n\n./start_mysqld.sh\n", "num_lines": 23}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n./stop_ndb.sh\n\n#for ((i=0; i<2; i++)) ; do echo \".\" ; sleep 1; done\n\n./start_ndb.sh\n", "num_lines": 23}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nfor X in `ps -efa | grep -i $1 | awk {'print $2'}`; do\n  kill $X;\ndone\n\nsleep 1\n\nfor X in `ps -efa | grep -i $1 | awk {'print $2'}`; do\n  kill -9 $X;\ndone\n", "num_lines": 27}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n./start_ndb.sh\n\n# need some extra time\n#for ((i=0; i<1; i++)) ; do echo \".\" ; sleep 1; done\n\n./start_mysqld.sh\n", "num_lines": 24}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nsource ../env.properties\necho MYSQL_HOME=$MYSQL_HOME\n\necho\necho start mysqld...\n\nmylogdir=\"ndblog\"\nmkdir -p \"$mylogdir\"\n\nuser=\"`whoami`\"\ncwd=\"`pwd`\"\nmycnf=\"$cwd/../my.cnf\"\nmyerr=\"$cwd/$mylogdir/mysqld.log.err\"\necho defaults-file=$mycnf\n( cd $MYSQL_HOME ; \"$MYSQL_BIN/mysqld_safe\" --defaults-file=\"$mycnf\" --user=\"$user\" --log-error=\"$myerr\" & )\n\n# need some extra time\nfor ((i=0; i<3; i++)) ; do echo \".\" ; sleep 1; done\n\necho\necho show cluster...\n\"$MYSQL_BIN/ndb_mgm\" -e show\n", "num_lines": 40}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nsource ../env.properties\necho MYSQL_HOME=$MYSQL_HOME\n\n#set -x\n\nmylogdir=\"ndblog\"\nmkdir -p \"$mylogdir\"\n\nmyini=\"../../config.ini\"\necho\necho start mgmd...\n( cd \"$mylogdir\" ; \"$MYSQL_LIBEXEC/ndb_mgmd\" --initial -f \"$myini\" )\n\n# need some extra time\nfor ((i=0; i<3; i++)) ; do echo \".\" ; sleep 1; done\n\necho\necho start ndbd...\n( cd \"$mylogdir\" ; \"$MYSQL_LIBEXEC/ndbd\" --initial )\n\n#echo\n#echo start ndbd...\n#( cd \"$mylogdir\" ; \"$MYSQL_LIBEXEC/ndbd\" --initial )\n\n# need some extra time\nfor ((i=0; i<1; i++)) ; do echo \".\" ; sleep 1; done\n\ntimeout=60\necho\necho waiting up to $timeout s for ndbd to start up...\n\"$MYSQL_BIN/ndb_waiter\" -t $timeout\n\necho\necho show cluster...\n\"$MYSQL_BIN/ndb_mgm\" -e show -t 1\n\n#set +x\n", "num_lines": 55}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\n./stop_mysqld.sh\n\n# need some extra time\n#for ((i=0; i<1; i++)) ; do echo \".\" ; sleep 1; done\n\n./stop_ndb.sh\n", "num_lines": 24}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nsource ../env.properties\necho MYSQL_HOME=$MYSQL_HOME\n\necho shut down mysqld...\n\"$MYSQL_BIN/mysqladmin\" shutdown\n\n# need some extra time\nfor ((i=0; i<3; i++)) ; do echo \".\" ; sleep 1; done\n", "num_lines": 26}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\nsource ../env.properties\necho MYSQL_HOME=$MYSQL_HOME\n\necho shut down NDB...\n\"$MYSQL_BIN/ndb_mgm\" -e shutdown -t 1\n\ntimeout=60\necho\necho waiting up to $timeout s for ndb_mgmd to shut down...\n#\"$MYSQL_BIN/ndb_waiter\" -t $timeout -c \"localhost:1186\" --no-contact\n\"$MYSQL_BIN/ndb_waiter\" -t $timeout --no-contact\n\n# need some extra time\nfor ((i=0; i<6; i++)) ; do echo \".\" ; sleep 1; done\n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n: ${load:=1}\n: ${loops:=100}\n: ${queries:=1000}\n: ${host:=loki43}\n: ${port:=4401}\n: ${RQG_HOME:=/net/fimafeng09/export/home/tmp/oleja/mysql/randgen/randgen-2.2.0}\n\n\nwhile getopts \":nm:r:l:h:p:\" opt; do\n  case $opt in\n    n)\n      load=0\n      ;;\n    m)\n      MYSQLINSTALL=${OPTARG}\n      ;;\n    r)\n      RQG_HOME=${OPTARG}\n      ;;\n    l)\n      loops=${OPTARG}\n      ;;\n    h)\n      host=${OPTARG}\n      ;;\n    p)\n      port=${OPTARG}\n      ;;\n    \\?)\n      echo \"Usage: `basename $0` [options]\"  >&2\n      echo \"-n : Do not create database (assumed to exist already).\"  >&2\n      echo \"-m <mysql install dir>\"  >&2\n      echo \"-r <rqg installation dir>\"  >&2\n      echo \"-l <no of loops>\"  >&2\n      echo \"-h <host>\"  >&2\n      echo \"-p <port>\"  >&2\n      exit 1\n      ;;\n    :)\n      echo \"Option -$OPTARG requires an argument.\" >&2\n      exit 1\n      ;;\n  esac\ndone\n\n\npre=\"spj\"\nopre=\"$pre.$$\"\n\n: ${data:= --spec=simple.zz}\n: ${grammar:=spj_test.yy}\n\n##: ${grammar:=$RQG_HOME/conf/optimizer_no_subquery.yy}   ## a pretty sensible grammar:\n##: ${grammar:=$RQG_HOME/conf/optimizer_no_subquery_portable.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_drizzle.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_materialization.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_semijoin.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_semijoin_nested.yy}\n##: ${grammar:=$RQG_HOME/conf/outer_join.yy}\n##: ${grammar:=$RQG_HOME/conf/outer_join_portable.yy}\n\n## Really simple (or: 'stupid') grammars: Have modified these, used to have nondeterministic behaviour\n##: ${grammar:=$RQG_HOME/conf/subquery.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery-5.1.yy}\n\n##: ${grammar:=$RQG_HOME/conf/optimizer_subquery.yy}\n\ngensql=${RQG_HOME}/gensql.pl\ngendata=${RQG_HOME}/gendata.pl\necp=\"set engine_condition_pushdown=on;\"\n\ndsn=dbi:mysql:host=${host}:port=${port}:user=root:database=${pre}_myisam\nmysqltest=\"$MYSQLINSTALL/bin/mysqltest -uroot --host=${host} --port=${port}\"\nmysql=\"$MYSQLINSTALL/bin/mysql --host=${host} --port=${port}\"\n\n# Create database with a case sensitive collation to ensure a deterministic \n# resultset when 'LIMIT' is specified:\ncharset_spec=\"character set latin1 collate latin1_bin\"\n#charset_spec=\"default character set utf8 default collate utf8_bin\"\n\nexport RQG_HOME\nif [ \"$load\" ]\nthen\n\t$mysql -uroot -e \"drop database if exists ${pre}_myisam; drop database if exists ${pre}_ndb\"\n\t$mysql -uroot -e \"create database ${pre}_myisam ${charset_spec}; create database ${pre}_ndb ${charset_spec}\"\n\t${gendata} --dsn=$dsn ${data}\ncat > /tmp/sproc.$$ <<EOF\nDROP PROCEDURE IF EXISTS copydb;\ndelimiter |;\nCREATE PROCEDURE copydb(dstdb varchar(64), srcdb varchar(64),\n                        dstengine varchar(64))\nBEGIN\n\n  declare tabname varchar(255);\n  declare indextype varchar(32);\n  declare _unique varchar(16);\n  declare done integer default 0;\n  declare cnt integer default 0;\n  declare c cursor for \n    SELECT table_name\n    FROM INFORMATION_SCHEMA.TABLES where table_schema = srcdb;\n  declare continue handler for not found set done = 1;\n\n  open c;\n  \n  repeat\n    fetch c into tabname;\n    if not done then\n       set @ddl = CONCAT('CREATE TABLE ', dstdb, '.', tabname, \n                         ' LIKE ', srcdb, '.', tabname);\n       select @ddl;\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n       set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, \n                         ' engine = ', dstengine);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n\n       ## Drop the original index 'col_int_unique' - recreate a richer set of indexes below\n       set @ddl = CONCAT('DROP INDEX col_int_unique ON ', dstdb, '.', tabname);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n\n       set cnt = cnt+1;\n\n       set _unique = '';\n       set indextype = '';\n       ## Create a mix if 'CREATE INDEX' | 'CREATE UNIQUE INDEX [USING HASH] '\n\n       if ((cnt%3) <> 0) then\n         set _unique = ' UNIQUE';\n\n         if ((cnt%2) = 0) then\n           set indextype = ' USING HASH';\n         else\n           set indextype = '';\n         end if;\n       end if;\n\n       ## Add some composite, possibly unique, indexes\n       if tabname > 'T' then\n          set @ddl = CONCAT('DROP INDEX col_varchar_10_unique ON ', dstdb, '.', tabname);\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_char_16,col_char_16_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix2 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_varchar_256,col_varchar_10_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       elseif tabname > 'O' then\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix2 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int_key,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       elseif tabname > 'H' then\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix3 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int,col_int_key,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       else\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n       end if;\n\n       ## Modify primary key & partition for some tables\n       if ((cnt%3) = 0) then\n          set @ddl = CONCAT('UPDATE ', srcdb, '.', tabname, ' SET col_int=0 WHERE col_int IS NULL');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY ', '(col_int,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_int)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%5) = 0) then\n           set @ddl = CONCAT('UPDATE ', srcdb, '.', tabname, ' SET col_int=0 WHERE col_int IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(col_int,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%7) = 0) then\n           set @ddl = CONCAT('DELETE FROM ', srcdb, '.', tabname, ' WHERE col_char_16 IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(col_char_16,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_char_16)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%11) = 0) then\n           set @ddl = CONCAT('DELETE FROM ', srcdb, '.', tabname, ' WHERE col_varchar_10 IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(pk,col_varchar_256)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_varchar_256)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n        end if;\n\n       set @ddl = CONCAT('INSERT INTO ', dstdb, '.', tabname, \n                         ' SELECT * FROM ', srcdb, '.', tabname);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n    end if;\n  until done end repeat;\n  close c;\nEND\n\\G\n\nDROP PROCEDURE IF EXISTS alterengine\\G\nCREATE PROCEDURE alterengine (db varchar(64), newengine varchar(64))\nBEGIN\n\n  declare tabname varchar(255);\n  declare done integer default 0;\n  declare c cursor for \n  SELECT table_name\n  FROM INFORMATION_SCHEMA.TABLES where table_schema = db;\n  declare continue handler for not found set done = 1;\n\n  open c;\n  \n  repeat\n    fetch c into tabname;\n    if not done then\n       set @ddl = CONCAT('ALTER TABLE ', db, '.', tabname, \n                         ' engine = ', newengine);\n       select @ddl;\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n    end if;\n  until done end repeat;\n  close c;\nEND\n\\G\n\n\nCALL copydb('${pre}_ndb', '${pre}_myisam', 'ndb')\\G\n##CALL alterengine('${pre}_ndb', 'ndb')\\G\nDROP PROCEDURE copydb\\G\nDROP PROCEDURE alterengine\\G\nEOF\n\t$mysql -uroot test < /tmp/sproc.$$\n\trm -f /tmp/sproc.$$\nfi\n\ncheck_query(){\n    file=$1\n    no=$2\n    line=`expr $no \\* 3` || true\n    line=`expr $line + 3 + 2 + 1 + 1` || true\n    sql=`head -n $line $file | tail -n 1`\n\n    tmp=${opre}.$no.sql\n    cat > $tmp <<EOF\n--disable_warnings\n--disable_query_log\n--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\n$ecp\n--echo kalle\n--sorted_result\n--error 0,233,1242,4006\n$sql\n--exit\nEOF\n\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest ${pre}_myisam < $tmp >> ${opre}.$no.myisam.$i.txt\n    done\n\n    for t in 1\n    do\n\t$mysqltest ${pre}_ndb < $tmp >> ${opre}.$no.ndb.$i.txt\n    done\n\n    NDB_JOIN_PUSHDOWN=on\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest ${pre}_ndb < $tmp >> ${opre}.$no.ndbpush.$i.txt\n    done\n\n    cnt=`md5sum ${opre}.$no.*.txt | awk '{ print $1;}' | sort | uniq | wc -l`\n    if [ $cnt -ne 1 ]\n    then\n\techo -n \"$no \"\n\techo $sql >> ${opre}.failing.sql\n    fi\n\n    rm $tmp ${opre}.$no.*.txt\n}\n\nlocate_query (){\n    file=$1\n    rows=`cat $file | wc -l`\n    queries=`expr $rows - 4`\n    queries=`expr $queries / 3`\n    q=0\n    echo -n \"checking queries...\"\n    while [ $q -ne $queries ]\n    do\n\tcheck_query $file $q\n\tq=`expr $q + 1`\n    done\n    echo\n}\n\nrun_all() {\n    file=$1\n\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    echo \"- run myisam\"\n    $mysqltest ${pre}_myisam < $file > ${opre}_myisam.out\n    md5_myisam=`md5sum ${opre}_myisam.out | awk '{ print $1;}'`\n\n    echo \"- run ndb without push\"\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    $mysqltest ${pre}_ndb < $file > ${opre}_ndb.out\n    md5_ndb=`md5sum ${opre}_ndb.out | awk '{ print $1;}'`\n\n    echo \"- run ndb with push\"\n    NDB_JOIN_PUSHDOWN=on\n    export NDB_JOIN_PUSHDOWN\n    $mysqltest ${pre}_ndb < $file > ${opre}_ndbpush.out\n    md5_ndbpush=`md5sum ${opre}_ndbpush.out | awk '{ print $1;}'`\n\n    if [ \"$md5_myisam\" != \"$md5_ndb\" ] || [ \"$md5_myisam\" != \"$md5_ndbpush\" ]\n    then\n\techo \"md5 missmatch: $md5_myisam $md5_ndb $md5_ndbpush\"\n\techo \"locating failing query(s)\"\n\tlocate_query $file\n    fi\n\n    rm ${opre}_myisam.out ${opre}_ndb.out ${opre}_ndbpush.out\n}\n\ni=0\nwhile [ $i -ne $loops ]\ndo\n    i=`expr $i + 1`\n\n    echo \"** loop $i\"\n    us=\"$seed\" || true\n    if [ -z \"$us\" ]\n    then\n    \tus=`date '+%N'`\n    fi\n\n    echo \"- generating sql seed: $us\"\n\n    (\n\techo \"--disable_warnings\"\n\techo \"--disable_query_log\"\n\techo \"--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\"\n\techo \"$ecp\"\n\t${gensql} --seed=$us --queries=$queries --dsn=$dsn --grammar=$grammar|\n        awk '{ print \"--sorted_result\"; print \"--error 0,233,1242,4006\"; print; }'\n\techo \"--exit\"\n    ) > ${opre}_test.sql\n\n    run_all ${opre}_test.sql\n    rm ${opre}_test.sql\n    echo\ndone\n", "num_lines": 416}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2008 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\ncores=`find result -name 'core*'`\nif [ \"$cores\" ]\nthen\n    for i in \"$cores\"\n    do\n\tatrt-backtrace.sh $i\n    done\nfi\n\nf=`find result -name 'log.out' | xargs grep \"NDBT_ProgramExit: \" | grep -c \"Failed\"`\no=`find result -name 'log.out' | xargs grep \"NDBT_ProgramExit: \" | grep -c \"OK\"`\n\nif [ $o -gt 0 -a $f -eq 0 ]\nthen\n    exit 0\nfi\n\nexit 1\n\n", "num_lines": 38}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# Does not work on Windows (gcc only)\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    exit\nfi\n\ncore=$1\nout=$2\n\nif [ ! -f \"$core\" ]\nthen\n    exit\nfi\n\nif [ -f `dirname $core`/env.sh ]\nthen\n    . `dirname $core`/env.sh\nfi\n\n#\n# gdb command file\n#\nbt=`dirname $core`/bt.gdb\necho \"thread apply all bt\" > $bt\necho \"quit\" >> $bt\n\n#\n# Fix output\n#\nif [ -z \"$out\" ]\nthen\n    out=`dirname $core`/bt.txt\nfi\noutarg=\">> $out 2>&1\"\nif [ \"$out\" = \"-\" ]\nthen\n    outarg=\"\"\nfi\n\n#\n# get binary\n#\ntmp=`echo ${core}.tmp`\ngdb -c $core -x $bt -q 2>&1 | grep \"Core was generated\" | awk '{ print $5;}' | sed 's!`!!' | sed `echo \"s/'\\.//\"` > $tmp\nexe=`cat $tmp`\nrm -f $tmp\n\nif [ -x $exe ]\nthen\n    echo \"*** $exe - $core\" >> $out\n    gdb -q -batch -x $bt -c $core $exe >> $out 2>&1\nelif [ -x \"`which $exe 2> /dev/null`\" ]\nthen\n    exe=`which $exe`\n    echo \"*** $exe - $core\" >> $out\n    gdb -q -batch -x $bt -c $core $exe >> $out 2>&1\nelse\n    echo \"*** $core : cant find exe: $exe\" >> $out\nfi\nrm -f $bt\n", "num_lines": 78}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nmkdir -p result\ncd result\nrm -rf *\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n  while [ $# -gt 0 ]\n  do\n    SAVE_IFS=$IFS\n    IFS=\":\"\n    declare -a ARR=\"($1)\"\n    IFS=$SAVE_IFS\n    DIR=`dirname \"${ARR[1]}\"`\n    REMOTE_DIR=`cygpath -u $DIR`\n    HOST=\"${ARR[0]}\"\n    rsync -a --exclude='BACKUP' --exclude='ndb_*_fs' \"$HOST:$REMOTE_DIR\" .\n    shift\n  done\nelse\n  while [ $# -gt 0 ]\n  do\n    rsync -a --exclude='BACKUP' --exclude='ndb_*_fs' \"$1\" .\n    shift\n  done\n\n  #\n  # clean tables...not to make results too large\n  #\n  lst=`find . -name '*.frm'`\n  if [ \"$lst\" ]\n  then\n \t  basename=`echo $i | sed 's!\\.frm!!'`\n\t  if [ \"$basename\" ]\n\t  then\n\t    rm -f $basename.*\n\t  fi\n  fi\n\nfi\n", "num_lines": 59}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nMACHINE=$1\nLOCAL_DIR=$2\nREMOTE_DIR=$3\nverbose=\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    verbose=1\nfi\n\nname=\"`uname -n | sed 's!\\..*!!g'`\"\n\n# Local copy\nif [ \"$MACHINE\" = \"$name\" -o \"$MACHINE\" = \"localhost\" ]\nthen\n    if [ \"$REMOTE_DIR\" = \"$LOCAL_DIR\" -o \"$REMOTE_DIR/\" = \"$LOCAL_DIR\" ]\n    then\n\tif [ \"$verbose\" ]\n\tthen\n\t    echo \"$0: Same directory on localhost. Skipping setup...\"\n\tfi\n    else\n\tif [ \"$verbose\" ]\n\tthen\n\t    echo \"$0: Local machine setup from '$REMOTE_DIR' to '$LOCAL_DIR'...\"\n\tfi\n\tcp -r \"$REMOTE_DIR\" \"$LOCAL_DIR\"\n    fi\n    exit 0;\nfi\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    LOCAL_DIR=`cygpath -u $LOCAL_DIR`\n    REMOTE_DIR=`cygpath -u $REMOTE_DIR`\nfi\n\nset -e\nssh $MACHINE rm -rf $REMOTE_DIR\nssh $MACHINE mkdir -p $REMOTE_DIR\nrsync -a --delete --force --ignore-errors $LOCAL_DIR $MACHINE:$REMOTE_DIR\n", "num_lines": 59}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"autotest-boot.sh version 1.01\"\n\nDATE=`date '+%Y-%m-%d'`\nif [ `uname -s` != \"SunOS\" ]\nthen\n  if [ `uname | grep -ic cygwin || true` -ne 0 ]\n  then\n    HOST=`hostname`\n  else\n    HOST=`hostname -s`\n  fi\nelse\n  HOST=`hostname`\nfi\nexport DATE HOST\n\nset -e\n\necho \"`date` starting: $*\"\n\nverbose=0\ndo_clone=yes\nbuild=yes\n\ntag0=\ntag1=\nconf=\nclonename=\nextra_args=\nextra_clone0=\nextra_clone1=\ninstall_dir0=\ninstall_dir1=\nRUN=\n\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n                --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n                --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n                --version) echo $VERSION; exit;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n\t        --tag=*) tag0=`echo $1 | sed s/--tag=//`;;\n\t        --tag0=*) tag0=`echo $1 | sed s/--tag0=//`;;\n\t        --tag1=*) tag1=`echo $1 | sed s/--tag1=//`;;\n\t        --clonename=*) clonename=`echo $1 | sed s/--clonename=//`;;\n\t        --*) echo \"Unknown arg: $1\";;\n                *) RUN=\"$RUN $1\";;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\nif [ -z \"$conf\" ]\nthen\n\tif [ -f \"`pwd`/autotest.conf\" ]\n\tthen\n\t\tconf=\"`pwd`/autotest.conf\"\n\telif [ -f \"$HOME/autotest.conf\" ]\n\tthen\n\t\tconf=\"$HOME/autotest.conf\"\n\tfi\nfi\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: >$conf<\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"src_clone_base install_dir build_dir bzr_src_base\"\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\n#src_clone=${src_clone_base}/${clone}\nsrc_clone0=${bzr_src_base}/${clone0}\nsrc_clone1=${bzr_src_base}/${clone1}\n\nif [ -z \"$clone1\" ]\nthen\n    install_dir0=$install_dir\nelse\n    install_dir0=$install_dir/0\n    install_dir1=$install_dir/1\nfi\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\nif [ `uname -s` != \"SunOS\" ]\nthen\n\ttrap \"rm -f $LOCK\" ERR\nfi\n\n# You can add more to this path#\n################################\n\nif [ -z \"$tag0\" ]\nthen\n    dst_place0=${build_dir}/clone-$clone0-$DATE.$$\nelse\n    dst_place0=${build_dir}/clone-$tag0-$DATE.$$\n    extra_args=\"$extra_args --clone0=$tag0\"\n    extra_clone0=\"-r$tag0\"\nfi\n\nif [ -z \"$tag1\" ]\nthen\n    dst_place1=${build_dir}/clone1-$clone1-$DATE.$$\nelse\n    dst_place1=${build_dir}/clone1-$tag1-$DATE.$$\n    extra_args=\"$extra_args --clone1=$tag1\"\n    extra_clone1=\"-r$tag1\"\nfi\n\nif [ \"$clonename\" ]\nthen\n    extra_args=\"$extra_args --clonename=$clonename\"\nfi\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place0\n\tmkdir -p ${build_dir}\n\t\n\t# Can use local copy if clone_dir is set, to speed up\n\tif [ ! -z \"$clone_dir\" ]\n\tthen\n\t\tif [ -d \"$clone_dir/$clone0\" ]\n\t\tthen\n\t\t\techo \"Copying $clone_dir/$clone0 to $dst_place0\"\n\t\t\tcp -r $clone_dir/$clone0 $dst_place0\n\t\tfi\n\telse\n\t\tbzr export $dst_place0 $extra_clone0 $src_clone0    \n\tfi\n\n\tif [ \"$clone1\" ]\n\tthen\n\t    rm -rf $dst_place1\n\t    bzr export $dst_place1 $extra_clone1 $src_clone1\n\tfi\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\n\nif [ \"$build\" ]\nthen\n    rm -rf $install_dir\n    p=`pwd`\n    if [ -z \"$clone1\" ]\n    then\n        cd $dst_place0\n        if [ `uname | grep -ic cygwin || true` -ne 0 ]\n        then\n            install_dir_dos=`cygpath -w $install_dir`\n            cmd /c cscript win/configure.js WITH_NDBCLUSTER_STORAGE_ENGINE --without-plugins=archive,blackhole,example,federated\n            cmd /c cmake -G \"Visual Studio 9 2008\" -DWITH_ERROR_INSERT=1 -DWITH_NDB_TEST=1 -DCMAKE_INSTALL_PREFIX=$install_dir_dos\n            cmd /c devenv.com MySql.sln /Build RelWithDebInfo\n            cmd /c devenv.com MySql.sln /Project INSTALL /Build\n        else\n\t    BUILD/compile-ndb-autotest --prefix=$install_dir0\n\t    make install\n        fi\n    else\n\tcd $dst_place0\n\tBUILD/compile-ndb-autotest --prefix=$install_dir0\n\tmake install\n\t\n\tcd $dst_place1\n\tBUILD/compile-ndb-autotest --prefix=$install_dir1\n\tmake install\n    fi\n    cd $p\nfi\n\n\n################################\n# Start run script             #\n################################\n\nscript=$install_dir0/mysql-test/ndb/autotest-run.sh\nfor R in $RUN\ndo\n    sh -x $script $save_args --conf=$conf --run-dir=$install_dir --install-dir0=$install_dir0 --install-dir1=$install_dir1 --suite=$R --nolock $extra_args\ndone\n\nif [ \"$build\" ]\nthen\n    rm -rf $dst_place0\n\n    if [ \"$dst_place1\" ]\n    then\n\trm -rf $dst_place1\n    fi\nfi\n\nrm -f $LOCK\n", "num_lines": 295}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"autotest-run.sh version 1.00\"\n\nDATE=`date '+%Y-%m-%d'`\nif [ `uname -s` != \"SunOS\" ]\nthen\n  if [ `uname | grep -ic cygwin || true` -ne 0 ]\n  then\n    HOST=`hostname`\n    # Returns windows CRLF\n    HOST=`echo $HOST | tr -d \"\\015\"`\n    echo \"Host: '$HOST'\"\n  else\n    HOST=`hostname -s`\n  fi\nelse\n  HOST=`hostname`\nfi\nexport DATE HOST\n\nset -e\nulimit -Sc unlimited\n\necho \"`date` starting: $*\"\n\nRSYNC_RSH=ssh\nexport RSYNC_RSH\n\nverbose=0\nreport=yes\nnolock=\nclonename=\nRUN=\"daily-basic\"\nconf=autotest.conf\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --verbose) verbose=`expr $verbose + 1`;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n                --version) echo $VERSION; exit;;\n\t        --suite=*) RUN=`echo $1 | sed s/--suite=//`;;\n\t        --run-dir=*) run_dir=`echo $1 | sed s/--run-dir=//`;;\n\t        --install-dir=*) install_dir0=`echo $1 | sed s/--install-dir=//`;;\n\t        --install-dir0=*) install_dir0=`echo $1 | sed s/--install-dir0=//`;;\n\t        --install-dir1=*) install_dir1=`echo $1 | sed s/--install-dir1=//`;;\n\t        --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n\t        --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n\t        --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n\t        --nolock) nolock=true;;\n\t        --clonename=*) clonename=`echo $1 | sed s/--clonename=//`;;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\n\ninstall_dir_save=$install_dir0\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: $conf\"\n\texit\nfi\ninstall_dir0=$install_dir_save\n\nif [ -z \"$run_dir\" ]\nthen\n    if [ \"$install_dir1\" ]\n    then\n\techo \"--run-dir not specified but install_dir1 specified\"\n\techo \"giving up\"\n\texit\n    fi\n    run_dir=$install_dir0\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"target base_dir install_dir0 hosts\"\nif [ \"$report\" ]\nthen\n\tvars=\"$vars result_host result_path\"\nfi\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -z \"$nolock\" ]\nthen\n    if [ -f $LOCK ]\n    then\n\techo \"Lock file exists: $LOCK\"\n\texit 1\n    fi\n    echo \"$DATE $RUN\" > $LOCK\nfi\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\nif [ `uname -s` != \"SunOS\" ]\nthen\n\ttrap \"rm -f $LOCK\" ERR\nfi\n\n\n###############################################\n# Check that all interesting files are present#\n###############################################\n\ntest_dir=$install_dir0/mysql-test/ndb\natrt=$test_dir/atrt\ntest_file=$test_dir/$RUN-tests.txt\n\nif [ ! -f \"$test_file\" ]\nthen\n    echo \"Cant find testfile: $test_file\"\n    exit 1\nfi\n\nif [ ! -x \"$atrt\" ]\nthen\n    echo \"Cant find atrt binary at $atrt\"\n    exit 1\nfi\n\n############################\n# check ndb_cpcc fail hosts#\n############################\nfailed=`ndb_cpcc $hosts | awk '{ if($1==\"Failed\"){ print;}}'`\nif [ \"$failed\" ]\nthen\n  echo \"Cant contact cpcd on $failed, exiting\"\n  exit 1\nfi\n\n#############################\n# Function for replacing the#\n# choose host with real host#\n# names. Note $$ = PID\t    #\n#############################\nchoose(){\n        SRC=$1\n        TMP1=/tmp/choose.$$\n        TMP2=/tmp/choose.$$.$$\n        shift\n\n        cp $SRC $TMP1\n        i=1\n        while [ $# -gt 0 ]\n        do\n                sed -e s,\"CHOOSE_host$i\",$1,g < $TMP1 > $TMP2\n                mv $TMP2 $TMP1\n                shift\n                i=`expr $i + 1`\n        done\n        cat $TMP1\n        rm -f $TMP1\n}\n\nchoose_conf(){\n    if [ -f $test_dir/conf-$1-$HOST.cnf ]\n\tthen\n\techo \"$test_dir/conf-$1-$HOST.cnf\"\n    elif [ -f $test_dir/conf-$1.cnf ]\n    then\n\techo \"$test_dir/conf-$1.cnf\"\n    elif [ -f $test_dir/conf-$HOST.cnf ]\n    then\n\techo \"$test_dir/conf-$HOST.cnf\"\n    else\n\techo \"Unable to find conf file looked for\" 1>&2\n\techo \"$test_dir/conf-$1-$HOST.cnf and\" 1>&2\n\techo \"$test_dir/conf-$HOST.cnf\" 1>&2\n\techo \"$test_dir/conf-$1.cnf\" 1>&2\n\texit\n    fi\n}\n\n#########################################\n# Count how many computers we have ready#\n#########################################\n\ncount_hosts(){\n    ch=\"CHOOSE_host\"\n    list=`grep $ch $1 | sed 's!,! !g'`\n    cnt=`for i in $list; do echo $i; done | grep $ch | sort | uniq | wc -l`\n    echo $cnt\n}\n\nconf=`choose_conf $RUN`\ncount=`count_hosts $conf`\navail=`echo $hosts | wc -w`\nif  [ $count -gt $avail ]\n    then\n    echo \"Not enough hosts\"\n    echo \"Needs: $count available: $avail ($avail_hosts)\"\n    exit 1\nfi\n\n###\n# Make directories needed\n\np=`pwd`\nrun_dir=$run_dir/run-$RUN-$clone0-$target\nres_dir=$base_dir/result-$RUN-$clone0-$target/$DATE\ntar_dir=$base_dir/saved-results\n\nmkdir -p $run_dir $res_dir $tar_dir\nrm -rf $res_dir/* $run_dir/*\n\n###\n#\n# Do sed substitiutions\n# \ncd $run_dir\nmkdir run\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n  run_dir=`cygpath -m $run_dir`\n  install_dir0=`cygpath -u $install_dir0`\n  if [ \"$install_dir1\" ]\n  then\n    install_dir1=`cygpath -u $install_dir1`\n  fi\n  test_dir=`cygpath -m $test_dir`\nfi\n\nchoose $conf $hosts > d.tmp.$$\nsed -e s,CHOOSE_dir,\"$run_dir/run\",g < d.tmp.$$ > my.cnf\n\nprefix=\"--prefix=$install_dir0\"\nif [ \"$install_dir1\" ]\nthen\n    prefix=\"$prefix --prefix1=$install_dir1\"\nfi\n\n# Setup configuration\n$atrt Cdq $prefix my.cnf\n\n# Start...\nargs=\"\"\nargs=\"--report-file=report.txt\"\nargs=\"$args --log-file=log.txt\"\nargs=\"$args --testcase-file=$test_dir/$RUN-tests.txt\"\nargs=\"$args $prefix\"\n$atrt $args my.cnf\n\n# Make tar-ball\n[ -f log.txt ] && mv log.txt $res_dir\n[ -f report.txt ] && mv report.txt $res_dir\n[ \"`find . -name 'result*'`\" ] && mv result* $res_dir\ncd $res_dir\n\necho \"date=$DATE\" > info.txt\necho \"suite=$RUN\" >> info.txt\necho \"clone=$clone0\" >> info.txt\necho \"arch=$target\" >> info.txt\necho \"host=$HOST\" >> info.txt\nif [ \"$clone1\" ]\nthen\n    echo \"clone1=$clone1\" >> info.txt\nfi\nif [ \"$clonename\" ]\nthen\n    echo \"clonename=$clonename\" >> info.txt\nelse\n    echo \"clonename=$clone0\" >> info.txt\nfi\nfind . | xargs chmod ugo+r\n\n# Try to pack and transfer as much as possible\nset +e\n\ncd ..\np2=`pwd`\ncd ..\ntarfile=res.$RUN.$clone0.$target.$DATE.$HOST.$$.tgz\nif [ `uname -s` != \"SunOS\" ]\nthen\n    tar cfz $tar_dir/$tarfile `basename $p2`/$DATE\nelse\n    tarfile2=res.$RUN.$clone0.$target.$DATE.$HOST.$$.tar\n    tar cf $tar_dir/$tarfile2 `basename $p2`/$DATE\n    gzip -c $tar_dir/$tarfile2 > $tar_dir/$tarfile\n    rm -f $tar_dir/$tarfile2\nfi\n\nif [ \"$report\" ]\nthen\n    scp $tar_dir/$tarfile $result_host:$result_path/${tarfile}.upload\n    ssh $result_host mv $result_path/${tarfile}.upload $result_path/${tarfile}\nfi\n\ncd $p\nrm -rf $res_dir $run_dir\n\nif [ -z \"$nolock\" ]\nthen\n    rm -f $LOCK\nfi\n", "num_lines": 365}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nfiles=\"daily-basic-tests.txt daily-devel-tests.txt upgrade-tests.txt\"\n\ndie(){\n    echo \"error at $1 : $2\"\n    exit 1\n}\n\ncheck_state(){\n    if  [ $1 != $2 ]\n    then\n\tdie $3 $4\n    fi\n}\n\ncheck_file(){\n    file=$1\n    lineno=0\n    testcase=0\n\n    echo -n \"-- checking $file...\"\n    cat $file | awk '{ print \"^\" $0 \"$\";}' > /tmp/ct.$$\n    while read line\n    do\n\tlineno=$(expr $lineno + 1)\n\tif [ $(echo $line | grep -c \"^^#\") -ne 0 ]\n\tthen\n\t    continue\n\tfi\n\t\n\tcase \"$line\" in\n\t    ^max-time:*)\n\t\ttestcase=$(expr $testcase + 1);;\n\t    ^cmd:*)\n\t\tif [ $(echo $line | wc -w) -ne 2 ]\n\t\tthen\n\t\t    die $file $lineno\n\t\tfi\n\t\ttestcase=$(expr $testcase + 2);;\n\t    ^args:*)\n\t\ttestcase=$(expr $testcase + 4);;\n\t    ^type:*)\n\t\t;;\n\t    ^$) \n                if [ $testcase -ne 7 ]\n\t\tthen\n\t\t    die $file $lineno\n\t\telse\n\t\t    testcase=0\n\t\t    cnt=$(expr $cnt + 1)\n\t\tfi;;\n\t    *)\n\t        die $file $lineno\n\tesac\n   done < /tmp/ct.$$\n   rm -f /tmp/ct.$$\n   if [ $testcase -ne 0 ]\n   then\n   \techo \"Missing newline in end-of-file\"\n\tdie $file $lineno\n   fi\n\n   echo \"ok\"\n}\n   \nfor file in $files\ndo\n    check_file $file\ndone\n", "num_lines": 88}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nbaseport=\"\"\nbasedir=\"\"\nproc_no=1\nnode_id=1\n\nd_file=/tmp/d.$$\ndir_file=/tmp/dirs.$$\nconfig_file=/tmp/config.$$\ncluster_file=/tmp/cluster.$$\n\nadd_procs(){\n\ttype=$1; shift\n\twhile [ $# -ne 0 ]\n\tdo\n\t\tadd_proc $type $1\n\t\tshift\n\tdone\n}\n\nadd_proc (){\n\tcase $type in\n\tmgm)\n\t\techo \"$proc_no.ndb_mgmd\" >> $dir_file\n\t\techo \"[ndb_mgmd]\"        >> $config_file\n\t\techo \"Id: $node_id\"      >> $config_file\n\t\techo \"HostName: $2\"      >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tapi)\n\t\techo \"$proc_no.ndb_api\" >> $dir_file\n                echo \"[api]\"            >> $config_file\n                echo \"Id: $node_id\"     >> $config_file\n                echo \"HostName: $2\"     >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tndb)\n\t\techo \"$proc_no.ndbd\" >> $dir_file\n                echo \"[ndbd]\"        >> $config_file\n                echo \"Id: $node_id\"  >> $config_file\n                echo \"HostName: $2\"  >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tmysqld)\n\t\techo \"$proc_no.mysqld\" >> $dir_file\n                echo \"[mysqld]\"      >> $config_file\n                echo \"Id: $node_id\"    >> $config_file\n                echo \"HostName: $2\"    >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tmysql)\n\t\techo \"$proc_no.mysql\" >> $dir_file\n\t\t;;\n\tesac\n\tproc_no=`expr $proc_no + 1`\n}\n\n\ncnf=/dev/null\ncat $1 | while read line\ndo\n\tcase $line in\n\tbaseport:*) baseport=`echo $line | sed 's/baseport[ ]*:[ ]*//g'`;;\n\tbasedir:*) basedir=`echo $line | sed 's/basedir[ ]*:[ ]*//g'`;;\n\tmgm:*) add_procs mgm `echo $line | sed 's/mgm[ ]*:[ ]*//g'`;;\n\tapi:*) add_procs api `echo $line | sed 's/api[ ]*:[ ]*//g'`;;\n\tndb:*) add_procs ndb `echo $line | sed 's/ndb[ ]*:[ ]*//g'`;;\n\tmysqld:*) add_procs mysqld `echo $line | sed 's/mysqld[ ]*:[ ]*//g'`;;\n\tmysql:*) add_procs mysql `echo $line | sed 's/mysql[ ]*:[ ]*//g'`;;\n\t\"-- cluster config\") \n\t\tif [ \"$cnf\" = \"/dev/null\" ]\n\t\t    then\n\t\t    cnf=$cluster_file\n\t\telse\n\t\t    cnf=/dev/null\n\t\tfi\n\t\tline=\"\";;\n\t    *) echo $line >> $cnf; line=\"\";;\n\tesac\n\tif [ \"$line\" ]\n\tthen\n\t    echo $line >> $d_file\n\tfi\ndone\n\ncat $dir_file | xargs mkdir -p\n\nif [ -f $cluster_file ]\n    then\n    cat $cluster_file $config_file >> /tmp/config2.$$\n    mv /tmp/config2.$$ $config_file\nfi\n\nfor i in `find . -type d -name '*.ndb_mgmd'`\n  do\n  cp $config_file $i/config.ini\ndone\n\nmv $d_file d.txt\nrm -f $config_file $dir_file $cluster_file\n", "num_lines": 118}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nsrc_dir=$1\nrun=$2\ndate=$3\nsrc_file=$src_dir/report.txt\n\nif [ ! -f $src_dir/report.txt ]\nthen\n\techo \"$src_dir/report.txt is missing\"\n\texit 1\nfi\n\n###\n#\n# General html functions\ntrim(){\n\techo $*\n}\n\nheader(){\n    cat <<EOF\n<html><head><title>$*</title></head>\n<body>\nEOF\n}\n\nfooter(){\n    cat <<EOF\n</body></html>\nEOF\n}\n\nheading(){\n    h=$1; shift\n    cat <<EOF\n<h$h>$*</h$h>\nEOF\n}\n\ntable(){\n    echo \"<table $*>\"\n}\n\nend_table(){\n    echo \"</table>\"\n}\n\nrow(){\n    echo \"<tr>\"\n}\n\nend_row(){\n    echo \"</tr>\"\n}\n\nc_column(){\n    cat <<EOF\n<td valign=center align=center>$*</td>\nEOF\n}\n\nbold(){\n    cat <<EOF\n<b>$*</b>\nEOF\n}\ncolumn(){\n    cat <<EOF\n<td valign=center align=left>$*</td>\nEOF\n}\n\npara(){\n    cat <<EOF\n<p></p>\nEOF\n}\n\nhr(){\n    cat <<EOF\n<hr>\nEOF\n}\n\n# -- Verify\ntime_spec(){\n    # $1 - secs\n    _ts_tmp=$1\n    \n    _ts_s=`expr $_ts_tmp % 60`\n    _ts_tmp=`expr $_ts_tmp / 60`\n    \n    _ts_m=`expr $_ts_tmp % 60`\n    if [ $_ts_tmp -ge 60 ]\n    then\n\t_ts_tmp=`expr $_ts_tmp / 60`\n    else\n\t_ts_tmp=0\n    fi\n\n    a=3\n    _ts_h=$_ts_tmp\n\n    if [ $_ts_h -gt 0 ]\n    then\n\tret=\"${_ts_h}h\"\n    fi\n\n    [ $_ts_m -gt 0 ] || [ $_ts_h -gt 0 ] && ret=\"$ret${_ts_m}m\"\n\n    ret=\"$ret${_ts_s}s\"\n    echo $ret\n}\n\n### Main\n\nreport_file=$src_dir/report.html\nsummary_file=$src_dir/summary.html\n\npassed=0\nfailed=0\ntotal=0\n\npass(){\n\tpassed=`expr $passed + 1`\n}\n\nfail(){\n\tfailed=`expr $failed + 1`\n}\n\n(\n\theader Report $run $date\n\ttable \"border=1\"\n\trow\n\tcolumn `bold Test case`\n\tcolumn `bold Result`\n\tcolumn `bold Elapsed`\n\tcolumn `bold Log`\n\tend_row\n) > $report_file\n\ncat $src_file | while read line \ndo\n    \teval `echo $line | awk -F\";\" '{ printf(\"prg=\\\"%s\\\"; no=\\\"%s\\\"; res=\\\"%s\\\"; time=\\\"%s\\\"\", $1, $2, $3, $4); }'`\n\n\tprg=`trim $prg`\n\tno=`trim $no`\n\tres=`trim $res`\n\ttime=`trim $time`\n\tres_dir=\"<a href=\\\"result.$no/\\\">log</a>\"\n\n\tts=`time_spec $time`\n\tres_txt=\"\"\n\tcase $res in\n\t0) pass; res_txt=\"PASSED\";;\n\t*) fail; res_txt=\"FAILED\";;\n\tesac\n\n\tif [ ! -d \"$src_dir/result.$no\" ]; then res_dir=\"&nbsp;\"; fi\n\n\ttotal=`expr $total + $time`\n\n\t(\n\t\trow \n\t\tcolumn $prg\n\t\tcolumn $res_txt\n\t\tcolumn $ts \n\t\tcolumn $res_dir\n\t\tend_row\n\t) >> $report_file\n\n\t(\n        \trow\n        \tcolumn $run\n        \tcolumn $date\n        \tcolumn $passed\n        \tcolumn $failed\n        \tcolumn `time_spec $total`\n        \tcolumn \"<a href=\\\"result-$run/$date/report.html\\\">report</a>\"\n        \tcolumn \"<a href=\\\"result-$run/$date/log.txt\\\">log.txt</a>\"\n        \tend_row\n\t) > $summary_file\ndone\n\n(\n\tend_table\n\tfooter\n) >> $report_file\n\nexit 0\n", "num_lines": 209}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# NAME\n#   make-index.sh\n#\n# SYNOPSIS\n#   make-index.sh [ -d <dir> ]\n#\n# DESCRIPTION\n#\n# OPTIONS\n#\n# EXAMPLES\n#   \n#   \n# ENVIRONMENT\n#   NDB_PROJ_HOME       Home dir for ndb\n#   \n# FILES\n#   $NDB_PROJ_HOME/lib/funcs.sh  general shell script functions\n#\n#\n# SEE ALSO\n#   \n# DIAGNOSTICTS\n#   \n# VERSION   \n#   1.0\n#   \n# AUTHOR\n#   Jonas Oreland\n#\n\nprogname=`basename $0`\nsynopsis=\"make-index.sh [ -d <dir> ]\"\n\n: ${NDB_PROJ_HOME:?}\t\t # If undefined, exit with error message\n\n: ${NDB_LOCAL_BUILD_OPTIONS:=--} # If undef, set to --. Keeps getopts happy.\n\t\t\t         # You may have to experiment a bit  \n                                 # to get quoting right (if you need it).\n\n\n. $NDB_PROJ_HOME/lib/funcs.sh    # Load some good stuff\n\n# defaults for options related variables \n#\n\ndst_dir=/home/autotest/html\nreport_date=`date '+%Y-%m-%d'`\nuniq_id=$$.$$\nverbose=yes\n\n# used if error when parsing the options environment variable\n#\nenv_opterr=\"options environment variable: <<$options>>\" \n\n# Option parsing, for the options variable as well as the command line.\n#\n# We want to be able to set options in an environment variable,\n# as well as on the command line. In order not to have to repeat\n# the same getopts information twice, we loop two times over the\n# getopts while loop. The first time, we process options from\n# the options environment variable, the second time we process \n# options from the command line.\n#\n# The things to change are the actual options and what they do.\n#\n#\n\nfor optstring in \"$options\"  \"\"\t     # 1. options variable  2. cmd line\ndo\n\n    while getopts q:s:R:d: i $optstring  # optstring empty => no arg => cmd line\n    do\n\tcase $i in\n\n\tq)\tverbose=\"\";;\t\t# echo important things\n\td)      dst_dir=$OPTARG;;       # Destination directory\n\t\\?)\tsyndie $env_opterr;;    # print synopsis and exit\n\n\tesac\n    done\n\n    [ -n \"$optstring\" ]  &&  OPTIND=1 \t# Reset for round 2, cmdline options\n\n    env_opterr= \t\t\t# Round 2 should not use the value\n\ndone\nshift `expr $OPTIND - 1`\n\ndst_dir=`abspath $dst_dir`\n\n###\n#\n# General html functions\nheader(){\n    cat <<EOF\n<html><head><title>$*</title></head>\n<body>\nEOF\n}\n\nfooter(){\n    cat <<EOF\n</body></html>\nEOF\n}\n\nheading(){\n    h=$1; shift\n    cat <<EOF\n<h$h>$*</h$h>\nEOF\n}\n\ntable(){\n    echo \"<table $*>\"\n}\n\nend_table(){\n    echo \"</table>\"\n}\n\nrow(){\n    echo \"<tr>\"\n}\n\nend_row(){\n    echo \"</tr>\"\n}\n\nc_column(){\n    cat <<EOF\n<td valign=center align=center>$*</td>\nEOF\n}\n\nbold(){\n    cat <<EOF\n<b>$*</b>\nEOF\n}\ncolumn(){\n    cat <<EOF\n<td valign=center align=left>$*</td>\nEOF\n}\n\npara(){\n    cat <<EOF\n<p></p>\nEOF\n}\n\nhr(){\n    cat <<EOF\n<hr>\nEOF\n}\n\ninc_summary() {\n\tgrep -v 'html>' $2 | grep -v body |  sed 's/href=\"/href=\"'$1'\\//g'\n}\n\n# --- option parsing done ---\n\n\n\n# -- Verify\ntrace \"Verifying arguments\"\n\n# --- option verifying done ---\n\n### Main\n\n# Re creating index\ntrace \"Creating index\"\n(\n    header \"Autotest super-duper index\"\n    heading 1 \"<center>Autotest super-duper index</center>\"\n    cat -E README.autotest | sed 's/\\$/<BR>/g'\n    echo \"<br>\" \n    echo \"Current <a href=\"crontab.current\">crontab</a> installed on mc01 running [\" `uname -a` \"]\"\n    hr\n\n    dirs=`find $dst_dir -name 'summary.*.html' -type f -maxdepth 2 -exec dirname {} \\; | sort -u`\n\n    dates=`find $dst_dir -name 'summary.*.html' -type f -maxdepth 2 -exec basename {} \\; | sed 's/summary\\.\\(.*\\)\\.html/\\1/g' | sort -u | sort -r`\n\n    echo \"<p align=center>\"\n\n#inline 5 latest reports\n    r_count=5\n    for d in $dates\n    do\n\tfor o in $dirs\n\tdo\n            o=`basename $o`\n            if [ -r $dst_dir/$o/summary.$d.html ]\n            then\n                inc_summary $o $dst_dir/$o/summary.$d.html\n\t\thr\n\n\t\tr_count=`expr $r_count - 1`\n\t\tif [ $r_count -eq 0 ]\n\t\tthen\n\t\t\tbreak 2\n\t\tfi\n            fi\n        done\n    done\n\t\n    table \"border=1\"\n    row\n    for i in $dirs\n    do\n\ti=`basename $i`\n\tcolumn `bold $i`\n    done\n    end_row\n\n\n    for d in $dates\n    do\n\trow\n\tfor o in $dirs\n\tdo\n\t    o=`basename $o`\n\t    if [ -r $dst_dir/$o/summary.$d.html ]\n\t    then\n\t\tcolumn \"<a href=$o/summary.$d.html>$d</a>\"\n\t    else\n\t\tcolumn \"\"\n\t    fi\n\tdone\n\tend_row\n    done\n    end_table\n    footer\n) > $dst_dir/index.html\n\nexit 0\n", "num_lines": 260}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2005, 2006 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"ndb-autotest.sh version 1.04\"\n\nDATE=`date '+%Y-%m-%d'`\nHOST=`hostname -s`\nexport DATE HOST\n\nset -e\nulimit -Sc unlimited\n\necho \"`date` starting: $*\"\n\nRSYNC_RSH=ssh\nexport RSYNC_RSH\n\nverbose=0\ndo_clone=yes\nbuild=yes\ndeploy=yes\nrun_test=yes\nconfig=yes\nreport=yes\n\nclone=5.0-ndb\nRUN=\"daily-basic daily-devel\"\nconf=autotest.conf\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --no-deploy) deploy=\"\";;\n                --no-test) run_test=\"\";;\n                --no-config) config=\"\";;\n                --no-report) report=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone=`echo $1 | sed s/--clone=//`;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n                --version) echo $VERSION; exit;;\n                *) RUN=$*;;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: $conf\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"target base_dir src_clone_base install_dir build_dir hosts configure\"\nif [ \"$report\" ]\nthen\n\tvars=\"$vars result_host result_path\"\nfi\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\nsrc_clone=$src_clone_base-$clone\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\nif [ `uname -s` != \"SunOS\" ]\nthen\n\ttrap \"rm -f $LOCK\" ERR\nfi\n\n# You can add more to this path#\n################################\n\ndst_place=${build_dir}/clone-mysql-$clone-$DATE\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place\n\tbk clone  $src_clone $dst_place\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\n\nif [ \"$build\" ]\nthen\n\tcd $dst_place\n        rm -rf $install_dir/*\n\tif [ -x BUILD/autorun.sh ]\n\tthen\n\t    ./BUILD/autorun.sh\n\telse\n\t    aclocal; autoheader; autoconf; automake\n\t    if [ -d storage ]\n\t    then\n\t\t(cd storage/innobase; aclocal; autoheader; autoconf; automake)\n\t    else\n\t\t(cd innobase; aclocal; autoheader; autoconf; automake)\n\t    fi\n\tfi\n\teval $configure --prefix=$install_dir\n\tmake\n\tmake install\n\t(cd $install_dir; ./bin/mysql_install_db) # This will be rsynced to all\nfi\n\n################################\n# check script version. If the #\n# version is old, replace it   #\n# and restart\t\t       #\n################################\n\nscript=$install_dir/mysql-test/ndb/ndb-autotest.sh\nif [ -x $script ]\nthen\n\t$script --version > /tmp/version.$$\nelse\n\techo $VERSION > /tmp/version.$$\nfi\t\nmatch=`grep -c \"$VERSION\" /tmp/version.$$ | xargs echo`\nrm -f /tmp/version.$$\nif [ $match -eq 0 ]\nthen\n\techo \"Incorrect script version...restarting\"\n\tcp $install_dir/mysql-test/ndb/ndb-autotest.sh /tmp/at.$$.sh\n\trm -rf $install_dir $dst_place\n\tsh /tmp/at.$$.sh $save_args\n\texit\nfi\n\n###############################################\n# Check that all interesting files are present#\n###############################################\n\ntest_dir=$install_dir/mysql-test/ndb\natrt=$test_dir/atrt\nhtml=$test_dir/make-html-reports.sh\nmkconfig=$install_dir/mysql-test/ndb/make-config.sh\n\n##########################\n#Setup bin and test paths#\n##########################\n\nPATH=$install_dir/bin:$test_dir:$PATH\nexport PATH\n\n###########################\n# This will filter out all#\n# the host that did not   #\n# respond. Called below   #\n###########################\n\nfilter(){\n\tneg=$1\n\tshift\n\twhile [ $# -gt 0 ]\n\tdo\n\t\tif [ `grep -c $1 $neg | xargs echo` -eq 0 ] ; then echo $1; fi\n\t\tshift\n\tdone\n}\n\n############################\n# check ndb_cpcc fail hosts#\n############################\nndb_cpcc $hosts | awk '{ if($1==\"Failed\"){ print;}}' > /tmp/failed.$DATE\nfilter /tmp/failed.$DATE $hosts > /tmp/hosts.$DATE\nhosts=`cat /tmp/hosts.$DATE` \n\n#############################\n# Push bin and test to hosts#\n#############################\n\nif [ \"$deploy\" ]\nthen\n    for i in $hosts\n    do\n      rsync -a --delete --force --ignore-errors $install_dir/ $i:$install_dir\n      ok=$?\n      if [ $ok -ne 0 ]\n\t  then\n\t  echo \"$i failed during rsync, excluding\"\n\t  echo $i >> /tmp/failed.$DATE\n      fi\n    done\nfi\n\n###\n# handle scp failed hosts\n#\nfilter /tmp/failed.$DATE $hosts > /tmp/hosts.$DATE\nhosts=`cat /tmp/hosts.$DATE` \ncat /tmp/failed.$DATE > /tmp/filter_hosts.$$\n\n#############################\n# Function for replacing the#\n# choose host with real host#\n# names. Note $$ = PID\t    #\n#############################\nchoose(){\n        SRC=$1\n        TMP1=/tmp/choose.$$\n        TMP2=/tmp/choose.$$.$$\n        shift\n\n        cp $SRC $TMP1\n        i=1\n        while [ $# -gt 0 ]\n        do\n                sed -e s,\"CHOOSE_host$i\",$1,g < $TMP1 > $TMP2\n                mv $TMP2 $TMP1\n                shift\n                i=`expr $i + 1`\n        done\n        cat $TMP1\n        rm -f $TMP1\n}\n\nchoose_conf(){\n    if [ -f $test_dir/conf-$1-$HOST.txt ]\n\tthen\n\techo \"$test_dir/conf-$1-$HOST.txt\"\n    elif [ -f $test_dir/conf-$1.txt ]\n    then\n\techo \"$test_dir/conf-$1.txt\"\n    elif [ -f $test_dir/conf-$HOST.txt ]\n\techo \"$test_dir/conf-$HOST.txt\"\n    else\n\techo \"Unable to find conf file looked for\" 1>&2\n\techo \"$test_dir/conf-$1-$HOST.txt and\" 1>&2\n\techo \"$test_dir/conf-$HOST.txt\" 1>&2\n\techo \"$test_dir/conf-$1.txt\" 1>&2\n\texit\n    fi\n}\n######################################\n# Starts ATRT and gives it the right #\n# command line options. after it     #\n# Gathers results and moves them     #\n######################################\nstart(){\n\trm -rf report.txt result* log.txt\n\t$atrt -v -v -r -R --log-file=log.txt --testcase-file=$test_dir/$2-tests.txt &\n\tpid=$!\n\techo $pid > run.pid\n\twait $pid\n\trm run.pid\n\t[ -f log.txt ] && mv log.txt $3\n\t[ -f report.txt ] && mv report.txt $3\n\t[ \"`find . -name 'result*'`\" ] && mv result* $3\n\tcd $3\n\tsh $html . $1 $DATE\n\tcd ..\n\tp2=`pwd`\n\tcd ..\n\tif [ \"$report\" ]\n\tthen\n\t\ttar cfz /tmp/res.$2.$$.tgz `basename $p2`/$DATE\n\t\tscp /tmp/res.$2.$$.tgz \\\n\t\t    $result_host:$result_path/res.$DATE.$HOST.$2.$$.tgz\n\t\tif [ $? -eq 0 ]\n\t\tthen\n\t\t    rm -f /tmp/res.$2.$$.tgz\n\t\tfi\n\tfi\n}\n\n#########################################\n# Count how many computers we have ready#\n#########################################\n\ncount_hosts(){\n    cnt=`grep \"CHOOSE_host\" $1 | awk '{for(i=1; i<=NF;i++) \\\n    if(index($i, \"CHOOSE_host\") > 0) print $i;}' | sort | uniq | wc -l`\n    echo $cnt\n}\n#######################################################\n# Calls: Choose                                       #\n#\t Choose_host                                  #\n#        Count_host                                   #\n#\t start                                        #\n# for each directory in the $RUN variable\t      #\n#######################################################\n\np=`pwd`\nfor dir in $RUN\ndo\n\techo \"Fixing hosts for $dir\"\n\n\trun_dir=$base_dir/run-$dir-mysql-$clone-$target\n\tres_dir=$base_dir/result-$dir-mysql-$clone-$target/$DATE\n\n\tmkdir -p $run_dir $res_dir\n\trm -rf $res_dir/*\n\tcd $run_dir\n\n\tif [ \"$config\" ]\n\tthen\n\t    rm -rf $run_dir/*\n\n\t    conf=`choose_conf $dir`\n\t    count=`count_hosts $conf`\n\t    avail_hosts=`filter /tmp/filter_hosts.$$ $hosts`\n\t    avail=`echo $avail_hosts | wc -w`\n\t    if  [ $count -gt $avail ]\n\t    then\n\t\techo \"Not enough hosts\"\n\t\techo \"Needs: $count available: $avail ($avail_hosts)\"\n\t\tbreak;\n\t    fi\n\n\t    run_hosts=`echo $avail_hosts| \\\n                       awk '{for(i=1;i<='$count';i++)print $i;}'`\n\t    echo $run_hosts >> /tmp/filter_hosts.$$\t\n\t\n\t    choose $conf $run_hosts > d.tmp.$$\n            sed -e s,CHOOSE_dir,\"$install_dir\",g < d.tmp.$$ > d.tmp\n\t    $mkconfig d.tmp\n\tfi\n\t\n\tif [ \"$run_test\" ]\n\tthen\n\t    start $dir-mysql-$clone-$target $dir $res_dir &\n\tfi\ndone\ncd $p\nrm /tmp/filter_hosts.$$\n\nwait\n\nrm -f $LOCK\n", "num_lines": 423}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2007 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"upgrade-boot.sh version 1.00\"\n\nDATE=`date '+%Y-%m-%d'`\nHOST=`hostname -s`\nexport DATE HOST\n\nset -e\n\necho \"`date` starting: $*\"\n\nverbose=0\ndo_clone=yes\nbuild=yes\n\ntag0=\ntag1=\nconf=\nextra_args=\nextra_clone=\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n                --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n                --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n                --version) echo $VERSION; exit;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n\t        --tag=*) tag0=`echo $1 | sed s/--tag=//`;;\n\t        --tag0=*) tag0=`echo $1 | sed s/--tag0=//`;;\n\t        --tag1=*) tag1=`echo $1 | sed s/--tag1=//`;;\n\t        --*) echo \"Unknown arg: $1\";;\n                *) RUN=$*;;\n        esac\n        shift\ndone\n\nif [ -z \"$clone1\" ]\nthen\n\tclone1=$clone0\nfi\n\nif [ -z \"$tag0\" ]\nthen\n\techo \"No tag0 specified\"\n\texit\nfi\n\nif [ -z \"$tag1\" ]\nthen\n        echo \"No tag1 specified\"\n        exit\nfi\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\nif [ -z \"$conf\" ]\nthen\n\tif [ -f \"`pwd`/autotest.conf\" ]\n\tthen\n\t\tconf=\"`pwd`/autotest.conf\"\n\telif [ -f \"$HOME/autotest.conf\" ]\n\tthen\n\t\tconf=\"$HOME/autotest.conf\"\n\tfi\nfi\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: >$conf<\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"src_clone_base install_dir build_dir\"\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\nsrc_clone0=${src_clone_base}${clone0}\nsrc_clone1=${src_clone_base}${clone1}\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\nif [ `uname -s` != \"SunOS\" ]\nthen\n\ttrap \"rm -f $LOCK\" ERR\nfi\n\n# You can add more to this path#\n################################\n\ndst_place0=${build_dir}/clone-$tag0-$DATE.$$\ndst_place1=${build_dir}/clone-$tag1-$DATE.$$\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place0 $dst_place1\n\tif [ `echo $src_clone0 | grep -c 'file:\\/\\/'` = 1 ]\n\tthen\n\t\tbk clone -l -r$tag0 $src_clone0 $dst_place0\n\telse\n\t\tbk clone -r$tag0 $src_clone0 $dst_place0\n\tfi\n\n        if [ `echo $src_clone1 | grep -c 'file:\\/\\/'` = 1 ]\n        then\n                bk clone -l -r$tag1 $src_clone1 $dst_place1\n        else\n                bk clone -r$tag1 $src_clone1 $dst_place1\n        fi\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\ninstall_dir0=$install_dir/$tag0\ninstall_dir1=$install_dir/$tag1\nif [ \"$build\" ]\nthen\n\tcd $dst_place0\n        rm -rf $install_dir0\n\tBUILD/compile-ndb-autotest --prefix=$install_dir0\n\tmake install\n\n\tcd $dst_place1\n\trm -rf $install_dir1\n        BUILD/compile-ndb-autotest --prefix=$install_dir1\n\tmake install\nfi\n\n\n################################\n# Start run script             #\n################################\n\nscript=$install_dir1/mysql-test/ndb/upgrade-run.sh\n$script $save_args --conf=$conf --install-dir=$install_dir --suite=$RUN --nolock $extra_args\n\nif [ \"$build\" ]\nthen\n    rm -rf $dst_place0 $dst_place1\nfi\nrm -f $LOCK\n", "num_lines": 236}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nMKFILE=`mktemp`\n# create and run a simple makefile\n# include rocksdb make file relative to the path of this script\necho \"include rocksdb/src.mk\nall:\n\t@echo \\$(LIB_SOURCES)\" > $MKFILE\nfor f in `make --makefile $MKFILE`\ndo\n  echo ../../rocksdb/$f\ndone\nrm $MKFILE\n\n# create build_version.cc file. Only create one if it doesn't exists or if it is different\n# this is so that we don't rebuild mysqld every time\nbv=rocksdb/util/build_version.cc\nbuild_date=$(date +%F)\npushd rocksdb>/dev/null\ngit_sha=$(git rev-parse  HEAD 2>/dev/null)\ngit_tag=$(git symbolic-ref -q --short HEAD || \\\n  git describe --tags --exact-match 2>/dev/null)\ngit_mod=$(git diff-index HEAD --quiet 2>/dev/null; echo $?)\ngit_date=$(git log -1 --date=format:\"%Y-%m-%d %T\" --format=\"%ad\" 2>/dev/null)\npopd>/dev/null\nif [ ! -f $bv ] || [ -z $git_sha ] || [ ! `grep -q $git_sha $bv` ]\nthen\nsed -e s/@GIT_SHA@/$git_sha/ -e s:@GIT_TAG@:\"$git_tag\":  \\\n    -e s/@GIT_MOD@/\"$git_mod\"/ -e s/@BUILD_DATE@/\"$build_date\"/  \\\n    -e s/@GIT_DATE@/\"$git_date\"/ \\\n    -e s/@ROCKSDB_PLUGIN_BUILTINS@/\"$(ROCKSDB_PLUGIN_BUILTINS)\"/ \\\n    -e s/@ROCKSDB_PLUGIN_EXTERNS@/\"$(ROCKSDB_PLUGIN_EXTERNS)\"/ \\\n    rocksdb/util/build_version.cc.in > $bv\nfi\n", "num_lines": 34}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nSCRIPT_NAME=\"`basename $0`\"\n\nusage()\n{\n  echo \"Usage: ${SCRIPT_NAME} [--help|-h]\"\n  echo \"\"\n  echo \"This script creates the MySQL system tables and starts the server.\"\n}\n\nfor arg do\n  case \"$arg\" in\n    --help|-h)\n      usage\n      exit 0\n      ;;\n    *)\n      echo \"${SCRIPT_NAME}: unknown option $arg\"\n      usage\n      exit 2\n      ;;\n  esac\ndone\n\nif test ! -x  ./scripts/mysql_install_db\nthen\n  echo \"I didn't find the script './scripts/mysql_install_db'.\"\n  echo \"Please execute this script in the mysql distribution directory!\"\n  exit 1;\nfi\n\necho \"NOTE: This is a MySQL binary distribution. It's ready to run, you don't\"\necho \"need to configure it!\"\necho \"\"\necho \"To help you a bit, I am now going to create the needed MySQL databases\"\necho \"and start the MySQL server for you.  If you run into any trouble, please\"\necho \"consult the MySQL manual, that you can find in the Docs directory.\"\necho \"\"\n\n./scripts/mysql_install_db --no-defaults\nif [ $? = 0 ]\nthen\n  echo \"Starting the mysqld server.  You can test that it is up and running\"\n  echo \"with the command:\"\n  echo \"./bin/mysqladmin version\"\n  ./bin/mysqld_safe --no-defaults &\nfi\n", "num_lines": 49}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# For advice on how to change settings please see\n# http://dev.mysql.com/doc/refman/5.6/en/server-configuration-defaults.html\n# *** DO NOT EDIT THIS FILE. It's a template which will be copied to the\n# *** default location during install, and will be replaced if you\n# *** upgrade to a newer version of MySQL.\n\n[mysqld]\n\n# Remove leading # and set to the amount of RAM for the most important data\n# cache in MySQL. Start at 70% of total RAM for dedicated server, else 10%.\n# innodb_buffer_pool_size = 128M\n\n# Remove leading # to turn on a very important data integrity option: logging\n# changes to the binary log between backups.\n# log_bin\n\n# These are commonly set, remove the # and set as required.\n# basedir = .....\n# datadir = .....\n# port = .....\n# server_id = .....\n@CNF_SOCKET_LINE@\n\n# Remove leading # to set options mainly useful for reporting servers.\n# The server defaults are faster for transactions and fast SELECTs.\n# Adjust sizes as needed, experiment to find the optimal values.\n# join_buffer_size = 128M\n# sort_buffer_size = 2M\n# read_rnd_buffer_size = 2M \n\nsql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES \n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# The log file name and location can be set in\n# /etc/my.cnf by setting the \"log-error\" option\n# in either [mysqld] or [mysqld_safe] section as\n# follows:\n#\n# [mysqld]\n# log-error=@localstatedir@/mysqld.log\n#\n# In case the root user has a password, then you\n# have to create a /root/.my.cnf configuration file\n# with the following content:\n#\n# [mysqladmin]\n# password = <secret> \n# user= root\n#\n# where \"<secret>\" is the password. \n#\n# ATTENTION: The /root/.my.cnf file should be readable\n# _ONLY_ by root !\n\n@localstatedir@/mysqld.log {\n        # create 600 mysql mysql\n        notifempty\n        daily\n        rotate 5\n        missingok\n        compress\n    postrotate\n\t# just if mysqld is really running\n\tif test -x @bindir@/mysqladmin && \\\n\t   @bindir@/mysqladmin ping &>/dev/null\n\tthen\n\t   @bindir@/mysqladmin flush-logs\n\tfi\n    endscript\n}\n", "num_lines": 38}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n\n# Mysql daemon start/stop script. Multi-instance enhancements by Tim Bunce.\n\n# Usually this is put in /etc/init.d (at least on machines SYSV R4\n# based systems) and linked to\n#     /etc/rc3.d/S99mysql.svr1\n# and /etc/rc0.d/S01mysql.svr1\n# When this is done the mysql server will be started when the machine is\n# started and shut down when the systems goes down. The '.svr1' suffix can\n# be used to identify one of a number of servers. Multiple symlinks can be\n# created, one per instance. The 'svrN' suffix can then be used to\n# prefix configuration variables in a seperate section of /etc/my.cnf.\n# See example below.\n#\n# A typical multi-instance /etc/my.cnf file would look like:\n# [mysqld]\n# basedir=...\n# key_buffer_size=16M\n# max_allowed_packet=1M\n# [mysql_multi_server]\n# svr1-datadir=/foo1/bar\n# svr2-datadir=/foo2/bar\n#\n# and then the /foo1/bar/my.cnf and /foo2/bar/my.cnf files\n# would contain all the *instance specific* configurations.\n#\n# This script can also be run manually in which case the server instance\n# is identified by an extra argument, for example:\n#     /etc/init.d/mysql stop svr3\n#\n\nPATH=/sbin:/usr/sbin:/bin:/usr/bin\nexport PATH\n\nmode=$1    # start or stop\nsvr=$2     # eg 'svr1' (optional)\nif [ \"$2\" = \"\" ]\nthen name=`basename $0`\nelse name=$2\nfi\n\n# Extract identity of the server we are working with\nsvr=`echo \"$name\" | sed -e 's/.*\\<\\(svr[1-9][0-9]*\\)\\>.*/\\1/'`\nif [ \"$svr\" = \"\" ]\nthen\n  echo \"Can't determine database svr number from name '$name'\"\n  exit 1\nfi\n\necho \"mysqld $svr $mode\"\n\nparse_arguments() {\n  for arg do\n    case \"$arg\" in\n      --basedir=*|--${svr}-basedir=*)\n        basedir=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n      --datadir=*|--${svr}-basedir=*)\n        datadir=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n      --pid-file=*|--${svr}-basedir=*)\n        pid_file=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n    esac\n  done\n}\n\n# Get arguments from the my.cnf file, groups [mysqld], [mysql_server],\n# and mysql_multi_server\nif test -x ./bin/my_print_defaults\nthen\n  print_defaults=\"./bin/my_print_defaults\"\nelif test -x @bindir@/my_print_defaults\nthen\n  print_defaults=\"@bindir@/my_print_defaults\"\nelif test -x @bindir@/mysql_print_defaults\nthen\n  print_defaults=\"@bindir@/mysql_print_defaults\"\nelse\n  # Try to find basedir in /etc/my.cnf\n  conf=/etc/my.cnf\n  print_defaults=\n  if test -r $conf\n  then\n    subpat='^[^=]*basedir[^=]*=\\(.*\\)$'\n    dirs=`sed -e \"/$subpat/!d\" -e 's//\\1/' $conf\n    for d in $dirs\n    do\n      d=`echo $d | sed -e 's/[ \t]//g'`\n      if test -x \"$d/bin/my_print_defaults\"\n      then\n        print_defaults=\"$d/bin/my_print_defaults\"\n        break\n      fi\n      if test -x \"$d/bin/mysql_print_defaults\"\n      then\n        print_defaults=\"$d/bin/mysql_print_defaults\"\n        break\n      fi\n    done\n  fi\n\n  # Hope it's in the PATH ... but I doubt it\n  test -z \"$print_defaults\" && print_defaults=\"my_print_defaults\"\nfi\n\ndatadir=@localstatedir@\nbasedir=\npid_file=\nparse_arguments `$print_defaults $defaults mysqld mysql_server mysql_multi_server`\n\nif test -z \"$basedir\"\nthen\n  basedir=@prefix@\n  bindir=@bindir@\nelse\n  bindir=\"$basedir/bin\"\nfi\nif test -z \"$pid_file\"\nthen\n  pid_file=$datadir/`@HOSTNAME@`.pid\nelse\n  case \"$pid_file\" in\n    /* ) ;;\n    * )  pid_file=\"$datadir/$pid_file\" ;;\n  esac\nfi\n\n# Safeguard (relative paths, core dumps..)\ncd $basedir\n\ncase \"$mode\" in\n  'start')\n    # Start daemon\n\n    if test -x $bindir/mysqld_safe\n    then\n      # We only need to specify datadir and pid-file here and we\n      # get all other instance-specific config from $datadir/my.cnf.\n      # We have to explicitly pass --defaults-extra-file because it\n      # reads the config files before the command line options.\n      # Also it must be first because of the way mysqld_safe works.\n      $bindir/mysqld_safe --defaults-extra-file=$datadir/my.cnf \\\n                          --datadir=$datadir --pid-file=$pid_file &\n      # Make lock for RedHat / SuSE\n      if test -d /var/lock/subsys\n      then\n        touch /var/lock/subsys/mysql\n      fi\n    else\n      echo \"Can't execute $bindir/mysqld_safe\"\n    fi\n    ;;\n\n  'stop')\n    # Stop daemon. We use a signal here to avoid having to know the\n    # root password.\n    if test -f \"$pid_file\"\n    then\n      mysqld_pid=`cat $pid_file`\n      echo \"Killing mysqld $svr with pid $mysqld_pid\"\n      kill $mysqld_pid\n      # mysqld should remove the pid_file when it exits, so wait for it.\n\n      sleep 1\n      while [ -s $pid_file -a \"$flags\" != aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ]\n      do\n        [ -z \"$flags\" ] && echo \"Wait for mysqld $svr to exit\\c\" || echo \".\\c\"\n        flags=a$flags\n        sleep 1\n      done\n      if [ -s $pid_file ]\n         then echo \" gave up waiting!\"\n      elif [ -n \"$flags\" ]\n         then echo \" done\"\n      fi\n      # delete lock for RedHat / SuSE\n      if test -e /var/lock/subsys/mysql\n      then\n        rm /var/lock/subsys/mysql\n      fi\n    else\n      echo \"No mysqld pid file found. Looked for $pid_file.\"\n    fi\n    ;;\n\n  *)\n    # usage\n    echo \"usage: $0 start|stop [ svrN ]\"\n    exit 1\n    ;;\nesac\n", "num_lines": 193}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# MySQL-shared-compat.spec\n#\n# RPM build instructions to create a \"meta\" package that includes two\n# versions of the MySQL shared libraries (for compatibility with\n# distributions that ship older versions of MySQL and do not provide a\n# separate \"MySQL-shared\" package. This spec file simply repackages two\n# already existing MySQL-shared RPMs into a single package.\n# \n# This program is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the Free\n# Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License along\n# with this program; if not, write to the Free Software Foundation, Inc., 51\n# Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n\n# For 5.0 and up, this is needed because of \"libndbclient\".\n%define _unpackaged_files_terminate_build 0\n\n#\n# Change this to match the version of the shared libs you want to include\n#\n%define version_cur @MYSQL_RPM_VERSION@\n%define version41 4.1.17\n%define version40 4.0.26\n%define version3 3.23.58\n\nName:         MySQL-shared-compat\nPackager:     Sun Microsystems, Inc. Product Engineering Team <build@mysql.com>\nVendor:       Sun Microsystems, Inc.\nLicense:      GPL\nGroup:        Applications/Databases\nURL:          http://www.mysql.com/\nAutoreqprov:  on\nVersion:      %{version_cur}\nRelease:      1\nBuildRoot:    %{_tmppath}/%{name}-%{version}-build\nObsoletes:    mysql-shared\nProvides:     MySQL-shared\nSummary:      MySQL shared client libraries for MySQL %{version}, %{version41}, %{version40} and %{version3}\n# We simply use the \"MySQL-shared\" subpackages as input sources instead of\n# rebuilding all from source\nSource0:      MySQL-shared-%{version_cur}-1.%{_arch}.rpm\nSource1:      MySQL-shared-%{version41}-1.%{_arch}.rpm\nSource2:      MySQL-shared-%{version40}-0.%{_arch}.rpm\nSource3:      MySQL-shared-%{version3}-1.%{_arch}.rpm\n# No need to include the RPMs once more - they can be downloaded seperately\n# if you want to rebuild this package\nNoSource:     0\nNoSource:     1\nNoSource:     2\nNoSource:     3\nBuildRoot:    %{_tmppath}/%{name}-%{version}-build\n\n%description\nThis package includes the shared libraries for MySQL %{version3},\nMySQL %{version40}, %{version41} as well as MySQL %{version_cur}.\nInstall this package instead of \"MySQL-shared\", if you have applications\ninstalled that are dynamically linked against older versions of the MySQL\nclient library but you want to upgrade to MySQL %{version} without breaking the\nlibrary dependencies.\n\n%install\n[ \"$RPM_BUILD_ROOT\" != \"/\" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT;\nmkdir -p $RPM_BUILD_ROOT\ncd $RPM_BUILD_ROOT\nrpm2cpio %{SOURCE0} | cpio -iv --make-directories\nrpm2cpio %{SOURCE1} | cpio -iv --make-directories\nrpm2cpio %{SOURCE2} | cpio -iv --make-directories\nrpm2cpio %{SOURCE3} | cpio -iv --make-directories\n/sbin/ldconfig -n $RPM_BUILD_ROOT%{_libdir}\n\n%clean\n[ \"$RPM_BUILD_ROOT\" != \"/\" ] && [ -d $RPM_BUILD_ROOT ] && rm -rf $RPM_BUILD_ROOT;\n\n%files\n%defattr(-, root, root)\n%{_libdir}/libmysqlclient*\n\n# The spec file changelog only includes changes made to the spec file\n# itself - note that they must be ordered by date (important when\n# merging BK trees)\n%changelog\n* Tue Dec 22 2009 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Change RPM file naming:\n  - Suffix like \"-m2\", \"-rc\" becomes part of version as \"_m2\", \"_rc\".\n  - Release counts from 1, not 0.\n\n", "num_lines": 97}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# This is an example SysV-init-script by Winfried Truemper that you can use\n# and modify to your liking\n#\n\nPATH=\"$PATH:@prefix@\"\nexport PATH\nMY_CFG=\"@prefix@/mysql.cfg\"\n\nread_mysql_config() {\n    # this routine requires a sed, which reads even the last line of input\n\n    MY_CONFIG_FILE=\"$1\"    # file to read setting from\n    MY_CONFIG_SECTION=\"$2\" # section inside the file\n    MY_CONFIG_TAG=\"$3\"     # name of the setting inside the section\n    TAB=`printf \"\\t\" \"\"`   # makes the code cut&paste safe\n\n    sed -n -f - \"$MY_CONFIG_FILE\" <<EOF\n1,/^\\[$MY_CONFIG_SECTION\\]/ d\n/^\\[[a-z]/ q\n/^$MY_CONFIG_TAG/ {\ns/^$MY_CONFIG_TAG[ $TAB]*=[ $TAB]*\\([^ $TAB]*\\)/\\1/\np\nq\n}\nEOF\n}\n\n\n\ndo_start() {\n    nohup ./bin/mysqld --defaults-file=\"$MY_CFG\" &\n}\n\ndo_stop() {\n    ./bin/mysqladmin --defaults-file=\"$MY_CFG\" shutdown\n}\n\ndo_kill_all() {\n    PIDS=`ps -efo pid,args | grep mysql | sed -e \"s,  *.*,,\" | sort | uniq`\n    kill $PIDS\n    sleep 5\n    kill -9 $PIDS\n}\n\ndo_kill() {\n    MY_PIDFILE=`read_mysql_config \"$MY_CFG\" \"mysqld\" \"pidfile\" `\n    read MY_PID < \"$MY_PIDFILE\"\n    kill \"$MY_PID\"\n    sleep 2\n    kill -KILL \"$MY_PID\"\n}\n\n# z.B. mysql.sh admin \"ping\"\ndo_admin() {\n    shift\n    ./bin/mysqladmin --defaults-file=\"$MY_CFG\" $@\n    exit\n}\n\ndo_repair() {\n    MY_DATADIR=`read_mysql_config \"$MY_CFG\" \"mysqld\" \"datadir\" `\n    ./bin/isamchk --defaults-file=\"$MY_CFG\" --repair \"$MY_DATADIR/$1\"\n    shift\n}\n\n\ndo_repair_all() {\n    MY_DATADIR=`read_mysql_config \"$MY_CFG\" \"mysqld\" \"datadir\" `\n    for i in `find \"$MY_DATADIR\" -name \"*.ISM\"`\n    do\n        ./bin/isamchk --defaults-file=\"$MY_CFG\" --repair \"$MY_DATADIR/$i\"\n    done\n}\n\n\n\nMY_BASEDIR=`read_mysql_config \"$MY_CFG\" \"mysqld\" \"basedir\"`\ncd \"$MY_BASEDIR\" || exit 1\nwhile test $# -gt 0\ndo\n    MY_ARG=\"$1\"\n    do_$MY_ARG $@\n    shift\ndone\n", "num_lines": 87}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n\n# MySQL daemon start/stop script.\n\n# Usually this is put in /etc/init.d (at least on machines SYSV R4 based\n# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.\n# When this is done the mysql server will be started when the machine is\n# started and shut down when the systems goes down.\n\n# Comments to support chkconfig on RedHat Linux\n# chkconfig: 2345 64 36\n# description: A very fast and reliable SQL database engine.\n\n# Comments to support LSB init script conventions\n### BEGIN INIT INFO\n# Provides: mysql\n# Required-Start: $local_fs $network $remote_fs\n# Should-Start: ypbind nscd ldap ntpd xntpd\n# Required-Stop: $local_fs $network $remote_fs\n# Default-Start:  2 3 4 5\n# Default-Stop: 0 1 6\n# Short-Description: start and stop MySQL\n# Description: MySQL is a very fast and reliable SQL database engine.\n### END INIT INFO\n \n# If you install MySQL on some other places than @prefix@, then you\n# have to do one of the following things for this script to work:\n#\n# - Run this script from within the MySQL installation directory\n# - Create a /etc/my.cnf file with the following information:\n#   [mysqld]\n#   basedir=<path-to-mysql-installation-directory>\n# - Add the above to any other configuration file (for example ~/.my.ini)\n#   and copy my_print_defaults to /usr/bin\n# - Add the path to the mysql-installation-directory to the basedir variable\n#   below.\n#\n# If you want to affect other MySQL variables, you should make your changes\n# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.\n\n# If you change base dir, you must also change datadir. These may get\n# overwritten by settings in the MySQL configuration files.\n\nbasedir=\ndatadir=\n\n# Default value, in seconds, afterwhich the script should timeout waiting\n# for server start. \n# Value here is overriden by value in my.cnf. \n# 0 means don't wait at all\n# Negative numbers mean to wait indefinitely\nservice_startup_timeout=900\n\n# Lock directory for RedHat / SuSE.\nlockdir='/var/lock/subsys'\nlock_file_path=\"$lockdir/mysql\"\n\n# The following variables are only set for letting mysql.server find things.\n\n# Set some defaults\nmysqld_pid_file_path=\nif test -z \"$basedir\"\nthen\n  basedir=@prefix@\n  bindir=@bindir@\n  if test -z \"$datadir\"\n  then\n    datadir=@localstatedir@\n  fi\n  sbindir=@sbindir@\n  libexecdir=@libexecdir@\nelse\n  bindir=\"$basedir/bin\"\n  if test -z \"$datadir\"\n  then\n    datadir=\"$basedir/data\"\n  fi\n  sbindir=\"$basedir/sbin\"\n  libexecdir=\"$basedir/libexec\"\nfi\n\n# datadir_set is used to determine if datadir was set (and so should be\n# *not* set inside of the --basedir= handler.)\ndatadir_set=\n\n#\n# Use LSB init script functions for printing messages, if possible\n#\nlsb_functions=\"/lib/lsb/init-functions\"\nif test -f $lsb_functions ; then\n  . $lsb_functions\nelse\n  log_success_msg()\n  {\n    echo \" SUCCESS! $@\"\n  }\n  log_failure_msg()\n  {\n    echo \" ERROR! $@\"\n  }\nfi\n\nPATH=\"/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin\"\nexport PATH\n\nmode=$1    # start or stop\n\n[ $# -ge 1 ] && shift\n\n\nother_args=\"$*\"   # uncommon, but needed when called from an RPM upgrade action\n           # Expected: \"--skip-networking --skip-grant-tables\"\n           # They are not checked here, intentionally, as it is the resposibility\n           # of the \"spec\" file author to give correct arguments only.\n\ncase `echo \"testing\\c\"`,`echo -n testing` in\n    *c*,-n*) echo_n=   echo_c=     ;;\n    *c*,*)   echo_n=-n echo_c=     ;;\n    *)       echo_n=   echo_c='\\c' ;;\nesac\n\nparse_server_arguments() {\n  for arg do\n    case \"$arg\" in\n      --basedir=*)  basedir=`echo \"$arg\" | sed -e 's/^[^=]*=//'`\n                    bindir=\"$basedir/bin\"\n\t\t    if test -z \"$datadir_set\"; then\n\t\t      datadir=\"$basedir/data\"\n\t\t    fi\n\t\t    sbindir=\"$basedir/sbin\"\n\t\t    libexecdir=\"$basedir/libexec\"\n        ;;\n      --datadir=*)  datadir=`echo \"$arg\" | sed -e 's/^[^=]*=//'`\n\t\t    datadir_set=1\n\t;;\n      --pid-file=*) mysqld_pid_file_path=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n      --service-startup-timeout=*) service_startup_timeout=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n    esac\n  done\n}\n\nwait_for_pid () {\n  verb=\"$1\"           # created | removed\n  pid=\"$2\"            # process ID of the program operating on the pid-file\n  pid_file_path=\"$3\" # path to the PID file.\n\n  i=0\n  avoid_race_condition=\"by checking again\"\n\n  while test $i -ne $service_startup_timeout ; do\n\n    case \"$verb\" in\n      'created')\n        # wait for a PID-file to pop into existence.\n        test -s \"$pid_file_path\" && i='' && break\n        ;;\n      'removed')\n        # wait for this PID-file to disappear\n        test ! -s \"$pid_file_path\" && i='' && break\n        ;;\n      *)\n        echo \"wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path\"\n        exit 1\n        ;;\n    esac\n\n    # if server isn't running, then pid-file will never be updated\n    if test -n \"$pid\"; then\n      if kill -0 \"$pid\" 2>/dev/null; then\n        :  # the server still runs\n      else\n        # The server may have exited between the last pid-file check and now.  \n        if test -n \"$avoid_race_condition\"; then\n          avoid_race_condition=\"\"\n          continue  # Check again.\n        fi\n\n        # there's nothing that will affect the file.\n        log_failure_msg \"The server quit without updating PID file ($pid_file_path).\"\n        return 1  # not waiting any more.\n      fi\n    fi\n\n    echo $echo_n \".$echo_c\"\n    i=`expr $i + 1`\n    sleep 1\n\n  done\n\n  if test -z \"$i\" ; then\n    log_success_msg\n    return 0\n  else\n    log_failure_msg\n    return 1\n  fi\n}\n\n# Get arguments from the my.cnf file,\n# the only group, which is read from now on is [mysqld]\nif test -x ./bin/my_print_defaults\nthen\n  print_defaults=\"./bin/my_print_defaults\"\nelif test -x $bindir/my_print_defaults\nthen\n  print_defaults=\"$bindir/my_print_defaults\"\nelif test -x $bindir/mysql_print_defaults\nthen\n  print_defaults=\"$bindir/mysql_print_defaults\"\nelse\n  # Try to find basedir in /etc/my.cnf\n  conf=/etc/my.cnf\n  print_defaults=\n  if test -r $conf\n  then\n    subpat='^[^=]*basedir[^=]*=\\(.*\\)$'\n    dirs=`sed -e \"/$subpat/!d\" -e 's//\\1/' $conf`\n    for d in $dirs\n    do\n      d=`echo $d | sed -e 's/[ \t]//g'`\n      if test -x \"$d/bin/my_print_defaults\"\n      then\n        print_defaults=\"$d/bin/my_print_defaults\"\n        break\n      fi\n      if test -x \"$d/bin/mysql_print_defaults\"\n      then\n        print_defaults=\"$d/bin/mysql_print_defaults\"\n        break\n      fi\n    done\n  fi\n\n  # Hope it's in the PATH ... but I doubt it\n  test -z \"$print_defaults\" && print_defaults=\"my_print_defaults\"\nfi\n\n#\n# Read defaults file from 'basedir'.   If there is no defaults file there\n# check if it's in the old (depricated) place (datadir) and read it from there\n#\n\nextra_args=\"\"\nif test -r \"$basedir/my.cnf\"\nthen\n  extra_args=\"-e $basedir/my.cnf\"\nelse\n  if test -r \"$datadir/my.cnf\"\n  then\n    extra_args=\"-e $datadir/my.cnf\"\n  fi\nfi\n\nparse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`\n\n#\n# Set pid file if not given\n#\nif test -z \"$mysqld_pid_file_path\"\nthen\n  mysqld_pid_file_path=$datadir/`@HOSTNAME@`.pid\nelse\n  case \"$mysqld_pid_file_path\" in\n    /* ) ;;\n    * )  mysqld_pid_file_path=\"$datadir/$mysqld_pid_file_path\" ;;\n  esac\nfi\n\ncase \"$mode\" in\n  'start')\n    # Start daemon\n\n    # Safeguard (relative paths, core dumps..)\n    cd $basedir\n\n    echo $echo_n \"Starting MySQL\"\n    if test -x $bindir/mysqld_safe\n    then\n      # Give extra arguments to mysqld with the my.cnf file. This script\n      # may be overwritten at next upgrade.\n      $bindir/mysqld_safe --datadir=\"$datadir\" --pid-file=\"$mysqld_pid_file_path\" $other_args >/dev/null &\n      wait_for_pid created \"$!\" \"$mysqld_pid_file_path\"; return_value=$?\n\n      # Make lock for RedHat / SuSE\n      if test -w \"$lockdir\"\n      then\n        touch \"$lock_file_path\"\n      fi\n\n      exit $return_value\n    else\n      log_failure_msg \"Couldn't find MySQL server ($bindir/mysqld_safe)\"\n    fi\n    ;;\n\n  'stop')\n    # Stop daemon. We use a signal here to avoid having to know the\n    # root password.\n\n    if test -s \"$mysqld_pid_file_path\"\n    then\n      mysqld_pid=`cat \"$mysqld_pid_file_path\"`\n\n      if (kill -0 $mysqld_pid 2>/dev/null)\n      then\n        echo $echo_n \"Shutting down MySQL\"\n        kill $mysqld_pid\n        # mysqld should remove the pid file when it exits, so wait for it.\n        wait_for_pid removed \"$mysqld_pid\" \"$mysqld_pid_file_path\"; return_value=$?\n      else\n        log_failure_msg \"MySQL server process #$mysqld_pid is not running!\"\n        rm \"$mysqld_pid_file_path\"\n      fi\n\n      # Delete lock for RedHat / SuSE\n      if test -f \"$lock_file_path\"\n      then\n        rm -f \"$lock_file_path\"\n      fi\n      exit $return_value\n    else\n      log_failure_msg \"MySQL server PID file could not be found!\"\n    fi\n    ;;\n\n  'restart')\n    # Stop the service and regardless of whether it was\n    # running or not, start it again.\n    if $0 stop  $other_args; then\n      $0 start $other_args\n    else\n      log_failure_msg \"Failed to stop running server, so refusing to try to start.\"\n      exit 1\n    fi\n    ;;\n\n  'reload'|'force-reload')\n    if test -s \"$mysqld_pid_file_path\" ; then\n      read mysqld_pid <  \"$mysqld_pid_file_path\"\n      kill -HUP $mysqld_pid && log_success_msg \"Reloading service MySQL\"\n      touch \"$mysqld_pid_file_path\"\n    else\n      log_failure_msg \"MySQL PID file could not be found!\"\n      exit 1\n    fi\n    ;;\n  'status')\n    # First, check to see if pid file exists\n    if test -s \"$mysqld_pid_file_path\" ; then \n      read mysqld_pid < \"$mysqld_pid_file_path\"\n      if kill -0 $mysqld_pid 2>/dev/null ; then \n        log_success_msg \"MySQL running ($mysqld_pid)\"\n        exit 0\n      else\n        log_failure_msg \"MySQL is not running, but PID file exists\"\n        exit 1\n      fi\n    else\n      # Try to find appropriate mysqld process\n      mysqld_pid=`pidof $libexecdir/mysqld`\n\n      # test if multiple pids exist\n      pid_count=`echo $mysqld_pid | wc -w`\n      if test $pid_count -gt 1 ; then\n        log_failure_msg \"Multiple MySQL running but PID file could not be found ($mysqld_pid)\"\n        exit 5\n      elif test -z $mysqld_pid ; then \n        if test -f \"$lock_file_path\" ; then \n          log_failure_msg \"MySQL is not running, but lock file ($lock_file_path) exists\"\n          exit 2\n        fi \n        log_failure_msg \"MySQL is not running\"\n        exit 3\n      else\n        log_failure_msg \"MySQL is running but PID file could not be found\"\n        exit 4\n      fi\n    fi\n    ;;\n    *)\n      # usage\n      basename=`basename \"$0\"`\n      echo \"Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]\"\n      exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 391}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; see the file COPYING. If not, write to the\n# Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston\n# MA  02110-1301  USA.\n\n##############################################################################\n# Some common macro definitions\n##############################################################################\n\n# NOTE: \"vendor\" is used in upgrade/downgrade check, so you can't\n# change these, has to be exactly as is.\n%global mysql_old_vendor        MySQL AB\n%global mysql_vendor_2          Sun Microsystems, Inc.\n%global mysql_vendor            Oracle and/or its affiliates\n\n%global mysql_version   @VERSION@\n\n%global mysqld_user     mysql\n%global mysqld_group    mysql\n%global mysqldatadir    /var/lib/mysql\n\n%global release         1  \n\n\n#\n# Macros we use which are not available in all supported versions of RPM\n#\n# - defined/undefined are missing on RHEL4\n#\n%if %{expand:%{?defined:0}%{!?defined:1}}\n%define defined()       %{expand:%%{?%{1}:1}%%{!?%{1}:0}}\n%endif\n%if %{expand:%{?undefined:0}%{!?undefined:1}}\n%define undefined()     %{expand:%%{?%{1}:0}%%{!?%{1}:1}}\n%endif\n\n# ----------------------------------------------------------------------------\n# RPM build tools now automatically detect Perl module dependencies.  This\n# detection causes problems as it is broken in some versions, and it also\n# provides unwanted dependencies from mandatory scripts in our package.\n# It might not be possible to disable this in all versions of RPM, but here we\n# try anyway.  We keep the \"AutoReqProv: no\" for the \"test\" sub package, as\n# disabling here might fail, and that package has the most problems.\n# See:\n#  http://fedoraproject.org/wiki/Packaging/Perl#Filtering_Requires:_and_Provides\n#  http://www.wideopen.com/archives/rpm-list/2002-October/msg00343.html\n# ----------------------------------------------------------------------------\n%undefine __perl_provides\n%undefine __perl_requires\n\n##############################################################################\n# Command line handling\n##############################################################################\n#\n# To set options:\n#\n#   $ rpmbuild --define=\"option <x>\" ...\n#\n\n# ----------------------------------------------------------------------------\n# Commercial builds\n# ----------------------------------------------------------------------------\n%if %{undefined commercial}\n%define commercial 0\n%endif\n\n# ----------------------------------------------------------------------------\n# Source name\n# ----------------------------------------------------------------------------\n%if %{undefined src_base}\n%define src_base mysql\n%endif\n%define src_dir %{src_base}-%{mysql_version}\n\n# ----------------------------------------------------------------------------\n# Feature set (storage engines, options).  Default to community (everything)\n# ----------------------------------------------------------------------------\n%if %{undefined feature_set}\n%define feature_set community\n%endif\n\n# ----------------------------------------------------------------------------\n# Server comment strings\n# ----------------------------------------------------------------------------\n%if %{undefined compilation_comment_debug}\n%define compilation_comment_debug       MySQL Community Server - Debug (GPL)\n%endif\n%if %{undefined compilation_comment_release}\n%define compilation_comment_release     MySQL Community Server (GPL)\n%endif\n\n# ----------------------------------------------------------------------------\n# Product and server suffixes\n# ----------------------------------------------------------------------------\n%if %{undefined product_suffix}\n  %if %{defined short_product_tag}\n    %define product_suffix      -%{short_product_tag}\n  %else\n    %define product_suffix      %{nil}\n  %endif\n%endif\n\n%if %{undefined server_suffix}\n%define server_suffix   %{nil}\n%endif\n\n# ----------------------------------------------------------------------------\n# Distribution support\n# ----------------------------------------------------------------------------\n%if %{undefined distro_specific}\n%define distro_specific 0\n%endif\n%if %{distro_specific}\n  %if %(test -f /etc/enterprise-release && echo 1 || echo 0)\n    %define oelver %(rpm -qf --qf '%%{version}\\\\n' /etc/enterprise-release | sed -e 's/^\\\\([0-9]*\\\\).*/\\\\1/g')\n    %if \"%oelver\" == \"4\"\n      %define distro_description        Oracle Enterprise Linux 4\n      %define distro_releasetag         oel4\n      %define distro_buildreq           gcc-c++ gperf ncurses-devel perl time zlib-devel cmake libaio-devel\n      %define distro_requires           chkconfig coreutils grep procps shadow-utils net-tools\n    %else\n      %if \"%oelver\" == \"5\"\n        %define distro_description      Oracle Enterprise Linux 5\n        %define distro_releasetag       oel5\n        %define distro_buildreq         gcc-c++ gperf ncurses-devel perl time zlib-devel cmake libaio-devel\n        %define distro_requires         chkconfig coreutils grep procps shadow-utils net-tools\n      %else\n        %{error:Oracle Enterprise Linux %{oelver} is unsupported}\n      %endif\n    %endif\n  %else\n    %if %(test -f /etc/oracle-release && echo 1 || echo 0)\n      %define elver %(rpm -qf --qf '%%{version}\\\\n' /etc/oracle-release | sed -e 's/^\\\\([0-9]*\\\\).*/\\\\1/g')\n      %if \"%elver\" == \"6\" || \"%elver\" == \"7\"\n        %define distro_description      Oracle Linux %elver\n        %define distro_releasetag       el%elver\n        %define distro_buildreq         gcc-c++ ncurses-devel perl time zlib-devel cmake libaio-devel numactl-devel\n        %define distro_requires         chkconfig coreutils grep procps shadow-utils net-tools\n      %else\n        %{error:Oracle Linux %{elver} is unsupported}\n      %endif\n    %else\n      %if %(test -f /etc/redhat-release && echo 1 || echo 0)\n        %define rhelver %(rpm -qf --qf '%%{version}\\\\n' /etc/redhat-release | sed -e 's/^\\\\([0-9]*\\\\).*/\\\\1/g')\n        %if \"%rhelver\" == \"4\"\n          %define distro_description      Red Hat Enterprise Linux 4\n          %define distro_releasetag       rhel4\n          %define distro_buildreq         gcc-c++ gperf ncurses-devel perl time zlib-devel cmake libaio-devel\n          %define distro_requires         chkconfig coreutils grep procps shadow-utils net-tools\n        %else\n          %if \"%rhelver\" == \"5\"\n            %define distro_description    Red Hat Enterprise Linux 5\n            %define distro_releasetag     rhel5\n            %define distro_buildreq       gcc-c++ gperf ncurses-devel perl time zlib-devel cmake libaio-devel\n            %define distro_requires       chkconfig coreutils grep procps shadow-utils net-tools\n          %else\n            %if \"%rhelver\" == \"6\"\n              %define distro_description    Red Hat Enterprise Linux 6\n              %define distro_releasetag     rhel6\n              %define distro_buildreq       gcc-c++ ncurses-devel perl time zlib-devel cmake libaio-devel numactl-devel\n              %define distro_requires       chkconfig coreutils grep procps shadow-utils net-tools\n            %else\n              %{error:Red Hat Enterprise Linux %{rhelver} is unsupported}\n            %endif\n          %endif\n        %endif\n      %else\n        %if %(test -f /etc/SuSE-release && echo 1 || echo 0)\n          %define susever %(rpm -qf --qf '%%{version}\\\\n' /etc/SuSE-release | cut -d. -f1)\n          %if \"%susever\" == \"10\"\n            %define distro_description    SUSE Linux Enterprise Server 10\n            %define distro_releasetag     sles10\n            %define distro_buildreq       gcc-c++ gdbm-devel gperf ncurses-devel openldap2-client zlib-devel cmake libaio-devel\n            %define distro_requires       aaa_base coreutils grep procps pwdutils\n          %else\n            %if \"%susever\" == \"11\"\n              %define distro_description  SUSE Linux Enterprise Server 11\n              %define distro_releasetag   sles11\n              %define distro_buildreq     gcc-c++ gdbm-devel gperf ncurses-devel openldap2-client procps pwdutils zlib-devel cmake libaio-devel libnuma-devel\n              %define distro_requires     aaa_base coreutils grep procps pwdutils\n            %else\n              %{error:SuSE %{susever} is unsupported}\n            %endif\n          %endif\n        %else\n          %{error:Unsupported distribution}\n        %endif\n      %endif\n    %endif\n  %endif\n%else\n  %define glibc_version %(/lib/libc.so.6 | grep stable | cut -d, -f1 | cut -c38-)\n  %define distro_description            Generic Linux (glibc %{glibc_version})\n  %define distro_releasetag             linux_glibc%{glibc_version}\n  %define distro_buildreq               gcc-c++ gperf ncurses-devel perl  time zlib-devel\n  %define distro_requires               coreutils grep procps /sbin/chkconfig /usr/sbin/useradd /usr/sbin/groupadd\n%endif\n\n# Avoid debuginfo RPMs, leaves binaries unstripped\n%define debug_package   %{nil}\n\n# Hack to work around bug in RHEL5 __os_install_post macro, wrong inverted\n# test for __debug_package\n%define __strip         /bin/true\n\n# ----------------------------------------------------------------------------\n# Support optional \"tcmalloc\" library (experimental)\n# ----------------------------------------------------------------------------\n%if %{defined malloc_lib_target}\n%define WITH_TCMALLOC 1\n%else\n%define WITH_TCMALLOC 0\n%endif\n\n##############################################################################\n# Configuration based upon above user input, not to be set directly\n##############################################################################\n\n%if 0%{?commercial}\n%define license_files_server    %{src_dir}/LICENSE.mysql\n%define license_type            Commercial\n%else\n%define license_files_server    %{src_dir}/COPYING %{src_dir}/README\n%define license_type            GPL\n%endif\n\n##############################################################################\n# Main spec file section\n##############################################################################\n\nName:           MySQL%{product_suffix}\nSummary:        MySQL: a very fast and reliable SQL database server\nGroup:          Applications/Databases\nVersion:        @MYSQL_RPM_VERSION@\nRelease:        %{release}%{?distro_releasetag:.%{distro_releasetag}}\nDistribution:   %{distro_description}\nLicense:        Copyright (c) 2000, @MYSQL_COPYRIGHT_YEAR@, %{mysql_vendor}. All rights reserved. Under %{license_type} license as shown in the Description field.\nSource:         http://www.mysql.com/Downloads/MySQL-@MYSQL_BASE_VERSION@/%{src_dir}.tar.gz\nURL:            http://www.mysql.com/\nPackager:       MySQL Release Engineering <mysql-build@oss.oracle.com> \nVendor:         %{mysql_vendor}\nBuildRequires:  %{distro_buildreq}\n\n# Regression tests may take a long time, override the default to skip them \n%{!?runselftest:%global runselftest 1}\n\n# Think about what you use here since the first step is to\n# run a rm -rf\nBuildRoot:    %{_tmppath}/%{name}-%{version}-build\n\n# From the manual\n%description\nThe MySQL(TM) software delivers a very fast, multi-threaded, multi-user,\nand robust SQL (Structured Query Language) database server. MySQL Server\nis intended for mission-critical, heavy-load production systems as well\nas for embedding into mass-deployed software. MySQL is a trademark of\n%{mysql_vendor}\n\nThe MySQL software has Dual Licensing, which means you can use the MySQL\nsoftware free of charge under the GNU General Public License\n(http://www.gnu.org/licenses/). You can also purchase commercial MySQL\nlicenses from %{mysql_vendor} if you do not wish to be bound by the terms of\nthe GPL. See the chapter \"Licensing and Support\" in the manual for\nfurther info.\n\nThe MySQL web site (http://www.mysql.com/) provides the latest\nnews and information about the MySQL software. Also please see the\ndocumentation and the manual for more information.\n\n##############################################################################\n# Sub package definition\n##############################################################################\n\n%package -n MySQL-server%{product_suffix}\nSummary:        MySQL: a very fast and reliable SQL database server\nGroup:          Applications/Databases\nRequires:       %{distro_requires}\n%if 0%{?commercial}\nObsoletes:      MySQL-server\n%else\nObsoletes:      MySQL-server-advanced\n%endif\nObsoletes:      mysql-server < %{version}-%{release}\nObsoletes:      mysql-server-advanced\nObsoletes:      MySQL-server-classic MySQL-server-community MySQL-server-enterprise\nObsoletes:      MySQL-server-advanced-gpl MySQL-server-enterprise-gpl\nProvides:       mysql-server = %{version}-%{release}\nProvides:       mysql-server%{?_isa} = %{version}-%{release}\n\n%description -n MySQL-server%{product_suffix}\nThe MySQL(TM) software delivers a very fast, multi-threaded, multi-user,\nand robust SQL (Structured Query Language) database server. MySQL Server\nis intended for mission-critical, heavy-load production systems as well\nas for embedding into mass-deployed software. MySQL is a trademark of\n%{mysql_vendor}\n\nThe MySQL software has Dual Licensing, which means you can use the MySQL\nsoftware free of charge under the GNU General Public License\n(http://www.gnu.org/licenses/). You can also purchase commercial MySQL\nlicenses from %{mysql_vendor} if you do not wish to be bound by the terms of\nthe GPL. See the chapter \"Licensing and Support\" in the manual for\nfurther info.\n\nThe MySQL web site (http://www.mysql.com/) provides the latest news and\ninformation about the MySQL software.  Also please see the documentation\nand the manual for more information.\n\nThis package includes the MySQL server binary as well as related utilities\nto run and administer a MySQL server.\n\nIf you want to access and work with the database, you have to install\npackage \"MySQL-client%{product_suffix}\" as well!\n\n# ----------------------------------------------------------------------------\n%package -n MySQL-client%{product_suffix}\nSummary:        MySQL - Client\nGroup:          Applications/Databases\n%if 0%{?commercial}\nObsoletes:      MySQL-client\n%else\nObsoletes:      MySQL-client-advanced\n%endif\nObsoletes:      mysql < %{version}-%{release}\nObsoletes:      mysql-advanced < %{version}-%{release}\nObsoletes:      MySQL-client-classic MySQL-client-community MySQL-client-enterprise\nObsoletes:      MySQL-client-advanced-gpl MySQL-client-enterprise-gpl\nProvides:       mysql = %{version}-%{release} \nProvides:       mysql%{?_isa} = %{version}-%{release}\n\n%description -n MySQL-client%{product_suffix}\nThis package contains the standard MySQL clients and administration tools.\n\nFor a description of MySQL see the base MySQL RPM or http://www.mysql.com/\n\n# ----------------------------------------------------------------------------\n%package -n MySQL-test%{product_suffix}\nSummary:        MySQL - Test suite\nGroup:          Applications/Databases\n%if 0%{?commercial}\nRequires:       MySQL-client-advanced perl\nObsoletes:      MySQL-test\n%else\nRequires:       MySQL-client perl\nObsoletes:      MySQL-test-advanced\n%endif\nObsoletes:      mysql-test < %{version}-%{release}\nObsoletes:      mysql-test-advanced\nObsoletes:      MySQL-test-classic MySQL-test-community MySQL-test-enterprise\nObsoletes:      MySQL-test-advanced-gpl MySQL-test-enterprise-gpl\nProvides:       mysql-test = %{version}-%{release}\nProvides:       mysql-test%{?_isa} = %{version}-%{release}\nAutoReqProv:    no\n\n%description -n MySQL-test%{product_suffix}\nThis package contains the MySQL regression test suite.\n\nFor a description of MySQL see the base MySQL RPM or http://www.mysql.com/\n\n# ----------------------------------------------------------------------------\n%package -n MySQL-devel%{product_suffix}\nSummary:        MySQL - Development header files and libraries\nGroup:          Applications/Databases\n%if 0%{?commercial}\nObsoletes:      MySQL-devel\n%else\nObsoletes:      MySQL-devel-advanced\n%endif\nObsoletes:      mysql-devel < %{version}-%{release}\nObsoletes:      mysql-embedded-devel mysql-devel-advanced mysql-embedded-devel-advanced\nObsoletes:      MySQL-devel-classic MySQL-devel-community MySQL-devel-enterprise\nObsoletes:      MySQL-devel-advanced-gpl MySQL-devel-enterprise-gpl\nProvides:       mysql-devel = %{version}-%{release}\nProvides:       mysql-devel%{?_isa} = %{version}-%{release}\n\n%description -n MySQL-devel%{product_suffix}\nThis package contains the development header files and libraries necessary\nto develop MySQL client applications.\n\nFor a description of MySQL see the base MySQL RPM or http://www.mysql.com/\n\n# ----------------------------------------------------------------------------\n%package -n MySQL-shared%{product_suffix}\nSummary:        MySQL - Shared libraries\nGroup:          Applications/Databases\n%if 0%{?commercial}\nObsoletes:      MySQL-shared\n%else\nObsoletes:      MySQL-shared-advanced\n%endif\nObsoletes:      MySQL-shared-standard MySQL-shared-pro\nObsoletes:      MySQL-shared-pro-cert MySQL-shared-pro-gpl\nObsoletes:      MySQL-shared-pro-gpl-cert\nObsoletes:      MySQL-shared-classic MySQL-shared-community MySQL-shared-enterprise\nObsoletes:      MySQL-shared-advanced-gpl MySQL-shared-enterprise-gpl\n\n%description -n MySQL-shared%{product_suffix}\nThis package contains the shared libraries (*.so*) which certain languages\nand applications need to dynamically load and use MySQL.\n\n# ----------------------------------------------------------------------------\n%package -n MySQL-embedded%{product_suffix}\nSummary:        MySQL - Embedded library\nGroup:          Applications/Databases\n%if 0%{?commercial}\nRequires:       MySQL-devel-advanced\nObsoletes:      MySQL-embedded\n%else\nRequires:       MySQL-devel\nObsoletes:      MySQL-embedded-advanced\n%endif\nObsoletes:      mysql-embedded < %{version}-%{release}\nObsoletes:      mysql-embedded-advanced\nObsoletes:      MySQL-embedded-pro\nObsoletes:      MySQL-embedded-classic MySQL-embedded-community MySQL-embedded-enterprise\nObsoletes:      MySQL-embedded-advanced-gpl MySQL-embedded-enterprise-gpl\nProvides:       mysql-embedded = %{version}-%{release}\nProvides:       mysql-embedded%{?_isa} = %{version}-%{release}\n\n%description -n MySQL-embedded%{product_suffix}\nThis package contains the MySQL server as an embedded library.\n\nThe embedded MySQL server library makes it possible to run a full-featured\nMySQL server inside the client application. The main benefits are increased\nspeed and more simple management for embedded applications.\n\nThe API is identical for the embedded MySQL version and the\nclient/server version.\n\nFor a description of MySQL see the base MySQL RPM or http://www.mysql.com/\n\n##############################################################################\n%prep\n%setup -T -a 0 -c -n %{src_dir}\n##############################################################################\n%build\n\n# Fail quickly and obviously if user tries to build as root\n%if %runselftest\n    if [ x\"`id -u`\" = x0 ]; then\n        echo \"The MySQL regression tests may fail if run as root.\"\n        echo \"If you really need to build the RPM as root, use\"\n        echo \"--define='runselftest 0' to skip the regression tests.\"\n        exit 1\n    fi\n%endif\n\n# Be strict about variables, bail at earliest opportunity, etc.\nset -eu\n\n# Optional package files\ntouch optional-files-devel\n\n#\n# Set environment in order of preference, MYSQL_BUILD_* first, then variable\n# name, finally a default.  RPM_OPT_FLAGS is assumed to be a part of the\n# default RPM build environment.\n#\n\n# This is a hack, $RPM_OPT_FLAGS on ia64 hosts contains flags which break\n# the compile in cmd-line-utils/libedit - needs investigation, but for now\n# we simply unset it and use those specified directly in cmake.\n%if \"%{_arch}\" == \"ia64\"\nRPM_OPT_FLAGS=\n%endif\n\nexport PATH=${MYSQL_BUILD_PATH:-$PATH}\nexport CC=${MYSQL_BUILD_CC:-${CC:-gcc}}\nexport CXX=${MYSQL_BUILD_CXX:-${CXX:-g++}}\nexport CFLAGS=${MYSQL_BUILD_CFLAGS:-${CFLAGS:-$RPM_OPT_FLAGS}}\nexport CXXFLAGS=${MYSQL_BUILD_CXXFLAGS:-${CXXFLAGS:-$RPM_OPT_FLAGS -felide-constructors}}\nexport LDFLAGS=${MYSQL_BUILD_LDFLAGS:-${LDFLAGS:-}}\nexport CMAKE=${MYSQL_BUILD_CMAKE:-${CMAKE:-cmake}}\nexport MAKE_JFLAG=${MYSQL_BUILD_MAKE_JFLAG:-}\n\n# By default, a build will include the bundeled \"yaSSL\" library for SSL.\n# However, there may be a need to override.\n# Protect against undefined variables if there is no override option.\n%if %{undefined with_ssl}\n%define ssl_option   %{nil}\n%else\n%define ssl_option   -DWITH_SSL=%{with_ssl}\n%endif\n\n# Build debug mysqld and libmysqld.a\nmkdir debug\n(\n  cd debug\n  # Attempt to remove any optimisation flags from the debug build\n  CFLAGS=`echo \" ${CFLAGS} \" | \\\n            sed -e 's/ -O[0-9]* / /' \\\n                -e 's/-Wp,-D_FORTIFY_SOURCE=2/ /' \\\n                -e 's/ -unroll2 / /' \\\n                -e 's/ -ip / /' \\\n                -e 's/^ //' \\\n                -e 's/ $//'`\n  CXXFLAGS=`echo \" ${CXXFLAGS} \" | \\\n              sed -e 's/ -O[0-9]* / /' \\\n                  -e 's/-Wp,-D_FORTIFY_SOURCE=2/ /' \\\n                  -e 's/ -unroll2 / /' \\\n                  -e 's/ -ip / /' \\\n                  -e 's/^ //' \\\n                  -e 's/ $//'`\n  # XXX: MYSQL_UNIX_ADDR should be in cmake/* but mysql_version is included before\n  # XXX: install_layout so we can't just set it based on INSTALL_LAYOUT=RPM\n  ${CMAKE} ../%{src_dir} -DBUILD_CONFIG=mysql_release -DINSTALL_LAYOUT=RPM \\\n           -DCMAKE_BUILD_TYPE=Debug \\\n           -DMYSQL_UNIX_ADDR=\"%{mysqldatadir}/mysql.sock\" \\\n           -DFEATURE_SET=\"%{feature_set}\" \\\n           %{ssl_option} \\\n           -DCOMPILATION_COMMENT=\"%{compilation_comment_debug}\" \\\n           -DMYSQL_SERVER_SUFFIX=\"%{server_suffix}\"\n  echo BEGIN_DEBUG_CONFIG ; egrep '^#define' include/config.h ; echo END_DEBUG_CONFIG\n  make ${MAKE_JFLAG} VERBOSE=1\n)\n# Build full release\nmkdir release\n(\n  cd release\n  # XXX: MYSQL_UNIX_ADDR should be in cmake/* but mysql_version is included before\n  # XXX: install_layout so we can't just set it based on INSTALL_LAYOUT=RPM\n  ${CMAKE} ../%{src_dir} -DBUILD_CONFIG=mysql_release -DINSTALL_LAYOUT=RPM \\\n           -DCMAKE_BUILD_TYPE=RelWithDebInfo \\\n           -DMYSQL_UNIX_ADDR=\"%{mysqldatadir}/mysql.sock\" \\\n           -DFEATURE_SET=\"%{feature_set}\" \\\n           %{ssl_option} \\\n           -DCOMPILATION_COMMENT=\"%{compilation_comment_release}\" \\\n           -DMYSQL_SERVER_SUFFIX=\"%{server_suffix}\"\n  echo BEGIN_NORMAL_CONFIG ; egrep '^#define' include/config.h ; echo END_NORMAL_CONFIG\n  make ${MAKE_JFLAG} VERBOSE=1\n)\n\n%if %runselftest\n  MTR_BUILD_THREAD=auto\n  export MTR_BUILD_THREAD\n\n  (cd release && make test-bt-fast || true)\n%endif\n\n##############################################################################\n%install\n\nRBR=$RPM_BUILD_ROOT\nMBD=$RPM_BUILD_DIR/%{src_dir}\n\n# Ensure that needed directories exists\ninstall -d $RBR%{_sysconfdir}/{logrotate.d,init.d}\ninstall -d $RBR%{mysqldatadir}/mysql\ninstall -d $RBR%{_datadir}/mysql-test\ninstall -d $RBR%{_datadir}/mysql/SELinux/RHEL4\ninstall -d $RBR%{_includedir}\ninstall -d $RBR%{_libdir}\ninstall -d $RBR%{_mandir}\ninstall -d $RBR%{_sbindir}\ninstall -d $RBR/var/lib/mysql-files\n\nmkdir -p $RBR%{_sysconfdir}/my.cnf.d\n\n# Install all binaries\n(\n  cd $MBD/release\n  make DESTDIR=$RBR install\n)\n\n# FIXME: at some point we should stop doing this and just install everything\n# FIXME: directly into %{_libdir}/mysql - perhaps at the same time as renaming\n# FIXME: the shared libraries to use libmysql*-$major.$minor.so syntax\nmv -v $RBR/%{_libdir}/*.a $RBR/%{_libdir}/mysql/\n\n# Install logrotate and autostart\ninstall -m 644 $MBD/release/support-files/mysql-log-rotate $RBR%{_sysconfdir}/logrotate.d/mysql\ninstall -m 755 $MBD/release/support-files/mysql.server $RBR%{_sysconfdir}/init.d/mysql\n\n# Create a symlink \"rcmysql\", pointing to the init.script. SuSE users\n# will appreciate that, as all services usually offer this.\nln -s %{_sysconfdir}/init.d/mysql $RBR%{_sbindir}/rcmysql\n\n# Touch the place where the my.cnf config file might be located\n# Just to make sure it's in the file list and marked as a config file\ntouch $RBR%{_sysconfdir}/my.cnf\n\n# Install SELinux files in datadir\ninstall -m 600 $MBD/%{src_dir}/support-files/RHEL4-SElinux/mysql.{fc,te} \\\n  $RBR%{_datadir}/mysql/SELinux/RHEL4\n\n%if %{WITH_TCMALLOC}\n# Even though this is a shared library, put it under /usr/lib*/mysql, so it\n# doesn't conflict with possible shared lib by the same name in /usr/lib*.  See\n# `mysql_config --variable=pkglibdir` and mysqld_safe for how this is used.\ninstall -m 644 \"%{malloc_lib_source}\" \\\n  \"$RBR%{_libdir}/mysql/%{malloc_lib_target}\"\n%endif\n\n# Remove man pages we explicitly do not want to package, avoids 'unpackaged\n# files' warning.\n# This has become obsolete:  rm -f $RBR%{_mandir}/man1/make_win_bin_dist.1*\n\n##############################################################################\n#  Post processing actions, i.e. when installed\n##############################################################################\n\n%pre -n MySQL-server%{product_suffix}\n# This is the code running at the beginning of a RPM upgrade action,\n# before replacing the old files with the new ones.\n\n# ATTENTION: Parts of this are duplicated in the \"triggerpostun\" !\n\n# There are users who deviate from the default file system layout.\n# Check local settings to support them.\nif [ -x %{_bindir}/my_print_defaults ]\nthen\n  mysql_datadir=`%{_bindir}/my_print_defaults server mysqld | grep '^--datadir=' | tail -1 | sed -n 's/--datadir=//p'`\n  PID_FILE_PATT=`%{_bindir}/my_print_defaults server mysqld | grep '^--pid-file=' | sed -n 's/--pid-file=//p'`\nfi\nif [ -z \"$mysql_datadir\" ]\nthen\n  mysql_datadir=%{mysqldatadir}\nfi\nif [ -z \"$PID_FILE_PATT\" ]\nthen\n  PID_FILE_PATT=\"$mysql_datadir/*.pid\"\nfi\n\n# Check if we can safely upgrade.  An upgrade is only safe if it's from one\n# of our RPMs in the same version family.\n\n# Handle both ways of spelling the capability.\ninstalled=`rpm -q --whatprovides mysql-server 2> /dev/null`\nif [ $? -ne 0 -o -z \"$installed\" ]; then\n  installed=`rpm -q --whatprovides MySQL-server 2> /dev/null`\nfi\nif [ $? -eq 0 -a -n \"$installed\" ]; then\n  installed=`echo $installed | sed 's/\\([^ ]*\\) .*/\\1/'` # Tests have shown duplicated package names\n  vendor=`rpm -q --queryformat='%{VENDOR}' \"$installed\" 2>&1`\n  version=`rpm -q --queryformat='%{VERSION}' \"$installed\" 2>&1`\n  myoldvendor='%{mysql_old_vendor}'\n  myvendor_2='%{mysql_vendor_2}'\n  myvendor='%{mysql_vendor}'\n  myversion='%{mysql_version}'\n\n  old_family=`echo $version \\\n    | sed -n -e 's,^\\([1-9][0-9]*\\.[0-9][0-9]*\\)\\..*$,\\1,p'`\n  new_family=`echo $myversion \\\n    | sed -n -e 's,^\\([1-9][0-9]*\\.[0-9][0-9]*\\)\\..*$,\\1,p'`\n\n  [ -z \"$vendor\" ] && vendor='<unknown>'\n  [ -z \"$old_family\" ] && old_family=\"<unrecognized version $version>\"\n  [ -z \"$new_family\" ] && new_family=\"<bad package specification: version $myversion>\"\n\n  error_text=\n  if [ \"$vendor\" != \"$myoldvendor\" \\\n    -a \"$vendor\" != \"$myvendor_2\" \\\n    -a \"$vendor\" != \"$myvendor\" ]; then\n    error_text=\"$error_text\nThe current MySQL server package is provided by a different\nvendor ($vendor) than $myoldvendor, $myvendor_2, or $myvendor.\nSome files may be installed to different locations, including log\nfiles and the service startup script in %{_sysconfdir}/init.d/.\n\"\n  fi\n\n  if [ \"$old_family\" != \"$new_family\" ]; then\n    error_text=\"$error_text\nUpgrading directly from MySQL $old_family to MySQL $new_family may not\nbe safe in all cases.  A manual dump and restore using mysqldump is\nrecommended.  It is important to review the MySQL manual's Upgrading\nsection for version-specific incompatibilities.\n\"\n  fi\n\n  if [ -n \"$error_text\" ]; then\n    cat <<HERE >&2\n\n******************************************************************\nA MySQL server package ($installed) is installed.\n$error_text\nA manual upgrade is required.\n\n- Ensure that you have a complete, working backup of your data and my.cnf\n  files\n- Shut down the MySQL server cleanly\n- Remove the existing MySQL packages.  Usually this command will\n  list the packages you should remove:\n  rpm -qa | grep -i '^mysql-'\n\n  You may choose to use 'rpm --nodeps -ev <package-name>' to remove\n  the package which contains the mysqlclient shared library.  The\n  library will be reinstalled by the MySQL-shared-compat package.\n- Install the new MySQL packages supplied by $myvendor\n- Ensure that the MySQL server is started\n- Run the 'mysql_upgrade' program\n\nThis is a brief description of the upgrade process.  Important details\ncan be found in the MySQL manual, in the Upgrading section.\n******************************************************************\nHERE\n    exit 1\n  fi\nfi\n\n# We assume that if there is exactly one \".pid\" file,\n# it contains the valid PID of a running MySQL server.\nNR_PID_FILES=`ls -1 $PID_FILE_PATT 2>/dev/null | wc -l`\ncase $NR_PID_FILES in\n\t0 ) SERVER_TO_START=''  ;;  # No \"*.pid\" file == no running server\n\t1 ) SERVER_TO_START='true' ;;\n\t* ) SERVER_TO_START=''      # Situation not clear\n\t    SEVERAL_PID_FILES=true ;;\nesac\n# That logic may be debated: We might check whether it is non-empty,\n# contains exactly one number (possibly a PID), and whether \"ps\" finds it.\n# OTOH, if there is no such process, it means a crash without a cleanup -\n# is that a reason not to start a new server after upgrade?\n\nSTATUS_FILE=$mysql_datadir/RPM_UPGRADE_MARKER\n\nif [ -f \"$STATUS_FILE\" ]; then\n\techo \"Some previous upgrade was not finished:\"\n\tls -ld $STATUS_FILE\n\techo \"Please check its status, then do\"\n\techo \"    rm $STATUS_FILE\"\n\techo \"before repeating the MySQL upgrade.\"\n\texit 1\nelif [ -n \"$SEVERAL_PID_FILES\" ] ; then\n\techo \"You have more than one PID file:\"\n\tls -ld $PID_FILE_PATT\n\techo \"Please check which one (if any) corresponds to a running server\"\n\techo \"and delete all others before repeating the MySQL upgrade.\"\n\texit 1\nfi\n\nNEW_VERSION=%{mysql_version}-%{release}\n\n# The \"pre\" section code is also run on a first installation,\n# when there  is no data directory yet. Protect against error messages.\n# Check for the existence of subdirectory \"mysql/\", the database of system\n# tables like \"mysql.user\".\nif [ -d $mysql_datadir/mysql ] ; then\n        echo \"MySQL RPM upgrade to version $NEW_VERSION\"  > $STATUS_FILE\n        echo \"'pre' step running at `date`\"          >> $STATUS_FILE\n        echo                                         >> $STATUS_FILE\n        fcount=`ls -ltr $mysql_datadir/*.err 2>/dev/null | wc -l`\n        if [ $fcount -gt 0 ] ; then\n             echo \"ERR file(s):\"                          >> $STATUS_FILE\n             ls -ltr $mysql_datadir/*.err                 >> $STATUS_FILE\n             echo                                         >> $STATUS_FILE\n             echo \"Latest 'Version' line in latest file:\" >> $STATUS_FILE\n             grep '^Version' `ls -tr $mysql_datadir/*.err | tail -1` | \\\n                tail -1                              >> $STATUS_FILE\n             echo                                         >> $STATUS_FILE\n        fi\n\n\tif [ -n \"$SERVER_TO_START\" ] ; then\n\t\t# There is only one PID file, race possibility ignored\n\t\techo \"PID file:\"                           >> $STATUS_FILE\n\t\tls -l   $PID_FILE_PATT                     >> $STATUS_FILE\n\t\tcat     $PID_FILE_PATT                     >> $STATUS_FILE\n\t\techo                                       >> $STATUS_FILE\n\t\techo \"Server process:\"                     >> $STATUS_FILE\n\t\tps -fp `cat $PID_FILE_PATT`                >> $STATUS_FILE\n\t\techo                                       >> $STATUS_FILE\n\t\techo \"SERVER_TO_START=$SERVER_TO_START\"    >> $STATUS_FILE\n\telse\n\t\t# Take a note we checked it ...\n\t\techo \"PID file:\"                           >> $STATUS_FILE\n\t\tls -l   $PID_FILE_PATT                     >> $STATUS_FILE 2>&1\n\tfi\nfi\n\n# Shut down a previously installed server first\n# Note we *could* make that depend on $SERVER_TO_START, but we rather don't,\n# so a \"stop\" is attempted even if there is no PID file.\n# (Maybe the \"stop\" doesn't work then, but we might fix that in itself.)\nif [ -x %{_sysconfdir}/init.d/mysql ] ; then\n        %{_sysconfdir}/init.d/mysql stop > /dev/null 2>&1\n        echo \"Giving mysqld 5 seconds to exit nicely\"\n        sleep 5\nfi\n\n%post -n MySQL-server%{product_suffix}\n# This is the code running at the end of a RPM install or upgrade action,\n# after the (new) files have been written.\n\n# ATTENTION: Parts of this are duplicated in the \"triggerpostun\" !\n\n# There are users who deviate from the default file system layout.\n# Check local settings to support them.\nif [ -x %{_bindir}/my_print_defaults ]\nthen\n  mysql_datadir=`%{_bindir}/my_print_defaults server mysqld | grep '^--datadir=' | tail -1 | sed -n 's/--datadir=//p'`\nfi\nif [ -z \"$mysql_datadir\" ]\nthen\n  mysql_datadir=%{mysqldatadir}\nfi\n\nNEW_VERSION=%{mysql_version}-%{release}\nSTATUS_FILE=$mysql_datadir/RPM_UPGRADE_MARKER\n\n# ----------------------------------------------------------------------\n# Create data directory if needed, check whether upgrade or install\n# ----------------------------------------------------------------------\nif [ ! -d \"$mysql_datadir\" ] ; then mkdir -m 755 \"$mysql_datadir\" ; fi\nif [ -f \"$STATUS_FILE\" ] ; then\n\tSERVER_TO_START=`grep '^SERVER_TO_START=' $STATUS_FILE | cut -c17-`\nelse\n\tSERVER_TO_START=''\nfi\n# echo \"Analyzed: SERVER_TO_START=$SERVER_TO_START\"\nif [ ! -d $mysql_datadir/mysql ] ; then\n\tmkdir $mysql_datadir/mysql $mysql_datadir/test\n\techo \"MySQL RPM installation of version $NEW_VERSION\" >> $STATUS_FILE\nelse\n\t# If the directory exists, we may assume it is an upgrade.\n\techo \"MySQL RPM upgrade to version $NEW_VERSION\" >> $STATUS_FILE\nfi\n\n# ----------------------------------------------------------------------\n# Make MySQL start/shutdown automatically when the machine does it.\n# ----------------------------------------------------------------------\n# NOTE: This still needs to be debated. Should we check whether these links\n# for the other run levels exist(ed) before the upgrade?\n# use chkconfig on Enterprise Linux and newer SuSE releases\nif [ -x /sbin/chkconfig ] ; then\n        /sbin/chkconfig --add mysql\n# use insserv for older SuSE Linux versions\nelif [ -x /sbin/insserv ] ; then\n        /sbin/insserv %{_sysconfdir}/init.d/mysql\nfi\n\n# ----------------------------------------------------------------------\n# Create a MySQL user and group. Do not report any problems if it already\n# exists.\n# ----------------------------------------------------------------------\ngroupadd -r %{mysqld_group} 2> /dev/null || true\nuseradd -M -r -d $mysql_datadir -s /bin/bash -c \"MySQL server\" \\\n  -g %{mysqld_group} %{mysqld_user} 2> /dev/null || true\n# The user may already exist, make sure it has the proper group nevertheless\n# (BUG#12823)\nusermod -g %{mysqld_group} %{mysqld_user} 2> /dev/null || true\n\n# ----------------------------------------------------------------------\n# Change permissions so that the user that will run the MySQL daemon\n# owns all database files.\n# ----------------------------------------------------------------------\nchown -R %{mysqld_user}:%{mysqld_group} $mysql_datadir\n\n# ----------------------------------------------------------------------\n# Initiate databases if needed\n# ----------------------------------------------------------------------\nif ! grep '^MySQL RPM upgrade' $STATUS_FILE >/dev/null 2>&1 ; then\n\t# Fix bug#45415: no \"mysql_install_db\" on an upgrade\n\t# Do this as a negative to err towards more \"install\" runs\n\t# rather than to miss one.\n\t%{_bindir}/mysql_install_db --rpm --user=%{mysqld_user} --random-passwords\n\n\t# Attention: Now 'root' is the only database user,\n\t# its password is a random value found in ~/.mysql_secret,\n\t# and the \"password expired\" flag is set:\n\t# Any client needs that password, and the first command\n\t# executed must be a new \"set password\"!\nfi\n\n# ----------------------------------------------------------------------\n# Upgrade databases if needed would go here - but it cannot be automated yet\n# ----------------------------------------------------------------------\n\n# ----------------------------------------------------------------------\n# Change permissions again to fix any new files.\n# ----------------------------------------------------------------------\nchown -R %{mysqld_user}:%{mysqld_group} $mysql_datadir\n\n# ----------------------------------------------------------------------\n# Fix permissions for the permission database so that only the user\n# can read them.\n# ----------------------------------------------------------------------\nchmod -R og-rw $mysql_datadir/mysql\n\n# ----------------------------------------------------------------------\n# install SELinux files - but don't override existing ones\n# ----------------------------------------------------------------------\nSETARGETDIR=/etc/selinux/targeted/src/policy\nSEDOMPROG=$SETARGETDIR/domains/program\nSECONPROG=$SETARGETDIR/file_contexts/program\nif [ -f /etc/redhat-release ] \\\n && (grep -q \"Red Hat Enterprise Linux .. release 4\" /etc/redhat-release \\\n || grep -q \"CentOS release 4\" /etc/redhat-release) ; then\n  echo\n  echo\n  echo 'Notes regarding SELinux on this platform:'\n  echo '========================================='\n  echo\n  echo 'The default policy might cause server startup to fail because it is'\n  echo 'not allowed to access critical files.  In this case, please update'\n  echo 'your installation.'\n  echo\n  echo 'The default policy might also cause inavailability of SSL related'\n  echo 'features because the server is not allowed to access /dev/random'\n  echo 'and /dev/urandom. If this is a problem, please do the following:'\n  echo\n  echo '  1) install selinux-policy-targeted-sources from your OS vendor'\n  echo '  2) add the following two lines to '$SEDOMPROG/mysqld.te':'\n  echo '       allow mysqld_t random_device_t:chr_file read;'\n  echo '       allow mysqld_t urandom_device_t:chr_file read;'\n  echo '  3) cd to '$SETARGETDIR' and issue the following command:'\n  echo '       make load'\n  echo\n  echo\nfi\n\nif [ -x sbin/restorecon ] ; then\n  sbin/restorecon -R var/lib/mysql\nfi\n\n# Was the server running before the upgrade? If so, restart the new one.\nif [ \"$SERVER_TO_START\" = \"true\" ] ; then\n\t# Restart in the same way that mysqld will be started normally.\n\tif [ -x %{_sysconfdir}/init.d/mysql ] ; then\n\t\t%{_sysconfdir}/init.d/mysql start\n\t\techo \"Giving mysqld 5 seconds to start\"\n\t\tsleep 5\n\tfi\nfi\n\n# Collect an upgrade history ...\necho \"Upgrade/install finished at `date`\"        >> $STATUS_FILE\necho                                             >> $STATUS_FILE\necho \"=====\"                                     >> $STATUS_FILE\nSTATUS_HISTORY=$mysql_datadir/RPM_UPGRADE_HISTORY\ncat $STATUS_FILE >> $STATUS_HISTORY\nmv -f  $STATUS_FILE ${STATUS_FILE}-LAST  # for \"triggerpostun\"\n\n\n#echo \"Thank you for installing the MySQL Community Server! For Production\n#systems, we recommend MySQL Enterprise, which contains enterprise-ready\n#software, intelligent advisory services, and full production support with\n#scheduled service packs and more.  Visit www.mysql.com/enterprise for more\n#information.\"\n\n%preun -n MySQL-server%{product_suffix}\n\n# Which '$1' does this refer to?  Fedora docs have info:\n# \" ... a count of the number of versions of the package that are installed.\n#   Action                           Count\n#   Install the first time           1\n#   Upgrade                          2 or higher (depending on the number of versions installed)\n#   Remove last version of package   0 \"\n#\n#  http://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch09s04s05.html\n \nif [ $1 = 0 ] ; then\n        # Stop MySQL before uninstalling it\n        if [ -x %{_sysconfdir}/init.d/mysql ] ; then\n                %{_sysconfdir}/init.d/mysql stop > /dev/null\n                # Remove autostart of MySQL\n                # use chkconfig on Enterprise Linux and newer SuSE releases\n                if [ -x /sbin/chkconfig ] ; then\n                        /sbin/chkconfig --del mysql\n                # For older SuSE Linux versions\n                elif [ -x /sbin/insserv ] ; then\n                        /sbin/insserv -r %{_sysconfdir}/init.d/mysql\n                fi\n        fi\nfi\n\n# We do not remove the mysql user since it may still own a lot of\n# database files.\n\n%triggerpostun -n MySQL-server%{product_suffix} --MySQL-server-community\n\n# Setup: We renamed this package, so any existing \"server-community\"\n#   package will be removed when this \"server\" is installed.\n# Problem: RPM will first run the \"pre\" and \"post\" sections of this script,\n#   and only then the \"preun\" of that old community server.\n#   But this \"preun\" includes stopping the server and uninstalling the service,\n#   \"chkconfig --del mysql\" which removes the symlinks to the start script.\n# Solution: *After* the community server got removed, restart this server\n#   and re-install the service.\n#\n# For information about triggers in spec files, see the Fedora docs:\n#   http://docs.fedoraproject.org/en-US/Fedora_Draft_Documentation/0.1/html/RPM_Guide/ch10s02.html\n# For all details of this code, see the \"pre\" and \"post\" sections.\n\n# There are users who deviate from the default file system layout.\n# Check local settings to support them.\nif [ -x %{_bindir}/my_print_defaults ]\nthen\n  mysql_datadir=`%{_bindir}/my_print_defaults server mysqld | grep '^--datadir=' | tail -1 | sed -n 's/--datadir=//p'`\nfi\nif [ -z \"$mysql_datadir\" ]\nthen\n  mysql_datadir=%{mysqldatadir}\nfi\n\nNEW_VERSION=%{mysql_version}-%{release}\nSTATUS_FILE=$mysql_datadir/RPM_UPGRADE_MARKER-LAST  # Note the difference!\nSTATUS_HISTORY=$mysql_datadir/RPM_UPGRADE_HISTORY\n\nif [ -f \"$STATUS_FILE\" ] ; then\n\tSERVER_TO_START=`grep '^SERVER_TO_START=' $STATUS_FILE | cut -c17-`\nelse\n\t# This should never happen, but let's be prepared\n\tSERVER_TO_START=''\nfi\necho \"Analyzed: SERVER_TO_START=$SERVER_TO_START\"\n\nif [ -x /sbin/chkconfig ] ; then\n        /sbin/chkconfig --add mysql\n# use insserv for older SuSE Linux versions\nelif [ -x /sbin/insserv ] ; then\n        /sbin/insserv %{_sysconfdir}/init.d/mysql\nfi\n\n# Was the server running before the upgrade? If so, restart the new one.\nif [ \"$SERVER_TO_START\" = \"true\" ] ; then\n\t# Restart in the same way that mysqld will be started normally.\n\tif [ -x %{_sysconfdir}/init.d/mysql ] ; then\n\t\t%{_sysconfdir}/init.d/mysql start\n\t\techo \"Giving mysqld 5 seconds to start\"\n\t\tsleep 5\n\tfi\nfi\n\necho \"Trigger 'postun --community' finished at `date`\"        >> $STATUS_HISTORY\necho                                             >> $STATUS_HISTORY\necho \"=====\"                                     >> $STATUS_HISTORY\n\n\n# ----------------------------------------------------------------------\n# Clean up the BuildRoot after build is done\n# ----------------------------------------------------------------------\n%clean\n[ \"$RPM_BUILD_ROOT\" != \"/\" ] && [ -d $RPM_BUILD_ROOT ] \\\n  && rm -rf $RPM_BUILD_ROOT;\n\n##############################################################################\n#  Files section\n##############################################################################\n\n%files -n MySQL-server%{product_suffix} -f release/support-files/plugins.files\n%defattr(-,root,root,0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n%doc %{src_dir}/Docs/ChangeLog\n%doc %{src_dir}/Docs/INFO_SRC*\n%doc release/Docs/INFO_BIN*\n%doc release/support-files/my-default.cnf\n\n%if 0%{?commercial}\n%doc %attr(644, root, root) %{_infodir}/mysql.info*\n%endif\n\n%doc %attr(644, root, man) %{_mandir}/man1/innochecksum.1*\n%doc %attr(644, root, man) %{_mandir}/man1/my_print_defaults.1*\n%doc %attr(644, root, man) %{_mandir}/man1/myisam_ftdump.1*\n%doc %attr(644, root, man) %{_mandir}/man1/myisamchk.1*\n%doc %attr(644, root, man) %{_mandir}/man1/myisamlog.1*\n%doc %attr(644, root, man) %{_mandir}/man1/myisampack.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_convert_table_format.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_fix_extensions.1*\n%doc %attr(644, root, man) %{_mandir}/man8/mysqld.8*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqld_multi.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqld_safe.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqldumpslow.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_install_db.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_plugin.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_secure_installation.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_setpermission.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_upgrade.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlman.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql.server.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqltest.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_tzinfo_to_sql.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_zap.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlbug.1*\n%doc %attr(644, root, man) %{_mandir}/man1/perror.1*\n%doc %attr(644, root, man) %{_mandir}/man1/replace.1*\n%doc %attr(644, root, man) %{_mandir}/man1/resolve_stack_dump.1*\n%doc %attr(644, root, man) %{_mandir}/man1/resolveip.1*\n\n%ghost %config(noreplace,missingok) %{_sysconfdir}/my.cnf\n%dir %{_sysconfdir}/my.cnf.d\n\n%attr(755, root, root) %{_bindir}/innochecksum\n%attr(755, root, root) %{_bindir}/my_print_defaults\n%attr(755, root, root) %{_bindir}/myisam_ftdump\n%attr(755, root, root) %{_bindir}/myisamchk\n%attr(755, root, root) %{_bindir}/myisamlog\n%attr(755, root, root) %{_bindir}/myisampack\n%attr(755, root, root) %{_bindir}/mysql_convert_table_format\n%attr(755, root, root) %{_bindir}/mysql_fix_extensions\n%attr(755, root, root) %{_bindir}/mysql_install_db\n%attr(755, root, root) %{_bindir}/mysql_plugin\n%attr(755, root, root) %{_bindir}/mysql_secure_installation\n%attr(755, root, root) %{_bindir}/mysql_setpermission\n%attr(755, root, root) %{_bindir}/mysql_tzinfo_to_sql\n%attr(755, root, root) %{_bindir}/mysql_upgrade\n%attr(755, root, root) %{_bindir}/mysql_zap\n%attr(755, root, root) %{_bindir}/mysqlbug\n%attr(755, root, root) %{_bindir}/mysqld_multi\n%attr(755, root, root) %{_bindir}/mysqld_safe\n%attr(755, root, root) %{_bindir}/mysqldumpslow\n%attr(755, root, root) %{_bindir}/mysqltest\n%attr(755, root, root) %{_bindir}/perror\n%attr(755, root, root) %{_bindir}/replace\n%attr(755, root, root) %{_bindir}/resolve_stack_dump\n%attr(755, root, root) %{_bindir}/resolveip\n\n%attr(755, root, root) %{_sbindir}/mysqld\n%attr(755, root, root) %{_sbindir}/mysqld-debug\n%attr(755, root, root) %{_sbindir}/rcmysql\n%attr(755, root, root) %{_libdir}/mysql/plugin/daemon_example.ini\n\n%if %{WITH_TCMALLOC}\n%attr(755, root, root) %{_libdir}/mysql/%{malloc_lib_target}\n%endif\n\n%attr(644, root, root) %config(noreplace,missingok) %{_sysconfdir}/logrotate.d/mysql\n%attr(755, root, root) %{_sysconfdir}/init.d/mysql\n%attr(755, root, root) %{_datadir}/mysql/\n%dir %attr(755, mysql, mysql) /var/lib/mysql\n%dir %attr(750, mysql, mysql) /var/lib/mysql-files\n\n# ----------------------------------------------------------------------------\n%files -n MySQL-client%{product_suffix}\n%defattr(-, root, root, 0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n%attr(755, root, root) %{_bindir}/msql2mysql\n%attr(755, root, root) %{_bindir}/mysql\n%attr(755, root, root) %{_bindir}/mysql_find_rows\n%attr(755, root, root) %{_bindir}/mysql_waitpid\n%attr(755, root, root) %{_bindir}/mysqlaccess\n# XXX: This should be moved to %{_sysconfdir}\n%attr(644, root, root) %{_bindir}/mysqlaccess.conf\n%attr(755, root, root) %{_bindir}/mysqladmin\n%attr(755, root, root) %{_bindir}/mysqlbinlog\n%attr(755, root, root) %{_bindir}/mysqlcheck\n%attr(755, root, root) %{_bindir}/mysqldump\n%attr(755, root, root) %{_bindir}/mysqlimport\n%attr(755, root, root) %{_bindir}/mysqlshow\n%attr(755, root, root) %{_bindir}/mysqlslap\n%attr(755, root, root) %{_bindir}/mysql_config_editor\n\n%doc %attr(644, root, man) %{_mandir}/man1/msql2mysql.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_find_rows.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_waitpid.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlaccess.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqladmin.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlbinlog.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlcheck.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqldump.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlimport.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlshow.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqlslap.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_config_editor.1*\n\n# ----------------------------------------------------------------------------\n%files -n MySQL-devel%{product_suffix} -f optional-files-devel\n%defattr(-, root, root, 0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n%doc %attr(644, root, man) %{_mandir}/man1/comp_err.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_config.1*\n%attr(755, root, root) %{_bindir}/mysql_config\n%dir %attr(755, root, root) %{_includedir}/mysql\n%dir %attr(755, root, root) %{_libdir}/mysql\n%{_includedir}/mysql/*\n%{_datadir}/aclocal/mysql.m4\n%{_libdir}/mysql/libmysqlclient.a\n%{_libdir}/mysql/libmysqlclient_r.a\n%{_libdir}/mysql/libmysqlservices.a\n\n# ----------------------------------------------------------------------------\n%files -n MySQL-shared%{product_suffix}\n%defattr(-, root, root, 0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n# Shared libraries (omit for architectures that don't support them)\n%{_libdir}/libmysql*.so*\n\n%post -n MySQL-shared%{product_suffix}\n/sbin/ldconfig\n\n%postun -n MySQL-shared%{product_suffix}\n/sbin/ldconfig\n\n# ----------------------------------------------------------------------------\n%files -n MySQL-test%{product_suffix}\n%defattr(-, root, root, 0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n%attr(-, root, root) %{_datadir}/mysql-test\n%attr(755, root, root) %{_bindir}/mysql_client_test\n%attr(755, root, root) %{_bindir}/mysql_client_test_embedded\n%attr(755, root, root) %{_bindir}/mysqltest_embedded\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_client_test.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql-stress-test.pl.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql-test-run.pl.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysql_client_test_embedded.1*\n%doc %attr(644, root, man) %{_mandir}/man1/mysqltest_embedded.1*\n\n# ----------------------------------------------------------------------------\n%files -n MySQL-embedded%{product_suffix}\n%defattr(-, root, root, 0755)\n%if %{defined license_files_server}\n%doc %{license_files_server}\n%endif\n%attr(755, root, root) %{_bindir}/mysql_embedded\n%attr(644, root, root) %{_libdir}/mysql/libmysqld.a\n%attr(644, root, root) %{_libdir}/mysql/libmysqld-debug.a\n\n##############################################################################\n# The spec file changelog only includes changes made to the spec file\n# itself - note that they must be ordered by date (important when\n# merging BK trees)\n##############################################################################\n%changelog\n* Mon Oct 06 2014 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Add license info in each subpackage\n\n* Wed May 28 2014 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Updated usergroup to mysql on datadir\n\n* Wed Oct 30 2013 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Removed non gpl file docs/mysql.info from community packages\n\n* Mon Sep 09 2013 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Updated logic to get the correct count of PID files\n\n* Fri Aug 16 2013 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Added provides lowercase mysql tags  \n\n* Wed Jun 26 2013 Balasubramanian Kandasamy <balasubramanian.kandasamy@oracle.com>\n- Cleaned up spec file to resolve rpm dependencies.\n\n* Mon Nov 05 2012 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Allow to override the default to use the bundled yaSSL by an option like\n      --define=\"with_ssl /path/to/ssl\"\n\n* Wed Oct 10 2012 Bjorn Munch <bjorn.munch@oracle.com>\n\n- Replace old my-*.cnf config file examples with template my-default.cnf\n\n* Fri Oct 05 2012 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Let the installation use the new option \"--random-passwords\" of \"mysql_install_db\".\n  (Bug# 12794345 Ensure root password)\n- Fix an inconsistency: \"new install\" vs \"upgrade\" are told from the (non)existence\n  of \"$mysql_datadir/mysql\" (holding table \"mysql.user\" and other system stuff).\n\n* Tue Jul 24 2012 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Add a macro \"runselftest\":\n  if set to 1 (default), the test suite will be run during the RPM build;\n  this can be oveeridden via the command line by adding\n      --define \"runselftest 0\"\n  Failures of the test suite will NOT make the RPM build fail!\n\n* Mon Jul 16 2012 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Add the man page for the \"mysql_config_editor\".\n\n* Mon Jun 11 2012 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Make sure newly added \"SPECIFIC-ULN/\" directory does not disturb packaging.\n\n* Wed Feb 29 2012 Brajmohan Saxena <brajmohan.saxena@oracle.com>\n\n- Removal all traces of the readline library from mysql (BUG 13738013)\n\n* Wed Sep 28 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Fix duplicate mentioning of \"mysql_plugin\" and its manual page,\n  it is better to keep alphabetic order in the files list (merging!).\n\n* Wed Sep 14 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Let the RPM capabilities (\"obsoletes\" etc) ensure that an upgrade may replace\n  the RPMs of any configuration (of the current or the preceding release series)\n  by the new ones. This is done by not using the implicitly generated capabilities\n  (which include the configuration name) and relying on more generic ones which\n  just list the function (\"server\", \"client\", ...).\n  The implicit generation cannot be prevented, so all these capabilities must be\n  explicitly listed in \"Obsoletes:\"\n\n* Tue Sep 13 2011 Jonathan Perkin <jonathan.perkin@oracle.com>\n\n- Add support for Oracle Linux 6 and Red Hat Enterprise Linux 6.  Due to\n  changes in RPM behaviour ($RPM_BUILD_ROOT is removed prior to install)\n  this necessitated a move of the libmygcc.a installation to the install\n  phase, which is probably where it belonged in the first place.\n\n* Tue Sep 13 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- \"make_win_bin_dist\" and its manual are dropped, cmake does it different.\n\n* Thu Sep 08 2011 Daniel Fischer <daniel.fischer@oracle.com>\n\n- Add mysql_plugin man page.\n\n* Tue Aug 30 2011 Tor Didriksen <tor.didriksen@oracle.com>\n\n- Set CXX=g++ by default to add a dependency on libgcc/libstdc++.\n  Also, remove the use of the -fno-exceptions and -fno-rtti flags.\n  TODO: update distro_buildreq/distro_requires\n\n* Tue Aug 30 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Add the manual page for \"mysql_plugin\" to the server package.\n\n* Fri Aug 19 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Null-upmerge the fix of bug#37165: This spec file is not affected.\n- Replace \"/var/lib/mysql\" by the spec file variable \"%%{mysqldatadir}\".\n\n* Fri Aug 12 2011 Daniel Fischer <daniel.fischer@oracle.com>\n\n- Source plugin library files list from cmake-generated file.\n\n* Mon Jul 25 2011 Chuck Bell <chuck.bell@oracle.com>\n\n- Added the mysql_plugin client - enables or disables plugins.\n\n* Thu Jul 21 2011 Sunanda Menon <sunanda.menon@oracle.com>\n\n- Fix bug#12561297: Added the MySQL embedded binary\n\n* Thu Jul 07 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Fix bug#45415: \"rpm upgrade recreates test database\"\n  Let the creation of the \"test\" database happen only during a new installation,\n  not in an RPM upgrade.\n  This affects both the \"mkdir\" and the call of \"mysql_install_db\".\n\n* Wed Feb 09 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Fix bug#56581: If an installation deviates from the default file locations\n  (\"datadir\" and \"pid-file\"), the mechanism to detect a running server (on upgrade)\n  should still work, and use these locations.\n  The problem was that the fix for bug#27072 did not check for local settings.\n\n* Mon Jan 31 2011 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- Install the new \"manifest\" files: \"INFO_SRC\" and \"INFO_BIN\".\n\n* Tue Nov 23 2010 Jonathan Perkin <jonathan.perkin@oracle.com>\n\n- EXCEPTIONS-CLIENT has been deleted, remove it from here too\n- Support MYSQL_BUILD_MAKE_JFLAG environment variable for passing\n  a '-j' argument to make.\n\n* Mon Nov 1 2010 Georgi Kodinov <georgi.godinov@oracle.com>\n\n- Added test authentication (WL#1054) plugin binaries\n\n* Wed Oct 6 2010 Georgi Kodinov <georgi.godinov@oracle.com>\n\n- Added example external authentication (WL#1054) plugin binaries\n\n* Wed Aug 11 2010 Joerg Bruehe <joerg.bruehe@oracle.com>\n\n- With a recent spec file cleanup, names have changed: A \"-community\" part was dropped.\n  Reflect that in the \"Obsoletes\" specifications.\n- Add a \"triggerpostun\" to handle the uninstall of the \"-community\" server RPM.\n- This fixes bug#55015 \"MySQL server is not restarted properly after RPM upgrade\".\n\n* Tue Jun 15 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Change the behaviour on installation and upgrade:\n  On installation, do not autostart the server.\n  *Iff* the server was stopped before the upgrade is started, this is taken as a\n  sign the administrator is handling that manually, and so the new server will\n  not be started automatically at the end of the upgrade.\n  The start/stop scripts will still be installed, so the server will be started\n  on the next machine boot.\n  This is the 5.5 version of fixing bug#27072 (RPM autostarting the server).\n\n* Tue Jun 1 2010 Jonathan Perkin <jonathan.perkin@oracle.com>\n\n- Implement SELinux checks from distribution-specific spec file.\n\n* Wed May 12 2010 Jonathan Perkin <jonathan.perkin@oracle.com>\n\n- Large number of changes to build using CMake\n- Introduce distribution-specific RPMs\n- Drop debuginfo, build all binaries with debug/symbols\n- Remove __os_install_post, use native macro\n- Remove _unpackaged_files_terminate_build, make it an error to have\n  unpackaged files\n- Remove cluster RPMs\n\n* Wed Mar 24 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Add \"--with-perfschema\" to the configure options.\n\n* Mon Mar 22 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- User \"usr/lib*\" to allow for both \"usr/lib\" and \"usr/lib64\",\n  mask \"rmdir\" return code 1.\n- Remove \"ha_example.*\" files from the list, they aren't built.\n\n* Wed Mar 17 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Fix a wrong path name in handling the debug plugins.\n\n* Wed Mar 10 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Take the result of the debug plugin build and put it into the optimized tree,\n  so that it becomes part of the final installation;\n  include the files in the packlist. Part of the fixes for bug#49022.\n\n* Mon Mar 01 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Set \"Oracle and/or its affiliates\" as the vendor and copyright owner,\n  accept upgrading from packages showing MySQL or Sun as vendor.\n\n* Fri Feb 12 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Formatting changes:\n  Have a consistent structure of separator lines and of indentation\n  (8 leading blanks => tab).\n- Introduce the variable \"src_dir\".\n- Give the environment variables \"MYSQL_BUILD_CC(CXX)\" precedence\n  over \"CC\" (\"CXX\").\n- Drop the old \"with_static\" argument analysis, this is not supported\n  in 5.1 since ages.\n- Introduce variables to control the handlers individually, as well\n  as other options.\n- Use the new \"--with-plugin\" notation for the table handlers.\n- Drop handling \"/etc/rc.d/init.d/mysql\", the switch to \"/etc/init.d/mysql\"\n  was done back in 2002 already.\n- Make \"--with-zlib-dir=bundled\" the default, add an option to disable it.\n- Add missing manual pages to the file list.\n- Improve the runtime check for \"libgcc.a\", protect it against being tried\n  with the Intel compiler \"icc\".\n\n* Mon Jan 11 2010 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Change RPM file naming:\n  - Suffix like \"-m2\", \"-rc\" becomes part of version as \"_m2\", \"_rc\".\n  - Release counts from 1, not 0.\n\n* Wed Dec 23 2009 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- The \"semisync\" plugin file name has lost its introductory \"lib\",\n  adapt the file lists for the subpackages.\n  This is a part missing from the fix for bug#48351.\n- Remove the \"fix_privilege_tables\" manual, it does not exist in 5.5\n  (and likely, the whole script will go, too).\n\n* Mon Nov 16 2009 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Fix some problems with the directives around \"tcmalloc\" (experimental),\n  remove erroneous traces of the InnoDB plugin (that is 5.1 only).\n\n* Tue Oct 06 2009 Magnus Blaudd <mvensson@mysql.com>\n\n- Removed mysql_fix_privilege_tables\n\n* Fri Oct 02 2009 Alexander Nozdrin <alexander.nozdrin@sun.com>\n\n- \"mysqlmanager\" got removed from version 5.4, all references deleted.\n\n* Fri Aug 28 2009 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- Merge up from 5.1 to 5.4: Remove handling for the InnoDB plugin.\n\n* Thu Aug 27 2009 Joerg Bruehe <joerg.bruehe@sun.com>\n\n- This version does not contain the \"Instance manager\", \"mysqlmanager\":\n  Remove it from the spec file so that packaging succeeds.\n\n* Mon Aug 24 2009 Jonathan Perkin <jperkin@sun.com>\n\n- Add conditionals for bundled zlib and innodb plugin\n\n* Fri Aug 21 2009 Jonathan Perkin <jperkin@sun.com>\n\n- Install plugin libraries in appropriate packages.\n- Disable libdaemon_example and ftexample plugins.\n\n* Thu Aug 20 2009 Jonathan Perkin <jperkin@sun.com>\n\n- Update variable used for mysql-test suite location to match source.\n\n* Fri Nov 07 2008 Joerg Bruehe <joerg@mysql.com>\n\n- Correct yesterday's fix, so that it also works for the last flag,\n  and fix a wrong quoting: un-quoted quote marks must not be escaped.\n\n* Thu Nov 06 2008 Kent Boortz <kent.boortz@sun.com>\n\n- Removed \"mysql_upgrade_shell\"\n- Removed some copy/paste between debug and normal build\n\n* Thu Nov 06 2008 Joerg Bruehe <joerg@mysql.com>\n\n- Modify CFLAGS and CXXFLAGS such that a debug build is not optimized.\n  This should cover both gcc and icc flags.  Fixes bug#40546.\n\n* Fri Aug 29 2008 Kent Boortz <kent@mysql.com>\n\n- Removed the \"Federated\" storage engine option, and enabled in all\n\n* Tue Aug 26 2008 Joerg Bruehe <joerg@mysql.com>\n\n- Get rid of the \"warning: Installed (but unpackaged) file(s) found:\"\n  Some generated files aren't needed in RPMs:\n  - the \"sql-bench/\" subdirectory\n  Some files were missing:\n  - /usr/share/aclocal/mysql.m4  (\"devel\" subpackage)\n  - Manual \"mysqlbug\" (\"server\" subpackage)\n  - Program \"innochecksum\" and its manual (\"server\" subpackage)\n  - Manual \"mysql_find_rows\" (\"client\" subpackage)\n  - Script \"mysql_upgrade_shell\" (\"client\" subpackage)\n  - Program \"ndb_cpcd\" and its manual (\"ndb-extra\" subpackage)\n  - Manuals \"ndb_mgm\" + \"ndb_restore\" (\"ndb-tools\" subpackage)\n\n* Mon Mar 31 2008 Kent Boortz <kent@mysql.com>\n\n- Made the \"Federated\" storage engine an option\n- Made the \"Cluster\" storage engine and sub packages an option\n\n* Wed Mar 19 2008 Joerg Bruehe <joerg@mysql.com>\n\n- Add the man pages for \"ndbd\" and \"ndb_mgmd\".\n\n* Mon Feb 18 2008 Timothy Smith <tim@mysql.com>\n\n- Require a manual upgrade if the alread-installed mysql-server is\n  from another vendor, or is of a different major version.\n\n* Wed May 02 2007 Joerg Bruehe <joerg@mysql.com>\n\n- \"ndb_size.tmpl\" is not needed any more,\n  \"man1/mysql_install_db.1\" lacked the trailing '*'.\n\n* Sat Apr 07 2007 Kent Boortz <kent@mysql.com>\n\n- Removed man page for \"mysql_create_system_tables\"\n\n* Wed Mar 21 2007 Daniel Fischer <df@mysql.com>\n\n- Add debug server.\n\n* Mon Mar 19 2007 Daniel Fischer <df@mysql.com>\n\n- Remove Max RPMs; the server RPMs contain a mysqld compiled with all\n  features that previously only were built into Max.\n\n* Fri Mar 02 2007 Joerg Bruehe <joerg@mysql.com>\n\n- Add several man pages for NDB which are now created.\n\n* Fri Jan 05 2007 Kent Boortz <kent@mysql.com>\n\n- Put back \"libmygcc.a\", found no real reason it was removed.\n\n- Add CFLAGS to gcc call with --print-libgcc-file, to make sure the\n  correct \"libgcc.a\" path is returned for the 32/64 bit architecture.\n\n* Mon Dec 18 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Fix the move of \"mysqlmanager\" to section 8: Directory name was wrong.\n\n* Thu Dec 14 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Include the new man pages for \"my_print_defaults\" and \"mysql_tzinfo_to_sql\"\n  in the server RPM.\n- The \"mysqlmanager\" man page got moved from section 1 to 8.\n\n* Thu Nov 30 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Call \"make install\" using \"benchdir_root=%%{_datadir}\",\n  because that is affecting the regression test suite as well.\n\n* Thu Nov 16 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Explicitly note that the \"MySQL-shared\" RPMs (as built by MySQL AB)\n  replace \"mysql-shared\" (as distributed by SuSE) to allow easy upgrading\n  (bug#22081).\n\n* Mon Nov 13 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Add \"--with-partition\" to all server builds.\n\n- Use \"--report-features\" in one test run per server build.\n\n* Tue Aug 15 2006 Joerg Bruehe <joerg@mysql.com>\n\n- The \"max\" server is removed from packages, effective from 5.1.12-beta.\n  Delete all steps to build, package, or install it.\n\n* Mon Jul 10 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Fix a typing error in the \"make\" target for the Perl script to run the tests.\n\n* Tue Jul 04 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Use the Perl script to run the tests, because it will automatically check\n  whether the server is configured with SSL.\n\n* Tue Jun 27 2006 Joerg Bruehe <joerg@mysql.com>\n\n- move \"mysqldumpslow\" from the client RPM to the server RPM (bug#20216)\n\n- Revert all previous attempts to call \"mysql_upgrade\" during RPM upgrade,\n  there are some more aspects which need to be solved before this is possible.\n  For now, just ensure the binary \"mysql_upgrade\" is delivered and installed.\n\n* Thu Jun 22 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Close a gap of the previous version by explicitly using\n  a newly created temporary directory for the socket to be used\n  in the \"mysql_upgrade\" operation, overriding any local setting.\n\n* Tue Jun 20 2006 Joerg Bruehe <joerg@mysql.com>\n\n- To run \"mysql_upgrade\", we need a running server;\n  start it in isolation and skip password checks.\n\n* Sat May 20 2006 Kent Boortz <kent@mysql.com>\n\n- Always compile for PIC, position independent code.\n\n* Wed May 10 2006 Kent Boortz <kent@mysql.com>\n\n- Use character set \"all\" when compiling with Cluster, to make Cluster\n  nodes independent on the character set directory, and the problem\n  that two RPM sub packages both wants to install this directory.\n\n* Mon May 01 2006 Kent Boortz <kent@mysql.com>\n\n- Use \"./libtool --mode=execute\" instead of searching for the\n  executable in current directory and \".libs\".\n\n* Fri Apr 28 2006 Kent Boortz <kent@mysql.com>\n\n- Install and run \"mysql_upgrade\"\n\n* Wed Apr 12 2006 Jim Winstead <jimw@mysql.com>\n\n- Remove sql-bench, and MySQL-bench RPM (will be built as an independent\n  project from the mysql-bench repository)\n\n* Tue Apr 11 2006 Jim Winstead <jimw@mysql.com>\n\n- Remove old mysqltestmanager and related programs\n* Sat Apr 01 2006 Kent Boortz <kent@mysql.com>\n\n- Set $LDFLAGS from $MYSQL_BUILD_LDFLAGS\n\n* Tue Mar 07 2006 Kent Boortz <kent@mysql.com>\n\n- Changed product name from \"Community Edition\" to \"Community Server\"\n\n* Mon Mar 06 2006 Kent Boortz <kent@mysql.com>\n\n- Fast mutexes is now disabled by default, but should be\n  used in Linux builds.\n\n* Mon Feb 20 2006 Kent Boortz <kent@mysql.com>\n\n- Reintroduced a max build\n- Limited testing of 'debug' and 'max' servers\n- Berkeley DB only in 'max'\n\n* Mon Feb 13 2006 Joerg Bruehe <joerg@mysql.com>\n\n- Use \"-i\" on \"make test-force\";\n  this is essential for later evaluation of this log file.\n\n* Thu Feb 09 2006 Kent Boortz <kent@mysql.com>\n\n- Pass '-static' to libtool, link static with our own libraries, dynamic\n  with system libraries.  Link with the bundled zlib.\n\n* Wed Feb 08 2006 Kristian Nielsen <knielsen@mysql.com>\n\n- Modified RPM spec to match new 5.1 debug+max combined community packaging.\n\n* Sun Dec 18 2005 Kent Boortz <kent@mysql.com>\n\n- Added \"client/mysqlslap\"\n\n* Mon Dec 12 2005 Rodrigo Novo <rodrigo@mysql.com>\n\n- Added zlib to the list of (static) libraries installed\n- Added check against libtool wierdness (WRT: sql/mysqld || sql/.libs/mysqld)\n- Compile MySQL with bundled zlib\n- Fixed %%packager name to \"MySQL Production Engineering Team\"\n\n* Mon Dec 05 2005 Joerg Bruehe <joerg@mysql.com>\n\n- Avoid using the \"bundled\" zlib on \"shared\" builds:\n  As it is not installed (on the build system), this gives dependency\n  problems with \"libtool\" causing the build to fail.\n  (Change was done on Nov 11, but left uncommented.)\n\n* Tue Nov 22 2005 Joerg Bruehe <joerg@mysql.com>\n\n- Extend the file existence check for \"init.d/mysql\" on un-install\n  to also guard the call to \"insserv\"/\"chkconfig\".\n\n* Thu Oct 27 2005 Lenz Grimmer <lenz@grimmer.com>\n\n- added more man pages\n\n* Wed Oct 19 2005 Kent Boortz <kent@mysql.com>\n\n- Made yaSSL support an option (off by default)\n\n* Wed Oct 19 2005 Kent Boortz <kent@mysql.com>\n\n- Enabled yaSSL support\n\n* Sat Oct 15 2005 Kent Boortz <kent@mysql.com>\n\n- Give mode arguments the same way in all places\n- Moved copy of mysqld.a to \"standard\" build, but\n  disabled it as we don't do embedded yet in 5.0\n\n* Fri Oct 14 2005 Kent Boortz <kent@mysql.com>\n\n- For 5.x, always compile with --with-big-tables\n- Copy the config.log file to location outside\n  the build tree\n\n* Fri Oct 14 2005 Kent Boortz <kent@mysql.com>\n\n- Removed unneeded/obsolete configure options\n- Added archive engine to standard server\n- Removed the embedded server from experimental server\n- Changed suffix \"-Max\" => \"-max\"\n- Changed comment string \"Max\" => \"Experimental\"\n\n* Thu Oct 13 2005 Lenz Grimmer <lenz@mysql.com>\n\n- added a usermod call to assign a potential existing mysql user to the\n  correct user group (BUG#12823)\n- Save the perror binary built during Max build so it supports the NDB\n  error codes (BUG#13740)\n- added a separate macro \"mysqld_group\" to be able to define the\n  user group of the mysql user seperately, if desired.\n\n* Thu Sep 29 2005 Lenz Grimmer <lenz@mysql.com>\n\n- fixed the removing of the RPM_BUILD_ROOT in the %clean section (the\n  $RBR variable did not get expanded, thus leaving old build roots behind)\n\n* Thu Aug 04 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Fixed the creation of the mysql user group account in the postinstall\n  section (BUG 12348)\n- Fixed enabling the Archive storage engine in the Max binary\n\n* Tue Aug 02 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Fixed the Requires: tag for the server RPM (BUG 12233)\n\n* Fri Jul 15 2005 Lenz Grimmer <lenz@mysql.com>\n\n- create a \"mysql\" user group and assign the mysql user account to that group\n  in the server postinstall section. (BUG 10984)\n\n* Tue Jun 14 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Do not build statically on i386 by default, only when adding either \"--with\n  static\" or \"--define '_with_static 1'\" to the RPM build options. Static\n  linking really only makes sense when linking against the specially patched\n  glibc 2.2.5.\n\n* Mon Jun 06 2005 Lenz Grimmer <lenz@mysql.com>\n\n- added mysql_client_test to the \"bench\" subpackage (BUG 10676)\n- added the libndbclient static and shared libraries (BUG 10676)\n\n* Wed Jun 01 2005 Lenz Grimmer <lenz@mysql.com>\n\n- use \"mysqldatadir\" variable instead of hard-coding the path multiple times\n- use the \"mysqld_user\" variable on all occasions a user name is referenced\n- removed (incomplete) Brazilian translations\n- removed redundant release tags from the subpackage descriptions\n\n* Wed May 25 2005 Joerg Bruehe <joerg@mysql.com>\n\n- Added a \"make clean\" between separate calls to \"BuildMySQL\".\n\n* Thu May 12 2005 Guilhem Bichot <guilhem@mysql.com>\n\n- Removed the mysql_tableinfo script made obsolete by the information schema\n\n* Wed Apr 20 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Enabled the \"blackhole\" storage engine for the Max RPM\n\n* Wed Apr 13 2005 Lenz Grimmer <lenz@mysql.com>\n\n- removed the MySQL manual files (html/ps/texi) - they have been removed\n  from the MySQL sources and are now available seperately.\n\n* Mon Apr 4 2005 Petr Chardin <petr@mysql.com>\n\n- old mysqlmanager, mysqlmanagerc and mysqlmanager-pwger renamed into\n  mysqltestmanager, mysqltestmanager and mysqltestmanager-pwgen respectively\n\n* Fri Mar 18 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Disabled RAID in the Max binaries once and for all (it has finally been\n  removed from the source tree)\n\n* Sun Feb 20 2005 Petr Chardin <petr@mysql.com>\n\n- Install MySQL Instance Manager together with mysqld, touch mysqlmanager\n  password file\n\n* Mon Feb 14 2005 Lenz Grimmer <lenz@mysql.com>\n\n- Fixed the compilation comments and moved them into the separate build sections\n  for Max and Standard\n\n* Mon Feb 7 2005 Tomas Ulin <tomas@mysql.com>\n\n- enabled the \"Ndbcluster\" storage engine for the max binary\n- added extra make install in ndb subdir after Max build to get ndb binaries\n- added packages for ndbcluster storage engine\n\n* Fri Jan 14 2005 Lenz Grimmer <lenz@mysql.com>\n\n- replaced obsoleted \"BuildPrereq\" with \"BuildRequires\" instead\n\n* Thu Jan 13 2005 Lenz Grimmer <lenz@mysql.com>\n\n- enabled the \"Federated\" storage engine for the max binary\n\n* Tue Jan 04 2005 Petr Chardin <petr@mysql.com>\n\n- ISAM and merge storage engines were purged. As well as appropriate\n  tools and manpages (isamchk and isamlog)\n\n* Fri Dec 31 2004 Lenz Grimmer <lenz@mysql.com>\n\n- enabled the \"Archive\" storage engine for the max binary\n- enabled the \"CSV\" storage engine for the max binary\n- enabled the \"Example\" storage engine for the max binary\n\n* Thu Aug 26 2004 Lenz Grimmer <lenz@mysql.com>\n\n- MySQL-Max now requires MySQL-server instead of MySQL (BUG 3860)\n\n* Fri Aug 20 2004 Lenz Grimmer <lenz@mysql.com>\n\n- do not link statically on IA64/AMD64 as these systems do not have\n  a patched glibc installed\n\n* Tue Aug 10 2004 Lenz Grimmer <lenz@mysql.com>\n\n- Added libmygcc.a to the devel subpackage (required to link applications\n  against the the embedded server libmysqld.a) (BUG 4921)\n\n* Mon Aug 09 2004 Lenz Grimmer <lenz@mysql.com>\n\n- Added EXCEPTIONS-CLIENT to the \"devel\" package\n\n* Thu Jul 29 2004 Lenz Grimmer <lenz@mysql.com>\n\n- disabled OpenSSL in the Max binaries again (the RPM packages were the\n  only exception to this anyway) (BUG 1043)\n\n* Wed Jun 30 2004 Lenz Grimmer <lenz@mysql.com>\n\n- fixed server postinstall (mysql_install_db was called with the wrong\n  parameter)\n\n* Thu Jun 24 2004 Lenz Grimmer <lenz@mysql.com>\n\n- added mysql_tzinfo_to_sql to the server subpackage\n- run \"make clean\" instead of \"make distclean\"\n\n* Mon Apr 05 2004 Lenz Grimmer <lenz@mysql.com>\n\n- added ncurses-devel to the build prerequisites (BUG 3377)\n\n* Thu Feb 12 2004 Lenz Grimmer <lenz@mysql.com>\n\n- when using gcc, _always_ use CXX=gcc\n- replaced Copyright with License field (Copyright is obsolete)\n\n* Tue Feb 03 2004 Lenz Grimmer <lenz@mysql.com>\n\n- added myisam_ftdump to the Server package\n\n* Tue Jan 13 2004 Lenz Grimmer <lenz@mysql.com>\n\n- link the mysql client against libreadline instead of libedit (BUG 2289)\n\n* Mon Dec 22 2003 Lenz Grimmer <lenz@mysql.com>\n\n- marked /etc/logrotate.d/mysql as a config file (BUG 2156)\n\n* Sat Dec 13 2003 Lenz Grimmer <lenz@mysql.com>\n\n- fixed file permissions (BUG 1672)\n\n* Thu Dec 11 2003 Lenz Grimmer <lenz@mysql.com>\n\n- made testing for gcc3 a bit more robust\n\n* Fri Dec 05 2003 Lenz Grimmer <lenz@mysql.com>\n\n- added missing file mysql_create_system_tables to the server subpackage\n\n* Fri Nov 21 2003 Lenz Grimmer <lenz@mysql.com>\n\n- removed dependency on MySQL-client from the MySQL-devel subpackage\n  as it is not really required. (BUG 1610)\n\n* Fri Aug 29 2003 Lenz Grimmer <lenz@mysql.com>\n\n- Fixed BUG 1162 (removed macro names from the changelog)\n- Really fixed BUG 998 (disable the checking for installed but\n  unpackaged files)\n\n* Tue Aug 05 2003 Lenz Grimmer <lenz@mysql.com>\n\n- Fixed BUG 959 (libmysqld not being compiled properly)\n- Fixed BUG 998 (RPM build errors): added missing files to the\n  distribution (mysql_fix_extensions, mysql_tableinfo, mysqldumpslow,\n  mysql_fix_privilege_tables.1), removed \"-n\" from install section.\n\n* Wed Jul 09 2003 Lenz Grimmer <lenz@mysql.com>\n\n- removed the GIF Icon (file was not included in the sources anyway)\n- removed unused variable shared_lib_version\n- do not run automake before building the standard binary\n  (should not be necessary)\n- add server suffix '-standard' to standard binary (to be in line\n  with the binary tarball distributions)\n- Use more RPM macros (_exec_prefix, _sbindir, _libdir, _sysconfdir,\n  _datadir, _includedir) throughout the spec file.\n- allow overriding CC and CXX (required when building with other compilers)\n\n* Fri May 16 2003 Lenz Grimmer <lenz@mysql.com>\n\n- re-enabled RAID again\n\n* Wed Apr 30 2003 Lenz Grimmer <lenz@mysql.com>\n\n- disabled MyISAM RAID (--with-raid) - it throws an assertion which\n  needs to be investigated first.\n\n* Mon Mar 10 2003 Lenz Grimmer <lenz@mysql.com>\n\n- added missing file mysql_secure_installation to server subpackage\n  (BUG 141)\n\n* Tue Feb 11 2003 Lenz Grimmer <lenz@mysql.com>\n\n- re-added missing pre- and post(un)install scripts to server subpackage\n- added config file /etc/my.cnf to the file list (just for completeness)\n- make sure to create the datadir with 755 permissions\n\n* Mon Jan 27 2003 Lenz Grimmer <lenz@mysql.com>\n\n- removed unused CC and CXX variables\n- CFLAGS and CXXFLAGS should honor RPM_OPT_FLAGS\n\n* Fri Jan 24 2003 Lenz Grimmer <lenz@mysql.com>\n\n- renamed package \"MySQL\" to \"MySQL-server\"\n- fixed Copyright tag\n- added mysql_waitpid to client subpackage (required for mysql-test-run)\n\n* Wed Nov 27 2002 Lenz Grimmer <lenz@mysql.com>\n\n- moved init script from /etc/rc.d/init.d to /etc/init.d (the majority of\n  Linux distributions now support this scheme as proposed by the LSB either\n  directly or via a compatibility symlink)\n- Use new \"restart\" init script action instead of starting and stopping\n  separately\n- Be more flexible in activating the automatic bootup - use insserv (on\n  older SuSE versions) or chkconfig (Red Hat, newer SuSE versions and\n  others) to create the respective symlinks\n\n* Wed Sep 25 2002 Lenz Grimmer <lenz@mysql.com>\n\n- MySQL-Max now requires MySQL >= 4.0 to avoid version mismatches\n  (mixing 3.23 and 4.0 packages)\n\n* Fri Aug 09 2002 Lenz Grimmer <lenz@mysql.com>\n\n- Turn off OpenSSL in MySQL-Max for now until it works properly again\n- enable RAID for the Max binary instead\n- added compatibility link: safe_mysqld -> mysqld_safe to ease the\n  transition from 3.23\n\n* Thu Jul 18 2002 Lenz Grimmer <lenz@mysql.com>\n\n- Reworked the build steps a little bit: the Max binary is supposed\n  to include OpenSSL, which cannot be linked statically, thus trying\n  to statically link against a special glibc is futile anyway\n- because of this, it is not required to make yet another build run\n  just to compile the shared libs (saves a lot of time)\n- updated package description of the Max subpackage\n- clean up the BuildRoot directory afterwards\n\n* Mon Jul 15 2002 Lenz Grimmer <lenz@mysql.com>\n\n- Updated Packager information\n- Fixed the build options: the regular package is supposed to\n  include InnoDB and linked statically, while the Max package\n  should include BDB and SSL support\n\n* Fri May 03 2002 Lenz Grimmer <lenz@mysql.com>\n\n- Use more RPM macros (e.g. infodir, mandir) to make the spec\n  file more portable\n- reorganized the installation of documentation files: let RPM\n  take care of this\n- reorganized the file list: actually install man pages along\n  with the binaries of the respective subpackage\n- do not include libmysqld.a in the devel subpackage as well, if we\n  have a special \"embedded\" subpackage\n- reworked the package descriptions\n\n* Mon Oct  8 2001 Monty\n\n- Added embedded server as a separate RPM\n\n* Fri Apr 13 2001 Monty\n\n- Added mysqld-max to the distribution\n\n* Tue Jan 2  2001  Monty\n\n- Added mysql-test to the bench package\n\n* Fri Aug 18 2000 Tim Smith <tim@mysql.com>\n\n- Added separate libmysql_r directory; now both a threaded\n  and non-threaded library is shipped.\n\n* Tue Sep 28 1999 David Axmark <davida@mysql.com>\n\n- Added the support-files/my-example.cnf to the docs directory.\n\n- Removed devel dependency on base since it is about client\n  development.\n\n* Wed Sep 8 1999 David Axmark <davida@mysql.com>\n\n- Cleaned up some for 3.23.\n\n* Thu Jul 1 1999 David Axmark <davida@mysql.com>\n\n- Added support for shared libraries in a separate sub\n  package. Original fix by David Fox (dsfox@cogsci.ucsd.edu)\n\n- The --enable-assembler switch is now automatically disables on\n  platforms there assembler code is unavailable. This should allow\n  building this RPM on non i386 systems.\n\n* Mon Feb 22 1999 David Axmark <david@detron.se>\n\n- Removed unportable cc switches from the spec file. The defaults can\n  now be overridden with environment variables. This feature is used\n  to compile the official RPM with optimal (but compiler version\n  specific) switches.\n\n- Removed the repetitive description parts for the sub rpms. Maybe add\n  again if RPM gets a multiline macro capability.\n\n- Added support for a pt_BR translation. Translation contributed by\n  Jorge Godoy <jorge@bestway.com.br>.\n\n* Wed Nov 4 1998 David Axmark <david@detron.se>\n\n- A lot of changes in all the rpm and install scripts. This may even\n  be a working RPM :-)\n\n* Sun Aug 16 1998 David Axmark <david@detron.se>\n\n- A developers changelog for MySQL is available in the source RPM. And\n  there is a history of major user visible changed in the Reference\n  Manual.  Only RPM specific changes will be documented here.\n", "num_lines": 2104}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# A simple startup script for mysqld_multi by Tim Smith and Jani Tolonen.\n# This script assumes that my.cnf file exists either in /etc/my.cnf or\n# /root/.my.cnf and has groups [mysqld_multi] and [mysqldN]. See the\n# mysqld_multi documentation for detailed instructions.\n#\n# This script can be used as /etc/init.d/mysql.server\n#\n# Comments to support chkconfig on RedHat Linux\n# chkconfig: 2345 64 36\n# description: A very fast and reliable SQL database engine.\n#\n# Version 1.0\n#\n\nbasedir=/usr/local/mysql\nbindir=/usr/local/mysql/bin\n\nif test -x $bindir/mysqld_multi\nthen\n  mysqld_multi=\"$bindir/mysqld_multi\";\nelse\n  echo \"Can't execute $bindir/mysqld_multi from dir $basedir\";\n  exit;\nfi\n\ncase \"$1\" in\n    'start' )\n        \"$mysqld_multi\" start $2\n        ;;\n    'stop' )\n        \"$mysqld_multi\" stop $2\n        ;;\n    'report' )\n        \"$mysqld_multi\" report $2\n        ;;\n    'restart' )\n        \"$mysqld_multi\" stop $2\n        \"$mysqld_multi\" start $2\n        ;;\n    *)\n        echo \"Usage: $0 {start|stop|report|restart}\" >&2\n        ;;\nesac\n", "num_lines": 46}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>IFPkgDescriptionDeleteWarning</key>\n\t<string></string>\n\t<key>IFPkgDescriptionDescription</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>\n\t<key>IFPkgDescriptionTitle</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>\n\t<key>IFPkgDescriptionVersion</key>\n\t<string>@VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t</dict>\n</plist>\n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003, 2008 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleGetInfoString</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>com.mysql.mysql</string>\n\t<key>CFBundleName</key>\n\t<string>MySQL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>@MYSQL_NUMERIC_VERSION@</string>\n\t<key>IFPkgFlagAllowBackRev</key>\n\t<false/>\n\t<key>IFPkgFlagAuthorizationAction</key>\n\t<string>RootAuthorization</string>\n\t<key>IFPkgFlagDefaultLocation</key>\n\t<string>/usr/local</string>\n\t<key>IFPkgFlagInstallFat</key>\n\t<false/>\n\t<key>IFPkgFlagIsRequired</key>\n\t<false/>\n\t<key>IFPkgFlagRelocatable</key>\n\t<false/>\n\t<key>IFPkgFlagRestartAction</key>\n\t<string>NoRestart</string>\n\t<key>IFPkgFlagRootVolumeOnly</key>\n\t<true/>\n\t<key>IFPkgFlagUpdateInstalledLanguages</key>\n\t<false/>\n\t<key>IFPkgFormatVersion</key>\n\t<real>0.10000000149011612</real>\n</dict>\n</plist>\n", "num_lines": 52}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# postflight - this script will be executed after the MySQL PKG\n# installation has been performed.\n#\n# This script will install the MySQL privilege tables using the\n# \"mysql_install_db\" script and will correct the ownerships of these files\n# afterwards.\n#\n\nif cd @prefix@ ; then\n\tif [ ! -f data/mysql/db.frm ] ; then\n\t\t./scripts/mysql_install_db --rpm\n\tfi\n\n\tif [ -d data ] ; then\n\t\tchown -R @MYSQLD_USER@ data\n\tfi\nelse\n\texit $?\nfi\n", "num_lines": 41}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# preflight - this script will be executed before the MySQL PKG\n# installation will be performed.\n#\n# If this package has been compiled with a prefix ending with \"mysql\" (e.g.\n# /usr/local/mysql or /opt/mysql), it will rename any previously existing\n# directory with this name before installing the new package (which includes\n# a symlink named \"mysql\", pointing to the newly installed directory, which\n# is named mysql-<version>)\n#\n\nPREFIX=\"@prefix@\"\nBASENAME=`basename $PREFIX`\n\nif [ -d $PREFIX -a ! -L $PREFIX -a $BASENAME = \"mysql\" ] ; then\n\tmv $PREFIX $PREFIX.bak\nfi\n", "num_lines": 38}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>Description</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t<key>OrderPreference</key>\n\t<string>None</string>\n\t<key>Provides</key>\n\t<array>\n\t\t<string>MySQL</string>\n\t</array>\n\t<key>Uses</key>\n\t<array>\n\t\t<string>Network</string>\n\t\t<string>Resolver</string>\n\t</array>\n\t</dict>\n</plist>\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Backup script for MySQL 5.5 on RHEL5 using XtraBackup\n#\n# Requires: xtrabackup, bash, awk, coreutils\n#\n# Copyright (C) 2011 Daniel van Eeden\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 2 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n## Settings ##\nPATH=\"/bin:/usr/bin\"\nBACKUPDIR=\"/var/mysql/backups/xtrabackup\"\nMINFREE_M=\"5000\"\nINNOBACKUPEX_OPTIONS=\"\"\nRETENTION_DAYS=\"7\"\n\n## Logic ##\ntimestamp=`date +%Y%m%d_%H%M%S_%Z`\nexport PATH;\n\nif [ ! -x \"/usr/bin/innobackupex-1.5.1\" ]; then\n  echo \"ERROR: /usr/bin/innobackupex-1.5.1 is not executable.\"\n  exit 1\nfi \n\nif [ ! -d ${BACKUPDIR} ]; then\n  echo \"ERROR: ${BACKUPDIR} is not a directory.\"\n  exit 2\nfi\n\nfreespace_m=`df -k ${BACKUPDIR} | awk '{ if ($4 ~ /^[0-9]*$/) { print int($4/1024) } }'`\nif [ ${freespace_m} -le ${MINFREE_M} ]; then\n  echo \"ERROR: There is less than ${MINFREE_M} MB of free space on ${BACKUPDIR}\"\n  exit 3\nfi\n\n# Remove backups older than $RETENTION_DAYS\nfind /var/mysql/backups/xtrabackup -name \"*_*_*_xtrabackup\\.tar\\.bz2\" -type f -mtime +${RETENTION_DAYS}\n\n# Create the backup\n/usr/bin/innobackupex-1.5.1 ${INNOBACKUPEX_OPTIONS} --stream=tar /tmp 2> ${BACKUPDIR}/${timestamp}_xtrabackup.log | bzip2 > ${BACKUPDIR}/${timestamp}_xtrabackup.tar.bz2\n", "num_lines": 53}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nPATH=/usr/local/gnu-autotools/bin/:$PATH\nexport PATH\n\n# Start from one level above the build directory\nif [ -f version ]; then\n    cd ..\nfi\n\nif [ \\! -f build/version ]; then\n    echo \"Can't find source directory\"\n    exit 1\nfi\n\n# BSD make's \"OBJDIR\" support freaks out the automake-generated\n# Makefile.  Effectively disable it.\nexport MAKEOBJDIRPREFIX=/junk\n\n# Start from the build directory, where the version file is located\nif [ -f build/version ]; then\n    cd build\nfi\n\nif [ \\! -f version ]; then\n    echo \"Can't find version file\"\n    exit 1\nfi\n\n# Update the build number in the 'version' file.\n# Separate number from additional alpha/beta/etc marker\nMARKER=`cat version | sed 's/[0-9.]//g'`\n# Bump the number\nVN=`cat version | sed 's/[^0-9.]//g'`\n# Build out the string.\nVS=\"$(($VN/1000000)).$(( ($VN/1000)%1000 )).$(( $VN%1000 ))$MARKER\"\n\ncd ..\n\n# Clean up the source dir as much as we can.\n/bin/sh build/clean.sh\n\n# Substitute the integer version into Libarchive's archive.h\nperl -p -i -e \"s/^(#define\\tARCHIVE_VERSION_NUMBER).*/\\$1 $VN/\" libarchive/archive.h\nperl -p -i -e \"s/^(#define\\tARCHIVE_VERSION_STRING).*/\\$1 \\\"libarchive $VS\\\"/\" libarchive/archive.h\n# Substitute versions into configure.ac as well\nperl -p -i -e 's/(m4_define\\(\\[LIBARCHIVE_VERSION_S\\]),.*\\)/$1,['\"$VS\"'])/' configure.ac\nperl -p -i -e 's/(m4_define\\(\\[LIBARCHIVE_VERSION_N\\]),.*\\)/$1,['\"$VN\"'])/' configure.ac\n\nset -xe\naclocal -I build/autoconf\n\n# Note: --automake flag needed only for libtoolize from\n# libtool 1.5.x; in libtool 2.2.x it is a synonym for --quiet\ncase `uname` in\nDarwin) glibtoolize --automake -c;;\n*) libtoolize --automake -c;;\nesac\nautoconf\nautoheader\nautomake -a -c\n\n./configure\nmake distcheck\nmake dist-zip", "num_lines": 65}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh +v\n\n# Start from the build directory, where the version file is located\nif [ -f build/version ]; then\n    cd build\nfi\n\nif [ \\! -f version ]; then\n    echo \"Can't find version file\"\n    exit 1\nfi\n\n# Update the build number in the 'version' file.\n# Separate number from additional alpha/beta/etc marker\nMARKER=`cat version | sed 's/[0-9.]//g'`\n# Bump the number\nVN=`cat version | sed 's/[^0-9.]//g'`\n# Reassemble and write back out\nVN=$(($VN + 1))\nrm -f version.old\nmv version version.old\nchmod +w version.old\necho $VN$MARKER > version\nVS=\"$(($VN/1000000)).$(( ($VN/1000)%1000 )).$(( $VN%1000 ))$MARKER\"\ncd ..\n\nANNOUNCE=`date +\"%b %d, %Y:\"`\" libarchive $VS released\"\n\necho $ANNOUNCE\n\n# Add a version notice to NEWS\nmv NEWS NEWS.bak\nchmod +w NEWS.bak\necho > NEWS\necho $ANNOUNCE >> NEWS\ncat NEWS.bak >> NEWS\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \\! -f build/version ]; then\n    echo 'Must run the clean script from the top-level dir of the libarchive distribution' 1>&2\n    exit 1\nfi\n\n#\n# The automake-generated 'maintainer-clean' target does clean up a\n# lot.  If that fails, try plain 'clean' in case we're using the cmake\n# or other makefile.  But don't worry if we can't...\n#\nmake maintainer-clean || make clean || true\n\n# If we're on BSD, blow away the build dir under /usr/obj\nrm -rf /usr/obj`pwd`\n\n#\n# Try to clean up a bit more...\n#\n\nfind . -name '*.So' | xargs rm\nfind . -name '*.a' | xargs rm\nfind . -name '*.la' | xargs rm\nfind . -name '*.lo' | xargs rm\nfind . -name '*.o' | xargs rm\nfind . -name '*.orig' | xargs rm\nfind . -name '*.po' | xargs rm\nfind . -name '*.rej' | xargs rm\nfind . -name '*~' | xargs rm\nfind . -name '.depend' | xargs rm\nfind . -name '.deps' | xargs rm -rf\nfind . -name '.dirstamp' | xargs rm\nfind . -name '.libs' | xargs rm -rf\n\nrm -rf autom4te.cache\n\nrm -f Makefile.in\nrm -f aclocal.m4\nrm -f bsdcpio\nrm -f bsdcpio_test\nrm -f bsdtar\nrm -f bsdtar_test\nrm -f build/autoconf/compile\nrm -f build/autoconf/config.*\nrm -f build/autoconf/depcomp\nrm -f build/autoconf/install-sh\nrm -f build/autoconf/libtool.m4\nrm -f build/autoconf/ltmain.sh\nrm -f build/autoconf/ltoptions.m4\nrm -f build/autoconf/ltsugar.m4\nrm -f build/autoconf/ltversion.m4\nrm -f build/autoconf/lt~obsolete.m4\nrm -f build/autoconf/missing\nrm -f build/pkgconfig/libarchive.pc\nrm -f build/version.old\nrm -f config.h\nrm -f config.h.in\nrm -f config.log\nrm -f config.status\nrm -f configure\nrm -f cpio/*.1.gz\nrm -f cpio/bsdcpio\nrm -f cpio/test/bsdcpio_test\nrm -f cpio/test/list.h\nrm -f doc/html/*\nrm -f doc/man/*\nrm -f doc/pdf/*\nrm -f doc/text/*\nrm -f doc/wiki/*\nrm -f libarchive/*.[35].gz\nrm -f libarchive/libarchive.so*\nrm -f libarchive/test/libarchive_test\nrm -f libarchive/test/list.h\nrm -f libarchive_test\nrm -f libtool\nrm -f stamp-h1\nrm -f tar/*.1.gz\nrm -f tar/bsdtar\nrm -f tar/test/bsdtar_test\nrm -f tar/test/list.h\n", "num_lines": 82}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "\n# libtool (GNU libtool) 2.4.2\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006,\n# 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GNU Libtool; see the file COPYING.  If not, a copy\n# can be downloaded from http://www.gnu.org/licenses/gpl.html,\n# or obtained by writing to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n# Usage: $progname [OPTION]... [MODE-ARG]...\n#\n# Provide generalized library-building support services.\n#\n#       --config             show all configuration variables\n#       --debug              enable verbose shell tracing\n#   -n, --dry-run            display commands without modifying any files\n#       --features           display basic configuration information and exit\n#       --mode=MODE          use operation mode MODE\n#       --preserve-dup-deps  don't remove duplicate dependency libraries\n#       --quiet, --silent    don't print informational messages\n#       --no-quiet, --no-silent\n#                            print informational messages (default)\n#       --no-warn            don't display warning messages\n#       --tag=TAG            use configuration variables from tag TAG\n#   -v, --verbose            print more informational messages than default\n#       --no-verbose         don't print the extra informational messages\n#       --version            print version information\n#   -h, --help, --help-all   print short, long, or detailed help message\n#\n# MODE must be one of the following:\n#\n#         clean              remove files from the build directory\n#         compile            compile a source file into a libtool object\n#         execute            automatically set library path, then run a program\n#         finish             complete the installation of libtool libraries\n#         install            install libraries or executables\n#         link               create a library or an executable\n#         uninstall          remove libraries from an installed directory\n#\n# MODE-ARGS vary depending on the MODE.  When passed as first option,\n# `--mode=MODE' may be abbreviated as `MODE' or a unique abbreviation of that.\n# Try `$progname --help --mode=MODE' for a more detailed description of MODE.\n#\n# When reporting a bug, please describe a test case to reproduce it and\n# include the following information:\n#\n#         host-triplet:\t$host\n#         shell:\t\t$SHELL\n#         compiler:\t\t$LTCC\n#         compiler flags:\t\t$LTCFLAGS\n#         linker:\t\t$LD (gnu? $with_gnu_ld)\n#         $progname:\t(GNU libtool) 2.4.2\n#         automake:\t$automake_version\n#         autoconf:\t$autoconf_version\n#\n# Report bugs to <bug-libtool@gnu.org>.\n# GNU libtool home page: <http://www.gnu.org/software/libtool/>.\n# General help using GNU software: <http://www.gnu.org/gethelp/>.\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=2.4.2\nTIMESTAMP=\"\"\npackage_revision=1.3337\n\n# Be Bourne compatible\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# NLS nuisances: We save the old values to restore during execute mode.\nlt_user_locale=\nlt_safe_locale=\nfor lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test \\\"\\${$lt_var+set}\\\" = set; then\n          save_$lt_var=\\$$lt_var\n          $lt_var=C\n\t  export $lt_var\n\t  lt_user_locale=\\\"$lt_var=\\\\\\$save_\\$lt_var; \\$lt_user_locale\\\"\n\t  lt_safe_locale=\\\"$lt_var=C; \\$lt_safe_locale\\\"\n\tfi\"\ndone\nLC_ALL=C\nLANGUAGE=C\nexport LANGUAGE LC_ALL\n\n$lt_unset CDPATH\n\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=\"$0\"\n\n\n\n: ${CP=\"cp -f\"}\ntest \"${ECHO+set}\" = set || ECHO=${as_echo-'printf %s\\n'}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n: ${Xsed=\"$SED -e 1s/^X//\"}\n\n# Global variables:\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\nexit_status=$EXIT_SUCCESS\n\n# Make sure IFS has a sensible default\nlt_nl='\n'\nIFS=\" \t$lt_nl\"\n\ndirname=\"s,/[^/]*$,,\"\nbasename=\"s,^.*/,,\"\n\n# func_dirname file append nondir_replacement\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\nfunc_dirname ()\n{\n    func_dirname_result=`$ECHO \"${1}\" | $SED \"$dirname\"`\n    if test \"X$func_dirname_result\" = \"X${1}\"; then\n      func_dirname_result=\"${3}\"\n    else\n      func_dirname_result=\"$func_dirname_result${2}\"\n    fi\n} # func_dirname may be replaced by extended shell implementation\n\n\n# func_basename file\nfunc_basename ()\n{\n    func_basename_result=`$ECHO \"${1}\" | $SED \"$basename\"`\n} # func_basename may be replaced by extended shell implementation\n\n\n# func_dirname_and_basename file append nondir_replacement\n# perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# Implementation must be kept synchronized with func_dirname\n# and func_basename. For efficiency, we do not delegate to\n# those functions but instead duplicate the functionality here.\nfunc_dirname_and_basename ()\n{\n    # Extract subdirectory from the argument.\n    func_dirname_result=`$ECHO \"${1}\" | $SED -e \"$dirname\"`\n    if test \"X$func_dirname_result\" = \"X${1}\"; then\n      func_dirname_result=\"${3}\"\n    else\n      func_dirname_result=\"$func_dirname_result${2}\"\n    fi\n    func_basename_result=`$ECHO \"${1}\" | $SED -e \"$basename\"`\n} # func_dirname_and_basename may be replaced by extended shell implementation\n\n\n# func_stripname prefix suffix name\n# strip PREFIX and SUFFIX off of NAME.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\n# func_strip_suffix prefix name\nfunc_stripname ()\n{\n    case ${2} in\n      .*) func_stripname_result=`$ECHO \"${3}\" | $SED \"s%^${1}%%; s%\\\\\\\\${2}\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"${3}\" | $SED \"s%^${1}%%; s%${2}\\$%%\"`;;\n    esac\n} # func_stripname may be replaced by extended shell implementation\n\n\n# These SED scripts presuppose an absolute path with a trailing slash.\npathcar='s,^/\\([^/]*\\).*$,\\1,'\npathcdr='s,^/[^/]*,,'\nremovedotparts=':dotsl\n\t\ts@/\\./@/@g\n\t\tt dotsl\n\t\ts,/\\.$,/,'\ncollapseslashes='s@/\\{1,\\}@/@g'\nfinalslash='s,/*$,/,'\n\n# func_normal_abspath PATH\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\n#             value returned in \"$func_normal_abspath_result\"\nfunc_normal_abspath ()\n{\n  # Start from root dir and reassemble the path.\n  func_normal_abspath_result=\n  func_normal_abspath_tpath=$1\n  func_normal_abspath_altnamespace=\n  case $func_normal_abspath_tpath in\n    \"\")\n      # Empty path, that just means $cwd.\n      func_stripname '' '/' \"`pwd`\"\n      func_normal_abspath_result=$func_stripname_result\n      return\n    ;;\n    # The next three entries are used to spot a run of precisely\n    # two leading slashes without using negated character classes;\n    # we take advantage of case's first-match behaviour.\n    ///*)\n      # Unusual form of absolute path, do nothing.\n    ;;\n    //*)\n      # Not necessarily an ordinary path; POSIX reserves leading '//'\n      # and for example Cygwin uses it to access remote file shares\n      # over CIFS/SMB, so we conserve a leading double slash if found.\n      func_normal_abspath_altnamespace=/\n    ;;\n    /*)\n      # Absolute path, do nothing.\n    ;;\n    *)\n      # Relative path, prepend $cwd.\n      func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n    ;;\n  esac\n  # Cancel out all the simple stuff to save iterations.  We also want\n  # the path to end with a slash for ease of parsing, so make sure\n  # there is one (and only one) here.\n  func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n        -e \"$removedotparts\" -e \"$collapseslashes\" -e \"$finalslash\"`\n  while :; do\n    # Processed it all yet?\n    if test \"$func_normal_abspath_tpath\" = / ; then\n      # If we ascended to the root using \"..\" the result may be empty now.\n      if test -z \"$func_normal_abspath_result\" ; then\n        func_normal_abspath_result=/\n      fi\n      break\n    fi\n    func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n        -e \"$pathcar\"`\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n        -e \"$pathcdr\"`\n    # Figure out what to do with it\n    case $func_normal_abspath_tcomponent in\n      \"\")\n        # Trailing empty path component, ignore it.\n      ;;\n      ..)\n        # Parent dir; strip last assembled component from result.\n        func_dirname \"$func_normal_abspath_result\"\n        func_normal_abspath_result=$func_dirname_result\n      ;;\n      *)\n        # Actual path component, append it.\n        func_normal_abspath_result=$func_normal_abspath_result/$func_normal_abspath_tcomponent\n      ;;\n    esac\n  done\n  # Restore leading double-slash if one was found on entry.\n  func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n# func_relative_path SRCDIR DSTDIR\n# generates a relative path from SRCDIR to DSTDIR, with a trailing\n# slash if non-empty, suitable for immediately appending a filename\n# without needing to append a separator.\n#             value returned in \"$func_relative_path_result\"\nfunc_relative_path ()\n{\n  func_relative_path_result=\n  func_normal_abspath \"$1\"\n  func_relative_path_tlibdir=$func_normal_abspath_result\n  func_normal_abspath \"$2\"\n  func_relative_path_tbindir=$func_normal_abspath_result\n\n  # Ascend the tree starting from libdir\n  while :; do\n    # check if we have found a prefix of bindir\n    case $func_relative_path_tbindir in\n      $func_relative_path_tlibdir)\n        # found an exact match\n        func_relative_path_tcancelled=\n        break\n        ;;\n      $func_relative_path_tlibdir*)\n        # found a matching prefix\n        func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n        func_relative_path_tcancelled=$func_stripname_result\n        if test -z \"$func_relative_path_result\"; then\n          func_relative_path_result=.\n        fi\n        break\n        ;;\n      *)\n        func_dirname $func_relative_path_tlibdir\n        func_relative_path_tlibdir=${func_dirname_result}\n        if test \"x$func_relative_path_tlibdir\" = x ; then\n          # Have to descend all the way to the root!\n          func_relative_path_result=../$func_relative_path_result\n          func_relative_path_tcancelled=$func_relative_path_tbindir\n          break\n        fi\n        func_relative_path_result=../$func_relative_path_result\n        ;;\n    esac\n  done\n\n  # Now calculate path; take care to avoid doubling-up slashes.\n  func_stripname '' '/' \"$func_relative_path_result\"\n  func_relative_path_result=$func_stripname_result\n  func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n  if test \"x$func_stripname_result\" != x ; then\n    func_relative_path_result=${func_relative_path_result}/${func_stripname_result}\n  fi\n\n  # Normalisation. If bindir is libdir, return empty string,\n  # else relative path ending with a slash; either way, target\n  # file name can be directly appended.\n  if test ! -z \"$func_relative_path_result\"; then\n    func_stripname './' '' \"$func_relative_path_result/\"\n    func_relative_path_result=$func_stripname_result\n  fi\n}\n\n# The name of this program:\nfunc_dirname_and_basename \"$progpath\"\nprogname=$func_basename_result\n\n# Make sure we have an absolute path for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=$func_dirname_result\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=\"$progdir/$progname\"\n     ;;\n  *)\n     save_IFS=\"$IFS\"\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=\"$save_IFS\"\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=\"$save_IFS\"\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=\"$progdir/$progname\"\n     ;;\nesac\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nXsed=\"${SED}\"' -e 1s/^X//'\nsed_quote_subst='s/\\([`\"$\\\\]\\)/\\\\\\1/g'\n\n# Same as above, but do not quote variable references.\ndouble_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s,[].[^$\\\\*\\/],\\\\&,g'\n\n# Sed substitution that converts a w32 file name or path\n# which contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nlt_sed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-`\\' parameter expansions in output of double_quote_subst that were\n# `\\'-ed in input to the same.  If an odd number of `\\' preceded a '$'\n# in input to double_quote_subst, that '$' was protected from expansion.\n# Since each input `\\' is now two `\\'s, look for any number of runs of\n# four `\\'s followed by two `\\'s and then a '$'.  `\\' that '$'.\nbs='\\\\'\nbs2='\\\\\\\\'\nbs4='\\\\\\\\\\\\\\\\'\ndollar='\\$'\nsed_double_backslash=\"\\\n  s/$bs4/&\\\\\n/g\n  s/^$bs2$dollar/$bs&/\n  s/\\\\([^$bs]\\\\)$bs2$dollar/\\\\1$bs2$bs$dollar/g\n  s/\\n//g\"\n\n# Standard options:\nopt_dry_run=false\nopt_help=false\nopt_quiet=false\nopt_verbose=false\nopt_warning=:\n\n# func_echo arg...\n# Echo program name prefixed message, along with the current mode\n# name if it has been set yet.\nfunc_echo ()\n{\n    $ECHO \"$progname: ${opt_mode+$opt_mode: }$*\"\n}\n\n# func_verbose arg...\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $opt_verbose && func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n# func_echo_all arg...\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n# func_error arg...\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $ECHO \"$progname: ${opt_mode+$opt_mode: }\"${1+\"$@\"} 1>&2\n}\n\n# func_warning arg...\n# Echo program name prefixed warning message to standard error.\nfunc_warning ()\n{\n    $opt_warning && $ECHO \"$progname: ${opt_mode+$opt_mode: }warning: \"${1+\"$@\"} 1>&2\n\n    # bash bug again:\n    :\n}\n\n# func_fatal_error arg...\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n# func_fatal_help arg...\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    func_error ${1+\"$@\"}\n    func_fatal_error \"$help\"\n}\nhelp=\"Try \\`$progname --help' for more information.\"  ## default\n\n\n# func_grep expression filename\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_mkdir_p directory-path\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    my_directory_path=\"$1\"\n    my_dir_list=\n\n    if test -n \"$my_directory_path\" && test \"$opt_dry_run\" != \":\"; then\n\n      # Protect directory names starting with `-'\n      case $my_directory_path in\n        -*) my_directory_path=\"./$my_directory_path\" ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$my_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        my_dir_list=\"$my_directory_path:$my_dir_list\"\n\n        # If the last portion added has no slash in it, the list is done\n        case $my_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        my_directory_path=`$ECHO \"$my_directory_path\" | $SED -e \"$dirname\"`\n      done\n      my_dir_list=`$ECHO \"$my_dir_list\" | $SED 's,:*$,,'`\n\n      save_mkdir_p_IFS=\"$IFS\"; IFS=':'\n      for my_dir in $my_dir_list; do\n\tIFS=\"$save_mkdir_p_IFS\"\n        # mkdir can fail with a `File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$my_dir\" 2>/dev/null || :\n      done\n      IFS=\"$save_mkdir_p_IFS\"\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$my_directory_path\" || \\\n        func_fatal_error \"Failed to create \\`$1'\"\n    fi\n}\n\n\n# func_mktempdir [string]\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, STRING is the basename for that directory.\nfunc_mktempdir ()\n{\n    my_template=\"${TMPDIR-/tmp}/${1-$progname}\"\n\n    if test \"$opt_dry_run\" = \":\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      my_tmpdir=\"${my_template}-$$\"\n    else\n\n      # If mktemp works, use that first and foremost\n      my_tmpdir=`mktemp -d \"${my_template}-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$my_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        my_tmpdir=\"${my_template}-${RANDOM-0}$$\"\n\n        save_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$my_tmpdir\"\n        umask $save_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$my_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory \\`$my_tmpdir'\"\n    fi\n\n    $ECHO \"$my_tmpdir\"\n}\n\n\n# func_quote_for_eval arg\n# Aesthetically quote ARG to be evaled later.\n# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT\n# is double-quoted, suitable for a subsequent eval, whereas\n# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters\n# which are still active within double quotes backslashified.\nfunc_quote_for_eval ()\n{\n    case $1 in\n      *[\\\\\\`\\\"\\$]*)\n\tfunc_quote_for_eval_unquoted_result=`$ECHO \"$1\" | $SED \"$sed_quote_subst\"` ;;\n      *)\n        func_quote_for_eval_unquoted_result=\"$1\" ;;\n    esac\n\n    case $func_quote_for_eval_unquoted_result in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting, command substitution and and variable\n      # expansion for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        func_quote_for_eval_result=\"\\\"$func_quote_for_eval_unquoted_result\\\"\"\n        ;;\n      *)\n        func_quote_for_eval_result=\"$func_quote_for_eval_unquoted_result\"\n    esac\n}\n\n\n# func_quote_for_expand arg\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\tmy_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        my_arg=\"$1\" ;;\n    esac\n\n    case $my_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        my_arg=\"\\\"$my_arg\\\"\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=\"$my_arg\"\n}\n\n\n# func_show_eval cmd [fail_exp]\n# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    my_cmd=\"$1\"\n    my_fail_exp=\"${2-:}\"\n\n    ${opt_silent-false} || {\n      func_quote_for_expand \"$my_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    if ${opt_dry_run-false}; then :; else\n      eval \"$my_cmd\"\n      my_status=$?\n      if test \"$my_status\" -eq 0; then :; else\n\teval \"(exit $my_status); $my_fail_exp\"\n      fi\n    fi\n}\n\n\n# func_show_eval_locale cmd [fail_exp]\n# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    my_cmd=\"$1\"\n    my_fail_exp=\"${2-:}\"\n\n    ${opt_silent-false} || {\n      func_quote_for_expand \"$my_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    if ${opt_dry_run-false}; then :; else\n      eval \"$lt_user_locale\n\t    $my_cmd\"\n      my_status=$?\n      eval \"$lt_safe_locale\"\n      if test \"$my_status\" -eq 0; then :; else\n\teval \"(exit $my_status); $my_fail_exp\"\n      fi\n    fi\n}\n\n# func_tr_sh\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n  case $1 in\n  [0-9]* | *[!a-zA-Z0-9_]*)\n    func_tr_sh_result=`$ECHO \"$1\" | $SED 's/^\\([0-9]\\)/_\\1/; s/[^a-zA-Z0-9_]/_/g'`\n    ;;\n  * )\n    func_tr_sh_result=$1\n    ;;\n  esac\n}\n\n\n# func_version\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $opt_debug\n\n    $SED -n '/(C)/!b go\n\t:more\n\t/\\./!{\n\t  N\n\t  s/\\n# / /\n\t  b more\n\t}\n\t:go\n\t/^# '$PROGRAM' (GNU /,/# warranty; / {\n        s/^# //\n\ts/^# *$//\n        s/\\((C)\\)[ 0-9,-]*\\( [1-9][0-9]*\\)/\\1\\2/\n        p\n     }' < \"$progpath\"\n     exit $?\n}\n\n# func_usage\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $opt_debug\n\n    $SED -n '/^# Usage:/,/^#  *.*--help/ {\n        s/^# //\n\ts/^# *$//\n\ts/\\$progname/'$progname'/\n\tp\n    }' < \"$progpath\"\n    echo\n    $ECHO \"run \\`$progname --help | more' for full usage\"\n    exit $?\n}\n\n# func_help [NOEXIT]\n# Echo long help message to standard output and exit,\n# unless 'noexit' is passed as argument.\nfunc_help ()\n{\n    $opt_debug\n\n    $SED -n '/^# Usage:/,/# Report bugs to/ {\n\t:print\n        s/^# //\n\ts/^# *$//\n\ts*\\$progname*'$progname'*\n\ts*\\$host*'\"$host\"'*\n\ts*\\$SHELL*'\"$SHELL\"'*\n\ts*\\$LTCC*'\"$LTCC\"'*\n\ts*\\$LTCFLAGS*'\"$LTCFLAGS\"'*\n\ts*\\$LD*'\"$LD\"'*\n\ts/\\$with_gnu_ld/'\"$with_gnu_ld\"'/\n\ts/\\$automake_version/'\"`(${AUTOMAKE-automake} --version) 2>/dev/null |$SED 1q`\"'/\n\ts/\\$autoconf_version/'\"`(${AUTOCONF-autoconf} --version) 2>/dev/null |$SED 1q`\"'/\n\tp\n\td\n     }\n     /^# .* home page:/b print\n     /^# General help using/b print\n     ' < \"$progpath\"\n    ret=$?\n    if test -z \"$1\"; then\n      exit $ret\n    fi\n}\n\n# func_missing_arg argname\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $opt_debug\n\n    func_error \"missing argument for $1.\"\n    exit_cmd=exit\n}\n\n\n# func_split_short_opt shortopt\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nfunc_split_short_opt ()\n{\n    my_sed_short_opt='1s/^\\(..\\).*$/\\1/;q'\n    my_sed_short_rest='1s/^..\\(.*\\)$/\\1/;q'\n\n    func_split_short_opt_name=`$ECHO \"$1\" | $SED \"$my_sed_short_opt\"`\n    func_split_short_opt_arg=`$ECHO \"$1\" | $SED \"$my_sed_short_rest\"`\n} # func_split_short_opt may be replaced by extended shell implementation\n\n\n# func_split_long_opt longopt\n# Set func_split_long_opt_name and func_split_long_opt_arg shell\n# variables after splitting LONGOPT at the `=' sign.\nfunc_split_long_opt ()\n{\n    my_sed_long_opt='1s/^\\(--[^=]*\\)=.*/\\1/;q'\n    my_sed_long_arg='1s/^--[^=]*=//'\n\n    func_split_long_opt_name=`$ECHO \"$1\" | $SED \"$my_sed_long_opt\"`\n    func_split_long_opt_arg=`$ECHO \"$1\" | $SED \"$my_sed_long_arg\"`\n} # func_split_long_opt may be replaced by extended shell implementation\n\nexit_cmd=:\n\n\n\n\n\nmagic=\"%%%MAGIC variable%%%\"\nmagic_exe=\"%%%MAGIC EXE variable%%%\"\n\n# Global variables.\nnonopt=\npreserve_args=\nlo2o=\"s/\\\\.lo\\$/.${objext}/\"\no2lo=\"s/\\\\.${objext}\\$/.lo/\"\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n# func_append var value\n# Append VALUE to the end of shell variable VAR.\nfunc_append ()\n{\n    eval \"${1}=\\$${1}\\${2}\"\n} # func_append may be replaced by extended shell implementation\n\n# func_append_quoted var value\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nfunc_append_quoted ()\n{\n    func_quote_for_eval \"${2}\"\n    eval \"${1}=\\$${1}\\\\ \\$func_quote_for_eval_result\"\n} # func_append_quoted may be replaced by extended shell implementation\n\n\n# func_arith arithmetic-term...\nfunc_arith ()\n{\n    func_arith_result=`expr \"${@}\"`\n} # func_arith may be replaced by extended shell implementation\n\n\n# func_len string\n# STRING may not start with a hyphen.\nfunc_len ()\n{\n    func_len_result=`expr \"${1}\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n} # func_len may be replaced by extended shell implementation\n\n\n# func_lo2o object\nfunc_lo2o ()\n{\n    func_lo2o_result=`$ECHO \"${1}\" | $SED \"$lo2o\"`\n} # func_lo2o may be replaced by extended shell implementation\n\n\n# func_xform libobj-or-source\nfunc_xform ()\n{\n    func_xform_result=`$ECHO \"${1}\" | $SED 's/\\.[^.]*$/.lo/'`\n} # func_xform may be replaced by extended shell implementation\n\n\n# func_fatal_configuration arg...\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func_error ${1+\"$@\"}\n    func_error \"See the $PACKAGE documentation for more information.\"\n    func_fatal_error \"Fatal configuration error.\"\n}\n\n\n# func_config\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n# func_features\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test \"$build_libtool_libs\" = yes; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test \"$build_old_libs\" = yes; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n# func_enable_tag tagname\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n  # Global variable:\n  tagname=\"$1\"\n\n  re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n  re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n  sed_extractcf=\"/$re_begincf/,/$re_endcf/p\"\n\n  # Validate tagname.\n  case $tagname in\n    *[!-_A-Za-z0-9,/]*)\n      func_fatal_error \"invalid tag name: $tagname\"\n      ;;\n  esac\n\n  # Don't test for the \"default\" C tag, as we know it's\n  # there but not specially marked.\n  case $tagname in\n    CC) ;;\n    *)\n      if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\ttaglist=\"$taglist $tagname\"\n\n\t# Evaluate the configuration.  Be careful to quote the path\n\t# and the sed script, to avoid splitting on whitespace, but\n\t# also don't use non-portable quotes within backquotes within\n\t# quotes we have to do it in 2 steps:\n\textractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\teval \"$extractedcf\"\n      else\n\tfunc_error \"ignoring unknown tag $tagname\"\n      fi\n      ;;\n  esac\n}\n\n# func_check_version_match\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n  if test \"$package_revision\" != \"$macro_revision\"; then\n    if test \"$VERSION\" != \"$macro_version\"; then\n      if test -z \"$macro_version\"; then\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n      fi\n    else\n      cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n    fi\n\n    exit $EXIT_MISMATCH\n  fi\n}\n\n\n# Shorthand for --mode=foo, only valid as the first argument\ncase $1 in\nclean|clea|cle|cl)\n  shift; set dummy --mode clean ${1+\"$@\"}; shift\n  ;;\ncompile|compil|compi|comp|com|co|c)\n  shift; set dummy --mode compile ${1+\"$@\"}; shift\n  ;;\nexecute|execut|execu|exec|exe|ex|e)\n  shift; set dummy --mode execute ${1+\"$@\"}; shift\n  ;;\nfinish|finis|fini|fin|fi|f)\n  shift; set dummy --mode finish ${1+\"$@\"}; shift\n  ;;\ninstall|instal|insta|inst|ins|in|i)\n  shift; set dummy --mode install ${1+\"$@\"}; shift\n  ;;\nlink|lin|li|l)\n  shift; set dummy --mode link ${1+\"$@\"}; shift\n  ;;\nuninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n  shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n  ;;\nesac\n\n\n\n# Option defaults:\nopt_debug=:\nopt_dry_run=false\nopt_config=false\nopt_preserve_dup_deps=false\nopt_features=false\nopt_finish=false\nopt_help=false\nopt_help_all=false\nopt_silent=:\nopt_warning=:\nopt_verbose=:\nopt_silent=false\nopt_verbose=false\n\n\n# Parse options once, thoroughly.  This comes as soon as possible in the\n# script to make things like `--version' happen as quickly as we can.\n{\n  # this just eases exit handling\n  while test $# -gt 0; do\n    opt=\"$1\"\n    shift\n    case $opt in\n      --debug|-x)\topt_debug='set -x'\n\t\t\tfunc_echo \"enabling shell trace mode\"\n\t\t\t$opt_debug\n\t\t\t;;\n      --dry-run|--dryrun|-n)\n\t\t\topt_dry_run=:\n\t\t\t;;\n      --config)\n\t\t\topt_config=:\nfunc_config\n\t\t\t;;\n      --dlopen|-dlopen)\n\t\t\toptarg=\"$1\"\n\t\t\topt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$optarg\"\n\t\t\tshift\n\t\t\t;;\n      --preserve-dup-deps)\n\t\t\topt_preserve_dup_deps=:\n\t\t\t;;\n      --features)\n\t\t\topt_features=:\nfunc_features\n\t\t\t;;\n      --finish)\n\t\t\topt_finish=:\nset dummy --mode finish ${1+\"$@\"}; shift\n\t\t\t;;\n      --help)\n\t\t\topt_help=:\n\t\t\t;;\n      --help-all)\n\t\t\topt_help_all=:\nopt_help=': help-all'\n\t\t\t;;\n      --mode)\n\t\t\ttest $# = 0 && func_missing_arg $opt && break\n\t\t\toptarg=\"$1\"\n\t\t\topt_mode=\"$optarg\"\ncase $optarg in\n  # Valid mode arguments:\n  clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n  # Catch anything else as an error\n  *) func_error \"invalid argument for $opt\"\n     exit_cmd=exit\n     break\n     ;;\nesac\n\t\t\tshift\n\t\t\t;;\n      --no-silent|--no-quiet)\n\t\t\topt_silent=false\nfunc_append preserve_args \" $opt\"\n\t\t\t;;\n      --no-warning|--no-warn)\n\t\t\topt_warning=false\nfunc_append preserve_args \" $opt\"\n\t\t\t;;\n      --no-verbose)\n\t\t\topt_verbose=false\nfunc_append preserve_args \" $opt\"\n\t\t\t;;\n      --silent|--quiet)\n\t\t\topt_silent=:\nfunc_append preserve_args \" $opt\"\n        opt_verbose=false\n\t\t\t;;\n      --verbose|-v)\n\t\t\topt_verbose=:\nfunc_append preserve_args \" $opt\"\nopt_silent=false\n\t\t\t;;\n      --tag)\n\t\t\ttest $# = 0 && func_missing_arg $opt && break\n\t\t\toptarg=\"$1\"\n\t\t\topt_tag=\"$optarg\"\nfunc_append preserve_args \" $opt $optarg\"\nfunc_enable_tag \"$optarg\"\n\t\t\tshift\n\t\t\t;;\n\n      -\\?|-h)\t\tfunc_usage\t\t\t\t;;\n      --help)\t\tfunc_help\t\t\t\t;;\n      --version)\tfunc_version\t\t\t\t;;\n\n      # Separate optargs to long options:\n      --*=*)\n\t\t\tfunc_split_long_opt \"$opt\"\n\t\t\tset dummy \"$func_split_long_opt_name\" \"$func_split_long_opt_arg\" ${1+\"$@\"}\n\t\t\tshift\n\t\t\t;;\n\n      # Separate non-argument short options:\n      -\\?*|-h*|-n*|-v*)\n\t\t\tfunc_split_short_opt \"$opt\"\n\t\t\tset dummy \"$func_split_short_opt_name\" \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n\t\t\tshift\n\t\t\t;;\n\n      --)\t\tbreak\t\t\t\t\t;;\n      -*)\t\tfunc_fatal_help \"unrecognized option \\`$opt'\" ;;\n      *)\t\tset dummy \"$opt\" ${1+\"$@\"};\tshift; break  ;;\n    esac\n  done\n\n  # Validate options:\n\n  # save first non-option argument\n  if test \"$#\" -gt 0; then\n    nonopt=\"$opt\"\n    shift\n  fi\n\n  # preserve --debug\n  test \"$opt_debug\" = : || func_append preserve_args \" --debug\"\n\n  case $host in\n    *cygwin* | *mingw* | *pw32* | *cegcc*)\n      # don't eliminate duplications in $postdeps and $predeps\n      opt_duplicate_compiler_generated_deps=:\n      ;;\n    *)\n      opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n      ;;\n  esac\n\n  $opt_help || {\n    # Sanity checks first:\n    func_check_version_match\n\n    if test \"$build_libtool_libs\" != yes && test \"$build_old_libs\" != yes; then\n      func_fatal_configuration \"not configured to build any kind of library\"\n    fi\n\n    # Darwin sucks\n    eval std_shrext=\\\"$shrext_cmds\\\"\n\n    # Only execute mode is allowed to have -dlopen flags.\n    if test -n \"$opt_dlopen\" && test \"$opt_mode\" != execute; then\n      func_error \"unrecognized option \\`-dlopen'\"\n      $ECHO \"$help\" 1>&2\n      exit $EXIT_FAILURE\n    fi\n\n    # Change the help message to a mode-specific one.\n    generic_help=\"$help\"\n    help=\"Try \\`$progname --help --mode=$opt_mode' for more information.\"\n  }\n\n\n  # Bail if the options were screwed\n  $exit_cmd $EXIT_FAILURE\n}\n\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\n# func_lalib_p file\n# True iff FILE is a libtool `.la' library or `.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null \\\n        | $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool `.la' library or `.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if `file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case \"$lalib_p_line\" in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test \"$lalib_p\" = yes\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    func_lalib_p \"$1\"\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=\"$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\"\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $opt_debug\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$save_ifs\n      eval cmd=\\\"$cmd\\\"\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# `FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $opt_debug\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case \"$lt_sysroot:$1\" in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result=\"=$func_stripname_result\"\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $opt_debug\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with \\`--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=${1}\n    if test \"$build_libtool_libs\" = yes; then\n      write_lobj=\\'${2}\\'\n    else\n      write_lobj=none\n    fi\n\n    if test \"$build_old_libs\" = yes; then\n      write_oldobj=\\'${3}\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"${write_libobj}\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $opt_debug\n  func_convert_core_file_wine_to_w32_result=\"$1\"\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"${func_convert_core_file_wine_to_w32_tmp}\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$lt_sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $opt_debug\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\"\"\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\" ; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=\"$func_convert_core_file_wine_to_w32_result\"\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $opt_debug\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: \\`$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $opt_debug\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$lt_sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $opt_debug\n  if test -z \"$2\" && test -n \"$1\" ; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  \\`$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=\"$1\"\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $opt_debug\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  \\`$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=\"$3\"\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $opt_debug\n  case $4 in\n  $1 ) func_to_host_path_result=\"$3$func_to_host_path_result\"\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via `$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $opt_debug\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $opt_debug\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=\"$1\"\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $opt_debug\n  func_to_host_file_result=\"$1\"\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=\"$func_convert_core_msys_to_w32_result\"\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $opt_debug\n  func_to_host_file_result=\"$1\"\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $opt_debug\n  func_to_host_file_result=\"$1\"\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=\"$func_convert_core_file_wine_to_w32_result\"\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $opt_debug\n  func_to_host_file_result=\"$1\"\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=\"$func_cygpath_result\"\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $opt_debug\n  func_to_host_file_result=\"$1\"\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=\"$func_cygpath_result\"\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via `$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $opt_debug\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=\"func_convert_path_${func_stripname_result}\"\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $opt_debug\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=\"$1\"\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $opt_debug\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=\"$func_convert_core_msys_to_w32_result\"\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $opt_debug\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $opt_debug\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=\"$func_convert_core_path_wine_to_w32_result\"\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $opt_debug\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=\"$func_cygpath_result\"\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $opt_debug\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=\"$func_cygpath_result\"\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $opt_debug\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=\"$nonopt\"  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=\"$arg\"\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=\"$arg\"\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify \\`-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=\"$IFS\"; IFS=','\n\t  for arg in $args; do\n\t    IFS=\"$save_ifs\"\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=\"$save_ifs\"\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=\"$srcfile\"\n\t  srcfile=\"$arg\"\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with \\`-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=\"$func_basename_result\"\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from \\`$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest \"$build_libtool_libs\" != yes && \\\n\t  func_fatal_configuration \"can not build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name \\`$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=\"$func_basename_result\"\n    xdir=\"$func_dirname_result\"\n    lobj=${xdir}$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test \"$build_old_libs\" = yes; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test \"$pic_mode\" = no && test \"$deplibs_check_method\" != pass_all; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test \"$compiler_c_o\" = no; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.${objext}\n      lockfile=\"$output_obj.lock\"\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test \"$need_locks\" = yes; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test \"$need_locks\" = warn; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test \"$build_libtool_libs\" = yes; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test \"$pic_mode\" != no; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test \"$need_locks\" = warn &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test \"$suppress_opt\" = yes; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test \"$build_old_libs\" = yes; then\n      if test \"$pic_mode\" != yes; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test \"$compiler_c_o\" = yes; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test \"$need_locks\" = warn &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test \"$need_locks\" != no; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test \"$opt_mode\" = compile && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically \\`/bin/rm').  RM-OPTIONS are options (such as \\`-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a \\`.o' file suitable for static linking\n  -static           only build a \\`.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a \\`standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix \\`.c' with the\nlibrary object suffix, \\`.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to \\`-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe \\`--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the \\`install' or \\`cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      \\`-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  Use a list of object files found in FILE to specify objects\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with \\`-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in \\`.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in \\`.la', then a libtool library is created,\nonly library objects (\\`.lo' files) may be specified, and \\`-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in \\`.a' or \\`.lib', then a standard library is created\nusing \\`ar' and \\`ranlib', or on Windows using \\`lib'.\n\nIf OUTPUT-FILE ends in \\`.lo' or \\`.${objext}', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically \\`/bin/rm').  RM-OPTIONS are options (such as \\`-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode \\`$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try \\`$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test \"$opt_help\" = :; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | sed -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    sed '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $opt_debug\n    # The first argument is the command name.\n    cmd=\"$nonopt\"\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"\\`$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"\\`$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"\\`$file' was not linked with \\`-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=\"$func_dirname_result\"\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find \\`$dlname' in \\`$dir' or \\`$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=\"$func_dirname_result\"\n\t;;\n\n      *)\n\tfunc_warning \"\\`-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=\"$absdir\"\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=\"$magic\"\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=\"$progdir/$program\"\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=\"$progdir/$program\"\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if test \"X$opt_dry_run\" = Xfalse; then\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\"\\$cmd$args\"\n    else\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest \"$opt_mode\" = execute && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $opt_debug\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"\\`$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument \\`$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and \\`=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  sed -e \"${sysroot_cmd} s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_silent && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the \\`-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the \\`$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the \\`$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the \\`$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to \\`/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest \"$opt_mode\" = finish && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $opt_debug\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$nonopt\" = \"$SHELL\" || test \"$nonopt\" = /bin/sh ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac; then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=no\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=yes ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test \"x$prev\" = x-m && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the \\`$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=yes\n    if test \"$isdir\" = yes; then\n      destdir=\"$dest\"\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=\"$func_dirname_result\"\n      destname=\"$func_basename_result\"\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"\\`$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"\\`$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=\"$magic\"\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"\\`$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=\"$func_dirname_result\"\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install \\`$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking \\`$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink \\`$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=\"$1\"\n\t  shift\n\n\t  srcname=\"$realname\"\n\t  test -n \"$relink_command\" && srcname=\"$realname\"T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=\"$stripme\"\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\"\"\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try `ln -sf' first, because the `ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=\"$destdir/$realname\"\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=\"$func_basename_result\"\n\tinstname=\"$dir/$name\"i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=\"$destdir/$destname\"\n\telse\n\t  func_basename \"$file\"\n\t  destfile=\"$func_basename_result\"\n\t  destfile=\"$destdir/$destfile\"\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=\"$destfile\"\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to \\`$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test \"$build_old_libs\" = yes; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=\"$destdir/$destname\"\n\telse\n\t  func_basename \"$file\"\n\t  destfile=\"$func_basename_result\"\n\t  destfile=\"$destdir/$destfile\"\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\"\"\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=\".exe\"\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script \\`$wrapper'\"\n\n\t  finalize=yes\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=\"$libdir/\"`$ECHO \"$lib\" | $SED 's%^.*/%%g'` ### testsuite: skip nested quoting test\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"\\`$lib' has not been installed in \\`$libdir'\"\n\t      finalize=no\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test \"$fast_install\" = no && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if test \"$finalize\" = yes; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=\"$func_basename_result\"\n\t        outputname=\"$tmpdir/$file\"\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_silent || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink \\`$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=\"$outputname\"\n\t      else\n\t        func_warning \"cannot relink \\`$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=\"$func_basename_result\"\n\n      # Set up the ranlib parameters.\n      oldlib=\"$destdir/$name\"\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run \\`$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest \"$opt_mode\" = install && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $opt_debug\n    my_outputname=\"$1\"\n    my_originator=\"$2\"\n    my_pic_p=\"${3-no}\"\n    my_prefix=`$ECHO \"$my_originator\" | sed 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=\"${my_outputname}S.c\"\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=\"$output_objdir/${my_outputname}.nm\"\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for \\`$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined(__GNUC__) && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined(_WIN32) || defined(__CYGWIN__) || defined(_WIN32_WCE)\n/* DATA imports from DLLs on WIN32 con't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined(__osf__)\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test \"$dlself\" = yes; then\n\t  func_verbose \"generating symbol list for \\`$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from \\`$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=\"$output_objdir/$outputname.exp\"\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"${SED} -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from \\`$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=\"$func_basename_result\"\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\"\"\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\" ; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=\"$func_basename_result\"\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\" ; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{\\\n  { \\\"$my_originator\\\", (void *) 0 },\"\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    if test \"X$my_pic_p\" != Xno; then\n\t      pic_flag_for_symtable=\" $pic_flag\"\n\t    fi\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=\"$output_objdir/${my_outputname}S.$objext\"\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for \\`$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $opt_debug\n  win32_libid_type=\"unknown\"\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n      win32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t$SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s,.*,import,\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $opt_debug\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $opt_debug\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive which possess that section. Heuristic: eliminate\n    # all those which have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $opt_debug\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $opt_debug\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $opt_debug\n  if func_cygming_gnu_implib_p \"$1\" ; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\" ; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\"\"\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $opt_debug\n    f_ex_an_ar_dir=\"$1\"; shift\n    f_ex_an_ar_oldlib=\"$1\"\n    if test \"$lock_old_archive_extraction\" = yes; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test \"$lock_old_archive_extraction\" = yes; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $opt_debug\n    my_gentop=\"$1\"; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\"\"\n    my_xlib=\"\"\n    my_xabs=\"\"\n    my_xdir=\"\"\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=\"$my_xlib\" ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=\"$func_basename_result\"\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=\"$my_gentop/$my_xlib_u\"\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  darwin_base_archive=`basename \"$darwin_archive\"`\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches ; do\n\t      func_mkdir_p \"unfat-$$/${darwin_base_archive}-${darwin_arch}\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}\" \"${darwin_archive}\"\n\t      cd \"unfat-$$/${darwin_base_archive}-${darwin_arch}\"\n\t      func_extract_an_archive \"`pwd`\" \"${darwin_base_archive}\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=\"$my_oldobjs\"\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory in which it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ which is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options which match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"${outputname}:${output}:\\${LINENO}: libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"${outputname}:${output}:\\${LINENO}: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"${outputname}:${output}:\\${LINENO}: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"${outputname}:${output}:\\${LINENO}: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test \"$fast_install\" = yes; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | ${SED} 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test \"$shlibpath_overrides_runpath\" = yes && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: \\\\\\`\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n/* declarations of non-ANSI functions */\n#if defined(__MINGW32__)\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined(__CYGWIN__)\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined (other platforms) ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined(_MSC_VER)\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n# ifndef _INTPTR_T_DEFINED\n#  define _INTPTR_T_DEFINED\n#  define intptr_t int\n# endif\n#elif defined(__MINGW32__)\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined(__CYGWIN__)\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined (other platforms) ... */\n#endif\n\n#if defined(PATH_MAX)\n# define LT_PATHMAX PATH_MAX\n#elif defined(MAXPATHLEN)\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \\\n  defined (__OS2__)\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free ((void *) stale); stale = 0; } \\\n} while (0)\n\n#if defined(LT_DEBUGWRAPPER)\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\nvolatile const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test \"$shlibpath_overrides_runpath\" = yes && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test \"$fast_install\" = yes; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  intptr_t rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (strcmp (argv[i], dumpscript_opt) == 0)\n\t{\nEOF\n\t    case \"$host\" in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (strcmp (argv[i], debug_opt) == 0)\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (strcmp (argv[i], ltwrapper_option_prefix) == 0)\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE$TIMESTAMP) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  int tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = q - p;\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (strcmp (str, pat) == 0)\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    int len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      int orig_value_len = strlen (orig_value);\n      int add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      int len = strlen (new_value);\n      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[len-1] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $opt_debug\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $opt_debug\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # which system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll which has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=no\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=\"${wl}-single_module\"\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest \"$build_libtool_libs\" != yes && \\\n\t  func_fatal_configuration \"can not build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test \"$build_libtool_libs\" = yes && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=\"$1\"\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  if test \"$preload\" = no; then\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=yes\n\t  fi\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test \"$dlself\" = no; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test \"$prev\" = dlprefiles; then\n\t      dlself=yes\n\t    elif test \"$prev\" = dlfiles && test \"$dlopen_self\" != yes; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test \"$prev\" = dlfiles; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=\"$arg\"\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file \\`$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test \"$pic_object\" = none &&\n\t\t   test \"$non_pic_object\" = none; then\n\t\t  func_fatal_error \"cannot find name of object for \\`$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=\"$func_dirname_result\"\n\n\t\tif test \"$pic_object\" != none; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=\"$xdir$pic_object\"\n\n\t\t  if test \"$prev\" = dlfiles; then\n\t\t    if test \"$build_libtool_libs\" = yes && test \"$dlopen_support\" = yes; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test \"$prev\" = dlprefiles; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=\"$pic_object\"\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test \"$non_pic_object\" != none; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=\"$xdir$non_pic_object\"\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test \"$pic_object\" = none ; then\n\t\t    arg=\"$non_pic_object\"\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=\"$pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=\"$func_dirname_result\"\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"\\`$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file \\`$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=\"-$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test \"$prev\" = rpath; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=\"$arg\"\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"\\`-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test \"X$arg\" = \"X-export-symbols\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between \\`-L' and \\`$1'\"\n\t  else\n\t    func_fatal_error \"need path for \\`-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of \\`$dir'\"\n\t  dir=\"$absdir\"\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test \"X$arg\" = \"X-lc\" || test \"X$arg\" = \"X-lm\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  esac\n\telif test \"X$arg\" = \"X-lc_r\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=\"${wl}-multi_module\"\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"\\`-no-install' is ignored for $host\"\n\t  func_warning \"assuming \\`-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=\"$IFS\"; IFS=','\n\tfor flag in $args; do\n\t  IFS=\"$save_ifs\"\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=\"$save_ifs\"\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=\"$IFS\"; IFS=','\n\tfor flag in $args; do\n\t  IFS=\"$save_ifs\"\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=\"$save_ifs\"\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-flto*|-fwhopr*|-fuse-linker-plugin)\n        func_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test \"$pic_object\" = none &&\n\t     test \"$non_pic_object\" = none; then\n\t    func_fatal_error \"cannot find name of object for \\`$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=\"$func_dirname_result\"\n\n\t  if test \"$pic_object\" != none; then\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=\"$xdir$pic_object\"\n\n\t    if test \"$prev\" = dlfiles; then\n\t      if test \"$build_libtool_libs\" = yes && test \"$dlopen_support\" = yes; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test \"$prev\" = dlprefiles; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=\"$pic_object\"\n\t  fi\n\n\t  # Non-PIC object.\n\t  if test \"$non_pic_object\" != none; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=\"$xdir$non_pic_object\"\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test \"$pic_object\" = none ; then\n\t      arg=\"$non_pic_object\"\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=\"$pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=\"$func_dirname_result\"\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"\\`$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test \"$prev\" = dlfiles; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test \"$prev\" = dlprefiles; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the \\`$prevarg' option requires an argument\"\n\n    if test \"$export_dynamic\" = yes && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=\"$func_basename_result\"\n    libobjs_save=\"$libobjs\"\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\${$shlibpath_var}\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=\"$func_dirname_result$objdir\"\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps ; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test \"$linkmode\" = lib; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can \\`-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=no\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test \"$linkmode,$pass\" = \"lib,link\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=\"$tmp_deplibs\"\n      fi\n\n      if test \"$linkmode,$pass\" = \"lib,link\" ||\n\t test \"$linkmode,$pass\" = \"prog,scan\"; then\n\tlibs=\"$deplibs\"\n\tdeplibs=\n      fi\n      if test \"$linkmode\" = prog; then\n\tcase $pass in\n\tdlopen) libs=\"$dlfiles\" ;;\n\tdlpreopen) libs=\"$dlprefiles\" ;;\n\tlink) libs=\"$deplibs %DEPLIBS% $dependency_libs\" ;;\n\tesac\n      fi\n      if test \"$linkmode,$pass\" = \"lib,dlpreopen\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=\"$dlprefiles\"\n      fi\n      if test \"$pass\" = dlopen; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=\"$deplibs\"\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=no\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test \"$linkmode\" = lib ; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test \"$linkmode\" != lib && test \"$linkmode\" != prog; then\n\t    func_warning \"\\`-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test \"$linkmode\" = lib; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=\"$searchdir/lib${name}${search_ext}\"\n\t      if test -f \"$lib\"; then\n\t\tif test \"$search_ext\" = \".la\"; then\n\t\t  found=yes\n\t\telse\n\t\t  found=no\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if test \"$found\" != yes; then\n\t    # deplib doesn't seem to be a libtool library\n\t    if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test \"$linkmode\" = lib && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  else # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=\"$l\"\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\" ; then # only static version available\n\t\t    found=no\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=\"$func_dirname_result\"\n\t\t    lib=$ladir/$old_library\n\t\t    if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test \"$linkmode\" = lib && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test \"$linkmode\" = lib ; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test \"$pass\" = conv && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test \"$pass\" = conv; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test \"$pass\" = scan; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"\\`-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test \"$pass\" = link; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test \"$pass\" = conv; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=no\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=yes\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=yes\n\t\t;;\n\t      esac\n\t      if test \"$valid_a_lib\" != yes; then\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test \"$pass\" != link; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test \"$pass\" = conv; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test \"$linkmode\" = prog; then\n\t    if test \"$pass\" = dlpreopen || test \"$dlopen_support\" != yes || test \"$build_libtool_libs\" = no; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=yes\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\tif test \"$found\" = yes || test -f \"$lib\"; then :\n\telse\n\t  func_fatal_error \"cannot find the library \\`$lib' or unhandled argument \\`$deplib'\"\n\tfi\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=\"$func_dirname_result\"\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test \"$linkmode,$pass\" = \"lib,link\" ||\n\t   test \"$linkmode,$pass\" = \"prog,scan\" ||\n\t   { test \"$linkmode\" != prog && test \"$linkmode\" != lib; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test \"$pass\" = conv; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for \\`$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t  elif test \"$linkmode\" != prog && test \"$linkmode\" != lib; then\n\t    func_fatal_error \"\\`$lib' is not a convenience library\"\n\t  fi\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    deplibs=\"$deplib $deplibs\"\n\t    if $opt_preserve_dup_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test \"$prefer_static_libs\" = yes ||\n\t     test \"$prefer_static_libs,$installed\" = \"built,no\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=\"$l\"\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for \\`$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test \"$pass\" = dlopen; then\n\t  if test -z \"$libdir\"; then\n\t    func_fatal_error \"cannot -dlopen a convenience library: \\`$lib'\"\n\t  fi\n\t  if test -z \"$dlname\" ||\n\t     test \"$dlopen_support\" != yes ||\n\t     test \"$build_libtool_libs\" = no; then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=\"$ladir\" ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of \\`$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=\"$ladir\"\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=\"$func_basename_result\"\n\n\t# Find the relevant object directory and library name.\n\tif test \"X$installed\" = Xyes; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library \\`$lib' was moved.\"\n\t    dir=\"$ladir\"\n\t    absdir=\"$abs_ladir\"\n\t    libdir=\"$abs_ladir\"\n\t  else\n\t    dir=\"$lt_sysroot$libdir\"\n\t    absdir=\"$lt_sysroot$libdir\"\n\t  fi\n\t  test \"X$hardcode_automatic\" = Xyes && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=\"$ladir\"\n\t    absdir=\"$abs_ladir\"\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=\"$ladir/$objdir\"\n\t    absdir=\"$abs_ladir/$objdir\"\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test \"$pass\" = dlpreopen; then\n\t  if test -z \"$libdir\" && test \"$linkmode\" = prog; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: \\`$lib'\"\n\t  fi\n\t  case \"$host\" in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test \"$linkmode\" = lib; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test \"$linkmode\" = prog && test \"$pass\" != link; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=no\n\t  if test \"$link_all_deplibs\" != no || test -z \"$library_names\" ||\n\t     test \"$build_libtool_libs\" = no; then\n\t    linkalldeplibs=yes\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if test \"$linkalldeplibs\" = yes; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test \"$linkmode,$pass\" = \"prog,link\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test \"$prefer_static_libs\" = no ||\n\t         test \"$prefer_static_libs,$installed\" = \"built,yes\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\" ; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case \"$temp_rpath:\" in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if test \"$alldeplibs\" = yes &&\n\t     { test \"$deplibs_check_method\" = pass_all ||\n\t       { test \"$build_libtool_libs\" = yes &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test \"$use_static_libs\" = built && test \"$installed\" = yes; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test \"$use_static_libs\" = no || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test \"$installed\" = no; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\"\"\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=\"$dlpremoduletest\"\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test \"$shouldnotlink\" = yes && test \"$pass\" = link; then\n\t    echo\n\t    if test \"$linkmode\" = prog; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test \"$linkmode\" = lib &&\n\t     test \"$hardcode_into_libs\" = yes; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=\"$1\"\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=\"$dlname\"\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=\"-$major\"\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=\"$realname\"\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=\"$soname\"\n\t    func_basename \"$soroot\"\n\t    soname=\"$func_basename_result\"\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from \\`$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for \\`$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test \"$linkmode\" = prog || test \"$opt_mode\" != relink; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test \"$hardcode_direct\" = no; then\n\t\tadd=\"$dir/$linklib\"\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-sysv4*uw2*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we can not\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null ; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\" ; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=\"$dir/$old_library\"\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=\"$dir/$old_library\"\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test \"$hardcode_minus_L\" = no; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=\"$dir\" ;;\n\t\tesac\n\t\tadd_dir=\"-L$dir\"\n\t\tadd=\"-l$name\"\n\t      elif test \"$hardcode_shlibpath_var\" = no; then\n\t\tadd_shlibpath=\"$dir\"\n\t\tadd=\"-l$name\"\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test \"$hardcode_direct\" = yes &&\n\t         test \"$hardcode_direct_absolute\" = no; then\n\t\tadd=\"$dir/$linklib\"\n\t      elif test \"$hardcode_minus_L\" = yes; then\n\t\tadd_dir=\"-L$absdir\"\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=\"-l$name\"\n\t      elif test \"$hardcode_shlibpath_var\" = yes; then\n\t\tadd_shlibpath=\"$dir\"\n\t\tadd=\"-l$name\"\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test \"$lib_linked\" != yes; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test \"$linkmode\" = prog; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test \"$hardcode_direct\" != yes &&\n\t\t test \"$hardcode_minus_L\" != yes &&\n\t\t test \"$hardcode_shlibpath_var\" = yes; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test \"$linkmode\" = prog || test \"$opt_mode\" = relink; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test \"$hardcode_direct\" = yes &&\n\t       test \"$hardcode_direct_absolute\" = no; then\n\t      add=\"$libdir/$linklib\"\n\t    elif test \"$hardcode_minus_L\" = yes; then\n\t      add_dir=\"-L$libdir\"\n\t      add=\"-l$name\"\n\t    elif test \"$hardcode_shlibpath_var\" = yes; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=\"-l$name\"\n\t    elif test \"$hardcode_automatic\" = yes; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\" ; then\n\t\tadd=\"$inst_prefix_dir$libdir/$linklib\"\n\t      else\n\t\tadd=\"$libdir/$linklib\"\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=\"-L$libdir\"\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=\"-l$name\"\n\t    fi\n\n\t    if test \"$linkmode\" = prog; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test \"$linkmode\" = prog; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test \"$hardcode_direct\" != unsupported; then\n\t    test -n \"$old_library\" && linklib=\"$old_library\"\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test \"$build_libtool_libs\" = yes; then\n\t  # Not a shared library\n\t  if test \"$deplibs_check_method\" != pass_all; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system can not link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test \"$module\" = yes; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using \\`nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** \\`nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test \"$build_old_libs\" = no; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test \"$linkmode\" = lib; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test \"$hardcode_into_libs\" != yes ||\n\t       test \"$build_old_libs\" = yes ||\n\t       test \"$link_static\" = yes; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=\"$temp_deplibs\"\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test \"$link_static\" = no && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test \"$link_all_deplibs\" != no; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=\"$deplib\" ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=\"$dir\" ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of \\`$dir'\"\n\t\t    absdir=\"$dir\"\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`${SED} -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\" ; then\n\t\t    for tmp in $deplibrary_names ; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\" ; then\n\t\t      depdepl=\"$absdir/$objdir/$depdepl\"\n\t\t      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}\"\n\t\t      func_append linker_flags \" -dylib_file ${darwin_install_name}:${depdepl}\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=\"-L$absdir/$objdir\"\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"\\`$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"\\`$deplib' seems to be moved\"\n\n\t\t  path=\"-L$absdir\"\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test \"$pass\" = link; then\n\tif test \"$linkmode\" = \"prog\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=\"$newdependency_libs\"\n      if test \"$pass\" = dlpreopen; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test \"$pass\" != dlopen; then\n\tif test \"$pass\" != conv; then\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\tfi\n\n\tif test \"$linkmode,$pass\" != \"prog,link\"; then\n\t  vars=\"deplibs\"\n\telse\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs ; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\"\"\n\t  ;;\n\tesac\n\tif test -n \"$i\" ; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test \"$linkmode\" = prog; then\n      dlfiles=\"$newdlfiles\"\n    fi\n    if test \"$linkmode\" = prog || test \"$linkmode\" = lib; then\n      dlprefiles=\"$newdlprefiles\"\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n\tfunc_warning \"\\`-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"\\`-l' and \\`-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"\\`-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"\\`-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"\\`-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=\"$output\"\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form `libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest \"$module\" = no && \\\n\t  func_fatal_help \"libtool library \\`$output' must begin with \\`lib'\"\n\n\tif test \"$need_lib_prefix\" != no; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test \"$deplibs_check_method\" != pass_all; then\n\t  func_fatal_error \"cannot build libtool library \\`$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test \"$dlself\" != no && \\\n\tfunc_warning \"\\`-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test \"$#\" -gt 1 && \\\n\tfunc_warning \"ignoring multiple \\`-rpath's for a libtool library\"\n\n      install_libdir=\"$1\"\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test \"$build_libtool_libs\" = yes; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a `.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"\\`-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"\\`-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=\"$IFS\"; IFS=':'\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=\"$save_ifs\"\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to \\`-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=\"$1\"\n\t  number_minor=\"$2\"\n\t  number_revision=\"$3\"\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # which has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=\"$number_minor\"\n\t    revision=\"$number_revision\"\n\t    ;;\n\t  freebsd-aout|freebsd-elf|qnx|sunos)\n\t    current=\"$number_major\"\n\t    revision=\"$number_minor\"\n\t    age=\"0\"\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=\"$number_minor\"\n\t    revision=\"$number_minor\"\n\t    lt_irix_increment=no\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=\"$1\"\n\t  revision=\"$2\"\n\t  age=\"$3\"\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT \\`$current' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION \\`$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE \\`$age' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE \\`$age' is greater than the current interface number \\`$current'\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\"$major.$age.$revision\"\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=\".$current\"\n\t  versuffix=\".$current.$revision\";\n\t  ;;\n\n\tfreebsd-elf)\n\t  major=\".$current\"\n\t  versuffix=\".$current\"\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test \"X$lt_irix_increment\" = \"Xno\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=\"$verstring_prefix$major.$revision\"\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test \"$loop\" -ne 0; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=\"$verstring_prefix$major.$iface:$verstring\"\n\t  done\n\n\t  # Before this point, $major must not contain `.'.\n\t  major=.$major\n\t  versuffix=\"$major.$revision\"\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\"$major.$age.$revision\"\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\".$current.$age.$revision\"\n\t  verstring=\"$current.$age.$revision\"\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test \"$loop\" -ne 0; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=\"$verstring:${iface}.0\"\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":${current}.0\"\n\t  ;;\n\n\tqnx)\n\t  major=\".$current\"\n\t  versuffix=\".$current\"\n\t  ;;\n\n\tsunos)\n\t  major=\".$current\"\n\t  versuffix=\".$current.$revision\"\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 filesystems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=\"-$major\"\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type \\`$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=\"0.0\"\n\t    ;;\n\t  esac\n\t  if test \"$need_version\" = no; then\n\t    versuffix=\n\t  else\n\t    versuffix=\".0.0\"\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test \"$avoid_version\" = yes && test \"$need_version\" = no; then\n\t  major=\n\t  versuffix=\n\t  verstring=\"\"\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test \"$allow_undefined\" = yes; then\n\t  if test \"$allow_undefined_flag\" = unsupported; then\n\t    func_warning \"undefined symbols not allowed in $host shared libraries\"\n\t    build_libtool_libs=no\n\t    build_old_libs=yes\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=\"$no_undefined_flag\"\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" \"yes\"\n      func_append libobjs \" $symfileobj\"\n      test \"X$libobjs\" = \"X \" && libobjs=\n\n      if test \"$opt_mode\" != relink; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)\n\t       if test \"X$precious_files_regex\" != \"X\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test \"$build_old_libs\" = yes && test \"$build_libtool_libs\" != convenience ; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.${libext}$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test \"$hardcode_into_libs\" != yes || test \"$build_old_libs\" = yes; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=\"$dlfiles\"\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=\"$dlprefiles\"\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test \"$build_libtool_libs\" = yes; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test \"$build_libtool_need_lc\" = \"yes\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\"\"\n\tversuffix=\"\"\n\tmajor=\"\"\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\"\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\" ; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0 ; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\"\"\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\" ; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0 ; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\"\"\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest \"$want_nocaseglob\" = yes && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test \"$want_nocaseglob\" = yes; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=\"$potent_lib\"\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=\"$potliblink\";;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's,[^/]*$,,'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\"\"\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\" ; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\"\"\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=\"$potent_lib\" # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\"\"\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\" ; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\"\"\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t    for i in $predeps $postdeps ; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s,$i,,\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test \"X$deplibs_check_method\" = \"Xnone\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test \"$droppeddeps\" = yes; then\n\t  if test \"$module\" = yes; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using \\`nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** \\`nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test \"$build_old_libs\" = no; then\n\t      oldlibs=\"$output_objdir/$libname.$libext\"\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test \"$allow_undefined\" = no; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test \"$build_old_libs\" = no; then\n\t\toldlibs=\"$output_objdir/$libname.$libext\"\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=\"$new_libs\"\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test \"$build_libtool_libs\" = yes; then\n\t# Remove ${wl} instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test \"$hardcode_into_libs\" = yes; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=\"$finalize_rpath\"\n\t  test \"$opt_mode\" != relink && rpath=\"$compile_rpath$rpath\"\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=\"$libdir\"\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=\"$hardcode_libdirs\"\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=\"$finalize_shlibpath\"\n\ttest \"$opt_mode\" != relink && shlibpath=\"$compile_shlibpath$shlibpath\"\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=\"$1\"\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=\"$realname\"\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=\"$output_objdir/$realname\"\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=\"$output_objdir/$libname.uexp\"\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    if test \"x`$SED 1q $export_symbols`\" != xEXPORTS; then\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=\"$export_symbols\"\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    fi\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test \"$always_export_symbols\" = yes || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for \\`$libname.la'\"\n\t    export_symbols=\"$output_objdir/$libname.exp\"\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=\"$IFS\"; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=\"$save_ifs\"\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test \"$try_normal_branch\" = yes \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=${output_objdir}/${output_la}.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=\"$save_ifs\"\n\t    if test -n \"$export_symbols_regex\" && test \"X$skipped_export\" != \"X:\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=\"$export_symbols\"\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=\"$orig_export_symbols\"\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test \"X$skipped_export\" != \"X:\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for \\`$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=\"$tmp_deplibs\"\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test \"$compiler_needs_object\" = yes &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=\"$output_objdir/${outputname}x\"\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test \"$thread_safe\" = yes && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test \"$opt_mode\" = relink; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test \"$module\" = yes && test -n \"$module_cmds\" ; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test \"X$skipped_export\" != \"X:\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test \"X$skipped_export\" != \"X:\" && test \"$with_gnu_ld\" = yes; then\n\t    output=${output_objdir}/${output_la}.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test \"X$skipped_export\" != \"X:\" && test \"X$file_list_spec\" != X; then\n\t    output=${output_objdir}/${output_la}.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test \"$compiler_needs_object\" = yes; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-${k}.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test \"X$objlist\" = X ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test \"$k\" -eq 1 ; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-${k}.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-${k}.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\${concat_cmds}$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\${concat_cmds}~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    if ${skipped_export-false}; then\n\t      func_verbose \"generating symbol list for \\`$libname.la'\"\n\t      export_symbols=\"$output_objdir/$libname.exp\"\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    fi\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=\"$IFS\"; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=\"$save_ifs\"\n\t      $opt_silent || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test \"$opt_mode\" = relink; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=\"$save_ifs\"\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          if ${skipped_export-false}; then\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=\"$export_symbols\"\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=\"$orig_export_symbols\"\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for \\`$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  fi\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test \"$module\" = yes && test -n \"$module_cmds\" ; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=\"$IFS\"; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=\"$save_ifs\"\n\t  eval cmd=\\\"$cmd\\\"\n\t  $opt_silent || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test \"$opt_mode\" = relink; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=\"$save_ifs\"\n\n\t# Restore the uninstalled library and exit\n\tif test \"$opt_mode\" = relink; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test \"$module\" = yes || test \"$export_dynamic\" = yes; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=\"$soname\"\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n\tfunc_warning \"\\`-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"\\`-l' and \\`-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"\\`-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"\\`-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object \\`$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=\"$output\"\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # reload_cmds runs $LD directly, so let us get rid of\n      # -Wl from whole_archive_flag_spec and hope we can get by with\n      # turning comma into space..\n      wl=\n\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  reload_conv_objs=$reload_objs\\ `$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\telse\n\t  gentop=\"$output_objdir/${obj}x\"\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test \"$build_libtool_libs\" != yes && libobjs=\"$non_pic_objects\"\n\n      # Create the old-style object.\n      reload_objs=\"$objs$old_deplibs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.${libext}$/d; /\\.lib$/d; $lo2o\" | $NL2SP`\" $reload_conv_objs\" ### testsuite: skip nested quoting test\n\n      output=\"$obj\"\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      if test \"$build_libtool_libs\" != yes; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      fi\n\n      if test -n \"$pic_flag\" || test \"$pic_mode\" != default; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=\"$libobj\"\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for programs\"\n\n      test \"$preload\" = yes \\\n        && test \"$dlopen_support\" = unknown \\\n\t&& test \"$dlopen_self\" = unknown \\\n\t&& test \"$dlopen_self_static\" = unknown && \\\n\t  func_warning \"\\`LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test \"$tagname\" = CXX ; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" ${wl}-bind_at_load\"\n\t      func_append finalize_command \" ${wl}-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=\"$new_libs\"\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=\"$libdir\"\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`${ECHO} \"$libdir\" | ${SED} -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=\"$hardcode_libdirs\"\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=\"$rpath\"\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=\"$libdir\"\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=\"$hardcode_libdirs\"\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=\"$rpath\"\n\n      if test -n \"$libobjs\" && test \"$build_old_libs\" = yes; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" \"no\"\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=yes\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=no\n        ;;\n      *cygwin* | *mingw* )\n        if test \"$build_libtool_libs\" != yes; then\n          wrappers_required=no\n        fi\n        ;;\n      *)\n        if test \"$need_relink\" = no || test \"$build_libtool_libs\" != yes; then\n          wrappers_required=no\n        fi\n        ;;\n      esac\n      if test \"$wrappers_required\" = no; then\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=\"$compile_command$compile_rpath\"\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.${objext}\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.${objext}\"'\n\tfi\n\n\texit $exit_status\n      fi\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test \"$no_install\" = yes; then\n\t# We don't need to create a wrapper script.\n\tlink_command=\"$compile_var$compile_command$compile_rpath\"\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      if test \"$hardcode_action\" = relink; then\n\t# Fast installation is not supported\n\tlink_command=\"$compile_var$compile_command$compile_rpath\"\n\trelink_command=\"$finalize_var$finalize_command$finalize_rpath\"\n\n\tfunc_warning \"this platform does not like uninstalled shared libraries\"\n\tfunc_warning \"\\`$output' will be relinked during installation\"\n      else\n\tif test \"$fast_install\" != no; then\n\t  link_command=\"$finalize_var$compile_command$finalize_rpath\"\n\t  if test \"$fast_install\" = yes; then\n\t    relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n\t  else\n\t    # fast_install is set to needless\n\t    relink_command=\n\t  fi\n\telse\n\t  link_command=\"$compile_var$compile_command$compile_rpath\"\n\t  relink_command=\"$finalize_var$finalize_command$finalize_rpath\"\n\tfi\n      fi\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=\"$output_path/$objdir/lt-$output_name.c\"\n\t    cwrapper=\"$output_path/$output_name.exe\"\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\" ; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      if test \"$build_libtool_libs\" = convenience; then\n\toldobjs=\"$libobjs_save $symfileobj\"\n\taddlibs=\"$convenience\"\n\tbuild_libtool_libs=no\n      else\n\tif test \"$build_libtool_libs\" = module; then\n\t  oldobjs=\"$libobjs_save\"\n\t  build_libtool_libs=no\n\telse\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  if test \"$preload\" = yes && test -f \"$symfileobj\"; then\n\t    func_append oldobjs \" $symfileobj\"\n\t  fi\n\tfi\n\taddlibs=\"$old_convenience\"\n      fi\n\n      if test -n \"$addlibs\"; then\n\tgentop=\"$output_objdir/${outputname}x\"\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test \"$build_libtool_libs\" = yes; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=\"$func_basename_result\"\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\" ; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\${concat_cmds}$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test \"X$oldobjs\" = \"X\" ; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test \"$build_old_libs\" = yes && old_library=\"$libname.$libext\"\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test \"$hardcode_automatic\" = yes ; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test \"$installed\" = yes; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=\"$output_objdir/$outputname\"i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=\"$func_basename_result\"\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=\"$newdependency_libs\"\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=\"$func_basename_result\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=\"$newdlfiles\"\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=\"$func_basename_result\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=\"$newdlprefiles\"\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=\"$lib\" ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=\"$newdlfiles\"\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=\"$lib\" ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=\"$newdlprefiles\"\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test \"x$bindir\" != x ;\n\t      then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that can not go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test \"$installed\" = no && test \"$need_relink\" = yes; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\n{ test \"$opt_mode\" = link || test \"$opt_mode\" = relink; } &&\n    func_mode_link ${1+\"$@\"}\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $opt_debug\n    RM=\"$nonopt\"\n    files=\n    rmforce=\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=\"$magic\"\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=yes ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=\"$func_dirname_result\"\n      if test \"X$dir\" = X.; then\n\todir=\"$objdir\"\n      else\n\todir=\"$dir/$objdir\"\n      fi\n      func_basename \"$file\"\n      name=\"$func_basename_result\"\n      test \"$opt_mode\" = uninstall && odir=\"$dir\"\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test \"$opt_mode\" = clean; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif test \"$rmforce\" = yes; then\n\tcontinue\n      fi\n\n      rmfiles=\"$file\"\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case \"$opt_mode\" in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" 'test \"$rmforce\" = yes || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" 'test \"$rmforce\" = yes || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" &&\n\t     test \"$pic_object\" != none; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" &&\n\t     test \"$non_pic_object\" != none; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test \"$opt_mode\" = clean ; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.${objext}\"\n\t    if test \"$fast_install\" = yes && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\" ; then\n\t      func_append rmfiles \" $odir/lt-${noexename}.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the ${objdir}s in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\n{ test \"$opt_mode\" = uninstall || test \"$opt_mode\" = clean; } &&\n    func_mode_uninstall ${1+\"$@\"}\n\ntest -z \"$opt_mode\" && {\n  help=\"$generic_help\"\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode \\`$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# in which we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n# vi:sw=2\n\n", "num_lines": 9656}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# tar comparision program\n# 2007-10-25 Jan Psota\n\nn=3                                     # number of repetitions\nTAR=(bsdtar gnutar star)                # TApeArchivers to compare\nOPT=(\"\" \"--seek\" \"-no-fsync\")\npax=\"--format=pax\"                      # comment out for defaults\nOPN=(create list extract compare)       # operations\nversion=\"2007-10-25\"\nTIMEFORMAT=$'%R\\t%U\\t%S\\t%P'\nLC_ALL=C\n\ntest $# -ge 2 || {\n        echo -e \"usage:\\t$0 source_dir where_to_place_archive \n[where_to_extract_it]\n\nTCP, version $version\nTCP stands for Tar Comparision Program here.\nIt currently compares: BSD tar (bsdtar), GNU tar (gnutar) and star in archive\ncreation, listing, extraction and archive-to-extracted comparision.\nTcp prints out best time of n=$n repetitions.\n\nTcp creates temporary archive named tcp.tar with $pax and some native\n(--seek/-no-fsync) options and extracts it to [\\$3]/tcptmp/.\nIf unset, third argument defaults to [\\$2].\nAfter normal exit tcp removes tarball and extracted files.\nTcp does not check filesystems destination directories are on for free space,\nso make sure there is enough space (a bit more than source_dir uses) for both:\narchive and extracted files.\nDo not use white space in arguments.\n        Jan Psota, $version\"\n        exit 0\n}\nsrc=$1\ndst=$2/tcp.tar\ndst_path=${3:-$2}/tcptmp\ntest -e $dst -o -e /tmp/tcp \\\n        && { echo \"$dst or /tmp/tcp exists, exiting\"; exit 1; }\nmkdir $dst_path || exit 2\n\nuse_times ()\n{\n        awk -F\"\\t\" -vN=$n -vL=\"`du -k $dst`\" -vOFS=\"\\t\" -vORS=\"\" '\n                { if (NF==4) { printf \"\\t%s\\t%10.1d KB/s\\n\", $0, ($1+0>0 ? \n(L+0)/($1+0) : 0) } }' \\\n                /tmp/tcp | sort | head -1\n        > /tmp/tcp\n}\n\ntest -d $src || { echo \"'$src' is not a directory\"; exit 3; }\n\n# system information: type, release, memory, cpu(s), compiler and flags\necho -e \"TCP, version $version\\n\"`uname -sr`\" / \"`head -1 /etc/*-release`\nfree -m | awk '/^Mem/ { printf \"%dMB of memory, \", $2 }'\ntest -e /proc/cpuinfo \\\n        && awk -F: '/name|cache size|MHz|mips/ { if (!a) b=b $2 }\n        /^$/ { a++ } END { print a\" x\"b\" bmips\" }' /proc/cpuinfo\ntest -e /etc/gentoo-release \\\n        && gcc --version | head -1 && grep ^CFLAGS /etc/make.conf\n\n# tar versions\necho\nfor tar in [EMAIL PROTECTED]; do echo -ne \"$tar:\\t\"; $tar --version | head -1; \ndone\n\necho -e \"\\nbest time of $n repetitions,\\n\"\\\n\"       src=$src, \"\\\n`du -sh $src | awk '{print $1}'`\" in \"`find $src | wc -l`\" files, \"\\\n\"avg \"$((`du -sk $src | awk '{print $1}'`/`find $src -type f | wc \n-l`))\"KB/file,\\n\"\\\n\"       archive=$dst, extract to $dst_path\"\n\necho -e \"program\\toperation\\treal\\tuser\\tsystem\\t%CPU\\t     speed\"\n> /tmp/tcp\nlet op_num=0\nfor op in \"cf $dst $pax -C $src .\" \"tf $dst\" \"xf $dst -C $dst_path\" \\\n        \"f $dst -C $dst_path --diff\"; do\n        let tar_num=0\n        for tar in [EMAIL PROTECTED]; do\n                echo -en \"$tar\\t${OPN[op_num]}\\t\"\n                for ((i=1; i<=$n; i++)); do\n                        echo $op | grep -q ^cf && rm -f $dst\n                        echo $op | grep -q ^xf &&\n                                { chmod -R u+w $dst_path\n                                rm -rf $dst_path; mkdir $dst_path; }\n                        sync\n                        if echo $op | grep -q ^f; then  # op == compare\n                                time $tar $op ${OPT[$tar_num]} > /dev/null\n                        else    # op in (create | list | extract)\n                                time $tar $op ${OPT[$tar_num]} > /dev/null \\\n                                        || break 3\n                        fi 2>> /tmp/tcp\n                done\n                use_times\n                let tar_num++\n        done\n        let op_num++\n        echo\ndone\nrm -rf $dst_path $dst\necho\ncat /tmp/tcp\nrm -f /tmp/tcp\n", "num_lines": 105}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#\n# Simple script to repopulate the 'doc' tree from\n# the mdoc man pages stored in each project.\n#\n\n# Collect list of man pages, relative to my subdirs\ncd man\nMANPAGES=`for d in libarchive tar cpio;do ls ../../$d/*.[135];done | grep -v '\\.so\\.'`\ncd ..\n\n# Build Makefile in 'man' directory\ncd man\nrm -f *.[135]\necho > Makefile\necho \"default: all\" >>Makefile\necho >>Makefile\nall=\"all:\"\nfor f in $MANPAGES; do\n    outname=\"`basename $f`\"\n    echo >> Makefile\n    echo $outname: ../mdoc2man.awk $f >> Makefile\n    echo \"\tawk -f ../mdoc2man.awk < $f > $outname\" >> Makefile\n    all=\"$all $outname\"\ndone\necho $all >>Makefile\ncd ..\n\n# Rebuild Makefile in 'text' directory\ncd text\nrm -f *.txt\necho > Makefile\necho \"default: all\" >>Makefile\necho >>Makefile\nall=\"all:\"\nfor f in $MANPAGES; do\n    outname=\"`basename $f`.txt\"\n    echo >> Makefile\n    echo $outname: $f >> Makefile\n    echo \"\tnroff -mdoc $f | col -b > $outname\" >> Makefile\n    all=\"$all $outname\"\ndone\necho $all >>Makefile\ncd ..\n\n# Rebuild Makefile in 'pdf' directory\ncd pdf\nrm -f *.pdf\necho > Makefile\necho \"default: all\" >>Makefile\necho >>Makefile\nall=\"all:\"\nfor f in $MANPAGES; do\n    outname=\"`basename $f`.pdf\"\n    echo >> Makefile\n    echo $outname: $f >> Makefile\n    echo \"\tgroff -mdoc -T ps $f | ps2pdf - - > $outname\" >> Makefile\n    all=\"$all $outname\"\ndone\necho $all >>Makefile\ncd ..\n\n# Build Makefile in 'html' directory\ncd html\nrm -f *.html\necho > Makefile\necho \"default: all\" >>Makefile\necho >>Makefile\nall=\"all:\"\nfor f in $MANPAGES; do\n    outname=\"`basename $f`.html\"\n    echo >> Makefile\n    echo $outname: $f >> Makefile\n    echo \"\tgroff -mdoc2html $f > $outname\" >> Makefile\n    all=\"$all $outname\"\ndone\necho $all >>Makefile\ncd ..\n\n# Build Makefile in 'wiki' directory\ncd wiki\nrm -f *.wiki\necho > Makefile\necho \"default: all\" >>Makefile\necho >>Makefile\nall=\"all:\"\nfor f in $MANPAGES; do\n    outname=\"`basename $f | awk '{ac=split($0,a,\"[_.-]\");o=\"ManPage\";for(w=0;w<=ac;++w){o=o toupper(substr(a[w],1,1)) substr(a[w],2)};print o}'`.wiki\"\n    echo >> Makefile\n    echo $outname: ../mdoc2wiki.awk $f >> Makefile\n    echo \"\tawk -f ../mdoc2wiki.awk < $f > $outname\" >> Makefile\n    all=\"$all $outname\"\ndone\necho $all >>Makefile\ncd ..\n\n# Convert all of the manpages to -man format\n(cd man && make)\n# Format all of the manpages to text\n(cd text && make)\n# Format all of the manpages to PDF\n(cd pdf && make)\n# Format all of the manpages to HTML\n(cd html && make)\n# Format all of the manpages to Google Wiki syntax\n(cd wiki && make)\n", "num_lines": 108}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nfunction usage()\n{\n    cat <<EOF\nUsage: \n$0 xtrabackup_target [installation_directory]\n$0 path_to_server_tarball [installation_directory]\n\nPrepares a server binary directory to be used by run.sh when running XtraBackup\ntests.\n\nIf the argument is one of the build targets passed to build.sh \n(i.e. innodb51_builtin innodb51 innodb55 innodb56 xtradb51 xtradb55) then the \nappropriate Linux tarball is downloaded from a pre-defined location and\nunpacked into the specified installation  directory ('./server' by default).\n\nOtherwise the argument is assumed to be a path to a server binary tarball.\nEOF\n}\n\nif [ -z \"$1\" ]\nthen\n    usage\nfi\n\narch=\"`uname -m`\"\nif [ \"$arch\" = \"i386\" ]\nthen\n    arch=\"i686\"\nfi\n\nif [ \"$arch\" = \"i686\" ]\nthen\n    maria_arch_path=x86\nelse\n    maria_arch_path=amd64\nfi\n\ncase \"$1\" in\n    innodb50)\n        url=\"http://s3.amazonaws.com/percona.com/downloads/community\"\n        tarball=\"mysql-5.0.96-linux-$arch-glibc23.tar.gz\"\n\t;;\n\n    innodb51_builtin | innodb51)\n\turl=\"http://s3.amazonaws.com/percona.com/downloads/community\"\n\ttarball=\"mysql-5.1.49-linux-$arch-glibc23.tar.gz\"\n\t;;\n\n    innodb55)\n\turl=\"http://s3.amazonaws.com/percona.com/downloads/community\"\n\ttarball=\"mysql-5.5.16-linux2.6-$arch.tar.gz\"\n\t;;\n\n    innodb56)\n        url=\"http://s3.amazonaws.com/percona.com/downloads/community\"\n        tarball=\"mysql-5.6.10-linux-glibc2.5-$arch.tar.gz\"\n        ;;\n\n    xtradb51)\n\turl=\"http://www.percona.com/redir/downloads/Percona-Server-5.1/Percona-Server-5.1.60-13.1/binary/linux/$arch\"\n\ttarball=\"Percona-Server-5.1.60-rel13.1-413.Linux.$arch.tar.gz\"\n\t;;\n\n    xtradb55)\n\turl=\"http://s3.amazonaws.com/percona.com/downloads/Percona-Server-5.5/Percona-Server-5.5.11-20.2/Linux/binary\"\n\ttarball=\"Percona-Server-5.5.11-rel20.2-116.Linux.$arch.tar.gz\"\n\t;;\n\n    galera55)\n\turl=\"http://www.percona.com/downloads/Percona-XtraDB-Cluster/5.5.24-23.6/binary/linux/$arch\"\n\ttarball=\"Percona-XtraDB-Cluster-5.5.24-23.6.342.Linux.$arch.tar.gz\"\n\t#galera=1\n\t;;\n\n    mariadb51)\n\turl=\"ftp://ftp.osuosl.org/pub/mariadb/mariadb-5.1.62/kvm-bintar-hardy-$maria_arch_path\"\n\ttarball=\"mariadb-5.1.62-Linux-$arch.tar.gz\"\n\t;;\n\n    mariadb52)\n\turl=\"ftp://ftp.osuosl.org/pub/mariadb/mariadb-5.2.12/kvm-bintar-hardy-$maria_arch_path\"\n\ttarball=\"mariadb-5.2.12-Linux-$arch.tar.gz\"\n\t;;\n\n    mariadb53)\n\turl=\"ftp://ftp.osuosl.org/pub/mariadb/mariadb-5.3.9/kvm-bintar-hardy-$maria_arch_path\"\n\ttarball=\"mariadb-5.3.9-Linux-$arch.tar.gz\"\n\t;;\n\n    mariadb55)\n\turl=\"ftp://ftp.osuosl.org/pub/mariadb/mariadb-5.5.28/kvm-bintar-hardy-$maria_arch_path\"\n\ttarball=\"mariadb-5.5.28-linux-$arch.tar.gz\"\n\t;;\n\n    *)\n\tif ! test -r \"$1\"\n\tthen\n\t    echo \"$1 does not exist\"\n\t    exit 1\n\tfi\n\ttarball=\"$1\"\n\t;;\nesac\n\nif test -n \"$2\"\nthen\n    destdir=\"$2\"\nelse\n    destdir=\"./server\"\nfi\n\nif test -d \"$destdir\"\nthen\n    rm -rf \"$destdir\"\nfi\nmkdir \"$destdir\"\n\nif test ! $galera\nthen\n    if test -n \"$url\"\n    then\n\techo \"Downloading $tarball\"\n\twget -qc \"$url/$tarball\"\n    fi\n\n    echo \"Unpacking $tarball into $destdir\"\n    tar zxf $tarball -C $destdir \n    sourcedir=\"$destdir/`ls $destdir`\"\n    if test -n \"$sourcedir\"\n    then\n\tmv $sourcedir/* $destdir\n\trm -rf $sourcedir\n    fi\nelse\n    if test ! -d galerabuild\n    then\n\tbzr init-repo galerabuild\n    fi\n    cd galerabuild\n\n    rm -rf percona-xtradb-cluster\n    bzr branch lp:percona-xtradb-cluster percona-xtradb-cluster\n    rm -rf galera2x\n    bzr branch lp:galera/2.x galera2x\n    cd percona-xtradb-cluster\n    cmake -DENABLE_DTRACE=0 -DWITH_WSREP:BOOL=\"1\" -DCMAKE_INSTALL_PREFIX=\"../../server\"\n\n    if test -f /proc/cpuinfo\n    then\n\tMAKE_J=`grep '^processor' /proc/cpuinfo | wc -l`\n    else\n\tMAKE_J=4\n    fi\n\n    make -j$MAKE_J\n    make install\n\n    cd ../galera2x\n    ./scripts/build.sh\n    cp libgalera_smm.so ../../server/\n    cd ..\nfi\n", "num_lines": 167}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nXB_BUILD=\"autodetect\"\nwhile getopts \"fc:\" options; do\n\tcase $options in\n\t        c ) XB_BUILD=\"$OPTARG\";;\n\t\tf ) ;; # ignored\n\tesac\ndone\n\nrm -rf results/ var/ test_results.subunit \n\nCFLAGS=-g make testrun\n./testrun -c $XB_BUILD\n", "num_lines": 15}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#\n#  subunit.sh: shell functions to report test status via the subunit protocol.\n#  Copyright (C) 2006  Robert Collins <robertc@robertcollins.net>\n#\n#  Licensed under either the Apache License, Version 2.0 or the BSD 3-clause\n#  license at the users choice. A copy of both licenses are available in the\n#  project source as Apache-2.0 and BSD. You may not use this file except in\n#  compliance with one of these two licences.\n#  \n#  Unless required by applicable law or agreed to in writing, software\n#  distributed under these licenses is distributed on an \"AS IS\" BASIS, WITHOUT\n#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the\n#  license you chose for the specific language governing permissions and\n#  limitations under that license.\n#\n\nsubunit_start_test () {\n  # emit the current protocol start-marker for test $1\n  echo \"time: `date -u '+%Y-%m-%d %H:%M:%S'`\"\n  echo \"test: $1\"\n}\n\n\nsubunit_pass_test () {\n  # emit the current protocol test passed marker for test $1\n  echo \"time: `date -u '+%Y-%m-%d %H:%M:%S'`\"\n  echo \"success: $1\"\n}\n\n\nsubunit_fail_test () {\n  # emit the current protocol fail-marker for test $1, and emit stdin as\n  # the error text.\n  # we use stdin because the failure message can be arbitrarily long, and this\n  # makes it convenient to write in scripts (using <<END syntax.\n  echo \"time: `date -u '+%Y-%m-%d %H:%M:%S'`\"\n  echo \"failure: $1 [\"\n  cat -\n  echo \"]\"\n}\n\n\nsubunit_error_test () {\n  # emit the current protocol error-marker for test $1, and emit stdin as\n  # the error text.\n  # we use stdin because the failure message can be arbitrarily long, and this\n  # makes it convenient to write in scripts (using <<END syntax.\n  echo \"time: `date -u '+%Y-%m-%d %H:%M:%S'`\"\n  echo \"error: $1 [\"\n  cat -\n  echo \"]\"\n}\n\n\nsubunit_skip_test () {\n  # emit the current protocol test skipped marker for test $1\n  echo \"time: `date -u '+%Y-%m-%d %H:%M:%S'`\"\n  echo \"skip: $1\"\n}\n\n\n", "num_lines": 62}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport DEBUG=\n\n. inc/common.sh\n\ntrap kill_leftovers 1 2 3 15\n\nset +e\n\nresult=0\n\nfunction usage()\n{\ncat <<EOF\nUsage: $0 [-f] [-g] [-h] [-s suite] [-t test_name] [-d mysql_basedir] [-c build_conf]\n-f          Continue running tests after failures\n-d path     Server installation directory. Default is './server'.\n-g          Debug mode\n-t path     Run only a single named test\n-h          Print this help message\n-s suite    Select a test suite to run. Possible values: experimental, t. \n            Default is 't'.\n-c conf     XtraBackup build configuration as specified to build.sh.\n            Default is 'autodetect', i.e. xtrabackup binary is determined based\n            on the MySQL version.\nEOF\n}\n\nfunction find_program()\n{\n    local VARNAME=\"$1\"\n    shift\n    local PROGNAME=\"$1\"\n    shift\n    local DIRLIST=\"$*\"\n    local found=\"\"\n\n    for dir in in $DIRLIST\n    do\n\tif [ -d \"$dir\" -a -x \"$dir/$PROGNAME\" ]\n\tthen\n\t    eval \"$VARNAME=\\\"$dir/$PROGNAME\\\"\"\n\t    found=\"yes\"\n\t    break\n\tfi\n    done\n    if [ -z \"$found\" ]\n    then\n\techo \"Can't find $PROGNAME in $DIRLIST\"\n\texit -1\n    fi\n}\n\nfunction set_vars()\n{\n    TEST_BASEDIR=${TEST_BASEDIR:-\"$PWD\"}\n    MYSQL_BASEDIR=${MYSQL_BASEDIR:-\"$PWD/server\"}\n    PORT_BASE=$((3306 + $RANDOM))\n\n    if gnutar --version > /dev/null 2>&1\n    then\n\tTAR=gnutar\n    else\n\tTAR=tar\n    fi\n\n    find_program MYSQL_INSTALL_DB mysql_install_db $MYSQL_BASEDIR/bin \\\n\t$MYSQL_BASEDIR/scripts\n    find_program MYSQLD mysqld $MYSQL_BASEDIR/bin/ $MYSQL_BASEDIR/libexec\n    find_program MYSQL mysql $MYSQL_BASEDIR/bin\n    find_program MYSQLADMIN mysqladmin $MYSQL_BASEDIR/bin\n\n    # Check if we are running from a source tree and, if so, set PATH \n    # appropriately\n    if test \"`basename $PWD`\" = \"test\"\n    then\n\tPATH=\"$PWD/..:$PWD/../src:$PATH\"\n    fi\n\n    PATH=\"${MYSQL_BASEDIR}/bin:$PATH\"\n\n    if [ -z \"${LD_LIBRARY_PATH:-}\" ]; then\n\tLD_LIBRARY_PATH=$MYSQL_BASEDIR/lib/mysql\n    else\n\tLD_LIBRARY_PATH=$MYSQL_BASEDIR/lib/mysql:$LD_LIBRARY_PATH\n    fi\n\n    export TEST_BASEDIR PORT_BASE TAR MYSQL_BASEDIR MYSQL MYSQLD MYSQLADMIN \\\nMYSQL_INSTALL_DB PATH LD_LIBRARY_PATH\n}\n\nfunction get_version_info()\n{\n    MYSQLD_EXTRA_ARGS=\n\n    XB_BIN=\"\"\n    IB_ARGS=\"--user=root --ibbackup=$XB_BIN\"\n    XB_ARGS=\"--no-defaults\"\n\n    if [ \"$XB_BUILD\" != \"autodetect\" ]\n    then\n\tcase \"$XB_BUILD\" in\n\t    \"innodb50\" )\n\t\tXB_BIN=\"xtrabackup_51\";;\n\t    \"innodb51_builtin\" )\n\t\tXB_BIN=\"xtrabackup_51\";;\n\t    \"innodb51\" )\n\t\tXB_BIN=\"xtrabackup_plugin\"\n\t\tMYSQLD_EXTRA_ARGS=\"--ignore-builtin-innodb --plugin-load=innodb=ha_innodb_plugin.so\";;\n\t    \"innodb55\" )\n\t\tXB_BIN=\"xtrabackup_innodb55\";;\n            \"innodb56\" )\n                XB_BIN=\"xtrabackup_innodb56\" ;;\n\t    \"xtradb51\" | \"mariadb51\" | \"mariadb52\" | \"mariadb53\")\n\t\tXB_BIN=\"xtrabackup\";;\n\t    \"xtradb55\" | \"mariadb55\")\n\t\tXB_BIN=\"xtrabackup_55\";;\n\t    \"galera55\" )\n\t\tXB_BIN=\"xtrabackup_55\";;\n\tesac\n\tif [ -z \"$XB_BIN\" ]\n\tthen\n\t    vlog \"Unknown configuration: '$XB_BUILD'\"\n\t    exit -1\n\tfi\n    fi\n\n    MYSQL_VERSION=\"\"\n    INNODB_VERSION=\"\"\n\n    start_server >>$OUTFILE 2>&1\n\n    # Get MySQL and InnoDB versions\n    MYSQL_VERSION=`$MYSQL ${MYSQL_ARGS} -Nsf -e \"SHOW VARIABLES LIKE 'version'\"`\n    MYSQL_VERSION=${MYSQL_VERSION#\"version\t\"}\n    MYSQL_VERSION_COMMENT=`$MYSQL ${MYSQL_ARGS} -Nsf -e \"SHOW VARIABLES LIKE 'version_comment'\"`\n    MYSQL_VERSION_COMMENT=${MYSQL_VERSION_COMMENT#\"version_comment\t\"}\n    INNODB_VERSION=`$MYSQL ${MYSQL_ARGS} -Nsf -e \"SHOW VARIABLES LIKE 'innodb_version'\"`\n    INNODB_VERSION=${INNODB_VERSION#\"innodb_version\t\"}\n    XTRADB_VERSION=\"`echo $INNODB_VERSION  | sed 's/[0-9]\\.[0-9]\\.[0-9][0-9]*\\(-[0-9][0-9]*\\.[0-9][0-9]*\\)*$/\\1/'`\"\n\n    # Version-specific defaults\n    DEFAULT_IBDATA_SIZE=\"10M\"\n\n    # Determine MySQL flavor\n    if [[ \"$MYSQL_VERSION\" =~ \"MariaDB\" ]]\n    then\n\tMYSQL_FLAVOR=\"MariaDB\"\n    elif [ -n \"$XTRADB_VERSION\" ]\n    then\n\tMYSQL_FLAVOR=\"Percona Server\"\n    else\n\tMYSQL_FLAVOR=\"MySQL\"\n    fi\n\n    # Determine InnoDB flavor\n    if [ -n \"$XTRADB_VERSION\" ]\n    then\n\tINNODB_FLAVOR=\"XtraDB\"\n    else\n\tINNODB_FLAVOR=\"innoDB\"\n    fi\n\n    if [ \"$XB_BUILD\" = \"autodetect\" ]\n    then\n        # Determine xtrabackup build automatically\n\tif [ \"${MYSQL_VERSION:0:3}\" = \"5.0\" ]\n\tthen\n\t    XB_BIN=\"xtrabackup_51\"\n\telif [ \"${MYSQL_VERSION:0:3}\" = \"5.1\" ]\n\tthen\n\t    if [ -z \"$INNODB_VERSION\" ]\n\t    then\n\t\tXB_BIN=\"xtrabackup_51\" # InnoDB 5.1 builtin\n\t    else\n\t\tXB_BIN=\"xtrabackup\"    # InnoDB 5.1 plugin or Percona Server 5.1\n\t    fi\n\telif [ \"${MYSQL_VERSION:0:3}\" = \"5.2\" -o\n\t       \"${MYSQL_VERSION:0:3}\" = \"5.3\"]\n\tthen\n\t    XB_BIN=\"xtrabackup\"\n\telif [ \"${MYSQL_VERSION:0:3}\" = \"5.5\" ]\n\tthen\n\t    if [ -n \"$XTRADB_VERSION\" ]\n\t    then\n\t\tXB_BIN=\"xtrabackup_55\"\n\t    else\n\t\tXB_BIN=\"xtrabackup_innodb55\"\n\t    fi\n        elif [ \"${MYSQL_VERSION:0:3}\" = \"5.6\" ]\n        then\n            XB_BIN=\"xtrabackup_innodb56\"\n            DEFAULT_IBDATA_SIZE=\"12M\"\n\telse\n\t    vlog \"Unknown MySQL/InnoDB version: $MYSQL_VERSION/$INNODB_VERSION\"\n\t    exit -1\n\tfi\n    fi\n\n    XB_PATH=\"`which $XB_BIN`\"\n    if [ -z \"$XB_PATH\" ]\n    then\n\tvlog \"Cannot find '$XB_BIN' in PATH\"\n\treturn 1\n    fi\n    XB_BIN=\"$XB_PATH\"\n\n    # Set the correct binary for innobackupex\n    IB_BIN=\"`which innobackupex`\"\n    if [ -z \"$IB_BIN\" ]\n    then\n\tvlog \"Cannot find 'innobackupex' in PATH\"\n\treturn 1\n    fi\n\n    stop_server\n\n    export MYSQL_VERSION MYSQL_VERSION_COMMENT MYSQL_FLAVOR \\\n\tINNODB_VERSION XTRADB_VERSION INNODB_FLAVOR \\\n\tXB_BIN IB_BIN IB_ARGS XB_ARGS MYSQLD_EXTRA_ARGS \\\n        DEFAULT_IBDATA_SIZE\n}\n\nexport SKIPPED_EXIT_CODE=200\n\ntname=\"\"\nXTRACE_OPTION=\"\"\nXB_BUILD=\"autodetect\"\nforce=\"\"\nKEEP_RESULTS=0\nSUBUNIT_OUT=test_results.subunit\n\nwhile getopts \"fgh?:t:s:d:c:b:nr:\" options; do\n\tcase $options in\n\t        f ) force=\"yes\";;\n\t\tt ) tname=\"$OPTARG\";;\n\t\tg ) XTRACE_OPTION=\"-x\"; DEBUG=on;;\n\t\th ) usage; exit;;\n\t\ts ) tname=\"$OPTARG/*.sh\";;\n\t        d ) export MYSQL_BASEDIR=\"$OPTARG\";;\n\t        b ) TEST_BASEDIR=\"$OPTARG\";;\n\t        c ) XB_BUILD=\"$OPTARG\";;\n\t        n ) KEEP_RESULTS=1;;\n\t        r ) SUBUNIT_OUT=\"$OPTARG\";;\n\t\t? ) echo \"Use \\`$0 -h' for the list of available options.\"\n                    exit -1;;\n\tesac\ndone\n\nif [ $KEEP_RESULTS -eq 0 ];\nthen\n    rm -rf results\n    rm -f $SUBUNIT_OUT\nfi\nmkdir results\n\nset_vars\n\nif [ -n \"$tname\" ]\nthen\n   tests=\"$tname\"\nelse\n   tests=\"t/*.sh\"\nfi\n\nfailed_count=0\nfailed_tests=\ntotal_count=0\n\nexport OUTFILE=\"$PWD/results/setup\"\n\nclean >>$OUTFILE 2>&1\n\nif ! get_version_info\nthen\n    echo \"get_version_info failed. See $OUTFILE for details.\"\n    exit -1\nfi\n\necho \"Running against $MYSQL_FLAVOR $MYSQL_VERSION ($INNODB_FLAVOR $INNODB_VERSION)\" |\n  tee -a $OUTFILE\n\necho \"Using '`basename $XB_BIN`' as xtrabackup binary\" | tee -a $OUTFILE\necho | tee -a $OUTFILE\n\nkill_leftovers >>$OUTFILE 2>&1\nclean >>$OUTFILE 2>&1\n\nsource subunit.sh\n\necho \"========================================================================\"\n\nfor t in $tests\ndo\n   total_count=$((total_count+1))\n\n   printf \"%-40s\" $t\n   subunit_start_test $t >> $SUBUNIT_OUT\n   name=`basename $t .sh`\n   export OUTFILE=\"$PWD/results/$name\"\n   export SKIPPED_REASON=\"$PWD/results/$name.skipped\"\n   bash $XTRACE_OPTION $t > $OUTFILE 2>&1\n   rc=$?\n\n   if [[ -z \"$DEBUG\" || -n \"$force\" ]]\n   then\n       kill_leftovers >>$OUTFILE 2>&1\n       clean >>$OUTFILE 2>&1\n   fi\n\n   if [ $rc -eq 0 ]\n   then\n       echo \"[passed]\"\n       subunit_pass_test $t >> $SUBUNIT_OUT\n   elif [ $rc -eq $SKIPPED_EXIT_CODE ]\n   then\n       sreason=\"\"\n       test -r $SKIPPED_REASON && sreason=`cat $SKIPPED_REASON`\n       echo \"[skipped]    $sreason\"\n       subunit_skip_test $t >> $SUBUNIT_OUT\n   else\n       echo \"[failed]\"\n\n       (\n\t   (echo \"Something went wrong running $t. Exited with $rc\";\n\t       echo; echo; cat $OUTFILE\n\t   ) | subunit_fail_test $t\n       ) >> $SUBUNIT_OUT\n\n       failed_count=$((failed_count+1))\n       failed_tests=\"$failed_tests $t\"\n       result=1\n       if [ -z \"$force\" ]\n       then\n\t   break;\n       fi\n   fi       \ndone\n\necho \"========================================================================\"\necho\n\nif [ $result -eq 1 ]\nthen\n    echo\n    echo \"$failed_count/$total_count tests have failed: $failed_tests\"\n    echo \"See results/ for detailed output\"\n    exit -1\nfi\n", "num_lines": 351}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --interactive_timeout=1 --wait_timeout=1\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nmkdir -p $topdir/backup\ninnobackupex  $topdir/backup > $OUTFILE 2>&1\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup dir in $backup_dir\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\necho \"###########\" >> $OUTFILE\necho \"# PREPARE #\" >> $OUTFILE\necho \"###########\" >> $OUTFILE\ninnobackupex --apply-log $backup_dir >> $OUTFILE 2>&1\n\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\necho \"###########\" >> $OUTFILE\necho \"# RESTORE #\" >> $OUTFILE\necho \"###########\" >> $OUTFILE\ninnobackupex --copy-back $full_backup_dir >> $OUTFILE 2>&1\n\nstart_server\n# Check sakila\n${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 33}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nfunction race_create_drop()\n{\n  vlog \"Started create/drop table cycle\"\n  race_cycle_num=$1\n  if [ -z $race_cycle_num ]\n  then\n    race_cycle_num=1000\n  fi\n  run_cmd ${MYSQL} ${MYSQL_ARGS} -e \"create database race;\"\n  race_cycle_cnt=0;\n  while [ \"$race_cycle_num\" -gt \"$race_cycle_cnt\"]\n  do\n\tt1=tr$RANDOM\n\tt2=tr$RANDOM\n\tt3=tr$RANDOM\n\t${MYSQL} ${MYSQL_ARGS} -e \"create table $t1 (a int) ENGINE=InnoDB;\" race\n\t${MYSQL} ${MYSQL_ARGS} -e \"create table $t2 (a int) ENGINE=InnoDB;\" race\n\t${MYSQL} ${MYSQL_ARGS} -e \"create table $t3 (a int) ENGINE=InnoDB;\" race\n\t${MYSQL} ${MYSQL_ARGS} -e \"drop table $t1;\" race\n\t${MYSQL} ${MYSQL_ARGS} -e \"drop table $t2;\" race\n\t${MYSQL} ${MYSQL_ARGS} -e \"drop table $t3;\" race\n\tlet \"race_cycle_cnt=race_cycle_cnt+1\"\n  done\n}\n\nstart_server --innodb_file_per_table\n\nrun_cmd race_create_drop &\n\nsleep 3\n# Full backup\nmkdir -p $topdir/data/full\nvlog \"Starting backup\"\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full\nvlog \"Full backup done\"\n", "num_lines": 38}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "set -eu\n\nfunction innobackupex()\n{\n    run_cmd $IB_BIN $IB_ARGS $*\n}\n\nfunction xtrabackup()\n{\n    run_cmd $XB_BIN $XB_ARGS $*\n}\n\nfunction vlog\n{\n    echo \"`date +\"%F %T\"`: `basename \"$0\"`: $@\" >&2\n}\n\n\nfunction clean()\n{\n    rm -rf ${TEST_BASEDIR}/var[0-9]\n}\n\nfunction die()\n{\n  vlog \"$*\" >&2\n  exit 1\n}\n\nfunction init_mysql_dir()\n{\n    if [ ! -d \"$MYSQLD_VARDIR\" ]\n    then\n\tvlog \"Creating server root directory: $MYSQLD_VARDIR\"\n\tmkdir \"$MYSQLD_VARDIR\"\n    fi\n    if [ ! -d \"$MYSQLD_TMPDIR\" ]\n    then\n\tvlog \"Creating server temporary directory: $MYSQLD_TMPDIR\"\n\tmkdir \"$MYSQLD_TMPDIR\"\n    fi\n    if [ ! -d \"$MYSQLD_DATADIR\" ]\n    then\n\tvlog \"Creating server data directory: $MYSQLD_DATADIR\"\n\tmkdir -p \"$MYSQLD_DATADIR\"\n\tvlog \"Calling mysql_install_db\"\n\t$MYSQL_INSTALL_DB --no-defaults --basedir=$MYSQL_BASEDIR --datadir=\"$MYSQLD_DATADIR\" --tmpdir=\"$MYSQLD_TMPDIR\" ${MYSQLD_EXTRA_ARGS}\n    fi\n}\n\n########################################################################\n# Checks whether MySQL is alive\n########################################################################\nfunction mysql_ping()\n{\n    $MYSQLADMIN $MYSQL_ARGS --wait=100 ping >/dev/null 2>&1 || return 1\n}\n\nfunction kill_leftovers()\n{\n    local file\n    for file in ${TEST_BASEDIR}/mysqld*.pid\n    do\n\tif [ -f $file ]\n\tthen\n\t    vlog \"Found a leftover mysqld processes with PID `cat $file`, stopping it\"\n\t    kill -9 `cat $file` 2>/dev/null || true\n\t    rm -f $file\n\tfi\n    done\n}\n\nfunction run_cmd()\n{\n  vlog \"===> $@\"\n  set +e\n  \"$@\"\n  local rc=$?\n  set -e\n  if [ $rc -ne 0 ]\n  then\n      die \"===> `basename $1` failed with exit code $rc\"\n  fi\n}\n\nfunction run_cmd_expect_failure()\n{\n  vlog \"===> $@\"\n  set +e\n  \"$@\"\n  local rc=$?\n  set -e\n  if [ $rc -eq 0 ]\n  then\n      die \"===> `basename $1` succeeded when it was expected to fail\"\n  fi\n}\n\nfunction load_sakila()\n{\nvlog \"Loading sakila\"\n${MYSQL} ${MYSQL_ARGS} -e \"create database sakila\"\nvlog \"Loading sakila scheme\"\n${MYSQL} ${MYSQL_ARGS} sakila < inc/sakila-db/sakila-schema.sql\nvlog \"Loading sakila data\"\n${MYSQL} ${MYSQL_ARGS} sakila < inc/sakila-db/sakila-data.sql\n}\n\nfunction load_dbase_schema()\n{\nvlog \"Loading $1 database schema\"\n${MYSQL} ${MYSQL_ARGS} -e \"create database $1\"\n${MYSQL} ${MYSQL_ARGS} $1 < inc/$1-db/$1-schema.sql\n}\n\nfunction load_dbase_data()\n{\nvlog \"Loading $1 database data\"\n${MYSQL} ${MYSQL_ARGS} $1 < inc/$1-db/$1-data.sql\n}\n\nfunction drop_dbase()\n{\n  vlog \"Dropping database $1\"\n  run_cmd ${MYSQL} ${MYSQL_ARGS} -e \"DROP DATABASE $1\"\n}\n\n########################################################################\n# Choose a free port for a MySQL server instance\n########################################################################\nfunction get_free_port()\n{\n    local id=$1\n    local port\n    local lockfile\n\n    for (( port=PORT_BASE+id; port < 65535; port++))\n    do\n\tlockfile=\"/tmp/xtrabackup_port_lock.$port\"\n\t# Try to atomically lock the current port number\n\tif ! set -C > $lockfile\n\tthen\n\t    set +C\n\t    # check if the process still exists\n\t    if kill -0 \"`cat $lockfile`\"\n\t    then\n\t\tcontinue;\n\t    fi\n\t    # stale file, overwrite it with the current PID\n\tfi\n\tset +C\n\techo $$ > $lockfile\n\tif ! nc -z -w1 localhost $port >/dev/null 2>&1\n\tthen\n\t    echo $port\n\t    return 0\n\tfi\n\trm -f $lockfile\n    done\n\n    die \"Could not find a free port for server id $id!\"\n}\n\nfunction free_reserved_port()\n{\n   local port=$1\n\n   rm -f /tmp/xtrabackup_port_lock.${port}\n}\n\n\n########################################################################\n# Initialize server variables such as datadir, tmpdir, etc. and store\n# them with the specified index in SRV_MYSQLD_* arrays to be used by\n# switch_server() later\n########################################################################\nfunction init_server_variables()\n{\n    local id=$1\n\n    if [ -n ${SRV_MYSQLD_IDS[$id]:-\"\"} ]\n    then\n\tdie \"Server with id $id has already been started\"\n    fi\n\n    SRV_MYSQLD_IDS[$id]=\"$id\"\n    local vardir=\"${TEST_BASEDIR}/var${id}\"\n    SRV_MYSQLD_VARDIR[$id]=\"$vardir\"\n    SRV_MYSQLD_DATADIR[$id]=\"$vardir/data\"\n    SRV_MYSQLD_TMPDIR[$id]=\"$vardir/tmp\"\n    SRV_MYSQLD_PIDFILE[$id]=\"${TEST_BASEDIR}/mysqld${id}.pid\"\n    SRV_MYSQLD_PORT[$id]=`get_free_port $id`\n    SRV_MYSQLD_SOCKET[$id]=`mktemp -t xtrabackup.mysql.sock.XXXXXX`\n}\n\n########################################################################\n# Reset server variables\n########################################################################\nfunction reset_server_variables()\n{\n    local id=$1\n\n    if [ -z ${SRV_MYSQLD_VARDIR[$id]:-\"\"} ]\n    then\n\t# Variables have already been reset\n\treturn 0;\n    fi\n\n    SRV_MYSQLD_IDS[$id]=\n    SRV_MYSQLD_VARDIR[$id]=\n    SRV_MYSQLD_DATADIR[$id]=\n    SRV_MYSQLD_TMPDIR[$id]=\n    SRV_MYSQLD_PIDFILE[$id]=\n    SRV_MYSQLD_PORT[$id]=\n    SRV_MYSQLD_SOCKET[$id]=\n}\n\n##########################################################################\n# Change the environment to make all utilities access the server with an\n# id specified in the argument.\n##########################################################################\nfunction switch_server()\n{\n    local id=$1\n\n    MYSQLD_VARDIR=\"${SRV_MYSQLD_VARDIR[$id]}\"\n    MYSQLD_DATADIR=\"${SRV_MYSQLD_DATADIR[$id]}\"\n    MYSQLD_TMPDIR=\"${SRV_MYSQLD_TMPDIR[$id]}\"\n    MYSQLD_PIDFILE=\"${SRV_MYSQLD_PIDFILE[$id]}\"\n    MYSQLD_PORT=\"${SRV_MYSQLD_PORT[$id]}\"\n    MYSQLD_SOCKET=\"${SRV_MYSQLD_SOCKET[$id]}\"\n\n    MYSQL_ARGS=\"--no-defaults --socket=${MYSQLD_SOCKET} --user=root\"\n    MYSQLD_ARGS=\"--no-defaults --basedir=${MYSQL_BASEDIR} \\\n--socket=${MYSQLD_SOCKET} --port=${MYSQLD_PORT} --server-id=$id \\\n--datadir=${MYSQLD_DATADIR} --tmpdir=${MYSQLD_TMPDIR} --log-bin=mysql-bin \\\n--relay-log=mysql-relay-bin --pid-file=${MYSQLD_PIDFILE} ${MYSQLD_EXTRA_ARGS}\"\n    if [ \"`whoami`\" = \"root\" ]\n    then\n\tMYSQLD_ARGS=\"$MYSQLD_ARGS --user=root\"\n    fi\n\n    export MYSQL_HOME=$MYSQLD_VARDIR\n\n    IB_ARGS=\"--user=root --socket=${MYSQLD_SOCKET} --ibbackup=$XB_BIN\"\n    XB_ARGS=\"--no-defaults\"\n\n    # Some aliases for compatibility, as tests use the following names\n    topdir=\"$MYSQLD_VARDIR\"\n    mysql_datadir=\"$MYSQLD_DATADIR\"\n    mysql_tmpdir=\"$MYSQLD_TMPDIR\"\n    mysql_socket=\"$MYSQLD_SOCKET\"\n}\n\n########################################################################\n# Start server with the id specified as the first argument\n########################################################################\nfunction start_server_with_id()\n{\n    local id=$1\n    shift\n\n    vlog \"Starting server with id=$id...\"\n\n    init_server_variables $id\n    switch_server $id\n\n    init_mysql_dir\n    cat > ${MYSQLD_VARDIR}/my.cnf <<EOF\n[mysqld]\ndatadir=${MYSQLD_DATADIR}\ntmpdir=${MYSQLD_TMPDIR}\n\n[xtrabackup]\n${XB_EXTRA_MY_CNF_OPTS:-}\nEOF\n\n    # Start the server\n    ${MYSQLD} ${MYSQLD_ARGS} $* &\n    if ! mysql_ping\n    then\n        die \"Can't start the server!\"\n    fi\n    vlog \"Server with id=$id has been started on port $MYSQLD_PORT, \\\nsocket $MYSQLD_SOCKET\"\n}\n\n########################################################################\n# Stop server with the id specified as the first argument and additional\n# command line arguments (if specified)\n########################################################################\nfunction stop_server_with_id()\n{\n    local id=$1\n    switch_server $id\n\n    vlog \"Stopping server with id=$id...\"\n\n    if [ -f \"${MYSQLD_PIDFILE}\" ]\n    then\n\t${MYSQLADMIN} ${MYSQL_ARGS} --shutdown-timeout=60 shutdown\n\tif [ -f \"${MYSQLD_PIDFILE}\" ]\n\tthen\n\t    vlog \"Could not stop the server with id=$id, using kill -9\"\n\t    kill -9 `cat ${MYSQLD_PIDFILE}`\n\t    rm -f ${MYSQLD_PIDFILE}\n\tfi\n\tvlog \"Server with id=$id has been stopped\"\n    else\n\tvlog \"Server pid file '${MYSQLD_PIDFILE}' doesn't exist!\"\n    fi\n\n    # unlock the port number\n    free_reserved_port $MYSQLD_PORT\n\n    reset_server_variables $id\n}\n\n########################################################################\n# Start server with id=1 and additional command line arguments\n# (if specified)\n########################################################################\nfunction start_server()\n{\n    start_server_with_id 1 $*\n}\n\n########################################################################\n# Stop server with id=1\n########################################################################\nfunction stop_server()\n{\n    stop_server_with_id 1\n}\n\n########################################################################\n# Stop all running servers\n########################################################################\nfunction stop_all_servers()\n{\n    local id\n    for id in ${SRV_MYSQLD_IDS[*]}\n    do\n\tstop_server_with_id ${SRV_MYSQLD_IDS[$id]}\n    done\n}\n\n########################################################################\n# Configure a specified server as a slave\n# Synopsis:\n#   setup_slave <slave_id> <master_id>\n#########################################################################\nfunction setup_slave()\n{\n    local slave_id=$1\n    local master_id=$2\n\n    vlog \"Setting up server #$slave_id as a slave of server #$master_id\"\n\n    switch_server $slave_id\n\n    run_cmd $MYSQL $MYSQL_ARGS <<EOF\nCHANGE MASTER TO\n  MASTER_HOST='localhost',\n  MASTER_USER='root',\n  MASTER_PORT=${SRV_MYSQLD_PORT[$master_id]};\n\nSTART SLAVE\nEOF\n}\n\n########################################################################\n# Wait until slave catches up with master.\n# The timeout is hardcoded to 300 seconds\n#\n# Synopsis:\n#   sync_slave_with_master <slave_id> <master_id>\n#########################################################################\nfunction sync_slave_with_master()\n{\n    local slave_id=$1\n    local master_id=$2\n    local count\n    local master_file\n    local master_pos\n\n    vlog \"Syncing slave (id=#$slave_id) with master (id=#$master_id)\"\n\n    # Get master log pos\n    switch_server $master_id\n    count=0\n    while read line; do\n      \tif [ $count -eq 1 ] # File:\n      \tthen\n      \t    master_file=`echo \"$line\" | sed s/File://`\n      \telif [ $count -eq 2 ] # Position:\n      \tthen\n      \t    master_pos=`echo \"$line\" | sed s/Position://`\n      \tfi\n      \tcount=$((count+1))\n    done <<< \"`run_cmd $MYSQL $MYSQL_ARGS -Nse 'SHOW MASTER STATUS\\G' mysql`\"\n\n    echo \"master_file=$master_file, master_pos=$master_pos\"\n\n    # Wait for the slave SQL thread to catch up\n    switch_server $slave_id\n\n    run_cmd $MYSQL $MYSQL_ARGS <<EOF\nSELECT MASTER_POS_WAIT('$master_file', $master_pos, 300);\nEOF\n}\n\n########################################################################\n# Prints checksum for a given table.\n# Expects 2 arguments: $1 is the DB name and $2 is the table to checksum\n########################################################################\nfunction checksum_table()\n{\n    $MYSQL $MYSQL_ARGS -Ns -e \"CHECKSUM TABLE $2 EXTENDED\" $1 | awk {'print $2'}\n}\n\n########################################################################\n# Workarounds for a bug in grep 2.10 when grep -q file > file would\n# result in a failure.\n########################################################################\nfunction grep()\n{\n    command grep \"$@\" | cat\n    return ${PIPESTATUS[0]}\n}\n\nfunction egrep()\n{\n    command egrep \"$@\" | cat\n    return ${PIPESTATUS[0]}\n}\n\n##############################################################\n# Helper functions for xtrabackup process suspend and resume #\n##############################################################\nfunction wait_for_xb_to_suspend()\n{\n    local file=$1\n    local i=0\n    echo \"Waiting for $file to be created\"\n    while [ ! -r $file ]\n    do\n        sleep 1\n        i=$((i+1))\n        echo \"Waited $i seconds for xtrabackup_suspended to be created\"\n    done\n}\n\nfunction resume_suspended_xb()\n{\n    local file=$1\n    echo \"Removing $file\"\n    kill -SIGCONT `cat $file`\n}\n\n# To avoid unbound variable error when no server have been started\nSRV_MYSQLD_IDS=\n", "num_lines": 463}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "\n\nfunction check_partitioning()\n{\n   $MYSQL $MYSQL_ARGS -Ns -e \"show variables like 'have_partitioning'\"\n}\n\nfunction require_partitioning()\n{\n\tPARTITION_CHECK=`check_partitioning`\n\n\tif [ -z \"$PARTITION_CHECK\" ]; then\n\t    echo \"Requires Partitioning.\" > $SKIPPED_REASON\n\t    exit $SKIPPED_EXIT_CODE\n\tfi\n}\n\nfunction ib_part_schema()\n{\n\ttopdir=$1\n\tengine=$2\n\n\tcat <<EOF\nCREATE TABLE test (\n  a int(11) DEFAULT NULL\n) ENGINE=$engine DEFAULT CHARSET=latin1\nPARTITION BY RANGE (a)\n(PARTITION p0 VALUES LESS THAN (100) ENGINE = $engine,\n PARTITION P1 VALUES LESS THAN (200) ENGINE = $engine,\n PARTITION p2 VALUES LESS THAN (300)\n   DATA DIRECTORY = '$topdir/ext' INDEX DIRECTORY = '$topdir/ext'\n   ENGINE = $engine,\n PARTITION p3 VALUES LESS THAN (400)\n   DATA DIRECTORY = '$topdir/ext' INDEX DIRECTORY = '$topdir/ext'\n   ENGINE = $engine,\n PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = $engine);\nEOF\n}\n\nfunction ib_part_data()\n{\n\techo 'INSERT INTO test VALUES (1), (101), (201), (301), (401);';\n}\n\nfunction ib_part_init()\n{\n\ttopdir=$1\n\tengine=$2\n\n\tif [ -d $topdir/ext ] ; then\n\t\trm -rf $topdir/ext\n\tfi\n\tmkdir -p $topdir/ext\n\n\tib_part_schema $topdir $engine | run_cmd $MYSQL $MYSQL_ARGS test\n\tib_part_data $topdir $engine | run_cmd $MYSQL $MYSQL_ARGS test\n}\n\nfunction ib_part_restore()\n{\n\ttopdir=$1\n\tmysql_datadir=$2\n\n\t# Remove database\n\trm -rf $mysql_datadir/test/*\n\trm -rf $topdir/ext/*\n\tvlog \"Original database removed\"\n\n\t# Restore database from backup\n\tcp -rv $topdir/backup/test/* $mysql_datadir/test\n\tvlog \"database restored from backup\"\n\n}\n\nfunction ib_part_assert_checksum()\n{\n\tchecksum_a=$1\n\n\tvlog \"Checking checksums\"\n\tchecksum_b=`checksum_table test test`\n\n\tvlog \"Checksums are $checksum_a and $checksum_b\"\n\n\tif [ \"$checksum_a\" != \"$checksum_b\" ]\n\tthen \n\t\tvlog \"Checksums are not equal\"\n\t\texit -1\n\tfi\n\n\tvlog \"Checksums are OK\"\n\n}\n", "num_lines": 93}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Common code for ib_stream_*.sh tests.\n# Expects the following variables to be set appropriately before \n# including:\n#   stream_format: passed to the --stream innobackupex option\n#   stream_extract_cmd: shell command to be used to extract the stream\n#\n# Optionally the following variables may be set:\n#   innobackupex_option:  additional options to be passed to innobackupex.\n#   stream_uncompress_cmd: command used to uncompress data streamed data\n############################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\ninnobackupex_options=${innobackupex_options:-\"\"}\n\n# Take backup\nmkdir -p $topdir/backup\ninnobackupex --stream=$stream_format $innobackupex_options $topdir/backup > $topdir/backup/out\n\nstop_server\n\n# Remove datadir\nrm -r $mysql_datadir\n\n# Restore sakila\nvlog \"Applying log\"\nbackup_dir=$topdir/backup\ncd $backup_dir\nrun_cmd bash -c \"$stream_extract_cmd out\"\ntest -n \"${stream_uncompress_cmd:-\"\"}\" && run_cmd bash -c \"$stream_uncompress_cmd\";\ncd - >/dev/null 2>&1 \nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $backup_dir\n\nstart_server\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 52}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #1002688: innobackupex incremental apply-log copies to wrong directory\n############################################################################\n. inc/common.sh\n\nstart_server --innodb_file_per_table\nload_sakila\n\n# Full backup\n# backup root directory\nvlog \"Starting backup\"\n\nfull_backup_dir=$topdir/full_backup\ninnobackupex  --no-timestamp $full_backup_dir\n\n# Changing data\n\nrun_cmd $MYSQL $MYSQL_ARGS -e \"CREATE DATABASE newdb\"\nrun_cmd $MYSQL $MYSQL_ARGS -e \\\n    \"CREATE TABLE actor_copy ENGINE=MyISAM SELECT * FROM sakila.actor\" newdb\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table newdb actor_copy`\ntest -n \"$checksum_a\" || die \"Failed to checksum table actor_copy\"\n\nvlog \"Making incremental backup\"\n\n# Incremental backup\ninc_backup_dir=$topdir/incremental_backup\ninnobackupex --incremental --no-timestamp \\\n    --incremental-basedir=$full_backup_dir $inc_backup_dir\nvlog \"Incremental backup created in directory $inc_backup_dir\"\n\nvlog \"Preparing backup\"\ninnobackupex --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\n\ninnobackupex --apply-log --redo-only --incremental-dir=$inc_backup_dir/ \\\n    $full_backup_dir\nvlog \"Delta applied to full backup\"\n\ninnobackupex --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files to their original locations\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table\n\nvlog \"Checking checksums\"\nchecksum_b=`checksum_table newdb actor_copy`\n\nvlog \"Old checksum: $checksum_a\"\nvlog \"New checksum: $checksum_b\"\n\nif [ \"$checksum_a\" != \"$checksum_b\"  ]\nthen \n    vlog \"Checksums do not match\"\n    exit -1\nfi\n", "num_lines": 68}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #1007446: innobackupex should remove stale xtrabackup_suspended file\n############################################################################\n\n. inc/common.sh\n\nstart_server\n\necho \"\" > $MYSQLD_TMPDIR/xtrabackup_suspended\n\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > /dev/null\n\ngrep -q \"A left over instance of suspend file\" $OUTFILE\n", "num_lines": 15}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nmysqld_additional_args=\"--innodb_file_per_table\"\n  \nstart_server ${mysqld_additional_args}\n\nload_dbase_schema incremental_sample\n\n# Full backup\n\n# Full backup folder\nrm -rf $topdir/data/full\nmkdir -p $topdir/data/full\n# Incremental data\nrm -rf $topdir/data/delta\nmkdir -p $topdir/data/delta\n\nvlog \"Starting backup\"\n\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full \\\n    $mysqld_additional_args\n\nvlog \"Full backup done\"\n\n# Changing data in sakila\n\nvlog \"Making changes to database\"\n\n${MYSQL} ${MYSQL_ARGS} -e \"CREATE TABLE t2 (a INT(11) DEFAULT NULL, \\\n number INT(11) DEFAULT NULL) ENGINE=INNODB\" incremental_sample\n${MYSQL} ${MYSQL_ARGS} -e \"INSERT INTO t2 VALUES (1, 1)\" incremental_sample\n  \nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_t2_a=`checksum_table incremental_sample t2`\n\nvlog \"Table 't2' checksum is $checksum_t2_a\"\n\nvlog \"Making incremental backup\"\n\n# Incremental backup\nxtrabackup --datadir=$mysql_datadir --backup \\\n    --target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full \\\n    $mysqld_additional_args\n\nvlog \"Incremental backup done\"\nvlog \"Preparing backup\"\n\n# Prepare backup\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full $mysqld_additional_args\nvlog \"Log applied to backup\"\n\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta \\\n    $mysqld_additional_args\nvlog \"Delta applied to backup\"\n\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/full \\\n    $mysqld_additional_args\nvlog \"Data prepared for restore\"\n\n# removing rows\n${MYSQL} ${MYSQL_ARGS} -e \"delete from t2;\" incremental_sample\nvlog \"Table cleared\"\n\n# Restore backup\n\nstop_server\n\nvlog \"Copying files\"\n\ncd $topdir/data/full/\ncp -r * $mysql_datadir\ncd -\n\nvlog \"Data restored\"\n\nstart_server ${mysqld_additional_args}\n\nvlog \"Checking checksums\"\nchecksum_t2_b=`checksum_table incremental_sample t2`\n\nif [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\nthen \n    vlog \"Checksums of table 't2' are not equal\"\n    exit -1\nfi\n\nvlog \"Checksums are OK\"\n\nstop_server\n", "num_lines": 94}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nif [ -z \"$INNODB_VERSION\" ]; then\n    echo \"Requires InnoDB plugin or XtraDB\" >$SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nfunction test_bug_1028949()\n{\n  page_size=$1\n\n  mysqld_additional_args=\"--innodb_file_per_table --innodb_strict_mode \\\n--innodb_file_format=Barracuda\"\n  \n  start_server ${mysqld_additional_args}\n\n  load_dbase_schema incremental_sample\n\n  # Full backup\n\n  # Full backup folder\n  rm -rf $topdir/data/full\n  mkdir -p $topdir/data/full\n  # Incremental data\n  rm -rf $topdir/data/delta\n  mkdir -p $topdir/data/delta\n\n  vlog \"Starting backup\"\n\n  xtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full \\\n      $mysqld_additional_args\n\n  vlog \"Full backup done\"\n\n  # Changing data in sakila\n\n  vlog \"Making changes to database\"\n\n  ${MYSQL} ${MYSQL_ARGS} -e \"CREATE TABLE t2 (a INT(11) DEFAULT NULL, \\\n number INT(11) DEFAULT NULL) ENGINE=INNODB\\\n ROW_FORMAT=compressed KEY_BLOCK_SIZE=$page_size\" incremental_sample\n  ${MYSQL} ${MYSQL_ARGS} -e \"INSERT INTO t2 VALUES (1, 1)\" incremental_sample\n  \n  vlog \"Changes done\"\n\n  # Saving the checksum of original table\n  checksum_t2_a=`checksum_table incremental_sample t2`\n\n  vlog \"Table 't2' checksum is $checksum_t2_a\"\n\n  vlog \"Making incremental backup\"\n\n  # Incremental backup\n  xtrabackup --datadir=$mysql_datadir --backup \\\n      --target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full \\\n      $mysqld_additional_args\n\n  vlog \"Incremental backup done\"\n  vlog \"Preparing backup\"\n\n  # Prepare backup\n  xtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n      --target-dir=$topdir/data/full $mysqld_additional_args\n  vlog \"Log applied to backup\"\n\n  xtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n      --target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta \\\n      $mysqld_additional_args\n  vlog \"Delta applied to backup\"\n\n  xtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/full \\\n      $mysqld_additional_args\n  vlog \"Data prepared for restore\"\n\n  # removing rows\n  ${MYSQL} ${MYSQL_ARGS} -e \"delete from t2;\" incremental_sample\n  vlog \"Table cleared\"\n\n  # Restore backup\n\n  stop_server\n\n  vlog \"Copying files\"\n\n  cd $topdir/data/full/\n  cp -r * $mysql_datadir\n  cd -\n\n  vlog \"Data restored\"\n\n  start_server ${mysqld_additional_args}\n\n  vlog \"Checking checksums\"\n  checksum_t2_b=`checksum_table incremental_sample t2`\n\n  if [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\n  then \n      vlog \"Checksums of table 't2' are not equal\"\n      exit -1\n  fi\n\n  vlog \"Checksums are OK\"\n\n  stop_server\n}\n\nfor page_size in 1 2 4 8 16; do\n    test_bug_1028949 ${page_size}\n    clean\ndone\n", "num_lines": 111}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "################################################################################\n# Bug #1037379: SQL_THREAD left in stopped state of safe-slave-backup-timeout is\n#               reached\n# Bug #887803: innobackupex --safe-slave-backup-timeout option doesn't work\n################################################################################\n\n. inc/common.sh\n\n################################################################################\n# Create a temporary table and pause \"indefinitely\" to keep the connection open\n################################################################################\nfunction create_temp_table()\n{\n    switch_server $master_id\n    run_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TEMPORARY TABLE tmp(a INT);\nINSERT INTO tmp VALUES (1);\nSELECT SLEEP(10000);\nEOF\n}\n\nmaster_id=1\nslave_id=2\n\nstart_server_with_id $master_id\nstart_server_with_id $slave_id\n\nsetup_slave $slave_id $master_id\n\ncreate_temp_table &\njob_master=$!\n\nsync_slave_with_master $slave_id $master_id\n\nswitch_server $slave_id\n\n################################################################################\n# First check if the SQL thread is left in the running state\n# if it is running when taking a backup\n################################################################################\n\n# The following will fail due to a timeout\nrun_cmd_expect_failure $IB_BIN $IB_ARGS --no-timestamp --safe-slave-backup \\\n    --safe-slave-backup-timeout=3 $topdir/backup1\n\ngrep -q \"Slave_open_temp_tables did not become zero\" $OUTFILE\n\n# Check that the SQL thread is running\nrun_cmd $MYSQL $MYSQL_ARGS -e \"SHOW SLAVE STATUS\\G\" |\n  egrep 'Slave_SQL_Running:[[:space:]]+Yes'\n\n################################################################################\n# Now check if the SQL thread is left in the stopped state\n# if it is stopped when taking a backup\n################################################################################\n\nrun_cmd $MYSQL $MYSQL_ARGS -e \"STOP SLAVE SQL_THREAD\"\n\n# The following will fail due to a timeout\nrun_cmd_expect_failure $IB_BIN $IB_ARGS --no-timestamp --safe-slave-backup \\\n    --safe-slave-backup-timeout=3 $topdir/backup2\n\ngrep -c \"Slave_open_temp_tables did not become zero\" $OUTFILE | grep -w 2\n\n# Check that the SQL thread is stopped\nrun_cmd $MYSQL $MYSQL_ARGS -e \"SHOW SLAVE STATUS\\G\" |\n  egrep 'Slave_SQL_Running:[[:space:]]+No'\n\nkill -SIGKILL $job_master\n", "num_lines": 70}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #1038127: XtraBackup 2.0.2 is not backwards compatible\n#               if no space_id found in .meta file, applying delta\n#               to full backup failing\n############################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TABLE t1(a INT) ENGINE=InnoDB;\nINSERT INTO t1 VALUES (1), (2), (3);\nEOF\n\n# Full backup\n# backup root directory\nvlog \"Starting backup\"\ninnobackupex  --no-timestamp $topdir/full\n\nvlog \"Creating incremental backup\"\n\ninnobackupex --incremental --no-timestamp \\\n    --incremental-basedir=$topdir/full $topdir/inc\n\n# remove space_id = something line from .meta file\nsed -ie '/space_id/ d' $topdir/inc/test/t1.ibd.meta\n\nvlog \"Preparing backup\"\n\ninnobackupex --apply-log --redo-only $topdir/full\nvlog \"Log applied to full backup\"\n\ninnobackupex --apply-log --redo-only --incremental-dir=$topdir/inc \\\n    $topdir/full\nvlog \"Delta applied to full backup\"\n\ninnobackupex --apply-log $topdir/full\nvlog \"Data prepared for restore\"\n\ngrep -q \"This backup was taken with XtraBackup 2.0.1\" $OUTFILE\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "MYSQLD_EXTRA_ARGS=--innodb-data-file-path=\"ibdata1:${DEFAULT_IBDATA_SIZE};ibdata2:5M:autoextend\"\n. inc/common.sh\n\nstart_server --innodb-data-file-path=\"ibdata1:${DEFAULT_IBDATA_SIZE};ibdata2:5M:autoextend\"\nload_dbase_schema incremental_sample\n\necho \"innodb-data-file-path=ibdata1:${DEFAULT_IBDATA_SIZE};ibdata2:5M:autoextend\" >>$topdir/my.cnf\n\n# Adding initial rows\nvlog \"Adding initial rows to database...\"\n${MYSQL} ${MYSQL_ARGS} -e \"insert into test values (1, 1);\" incremental_sample\n\n# Full backup\n# backup root directory\nmkdir -p $topdir/backup\n\nvlog \"Starting backup\"\ninnobackupex  $topdir/backup\nfull_backup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{print $2}'`\nvlog \"Full backup done to directory $full_backup_dir\"\n\n# Changing data\n\nvlog \"Making changes to database\"\n${MYSQL} ${MYSQL_ARGS} -e \"create table t2 (a int(11) default null, number int(11) default null) engine=innodb\" incremental_sample\n${MYSQL} ${MYSQL_ARGS} -e \"insert into test values (10, 1);\" incremental_sample\n${MYSQL} ${MYSQL_ARGS} -e \"insert into t2 values (10, 1);\" incremental_sample\nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_test_a=`checksum_table incremental_sample test`\nchecksum_t2_a=`checksum_table incremental_sample t2`\nvlog \"Table 'test' checksum is $checksum_test_a\"\nvlog \"Table 't2' checksum is $checksum_t2_a\"\n\nvlog \"Making incremental backup\"\n\nvlog \"###############\"\nvlog \"# INCREMENTAL #\"\nvlog \"###############\"\n\n# Incremental backup\ninnobackupex --incremental --incremental-basedir=$full_backup_dir \\\n    $topdir/backup\ninc_backup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | tail -n 1 | awk -F\\' '{print $2}'`\nvlog \"Incremental backup done to directory $inc_backup_dir\"\n\nvlog \"Preparing backup\"\n# Prepare backup\nvlog \"##############\"\nvlog \"# PREPARE #1 #\"\nvlog \"##############\"\ninnobackupex --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #2 #\"\nvlog \"##############\"\ninnobackupex --apply-log --redo-only --incremental-dir=$inc_backup_dir \\\n    $full_backup_dir\nvlog \"Delta applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #3 #\"\nvlog \"##############\"\ninnobackupex --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files\"\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb-data-file-path=\"ibdata1:${DEFAULT_IBDATA_SIZE};ibdata2:5M:autoextend\"\n\nvlog \"Checking checksums\"\nchecksum_test_b=`checksum_table incremental_sample test`\nchecksum_t2_b=`checksum_table incremental_sample t2`\n\nif [ \"$checksum_test_a\" != \"$checksum_test_b\"  ]\nthen \n\tvlog \"Checksums for table 'test' are not equal\"\n\texit -1\nfi\n\nif [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\nthen \n\tvlog \"Checksums for table 't2' are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 99}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#\n# Bug 1461735: database directories not removed when drop database happened during backup\n#\n\n. inc/common.sh\n\nif ! $XB_BIN --help 2>&1 | grep -q debug-sync; then\n    skip_test \"Requires --debug-sync support\"\nfi\n\nXB_EXTRA_MY_CNF_OPTS=\"\ndebug-sync=xtrabackup_load_tablespaces_pause\n\"\n\nstart_server\n\nfunction backup_local() {\n\tinnobackupex --no-timestamp $topdir/backup\n}\n\nfunction prepare_local() {\n\tinnobackupex --apply-log $topdir/backup\n}\n\nfunction backup_xbstream() {\n\tinnobackupex --no-timestamp --stream=xbstream $topdir/backup > $topdir/backup.xbs\n}\n\nfunction prepare_xbstream() {\n\tmkdir $topdir/backup\n\txbstream -x -C $topdir/backup < $topdir/backup.xbs\n\tinnobackupex --apply-log $topdir/backup\n}\n\nfunction backup_rsync() {\n\tinnobackupex --no-timestamp --rsync $topdir/backup\n}\n\nfunction prepare_rsync() {\n\tinnobackupex --apply-log $topdir/backup\n}\n\nfunction do_test() {\n\n\tcat <<EOF | $MYSQL $MYSQL_ARGS\nCREATE DATABASE sakila;\nuse sakila;\nCREATE TABLE t (a INT);\nINSERT INTO t (a) VALUES (1), (2), (3);\nEOF\n\n\t(eval $backup_cmd) &\n\tjob_pid=$!\n\n\twait_for_xb_to_suspend $pid_file\n\n\txb_pid=`cat $pid_file`\n\n\t$MYSQL $MYSQL_ARGS -Ns -e \"DROP DATABASE sakila\"\n\n\t# Resume the xtrabackup process\n\tvlog \"Resuming xtrabackup\"\n\tkill -SIGCONT $xb_pid\n\n\t# wait's return code will be the code returned by the background process\n\trun_cmd wait $job_pid\n\n\teval $prepare_cmd\n\n\tif [ ! -d $topdir/backup/test ] ; then\n\t\tvlog \"Database directory test is removed\"\n\t\texit 1\n\tfi\n\n\tif [ -d $topdir/backup/sakila ] ; then\n\t\tvlog \"Database directory is not removed\"\n\t\texit 1\n\tfi\n\n\trm -rf $topdir/backup\n\trm -rf $pid_file\n\n}\n\nvlog \"##############################\"\nvlog \"# Streaming backup\"\nvlog \"##############################\"\n\nexport backup_cmd=backup_xbstream\nexport prepare_cmd=prepare_xbstream\nexport pid_file=$topdir/tmp/xtrabackup_debug_sync\ndo_test\n\nvlog \"##############################\"\nvlog \"# Local backup\"\nvlog \"##############################\"\n\nexport backup_cmd=backup_local\nexport prepare_cmd=prepare_local\nexport pid_file=$topdir/backup/xtrabackup_debug_sync\ndo_test\n\nvlog \"##############################\"\nvlog \"# Backup using rsync\"\nvlog \"##############################\"\n\nexport backup_cmd=backup_rsync\nexport prepare_cmd=prepare_rsync\nexport pid_file=$topdir/backup/xtrabackup_debug_sync\ndo_test\n", "num_lines": 111}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #483827: support for mysqld_multi\n########################################################################\n\nfunction modify_args()\n{\n  XB_ARGS=`echo $XB_ARGS | sed -e 's/my.cnf/my_multi.cnf/'`\n  IB_ARGS=`echo $IB_ARGS | sed -e 's/my.cnf/my_multi.cnf/'`\n}\n\n. inc/common.sh\n\nstart_server\n\nbackup_dir=$topdir/backup\n\n# change defaults file from my.cnf to my_multi.cnf\nmodify_args\n\n# make my_multi.cnf\necho \"\n[mysqld1]\ndatadir=${mysql_datadir}\ntmpdir=$mysql_tmpdir\" > $topdir/my_multi.cnf\n\n# Backup\ninnobackupex --no-timestamp --defaults-group=mysqld1 $backup_dir\ninnobackupex --apply-log $backup_dir\n\nstop_server\n\n# clean datadir\nrm -rf ${mysql_datadir}/*\n\n# restore backup\ninnobackupex --copy-back --defaults-group=mysqld1 $backup_dir\n\n# make sure that data are in correct place\nif [ ! -f ${mysql_datadir}/ibdata1 ] ; then\n  vlog \"Data not found in ${mysql_datadir}\"\n  exit -1\nfi\n", "num_lines": 43}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #489290: xtrabackup defaults to mysql datadir\n########################################################################\n\n. inc/common.sh\n\nstart_server\n\nbackup_dir=$topdir/backup\nmkdir -p $backup_dir\nvlog \"Backup created in directory $backup_dir\"\n\ncwd=`pwd`\ncd $topdir\n\n# Backup\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=backup\n\n# Assure that directory is correct\nif [ ! -f $backup_dir/ibdata1 ] ; then\n\tvlog \"Backup not found in $backup_dir\"\n\texit -1\nfi\n\ncd $cwd\n", "num_lines": 26}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##################################################################\n# Bug #514068: Output to STDOUT and STDERR is not conventional\t #\n# Bug #741021: xtrabackup --prepare prints a few lines to stdout #\n##################################################################\n\n. inc/common.sh\n\nstart_server\n\ninnobackupex  --no-timestamp $topdir/backup >$topdir/stdout 2>$topdir/stderr\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n\n# Restore sakila\nvlog \"Applying log\"\ninnobackupex --apply-log $topdir/backup >>$topdir/stdout 2>>$topdir/stderr\n\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ninnobackupex --copy-back $topdir/backup >>$topdir/stdout 2>>$topdir/stderr\n\nif [ \"`cat $topdir/stdout | wc -l`\" -gt 0 ]\nthen\n    vlog \"Got the following output on stdout:\"\n    cat $topdir/stdout\n    exit -1\nfi\n", "num_lines": 30}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Test for bug 528752: xtrabackup does not handle innodb=force in my.cnf\n\n. inc/common.sh\n\n# XB fails with exit code 3 when the bug is present\nxtrabackup --print-param --innodb=force\n", "num_lines": 7}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nif test \"`uname -s`\" != \"Linux\"\nthen\n    echo \"Requires Linux\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_file_per_table\n\nload_sakila\n\n# Take backup\necho \"innodb_flush_method=O_DIRECT\" >> $topdir/my.cnf\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/out.tar\nstop_server\n\n# See if xtrabackup was using O_DIRECT\nif ! grep -q \"xtrabackup: using O_DIRECT\" $OUTFILE ;\nthen\n  vlog \"xtrabackup was not using O_DIRECT for the input file.\"\n  exit -1\nfi\n\n# Remove datadir\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\nbackup_dir=$topdir/backup\ncd $backup_dir\n$TAR -ixvf out.tar\ncd - >/dev/null 2>&1 \ninnobackupex --apply-log --defaults-file=$topdir/my.cnf $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ninnobackupex --copy-back --defaults-file=$topdir/my.cnf $backup_dir\n\nstart_server\n# Check sakila\n${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #722638: xtrabackup: taking backup while tables are droped and \n#              created breaks backup\n########################################################################\n\n. inc/common.sh\n\nif ! $XB_BIN --help 2>&1 | grep -q debug-sync; then\n    echo \"Requires --debug-sync support\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_file_per_table\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\n\nCREATE TABLE t1(a INT) ENGINE=InnoDB;\nINSERT INTO t1 VALUES (1), (2), (3);\n\nCREATE TABLE t2(a INT) ENGINE=InnoDB;\nINSERT INTO t2 VALUES (1), (2), (3);\n\nCREATE TABLE t3(a INT) ENGINE=InnoDB;\nINSERT INTO t3 VALUES (1), (2), (3);\n\nCREATE TABLE t4_old(a INT) ENGINE=InnoDB;\nINSERT INTO t4_old VALUES (1), (2), (3);\n\nEOF\n\nmkdir -p $topdir/backup\n\n# Backup\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/backup \\\n    --debug-sync=\"data_copy_thread_func\" &\n\njob_pid=$!\n\npid_file=$topdir/backup/xtrabackup_debug_sync\n\n# Wait for xtrabackup to suspend\ni=0\nwhile [ ! -r \"$pid_file\" ]\ndo\n    sleep 1\n    i=$((i+1))\n    echo \"Waited $i seconds for $pid_file to be created\"\ndone\n\nxb_pid=`cat $pid_file`\n\n# Modify the original tables, then change spaces ids by running DDL\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\n\nINSERT INTO t1 VALUES (4), (5), (6);\nDROP TABLE t1;\nCREATE TABLE t1(a CHAR(1)) ENGINE=InnoDB;\nINSERT INTO t1 VALUES (\"1\"), (\"2\"), (\"3\");\n\nINSERT INTO t2 VALUES (4), (5), (6);\nALTER TABLE t2 MODIFY a BIGINT;\nINSERT INTO t2 VALUES (7), (8), (9);\n\nINSERT INTO t3 VALUES (4), (5), (6);\nTRUNCATE t3;\nINSERT INTO t3 VALUES (7), (8), (9);\n\nINSERT INTO t4_old VALUES (4), (5), (6);\nALTER TABLE t4_old RENAME t4;\nINSERT INTO t4 VALUES (7), (8), (9);\n\nEOF\n\n# Calculate checksums\nchecksum_t1=`checksum_table test t1`\nchecksum_t2=`checksum_table test t2`\nchecksum_t3=`checksum_table test t3`\nchecksum_t4=`checksum_table test t4`\n\n# Resume xtrabackup\nvlog \"Resuming xtrabackup\"\nkill -SIGCONT $xb_pid\n\nrun_cmd wait $job_pid\n\n# Prepare\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/backup\n\nstop_server\n\n# Restore\nrm -rf $mysql_datadir/ibdata1 $mysql_datadir/ib_logfile* \\\n    $mysql_datadir/test/*.ibd\ncp -r $topdir/backup/* $mysql_datadir\n\nstart_server --innodb_file_per_table\n\n# Verify checksums\nchecksum_t1_new=`checksum_table test t1`\nchecksum_t2_new=`checksum_table test t2`\nchecksum_t3_new=`checksum_table test t3`\nchecksum_t4_new=`checksum_table test t4`\nvlog \"Checksums (old/new):\"\nvlog \"t1: $checksum_t1/$checksum_t1_new\"\nvlog \"t2: $checksum_t2/$checksum_t2_new\"\nvlog \"t3: $checksum_t3/$checksum_t3_new\"\nvlog \"t4: $checksum_t4/$checksum_t4_new\"\n\nif [ \"$checksum_t1\" = \"$checksum_t1_new\" -a \\\n     \"$checksum_t2\" = \"$checksum_t2_new\" -a \\\n     \"$checksum_t3\" = \"$checksum_t3_new\" -a \\\n     \"$checksum_t4\" = \"$checksum_t4_new\" ]; then\n    exit 0\nfi\n\nvlog \"Checksums do not match\"\nexit -1\n", "num_lines": 119}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\n\nvlog \"Loading data from sql file\"\nrun_cmd ${MYSQL} ${MYSQL_ARGS} test < inc/bug723097.sql\n\nvlog \"Saving checksum\"\nchecksum_a=`checksum_table test messages`\nvlog \"Checksum before is $checksum_a\"\n\nvlog \"Creating backup directory\"\nmkdir -p $topdir/data/full\nvlog \"Starting backup\"\n\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full\nvlog \"Backup is done\"\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/full\nvlog \"Data prepared fo restore\"\nstop_server\n\ncd $topdir/data/full/test\ncp -r * $mysql_datadir/test\ncd -\nstart_server --innodb_file_per_table\nchecksum_b=`checksum_table test messages`\nvlog \"Checksum after is $checksum_b\"\n\nif [ \"$checksum_a\" -eq \"$checksum_b\" ]\nthen\n\tvlog \"Checksums are Ok\"\nelse\n\tvlog \"Checksums are not equal\"\n\texit -1\nfi\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nmkdir -p $topdir/backup\nmkdir -p $topdir/backup/stream\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/stream/out.tar \n\nstop_server\n\ncd $topdir/backup/stream/\n$TAR -ixvf out.tar\n\nif [ -f $topdir/backup/stream/xtrabackup_binary ]\nthen\n\tvlog \"File xtrabackup_binary was copied\"\nelse\n\tvlog \"File xtrabackup_binary was not copied\"\n\texit -1\nfi\n\ncd - >/dev/null 2>&1 \n", "num_lines": 27}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #729843: innobackupex logs plaintext password\n########################################################################\n\n. inc/common.sh\n\nstart_server\n\nmkdir $topdir/backup\nlogfile=$topdir/backup/innobackupex_log\n\n# Don't use run_cmd_* or innobackupex functions here to avoid logging\n# the full command line (including the password in plaintext)\nset +e\n$IB_BIN $IB_ARGS --password=secret $topdir/backup 2>&1 | tee $logfile\nset -e\n\n# Check that the password was not logged in plaintext\nrun_cmd grep  -- \"--password=xxxxxxxx\" $logfile \nrun_cmd_expect_failure grep -- \"--password=secret\" $logfile\n", "num_lines": 21}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #733651: innobackupex not stores some critical\n# innodb options in backup-my.cnf\n########################################################################\n\n. inc/common.sh\n\noptions=\"innodb_log_files_in_group innodb_log_file_size\"\nif [ ! -z \"$XTRADB_VERSION\" ]; then\n    options=\"$options innodb_page_size innodb_fast_checksum innodb_log_block_size\"\nfi\n\nstart_server\n\nmkdir -p $topdir/backup\ninnobackupex  $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup created in directory $backup_dir\"\n\n# test presence of options\nfor option in $options ; do\n\n\tif [ \"`cat $backup_dir/backup-my.cnf | grep $option | wc -l`\" == \"0\" ] ; then\n\t\tvlog \"Option $option is absent\"\n\t\texit -1\n\telse\n\t\tvlog \"Option $option is present\"\n\tfi\n\ndone\n", "num_lines": 31}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #740489: Add --defaults-extra-file param to innobackupex\n############################################################################\n. inc/common.sh\n\nstart_server --innodb_file_per_table\nload_sakila\n\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; FLUSH PRIVILEGES;\"\n\ndefaults_extra_file=${TEST_BASEDIR}/740489.cnf\n\necho \"[client]\" > $defaults_extra_file\necho \"user=root\" >> $defaults_extra_file\necho \"password=password\" >> $defaults_extra_file\n\nmkdir -p $topdir/backup\ncat ${MYSQLD_VARDIR}/my.cnf\nrun_cmd $IB_BIN --defaults-extra-file=$defaults_extra_file --socket=${MYSQLD_SOCKET} --ibbackup=$XB_BIN $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup created in directory $backup_dir\"\n\nrun_cmd ${MYSQL} ${MYSQL_ARGS} --password=password -e \"UPDATE mysql.user SET Password=PASSWORD('') WHERE User='root'; FLUSH PRIVILEGES;\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n#init_mysql_dir\n# Restore sakila\nvlog \"Applying log\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $backup_dir\n\nstart_server\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} --password=password -e \"SELECT count(*) from actor\" sakila\n\nrm -f $defaults_extra_file\n", "num_lines": 47}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #759225: xtrabackup does not support ALL_O_DIRECT for \n#              innodb_flush_method\n########################################################################\n\n. inc/common.sh\n\nif test \"`uname -s`\" != \"Linux\"\nthen\n    echo \"Requires Linux\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\nload_sakila\n\n# Take backup\necho \"innodb_flush_method=ALL_O_DIRECT\" >> $topdir/my.cnf\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/out.tar\nstop_server\n\n# See if xtrabackup was using ALL_O_DIRECT\nif ! grep -q \"xtrabackup: using ALL_O_DIRECT\" $OUTFILE ;\nthen\n  vlog \"xtrabackup was not using ALL_O_DIRECT for the input file.\"\n  exit -1\nfi\n\n# Remove datadir\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\nbackup_dir=$topdir/backup\ncd $backup_dir\n$TAR -ixvf out.tar\ncd - >/dev/null 2>&1 \ninnobackupex --apply-log --defaults-file=$topdir/my.cnf $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ninnobackupex --copy-back --defaults-file=$topdir/my.cnf $backup_dir\n\nstart_server\n# Check sakila\n${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 51}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##########################################################################\n# Bug #759701: innobackupex does not copy non-InnoDB files when applying #\n#              incremental backups                                       #\n##########################################################################\n. inc/common.sh\n\nstart_server --innodb_file_per_table\nload_sakila\n\n# Full backup\n# backup root directory\nvlog \"Starting backup\"\n\nfull_backup_dir=$topdir/full_backup\ninnobackupex  --no-timestamp $full_backup_dir\n\n# Changing data\n\nrun_cmd $MYSQL $MYSQL_ARGS -e \"CREATE DATABASE newdb\"\nrun_cmd $MYSQL $MYSQL_ARGS -e \\\n    \"CREATE TABLE actor_copy ENGINE=MyISAM SELECT * FROM sakila.actor\" newdb\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table newdb actor_copy`\ntest -n \"$checksum_a\" || die \"Failed to checksum table actor_copy\"\n\nvlog \"Making incremental backup\"\n\n# Incremental backup\ninc_backup_dir=$topdir/incremental_backup\ninnobackupex --incremental --no-timestamp \\\n    --incremental-basedir=$full_backup_dir $inc_backup_dir\nvlog \"Incremental backup created in directory $inc_backup_dir\"\n\nvlog \"Preparing backup\"\ninnobackupex --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\n\ninnobackupex --apply-log --redo-only --incremental-dir=$inc_backup_dir \\\n    $full_backup_dir\nvlog \"Delta applied to full backup\"\n\ninnobackupex --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files to their original locations\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table\n\nvlog \"Checking checksums\"\nchecksum_b=`checksum_table newdb actor_copy`\n\nvlog \"Old checksum: $checksum_a\"\nvlog \"New checksum: $checksum_b\"\n\nif [ \"$checksum_a\" != \"$checksum_b\"  ]\nthen \n    vlog \"Checksums do not match\"\n    exit -1\nfi\n", "num_lines": 69}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##########################################################################\n# Bug #766033: xtrabackup doesn't report file name in error message      #\n##########################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\nload_sakila\n\nstop_server\n\n# Full backup\nvlog \"Starting backup\"\n\n# corrupt database\ndd if=/dev/zero of=$mysql_datadir/sakila/rental.ibd seek=1000 count=1\n\n# we want xtrabackup to be failed on rental.ibd\nrun_cmd_expect_failure $XB_BIN $XB_ARGS  --backup --datadir=$mysql_datadir \\\n    --target-dir=$topdir/backup \n\ngrep -q \"File ./sakila/rental.ibd seems to be corrupted\" $OUTFILE\n\n", "num_lines": 24}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\nload_dbase_schema incremental_sample\n\n# Full backup dir\nmkdir -p $topdir/data/full\n# Incremental backup dir\nmkdir -p $topdir/data/delta\n\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full\n\nvlog \"Creating and filling a new table\"\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TABLE t(a int) ENGINE=InnoDB;\nINSERT INTO t VALUES (1), (2), (3);\nFLUSH LOGS;\nEOF\n\nstop_server\nstart_server --innodb_file_per_table\n\nvlog \"Making incremental backup\"\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full\n\nvlog \"Preparing full backup\"\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full\n\n# The following would fail before the bugfix\nvlog \"Applying incremental delta\"\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta\n\nvlog \"Preparing full backup\"\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/full\nvlog \"Data prepared for restore\"\n\nstop_server\n\nvlog \"Copying files\"\n\ncd $topdir/data/full/\ncp -r * $mysql_datadir\ncd $topdir\n\nvlog \"Data restored\"\nstart_server --innodb_file_per_table\n\nrun_cmd $MYSQL $MYSQL_ARGS -e \"SELECT * FROM t\" test\n", "num_lines": 51}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #803636: \"moves files\" option needed with --copy-back\n########################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_sakila\n\n# Backup\ninnobackupex --no-timestamp $topdir/backup\n\nstop_server\n\nrm -r $mysql_datadir\n\n# Prepare\ninnobackupex --apply-log $topdir/backup\n\n# Restore\nmkdir -p $mysql_datadir\ninnobackupex --move-back $topdir/backup\n\n# Check that there are no data files in the backup directory\nrun_cmd_expect_failure ls -R $topdir/backup/*/*.{ibd,MYD,MYI,frm}\n\nstart_server\n\n# Verify data\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #665210: tar4ibd does not support innodb row_format=compressed\n# Bug #810269: tar4ibd does not check for doublewrite buffer pages\n########################################################################\n\n. inc/common.sh\n\nif [ -z \"$INNODB_VERSION\" ]; then\n    echo \"Requires InnoDB plugin or XtraDB\" >$SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server \"--innodb_strict_mode --innodb_file_per_table \\\n--innodb_file_format=Barracuda\"\n\nload_dbase_schema incremental_sample\n\nvlog \"Compressing the table\"\n\nrun_cmd $MYSQL $MYSQL_ARGS -e \\\n    \"ALTER TABLE test ENGINE=InnoDB ROW_FORMAT=compressed \\\nKEY_BLOCK_SIZE=4\" incremental_sample\n\nvlog \"Adding initial rows to table\"\n\nnumrow=10000\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]; do\n    sql=\"INSERT INTO test VALUES ($count, $numrow)\"\n    let \"count=count+1\"\n    for ((i=0; $i<99; i++)); do\n\tsql=\"$sql,($count, $numrow)\"\n\tlet \"count=count+1\"\n    done\n    ${MYSQL} ${MYSQL_ARGS} -e \"$sql\" incremental_sample\ndone\n\nrows=`${MYSQL} ${MYSQL_ARGS} -Ns -e \"SELECT COUNT(*) FROM test\" \\\n    incremental_sample`\nif [ \"$rows\" != \"10000\" ]; then\n    vlog \"Failed to add initial rows\"\n    exit -1\nfi\n\nvlog \"Initial rows added\"\n\nchecksum_a=`checksum_table incremental_sample test`\n\nvlog \"Starting streaming backup\"\n\nmkdir -p $topdir/backup\n\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/out.tar\n\nstop_server\nrm -rf $mysql_datadir\n\nvlog \"Applying log\"\n\ncd $topdir/backup\n$TAR -ixvf out.tar\ncd -\ninnobackupex --apply-log $topdir/backup\n\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ninnobackupex --copy-back $topdir/backup\n\nstart_server\n\nchecksum_b=`checksum_table incremental_sample test`\n\nif [ \"$checksum_a\" != \"$checksum_b\" ]; then\n    vlog \"Checksums do not match\"\n    exit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 79}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #817132: innobackupex copy-back doesn't work without ibbackup\n########################################################################\n\n. inc/common.sh\n\n# innobackupex --copy-back without explicit --ibbackup specification\n# defaults to 'xtrabackup'. So any build configurations other than xtradb51\n# would fail in Jenkins.\nif [ \"`basename $XB_BIN`\" != \"xtrabackup\" ]; then\n    echo \"Requires xtradb51\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\nload_dbase_schema sakila\nload_dbase_data sakila\n\nmkdir -p $topdir/backup\ninnobackupex  $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup created in directory $backup_dir\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n\n# Restore sakila\nvlog \"Applying log\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\n\n# The following would fail before #817132 was fixed.\n# Cannot use innobackupex here, because that would specify\n# --ibbackup explicitly (see $IB_ARGS).\nrun_cmd $IB_BIN --defaults-file=$topdir/my.cnf --user=root --socket=$mysql_socket --copy-back $backup_dir\n\nstart_server\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 42}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #884737: xtrabackup's --parallel option asserts / crashes with a\n#              value of -1\n########################################################################\n\n. inc/common.sh\n\nstart_server\n\n# Check that --parallel=<negative value> doesn't blow up\nvlog \"Creating the backup directory: $topdir/backup\"\nmkdir -p $topdir/backup\ninnobackupex $topdir/backup --parallel=-1  \n", "num_lines": 14}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##########################################################################\n# Bug #891496: tar4ibd fails on datafiles generated on 5.0               #\n##########################################################################\nMYSQLD_EXTRA_ARGS=--innodb-data-file-path=\"ibdata1:3M;ibdata2:10M:autoextend\"\n\n. inc/common.sh\n\ninnodb_data_file_path=\"ibdata1:3M;ibdata2:10M:autoextend\"\n\nstart_server --innodb_data_file_path=$innodb_data_file_path\n\ncat >> $topdir/my.cnf <<EOF\ninnodb_data_file_path=$innodb_data_file_path\nEOF\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/out.tar\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\nbackup_dir=$topdir/backup\ncd $backup_dir\n$TAR -ixvf out.tar\ncd - >/dev/null 2>&1 \nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex  --copy-back $backup_dir\n\nstart_server --innodb_data_file_path=$innodb_data_file_path\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 46}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #932623: RENAME TABLE causes incremental prepare to fail\n########################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TABLE t1_old(a INT) ENGINE=InnoDB;\nINSERT INTO t1_old VALUES (1), (2), (3);\n\nCREATE TABLE t1(a INT) ENGINE=InnoDB;\nINSERT INTO t1 VALUES (4), (5), (6);\nEOF\n\n# Full backup\n# backup root directory\nvlog \"Starting backup\"\ninnobackupex  --no-timestamp $topdir/full\n\nvlog \"Rotating the table\"\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TABLE t1_new(a int) ENGINE=InnoDB;\nINSERT INTO t1_new VALUES (7), (8), (9);\n\nCREATE DATABASE db2;\nRENAME TABLE t1_old TO db2.t1;\n\nRENAME TABLE t1 TO t1_old;\nRENAME TABLE t1_new TO t1;\n\nINSERT INTO t1_old VALUES (10), (11), (12);\nINSERT INTO t1 VALUES (13), (14), (15);\n\nEOF\n\nvlog \"Creating incremental backup\"\n\ninnobackupex --incremental --no-timestamp \\\n    --incremental-basedir=$topdir/full $topdir/inc\n\nvlog \"Preparing backup\"\n\ninnobackupex --apply-log --redo-only $topdir/full\nvlog \"Log applied to full backup\"\n\ninnobackupex --apply-log --redo-only --incremental-dir=$topdir/inc \\\n    $topdir/full\nvlog \"Delta applied to full backup\"\n\ninnobackupex --apply-log $topdir/full\nvlog \"Data prepared for restore\"\n\nchecksum_t1_a=`checksum_table test t1`\nchecksum_t1_old_a=`checksum_table test t1_old`\nchecksum_t1_db2_a=`checksum_table db2 t1`\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files\"\n\ninnobackupex --copy-back $topdir/full\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table\n\nvlog \"Checking checksums\"\nchecksum_t1_b=`checksum_table test t1`\nchecksum_t1_old_b=`checksum_table test t1_old`\nchecksum_t1_db2_b=`checksum_table db2 t1`\n\nif [ \"$checksum_t1_a\" != \"$checksum_t1_b\" -o \"$checksum_t1_old_a\" != \"$checksum_t1_old_b\" \\\n\t-o \"$checksum_t1_db2_a\" != \"$checksum_t1_db2_b\" ]\nthen \n\tvlog \"Checksums do not match\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 86}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #972169: --compress in 2.0 should be incompatible with --stream=tar\n############################################################################\n\n. inc/common.sh\n\nstart_server\n\nrun_cmd_expect_failure $XB_BIN $XB_ARGS --datadir=$mysql_datadir --backup \\\n    --compress --stream=tar\ngrep -q \"xtrabackup: error: compressed backups are incompatible with the\" \\\n    $OUTFILE\n", "num_lines": 13}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #976945: innodb_log_block_size=4096 is not supported\n############################################################################\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_log_block_size=4096\necho innodb_log_block_size=4096 >> ${MYSQLD_VARDIR}/my.cnf\nload_sakila\n\n# Full backup\nvlog \"Starting backup\"\n\nfull_backup_dir=${MYSQLD_VARDIR}/full_backup\ninnobackupex  --no-timestamp $full_backup_dir\n\nvlog \"Preparing backup\"\ninnobackupex --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files to their original locations\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_log_block_size=4096\n", "num_lines": 36}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #977101: --safe-slave-backup results in incorrect binlog info\n########################################################################\n\n. inc/common.sh\n\nmaster_id=1\nslave_id=2\n\nstart_server_with_id $master_id\nstart_server_with_id $slave_id\n\nsetup_slave $slave_id $master_id\n\n# Full backup of the slave server\nswitch_server $slave_id\n\n# Check that binlog info is correct with --safe-slave-backup\ninnobackupex --no-timestamp --safe-slave-backup $topdir/backup\negrep -q '^mysql-bin.000001[[:space:]]+[0-9]+[[:space:]]+$' \\\n    $topdir/backup/xtrabackup_binlog_info\n\n# Check that both binlog info and slave info are correct with \n# --safe-slave-backup\nrm -rf $topdir/backup\ninnobackupex --no-timestamp --slave-info --safe-slave-backup $topdir/backup\negrep -q '^mysql-bin.000001[[:space:]]+[0-9]+[[:space:]]+$' \\\n    $topdir/backup/xtrabackup_binlog_info\negrep -q '^CHANGE MASTER TO MASTER_LOG_FILE='\\''mysql-bin.000001'\\'', MASTER_LOG_POS=[0-9]+$' \\\n    $topdir/backup/xtrabackup_slave_info\n\n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#############################################################################\n# Bug #977652: Compressed/Uncompressed incremental backup fails on compressed\n#              full backup in Xtrabackup 2.0.0\n#############################################################################\n\nif ! which qpress > /dev/null 2>&1 ; then\n  echo \"Requires qpress to be installed\" > $SKIPPED_REASON\n  exit $SKIPPED_EXIT_CODE\nfi\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_sakila\n\n# Take a full compressed backup\ninnobackupex --compress --no-timestamp $topdir/full\n\n# Test that incremental backups work without uncompressing the full one\ninnobackupex --compress --no-timestamp --incremental \\\n    --incremental-basedir=$topdir/full $topdir/incremental\n", "num_lines": 23}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #983685: innodb_data_file_path is not written to backup-my.cnf\n########################################################################\n\n. inc/common.sh\n\nstart_server\n\noptions=\"innodb_data_file_path\"\n\nmkdir -p $topdir/backup\ninnobackupex  $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup created in directory $backup_dir\"\n\n# test presence of options\nfor option in $options ; do\n\n\tif ! grep $option $backup_dir/backup-my.cnf ; then\n\t\tvlog \"Option $option is absent\"\n\t\texit -1\n\telse\n\t\tvlog \"Option $option is present\"\n\tfi\n\ndone\n", "num_lines": 27}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #983695: --copy-back should ignore *.qp files\n########################################################################\n\n. inc/common.sh\n\nif ! which qpress > /dev/null 2>&1 ; then\n  echo \"Requires qpress to be installed\" > $SKIPPED_REASON\n  exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\nload_sakila\n\ninnobackupex --compress --no-timestamp $topdir/backup\n\nstop_server\nrm -rf ${MYSQLD_DATADIR}/*\n\ninnobackupex --copy-back $topdir/backup\n\nrun_cmd_expect_failure ls ${MYSQLD_DATADIR}/*.qp\nrun_cmd_expect_failure ls ${MYSQLD_DATADIR}/sakila/*.qp\n", "num_lines": 24}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug983720: ib_lru_dump and --galera-info fail with --stream=xbstream\n############################################################################\n\n. inc/common.sh\n\nset +e\n${MYSQLD} --basedir=$MYSQL_BASEDIR --user=$USER --help --verbose --wsrep-sst-method=rsync| grep -q wsrep\nprobe_result=$?\nif [[ \"$probe_result\" == \"0\" ]]\n    then\n        vlog \"Server supports wsrep\"\n    else\n        echo \"Requires WSREP enabled\" > $SKIPPED_REASON\n        exit $SKIPPED_EXIT_CODE\nfi\nset -e\n\ngalera_port=`get_free_port 2`\n\nstart_server --log-bin=`hostname`-bin --binlog-format=ROW --wsrep-provider=${MYSQL_BASEDIR}/lib/libgalera_smm.so --wsrep_cluster_address=gcomm:// --wsrep_provider_options=\"base_port=${galera_port}\"\n\n# take a backup with stream mode\nmkdir -p $topdir/backup\ninnobackupex --galera-info --stream=xbstream $topdir/backup > $topdir/backup/stream.xbs\n\nxbstream -xv -C $topdir/backup < $topdir/backup/stream.xbs\nif [ -f $topdir/backup/xtrabackup_galera_info ] ; then\n    vlog \"galera info has been backed up\"\nelse\n    vlog \"galera info has not been backed up\"\n    exit -1\nfi\n\nstop_server\nfree_reserved_port ${galera_port}\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug983720: ib_lru_dump and --galera-info fail with --stream=xbstream\n############################################################################\n\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\n\n# produce ib_lru_dump\n${MYSQL} ${MYSQL_ARGS} -e \"select * from information_schema.XTRADB_ADMIN_COMMAND /*!XTRA_LRU_DUMP*/;\"\n\n# take a backup with stream mode\nmkdir -p $topdir/backup\ninnobackupex --stream=xbstream $topdir/backup > $topdir/backup/stream.xbs\n\nxbstream -xv -C $topdir/backup < $topdir/backup/stream.xbs\nif [ -f $topdir/backup/ib_lru_dump ] ; then\n    vlog \"LRU dump has been backed up\"\nelse\n    vlog \"LRU dump has not been backed up\"\n    exit -1\nfi\n", "num_lines": 28}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug989397: InnoDB tables with names *opt*, *par*, *CSV*, *MYD* and so on\n# backed up twice\n############################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\n# create table which name ends with opt\n${MYSQL} ${MYSQL_ARGS} -e \"create table test.topt (a int auto_increment primary key);\"\n\n# take a backup with stream mode\nmkdir -p $topdir/backup\ninnobackupex --stream=xbstream $topdir/backup > $topdir/backup/stream.xbs\n\n# will fail if table topt backed up twice\nxbstream -xv -C $topdir/backup < $topdir/backup/stream.xbs\n", "num_lines": 19}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #996493: innobackupex --apply-log doesn't read config from\n# backup-my.cnf\n########################################################################\n\n. inc/common.sh\n\nstart_server\n\nbackup_dir=$topdir/backup\ninnobackupex --no-timestamp $backup_dir\nvlog \"Backup created in directory $backup_dir\"\n\nvlog \"Stop mysqld\"\nstop_server\n\nvlog \"Remove datadir\"\nrm -r $mysql_datadir/*\n\nvlog \"Remove my.cnf\"\nmv $topdir/my.cnf $topdir/my.cnf.bak\n\ntrap \"vlog restoring $topdir/my.cnf ; \\\nmv $topdir/my.cnf.bak $topdir/my.cnf\" INT TERM EXIT\n\nvlog \"Apply log\"\n# Do not run innobackupex, because it pass option --defaults-file\n# which we should avoid. Our goal is to test that backup-my.cnf\n# will be read by default when apply-log is run.\nrun_cmd $IB_BIN --ibbackup=$XB_BIN --apply-log $backup_dir\n\nvlog \"Get my.cnf back\"\nmv $topdir/my.cnf.bak $topdir/my.cnf\ntrap \"vlog test exit\" INT TERM EXIT\n\nvlog \"Copy back\"\ninnobackupex --copy-back $backup_dir\n", "num_lines": 38}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Bug #999750: incremental backups should be incompatible with --stream=tar\n############################################################################\n\n. inc/common.sh\n\n# Exclude the built-in InnoDB configuration as it requires a different format\n# for --incremental-lsn.\nif [ -z \"$INNODB_VERSION\" ]; then\n    echo \"Requires InnoDB plugin or XtraDB\" >$SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\n\nrun_cmd_expect_failure $XB_BIN $XB_ARGS --datadir=$mysql_datadir --backup \\\n    --incremental-lsn=0 --stream=tar\ngrep -q \"xtrabackup: error: streaming incremental backups are incompatible with the \" \\\n    $OUTFILE\n", "num_lines": 20}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##########################################################################\n# Bug #907147: 1.6.4-313 loses master log info                           #\n##########################################################################\n\n. inc/common.sh\n\nstart_server\nload_sakila\n\ninnobackupex --no-timestamp $topdir/backup\n\nrun_cmd_expect_failure grep \"xtrabackup ping\" \\\n    $topdir/backup/xtrabackup_binlog_info\n", "num_lines": 14}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Basic test for local compressed backups\n########################################################################\n\n. inc/common.sh\n\nif ! which qpress > /dev/null 2>&1 ; then\n  echo \"Requires qpress to be installed\" > $SKIPPED_REASON\n  exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_file_per_table\nload_sakila\n\ninnobackupex --compress --no-timestamp $topdir/backup\n\nstop_server\nrm -rf ${MYSQLD_DATADIR}/*\n\ncd $topdir/backup\n\nfor i in *.qp;  do qpress -d $i ./; done; \\\nfor i in sakila/*.qp; do qpress -d $i sakila/; done\n\ninnobackupex --apply-log $topdir/backup\n\ninnobackupex --copy-back $topdir/backup\n\nstart_server\n\n# TODO: proper validation\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 33}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"create database csv\"\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"create table csm (a int NOT NULL ) ENGINE=CSV\" csv\n# Adding initial rows\nvlog \"Adding initial rows to database...\"\nnumrow=100\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into csm values ($count);\" csv\n\tlet \"count=count+1\"\ndone\nvlog \"Initial rows added\"\n\n# Full backup\n# backup root directory\nmkdir -p $topdir/backup\n\nvlog \"Starting backup\"\ninnobackupex $topdir/backup\nfull_backup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{print $2}'`\nvlog \"Full backup done to directory $full_backup_dir\"\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table csv csm`\nvlog \"Table checksum is $checksum_a\"\n\nvlog \"Preparing backup\"\n# Prepare backup\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files\"\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table\nchecksum_b=`checksum_table csv csm`\nvlog \"Checking checksums: $checksum_a/$checksum_b\"\n\nif [ \"$checksum_a\" != \"$checksum_b\"  ]\nthen \n\tvlog \"Checksums are not equal\"\n\texit -1\nfi\nvlog \"Checksums are OK\"\n", "num_lines": 61}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #1066843: Fix for bug #932623 does not take separate doublewrite\n#               tablespace into account\n# Bug #1068470: XtraBackup handles separate doublewrite buffer file\n#               incorrectly\n# We testing full and incremental backup and restore to check that\n# separate doublewrite buffer file handled correctly\n########################################################################\n\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nDBLWR=dblwr.ibd\nstart_server --innodb_file_per_table --innodb_doublewrite_file=${DBLWR}\nload_dbase_schema incremental_sample\n\n# Workaround for bug #1072695\nIB_ARGS_NO_DEFAULTS_FILE=`echo $IB_ARGS | sed -e 's/--defaults-file=[^ ]* / /'`\nfunction innobackupex_no_defaults_file ()\n{\n\trun_cmd $IB_BIN $IB_ARGS_NO_DEFAULTS_FILE $*\n}\n\necho \"innodb_doublewrite_file=${DBLWR}\" >>$topdir/my.cnf\n\n# Adding initial rows\nvlog \"Adding initial rows to database...\"\n${MYSQL} ${MYSQL_ARGS} -e \"insert into test values (1, 1);\" incremental_sample\n\n# Full backup\n# backup root directory\nmkdir -p $topdir/backup\n\nvlog \"Starting backup\"\nfull_backup_dir=$topdir/backup/full\ninnobackupex  --no-timestamp $full_backup_dir\nvlog \"Full backup done to directory $full_backup_dir\"\ncat $full_backup_dir/backup-my.cnf\n\n# Changing data\n\nvlog \"Making changes to database\"\n${MYSQL} ${MYSQL_ARGS} -e \"create table t2 (a int(11) default null, number int(11) default null) engine=innodb\" incremental_sample\n${MYSQL} ${MYSQL_ARGS} -e \"insert into test values (10, 1);\" incremental_sample\n${MYSQL} ${MYSQL_ARGS} -e \"insert into t2 values (10, 1);\" incremental_sample\nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_test_a=`checksum_table incremental_sample test`\nchecksum_t2_a=`checksum_table incremental_sample t2`\nvlog \"Table 'test' checksum is $checksum_test_a\"\nvlog \"Table 't2' checksum is $checksum_t2_a\"\n\nvlog \"Making incremental backup\"\n\nvlog \"###############\"\nvlog \"# INCREMENTAL #\"\nvlog \"###############\"\n\n# Incremental backup\ninc_backup_dir=$topdir/backup/inc\ninnobackupex --no-timestamp --incremental --incremental-basedir=$full_backup_dir \\\n    $inc_backup_dir\nvlog \"Incremental backup done to directory $inc_backup_dir\"\n\nvlog \"Preparing backup\"\n# Prepare backup\nvlog \"##############\"\nvlog \"# PREPARE #1 #\"\nvlog \"##############\"\ninnobackupex_no_defaults_file --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #2 #\"\nvlog \"##############\"\ninnobackupex_no_defaults_file --apply-log --redo-only --incremental-dir=$inc_backup_dir \\\n    $full_backup_dir\nvlog \"Delta applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #3 #\"\nvlog \"##############\"\ninnobackupex_no_defaults_file --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files\"\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table --innodb_doublewrite_file=${DBLWR}\n\nvlog \"Checking checksums\"\nchecksum_test_b=`checksum_table incremental_sample test`\nchecksum_t2_b=`checksum_table incremental_sample t2`\n\nif [ \"$checksum_test_a\" != \"$checksum_test_b\"  ]\nthen \n\tvlog \"Checksums for table 'test' are not equal\"\n\texit -1\nfi\n\nif [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\nthen \n\tvlog \"Checksums for table 't2' are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 121}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Test for bug https://bugs.launchpad.net/percona-xtrabackup/+bug/737569\n. inc/common.sh\n\nstart_server\n\ninnobackupex --no-timestamp $topdir/backup\nbackup_dir=$topdir/backup\nvlog \"Backup created in directory $backup_dir\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n# Restore backup\nvlog \"Applying log\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ntouch $mysql_datadir/anyfile\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\nrun_cmd_expect_failure $IB_BIN $IB_ARGS --copy-back $backup_dir\n\nif grep -q \"is not empty!\" $OUTFILE\nthen\n    vlog \"innobackupex reported error about non-empty dirrectory correctly\"\n    exit 0\nelse\n    vlog \"innobackupex did not report an error about non-empty dir\"\n    exit 1\nfi\n", "num_lines": 35}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\nload_dbase_schema incremental_sample\n\n# Adding initial rows\nvlog \"Adding initial rows to database...\"\nnumrow=100\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\nvlog \"Initial rows added\"\n\n# Full backup\n# backup root directory\nmkdir -p $topdir/backup\n\nvlog \"Starting backup\"\ninnobackupex  $topdir/backup\nfull_backup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{print $2}'`\nvlog \"Full backup done to directory $full_backup_dir\"\n\n# Changing data\n\nvlog \"Making changes to database\"\n${MYSQL} ${MYSQL_ARGS} -e \"create table t2 (a int(11) default null, number int(11) default null) engine=innodb\" incremental_sample\nlet \"count=numrow+1\"\nlet \"numrow=1000\"\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into t2 values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_test_a=`checksum_table incremental_sample test`\nchecksum_t2_a=`checksum_table incremental_sample t2`\nvlog \"Table 'test' checksum is $checksum_test_a\"\nvlog \"Table 't2' checksum is $checksum_t2_a\"\n\nvlog \"Making incremental backup\"\n\nvlog \"###############\"\nvlog \"# INCREMENTAL #\"\nvlog \"###############\"\n\n# Incremental backup\ninnobackupex --incremental --incremental-basedir=$full_backup_dir \\\n    $topdir/backup\ninc_backup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | tail -n 1 | awk -F\\' '{print $2}'`\nvlog \"Incremental backup done to directory $inc_backup_dir\"\n\nvlog \"Preparing backup\"\n# Prepare backup\nvlog \"##############\"\nvlog \"# PREPARE #1 #\"\nvlog \"##############\"\ninnobackupex --apply-log --redo-only $full_backup_dir\nvlog \"Log applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #2 #\"\nvlog \"##############\"\ninnobackupex --apply-log --redo-only --incremental-dir=$inc_backup_dir \\\n    $full_backup_dir\nvlog \"Delta applied to full backup\"\nvlog \"##############\"\nvlog \"# PREPARE #3 #\"\nvlog \"##############\"\ninnobackupex --apply-log $full_backup_dir\nvlog \"Data prepared for restore\"\n\n# Destroying mysql data\nstop_server\nrm -rf $mysql_datadir/*\nvlog \"Data destroyed\"\n\n# Restore backup\nvlog \"Copying files\"\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $full_backup_dir\nvlog \"Data restored\"\n\nstart_server --innodb_file_per_table\n\nvlog \"Checking checksums\"\nchecksum_test_b=`checksum_table incremental_sample test`\nchecksum_t2_b=`checksum_table incremental_sample t2`\n\nif [ \"$checksum_test_a\" != \"$checksum_test_b\"  ]\nthen \n\tvlog \"Checksums for table 'test' are not equal\"\n\texit -1\nfi\n\nif [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\nthen \n\tvlog \"Checksums for table 't2' are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 109}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #543134: Missing support for LRU dump/restore\n########################################################################\n\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\n\n# produce ib_lru_dump\n${MYSQL} ${MYSQL_ARGS} -e \"select * from information_schema.XTRADB_ADMIN_COMMAND /*!XTRA_LRU_DUMP*/;\"\n\n# take a backup\ninnobackupex --no-timestamp $topdir/backup\n\nif [ -f $topdir/backup/ib_lru_dump ] ; then\n    vlog \"LRU dump has been backed up\"\nelse\n    vlog \"LRU dump has not been backed up\"\n    exit -1\nfi\n\n# restore from backup\nrm -rf $mysql_datadir/*\ninnobackupex --copy-back $topdir/backup\n\nif [ -f $mysql_datadir/ib_lru_dump ] ; then\n    vlog \"LRU dump has been restored\"\nelse\n    vlog \"LRU dump has not been restored\"\n    exit -1\nfi\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #543134: Missing support for LRU dump/restore\n########################################################################\n\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nif ! which rsync > /dev/null 2>&1 ; then\n    echo \"Requires rsync to be installed\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\n\n# produce ib_lru_dump\n${MYSQL} ${MYSQL_ARGS} -e \"select * from information_schema.XTRADB_ADMIN_COMMAND /*!XTRA_LRU_DUMP*/;\"\n\n# take a backup with rsync mode\ninnobackupex --rsync --no-timestamp $topdir/backup\n\nif [ -f $topdir/backup/ib_lru_dump ] ; then\n    vlog \"LRU dump has been backed up\"\nelse\n    vlog \"LRU dump has not been backed up\"\n    exit -1\nfi\n", "num_lines": 31}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #543134: Missing support for LRU dump/restore\n########################################################################\n\n. inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server\n\n# produce ib_lru_dump\n${MYSQL} ${MYSQL_ARGS} -e \"select * from information_schema.XTRADB_ADMIN_COMMAND /*!XTRA_LRU_DUMP*/;\"\n\n# take a backup with stream mode\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/stream.tar\n\nif $TAR itf $topdir/backup/stream.tar | grep ib_lru_dump ; then\n    vlog \"LRU dump has been backed up\"\nelse\n    vlog \"LRU dump has not been backed up\"\n    exit -1\nfi\n", "num_lines": 27}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --databases option with MyISAM\n#              database\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server\n\nrequire_partitioning\n\n# Create MyISAM partitioned table with some partitions in\n# different location\nib_part_init $topdir MyISAM\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\ncat >$topdir/databases_file <<EOF\ntest.test\nEOF\ninnobackupex --no-timestamp --databases=$topdir/databases_file $topdir/backup\ninnobackupex --apply-log $topdir/backup\nvlog \"Backup taken\"\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\n# compare checksum\nib_part_assert_checksum $checksum_a\n", "num_lines": 40}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --include option with InnoDB\n#              database\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server --innodb_file_per_table\n\nrequire_partitioning\n\n# Create InnoDB partitioned table\nib_part_init $topdir InnoDB\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\n# Only backup of test.test table will be taken\ncat >$topdir/tables <<EOF\ntest.test\nEOF\ninnobackupex --no-timestamp --include='test.test$' $topdir/backup\ninnobackupex --apply-log $topdir/backup\nvlog \"Backup taken\"\n\n# also test xtrabackup --stats work with --tables-file\nCOUNT=`xtrabackup --stats --tables='test.test$' --datadir=$topdir/backup \\\n       | grep table: | awk '{print $2}' | sort -u | wc -l`\n\nif [ $COUNT != 7 ] ; then\n\tvlog \"xtrabackup --stats does not work\"\n\texit -1\nfi\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\nib_part_assert_checksum $checksum_a\n", "num_lines": 48}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --include option with InnoDB\n#              database and --stream mode\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server --innodb_file_per_table\n\nrequire_partitioning\n\n# Create MyISAM partitioned table\nib_part_init $topdir MyISAM\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\nmkdir -p $topdir/backup\ninnobackupex --stream=tar --include='test.test$' $topdir/backup > $topdir/backup/backup.tar\n$TAR ixvf $topdir/backup/backup.tar -C $topdir/backup \n$TAR cvhf $topdir/backup/backup11.tar $mysql_datadir/test/*\n\ninnobackupex --apply-log $topdir/backup\n\nvlog \"Backup taken\"\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\nib_part_assert_checksum $checksum_a\n", "num_lines": 40}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --tables-file option with InnoDB\n#              database\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server --innodb_file_per_table\n\nrequire_partitioning\n\n# Create InnoDB partitioned table\nib_part_init $topdir InnoDB\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\n# Only backup of test.test table will be taken\ncat >$topdir/tables <<EOF\ntest.test\nEOF\ninnobackupex --no-timestamp --tables-file=$topdir/tables $topdir/backup\ninnobackupex --apply-log $topdir/backup\nvlog \"Backup taken\"\n\nCOUNT=`xtrabackup --stats --tables-file=$topdir/tables --datadir=$topdir/backup \\\n       | grep table: | awk '{print $2}' | sort -u | wc -l`\necho \"COUNT = $COUNT\"\nif [ $COUNT != 7 ] ; then\n\tvlog \"xtrabackup --stats does not work\"\n\texit -1\nfi\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\nib_part_assert_checksum $checksum_a\n", "num_lines": 47}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --tables-file option with InnoDB\n#              database and --stream mode\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server --innodb_file_per_table\n\nrequire_partitioning\n\n# Create InnoDB partitioned table\nib_part_init $topdir InnoDB\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\n# Only backup of test.test table will be taken\ncat >$topdir/tables <<EOF\ntest.test\nEOF\nmkdir -p $topdir/backup\ninnobackupex --stream=tar --no-timestamp --tables-file=$topdir/tables $topdir/backup > $topdir/backup/backup.tar\n$TAR ixvf $topdir/backup/backup.tar -C $topdir/backup \ninnobackupex --apply-log $topdir/backup\nvlog \"Backup taken\"\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\nib_part_assert_checksum $checksum_a\n", "num_lines": 41}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Bug #711166: Partitioned tables are not correctly handled by the\n#              --databases and --tables-file options of innobackupex,\n#              and by the --tables option of xtrabackup.\n#              Testcase covers using --tables-file option with MyISAM\n#              database\n########################################################################\n\n. inc/common.sh\n. inc/ib_part.sh\n\nstart_server\n\nrequire_partitioning\n\n# Create MyISAM partitioned table with some partitions in\n# different location\nib_part_init $topdir MyISAM\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\n# Take a backup\n# Only backup of test.test table will be taken\ncat >$topdir/tables <<EOF\ntest.test\nEOF\ninnobackupex --no-timestamp --tables-file=$topdir/tables $topdir/backup\ninnobackupex --apply-log $topdir/backup\nvlog \"Backup taken\"\n\nstop_server\n\n# Restore partial backup\nib_part_restore $topdir $mysql_datadir\n\nstart_server\n\nib_part_assert_checksum $checksum_a\n", "num_lines": 40}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nif ! which rsync > /dev/null 2>&1\nthen\n    echo \"Requires rsync to be installed\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_file_per_table\nload_sakila\n\ninnobackupex --rsync --no-timestamp $topdir/backup\n\nstop_server\n\nrun_cmd rm -r $mysql_datadir\n\ninnobackupex --apply-log $topdir/backup\n\nrun_cmd mkdir -p $mysql_datadir\n\ninnobackupex --copy-back $topdir/backup\n\nstart_server\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT COUNT(*) FROM actor\" sakila\n", "num_lines": 26}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nmaster_id=1\nslave_id=2\n\nstart_server_with_id $master_id\nstart_server_with_id $slave_id\n\nsetup_slave $slave_id $master_id\n\nswitch_server $master_id\nload_dbase_schema incremental_sample\n\n# Adding initial rows\nvlog \"Adding initial rows to database...\"\nnumrow=100\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\nvlog \"Initial rows added\"\n\n# Full backup of the slave server\nswitch_server $slave_id\n\nvlog \"Check that --slave-info with --no-lock and no --safe-slave-backup fails\"\nrun_cmd_expect_failure $IB_BIN $IB_ARGS --no-timestamp --slave-info --no-lock \\\n  $topdir/backup\n\ninnobackupex --no-timestamp --slave-info $topdir/backup\negrep -q '^mysql-bin.000001[[:space:]]+[0-9]+[[:space:]]+$' \\\n    $topdir/backup/xtrabackup_binlog_info\negrep -q '^CHANGE MASTER TO MASTER_LOG_FILE='\\''mysql-bin.000001'\\'', MASTER_LOG_POS=[0-9]+$' \\\n    $topdir/backup/xtrabackup_slave_info\n", "num_lines": 37}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\nPASSWD=\"123&123\"\nvlog \"Password is $PASSWD\"\n\nmkdir -p $topdir/backup\n\nrun_cmd ${MYSQLADMIN} ${MYSQL_ARGS} password '$PASSWD'\nvlog \"mysql password has been changed to contain special char\"\n\nvlog \"Starting innobackupex wrapper\"\ninnobackupex --password='$PASSWD' $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\n\nrun_cmd ${MYSQLADMIN} ${MYSQL_ARGS} -p'$PASSWD' password ''\n\nvlog \"Stopping database server\"\nstop_server\n# Remove datadir\nvlog \"Removing data folder\"\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"Performing copyback\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --copy-back $backup_dir\n\nvlog \"Starting database server\"\n# using --skip-grant-tables to override root password restored from backup\nstart_server --skip-grant-tables\nvlog \"Database server started\"\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila \n", "num_lines": 47}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Test streaming + compression\n############################################################################\n\nif ! which qpress > /dev/null 2>&1 ; then\n  echo \"Requires qpress to be installed\" > $SKIPPED_REASON\n  exit $SKIPPED_EXIT_CODE\nfi\n\nstream_format=xbstream\nstream_extract_cmd=\"xbstream -xv <\"\nstream_uncompress_cmd=\"for i in *.qp;  do qpress -d \\$i ./; done; \\\nfor i in sakila/*.qp; do qpress -d \\$i sakila/; done\"\ninnobackupex_options=\"--compress --compress-threads=4\"\n\n. inc/ib_stream_common.sh\n", "num_lines": 17}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Tests for streaming incremental backups\n########################################################################\n\n. inc/common.sh\n\n#\n# Test streaming incremental backup with a specified stream format\n#\n# Expects the following variables to be set before calling:\n# stream_format - current can be either 'xbstream' or 'tar'.\n# stream_extract_cmd - command to extract an archive of the format\n#                      specified with $stream_format\n#\nfunction test_streaming_incremental()\n{\n    vlog \"************************************************************************\"\n    vlog \"Testing a streaming incremental backup with the '$stream_format' format\"\n    vlog \"************************************************************************\"\n\n    start_server\n    load_dbase_schema incremental_sample\n\n# Adding initial rows\n    vlog \"Adding initial rows to database...\"\n    numrow=100\n    count=0\n    while [ \"$numrow\" -gt \"$count\" ]\n    do\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\n    done\n    vlog \"Initial rows added\"\n\n    full_backup_dir=$topdir/full_backup\n\n    vlog \"Starting backup\"\n    innobackupex --no-timestamp $full_backup_dir\n\n# Changing data\n\n    vlog \"Making changes to database\"\n    let \"count=numrow+1\"\n    let \"numrow=500\"\n    while [ \"$numrow\" -gt \"$count\" ]\n    do\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\n    done\n    vlog \"Changes done\"\n\n# Saving the checksum of original table\n    checksum_a=`checksum_table incremental_sample test`\n    vlog \"Table checksum is $checksum_a\"\n\n    vlog \"Making incremental backup\"\n\n# Incremental backup\n    inc_backup_dir=$topdir/inc_backup\n    mkdir $inc_backup_dir\n    innobackupex --stream=$stream_format --incremental \\\n\t--incremental-basedir=$full_backup_dir ./ > \\\n\t$inc_backup_dir/inc_backup_archive\n\n    vlog \"Preparing full backup\"\n    innobackupex --apply-log --redo-only $full_backup_dir\n    vlog \"Log applied to full backup\"\n\n    vlog \"Unpacking incremental backup archive\"\n    cd $inc_backup_dir\n    run_cmd bash -c \"$stream_extract_cmd inc_backup_archive\"\n    cd - >/dev/null 2>&1 \n    innobackupex --apply-log --redo-only --incremental-dir=$inc_backup_dir \\\n\t$full_backup_dir\n    vlog \"Delta applied to full backup\"\n\n    innobackupex --apply-log $full_backup_dir\n    vlog \"Data prepared for restore\"\n\n# Destroying mysql data\n    stop_server\n    rm -rf $mysql_datadir/*\n    vlog \"Data destroyed\"\n\n# Restore backup\n    vlog \"Copying files back to data directory\"\n    innobackupex --copy-back $full_backup_dir\n    vlog \"Data restored\"\n\n    start_server --innodb_file_per_table\n\n    vlog \"Checking checksums\"\n    checksum_b=`checksum_table incremental_sample test`\n\n    if [ \"$checksum_a\" != \"$checksum_b\"  ]\n    then \n\tvlog \"Checksums do not matc\"\n\texit -1\n    fi\n    \n    clean\n}\n\nstream_format=\"xbstream\"\nstream_extract_cmd=\"xbstream -xv <\"\ntest_streaming_incremental\n", "num_lines": 107}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Test parallel streaming feature of the 'xbstream' format\n############################################################################\n\nstream_format=xbstream\nstream_extract_cmd=\"xbstream -xv <\"\ninnobackupex_options=\"--parallel=16\"\n\n. inc/ib_stream_common.sh\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Test streaming in the TAR format\n############################################################################\n\nstream_extract_cmd=\"$TAR -ixvf\"\n\nstream_format=tar\n\n. inc/ib_stream_common.sh\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "############################################################################\n# Test streaming in the XBSTREAM format\n############################################################################\n\nstream_format=xbstream\nstream_extract_cmd=\"xbstream -xv <\"\n\n. inc/ib_stream_common.sh\n", "num_lines": 9}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "########################################################################\n# Tests for tar4ibd + symlinks (bug #387587)\n########################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Force a checkpoint\nstop_server\nstart_server\n\n# Copy some .ibd files to a temporary location and replace them with symlinks\n\nmv $MYSQLD_DATADIR/sakila/actor.ibd $MYSQLD_VARDIR/\nln -s $MYSQLD_VARDIR/actor.ibd $MYSQLD_DATADIR/sakila/actor.ibd\n\nmv $MYSQLD_DATADIR/sakila/customer.ibd $MYSQLD_VARDIR/customer.ibd\nln -s $MYSQLD_VARDIR/customer.ibd $MYSQLD_VARDIR/customer_link.ibd\nln -s $MYSQLD_VARDIR/customer_link.ibd $MYSQLD_DATADIR/sakila/customer.ibd\n\n# Take backup\nmkdir -p $MYSQLD_VARDIR/backup\ninnobackupex --stream=tar $MYSQLD_VARDIR/backup > $MYSQLD_VARDIR/backup/out.tar \n\nstop_server\n\n# Remove datadir\nrm -r $mysql_datadir\n\n# Remove the temporary files referenced by symlinks\nrm -f $MYSQLD_VARDIR/actor.ibd\nrm -f $MYSQLD_VARDIR/customer.ibd\nrm -f $MYSQLD_VARDIR/customer_link.ibd\n\n# Restore sakila\nvlog \"Applying log\"\nbackup_dir=$MYSQLD_VARDIR/backup\ncd $backup_dir\nrun_cmd $TAR -ixvf out.tar\ncd - >/dev/null 2>&1 \n\ninnobackupex --apply-log $backup_dir\n\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\n\ninnobackupex --copy-back $backup_dir\n\nstart_server\n\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT COUNT(*) FROM actor\" sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT COUNT(*) FROM customer\" sakila\n", "num_lines": 58}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\nmkdir -p $topdir/backup\ninnobackupex $topdir/backup\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\nvlog \"Backup created in directory $backup_dir\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n#init_mysql_dir\n# Restore sakila\nvlog \"Applying log\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $backup_dir\n\nstart_server\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 33}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#\n# Bug #798488: xtrabackup ignores defaults-file in apply-log-only prepare mode \n#\n# Test xtrabackup fails with an error when --defaults-file is not the first argument\n# on the command line (and thus would be ignored).\n\n. inc/common.sh\n\nstart_server\n\n# The following should succeed (can't use xtrabackup directly as it uses\n# --no-defaults)\nrun_cmd $XB_BIN --defaults-file=$topdir/my.cnf --backup \\\n    --datadir=$mysql_datadir --target-dir=$topdir/backup\n\nrm -rf $topdir/backup\n\n# The following should fail (can't use xtrabackup directly as that would make\n# the test fail)\n\nrun_cmd_expect_failure $XB_BIN --backup --defaults-file=$topdir/my.cnf \\\n    --datadir=$mysql_datadir --target-dir=$topdir/backup\n\nexit 0\n", "num_lines": 25}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nif [ -z \"$XTRADB_VERSION\" ]; then\n    echo \"Requires XtraDB\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nif [ ${MYSQL_VERSION:0:3} = \"5.5\" ]\nthen\n    import_option=\"--innodb_import_table_from_xtrabackup=1\"\nelse\n    import_option=\"--innodb_expand_import=1\"\nfi\n\nmysql_extra_args=\"--innodb_file_per_table $import_option \\\n--innodb_file_format=Barracuda\"\n\n# Starting database server\nstart_server $mysql_extra_args\n\nbackup_dir=$topdir/xb_export_backup\nrm -rf $backup_dir\nmkdir $backup_dir\n\n# Loading table schema\nload_dbase_schema incremental_sample\n\n# Adding some data to database\nvlog \"Adding initial rows to database...\"\nnumrow=100\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\nvlog \"Initial rows added\"\n\nchecksum_1=`checksum_table incremental_sample test`\nrowsnum_1=`${MYSQL} ${MYSQL_ARGS} -Ns -e \"select count(*) from test\" incremental_sample`\nvlog \"rowsnum_1 is $rowsnum_1\"\nvlog \"checksum_1 is $checksum_1\"\n\n# Performing table backup\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$backup_dir\nvlog \"Table was backed up\"\n\nvlog \"Re-initializing database server\"\nstop_server\nrm -rf ${MYSQLD_DATADIR}\nstart_server $mysql_extra_args\nload_dbase_schema incremental_sample\nvlog \"Database was re-initialized\"\n\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"alter table test discard tablespace;\" incremental_sample\n\n# Test the with innodb_file_per_table=0 --export bails out with an error\n# (bug #758888)\n\nrun_cmd_expect_failure $XB_BIN $XB_ARGS --datadir=$mysql_datadir --prepare \\\n    --export --target-dir=$backup_dir --innodb-file-per-table=0\n\nXB_ARGS=\"$XB_ARGS --innodb-file-per-table=1\"\n\nxtrabackup --datadir=$mysql_datadir --prepare --export \\\n    --target-dir=$backup_dir\n\nrun_cmd cp $backup_dir/incremental_sample/test* $mysql_datadir/incremental_sample/\nrun_cmd ls -lah $mysql_datadir/incremental_sample/\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"alter table test import tablespace\" incremental_sample\nvlog \"Table has been imported\"\n\nvlog \"Cheking checksums\"\nchecksum_2=`checksum_table incremental_sample test`\nvlog \"checksum_2 is $checksum_2\"\nrowsnum_1=`${MYSQL} ${MYSQL_ARGS} -Ns -e \"select count(*) from test\" incremental_sample`\nvlog \"rowsnum_1 is $rowsnum_1\"\n\nif [ \"$checksum_1\" != \"$checksum_2\"  ]\nthen \n\tvlog \"Checksums are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n\n# Tablespace import is asynchronous, so shutdown the server to have\n# consistent backup results. Otherwise we risk ending up with no test.ibd\n# in the backup in case importing has not finished before taking backup\n\nstop_server\nstart_server $mysql_extra_args\n\n# Some testing queries\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"select count(*) from test;\" incremental_sample\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"show create table test;\" incremental_sample\n\n# Performing full backup of imported table\nmkdir -p $topdir/backup/full\n\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/backup/full\n\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/backup/full\n\nxtrabackup --datadir=$mysql_datadir --prepare \\\n    --target-dir=$topdir/backup/full\n\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"delete from test;\" incremental_sample\n\nstop_server\n\ncd $topdir/backup/full\ncp -r * $mysql_datadir\ncd -\n\nstart_server $mysql_extra_args\n\nvlog \"Cheking checksums\"\nchecksum_3=`checksum_table incremental_sample test`\nvlog \"checksum_3 is $checksum_3\"\n\nif [ \"$checksum_3\" != \"$checksum_2\"  ]\nthen\n        vlog \"Checksums are not equal\"\n        exit -1\nfi\n\nvlog \"Checksums are OK\"\n\nstop_server\n\nrm -rf $backup_dir\n", "num_lines": 134}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nset +e\n${MYSQLD} --basedir=$MYSQL_BASEDIR --user=$USER --help --verbose --wsrep-sst-method=rsync| grep -q wsrep\nprobe_result=$?\nif [[ \"$probe_result\" == \"0\" ]]\n    then\n        vlog \"Server supports wsrep\"\n    else\n        echo \"Requires WSREP enabled\" > $SKIPPED_REASON\n        exit $SKIPPED_EXIT_CODE\nfi\nset -e\n\nstart_server --log-bin=`hostname`-bin --binlog-format=ROW --wsrep-provider=${MYSQL_BASEDIR}/lib/libgalera_smm.so --wsrep_cluster_address=gcomm://\n\ninnobackupex --no-timestamp --galera-info $topdir/backup \nbackup_dir=$topdir/backup\nvlog \"Backup created in directory $backup_dir\"\nif [[ \"`${MYSQL} ${MYSQL_ARGS} -Ns -e 'SHOW STATUS LIKE \"wsrep_local_state_uuid\"'|awk {'print $2'}`\" == \"`sed  -re 's/:.+$//' $topdir/backup/xtrabackup_galera_info`\" && \"`${MYSQL} ${MYSQL_ARGS} -Ns -e 'SHOW STATUS LIKE \"wsrep_last_committed\"'|awk {'print $2'}`\" == \"`sed  -re 's/^.+://' $topdir/backup/xtrabackup_galera_info`\" ]]\nthen\n\tvlog \"File is written correctly\"\nelse\n\tvlog \"File incorrect\"\n\texit 1\nfi\n\nstop_server\n", "num_lines": 29}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema incremental_sample\n\n# Adding 10k rows\n\nvlog \"Adding initial rows to database...\"\n\nnumrow=100\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\n\n\nvlog \"Initial rows added\"\n\n# Full backup\n\n# Full backup folder\nmkdir -p $topdir/data/full\n# Incremental data\nmkdir -p $topdir/data/delta\n\nvlog \"Starting backup\"\n\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/full\n\nvlog \"Full backup done\"\n\n# Changing data in sakila\n\nvlog \"Making changes to database\"\n\n${MYSQL} ${MYSQL_ARGS} -e \"create table t2 (a int(11) default null, number int(11) default null) engine=innodb\" incremental_sample\nlet \"count=numrow+1\"\nlet \"numrow=1000\"\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n        ${MYSQL} ${MYSQL_ARGS} -e \"insert into t2 values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\n\nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_test_a=`checksum_table incremental_sample test`\nchecksum_t2_a=`checksum_table incremental_sample t2`\n\nvlog \"Table 'test' checksum is $checksum_test_a\"\nvlog \"Table 't2' checksum is $checksum_t2_a\"\nvlog \"Making incremental backup\"\n\n# Incremental backup\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full\n\nvlog \"Incremental backup done\"\nvlog \"Preparing backup\"\n\n# Prepare backup\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full\nvlog \"Log applied to backup\"\nxtrabackup --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta\nvlog \"Delta applied to backup\"\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/full\nvlog \"Data prepared for restore\"\n\n# removing rows\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"delete from test;\" incremental_sample\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"delete from t2;\" incremental_sample\nvlog \"Tables cleared\"\n\n# Restore backup\nstop_server\nvlog \"Copying files\"\ncd $topdir/data/full/\ncp -r * $mysql_datadir\ncd $topdir\n\nvlog \"Data restored\"\nstart_server --innodb_file_per_table\n\nvlog \"Checking checksums\"\nchecksum_test_b=`checksum_table incremental_sample test`\nchecksum_t2_b=`checksum_table incremental_sample t2`\n\nif [ \"$checksum_test_a\" != \"$checksum_test_b\"  ]\nthen \n\tvlog \"Checksums of table 'test' are not equal\"\n\texit -1\nfi\n\nif [ \"$checksum_t2_a\" != \"$checksum_t2_b\"  ]\nthen \n\tvlog \"Checksums of table 't2' are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 107}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "source t/xb_incremental_compressed.inc\ntest_incremental_compressed 16\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "source t/xb_incremental_compressed.inc\ntest_incremental_compressed 1\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "source t/xb_incremental_compressed.inc\ntest_incremental_compressed 2\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "source t/xb_incremental_compressed.inc\ntest_incremental_compressed 4\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "source t/xb_incremental_compressed.inc\ntest_incremental_compressed 8\n", "num_lines": 3}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nif ! $XB_BIN --help 2>&1 | grep -q debug-sync; then\n    echo \"Requires --debug-sync support\" > $SKIPPED_REASON\n    exit $SKIPPED_EXIT_CODE\nfi\n\nstart_server --innodb_log_file_size=1M --innodb_thread_concurrency=1 \\\n    --innodb_log_buffer_size=1M\n\nload_dbase_schema sakila\nload_dbase_data sakila\nmkdir $topdir/backup\n\nrun_cmd_expect_failure $XB_BIN $XB_ARGS --datadir=$mysql_datadir --backup \\\n    --innodb_log_file_size=1M --target-dir=$topdir/backup \\\n    --debug-sync=\"xtrabackup_copy_logfile_pause\" &\n\njob_pid=$!\n\npid_file=$topdir/backup/xtrabackup_debug_sync\n\n# Wait for xtrabackup to suspend\ni=0\nwhile [ ! -r \"$pid_file\" ]\ndo\n    sleep 1\n    i=$((i+1))\n    echo \"Waited $i seconds for $pid_file to be created\"\ndone\n\nxb_pid=`cat $pid_file`\n\n# Create 4M+ of log data\n\n$MYSQL $MYSQL_ARGS -Ns -e \"CREATE TABLE tmp1 ENGINE=InnoDB SELECT * FROM payment\" sakila\n$MYSQL $MYSQL_ARGS -Ns -e \"CREATE TABLE tmp2 ENGINE=InnoDB SELECT * FROM payment\" sakila\n$MYSQL $MYSQL_ARGS -Ns -e \"CREATE TABLE tmp3 ENGINE=InnoDB SELECT * FROM payment\" sakila\n\n# Resume the xtrabackup process\nvlog \"Resuming xtrabackup\"\nkill -SIGCONT $xb_pid\n\n# wait's return code will be the code returned by the background process\nrun_cmd wait $job_pid\n", "num_lines": 46}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nvlog \"Creating the backup directory: $topdir/backup\"\nmkdir -p $topdir/backup\ninnobackupex $topdir/backup --parallel=8\nbackup_dir=`grep \"innobackupex: Backup created in directory\" $OUTFILE | awk -F\\' '{ print $2}'`\n\n#echo \"Backup dir in $backup_dir\"\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n# Restore sakila\nvlog \"Applying log\"\nvlog \"###########\"\nvlog \"# PREPARE #\"\nvlog \"###########\"\ninnobackupex --apply-log $backup_dir\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\nvlog \"###########\"\nvlog \"# RESTORE #\"\nvlog \"###########\"\ninnobackupex --copy-back $backup_dir\n\nstart_server\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 35}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "##########################################################################\n# Bug #826632: parallel option breaks incremental backups                #\n##########################################################################\n\n. inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nvlog \"Creating the backup directory: $topdir/backup\"\nbackup_dir=\"$topdir/backup\"\ninnobackupex $topdir/full_backup --no-timestamp --parallel=8\n\n# Make some changes for incremental backup by truncating and reloading\n# tables. TRUNCATE cannot be used here, because that would be executed\n# as DROP + CREATE internally for InnoDB tables, so tablespace IDs\n# would change.\n\ntable_list=`$MYSQL $MYSQL_ARGS -Ns -e \\\n\"SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='sakila' \\\nAND TABLE_TYPE='BASE TABLE'\"`\n\nfor t in $table_list\ndo\n    run_cmd $MYSQL $MYSQL_ARGS -s sakila <<EOF\nSET foreign_key_checks=0;\nDELETE FROM $t;\nSET foreign_key_checks=1;\nEOF\ndone\n\nload_dbase_data sakila\n\n# Do an incremental parallel backup\ninnobackupex --incremental --no-timestamp --parallel=8 \\\n    --incremental-basedir=$topdir/full_backup $topdir/inc_backup\n\nstop_server\n# Remove datadir\nrm -r $mysql_datadir\n\nvlog \"Applying log\"\ninnobackupex --apply-log --redo-only $topdir/full_backup\ninnobackupex --apply-log --redo-only --incremental-dir=$topdir/inc_backup \\\n    $topdir/full_backup\ninnobackupex --apply-log $topdir/full_backup\n\nvlog \"Restoring MySQL datadir\"\nmkdir -p $mysql_datadir\ninnobackupex --copy-back $topdir/full_backup\n\nstart_server\n\n# Check sakila\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"SELECT count(*) from actor\" sakila\n", "num_lines": 59}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server --innodb_file_per_table\n\nload_dbase_schema incremental_sample\n\n# Adding 10k rows\nvlog \"Adding initial rows to database...\"\nnumrow=1000\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count, $numrow);\" incremental_sample\n\tlet \"count=count+1\"\ndone\nvlog \"Initial rows added\"\nchecksum_a=`checksum_table incremental_sample test`\nvlog \"Table checksum is $checksum_a\"\n\n# Backup directory\nmkdir -p $topdir/data/parted\n\nvlog \"Starting backup\"\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/data/parted \\\n    --tables=\"^incremental_sample[.]test\"\nvlog \"Partial backup done\"\n\n# Prepare backup\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/data/parted\nvlog \"Data prepared for restore\"\n\n# removing rows\nrun_cmd ${MYSQL} ${MYSQL_ARGS} -e \"delete from test;\" incremental_sample\nvlog \"Table cleared\"\n\n# Restore backup\nstop_server\nvlog \"Copying files\"\ncd $topdir/data/parted/\ncp -r * $mysql_datadir\ncd $topdir\nvlog \"Data restored\"\nstart_server --innodb_file_per_table\nvlog \"Checking checksums\"\nchecksum_b=`checksum_table incremental_sample test`\n\nif [ \"$checksum_a\" != \"$checksum_b\"  ]\nthen \n\tvlog \"Checksums are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 54}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server\n\nfunction check_partitioning()\n{\n   $MYSQL $MYSQL_ARGS -Ns -e \"show variables like 'have_partitioning'\"\n}\n\nPARTITION_CHECK=`check_partitioning`\n\nif [ -z \"$PARTITION_CHECK\" ]; then\n    echo \"Requires Partitioning.\" > $SKIPPED_REASON\n    stop_server\n    exit $SKIPPED_EXIT_CODE\nfi\n\nrun_cmd $MYSQL $MYSQL_ARGS test <<EOF\nCREATE TABLE test (\n  a int(11) DEFAULT NULL\n) ENGINE=InnoDB DEFAULT CHARSET=latin1\nPARTITION BY RANGE (a)\n(PARTITION p0 VALUES LESS THAN (100) ENGINE = InnoDB,\n PARTITION P1 VALUES LESS THAN (200) ENGINE = InnoDB,\n PARTITION p2 VALUES LESS THAN (300) ENGINE = InnoDB,\n PARTITION p3 VALUES LESS THAN (400) ENGINE = InnoDB,\n PARTITION p4 VALUES LESS THAN MAXVALUE ENGINE = InnoDB);\nEOF\n\n# Adding 10k rows\n\nvlog \"Adding initial rows to database...\"\n\nnumrow=500\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count);\" test\n\tlet \"count=count+1\"\ndone\n\n\nvlog \"Initial rows added\"\n\n# Full backup\n\n# Full backup folder\nmkdir -p $topdir/data/full\n# Incremental data\nmkdir -p $topdir/data/delta\n\nvlog \"Starting backup\"\n\nxtrabackup --no-defaults --datadir=$mysql_datadir --backup \\\n    --target-dir=$topdir/data/full\n\nvlog \"Full backup done\"\n\n# Changing data in sakila\n\nvlog \"Making changes to database\"\n\nnumrow=500\ncount=0\nwhile [ \"$numrow\" -gt \"$count\" ]\ndo\n\t${MYSQL} ${MYSQL_ARGS} -e \"insert into test values ($count);\" test\n\tlet \"count=count+1\"\ndone\n\nvlog \"Changes done\"\n\n# Saving the checksum of original table\nchecksum_a=`checksum_table test test`\n\nvlog \"Table checksum is $checksum_a - before backup\"\n\nvlog \"Making incremental backup\"\n\n# Incremental backup\nxtrabackup --no-defaults --datadir=$mysql_datadir --backup \\\n    --target-dir=$topdir/data/delta --incremental-basedir=$topdir/data/full\n\nvlog \"Incremental backup done\"\nvlog \"Preparing backup\"\n\n# Prepare backup\nxtrabackup --no-defaults --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full\nvlog \"Log applied to backup\"\nxtrabackup --no-defaults --datadir=$mysql_datadir --prepare --apply-log-only \\\n    --target-dir=$topdir/data/full --incremental-dir=$topdir/data/delta\nvlog \"Delta applied to backup\"\nxtrabackup --no-defaults --datadir=$mysql_datadir --prepare \\\n    --target-dir=$topdir/data/full\nvlog \"Data prepared for restore\"\n\n# removing rows\nvlog \"Table cleared\"\n${MYSQL} ${MYSQL_ARGS} -e \"delete from test\" test\n\n# Restore backup\n\nstop_server\n\nvlog \"Copying files\"\n\ncd $topdir/data/full/\ncp -r * $mysql_datadir\ncd $topdir\n\nvlog \"Data restored\"\n\nstart_server\n\nvlog \"Cheking checksums\"\nchecksum_b=`checksum_table test test`\n\nif [ \"$checksum_a\" != \"$checksum_b\"  ]\nthen \n\tvlog \"Checksums are not equal\"\n\texit -1\nfi\n\nvlog \"Checksums are OK\"\n", "num_lines": 126}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Test for fix of https://bugs.launchpad.net/percona-xtrabackup/+bug/691090\n. inc/common.sh\n\nstart_server\n\nchmod -R 500 $mysql_datadir\ntrap \"vlog restoring permissions on datadir $mysql_datadir ; \\\nchmod -R 700 $mysql_datadir\" INT TERM EXIT\ninnobackupex  --no-timestamp $topdir/backup\n", "num_lines": 10}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Test for fix of https://bugs.launchpad.net/percona-xtrabackup/+bug/691090\n. inc/common.sh\n\nstart_server\n\n# Take backup\nchmod -R 500 $mysql_datadir\ntrap \"vlog restoring permissions on datadir $mysql_datadir ; \\\nchmod -R 700 $mysql_datadir\" INT TERM EXIT\nmkdir -p $topdir/backup\ninnobackupex --stream=tar $topdir/backup > $topdir/backup/out.tar\n", "num_lines": 12}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nstart_server\n\nload_dbase_schema sakila\nload_dbase_data sakila\n\n# Take backup\nmkdir -p $topdir/backup\nxtrabackup --datadir=$mysql_datadir --backup --target-dir=$topdir/backup\nvlog \"Backup taken, trying stats\"\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/backup\n\n# First check that xtrabackup fails with the correct error message\n# when trying to get stats before creating the log files\n\nvlog \"===> xtrabackup --stats --datadir=$topdir/backup\"\nrun_cmd_expect_failure $XB_BIN $XB_ARGS --stats --datadir=$topdir/backup\n\nif ! grep -q \"Cannot find log file ib_logfile0\" $OUTFILE\nthen\n    die \"Cannot find the expected error message from xtrabackup --stats\"\nfi\n\n# Now create the log files in the backup and try xtrabackup --stats again\n\nxtrabackup --datadir=$mysql_datadir --prepare --target-dir=$topdir/backup\n\nxtrabackup --stats --datadir=$topdir/backup\n\nvlog \"stats did not fail\"\n", "num_lines": 32}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": ". inc/common.sh\n\nxtrabackup --version\n\n", "num_lines": 5}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Execute this tool to setup the environment and build binary releases\n# for xtrabackup starting from a fresh tree.\n#\n# Usage: build-binary.sh [target dir]\n# The default target directory is the current directory. If it is not\n# supplied and the current directory is not empty, it will issue an error in\n# order to avoid polluting the current directory after a test run.\n#\n\n# Bail out on errors, be strict\nset -ue\n\n# Examine parameters\nTARGET=\"$(uname -m)\"\nTARGET_CFLAGS=''\n\n# Some programs that may be overriden\nTAR=${TAR:-tar}\n\n# Check if we have a functional getopt(1)\nif ! getopt --test\nthen\n    go_out=\"$(getopt --options=\"i\" --longoptions=i686 \\\n        --name=\"$(basename \"$0\")\" -- \"$@\")\"\n    test $? -eq 0 || exit 1\n    eval set -- $go_out\nfi\n\nfor arg\ndo\n    case \"$arg\" in\n    -- ) shift; break;;\n    -i | --i686 )\n        shift\n        TARGET=\"i686\"\n        TARGET_CFLAGS=\"-m32 -march=i686\"\n        ;;\n    esac\ndone\n\n# Working directory\nif test \"$#\" -eq 0\nthen\n    WORKDIR=\"$(pwd)\"\n    \n    # Check that the current directory is not empty\n    if test \"x$(echo *)\" != \"x*\"\n    then\n        echo >&2 \\\n            \"Current directory is not empty. Use $0 . to force build in .\"\n        exit 1\n    fi\n\n    WORKDIR_ABS=\"$(cd \"$WORKDIR\"; pwd)\"\n\nelif test \"$#\" -eq 1\nthen\n    WORKDIR=\"$1\"\n\n    # Check that the provided directory exists and is a directory\n    if ! test -d \"$WORKDIR\"\n    then\n        echo >&2 \"$WORKDIR is not a directory\"\n        exit 1\n    fi\n\n    WORKDIR_ABS=\"$(cd \"$WORKDIR\"; pwd)\"\n\nelse\n    echo >&2 \"Usage: $0 [target dir]\"\n    exit 1\n\nfi\n\nSOURCEDIR=\"$(cd $(dirname \"$0\"); cd ..; pwd)\"\ntest -e \"$SOURCEDIR/VERSION\" || exit 2\n\n# Read XTRABACKUP_VERSION from the VERSION file\n. $SOURCEDIR/VERSION\n\n# Build information\nREVISION=\"$(cd \"$SOURCEDIR\"; bzr revno)\"\n\n# Compilation flags\nexport CC=${CC:-gcc}\nexport CXX=${CXX:-gcc}\nexport CFLAGS=\"-fPIC -Wall -O3 -g -static-libgcc -fno-omit-frame-pointer ${CFLAGS:-}\"\nexport CXXFLAGS=\"-O2 -fno-omit-frame-pointer -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fno-exceptions ${CXXFLAGS:-}\"\nexport MAKE_JFLAG=-j4\n\n# Create a temporary working directory\nBASEINSTALLDIR=\"$(cd \"$WORKDIR\" && TMPDIR=\"$WORKDIR_ABS\" mktemp -d xtrabackup-build.XXXXXX)\"\nINSTALLDIR=\"$WORKDIR_ABS/$BASEINSTALLDIR/percona-xtrabackup-$XTRABACKUP_VERSION\"   # Make it absolute\n\nmkdir \"$INSTALLDIR\"\n\nexport AUTO_DOWNLOAD=yes\n\n# Build\n(\n    cd \"$WORKDIR\"\n\n    # Make a copy of the source\n    rm -f \"percona-xtrabackup-$XTRABACKUP_VERSION\"\n\n    bzr export \"percona-xtrabackup-$XTRABACKUP_VERSION\" \"$SOURCEDIR\"\n\n    # Build proper\n    (\n        cd \"percona-xtrabackup-$XTRABACKUP_VERSION\"\n\n        # Install the files\n        mkdir \"$INSTALLDIR/bin\" \"$INSTALLDIR/share\"\n        mkdir -p \"$INSTALLDIR/share/doc/percona-xtrabackup\"\n\n        bash utils/build.sh xtradb55\n        install -m 755 src/xtrabackup_55 \"$INSTALLDIR/bin\"\n\n        bash utils/build.sh xtradb\n        install -m 755 src/xtrabackup \"$INSTALLDIR/bin\"\n\n        bash utils/build.sh 5.1\n        install -m 755 src/xtrabackup_51 \"$INSTALLDIR/bin\"\n\n        install -m 755 src/xbstream \"$INSTALLDIR/bin\"\n\n        install -m 755 innobackupex \"$INSTALLDIR/bin\"\n        ln -s innobackupex \"$INSTALLDIR/bin/innobackupex-1.5.1\"\n\n        install -m 644 COPYING \"$INSTALLDIR/share/doc/percona-xtrabackup\"\n\n        cp -R test \"$INSTALLDIR/share/percona-xtrabackup-test\"\n\n    ) || false\n\n    $TAR czf \"percona-xtrabackup-$XTRABACKUP_VERSION-$REVISION.tar.gz\" \\\n        --owner=0 --group=0 -C \"$INSTALLDIR/../\" \\\n        \"percona-xtrabackup-$XTRABACKUP_VERSION\"\n\n    # Clean up build dir\n    rm -rf \"percona-xtrabackup-$XTRABACKUP_VERSION\"\n    \n) || false\n\n# Clean up\nrm -rf \"$WORKDIR_ABS/$BASEINSTALLDIR\"\n\n", "num_lines": 150}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Usage: build-dpkg.sh [target dir]\n# The default target directory is the current directory. If it is not\n# supplied and the current directory is not empty, it will issue an error in\n# order to avoid polluting the current directory after a test run.\n#\n# The program will setup the dpkg building environment and ultimately call\n# dpkg-buildpackage with the appropiate parameters.\n#\n\n# Bail out on errors, be strict\nset -ue\n\n# Examine parameters\ngo_out=\"$(getopt --options \"k:KbBSnT\"\\\n    --longoptions key:,nosign,binary,binarydep,source,dummy,notransitional \\\n    --name \"$(basename \"$0\")\" -- \"$@\")\"\ntest $? -eq 0 || exit 1\neval set -- $go_out\n\nBUILDPKG_KEY=''\nDPKG_BINSRC=''\nDUMMY=''\nNOTRANSITIONAL=''\n\nfor arg\ndo\n    case \"$arg\" in\n    -- ) shift; break;;\n    -k | --key ) shift; BUILDPKG_KEY=\"-pgpg -k$1\"; shift;;\n    -K | --nosign ) shift; BUILDPKG_KEY=\"-uc -us\";;\n    -b | --binary ) shift; DPKG_BINSRC='-b';;\n    -B | --binarydep ) shift; DPKG_BINSRC='-B';;\n    -S | --source ) shift; DPKG_BINSRC='-S';;\n    -n | --dummy ) shift; DUMMY='yes';;\n    -T | --notransitional ) shift; NOTRANSITIONAL='yes';;\n    esac\ndone\n\n# Working directory\nif test \"$#\" -eq 0\nthen\n    WORKDIR=\"$(pwd)\"\n\n    # Check that the current directory is not empty\n    if test \"x$(echo *)\" != \"x*\"\n    then\n        echo >&2 \\\n            \"Current directory is not empty. Use $0 . to force build in .\"\n        exit 1\n    fi\n\nelif test \"$#\" -eq 1\nthen\n    WORKDIR=\"$1\"\n\n    # Check that the provided directory exists and is a directory\n    if ! test -d \"$WORKDIR\"\n    then\n        echo >&2 \"$WORKDIR is not a directory\"\n        exit 1\n    fi\n\nelse\n    echo >&2 \"Usage: $0 [target dir]\"\n    exit 1\n\nfi\n\nSOURCEDIR=\"$(cd $(dirname \"$0\"); cd ..; pwd)\"\n\n# Read XTRABACKUP_VERSION from the VERSION file\n. $SOURCEDIR/VERSION\n\nDEBIAN_VERSION=\"$(lsb_release -sc)\"\nREVISION=\"$(cd \"$SOURCEDIR\"; bzr log -r-1 | grep ^revno: | cut -d ' ' -f 2)\"\nFULL_VERSION=\"$XTRABACKUP_VERSION-$REVISION.$DEBIAN_VERSION\"\n\n# Build information\nexport CC=${CC:-gcc}\nexport CXX=${CXX:-gcc}\nexport CFLAGS=\"-fPIC -Wall -O3 -g -static-libgcc -fno-omit-frame-pointer\"\nexport CXXFLAGS=\"-O2 -fno-omit-frame-pointer -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fno-exceptions\"\nexport MAKE_JFLAG=-j4\n\nexport DEB_BUILD_OPTIONS='debug nocheck'\nexport DEB_CFLAGS_APPEND=\"$CFLAGS\"\nexport DEB_CXXFLAGS_APPEND=\"$CXXFLAGS\"\n\n# Build\n(\n    # Make a copy in workdir and copy debian files\n    cd \"$WORKDIR\"\n    bzr export \"percona-xtrabackup-$FULL_VERSION\" \"$SOURCEDIR\"\n\n    (\n        cd \"percona-xtrabackup-$FULL_VERSION\"\n\n        # Move the debian dir to the appropriate place\n        cp -a \"$SOURCEDIR/utils/debian/\" .\n\n        # Don't build transitional packages if requested\n        if test \"x$NOTRANSITIONAL\" = \"xyes\"\n        then\n            sed -i '/Package: xtrabackup/,/^$/d' debian/control\n        fi\n\n        # Apply dummy patch if wanted\n        if test \"x$DUMMY\" = \"xyes\"\n        then\n            patch -p1 < 'utils/debian-dummy-rules.patch'\n        fi\n\n        # Update distribution\n        dch -m -D \"$DEBIAN_VERSION\" --force-distribution -v \"$XTRABACKUP_VERSION-$REVISION.$DEBIAN_VERSION\" 'Update distribution'\n        # Issue dpkg-buildpackage command\n        dpkg-buildpackage $DPKG_BINSRC $BUILDPKG_KEY\n \n    )\n\n    rm -rf \"percona-xtrabackup-$FULL_VERSION\"\n\n)\n", "num_lines": 124}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Execute this tool to setup and build RPMs for XtraBackup starting\n# from a fresh tree\n#\n# Usage: build-rpm.sh [--i686] [--nosign] [--test] [target dir]\n# The default target directory is the current directory. If it is not\n# supplied and the current directory is not empty, it will issue an error in\n# order to avoid polluting the current directory after a test run.\n#\n# The program will setup the rpm building environment and ultimately call\n# rpmbuild with the appropiate parameters.\n#\n\n# Bail out on errors, be strict\nset -ue\n\n# Examine parameters\nTARGET=''\nTARGET_CFLAGS=''\nTARGET_ARG=''\nSIGN='--sign'  # We sign by default\nTEST='no'    # We don't test by default\n\n# Check if we have got a functional getopt(1)\nif ! getopt --test\nthen\n    go_out=\"$(getopt --options=\"iKt\" --longoptions=i686,nosign,test \\\n        --name=\"$(basename \"$0\")\" -- \"$@\")\"\n    test $? -eq 0 || exit 1\n    eval set -- $go_out\nfi\n\nfor arg\ndo\n    case \"$arg\" in\n    -- ) shift; break;;\n    -i | --i686 )\n        shift\n        TARGET=\"--target i686\"\n        TARGET_CFLAGS=\"-m32 -march=i686\"\n        TARGET_ARG='i686'\n        ;;\n    -K | --nosign )\n        shift\n        SIGN=''\n        ;;\n    -t | --test )\n        shift\n        TEST='yes'\n        ;;\n    esac\ndone\n\n# Working directory\nif test \"$#\" -eq 0\nthen\n    WORKDIR=\"$(pwd)\"\n\n    # Check that the current directory is not empty\n    if test \"x$(echo *)\" != \"x*\"\n    then\n        echo >&2 \\\n            \"Current directory is not empty. Use $0 . to force build in .\"\n        exit 1\n    fi\n\n    WORKDIR_ABS=\"$(cd \"$WORKDIR\"; pwd)\"\n\nelif test \"$#\" -eq 1\nthen\n    WORKDIR=\"$1\"\n\n    # Check that the provided directory exists and is a directory\n    if ! test -d \"$WORKDIR\"\n    then\n        echo >&2 \"$WORKDIR is not a directory\"\n        exit 1\n    fi\n\n    WORKDIR_ABS=\"$(cd \"$WORKDIR\"; pwd)\"\n\nelse\n    echo >&2 \"Usage: $0 [target dir]\"\n    exit 1\n\nfi\n\nSOURCEDIR=\"$(cd $(dirname \"$0\"); cd ..; pwd)\"\ntest -e \"$SOURCEDIR/VERSION\" || exit 2\n\n# Read XTRABACKUP_VERSION from the VERSION file\n. $SOURCEDIR/VERSION\n\n# Build information\nREDHAT_RELEASE=\"$(grep -o 'release [0-9][0-9]*' /etc/redhat-release | \\\n    cut -d ' ' -f 2)\"\nREVISION=\"$(cd \"$SOURCEDIR\"; bzr log -r-1 | grep ^revno: | cut -d ' ' -f 2)\"\n\n# Fix problems in rpmbuild for rhel4: _libdir and _arch are not correctly set.\nif test \"x$REDHAT_RELEASE\" == \"x4\" && test \"x$TARGET_ARG\" == \"xi686\"\nthen\n    TARGET_LIBDIR='--define=_libdir=/usr/lib'\n    TARGET_ARCH='--define=_arch=i386'\nelse\n    TARGET_LIBDIR=''\n    TARGET_ARCH=''\nfi\n\n# Compilation flags\nexport CC=${CC:-gcc}\nexport CXX=${CXX:-gcc}\nexport CFLAGS=\"-fPIC -Wall -O3 -g -static-libgcc -fno-omit-frame-pointer $TARGET_CFLAGS\"\nexport CXXFLAGS=\"-O2 -fno-omit-frame-pointer -g -pipe -Wall -Wp,-D_FORTIFY_SOURCE=2 -fno-exceptions $TARGET_CFLAGS\"\nexport MAKE_JFLAG=-j4\n\nexport MYSQL_RPMBUILD_TEST=\"$TEST\"\n\n(\n    cd \"$WORKDIR\"\n\n    mkdir -p BUILD SOURCES RPMS SRPMS\n\n    # Copy source to SOURCE dir -- create a suitable tar\n    rm -f \"SOURCE/percona-xtrabackup-$XTRABACKUP_VERSION.tar.gz\"\n\n    bzr export \\\n        \"$WORKDIR_ABS/SOURCES/percona-xtrabackup-$XTRABACKUP_VERSION.tar.gz\" \\\n            \"$SOURCEDIR\"\n\n    # Issue RPM command\n    rpmbuild $SIGN $TARGET $TARGET_LIBDIR $TARGET_ARCH \\\n        -ba --clean \"$SOURCEDIR/utils/xtrabackup.spec\" \\\n        --define \"_topdir $WORKDIR_ABS\" \\\n        --define \"xtrabackup_version $XTRABACKUP_VERSION\" \\\n        --define \"xtrabackup_revision $REVISION\" \\\n        --define \"redhat_version $REDHAT_RELEASE\" \\\n        --define \"buildnumber $REVISION\"\n\n)\n\n", "num_lines": 142}
{"repo_name": "mysql-5.6", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nMYSQL_56_VERSION=5.6.10\n\nif [ -r ../CMakeCache.txt ]; then\n  echo BUILD_TYPE=${BUILD_TYPE:=\"$(grep CMAKE_BUILD_TYPE:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo SRC_DIR=${SRC_DIR:=\"$(grep MySQL_SOURCE_DIR:STATIC= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo CMAKE=${CMAKE:=\"$(grep CMAKE_COMMAND:INTERNAL= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo AR=${AR:=\"$(grep CMAKE_AR:FILEPATH= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo LD=${LD:=\"$(grep CMAKE_LINKER:FILEPATH= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo RANLIB=${RANLIB:=\"$(grep CMAKE_RANLIB:FILEPATH= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo CC=${CC:=\"$(grep CMAKE_C_COMPILER:FILEPATH= ../CMakeCache.txt | cut -f2- -d=) $(grep CMAKE_C_COMPILER_ARG1:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo CXX=${CXX:=\"$(grep CMAKE_CXX_COMPILER:FILEPATH= ../CMakeCache.txt | cut -f2- -d=) $(grep CMAKE_CXX_COMPILER_ARG1:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo CFLAGS=${CFLAGS:=\"$(grep CMAKE_C_FLAGS:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo CXXFLAGS=${CXXFLAGS:=\"$(grep CMAKE_CXX_FLAGS:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo LDFLAGS=${LDFLAGS:=\"$(grep CMAKE_EXE_LINKER_FLAGS:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\n  echo MYSQLD_LDFLAGS=${MYSQLD_LDFLAGS:=\"$(grep MYSQLD_LDFLAGS:STRING= ../CMakeCache.txt | cut -f2- -d=)\"}\nelse\n  echo BUILD_TYPE=${BUILD_TYPE:=RelWithDebInfo}\n  echo SRC_DIR=${SRC_DIR:=$(readlink -f ..)}\n  echo CMAKE=${CMAKE:=cmake}\n  echo AR= ${AR:-}\n  echo LD=${LD:-}\n  echo RANLIB=${RANLIB:-}\n  echo CC=${CC:=gcc}\n  echo CXX=${CXX:=g++}\n  echo CFLAGS=${CFLAGS:-}\n  echo CXXFLAGS=${CXXFLAGS:-}\n  echo LDFLAGS=${LDFLAGS:-}\n  echo MYSQLD_LDFLAGS=${MYSQLD_LDFLAGS:-}\nfi\n\nexport AR=\"$AR\"\nexport LD=\"$LD\"\nexport RANLIB=\"$RANLIB\"\nexport CC=\"$CC\"\nexport CXX=\"$CXX\"\nexport CFLAGS=\"$CFLAGS -DXTRABACKUP\"\nexport CXXFLAGS=\"$CXXFLAGS -DXTRABACKUP\"\nexport LDFLAGS=\"$LDFLAGS\"\nexport MYSQLD_LDFLAGS=\"$MYSQLD_LDFLAGS\"\nexport SRC_DIR=\"$SRC_DIR\"\nexport BUILD_TYPE=\"$BUILD_TYPE\"\n\nMAKE_CMD=make\nif gmake --version > /dev/null 2>&1\nthen\n    MAKE_CMD=gmake\nfi\nMAKE_CMD=\"$MAKE_CMD -j32\"\n\nfunction usage()\n{\n    echo \"Build an xtrabackup binary against the specified InnoDB flavor.\"\n    echo\n    echo \"Usage: `basename $0` CODEBASE\"\n    echo \"where CODEBASE can be one of the following values or aliases:\"\n    echo \"  innodb56         | 5.6                   build against InnoDB in MySQL 5.6\"\n    exit -1\n}\n\n################################################################################\n# Invoke 'make' in the specified directoies\n################################################################################\nfunction make_dirs()\n{\n    for d in $*\n    do\n    $MAKE_CMD -C $d\n    done\n}\n\nfunction build_server()\n{\n    local $type=$1\n    echo \"Configuring the server\"\n    cd $server_dir\n    echo eval $configure_cmd\n    eval $configure_cmd\n\n    echo \"Creating generated files\"\n    $MAKE_CMD -C sql GenDigestServerSource\n\n    echo \"Building the server\"\n    make_dirs libmysqld\n    cd $top_dir\n}\n\nfunction build_libarchive()\n{\n    echo \"Building libarchive\"\n    cd $top_dir/src/libarchive\n\n    ${CMAKE}  . \\\n        -DCMAKE_BUILD_TYPE=\"$BUILD_TYPE\" \\\n        -DCMAKE_AR=\"$AR\" \\\n        -DCMAKE_LINKER=\"$LD\" \\\n        -DCMAKE_RANLIB=\"$RANLIB\" \\\n        -DCMAKE_C_FLAGS=\"$CFLAGS\" \\\n        -DCMAKE_CXX_FLAGS=\"$CXXFLAGS\" \\\n        -DCMAKE_DISABLE_FIND_PACKAGE_BZip2=TRUE \\\n        -DCMAKE_DISABLE_FIND_PACKAGE_LZMA=TRUE \\\n        -DCMAKE_DISABLE_FIND_PACKAGE_LibXml2=TRUE \\\n        -DCMAKE_DISABLE_FIND_PACKAGE_EXPAT=TRUE \\\n        -DENABLE_TRACE=0 \\\n        -DENABLE_CPIO=OFF \\\n        -DENABLE_OPENSSL=OFF \\\n        -DENABLE_TAR=OFF \\\n        -DENABLE_TEST=OFF\n    $MAKE_CMD || exit -1\n}\n\nfunction build_xtrabackup()\n{\n    build_libarchive\n    echo \"Building XtraBackup\"\n\n    # Read XTRABACKUP_VERSION from the VERSION file\n    . $top_dir/VERSION\n\n    cd $top_dir/src\n    if [ \"`uname -s`\" = \"Linux\" ]\n    then\n    export LIBS=\"$LIBS -lrt\"\n    fi\n    $MAKE_CMD MYSQL_ROOT_DIR=$server_dir clean\n    $MAKE_CMD MYSQL_ROOT_DIR=$server_dir \\\n      XTRABACKUP_VERSION=$XTRABACKUP_VERSION $xtrabackup_target\n    cd $top_dir\n}\n\n\n################################################################################\n# Do all steps to build the server, xtrabackup and xbstream\n# Expects the following variables to be set before calling:\n#   mysql_version   version string (e.g. \"5.1.53\")\n#   server_patch    name of the patch to apply to server source before\n#                       building (e.g. \"xtradb51.patch\")\n#   innodb_name     either \"innobase\" or \"innodb_plugin\"\n#   configure_cmd   server configure command\n#   xtrabackup_target   'make' target to build in the xtrabackup build directory\n#\n################################################################################\nfunction build_all()\n{\n    local type=$1\n\n    mkdir -p $server_dir\n    build_server $type\n\n    build_xtrabackup\n}\n\nif ! test -f src/xtrabackup.cc\nthen\n    echo \"`basename $0` must be run from the directory with XtraBackup sources\"\n    usage\nfi\n\ntype=$1\ntop_dir=`pwd`\n\n\ncase \"$type\" in\n\"innodb56\" | \"5.6\")\n        mysql_version=$MYSQL_56_VERSION\n        server_patch=innodb56.patch\n        innodb_name=innobase\n        xtrabackup_target=5.6\n        mysql_version_short=${mysql_version:0:3}\n        server_dir=$top_dir/mysql-$mysql_version_short\n        configure_cmd=\"${CMAKE} $SRC_DIR \\\n                -DWITH_MYSQLD_LDFLAGS='$MYSQLD_LDFLAGS' \\\n                -DWITH_INNOBASE_STORAGE_ENGINE=ON \\\n                -DWITH_PERFSCHEMA_STORAGE_ENGINE=ON \\\n                -DMYSQL_DATADIR=\"/var/lib/mysql\" \\\n                -DMYSQL_UNIX_ADDR=\"/var/lib/mysql/mysql.sock\" \\\n                -DBUILD_CONFIG=mysql_release \\\n                -DMYSQL_USER=\"mysql\" \\\n                -DENABLE_DTRACE=0 \\\n                -DWITH_FAST_MUTEXES=1 \\\n                -DWITH_EXTRA_CHARSETS=all \\\n                -DWITH_EMBEDDED_SERVER=1 \\\n                -DWITHOUT_ROCKSDB_SE_STORAGE_ENGINE=1 \\\n                -DMYSQL_GITHASH=empty \\\n                -DMYSQL_GITDATE=empty \\\n                -DROCKSDB_GITHASH=empty \\\n                -DROCKSDB_GITDATE=empty \\\n                -DMYSQL_MAINTAINER_MODE=1 \\\n                -DMYSQL_ROOT_DIR=$server_dir \\\n                -DCMAKE_AR=$AR \\\n                -DCMAKE_LINKER=$LD \\\n                -DCMAKE_RANLIB=$RANLIB \\\n                -DCMAKE_BUILD_TYPE=$BUILD_TYPE\"\n        if [ -n \"$CMAKE_PREFIX_PATH\" ]; then\n                configure_cmd+=\" -DCMAKE_PREFIX_PATH=$CMAKE_PREFIX_PATH\"\n        fi\n        if [ -n \"$CURSES_LIBRARY\" ]; then\n                configure_cmd+=\" -DCURSES_LIBRARY=$CURSES_LIBRARY\"\n        fi\n        if [ -n \"$CURSES_INCLUDE_PATH\" ]; then\n                configure_cmd+=\" -DCURSES_INCLUDE_PATH=$CURSES_INCLUDE_PATH\"\n        fi\n        if [ -n \"$KRB_PATH\" ]; then\n                configure_cmd+=\" -DWITH_KRB=$KRB_PATH\"\n        fi\n        if [ -n \"$SSL_PATH\" ]; then\n                configure_cmd+=\" -DWITH_SSL=$SSL_PATH\"\n        fi\n        if [ -n \"$LZ4_PATH\" ]; then\n                configure_cmd+=\" -DWITH_LZ4=$LZ4_PATH\"\n        fi\n        if [ -n \"$ZSTD_PATH\" ]; then\n                configure_cmd+=\" -DWITH_ZSTD=$ZSTD_PATH\"\n        fi\n        if [ -n \"$ZLIB_PATH\" ]; then\n                configure_cmd+=\" -DWITH_ZLIB=$ZLIB_PATH\"\n        else\n                congigure_cmd+=\" -DWITH_ZLIB=bundled\"\n        fi\n        if [ -n \"$GLIBC_PATH\" ]; then\n                configure_cmd+=\" -DWITH_GLIBC=$GLIBC_PATH\"\n        fi\n        build_all $type\n        ;;\n\n*)\n    usage\n    ;;\nesac\n", "num_lines": 233}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -\n#\t$NetBSD: makelist,v 1.16 2010/04/18 21:17:05 christos Exp $\n#\n# Copyright (c) 1992, 1993\n#\tThe Regents of the University of California.  All rights reserved.\n#\n# This code is derived from software contributed to Berkeley by\n# Christos Zoulas of Cornell University.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n# 1. Redistributions of source code must retain the above copyright\n#    notice, this list of conditions and the following disclaimer.\n# 2. Redistributions in binary form must reproduce the above copyright\n#    notice, this list of conditions and the following disclaimer in the\n#    documentation and/or other materials provided with the distribution.\n# 3. Neither the name of the University nor the names of its contributors\n#    may be used to endorse or promote products derived from this software\n#    without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND\n# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE\n# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n# SUCH DAMAGE.\n#\n#\t@(#)makelist\t5.3 (Berkeley) 6/4/93\n\n# makelist.sh: Automatically generate header files...\n\nAWK=@AWK@\nUSAGE=\"Usage: $0 -n|-h|-e|-fc|-fh|-bc|-bh|-m <filenames>\"\n\nif [ \"x$1\" = \"x\" ]\nthen\n    echo $USAGE 1>&2\n    exit 1\nfi\n\nFLAG=\"$1\"\nshift\n\nFILES=\"$@\"\n\ncase $FLAG in\n\n#\tgenerate foo.h file from foo.c\n#\n-n)\n    cat << _EOF\n#undef WIDECHAR\n#define NARROWCHAR\n#include \"${FILES}\"\n_EOF\n    ;;\n    \n-h)\n    set - `echo $FILES | sed -e 's/\\\\./_/g'`\n    hdr=\"_h_`basename $1`\"\n    cat $FILES | $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#ifndef %s\\n#define %s\\n\", \"'$hdr'\", \"'$hdr'\");\n\t}\n\t/\\(\\):/ {\n\t    pr = substr($2, 1, 2);\n\t    if (pr == \"vi\" || pr == \"em\" || pr == \"ed\") {\n\t\t# XXXMYSQL: support CRLF\n\t\tname = substr($2, 1, index($2,\"(\") - 1);\n#\n# XXX:\tneed a space between name and prototype so that -fc and -fh\n#\tparsing is much easier\n#\n\t\tprintf(\"protected el_action_t\\t%s (EditLine *, Int);\\n\", name);\n\t    }\n\t}\n\tEND {\n\t    printf(\"#endif /* %s */\\n\", \"'$hdr'\");\n\t}'\n\t;;\n\n#\tgenerate help.c from various .c files\n#\n-bc)\n    cat $FILES | $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#include \\\"config.h\\\"\\n#include \\\"el.h\\\"\\n\");\n\t    printf(\"#include \\\"chartype.h\\\"\\n\");\n\t    printf(\"private const struct el_bindings_t el_func_help[] = {\\n\");\n\t    low = \"abcdefghijklmnopqrstuvwxyz_\";\n\t    high = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ_\";\n\t    for (i = 1; i <= length(low); i++)\n\t\ttr[substr(low, i, 1)] = substr(high, i, 1);\n\t}\n\t/\\(\\):/ {\n\t    pr = substr($2, 1, 2);\n\t    if (pr == \"vi\" || pr == \"em\" || pr == \"ed\") {\n\t\t# XXXMYSQL: support CRLF\n\t\tname = substr($2, 1, index($2,\"(\") - 1);\n\t\tuname = \"\";\n\t\tfname = \"\";\n\t\tfor (i = 1; i <= length(name); i++) {\n\t\t    s = substr(name, i, 1);\n\t\t    uname = uname tr[s];\n\t\t    if (s == \"_\")\n\t\t\ts = \"-\";\n\t\t    fname = fname s;\n\t\t}\n\n\t\tprintf(\"    { %-30.30s %-30.30s\\n\",\"STR(\\\"\" fname \"\\\"),\", uname \",\");\n\t\tok = 1;\n\t    }\n\t}\n\t/^ \\*/ {\n\t    if (ok) {\n\t\tprintf(\"      STR(\\\"\");\n\t\tfor (i = 2; i < NF; i++)\n\t\t    printf(\"%s \", $i);\n        # XXXMYSQL: support CRLF\n\t\tsub(\"\\r\", \"\", $i);\n\t\tprintf(\"%s\\\") },\\n\", $i);\n\t\tok = 0;\n\t    }\n\t}\n\tEND {\n\t    printf(\"};\\n\");\n\t    printf(\"\\nprotected const el_bindings_t* help__get()\");\n\t    printf(\"{ return el_func_help; }\\n\");\n\t}'\n\t;;\n\n#\tgenerate help.h from various .c files\n#\n-bh)\n    $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#ifndef _h_help_c\\n#define _h_help_c\\n\");\n\t    printf(\"protected const el_bindings_t *help__get(void);\\n\");\n\t    printf(\"#endif /* _h_help_c */\\n\");\n\t}' /dev/null\n\t;;\n\n#\tgenerate fcns.h from various .h files\n#\n# XXXMYSQL: use portable tr syntax\n-fh)\n    cat $FILES | $AWK '/el_action_t/ { print $3 }' | \\\n    sort | tr abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ | $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#ifndef _h_fcns_c\\n#define _h_fcns_c\\n\");\n\t    count = 0;\n\t}\n\t{\n\t    printf(\"#define\\t%-30.30s\\t%3d\\n\", $1, count++);\n\t}\n\tEND {\n\t    printf(\"#define\\t%-30.30s\\t%3d\\n\", \"EL_NUM_FCNS\", count);\n\n\t    printf(\"typedef el_action_t (*el_func_t)(EditLine *, Int);\");\n\t    printf(\"\\nprotected const el_func_t* func__get(void);\\n\");\n\t    printf(\"#endif /* _h_fcns_c */\\n\");\n\t}'\n\t;;\n\n#\tgenerate fcns.c from various .h files\n#\n-fc)\n    cat $FILES | $AWK '/el_action_t/ { print $3 }' | sort | $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#include \\\"config.h\\\"\\n#include \\\"el.h\\\"\\n\");\n\t    printf(\"private const el_func_t el_func[] = {\");\n\t    maxlen = 80;\n\t    needn = 1;\n\t    len = 0;\n\t}\n\t{\n\t    clen = 25 + 2;\n\t    len += clen;\n\t    if (len >= maxlen)\n\t\tneedn = 1;\n\t    if (needn) {\n\t\tprintf(\"\\n    \");\n\t\tneedn = 0;\n\t\tlen = 4 + clen;\n\t    }\n\t    s = $1 \",\";\n\t    printf(\"%-26.26s \", s);\n\t}\n\tEND {\n\t    printf(\"\\n};\\n\");\n\t    printf(\"\\nprotected const el_func_t* func__get() { return el_func; }\\n\");\n\t}'\n\t;;\n\n#\tgenerate editline.c from various .c files\n#\n-e)\n\techo \"$FILES\" | tr ' ' '\\012' | $AWK '\n\tBEGIN {\n\t    printf(\"/* Automatically generated file, do not edit */\\n\");\n\t    printf(\"#define protected static\\n\");\n\t    printf(\"#define SCCSID\\n\");\n\t}\n\t{\n\t    printf(\"#include \\\"%s\\\"\\n\", $1);\n\t}'\n\t;;\n\n#\tgenerate man page fragment from various .c files\n#\n-m)\n    cat $FILES | $AWK '\n\tBEGIN {\n\t    printf(\".\\\\\\\" Section automatically generated with makelist\\n\");\n\t    printf(\".Bl -tag -width 4n\\n\");\n\t}\n\t/\\(\\):/ {\n\t    pr = substr($2, 1, 2);\n\t    if (pr == \"vi\" || pr == \"em\" || pr == \"ed\") {\n\t\t# XXXMYSQL: support CRLF\n\t\tname = substr($2, 1, index($2, \"(\") - 1);\n\t\tfname = \"\";\n\t\tfor (i = 1; i <= length(name); i++) {\n\t\t    s = substr(name, i, 1);\n\t\t    if (s == \"_\")\n\t\t\ts = \"-\";\n\t\t    fname = fname s;\n\t\t}\n\n\t\tprintf(\".It Ic %s\\n\", fname);\n\t\tok = 1;\n\t    }\n\t}\n\t/^ \\*/ {\n\t    if (ok) {\n\t\tfor (i = 2; i < NF; i++)\n\t\t    printf(\"%s \", $i);\n\t\tprintf(\"%s.\\n\", $i);\n\t\tok = 0;\n\t    }\n\t}\n\tEND {\n\t    printf(\".El\\n\");\n\t    printf(\".\\\\\\\" End of section automatically generated with makelist\\n\");\n\t}'\n\t;;\n\n*)\n    echo $USAGE 1>&2\n    exit 1\n    ;;\n\nesac\n", "num_lines": 265}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nLIBTOOLIZE=libtoolize\nSYSNAME=`uname`\nif [ \"x$SYSNAME\" = \"xDarwin\" ] ; then\n  LIBTOOLIZE=glibtoolize\nfi\naclocal && \\\n\tautoheader && \\\n\t$LIBTOOLIZE && \\\n\tautoconf && \\\n\tautomake --add-missing --copy\n", "num_lines": 12}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nsetup () {\n\t EVENT_NOKQUEUE=yes; export EVENT_NOKQUEUE\n\t EVENT_NODEVPOLL=yes; export EVENT_NODEVPOLL\n\t EVENT_NOPOLL=yes; export EVENT_NOPOLL\n\t EVENT_NOSELECT=yes; export EVENT_NOSELECT\n\t EVENT_NOEPOLL=yes; export EVENT_NOEPOLL\n\t EVENT_NOEVPORT=yes; export EVENT_NOEVPORT\n}\n\ntest () {\n\tif ./test-init 2>/dev/null ;\n\tthen\n\t        true\n\telse\n\t\techo Skipping test\n\t\treturn\n\tfi\t\n\necho -n \" test-eof: \"\nif ./test-eof >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" test-weof: \"\nif ./test-weof >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" test-time: \"\nif ./test-time >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\necho -n \" regress: \"\nif ./regress >/dev/null ; \nthen \n\techo OKAY ; \nelse \n\techo FAILED ; \nfi\n}\n\necho \"Running tests:\"\n\n# Need to do this by hand?\nsetup\nunset EVENT_NOKQUEUE\nexport EVENT_NOKQUEUE\necho \"KQUEUE\"\ntest\n\nsetup\nunset EVENT_NODEVPOLL\nexport EVENT_NODEVPOLL\necho \"DEVPOLL\"\ntest\n\nsetup\nunset EVENT_NOPOLL\nexport EVENT_NOPOLL\necho \"POLL\"\ntest\n\nsetup\nunset EVENT_NOSELECT\nexport EVENT_NOSELECT\necho \"SELECT\"\ntest\n\nsetup\nunset EVENT_NOEPOLL\nexport EVENT_NOEPOLL\necho \"EPOLL\"\ntest\n\nsetup\nunset EVENT_NOEVPORT\nexport EVENT_NOEVPORT\necho \"EVPORT\"\ntest\n\n\n\n", "num_lines": 92}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Run this script to generate the configure script and other files that will\n# be included in the distribution.  These files are not checked in because they\n# are automatically generated.\n\nset -e\n\n# Check that we're being run from the right directory.\nif test ! -f src/google/protobuf/stubs/common.h; then\n  cat >&2 << __EOF__\nCould not find source code.  Make sure you are running this script from the\nroot of the distribution tree.\n__EOF__\n  exit 1\nfi\n\n# Check that gtest is present.  Usually it is already there since the\n# directory is set up as an SVN external.\nif test ! -e gtest; then\n  echo \"Google Test not present.  Fetching gtest-1.5.0 from the web...\"\n  curl http://googletest.googlecode.com/files/gtest-1.5.0.tar.bz2 | tar jx\n  mv gtest-1.5.0 gtest\nfi\n\nset -ex\n\n# Temporary hack:  Must change C runtime library to \"multi-threaded DLL\",\n#   otherwise it will be set to \"multi-threaded static\" when MSVC upgrades\n#   the project file to MSVC 2005/2008.  vladl of Google Test says gtest will\n#   probably change their default to match, then this will be unnecessary.\n#   One of these mappings converts the debug configuration and the other\n#   converts the release configuration.  I don't know which is which.\nsed -i -e 's/RuntimeLibrary=\"5\"/RuntimeLibrary=\"3\"/g;\n           s/RuntimeLibrary=\"4\"/RuntimeLibrary=\"2\"/g;' gtest/msvc/*.vcproj\n\n# TODO(kenton):  Remove the \",no-obsolete\" part and fix the resulting warnings.\nautoreconf -f -i -Wall,no-obsolete\n\nrm -rf autom4te.cache config.h.in~\nexit 0\n", "num_lines": 42}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Run this script to regenerate descriptor.pb.{h,cc} after the protocol\n# compiler changes.  Since these files are compiled into the protocol compiler\n# itself, they cannot be generated automatically by a make rule.  \"make check\"\n# will fail if these files do not match what the protocol compiler would\n# generate.\n#\n# HINT:  Flags passed to generate_descriptor_proto.sh will be passed directly\n#   to make when building protoc.  This is particularly useful for passing\n#   -j4 to run 4 jobs simultaneously.\n\nif test ! -e src/google/protobuf/stubs/common.h; then\n  cat >&2 << __EOF__\nCould not find source code.  Make sure you are running this script from the\nroot of the distribution tree.\n__EOF__\n  exit 1\nfi\n\nif test ! -e src/Makefile; then\n  cat >&2 << __EOF__\nCould not find src/Makefile.  You must run ./configure (and perhaps\n./autogen.sh) first.\n__EOF__\n  exit 1\nfi\n\ncd src\nmake $@ protoc &&\n  ./protoc --cpp_out=dllexport_decl=LIBPROTOBUF_EXPORT:. google/protobuf/descriptor.proto && \\\n  ./protoc --cpp_out=dllexport_decl=LIBPROTOC_EXPORT:. google/protobuf/compiler/plugin.proto\ncd ..\n", "num_lines": 34}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Protocol Buffers - Google's data interchange format\n# Copyright 2009 Google Inc.  All rights reserved.\n# https://developers.google.com/protocol-buffers/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Author: kenton@google.com (Kenton Varda)\n#\n# Test protoc's zip output mode.\n\nfail() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nTEST_TMPDIR=.\nPROTOC=./protoc\n\necho '\n  syntax = \"proto2\";\n  option java_multiple_files = true;\n  option java_package = \"test.jar\";\n  option java_outer_classname = \"Outer\";\n  message Foo {}\n  message Bar {}\n' > $TEST_TMPDIR/testzip.proto\n\n$PROTOC \\\n    --cpp_out=$TEST_TMPDIR/testzip.zip --python_out=$TEST_TMPDIR/testzip.zip \\\n    --java_out=$TEST_TMPDIR/testzip.jar -I$TEST_TMPDIR testzip.proto \\\n    || fail 'protoc failed.'\n\necho \"Testing output to zip...\"\nif unzip -h > /dev/null; then\n  unzip -t $TEST_TMPDIR/testzip.zip > $TEST_TMPDIR/testzip.list || fail 'unzip failed.'\n\n  grep 'testing: testzip\\.pb\\.cc *OK$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'testzip.pb.cc not found in output zip.'\n  grep 'testing: testzip\\.pb\\.h *OK$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'testzip.pb.h not found in output zip.'\n  grep 'testing: testzip_pb2\\.py *OK$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'testzip_pb2.py not found in output zip.'\n  grep -i 'manifest' $TEST_TMPDIR/testzip.list > /dev/null \\\n    && fail 'Zip file contained manifest.'\nelse\n  echo \"Warning:  'unzip' command not available.  Skipping test.\"\nfi\n\necho \"Testing output to jar...\"\nif jar c $TEST_TMPDIR/testzip.proto > /dev/null; then\n  jar tf $TEST_TMPDIR/testzip.jar > $TEST_TMPDIR/testzip.list || fail 'jar failed.'\n\n  grep '^test/jar/Foo\\.java$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'Foo.java not found in output jar.'\n  grep '^test/jar/Bar\\.java$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'Bar.java not found in output jar.'\n  grep '^test/jar/Outer\\.java$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'Outer.java not found in output jar.'\n  grep '^META-INF/MANIFEST\\.MF$' $TEST_TMPDIR/testzip.list > /dev/null \\\n    || fail 'Manifest not found in output jar.'\nelse\n  echo \"Warning:  'jar' command not available.  Skipping test.\"\nfi\n\necho PASS\n", "num_lines": 92}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -x\n#\n# Protocol Buffers - Google's data interchange format\n# Copyright 2009 Google Inc.  All rights reserved.\n# https://developers.google.com/protocol-buffers/\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n#\n# Author: brianolson@google.com (Brian Olson)\n#\n# Test compatibility between command line gzip/gunzip binaries and\n# ZeroCopyStream versions.\n\nTESTFILE=Makefile\n\n(./zcgzip < ${TESTFILE} | gunzip | cmp - ${TESTFILE}) && \\\n(gzip < ${TESTFILE} | ./zcgunzip | cmp - ${TESTFILE})\n\n# Result of \"(cmd) && (cmd)\" implicitly becomes result of this script\n# and thus the test.\n", "num_lines": 45}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Update Doxygen documentation after push to 'master'.\n# Author: @pah\n\nset -e\n\nDOXYGEN_VER=doxygen-1.8.7\nDOXYGEN_TAR=${DOXYGEN_VER}.linux.bin.tar.gz\nDOXYGEN_URL=\"http://ftp.stack.nl/pub/users/dimitri/${DOXYGEN_TAR}\"\nDOXYGEN_BIN=\"/usr/local/bin/doxygen\"\n\n: ${GITHUB_REPO:=\"miloyip/rapidjson\"}\nGITHUB_HOST=\"github.com\"\nGITHUB_CLONE=\"git://${GITHUB_HOST}/${GITHUB_REPO}\"\nGITHUB_URL=\"https://${GITHUB_HOST}/${GITHUB_PUSH-${GITHUB_REPO}}\"\n\n# if not set, ignore password\n#GIT_ASKPASS=\"${TRAVIS_BUILD_DIR}/gh_ignore_askpass.sh\"\n\nskip() {\n\techo \"$@\" 1>&2\n\techo \"Exiting...\" 1>&2\n\texit 0\n}\n\nabort() {\n\techo \"Error: $@\" 1>&2\n\techo \"Exiting...\" 1>&2\n\texit 1\n}\n\n# TRAVIS_BUILD_DIR not set, exiting\n[ -d \"${TRAVIS_BUILD_DIR-/nonexistent}\" ] || \\\n\tabort '${TRAVIS_BUILD_DIR} not set or nonexistent.'\n\n# check for pull-requests\n[ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ] || \\\n\tskip \"Not running Doxygen for pull-requests.\"\n\n# check for branch name\n[ \"${TRAVIS_BRANCH}\" = \"master\" ] || \\\n\tskip \"Running Doxygen only for updates on 'master' branch (current: ${TRAVIS_BRANCH}).\"\n\n# check for job number\n# [ \"${TRAVIS_JOB_NUMBER}\" = \"${TRAVIS_BUILD_NUMBER}.1\" ] || \\\n# \tskip \"Running Doxygen only on first job of build ${TRAVIS_BUILD_NUMBER} (current: ${TRAVIS_JOB_NUMBER}).\"\n\n# install doxygen binary distribution\ndoxygen_install()\n{\n\twget -O - \"${DOXYGEN_URL}\" | \\\n\t\ttar xz -C ${TMPDIR-/tmp} ${DOXYGEN_VER}/bin/doxygen\n    export PATH=\"${TMPDIR-/tmp}/${DOXYGEN_VER}/bin:$PATH\"\n}\n\ndoxygen_run()\n{\n\tcd \"${TRAVIS_BUILD_DIR}\";\n\tdoxygen ${TRAVIS_BUILD_DIR}/build/doc/Doxyfile;\n\tdoxygen ${TRAVIS_BUILD_DIR}/build/doc/Doxyfile.zh-cn;\n}\n\ngh_pages_prepare()\n{\n\tcd \"${TRAVIS_BUILD_DIR}/build/doc\";\n\t[ ! -d \"html\" ] || \\\n\t\tabort \"Doxygen target directory already exists.\"\n\tgit --version\n\tgit clone -b gh-pages \"${GITHUB_CLONE}\" html\n\tcd html\n\t# setup git config (with defaults)\n\tgit config user.name \"${GIT_NAME-travis}\"\n\tgit config user.email \"${GIT_EMAIL-\"travis@localhost\"}\"\n\t# clean working dir\n\trm -f .git/index\n\tgit clean -df\n}\n\ngh_pages_commit() {\n\tcd \"${TRAVIS_BUILD_DIR}/build/doc/html\";\n\techo \"rapidjson.org\" > CNAME\n\tgit add --all;\n\tgit diff-index --quiet HEAD || git commit -m \"Automatic doxygen build\";\n}\n\ngh_setup_askpass() {\n\tcat > ${GIT_ASKPASS} <<EOF\n#!/bin/bash\necho\nexit 0\nEOF\n\tchmod a+x \"$GIT_ASKPASS\"\n}\n\ngh_pages_push() {\n\t# check for secure variables\n\t[ \"${TRAVIS_SECURE_ENV_VARS}\" = \"true\" ] || \\\n\t\tskip \"Secure variables not available, not updating GitHub pages.\"\n\t# check for GitHub access token\n\t[ \"${GH_TOKEN+set}\" = set ] || \\\n\t\tskip \"GitHub access token not available, not updating GitHub pages.\"\n\t[ \"${#GH_TOKEN}\" -eq 40 ] || \\\n\t\tabort \"GitHub token invalid: found ${#GH_TOKEN} characters, expected 40.\"\n\n\tcd \"${TRAVIS_BUILD_DIR}/build/doc/html\";\n\t# setup credentials (hide in \"set -x\" mode)\n\tgit remote set-url --push origin \"${GITHUB_URL}\"\n\tgit config credential.helper 'store'\n\t# ( set +x ; git config credential.username \"${GH_TOKEN}\" )\n\t( set +x ; [ -f ${HOME}/.git-credentials ] || \\\n\t\t\t( echo \"https://${GH_TOKEN}:@${GITHUB_HOST}\" > ${HOME}/.git-credentials ; \\\n\t\t\t chmod go-rw ${HOME}/.git-credentials ) )\n\t# push to GitHub\n\tgit push origin gh-pages\n}\n\ndoxygen_install\ngh_pages_prepare\ndoxygen_run\ngh_pages_commit\ngh_pages_push\n\n", "num_lines": 123}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# test all yassl cipher suties \n# \n\n\nno_pid=-1\nserver_pid=$no_pid\n\n\ndo_cleanup() {\n    echo \"in cleanup\"\n\n    if [[ $server_pid != $no_pid ]]\n    then\n        echo \"killing server\"\n        kill -9 $server_pid\n    fi\n}\n\ndo_trap() {\n    echo \"got trap\"\n    do_cleanup\n    exit -1\n}\n\ntrap do_trap INT TERM\n\n\n# make sure example server and client are built\nif test ! -s ../examples/server/server; then\n    echo \"Please build yaSSL first, example server missing\"\n    exit -1\nfi\n\nif test ! -s ../examples/client/client; then\n    echo \"Please build yaSSL first, example client missing\"\n    exit -1\nfi\n\n\n# non DSA suites\nfor suite in {\"DHE-RSA-AES256-SHA\",\"AES256-SHA\",\"DHE-RSA-AES128-SHA\",\"AES128-SHA\",\"AES256-RMD\",\"AES128-RMD\",\"DES-CBC3-RMD\",\"DHE-RSA-AES256-RMD\",\"DHE-RSA-AES128-RMD\",\"DHE-RSA-DES-CBC3-RMD\",\"RC4-SHA\",\"RC4-MD5\",\"DES-CBC3-SHA\",\"DES-CBC-SHA\",\"EDH-RSA-DES-CBC3-SHA\",\"EDH-RSA-DES-CBC-SHA\"}\ndo\n  for client_auth in {y,n}\n  do\n    echo \"Trying $suite client auth = $client_auth ...\"\n\n    if test -e server_ready; then\n        echo -e \"removing exisitng server_ready file\"\n        rm server_ready\n    fi\n    ../examples/server/server $client_auth &\n    server_pid=$!\n\n    while [ ! -s server_ready ]; do\n        echo -e \"waiting for server_ready file...\"\n        sleep 0.1\n    done\n\n    ../examples/client/client $suite\n    client_result=$?\n\n    wait $server_pid\n    server_result=$?\n\n    server_pid=$no_pid\n\n    if [[ $client_result != 0 ]]\n    then\n        echo \"Client Error\"\n        exit $client_result\n    fi\n\n    if [[ $server_result != 0 ]]\n    then\n        echo \"Server Error\"\n        exit $server_result\n    fi\n\n  done   # end client auth loop\ndone  # end non dsa suite list\necho -e \"Non DSA Loop SUCCESS\"\n\n\n\n# DSA suites\nfor suite in {\"DHE-DSS-AES256-SHA\",\"DHE-DSS-AES128-SHA\",\"DHE-DSS-AES256-RMD\",\"DHE-DSS-AES128-RMD\",\"DHE-DSS-DES-CBC3-RMD\",\"EDH-DSS-DES-CBC3-SHA\",\"EDH-DSS-DES-CBC-SHA\"}\ndo\n  for client_auth in {y,n}\n  do\n    echo \"Trying $suite client auth = $client_auth ...\"\n\n    if test -e server_ready; then\n        echo -e \"removing exisitng server_ready file\"\n        rm server_ready\n    fi\n    # d signifies DSA\n    ../examples/server/server $client_auth d &\n    server_pid=$!\n\n    while [ ! -s server_ready ]; do\n        echo -e \"waiting for server_ready file...\"\n        sleep 0.1\n    done\n\n    ../examples/client/client $suite\n    client_result=$?\n\n    wait $server_pid\n    server_result=$?\n\n    server_pid=$no_pid\n\n    if [[ $client_result != 0 ]]\n    then\n        echo \"Client Error\"\n        exit $client_result\n    fi\n\n    if [[ $server_result != 0 ]]\n    then\n        echo \"Server Error\"\n        exit $server_result\n    fi\n\n  done   # end client auth loop\ndone  # end dsa suite list\necho -e \"DSA Loop SUCCESS\"\n\nexit 0\n", "num_lines": 132}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/std_data_master_link\nln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_master_link\n", "num_lines": 5}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/std_data_slave_link\nln -s $MYSQLTEST_VARDIR/std_data $MYSQLTEST_VARDIR/std_data_slave_link\n", "num_lines": 5}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\nrm -f $MYSQLTEST_VARDIR/master-data/test/rpl_misc_functions.outfile\n", "num_lines": 4}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nmkdir $MYSQLTEST_VARDIR/tmp/innodb\ncp $MYSQLTEST_VARDIR/mysqld.1/data/ibdata1 $MYSQLTEST_VARDIR/tmp/innodb\ncp $MYSQLTEST_VARDIR/mysqld.1/data/ib_buffer_pool $MYSQLTEST_VARDIR/tmp/innodb\nmkdir $MYSQLTEST_VARDIR/tmp/innodb_logs\ncp $MYSQLTEST_VARDIR/mysqld.1/data/ib_logfile* $MYSQLTEST_VARDIR/tmp/innodb_logs\nmkdir $MYSQLTEST_VARDIR/tmp/innodb_undo", "num_lines": 8}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nd=\"$MYSQLTEST_VARDIR/tmp/long_temporary_directory_path_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 6}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# This test requires a non-lowercase tmpdir directory on a case-sensitive\n# filesystem.\n\nd=\"$MYSQLTEST_VARDIR/tmp/MixedCase\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 9}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# This test requires a non-lowercase tmpdir directory on a case-sensitive\n# filesystem.\n\nd=\"$MYSQLTEST_VARDIR/tmp/MixedCase\"\ntest -d \"$d\" || mkdir \"$d\"\nrm -f \"$d\"/*\n", "num_lines": 9}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "mysqld_pid=`cat $1`\nkill -9 $mysqld_pid\n", "num_lines": 3}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.prov $* |\nsed -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n\n/usr/lib/rpm/perl.req $* |\nsed -e '/perl(GD)/d' -e '/perl(hostnames)/d' -e '/perl(lib::mtr.*/d' -e '/perl(lib::v1.*/d' -e '/perl(mtr_.*/d' -e '/perl(My::.*/d'\n\n", "num_lines": 7}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Wrapper script for mysql_config to support multilib\n#\n#\n\n# This command respects setarch, works on OL6/RHEL6 and later\nbits=$(rpm --eval %__isa_bits)\n\ncase $bits in\n    32|64) ;;\n        *) bits=unknown ;;\nesac\n\n# Try mapping by uname if rpm command failed\nif [ \"$bits\" = \"unknown\" ] ; then\n    arch=$(uname -m)\n    case $arch in\n\tx86_64|ppc64|ppc64le|aarch64|s390x|sparc64) bits=64 ;;\n\ti386|i486|i586|i686|pentium3|pentium4|athlon|ppc|s390|sparc) bits=32 ;;\n\t*) bits=unknown ;;\n    esac\nfi\n\nif [ \"$bits\" == \"unknown\" ] ; then\n    echo \"$0: error: failed to determine isa bits on your arch.\"\n    exit 1\nfi\n\nif [ -x /usr/bin/mysql_config-$bits ] ; then\n    /usr/bin/mysql_config-$bits \"$@\"\nelse\n    echo \"$0: error: needed binary: /usr/bin/mysql_config-$bits is missing. Please check your MySQL installation.\"\n    exit 1\nfi\n", "num_lines": 36}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA\n#\n# Solaris post install script\n#\n\n#if [ /usr/man/bin/makewhatis ] ; then\n#  /usr/man/bin/makewhatis \"$BASEDIR/mysql/man\"\n#fi\n\nmygroup=mysql\nmyuser=mysql\nmydatadir=/var/lib/mysql\nbasedir=@@basedir@@\nmysecurefiledir=/var/lib/mysql-files\nmykeyringdir=/var/lib/mysql-keyring\n\nif [ -n \"$BASEDIR\" ] ; then\n  basedir=\"$BASEDIR\"\nfi\n\n# What MySQL calls \"basedir\" and what pkgadd tools calls \"basedir\"\n# is not the same thing. The default pkgadd base directory is /opt/mysql,\n# the MySQL one \"/opt/mysql/mysql\".\n\nmybasedir=\"$basedir/@@instdir@@\"\nmystart1=\"$mybasedir/support-files/mysql.server\"\nmystart=/etc/init.d/mysql\n\n# Check: Is this a first installation, or an upgrade ?\n\nif [ -d \"$mydatadir/mysql\" ] ; then\n  :   # If the directory for system table files exists, we assume an upgrade.\nelse\n  INSTALL=new  # This is a new installation, the directory will soon be created.\nfi\n\n# Create data directory if needed\n\n[ -d \"$mydatadir\"       ] || mkdir -p -m 750 \"$mydatadir\" || exit 1\n\n# Set the data directory to the right user/group\n\nchown -R $myuser:$mygroup $mydatadir\n\n# Create securefile directory\n[ -d \"$mysecurefiledir\"  ] || mkdir -p -m 770 \"$mysecurefiledir\"      || exit 1\nchown -R $myuser:$mygroup $mysecurefiledir\n\n# Create Keyring directory\n[ -d \"$mykeyringdir\"  ] || mkdir -p -m 750 \"$mykeyringdir\"      || exit 1\nchown -R $myuser:$mygroup $mykeyringdir\n\n# Solaris patch 119255 (somewhere around revision 42) changes the behaviour\n# of pkgadd to set TMPDIR internally to a root-owned install directory.  This\n# has the unfortunate side effect of breaking running mysqld --initialize with\n# the --user=mysql argument as mysqld uses TMPDIR if set, and is unable to\n# write temporary tables to that directory.  To work around this issue, we\n# create a subdirectory inside TMPDIR (if set) for mysqld to write to.\n#\n# Idea from Ben Hekster <heksterb@gmail.com> in bug#31164\n\nif [ -n \"$TMPDIR\" ] ; then\n  savetmpdir=\"$TMPDIR\"\n  TMPDIR=\"$TMPDIR/mysql.$$\"\n  export TMPDIR\n  mkdir \"$TMPDIR\"\n  chown $myuser:$mygroup \"$TMPDIR\"\nfi\n\nif [ -n \"$INSTALL\" ] ; then\n  # We install/update the system tables\n  (\n    cd \"$mybasedir\"\n    bin/mysqld --initialize \\\n\t  --user=mysql \\\n\t  --basedir=\"$mybasedir\" \\\n\t  --datadir=$mydatadir\n  )\nfi\n\nif [ -n \"$savetmpdir\" ] ; then\n  TMPDIR=\"$savetmpdir\"\nfi\n\n# ----------------------------------------------------------------------\n\n# Handle situation there is old start script installed already\n\n# If old start script is a soft link, we just remove it\n[ -h \"$mystart\" ] && rm -f \"$mystart\"\n\n# If old start script is a file, we rename it\n[ -f \"$mystart\" ] && mv -f \"$mystart\" \"$mystart.old.$$\"\n\n# ----------------------------------------------------------------------\n\n# We create a copy of an unmodified start script,\n# as a reference for the one maybe modifying it\n\ncp -f \"$mystart1.in\" \"$mystart.in\" || exit 1\n\n# We rewrite some scripts\n\nfor script in \"$mystart\" \"$mystart1\"; do\n  script_in=\"$script.in\"\n  sed -e \"s,@basedir@,$mybasedir,g\" \\\n      -e \"s,@datadir@,$mydatadir,g\" \"$script_in\" > \"$script\"\n  chmod u+x $script\ndone\n\nrm -f \"$mystart.in\"\n\nexit 0\n\n", "num_lines": 130}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\nMEMC_VERSION=`git describe | tr '-' '_'`;\ncat > .libs/config_version.h << EOF\n#ifndef CONFIG_VERSION_H\n#define CONFIG_VERSION_H\n\n/* Define to the full name and version of this package. */\n#define PACKAGE_STRING \"memcached $MEMC_VERSION\"\n\n/* Define to the version of this package. */\n#define PACKAGE_VERSION \"$MEMC_VERSION\"\n\n/* Version number of package */\n#define VERSION \"$MEMC_VERSION\"\n\n#endif // CONFIG_VERSION_H\nEOF\n", "num_lines": 18}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!@PERL_PATH@\n\n# Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n# mysqldumpslow - parse and summarize the MySQL slow query log\n\n# Original version by Tim Bunce, sometime in 2000.\n# Further changes by Tim Bunce, 8th March 2001.\n# Handling of strings with \\ and double '' by Monty 11 Aug 2001.\n\nuse strict;\nuse Getopt::Long;\n\n# t=time, l=lock time, r=rows\n# at, al, and ar are the corresponding averages\n\nmy %opt = (\n    s => 'at',\n    h => '*',\n);\n\nGetOptions(\\%opt,\n    'v|verbose+',# verbose\n    'help+',\t# write usage info\n    'd|debug+',\t# debug\n    's=s',\t# what to sort by (al, at, ar, c, t, l, r)\n    'r!',\t# reverse the sort order (largest last instead of first)\n    't=i',\t# just show the top n queries\n    'a!',\t# don't abstract all numbers to N and strings to 'S'\n    'n=i',\t# abstract numbers with at least n digits within names\n    'g=s',\t# grep: only consider stmts that include this string\n    'h=s',\t# hostname of db server for *-slow.log filename (can be wildcard)\n    'i=s',\t# name of server instance (if using mysql.server startup script)\n    'l!',\t# don't subtract lock time from total time\n) or usage(\"bad option\");\n\n$opt{'help'} and usage();\n\nunless (@ARGV) {\n    my $defaults   = `my_print_defaults mysqld`;\n    my $basedir = ($defaults =~ m/--basedir=(.*)/)[0]\n\tor die \"Can't determine basedir from 'my_print_defaults mysqld' output: $defaults\";\n    warn \"basedir=$basedir\\n\" if $opt{v};\n\n    my $datadir = ($defaults =~ m/--datadir=(.*)/)[0];\n    my $slowlog = ($defaults =~ m/--slow-query-log-file=(.*)/)[0];\n    if (!$datadir or $opt{i}) {\n\t# determine the datadir from the instances section of /etc/my.cnf, if any\n\tmy $instances  = `my_print_defaults instances`;\n\tdie \"Can't determine datadir from 'my_print_defaults mysqld' output: $defaults\"\n\t    unless $instances;\n\tmy @instances = ($instances =~ m/^--(\\w+)-/mg);\n\tdie \"No -i 'instance_name' specified to select among known instances: @instances.\\n\"\n\t    unless $opt{i};\n\tdie \"Instance '$opt{i}' is unknown (known instances: @instances)\\n\"\n\t    unless grep { $_ eq $opt{i} } @instances;\n\t$datadir = ($instances =~ m/--$opt{i}-datadir=(.*)/)[0]\n\t    or die \"Can't determine --$opt{i}-datadir from 'my_print_defaults instances' output: $instances\";\n\twarn \"datadir=$datadir\\n\" if $opt{v};\n    }\n\n    if ( -f $slowlog ) {\n        @ARGV = ($slowlog);\n        die \"Can't find '$slowlog'\\n\" unless @ARGV;\n    } else {\n        @ARGV = <$datadir/$opt{h}-slow.log>;\n        die \"Can't find '$datadir/$opt{h}-slow.log'\\n\" unless @ARGV;\n    }\n}\n\nwarn \"\\nReading mysql slow query log from @ARGV\\n\";\n\nmy @pending;\nmy %stmt;\n$/ = \";\\n#\";\t\t# read entire statements using paragraph mode\nwhile ( defined($_ = shift @pending) or defined($_ = <>) ) {\n    warn \"[[$_]]\\n\" if $opt{d};\t# show raw paragraph being read\n\n    my @chunks = split /^\\/.*Version.*started with[\\000-\\377]*?Time.*Id.*Command.*Argument.*\\n/m;\n    if (@chunks > 1) {\n\tunshift @pending, map { length($_) ? $_ : () } @chunks;\n\twarn \"<<\".join(\">>\\n<<\",@chunks).\">>\" if $opt{d};\n\tnext;\n    }\n\n    s/^#? Time: \\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d+(Z|[+-]\\d{2}:\\d{2}).*\\n//;\n    my ($user,$host,$dummy,$thread_id) = s/^#? User\\@Host:\\s+(\\S+)\\s+\\@\\s+(\\S+)\\s+\\S+(\\s+Id:\\s+(\\d+))?.*\\n// ? ($1,$2,$3,$4) : ('','','','','');\n\n    s/^# Query_time: ([0-9.]+)\\s+Lock_time: ([0-9.]+)\\s+Rows_sent: ([0-9.]+).*\\n//;\n    my ($t, $l, $r) = ($1, $2, $3);\n    $t -= $l unless $opt{l};\n\n    # remove fluff that mysqld writes to log when it (re)starts:\n    s!^/.*Version.*started with:.*\\n!!mg;\n    s!^Tcp port: \\d+  Unix socket: \\S+\\n!!mg;\n    s!^Time.*Id.*Command.*Argument.*\\n!!mg;\n\n    s/^use \\w+;\\n//;\t# not consistently added\n    s/^SET timestamp=\\d+;\\n//;\n\n    s/^[ \t]*\\n//mg;\t# delete blank lines\n    s/^[ \t]*/  /mg;\t# normalize leading whitespace\n    s/\\s*;\\s*(#\\s*)?$//;\t# remove trailing semicolon(+newline-hash)\n\n    next if $opt{g} and !m/$opt{g}/io;\n\n    unless ($opt{a}) {\n\ts/\\b\\d+\\b/N/g;\n\ts/\\b0x[0-9A-Fa-f]+\\b/N/g;\n        s/''/'S'/g;\n        s/\"\"/\"S\"/g;\n        s/(\\\\')//g;\n        s/(\\\\\")//g;\n        s/'[^']+'/'S'/g;\n        s/\"[^\"]+\"/\"S\"/g;\n\t# -n=8: turn log_20001231 into log_NNNNNNNN\n\ts/([a-z_]+)(\\d{$opt{n},})/$1.('N' x length($2))/ieg if $opt{n};\n\t# abbreviate massive \"in (...)\" statements and similar\n\ts!(([NS],){100,})!sprintf(\"$2,{repeated %d times}\",length($1)/2)!eg;\n    }\n\n    my $s = $stmt{$_} ||= { users=>{}, hosts=>{} };\n    $s->{c} += 1;\n    $s->{t} += $t;\n    $s->{l} += $l;\n    $s->{r} += $r;\n    $s->{users}->{$user}++ if $user;\n    $s->{hosts}->{$host}++ if $host;\n\n    warn \"{{$_}}\\n\\n\" if $opt{d};\t# show processed statement string\n}\n\nforeach (keys %stmt) {\n    my $v = $stmt{$_} || die;\n    my ($c, $t, $l, $r) = @{ $v }{qw(c t l r)};\n    $v->{at} = $t / $c;\n    $v->{al} = $l / $c;\n    $v->{ar} = $r / $c;\n}\n\nmy @sorted = sort { $stmt{$b}->{$opt{s}} <=> $stmt{$a}->{$opt{s}} } keys %stmt;\n@sorted = @sorted[0 .. $opt{t}-1] if $opt{t};\n@sorted = reverse @sorted         if $opt{r};\n\nforeach (@sorted) {\n    my $v = $stmt{$_} || die;\n    my ($c, $t,$at, $l,$al, $r,$ar) = @{ $v }{qw(c t at l al r ar)};\n    my @users = keys %{$v->{users}};\n    my $user  = (@users==1) ? $users[0] : sprintf \"%dusers\",scalar @users;\n    my @hosts = keys %{$v->{hosts}};\n    my $host  = (@hosts==1) ? $hosts[0] : sprintf \"%dhosts\",scalar @hosts;\n    printf \"Count: %d  Time=%.2fs (%ds)  Lock=%.2fs (%ds)  Rows=%.1f (%d), $user\\@$host\\n%s\\n\\n\",\n\t    $c, $at,$t, $al,$l, $ar,$r, $_;\n}\n\nsub usage {\n    my $str= shift;\n    my $text= <<HERE;\nUsage: mysqldumpslow [ OPTS... ] [ LOGS... ]\n\nParse and summarize the MySQL slow query log. Options are\n\n  --verbose    verbose\n  --debug      debug\n  --help       write this text to standard output\n\n  -v           verbose\n  -d           debug\n  -s ORDER     what to sort by (al, at, ar, c, l, r, t), 'at' is default\n                al: average lock time\n                ar: average rows sent\n                at: average query time\n                 c: count\n                 l: lock time\n                 r: rows sent\n                 t: query time  \n  -r           reverse the sort order (largest last instead of first)\n  -t NUM       just show the top n queries\n  -a           don't abstract all numbers to N and strings to 'S'\n  -n NUM       abstract numbers with at least n digits within names\n  -g PATTERN   grep: only consider stmts that include this string\n  -h HOSTNAME  hostname of db server for *-slow.log filename (can be wildcard),\n               default is '*', i.e. match all\n  -i NAME      name of server instance (if using mysql.server startup script)\n  -l           don't subtract lock time from total time\n\nHERE\n    if ($str) {\n      print STDERR \"ERROR: $str\\n\\n\";\n      print STDERR $text;\n      exit 1;\n    } else {\n      print $text;\n      exit 0;\n    }\n}\n", "num_lines": 212}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!@PERL_PATH@\n\n# Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\nuse Getopt::Long;\nuse POSIX qw(strftime getcwd);\nuse File::Path qw(mkpath);\n\n$|=1;\n$VER=\"2.16\";\n\nmy @defaults_options;   #  Leading --no-defaults, --defaults-file, etc.\n\n$opt_example       = 0;\n$opt_help          = 0;\n$opt_log           = undef();\n$opt_mysqladmin    = \"@bindir@/mysqladmin\";\n$opt_mysqld        = \"@libexecdir@/mysqld\";\n$opt_no_log        = 0;\n$opt_password      = undef();\n$opt_tcp_ip        = 0;\n$opt_user          = \"root\";\n$opt_version       = 0;\n$opt_silent        = 0;\n$opt_verbose       = 0;\n\nmy $my_print_defaults_exists= 1;\nmy $logdir= undef();\n\nmy ($mysqld, $mysqladmin, $groupids, $homedir, $my_progname);\n\n$homedir = $ENV{HOME};\n$my_progname = $0;\n$my_progname =~ s/.*[\\/]//;\n\n\nif (defined($ENV{UMASK})) {\n  my $UMASK = $ENV{UMASK};\n  my $m;\n  my $fmode = \"0640\";\n\n  if(($UMASK =~ m/[^0246]/) || ($UMASK =~ m/^[^0]/) || (length($UMASK) != 4)) {\n    printf(\"UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\\n\");\n    printf(\"The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\\n\"); }\n  else {\n    $fmode= substr $UMASK, 2, 2;\n    $fmode= \"06${fmode}\"; }\n\n  if($fmode != $UMASK) {\n    printf(\"UMASK corrected from $UMASK to $fmode ...\\n\"); }\n\n  $fmode= oct($fmode);\n\n  umask($fmode);\n}\n\n\nmain();\n\n####\n#### main sub routine\n####\n\nsub main\n{\n  my $flag_exit= 0;\n\n  if (!defined(my_which(my_print_defaults)))\n  {\n    # We can't throw out yet, since --version, --help, or --example may\n    # have been given\n    print \"WARNING: my_print_defaults command not found.\\n\";\n    print \"Please make sure you have this command available and\\n\";\n    print \"in your path. The command is available from the latest\\n\";\n    print \"MySQL distribution.\\n\";\n    $my_print_defaults_exists= 0;\n  }\n\n  # Remove leading defaults options from @ARGV\n  while (@ARGV > 0)\n  {\n    last unless $ARGV[0] =~\n      /^--(?:no-defaults$|(?:defaults-file|defaults-extra-file)=)/;\n    push @defaults_options, (shift @ARGV);\n  }\n\n  foreach (@defaults_options)\n  {\n    $_ = quote_shell_word($_);\n  }\n\n  # Add [mysqld_multi] options to front of @ARGV, ready for GetOptions()\n  unshift @ARGV, defaults_for_group('mysqld_multi');\n\n  # We've already handled --no-defaults, --defaults-file, etc.\n  if (!GetOptions(\"help\", \"example\", \"version\", \"mysqld=s\", \"mysqladmin=s\",\n                  \"user=s\", \"password=s\", \"log=s\", \"no-log\",\n                  \"tcp-ip\",  \"silent\", \"verbose\"))\n  {\n    $flag_exit= 1;\n  }\n  usage() if ($opt_help);\n\n  if ($opt_verbose && $opt_silent)\n  {\n    print \"Both --verbose and --silent have been given. Some of the warnings \";\n    print \"will be disabled\\nand some will be enabled.\\n\\n\";\n  }\n\n  init_log() if (!defined($opt_log));\n  $groupids = $ARGV[1];\n  if ($opt_version)\n  {\n    print \"$my_progname version $VER by Jani Tolonen\\n\";\n    exit(0);\n  }\n  example() if ($opt_example);\n  if ($flag_exit)\n  {\n    print \"Error with an option, see $my_progname --help for more info.\\n\";\n    exit(1);\n  }\n  if (!defined(my_which(my_print_defaults)))\n  {\n    print \"ABORT: Can't find command 'my_print_defaults'.\\n\";\n    print \"This command is available from the latest MySQL\\n\";\n    print \"distribution. Please make sure you have the command\\n\";\n    print \"in your PATH.\\n\";\n    exit(1);\n  }\n  usage() if (!defined($ARGV[0]) ||\n\t      (!($ARGV[0] =~ m/^start$/i) &&\n\t       !($ARGV[0] =~ m/^stop$/i) &&\n\t       !($ARGV[0] =~ m/^reload$/i) &&\n\t       !($ARGV[0] =~ m/^report$/i)));\n\n  if (!$opt_no_log)\n  {\n    w2log(\"$my_progname log file version $VER; run: \",\n\t  \"$opt_log\", 1, 0);\n  }\n  else\n  {\n    print \"$my_progname log file version $VER; run: \";\n    print strftime \"%a %b %e %H:%M:%S %Y\", localtime;\n    print \"\\n\";\n  }\n  if (($ARGV[0] =~ m/^start$/i) || ($ARGV[0] =~ m/^reload$/i))\n  {\n    if (!defined(($mysqld= my_which($opt_mysqld))) && $opt_verbose)\n    {\n      print \"WARNING: Couldn't find the default mysqld binary.\\n\";\n      print \"Tried: $opt_mysqld\\n\";\n      print \"This is OK, if you are using option \\\"mysqld=...\\\" in \";\n      print \"groups [mysqldN] separately for each.\\n\\n\";\n    }\n    if ($ARGV[0] =~ m/^start$/i) {\n      start_mysqlds();\n    } elsif ($ARGV[0] =~ m/^reload$/i) {\n      reload_mysqlds();\n    }\n  }\n  else\n  {\n    if (!defined(($mysqladmin= my_which($opt_mysqladmin))) && $opt_verbose)\n    {\n      print \"WARNING: Couldn't find the default mysqladmin binary.\\n\";\n      print \"Tried: $opt_mysqladmin\\n\";\n      print \"This is OK, if you are using option \\\"mysqladmin=...\\\" in \";\n      print \"groups [mysqldN] separately for each.\\n\\n\";\n    }\n    if ($ARGV[0] =~ m/^report$/i)\n    {\n      report_mysqlds();\n    }\n    else\n    {\n      stop_mysqlds();\n    }\n  }\n}\n\n#\n# Quote word for shell\n#\n\nsub quote_shell_word\n{\n  my ($option)= @_;\n\n  $option =~ s!([^\\w=./-])!\\\\$1!g;\n  return $option;\n}\n\nsub defaults_for_group\n{\n  my ($group) = @_;\n\n  return () unless $my_print_defaults_exists;\n\n  my $com= join ' ', 'my_print_defaults', @defaults_options, $group;\n  my @defaults = `$com`;\n  chomp @defaults;\n  return @defaults;\n}\n\n####\n#### Init log file. Check for appropriate place for log file, in the following\n#### order:  my_print_defaults mysqld datadir, @datadir@\n####\n\nsub init_log\n{\n  foreach my $opt (defaults_for_group('mysqld'))\n  {\n    if ($opt =~ m/^--datadir=(.*)/ && -d \"$1\" && -w \"$1\")\n    {\n      $logdir= $1;\n    }\n  }\n  if (!defined($logdir))\n  {\n    $logdir= \"@datadir@\" if (-d \"@datadir@\" && -w \"@datadir@\");\n  }\n  if (!defined($logdir))\n  {\n    # Log file was not specified and we could not log to a standard place,\n    # so log file be disabled for now.\n    if (!$opt_silent)\n    {\n      print \"WARNING: Log file disabled. Maybe directory or file isn't writable?\\n\";\n    }\n    $opt_no_log= 1;\n  }\n  else\n  {\n    $opt_log= \"$logdir/mysqld_multi.log\";\n  }\n}\n\n####\n#### Report living and not running MySQL servers\n####\n\nsub report_mysqlds\n{\n  my (@groups, $com, $i, @options, $pec);\n\n  print \"Reporting MySQL servers\\n\";\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nReporting MySQL servers\",\"$opt_log\",0,0);\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $com= get_mysqladmin_options($i, @groups);\n    $com.= \" ping >> /dev/null 2>&1\";\n    system($com);\n    $pec = $? >> 8;\n    if ($pec)\n    {\n      print \"MySQL server from group: $groups[$i] is not running\\n\";\n      if (!$opt_no_log)\n      {\n\tw2log(\"MySQL server from group: $groups[$i] is not running\",\n\t      \"$opt_log\", 0, 0);\n      }\n    }\n    else\n    {\n      print \"MySQL server from group: $groups[$i] is running\\n\";\n      if (!$opt_no_log)\n      {\n\tw2log(\"MySQL server from group: $groups[$i] is running\",\n\t      \"$opt_log\", 0, 0);\n      }\n    }\n  }\n  if (!$i)\n  {\n    print \"No groups to be reported (check your GNRs)\\n\";\n    if (!$opt_no_log)\n    {\n      w2log(\"No groups to be reported (check your GNRs)\", \"$opt_log\", 0, 0);\n    }\n  }\n}\n\n####\n#### start multiple servers\n####\n\nsub start_mysqlds()\n{\n  my (@groups, $com, $tmp, $i, @options, $j, $mysqld_found, $info_sent);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nStarting MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nStarting MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    @options = defaults_for_group($groups[$i]);\n\n    $basedir_found= 0; # The default\n    $mysqld_found= 1; # The default\n    $mysqld_found= 0 if (!length($mysqld));\n    $com= \"$mysqld\";\n    for ($j = 0, $tmp= \"\"; defined($options[$j]); $j++)\n    {\n      if (\"--datadir=\" eq substr($options[$j], 0, 10)) {\n        $datadir = $options[$j];\n        $datadir =~ s/\\-\\-datadir\\=//;\n        eval { mkpath($datadir) };\n        if ($@) {\n          print \"FATAL ERROR: Cannot create data directory $datadir: $!\\n\";\n          exit(1);\n        }\n      }\n      elsif (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n      {\n\t# catch this and ignore\n      }\n      elsif (\"--mysqld=\" eq substr($options[$j], 0, 9))\n      {\n\t$options[$j]=~ s/\\-\\-mysqld\\=//;\n\t$com= $options[$j];\n        $mysqld_found= 1;\n      }\n      elsif (\"--basedir=\" eq substr($options[$j], 0, 10))\n      {\n        $basedir= $options[$j];\n        $basedir =~ s/^--basedir=//;\n        $basedir_found= 1;\n        $options[$j]= quote_shell_word($options[$j]);\n        $tmp.= \" $options[$j]\";\n      }\n      else\n      {\n\t$options[$j]= quote_shell_word($options[$j]);\n\t$tmp.= \" $options[$j]\";\n      }\n    }\n    if ($opt_verbose && $com =~ m/\\/(safe_mysqld|mysqld_safe)$/ && !$info_sent)\n    {\n      print \"WARNING: $1 is being used to start mysqld. In this case you \";\n      print \"may need to pass\\n\\\"ledir=...\\\" under groups [mysqldN] to \";\n      print \"$1 in order to find the actual mysqld binary.\\n\";\n      print \"ledir (library executable directory) should be the path to the \";\n      print \"wanted mysqld binary.\\n\\n\";\n      $info_sent= 1;\n    }\n    $com.= $tmp;\n    $com.= \" >> $opt_log 2>&1\" if (!$opt_no_log);\n    if (!$mysqld_found)\n    {\n      print \"\\n\";\n      print \"FATAL ERROR: Tried to start mysqld under group [$groups[$i]], \";\n      print \"but no mysqld binary was found.\\n\";\n      print \"Please add \\\"mysqld=...\\\" in group [mysqld_multi], or add it to \";\n      print \"group [$groups[$i]] separately.\\n\";\n      exit(1);\n    }\n    if ($basedir_found)\n    {\n      $curdir=getcwd();\n      chdir($basedir) or die \"Can't change to datadir $basedir\";\n    }\n    if (! -d $datadir.\"/mysql\") {\n      if (-w $datadir) {\n        print \"\\n\\nInstalling new database in $datadir\\n\\n\";\n        system($com.\" --initialize\");\n      } else {\n        print \"\\n\";\n        print \"FATAL ERROR: Tried to create mysqld under group [$groups[$i]],\\n\";\n        print \"but the data directory is not writable.\\n\";\n        print \"data directory used: $datadir\\n\";\n        exit(1);\n      }\n    }\n    if (! -d $datadir.\"/mysql\") {\n      print \"\\n\";\n      print \"FATAL ERROR: Tried to start mysqld under group [$groups[$i]],\\n\";\n      print \"but no data directory was found or could be created.\\n\";\n      print \"data directory used: $datadir\\n\";\n      exit(1);\n    }\n    system($com.\" &\");\n    if ($basedir_found)\n    {\n      chdir($curdir) or die \"Can't change back to original dir $curdir\";\n    }\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be started (check your GNRs)\",\n\t  \"$opt_log\", 0, 0);\n  }\n}\n\n####\n#### reload multiple servers\n####\n\nsub reload_mysqlds()\n{\n  my (@groups, $com, $tmp, $i, @options, $j);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nReloading MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nReloading MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $mysqld_server = $mysqld;\n    @options = defaults_for_group($groups[$i]);\n\n    for ($j = 0, $tmp= \"\"; defined($options[$j]); $j++)\n    {\n      if (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n      {\n        # catch this and ignore\n      }\n      elsif (\"--mysqld=\" eq substr($options[$j], 0, 9))\n      {\n        $options[$j] =~ s/\\-\\-mysqld\\=//;\n        $mysqld_server = $options[$j];\n      }\n      elsif (\"--pid-file=\" eq substr($options[$j], 0, 11))\n      {\n        $options[$j] =~ s/\\-\\-pid-file\\=//;\n        $pid_file = $options[$j];\n      }\n    }\n    $com = \"killproc -p $pid_file -HUP $mysqld_server\";\n    system($com);\n\n    $com = \"touch $pid_file\";\n    system($com);\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be reloaded (check your GNRs)\",\n         \"$opt_log\", 0, 0);\n  }\n}\n\n###\n#### stop multiple servers\n####\n\nsub stop_mysqlds()\n{\n  my (@groups, $com, $i, @options);\n\n  if (!$opt_no_log)\n  {\n    w2log(\"\\nStopping MySQL servers\\n\",\"$opt_log\",0,0);\n  }\n  else\n  {\n    print \"\\nStopping MySQL servers\\n\";\n  }\n  @groups = &find_groups($groupids);\n  for ($i = 0; defined($groups[$i]); $i++)\n  {\n    $com= get_mysqladmin_options($i, @groups);\n    $com.= \" shutdown\";\n    $com.= \" >> $opt_log 2>&1\" if (!$opt_no_log);\n    $com.= \" &\";\n    system($com);\n  }\n  if (!$i && !$opt_no_log)\n  {\n    w2log(\"No MySQL servers to be stopped (check your GNRs)\",\n\t  \"$opt_log\", 0, 0);\n  }\n}\n\n####\n#### Sub function for mysqladmin option parsing\n####\n\nsub get_mysqladmin_options\n{\n  my ($i, @groups)= @_;\n  my ($mysqladmin_found, $com, $tmp, $j);\n\n  @options = defaults_for_group($groups[$i]);\n\n  $mysqladmin_found= 1; # The default\n  $mysqladmin_found= 0 if (!length($mysqladmin));\n  $com = \"$mysqladmin\";\n  $tmp = \" -u $opt_user\";\n  if (defined($opt_password)) {\n    my $pw= $opt_password;\n    # Protect single quotes in password\n    $pw =~ s/'/'\"'\"'/g;\n    $tmp.= \" -p'$pw'\";\n  }\n  $tmp.= $opt_tcp_ip ? \" -h 127.0.0.1\" : \"\";\n  for ($j = 0; defined($options[$j]); $j++)\n  {\n    if (\"--mysqladmin=\" eq substr($options[$j], 0, 13))\n    {\n      $options[$j]=~ s/\\-\\-mysqladmin\\=//;\n      $com= $options[$j];\n      $mysqladmin_found= 1;\n    }\n    elsif ((($options[$j] =~ m/^(\\-\\-socket\\=)(.*)$/) && !$opt_tcp_ip) ||\n\t   ($options[$j] =~ m/^(\\-\\-port\\=)(.*)$/))\n    {\n      $tmp.= \" $options[$j]\";\n    }\n  }\n  if (!$mysqladmin_found)\n  {\n    print \"\\n\";\n    print \"FATAL ERROR: Tried to use mysqladmin in group [$groups[$i]], \";\n    print \"but no mysqladmin binary was found.\\n\";\n    print \"Please add \\\"mysqladmin=...\\\" in group [mysqld_multi], or \";\n    print \"in group [$groups[$i]].\\n\";\n    exit(1);\n  }\n  $com.= $tmp;\n  return $com;\n}\n\n# Return a list of option files which can be opened.  Similar, but not\n# identical, to behavior of my_search_option_files()\nsub list_defaults_files\n{\n  my %opt;\n  foreach (@defaults_options)\n  {\n    return () if /^--no-defaults$/;\n    $opt{$1} = $2 if /^--defaults-(extra-file|file)=(.*)$/;\n  }\n\n  return ($opt{file}) if exists $opt{file};\n\n  my %seen;  # Don't list the same file more than once\n  return grep { defined $_ and not $seen{$_}++ and -f $_ and -r $_ }\n              ('/etc/my.cnf',\n               '/etc/mysql/my.cnf',\n               '@sysconfdir@/my.cnf',\n               ($ENV{MYSQL_HOME} ? \"$ENV{MYSQL_HOME}/my.cnf\" : undef),\n               $opt{'extra-file'},\n               ($ENV{HOME} ? \"$ENV{HOME}/.my.cnf\" : undef));\n}\n\n\n# Takes a specification of GNRs (see --help), and returns a list of matching\n# groups which actually are mentioned in a relevant config file\nsub find_groups\n{\n  my ($raw_gids) = @_;\n\n  my %gids;\n  my @groups;\n\n  if (defined($raw_gids))\n  {\n    # Make a hash of the wanted group ids\n    foreach my $raw_gid (split ',', $raw_gids)\n    {\n      # Match 123 or 123-456\n      my ($start, $end) = ($raw_gid =~ /^\\s*(\\d+)(?:\\s*-\\s*(\\d+))?\\s*$/);\n      $end = $start if not defined $end;\n      if (not defined $start or $end < $start or $start < 0)\n      {\n        print \"ABORT: Bad GNR: $raw_gid; see $my_progname --help\\n\";\n        exit(1);\n      }\n\n      foreach my $i ($start .. $end)\n      {\n        # Use $i + 0 to normalize numbers (002 + 0 -> 2)\n        $gids{$i + 0}= 1;\n      }\n    }\n  }\n\n  my @defaults_files = list_defaults_files();\n  #warn \"@{[sort keys %gids]} -> @defaults_files\\n\";\n  foreach my $file (@defaults_files)\n  {\n    next unless open CONF, \"< $file\";\n\n    while (<CONF>)\n    {\n      if (/^\\s*\\[\\s*(mysqld)(\\d+)\\s*\\]\\s*$/)\n      {\n        #warn \"Found a group: $1$2\\n\";\n        # Use $2 + 0 to normalize numbers (002 + 0 -> 2)\n        if (not defined($raw_gids) or $gids{$2 + 0})\n        {\n          push @groups, \"$1$2\";\n        }\n      }\n    }\n\n    close CONF;\n  }\n  return @groups;\n}\n\n####\n#### w2log: Write to a logfile.\n#### 1.arg: append to the log file (given string, or from a file. if a file,\n####        file will be read from $opt_logdir)\n#### 2.arg: logfile -name (w2log assumes that the logfile is in $opt_logdir).\n#### 3.arg. 0 | 1, if true, print current date to the logfile. 3. arg will\n####        be ignored, if 1. arg is a file.\n#### 4.arg. 0 | 1, if true, first argument is a file, else a string\n####\n\nsub w2log\n{\n  my ($msg, $file, $date_flag, $is_file)= @_;\n  my (@data);\n\n  open (LOGFILE, \">>$opt_log\")\n    or die \"FATAL: w2log: Couldn't open log file: $opt_log\\n\";\n\n  if ($is_file)\n  {\n    open (FROMFILE, \"<$msg\") && (@data=<FROMFILE>) &&\n      close(FROMFILE)\n\tor die \"FATAL: w2log: Couldn't open file: $msg\\n\";\n    foreach my $line (@data)\n    {\n      print LOGFILE \"$line\";\n    }\n  }\n  else\n  {\n    print LOGFILE \"$msg\";\n    print LOGFILE strftime \"%a %b %e %H:%M:%S %Y\", localtime if ($date_flag);\n    print LOGFILE \"\\n\";\n  }\n  close (LOGFILE);\n  return;\n}\n\n####\n#### my_which is used, because we can't assume that every system has the\n#### which -command. my_which can take only one argument at a time.\n#### Return values: requested system command with the first found path,\n#### or undefined, if not found.\n####\n\nsub my_which\n{\n  my ($command) = @_;\n  my (@paths, $path);\n\n # If the argument is not 'my_print_defaults' then it would be of the format\n # <absolute_path>/<program>\n return $command if ($command ne 'my_print_defaults' && -f $command &&\n                     -x $command);\n\n  @paths = split(':', $ENV{'PATH'});\n  foreach $path (@paths)\n  {\n    $path .= \"/$command\";\n    return $path if (-f $path && -x $path);\n  }\n  return undef();\n}\n\n\n####\n#### example\n####\n\nsub example\n{\n  print <<EOF;\n# This is an example of a my.cnf file for $my_progname.\n# Usually this file is located in home dir ~/.my.cnf or /etc/my.cnf\n#\n# SOME IMPORTANT NOTES FOLLOW:\n#\n# 1.COMMON USER\n#\n#   Make sure that the MySQL user, who is stopping the mysqld services, has\n#   the same password to all MySQL servers being accessed by $my_progname.\n#   This user needs to have the 'Shutdown_priv' -privilege, but for security\n#   reasons should have no other privileges. It is advised that you create a\n#   common 'multi_admin' user for all MySQL servers being controlled by\n#   $my_progname. Here is an example how to do it:\n#\n#   GRANT SHUTDOWN ON *.* TO multi_admin\\@localhost IDENTIFIED BY 'password'\n#\n#   You will need to apply the above to all MySQL servers that are being\n#   controlled by $my_progname. 'multi_admin' will shutdown the servers\n#   using 'mysqladmin' -binary, when '$my_progname stop' is being called.\n#\n# 2.PID-FILE\n#\n#   If you are using mysqld_safe to start mysqld, make sure that every\n#   MySQL server has a separate pid-file. In order to use mysqld_safe\n#   via $my_progname, you need to use two options:\n#\n#   mysqld=/path/to/mysqld_safe\n#   ledir=/path/to/mysqld-binary/\n#\n#   ledir (library executable directory), is an option that only mysqld_safe\n#   accepts, so you will get an error if you try to pass it to mysqld directly.\n#   For this reason you might want to use the above options within [mysqld#]\n#   group directly.\n#\n# 3.DATA DIRECTORY\n#\n#   It is NOT advised to run many MySQL servers within the same data directory.\n#   You can do so, but please make sure to understand and deal with the\n#   underlying caveats. In short they are:\n#   - Speed penalty\n#   - Risk of table/data corruption\n#   - Data synchronising problems between the running servers\n#   - Heavily media (disk) bound\n#   - Relies on the system (external) file locking\n#   - Is not applicable with all table types. (Such as InnoDB)\n#     Trying so will end up with undesirable results.\n#\n# 4.TCP/IP Port\n#\n#   Every server requires one and it must be unique.\n#\n# 5.[mysqld#] Groups\n#\n#   In the example below the first and the fifth mysqld group was\n#   intentionally left out. You may have 'gaps' in the config file. This\n#   gives you more flexibility.\n#\n# 6.MySQL Server User\n#\n#   You can pass the user=... option inside [mysqld#] groups. This\n#   can be very handy in some cases, but then you need to run $my_progname\n#   as UNIX root.\n#\n# 7.A Start-up Manage Script for $my_progname\n#\n#   In the recent MySQL distributions you can find a file called\n#   mysqld_multi.server.sh. It is a wrapper for $my_progname. This can\n#   be used to start and stop multiple servers during boot and shutdown.\n#\n#   You can place the file in /etc/init.d/mysqld_multi.server.sh and\n#   make the needed symbolic links to it from various run levels\n#   (as per Linux/Unix standard). You may even replace the\n#   /etc/init.d/mysql.server script with it.\n#\n#   Before using, you must create a my.cnf file either in @sysconfdir@/my.cnf\n#   or /root/.my.cnf and add the [mysqld_multi] and [mysqld#] groups.\n#\n#   The script can be found from support-files/mysqld_multi.server.sh\n#   in MySQL distribution. (Verify the script before using)\n#\n\n[mysqld_multi]\nmysqld     = @bindir@/mysqld_safe\nmysqladmin = @bindir@/mysqladmin\nuser       = multi_admin\npassword   = my_password\n\n[mysqld2]\nsocket     = /tmp/mysql.sock2\nport       = 3307\npid-file   = @localstatedir@2/hostname.pid2\ndatadir    = @localstatedir@2\nlanguage   = @datadir@/mysql/english\nuser       = unix_user1\n\n[mysqld3]\nmysqld     = /path/to/mysqld_safe\nledir      = /path/to/mysqld-binary/\nmysqladmin = /path/to/mysqladmin\nsocket     = /tmp/mysql.sock3\nport       = 3308\npid-file   = @localstatedir@3/hostname.pid3\ndatadir    = @localstatedir@3\nlanguage   = @datadir@/mysql/swedish\nuser       = unix_user2\n\n[mysqld4]\nsocket     = /tmp/mysql.sock4\nport       = 3309\npid-file   = @localstatedir@4/hostname.pid4\ndatadir    = @localstatedir@4\nlanguage   = @datadir@/mysql/estonia\nuser       = unix_user3\n \n[mysqld6]\nsocket     = /tmp/mysql.sock6\nport       = 3311\npid-file   = @localstatedir@6/hostname.pid6\ndatadir    = @localstatedir@6\nlanguage   = @datadir@/mysql/japanese\nuser       = unix_user4\nEOF\n  exit(0);\n}\n\n####\n#### usage\n####\n\nsub usage\n{\n  print <<EOF;\n$my_progname version $VER by Jani Tolonen\n\nDescription:\n$my_progname can be used to start, reload, or stop any number of separate\nmysqld processes running in different TCP/IP ports and UNIX sockets.\n\n$my_progname can read group [mysqld_multi] from my.cnf file. You may\nwant to put options mysqld=... and mysqladmin=... there.  Since\nversion 2.10 these options can also be given under groups [mysqld#],\nwhich gives more control over different versions.  One can have the\ndefault mysqld and mysqladmin under group [mysqld_multi], but this is\nnot mandatory. Please note that if mysqld or mysqladmin is missing\nfrom both [mysqld_multi] and [mysqld#], a group that is tried to be\nused, $my_progname will abort with an error.\n\n$my_progname will search for groups named [mysqld#] from my.cnf (or\nthe given --defaults-extra-file=...), where '#' can be any positive \ninteger starting from 1. These groups should be the same as the regular\n[mysqld] group, but with those port, socket and any other options\nthat are to be used with each separate mysqld process. The number\nin the group name has another function; it can be used for starting,\nreloading, stopping, or reporting any specific mysqld server.\n\nUsage: $my_progname [OPTIONS] {start|reload|stop|report} [GNR,GNR,GNR...]\nor     $my_progname [OPTIONS] {start|reload|stop|report} [GNR-GNR,GNR,GNR-GNR,...]\n\nThe GNR means the group number. You can start, reload, stop or report any GNR,\nor several of them at the same time. (See --example) The GNRs list can\nbe comma separated or a dash combined. The latter means that all the\nGNRs between GNR1-GNR2 will be affected. Without GNR argument all the\ngroups found will either be started, reloaded, stopped, or reported. Note that\nsyntax for specifying GNRs must appear without spaces.\n\nOptions:\n\nThese options must be given before any others:\n--no-defaults      Do not read any defaults file\n--defaults-file=...  Read only this configuration file, do not read the\n                   standard system-wide and user-specific files\n--defaults-extra-file=...  Read this configuration file in addition to the\n                   standard system-wide and user-specific files\nUsing:  @{[join ' ', @defaults_options]}\n\n--example          Give an example of a config file with extra information.\n--help             Print this help and exit.\n--log=...          Log file. Full path to and the name for the log file. NOTE:\n                   If the file exists, everything will be appended.\n                   Using: $opt_log\n--mysqladmin=...   mysqladmin binary to be used for a server shutdown.\n                   Since version 2.10 this can be given within groups [mysqld#]\n                   Using: $mysqladmin\n--mysqld=...       mysqld binary to be used. Note that you can give mysqld_safe\n                   to this option also. The options are passed to mysqld. Just\n                   make sure you have mysqld in your PATH or fix mysqld_safe.\n                   Using: $mysqld\n                   Please note: Since mysqld_multi version 2.3 you can also\n                   give this option inside groups [mysqld#] in ~/.my.cnf,\n                   where '#' stands for an integer (number) of the group in\n                   question. This will be recognised as a special option and\n                   will not be passed to the mysqld. This will allow one to\n                   start different mysqld versions with mysqld_multi.\n--no-log           Print to stdout instead of the log file. By default the log\n                   file is turned on.\n--password=...     Password for mysqladmin user.\n--silent           Disable warnings.\n--tcp-ip           Connect to the MySQL server(s) via the TCP/IP port instead\n                   of the UNIX socket. This affects stopping and reporting.\n                   If a socket file is missing, the server may still be\n                   running, but can be accessed only via the TCP/IP port.\n                   By default connecting is done via the UNIX socket.\n--user=...         mysqladmin user. Using: $opt_user\n--verbose          Be more verbose.\n--version          Print the version number and exit.\nEOF\n  exit(0);\n}\n", "num_lines": 914}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!@SHELL_PATH@\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n#\n# Script to start the MySQL daemon and restart it if it dies unexpectedly\n#\n# This should be executed in the MySQL base directory if you are using a\n# binary installation that is not installed in its compile-time default\n# location\n#\n# mysql.server works by first doing a cd to the base directory and from there\n# executing mysqld_safe\n\n# Initialize script globals\nKILL_MYSQLD=1;\nMYSQLD=\nniceness=0\nmysqld_ld_preload=\nmysqld_ld_library_path=\n\n# Initial logging status: error log is not open, and not using syslog\nlogging=init\nwant_syslog=0\nsyslog_tag=\nuser='@MYSQLD_USER@'\npid_file=\npid_file_append=\nerr_log=\nerr_log_append=\ntimestamp_format=UTC\n\nsyslog_tag_mysqld=mysqld\nsyslog_tag_mysqld_safe=mysqld_safe\nsyslog_facility=daemon\n\ntrap '' 1 2 3 15\t\t\t# we shouldn't let anyone kill us\ntrap '' 13                              # not even SIGPIPE\n\n# MySQL-specific environment variable. First off, it's not really a umask,\n# it's the desired mode. Second, it follows umask(2), not umask(3) in that\n# octal needs to be explicit. Our shell might be a proper sh without printf,\n# multiple-base arithmetic, and binary arithmetic, so this will get ugly.\n# We reject decimal values to keep things at least half-sane.\numask 007                               # fallback\nUMASK=\"${UMASK-0640}\"\nfmode=`echo \"$UMASK\" | sed -e 's/[^0246]//g'`\noctalp=`echo \"$fmode\"|cut -c1`\nfmlen=`echo \"$fmode\"|wc -c|sed -e 's/ //g'`\nif [ \"x$octalp\" != \"x0\" -o \"x$UMASK\" != \"x$fmode\" -o \"x$fmlen\" != \"x5\" ]\nthen\n  fmode=0640\n  echo \"UMASK must be a 3-digit mode with an additional leading 0 to indicate octal.\" >&2\n  echo \"The first digit will be corrected to 6, the others may be 0, 2, 4, or 6.\" >&2\nfi\nfmode=`echo \"$fmode\"|cut -c3-4`\nfmode=\"6$fmode\"\nif [ \"x$UMASK\" != \"x0$fmode\" ]\nthen\n  echo \"UMASK corrected from $UMASK to 0$fmode ...\"\nfi\n\ndefaults=\ncase \"$1\" in\n    --no-defaults|--defaults-file=*|--defaults-extra-file=*)\n      defaults=\"$1\"; shift\n      ;;\nesac\n\nusage () {\n        cat <<EOF\nUsage: $0 [OPTIONS]\n The following options may be given as the first argument:\n  --no-defaults              Don't read the system defaults file\n  --defaults-file=FILE       Use the specified defaults file\n  --defaults-extra-file=FILE Also use defaults from the specified file\n\n Other options:\n  --ledir=DIRECTORY          Look for mysqld in the specified directory\n  --open-files-limit=LIMIT   Limit the number of open files\n  --core-file-size=LIMIT     Limit core files to the specified size\n  --timezone=TZ              Set the system timezone\n  --malloc-lib=LIB           Preload shared library LIB if available\n  --mysqld=FILE              Use the specified file as mysqld\n  --mysqld-version=VERSION   Use \"mysqld-VERSION\" as mysqld\n  --nice=NICE                Set the scheduling priority of mysqld\n  --plugin-dir=DIR           Plugins are under DIR or DIR/VERSION, if\n                             VERSION is given\n  --skip-kill-mysqld         Don't try to kill stray mysqld processes\n  --syslog                   Log messages to syslog with 'logger'\n  --skip-syslog              Log messages to error log (default)\n  --syslog-tag=TAG           Pass -t \"mysqld-TAG\" to 'logger'\n  --mysqld-safe-log-         TYPE must be one of UTC (ISO 8601 UTC),\n    timestamps=TYPE          system (ISO 8601 local time), hyphen\n                             (hyphenated date a la mysqld 5.6), legacy\n                             (legacy non-ISO 8601 mysqld_safe timestamps)\n\nAll other options are passed to the mysqld program.\n\nEOF\n        exit 1\n}\n\nmy_which ()\n{\n  save_ifs=\"${IFS-UNSET}\"\n  IFS=:\n  ret=0\n  for file\n  do\n    for dir in $PATH\n    do\n      if [ -f \"$dir/$file\" ]\n      then\n        echo \"$dir/$file\"\n        continue 2\n      fi\n    done\n\n\tret=1  #signal an error\n\tbreak\n  done\n\n  if [ \"$save_ifs\" = UNSET ]\n  then\n    unset IFS\n  else\n    IFS=\"$save_ifs\"\n  fi\n  return $ret  # Success\n}\n\nlog_generic () {\n  priority=\"$1\"\n  shift\n\n  msg=\"`eval $DATE` mysqld_safe $*\"\n  echo \"$msg\"\n  case $logging in\n    init) ;;  # Just echo the message, don't save it anywhere\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        true\n      else\n        echo \"$msg\" >> \"$err_log\"\n      fi\n      ;;\n    syslog) logger -t \"$syslog_tag_mysqld_safe\" -p \"$priority\" \"$*\" ;;\n    both)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        true\n      else\n        echo \"$msg\" >> \"$err_log\"\n      fi\n      logger -t \"$syslog_tag_mysqld_safe\" -p \"$priority\" \"$*\"\n      ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n}\n\nlog_error () {\n  log_generic ${syslog_facility}.error \"$@\" >&2\n}\n\nlog_notice () {\n  log_generic ${syslog_facility}.notice \"$@\"\n}\n\neval_log_error () {\n  cmd=\"$1\"\n  case $logging in\n    file)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        cmd=\"$cmd > /dev/null 2>&1\"\n      else\n        cmd=\"$cmd >> \"`shell_quote_string \"$err_log\"`\" 2>&1\"\n      fi\n      ;;\n    syslog)\n      cmd=\"$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' > /dev/null 2>&1\"\n      ;;\n    both)\n      if [ -w / -o \"$USER\" = \"root\" ]; then\n        cmd=\"$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' > /dev/null 2>&1\"\n      else\n        cmd=\"$cmd --log-syslog=1 --log-syslog-facility=$syslog_facility '--log-syslog-tag=$syslog_tag' >> \"`shell_quote_string \"$err_log\"`\" 2>&1\"\n      fi\n      ;;\n    *)\n      echo \"Internal program error (non-fatal):\" \\\n           \" unknown logging method '$logging'\" >&2\n      ;;\n  esac\n\n  #echo \"Running mysqld: [$cmd]\"\n  eval \"$cmd\"\n}\n\nshell_quote_string() {\n  # This sed command makes sure that any special chars are quoted,\n  # so the arg gets passed exactly to the server.\n  echo \"$1\" | sed -e 's,\\([^a-zA-Z0-9/_.=-]\\),\\\\\\1,g'\n}\n\nparse_arguments() {\n  # We only need to pass arguments through to the server if we don't\n  # handle them here.  So, we collect unrecognized options (passed on\n  # the command line) into the args variable.\n  pick_args=\n  if test \"$1\" = PICK-ARGS-FROM-ARGV\n  then\n    pick_args=1\n    shift\n  fi\n\n  for arg do\n    # the parameter after \"=\", or the whole $arg if no match\n    val=`echo \"$arg\" | sed -e 's;^--[^=]*=;;'`\n    # what's before \"=\", or the whole $arg if no match\n    optname=`echo \"$arg\" | sed -e 's/^\\(--[^=]*\\)=.*$/\\1/'`\n    # replace \"_\" by \"-\" ; mysqld_safe must accept \"_\" like mysqld does.\n    optname_subst=`echo \"$optname\" | sed 's/_/-/g'`\n    arg=`echo $arg | sed \"s/^$optname/$optname_subst/\"`\n    case \"$arg\" in\n      # these get passed explicitly to mysqld\n      --basedir=*) MY_BASEDIR_VERSION=\"$val\" ;;\n      --datadir=*)\n        case $val in\n          /) DATADIR=$val ;;\n          *) DATADIR=\"`echo $val | sed 's;/*$;;'`\" ;;\n        esac\n        ;;\n      --pid-file=*) pid_file=\"$val\" ;;\n      --plugin-dir=*) PLUGIN_DIR=\"$val\" ;;\n      --user=*) user=\"$val\"; SET_USER=1 ;;\n\n      # these might have been set in a [mysqld_safe] section of my.cnf\n      # they are added to mysqld command line to override settings from my.cnf\n      --log-error=*) err_log=\"$val\" ;;\n      --port=*) mysql_tcp_port=\"$val\" ;;\n      --socket=*) mysql_unix_port=\"$val\" ;;\n\n      # mysqld_safe-specific options - must be set in my.cnf ([mysqld_safe])!\n      --core-file-size=*) core_file_size=\"$val\" ;;\n      --ledir=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--ledir option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        ledir=\"$val\"\n        ;;\n      --malloc-lib=*) set_malloc_lib \"$val\" ;;\n      --mysqld=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        MYSQLD=\"$val\" ;;\n      --mysqld-version=*)\n        if [ -z \"$pick_args\" ]; then\n          log_error \"--mysqld-version option can only be used as command line option, found in config file\"\n          exit 1\n        fi\n        if test -n \"$val\"\n        then\n          MYSQLD=\"mysqld-$val\"\n          PLUGIN_VARIANT=\"/$val\"\n        else\n          MYSQLD=\"mysqld\"\n        fi\n        ;;\n      --nice=*) niceness=\"$val\" ;;\n      --open-files-limit=*) open_files=\"$val\" ;;\n      --open_files_limit=*) open_files=\"$val\" ;;\n      --skip-kill-mysqld*) KILL_MYSQLD=0 ;;\n      --mysqld-safe-log-timestamps=*) timestamp_format=\"$val\" ;;\n      --syslog) want_syslog=1 ;;\n      --skip-syslog) want_syslog=0 ;;\n      --syslog-tag=*) syslog_tag=\"$val\" ;;\n      --timezone=*) TZ=\"$val\"; export TZ; ;;\n\n      --help) usage ;;\n\n      *)\n        if test -n \"$pick_args\"\n        then\n          append_arg_to_args \"$arg\"\n        fi\n        ;;\n    esac\n  done\n}\n\n\n# Add a single shared library to the list of libraries which will be added to\n# LD_PRELOAD for mysqld\n#\n# Since LD_PRELOAD is a space-separated value (for historical reasons), if a\n# shared lib's path contains spaces, that path will be prepended to\n# LD_LIBRARY_PATH and stripped from the lib value.\nadd_mysqld_ld_preload() {\n  lib_to_add=\"$1\"\n  log_notice \"Adding '$lib_to_add' to LD_PRELOAD for mysqld\"\n\n  case \"$lib_to_add\" in\n    *' '*)\n      # Must strip path from lib, and add it to LD_LIBRARY_PATH\n      lib_file=`basename \"$lib_to_add\"`\n      case \"$lib_file\" in\n        *' '*)\n          # The lib file itself has a space in its name, and can't\n          # be used in LD_PRELOAD\n          log_error \"library name '$lib_to_add' contains spaces and can not be used with LD_PRELOAD\"\n          exit 1\n          ;;\n      esac\n      lib_path=`dirname \"$lib_to_add\"`\n      lib_to_add=\"$lib_file\"\n      [ -n \"$mysqld_ld_library_path\" ] && mysqld_ld_library_path=\"$mysqld_ld_library_path:\"\n      mysqld_ld_library_path=\"$mysqld_ld_library_path$lib_path\"\n      ;;\n  esac\n\n  # LD_PRELOAD is a space-separated\n  [ -n \"$mysqld_ld_preload\" ] && mysqld_ld_preload=\"$mysqld_ld_preload \"\n  mysqld_ld_preload=\"${mysqld_ld_preload}$lib_to_add\"\n}\n\n\n# Returns LD_PRELOAD (and LD_LIBRARY_PATH, if needed) text, quoted to be\n# suitable for use in the eval that calls mysqld.\n#\n# All values in mysqld_ld_preload are prepended to LD_PRELOAD.\nmysqld_ld_preload_text() {\n  text=\n\n  if [ -n \"$mysqld_ld_preload\" ]; then\n    new_text=\"$mysqld_ld_preload\"\n    [ -n \"$LD_PRELOAD\" ] && new_text=\"$new_text $LD_PRELOAD\"\n    text=\"${text}LD_PRELOAD=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  if [ -n \"$mysqld_ld_library_path\" ]; then\n    new_text=\"$mysqld_ld_library_path\"\n    [ -n \"$LD_LIBRARY_PATH\" ] && new_text=\"$new_text:$LD_LIBRARY_PATH\"\n    text=\"${text}LD_LIBRARY_PATH=\"`shell_quote_string \"$new_text\"`' '\n  fi\n\n  echo \"$text\"\n}\n\n# set_malloc_lib LIB\n# - If LIB is empty, do nothing and return\n# - If LIB is 'tcmalloc', look for tcmalloc shared library in $malloc_dirs.\n#   tcmalloc is part of the Google perftools project.\n# - If LIB is an absolute path, assume it is a malloc shared library\n#\n# Put LIB in mysqld_ld_preload, which will be added to LD_PRELOAD when\n# running mysqld.  See ld.so for details.\nset_malloc_lib() {\n  # This list is kept intentionally simple.\n  malloc_dirs=\"/usr/lib /usr/lib64 /usr/lib/i386-linux-gnu /usr/lib/x86_64-linux-gnu\"\n  malloc_lib=\"$1\"\n\n  if [ \"$malloc_lib\" = tcmalloc ]; then\n    malloc_lib=\n    for libdir in `echo $malloc_dirs`; do\n      for flavor in _minimal '' _and_profiler _debug; do\n        tmp=\"$libdir/libtcmalloc$flavor.so\"\n        #log_notice \"DEBUG: Checking for malloc lib '$tmp'\"\n        [ -r \"$tmp\" ] || continue\n        malloc_lib=\"$tmp\"\n        break 2\n      done\n    done\n\n    if [ -z \"$malloc_lib\" ]; then\n      log_error \"no shared library for --malloc-lib=tcmalloc found in $malloc_dirs\"\n      exit 1\n    fi\n  fi\n\n  # Allow --malloc-lib='' to override other settings\n  [ -z  \"$malloc_lib\" ] && return\n\n  case \"$malloc_lib\" in\n    /*)\n      if [ ! -r \"$malloc_lib\" ]; then\n        log_error \"--malloc-lib can not be read and will not be used\"\n        exit 1\n      fi\n\n      # Restrict to a the list in $malloc_dirs above\n      case \"`dirname \"$malloc_lib\"`\" in\n        /usr/lib) ;;\n        /usr/lib64) ;;\n        /usr/lib/i386-linux-gnu) ;;\n        /usr/lib/x86_64-linux-gnu) ;;\n        *)\n          log_error \"--malloc-lib must be located in one of the directories: $malloc_dirs\"\n          exit 1\n          ;;\n      esac\n      ;;\n    *)\n      log_error \"--malloc-lib must be an absolute path or 'tcmalloc'; \" \\\n        \"ignoring value '$malloc_lib'\"\n      exit 1\n      ;;\n  esac\n\n  add_mysqld_ld_preload \"$malloc_lib\"\n}\n\nfind_basedir_from_cmdline () {\n  for arg in \"$@\"; do\n    case $arg in\n      --basedir=*)\n        MY_BASEDIR_VERSION=\"`echo \"$arg\" | sed -e 's;^--[^=]*=;;'`\"\n        # Convert to full path\n        cd \"$MY_BASEDIR_VERSION\"\n        if [ $? -ne 0 ] ; then\n          log_error \"--basedir set to '$MY_BASEDIR_VERSION', however could not access directory\"\n          exit 1\n        fi\n        MY_BASEDIR_VERSION=\"`pwd`\"\n        ;;\n    esac\n  done\n}\n\n#\n# First, try to find BASEDIR and ledir (where mysqld is)\n#\n\noldpwd=\"`pwd`\"\n\n# Args not parsed yet, check if --basedir was given on command line\nfind_basedir_from_cmdline \"$@\"\n\n# --basedir is already overridden on command line\nif test -n \"$MY_BASEDIR_VERSION\" -a -d \"$MY_BASEDIR_VERSION\" ; then\n  # Search for mysqld and set ledir\n  for dir in @INSTALL_SBINDIR@ libexec sbin bin ; do\n    if test -x \"$MY_BASEDIR_VERSION/$dir/mysqld\" ; then\n      ledir=\"$MY_BASEDIR_VERSION/$dir\"\n      break\n    fi\n  done\n\nelse\n  # Basedir should be parent dir of bindir, unless some non-standard\n  # layout is used\n\n  cd \"`dirname $0`\"\n  if [ -h \"$0\" ] ; then\n    realpath=\"`ls -l  \"$0\" | awk '{print $NF}'`\"\n    cd \"`dirname \"$realpath\"`\"\n  fi\n  cd ..\n  MY_PWD=\"`pwd`\"\n\n  # Search for mysqld and set ledir and BASEDIR\n  for dir in @INSTALL_SBINDIR@ libexec sbin bin ; do\n    if test -x \"$MY_PWD/$dir/mysqld\" ; then\n      MY_BASEDIR_VERSION=\"$MY_PWD\"\n      ledir=\"$MY_BASEDIR_VERSION/$dir\"\n      break\n    fi\n  done\n\n  # If we still didn't find anything, use the compiled-in defaults\n  if test -z \"$MY_BASEDIR_VERSION\" ; then\n    MY_BASEDIR_VERSION='@prefix@'\n    ledir='@libexecdir@'\n  fi\nfi\n\n#\n# Second, try to find the data directory\n#\n\n# Try where the binary installs put it\nif test -d $MY_BASEDIR_VERSION/data/mysql\nthen\n  DATADIR=$MY_BASEDIR_VERSION/data\n# Or just give up and use our compiled-in default\nelse\n  DATADIR=@localstatedir@\nfi\n\nif test -z \"$MYSQL_HOME\"\nthen \n  MYSQL_HOME=$MY_BASEDIR_VERSION\nfi\nexport MYSQL_HOME\n\n\n# Get first arguments from the my.cnf file, groups [mysqld] and [mysqld_safe]\n# and then merge with the command line arguments\nif test -x \"$MY_BASEDIR_VERSION/bin/my_print_defaults\" ; then\n  print_defaults=\"$MY_BASEDIR_VERSION/bin/my_print_defaults\"\nelif test -x \"@bindir@/my_print_defaults\" ; then\n  print_defaults=\"@bindir@/my_print_defaults\"\nelse\n  print_defaults=\"my_print_defaults\"\nfi\n\nappend_arg_to_args () {\n  args=\"$args \"`shell_quote_string \"$1\"`\n}\n\nargs=\n\ncd \"$oldpwd\"\n\nSET_USER=2\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld server`\nif test $SET_USER -eq 2\nthen\n  SET_USER=0\nfi\n\nparse_arguments `$print_defaults $defaults --loose-verbose mysqld_safe safe_mysqld`\nparse_arguments PICK-ARGS-FROM-ARGV \"$@\"\n\n#\n# Sort out date command from $timestamp_format early so we'll start off\n# with correct log messages.\n#\ncase \"$timestamp_format\" in\n    UTC|utc)       DATE=\"date -u +%Y-%m-%dT%H:%M:%S.%06NZ\";;\n    SYSTEM|system) DATE=\"date +%Y-%m-%dT%H:%M:%S.%06N%:z\";;\n    HYPHEN|hyphen) DATE=\"date +'%Y-%m-%d %H:%M:%S'\";;\n    LEGACY|legacy) DATE=\"date +'%y%m%d %H:%M:%S'\";;\n    *)             DATE=\"date -u +%Y-%m-%dT%H:%M:%S.%06NZ\";\n                   log_error \"unknown data format $timestamp_format, using UTC\";;\nesac\n\n#\n# Try to find the plugin directory\n#\n\n# Use user-supplied argument\nif [ -n \"${PLUGIN_DIR}\" ]; then\n  plugin_dir=\"${PLUGIN_DIR}\"\nelse\n  # Try to find plugin dir relative to basedir\n  for dir in lib64/mysql/plugin lib64/plugin lib/mysql/plugin lib/plugin\n  do\n    if [ -d \"${MY_BASEDIR_VERSION}/${dir}\" ]; then\n      plugin_dir=\"${MY_BASEDIR_VERSION}/${dir}\"\n      break\n    fi\n  done\n  # Give up and use compiled-in default\n  if [ -z \"${plugin_dir}\" ]; then\n    plugin_dir='@pkgplugindir@'\n  fi\nfi\nplugin_dir=\"${plugin_dir}${PLUGIN_VARIANT}\"\n\n# Determine what logging facility to use\n\n# Ensure that 'logger' exists, if it's requested\nif [ $want_syslog -eq 1 ]\nthen\n  my_which logger > /dev/null 2>&1\n  if [ $? -ne 0 ]\n  then\n    log_error \"--syslog requested, but no 'logger' program found.  Please ensure that 'logger' is in your PATH, or do not specify the --syslog option to mysqld_safe.\"\n    exit 1\n  fi\nfi\n\nif [ $want_syslog -eq 1 ]\nthen\n  if [ -n \"$syslog_tag\" ]\n  then\n    # Sanitize the syslog tag\n    syslog_tag=`echo \"$syslog_tag\" | sed -e 's/[^a-zA-Z0-9_-]/_/g'`\n    syslog_tag_mysqld_safe=\"${syslog_tag_mysqld_safe}-$syslog_tag\"\n    syslog_tag_mysqld=\"${syslog_tag_mysqld}-$syslog_tag\"\n  fi\n  log_notice \"Logging to syslog.\"\n  logging=syslog\nfi\n\nif [ -n \"$err_log\" -o $want_syslog -eq 0 ]\nthen\n  if [ -n \"$err_log\" ]\n  then\n    # mysqld adds \".err\" if there is no extension on the --log-error\n    # argument; must match that here, or mysqld_safe will write to a\n    # different log file than mysqld\n\n    # mysqld does not add \".err\" to \"--log-error=foo.\"; it considers a\n    # trailing \".\" as an extension\n    \n    if expr \"$err_log\" : '.*\\.[^/]*$' > /dev/null\n    then\n        :\n    else\n      err_log=\"$err_log\".err\n    fi\n\n    err_log_append=\"$err_log\"\n    case \"$err_log\" in\n      /* ) ;;\n      ./*|../*)\n          # Preparing absolute path from the relative path value specified for the\n          # --log-error argument.\n          #\n          # Absolute path will be prepared for the value of following form\n          #    ./bar/foo OR\n          #   ../old_bar/foo\n          # for --log-error argument.\n          #\n          # Note: If directory of log file name does not exists or\n          #       if write or execute permissions are missing on directory then\n          #       --log-error is set  $DATADIR/`@HOSTNAME@`.err\n\n          log_dir_name=\"$(dirname \"$err_log\")\";\n          if [ ! -d \"$log_dir_name\" ]\n          then\n            log_notice \"Directory \"$log_dir_name\" does not exists.\";\n            err_log=$DATADIR/`@HOSTNAME@`.err\n          elif [ ! -x \"$log_dir_name\" -o ! -w \"$log_dir_name\" ]\n          then\n            log_notice \"Do not have Execute or Write permissions on directory \"$log_dir_name\".\";\n            err_log=$DATADIR/`@HOSTNAME@`.err\n          else\n            err_log=$(cd $log_dir_name && pwd -P)/$(basename \"$err_log\")\n          fi\n          ;;\n      * ) err_log=\"$DATADIR/$err_log\" ;;\n    esac\n  else\n    err_log=$DATADIR/`@HOSTNAME@`.err\n    err_log_append=`@HOSTNAME@`.err\n  fi\n\n  append_arg_to_args \"--log-error=$err_log_append\"\n\n  if [ $want_syslog -eq 1 ]\n  then\n    logging=both\n  else\n    logging=file\n  fi\nfi\n\nlogdir=`dirname \"$err_log\"`\n# Change the err log to the right user, if possible and it is in use\nif [ $logging = \"file\" -o $logging = \"both\" ]; then\n  if [ ! -e \"$err_log\" -a ! -h \"$err_log\" ]; then\n    if test -w / -o \"$USER\" = \"root\"; then\n      case $logdir in\n        /var/log)\n          (\n            umask 0137\n            set -o noclobber\n            > \"$err_log\" && chown $user \"$err_log\"\n          ) ;;\n        *) ;;\n      esac\n    else\n      (\n        umask 0137\n        set -o noclobber\n        > \"$err_log\"\n      )\n    fi\n  fi\n\n  if [ -f \"$err_log\" -o -p \"$err_log\" ]; then        # Log to err_log file\n    log_notice \"Logging to '$err_log'.\"\n  elif [ \"x$user\" = \"xroot\" ]; then # running as root, mysqld can create log file; continue\n    echo \"Logging to '$err_log'.\" >&2\n  else\n    case $logdir in\n      # We can't create $err_log, however mysqld can; continue\n      /tmp|/var/tmp|/var/log/mysql|$DATADIR)\n        echo \"Logging to '$err_log'.\" >&2\n        ;;\n      # We can't create $err_log and don't know if mysqld can; error out\n      *)\n        log_error \"error: log-error set to '$err_log', however file don't exists. Create writable for user '$user'.\"\n        exit 1\n        ;;\n    esac\n  fi\nfi\n\nUSER_OPTION=\"\"\nif test -w / -o \"$USER\" = \"root\"\nthen\n  if test \"$user\" != \"root\" -o $SET_USER = 1\n  then\n    USER_OPTION=\"--user=$user\"\n  fi\n  if test -n \"$open_files\"\n  then\n    ulimit -n $open_files\n  fi\nfi\n\nif test -n \"$open_files\"\nthen\n  append_arg_to_args \"--open-files-limit=$open_files\"\nfi\n\nsafe_mysql_unix_port=${mysql_unix_port:-${MYSQL_UNIX_PORT:-@MYSQL_UNIX_ADDR@}}\n# Check that directory for $safe_mysql_unix_port exists\nmysql_unix_port_dir=`dirname $safe_mysql_unix_port`\nif [ ! -d $mysql_unix_port_dir ]\nthen\n  log_error \"Directory '$mysql_unix_port_dir' for UNIX socket file don't exists.\"\n  exit 1\nfi\n\n# If the user doesn't specify a binary, we assume name \"mysqld\"\nif test -z \"$MYSQLD\"\nthen\n  MYSQLD=mysqld\nfi\n\nif test ! -x \"$ledir/$MYSQLD\"\nthen\n  log_error \"The file $ledir/$MYSQLD\ndoes not exist or is not executable. Please cd to the mysql installation\ndirectory and restart this script from there as follows:\n./bin/mysqld_safe&\nSee http://dev.mysql.com/doc/mysql/en/mysqld-safe.html for more information\"\n  exit 1\nfi\n\nif test -z \"$pid_file\"\nthen\n  pid_file=\"$DATADIR/`@HOSTNAME@`.pid\"\n  pid_file_append=\"`@HOSTNAME@`.pid\"\nelse\n  pid_file_append=\"$pid_file\"\n  case \"$pid_file\" in\n    /* ) ;;\n    * )  pid_file=\"$DATADIR/$pid_file\" ;;\n  esac\nfi\nappend_arg_to_args \"--pid-file=$pid_file_append\"\n\nif test -n \"$mysql_unix_port\"\nthen\n  append_arg_to_args \"--socket=$mysql_unix_port\"\nfi\nif test -n \"$mysql_tcp_port\"\nthen\n  append_arg_to_args \"--port=$mysql_tcp_port\"\nfi\n\nif test $niceness -eq 0\nthen\n  NOHUP_NICENESS=\"nohup\"\nelse\n  NOHUP_NICENESS=\"nohup nice -$niceness\"\nfi\n\n# Using nice with no args to get the niceness level is GNU-specific.\n# This check could be extended for other operating systems (e.g.,\n# BSD could use \"nohup sh -c 'ps -o nice -p $$' | tail -1\").\n# But, it also seems that GNU nohup is the only one which messes\n# with the priority, so this is okay.\nif nohup nice > /dev/null 2>&1\nthen\n    normal_niceness=`nice`\n    nohup_niceness=`nohup nice 2>/dev/null`\n\n    numeric_nice_values=1\n    for val in $normal_niceness $nohup_niceness\n    do\n        case \"$val\" in\n            -[0-9] | -[0-9][0-9] | -[0-9][0-9][0-9] | \\\n             [0-9] |  [0-9][0-9] |  [0-9][0-9][0-9] )\n                ;;\n            * )\n                numeric_nice_values=0 ;;\n        esac\n    done\n\n    if test $numeric_nice_values -eq 1\n    then\n        nice_value_diff=`expr $nohup_niceness - $normal_niceness`\n        if test $? -eq 0 && test $nice_value_diff -gt 0 && \\\n            nice --$nice_value_diff echo testing > /dev/null 2>&1\n        then\n            # nohup increases the priority (bad), and we are permitted\n            # to lower the priority with respect to the value the user\n            # might have been given\n            niceness=`expr $niceness - $nice_value_diff`\n            NOHUP_NICENESS=\"nice -$niceness nohup\"\n        fi\n    fi\nelse\n    if nohup echo testing > /dev/null 2>&1\n    then\n        :\n    else\n        # nohup doesn't work on this system\n        NOHUP_NICENESS=\"\"\n    fi\nfi\n\n# Try to set the core file size (even if we aren't root) because many systems\n# don't specify a hard limit on core file size.\nif test -n \"$core_file_size\"\nthen\n  ulimit -c $core_file_size\nfi\n\n#\n# If there exists an old pid file, check if the daemon is already running\n# Note: The switches to 'ps' may depend on your operating system\nif test -f \"$pid_file\"\nthen\n  PID=`cat \"$pid_file\"`\n  if @CHECK_PID@\n  then\n    if @FIND_PROC@\n    then    # The pid contains a mysqld process\n      log_error \"A mysqld process already exists\"\n      exit 1\n    fi\n  fi\n  if [ ! -h \"$pid_file\" ]; then\n      rm -f \"$pid_file\"\n      if test -f \"$pid_file\"; then\n        log_error \"Fatal error: Can't remove the pid file:\n$pid_file.\nPlease remove the file manually and start $0 again;\nmysqld daemon not started\"\n        exit 1\n      fi\n  fi\n  if [ ! -h \"$safe_mysql_unix_port\" ]; then\n      rm -f \"$safe_mysql_unix_port\"\n      if test -f \"$safe_mysql_unix_port\"; then\n        log_error \"Fatal error: Can't remove the socket file:\n$safe_mysql_unix_port.\nPlease remove the file manually and start $0 again;\nmysqld daemon not started\"\n        exit 1\n      fi\n  fi\n  if [ ! -h \"$pid_file.shutdown\" ]; then\n      rm -f \"$pid_file.shutdown\"\n      if test -f \"$pid_file.shutdown\"; then\n        log_error \"Fatal error: Can't remove the shutdown file:\n$pid_file.shutdown.\nPlease remove the file manually and start $0 again;\nmysqld daemon not started\"\n        exit 1\n      fi\n  fi\nfi\n\n#\n# Uncomment the following lines if you want all tables to be automatically\n# checked and repaired during startup. You should add sensible key_buffer\n# and sort_buffer values to my.cnf to improve check performance or require\n# less disk space.\n# Alternatively, you can start mysqld with the \"myisam-recover\" option. See\n# the manual for details.\n#\n# echo \"Checking tables in $DATADIR\"\n# $MY_BASEDIR_VERSION/bin/myisamchk --silent --force --fast --medium-check $DATADIR/*/*.MYI\n# $MY_BASEDIR_VERSION/bin/isamchk --silent --force $DATADIR/*/*.ISM\n\n# Does this work on all systems?\n#if type ulimit | grep \"shell builtin\" > /dev/null\n#then\n#  ulimit -n 256 > /dev/null 2>&1\t\t# Fix for BSD and FreeBSD systems\n#fi\n\ncmd=\"`mysqld_ld_preload_text`$NOHUP_NICENESS\"\n\nfor i in  \"$ledir/$MYSQLD\" \"$defaults\" \"--basedir=$MY_BASEDIR_VERSION\" \\\n  \"--datadir=$DATADIR\" \"--plugin-dir=$plugin_dir\" \"$USER_OPTION\"\ndo\n  cmd=\"$cmd \"`shell_quote_string \"$i\"`\ndone\ncmd=\"$cmd $args\"\n# Avoid 'nohup: ignoring input' warning\ntest -n \"$NOHUP_NICENESS\" && cmd=\"$cmd < /dev/null\"\n\nlog_notice \"Starting $MYSQLD daemon with databases from $DATADIR\"\n\n# variable to track the current number of \"fast\" (a.k.a. subsecond) restarts\nfast_restart=0\n# maximum number of restarts before trottling kicks in\nmax_fast_restarts=5\n# flag whether a usable sleep command exists\nhave_sleep=1\n\nwhile true\ndo\n  start_time=`date +%M%S`\n\n  eval_log_error \"$cmd\"\n\n  # hypothetical: log was renamed but not\n  # flushed yet. we'd recreate it with\n  # wrong owner next time we log, so set\n  # it up correctly while we can!\n\n  if [ $want_syslog -eq 0 -a ! -f \"$err_log\" -a ! -h \"$err_log\" ]; then\n    if test -w / -o \"$USER\" = \"root\"; then\n      logdir=`dirname \"$err_log\"`\n      case $logdir in\n        /var/log)\n          (\n            umask 0137\n            set -o noclobber\n            > \"$err_log\" && chown $user \"$err_log\"\n          ) ;;\n        *) ;;\n      esac\n    else\n      (\n        umask 0137\n        set -o noclobber\n        > \"$err_log\"\n      )\n    fi\n  fi\n\n  end_time=`date +%M%S`\n\n  if test ! -f \"$pid_file\"\t\t# This is removed if normal shutdown\n  then\n    break\n  else                                  # self's mysqld crashed or other's mysqld running\n    PID=`cat \"$pid_file\"`\n    if @CHECK_PID@\n    then                                # true when above pid belongs to a running mysqld process\n      log_error \"A mysqld process with pid=$PID is already running. Aborting!!\"\n      exit 1\n    fi\n  fi\n\n  if test -f \"$pid_file.shutdown\"\t# created to signal that it must stop\n  then\n    log_notice \"$pid_file.shutdown present. The server will not restart.\"\n    break\n  fi\n\n\n  # sanity check if time reading is sane and there's sleep\n  if test $end_time -gt 0 -a $have_sleep -gt 0\n  then\n    # throttle down the fast restarts\n    if test $end_time -eq $start_time\n    then\n      fast_restart=`expr $fast_restart + 1`\n      if test $fast_restart -ge $max_fast_restarts\n      then\n        log_notice \"The server is respawning too fast. Sleeping for 1 second.\"\n        sleep 1\n        sleep_state=$?\n        if test $sleep_state -gt 0\n        then\n          log_notice \"The server is respawning too fast and no working sleep command. Turning off trottling.\"\n          have_sleep=0\n        fi\n\n        fast_restart=0\n      fi\n    else\n      fast_restart=0\n    fi\n  fi\n\n  if @TARGET_LINUX@ && test $KILL_MYSQLD -eq 1\n  then\n    # Test if one process was hanging.\n    # This is only a fix for Linux (running as base 3 mysqld processes)\n    # but should work for the rest of the servers.\n    # The only thing is ps x => redhat 5 gives warnings when using ps -x.\n    # kill -9 is used or the process won't react on the kill.\n    numofproces=`ps xaww | grep -v \"grep\" | grep \"$ledir/$MYSQLD\\>\" | grep -c \"pid-file=$pid_file\"`\n\n    log_notice \"Number of processes running now: $numofproces\"\n    I=1\n    while test \"$I\" -le \"$numofproces\"\n    do \n      PROC=`ps xaww | grep \"$ledir/$MYSQLD\\>\" | grep -v \"grep\" | grep \"pid-file=$pid_file\" | sed -n '$p'` \n\n      for T in $PROC\n      do\n        break\n      done\n      #    echo \"TEST $I - $T **\"\n      if kill -9 $T\n      then\n        log_error \"$MYSQLD process hanging, pid $T - killed\"\n      else\n        break\n      fi\n      I=`expr $I + 1`\n    done\n  fi\n  if [ ! -h \"$pid_file\" ]; then\n    rm -f \"$pid_file\"\n  fi\n  if [ ! -h \"$safe_mysql_unix_port\" ]; then\n    rm -f \"$safe_mysql_unix_port\"\n  fi\n  if [ ! -h \"$pid_file.shutdown\" ]; then\n    rm -f \"$pid_file.shutdown\"\n  fi\n  log_notice \"mysqld restarted\"\ndone\n\nif [ ! -h \"$pid_file.shutdown\" ]; then\n  rm -f \"$pid_file.shutdown\"\nfi\n\nlog_notice \"mysqld from pid file $pid_file ended\"\n\nif [ ! -h \"$safe_pid\" ]; then\n  rm -f \"$safe_pid\"                       # Some Extra Safety. File is deleted\nfi                                        # once the mysqld process ends.\n", "num_lines": 1033}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.\n# \n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# This script reports various configuration settings that may be needed\n# when using the MySQL client library.\n\nwhich ()\n{\n  IFS=\"${IFS=   }\"; save_ifs=\"$IFS\"; IFS=':'\n  for file\n  do\n    for dir in $PATH\n    do\n      if test -f $dir/$file\n      then\n        echo \"$dir/$file\"\n        continue 2\n      fi\n    done\n    echo \"which: no $file in ($PATH)\"\n    exit 1\n  done\n  IFS=\"$save_ifs\"\n}\n\n#\n# If we can find the given directory relatively to where mysql_config is\n# we should use this instead of the incompiled one.\n# This is to ensure that this script also works with the binary MySQL\n# version\n\nfix_path ()\n{\n  var=$1\n  shift\n  for filename\n  do\n    path=$basedir/$filename\n    if [ -d \"$path\" ] ;\n    then\n      eval \"$var\"=$path\n      return\n    fi\n  done\n}\n\nget_full_path ()\n{\n  file=$1\n\n  # if the file is a symlink, try to resolve it\n  if [ -h $file ];\n  then\n    file=`ls -l $file | awk '{ print $NF }'`\n  fi\n\n  case $file in\n    /*) echo \"$file\";;\n    */*) tmp=`pwd`/$file; echo $tmp | sed -e 's;/\\./;/;' ;;\n    *) which $file ;;\n  esac\n}\n\nme=`get_full_path $0`\n\n# Script might have been renamed but assume mysql_<something>config<something>\nbasedir=`echo $me | sed -e 's;/bin/mysql_.*config.*;;'`\n\nldata='@localstatedir@'\nexecdir='@libexecdir@'\nbindir='@bindir@'\n\n# If installed, search for the compiled in directory first (might be \"lib64\")\npkglibdir='@pkglibdir@'\npkglibdir_rel=`echo $pkglibdir | sed -e \"s;^$basedir/;;\"`\nfix_path pkglibdir $pkglibdir_rel @libsubdir@/mysql @libsubdir@\n\nplugindir='@pkgplugindir@'\nplugindir_rel=`echo $plugindir | sed -e \"s;^$basedir/;;\"`\nfix_path plugindir $plugindir_rel @libsubdir@/mysql/plugin @libsubdir@/plugin\n\npkgincludedir='@pkgincludedir@'\nif [ -f \"$basedir/include/mysql/mysql.h\" ]; then\n  pkgincludedir=\"$basedir/include/mysql\"\nelif [ -f \"$basedir/include/mysql.h\" ]; then\n  pkgincludedir=\"$basedir/include\"\nfi\n\nversion='@VERSION@'\nsocket='@MYSQL_UNIX_ADDR@'\nldflags='@LDFLAGS@'\n\nif [ @MYSQL_TCP_PORT_DEFAULT@ -eq 0 ]; then\n  port=0\nelse\n  port=@MYSQL_TCP_PORT@\nfi\n\n# Create options \nlibs=\"@QUOTED_CMAKE_CXX_LINK_FLAGS@-L$pkglibdir@RPATH_OPTION@\"\nlibs=\"$libs -l@LIBMYSQL_OS_OUTPUT_NAME@ @CONFIG_CLIENT_LIBS@\"\n\ncflags=\"-I$pkgincludedir @CFLAGS@\"\ncxxflags=\"-I$pkgincludedir @CXXFLAGS@\"\ninclude=\"-I$pkgincludedir\"\n\n\nusage () {\n        cat <<EOF\nUsage: $0 [OPTIONS]\nCompiler: @COMPILER_ID_AND_VERSION@\nOptions:\n        --cflags         [$cflags]\n        --cxxflags       [$cxxflags]\n        --include        [$include]\n        --libs           [$libs]\n        --libs_r         [$libs]\n        --plugindir      [$plugindir]\n        --socket         [$socket]\n        --port           [$port]\n        --version        [$version]\n        --variable=VAR   VAR is one of:\n                pkgincludedir [$pkgincludedir]\n                pkglibdir     [$pkglibdir]\n                plugindir     [$plugindir]\nEOF\n        exit 1\n}\n\nif test $# -le 0; then usage; fi\n\nwhile test $# -gt 0; do\n        case $1 in\n        --cflags)  echo \"$cflags\" ;;\n        --cxxflags)echo \"$cxxflags\";;\n        --include) echo \"$include\" ;;\n        --libs)    echo \"$libs\" ;;\n        --libs_r)  echo \"$libs\" ;;\n        --plugindir) echo \"$plugindir\" ;;\n        --socket)  echo \"$socket\" ;;\n        --port)    echo \"$port\" ;;\n        --version) echo \"$version\" ;;\n        --variable=*)\n          var=`echo \"$1\" | sed 's,^[^=]*=,,'`\n          case \"$var\" in\n            pkgincludedir) echo \"$pkgincludedir\" ;;\n            pkglibdir) echo \"$pkglibdir\" ;;\n            plugindir) echo \"$plugindir\" ;;\n            *) usage ;;\n          esac\n          ;;\n        *)         usage ;;\n        esac\n\n        shift\ndone\n\n#echo \"ldata: '\"$ldata\"'\"\n#echo \"execdir: '\"$execdir\"'\"\n#echo \"bindir: '\"$bindir\"'\"\n#echo \"pkglibdir: '\"$pkglibdir\"'\"\n#echo \"pkgincludedir: '\"$pkgincludedir\"'\"\n#echo \"version: '\"$version\"'\"\n#echo \"socket: '\"$socket\"'\"\n#echo \"port: '\"$port\"'\"\n#echo \"ldflags: '\"$ldflags\"'\"\n#echo \"client_libs: '\"$client_libs\"'\"\n\nexit 0\n", "num_lines": 183}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 1994, 2013, Oracle and/or its affiliates. All Rights Reserved.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA\n#\n# generate parser files from bison input files.\n\nset -eu\nTMPFILE=pars0grm.tab.c\nOUTFILE=pars0grm.cc\n\nbison -d pars0grm.y\nmv pars0grm.tab.h ../include/pars0grm.h\n\nsed -e '\ns/'\"$TMPFILE\"'/'\"$OUTFILE\"'/;\ns/^\\(\\(YYSTYPE\\|int\\) yy\\(char\\|nerrs\\)\\)/static \\1/;\n' < \"$TMPFILE\" > \"$OUTFILE\"\n\nrm \"$TMPFILE\"\n", "num_lines": 32}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 1994, 2016, Oracle and/or its affiliates. All Rights Reserved.\n#\n# This program is free software; you can redistribute it and/or modify it under\n# the terms of the GNU General Public License as published by the Free Software\n# Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Suite 500, Boston, MA 02110-1335 USA\n#\n# generate lexer files from flex input files.\n\nset -eu\n\nTMPFILE=_flex_tmp.cc\nOUTFILE=lexyy.cc\n\nflex -o $TMPFILE pars0lex.l\n\n# AIX needs its includes done in a certain order, so include \"univ.i\" first\n# to be sure we get it right.\necho '#include \"univ.i\"' > $OUTFILE\necho 'static char *yytext;' >> $OUTFILE\n\n# flex assigns a pointer to an int in one place without a cast, resulting in\n# a warning on Win64.  Add the cast.  Also define some symbols as static.\nsed -e '\ns/'\"$TMPFILE\"'/'\"$OUTFILE\"'/;\ns/\\<register\\> *//;\ns/\\(int offset = \\)\\((yy_c_buf_p) - (yytext_ptr)\\);/\\1(int)(\\2);/;\ns/\\(void yy\\(restart\\|_\\(delete\\|flush\\)_buffer\\)\\)/static \\1/;\ns/\\(void yy_switch_to_buffer\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(void yy\\(push\\|pop\\)_buffer_state\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(YY_BUFFER_STATE yy_create_buffer\\)/static \\1/;\ns/^void yyset_extra.*;//;\ns/\\(\\(int\\|void\\) yy[gs]et_\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/\\(void \\*\\?yy\\(\\(re\\)\\?alloc\\|free\\)\\)/static \\1/;\ns/\\(extern \\)\\?\\(int yy\\(leng\\|lineno\\|_flex_debug\\)\\)/static \\2/;\ns/\\(int yylex_destroy\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/^\\(\\(FILE\\|char\\) *\\* *yyget\\)/MY_ATTRIBUTE((unused)) static \\1/;\ns/^\\(extern \\)\\?\\(\\(FILE\\|char\\) *\\* *yy\\)/static \\2/;\ns/^static FILE \\*yyin = .*0, \\*yyout = .*0;//;\ns/^static int yy\\(_flex_debug\\|lineno\\);//;\ns/^static char \\*yytext;//;\n' < $TMPFILE >> $OUTFILE\n\nrm $TMPFILE\n", "num_lines": 54}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2000, 2007 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# Execute some simple basic test on MyISAM libary to check if things\n# works at all.\n\nvalgrind=\"valgrind --alignment=8 --leak-check=yes\"\nsilent=\"-s\"\n\nif test -f mi_test1$MACH ; then suffix=$MACH ; else suffix=\"\"; fi\n./mi_test1$suffix $silent\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -N -S\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -P --checksum\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -P -N -S\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent -B -N -R2\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -k 480 --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -N -S -R1\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --key_length=127 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S -N --key_length=128\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -S --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B --key_length=64  --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B -k 480 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -B -k 480 -N  --unique --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m -P --unique --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -m -P --key_length=480 --key_cache\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -m -p\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -w -S --unique\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w --key_length=64 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w -N --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -w -S --key_length=480 --checksum\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -b -N\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -a -b --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent -p -B --key_length=480\n./myisamchk$suffix -sm test1\n\n./mi_test1$suffix $silent --checksum\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rs test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rs --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqs --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -ros --correct-checksum test1\n./myisamchk$suffix -se test1\n./myisamchk$suffix -rqos --correct-checksum test1\n./myisamchk$suffix -se test1\n\n# check of myisampack / myisamchk\n./myisampack$suffix --force -s test1\n# Ignore error for index file\n./myisamchk$suffix -es test1 2>&1 >& /dev/null\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rus test1\n./myisamchk$suffix -es test1\n\n./mi_test1$suffix $silent --checksum -S\n./myisamchk$suffix -se test1\n./myisamchk$suffix -ros test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -se test1\n\n./myisampack$suffix --force -s test1\n./myisamchk$suffix -rqs test1\n./myisamchk$suffix -es test1\n./myisamchk$suffix -rus test1\n./myisamchk$suffix -es test1\n\n./mi_test1$suffix $silent --checksum --unique\n./myisamchk$suffix -se test1\n./mi_test1$suffix $silent --unique -S\n./myisamchk$suffix -se test1\n\n\n./mi_test1$suffix $silent --key_multiple -N -S\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -a -p --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -a -B --key_length=480\n./myisamchk$suffix -sm test1\n./mi_test1$suffix $silent --key_multiple -P -S\n./myisamchk$suffix -sm test1\n\n./mi_test2$suffix $silent -L -K -W -P\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -W -P -A\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -W -P -S -R1 -m500\necho \"mi_test2$suffix $silent -L -K -R1 -m2000 ;  Should give error 135\"\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -R1 -m2000\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -K -P -S -R3 -m50 -b1000000\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -L -B\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -D -B -c\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -m10000 -e8192 -K\n./myisamchk$suffix -sm test2\n./mi_test2$suffix $silent -m10000 -e16384 -E16384 -K -L\n./myisamchk$suffix -sm test2\n\n./mi_test2$suffix $silent -L -K -W -P -m50 -l\n./myisamlog$suffix\n./mi_test2$suffix $silent -L -K -W -P -m50 -l -b100\n./myisamlog$suffix\ntime ./mi_test2$suffix $silent\ntime ./mi_test2$suffix $silent -K -B\ntime ./mi_test2$suffix $silent -L -B\ntime ./mi_test2$suffix $silent -L -K -B\ntime ./mi_test2$suffix $silent -L -K -W -B\ntime ./mi_test2$suffix $silent -L -K -W -S -B\ntime ./mi_test2$suffix $silent -D -K -W -S -B\n", "num_lines": 168}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2005, 2006 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\nif [ ! -x ./ft-test-run.sh ] ; then\n  echo \"Usage: ./ft-test-run.sh\"\n  exit 1\nfi\n\nBASE=`pwd`\nDATA=$BASE/var\nROOT=`cd ../..; pwd`\nMYSQLD=$ROOT/sql/mysqld\nMYSQL=$ROOT/client/mysql\nMYSQLADMIN=$ROOT/client/mysqladmin\nSOCK=$DATA/mysql.sock\nPID=$DATA/mysql.pid\nH=../ftdefs.h\nOPTS=\"--no-defaults --socket=$SOCK --character-sets-dir=$ROOT/sql/share/charsets\"\nDELAY=10\n\nstop_myslqd()\n{\n  [ -S $SOCK ] && $MYSQLADMIN $OPTS shutdown\n  [ -f $PID ] && kill `cat $PID` && sleep 15 && [ -f $PID ] && kill -9 `cat $PID`\n}\n\nif [ ! -d t/BEST ] ; then\n  echo \"No ./t/BEST directory! Aborting...\"\n  exit 1\nfi\nrm -f t/BEST/report.txt\nif [ -w $H ] ; then\n  echo \"$H is writeable! Aborting...\"\n  exit 1\nfi\n\nstop_myslqd\nrm -rf var > /dev/null 2>&1\nmkdir var\nmkdir var/test\n\nfor batch in t/* ; do\n  [ ! -d $batch ] && continue\n  [ $batch -ef t/BEST -a $batch != t/BEST ] && continue\n\n  rm -rf var/test/* > /dev/null 2>&1\n  rm -f $H\n  if [ -f $BASE/$batch/ftdefs.h ] ; then\n    cat $BASE/$batch/ftdefs.h > $H\n    chmod a-wx $H\n  else\n    bk get -q $H\n  fi\n  OPTS=\"--defaults-file=$BASE/$batch/my.cnf --socket=$SOCK --character-sets-dir=$ROOT/sql/share/charsets\"\n  stop_myslqd\n  rm -f $MYSQLD\n  echo \"building $batch\"\n  echo \"============== $batch ===============\" >> var/ft_test.log\n  (cd $ROOT; gmake) >> var/ft_test.log 2>&1\n\n  for prog in $MYSQLD $MYSQL $MYSQLADMIN ; do\n    if [ ! -x $prog ] ; then\n      echo \"build failed: no $prog\"\n      exit 1\n    fi\n  done\n\n  echo \"=====================================\" >> var/ft_test.log\n  $MYSQLD $OPTS --basedir=$BASE --pid-file=$PID \\\n                --language=$ROOT/sql/share/english \\\n                --skip-grant-tables --skip-innodb \\\n                --skip-networking --tmpdir=$DATA >> var/ft_test.log 2>&1 &\n\n  sleep $DELAY\n  $MYSQLADMIN $OPTS ping\n  if [ $? != 0 ] ; then\n    echo \"$MYSQLD refused to start\"\n    exit 1\n  fi\n  for test in `cd data; echo *.r|sed \"s/\\.r//g\"` ; do\n    if [ -f $batch/$test.out ] ; then\n      echo \"skipping $batch/$test.out\"\n      continue\n    fi\n    echo \"testing $batch/$test\"\n    FT_MODE=`cat $batch/ft_mode 2>/dev/null`\n    ./Ecreate.pl $test \"$FT_MODE\" | $MYSQL $OPTS --skip-column-names test >var/$test.eval\n    echo \"reporting $batch/$test\"\n    ./Ereport.pl var/$test.eval data/$test.r > $batch/$test.out || exit\n  done\n  stop_myslqd\n  rm -f $H\n  bk get -q $H\n  if [ ! $batch -ef t/BEST ] ; then\n    echo \"comparing $batch\"\n    ./Ecompare.pl t/BEST $batch >> t/BEST/report.txt\n  fi\ndone\n\n", "num_lines": 117}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "echo $NDB_HOST $NDB_EXTHOST\n\nNDB_PORT=$NDB_PORT_BASE\"00\"\nNDB_CONNECTSTRING_BASE=\"host=$NDB_HOST:$NDB_PORT;nodeid=\"\n\n# Edit file system path\n\ncd $NDB_DEMO\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$NDB_DEMO/filesystem,g \\\n    -e s,\"CHOOSE_HOSTNAME\",$NDB_HOST,g\\\n    -e s,\"CHOOSE_EXTHOSTNAME\",$NDB_EXTHOST,g\\\n    -e s,\"CHOOSE_PORT_BASE\",$NDB_PORT_BASE,g\\\n    -e s,\"CHOOSE_REP_ID\",$NDB_REP_ID,g\\\n    -e s,\"CHOOSE_EXTREP_ID\",$NDB_EXTREP_ID,g\\\n    < ../config-templates/config_template-1-REP.ini > config.ini\n\n# Start management server as deamon\n\nNDB_ID=\"1\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n# Start database node \n\nNDB_ID=\"2\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME DB Node $NDB_ID\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\nNDB_ID=\"3\"\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME API Node $NDB_ID\" -geometry 80x10 &\n\n# Start xterm for rep node\n\nNDB_ID=$NDB_REP_ID\nNDB_CONNECTSTRING=$NDB_CONNECTSTRING_BASE$NDB_ID\nexport NDB_CONNECTSTRING\nxterm -T \"$NDB_DEMO_NAME REP Node $NDB_ID\" -geometry 80x10 -xrm *.hold:true -e ndb_rep &\n\n# Start management client\n\nxterm -T \"$NDB_DEMO_NAME Mgmt Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient $NDB_HOST $NDB_PORT &\n", "num_lines": 51}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nNDB_DEMO=$MYSQLCLUSTER_TOP/ndb/demos/1-node-PS\n\nNDB_PORT_BASE=\"102\"\nNDB_REP_ID=\"5\"\nNDB_EXTREP_ID=\"4\"\n\nNDB_DEMO_NAME=\"Demo 1-PS MySQL Cluster\"\nNDB_HOST1=$1\nNDB_HOST2=$2\nif [ -z \"$NDB_HOST1\" ]; then\n  NDB_HOST1=localhost\nfi\nif [ -z \"$NDB_HOST2\" ]; then\n  NDB_HOST2=localhost\nfi\nNDB_HOST=$NDB_HOST1\nNDB_EXTHOST=$NDB_HOST2\n\nsource $MYSQLCLUSTER_TOP/ndb/demos/run_demo1-PS-SS_common.sh\n", "num_lines": 31}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nNDB_DEMO=$MYSQLCLUSTER_TOP/ndb/demos/1-node-SS\n\nNDB_PORT_BASE=\"101\"\nNDB_REP_ID=\"4\"\nNDB_EXTREP_ID=\"5\"\n\nNDB_DEMO_NAME=\"Demo 1-SS MySQL Cluster\"\nNDB_HOST1=$1\nNDB_HOST2=$2\nif [ -z \"$NDB_HOST1\" ]; then\n  NDB_HOST1=localhost\nfi\nif [ -z \"$NDB_HOST2\" ]; then\n  NDB_HOST2=localhost\nfi\nNDB_HOST=$NDB_HOST2\nNDB_EXTHOST=$NDB_HOST1\n\nsource $MYSQLCLUSTER_TOP/ndb/demos/run_demo1-PS-SS_common.sh\n", "num_lines": 31}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nndb_demo=$MYSQLCLUSTER_TOP/ndb/demos\n\n# Edit file system path\n\ncd $ndb_demo/1-node/1-mgm-1\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$ndb_demo/1-node/1-db-2/filesystem,g \\\n    < template_config.ini > config.ini\n\n# Start management server as deamon\n\ncd $ndb_demo/1-node/1-mgm-1\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n# Start database node \n\ncd $ndb_demo/1-node/1-db-2\nxterm -T \"Demo 1 NDB Cluster DB Node 2\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\ncd $ndb_demo/1-node/1-api-3\nxterm -T \"Demo 1 NDB Cluster API Node 3\" -geometry 80x10 &\n\n# Start management client\n\ncd $ndb_demo\nxterm -T \"Demo 1 NDB Management Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient localhost 10000 &\n", "num_lines": 42}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nif [ -z \"$MYSQLCLUSTER_TOP\" ]; then\n  echo \"MYSQLCLUSTER_TOP not set\"\n  exit 1\nfi\nif [ -d \"$MYSQLCLUSTER_TOP/ndb\" ]; then :; else\n  echo \"$MYSQLCLUSTER_TOP/ndb directory does not exist\"\n  exit 1\nfi\nNDB_CONNECTSTRING=\nNDB_HOME=\nndb_demo=$MYSQLCLUSTER_TOP/ndb/demos\n\n# Edit file system path\n\ncd $ndb_demo/2-node/2-mgm-1\nsed -e s,\"WRITE_PATH_TO_FILESYSTEM_2_HERE\",$ndb_demo/2-node/2-db-2/filesystem,g \\\n    -e s,\"WRITE_PATH_TO_FILESYSTEM_3_HERE\",$ndb_demo/2-node/2-db-3/filesystem,g \\\n    < template_config.ini > config.ini\n\n# Start management server as deamon\n\ncd $ndb_demo/2-node/2-mgm-1\nif mgmtsrvr -d -c config.ini ; then :; else\n  echo \"Unable to start mgmtsrvr\"\n  exit 1\nfi\n\n#xterm -T \"Demo 2 NDB Management Server\" -geometry 80x10 -xrm *.hold:true -e mgmtsrvr -c config.ini &\n\n# Start database node \n\ncd $ndb_demo/2-node/2-db-2\nxterm -T \"Demo 2 NDB Cluster DB Node 2\" -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start database node \n\ncd $ndb_demo/2-node/2-db-3\nxterm -T \"Demo 2 NDB Cluster DB Node 3\"  -geometry 80x10 -xrm *.hold:true -e ndb -i &\n\n# Start xterm for application programs\n\ncd $ndb_demo/2-node/2-api-4\nxterm -T \"Demo 2 NDB Cluster API Node 4\" -geometry 80x10 &\n\n# Start xterm for application programs\n\ncd $ndb_demo/2-node/2-api-5\nxterm -T \"Demo 2 NDB Cluster API Node 5\" -geometry 80x10 &\n\n# Start management client\n\ncd $ndb_demo\nxterm -T \"Demo 2 NDB Management Client\" -geometry 80x10 -xrm *.hold:true -e mgmtclient localhost 10000 &\n", "num_lines": 55}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Build script for dojox.mobile\n\nif [ $# -eq 0 ]; then\n  echo 'Usage: build separate|single [webkit]'\n  echo '  separate  Create mobile.js that includes only dojox.mobile'\n  echo '  single    Create a single dojo.js layer that includes dojox.mobile'\n  echo '  webkit    Enable webkitMobile=true option (Loses PC browser support)'\n  exit 1\nfi\n\n#optimize=shrinksafe\noptimize=closure\nprofile=mobile\ndir=release-mobile-separate\nwebkit=\n#standalone=standaloneScrollable=true\nif [ \"$1\" == \"single\" ]; then\n  profile=mobile-all\nfi\nif [ \"$1\" == \"single\" ]; then\n  dir=release-mobile-single\nfi\nshift 1\nif [ \"$1\" == \"webkit\" ]; then\n  webkit=webkitMobile=true\n  shift 1\nfi\n\ncd ../../../util/buildscripts\n\n./build.sh profile=$profile action=release optimize=$optimize layerOptimize=$optimize cssOptimize=comments releaseDir=../../$dir/ $webkit $standalone $*\n\ncd ../../dojox/mobile/build\n", "num_lines": 36}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# TODO: FIXME: Get rid of this and hook it into Dojo's general build script\n# You must have mtasc to run this\nmtasc -trace DojoExternalInterface.trace -main -cp ../flash -swf Storage.swf -version 8 -header 215:138:10 Storage.as\n", "num_lines": 5}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\nMEMC_VERSION=`git describe | tr '-' '_'`;\ncat > .libs/config_version.h << EOF\n#ifndef CONFIG_VERSION_H\n#define CONFIG_VERSION_H\n\n/* Define to the full name and version of this package. */\n#define PACKAGE_STRING \"memcached $MEMC_VERSION\"\n\n/* Define to the version of this package. */\n#define PACKAGE_VERSION \"$MEMC_VERSION\"\n\n/* Version number of package */\n#define VERSION \"$MEMC_VERSION\"\n\n#endif // CONFIG_VERSION_H\nEOF\n", "num_lines": 18}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Some sample queries using the command line\nexport JONES_ADAPTER=mysql || setenv JONES_ADAPTER mysql  # sh || csh\n\n\n# Get tweets that mention @agrippina\necho \"Getting tweets @agrippina:\"\nnode tweet get tweets-at agrippina\n\n# Get tweets with hashtag #carthage\necho \"Getting tweets about #carthage:\"\nnode tweet get tweets-about carthage\n\n# Get tweets written by Nero\necho \"Getting tweets by nero:\"\nnode tweet get tweets-by nero\n\n# Get the five most recent tweets\necho \"Getting the five most recent tweets:\"\nnode tweet get tweets-recent 5\n\n# Nobody follows Claudius\necho \"Getting: who follows claudius?\"\nnode tweet get followers uncle_claudius\n\n# See who Agrippina follows\necho \"Getting: who does agrippina follow?\"\nnode tweet get following agrippina\n", "num_lines": 28}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#\n#\n# Before running these, start the tweet.js app as a web server:\n#\n#       node tweet start server 7800\n#\n#\n\n\n# Delete everyone.  Afterwards the database will be empty\n# due to cascading deletes.\necho\necho \"Deleting users:\"\ncurl -X DELETE http://localhost:7800/user/caligula\ncurl -X DELETE http://localhost:7800/user/uncle_claudius\ncurl -X DELETE http://localhost:7800/user/agrippina\ncurl -X DELETE http://localhost:7800/user/nero\n\n\n# See that the tweets are all gone:\necho\necho \"Fetching the most recent tweets:\"\ncurl http://localhost:7800/tweets-recent/10  # empty\n\n\n# Try to delete someone a second time & you get an error:\necho\necho \"Deleting a user again:\"\ncurl -X DELETE http://localhost:7800/user/uncle_claudius\n", "num_lines": 30}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#\n#\n# Before running these, start the tweet.js app as a web server:\n#\n#       node tweet start server 7800\n#\n#\n\n# Some sample queries that use curl to demonstrate the REST Tweet API:\n\n# Get tweets @agrippina\necho\necho \"Getting tweets @agrippina:\"\ncurl http://localhost:7800/tweets-at/agrippina\n\n# Get tweets about #carthage\necho\necho \"Getting tweets about #carthage:\"\ncurl http://localhost:7800/tweets-about/carthage\n\n# There are no tweets about #aqueduct\necho\necho \"Getting tweets about #aquedeuct:\"\ncurl http://localhost:7800/tweets-about/aqueduct\n\n# Nero can use the API to post a tweet about his aqueduct:\necho\necho \"Posting a new tweet:\"\ncurl http://localhost:7800/tweet/nero -d \\\n   'help! my #aqueduct has run dry again! @uncle_claudius!'\n\n# Query again to see the new tweet:\necho\necho \"Getting tweets about #aquedeuct:\"\ncurl http://localhost:7800/tweets-about/aqueduct\n\necho\necho \"Getting tweets @uncle_claudius:\"\ncurl http://localhost:7800/tweets-at/uncle_claudius\n", "num_lines": 40}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "# This script populates the sample database\nexport JONES_ADAPTER=mysql || setenv JONES_ADAPTER mysql  # sh || csh\nset -x\n\n# Create four users: Caligula, Claudius, Nero, Agrippina\n#\nnode tweet put user caligula '{ \"full_name\": \"Gaius Julius Caesar Germanicus\" , \"profile_text\": \"I am your little boot!\" }'\nnode tweet put user uncle_claudius '{ \"full_name\": \"Tiberius Claudius Nero Germanicus\" }'\nnode tweet put user nero '{ \"full_name\": \"Lucius Domitius Ahenobarus\" }'\nnode tweet put user agrippina '{ \"full_name\": \"Julia Augusta Agrippina Minor\"}'\n\n\n# Create follow records: Nero follows Agrippina, etc.\n#\nnode tweet put follow nero agrippina\nnode tweet put follow agrippina nero\nnode tweet put follow agrippina uncle_claudius\nnode tweet put follow agrippina caligula\n\n\n# Now post some tweets from each user\n#\nnode tweet post tweet caligula '@agrippina You really are my favorite sister.'\nnode tweet post tweet agrippina '@nero Remember to be nice to Uncle Claudius!' \nnode tweet post tweet nero 'I love to sing!'\nnode tweet post tweet nero 'I am the best #poet and the best #gladiator!'\nnode tweet post tweet agrippina \\\n '@uncle_claudius Please come over for dinner, we have some fantastic #mushrooms'\nnode tweet post tweet uncle_claudius 'I am writing a new history of #carthage'\nnode tweet post tweet caligula '@agrippina you are my worst sister! worst!' \nnode tweet post tweet caligula '@agrippina Rome is terrible!!!'\n", "num_lines": 32}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\necho \"--> $0\"\n\noutdir=\"logs\"\nnewdir=\"$outdir/xxx\"\ndstdir=\"$outdir/$1\"\nout=\"$newdir/out.txt\"\n\nif [ $# -ne 1 ] || [[ \"$1\" = *\"help\" ]] ; then\n    echo \"usage: $0 <run.c++crund|run.jcrund|...>\"\n    exit 1\nfi\n\ndriver=$1\ncase $driver in\n    run.c++crund|run.jcrund)\n\t;;\n    \"\")\n\techo \"missing argument: <driver>\"; exit 1\n\t;;\n    *)\n\techo \"unknown <driver>: $driver\"; exit 1\n\t;;\nesac\n\nif [ -d \"$newdir\" ] ; then\n    echo \"dir already exists: $newdir\"\n    exit 1\nfi\nif [ -d \"$dstdir\" ] ; then\n    echo \"dir already exists: $dstdir\"\n    exit 1\nfi\n\nmkdir -p \"$newdir\"\ntouch \"$out\"\necho \"\" | tee -a \"$out\"\nif command -v hwprefs >> \"$out\" 2>&1 ; then\n    hwprefs -v os_type machine_type cpu_type cpu_freq cpu_bus_freq cpu_count \\\n\t2>&1 | tee -a \"$out\"\nfi\necho \"\" | tee -a \"$out\"\n#./restart_cluster.sh 2>&1 | tee -a \"$out\"\n\n#vmstat 5 > vmstat5.txt 2>&1 &\niostat 5 > iostat5.txt 2>&1 &\npid=$!\n\necho \"\" | tee -a \"$out\"\n./mysql.sh -v < ../src/crund_schema.sql 2>&1 | tee -a \"$out\"\n\necho \"RUNNING CRUND ...\" | tee -a \"$out\"\ncase $driver in\n    run.c++crund)\n\t( cd .. ; make run.crund ) >> \"$out\" 2>&1\n\t;;\n    run.jcrund)\n\t( cd .. ; ant run.crund.opt ) >> \"$out\" 2>&1\n\t;;\n    *)\n\techo \"unknown <driver>: $driver\" | tee -a \"$out\"\n\t;;\nesac\necho \"... DONE CRUND\" | tee -a \"$out\"\n\nsleep 6\nkill -9 $pid\n\nmv -v \"$out\" *stat*.txt ../log*.txt \"$newdir\"\ncp -v ../*.properties ../build.xml ../config.ini ../my.cnf \"$newdir\"\nmv -v \"$newdir\" \"$dstdir\"\n\necho\necho \"<-- $0\"\n", "num_lines": 91}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#set -x\n\nuser=\"$(whoami)\"\necho\necho \"grant privileges to users: '', $user\"\n# MySQL doesn't support wildcards in user names but anonymous users as '';\n# any user who connects from the local host with the correct password for\n# the anonymous user will be allowed access then.\n./mysql.sh -v -u root -e \"GRANT ALL ON *.* TO ''@localhost, $user@localhost;\"\ns=$?\necho \"mysql exit status: $s\"\n\necho\necho done.\nexit $s\n\n#set +x\n", "num_lines": 35}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\n# 4 bash parameter substitution forms: $*, \"$*\", $@, \"$@\" (use last here)\n#echo nArgs=$#\n#echo args=\\'\"$@\"\\'\n#for p in \"$@\"; do echo \"    [$p]\"; done\n\necho\n\"ndb_mgm\" -c \"$NDB_CONNECT\" \"$@\"\n\n#set +x\n", "num_lines": 35}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\nmysock=\"/tmp/mysql.sock\"\n#mysock=\"$mylogdir/mysql.sock\"\n\n# 4 bash parameter substitution forms: $*, \"$*\", $@, \"$@\" (use last here)\n#echo nArgs=$#\n#echo args=\\'\"$@\"\\'\n#for p in \"$@\"; do echo \"    [$p]\"; done\n\n#echo\n#\"mysql\" \"$@\"\n# for localhost connections:\n\"mysql\" --socket=\"$mysock\" \"$@\"\n# for remote connections:\n#\"mysql\" -h localhost -P 3307 \"$@\"\n#\"mysql\" -host=localhost -port=3307 \"$@\"\n\n#set +x\n", "num_lines": 43}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# simulate network latency on Mac OS X, see man ipfw(8)\n\n#set -x\n\nif [ $# -lt 1 ] ; then\n  echo \"usage: `basename $0` <delay-ms> [<port> ...]\"\n  echo \"                 delay < 0 deletes the delay rule set\"\n  echo \"                       = 0 disables the delay rule set\"\n  echo \"                       > 0 enables the delay rule set\"\n  echo \"                 port... adds the ports to the delay rule set\"\n  exit 1\nfi\n\ndelay=$1\nshift\nports=$*\n#echo \"simulate a delay of ($delay + $delay) ms on ports $ports\"\necho \"simulate a delay of $delay ms on destination ports $ports\"\npipe=4711 # 1..64k\nrset=21   # 0..30\n\nif [ $delay -lt 0 ] ; then\n    echo \"removing rules (as admin)...\"\n    sudo ipfw delete set $rset\n    sudo ipfw pipe delete $pipe > /dev/null 2>&1\nelif [ $delay -eq 0 ] ; then\n    echo \"disabling rules (as admin)...\"\n    sudo ipfw set disable $rset\nelse\n    echo \"adding rules (as admin)...\"\n    # not strictly necessary but better change atomically\n    sudo ipfw set disable $rset\n    sudo ipfw pipe $pipe config delay $delay\n    sudo ipfw set enable $rset\n    # rules not visible if set disabled\n    for p in $ports ; do\n        sudo ipfw list $p > /dev/null\n        if [ $? -ne 0 ] ; then\n            # not strictly necessary but better change atomically\n            sudo ipfw set disable $rset\n#            sudo ipfw add $p set $rset pipe $pipe src-port $p > /dev/null 2>&1\n            sudo ipfw add $p set $rset pipe $pipe dst-port $p > /dev/null 2>&1\n            sudo ipfw set enable $rset\n        fi\n    done\nfi\necho \"current rules:\"\nsudo ipfw list | grep $pipe\n#sudo ipfw show\necho \"done.\"\n\n#set +x\n", "num_lines": 70}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# simulate network latency on data nodes' ports listed in config.ini\n\n#set -x\n\nif [ $# -lt 1 ] ; then\n  echo \"usage: `basename $0` <delay-ms> [<config.ini>]\"\n  exit 1\nfi\n\ndelay=$1\nmyini=${2:-\"../config.ini\"}\nif [ ! -e \"$myini\" ] ; then\n  echo \"file not found: $myini\"\n  exit 1\nfi\n\nports=\"`grep '^ServerPort' $myini | sed -e 's/.*=//' -e 's/#.*//'`\"\nports=\"`echo $ports`\" # remove newlines\necho \"found ServerPorts in $myini : $ports\"\n\nif [ x\"`uname`\" = x\"Darwin\" ] ; then\n    ./pdelay_mac.sh $delay $ports\nfi\n\n#set +x\n", "num_lines": 43}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA\n\necho \"running result processor...\"\njava -classpath build com.mysql.cluster.crund.ResultProcessor $*\necho \"done.\"\n", "num_lines": 21}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n./stop_cluster.sh\n\n#for ((i=0; i<2; i++)) ; do printf \".\" ; sleep 1 ; done\n\n./start_cluster.sh\n", "num_lines": 23}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n./stop_mysqld.sh\n\n#for ((i=0; i<2; i++)) ; do printf \".\" ; sleep 1 ; done\n\n./start_mysqld.sh\n", "num_lines": 23}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n./stop_ndb.sh\n\n#for ((i=0; i<2; i++)) ; do printf \".\" ; sleep 1 ; done\n\n./start_ndb.sh\n", "num_lines": 23}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\nfi\n\n#set -x\n\n#ps -efa | grep ndb\n\necho\necho show cluster...\n\"$MYSQL_BIN/ndb_mgm\" -c \"$NDB_CONNECT\" -e show -t 1\n\n#set +x\n", "num_lines": 32}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#XXX fix: also kills this script, possibly before other matching processes\nps -efa | grep -i $1\n\nfor X in `ps -efa | grep -i $1 | awk {'print $2'}`; do\n  kill $X;\ndone\n\nsleep 1\n\nfor X in `ps -efa | grep -i $1 | awk {'print $2'}`; do\n  kill -9 $X;\ndone\n", "num_lines": 30}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n./start_ndb.sh\n\n# need some extra time\n#for ((i=0; i<1; i++)) ; do printf \".\" ; sleep 1 ; done\n\n./start_mysqld.sh\n", "num_lines": 24}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2013, 2014 Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo \"MYSQL_HOME=$MYSQL_HOME\"\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\ncwd=\"$(pwd)\"\nmylogdir=\"$cwd/ndblog\"\nmkdir -p \"$mylogdir\"\nmyini=\"$cwd/../config.ini\"\n\necho\necho start mgmd...\n# options:\n# --print-defaults         Print the program argument list and exit.\n# -P, --print-full-config  Print full config and exit\n# -c, --ndb-connectstring=name  Set connect string for connecting to ndb_mgmd\n#                          \"[nodeid=<id>;][host=]<hostname>[:<port>]\"\n#                          Overrides entries in NDB_CONNECTSTRING and my.cnf\n# --bind-address=name      Local bind address\n# -f, --config-file=name   Specify cluster configuration file\n# --mycnf                  Read cluster config from my.cnf\n# --initial                Delete all binary config files and start from\n#                          config.ini or my.cnf.  Only in > 6.3\n( cd \"$mylogdir\" ; \"ndb_mgmd\" --initial -f \"$myini\" )\n#( cd \"$mylogdir\" ; \"ndb_mgmd\" --debug --initial -f \"$myini\" )\n#\n# XXX no effect: -c \"localhost:1187\"\n#( cd \"$mylogdir\" ; \"ndb_mgmd\" --initial -c \"localhost:1187\" -f \"$myini\" )\n# see ndb_1_cluster.log\n#     [MgmtSrvr] INFO     -- Got initial configuration from '../../config.ini', will try to set it when all ndb_mgmd(s) started\n#     [MgmtSrvr] INFO     -- Id: 1, Command port: *:1186\n# MgmtSrvr.cpp sets default port:\n#   ndb_mgm_set_connectstring(mgm_handle, buf.c_str());\n# ConfigManager.cpp likely not called:\n#   m_connect_string(connect_string),\n#\n# port number seems not supported as part of --bind-address=\"localhost:1187\"\n#( cd \"$mylogdir\" ; \"ndb_mgmd\" --bind-address=\"localhost:1187\" -f \"$myini\" )\n\n#echo\n#ps -efa | grep ndb\n\n#set +x\n", "num_lines": 64}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\ncwd=\"$(pwd)\"\nmylogdir=\"$cwd/ndblog\"\nmkdir -p \"$mylogdir\"\nuser=\"$(whoami)\"\nmycnf=\"$cwd/../my.cnf\"\nmyerr=\"$mylogdir/mysqld.log.err\"\nmysock=\"/tmp/mysql.sock\"\n#mysock=\"$mylogdir/mysql.sock\"\n\necho\necho start mysqld...\n( cd $MYSQL_HOME ; \"mysqld_safe\" --defaults-file=\"$mycnf\" --user=\"$user\" --log-error=\"$myerr\" --socket=\"$mysock\" & )\n#\n# debug:\n#( cd $MYSQL_HOME ; \"mysqld_safe\" --defaults-file=\"$mycnf\" --user=\"$user\" --log-error=\"$myerr\" -#d & )\n# crashes when --debug/-# at beginning:\n#( cd $MYSQL_HOME ; \"$mysqld\" --debug --defaults-file=\"$mycnf\" --user=\"$user\" --log-error=\"$myerr\" & )\n\n# need some extra time\nfor ((i=0; i<10; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\n#echo\n#ps -efa | grep mysqld\n\n./show_cluster.sh\n\n#set +x\n", "num_lines": 53}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\n./start_mgmd.sh\n\n# need some extra time\nfor ((i=0; i<10; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\ncwd=\"$(pwd)\"\nmylogdir=\"$cwd/ndblog\"\nmkdir -p \"$mylogdir\"\nmyini=\"$cwd/../config.ini\"\nnNodes=$(grep -c '^ *\\[ndbd\\]' \"$myini\")\n\necho\necho \"starting $nNodes data nodes...\"\nfor ((i=0; i<nNodes; i++)) ; do\n    echo\n    echo \"start ndbd...\"\n    # apparently, these options need to come first:\n    # --print-defaults        Print the program argument list and exit.\n    # --no-defaults           Don't read default options from any option file.\n    # --defaults-file=#       Only read default options from the given file #.\n    # --defaults-extra-file=# Read this file after the global files are read.\n    #( cd \"$mylogdir\" ; \"ndbd\" --initial )\n    ( cd \"$mylogdir\" ; \"ndbd\" -c \"$NDB_CONNECT\" --initial )\ndone\n\n#echo\n#ps -efa | grep ndb\n\n# need some extra time\nfor ((i=0; i<3; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\ntimeout=60\necho\necho \"waiting ($timeout s) for ndbd to start up...\"\n\"ndb_waiter\" -c \"$NDB_CONNECT\" -t $timeout\n\n# need some extra time\nfor ((i=0; i<3; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\n./show_cluster.sh\n\n#set +x\n", "num_lines": 68}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n./stop_mysqld.sh\n\n# need some extra time\n#for ((i=0; i<1; i++)) ; do printf \".\" ; sleep 1 ; done\n\n./stop_ndb.sh\n", "num_lines": 24}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\ncwd=\"$(pwd)\"\nmylogdir=\"$cwd/ndblog\"\nmysock=\"/tmp/mysql.sock\"\n#mysock=\"$mylogdir/mysql.sock\"\n\necho shut down mysqld...\n#\"mysqladmin\" shutdown\n\"mysqladmin\" --socket=\"$mysock\" shutdown\n\n# need some extra time\nfor ((i=0; i<5; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\n#echo\n#ps -efa | grep mysqld\n\n#set +x\n", "num_lines": 42}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nif [ \"$MYSQL_HOME\" = \"\" ] ; then\n  source ../env.properties\n  echo MYSQL_HOME=$MYSQL_HOME\n  PATH=\"$MYSQL_LIBEXEC:$MYSQL_BIN:$PATH\"\nfi\n\n#set -x\n\n#./show_cluster.sh\n\necho shut down NDB...\n./mgm.sh -e shutdown -t 1\n\ntimeout=60\necho\necho \"waiting ($timeout s) for ndb to shut down...\"\n\"ndb_waiter\" -c \"$NDB_CONNECT\" -t $timeout --no-contact\n\n# need some extra time for ndb_mgmd to terminate\nfor ((i=0; i<10; i++)) ; do printf \".\" ; sleep 1 ; done ; echo\n\n#echo\n#ps -efa | grep ndb\n\n#set +x\n", "num_lines": 43}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nbase=\"`dirname $0`\"\nsource \"$base\"/parseargs.sh\n\necp=\"set optimizer_switch = 'engine_condition_pushdown=on';\"\n\nif [ \"$load\" ]\nthen\n    source \"$base\"/load.sh\nfi\n\nif [ \"$runtime\" -o \"$loops\" ]\nthen\n    source \"$base\"/run.sh\nfi\n", "num_lines": 34}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nbase=\"`dirname $0`\"\nsource \"$base\"/parseargs.sh\n\n# Create database with a case sensitive collation to ensure a deterministic \n# resultset when 'LIMIT' is specified:\ncharset_spec=\"\"\nif [ \"$charset\" ]\nthen\n    charset_spec=\"character set $charset\"\nfi\n\nsprocs=\"copydb alter_engine analyze_db\"\nif [ \"$oj\" ]\nthen\n    sprocs=\"oj_schema_mod copydb alter_engine oj_schema_mod_ndb analyze_db\"\nfi\n\n$mysql_exe -e \"drop database if exists ${innodb_db};\"\n$mysql_exe -e \"drop database if exists ${ndb_db};\"\n$mysql_exe -e \"create database ${innodb_db} ${charset_spec};\"\n$mysql_exe -e \"create database ${ndb_db} ${charset_spec}\"\n\n# Call RANDGEN\n${gendata} --dsn=\"$dsn:database=${innodb_db}\" --spec ${data}\n\nfor i in $sprocs\ndo\n    $mysql_exe ${ndb_db} < $base/$i.sproc.sql\ndone\n\nfor i in $sprocs\ndo\n    if [ \"$i\" = \"oj_schema_mod\" ]\n    then\n\t$mysql_exe ${ndb_db} -e \"call $i('${innodb_db}');\"\n    elif [ \"$i\" = \"copydb\" ]\n    then\n\t$mysql_exe ${ndb_db} -e \"call copydb('${ndb_db}', '${innodb_db}');\"\n    elif [ \"$i\" = \"alter_engine\" ]\n    then\n\t$mysql_exe ${ndb_db} -e \"call $i('${ndb_db}', 'ndb');\"\n    else\n\t$mysql_exe ${ndb_db} -e \"call $i('${ndb_db}');\"\n    fi\ndone\n\n\nfor i in $sprocs\ndo\n    $mysql_exe ${ndb_db} -e \"drop procedure $i;\"\ndone\n", "num_lines": 71}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\n: ${load:=1}\n: ${loops:=10}\n: ${queries:=500}\n: ${host:=127.0.0.1}\n: ${port:=3306}\n: ${RQG_HOME:=~/randgen-2.2.0}\n: ${user:=root}\n: ${data:=simple.zz}\n: ${grammar:=spj_test.yy}\n: ${charset:=\"latin1 collate latin1_bin\"}\n: ${EXE_MYSQL:=}\n: ${EXE_MYSQLTEST:=}\n: ${runtime:=}\n: ${seed:=}\n: ${mode:=m,nv,np}\n: ${oj=}\n\nwhile getopts \":nom:r:l:h:p:q:d:c:g:u:t:M:s:R:\" opt; do\n  case $opt in\n    M)\n      MYSQL_BASE_DIR=\"${OPTARG}\"\n      ;;\n    R)\n      RQG_HOME=\"${OPTARG}\"\n      ;;\n    s)\n      seed=\"${OPTARG}\"\n      ;;\n    l)\n      loops=\"${OPTARG}\"\n      ;;\n    q)\n      queries=\"${OPTARG}\"\n      ;;\n    d)\n      data=\"${OPTARG}\"\n      ;;\n    c)\n      charset=\"${OPTARG}\"\n      ;;\n    g)\n      grammar=\"${OPTARG}\"\n      ;;\n    h)\n      host=\"${OPTARG}\"\n      ;;\n    p)\n      port=\"${OPTARG}\"\n      ;;\n    u)\n      user=\"${OPTARG}\"\n      ;;\n    t)\n      runtime=\"${OPTARG}\"\n      ;;\n    n)\n      load=\"\";\n      ;;\n    m)\n      mode=\"${OPTARG}\"\n      ;;\n    o)\n      oj=1\n      ;;\n    \\?)\n      echo \"Usage: `basename $0` [options]                        \" >&2\n      echo \"-R <RQH_HOME>         :                               \" >&2\n      echo \"-M <mysql install>    :                               \" >&2\n      echo \"-l <no of loops>      :                               \" >&2\n      echo \"-q <queries per loop> :                               \" >&2\n      echo \"-t <runtime>          : in seconds, overrides loops   \" >&2\n      echo \"-h <host>             :                               \" >&2\n      echo \"-p <port>             :                               \" >&2\n      echo \"-u <user>             :                               \" >&2\n      echo \"-d <data-spec>        :                               \" >&2\n      echo \"-g <grammar-spec>     :                               \" >&2\n      echo \"-n                    : skip creating/loading database\" >&2\n      echo \"-c <charsets>         : charsets                      \" >&2\n      echo \"-m <mode>             :                               \" >&2\n      echo \"-s <seed>             :                               \" >&2\n      echo \"-o                    : oj schema extentions          \" >&2\n\n      exit 1\n      ;;\n    :)\n      echo \"Option -$OPTARG requires an argument.\" >&2\n      exit 1\n      ;;\n  esac\ndone\n\nif [ ! -x \"${RQG_HOME}/gensql.pl\" ]\nthen\n    echo \"Failed to locate \\\"${RQG_HOME}/gensql.pl\\\", check RQG_HOME\"\n    exit 1\nfi\n\nif [ ! -x \"${RQG_HOME}/gendata.pl\" ]\nthen\n    echo \"Failed to locate \\\"${RQG_HOME}/gendata.pl\\\", check RQG_HOME\"\n    exit 1\nfi\n\nif [ -z \"$EXE_MYSQL\" ]\nthen\n    if [ -z \"$MYSQL_BASE_DIR\" ]\n    then\n\tEXE_MYSQL=`which mysql`\n    else\n\tEXE_MYSQL=\"$MYSQL_BASE_DIR/bin/mysql\"\n    fi\nfi\n\nif [ -z \"$EXE_MYSQLTEST\" ]\nthen\n    if [ -z \"$MYSQL_BASE_DIR\" ]\n    then\n\tEXE_MYSQLTEST=`which mysqltest`\n    else\n\tEXE_MYSQLTEST=\"$MYSQL_BASE_DIR/bin/mysqltest\"\n    fi\nfi\n\n\nif [ ! -x \"$EXE_MYSQL\" ]\nthen\n    echo \"Failed to locate mysql binary\"\n    exit 1\nfi\n\nif [ ! -x \"$EXE_MYSQLTEST\" ]\nthen\n    echo \"Failed to locate mysqltest binary\"\n    exit 1\nfi\n\nif [ ! -f \"${data}\" ]\nthen\n    if [ -f \"`dirname $0`/${data}\" ]\n    then\n\tdata=\"`dirname $0`/${data}\"\n    fi\nfi\n\nif [ ! -f \"${grammar}\" ]\nthen\n    if [ -f \"`dirname $0`/${grammar}\" ]\n    then\n\tgrammar=\"`dirname $0`/${grammar}\"\n    fi\nfi\n\n\ndsn=\"dbi:mysql:host=${host}:port=${port}:user=root\"\ngensql=${RQG_HOME}/gensql.pl\ngendata=${RQG_HOME}/gendata.pl\nmysql_exe=\"$EXE_MYSQL --show-warnings --user=${user} --host=${host} --port=${port}\"\nmysqltest_exe=\"$EXE_MYSQLTEST --user=${user} --host=${host} --port=${port}\"\nexport RQG_HOME\n\ngetepochtime=\"date +%s\"\nif [ `uname` = \"SunOS\" ]\nthen\n    getepochtime=\"nawk 'BEGIN{print srand();}'\"\nfi\n\nmd5sum=\"md5sum\"\nif [ `uname` = \"SunOS\" ]\nthen\n    md5sum=\"digest -a md5\"\nfi\n\nawk_exe=awk\nif [ `uname` = \"SunOS\" ]\nthen\n    awk_exe=gawk\nfi\n\npre=\"spj\"\nopre=\"$pre.$$\"\ninnodb_db=\"${pre}_innodb\"\nndb_db=\"${pre}_ndb\"\n", "num_lines": 202}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\n: ${load:=1}\n: ${loops:=100}\n: ${queries:=1000}\n: ${host:=loki43}\n: ${port:=4401}\n: ${RQG_HOME:=/net/fimafeng09/export/home/tmp/oleja/mysql/randgen/randgen-2.2.0}\n\n\nwhile getopts \":nm:r:l:h:p:\" opt; do\n  case $opt in\n    n)\n      load=0\n      ;;\n    m)\n      MYSQLINSTALL=${OPTARG}\n      ;;\n    r)\n      RQG_HOME=${OPTARG}\n      ;;\n    l)\n      loops=${OPTARG}\n      ;;\n    h)\n      host=${OPTARG}\n      ;;\n    p)\n      port=${OPTARG}\n      ;;\n    \\?)\n      echo \"Usage: `basename $0` [options]\"  >&2\n      echo \"-n : Do not create database (assumed to exist already).\"  >&2\n      echo \"-m <mysql install dir>\"  >&2\n      echo \"-r <rqg installation dir>\"  >&2\n      echo \"-l <no of loops>\"  >&2\n      echo \"-h <host>\"  >&2\n      echo \"-p <port>\"  >&2\n      exit 1\n      ;;\n    :)\n      echo \"Option -$OPTARG requires an argument.\" >&2\n      exit 1\n      ;;\n  esac\ndone\n\n\npre=\"spj\"\nopre=\"$pre.$$\"\n\n: ${data:= --spec=simple.zz}\n: ${grammar:=spj_test.yy}\n\n##: ${grammar:=$RQG_HOME/conf/optimizer_no_subquery.yy}   ## a pretty sensible grammar:\n##: ${grammar:=$RQG_HOME/conf/optimizer_no_subquery_portable.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_drizzle.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_materialization.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_semijoin.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery_semijoin_nested.yy}\n##: ${grammar:=$RQG_HOME/conf/outer_join.yy}\n##: ${grammar:=$RQG_HOME/conf/outer_join_portable.yy}\n\n## Really simple (or: 'stupid') grammars: Have modified these, used to have nondeterministic behaviour\n##: ${grammar:=$RQG_HOME/conf/subquery.yy}\n##: ${grammar:=$RQG_HOME/conf/subquery-5.1.yy}\n\n##: ${grammar:=$RQG_HOME/conf/optimizer_subquery.yy}\n\ngensql=${RQG_HOME}/gensql.pl\ngendata=${RQG_HOME}/gendata.pl\necp=\"set optimizer_switch = 'engine_condition_pushdown=on';\"\n\ndsn=dbi:mysql:host=${host}:port=${port}:user=root:database=${pre}_innodb\nmysqltest=\"$MYSQLINSTALL/bin/mysqltest -uroot --host=${host} --port=${port}\"\nmysql=\"$MYSQLINSTALL/bin/mysql --host=${host} --port=${port}\"\n\n# Create database with a case sensitive collation to ensure a deterministic \n# resultset when 'LIMIT' is specified:\ncharset_spec=\"character set latin1 collate latin1_bin\"\n#charset_spec=\"default character set utf8 default collate utf8_bin\"\n\nexport RQG_HOME\nif [ \"$load\" ]\nthen\n\t$mysql -uroot -e \"drop database if exists ${pre}_innodb; drop database if exists ${pre}_ndb\"\n\t$mysql -uroot -e \"create database ${pre}_innodb ${charset_spec}; create database ${pre}_ndb ${charset_spec}\"\n\t${gendata} --dsn=$dsn ${data}\ncat > /tmp/sproc.$$ <<EOF\nDROP PROCEDURE IF EXISTS copydb;\ndelimiter |;\nCREATE PROCEDURE copydb(dstdb varchar(64), srcdb varchar(64),\n                        dstengine varchar(64))\nBEGIN\n\n  declare tabname varchar(255);\n  declare indextype varchar(32);\n  declare _unique varchar(16);\n  declare done integer default 0;\n  declare cnt integer default 0;\n  declare c cursor for \n    SELECT table_name\n    FROM INFORMATION_SCHEMA.TABLES where table_schema = srcdb;\n  declare continue handler for not found set done = 1;\n\n  open c;\n  \n  repeat\n    fetch c into tabname;\n    if not done then\n       set @ddl = CONCAT('CREATE TABLE ', dstdb, '.', tabname, \n                         ' LIKE ', srcdb, '.', tabname);\n       select @ddl;\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n       set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, \n                         ' engine = ', dstengine);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n\n       ## Drop the original index 'col_int_unique' - recreate a richer set of indexes below\n       set @ddl = CONCAT('DROP INDEX col_int_unique ON ', dstdb, '.', tabname);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n\n       set cnt = cnt+1;\n\n       set _unique = '';\n       set indextype = '';\n       ## Create a mix if 'CREATE INDEX' | 'CREATE UNIQUE INDEX [USING HASH] '\n\n       if ((cnt%3) <> 0) then\n         set _unique = ' UNIQUE';\n\n         if ((cnt%2) = 0) then\n           set indextype = ' USING HASH';\n         else\n           set indextype = '';\n         end if;\n       end if;\n\n       ## Add some composite, possibly unique, indexes\n       if tabname > 'T' then\n          set @ddl = CONCAT('DROP INDEX col_varchar_10_unique ON ', dstdb, '.', tabname);\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_char_16,col_char_16_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix2 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_varchar_256,col_varchar_10_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       elseif tabname > 'O' then\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix2 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int_key,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       elseif tabname > 'H' then\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix3 ', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int,col_int_key,col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n\n       else\n          set @ddl = CONCAT('CREATE', _unique, ' INDEX ix1', indextype,\n                            ' ON ', dstdb, '.', tabname, \n                            '(col_int_unique)');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n       end if;\n\n       ## Modify primary key & partition for some tables\n       if ((cnt%3) = 0) then\n          set @ddl = CONCAT('UPDATE ', srcdb, '.', tabname, ' SET col_int=0 WHERE col_int IS NULL');\n          PREPARE stmt from @ddl;\n          EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY ', '(col_int,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_int)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%5) = 0) then\n           set @ddl = CONCAT('UPDATE ', srcdb, '.', tabname, ' SET col_int=0 WHERE col_int IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(col_int,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%7) = 0) then\n           set @ddl = CONCAT('DELETE FROM ', srcdb, '.', tabname, ' WHERE col_char_16 IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(col_char_16,pk)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_char_16)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n\n        elseif ((cnt%11) = 0) then\n           set @ddl = CONCAT('DELETE FROM ', srcdb, '.', tabname, ' WHERE col_varchar_10 IS NULL');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname,\n                               '  CHANGE COLUMN pk pk INT(11) NOT NULL',\n                               ', DROP PRIMARY KEY',\n                               ', ADD PRIMARY KEY', indextype, '(pk,col_varchar_256)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n           set @ddl = CONCAT('ALTER TABLE ', dstdb, '.', tabname, ' PARTITION BY KEY(col_varchar_256)');\n           PREPARE stmt from @ddl;\n           EXECUTE stmt;\n        end if;\n\n       set @ddl = CONCAT('INSERT INTO ', dstdb, '.', tabname, \n                         ' SELECT * FROM ', srcdb, '.', tabname);\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n    end if;\n  until done end repeat;\n  close c;\nEND\n\\G\n\nDROP PROCEDURE IF EXISTS alterengine\\G\nCREATE PROCEDURE alterengine (db varchar(64), newengine varchar(64))\nBEGIN\n\n  declare tabname varchar(255);\n  declare done integer default 0;\n  declare c cursor for \n  SELECT table_name\n  FROM INFORMATION_SCHEMA.TABLES where table_schema = db;\n  declare continue handler for not found set done = 1;\n\n  open c;\n  \n  repeat\n    fetch c into tabname;\n    if not done then\n       set @ddl = CONCAT('ALTER TABLE ', db, '.', tabname, \n                         ' engine = ', newengine);\n       select @ddl;\n       PREPARE stmt from @ddl;\n       EXECUTE stmt;\n    end if;\n  until done end repeat;\n  close c;\nEND\n\\G\n\nCREATE PROCEDURE analyzedb(db varchar(64))\nBEGIN\n\n  declare tabname varchar(255);\n  declare done integer default 0;\n  declare cnt integer default 0;\n  declare c cursor for \n    SELECT table_name\n    FROM INFORMATION_SCHEMA.TABLES where table_schema = db;\n  declare continue handler for not found set done = 1;\n\n  set @ddl = 'ANALYZE TABLE ';\n  open c;\n  \n  repeat\n    fetch c into tabname;\n    if not done then\n       set cnt = cnt+1;\n       if cnt > 1 then\n         set @ddl = CONCAT(@ddl, ', ');\n       end if;\n       set @ddl = CONCAT(@ddl,  db, '.', tabname);\n    end if;\n  until done end repeat;\n  close c;\n\n  PREPARE stmt from @ddl;\n  EXECUTE stmt;\nEND\n\\G\n\nCALL copydb('${pre}_ndb', '${pre}_innodb', 'ndb')\\G\nCALL analyzedb('${pre}_ndb')\\G\n\n##CALL alterengine('${pre}_ndb', 'ndb')\\G\nDROP PROCEDURE copydb\\G\nDROP PROCEDURE alterengine\\G\nDROP PROCEDURE analyzedb\\G\nEOF\n\t$mysql -uroot test < /tmp/sproc.$$\n\trm -f /tmp/sproc.$$\nfi\n\ncheck_query(){\n    file=$1\n    no=$2\n    line=`expr $no \\* 3` || true\n    line=`expr $line + 3 + 2 + 1 + 1` || true\n    sql=`head -n $line $file | tail -n 1`\n\n    tmp=${opre}.$no.sql\n    cat > $tmp <<EOF\n--disable_warnings\n--disable_query_log\n--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\n$ecp\n--echo kalle\n--sorted_result\n--error 0,233,1242,4006\n$sql\n--exit\nEOF\n\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest ${pre}_innodb < $tmp >> ${opre}.$no.innodb.$i.txt\n    done\n\n    for t in 1\n    do\n\t$mysqltest ${pre}_ndb < $tmp >> ${opre}.$no.ndb.$i.txt\n    done\n\n    NDB_JOIN_PUSHDOWN=on\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest ${pre}_ndb < $tmp >> ${opre}.$no.ndbpush.$i.txt\n    done\n\n    cnt=`md5sum ${opre}.$no.*.txt | awk '{ print $1;}' | sort | uniq | wc -l`\n    if [ $cnt -ne 1 ]\n    then\n\techo -n \"$no \"\n\techo $sql >> ${opre}.failing.sql\n    fi\n\n    rm $tmp ${opre}.$no.*.txt\n}\n\nlocate_query (){\n    file=$1\n    rows=`cat $file | wc -l`\n    queries=`expr $rows - 4`\n    queries=`expr $queries / 3`\n    q=0\n    echo -n \"checking queries...\"\n    while [ $q -ne $queries ]\n    do\n\tcheck_query $file $q\n\tq=`expr $q + 1`\n    done\n    echo\n}\n\nrun_all() {\n    file=$1\n\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    echo \"- run innodb\"\n    $mysqltest ${pre}_innodb < $file > ${opre}_innodb.out\n    md5_innodb=`md5sum ${opre}_innodb.out | awk '{ print $1;}'`\n\n    echo \"- run ndb without push\"\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    $mysqltest ${pre}_ndb < $file > ${opre}_ndb.out\n    md5_ndb=`md5sum ${opre}_ndb.out | awk '{ print $1;}'`\n\n    echo \"- run ndb with push\"\n    NDB_JOIN_PUSHDOWN=on\n    export NDB_JOIN_PUSHDOWN\n    $mysqltest ${pre}_ndb < $file > ${opre}_ndbpush.out\n    md5_ndbpush=`md5sum ${opre}_ndbpush.out | awk '{ print $1;}'`\n\n    if [ \"$md5_innodb\" != \"$md5_ndb\" ] || [ \"$md5_innodb\" != \"$md5_ndbpush\" ]\n    then\n\techo \"md5 missmatch: $md5_innodb $md5_ndb $md5_ndbpush\"\n\techo \"locating failing query(s)\"\n\tlocate_query $file\n    fi\n\n    rm ${opre}_innodb.out ${opre}_ndb.out ${opre}_ndbpush.out\n}\n\ni=0\nwhile [ $i -ne $loops ]\ndo\n    i=`expr $i + 1`\n\n    echo \"** loop $i\"\n    us=\"$seed\" || true\n    if [ -z \"$us\" ]\n    then\n    \tus=`date '+%N'`\n    fi\n\n    echo \"- generating sql seed: $us\"\n\n    (\n\techo \"--disable_warnings\"\n\techo \"--disable_query_log\"\n\techo \"--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\"\n\techo \"$ecp\"\n\t${gensql} --seed=$us --queries=$queries --dsn=$dsn --grammar=$grammar|\n        awk '{ print \"--sorted_result\"; print \"--error 0,233,1242,4006\"; print; }'\n\techo \"--exit\"\n    ) > ${opre}_test.sql\n\n    run_all ${opre}_test.sql\n    rm ${opre}_test.sql\n    echo\ndone\n", "num_lines": 464}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nbase=\"`dirname $0`\"\nsource \"$base\"/parseargs.sh\n\necp=\"set optimizer_switch = 'engine_condition_pushdown=on';\"\n# Remove ONLY_FULL_GROUP_BY from sql_mode since the\n# syntax have been written with non aggregated columns in\n# the select list\ndisable_only_full_group_by=\"set sql_mode=(select replace(@@sql_mode,'ONLY_FULL_GROUP_BY',''));\"\n\ncheck_query(){\n    file=$1\n    no=$2\n    line=`expr $no \\* 3` || true\n    line=`expr $line + 3 + 2 + 1 + 1` || true\n    sql=`head -n $line $file | tail -1`\n\n    tmp=${opre}.$no.sql\n    cat > $tmp <<EOF\n--disable_warnings\n--disable_query_log\n--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\n$ecp\n$disable_only_full_group_by\n--echo kalle\n--sorted_result\n--error 0,233,1242,4006\n$sql\n--exit\nEOF\n\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest_exe ${innodb_db} < $tmp >> ${opre}.$no.innodb.$i.txt\n    done\n\n    for t in 1\n    do\n\t$mysqltest_exe ${ndb_db} < $tmp >> ${opre}.$no.ndb.$i.txt\n    done\n\n    NDB_JOIN_PUSHDOWN=on\n    export NDB_JOIN_PUSHDOWN\n    for t in 1\n    do\n\t$mysqltest_exe ${ndb_db} < $tmp >> ${opre}.$no.ndbpush.$i.txt\n    done\n\n    cnt=`$md5sum ${opre}.$no.*.txt | $awk_exe '{ print $1;}' | sort | uniq | wc -l`\n    if [ $cnt -ne 1 ]\n    then\n\techo -n \"$no \"\n\techo $sql >> ${opre}.failing.sql\n    fi\n\n    rm $tmp ${opre}.$no.*.txt\n}\n\nlocate_query (){\n    file=$1\n    rows=`cat $file | wc -l`\n    queries=`expr $rows - 4`\n    queries=`expr $queries / 3`\n    q=0\n    echo -n \"checking queries...\"\n    while [ $q -ne $queries ]\n    do\n\tcheck_query $file $q\n\tq=`expr $q + 1`\n    done\n    echo\n}\n\nrun_all() {\n    file=$1\n\n    tmpfiles=\"\"\n    NDB_JOIN_PUSHDOWN=off\n    export NDB_JOIN_PUSHDOWN\n    if [ `echo $mode | grep -c m` -ne 0 ]\n    then\n\techo \"- run innodb\"\n\tstart=`eval $getepochtime`\n\t$mysqltest_exe ${innodb_db} < $file > ${opre}_innodb.out\n\tstop=`eval $getepochtime`\n\techo \"  elapsed: `expr $stop - $start`s\"\n\ttmpfiles=\"$tmpfiles ${opre}_innodb.out\"\n    fi\n\n    if [ `echo $mode | grep -c nv` -ne 0 ]\n    then\n\techo \"- run ndb without push\"\n\tNDB_JOIN_PUSHDOWN=off\n\texport NDB_JOIN_PUSHDOWN\n\tstart=`eval $getepochtime`\n\t$mysqltest_exe ${ndb_db} < $file > ${opre}_ndb.out\n\tstop=`eval $getepochtime`\n\techo \"  elapsed: `expr $stop - $start`s\"\n\ttmpfiles=\"$tmpfiles ${opre}_ndb.out\"\n    fi\n\n    if [ `echo $mode | grep -c np` -ne 0 ]\n    then\n\techo \"- run ndb with push\"\n\tNDB_JOIN_PUSHDOWN=on\n\texport NDB_JOIN_PUSHDOWN\n\tstart=`eval $getepochtime`\n\t$mysqltest_exe ${ndb_db} < $file > ${opre}_ndbpush.out\n\tstop=`eval $getepochtime`\n\techo \"  elapsed: `expr $stop - $start`s\"\n\ttmpfiles=\"$tmpfiles ${opre}_ndbpush.out\"\n    fi\n\n    md5s=\"\"\n    for f in $tmpfiles\n    do\n\tmd5s=\"$md5s `$md5sum $f | $awk_exe '{ print $1;}'`\"\n    done\n\n    ###\n    # Check that they are all equal\n    check=\"\"\n    fail=\"\"\n    for s in $md5s\n    do\n\tif [ -z \"$check\" ]\n\tthen\n\t    check=\"$s\"\n\telif [ \"$check\" != \"$s\" ]\n\tthen\n\t    fail=\"yes\"\n\tfi\n    done\n\n    if [ \"$fail\" ]\n    then\n\techo \"md5 missmatch: $md5s\"\n\techo \"locating failing query(s)\"\n\tlocate_query $file\n    fi\n\n    rm -f $tmpfiles\n}\n\ni=0\nstoptime=\"\"\nif [ \"$runtime\" ]\nthen\n    stoptime=`eval $getepochtime`\n    stoptime=`expr $stoptime + $runtime`\n    loops=1000000\nfi\n\nwhile [ $i -ne $loops ]\ndo\n    i=`expr $i + 1`\n\n    echo \"** loop $i\"\n    us=\"$seed\" || true\n    if [ -z \"$us\" ]\n    then\n    \tus=`eval $getepochtime`\n    fi\n\n    echo \"- generating sql seed: $us queries: $queries\"\n\n    (\n\techo \"--disable_warnings\"\n\techo \"--disable_query_log\"\n\techo \"--eval set ndb_join_pushdown='\\$NDB_JOIN_PUSHDOWN';\"\n\techo \"$ecp\"\n\techo \"$disable_only_full_group_by\"\n\t${gensql} --seed=$us --queries=$queries --dsn=\"$dsn:database=${innodb_db}\" --grammar=$grammar | grep -v \"#\" |\n        $awk_exe '{ print \"--sorted_result\"; print \"--error 0,233,1242,4006\"; print; }'\n\techo \"--exit\"\n    ) > ${opre}_test.sql\n\n    run_all ${opre}_test.sql\n    rm ${opre}_test.sql\n    echo\n\n    if [ \"$stoptime\" ]\n    then\n\tif [ `eval $getepochtime` -ge $stoptime ]\n\tthen\n\t    break;\n\tfi\n    fi\ndone\n\nif [ -f \"${opre}.failing.sql\" ]\nthen\n    echo \"*** FAILING QUERIES ***\"\n    cat \"${opre}.failing.sql\"\n    exit 1\nfi\n", "num_lines": 217}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\ncores=`find result -name 'core*'`\nif [ \"$cores\" ]\nthen\n    for i in \"$cores\"\n    do\n\tatrt-backtrace.sh $i\n    done\nfi\n\n# Log files may be left between test runs so we need to keep some\n# state about what results we have seen.\n\nSTATEFILE=atrt-analyze-result.state\nOLDOK=0\n\n# Checksum of beginning of log file is used to determine if log file\n# is reused or not.  If it is reused the count of seen OK reports\n# are updated.\nif [ -f \"${STATEFILE}\" ] ; then\n  while read file oks chars sum ; do\n    chk=`dd 2>/dev/null if=\"$file\" bs=\"${chars}\" count=1 | sum`\n    if [ \"${chk}\" = \"${sum}\" ] ; then\n      OLDOK=`expr ${OLDOK} + ${oks}`\n    fi\n  done < \"${STATEFILE}\"\nfi\n\n# List of log files with result report.\nLOGFILES=`find result/ -name log.out -size +0c | xargs grep -l 'NDBT_ProgramExit: ' /dev/null`\n\n# Save the number of OK reports and checksum  per log file\nOK=0\nfor file in ${LOGFILES} ; do\n  oks=`grep -c 'NDBT_ProgramExit: .*OK' \"${file}\"`\n  if [ $oks -gt 0 ] ; then\n    OK=`expr ${OK} + ${oks}`\n    chars=`wc -c < \"${file}\" | awk '{ print $1 }'`\n    sum=`dd 2>/dev/null if=\"$file\" bs=\"${chars}\" count=1 | sum`\n    echo \"${file}\" \"${oks}\" \"${chars}\" \"${sum}\"\n  fi\ndone > \"${STATEFILE}\"\n\n# Succeed if found a new OK\n[ ${OK} -gt ${OLDOK} ]\n", "num_lines": 63}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# Does not work on Windows (gcc only)\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    exit\nfi\n\ncore=$1\nout=$2\n\nif [ ! -f \"$core\" ]\nthen\n    exit\nfi\n\nif [ -f `dirname $core`/env.sh ]\nthen\n    . `dirname $core`/env.sh\nfi\n\n#\n# gdb command file\n#\nbt=`dirname $core`/bt.gdb\necho \"thread apply all bt\" > $bt\necho \"quit\" >> $bt\n\n#\n# Fix output\n#\nif [ -z \"$out\" ]\nthen\n    out=`dirname $core`/bt.txt\nfi\noutarg=\">> $out 2>&1\"\nif [ \"$out\" = \"-\" ]\nthen\n    outarg=\"\"\nfi\n\n#\n# get binary\n#\ntmp=`echo ${core}.tmp`\ngdb -c $core -x $bt -q 2>&1 | grep \"Core was generated\" | awk '{ print $5;}' | sed 's!`!!' | sed `echo \"s/'\\.//\"` > $tmp\nexe=`cat $tmp`\nrm -f $tmp\n\nif [ -x \"$exe\" ]\nthen\n    echo \"*** $exe - $core\" >> $out\n    gdb -q -batch -x $bt -c $core $exe >> $out 2>&1\nelif [ -x \"`which $exe 2> /dev/null`\" ]\nthen\n    exe=`which $exe`\n    echo \"*** $exe - $core\" >> $out\n    gdb -q -batch -x $bt -c $core $exe >> $out 2>&1\nelse\n    echo \"*** $core : cant find exe: $exe\" >> $out\nfi\nrm -f $bt\n", "num_lines": 78}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nmkdir -p result\ncd result\nrm -rf *\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n  while [ $# -gt 0 ]\n  do\n    SAVE_IFS=$IFS\n    IFS=\":\"\n    declare -a ARR=\"($1)\"\n    IFS=$SAVE_IFS\n    DIR=`dirname \"${ARR[1]}\"`\n    REMOTE_DIR=`cygpath -u $DIR`\n    HOST=\"${ARR[0]}\"\n    rsync -a --exclude='BACKUP' --exclude='ndb_*_fs' \"$HOST:$REMOTE_DIR\" .\n    shift\n  done\nelse\n  while [ $# -gt 0 ]\n  do\n#\n# The below commented out lines can be used if we want to keep the file\n# as part of the result from a faulty test in autotest. The first line\n# also keeps the BACKUP files as part of a faulty test case. These lines\n# can be used in special autotest runs when a the file contents are\n# needed to debug issues in test cases.\n#\n#    rsync -a \"$1\" .\n#    rsync -a --exclude='BACKUP' \"$1\" .\n    rsync -a --exclude='BACKUP' --exclude='ndb_*_fs' \"$1\" .\n    shift\n  done\n\n  #\n  # clean tables...not to make results too large\n  #\n  lst=`find . -name '*.frm'`\n  if [ \"$lst\" ]\n  then\n \t  basename=`echo $i | sed 's!\\.frm!!'`\n\t  if [ \"$basename\" ]\n\t  then\n\t    rm -f $basename.*\n\t  fi\n  fi\n\nfi\n", "num_lines": 68}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nMACHINE=$1\nLOCAL_DIR=$2\nREMOTE_DIR=$3\nverbose=\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    verbose=1\nfi\n\nname=\"`uname -n | sed 's!\\..*!!g'`\"\n\n# Local copy\nif [ \"$MACHINE\" = \"$name\" -o \"$MACHINE\" = \"localhost\" ]\nthen\n    if [ \"$REMOTE_DIR\" = \"$LOCAL_DIR\" -o \"$REMOTE_DIR/\" = \"$LOCAL_DIR\" ]\n    then\n\tif [ \"$verbose\" ]\n\tthen\n\t    echo \"$0: Same directory on localhost. Skipping setup...\"\n\tfi\n    else\n\tif [ \"$verbose\" ]\n\tthen\n\t    echo \"$0: Local machine setup from '$REMOTE_DIR' to '$LOCAL_DIR'...\"\n\tfi\n\tcp -r \"$REMOTE_DIR\" \"$LOCAL_DIR\"\n    fi\n    exit 0;\nfi\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n    LOCAL_DIR=`cygpath -u $LOCAL_DIR`\n    REMOTE_DIR=`cygpath -u $REMOTE_DIR`\nfi\n\nset -e\nssh $MACHINE rm -rf $REMOTE_DIR\nssh $MACHINE mkdir -p $REMOTE_DIR\nrsync -a --delete --force --ignore-errors $LOCAL_DIR $MACHINE:$REMOTE_DIR\n", "num_lines": 59}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"autotest-boot.sh version 1.01\"\n\nDATE=`date '+%Y-%m-%d'`\nif [ `uname -s` != \"SunOS\" ]\nthen\n  if [ `uname | grep -ic cygwin || true` -ne 0 ]\n  then\n    HOST=`hostname`\n  else\n    HOST=`hostname -s`\n  fi\nelse\n  HOST=`hostname`\nfi\nexport DATE HOST\n\nset -e\n\necho \"`date` starting: $*\"\n\nverbose=0\ndo_clone=yes\nbuild=yes\n\npatch0=\npatch1=\ntag0=\ntag1=\nconf=\nclonename=\nextra_args=\nextra_clone0=\nextra_clone1=\ninstall_dir0=\ninstall_dir1=\nRUN=\n\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n                --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n                --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n                --version) echo $VERSION; exit;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n\t        --tag=*) tag0=`echo $1 | sed s/--tag=//`;;\n\t        --tag0=*) tag0=`echo $1 | sed s/--tag0=//`;;\n\t        --tag1=*) tag1=`echo $1 | sed s/--tag1=//`;;\n\t        --clonename=*) clonename=`echo $1 | sed s/--clonename=//`;;\n\t        --patch=*) patch=`echo $1 | sed s/--patch=//` ; patch0=\"$patch0$patch \" ; patch1=\"$patch1$patch \" ;;\n\t        --patch0=*) patch=`echo $1 | sed s/--patch0=//` ; patch0=\"$patch0$patch \" ;;\n\t        --patch1=*) patch=`echo $1 | sed s/--patch1=//` ; patch1=\"$patch1$patch \" ;;\n\t        --*) echo \"Unknown arg: $1\";;\n                *) RUN=\"$RUN $1\";;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\nif [ -z \"$conf\" ]\nthen\n\tif [ -f \"`pwd`/autotest.conf\" ]\n\tthen\n\t\tconf=\"`pwd`/autotest.conf\"\n\telif [ -f \"$HOME/autotest.conf\" ]\n\tthen\n\t\tconf=\"$HOME/autotest.conf\"\n\tfi\nfi\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: >$conf<\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"install_dir build_dir git_remote_repo git_local_repo\"\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\nif [ -z \"$clone1\" ]\nthen\n    install_dir0=$install_dir\nelse\n    install_dir0=$install_dir/0\n    install_dir1=$install_dir/1\nfi\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\ntrap \"rm -f $LOCK\" EXIT\n\n# You can add more to this path#\n################################\n\nif [ -z \"$tag0\" ]\nthen\n    dst_place0=${build_dir}/clone-$clone0-$DATE.$$\nelse\n    dst_place0=${build_dir}/clone-$tag0-$DATE.$$\n    extra_args=\"$extra_args --clone0=$tag0\"\n    extra_clone0=\"\"\nfi\n\nif [ -z \"$tag1\" ]\nthen\n    dst_place1=${build_dir}/clone1-$clone1-$DATE.$$\nelse\n    dst_place1=${build_dir}/clone1-$tag1-$DATE.$$\n    extra_args=\"$extra_args --clone1=$tag1\"\n    extra_clone1=\"\"\nfi\n\nif [ \"$clonename\" ]\nthen\n    extra_args=\"$extra_args --clonename=$clonename\"\nfi\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place0\n\tmkdir -p ${build_dir}\n\t\n\t# Can use local copy if clone_dir is set, to speed up\n\tif [ ! -z \"$clone_dir\" ]\n\tthen\n\t\tif [ -d \"$clone_dir/$clone0\" ]\n\t\tthen\n\t\t\techo \"Copying $clone_dir/$clone0 to $dst_place0\"\n\t\t\tcp -r $clone_dir/$clone0 $dst_place0\n\t\tfi\n\t\tif [ -d \"$clone_dir/$clone1\" ]\n\t\tthen\n\t\t\techo \"Copying $clone_dir/$clone1 to $dst_place1\"\n\t\t\tcp -r $clone_dir/$clone1 $dst_place1\n\t\tfi\n\telse\n# Comment out the next line if using git of version < 2.0\n# and ensure that the local repo is up to date.\n                git -C ${git_local_repo} fetch ${git_remote_repo}\n\n                git clone -b${clone0} ${git_local_repo} ${dst_place0}\n                [ ! -n \"${tag0}\" ] || git -C ${dst_place0} reset --hard ${tag0}\n\t\tfor patch in $patch0 ; do\n\t\t\t( cd $dst_place0 && patch -p0 ) < $patch\n\t\tdone\n                {\n# Comment out the next line if using git of version < 2.0 and replace with:\n#                 cd ${dst_place0}\n#                 git log -1\n                  git -C ${dst_place0} log -1\n\t          if [ $patch0 ] ; then echo patches: $patch0 ; cat $patch0 ; fi\n                } > $dst_place0/code0.txt\n\n                if [ \"$clone1\" ]\n\t       \tthen\n\t                rm -rf $dst_place1\n                        git clone -b${clone1} ${git_local_repo} ${dst_place1}\n                        [ ! -n \"${tag1}\" ] || git -C ${dst_place1} reset --hard ${tag1}\n\t                for patch in $patch1 ; do\n\t\t                ( cd $dst_place1 && patch -p0 ) < $patch\n\t                done\n                        {\n                          git -C ${dst_place1} log -1\n\t                  if [ $patch1 ] ; then echo patches: $patch1 ; cat $patch1 ; fi\n                        } > $dst_place1/code1.txt\n                fi\n\tfi\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\n\nfunction build_cluster()\n{\n    if grep -qc autotest storage/ndb/compile-cluster 2>/dev/null\n    then\n        storage/ndb/compile-cluster --autotest $*\n    else\n        BUILD/compile-ndb-autotest $*\n    fi\n}\n\nif [ \"$build\" ]\nthen\n    rm -rf $install_dir\n    p=`pwd`\n    if [ -z \"$clone1\" ]\n    then\n        cd $dst_place0\n        if [ `uname | grep -ic cygwin || true` -ne 0 ]\n        then\n            install_dir_dos=`cygpath -w $install_dir`\n            cmd /c cscript win/configure.js WITH_NDBCLUSTER_STORAGE_ENGINE --without-plugins=archive,blackhole,example,federated\n            cmd /c cmake -G \"Visual Studio 9 2008\" -DWITH_ERROR_INSERT=1 -DWITH_NDB_TEST=1 -DCMAKE_INSTALL_PREFIX=$install_dir_dos\n            cmd /c devenv.com MySql.sln /Build RelWithDebInfo\n            cmd /c devenv.com MySql.sln /Project INSTALL /Build\n        else\n\t    build_cluster --prefix=$install_dir0\n\t    make install\n\t    [ ! -f code0.txt ] || cp code0.txt $install_dir0/\n        fi\n    else\n\tcd $dst_place0\n\tbuild_cluster --prefix=$install_dir0\n\tmake install\n\t[ ! -f code0.txt ] || cp code0.txt $install_dir0/\n\t\n\tcd $dst_place1\n\tbuild_cluster --prefix=$install_dir1\n\tmake install\n\t[ ! -f code1.txt ] || cp code1.txt $install_dir1/\n    fi\n    cd $p\nfi\n\n\n################################\n# Start run script             #\n################################\n\nscript=$install_dir0/mysql-test/ndb/autotest-run.sh\nfor R in $RUN\ndo\n    sh -x $script $save_args --conf=$conf --run-dir=$install_dir --install-dir0=$install_dir0 --install-dir1=$install_dir1 --suite=$R --nolock $extra_args\ndone\n\nif [ \"$build\" ]\nthen\n    rm -rf $dst_place0\n\n    if [ \"$dst_place1\" ]\n    then\n\trm -rf $dst_place1\n    fi\nfi\n", "num_lines": 332}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"autotest-run.sh version 1.07\"\n\nDATE=`date '+%Y-%m-%d'`\nif [ `uname -s` != \"SunOS\" ]\nthen\n  if [ `uname | grep -ic cygwin || true` -ne 0 ]\n  then\n    HOST=`hostname`\n    # Returns windows CRLF\n    HOST=`echo $HOST | tr -d \"\\015\"`\n    echo \"Host: '$HOST'\"\n  else\n    HOST=`hostname -s`\n  fi\nelse\n  HOST=`hostname`\nfi\nexport DATE HOST\n\nset -e\nulimit -Sc unlimited\n\necho \"`date` starting: $*\"\n\nRSYNC_RSH=ssh\nexport RSYNC_RSH\n\nverbose=0\nreport=yes\nnolock=\nclonename=\nRUN=\"daily-basic\"\nconf=autotest.conf\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --verbose=*) verbose=`echo $1 | sed s/--verbose=//`;;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n                --version) echo $VERSION; exit;;\n\t        --suite=*) RUN=`echo $1 | sed s/--suite=//`;;\n\t        --run-dir=*) run_dir=`echo $1 | sed s/--run-dir=//`;;\n\t        --install-dir=*) install_dir=`echo $1 | sed s/--install-dir=//`;;\n\t        --install-dir0=*) install_dir0=`echo $1 | sed s/--install-dir0=//`;;\n\t        --install-dir1=*) install_dir1=`echo $1 | sed s/--install-dir1=//`;;\n\t        --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n\t        --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n\t        --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n\t        --nolock) nolock=true;;\n\t        --clonename=*) clonename=`echo $1 | sed s/--clonename=//`;;\n                --baseport=*) baseport_arg=\"$1\";;\n                --base-dir=*) base_dir=`echo $1 | sed s/--base-dir=//`;;\n                --clusters=*) clusters_arg=\"$1\";;\n                --site=*) site_arg=\"$1\";;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\n\ninstall_dir=${install_dir:-$install_dir0}\ninstall_dir0=${install_dir0:-$install_dir}\n\ninstall_dir_save=$install_dir0\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: $conf\"\n\texit\nfi\ninstall_dir0=$install_dir_save\n\nif [ -z \"$run_dir\" ]\nthen\n    if [ \"$install_dir1\" ]\n    then\n\techo \"--run-dir not specified but install_dir1 specified\"\n\techo \"giving up\"\n\texit\n    fi\n    run_dir=$install_dir0\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"target base_dir install_dir0 hosts\"\nif [ \"$report\" ]\nthen\n\tvars=\"$vars result_host result_path\"\nfi\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -z \"$nolock\" ]\nthen\n    if [ -f $LOCK ]\n    then\n\techo \"Lock file exists: $LOCK\"\n\texit 1\n    fi\n    echo \"$DATE $RUN\" > $LOCK\nfi\n\n####################################\n# Remove the lock file before exit #\n####################################\nif [ -z \"${nolock}\" ]\nthen\n    trap \"rm -f $LOCK\" EXIT\nfi\n\n\n###############################################\n# Check that all interesting files are present#\n###############################################\n\ntest_dir=$install_dir/mysql-test/ndb\n\n# Check if executables in $install_dir0 is executable at current\n# platform, they could be built for another kind of platform\nunset NDB_CPCC_HOSTS\nif ${install_dir}/bin/ndb_cpcc 2>/dev/null ; then\n  # Use atrt and ndb_cpcc from test build\n  atrt=\"${test_dir}/atrt\"\n  ndb_cpcc=\"${install_dir}/bin/ndb_cpcc\"\nelse\n  echo \"Note: Cross platform testing, atrt and ndb_cpcc is not used from test build\" >&2\n  atrt=`which atrt`\n  ndb_cpcc=`which ndb_cpcc`\nfi\n\ntest_file=$test_dir/$RUN-tests.txt\n\nif [ ! -f \"$test_file\" ]\nthen\n    echo \"Cant find testfile: $test_file\"\n    exit 1\nfi\n\nif [ ! -x \"$atrt\" ]\nthen\n    echo \"Cant find atrt binary at $atrt\"\n    exit 1\nfi\n\n############################\n# check ndb_cpcc fail hosts#\n############################\nfailed=`$ndb_cpcc $hosts | awk '{ if($1==\"Failed\"){ print;}}'`\nif [ \"$failed\" ]\nthen\n  echo \"Cant contact cpcd on $failed, exiting\"\n  exit 1\nfi\n\n#############################\n# Function for replacing the#\n# choose host with real host#\n# names. Note $$ = PID\t    #\n#############################\nchoose(){\n        SRC=$1\n        TMP1=/tmp/choose.$$\n        TMP2=/tmp/choose.$$.$$\n        shift\n\n        cp $SRC $TMP1\n        i=1\n        while [ $# -gt 0 ]\n        do\n                sed -e s,\"CHOOSE_host$i\",$1,g < $TMP1 > $TMP2\n                mv $TMP2 $TMP1\n                shift\n                i=`expr $i + 1`\n        done\n        cat $TMP1\n        rm -f $TMP1\n}\n\nchoose_conf(){\n    if [ -f $test_dir/conf-$1-$HOST.cnf ]\n\tthen\n\techo \"$test_dir/conf-$1-$HOST.cnf\"\n    elif [ -f $test_dir/conf-$1.cnf ]\n    then\n\techo \"$test_dir/conf-$1.cnf\"\n    elif [ -f $test_dir/conf-$HOST.cnf ]\n    then\n\techo \"$test_dir/conf-$HOST.cnf\"\n    else\n\techo \"Unable to find conf file looked for\" 1>&2\n\techo \"$test_dir/conf-$1-$HOST.cnf and\" 1>&2\n\techo \"$test_dir/conf-$HOST.cnf\" 1>&2\n\techo \"$test_dir/conf-$1.cnf\" 1>&2\n\texit\n    fi\n}\n\n#########################################\n# Count how many computers we have ready#\n#########################################\n\ncount_hosts(){\n    ch=\"CHOOSE_host\"\n    list=`grep $ch $1 | sed 's!,! !g'`\n    cnt=`for i in $list; do echo $i; done | grep $ch | sort | uniq | wc -l`\n    echo $cnt\n}\n\nconf=`choose_conf $RUN`\ncount=`count_hosts $conf`\navail=`echo $hosts | wc -w`\nif  [ $count -gt $avail ]\n    then\n    echo \"Not enough hosts\"\n    echo \"Needs: $count available: $avail ($avail_hosts)\"\n    exit 1\nfi\n\n###\n# Make directories needed\n\np=`pwd`\nrun_dir=$run_dir/run-$RUN-$clone0-$target\nres_dir=$base_dir/result-$RUN-$clone0-$target/$DATE\ntar_dir=$base_dir/saved-results\n\nmkdir -p $run_dir $res_dir $tar_dir\nrm -rf $res_dir/* $run_dir/*\n\n###\n#\n# Do sed substitiutions\n# \ncd $run_dir\nmkdir run\n\nif [ `uname | grep -ic cygwin || true` -ne 0 ]\nthen\n  run_dir=`cygpath -m $run_dir`\n  install_dir0=`cygpath -u $install_dir0`\n  if [ \"$install_dir1\" ]\n  then\n    install_dir1=`cygpath -u $install_dir1`\n  fi\n  test_dir=`cygpath -m $test_dir`\nfi\n\nchoose $conf $hosts > d.tmp.$$\nsed -e s,CHOOSE_dir,\"$run_dir/run\",g < d.tmp.$$ > my.cnf\n\nprefix=\"--prefix=$install_dir --prefix0=$install_dir0\"\nif [ -n \"$install_dir1\" ]\nthen\n    prefix=\"$prefix --prefix1=$install_dir1\"\nfi\n\n# If verbose level 0, use default verbose mode (1) for atrt anyway\n# otherwise it will not write test progress to log file\nif [ ${verbose} -gt 0 ] ; then\n  verbose_arg=--verbose=${verbose}\nfi\n\n# Setup configuration\n$atrt Cdq ${site_arg} ${clusters_arg} ${verbose_arg} $prefix my.cnf\n\n# Start...\nargs=\"\"\nargs=\"--report-file=report.txt\"\nargs=\"$args --log-file=log.txt\"\nargs=\"$args --testcase-file=$test_dir/$RUN-tests.txt\"\nargs=\"$args ${baseport_arg}\"\nargs=\"$args ${site_arg} ${clusters_arg}\"\nargs=\"$args $prefix\"\nargs=\"$args ${verbose_arg}\"\n$atrt $args my.cnf || echo \"ERROR: $?: $atrt $args my.cnf\"\n\n# Make tar-ball\n[ -f log.txt ] && mv log.txt $res_dir\n[ -f report.txt ] && mv report.txt $res_dir\n[ \"`find . -name 'result*'`\" ] && mv result* $res_dir\ncd $res_dir\n\necho \"date=$DATE\" > info.txt\necho \"suite=$RUN\" >> info.txt\necho \"clone=$clone0\" >> info.txt\necho \"arch=$target\" >> info.txt\necho \"host=$HOST\" >> info.txt\n[ -z \"${clusters_arg}\" ] || echo \"clusters=${clusters_arg/--clusters=/}\" >> info.txt\necho \"test_hosts='$hosts'\" >> info.txt\necho \"test_atrt_command='$atrt $args my.cnf'\" >> info.txt\nif [ \"$clone1\" ]\nthen\n    echo \"clone1=$clone1\" >> info.txt\n    [ ! -f $install_dir1/code1.txt ] || cp $install_dir1/code1.txt .\nfi\n[ ! -f $install_dir0/code0.txt ] || cp $install_dir0/code0.txt .\nif [ \"$clonename\" ]\nthen\n    echo \"clonename=$clonename\" >> info.txt\nelse\n    echo \"clonename=$clone0\" >> info.txt\nfi\nfor f in INFO_BIN INFO_SRC ; do\n  [ ! -f \"${install_dir0}/docs/${f}\" ] || cp \"${install_dir0}/docs/${f}\" \"${f}.0\"\n  [ ! -f \"${install_dir1}/docs/${f}\" ] || cp \"${install_dir1}/docs/${f}\" \"${f}.1\"\ndone\nfind . | xargs chmod ugo+r\n\n# Try to pack and transfer as much as possible\nset +e\n\ncd ..\np2=`pwd`\ncd ..\ntarfile=res.$RUN.$clone0.$target.$DATE.$HOST.$$.tgz\nif [ `uname -s` != \"SunOS\" ]\nthen\n    tar cfz $tar_dir/$tarfile `basename $p2`/$DATE\nelse\n    tarfile2=res.$RUN.$clone0.$target.$DATE.$HOST.$$.tar\n    tar cf $tar_dir/$tarfile2 `basename $p2`/$DATE\n    gzip -c $tar_dir/$tarfile2 > $tar_dir/$tarfile\n    rm -f $tar_dir/$tarfile2\nfi\n\nif [ \"$report\" ]\nthen\n    scp $tar_dir/$tarfile $result_host:$result_path/${tarfile}.upload\n    ssh $result_host mv $result_path/${tarfile}.upload $result_path/${tarfile}\nfi\n\ncd $p\nrm -rf $res_dir $run_dir\n", "num_lines": 397}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) 2009, 2010, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nset -e\n\nfiles=\"daily-basic-tests.txt daily-devel-tests.txt upgrade-tests.txt\"\n\ndie(){\n    echo \"error at $1 : $2\"\n    exit 1\n}\n\ncheck_state(){\n    if  [ $1 != $2 ]\n    then\n\tdie $3 $4\n    fi\n}\n\ncheck_file(){\n    file=$1\n    lineno=0\n    testcase=0\n\n    echo -n \"-- checking $file...\"\n    cat $file | awk '{ print \"^\" $0 \"$\";}' > /tmp/ct.$$\n    while read line\n    do\n\tlineno=$(expr $lineno + 1)\n\tif [ $(echo $line | grep -c \"^^#\") -ne 0 ]\n\tthen\n\t    continue\n\tfi\n\t\n\tcase \"$line\" in\n\t    ^max-time:*)\n\t\ttestcase=$(expr $testcase + 1);;\n\t    ^cmd:*)\n\t\tif [ $(echo $line | wc -w) -ne 2 ]\n\t\tthen\n\t\t    die $file $lineno\n\t\tfi\n\t\ttestcase=$(expr $testcase + 2);;\n\t    ^args:*)\n\t\ttestcase=$(expr $testcase + 4);;\n\t    ^type:*)\n\t\t;;\n\t    ^$) \n                if [ $testcase -ne 7 ]\n\t\tthen\n\t\t    die $file $lineno\n\t\telse\n\t\t    testcase=0\n\t\t    cnt=$(expr $cnt + 1)\n\t\tfi;;\n\t    *)\n\t        die $file $lineno\n\tesac\n   done < /tmp/ct.$$\n   rm -f /tmp/ct.$$\n   if [ $testcase -ne 0 ]\n   then\n   \techo \"Missing newline in end-of-file\"\n\tdie $file $lineno\n   fi\n\n   echo \"ok\"\n}\n   \nfor file in $files\ndo\n    check_file $file\ndone\n", "num_lines": 88}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nbaseport=\"\"\nbasedir=\"\"\nproc_no=1\nnode_id=1\n\nd_file=/tmp/d.$$\ndir_file=/tmp/dirs.$$\nconfig_file=/tmp/config.$$\ncluster_file=/tmp/cluster.$$\n\nadd_procs(){\n\ttype=$1; shift\n\twhile [ $# -ne 0 ]\n\tdo\n\t\tadd_proc $type $1\n\t\tshift\n\tdone\n}\n\nadd_proc (){\n\tcase $type in\n\tmgm)\n\t\techo \"$proc_no.ndb_mgmd\" >> $dir_file\n\t\techo \"[ndb_mgmd]\"        >> $config_file\n\t\techo \"Id: $node_id\"      >> $config_file\n\t\techo \"HostName: $2\"      >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tapi)\n\t\techo \"$proc_no.ndb_api\" >> $dir_file\n                echo \"[api]\"            >> $config_file\n                echo \"Id: $node_id\"     >> $config_file\n                echo \"HostName: $2\"     >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tndb)\n\t\techo \"$proc_no.ndbd\" >> $dir_file\n                echo \"[ndbd]\"        >> $config_file\n                echo \"Id: $node_id\"  >> $config_file\n                echo \"HostName: $2\"  >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tmysqld)\n\t\techo \"$proc_no.mysqld\" >> $dir_file\n                echo \"[mysqld]\"      >> $config_file\n                echo \"Id: $node_id\"    >> $config_file\n                echo \"HostName: $2\"    >> $config_file\n\t\tnode_id=`expr $node_id + 1`\n\t\t;;\n\tmysql)\n\t\techo \"$proc_no.mysql\" >> $dir_file\n\t\t;;\n\tesac\n\tproc_no=`expr $proc_no + 1`\n}\n\n\ncnf=/dev/null\ncat $1 | while read line\ndo\n\tcase $line in\n\tbaseport:*) baseport=`echo $line | sed 's/baseport[ ]*:[ ]*//g'`;;\n\tbasedir:*) basedir=`echo $line | sed 's/basedir[ ]*:[ ]*//g'`;;\n\tmgm:*) add_procs mgm `echo $line | sed 's/mgm[ ]*:[ ]*//g'`;;\n\tapi:*) add_procs api `echo $line | sed 's/api[ ]*:[ ]*//g'`;;\n\tndb:*) add_procs ndb `echo $line | sed 's/ndb[ ]*:[ ]*//g'`;;\n\tmysqld:*) add_procs mysqld `echo $line | sed 's/mysqld[ ]*:[ ]*//g'`;;\n\tmysql:*) add_procs mysql `echo $line | sed 's/mysql[ ]*:[ ]*//g'`;;\n\t\"-- cluster config\") \n\t\tif [ \"$cnf\" = \"/dev/null\" ]\n\t\t    then\n\t\t    cnf=$cluster_file\n\t\telse\n\t\t    cnf=/dev/null\n\t\tfi\n\t\tline=\"\";;\n\t    *) echo $line >> $cnf; line=\"\";;\n\tesac\n\tif [ \"$line\" ]\n\tthen\n\t    echo $line >> $d_file\n\tfi\ndone\n\ncat $dir_file | xargs mkdir -p\n\nif [ -f $cluster_file ]\n    then\n    cat $cluster_file $config_file >> /tmp/config2.$$\n    mv /tmp/config2.$$ $config_file\nfi\n\nfor i in `find . -type d -name '*.ndb_mgmd'`\n  do\n  cp $config_file $i/config.ini\ndone\n\nmv $d_file d.txt\nrm -f $config_file $dir_file $cluster_file\n", "num_lines": 118}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\nsrc_dir=$1\nrun=$2\ndate=$3\nsrc_file=$src_dir/report.txt\n\nif [ ! -f $src_dir/report.txt ]\nthen\n\techo \"$src_dir/report.txt is missing\"\n\texit 1\nfi\n\n###\n#\n# General html functions\ntrim(){\n\techo $*\n}\n\nheader(){\n    cat <<EOF\n<html><head><title>$*</title></head>\n<body>\nEOF\n}\n\nfooter(){\n    cat <<EOF\n</body></html>\nEOF\n}\n\nheading(){\n    h=$1; shift\n    cat <<EOF\n<h$h>$*</h$h>\nEOF\n}\n\ntable(){\n    echo \"<table $*>\"\n}\n\nend_table(){\n    echo \"</table>\"\n}\n\nrow(){\n    echo \"<tr>\"\n}\n\nend_row(){\n    echo \"</tr>\"\n}\n\nc_column(){\n    cat <<EOF\n<td valign=center align=center>$*</td>\nEOF\n}\n\nbold(){\n    cat <<EOF\n<b>$*</b>\nEOF\n}\ncolumn(){\n    cat <<EOF\n<td valign=center align=left>$*</td>\nEOF\n}\n\npara(){\n    cat <<EOF\n<p></p>\nEOF\n}\n\nhr(){\n    cat <<EOF\n<hr>\nEOF\n}\n\n# -- Verify\ntime_spec(){\n    # $1 - secs\n    _ts_tmp=$1\n    \n    _ts_s=`expr $_ts_tmp % 60`\n    _ts_tmp=`expr $_ts_tmp / 60`\n    \n    _ts_m=`expr $_ts_tmp % 60`\n    if [ $_ts_tmp -ge 60 ]\n    then\n\t_ts_tmp=`expr $_ts_tmp / 60`\n    else\n\t_ts_tmp=0\n    fi\n\n    a=3\n    _ts_h=$_ts_tmp\n\n    if [ $_ts_h -gt 0 ]\n    then\n\tret=\"${_ts_h}h\"\n    fi\n\n    [ $_ts_m -gt 0 ] || [ $_ts_h -gt 0 ] && ret=\"$ret${_ts_m}m\"\n\n    ret=\"$ret${_ts_s}s\"\n    echo $ret\n}\n\n### Main\n\nreport_file=$src_dir/report.html\nsummary_file=$src_dir/summary.html\n\npassed=0\nfailed=0\ntotal=0\n\npass(){\n\tpassed=`expr $passed + 1`\n}\n\nfail(){\n\tfailed=`expr $failed + 1`\n}\n\n(\n\theader Report $run $date\n\ttable \"border=1\"\n\trow\n\tcolumn `bold Test case`\n\tcolumn `bold Result`\n\tcolumn `bold Elapsed`\n\tcolumn `bold Log`\n\tend_row\n) > $report_file\n\ncat $src_file | while read line \ndo\n    \teval `echo $line | awk -F\";\" '{ printf(\"prg=\\\"%s\\\"; no=\\\"%s\\\"; res=\\\"%s\\\"; time=\\\"%s\\\"\", $1, $2, $3, $4); }'`\n\n\tprg=`trim $prg`\n\tno=`trim $no`\n\tres=`trim $res`\n\ttime=`trim $time`\n\tres_dir=\"<a href=\\\"result.$no/\\\">log</a>\"\n\n\tts=`time_spec $time`\n\tres_txt=\"\"\n\tcase $res in\n\t0) pass; res_txt=\"PASSED\";;\n\t*) fail; res_txt=\"FAILED\";;\n\tesac\n\n\tif [ ! -d \"$src_dir/result.$no\" ]; then res_dir=\"&nbsp;\"; fi\n\n\ttotal=`expr $total + $time`\n\n\t(\n\t\trow \n\t\tcolumn $prg\n\t\tcolumn $res_txt\n\t\tcolumn $ts \n\t\tcolumn $res_dir\n\t\tend_row\n\t) >> $report_file\n\n\t(\n        \trow\n        \tcolumn $run\n        \tcolumn $date\n        \tcolumn $passed\n        \tcolumn $failed\n        \tcolumn `time_spec $total`\n        \tcolumn \"<a href=\\\"result-$run/$date/report.html\\\">report</a>\"\n        \tcolumn \"<a href=\\\"result-$run/$date/log.txt\\\">log.txt</a>\"\n        \tend_row\n\t) > $summary_file\ndone\n\n(\n\tend_table\n\tfooter\n) >> $report_file\n\nexit 0\n", "num_lines": 209}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n# NAME\n#   make-index.sh\n#\n# SYNOPSIS\n#   make-index.sh [ -d <dir> ]\n#\n# DESCRIPTION\n#\n# OPTIONS\n#\n# EXAMPLES\n#   \n#   \n# ENVIRONMENT\n#   NDB_PROJ_HOME       Home dir for ndb\n#   \n# FILES\n#   $NDB_PROJ_HOME/lib/funcs.sh  general shell script functions\n#\n#\n# SEE ALSO\n#   \n# DIAGNOSTICTS\n#   \n# VERSION   \n#   1.0\n#   \n# AUTHOR\n#   Jonas Oreland\n#\n\nprogname=`basename $0`\nsynopsis=\"make-index.sh [ -d <dir> ]\"\n\n: ${NDB_PROJ_HOME:?}\t\t # If undefined, exit with error message\n\n: ${NDB_LOCAL_BUILD_OPTIONS:=--} # If undef, set to --. Keeps getopts happy.\n\t\t\t         # You may have to experiment a bit  \n                                 # to get quoting right (if you need it).\n\n\n. $NDB_PROJ_HOME/lib/funcs.sh    # Load some good stuff\n\n# defaults for options related variables \n#\n\ndst_dir=/home/autotest/html\nreport_date=`date '+%Y-%m-%d'`\nuniq_id=$$.$$\nverbose=yes\n\n# used if error when parsing the options environment variable\n#\nenv_opterr=\"options environment variable: <<$options>>\" \n\n# Option parsing, for the options variable as well as the command line.\n#\n# We want to be able to set options in an environment variable,\n# as well as on the command line. In order not to have to repeat\n# the same getopts information twice, we loop two times over the\n# getopts while loop. The first time, we process options from\n# the options environment variable, the second time we process \n# options from the command line.\n#\n# The things to change are the actual options and what they do.\n#\n#\n\nfor optstring in \"$options\"  \"\"\t     # 1. options variable  2. cmd line\ndo\n\n    while getopts q:s:R:d: i $optstring  # optstring empty => no arg => cmd line\n    do\n\tcase $i in\n\n\tq)\tverbose=\"\";;\t\t# echo important things\n\td)      dst_dir=$OPTARG;;       # Destination directory\n\t\\?)\tsyndie $env_opterr;;    # print synopsis and exit\n\n\tesac\n    done\n\n    [ -n \"$optstring\" ]  &&  OPTIND=1 \t# Reset for round 2, cmdline options\n\n    env_opterr= \t\t\t# Round 2 should not use the value\n\ndone\nshift `expr $OPTIND - 1`\n\ndst_dir=`abspath $dst_dir`\n\n###\n#\n# General html functions\nheader(){\n    cat <<EOF\n<html><head><title>$*</title></head>\n<body>\nEOF\n}\n\nfooter(){\n    cat <<EOF\n</body></html>\nEOF\n}\n\nheading(){\n    h=$1; shift\n    cat <<EOF\n<h$h>$*</h$h>\nEOF\n}\n\ntable(){\n    echo \"<table $*>\"\n}\n\nend_table(){\n    echo \"</table>\"\n}\n\nrow(){\n    echo \"<tr>\"\n}\n\nend_row(){\n    echo \"</tr>\"\n}\n\nc_column(){\n    cat <<EOF\n<td valign=center align=center>$*</td>\nEOF\n}\n\nbold(){\n    cat <<EOF\n<b>$*</b>\nEOF\n}\ncolumn(){\n    cat <<EOF\n<td valign=center align=left>$*</td>\nEOF\n}\n\npara(){\n    cat <<EOF\n<p></p>\nEOF\n}\n\nhr(){\n    cat <<EOF\n<hr>\nEOF\n}\n\ninc_summary() {\n\tgrep -v 'html>' $2 | grep -v body |  sed 's/href=\"/href=\"'$1'\\//g'\n}\n\n# --- option parsing done ---\n\n\n\n# -- Verify\ntrace \"Verifying arguments\"\n\n# --- option verifying done ---\n\n### Main\n\n# Re creating index\ntrace \"Creating index\"\n(\n    header \"Autotest super-duper index\"\n    heading 1 \"<center>Autotest super-duper index</center>\"\n    cat -E README.autotest | sed 's/\\$/<BR>/g'\n    echo \"<br>\" \n    echo \"Current <a href=\"crontab.current\">crontab</a> installed on mc01 running [\" `uname -a` \"]\"\n    hr\n\n    dirs=`find $dst_dir -name 'summary.*.html' -type f -maxdepth 2 -exec dirname {} \\; | sort -u`\n\n    dates=`find $dst_dir -name 'summary.*.html' -type f -maxdepth 2 -exec basename {} \\; | sed 's/summary\\.\\(.*\\)\\.html/\\1/g' | sort -u | sort -r`\n\n    echo \"<p align=center>\"\n\n#inline 5 latest reports\n    r_count=5\n    for d in $dates\n    do\n\tfor o in $dirs\n\tdo\n            o=`basename $o`\n            if [ -r $dst_dir/$o/summary.$d.html ]\n            then\n                inc_summary $o $dst_dir/$o/summary.$d.html\n\t\thr\n\n\t\tr_count=`expr $r_count - 1`\n\t\tif [ $r_count -eq 0 ]\n\t\tthen\n\t\t\tbreak 2\n\t\tfi\n            fi\n        done\n    done\n\t\n    table \"border=1\"\n    row\n    for i in $dirs\n    do\n\ti=`basename $i`\n\tcolumn `bold $i`\n    done\n    end_row\n\n\n    for d in $dates\n    do\n\trow\n\tfor o in $dirs\n\tdo\n\t    o=`basename $o`\n\t    if [ -r $dst_dir/$o/summary.$d.html ]\n\t    then\n\t\tcolumn \"<a href=$o/summary.$d.html>$d</a>\"\n\t    else\n\t\tcolumn \"\"\n\t    fi\n\tdone\n\tend_row\n    done\n    end_table\n    footer\n) > $dst_dir/index.html\n\nexit 0\n", "num_lines": 260}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2005, 2006 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"ndb-autotest.sh version 1.04\"\n\nDATE=`date '+%Y-%m-%d'`\nHOST=`hostname -s`\nexport DATE HOST\n\nset -e\nulimit -Sc unlimited\n\necho \"`date` starting: $*\"\n\nRSYNC_RSH=ssh\nexport RSYNC_RSH\n\nverbose=0\ndo_clone=yes\nbuild=yes\ndeploy=yes\nrun_test=yes\nconfig=yes\nreport=yes\n\nclone=5.0-ndb\nRUN=\"daily-basic daily-devel\"\nconf=autotest.conf\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --no-deploy) deploy=\"\";;\n                --no-test) run_test=\"\";;\n                --no-config) config=\"\";;\n                --no-report) report=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone=`echo $1 | sed s/--clone=//`;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n                --version) echo $VERSION; exit;;\n                *) RUN=$*;;\n        esac\n        shift\ndone\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: $conf\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"target base_dir src_clone_base install_dir build_dir hosts configure\"\nif [ \"$report\" ]\nthen\n\tvars=\"$vars result_host result_path\"\nfi\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\nsrc_clone=$src_clone_base-$clone\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\nif [ `uname -s` != \"SunOS\" ]\nthen\n\ttrap \"rm -f $LOCK\" ERR\nfi\n\n# You can add more to this path#\n################################\n\ndst_place=${build_dir}/clone-mysql-$clone-$DATE\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place\n\tbk clone  $src_clone $dst_place\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\n\nif [ \"$build\" ]\nthen\n\tcd $dst_place\n        rm -rf $install_dir/*\n\tif [ -x BUILD/autorun.sh ]\n\tthen\n\t    ./BUILD/autorun.sh\n\telse\n\t    aclocal; autoheader; autoconf; automake\n\t    if [ -d storage ]\n\t    then\n\t\t(cd storage/innobase; aclocal; autoheader; autoconf; automake)\n\t    else\n\t\t(cd innobase; aclocal; autoheader; autoconf; automake)\n\t    fi\n\tfi\n\teval $configure --prefix=$install_dir\n\tmake\n\tmake install\n\t(cd $install_dir; ./bin/mysql_install_db) # This will be rsynced to all\nfi\n\n################################\n# check script version. If the #\n# version is old, replace it   #\n# and restart\t\t       #\n################################\n\nscript=$install_dir/mysql-test/ndb/ndb-autotest.sh\nif [ -x $script ]\nthen\n\t$script --version > /tmp/version.$$\nelse\n\techo $VERSION > /tmp/version.$$\nfi\t\nmatch=`grep -c \"$VERSION\" /tmp/version.$$ | xargs echo`\nrm -f /tmp/version.$$\nif [ $match -eq 0 ]\nthen\n\techo \"Incorrect script version...restarting\"\n\tcp $install_dir/mysql-test/ndb/ndb-autotest.sh /tmp/at.$$.sh\n\trm -rf $install_dir $dst_place\n\tsh /tmp/at.$$.sh $save_args\n\texit\nfi\n\n###############################################\n# Check that all interesting files are present#\n###############################################\n\ntest_dir=$install_dir/mysql-test/ndb\natrt=$test_dir/atrt\nhtml=$test_dir/make-html-reports.sh\nmkconfig=$install_dir/mysql-test/ndb/make-config.sh\n\n##########################\n#Setup bin and test paths#\n##########################\n\nPATH=$install_dir/bin:$test_dir:$PATH\nexport PATH\n\n###########################\n# This will filter out all#\n# the host that did not   #\n# respond. Called below   #\n###########################\n\nfilter(){\n\tneg=$1\n\tshift\n\twhile [ $# -gt 0 ]\n\tdo\n\t\tif [ `grep -c $1 $neg | xargs echo` -eq 0 ] ; then echo $1; fi\n\t\tshift\n\tdone\n}\n\n############################\n# check ndb_cpcc fail hosts#\n############################\nndb_cpcc $hosts | awk '{ if($1==\"Failed\"){ print;}}' > /tmp/failed.$DATE\nfilter /tmp/failed.$DATE $hosts > /tmp/hosts.$DATE\nhosts=`cat /tmp/hosts.$DATE` \n\n#############################\n# Push bin and test to hosts#\n#############################\n\nif [ \"$deploy\" ]\nthen\n    for i in $hosts\n    do\n      rsync -a --delete --force --ignore-errors $install_dir/ $i:$install_dir\n      ok=$?\n      if [ $ok -ne 0 ]\n\t  then\n\t  echo \"$i failed during rsync, excluding\"\n\t  echo $i >> /tmp/failed.$DATE\n      fi\n    done\nfi\n\n###\n# handle scp failed hosts\n#\nfilter /tmp/failed.$DATE $hosts > /tmp/hosts.$DATE\nhosts=`cat /tmp/hosts.$DATE` \ncat /tmp/failed.$DATE > /tmp/filter_hosts.$$\n\n#############################\n# Function for replacing the#\n# choose host with real host#\n# names. Note $$ = PID\t    #\n#############################\nchoose(){\n        SRC=$1\n        TMP1=/tmp/choose.$$\n        TMP2=/tmp/choose.$$.$$\n        shift\n\n        cp $SRC $TMP1\n        i=1\n        while [ $# -gt 0 ]\n        do\n                sed -e s,\"CHOOSE_host$i\",$1,g < $TMP1 > $TMP2\n                mv $TMP2 $TMP1\n                shift\n                i=`expr $i + 1`\n        done\n        cat $TMP1\n        rm -f $TMP1\n}\n\nchoose_conf(){\n    if [ -f $test_dir/conf-$1-$HOST.txt ]\n\tthen\n\techo \"$test_dir/conf-$1-$HOST.txt\"\n    elif [ -f $test_dir/conf-$1.txt ]\n    then\n\techo \"$test_dir/conf-$1.txt\"\n    elif [ -f $test_dir/conf-$HOST.txt ]\n\techo \"$test_dir/conf-$HOST.txt\"\n    else\n\techo \"Unable to find conf file looked for\" 1>&2\n\techo \"$test_dir/conf-$1-$HOST.txt and\" 1>&2\n\techo \"$test_dir/conf-$HOST.txt\" 1>&2\n\techo \"$test_dir/conf-$1.txt\" 1>&2\n\texit\n    fi\n}\n######################################\n# Starts ATRT and gives it the right #\n# command line options. after it     #\n# Gathers results and moves them     #\n######################################\nstart(){\n\trm -rf report.txt result* log.txt\n\t$atrt -v -v -r -R --log-file=log.txt --testcase-file=$test_dir/$2-tests.txt &\n\tpid=$!\n\techo $pid > run.pid\n\twait $pid\n\trm run.pid\n\t[ -f log.txt ] && mv log.txt $3\n\t[ -f report.txt ] && mv report.txt $3\n\t[ \"`find . -name 'result*'`\" ] && mv result* $3\n\tcd $3\n\tsh $html . $1 $DATE\n\tcd ..\n\tp2=`pwd`\n\tcd ..\n\tif [ \"$report\" ]\n\tthen\n\t\ttar cfz /tmp/res.$2.$$.tgz `basename $p2`/$DATE\n\t\tscp /tmp/res.$2.$$.tgz \\\n\t\t    $result_host:$result_path/res.$DATE.$HOST.$2.$$.tgz\n\t\tif [ $? -eq 0 ]\n\t\tthen\n\t\t    rm -f /tmp/res.$2.$$.tgz\n\t\tfi\n\tfi\n}\n\n#########################################\n# Count how many computers we have ready#\n#########################################\n\ncount_hosts(){\n    cnt=`grep \"CHOOSE_host\" $1 | awk '{for(i=1; i<=NF;i++) \\\n    if(index($i, \"CHOOSE_host\") > 0) print $i;}' | sort | uniq | wc -l`\n    echo $cnt\n}\n#######################################################\n# Calls: Choose                                       #\n#\t Choose_host                                  #\n#        Count_host                                   #\n#\t start                                        #\n# for each directory in the $RUN variable\t      #\n#######################################################\n\np=`pwd`\nfor dir in $RUN\ndo\n\techo \"Fixing hosts for $dir\"\n\n\trun_dir=$base_dir/run-$dir-mysql-$clone-$target\n\tres_dir=$base_dir/result-$dir-mysql-$clone-$target/$DATE\n\n\tmkdir -p $run_dir $res_dir\n\trm -rf $res_dir/*\n\tcd $run_dir\n\n\tif [ \"$config\" ]\n\tthen\n\t    rm -rf $run_dir/*\n\n\t    conf=`choose_conf $dir`\n\t    count=`count_hosts $conf`\n\t    avail_hosts=`filter /tmp/filter_hosts.$$ $hosts`\n\t    avail=`echo $avail_hosts | wc -w`\n\t    if  [ $count -gt $avail ]\n\t    then\n\t\techo \"Not enough hosts\"\n\t\techo \"Needs: $count available: $avail ($avail_hosts)\"\n\t\tbreak;\n\t    fi\n\n\t    run_hosts=`echo $avail_hosts| \\\n                       awk '{for(i=1;i<='$count';i++)print $i;}'`\n\t    echo $run_hosts >> /tmp/filter_hosts.$$\t\n\t\n\t    choose $conf $run_hosts > d.tmp.$$\n            sed -e s,CHOOSE_dir,\"$install_dir\",g < d.tmp.$$ > d.tmp\n\t    $mkconfig d.tmp\n\tfi\n\t\n\tif [ \"$run_test\" ]\n\tthen\n\t    start $dir-mysql-$clone-$target $dir $res_dir &\n\tfi\ndone\ncd $p\nrm /tmp/filter_hosts.$$\n\nwait\n\nrm -f $LOCK\n", "num_lines": 423}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA\n\n#############################################################\n# This script created by Jonas does the following\t    #\n# Cleans up clones and pevious builds, pulls new clones,    #\n# builds, deploys, configures the tests and launches ATRT   #\n#############################################################\n\n###############\n#Script setup #\n##############\n\nsave_args=$*\nVERSION=\"upgrade-boot.sh version 1.00\"\n\nDATE=`date '+%Y-%m-%d'`\nHOST=`hostname -s`\nexport DATE HOST\n\nset -e\n\necho \"`date` starting: $*\"\n\nverbose=0\ndo_clone=yes\nbuild=yes\n\ntag0=\ntag1=\nconf=\nextra_args=\nextra_clone=\nLOCK=$HOME/.autotest-lock\n\n############################\n# Read command line entries#\n############################\n\nwhile [ \"$1\" ]\ndo\n        case \"$1\" in\n                --no-clone) do_clone=\"\";;\n                --no-build) build=\"\";;\n                --verbose) verbose=`expr $verbose + 1`;;\n                --clone=*) clone0=`echo $1 | sed s/--clone=//`;;\n                --clone0=*) clone0=`echo $1 | sed s/--clone0=//`;;\n                --clone1=*) clone1=`echo $1 | sed s/--clone1=//`;;\n                --version) echo $VERSION; exit;;\n                --conf=*) conf=`echo $1 | sed s/--conf=//`;;\n\t        --tag=*) tag0=`echo $1 | sed s/--tag=//`;;\n\t        --tag0=*) tag0=`echo $1 | sed s/--tag0=//`;;\n\t        --tag1=*) tag1=`echo $1 | sed s/--tag1=//`;;\n\t        --*) echo \"Unknown arg: $1\";;\n                *) RUN=$*;;\n        esac\n        shift\ndone\n\nif [ -z \"$clone1\" ]\nthen\n\tclone1=$clone0\nfi\n\nif [ -z \"$tag0\" ]\nthen\n\techo \"No tag0 specified\"\n\texit\nfi\n\nif [ -z \"$tag1\" ]\nthen\n        echo \"No tag1 specified\"\n        exit\nfi\n\n#################################\n#Make sure the configfile exists#\n#if it does not exit. if it does#\n# (.) load it\t\t\t# \n#################################\nif [ -z \"$conf\" ]\nthen\n\tif [ -f \"`pwd`/autotest.conf\" ]\n\tthen\n\t\tconf=\"`pwd`/autotest.conf\"\n\telif [ -f \"$HOME/autotest.conf\" ]\n\tthen\n\t\tconf=\"$HOME/autotest.conf\"\n\tfi\nfi\n\nif [ -f $conf ]\nthen\n\t. $conf\nelse\n\techo \"Can't find config file: >$conf<\"\n\texit\nfi\n\n###############################\n# Validate that all interesting\n#   variables where set in conf\n###############################\nvars=\"src_clone_base install_dir build_dir\"\nfor i in $vars\ndo\n  t=`echo echo \\\\$$i`\n  if [ -z \"`eval $t`\" ]\n  then\n      echo \"Invalid config: $conf, variable $i is not set\"\n      exit\n  fi\ndone\n\n###############################\n#Print out the enviroment vars#\n###############################\n\nif [ $verbose -gt 0 ]\nthen\n\tenv\nfi\n\n####################################\n# Setup the lock file name and path#\n# Setup the clone source location  #\n####################################\n\nsrc_clone0=${src_clone_base}${clone0}\nsrc_clone1=${src_clone_base}${clone1}\n\n#######################################\n# Check to see if the lock file exists#\n# If it does exit. \t\t      #\n#######################################\n\nif [ -f $LOCK ]\nthen\n\techo \"Lock file exists: $LOCK\"\n\texit 1\nfi\n\n#######################################\n# If the lock file does not exist then#\n# create it with date and run info    #\n#######################################\n\necho \"$DATE $RUN\" > $LOCK\n\n#############################\n#If any errors here down, we#\n# trap them, and remove the #\n# Lock file before exit     #\n#############################\ntrap \"rm -f $LOCK\" EXIT\n\n# You can add more to this path#\n################################\n\ndst_place0=${build_dir}/clone-$tag0-$DATE.$$\ndst_place1=${build_dir}/clone-$tag1-$DATE.$$\n\n#########################################\n# Delete source and pull down the latest#\n#########################################\n\nif [ \"$do_clone\" ]\nthen\n\trm -rf $dst_place0 $dst_place1\n\tif [ `echo $src_clone0 | grep -c 'file:\\/\\/'` = 1 ]\n\tthen\n\t\tbk clone -l -r$tag0 $src_clone0 $dst_place0\n\telse\n\t\tbk clone -r$tag0 $src_clone0 $dst_place0\n\tfi\n\n        if [ `echo $src_clone1 | grep -c 'file:\\/\\/'` = 1 ]\n        then\n                bk clone -l -r$tag1 $src_clone1 $dst_place1\n        else\n                bk clone -r$tag1 $src_clone1 $dst_place1\n        fi\nfi\n\n##########################################\n# Build the source, make installs, and   #\n# create the database to be rsynced\t #\n##########################################\nfunction build_cluster()\n{\n    if [ -x storage/ndb/compile-cluster ]\n    then\n        storage/ndb/compile-cluster --autotest $*\n    else\n        BUILD/compile-ndb-autotest $*\n    fi\n}\n\ninstall_dir0=$install_dir/$tag0\ninstall_dir1=$install_dir/$tag1\nif [ \"$build\" ]\nthen\n\tcd $dst_place0\n        rm -rf $install_dir0\n        build_cluster --prefix=$install_dir0\n\tmake install\n\n\tcd $dst_place1\n\trm -rf $install_dir1\n        build_cluster --prefix=$install_dir1\n\tmake install\n        fi\nfi\n\n\n################################\n# Start run script             #\n################################\n\nscript=$install_dir1/mysql-test/ndb/upgrade-run.sh\n$script $save_args --conf=$conf --install-dir=$install_dir --suite=$RUN --nolock $extra_args\n\nif [ \"$build\" ]\nthen\n    rm -rf $dst_place0 $dst_place1\nfi\n", "num_lines": 242}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "# The log file name and location can be set in\n# /etc/my.cnf by setting the \"log-error\" option\n# in either [mysqld] or [mysqld_safe] section as\n# follows:\n#\n# [mysqld]\n# log-error=@localstatedir@/mysqld.log\n#\n# In case the root user has a password, then you\n# have to create a /root/.my.cnf configuration file\n# with the following content:\n#\n# [mysqladmin]\n# password = <secret> \n# user= root\n#\n# where \"<secret>\" is the password. \n#\n# ATTENTION: The /root/.my.cnf file should be readable\n# _ONLY_ by root !\n\n@localstatedir@/mysqld.log {\n        # create 600 mysql mysql\n        notifempty\n        daily\n        rotate 5\n        missingok\n        compress\n    postrotate\n\t# just if mysqld is really running\n\tif test -x @bindir@/mysqladmin && \\\n\t   @bindir@/mysqladmin ping &>/dev/null\n\tthen\n\t   @bindir@/mysqladmin flush-logs\n\tfi\n    endscript\n}\n", "num_lines": 38}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Abandoned 1996 TCX DataKonsult AB & Monty Program KB & Detron HB\n# This file is public domain and comes with NO WARRANTY of any kind\n\n# MySQL daemon start/stop script.\n\n# Usually this is put in /etc/init.d (at least on machines SYSV R4 based\n# systems) and linked to /etc/rc3.d/S99mysql and /etc/rc0.d/K01mysql.\n# When this is done the mysql server will be started when the machine is\n# started and shut down when the systems goes down.\n\n# Comments to support chkconfig on RedHat Linux\n# chkconfig: 2345 64 36\n# description: A very fast and reliable SQL database engine.\n\n# Comments to support LSB init script conventions\n### BEGIN INIT INFO\n# Provides: mysql\n# Required-Start: $local_fs $network $remote_fs\n# Should-Start: ypbind nscd ldap ntpd xntpd\n# Required-Stop: $local_fs $network $remote_fs\n# Default-Start:  2 3 4 5\n# Default-Stop: 0 1 6\n# Short-Description: start and stop MySQL\n# Description: MySQL is a very fast and reliable SQL database engine.\n### END INIT INFO\n \n# If you install MySQL on some other places than @prefix@, then you\n# have to do one of the following things for this script to work:\n#\n# - Run this script from within the MySQL installation directory\n# - Create a /etc/my.cnf file with the following information:\n#   [mysqld]\n#   basedir=<path-to-mysql-installation-directory>\n# - Add the above to any other configuration file (for example ~/.my.ini)\n#   and copy my_print_defaults to /usr/bin\n# - Add the path to the mysql-installation-directory to the basedir variable\n#   below.\n#\n# If you want to affect other MySQL variables, you should make your changes\n# in the /etc/my.cnf, ~/.my.cnf or other MySQL configuration files.\n\n# If you change base dir, you must also change datadir. These may get\n# overwritten by settings in the MySQL configuration files.\n\nbasedir=\ndatadir=\n\n# Default value, in seconds, afterwhich the script should timeout waiting\n# for server start. \n# Value here is overriden by value in my.cnf. \n# 0 means don't wait at all\n# Negative numbers mean to wait indefinitely\nservice_startup_timeout=900\n\n# Lock directory for RedHat / SuSE.\nlockdir='/var/lock/subsys'\nlock_file_path=\"$lockdir/mysql\"\n\n# The following variables are only set for letting mysql.server find things.\n\n# Set some defaults\nmysqld_pid_file_path=\nif test -z \"$basedir\"\nthen\n  basedir=@prefix@\n  bindir=@bindir@\n  if test -z \"$datadir\"\n  then\n    datadir=@localstatedir@\n  fi\n  sbindir=@sbindir@\n  libexecdir=@libexecdir@\nelse\n  bindir=\"$basedir/bin\"\n  if test -z \"$datadir\"\n  then\n    datadir=\"$basedir/data\"\n  fi\n  sbindir=\"$basedir/sbin\"\n  libexecdir=\"$basedir/libexec\"\nfi\n\n# datadir_set is used to determine if datadir was set (and so should be\n# *not* set inside of the --basedir= handler.)\ndatadir_set=\n\n#\n# Use LSB init script functions for printing messages, if possible\n#\nlsb_functions=\"/lib/lsb/init-functions\"\nif test -f $lsb_functions ; then\n  . $lsb_functions\nelse\n  log_success_msg()\n  {\n    echo \" SUCCESS! $@\"\n  }\n  log_failure_msg()\n  {\n    echo \" ERROR! $@\"\n  }\nfi\n\nPATH=\"/sbin:/usr/sbin:/bin:/usr/bin:$basedir/bin\"\nexport PATH\n\nmode=$1    # start or stop\n\n[ $# -ge 1 ] && shift\n\n\nother_args=\"$*\"   # uncommon, but needed when called from an RPM upgrade action\n           # Expected: \"--skip-networking --skip-grant-tables\"\n           # They are not checked here, intentionally, as it is the resposibility\n           # of the \"spec\" file author to give correct arguments only.\n\ncase `echo \"testing\\c\"`,`echo -n testing` in\n    *c*,-n*) echo_n=   echo_c=     ;;\n    *c*,*)   echo_n=-n echo_c=     ;;\n    *)       echo_n=   echo_c='\\c' ;;\nesac\n\nparse_server_arguments() {\n  for arg do\n    case \"$arg\" in\n      --basedir=*)  basedir=`echo \"$arg\" | sed -e 's/^[^=]*=//'`\n                    bindir=\"$basedir/bin\"\n\t\t    if test -z \"$datadir_set\"; then\n\t\t      datadir=\"$basedir/data\"\n\t\t    fi\n\t\t    sbindir=\"$basedir/sbin\"\n\t\t    libexecdir=\"$basedir/libexec\"\n        ;;\n      --datadir=*)  datadir=`echo \"$arg\" | sed -e 's/^[^=]*=//'`\n\t\t    datadir_set=1\n\t;;\n      --pid-file=*) mysqld_pid_file_path=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n      --service-startup-timeout=*) service_startup_timeout=`echo \"$arg\" | sed -e 's/^[^=]*=//'` ;;\n    esac\n  done\n}\n\nwait_for_pid () {\n  verb=\"$1\"           # created | removed\n  pid=\"$2\"            # process ID of the program operating on the pid-file\n  pid_file_path=\"$3\" # path to the PID file.\n\n  i=0\n  avoid_race_condition=\"by checking again\"\n\n  while test $i -ne $service_startup_timeout ; do\n\n    case \"$verb\" in\n      'created')\n        # wait for a PID-file to pop into existence.\n        test -s \"$pid_file_path\" && i='' && break\n        ;;\n      'removed')\n        # wait for this PID-file to disappear\n        test ! -s \"$pid_file_path\" && i='' && break\n        ;;\n      *)\n        echo \"wait_for_pid () usage: wait_for_pid created|removed pid pid_file_path\"\n        exit 1\n        ;;\n    esac\n\n    # if server isn't running, then pid-file will never be updated\n    if test -n \"$pid\"; then\n      if kill -0 \"$pid\" 2>/dev/null; then\n        :  # the server still runs\n      else\n        # The server may have exited between the last pid-file check and now.  \n        if test -n \"$avoid_race_condition\"; then\n          avoid_race_condition=\"\"\n          continue  # Check again.\n        fi\n\n        # there's nothing that will affect the file.\n        log_failure_msg \"The server quit without updating PID file ($pid_file_path).\"\n        return 1  # not waiting any more.\n      fi\n    fi\n\n    echo $echo_n \".$echo_c\"\n    i=`expr $i + 1`\n    sleep 1\n\n  done\n\n  if test -z \"$i\" ; then\n    log_success_msg\n    return 0\n  else\n    log_failure_msg\n    return 1\n  fi\n}\n\n# Get arguments from the my.cnf file,\n# the only group, which is read from now on is [mysqld]\nif test -x \"$bindir/my_print_defaults\";  then\n  print_defaults=\"$bindir/my_print_defaults\"\nelse\n  # Try to find basedir in /etc/my.cnf\n  conf=/etc/my.cnf\n  print_defaults=\n  if test -r $conf\n  then\n    subpat='^[^=]*basedir[^=]*=\\(.*\\)$'\n    dirs=`sed -e \"/$subpat/!d\" -e 's//\\1/' $conf`\n    for d in $dirs\n    do\n      d=`echo $d | sed -e 's/[ \t]//g'`\n      if test -x \"$d/bin/my_print_defaults\"\n      then\n        print_defaults=\"$d/bin/my_print_defaults\"\n        break\n      fi\n    done\n  fi\n\n  # Hope it's in the PATH ... but I doubt it\n  test -z \"$print_defaults\" && print_defaults=\"my_print_defaults\"\nfi\n\n#\n# Read defaults file from 'basedir'.   If there is no defaults file there\n# check if it's in the old (depricated) place (datadir) and read it from there\n#\n\nextra_args=\"\"\nif test -r \"$basedir/my.cnf\"\nthen\n  extra_args=\"-e $basedir/my.cnf\"\nfi\n\nparse_server_arguments `$print_defaults $extra_args mysqld server mysql_server mysql.server`\n\n#\n# Set pid file if not given\n#\nif test -z \"$mysqld_pid_file_path\"\nthen\n  mysqld_pid_file_path=$datadir/`@HOSTNAME@`.pid\nelse\n  case \"$mysqld_pid_file_path\" in\n    /* ) ;;\n    * )  mysqld_pid_file_path=\"$datadir/$mysqld_pid_file_path\" ;;\n  esac\nfi\n\ncase \"$mode\" in\n  'start')\n    # Start daemon\n\n    # Safeguard (relative paths, core dumps..)\n    cd $basedir\n\n    echo $echo_n \"Starting MySQL\"\n    if test -x $bindir/mysqld_safe\n    then\n      # Give extra arguments to mysqld with the my.cnf file. This script\n      # may be overwritten at next upgrade.\n      $bindir/mysqld_safe --datadir=\"$datadir\" --pid-file=\"$mysqld_pid_file_path\" $other_args >/dev/null &\n      wait_for_pid created \"$!\" \"$mysqld_pid_file_path\"; return_value=$?\n\n      # Make lock for RedHat / SuSE\n      if test -w \"$lockdir\"\n      then\n        touch \"$lock_file_path\"\n      fi\n\n      exit $return_value\n    else\n      log_failure_msg \"Couldn't find MySQL server ($bindir/mysqld_safe)\"\n    fi\n    ;;\n\n  'stop')\n    # Stop daemon. We use a signal here to avoid having to know the\n    # root password.\n\n    if test -s \"$mysqld_pid_file_path\"\n    then\n      # signal mysqld_safe that it needs to stop\n      touch \"$mysqld_pid_file_path.shutdown\"\n\n      mysqld_pid=`cat \"$mysqld_pid_file_path\"`\n\n      if (kill -0 $mysqld_pid 2>/dev/null)\n      then\n        echo $echo_n \"Shutting down MySQL\"\n        kill $mysqld_pid\n        # mysqld should remove the pid file when it exits, so wait for it.\n        wait_for_pid removed \"$mysqld_pid\" \"$mysqld_pid_file_path\"; return_value=$?\n      else\n        log_failure_msg \"MySQL server process #$mysqld_pid is not running!\"\n        rm \"$mysqld_pid_file_path\"\n      fi\n\n      # Delete lock for RedHat / SuSE\n      if test -f \"$lock_file_path\"\n      then\n        rm -f \"$lock_file_path\"\n      fi\n      exit $return_value\n    else\n      log_failure_msg \"MySQL server PID file could not be found!\"\n    fi\n    ;;\n\n  'restart')\n    # Stop the service and regardless of whether it was\n    # running or not, start it again.\n    if $0 stop  $other_args; then\n      $0 start $other_args\n    else\n      log_failure_msg \"Failed to stop running server, so refusing to try to start.\"\n      exit 1\n    fi\n    ;;\n\n  'reload'|'force-reload')\n    if test -s \"$mysqld_pid_file_path\" ; then\n      read mysqld_pid <  \"$mysqld_pid_file_path\"\n      kill -HUP $mysqld_pid && log_success_msg \"Reloading service MySQL\"\n      touch \"$mysqld_pid_file_path\"\n    else\n      log_failure_msg \"MySQL PID file could not be found!\"\n      exit 1\n    fi\n    ;;\n  'status')\n    # First, check to see if pid file exists\n    if test -s \"$mysqld_pid_file_path\" ; then \n      read mysqld_pid < \"$mysqld_pid_file_path\"\n      if kill -0 $mysqld_pid 2>/dev/null ; then \n        log_success_msg \"MySQL running ($mysqld_pid)\"\n        exit 0\n      else\n        log_failure_msg \"MySQL is not running, but PID file exists\"\n        exit 1\n      fi\n    else\n      # Try to find appropriate mysqld process\n      mysqld_pid=`@PIDOF@ $libexecdir/mysqld`\n\n      # test if multiple pids exist\n      pid_count=`echo $mysqld_pid | wc -w`\n      if test $pid_count -gt 1 ; then\n        log_failure_msg \"Multiple MySQL running but PID file could not be found ($mysqld_pid)\"\n        exit 5\n      elif test -z $mysqld_pid ; then \n        if test -f \"$lock_file_path\" ; then \n          log_failure_msg \"MySQL is not running, but lock file ($lock_file_path) exists\"\n          exit 2\n        fi \n        log_failure_msg \"MySQL is not running\"\n        exit 3\n      else\n        log_failure_msg \"MySQL is running but PID file could not be found\"\n        exit 4\n      fi\n    fi\n    ;;\n    *)\n      # usage\n      basename=`basename \"$0\"`\n      echo \"Usage: $basename  {start|stop|restart|reload|force-reload|status}  [ MySQL server options ]\"\n      exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 377}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# A simple startup script for mysqld_multi by Tim Smith and Jani Tolonen.\n# This script assumes that my.cnf file exists either in /etc/my.cnf or\n# /root/.my.cnf and has groups [mysqld_multi] and [mysqldN]. See the\n# mysqld_multi documentation for detailed instructions.\n#\n# This script can be used as /etc/init.d/mysql.server\n#\n# Comments to support chkconfig on RedHat Linux\n# chkconfig: 2345 64 36\n# description: A very fast and reliable SQL database engine.\n#\n# Version 1.0\n#\n\nbasedir=/usr/local/mysql\nbindir=/usr/local/mysql/bin\n\nif test -x $bindir/mysqld_multi\nthen\n  mysqld_multi=\"$bindir/mysqld_multi\";\nelse\n  echo \"Can't execute $bindir/mysqld_multi from dir $basedir\";\n  exit;\nfi\n\ncase \"$1\" in\n    'start' )\n        \"$mysqld_multi\" start $2\n        ;;\n    'stop' )\n        \"$mysqld_multi\" stop $2\n        ;;\n    'report' )\n        \"$mysqld_multi\" report $2\n        ;;\n    'restart' )\n        \"$mysqld_multi\" stop $2\n        \"$mysqld_multi\" start $2\n        ;;\n    *)\n        echo \"Usage: $0 {start|stop|report|restart}\" >&2\n        ;;\nesac\n", "num_lines": 46}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>IFPkgDescriptionDeleteWarning</key>\n\t<string></string>\n\t<key>IFPkgDescriptionDescription</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>\n\t<key>IFPkgDescriptionTitle</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@ for Mac OS X</string>\n\t<key>IFPkgDescriptionVersion</key>\n\t<string>@VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t</dict>\n</plist>\n", "num_lines": 32}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003, 2008 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleGetInfoString</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>com.mysql.mysql</string>\n\t<key>CFBundleName</key>\n\t<string>MySQL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>@MYSQL_NUMERIC_VERSION@</string>\n\t<key>IFPkgFlagAllowBackRev</key>\n\t<false/>\n\t<key>IFPkgFlagAuthorizationAction</key>\n\t<string>RootAuthorization</string>\n\t<key>IFPkgFlagDefaultLocation</key>\n\t<string>/usr/local</string>\n\t<key>IFPkgFlagInstallFat</key>\n\t<false/>\n\t<key>IFPkgFlagIsRequired</key>\n\t<false/>\n\t<key>IFPkgFlagRelocatable</key>\n\t<false/>\n\t<key>IFPkgFlagRestartAction</key>\n\t<string>NoRestart</string>\n\t<key>IFPkgFlagRootVolumeOnly</key>\n\t<true/>\n\t<key>IFPkgFlagUpdateInstalledLanguages</key>\n\t<false/>\n\t<key>IFPkgFormatVersion</key>\n\t<real>0.10000000149011612</real>\n</dict>\n</plist>\n", "num_lines": 52}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# postflight - this script will be executed after the MySQL PKG\n# installation has been performed.\n#\n# This script will install the MySQL privilege tables using the\n# \"mysql_install_db\" script and will correct the ownerships of these files\n# afterwards.\n#\n\nif cd @prefix@ ; then\n\tif [ ! -f data/mysql/db.frm ] ; then\n\t\t./sbin/mysqld --initialize --datadir=@prefix@/data --basedir=@prefix@\n\tfi\n\n\tif [ -d data ] ; then\n\t\tchown -R @MYSQLD_USER@ data\n\tfi\nelse\n\texit $?\nfi\n", "num_lines": 40}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2003, 2005 MySQL AB\n# Use is subject to license terms\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; version 2\n# of the License.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the Free\n# Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n# MA 02110-1301, USA\n\n#\n# preflight - this script will be executed before the MySQL PKG\n# installation will be performed.\n#\n# If this package has been compiled with a prefix ending with \"mysql\" (e.g.\n# /usr/local/mysql or /opt/mysql), it will rename any previously existing\n# directory with this name before installing the new package (which includes\n# a symlink named \"mysql\", pointing to the newly installed directory, which\n# is named mysql-<version>)\n#\n\nPREFIX=\"@prefix@\"\nBASENAME=`basename $PREFIX`\n\nif [ -d $PREFIX -a ! -L $PREFIX -a $BASENAME = \"mysql\" ] ; then\n\tmv $PREFIX $PREFIX.bak\nfi\n", "num_lines": 38}
{"repo_name": "mysql-8.0", "repo_creator": "facebook", "programming_language": "Shell", "code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple Computer//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<!--\n   Copyright (C) 2003 MySQL AB\n   Use is subject to license terms\n\n   This program is free software; you can redistribute it and/or modify\n   it under the terms of the GNU General Public License as published by\n   the Free Software Foundation; version 2 of the License.\n\n   This program is distributed in the hope that it will be useful,\n   but WITHOUT ANY WARRANTY; without even the implied warranty of\n   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n   GNU General Public License for more details.\n\n   You should have received a copy of the GNU General Public License\n   along with this program; if not, write to the Free Software\n   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n-->\n<plist version=\"1.0\">\n<dict>\n\t<key>Description</key>\n\t<string>MySQL @VERSION@@MYSQL_SERVER_SUFFIX@</string>\n\t<key>OrderPreference</key>\n\t<string>None</string>\n\t<key>Provides</key>\n\t<array>\n\t\t<string>MySQL</string>\n\t</array>\n\t<key>Uses</key>\n\t<array>\n\t\t<string>Network</string>\n\t\t<string>Resolver</string>\n\t</array>\n\t</dict>\n</plist>\n", "num_lines": 37}
{"repo_name": "ocamlrep", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -euxo pipefail\n\nif ! command -v opam &> /dev/null\nthen\n    echo \"opam is not installed, which is a dependency for building targets in ocaml.\"\n    exit\nfi\n\nif [ -z \"$OPAM_SWITCH_PREFIX\" ]; then\n    echo \"OPAM_SWITCH_PREFIX is undefined. First execute \\`eval (\\$opam env)\\` and then try running $0 again.\"\n    exit\nfi\n\n# Link 'shim/third-party/ocaml/standard_library'.\nif [ ! -L shim/third-party/ocaml/standard_library ]; then\n  (cd shim/third-party/ocaml && ln -s \"$(ocamlopt.opt -config | grep standard_library: | awk '{ print $2 }' )\" standard_library)\nelse\n    echo \"Link 'shim/third-party/ocaml/standard_library' exists. To overwrite it, first remove it and run $0 again\"\nfi\n\n# Link 'third-party/ocaml/opam'.\nif [ ! -L shim/third-party/ocaml/opam ]; then\n  (cd shim/third-party/ocaml && ln -s \"$OPAM_SWITCH_PREFIX\" opam)\nelse\n    echo \"Link 'shim/third-party/ocaml/opam' exists. To overwrite it, first remove it and run $0 again\"\nfi\n", "num_lines": 36}
{"repo_name": "ocamlrep", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -e\n\n# - Apply a debug prefix map for the current directory\n# to make debug info relocatable.\n# - Use $TMPDIR for the module cache location. This\n# will be set to a unique location for each RE action\n# which will avoid sharing modules across RE actions.\n# This is necessary as the inputs to the modules will\n# be transient and can be removed at any point, causing\n# module validation errors to fail builds.\nif [ -n \"$INSIDE_RE_WORKER\" ]; then\n    MODULE_CACHE_PATH=\"$TMPDIR/module-cache\"\nelse\n    # When building locally we can use a shared module\n    # cache as the inputs should remain at a fixed\n    # location.\n    MODULE_CACHE_PATH=\"/tmp/buck-module-cache\"\nfi\n\nmodule_cache_path_args=()\nif [ -z \"$EXPLICIT_MODULES_ENABLED\" ]; then\n    module_cache_path_args+=(\"-module-cache-path\")\n    module_cache_path_args+=(\"$MODULE_CACHE_PATH\")\nfi\n\n\"$@\" -debug-prefix-map \"$PWD\"=. \"${module_cache_path_args[@]}\"\n\nOUTPUT_PATHS=()\nfor ARG in \"$@\"\ndo\n    if [ \"${FOUND_OUTPUT_ARG}\" = 1 ]; then\n        OUTPUT_PATHS+=( \"${ARG}\" )\n    fi\n    FOUND_OUTPUT_ARG=0\n    if [ \"${ARG}\" = \"-o\" ] || [ \"${ARG}\" = \"-emit-module-path\" ] || [ \"${ARG}\" = \"-emit-objc-header-path\" ]; then\n        FOUND_OUTPUT_ARG=1\n    fi\ndone\n\nif [ ${#OUTPUT_PATHS[@]} -eq 0 ]; then\n    >&2 echo \"No output paths found, ensure output args are not passed in argfiles\"\n    exit 1\nfi\n\nfor OUTPUT_PATH in \"${OUTPUT_PATHS[@]}\"\ndo\n    # We've observed cases where the Swift compiler would return with a zero exit code but\n    # would not have created the output file, correctly a non-zero exit code in such cases.\n    if [ ! -f \"${OUTPUT_PATH}\" ]; then\n        >&2 echo \"Output file does not exist: '${OUTPUT_PATH}'\"\n        exit 1\n    fi\ndone\n", "num_lines": 62}
{"repo_name": "ocamlrep", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nset -eu\n\n$1 \"${@:2}\" 1>&2\n", "num_lines": 12}
{"repo_name": "ocamlrep", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under both the MIT license found in the\n# LICENSE-MIT file in the root directory of this source tree and the Apache\n# License, Version 2.0 found in the LICENSE-APACHE file in the root directory\n# of this source tree.\n\nPYTHONPATH=\"$(dirname \"$(dirname \"$(dirname \"$(realpath \"$0\")\")\")\")\"\nexport PYTHONPATH\nexec python3 -m unittest sourcedb_merger.tests\n", "num_lines": 12}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nobmc_dir=$(realpath \"$(dirname \"$0\")\")\n. $obmc_dir/yocto_repos.sh\n\nFETCH_ONLY=0\nwhile [[ $# -gt 0 ]]\ndo\n  case $1 in\n    -f|--fetch-only)\n      FETCH_ONLY=1\n      shift\n      ;;\n\n    *)\n      shift\n      ;;\n  esac\ndone\n\nif [ ! -d ./yocto ]; then\n  mkdir ./yocto\nfi\n\ngit remote add yocto-poky \\\n    https://git.yoctoproject.org/git/poky || true\ngit remote add yocto-meta-openembedded \\\n    https://github.com/openembedded/meta-openembedded.git || true\ngit remote add yocto-meta-security \\\n    https://git.yoctoproject.org/git/meta-security || true\ngit remote add yocto-lf-openbmc \\\n    https://github.com/openbmc/openbmc.git || true\n\nfor branch in ${branches[@]}\ndo\n  # Make the branch if it does not exist.\n  if [ ! -d ./yocto/$branch ]; then\n    mkdir ./yocto/$branch\n  fi\n\n  if [[ ${branch} == lf-* ]]; then\n      real_branch=\"${branch/lf-/}\"\n  else\n      real_branch=\"${branch}\"\n  fi\n\n  repos=${branch/-/_}_repos[@]\n  for repo in ${!repos}\n  do\n    repo_name=${repo%%:*}\n    commit_id=${repo##*:}\n\n    if [ \"lf-openbmc\" = \"$repo_name\" ]; then\n        repo_name=\"lf-openbmc\"\n        repo_path=\"./yocto/${branch}\"\n        repo_patch_var=\"${real_branch}_openbmc_patch\"\n    else\n        repo_path=\"./yocto/${branch}/${repo_name}\"\n        repo_patch_var=\"${branch}_${repo_name/-/_}_patch\"\n    fi\n\n    # Remove the repo in the branch\n    if [ -d ${repo_path} ]; then\n      rm -rf ${repo_path}\n    fi\n\n    # Fetch the repo branch\n    git fetch yocto-${repo_name} ${real_branch}\n\n    # Add specific commit of repo into yocto/branch/repo/ worktree\n    if [ $FETCH_ONLY -eq 0 ]; then\n      git worktree add -f ${repo_path} ${commit_id}\n      if [ -n \"${!repo_patch_var}\" ]; then\n          for patch in ${!repo_patch_var}; do\n              git -C ${repo_path} am \\\n                $(realpath ./github/yocto/patches/${patch})\n          done\n      fi\n    fi\n  done\ndone\n\n", "num_lines": 84}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "branches=(\n    rocko\n    lf-master\n    lf-dunfell\n    lf-kirkstone\n    lf-langdale\n)\n\nrocko_repos=(\n    meta-openembedded:eae996301\n    meta-security:74860b2\n    poky:5f660914cd # bitbake: bitbake-user-manual: Fixed section head typo\n)\nrocko_poky_patch=\"0001-rocko-backport-support-for-override.patch 0002-Remove-checks-on-python.patch 0003-Add-support-to-build-on-centOS9.patch\"\nlf_master_repos=(\n    lf-openbmc:15c7c77bf\n)\nlf_dunfell_repos=(\n    lf-openbmc:c2858f16b\n)\nlf_kirkstone_repos=(\n    lf-openbmc:821a859c1\n)\nlf_langdale_repos=(\n    lf-openbmc:f4e5dde7f\n)\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "if [[ \"$(realpath /proc/self/fd/0)\" == *\"/pts/\"* ]]; then\n    export TMOUT=__SSH_TMOUT__\nfi\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "alias ls='ls --color=auto'\n", "num_lines": 2}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "if [[ \"$(realpath /proc/self/fd/0)\" == *\"ttyS\"* ]]; then\n    export TMOUT=__TMOUT__\nfi\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cache\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n# shellcheck disable=SC1091\nsource /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\n\n/usr/local/bin/bic-cache 0 > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nexec /usr/local/bin/bicmond\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n# shellcheck disable=SC1091\necho -n \"Setup bic monitoring... \"\n\nrunsv /etc/sv/bicmond > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nrm -f ../bios-util/*.pyc\nrm -rf ./*.pyc                     \n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nFRUID_UTIL=\"/usr/local/bin/fruid-util\"\nFW_UTIL=\"/usr/bin/fw-util\"\nKV_CMD=\"/usr/bin/kv\"\nSLOT_NAME=\"\"\nRUN_MODE=\"manual\"\n\nSCRIPT_PATH=\"${0}\"\n\nupdate_crashdump_history()\n{\n  l_SLOT_NUM=$1\n  l_CURT_DTIME=$2\n\n  HISTORY_KEY=\"crashdump_history_slot$l_SLOT_NUM\"\n\n  HISTORY_RECORD=$($KV_CMD get \"$HISTORY_KEY\" persistent)\n  HIST_INDEX_1=$(echo \"$HISTORY_RECORD\" | awk -F',' '{ print $1 }')\n  HIST_INDEX_2=$(echo \"$HISTORY_RECORD\" | awk -F',' '{ print $2 }')\n\n  OUT_STR=\"$l_CURT_DTIME\"\n  if [ -n \"$HIST_INDEX_1\" ]; then\n    OUT_STR=\"$OUT_STR,$HIST_INDEX_1\"\n  fi\n  if [ -n \"$HIST_INDEX_2\" ]; then\n    OUT_STR=\"$OUT_STR,$HIST_INDEX_2\"\n  fi\n \n  $KV_CMD set \"$HISTORY_KEY\" \"$OUT_STR\" persistent\n}\n\nclear_crashdump_archive()\n{\n  l_SLOT_NUM=$1\n  HISTORY_KEY=\"crashdump_history_slot$l_SLOT_NUM\"\n\n  HISTORY_RECORD=$(${KV_CMD} get \"$HISTORY_KEY\" persistent)\n  hist_dtime_1=$(echo \"$HISTORY_RECORD\" | awk -F',' '{ print $1 }')\n  hist_dtime_2=$(echo \"$HISTORY_RECORD\" | awk -F',' '{ print $2 }')\n  hist_dtime_3=$(echo \"$HISTORY_RECORD\" | awk -F',' '{ print $3 }')\n\n  for i in /mnt/data/crashdump_slot\"$l_SLOT_NUM\"*.tar.gz\n  do\n    file_dtime=$(basename \"$i\" | awk -F'.' '{print $1}' | awk -F'_' '{print $3}')\n    if [ \"$file_dtime\" = \"$hist_dtime_1\" ]; then\n      continue\n    elif [ \"$file_dtime\" = \"$hist_dtime_2\" ]; then\n      continue\n    elif [ \"$file_dtime\" = \"$hist_dtime_3\" ]; then\n      continue\n    else\n      rm \"$i\"\n    fi\n  done\n}\n\ndump_sensor_history() \n{\n  l_SLOT=$1\n  l_SENSOR_HISTORY=180\n\n  /usr/local/bin/sensor-util \"$l_SLOT\" --history $l_SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util spb --history $l_SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util nic --history $l_SENSOR_HISTORY \n}\n\ndump_sensor_threshold()\n{\n  l_SLOT=$1\n\n  /usr/local/bin/sensor-util \"$l_SLOT\" --threshold \\\n   && /usr/local/bin/sensor-util spb --threshold \\\n   && /usr/local/bin/sensor-util nic --threshold\n}\n\nscript_filename()\n{\n  N=${SCRIPT_PATH##*/}\n  N=${N#[SK]??}\n  echo \"$N\"\n}\n\nfor i in \"$@\"; do\n  case \"$1\" in\n    -e|--event)\n      RUN_MODE=\"event\"\n      shift\n      ;;\n    --*|-*=) # unsupported flags\n      echo \"Error: Unsupported flag $i\" >&2\n      exit 1\n      ;;\n    *) # preserve positional arguments\n      SLOT_NAME=\"$i\"\n      shift\n      ;;\n  esac\ndone\n\ncase $SLOT_NAME in\n    slot1)\n      SLOT_NUM=1\n      ;;\n    slot2)\n      SLOT_NUM=2\n      ;;\n    slot3)\n      SLOT_NUM=3\n      ;;\n    slot4)\n      SLOT_NUM=4\n      ;;\n    *)\n      echo \"Usage: $(script_filename) {slot1|slot2|slot3|slot4}\"\n      exit 1\n      ;;\nesac\n\n# We only support event triggered crashdump for now\nif [ \"$RUN_MODE\" = \"manual\" ]; then\n  echo \"$(script_filename): Manual trigger not supported\"\n  exit 1\nfi\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump${SLOT_NUM}.pid\"\n\nCURT_DTIME=$(date +\"%Y%m%d-%H%M%S\")\nCRASHDUMP_FILE=\"/tmp/crashdump_${SLOT_NAME}\"\nCRASHDUMP_DECODED_FILE=\"/tmp/crashdump_${SLOT_NAME}_mca\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_${SLOT_NAME}_${CURT_DTIME}.tar.gz\"\nLOG_MSG_PREFIX=\"\"\n\necho \"Auto Dump for $SLOT_NAME Started\"\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM started\"\n\n#HEADER LINE for the dump\necho \"Crash Dump generated at $(date)\" > \"$CRASHDUMP_FILE\"\n\n{\n  # Get BMC version & hostname\n  echo \"Get BMC version info: \"\n  \"$FW_UTIL\" bmc --version\n  uname -a\n  cat /etc/issue\n\n  # Get fw info\n\n  echo \"Get firmware version info: \"\n  \"$FW_UTIL\" \"$SLOT_NAME\" \"--version\"\n\n\n  # Get FRUID info\n  echo \"Get FRUID Info:\"\n  \"$FRUID_UTIL\" \"$SLOT_NAME\"\n\n  # Sensors & sensor thresholds\n  echo \"Sensor history at dump:\"\n  dump_sensor_history \"$SLOT_NAME\"\n  echo \"Sensor threshold at dump:\"\n  dump_sensor_threshold \"$SLOT_NAME\"\n\n  # MCA dumps\n  echo \"Crashdump v1.0:\"\n  cat \"$CRASHDUMP_DECODED_FILE\"\n  echo \"=================\"\n\n  echo \"Auto Dump End at $(date)\"\n} >> \"$CRASHDUMP_FILE\"\n\ntar zcf \"$CRASHDUMP_LOG_ARCHIVE\" -C \"$(dirname \"$CRASHDUMP_FILE\")\" \"$(basename \"$CRASHDUMP_FILE\")\" && \\\nrm -rf \"$CRASHDUMP_DECODED_FILE\" && \\\nrm -rf \"$CRASHDUMP_FILE\" && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM is generated at $CRASHDUMP_LOG_ARCHIVE\"\n# cp -f \"$CRASHDUMP_LOG_ARCHIVE\" /tmp\n\n# update crashdump history, only keep last three archive for each slot\nupdate_crashdump_history $SLOT_NUM \"$CURT_DTIME\"\nclear_crashdump_archive $SLOT_NUM\n\necho \"Auto Dump for $SLOT_NAME Completed\"\n\n# Remove current pid file\nrm \"$PID_FILE\"\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $CRASHDUMP_LOG_ARCHIVE\"\nexit 0\n", "num_lines": 206}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/emmcd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-emmcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start eMMC monitor daemon\n### END INIT INFO\n\necho \"Setup eMMC Daemon..\"\n\nCACHE_STORE_DIR=\"/tmp/cache_store\"\nEXTCSD_CACHE=\"${CACHE_STORE_DIR}/mmc0_extcsd\"\nMMC_DEVICE=\"/dev/mmcblk0\"\nMMCRAW_CMD=\"/usr/local/bin/mmcraw\"\n\nif [ ! -b \"$MMC_DEVICE\" ]; then\n  echo \"$MMC_DEVICE does not exist. Exiting.\"\n  exit 1\nfi\n\nif [ ! -d \"$CACHE_STORE_DIR\" ]; then\n  mkdir -p \"$CACHE_STORE_DIR\" || exit 1\nfi\n\nif ! [[ -f $EXTCSD_CACHE ]]; then\n  \"$MMCRAW_CMD\" read-extcsd \"$MMC_DEVICE\" > \"$EXTCSD_CACHE\"\nfi\n\n# Display eMMC device summary\nEMMC_INFO=$(\"$MMCRAW_CMD\" show-summary \"$MMC_DEVICE\")\necho \"$EMMC_INFO\"\n\nif echo \"$EMMC_INFO\" | grep \"Device Health.*Undefined\" > /dev/null 2>&1 &&\n   echo \"$EMMC_INFO\" | grep \"Life Time.*Undefined\" > /dev/null 2>&1; then\n    echo \"emmcd not started: device life time estimates not supported.\"\n    exit 1\nfi\n\necho \"Starting emmcd daemon..\"\nrunsv /etc/sv/emmcd > /dev/null 2>&1 &\nexit 0\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/fru-svcd\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          fru-svcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: dbus based fru service\n### END INIT INFO\n\necho -n \"Setup fru svcd for FBTP... \"\n\nrunsv /etc/sv/fru-svcd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# execute <fscd.py> <min syslog level>\n# log_level = <debug, warning, info>\n# Default log level in fscd is set to warning, if any other level is needed\n# set here\nexec /usr/bin/fscd.py 'warning'\n", "num_lines": 7}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nrm -f ../fscd/*.pyc\nrm -rf ./*.pyc\nrm -rf ./ply/*.pyc\nrm -f ../fscd/parser.out\nrm -f ../fscd/parsetab.py\n\n# reset all fan set data\necho 0 > ./test-data/test-util-data/fan0-set-data\necho 0 > ./test-data/test-util-data/fan1-set-data\necho 0 > ./test-data/test-util-data/fan2-set-data\necho 0 > ./test-data/test-util-data/fan3-set-data\necho 0 > ./test-data/test-util-data/fan4-set-data\necho 0 > ./test-data/test-util-data/fan5-set-data\necho 0 > ./test-data/test-sysfs-data/fantray0_pwm\necho 0 > ./test-data/test-sysfs-data/fantray1_pwm\necho 0 > ./test-data/test-sysfs-data/fantray2_pwm\necho 0 > ./test-data/test-sysfs-data/fantray3_pwm\necho 0 > ./test-data/test-sysfs-data/fantray4_pwm\necho 0 > ./test-data/test-sysfs-data/fantray5_pwm\necho 15000 > ./test-data/test-sysfs-data/4-0033/temp1_input\necho 15000 > ./test-data/test-sysfs-data/3-004b/temp1_input\necho 15000 > ./test-data/test-sysfs-data/3-0048/temp1_input\n                        \n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nFILE=$1\nFAN=$2\ncat $FILE | head -n $FAN | tail -n 1\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "file_name=$1\nother=$2\ncat ./test-data/test-util-data/$file_name\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "file_name=$0\npwm_value=$1\npwm_num=$2\necho $pwm_value > ./test-data/test-util-data/fan$pwm_num-set-data\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/healthd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-healthd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup healthd for BMC \"\n\nrunsv /etc/sv/healthd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.eth0.pid\"\nexec dhclient -6 -d -D LL -pf ${pid} eth0 \"$@\"\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.eth0.pid\"\n\n# shellcheck disable=SC2086\nmac_to_ll() {\n  IFS=':'; set $1; unset IFS\n  echo \"fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6\" | \\\n    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'\n}\n\nexp_ll=\nll=\n\nfor _ in {1..30}; do\n  # wait getting address from NC-SI\n  if [ \"$(cat /sys/class/net/eth0/addr_assign_type)\" = \"3\" ]; then\n    exp_ll=$(mac_to_ll \"$(cat /sys/class/net/eth0/address)\")\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break\n    fi\n    # re-generate link-local address\n    ip -6 addr flush dev eth0 scope link\n    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    break;\n  fi\n  sleep 1\ndone\n\nif [ \"$ll\" != \"$exp_ll\" ]; then\n  for _ in {1..100}; do\n    usleep 10000\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break;\n    fi\n  done\nfi\n\nexec dhclient -6 -d -D LL -pf ${pid} eth0 \"$@\"\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.eth0.pid\"\nexec dhclient -6 -d -D LL --address-prefix-len 64 -pf ${pid} eth0 \"$@\"\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.eth0.pid\"\n\n# shellcheck disable=SC2086\nmac_to_ll() {\n  IFS=':'; set $1; unset IFS\n  echo \"fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6\" | \\\n    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'\n}\n\nexp_ll=\nll=\n\nfor _ in {1..30}; do\n  # wait getting address from NC-SI\n  if [ \"$(cat /sys/class/net/eth0/addr_assign_type)\" = \"3\" ]; then\n    exp_ll=$(mac_to_ll \"$(cat /sys/class/net/eth0/address)\")\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break\n    fi\n    # re-generate link-local address\n    ip -6 addr flush dev eth0 scope link\n    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    break;\n  fi\n  sleep 1\ndone\n\nif [ \"$ll\" != \"$exp_ll\" ]; then\n  for _ in {1..100}; do\n    usleep 10000\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break;\n    fi\n  done\nfi\n\nexec dhclient -6 -d -D LL --address-prefix-len 64 -pf ${pid} eth0 \"$@\"\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\necho -n \"Setup dhclient for IPv6... \"\nrunsv /etc/sv/dhc6 > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n### BEGIN INIT INFO\n# Provides:          hostname\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set hostname based on /etc/hostname\n### END INIT INFO\nHOSTNAME=\"bmc-oob.\"\n\nset_hostname() {\n  local name=$1\n  # Update /etc configuration and persistent cache.\n  echo $name > /etc/hostname\n  echo $name > /mnt/data/hostname\n  # Set hostname\n  hostname $name\n  # Reload/Restart any services needing the updated hostname\n  /etc/init.d/syslog reload\n}\n\nif [ -s /mnt/data/hostname ]; then\n  # Use the cached copy to set the hostname\n  HOSTNAME=$(cat /mnt/data/hostname)\nfi\nset_hostname $HOSTNAME\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmid\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ipmid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set IPMI Message handler\n### END INIT INFO\n\necho -n \"Setup IPMI message handler... \"\nrunsv /etc/sv/ipmid > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          kcsd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides kcs message tx/rx service\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\nDAEMON=/usr/local/bin/kcsd\nNAME=kcsd\nDESC=\"KCS Rx/Tx Daemon\"\n\ntest -f $DAEMON || exit 0\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    echo -n \"Starting $DESC: \"\n    $DAEMON 2 BMC_READY_N > /dev/null 2>&1 &\n    $DAEMON 1 BMC_READY_N > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    sleep 1\n    $DAEMON 2 BMC_READY_N > /dev/null 2>&1 &\n    $DAEMON 1 BMC_READY_N > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nINITD=\"/etc/init.d\"\nIF_DIR=\"/mnt/data/etc/network\"\nIF_CONF=\"interfaces\"\n\nIF_UPDATE_CONF=\"$IF_DIR/$IF_CONF\"\nIF_TARGET_CONF=\"/etc/network/interfaces\"\nIF_UP=\"/etc/network/if-up.d\"\nIF_DOWN=\"/etc/network/if-down.d\"\n\nSV_PREFIX=\"/etc/sv/dhc6_\"\nRUN_SV_PREFIX=\"runsv $SV_PREFIX\"\n\nfunction init_conf()\n{\n  if [ ! -d $IF_DIR ];\n  then\n    mkdir -p $IF_DIR\n  fi\n\n  if_name=\"\"\n  if [ ! -f $IF_UPDATE_CONF ];\n  then\n    while IFS='' read -r line || [[ -n \"$line\" ]];\n    do\n      if ! [[ $line = \\#* ]];\n      then\n        echo \"$line\" >> $IF_UPDATE_CONF\n        if [[ $line = iface* ]];\n        then\n          if_name=$(echo $line | awk -F' ' '{print $2}')\n          if [[ $if_name = eth* ]];\n          then\n            echo -e \"\\niface $if_name inet6 dhcp\" >> $IF_UPDATE_CONF\n          fi\n        fi\n      fi\n    done < \"$IF_TARGET_CONF\"\n  fi\n}\n\nfunction update_rc5()\n{\n  out=\"setup-dhc6_$1.sh\"\n  echo \"#!/bin/sh\" >> $out\n  echo \"echo -n \\\"Setup the dhclient of $1 for IPv6...\\\"\" >> $out\n  echo \"$RUN_SV_PREFIX$1 &>/dev/null &\" >> $out\n  echo \"echo \\\"done.\\\"\" >> $out\n  chmod 755 $out\n  mv $out $INITD\n  update-rc.d -f $out remove &>/dev/null\n  update-rc.d $out start 2 5 S . &>/dev/null\n}\n\nfunction update_sv()\n{\n  folder=\"$SV_PREFIX$1\"\n  out=\"$folder/run\"\n\n  if [ ! -d \"$folder\" ];\n  then\n    mkdir -p $folder\n  fi\n\n  cat /dev/null > $out\n  echo \"#!/bin/sh\" >> $out\n  echo \"pid=\\\"/var/run/dhclient6.$1.pid\\\"\" >> $out\n  echo \"exec dhclient -6 -d -D LL -pf \\${pid} $1 \\\"\\$@\\\"\" >> $out\n  chmod 755 $out\n}\n\nfunction update_ifupdown()\n{\n  #up\n  out=\"$IF_UP/dhcpv6_$1_up\"\n  cat /dev/null > $out\n  echo \"#!/bin/bash\" >> $out\n  echo \"if [ \\\"\\$IFACE\\\" == \\\"$1\\\" ]; then\" >> $out\n  echo \"  sv status dhc6_$1 &>/dev/null &&\\\\\" >> $out\n  echo \"  sv restart dhc6_$1\" >> $out\n  echo \"fi\" >> $out\n  echo \"exit 0\" >> $out\n  chmod 755 $out\n\n  #down\n  out=\"$IF_DOWN/dhcpv6_$1_down\"\n  cat /dev/null > $out\n  echo \"#!/bin/bash\" >> $out\n  echo \"if [ \\\"\\$IFACE\\\" == \\\"$1\\\" ]; then\" >> $out\n  echo \"  sv stop dhc6_$1 $> /dev/null &\" >> $out\n  echo \"fi\" >> $out\n  chmod 755 $out\n}\n\nfunction deploy_setting()\n{\n  update_rc5 $1\n  update_sv $1\n  update_ifupdown $1\n}\n\nfunction update_conf()\n{\n  #clear the old content\n  cat /dev/null > $IF_TARGET_CONF\n\n  #Update the new content\n  i=0\n  vlan_id=\"\"\n  record_vlan=\"\"\n  while IFS='' read -r line || [[ -n \"$line\" ]];\n  do\n    interface=\"\"\n    if_family=\"\"\n    method=\"\"\n\n    if [[ $line = iface* ]];\n    then\n      interface=$(echo $line | awk -F' ' '{print $2}')\n      if_family=$(echo $line | awk -F' ' '{print $3}')\n      method=$(echo $line | awk -F' ' '{print $4}')\n      if [ \"$record_vlan\" == \"\" ];\n      then\n        record_vlan=$(echo $interface | awk -F'.' '{print $2}')\n      fi\n      \n      if ! [[ $interface = lo* ]];\n      then\n        /sbin/ifconfig $interface 0 > /dev/null 2>&1\n      fi\n    fi\n\n    if ! [ \"$record_vlan\" == \"$vlan_id\" ] && [[ $interface = eth* ]];\n    then\n      actual_if=$(echo $interface | awk -F'.' '{print $1}')\n      /sbin/vconfig add $actual_if $record_vlan\n      vlan_id=$record_vlan\n    fi\n\n    if [ \"$if_family\" == \"inet6\" ] && [ \"$method\" == \"dhcp\" ];\n    then\n      deploy_setting $interface\n    else\n      if [ \"$line\" == \"\" ];\n      then\n        ((i++))\n      else\n        i=0\n      fi\n\n      if [ $i -lt 2 ];\n      then\n        echo \"$line\" >> $IF_TARGET_CONF\n      fi\n    fi\n  done < \"$IF_UPDATE_CONF\"\n}\n\nfunction clear_dhc6()\n{\n  SV_PATH=\"/etc/sv\"\n  for file in $SV_PATH/*\n  do\n    if [[ $file = $SV_PATH/dhc6* ]];\n    then\n      #stop service\n      sv_name=$(echo $file | awk -F'/' '{print $4}')\n      /usr/bin/sv stop $sv_name $> /dev/null\n\n      #kill runsv id\n      sv_id=$(ps | grep \"runsv /etc/sv/$sv_name\\$\" | head -n 1 | awk -F' ' '{print $1}')\n      /bin/kill -9 $sv_id > /dev/null 2>&1\n\n      #rm the dir\n      rm -rf $file\n    fi\n  done\n\n  rm -rf $IF_UP/dhcpv6_*\n  rm -rf $IF_DOWN/dhcpv6_*\n  rm -rf $INITD/setup-dhc6_*\n  rm -rf /etc/rc5.d/S02setup-dhc6_*\n}\n\nfunction clear_vlan()\n{\n  list=$(ip a | grep @ | cut -d \":\" -f 2)\n  IFS=' '\n  for intf in $list;\n  do\n    if [ \"$intf\" == \"\" ];\n    then\n      continue\n    fi\n\n    intf=$(echo $intf | tr -d '\\040\\011\\012\\015')\n\n    vintf=$(echo $intf | cut -d \"@\" -f 1)\n    intf=$(echo $intf | cut -d \"@\" -f 2 | awk '{print tolower($0)}')\n\n    if [ \"$intf\" == \"none\" ];\n    then\n      continue\n    fi\n\n    /sbin/vconfig rem $vintf\n  done\n}\n\nfunction run_dhc6()\n{\n  RC5D=\"/etc/rc5.d\"\n  for file in $RC5D/*\n  do\n    if [[ $file = $RC5D/S02setup-dhc6* ]];\n    then\n      sh $file $> /dev/null\n    fi\n  done\n}\n\nif [ \"$1\" == \"start\" ];\nthen\n  init_conf\n  update_conf\nelif [ \"$1\" == \"restart\" ];\nthen\n  /sbin/ifdown -a\n  clear_vlan\n  clear_dhc6\n  init_conf\n  update_conf\n  /sbin/ifup -a\n  run_dhc6\nfi\n\n", "num_lines": 238}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 7}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          enable-aen\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho \"Enable standard AENs:(Link Status, Config Req, Driver Status)\" >> /dev/kmsg\n/usr/local/bin/ncsi-util 8 0 0 0 0 0 0 0 7\n\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ncsid\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ncsid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup ncsid for BMC \"\n\nrunsv /etc/sv/ncsid > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          oob-nic\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: One of the first scripts to be executed. Starts or stops\n#               the OOB NIC.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/oob-nic\nNAME=oob-nic\nDESC=\"OOB NIC Driver\"\n\n# source function library\n. /etc/init.d/functions\n\ntest -f $DAEMON || exit 0\n\n# enable the isolation buffer\n. /usr/local/bin/openbmc-utils.sh\n\nfix_etc_interfaces() {\n    local intf_conf board_rev board_type enable_oob\n    if wedge_should_enable_oob; then\n        intf_conf=\"/etc/network/interfaces\"\n        if ! grep oob $intf_conf > /dev/null 2>&1; then\n            echo >> $intf_conf\n            echo \"auto oob\" >> $intf_conf\n            echo \"iface oob inet dhcp\" >> $intf_conf\n        fi\n    fi\n}\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    echo -n \"Starting $DESC: \"\n    if [ ! -d /dev/net ]\n    then\n      mkdir /dev/net\n    fi\n    if [ ! -f /dev/net/tun ]\n    then\n      mknod /dev/net/tun c 10 200\n      chmod 666 /dev/net/tun\n    fi\n    fix_etc_interfaces\n    $DAEMON > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    echo \"$NAME.\"\n    ;;\n   restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    sleep 1\n    fix_etc_interfaces\n    $DAEMON > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"*****Running platform-svc HotPlugDetectionMechanism unit tests**********\"\n/usr/bin/test-platform-svc-hotplugdetectionmechanism\n\necho \"*****Running platform-svc FRU unit tests********************************\"\n/usr/bin/test-platform-svc-fru\n\necho \"*****Running platform-svc PlatformObjectTree unit tests*****************\"\n/usr/bin/test-platform-svc-platform-object-tree\n", "num_lines": 11}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n(sleep 5; PYTHONPATH=/etc python /etc/rackmon-config.py) &\nexport RACKMOND_FOREGROUND=1\n# Give PSUs 2ms of grace time to let go of the bus after they respond to a\n# command\nexport RACKMOND_MIN_DELAY=2000\nexec /usr/local/bin/rackmond\n\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-rackmond\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start Rackmon service\n### END INIT INFO\n\nrunsv /etc/sv/rackmond > /dev/null 2>&1 &\nsv $1 rackmond\n", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2021-present Facebook. All Rights Reserved.\nln -s /etc/aspeed_uart.conf /etc/rackmon.conf\nexec /usr/local/bin/rackmond\n\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-rackmond\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start Rackmon service\n### END INIT INFO\n\nrunsv /etc/sv/rackmond > /dev/null 2>&1 &\nsv $1 rackmond\n", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/redfish-events.py\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nrunsv /etc/sv/redfishevents >/dev/null 2>&1 &\n# delay 0.5 seconds to avoid suprising error print like below:\n# warning: restapi: can't open supervise/control: No such file or directory\n# root casue is runit daemon is not ready.\nif [ -n \"$1\" ]; then\n    (sleep 0.5; sv \"$1\" redfishevents) &\nfi\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/sensord SENSORD_LAUNCH_ARGS\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup sensor monitoring... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ninput=$1\n\n\nprint_usage() {\n\n    echo \"  slot to host name lookup\"\n    echo \"\"\n    echo \"  Usage:      slot-util [ slot1, slot2, slot3, slot4, all ] : shows host for a particular/all slot(s)\"\n    echo \"              slot-util [ 1, 2, 3, 4 ]                      : shows host for a particular slot\"\n    echo \"              slot-util [ hostname ]                        : shows slot number for a host\"\n    echo \"              slot-util --show-mac                          : shows MAC address assigned for each host\"\n}\n\nif [ $# -eq 0 ]; then\n    print_usage\n    exit 1\nfi\n\nocp3nic=0\nsku_type=0\n\nif grep -q \"yosemite\" /etc/issue; then\n    sku_type=0\nelif grep -q \"halfdome\" /etc/issue; then\n    sku_type=fffd\n    ocp3nic=1\nelif grep -q \"fby35\" /etc/issue; then\n    sku_type=fffe\n    ocp3nic=1\nelif grep -q \"fby3\" /etc/issue; then\n    sku_type=ffff\n    ocp3nic=1\nelse\n    # fby2 file\n    # shellcheck disable=SC1091\n    . /usr/local/fbpackages/utils/ast-functions\n\n    # if no get_slot_type exist (such as Yosemite 1), assume 4 server config\n    if [ -n \"$(LC_ALL=C type -t get_slot_type)\" ] && [ \"$(LC_ALL=C type -t get_slot_type)\" = function ]; then\n      for i in $(seq 1 1 4)\n      do\n        tmp_sku=\"$(get_slot_type \"$i\")\"\n        sku_type=\"$(($((\"$tmp_sku\" << $((\"$((\"$i\"*4))\" - 4))))+\"$sku_type\"))\"\n      done\n    fi\n    # OCP3 NIC detection\n    GPIOCLI_CMD=/usr/local/bin/gpiocli\n    prsnt_a=$($GPIOCLI_CMD get-value --shadow MEZZ_PRSNTA2_N | awk -F= '{print $2}')\n    prsnt_b=$($GPIOCLI_CMD get-value --shadow MEZZ_PRSNTB2_N | awk -F= '{print $2}')\n    if ((prsnt_a == 0 && prsnt_b == 1)); then\n      ocp3nic=1\n    else\n      ocp3nic=0\n    fi\nfi\n\n\n\n# get BMC mac address and conver it to base 10 integer\nbmc_mac_dec=\"$( printf \"%d\\\\n\" \"0x$(sed s/://g \"/sys/class/net/eth0/address\")\")\"\n\n\n# get neighboring devices in {hostname, MAC} format, shows only entries that can resolve to host name\nhost_table=$(ip -r neigh show dev eth0 | grep -iE 'com|edu|gov|org' | sort -k 3)\n\n\n# calculate expected MAC address for each slot, convert it back to hex str\n#\n# MAC address calculation is different for 2xTL+2x carrier\ncase \"$sku_type\" in\n   \"0\")\n      if [ $ocp3nic -eq 1 ]; then\n        echo \"4 server, OCP3 NIC\"\n        slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-4)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-3)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-2)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//');\n      else\n        echo \"4 server, OCP2 NIC\"\n        slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n        slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      fi\n   ;;\n   \"fffd\")\n      echo \"Half Dome, OCP3 NIC\"\n      slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n   ;;\n   \"fffe\")\n      echo \"Yosemite V3.5, OCP3 NIC\"\n      slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n   ;;\n   \"ffff\")\n      echo \"Yosemite V3, OCP3 NIC\"\n      slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n   ;;\n   \"1028\")\n      echo \"2server + 2GPv2, OCP2 NIC\"\n      slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n   ;;\n   *)\n      echo \"unknown config - use default\"\n      slot1_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec-1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot2_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+1)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot3_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+3)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n      slot4_mac=$(printf \"%012x\\\\n\" $((bmc_mac_dec+5)) | sed -e 's/[0-9A-Fa-f]\\{2\\}/&:/g' -e 's/:$//')\n   ;;\nesac\n\nif [ \"$1\" == \"--show-mac\" ]; then\n  for i in 1 2 3 4\n  do\n    slotmac=\"slot$i\"\n    slotmac=\"${slotmac}_mac\"\n    eval echo slot$i MAC: \"${!slotmac}\"\n  done\n  exit 1\nfi\n\n# match host name to each slot based on MAC address\nif [[ -n $slot1_mac ]]; then\n  # shellcheck disable=SC2034\n  host1=\"$(echo \"$host_table\" | grep -i \"${slot1_mac}\" | cut  -d \" \" -f1)\"\nfi\nif [[ -n $slot2_mac ]]; then\n  # shellcheck disable=SC2034\n  host2=\"$(echo \"$host_table\" | grep -i \"${slot2_mac}\" | cut  -d \" \" -f1)\"\nfi\nif [[ -n $slot3_mac ]]; then\n  # shellcheck disable=SC2034\n  host3=\"$(echo \"$host_table\" | grep -i \"${slot3_mac}\" | cut  -d \" \" -f1)\"\nfi\nif [[ -n $slot4_mac ]]; then\n  # shellcheck disable=SC2034\n  host4=\"$(echo \"$host_table\" | grep -i \"${slot4_mac}\" | cut  -d \" \" -f1)\"\nfi\n\n# check if user asked for a specific slot, either in \"slotX\", or just \"X\"\nif [[ \"$input\" =~ ^[0-9]+$ ]]; then\n    slot_num=$input\nelif [[ $1 == \"slot\"* ]]; then\n    slot_num=$(echo \"$1\" | tr -dc '0-9')\nfi\n\n\n# check if user specified \"all\" option\nif [ -z \"$slot_num\" ]; then\n    if [[ $1 == \"all\" ]]; then\n        for i in 1 2 3 4\n        do\n           eval echo slot$i: \\$host$i\n        done\n    else\n        # check if user entered a valid host name\n        match=$(echo \"$host_table\" | grep -i \"$1\")\n        # if no match\n        if [ -z \"$match\" ]; then\n            echo host name \"$1\" not found\n        else\n            for i in 1 2 3 4\n            do\n               hostname=$( (eval echo \\$host$i) | grep -i \"$1\")\n               if [ -z \"$hostname\" ]; then\n                   :\n               else\n                   eval echo slot$i: \\$host$i\n               fi\n            done\n        fi\n    fi\nelse\n    # user specified a specific slot\n    eval echo slot\"$slot_num\": \\$host\"$slot_num\"\nfi\n", "num_lines": 204}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nHOSTNAME=\"bmc-oob.\"\n\nset_hostname() {\n  local name=$1\n  # Update /etc configuration and persistent cache.\n  echo \"$name\" > /etc/hostname\n  echo \"$name\" > /mnt/data/hostname\n  # Set hostname\n  hostname \"$name\"\n}\n\nif [ -s /mnt/data/hostname ]; then\n  # Use the cached copy to set the hostname\n  HOSTNAME=\"$(cat /mnt/data/hostname)\"\nfi\n\nset_hostname \"$HOSTNAME\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n    echo \"Usage: $0 <on | off>\" >&2\n}\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\ncase \"$1\" in\n\"on\")\n    echo \"Enabling watchdog. Note: this does not start the watchdog!\"\n    echo \"x\" > /dev/watchdog\n    ;;\n\"off\")\n    echo \"Disabling watchdog.\"\n    echo \"X\" > /dev/watchdog\n    ;;\n*)\n    usage\n    exit 1\n    ;;\nesac\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/bash\n\nrm -rf gen/com\nsdbus++-gen-meson \\\n    --command meson \\\n    --directory yaml \\\n    --output gen\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\niteration=4100\nfor ((i=1;i<iteration;i=i*2));\ndo\n  python service-memorytest.py --i $i &\n  spid=$(echo $!)\n  python ipc-memorytest.py --i $i &\n  ipid=$(echo $!)\n\n  # wait for the connection to service to be set up\n  python caller-memorytest.py\n\n  echo $i routes: $(top -b -n 1 | grep Mem)\n  kill $spid $ipid\ndone\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\neval `dbus-launch --auto-syntax`\ndbuspid=$(ps | grep dbus | grep fork | grep -o \"^ *[0-9]*\")\n./dbus-testserver &\nserverpid=$(ps | grep dbus-testserver | grep -o \"^ *[0-9]*\")\n\niteration=1000\nfor ((i=0;i<iteration;i++));\ndo\n  dbus-send --session --type=method_call \\\n            --dest=org.openbmc.TestServer \\\n            /org/openbmc/test \\\n            org.openbmc.TestInterface.HelloWorld \\\n            string:'greeting'\ndone\nkill $serverpid\nkill $dbuspid\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\neval `dbus-launch --auto-syntax`\ndbuspid=$(ps | grep dbus | grep fork | grep -o \"^ *[0-9]*\")\n./dbus-testserver &\nserverpid=$(ps | grep dbus-testserver | grep -o \"^ *[0-9]*\")\n\n./dbus-latencytest\n\nkill $serverpid\nkill $dbuspid\n", "num_lines": 11}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\neval `dbus-launch --auto-syntax`\niteration=4100\nfor ((i=1;i<iteration;i=i*2));\ndo\n  dbuspid=$(ps | grep dbus | grep fork | grep -o \"^ *[0-9]*\")\n  ./dbus-mem-testserver $i &\n  serverpid=$(echo $!)\n\n  sleep 1\n  echo $i objects: $(top -b -n 1 | grep Mem)\n  kill $serverpid\ndone\nkill $dbuspid\n", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\neval `dbus-launch --auto-syntax`\ndbuspid=$(ps | grep dbus | grep fork | grep -o \"^ *[0-9]*\")\n./dbus-interface-test &\nserverpid=$(ps | grep dbus-interface-test | grep -o \"^ *[0-9]*\")\n\nsleep 1\n\ndbus-send --session --type=method_call --print-reply \\\n          --dest=org.openbmc.TestServer \\\n            /org/openbmc/test \\\n            org.openbmc.TestInterface.Ping\n\nkill $serverpid\nkill $dbuspid\n", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-rest-api\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set REST API handler\n### END INIT INFO\n\nrunsv /etc/sv/restapi >/dev/null 2>&1 &\n# delay 0.5 seconds to avoid suprising error print like below:\n# warning: restapi: can't open supervise/control: No such file or directory\n# root casue is runit daemon is not ready.\nif [ -n \"$1\" ]; then\n    (sleep 0.5; sv \"$1\" restapi) &\nfi\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Sets up the bootargs so that we can boot with the desired chips\n# exposed.\n\nset -xeu -o pipefail\n\nif grep -q wedge100 /etc/issue\nthen\n    openbmc_gpio_util.py config ROMCS1#\nfi\n\n# If verified boot mount flash1rw as well\nif [ -f /usr/local/bin/vboot-util ]\nthen\n    if grep -q rom /proc/mtd\n    then\n        echo \"Verified boot\"\n        EXTRA_BOOTARGS=\"mtdparts=spi0.0:32M@0x0(flash0),0x20000@0x60000(env);spi0.1:32M@0x0(flash1),0x01ff0000@0x10000(flash1rw) dual_flash=1\"\n    else\n        echo \"Verified boot detected, but no ROM found\"\n        exit 1\n    fi\nelse\n    echo \"Non-verified boot\"\n    EXTRA_BOOTARGS=\"mtdparts=spi0.0:32M@0x0(flash0),0x20000@0x60000(env);spi0.1:-(flash1) dual_flash=1\";\nfi\n\nbootargs=$(fw_printenv bootargs|sed 's/bootargs=//')\nif grep -q mtdparts= <<<\"$bootargs\"\nthen\n    echo \"Bootargs already applied.\"\n    exit 0\nfi\n\nbootargs=\"${bootargs} ${EXTRA_BOOTARGS}\"\n\nfw_setenv bootargs \"${bootargs}\"\n\necho \"All set. Now go ahead and reboot!\"\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Selects the primary chip and re-flashes it with the image URL given\n# as an argument, or with the default one from yum.\n\nset -xeuo pipefail\n\nplatform=$(awk '{print $NF}' /etc/issue|cut -d- -f1)\n\nfunction default_url() {\n    echo \"http://yum/fbpkg/openbmc.image.${platform}:DEFAULT\"\n}\n\nurl=${1:-$(default_url)}\n\nif [ \"${platform}\" = \"wedge100\" ]\nthen\n    openbmc_gpio_util.py config ROMCS1#\nfi\n\ndevmem 0x1e785034 32 0x1\n\ndev=$(awk -F: '/\"flash0\"/{print $1}' /proc/mtd)\n\nwget \"$url\" -O image\n\nflashcp image \"/dev/${dev}\"\n\necho \"All flashed to a safe version! Now reboot\"\n", "num_lines": 29}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttcsd trousers\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tcsd\n# Description:\t\ttcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo \"Starting $DESC: \"\n\n    # If TPM chip has not been discovered, probe the chip here\n\t\tif [ ! -e /dev/tpm* ]\n\t\tthen\n      # Pulse resetting TPM can sometimes (rarely) cause \n      # COMe CPU to hang, if the reset sequence is performed while\n      # X86 CPU (BIOS or Kernel) is talking to TPM. So we don't\n      # pulse reset TPM here, but just turn it \"on\". (active low signal)\n      echo 1 > /sys/bus/i2c/drivers/syscpld/12-0031/tpm_lpc_rst_n\n      echo 1 > /sys/bus/i2c/drivers/syscpld/12-0031/tpm_spi_rst_n\n      # Depending on the previous state, TPM might have been in reset, \n      # so we give it enough time after waking up, so that its crypto \n      # stuff will initialize, and the chip becomes ready to access.\n      sleep 7\n      # Finally, register the device and install the driver\n      . /usr/local/bin/openbmc-utils.sh\n      i2c_device_add 9 0x20 tpm_i2c_infineon\n    fi\n\n    # Additionally, Generate symlink to tpm0 or tpm1, so that tcsd can use it\n    rm -f /dev/tpm\n\t\tif [ -e /dev/tpm0 ]\n    then\n      ln -s /dev/tpm0 /dev/tpm\n    else\n      ln -s /dev/tpm1 /dev/tpm\n    fi\n\n\t\tstart-stop-daemon --start --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 87}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n\n# Store and Clear POR bit\nstore_clear_por() {\n  if [ -f /tmp/ast_por ]; then\n    return\n  fi\n\n  soc_model=$(cat /etc/soc_model 2>/dev/null)\n\n  # default AST G4/G5\n  system_reset_reg=\"0x1e6e203c\"\n  if [ \"$soc_model\" = \"SOC_MODEL_ASPEED_G6\" ]; then\n      system_reset_reg=\"0x1e6e2074\"\n  fi\n\n  # Read the SRST Rest Flag\n  val=$(devmem \"$system_reset_reg\" 2>/dev/null)\n  if [[ \"$((val & 0x1))\" == \"1\" ]]; then\n      # Power ON Reset\n      echo 1 > /tmp/ast_por\n  else\n      echo 0 > /tmp/ast_por\n  fi\n\n  # Clear Power On Reset bit\n  devmem \"$system_reset_reg\" 32 0x1 2>/dev/null\n}\n\n# Check to see if BMC power-on-reset\nis_bmc_por() {\n  store_clear_por\n  /bin/cat /tmp/ast_por\n}\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nset -eu -o pipefail\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif [ $# -ne 2 ]; then\n    echo \"Error: invalid command line arguments!\"\n    echo \"Usage: $0 <block-device> <mount-point>\"\n    exit 1\nfi\nBLK_DEVICE=$1\nMOUNT_POINT=$2\n\nif mount | grep \"$BLK_DEVICE\"; then\n    echo \"$BLK_DEVICE is already mounted. Exiting.\"\n    exit 0\nfi\n\nSUPPORTED_FS_TYPE=\"btrfs\"\n\nmount_btrfs() {\n\n    #\n    # Use blkid to find the underlying filesystem type.\n    #\n    FS_TYPE=\"$(blkid \"$BLK_DEVICE\" || echo 'TYPE=\"unknown\"')\"\n    FS_TYPE=\"$(echo \"$FS_TYPE\" | sed 's/.*TYPE=\"\\([^\"]*\\).*/\\1/')\"\n\n    #\n    # If filesystem is not btrfs already, convert or reformat.\n    #\n    case \"$FS_TYPE\" in\n        ext4)\n            echo \"EXT4 filesystem found on $BLK_DEVICE.  Reformat as btrfs..\"\n            if ! output=\"$(mkfs.btrfs -f \"$BLK_DEVICE\" 2>&1)\"; then\n                echo \"Error: failed to format as btrfs on $BLK_DEVICE:\"\n                echo \"$output\"\n                exit 1\n            fi\n            ;;\n\n        btrfs)\n            ;;\n\n        *)\n            echo \"No filesystem found on $BLK_DEVICE. Creating btrfs fs..\"\n            if ! output=$(mkfs.btrfs -f \"$BLK_DEVICE\" 2>&1); then\n                echo \"Error: failed to create btrfs on $BLK_DEVICE:\"\n                echo \"$output\"\n                exit 1\n            fi\n            ;;\n    esac\n\n    #\n    # Run btrfs-check (same as btrfsck) to confirm filesystem integrity.\n    #\n    if ! output=\"$(btrfs check \"$BLK_DEVICE\" 2>&1)\"; then\n        echo \"Error: btrfs volume shows errors:\"\n        echo \"$output\"\n        echo \"Try to repair btrfs\"\n        if ! output=\"$(btrfs check --repair \"$BLK_DEVICE\" 2>&1)\"; then\n            echo \"Error: btrfs volume shows errors:\"\n            echo \"$output\"\n            exit 1\n        fi\n    fi\n\n    #\n    # Mount btrfs.\n    #   Use zstd compression because we get faster speed and less wear.\n    #\n    echo \"Mounting $BLK_DEVICE to $MOUNT_POINT..\"\n    if ! output=$(mount -o compress=zstd,discard \"$BLK_DEVICE\" \"$MOUNT_POINT\" 2>&1);\n    then\n        echo \"Error: failed to mount $BLK_DEVICE to $MOUNT_POINT:\"\n        echo \"$output\"\n        exit 1\n    fi\n\n    #\n    # Mount successful.  Show some usage statstics.\n    #\n    echo \"$MOUNT_POINT mounted successfully, device usage:\"\n    df -h \"$MOUNT_POINT\"\n    btrfs filesystem df \"$MOUNT_POINT\"\n    exit 0\n}\n\nmount_ext4() {\n\n    #\n    # Workaround for EMMC data lost because sometimes e2fsck detect filesystem fails\n    # if SDHCI IO fails when system boot up, add retry to avoid EMMC format by mistake.\n    #\n    maxtry=3\n    retry=0\n    while [ $retry -lt $maxtry ]; do\n        if ! e2fsck -p \"$BLK_DEVICE\" > /dev/null 2>&1; then\n            retry=$((retry + 1))\n            echo \"No filesystem found on $BLK_DEVICE try: $retry.\"\n        else\n            break\n        fi\n    done\n\n    #\n    # Create ext4 if ext filesystem is not detected or corrupted.\n    #\n    if [ $retry -eq $maxtry ]; then\n        echo \"No filesystem found on $BLK_DEVICE after $maxtry times try. Creating ext4 filesystem..\"\n        if ! output=$(mkfs.ext4 -F \"$BLK_DEVICE\" 2>&1); then\n            echo \"Error: failed to create ext4 on $BLK_DEVICE:\"\n            echo \"$output\"\n            exit 1\n        fi\n    fi\n\n    #\n    # Mount block device to specified mount point.\n    #\n    echo \"Mounting $BLK_DEVICE to $MOUNT_POINT..\"\n    if ! output=$(mount \"$BLK_DEVICE\" \"$MOUNT_POINT\" 2>&1); then\n        echo \"Error: failed to mount $BLK_DEVICE to $MOUNT_POINT:\"\n        echo \"$output\"\n        exit 1\n    fi\n\n    #\n    # Dump summary information.\n    #\n    echo \"$BLK_DEVICE mounted successfully, device usage:\"\n    df -h \"$BLK_DEVICE\"\n    exit 0\n}\n\nmount_$SUPPORTED_FS_TYPE\n", "num_lines": 156}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nubifs_mount() {\n    ubi_vol=\"$1\"\n    mnt_point=\"$2\"\n\n    echo \"ubifs_mount $ubi_vol to $mnt_point..\"\n    mount -t ubifs \"$ubi_vol\" \"$mnt_point\" -o sync,compr=zstd\n}\n\nubifs_resize() {\n    ubi_dev=\"$1\"\n    vol_id=\"$2\"\n    ubi_vol=\"${ubi_dev}_${vol_id}\"\n    mnt_point=\"$3\"\n    backup_dir=\"/tmp/mnt_data_ubifs_backup\"\n    ubi_dev_avali_leb=$(ubinfo \"$ubi_dev\" | grep \"available logical eraseblocks\" | awk -F':' '{print $2}' | awk '{print $1}')\n    ubi_vol_leb=$(ubinfo \"$ubi_vol\" | grep \"Size\" | awk -F':' '{print $2}' | awk '{print $1}')\n    new_vol_leb=$((ubi_dev_avali_leb+ubi_vol_leb))\n\n    echo \"available leb:    $ubi_dev_avali_leb\"\n    echo \"volume leb:       $ubi_vol_leb\"\n\n    if [ \"$ubi_dev_avali_leb\" -eq 0 ]; then\n        # no more avaliable LEBs\n        echo \"no more avaliable LEBs\"\n        return 0\n    fi\n\n    if ! /bin/mountpoint \"$mnt_point\"; then\n        echo \"$mnt_point is not a correct mount point\"\n        return 1\n    fi\n\n    # prepare backup data folder\n    if [ -e \"$backup_dir\" ]; then\n        echo \"backup folder already exist, please move it to safe place\"\n        echo \"backup folder: $backup_dir\"\n        return 1\n    fi\n    cp -ar \"$mnt_point\" \"$backup_dir\"\n\n    # umount mount point\n    if ! umount \"$mnt_point\"; then\n        rm -rf \"$backup_dir\"\n        echo \"umount $mnt_point failed\"\n        return 1\n    fi\n\n    # do resize\n    if ! ubirsvol \"$ubi_dev\" -n \"$vol_id\" -S \"$new_vol_leb\"; then\n        echo \"ubifs volume resize failed (ubirsvol), err_code: $?\"\n    elif ! mkfs.ubifs -y -r \"$backup_dir\" \"$ubi_vol\"; then\n        echo \"ubifs volume resize failed (mkfs.ubifs), err_code: $?\"\n    elif ! ubifs_mount \"$ubi_vol\" \"$mnt_point\"; then\n        echo \"ubifs volume resize failed (ubifs_mount), err_code: $?\"\n    else\n        # resize done\n        echo \"ubifs volume resize done, vol: $ubi_vol, origin LEBs: $ubi_vol_leb, new LEBs: $new_vol_leb\"\n        rm -rf \"$backup_dir\"\n        return 0\n    fi\n\n    # undo resize\n    if ! ubirsvol \"$ubi_dev\" -n \"$vol_id\" -S \"$ubi_vol_leb\"; then\n        echo \"ubifs volume undo resize failed (ubirsvol), err_code: $?\"\n    elif ! mkfs.ubifs -y -r \"$backup_dir\" \"$ubi_vol\"; then\n        echo \"ubifs volume undo resize failed (mkfs.ubifs), err_code: $?\"\n    elif ! ubifs_mount \"$ubi_vol\" \"$mnt_point\"; then\n        echo \"ubifs volume undo resize failed (ubifs_mount), err_code: $?\"\n    else\n        # undo resize done\n        echo \"ubifs volume undo resize done, vol: $ubi_vol, LEBs: $ubi_vol_leb\"\n        rm -rf \"$backup_dir\"\n        return 0\n    fi\n\n    # undo reise failed\n    echo \"undo resize failed, backup folder: $backup_dir\"\n    return 1\n}\n\n/usr/bin/killall rsyslogd\n\nubifs_resize /dev/ubi0 0 /mnt/data\nret_val=$?\n\n/usr/sbin/rsyslogd\nexit $ret_val\n", "num_lines": 90}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nset -eu -o pipefail\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif [ $# -ne 1 ]; then\n    echo \"Error: invalid command line arguments!\"\n    echo \"Usage: $0 <mount-point>\"\n    exit 1\nfi\nMOUNT_POINT=$1\nMMC_DEVICE=\"/dev/mmcblk0\"\nMOUNT_SCRIPT=\"/usr/local/bin/blkdev_mount.sh\"\n\n#\n# We provide people a way to disable/skip the script by setting u-boot\n# environment variable, and it's mainly intended for cases when something\n# is wrong with emmc driver/device.\n#\nemmc_mount_precheck() {\n    lock_dir=\"/run/lock\"\n    link_path=\"/var/lock\"\n\n    #\n    # the script may be triggered when \"/var/lock\" is not populated, so\n    # let's manually create the directories to avoid fw_printenv failure\n    # when creating \"/var/lock/fw_printenv.lock\".\n    #\n    if [ ! -d \"$lock_dir\" ]; then\n        if ! output=$(mkdir -p \"$lock_dir\"); then\n            echo \"Error: failed to create $lock_dir:\"\n            echo \"$output\"\n            exit 1\n        fi\n    fi\n    if [ ! -L \"$link_path\" ]; then\n        if ! output=$(ln -s \"$lock_dir\" \"$link_path\"); then\n            echo \"Error: failed to create symlink $link_path:\"\n            echo \"$output\"\n            exit 1\n        fi\n    fi\n\n    if fw_printenv | grep \"emmc_auto_mount=no\" > /dev/null 2>&1; then\n        echo \"emmc_auto_mount is disabled by uboot env. Skip emmc mount.\"\n        exit 0\n    fi\n\n    if [ \"x$(kv get emmc_auto_mount persistent || true)\" = \"xno\" ]; then\n        echo \"emmc_auto_mount is disabled by persistent kv. Skip emmc mount.\"\n        exit 0\n    fi\n\n    if [ \"x$(kv get emmc_auto_mount || true)\" = \"xno\" ]; then\n        echo \"emmc_auto_mount is disabled by temporary kv. Skip emmc mount.\"\n        exit 0\n    fi\n}\n\nemmc_mount_precheck\n\n#\n# timeout \"-t\" option is removed since Busybox version v1.30.0, so we\n# need to get rid of \"-t\" from all yocto-warrior platforms (Busybox\n# v1.30.1), but the option is still needed for all yocto-rocko platforms\n# (without Busybox v1.24.1).\n# MOUNT_SCRIPT takes ~25 seconds if ext4 filesystem needs to be created,\n# so 60 seconds timeout value is long enough.\n#\nMOUNT_TIMEOUT=60\nif timeout --help 2>&1 | grep \"Usage:.*\\[\\-t \" > /dev/null 2>&1; then\n    timeout -t \"$MOUNT_TIMEOUT\" \"$MOUNT_SCRIPT\" \"$MMC_DEVICE\" \"$MOUNT_POINT\"\nelse\n    timeout \"$MOUNT_TIMEOUT\" \"$MOUNT_SCRIPT\" \"$MMC_DEVICE\" \"$MOUNT_POINT\"\nfi\n\n# Create the rsyslog directory, in case it doesn't exist.\nmkdir -p \"$MOUNT_POINT/log\"\n", "num_lines": 97}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nshow_usage() {\n  echo \"Error  : invalid command line arguments!\"\n  echo \"Usage  : $0 <mmc_device>\"\n  echo \"Example: $0 /dev/mmcblk0\"\n  exit -1\n}\nif [[ $# -ne 1 ]] || ! [[ -e $1 ]]; then\n  show_usage\nfi\nMMC_DEVICE=$1\n\numount /mnt/data1 > /dev/null\n\nemmc_config_extcsd() {\n  # Configure pSLC mode\n  vendor=$(mmc cid read /sys/class/mmc_host/mmc0/mmc0\\:0001/ | grep manufacturer | cut -d \" \" -f 2)\n  if [[ \"$vendor\" = \"'Micron'\" ]]; then\n    # Refer Micron document TN-FC-40\n    val=$(mmc extcsd read $MMC_DEVICE | grep PARTITIONING_SUPPORT)\n    val=${val:0-4}\n    partitioning_sup=$((val%2))\n    enhanced_sup=$((val/2%2))\n    if [[ \"$partitioning_sup\" != \"1\" ]] || [[ \"$enhanced_sup\" != \"1\" ]]; then\n      echo \"This eMMC don't support partitioning.\"\n      return\n    fi\n\n    completed=$(mmc extcsd read $MMC_DEVICE | grep PARTITION_SETTING_COMPLETED)\n    completed=${completed:0-4}\n    if [[ \"$completed\" == \"0x01\" ]]; then\n      echo \"Partitioning had been done\"\n      exit 0\n    fi\n    echo \"Configure eMMC partitions\"\n    # Set ERASE_GROUP_DEF to 1\n    mmcraw -o 175 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null\n    # Set ENH_START_ADDR to 0\n    mmcraw -o 136 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null\n    mmcraw -o 137 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null\n    mmcraw -o 138 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null\n    mmcraw -o 139 -D 0x0 write-extcsd $MMC_DEVICE > /dev/null\n    # Set ENH_SIZE_MULT to MAX_ENH_SIZE_MULT\n    max_enh_size_mult=$(mmc extcsd read $MMC_DEVICE | grep MAX_ENH_SIZE_MULT)\n    max_enh_size_mult0=0x${max_enh_size_mult:0-2}\n    max_enh_size_mult1=0x${max_enh_size_mult:0-4:2}\n    max_enh_size_mult2=0x${max_enh_size_mult:0-6:2}\n    mmcraw -o 140 -D $max_enh_size_mult0 write-extcsd $MMC_DEVICE > /dev/null\n    mmcraw -o 141 -D $max_enh_size_mult1 write-extcsd $MMC_DEVICE > /dev/null\n    mmcraw -o 142 -D $max_enh_size_mult2 write-extcsd $MMC_DEVICE > /dev/null\n    # Set ENH_USR to 1\n    mmcraw -o 156 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null\n    # Set PARTITIONING_SETTING_COMPLETED to 1\n    mmcraw -o 155 -D 0x1 write-extcsd $MMC_DEVICE > /dev/null\n  else\n    echo \"The manufacturer $vendor is not supported\"\n  fi\n  # Disable cache\n  cache_ctl=$(mmc extcsd read $MMC_DEVICE | grep CACHE_CTRL)\n  cache_ctl=${cache_ctl:0-4}\n  if [[ $cache == \"0x01\" ]]; then\n    echo \"Disable eMMC cache\"\n    mmc cache disable > /dev/null\n  fi\n}\nemmc_config_extcsd\n\necho \"WARNING: Do chassis cycle to apply the enhancement\"\n", "num_lines": 89}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n# get the MAC from EEPROM\nif [ \"$(LC_ALL=C type -t bmc_mac_addr)\" = function ]; then\n    mac=$(bmc_mac_addr)\nelse\n    mac=$(weutil  | grep '^Local MAC' | cut -d' ' -f3)\nfi\n\n# get the MAC from u-boot environment\nethaddr=$(fw_printenv | grep \"^ethaddr=\" | cut -d'=' -f2)\n\nif [ -z \"$mac\" ]; then\n    if [ -n \"$ethaddr\" ]; then\n        # no MAC from EEPROM, use the one from u-boot environment\n        echo \"No MAC address from EEPROM: use $ethaddr from uboot-env\"\n        mac=\"$ethaddr\"\n    else\n        echo \"Error: unable to read MAC address from EEPROM or uboot-env!\"\n        exit 1\n    fi\nfi\n\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    # set the MAC from EEPROM back to u-boot environment so that\n    # u-boot can use it\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n\n#ifconfig eth0 hw ether $macifconfig\necho \"Update BMC eth0 MAC address to $mac\"\nip link set dev eth0 address \"$mac\"\nexit $?\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#\n# The file contains helper functions to parse flashrom output.\n#\n# Sample flashrom command output:\n#\n#   root@bmc:~# flashrom -p linux_spi:dev=/dev/spidev1.0\n#   flashrom v1.0 on Linux 5.10.5-minipack (armv6l)\n#   flashrom is free software, get the source code at https://flashrom.org\n#\n#   Using clock_gettime for delay loops (clk_id: 1, resolution: 1ns).\n#   Found Winbond flash chip \"W25Q128.V\" (16384 kB, SPI) on linux_spi.\n#   No operations were specified.\n#\n\n#\n# Generate spidev device name in <spidev#.#> format.\n#\n# $1 - spi bus number\n# $2 - spi device address\n#\nflash_device_name() {\n    echo \"spidev${1}.${2}\"\n}\n\n#\n# Wrapper function to launch flashrom command.\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n# $@ - extra options passed to flashrom command\n#\nflashrom_cmd() {\n    spi_dev=\"$1\"\n    shift\n\n    flashrom -p linux_spi:dev=/dev/\"$spi_dev\" $@\n}\n\n#\n# Dump flash summary by running flashrom.\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n#\nflash_dump_summary() {\n    flashrom_cmd \"$1\"\n}\n\n#\n# Extract flash information from flashrom output.\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n#\nflash_extract_info() {\n    summary=$(flash_dump_summary \"$1\")\n    info=$(echo \"$summary\" | grep -E \"Found.*flash.*linux_spi\")\n    if [ -z \"$info\" ]; then\n        echo \"Unable to extract flash info! flashrom output:\"\n        echo \"$summary\"\n        return 1\n    fi\n\n    echo \"$info\"\n}\n\n#\n# Read flash vendor from flashrom output.\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n#\nflash_get_vendor() {\n    if ! info=$(flash_extract_info \"$1\"); then\n        return 1\n    fi\n\n    vendor=$(echo \"$info\" | cut -d ' ' -f 2)\n    if [ -z \"$vendor\" ]; then\n        echo \"Unable to determine flash vendor! flashrom output:\"\n        flash_dump_summary \"$1\"\n        return 1\n    fi\n\n    echo \"$vendor\"\n}\n\n#\n# Read flash model from flashrom output.\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n#\nflash_get_model() {\n    if ! info=$(flash_extract_info \"$1\"); then\n        return 1\n    fi\n\n    model=$(echo \"$info\" | cut -d '\"' -f 2)\n    if [ -z \"$model\" ]; then\n        echo \"Unable to determine flash model! flashrom output:\"\n        flash_dump_summary \"$1\"\n        return 1\n    fi\n\n    echo \"$model\"\n}\n\n#\n# Helper function to check if given input is a decimal number.\n#\n# $1 - decimal number.\n#\nis_decimal() {\n    echo \"$size\" | grep -E -q '^[0-9]+$' > /dev/null 2>&1\n}\n\n#\n# Read flash size from flashrom output (unit: kb).\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n#\nflash_get_size() {\n    if ! info=$(flash_extract_info \"$1\"); then\n        return 1\n    fi\n\n    size=$(echo \"$info\" | cut -d '(' -f 2 | cut -d ' ' -f 1)\n    if ! is_decimal \"$size\"; then\n        echo \"Unable to determine flash size! flashrom output:\"\n        flash_dump_summary \"$1\"\n        return 1\n    fi\n\n    echo \"$size\"\n}\n\n#\n# Read the flash ($1) and store content in the given file ($2).\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n# $2 - file name/path to store the flash content.\n# $3 - flash model, optional.\n#\nflash_read() {\n    spi_dev=\"$1\"\n    image_file=\"$2\"\n\n    if [ -n \"$3\" ]; then\n        model=\"$3\"\n    else\n        if ! model=$(flash_get_model \"$spi_dev\"); then\n            return 1\n        fi\n    fi\n\n    flashrom_cmd \"$spi_dev\" -r \"$image_file\" -c \"$model\"\n}\n\n#\n# Write the file ($2) to the given flash ($1).\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n# $2 - file name/path containing the flash image.\n# $3 - flash model, optional.\n#\nflash_write() {\n    spi_dev=\"$1\"\n    image_file=\"$2\"\n\n    if [ ! -e \"$image_file\" ]; then\n        echo \"Error: image file $image_file does not exist!\"\n        return 1\n    fi\n\n    if [ -n \"$3\" ]; then\n        model=\"$3\"\n    else\n        if ! model=$(flash_get_model \"$spi_dev\"); then\n            return 1\n        fi\n    fi\n\n    flashrom_cmd \"$spi_dev\" -w \"$image_file\" -c \"$model\"\n}\n\n#\n# Erase the given flash ($1).\n#\n# $1 - spi device name in \"spidev#.#\" format. For example, \"spidev1.0\".\n# $3 - flash model, optional.\n#\nflash_erase() {\n    spi_dev=\"$1\"\n\n    if [ -n \"$2\" ]; then\n        model=\"$2\"\n    else\n        if ! model=$(flash_get_model \"$spi_dev\"); then\n            return 1\n        fi\n    fi\n\n    flashrom_cmd \"$spi_dev\" -E -c \"$model\"\n}\n", "num_lines": 218}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nGPIODIR=\"/sys/class/gpio\"\nGPIOEXPORT=\"$GPIODIR/export\"\nSHADOW_GPIO=/tmp/gpionames\nGPIOCLI_CMD=/usr/local/bin/gpiocli\n\n# Name of ASPEED GPIO Controller, usually used by gpiocli command.\nASPEED_GPIO=\"aspeed-gpio\"\n\ngpio_dir() {\n    echo \"$GPIODIR/gpio$1\"\n}\n\ngpio_name2value() {\n    local first remaining base val\n    remaining=$1\n    base=\"${SHADOW_GPIO}/${remaining}\"\n    if [ -L \"${base}\" ]; then\n        val=$(readlink -f ${base} 2>/dev/null)\n        if [ -n \"${val}\" ]; then\n            val=${val##*gpio}\n            if [ -n \"${val}\" ]; then\n                echo \"$val\"\n                return\n            fi\n        fi\n    fi\n    val=0\n    while [ -n \"$remaining\" ]; do\n        first=${remaining:0:1}\n        case \"$first\" in\n            [[:lower:]])\n                base=$(printf \"%d\" \"'$first'\")\n                base=$((base - 96))\n                val=$((val * 26 + base))\n                ;;\n            [[:upper:]])\n                base=$(printf \"%d\" \"'$first'\")\n                base=$((base - 64))\n                val=$((val * 26 + base))\n                ;;\n            *)\n                if [ $val -gt 0 ]; then\n                    val=$((val-1))\n                fi\n                val=$((val * 8 + $remaining))\n                break\n                ;;\n        esac\n        remaining=${remaining:1}\n    done\n    echo \"$val\"\n}\n\ngpio_export() {\n    local gpio\n    gpio=$(gpio_name2value $1)\n    dir=$(gpio_dir $gpio)\n    if [ ! -d ${dir} ]; then\n        echo $gpio > $GPIOEXPORT\n    fi\n    if [ $# -gt 1 ]; then\n        if [ ! -d  $SHADOW_GPIO ]; then\n            mkdir -p $SHADOW_GPIO\n        fi\n        ln -s $dir $SHADOW_GPIO/$2\n    fi\n}\n\ngpio_export_by_name() {\n    local chip=$1\n    local name=$2\n    local shadow=$3\n\n    echo \"exporting gpio (${chip}, ${name}), shadow=${shadow}\"\n    $GPIOCLI_CMD --chip ${chip} --pin-name ${name} --shadow ${shadow} export\n}\n\ngpio_export_by_offset() {\n    local chip=$1\n    local offset=$2\n    local shadow=$3\n\n    echo \"exporting gpio (${chip}, ${offset}), shadow=${shadow}\"\n    $GPIOCLI_CMD --chip ${chip} --pin-offset ${offset} --shadow ${shadow} export\n}\n\ngpio_unexport() {\n    local shadow=$1\n\n    echo \"unexporting gpio ${shadow}\"\n    $GPIOCLI_CMD --shadow ${shadow} unexport\n}\n\ngpio_set() {\n    local gpio\n    local val\n    gpio=$(gpio_name2value $1)\n    val=$2\n    dir=$(gpio_dir $gpio)\n    if [ ! -d ${dir} ]; then\n        echo $gpio > $GPIOEXPORT\n    fi\n    if [ $val -eq 0 ]; then\n        echo low > ${dir}/direction\n    else\n        echo high > ${dir}/direction\n    fi\n}\n\ngpio_get() {\n    local gpio\n    local val\n    local keepdirection\n    gpio=$(gpio_name2value $1)\n    dir=$(gpio_dir $gpio)\n    keepdirection=\"$2\"\n    if [ ! -d ${dir} ]; then\n        echo $gpio > $GPIOEXPORT\n    fi\n    if [ \"$keepdirection\" != \"keepdirection\" ]; then\n        echo in > ${dir}/direction\n    fi\n    cat ${dir}/value\n}\n\n#\n# Set gpio pin with the given value.\n# $1 - GPIO pin shadow name\n# $2 - GPIO value\n#\ngpio_set_value() {\n    local shadow=\"$1\"\n    local value=\"$2\"\n\n    \"${GPIOCLI_CMD}\" --shadow \"${shadow}\" set-init-value \"${value}\"\n}\n\n#\n# Get value of the given gpio pin.\n# $1 - GPIO pin shadow name\n#\ngpio_get_value() {\n    local shadow=\"$1\"\n\n    val=$(\"${GPIOCLI_CMD}\" --shadow \"${shadow}\" get-value)\n    if [ \"$?\" == \"0\" ]; then\n        echo \"${val}\" | cut -d'=' -f2\n    fi\n}\n\n#\n# Set the GPIO pin with given direction.\n# $1 - GPIO pin shadow name\n# $2 - GPIO pin direction: \"in\" or \"out\"\n#\ngpio_set_direction() {\n    local shadow=\"$1\"\n    local direction=\"$2\"\n\n    \"${GPIOCLI_CMD}\" --shadow \"${shadow}\" set-direction \"${direction}\"\n}\n\n#\n# Get the direction of given GPIO pin.\n# $1 - GPIO pin shadow name\n#\ngpio_get_direction() {\n    local shadow=\"$1\"\n\n    dir=$(\"${GPIOCLI_CMD}\" --shadow \"${shadow}\" get-direction)\n    if [ \"$?\" == \"0\" ]; then\n        echo \"${dir}\" | cut -d'=' -f2\n    fi\n}\n\n#\n# Lookup sysfs \"gpiochip###\" directory based on chip label.\n# $1 - gpiochip label\n#\ngpiochip_lookup_by_label() {\n    local input_label=${1}\n    local label entry\n\n    for entry in \"${GPIODIR}\"/gpiochip* ; do\n        label=$(cat \"${entry}/label\")\n        if [ \"${label}\" = \"${input_label}\" ]; then\n            basename \"$entry\"\n            return\n        fi\n    done\n}\n\n#\n# Lookup sysfs \"gpiochip###\" directory based on i2c path (of the\n# io expander).\n# $1 - i2c device path in <bus-addr> format. For example: 30-0021\n#\ngpiochip_lookup_by_i2c_path() {\n    local i2c_path=${1}\n    local entry link_path\n\n    for entry in \"${GPIODIR}\"/gpiochip* ; do\n        link_path=$(readlink -f \"$entry\" 2>/dev/null)\n        if [[ ${link_path} == *i2c*/${i2c_path}/* ]]; then\n            basename \"$entry\"\n            return\n        fi\n    done\n}\n\n#\n# Get base pin number managed by the given gpio chip.\n# $1 - gpiochip sysfs directory. For example, \"gpiochip400\".\n#\ngpiochip_get_base() {\n    local chip=${1}\n    local chip_dir=\"${GPIODIR}/${chip}\"\n\n    if [ -L ${chip_dir} ]; then\n       cat ${chip_dir}/base\n    fi\n}\n", "num_lines": 241}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nSYSFS_I2C_ROOT=\"/sys/bus/i2c\"\nSYSFS_I2C_DEVICES=\"${SYSFS_I2C_ROOT}/devices\"\nSYSFS_I2C_DRIVERS=\"${SYSFS_I2C_ROOT}/drivers\"\n\n#\n# Return the given i2c device's absolute sysfs path.\n# $1 - i2c device in <bus>-00<add> format (for example 0-0050).\n#\ni2c_device_sysfs_abspath() {\n    echo \"${SYSFS_I2C_DEVICES}/${1}\"\n}\n\n#\n# instantiate an i2c device.\n# $1 - parent bus number\n# $2 - device address\n# $3 - device name/type\n#\ni2c_device_add() {\n    bus=$\"$1\"\n    addr=\"$2\"\n    device=\"$3\"\n    echo \"$device\" \"$addr\" > \"${SYSFS_I2C_DEVICES}/i2c-${bus}/new_device\"\n}\n\n#\n# delete an i2c device.\n# $1 - parent bus number\n# $2 - device address\n#\ni2c_device_delete() {\n    bus=$\"$1\"\n    addr=\"$2\"\n    echo \"$addr\" > \"${SYSFS_I2C_DEVICES}/i2c-${bus}/delete_device\"\n}\n\n#\n# Create message-queue i2c slave backend for the given i2c master.\n# $1 - i2c bus number\n# $2 - slave device address\n#\ni2c_mslave_add() {\n    bus=$1\n    addr=$2\n\n    addr=$((addr | 0x1000))\n    i2c_device_add \"$bus\" \"$addr\" slave-mqueue\n}\n\n#\n# instantiate an i2c-mux device and wait untill all its child buses\n# are initialized before the function returns.\n# $1 - parent bus number\n# $2 - i2c-mux device address\n# $3 - i2c-mux device name/type\n# $4 - total number of channels provided by the i2c-mux\n#\ni2c_mux_add_sync() {\n    bus=\"$1\"\n    addr=\"$2\"\n    name=\"$3\"\n    nchans=\"$4\"\n\n    i2c_device_add \"$bus\" \"$addr\" \"$name\"\n\n    retry=0\n    format_addr=$(printf \"%04x\" \"$addr\")\n    dev_entry=\"${bus}-${format_addr}\"\n    nchans=$((nchans - 1))\n    last_channel=\"${SYSFS_I2C_DEVICES}/${dev_entry}/channel-${nchans}\"\n    until [ -d \"${last_channel}\" ]; do\n        usleep 10000 # sleep for 10 milliseconds\n\n        retry=$((retry + 1))\n        if [ \"$retry\" -ge 10 ]; then\n            echo \"failed to create child buses for i2c-mux $dev_entry!\"\n            return 1\n        fi\n    done\n\n    return 0\n}\n\n#\n# Lookup i2c driver based on device name.\n# $1 - device name\n#\ni2c_driver_map() {\n    local device_name=$1\n\n    case ${device_name} in\n        \"24c64\" | \"24c32\" | \"24c16\" | \"24c08\" | \"24c04\" | \"24c02\" | \"24c01\" | \"24c00\")\n            echo \"at24\";;\n        \"adm1278\")\n            echo \"adm1275\";;\n        \"adm1266\")\n            echo \"adm1266\";;\n        \"tmp75\" | \"lm75\" | \"tmp1075\")\n            echo \"lm75\";;\n        \"tmp421\" | \"tmp422\")\n            echo \"tmp421\";;\n        \"pca9505\" | \"pca9534\" | \"pca9535\")\n            echo \"pca953x\";;\n        \"pca9548\")\n            echo \"pca954x\";;\n        \"pfe1100\" | \"pfe3000\")\n            echo \"bel-pfe\";;\n        \"fancpld\")\n            echo \"fancpld\";;\n        \"cmmcpld\")\n            echo \"cmmcpld\";;\n        \"mp2975\" | \"mp2978\")\n            echo \"mp2975\";;\n        \"lm25066\")\n            echo \"lm25066\";;\n        \"ucd90160\" | \"ucd90124\")\n            echo \"ucd9000\";;\n        \"xdpe132g5c\")\n            echo \"xdpe132g5c\";;\n        \"ir35215\")\n            echo \"ir35215\";;\n        \"xdpe12284\")\n            echo \"xdpe12284\";;\n        \"pxe1211\")\n            echo \"pxe1610\";;\n        *)\n            echo \"\";;\n    esac\n}\n\n#\n# Trigger driver binding manually\n# $1 - driver name\n# $2 - device path in <bus>-00<addr> format.\n# $3 - retry count, optional argument (default 1: no retry).\n#\ni2c_bind_driver() {\n    driver_name=\"$1\"\n    i2c_device=\"$2\"\n    driver_dir=\"${SYSFS_I2C_DRIVERS}/${driver_name}\"\n\n    if [ -n \"$3\" ]; then\n        retries=\"$3\"\n    else\n        retries=1\n    fi\n\n    if [ ! -d ${driver_dir} ]; then\n        echo \"unable to locate i2c driver ${driver_name} in sysfs\"\n        return 1\n    fi\n\n    retry=0\n    while [ \"$retry\" -lt \"$retries\" ]; do\n        if echo \"${i2c_device}\" > \"${driver_dir}/bind\"; then\n            return 0\n        fi\n\n        usleep 50000  # sleep for 50 milliseconds\n        retry=$((retry + 1))\n    done\n\n    return 1\n}\n\n#\n# The function goes through all i2c devices and check if some devices\n# are not claimed by drivers (due to scheduling delay, missing drivers,\n# intermittent i2c transaction errors in device_probe() function, and\n# etc.).\n# $1 - \"fix-binding\" flag. Optional argument: if $1 is \"fix-binding\",\n#      the function will try to lookup drivers and fix driver binding.\n#      Otherwise, nothing is done for \"missing-driver\" devices.\n# $2 - retry count. It defines number of retries in case of driver\n#      binding failures.\n#\ni2c_check_driver_binding() {\n    errors=0\n    errors_fixed=0\n    total_devs=0\n\n    if [ -n \"$1\" ] && [ \"$1\" = \"fix-binding\" ]; then\n        fix_binding=1\n    fi\n    if [ -n \"$2\" ]; then\n        retries=\"$2\"\n    else\n        retries=1\n    fi\n\n    echo \"checking i2c driver binding status\"\n    for dev_path in \"${SYSFS_I2C_DEVICES}\"/*-00*; do\n        total_devs=$((total_devs + 1))\n\n        if [ -L \"${dev_path}/driver\" ]; then\n            continue # bound to driver successfully\n        fi\n\n        errors=$((errors + 1))\n        dev_uid=$(basename \"$dev_path\")\n        dev_name=$(cat \"${dev_path}/name\")\n        echo \"${dev_uid} (${dev_name}) - no driver bound\"\n\n        # Try to manually bind the device.\n        if [ -n \"${fix_binding}\" ]; then\n            driver_name=$(i2c_driver_map \"${dev_name}\")\n            if [ -z \"${driver_name}\" ]; then\n                echo \"unable to find driver for ${dev_uid}\"\n                continue\n            fi\n\n            echo \"manually bind ${dev_uid} to driver ${driver_name}\"\n            if i2c_bind_driver \"${driver_name}\" \"${dev_uid}\" \"$retries\"; then\n                errors_fixed=$((errors_fixed + 1))\n            fi\n        fi\n    done\n\n    # Dump driver binding summary.\n    errors=$((errors - errors_fixed))\n    sum_info=\"total ${total_devs} i2c devices checked\"\n    if [ ${errors} -eq 0 ]; then\n        result_info=\"all bound to drivers\"\n    else\n        result_info=\"${errors} devices without drivers\"\n    fi\n    if [ \"$errors_fixed\" -gt 0 ]; then\n        result_info=\"${result_info} ($errors_fixed manually fixed)\"\n    fi\n    echo \"${sum_info}: ${result_info}\"\n}\n", "num_lines": 249}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          mount_data0\n# Required-Start:    mountvirtfs\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Mount data0 partition from flash chip.\n# Description:\n### END INIT INFO\n\n# shellcheck disable=SC1091\nif [ -f /etc/default/rcS ]; then\n    . /etc/default/rcS\nfi\n\n#\n# The default filesystem type is jffs2, but people can override it by\n# adding \"mtd-ubifs\" to MACHINE_FEATURES.\n#\nFLASH_FS_TYPE=jffs2\n\nMOUNT_POINT=\"/mnt/data\"\n\nmtd_lookup_data_partition() {\n    dev_data0=$(cat /proc/mtd |\n                awk '{ if ($4 == \"\\\"data0\\\"\") print $1 }' |\n                cut -d ':' -f 1)\n    if [ -n \"$dev_data0\" ]; then\n        echo \"$dev_data0\"\n    else\n        dev_dataro=$(cat /proc/mtd |\n                     awk '{ if ($4 == \"\\\"dataro\\\"\") print $1 }' |\n                     cut -d ':' -f 1)\n        echo \"$dev_dataro\"\n    fi\n}\n\n#\n# Sanity check if directories and files are corrupted after mount. The\n# function can be called regardless of fs type.\n#\nmnt_point_health_check() {\n    mnt_error=0\n    mnt_point=\"$1\"\n\n    #\n    # Failing to list root directory is definitely not acceptable.\n    #\n    if ! ls \"$mnt_point\" > /dev/null 2>&1; then\n        echo \"$FLASH_FS_TYPE health check error: unable to list root directory!\"\n        mnt_error=$((mnt_error+1))\n    fi\n\n    #\n    # We've seen several instances of corrupted /mnt/data/etc on Minipack\n    # and CMM BMC: somehow /mnt/data/etc is interpreted as a regular file\n    # instead of a directory, and people lost connection to BMC in this\n    # condition because sshd cannot be started.\n    #\n    persist_etc=\"${mnt_point}/etc\"\n    if [ -e \"$persist_etc\" ] && [ ! -d \"$persist_etc\" ] ; then\n        echo \"$FLASH_FS_TYPE health check error: $persist_etc corrupted (not a directory)!\"\n        mnt_error=$((mnt_error+1))\n    fi\n\n    return \"$mnt_error\"\n}\n\nget_reboot_cause_addr() {\n    data_type=$1\n    soc_model=$(cat /etc/soc_model)\n\n    if [ \"$soc_model\" == \"SOC_MODEL_ASPEED_G6\" ]; then\n        # ast_g6\n        # sram reboot base:     0x10015000\n        # sram reboot offset:   0xC00\n        # cmd offset:           0x4\n        # sig offset:           0x8\n        if [ \"$data_type\" == \"cmd\" ]; then\n            echo \"0x10015C04\"\n        elif [ \"$data_type\" == \"sig\" ]; then\n            echo \"0x10015C08\"\n        fi\n    else\n        # ast_g5 & ast_g4\n        # sram reboot base:     0x1E721000\n        # sram reboot offset:   0x200\n        # reboot cmd offset:    0x4\n        # sig offset:           0x8\n        if [ \"$data_type\" == \"cmd\" ]; then\n            echo \"0x1E721204\"\n        elif [ \"$data_type\" == \"sig\" ]; then\n            echo \"0x1E721208\"\n        fi\n    fi\n}\n\nis_ubifs_error_set() {\n    BOOT_MAGIC=\"0xFB420054\"\n    reboot_sig_addr=$(get_reboot_cause_addr sig)\n    reboot_sig_val=$(devmem $reboot_sig_addr 2>/dev/null)\n    if [ \"$reboot_sig_val\" != \"$BOOT_MAGIC\" ]; then\n        # Power on reset\n        return 1\n    fi\n\n    # Read reboot command flags\n    reboot_cmd_addr=$(get_reboot_cause_addr cmd)\n    reboot_cmd_flags=$(devmem $reboot_cmd_addr 2>/dev/null)\n    if [ \"$((reboot_cmd_flags & 0x4))\" -eq 0 ]; then\n        # UBIFS_ERROR not set\n        return 1\n    fi\n\n    # UBIFS_ERROR is set\n    return 0\n}\n\nubifs_format() {\n    mtd_chardev=\"$1\"\n    ubi_dev=\"$2\"\n\n    if ubinfo \"$ubi_dev\" > /dev/null; then\n        if ! ubidetach -p \"$mtd_chardev\"; then\n            return 1\n        fi\n    fi\n\n    if ! ubiformat -y \"$mtd_chardev\"; then\n        return 1\n    fi\n\n    if ! ubiattach -p \"$mtd_chardev\"; then\n        return 1\n    fi\n\n    if ! ubimkvol \"$ubi_dev\" -N data0 -m; then\n        return 1\n    fi\n}\n\nubifs_mount() {\n    ubi_vol=\"$1\"\n    mnt_point=\"$2\"\n\n    echo \"ubifs_mount $ubi_vol to $mnt_point..\"\n    mount -t ubifs \"$ubi_vol\" \"$mnt_point\" -o sync,compr=zstd\n}\n\ndo_mount_ubifs() {\n    mtd_chardev=\"$1\"\n    mnt_point=\"$2\"\n    ubi_dev=\"/dev/ubi0\"\n    ubi_vol=\"${ubi_dev}_0\"\n    need_recovery=0\n\n    #\n    # Blindly load ubi module just in case it's compiled as a module.\n    # Ignore modprobe failures and we will run more check later.\n    #\n    modprobe ubi mtd=data0 > /dev/null 2>&1\n\n    #\n    # Attached ubi device manually if ubi is compiled into kernel but\n    # \"ubi.mtd=data0\" bootargs is not supplied.\n    #\n    if ! [ -e \"$ubi_dev\" ]; then\n        ubiattach -p \"$mtd_chardev\"\n        # Fall through regardless of attach results: we will start\n        # filesystem recovery if the ubi volume doesn't show up after\n        # attach.\n    fi\n\n    #\n    # ubifs \"recovery\" is needed when:\n    #   1) the mtd partition is never formatted, for example, when people\n    #      migrate a BMC from jffs2 to ubifs for the first time.\n    #   2) the mtd partition or ubi volume is corrupted for some reasons.\n    #\n    if is_ubifs_error_set; then\n        echo \"UBIFS ERROR flag is set, start recovery..\"\n        need_recovery=1\n    elif [ -e \"$ubi_vol\" ]; then\n        if ubifs_mount \"$ubi_vol\" \"$mnt_point\"; then\n            echo \"Check ubifs filesystem health on $ubi_vol..\"\n\n            if ! mnt_point_health_check \"$mnt_point\"; then\n                need_recovery=$((need_recovery+1))\n            fi\n\n            if [ \"$need_recovery\" -gt 0 ]; then\n                echo \"ubifs health check failed. Unmount $ubi_vol and start recovery..\"\n                umount \"$mnt_point\"\n                ubidetach -p \"$mtd_chardev\"\n            else\n                echo \"ubifs health check passed: no error found.\"\n            fi\n        else\n            echo \"unable to mount $ubi_vol. Start recovery soon..\"\n            need_recovery=1\n        fi\n    else\n        echo \"$ubi_vol does not exist. Start recovery soon..\"\n        need_recovery=1\n    fi\n\n    if [ \"$need_recovery\" -gt 0 ]; then\n        if ! ubifs_format \"$mtd_chardev\" \"$ubi_dev\"; then\n            echo \"ubifs_format failed. Exiting!\"\n            exit 1\n        fi\n\n        if ! ubifs_mount \"$ubi_vol\" \"$mnt_point\"; then\n            echo \"ubifs_mount failed after recovery. Exiting!\"\n            exit 1\n        fi\n    fi\n}\n\njffs2_format() {\n    mtd_chardev=\"$1\"\n\n    echo \"Create jffs2 filesystem on $mtd_chardev..\"\n    flash_eraseall -j \"$mtd_chardev\"\n}\n\njffs2_mount() {\n    mtd_blkdev=\"$1\"\n    mnt_point=\"$2\"\n\n    echo \"jffs2_mount $mtd_blkdev to $mnt_point..\"\n    mount -t jffs2 \"$mtd_blkdev\" \"$mnt_point\"\n}\n\njffs2_health_check() {\n    #\n    # If JFFS2 prints below messages at mount time, then probably the\n    # filesystem is corrupted. Although mount may still return \"success\",\n    # the file structure/content can be corrupted in this case.\n    # For details, please refer to:\n    # http://www.linux-mtd.infradead.org/faq/jffs2.html\n    #\n    if dmesg | grep \"jffs2.*: Magic bitmask.*not found\" > /dev/null 2>&1; then\n        echo \"jffs2 health check error: <Magic bitmask not found> reported!\"\n        return 1\n    fi\n\n    return 0\n}\n\ndo_mount_jffs2() {\n    mtd_chardev=\"$1\"\n    mnt_point=\"$2\"\n    need_recovery=0\n\n    #\n    # \"/proc/mtd\" lists partitions using mtd#, but we need to use the\n    # according \"block\" device (/dev/mtdblock#) due to mount.busybox\n    # limitations.\n    #\n    mtd_blkdev=${mtd_chardev/mtd/mtdblock}\n\n    if jffs2_mount \"$mtd_blkdev\" \"$mnt_point\"; then\n        #\n        # Wait a second to make sure filesystem is fully ready.\n        #\n        sleep 1\n        echo \"Check jffs2 filesystem health on $mtd_blkdev..\"\n\n        if ! jffs2_health_check; then\n            need_recovery=$((need_recovery+1))\n        fi\n        if ! mnt_point_health_check \"$mnt_point\"; then\n            need_recovery=$((need_recovery+1))\n        fi\n\n        if [ \"$need_recovery\" -gt 0 ]; then\n            echo \"jffs2 health check failed. Unmount $mtd_blkdev and start recovery..\"\n            umount \"$mtd_blkdev\"\n        else\n            echo \"jffs2 health check passed: no error found.\"\n        fi\n    else\n        echo \"jffs2_mount $mtd_blkdev failed. Start recovery..\"\n        need_recovery=1\n    fi\n\n    if [ \"$need_recovery\" -gt 0 ]; then\n        if ! jffs2_format \"$mtd_chardev\"; then\n            echo \"jffs2_format failed. Exiting!\"\n            exit 1\n        fi\n\n        if ! jffs2_mount \"$mtd_blkdev\" \"$mnt_point\"; then\n            echo \"jffs2_mount failed after recovery. Exiting!\"\n            exit 1\n        fi\n    fi\n}\n\nis_vboot_recovery_boot(){\n   recv_boot=$(/usr/local/bin/vboot-util | awk -F: -e '/recovery_boot/{ print $2 }')\n   test $(( \"$recv_boot\" )) -ne 0\n}\n\nif is_vboot_recovery_boot; then\n    echo \"Recovery boot, skip mounting /mnt/data\"\n    exit 1\nfi\n\nMTD_DATA_DEV=$(mtd_lookup_data_partition)\nif [ -z \"$MTD_DATA_DEV\" ]; then\n    echo \"No data0/dataro partition found. $MOUNT_POINT not mounted.\"\n    exit 1\nfi\n\nMTD_DATA_PATH=\"/dev/$MTD_DATA_DEV\"\n[ -d $MOUNT_POINT ] || mkdir -p $MOUNT_POINT\n\ndo_mount_$FLASH_FS_TYPE \"$MTD_DATA_PATH\" \"$MOUNT_POINT\"\n\n: exit 0\n", "num_lines": 343}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          mount_data1.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Mount persistent storage (currently eMMC) to /mnt/data1\n# Description:\n### END INIT INFO\n\nMOUNT_POINT=\"/mnt/data1\"\nif [ ! -d \"$MOUNT_POINT\" ]; then\n    if ! output=$(mkdir -p \"$MOUNT_POINT\"); then\n        echo \"Error: failed to create $MOUNT_POINT directory:\"\n        echo \"$output\"\n        exit 1\n    fi\nfi\n\n/usr/local/bin/emmc_auto_mount.sh \"$MOUNT_POINT\"\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nDEVMEM=/sbin/devmem\n\ndevmem_set_bit() {\n    local addr\n    local val\n    addr=$1\n    val=$($DEVMEM $addr)\n    val=$((val | (0x1 << $2)))\n    $DEVMEM $addr 32 $val\n}\n\ndevmem_clear_bit() {\n    local addr\n    local val\n    addr=$1\n    val=$($DEVMEM $addr)\n    val=$((val & ~(0x1 << $2)))\n    $DEVMEM $addr 32 $val\n}\n\n#\n# Test if the given bit is set in register <addr>\n# $1 - register address\n# $2 - bit position\n#\ndevmem_test_bit() {\n    local addr=$1\n    local bitpos=$2\n    local val\n\n    val=$($DEVMEM $addr)\n    val=$(((val >> $bitpos) & 0x1))\n\n    if [ $val -eq 1 ]; then\n        # 0 for true\n        return 0\n    else\n        # 1 for false\n        return 1\n    fi\n}\n\nsource \"/usr/local/bin/shell-utils.sh\"\nsource \"/usr/local/bin/i2c-utils.sh\"\nsource \"/usr/local/bin/gpio-utils.sh\"\nsource \"/usr/local/bin/ast-utils.sh\"\n\nif [ -f \"/usr/local/bin/soc-utils.sh\" ]; then\n    source \"/usr/local/bin/soc-utils.sh\"\nfi\n\nif [ -f \"/usr/local/bin/board-utils.sh\" ]; then\n    source \"/usr/local/bin/board-utils.sh\"\nfi\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#Remove poweroff command from .bash\necho \"Remove poweroff command from .bash\"\nrm /sbin/poweroff\nrm /sbin/poweroff.sysvinit\n\n#Copy modified inittab to change \"init 0\" action from shutdown to reboot\ncp /usr/local/bin/revise_inittab /etc/inittab\n\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# set reboot_ongoing cache to notify other process\n/usr/bin/kv set reboot_ongoing 1\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nsoc_model=$(cat /etc/soc_model 2>/dev/null)\nsram_reboot=\"0x1e721204\"\nif [ \"$soc_model\" = \"SOC_MODEL_ASPEED_G6\" ]; then\n    sram_reboot=\"0x10015c04\"\nfi\n\n# flag for healthd logging reboot cause\nval=$(devmem \"$sram_reboot\" 32 2>/dev/null)\ndevmem \"$sram_reboot\" 32 $((val | 0x101)) 2>/dev/null\n", "num_lines": 12}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup_persist_log.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Mount persistent storage (currently eMMC) to /var/log\n# Description:\n### END INIT INFO\n\nMOUNT_POINT=\"/var/volatile/log/\"\nif [ ! -d \"$MOUNT_POINT\" ]; then\n    if ! output=$(mkdir -p \"$MOUNT_POINT\"); then\n        echo \"Error: failed to create $MOUNT_POINT directory:\"\n        echo \"$output\"\n        exit 1\n    fi\nfi\n\n/usr/local/bin/emmc_auto_mount.sh \"$MOUNT_POINT\"\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run a command given as the second through nth arguments, and report whether\n# it succeeded in a pretty fashion to both stdout and syslog, using the action\n# message given in the first argument. Examples of good action messages are\n# \"enabling userver power\" and \"starting network service\".\n#\n# Note that the command should not produce output of its own, or else the\n# stdout message's formatting will be disrupted.\ntry_and_log() {\n    local message ret\n\n    message=\"$1\"; shift\n    echo -n \"$message ...\"\n    logger \"$message\"\n\n    \"$@\"\n    ret=\"$?\"\n    if [ \"$ret\" -eq 0 ]; then\n        echo \" done\"\n        logger \"finished $message\"\n    else\n        echo \" failed\"\n        logger \"failed while $message\"\n    fi\n\n    return \"$ret\"\n}\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nboard_type=$(type wedge_board_type >/dev/null 2>&1 && wedge_board_type || echo \"no_type\")\n\nif [ \"$board_type\" = \"no_type\" ]; then\n    echo \"Unknown board type!\"\n    exit 1\nfi\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"  $program <bmc> reset <primary|secondary>\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program bmc\"\n    echo \"  $program bmc reset primary\"\n}\n\nboard_type=$(type wedge_board_type >/dev/null 2>&1 && wedge_board_type || echo \"no_type\")\n\nWDT1_STATUS_REG=\"0x1e785010\"\nWDT1_CLR_STATUS_REG=\"0x1e785014\"\n\nWDT2_STATUS_REG=\"0x1e785030\"\nWDT2_CLR_STATUS_REG=\"0x1e785034\"\nWDT2_CNT_RELAOD_REG=\"0x1e785024\"\nWDT2_CNT_RESTART_REG=\"0x1e785028\"\nWDT2_CTRL_REG=\"0x1e78502c\"\n\n# FMC04 CE Control register\nFMC_CE_CTRL_REG=\"0x1e620004\"\n\ncheck_boot_source(){\n    # Please refer to reg WDT1/WDT2 Control Register definition to\n    # understand this code block, WDT1 is on page 646 of ast2500v16.pdf\n    # and WDT2 is on page 649 of ast2500v16.pdf\n    # get watch dog1 timeout status register\n    wdt1=$(devmem \"$WDT1_STATUS_REG\")\n\n    # get watch dog2 timeout status register\n    wdt2=$(devmem \"$WDT2_STATUS_REG\")\n\n    wdt1_timeout_cnt=$(( ((wdt1 & 0xff00) >> 8) ))\n    wdt2_timeout_cnt=$(( ((wdt2 & 0xff00) >> 8) ))\n    wdt1_boot_code_source=$(( ((wdt1 & 0x2) >> 1) ))\n    wdt2_boot_code_source=$(( ((wdt2 & 0x2) >> 1) ))\n    boot_code_source=0\n\n    # Check both WDT1 and WDT2 to indicate the boot source\n    if [ $wdt1_timeout_cnt -ge 1 ] && [ $wdt1_boot_code_source -eq 1 ]; then\n        boot_code_source=1\n    elif [ $wdt2_timeout_cnt -ge 1 ] && [ $wdt2_boot_code_source -eq 1 ]; then\n        boot_code_source=1\n    fi\n\n    echo $boot_code_source\n}\n\nbmc_boot_info() {\n    # get watch dog1 timeout status register\n    wdt1=$(devmem \"$WDT1_STATUS_REG\")\n\n    # get watch dog2 timeout status register\n    wdt2=$(devmem \"$WDT2_STATUS_REG\")\n\n    wdt1_timeout_cnt=$(( ((wdt1 & 0xff00) >> 8) ))\n    wdt2_timeout_cnt=$(( ((wdt2 & 0xff00) >> 8) ))\n\n    boot_code_source=$(check_boot_source)\n\n    boot_source=\"primary Flash\"\n    if [ $((boot_code_source)) -eq 1 ]\n    then\n      boot_source=\"secondary Flash\"\n    fi\n\n    echo \"WDT1 Timeout Count: \" $wdt1_timeout_cnt\n    echo \"WDT2 Timeout Count: \" $wdt2_timeout_cnt\n    echo \"Current Boot Code Source: $boot_source\"\n}\n\nbmc_boot_from() {\n    # Please refer to reg WDT1/WDT2 Control Register definition to\n    # understand this code block, WDT1 is on page 646 of ast2500v16.pdf\n    # and WDT2 is on page 649 of ast2500v16.pdf\n    # Enable watchdog reset_system_after_timeout bit and WDT_enable_signal bit.\n    # Refer to ast2500v16.pdf page 650th.\n    boot_source=0x00000013\n    boot_code_source=$(check_boot_source)\n    if [ \"$1\" = \"primary\" ]; then\n        if [ $((boot_code_source)) -eq 0 ]; then\n            echo \"Current boot source is primary, no need to switch.\"\n            return 0\n        fi\n        # Set bit_7 to 0 : Use default boot code whenever WDT reset.\n        boot_source=0x00000033\n    elif [ \"$1\" = \"secondary\" ]; then\n        if [ $((boot_code_source)) -eq 1 ]; then\n            echo \"Current boot source is secondary, no need to switch.\"\n            return 0\n        fi\n        # No matter BMC boot from any one of primary and secondary.\n        # Set bit_7 to 1 : Use second boot code whenever WDT reset.\n        # And the sencond boot code stands for the other boot source.\n        boot_source=0x000000b3\n    fi\n    echo \"BMC will switch to $1 after 10 seconds...\"\n    # Clear WDT1 counter and boot code source status\n    devmem \"$WDT1_CLR_STATUS_REG\" w 0x77\n    # Clear WDT2 counter and boot code source status\n    devmem \"$WDT2_CLR_STATUS_REG\" w 0x77\n    # Set WDT time out 10s, 0x00989680 = 10,000,000 us\n    devmem \"$WDT2_CNT_RELAOD_REG\" 32 0x00989680\n    # WDT magic number to restart WDT counter to decrease.\n    devmem \"$WDT2_CNT_RESTART_REG\" 32 0x4755\n    devmem \"$WDT2_CTRL_REG\" 32 $boot_source\n\n    # Workaround by set default value to FMC04 of \"unable to boot 2nd flash issue\"\n    # only for Wedge400/Wedge400C\n    if grep -q \"wedge400\" /etc/issue; then\n        devmem \"$FMC_CE_CTRL_REG\" w 0x700\n    fi\n}\n\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncase $1 in\n    \"bmc\")\n        if [ $# -eq 1 ]; then\n            bmc_boot_info\n            exit 0\n        else\n            if [ \"$2\" = \"reset\" ] && [ $# -ge 3 ]; then\n                case $3 in\n                    \"primary\" | \"secondary\")\n                        bmc_boot_from \"$3\"\n                        exit 0\n                    ;;\n                    *)\n                        usage\n                        exit 1\n                    ;;\n                esac\n            fi\n        fi\n    ;;\n    *)\n        usage\n        exit 1\n    ;;\nesac\n", "num_lines": 178}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n# Disable the dual boot watch dog\ndevmem_clear_bit 0x1e78502c 0\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nboard_type=$(type wedge_board_type >/dev/null 2>&1 && wedge_board_type || echo \"no_type\")\n\nif [ \"$board_type\" = \"no_type\" ]; then\n    echo \"Unkonwn board type!\"\n    exit 1\nfi\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    if [ \"$board_type\" != \"CMM\" ]; then\n        echo \"  $program <bmc|bios> reset <master|slave>\"\n    else\n        echo \"  $program <bmc> reset <master|slave>\"\n    fi\n\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program bmc\"\n    echo \"  $program bmc reset master\"\n}\n\nboard_type=$(type wedge_board_type >/dev/null 2>&1 && wedge_board_type || echo \"no_type\")\n\nWDT1_STATUS_REG=\"0x1e785010\"\nWDT1_CLR_STATUS_REG=\"0x1e785014\"\n\nWDT2_STATUS_REG=\"0x1e785030\"\nWDT2_CLR_STATUS_REG=\"0x1e785034\"\nWDT2_CNT_RELAOD_REG=\"0x1e785024\"\nWDT2_CNT_RESTART_REG=\"0x1e785028\"\nWDT2_CTRL_REG=\"0x1e78502c\"\n\n# FMC04 CE Control register\nFMC_CE_CTRL_REG=\"0x1e620004\"\n\ncheck_boot_source(){\n    # Please refer to reg WDT1/WDT2 Control Register definition to\n    # understand this code block, WDT1 is on page 646 of ast2500v16.pdf\n    # and WDT2 is on page 649 of ast2500v16.pdf\n    # get watch dog1 timeout status register\n    wdt1=$(devmem \"$WDT1_STATUS_REG\")\n\n    # get watch dog2 timeout status register\n    wdt2=$(devmem \"$WDT2_STATUS_REG\")\n\n    wdt1_timeout_cnt=$(( ((wdt1 & 0xff00) >> 8) ))\n    wdt2_timeout_cnt=$(( ((wdt2 & 0xff00) >> 8) ))\n    wdt1_boot_code_source=$(( ((wdt1 & 0x2) >> 1) ))\n    wdt2_boot_code_source=$(( ((wdt2 & 0x2) >> 1) ))\n    boot_code_source=0\n\n    # Check both WDT1 and WDT2 to indicate the boot source\n    if [ $wdt1_timeout_cnt -ge 1 ] && [ $wdt1_boot_code_source -eq 1 ]; then\n        boot_code_source=1\n    elif [ $wdt2_timeout_cnt -ge 1 ] && [ $wdt2_boot_code_source -eq 1 ]; then\n        boot_code_source=1\n    fi\n\n    echo $boot_code_source\n}\n\nbmc_boot_info() {\n    # get watch dog1 timeout status register\n    wdt1=$(devmem \"$WDT1_STATUS_REG\")\n\n    # get watch dog2 timeout status register\n    wdt2=$(devmem \"$WDT2_STATUS_REG\")\n\n    wdt1_timeout_cnt=$(( ((wdt1 & 0xff00) >> 8) ))\n    wdt2_timeout_cnt=$(( ((wdt2 & 0xff00) >> 8) ))\n\n    boot_code_source=$(check_boot_source)\n\n    boot_source=\"Master Flash\"\n    if [ $((boot_code_source)) -eq 1 ]\n    then\n      boot_source=\"Slave Flash\"\n    fi\n\n    echo \"WDT1 Timeout Count: \" $wdt1_timeout_cnt\n    echo \"WDT2 Timeout Count: \" $wdt2_timeout_cnt\n    echo \"Current Boot Code Source: $boot_source\"\n}\n\nbmc_boot_from() {\n    # Please refer to reg WDT1/WDT2 Control Register definition to\n    # understand this code block, WDT1 is on page 646 of ast2500v16.pdf\n    # and WDT2 is on page 649 of ast2500v16.pdf\n    # Enable watchdog reset_system_after_timeout bit and WDT_enable_signal bit.\n    # Refer to ast2500v16.pdf page 650th.\n    boot_source=0x00000013\n    boot_code_source=$(check_boot_source)\n    if [ \"$1\" = \"master\" ]; then\n        if [ $((boot_code_source)) -eq 0 ]; then\n            echo \"Current boot source is master, no need to switch.\"\n            return 0\n        fi\n        # Set bit_7 to 0 : Use default boot code whenever WDT reset.\n        boot_source=0x00000033\n    elif [ \"$1\" = \"slave\" ]; then\n        if [ $((boot_code_source)) -eq 1 ]; then\n            echo \"Current boot source is slave, no need to switch.\"\n            return 0\n        fi\n        # No matter BMC boot from any one of master and slave.\n        # Set bit_7 to 1 : Use second boot code whenever WDT reset.\n        # And the sencond boot code stands for the other boot source.\n        boot_source=0x000000b3\n    fi\n    echo \"BMC will switch to $1 after 10 seconds...\"\n    # Clear WDT1 counter and boot code source status\n    devmem \"$WDT1_CLR_STATUS_REG\" w 0x77\n    # Clear WDT2 counter and boot code source status\n    devmem \"$WDT2_CLR_STATUS_REG\" w 0x77\n    # Set WDT time out 10s, 0x00989680 = 10,000,000 us\n    devmem \"$WDT2_CNT_RELAOD_REG\" 32 0x00989680\n    # WDT magic number to restart WDT counter to decrease.\n    devmem \"$WDT2_CNT_RESTART_REG\" 32 0x4755\n    devmem \"$WDT2_CTRL_REG\" 32 $boot_source\n\n    # Workaround by set default value to FMC04 of \"unable to boot 2nd flash issue\"\n    # only for Wedge400/Wedge400C\n    if grep -q \"wedge400\" /etc/issue; then\n        devmem \"$FMC_CE_CTRL_REG\" w 0x700\n    fi\n}\n\nbios_boot_info() {\n    # CPLD path and related COMe BIOS select bits may differ for different\n    # AST2500 based platforms. Additional logic may needed for specific\n    # platforms\n    master_disable=$(( $(head -n 1 < \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\") ))\n    slave_disable=$(( $(head -n 1 < \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\") ))\n    boot_source=\"master\"\n    if [ $master_disable -eq 0 ]; then\n        boot_source=\"master\"\n    elif [ $slave_disable -eq 0 ]; then\n        boot_source=\"slave\"\n    fi\n    echo $boot_source\n}\n\nbios_boot_from() {\n    boot_source=$(bios_boot_info)\n    if [ \"$1\" = \"master\" ]; then\n        if [ \"$boot_source\" = \"master\" ]; then\n            echo \"Current boot source is master, no need to switch.\"\n            return 0\n        fi\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\"\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\"\n\n        echo \"uServer will boot from $1 bios at next reboot!!!!\"\n    elif [ \"$1\" = \"slave\" ]; then\n        if [ \"$boot_source\" = \"slave\" ]; then\n            echo \"Current boot source is slave, no need to switch.\"\n            return 0\n        fi\n        echo 1 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\"\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\"\n\n        echo \"uServer will boot from $1 bios at next reboot!!!!\"\n    else\n        echo \"Unknown uServer boot source, should be either master or slave!\"\n    fi\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncase $1 in\n    \"bmc\")\n        if [ $# -eq 1 ]; then\n            bmc_boot_info\n            exit 0\n        else\n            if [ \"$2\" = \"reset\" ] && [ $# -ge 3 ]; then\n                case $3 in\n                    \"master\" | \"slave\")\n                        bmc_boot_from \"$3\"\n                        exit 0\n                    ;;\n                    *)\n                        usage\n                        exit 1\n                    ;;\n                esac\n            fi\n        fi\n    ;;\n    \"bios\")\n        if [ \"$board_type\" != \"CMM\" ]; then\n            if [ $# -eq 1 ]; then\n                bios_boot_info\n                exit 0\n            else\n                if [ \"$2\" = \"reset\" ] && [ $# -ge 3 ]; then\n                    case $3 in\n                        \"master\" | \"slave\")\n                            bios_boot_from \"$3\"\n                            exit 0\n                        ;;\n                        *)\n                            usage\n                            exit 1\n                        ;;\n                    esac\n                fi\n            fi\n        fi\n    ;;\n    *)\n        usage\n        exit 1\n    ;;\nesac\n", "num_lines": 243}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n#\n# WDT2C Register. Check AST2500 Datasheet, Chapter 41 \"Watchdog Timer\"\n# for details.\n#\nWDT2_CTRL_REG=0x1e78502c\nWDT2_ENABLE_BIT=0\n\n# Disable the dual boot watchdog\ndevmem_clear_bit \"$WDT2_CTRL_REG\" \"$WDT2_ENABLE_BIT\"\n\nif devmem_test_bit \"$WDT2_CTRL_REG\" \"$WDT2_ENABLE_BIT\"; then\n    val=$(devmem \"$WDT2_CTRL_REG\")\n    echo \"ALERT: failed to disable the 2nd watchdog: WDT2C=$val!!!\"\n    logger -p user.crit \"failed to disable the 2nd watchdog: WDT2C=$val!!!\"\n    exit 1\nfi\n\necho \"Disabled the 2nd watchdog (WDT2) successfully.\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"  $program <bmc|bios> reset <master|slave>\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program bmc\"\n    echo \"  $program bmc reset master\"\n}\n\nWDT1_STATUS_REG=\"0x1E785010\"\nFMC_WDT2_RELOAD_VAL_REG=\"0x1E620068\"\nFMC_WDT2_RESTART_REG=\"0x1E62006C\"\nFMC_WDT2_CTRL_STATUS_REG=\"0x1E620064\"\n\n\nbmc_boot_info() {\n    # Please refer to reg WDT1/WDT2 Control Register definition to\n    # understand this code block, WDT1 is on page 758 of ast2620.pdf\n    # and WDT2 is on page 232 of ast2620.pdf\n    # get watch dog1 timeout status register\n    wdt1=$(devmem \"$WDT1_STATUS_REG\")\n\n    # get watch dog2 timeout status register\n    wdt2=$(devmem \"$FMC_WDT2_CTRL_STATUS_REG\" )\n\n    wdt1_timeout_cnt=$(( ((wdt1 & 0xff00) >> 8) ))\n    wdt2_timeout_cnt=$(( ((wdt2 & 0xff00) >> 8) ))\n    boot_code_source=$(( ((wdt2 & 0x10) >> 4) ))\n\n    boot_source=\"Master Flash\"\n    if [ $boot_code_source -eq 1 ]\n    then\n      boot_source=\"Slave Flash\"\n    fi\n\n    echo \"WDT1 Timeout Count: \" $wdt1_timeout_cnt\n    echo \"WDT2 Timeout Count: \" $wdt2_timeout_cnt\n    echo \"Current Boot Code Source: $boot_source\"\n}\n\nbmc_boot_from() {\n    # Please refer to reg WDT2 Control Register definition to\n    # understand this code block, WDT2 is on page 232 of ast2620.pdf\n    # Enable watchdog reset_system_after_timeout bit and WDT_enable_signal bit.\n    # Refer to ast2620.pdf page 232.\n    boot_source=0x00000000\n    wdt2=$(devmem \"$FMC_WDT2_CTRL_STATUS_REG\")\n    boot_code_source=$(( (wdt2 & 0x10) >> 4 ))\n    if [ \"$1\" = \"master\" ]; then\n        if [ $boot_code_source = 0 ]; then\n            echo \"Current boot source is master, no need to switch.\"\n            return 0\n        fi\n        # No matter BMC boot from any one of master and slave.\n        # Set bit_7 to 1 : Use second boot code whenever WDT reset.\n        # And the sencond boot code stands for the other boot source.\n        boot_source=0x00000001\n    elif [ \"$1\" = \"slave\" ]; then\n        if [ $boot_code_source = 1 ]; then\n            echo \"Current boot source is slave, no need to switch.\"\n            return 0\n        fi\n        # No matter BMC boot from any one of master and slave.\n        # Set bit_7 to 1 : Use second boot code whenever WDT reset.\n        # And the sencond boot code stands for the other boot source.\n        boot_source=0x00000001\n    fi\n\n    # Extend wdt1 timeout value to prevent wdt1 timeout during uboot stage.\n    if [ \"$(LC_ALL=C type -t wdt_set_timeout)\" = function ]; then\n        wdt_set_timeout 120\n    else\n        wdtcli set-timeout 120\n    fi\n    echo \"BMC will switch to $1 after 2 seconds    ...\"\n    # Set WDT time out 2s, 0x00000014 = 2s\n    devmem \"$FMC_WDT2_RELOAD_VAL_REG\" 32 0x00000014\n    # WDT magic number to restart WDT counter to decrease.\n    devmem \"$FMC_WDT2_RESTART_REG\" 32 0x4755\n    devmem \"$FMC_WDT2_CTRL_STATUS_REG\" 32 $boot_source\n}\n\nbios_boot_info() {\n    master_disable=$(( $(head -n 1 < \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\") ))\n    slave_disable=$(( $(head -n 1 < \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\") ))\n    boot_source=\"master\"\n    if [ $master_disable -eq 0 ]; then\n        boot_source=\"master\"\n    elif [ $slave_disable -eq 0 ]; then\n        boot_source=\"slave\"\n    fi\n    echo $boot_source\n}\n\nbios_boot_from() {\n    boot_source=$(bios_boot_info)\n    if [ \"$1\" = \"master\" ]; then\n        if [ \"$boot_source\" = \"master\" ]; then\n            echo \"Current boot source is master, no need to switch.\"\n            return 0\n        fi\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\"\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\"\n\n        echo \"uServer will boot from $1 bios at next reboot!!!!\"\n    elif [ \"$1\" = \"slave\" ]; then\n        if [ \"$boot_source\" = \"slave\" ]; then\n            echo \"Current boot source is slave, no need to switch.\"\n            return 0\n        fi\n        echo 1 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis0_n\"\n        echo 0 > \"${SCMCPLD_SYSFS_DIR}/iso_buff_brg_com_bios_dis1_n\"\n\n        echo \"uServer will boot from $1 bios at next reboot!!!!\"\n    else\n        echo \"Unknown uServer boot source, should be either master or slave!\"\n    fi\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncase $1 in\n    \"bmc\")\n        if [ $# -eq 1 ]; then\n            bmc_boot_info\n            exit 0\n        else\n            if [ \"$2\" = \"reset\" ] && [ $# -ge 3 ]; then\n                case $3 in\n                    \"master\" | \"slave\")\n                        bmc_boot_from \"$3\"\n                        exit 0\n                    ;;\n                    *)\n                        usage\n                        exit 1\n                    ;;\n                esac\n            fi\n        fi\n    ;;\n    \"bios\")\n        if [ $# -eq 1 ]; then\n            bios_boot_info\n            exit 0\n        else\n            if [ \"$2\" = \"reset\" ] && [ $# -ge 3 ]; then\n                case $3 in\n                    \"master\" | \"slave\")\n                        bios_boot_from \"$3\"\n                        exit 0\n                    ;;\n                    *)\n                        usage\n                        exit 1\n                    ;;\n                esac\n            fi\n        fi\n    ;;\n    *)\n        usage\n        exit 1\n    ;;\nesac\n", "num_lines": 195}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n#\n# FMC64 Register. Check AST2600 Datasheet, Chapter 14 \"Firmware SPI Memory\n# Controller (BSPI)\" for details.\n#\nFMC_WDT2_REG=0x1e620064\nFMC_WDT2_ENABLE_BIT=0\n\n# Disable the fmc dual boot watch dog\ndevmem_clear_bit \"$FMC_WDT2_REG\" \"$FMC_WDT2_ENABLE_BIT\"\n\nif devmem_test_bit 0x1e620064 \"$FMC_WDT2_ENABLE_BIT\"; then\n    val=$(devmem \"$FMC_WDT2_REG\")\n    echo \"Error: unable to disable the 2nd watchdog: FMC_WDT2=$val\"\n    exit 1\nfi\n\necho \"Disabled the 2nd watchdog (FMC_WDT2) successfully.\"\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nscu_addr() {\n    echo $((0x1E6E2000 + 0x$1))\n}\n\nast_config_adc() {\n    local ADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n    local channel=$1\n    local r1=$2\n    local r2=$3\n    local v2=$4\n    echo \"$r1\" > ${ADC_PATH}/adc${channel}_r1\n    echo \"$r2\" > ${ADC_PATH}/adc${channel}_r2\n    echo \"$v2\" > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\n\naspeed_g6_chip_ver() {\n        chip_ver=$(devmem 0x1e6e2014 | awk '{print substr($0,6,1)}')\n        case $chip_ver in\n                0)\n                        echo \"A0\"\n                        ;;\n                1)\n                        echo \"A1\"\n                        ;;\n                2)\n                        echo \"A2\"\n                        ;;\n                3)\n                        echo \"A3\"\n                        ;;\n        esac\n}\n\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..5) (upper: 6...10)] [board type (Mavericks Montara)]\" >&2\n}\n\nFAN_DIR=/sys/class/i2c-adapter/i2c-8/8-0033\nFAN_DIR_UPPER=/sys/class/i2c-adapter/i2c-9/9-0033\n\nshow_pwm()\n{\n    if [ $1 -gt 5 ]; then\n        fan=$(( $1 - 5 ))\n        pwm=\"${FAN_DIR_UPPER}/fantray${fan}_pwm\"\n    else\n        pwm=\"${FAN_DIR}/fantray${1}_pwm\"\n    fi\n    val=$(cat $pwm | head -n 1)\n    echo \"$((val * 100 / 31))%\"\n}\n\nshow_rpm()\n{\n    if [ $1 -gt 5 ]; then\n        front_rpm=\"${FAN_DIR_UPPER}/fan$(((($1 - 5) * 2 - 1)))_input\"\n        rear_rpm=\"${FAN_DIR_UPPER}/fan$(((($1 - 5) * 2)))_input\"\n    else\n        front_rpm=\"${FAN_DIR}/fan$((($1 * 2 - 1)))_input\"\n        rear_rpm=\"${FAN_DIR}/fan$((($1 * 2)))_input\"\n    fi\n    echo \"$(cat $front_rpm), $(cat $rear_rpm)\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\n# fixing function to handle maverciks and montara number of fans \n# while keeping backward command line compatibility with original FB script\nif [ \"$#\" -eq 0 ]; then\n    \tFANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ $1 = \"Mavericks\" ]; then\n    \tFANS=\"1 2 3 4 5 6 7 8 9 10\"\n    elif [ $1 = \"Montara\" ]; then\n    \tFANS=\"1 2 3 4 5\"\n    else \n\tif [ $1 -gt 10 ]; then\n      \t    usage\n            exit 1\n\tfi\n\tFANS=\"$1\"\n    fi\nelif [ \"$#\" -eq 2 ]; then\n    if [ $2 != \"Mavericks\" ] && [ $2 != \"Montara\" ]; then\n    \tusage\n    \texit 1\n    fi\n    if [ $1 -gt 10 ]; then\n        usage\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\nfor fan in $FANS; do\n    echo \"Fan $fan RPMs: $(show_rpm $fan), ($(show_pwm $fan))\"\ndone\n", "num_lines": 89}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/set_fan_speed.sh 50\n/usr/local/bin/fand\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..5)(6...10)> <board type (Montara Mavericks)>\" >&2\n}\n\nFAN_DIR=/sys/class/i2c-adapter/i2c-8/8-0033\nFAN_DIR_UPPER=/sys/class/i2c-adapter/i2c-9/9-0033\n\nset -e\n\nif [ \"$#\" -gt 3 ] || [ \"$#\" -lt 1 ]; then\n    usage\n    exit 1\nfi\n\n# Adding fix for Mavericks and Montara while keeping backward compatibility with FB command line.\nif [ \"$#\" -eq 1 ]; then\n    FANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 2 ]; then\n    if [ $2 = \"Mavericks\" ]; then\n    \tFANS=\"1 2 3 4 5 6 7 8 9 10\"\n    elif [ $2 = \"Montara\" ]; then\n    \tFANS=\"1 2 3 4 5\"\n    else \n    \tif [ $2 -gt 10 ]; then\n       \t    usage\n            exit 1\n    \tfi\n    \tFANS=\"$2\"\n    fi\nelse\n    if [ $3 = \"Mavericks\" ]; then\n    \tif [ $2 -gt 10 ]; then\n       \t    usage\n            exit 1\n    \tfi\n    elif [ $3 = \"Montara\" ]; then\n    \tif [ $2 -gt 5 ]; then\n       \t    usage\n            exit 1\n    \tfi\n    else \n        usage\n        exit 1\n    fi\n    FANS=\"$2\"\nfi\n\n# Convert the percentage to our 1/32th unit (0-31).\nunit=$(( ( $1 * 31 ) / 100 ))\n\nfor fan in $FANS; do\n    if [ $fan -gt 5 ]; then\n        fan_idx=$(( $fan - 5))\n        pwm=\"${FAN_DIR_UPPER}/fantray${fan_idx}_pwm\"\n    else\n        pwm=\"${FAN_DIR}/fantray${fan}_pwm\"\n    fi\n    echo \"$unit\" > $pwm\n    echo \"Successfully set fan ${fan} speed to $1%\"\ndone\n", "num_lines": 80}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..5)]\" >&2\n}\n\nFAN_DIR=/sys/class/i2c-adapter/i2c-8/8-0033\n\nshow_pwm()\n{\n    pwm=\"${FAN_DIR}/fantray${1}_pwm\"\n    val=$(cat $pwm | head -n 1)\n    echo \"$((val * 100 / 31))%\"\n}\n\nshow_rpm()\n{\n    front_rpm=\"${FAN_DIR}/fan$((($1 * 2 - 1)))_input\"\n    rear_rpm=\"${FAN_DIR}/fan$((($1 * 2)))_input\"\n    echo \"$(cat $front_rpm), $(cat $rear_rpm)\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ $1 -gt 5 ]; then\n        usage\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\nfor fan in $FANS; do\n    echo \"Fan $fan RPMs: $(show_rpm $fan), ($(show_pwm $fan))\"\ndone\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/set_fan_speed.sh 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..5)> \" >&2\n}\n\nFAN_DIR=/sys/class/i2c-adapter/i2c-8/8-0033\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$#\" -eq 1 ]; then\n    FANS=\"1 2 3 4 5\"\nelse\n    FANS=\"$2\"\nfi\n\n# Convert the percentage to our 1/32th unit (0-31).\nunit=$(( ( $1 * 31 ) / 100 ))\n\nfor fan in $FANS; do\n    pwm=\"${FAN_DIR}/fantray${fan}_pwm\"\n    echo \"$unit\" > $pwm\n    echo \"Successfully set fan ${fan} speed to $1%\"\ndone\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n\nSYSCPLD_SYSFS_DIR=\"/sys/class/i2c-adapter/i2c-12/12-0031\"\nPWR_MAIN_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_main_n\"\nPWR_USRV_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_usrv_en\"\nPWR_USRV_BTN_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_usrv_btn_en\"\nSLOTID_SYSFS=\"${SYSCPLD_SYSFS_DIR}/slotid\"\n\nwedge_iso_buf_enable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_is_us_on() {\n    local val n retries prog\n    if [ $# -gt 0 ]; then\n        retries=\"$1\"\n    else\n        retries=1\n    fi\n    if [ $# -gt 1 ]; then\n        prog=\"$2\"\n    else\n        prog=\"\"\n    fi\n    if [ $# -gt 2 ]; then\n        default=$3              # value 0 means defaul is 'ON'\n    else\n        default=1\n    fi\n    val=$(cat $PWR_USRV_SYSFS 2> /dev/null | head -n 1)\n    if [ -z \"$val\" ]; then\n        return $default\n    elif [ \"$val\" == \"0x1\" ]; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n}\n\nwedge_board_type() {\n    echo 'MAVERICKS'\n}\n\nwedge_slot_id() {\n    printf \"%d\\n\" $(cat $SLOTID_SYSFS)\n}\n\nwedge_board_rev() {\n    local val0 val1 val2\n    val0=$(gpio_get BOARD_REV_ID0)\n    val1=$(gpio_get BOARD_REV_ID1)\n    val2=$(gpio_get BOARD_REV_ID2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    # wedge100 uses BMC MAC since beginning\n    return -1\n}\n\nwedge_power_on_board() {\n    local val isolbuf\n    # power on main power, uServer power, and enable power button\n    val=$(cat $PWR_MAIN_SYSFS | head -n 1)\n    if [ \"$val\" != \"0x1\" ]; then\n        echo 1 > $PWR_MAIN_SYSFS\n        sleep 2\n    fi\n    val=$(cat $PWR_USRV_BTN_SYSFS | head -n 1)\n    if [ \"$val\" != \"0x1\" ]; then\n        echo 1 > $PWR_USRV_BTN_SYSFS\n        sleep 1\n    fi\n\n    # Enable the COME I2C isolation buffer\n    val=$(i2cget -f -y 12 0x31 0x28)\n    isolbuf=$(($val|0x30))\n    i2cset -f -y 12 0x31 0x28 $isolbuf\n}\n", "num_lines": 87}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nCMD='/sys/class/i2c-adapter/i2c-12/12-0031/i2c_flush_en'\n\necho -n \"I2c flush to CP2112...\"\necho 1 > $CMD\nusleep 50000\necho 0 > $CMD\necho \"Done\"\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nrev=$(head -1 /sys/class/i2c-adapter/i2c-12/12-0031/cpld_rev)\nsub_rev=$(head -1 /sys/class/i2c-adapter/i2c-12/12-0031/cpld_sub_rev)\n\necho $(($rev)).$(($sub_rev))\n\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nupgrade_syscpld() {\n  echo \"Started SYSCPLD upgrade ..\"\n  echo out > /tmp/gpionames/CPLD_JTAG_SEL/direction\n  echo 1 > /tmp/gpionames/CPLD_JTAG_SEL/value\n  sys_usercode=$(jbi -r -aREAD_USERCODE -gc102 -gi101 -go103 -gs100 $1 | grep -i \"USERCODE code is\" | awk '{ print $6 }')\n  new_usercode=$(jbi -i $1 | grep -i \"\\\"USERCODE\"\\\" | awk -F '\"' '{ print $4 }')\n  if [ \"${sys_usercode}\" != \"${new_usercode}\" ];\n  then\n      #disable heartbeat\n      i2cset -f -y 12 0x31 0x2e 0x18\n      #program syscpld\n      rc=$(jbi -r -aPROGRAM -gc102 -gi101 -go103 -gs100 $1 | grep -i \"Success\")\n      if [[ $rc == *\"Success\"* ]];\n      then\n          echo \"Finished SYSCPLD upgrade: Pass\"\n      else\n          echo \"Finished SYSCPLD upgrade: Fail (Program failed)\"\n      fi\n  else\n    echo \"Finished SYSCPLD upgrade: No Action (Same usercode)\"\n  fi\n}\n\nupgrade_fancpld() {\n  echo \"Started FANCPLD upgrade ..\"\n  echo out > /tmp/gpionames/CPLD_UPD_EN/direction\n  echo 0 > /tmp/gpionames/CPLD_UPD_EN/value\n  #get usercode from system\n  sys_usercode=$(jbi -r -aREAD_USERCODE -gc77 -gi78 -go79 -gs76 $1 | grep -i \"USERCODE code is\" | awk '{ print $6 }')\n  #get usercode from file\n  new_usercode=$(jbi -i $1 | grep -i \"\\\"USERCODE\"\\\" | awk -F '\"' '{ print $4 }')\n  if [ \"${sys_usercode}\" != \"${new_usercode}\" ];\n  then\n      #program fancpld\n      rc=$(jbi -aPROGRAM -gc77 -gi78 -go79 -gs76 $1 | grep -i \"Success\")\n      if [[ $rc == *\"Success\"* ]];\n      then\n          echo \"Finished FANCPLD upgrade: Pass\"\n      else\n          echo \"Finished FANCPLD upgrade: Fail (Program failed)\"\n      fi\n  else\n    echo \"Finished FANCPLD upgrade: No Action (Same usercode)\"\n  fi\n}\n\n# Check the number of arguments provided, should get atleast 1 for file path\nif [ $# -lt 1 ]; then\n  echo \"Provide FAN or SYSCPLD path\"\n  exit -1\nfi\n\n# Check the file path provided is a valid one.\njbcfile=\"$1\"\nif [ ! -f $jbcfile ]; then\n    echo \"$jbcfile does not exist\"\n    exit -1\nfi\n\n# Check the file path extension is .jbc\nfilename=\"$(basename $jbcfile)\"\nif [[ ${filename: -4} != \".jbc\" ]]; then\n    echo \"Must pass in a .jbc file\"\n    exit -1\nfi\n\n# Check the file name and upgrade accordingly\nif [[ $filename == *\"FAN\"* ]];\nthen\n    upgrade_fancpld $jbcfile\nelse if [[ $filename == *\"SYSCPLD\"* ]];\nthen\n    upgrade_syscpld $jbcfile\nelse\n  echo \"Provide FAN or SYSCPLD path\"\n  exit -1\nfi\nfi\n", "num_lines": 98}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.\u00c2\u00a0 See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nversion=$(cat /sys/class/i2c-adapter/i2c-4/4-0033/version)\nreleased_date=$(cat /sys/class/i2c-adapter/i2c-4/4-0033/date)\n\nif [ \"${version:(-4)}\" == \"0x80\" ]; then\n  echo \"EC Test Version\"\n  echo \"EC Released Date: $released_date\"\nelse\n  r=$((16#${version:15:2}))\n  e=$((16#${version:22:2}))\n  echo \"EC Released Version: R$(printf '%02d' $r).E$(printf '%02d' $e)\"\n  echo \"EC Released Date: $released_date\"\nfi\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/bin/openbmc-utils.sh\n\n# select WDTRST\ndevmem_clear_bit $(scu_addr 2C) 1\ndevmem_set_bit $(scu_addr 84) 4\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# reconfigure the CPLD<-->COMe UART mux \n# useful to force redirect COMe tx/rx data from reaching BMC UART durign COMe boot\n# We could not disable the BMC UART from transmitting to COMe and hence this work around.\n# usage wedge_tty_block <1:switch | 0: dont switch > [delay in seconds; default no delay]\n\nif [ $# -eq 0 ]; then                                                           \n  exit 1                                                                        \nfi                                                                              \n                                                                                \nswitch=$1                                                                       \nif [ $# -gt 1 ]; then                                                           \n  delay=\"$2\"                                                                    \nelse                                                                            \n  delay=0                                                                       \nfi                                                                              \n                                                                                \nif [ $delay -gt 0 ]; then                                                       \n  sleep \"$delay\"                                                                \nfi                                                                              \n                                                                                \nval=$(i2cget -f -y 12 0x31 0x26)                                                \nif [ $switch -eq 1 ]; then                                                      \n  newval=$(($val|0x01))                                                         \n  echo \"switching COMe uart to dbg port\"                                        \nelse                                                                            \n  newval=$(($val&0xFE))                                                         \n  echo \"switching COMe uart to BMC UART\"                                        \nfi                                                                              \ni2cset -f -y 12 0x31 0x26 $newval                                               \n\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\ndisplay_value() {\n    num=0\n    input=$1\n    while [ $num -lt 8 ]; do  {\n        gpio_set $(gpio_name2value LED_POSTCODE_$num) $((input & 1))\n        input=$((input >> 1))\n        num=$((num + 1))\n    }\n    done\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\ndisplay_value $DEC_VALUE\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# make power button high to prepare for power on sequence\ngpio_set BMC_PWR_BTN_OUT_N 1\n\n#switch COMe tty to dbg port\nmav_tty_switch_delay.sh 1\n\n# First power on TH, and if Panther+ is used,\n# provide standby power to Panther+.\nwedge_power_on_board\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n\n#switch COMe tty to BMC UART after 45 seconds\necho \"wait for 45 seconds before connecting to COMe...\"\nmav_tty_switch_delay.sh 0 45 &\n\n# set the Tofino VDD voltage here before powering-ON COMe\nCODE=\"$(i2cget -f -y 12 0x31 0xb)\"\nCODE_M=$(($CODE & 0x7))\nif [ $CODE_M != 0 ]; then\n    tbl=(0 0.83 0.78 0.88 0.755 0.855 0.805 0.905)\n    # If not able to access value it is a montara otherwise mavericks\n    cat /sys/bus/i2c/drivers/fancpld/9-0033/board_rev >& /dev/null\n    if [ $? == 1 ]; then\n        btools.py --IR set_vdd_core montara ${tbl[$CODE_M]}\n    else\n        btools.py --IR set_vdd_core mavericks ${tbl[$CODE_M]}\n    fi  \n    logger \"VDD setting: ${tbl[$CODE_M]}\"\nfi\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPWR_TH_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/th_sys_rst_n\"\n\necho 0 > $PWR_TH_RST_SYSFS\nsleep 1\necho 1 > $PWR_TH_RST_SYSFS\n\nlogger \"Reset Tofino\"\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nCMD='/sys/class/i2c-adapter/i2c-12/12-0031/usb2cp2112_rst_n'\n\necho -n \"Reset CP2112 Switch ... \"\necho 0 > $CMD\nusleep 50000\necho 1 > $CMD\n\necho \"Done\"\n", "num_lines": 29}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nfunction reset_to_mux\n{\n  local num=0 val=$1\n  while [ $num -lt 4 ]; do\n    CMD='/sys/class/i2c-adapter/i2c-12/12-0031/i2c_mux'$num'_rst_n'\n    echo $val > $CMD\n    (( num++ ))\n  done\n}\n\necho -n \"Reset QSFP i2c-mux ... \"\nreset_to_mux 0\nusleep 50000\nreset_to_mux 1\necho \"Done\"\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nSERVICE=\"rest.py\"\n\ncheck_8080_port(){\n\tfor ((i=0; i<=12; i++)); do\n\t\tnetstat -tanu | grep 8080 | grep LISTEN\n\t\tcmd=$?\n\t\tif [ \"$cmd\" == 0 ]; then\n\t\t\treturn\n\t\tfi\n\t\tsleep 5\n\tdone\n}\n      \nwhile [ 1 ]\ndo\n\tRESULT=`ps | sed -n /${SERVICE}/p`\n\tif [ \"${RESULT:-null}\" = null ]; then\n\t    echo \"rest.py not running\"\n\t    /usr/local/bin/setup-rest-api.sh restart\n\t    check_8080_port\n\t    if [ -e \"/tmp/btools_lock\" ]; then\n\t      rm -f \"/tmp/btools_lock\"\n\t      echo \"Stale btools_lock exists. Removing it\"\n\t    fi\n\tfi\n\tsleep 5\ndone\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nboard_rev=$(wedge_board_rev)\n\nif [ $board_rev -ge 2 ]; then\n    # DVT or later\n    # Enable the isolation buffer between BMC and COMe i2c bus\n    echo 1 > ${SYSCPLD_SYSFS_DIR}/com-e_i2c_isobuf_en\n    # Enable the COM6_BUF_EN to open the isolation buffer between COMe BIOS\n    # EEPROM with COMe\n    gpio_set COM6_BUF_EN 0\n    # Make the BIOS EEPROM connect to COMe instead of BMC\n    gpio_set COM_SPI_SEL 0\nfi\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Bus 3\ni2c_device_add 3 0x48 tmp75\ni2c_device_add 3 0x49 tmp75\ni2c_device_add 3 0x4a tmp75\ni2c_device_add 3 0x4b tmp75\ni2c_device_add 3 0x4c tmp75\n\n# Bus 4\ni2c_device_add 4 0x33 com_e_driver\n\n# Bus 6\ni2c_device_add 6 0x2f pcf8574\ni2c_device_add 6 0x51 24c64\n\n# Bus 7\ni2c_device_add 7 0x50 24c02         # BMC PHY EEPROM\ni2c_device_add 7 0x51 24c64         # PFE1100 power supply EEPROM\ni2c_device_add 7 0x52 24c64         # PFE1100 power supply EEPROM\ni2c_device_add 7 0x6f ltc4151\n\n# Bus 8\ni2c_device_add 8 0x33 fancpld\ni2c_device_add 8 0x48 tmp75\ni2c_device_add 8 0x49 tmp75\n\n# Bus 9\n# 9 0x20 tpm_i2c_infineon added by trousers.init.sh\n\n# Bus 12\ni2c_device_add 12 0x31 syscpld\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nPWR_BTN_GPIO=\"BMC_PWR_BTN_OUT_N\"\nPWR_SYSTEM_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_cyc_all_n\"\nPWR_USRV_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/usrv_rst_n\"\nPWR_TH_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/th_sys_rst_n\"\nMAIN_PWR=\"${SYSCPLD_SYSFS_DIR}/pwr_main_n\"\nPWR_USRV_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_main_n\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge system ungracefully\"\n    echo\n}\n\nmain_power_status() {\n  status=$(cat $MAIN_PWR | head -1 )\n  if [ \"$status\" == \"0x1\" ]; then\n      return 0            # powered on\n  else\n      return 1\n  fi\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n    main_power_status\n    rc=$?\n    if [ $rc == \"0\" ]; then\n        echo \"System main power is on\"\n    else\n        echo \"System main power is off\"\n        return_code=1\n    fi\n    return $return_code\n}\n\ndo_on_com_e() {\n    echo 1 > $PWR_USRV_SYSFS\n    return $?\n}\n\ndo_on_main_pwr() {\n  main_power_status\n  rc=$?\n  if [ $rc == \"1\" ]; then\n    echo 1 > $MAIN_PWR\n    ret=$?\n    if [ $ret -eq 0 ]; then\n      echo \"Turning on system main power\"\n      logger \"Successfully power on main power\"\n      return 0\n    else\n      return 1\n    fi\n  fi\n  return 0\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on 10 \".\"; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # reset Tofino\n    reset_brcm.sh\n    # power on sequence\n    do_on_main_pwr\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n\tlogger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    echo 0 > $PWR_USRV_SYSFS\n    return $?\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_reset() {\n    local system opt pulse_us\n    system=0\n    while getopts \"s\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        pulse_us=100000             # 100ms\n        logger \"Power reset the whole system ...\"\n        echo -n \"Power reset the whole system ...\"\n        sleep 1\n        echo 0 > $PWR_SYSTEM_SYSFS\n        # Echo 0 above should work already. However, after CPLD upgrade,\n        # We need to re-generate the pulse to make this work\n        usleep $pulse_us\n        echo 1 > $PWR_SYSTEM_SYSFS\n        usleep $pulse_us\n        echo 0 > $PWR_SYSTEM_SYSFS\n        usleep $pulse_us\n        echo 1 > $PWR_SYSTEM_SYSFS\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return -1\n        fi\n        # reset Tofino first\n        reset_brcm.sh\n        echo -n \"Power reset microserver ...\"\n        echo 0 > $PWR_USRV_RST_SYSFS\n        sleep 1\n        echo 1 > $PWR_USRV_RST_SYSFS\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit -1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 236}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nif ! wedge_is_us_on; then\n    echo \"Cannot retrive microserver MAC when microserver is powered off.\" 1>&2\n    exit -2\nfi\n\nmac=$(cat /sys/class/i2c-adapter/i2c-4/4-0033/mac)\n\nif [ -n \"$mac\" -a \"${mac/X/}\" = \"${mac}\" ]; then\n    echo $mac\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit -1\nfi\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttpm2-abrmd\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tpm2-abrmd\n# Description:\t\ttpm2-abrmd implements the TCG resource manager\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tpm2-abrmd\nNAME=tpm2-abrmd\nDESC=\"TCG TSS2 Access Broker and Resource Management daemon\"\nUSER=\"tss\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo -n \"Starting $DESC: \"\n\n\t\tif [ ! -e /dev/tpm? ]\n\t\tthen\n\t\t\techo \"device driver not loaded, skipping.\"\n\t\t\texit 0\n\t\tfi\n\n\t\tstart-stop-daemon --start --quiet --oknodo --background --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo -n \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\n# shellcheck disable=SC2001\n\n# The Marvell GW swith reset and the Marvell GW switch EEPROM I2C access are controlled by writing to the CPU CPLD registers.\n# To write to a CPU CLPD rigister:\n# 1- First the CPLD register address is specified by writing to I2C addresses 0x31 to 0x34.\n# 2- Then the data is specified by writing to addresses 0x35 to 0x38.\n# 3- And finally the write request is triggered by writing to address 0x30 as below:\n#\n#0x30 is command  1: read,  0: write\n#0x31 addr[7:0]\n#0x32 addr[15:8]\n#0x33 addr[23:16]\n#0x34 addr[31:24]\n#0x35 data[7:0]\n#0x36 data[15:8]\n#0x37 data[23:16]\n#0x38 data[31:24]\"\n\n# To enable I2C access to Marvell GW switch EEPROM we are writing to register 0xC (\"Misc. Control Register\" in CPLD register map spec.).\n# Setting bit 3 (\"geSwI2cSel\" in CPLD register map spec.) enables EEPROM access. The other bits are not modified from default values.\n\n# enable access to GE switch EEPROM\noob_switch_eeprom_select() {\n\n    i2cset -f -y 12 0x31 0x0c\n    i2cset -f -y 12 0x32 0x00\n    i2cset -f -y 12 0x33 0x00\n    i2cset -f -y 12 0x34 0x00\n    i2cset -f -y 12 0x35 0x07\n    i2cset -f -y 12 0x36 0x2a\n    i2cset -f -y 12 0x30 0x0\n}\n\n# To enable I2C access to Marveell GW switch EEPROM we are writing to register 0xC (\"Misc. Control Register\" in CPLD register map spec.).\n# Clearing bit 2 (\"geSwI2cSel\" in CPLD register map spec.) disable EEPROM access. The other bits are not modified from default values.\n\n# disable access to GE switch EEPROM\noob_switch_eeprom_deselect() {\n\n    i2cset -f -y 12 0x31 0x0c\n    i2cset -f -y 12 0x32 0x00\n    i2cset -f -y 12 0x33 0x00\n    i2cset -f -y 12 0x34 0x00\n    i2cset -f -y 12 0x35 0x03\n    i2cset -f -y 12 0x36 0x2a\n    i2cset -f -y 12 0x30 0x0\n}\n\n# For switch reset we are writing to register 0xC (\"Misc. Control Register\" in CPLD register map spec.).\n# 1- First, setting bit 8 (\"gwSwRst\" in CPLD register map spec.) to put the switch in reset. The other bits are not modified from default values.\n# 2- After 0.5 second, bit 8 (\"gwSwRst\" in CPLD register map spec.) is cleared to bring the switch out of reset.\n\n# GE switch reset\noob_switch_reset() {\n\n    i2cset -f -y 12 0x31 0x0c\n    i2cset -f -y 12 0x32 0x00\n    i2cset -f -y 12 0x33 0x00\n    i2cset -f -y 12 0x34 0x00\n    i2cset -f -y 12 0x35 0x03\n    i2cset -f -y 12 0x36 0x2b\n    i2cset -f -y 12 0x30 0x0\n    sleep 0.5\n    i2cset -f -y 12 0x31 0x0c\n    i2cset -f -y 12 0x32 0x00\n    i2cset -f -y 12 0x33 0x00\n    i2cset -f -y 12 0x34 0x00\n    i2cset -f -y 12 0x35 0x03\n    i2cset -f -y 12 0x36 0x2a\n    i2cset -f -y 12 0x30 0x0\n}\n\n# read bmc mac address from eeprom\nread_mac_from_eeprom() {\n\n    mac=00:00:00:00:00:00\n\n    if [  -f  \"/opt/cisco/bin/idprom\" ]; then\n\n        temp_mac=$(idprom /sys/bus/i2c/devices/8-0054/eeprom | grep MACADDR_BASE | awk '{print $2}' | cut -c1-12)\n        if [ -z \"$temp_mac\" ]; then\n            echo \"mac address not found\"\n        else\n            mac=$(sed -e \"s/\\(..\\)\\(..\\)\\(..\\)\\(..\\)\\(..\\)\\(..\\)/\\1:\\2:\\3:\\4:\\5:\\6/\" <<< \"$temp_mac\")\n        fi\n\n    else\n\n        # Temporary workaround until we get the idprom utility via PR for BSP\n        hexdump -ve '1/1 \"%.2x\"' /sys/bus/i2c/devices/8-0054/eeprom > /tmp/eeprom_data\n\n        ((i = 0))\n        while [[ $i -lt 512 ]]\n        do\n            var=$( dd skip=$i count=4 if=/tmp/eeprom_data bs=1 2> /dev/null )\n            if [ \"$var\" = \"cf06\" ];then\n                ((i = i + 4))\n                mac1=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac2=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac3=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac4=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac5=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac6=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n\n                mac=$mac1:$mac2:$mac3:$mac4:$mac5:$mac6\n                break\n            fi\n            ((i = i + 1))\n        done\n        rm /tmp/eeprom_data\n    fi\n\n    echo \"$mac\"\n}\n\n\n# read x86 mac address from eeprom\nread_x86_mac_from_eeprom() {\n\n    mac=00:00:00:00:00:00\n\n    if [  -f  \"/opt/cisco/bin/idprom\" ]; then\n\n            # This would provide the output for x86 mac address\n\t    temp_mac=$(idprom /sys/bus/i2c/devices/8-0054/eeprom | grep MACADDR_BASE | awk '{print $3}')\n        if [ -z \"$temp_mac\" ]; then\n            echo \"mac address not found\"\n        else\n            mac=$(sed -e \"s/\\(..\\)\\(..\\)\\(..\\)\\(..\\)\\(..\\)\\(..\\)/\\1:\\2:\\3:\\4:\\5:\\6/\" <<< \"$temp_mac\")\n        fi\n\n    else\n\n        # Temporary workaround until we get the idprom utility via PR for BSP\n        hexdump -ve '1/1 \"%.2x\"' /sys/bus/i2c/devices/8-0054/eeprom > /tmp/eeprom_data\n\n        ((i = 0))\n        ((j = 0))\n        while [[ $i -lt 512 ]]\n        do\n            var=$( dd skip=$i count=4 if=/tmp/eeprom_data bs=1 2> /dev/null )\n            if [ \"$var\" = \"cf06\" ];then\n                ((j = j + 1))\n                if [[ $j -eq 1 ]];then\n                    ((i = i + 4))\n                    continue\n                fi\n                ((i = i + 4))\n                mac1=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac2=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac3=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac4=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac5=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n                ((i = i + 2))\n                mac6=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n\n                mac=$mac1:$mac2:$mac3:$mac4:$mac5:$mac6\n                break\n            fi\n            ((i = i + 1))\n        done\n        rm /tmp/eeprom_data\n    fi\n\n    echo \"$mac\"\n}\n", "num_lines": 197}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on BMC EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin:/opt/cisco/bin\n. /usr/local/bin/board-utils.sh\n\n# get the MAC from EEPROM\nmac=$(read_mac_from_eeprom)\necho \"mac is $mac\"\n\n# get the MAC from u-boot environment\nethaddr=$(fw_printenv | grep \"^ethaddr=\" | cut -d'=' -f2)\n\nif [ \"$mac\" = \"00:00:00:00:00:00\" ] || [ \"$mac\" = \"ff:ff:ff:ff:ff:ff\" ]; then\n    if [ -n \"$ethaddr\" ]; then\n        # no MAC from EEPROM, use the one from u-boot environment\n        echo \"No MAC address from EEPROM: use $ethaddr from uboot-env\"\n        mac=\"$ethaddr\"\n    else\n        echo \"Error: unable to read MAC address from EEPROM or uboot-env!\"\n        mac=ba:d0:4a:9c:4e:ce\n    fi\nfi\n\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    # set the MAC from EEPROM back to u-boot environment so that\n    # u-boot can use it\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n\necho \"Update BMC eth0 MAC address to $mac\"\nip link set dev eth0 address \"$mac\"\nexit $?\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#shellcheck disable=SC1091\n#shellcheck disable=SC2001\n#shellcheck disable=SC2059\n. /usr/local/bin/openbmc-utils.sh\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG4 TXD8_SD2DAT2_SALT13 2> /dev/null\n\ncached_eeprom_dir=/mnt/data1/mac_idprom\ncache_eeprom_file=/mnt/data1/mac_idprom/cached_eeprom_54\neeprom_file=/sys/bus/i2c/devices/8-0054/eeprom\ncrc_cal_file=/usr/local/bin/crc_16.py\nstartfile=/tmp/startfile\nendfile=/tmp/endfile\nerasefile=/tmp/erasefile\ninputfile=/tmp/inputfile\neeprom_data=/tmp/eeprom_data\n\n# Start Bytes\nprintf '\\xcf\\x06' > $startfile\n# End Bytes\nprintf '\\x43\\x00\\x01' > $endfile\n# ff bytes for paddding at the end\nprintf '\\xff' > $erasefile\n\nprog=$0\n\nusage() {\n    echo\n    echo \"Usage: $prog <Mac_Address>\"\n    echo\n    echo \"Mac Address:\"\n    echo \"  Format(Hex): xx:xx:xx:xx:xx:xx \"\n    echo \"  Example    : d4:eb:68:b5:65:68\"\n    echo\n}\n\nclean_up() {\n    # cleaning up temp files\n    rm $startfile 2> /dev/null\n    rm $endfile 2> /dev/null\n    rm $erasefile 2> /dev/null\n    rm $inputfile 2> /dev/null\n}\n\nget_idprom_permission () {\n\n    perm=$( gpio_get_value TXD8_SD2DAT2_SALT13 )\n    echo \"$perm\"\n\n}\n\nset_idprom_permission () {\n\n    gpio_set_value TXD8_SD2DAT2_SALT13 \"$1\"\n\n}\n\npadding_cache_eeprom_mac () {\n\n    ((i = \"${1}\"))\n    while [[ $i -lt 512 ]]\n    do\n        dd seek=$i count=1 if=$erasefile of=$cache_eeprom_file bs=1 2> /dev/null\n        ((i = i +1))\n    done\n\n}\n\nwrite_cache_eeprom_mac () {\n\n    ((i = \"${1}\")) \n    dd seek=$i count=2 if=$startfile of=$cache_eeprom_file bs=1 2> /dev/null\n    ((i = i + 2))\n    dd seek=$i count=6 if=$inputfile of=$cache_eeprom_file bs=1 2> /dev/null\n    end=$((i + 6))\n    dd seek=$end count=3 if=$endfile of=$cache_eeprom_file bs=1 2> /dev/null\n    end=$((end + 3))\n    echo $end\n}\n\nread_eeprom_end() {\n\n    hexdump -ve '1/1 \"%.2x\"' $cache_eeprom_file > $eeprom_data\n\n    ((i = 0))\n    while [[ $i -lt 512 ]]\n    do\n        # Looks for end of the eeprom content\n        # So, it checks for ffffffff bytes to mark the end\n        var=$( dd skip=$i count=8 if=$eeprom_data bs=1 2> /dev/null )\n        if [ \"$var\" = \"ffffffff\" ];then\n            echo $((i / 2))\n            break\n        fi\n        ((i = i + 1))\n    done\n\n    rm $eeprom_data\n\n}\n\ncheck_crc_mac_address() {\n\n    # Check for CRC of eeprom\n    crc=$(python $crc_cal_file $eeprom_file check)\n    if [[ $crc -eq 1 ]];then\n        echo \"CRC is Valid\"\n    else\n        echo \"Invalid CRC ... Fatal Error !\"\n        echo \"FAIL\"\n    fi\n\n    # Check for programmed mac address in eeprom\n    mac_address=$(read_x86_mac_from_eeprom)\n\n    if [[ $mac_address = \"$input_mac_address\" ]]; then\n        echo \"x86 mac address programmed successfully\"\n        echo \"PASS\"\n    else\n        echo \"x86 mac address is not programmed\"\n        echo \"FAIL\"\n    fi\n\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    clean_up\n    echo \"FAIL\"\n    exit 1\nfi\n\nif ! [[ $1 =~ ^([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}$ ]]; then\n    echo \"Invalid mac address\"\n    usage\n    clean_up\n    echo \"FAIL\"\n    exit 1\nfi\n\ninput_mac_address=\"$1\"\narg_str=$(echo \"$1\" | sed 's/:/\\\\x/g')\ninput_str=\"\\x$arg_str\"\nprintf \"$input_str\" > $inputfile\n\n# Check for mac address in eeprom\nmac_address=$(read_x86_mac_from_eeprom)\nmac_address_present=0\n\nif [[ $mac_address =~ ^([[:xdigit:]]{2}:){5}[[:xdigit:]]{2}$ ]]; then\n    echo \"x86 mac address is present\"\n    mac_address_present=1\nelse\n    echo \"No x86 mac address\"\nfi\n\n# CRC check\ncrc=$(python $crc_cal_file $eeprom_file check)\n\nif [[ $crc -eq 1 ]];then\n    echo \"CRC is Valid\"\n    if [[ $mac_address_present -eq 1 ]];then\n        clean_up\n        echo \"PASS\"\n        exit 1\n    fi\n    mkdir -p $cached_eeprom_dir\n    # Copying EEPROM to buffer\n    dd if=$eeprom_file of=$cache_eeprom_file 2> /dev/null\n    sync\nelse\n    echo \"Invalid CRC... checking for cached eeprom\"\n    if [  -f  \"$cache_eeprom_file\" ]; then\n        echo \"Cache file is present\"\n        crc=$(python $crc_cal_file $cache_eeprom_file check)\n        if [[ $crc -eq 1 ]];then\n            set_idprom_permission 0\n            dd if=$cache_eeprom_file of=$eeprom_file 2> /dev/null\n            set_idprom_permission 1\n            check_crc_mac_address\n            clean_up\n            exit 1\n        else\n            echo \"Fatal Error! Cached eeprom has bad CRC. Unable to repair IDPROM\"\n            clean_up\n            echo \"FAIL\"\n            exit 1\n        fi\n    else\n        echo \"Fatal Error! IDPROM is corrupt and no cached IDPROM is available. Unable to repair IDPROM\"\n        clean_up\n        echo \"FAIL\"\n        exit 1\n    fi\nfi\n\n# Get start address to write from\nstart_address=$(read_eeprom_end)\n\n# Writing x86 mac address to eeprom\nend_address=$(write_cache_eeprom_mac \"$start_address\")\n\n# Padding ff to end of the buffer\npadding_cache_eeprom_mac \"$end_address\"\n\n# Updating the CRC for eeprom \n# after mac address addition\npython $crc_cal_file $cache_eeprom_file\n\n# Setting write permission\n# 0 - permission to write\n# 1 - permission denial\nset_idprom_permission 0\n\n# Copying buffer to EEPROM\ndd if=$cache_eeprom_file of=$eeprom_file 2> /dev/null\n\n# Setting back write protection\nset_idprom_permission 1\n\ncheck_crc_mac_address\n\nclean_up\n", "num_lines": 224}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nget_version () {\n    length=$( stat -c%s \"$1\" )\n    ((i = length - 4))\n    ((major_offset_found = 0))\n    while [[ $i -ne 0 ]]\n    do\n        var=$( dd skip=$i count=4 if=\"$1\" bs=1 2> /dev/null )\n        if [ \"$var\" = \"fa7f\" ];then\n            if [ $major_offset_found -eq 0 ]; then\n                ((major_offset_found = 1))\n                ((major_offset = i + 4))\n            else\n                ((minor_offset = i + 4))\n                break\n            fi\n        fi\n        ((i = i - 1))\n    done\n    major=$( dd skip=$major_offset count=2 if=\"$1\" bs=1 2> /dev/null)\n    minor=$( dd skip=$minor_offset count=2 if=\"$1\" bs=1 2> /dev/null)\n    echo \"version is $major.$minor\"\n}\n\n#Port 0 - I210 (x86 side)\n#Port 1 - 1G PHY (front panel) ethernet port\n#Port 5 - BMC CPU\nmonitored_ports=(\"0\" \"1\" \"5\")\n\nstart_monitoring() {\n    reset_count=0\n    while : ; do\n        sleep 3\n        if ! echo \"status\" > /dev/switch 2> /dev/null; then\n            # A device busy error may be seen if more than\n            # one instance of this script is run at the same\n            # time\n            continue\n        fi\n        ports_status=$( tr -d '\\0' < /dev/switch )\n        if [ \"$ports_status\" ]; then\n            # Loop over the \"ports_status\" line by line, each line has\n            # the status of one port. If that port status was not read\n            # before (i.e first check) then it is printed out, but if\n            # the status was read before then it is only printed\n            # if the status has changed since the last check.\n            # Sample \"ports_status\" output:\n                  #Link status for port 0 is UP\n                  #Link status for port 1 is UP\n                  #Link status for port 2 is DOWN\n                  #Link status for port 3 is DOWN\n                  #Link status for port 4 is DOWN\n                  #Link status for port 5 is UP\n                  #Link status for port 6 is DOWN\n            # The \"all_ports_down\" flag is set to true before the ports\n            # status is checked, then if any of the ports is UP the flag\n            # is set to false. If \"all_ports_down\" flag is true for 2\n            # polling intervals (i.e. all ports are down for more than\n            # three seconds, then the switch will be reset to recover for a\n            # maximum three consecutive attempts.\n            all_ports_down=1\n            while read -r line\n            do\n                port=$( echo \"$line\" | cut -d ' ' -f 5)\n                status=$( echo \"$line\" | cut -d ' ' -f 7)\n                if [[ -z \"$port\" ]]; then\n                    continue\n                fi\n                if [[ \" ${monitored_ports[*]} \" =~ $port ]]; then\n                    if [ -z \"${port_status[$port]}\" ]; then\n                        printf '%(%Y-%m-%d %H:%M:%S)T\\n' -1\n                        printf \"port %s link status is %s\\n\" \"$port\" \"$status\"\n                        port_status[\"$port\"]=$status\n                    else\n                        if [[ \"${port_status[$port]}\" != \"$status\" ]]; then\n                            printf '%(%Y-%m-%d %H:%M:%S)T\\n' -1\n                            printf \"port %s link status changed to %s\\n\" \"$port\" \"$status\"\n                        fi\n                    fi\n                    port_status[\"$port\"]=$status\n                    if [ \"$status\" = \"UP\" ]; then\n                        # For testing only, to trigger a switch reset\n                        if [ ! -f /tmp/link_down_test ]; then\n                            all_ports_down=0\n                        fi\n                    fi\n                fi\n            done < <(printf '%s\\n' \"$ports_status\")\n\n            if [ \"$all_ports_down\" -eq 1 ]; then\n                if [ -n \"$reset_pending\" ] && [ \"$reset_pending\" -eq 1 ]; then\n                    printf '%(%Y-%m-%d %H:%M:%S)T\\n' -1\n                    printf \"all ports are down, resetting the switch to recover\\n\"\n                    # RESET SWITCH\n                    oob_switch_reset\n                    ((reset_count+=1))\n                    # Testing shows that MDIO access fails for 3 or 4\n                    # seconds after switch reset\n                    sleep 6\n                    reset_pending=0\n                else\n                    if [ \"$reset_count\" -eq 3 ]; then\n                        printf '%(%Y-%m-%d %H:%M:%S)T\\n' -1\n                        printf \"all ports are down, exhausted all %s recovery attempts\\n\" \"$reset_count\"\n                        # May issue router power cycle at the point\n                        exit 0\n                    fi\n                    reset_pending=1\n                fi\n            else\n                reset_count=0\n                reset_pending=0\n            fi\n        fi\n    done\n}\n\ngb_util() {\n\n    if [ ! -f /sys/bus/i2c/devices/8-0050/eeprom ]; then\n        echo \"/sys/bus/i2c/devices/8-0050/eeprom does not exist\"\n        return 1\n    fi\n\n    if [ \"$1\" = \"upgrade\" ];then\n        if [ -f \"$2\" ]; then\n            oob_switch_eeprom_select \n            cat < \"$2\" 1<> /sys/bus/i2c/devices/8-0050/eeprom\n            oob_switch_eeprom_deselect \n        else \n            echo \"$2 does not exist\"\n        fi\n    fi\n\n    if [ \"$1\" = \"enable\" ];then\n        oob_switch_eeprom_select \n    fi\n\n    if [ \"$1\" = \"disable\" ];then\n        oob_switch_eeprom_deselect \n    fi\n\n    if [ \"$1\" = \"reset\" ];then\n        oob_switch_reset \n    fi\n\n    if [ \"$1\" = \"erase\" ];then\n        printf '\\xff' > /tmp/erasefile\n        oob_switch_eeprom_select \n        ((i = 0))\n        while [[ $i -lt 512 ]]\n        do\n            dd seek=$i count=1 if=/tmp/erasefile of=/sys/bus/i2c/devices/8-0050/eeprom bs=1 2> /dev/null\n            ((i = i +1))\n        done\n        oob_switch_eeprom_deselect \n        rm /tmp/erasefile\n    fi\n\n    if [ \"$1\" = \"eeprom_version\" ];then\n        oob_switch_eeprom_select\n        hexdump -ve '1/1 \"%.2x\"' /sys/bus/i2c/devices/8-0050/eeprom > /tmp/eeprom_data\n        oob_switch_eeprom_deselect\n        get_version /tmp/eeprom_data\n        rm /tmp/eeprom_data\n    fi\n\n    if [ \"$1\" = \"packaged_version\" ];then\n        hexdump -ve '1/1 \"%.2x\"' \"$2\" > /tmp/eeprom_data\n        get_version /tmp/eeprom_data\n        rm /tmp/eeprom_data\n    fi\n\n    if [ \"$1\" = \"check\" ];then\n        i2cset -f -y 12 0x31 0x0c\n        i2cset -f -y 12 0x32 0x00\n        i2cset -f -y 12 0x33 0x00\n        i2cset -f -y 12 0x34 0x00\n        i2cset -f -y 12 0x30 0x1\n        access=$( i2cget -f -y 12 0x35 )\n        if [ $(( access & 0x4 )) -eq $(( 0x0 )) ]; then\n            echo \"access is disabled\"\n        else\n            echo \"access is enabled\"\n        fi\n    fi\n\n    if [ \"$1\" = \"status\" ];then\n        if [ ! -c \"/dev/switch\" ]; then\n            echo \"/dev/switch does not exist, mv88e6320 kernel module needed\"\n            return 1\n        fi\n        if echo \"status\" > /dev/switch 2> /dev/null; then\n            cat /dev/switch\n        fi\n    fi\n\n    if [ \"$1\" = \"statistics\" ];then\n        if [ ! -c \"/dev/switch\" ]; then\n            echo \"/dev/switch does not exist, mv88e6320 kernel module needed\"\n            return 1\n        fi\n        if echo \"statistics\" > /dev/switch 2> /dev/null; then\n            cat /dev/switch\n        fi\n    fi\n\n    if [ \"$1\" = \"monitor\" ];then\n        if [ ! -c \"/dev/switch\" ]; then\n            echo \"/dev/switch does not exist, mv88e6320 kernel module needed\"\n            return 1\n        fi\n        start_monitoring\n    fi\n}\n\ncase \"$1\" in\n    \"--help\" | \"?\" | \"-h\")\n        program=$(basename \"$0\")\n        echo \"Usage: switch firmware upgrade command\"\n        echo \"  <$program upgrade image> enable access to switch EEPROM, upgrade FW with provided image, then disable access\"\n        echo \"  <$program enable> enable access to switch EEPROM for firmware upgrade\"\n        echo \"  <$program disable> disable access to switch EEPROM\"\n        echo \"  <$program reset> reset switch, can be done after FW upgrade to activate new image\"\n        echo \"  <$program erase> erase the FW image from the switch EEPROM, switch will boot with HW configuration after next reset\"\n        echo \"  <$program eeprom_version> get the FW version from the switch EEPROM\"\n        echo \"  <$program packaged_version image> get the FW version from the switch FW image file\" \n        echo \"  <$program check> check access status to switch EEPROM\"\n        echo \"  <$program status> get all ports status (UP or DOWN)\"\n        echo \"  <$program statistics> get statisitcs for ports that are UP\"\n        echo \"  <$program monitor> start monitoring and recovery. Switch will be reset if all used ports are DOWN for more than 3 seconds\"\n    ;;\n\n    *)\n        gb_util \"$1\" \"$2\"\n    ;;\nesac\n", "num_lines": 259}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:    85\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Power on if not already powered on\nwedge_power.sh on\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/bin/board-utils.sh\n\n#BMC Temp sensor\ni2c_device_add 8 0x4A lm75\n\n#BMC IDPROM\ni2c_device_add 8 0x54 24c64\n\n#Chassis IDPROM\ni2c_device_add 8 0x56 24c64\n\n#enable access to GE switch EEPROM\noob_switch_eeprom_select\n\n#GE switch EEPROM\ni2c_device_add 8 0x50 24c04\n\n#disable access to GE switch EEPROM\noob_switch_eeprom_deselect\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091,SC2009\n. /usr/local/bin/openbmc-utils.sh\n\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS4\n\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n        awk '{print $1}')\n  if [ \"$pid\" ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -e $FILE ]; then\n    read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 \"$TTY\"\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\necho 0x3 > \"$SMBCPLD_SYSFS_DIR/uart_selection\"\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) 2022 Cisco Systems Inc.\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current x86 power status\"\n    echo\n    echo \"  on: Power on x86 if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if x86 has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off x86 ungracefully\"\n    echo\n    echo \"  reset: Power reset x86 ungracefully\"\n    echo\n    echo\n}\n\ndo_status() {\n    cat /sys/bus/platform/devices/pseq/power_state\n}\n\ndo_on_com_e() {\n    #Commands to turn x86 on\n    PDEV=/sys/bus/platform/devices\n    if [ -w ${PDEV}/pseq/config ]; then\n        echo on > ${PDEV}/pseq/config\n    else\n        i2cset -f -y 2 0x21 0x8c\n        i2cset -f -y 2 0x22 0x40\n        i2cset -f -y 2 0x23 0x01\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x02\n        i2cset -f -y 2 0x20 0x0\n    fi\n}\n\ndo_on() {\n    local force opt\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    echo -n \"Power on x86 ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if power is on or not\n        do_status | grep \"on\"\n        if [ $? == 0 ]; then\n            echo \" Skip!\"\n            return 1\n        fi\n    fi\n\n    do_on_com_e\n    echo \" Done\"\n}\n\ndo_off_com_e() {\n    PDEV=/sys/bus/platform/devices\n    if [ -w ${PDEV}/pseq/config ]; then\n        echo off > ${PDEV}/pseq/config\n    else\n        i2cset -f -y 2 0x21 0x8c\n        i2cset -f -y 2 0x22 0x40\n        i2cset -f -y 2 0x23 0x01\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x04\n        i2cset -f -y 2 0x20 0x0\n    fi\n}\n\ndo_off() {\n    echo -n \"Power off x86 ...\"\n    do_off_com_e\n    echo \" Done\"\n}\n\ndo_reset_com_e() {\n    #Commands to reboot x86\n    PDEV=/sys/bus/platform/devices\n    if [ -w ${PDEV}/pseq/config ]; then\n        echo cycle > ${PDEV}/pseq/config\n    else\n        i2cset -f -y 2 0x21 0x8c\n        i2cset -f -y 2 0x22 0x40\n        i2cset -f -y 2 0x23 0x01\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x08\n        i2cset -f -y 2 0x20 0x0\n    fi\n}\n\ndo_reset() {\n    echo -n \"Reset x86 ...\"\n    do_reset_com_e\n    echo \" Done\"\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\n\nexit $?\n", "num_lines": 162}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\neeprom_file=/sys/bus/i2c/devices/8-0054/eeprom\ncrc_cal_file=/usr/local/bin/crc_16.py\n\ncrc=$(python $crc_cal_file $eeprom_file check)\nif [[ $crc -eq 1 ]];then\n    echo \"CRC is Valid\"\nelse\n    echo \"Invalid CRC ... Fatal Error !\"\nfi\n\nread_x86_mac_from_eeprom\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.usb0.pid\"\nexec dhclient -1 -6 -d -D LL --address-prefix-len 64 -pf ${pid} usb0 \"$@\"\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\n/usr/local/bin/front-paneld &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# execute <fscd.py> <min syslog level>\n# log_level = <debug, warning, info>\n# Default log level in fscd is set to warning, if any other level is needed\n# set here\n. /usr/local/fbpackages/utils/ast-functions\n\ndefault_fsc_config=\"/etc/fsc-config.json\"\nif [[ -f ${default_fsc_config} ]]; then\n  rm ${default_fsc_config}\nfi\n\ngp_board_id0=$(gpio_get BOARD_ID0 GPION5)\ngp_board_id1=$(gpio_get BOARD_ID1 GPION6)\ngp_board_id2=$(gpio_get BOARD_ID2 GPION7)\n\nif [ $gp_board_id0 -eq 1 ] && [ $gp_board_id1 -eq 1 ] && [ $gp_board_id2 -eq 0 ]; then\n  ln -s /etc/fsc-config_BRCM.json ${default_fsc_config}\nelse\n  ln -s /etc/fsc-config_MICRON.json ${default_fsc_config}\nfi\n\nexec /usr/bin/fscd.py 'warning'\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho \"Setup fan speed... \"\n/usr/local/bin/fan-util --set 70\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup gpio monitoring for clearcreek... \"\n\n/usr/local/bin/gpiod &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 0 1", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 8 1", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\ni2c_mslave_add 0 0x17 #MB\ni2c_mslave_add 8 0x10 #USB DBG\ni2c_mslave_add 1 0x10  #NIC0\ni2c_mslave_add 9 0x10  #NIC1\ni2c_mslave_add 2 0x10  #NIC2\ni2c_mslave_add 10 0x10 #NIC3\ni2c_mslave_add 4 0x10  #NIC4\ni2c_mslave_add 11 0x10 #NIC5\ni2c_mslave_add 7 0x10  #NIC6\ni2c_mslave_add 13 0x10 #NIC7\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_8 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n/etc/init.d/sync-rtc.sh &", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# To enable GPIOAC\ndevmem_clear_bit $(scu_addr ac) 0\ndevmem_clear_bit $(scu_addr ac) 1\ndevmem_clear_bit $(scu_addr ac) 2\ndevmem_clear_bit $(scu_addr ac) 3\ndevmem_clear_bit $(scu_addr ac) 5\ndevmem_clear_bit $(scu_addr ac) 6\ndevmem_clear_bit $(scu_addr ac) 7\n\n#setup BMC SKU ID\ngpio_export SKU_ID1_PAX0 GPIOB6\n\ngpio_export SKU_ID0_PAX0 GPIOAC0\n\ngpio_export SKU_ID1_PAX1 GPIOB7\n\ngpio_export SKU_ID0_PAX1 GPIOAC2\n\ngpio_export SKU_ID1_PAX2 GPIOM0\n\ngpio_export SKU_ID0_PAX2 GPIOB0\n\ngpio_export SKU_ID1_PAX3 GPIOM6\n\ngpio_export SKU_ID0_PAX3 GPIOB4\n\n# PDB 12V POWER (output)\ngpio_export BMC_IPMI_PWR_ON GPIOE1\ngpio_set BMC_IPMI_PWR_ON 1\n\n# BMC ready\ngpio_export BMC_READY_N GPIOB2\n\n# System power good\ngpio_export SYS_PWR_READY GPIOB3\n\n# BMC power button (input)\ngpio_export BMC_PWR_BTN_IN_N GPIOE0\n\ngpio_set BMC_READY_N 0\n\n# CPLD SMB ALERT\ngpio_export CPLD_SMB_ALERT_N_R GPIOE5\n\ngpio_export RST_PEX_I2C_SW_R_N GPIOA0\n\n# Reserved\ngpio_export BMC_GPIOA1 GPIOA1\ngpio_export BMC_GPIOA2 GPIOA2\ngpio_export BMC_GPIOA3 GPIOA3\n\n# POST LED \ngpio_export LED_POSTCODE_0 GPIOF0\ngpio_set LED_POSTCODE_0 0\ngpio_export LED_POSTCODE_1 GPIOF1\ngpio_set LED_POSTCODE_1 0\ngpio_export LED_POSTCODE_2 GPIOF2\ngpio_set LED_POSTCODE_2 0\ngpio_export LED_POSTCODE_3 GPIOF3\ngpio_set LED_POSTCODE_3 0\ngpio_export LED_POSTCODE_4 GPIOF4\ngpio_set LED_POSTCODE_4 0\ngpio_export LED_POSTCODE_5 GPIOF5\ngpio_set LED_POSTCODE_5 0\ngpio_export LED_POSTCODE_6 GPIOF6\ngpio_set LED_POSTCODE_6 0\ngpio_export LED_POSTCODE_7 GPIOF7\ngpio_set LED_POSTCODE_7 0\n\ngpio_export PEX0_SYS_ERR_BMC GPION4\ngpio_export PEX1_SYS_ERR_BMC GPIOG0\ngpio_export PEX2_SYS_ERR_BMC GPIOG3\ngpio_export PEX3_SYS_ERR_BMC GPIOG7\n\n# Board revision ID\ngpio_export REV_ID0 GPIOG4\ngpio_export REV_ID1 GPIOG5\ngpio_export REV_ID2 GPIOG6\n\nkv set mb_rev $(($(gpio_get REV_ID2)<<2 |\n        $(gpio_get REV_ID1)<<1 |\n        $(gpio_get REV_ID0)))\n\n# OCP3.0 NIC power good\ngpio_export OCP_V3_0_NIC_POWER_GOOD GPIOH0\ngpio_export OCP_V3_1_NIC_POWER_GOOD GPIOH1\ngpio_export OCP_V3_2_NIC_POWER_GOOD GPIOH2\ngpio_export OCP_V3_3_NIC_POWER_GOOD GPIOH3\ngpio_export OCP_V3_4_NIC_POWER_GOOD GPIOH4\ngpio_export OCP_V3_5_NIC_POWER_GOOD GPIOH5\ngpio_export OCP_V3_6_NIC_POWER_GOOD GPIOH6\ngpio_export OCP_V3_7_NIC_POWER_GOOD GPIOH7\n\n# SEL FLASH PAX\ngpio_export SEL_FLASH_PAX0 GPIOAA0\ngpio_export SEL_FLASH_PAX1 GPIOAA1\ngpio_export SEL_FLASH_PAX2 GPIOAA5\ngpio_export SEL_FLASH_PAX3 GPIOAA6\n\ngpio_export OCP_V3_3_PRSNTB_R_N GPIOAA2\ngpio_export OCP_V3_4_PRSNTB_R_N GPIOAA3\ngpio_export OCP_V3_5_PRSNTB_R_N GPIOAB3\n\ngpio_export CARRIER_0_ALERT_R_N GPIOAB0\ngpio_export CARRIER_1_ALERT_R_N GPIOAB1\n\ngpio_export BMC_BOOT_RCVR_B0_PAX0 GPIOL0\ngpio_set BMC_BOOT_RCVR_B0_PAX0 0\ngpio_export BMC_BOOT_RCVR_B0_PAX1 GPIOL1\ngpio_set BMC_BOOT_RCVR_B0_PAX1 0\ngpio_export BMC_BOOT_RCVR_B0_PAX2 GPIOL2\ngpio_set BMC_BOOT_RCVR_B0_PAX2 0\ngpio_export BMC_BOOT_RCVR_B0_PAX3 GPIOL3\ngpio_set BMC_BOOT_RCVR_B0_PAX3 0\n\n# BSM EMMC PRSNT\ngpio_export BSM_EMMC_PRSNT_R_N GPIOL4\n\ngpio_export RST_BMC_SMB4_BUF_R_N GPIOL5\n\n# NVME PRSNT\ngpio_export NVME_0_1_PRSNTB_R_N GPIOL6\ngpio_export NVME_2_3_PRSNTB_R_N GPIOL7\n\ngpio_export SMB_MB_BMC_MUX_OE_R GPIOM3\ngpio_set SMB_MB_BMC_MUX_OE_R 0\ngpio_export SMB_MB_BMC_MUX_S0_R GPIOM4\ngpio_set SMB_MB_BMC_MUX_S0_R 1\ngpio_export SMB_MB_BMC_MUX_S1_R GPIOM5\ngpio_set SMB_MB_BMC_MUX_S1_R 0\n\n# BOARD ID\ngpio_export BOARD_ID0 GPION5\ngpio_export BOARD_ID1 GPION6\ngpio_export BOARD_ID2 GPION7\n\n# BATTERY_DETECT\ngpio_export BATTERY_DETECT GPIOQ6\ngpio_set BATTERY_DETECT 0\n\ngpio_export SMB_PMBUS_ISO_HSC_R2_ALERT_0_1 GPIOS0\ngpio_export SMB_PMBUS_ISO_HSC_R2_ALERT_2_3 GPIOS1\ngpio_export OCP_V3_6_PRSNTB_R_N GPIOS2\ngpio_export OCP_V3_7_PRSNTB_R_N GPIOS3\ngpio_export PD_GPIOS4 GPIOS4\ngpio_set PD_GPIOS4 0\ngpio_export PD_GPIOS5 GPIOS5\ngpio_export PD_GPIOS6 GPIOS6\ngpio_set PD_GPIOS6 0\ngpio_export PD_GPIOS7 GPIOS7\ngpio_set PD_GPIOS7 0\n\ngpio_export RST_SMB_CARRIER_N GPIOY0\ngpio_export OCP_V3_0_PRSNTB_R_N GPIOY3\n\ngpio_export OCP_V3_1_PRSNTB_R_N GPIOZ2\ngpio_export OCP_V3_2_PRSNTB_R_N GPIOZ3\n\ngpio_export PU_GPIOZ4 GPIOZ4\ngpio_set PU_GPIOZ4 0\ngpio_export PU_GPIOZ5 GPIOZ5\ngpio_set PU_GPIOZ5 0\ngpio_export PU_GPIOZ6 GPIOZ6\ngpio_set PU_GPIOZ6 0\ngpio_export PU_GPIOZ7 GPIOZ7\ngpio_set PU_GPIOZ7 1\n\ngpio_export NCSI_BMC_TX_EN GPIOT1\ngpio_set NCSI_BMC_TX_EN 0\ngpio_export NCSI_BMC_TXD0 GPIOT2\ngpio_set NCSI_BMC_TXD0 0\ngpio_export NCSI_BMC_TXD1 GPIOT3\ngpio_set NCSI_BMC_TXD1 0\ngpio_export PD_GPIOT4 GPIOT4\ngpio_set PD_GPIOT4 0\ngpio_export PD_GPIOT5 GPIOT5\ngpio_set PD_GPIOT5 0\n\ngpio_export NCSI_BMC_2_TX_EN GPIOT7\ngpio_set NCSI_BMC_2_TX_EN 0\ngpio_export NCSI_BMC_2_TXD0 GPIOU0\ngpio_set NCSI_BMC_2_TXD0 0\ngpio_export NCSI_BMC_2_TXD1 GPIOU1\ngpio_set NCSI_BMC_2_TXD1 0\ngpio_export PD_GPIOU2 GPIOU2\ngpio_set PD_GPIOU2 0\ngpio_export PD_GPIOU3 GPIOU3\ngpio_set PD_GPIOU3 0\n\ngpio_export USB2_SEL0 GPIOZ0\ngpio_set USB2_SEL0 0\ngpio_export USB2_SEL1 GPIOZ1\ngpio_set USB2_SEL1 0\n\n# To enable GPIOP\ndevmem_clear_bit $(scu_addr 88) 16\ndevmem_clear_bit $(scu_addr 88) 17\ndevmem_clear_bit $(scu_addr 88) 18\ndevmem_clear_bit $(scu_addr 88) 19\ndevmem_clear_bit $(scu_addr 88) 20\ndevmem_clear_bit $(scu_addr 88) 21\ndevmem_clear_bit $(scu_addr 88) 22\ndevmem_clear_bit $(scu_addr 88) 23\n\ngpio_export BMC_FORCE_THROTTLE_N GPIOP6\ngpio_set BMC_FORCE_THROTTLE_N 1\ngpio_export HSC_TIMER_R_N GPIOP2\ngpio_export HSC_OC_R_N GPIOP3\ngpio_export HSC_UV_R_N GPIOP4\ngpio_export PMBUS_HSC_ALERT_R_N GPIOP5\ngpio_export FM_SYS_THROTTLE_R GPIOP7\n\ngpio_export EP0_CBL_PRSNT_R1 GPIOJ0\ngpio_export EP1_CBL_PRSNT_R1 GPIOJ1\ngpio_export EP2_CBL_PRSNT_R1 GPIOJ2\ngpio_export EP3_CBL_PRSNT_R1 GPIOJ3\ngpio_export MB0_CBL_PRSNT_P1_R1 GPIOJ4\ngpio_export MB0_CBL_PRSNT_P0_R1 GPIOJ5\ngpio_export MB1_CBL_PRSNT_P1_R1 GPIOJ6\ngpio_export MB1_CBL_PRSNT_P0_R1 GPIOJ7\n\ngpio_export RST_PMBUS_N GPIOY1\ngpio_set RST_PMBUS_N 1\n\ngpio_export RST_FIO_IOEXP_N GPIOY2\ngpio_set RST_FIO_IOEXP_N 1\n\ngpio_export CPLD_BMC_GPIO_R_01 GPIOAC3\n\ngpio_export CPLD_BMC_GPIO_R_00 GPIOAC1\ngpio_set CPLD_BMC_GPIO_R_00 0\n", "num_lines": 267}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/fbpackages/utils/ast-functions\n\nKVSET_CMD=/usr/bin/kv\n\necho \"Setup TCA9539 input/output pin\"\ni2cset -y -f 5 0x77 0x06 0x00\ni2cset -y -f 5 0x77 0x07 0x0f\ni2cset -y -f 5 0x77 0x02 0x0f\n\n#Setup BB MAXIM ADC\ngp_board_id0=$(gpio_get BOARD_ID0 GPION5)\ngp_board_id1=$(gpio_get BOARD_ID1 GPION6)\nif [ $gp_board_id0 -eq 1 ] && [ $gp_board_id1 -eq 0 ]; then\n  i2c_device_add 23 0x33 max11615\n  i2c_device_add 23 0x35 max11617\nfi\n\n#Setup TMP75 for carrier board\ngp_carrier1_prsnt=$(gpio_get NVME_0_1_PRSNTB_R_N)\nif [ $gp_carrier1_prsnt -eq 0 ]; then\n  i2c_device_add 21 0x48 tmp75\n  i2c_device_add 21 0x49 tmp75\n  i2cset -y -f 21 0x1d 0x0b 0x2\n  i2cset -y -f 21 0x1f 0x0b 0x2\n  i2c_device_add 21 0x1d adc128d818\n  i2c_device_add 21 0x1f adc128d818\nfi\n\ngp_carrier2_prsnt=$(gpio_get NVME_2_3_PRSNTB_R_N)\nif [ $gp_carrier2_prsnt -eq 0 ]; then\n  i2c_device_add 22 0x48 tmp75\n  i2c_device_add 22 0x49 tmp75\n  i2cset -y -f 22 0x1d 0x0b 0x2\n  i2cset -y -f 22 0x1f 0x0b 0x2\n  i2c_device_add 22 0x1d adc128d818\n  i2c_device_add 22 0x1f adc128d818\nfi\n\n#Set PWR_AVR to 128 samples\ni2cset -y -f 5 0x11 0xd4 0x3F1E w\n\n#Set FIO LED\ni2cset -y -f 0x08 0x77 0x7 0x3F\ni2cset -y -f 0x08 0x77 0x3 0x80\n\n#Check carrier#0 type\nretry=0\nwhile [ $retry -lt 3 ]\ndo\ncarrier0=`i2ctransfer -f -y 23 w2@0x17 0x00 0x05 r1`\nif [ $carrier0 = \"0xcc\" ]; then\n    $KVSET_CMD set \"carrier_0\" \"m.2\"\n    i2cset -y -f 21 0x77 0x2 0xFF\n    echo \"Carrier#0 Type is m.2\"\n    #Set M.2 carrier INA219 Calibration register\n    i2cset -y -f 21 0x45 5 0xC800 w\n    break\nelif [ $carrier0 = \"0x22\" ] || [ $carrier0 = \"0x44\" ]; then\n    $KVSET_CMD set \"carrier_0\" \"e1.s\"\n    i2cset -y -f 21 0x77 0x02 0x00\n    echo \"Carrier#0 Type is e1.s\"\n    break\nelif [ $carrier0 = \"0x33\" ]; then\n    $KVSET_CMD set \"carrier_0\" \"e1.s_v2\"\n    i2cset -y -f 21 0x77 0x02 0x00\n    echo \"Carrier#0 Type is e1.s_v2\"\n    break\nelif [ $carrier0 = \"0xdd\" ]; then\n    $KVSET_CMD set \"carrier_0\" \"m.2_v2\"\n    i2cset -y -f 21 0x77 0x02 0xFF\n    echo \"Carrier#0 Type is m.2_v2\"\n    #Set M.2 carrier INA219 Calibration register\n    i2cset -y -f 21 0x45 5 0xC800 w\n    break\nelse\n    retry=$(($retry+1))\nfi\ndone\n\n#Check carrier#1 type\nretry=0\nwhile [ $retry -lt 3 ]\ndo\ncarrier1=`i2ctransfer -f -y 23 w2@0x17 0x00 0x06 r1`\nif [ $carrier1 = \"0xcc\" ]; then\n    $KVSET_CMD set \"carrier_1\" \"m.2\"\n    i2cset -y -f 22 0x77 0x2 0xFF\n    echo \"Carrier#1 Type is m.2\"\n    #Set M.2 carrier INA219 Calibration register\n    i2cset -y -f 22 0x45 5 0xC800 w\n    break\nelif [ $carrier1 = \"0x22\" ] || [ $carrier1 = \"0x44\" ]; then\n    $KVSET_CMD set \"carrier_1\" \"e1.s\"\n    i2cset -y -f 22 0x77 0x02 0x00\n    echo \"Carrier#1 Type is e1.s\"\n    break\nelif [ $carrier1 = \"0x33\" ]; then\n    $KVSET_CMD set \"carrier_1\" \"e1.s_v2\"\n    i2cset -y -f 22 0x77 0x02 0x00\n    echo \"Carrier#1 Type is e1.s_v2\"\n    break\nelif [ $carrier1 = \"0xdd\" ]; then\n    $KVSET_CMD set \"carrier_1\" \"m.2_v2\"\n    i2cset -y -f 22 0x77 0x02 0xFF\n    echo \"Carrier#1 Type is m.2_v2\"\n    #Set M.2 carrier INA219 Calibration register\n    i2cset -y -f 22 0x45 5 0xC800 w\n    break\nelse\n    retry=$(($retry+1))\nfi\ndone\n\n# Mark driver loaded\necho > /tmp/driver_probed\n", "num_lines": 138}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston\n\n. /usr/local/fbpackages/utils/ast-functions\n\nrev=$(kv get mb_rev)\n\nif [ $rev -eq 0 ]; then\n  gp_carrier1_prsnt=$(gpio_get NVME_0_1_PRSNTB_R_N)\n  if [ $gp_carrier1_prsnt -eq 0 ]; then\n    i2cset -y -f 21 0x77 0x6 0\n  fi\n\n  gp_carrier2_prsnt=$(gpio_get NVME_2_3_PRSNTB_R_N)\n  if [ $gp_carrier2_prsnt -eq 0 ]; then\n    i2cset -y -f 22 0x77 0x6 0\n  fi\nfi\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nif [ \"$(gpio_get OCP_V3_0_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 1 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_4_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 9 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_1_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 2 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_5_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 10 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_2_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 4 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_6_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 11 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_3_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 7 0x50 24c32\nfi\n\nif [ \"$(gpio_get OCP_V3_7_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 13 0x50 24c32\nfi\n\nif [ \"$(gpio_get NVME_0_1_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 21 0x50 24c64\nfi\n\nif [ \"$(gpio_get NVME_2_3_PRSNTB_R_N)\" == \"0\" ]; then\n  i2c_device_add 22 0x50 24c64\nfi\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/fbpackages/utils/ast-functions\n\ngp_sys_pwr_good=$(gpio_get SYS_PWR_READY GPIOB3)\nif [ $gp_sys_pwr_good -eq 1 ]; then\n  echo \"Setup TMP422 driver\"\n  i2c_device_add 6 0x4d tmp422\n  i2c_device_add 6 0x4e tmp422\n\n  echo \"Setup VR sensor driver\"\n\n  gp_board_id0=$(gpio_get BOARD_ID0 GPION5)\n  gp_board_id1=$(gpio_get BOARD_ID1 GPION6)\n  gp_board_id2=$(gpio_get BOARD_ID2 GPION7)\n\n  if [ $gp_board_id0 -eq 1 ] && [ $gp_board_id1 -eq 1 ] && [ $gp_board_id2 -eq 0 ]; then\n    i2c_device_add 5 0x34 mpq8645p\n    i2c_device_add 5 0x36 mpq8645p\n    i2c_device_add 5 0x60 isl69260\n    i2c_device_add 5 0x61 isl69260\n    i2c_device_add 5 0x72 isl69260\n    i2c_device_add 5 0x75 isl69260\n  else\n    i2c_device_add 5 0x30 mpq8645p\n    i2c_device_add 5 0x31 mpq8645p\n    i2c_device_add 5 0x32 mpq8645p\n    i2c_device_add 5 0x33 mpq8645p\n    i2c_device_add 5 0x34 mpq8645p\n    i2c_device_add 5 0x35 mpq8645p\n    i2c_device_add 5 0x36 mpq8645p\n    i2c_device_add 5 0x3b mpq8645p\n  fi\n\n  sv restart sensord\n  kv set pon_driver_loaded on\nfi\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ni2cset -f -y 17 0x2c 0x00 0x24 0x04 0x14 0x25 0x00 0x02 0xBB 0x20 0x02 0x00 0x00 0x00 0x01 0x32 0x01 0x32 0x32 s\ni2cset -f -y 17 0x2c 0xff 0x01 s\ni2cset -f -y 19 0x2c 0x00 0x24 0x04 0x14 0x25 0x00 0x02 0xBB 0x20 0x02 0x00 0x00 0x00 0x01 0x32 0x01 0x32 0x32 s\ni2cset -f -y 19 0x2c 0xff 0x01 s\ni2cset -f -y 20 0x2c 0x00 0x24 0x04 0x14 0x25 0x00 0x02 0xBB 0x20 0x02 0x00 0x00 0x00 0x01 0x32 0x01 0x32 0x32 s\ni2cset -f -y 20 0x2c 0xff 0x01 s", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\naddr=$(/usr/bin/mac-util --get)\nif [[ \"$addr\" == \"ff:ff:ff:ff:ff:ff\" ]]\nthen\n  addr=\"02:00:00:00:00:01\"\nfi\nmodprobe g_ether host_addr=02:00:00:00:00:02 dev_addr=$addr\n\nifconfig usb0 up\n\ndhclient -d -pf /var/run/dhclient.usb0.pid usb0 > /dev/null 2>&1 &\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Sync RTC with NTP\nsync_rtc()\n{\n  while [ \"$(ntpq -c rv | grep leap_none)\" == \"\" ]\n  do\n    sleep 10\n  done\n  # if leap code returned normal sync state\n  echo Syncing up RTC time with NTP...\n  test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  return\n}\n\nsync_rtc", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nSLOT_NAME=$1\n\ncase $SLOT_NAME in\n    scm)\n      SLOT_NUM=1\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {scm}\"\n      exit 1\n      ;;\nesac\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump$SLOT_NUM.pid\"\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  echo \"Another auto crashdump for $SLOT_NAME is runnung\"\n  exit 1\nelse\n  touch $PID_FILE\nfi\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\necho $((sys_runtime+630)) > /tmp/cache_store/fru${SLOT_NUM}_crashdump\n\nDUMP_SCRIPT=\"/usr/local/bin/dump.sh\"\nCRASHDUMP_FILE=\"/mnt/data/crashdump_$SLOT_NAME\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_$SLOT_NAME.tar.gz\"\n\necho \"Auto Dump for $SLOT_NAME Started\"\n\n#HEADER LINE for the dump\n$DUMP_SCRIPT \"time\" > \"$CRASHDUMP_FILE\"\n#COREID dump\n$DUMP_SCRIPT \"$SLOT_NAME\" \"coreid\" >> \"$CRASHDUMP_FILE\"\n#MSR dump\n$DUMP_SCRIPT \"$SLOT_NAME\" \"msr\" >> \"$CRASHDUMP_FILE\"\n# Sensors & sensor thresholds\necho \"Sensor history at dump:\" >> \"$CRASHDUMP_FILE\" 2>&1\n$DUMP_SCRIPT \"$SLOT_NAME\" \"sensors\" >> \"$CRASHDUMP_FILE\"\necho \"Sensor threshold at dump:\" >> \"$CRASHDUMP_FILE\" 2>&1\n$DUMP_SCRIPT \"$SLOT_NAME\" \"threshold\" >> \"$CRASHDUMP_FILE\"\n\ntar zcf \"$CRASHDUMP_LOG_ARCHIVE\" -C \"$(dirname \"$CRASHDUMP_FILE\")\" \"$(basename \"$CRASHDUMP_FILE\")\" && \\\nrm -rf \"$CRASHDUMP_FILE\" && \\\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for $SLOT_NAME is generated at $CRASHDUMP_LOG_ARCHIVE\"\n\necho \"Auto Dump for $SLOT_NAME Completed\"\n\nrm $PID_FILE\nexit 0\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIC_UTIL=\"/usr/bin/bic-util\"\nSENSOR_HISTORY=180\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"$0 <slot#> coreid    ==> for CPU CoreID\"\n  echo \"$0 <slot#> msr       ==> for CPU MSR\"\n  echo \"$0 <slot#> sensors   ==> for sensor history\"\n  echo \"$0 <slot#> threshold ==> for sensor threshold\"\n  exit 1\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_coreid ] && $BIC_UTIL \"$1\" --me_file /usr/local/fbpackages/crashdump/crashdump_coreid\nelif [ \"$2\" = \"msr\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_msr ] && $BIC_UTIL \"$1\" --me_file /usr/local/fbpackages/crashdump/crashdump_msr\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util all --threshold \nfi\n\nexit 0\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nexec /usr/local/bin/front-paneld\n", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon...\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 0 1\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\necho -n \"Starting IPMB Rx/Tx Daemon ...\"\nulimit -q 1024000\n\ndeclare -a ipmbd_list\nipmbd_list=(0 4)\nfor ipmb in \"${ipmbd_list[@]}\"\ndo\n    runsv \"/etc/sv/ipmbd_$ipmb\" &> /dev/null &\ndone\n\necho \"Done\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/sensord scm smb psu1 psu2\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup sensor monitoring for Cloudripper... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $(basename $0) [Fan Unit (1..4)]\"\n}\n\n# FCB PWM 1 ~ 4 control Fantray 1 2 3 4\nshow_pwm()\n{\n    pwm=\"$FCMCPLD_SYSFS_DIR/fan$1_pwm\"\n    val=$(head -n 1 \"$pwm\")\n\n    # Convert the percentage to our 1/64th level (0-63) and round.\n    echo \"$(( (val * 1000 / 63 + 5) /10 ))%\"\n}\n\nshow_rpm()\n{\n    front_rpm=\"$FCMCPLD_SYSFS_DIR/fan$((($1 * 2 - 1)))_input\"\n    rear_rpm=\"$FCMCPLD_SYSFS_DIR/fan$((($1 * 2)))_input\"\n    echo \"$(cat \"$front_rpm\"), $(cat \"$rear_rpm\")\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 5 ]; then\n        echo \"Fan $1: not a valid Fan Unit\"\n        usage\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    FAN=\"${fan}\"\n    UNIT=${FAN}\n\n    echo \"Fan $fan RPMs: $(show_rpm \"$UNIT\"), ($(show_pwm \"$UNIT\"))\"\ndone\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho \"Setup fan speed...\"\n\necho \"Setting fan speed to 50%...\"\n/usr/local/bin/set_fan_speed.sh 50\n\necho \"Starting fscd...\"\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $(basename $0) <PERCENT (0..100)> <Fan Unit (1..4)>\"\n}\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# check percent argument be number\ncheck_number=$(echo \"$1\" | grep -E \"^[0-9]+$\")\nif [ \"$check_number\" = '' ]; then\n    echo \"Percent argument can be only integer number\"\n    usage\n    exit 1\nfi\n\n# check percent in range 0-100\nif [ \"$1\" -lt 0 ] || [ \"$1\" -gt 100 ]; then\n    echo \"Percent argument out of range\"\n    usage\n    exit 1\nfi\n\n# FCB PWM 1 ~ 4 control Fantray 1 2 3 4\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -gt 4 ]; then\n        echo \"Fan $2: not a valid Fan Unit\"\n        exit 1\n    fi\n\n    FAN=\"$2\"\n    FAN_UNIT=$((FAN / 1))\nfi\n\n# Convert the percentage to our 1/64th level (0-63) and round.\nstep=$(( ($1 * 630 + 5) / 1000 ))\ncnt=1\n\nfor unit in ${FAN_UNIT}; do\n    pwm=\"$FCMCPLD_SYSFS_DIR/fan${unit}_pwm\"\n    echo \"$step\" > \"${pwm}\"\n    if [ \"$#\" -eq 1 ]; then\n        echo \"Successfully set fan $cnt speed to $1%\"\n        cnt=$((cnt + 1))\n    else\n        echo \"Successfully set fan $2 speed to $1%\"\n    fi\ndone\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n# Do not change this line to openbmc-utils.sh, or it will generate a source loop.\n. /usr/local/bin/i2c-utils.sh\n\nSCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-003e)\nSMBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-003e)\nPWRCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 47-003e)\nFCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 48-003e)\n\nPWR_USRV_SYSFS=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable\"\nPWR_USRV_FORCE_OFF=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_force_off\"\nPWR_TH_RST_SYSFS=\"${SMBCPLD_SYSFS_DIR}/mac_reset_n\"\n\n# CPLD version\nSMB_CPLD_VER=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nSMB_CPLD_SUB_VER=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nPWR_CPLD_VER=$(head -n 1 \"$PWRCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nPWR_CPLD_SUB_VER=$(head -n 1 \"$PWRCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nSCM_CPLD_VER=$(head -n 1 \"$SCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nSCM_CPLD_SUB_VER=$(head -n 1 \"$SCMCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nFCM_CPLD_VER=$(head -n 1 \"$FCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nFCM_CPLD_SUB_VER=$(head -n 1 \"$FCMCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\n\nexport SCMCPLD_SYSFS_DIR\nexport SMBCPLD_SYSFS_DIR\nexport PWRCPLD_SYSFS_DIR\nexport FCMCPLD_SYSFS_DIR\nexport PWR_USRV_SYSFS\nexport PWR_USRV_FORCE_OFF\nexport PWR_TH_RST_SYSFS\nexport SMB_CPLD_VER\nexport SMB_CPLD_SUB_VER\nexport PWR_CPLD_VER\nexport PWR_CPLD_SUB_VER\nexport SCM_CPLD_VER\nexport SCM_CPLD_SUB_VER\nexport FCM_CPLD_VER\nexport FCM_CPLD_SUB_VER\n\nwedge_is_us_on() {\n    local val0 val1\n\n    val0=$(head -n 1 < \"$PWR_USRV_SYSFS\" 2> /dev/null)\n    val1=$(head -n 1 < \"$PWR_USRV_FORCE_OFF\" 2> /dev/null)\n    \n    if [ \"$val0\" == \"0x1\" ] && [ \"$val1\" == \"0x1\" ] ; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n\n    return 0\n}\n\nwedge_board_type_rev() {\n    rev=$(wedge_board_rev)\n    case $rev in\n        0)\n            echo \"Cloudripper_EVT\"\n            ;;\n        1)\n            echo \"Cloudripper_EVT2\"\n            ;;\n        2)\n            echo \"Cloudripper_EVT3\"\n            ;;\n        3)\n            echo \"Cloudripper_DVT\"\n            ;;\n        4)\n            echo \"Cloudripper_PVT\"\n            ;;\n        *)\n            echo \"Cloudripper (Undefine $rev)\"\n            ;;\n    esac\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    echo \"$(( $(head -n 1 \"$SMBCPLD_SYSFS_DIR/board_ver\") ))\"\n}\n\nwedge_power_on_board() {\n    # Cloudripper SCM power is controlled by SCM CPLD\n    return 0\n}\n\nwedge_prepare_cpld_update() {\n    echo \"Stop fscd service.\"\n    systemctl stop fscd.service\n\n    echo \"Disable watchdog.\"\n    /usr/local/bin/wdtcli stop\n\n    echo \"Set fan speed 40%.\"\n    set_fan_speed.sh 40\n}\n", "num_lines": 122}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\nchip_ver=$(aspeed_g6_chip_ver)\n\nusage() {\n    prog=$(basename \"$0\")\n    echo \"Usage: $prog -s <CPLD_TYPE> -f <img_file> <hw|sw>\"\n    echo\n    echo \"CPLD_TYPE: ( FCM | SCM | SMB | PWR )\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 5 ]; then\n    usage\n    exit 1\nfi\n\nCPLD_TYPE=\"$2\"\nUPDATE_IMG=\"$4\"\n\nenable_fcm_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN_R      1\n    gpio_set_value BMC_FCM_SEL_R          0\n\n    gpio_set_value PWR_CPLD_JTAG_EN_N     1\n    gpio_set_value FCM_CPLD_JTAG_EN_N     0\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value SCM_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_EN_R      1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n\n    gpio_set_value DOM_FPGA1_JTAG_EN_N_R  1\n    gpio_set_value DOM_FPGA2_JTAG_EN_N_R  1\n    # set PWR_CPLD_HITLESS to 1 will disable wedge_power.sh reset -s\n    gpio_set_value PWR_CPLD_HITLESS_R     1\n}\n\nenable_smb_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN_R      1\n    gpio_set_value BMC_FCM_SEL_R          1\n    gpio_set_value PWR_CPLD_JTAG_EN_N     1\n    gpio_set_value FCM_CPLD_JTAG_EN_N     1\n\n    gpio_set_value SYS_CPLD_JTAG_EN_N     0\n    gpio_set_value SCM_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_EN_R      1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n\n    gpio_set_value DOM_FPGA1_JTAG_EN_N_R  1\n    gpio_set_value DOM_FPGA2_JTAG_EN_N_R  1\n    # set PWR_CPLD_HITLESS to 1 will disable wedge_power.sh reset -s\n    gpio_set_value PWR_CPLD_HITLESS_R     1\n}\n\nenable_scm_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN_R      1\n    gpio_set_value BMC_FCM_SEL_R          1\n    gpio_set_value PWR_CPLD_JTAG_EN_N     1\n\n    gpio_set_value FCM_CPLD_JTAG_EN_N     1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value SCM_CPLD_JTAG_EN_N     0\n    gpio_set_value BMC_SCM_CPLD_EN_R      0\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n\n    gpio_set_value DOM_FPGA1_JTAG_EN_N_R  1\n    gpio_set_value DOM_FPGA2_JTAG_EN_N_R  1\n    # set PWR_CPLD_HITLESS to 1 will disable wedge_power.sh reset -s\n    gpio_set_value PWR_CPLD_HITLESS_R     1\n}\n\nenable_pdb_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN_R      1\n    gpio_set_value BMC_FCM_SEL_R          1\n    gpio_set_value PWR_CPLD_JTAG_EN_N     0\n\n    gpio_set_value FCM_CPLD_JTAG_EN_N     1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value SCM_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_EN_R      1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n\n    gpio_set_value DOM_FPGA1_JTAG_EN_N_R  1\n    gpio_set_value DOM_FPGA2_JTAG_EN_N_R  1\n    # set PWR_CPLD_HITLESS to 1 will disable wedge_power.sh reset -s\n    gpio_set_value PWR_CPLD_HITLESS_R     1\n}\n\ndisable_jtag_chain(){\n\n    gpio_set_value BMC_JTAG_MUX_IN_R      0\n    gpio_set_value BMC_FCM_SEL_R          1\n\n    gpio_set_value FCM_CPLD_JTAG_EN_N     1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value SCM_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_EN_R      1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n    gpio_set_value PWR_CPLD_JTAG_EN_N     1\n\n    gpio_set_value DOM_FPGA1_JTAG_EN_N_R  1\n    gpio_set_value DOM_FPGA2_JTAG_EN_N_R  1\n    # set PWR_CPLD_HITLESS to 0 will enable wedge_power.sh reset -s\n    gpio_set_value PWR_CPLD_HITLESS_R     0\n}\n\ntrap 'rm -rf /tmp/cpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/cpld_update\n\nif [ -e \"$UPDATE_IMG\" ]; then\n    if [[  $CPLD_TYPE == \"FCM\" ]]; then\n        enable_fcm_jtag_chain\n    elif [[  $CPLD_TYPE == \"SMB\" ]]; then\n        enable_smb_jtag_chain\n    elif [[  $CPLD_TYPE == \"SCM\" ]]; then\n        enable_scm_jtag_chain\n    elif [[  $CPLD_TYPE == \"PWR\" ]]; then\n        enable_pdb_jtag_chain\n   else\n        echo 'argument '\"$CPLD_TYPE\"' is wrong'\n        exit 1\n    fi\nelse\n    echo 'argument '\"$UPDATE_IMG\"' not exist'\n    exit 1\nfi\n\nexpect=0\ncpld_update_sw_mode(){\n        expect=1\n        for n in {1..5}\n        do\n                echo \"Program $CPLD_TYPE $n times\"\n                ispvm -f 1000 dll $DLL_PATH \"${UPDATE_IMG}\"\n                result=$?\n                if [ $result -eq $expect ]; then\n                        break\n                fi\n        done\n}\n\ncpld_update_hw_mode(){\n        expect=0\n        if [ \"$chip_ver\" == \"A3\" ]; then\n                if [[  $CPLD_TYPE == \"PWR\" ]]; then\n                        cpldprog -p \"${UPDATE_IMG}\" -R\n                else\n                        cpldprog -p \"${UPDATE_IMG}\"\n                fi\n        else\n                echo \"Only AST262x A3 chip can support HW Mode !!!\"\n                exit 1\n        fi\n        result=$?\n}\n\nwedge_prepare_cpld_update\n\ncase $5 in\n    hw)\n        cpld_update_hw_mode\n        ;;\n    sw)\n        cpld_update_sw_mode\n        ;;\n    *)\n        # default: hw mode\n        cpld_update_hw_mode\n        ;;\nesac\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    exit 1\nfi\n", "num_lines": 213}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\necho \"SMB_SYSCPLD: $((SMB_CPLD_VER)).$((SMB_CPLD_SUB_VER))\"\necho \"SMB_PWRCPLD: $((PWR_CPLD_VER)).$((PWR_CPLD_SUB_VER))\"\necho \"SCMCPLD: $((SCM_CPLD_VER)).$((SCM_CPLD_SUB_VER))\"\necho \"FCMCPLD: $((FCM_CPLD_VER)).$((FCM_CPLD_SUB_VER))\"\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091,SC2034\n. /usr/local/bin/openbmc-utils.sh\n\nDOMFPGA1_SYSFS_DIR=$(i2c_device_sysfs_abspath 13-0060)\nDOMFPGA2_SYSFS_DIR=$(i2c_device_sysfs_abspath 5-0060)\n\ndump_fpga_version() {\n    local fpga_dir=$1\n    local fpga_name=$2\n\n    fpga_ver=$(head -n 1 \"$fpga_dir/fpga_ver\" 2> /dev/null)\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        return\n    fi\n\n    fpga_sub_ver=$(head -n 1 \"${fpga_dir}/fpga_sub_ver\" 2> /dev/null)\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        return\n    fi\n\n    echo \"${fpga_name}: $((fpga_ver)).$((fpga_sub_ver))\"\n}\n\ndump_fpga_version \"$DOMFPGA1_SYSFS_DIR\" DOMFPGA1\ndump_fpga_version \"$DOMFPGA2_SYSFS_DIR\" DOMFPGA2\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:    85\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nwedge_power_on_board\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 49}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nSMB_DIR=$SMBCPLD_SYSFS_DIR\nSCM_CMD=$SMB_DIR\"/scm_present_int_status\"\nFAN_CMD=$FCMCPLD_SYSFS_DIR\nDEBUG_CARD_PRSNT_GPIO=\"/tmp/gpionames/DEBUG_PRESENT_N/value\"\n\nfunction usage\n{\n  program=$(basename \"$0\")\n  echo \"Usage:\"\n  echo \"     $program \"\n  echo \"     $program <TYPE>\"\n  echo \"     <TYPE>: scm/fan/psu/debug_card\"\n}\n\n# Will return <key> : <val>\n# eg - scm : 1\nfunction get_presence\n{\n  local file=$1 key=$2\n  val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n  if [ \"$val\" = \"0\" ]; then\n      val=1\n  else\n      val=0\n  fi\n  echo \"$key : $val\"\n}\n\n# SCM\nfunction get_scm_presence\n{\n  key=\"scm\"\n  get_presence \"$SCM_CMD\" \"$key\"\n}\n\n# FANs\nfunction get_fan_presence\n{\n  local num=1\n  while [ $num -le 4 ]; do\n      key=\"fan${num}\"\n      file=\"$FAN_CMD/fan${num}_present\"\n      get_presence \"$file\" \"$key\"\n      (( num++ ))\n  done\n}\n\n# Power supplies\nfunction get_psu_presence\n{\n  for i in {1..2}; do\n      key=\"psu${i}\"\n      file=\"$SMB_DIR/psu_present_${i}_N_int_status\"\n      get_presence \"$file\" \"$key\"\n  done\n}\n\n# Debug card\nfunction get_debug_card_presence\n{\n  key=\"debug_card\"\n  val=$(head -n1 $DEBUG_CARD_PRSNT_GPIO | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n  if [ \"$val\" = \"0\" ]; then\n      val=0\n  else\n      val=1\n  fi\n  echo $key \":\" $val\n}\n\n# get all info\nif [[ $1 = \"\" ]]; then\n  echo \"CARDS\"\n  get_scm_presence\n\n  echo \"FANS\"\n  get_fan_presence\n\n  echo \"POWER SUPPLIES\"\n  get_psu_presence\n\n  echo \"DEBUG CARD\"\n  get_debug_card_presence\n\n  exit 0\nelse\n  if [[ $1 = \"scm\" ]]; then\n    get_scm_presence\n  elif [[ $1 = \"fan\" ]]; then\n    get_fan_presence\n  elif [[ $1 = \"psu\" ]]; then\n    get_psu_presence\n  elif [[ $1 = \"debug_card\" ]]; then\n    get_debug_card_presence\n  else\n    usage\n  fi\n  exit 0\nfi\n", "num_lines": 123}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n\tprogram=$(basename \"$0\")\n\techo \"Usage:\"\n\techo \"  $program <led>\"\n\techo \"  <led>: sys/fan/psu/scm\"\n\techo \"  $program without option to display all leds\"\n\techo\n\techo \"Output:\"\n\techo \"  <led>: color\"\n\texit 1\n}\n\nread_led_color_value() {\n\tcase $1 in\n\t\"sys\" | \"fan\" | \"psu\" | \"scm\")\n\t\tcat \"/sys/class/leds/$1/multi_intensity\"\n\t;;\n\t*)\n\t\tusage\n\t;;\n\tesac\n}\n\n# color: red-blue-green (value: 0-255)\n#   red(255 0 0)\n#   blue(0 255 0)\n#   green(0 0 255)\n#   amber(255 0 45)\nprint_led_color() {\n\tcolor=\"\"\n\tcase $(read_led_color_value \"$1\") in\n\t\"255 0 0\")\n\t\tcolor=\"red\"\n\t\t;;\n\t\"0 255 0\")\n\t\tcolor=\"blue\"\n\t\t;;\n\t\"0 0 255\")\n\t\tcolor=\"green\"\n\t\t;;\n\t\"255 0 45\")\n\t\tcolor=\"amber\"\n\t\t;;\n\t\"0 0 0\")\n\t\tcolor=\"off\"\n\t\t;;\n\t*)\n\t\tcolor=\"unknown\"\n\t\t;;\n\tesac\n\techo \"$1: $color\"\n}\n\nif [ $# -ge 1 ]; then\n\tled=$1\n\tcase $1 in\n\t\t\"?\" | \"help\")\n\t\t\tusage\n\t\t\t;;\n\t\t\"sys\" | \"fan\" | \"psu\" | \"scm\")\n\t\t\tprint_led_color \"$led\"\n\t\t\texit 0\n\t\t\t;;\n\t\t*)\n\t\t\tusage\n\t\t\t;;\n\tesac\nfi\n\nleds=(\"sys\" \"fan\" \"psu\" \"scm\")\nfor led in ${leds[*]}\ndo\n\tprint_led_color \"$led\"\ndone\n", "num_lines": 95}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     60 S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# Export GPIO\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB1 NP_POWER_STABLE_3V3_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF3 SMB_CPLD_HITLESS_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF6 BMC_EMMC_CD_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF7 BMC_EMMC_WP_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG2 CPLD_INT_BMC_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG4 CPLD_RESERVED_2_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG6 BMC_DOM_FPGA2_RST_L_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG7 FCM_CARD_PRESENT\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH0 GPIO_H0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH1 GPIO_H1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH2 GPIO_H2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH3 GPIO_H3\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH4 GPIO_H4\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH5 GPIO_H5\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOM1 BMC_UART_SEL_5\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOM3 SCM_CPLD_HITLESS_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO0 PWR_CPLD_JTAG_EN_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO1 BMC_JTAG_MUX_IN_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO2 FCM_CPLD_JTAG_EN_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO3 SYS_CPLD_JTAG_EN_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO4 DOM_FPGA1_JTAG_EN_N_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO5 GPIO_H6\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO6 SCM_CPLD_JTAG_EN_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOO7 GPIO_H7\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOP0 BMC_UART_SEL_2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOP6 BMC_CPLD_SPARE3_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ0 FCM_CPLD_HITLESS_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ2 PWR_CPLD_HITLESS_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ3 BMC_IN_P1220_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ4 BMC_FCM_SEL_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ6 BMC_CPLD_SPARE4_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ7 SYS_CPLD_RST_L_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR0 BMC_CPLD_SPARE2_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR1 DOM_FPGA2_JTAG_EN_N_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR2 BMC_CPLD_SPARE1_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR3 DEBUG_PRESENT_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR4 BMC_SCM_CPLD_EN_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR5 BMC_CPLD_TPM_RST_L_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR6 BMC_DOM_FPGA1_RST_L_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOV1 CPLD_RESERVED_3_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOV2 CPLD_RESERVED_4_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOV3 BMC_P1220_SYS_OK\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOV4 BMC_POWER_OK\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW0 SCM_LPC_AD_0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW1 SCM_LPC_AD_1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW2 SCM_LPC_AD_2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW3 SCM_LPC_AD_3\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW4 SCM_LPC_CLK\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW5 SCM_LPC_FRAME_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW6 SCM_LPC_SERIRQ_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOW7 BMC_LPCRST_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOX6 BMC_FPGA_JTAG_EN\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY2 CPU_CATERR_MSMI_R\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY3 BMC_EMMC_RST_N\n\n# Set GPIO direction\ngpio_set_direction NP_POWER_STABLE_3V3_R    \"in\"\ngpio_set_direction SMB_CPLD_HITLESS_R       \"out\"\ngpio_set_direction BMC_EMMC_CD_N            \"in\"\ngpio_set_direction BMC_EMMC_WP_N            \"in\"\ngpio_set_direction CPLD_INT_BMC_R           \"in\"\ngpio_set_direction CPLD_RESERVED_2_R        \"in\"\ngpio_set_direction BMC_DOM_FPGA2_RST_L_R    \"out\"\ngpio_set_direction FCM_CARD_PRESENT         \"in\"\ngpio_set_direction GPIO_H0                  \"in\"\ngpio_set_direction GPIO_H1                  \"in\"\ngpio_set_direction GPIO_H2                  \"in\"\ngpio_set_direction GPIO_H3                  \"in\"\ngpio_set_direction GPIO_H4                  \"in\"\ngpio_set_direction GPIO_H5                  \"in\"\ngpio_set_direction BMC_UART_SEL_5           \"in\"\ngpio_set_direction SCM_CPLD_HITLESS_R       \"out\"\ngpio_set_direction PWR_CPLD_JTAG_EN_N       \"out\"\ngpio_set_direction BMC_JTAG_MUX_IN_R        \"out\"\ngpio_set_direction FCM_CPLD_JTAG_EN_N       \"out\"\ngpio_set_direction SYS_CPLD_JTAG_EN_N       \"out\"\ngpio_set_direction DOM_FPGA1_JTAG_EN_N_R    \"out\"\ngpio_set_direction GPIO_H6                  \"in\"\ngpio_set_direction SCM_CPLD_JTAG_EN_N       \"out\"\ngpio_set_direction GPIO_H7                  \"in\"\ngpio_set_direction BMC_UART_SEL_2           \"in\"\ngpio_set_direction BMC_CPLD_SPARE3_R        \"in\"\ngpio_set_direction FCM_CPLD_HITLESS_R       \"out\"\ngpio_set_direction PWR_CPLD_HITLESS_R       \"out\"\ngpio_set_direction BMC_IN_P1220_R           \"in\"\ngpio_set_direction BMC_FCM_SEL_R            \"out\"\ngpio_set_direction BMC_CPLD_SPARE4_R        \"in\"\ngpio_set_direction SYS_CPLD_RST_L_R         \"out\"\ngpio_set_direction BMC_CPLD_SPARE2_R        \"in\"\ngpio_set_direction DOM_FPGA2_JTAG_EN_N_R    \"out\"\ngpio_set_direction BMC_CPLD_SPARE1_R        \"out\"\ngpio_set_direction DEBUG_PRESENT_N          \"in\"\ngpio_set_direction BMC_SCM_CPLD_EN_R        \"out\"\ngpio_set_direction BMC_CPLD_TPM_RST_L_R     \"out\"\ngpio_set_direction BMC_DOM_FPGA1_RST_L_R    \"out\"\ngpio_set_direction CPLD_RESERVED_3_R        \"in\"\ngpio_set_direction CPLD_RESERVED_4_R        \"in\"\ngpio_set_direction BMC_P1220_SYS_OK         \"in\"\ngpio_set_direction BMC_POWER_OK             \"in\"\ngpio_set_direction SCM_LPC_AD_0             \"in\"\ngpio_set_direction SCM_LPC_AD_1             \"in\"\ngpio_set_direction SCM_LPC_AD_2             \"in\"\ngpio_set_direction SCM_LPC_AD_3             \"in\"\ngpio_set_direction SCM_LPC_CLK              \"in\"\ngpio_set_direction SCM_LPC_FRAME_N          \"in\"\ngpio_set_direction SCM_LPC_SERIRQ_N         \"in\"\ngpio_set_direction BMC_LPCRST_N             \"in\"\ngpio_set_direction CPU_CATERR_MSMI_R        \"in\"\ngpio_set_direction BMC_EMMC_RST_N           \"out\"\ngpio_set_direction BMC_FPGA_JTAG_EN         \"out\"\n\n# Set GPIO default value\n# Default set to 1. RST signal is active low, set it to high for normal operation\ngpio_set_value BMC_DOM_FPGA2_RST_L_R    1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value PWR_CPLD_JTAG_EN_N       1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value BMC_FPGA_JTAG_EN         1\ngpio_set_value BMC_JTAG_MUX_IN_R        0\n# Default set to 0. Use header for CPLD FW burn in as default setting\ngpio_set_value FCM_CPLD_JTAG_EN_N       1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value SYS_CPLD_JTAG_EN_N       1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value DOM_FPGA1_JTAG_EN_N_R    1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value SCM_CPLD_JTAG_EN_N       1\n# Default set to 1. Use header for SCM CPLD FW burn in as default setting\ngpio_set_value BMC_FCM_SEL_R            0\n# Default set to 1. RST signal is active low, set it to high for normal operation\ngpio_set_value SYS_CPLD_RST_L_R         1\n# Default set to 1. Enable signal active low, set it to high for normal operation(No JTAG burn in)\ngpio_set_value DOM_FPGA2_JTAG_EN_N_R    1\n# Default set to 1. Use header for SCM CPLD FW burn in as default setting\ngpio_set_value BMC_SCM_CPLD_EN_R        1\n# Default set to 1. RST signal is active low, set it to high for normal operation\ngpio_set_value BMC_DOM_FPGA1_RST_L_R    1\n# Default set to 0. 0 to enable wedge_power.sh reset -s, 1 to disable wedge_power.sh reset -s\ngpio_set_value PWR_CPLD_HITLESS_R       0\n# set BMC_EMMC_RST_N High to prevent EMMC disable\ngpio_set_value BMC_EMMC_RST_N 1\n", "num_lines": 175}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ncmd_bic_ver=\"bic-util scm 0xe2 0x0b 0x15 0xa0 0x00 0x02\"\nCOUNTER=0\nMAX_RETRY=10\nrex='^[0-9]+$'\n\necho \"Initializing Bridge-IC I2C Frequency...\"\nwhile [ $COUNTER -lt $MAX_RETRY ]; do\n    readarray -td ' ' bic_data <<<\"$($cmd_bic_ver)\"\n    if [[ ${bic_data[4]} =~ $rex ]] ; then\n        break\n    fi\n    sleep 3\n    ((COUNTER+=1))\ndone\n\nif [ \"$COUNTER\" -eq $MAX_RETRY ];then\n    echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\nfi\n\nbic_major=$(( 10#${bic_data[3]} ))\nbic_minor=$(( 10#${bic_data[4]} ))\nbic_ver=\"$bic_major.${bic_data[4]}\"\n\necho Bridge-IC version is v\"$bic_ver\".\n\nif [ \"$bic_major\" -ge 1 ];then\n    if [ \"$bic_minor\" -ge 11 ];then\n        ret=$(bic-util scm 0xe0 0x2a 0x15 0xa0 0x00 0x01)\n        IANA=\"15 A0 00\"\n        if [ -z \"${ret##*$IANA*}\" ];then\n            echo Bridge-IC is initialized SCL to 1Mhz.\n        else\n            echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\n        fi\n    fi\nfi\n\nexit 0\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Make the backup BIOS flash connect to COMe instead of BMC\n# echo 0 > \"${SCMCPLD_SYSFS_DIR}/com_spi_oe_n\"\n# echo 0 > \"${SCMCPLD_SYSFS_DIR}/com_spi_sel\"\n\n# Setup management port LED\n/usr/local/bin/setup_mgmt.sh led &\n\n# Init server_por_cfg\nif [ ! -f \"/mnt/data/kv_store/server_por_cfg\" ]; then\n    /usr/bin/kv set server_por_cfg on persistent\nfi\n\n# Force COMe's UART connect to BMC UART-5 and FB USB debug\n# UART connect to BMC UART-2\necho 0x3 > \"$SMBCPLD_SYSFS_DIR/uart_selection\"\n\n# export_gpio_pin for PCA9555 4-0027\ngpiocli export -c 4-0027 -o 8 --shadow ISO_DEBUG_RST_BTN_N\ngpiocli export -c 4-0027 -o 9 --shadow ISO_PWR_BTN_N\ngpiocli export -c 4-0027 -o 10 --shadow PWRGD_PCH_PWROK\ngpiocli export -c 4-0027 -o 11 --shadow ISO_CB_RESET_N\ngpiocli export -c 4-0027 -o 12 --shadow COM_PWROK\ngpiocli export -c 4-0027 -o 13 --shadow CPU_CATERR_MSMI_EXT\ngpiocli export -c 4-0027 -o 14 --shadow ISO_COM_SUS_S3_N\ngpiocli export -c 4-0027 -o 15 --shadow DEBUG_UART_SELECT\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# Bus 0: Create i2c slave backend for ipmbd_0(BIC)\ni2c_mslave_add 0 0x10\n\n# Bus 4: Create i2c slave backend for ipmbd_4(Debug Card)\ni2c_mslave_add 4 0x10\n\n# Bus 16: i2c bus 1 mux, channel 0\ni2c_device_add 16 0x4d ir35215              # ir35215\n# Bus 17: i2c bus 1 mux, channel 1\ni2c_device_add 17 0x40 xdpe132g5c           # xdpe132g5c\n# Bus 18: i2c bus 1 mux, channel 2\ni2c_device_add 18 0x3a powr1220             # powr1220\n# Bus 19: i2c bus 1 mux, channel 3\ni2c_device_add 19 0x68 xdpe12284            # xdpe12284\n# Bus 20: i2c bus 1 mux, channel 4\ni2c_device_add 20 0x0e pxe1211              # pxe1211\n# Bus 21: i2c bus 1 mux, channel 5\ni2c_device_add 21 0x47 ir35215              # ir35215\n# Bus 22: i2c bus 1 mux, channel 6\ni2c_device_add 22 0x60 xdpe12284            # xdpe12284\n# Bus 23: i2c bus 1 mux, channel 7\n# None\n\n# Bus 2\ni2c_device_add 2 0x3e scmcpld               # SCM CPLD\n\n# Bus 24: i2c bus 2 mux, channel 0\ni2c_device_add 24 0x10 adm1278              # adm1278\n# Bus 26: i2c bus 2 mux, channel 2\n# None\n# Bus 27: i2c bus 2 mux, channel 3\ni2c_device_add 27 0x52 24c64                # SCM EEPROM\n# Bus 28: i2c bus 2 mux, channel 4\ni2c_device_add 28 0x50 24c02                # SCM BCM546161S EEPROM\n# Bus 29: i2c bus 2 mux, channel 5\n# None\n# Bus 30: i2c bus 2 mux, channel 6\n# None\n# Bus 31: i2c bus 2 mux, channel 7\n# i2c_device_add 31 0x50 si53108            # si53108 do not enable this\n\n# Bus 3\n# Bus 35: i2c bus 3 mux, channel 3\ni2c_device_add 35 0x4c tmp421               # tmp421\n# Bus 36: i2c bus 3 mux, channel 4\ni2c_device_add 36 0x4d tmp421               # tmp421\n# Bus 38: i2c bus 3 mux, channel 6\ni2c_device_add 38 0x2a net_asic             # GB switch i2c driver\n\n# Bus 4\ni2c_device_add 4 0x27 pca9555               # PCA9555 GPIO expander for debug card\n\n# Bus 5\ni2c_device_add 5 0x60 domfpga               # DOM FPGA 2\n\n# Bus 6\ni2c_device_add 6 0x51 24c64                 # SMB EEPROM\ni2c_device_add 6 0x21 pca9534               # pca9534 GPIO expander\n\n# Bus 7\n# i2c_device_add 7 0x2e tpm_tis_i2c         # i2c tpm, driver binding in device tree\n\n# Bus 8\ni2c_device_add 8 0x51 24c64                 # i2c EEPROM\n# Bus 40: i2c bus 8 mux, channel 0\n# i2c_device_add 40 0xa0/0xb0 24c02/24c64   # PSU1 EEPROM\ni2c_device_add 40 0x58 psu_driver           # PSU1 MCU\n# Bus 41: i2c bus 8 mux, channel 1\n# i2c_device_add 41 0xa0/0xb0 24c02/24c64   # PSU1 EEPROM\ni2c_device_add 41 0x58 psu_driver           # PSU2 MCU\n# Bus 42: i2c bus 8 mux, channel 2\ni2c_device_add 42 0x50 24c02                # BMC BCM54616S EEPROM\n# Bus 43: i2c bus 8 mux, channel 3\ni2c_device_add 43 0x50 24c02                # BCM5389 BCM54616S EEPROM\n# Bus 44: i2c bus 8 mux, channel 4\n# None\n# Bus 45: i2c bus 8 mux, channel 5\n# pwr cpld upgrade interface\n# Bus 46: i2c bus 8 mux, channel 6\n# None\n# Bus 47: i2c bus 8 mux, channel 7\ni2c_device_add 47 0x3e smb_pwrcpld          # PWR CPLD\n\n# Bus 9\n# i2c_device_add 9 0x74 si5391b             # si5391b do not enable this\n# i2c_device_add 9 TBD usb_hub              # usb_hub do not enable this\n\n# Bus 10\n# i2c_device_add 10 0x0d runbmc_fpga        # PFR FPGA\n\n# Bus 12\ni2c_device_add 12 0x3e smb_syscpld          # SMB CPLD\n\n# Bus 13\ni2c_device_add 13 0x60 domfpga              # DOM FPGA 1\n\n# Bus 14\n# disabled, multiple function pin, used as MDIO\n\n# Bus 48: i2c bus 15 mux, channel 0\ni2c_device_add 48 0x3e fcbcpld              # FCM CPLD\n# Bus 49: i2c bus 15 mux, channel 1\ni2c_device_add 49 0x51 24c64                # FCM EEPROM\n# Bus 51: i2c bus 15 mux, channel 3\ni2c_device_add 51 0x10 adm1278              # FCM Hotswap adm1278\n# Bus 52: i2c bus 15 mux, channel 4\ni2c_device_add 52 0x52 24c64                # FAN4 EEPROM\n# Bus 53: i2c bus 15 mux, channel 5\ni2c_device_add 53 0x52 24c64                # FAN3 EEPROM\n# Bus 54: i2c bus 15 mux, channel 6\ni2c_device_add 54 0x52 24c64                # FAN2 EEPROM\n# Bus 55: i2c bus 15 mux, channel 7\ni2c_device_add 55 0x52 24c64                # FAN1 EEPROM\n\n# cloudripper will mix the NXP LM75 and TI TMP1075 sensor chips\n# LM75 not support device id read, but TI TMP1075 support\n# BMC can access TMP1075 0x0F address to get TMP1075 device id\nTMP1075_ID=0x75\nfixup_lm75_tmp1075_devices() {\n    # Bus 25: i2c bus 2 mux, channel 1\n    DEV_ID=$(i2cget -y -f 25 0x4c 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 25 0x4c tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 25 0x4c lm75                 # i2c lm75\n    fi\n\n    DEV_ID=$(i2cget -y -f 25 0x4d 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 25 0x4d tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 25 0x4d lm75                 # i2c lm75\n    fi\n\n    # Bus 3\n    DEV_ID=$(i2cget -y -f 3 0x4a 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 3 0x4a tmp1075               # i2c tmp1075\n    else\n        i2c_device_add 3 0x4a lm75                  # i2c lm75\n    fi\n\n    # Bus 32: i2c bus 3 mux, channel 0\n    DEV_ID=$(i2cget -y -f 32 0x48 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 32 0x48 tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 32 0x48 lm75                 # i2c lm75\n    fi\n    # Bus 33: i2c bus 3 mux, channel 1\n    DEV_ID=$(i2cget -y -f 33 0x49 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 33 0x49 tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 33 0x49 lm75                 # i2c lm75\n    fi\n    # Bus 34: i2c bus 3 mux, channel 2\n    DEV_ID=$(i2cget -y -f 34 0x4b 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 34 0x4b tmp1075              # tmp1075\n    else\n        i2c_device_add 34 0x4b lm75                 # i2c lm75\n    fi\n\n    # Bus 37: i2c bus 3 mux, channel 5\n    DEV_ID=$(i2cget -y -f 37 0x4e 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 37 0x4e tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 37 0x4e lm75                 # i2c lm75\n    fi\n\n    # Bus 39: i2c bus 3 mux, channel 7\n    DEV_ID=$(i2cget -y -f 39 0x4f 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 39 0x4f tmp1075              # i2c tmp1075\n    else\n        i2c_device_add 39 0x4f lm75                 # i2c lm75\n    fi\n\n    # Bus 8\n    DEV_ID=$(i2cget -y -f 8 0x4a 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 8 0x4a tmp1075               # i2c tmp1075\n    else\n        i2c_device_add 8 0x4a lm75                  # i2c lm75\n    fi\n\n    # Bus 50: i2c bus 15 mux, channel 2\n    DEV_ID=$(i2cget -y -f 50 0x48 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 50 0x48 tmp1075              # FCM tmp1075\n    else\n        i2c_device_add 50 0x48 lm75                 # FCM lm75\n    fi\n\n    DEV_ID=$(i2cget -y -f 50 0x49 0x0f)\n    if [ \"$DEV_ID\" = \"$TMP1075_ID\" ]; then\n        i2c_device_add 50 0x49 tmp1075              # FCM tmp1075\n    else\n        i2c_device_add 50 0x49 lm75                 # FCM lm75\n    fi\n}\n\nfixup_lm75_tmp1075_devices", "num_lines": 227}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nCOM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok\")\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"     $program led\"\n}\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# When COM-e power is not ready, it doesn't work to set PHY register.\n# Therefore, waiting for COM-e power ready, then start to set PHY register.\nwhile [ \"$COM_E_PWRGD\" = \"0x0\" ];\ndo\n    COM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok\")\n    sleep 5\ndone\n\nif [ \"$1\" = \"led\" ]; then\n    echo \"Wait a few seconds to setup management port LED...\"\n    # refer to BCM54616S Section 5, register 1C access\n    # Register 1C (Shadow 00010): Spare Control 1\n    # Bit0: 1: Enable link LED mode.\n    mdio-util -m 2 -p 0xe -w 0x1c -d 0x8801\n    # Register 1C (Shadow 01110): LED Selector 2\n    # Bit7~4: LED4 Selector, b0011: Activity LED \n    # Bit3~0: LED4 Selector, b0101: Slave\n    mdio-util -m 2 -p 0xe -w 0x1c -d 0xb435\n    echo \"Done!\"\nelse\n    usage\n    exit 1\nfi\n", "num_lines": 62}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ndev=$1\ncolor=$2\n\nusage(){\n  program=$(basename \"$0\")\n  echo \"Usage:\"\n  echo \"     $program <dev> <color>\"\n  echo \"\"\n  echo \"     <dev>: sys/fan/psu/scm\"\n  echo \"     <color>: off/red/blue/green/amber\"\n}\n\nled=\"\"\ncase $dev in\n  \"sys\" | \"fan\" | \"psu\" | \"scm\")\n    led=\"/sys/class/leds/$dev\"\n  ;;\n  *)\n    usage\n    exit 1\n  ;;\nesac\n\n# color: red/blue/green value: 0-255\n# brightness: 0-255\nbrightness=\"255\"\ncase $color in\n  \"red\")\n    color=\"255 0 0\"\n  ;;\n  \"blue\")\n    color=\"0 255 0\"\n  ;;\n  \"green\")\n    color=\"0 0 255\"\n  ;;\n  \"amber\")\n    color=\"255 0 45\"\n  ;;\n  \"off\")\n    color=\"0 0 0\"\n    brightness=0\n  ;;\n  *)\n    usage\n    exit 1\n  ;;\nesac\n\necho \"$color\" > \"$led/multi_intensity\"\necho $brightness > \"$led/brightness\"\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/i2c-utils.sh\n\nusage()\n{\n  echo \"usage :\"\n  echo \"   $0 <voltage in mv>\"\n  echo \"   eg. $0 850\"\n  echo \" limit : max 930 mV\"\n}\n\nfind_hwmon_path() {\n  cd \"$1\"/hwmon/hwmon* 2> /dev/null || return 1\n  pwd\n}\n\nif [ $# -ne 1 ]; then\n  usage\n  exit 255\nfi\n\nif [ $(($1)) -gt 931 ]; then\n  usage\n  exit 255\nfi\n\nvddcore_i2c_path=$(i2c_device_sysfs_abspath 17-0040)\nvddcore_hwmon_path=$(find_hwmon_path \"$vddcore_i2c_path\")\nif [ -z \"$vddcore_hwmon_path\" ]; then\n  echo \"device is not found\"\n  exit 1\nfi\nvddcore_sysfs_node=\"$vddcore_hwmon_path/vout0_value\"\n\nif echo \"$1\" > \"$vddcore_sysfs_node\"; then\n  echo \"$1\"\n  exit 0\nelse\n  echo \"setting error\"\n  exit 254\nfi\n", "num_lines": 62}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091,SC2009\n. /usr/local/bin/openbmc-utils.sh\n\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS4\n\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n        awk '{print $1}')\n  if [ \"$pid\" ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -e $FILE ]; then\n    read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 \"$TTY\"\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\necho 0x3 > \"$SMBCPLD_SYSFS_DIR/uart_selection\"\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\n#shellcheck disable=SC2039\n#shellcheck disable=SC2086\n. /usr/local/bin/openbmc-utils.sh\n\nret=0\ntrap cleanup_spi INT TERM QUIT EXIT\n\nPIDFILE=\"/var/run/spi_util.pid\"\ncheck_duplicate_process()\n{\n    exec 2>$PIDFILE\n    flock -n 2 || (echo \"Another process is running\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 1\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n\nremove_pid_file()\n{\n    if [ -f $PIDFILE ]; then\n        rm $PIDFILE\n    fi\n}\n\nSPI1_MTD_INDEX=7\nSPI1_DRIVER=\"1e630000.spi\"\nASPEED_SMC_PATH=\"/sys/bus/platform/drivers/aspeed-smc/\"\n\nread_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Reading ${dev} to $file...\"\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -r \"$file\"\n}\n\nwrite_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Writing $file to ${dev}...\"\n\n    tmpfile=\"$file\"_ext\n    flashsize=$(flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX | grep -i kB | xargs echo | cut -d '(' -f 2 | cut -d ' ' -f 0)\n    targetsize=$((flashsize * 1024))\n\n    cp \"$file\" \"$tmpfile\"\n\n    #extend the temp-file\n    filesize=$(stat -c%s $tmpfile)\n    add_size=$((targetsize - filesize))\n    dd if=/dev/zero bs=\"$add_size\" count=1 | tr \"\\000\" \"\\377\" >> \"$tmpfile\"\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -w \"$tmpfile\"\n}\n\nerase_spi1_dev(){\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -E\n}\n\nmtd_driver_unbind_spi1() {\n    [ -e ${ASPEED_SMC_PATH}${SPI1_DRIVER} ] && echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}unbind\n}\n\nmtd_driver_rebind_spi1() {\n    # Sometime kernel may complain \"vmap allocation for size 268439552 failed: use vmalloc=<size> to increase size\"\n    # until now the root cause is not clear, still need more investigation\n    mtd_driver_unbind_spi1\n    echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}bind\n}\n\nconfig_spi1_pin_and_path(){\n    dev=$1\n    case ${dev} in\n        \"BIOS\")\n            echo \"[Setup] BIOS\"\n            echo 0x01 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n        ;;\n        \"GB_PCIE_FLASH\")\n            echo \"[Setup] GB_PCIE_FLASH\"\n            echo 0x03 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n        ;;\n        \"DOM_FPGA_FLASH1\")\n            echo \"[Setup] DOM_FPGA_FLASH1\"\n            echo 0x04 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n        ;;\n        \"DOM_FPGA_FLASH2\")\n            echo \"[Setup] DOM_FPGA_FLASH2\"\n            echo 0x05 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n        ;;\n        *)\n            echo \"Please enter {BIOS, GB_PCIE_FLASH, DOM_FPGA_FLASH1, DOM_FPGA_FLASH2}\"\n            exit 1\n        ;;\n    esac\n    echo \"Config SPI1 Done.\"\n}\n\noperate_spi1_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    mtd_driver_rebind_spi1\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n                read_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                write_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi1_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n    mtd_driver_unbind_spi1\n}\n\nread_spi2_dev(){\n    dev=$1\n    file=$2\n    file_temp=\"$file\"_temp\n    echo -n \"Reading ${dev} to $file ... \"\n    # Sometimes the read back BCM5389_EE image one bit fail.\n    # still not found the real root cause\n    for n in 1 2 3 4 5\n    do\n        echo \"Reading $file $n times\"\n        dd if=/sys/bus/spi/devices/spi2.1/eeprom of=\"$file\"\n        sleep 1\n        dd if=/sys/bus/spi/devices/spi2.1/eeprom of=\"$file_temp\"\n        if ! diff $file $file_temp >/dev/null; then\n            # read-back file differ\n            rm -rf \"$file\"*\n        else\n            # read-back file same\n            rm -rf $file_temp;\n            return;\n        fi\n    done\n    logger -p user.err \"Unable to read the correct $file after 5 retries\"\n    exit 1\n}\n\nwrite_spi2_dev(){\n    dev=$1\n    file=$2\n    echo -n \"Writing $file to ${dev} ... \"\n    dd if=\"$file\" of=/sys/bus/spi/devices/spi2.1/eeprom\n    echo \"Done\"\n}\n\nerase_spi2_dev(){\n    echo -n \"Erasing ${dev} ... \"\n    echo 1 > /sys/bus/spi/devices/spi2.1/erase\n    echo \"Done\"\n}\n\nconfig_spi2_pin_and_path(){\n    dev=$1\n\n    case ${dev} in\n        \"BCM5389_EE\")\n            echo \"[Setup] BCM5389_EE\"\n            echo 0x02 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n        ;;\n        *)\n            echo \"Please enter {BCM5389_EE}\"\n            exit 1\n        ;;\n    esac\n    echo \"Config SPI2 Done.\"\n}\n\noperate_spi2_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n            read_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n            write_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n            erase_spi2_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n}\n\ncleanup_spi(){\n    if [ $ret -eq 1 ]; then\n        exit 1\n    fi\n    echo 0 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n\n    rm -rf /tmp/*_spi*_tmp\n    remove_pid_file\n}\n\nui(){\n    . /usr/local/bin/openbmc-utils.sh\n    op=$1\n    spi=$2\n    ## Open the path to device ##\n    case ${spi} in\n        \"spi1\")\n            dev=$3\n            file=$4\n            config_spi1_pin_and_path \"$dev\"\n            operate_spi1_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        \"spi2\")\n            dev=$3\n            file=$4\n            config_spi2_pin_and_path \"$dev\"\n            operate_spi2_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        *)\n            echo \"No such SPI bus.\"\n            return 1\n        ;;\n    esac\n}\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"  $program <op> <spi1> <spi device> <file>\"\n    echo \"    <op>          : read, write, erase\"\n    echo \"    <spi1 device> : BIOS, GB_PCIE_FLASH, DOM_FPGA_FLASH1, DOM_FPGA_FLASH2\"\n    echo \"    <spi2 device> : BCM5389_EE\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program write spi1 BIOS bios.bin\"\n    echo \"\"\n}\n\ncheck_parameter(){\n    program=$(basename \"$0\")\n    op=$1\n    spi=$2\n\n    # check operations.\n    case ${op} in\n        \"read\" | \"write\" | \"erase\")\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n\n    case ${spi} in\n        # check spi 1 device and parameters.\n        \"spi1\")\n            dev=$3\n            file=$4\n            case ${dev} in\n                \"BIOS\"|\"GB_PCIE_FLASH\"|\"DOM_FPGA_FLASH1\"|\"DOM_FPGA_FLASH2\")\n                    case ${op} in\n                        \"read\" | \"write\")\n                            if [ $# -ne 4 ]; then\n                                return 1\n                            fi\n                            ;;\n                    \"erase\")\n                            if [ $# -ne 3 ]; then\n                                return 1\n                            fi\n                            ;;\n                    esac\n                    ;;\n                *)\n                    return 1\n                    ;;\n            esac\n            ;;\n        # check spi 2 device and parameters.\n        \"spi2\")\n            dev=$3\n            file=$4\n            case ${dev} in\n                \"BCM5389_EE\")\n                    case ${op} in\n                        \"read\" | \"write\")\n                            if [ $# -ne 4 ]; then\n                                return 1\n                            fi\n                            ;;\n                        \"erase\")\n                            if [ $# -ne 3 ]; then\n                                return 1\n                            fi\n                            ;;\n                    esac\n                    ;;\n                *)\n                    return 1\n                    ;;\n            esac\n            ;;\n        # check device and parameters fail.\n        *)\n            return 1\n            ;;\n    esac\n\n    return 0\n}\n\n\n# check_duplicate_process - to check if there is the duplicate spi util process, will return fail and stop execute command.\ncheck_duplicate_process\n\n# check_parameter - to check command parameters\ncheck_parameter \"$@\"\n\nis_par_ok=$?\n\nif [ $is_par_ok -eq 0 ]; then\n    ui \"$@\"\n    exit 0\nelse\n    usage\n    exit 1\nfi\n\n", "num_lines": 356}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nSMB_CPLD_I2C_BUS=\"12\"\nSMB_CPLD_I2C_ADDR=\"0x3e\"\n\ni2c_wr() {\n    i2cset \"$@\"; sleep 0.01;\n}\n\n# Wedge400-C GB switch reset commands collection\ngb_reset() {\n    if [ \"$1\" = \"cycle\" ];then\n        # gb power off\n        i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x42 0x0e\n        sleep 0.5\n        # gb power on\n        i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x42 0x0f\n        sleep 1\n    fi\n\n    # [3] mux_ps=1, ps=1, scan=0, tri_l=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    # [0] a_rstn=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xfe\n    # [0] tri_l=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xc\n    # [1] scan_mode=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xe\n    # [1] scan_mode=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xc\n    # [0] tri_l=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    # [0] a_rstn=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xff\n    # [0] a_rstn=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xfe\n    # [2] ps=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0x9\n    # [2] ps=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    sleep 0.5\n    # [0] a_rstn=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xff\n    # [3] mux_ps=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0x5\n}\n\ncase \"$1\" in\n    \"--help\" | \"?\" | \"-h\")\n        program=$(basename \"$0\")\n        echo \"Usage: switch chip reset command\"\n        echo \"  <$program> only reset switch without switch power cycle\"\n        echo \"  <$program cycle> to reset switch after switch power cycle\"\n    ;;\n\n    *)\n        shift\n        gb_reset \"$1\"\n    ;;\nesac\n", "num_lines": 81}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\n\nPWR_USRV_RST_SYSFS=\"${SCMCPLD_SYSFS_DIR}/iso_com_rst_n\"\nPWR_CYCLE_SYSFS=\"${PWRCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_TIMER_BASE_1S_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_TIMER_BASE_10S_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_TIMER_COUNTER_SETTING_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_counter_setting_update\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge400 system ungracefully\"\n    echo \"      -s -t [1-2550]: Setting boot up time.\"\n    echo \"            From 1 to 249 the step is 1 second.\"\n    echo \"            From 250 to 2550 the step is 10 seconds\"\n    echo \"            and don't care ones-digits.\"\n    echo\n    echo\n}\n\nmain_power_status() {\n    return 0\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on_com_e() {\n    echo 1 > \"$PWR_USRV_SYSFS\"\n    echo 1 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # reset TH\n    # reset_brcm.sh\n    # power on sequence\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n\tlogger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    echo 0 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_config_reset_timer() {\n    # Check numeric\n    wake_t=$1\n    echo \"$wake_t\" | grep -E -q '^[0-9]+$'\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        usage\n        exit 1\n    else\n        if [ \"$wake_t\" -ge 1 ] && [ \"$wake_t\" -lt 250 ];then\n            echo 1 > \"$PWR_TIMER_BASE_1S_SYSFS\"\n            echo 0 > \"$PWR_TIMER_BASE_10S_SYSFS\"\n            logger \"Waiting $wake_t seconds for the system boot up\"\n            echo \"Waiting $wake_t seconds for the system boot up\"\n        elif [ \"$wake_t\" -ge 250 ] && [ \"$wake_t\" -le 2550 ];then\n            echo 0 > \"$PWR_TIMER_BASE_1S_SYSFS\"\n            echo 1 > \"$PWR_TIMER_BASE_10S_SYSFS\"\n            wake_t=$((wake_t/10))\n            logger \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n            echo \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n        else\n            usage\n            exit 1\n        fi\n        echo $wake_t > \"$PWR_TIMER_COUNTER_SETTING_SYSFS\"\n        echo 1 > \"$PWR_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n    fi\n}\n\ndo_reset() {\n    local system timer wake_t opt\n    system=0\n    timer=0\n    wake_t=0\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            t)\n                timer=1\n                wake_t=$OPTARG\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n\n    if [ $system -eq 1 ]; then\n        if [ $timer -eq 1 ]; then\n            do_config_reset_timer \"$wake_t\"\n        fi\n        # Synchronize cached writes to persistent storage\n        # We found somethimes /mnt/data data lost after wedge_power.sh reset -s,\n        # add sync in case of file system will be broken by random power cycle.\n        sync\n        logger \"Power reset the whole system ...\"\n        echo  \"Power reset the whole system ...\"\n        echo 1 > \"$PWR_CYCLE_SYSFS\"\n        sleep 3\n        # Control should not reach here, but if it failed to reset\n        # the system through PSU, then run a workaround to reset\n        # most of the system instead (if not all)\n        logger \"Failed to reset the system. Will sleep for 3 sec then running a workaround\"\n        echo \"Failed to reset the system. Will sleep for 3 sec then running a workaround\"\n        i2cset -f -y 1 0x3a 0x12 0\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return 1\n        fi\n        # reset TH first\n        # reset_brcm.sh\n        echo -n \"Power reset microserver ...\"\n        echo 0 > \"$PWR_USRV_RST_SYSFS\"\n        sleep 1\n        echo 1 > \"$PWR_USRV_RST_SYSFS\"\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\nset_bic=0\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        set_bic=1\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        set_bic=1\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nif [ $set_bic -ne 0 ]; then\n    # sleep 10 seconds to wait BIC ready\n    (sleep 10; setup_bic.sh) &\nfi\n\nexit $?\n", "num_lines": 259}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get output from bic-util\nbic_output=$(bic-util scm --read_mac)\n\n# Check if the read was successful and output matches with our format\nmatch=$(echo \"$bic_output\" | grep -c 'MAC address: [0-9a-f][0-9a-f]:')\nif [ \"$match\" = \"1\" ]; then\n    # Mac address: xx:xx:xx:xx:xx:xx\n    echo \"$bic_output\" | cut -d ' ' -f 3\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit 1\nfi\n\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Provides:          xdpe12284 setup on EVT3\n# Short-Description: Some EVT3 units xdpe12284 has uncorrect firmware, BMC need\n#                    to set xdpe12284 registers to change max power supply as\n#                    power required.\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# Only some EVT3 need to set xdpe12284 power\n[ \"$(wedge_board_type_rev)\" != \"Cloudripper_EVT3\" ] && exit 0\n\necho -n \"Setup xdpe12284 on EVT3 unit ...\"\n\n# set register value n~m bits as expected\n# $1: current value\n# $2: start bit\n# $3: end bit\n# $4: start-end bits expect value\nupdate_reg() {\n    reg=$1\n    startbit=$2\n    endbit=$3\n    data=$4\n\n    ((lsb_mask = ((0xffff) >> startbit) << startbit))\n    ((msb_mask = ((0xffff) >> (15 - endbit)) ))\n    ((mask = lsb_mask & msb_mask))\n\n    reg=$((reg & ~mask))\n    reg=$((reg | ((data << startbit) & mask)))\n\n    printf 0x%x $reg\n}\n\nfor i in $(seq 1 2)\ndo\n    if [ \"$i\" -eq 1 ]; then\n        XPDE_BUS=\"19\"\n        XPDE_ADDR=\"0x68\"\n    elif [ \"$i\" -eq 2 ]; then\n        XPDE_BUS=\"22\"\n        XPDE_ADDR=\"0x60\"\n    fi\n\n    # We need to use i2c get/set instead of sysfs nodes because the pmbus driver not support.\n    # set page to 0x20\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x00 0x20\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x9 w)      #   page addr start end expect\n    val=$(update_reg \"$val\" 10 15 0x14)                 #   0x20  0x9   10   15  0x14\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x9 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0xA w)\n    val=$(update_reg \"$val\" 10 15 0x24)                 #   0x20  0xA   10   15  0x24\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0xA \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0xB w)\n    val=$(update_reg \"$val\" 6 11 0x14)                  #   0x20  0xB   6    11  0x14\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0xB \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x11 w)\n    val=$(update_reg \"$val\" 6 10 0x2)                   #   0x20  0x11  6    10  0x2\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x11 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x25 w)\n    val=$(update_reg \"$val\" 0 5  0x1E)                  #   0x20  0x25  0    5   0x1E\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x25 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x26 w)\n    val=$(update_reg \"$val\" 0 6  0x75)                  #   0x20  0x26  0    6   0x75\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x26 \"$val\" w\n\n    # set page to 0x21\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x00 0x21\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x2 w)\n    val=$(update_reg \"$val\" 0 9  0x50)                  #   0x21  0x2   0    9   0x50\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x2 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x5 w)\n    val=$(update_reg \"$val\" 8 10 0x6)                   #   0x21  0x5   8    10  0x6\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x5 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x9 w)\n    val=$(update_reg \"$val\" 10 15 0x1E)                 #   0x21  0x9   10   15  0x1E\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x9 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0xA w)\n    val=$(update_reg \"$val\" 10 15 0x1E)                 #   0x21  0xA   10   15  0x1E\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0xA \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0xB w)\n    val=$(update_reg \"$val\" 6 11 0x14)                  #   0x21  0xB   6    11  0x14\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0xB \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0xE w)\n    val=$(update_reg \"$val\" 0 5  0x29)                  #   0x21  0xE   0    5   0x29\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0xE \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x1E w)\n    val=$(update_reg \"$val\" 4 7  0x2)                   #   0x21  0x1E  4    7   0x2\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x1E \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x23 w)\n    val=$(update_reg \"$val\" 6 15 0x3C)                  #   0x21  0x23  6    15  0x3C\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x23 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x25 w)\n    val=$(update_reg \"$val\" 0 5  0x14)                  #   0x21  0x25  0    5   0x14\n    val=$(update_reg \"$val\" 6 15 0x50)                  #   0x21  0x25  6    15  0x50\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x25 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x27 w)\n    val=$(update_reg \"$val\" 0 7  0x2A)                  #   0x21  0x27  0    7   0x2A\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x27 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x2C w)\n    val=$(update_reg \"$val\" 0 3  0x2)                   #   0x21  0x2C  0    3   0x2\n    val=$(update_reg \"$val\" 4 7  0x2)                   #   0x21  0x2C  4    7   0x2\n    val=$(update_reg \"$val\" 8 11 0x2)                   #   0x21  0x2C  8    11  0x2\n    val=$(update_reg \"$val\" 12 15 0x2)                  #   0x21  0x2C  12   15  0x2\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x2C \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x37 w)\n    val=$(update_reg \"$val\" 0 7  0x28)                  #   0x21  0x37  0    7   0x28\n    val=$(update_reg \"$val\" 8 11 0x0)                   #   0x21  0x37  8    11  0x0\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x37 \"$val\" w\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x53 w)\n    val=$(update_reg \"$val\" 0 6  0xC)                   #   0x21  0x53  0    6   0xC\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x53 \"$val\" w\n\n    # set page to 0x22\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x00 0x22\n    val=$(i2cget -f -y $XPDE_BUS $XPDE_ADDR 0x45 w)\n    val=$(update_reg \"$val\" 0 3  0x0)                   #   0x22  0x45  0    3   0x0\n    i2cset -y -f $XPDE_BUS $XPDE_ADDR 0x45 \"$val\" w\n\n    # reset page to 0x0\n    i2cset -f -y $XPDE_BUS $XPDE_ADDR 0x0 0x0\ndone\n\necho \"done.\"\n", "num_lines": 144}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n# This script is a workaround for the I2C PMBUS vout sensor reading issue given\n# the root cause has not been found. When the issue happens, reload the pmbus\n# device driver will fix the issue.\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprintf \"Check special sensors and rebind driver...\"\n\ni2c_check_driver_binding \"fix-binding\"\n\n/usr/local/bin/xdpe12284-hack.sh\n\nretry=0\n# ir35215 chip enabled by COMe power on, \n# so need sleep some time to wait COMe Power on\nsleep 5\n#\n# We have seen intermittent ir35215 voltage reading value unreasonable and root cause is\n# not clear as of now. Testing shows below retry will help to mitigate\n# such error.\n#\nfixup_i2c_ir35215() {\n    while [ $retry -lt 5 ]; do\n        sensor1_ok=$(/usr/local/bin/sensor-util smb 0x12 --force | grep ok &> /dev/null; echo $?)\n        sensor2_ok=$(/usr/local/bin/sensor-util smb 0x20 --force | grep ok &> /dev/null; echo $?)\n        if [ $((sensor1_ok)) -eq 0 ] && [ $((sensor2_ok)) -eq 0 ]; then\n            echo \"Check ir35215 done\"\n            return\n        fi\n        retry=$((retry + 1))\n        echo \"trying fixup driver ir35215 for i2c device 16-4d, time $retry\"\n        i2c_device_delete 16 0x4d\n        i2c_device_add 16 0x4d ir35215\n    done\n    logger -p user.err \"Unable to fix ir35215 sensor reading after 5 retries\"\n}\n#\n# We have seen intermittent pxe1211 voltage reading value unreasonable and root cause is\n# not clear as of now. Testing shows below retry will help to mitigate\n# such error.\n#\nretry=0\nfixup_i2c_pxe1211() {\n    while [ $retry -lt 5 ]; do\n        sensor1_ok=$(/usr/local/bin/sensor-util smb 0x6e --force | grep ok &> /dev/null; echo $?)\n        sensor2_ok=$(/usr/local/bin/sensor-util smb 0x75 --force | grep ok &> /dev/null; echo $?)\n        sensor3_ok=$(/usr/local/bin/sensor-util smb 0x7c --force | grep ok &> /dev/null; echo $?)\n        if [ $((sensor1_ok)) -eq 0 ] && [ $((sensor2_ok)) -eq 0 ]  && [ $((sensor3_ok)) -eq 0 ]; then\n            echo \"Check pxe1211 done\"\n            return\n        fi\n        retry=$((retry + 1))\n        echo \"trying fixup driver pxe1211 for i2c device 20-0e, time $retry\"\n        i2c_device_delete 20 0x0e\n        i2c_device_add 20 0x0e pxe1211\n    done\n    logger -p user.err \"Unable to fix pxe1211 sensor reading after 5 retries\"\n}\n#\n# We have seen intermittent xdpe132g5c voltage reading value unreasonable and root cause is\n# not clear as of now. Testing shows below retry will help to mitigate\n# such error.\n#\nretry=0\nfixup_i2c_xdpe132g5c() {\n    while [ $retry -lt 5 ]; do\n        sensor1_ok=$(/usr/local/bin/sensor-util smb 0x35 --force | grep ok &> /dev/null; echo $?)\n        sensor2_ok=$(/usr/local/bin/sensor-util smb 0x2e --force | grep ok &> /dev/null; echo $?)\n        if [ $((sensor1_ok)) -eq 0 ] && [ $((sensor2_ok)) -eq 0 ]; then\n            echo \"Check xdpe132g5c done\"\n            return\n        fi\n        retry=$((retry + 1))\n        echo \"trying fixup driver xdpe132g5c for i2c device 17-40, time $retry\"\n        i2c_device_delete 17 0x40\n        i2c_device_add 17 0x40 xdpe132g5c\n    done\n    logger -p user.err \"Unable to fix xdpe132g5c sensor reading after 5 retries\"\n}\n\nfixup_i2c_ir35215\nfixup_i2c_pxe1211\nfixup_i2c_xdpe132g5c\n", "num_lines": 99}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/set_fan_speed.sh 50\n/usr/local/bin/fand -v\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n\nSYSCPLD_SYSFS_DIR=\"/sys/class/i2c-dev/i2c-13/device/13-003e\"\nSLOTID_SYSFS=\"${SYSCPLD_SYSFS_DIR}/slotid\"\n\nwedge_board_type() {\n    echo 'CMM'\n}\n\nwedge_slot_id() {\n    val=$(head -n 1 $SLOTID_SYSFS)\n    if [ \"${val}\" = \"0x1\" ]; then\n        echo c1\n    else\n        echo c2\n    fi\n}\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ndeclare -a DEVICES\nDEVICES=(\n  I2C:0x1\n  SCM-BMC:0x2\n)\n\ndeclare -a MODULES\nMODULES=(\n  LC101:0x40\n  LC102:0x50\n  LC201:0x41\n  LC202:0x51\n  LC301:0x42\n  LC302:0x52\n  LC401:0x43\n  LC402:0x53\n  FC1:0x88\n  FC2:0x89\n  FC3:0x8a\n  FC4:0x8b\n  SCM-FC1-LEFT:0xc2\n  SCM-FC1-RIGHT:0xd2\n  SCM-FC2-LEFT:0xc3\n  SCM-FC2-RIGHT:0xd3\n  SCM-LC101:0xc4\n  SCM-LC102:0xd4\n  SCM-LC201:0xc5\n  SCM-LC202:0xd5\n  SCM-LC301:0xc6\n  SCM-LC302:0xd6\n  SCM-LC401:0xc7\n  SCM-LC402:0xd7\n  SCM-FC3-LEFT:0xc8\n  SCM-FC3-RIGHT:0xd8\n  SCM-FC4-LEFT:0xc9\n  SCM-FC4-RIGHT:0xd9\n)\n\n#Resetting all the devices of a module\nresetModuleDeviceAll(){\n    for key in ${MODULES[*]}; do\n        module=${key%%:*}\n        m_value=${key##*:}\n        if [[ \"${module}\" = \"$1\" || -z \"$1\" ]]; then\n            echo \"Resetting ${module} module and the device on SCM-BMC and the i2c endpoints\"\n            for dev in ${DEVICES[*]}; do\n                device=${dev%%:*}\n                d_value=${dev##*:}\n                echo \"Resetting ${device} devices of ${module} module.\"\n                sleep 1\n                echo ${d_value} > /sys/bus/i2c/drivers/cmmcpld/13-003e/one_wire_rst_device\n                echo ${m_value} > /sys/bus/i2c/drivers/cmmcpld/13-003e/one_wire_rst_trig\n            done\n            #Only reset one LC/FC\n            if [ -n \"$1\" ]; then\n                break\n            fi\n        fi\n    done\n\n    if [[ -n \"$1\" && ${module} != \"$1\" ]]; then\n        echo \"Error: unsupported module name <$1>!\"\n        usage\n    fi\n    unset module value\n}\n\n#Resetting a specific device from a module\nresetModuleDevice(){\n    for key in ${MODULES[*]}; do\n        module=${key%%:*}\n        m_value=${key##*:}\n        if [ \"${module}\" = \"$1\" ]; then\n            if [ \"$2\" = \"all\" ]; then\n                resetModuleDeviceAll $module\n                unset module m_value\n                return\n            else\n                for dev in ${DEVICES[*]}; do\n                    device=${dev%%:*}\n                    d_value=${dev##*:}\n                    if [ \"${device}\" = $2 ]; then\n                        echo \"Resetting ${device} devices of ${module} module.\"\n                        sleep 1\n                        echo ${d_value} > /sys/bus/i2c/drivers/cmmcpld/13-003e/one_wire_rst_device\n                        echo ${m_value} > /sys/bus/i2c/drivers/cmmcpld/13-003e/one_wire_rst_trig\n                        unset module m_value device d_value\n                        return\n                    fi\n                done\n            fi\n        fi\n    done\n\n    if  [[ ${module} != \"$1\" || ${device} != \"$2\" ]]; then\n        echo \"Error: unsupported module/device name!\"\n        usage\n    fi\n    unset module m_value device d_value\n}\n\n#List supported modules and devices for the user\nviewModuleDevices(){\n    echo \"Available modules:\"\n    for key in ${MODULES[*]}; do\n        module=${key%%:*}\n        echo \"$module\"\n    done\n    echo -e \"\\nAvailable devices:\"\n\n    for key in ${DEVICES[*]}; do\n        device=${key%%:*}\n        echo \"$device\"\n    done\n    unset module device\n}\n\nusage() {\n    echo \"Usage: cmm-modules-devices-reset.sh <module> [device] | all\"\n    echo \"\"\n\n    viewModuleDevices\n\n    echo \"\"\n    echo \"Example: cmm-modules-devices-reset.sh LC101\"\n    echo \"Example reset all LC/FC: cmm-modules-devices-reset.sh all\"\n}\n\n#parse command line arguments\nif [ $# == 0 ]; then\n    echo \"Error: <module> parameter is missing!\"\n    usage\nelif [ $# == 1 ]; then\n    if [ \"$1\" = \"view-modules-devices\" ]; then\n        viewModuleDevices\n    elif [ \"$1\" = \"all\" ]; then\n        resetModuleDeviceAll\n    else\n        resetModuleDeviceAll \"$1\"\n    fi\nelif [ $# == 2 ]; then\n    resetModuleDevice \"$1\" \"$2\"\nelse\n    echo \"Error: invalid command line arguments!\"\n    usage\n    exit 1\nfi\n", "num_lines": 170}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif [ $# -ne 1 ]; then\n    exit -1\nfi\n\nimg=\"$1\"\n\nsource /usr/local/bin/openbmc-utils.sh\n\n# change CPLD_JTAG_SEL to 0 to connect BMC_CPLD pins\ngpio_set CPLD_JTAG_SEL 0\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n    --tms BMC_CPLD_TMS \\\n    --tdo BMC_CPLD_TDO \\\n    --tdi BMC_CPLD_TDI \\\n    --tck BMC_CPLD_TCK\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nsource /usr/local/bin/gpio-utils.sh\n\nif [ $# -ne 2 ]; then\n    exit -1\nfi\n\n# Convert card string to upper case\ncard=\"${1^^}\"\nif [ ${card} != \"FCB1\" && ${card} != \"FCB2\" && \\\n     ${card} != \"FCB3\" && ${card} != \"FCB4\" ]; then\n    echo \"${1} is not a correct FCB card name.\"\n    exit -1\nfi\nimg=\"$2\"\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n    --tms ${card}_CPLD_TMS \\\n    --tck ${card}_CPLD_TCK \\\n    --tdi ${card}_CPLD_TDI \\\n    --tdo ${card}_CPLD_TDO\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nusage() {\n  echo \"Usage: $0 [Fan Unit (1...12)]\" >&2\n}\n\n# map the output of the command into an array\nmapfile -t FAN_ARRAY < <(sensors fancpld-*|grep ^Fan)\n\nshow_rpm(){\n  front_fan_idx=$(( ($1 - 1) * 2 ))\n  rear_fan_idx=$((( ( $1 - 1) * 2) + 1))\n  IFS=' ' read -r -a fan_front <<< \"${FAN_ARRAY[$front_fan_idx]}\"\n  IFS=' ' read -r -a fan_rear <<< \"${FAN_ARRAY[$rear_fan_idx]}\"\n\n  if [ \"${#fan_front[@]}\" -ne 5 ] || [ \"${#fan_rear[@]}\" -ne 5 ]; then\n      echo \"wrong sensors fan reading input. Exiting ...\"\n      exit 1\n  fi\n\n  echo \"${fan_front[3]}, ${fan_rear[3]}\"\n}\n\n# Return appropriate value based on the argument passed to it.\nif [ \"$#\" -eq 0 ]; then\n  FANS=\"1 2 3 4 5 6 7 8 9 10 11 12\"\nelif [ \"${#}\" -eq 1 ]; then\n    if [ \"${1}\" -lt 1 ] || [ \"${1}\" -gt 12 ]; then\n        usage\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\nfor fan in $FANS; do\n  echo \"Fan $fan RPMs: $(show_rpm \"${fan}\")\"\ndone\n", "num_lines": 58}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nsource /usr/local/bin/openbmc-utils.sh\n\nSYSFS_I2C_DEVICES='/sys/bus/i2c/devices'\n\nCMD=\"${SYSFS_I2C_DEVICES}/13-003e/*present\"\nFAN_CMD1=\"${SYSFS_I2C_DEVICES}/171-0033/\"\nFAN_CMD2=\"${SYSFS_I2C_DEVICES}/179-0033/\"\nFAN_CMD3=\"${SYSFS_I2C_DEVICES}/187-0033/\"\nFAN_CMD4=\"${SYSFS_I2C_DEVICES}/195-0033/\"\n\n# Will return <key> : <val>\n# eg :- cmm : 1\nfunction get_presence\n{\n  local file=$1 key=$2\n  val=$(head -n1 $file | awk '{print substr($0,0,3) }' | sed 's/.x//')\n  if [ $val -eq 0 ]; then\n    val=1\n  else\n    val=0\n  fi\n  echo $key \":\" $val\n}\n\n# CMMs, FCs, LCs, SCMs\nfunction get_card_presence\n{\n  for file in $CMD\n  do\n    key=$(echo $file | sed 's/.*003e\\///' | sed 's/_present.*//')\n    get_presence $file $key\n  done\n}\n\n# If fc1 is present fcb1 is present, same for other fcbs\n# Fans\nfunction get_fan_presence\n{\n  local num=1 fan_cmd=$1 count=$((($2 * 3) - 2))\n  while [ $num -lt 4 ]; do\n    key='fan'$count\n    file=$fan_cmd'fantray'$num'_present'\n    get_presence $file $key\n    (( num++ ))\n    (( count++ ))\n  done\n}\n\n# Power supplies\nfunction get_psu_presence\n{\n  local num=1\n  while [ $num -lt 5 ]; do\n    key='psu'$num\n    cmd='gpio_get PSU'$num'_PRESENT'\n    val=$($cmd)\n    if [ $val -eq 0 ]; then\n      val=1\n    else\n      val=0\n    fi\n    echo $key \":\" $val\n    (( num++ ))\n  done\n}\n\n# get all info\necho \"CARDS\"\nget_card_presence\n\necho \"FANS\"\nget_fan_presence $FAN_CMD1 1\nget_fan_presence $FAN_CMD2 2\nget_fan_presence $FAN_CMD3 3\nget_fan_presence $FAN_CMD4 4\n\necho \"POWER SUPPLIES\"\nget_psu_presence\n", "num_lines": 101}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# channel 0: r1: 17.8K; r2:  2.2K; v2: 0mv\n# channel 1: r1:  3.3K; r2:  1.0K; v2: 0mv\n# channel 2: r1:  3.3K; r2:  2.2K; v2: 0mv\n# channel 3: r1:  3.3K; r2:  3.3K; v2: 0mv\n# channel 4: r1:  0.0K; r2:  1.0K; v2: 0mv\n# channel 5: r1:  0.0K; r2:  1.0K; v2: 0mv\n# channel 6: r1: 17.8K; r2:  2.2K; v2: 0mv\n# channel 7: r1:  3.3K; r2:  1.0K; v2: 0mv\n# channel 8-15: not used by cmm.\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    sysfs_adc_path=\"/sys/devices/platform/ast_adc.0\"\n\n    echo $r1 > ${sysfs_adc_path}/adc${channel}_r1\n    echo $r2 > ${sysfs_adc_path}/adc${channel}_r2\n    echo $v2 > ${sysfs_adc_path}/adc${channel}_v2\n    echo 1 > ${sysfs_adc_path}/adc${channel}_en\n}\n\nbulk_setup_adc() {\n    config_adc 0 178 22 0\n    config_adc 1  33 10 0\n    config_adc 2  33 22 0\n    config_adc 3  33 33 0\n    config_adc 4   0 10 0\n    config_adc 5   0 10 0\n    config_adc 6 178 22 0\n    config_adc 7  33 10 0\n}\n\n#\n# Passing R1, R2 and V2 values to kernel is only needed in kernel 4.1;\n# In kernel 4.17 (or newer versions), voltage computation formulas are\n# defined in lm_sensors config file.\n#\nKERNEL_VERSION=`uname -r`\nif [[ ${KERNEL_VERSION} == 4.1.* ]]; then\n    bulk_setup_adc\nfi\n", "num_lines": 65}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nsource /usr/local/bin/openbmc-utils.sh\n\n#\n# Setup gpios managed by the given i2c IO Expander.\n# $1 - sysfs path of the i2c io expander. For example, 30-0020\n# $2 - offset (within the gpio chip)\n# $3 - list of symbolic links for the gpio pins\n#\nsetup_i2c_gpios() {\n    local i2c_path=${1}\n    local offset=${2}\n    shift 2\n    local symlinks=\"$*\"\n    local gpio_chip=$(gpiochip_lookup_by_i2c_path ${i2c_path})\n    local gpio_base=$(gpiochip_get_base ${gpio_chip})\n    local pin link_name\n\n    if [ -z \"${gpio_base}\" ]; then\n        echo \"unable to export pins of io expander ${i2c_path}\"\n        return\n    fi\n\n    for link_name in ${symlinks}; do\n        pin=$((gpio_base + offset))\n        gpio_export ${pin} ${link_name}\n        offset=$((offset + 1))\n    done\n}\n\n#\n# Explicitly disable other functions so the pins function as gpio.\n# NOTE: the function is only needed in kernel 4.1: pinctrl is handled\n# in device tree in kernel 4.18 and future versions.\n#\npinctrl_request_gpios() {\n    # GPIOM0|M1|M2|M3\n    # SCU84[24|25|26|27] must be 0 to disable UART2 function pins.\n    for bit in 24 25 26 27; do\n        devmem_clear_bit $(scu_addr 84) $bit\n    done\n\n    # GPIOF0\n    # SCU90[30] must be 0 to disable LPC LHAD0 function.\n    # SCU80[24] must be 0 to disable UART4 NCTS function.\n    devmem_clear_bit $(scu_addr 90) 30\n    devmem_clear_bit $(scu_addr 80) 24\n}\n\n#\n# Test if the pins are functions as gpio pins.\n#\npinctrl_check_gpios() {\n    # GPIOM0|M1|M2|M3\n    # SCU84[24|25|26|27] must be 0 to disable UART2 function pins.\n    for bit in 24 25 26 27; do\n        if devmem_test_bit $(scu_addr 84) $bit; then\n            echo \"pinctrl error: GPIOM# pins are claimed by UART2 functions\"\n        fi\n    done\n\n    # GPIOF0\n    # SCU90[30] must be 0 to disable LPC LHAD0 function.\n    # SCU80[24] must be 0 to disable UART4 NCTS function.\n    if devmem_test_bit $(scu_addr 90) 30; then\n        echo \"pinctrl error: GPIOF0 pin is claimed by LPC function\"\n    fi\n    if devmem_test_bit $(scu_addr 80) 24; then\n        echo \"pinctrl error: GPIOF0 pin is claimed by UART4 function\"\n    fi\n}\n\n# The gpio pins managed by aspeed gpio controller always start\n# from 0 in kernel 4.1, but it's dynamically allocated in kernel\n# 4.17, thus we need to read the base from sysfs.\nKERNEL_VERSION=`uname -r`\nif [[ ${KERNEL_VERSION} == 4.1.* ]]; then\n    ASPEED_GPIO_BASE=0\n    pinctrl_request_gpios\nelse\n    ASPEED_GPIOCHIP=$(gpiochip_lookup_by_label 1e780000.gpio)\n    ASPEED_GPIO_BASE=$(gpiochip_get_base ${ASPEED_GPIOCHIP})\n    if [ -z \"${ASPEED_GPIO_BASE}\" ]; then\n        echo \"unable to find base pin of aspeed gpio controller\"\n        exit 1\n    fi\nfi\n\npinctrl_check_gpios\n\n# GPIOM0: BMC_CPLD_TMS\n# GPIOM1: BMC_CPLD_TDI\n# GPIOM2: BMC_CPLD_TCK\n# GPIOM3: BMC_CPLD_TDO\nIDX=0\nSYMLINKS=\"BMC_CPLD_TMS BMC_CPLD_TDI BMC_CPLD_TCK BMC_CPLD_TDO\"\nfor LINK_NAME in ${SYMLINKS}; do\n    OFFSET=$(gpio_name2value M${IDX})\n    PIN=$((ASPEED_GPIO_BASE + OFFSET))\n    gpio_export ${PIN} ${LINK_NAME}\n    IDX=$((IDX + 1))\ndone\n\n# GPIOF0: CPLD_JTAG_SEL (needs to be low)\nOFFSET=$(gpio_name2value F0)\nPIN=$((ASPEED_GPIO_BASE + OFFSET))\ngpio_export ${PIN} CPLD_JTAG_SEL\n\n# SYSTEM LED GPIOs\nSYSLED_SYMLINKS=\"SYS_LED_RED SYS_LED_GREEN SYS_LED_BLUE\n                 FAN_LED_RED FAN_LED_GREEN FAN_LED_BLUE\n                 PSU_LED_RED PSU_LED_GREEN PSU_LED_BLUE\n                 FAB_LED_RED FAB_LED_GREEN FAB_LED_BLUE\"\nsetup_i2c_gpios \"30-0021\" 0 ${SYSLED_SYMLINKS}\n\n# PSU PRESENCE GPIOs\nPSU_SYMLINKS=\"PSU4_PRESENT PSU3_PRESENT PSU2_PRESENT PSU1_PRESENT\"\nsetup_i2c_gpios \"29-0020\" 8 ${PSU_SYMLINKS}\n\n# FCB1 GPIOs\nFCB1_SYMLINKS=\"FCB1_CPLD_TMS FCB1_CPLD_TCK FCB1_CPLD_TDI FCB1_CPLD_TDO\"\nsetup_i2c_gpios \"172-0022\" 0 ${FCB1_SYMLINKS}\n\n# FCB2 GPIOs\nFCB2_SYMLINKS=\"FCB2_CPLD_TMS FCB2_CPLD_TCK FCB2_CPLD_TDI FCB2_CPLD_TDO\"\nsetup_i2c_gpios \"180-0022\" 0 ${FCB2_SYMLINKS}\n\n# FCB3 GPIOs\nFCB3_SYMLINKS=\"FCB3_CPLD_TMS FCB3_CPLD_TCK FCB3_CPLD_TDI FCB3_CPLD_TDO\"\nsetup_i2c_gpios \"188-0022\" 0 ${FCB3_SYMLINKS}\n\n# FCB4 GPIOs\nFCB4_SYMLINKS=\"FCB4_CPLD_TMS FCB4_CPLD_TCK FCB4_CPLD_TDI FCB4_CPLD_TDO\"\nsetup_i2c_gpios \"196-0022\" 0 ${FCB4_SYMLINKS}\n", "num_lines": 155}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n##### NOTE #########################################################\n# - When adding new devices, always add to end of the list here\n#   so any other dependencies that are hard coded with GPIO\n#   will not break.\n# - Although technically all the i2c devices can be created by using\n#   device tree, we prefer to do it here, mainly because:\n#     * it's easier to control the order of device creation.\n#     * a majority of i2c devices are located on line/fabric cards,\n#       and it's easier to control device creation/removal and add\n#       hot-plug support in the future.\n####################################################################\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/i2c-utils.sh\n\n#\n# instantiate all the i2c-muxes.\n# Note:\n#   - the function may be skipped if i2c switches were already created\n#     in kernel space.\n#   - please do not modify the order of i2c-mux creation unless you've\n#     decided to fix bus-number of leaf i2c-devices.\n#\nbulk_create_i2c_mux() {\n    i2c_mux_name=\"pca9548\"\n    mux_channels=8\n\n    # The first-level i2c-muxes which are directly connected to aspeed\n    # i2c adapters are described in device tree, and the bus number of\n    # these i2c-muxes' channels are hardcoded (as below) to avoid\n    # breaking the existing applications.\n    #    i2c-mux 1-0077: child bus 16-23\n    #    i2c-mux 2-0071: child bus 24-31\n    #    i2c-mux 8-0077: child bus 32-39\n\n    # Create second-level i2c-muxes which are connected to first level\n    # mux \"1-0077\". \"1-0077\" has 8 channels and each channel is connected\n    # with 2 more i2c-muxes (@ address 0x70 & 0x73), thus total 128 i2c\n    # buses (40-167) will be registered.\n    parent_buses=\"18 19 20 21 16 17 22 23\"\n    mux_addresses=\"0x70 0x73\"\n    for bus in ${parent_buses}; do\n        for addr in ${mux_addresses}; do\n            i2c_mux_add_sync \"$bus\" \"$addr\" \"$i2c_mux_name\" \"$mux_channels\"\n        done\n    done\n\n    # Create second-level i2c-muxes which are connected to first level\n    # mux \"8-0077\". \"8-0077\" has 8 channels and the first 4 channels are\n    # connected with 1 extra level of i2c-mux (@ address 0x70), thus\n    # totally 32 i2c buses (168-199) will be registered.\n    parent_buses=\"32 33 34 35\"\n    for bus in ${parent_buses}; do\n        i2c_mux_add_sync \"$bus\" 0x70 \"$i2c_mux_name\" \"$mux_channels\"\n    done\n}\n\n#\n# We've seen some intermittent i2c transaction failures on i2c8 because\n# some slaves (on Fan Control Boards) NACK the address stage.\n# We are not quite clear if it's caused by flaw(s) in i2c switch channel\n# selection, or due to the \"longer\" distance between BMC SoC and Fan\n# Control Boards (compared with other i2c buses on Galaxy Chassis), but\n# increasing base clock divisor (which impacts bus free time as well as\n# data setup/hold time) helps to fix/mitigate the issue.\n#\n# Below line updates i2c8 (0-based) I2CD04: Clock and AC Timing Control\n# Register #1 value from default 0xFFFFE003 to 0xFFF77004.\n#\ndevmem 0x1E78A344 32 0xFFF77004\n\n#\n# Let's check a few i2c switches on fabric cards to determine if these\n# switches were already created in kernel space.\n#\nI2C_MUX_FAB1=\"${SYSFS_I2C_DEVICES}/16-0070\"\nI2C_MUX_FAB2=\"${SYSFS_I2C_DEVICES}/17-0070\"\nI2C_MUX_FAB3=\"${SYSFS_I2C_DEVICES}/22-0070\"\nI2C_MUX_FAB4=\"${SYSFS_I2C_DEVICES}/23-0070\"\nif [ ! -e \"${I2C_MUX_FAB1}\" ] && [ ! -e \"${I2C_MUX_FAB2}\" ] && \\\n   [ ! -e \"${I2C_MUX_FAB3}\" ] && [ ! -e \"${I2C_MUX_FAB4}\" ]; then\n    bulk_create_i2c_mux\nfi\n\n# EEPROM\ni2c_device_add 6 0x51 24c64\n\n#PCB EEPROM\ni2c_device_add 28 0x50 24c64\n\n# Two temperature sensors on CMM\ni2c_device_add 3 0x48 tmp75 # inlet\ni2c_device_add 3 0x49 tmp75 # outlet\n\n# CMM CPLD\ni2c_device_add 13 0x3e cmmcpld\n\n# FAN CPLD\nfancpld_busses=\"171 179 187 195\"\nfor bus in ${fancpld_busses}; do\n    i2c_device_add ${bus} 0x33 fancpld\ndone\n\n# Temperature sensors\n# FAB1: 106   0x48 - 0x4b\n# SCM-FAB1: 113 0x48, 114 0x49\n\n# FAB2: 122\n# SCM-FAB2: 129 0x48, 130 0x49\n\n# LC101: 42, 0x48-0x4b\n# LC102: 45, 0x48-0x4b\n# SCM-LC1: 49 0x48, 50 0x49\n\n# LC201: 58\n# LC202: 61\n# SCM-LC2: 65 0x48, 66, 0x49\n\n# LC301: 74\n# LC302: 77\n# SCM-LC3: 81 0x48, 82, 0x49\n\n# LC401: 90\n# LC401: 93\n# SCM-LC4: 97 0x48, 98 0x49\n\n# FAB3: 138\n# SCM-FAB3: 145 0x48, 146 0x49\n\n# FAB4: 154\n# SCM-FAB4: 161 0x48, 162 0x49\n\n# Temperature sensors on LC/FC\ntemp_busses=\"42 45 58 61 74 77 90 93 106 122 138 154\"\ntemp_addrs=\"0x48 0x49 0x4a 0x4b\"\nfor bus in ${temp_busses}; do\n    for addr in ${temp_addrs}; do\n        i2c_device_add ${bus} ${addr} tmp75\n    done\ndone\n\n# Temperature sensors on SCM\ntemp_busses=\"113 129 49 65 81 97 145 161\"\nfor bus in ${temp_busses}; do\n    i2c_device_add ${bus} 0x48 tmp75\n    i2c_device_add $((bus + 1)) 0x49 tmp75\ndone\n\n# FCB PCA9534\n# GPIOs are allocated backwards.\n# So, list the bus list in reverse order,\n# so that GPIO numbers are increasing from FCB1-FCB4\nfcb_busses=\"196 188 180 172\"\nfor bus in ${fcb_busses}; do\n    i2c_device_add ${bus} 0x22 pca9534\ndone\n\n# PSU PRESENCE\n# Spec says pca9506 but this kernel version supports only 9505\n# which works for us\ni2c_device_add 29 0x20 pca9505\n\n# PFE modules\ni2c_device_add 27 0x10 pfe3000 # psu1\ni2c_device_add 26 0x10 pfe3000 # psu2\ni2c_device_add 25 0x10 pfe3000 # psu3\ni2c_device_add 24 0x10 pfe3000 # psu4\n\n# LEDs\ni2c_device_add 30 0x21 pca9535\n\n#\n# Go through all i2c devices and trigger manual driver binding if needed.\n#\nif [[ ${KERNEL_VERSION} != 4.1.* ]]; then\n    # sleep 50 milliseconds just in case driver binding is \"delayed\".\n    usleep 50000\n\n    i2c_check_driver_binding \"fix-binding\"\nfi\n", "num_lines": 201}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          system monitoring\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set system monitoring\n### END INIT INFO\n\necho -n \"Setup system monitoring \"\n/usr/local/bin/system_monitor.sh >/dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# There are 4 busses and 3 fans on each bus. The fans are labeled 1-12 in the\n# following order: Bus 171 fan 1,2,3; Bus 179 fan 4,5,6; Bus 187 fan 7,8,9; and\n# Bus 195 fan 10,11,12.\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)>  <Fan ID (1..12)>\" >&2\n}\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nbusses=\"171 179 187 195\"\nif [ \"$#\" -eq 1 ]; then\n    ids=\"1 2 3\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 13 ]; then\n        echo \"Fan id $2: not a valid id\"\n        exit 1\n    fi\n    FAN=\"$2\"\n    FAN=$((${FAN} - 1))\n    busIndex=$((${FAN} / 3))\n    temp=$((${FAN} - ( ${FAN} / 3 * 3 )))\n    ids=$((${temp} + 1))\n    if [ ${busIndex} -eq 0 ]; then\n        busses=\"171\"\n    elif [ ${busIndex} -eq 1 ]; then\n        busses=\"179\"\n    elif [ ${busIndex} -eq 2 ]; then\n        busses=\"187\"\n    else\n        busses=\"195\"\n    fi\nfi\n\n# Convert the percentage to our 1/32th unit (0-31).\nunit=$(( ( $1 * 31 ) / 100 ))\n\nfor bus in ${busses}; do\n    for id in ${ids}; do\n        pwm=\"/sys/class/i2c-dev/i2c-${bus}/device/${bus}-0033/fantray${id}_pwm\"\n        echo \"$unit\" > \"${pwm}\"\n        echo \"Successfully set fan ${id} on bus ${bus} speed to $1%\"\n    done\ndone\n", "num_lines": 69}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nusage() {\n    echo \"Usage: $0 <card name>\"\n    echo \"    card name: lc101, lc102, ..., fc3, fc4, cmm\"\n}\n\nif [ $# -ne 1 ]; then\n    usage \"$0\"\n    exit -1\nfi\n\ndeclare -A card_uart_map\ncard_uart_map[fc1]=0x1\ncard_uart_map[fc2]=0x2\ncard_uart_map[fc3]=0x3\ncard_uart_map[fc4]=0x4\ncard_uart_map[lc101]=0x5\ncard_uart_map[lc102]=0x9\ncard_uart_map[lc201]=0x6\ncard_uart_map[lc202]=0xa\ncard_uart_map[lc301]=0x7\ncard_uart_map[lc302]=0xb\ncard_uart_map[lc401]=0x8\ncard_uart_map[lc402]=0xc\ncard_uart_map[cmm]=0xd\n\nvalue=${card_uart_map[${1,,}]}\nif [ -z \"$value\" ]; then\n    usage \"$0\"\n    exit -1\nfi\n\nsysfs_path=\"/sys/class/i2c-dev/i2c-13/device/13-003e/uart3_mux_ctrl\"\n\necho \"You are in SOL session.\"\necho \"Use ctrl-x to quit.\"\necho \"-----------------------\"\necho\n\ntrap 'echo 0 > \"$sysfs_path\"' INT TERM QUIT EXIT\n\necho $value > \"$sysfs_path\"\n\n/usr/bin/microcom -s 9600 /dev/ttyS2\n\necho\necho\necho \"-----------------------\"\necho \"Exit from SOL session.\"\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\nsource /usr/local/bin/openbmc-utils.sh\n\nfunction set_led_color\n{\n  local component=$1 color=$2\n\n  if [ \"$color\" = 'yellow' ]; then\n    echo out > /tmp/gpionames/${component}_RED/direction\n    echo 0 > /tmp/gpionames/${component}_RED/value\n\n    echo out > /tmp/gpionames/${component}_GREEN/direction\n    echo 0 > /tmp/gpionames/${component}_GREEN/value\n\n    echo in > /tmp/gpionames/${component}_BLUE/direction\n    echo 1 > /tmp/gpionames/${component}_BLUE/value\n\n  elif [ \"$color\" = 'red' ]; then\n    echo out > /tmp/gpionames/${component}_RED/direction\n    echo 0 > /tmp/gpionames/${component}_RED/value\n\n    echo in > /tmp/gpionames/${component}_GREEN/direction\n    echo 1 > /tmp/gpionames/${component}_GREEN/value\n\n    echo in > /tmp/gpionames/${component}_BLUE/direction\n    echo 1 > /tmp/gpionames/${component}_BLUE/value\n\n  else\n    echo in > /tmp/gpionames/${component}_RED/direction\n    echo 1 > /tmp/gpionames/${component}_RED/value\n\n    echo in > /tmp/gpionames/${component}_GREEN/direction\n    echo 1 > /tmp/gpionames/${component}_GREEN/value\n\n    echo out > /tmp/gpionames/${component}_BLUE/direction\n    echo 0 > /tmp/gpionames/${component}_BLUE/value\n  fi\n}\n# System led:\n# If atleast 1 card is not present = yellow (red+green)\n# otherwise = blue\n# note presence util reads peer cmm =0\nfunction set_sys_led\n{\n  local ret=0\n  ret=$('/usr/local/bin/presence_util.sh' | grep \": 0\" | wc -l)\n  if [ $ret -gt 1 ]; then\n    set_led_color 'SYS_LED' 'yellow'\n  else\n    set_led_color 'SYS_LED' 'blue'\n  fi\n}\n\n# Fabric LED:\n# all present = blue\n# atleast 1 missing = yellow\n# more than 1 missing = red\nfunction set_fab_led\n{\n  local count=0\n  count=$(/usr/local/bin/presence_util.sh | sed -n \"/^fc.*: 0/p\" | wc -l)\n  if [ $count -eq 1 ]; then\n    set_led_color 'FAB_LED' 'yellow'\n  elif [ $count -gt 1 ]; then\n    set_led_color 'FAB_LED' 'red'\n  else\n    set_led_color 'FAB_LED' 'blue'\n  fi\n}\n\nfunction check_psu_alarm\n{\n  local sensor=$1\n  local vout_low_th=11 vout_high_th=13 vin_low_th=100 vin_high_th=250 vin=0 vout=0\n\n  readarray pfe1 < <(/usr/bin/sensors $sensor | grep -e vin -e vout1)\n  vin=$(echo \"${pfe1}\" | sed -e 's/vin:\\s*+\\(.*\\)[.].*$/\\1/')\n  vout=$(echo \"${pfe1[1]}\" | sed -e 's/vout1:\\s*+\\(.*\\)[.].*$/\\1/')\n  if [ $vin -lt $vin_low_th ] || [ $vin -gt $vin_high_th ] ; then\n    return 0\n  fi\n  if [ $vout -lt $vout_low_th ] || [ $vout -gt $vout_high_th ]; then\n    return 0\n  fi\n  return 1\n}\n\nfunction set_psu_led\n{\n  local ret=0\n  sensors=( \"pfe3000-i2c-24-10\" \"pfe3000-i2c-25-10\" \"pfe3000-i2c-26-10\" \"pfe3000-i2c-27-10\" )\n  for i in \"${sensors[@]}\"\n  do\n    if check_psu_alarm $i; then\n      set_led_color 'PSU_LED' 'red'\n      return\n    fi\n  done\n  ret=$(/usr/local/bin/presence_util.sh | sed -n \"/psu.*: 0/p\" | wc -l)\n  if [ $ret -gt 0 ]; then\n    set_led_color 'PSU_LED' 'yellow'\n  else\n    set_led_color 'PSU_LED' 'blue'\n  fi\n}\n\nfunction set_fan_led\n{\n  local ret=0\n  ret=$(/usr/bin/sensors fancpld-* | sed -n \"/^Fan.*: 0 RPM/p\" | wc -l)\n  if [ $ret -gt 0 ]; then\n    set_led_color 'FAN_LED' 'red'\n    return\n  fi\n  ret=$(/usr/local/bin/presence_util.sh | sed -n \"/fan.*: 0/p\" | wc -l)\n  if [ $ret -gt 0 ]; then\n    set_led_color 'FAN_LED' 'yellow'\n  else\n    set_led_color 'FAN_LED' 'blue'\n  fi\n}\n\nwhile :\ndo\n  set_sys_led\n  sleep 1s\n  set_fab_led\n  sleep 1s\n  set_psu_led\n  sleep 1s\n  set_fan_led\n  sleep 10m\ndone\n", "num_lines": 154}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nTTY=/dev/ttyS1\n\nmTerm_server_running() {\n  # shellcheck disable=SC2009\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ \"$pid\" ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  /usr/bin/microcom -s 57600 $TTY\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\nexec /usr/local/bin/front-paneld\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon...\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/led-controld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/led-controld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nARGS=\"scm smb pim2 pim3 pim4 pim5 pim6 pim7 pim8 pim9 psu1 psu2 psu3 psu4 fan\"\n#shellcheck disable=SC2086\nexec /usr/local/bin/sensord $ARGS\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n#shellcheck disable=SC1091\nsource /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for ELBERT... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe lm90\nmodprobe max6697\nmodprobe pmbus\nmodprobe ucd9000\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttcsd trousers\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tcsd\n# Description:\t\ttcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n# shellcheck source=/dev/null\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo \"Starting $DESC: \"\n\n    # For ELBERT platform, it has separate TPM for BMC only - it's probed during\n    # BMC start up. So there is no need for additional device probe / addition\n\n    # Generate symlink for tcsd\n    rm -f /dev/tpm\n\t\tif [ -e /dev/tpm0 ]\n    then\n      ln -s /dev/tpm0 /dev/tpm\n    else\n      ln -s /dev/tpm1 /dev/tpm\n    fi\n\n\t\tstart-stop-daemon --start --quiet --oknodo --pidfile /var/run/\"${NAME}\".pid --user \"${USER}\" --chuid \"${USER}\" --exec \"${DAEMON}\" -- \"${DAEMON_OPTS}\"\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..5)]\" >&2\n}\n\nFCMCPLD=\"/sys/bus/i2c/drivers/fancpld/6-0060\"\n\nshow_pwm()\n{\n    pwm=\"$FCMCPLD/fan$1_pwm\"\n    val=\"$(head -n 1 \"$pwm\")\"\n    # Val is [0,255], so let's scale the value down to [0,100]\n    float_val=$(echo \"$val 100 * 255 / p\" | dc)\n    rounded=\"$(printf '%.*f' 0 \"$float_val\")\"\n    echo \"$rounded%\"\n}\n\nshow_rpm()\n{\n    rpm=\"$(head -n 1 \"$FCMCPLD\"/fan\"$1\"_input)\"\n    # Keep the output in the same format as Minipack\n    echo \"$rpm, $rpm\"\n}\n\nset -e\n\n# If user input is given, use it as FAN TRAY instance\n# Otherwise, read all\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 6 ]; then\n        echo \"Fan $1: Should be between 1 and 5\"\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    echo \"Fan $fan RPMs: $(show_rpm \"$fan\"), ($(show_pwm \"$fan\"))\"\ndone\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nif ! wedge_is_bmc_personality; then\n    echo \"uServer is not in BMC personality. Skipping all fan control\"\n    return\nfi\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\ndefault_fsc_config=\"/etc/fsc-config.json\"\n\nif ! wedge_is_bmc_personality; then\n    echo \"uServer is not in BMC personality. Skipping all fan control\"\n    return\nfi\n\nnum_pim16q=0\nnum_pim8ddm=0\n\npim_list=\"2 3 4 5 6 7 8 9\"\nfor pim in ${pim_list}; do\n     fru=\"$(peutil \"$pim\" 2>&1)\"\n     # PIM 16CD and 16CD2 are equivilant for FSCD\n     if echo \"$fru\" | grep -q '88-16CD'; then\n         num_pim16q=$((num_pim16q+1))\n     elif echo \"$fru\" | grep -q '88-8D'; then\n         num_pim8ddm=$((num_pim8ddm+1))\n     fi\ndone\n\nif [ $num_pim16q -eq 8 ]; then\n    # 8xPIM16Q\n    cp /etc/FSC-8-PIM16Q-config.json ${default_fsc_config}\nelif [ $num_pim16q -eq 5 ] && [ $num_pim8ddm -eq 3 ]; then\n    cp /etc/FSC-5-PIM16Q-3-PIM8DDM-config.json ${default_fsc_config}\nelif [ $num_pim16q -eq 2 ] && [ $num_pim8ddm -eq 6 ]; then\n    cp /etc/FSC-2-PIM16Q-6-PIM8DDM-config.json ${default_fsc_config}\nelse\n    # Assume highest power configuration otherwise\n    cp /etc/FSC-8-PIM8DDM-config.json ${default_fsc_config}\nfi\n\n# Create dummy sensors which host will write\necho 0 > /tmp/.PIM_QSFP200\necho 0 > /tmp/.PIM_QSFP400\necho 0 > /tmp/.PIM_F104\n\necho \"Setup fan speed...\"\n/usr/local/bin/set_fan_speed.sh 30\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 85}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# ELBERT fan set utility for fscd.\n\nusage() {\n  echo \"Usage: $0 <PWM_PERCENT> [FAN_TRAY] \"\n  echo \"<PWM_PERCENT> : From 0 to 100 \"\n  echo \"[FAN_TRAY] : 1, 2, 3, 4 or 5.\"\n  echo \"If no FAN_TRAY is specified, all FANs will be programmed\"\n}\n\nset -e\n\n# Make sure we only have 1 or 2 arguments\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# Also make sure that percent value is really between 0 and 100\nif [ \"$1\" -lt 0 ] || [ \"$1\" -gt 100 ]; then\n    echo \"PWM_PERCENT $1: should be between 0 and 100\"\n    exit 1\nfi\n\n# Read FAN_TRAY value from user argument.\n# If no FAN_TRAY is given, configure all FANs\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4 5\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 6 ]; then\n        echo \"Fan $2: should be between 1 and 5\"\n        exit 1\n    fi\n    FAN_UNIT=\"$2\"\nfi\n\n# Convert input (0-100%) to PWM (0-255)\n# Multiple by 2.5\nfloat_step=$(echo \"$1 255 * 100 / p\" | dc)\nstep=\"$(printf '%.*f' 0 \"$float_step\")\"\n\nfor unit in ${FAN_UNIT}; do\n    pwm=\"/sys/bus/i2c/drivers/fancpld/6-0060/fan${unit}_pwm\"\n    echo \"$step\" > \"${pwm}\"\n    echo \"$step will be set to ${pwm} !!!!\"\n    echo \"Successfully set fan ${unit} speed to $1%\"\ndone\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# led-controld looks for this file; if found, beacon LED will be on.\nBEACON_FILE=\"/tmp/.elbert_beacon\"\n\n# This enum is defined in led-controld.h; do not make changes here without\n# also updating that file.\nBEACON_MODE_OFF=-1\nBEACON_MODE_LOCATOR=0\nBEACON_MODE_NETSTATE=1\nBEACON_MODE_DRAINED=2\nBEACON_MODE_AUDIT=3\n\nbeacon_stoi() {\n     # Translate mode to int for file storage.\n     mode_str=$1\n     mode_int=\"$BEACON_MODE_OFF\"\n     case \"$mode_str\" in\n          locator)\n               mode_int=\"$BEACON_MODE_LOCATOR\"\n               ;;\n          netstate)\n               mode_int=\"$BEACON_MODE_NETSTATE\"\n               ;;\n          drained)\n               mode_int=\"$BEACON_MODE_DRAINED\"\n               ;;\n          audit)\n               mode_int=\"$BEACON_MODE_AUDIT\"\n               ;;\n          *)\n               usage\n               ;;\n     esac\n\n     echo \"$mode_int\"\n}\n\nbeacon_led_on() {\n     mode_str=$1\n\n     if [ -z \"$mode_str\" ]; then\n          mode_str=\"locator\"\n     fi\n\n     mode_int=$(beacon_stoi \"$mode_str\")\n     if [ -f \"$BEACON_FILE\" ]; then\n          curr_mode=$(<\"$BEACON_FILE\")\n          if [[ \"$mode_int\" == \"$curr_mode\" ]]; then\n               echo \"Beacon LED: already ON in $mode_str mode\"\n               exit 1\n          fi\n     fi\n\n     echo \"$mode_int\" > \"$BEACON_FILE\"\n     echo \"Beacon LED: now ON in $mode_str mode\"\n}\n\nbeacon_led_off() {\n     if [ ! -f \"$BEACON_FILE\" ]; then\n          echo \"Beacon LED: already OFF\"\n          exit 1\n     fi\n\n     rm -rf \"$BEACON_FILE\"\n     echo \"Beacon LED: now OFF\"\n}\n\nbeacon_led_status() {\n     # Print beacon status for every mode.\n     curr_mode=\"$BEACON_MODE_OFF\"\n     if [ -f \"$BEACON_FILE\" ]; then\n          curr_mode=$(<\"$BEACON_FILE\")\n     fi\n\n     for mode_str in locator netstate drained audit; do\n          mode_int=$(beacon_stoi \"$mode_str\")\n          if [[ \"$mode_int\" == \"$curr_mode\" ]]; then\n             echo \"$mode_str: ON\"\n          else\n             echo \"$mode_str: OFF\"\n          fi\n     done\n}\n\nusage() {\n     program=$(basename \"$0\")\n     echo \"Usage:\"\n     echo \"$program <on|off|status> [locator | netstate | drained | audit]\"\n     exit 1\n}\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n     on)\n          beacon_led_on \"$1\"\n          ;;\n     off)\n          beacon_led_off\n          ;;\n     status)\n          beacon_led_status\n          ;;\n     *)\n          usage\n          ;;\nesac\n", "num_lines": 128}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2012\n# shellcheck disable=SC2039\n. /usr/local/bin/openbmc-utils.sh\n\n# Check if another fw upgrade is ongoing\ncheck_fwupgrade_running\n\ntrap cleanup INT TERM QUIT EXIT\n\nSCM_SPI=\"spi1.0\"\nSCM_SPIDEV=\"spidev1.0\"\nSCM_MTD=\"\"\nABOOT_CONF_START=$((0x9FA000))\nFLASH_SIZE=$((0x1000000))\nABOOT_CONF_SIZE=$((0x5000))\nSECTION_BLOCK_SIZE=$((0x1000))\n\n# Temp files for storing bios file.\nTEMP_BIOS_IMAGE=\"/tmp/tmp_bios_image\"\n# Temp file for storing aboot_conf data\nTEMP_ABOOT_CONF=\"/tmp/aboot_conf.bin\"\n\nDEFAULT_ABOOT_CONF=\"BOOT_METHOD1=IPV6_PXE,BOOT_METHOD2=LOCAL,BOOT_METHOD3=ARISTA\"\n\ncleanup() {\n    disconnect_spi\n    rm -f $TEMP_ABOOT_CONF $TEMP_BIOS_IMAGE\n}\n\nbind_spi_nor() {\n    # Unbind spidev\n    if [ -e /dev/\"$SCM_SPIDEV\" ]; then\n        echo \"$SCM_SPI\" > /sys/bus/spi/drivers/spidev/unbind\n    fi\n\n    # Bind\n    echo spi-nor  > /sys/bus/spi/devices/\"$SCM_SPI\"/driver_override\n    if [ ! -e /sys/bus/spi/drivers/spi-nor/\"$SCM_SPI\" ]; then\n        echo Binding \"$SCM_SPI\" to ...\n        echo \"$SCM_SPI\" > /sys/bus/spi/drivers/spi-nor/bind\n        sleep 0.5\n    fi\n    SCM_MTD=\"$(grep \"$SCM_SPI\" /proc/mtd |awk '{print$1}' | tr -d : | tr -d mtd)\"\n    if test -z \"$SCM_MTD\"; then\n        echo \"Failed to locate mtd partition for SPI Flash!\"\n        exit 1\n    fi\n}\n\nunbind_spi_nor() {\n    # Method for unloading spi-nor driver dynamically back to spidev\n    echo > /sys/bus/spi/devices/\"$SCM_SPI\"/driver_override\n    if grep \"$SCM_SPI\" /proc/mtd > /dev/null 2>&1 ; then\n        echo \"Unbinding spi-nor from $SCM_SPI\"\n        echo \"$SCM_SPI\" > /sys/bus/spi/drivers/spi-nor/unbind\n    fi\n    if [ ! -e /dev/\"$SCM_SPIDEV\" ]; then\n        echo \"Binding spidev back to $SCM_SPI\"\n        echo \"$SCM_SPI\" > /sys/bus/spi/drivers/spidev/bind\n    fi\n}\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <OP> <bios file>\"\n    echo \"      <OP> : read, write, erase, verify\"\n    exit 1\n}\n\ndisconnect_spi() {\n    # connect through CPLD\n    echo 0x0 > \"${SCMCPLD_SYSFS_DIR}\"/bios_select\n    # Set GPIOV0 to 0 (default GPIO state)\n    gpio_set_value BMC_SPI1_CS0_MUX_SEL 0\n    unbind_spi_nor\n}\n\nconnect_spi() {\n    # Set GPIOV0 to 0\n    gpio_set_value BMC_SPI1_CS0_MUX_SEL 0\n    # connect through CPLD\n    echo 0x1 > \"${SCMCPLD_SYSFS_DIR}\"/bios_select\n    bind_spi_nor\n}\n\nconnect_spi\n\nread_flash() {\n    echo \"Reading flash content...\"\n    flashrom -f -p linux_mtd:dev=\"$SCM_MTD\" -r \"$1\" || return 1\n    sleep 1\n    echo \"Verifying flash content...\"\n    flashrom -f -p linux_mtd:dev=\"$SCM_MTD\" -v \"$1\" || return 1\n    return 0\n}\n\ncreate_bios_image() {\n    start_block=\"$(($1 / SECTION_BLOCK_SIZE))\"\n    num_blocks=\"$(($2 / SECTION_BLOCK_SIZE))\"\n    rm -f \"$TEMP_BIOS_IMAGE\"\n    dd if=\"$3\" of=\"$TEMP_BIOS_IMAGE\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$start_block\" \\\n       2> /dev/null\n    dd if=\"$4\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$num_blocks\" >> \"$TEMP_BIOS_IMAGE\" \\\n       2> /dev/null\n    end_blocks=$(( (FLASH_SIZE / SECTION_BLOCK_SIZE) - start_block - num_blocks ))\n    dd if=\"$3\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$end_blocks\" skip=$((start_block + num_blocks)) \\\n       >> \"$TEMP_BIOS_IMAGE\" 2> /dev/null\n}\n\ncreate_aboot_conf() {\n    echo \"Using Aboot conf: $1\"\n\n    nvs=\"$1,\"\n\n    rm -f \"$TEMP_ABOOT_CONF\"\n    touch \"$TEMP_ABOOT_CONF\"\n    while [ -n \"${nvs%%,*}\" ]; do\n        nv=\"${nvs%%,*}\"\n        name=\"${nv%%=*}\"\n        if [ \"$name\" = \"$nv\" ]; then\n            echo \"Invalid name-value argument $nv\" >&2\n            return 1\n        fi\n        echo -n \"${nv%%=*}=\" >> \"$TEMP_ABOOT_CONF\"\n        echo -n \"${nv#*=}\" | base64 >> \"$TEMP_ABOOT_CONF\"\n        nvs=\"${nvs#*,}\"\n    done\n\n    size=\"$(ls -l \"$TEMP_ABOOT_CONF\" | awk '{print $5}')\"\n    pad_size=\"$((ABOOT_CONF_SIZE - size))\"\n    dd if=/dev/zero bs=1 count=\"$pad_size\" >> \"$TEMP_ABOOT_CONF\" 2> /dev/null\n}\n\naboot_version() {\n    grep -a CONFIG_LOCALVERSION \"$1\" 2> /dev/null | awk -F'\"' '{print $2}'\n}\n\nif [ \"$1\" = \"erase\" ]; then\n    echo \"Erasing flash content ...\"\n    flashrom -f -p linux_mtd:dev=\"$SCM_MTD\" -E || exit 1\nelif [ \"$1\" = \"read\" ]; then\n    retry_command 5 read_flash \"$2\" || exit 1\nelif [ \"$1\" = \"verify\" ]; then\n    bios_image=\"$2\"\n    if [ -n \"$(aboot_version \"$bios_image\")\" ]; then\n        create_aboot_conf \"$DEFAULT_ABOOT_CONF\" || exit 1\n        create_bios_image \"$ABOOT_CONF_START\" \"$ABOOT_CONF_SIZE\" \\\n                          \"$bios_image\" \"$TEMP_ABOOT_CONF\" || exit 1\n        bios_image=\"$TEMP_BIOS_IMAGE\"\n    fi\n    echo \"Verifying flash content...\"\n    flashrom -f -p linux_mtd:dev=\"$SCM_MTD\" -v \"$bios_image\" || exit 1\nelif [ \"$1\" = \"write\" ]; then\n    bios_image=\"$2\"\n    if [ -n \"$(aboot_version \"$bios_image\")\" ]; then\n        create_aboot_conf \"$DEFAULT_ABOOT_CONF\" || exit 1\n        create_bios_image \"$ABOOT_CONF_START\" \"$ABOOT_CONF_SIZE\" \\\n                          \"$bios_image\" \"$TEMP_ABOOT_CONF\" || exit 1\n        bios_image=\"$TEMP_BIOS_IMAGE\"\n    fi\n    echo \"Writing flash content...\"\n    retry_command 5 flashrom -n -f -p linux_mtd:dev=\"$SCM_MTD\" -w \"$bios_image\" || exit 1\n    sleep 1\n    echo \"Verifying flash content...\"\n    # Retry verification up to 5 times\n    retry_command 5 flashrom -f -p linux_mtd:dev=\"$SCM_MTD\" -v \"$bios_image\" || exit 1\nelse\n    usage\nfi\n", "num_lines": 174}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Read AST2620 register SCU014 [23:16] to retrieve the board hardware revision.\n\nSCU014_REG=0x1e6e2014\nHW_REV_BIT=16\nBOARD_REV=$(($(($(devmem \"${SCU014_REG}\") >> \"${HW_REV_BIT}\")) & 0xff))\necho \"BMC Board Revision: A${BOARD_REV}\"\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2020-present Facebook. All Rights Reserved.\n\n# shellcheck disable=SC2034\n\nSCMCPLD_SYSFS_DIR=\"$(i2c_device_sysfs_abspath 12-0043)\"\nSMBCPLD_SYSFS_DIR=\"$(i2c_device_sysfs_abspath 4-0023)\"\nFANCPLD_SYSFS_DIR=\"$(i2c_device_sysfs_abspath 6-0060)\"\nSCM_PWR_ON_SYSFS=\"${SCMCPLD_SYSFS_DIR}/cpu_control\"\nSCM_SMB_POWERGOOD_SYSFS=\"${SCMCPLD_SYSFS_DIR}/switchcard_powergood\"\nPWR_SYSTEM_SYSFS=\"${SCMCPLD_SYSFS_DIR}/chassis_power_cycle\"\nSMB_TH4_RST_ON_SYSFS=\"${SMBCPLD_SYSFS_DIR}/th4_reset\"\nSMB_TH4_PCI_RST_ON_SYSFS=\"${SMBCPLD_SYSFS_DIR}/th4_pci_reset\"\nSMB_TH4_I2C_EN_SYSFS=\"${SMBCPLD_SYSFS_DIR}/th4_i2c_bsc2_en\"\nSMB_FULL_POWER_SYSFS=\"${SMBCPLD_SYSFS_DIR}/smb_power_en\"\nPIM_SMB_MUX_RST=\"${SMBCPLD_SYSFS_DIR}/pim_smb_mux_rst\"\nPSU_SMB_MUX_RST=\"${SMBCPLD_SYSFS_DIR}/psu_smb_mux_rst\"\nSMB_P1_DETECT_PATH=\"/tmp/.smb_p1_board\"\nSMB_P2_DETECT_PATH=\"/tmp/.smb_p2_board\"\nDS4520_BUS=8\nDS4520_DEV=$(( 0x50 ))\nDS4520_IO0_REG=0xf2\nUCD_SECURITY_REG=0xf1\nWRITE_PROTECT_REG=0x10\n\nwedge_iso_buf_enable() {\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    return 0\n}\n\nwedge_is_bmc_personality() {\n    io_reg_val=$(i2cget -y $DS4520_BUS $DS4520_DEV $DS4520_IO0_REG)\n    if [ \"$((io_reg_val & 0x1))\" = \"0\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nwedge_is_smb_p1() {\n    # Check if we previously detected P1/P2 SMB\n    if [ -f \"$SMB_P1_DETECT_PATH\" ]; then\n        return 0\n    elif [ -f \"$SMB_P2_DETECT_PATH\" ]; then\n        return 1\n    fi\n    # Read SMB eeprom to determine if P1/P2\n    if weutil smb | grep -q 'PCA014590[1|5]0[1|5|6]'; then\n        touch \"$SMB_P1_DETECT_PATH\"\n        return 0\n    else\n        touch \"$SMB_P2_DETECT_PATH\"\n        return 1\n    fi\n}\n\nwedge_is_us_on() {\n    isWedgeOn=\"$(head -n 1 \"$SCM_PWR_ON_SYSFS\" 2> /dev/null)\"\n    if [ -z \"$isWedgeOn\" ]; then\n        return 1\n    elif [ \"$isWedgeOn\" = \"0x1\" ]; then\n        return 0 # uServer is on\n    else\n        return 1\n    fi\n}\n\nwedge_is_smb_powergood() {\n    isPowerGood=\"$(head -n 1 \"$SCM_SMB_POWERGOOD_SYSFS\" 2> /dev/null)\"\n    if [ -z \"$isPowerGood\" ]; then\n        return 1\n    elif [ \"$isPowerGood\" = \"0x1\" ]; then\n        return 0 # Power is good\n    else\n        return 1\n    fi\n}\n\nwedge_board_type() {\n    echo 'ELBERT'\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    # Assume P1\n    return 1\n}\n\nwedge_should_enable_oob() {\n    return 1\n}\n\nwedge_pim_bus() {\n   # $1 -  pim range 2 - 9\n   pim=\"$1\"\n\n   # PIM SMBus 16-23\n   pim_index=(0 1 2 3 4 5 6 7)\n   pim_bus=(16 17 18 19 20 21 22 23)\n   if wedge_is_smb_p1; then\n       # P1 has different PIM bus mapping\n       pim_bus=(16 17 18 23 20 21 22 19)\n   fi\n   echo \"${pim_bus[$((pim-2))]}\"\n}\n\nwedge_is_pim_present() {\n   # $1 -  pim range 2 - 9\n   pim=\"$1\"\n\n   busId=$(wedge_pim_bus \"$pim\")\n   pim_prsnt=\"$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$pim\"_present)\"\n   if [ \"$((pim_prsnt))\" -eq 1 ]; then\n      return 0\n   prsnt_i2c=\"$(i2cget -f -y \"$busId\" 0x50 >/dev/null 2>&1 && echo 1 || echo 0)\"\n   elif [ \"$((prsnt_i2c))\" -eq 1 ]; then\n      # PIM Eeprom found but PIM present bit is incorrect\n      echo \"PIM$pim present is false but eeprom detected.\"\n      return 0\n   fi\n   return 1\n}\n\nwedge_pim_type() {\n   pim=\"$1\"\n\n   busId=$(wedge_pim_bus \"$pim\")\n   pim_type=$(/usr/bin/kv get pim\"$pim\"_type)\n   echo \"$pim_type\"\n}\n\nwedge_power_off_asic() {\n    # ASIC put into reset\n    echo 1 > \"$SMB_TH4_RST_ON_SYSFS\"\n    echo 1 > \"$SMB_TH4_PCI_RST_ON_SYSFS\"\n    # Turn off power to ASIC\n    echo 0 > \"$SMB_FULL_POWER_SYSFS\"\n}\n\nwedge_power_on_asic() {\n    # Enable power to asic\n    echo 1 > \"$SMB_FULL_POWER_SYSFS\"\n    sleep 1\n\n    if wedge_is_smb_powergood; then\n        echo \"Switchcard power is good...\"\n    else\n        echo \"FATAL ERROR: Switchcard power signal is NOT good.\"\n    fi\n\n    # Take ASIC out of reset. Order matters here\n    echo 0 > \"$SMB_TH4_RST_ON_SYSFS\"\n    usleep 250000\n    echo 0 > \"$SMB_TH4_PCI_RST_ON_SYSFS\"\n}\n\nwedge_power_on_board() {\n    wedge_power_off_asic\n    wedge_power_on_asic\n    echo 1 > \"$SCM_PWR_ON_SYSFS\"\n}\n\nwedge_power_off_board() {\n    wedge_power_off_asic\n    echo 0 > \"$SCM_PWR_ON_SYSFS\"\n}\n\nmaybe_set_security_bitmask() {\n    bus=\"$1\"\n    dev=\"$2\"\n    model=\"$3\"\n\n    if [[ \"$model\" == *\"UCD9090\"* ]]\n    then\n        # A 0 bit indicates the command is not write protected.\n        # Each bit represents a command code where the codes\n        # increment left to right. eg. byte 0, bit 7 = 00,\n        # byte 0, bit 6 = 01, etc.\n        #\n        # The following commands are allowed:\n        #   00       - PAGE\n        #   03       - CLEAR_FAULTS\n        #   D7       - RUN_TIME_CLOCK\n        #   EA-ED,EF - FAULT commands\n        #   F0       - EXECUTE_FLASH\n        #   F1       - SECURITY\n        #   F2       - SECURITY_BIT_MASK\n        #   FA       - GPIO SELECT\n        #   FB       - GPIO CONFIG\n        #   FC       - MISC CONFIG\n        i2cset -f -y \"$bus\" \"$dev\" 0xf2 \\\n           0x6f 0xff 0xff 0xff 0xff 0xff 0xff 0xff \\\n           0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff \\\n           0xff 0xff 0xff 0xff 0xff 0xff 0xff 0xff \\\n           0xff 0xff 0xfe 0xff 0xff 0xc2 0x1f 0xc7 s\n    #else\n    #    Model does not support security bitmask, so treat as no-op\n    fi\n}\n\nenable_power_security_mode() {\n    bus=\"$1\"\n    dev=\"$2\"\n    model=\"$3\"\n\n    # Some UCD models support a security bitmask\n    maybe_set_security_bitmask \"$bus\" \"$dev\" \"$model\"\n\n    locked=\"$(printf \"%d\" \"$(i2cget -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" s | awk '{print $(NF)}')\")\"\n    if [ \"$locked\" -eq 0 ]; then\n        # Write a new 6-byte password, enabling security\n        i2cset -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" 0x06 0x31 0x32 0x33 0x34 0x35 0x36 i\n        locked=\"$(printf \"%d\" \"$(i2cget -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" s | awk '{print $(NF)}')\")\"\n        if [ \"$locked\" -eq 0 ]; then\n            echo \"Failed to lock $model $bus-00$dev\"\n            return 1\n        fi\n    else\n        echo \"UCD bus $bus device $dev already locked!\"\n        return 0\n    fi\n}\n\ndisable_power_security_mode() {\n    bus=\"$1\"\n    dev=\"$2\"\n    model=\"$3\"\n\n    # If locked, unlock it\n    locked=\"$(printf \"%d\" \"$(i2cget -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" s | awk '{print $(NF)}')\")\"\n    if [ \"$locked\" -eq 0 ]; then\n        echo \"UCD bus $bus device $dev already unlocked!\"\n        return 0\n    else\n        # If security is enabled, disable security by writing the correct password\n        i2cset -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" 0x06 0x31 0x32 0x33 0x34 0x35 0x36 i\n        # Make the security disable permanent. Otherwise a subsequent STORE_DEFAULT_ALL command\n        # will persist the security setting.\n        i2cset -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" 0x06 0xff 0xff 0xff 0xff 0xff 0xff i\n        locked=\"$(printf \"%d\" \"$(i2cget -f -y \"$bus\" \"$dev\" \"$UCD_SECURITY_REG\" s | awk '{print $(NF)}')\")\"\n        if [ \"$locked\" -eq 0 ]; then\n            return 0\n        else\n           echo \"Failed to lock $model $bus-00$dev\"\n           return 1\n        fi\n    fi\n}\n\nenable_tps546d24_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    # Disable all writes except for WRITE_PROTECT and STORE_USER_ALL\n    i2cset -f -y \"$bus\" \"$dev\" \"$WRITE_PROTECT_REG\" 0x80\n}\n\ndisable_tps546d24_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    # Enable all writes\n    i2cset -f -y \"$bus\" \"$dev\" \"$WRITE_PROTECT_REG\" 0x0\n}\n\n# Not all PIMs have the ISL68224. Calling this for a PIM\n# without one is a no-op.\nmaybe_enable_isl_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    devhex=$(printf \"%02x\" \"$dev\")\n    if [ ! -e /sys/bus/i2c/devices/\"$bus\"-00\"$devhex\" ]\n    then\n        return 0\n    fi\n    \n    # Disable all writes except for WRITE_PROTECT, OPERATION, and PAGE\n    i2cset -f -y \"$bus\" \"$dev\" \"$WRITE_PROTECT_REG\" 0x40\n}\n\nmaybe_disable_isl_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    devhex=$(printf \"%02x\" \"$dev\")\n    if [ ! -e /sys/bus/i2c/devices/\"$bus\"-00\"$devhex\" ]\n    then\n        return 0\n    fi\n    \n    # Enable all writes\n    i2cset -f -y \"$bus\" \"$dev\" 0x10 0x0\n}\n\nenable_switchcard_power_security() {\n    retry_command 3 enable_power_security_mode 3 0x4e \"UCD90160B\"\n    retry_command 3 maybe_enable_isl_wp 3 0x60\n    retry_command 3 maybe_enable_isl_wp 3 0x62\n}\n\ndisable_switchcard_power_security() {\n    retry_command 3 disable_power_security_mode 3 0x4e \"UCD90160B\"\n    retry_command 3 maybe_disable_isl_wp 3 0x60\n    retry_command 3 maybe_disable_isl_wp 3 0x62\n}\n\nenable_psu_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    # Disable all writes except for WRITE_PROTECT, OPERATION, and PAGE\n    i2cset -f -y \"$bus\" \"$dev\" \"$WRITE_PROTECT_REG\" 0x40\n}\n\ndisable_psu_wp() {\n    bus=\"$1\"\n    dev=\"$2\"\n\n    # Enable all writes\n    i2cset -f -y \"$bus\" \"$dev\" \"$WRITE_PROTECT_REG\" 0x0\n}\n\npower_on_pim() {\n    pim=$1\n    old_rst_value=$(gpio_get PIM\"${pim}\"_FPGA_RESET_L keepdirection)\n    if [ \"$old_rst_value\" -eq 1 ]; then\n       # already powered on, skip\n       return\n    fi\n\n    # Skip power_on if we are still powercycling\n    if [ \"$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim_reset)\" != '0x0' ]; then\n        logger pim_enable: skipping power_on_pim. PIM\"$pim\" is still powercycling\n        return\n    fi\n\n    # Skip power_on if the FPGA is still being programmed\n    pim_major=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$pim\"_fpga_rev_major)\n    if [ \"$((pim_major))\" -eq 255 ]; then\n        logger pim_enable: skipping power_on_pim. PIM\"$pim\" is fpga loading is not complete\n        return\n    fi\n\n    fpga_done_value=$(gpio_get PIM\"${pim}\"_FPGA_DONE keepdirection)\n    if [ \"$fpga_done_value\" -eq 0 ]; then\n        logger pim_enable: skipping power_on_pim. PIM\"$pim\" is FPGA_DONE is not ready\n        return\n    fi\n\n    sleep 0.5 # Give FPGA some time to finish initialization\n    bus=$(wedge_pim_bus \"$pim\")\n    dev=\"0x4e\"\n    gpio_set PIM\"${pim}\"_FPGA_RESET_L 1  # FPGA out of reset\n\n    logger pim_enable: Locking PIM\"$pim\" UCD9090B security\n    retry_command 3 enable_power_security_mode \"$bus\" \"$dev\" \"UCD9090B\"\n\n    logger pim_enable: Enable WRITE_PROTECT on PIM\"$pim\" TPS/ISL chips\n    retry_command 3 enable_tps546d24_wp \"$bus\" 0x16\n    retry_command 3 enable_tps546d24_wp \"$bus\" 0x18\n    retry_command 3 maybe_enable_isl_wp \"$bus\" 0x54\n\n    sleep 0.1\n\n    skip_pim_off_cache=$2\n    pim_off_cache=\"/tmp/.pim${pim}_powered_off\"\n    if [ -z \"${skip_pim_off_cache}\" ] && [ -f \"${pim_off_cache}\" ]; then\n       rm  \"${pim_off_cache}\"\n    fi\n    logger pim_enable: powered on PIM\"${pim}\"\n}\n\npower_off_pim() {\n    pim=$1\n    old_rst_value=$(gpio_get PIM\"${pim}\"_FPGA_RESET_L keepdirection)\n    if [ \"$old_rst_value\" -eq 0 ]; then\n       # already powered off, skip\n       return\n    fi\n\n    bus=$(wedge_pim_bus \"$pim\")\n    dev=\"0x4e\"\n    gpio_set PIM\"${pim}\"_FPGA_RESET_L 0  # FPGA in of reset\n    sleep 0.1\n\n    skip_pim_off_cache=$2\n    pim_off_cache=\"/tmp/.pim${pim}_powered_off\"\n    if [ -z \"${skip_pim_off_cache}\" ]; then\n       touch \"${pim_off_cache}\"\n    fi\n    logger pim_enable: powered off PIM\"${pim}\"\n}\n\nretry_command() {\n    # Retry command up to $1 attempts\n    local retries=$1\n    shift\n\n    local count=0\n    until \"$@\"; do\n        exit=$?\n        count=$((count+1))\n        if [ \"$count\" -lt \"$retries\" ]; then\n            msg=\"Attempt $count/$retries failed with $exit, retrying...\"\n            echo \"$msg\"\n            logger retry_command: \"$msg\"\n        else\n            msg=\"Retry $count/$retries failed with $exit, no more retries left\"\n            echo \"$msg\"\n            logger retry_command: \"$msg\"\n            return $exit\n        fi\n    done\n    return 0\n}\n\nFWUPGRADE_PIDFILE=\"/var/run/firmware_upgrade.pid\"\ncheck_fwupgrade_running()\n{\n    exec 200>$FWUPGRADE_PIDFILE\n    flock -n 200 || (echo \"Another FW upgrade is running\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 1\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n", "num_lines": 437}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nfunction dpe_status(){\n  regVal=\"$1\"\n  dpeResultStr=\"$2\"\n  if [ \"$(head -n 1 /sys/bus/i2c/drivers/scmcpld/12-0043/dpe_image)\" != \"$regVal\" ];\n  then\n    echo \"${dpeResultStr} image detected. exiting...\"\n    exit 1\n  fi\n}\n\ncase \"$1\" in\n    dpe)\n        dpe_status \"0x1\" \"dpe image\"\n        ;;\n    nondpe)\n        dpe_status \"0x0\" \"non dpe image\"\n        ;;\nesac\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/dpm_utils.sh\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nlogfile=\"/mnt/data1/log/dpm_log\"\nlogfile_old=\"${logfile}.1\"\nmax_loglines=1000\nswitchcard_bus=3\n\n# Check to see if the log file needs to be rotated\ntouch $logfile $logfile_old\nlines=\"$(wc -l $logfile|cut -d' ' -f1)\"\nif [ \"$lines\" -gt $max_loglines ]\nthen\n    echo \"Rotating DPM log file\"\n    rm -f \"$logfile_old\"\n    cp \"$logfile\" \"$logfile_old\"\n    rm -f \"$logfile\"\nfi\n\necho \"Reading DPM logs...\"\nread_logs \"$switchcard_bus\" \"SWITCHCARD\" >> \"$logfile\"\n\n# The UCD90160B does not support a security bitmask. Disable\n# security in order to update the clock. Security will be\n# re-enabled later in the boot.\nretry_command 3 disable_power_security_mode 3 0x4e \"UCD90160B\"\nupdate_clock \"$switchcard_bus\"\n# For the switchcard UCD90160B, there are 18 bytes to clear\necho \"Clearing SWITCHCARD DPM logs...\"\ni2cset -y 3 0x4e 0xea 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 s\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\ndpm_verbose=\"no\"\nprint_debug() {\n    if [ \"$dpm_verbose\" = \"yes\" ]\n    then\n        echo \"$*\" >&2\n    fi\n}\n\nread_logs() {\n    local bus=\"$1\"\n    local fault_source=\"$2\"\n    dpm_path=\"/sys/bus/i2c/drivers/ucd9000/$bus-004e\"\n\n    if [ -d \"$dpm_path\" ]; then\n        echo \"Script cannot run while driver present\" >&2\n        echo \"Use the following commands to unbind/rebind\" >&2\n        echo 'echo \"'\"$bus\"'-004e\" > /sys/bus/i2c/drivers/ucd9000/unbind' >&2\n        echo 'echo \"'\"$bus\"'-004e\" > /sys/bus/i2c/drivers/ucd9000/bind' >&2\n        exit 1\n    fi\n\n    print_debug \"Reading $fault_source DPM logs...\"\n\n    echo -n \"{'Date':'$(date -u \"+%Y-%m-%d %T\")'\"\n    echo -n \",'Source':'$fault_source'\"\n    echo -n \",'Log':'$(i2cget -y \"$bus\" 0x4e 0xea s)'\"\n\n    eb=\"$(i2cget -y \"$bus\" 0x4e 0xeb w)\"\n\n    len=\"$((0x${eb:2:2}))\"\n\n    for (( i = 0 ; i < \"$len\" ; i++ ))\n    do\n      i2cset -y \"$bus\" 0x4e 0xeb \"0x$len$(printf '%02x' \"$i\")\" w\n      man=\"$(i2cget -y \"$bus\" 0x4e 0xec s)\"\n      exp=\"$(i2cget -y \"$bus\" 0x4e 0x20 | tail -n 1)\"\n      echo -n \",'detail_$i':{'m':'$man','e':'$exp'}\"\n    done\n\n    echo \"}\"\n}\n\nupdate_clock() {\n    local bus=\"$1\"\n\n    # Make sure the time set set correctly on the DPM\n    seconds=\"$(date +%s)\"\n    seconds_per_day=\"$((24 * 60 * 60))\"\n    days=\"$((seconds / seconds_per_day))\"\n    milliseconds=\"$((seconds % seconds_per_day * 1000))\"\n    d1=\"$((days >> 24))\"\n    d2=\"$((days >> 16 & 0xff))\"\n    d3=\"$((days >> 8 & 0xff))\"\n    d4=\"$((days & 0xff))\"\n    m1=\"$((milliseconds >> 24))\"\n    m2=\"$((milliseconds >> 16 & 0xff))\"\n    m3=\"$((milliseconds >> 8 & 0xff))\"\n    m4=\"$((milliseconds & 0xff))\"\n\n    print_debug \"$fault_source: updating run time clock on DPM\"\n    i2cset -y \"$bus\" 0x4e 0xd7 \"$m1\" \"$m2\" \"$m3\" \"$m4\" \"$d1\" \"$d2\" \"$d3\" \"$d4\" s\n}\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nshow_dpm_ver() {\n  name=$1\n  bus=$2\n  addr=$3\n  dump=$(i2cdump -f -y \"${bus}\" \"${addr}\" s 0x9e | grep -v abcdef)\n  dpm_ver=\"${dump##* }\"\n  echo \"$name\" \"$dpm_ver\"\n}\necho \"!!!\"\necho \"!!! WARNING: Displaying Digital Power Manager (DPM) version may disrupt sensor reading !!!\"\necho \"!!!\"\n\nscm_dpm_bus='9'\nscm_dpm_addr='0x11'\nsmb_dpm_bus='3'\nsmb_dpm_addr='0x4e'\n\nshow_dpm_ver \"SCM.:\" \"$scm_dpm_bus\" \"$scm_dpm_addr\"\nshow_dpm_ver \"SMB.:\" \"$smb_dpm_bus\" \"$smb_dpm_addr\"\n\n# PIM DPM\npim_index=(0 1 2 3 4 5 6 7)\n# This is a map between PIM2-9 to associated i2c BUS\n# Currently, this doesn't map in order between PIM2-9 to bus 16-23\npim_bus=(16 17 18 19 20 21 22 23)\nif wedge_is_smb_p1; then\n    # P1 has different PIM bus mapping\n    pim_bus=(16 17 18 23 20 21 22 19)\nfi\npim_dpm_addr='0x4e'\n\nfor i in \"${pim_index[@]}\"\ndo\n    pim=$((i+2))\n    # PIM numbered 2-9\n    pim=$((i+2))\n    if wedge_is_pim_present \"$pim\"; then\n        pim_type=$(wedge_pim_type \"$pim\")\n        if [[ \"$pim_type\" == \"16q2\" ]]; then\n            echo \"PIM${pim} has no DPM...\"\n        else\n            # PIM 2-9, SMBUS 16-23\n            bus_id=\"${pim_bus[$i]}\"\n            show_dpm_ver \"PIM${pim}.:\" \"$bus_id\" \"$pim_dpm_addr\"\n        fi\n    else\n        echo \"PIM${pim} not present... skipping.\"\n    fi\ndone\n\nshow_isl_ver() {\n  name=\"$1\"\n  bus=\"$2\"\n  addr=\"$3\"\n\n  mdl=$(i2cdump -f -y \"${bus}\" \"${addr}\" s 0x9a | grep 00: | awk '{print $5$4$3$2}')\n  mfr=$(i2cdump -f -y \"${bus}\" \"${addr}\" s 0x9b | grep 00: | awk '{print $5$4$3$2}')\n  rstr=\"SFT${mdl:1:5}${mdl:6:2}$(printf \"%02d\" \"0x$mfr\")\"\n  echo \"$name: $rstr\"\n}\n\n# ISL68226 Revision\nshow_isl_ver \"SMB ISL68226\" 3 0x62\n\n# RAA228228 Revision\nshow_isl_ver \"SMB RAA228228\" 3 0x60\n\n# PIM ISL Revision\npim_isl_addr='0x54'\nfor i in \"${pim_index[@]}\"\ndo\n    pim=$((i+2))\n    pim_type=$(wedge_pim_type \"$pim\")\n    if [[ \"$pim_type\" == \"8ddm\" ]]; then\n        bus_id=\"${pim_bus[$i]}\"\n        show_isl_ver \"PIM${pim} ISL68224\" \"$bus_id\" \"$pim_isl_addr\"\n    elif [[ \"$pim_type\" == \"16q2\" ]]; then\n        echo \"PIM${pim} has no ISL... skipping.\"\n    elif [[ \"$pim_type\" == \"16q\" ]]; then\n        echo \"PIM${pim} has no ISL... skipping.\"\n    elif [[ \"$pim_type\" == \"unplug\" ]]; then\n        echo \"PIM${pim} not present... skipping.\"\n    fi\ndone\n\necho \"!!! Done.\"\n", "num_lines": 92}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprintf \"%-1s | %-3s | %-30s\\n\" \"v\" \"dir\" \"GPIONAME\"\nfor i in /tmp/gpionames/*\ndo\n   gpio=\"$(basename \"$i\")\"\n   val=\"$(gpio_get_value \"$gpio\")\"\n   direction=\"$(gpio_get_direction \"$gpio\")\"\n   printf \"%-1s | %-3s | %-30s\\n\" \"$val\" \"$direction\" \"$gpio\"\ndone\n", "num_lines": 14}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nfor index in 2 3 4 5 6 7 8 9\ndo\n    pim_prsnt=\"$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$index\"_present)\"\n    cache_file=/tmp/pim\"$index\"_serial.txt\n\n    if [ ! -s \"$cache_file\" ] || [ -z \"$(cat $cache_file)\" ]; then\n        if [ \"$((pim_prsnt))\" -eq 1 ]; then\n            /usr/bin/weutil pim\"$index\" |grep Product|grep Serial|cut -d ' ' -f 4 > \"$cache_file\"\n        else\n            echo '' > \"$cache_file\"\n        fi\n    fi\n    serial=\"$(cat $cache_file)\"\n    echo PIM${index} : \"$serial\"\ndone\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# get the MAC from Elbert SCM EEPROM\nmac_base=$(weutil scm | grep '^Extended MAC Base' | cut -d' ' -f4)\n\n# get the MAC from u-boot environment\nethaddr=$(fw_printenv ethaddr | cut -d'=' -f2)\n\nif [ -z \"$mac_base\" ]; then\n    echo \"No MAC Base programmed in EEPROM!\"\n    if [ -n \"$ethaddr\" ]; then\n        echo \"Using U-boot ethaddr for mac.\"\n        mac=\"$ethaddr\"\n    fi\nelse\n    # Increment MAC BASE as our MAC should be BASE + 1\n    # Convert MAC Base to Decimal\n    mac_base_hex=$(echo \"$mac_base\" |  tr '[:lower:]' '[:upper:]' | tr -d ':')\n    mac_dec=$(printf '%d\\n' 0x\"$mac_base_hex\")\n    # Add 1 to MAC Base\n    mac_dec=$((mac_dec + 1))\n    # Convert base to MAC format\n    mac_hex=$(printf '%X\\n' \"$mac_dec\")\n    mac=$(echo \"$mac_hex\" | sed 's/../&:/g;s/:$//')\nfi\n\nif [ -n \"$mac\" ]; then\n    ifconfig eth0 hw ether \"$mac\"\nelse\n    # No MAC from either EEPROM or u-boot, use whatever was assigned by kernel\n    mac=$(ifconfig eth0 | grep HWaddr | awk '{ print $5 }')\nfi\n\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    # Set the MAC from EEPROM or ifconfig back to u-boot environment\n    # so that u-boot can use it\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2012\n# shellcheck disable=SC2034\n. /usr/local/bin/openbmc-utils.sh\n\nCPLD_JTAG_SEL_L=\"CPLD_JTAG_SEL_L\"\nJTAG_TRST_L=\"JTAG_TRST_L\"\nSCM_FPGA_LATCH_L=\"SCM_FPGA_LATCH_L\"\nJTAG_EN=\"${SCMCPLD_SYSFS_DIR}/jtag_en\"\nPROGRAM_SEL=\"${SCMCPLD_SYSFS_DIR}/program_sel\"\nSPI_CTRL=\"${SMBCPLD_SYSFS_DIR}/spi_ctrl\"\nSPI_PIM_SEL=\"${SMBCPLD_SYSFS_DIR}/spi_pim_en\"\nSPI_TH4_QSPI_SEL=\"${SMBCPLD_SYSFS_DIR}/spi_th4_qspi_en\"\nJTAG_CTRL=\"${SMBCPLD_SYSFS_DIR}/jtag_ctrl\"\nSMB_SPIDEV=\"spidev1.1\"\nSMB_SPI=\"spi1.1\"\nSMB_MTD=\"\"\n\nSCM_PROGRAM=false\nSMB_PROGRAM=false\nCACHED_SCM_PWR_ON_SYSFS=\"0x1\"\n\n# Temporary path for 32MB read\nTEMP_SPI_IMAGE=\"/tmp/tmp_spi_image\"\n\n# Check if another fw upgrade is ongoing\ncheck_fwupgrade_running\n\ntrap cleanup INT TERM QUIT EXIT\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <fpga> <action> <fpga file>\"\n    echo \"      <fpga> : scm, smb, smb_cpld, fan, th4_qspi,\"\n    echo \"               pim, pim_base, pim16q, pim8ddm\"\n    echo \"      <action> : program, verify, erase (spi only)\"\n    exit 1\n}\n\ncleanup() {\n    disconnect_program_paths\n    rm -f $TEMP_SPI_IMAGE\n}\n\ndisconnect_program_paths() {\n    # Return values to defaults\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    gpio_set_value $JTAG_TRST_L 0\n    if [ \"$SCM_PROGRAM\" = true ]; then\n        # Give SCM cpld time to come back on SMBus\n        sleep 2\n        # Restore x86 power state\n        echo \"$CACHED_SCM_PWR_ON_SYSFS\" > \"$SCM_PWR_ON_SYSFS\" || {\n           echo \"Failed to recover CPU power state.\"\n        }\n        sleep 1\n        gpio_set_value $SCM_FPGA_LATCH_L 1\n    else\n        echo 0 > \"$JTAG_EN\"\n        echo 0 > \"$PROGRAM_SEL\"\n    fi\n\n    if [ \"$SMB_PROGRAM\" = false ]; then\n        echo 0 > \"$SPI_CTRL\"\n        echo 0 > \"$JTAG_CTRL\"\n    fi\n    devmem_clear_bit 0x1e6e2438 8 # SPI1CS1 Function enable\n}\n\nconnect_scm_jtag() {\n    # Store initial state of x86 power in order to restore after programming\n    CACHED_SCM_PWR_ON_SYSFS=\"$(head -n 1 \"$SCM_PWR_ON_SYSFS\" 2> /dev/null)\"\n    gpio_set_value $SCM_FPGA_LATCH_L 0\n\n    gpio_set_value $CPLD_JTAG_SEL_L 0\n    gpio_set_value $JTAG_TRST_L 1\n    echo 0 > \"$JTAG_EN\"\n}\n\nconnect_smb_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    gpio_set_value $JTAG_TRST_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 1 > \"$PROGRAM_SEL\"\n}\n\nconnect_smb_cpld_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    gpio_set_value $JTAG_TRST_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 0 > \"$PROGRAM_SEL\"\n    echo 0 > \"$SPI_CTRL\"\n    echo 0x2 > \"$JTAG_CTRL\"\n}\n\nconnect_fan_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    gpio_set_value $JTAG_TRST_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 0 > \"$PROGRAM_SEL\"\n    echo 0 > \"$SPI_CTRL\"\n    echo 0x1 > \"$JTAG_CTRL\"\n}\n\nbind_spi_nor() {\n    # Unbind spidev1.1\n    if [ -e /dev/spidev1.1 ]; then\n        echo \"$SMB_SPI\" > /sys/bus/spi/drivers/spidev/unbind\n    fi\n\n    # Bind\n    echo spi-nor  > /sys/bus/spi/devices/\"$SMB_SPI\"/driver_override\n    if [ ! -e /sys/bus/spi/drivers/spi-nor/\"$SMB_SPI\" ]; then\n        echo Binding \"$SMB_SPI\" to ...\n        echo \"$SMB_SPI\" > /sys/bus/spi/drivers/spi-nor/bind\n        sleep 0.5\n    fi\n    SMB_MTD=\"$(grep \"$SMB_SPI\" /proc/mtd |awk '{print$1}' | tr -d : | tr -d mtd)\"\n    if test -z \"$SMB_MTD\"; then\n        echo \"Failed to locate mtd partition for SPI Flash!\"\n        exit 1\n    fi\n}\n\nunbind_spi_nor() {\n    # Method for unloading spi-nor driver dynamically back to spidev\n    echo > /sys/bus/spi/devices/\"$SMB_SPI\"/driver_override\n    if grep \"$SMB_SPI\" /proc/mtd > /dev/null 2>&1 ; then\n        echo \"Unbinding spi-nor from $SMB_SPI\"\n        echo \"$SMB_SPI\" > /sys/bus/spi/drivers/spi-nor/unbind\n    fi\n    if [ ! -e /dev/spidev1.1 ]; then\n        echo \"Binding spidev back to $SMB_SPI\"\n        echo \"$SMB_SPI\" > /sys/bus/spi/drivers/spidev/bind\n    fi\n}\n\nconnect_pim_flash() {\n    # Set SPI path to PIM SPI flash\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    echo 0 > \"$PROGRAM_SEL\"\n    echo 1 > \"$SPI_PIM_SEL\"\n    devmem_set_bit 0x1e6e2438 8 # SPI1CS1 Function enable\n    sleep 0.1\n    bind_spi_nor\n}\n\nconnect_th4_qspi_flash() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    echo 0 > \"$PROGRAM_SEL\"\n    echo 1 > \"$SPI_TH4_QSPI_SEL\"\n    devmem_set_bit 0x1e6e2438 8 # SPI1CS1 Function enable\n    sleep 0.1\n}\n\ndo_scm() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*ird\" \"$2\" > /dev/null; then\n        echo \"$2 is not a valid SCM FPGA file\"\n        exit 1\n    fi\n    SCM_PROGRAM=true\n    connect_scm_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl IOCBITBANG\n}\n\ndo_smb() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*onda\" \"$2\" > /dev/null; then\n        echo \"$2 is not a valid SMB FPGA file\"\n        exit 1\n    fi\n    # P1 fpga - Revision <= 1, otherwise P2\n    if [ \"$(printf \"%d\" \"$(grep A_REVISION \"$2\" | \\\n         awk '{print $3}' | tr -d '\";')\")\" -le 1 ]; then\n        # We are using P1 fpga_file\n        if ! wedge_is_smb_p1; then\n            echo \"P1 FPGA FILE not compatible with P2 Hardware!\"\n            exit 1\n        fi\n    else\n        if wedge_is_smb_p1; then\n            echo \"P2 FPGA FILE not compatible with P1 Hardware!\"\n            exit 1\n        fi\n    fi\n    SMB_PROGRAM=true\n    connect_smb_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl IOCBITBANG\n}\n\ndo_smb_cpld() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*ide\" \"$2\" > /dev/null; then\n        echo \"$2 is not a valid SMB CPLD file\"\n        exit 1\n    fi\n    # P1 fpga - Revision <= 4, otherwise P2\n    if [ \"$(printf \"%d\" \"$(grep A_REVISION \"$2\" | \\\n         awk '{print $3}' | tr -d '\";')\")\" -le 4 ]; then\n        # We are using P1 fpga binary\n        if ! wedge_is_smb_p1; then\n            echo \"P1 FPGA FILE not compatible with P2 Hardware!\"\n            exit 1\n        fi\n    else\n        # We are using P2 fpga binary\n        if wedge_is_smb_p1; then\n            echo \"P2 FPGA FILE not compatible with P1 Hardware!\"\n            exit 1\n        fi\n    fi\n    connect_smb_cpld_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl IOCBITBANG\n}\n\ndo_fan() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*ckels\" \"$2\" > /dev/null; then\n        echo \"$2 is not a valid FAN FPGA file\"\n        exit 1\n    fi\n    connect_fan_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl IOCBITBANG\n}\n\nprogram_spi_image() {\n    ORIGINAL_IMAGE=\"$1\" # Image path\n    ACTION=\"${4^^}\"         # Program or verify\n\n    case \"${2^^}\" in # Selects driver used\n        FLASHROM)\n           DRIVER=linux_spi:dev=/dev/\"$SMB_SPIDEV\"\n           ;;\n        SPINOR)\n           DRIVER=linux_mtd:dev=\"$SMB_MTD\"\n           ;;\n        *)\n           echo \"Unknown driver $2 specified\"\n           exit 1\n           ;;\n    esac\n\n    case \"${3^^}\" in # Selects passed partition name\n        PIM_BASE)\n           PARTITION=\"pim_base\"\n           SKIP_MB=0\n           # TODO: Restrict PIM_BASE later\n           # FPGA_TYPE=0\n           FPGA_TYPE=-1\n           ;;\n        TH4_QSPI)\n           PARTITION=\"th4_qspi\"\n           SKIP_MB=0\n           FPGA_TYPE=-1\n           ;;\n        PIM16Q)\n           PARTITION=\"pim16q\"\n           SKIP_MB=1\n           FPGA_TYPE=1\n           ;;\n        PIM8DDM)\n           PARTITION=\"pim8ddm\"\n           SKIP_MB=2\n           FPGA_TYPE=2\n           ;;\n        FULL)\n           PARTITION=\"full\" # Flash entire spi flash\n           SKIP_MB=0\n           FPGA_TYPE=-1\n           ;;\n        *)\n           echo \"Unknown region $3 specified\"\n           exit 1\n           ;;\n    esac\n\n    echo \"Selected partition $PARTITION to program.\"\n    # Clear any cached pim header version files\n    rm /tmp/.pim_spi_header* 2>/dev/null\n    rm /tmp/.qspi_spi_image* 2>/dev/null\n\n    if [ \"$FPGA_TYPE\" -ge 0 ] ; then\n        # Verify the image type\n        IMG_FPGA_TYPE=$(head -c3 \"$ORIGINAL_IMAGE\" | hexdump -v -e '/1 \"%u\\n\"' | \\\n                        tail -n1)\n        if [ \"$IMG_FPGA_TYPE\" != \"$FPGA_TYPE\" ]; then\n            echo \"FPGA type in image, $IMG_FPGA_TYPE, does not match expected\" \\\n                 \"FPGA type, $FPGA_TYPE, for partition $PARTITION\"\n            exit 1\n        fi\n    fi\n\n    # We need to 32 MB binary, we will fill if needed with 1s.\n    # We will only program/verify the specified image partition\n    EEPROM_SIZE=\"33554432\" # 32 MB\n    IMAGE_SIZE=\"$(ls -l \"$ORIGINAL_IMAGE\" | awk '{print $5}')\"\n    TEMP_IMAGE=\"/tmp/pim_image_32mb.bin\"\n\n    if [ \"$IMAGE_SIZE\" -gt \"$EEPROM_SIZE\" ] ; then\n        echo \"$IMAGE size $IMAGE_SIZE is greater than eeprom capacity $EEPROM_SIZE\"\n        exit 1\n    fi\n\n    OPERATION=\"-w\"\n    if [ \"$ACTION\" = \"VERIFY\" ]\n    then\n        OPERATION=\"-v\"\n    fi\n\n    fill=$((EEPROM_SIZE - IMAGE_SIZE))\n    bs=1048576 # 1MB blocks\n\n    echo \"$ORIGINAL_IMAGE size $IMAGE_SIZE < $EEPROM_SIZE (32MB)\"\n    echo \"Resizing $ORIGINAL_IMAGE by $fill bytes to $TEMP_IMAGE\"\n\n    # Let's make a copy of the program image and 0xff-fill it to 32MB\n    # Prepend/append 0x1 bytes accordingly\n    {\n        dd if=/dev/zero bs=$bs count=\"$SKIP_MB\" | tr \"\\000\" \"\\377\"\n        dd if=\"$ORIGINAL_IMAGE\"\n    } 2>/dev/null > \"$TEMP_IMAGE\"\n\n    div=$((fill/bs)) # Number of 1MB blocks to write\n    div=$((div - SKIP_MB))\n    rem=$((fill%bs)) # Remaining\n    {\n        dd if=/dev/zero bs=$bs count=$div | tr \"\\000\" \"\\377\"\n        dd if=/dev/zero bs=$rem count=1 | tr \"\\000\" \"\\377\"\n    } 2>/dev/null >> \"$TEMP_IMAGE\"\n\n    TEMP_IMAGE_SIZE=\"$(ls -l \"$TEMP_IMAGE\" | awk '{print $5}')\"\n    if [ \"$TEMP_IMAGE_SIZE\" -ne \"$EEPROM_SIZE\" ] ; then\n        echo \"Failed to resize $ORIGINAL_IMAGE to 32MB... exiting.\"\n        exit 1\n    fi\n\n    # Retry the programming if it fails up to 3 times\n    n=1\n    max=3\n    while true; do\n        # Program the 32MB pim image\n        if flashrom -p \"$DRIVER\" -N --layout /etc/elbert_pim.layout \\\n           --image \"$PARTITION\" $OPERATION \"$TEMP_IMAGE\" ; then\n            break\n        else\n            if [ $n -lt $max ]; then\n                echo \"Programming SPI failed, retry attempt $n/$max\"\n                n=$((n+1))\n            else\n                echo \"Failed to program after $n attempts\"\n                rm \"$TEMP_IMAGE\"\n                exit 1\n            fi\n        fi\n    done\n\n    rm \"$TEMP_IMAGE\"\n}\n\nread_spi_partition_image() {\n    DEST=\"$1\" # READ Image output path\n    BS=\"1M\" # Default partition is 1MB\n    COUNT=1 # Default partition size is 1 * BS\n    SKIP_MB=0\n\n    case \"${2^^}\" in # Selects driver used\n        FLASHROM)\n           DRIVER=linux_spi:dev=/dev/\"$SMB_SPIDEV\"\n           ;;\n        SPINOR)\n           DRIVER=linux_mtd:dev=\"$SMB_MTD\"\n           ;;\n        *)\n           echo \"Unknown driver $2 specified\"\n           exit 1\n           ;;\n    esac\n\n    case \"${3^^}\" in # Selects passed partition name\n        PIM_BASE)\n           PARTITION=\"pim_base\"\n           ;;\n        HEADER_PIM_BASE)\n           PARTITION=\"header_pim_base\"\n           ;;\n        HEADER_TH4_QSPI)\n           PARTITION=\"header_th4_qspi\"\n           ;;\n        TH4_QSPI)\n           BS=1K # TH4 QSPI is small, use 1K increments\n           COUNT=32 # TH4 QSPI is <32KB\n           PARTITION=\"th4_qspi\"\n           ;;\n        PIM16Q)\n           PARTITION=\"pim16q\"\n           SKIP_MB=1\n           ;;\n        HEADER_PIM16Q)\n           PARTITION=\"header_pim16q\"\n           SKIP_MB=1\n           ;;\n        PIM8DDM)\n           PARTITION=\"pim8ddm\"\n           SKIP_MB=2\n           ;;\n        HEADER_PIM8DDM)\n           PARTITION=\"header_pim8ddm\"\n           SKIP_MB=2\n           ;;\n        FULL)\n           PARTITION=\"full\" # Read Entire SPI flash\n           COUNT=32 # Full 32MB image\n           ;;\n        *)\n           echo \"Unknown region $3 specified\"\n           exit 1\n           ;;\n    esac\n\n    echo \"Selected partition $PARTITION to read.\"\n\n    flashrom -p \"$DRIVER\" \\\n        --layout /etc/elbert_pim.layout --image \"$PARTITION\" -r \"$TEMP_SPI_IMAGE\" \\\n        || return 1\n    sleep 1\n    flashrom -p \"$DRIVER\" \\\n        --layout /etc/elbert_pim.layout --image \"$PARTITION\" -v \"$TEMP_SPI_IMAGE\" \\\n        || return 1\n    dd if=\"$TEMP_SPI_IMAGE\" of=\"$DEST\" bs=\"$BS\" count=\"$COUNT\" skip=\"$SKIP_MB\" 2> /dev/null\n    return 0\n}\n\nstrip_image_header() {\n    ORIG_IMAGE=\"$1\"\n    NEW_IMAGE=\"$2\"\n    POS=$(head -c4096 \"$ORIG_IMAGE\" | hexdump -v -e '/1 \"%u\\n\"' | \\\n          (grep -n -e '^0$' || echo 0) | head -n1 | cut -d':' -f1)\n    if [ \"$POS\" -gt 0 ]\n    then\n        if ! dd if=\"$ORIG_IMAGE\" bs=1 count=\"$POS\" 2> /dev/null | grep _REVISION \\\n             > /dev/null\n        then\n            # No REVISION header found\n            POS=0\n        fi\n    fi\n\n    if [ \"$POS\" -gt 0 ]\n    then\n        dd if=\"$ORIG_IMAGE\" of=\"$NEW_IMAGE\" bs=\"$POS\" skip=1 2> /dev/null\n    else\n        cp \"$ORIG_IMAGE\" \"$NEW_IMAGE\"\n    fi\n}\n\ndo_pim() {\n    case \"${1^^}\" in\n        PROGRAM|VERIFY)\n            # Image with header stripped\n            BIN_IMAGE=\"/tmp/stripped_pim_image\"\n            connect_pim_flash\n            strip_image_header \"$2\" \"$BIN_IMAGE\"\n            program_spi_image \"$BIN_IMAGE\" \"SPINOR\" \"$3\" \"$1\"\n            rm \"$BIN_IMAGE\"\n            ;;\n        READ)\n            connect_pim_flash\n            if [ -z \"$3\" ]; then\n                flashrom -p linux_mtd:dev=\"$SMB_MTD\" -r \"$2\" || exit 1\n                sleep 1\n                flashrom -p linux_mtd:dev=\"$SMB_MTD\" -v \"$2\" || exit 1\n            else\n                read_spi_partition_image \"$2\" \"SPINOR\" \"$3\" || exit 1\n            fi\n            ;;\n        ERASE)\n            connect_pim_flash\n            if [ -z \"$2\" ]; then\n                flashrom -p linux_mtd:dev=\"$SMB_MTD\" -E || exit 1\n            else\n                flashrom -p linux_mtd:dev=\"$SMB_MTD\" \\\n                    --layout /etc/elbert_pim.layout --image \"$2\" -E || exit 1\n            fi\n            ;;\n        *)\n            echo \"PIM only supports program/verify/read/erase action. Exiting...\"\n            exit 1\n            ;;\n    esac\n}\n\ndo_th4_qspi() {\n    case \"${1^^}\" in\n        PROGRAM|VERIFY)\n            # Image with header stripped\n            BIN_IMAGE=\"/tmp/stripped_qspi_image\"\n            unbind_spi_nor\n            connect_th4_qspi_flash\n            strip_image_header \"$2\" \"$BIN_IMAGE\"\n            program_spi_image \"$BIN_IMAGE\" \"FLASHROM\" th4_qspi \"$1\"\n            ;;\n        READ)\n            unbind_spi_nor\n            connect_th4_qspi_flash\n            if [ -z \"$3\" ]; then\n                read_spi_partition_image \"$2\" \"FLASHROM\" th4_qspi || exit 1\n            else\n                read_spi_partition_image \"$2\" \"FLASHROM\" \"$3\" || exit 1\n            fi\n            ;;\n        *)\n            echo \"TH4 QSPI only supports program/verify/read action. Exiting...\"\n            exit 1\n            ;;\n    esac\n}\n\nif [ $# -lt 2 ]; then\n    usage\nfi\n\ncase \"$1\" in\n   smb) shift 1\n      do_smb \"$@\"\n      ;;\n   smb_cpld) shift 1\n      do_smb_cpld \"$@\"\n      ;;\n   scm) shift 1\n      do_scm \"$@\"\n      ;;\n   pim) shift 1\n      do_pim \"$@\" full\n      ;;\n   pim_base) shift 1\n      do_pim \"$@\" pim_base\n      ;;\n   pim16q) shift 1\n      do_pim \"$@\" pim16q\n      ;;\n   pim8ddm) shift 1\n      do_pim \"$@\" pim8ddm\n      ;;\n   header_pim_base) shift 1\n      do_pim \"$@\" header_pim_base\n      ;;\n   header_pim16q) shift 1\n      do_pim \"$@\" header_pim16q\n      ;;\n   header_pim8ddm) shift 1\n      do_pim \"$@\" header_pim8ddm\n      ;;\n   fan) shift 1\n      do_fan \"$@\"\n      ;;\n   th4_qspi) shift 1\n      do_th4_qspi \"$@\"\n      ;;\n   header_th4_qspi) shift 1\n      do_th4_qspi \"$@\" header_th4_qspi\n      ;;\n   *)\n      usage\n      ;;\nesac\n", "num_lines": 574}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nmaj_ver=\"cpld_ver_major\"\nmin_ver=\"cpld_ver_minor\"\nexitCode=0\n\necho \"------SCM-FPGA------\"\n\nif [ ! -d \"$SCMCPLD_SYSFS_DIR\" ]; then\n    echo \"SCM_FPGA: FPGA_DRIVER_NOT_DETECTED\"\n    exitCode=1\nelse\n    val_major=$(head -n 1 \"$SCMCPLD_SYSFS_DIR\"/\"$maj_ver\")\n    val_minor=$(head -n 1 \"$SCMCPLD_SYSFS_DIR\"/\"$min_ver\")\n    echo \"SCM_FPGA: $((val_major)).$((val_minor))\"\nfi\n\necho \"------FAN-FPGA------\"\nif [ ! -d \"$FANCPLD_SYSFS_DIR\" ]; then\n    echo \"FAN_FPGA: FPGA_DRIVER_NOT_DETECTED\"\n    exitCode=1\nelse\n    val_major=$(head -n 1 \"$FANCPLD_SYSFS_DIR\"/\"$maj_ver\")\n    val_minor=$(head -n 1 \"$FANCPLD_SYSFS_DIR\"/\"$min_ver\")\n    echo \"FAN_FPGA: $((val_major)).$((val_minor))\"\nfi\n\necho \"------SMB-FPGA------\"\nif [ ! -d \"$SMBCPLD_SYSFS_DIR\" ]; then\n    echo \"SMB_FPGA: FPGA_DRIVER_NOT_DETECTED\"\n    echo \"Unable to retrieve PIM FPGA versions either\"\n    exitCode=1\nelse\n    val_major=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/\"$maj_ver\")\n    val_minor=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/\"$min_ver\")\n    echo \"SMB_FPGA: $((val_major)).$((val_minor))\"\n\n    echo \"------SMB-CPLD------\"\n    val_major=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/th4_cpld_ver_major)\n    val_minor=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/th4_cpld_ver_minor)\n    echo \"SMB_CPLD: $((val_major)).$((val_minor))\"\n\n    echo \"------PIM-FPGA------\"\n    pim_list=\"2 3 4 5 6 7 8 9\"\n    for pim in ${pim_list}; do\n      pim_present=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$pim\"_present)\n      pim_major=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$pim\"_fpga_rev_major)\n      pim_minor=$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim\"$pim\"_fpga_rev_minor)\n      if [ \"$((pim_present))\" -eq 0 ]; then\n        echo \"PIM $pim: NOT_INSERTED\"\n      elif [ \"$((pim_major))\" -eq 255 ]; then\n        # The FPGA version read was 0xFF, which indicates not detected\n        echo \"PIM $pim: VERSION_NOT_DETECTED\"\n        exitCode=1\n      else\n        echo \"PIM $pim: $((pim_major)).$((pim_minor))\"\n      fi\n    done\nfi\n\nif [ \"$exitCode\" -ne 0 ]; then\n    echo \"One or more fpga versions was not detected... exiting\"\n    exit 1\nfi\n", "num_lines": 86}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# This utility prints the meta information for specified boot flash\n# mtd partition\nSTART_OFFSET_KB=960\nLEN_KB=64\n\nusage() {\n    echo \"Usage $0 [flash0|flash1]\"\n}\n\ncase \"$1\" in\n    flash0)\n        mtd=\"$(grep flash0 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    flash1)\n        mtd=\"$(grep flash1 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\ndd if=/dev/\"$mtd\" of=/tmp/.\"$1\"_meta bs=1K skip=\"$START_OFFSET_KB\" count=\"$LEN_KB\"\nstrings /tmp/.\"$1\"_meta\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2039\n# SC2059 is disabled to allow binary character printing using printf\n# shellcheck disable=SC2059\n\n. /usr/local/bin/openbmc-utils.sh\n\nEWEN_CMD=0x0\nEWEN_ADDR=0x300\nEWDS_CMD=0x0\nEWDS_ADDR=0x0\nREAD_CMD=0x2\nWRITE_CMD=0x1\n\nSPEED_1MHZ=0x1\n\nDS4520_PROGRAMMED=0\nWRITES_ENABLED=0\n\nCOMMAND_REG_PREFIX=\"oob_eeprom_cmd_\"\nRESPONSE_REG_PREFIX=\"oob_eeprom_resp_\"\nREAD_TRIGGER_REG=\"oob_eeprom_resp_trigger\"\nEEPROM_SIZE=1024\n\nDS4520_BUS=8\nDS4520_DEV=$(( 0x50 ))\n\n# DS4520 pullup enable register for IO_0 through IO_7\nDS4520_PULL0_REG=0xf0\n# DS4520 I/O control register for IO_0 through IO_7\nDS4520_PULL1_REG=0xf1\n# DS4520 pullup enable register for IO_8\nDS4520_IO0_REG=0xf2\n# DS4520 I/O control register for IO_8\nDS4520_IO1_REG=0xf3\n\n# Setting bit 0 in the DS4520 config register makes subsequent changes\n# volatile. This ensures that default settings will be restored on power loss.\nDS4520_CONFIG_REG=0xf4\nDS4520_VOLATILE=0x1\nDS4520_CONFIG_MASK=$(( 1 << 0 ))\n\n# PULL0/IO0 bit definitions:\nSC_SPI_BUF_EN_L=7\nMSW_SPI_CTRL_EN_L=6\nEEPROMMASTER_SEL_EN_L=5\nEEPROMMASTER_SEL=4\nCPUEEEPROM_SEL_EN_L=3\nCPUEEEPROM_SEL=2\nDS4520_IO0_MASK=$(( ( 1 << SC_SPI_BUF_EN_L ) \\\n                  | ( 1 << MSW_SPI_CTRL_EN_L ) \\\n                  | ( 1 << EEPROMMASTER_SEL_EN_L ) \\\n                  | ( 1 << EEPROMMASTER_SEL ) \\\n                  | ( 1 << CPUEEEPROM_SEL_EN_L ) \\\n                  | ( 1 << CPUEEEPROM_SEL ) ))\n\n# PULL1/IO1 bit definitions:\nMSW_SPI_CTRL_SEL=0\nDS4520_IO1_MASK=$(( 1 << MSW_SPI_CTRL_SEL ))\n\nCPLD_EEPROM_MODE_0=$(( ( 1 << SC_SPI_BUF_EN_L ) \\\n                     | ( 1 << EEPROMMASTER_SEL ) \\\n                     | ( 1 << CPUEEEPROM_SEL_EN_L ) ))\nCPLD_EEPROM_MODE_1=$(( 1 << MSW_SPI_CTRL_SEL ))\nEEPROM_MODE_0=$(( 1 << MSW_SPI_CTRL_EN_L ))\nEEPROM_MODE_1=0\n\ntrap cleanup EXIT\ntrap handle_signal INT TERM QUIT\n\nusage() {\n    echo \"Dumps or programs the OOB Eeprom\"\n    echo\n    echo \"dump [--full]\"\n    echo \"save <filename>\"\n    echo \"program <filename>\"\n    echo \"read <index> [<num-words>]\"\n    echo \"write <index> <word>\"\n    echo \"version\"\n}\n\nread_index() {\n    local cmd_reg\n    cmd_reg=$(( ( READ_CMD << 30 ) | ( SPEED_1MHZ << 28 ) | ( $1 << 16 ) ))\n    desc=\"reading index $idx\"\n    send_cmd \"$cmd_reg\" \"$desc\" \"trig_read\"\n}\n\nwrite_index() {\n    local idx=$1\n    local val=$2\n    local cmd_reg\n    cmd_reg=$(( ( WRITE_CMD << 30 ) | ( SPEED_1MHZ << 28 ) \\\n              | ( idx << 16 ) | val ))\n    desc=\"writing index $idx value $val\"\n    local resp_val\n    local try_num=0\n    while [ $try_num -lt 5 ]\n    do\n        resp_val=$( send_cmd \"$cmd_reg\" \"$desc\" \"trig_read\" ) || exit 1\n        if [ $(( resp_val )) -eq $(( val )) ]\n        then\n            # verify the value read matches the value programmed\n            read_val=$( read_index \"$idx\" )\n            if [ $(( read_val )) = $(( val )) ]\n            then\n                return\n            fi\n\n            printf \"Error: try %d: read value after write(\" $try_num >&2\n            printf \"0x%x) does not match write val(0x%x)\\n\" \"$read_val\" \"$val\" >&2\n        else\n            printf \"Error: try %d: response value from write(\" $try_num >&2\n            printf \"0x%x) does not match write val(0x%x)\\n\" \"$resp_val\" \"$val\" >&2\n        fi\n\n        try_num=$(( try_num + 1 ))\n    done\n\n    echo \"failed to write register\" >&2\n    exit 1\n}\n\neeprom_disable_write() {\n    echo \"Write interrupted. Disabling writes.\" >&2\n    eeprom_write_protect \"disable\"\n}\n\nset_cpld_eeprom_mode() {\n    # Program the DS4520 to allow access to the EEPROM.\n    DS4520_PROGRAMMED=1\n    i2cset -y -m $DS4520_CONFIG_MASK $DS4520_BUS $DS4520_DEV $DS4520_CONFIG_REG \\\n                 $DS4520_VOLATILE\n    # A small delay is needed after toggling persistence setting.\n    sleep 1\n    i2cset -y -m $DS4520_IO0_MASK $DS4520_BUS $DS4520_DEV $DS4520_PULL0_REG \\\n                 $CPLD_EEPROM_MODE_0\n    i2cset -y -m $DS4520_IO1_MASK $DS4520_BUS $DS4520_DEV $DS4520_PULL1_REG \\\n                 $CPLD_EEPROM_MODE_1\n    i2cset -y -m $DS4520_IO0_MASK $DS4520_BUS $DS4520_DEV $DS4520_IO0_REG \\\n                 $CPLD_EEPROM_MODE_0\n    i2cset -y -m $DS4520_IO1_MASK $DS4520_BUS $DS4520_DEV $DS4520_IO1_REG \\\n                 $CPLD_EEPROM_MODE_1\n}\n\nrestore_eeprom_mode() {\n    i2cset -y -m $DS4520_CONFIG_MASK $DS4520_BUS $DS4520_DEV $DS4520_CONFIG_REG \\\n                 $DS4520_VOLATILE\n    i2cset -y -m $DS4520_IO0_MASK $DS4520_BUS $DS4520_DEV $DS4520_PULL0_REG \\\n                 $EEPROM_MODE_0\n    i2cset -y -m $DS4520_IO1_MASK $DS4520_BUS $DS4520_DEV $DS4520_PULL1_REG \\\n                 $EEPROM_MODE_1\n    i2cset -y -m $DS4520_IO0_MASK $DS4520_BUS $DS4520_DEV $DS4520_IO0_REG \\\n                 $EEPROM_MODE_0\n    i2cset -y -m $DS4520_IO1_MASK $DS4520_BUS $DS4520_DEV $DS4520_IO1_REG \\\n                 $EEPROM_MODE_1\n    DS4520_PROGRAMMED=0\n}\n\ncleanup() {\n    if [ $WRITES_ENABLED -eq 1 ]\n    then\n        eeprom_disable_write\n        WRITES_ENABLED=0\n    fi\n\n    if [ $DS4520_PROGRAMMED -eq 1 ]\n    then\n        restore_eeprom_mode\n    fi\n}\n\nhandle_signal() {\n    echo \"Exiting because of signal\" >&2\n    cleanup\n    exit 1\n}\n\neeprom_write_protect() {\n    local enable=$1\n\n    local cmd cmd_addr\n    if [ \"$enable\" = \"enable\" ]\n    then\n        cmd=$EWEN_CMD\n        cmd_addr=$EWEN_ADDR\n        WRITES_ENABLED=1\n    else\n        cmd=$EWDS_CMD\n        cmd_addr=$EWDS_ADDR\n    fi\n\n    local cmd_reg\n    cmd_reg=$(( ( cmd << 30 ) | ( SPEED_1MHZ << 28 ) \\\n           | ( cmd_addr << 16 ) ))\n    desc=\"setting write protect to $enable\"\n    send_cmd \"$cmd_reg\" \"$desc\" \"trig_read\" > /dev/null\n\n    if [ \"$enable\" = \"disable\" ]\n    then\n        WRITES_ENABLED=0\n    fi\n}\n\neeprom_init() {\n    set_cpld_eeprom_mode\n\n    # Clear write cycle error, if present\n    i2c_set \"oob_eeprom_resp_3\" 0x8\n    i2c_set \"oob_eeprom_resp_trigger\" 0x0\n}\n\nsend_cmd() {\n    local cmd_reg=$1\n    local desc=\"$2\"\n    local trig_opt=\"$3\"\n\n    local cpld_reg reg_idx\n    local try_num=0\n    while [ $try_num -lt 5 ]\n    do\n        reg_idx=0\n        while [ $reg_idx -lt 4 ]\n        do\n            cpld_reg=${COMMAND_REG_PREFIX}$(( 3 - reg_idx ))\n            cpld_reg_val=$(( ( cmd_reg >> ( ( 3 - reg_idx ) * 8 ) ) & 0xff ))\n            i2c_set $cpld_reg \"$cpld_reg_val\"\n            reg_idx=$(( reg_idx + 1 ))\n        done\n\n        # The FPGA requires 10ms prior to triggering the read request.\n        # Sleep for 20ms.\n        sleep 0.02\n\n        if [ \"$trig_opt\" = \"trig_read\" ]\n        then\n            i2c_set $READ_TRIGGER_REG 0x0\n        fi\n\n        get_response \"$desc\" && return\n        if [ $? -gt 1 ]\n        then\n           exit 1\n        fi\n\n        printf \"Send command failed on try %d\\n\" $try_num >&2\n        try_num=$(( try_num + 1 ))\n    done\n\n    echo \"Send command failed\" >&2\n    exit 1\n}\n\nget_response() {\n    local desc=$1\n    local timeout=5\n    local interval=0.1\n    local time_limit=0\n    local reg_idx resp_val\n    while true\n    do\n        resp_val=0\n        reg_idx=0\n        while [ $reg_idx -lt 4 ]\n        do\n            cpld_reg=${RESPONSE_REG_PREFIX}$(( 3 - reg_idx ))\n            cpld_reg_val=$( i2c_get $cpld_reg )\n            # Each CPLD register contains one byte of the response with the\n            # MSB first and the LSB last.\n            bit_offset=$(( ( 3 - reg_idx ) * 8 ))\n            shifted_val=$(( cpld_reg_val << bit_offset ))\n            resp_val=$(( resp_val | shifted_val ))\n            reg_idx=$(( reg_idx + 1 ))\n        done\n\n        if [ $(( ( resp_val >> 27 ) & 0x1 )) -ne 0 ]\n        then\n            echo \"Error: Write cycle error\" >&2\n            return 2\n        fi\n\n        if [ $(( ( resp_val >> 28 ) & 0x1 )) -ne 0 ]\n        then\n            echo $(( resp_val & 0xffff ))\n            return 0\n        fi\n\n        if [ $time_limit -eq 0 ]\n        then\n            time_limit=$(( $( date +%s ) + timeout ))\n        fi\n        if [ \"$( date +%s )\" -gt $time_limit ]\n        then\n            break\n        fi\n\n        sleep $interval\n    done\n\n    echo \"Timed out $desc\" >&2\n    return 1\n}\n\ni2c_set() {\n    echo \"$2\" > \"$SCMCPLD_SYSFS_DIR/$1\"\n}\n\ni2c_get() {\n    head -n 1 \"$SCMCPLD_SYSFS_DIR/$1\"\n}\n\neeprom_read() {\n    if [ $# -lt 1 ]\n    then\n        echo \"Error: missing read index\" >&2\n        usage\n        exit 1\n    fi\n\n    local start=$(( $1 ))\n    local num_words=1\n    if [ $# -gt 1 ]\n    then\n        num_words=$2\n    fi\n    local end=$(( start + num_words ))\n    if [ $end -gt $EEPROM_SIZE ]\n    then\n        echo \"Error: end index exceeds size\" >&2\n        exit 1\n    fi\n\n    eeprom_write_protect \"disable\"\n\n    local idx=$start\n    local val\n    while [ $idx -lt \"$end\" ]\n    do\n        val=$( read_index $idx )\n        printf \"0x%x: 0x%x\\n\" $idx \"$val\"\n        idx=$(( idx + 1 ))\n    done\n}\n\nadd_to_csum() {\n    local csum=$1\n    local idx=$2\n    local val=$3\n    csum=$(( csum + ( idx << 16 ) + val ))\n    # To prevent overflowing 32 bits, modulus with bit 31.\n    csum=$(( csum % 0x80000000 ))\n    echo $csum\n}\n\neeprom_dump() {\n    local csum_lsb csum_msb header version\n\n    local full=\"no\"\n    if [ $# -gt 0 ] && [ \"$1\" = \"--full\" ]\n    then\n        full=\"yes\"\n    fi\n\n    eeprom_write_protect \"disable\"\n    local calc_csum=0\n\n    header=$( read_index 0 )\n    printf \"0x%x: 0x%x\\n\" 0 \"$header\"\n    # As described in Broadcom's BCM53134P data sheet, the magic code\n    # is in bits 15:11 of the first word in the EEPROM and the expected\n    # value is 0x15.\n    local magic_code=$(( header >> 11 ))\n    if [ $magic_code -ne $(( 0x15 )) ]\n    then\n        printf \"Error: magic code 0x%x does not match expected \" $magic_code >&2\n        printf \"0x15\\n\" >&2\n        if [ $full = \"no\" ]\n        then\n            exit 1\n        fi\n    fi\n    calc_csum=$( add_to_csum $calc_csum 0 \"$header\" )\n\n    local num_entries=$(( header & 0x3ff ))\n    local stream_end=$(( 1 + num_entries ))\n    echo \"Number of data words: $num_entries\"\n    local start=1\n    # 3 words are reserved at the end of the image.\n    # 2 are for the checksum. 1 is for the version.\n    local eeprom_end=$(( EEPROM_SIZE - 3 ))\n    local end=$eeprom_end\n    if [ $full = \"no\" ]\n    then\n        end=$stream_end\n    fi\n\n    local idx=$start\n    while [ $idx -lt \"$end\" ]\n    do\n        val=$( read_index $idx )\n        printf \"0x%x: 0x%x\\n\" $idx \"$val\"\n        if [ $idx -lt $stream_end ]\n        then\n            calc_csum=$( add_to_csum \"$calc_csum\" $idx \"$val\" )\n        fi\n        idx=$(( idx + 1 ))\n    done\n\n    idx=$eeprom_end\n    csum_lsb=$( read_index idx )\n    printf \"0x%x: 0x%x\\n\" $idx \"$csum_lsb\"\n    idx=$(( idx + 1 ))\n    csum_msb=$( read_index idx )\n    printf \"0x%x: 0x%x\\n\" $idx \"$csum_msb\"\n    idx=$(( idx + 1 ))\n    version=$( read_index idx )\n    printf \"0x%x: 0x%x\\n\" $idx \"$version\"\n    printf \"Version: %x.%x\\n\" $(( version >> 8 )) $(( version & 0xff ))\n\n    csum=$(( ( csum_msb << 16 ) | csum_lsb ))\n    printf \"Checksum: 0x%x\\n\" $csum\n    printf \"Calculated checksum: 0x%x\\n\" \"$calc_csum\"\n\n    if [ \"$csum\" -ne \"$calc_csum\" ]\n    then\n        echo \"Error: Checksum is not expected value\" >&2\n        exit 1\n    fi\n}\n\neeprom_version() {\n    local idx version\n\n    eeprom_write_protect \"disable\"\n\n    # Last word at the end of the image contains version.\n    idx=$(( EEPROM_SIZE - 1 ))\n    version=$( read_index idx )\n    printf \"Version: %x.%x\\n\" $(( version >> 8 )) $(( version & 0xff ))\n}\n\neeprom_save() {\n    if [ $# -lt 1 ]\n    then\n        echo \"Error: missing filename\" >&2\n        usage\n        exit 1\n    fi\n\n    local filename=$1\n    if [ -f \"$filename\" ]\n    then\n        echo \"Error: file $filename already exists. Remove this file.\" >&2\n        exit 1\n    fi\n\n    touch \"$filename\"\n    local idx=0\n    local val\n    while [ $idx -lt \"$EEPROM_SIZE\" ]\n    do\n        val=$( read_index $idx )\n        printf \"\\\\$( printf \"%o\" $(( val & 0xff )) )\" >> \"$filename\"\n        printf \"\\\\$( printf \"%o\" $(( val >> 8 )) )\" >> \"$filename\"\n        if [ $(( ( idx + 1 ) % 0x80 )) -eq 0 ]\n        then\n            printf \"Saved word 0x%x\\n\" \"$idx\"\n        fi\n        idx=$(( idx + 1 ))\n    done\n    sync\n}\n\neeprom_write() {\n    if [ $# -lt 2 ]\n    then\n        echo \"Error: missing arguments\" >&2\n        usage\n        exit 1\n    fi\n\n    eeprom_write_protect \"enable\"\n\n    local idx=$1\n    local val=$2\n\n    write_index \"$idx\" \"$val\"\n    printf \"Wrote 0x%x to 0x%x\\n\" \"$val\" \"$idx\"\n\n    eeprom_write_protect \"disable\"\n}\n\nprogram_file() {\n    local i=0\n    local idx=0\n    local val=0\n\n    while read -r c\n    do\n        if [ $i -eq 0 ]\n        then\n            val=$c\n            i=1\n        else\n            val=$(( val | ( c << 8 ) ))\n            write_index \"$idx\" \"$val\"\n            printf \"Wrote 0x%x to 0x%x\\n\" \"$val\" \"$idx\"\n\n            idx=$(( idx + 1 ))\n            i=0\n        fi\n    done\n}\n\neeprom_program() {\n    if [ $# -lt 1 ]\n    then\n        echo \"Error: missing filename\" >&2\n        usage\n        exit 1\n    fi\n\n    local filename=$1\n\n    if [ ! -f \"$filename\" ]\n    then\n        echo \"Error: could not access file $filename\" >&2\n        exit 1\n    fi\n\n    size=$( stat -c %s \"$filename\" )\n    words=$(( size / 2 ))\n    if [ \"$words\" -ne $EEPROM_SIZE ]\n    then\n        printf \"Error: words in file(%d) does not match eeprom \" \"$words\" >&2\n        printf \"size(%d)\\n\" $EEPROM_SIZE >&2\n        exit 1\n    fi\n\n    eeprom_write_protect \"enable\"\n    hexdump -v -e '/1 \"%u\\n\"' \"$filename\" | program_file\n    eeprom_write_protect \"disable\"\n}\n\nif [ $# -lt 1 ]\nthen\n    echo \"Error: missing command\" >&2\n    usage\n    exit 1\nfi\n\n# Only allow one instance of script to run at a time.\nscript=$(realpath \"$0\")\nexec 100< \"$script\"\nflock -n 100 || { echo \"ERROR: $0 already running\" && exit 1; }\n\nif [ ! -d \"$SCMCPLD_SYSFS_DIR\" ]\nthen\n    echo \"Error: SCM CPLD not detected\" >&2\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\neeprom_init\n\ncase \"$command\" in\n    dump)\n        eeprom_dump \"$@\"\n        ;;\n    save)\n        eeprom_save \"$@\"\n        ;;\n    program)\n        eeprom_program \"$@\"\n        ;;\n    read)\n        eeprom_read \"$@\"\n        ;;\n    write)\n        eeprom_write \"$@\"\n        ;;\n    version)\n        eeprom_version \"$@\"\n        ;;\n    *)\n        echo \"Error: invalid command: $command\" >&2\n        usage\n        exit 1\n        ;;\nesac\n", "num_lines": 613}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC2039\nusage() {\n    echo \"Reads/writes Bcm53134 registers\"\n    echo\n    echo \"read[(8|16|32|64)] <page> <addr>\"\n    echo \"write[(8|16|32|64)] <page> <addr> <val>\"\n    echo\n    echo \"read/write are equivalent to read8/write8\"\n}\n\nmdio0_base_reg=0x1e650000\nmdio_ctrl_reg=0x0\nmdio_read_reg=0x4\npseudo_phy_port_addr=0x1e\n\nscu_reset_set2=0x1e6e2050\nscu_reset_clear2=$((scu_reset_set2 + 0x4))\nscu_reset_mii_controller=$((1 << 3))\nscu_pin_control8=0x1e6e2430\nscu_mdcmdio_enable=$(( (1 << 16) | (1 << 17) ))\n\ntrap cleanup EXIT INT TERM QUIT\n\nMDIO_INITIALIZED=0\ncleanup() {\n    if [ $MDIO_INITIALIZED -eq 1 ]\n    then\n        mdio_restore\n    fi\n}\n\nmdio_init() {\n    MDIO_INITIALIZED=1\n    devmem \"$scu_reset_clear2\" 32 \"$scu_reset_mii_controller\"\n\n    val=$(devmem \"$scu_pin_control8\")\n    devmem \"$scu_pin_control8\" 32 $((val | scu_mdcmdio_enable))\n}\n\nmdio_restore() {\n    devmem \"$scu_reset_set2\" 32 \"$scu_reset_mii_controller\"\n    val=$(devmem \"$scu_pin_control8\")\n    devmem \"$scu_pin_control8\" 32 $((val & ~scu_mdcmdio_enable))\n    MDIO_INITIALIZED=0\n}\n\nto_hex() {\n    local val=$1\n    printf \"0x%x\" \"$val\"\n}\n\ndevmem_read() {\n    local reg_addr=$1\n    local mem_addr\n\n    mem_addr=$(to_hex $((mdio0_base_reg + reg_addr)))\n    devmem \"$mem_addr\"\n}\n\ndevmem_write() {\n    local reg_addr=$1\n    local val mem_addr\n\n    val=$(to_hex \"$2\")\n    mem_addr=$(to_hex $((mdio0_base_reg + reg_addr)))\n    devmem \"$mem_addr\" 32 \"$val\"\n}\n\nmdio_read() {\n    local addr=$1\n    local fire_busy clause_22 read_request reg_val read_reg_val ctrl_idle\n\n    fire_busy=$(( 1 << 31 ))\n    clause_22=$(( 1 << 28 ))\n    read_request=$(( 1 << 27 ))\n    reg_val=$(( fire_busy \\\n              | clause_22 \\\n              | read_request \\\n              | ( pseudo_phy_port_addr << 21 ) \\\n              | ( addr << 16 ) ))\n\n    devmem_write $mdio_ctrl_reg $reg_val\n    ctrl_idle=$(( 1 << 16 ))\n    desc=$(printf \"read 0x%x\" \"$addr\")\n    mdio_wait_op_complete \"$mdio_read_reg\" \"$ctrl_idle\" \"$ctrl_idle\" \"$desc\"\n\n    read_reg_val=$(devmem_read $mdio_read_reg)\n    echo $(( read_reg_val & 0xffff ))\n}\n\nmdio_write() {\n    local addr=$1\n    local val=$2\n    local fire_busy clause_22 write_request reg_val\n\n    fire_busy=$(( 1 << 31 ))\n    clause_22=$(( 1 << 28 ))\n    write_request=$(( 1 << 26 ))\n    reg_val=$(( fire_busy \\\n              | clause_22 \\\n              | write_request \\\n              | ( pseudo_phy_port_addr << 21 ) \\\n              | ( addr << 16 ) \\\n              | val ))\n\n    devmem_write $mdio_ctrl_reg \"$reg_val\"\n\n    desc=$(printf \"write 0x%x 0x%x\" \"$addr\" \"$val\")\n    mdio_wait_op_complete \"$mdio_ctrl_reg\" \"$fire_busy\" 0 \"$desc\"\n}\n\nmdio_wait_op_complete() {\n    local mdio_reg=$1 \n    local mask=$2\n    local wait_val=$3\n    local desc=$4\n    local timeout=5\n    local interval=0.1\n    local val\n\n    local time_limit=$(( $(date +%s) + timeout ))\n    while [ \"$(date +%s)\" -lt $time_limit ]\n    do\n        val=$(devmem_read \"$mdio_reg\")\n        if [ $(( val & \"$mask\" )) -eq \"$wait_val\" ]\n        then\n            return\n        fi\n        sleep $interval\n    done\n\n    echo \"Error: timed out waiting for operation to complete: $desc\" >&2\n    exit 1\n}\n\noob_page_reg=16\noob_addr_reg=17\noob_data_reg_base=24\n\nreg_read() {\n    local page=$1\n    local addr=$2\n    local data_size=$3\n    local data data_reg_num reg_val\n\n    data=$(reg_page_data \"$page\" 1)\n    mdio_write $oob_page_reg \"$data\"\n\n    data=$(reg_addr_data \"$addr\" 0x2)\n    mdio_write $oob_addr_reg \"$data\"\n\n    reg_wait_addr_reg_acked\n\n    # Read data registers\n    local val=0\n    num_data_regs=$(( ( data_size + 1 ) / 2 ))\n    local reg_idx=0\n    while [ $reg_idx -lt $num_data_regs ]\n    do\n        data_reg_num=$(( oob_data_reg_base + reg_idx ))\n        reg_val=$(mdio_read $data_reg_num)\n        val=$(( val | ( reg_val << ( reg_idx * 16 ) ) ))\n\n        reg_idx=$(( reg_idx + 1 ))\n    done\n\n    binary_str=$(val_to_binary_str \"$val\" \"$data_size\")\n    printf \"0x%x/0x%x 0x%x == $binary_str\\n\" \"$page\" \"$addr\" $val\n\n    reg_clear_access_enable\n}\n\nreg_write() {\n    local page=$1\n    local addr=$2\n    local val=$3\n    local data_size=$4\n    local data reg_val data_reg_num\n\n    data=$(reg_page_data \"$page\" 1)\n    mdio_write $oob_page_reg \"$data\"\n\n    # Write data registers\n    num_data_regs=$(( ( data_size + 1 ) / 2 ))\n    local reg_idx=0\n    while [ $reg_idx -lt $num_data_regs ]\n    do\n        data_reg_num=$(( oob_data_reg_base + reg_idx ))\n        reg_val=$(( ( val >> ( reg_idx * 16 ) ) & 0xffff ))\n        mdio_write $data_reg_num $reg_val\n\n        reg_idx=$(( reg_idx + 1 ))\n    done\n\n    data=$(reg_addr_data \"$addr\" 0x1)\n    mdio_write $oob_addr_reg \"$data\"\n\n    reg_wait_addr_reg_acked\n    reg_clear_access_enable\n}\n\nreg_wait_addr_reg_acked() {\n    local timeout=60\n    local interval=0.1\n    local time_limit response op\n\n    time_limit=$(( $(date +%s) + timeout ))\n    while [ \"$(date +%s)\" -lt $time_limit ]\n    do\n        response=$(mdio_read $oob_addr_reg)\n        op=$(( response & 0x3 ))\n        if [ $op -eq 0 ]\n        then\n            return\n        fi\n\n        sleep $interval\n    done\n\n    echo \"Error: timed out waiting for addr reg to be acknowledged\" >&2\n    exit 1\n}\n\nreg_clear_access_enable() {\n    data=$(reg_page_data 0 0)\n    mdio_write $oob_page_reg \"$data\"\n}\n\nreg_page_data() {\n    local page=$1\n    local access_enable=$2\n    local data=$(( page << 8 ))\n    data=$(( data | access_enable ))\n    echo $data\n}\n\nreg_addr_data() {\n    local addr=$1\n    local op=$2\n    local data=$(( addr << 8 ))\n    data=$(( data | op ))\n    echo $data\n}\n\nval_to_binary_str() {\n    local val=$1\n    local data_size=$2\n    local i=$(( data_size * 8 ))\n\n    while [ $i -gt 0 ]\n    do\n        i=$(( i - 1 ))\n        printf \"%d\" $(( ( val >> i ) & 0x1 ))\n        if [ $i -gt 0 ] && [ $(( i % 4 )) -eq 0 ]\n        then\n            printf \" \"\n        fi\n    done\n}\n\nhandle_read() {\n    local size=$1\n    shift\n    if [ $# -lt 2 ]\n    then\n        echo \"Error: missing arguments\" >&2\n        usage\n        exit 1\n    fi\n    local page=$1\n    local addr=$2\n    local data_size=$(( size / 8 ))\n    reg_read \"$page\" \"$addr\" \"$data_size\"\n}\n\nhandle_write() {\n    local size=$1\n    shift\n    if [ $# -lt 3 ]\n    then\n        echo \"Error: missing arguments\" >&2\n        usage\n        exit 1\n    fi\n    local page=$1\n    local addr=$2\n    local val=$3\n    local data_size=$(( size / 8 ))\n    reg_write \"$page\" \"$addr\" \"$val\" \"$data_size\"\n}\n\nif [ $# -lt 1 ]\nthen\n    echo \"Error: missing command\" >&2\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\ncase \"$command\" in\n    read8) cmd_type=\"read\"; size=\"8\";;\n    read16) cmd_type=\"read\"; size=\"16\";;\n    read32) cmd_type=\"read\"; size=\"32\";;\n    read64) cmd_type=\"read\"; size=\"64\";;\n    write8) cmd_type=\"write\"; size=\"8\";;\n    write16) cmd_type=\"write\"; size=\"16\";;\n    write32) cmd_type=\"write\"; size=\"32\";;\n    write64) cmd_type=\"write\"; size=\"64\";;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nmdio_init\n\nif [ \"$cmd_type\" = \"read\" ]\nthen\n    handle_read \"$size\" \"$@\"\nelse\n    handle_write \"$size\" \"$@\"\nfi\n", "num_lines": 343}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2235\n. /usr/local/bin/openbmc-utils.sh\n\ntrap handle_signal INT TERM QUIT\n\n# mdio prints in the format \"PAGE_HEX/OFFSET_HEX VALUE_HEX == VALUE_BIN\\n\"\nMDIO_READ_PATTERN=\"^.* (0x[a-fA-F0-9]+).*$\"\n\n# Global variable to stack tabs for formatting\ntab=\"\"\n\nusage() {\n    echo \"Read BCM53134P (oob switch) port status registers\"\n    echo \"\"\n    echo \"# To dump all port status\"\n    echo \"oob-status.sh\"\n    echo \"# To dump port status for ports in 0, 1, 2, IMP\"\n    echo \"oob-status.sh [Port(s)]\"\n    echo \"# To print only link status\"\n    echo \"oob-status.sh link_status [Port(s)]\"\n    echo \"# To print only link speed\"\n    echo \"oob-status.sh link_speed [Port(s)]\"\n    echo \"\"\n    echo \"Example:\"\n    echo \"\"\n    echo \"oob-status.sh link_status 0 IMP\"\n    echo \"Link Status:\"\n    echo \"\tPort 0: Link Up\"\n    echo \"\tPort IMP: Link Up\"\n\n}\n\nhandle_signal() {\n    echo \"Exiting because of signal\" >&2\n    exit 1\n}\n\ncheck_sts_args() {\n    # Convert arguments to port numbers\n    local port val\n    ret=\"$*\"\n    if [ $# -lt 1 ]; then\n       # No arguments: do all ports\n       ret=\"0 1 2 IMP\"\n    else\n        for port in \"$@\"; do\n            if [ \"${port^^}\" != \"IMP\" ] && (! [[ \"$port\" =~ ^[0-9]+$ ]] \\\n                || [ \"$port\" -lt 0 ] || [ \"$port\" -gt 2 ]); then\n                echo \"Invalid port $port\"\n                exit 1\n            fi\n        done\n    fi\n}\n\nport_to_val() {\n    local val\n    if [ \"$1\" == \"IMP\" ]; then\n        val=8\n    else\n        val=\"$1\"\n    fi\n    echo \"$val\"\n}\n\ndo_read_lnksts() {\n    local page offset result ports port val\n    page=0x1\n    offset=0x0\n    result=$(oob-mdio-util.sh read16 \"$page\" \"$offset\" \\\n        | sed -E \"s/$MDIO_READ_PATTERN/\\1/\")\n    ports=\"$*\"\n\n    printf \"%sLink status:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        val=$(port_to_val \"$port\")\n        val=$(( (result >> val) & 0x1 ))\n        case \"$val\" in\n            0)\n                printf \"%sPort: %s Link Down\\n\" \"$tab\" \"$port\"\n                ;;\n            1)\n                printf \"%sPort: %s Link Up\\n\" \"$tab\" \"$port\"\n                ;;\n        esac\n    done\n    tab=${tab:1}\n}\n\ndo_read_spdsts() {\n    local page offset result ports port val\n    page=0x1\n    offset=0x4\n    result=$(oob-mdio-util.sh read32 \"$page\" \"$offset\" \\\n        | sed -E \"s/$MDIO_READ_PATTERN/\\1/\")\n    ports=\"$*\"\n\n    printf \"%sLink speed:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        val=$(port_to_val \"$port\")\n        val=$(( (result >> (val * 2)) & 0x3 ))\n        case \"$val\" in\n            0)\n                printf \"%sPort: %s 10 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n            1)\n                printf \"%sPort: %s 100 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n            2)\n                printf \"%sPort: %s 1000 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n        esac\n    done\n    tab=${tab:1}\n}\n\nread_lnksts() {\n    check_sts_args \"$@\"\n    do_read_lnksts \"$ret\"\n}\n\nread_spdsts() {\n    check_sts_args \"$@\"\n    do_read_spdsts \"$ret\"\n}\n\nread_status() {\n    check_sts_args \"$@\"\n    printf \"%sStatus:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n    do_read_lnksts \"$ret\"\n    do_read_spdsts \"$ret\"\n    tab=${tab:1}\n}\n\n# Only allow one instance of script to run at a time.\nscript=$(realpath \"$0\")\nexec 100< \"$script\"\nflock -n 100 || { echo \"ERROR: $0 already running\" && exit 1; }\n\ncommand=\"$1\"\n\ncase \"$command\" in\n    link_status)\n        shift\n        read_lnksts \"$@\"\n        ;;\n    link_speed)\n        shift\n        read_spdsts \"$@\"\n        ;;\n    \"--help\")\n        usage\n        exit 1\n        ;;\n    *)\n        read_status \"$@\"\n        ;;\nesac\n", "num_lines": 187}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2034\nsource /usr/local/bin/dpm_utils.sh\n\nprog=\"$0\"\nusage() {\n    echo \"Usage: $prog [--clear] [--verbose ] (2-9)\"\n    echo\n    echo \"options:\"\n    echo \" --clear: clear faults after dumping them\"\n    echo \" --verbose: print debug messages to stderr\"\n    echo \"(2-9): PIM number\"\n}\n\nclear_faults=\"no\"\nwhile [ $# -gt 0 ]\ndo\n    case \"$1\" in\n        --clear)\n            clear_faults=\"yes\"\n            ;;\n        --verbose)\n            dpm_verbose=\"yes\"\n            ;;\n        *)\n            break\n            ;;\n    esac\n    shift\ndone\n\nif [ $# -lt 1 ]\nthen\n    echo \"Error: missing PIM number\" >&2\n    usage\n    exit 1\nfi\n\npim_num=\"$1\"\nif [ ! \"${pim_num##*[!0-9]*}\" ]\nthen\n    echo \"Error: invalid PIM number\" >&2\n    usage\n    exit 1\nfi\nif [ \"$pim_num\" -lt 2 ] || [ \"$pim_num\" -gt 9 ]\nthen\n    echo \"Error: invalid PIM number\" >&2\n    usage\n    exit 1\nfi\npim_idx=\"$((pim_num - 2))\"\n\npim_buses=(16 17 18 19 20 21 22 23)\n# P1 has a different PIM bus mapping, but the\n# wedge_is_smb_p1 function is not available at\n# the time this script runs.\npim_bus=\"${pim_buses[$pim_idx]}\"\nfault_source=\"PIM$pim_num\"\n\nclear_faults() {\n    bus=\"$pim_bus\"\n\n    update_clock \"$bus\"\n\n    misc_config=\"$(i2cget -y \"$bus\" 0x4e 0xfc s)\"\n    config_byte=\"$(echo \"$misc_config\" | awk '{print $1}')\"\n    b2=\"$(echo \"$misc_config\" | awk '{print $2}')\"\n    b3=\"$(echo \"$misc_config\" | awk '{print $3}')\"\n    b4=\"$(echo \"$misc_config\" | awk '{print $4}')\"\n\n    # In order for faults to be cleared in non-volatile store, the\n    # brownout bit in the misc_config byte needs to be cleared.\n    no_brown=$((config_byte & ~0x1))\n\n    print_debug \"$fault_source: clearing the brownout bit...\"\n    i2cset -y \"$bus\" 0x4e 0xfc \"$no_brown\" \"$b2\" \"$b3\" \"$b4\" s\n\n    print_debug \"Clearing $fault_source DPM logs...\"\n    i2cset -y \"$bus\" 0x4e 0xea 0 0 0 0 0 0 0 0 0 0 0 0 s\n\n    print_debug \"$fault_source: restoring the brownout bit...\"\n    i2cset -y \"$bus\" 0x4e 0xfc \"$config_byte\" \"$b2\" \"$b3\" \"$b4\" s\n}\n\nread_logs \"$pim_bus\" \"$fault_source\"\n\nif [ \"$clear_faults\" = \"yes\" ]\nthen\n    clear_faults\nfi\n", "num_lines": 111}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# This utility displays the inserted PIM types\n\npim_list=\"2 3 4 5 6 7 8 9\"\nfor pim in ${pim_list}; do\n    if ! wedge_is_pim_present \"$pim\"; then\n        echo \"PIM $pim: NOT INSERTED\"\n    else\n        pim_type='NOT DETECTED'\n        fru=\"$(/usr/local/bin/peutil \"$pim\" 2>&1)\"\n        if echo \"$fru\" | grep -q '88-16CD2'; then\n            pim_type='PIM16Q2'\n        elif echo \"$fru\" | grep -q '88-16CD'; then\n            pim_type='PIM16Q'\n        elif echo \"$fru\" | grep -q '88-8D'; then\n            pim_type='PIM8DDM'\n        fi\n        echo \"PIM $pim: $pim_type\"\n    fi\ndone\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif ! wedge_is_bmc_personality; then\n    echo \"uServer is not in BMC personality. Skipping all power-on sequences.\"\n    return\nfi\n\n# Only run board power up sequence is CPU is not up, otherwise this could\n# disrupt data plane\nif wedge_is_us_on; then\n    echo \"uServer is already up. Skipping board power-on sequence\"\nelse\n    echo \"uServer is not up. Running board power-on sequence\"\n    wedge_power_on_board\nfi\n\n# Now, double check if power is on, and do forced power up as needed.\necho \"Checking microserver power status ... \"\nif wedge_is_us_on; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    echo \"uServer still not up. Running forced power-up sequence\"\n    wedge_power.sh on -f\nfi\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nsetup_gpio_elbert_evt() {\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB1 BMC_ALIVE\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB3 CPLD_JTAG_SEL_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB4 CPU_TEMP_ALERT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB6 SCM_PWRGD\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB7 SMB_PWRGD\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF1 I2C_TPM_PIRQ_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOH0 BMC_BOARD_EEPROM_WP_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOH1 BMC_TEMP_ALERT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOI0 JTAG_TRST_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOS7 SMB_INTERRUPT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV0 BMC_SPI1_CS0_MUX_SEL\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV2 BMC_CHASSIS_EEPROM_WP_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX1 SPI2CS1#_GPIO86\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX2 SPI2CS2#_GPIO84\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX7 SPI_TPM_PIRQ_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOY2 CPU_OVERTEMP\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOY3 BMC_EMMC_RST_N\n}\n\nsetup_gpio_elbert_evt\n\ngpio_set_direction BMC_ALIVE in\ngpio_set_direction CPLD_JTAG_SEL_L out\ngpio_set_direction CPU_TEMP_ALERT in\ngpio_set_direction SCM_PWRGD in\ngpio_set_direction SMB_PWRGD in\ngpio_set_direction I2C_TPM_PIRQ_N in\ngpio_set_direction BMC_BOARD_EEPROM_WP_L out\ngpio_set_direction BMC_TEMP_ALERT  in\ngpio_set_direction SMB_INTERRUPT in\ngpio_set_direction BMC_SPI1_CS0_MUX_SEL out\ngpio_set_direction BMC_CHASSIS_EEPROM_WP_L out\ngpio_set_direction SPI_TPM_PIRQ_N in\ngpio_set_direction CPU_OVERTEMP in\ngpio_set_direction JTAG_TRST_L out\n\n# Once we set \"out\", output values will be random unless we set them\n# Set Default GPO values\ngpio_set_value CPLD_JTAG_SEL_L 1 # Disabled\ngpio_set_value BMC_SPI1_CS0_MUX_SEL 0 # BIOS\ngpio_set_value BMC_ALIVE 0 # Default\ngpio_set_value BMC_BOARD_EEPROM_WP_L 1 # Disabled\ngpio_set_value BMC_CHASSIS_EEPROM_WP_L 1 # Disabled\ngpio_set_value JTAG_TRST_L 1 # Disabled\n# Set BMC_EMMC_RST_N High to prevent EMMC disable\ngpio_set BMC_EMMC_RST_N 1\n", "num_lines": 80}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup_bcm53134.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Setup the speed on BCM53134 for eth0\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ncontrol_page=\"0x0\"\nport_state_reg=\"0xe\"\nport_state_reg_val=\"0x8b\"\nimp_rgmi_control_reg=\"0x60\"\nimp_rgmi_control_reg_val=\"0x0\"\n\n# Check BCM53134 registers\ncurr_speed=$(oob-mdio-util.sh read8 \"$control_page\" \"$port_state_reg\"|\n             cut -d' ' -f2)\ncurr_clk_dly=$(oob-mdio-util.sh read8 \"$control_page\" \"$imp_rgmi_control_reg\"|\n               cut -d' ' -f2)\nif [ \"$curr_speed\" == \"$port_state_reg_val\" ] && \\\n   [ \"$curr_clk_dly\" == \"$imp_rgmi_control_reg_val\" ]\nthen\n    # Register values are as expected\n    exit 0\nfi\n\necho \"BCM53134 registers not as expected. Configuring now.\"\necho \"Re-program the BCM53134 EEPROM to fix this permanently.\"\n\noob-mdio-util.sh write8 \"$control_page\" \"$port_state_reg\" \"$port_state_reg_val\"\noob-mdio-util.sh write8 \"$control_page\" \"$imp_rgmi_control_reg\" \\\n                        \"$imp_rgmi_control_reg_val\"\nexit 0\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# ELBERTTODO 442075 board_setup.sh\necho \"ELBERT BOARD SETUP NOT IMPLEMENTED YET\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\ni2c_device_add 0 0x50 24c512\nif ! wedge_is_bmc_personality; then\n    echo \"uServer is not in BMC personality. Skipping all power-on sequences.\"\n    return\nfi\n\n# Some devices occasionally fail to probe. Retry if this happens.\nhwmon_device_add() {\n    bus=\"$1\"\n    devIdHex=\"$2\"\n    driver=\"$3\"\n    devId=\"${devIdHex//0x/}\"\n    i2c_device_add \"$bus\" \"$devIdHex\" \"$driver\"\n\n    # Wait up to 2 seconds for the driver to load\n    i=0\n    while true; do\n        i=$((i+1))\n        # Check if device driver loaded successfully\n        if [ -d \"/sys/bus/i2c/devices/$bus-00$devId/hwmon/\" ]; then\n            break;\n        fi\n        if [ $i -gt 20 ]; then\n            echo \"Timed out waiting for $driver-$bus-$devId\"\n            break;\n        fi\n        sleep 0.1\n    done\n\n    # If device isn't loaded sucessfully, retry one more time\n    if [ ! -d \"/sys/bus/i2c/devices/$bus-00$devId/hwmon/\" ]; then\n        echo \"Probe of $driver-$bus-$devId failed. Retrying...\"\n        i2c_device_delete \"$bus\" \"$devIdHex\"\n        i2c_device_add \"$bus\" \"$devIdHex\" \"$driver\"\n    fi\n}\n\n# Calibrate TH4 MAX6581\ncalibrate_th4_max6581() {\n    i2cset -f -y 4 0x4d 0x4a 0x03\n    i2cset -f -y 4 0x4d 0x4b 0x1f\n    i2cset -f -y 4 0x4d 0x4c 0x03\n}\n\n# Probe FSCD devices first in case one module is taking too\n# long or is in bad shape\n# Supvervisor Inlet\nhwmon_device_add 11 0x4c max6658\nhwmon_device_add 4 0x4d max6581\ncalibrate_th4_max6581\n\n# SMBus 0\n# Currently not using I2C TPM\n# i2c_device_add 0 0x20 tpm_i2c_infineon\n# i2c_device_add 0 0x2e tpm_i2c_infineon\n\n# SMBus 3 - Switchcard VRD\nhwmon_device_add 3 0x4e ucd90160 # UCD90160\ni2c_device_add 3 0x60 raa228228  # RA228228\ni2c_device_add 3 0x62 isl68226   # ISL68226\nenable_switchcard_power_security\n\n# SMBus 4\ni2c_device_add 4 0x23 smbcpld\necho 0 > \"$PIM_SMB_MUX_RST\"\necho 0 > \"$PSU_SMB_MUX_RST\"\necho 1 > \"$SMB_TH4_I2C_EN_SYSFS\"\n# Switchcard EEEPROMs\ni2c_device_add 4 0x50 24c512\ni2c_device_add 4 0x51 24c512\ni2c_device_add 4 0x44 net_brcm\n\n# SMBus 6\ni2c_device_add 6 0x60 fancpld\n# Outlet Temperature\ni2c_device_add 6 0x4c max6658\n\n# SMBus 7 CHASSIS EEPROM\ni2c_device_add 7 0x50 24c512\n\n# SMBus 9 SCM DPM UCD90320\nretry_command 3 enable_power_security_mode 9 0x11 \"UCD90320U\"\nhwmon_device_add 9 0x11 ucd90320\ngpio_export_by_offset 9-0011 13 SCM_FPGA_LATCH_L\n\n# SMBus 10 SCM POWER\ni2c_device_add 10 0x30 cpupwr\ni2c_device_add 10 0x37 mempwr\n\n# SMBus 11 SCM TEMP, POWER\ni2c_device_add 11 0x40 pmbus\n\n# Bus  12 SCM CPLD, SCM EEPROM\ni2c_device_add 12 0x43 scmcpld\ni2c_device_add 12 0x50 24c512\n\n# SMBus 15\nhwmon_device_add 15 0x4a lm73\n\n# SMBus 2 PIM MUX, muxed as Bus 16-23\npim_index=(0 1 2 3 4 5 6 7)\n\npim_bus=(16 17 18 19 20 21 22 23)\nif wedge_is_smb_p1; then\n    # P1 has different PIM bus mapping\n    pim_bus=(16 17 18 23 20 21 22 19)\n    echo \"P1 SMB detected\"\nfi\n\nfor i in \"${pim_index[@]}\"\ndo\n    # PIM numbered 2-9\n    pim=$((i+2))\n    if wedge_is_pim_present \"$pim\"; then\n        # PIM 2-9, SMBUS 16-23\n        bus_id=\"${pim_bus[$i]}\"\n        i2c_device_add \"$bus_id\" 0x50 24c512  # EEPROM\n        # Only allow writes to certain registers for\n        # power controllers UCD9090/TPS546D24\n        retry_command 3 enable_tps546d24_wp \"$bus_id\" 0x16\n        retry_command 3 enable_tps546d24_wp \"$bus_id\" 0x18\n        i2c_device_add \"$bus_id\" 0x16 pmbus   # TPS546D24\n        i2c_device_add \"$bus_id\" 0x18 pmbus   # TPS546D24\n\n        fru=\"$(peutil \"$pim\" 2>&1)\"\n        if echo \"$fru\" | grep -q '88-16CD2'; then\n            echo \"PIM$pim has no UCD9090/LM73\"\n        else\n            retry_command 3 enable_power_security_mode \"$bus_id\" 0x4e \"UCD9090B\"\n            i2c_device_add \"$bus_id\" 0x4a lm73    # Temp sensor\n            i2c_device_add \"$bus_id\" 0x4e ucd9090 # UCD9090\n        fi\n\n        if echo \"$fru\" | grep -q '88-8D'; then\n            i2c_device_add \"$bus_id\" 0x40 pmbus # MP5023\n            i2c_device_add \"$bus_id\" 0x54 isl68224 # ISL68224\n            retry_command 3 maybe_enable_isl_wp \"$bus_id\" 0x54\n        fi\n    else\n        echo \"PIM${pim} not present... skipping.\"\n    fi\ndone\n\n# SMBus 5 PSU MUX, muxed as Bus 24-27\nfor id in 1 2 3 4\ndo\n    psu_prsnt=\"$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/psu\"$id\"_present)\"\n    if [ \"$((psu_prsnt))\" -eq 1 ]; then\n        # PSU 1-4, SMBUS 22-25\n        bus_id=$((23 + id))\n        echo \"Enable WRITE_PROTECT on PSU$id\"\n        retry_command 3 enable_psu_wp \"$bus_id\" 0x58\n        i2c_device_add \"$bus_id\" 0x58 psu_driver\n    else\n        echo \"PSU${id} not present... skipping.\"\n    fi\ndone\n\n# Print total number of devices.\ni2c_check_driver_binding\n\n# Apply lm_sensor threshold settings.\nsensors -s\n", "num_lines": 188}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n\n# This utility displays the FPGA versions in each PIM SPI Flash parition\n\necho \"------PIM-FLASH-CONFIG------\"\npartition_list=\"header_pim_base header_pim16q header_pim8ddm\"\nfor partition in ${partition_list}; do\n    PIM_REVISION_FILE=\"/tmp/.pim_spi_header_$partition\"\n    if [ ! -f \"$PIM_REVISION_FILE\" ]; then\n        # version is not cached, force read it\n        /usr/local/bin/fpga_util.sh \"$partition\" read \\\n                                    \"$PIM_REVISION_FILE\" > /dev/null 2>&1\n        if [ ! -f \"$PIM_REVISION_FILE\" ]; then\n            echo \"Failed to read header for $partition\"\n            exit 1\n        fi\n    fi\n    ver=\"$(hexdump -n2 \"$PIM_REVISION_FILE\" | cut -c 9-)\"\n    val_major=\"0x${ver:2:2}\"\n    val_minor=\"0x${ver:0:2}\"\n    if [ \"$((val_major))\" -eq 0 ]; then\n        echo \"${partition^^}: NOT PRESENT\"\n     elif [ \"$((val_major))\" -eq 255 ] && [ \"$((val_minor))\" -eq 255 ]; then\n        echo \"${partition^^}: NOT PRESENT\"\n    else\n        echo \"${partition^^}: $((val_major)).$((val_minor))\"\n    fi\ndone\n", "num_lines": 51}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2059\n. /usr/local/bin/openbmc-utils.sh\n\n\n# This utility displays the TH4 QSPI version in the QSPI flash\n\necho \"------QSPI-FLASH-CONFIG------\"\nQSPI_REVISION_FILE=\"/tmp/.qspi_spi_image\"\n\npartition=\"header_th4_qspi\"\nif [ ! -f \"$QSPI_REVISION_FILE\" ]; then\n    # version is not cached, force read it\n    /usr/local/bin/fpga_util.sh \"$partition\" read \\\n                                \"$QSPI_REVISION_FILE\" > /dev/null 2>&1\n    if [ ! -f \"$QSPI_REVISION_FILE\" ]; then\n        echo \"Failed to read $partition\"\n        exit 1\n    fi\nfi\n\nHEADER_OFFSET=0x2000\nHEADER_LEN=32\nLOADER_VERSION_OFFSET=0x4\nVERSION_OFFSET=0x10\nLOADER_BUILDDATE_OFFSET=0x1c\nVERSION_LEN=12\n\nhexbytes=()\nwhile IFS='' read -r line; do hexbytes+=(\"$line\"); done <<< \"$(\n   hexdump -v -e '/1 \"0x%x\\n\"' -s \"$HEADER_OFFSET\" -n \"$HEADER_LEN\" \\\n      \"$QSPI_REVISION_FILE\"\n)\"\n\nfwver=\"\"\nfoundnull=0\nfor h in \"${hexbytes[@]:$VERSION_OFFSET:$VERSION_LEN}\"\ndo\n    if (( h == 0 ))\n    then\n        foundnull=1\n        break\n    fi\n\n    if (( h < 0x20 || h > 0x7e ))\n    then\n        echo \"Error: non-printable characters detected\"\n        fwver=\"\"\n        break\n    fi\n\n    char=$(printf \"\\x\"\"${h#0x}\")\n    fwver=\"$fwver$char\"\ndone\n\nif (( foundnull == 0 ))\nthen\n    fwver=\"\"\nfi\n\nif [[ -z \"$fwver\" ]]\nthen\n    echo \"Error: failed to parse th4_qspi version\"\n    exit 1\nfi\n\n# Decode the firmware loader version\nLOADER_VERSION_OFFSET=0x4\nmjhigh=${hexbytes[$((LOADER_VERSION_OFFSET + 3 ))]}\nmjlow=${hexbytes[$((LOADER_VERSION_OFFSET + 2 ))]}\nmajor=$(( (mjhigh << 8) | mjlow ))\nmnhigh=${hexbytes[$((LOADER_VERSION_OFFSET + 1 ))]}\nmnlow=${hexbytes[$LOADER_VERSION_OFFSET]}\nminor=$(( (mnhigh << 8) | mnlow ))\n\n# Convert version string into major/minor int\n# e.g: D000_05 --> 53248.5\nfwver_major=\"$(echo \"$fwver\" | cut -d '_' -f 1)\"\nfwver_major_int=$(python -c \"print(int('$fwver_major',16))\")\nfwver_minor=\"$(echo \"$fwver\" | cut -d '_' -f 2)\"\nfwver_minor_int=$(python -c \"print(int('$fwver_minor',16))\")\n\nprintf \"FIRMWARE_LOADER_VERSION: %d.%d\\n\" $major $minor\necho \"FIRMWARE_VERSION: $fwver_major_int.$fwver_minor_int\"\necho \"FIRMWARE_STRING_VERSION: $fwver\"\n\n# Print the firmware loader build date\necho -n \"FIRMWARE_LOADER_BUILD_DATE: \"\nfor i in 3 2 1 0\ndo\n    printf \"%02d\" \"${hexbytes[$((LOADER_BUILDDATE_OFFSET + i))]#0x}\"\ndone\necho\n", "num_lines": 114}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole elbert system ungracefully\"\n    echo \"      -s -t [0-7]: Setting boot up time.\"\n    echo \"            0: 10 seconds (default), 1: 20 seconds, 2: 30 seconds, 3: 40 seconds\"\n    echo \"            4: 1 minute, 5: 2 minutes, 6: 5 minutes, 7: 10 minutes\"\n    echo\n    echo \"  pimreset: Power-cycle one or all PIM(s)\"\n    echo \"    options:\"\n    echo \"      -a  : Reset all PIMs or \"\n    echo \"      -2 , -3 , ... , -9 : Reset a single PIM (2, 3 ... 9) \"\n    echo\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    wedge_power_on_board\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n        logger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    wedge_power_off_board\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n        logger \"Successfully power off micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power off micro-server\"\n    fi\n    return $ret\n}\n\ndo_config_reset_duration() {\n   # Check valid numeric value\n    duration=$1\n    echo \"$duration\" | grep -q '^[0-7]$'\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        usage\n        exit 1\n    else\n        values=( 10 20 30 40 1 2 5 10 )\n        units=\"seconds\"\n        if [ \"$duration\" -eq 4 ]; then\n            units=\"minute\"\n        elif [ \"$duration\" -gt 4 ]; then\n            units=\"minutes\"\n        fi\n        echo \"$duration\" > \"$SMBCPLD_SYSFS_DIR\"/powercycle_duration\n        logger \"Waiting ${values[$duration]} $units for the system boot up\"\n        echo \"Waiting ${values[$duration]} $units for the system boot up\"\n    fi\n}\n\ndo_sync() {\n   # Try to flush all data to MMC and remount the drive read-only. Sync again\n   # because the remount is asynchronous.\n   partition=\"/dev/mmcblk0\"\n   mountpoint=\"/mnt/data1\"\n\n   sync\n   # rsyslogd logs to eMMC, so we must stop it prior to remouting.\n   kill -TERM \"$(cat /var/run/rsyslogd.pid)\"\n   sleep .05\n   if [ -e $mountpoint ]; then\n      retry_command 5 mount -o remount,ro $partition $mountpoint\n      sleep 1\n   fi\n   sync\n}\n\ndo_reset() {\n    local system opt\n    system=0\n    timer=0\n    duration=0\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            t)\n                timer=1\n                duration=$OPTARG\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        if [ $timer -eq 1 ]; then\n            do_config_reset_duration \"$duration\"\n        fi\n        # Log before do_sync since do_sync kills logging.\n        logger \"Power reset the whole system ...\"\n        do_sync\n        echo -n \"Power reset the whole system ...\"\n        sleep 1\n        echo 0xde > \"$PWR_SYSTEM_SYSFS\"\n        sleep 8\n        # The chassis shall be reset now... if not, we are in trouble\n        echo \" Failed\"\n        return 254\n    else\n        do_off\n        sleep 1\n        do_on\n    fi\n\n}\n\ntoggle_pim_reset() {\n    pim=$1\n    # Set the selected PIM to powercycle\n    for slot in 2 3 4 5 6 7 8 9; do\n        if [ \"$pim\" -eq 0 ] || [ \"$slot\" -eq \"$pim\" ]; then\n            echo \"Reset PIM${slot}...\"\n            echo '1' > \"$SMBCPLD_SYSFS_DIR\"/pim\"$slot\"_reset\n            touch /tmp/.pim\"$slot\"_reset\n        fi\n    done\n    echo 'Waiting for PIMs to be re-enabled...'\n\n    i=0\n    while true; do\n        i=$((i+1))\n        # Wait for all cards to be be re-enabled\n        if [ \"$(head -n 1 \"$SMBCPLD_SYSFS_DIR\"/pim_reset)\" == '0x0' ]; then\n            echo 'All cards enabled!'\n            break;\n        fi\n\n        if [ $i -gt 60 ]; then\n            echo 'Timed out waiting for cards to be re-enabled...'\n            exit 1\n        fi\n        sleep 1\n     done\n\n    # Re-initialize reset pims\n    for slot in 2 3 4 5 6 7 8 9; do\n        if [ \"$pim\" -eq 0 ] || [ \"$slot\" -eq \"$pim\" ]; then\n            if wedge_is_pim_present \"$slot\"; then\n                power_on_pim \"$slot\"\n            fi\n        fi\n    done\n}\n\ndo_pimreset() {\n    local pim opt retval\n    retval=0\n    pim=-1\n    while getopts \"23456789a\" opt; do\n        case $opt in\n            a)\n                pim=0\n                ;;\n            2)\n                pim=2\n                ;;\n            3)\n                pim=3\n                ;;\n            4)\n                pim=4\n                ;;\n            5)\n                pim=5\n                ;;\n            6)\n                pim=6\n                ;;\n            7)\n                pim=7\n                ;;\n            8)\n                pim=8\n                ;;\n            9)\n                pim=9\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    if [ $pim -eq -1 ]; then\n      usage\n      exit 1\n    fi\n\n    toggle_pim_reset $pim\n\n    return $retval\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        ;;\n    pimreset)\n        do_pimreset \"$@\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nexit $?\n", "num_lines": 318}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ELBERT's SCM MAC address is the first address of the block\n# allocated from \"Extended MAC Base\" field in SCM's EEPROM.\nweutil SCM 2>&1 | grep \"MAC Base\" | cut -d ' ' -f 4\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.eth0.pid\"\n\n# shellcheck disable=SC2086\nmac_to_ll() {\n  IFS=':'; set $1; unset IFS\n  echo \"fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6\" | \\\n    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'\n}\n\nexp_ll=\nll=\n\nfor _ in {1..30}; do\n  # wait getting address from NC-SI\n  if [ \"$(cat /sys/class/net/eth0/addr_assign_type)\" = \"3\" ]; then\n    if [ \"$(cat /sys/class/net/eth0/address)\" != \"$(cat /sys/class/net/br0/address)\" ]; then\n      ifconfig br0 hw ether \"$(cat /sys/class/net/eth0/address)\"\n    fi\n    exp_ll=$(mac_to_ll \"$(cat /sys/class/net/eth0/address)\")\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    br_ll=$(ip -6 addr show dev br0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    # re-generate link-local address\n    if [ \"$ll\" != \"$exp_ll\" ]; then\n      ip -6 addr flush dev eth0\n      echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n      echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    fi\n    if [ \"$br_ll\" != \"$exp_ll\" ]; then\n      ip -6 addr flush dev br0\n      echo 1 > /proc/sys/net/ipv6/conf/br0/addr_gen_mode\n      echo 0 > /proc/sys/net/ipv6/conf/br0/addr_gen_mode\n    fi\n    break;\n  fi\n  sleep 1\ndone\n\nif [[ \"$ll\" != \"$exp_ll\" || \"$br_ll\" != \"$exp_ll\" ]]; then\n  for _ in {1..100}; do\n    usleep 10000\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    br_ll=$(ip -6 addr show dev br0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [[ \"$ll\" = \"$exp_ll\" && \"$br_ll\" = \"$exp_ll\" ]]; then\n      break;\n    fi\n  done\nfi\n\nexec dhclient -6 -d -D LL --address-prefix-len 64 -pf ${pid} br0 \"$@\"\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\nDUMP_DIR='/tmp/crashdump/output'\nMAP_DIR='/var/bafi'\nPARSE_FILE=\"$DUMP_DIR/bafi.log\"\nDUMP_FILE=\"$DUMP_DIR/sensordump.log\"\nDUMP_UTIL='/usr/bin/crashdump'\nPARSE_UTIL='/usr/bin/bafi'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\nACD=true\n\nif [ ! -f $DUMP_UTIL ] ; then\n  # shellcheck disable=SC1091\n  . /usr/local/bin/gpio-utils.sh\n\n  ACD=false\n  DUMP_FILE=\"$DUMP_DIR/autodump.log\"\n  DUMP_UTIL='/usr/local/bin/dump.sh'\n  mkdir -p $DUMP_DIR\nfi\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=$(cat $PID_FILE) || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\nkv set fru1_crashdump $((sys_runtime+630))\n\n# kill previous autodump if exist\nif [ -n \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  killall -s 9 dump.sh >/dev/null 2>&1\n  killall -s 9 peci-util >/dev/null 2>&1\n  killall -s 9 crashdump >/dev/null 2>&1\n  killall -s 9 bafi >/dev/null 2>&1\n\n  if [ \"$ACD\" != true ] ; then\n    { echo -n \"(uncompleted) Auto Dump End at \"; date; } >> $DUMP_FILE\n    tar zcf '/mnt/data/autodump_uncompleted.tar.gz' -C $DUMP_DIR \"$(basename $DUMP_FILE)\"\n  fi\nfi\nunset OLDPID\n\nDELAY_SEC=30\nSENSOR_HISTORY=180\n\nwhile test $# -gt 0\ndo\n  case \"$1\" in\n  --now)\n    DELAY_SEC=0\n    ;;\n  *)\n    echo \"unknown argument $1\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n  sleep ${DELAY_SEC}\nfi\n\n# Block Power Cycle\n/usr/local/bin/ipmb-util 8 0x68 0xd8 0xf2 0x00 0x07 0x01\necho \"Auto Dump Started\"\n\nLOGS=$(basename $DUMP_FILE)\nif [ \"$ACD\" == true ] ; then\n  $DUMP_UTIL\n\n  mode=$(($(/usr/bin/kv get mb_skt) >> 1))\n  if [ \"$mode\" -eq 0 ]; then\n    PARSE_UTIL+=\" -p $MAP_DIR/4s_device_map.json -m $MAP_DIR/4s_memory_map.json\"\n  elif [ \"$mode\" -eq 1 ]; then\n    PARSE_UTIL+=\" -p $MAP_DIR/ex_device_map.json -m $MAP_DIR/ex_memory_map.json\"\n  fi\n\n  # shellcheck disable=SC2012\n  LOG_FILE=$(ls $DUMP_DIR/crashdump_* -t1 |head -n 1)\n  ${PARSE_UTIL} \"$LOG_FILE\" > $PARSE_FILE 2>&1\n\n  LOGS=\"$LOGS $(basename \"$LOG_FILE\") $(basename $PARSE_FILE)\"\n  { echo -n \"Sensor Dump Start at \"; date; } > $DUMP_FILE\n\nelse\n\n  { echo -n \"Auto Dump Start at \"; date; } > $DUMP_FILE\n\n  # CPU0\n  { $DUMP_UTIL 48 coreid; $DUMP_UTIL 48 msr; } >> $DUMP_FILE 2>&1\n\n  # CPU1\n  if [ \"$(gpio_get_value FM_CPU1_SKTOCC_LVT3_PLD_N)\" -eq \"0\" ]; then\n    { $DUMP_UTIL 49 coreid; $DUMP_UTIL 49 msr; } >> $DUMP_FILE 2>&1\n  else\n    echo \"<<---------- CPU1 is not present, skip it. ---------->>\" >> $DUMP_FILE\n  fi\n\n  # PCIe\n  #$DUMP_UTIL pcie >> $DUMP_FILE 2>&1\nfi\n\n# Sensors\n{\n  echo \"\"\n  echo \"Sensor history of last ${SENSOR_HISTORY}s at dump:\"\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\n\n  echo \"Sensor threshold at dump:\"\n  /usr/local/bin/sensor-util all --threshold\n\n  echo -n \"Dump End at \"; date\n} >> $DUMP_FILE 2>&1\n\n# shellcheck disable=SC2086\ntar zcf $LOG_ARCHIVE -C $DUMP_DIR $LOGS\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\n\n# Unblock Power Cycle\n/usr/local/bin/ipmb-util 8 0x68 0xd8 0xf2 0x00 0x07 0x00\necho \"Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 137}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROGRAM=$0\nPECI_UTIL=\"/usr/local/bin/peci-util\"\nCMD_DIR=\"/etc/peci\"\n\nCPU_ID=$(($1 - 48))\nDUMP_FILE=crashdump_p\"$CPU_ID\"_\n\n#2S:MODE=2, 4S_EX:MODE=1, 4S_EP:MODE=0\nMODE=$(($(/usr/bin/kv get mb_skt) >> 1))\nif [ \"$MODE\" -eq 2 ]; then\n  MAX_CPU=2;\nelse\n  MAX_CPU=4;\nfi\n\nfunction print_help_msg {\n  for ((i=0; i<MAX_CPU; i++))\n  do\n    addr=$((i+48))\n    echo \"$PROGRAM $addr coreid  ==> for CPU $i CoreID\"\n    echo \"$PROGRAM $addr msr     ==> for CPU $i MSR\"\n  done\n  echo \"$PROGRAM pcie       ==> for PCIe\"\n  echo \"$PROGRAM dwr        ==> for DWR check\"\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    $PECI_UTIL -i 10 -r 5 --file /dev/stdin\n}\n\n# read command from stdin\nfunction execute_cmd {\n  # echo \"Use BMC wired PECI interface\"\n  cat | execute_via_peci\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  RESULT=0\n  # BUS\n  RESULT=$((RESULT | (($1 & 0xFF) << 20) ))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15) ))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12) ))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0) ))\n  printf \"0x%x 0x%x 0x%x 0x%x\"\\\n    $(( RESULT & 0xFF )) \\\n    $(( (RESULT >> 8) & 0xFF )) \\\n    $(( (RESULT >> 16) & 0xFF )) \\\n    $(( (RESULT >> 24) & 0xFF ))\n  return 0\n}\n\nfunction pcie_dump {\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    execute_cmd < $CMD_DIR/crashdump_pcie\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n  # Completion Code\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n  # Root port buses\n  ROOT_BUSES=$(echo \"$RES\" | awk '{printf \"0x%s 0x%s 0x%s\", $3, $4, $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        echo \"Find Root Port Bus $ROOT Dev $DEV...\"\n        RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr \"$ROOT\" $DEV 0x00 0x18)\" | execute_cmd)\n        echo \"$RES\"\n        CC=$(echo \"$RES\"| awk '{print $1;}')\n        SECONDARY_BUS=0x$(echo \"$RES\"| awk '{print $3;}')\n        SUBORDINATE_BUS=0x$(echo \"$RES\"| awk '{print $4;}')\n        if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n          for (( BUS=SECONDARY_BUS; BUS<=SUBORDINATE_BUS; BUS++ )); do\n            BUS_MS_NIBBLE=$(printf \"%x\" $((BUS >> 4)) )\n            BUS_LS_NIBBLE=$(printf \"%x\" $((BUS & 0xF)) )\n            [ -r $CMD_DIR/crashdump_pcie_bus ] && \\\n              sed \"s/<BUSM>/$BUS_MS_NIBBLE/g; s/<BUSL>/$BUS_LS_NIBBLE/g\" $CMD_DIR/crashdump_pcie_bus | execute_cmd\n          done\n        fi\n      done\n    done\n  fi\n}\n\nfunction dwr_dump {\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n  DWR=0x$(echo \"$RES\"| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\necho \"\"\n\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"pcie\" ]; then\n  pcie_dump\n  exit 0\nfi\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"dwr\" ]; then\n  dwr_dump\n  exit $?\nfi\n\nif [ \"$#\" -ne 2 ]; then\n\n  print_help_msg\n  exit 1\n\nelif [ \"$CPU_ID\" -ge \"$MAX_CPU\" ] || [ \"$CPU_ID\" -lt 0 ]; then\n\n  print_help_msg\n  exit 1\n\nelif [ \"$2\" = \"coreid\" ] || [ \"$2\" = \"msr\" ]; then\n\n  DUMP_FILE=\"$CMD_DIR/${DUMP_FILE}$2\"\n  if [ -r \"$DUMP_FILE\" ]; then\n    execute_cmd < \"$DUMP_FILE\"\n  else\n    echo \"$DUMP_FILE\" not exist\n  fi\n  exit 0\n\nfi\n\nexit 0\n", "num_lines": 174}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\n# shellcheck disable=SC2039\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Setup fan speed... \"\n/usr/local/bin/ipmb-util 8 0x68 0xd8 0x08 0x46 0xff\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\n\nhost=$(($(/usr/bin/kv get mb_skt) & 0x1))  #Master:host=0, Slave:host=1\nmode=$(($(/usr/bin/kv get mb_skt) >> 1))   #2S:mode=2, 4S_EX:mode=1, 4S_EP:mode=0\n\n#echo host = $host\n#echo mode = $mode\n\nif [ \"$mode\" -eq 2 ]; then\n  echo probe 2s fan table\n  ln -s /etc/fsc-config2s.json ${default_fsc_config_path}\nelif [ \"$host\" -eq 0 ]; then  #4S Master Mode\n  echo probe 4s master fan table\n  ln -s /etc/fsc-config4s_M.json ${default_fsc_config_path}\nelse  #4S Slave\n  echo probe slave fan table\n  ln -s /etc/fsc-config_Slave.json ${default_fsc_config_path}\nfi\n\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# shellcheck disable=SC2039\necho -n \"Setup gpio monitoring for angelslanding... \"\n\n/usr/local/bin/gpiod &\n\necho \"done.\"\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 5\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 5 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 6 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 8 2\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\nmode=$(($(/usr/bin/kv get mb_skt) >> 1))  #2S:mode=2 4S_EX:mode=1 4S_EP:mode=0\nif [ $mode -eq 2 ]; then\n  addr=0x1010\nelse\n  addr=$((0x1010 | $(/usr/bin/kv get mb_pos)))\nfi\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-0/new_device  #USB DBG\necho slave-mqueue $addr > /sys/bus/i2c/devices/i2c-2/new_device   #BMC Slave Addr\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-5/new_device  #ME\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-6/new_device  #JG7\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device  #CM\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_2 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_5 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_6 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_8 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 58}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#This is workaround for IPV4 lost There is slim chance ipv4 lost when AC cycle. \n#DHCP Client can't get OFFER package from server.\n#This script is for reinitial ipv4 to prevnet it lost. \n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKERNEL_VERSION=$(uname -r)\nif [[ ${KERNEL_VERSION} != 4.1.* ]]; then\n  for _ in {1..10}; do\n    ip=$(ip -4 address |grep br0 |grep inet)\n    if [ -z \"$ip\" ]; then\n      # shellcheck disable=SC2009\n      vid=$(ps |grep \"dhclient.eth0\" |grep -v grep |awk '{print $1}')\n      kill \"$vid\"\n      dhclient -d -pf /var/run/dhclient.eth0.pid br0 > /dev/null 2>&1 &\n      sleep 10\n    else\n      break;\n    fi\n  done\nfi\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n/etc/init.d/setup-bridge.sh &\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n/etc/init.d/eth0_mac_fixup.sh &\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\n\nncsi_cmd() {\n  for _ in {0..2}; do\n    resp=$(/usr/local/bin/ncsi-util \"$@\" | grep \"COMMAND_COMPLETED(0x0000)\")\n    if [ \"$resp\" != \"\" ]; then\n      break\n    fi\n    sleep 0.1\n  done\n}\n\nasic_mac_check() {\n  mac3=$(/usr/local/bin/ncsi-util 0x17 | grep \"mac_3\" | awk '{print $3}')\n\n  if [ \"$mac3\" == \"0x0\" ]; then\n    logger -s -p user.warn -t setup-bridge \"Recover Bridge MAC Address Filter\"\n    ncsi_cmd 0x0e \"${mac_peer[@]:1}\" 0x02 0x01\n    ncsi_cmd 0x03\n  fi\n}\n\nusb_dev_lost() {\n  loop=0\n  while true; do\n    usb_pre=$(ifconfig -a | grep usb)\n\n    if [ \"$usb_pre\" == \"\" ]; then\n      echo \"==Lost Usb Ethernet Device==\"\n      break\n    elif [ $loop -ge 3 ]; then\n      loop=0\n      asic_mac_check\n    fi\n\n    loop=$((loop + 1))\n    sleep 10\n  done\n}\n\nusb_dev_detect() {\n  while true; do\n    usb_pre=$(ifconfig -a | grep usb)\n\n    if [ \"$usb_pre\" != \"\" ]; then\n      echo \"==Find Usb Ethernet Device==\"\n      break\n    fi\n\n    sleep 10\n  done\n}\n\n\n#Check MAC Filter for AL\nfor _ in {0..2}; do\n  mapfile mac <<< \"$(/usr/local/bin/ncsi-util 0x17 | grep -E \"mac_[1-2]\" | awk '{print $3}')\"\n  if [ ${#mac[@]} -ne 2 ]; then\n    continue\n  fi\n\n  mac_al=$(for i in {24..0..8}; do printf \"%02x:\" $((mac[0]>>i & 0xff)); done; \\\n        printf %02x:%02x $((mac[1]>>24 & 0xff)) $((mac[1]>>16 & 0xff)))\n  exp_mac=$(cat /sys/class/net/eth0/address)\n  if [ \"$exp_mac\" == \"$mac_al\" ]; then\n    break\n  fi\n  logger -s -p user.warn -t setup-bridge \"Recover MAC Address Filter: $mac_al to $exp_mac\"\n  IFS=\":\" read -r -a mac <<< \"$exp_mac\"\n  mac_al=(\"${mac[@]/#/0x}\")\n  ncsi_cmd 0x0e \"${mac_al[@]}\" 0x01 0x01\n  ncsi_cmd 0x03\ndone\n\n\n#Detect Cable Present\nwhile true; do\n  cable_pre1=$(($(gpio_get PRSNT_PCIE_CABLE_1_N)))\n  cable_pre2=$(($(gpio_get PRSNT_PCIE_CABLE_2_N)))\n\n  if [[ \"$cable_pre1\" -eq 0 || \"$cable_pre2\" -eq 0 ]]; then\n    echo \"==Usb Cable Present==\"\n    break\n  fi\n\n  sleep 10\ndone\n\n#Detect USB Ethernet Device\nusb_dev_detect\n\n\necho \"Initialize IP Bridge...\"\n\n#Get EP/CC MAC Address\nposition=$(($(/usr/bin/kv get mb_pos)))\nmode=$(($(/usr/bin/kv get mb_skt) >> 1))  #2S:mode=2, 4S_EX:mode=1, 4S_EP:mode=0\n\nif [[ \"$position\" -eq 0 || \"$mode\" -eq 2 ]]; then\n  peer_name=\"EP\"\n  peer_addr=\"0x2c\"\nelse\n  peer_name=\"CC\"\n  peer_addr=\"0x2e\"\nfi\n\nwhile true; do\n  echo \"Get $peer_name MAC\"\n  IFS=\" \" read -r -a mac <<< \"$(/usr/local/bin/ipmb-util 6 $peer_addr 0x30 0x02 0x00 0x05 2>/dev/null)\"\n  #mac=(11 78 03 9B 96 FC 99)\n  if [[ ${#mac[@]} -ge 7 && ${mac[0]} == \"11\" && $((16#${mac[1]} & 1)) -ne 1 ]]; then\n    if [ \"${mac[*]:1}\" != \"00 00 00 00 00 00\" ]; then\n      echo \"==Get MAC address Success==\"\n      break\n    fi\n  fi\n\n  sleep 3\ndone\n\n#Set MAC Filter for EP/CC\nmac_peer=(\"${mac[@]/#/0x}\")\necho \"Set MAC Address Filter for $peer_name: ${mac_peer[*]:1}\"\nncsi_cmd 0x0e \"${mac_peer[@]:1}\" 0x02 0x01\nncsi_cmd 0x03\n\nbrctl addif br0 usb0\nip link set up usb0\n\n\necho \"Detect USB Lost...\"\nwhile true; do\n  usb_dev_lost\n  usb_dev_detect\n  brctl addif br0 usb0\n  ip link set up usb0\n  sleep 5\ndone\n", "num_lines": 143}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Initial CMC Config\"\n#Unblock command\n/usr/local/bin/ipmb-util 8 0x68 0xd8 0xf2 0x00 0xff 0x00\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n. /usr/local/bin/i2c-utils.sh\n\n\n# FM_BOARD_BMC_REV_ID0\ngpio_export FM_BOARD_BMC_REV_ID0 GPIOA0\n\n# FM_BOARD_BMC_REV_ID1 / FM_CPU0_THERMTRIP_LVT3_PLD_N\ngpio_export FM_CPU0_THERMTRIP_LVT3_PLD_N GPIOA1\nln -n /tmp/gpionames/FM_CPU0_THERMTRIP_LVT3_PLD_N /tmp/gpionames/FM_BOARD_BMC_REV_ID1\n\n# BMC_EMMC_RST_N\ngpio_export BMC_EMMC_RST_N GPIOA2\n\n# FM_SPD_DDRCPU_LVLSHFT_EN\ngpio_export FM_SPD_DDRCPU_LVLSHFT_EN GPIOA3\n\n# SMB_SLOT1_ALT_N\ngpio_export SMB_SLOT1_ALT_N GPIOA6\n\n# SMB_SLOT2_ALT_N\ngpio_export SMB_SLOT2_ALT_N GPIOA7\n\n\n# FM_BOARD_BMC_SKU_ID0 / FM_MEM_THERM_EVENT_CPU0_LVT3_N\ngpio_export FM_MEM_THERM_EVENT_CPU0_LVT3_N GPIOB0\nln -n /tmp/gpionames/FM_MEM_THERM_EVENT_CPU0_LVT3_N /tmp/gpionames/FM_BOARD_BMC_SKU_ID0\n\n# FM_BOARD_BMC_SKU_ID1 / FM_MEM_THERM_EVENT_CPU1_LVT3_N\ngpio_export FM_MEM_THERM_EVENT_CPU1_LVT3_N GPIOB1\nln -n /tmp/gpionames/FM_MEM_THERM_EVENT_CPU1_LVT3_N /tmp/gpionames/FM_BOARD_BMC_SKU_ID1\n\n# FM_BOARD_BMC_SKU_ID2 / FM_CPU0_FIVR_FAULT_LVT3_PLD\ngpio_export FM_CPU0_FIVR_FAULT_LVT3_PLD GPIOB2\nln -n /tmp/gpionames/FM_CPU0_FIVR_FAULT_LVT3_PLD /tmp/gpionames/FM_BOARD_BMC_SKU_ID2\n\n# FM_BOARD_BMC_SKU_ID3 / FM_CPU1_FIVR_FAULT_LVT3_PLD\ngpio_export FM_CPU1_FIVR_FAULT_LVT3_PLD GPIOB3\nln -n /tmp/gpionames/FM_CPU1_FIVR_FAULT_LVT3_PLD /tmp/gpionames/FM_BOARD_BMC_SKU_ID3\n\n# FM_BOARD_BMC_SKU_ID4\ngpio_export FM_BOARD_BMC_SKU_ID4 GPIOB4\n\n# FM_BOARD_BMC_SKU_ID5\ngpio_export FM_BOARD_BMC_SKU_ID5 GPIOB5\n\n# FM_CPU0_PROCHOT_LVT3_BMC_N\ngpio_export FM_CPU0_PROCHOT_LVT3_BMC_N GPIOB6\n\n# FM_CPU1_PROCHOT_LVT3_BMC_N\ngpio_export FM_CPU1_PROCHOT_LVT3_BMC_N GPIOB7\n\n\n# FM_BOARD_BMC_REV_ID2 / FM_CPU1_THERMTRIP_LVT3_PLD_N\ngpio_export FM_CPU1_THERMTRIP_LVT3_PLD_N GPIOD0\nln -n /tmp/gpionames/FM_CPU1_THERMTRIP_LVT3_PLD_N /tmp/gpionames/FM_BOARD_BMC_REV_ID2\n\n# IRQ_TPM_BMC_SPI_N\ngpio_export IRQ_TPM_BMC_SPI_N GPIOD1\n\n# SMB_BMC_ADM1278_ALT_N\ngpio_export SMB_BMC_ADM1278_ALT_N GPIOD6\n\n# SMB_BMC_ADM1278_RST_N\ngpio_export SMB_BMC_ADM1278_RST_N GPIOD7\n\n\n# FP_BMC_RST_BTN_N\ngpio_export FP_BMC_RST_BTN_N GPIOE0\n\n# RST_BMC_RSTBTN_OUT_R_N, power reset to PCH\ngpio_export RST_BMC_RSTBTN_OUT_R_N GPIOE1\ngpio_set RST_BMC_RSTBTN_OUT_R_N 1\n\n# FM_BMC_PWR_BTN_R_N\ngpio_export FM_BMC_PWR_BTN_R_N GPIOE2\n\n# FM_BMC_PWRBTN_OUT_R_N, power button to CPLD\ngpio_export FM_BMC_PWRBTN_OUT_R_N GPIOE3\ngpio_set FM_BMC_PWRBTN_OUT_R_N 1\n\n# JTAG_MUX_SEL_0\ngpio_export JTAG_MUX_SEL_0 GPIOE4\ngpio_set JTAG_MUX_SEL_0 1\n\n# JTAG_MUX_SEL_1\ngpio_export JTAG_MUX_SEL_1 GPIOE5\ngpio_set JTAG_MUX_SEL_1 1\n\n# FP_FAULT_LED_N\ngpio_export FP_FAULT_LED_N GPIOE6\ngpio_set FP_FAULT_LED_N 1\n\n\n# FM_CPU_ERR0_LVT3_N\ngpio_export FM_CPU_ERR0_LVT3_N GPIOF0\n\n# FM_CPU_ERR1_LVT3_N\ngpio_export FM_CPU_ERR1_LVT3_N GPIOF1\n\n# FM_CPU_ERR2_LVT3_N\ngpio_export FM_CPU_ERR2_LVT3_N GPIOF2\n\n# FM_BMC_DEBUG_ENABLE_N\ngpio_export FM_BMC_DEBUG_ENABLE_N GPIOF3\n\n# FM_BMC_UV_ADR_TRIGGER_EN\ngpio_export FM_BMC_UV_ADR_TRIGGER_EN GPIOF4\n\n# FM_BMC_FORCE_ADR_N\ngpio_export FM_BMC_FORCE_ADR_N GPIOF5\n\n# RST_PLTRST_BMC_N\ngpio_export RST_PLTRST_BMC_N GPIOF6\n\n# IRQ_BMC_PRDY_N\ngpio_export IRQ_BMC_PRDY_N GPIOF7\n\n\n# FM_CPU1_DISABLE_COD_N\ngpio_export FM_CPU1_DISABLE_COD_N GPIOG0\n\n# FM_CPU_MSMI_CATERR_LVT3_N\ngpio_export FM_CPU_MSMI_CATERR_LVT3_N GPIOG1\n\n# FM_PCH_BMC_THERMTRIP_N\ngpio_export FM_PCH_BMC_THERMTRIP_N GPIOG2\n\n# BMC_READY_N\ngpio_export BMC_READY_N GPIOG3\ngpio_set BMC_READY_N 1\n# To disable Reset Tolerant\ndevmem_clear_bit 0x1e78003c 19\n\n# IRQ_NMI_EVENT_N\ngpio_export IRQ_NMI_EVENT_N GPIOG4\n\n# IRQ_BMC_PCH_SMI_LPC_N\ngpio_export IRQ_BMC_PCH_SMI_LPC_N GPIOG5\n\n# IRQ_SMB3_M2_ALERT_N\ngpio_export IRQ_SMB3_M2_ALERT_N GPIOG6\n\n\n# LED_POSTCODE_0\ngpio_export LED_POSTCODE_0 GPIOH0\n\n# LED_POSTCODE_1\ngpio_export LED_POSTCODE_1 GPIOH1\n\n# LED_POSTCODE_2\ngpio_export LED_POSTCODE_2 GPIOH2\n\n# LED_POSTCODE_3\ngpio_export LED_POSTCODE_3 GPIOH3\n\n# LED_POSTCODE_4\ngpio_export LED_POSTCODE_4 GPIOH4\n\n# LED_POSTCODE_5\ngpio_export LED_POSTCODE_5 GPIOH5\n\n# LED_POSTCODE_6\ngpio_export LED_POSTCODE_6 GPIOH6\n\n# LED_POSTCODE_7\ngpio_export LED_POSTCODE_7 GPIOH7\n\n\n# PRSNT_PCIE_CABLE_1_N\ngpio_export PRSNT_PCIE_CABLE_1_N GPIOI0\n\n# PRSNT_PCIE_CABLE_2_N\ngpio_export PRSNT_PCIE_CABLE_2_N GPIOI1\n\n# FM_PFR_ACTIVE_N\ngpio_export FM_PFR_ACTIVE_N GPIOI3\n\n\n# FM_UARTSW_LSB_N\ngpio_export FM_UARTSW_LSB_N GPIOL0\n\n# FM_UARTSW_MSB_N\ngpio_export FM_UARTSW_MSB_N GPIOL1\n\n# IRQ_HSC_FAULT_N\ngpio_export IRQ_HSC_FAULT_N GPIOL2\n\n# FM_CPU1_MEMHOT_OUT_N\ngpio_export FM_CPU1_MEMHOT_OUT_N GPIOL3\n\n# FM_MASTER_MB_N\ngpio_export FM_MASTER_MB_N GPIOL4\ngpio_set FM_MASTER_MB_N 1\n\n# JTAG_MUX_EN_N\ngpio_export JTAG_MUX_EN_N GPIOL5\n\n\n# IRQ_OC_DETECT_N\ngpio_export IRQ_OC_DETECT_N GPIOM0\n\n# IRQ_UV_DETECT_N\ngpio_export IRQ_UV_DETECT_N GPIOM1\n\n# FM_HSC_TIMER_EXP_N\ngpio_export FM_HSC_TIMER_EXP_N GPIOM2\n\n# P3V3_STBY_MON_ALERT\ngpio_export P3V3_STBY_MON_ALERT GPIOM3\n\n# FM_TPM_BMC_PRES_N\ngpio_export FM_TPM_BMC_PRES_N GPIOM4\n\n# SPI_BMC_BT_WP0_N\ngpio_export SPI_BMC_BT_WP0_N GPIOM5\n\n# SMB_BMC_MM5_ALT_N\ngpio_export SMB_BMC_MM5_ALT_N GPIOM6\n\n# SMB_BMC_MM5_RST_N\ngpio_export SMB_BMC_MM5_RST_N GPIOM7\n\n\n# REMOTE_DEBUG_DIS_N\ngpio_export REMOTE_DEBUG_DIS_N GPION2\n\n# FM_SOL_UART_CH_SEL\ngpio_export FM_SOL_UART_CH_SEL GPION3\n\n# IRQ_DIMM_SAVE_LVT3_N\ngpio_export IRQ_DIMM_SAVE_LVT3_N GPION4\n\n# LED_8S_2S_MODE_N\ngpio_export LED_4S_2S_MODE_N GPION5\n\n# Set debounce timer #1 value to 0x12E1FC ~= 100ms\n$DEVMEM 0x1e780050 32 0x12E1FC\n\n# Select debounce timer #1 for GPION6\ndevmem_clear_bit 0x1e780100 14\ndevmem_set_bit 0x1e780104 14\n\n# FM_POST_CARD_PRES_BMC_N\ngpio_export FM_POST_CARD_PRES_BMC_N GPION6\n\n# FM_PWRBRK_N\ngpio_export FM_PWRBRK_N GPION7\n\n\n# FM_BMC_SKT_ID_0\ngpio_export FM_BMC_SKT_ID_0 GPIOO0\n\n# FM_BMC_SKT_ID_1\ngpio_export FM_BMC_SKT_ID_1 GPIOO1\n\n# FM_BMC_SKT_ID_2\ngpio_export FM_BMC_SKT_ID_2 GPIOO2\nmode=$(($(gpio_get FM_BMC_SKT_ID_2)))\nkv set mb_skt $((mode<<2 |\n        $(gpio_get FM_BMC_SKT_ID_1)<<1 |\n        $(gpio_get FM_BMC_SKT_ID_0)))\n\n# FM_SMB_RETIMER_1_ISO_EN\ngpio_export FM_SMB_RETIMER_1_ISO_EN GPIOO3\n\n# FM_SMB_RETIMER_2_ISO_EN\ngpio_export FM_SMB_RETIMER_2_ISO_EN GPIOO4\n\n# PRSNT_UPI_BD_1_N\ngpio_export PRSNT_UPI_BD_1_N GPIOO5\n\n# PRSNT_UPI_BD_2_N\ngpio_export PRSNT_UPI_BD_2_N GPIOO6\n\n# PRSNT_UPI_BD_3_N\ngpio_export PRSNT_UPI_BD_3_N GPIOO7\n\n\n# PRSNT_UPI_BD_4_N\ngpio_export PRSNT_UPI_BD_4_N GPIOP0\n\n# SMB_BMC_ASICBOX_EN\ngpio_export SMB_BMC_ASICBOX_EN GPIOP1\ngpio_set SMB_BMC_ASICBOX_EN 1\n\n# FM_CM_READY_N\ngpio_export FM_CM_READY_N GPIOP2\n\n# RST_CM_N\ngpio_export RST_CM_N GPIOP3\ngpio_set RST_CM_N 1\n\n# FM_ASIC_POWER_EN\ngpio_export FM_ASIC_POWER_EN GPIOP4\n\n# FM_ASIC_PWRGD\ngpio_export FM_ASIC_PWRGD GPIOP5\n\n# FM_BLADE_ID_0\ngpio_export FM_BLADE_ID_0 GPIOP6\n\n# FM_BLADE_ID_1\ngpio_export FM_BLADE_ID_1 GPIOP7\nif [ \"$mode\" -eq 1 ]; then  # 2S\n  kv set mb_pos 0\nelse\n  kv set mb_pos $(($(gpio_get FM_BLADE_ID_1)<<1 | $(gpio_get FM_BLADE_ID_0)))\nfi\n\n\n# RST_TCA9545_DDR_MUX_N\ngpio_export RST_TCA9545_DDR_MUX_N GPIOQ6\n\n# FM_BMC_CPU_PWR_DEBUG_N\ngpio_export FM_BMC_CPU_PWR_DEBUG_N GPIOQ7\n\n\n# DBP_PRESENT_N\ngpio_export DBP_PRESENT_N GPIOR1\n\n# FM_BIOS_SPI_BMC_CTRL\ngpio_export FM_BIOS_SPI_BMC_CTRL GPIOR6\n\n# FM_SYS_THROTTLE_LVC3\ngpio_export FM_SYS_THROTTLE_LVC3 GPIOR7\n\n\n# FM_MODULAR_ASD_EN\ngpio_export FM_MODULAR_ASD_EN GPIOS0\n\n# DBP_SYSPWROK\ngpio_export DBP_SYSPWROK GPIOS1\n\n# RST_RSMRST_BMC_N\ngpio_export RST_RSMRST_BMC_N GPIOS2\n\n# IRQ_SML0_ALERT_MUX_N\ngpio_export IRQ_SML0_ALERT_MUX_N GPIOS3\n\n# FP_LOCATE_LED, ID LED\ngpio_export FP_LOCATE_LED GPIOS4\ngpio_set FP_LOCATE_LED 0\n\n# FM_2S_FAN_IO_EXP_RST\ngpio_export FM_2S_FAN_IO_EXP_RST GPIOS6\n\n# RST_SMB_OCP_MUX_N\ngpio_export RST_SMB_OCP_MUX_N GPIOS7\n\n\n# FM_FORCE_BMC_UPDATE_N\ngpio_export FM_FORCE_BMC_UPDATE_N GPIOT0\n\n# FP_LOCATE_LED_ACT\ngpio_export FP_LOCATE_LED_ACT GPIOT5\ngpio_set FP_LOCATE_LED_ACT 0\n\n# OCP_V3_NIC_2_PWR_GOOD\ngpio_export OCP_V3_NIC_2_PWR_GOOD GPIOT6\n\n\n# BOARD_ID_MUX_SEL\ngpio_export BOARD_ID_MUX_SEL GPIOU2\ngpio_set BOARD_ID_MUX_SEL 0\nkv set mb_rev $(($(gpio_get FM_BOARD_BMC_REV_ID2)<<2 |\n        $(gpio_get FM_BOARD_BMC_REV_ID1)<<1 |\n        $(gpio_get FM_BOARD_BMC_REV_ID0)))\n\nkv set mb_sku $(($(gpio_get FM_BOARD_BMC_SKU_ID5)<<5 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID4)<<4 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID3)<<3 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID2)<<2 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID1)<<1 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID0)))\n\ngpio_set BOARD_ID_MUX_SEL 1\n\n# BMC_FORCE_NM_THROTTLE_N\ngpio_export BMC_FORCE_NM_THROTTLE_N GPIOU3\n\n# FM_CPU0_MEMHOT_OUT_N\ngpio_export FM_CPU0_MEMHOT_OUT_N GPIOU5\n\n\n# OCP_V3_NIC_1_PWR_GOOD\ngpio_export OCP_V3_NIC_1_PWR_GOOD GPIOV3\n\n\n# FM_SLPS3_N\ngpio_export FM_SLPS3_N GPIOY0\n\n# FM_SLPS4_N\ngpio_export FM_SLPS4_N GPIOY1\n\n# PWRGD_SYS_PWROK, power GOOD from CPLD\ngpio_export PWRGD_SYS_PWROK GPIOY2\n\n# FM_BMC_ONCTL_N\ngpio_export FM_BMC_ONCTL_N GPIOY3\n\n\n# FM_CPU_CATERR_LVT3_N\ngpio_export FM_CPU_CATERR_LVT3_N GPIOZ0\n\n# PWRGD_CPU0_LVC3\ngpio_export PWRGD_CPU0_LVC3 GPIOZ1\n\n# FM_CPU_MSMI_LVT3_N\ngpio_export FM_CPU_MSMI_LVT3_N GPIOZ2\n\n# FM_BMC_PCH_SCI_LPC_N\ngpio_export FM_BMC_PCH_SCI_LPC_N GPIOZ3\n\n# UV_HIGH_SET\ngpio_export UV_HIGH_SET GPIOZ4\n\n# FM_OC_DETECT_EN_N\ngpio_export FM_OC_DETECT_EN_N GPIOZ5\n\n# FM_SML1_PMBUS_ALERT_EN_N\ngpio_export FM_SML1_PMBUS_ALERT_EN_N GPIOZ6\n\n# FM_BMC_LED_CATERR_N\ngpio_export FM_BMC_LED_CATERR_N GPIOZ7\ngpio_set FM_BMC_LED_CATERR_N 1\n\n\n# P3V_BAT_SCALED_EN\ngpio_export P3V_BAT_SCALED_EN GPIOAA0\ngpio_set P3V_BAT_SCALED_EN 0\n\n# IRQ_SML1_PMBUS_BMC_ALERT_N\ngpio_export IRQ_SML1_PMBUS_BMC_ALERT_N GPIOAA1\n\n# FM_PVCCIN_CPU0_PWR_IN_ALERT_N\ngpio_export FM_PVCCIN_CPU0_PWR_IN_ALERT_N GPIOAA2\n\n# FM_PVCCIN_CPU1_PWR_IN_ALERT_N\ngpio_export FM_PVCCIN_CPU1_PWR_IN_ALERT_N GPIOAA3\n\n# FM_BMC_PREQ_N\ngpio_export FM_BMC_PREQ_N GPIOAA4\n\n# FM_JTAG_TCK_MUX_SEL\ngpio_export FM_JTAG_TCK_MUX_SEL GPIOAA5\ngpio_set FM_JTAG_TCK_MUX_SEL 0\n\n# IRQ_SMI_ACTIVE_BMC_N\ngpio_export IRQ_SMI_ACTIVE_BMC_N GPIOAA6\n\n# FM_BIOS_POST_CMPLT_BMC_N\ngpio_export FM_BIOS_POST_CMPLT_BMC_N GPIOAA7\n\n\n# FM_BMC_BMCINIT\ngpio_export FM_BMC_BMCINIT GPIOAB0\n\n# PECI_MUX_SELECT\ngpio_export PECI_MUX_SELECT GPIOAB1\ngpio_set PECI_MUX_SELECT 0\n\n# PWRGD_BMC_PS_PWROK\ngpio_export PWRGD_BMC_PS_PWROK GPIOAB3\n\n\n# workaround for unexpected DIMM_MUX status\nif [ ! -L \"${SYSFS_I2C_DEVICES}/4-0076/driver\" ] ||\n   [ ! -L \"${SYSFS_I2C_DEVICES}/4-0077/driver\" ]; then\n  logger -t \"setup-gpio\" -p user.warn \"Reset DIMM_MUX\"\n  echo low > /tmp/gpionames/RST_TCA9545_DDR_MUX_N/direction\n  usleep 10000\n  echo in > /tmp/gpionames/RST_TCA9545_DDR_MUX_N/direction\n  usleep 10000\nfi\n\nif [ ! -L \"${SYSFS_I2C_DEVICES}/4-0076/driver\" ]; then\n  if i2c_bind_driver pca953x 4-0076 2 2>/dev/null; then\n    echo \"rebind 4-0076 to driver pca953x successfully\"\n  fi\nfi\n\n# I/O Expander TCA9539 0xEC\ngpio_export_ioexp 4-0076 FM_SLOT1_PRSNT_N 0\ngpio_export_ioexp 4-0076 FM_SLOT2_PRSNT_N 1\ngpio_export_ioexp 4-0076 RST_RTCRST_N 10\ngpio_export_ioexp 4-0076 RST_USB_HUB_N 11\n\nif [ ! -L \"${SYSFS_I2C_DEVICES}/4-0077/driver\" ]; then\n  if i2c_bind_driver pca953x 4-0077 2 2>/dev/null; then\n    echo \"rebind 4-0077 to driver pca953x successfully\"\n  fi\nfi\n\n# I/O Expander TCA9539 0xEE\ngpio_export_ioexp 4-0077 IRQ_PVCCIN_CPU0_VRHOT_LVC3_N 0\ngpio_export_ioexp 4-0077 IRQ_PVCCIN_CPU1_VRHOT_LVC3_N 1\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_ABC_CPU0_VRHOT_LVC3_N 2\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_DEF_CPU0_VRHOT_LVC3_N 3\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_ABC_CPU1_VRHOT_LVC3_N 4\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_DEF_CPU1_VRHOT_LVC3_N 5\ngpio_export_ioexp 4-0077 FM_CPU0_SKTOCC_LVT3_PLD_N 6\ngpio_export_ioexp 4-0077 FM_CPU1_SKTOCC_LVT3_PLD_N 7\ngpio_export_ioexp 4-0077 HP_LVC3_OCP_V3_2_PRSNT2_N 8\ngpio_export_ioexp 4-0077 HP_LVC3_OCP_V3_1_PRSNT2_N 9\n\n# Mode Setting (2S: mode=1 4S: mode=0)\nif [ \"$mode\" -eq 1 ]; then\n    gpio_set LED_4S_2S_MODE_N 0\nelse\n    gpio_set LED_4S_2S_MODE_N 1\nfi\n", "num_lines": 547}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# check usb hub i2c register\nResult=$(i2cget -f -y 4 0x2C 0xFF i 2>&1 1>/dev/null)\n\n# reset usb hub if usb hub i2c register was not available\nif [ -n \"$Result\" ]; then\n    echo \"Reset USB Hub\"\n    i2cset -f -y 4 0x76 0x07 0xf7\n    i2cset -f -y 4 0x76 0x03 0xf7\n    sleep 1\n    i2cset -f -y 4 0x76 0x07 0xff\nfi\n\necho \"Config USB Hub\"\ni2cset -f -y 4 0x2c 0x00 0x24 0x04 0x14 0x25 0x00 0x02 0xBB 0x20 0x02 0x00 0x00 0x00 0x01 0x32 0x01 0x32 0x32 s\ni2cset -f -y 4 0x2c 0xff 0x01 s\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nsku=$(kv get mb_sku)\nrev=$(kv get mb_rev)\n\n# retry to probe pxe1110c (pxe1211c).\n# note: still keep pxe1110c in dts, so it's the\n# 1st device to be probed on i2c-1\nif [ ! -L \"${SYSFS_I2C_DEVICES}/1-004a/driver\" ]; then\n  if i2c_bind_driver pxe1211c 1-004a 4 2>/dev/null; then\n    echo \"rebind 1-004a to driver pxe1211c successfully\"\n  fi\nfi\n\n#DVT SKU_ID[2:1] = 00(TI), 01(INFINEON), TODO: 10(3rd Source)\nsku=$((sku & 0x2))\nif [ $sku -eq 0 ]; then\n  i2c_device_add 1 0x60 tps53688\n  i2c_device_add 1 0x62 tps53688\n  i2c_device_add 1 0x66 tps53688\n  i2c_device_add 1 0x68 tps53688\n  i2c_device_add 1 0x6c tps53688\n  i2c_device_add 1 0x70 tps53688\n  i2c_device_add 1 0x72 tps53688\n  i2c_device_add 1 0x76 tps53688\nelse\n  i2c_device_add 1 0x60 xdpe12284\n  i2c_device_add 1 0x62 xdpe12284\n  i2c_device_add 1 0x66 xdpe12284\n  i2c_device_add 1 0x68 xdpe12284\n  i2c_device_add 1 0x6c xdpe12284\n  i2c_device_add 1 0x70 xdpe12284\n  i2c_device_add 1 0x72 xdpe12284\n  i2c_device_add 1 0x76 xdpe12284\nfi\n\nif [ \"$rev\" -lt 2 ]; then\n  i2c_device_add 4 0x54 24c64\nelse\n  i2c_device_add 4 0x57 24c64\nfi\n\n\nif [ \"$(gpio_get HP_LVC3_OCP_V3_1_PRSNT2_N)\" = \"0\" ]; then\n  i2c_device_add 17 0x50 24c32\nfi\n\nif [ \"$(gpio_get HP_LVC3_OCP_V3_2_PRSNT2_N)\" = \"0\" ]; then\n  i2c_device_add 18 0x52 24c32\n  if [ \"$(kv get eth1_disable_ipv6 persistent 2>/dev/null)\" != \"0\" ]; then\n    echo 1 > /proc/sys/net/ipv6/conf/eth1/disable_ipv6\n  fi\n  ifconfig eth1 up\nfi\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\n# Sync BMC's date with the server\nsync_date()\n{\n  sleep 1\n  # if no ntp peer has been declared the system peer\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    echo Syncing up BMC time with server...\n\n    position=$(($(/usr/bin/kv get mb_pos)))\n    host=$(($(/usr/bin/kv get mb_skt) & 0x1))  #0: Master 1:Slave\n\n    if [ $position -eq 0 ]; then #position 0\n      addr=$((16#22))\n    else\n      addr=$((16#20))\n    fi\n\n    # Use standard IPMI command 'get-sel-time' to read RTC time\n    for i in {1..10};\n    do\n    #Master\n      if [ $host -eq 0 ]; then\n        output=$(/usr/local/bin/ipmb-util 5 0x2c 0x28 0x48)\n        if [ ${#output} == 12 ]\n        then\n          break;\n        fi\n\n        if [ ${i} == 10 ]\n        then\n          exit\n        fi\n    #Slave\n      else\n        output=$(/usr/local/bin/ipmb-util 2 $addr 0xC0 0x34 0x01 0x0a 0x48)\n        if [ ${#output} == 12 ]\n        then\n          break;\n        fi\n\n        if [ ${i} == 10 ]\n        then\n          echo Sync time with Master BMC\n          output=$(/usr/local/bin/ipmb-util 2 $addr 0x28 0x48)\n        fi\n      fi\n      usleep 300\n    done\n\n    sys_date=$(date +%s)\n    set_date=$((16#$(echo \"$output\" | awk '{print $4$3$2$1}')))\n\n    if [ \"$sys_date\" -ge $set_date ]; then\n      echo \"Use BMC date\"\n      set_date=\"$sys_date\"\n    fi\n\n    date -s @\"$set_date\"\n    test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  fi\n}\n\nsync_date\n", "num_lines": 89}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util vr --version\" once before sensor monitoring to store vr information\necho \"Get VR FW version... \"\n/usr/bin/fw-util vr --version > /dev/null\n\n# shellcheck disable=2039\necho -n \"Setup sensor monitoring for FBAL... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Read AST2620 register SCU014 [23:16] to retrieve the board hardware revision.\n\nSCU014_REG=0x1e6e2014\nHW_REV_BIT=16\nBOARD_REV=$(($(($(devmem \"${SCU014_REG}\") >> \"${HW_REV_BIT}\")) & 0xff))\necho \"BMC Board Revision: A${BOARD_REV}\"\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2022-present Facebook. All Rights Reserved.\n\n# shellcheck disable=SC2034\n\nwedge_board_type() {\n    echo 'FBDARWIN'\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    # Assume P1\n    return 1\n}\n\nretry_command() {\n    # Retry command up to $1 attempts\n    local retries=$1\n    shift\n\n    local count=0\n    until \"$@\"; do\n        exit=$?\n        count=$((count+1))\n        if [ \"$count\" -lt \"$retries\" ]; then\n            msg=\"Attempt $count/$retries failed with $exit, retrying...\"\n            echo \"$msg\"\n            logger retry_command: \"$msg\"\n        else\n            msg=\"Retry $count/$retries failed with $exit, no more retries left\"\n            echo \"$msg\"\n            logger retry_command: \"$msg\"\n            return $exit\n        fi\n    done\n    return 0\n}\n\ndo_sync() {\n   # Try to flush all data to MMC and remount the drive read-only. Sync again\n   # because the remount is asynchronous.\n   partition=\"/dev/mmcblk0\"\n   mountpoint=\"/mnt/data1\"\n\n   sync\n   # rsyslogd logs to eMMC, so we must stop it prior to remouting.\n   systemctl stop syslog.socket rsyslog.service\n   sleep .05\n   if [ -e $mountpoint ]; then\n      retry_command 5 mount -o remount,ro $partition $mountpoint\n      sleep 1\n   fi\n   sync\n}\n\nuserver_power_is_on() {\n    return 0\n}\n\nuserver_power_on() {\n    return 0\n}\n\nuserver_power_off() {\n    echo \"FBDARWIN doesn't support SCM power off!\"\n    return 1\n}\n\nuserver_reset() {\n    retries=3\n    for _ in $(seq $retries); do\n        gpio_set_value BMC_SYS_PWR_CYC1 1\n        sleep 1\n        gpio_set_value BMC_SYS_PWR_CYC1 0\n        sleep 5\n    done\n}\n\nchassis_power_cycle() {\n    do_sync\n\n    gpio_set_value BMC_SYS_PWR_CYC0 1\n    sleep 8\n\n    # The chassis shall be reset now... if not, we are in trouble\n    echo \"ERROR: unable to power cycle chassis!!!\"\n    gpio_set_value BMC_SYS_PWR_CYC0 0\n    exit 1\n}\n\nbmc_mac_addr() {\n    weutil bmc | grep '^Extended MAC Base' | cut -d' ' -f 4\n}\n\nuserver_mac_addr() {\n    weutil CHASSIS 2>&1 | grep \"MAC Base\" | cut -d ' ' -f 4\n}\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC2039\nusage() {\n    echo \"Reads/writes Bcm53134 registers\"\n    echo\n    echo \"read[(8|16|32|64)] <page> <addr>\"\n    echo \"write[(8|16|32|64)] <page> <addr> <val>\"\n    echo\n    echo \"read/write are equivalent to read8/write8\"\n}\n\nmdio0_base_reg=0x1e650000\nmdio_ctrl_reg=0x0\nmdio_read_reg=0x4\npseudo_phy_port_addr=0x1e\n\nscu_reset_set2=0x1e6e2050\nscu_reset_clear2=$((scu_reset_set2 + 0x4))\nscu_reset_mii_controller=$((1 << 3))\nscu_pin_control8=0x1e6e2430\nscu_mdcmdio_enable=$(( (1 << 16) | (1 << 17) ))\n\ntrap cleanup EXIT INT TERM QUIT\n\nMDIO_INITIALIZED=0\ncleanup() {\n    if [ $MDIO_INITIALIZED -eq 1 ]\n    then\n        mdio_restore\n    fi\n}\n\nmdio_init() {\n    MDIO_INITIALIZED=1\n    devmem \"$scu_reset_clear2\" 32 \"$scu_reset_mii_controller\"\n\n    val=$(devmem \"$scu_pin_control8\")\n    devmem \"$scu_pin_control8\" 32 $((val | scu_mdcmdio_enable))\n}\n\nmdio_restore() {\n    devmem \"$scu_reset_set2\" 32 \"$scu_reset_mii_controller\"\n    val=$(devmem \"$scu_pin_control8\")\n    devmem \"$scu_pin_control8\" 32 $((val & ~scu_mdcmdio_enable))\n    MDIO_INITIALIZED=0\n}\n\nto_hex() {\n    local val=$1\n    printf \"0x%x\" \"$val\"\n}\n\ndevmem_read() {\n    local reg_addr=$1\n    local mem_addr\n\n    mem_addr=$(to_hex $((mdio0_base_reg + reg_addr)))\n    devmem \"$mem_addr\"\n}\n\ndevmem_write() {\n    local reg_addr=$1\n    local val mem_addr\n\n    val=$(to_hex \"$2\")\n    mem_addr=$(to_hex $((mdio0_base_reg + reg_addr)))\n    devmem \"$mem_addr\" 32 \"$val\"\n}\n\nmdio_read() {\n    local addr=$1\n    local fire_busy clause_22 read_request reg_val read_reg_val ctrl_idle\n\n    fire_busy=$(( 1 << 31 ))\n    clause_22=$(( 1 << 28 ))\n    read_request=$(( 1 << 27 ))\n    reg_val=$(( fire_busy \\\n              | clause_22 \\\n              | read_request \\\n              | ( pseudo_phy_port_addr << 21 ) \\\n              | ( addr << 16 ) ))\n\n    devmem_write $mdio_ctrl_reg $reg_val\n    ctrl_idle=$(( 1 << 16 ))\n    desc=$(printf \"read 0x%x\" \"$addr\")\n    mdio_wait_op_complete \"$mdio_read_reg\" \"$ctrl_idle\" \"$ctrl_idle\" \"$desc\"\n\n    read_reg_val=$(devmem_read $mdio_read_reg)\n    echo $(( read_reg_val & 0xffff ))\n}\n\nmdio_write() {\n    local addr=$1\n    local val=$2\n    local fire_busy clause_22 write_request reg_val\n\n    fire_busy=$(( 1 << 31 ))\n    clause_22=$(( 1 << 28 ))\n    write_request=$(( 1 << 26 ))\n    reg_val=$(( fire_busy \\\n              | clause_22 \\\n              | write_request \\\n              | ( pseudo_phy_port_addr << 21 ) \\\n              | ( addr << 16 ) \\\n              | val ))\n\n    devmem_write $mdio_ctrl_reg \"$reg_val\"\n\n    desc=$(printf \"write 0x%x 0x%x\" \"$addr\" \"$val\")\n    mdio_wait_op_complete \"$mdio_ctrl_reg\" \"$fire_busy\" 0 \"$desc\"\n}\n\nmdio_wait_op_complete() {\n    local mdio_reg=$1\n    local mask=$2\n    local wait_val=$3\n    local desc=$4\n    local timeout=5\n    local interval=0.1\n    local val\n\n    local time_limit=$(( $(date +%s) + timeout ))\n    while [ \"$(date +%s)\" -lt $time_limit ]\n    do\n        val=$(devmem_read \"$mdio_reg\")\n        if [ $(( val & \"$mask\" )) -eq \"$wait_val\" ]\n        then\n            return\n        fi\n        sleep $interval\n    done\n\n    echo \"Error: timed out waiting for operation to complete: $desc\" >&2\n    exit 1\n}\n\noob_page_reg=16\noob_addr_reg=17\noob_data_reg_base=24\n\nreg_read() {\n    local page=$1\n    local addr=$2\n    local data_size=$3\n    local data data_reg_num reg_val\n\n    data=$(reg_page_data \"$page\" 1)\n    mdio_write $oob_page_reg \"$data\"\n\n    data=$(reg_addr_data \"$addr\" 0x2)\n    mdio_write $oob_addr_reg \"$data\"\n\n    reg_wait_addr_reg_acked\n\n    # Read data registers\n    local val=0\n    num_data_regs=$(( ( data_size + 1 ) / 2 ))\n    local reg_idx=0\n    while [ $reg_idx -lt $num_data_regs ]\n    do\n        data_reg_num=$(( oob_data_reg_base + reg_idx ))\n        reg_val=$(mdio_read $data_reg_num)\n        val=$(( val | ( reg_val << ( reg_idx * 16 ) ) ))\n\n        reg_idx=$(( reg_idx + 1 ))\n    done\n\n    binary_str=$(val_to_binary_str \"$val\" \"$data_size\")\n    printf \"0x%x/0x%x 0x%x == $binary_str\\n\" \"$page\" \"$addr\" $val\n\n    reg_clear_access_enable\n}\n\nreg_write() {\n    local page=$1\n    local addr=$2\n    local val=$3\n    local data_size=$4\n    local data reg_val data_reg_num\n\n    data=$(reg_page_data \"$page\" 1)\n    mdio_write $oob_page_reg \"$data\"\n\n    # Write data registers\n    num_data_regs=$(( ( data_size + 1 ) / 2 ))\n    local reg_idx=0\n    while [ $reg_idx -lt $num_data_regs ]\n    do\n        data_reg_num=$(( oob_data_reg_base + reg_idx ))\n        reg_val=$(( ( val >> ( reg_idx * 16 ) ) & 0xffff ))\n        mdio_write $data_reg_num $reg_val\n\n        reg_idx=$(( reg_idx + 1 ))\n    done\n\n    data=$(reg_addr_data \"$addr\" 0x1)\n    mdio_write $oob_addr_reg \"$data\"\n\n    reg_wait_addr_reg_acked\n    reg_clear_access_enable\n}\n\nreg_wait_addr_reg_acked() {\n    local timeout=60\n    local interval=0.1\n    local time_limit response op\n\n    time_limit=$(( $(date +%s) + timeout ))\n    while [ \"$(date +%s)\" -lt $time_limit ]\n    do\n        response=$(mdio_read $oob_addr_reg)\n        op=$(( response & 0x3 ))\n        if [ $op -eq 0 ]\n        then\n            return\n        fi\n\n        sleep $interval\n    done\n\n    echo \"Error: timed out waiting for addr reg to be acknowledged\" >&2\n    exit 1\n}\n\nreg_clear_access_enable() {\n    data=$(reg_page_data 0 0)\n    mdio_write $oob_page_reg \"$data\"\n}\n\nreg_page_data() {\n    local page=$1\n    local access_enable=$2\n    local data=$(( page << 8 ))\n    data=$(( data | access_enable ))\n    echo $data\n}\n\nreg_addr_data() {\n    local addr=$1\n    local op=$2\n    local data=$(( addr << 8 ))\n    data=$(( data | op ))\n    echo $data\n}\n\nval_to_binary_str() {\n    local val=$1\n    local data_size=$2\n    local i=$(( data_size * 8 ))\n\n    while [ $i -gt 0 ]\n    do\n        i=$(( i - 1 ))\n        printf \"%d\" $(( ( val >> i ) & 0x1 ))\n        if [ $i -gt 0 ] && [ $(( i % 4 )) -eq 0 ]\n        then\n            printf \" \"\n        fi\n    done\n}\n\nhandle_read() {\n    local size=$1\n    shift\n    if [ $# -lt 2 ]\n    then\n        echo \"Error: missing arguments\" >&2\n        usage\n        exit 1\n    fi\n    local page=$1\n    local addr=$2\n    local data_size=$(( size / 8 ))\n    reg_read \"$page\" \"$addr\" \"$data_size\"\n}\n\nhandle_write() {\n    local size=$1\n    shift\n    if [ $# -lt 3 ]\n    then\n        echo \"Error: missing arguments\" >&2\n        usage\n        exit 1\n    fi\n    local page=$1\n    local addr=$2\n    local val=$3\n    local data_size=$(( size / 8 ))\n    reg_write \"$page\" \"$addr\" \"$val\" \"$data_size\"\n}\n\nif [ $# -lt 1 ]\nthen\n    echo \"Error: missing command\" >&2\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\ncase \"$command\" in\n    read8) cmd_type=\"read\"; size=\"8\";;\n    read16) cmd_type=\"read\"; size=\"16\";;\n    read32) cmd_type=\"read\"; size=\"32\";;\n    read64) cmd_type=\"read\"; size=\"64\";;\n    write8) cmd_type=\"write\"; size=\"8\";;\n    write16) cmd_type=\"write\"; size=\"16\";;\n    write32) cmd_type=\"write\"; size=\"32\";;\n    write64) cmd_type=\"write\"; size=\"64\";;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nmdio_init\n\nif [ \"$cmd_type\" = \"read\" ]\nthen\n    handle_read \"$size\" \"$@\"\nelse\n    handle_write \"$size\" \"$@\"\nfi\n", "num_lines": 343}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nsetup_gpio_fbdarwin_evt() {\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOB1 BMC_ALIVE\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOC3 TPM_BFLSH_WP_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOC4 BMC_MODE\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG6 BMC_BOARD_EEPROM_WP_L\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOO0 BMC_SYS_PWR_CYC0\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOO2 BMC_SYS_PWR_CYC1\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOO4 OOB_EEPROM_SPI_SEL\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOO6 OOB_RST\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX7 SPI_TPM_PIRQ_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOY3 BMC_EMMC_RST\n}\n\nsetup_gpio_fbdarwin_evt\n\ngpio_set_direction BMC_ALIVE out\ngpio_set_direction TPM_BFLSH_WP_L in\ngpio_set_direction BMC_MODE in\ngpio_set_direction BMC_BOARD_EEPROM_WP_L out\ngpio_set_direction BMC_SYS_PWR_CYC0 out\ngpio_set_direction BMC_SYS_PWR_CYC1 out\ngpio_set_direction OOB_EEPROM_SPI_SEL out\ngpio_set_direction OOB_RST out\ngpio_set_direction BMC_EMMC_RST out\ngpio_set_direction SPI_TPM_PIRQ_N in\n\n# Once we set \"out\", output values will be random unless we set them\n# Set Default GPIO values\n# Set BMC_EMMC_RST High to prevent EMMC disable\ngpio_set BMC_EMMC_RST 1\n\ngpio_set_value BMC_ALIVE 1\ngpio_set_value BMC_BOARD_EEPROM_WP_L 1 # Disabled\ngpio_set_value BMC_SYS_PWR_CYC0 0\ngpio_set_value BMC_SYS_PWR_CYC1 0\ngpio_set_value OOB_EEPROM_SPI_SEL 0\ngpio_set_value OOB_RST 0\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n#\n# Setup oob switch BCM53134, just in case the settings are not expected.\n#\nsetup_oob_switch() {\n    control_page=\"0x0\"\n    port_state_reg=\"0xe\"\n    port_state_reg_val=\"0x8b\"\n    imp_rgmi_control_reg=\"0x60\"\n    imp_rgmi_control_reg_val=\"0x0\"\n    ieee_vlan_control_page=\"0x34\"\n    vlan_port2_reg=\"0x14\"\n    vlan_port2_val=\"0xffa\"\n\n    # Check BCM53134 registers\n    curr_speed=$(oob-mdio-util.sh read8 \"$control_page\" \"$port_state_reg\"|\n               cut -d' ' -f2)\n    curr_clk_dly=$(oob-mdio-util.sh read8 \"$control_page\" \"$imp_rgmi_control_reg\"|\n                 cut -d' ' -f2)\n    if [ \"$curr_speed\" = \"$port_state_reg_val\" ] && \\\n       [ \"$curr_clk_dly\" = \"$imp_rgmi_control_reg_val\" ]; then\n        # Register values are as expected\n        return 0\n    fi\n\n    echo \"BCM53134 registers not as expected. Configuring now.\"\n    echo \"Re-program the BCM53134 EEPROM to fix this permanently.\"\n\n    oob-mdio-util.sh write8 \"$control_page\" \"$port_state_reg\" \"$port_state_reg_val\"\n    oob-mdio-util.sh write8 \"$control_page\" \"$imp_rgmi_control_reg\" \\\n                            \"$imp_rgmi_control_reg_val\"\n\n    # Enable Port 2 which is used on some platforms\n    oob-mdio-util.sh write16 \"$ieee_vlan_control_page\" \"$vlan_port2_reg\" \"$vlan_port2_val\"\n}\n\nsetup_oob_switch\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n### BEGIN INIT INFO\n# Provides:          find_serfmon.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Find Serfmon string from mTerm log and cache it\n### END INIT INFO\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2034\n. /usr/local/bin/openbmc-utils.sh\n\nMTERM_LOGFILE=\"/var/log/mTerm_wedge.log\"\nSERFMON_CACHE=\"/mnt/data1/.serfmon.txt\"\nMACMON_CACHE=\"/mnt/data1/.macmon.txt\"\nCHASSIS_EEPROM_CACHE=\"/mnt/data1/.chassis_eeprom\"\nSERFMON_REGEX=\"\\!serfmon\\:.*\\:.*\\:.*$\"\nMACMON_REGEX=\"\\!macmon\\:.*\\:.*\\:.*$\"\n\ncreate_dummy_chassis_eeprom() {\n    dummy_pca=\"PCA000000000\"\n\n    # Don't create dummy EEPROM until serfmon string is seen\n    if [ ! -f \"$SERFMON_CACHE\" ]; then\n       return\n    fi\n\n    # Extract SN from Serfmon Format \\!serfmon\\:.*\\:.*\\:.*$\n    chassis_serial=\"$(awk -F\":\" '{print $3}' \"$SERFMON_CACHE\")\"\n\n    # Create Fake EEPROM file for weutil in expected format\n    printf \"\\x00\\x00\\x00\\x03\\x00\\x00\\x00\\x00\\x30\\x30\\x30\\x32%s%s\\x31\\x31\\x31\"\\\n        \"$dummy_pca\" \"$chassis_serial\" > \"$CHASSIS_EEPROM_CACHE\"\n\n    # How many bytes to pad EEPROM file\n    pad_bytes=211\n\n    # If a cached Macmon string exists, add that to the EEPROM\n    if [ -f \"$MACMON_CACHE\" ]; then\n       chassis_mac=\"$(awk -F\":\" '{print $3}' \"$MACMON_CACHE\")\"\n\n       # Add MAC TLV. MAC is 12 (0x43 = C) bytes in length\n       printf \"\\x30\\x35\\x30\\x30\\x30\\x43%s\" \"$chassis_mac\" >> \"$CHASSIS_EEPROM_CACHE\"\n       pad_bytes=$((pad_bytes - 18))\n    fi\n\n    # Add an end TLV.\n    printf \"\\x30\\x30\\x30\\x30\\x30\\x30\" >> \"$CHASSIS_EEPROM_CACHE\"\n\n    # Pad file with all 0xFFs to size\n    dd if=/dev/zero bs=1 count=$pad_bytes \\\n       2>/dev/null | tr \"\\000\" \"\\377\" >> \"$CHASSIS_EEPROM_CACHE\"\n}\n\nmaybe_update_cache() {\n    # Check the mTerm logfile for the given regex. If found, update the cache_file\n    local -n cached_value=\"$1\"\n    local -n cache_updated=\"$2\"\n    regex=\"$3\"\n    cache_file=\"$4\"\n    name=\"$5\"\n\n    # Always clear update flag first\n    cache_updated=0\n\n    if grep -qE \"$regex\" \"$MTERM_LOGFILE\"; then\n        # Detect if string found in mTerm log\n        read_value=\"$(grep -oE \"$regex\" \"$MTERM_LOGFILE\" | tail -n 1)\"\n\n        # Read cached string from eMMC\n        if [ -f \"$cache_file\" ]; then\n            cached_value=\"$(cat \"$cache_file\")\"\n        else\n            cached_value=\"\"\n        fi\n\n        # If mTerm's string value doesn't match the cache, update it\n        if [ \"$read_value\" != \"$cached_value\" ]; then\n            echo \"$read_value\" > \"$cache_file\"\n            echo \"Registered new $name string!\"\n            cached_value=\"$(cat \"$cache_file\")\"\n            echo \"$read_value\"\n            cache_updated=1\n        fi\n    fi\n}\n\n# Print cached Serfmon/Macmon strings on starting service\ncached_serfmon=\"\"\nif [ -f \"$SERFMON_CACHE\" ]; then\n    cached_serfmon=\"$(cat \"$SERFMON_CACHE\")\"\n    echo \"$cached_serfmon\"\nfi\n\ncached_macmon=\"\"\nif [ -f \"$MACMON_CACHE\" ]; then\n    cached_macmon=\"$(cat \"$MACMON_CACHE\")\"\n    echo \"$cached_macmon\"\nfi\n\nif [ \"$cached_serfmon\" != \"\" ] || [ \"$cached_macmon\" != \"\" ]; then\n    create_dummy_chassis_eeprom\nfi\n\nserfmon_updated=0\nmacmon_updated=0\nwhile true; do\n    if [ -f \"$MTERM_LOGFILE\" ]; then\n        maybe_update_cache cached_serfmon serfmon_updated \"$SERFMON_REGEX\" \\\n            \"$SERFMON_CACHE\" \"Serfmon\"\n        maybe_update_cache cached_macmon macmon_updated \"$MACMON_REGEX\" \\\n            \"$MACMON_CACHE\" \"Macmon\"\n\n        if [ \"$serfmon_updated\" != 0 ] || [ \"$macmon_updated\" != 0 ]; then\n            create_dummy_chassis_eeprom\n        fi\n    fi\n\n    # Sleep 15 seconds until the next loop.\n    # reduce for faster scan.\n    sleep 15\ndone\n", "num_lines": 143}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprintf \"%-1s | %-3s | %-30s\\n\" \"v\" \"dir\" \"GPIONAME\"\nfor i in /tmp/gpionames/*\ndo\n   gpio=\"$(basename \"$i\")\"\n   val=\"$(gpio_get_value \"$gpio\")\"\n   direction=\"$(gpio_get_direction \"$gpio\")\"\n   printf \"%-1s | %-3s | %-30s\\n\" \"$val\" \"$direction\" \"$gpio\"\ndone\n", "num_lines": 14}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# This utility prints the meta information for specified boot flash\n# mtd partition\nSTART_OFFSET_KB=960\nLEN_KB=64\n\nusage() {\n    echo \"Usage $0 [flash0|flash1]\"\n}\n\ncase \"$1\" in\n    flash0)\n        mtd=\"$(grep flash0 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    flash1)\n        mtd=\"$(grep flash1 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\ndd if=/dev/\"$mtd\" of=/tmp/.\"$1\"_meta bs=1K skip=\"$START_OFFSET_KB\" count=\"$LEN_KB\"\nstrings /tmp/.\"$1\"_meta\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\ntrap cleanup EXIT\ntrap handle_signal INT TERM QUIT\n\nOOB_EEPROM_SPI_PATH=\"/sys/bus/spi/devices/spi1.1/spi1.10/nvmem\"\n\nusage() {\n    echo \"Read or write to the BCM53134 OOB EEPROM\"\n    echo\n    echo \"read <file>\"\n    echo \"write <file>\"\n    echo \"version\"\n}\n\ngrab_uWire() {\n    gpio_set_value OOB_EEPROM_SPI_SEL 1\n}\n\nungrab_uWire() {\n    gpio_set_value OOB_EEPROM_SPI_SEL 0\n}\n\ncleanup() {\n    ungrab_uWire\n}\n\nhandle_signal() {\n    echo \"Exiting because of signal\" >&2\n    cleanup\n    exit 1\n}\n\neeprom_read() {\n    file=\"$1\"\n    file_temp=\"$file\"_temp\n    echo \"Reading spi1.1 BCM53134P EEPROM to $file...\"\n    # Add retry to BCM53134_EE read in case it fails\n    for n in 1 2 3 4 5\n    do\n        echo \"Reading $file $n times\"\n        dd if=\"$OOB_EEPROM_SPI_PATH\" of=\"$file\"\n        dd if=\"$OOB_EEPROM_SPI_PATH\" of=\"$file_temp\"\n        if ! diff \"$file\" \"$file_temp\" >/dev/null; then\n            echo \"Readback file differ on attempt $n\"\n            # read-back file differ\n            rm -rf \"$file\"*\n        else\n            # read-back file same\n            rm -rf \"$file_temp\";\n            return;\n        fi\n    done\n    logger -p user.err \"Unable to read the correct $file after 5 retries\"\n    exit 1\n}\n\neeprom_write() {\n    file=$1\n    echo \"Verifying target binary to program...\"\n    # We expect 0x01FF to be read in a certain offset of the binary\n    # If we get 0xFF01, the endianness of the binary is likely incorrect\n    # If we get neither, the binary is not recognized\n    magic_bytes=\"$(dd if=\"$file\" bs=1 skip=2 count=2 2>/dev/null | hexdump -n2)\"\n    if echo \"$magic_bytes\" | grep -q \"01ff\"; then\n        echo \"Binary endianness is big endian\"\n    elif echo \"$magic_bytes\" | grep -q \"ff01\"; then\n        echo \"Binary endianness is little endian\"\n        echo \"Are you sure the binary is in the correct format?\"\n        exit 1\n    else\n        echo \"Unable to match magic byte in binary\"\n        echo \"Are you sure the binary is correct?\"\n        exit 1\n    fi\n    echo \"Writing $file to spi1.1 BCM53134P EEPROM...\"\n    dd if=\"$file\" of=\"$OOB_EEPROM_SPI_PATH\"\n}\n\neeprom_version() {\n    local version\n    version_file=\"/tmp/version.bin\"\n    eeprom_read $version_file >/dev/null 2>&1\n    # Failure of eemprom_read terminates the process;\n    # don't need to check return value\n    version=\"0x$(hexdump $version_file | awk '{$1=\"\"}1' | tr -d \"[:space:]\" | tail -c 4)\"\n    printf \"Version: %d.%d\\n\" $(( version & 0xff )) $(( version >> 8 ))\n    rm -rf $version_file\n}\n\nif [ $# -lt 1 ]\nthen\n    echo \"Error: missing command\" >&2\n    usage\n    exit 1\nfi\n\n# Only allow one instance of script to run at a time.\nscript=$(realpath \"$0\")\nexec 100< \"$script\"\nflock -n 100 || { echo \"ERROR: $0 already running\" && exit 1; }\n\ncommand=\"$1\"\nshift\n\ngrab_uWire\ncase \"$command\" in\n    read)\n        eeprom_read \"$@\"\n        ;;\n    write)\n        eeprom_write \"$@\"\n        ;;\n    version)\n        eeprom_version\n        ;;\n    *)\n        echo \"Error: invalid command: $command\" >&2\n        usage\n        exit 1\n        ;;\nesac\n", "num_lines": 144}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2235\n. /usr/local/bin/openbmc-utils.sh\n\ntrap handle_signal INT TERM QUIT\n\n# mdio prints in the format \"PAGE_HEX/OFFSET_HEX VALUE_HEX == VALUE_BIN\\n\"\nMDIO_READ_PATTERN=\"^.* (0x[a-fA-F0-9]+).*$\"\n\n# Global variable to stack tabs for formatting\ntab=\"\"\n\nusage() {\n    echo \"Read BCM53134P (oob switch) port status registers\"\n    echo \"\"\n    echo \"# To dump all port status\"\n    echo \"oob-status.sh\"\n    echo \"# To dump port status for ports in 0, 1, 2, IMP\"\n    echo \"oob-status.sh [Port(s)]\"\n    echo \"# To print only link status\"\n    echo \"oob-status.sh link_status [Port(s)]\"\n    echo \"# To print only link speed\"\n    echo \"oob-status.sh link_speed [Port(s)]\"\n    echo \"\"\n    echo \"Example:\"\n    echo \"\"\n    echo \"oob-status.sh link_status 0 IMP\"\n    echo \"Link Status:\"\n    echo \"\tPort 0: Link Up\"\n    echo \"\tPort IMP: Link Up\"\n\n}\n\nhandle_signal() {\n    echo \"Exiting because of signal\" >&2\n    exit 1\n}\n\ncheck_sts_args() {\n    # Convert arguments to port numbers\n    local port val\n    ret=\"$*\"\n    if [ $# -lt 1 ]; then\n       # No arguments: do all ports\n       ret=\"0 1 2 IMP\"\n    else\n        for port in \"$@\"; do\n            if [ \"${port^^}\" != \"IMP\" ] && (! [[ \"$port\" =~ ^[0-9]+$ ]] \\\n                || [ \"$port\" -lt 0 ] || [ \"$port\" -gt 2 ]); then\n                echo \"Invalid port $port\"\n                exit 1\n            fi\n        done\n    fi\n}\n\nport_to_val() {\n    local val\n    if [ \"$1\" == \"IMP\" ]; then\n        val=8\n    else\n        val=\"$1\"\n    fi\n    echo \"$val\"\n}\n\ndo_read_lnksts() {\n    local page offset result ports port val\n    page=0x1\n    offset=0x0\n    result=$(oob-mdio-util.sh read16 \"$page\" \"$offset\" \\\n        | sed -E \"s/$MDIO_READ_PATTERN/\\1/\")\n    ports=\"$*\"\n\n    printf \"%sLink status:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        val=$(port_to_val \"$port\")\n        val=$(( (result >> val) & 0x1 ))\n        case \"$val\" in\n            0)\n                printf \"%sPort: %s Link Down\\n\" \"$tab\" \"$port\"\n                ;;\n            1)\n                printf \"%sPort: %s Link Up\\n\" \"$tab\" \"$port\"\n                ;;\n        esac\n    done\n    tab=${tab:1}\n}\n\ndo_read_spdsts() {\n    local page offset result ports port val\n    page=0x1\n    offset=0x4\n    result=$(oob-mdio-util.sh read32 \"$page\" \"$offset\" \\\n        | sed -E \"s/$MDIO_READ_PATTERN/\\1/\")\n    ports=\"$*\"\n\n    printf \"%sLink speed:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        val=$(port_to_val \"$port\")\n        val=$(( (result >> (val * 2)) & 0x3 ))\n        case \"$val\" in\n            0)\n                printf \"%sPort: %s 10 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n            1)\n                printf \"%sPort: %s 100 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n            2)\n                printf \"%sPort: %s 1000 Mb/s\\n\" \"$tab\" \"$port\"\n                ;;\n        esac\n    done\n    tab=${tab:1}\n}\n\nread_lnksts() {\n    check_sts_args \"$@\"\n    do_read_lnksts \"$ret\"\n}\n\nread_spdsts() {\n    check_sts_args \"$@\"\n    do_read_spdsts \"$ret\"\n}\n\nread_status() {\n    check_sts_args \"$@\"\n    printf \"%sStatus:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n    do_read_lnksts \"$ret\"\n    do_read_spdsts \"$ret\"\n    tab=${tab:1}\n}\n\n# Only allow one instance of script to run at a time.\nscript=$(realpath \"$0\")\nexec 100< \"$script\"\nflock -n 100 || { echo \"ERROR: $0 already running\" && exit 1; }\n\ncommand=\"$1\"\n\ncase \"$command\" in\n    link_status)\n        shift\n        read_lnksts \"$@\"\n        ;;\n    link_speed)\n        shift\n        read_spdsts \"$@\"\n        ;;\n    \"--help\")\n        usage\n        exit 1\n        ;;\n    *)\n        read_status \"$@\"\n        ;;\nesac\n", "num_lines": 187}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nlogger \"run-dhc6.sh: dhclient -6 Started..\"\npid=\"/var/run/dhclient6.usb0.pid\"\nexec dhclient -1 -6 -d -D LL --address-prefix-len 64 -pf ${pid} usb0 \"$@\"\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\n\n/usr/local/bin/front-paneld &\n\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# execute <fscd.py> <min syslog level>\n# log_level = <debug, warning, info>\n# Default log level in fscd is set to warning, if any other level is needed\n# set here\n. /usr/local/fbpackages/utils/ast-functions\n\nvr_ic=$(kv get VR_IC)\n# check the switch IC\nResult=$(gpio_get BOARD_ID0)\n\ndefault_fsc_config=\"/etc/fsc-config.json\"\nif [[ -f ${default_fsc_config} ]]; then\n  rm ${default_fsc_config}\nfi\n\nvendor=$(/usr/local/bin/cfg-util asic_mfr)\nif [[ \"$vendor\" == \"AMD\" && \"$vr_ic\" == \"VI\" && \"$Result\" == \"1\" ]]; then\n  ln -s /etc/fsc-config_AMD_vicor_brcm.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"AMD\" && \"$vr_ic\" == \"VI\" && \"$Result\" == \"0\" ]]; then\n  ln -s /etc/fsc-config_AMD_vicor_micp.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"AMD\" && \"$vr_ic\" == \"IF\" && \"$Result\" == \"1\" ]]; then\n  ln -s /etc/fsc-config_AMD_infineon_brcm.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"AMD\" && \"$vr_ic\" == \"IF\" && \"$Result\" == \"0\" ]]; then\n  ln -s /etc/fsc-config_AMD_infineon_micp.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"NVIDIA\" && \"$vr_ic\" == \"VI\" && \"$Result\" == \"1\" ]]; then\n  ln -s /etc/fsc-config_NVIDIA_vicor_brcm.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"NVIDIA\" && \"$vr_ic\" == \"VI\" && \"$Result\" == \"0\" ]]; then\n  ln -s /etc/fsc-config_NVIDIA_vicor_micp.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"NVIDIA\" && \"$vr_ic\" == \"IF\" && \"$Result\" == \"1\" ]]; then\n  ln -s /etc/fsc-config_NVIDIA_infineon_brcm.json ${default_fsc_config}\nelif [[ \"$vendor\" == \"NVIDIA\" && \"$vr_ic\" == \"IF\" && \"$Result\" == \"0\" ]]; then\n  ln -s /etc/fsc-config_NVIDIA_infineon_micp.json ${default_fsc_config}\nelse\n  ln -s /etc/fsc-config_NVIDIA_vicor_micp.json ${default_fsc_config}\nfi\n\nexec /usr/bin/fscd.py 'warning'\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho -n \"Setup fan speed... \"\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup gpio monitoring for emeraldpools... \"\n\n/usr/local/bin/gpiod &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 13 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\ni2c_mslave_add 0 0x16 #MB1\ni2c_mslave_add 1 0x16 #MB2\ni2c_mslave_add 2 0x16 #MB3\ni2c_mslave_add 3 0x16 #MB4\ni2c_mslave_add 13 0x10 #USB DBG\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_13 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_2 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_3 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 49}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n/etc/init.d/setup-i2c.sh &\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n . /usr/local/bin/openbmc-utils.sh\n . /usr/local/fbpackages/utils/ast-functions\n\nKVSET_CMD=/usr/bin/kv\n\n# check the switch IC\nResult=$(gpio_get BOARD_ID0)\n\nif [ \"$Result\" == \"1\" ]; then\n    $KVSET_CMD set \"switch_chip\" \"BRCM\"\n    # remove unnecessary aggregate sensors\n    rm -f /etc/aggregate-sensors.d/0001-vrs.json\nelse\n    $KVSET_CMD set \"switch_chip\" \"MICRO\"\nfi", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n . /usr/local/bin/openbmc-utils.sh\n . /usr/local/fbpackages/utils/ast-functions\n\nKVSET_CMD=/usr/bin/kv\n\n# check the VR IC\nResult=$(i2cget -f -y 17 0x45 0x1b 2>&1 1>/dev/null)\n\nif [ -n \"$Result\" ]; then\n    $KVSET_CMD set \"VR_IC\" \"VI\"\nelse\n    $KVSET_CMD set \"VR_IC\" \"IF\"\nfi", "num_lines": 14}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n/etc/init.d/sync-rtc.sh &\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n. /usr/local/fbpackages/utils/ast-functions\n\nfor i in {0..7};\ndo\n  for j in {0..4};\n  do\n    gpioexp_export 7-002${i} OAM${i}_LINK_CONFIG${j} ${j}\n  done\n  gpioexp_export 7-002${i} OAM${i}_PE_BIF1 5\n  gpioexp_export 7-002${i} OAM${i}_PE_BIF0 6\n  gpioexp_export 7-002${i} OAM${i}_MANF_MODE 7\n  gpioexp_export 7-002${i} OAM${i}_FW_RECOVERY 8\n  gpioexp_export 7-002${i} OAM${i}_TEST_MODE 9\n  gpioexp_export 7-002${i} OAM${i}_PLINK_CAP 10\n  gpioexp_export 7-002${i} OAM${i}_PWRRDT0 11\n  gpioexp_export 7-002${i} OAM${i}_PWRRDT1 12\n  gpioexp_export 7-002${i} OAM${i}_MODULE_PWRGD 13\n  gpioexp_export 7-002${i} OAM${i}_THERMTRIP 14\n\n  gpio_set OAM${i}_LINK_CONFIG0 0\n  gpio_set OAM${i}_LINK_CONFIG2 0\n  gpio_set OAM${i}_LINK_CONFIG4 0\ndone\n\nfor i in {0..3};\ndo\n  gpioexp_export 18-0067 FAN${i}_PRESENT ${i}\n  gpioexp_export 18-0067 FAN${i}_PWR_GOOD $((i+4))\n  gpioexp_export 18-0067 FAN${i}_OK $((i+8))\n  gpioexp_export 18-0067 FAN${i}_FAIL $((i+12))\n  gpio_set FAN${i}_OK 1\n  gpio_set FAN${i}_FAIL 0\ndone\n\n# To enable GPIOA\n#devmem_clear_bit $(scu_addr 80) 0\n#devmem_clear_bit $(scu_addr 80) 1\n#devmem_clear_bit $(scu_addr 80) 3\n#devmem_clear_bit $(scu_addr 80) 6\n#devmem_clear_bit $(scu_addr 80) 7\n#devmem_clear_bit $(scu_addr 90) 2\n\ngpio_export ASIC_PWR_EN_CTRL GPIOA0\n\n# Reserved\ngpio_export BMC_GPIOA1 GPIOA1\ngpio_export BMC_GPIOA2 GPIOA2\ngpio_export BMC_GPIOA3 GPIOA3\n\n# OAM debug mode enable\ngpio_export SCALE_DEBUG_EN_N_ASIC0 GPIOA7\ngpio_export SCALE_DEBUG_EN_N_ASIC1 GPIOA6\n\n# To enable GPIOB\n#devmem_clear_scu70_bit 23\n#devmem_clear_bit $(scu_addr 80) 13\n#devmem_clear_bit $(scu_addr 80) 14\n\n# PCIe switch GPIO (preserved)\ngpio_export PAX2_SKU_ID0 GPIOB0\ngpio_export PAX2_ALERT GPIOB1\ngpio_export PAX3_SKU_ID0 GPIOB4\ngpio_export PAX3_ALERT GPIOB5\ngpio_export PAX0_SKU_ID1 GPIOB6\ngpio_set PAX0_SKU_ID1 0\ngpio_export PAX1_SKU_ID1 GPIOB7\ngpio_set PAX1_SKU_ID1 0\n\n# BMC ready\ngpio_export BMC_READY_N GPIOB2\n\n# System power good\ngpio_export SYS_PWR_READY GPIOB3\n\n# To enable GPIOD\n#devmem_clear_scu70_bit 21\n#devmem_clear_bit $(scu_addr 8c) 8\n#devmem_clear_bit $(scu_addr 8c) 9\n#devmem_clear_bit $(scu_addr 8c) 10\n#devmem_clear_bit $(scu_addr 8c) 11\n#devmem_clear_bit $(scu_addr 90) 1\ngpio_export THERMTRIP_N_ASIC07 GPIOD7\n\n# To enable GPIOE\n#devmem_clear_scu70_bit 22\n#devmem_clear_bit $(scu_addr 80) 16\n#devmem_clear_bit $(scu_addr 80) 17\n#devmem_clear_bit $(scu_addr 80) 18\n#devmem_clear_bit $(scu_addr 80) 19\n#devmem_clear_bit $(scu_addr 80) 20\n#devmem_clear_bit $(scu_addr 80) 21\n#devmem_clear_bit $(scu_addr 80) 22\n#devmem_clear_bit $(scu_addr 80) 23\n#devmem_clear_bit $(scu_addr 8c) 12\n#devmem_clear_bit $(scu_addr 8c) 13\n#devmem_clear_bit $(scu_addr 8c) 14\n#devmem_clear_bit $(scu_addr 8c) 15\n\n# BMC power button (input)\ngpio_export BMC_PWR_BTN_IN_N GPIOE0\n\n# PDB 12V POWER (output)\ngpio_export BMC_IPMI_PWR_ON GPIOE1\ngpio_set BMC_IPMI_PWR_ON 1\n\n# ASIC warm reset\ngpio_export WARMRST_BMC_N_ASIC0 GPIOE7\ngpio_set WARMRST_BMC_N_ASIC0 1\ngpio_export WARMRST_BMC_N_ASIC1 GPIOE6\ngpio_set WARMRST_BMC_N_ASIC1 1\ngpio_export WARMRST_BMC_N_ASIC2 GPIOE5\ngpio_set WARMRST_BMC_N_ASIC2 1\ngpio_export WARMRST_BMC_N_ASIC3 GPIOE4\ngpio_set WARMRST_BMC_N_ASIC3 1\ngpio_export WARMRST_BMC_N_ASIC4 GPIOE3\ngpio_set WARMRST_BMC_N_ASIC4 1\ngpio_export WARMRST_BMC_N_ASIC5 GPIOE2\ngpio_set WARMRST_BMC_N_ASIC5 1\n\n# To enable GPIOF\n#devmem_clear_bit $(scu_addr 80) 24\n#devmem_clear_bit $(scu_addr 80) 25\n#devmem_clear_bit $(scu_addr 80) 26\n#devmem_clear_bit $(scu_addr 80) 27\n#devmem_clear_bit $(scu_addr 80) 28\n#devmem_clear_bit $(scu_addr 80) 29\n#devmem_clear_bit $(scu_addr 80) 30\n#devmem_clear_bit $(scu_addr 80) 31\n#devmem_clear_bit $(scu_addr 90) 30\n\n# POST LED \ngpio_export LED_POSTCODE_0 GPIOF0\ngpio_set LED_POSTCODE_0 0\ngpio_export LED_POSTCODE_1 GPIOF1\ngpio_set LED_POSTCODE_1 0\ngpio_export LED_POSTCODE_2 GPIOF2\ngpio_set LED_POSTCODE_2 0\ngpio_export LED_POSTCODE_3 GPIOF3\ngpio_set LED_POSTCODE_3 0\ngpio_export LED_POSTCODE_4 GPIOF4\ngpio_set LED_POSTCODE_4 0\ngpio_export LED_POSTCODE_5 GPIOF5\ngpio_set LED_POSTCODE_5 0\ngpio_export LED_POSTCODE_6 GPIOF6\ngpio_set LED_POSTCODE_6 0\ngpio_export LED_POSTCODE_7 GPIOF7\ngpio_set LED_POSTCODE_7 0\n\n# To enable GPIOG\n#devmem_clear_bit $(scu_addr 84) 0\n#devmem_clear_bit $(scu_addr 84) 1\n#devmem_clear_bit $(scu_addr 84) 2\n#devmem_clear_bit $(scu_addr 84) 3\n#devmem_clear_bit $(scu_addr 84) 4\n#devmem_clear_bit $(scu_addr 84) 5\n#devmem_clear_bit $(scu_addr 84) 6\n#devmem_clear_bit $(scu_addr 84) 7\n#devmem_clear_bit $(scu_addr 94) 12\n\n# JTAG mux, 1 = Altera PFR, 0 = Lattice\ngpio_export SEL_CPLD GPIOG0\ngpio_set SEL_CPLD 0\n\n# TPM presence\ngpio_export FM_BMC_TPM_PRES_N GPIOG1\n\n# Enable JTAG mux, 1 = Disbale, 0 = Enable\ngpio_export JTAG_ENABLE GPIOG2\ngpio_set JTAG_ENABLE 0\n\n# OAM test pin (defined by OAM)\ngpio_export BMC_OAM_TEST7 GPIOG3\ngpio_export BMC_OAM_TEST8 GPIOG7\n\n# Board revision ID\ngpio_export REV_ID0 GPIOG4\ngpio_export REV_ID1 GPIOG5\ngpio_export REV_ID2 GPIOG6\n\nID0=$(gpio_get REV_ID0)\nID1=$(gpio_get REV_ID1)\nID2=$(gpio_get REV_ID2)\nREV_ID=$(($ID0 + $ID1*2 + $ID2*4))\nif [[ $REV_ID < 5 ]]; then\n  # FAB6\n  ioexp_bus=13\nelse\n  ioexp_bus=4\nfi\n\ngpioexp_export ${ioexp_bus}-0020 CONN1_0_PRSNT0_N 8\ngpioexp_export ${ioexp_bus}-0020 CONN1_0_PRSNT1_N 9\ngpioexp_export ${ioexp_bus}-0020 CONN1_1_PRSNT0_N 12\ngpioexp_export ${ioexp_bus}-0020 CONN1_1_PRSNT1_N 13\ngpioexp_export ${ioexp_bus}-0020 CONN2_0_PRSNT0_N 0\ngpioexp_export ${ioexp_bus}-0020 CONN2_0_PRSNT1_N 1\ngpioexp_export ${ioexp_bus}-0020 CONN2_1_PRSNT0_N 4\ngpioexp_export ${ioexp_bus}-0020 CONN2_1_PRSNT1_N 5\ngpioexp_export ${ioexp_bus}-0020 CONN3_0_PRSNT0_N 2\ngpioexp_export ${ioexp_bus}-0020 CONN3_0_PRSNT1_N 3\ngpioexp_export ${ioexp_bus}-0020 CONN3_1_PRSNT0_N 6\ngpioexp_export ${ioexp_bus}-0020 CONN3_1_PRSNT1_N 7\ngpioexp_export ${ioexp_bus}-0020 CONN4_0_PRSNT0_N 10\ngpioexp_export ${ioexp_bus}-0020 CONN4_0_PRSNT1_N 11\ngpioexp_export ${ioexp_bus}-0020 CONN4_1_PRSNT0_N 14\ngpioexp_export ${ioexp_bus}-0020 CONN4_1_PRSNT1_N 15\n\nif [[ \"$(gpio_get CONN2_0_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN2_0_PRSNT1_N)\" == \"0\" && \\\n      \"$(gpio_get CONN3_0_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN3_0_PRSNT1_N)\" == \"0\" ]]; then\n  MB0_PRSNT=1;\nelse\n  MB0_PRSNT=0;\nfi\n\nif [[ \"$(gpio_get CONN2_1_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN2_1_PRSNT1_N)\" == \"0\" && \\\n      \"$(gpio_get CONN3_1_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN3_1_PRSNT1_N)\" == \"0\" ]]; then\n  MB1_PRSNT=1;\nelse\n  MB1_PRSNT=0;\nfi\n\nif [[ \"$(gpio_get CONN1_0_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN1_0_PRSNT1_N)\" == \"0\" && \\\n      \"$(gpio_get CONN4_0_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN4_0_PRSNT1_N)\" == \"0\" ]]; then\n  MB2_PRSNT=1;\nelse\n  MB2_PRSNT=0;\nfi\n\nif [[ \"$(gpio_get CONN1_1_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN1_1_PRSNT1_N)\" == \"0\" && \\\n      \"$(gpio_get CONN4_1_PRSNT0_N)\" == \"0\" && \\\n      \"$(gpio_get CONN4_1_PRSNT1_N)\" == \"0\" ]]; then\n  MB3_PRSNT=1;\nelse\n  MB3_PRSNT=0;\nfi\n\n# To enable GPIOH\n#devmem_clear_bit $(scu_addr 90) 7\n#devmem_clear_bit $(scu_addr 94) 5\n#devmem_clear_bit $(scu_addr 94) 6\n#devmem_clear_bit $(scu_addr 94) 7\n\n# ASIC presence\ngpio_export PRSNT0_N_ASIC7 GPIOH0\ngpio_export PRSNT0_N_ASIC6 GPIOH1\ngpio_export PRSNT0_N_ASIC5 GPIOH2\ngpio_export PRSNT0_N_ASIC4 GPIOH3\ngpio_export PRSNT0_N_ASIC3 GPIOH4\ngpio_export PRSNT0_N_ASIC2 GPIOH5\ngpio_export PRSNT0_N_ASIC1 GPIOH6\ngpio_export PRSNT0_N_ASIC0 GPIOH7\n\n# To enable GPIOI\n#devmem_clear_scu70_bit 13\n\n# OAM debug pin (defined by OAM)\ngpio_export BMC_OAM_TEST13 GPIOI0\ngpio_export BMC_OAM_TEST14 GPIOI1\n\ngpio_export OAM_FAST_BRK_N GPIOI2\ngpio_set OAM_FAST_BRK_N 1\n\ngpio_export OAM_FAST_BRK_ON_N GPIOI3\ngpio_set OAM_FAST_BRK_ON_N 1\n\n# OAM debug pin (defined by OAM)\ngpio_export BMC_OAM_TEST3 GPIOJ0\ngpio_export BMC_OAM_TEST4 GPIOJ1\ngpio_export BMC_OAM_TEST5 GPIOJ2\ngpio_export BMC_OAM_TEST6 GPIOJ3\ngpio_export BMC_OAM_TEST0 GPIOJ6\ngpio_export BMC_OAM_TEST1 GPIOJ7\n\n# OAM debug mode enable\ngpio_export SCALE_DEBUG_EN_N_ASIC5 GPIOJ4\ngpio_export SCALE_DEBUG_EN_N_ASIC4 GPIOJ5\n\n# To enable GPIOL\n#devmem_clear_bit $(scu_addr 84) 16\n#devmem_clear_bit $(scu_addr 84) 17\n#devmem_clear_bit $(scu_addr 84) 18\n#devmem_clear_bit $(scu_addr 84) 19\n#devmem_clear_bit $(scu_addr 84) 20\n#devmem_clear_bit $(scu_addr 84) 21\n#devmem_clear_bit $(scu_addr 90) 5\n\n# Select clock source from MB\n# [S1:S0]\n# 0:0 = MB#0\n# 1:0 = MB#1\n# 0:1 = MB#2\n# 1:1 = MB#3\ngpio_export SEL0_CLK_MUX GPIOL0\ngpio_set SEL0_CLK_MUX 0\ngpio_export SEL1_CLK_MUX GPIOL1\ngpio_set SEL1_CLK_MUX 0\n\n# Output control for clock source from MB\n# 1 = enable, 0 = high-impedance state\ngpio_export OEA_CLK_MUX_N GPIOL2\ngpio_set OEA_CLK_MUX_N 1\ngpio_export OEB_CLK_MUX_N GPIOL3\ngpio_set OEB_CLK_MUX_N 0\n\n# ASIC warm reset\ngpio_export WARMRST_BMC_N_ASIC7 GPIOL4\ngpio_set WARMRST_BMC_N_ASIC7 1\ngpio_export WARMRST_BMC_N_ASIC6 GPIOL5\ngpio_set WARMRST_BMC_N_ASIC6 1\n\n# To enable GPIOM\n#devmem_clear_bit $(scu_addr 84) 24\n#devmem_clear_bit $(scu_addr 84) 25\n#devmem_clear_bit $(scu_addr 84) 26\n#devmem_clear_bit $(scu_addr 84) 27\n#devmem_clear_bit $(scu_addr 84) 28\n#devmem_clear_bit $(scu_addr 84) 29\n\n# Slave i2c alert (defined by OAM)\ngpio_export SMB_ALERT_ASIC01 GPIOM2\ngpio_export SMB_ALERT_ASIC23 GPIOM3\ngpio_export SMB_ALERT_ASIC45 GPIOM4\ngpio_export SMB_ALERT_ASIC67 GPIOM5\n\n# PCIe switch GPIO (preserved)\ngpio_export PAX2_SKU_ID1 GPIOM0\ngpio_set PAX2_SKU_ID1 0\ngpio_export PAX3_SKU_ID1 GPIOM6\ngpio_set PAX3_SKU_ID1 0\n\n# Power control for Debug\n# 1 = controlled by BMC\n# 0 = controlled by CPLD\ngpio_export PWR_CTRL GPIOM1\n\nfor i in {0..3};\ndo\n  PRSNT=MB${i}_PRSNT\n  if [[ \"${!PRSNT}\" == \"1\" ]]; then\n    echo \"Server is detected\"\n    gpio_set PWR_CTRL 0\n    break\n  fi\ndone\n\n# To enable GPION\n#devmem_clear_bit $(scu_addr 88) 2\n#devmem_clear_bit $(scu_addr 88) 3\n#devmem_clear_bit $(scu_addr 88) 4\n#devmem_clear_bit $(scu_addr 88) 5\n#devmem_clear_bit $(scu_addr 88) 6\n#devmem_clear_bit $(scu_addr 88) 7\n\n# OAM debug pin (defined by OAM)\ngpio_export BMC_OAM_TEST2 GPION4\n\n# Board ID\ngpio_export BOARD_ID0 GPION5\ngpio_export BOARD_ID1 GPION6\ngpio_export BOARD_ID2 GPION7\n\n# To enable GPIOO\n#devmem_clear_bit $(scu_addr 88) 8\n#devmem_clear_bit $(scu_addr 88) 9\n#devmem_clear_bit $(scu_addr 88) 10\n#devmem_clear_bit $(scu_addr 88) 11\n#devmem_clear_bit $(scu_addr 88) 12\n#devmem_clear_bit $(scu_addr 88) 13\n#devmem_clear_bit $(scu_addr 88) 14\n#devmem_clear_bit $(scu_addr 88) 15\n\n# To enable GPIOP\n#devmem_clear_bit $(scu_addr 88) 16\n#devmem_clear_bit $(scu_addr 88) 17\n#devmem_clear_bit $(scu_addr 88) 18\n#devmem_clear_bit $(scu_addr 88) 19\n#devmem_clear_bit $(scu_addr 88) 20\n#devmem_clear_bit $(scu_addr 88) 21\n#devmem_clear_bit $(scu_addr 88) 22\n#devmem_clear_bit $(scu_addr 88) 23\n\n# OAM debug pin (defined by OAM)\ngpio_export BMC_OAM_TEST9 GPIOP0\ngpio_export BMC_OAM_TEST10 GPIOP1\ngpio_export BMC_OAM_TEST11 GPIOP2\ngpio_export BMC_OAM_TEST12 GPIOP3\n\n# ASIC presence\ngpio_export PRSNT1_N_ASIC3 GPIOP4\ngpio_export PRSNT1_N_ASIC2 GPIOP5\ngpio_export PRSNT1_N_ASIC1 GPIOP6\ngpio_export PRSNT1_N_ASIC0 GPIOP7\n\n# To enable GPIOQ\n#devmem_clear_bit $(scu_addr 2c) 1\n#devmem_clear_bit $(scu_addr 2c) 29\n\n# Battery voltage detect control\ngpio_export BATTERY_DETECT GPIOQ6\ngpio_set BATTERY_DETECT 0\n\n# Reserved\ngpio_export BMC_GPIOQ7 GPIOQ7\n\n# To enable GPIOR\n#devmem_clear_bit $(scu_addr 88) 25\n#devmem_clear_bit $(scu_addr 88) 26\n#devmem_clear_bit $(scu_addr 88) 27\n#devmem_clear_bit $(scu_addr 88) 28\n#devmem_clear_bit $(scu_addr 88) 29\n#devmem_clear_bit $(scu_addr 88) 30\n#devmem_clear_bit $(scu_addr 88) 31\n\n# OAM debug mode enable\ngpio_export SCALE_DEBUG_EN_N_ASIC3 GPIOR6\ngpio_export SCALE_DEBUG_EN_N_ASIC2 GPIOR7\n\n# To enable GPIOS\n#devmem_clear_bit $(scu_addr 8C) 0\n#devmem_clear_bit $(scu_addr 8C) 1\n#devmem_clear_bit $(scu_addr 8C) 2\n#devmem_clear_bit $(scu_addr 8C) 3\n#devmem_clear_bit $(scu_addr 8C) 4\n#devmem_clear_bit $(scu_addr 8C) 5\n#devmem_clear_bit $(scu_addr 8C) 6\n#devmem_clear_bit $(scu_addr 8C) 7\n\n# HSC throttle\ngpio_export HSC1_THROT_N GPIOS0\ngpio_export HSC2_THROT_N GPIOS1\n\n# Set target OAM for test\ngpio_export CPLD_MUX_ID3 GPIOS2\ngpio_set CPLD_MUX_ID3 0\n\n# PMBUS alert from HSC\ngpio_export PMBUS_BMC_1_ALERT_N GPIOS3\n\n# To enable GPIOT\n#devmem_clear_bit $(scu_addr 48) 29\n#devmem_clear_bit $(scu_addr 48) 30\n#devmem_set_bit $(scu_addr a0) 0\n#devmem_set_bit $(scu_addr a0) 4\n#devmem_set_bit $(scu_addr a0) 5\n#devmem_set_bit $(scu_addr a0) 6\n\n# OAM debug mode enable\ngpio_export SCALE_DEBUG_EN_N_ASIC6 GPIOT0\ngpio_export SCALE_DEBUG_EN_N_ASIC7 GPIOT6\ngpio_export PD_GPIOT7 GPIOT7\n\n# To enable GPIOU\n#devmem_set_bit $(scu_addr a0) 10\n#devmem_set_bit $(scu_addr a0) 11\n#devmem_set_bit $(scu_addr a0) 13\ngpio_export PD_GPIOU1 GPIOU1\ngpio_export PD_GPIOU2 GPIOU2\ngpio_export PD_GPIOU3 GPIOU3\n\n# PCIe switch firmware recovery pin\ngpio_export BMC_BOOT_RCVR_B0_PAX0 GPIOU4\ngpio_set BMC_BOOT_RCVR_B0_PAX0 0\ngpio_export BMC_BOOT_RCVR_B0_PAX1 GPIOU5\ngpio_set BMC_BOOT_RCVR_B0_PAX1 0\ngpio_export BMC_BOOT_RCVR_B0_PAX2 GPIOU6\ngpio_set BMC_BOOT_RCVR_B0_PAX2 0\ngpio_export BMC_BOOT_RCVR_B0_PAX3 GPIOU7\ngpio_set BMC_BOOT_RCVR_B0_PAX3 0\n\n# To enable GPIOV\n#devmem_set_bit $(scu_addr a0) 19\n\n# Debug connector presence\n# 1 = no debug port\ngpio_export JTAG_0_SCR_PRESENT GPIOV1\n\n# OAM JTAG SEL\ngpio_export BMC2OAM_JTAG_PT_EN GPIOV2\ngpio_set BMC2OAM_JTAG_PT_EN 0\ngpio_export BMC2OAM_JTAG_PT_SEL GPIOV3\ngpio_set BMC2OAM_JTAG_PT_SEL 0\n\n# Reset eMMC on BSM\n# 0 = reset, 1 = not reset\ngpio_export BMC_EMMC_RST_R0_N GPIOV4\ngpio_set BMC_EMMC_RST_R0_N 1\n\n# PMBUS alert from HSC\ngpio_export PMBUS_BMC_3_ALERT_N GPIOV5\ngpio_export PMBUS_BMC_2_ALERT_N GPIOV6\n\n# i2c alert from CPLD\ngpio_export CPLD_SMB_ALERT_N GPIOV7\n\n# To enable GPIOY\n#devmem_clear_scu70_bit 19\n#devmem_clear_bit $(scu_addr 94) 10\n#devmem_clear_bit $(scu_addr 94) 11\n#devmem_clear_bit $(scu_addr a4) 8\n#devmem_clear_bit $(scu_addr a4) 9\n#devmem_clear_bit $(scu_addr a4) 10\n#devmem_clear_bit $(scu_addr a4) 11\n\n# ASIC presence\ngpio_export PRSNT1_N_ASIC7 GPIOY0\ngpio_export PRSNT1_N_ASIC6 GPIOY1\ngpio_export PRSNT1_N_ASIC5 GPIOY2\ngpio_export PRSNT1_N_ASIC4 GPIOY3\n\n# To enable GPIOZ\n#devmem_clear_bit $(scu_addr 90) 31\n#devmem_clear_bit $(scu_addr a4) 16\n#devmem_clear_bit $(scu_addr a4) 17\n#devmem_clear_bit $(scu_addr a4) 18\n#devmem_clear_bit $(scu_addr a4) 19\n#devmem_clear_bit $(scu_addr a4) 20\n#devmem_clear_bit $(scu_addr a4) 21\n#devmem_clear_bit $(scu_addr a4) 22\n#devmem_clear_bit $(scu_addr a4) 23\n\n# Select USB from MB\n# [S1:S0]\n# 1:1 = MB#0\n# 1:0 = MB#1\n# 0:1 = MB#2\n# 0:0 = MB#3\n# PCH\ngpio_export USB2_SEL0_U42 GPIOZ0\ngpio_set USB2_SEL0_U42 1\ngpio_export USB2_SEL1_U42 GPIOZ1\ngpio_set USB2_SEL1_U42 1\n# BMC\ngpio_export USB2_SEL0_U43 GPIOZ2\ngpio_set USB2_SEL0_U43 1\ngpio_export USB2_SEL1_U43 GPIOZ3\ngpio_set USB2_SEL1_U43 1\n\n# To enable GPIOAA\n#devmem_clear_bit $(scu_addr a4) 24\n#devmem_clear_bit $(scu_addr a4) 25\n#devmem_clear_bit $(scu_addr a4) 26\n#devmem_clear_bit $(scu_addr a4) 27\n#devmem_clear_bit $(scu_addr a4) 28\n#devmem_clear_bit $(scu_addr a4) 29\n#devmem_clear_bit $(scu_addr a4) 30\n#devmem_clear_bit $(scu_addr a4) 31\n\n# SPI flash select of PCIe switch\n# 0: access by PCIe switch\n# 1: access by BMC\ngpio_export SEL_FLASH_PAX0 GPIOAA0\ngpio_set SEL_FLASH_PAX0 0\ngpio_export SEL_FLASH_PAX1 GPIOAA1\ngpio_set SEL_FLASH_PAX1 0\ngpio_export SEL_FLASH_PAX2 GPIOAA5\ngpio_set SEL_FLASH_PAX2 0\ngpio_export SEL_FLASH_PAX3 GPIOAA6\ngpio_set SEL_FLASH_PAX3 0\n\n# System log LED\ngpio_export SYSTEM_LOG_LED GPIOAA2\ngpio_set SYSTEM_LOG_LED 0\n\n# Select USB from PCH/BMC of MB\n# 0: BMC\n# 1: PCH\ngpio_export SEL_USB_MUX GPIOAA3\ngpio_set SEL_USB_MUX 0\n\n# SPI BMC write protection\ngpio_export SPI_BMC_BT_WP0_N GPIOAA4\ngpio_set SPI_BMC_BT_WP0_N 1\n\n# FRU on BSM write protection\n# 0 = writable\ngpio_export FRU_WP GPIOAA7\ngpio_set FRU_WP 0\n\n# To enable GPIOAB\n#devmem_clear_bit $(scu_addr a8) 0\n#devmem_clear_bit $(scu_addr a8) 1\n#devmem_clear_bit $(scu_addr a8) 3\n\n# Set target OAM for test\ngpio_export CPLD_MUX_ID0 GPIOAB1\ngpio_set CPLD_MUX_ID0 0\ngpio_export CPLD_MUX_ID1 GPIOAB0\ngpio_set CPLD_MUX_ID1 0\ngpio_export CPLD_MUX_ID2 GPIOAB3\ngpio_set CPLD_MUX_ID2 0\n\n# To enable GPIOAC\ndevmem_clear_bit $(scu_addr ac) 0\ndevmem_clear_bit $(scu_addr ac) 1\ndevmem_clear_bit $(scu_addr ac) 2\ndevmem_clear_bit $(scu_addr ac) 3\ndevmem_clear_bit $(scu_addr ac) 5\ndevmem_clear_bit $(scu_addr ac) 6\ndevmem_clear_bit $(scu_addr ac) 7\n\n# PCIe switch GPIO (preserved)\ngpio_export PAX0_SKU_ID0 GPIOAC0\ngpio_export PAX0_ALERT GPIOAC1\ngpio_export PAX1_SKU_ID0 GPIOAC2\ngpio_export PAX1_ALERT GPIOAC3\n\n# Reserved\ngpio_export BMC_GPIOAC5 GPIOAC5\ngpio_export BMC_GPIOAC6 GPIOAC6\ngpio_export BMC_GPIOAC7 GPIOAC7\n", "num_lines": 651}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Keep \"power-util mb on\" for debug purpose\necho \"Waiting for power up\"\npwr_ctrl=$(gpio_get PWR_CTRL keepdirection)\npwr_ready=$(gpio_get SYS_PWR_READY keepdirection)\nboard_id=$(gpio_get BOARD_ID0 keepdirection)\nwhile [ \"$pwr_ready\" != \"1\" ]\ndo\n  if [[ \"$pwr_ctrl\" == \"1\" ]]; then\n    power-util mb on > /dev/null\n  fi\n  sleep 1\n  pwr_ready=$(gpio_get SYS_PWR_READY keepdirection)\ndone\n\n# Thermal sensors for PCIe switches\ni2c_device_add 6 0x4d tmp422\ni2c_device_add 6 0x4e tmp422\n\n# Voltage regulators\nif [ $board_id -eq 1 ]; then\n  i2c_device_add 5 0x60 isl69260\n  i2c_device_add 5 0x61 isl69260\n  i2c_device_add 5 0x72 isl69260\n  i2c_device_add 5 0x75 isl69260\n  i2c_device_add 5 0x34 mpq8645p\n  i2c_device_add 5 0x35 mpq8645p\n  i2c_device_add 5 0x36 mpq8645p\n  i2c_device_add 5 0x3b mpq8645p\nelse\n  i2c_device_add 5 0x30 mpq8645p\n  i2c_device_add 5 0x31 mpq8645p\n  i2c_device_add 5 0x32 mpq8645p\n  i2c_device_add 5 0x33 mpq8645p  \n  i2c_device_add 5 0x34 mpq8645p\n  i2c_device_add 5 0x35 mpq8645p\n  i2c_device_add 5 0x36 mpq8645p\n  i2c_device_add 5 0x3b mpq8645p\nfi\n\n# P48V HSCs\ni2c_bind_driver adm1275 16-0013\ni2c_bind_driver adm1275 17-0010\n\n# i2c mux in front of OAMs\ni2c_mux_add_sync 11 0x70 pca9543 2\ni2c_mux_add_sync 10 0x70 pca9543 2\ni2c_mux_add_sync 9 0x70 pca9543 2\ni2c_mux_add_sync 8 0x70 pca9543 2\n\n# Reload lm_sensors config\nsv restart sensord > /dev/null\nsv restart ipmid > /dev/null\n# Mark driver loaded\necho > /tmp/driver_probed\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Provision Status\nfor i in {1..3}; do\n  pfr=$(/usr/sbin/i2cget -y 4 0x58 0x0a b 2>/dev/null)\n  if [ $? -eq 0 ]; then\n    pfr=$((pfr & 0x20))\n    break\n  fi\n  pfr=255\n  sleep 0.5\ndone\n\nif [ $pfr -eq 255 ]; then\n  exit\nfi\n\nfor i in {1..3}; do\n  c0=$(/usr/sbin/i2cget -y 4 0x58 0xc0 b 2>/dev/null)\n  [  $? -eq 0 ] && c0=$((c0 & 0xff))\n  c1=$(/usr/sbin/i2cget -y 4 0x58 0xc1 b 2>/dev/null)\n  [  $? -eq 0 ] && c1=$((c1 & 0xff))\n\n  offs=$(devmem 0x1e72120c 2>/dev/null)\n  start=$((offs & 0xff))\n  end=$(((offs >> 8) & 0xff))\n\n  sleep 1\n  if [[ \"$c0\" == \"$start\" && \"$c1\" == \"$end\" ]]; then\n    break\n  fi\ndone\n\n# CHKPT_COMPLETE\nfor i in {1..3}; do\n  /usr/sbin/i2cset -y 4 0x58 0x0f 0x09 b > /dev/null 2>&1\n  if [ $? -eq 0 ]; then\n    break\n  fi\n  sleep 0.5\ndone\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          switch-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description:  Set up strap pins to determine the switch configuration\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup PCIe switch configuration \"\n# 4SEX by default\ngpio_set PAX0_SKU_ID0 0\ngpio_set PAX0_SKU_ID1 0\ngpio_set PAX1_SKU_ID0 0\ngpio_set PAX1_SKU_ID1 0\ngpio_set PAX2_SKU_ID0 0\ngpio_set PAX2_SKU_ID1 0\ngpio_set PAX3_SKU_ID0 0\ngpio_set PAX3_SKU_ID1 0\n\nserver_type=$(kv get server_type persistent)\nif [ $? -ne 0 ]; then\n  # Get config from MB0's BMC\n  for retry in {1..200};\n  do\n    val=$(/usr/local/bin/ipmb-util 2 0x20 0xE8 0x0)\n    val=${val:1:1}\n    if [[ \"$val\" == \"0\" ]]; then\n      /usr/local/bin/cfg-util server_type 8\n      server_type=8\n      break\n    elif [[ \"$val\" == \"1\" ]]; then\n      /usr/local/bin/cfg-util server_type 4\n      server_type=4\n      break\n    elif [[ \"$val\" == \"2\" ]]; then\n      /usr/local/bin/cfg-util server_type 2\n      server_type=2\n      break\n    else\n      echo -n \".\"\n      sleep 1\n    fi\n  done\nelse\n  # TODO:\n  #   Sync EEPROM with cache for those old systems\n  #   We can remove this after all systems got updated\n  val=$(ipmitool i2c bus=6 0xA8 0x1 0x4 0x6)\n  val=${val:2:1}\n  if [[ \"$val\" != \"$server_type\" ]]; then\n    /usr/local/bin/cfg-util server_type $server_type\n  fi\nfi\n\ncase $server_type in\n  8)\n    gpio_set PAX0_SKU_ID0 0\n    gpio_set PAX0_SKU_ID1 1\n    gpio_set PAX1_SKU_ID0 0\n    gpio_set PAX1_SKU_ID1 1\n    gpio_set PAX2_SKU_ID0 0\n    gpio_set PAX2_SKU_ID1 1\n    gpio_set PAX3_SKU_ID0 0\n    gpio_set PAX3_SKU_ID1 1\n    ;;\n  4)\n    gpio_set PAX0_SKU_ID0 0\n    gpio_set PAX0_SKU_ID1 0\n    gpio_set PAX1_SKU_ID0 0\n    gpio_set PAX1_SKU_ID1 0\n    gpio_set PAX2_SKU_ID0 0\n    gpio_set PAX2_SKU_ID1 0\n    gpio_set PAX3_SKU_ID0 0\n    gpio_set PAX3_SKU_ID1 0\n    ;;\n  2)\n    gpio_set PAX0_SKU_ID0 1\n    gpio_set PAX0_SKU_ID1 0\n    gpio_set PAX1_SKU_ID0 1\n    gpio_set PAX1_SKU_ID1 0\n    gpio_set PAX2_SKU_ID0 1\n    gpio_set PAX2_SKU_ID1 0\n    gpio_set PAX3_SKU_ID0 1\n    gpio_set PAX3_SKU_ID1 0\n    ;;\nesac\necho \"done\"\n\ngpio_set BMC_READY_N 0\n", "num_lines": 113}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\naddr=$(/usr/bin/mac-util --get)\nif [[ \"$addr\" == \"ff:ff:ff:ff:ff:ff\" ]]\nthen\n  addr=\"02:00:00:00:00:01\"\nfi\nmodprobe g_ether host_addr=02:00:00:00:00:02 dev_addr=$addr\n\nifconfig usb0 up\n\ndhclient -d -pf /var/run/dhclient.usb0.pid usb0 > /dev/null 2>&1 &\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Sync RTC with NTP\nsync_rtc()\n{\n  while [ \"$(ntpq -c rv | grep leap_none)\" == \"\" ]\n  do\n    sleep 10\n  done\n  # if leap code returned normal sync state\n  echo Syncing up RTC time with NTP...\n  test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  return\n}\n\nsync_rtc\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Overwrite the register 0x1 of AUX HSC with 0x2\"\ni2cset -f -y 18 0x43 0x1 0x2\n\n# Set the OCW of P12V_1/P12V_2 HSC to ~290 Amps then enable it\n\ni2cset -f -y 17 0x40 0xD 0xB9\ni2cset -f -y 16 0x53 0xD 0xB9\n\nval=$(i2cget -f -y 17 0x40 0x3)\nalert_reg=$(($val|0x20))\ni2cset -f -y 17 0x40 0x3 $alert_reg\nval=$(i2cget -f -y 16 0x53 0x3)\nalert_reg=$(($val|0x20))\ni2cset -f -y 16 0x53 0x3 $alert_reg", "num_lines": 16}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmid\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ipmid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set IPMI2 Message handler\n### END INIT INFO\n\necho -n \"Setup IPMI2 message handler... \"\nrunsv /etc/sv/ipmid > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nmTerm_server_running() {\n  # shellcheck disable=SC2009\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ \"$pid\" ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  /usr/bin/microcom -s @BAUDRATE@ /dev/@TERM@\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#\n# OVERRIDE_ME: this file needs to be overridden by platform!\n#\n\nuserver_power_is_on() {\n    echo \"userver_power_is_on() not implemented. Assuming uServer is off!\"\n    return 1\n}\n\nuserver_power_on() {\n    echo \"userver_power_on() not implemented. Exiting..\"\n    return 1\n}\n\nuserver_power_off() {\n    echo \"userver_power_off() not implemented. Exiting..\"\n    return 1\n}\n\nuserver_reset() {\n    echo \"userver_reset() not implemented. Exiting..\"\n    return 1\n}\n\nchassis_power_cycle() {\n    echo \"chassis_power_cycle() not implemented. Exiting..\"\n    return 1\n}\n\nbmc_mac_addr() {\n    echo \"\"\n}\n\nuserver_mac_addr() {\n    echo \"\"\n}\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\necho \"Checking x86 (userver) power status... \"\nif userver_power_is_on; then\n    echo \"userver is already powered. Skipped.\"\n    exit 0\nfi\n\nwedge_power.sh on -f\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n\n#\n# OVERRIDE_ME: this file needs to be overridden by platform!\n#\necho \"setup-gpio.sh is empty. Exiting.\"\nexit 0\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#\n# OVERRIDE_ME: this file needs to be overridden by platform!\n#\n\necho \"setup_board.sh is empty. Exiting.\"\nexit 0\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#\n# OVERRIDE_ME: this file needs to be overridden by platform!\n#\necho \"setup_i2c.sh is empty. Exiting.\"\nexit 0\n", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current x86 (userver) power status\"\n    echo\n    echo \"  on: Power on x86 (userver) if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if x86 (userver) has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off x86 (userver) ungracefully\"\n    echo\n    echo \"  reset: Power reset x86 (userver) ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power cycle the whole chassis ungracefully\"\n    echo\n    echo\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n\n    if userver_power_is_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n    fi\n\n    return 0\n}\n\ndo_on() {\n    local opt\n    local force=0\n\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n\n    if [ $force -eq 0 ]; then\n        if userver_power_is_on; then\n            echo \" uServer is already on. Skipped.\"\n            return 0\n        fi\n    fi\n\n    logger -p user.crit \"Power on x86 (userver) ...\"\n    echo -n \"Power on x86 (userver) ...\"\n    if userver_power_on; then\n        echo \" Done\"\n        return 0\n    fi\n\n    echo \" Failed\"\n    return 1\n}\n\ndo_off() {\n    logger -p user.crit \"Power off x86 (userver) ...\"\n    echo -n \"Power off x86 (userver) ...\"\n\n    if userver_power_off; then\n        echo \" Done\"\n        return 0\n    fi\n\n    echo \" Failed\"\n    return 1\n}\n\ndo_reset() {\n    local opt\n    local system=0\n\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n\n    if [ $system -eq 1 ]; then\n        logger -p user.crit \"Power reset the whole system ...\"\n        echo  \"Power reset the whole system ...\"\n\n        sync\n\n        chassis_power_cycle\n\n        sleep 3\n        # Control should not reach here!!!\n        logger -p user.crit \"Failed to reset the system!!!\"\n        echo \"Failed to reset the system!!!\"\n        exit 1\n    else\n        if userver_power_is_on; then\n            logger -p user.crit \"Power reset x86 (userver) ...\"\n            echo -n \"Power reset x86 (userver) ...\"\n\n            userver_reset\n            echo \" Done\"\n        else\n            echo \"x86 (userver) is off. Power on x86 now..\"\n            do_on\n        fi\n    fi\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nexit $?\n", "num_lines": 178}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nuserver_mac_addr\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:        tcsd trousers\n# Required-Start:    $local_fs $remote_fs $network\n# Required-Stop:    $local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:    2 3 4 5\n# Default-Stop:        0 1 6\n# Short-Description:    starts tcsd\n# Description:        tcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n# shellcheck source=/dev/null\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n    start)\n        echo \"Starting $DESC: \"\n\n        # Generate symlink for tcsd\n        rm -f /dev/tpm\n        if [ -e /dev/tpm0 ]; then\n            ln -s /dev/tpm0 /dev/tpm\n        else\n            ln -s /dev/tpm1 /dev/tpm\n        fi\n\n        start-stop-daemon --start --quiet --oknodo --pidfile /var/run/\"${NAME}\".pid --user \"${USER}\" --chuid \"${USER}\" --exec \"${DAEMON}\" -- \"${DAEMON_OPTS}\"\n        RETVAL=\"$?\"\n        echo \"$NAME.\"\n        [ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n        exit $RETVAL\n        ;;\n\n    stop)\n        echo \"Stopping $DESC: \"\n\n        start-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n        RETVAL=\"$?\"\n                echo  \"$NAME.\"\n        rm -f /var/run/${NAME}.pid\n        exit $RETVAL\n        ;;\n\n    restart|force-reload)\n        \"${0}\" stop\n        sleep 1\n        \"${0}\" start\n        exit $?\n        ;;\n\n    *)\n        echo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n        exit 3\n        ;;\nesac\n\nexit 0\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\nDWR_FILE='/tmp/DWR'\n\n. /usr/local/bin/gpio-utils.sh\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\necho $((sys_runtime+630)) > /tmp/cache_store/fru1_crashdump\n\n# kill previous autodump if exist\nif [ ! -z \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  LOG_FILE='/tmp/autodump.log'\n  LOG_ARCHIVE='/mnt/data/autodump_uncompleted.tar.gz'\n  echo -n \"(uncompleted) Auto Dump End at \" >> $LOG_FILE\n  date >> $LOG_FILE\n\n  tar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\n  rm -rf $LOG_FILE && \\\n\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  killall peci-util &> /dev/null\nfi\nunset OLDPID\n\nDUMP_SCRIPT='/usr/local/bin/dump.sh'\nLOG_FILE='/tmp/autodump.log'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\nLOG_MSG_PREFIX=\"\"\n\nCPU1_SKTOCC_N=\"FM_CPU1_SKTOCC_LVT3_PLD_N\"\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\nSENSOR_HISTORY=180\n\nwhile test $# -gt 0\ndo\n  case \"$1\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  *)\n    echo \"unknown argument $1\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  echo \"Auto Dump after System Reset or Demoted Warm Reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump Started\"\n\n# Start to dump and clear LOG_FILE\necho -n \"Auto Dump Start at \" > $LOG_FILE\ndate >> $LOG_FILE\n\n# CPU0\n$DUMP_SCRIPT 48 coreid >> $LOG_FILE 2>&1\n$DUMP_SCRIPT 48 msr >> $LOG_FILE 2>&1\n\n# CPU1\nif [ \"$(gpio_get_value ${CPU1_SKTOCC_N})\" -eq \"0\" ]; then\n  $DUMP_SCRIPT 49 coreid >> $LOG_FILE 2>&1\n  $DUMP_SCRIPT 49 msr >> $LOG_FILE 2>&1\nelse\n  echo \"<<---------- CPU1 is not present, skip it. ---------->>\" >> $LOG_FILE\nfi\n\n# PCIe\n#$DUMP_SCRIPT pcie >> $LOG_FILE 2>&1\n\n# Sensors\necho \"Sensor history of last ${SENSOR_HISTORY}s at dump:\" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --history $SENSOR_HISTORY >> $LOG_FILE 2>&1\n\necho \"Sensor threshold at dump: \" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --threshold >> $LOG_FILE 2>&1\n\n# only second/dwr autodump need to rename accordingly\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n# dwr\n$DUMP_SCRIPT dwr >> $LOG_FILE 2>&1\n\n# rename the archieve file based on whether dump in DWR mode or not\nif [ \"$?\" == \"2\" ]; then\n  LOG_ARCHIVE='/mnt/data/autodump_dwr.tar.gz'\n  LOG_MSG_PREFIX=\"DWR \"\nelse\n  LOG_ARCHIVE='/mnt/data/autodump_second.tar.gz'\n  LOG_MSG_PREFIX=\"SECOND_DUMP \"\nfi\nfi\n\necho -n \"Auto Dump End at \" >> $LOG_FILE\ndate >> $LOG_FILE\n\ntar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\nrm -rf $LOG_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\nrm -r $DWR_FILE >/dev/null 2>&1\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 134}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROGRAM=$0\nPECI_UTIL=\"/usr/local/bin/peci-util\"\nCMD_DIR=\"/etc/peci\"\n\nfunction print_help_msg {\n  echo \"$PROGRAM 48 coreid  ==> for CPU 1 CoreID\"\n  echo \"$PROGRAM 49 coreid  ==> for CPU 2 CoreID\"\n  echo \"$PROGRAM 48 msr     ==> for CPU 1 MSR\"\n  echo \"$PROGRAM 49 msr     ==> for CPU 2 MSR\"\n  echo \"$PROGRAM pcie       ==> for PCIe\"\n  echo \"$PROGRAM dwr        ==> for DWR check\"\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    $PECI_UTIL -i 10 -r 5 --file /dev/stdin\n}\n\n# read command from stdin\nfunction execute_cmd {\n  # echo \"Use BMC wired PECI interface\"\n  cat | execute_via_peci\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  RESULT=0\n  # BUS\n  RESULT=$((RESULT | (($1 & 0xFF) << 20) ))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15) ))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12) ))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0) ))\n  printf \"0x%x 0x%x 0x%x 0x%x\"\\\n    $(( RESULT & 0xFF )) \\\n    $(( (RESULT >> 8) & 0xFF )) \\\n    $(( (RESULT >> 16) & 0xFF )) \\\n    $(( (RESULT >> 24) & 0xFF ))\n  return 0\n}\n\nfunction pcie_dump {\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    cat $CMD_DIR/crashdump_pcie | execute_cmd\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  # Root port buses\n  ROOT_BUSES=$(echo $RES | awk '{printf \"0x%s 0x%s 0x%s\", $3, $4, $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        echo \"Find Root Port Bus $ROOT Dev $DEV...\"\n        RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr $ROOT $DEV 0x00 0x18)\" | execute_cmd)\n        echo \"$RES\"\n        CC=$(echo $RES| awk '{print $1;}')\n        SECONDARY_BUS=0x$(echo $RES| awk '{print $3;}')\n        SUBORDINATE_BUS=0x$(echo $RES| awk '{print $4;}')\n        if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n          for (( BUS=$SECONDARY_BUS; BUS<=$SUBORDINATE_BUS; BUS++ )); do\n            BUS_MS_NIBBLE=$(printf \"%x\" $((BUS >> 4)) )\n            BUS_LS_NIBBLE=$(printf \"%x\" $((BUS & 0xF)) )\n            [ -r $CMD_DIR/crashdump_pcie_bus ] && \\\n              sed \"s/<BUSM>/$BUS_MS_NIBBLE/g; s/<BUSL>/$BUS_LS_NIBBLE/g\" $CMD_DIR/crashdump_pcie_bus | execute_cmd\n          done\n        fi\n      done\n    done\n  fi\n}\n\nfunction dwr_dump {\n\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  DWR=0x$(echo $RES| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\necho \"\"\n\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"pcie\" ]; then\n\n  pcie_dump\n\n  exit 0\nfi\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"dwr\" ]; then\n\n  dwr_dump\n\n  exit $?\nfi\n\nif [ \"$#\" -ne 2 ]; then\n\n  print_help_msg\n\n  exit 1\n\nelif [ \"$1\" -ne 48 ] && [ \"$1\" -ne 49 ]; then\n\n  print_help_msg\n\n  exit 1\n\nelif [ \"$2\" = \"coreid\" ]; then\n\n  if [ \"$1\" -eq 48 ]; then\n    [ -r $CMD_DIR/crashdump_p0_coreid ] && \\\n      cat $CMD_DIR/crashdump_p0_coreid | execute_cmd\n  elif [ \"$1\" -eq 49 ]; then\n    [ -r $CMD_DIR/crashdump_p1_coreid ] && \\\n      cat $CMD_DIR/crashdump_p1_coreid | execute_cmd\n  fi\n\n  exit 0\n\nelif [ \"$2\" = \"msr\" ]; then\n\n  if [ \"$1\" -eq 48 ]; then\n    [ -r $CMD_DIR/crashdump_p0_msr ] && \\\n      cat $CMD_DIR/crashdump_p0_msr | execute_cmd\n  elif [ \"$1\" -eq 49 ]; then\n    [ -r $CMD_DIR/crashdump_p1_msr ] && \\\n      cat $CMD_DIR/crashdump_p1_msr | execute_cmd\n  fi\n\n  exit 0\n\nfi\n\nexit 0\n", "num_lines": 182}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Front Panel Daemon..\"\n  /usr/local/bin/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho \"Setup fan speed... \"\n/usr/local/bin/fan-util --set 70\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup gpio monitoring for Sonorapass... \"\n\n/usr/local/bin/gpiod &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 5 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-0/new_device  #USB DBG\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-5/new_device  #ME\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_5 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nBUS3_CHAN2_EXTEND_BUSNUM=34\nBUS3_CHAN3_EXTEND_BUSNUM=35\nU11_ADDR=0x60\nU13_ADDR=0x6d\nU95_ADDR=0x6f\n\n# Disable U13 IDT_9QXL2001BNHGI8 - DIF0~3\nU13_byte1=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN2_EXTEND_BUSNUM $U13_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f4)\nU13_byte1_val=${U13_byte1:2:2}\nmod_U13_byte1_val=$[$((16#${U13_byte1_val})) & $((16#F0))]\n# Disable U13 IDT_9QXL2001BNHGI8 - DIF13~15\nU13_byte2=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN2_EXTEND_BUSNUM $U13_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f5)\nU13_byte2_val=${U13_byte2:2:2}\nmod_U13_byte2_val=$[$((16#${U13_byte2_val})) & $((16#1F))]\n\n/usr/bin/i2craw -w \"1 2 $mod_U13_byte1_val $mod_U13_byte2_val\" $BUS3_CHAN2_EXTEND_BUSNUM $U13_ADDR\n\n# Disable U95 IDT_9QXL2001BNHGI8 - DIF16~18\nU95_byte0=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN2_EXTEND_BUSNUM $U95_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f3)\nU95_byte0_val=${U95_byte0:2:2}\nmod_U95_byte0_val=$[$((16#${U95_byte0_val})) & $((16#C7))]\n\n# Disable U95 IDT_9QXL2001BNHGI8 - DIF3~4\nU95_byte1=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN2_EXTEND_BUSNUM $U95_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f4)\nU95_byte1_val=${U95_byte1:2:2}\nmod_U95_byte1_val=$[$((16#${U95_byte1_val})) & $((16#E7))]\n\n# Disable U95 IDT_9QXL2001BNHGI8 - DIF13~15\nU95_byte2=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN2_EXTEND_BUSNUM $U95_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f5)\nU95_byte2_val=${U95_byte2:2:2}\nmod_U95_byte2_val=$[$((16#${U95_byte2_val})) & $((16#1F))]\n\n/usr/bin/i2craw -w \"0 3 $mod_U95_byte0_val $mod_U95_byte1_val $mod_U95_byte2_val\" $BUS3_CHAN2_EXTEND_BUSNUM $U95_ADDR\n\n# Disable U11 IDT_9FGP204BKLFT - RMII0, RMII5, RGMII1 and RGMII0\nU11_byte1=$(/usr/bin/i2craw -w 0 -r 10 $BUS3_CHAN3_EXTEND_BUSNUM $U11_ADDR | sed '$!d' | tr -s ' '| cut -d' ' -f4)\nU11_byte1_val=${U11_byte1:2:2}\nmod_U11_byte1_val=$[$((16#${U11_byte1_val})) & $((16#79))]\n\n/usr/bin/i2craw -w \"1 1 $mod_U11_byte1_val\" $BUS3_CHAN3_EXTEND_BUSNUM $U11_ADDR\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# FM_BOARD_BMC_REV_ID0\ngpio_export FM_BOARD_BMC_REV_ID0 GPIOA0\n\n# FM_BOARD_BMC_REV_ID1 / FM_CPU0_THERMTRIP_LVT3_PLD_N\ngpio_export FM_CPU0_THERMTRIP_LVT3_PLD_N GPIOA1\nln -n /tmp/gpionames/FM_CPU0_THERMTRIP_LVT3_PLD_N /tmp/gpionames/FM_BOARD_BMC_REV_ID1\n\n# FM_SPD_DDRCPU_LVLSHFT_EN\ngpio_export FM_SPD_DDRCPU_LVLSHFT_EN GPIOA3\n\n\n# FM_BOARD_BMC_SKU_ID0 / FM_MEM_THERM_EVENT_CPU0_LVT3_N\ngpio_export FM_MEM_THERM_EVENT_CPU0_LVT3_N GPIOB0\nln -n /tmp/gpionames/FM_MEM_THERM_EVENT_CPU0_LVT3_N /tmp/gpionames/FM_BOARD_BMC_SKU_ID0\n\n# FM_BOARD_BMC_SKU_ID1 / FM_MEM_THERM_EVENT_CPU1_LVT3_N\ngpio_export FM_MEM_THERM_EVENT_CPU1_LVT3_N GPIOB1\nln -n /tmp/gpionames/FM_MEM_THERM_EVENT_CPU1_LVT3_N /tmp/gpionames/FM_BOARD_BMC_SKU_ID1\n\n# FM_BOARD_BMC_SKU_ID2 / FM_CPU0_FIVR_FAULT_LVT3_PLD\ngpio_export FM_CPU0_FIVR_FAULT_LVT3_PLD GPIOB2\nln -n /tmp/gpionames/FM_CPU0_FIVR_FAULT_LVT3_PLD /tmp/gpionames/FM_BOARD_BMC_SKU_ID2\n\n# FM_BOARD_BMC_SKU_ID3 / FM_CPU1_FIVR_FAULT_LVT3_PLD\ngpio_export FM_CPU1_FIVR_FAULT_LVT3_PLD GPIOB3\nln -n /tmp/gpionames/FM_CPU1_FIVR_FAULT_LVT3_PLD /tmp/gpionames/FM_BOARD_BMC_SKU_ID3\n\n# FM_BOARD_BMC_SKU_ID4\ngpio_export FM_BOARD_BMC_SKU_ID4 GPIOB4\n\n# FM_BOARD_BMC_SKU_ID5\ngpio_export FM_BOARD_BMC_SKU_ID5 GPIOB5\n\n# FM_CPU0_PROCHOT_LVT3_BMC_N\ngpio_export FM_CPU0_PROCHOT_LVT3_BMC_N GPIOB6\n\n# FM_CPU1_PROCHOT_LVT3_BMC_N\ngpio_export FM_CPU1_PROCHOT_LVT3_BMC_N GPIOB7\n\n\n# FM_BOARD_BMC_REV_ID2 / FM_CPU1_THERMTRIP_LVT3_PLD_N\ngpio_export FM_CPU1_THERMTRIP_LVT3_PLD_N GPIOD0\nln -n /tmp/gpionames/FM_CPU1_THERMTRIP_LVT3_PLD_N /tmp/gpionames/FM_BOARD_BMC_REV_ID2\n\n# IRQ_TPM_BMC_SPI_N\ngpio_export IRQ_TPM_BMC_SPI_N GPIOD1\n\n# OCP_V3_1_NIC_PWR_GOOD\ngpio_export OCP_V3_1_NIC_PWR_GOOD GPIOD6\n\n# OCP_V3_2_NIC_PWR_GOOD\ngpio_export OCP_V3_2_NIC_PWR_GOOD GPIOD7\n\n\n# FP_BMC_RST_BTN_N\ngpio_export FP_BMC_RST_BTN_N GPIOE0\n\n# RST_BMC_RSTBTN_OUT_R_N, power reset to PCH\ngpio_export RST_BMC_RSTBTN_OUT_R_N GPIOE1\ngpio_set RST_BMC_RSTBTN_OUT_R_N 1\n\n# FM_BMC_PWR_BTN_R_N\ngpio_export FM_BMC_PWR_BTN_R_N GPIOE2\n\n# FM_BMC_PWRBTN_OUT_R_N, power button to CPLD\ngpio_export FM_BMC_PWRBTN_OUT_R_N GPIOE3\ngpio_set FM_BMC_PWRBTN_OUT_R_N 1\n\n# FP_NMI_BTN_N\ngpio_export FP_NMI_BTN_N GPIOE4\n\n# IRQ_BMC_PCH_NMI\ngpio_export IRQ_BMC_PCH_NMI GPIOE5\n\n# FP_FAULT_LED_N\ngpio_export FP_FAULT_LED_N GPIOE6\ngpio_set FP_FAULT_LED_N 1\n\n# ALT_PDB_N\ngpio_export ALT_PDB_N GPIOE7\n\n\n# FM_CPU_ERR0_LVT3_N\ngpio_export FM_CPU_ERR0_LVT3_N GPIOF0\n\n# FM_CPU_ERR1_LVT3_N\ngpio_export FM_CPU_ERR1_LVT3_N GPIOF1\n\n# FM_CPU_ERR2_LVT3_N\ngpio_export FM_CPU_ERR2_LVT3_N GPIOF2\n\n# FM_BMC_DBP_PRESENT_N\ngpio_export FM_BMC_DBP_PRESENT_N GPIOF3\n\n# FM_BMC_UV_ADR_TRIGGER_EN\ngpio_export FM_BMC_UV_ADR_TRIGGER_EN GPIOF4\n\n# FM_BMC_FORCE_ADR_N\ngpio_export FM_BMC_FORCE_ADR_N GPIOF5\n\n# RST_PLTRST_BMC_N\ngpio_export RST_PLTRST_BMC_N GPIOF6\n\n# JTAG_BMC_PRDY_N\ngpio_export JTAG_BMC_PRDY_N GPIOF7\n\n\n# FM_CPU1_DISABLE_COD_N\ngpio_export FM_CPU1_DISABLE_COD_N GPIOG0\n\n# FM_CPU_MSMI_CATERR_LVT3_N\ngpio_export FM_CPU_MSMI_CATERR_LVT3_N GPIOG1\n\n# FM_PCH_BMC_THERMTRIP_N\ngpio_export FM_PCH_BMC_THERMTRIP_N GPIOG2\n\n# BMC_READY_N\ngpio_export BMC_READY_N GPIOG3\ngpio_set BMC_READY_N 1\n# To disable Reset Tolerant\ndevmem_clear_bit 0x1e78003c 19\n\n# IRQ_NMI_EVENT_N\ngpio_export IRQ_NMI_EVENT_N GPIOG4\n\n# IRQ_BMC_PCH_SMI_LPC_N\ngpio_export IRQ_BMC_PCH_SMI_LPC_N GPIOG5\n\n# IRQ_SMB3_M2_ALERT_N\ngpio_export IRQ_SMB3_M2_ALERT_N GPIOG6\n\n# SLIVER_CONNA_BMC_ALERT_N\ngpio_export SLIVER_CONNA_BMC_ALERT_N GPIOG7\n\n\n# LED_POSTCODE_0\ngpio_export LED_POSTCODE_0 GPIOH0\ngpio_set LED_POSTCODE_0 0\n\n# LED_POSTCODE_1\ngpio_export LED_POSTCODE_1 GPIOH1\ngpio_set LED_POSTCODE_1 0\n\n# LED_POSTCODE_2\ngpio_export LED_POSTCODE_2 GPIOH2\ngpio_set LED_POSTCODE_2 0\n\n# LED_POSTCODE_3\ngpio_export LED_POSTCODE_3 GPIOH3\ngpio_set LED_POSTCODE_3 0\n\n# LED_POSTCODE_4\ngpio_export LED_POSTCODE_4 GPIOH4\ngpio_set LED_POSTCODE_4 0\n\n# LED_POSTCODE_5\ngpio_export LED_POSTCODE_5 GPIOH5\ngpio_set LED_POSTCODE_5 0\n\n# LED_POSTCODE_6\ngpio_export LED_POSTCODE_6 GPIOH6\ngpio_set LED_POSTCODE_6 0\n\n# LED_POSTCODE_7\ngpio_export LED_POSTCODE_7 GPIOH7\ngpio_set LED_POSTCODE_7 0\n\ndevmem_set_bit 0x1e780068 24\ndevmem_clear_bit 0x1e78006c 24\n\n\n# PRSNT_2C_PCIE_SLIVER_CABLE_1_N\ngpio_export PRSNT_2C_PCIE_SLIVER_CABLE_1_N GPIOI0\n\n# PRSNT_2C_PCIE_SLIVER_CABLE_2_N\ngpio_export PRSNT_2C_PCIE_SLIVER_CABLE_2_N GPIOI1\n\n# SLIVER_CONNB_BMC_ALERT_N\ngpio_export SLIVER_CONNB_BMC_ALERT_N GPIOI2\n\n# FM_PFR_ACTIVE_N\ngpio_export FM_PFR_ACTIVE_N GPIOI3\n\n\n# FM_UARTSW_LSB_N\ngpio_export FM_UARTSW_LSB_N GPIOL0\n\n# FM_UARTSW_MSB_N\ngpio_export FM_UARTSW_MSB_N GPIOL1\n\n# IRQ_HSC_FAULT_N\ngpio_export IRQ_HSC_FAULT_N GPIOL2\n\n# FM_CPU1_MEMHOT_OUT_N\ngpio_export FM_CPU1_MEMHOT_OUT_N GPIOL3\n\n# FM_MASTER_MB_N\ngpio_export FM_MASTER_MB_N GPIOL4\n\n# BMC_FORCE_NM_THROTTLE_N\ngpio_export BMC_FORCE_NM_THROTTLE_N GPIOL5\n\n\n# IRQ_OC_DETECT_N\ngpio_export IRQ_OC_DETECT_N GPIOM0\n\n# IRQ_UV_DETECT_N\ngpio_export IRQ_UV_DETECT_N GPIOM1\n\n# FM_HSC_TIMER_EXP_N\ngpio_export FM_HSC_TIMER_EXP_N GPIOM2\n\n# P3V3_STBY_MON_ALERT\ngpio_export P3V3_STBY_MON_ALERT GPIOM3\n\n# FM_TPM_BMC_PRES_N\ngpio_export FM_TPM_BMC_PRES_N GPIOM4\n\n# SPI_BMC_BT_WP0_N\ngpio_export SPI_BMC_BT_WP0_N GPIOM5\n\n\n# BOARD_ID_MUX_SEL\ngpio_export BOARD_ID_MUX_SEL GPION2\ngpio_set BOARD_ID_MUX_SEL 0\necho $(($(gpio_get FM_BOARD_BMC_REV_ID2)<<2 |\n        $(gpio_get FM_BOARD_BMC_REV_ID1)<<1 |\n        $(gpio_get FM_BOARD_BMC_REV_ID0))) > /tmp/mb_rev\n\necho $(($(gpio_get FM_BOARD_BMC_SKU_ID5)<<5 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID4)<<4 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID3)<<3 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID2)<<2 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID1)<<1 |\n        $(gpio_get FM_BOARD_BMC_SKU_ID0))) > /tmp/mb_sku\n\ngpio_set BOARD_ID_MUX_SEL 1\n\n# FM_SOL_UART_CH_SEL\ngpio_export FM_SOL_UART_CH_SEL GPION3\n\n# IRQ_DIMM_SAVE_LVT3_N\ngpio_export IRQ_DIMM_SAVE_LVT3_N GPION4\n\n# FM_REMOTE_DEBUG_EN_DET\ngpio_export FM_REMOTE_DEBUG_EN_DET GPION5\n\n# Set debounce timer #1 value to 0x12E1FC ~= 100ms\n$DEVMEM 0x1e780050 32 0x12E1FC\n\n# Select debounce timer #1 for GPION6\ndevmem_clear_bit 0x1e780100 14\ndevmem_set_bit 0x1e780104 14\n\n# FM_POST_CARD_PRES_BMC_N\ngpio_export FM_POST_CARD_PRES_BMC_N GPION6\n\n# FM_PWRBRK_N\ngpio_export FM_PWRBRK_N GPION7\n\n\n# RST_TCA9545_DDR_MUX_N\ngpio_export RST_TCA9545_DDR_MUX_N GPIOQ6\n\n# FM_BMC_CPU_PWR_DEBUG_N\ngpio_export FM_BMC_CPU_PWR_DEBUG_N GPIOQ7\n\n\n# DBP_PRESENT_N\ngpio_export DBP_PRESENT_N GPIOR1\n\n# SMB_BMC_MM5_ALT_N\ngpio_export SMB_BMC_MM5_ALT_N GPIOR2\n\n# SMB_BMC_MM5_RST_N\ngpio_export SMB_BMC_MM5_RST_N GPIOR3\n\n# SMB_SLOT1_ALT_N\ngpio_export SMB_SLOT1_ALT_N GPIOR4\n\n# SMB_SLOT2_ALT_N\ngpio_export SMB_SLOT2_ALT_N GPIOR5\n\n# FM_BIOS_SPI_BMC_CTRL\ngpio_export FM_BIOS_SPI_BMC_CTRL GPIOR6\n\n# FM_SYS_THROTTLE_LVC3\ngpio_export FM_SYS_THROTTLE_LVC3 GPIOR7\n\n\n# FM_BMC_REMOTE_DEBUG_EN\ngpio_export FM_BMC_REMOTE_DEBUG_EN GPIOS0\n\n# DBP_SYSPWROK\ngpio_export DBP_SYSPWROK GPIOS1\n\n# RST_RSMRST_BMC_N\ngpio_export RST_RSMRST_BMC_N GPIOS2\n\n# IRQ_SML0_ALERT_MUX_N\ngpio_export IRQ_SML0_ALERT_MUX_N GPIOS3\n\n# FP_LOCATE_LED, ID LED\ngpio_export FP_LOCATE_LED GPIOS4\ngpio_set FP_LOCATE_LED 0\n\n# FM_MRC_DEBUG_EN\ngpio_export FM_MRC_DEBUG_EN GPIOS5\n\n# FM_2S_FAN_IO_EXP_RST\ngpio_export FM_2S_FAN_IO_EXP_RST GPIOS6\n\n# RST_SMB_OCP_MUX_N\ngpio_export RST_SMB_OCP_MUX_N GPIOS7\n\n\n# FM_FORCE_BMC_UPDATE_N\ngpio_export FM_FORCE_BMC_UPDATE_N GPIOT0\n\n# FP_LOCATE_LED_ACT\ngpio_export FP_LOCATE_LED_ACT GPIOT5\n\n\n# FM_CPU0_MEMHOT_OUT_N\ngpio_export FM_CPU0_MEMHOT_OUT_N GPIOU5\n\n\n# FM_SLPS3_N\ngpio_export FM_SLPS3_N GPIOY0\n\n# FM_SLPS4_N\ngpio_export FM_SLPS4_N GPIOY1\n\n# PWRGD_SYS_PWROK, power GOOD from CPLD\ngpio_export PWRGD_SYS_PWROK GPIOY2\n\n# FM_BMC_ONCTL_N\ngpio_export FM_BMC_ONCTL_N GPIOY3\n\n\n# FM_CPU_CATERR_LVT3_N\ngpio_export FM_CPU_CATERR_LVT3_N GPIOZ0\n\n# PWRGD_CPU0_LVC3\ngpio_export PWRGD_CPU0_LVC3 GPIOZ1\n\n# FM_CPU_MSMI_LVT3_N\ngpio_export FM_CPU_MSMI_LVT3_N GPIOZ2\n\n# FM_BMC_PCH_SCI_LPC_N\ngpio_export FM_BMC_PCH_SCI_LPC_N GPIOZ3\n\n# UV_HIGH_SET\ngpio_export UV_HIGH_SET GPIOZ4\n\n# FM_OC_DETECT_EN_N\ngpio_export FM_OC_DETECT_EN_N GPIOZ5\n\n# FM_SML1_PMBUS_ALERT_EN_N\ngpio_export FM_SML1_PMBUS_ALERT_EN_N GPIOZ6\n\n# FM_BMC_LED_CATERR_N\ngpio_export FM_BMC_LED_CATERR_N GPIOZ7\ngpio_set FM_BMC_LED_CATERR_N 1\n\n\n# P3V_BAT_SCALED_EN\ngpio_export P3V_BAT_SCALED_EN GPIOAA0\ngpio_set P3V_BAT_SCALED_EN 0\n\n# IRQ_SML1_PMBUS_BMC_ALERT_N\ngpio_export IRQ_SML1_PMBUS_BMC_ALERT_N GPIOAA1\n\n# FM_PVCCIN_CPU0_PWR_IN_ALERT_N\ngpio_export FM_PVCCIN_CPU0_PWR_IN_ALERT_N GPIOAA2\n\n# FM_PVCCIN_CPU1_PWR_IN_ALERT_N\ngpio_export FM_PVCCIN_CPU1_PWR_IN_ALERT_N GPIOAA3\n\n# JTAG_DBP_CPU_PREQ_N\ngpio_export JTAG_DBP_CPU_PREQ_N GPIOAA4\n\n# FM_JTAG_TCK_MUX_SEL\ngpio_export FM_JTAG_TCK_MUX_SEL GPIOAA5\n\n# IRQ_SMI_ACTIVE_BMC_N\ngpio_export IRQ_SMI_ACTIVE_BMC_N GPIOAA6\n\n# FM_BIOS_POST_CMPLT_BMC_N\ngpio_export FM_BIOS_POST_CMPLT_BMC_N GPIOAA7\n\n\n# FM_BMC_BMCINIT\ngpio_export FM_BMC_BMCINIT GPIOAB0\n\n# PECI_MUX_SELECT\ngpio_export PECI_MUX_SELECT GPIOAB1\ngpio_set PECI_MUX_SELECT 1\n\n# PWRGD_BMC_PS_PWROK\ngpio_export PWRGD_BMC_PS_PWROK GPIOAB3\n\n# I/O Expander TCA9539 0xEC\ngpio_export_ioexp 4-0076 FM_SLOT1_PRSNT_N 0\ngpio_export_ioexp 4-0076 FM_SLOT2_PRSNT_N 1\ngpio_export_ioexp 4-0076 BMC_PWM_EN 7\ngpio_set BMC_PWM_EN 1\n\n# I/O Expander TCA9539 0xEE\ngpio_export_ioexp 4-0077 IRQ_PVCCIN_CPU0_VRHOT_LVC3_N 0\ngpio_export_ioexp 4-0077 IRQ_PVCCIN_CPU1_VRHOT_LVC3_N 1\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_ABC_CPU0_VRHOT_LVC3_N 2\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_DEF_CPU0_VRHOT_LVC3_N 3\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_ABC_CPU1_VRHOT_LVC3_N 4\ngpio_export_ioexp 4-0077 IRQ_PVDDQ_DEF_CPU1_VRHOT_LVC3_N 5\ngpio_export_ioexp 4-0077 FM_CPU0_SKTOCC_LVT3_PLD_N 6\ngpio_export_ioexp 4-0077 FM_CPU1_SKTOCC_LVT3_PLD_N 7\ngpio_export_ioexp 4-0077 HP_LVC3_OCP_V3_2_PRSNT2_N 8\ngpio_export_ioexp 4-0077 HP_LVC3_OCP_V3_1_PRSNT2_N 9\n\n# I/O Expander PCA9552PW 0xC0\nfor i in {0..3};\ndo\n  gpio_export_ioexp 8-0060 FM_FAN${i}_POWER_LED_N ${i}\n  gpio_export_ioexp 8-0060 FM_FAN${i}_FAULT_LED_N $((i+4))\n  gpio_export_ioexp 8-0060 FM_FAN${i}_BUF_PRESENT_R $((i+8))\n  gpio_export_ioexp 8-0060 FM_FAN${i}_P12V_EN  $((i+12))\ndone\n\n# I/O Expander PCA9552PW 0xC2\nfor i in {4..7};\ndo\n  gpio_export_ioexp 8-0061 FM_FAN${i}_POWER_LED_N $((i-4))\n  gpio_export_ioexp 8-0061 FM_FAN${i}_FAULT_LED_N $((i))\n  gpio_export_ioexp 8-0061 FM_FAN${i}_BUF_PRESENT_R $((i+4))\n  gpio_export_ioexp 8-0061 FM_FAN${i}_P12V_EN $((i+8))\ndone\n\n# Disable JTAG engine\ndevmem 0x1e6e4008 32 0x0\n", "num_lines": 476}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nrev=$(cat /tmp/mb_rev)\nsku=$(cat /tmp/mb_sku)\n\n#REV[1:0]: 01(EVT), 10(DVT)\n#EVT SKU_ID[2:1] = 00(INFINEON), 01(T1)\n#DVT SKU_ID[2:1] = 00(TI), 01(INFINEON), TODO: 10(3rd Source)\nif [ $rev -eq 1 ]; then\n  sku=$((sku & 0x4))\n  if [ $sku -eq 4 ]; then\n    i2c_device_add 1 0x60 tps53688\n    i2c_device_add 1 0x62 tps53688\n    i2c_device_add 1 0x66 tps53688\n    i2c_device_add 1 0x68 tps53688\n    i2c_device_add 1 0x6c tps53688\n    i2c_device_add 1 0x70 tps53688\n    i2c_device_add 1 0x72 tps53688\n    i2c_device_add 1 0x76 tps53688\n  else\n    i2c_device_add 1 0x60 xdpe12284\n    i2c_device_add 1 0x62 xdpe12284\n    i2c_device_add 1 0x66 xdpe12284\n    i2c_device_add 1 0x68 xdpe12284\n    i2c_device_add 1 0x6c xdpe12284\n    i2c_device_add 1 0x70 xdpe12284\n    i2c_device_add 1 0x72 xdpe12284\n    i2c_device_add 1 0x76 xdpe12284\n  fi\nelif [ $rev -eq 2 ]; then\n  sku=$((sku & 0x2))\n  if [ $sku -eq 0 ]; then\n    i2c_device_add 1 0x60 tps53688\n    i2c_device_add 1 0x62 tps53688\n    i2c_device_add 1 0x66 tps53688\n    i2c_device_add 1 0x68 tps53688\n    i2c_device_add 1 0x6c tps53688\n    i2c_device_add 1 0x70 tps53688\n    i2c_device_add 1 0x72 tps53688\n    i2c_device_add 1 0x76 tps53688\n  else\n    i2c_device_add 1 0x60 xdpe12284\n    i2c_device_add 1 0x62 xdpe12284\n    i2c_device_add 1 0x66 xdpe12284\n    i2c_device_add 1 0x68 xdpe12284\n    i2c_device_add 1 0x6c xdpe12284\n    i2c_device_add 1 0x70 xdpe12284\n    i2c_device_add 1 0x72 xdpe12284\n    i2c_device_add 1 0x76 xdpe12284\n  fi\nfi\n\nif [ \"$(gpio_get HP_LVC3_OCP_V3_1_PRSNT2_N)\" == \"0\" ]; then\n  i2c_device_add 17 0x50 24c32\nelse\n  echo \"Unknown or no device on the NIC#0\"\nfi\n\nif [ \"$(gpio_get HP_LVC3_OCP_V3_2_PRSNT2_N)\" == \"0\" ]; then\n  i2c_device_add 18 0x52 24c32\n  ifconfig eth1 up\nelse\n  echo \"Unknown or no device on the NIC#1\"\nfi\n\nif [ \"$(gpio_get FM_SLOT1_PRSNT_N)\" == \"0\" ]; then\n  i2c_device_add 2 0x50 24c32\nelse\n  echo \"Unknown or no device on the RISER_SLOT#1\"\nfi\n\nif [ \"$(gpio_get FM_SLOT2_PRSNT_N)\" == \"0\" ]; then\n  i2c_device_add 6 0x50 24c32\nelse\n  echo \"Unknown or no device on the RISER_SLOT#2\"\nfi\n", "num_lines": 98}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# CHKPT_COMPLETE\nfor i in {1..3}; do\n  /usr/sbin/i2cset -y 4 0x58 0x0f 0x09 b > /dev/null 2>&1\n  if [ $? -eq 0 ]; then\n    break\n  fi\n  sleep 0.5\ndone\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nMAX_RETRY_CNT=5\n\n# Sync BMC's date with the server\nsync_date()\n{\n  # if no ntp peer has been declared the system peer\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    retry=0\n    while [ $retry -lt $MAX_RETRY_CNT ]\n    do\n      # Use standard IPMI command 'get-sel-time' to read RTC time\n      output=$(/usr/local/bin/me-util 0x28 0x48)\n      if [ ${#output} == 12 ]; then\n        ts=$(date -s @$((16#$(echo \"$output\" | awk '{print $4$3$2$1}'))))\n        test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n\n        logger -s -p user.info -t sync_date \"Syncing up BMC time with server...\"\n        logger -s -p user.info -t sync_date \"Date: $ts\"\n        return\n      else\n        retry=$((retry+1))\n        logger -s -p user.info -t sync_date \"Get SEL time from ME failed, syncing up BMC time with server failed for $retry times.\"\n        sleep 1\n      fi\n    done\n  fi\n}\n\nsync_date\n", "num_lines": 51}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util vr --version\" once before sensor monitoring to store vr information\necho \"Get VR FW version... \"\n/usr/bin/fw-util vr --version > /dev/null\n\necho -n \"Setup sensor monitoring for FBSP... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\n#Set PWR_AVR to 128 samples\ni2cset -y -f 7 0x11 0xd4 0x3F1C w\n\n#calibrtion to get HSC to trigger 123A based on EE team input\n# 0xDC3 = 3523 (dec)\n#(3523*10-20475)/ (800*0.15)= 122.958A\ni2cset -y -f 7 0x11 0x4a 0x0DC3 w\n\n#Enable IOUT_OC_WARN_EN1\ni2cset -y -f 7 0x11 0xD5 0x0400 w\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\nDWR_FILE='/tmp/DWR'\n\n. /usr/local/bin/gpio-utils.sh\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\necho $((sys_runtime+630)) > /tmp/cache_store/fru1_crashdump\n \n# kill previous autodump if exist\nif [ ! -z \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n\n  LOG_FILE='/tmp/autodump.log'\n  LOG_ARCHIVE='/mnt/data/autodump_uncompleted.tar.gz'\n  echo -n \"(uncompleted) Auto Dump End at \" >> $LOG_FILE\n  date >> $LOG_FILE\n\n  tar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\n  rm -rf $LOG_FILE && \\\n\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  killall peci-util &> /dev/null\n  killall me-util &> /dev/null\nfi\nunset OLDPID\n\nDUMP_SCRIPT='/usr/local/bin/dump.sh'\nLOG_FILE='/tmp/autodump.log'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\nLOG_MSG_PREFIX=\"\"\n\nCPU1_SKTOCC_N=\"FM_CPU1_SKTOCC_LVT3_N\"\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\nSENSOR_HISTORY=180\n\nwhile test $# -gt 0\ndo\n  case \"$1\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  *)\n    echo \"unknown argument $1\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  echo \"Auto Dump after System Reset or Demoted Warm Reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump Started\"\n\n# Start to dump and clear LOG_FILE\necho -n \"Auto Dump Start at \" > $LOG_FILE\ndate >> $LOG_FILE\n\n# CPU0\n$DUMP_SCRIPT 48 coreid >> $LOG_FILE 2>&1\n$DUMP_SCRIPT 48 msr >> $LOG_FILE 2>&1\n\n# CPU1\nif [ \"$(gpio_get_value ${CPU1_SKTOCC_N})\" -eq \"0\" ]; then\n  $DUMP_SCRIPT 49 coreid >> $LOG_FILE 2>&1\n  $DUMP_SCRIPT 49 msr >> $LOG_FILE 2>&1\nelse\n  echo \"<<---------- CPU1 is not present, skip it. ---------->>\" >> $LOG_FILE\nfi\n\n# PCIe\n$DUMP_SCRIPT pcie >> $LOG_FILE 2>&1\n\n# Sensors\necho \"Sensor history of last ${SENSOR_HISTORY}s at dump:\" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --history $SENSOR_HISTORY >> $LOG_FILE 2>&1\n\necho \"Sensor threshold at dump: \" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --threshold >> $LOG_FILE 2>&1\n\n# only second/dwr autodump need to rename accordingly\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n# dwr\n$DUMP_SCRIPT dwr >> $LOG_FILE 2>&1\n\n# rename the archieve file based on whether dump in DWR mode or not\nif [ \"$?\" == \"2\" ]; then\n  LOG_ARCHIVE='/mnt/data/autodump_dwr.tar.gz'\n  LOG_MSG_PREFIX=\"DWR \"\nelse\n  LOG_ARCHIVE='/mnt/data/autodump_second.tar.gz'\n  LOG_MSG_PREFIX=\"SECOND_DUMP \"\nfi\nfi\n\necho -n \"Auto Dump End at \" >> $LOG_FILE\ndate >> $LOG_FILE\n\ntar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\nrm -rf $LOG_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\nrm -r $DWR_FILE >/dev/null 2>&1\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 136}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROGRAM=$0\nME_UTIL=\"/usr/local/bin/me-util\"\nPECI_UTIL=\"/usr/local/bin/peci-util\"\nCMD_DIR=\"/etc/peci\"\nINTERFACE=\"ME_INTERFACE\"\n\nfunction print_help_msg {\n  echo \"$PROGRAM 48 coreid  ==> for CPU 1 CoreID\"\n  echo \"$PROGRAM 49 coreid  ==> for CPU 2 CoreID\"\n  echo \"$PROGRAM 48 msr     ==> for CPU 1 MSR\"\n  echo \"$PROGRAM 49 msr     ==> for CPU 2 MSR\"\n  echo \"$PROGRAM pcie       ==> for PCIe\"\n  echo \"$PROGRAM dwr        ==> for DWR check\"\n}\n\n# read command from stdin\nfunction execute_via_me {\n  # if ME_UTIL cannot be executed, return\n  [ -x $ME_UTIL ] || \\\n    return\n\n  # Adapt command to ME-UTIL format\n  cat | \\\n    sed 's/^0x/0xb8 0x40 0x57 0x01 0x00 0x/g' $1 | \\\n      $ME_UTIL --file /dev/stdin | \\\n        sed 's/^57 01 00 //g'\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    $PECI_UTIL --file /dev/stdin\n}\n\n# read command from stdin\nfunction execute_cmd {\n  if [ \"$INTERFACE\" == \"PECI_INTERFACE\" ]; then\n    cat | execute_via_peci\n    return\n  fi\n  \n  RES=$($ME_UTIL 0x18 0x01)\n  RET=$?\n  # if ME has response and in operational mode, PECI through ME\n  if [ \"$RET\" -eq \"0\" ] && [ \"${RES:6:1}\" == \"0\" ]; then\n    cat | execute_via_me\n  # else use wired PECI directly\n  else\n  #  echo \"Use BMC wired PECI interface due to ME abnormal\"\n    INTERFACE=\"PECI_INTERFACE\"\n    cat | execute_via_peci\n  fi\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  RESULT=0\n  # BUS\n  RESULT=$((RESULT | (($1 & 0xFF) << 20) ))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15) ))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12) ))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0) ))\n  printf \"0x%x 0x%x 0x%x 0x%x\"\\\n    $(( RESULT & 0xFF )) \\\n    $(( (RESULT >> 8) & 0xFF )) \\\n    $(( (RESULT >> 16) & 0xFF )) \\\n    $(( (RESULT >> 24) & 0xFF ))\n  return 0\n}\n\nfunction pcie_dump {\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    cat $CMD_DIR/crashdump_pcie | execute_cmd\n  \n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  # Root port buses\n  ROOT_BUSES=$(echo $RES | awk '{printf \"0x%s 0x%s 0x%s\", $3, $4, $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        echo \"Find Root Port Bus $ROOT Dev $DEV...\"\n        RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr $ROOT $DEV 0x00 0x18)\" | execute_cmd)\n        echo \"$RES\"\n        CC=$(echo $RES| awk '{print $1;}')\n        SECONDARY_BUS=0x$(echo $RES| awk '{print $3;}')\n        SUBORDINATE_BUS=0x$(echo $RES| awk '{print $4;}')\n        if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n          for (( BUS=$SECONDARY_BUS; BUS<=$SUBORDINATE_BUS; BUS++ )); do\n            BUS_MS_NIBBLE=$(printf \"%x\" $((BUS >> 4)) )\n            BUS_LS_NIBBLE=$(printf \"%x\" $((BUS & 0xF)) )\n            [ -r $CMD_DIR/crashdump_pcie_bus ] && \\\n              sed \"s/<BUSM>/$BUS_MS_NIBBLE/g; s/<BUSL>/$BUS_LS_NIBBLE/g\" $CMD_DIR/crashdump_pcie_bus | execute_cmd\n          done\n        fi\n      done\n    done\n  fi\n}\n\nfunction dwr_dump {\n\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  DWR=0x$(echo $RES| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\necho \"\"\n\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"pcie\" ]; then\n\n  pcie_dump\n  \n  exit 0\nfi\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"dwr\" ]; then\n\n  dwr_dump\n\n  exit $?\nfi\n\nif [ \"$#\" -ne 2 ]; then\n\n  print_help_msg\n\n  exit 1\n\nelif [ \"$1\" -ne 48 ] && [ \"$1\" -ne 49 ]; then\n\n  print_help_msg\n\n  exit 1\n\nelif [ \"$2\" = \"coreid\" ]; then\n\n  if [ \"$1\" -eq 48 ]; then\n    [ -r $CMD_DIR/crashdump_p0_coreid ] && \\\n      cat $CMD_DIR/crashdump_p0_coreid | execute_cmd\n  elif [ \"$1\" -eq 49 ]; then\n    [ -r $CMD_DIR/crashdump_p1_coreid ] && \\\n      cat $CMD_DIR/crashdump_p1_coreid | execute_cmd\n  fi\n\n  exit 0\n\nelif [ \"$2\" = \"msr\" ]; then\n\n  if [ \"$1\" -eq 48 ]; then\n    [ -r $CMD_DIR/crashdump_p0_msr ] && \\\n      cat $CMD_DIR/crashdump_p0_msr | execute_cmd\n  elif [ \"$1\" -eq 49 ]; then\n    [ -r $CMD_DIR/crashdump_p1_msr ] && \\\n      cat $CMD_DIR/crashdump_p1_msr | execute_cmd\n  fi\n\n  exit 0\n\nfi\n\nexit 0\n", "num_lines": 211}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\n  /usr/local/bin/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On FBTP, there are 2 fans connected.\n# Here is the mapping between the fan and PWN/Tacho,\n# Fan 0: PWM 0, Tacho0\n# Fan 1: PWM 1, Tacho2\n\n# For each fan, setting the type, and 100% initially\nfor pwm in 0 1; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0, 2\necho 0 > $PWM_DIR/tacho0_source\necho 1 > $PWM_DIR/tacho0_en\n\necho 1 > $PWM_DIR/tacho2_source\necho 1 > $PWM_DIR/tacho2_en\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for FBTP... \"\n\n/usr/local/bin/gpiod\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\nKERNEL_VERSION=$(uname -r)\nif [[ \"${KERNEL_VERSION}\" != 4.1.* ]]; then\n    i2c_mslave_add 1 0x10\n    i2c_mslave_add 4 0x10\n    i2c_mslave_add 9 0x10\nfi\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_4 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 49}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm > /dev/null 2>&1 &\nrunsv /etc/sv/mTermBMC > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\nKV_STORE=\"/mnt/data/kv_store\"\n\npwr_on_host() {\n  pwr_sts=$(gpio_get PWRGD_SYS_PWROK)\n  if [ \"$pwr_sts\" != \"1\" ]; then\n    gpio_set FM_BMC_PWRBTN_OUT_N 0\n    sleep 1\n    gpio_set FM_BMC_PWRBTN_OUT_N 1\n    sleep 1\n    pwr_sts=$(gpio_get PWRGD_SYS_PWROK)\n    if [ \"$pwr_sts\" == \"1\" ]; then\n      logger \"Successfully power on the server\"\n    fi\n  else\n    logger \"The server was powered on\"\n  fi\n}\n\ncheck_por_config() {\n  #0:Power on reset 1:first power on\n  echo \"$(cat /tmp/ast_por)\"\n}\n\necho -n \"Power on the server...\"\n\n#get por cfg\npor_conf=\"$KV_STORE/server_por_cfg\"\nlps_conf=\"$KV_STORE/pwr_server_last_state\"\nif ! [ -f $por_conf ]; then\n    # power on the server directly\n    # healthd is S91 and power-on.sh is S66 in rc5.d\n    # when the system is first powered on, BMC would power on the server directly\n    logger -s -p user.info -t power-on \"Power Policy can't be found, power on the server directly\"\n    pwr_on_host\nelse\n    # control the system power based on $por_conf\n    por_val=$(cat $por_conf)\n    lps_val=$(cat $lps_conf)\n    logger -s -p user.info -t power-on \"Power Policy: $por_val, Last Power State: $lps_val\"\n    if [ \"$por_val\" == \"on\" ]; then\n      pwr_on_host\n    elif [ \"$por_val\" == \"lps\" ] && [ \"$lps_val\" == \"on\" ]; then\n      pwr_on_host\n    fi\nfi\n\necho \"Done\"\n\necho \"Check if P12V_STBY was turned off before...\"\n\ncheck_log=$($LOGUTIL_CMD all --print | grep -v grep | grep \"Turn off P12V_STBY\" | tail -n 1)\n\nif [ -n \"$check_log\" ]; then\n   logger -s -p user.crit -t power-on \"Turn off P12V_STBY because it was turned off before\"\n   turn_off_p12v_stby\nfi\n\necho \"Done\"\n", "num_lines": 87}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 1 ]; then\n    usage $0\nfi\n\nif [ $1 = \"on\" ]; then\n    val=0\nelif [ $1 = \"off\" ]; then\n    val=1\nelse\n    usage $0\nfi\n\ngpio_set SERVER_POWER_LED $val\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-consoled\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup console history buffering\n### END INIT INFO\n\n# Enable AST SNOOP DMA with default port 80\necho 1 > /sys/devices/platform/ast-snoop-dma.0/enable\n\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Sync BMC's date with the server\nsync_date()\n{\n  # if no ntp peer has been declared the system peer\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    echo Syncing up BMC time with server...\n    # Use standard IPMI command 'get-sel-time' to read RTC time\n    date -s @$((16#$(/usr/local/bin/me-util 0x28 0x48 | awk '{print $4$3$2$1}')))\n  fi\n}\n\nsync_date\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nARGS=\"--json /etc/platform-svcd-config.json\"\nexec /usr/local/bin/platform-svcd $ARGS\n", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          platform-svcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: dbus based platform service\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup platform svcd for FBTP... \"\n\nrunsv /etc/sv/platform-svcd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util mb --version\" once before sensor monitoring to store vr information\necho \"Get MB FW version... \"\n/usr/bin/fw-util mb --version > /dev/null\n\nif [ \"$(gpio_get FM_BOARD_SKU_ID0)\" = \"0\" ]; then\n  ln -s /etc/sensor-correction-sku0-conf.json /etc/sensor-correction-conf.json\nelse\n  new_source=$(/usr/local/bin/fruid-util mb | grep \"KSP2907ATF\")\n  if [ -z \"$new_source\" ];\n  then\n    ln -s /etc/sensor-correction-sku1-conf.json /etc/sensor-correction-conf.json\n  else\n    ln -s /etc/sensor-correction-sku1-diode-conf.json /etc/sensor-correction-conf.json\n  fi\nfi\n\necho -n \"Setup sensor monitoring for FBTP... \"\n\n# Vout is not enabled, set HSC_0xD4 register to 3F1Eh to enable Vout\n/usr/local/bin/me-util mb 0xb8 0xd9 0x57 0x01 0x0 0x88 0x8a 0x0 0x0 0x3 0x0 0xd4 0x1e 0x3f\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 56}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nexec /usr/local/bin/sensor-svcd\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-svcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: dbus based sensor service\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util mb --version\" once before sensor monitoring to store vr information\necho \"Get MB FW version... \"\n/usr/bin/fw-util mb --version > /dev/null\n\necho -n \"Setup sensor svcd for FBTP... \"\n\nrunsv /etc/sv/sensor-svcd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/setup-gpio\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n# channel 0: r1: 2.87K; r2:  2.0K; v2: 0mv\n# channel 1: r1: 5.36K; r2:  2.0K; v2: 0mv\n# channel 2: r1: 15.8K; r2:  2.0K; v2: 0mv\n# channel 3: r1:  1.0K; r2:    NA; v2: 0mv # No voltage divider\n# channel 4: r1:  1.0K; r2:    NA; v2: 0mv # No voltage divider\n# channel 5: r1: 2.87K; r2:  2.0K; v2: 0mv\n# channel 6: r1: 5.36K; r2:  2.0K; v2: 0mv\n# channel 7: r1:  200K; r2:  100K; v2: 0mv\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\nconfig_adc 0  287 200 0\nconfig_adc 1  536 200 0\nconfig_adc 2 1580 200 0\nconfig_adc 3    0   1 0\nconfig_adc 4    0   1 0\nconfig_adc 5  287 200 0\nconfig_adc 6  536 200 0\nconfig_adc 7  400 200 0\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\nif [ $(is_server_prsnt 1) == \"1\" ]; then\n  /usr/local/bin/bic-cached 1 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup_bios_util\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup bios-util config\n### END INIT INFO\n\necho -n \"Setup bios-util config... \"\n\nbios_util_config_path=\"/usr/local/fbpackages/bios-util/bios_support.json\"\nbc_type5_config_path=\"/usr/local/fbpackages/bios-util/BIOS_UTIL_BCT5_v2.json\"\nbc_type7_config_path=\"/usr/local/fbpackages/bios-util/BIOS_UTIL_BCT7_v2.json\"\nIOM_M2=1      # IOM type: M.2\nIOM_IOC=2     # IOM type: IOC\n\nsh /usr/local/bin/check_pal_sku.sh > /dev/NULL\n  PAL_SKU=$(($? & 0x3))\n  if [ \"$PAL_SKU\" == \"$IOM_M2\" ]; then\n    cp ${bc_type5_config_path} ${bios_util_config_path}\n  elif [ \"$PAL_SKU\" == \"$IOM_IOC\" ]; then\n  \tcp ${bc_type7_config_path} ${bios_util_config_path}\n  else\n  \techo \"Setup bios-util: System type is unknown! Please confirm the system type.\"\n  fi\n\necho \"done.\"\n", "num_lines": 49}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nrm -f ../bios-util/*.pyc\nrm -rf ./*.pyc                     \n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-consoled\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup console history buffering\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup console  buffering...\"\n  if [ $(is_server_prsnt 1) == \"1\" ] ; then\n    /usr/local/bin/consoled server --buffer\n  fi\n\necho \"done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-exp-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for SCC Expander info..\"\n#To do... get exp heartbeat\n\nif [ $(is_server_prsnt 1) == \"1\" ]; then\n  /usr/local/bin/exp-cached 1 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nget_sku()\n{\n  # * SCC_RMT_TYPE_0  GPIOF7  47\n  # 1: single server mode (Type 7 Headnode) ; 0: dual server mode (Type5)\n  SCC_RMT=`cat /sys/class/gpio/gpio47/value`\n  get_iom_location\n  SLOTID=$?\n  get_iom_type\n  IOM_TYPE=$?\n\n  if [ $IOM_TYPE -eq 1 ]; then\n    echo \"System: Type5\"\n    if [ $SLOTID -eq 1 ]; then\n      echo \"IOM Location: Side A\"\n    elif [ $SLOTID -eq 2 ]; then\n      echo \"IOM Location: Side B\"\n    else\n      echo \"IOM Location: Unknown\"\n    fi\n  elif [ $IOM_TYPE -eq 2 ]; then\n    echo \"System: Type7\"\n  else\n    echo \"System: Unknown\"\n  fi\n\n  PAL_SKU=$((($SCC_RMT << 6) | ($SLOTID << 4) | $IOM_TYPE))\n\n  return $PAL_SKU\n}\n\nget_iom_location()\n{\n  # * SLOTID_0  GPIOG0  48 Strap pin for IOM location\n  # * SLOTID_1  GPIOG1  49 Strap pin for IOM location\n  # SLOTID_[0:1]: 01=IOM_A; 10=IOM_B\n  SLOTID_0=`cat /sys/class/gpio/gpio48/value`\n  SLOTID_1=`cat /sys/class/gpio/gpio49/value`\n  SLOTID=$((($SLOTID_0 << 1) | $SLOTID_1))\n\n  return $SLOTID\n}\n\nget_iom_type()\n{\n  # * IOM_TYPE0  GPIOJ4  76\n  # * IOM_TYPE1  GPIOJ5  77\n  # * IOM_TYPE2  GPIOJ6  78\n  # * IOM_TYPE3  GPIOJ7  79\n  IOM_TYPE_0=`cat /sys/class/gpio/gpio76/value`\n  IOM_TYPE_1=`cat /sys/class/gpio/gpio77/value`\n  IOM_TYPE_2=`cat /sys/class/gpio/gpio78/value`\n  IOM_TYPE_3=`cat /sys/class/gpio/gpio79/value`\n  IOM_TYPE=$((($IOM_TYPE_0 << 3) | ($IOM_TYPE_1 << 2) | ($IOM_TYPE_2 << 1) | $IOM_TYPE_3))\n\n  return $IOM_TYPE\n}\n\nget_sku\nPAL_SKU=$?\necho -n \"Platform SKU: $PAL_SKU (\"\ni=0\nwhile [ \"${i}\" -lt 8 ]\ndo\n  tmp_sku_bit=$((($PAL_SKU >> i) & 1))\n  sku_bit=$tmp_sku_bit$sku_bit\n  i=$(($i+1))\ndone\n  echo -n $sku_bit\necho \")\"\necho \"<SKU[6:0] = {SCC_RMT_TYPE_0, IOM_SLOTID0, IOM_SLOTID1, IOM_TYPE0, IOM_TYPE1, IOM_TYPE2, IOM_TYPE3}>\"\n\nexit $PAL_SKU\n", "num_lines": 93}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Function to set the less significant hex digit\ndisplay_lower() {  \n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n    \n    # In FBTTN LED is controlled by H0~H7\n    gpio_set LED_POSTCODE_0 $bit0\n    gpio_set LED_POSTCODE_1 $bit1\n    gpio_set LED_POSTCODE_2 $bit2\n    gpio_set LED_POSTCODE_3 $bit3\n}\n\n# Function to set the more significant hex digit\ndisplay_upper() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # In FBTTN LED is controlled by H0~H7\n\n    gpio_set LED_POSTCODE_4 $bit0\n    gpio_set LED_POSTCODE_5 $bit1\n    gpio_set LED_POSTCODE_6 $bit2\n    gpio_set LED_POSTCODE_7 $bit3\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\n# Get upper/lower decimal values\nLOWER_DEC_VALUE=$(expr $DEC_VALUE % 16)\nUPPER_DEC_VALUE=$(expr $DEC_VALUE / 16)\n\n# Display the results\ndisplay_lower $LOWER_DEC_VALUE\ndisplay_upper $UPPER_DEC_VALUE\n\n", "num_lines": 88}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nDEF_PWR_ON=1\nTO_PWR_ON=-1\n\n# Check power policy\n# $1: slot number\ncheck_por_config()\n{\n  TO_PWR_ON=-1\n  slot_num=$1\n\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/slot${slot_num}_por_cfg\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    PWR_POLICY=`cat ${KEYDIR}/slot${slot_num}_por_cfg`\n\n    # Case ON\n    if [ \"$PWR_POLICY\" == \"on\" ]; then\n      TO_PWR_ON=1;\n\n    # Case OFF\n    elif [ \"$PWR_POLICY\" == \"off\" ]; then\n      TO_PWR_ON=0;\n\n    # Case LPS\n    elif [ \"$PWR_POLICY\" == \"lps\" ]; then\n\n      # Check if the file/key doesn't exist\n      if [ ! -f \"${KEYDIR}/pwr_server${slot_num}_last_state\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        LS=`cat ${KEYDIR}/pwr_server${slot_num}_last_state`\n        if [ \"$LS\" == \"on\" ]; then\n          TO_PWR_ON=1;\n        elif [ \"$LS\" == \"off\" ]; then\n          TO_PWR_ON=0;\n        fi\n      fi\n    fi\n    logger -s -p user.info -t power-on \"Power Policy: $PWR_POLICY, Last Power State: $LS\"\n  fi\n}\n\n# Check if BIC is ready or not\ncheck_bic_ready()\n{\n  retry=0\n  while [ \"$retry\" != \"5\" ]\n  do\n    if [ \"$(gpio_get BIC_READY_N)\" == \"0\" ]; then\n      logger -s -p user.warn -t power-on \"BIC is Ready!\"\n      return\n    else\n      logger -s -p user.info -t power-on \"BIC is NOT Ready!!! Retry: $retry\"\n      retry=$((retry+1))\n      sleep 1\n    fi\n  done\n}\n\n# Sync BMC's date with one of the four servers\nsync_date()\n{\n  retry=0\n  if [ \"$(is_server_prsnt)\" == \"1\" ] ; then\n    while [ \"$retry\" != \"5\" ]\n    do\n      # Use standard IPMI command 'get-sel-time' to read RTC time\n      output=$(/usr/local/bin/me-util server 0x28 0x48)\n      # Sync BMC time only when ME returns correct response length\n      if [ \"$(echo $output | wc -c)\" == \"12\" ] ; then\n        col1=$(echo $output | cut -d' ' -f1 | sed 's/^0*//')\n        col2=$(echo $output | cut -d' ' -f2 | sed 's/^0*//')\n        col3=$(echo $output | cut -d' ' -f3 | sed 's/^0*//')\n        col4=$(echo $output | cut -d' ' -f4 | sed 's/^0*//')\n        # create the integer from the hex bytes returned\n        val=$((0x$col4 << 24 | 0x$col3 << 16 | 0x$col2 << 8 | 0x$col1))\n        # create the timestamp required for busybox's date command\n        ts=$(date -d @$val +\"%Y.%m.%d-%H:%M:%S\")\n        # set the command\n        logger -s -p user.info -t power-on \"Syncing up BMC time with server...\"\n        logger -s -p user.info -t power-on \"`date $ts`\"\n        return\n      else\n        retry=$((retry+1))\n        logger -s -p user.info -t power-on \"Get SEL time from ME failed, syncing up BMC time with server failed for $retry times\"\n        sleep 1\n      fi\n    done\n  fi\n}\n\nis_server_12v_off=\"1\"\n\n# Check Mono Lake is  present or not:\n# If Mono Lake absent, turn off Mono Lake HSC 12V and IOM 3V3\nis_server_12v_off=\"1\"\nif [ \"$(is_server_prsnt)\" == \"0\" ]; then\n  logger -s -p user.warn -t power-on \"The Mono Lake is absent, turn off Mono Lake HSC 12V and IOM 3V3.\"\n  gpio_set COMP_PWR_EN 0\n  gpio_set IOM_FULL_PWR_EN 0\n  is_server_12v_off=\"0\"\nfi\n\n# Check whether it is fresh power on reset\nif [ \"$(is_bmc_por)\" == \"1\" ] && [ \"$is_server_12v_off\" == \"1\" ]; then\n  logger -s -p user.warn -t power-on \"BMC POR and Server is Present\"\n  # Disable clearing of PWM block on WDT SoC Reset\n  devmem_clear_bit $(scu_addr 9c) 17\n\n  # For fbttn remote SCC PWR sequence\n  sh /usr/local/bin/check_pal_sku.sh > /dev/NULL\n  PAL_SKU=$(($(($? >> 6)) & 0x1))\n  if [ \"$PAL_SKU\" == \"1\" ]; then  # type 7, always power-on SCC B\n    gpio_set SCC_RMT_FULL_PWR_EN 1\n    gpio_tolerance_fun SCC_RMT_FULL_PWR_EN GPIOF1\n  fi\n\n  # Turn on the IOM_FULL_PWR_EN to power on the M.2 and IOM 3v3 \n  gpio_set IOM_FULL_PWR_EN 1\n  logger -s -p user.warn -t power-on \"Turning on IOM 3v3(IOM_FULL_PWR_EN)\"\n  # For fbttn MonoLake PWR sequence\n  if [ \"$(gpio_get IOM_FULL_PGOOD)\" == \"1\" ]; then\n    logger -s -p user.warn -t power-on \"BMC full power good is enable\"\n    # set ML board power enable (12V on)\n    gpio_set COMP_PWR_EN 1\n    logger -s -p user.warn -t power-on \"Turning Server 12V-on\"\n    sleep 3  # waiting for ME ready\n    check_bic_ready    \n    sync_date\n    check_por_config 1\n    if [ \"$TO_PWR_ON\" == \"1\" ] && [ \"$(is_server_prsnt)\" == \"1\" ] ; then\n        power-util server on\n    fi\n  else\n    logger -s -p user.warn -t power-on \"IOM full power good is disable\"\n  fi\nelse\n  logger -s -p user.warn -t power-on \"BMC Rebooted or Server is not Present\"\n  sync_date\nfi\n", "num_lines": 174}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <slot#> <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 2 ]; then\n    usage $0\nfi\n\n# Slot#1: GPIOA3(3)\nif [ $1 = \"1\" ]; then\n    gpio=\"SYS_PWR_LED\"\nelse\n    usage $0\nfi\n\n\nif [ $2 = \"on\" ]; then\n    val=1\nelif [ $2 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set $gpio $val\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# exported in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# This is a workaround for MAC1LINK\ndevmem 0x1e660050 w 0xA954F\n\n# BMC_TO_EXP_RESET: A2 (2)\n# To use GPIOA2, SCU80[2], and SCU80[15] must be 0\ndevmem_clear_bit $(scu_addr 80) 2\ndevmem_clear_bit $(scu_addr 80) 15\n\ngpio_export BMC_TO_EXP_RESET GPIOA2\n# set GPIOA2 WDT reset tolerance\ngpio_tolerance_fun BMC_TO_EXP_RESET GPIOA2\n\n# SYS_PWR_LED: A3 (3)\n# To use GPIOA3, SCU80[3] must be 0\ndevmem_clear_bit $(scu_addr 80) 3\n\ngpio_export SYS_PWR_LED GPIOA3\ngpio_set SYS_PWR_LED 1\n\n# PWRBTN_OUT_N: D2 (26)\n# To use GPIOD2, SCU90[1], SCU8C[9], and SCU70[21] must be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8C) 9\ndevmem_clear_bit $(scu_addr 70) 21\n\ngpio_export PWRBTN_OUT_N GPIOD2\n\n# COMP_PWR_BTN_N: D3 (27)\n# To use GPIOD3, SCU90[1], SCU8C[9], and SCU70[21] must be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8C) 9\ndevmem_clear_bit $(scu_addr 70) 21\n\ngpio_export COMP_PWR_BTN_N GPIOD3\ngpio_set COMP_PWR_BTN_N 1\n# set GPIOD3 WDT reset tolerance\ngpio_tolerance_fun COMP_PWR_BTN_N GPIOD3\n\n# RSTBTN_OUT_N: D4 (28)\n# To use GPIOD4, SCU90[1], SCU8C[10], and SCU70[21] must be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8C) 10\ndevmem_clear_bit $(scu_addr 70) 21\n\ngpio_export RSTBTN_OUT_N GPIOD4\n\n# SYS_RESET_N_OUT: D5 (29)\n# To use GPIOD5, SCU90[1], SCU8C[10], and SCU70[21] must be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8C) 10\ndevmem_clear_bit $(scu_addr 70) 21\n\ngpio_export SYS_RESET_N_OUT GPIOD5\ngpio_set SYS_RESET_N_OUT 1\n# set GPIOD5 WDT reset tolerance\ngpio_tolerance_fun SYS_RESET_N_OUT GPIOD5\n\n# M2_1_PRESENT_N: E0 (32)\n# To use GPIOE0, SCU80[16], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 16\ndevmem_clear_bit $(scu_addr 8C) 12\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export M2_1_PRESENT_N GPIOE0\n\n# M2_2_PRESENT_N: E1 (33)\n# To use GPIOE1, SCU80[17], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 17\ndevmem_clear_bit $(scu_addr 8C) 12\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export M2_2_PRESENT_N GPIOE1\n\n# M2_1_FAULT_N: E2 (34)\n# To use GPIOE2, SCU80[18], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 18\ndevmem_clear_bit $(scu_addr 8C) 13\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export M2_1_FAULT_N GPIOE2\n\n# M2_2_FAULT_N: E3 (35)\n# To use GPIOE3, SCU80[19], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 19\ndevmem_clear_bit $(scu_addr 8C) 13\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export M2_2_FAULT_N GPIOE3\n\n# BMC_EXT1_LED_B: E4 (36)\n# To use GPIOE4, SCU80[20], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 20\ndevmem_clear_bit $(scu_addr 8C) 14\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export BMC_EXT1_LED_B GPIOE4\ngpio_set BMC_EXT1_LED_B 0\n\n# BMC_EXT1_LED_Y: E5 (37)\n# To use GPIOE5, SCU80[21], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 21\ndevmem_clear_bit $(scu_addr 8C) 14\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export BMC_EXT1_LED_Y GPIOE5\ngpio_set BMC_EXT1_LED_Y 1\n\n# BMC_EXT2_LED_B: E6 (38)\n# To use GPIOE6, SCU80[22], SCU8C[15], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 22\ndevmem_clear_bit $(scu_addr 8C) 15\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export BMC_EXT2_LED_B GPIOE6\ngpio_set BMC_EXT2_LED_B 0\n\n# BMC_EXT2_LED_Y: E7 (39)\n# To use GPIOE7, SCU80[23], SCU8C[15], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 23\ndevmem_clear_bit $(scu_addr 8C) 15\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export BMC_EXT2_LED_Y GPIOE7\ngpio_set BMC_EXT2_LED_Y 1\n\n# Because SCC power sequence is controlled by HW on EVT.\n# So we just configure SCC PWR pins to GPIO and does not export their GPIO node.\n# SCC PWR pins: GPIOF0, GPIOF1, and GPIOF4\n# SCC_LOC_FULL_PWR_EN: F0 (40), PS\n# To use GPIOF0, LHCR[0], SCU90[30], and SCU80[24] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 24\n\n# SCC_RMT_FULL_PWR_EN: F1 (41)\n# To use GPIOF1, LHCR[0], SCU90[30], and SCU80[25] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 25\n\ngpio_export SCC_RMT_FULL_PWR_EN GPIOF1\n\n# EXP_SPARE_0: F2 (42), EXP_SPARE_1: F3 (43)\n# To use GPIOF2, LHCR[0], SCU90[30], and SCU80[26] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 26\n# To use GPIOF3, LHCR[0], SCU90[30], and SCU80[27] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 27\n\ngpio_export EXP_SPARE_0 GPIOF2\ngpio_export EXP_SPARE_1 GPIOF3\n\n\n# SCC_STBY_PWR_EN: F4 (44), PS\n# To use GPIOF4, LHCR[0], SCU90[30], and SCU80[28] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 28\n\n# DPB_MISC_ALERT: F5 (45)\n# To use GPIOF5, LHCR[0], SCU90[30], and SCU80[29] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 29\n\ngpio_export DPB_MISC_ALERT GPIOF5\n\n# P12V_A_PGOOD: F6 (46)\n# To use GPIOF6, LHCR[0], and SCU80[30] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 80) 30\n\ngpio_export P12V_A_PGOOD GPIOF6\n\n# SCC_RMT_TYPE_0: F7 (47)\n# To use GPIOF7, LHCR[0], SCU90[30], and SCU80[31] must be 0\ndevmem_clear_bit $(lpc_addr A0) 0\ndevmem_clear_bit $(scu_addr 90) 30\ndevmem_clear_bit $(scu_addr 80) 31\n\ngpio_export SCC_RMT_TYPE_0 GPIOF7\n\n# SLOTID_0: G0 (48), SLOTID_1: G1 (49)\n# To use GPIOG0, SCU84[0] must be 0\ndevmem_clear_bit $(scu_addr 84) 0\n# To use GPIOG1, SCU84[1] must be 0\ndevmem_clear_bit $(scu_addr 84) 1\n\ngpio_export SLOTID_0 GPIOG0\ngpio_export SLOTID_1 GPIOG1\n\n# COMP_SPARE_0: G2 (50), COMP_SPARE_1: G3 (51))\n# To use GPIOG2, SCU84[2] must be 0\ndevmem_clear_bit $(scu_addr 84) 2\n# To use GPIOG3, SCU84[3] must be 0\ndevmem_clear_bit $(scu_addr 84) 3\n\ngpio_export COMP_SPARE_0 GPIOG2\ngpio_export COMP_SPARE_1 GPIOG3\n\n\n# BIC_READY_N: G7 (55)\n# To use GPIOG7, SCU94[12], and SCU84[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 12\ndevmem_clear_bit $(scu_addr 84) 7\n\ngpio_export BIC_READY_N GPIOG7\n\n# LED_POSTCODE_0: H0 (56)\n# To use GPIOH0, SCU94[5], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 5\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_0 GPIOH0\ngpio_set LED_POSTCODE_0 0\n\n# LED_POSTCODE_1: H1 (57)\n# To use GPIOH1, SCU94[5], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 5\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_1 GPIOH1\ngpio_set LED_POSTCODE_1 0\n\n# LED_POSTCODE_2: H2 (58)\n# To use GPIOH2, SCU94[6], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 6\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_2 GPIOH2\ngpio_set LED_POSTCODE_2 0\n\n# LED_POSTCODE_3: H3 (59)\n# To use GPIOH3, SCU94[6], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 6\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_3 GPIOH3\ngpio_set LED_POSTCODE_3 0\n\n# LED_POSTCODE_4: H4 (60)\n# To use GPIOH4, SCU94[7], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 7\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_4 GPIOH4\ngpio_set LED_POSTCODE_4 0\n\n# LED_POSTCODE_5: H5 (61)\n# To use GPIOH5, SCU94[7], and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 94) 7\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_5 GPIOH5\ngpio_set LED_POSTCODE_5 0\n\n# LED_POSTCODE_6: H6 (62)\n# To use GPIOH6, SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_6 GPIOH6\ngpio_set LED_POSTCODE_6 0\n\n# LED_POSTCODE_7: H7 (63)\n# To use GPIOH7, SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export LED_POSTCODE_7 GPIOH7\ngpio_set LED_POSTCODE_7 0\n\n# BOARD_REV_0: J0 (72), BOARD_REV_1: J1 (73), BOARD_REV_2: J2 (74)\n# To use GPIOJ0, SCU84[8] must be 0\ndevmem_clear_bit $(scu_addr 84) 8\n# To use GPIOJ1, SCU84[9] must be 0\ndevmem_clear_bit $(scu_addr 84) 9\n# To use GPIOJ2, SCU84[10] must be 0\ndevmem_clear_bit $(scu_addr 84) 10\n\ngpio_export BOARD_REV_0 GPIOJ0\ngpio_export BOARD_REV_1 GPIOJ1\ngpio_export BOARD_REV_2 GPIOJ2\n\n\n# PCIE_WAKE_N: J3 (75)\n# To use GPIOJ3, SCU84[11] must be 0\ndevmem_clear_bit $(scu_addr 84) 11\n\ngpio_export PCIE_WAKE_N GPIOJ3\n\n# IOM_TYPE0: J4 (76)\n# To use GPIOJ4, SCU84[12] must be 0\n# To use GPIOJ4, SCU94[8] must be 0\ndevmem_clear_bit $(scu_addr 84) 12\ndevmem_clear_bit $(scu_addr 94) 8\n\ngpio_export IOM_TYPE0 GPIOJ4\n\n# IOM_TYPE1: J5 (77)\n# To use GPIOJ5, SCU84[13] must be 0\n# To use GPIOJ5, SCU94[8] must be 0\ndevmem_clear_bit $(scu_addr 84) 13\ndevmem_clear_bit $(scu_addr 94) 8\n\ngpio_export IOM_TYPE1 GPIOJ5\n\n# IOM_TYPE2: J6 (78)\n# To use GPIOJ6, SCU84[14] must be 0\n# To use GPIOJ6, SCU94[9] must be 0\ndevmem_clear_bit $(scu_addr 84) 14\ndevmem_clear_bit $(scu_addr 94) 9\n\ngpio_export IOM_TYPE2 GPIOJ6\n\n# IOM_TYPE3: J7 (79)\n# To use GPIOJ7, SCU84[15] must be 0\n# To use GPIOJ7, SCU94[9] must be 0\ndevmem_clear_bit $(scu_addr 84) 15\ndevmem_clear_bit $(scu_addr 94) 9\n\ngpio_export IOM_TYPE3 GPIOJ7\n\n# BMC_RMT_HEARTBEAT(TACH): O0 (112)\n# To use GPIOO0, SCU88[8] must be 0\ndevmem_clear_bit $(scu_addr 88) 8\n\ngpio_export BMC_RMT_HEARTBEAT GPIOO0\n\n# BMC_LOC_HEARTBEAT: O1 (113)\n# To use GPIOO1, SCU88[9] must be 0\ndevmem_clear_bit $(scu_addr 88) 9\n\ngpio_export BMC_LOC_HEARTBEAT GPIOO1\ngpio_set BMC_LOC_HEARTBEAT 1\n\n# FLA0_WP_N: O2 (114)\n# To use GPIOO1, SCU88[10] must be 0\ndevmem_clear_bit $(scu_addr 88) 10\n\ngpio_export FLA0_WP_N GPIOO2\n\n# ENCL_FAULT_LED: O3 (115)\n# To use GPIOO1, SCU88[11] must be 0\ndevmem_clear_bit $(scu_addr 88) 11\n\ngpio_export ENCL_FAULT_LED GPIOO3\ngpio_set ENCL_FAULT_LED 0\n\n# SCC_LOC_HEARTBEAT: O4 (116)\n# To use GPIOO4, SCU88[12] must be 0\ndevmem_clear_bit $(scu_addr 88) 12\n\ngpio_export SCC_LOC_HEARTBEAT GPIOO4\n\n# SCC_RMT_HEARTBEAT: O5 (117)\n# To use GPIOO5, SCU88[13] must be 0\ndevmem_clear_bit $(scu_addr 88) 13\n\ngpio_export SCC_RMT_HEARTBEAT GPIOO5\n\n# COMP_POWER_FAIL_N: O6 (118)\n# To use GPIOO6, SCU88[14] must be 0\ndevmem_clear_bit $(scu_addr 88) 14\n\ngpio_export COMP_POWER_FAIL_N GPIOO6\n\n# COMP_PWR_EN: O7 (119), PS\n# To use GPIOO7, SCU88[15] must be 0\ndevmem_clear_bit $(scu_addr 88) 15\n\ngpio_export COMP_PWR_EN GPIOO7\n# set GPIOO7 WDT reset tolerance\ngpio_tolerance_fun COMP_PWR_EN GPIOO7\n\n# Disable GPIOP internal pull down\ndevmem_set_bit $(scu_addr 8C) 31\n\n# DEBUG_GPIO_BMC_6: P0 (120)\n# To use GPIOP0, SCU88[16] must be 0\ndevmem_clear_bit $(scu_addr 88) 16\n\ngpio_export DEBUG_GPIO_BMC_6 GPIOP0\ngpio_set DEBUG_GPIO_BMC_6 1\n# set GPIOP0 WDT reset tolerance\ngpio_tolerance_fun DEBUG_GPIO_BMC_6 GPIOP0\n\n# COMP_FAST_THROTTLE_N: P2 (122)\n# To use GPIOP2, SCU88[18] must be 0\ndevmem_clear_bit $(scu_addr 88) 18\n\n# TODO: Disable the CPU Throttle PIN to fix the leakage issue from BMC to ML\ngpio_export COMP_FAST_THROTTLE_N GPIOP2\n\n# DEBUG_PWR_BTN_N: P3 (123)\n# To use GPIOP3, SCU88[19] must be 0\ndevmem_clear_bit $(scu_addr 88) 19\n\ngpio_export DEBUG_PWR_BTN_N GPIOP3\n\n# DEBUG_GPIO_BMC_2: P4 (124)\n# To use GPIOP4, SCU88[20] must be 0\n# To use GPIOP4, SCU90[28] must be 0\ndevmem_clear_bit $(scu_addr 88) 20\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_export DEBUG_GPIO_BMC_2 GPIOP4\ngpio_set DEBUG_GPIO_BMC_2 1\n# set GPIOP4 WDT reset tolerance\ngpio_tolerance_fun DEBUG_GPIO_BMC_2 GPIOP4\n\n# DEBUG_GPIO_BMC_3: P5 (125)\n# To use GPIOP4, SCU88[20] must be 0\n# To use GPIOP5, SCU88[21] must be 0\ndevmem_clear_bit $(scu_addr 88) 21\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_export DEBUG_GPIO_BMC_3 GPIOP5\n\n# DEBUG_GPIO_BMC_4: P6 (126)\n# To use GPIOP4, SCU88[20] must be 0\n# To use GPIOP6, SCU88[22] must be 0\ndevmem_clear_bit $(scu_addr 88) 22\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_export DEBUG_GPIO_BMC_4 GPIOP6\n\n# DEBUG_GPIO_BMC_5: P7 (127)\n# To use GPIOP4, SCU88[20] must be 0\n# To use GPIOP7, SCU88[23] must be 0\ndevmem_clear_bit $(scu_addr 88) 23\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_export DEBUG_GPIO_BMC_5 GPIOP7\n\n# DB_PRSNT_BMC_N: Q6 (134)\n# To use GPIOQ6, SCU2C[1] must be 0\ndevmem_clear_bit $(scu_addr 2C) 1\n\ngpio_export DB_PRSNT_BMC_N GPIOQ6\n\n# EXP_UART_EN: S0 (144)\n# To use GPIOS0, SCU8C[0] must be 0\ndevmem_clear_bit $(scu_addr 8C) 0\n\ngpio_export EXP_UART_EN GPIOS0\ngpio_set EXP_UART_EN 0\n\n# UART_SEL_IN: S1 (145)\n# To use GPIOS1, SCU8C[1] must be 0\ndevmem_clear_bit $(scu_addr 8C) 1\n\ngpio_export UART_SEL_IN GPIOS1\n\n# BMC_GPIOS4: S4 (148)\n# To use GPIOS4, SCU8C[4] must be 0\ndevmem_clear_bit $(scu_addr 8C) 4\n\ngpio_export BMC_GPIOS4 GPIOS4\n\n# BMC_GPIOS5: S5 (149)\n# To use GPIOS5, SCU8C[5] must be 0\ndevmem_clear_bit $(scu_addr 8C) 5\n\ngpio_export BMC_GPIOS5 GPIOS5\n\n# BMC_GPIOS6: S6 (150)\n# To use GPIOS6, SCU8C[6] must be 0\ndevmem_clear_bit $(scu_addr 8C) 6\n\ngpio_export BMC_GPIOS6 GPIOS6\n\n# BMC_GPIOS7: S7 (151)\n# To use GPIOS7, SCU8C[7] must be 0\ndevmem_clear_bit $(scu_addr 8C) 7\n\ngpio_export BMC_GPIOS7 GPIOS7\n\n# Disable Z0~AB1 Function 3-4\n# To use NOR Function, SCU90[31] must be 0\ndevmem_clear_bit $(scu_addr 90) 31\n\n# DEBUG_RST_BTN_N: Z0 (200)\n# To use GPIOZ0, SCUA4[16], and SCU70[19] must be 0\ndevmem_clear_bit $(scu_addr A4) 16\ndevmem_clear_bit $(scu_addr 70) 19\n\ngpio_export DEBUG_RST_BTN_N GPIOZ0\n\n#Z1 = 1, Z2 = 0 to make IOM LED defualt OFF\n# BMC_ML_PWR_YELLOW_LED: Z1 (201)\n# To use GPIOZ1, SCUA4[17], and SCU70[19] must be 0\ndevmem_clear_bit $(scu_addr A4) 17\ndevmem_clear_bit $(scu_addr 70) 19\n\ngpio_export BMC_ML_PWR_YELLOW_LED GPIOZ1\ngpio_set BMC_ML_PWR_YELLOW_LED 1\n\n# BMC_ML_PWR_BLUE_LED: Z2 (202)\n# To use GPIOZ2, SCUA4[18], and SCU70[19] must be 0\ndevmem_clear_bit $(scu_addr A4) 18\ndevmem_clear_bit $(scu_addr 70) 19\n\ngpio_export BMC_ML_PWR_BLUE_LED GPIOZ2\ngpio_set BMC_ML_PWR_BLUE_LED 0\n\n# PCIE_COMP_TO_IOM_RST_4: Z3 (203)\n# To use GPIOZ3, SCUA4[19] must be 0\ndevmem_clear_bit $(scu_addr A4) 19\n\ngpio_export PCIE_COMP_TO_IOM_RST_4 GPIOZ3\n\n# BMC_GPIOZ4: Z4 (204)\n# To use GPIOZ4, SCUA4[20] must be 0\ndevmem_clear_bit $(scu_addr A4) 20\n\ngpio_export BMC_GPIOZ4 GPIOZ4\n\n# BMC_GPIOZ5: Z5 (205)\n# To use GPIOZ5, SCUA4[21] must be 0\ndevmem_clear_bit $(scu_addr A4) 21\n\ngpio_export BMC_GPIOZ5 GPIOZ5\n\n# BMC_GPIOZ6: Z6 (206)\n# To use GPIOZ6, SCUA4[22] must be 0\ndevmem_clear_bit $(scu_addr A4) 22\n\ngpio_export BMC_GPIOZ6 GPIOZ6\n\n# BMC_GPIOZ7: Z7 (207)\n# To use GPIOZ7, SCUA4[23] must be 0\ndevmem_clear_bit $(scu_addr A4) 23\n\ngpio_export BMC_GPIOZ7 GPIOZ7\n\n# COMP_RST_BTN_N: AA0 (208)\n# To use GPIOAA0, SCUA4[24] must be 0\ndevmem_clear_bit $(scu_addr A4) 24\n\ngpio_export COMP_RST_BTN_N GPIOAA0\ngpio_set COMP_RST_BTN_N 1\n\n# CONN_A_PRSNTA: AA1 (209)\n# To use GPIOAA1, SCUA4[25] must be 0\ndevmem_clear_bit $(scu_addr A4) 25\n\ngpio_export CONN_A_PRSNTA GPIOAA1\n\n# CONN_B_PRSNTB_N: AA2 (210)\n# To use GPIOAA2, SCUA4[26] must be 0\ndevmem_clear_bit $(scu_addr A4) 26\n\ngpio_export CONN_B_PRSNTB_N GPIOAA2\n\n# FM_TPM_PRSNT_N: AA3 (211)\n# To use GPIOAA3, SCUA4[27] must be 0\ndevmem_clear_bit $(scu_addr A4) 27\n\ngpio_export FM_TPM_PRSNT_N GPIOAA3\n\n# BMC_SELF_HW_RST: AA4 (212) For TPM; don't need to implement\n\n# IOM_FULL_PWR_EN: AA7 (215), PS\n# To use GPIOAA7, SCUA4[31] must be 0\ndevmem_clear_bit $(scu_addr A4) 31\n\ngpio_export IOM_FULL_PWR_EN GPIOAA7\n# set GPIOAA7 WDT reset tolerance\ngpio_tolerance_fun IOM_FULL_PWR_EN GPIOAA7\n\n# IOM_LOC_INS_N: AB0 (216)\n# To use GPIOAB0, SCUA8[0] must be 0\ndevmem_clear_bit $(scu_addr A8) 0\n\ngpio_export IOM_LOC_INS_N GPIOAB0\n\n# IOM_FULL_PGOOD: AB1 (217)\n# To use GPIOAB1, SCUA8[1] must be 0\ndevmem_clear_bit $(scu_addr A8) 1\n\ngpio_export IOM_FULL_PGOOD GPIOAB1\n\n# BMC_SELF_HW_RST: AB2 (218)\n# Set GPIOAB2 to funtion2:WDTRST1 , SCUA8[2] must be 1, and SCU94[1:0] must be 0\ndevmem_set_bit $(scu_addr A8) 2\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\n\n# === PCA9555 GPIOs ===\n# ML_INS_N: P00 (472)\npca9555_gpio_export ML_INS_N 0\n# FAN_0_INS_N: P01 (473)\npca9555_gpio_export FAN_0_INS_N 1\n# FAN_1_INS_N: P02 (474)\npca9555_gpio_export FAN_1_INS_N 2\n# FAN_2_INS_N: P03 (475)\npca9555_gpio_export FAN_2_INS_N 3\n# FAN_3_INS_N: P04 (476)\npca9555_gpio_export FAN_3_INS_N 4\n# ANOTHER_IOM_INS_N: P05 (477)\npca9555_gpio_export ANOTHER_IOM_INS_N 5\n# SCC_A_INS: P06 (478)\npca9555_gpio_export SCC_A_INS 6\n# SCC_B_INS: P07 (479)\npca9555_gpio_export SCC_B_INS 7\n\n# SCC_TYPE_0: P10 (480)\npca9555_gpio_export SCC_TYPE_0 8\n# SCC_TYPE_1: P11 (481)\npca9555_gpio_export SCC_TYPE_1 9\n# SCC_TYPE_2: P12 (482)\npca9555_gpio_export SCC_TYPE_2 10\n# SCC_TYPE_3: P13 (483)\npca9555_gpio_export SCC_TYPE_3 11\n# SCC_STBY_PGOOD: P14 (484)\npca9555_gpio_export SCC_STBY_PGOOD 12\n# SCC_FULL_PGOOD: P15 (485)\npca9555_gpio_export SCC_FULL_PGOOD 13\n# ML_PGOOD: P16 (486)\npca9555_gpio_export ML_PGOOD 14\n# DRAWER_CLOSED_N: P17 (487)\npca9555_gpio_export DRAWER_CLOSED_N 15\n", "num_lines": 660}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get platform SKU\nsh /usr/local/bin/check_pal_sku.sh > /dev/NULL\nPAL_SKU=$?\necho $PAL_SKU > /tmp/system.bin\n\n# Record the platform SKU in syslog\nIOM_TYPE=$(($PAL_SKU & 0xF))\nIOM_SLOTID=$(($(($PAL_SKU >> 4)) & 0x3))\n\nif [ $IOM_TYPE -eq 1 ]; then\n    if [ $IOM_SLOTID -eq 1 ]; then\n        IOM_LOCAL=\"side A\"\n    elif [ $IOM_SLOTID -eq 2 ]; then\n        IOM_LOCAL=\"side B\"\n    else\n        IOM_LOCAL=\"unknown\"\n    fi\n    logger -s -p user.info -t setup-platform \"System: type 5, IOM location: $IOM_LOCAL\"\n elif [ $IOM_TYPE -eq 2 ]; then\n    logger -s -p user.info -t setup-platform \"System: type 7\"\n else\n    logger -s -p user.info -t setup-platform \"System: unknown\"\n fi\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Determine BMC Power On Reset flag\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# The T2 chip can prefer different input voltages, depending, presumably\n# of manufacturing variations.  We need to determine whether it wants\n# 0.95V or 1.025V, reset the T2 to reduce total power usage, set the\n# outgoing voltage on the first buck converter, and bring T2 up out of\n# reset.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# read the T2 ROV after the GPIOs are enabled\nt2_rov() {\n    local val0 val1 val2\n    # Note that the values are *not* read in order.\n    val0=$(cat /sys/class/gpio/gpio58/value 2>/dev/null)\n    val1=$(cat /sys/class/gpio/gpio56/value 2>/dev/null)\n    val2=$(cat /sys/class/gpio/gpio57/value 2>/dev/null)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nrov=$(t2_rov)\n\n# target_volts come from the data sheet and 18mV of loss and\n# some fudging based on actual measurements to get either 1.025V\n# or 0.95V at T2\nif [ $rov -eq 1 ]; then\n    target_volts=0x5a\nelif [ $rov -eq 2 ]; then\n    target_volts=0x65\nelse\n    echo \"Unrecognized T2 ROV value $rov, setting failed.\"\n    exit 1\nfi\ntarget_volts=$(( $target_volts * 1 ))  # normalize to decimal\n\n# We shouldn't have to rmmod pmbus, because it hasn't been loaded yet,\n# but if the script is rerun after the system is up, it may be necessary.\nrmmod pmbus\nreload=$?\n\n# Get current voltage value\ncur_volts=$(i2cget -y 1 0x60 0x8b w)\ncur_volts=$(( $cur_volts * 1 ))  # normalize to decimal\n\n# Only bounce the T2 if we actually need to modify the voltage\nif [ $cur_volts -ne $target_volts ]; then \n    # Set values before turning out output;  we're using \"PCIE, then MCS\"\n    echo 1 > /sys/class/gpio/gpio42/value\n    echo 1 > /sys/class/gpio/gpio43/value\n    echo out > /sys/class/gpio/gpio42/direction\n    echo out > /sys/class/gpio/gpio43/direction\n    echo 0 > /sys/class/gpio/gpio16/value\n    echo out > /sys/class/gpio/gpio16/direction\n    # T2 is in reset;  note that this may cause NMI messages on the uServer,\n    # which shouldn't be up anyway when this is first run.\n    \n    # Set the requested value to the current value to avoid rapid shifts\n    i2cset -y 1 0x60 0x21 $cur_volts w\n    # Enable the requested voltage\n    i2cset -y 1 0x60 0xd2 0x5a\n    i2cset -y 1 0x60 0xd3 0x5a\n    sleep 1\n\n    # Set the target voltage\n    i2cset -y 1 0x60 0x21 $target_volts w\n    \n    sleep 1\n\n    # Let T2 come out of reset\n    echo 1 > /sys/class/gpio/gpio16/value\n    echo \"T2 ROV value set based on $rov.\"\n    sleep 2\n    echo 0 > /sys/class/gpio/gpio42/value\n    echo 0 > /sys/class/gpio/gpio43/value\nelse\n    echo \"T2 ROV already correctly set.\"\nfi\n# Bring back pmbus if necessary\nif [ $reload -eq 0 ]; then\n    modprobe pmbus\nfi\n", "num_lines": 100}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#This script is for checking if M.2 supports NVMe, by looking for 0x6a address on i2c bus\n\nsleep 30\n\npower_status=`/usr/local/bin/power-util server status | grep ON`\n\nif [ ! -z \"$power_status\" ]; then\n\tM2_1_i2c_NVMe=`/usr/sbin/i2cdetect -y 7 | grep 6a`\n\tM2_2_i2c_NVMe=`/usr/sbin/i2cdetect -y 8 | grep 6a`\n\n\tif [ ! -z \"$M2_1_i2c_NVMe\" ]; then\n      kv set M2_1_NVMe 1\n\telse\n      kv set M2_1_NVMe 0\n\tfi\n\n\tif [ ! -z \"$M2_2_i2c_NVMe\" ]; then\n      kv set M2_2_NVMe 1\n\telse\n      kv set M2_2_NVMe 0\n\tfi\nfi\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_h) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 800.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/100th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 4 > $PWM_DIR/pwm_type_m_division_l\necho 99 > $PWM_DIR/pwm_type_m_unit\n# Set Type M tacho clock division to 4\necho 0 > $PWM_DIR/tacho_type_m_division\n\n# On FBTTN, there are 4 fans (dual-rotate) connected on DPB.\n# Each fan uses same PWM input.\n# Tacho output is used for BMC or SCC heartbeat.\n# Here is the mapping between the fan and PWN/Tacho,\n# staring from the one from the edge\n# Fan 0: PWM 0\n# Fan 1: PWM 0\n# BMC Remote Heartbeat: PWM 0, Type M, Tacho0\n# SCC Local Heartbeat:  PWM 0, Type M, Tacho4\n# SCC Remote Heartbeat: PWM 0, Type M, Tacho5\n\n# For each fan, setting the type, and 100% initially\n# PWM0, PWM1: Type M\nfor pwm in 0 1; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0, 4, 5\nfor tach in 0 4 5; do\n    echo 0 > $PWM_DIR/tacho${tach}_source\n    echo 1 > $PWM_DIR/tacho${tach}_en\ndone\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fscd config... \"\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\nfsc_type5_config_path=\"/etc/FSC_BC_Type5_MP_v4_config.json\"\nfsc_type7_config_path=\"/etc/FSC_BC_Type7_MP_v4_config.json\"\nIOM_M2=1      # IOM type: M.2\nIOM_IOC=2     # IOM type: IOC\n\nsh /usr/local/bin/check_pal_sku.sh > /dev/NULL\n  PAL_SKU=$(($? & 0x3))\n  if [ \"$PAL_SKU\" == \"$IOM_M2\" ]; then\n    cp ${fsc_type5_config_path} ${default_fsc_config_path}\n  elif [ \"$PAL_SKU\" == \"$IOM_IOC\" ]; then\n  \tcp ${fsc_type7_config_path} ${default_fsc_config_path}\n  else\n  \tcp ${fsc_type5_config_path} ${default_fsc_config_path}\n  \techo \"Setup fscd: System type is unknown, using Type5 Config! Please confirm the system type.\"\n  fi\n\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 55}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#This script is for config checking and setting of fscd monitored sensor \n\n/etc/check_M2_nvme.sh &\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiod server\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for fbttn... \"\n  runsv /etc/sv/gpiod > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 11 11\n\n\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 1\n\n\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 4\n\n\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nif [ $(is_server_prsnt 1) == \"1\" ]; then\n  echo \"enable Mono Lake IPMB on I2C 3\"\n  runsv /etc/sv/ipmbd_3 > /dev/null 2>&1 &\nfi\n\necho \"enable Expander IPMB on I2C 9\"\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n\necho \"enable Debug Card IPMB on I2C 11\"\n  runsv /etc/sv/ipmbd_11 > /dev/null 2>&1 &\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\nSERVER_SDR_DONE_FILE=\"/tmp/sdr_server.done\"\ntimeout_of_waiting_sdr=180  # Maximum wait 3 minutes then go ahead, because get SDR timeout is also 3 minutes.\n\necho -n \"Setup sensor monitoring for fbttn... \"\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  if [ $(is_server_prsnt 1) == \"1\" ] && [ $(is_bic_ready 1) == \"1\" ]; then\n    SLOTS=\"server\"\n  fi\n\nSLOTS=\"iom nic $SLOTS\"\n\nwait_time=0\nlogger -p user.info -t sensord \"waiting for server SDR being ready...\"\nuntil [ $wait_time -eq $timeout_of_waiting_sdr ]\ndo\n  if [ -f $SERVER_SDR_DONE_FILE ]; then\n    logger -p user.info -t sensord \"server SDR is ready.\"\n    rm -rf $SERVER_SDR_DONE_FILE\n    break\n  else\n    sleep 1\n    wait_time=$[$wait_time+1]\n  fi\ndone\nif [ $wait_time -eq $timeout_of_waiting_sdr ]; then\n  logger -p user.warn -t sensord \"server SDR is not ready.\"\nfi\n\nexec /usr/local/bin/sensord $SLOTS\n\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe pmbus\n\n# Enable the ADC inputs;  adc0 - adc11 are connected to various voltage sensors\n\necho 1 > /sys/devices/platform/ast_adc.0/adc0_en\necho 1 > /sys/devices/platform/ast_adc.0/adc1_en\necho 1 > /sys/devices/platform/ast_adc.0/adc2_en\necho 1 > /sys/devices/platform/ast_adc.0/adc3_en\necho 1 > /sys/devices/platform/ast_adc.0/adc4_en\necho 1 > /sys/devices/platform/ast_adc.0/adc5_en\necho 1 > /sys/devices/platform/ast_adc.0/adc6_en\necho 1 > /sys/devices/platform/ast_adc.0/adc7_en\necho 1 > /sys/devices/platform/ast_adc.0/adc8_en\necho 1 > /sys/devices/platform/ast_adc.0/adc9_en\necho 1 > /sys/devices/platform/ast_adc.0/adc10_en\necho 1 > /sys/devices/platform/ast_adc.0/adc11_en\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n# For FBTTN tyep V:\n# channel 0:  r1:  7.87K; r2:  1.0K; v2: 0mv\n# channel 1:  r1:   2.7K; r2:  1.0K; v2: 0mv\n# channel 2:  r1:   1.4K; r2:  1.0K; v2: 0mv\n# channel 3:  r1: 0.330K; r2:  1.0K; v2: 0mv\n# channel 4:  r1: 0.866K; r2:  1.0K; v2: 0mv\n# channel 5:  r1:   0.0K; r2:  1.0K; v2: 0mv\n# channel 6:  r1:   0.0K; r2:  1.0K; v2: 0mv\n# channel 7:  r1:   1.4K; r2:  1.0K; v2: 0mv\n# channel 8:  r1: 0.330K; r2:  1.0K; v2: 0mv\n# channel 9:  r1:   0.0K; r2:  1.0K; v2: 0mv\t# fbttn type VII only\n# channel 10: r1:   0.0K; r2:  1.0K; v2: 0mv\t# fbttn type VII only\n# channel 11: r1:   1.4K; r2:  1.0K; v2: 0mv\t# fbttn type V only\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\n\nconfig_adc 0 7870 1000 0\nconfig_adc 1 2700 1000 0\nconfig_adc 2 1400 1000 0\nconfig_adc 3  330 1000 0\nconfig_adc 4  866 1000 0\nconfig_adc 5    0 1000 0\nconfig_adc 6    0 1000 0\nconfig_adc 7 1400 1000 0\nconfig_adc 8  330 1000 0\n\n# Detect GPIOF7 to recognize IOM type.\nIOM_SKU=`cat /sys/class/gpio/gpio47/value`\nif [ $IOM_SKU == \"0\" ]; then  # fbttn type V only\n  config_adc 11 1400 1000 0\nelse                        # fbttn type VII only\n  config_adc 9     0 1000 0\n  config_adc 10    0 1000 0\nfi\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nDEF_PWR_ON=1\nTO_PWR_ON=\nPOWER_ON_SLOT=\nRETRY=0\n\nDEBUG_ENABLE=false\n\nupdate_ntp_config_from_kv() {\n  local ntp_server\n  ntp_server=$(/usr/bin/kv get ntp_server persistent)\n  if [ -z \"$ntp_server\" ]; then\n    return\n  fi\n\n  sed -i \"s/.*# REPLACE WITH KV.*/server $ntp_server iburst # REPLACE WITH KV/\" /etc/ntp.conf\n  /etc/init.d/ntpd restart\n}\n\nis_ntp_time_synced() {\n  local str\n  local ret\n\n  str=$(/usr/sbin/ntpq -np | grep '^\\*')\n  ret=$?\n\n  if [ \"$DEBUG_ENABLE\" = true ] ; then\n    echo \"==================================\"\n    echo \"ret: $ret\"\n    echo \"----------------------------------\"\n    echo \"$str\"\n    echo \"==================================\"\n  fi\n\n  # ret == 0, synced\n  # ret == 1, not synced\n  return $ret\n}\n\ncheck_por_config()\n{\n  TO_PWR_ON=-1\n  local PWR_ON_RST\n  local LAST_STATE\n\n  PWR_ON_RST=$(/usr/bin/kv get slot${1}_por_cfg persistent)\n\n  if [ -z \"${PWR_ON_RST}\" ]; then       # File not exist\n    TO_PWR_ON=$DEF_PWR_ON\n  elif [ \"$PWR_ON_RST\" == \"on\" ]; then    # Case ON\n    TO_PWR_ON=1;\n  elif [ \"$PWR_ON_RST\" == \"off\" ]; then   # Case OFF\n    TO_PWR_ON=0;\n  elif [ \"$PWR_ON_RST\" == \"lps\" ]; then   # Case LPS\n    LAST_STATE=$(/usr/bin/kv get pwr_server${1}_last_state persistent)\n    if [ -z \"${LAST_STATE}\" ]; then\n      TO_PWR_ON=$DEF_PWR_ON\n    elif [ \"$LAST_STATE\" == \"on\" ]; then\n      TO_PWR_ON=1;\n    elif [ \"$LAST_STATE\" == \"off\" ]; then\n      TO_PWR_ON=0;\n    else\n      echo \"unexpected value in pwr_server${1}_last_state\"\n    fi\n  else\n    echo \"unexpected value in slot${1}_por_cfg\"\n  fi\n}\n\nremove_gp_m2_info() {\n  for i in {2..13};\n  do\n    /usr/bin/kv del sys_config/fru2_m2_${i}_info persistent > /dev/null 2>&1\n    /usr/bin/kv del sys_config/fru4_m2_${i}_info persistent > /dev/null 2>&1\n  done\n}\n\nntp_sync_delay() {\n    local NTP_DELAY_COUNT\n\n    NTP_DELAY_COUNT=0\n    echo \"[$(/bin/date)] ntp is enabled, ntp_server: $(/usr/bin/kv get ntp_server persistent)\"\n    while [ $NTP_DELAY_COUNT -lt 30 ];\n    do\n      if is_ntp_time_synced ; then\n        break\n      fi\n      ((NTP_DELAY_COUNT++))\n      [ \"$DEBUG_ENABLE\" = true ] && echo \"[$(/bin/date)] system time not synced, count: ${NTP_DELAY_COUNT}\"\n      sleep 1\n    done\n    if is_ntp_time_synced ; then\n      echo \"[$(/bin/date)] system time synced after $NTP_DELAY_COUNT sec\"\n    else\n      echo \"[$(/bin/date)] system time not synced after $NTP_DELAY_COUNT sec\"\n    fi\n}\n\n# Check whether it is fresh power on reset\nif [ $(is_bmc_por) -eq 1 ]; then\n  # Remove all GP/GPv2 info\n  remove_gp_m2_info\n\n  # Wait for NTP sync\n  update_ntp_config_from_kv\n  ntp_sync_delay\n\n  # check POR config for each slot\n  for i in $(seq 1 4)\n  do\n    check_por_config ${i}\n    if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt ${i}) == \"1\" ] && [ $(get_slot_type ${i}) == \"0\" ] ; then\n      POWER_ON_SLOT+=(${i})\n      power-util slot${i} on &\n    fi\n  done\n\n  # Wait for all slots to finish power-up.\n  wait\n\nfi\n", "num_lines": 152}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 1) == \"1\" ]] && [[ $(get_slot_type 1) == \"0\" || $(get_slot_type 1) == \"4\" ]]; then\n  /usr/local/bin/bic-cached 1 > /dev/null 2>&1 &\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 2) == \"1\" ]] && [[ $(get_slot_type 2) == \"0\" || $(get_slot_type 2) == \"4\" ]]; then\n  /usr/local/bin/bic-cached 2 > /dev/null 2>&1 &\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 3) == \"1\" ]] && [[ $(get_slot_type 3) == \"0\" || $(get_slot_type 3) == \"4\" ]]; then\n  /usr/local/bin/bic-cached 3 > /dev/null 2>&1 &\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 4) == \"1\" ]] && [[ $(get_slot_type 4) == \"0\" || $(get_slot_type 4) == \"4\" ]]; then\n  /usr/local/bin/bic-cached 4 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup_bios_util\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup bios-util config\n### END INIT INFO\n\necho -n \"Setup bios-util config... \"\n\nbios_util_config_path=\"/usr/local/fbpackages/bios-util/bios_support.json\"\nfby2_bios_config_path=\"/usr/local/fbpackages/bios-util/BIOS_UTIL_FBY2.json\"\n\ncp -rf ${fby2_bios_config_path} ${bios_util_config_path}\n\necho \"done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nME_UTIL=\"/usr/local/bin/me-util\"\nBIC_UTIL=\"/usr/bin/bic-util\"\nFRUID_UTIL=\"/usr/local/bin/fruid-util\"\nFW_UTIL=\"/usr/bin/fw-util\"\nSLOT_NAME=$1\nINTERFACE=\"PECI_INTERFACE\"\n\nfunction is_numeric {\n  if [ $(echo \"$1\" | grep -cE \"^\\-?([[:xdigit:]]+)(\\.[[:xdigit:]]+)?$\") -gt 0 ]; then\n    return 1\n  else\n    return 0\n  fi\n}\n\ncase $SLOT_NAME in\n    slot1)\n      SLOT_NUM=1\n      ;;\n    slot2)\n      SLOT_NUM=2\n      ;;\n    slot3)\n      SLOT_NUM=3\n      ;;\n    slot4)\n      SLOT_NUM=4\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {slot1|slot2|slot3|slot4}\"\n      exit 1\n      ;;\nesac\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump$SLOT_NUM.pid\"\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  echo \"Another auto crashdump for $SLOT_NAME is running\"\n  exit 1\nelse\n  touch $PID_FILE\nfi\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\n/usr/bin/kv set fru${SLOT_NUM}_crashdump $((sys_runtime+1200))\n\nDUMP_SCRIPT=\"/usr/local/bin/dump.sh\"\nCRASHDUMP_FILE=\"/mnt/data/crashdump_$SLOT_NAME\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_$SLOT_NAME.tar.gz\"\nLOG_MSG_PREFIX=\"\"\n\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\n\nwhile test $# -gt 1\ndo\n  case \"$2\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  *)\n    echo \"unknown argument $2\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  echo \"Auto Dump after System Reset or Demoted Warm Reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump for $SLOT_NAME Started\"\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM started\"\n\n#HEADER LINE for the dump\n$DUMP_SCRIPT \"time\" > $CRASHDUMP_FILE\n\n# Get BMC version & hostname\nstrings /dev/mtd0 | grep 2016.07 >> $CRASHDUMP_FILE\nuname -a >> $CRASHDUMP_FILE\ncat /etc/issue >> $CRASHDUMP_FILE\n\n# Get fw info\necho \"Get firmware version info: \" >> \"$CRASHDUMP_FILE\"\nRES=$(\"$FW_UTIL\" \"$SLOT_NAME\" \"--version\")\necho \"$RES\" >> \"$CRASHDUMP_FILE\"\n\n# Get FRUID info\necho \"Get FRUID Info:\" >> $CRASHDUMP_FILE\nRES=$($FRUID_UTIL $SLOT_NAME)\necho \"$RES\" >> $CRASHDUMP_FILE\n\n# Get Device ID\necho \"Get Device ID:\" >> $CRASHDUMP_FILE\nRES=$($ME_UTIL $SLOT_NAME 0x18 0x01)\necho \"$RES\" >> $CRASHDUMP_FILE\n\necho \"Get CPU Microcode Update Revision:\" >> \"$CRASHDUMP_FILE\"\nRES=\"$($BIC_UTIL $SLOT_NAME 0xe0 0x29 0x15 0xa0 0x00 0x30 0x05 0x05 0xa1 0x00 0x00 0x04 0x00)\"\necho \"$RES\" >> \"$CRASHDUMP_FILE\"\nRET=$?\n\nif [ \"$RET\" -eq \"0\" ] && [ \"${RES:0:11}\" == \"15 A0 00 40\" ]; then\n  echo \"Use BIC wired PECI interface\"\n  INTERFACE=\"PECI_INTERFACE\"\nelse\n  echo \"Use PECI through ME interface due to BIC wired PECI abnormal\"\n  INTERFACE=\"ME_INTERFACE\"\nfi\n\n# Major Firmware Revision\nREV=$(echo $RES| awk '{print $3;}')\n# Check whether the first parameter is numeric or not\n# If not, then it is an error message from me-util\nis_numeric $(echo $RES| awk '{print $1;}')\nif [ \"$?\" == 1 ] ;then\n  Mode=$(echo $(($REV & 0x80)))\n  if [ $Mode -ne 0 ] ;then\n    echo \"Device firmware update or Self-initialization in progress or Firmware in the recovery boot-loader mode\" >> $CRASHDUMP_FILE\n  fi\n  # Get Self-test result\n  echo \"Get Self-test result:\" >> $CRASHDUMP_FILE\n  RES=$($ME_UTIL $SLOT_NAME 0x18 0x04)\n  echo \"$RES\" >> $CRASHDUMP_FILE\n  CC=$(echo $RES| awk '{print $1;}')\n  # Check whether the first parameter is numeric or not\n  # If not, then it is an error message from me-util\n  is_numeric $CC\n  if [ \"$?\" == 1 ] ;then\n    if [ $CC -ne 55 ] ;then\n      if [ $CC -eq 56 ] ;then\n        echo \"Self Test function not implemented in this controller\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 57 ] ;then\n        echo \"Corrupted or inaccessible data or devices\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 58 ] ;then\n        echo \"Fatal hardware error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 80 ] ;then\n        echo \"PSU Monitoring service error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 81 ] ;then\n        echo \"Firmware entered Recovery boot-loader mode\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 82 ] ;then\n        echo \"HSC Monitoring service error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 83 ] ;then\n        echo \"Firmware entered non-UMA restricted mode of operation\" >> $CRASHDUMP_FILE\n      else\n        echo \"Unknown error\" >> $CRASHDUMP_FILE\n      fi\n    fi\n  fi\nfi\n\n# Sensors & sensor thresholds\necho \"Sensor history at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"sensors\" >> $CRASHDUMP_FILE\necho \"Sensor threshold at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"threshold\" >> $CRASHDUMP_FILE\n\necho COREID dump\ndate\necho \"Dumping coreid..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"coreid\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping pcu..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"pcu\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping ubox..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"ubox\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping pcie..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"pcie\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping iio..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"iio\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping imc..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"imc\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping mesh..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"mesh\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping upi..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"upi\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping uncore..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"uncore\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping tor..\"\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"tor\" $INTERFACE >> \"$CRASHDUMP_FILE\"\ndate\necho \"Dumping core mca..\"\n#MSR dump (core MCA)\n\"$DUMP_SCRIPT\" \"$SLOT_NAME\" \"msr\" $INTERFACE >> \"$CRASHDUMP_FILE\"\n\n# only second/dwr autodump need to rename accordingly\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  # dwr\n  $DUMP_SCRIPT $SLOT_NAME  \"dwr\" $INTERFACE >> $CRASHDUMP_FILE\n\n  # rename the archieve file based on whether dump in DWR mode or not\n  if [ \"$?\" == \"2\" ]; then\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_dwr_$SLOT_NAME.tar.gz\"\n    LOG_MSG_PREFIX=\"DWR \"\n  else\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_second_$SLOT_NAME.tar.gz\"\n    LOG_MSG_PREFIX=\"SECOND_DUMP \"\n  fi\nfi\n\necho -n \"Auto Dump End at \" >> $CRASHDUMP_FILE\ndate >> $CRASHDUMP_FILE\n\ntar zcf $CRASHDUMP_LOG_ARCHIVE -C `dirname $CRASHDUMP_FILE` `basename $CRASHDUMP_FILE` && \\\nrm -rf $CRASHDUMP_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: $SLOT_NUM is generated at $CRASHDUMP_LOG_ARCHIVE\"\ncp -f \"$CRASHDUMP_LOG_ARCHIVE\" /tmp\necho \"Auto Dump for $SLOT_NAME Completed\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $CRASHDUMP_LOG_ARCHIVE\"\nexit 0\n", "num_lines": 264}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nME_UTIL=\"/usr/local/bin/me-util\"\nPECI_UTIL=\"/usr/bin/bic-util\"\nCMD_DIR=\"/usr/local/fbpackages/crashdump\"\nINTERFACE=$3\nSENSOR_HISTORY=180\nSLOT=$1\n\n# read command from stdin\nfunction execute_via_me {\n  # if ME_UTIL cannot be executed, return\n  [ -x $ME_UTIL ] || \\\n    return\n\n  # Adapt command to ME-UTIL format\n  cat | \\\n    sed 's/^0x/0xb8 0x40 0x57 0x01 0x00 0x/g' $1 | \\\n      \"$ME_UTIL\" \"$SLOT\" --file /dev/stdin | \\\n        sed 's/^57 01 00 //g'\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    sed 's/^0x/0xe0 0x29 0x15 0xa0 0x00 0x/g' $1 | \\\n      \"$PECI_UTIL\" \"$SLOT\" --file /dev/stdin | \\\n        sed 's/^15 A0 00 //g'\n}\n\nfunction execute_cmd {\n  if [ \"$INTERFACE\" == \"ME_INTERFACE\" ]; then\n    cat | execute_via_me \n  else\n    cat | execute_via_peci\n  fi\n}\n\nfunction print_find_core_id {\n  printf \"0x30 0x05 0x09 0xB1 0x00 0x%02x 0x10 0x04\\n\"\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  # BUS\n  RESULT=$((($1 & 0xFF) << 20))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15)))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12)))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0)))\n  printf \"0x%x 0x%x 0x%x 0x%x\" \\\n    $((RESULT & 0xFF)) \\\n    $(((RESULT >> 8) & 0xFF)) \\\n    $(((RESULT >> 16) & 0xFF)) \\\n    $(((RESULT >> 24) & 0xFF))\n  return 0\n}\n\nfunction print_bus_device {\n  MAX_FUN=0\n  MAX_DEV=0\n  BUS=$(printf \"0x%02x\" $1)\n  if [ \"$BUS\" == \"0x17\" ] || [ \"$BUS\" == \"0x65\" ]; then\n    MAX_FUN=1\n  elif [ \"$BUS\" == \"0x18\" ]; then\n    MAX_DEV=7\n  elif [ \"$BUS\" == \"0x66\" ]; then\n    MAX_DEV=3\n  fi\n  BUSM=$(($1 >> 4))\n  BUSL=$((($1 & 0xF) << 4))\n  for (( DEV=0; DEV<=$MAX_DEV; DEV++ )); do\n    DEVM=$((DEV >> 1))\n    DEVL=$(((DEV & 0x1) << 3))\n    for (( FUN=0; FUN<=$MAX_FUN; FUN++ )); do\n      printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x0 ~ 0xFC\\\"\\n\" $1 $DEV $FUN\n      BYTE1=$(((DEVL | FUN) << 4 ))\n      BYTE2=$((BUSL | DEVM))\n      for REG in {0..63..4}; do\n        printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n      done\n      printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x100 ~ 0x147\\\"\\n\" $1 $DEV $FUN\n      BYTE1=$(((DEVL | FUN) << 4 | 0x1))\n      BYTE2=$((BUSL | DEVM))\n      for REG in {0..68..4}; do\n        printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n      done\n      if [ \"$BUS\" == \"0x18\" ] || [ \"$BUS\" == \"0x66\" ]; then\n        printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x1B0 ~ 0x1BB\\\"\\n\" $1 $DEV $FUN\n        for REG in {176..184..4}; do\n          printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n        done\n      fi\n    done\n  done\n}\n\nfunction find_end_device {\n  echo \"Find Root Port Bus $1 Dev $2 Fun $3...\"\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr $1 $2 $3 0x18)\" | execute_cmd)\n  echo \"$RES\"\n  CC=$(echo $RES| awk '{print $1;}')\n  SECONDARY_BUS=0x$(echo $RES| awk '{print $3;}')\n  SUBORDINATE_BUS=0x$(echo $RES| awk '{print $4;}')\n  if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n    for (( BUS=$SECONDARY_BUS; BUS<=$SUBORDINATE_BUS; BUS++ )); do\n      printf \"End Device on Bus 0x%02x\\n\" $BUS\n      echo \"$(print_bus_device $BUS)\" | execute_cmd\n    done\n  fi\n}\n\nfunction pcie_dump {\n\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie_pch ] && \\\n    cat $CMD_DIR/crashdump_pcie_pch | execute_cmd\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    # CPU root port - Bus 0x16/0x64, Dev 0~3, Fun:0\n    # Root port buses\n    ROOT_BUSES=$(echo $RES | awk '{printf \"0x%s 0x%s\", $3, $4;}')\n    ROOT_BUS=$(echo $RES | awk '{printf \"0x%s\", $2;}')\n    echo ROOT_BUSES=$ROOT_BUSES\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        find_end_device $ROOT $DEV 0\n      done\n    done\n\n    # CPU root port - Bus 0,Dev 0, Fun:0\n    echo ROOT_BUS=$ROOT_BUS\n    find_end_device $ROOT_BUS 0 0\n\n    # PCH root port - Bus 0,Dev 0x1B, Fun:0\n    find_end_device $ROOT_BUS 0x1B 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:0\n    find_end_device $ROOT_BUS 0x1D 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:4\n    find_end_device $ROOT_BUS 0x1D 4\n  fi\n}\n\nfunction uncore_mca_dump {\n  echo\n  echo find uncore MCA dump core id\n  echo =============================\n  echo\n  for (( CORE_ID=0; CORE_ID<=35; CORE_ID++ )); do\n    RES=$(echo \"$(print_find_core_id $CORE_ID)\" | execute_cmd)\n    echo CORE ID = $CORE_ID\n    echo $RES\n    # Completion Code\n    CC=$(echo $RES| awk '{print $1;}')\n    # Success Get CORED ID\n    if [ \"$CC\" == \"40\" ]; then\n      [ -r $CMD_DIR/crashdump_uncore ] && \\\n      cat $CMD_DIR/crashdump_uncore | execute_cmd\n      return $CORE_ID\n    else\n      printf \"CORE_ID 0x%02x CC 0x%s\\n\" $CORE_ID $CC\n      if [ \"$CORE_ID\" == \"35\" ]; then\n        # No CORED ID (Processor ID at EDS file) is valid\n        echo\n        echo  Fail to dump uncore MCA since no Processor ID is found\n        echo\n      fi\n    fi\n  done\n}\n\nfunction tor_dump {\n  echo\n  echo TOR dump:\n  echo =================\n  echo\n  echo \"0x30 0x0a 0x01 0xa5 0x00 0x80 0x03 0x00 0x02 0x00 0x03 0x00\" | execute_cmd\n  echo \"0x30 0x0a 0x01 0xa5 0x00 0x80 0x01 0x00 0x00 0x00 0x00 0x80\" | execute_cmd\n  echo \"0x30 0x0a 0x01 0xa5 0x00 0x80 0x01 0x30 0x00 0x00 0x00 0x00\" | execute_cmd\n  # get number of read value N\n  RES=$(echo \"0x30 0x05 0x05 0xa1 0x00 0x80 0x02 0x00\" | execute_cmd)\n  echo $RES\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  MAX_NUM=2015 # for tesing (2020-5= 2015)\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    echo \"start TOR dump\"\n    for (( NUM=0; NUM<$MAX_NUM; NUM++ )); do\n      echo \"0x30 0x0a 0x01 0xa5 0x00 0x80 0x01 0x30 0x00 0x00 0x00 0x00\" | execute_cmd\n    done\n  else\n    echo \"get TOR dump number fail\"\n  fi\n  echo \"0x30 0x0a 0x01 0xa5 0x00 0x80 0x04 0x00 0x02 0x00 0x03 0x00\" | execute_cmd\n}\n\nfunction dwr_dump {\n\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  DWR=0x$(echo $RES| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nfunction print_dump_help {\n  echo \"$0 <slot#> coreid <INTERFACE>   ==> for CPU CoreID\"\n  echo \"$0 <slot#> msr    <INTERFACE>   ==> for Core MCA\"\n  echo \"$0 <slot#> pcu    <INTERFACE>   ==> for PCU\"\n  echo \"$0 <slot#> ubox   <INTERFACE>   ==> for UBOX\"\n  echo \"$0 <slot#> iio    <INTERFACE>   ==> for IIO\"\n  echo \"$0 <slot#> imc    <INTERFACE>   ==> for IMC, MC, Mmap\"\n  echo \"$0 <slot#> mesh   <INTERFACE>   ==> for Mesh\"\n  echo \"$0 <slot#> upi    <INTERFACE>   ==> for UPI\"\n  echo \"$0 <slot#> uncore <INTERFACE>   ==> for Uncore MCA\"\n  echo \"$0 <slot#> sensors              ==> for sensor history\"\n  echo \"$0 <slot#> threshold            ==> for sensor threshold\"\n  echo \"$0 <slot#> pcie   <INTERFACE>   ==> for PCIe\"\n  echo \"$0 <slot#> tor    <INTERFACE>   ==> for TOR dump\"\n  echo \"$0 <slot#> dwr    <INTERFACE>   ==> for DWR check\"\n  exit 1\n}\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -eq 2 ]; then\n  if [ \"$2\" != \"sensors\" ] && [ \"$2\" != \"threshold\" ]; then\n    print_dump_help\n  fi\nelif [ \"$#\" -eq 3 ]; then\n  if [ \"$INTERFACE\" != \"ME_INTERFACE\" ] && [ \"$INTERFACE\" != \"PECI_INTERFACE\" ]; then\n    print_dump_help\n  fi\nelse\n  print_dump_help\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r $CMD_DIR/crashdump_coreid ] && \\\n      cat $CMD_DIR/crashdump_coreid | execute_cmd\nelif [ \"$2\" = \"msr\" ]; then # core MCA\n  [ -r $CMD_DIR/crashdump_msr ] && \\\n      cat $CMD_DIR/crashdump_msr | execute_cmd\nelif [ \"$2\" = \"pcu\" ]; then\n  [ -r $CMD_DIR/crashdump_pcu ] && \\\n      cat $CMD_DIR/crashdump_pcu | execute_cmd\nelif [ \"$2\" = \"ubox\" ]; then\n  [ -r $CMD_DIR/crashdump_ubox ] && \\\n      cat $CMD_DIR/crashdump_ubox | execute_cmd\nelif [ \"$2\" = \"iio\" ]; then\n  [ -r $CMD_DIR/crashdump_iio ] && \\\n      cat $CMD_DIR/crashdump_iio | execute_cmd\nelif [ \"$2\" = \"imc\" ]; then\n  [ -r $CMD_DIR/crashdump_imc ] && \\\n      cat $CMD_DIR/crashdump_imc | execute_cmd\nelif [ \"$2\" = \"mesh\" ]; then\n  [ -r $CMD_DIR/crashdump_mesh ] && \\\n      cat $CMD_DIR/crashdump_mesh | execute_cmd\nelif [ \"$2\" = \"upi\" ]; then\n  [ -r $CMD_DIR/crashdump_upi ] && \\\n      cat $CMD_DIR/crashdump_upi | execute_cmd\nelif [ \"$2\" = \"uncore\" ]; then\n  uncore_mca_dump\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util $1 --history $SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util spb --history $SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util nic --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util $1 --threshold \\\n   && /usr/local/bin/sensor-util spb --threshold \\\n   && /usr/local/bin/sensor-util nic --threshold\nelif [ \"$2\" = \"pcie\" ]; then\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    cat $CMD_DIR/crashdump_pcie | execute_cmd\n    pcie_dump\nelif [ \"$2\" = \"tor\" ]; then\n  tor_dump\nelif [ \"$2\" = \"dwr\" ]; then\n  dwr_dump\n  exit $?\nelse\n  print_dump_help\nfi\n\nexit 0\n", "num_lines": 333}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\nfan_check_delay=5\nspb_type=$(get_spb_type)\nkernel_ver=$(get_kernel_ver)\n\n\nif [ $kernel_ver == 5 ]; then\n    set_fan1='echo 180 > /sys/devices/platform/ahb/ahb:apb/1e786000.pwm-tacho-controller/hwmon/hwmon*/pwm1'\n    set_fan2='echo 180 > /sys/devices/platform/ahb/ahb:apb/1e786000.pwm-tacho-controller/hwmon/hwmon*/pwm2'\n    eval $set_fan1\n    eval $set_fan2\n    sleep $fan_check_delay\n    if [ $spb_type == 1 ] ; then\n        # for Yv2.50\n        fan0_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan3_input`\n        fan1_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan4_input`\n    else\n        fan0_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan1_input`\n        fan1_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan2_input`\n    fi\n    #restore the initial value 100% (init_pwm.sh)\n    reset_fan1='echo 255 > /sys/devices/platform/ahb/ahb:apb/1e786000.pwm-tacho-controller/hwmon/hwmon*/pwm1'\n    reset_fan2='echo 255 > /sys/devices/platform/ahb/ahb:apb/1e786000.pwm-tacho-controller/hwmon/hwmon*/pwm2'\n    eval $reset_fan1\n    eval $reset_fan2\nelse\n    echo 70 > /sys/devices/platform/ast_pwm_tacho.0/pwm0_falling\n    echo 70 > /sys/devices/platform/ast_pwm_tacho.0/pwm1_falling\n    sleep $fan_check_delay\n    if [ $spb_type == 1 ] ; then\n        # for Yv2.50\n        fan0_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho2_rpm`\n        fan1_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho3_rpm`\n    else\n        fan0_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho0_rpm`\n        fan1_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho1_rpm`\n    fi\n    #restore the initial value 100% (init_pwm.sh)\n    echo 0 > /sys/devices/platform/ast_pwm_tacho.0/pwm0_falling\n    echo 0 > /sys/devices/platform/ast_pwm_tacho.0/pwm1_falling\nfi\n\n# default 10K_FAN\nfan_config=0\n\nif [ $fan0_rpm -ge \"8000\" ] || [ $fan1_rpm -ge \"8000\" ]; then\n    # 15K_FAN\n    fan_config=1\nfi\n\necho \"$fan_config\" > /tmp/fan_config\n\n# add SEL log for Northdome if 10K fan detected\nif [ \"$spb_type\" -eq \"3\" ] && [ \"$fan_config\" -eq \"0\" ]; then\n    logger -p user.crit \"10K Fan detected\"\nfi\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\nsv stop fscd\n\nFSCD_END_REASON=$1\n\nSLOT_TYPE_GPV2=4\nhas_gpv2=0\n\npwm_value=100\n\nspb_type=$(get_spb_type)\nkernel_ver=$(get_kernel_ver)\nif [ $kernel_ver == 5 ]; then\n    if [ $spb_type == 1 ] ; then\n        # for Yv2.50\n        fan0_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan3_input`\n        fan1_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan4_input`\n    else\n        fan0_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan1_input`\n        fan1_rpm=`cat /sys/bus/platform/drivers/aspeed_pwm_tacho/1e786000.pwm-tacho-controller/hwmon/hwmon*/fan2_input`\n    fi\nelse\n    if [ $spb_type == 1 ] ; then\n        # for Yv2.50\n        fan0_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho2_rpm`\n        fan1_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho3_rpm`\n    else\n        fan0_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho0_rpm`\n        fan1_rpm=`cat /sys/devices/platform/ast_pwm_tacho.0/tacho1_rpm`\n    fi\nfi\n\nif [ $fan0_rpm -le \"500\" ] || [ $fan1_rpm -le \"500\" ]; then\n    # for fan fail condition\n    pwm_value=100\nelse\n    sku_type=0\n    server_type=0\n    for i in `seq 1 1 4`\n    do\n        tmp_sku=$(get_slot_type $i)\n        if [ \"$tmp_sku\" == \"$SLOT_TYPE_GPV2\" ] ; then\n            has_gpv2=1\n        fi\n        sku_type=$(($(($tmp_sku << $(($(($i*4)) - 4))))+$sku_type))\n        tmp_server=$(get_server_type $i)\n        server_type=$(($(($tmp_server << $(($(($i*4)) - 4))))+$server_type))\n    done\n    if [ \"$has_gpv2\" == \"1\" ] ; then\n        # only for GPv2 case\n        pwm_value=90\n    elif [ \"$sku_type\" == \"0\" ] && [ \"$server_type\" == \"17476\" ] ; then\n        # onle for FBND case\n        pwm_value=95\n    else\n        pwm_value=100\n    fi\nfi\n\nif [ \"$FSCD_END_REASON\" == \"$FSCD_END_INVALID_CONFIG\" ] ; then\n    logger -p user.warning \"Invalid fan config, fscd stopped, set fan speed to $pwm_value%\"\nelse\n    logger -p user.warning \"SLED not seated, fscd stopped, set fan speed to $pwm_value%\"\nfi\n/usr/local/bin/fan-util --set $pwm_value\n", "num_lines": 69}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\nkernel_ver=$(get_kernel_ver)\nif [ $kernel_ver == 4 ]; then\n    # The PWM frequency is\n    \n    #   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n    #\n    # Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n    # a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n    #\n    # We also want the unit to be as large as possible, since this controls the\n    # granularity with which we can modulate the PWM signal.  The following\n    # settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n    #\n    # The AST chip supports 3 different PWM clock configurations, but we only use\n    # type M for now.\n    echo 0 > $PWM_DIR/pwm_type_m_division_h\n    echo 5 > $PWM_DIR/pwm_type_m_division_l\n    echo 95 > $PWM_DIR/pwm_type_m_unit\n    \n    # On fby2, there are 2 fans connected.\n    # Each fan uses same PWM input and provide one tacho output.\n    # Here is the mapping between the fan and PWN/Tacho,\n    # staring from the one from the edge\n    # Fan 0: PWM 0, Tacho0\n    # Fan 1: PWM 0, Tacho1\n    #\n    # On fby2.50, there are 4 fan connected.\n    # Fan 0: PWM 0, Tacho0\n    # Fan 1: PWM 0, Tacho2\n    # Fan 2: PWM 0, Tacho1\n    # Fan 3: PWM 0, Tacho3\n    \n    fan_num=0\nfi\n\nspb_type=$(get_spb_type)\nfan_type=$(get_fan_type)\n\nif [[ $spb_type == \"1\" && $fan_type == \"0\" ]]; then\n    # 0 base\n    fan_num=3\n    echo \"FAN CONFIG : Dual Rotor FAN\"\nelse\n    # 0 base\n    fan_num=1\n    echo \"FAN CONFIG : Single Rotor FAN\"\nfi\n\nif [ $kernel_ver == 4 ]; then\n    # For each fan, setting the type, and 100% initially\n    for pwm in 0 1; do\n        echo 0 > $PWM_DIR/pwm${pwm}_type\n        echo 0 > $PWM_DIR/pwm${pwm}_rising\n        echo 0 > $PWM_DIR/pwm${pwm}_falling\n        echo 1 > $PWM_DIR/pwm${pwm}_en\n    done\n    \n    # Enable Tach\n    if [[ $spb_type == \"1\" && $fan_type == \"1\" ]]; then\n        echo 0 > $PWM_DIR/tacho2_source\n        echo 0 > $PWM_DIR/tacho3_source\n        echo 1 > $PWM_DIR/tacho2_en\n        echo 1 > $PWM_DIR/tacho3_en\n    else \n        for tach in 0 $fan_num; do\n            echo 0 > $PWM_DIR/tacho${tach}_source\n        done\n        t=0\n        while [ $t -le $fan_num ]; do\n            echo 1 > $PWM_DIR/tacho${t}_en\n            t=$((t+1))\n        done\n    fi\nfi\n", "num_lines": 98}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\ndefault_aggregate_config_path=\"/etc/aggregate-sensor-conf.json\"\nsku_type=0\nserver_type=0\nfull_config=1\ndev_type=0\n\nDEV_TYPE_UNKNOWN=0\nDEV_TYPE_SSD=1\nDEV_TYPE_VSI_ACC=2\nDEV_TYPE_BRCM_ACC=3\nDEV_TYPE_OTHER_ACC=4\nDEV_TYPE_DUAL_M2=5\n\nFAN_CONFIG_10K=0\nFAN_CONFIG_15K=1\n\nSLOT_TYPE_GPV2=4\nhas_gpv2=0\ninvalid_gpv2_config=0\nfan_config=0\n\nfunction init_fsc_config_default()\n{\n  for i in `seq 1 1 4`\n  do\n    tmp_sku=$(get_slot_type $i)\n    if [ \"$tmp_sku\" == \"$SLOT_TYPE_GPV2\" ] ; then\n      has_gpv2=1\n    fi\n    sku_type=$(($(($tmp_sku << $(($(($i*4)) - 4))))+$sku_type))\n    tmp_server=$(get_server_type $i)\n    server_type=$(($(($tmp_server << $(($(($i*4)) - 4))))+$server_type))\n  done\n\n  case \"$sku_type\" in\n    \"0\") # 4S\n      case \"$server_type\" in\n        \"0\")\n          echo \"Run FSC 4 TLs Config\"\n          cp /etc/FSC_FBY2_MP_4TL_config.json ${default_fsc_config_path}\n        ;;\n        \"17476\")\n          echo \"Run FSC 4 NDs Config\"\n          cp /etc/FSC_NORTHDOME_4ND_config.json ${default_fsc_config_path}\n          if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n              cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n          fi\n        ;;\n        *)\n          echo \"Unexpected 4 Servers config! Run FSC 4 TLs Config as default config\"\n          cp /etc/FSC_FBY2_MP_4TL_config.json ${default_fsc_config_path}\n        ;;\n      esac\n    ;;\n    \"514\") # 2S + 2GP\n      if [[ $(get_server_type 2) == \"0\" && $(get_server_type 4) == \"0\" ]] ; then\n        echo \"Run FSC 2 GPs and 2 TLs Config\"\n        cp /etc/FSC_FBY2_PVT_2GP_2TL_config.json ${default_fsc_config_path}\n      elif [[ $(get_server_type 2) == \"4\" && $(get_server_type 4) == \"4\" ]] ; then\n        echo \"Run FSC 4 NDs Config\"\n        cp /etc/FSC_NORTHDOME_4ND_config.json ${default_fsc_config_path}\n        if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n          cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n        fi\n      else\n        echo \"Unexpected 2 GPs and 2 Servers config! Run FSC 2 GPs and 2 TLs Config as default config\"\n        cp /etc/FSC_FBY2_PVT_2GP_2TL_config.json ${default_fsc_config_path}\n      fi\n    ;;\n    \"257\") # 2S + 2CF\n      if [[ $(get_server_type 2) == \"0\" && $(get_server_type 4) == \"0\" ]] ; then\n        echo \"Run FSC 2 CFs and 2 TLs Config\"\n        cp /etc/FSC_FBY2_PVT_2CF_2TL_config.json ${default_fsc_config_path}\n      elif [[ $(get_server_type 2) == \"4\" && $(get_server_type 4) == \"4\" ]] ; then\n        echo \"Run FSC 4 NDs Config\"\n        cp /etc/FSC_NORTHDOME_4ND_config.json ${default_fsc_config_path}\n        if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n          cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n        fi\n      else\n        echo \"Unexpected 2 CFs and 2 Servers config! Run FSC 2 CFs and 2 TLs Config as default config\"\n        cp /etc/FSC_FBY2_PVT_2CF_2TL_config.json ${default_fsc_config_path}\n      fi\n    ;;\n    \"1028\") # 2GPv2 +2TL\n      echo \"Run FSC 2 GPV2s and 2 TLs Config\"\n    ;;\n    *)\n      if [ \"$has_gpv2\" == \"1\" ] ; then\n        invalid_gpv2_config=1\n        echo \"Unexpected GPv2 sku type!\"\n      else\n        server_type_tmp=\"3\"\n        for i in 1 2 3 4 ; do\n          server_type_tmp=$(get_server_type $i)\n          if [ \"$server_type_tmp\" != \"3\" ] ; then\n            break;\n          fi\n        done\n\n        if [ \"$server_type_tmp\" == \"4\" ] ; then\n          echo \"Unexpected sku type! Use FSC 4 NDs Config as default config\"\n          cp /etc/FSC_NORTHDOME_4ND_config.json ${default_fsc_config_path}\n          if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n            cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n          fi\n        else\n          echo \"Unexpected sku type! Use FSC 4 TLs Config as default config\"\n          cp /etc/FSC_FBY2_MP_4TL_config.json ${default_fsc_config_path}\n        fi\n      fi\n    ;;\n  esac\n\n  if [ \"$has_gpv2\" == \"1\" ] ; then\n    if [ \"$dev_type\" == \"$DEV_TYPE_UNKNOWN\" ] ; then\n      fw_ver=$(/usr/bin/fw-util bmc --version fscd)\n      if [[ $fw_ver =~ \"fbgpv2\" ]] ; then\n        echo \"Keep FSC config : $fw_ver\"\n        logger -p user.info \"Keep FSC config : $fw_ver\"\n      else\n        echo \"Run default FSC for M.2 devices\"\n        logger -p user.info \"Run default FSC for M.2 devices\"\n        if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n          cp /etc/FSC_FBGPV2_DVT_config.json ${default_fsc_config_path}\n        else\n          cp /etc/FSC_FBGPV2_10KFAN_DVT_config.json ${default_fsc_config_path}\n        fi\n      fi\n    elif [ \"$dev_type\" == \"$DEV_TYPE_SSD\" ] ; then\n      echo \"Run FSC for SSD\"\n      logger -p user.info \"Run FSC for SSD\"\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/FSC_FBGPV2_DVT_config.json ${default_fsc_config_path}\n      else\n        cp /etc/FSC_FBGPV2_10KFAN_DVT_config.json ${default_fsc_config_path}\n      fi\n    elif [ \"$dev_type\" == \"$DEV_TYPE_VSI_ACC\" ] ; then\n      echo \"Run FSC for VSI Accelerator\"\n      logger -p user.info \"Run FSC for VSI Accelerator\"\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/FSC_FBGPV2_VSI_DVT_config.json ${default_fsc_config_path}\n      else\n        cp /etc/FSC_FBGPV2_VSI_10KFAN_DVT_config.json ${default_fsc_config_path}\n      fi\n    elif [ \"$dev_type\" == \"$DEV_TYPE_BRCM_ACC\" ] ; then\n      echo \"Run FSC for BRCM Accelerator\"\n      logger -p user.info \"Run FSC for BRCM Accelerator\"\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/FSC_FBGPV2_BRCM_PVT_config.json ${default_fsc_config_path}\n      else\n        cp /etc/FSC_FBGPV2_BRCM_10KFAN_PVT_config.json ${default_fsc_config_path}\n      fi\n    else\n      echo \"Run default FSC for M.2 devices\"\n      logger -p user.info \"Run default FSC for M.2 devices\"\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/FSC_FBGPV2_DVT_config.json ${default_fsc_config_path}\n      else\n        cp /etc/FSC_FBGPV2_10KFAN_DVT_config.json ${default_fsc_config_path}\n      fi\n    fi\n    if [ $spb_type == 1 ] ; then\n      # for Yv2.50\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/aggregate-sensor-yv250-15kfan-conf.json ${default_aggregate_config_path}\n        cp /etc/FSC_FBYV250_15KFAN_DVT_config.json ${default_fsc_config_path}\n      else\n        cp /etc/aggregate-sensor-yv250-10kfan-conf.json ${default_aggregate_config_path}\n        cp /etc/FSC_FBYV250_10KFAN_DVT_config.json ${default_fsc_config_path}\n      fi\n    else\n      if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n        cp /etc/aggregate-sensor-gpv2-conf.json ${default_aggregate_config_path}\n      else\n        cp /etc/aggregate-sensor-gpv2-10kfan-conf.json ${default_aggregate_config_path}\n      fi\n    fi\n  fi\n}\n\nfunction init_fsc_config_yv2nd2()\n{\n  cp /etc/FSC_NORTHDOME_4ND_config.json ${default_fsc_config_path}\n  cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n  if [ \"$fan_config\" == \"$FAN_CONFIG_15K\" ] ; then\n    cp /etc/aggregate-sensor-fbnd-conf.json ${default_aggregate_config_path}\n  fi\n}\n\nfunction get_fan_config()\n{\n  if ! kv get setup_fan_config ; then\n    logger -p user.warning \"Setup fan config\"\n    /usr/local/bin/check_fan_config.sh\n    kv set setup_fan_config 1\n  fi\n\n  fan_config=$(cat /tmp/fan_config)\n}\n\nif [ $# -eq 1 ] ; then\n  dev_type=$1\nfi\n\necho \"Setup fan speed... \"\n\nspb_type=$(get_spb_type)\n\nif [ $spb_type == 1 ] ; then\n  for i in `seq 1 1 4`\n  do\n     if [ $(is_server_prsnt $i) == \"0\" ]; then\n       echo \"slot$i is empty\"\n       full_config=0\n     fi\n  done\n\n  if [ $full_config -eq 0 ]; then\n     echo \"System is missing a slot - Unexpected sku type (system is not full config)!\"\n     /usr/local/bin/init_pwm.sh\n     /usr/local/bin/fan-util --set 90\n     exit 1\n  fi\nfi\n\n/usr/local/bin/init_pwm.sh\nget_fan_config\n\nif [ $spb_type == 3 ]; then\n  init_fsc_config_yv2nd2    # YV2ND2\nelse\n  init_fsc_config_default   # original method\nfi\n\n/usr/local/bin/fan-util --set 70\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\nlogger -p user.info \"fscd started\"\n\n# Check SLED in/out\nif [ $(gpio_get FAN_LATCH_DETECT H5) = 1 ]; then\n   /usr/local/bin/fscd_end.sh $FSCD_END_SLED_OUT\nelif [ \"$invalid_gpv2_config\" == \"1\" ] ; then\n   /usr/local/bin/fscd_end.sh $FSCD_END_INVALID_CONFIG\nelse\n   sv restart fscd\nfi\n\necho \"done.\"\n", "num_lines": 282}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  #Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n  #get_slot_type is to get slot type to check if the slot type is server\n  if [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) == \"0\" ]]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n  #Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n  #get_slot_type is to get slot type to check if the slot type is server\n  if [[ $(is_server_prsnt 2) == \"1\" && $(get_slot_type 2) == \"0\" ]]; then\n    SLOTS=\"$SLOTS slot2\"\n  fi\n  #Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n  #get_slot_type is to get slot type to check if the slot type is server\n  if [[ $(is_server_prsnt 3) == \"1\" && $(get_slot_type 3) == \"0\" ]]; then\n    SLOTS=\"$SLOTS slot3\"\n  fi\n  #Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n  #get_slot_type is to get slot type to check if the slot type is server\n  if [[ $(is_server_prsnt 4) == \"1\" && $(get_slot_type 4) == \"0\" ]]; then\n    SLOTS=\"$SLOTS slot4\"\n  fi\n\nexec /usr/local/bin/gpiod $SLOTS \n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for fby2... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio interrupt monitoring for FBY2... \"\n\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 13 5\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 2\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 5 3\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 7 4\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\nSPB_FRU_FILE=\"/tmp/fruid_spb.bin\"\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nkernel_ver=$(get_kernel_ver)\nif [ $kernel_ver == 5 ]; then\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-1/new_device\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-3/new_device\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-5/new_device\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-7/new_device\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-13/new_device\nfi\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_5 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_7 > /dev/null 2>&1 &\n\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) != \"0\" && $(get_slot_type 1) != \"4\" ]]; then\n  sv stop ipmbd_1\nelif [ $(is_server_prsnt 1) == \"0\" ]; then\n  sv stop ipmbd_1\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 2) == \"1\" && $(get_slot_type 2) != \"0\" && $(get_slot_type 2) != \"4\" ]]; then\n  sv stop ipmbd_3\nelif [ $(is_server_prsnt 2) == \"0\" ]; then\n  sv stop ipmbd_3\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 3) == \"1\" && $(get_slot_type 3) != \"0\" && $(get_slot_type 3) != \"4\" ]]; then\n  sv stop ipmbd_5\nelif [ $(is_server_prsnt 3) == \"0\" ]; then\n  sv stop ipmbd_5\nfi\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 4) == \"1\" && $(get_slot_type 4) != \"0\" && $(get_slot_type 4) != \"4\" ]]; then\n  sv stop ipmbd_7\nelif [ $(is_server_prsnt 4) == \"0\" ]; then\n  sv stop ipmbd_7\nfi\n\nrunsv /etc/sv/ipmbd_13 > /dev/null 2>&1 &\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm2 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm3 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm4 > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          enable-aen\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# enables OEM AENs if Broadcom NIC\nq=$(fw-util nic --version | grep -i broadcom)\nif [ -z \"$q\" ]\nthen\n      # non Broadcom\n      echo \"Enable standard AENs:(Link Status, Config Req, Driver Status)\" >> /dev/kmsg\n      /usr/local/bin/ncsi-util 8 0 0 0 0 0 0 0 7\nelse\n      # Broadcom\n      echo \"Enable standard & Broadcom OEM AENs \" >> /dev/kmsg\n      /usr/local/bin/ncsi-util 8 0 0 0 0 0 7 0 7\nfi\n\necho \"done.\"\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\ngpio_set MEZZ_PRSNTID_A_SEL_N F4 1\ngpio_set MEZZ_PRSNTID_B_SEL_N F5 1\n\nif [[ $(gpio_get MEZZ_PRSNTA2_N L0) == \"0\" && $(gpio_get MEZZ_PRSNTB2_N L1) == \"1\" ]]; then\n  val=0\n  for i in {1..3}; do\n    val=$(i2cget -y -f 12 0x20 0 b)\n    val=$((val & 0x07))  # NIC_AUX_POWER_EN=1,NIC_MAIN_POWER_EN=1,NIC_PWRGOOD=1\n    [ $val -eq 7 ] && break\n    usleep 100000\n  done\n\n  if [ $val -ne 7 ]; then\n    i2cset -y -f 12 0x20 6 0xffff w\n    i2cset -y -f 12 0x20 2 0xffff w\n    usleep 200000\n    i2cset -y -f 12 0x20 6 0xfe b  # NIC_AUX_POWER_EN=1\n    for i in {1..10}; do  # wait for NIC_PWRGOOD=1\n      val=$(i2cget -y -f 12 0x20 0 b)\n      val=$((val & 0x05))\n      [ $val -eq 5 ] && break\n      usleep 100000\n    done\n    i2cset -y -f 12 0x20 6 0xfc b  # NIC_MAIN_POWER_EN=1\n    sleep 1\n  fi\nfi\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nif [ \"$#\" -eq 1 ]; then\n  case $1 in\n    slot1)\n      SLOT=(1)\n      ;;\n    slot2)\n      SLOT=(2)\n      ;;\n    slot3)\n      SLOT=(3)\n      ;;\n    slot4)\n      SLOT=(4)\n      ;;\n    *)\n      exit 1\n      ;;\n  esac\nelse\n  SLOT=(1 2 3 4)\nfi\n\nTL_PRODUCT_ID0=39\nTL_PRODUCT_ID1=30\nND_PRODUCT_ID0=44\nND_PRODUCT_ID1=4E\n\nmax_retry=3\n\nfor (( i=0; i<${#SLOT[@]}; i++ )); do\n  slot_id=${SLOT[$i]}\n  slot_12v=$(is_slot_12v_on $slot_id)\n  if [ $(is_server_prsnt $slot_id) != \"1\" ]; then\n    server_type=3\n  elif [[ \"$slot_12v\" == \"1\" && $(get_slot_type $slot_id) == \"0\" ]]; then\n    j=0\n    while [ ${j} -lt ${max_retry} ]; do\n      # Use standard IPMI command 'get-device-id' to read product id of server board\n      output=$(/usr/bin/bic-util slot$slot_id 0x18 0x01)\n      # if the command fails and the number of retry times reach max retry, continue to next slot\n      if [ $(echo $output | wc -c) == 45 ]; then\n        product_id_l=`echo \"$output\" | cut -c 28-29`\n        product_id_h=`echo \"$output\" | cut -c 31-32`\n        if [[ \"$product_id_l\" == \"$TL_PRODUCT_ID0\" && \"$product_id_h\" == \"$TL_PRODUCT_ID1\" ]]; then\n          #TL\n          server_type=0\n        elif [[ \"$product_id_l\" == \"$ND_PRODUCT_ID0\" && \"$product_id_h\" == \"$ND_PRODUCT_ID1\" ]]; then\n          #ND\n          server_type=4\n          RES=$(/usr/bin/bic-util slot$slot_id 0xE0 0x2A 0x15 0xA0 0x00 0x01)\n          postcode=$(echo $RES| awk '{print $7$6$5$4;}')\n          # Since server may not power on, skip if post code empty\n          if [ -n \"$postcode\" ]; then\n            /usr/bin/kv set \"slot${slot_id}_last_postcode\" \"$postcode\" 2> /dev/null\n          fi\n        else\n          #unknown\n          server_type=3\n        fi\n        break\n      fi\n      sleep 1\n      j=$(($j+1))\n    done\n  elif [[ \"$slot_12v\" == \"1\" || ! -f \"/tmp/server_type$slot_id.bin\" ]]; then\n    server_type=3\n  else\n    continue\n  fi\n\n  echo \"Slot$slot_id Server Type: $server_type\"\n  echo $server_type > /tmp/server_type$slot_id.bin\ndone\n", "num_lines": 96}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nkernel_ver=$(get_kernel_ver)\n\nif [ \"$#\" -eq 1 ]; then\n  case $1 in\n    slot1)\n      SLOT=(1)\n      VOL_EN=(O4)\n      VOL_EN_NAME=(P12V_STBY_SLOT1_EN)\n      if [ $kernel_ver == 5 ]; then\n        ADC_VALUE=(in13_input)\n      else\n        ADC_VALUE=(adc12_value)\n      fi\n      ;;\n    slot2)\n      SLOT=(2)\n      VOL_EN=(O5)\n      VOL_EN_NAME=(P12V_STBY_SLOT2_EN)\n      if [ $kernel_ver == 5 ]; then\n        ADC_VALUE=(in14_input)\n      else\n        ADC_VALUE=(adc13_value)\n      fi\n      ;;\n    slot3)\n      SLOT=(3)\n      VOL_EN=(O6)\n      VOL_EN_NAME=(P12V_STBY_SLOT3_EN)\n      if [ $kernel_ver == 5 ]; then\n        ADC_VALUE=(in15_input)\n      else\n        ADC_VALUE=(adc14_value)\n      fi\n      ;;\n    slot4)\n      SLOT=(4)\n      VOL_EN=(O7)\n      VOL_EN_NAME=(P12V_STBY_SLOT4_EN)\n      if [ $kernel_ver == 5 ]; then\n        ADC_VALUE=(in16_input)\n      else\n        ADC_VALUE=(adc15_value)\n      fi\n      ;;\n    *)\n      exit 1\n      ;;\n  esac\nelse\n  SLOT=(1 2 3 4)\n  VOL_EN=(O4 O5 O6 O7)\n  VOL_EN_NAME=(P12V_STBY_SLOT1_EN P12V_STBY_SLOT2_EN P12V_STBY_SLOT3_EN P12V_STBY_SLOT4_EN)\n  if [ $kernel_ver == 5 ]; then\n      ADC_VALUE=(in13_input in14_input in15_input in16_input)\n  else\n      ADC_VALUE=(adc12_value adc13_value adc14_value adc15_value)\n  fi\nfi\n\n\nsku=0\nfor (( i=0; i<${#SLOT[@]}; i++ )); do\n  slot_id=${SLOT[$i]}\n  if [ $(is_server_prsnt $slot_id) != \"1\" ]; then\n    sku=3\n  elif [ $(gpio_get ${VOL_EN_NAME[$i]} ${VOL_EN[$i]}) == \"1\" ]; then\n    if [ $kernel_ver == 5 ]; then\n      slot_vol=`cat /sys/devices/platform/iio-hwmon/hwmon/hwmon*/\"${ADC_VALUE[$i]}\" | cut -d \\  -f 1 | awk '{printf (\"%.3f\\n\",$1/1000)}'`\n    else\n      slot_vol=`cat /sys/devices/platform/ast_adc.0/\"${ADC_VALUE[$i]}\" | cut -d \\  -f 1 | awk '{printf (\"%.3f\\n\",$1)}'`\n    fi\n    \n    if [[ `awk -v a=1.9 -v b=$slot_vol 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 &&  `awk -v a=$slot_vol -v b=1.5 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 ]]; then\n      sku=2\n      y=$(($slot_id*2-1))\n      i2cset -y $y 0x40 0x5 0xa w\n    elif [[ `awk -v a=1.4 -v b=$slot_vol 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 && `awk -v a=$slot_vol -v b=1.0 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 ]]; then\n      sku=1\n      y=$(($slot_id*2-1))\n      i2cset -y $y 0x70 0x5 c\n      usleep 10000\n      i2cset -y $y 0x40 0x5 0xa w\n    elif [[ `awk -v a=0.95 -v b=$slot_vol 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 && `awk -v a=$slot_vol -v b=0.55 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 ]]; then\n      sku=4\n    else\n      sku=0\n    fi\n  elif [ ! -f \"/tmp/slot$slot_id.bin\" ]; then\n    sku=3\n  else\n    continue\n  fi\n\n  echo \"Slot$slot_id Type: $sku\"\n  echo $sku > /tmp/slot$slot_id.bin\ndone\n", "num_lines": 119}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nmac=$(weutil  | grep '^Local MAC'  | cut -d' ' -f3 )\n\nif [ -n \"$mac\" ]; then\n    ifconfig eth0 hw ether $mac\n    # compare the 'ethaddr' from u-boot env\n    ethaddr=$(fw_printenv ethaddr  | cut -d'=' -f2 )\n    if [ \"$ethaddr\" != \"$mac\" ]; then\n        fw_setenv \"ethaddr\" \"$mac\"\n    fi\nfi\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nLPS_PATH=/mnt/data/power/por/last_state\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <slot#> <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current 1S server power status\"\n    echo\n    echo \"  on: Power on 1S server if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if 1S server has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off 1S server ungracefully\"\n    echo\n    echo\n}\n\ndo_status() {\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo  \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is not server\"\n      return 0\n    fi\n\n    echo -n \"1S Server power for slot#$slot is \"\n    if [ $(fby2_is_server_on $slot) -eq 1 ] ; then\n        echo \"on\"\n    else\n        echo \"off\"\n    fi\n    return 0\n}\n\ndo_on() {\n\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is not server\"\n      return 0\n    fi\n\n    local force opt\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n\n        esac\n    done\n    echo -n \"Power on slot#$slot server ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if 1S Server is on or not\n        if [ $(fby2_is_server_on $slot) -eq 1 ]; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # TODO: State the power state change\n    echo \"on $(date +%s)\" > $LPS_PATH\n\n    # disable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 7c) 21\n\n    # first make sure, GPIO is high\n    gpio_set $gpio_name $gpio 1\n    # generate the power on pulse\n    gpio_set $gpio_name $gpio 0\n    sleep 1\n    gpio_set $gpio_name $gpio 1\n    sleep 1\n    # Turn on the power LED\n    /usr/local/bin/power_led.sh $slot on\n\n    # enable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 70) 21\n\n    echo \" Done\"\n    return 0\n}\n\ndo_off() {\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is no server\"\n      return 0\n    fi\n\n    echo -n \"Power off slot#$slot server ...\"\n\n    #TODO: State the power state change\n    echo \"off $(date +%s)\" > $LPS_PATH\n\n    # disable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 7c) 21\n\n    # first make sure, GPIO is high\n    gpio_set $gpio_name $gpio 1\n    sleep 1\n    gpio_set $gpio_name $gpio 0\n    sleep 5\n    gpio_set $gpio_name $gpio 1\n    # Turn off the power LED\n    /usr/local/bin/power_led.sh $slot off\n\n    # enable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 70) 21\n\n    echo \" Done\"\n    return 0\n}\n\n# Slot1: GPIOD1(25), Slot2: GPIOD3(27), Slot3: GPIOD5(29), Slot4: GPIOD7(31)\nslot=$1\n\ncase $slot in\n  1)\n    gpio=D1\n    gpio_name=PWR_SLOT1_BTN_N\n    ;;\n  2)\n    gpio=D3\n    gpio_name=PWR_SLOT2_BTN_N\n    ;;\n  3)\n    gpio=D5\n    gpio_name=PWR_SLOT3_BTN_N\n    ;;\n  4)\n    gpio=D7\n    gpio_name=PWR_SLOT4_BTN_N\n    ;;\n  *)\n    gpio=D1\n    gpio_name=PWR_SLOT1_BTN_N\n    ;;\nesac\n\ncommand=\"$2\"\nshift\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 205}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          usbcons\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Creates a virtual USB serial device and starts a console\n#                    on it.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=\"FC Switcher\"\nDESC=\"FC Failover Daemon\"\n\n# source function library\n. /etc/init.d/functions\n\n. /usr/local/fbpackages/utils/ast-functions\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    if [ \"$(wedge_board_type)\" = \"LC\" ]; then\n      # Ability to prevent this from starting by editing cmdline in u-boot.\n      # Keeping this here until I get gadget switching working properly. (t4906522)\n      /usr/local/bin/watch-fc.sh > /dev/null 2>&1 &\n      echo \"$NAME.\"\n    else\n      echo 'skipping watch-fc.sh: only necessary on six-pack line cards.'\n    fi\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall watch-fc.sh\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall watch-fc.sh\n    if [ \"$(wedge_board_type)\" = \"LC\" ]; then\n      sleep 1\n      /usr/local/bin/watch-fc.sh > /dev/null 2>&1 &\n      echo \"$NAME.\"\n    else\n      echo 'skipping watch-fc.sh: only necessary on six-pack line cards.'\n    fi\n    ;;\n  status)\n    status watch-fc.sh\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 84}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\necho \"Hot service is triggered, re-init process... \"\n\nfunction device_config() {\n      SLOT_N=$1\n      SLOT_B=$2\n\n      case $SLOT_N in\n          1)\n            I2C_REG=0x1e78a084\n          ;;\n          3)\n            I2C_REG=0x1e78a184\n          ;;\n      esac\n\n      # Delete devices on I2C bus 1 and bus 5 if there are device cards\n      # EEPROM, 0xA2\n      i2c_remove_device $SLOT_B 0x51\n      # Inlet temp sensor, 0x9A\n      i2c_remove_device $SLOT_B 0x4d\n      # outlet temp sensor, 0x9C\n      i2c_remove_device $SLOT_B 0x4e\n      # I2C mux, 0xE2\n      i2c_remove_device $SLOT_B 0x71\n      # I2C GPIO, 0x40\n      i2c_remove_device $SLOT_B 0x20\n      # Voltage sensor, 0x80\n      i2c_remove_device $SLOT_B 0x40\n\n      #if [ $(is_server_prsnt $(($SLOT_N+1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N+1))) == \"0\" ] ; then\n        if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] && [ $(get_slot_type $SLOT_N) != \"4\" ] ; then\n\n           devmem $I2C_REG w 0xFFF77304\n\n           if [ $(get_slot_type $SLOT_N) == \"2\" ]; then\n              # I2C mux, 0xE2\n              i2c_add_device $SLOT_B 0x71 pca9551\n              # I2C GPIO, 0x40\n              i2c_add_device $SLOT_B 0x20 pca9551\n           fi\n\n           # EEPROM, 0xA2\n           i2c_add_device $SLOT_B 0x51 24c128\n           # Inlet temp sensor, 0x9A\n           i2c_add_device $SLOT_B 0x4d tmp75\n           # outlet temp sensor, 0x9C\n           i2c_add_device $SLOT_B 0x4e tmp75\n           # Voltage sensor, 0x80\n           i2c_add_device $SLOT_B 0x40 ina230\n        else\n\n           devmem $I2C_REG w 0xFFF5E700\n        fi\n      #fi\n}\n\nfunction set_sysconfig() {\n      SLOT_N=$1\n      SLOT_B=$2\n\n      case $SLOT_N in\n          1)\n            device_config $SLOT_N $SLOT_B\n          ;;\n          2)\n            # Detect invalid configuration and then power-down the 12V for that slot(e.g. GP/CF plugged in to slot#2/slot#4)\n            if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] ; then\n                  gpio_set P12V_STBY_SLOT2_EN O5 0\n                  logger -p user.crit \"Invalid configuration on SLOT$SLOT_N\"\n\n                  if [ $(is_server_prsnt $(($SLOT_N-1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N-1))) != \"0\" ] ; then\n                     gpio_set P12V_STBY_SLOT1_EN O4 0\n                  fi\n            fi\n          ;;\n          3)\n            device_config $SLOT_N $SLOT_B\n          ;;\n          4)\n            # Detect invalid configuration and then power-down the 12V for that slot(e.g. GP/CF plugged in to slot#2/slot#4)\n            if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] ; then\n                  gpio_set P12V_STBY_SLOT4_EN O7 0\n                  logger -p user.crit \"Invalid configuration on SLOT$SLOT_N\"\n                  if [ $(is_server_prsnt $(($SLOT_N-1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N-1))) != \"0\" ] ; then\n                     gpio_set P12V_STBY_SLOT3_EN O6 0\n                  fi\n            fi\n          ;;\n      esac\n}\n\nSLOT=$1\nOPTION=$2\n\ncase $SLOT in\n    slot1)\n      SLOT_NUM=1\n      PE_BUFF_OE_0=B4\n      PE_BUFF_OE_1=B5\n      ;;\n    slot2)\n      SLOT_NUM=2\n      PE_BUFF_OE_0=B4\n      PE_BUFF_OE_1=B5\n      ;;\n    slot3)\n      SLOT_NUM=3\n      PE_BUFF_OE_0=B6\n      PE_BUFF_OE_1=B7\n      ;;\n    slot4)\n      SLOT_NUM=4\n      PE_BUFF_OE_0=B6\n      PE_BUFF_OE_1=B7\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {slot1|slot2|slot3|slot4} {start}\"\n      exit 1\n      ;;\nesac\n\nSLOT_BUS=$(get_slot_bus $SLOT_NUM)\n\ncase $OPTION in\n    start)\n      if [ $(is_server_prsnt $SLOT_NUM) == 0 ]; then\n        exit 1\n      fi\n      logger -p user.crit \"Start to re-init for slot$SLOT_NUM insertion\"\n      echo \"start to re-init for slot$SLOT_NUM insertion\"\n\n      # Delay 1 second for slot_type voltage ready\n      sleep 2\n\n      # System Configuration\n      echo \"reset system configuration for $SLOT $OPTION\"\n      /usr/local/bin/check_slot_type.sh $SLOT\n\n      # Remove Service for new device/server\n      # REST API\n      sv stop restapi\n\n      # Sensor\n      sv stop sensord\n      /usr/bin/kv del $SLOT'.*'\n      set_sysconfig $SLOT_NUM $SLOT_BUS\n\n      # GPIO\n      sv stop gpiod\n\n      # IPMB\n      sv stop ipmbd_$SLOT_BUS\n\n      # Console\n      sv stop mTerm$SLOT_NUM\n\n      # Delay to wait for sv stop\n      sleep 3\n\n      # Restart Service for new device/server\n      if [[ $(is_server_prsnt $SLOT_NUM) == \"1\" ]]; then\n        if [[ $(get_slot_type $SLOT_NUM) == \"0\" || $(get_slot_type $SLOT_NUM) == \"4\" ]]; then\n          echo \"restart mTerm for $SLOT $OPTION\"\n          sv start mTerm$SLOT_NUM\n\n          echo \"restart ipmbd for $SLOT $OPTION\"\n          sv start ipmbd_$SLOT_BUS\n          rm -rf /tmp/fruid_$SLOT*\n          /usr/local/bin/bic-cached -s $SLOT_NUM > /dev/null 2>&1 &\n        fi\n      fi\n\n      # Server Type recognition restart\n      echo \"restart server type recognition for $SLOT\"\n      /usr/local/bin/check_server_type.sh $SLOT\n\n      # Setup fan config\n      /etc/init.d/setup-fan.sh\n\n      echo \"restart gpiod for $SLOT $OPTION\"\n      sv start gpiod\n\n      echo \"restart sensord for $SLOT $OPTION\"\n      sv start sensord\n\n      echo \"restart rest-api for $SLOT $OPTION\"\n      sv start restapi\n\n      if [ $(is_date_synced) == \"0\" ]; then\n        /usr/local/bin/sync_date.sh\n      fi\n\n      logger -p user.crit \"Finish re-init for slot$SLOT_NUM insertion\"\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {slot1|slot2|slot3|slot4} {start}\"\n      exit 1\n      ;;\nesac\n\necho \"done.\"\n", "num_lines": 228}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Function to set the less significant hex digit\ndisplay_lower() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOG[0...3].\n    # For GPIO bank G, SCU84[0..3] must be 0.\n    devmem_clear_bit $(scu_addr 84) 0\n    devmem_clear_bit $(scu_addr 84) 1\n    devmem_clear_bit $(scu_addr 84) 2\n    devmem_clear_bit $(scu_addr 84) 3\n\n    # Now set the GPIOs to the right binary values\n    gpio_set LED_POSTCODE_0 G0 $bit0\n    gpio_set LED_POSTCODE_1 G1 $bit1\n    gpio_set LED_POSTCODE_2 G2 $bit2\n    gpio_set LED_POSTCODE_3 G3 $bit3\n}\n\n# Function to set the more significant hex digit\ndisplay_upper() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOP[4...7].\n\n    gpio_set LED_POSTCODE_4 P4 $bit0\n    gpio_set LED_POSTCODE_5 P5 $bit1\n    gpio_set LED_POSTCODE_6 P6 $bit2\n    gpio_set LED_POSTCODE_7 P7 $bit3\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\n# Get upper/lower decimal values\nLOWER_DEC_VALUE=$(expr $DEC_VALUE % 16)\nUPPER_DEC_VALUE=$(expr $DEC_VALUE / 16)\n\n# Display the results\ndisplay_lower $LOWER_DEC_VALUE\ndisplay_upper $UPPER_DEC_VALUE\n\n", "num_lines": 97}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nDEF_PWR_ON=1\nTO_PWR_ON=\nPOWER_ON_SLOT=\nRETRY=0\n\ncheck_por_config()\n{\n\n  TO_PWR_ON=-1\n\n  POR=`kv get slot${1}_por_cfg persistent`\n  # Check if the file/key doesn't exist\n  if [ -z \"${POR}\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    # Case ON\n    if [ $POR == \"on\" ]; then\n      TO_PWR_ON=1;\n\n    # Case OFF\n    elif [ $POR == \"off\" ]; then\n      TO_PWR_ON=0;\n\n    # Case LPS\n    elif [ $POR == \"lps\" ]; then\n\n      # Check if the file/key doesn't exist\n      LS=`kv get /pwr_server${1}_last_state persistent`\n      if [ -z \"${LS}\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        if [ $LS == \"on\" ]; then\n          TO_PWR_ON=1;\n        elif [ $LS == \"off\" ]; then\n          TO_PWR_ON=0;\n        fi\n      fi\n    fi\n  fi\n}\n\n# Check whether it is fresh power on reset\nif [ $(is_bmc_por) -eq 1 ]; then\n  # Remove all GP/GPv2 info\n  for i in {2..13};\n  do\n    kv del sys_config/fru2_m2_${i}_info persistent > /dev/null 2>&1\n    kv del sys_config/fru4_m2_${i}_info persistent > /dev/null 2>&1\n  done\n\n  /usr/local/bin/sync_date.sh\n\n  # Disable clearing of PWM block on WDT SoC Reset\n  devmem_clear_bit $(scu_addr 9c) 17\n\n  check_por_config 1\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) == \"0\" ] ; then\n    POWER_ON_SLOT+=(1)\n    power-util slot1 on &\n  fi\n\n  check_por_config 2\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 2) == \"1\" ] && [ $(get_slot_type 2) == \"0\" ] ; then\n    POWER_ON_SLOT+=(2)\n    power-util slot2 on &\n  fi\n\n  check_por_config 3\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 3) == \"1\" ] && [ $(get_slot_type 3) == \"0\" ] ; then\n    POWER_ON_SLOT+=(3)\n    power-util slot3 on &\n  fi\n\n  check_por_config 4\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 4) == \"1\" ] && [ $(get_slot_type 4) == \"0\" ] ; then\n    POWER_ON_SLOT+=(4)\n    power-util slot4 on &\n  fi\n\n  # Wait for all slots finish power-up\n  while [ $RETRY -lt 10 ]\n  do\n    FINISH=1\n    for i in ${POWER_ON_SLOT[@]}\n    do\n      status=$(power-util slot$i status)\n      if [ ${status:(-3)} == \"OFF\" ]; then\n        FINISH=0\n      fi\n    done\n    if [ $FINISH -eq 1 ]; then\n      break\n    fi\n    RETRY=$(($RETRY+1))\n    sleep 1\n  done\n\n  if [ $(is_date_synced) == \"0\" ]; then\n    # Time sync with RC Server\n    echo \"Start time sync with server\"\n    sh /usr/local/bin/time-sync.sh &\n  fi\nfi\n", "num_lines": 135}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <slot#> <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 2 ]; then\n    usage $0\nfi\n\n# Slot#1: GPIOM0(96),Slot#2: GPIOM1(97),Slot#3: GPIOM2(98),Slot#4: GPIOM3(99)\nif [ $1 = \"1\" ]; then\n    gpio=M0\n    name=PWR1_LED\nelif [ $1 = \"2\" ]; then\n    gpio=M1\n    name=PWR2_LED\nelif [ $1 = \"3\" ]; then\n    gpio=M2\n    name=PWR3_LED\nelif [ $1 = \"4\" ]; then\n    gpio=M3\n    name=PWR4_LED\nelse\n    usage $0\nfi\n\n\nif [ $2 = \"on\" ]; then\n    val=1\nelif [ $2 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set $name $gpio $val\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\n#TODO: Add logic to control mux based on front panel switch\necho -n \"Set USB Mux to given slot ... \"\n\n# USB_MUX_SEL signals: GPIOE4(36), GPIOE5(37)\nslot=$1\n\ncase $slot in\n  1)\n    gpio_set FM_USB_SW0 E4 0\n    gpio_set FM_USB_SW1 E5 0\n    gpio_set USB_MUX_EN_R_N AB3 0\n    ;;\n  2)\n    gpio_set FM_USB_SW0 E4 E4 1\n    gpio_set FM_USB_SW1 E5 E5 0\n    gpio_set USB_MUX_EN_R_NAB3 0\n    ;;\n  3)\n    gpio_set FM_USB_SW0 E4 E4 0\n    gpio_set FM_USB_SW1 E5 E5 1\n    gpio_set USB_MUX_EN_R_N AB3 0\n    ;;\n  4)\n    gpio_set FM_USB_SW0 E4 E4 1\n    gpio_set FM_USB_SW1 E5 E5 1\n    gpio_set USB_MUX_EN_R_N AB3 0\n    ;;\n  *)\n    gpio_set USB_MUX_EN_R_N AB3 1\n    ;;\nesac\n\necho \"Done\"\n", "num_lines": 56}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Check OCP NIC\nsh /usr/local/bin/check_ocp_nic.sh > /dev/NULL\n\n# Get and Set slot type\nsh /usr/local/bin/check_slot_type.sh > /dev/NULL\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Determine BMC Power On Reset flag\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get server type\nsh /usr/local/bin/check_server_type.sh > /dev/NULL\n\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# This file contains definitions for the different system configurations. \n# We should probably move some more of the definitions to this file at some point.\n\necho -n \"Setup System Configuration ..\"\n\n. /usr/local/fbpackages/utils/ast-functions\n\nif [ $(is_server_prsnt 2) == \"1\" ] ; then\n   if [ $(get_slot_type 2) != \"0\" ] ; then\n      gpio_set P12V_STBY_SLOT2_EN O5 0\n      logger -p user.crit \"Invalid configuration on SLOT2\"\n      if [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) != \"0\" ] ; then\n         gpio_set P12V_STBY_SLOT1_EN O4 0\n      fi\n   fi\nelse\n   if [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) != \"0\" ] ; then\n      gpio_set P12V_STBY_SLOT1_EN O4 0\n   fi\nfi\n\nif [ $(is_server_prsnt 4) == \"1\" ] ; then\n   if [ $(get_slot_type 4) != \"0\" ] ; then\n      gpio_set P12V_STBY_SLOT4_EN O7 0\n      logger -p user.crit \"Invalid configuration on SLOT4\"\n      if [ $(is_server_prsnt 3) == \"1\" ] && [ $(get_slot_type 3) != \"0\" ] ; then\n         gpio_set P12V_STBY_SLOT3_EN O6 0\n      fi\n   fi\nelse\n   if [ $(is_server_prsnt 3) == \"1\" ] && [ $(get_slot_type 3) != \"0\" ] ; then\n      gpio_set P12V_STBY_SLOT3_EN O6 0\n   fi\nfi\n\n# Enable buffer to pass through signal by system configuration\nif [ $(is_server_prsnt 1) == \"1\" ] && [ $(is_server_prsnt 2) == \"1\" ] ; then\n   if [ $(get_slot_type 1) != \"0\" ] && [ $(get_slot_type 2) == \"0\" ] ; then\n      gpio_set CLK_BUFF1_PWR_EN_N J0 0\n      gpio_set PE_BUFF_OE_0_N B4 0\n      gpio_set PE_BUFF_OE_1_N B5 0\n   else\n      gpio_set PE_BUFF_OE_0_N B4 1\n      gpio_set PE_BUFF_OE_1_N B5 1\n   fi\nelse\n   gpio_set PE_BUFF_OE_0_N B4 1\n   gpio_set PE_BUFF_OE_1_N B5 1\nfi\n\nif [ $(is_server_prsnt 3) == \"1\" ] && [ $(is_server_prsnt 4) == \"1\" ] ; then\n   if [ $(get_slot_type 3) != \"0\" ] && [ $(get_slot_type 4) == \"0\" ] ; then\n      gpio_set CLK_BUFF2_PWR_EN_N J1 0\n      gpio_set PE_BUFF_OE_2_N B6 0\n      gpio_set PE_BUFF_OE_3_N B7 0\n   else\n      gpio_set PE_BUFF_OE_2_N B6 1\n      gpio_set PE_BUFF_OE_3_N B7 1\n   fi\nelse\n   gpio_set PE_BUFF_OE_2_N B6 1\n   gpio_set PE_BUFF_OE_3_N B7 1\nfi\n\n# create devices on I2C bus 1 and bus 5\n# Bus1,  Glacier Point\nif [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) != \"0\" && $(get_slot_type 1) != \"4\" ]]; then\n\n   devmem 0x1e78a084 w 0xFFF77304\n\n   if [ $(get_slot_type 1) == \"2\" ]; then\n      # I2C mux, 0xE2\n      echo pca9551 0x71 > /sys/class/i2c-dev/i2c-1/device/new_device\n      # I2C GPIO, 0x40\n      echo pca9551 0x20 > /sys/class/i2c-dev/i2c-1/device/new_device\n   fi\n\n   # EEPROM, 0xA2\n   echo 24c128 0x51 > /sys/class/i2c-dev/i2c-1/device/new_device\n   # Inlet temp sensor, 0x9A\n   echo tmp75 0x4d > /sys/class/i2c-dev/i2c-1/device/new_device\n   # outlet temp sensor, 0x9C\n   echo tmp75 0x4e > /sys/class/i2c-dev/i2c-1/device/new_device\n   # Voltage sensor, 0x80\n   echo ina230 0x40 > /sys/class/i2c-dev/i2c-1/device/new_device\nelse\n   devmem 0x1e78a084 w 0xFFF5E700\nfi\n\n# Bus5,  Glacier Point\nif [[ $(is_server_prsnt 3) == \"1\" && $(get_slot_type 3) != \"0\" && $(get_slot_type 3) != \"4\" ]]; then\n\n   devmem 0x1e78a184 w 0xFFF77304\n\n   if [ $(get_slot_type 3) == \"2\" ]; then\n      # I2C mux, 0xE2\n      echo pca9551 0x71 > /sys/class/i2c-dev/i2c-5/device/new_device\n      # I2C GPIO, 0x40\n      echo pca9551 0x20 > /sys/class/i2c-dev/i2c-5/device/new_device\n   fi\n\n   # EEPROM, 0xA2\n   echo 24c128 0x51 > /sys/class/i2c-dev/i2c-5/device/new_device\n   # Inlet temp sensor, 0x9A\n   echo tmp75 0x4d > /sys/class/i2c-dev/i2c-5/device/new_device\n   # outlet temp sensor, 0x9C\n   echo tmp75 0x4e > /sys/class/i2c-dev/i2c-5/device/new_device\n   # Voltage sensor, 0x80\n   echo ina230 0x40 > /sys/class/i2c-dev/i2c-5/device/new_device\nelse\n   devmem 0x1e78a184 w 0xFFF5E700\nfi\n\necho \"done\"\n", "num_lines": 115}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# The T2 chip can prefer different input voltages, depending, presumably\n# of manufacturing variations.  We need to determine whether it wants\n# 0.95V or 1.025V, reset the T2 to reduce total power usage, set the\n# outgoing voltage on the first buck converter, and bring T2 up out of\n# reset.\n\n. /usr/local/fbpackages/utils/ast-functions\n\nkernel_ver=$(get_kernel_ver)\n\n# read the T2 ROV after the GPIOs are enabled\nt2_rov() {\n    local val0 val1 val2\n    # Note that the values are *not* read in order.\n    if [ $kernel_ver == 5 ]; then\n        val0=$(cat /sys/class/gpio/gpio850/value 2>/dev/null)\n        val1=$(cat /sys/class/gpio/gpio848/value 2>/dev/null)\n        val2=$(cat /sys/class/gpio/gpio849/value 2>/dev/null)\n    else\n        val0=$(cat /sys/class/gpio/gpio58/value 2>/dev/null)\n        val1=$(cat /sys/class/gpio/gpio56/value 2>/dev/null)\n        val2=$(cat /sys/class/gpio/gpio57/value 2>/dev/null)\n    fi\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nrov=$(t2_rov)\n\n# target_volts come from the data sheet and 18mV of loss and\n# some fudging based on actual measurements to get either 1.025V\n# or 0.95V at T2\nif [ $rov -eq 1 ]; then\n    target_volts=0x5a\nelif [ $rov -eq 2 ]; then\n    target_volts=0x65\nelse\n    echo \"Unrecognized T2 ROV value $rov, setting failed.\"\n    exit 1\nfi\ntarget_volts=$(( $target_volts * 1 ))  # normalize to decimal\n\n# We shouldn't have to rmmod pmbus, because it hasn't been loaded yet,\n# but if the script is rerun after the system is up, it may be necessary.\nif [ $kernel_ver == 4 ]; then\n    rmmod pmbus\n    reload=$?\nfi\n\n# Get current voltage value\ncur_volts=$(i2cget -y 1 0x60 0x8b w)\ncur_volts=$(( $cur_volts * 1 ))  # normalize to decimal\n\n# Only bounce the T2 if we actually need to modify the voltage\nif [ $cur_volts -ne $target_volts ]; then \n    # Set values before turning out output;  we're using \"PCIE, then MCS\"\n    gpio_set SYSTEM_ID3_LED_N F2 1\n    gpio_set SYSTEM_ID4_LED_N F3 1\n    gpio_set SMB_TEMP_SCL_R C0 0\n    # T2 is in reset;  note that this may cause NMI messages on the uServer,\n    # which shouldn't be up anyway when this is first run.\n    \n    # Set the requested value to the current value to avoid rapid shifts\n    i2cset -y 1 0x60 0x21 $cur_volts w\n    # Enable the requested voltage\n    i2cset -y 1 0x60 0xd2 0x5a\n    i2cset -y 1 0x60 0xd3 0x5a\n    sleep 1\n\n    # Set the target voltage\n    i2cset -y 1 0x60 0x21 $target_volts w\n    \n    sleep 1\n\n    # Let T2 come out of reset\n    gpio_set SMB_TEMP_SCL_R C0 1\n    echo \"T2 ROV value set based on $rov.\"\n    sleep 2\n    gpio_set SYSTEM_ID3_LED_N F2 0\n    gpio_set SYSTEM_ID4_LED_N F3 0\nelse\n    echo \"T2 ROV already correctly set.\"\nfi\n\nif [ $kernel_ver == 4 ]; then\n    # Bring back pmbus if necessary\n    if [ $reload -eq 0 ]; then\n        modprobe pmbus\n    fi\nfi\n", "num_lines": 110}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nSLOT=$1\nSLOT_NUM=${SLOT#\"slot\"}\n\nPWR_UTIL_PID=$(ps | grep power-util | grep \"$SLOT\" | awk '{print $1}')\nHSV_REINIT_PID=$(ps | grep hotservice-reinit.sh | grep \"$SLOT\" | awk '{print $1}')\n\nPWR_UTIL_LOCK=\"/var/run/power-util_$SLOT_NUM.lock\"\nBIC_CACHED_LOCK=\"/var/run/bic-cached_$SLOT_NUM.lock\"\n\nif [ ! -z \"$PWR_UTIL_PID\" ]; then\n  logger -p user.info \"slot-removal-precheck.sh: kill power-util $SLOT, pid: $PWR_UTIL_PID\"\n  kill -9 \"$PWR_UTIL_PID\"\nfi\n\nif [ ! -z \"$HSV_REINIT_PID\" ]; then\n  logger -p user.info \"slot-removal-precheck.sh: kill hotservice-reinit.sh $SLOT, pid: $HSV_REINIT_PID\"\n  kill -9 \"$HSV_REINIT_PID\"\nfi\n\n# check the lock file to find out the flock are occupied by which process\n# then kill the processes to free the flock\nfor lock_file in \"$PWR_UTIL_LOCK\" \"$BIC_CACHED_LOCK\"\ndo\n  if [ -f \"$lock_file\" ]; then\n    for lock_pid in $(fuser \"$lock_file\")\n    do\n      cmdline=$(cat < /proc/\"$lock_pid\"/cmdline | tr '\\000' ' ')\n      logger -p user.info \"slot-removal-precheck.sh: kill $cmdline, pid: $lock_pid, lock_file: $lock_file\"\n      kill -9 \"$lock_pid\"\n    done\n\n    rm \"$lock_file\"\n  fi\ndone\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Sync BMC's date with one of the four servers\nsync_date()\n{\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    if  kv get time_sync ; then\n      # ND Server Time Sync by IPMI command\n      output=$(kv get time_sync)\n      if [ ${#output} == 11 ] ; then\n        echo Syncing up BMC time with server...\n        date -s @$((16#$(echo \"$output\" | awk '{print $4$3$2$1}')))\n        test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n        echo 1 > /tmp/sync_date\n      fi\n    else\n      for i in 1 2 3 4\n      do\n        if [[ $(is_server_prsnt $i) == \"1\" && $(get_slot_type $i) == \"0\" ]] ; then\n          # Use standard IPMI command 'get-sel-time' to read RTC time\n          s_type=$(get_server_type $i)\n          if [ \"$s_type\" == \"0\" ] ; then\n            output=$(/usr/local/bin/me-util slot$i 0x28 0x48)\n          elif [ \"$s_type\" == \"2\" ] ; then\n            output=$(/usr/bin/bic-util slot$i 0x28 0x48)\n          fi\n          # if the command fails, continue to next slot\n          [ ${#output} != 12 ] && continue\n          echo Syncing up BMC time with server$i...\n          date -s @$((16#$(echo \"$output\" | awk '{print $4$3$2$1}')))\n          test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n          echo 1 > /tmp/sync_date\n          break\n        fi\n      done\n    fi\n  else\n    test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n    echo 1 > /tmp/sync_date\n  fi\n}\n\nsync_date\n", "num_lines": 65}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          time-sync\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Time Sync With Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\ntime_sync_success=0\ntime_sync_with_IMC=0\n\n# Sync BMC's date with one of the four servers\nsync_date()\n{\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    sleep 60    #wait for BIOS writes RTC time to internal memory \n    max_retry=6\n    default_time_h=5A   #default time high byte 2018-01-01\n    default_time_l=4A   #default time low byte 2018-01-01\n    for i in 1 2 3 4 \n    do\n      if [[ $(is_server_prsnt $i) == \"1\" && $(get_slot_type $i) == \"0\" && $(get_server_type $i) == \"1\" ]] ; then\n        retry_times=0\n        time_sync_with_IMC=1\n        while [ ${retry_times} -lt ${max_retry} ]\n        do\n          # Use IMC command 'get-rtc-time' to read RTC time\n          output=$(/usr/bin/bic-util slot$i 0xe0 0x02 0x15 0xa0 0x00 0x10 0xb8 0xe3 0xa9 0x05 0x0 0x0 0x0 0x0 0x0)\n          # if the command fails and the number of retry times reach max retry, continue to next slot\n          if [ $(echo $output | wc -c) == 36 ] ; then \n            time_h=$((16#$(echo \"$output\" | cut -c 34-35)))\n            time_l=$((16#$(echo \"$output\" | cut -c 31-32)))\n\n            if [ \"$time_h\" -gt $((16#${default_time_h})) ] ; then\n              echo Syncing up BMC time with server$i...\n              date -s @$((16#$(echo $output | awk '{print $12$11$10$9}')))\n              test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n              time_sync_success=1\n              break\n            fi\n\n            if [[ \"$time_h\" -ge $((16#${default_time_h})) && \"$time_l\" -ge $((16#${default_time_l})) ]] ; then\n              echo Syncing up BMC time with server$i...\n              date -s @$((16#$(echo $output | awk '{print $12$11$10$9}')))\n              test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n              time_sync_success=1\n              break\n            fi\n          fi\n          retry_times=$(($retry_times+1))\n          sleep 5\n        done\n      fi\n      if [ $time_sync_success == 1 ] ; then\n        break\n      fi\n    done\n    # This log only appears in the RC system\n    if [[ $time_sync_success == 0 && $time_sync_with_IMC == 1 ]] ; then\n      logger -p user.crit \"Time sync with IMC failed, using 2018/01/01 as default\" \n    fi\n  fi\n  sts=$(ifconfig eth0 | grep -i \"inet addr\")\n  if [ \"$sts\" == \"\" ]; then    #No ipv4 ip\n    kill -9 `cat /var/run/dhclient.eth0.pid`\n    #if dhcleint need to restart, make it non-demonized so that dhclient will continuely re-access ipv4 address\n    dhclient -d -pf /var/run/dhclient.eth0.pid eth0 > /dev/null 2>&1 &\n  fi\n}\n\nsync_date\n\n", "num_lines": 94}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\ngpio_set DEBUG_UART_SEL_0 E0 $VALUE\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nMAC1LINK=A0   # GPIOA0\nFAB0_PRES=C4  # GPIOC4\nFAB1_PRES=C5  # GPIOC5\n\nwhile true; do\n  # fabN_pres: active low.\n  if [ $(gpio_get SMB_MEZZ_NIC_CLK_R $FAB0_PRES) = 0 ]; then\n    gpio_set BMC_READY_N $MAC1LINK 0\n  elif [ $(gpio_get SMB_MEZZ_NIC_DAT_R $FAB1_PRES) = 0 ]; then\n    gpio_set BMC_READY_N $MAC1LINK 1\n  fi\n  sleep 1\ndone\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nmac=$(i2cdump -y 0x0 0x49 s 0xd4 | grep '^00: d4'| awk '{ print $3\":\"$4\":\"$5\":\"$6\":\"$7\":\"$8 }') 2>/dev/null\n\nif [ -n \"$mac\" ]; then\n    echo $mac\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\nfi\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for fby2... \"\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  if [ $(is_server_prsnt 1) == \"1\" ]; then\n    if [ $(is_slot_12v_on 1) == \"1\" ]; then\n      if [[ $(get_slot_type 1) != \"0\" || $(is_bic_ready 1) == \"1\" ]]; then\n        SLOTS=\"$SLOTS slot1\" \n      fi\n    else\n      SLOTS=\"$SLOTS slot1\"\n    fi\n  fi\n\n  if [ $(is_server_prsnt 2) == \"1\" ]; then\n    if [ $(is_slot_12v_on 2) == \"1\" ]; then\n      if [[ $(get_slot_type 2) != \"0\" || $(is_bic_ready 2) == \"1\" ]]; then\n        SLOTS=\"$SLOTS slot2\"\n      fi\n    else\n      SLOTS=\"$SLOTS slot2\"\n    fi\n  fi\n\n  if [ $(is_server_prsnt 3) == \"1\" ]; then\n    if [ $(is_slot_12v_on 3) == \"1\" ]; then\n      if [[ $(get_slot_type 3) != \"0\" || $(is_bic_ready 3) == \"1\" ]]; then\n        SLOTS=\"$SLOTS slot3\"\n      fi\n    else\n      SLOTS=\"$SLOTS slot3\"\n    fi\n  fi\n\n  if [ $(is_server_prsnt 4) == \"1\" ]; then\n    if [ $(is_slot_12v_on 4) == \"1\" ]; then\n      if [[ $(get_slot_type 4) != \"0\" || $(is_bic_ready 4) == \"1\" ]]; then\n        SLOTS=\"$SLOTS slot4\"\n      fi\n    else\n      SLOTS=\"$SLOTS slot4\"\n    fi\n  fi\n\nSLOTS=\"$SLOTS spb nic\"\nexec /usr/local/bin/sensord $SLOTS\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n. /usr/local/bin/i2c-utils.sh\n\ncheck_i2c_device_bind() {\n   # $1 - driver name\n   # $2 - device path in <bus>-00<addr> format.\n   chk_driver_dir=\"/sys/bus/i2c/drivers/$1\"\n\n   if [ ! -L \"$chk_driver_dir\"/\"$2\" ]; then\n      # device not found in driver folder\n      return 1\n   fi\n\n   # bind success\n   return 0\n}\n\ninit_northdome_inlet_temp_type() {\n   key_name=\"inlet_temp_type\"\n   dev_uid_1=\"9-004e\"\n   dev_name_1=\"tmp421\"\n   dev_driver_1=\"$(i2c_driver_map $dev_name_1)\"\n   dev_uid_2=\"9-0048\"\n   dev_name_2=\"tmp75\"\n   dev_driver_2=\"$(i2c_driver_map $dev_name_2)\"\n   retry_count=3\n   val=\"unknow\"\n\n   while [ \"$retry_count\" -gt \"0\" ]\n   do\n      check_i2c_device_bind $dev_driver_1 $dev_uid_1 && val=$dev_name_1 && break\n      check_i2c_device_bind $dev_driver_2 $dev_uid_2 && val=$dev_name_2 && break\n\n      # both sensors not  successful binding, rebind again\n      i2c_bind_driver $dev_driver_1 $dev_uid_1\n      i2c_bind_driver $dev_driver_2 $dev_uid_2\n\n      retry_count=$((retry_count-1))\n   done\n\n   kv set \"$key_name\" \"$val\"\n}\n\ninit_northdome_outlet_temp_type() {\n   key_name=\"outlet_temp_type\"\n   dev_uid_1=\"9-004f\"\n   dev_name_1=\"tmp421\"\n   dev_driver_1=\"$(i2c_driver_map $dev_name_1)\"\n   dev_uid_2=\"9-0049\"\n   dev_name_2=\"tmp75\"\n   dev_driver_2=\"$(i2c_driver_map $dev_name_2)\"\n   retry_count=3\n   val=\"unknow\"\n\n   while [ \"$retry_count\" -gt \"0\" ]\n   do\n      check_i2c_device_bind $dev_driver_1 $dev_uid_1 && val=$dev_name_1 && break\n      check_i2c_device_bind $dev_driver_2 $dev_uid_2 && val=$dev_name_2 && break\n\n      # both sensors not  successful binding, rebind again\n      i2c_bind_driver $dev_driver_1 $dev_uid_1\n      i2c_bind_driver $dev_driver_2 $dev_uid_2\n\n      retry_count=$((retry_count-1))\n   done\n\n   kv set \"$key_name\" \"$val\"\n}\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\nkernel_ver=$(get_kernel_ver)\nif [ $kernel_ver == 4 ]; then\n    modprobe lm75\n    modprobe pmbus\n\n    # Enable the ADC inputs;  adc0 - adc15 are connected to various voltage sensors\n    # adc12 - adc15 are for SLOT_TYPE\n\n    PATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n    # setup ADC channels\n\n    ADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n    # For FBY2 tyep V:\n    # channel 0:  r1:  5.36K; r2:  2.0K; v2: 0mv\n    # channel 1:  r1:  15.8K; r2:  2.0K; v2: 0mv\n    # channel 2:  r1:  2.87K; r2:  2.0K; v2: 0mv\n    # channel 3:  r1:  15.8K; r2:  2.0K; v2: 0mv\n    # channel 4:  r1:  15.8K; r2:  2.0K; v2: 0mv\n    # channel 5:  r1:  15.8K; r2:  2.0K; v2: 0mv\n    # channel 6:  r1:  15.8K; r2:  2.0K; v2: 0mv\n    # channel 7:  r1:  2.87K; r2:  2.0K; v2: 0mv\n    # channel 8:  r1:     1K; r2:  0.0K; v2: 0mv\n    # channel 9:  r1:     1K; r2:  0.0K; v2: 0mv\n    # channel 10: r1:  1.69K; r2:  2.0K; v2: 0mv\n    # channel 11: r1:    665; r2:  2.0K; v2: 0mv\n    # channel 12: r1:     1K; r2:    0K; v2: 0mv\n    # channel 13: r1:     1K; r2:    0K; v2: 0mv\n    # channel 14: r1:     1K; r2:    0K; v2: 0mv\n    # channel 15: r1:     1K; r2:    0K; v2: 0mv\n\n    config_adc() {\n        channel=$1\n        r1=$2\n        r2=$3\n        v2=$4\n        echo $r1 > ${ADC_PATH}/adc${channel}_r1\n        echo $r2 > ${ADC_PATH}/adc${channel}_r2\n        echo $v2 > ${ADC_PATH}/adc${channel}_v2\n        echo 1 > ${ADC_PATH}/adc${channel}_en\n    }\n\n    config_adc 0  5360  2000 0\n    config_adc 1 15800  2000 0\n    config_adc 2  2870  2000 0\n    config_adc 3 15800  2000 0\n    config_adc 4 15800  2000 0\n    config_adc 5 15800  2000 0\n    config_adc 6 15800  2000 0\n    config_adc 7  2870  2000 0\n    config_adc 8  \t 0  1000 0\n    config_adc 9  \t 0  1000 0\n    config_adc 10 1690  2000 0\n    config_adc 11  665  2000 0\n    config_adc 12    0  1000 0\n    config_adc 13    0  1000 0\n    config_adc 14    0  1000 0\n    config_adc 15    0  1000 0\nfi\n\ngpio_export MB_HSC_RSENSE_SRC GPIOA2\n\nspb_type=$(get_spb_type)\n\n# ADM1278 Configuration\nif [ $spb_type == \"1\" ]; then\n   # Yosemite V2.50 Platform\n   # Clear PEAK_PIN & PEAK_IOUT register\n   i2cset -y -f 10 0x40 0xd0 0x0000 w\n   i2cset -y -f 10 0x40 0xda 0x0000 w\n\n   #\n   i2cset -y -f 10 0x40 0xd4 0x3f1c w\n   i2cset -y -f 10 0x40 0xd5 0x0400 w\n   i2cset -y -f 10 0x40 0xd8 0x0003 w\n\n   # calibrtion to get HSC to trigger 60A based on EE team input\n   # 0xe18 = 3608 (dec)\n   #(3608*10-20475)/ (800*0.3)= 65.0208A\n   # 65.0208* 0.92259 = 59.9875A\n\n   # Get ADM1278 Rsense source, low: main source, high: 2nd source\n   src=$(gpio_get MB_HSC_RSENSE_SRC GPIOA2)\n   if [ $src == \"0\" ]; then\n      i2cset -y -f 10 0x40 0x4a 0x0e18 w\n   else\n      i2cset -y -f 10 0x40 0x4a 0x0d9f w\n   fi\nelif [ $spb_type == \"2\" ]; then\n   # FBND Rome & GPv2 Platform\n   # Clear PEAK_PIN & PEAK_IOUT register\n   i2cset -y -f 10 0x40 0xd0 0x0000 w\n   i2cset -y -f 10 0x40 0xda 0x0000 w\n\n   #\n   i2cset -y -f 10 0x40 0xd4 0x3d1c w\n   i2cset -y -f 10 0x40 0xd5 0x0400 w\n\n   # calibrtion to get HSC to trigger 63A based on EE team input\n   # 0xe64 = 3686 (dec)\n   #(3684*10-20475)/ (800*0.3)= 68.1875A\n   # 68.1875* 0.92355 = 62.9746A\n   i2cset -y -f 10 0x40 0x4a 0x0e64 w\nelif [ $spb_type == \"3\" ]; then\n   # FBND Milan Platform\n   if [ $(gpio_get HSC_SELECT A1) == \"0\" ]; then\n      # ADM1278\n      echo \"HSC Type: ADM1278\"\n      # Clear PEAK_PIN & PEAK_IOUT register\n      i2cset -y -f 10 0x40 0xd0 0x0000 w\n      i2cset -y -f 10 0x40 0xda 0x0000 w\n\n      #\n      i2cset -y -f 10 0x40 0xd4 0x3d1c w\n      i2cset -y -f 10 0x40 0xd5 0x0400 w\n\n      # calibrtion to get HSC to trigger 63A based on EE team input\n      # 0x0de9 = 3561 (dec)\n      #(3561*10-20475)/ (800*0.3)= 63.0625A\n      # 63.0625 * 0.9989997 = 62.9994A\n      i2cset -y -f 10 0x40 0x4a 0x0de9 w\n   else\n      # LTC4282\n      echo \"HSC Type: LTC4282\"\n\n      # ILIM_ADJUST (0x11)\n      # bit[7-5]: 000b\n      # bit[4-3]: 10b\n      # bit[2]: 0b\n      # bit[1]: 1b\n      # bit[0]: 0b\n      i2cset -y -f 10 0x41 0x11 0x12 b\n\n      i2cset -y -f 10 0x41 0x02 0x04 b\n      # Set VSENSE MAX for OC Warning\n      # (75 * 0.04)/(255* 0.001* 0.1875)= 62.745098039 A\n      i2cset -y -f 10 0x41 0x03 0x20 b\n      i2cset -y -f 10 0x41 0x0d 0x4B b\n\n      # FET_BAD_FAULT_TIME set to 80\n      i2cset -y -f 10 0x41 0x06 0x50 b\n\n      # Clear PEAK_PIN & PEAK_IOUT register\n      i2cset -y -f 10 0x41 0x44 0x0000 w\n      i2cset -y -f 10 0x41 0x4A 0x0000 w\n   fi\nelse\n   # Yosemite V2 Platform\n   # Clear PEAK_PIN & PEAK_IOUT register\n   i2cset -y -f 10 0x40 0xd0 0x0000 w\n   i2cset -y -f 10 0x40 0xda 0x0000 w\n\n   #\n   i2cset -y -f 10 0x40 0xd4 0x3f1c w\n   i2cset -y -f 10 0x40 0xd5 0x0400 w\n\n   # calibrtion to get HSC to trigger 50A based on EE team input\n   # 0xd14 = 3348 (dec)\n   #(3348*10-20475)/ (800*0.3)= 54.1875A\n   # 54.1875* 0.92190 = 49.9554A\n   i2cset -y -f 10 0x40 0x4a 0x0d14 w\nfi\n\nif [ $kernel_ver == 4 ]; then\n  rmmod adm1275\n  modprobe adm1275\nfi\n\n# init inlet & outlet temp sensor type cache\nif [ \"$spb_type\" -eq \"3\" ]; then\n   init_northdome_inlet_temp_type\n   init_northdome_outlet_temp_type\nfi\n", "num_lines": 282}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n\nSENSOR_UTIL=\"/usr/local/bin/sensor-util\"\nSENSORDUMP_FILE=\"/mnt/data/sensordump\"\n\nlogger -t \"gpiointrd\" -p daemon.crit \"Sensordump is generated at $SENSORDUMP_FILE\"\n\necho \"Sensor dump log created at \" > $SENSORDUMP_FILE  && date >> $SENSORDUMP_FILE && echo $'\\n\\n' >> $SENSORDUMP_FILE && echo \"Senor Dump\" >> $SENSORDUMP_FILE && $SENSOR_UTIL all >> $SENSORDUMP_FILE\nexit 0\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/setup-gpio\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\nfunction init_class2_sdr() {\n  /usr/local/bin/bic-cached -s slot1\n  /usr/local/bin/bic-cached -f slot1 > /dev/null 2>&1 &\n}\n\nfunction init_class1_sdr() {\n  # -f means `dump fru` only\n  if [[ $(is_sb_bic_ready 1) == \"1\" ]]; then\n    /usr/local/bin/bic-cached -s slot1\n    /usr/local/bin/bic-cached -f slot1 > /dev/null 2>&1 &\n  fi\n\n  if [[ $(is_sb_bic_ready 2) == \"1\" ]]; then\n    /usr/local/bin/bic-cached -s slot2\n    /usr/local/bin/bic-cached -f slot2 > /dev/null 2>&1 &\n  fi\n\n  if [[ $(is_sb_bic_ready 3) == \"1\" ]]; then\n    /usr/local/bin/bic-cached -s slot3\n    /usr/local/bin/bic-cached -f slot3 > /dev/null 2>&1 &\n  fi\n\n  if [[ $(is_sb_bic_ready 4) == \"1\" ]]; then\n    /usr/local/bin/bic-cached -s slot4\n    /usr/local/bin/bic-cached -f slot4 > /dev/null 2>&1 &\n  fi\n}\n\necho -n \"Setup Caching for Bridge IC info..\"\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_sdr\nelif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_sdr\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"done.\"\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n. /usr/local/fbpackages/utils/ast-functions\n\nBOARD_ID=$(get_bmc_board_id)\nME_UTIL=\"/usr/local/bin/me-util\"\nFRUID_UTIL=\"/usr/local/bin/fruid-util\"\nFW_UTIL=\"/usr/bin/fw-util\"\nSLOT_NAME=$1\nINTERFACE=\"PECI_INTERFACE\"\nPCIE_INTERFACE=\"PECI_INTERFACE\"\n\nfunction is_numeric {\n  if [ $(echo \"$1\" | grep -cE \"^\\-?([[:xdigit:]]+)(\\.[[:xdigit:]]+)?$\") -gt 0 ]; then\n    return 1\n  else\n    return 0\n  fi\n}\n\ncase $SLOT_NAME in\n    slot1)\n      SLOT_NUM=1\n      ;;\n    slot2)\n      SLOT_NUM=2\n      ;;\n    slot3)\n      SLOT_NUM=3\n      ;;\n    slot4)\n      SLOT_NUM=4\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      if [ \"$BOARD_ID\" -eq 9 ]; then\n        echo \"Usage: $N {slot1}\"\n      else\n        echo \"Usage: $N {slot1|slot2|slot3|slot4}\"\n      fi\n      exit 1\n      ;;\nesac\n\n\nif [ \"$BOARD_ID\" -eq 9 ] && [ \"$SLOT_NAME\" != \"slot1\" ]; then\n  # class2 checking\n  echo \"$SLOT_NAME not supported\"\n  exit 1\nfi\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID=$$\nPID_FILE=\"/var/run/autodump$SLOT_NUM.pid\"\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# kill previous autodump if exist\nif [ ! -z \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  # Check if 2nd dump is running\n  if [ ! -z \"$(ps | grep '{autodump.sh}' | grep \"${SLOT_NAME}\" | grep \"second\\|dwr\")\" ]; then\n    echo \"$OLDPID\" > $PID_FILE\n    echo \"2nd DUMP or Demoted Warm Reset DUMP is running. exit.\"\n    exit 1\n  fi\n\n  LOG_FILE=\"/tmp/crashdump/\"\n  LOG_ARCHIVE=\"/mnt/data/acd_uncompleted_${SLOT_NAME}.tar.gz\"\n\n  tar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\n  rm -rf $LOG_FILE && \\\n\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 \"$OLDPID\"\n  ps | grep 'crashdump' | grep \"$SLOT_NAME\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\nfi\nunset OLDPID\n\n# Set crashdump timestamp\n# pal_is_crashdump_ongoing() need the crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\n/usr/bin/kv set fru${SLOT_NUM}_crashdump $((sys_runtime+1200))\n\nCRASHDUMP_FILE=\"/tmp/crashdump/\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/acd_crashdump_$SLOT_NAME.tar.gz\"\nLOG_MSG_PREFIX=\"\"\n\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\nPOWER_OFF=0\n\nwhile test $# -gt 1\ndo\n  case \"$2\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  --power_off)\n    POWER_OFF=1\n    ;;\n  *)\n    echo \"unknown argument $2\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  echo \"ACD Dump after System Reset or Demoted Warm Reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"ACD Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"ACD for $SLOT_NAME Started\"\nlogger -t \"ipmid\" -p daemon.crit \"ACD for FRU: $SLOT_NUM started\"\n\ncrashdump $SLOT_NUM\n\n# only second/dwr dump need to rename accordingly\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  # rename the archieve file based on whether dump in DWR mode or not\n  if [ \"$?\" == \"2\" ]; then\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/acd_crashdump_dwr_$SLOT_NAME.tar.gz\"\n    LOG_MSG_PREFIX=\"DWR \"\n  else\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/acd_crashdump_second_$SLOT_NAME.tar.gz\"\n    LOG_MSG_PREFIX=\"SECOND_DUMP \"\n  fi\nfi\n\ntar zcf $CRASHDUMP_LOG_ARCHIVE -C `dirname $CRASHDUMP_FILE` `basename $CRASHDUMP_FILE` && \\\nrm -rf $CRASHDUMP_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}ACD for FRU: $SLOT_NUM is generated at $CRASHDUMP_LOG_ARCHIVE\"\ncp -f \"$CRASHDUMP_LOG_ARCHIVE\" /tmp\necho \"ACD for $SLOT_NAME Completed\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"${LOG_MSG_PREFIX}ACD Dump Stored in $CRASHDUMP_LOG_ARCHIVE\"\n\nif [ \"$POWER_OFF\" = \"1\" ]; then\n  logger -t \"ipmid\" -p daemon.crit \"Dump completed, power off FRU: $SLOT_NUM\"\n  /usr/local/bin/power-util \"slot$SLOT_NUM\" off\nfi\n\nexit 0\n", "num_lines": 165}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nME_UTIL=\"/usr/local/bin/me-util\"\nPECI_UTIL=\"/usr/bin/bic-util\"\nCMD_DIR=\"/usr/local/fbpackages/crashdump\"\nINTERFACE=$3\nSENSOR_HISTORY=180\nSLOT=$1\n\n# read command from stdin\nfunction execute_via_me {\n  # if ME_UTIL cannot be executed, return\n  [ -x $ME_UTIL ] || \\\n    return\n\n  # Adapt command to ME-UTIL format\n  cat | \\\n    sed 's/^0x/0xb8 0x40 0x57 0x01 0x00 0x/g' $1 | \\\n      $ME_UTIL $SLOT --file /dev/stdin | \\\n        sed 's/^57 01 00 //g'\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    sed 's/^0x/0xe0 0x29 0x9c 0x9c 0x00 0x/g' $1 | \\\n      $PECI_UTIL $SLOT --file /dev/stdin | \\\n        sed 's/^9C 9C 00 //g'\n}\n\nfunction execute_cmd {\n  if [ \"$INTERFACE\" == \"ME_INTERFACE\" ]; then\n    cat | execute_via_me\n  else\n    cat | execute_via_peci\n  fi\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  # BUS\n  RESULT=$((($1 & 0xFF) << 20))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15)))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12)))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0)))\n  printf \"0x%x 0x%x 0x%x 0x%x\" \\\n    $((RESULT & 0xFF)) \\\n    $(((RESULT >> 8) & 0xFF)) \\\n    $(((RESULT >> 16) & 0xFF)) \\\n    $(((RESULT >> 24) & 0xFF))\n  return 0\n}\n\nfunction print_bus_device {\n  MAX_FUN=0\n  MAX_DEV=0\n  BUS=$(printf \"0x%02x\" $1)\n  if [ \"$BUS\" == \"0x17\" ] || [ \"$BUS\" == \"0x65\" ]; then\n    MAX_FUN=1\n  elif [ \"$BUS\" == \"0x18\" ]; then\n    MAX_DEV=7\n  elif [ \"$BUS\" == \"0x66\" ]; then\n    MAX_DEV=3\n  fi\n  BUSM=$(($1 >> 4))\n  BUSL=$((($1 & 0xF) << 4))\n  for (( DEV=0; DEV<=$MAX_DEV; DEV++ )); do\n    DEVM=$((DEV >> 1))\n    DEVL=$(((DEV & 0x1) << 3))\n    for (( FUN=0; FUN<=$MAX_FUN; FUN++ )); do\n      printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x100 ~ 0x147\\\"\\n\" $1 $DEV $FUN\n      BYTE1=$(((DEVL | FUN) << 4 | 0x1))\n      BYTE2=$((BUSL | DEVM))\n      for REG in {0..68..4}; do\n        printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n      done\n      if [ \"$BUS\" == \"0x18\" ] || [ \"$BUS\" == \"0x66\" ]; then\n        printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x1B0 ~ 0x1BB\\\"\\n\" $1 $DEV $FUN\n        for REG in {176..184..4}; do\n          printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n        done\n      fi\n    done\n  done\n}\n\nfunction find_end_device {\n  echo \"Find Root Port Bus $1 Dev $2 Fun $3...\"\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr $1 $2 $3 0x18)\" | execute_cmd)\n  echo \"$RES\"\n  CC=$(echo $RES| awk '{print $1;}')\n  SECONDARY_BUS=0x$(echo $RES| awk '{print $3;}')\n  SUBORDINATE_BUS=0x$(echo $RES| awk '{print $4;}')\n  if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n    for (( BUS=$SECONDARY_BUS; BUS<=$SUBORDINATE_BUS; BUS++ )); do\n      printf \"End Device on Bus 0x%02x\\n\" $BUS\n      echo \"$(print_bus_device $BUS)\" | execute_cmd\n    done\n  fi\n}\n\nfunction pcie_dump {\n\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    cat $CMD_DIR/crashdump_pcie | execute_cmd\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    # CPU root port - Bus 0x16/0x64, Dev 0~3, Fun:0\n    # Root port buses\n    ROOT_BUSES=$(echo $RES | awk '{printf \"0x%s 0x%s\", $3, $4;}')\n    ROOT_BUS=$(echo $RES | awk '{printf \"0x%s\", $2;}')\n    echo ROOT_BUSES=$ROOT_BUSES\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        find_end_device $ROOT $DEV 0\n      done\n    done\n\n    # CPU root port - Bus 0,Dev 0, Fun:0\n    echo ROOT_BUS=$ROOT_BUS\n    find_end_device $ROOT_BUS 0 0\n\n    # PCH root port - Bus 0,Dev 0x1B, Fun:0\n    find_end_device $ROOT_BUS 0x1B 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:0\n    find_end_device $ROOT_BUS 0x1D 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:4\n    find_end_device $ROOT_BUS 0x1D 4\n  fi\n}\n\nfunction dwr_dump {\n\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  DWR=0x$(echo $RES| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nfunction print_dump_help {\n  echo \"$0 <slot#> coreid <INTERFACE> ==> for CPU CoreID\"\n  echo \"$0 <slot#> msr    <INTERFACE> ==> for CPU MSR\"\n  echo \"$0 <slot#> sensors            ==> for sensor history\"\n  echo \"$0 <slot#> threshold          ==> for sensor threshold\"\n  echo \"$0 <slot#> pcie   <INTERFACE> ==> for PCIe\"\n  echo \"$0 <slot#> dwr    <INTERFACE> ==> for DWR check\"\n  exit 1\n}\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -eq 2 ]; then\n  if [ \"$2\" != \"sensors\" ] && [ \"$2\" != \"threshold\" ]; then\n    print_dump_help\n  fi\nelif [ \"$#\" -eq 3 ]; then\n  if [ \"$2\" != \"coreid\" ] && [ \"$2\" != \"msr\" ] && [ \"$2\" != \"pcie\" ] && [ \"$2\" != \"dwr\" ]; then\n    print_dump_help\n  fi\n  if [ \"$INTERFACE\" != \"ME_INTERFACE\" ] && [ \"$INTERFACE\" != \"PECI_INTERFACE\" ]; then\n    print_dump_help     \n  fi\nelse\n  print_dump_help\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r $CMD_DIR/crashdump_coreid ] && \\\n      cat $CMD_DIR/crashdump_coreid | execute_cmd\nelif [ \"$2\" = \"msr\" ]; then\n  [ -r $CMD_DIR/crashdump_msr ] && \\\n      cat $CMD_DIR/crashdump_msr | execute_cmd\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util $1 --history $SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util bmc --history $SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util nic --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util $1 --threshold \\\n   && /usr/local/bin/sensor-util bmc --threshold \\\n   && /usr/local/bin/sensor-util nic --threshold\nelif [ \"$2\" = \"pcie\" ]; then\n  pcie_dump\nelif [ \"$2\" = \"dwr\" ]; then\n  dwr_dump\n  exit $?\nfi\n\nexit 0\n", "num_lines": 238}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\n\nKV_CMD=/usr/bin/kv\n\nfunction init_class1_fsc(){\n  sys_config=$(/usr/local/bin/show_sys_config | grep -i \"config:\" | awk -F \": \" '{print $3}')\n  target_fsc_config=\"\"\n  config_type=\"\"\n  last_config_type=\"\"\n  if [ \"$sys_config\" = \"A\" ]; then\n    config_type=\"1\"\n    target_fsc_config=\"/etc/FSC_CLASS1_PVT_type1.json\"\n  elif [ \"$sys_config\" = \"B\" ]; then\n    get_1ou_type\n    if [ \"$type_1ou\" = \"EDSFF_1U\" ]; then\n      echo \"use EDSFF_1U fan table\"\n      config_type=\"EDSFF_1U\"\n      target_fsc_config=\"/etc/FSC_CLASS1_DVT_EDSFF_1U.json\"\n    else\n      config_type=\"10\"\n      target_fsc_config=\"/etc/FSC_CLASS1_EVT_type10.json\"\n    fi\n  elif [ \"$sys_config\" = \"D\" ]; then\n    get_2ou_type\n    config_type=\"15\"\n    if ([ $type_2ou == \"0x00\" ] || [ $type_2ou == \"0x03\" ]); then\n      echo \"use Config D GPv3 fan table\"\n      target_fsc_config=\"/etc/FSC_CLASS1_CONFIG_D_GPV3.json\"\n    elif [ \"$type_2ou\" == \"0x06\" ]; then\n      # boot with last fan table, check and reload it after recieve host post complete code\n      last_config_type=\"$($KV_CMD get sled_system_conf persistent)\"\n      case \"$last_config_type\" in\n        \"Type_DPB\")\n          config_type=\"DPB\"\n          target_fsc_config=\"/etc/FSC_CLASS1_DVT_DP_HBA.json\"\n          ;;\n        \"Type_DPF\")\n          config_type=\"DPF\"\n          target_fsc_config=\"/etc/FSC_CLASS1_DP_FAVA.json\"\n          ;;\n        *)\n          config_type=\"DP\"\n          target_fsc_config=\"/etc/FSC_CLASS1_EVT_DP.json\"\n          ;;\n      esac\n      echo \"use $config_type fan table\"\n    else\n      target_fsc_config=\"/etc/FSC_CLASS1_type15.json\"\n    fi\n  else\n    config_type=\"15\"\n    target_fsc_config=\"/etc/FSC_CLASS1_type15.json\"\n  fi\n\n  cp ${target_fsc_config} ${default_fsc_config_path}\n  $KV_CMD set sled_system_conf \"Type_${config_type}\" persistent\n}\n\nfunction init_class2_fsc(){\n  cpld_bus_num=\"4\"\n  exp_board=$(get_2ou_board_type $cpld_bus_num)\n  if [ \"$exp_board\" == \"0x02\" ]; then # E1.S board\n    ln -s /etc/FSC_CLASS2_PVT_SPE_config.json ${default_fsc_config_path}\n    echo -n \"Type_8\" > /mnt/data/kv_store/sled_system_conf\n  elif [ \"$exp_board\" == \"0x04\" ]; then #CWC board\n    ln -s /etc/FSC_CLASS2_DVT_CWC.json ${default_fsc_config_path}\n    echo -n \"Type_17\" > /mnt/data/kv_store/sled_system_conf\n  else\n    ln -s /etc/FSC_CLASS2_EVT_config.json ${default_fsc_config_path}\n    echo -n \"Type_17\" > /mnt/data/kv_store/sled_system_conf\n  fi\n  \n}\n\n\nfunction get_1ou_type(){\n  for i in $(seq 1 4)\n  do\n    if [[ $(is_sb_bic_ready $i) == \"1\" ]]; then\n      output=$(bic-util slot$i 0xE0 2 0x9c 0x9c 0 0x5 0xe0 0xa0 0x9c 0x9c 0 | awk '{print $7\" \"$11}')\n      if [[ ${output} == \"00 07\" ]]; then\n        type_1ou=EDSFF_1U\n        break\n      elif [[ ${output} == \"C1 \" ]]; then\n        break\n      fi\n    fi\n  done\n}\n\nfunction get_2ou_type(){\n  for i in {1..4..2}\n  do\n    I2C_NUM=$(($i+3))\n    type_2ou=$(get_2ou_board_type $I2C_NUM)\n    if [ $type_2ou != \"0xff\" ]; then\n      break\n    fi\n  done\n}\n\nfunction start_sled_fsc() {\n  echo \"Setup fan speed...\"\n  /usr/local/bin/fan-util --set 70\n\n  bmc_location=$(get_bmc_board_id)\n  if [ $bmc_location -eq 9 ]; then\n    #The BMC of class2\n    init_class2_fsc\n  elif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n    #The BMC of class1\n    init_class1_fsc\n  else\n    echo -n \"Is board id correct(id=$bmc_location)?...\"\n    exit -1\n  fi\n\n  echo -n \"Setup fscd for fby3...\"\n  runsv /etc/sv/fscd > /dev/null 2>&1 &\n  echo \"Done.\"\n}\n\nfunction reload_sled_fsc() {\n  bmc_location=$(get_bmc_board_id)\n  if [ $bmc_location -eq 9 ]; then\n    exp_board=$(get_2ou_board_type 4)\n\n    if [ $exp_board == \"0x04\" ]; then\n      run_fscd=true\n    else\n      #The BMC of class2 need to check the present status from BB BIC\n      slot1_prsnt=$(bic-util slot1 0xe0 0x2 0x9c 0x9c 0x0 0x10 0xe0 0x41 0x9c 0x9c 0x0 0x0 27 | awk '{print $12}')\n      slot3_prsnt=$(bic-util slot1 0xe0 0x2 0x9c 0x9c 0x0 0x10 0xe0 0x41 0x9c 0x9c 0x0 0x0 28 | awk '{print $12}')\n      if [ \"$slot1_prsnt\" == \"01\" ] || [ \"$slot3_prsnt\" == \"01\" ]; then\n        run_fscd=false\n      else\n        run_fscd=true\n      fi\n    fi\n  else\n    cnt=`get_all_server_prsnt`\n    run_fscd=false\n  \n    #Config A and B or Config D\n    sys_config=$(cat /mnt/data/kv_store/sled_system_conf)\n    if [[ \"$sys_config\" =~ ^(Type_(1|10|EDSFF_1U))$ ]]; then\n      if [ $cnt -eq 4 ]; then\n        run_fscd=true\n      fi\n    else\n      if [ $cnt -eq 2 ]; then\n        run_fscd=true\n      elif [ $cnt -eq 1 ]; then\n        # DP system only has one slot\n        if [ \"$sys_config\" = \"Type_DP\" ] || [ \"$sys_config\" = \"Type_DPB\" ] || [ \"$sys_config\" = \"Type_DPF\" ]; then\n          run_fscd=true\n        fi\n      fi\n    fi\n  fi\n\n  fscd_status=$(cat /etc/sv/fscd/supervise/stat)\n  if [ $run_fscd = false ]; then\n    if [ \"$fscd_status\" == \"run\" ]; then\n      sleep 1 && /usr/bin/sv stop fscd\n      echo \"slot is pulled out, stop fscd.\"\n      /usr/local/bin/fan-util --set 100\n    else\n      echo \"fscd is already stopped.\"\n    fi\n  else\n    #if fscd has been running, there is no need to restart\n    if ! [ \"$fscd_status\" == \"run\" ]; then\n      sleep 1 && /usr/bin/sv restart fscd\n    fi\n  fi\n}\n\ncase \"$1\" in\n  start)\n    start_sled_fsc\n    #if one of the blades is not present, stop fscd\n    reload_sled_fsc\n  ;;\n\n  reload)\n    #if one of the blades is pulled out, stop fscd\n    reload_sled_fsc\n  ;;\n\n  *)\n    echo \"Usage: /etc/init.d/setup-fan.sh {start|reload}\"\n  ;;\nesac\n\nexit 0\n", "num_lines": 228}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\nSLOTS=\n\nfunction init_class2_gpiod() {\n  SLOTS=\"$SLOTS slot1\"\n}\n\nfunction init_class1_gpiod() {\n  if [[ $(is_server_prsnt 1) == \"1\" ]]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n\n  if [[ $(is_server_prsnt 2) == \"1\" ]]; then\n    SLOTS=\"$SLOTS slot2\"\n  fi\n\n  if [[ $(is_server_prsnt 3) == \"1\" ]]; then\n    SLOTS=\"$SLOTS slot3\"\n  fi\n\n  if [[ $(is_server_prsnt 4) == \"1\" ]]; then\n    SLOTS=\"$SLOTS slot4\"\n  fi\n}\n\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_gpiod\nelif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_gpiod\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\nexec /usr/local/bin/gpiod $SLOTS \n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for fby3... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          server-init\n# Required-Start:\n# Required-Stop:\n# Default-Start:\n# Default-Stop:\n# Short-Description: Provides a service to reinitialize the server\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# stop the service first\nsv stop gpiod\nsv stop sensord\n\nslot_num=$1\nPID=$$\nPID_FILE=\"/var/run/server-init.${slot_num}.pid\"\nbus=$((slot_num-1))\n\n# check if the script is running\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set the current pid\necho $PID > $PID_FILE\n\n# kill the previous running script if it is existed\nif [ ! -z \"$OLDPID\" ] && (grep \"server-init\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  ps | grep 'bic-cached' | grep \"slot${slot_num}\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\n  ps | grep 'power-util' | grep \"slot${slot_num}\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\n  ps | grep 'setup-fan' | awk '{print $1}'| xargs kill -s 9 &> /dev/null\nfi\nunset OLDPID\n\nif [ $(is_server_prsnt $slot_num) == \"0\" ]; then\n  disable_server_12V_power $slot_num\n  gpio_set FM_BMC_SLOT${slot_num}_ISOLATED_EN_R 0\n  rm -f /tmp/*fruid_slot${slot_num}*\n  rm -f /tmp/*sdr_slot${slot_num}*\n  rm -f /tmp/cache_store/slot${slot_num}_vr*\n  rm -f /tmp/cache_store/fru${slot_num}_2ou_board_type\n  rm -f /tmp/cache_store/slot${slot_num}_is_m2_exp_prsnt\n  rm -f /tmp/cache_store/slot${slot_num}_1ou_card_type\n  for pcie_info_file in $(ls /mnt/data/kv_store/sys_config/fru${slot_num}_pcie_*)\n  do\n    /usr/bin/kv del ${pcie_info_file:19} persistent > /dev/null 2>&1\n  done\n  set_nic_power\n\n  # reload fscd\n  /etc/init.d/setup-fan.sh reload\nelse\n  /usr/bin/sv start ipmbd_${bus} > /dev/null 2>&1\n  /usr/local/bin/power-util \"slot${slot_num}\" 12V-on\n  /usr/local/bin/bic-cached -s \"slot${slot_num}\"\n  /usr/local/bin/bic-cached -f \"slot${slot_num}\"\n  /usr/bin/fw-util \"slot${slot_num}\" --version > /dev/null\n  /etc/init.d/setup-sic.sh \"slot${slot_num}\" > /dev/null\n\n  # reload fscd\n  /etc/init.d/setup-fan.sh start\nfi\n\n# start the services again\nsv start gpiod\nsv start sensord\n", "num_lines": 90}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start gpiointrd daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpiointrd for fby3...\"\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\n\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  #gpiointrd only supports the hot service and the hot service is not supported on class 2.\n  #stop it\n  sv stop gpiointrd\nfi\n\necho \"done.\"\n\n\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 2\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 3 \n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 4\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 5 \n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n\n. /usr/local/fbpackages/utils/ast-functions\n\nfunction init_class1_ipmb(){\n  for slot_num in $(seq 1 4); do\n    bus=$((slot_num-1))\n    echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-${bus}/new_device\n    runsv /etc/sv/ipmbd_${bus} > /dev/null 2>&1 &\n    slot_present=$(gpio_get PRSNT_MB_BMC_SLOT${slot_num}_BB_N)\n    if [[ \"$slot_present\" == \"1\" ]]; then\n      sv stop ipmbd_${bus}\n      disable_server_12V_power ${slot_num}\n    else\n      enable_server_i2c_bus ${slot_num}\n    fi\n  done\n\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n\n  # add BMC slave address to NIC I2C bus for MCTP\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device\n}\n\nfunction init_class2_ipmb(){\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-0/new_device\n  runsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\n\n  # add BMC slave address to NIC I2C bus for MCTP\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device\n}\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\nulimit -q 1024000\n\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_ipmb\nelif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_ipmb\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"Done.\"\n", "num_lines": 79}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\nBOARD_ID=$(get_bmc_board_id)\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\n\nif [ $BOARD_ID -eq 14 ] || [ $BOARD_ID -eq 7 ]; then\n  runsv /etc/sv/mTerm2 > /dev/null 2>&1 &\n  runsv /etc/sv/mTerm3 > /dev/null 2>&1 &\n  runsv /etc/sv/mTerm4 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#This is workaround for IPV4 lost There is slim chance ipv4 lost when AC cycle.\n#DHCP Client can't get OFFER package from server.\n#This script is for reinitial ipv4 to prevnet it lost.\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ncheck_eth0_ipv4() {\n  for i in {1..10};\n  do\n    ip=$(ifconfig eth0 |grep \"inet addr\")\n    if [[ -z \"$ip\" ]]; then\n      pid=$(cat /var/run/dhclient.eth0.pid)\n      kill $pid\n      dhclient -d -pf /var/run/dhclient.eth0.pid eth0 > /dev/null 2>&1 &\n      sleep 3\n    else\n      break;\n    fi\n  done\n}\n\necho \"check eth0 ipv4...\"\ncheck_eth0_ipv4 &\n", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config() {\n  TO_PWR_ON=-1\n\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/slot${1}_por_cfg\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    POR=`cat ${KEYDIR}/slot${1}_por_cfg`\n\n    if [ $POR == \"on\" ]; then\n      TO_PWR_ON=1;\n    elif [ $POR == \"lps\" ]; then\n      # Check if the file/key doesn't exist\n      if [ ! -f \"${KEYDIR}/pwr_server${1}_last_state\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        LS=`cat ${KEYDIR}/pwr_server${1}_last_state`\n        if [ $LS == \"on\" ]; then\n          TO_PWR_ON=1;\n        fi\n      fi\n    fi\n  fi\n}\n\nfunction init_4u_gpv3_bic() {\n  GPV3_PRESENT=$(/usr/sbin/i2cget -y 4 0x50 0x04)\n\n  if [ $((GPV3_PRESENT & 0x03)) -eq 0 ]; then\n    retry=3\n\n    while [ $retry -gt 0 ]; do\n      res=$(/usr/bin/bic-util slot1-2U-top 0xe0 0x70 0x9c 0x9c 0x0 0x1 0x0)\n\n      if [[ ${res:0:8} == \"9C 9C 00\" ]]; then\n        logger \"Init top gpv3 position\"\n        break\n      else\n        retry=$((retry - 1))\n        sleep 1\n      fi\n    done\n\n    if [ $retry -eq 0 ]; then\n      logger \"Fail to init top gpv3 position\"\n    fi\n  fi\n\n  if [ $((GPV3_PRESENT & 0x0C)) -eq 0 ]; then\n    retry=3\n\n    while [ $retry -gt 0 ]; do\n      res=$(/usr/bin/bic-util slot1-2U-bot 0xe0 0x70 0x9c 0x9c 0x0 0x1 0x1)\n\n      if [[ ${res:0:8} == \"9C 9C 00\" ]]; then\n        logger \"Init bot gpv3 position\"\n        break\n      else\n        retry=$((retry - 1))\n        sleep 1\n      fi\n    done\n\n    if [ $retry -eq 0 ]; then\n      logger \"Fail to init bot gpv3 position\"\n    fi\n  fi\n}\n\nfunction init_2u_gpv3_bic() {\n  retry=3\n  while [ $retry -gt 0 ]; do\n    res=$(/usr/bin/bic-util slot1 0xe0 0x2 0x9c 0x9c 0x0 0x15 0xe0 0x70 0x9c 0x9c 0x0 0x1 0xff)\n\n    if [[ ${res:0:29} == \"9C 9C 00 15 E4 70 00 9C 9C 00\" ]]; then\n      logger \"Init gpv3 position\"\n      break\n    else\n      retry=$((retry - 1))\n      sleep 1\n    fi\n  done\n\n  if [ $retry -eq 0 ]; then\n    logger \"Fail to init gpv3 position\"\n  fi\n}\n\nfunction init_class2_server() {\n  EXP_BOARD_TYPE=$(get_2ou_board_type 4)\n  if [ $EXP_BOARD_TYPE == \"0x04\" ]; then\n    init_4u_gpv3_bic\n  elif [ $EXP_BOARD_TYPE == \"0x00\" ] || [ $EXP_BOARD_TYPE == \"0x03\" ]; then\n    init_2u_gpv3_bic\n  fi\n\n  if [ $(is_bmc_por) -eq 1 ]; then\n    devmem_clear_bit $(scu_addr 9c) 17\n\n    check_por_config 1\n    if [ $TO_PWR_ON -eq 1 ] ; then\n      power-util slot1 on\n    fi\n  fi\n\n  show_sys_config -r > /dev/null\n}\n\nfunction init_class1_server() {\n  # Check whether it is fresh power on reset\n  if [ $(is_bmc_por) -eq 1 ]; then\n    # Disable clearing of PWM block on WDT SoC Reset\n    devmem_clear_bit $(scu_addr 9c) 17\n\n    check_por_config 1\n    if [ $(is_sb_bic_ready 1) == \"1\" ] && [ $TO_PWR_ON -eq 1 ] ; then\n      power-util slot1 on\n    fi\n\n    check_por_config 2\n    if [ $(is_sb_bic_ready 2) == \"1\" ] && [ $TO_PWR_ON -eq 1 ] ; then\n      power-util slot2 on\n    fi\n\n    check_por_config 3\n    if [ $(is_sb_bic_ready 3) == \"1\" ] && [ $TO_PWR_ON -eq 1 ] ; then\n      power-util slot3 on\n    fi\n\n    check_por_config 4\n    if [ $(is_sb_bic_ready 4) == \"1\" ] && [ $TO_PWR_ON -eq 1 ] ; then\n      power-util slot4 on\n    fi\n  fi\n}\n\nif ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n  date -s \"2018-01-01 00:00:00\"\nfi\n\n/usr/local/bin/sync_date.sh\n\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_server\nelif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_server\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n", "num_lines": 188}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\n\nHSC_DET_ADM1278=0\nHSC_DET_LTC4282=1\nHSC_DET_MP5990=2\nHSC_DET_ADM1276=3\n\nfunction create_new_dev() {\n  local dev_name=$1\n  local addr=$2\n  local bus=$3\n\n  echo $dev_name $addr > /sys/class/i2c-dev/i2c-${bus}/device/new_device\n}\n\nfunction init_class1_dev(){\n  hsc_detect=$(get_hsc_bb_detect)\n  VENDOR_TI=\"0x55\"\n  KEY_TEMP_VENDOR=\"tmp_vendor\"\n\n  if [ $hsc_detect -eq $HSC_DET_ADM1278 ]; then\n    for i in $(seq 1 5)\n    do\n      #enable the register of the temperature of hsc\n      /usr/sbin/i2cset -y 11 0x40 0xd4 0x1c 0x3f i 2> /dev/null\n      RET=$?\n      if [ \"$RET\" = 0 ]; then\n        break\n      fi\n    done\n  elif [ $hsc_detect -eq $HSC_DET_LTC4282 ] || [ $hsc_detect -eq $HSC_DET_ADM1276 ]; then\n    if [ $hsc_detect -eq $HSC_DET_LTC4282 ]; then\n      create_new_dev \"ltc4282\" 0x40 11\n    fi\n    vendor=$(/usr/sbin/i2cget -f -y 12 0x4c 0xfe)\n    if [ \"$vendor\" = \"$VENDOR_TI\" ]; then\n      /usr/bin/kv set $KEY_TEMP_VENDOR \"TI\"\n      echo \"$vendor\"\n      create_new_dev \"tmp401\" 0x4c 12\n    else\n      echo \"$vendor\"\n      /usr/bin/kv set $KEY_TEMP_VENDOR \"non-TI\"\n      create_new_dev \"lm90\" 0x4c 12\n    fi\n  fi\n\n  #create the device of the inlet/outlet temp.\n  create_new_dev \"lm75\" 0x4e 12\n  create_new_dev \"lm75\" 0x4f 12\n\n  #create the device of bmc/bb fru.\n  create_new_dev \"24c128\" 0x51 11 \n  create_new_dev \"24c128\" 0x54 11\n\n  local VENDOR_MPS=\"0x4d5053\"\n  local chip=\"\"\n\n  #create the device of medusa board\n  vendor=$(/usr/sbin/i2cget -y 11 0x44 0x99 i 2> /dev/null | tail -n 1)\n  if [ \"$vendor\" == \"$VENDOR_MPS\" ]; then\n    chip=\"mp5920\"\n  else\n    chip=\"ltc4282\"\n  fi\n\n  create_new_dev $chip 0x44 11\n\n  # /mnt/data/kv_store checking, and create one if not exist\n  if [ ! -d /mnt/data/kv_store ]; then\n    /bin/mkdir -p /mnt/data/kv_store\n  fi\n  echo -n $chip > /mnt/data/kv_store/bb_hsc_conf\n\n  # check nic power to see if it's need to be set to standby mode\n  set_nic_power\n}\n\nfunction init_class2_dev(){\n  #create the device of the outlet temp. \n  create_new_dev \"lm75\" 0x4f 2\n\n  #create the device of bmc/nic fru.\n  create_new_dev \"24c128\" 0x51 10\n  create_new_dev \"24c128\" 0x54 10\n}\n\n#create the device of mezz card\ncreate_new_dev \"tmp421\" 0x1f 8\ncreate_new_dev \"24c32\" 0x50 8\n\necho -n \"Setup devs for fby3...\"\n\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_dev\nelif [ $bmc_location -eq 14 ] || [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_dev\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"Done.\"\n", "num_lines": 124}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Set up GPIO pins.....\"\n\n# GPIOF0-BOARD_BMC_ID0_R\n# GPIOF1-BOARD_BMC_ID1_R\n# GPIOF2-BOARD_BMC_ID2_R\n# GPIOF3-BOARD_BMC_ID3_R\ndevmem_clear_bit $(scu_addr 80) 24\ndevmem_clear_bit $(scu_addr 80) 25\ndevmem_clear_bit $(scu_addr 80) 26\ndevmem_clear_bit $(scu_addr 80) 27\ndevmem_clear_bit $(scu_addr 90) 30\ngpio_export BOARD_BMC_ID0_R GPIOF0\ngpio_export BOARD_BMC_ID1_R GPIOF1\ngpio_export BOARD_BMC_ID2_R GPIOF2\ngpio_export BOARD_BMC_ID3_R GPIOF3\n\nBOARD_ID=$(get_bmc_board_id)\n\n# GPIOA0-BMC_READY_R\ndevmem_clear_bit $(scu_addr 80) 0\ngpio_export BMC_READY_R GPIOA0\ngpio_set BMC_READY_R 0\n\n# GPIOA3-FM_NIC_WAKE_BMC_N\ndevmem_clear_bit $(scu_addr 80) 3\ngpio_export FM_NIC_WAKE_BMC_N GPIOA3\n\n# GPIOE0-P3V3_NIC_FAULT_N\n# GPIOE1-NIC_POWER_BMC_EN_R\n# GPIOE2-P12V_NIC_FAULT_N\n# GPIOE5-EMMC_RST_N_R\ndevmem_clear_bit $(scu_addr 80) 16\ndevmem_clear_bit $(scu_addr 80) 17\ndevmem_clear_bit $(scu_addr 80) 18\ndevmem_clear_bit $(scu_addr 80) 21\ndevmem_clear_bit $(scu_addr 8C) 12\ndevmem_clear_bit $(scu_addr 8C) 13\ndevmem_clear_bit $(scu_addr 8C) 14\ngpio_export P3V3_NIC_FAULT_N GPIOE0\ngpio_export NIC_POWER_BMC_EN_R GPIOE1\ngpio_export P12V_NIC_FAULT_N GPIOE2\ngpio_export EMMC_RST_N_R GPIOE5\ngpio_set NIC_POWER_BMC_EN_R 1\ngpio_set EMMC_RST_N_R 1\n\n# GPIOF4-SMB_RST_PRIMARY_BMC_N_R\ndevmem_clear_bit $(scu_addr 80) 28\ngpio_export SMB_RST_PRIMARY_BMC_N_R GPIOF4\n\n# GPIOG3-SMB_RST_SECONDARY_BMC_N_R\ndevmem_clear_bit $(scu_addr 84) 3\ngpio_export SMB_RST_SECONDARY_BMC_N_R GPIOG3\n\n# GPIOM4-FM_PWRBRK_PRIMARY_R\ndevmem_clear_bit $(scu_addr 84) 28\ngpio_export FM_PWRBRK_PRIMARY_R GPIOM4\ngpio_set FM_PWRBRK_PRIMARY_R 0\n\n# GPIOM5-OCP_NIC_PRSNT_BMC_N\ndevmem_clear_bit $(scu_addr 84) 29\ngpio_export OCP_NIC_PRSNT_BMC_N GPIOM5\n\n# GPIOQ7-FM_BMC_TPM_PRSNT_N\ndevmem_clear_bit $(scu_addr 2C) 29\ngpio_export FM_BMC_TPM_PRSNT_N GPIOQ7\n\n# GPIOAB0-PWRGD_NIC_BMC\ndevmem_clear_bit $(scu_addr A8) 0\ngpio_export PWRGD_NIC_BMC GPIOAB0\n\n# GPIOAB3-RST_BMC_WDRST2_R\ndevmem_set_bit $(scu_addr A8) 3\ngpio_export RST_BMC_WDRST2_R GPIOAB3\n\n# GPIOAC4-EMMC_PRESENT_N\ndevmem_clear_bit $(scu_addr AC) 4\ngpio_export EMMC_PRESENT_N GPIOAC4\n\n###NIC EXP BMC###\nif [ $BOARD_ID -eq 9 ]; then\n  # GPIOB0-SMB_MUX_ALT_N\n  gpio_export SMB_MUX_ALT_N GPIOB0\n\n  # GPIOS0-PWROK_STBY_BMC\n  devmem_clear_bit $(scu_addr 8C) 0\n  gpio_export PWROK_STBY_BMC GPIOS0\n\n  # GPIOZ0-FM_BMC_ISOLATED_EN_R\n  # GPIOZ1-FM_BMC_ISOLATED_UART_EN_R\n  devmem_clear_bit $(scu_addr A4) 16\n  devmem_clear_bit $(scu_addr A4) 17\n  gpio_export FM_BMC_ISOLATED_EN_R GPIOZ0\n  gpio_export FM_BMC_ISOLATED_UART_EN_R GPIOZ1\n  gpio_set FM_BMC_ISOLATED_EN_R 1\n  gpio_set FM_BMC_ISOLATED_UART_EN_R 0\n\n###Baseboard BMC###\nelif [ $BOARD_ID -eq 14 ] || [ $BOARD_ID -eq 7 ]; then\n  # GPIOA1-SMB_HOTSWAP_BMC_ALERT_N_R\n  devmem_clear_bit $(scu_addr 80) 1\n  gpio_export SMB_HOTSWAP_BMC_ALERT_N_R GPIOA1\n\n  # GPIOA2-FM_HSC_BMC_FAULT_N_R\n  devmem_clear_bit $(scu_addr 80) 15\n  gpio_export FM_HSC_BMC_FAULT_N_R GPIOA2\n\n  # GPIOB0-SMB_BMC_SLOT1_ALT_N\n  # GPIOB1-SMB_BMC_SLOT2_ALT_N\n  # GPIOB2-SMB_BMC_SLOT3_ALT_N\n  # GPIOB3-SMB_BMC_SLOT4_ALT_N\n  gpio_export SMB_BMC_SLOT1_ALT_N GPIOB0\n  gpio_export SMB_BMC_SLOT2_ALT_N GPIOB1\n  gpio_export SMB_BMC_SLOT3_ALT_N GPIOB2\n  gpio_export SMB_BMC_SLOT4_ALT_N GPIOB3\n\n  # GPIOB4-PRSNT_MB_BMC_SLOT1_BB_N\n  # GPIOB5-PRSNT_MB_BMC_SLOT2_BB_N\n  # GPIOB6-PRSNT_MB_BMC_SLOT3_BB_N\n  # GPIOB7-PRSNT_MB_BMC_SLOT4_BB_N\n  devmem_clear_bit $(scu_addr 80) 13\n  devmem_clear_bit $(scu_addr 80) 14\n  gpio_export PRSNT_MB_BMC_SLOT1_BB_N GPIOB4\n  gpio_export PRSNT_MB_BMC_SLOT2_BB_N GPIOB5\n  gpio_export PRSNT_MB_BMC_SLOT3_BB_N GPIOB6\n  gpio_export PRSNT_MB_BMC_SLOT4_BB_N GPIOB7\n\n  # GPIOE3-ADAPTER_BUTTON_BMC_CO_N_R\n  # GPIOE4-RST_BMC_USB_HUB_N_R\n  devmem_clear_bit $(scu_addr 80) 19\n  devmem_clear_bit $(scu_addr 80) 20\n  gpio_export ADAPTER_BUTTON_BMC_CO_N_R GPIOE3\n  gpio_export RST_BMC_USB_HUB_N_R GPIOE4\n  gpio_set RST_BMC_USB_HUB_N_R 1\n\n  # GPIOG4-HSC_BB_BMC_DETECT2\n  # GPIOG6-HSC_BB_BMC_DETECT1\n  devmem_clear_bit $(scu_addr 84) 4\n  devmem_clear_bit $(scu_addr 84) 6\n  devmem_clear_bit $(scu_addr 94) 12\n  gpio_export HSC_BB_BMC_DETECT2 GPIOG4\n  gpio_export HSC_BB_BMC_DETECT1 GPIOG6\n\n  # GPIOI5-HSC_BB_BMC_DETECT0\n  gpio_export HSC_BB_BMC_DETECT0 GPIOI5\n\n  # GPIOI0-FAN0_BMC_CPLD_EN_R\n  # GPIOI1-FAN1_BMC_CPLD_EN_R\n  # GPIOI2-FAN2_BMC_CPLD_EN_R\n  # GPIOI3-FAN3_BMC_CPLD_EN_R\n  devmem_clear_bit $(scu_addr 90) 6\n  gpio_export FAN0_BMC_CPLD_EN_R GPIOI0\n  gpio_export FAN1_BMC_CPLD_EN_R GPIOI1\n  gpio_export FAN2_BMC_CPLD_EN_R GPIOI2\n  gpio_export FAN3_BMC_CPLD_EN_R GPIOI3\n  gpio_set FAN0_BMC_CPLD_EN_R 1\n  gpio_set FAN1_BMC_CPLD_EN_R 1\n  gpio_set FAN2_BMC_CPLD_EN_R 1\n  gpio_set FAN3_BMC_CPLD_EN_R 1\n\n  # GPIOJ4-RST_PCIE_RESET_SLOT1_N\n  # GPIOJ5-RST_PCIE_RESET_SLOT2_N\n  # GPIOJ6-RST_PCIE_RESET_SLOT3_N\n  # GPIOJ7-RST_PCIE_RESET_SLOT4_N\n  devmem_clear_bit $(scu_addr 84) 12\n  devmem_clear_bit $(scu_addr 84) 13\n  devmem_clear_bit $(scu_addr 84) 14\n  devmem_clear_bit $(scu_addr 84) 15\n  devmem_clear_bit $(scu_addr 94) 8\n  devmem_clear_bit $(scu_addr 94) 9\n  gpio_export RST_PCIE_RESET_SLOT1_N GPIOJ4\n  gpio_export RST_PCIE_RESET_SLOT2_N GPIOJ5\n  gpio_export RST_PCIE_RESET_SLOT3_N GPIOJ6\n  gpio_export RST_PCIE_RESET_SLOT4_N GPIOJ7\n\n  # GPIOL0-AC_ON_OFF_BTN_SLOT1_N\n  # GPIOL1-AC_ON_OFF_BTN_BMC_SLOT2_N_R\n  # GPIOL2-AC_ON_OFF_BTN_SLOT3_N\n  # GPIOL3-AC_ON_OFF_BTN_BMC_SLOT4_N_R\n  devmem_clear_bit $(scu_addr 84) 16\n  devmem_clear_bit $(scu_addr 84) 17\n  devmem_clear_bit $(scu_addr 84) 18\n  devmem_clear_bit $(scu_addr 84) 19\n  gpio_export AC_ON_OFF_BTN_SLOT1_N GPIOL0\n  gpio_export AC_ON_OFF_BTN_SLOT2_N GPIOL1\n  gpio_export AC_ON_OFF_BTN_SLOT3_N GPIOL2\n  gpio_export AC_ON_OFF_BTN_SLOT4_N GPIOL3\n\n  # GPIOL4-FAST_PROCHOT_BMC_N_R\n  devmem_clear_bit $(scu_addr 84) 20\n  gpio_export FAST_PROCHOT_BMC_N_R GPIOL4\n\n  # GPIOL5-USB_BMC_EN_R\n  devmem_clear_bit $(scu_addr 84) 21\n  gpio_export USB_BMC_EN_R GPIOL5\n  gpio_set USB_BMC_EN_R 1\n\n  # GPIOM0-HSC_FAULT_SLOT1_N\n  # GPIOM1-HSC_FAULT_BMC_SLOT2_N_R\n  # GPIOM2-HSC_FAULT_SLOT3_N\n  # GPIOM3-HSC_FAULT_BMC_SLOT4_N_R\n  devmem_clear_bit $(scu_addr 84) 24\n  devmem_clear_bit $(scu_addr 84) 25\n  devmem_clear_bit $(scu_addr 84) 26\n  devmem_clear_bit $(scu_addr 84) 27\n  gpio_export HSC_FAULT_SLOT1_N GPIOM0\n  gpio_export HSC_FAULT_BMC_SLOT2_N_R GPIOM1\n  gpio_export HSC_FAULT_SLOT3_N GPIOM2\n  gpio_export HSC_FAULT_BMC_SLOT4_N_R GPIOM3\n\n  # GPION4-DUAL_FAN0_DETECT_BMC_N_R\n  # GPION5-DUAL_FAN1_DETECT_BMC_N_R\n  devmem_clear_bit $(scu_addr 88) 4\n  devmem_clear_bit $(scu_addr 88) 5\n  gpio_export DUAL_FAN0_DETECT_BMC_N_R GPION4\n  gpio_export DUAL_FAN1_DETECT_BMC_N_R GPION5\n\n  # GPIOP0-SLOT1_ID0_DETECT_BMC_N\n  # GPIOP1-SLOT1_ID1_DETECT_BMC_N\n  # GPIOP2-SLOT2_ID0_DETECT_BMC_N\n  # GPIOP3-SLOT2_ID1_DETECT_BMC_N\n  # GPIOP4-SLOT3_ID0_DETECT_BMC_N\n  # GPIOP5-SLOT3_ID1_DETECT_BMC_N\n  # GPIOP6-SLOT4_ID0_DETECT_BMC_N\n  # GPIOP7-SLOT4_ID1_DETECT_BMC_N\n  devmem_clear_bit $(scu_addr 88) 16\n  devmem_clear_bit $(scu_addr 88) 17\n  devmem_clear_bit $(scu_addr 88) 18\n  devmem_clear_bit $(scu_addr 88) 19\n  devmem_clear_bit $(scu_addr 88) 20\n  devmem_clear_bit $(scu_addr 88) 21\n  devmem_clear_bit $(scu_addr 88) 22\n  devmem_clear_bit $(scu_addr 88) 23\n  gpio_export SLOT1_ID0_DETECT_BMC_N GPIOP0\n  gpio_export SLOT1_ID1_DETECT_BMC_N GPIOP1\n  gpio_export SLOT2_ID0_DETECT_BMC_N GPIOP2\n  gpio_export SLOT2_ID1_DETECT_BMC_N GPIOP3\n  gpio_export SLOT3_ID0_DETECT_BMC_N GPIOP4\n  gpio_export SLOT3_ID1_DETECT_BMC_N GPIOP5\n  gpio_export SLOT4_ID0_DETECT_BMC_N GPIOP6\n  gpio_export SLOT4_ID1_DETECT_BMC_N GPIOP7\n\n  # GPIOQ6-USB_OC_N\n  devmem_clear_bit $(scu_addr 2C) 1\n  gpio_export USB_OC_N GPIOQ6\n\n  # GPIOS0-PWROK_STBY_BMC_SLOT1\n  # GPIOS1-PWROK_STBY_BMC_SLOT2\n  # GPIOS2-PWROK_STBY_BMC_SLOT3\n  # GPIOS3-PWROK_STBY_BMC_SLOT4\n  devmem_clear_bit $(scu_addr 8C) 0\n  devmem_clear_bit $(scu_addr 8C) 1\n  devmem_clear_bit $(scu_addr 8C) 2\n  devmem_clear_bit $(scu_addr 8C) 3\n  gpio_export PWROK_STBY_BMC_SLOT1 GPIOS0\n  gpio_export PWROK_STBY_BMC_SLOT2 GPIOS1\n  gpio_export PWROK_STBY_BMC_SLOT3 GPIOS2\n  gpio_export PWROK_STBY_BMC_SLOT4 GPIOS3\n\n  # GPIOZ0-FM_BMC_SLOT1_ISOLATED_EN_R\n  # GPIOZ1-FM_BMC_SLOT2_ISOLATED_EN_R\n  # GPIOZ2-FM_BMC_SLOT3_ISOLATED_EN_R\n  # GPIOZ3-FM_BMC_SLOT4_ISOLATED_EN_R\n  devmem_clear_bit $(scu_addr A4) 16\n  devmem_clear_bit $(scu_addr A4) 17\n  devmem_clear_bit $(scu_addr A4) 18\n  devmem_clear_bit $(scu_addr A4) 19\n  gpio_export FM_BMC_SLOT1_ISOLATED_EN_R GPIOZ0\n  gpio_export FM_BMC_SLOT2_ISOLATED_EN_R GPIOZ1\n  gpio_export FM_BMC_SLOT3_ISOLATED_EN_R GPIOZ2\n  gpio_export FM_BMC_SLOT4_ISOLATED_EN_R GPIOZ3\n  gpio_set FM_BMC_SLOT1_ISOLATED_EN_R 0\n  gpio_set FM_BMC_SLOT2_ISOLATED_EN_R 0\n  gpio_set FM_BMC_SLOT3_ISOLATED_EN_R 0\n  gpio_set FM_BMC_SLOT4_ISOLATED_EN_R 0\n\n  # GPIOAB1-OCP_DEBUG_BMC_PRSNT_N\n  devmem_clear_bit $(scu_addr A8) 1\n  gpio_export OCP_DEBUG_BMC_PRSNT_N GPIOAB1\n\n  # These pins are added in DVT\n  # GPIOI4-FM_RESBTN_SLOT3_BMC_N\n  # GPIOI6-FM_RESBTN_SLOT4_BMC_N\n  # GPIOAC2-FM_RESBTN_SLOT1_BMC_N\n  # GPIOAC3-FM_RESBTN_SLOT2_BMC_N\n  devmem_clear_bit $(scu_addr AC) 2\n  devmem_clear_bit $(scu_addr AC) 3\n  gpio_export FM_RESBTN_SLOT3_BMC_N GPIOI4\n  gpio_export FM_RESBTN_SLOT4_BMC_N GPIOI6\n  gpio_export FM_RESBTN_SLOT1_BMC_N GPIOAC2\n  gpio_export FM_RESBTN_SLOT2_BMC_N GPIOAC3\n\nelse\n  echo \"Is board id correct(id=$BOARD_ID)?\"\nfi\n\ngpio_set BMC_READY_R 1\n", "num_lines": 340}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup Vishay IC 450/451\n# Required-Start:\n# Required-Stop:\n# Default-Start:\n# Default-Stop:\n# Short-Description: setup Vout and OCP dynamically \n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\nLOG=\"/tmp/setup-sic.log\"\nFEXP_INTF=\"0x05\"\nREXP_INTF=\"0x15\"\n\nfunction run_cmd() {\n  echo \"bic-util $1\" >> $LOG\n  /usr/bin/bic-util $1 >> $LOG\n}\n\nfunction init_vishay_ic(){\n  local slot=$1\n  local intf=$2\n\n  #SiC450\n  #OCP: 48A\n  run_cmd \"$slot 0xe0 0x02 0x9c 0x9c 0x0 $intf 0x18 0x52 0x13 0x28 0x00 0x46 0x60 0xf8\"\n\n  #Offset Vout 70mV\n  run_cmd \"$slot 0xe0 0x02 0x9c 0x9c 0x0 $intf 0x18 0x52 0x13 0x28 0x00 0x22 0x09 0x00\"\n\n  #Clear fault flag\n  run_cmd \"$slot 0xe0 0x02 0x9c 0x9c 0x0 $intf 0x18 0x52 0x13 0x28 0x00 0x03 0x0f\"\n\n  #SiC451\n  #Offset Vout 50mV\n  run_cmd \"$slot 0xe0 0x02 0x9c 0x9c 0x0 $intf 0x18 0x52 0x13 0x26 0x00 0x22 0x06 0x00\"\n\n  #Clear fault flag\n  run_cmd \"$slot 0xe0 0x02 0x9c 0x9c 0x0 $intf 0x18 0x52 0x13 0x26 0x00 0x03\"\n}\n\nfunction check_class1_config() {\n  local slot=$1\n  local val=$2\n  local i2c_num=$(get_cpld_bus ${slot:4:1})\n  local type_2ou=$(get_2ou_board_type $i2c_num)\n\n  if [[ $((val & 0x08)) = \"0\" && $type_2ou == \"0x06\" ]]; then\n    # waive 2OU present if 2OU type is dp riser card (0x06)\n    val=$((val | 0x08))\n  fi\n\n  if [ $val = 0 ]; then\n    echo \"2OU:\" >> $LOG\n    init_vishay_ic $slot $REXP_INTF \n    echo \"1OU:\" >> $LOG\n    init_vishay_ic $slot $FEXP_INTF \n  elif [ $val = 4 ]; then\n    echo \"1OU is not present\" >> $LOG\n    echo \"2OU:\" >> $LOG\n    init_vishay_ic $slot $REXP_INTF \n  elif [ $val = 8 ]; then\n    echo \"2OU is not present\" >> $LOG\n    echo \"1OU:\" >> $LOG\n    init_vishay_ic $slot $FEXP_INTF\n  else\n    echo \"1OU and 2OU are not present\" >> $LOG\n  fi\n}\n\nfunction init_class1_sic(){\n  for slot_num in $(seq 1 4); do\n    slot_present=$(gpio_get PRSNT_MB_BMC_SLOT${slot_num}_BB_N)\n    slot=\"slot${slot_num}\"\n    if [[ \"$slot_present\" == \"1\" ]]; then\n      echo \"$slot is not present\" >> $LOG\n    elif [[ $(is_sb_bic_ready ${slot_num}) == \"0\" ]]; then\n      echo \"$slot bic is not ready\" >> $LOG\n    else\n      val=$(get_m2_prsnt_sts $slot)\n      echo \"$slot\" >> $LOG\n      check_class1_config $slot $val\n    fi\n    echo \"\" >> $LOG\n  done\n}\n\nfunction check_4u_gpv3_type() {\n  echo \"Check 4U GPv3 type\" >> $LOG\n  # get the top configure\n  cmd=\"slot1 0xe0 0x02 0x9c 0x9c 0x0 0x15 0xe0 0x02 0x9c 0x9c 0x0 0x45 0xe0 0x66 0x9c 0x9c 0x0 0x0\"\n  run_cmd \"$cmd\"\n  top_cfg=$(cut -d' ' -f2 <<<\"$(cat $LOG | tail -n 1)\")\n  echo \"top_cfg result: $top_cfg\" >> $LOG\n\n  echo \"\" >> $LOG\n\n  # get the bot configure\n  cmd=\"slot1 0xe0 0x02 0x9c 0x9c 0x0 0x15 0xe0 0x02 0x9c 0x9c 0x0 0x40 0xe0 0x66 0x9c 0x9c 0x0 0x0\"\n  run_cmd \"$cmd\"\n  bot_cfg=$(cut -d' ' -f2 <<<\"$(cat $LOG | tail -n 1)\")\n  echo \"bot_cfg result: $bot_cfg\" >> $LOG\n\n  if ! [ \"$bot_cfg\" == \"$top_cfg\" ]; then\n    echo \"BMC doesn't support multi config\" >> $LOG\n    echo \"Use TOP_CFG ${top_cfg} by default\" >> $LOG\n  fi\n\n  echo $top_cfg\n}\n\nfunction check_2u_gpv3_type() {\n  echo \"Check 2U GPv3 type\" >> $LOG\n\n  cmd=\"slot1 0xe0 0x02 0x9c 0x9c 0x0 0x15 0xe0 0x66 0x9c 0x9c 0x0 0x0\"\n  run_cmd \"$cmd\"\n\n  cfg=$(cut -d' ' -f11 <<<\"$(cat $LOG | tail -n 1)\")\n  echo -n \"result: \" >> $LOG\n  echo $cfg | tee -a $LOG\n}\n\nfunction init_class2_sic(){\n  local slot=\"slot1\"\n  local cfg=\"\"\n\n  val=$(get_m2_prsnt_sts $slot)\n  echo \"$slot\" >> $LOG\n  if [ $val = 0 ] || [ $val = 4 ]; then\n    echo \"2OU:\" >> $LOG\n    # 0h = GPv3 with BRCM\n    # 1h = 2OU EXP w/o PCIe Switch\n    # 2h = SPE\n    # 3h = GPv3 w/ MCHP\n    # 4h = CWC w/ MCHP\n    # 5h = TBD\n    # 6h = DPv1, class 1\n    # 7h = DPv2, class 1\n    EXP_BOARD_TYPE=$(get_2ou_board_type 4) #only slot1\n    if [ $EXP_BOARD_TYPE == \"0x01\" ]; then\n      init_vishay_ic $slot $REXP_INTF\n    else\n      # GPv3, CWC, and SPE\n      echo \"no need to initialize it because it's done by BIC or no VRs\" >> $LOG\n      # check if it's 2U or 4U GPv3\n      if [ $EXP_BOARD_TYPE == \"0x04\" ]; then\n        cfg=$(check_4u_gpv3_type)\n      elif [ $EXP_BOARD_TYPE == \"0x03\" ]; then\n        cfg=$(check_2u_gpv3_type)\n      fi\n\n      [[ ! -z \"$cfg\" ]] && /usr/bin/kv set \"gpv3_cfg\" \"$cfg\" create\n    fi\n  else\n    echo \"2OU is not present\" >> $LOG\n  fi\n}\n\necho \"\" > $LOG\nif [[ $1 =~ slot ]]; then\n  val=$(get_m2_prsnt_sts $1)\n  echo \"$1\" >> $LOG\n  check_class1_config $1 $val\n  exit\nfi\n\necho -n \"Setup VishayIC for fby3...\"\nbmc_location=$(get_bmc_board_id)\nif [ $bmc_location -eq 9 ]; then\n  #The BMC of class2\n  init_class2_sic\nelif [ $bmc_location -eq 14 ] ||  [ $bmc_location -eq 7 ]; then\n  #The BMC of class1\n  init_class1_sic\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"Done.\"\n", "num_lines": 201}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nfunction get_sel_time_from_server {\n  local BOARD_ID=$(get_bmc_board_id)\n  local output=\"\"\n  local snum=0\n\n  if [ $BOARD_ID -eq 9 ]; then\n    output=\"$(/usr/local/bin/me-util slot1 0x28 0x48)\"\n    [ ${#output} == 12 ] && snum=1\n  else\n    for i in $(seq 1 4)\n    do\n      if [[ $(is_server_prsnt $i) == \"1\" ]] ; then\n        # Use standard IPMI command 'get-sel-time' to read RTC time\n        output=$(/usr/local/bin/me-util slot$i 0x28 0x48)\n        if [ ${#output} == 12 ]; then\n          snum=$i\n          break\n        fi\n      fi\n    done\n  fi\n\n  # return IPMI \"Get sel time\" command output, or return empty string if command failed\n  [ ${#output} == 12 ] && echo $output || echo \"\"\n\n  return $snum\n}\n\nfunction do_sync {\n  local sel_time=$1\n  date -s @$((16#$(echo \"$sel_time\" | awk '{print $4$3$2$1}')))\n  test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  echo 1 > /tmp/sync_date\n}\n\nfunction server_sync {\n  output=\"$(/usr/bin/kv get time_sync)\"\n  if [ -n \"${output}\" ] ; then\n    if [ ${#output} == 11 ] ; then\n      echo Syncing up BMC time with server...\n      do_sync \"$output\"\n    else\n      echo Syncing up BMC time with IPMI command failed\n      logger -p user.info \"Time sync with IPMI command failed\"\n    fi\n  else\n    output=$(get_sel_time_from_server)\n    num=$?\n    if [ -n \"$output\" ]; then\n      echo Syncing up BMC time with server$num...\n      do_sync \"$output\"\n    else\n      echo Syncing up BMC time with server failed\n      logger -p user.info \"Time sync with server failed\"\n    fi\n  fi\n}\n\nfunction update_ntp_config_from_kv() {\n  local ntp_server\n  ntp_server=$(/usr/bin/kv get ntp_server persistent)\n  if [ -z \"$ntp_server\" ]; then\n    return\n  fi\n\n  sed -i \"s/.*# REPLACE WITH KV.*/server $ntp_server iburst # REPLACE WITH KV/\" /etc/ntp.conf\n  /etc/init.d/ntpd restart\n}\n\n# Sync BMC's date with one of the four servers\nfunction sync_date {\n  local NTP_DELAY_COUNT\n\n  update_ntp_config_from_kv\n\n  NTP_DELAY_COUNT=0\n  while [ $NTP_DELAY_COUNT -lt 30 ];\n  do\n    if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n      server_sync\n      break\n    fi\n  done\n}\n\nsync_date\n", "num_lines": 110}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n. /usr/local/fbpackages/utils/ast-functions\n\ncmd=$1\nfru=$2\ndev=$3\nbusid=\nexp=\nretry=10\nBOARD_ID=$(get_bmc_board_id)\n\nfunction show_usage() {\n  if [ \"$BOARD_ID\" -eq 9 ]; then\n    #The BMC of class2\n    echo \"Usage: usb-util.sh [ bind | unbind ] [ slot1-2U | slot1-2U-exp | slot1-2U-top | slot1-2U-bot ] [ pesw-uart, uart0, uart1, uart2, dev0, dev1, ..., dev11 ]\"\n    echo \"Usage: usb-util.sh bus-id [ slot1-2U | slot1-2U-exp | slot1-2U-top | slot1-2U-bot ] [ pesw-uart, uart0, uart1, uart2, dev0, dev1, ..., dev11 ]\"\n  else\n    #The BMC of class1\n    echo \"Usage: usb-util.sh [ bind | unbind ] [ slot1-2U | slot3-2U ] [ dev0, dev1, ..., dev11 ]\"\n    echo \"Usage: usb-util.sh bus-id [ slot1-2U | slot3-2U  ] [ dev0, dev1, ..., dev11 ]\"\n  fi\n}\n\nfunction check_file_exist() {\n    local found=0\n    for i in $(seq 0 $retry)\n    do\n        ls /sys/bus/usb/devices/ | grep -x $busid\n        if [ $? -eq 0 ]; then\n        # if usb path exist\n            found=1\n            break\n        fi\n        sleep 2\n    done\n\n    if [ $found -eq 0 ]; then\n        echo \"bus id: $busid not found\"\n        exit -1\n    fi\n}\n\nfunction get_2u_gpv3_bus_id() {\n    if [ $exp != \"0x00\" ] && [ $exp != \"0x03\" ]; then\n        echo \"command not supported by this platform\"\n        exit -1\n    fi\n\n    case $dev in\n    pesw-uart)\n        busid=\"1-1.3.4.2.4\"\n    ;;\n\n    uart0)\n        busid=\"1-1.3.1\"\n    ;;\n\n    uart1)\n        busid=\"1-1.3.2.2\"\n    ;;\n\n    uart2)\n        busid=\"1-1.3.2.4\"\n    ;;\n\n    dev0)\n        busid=\"1-1.3.4.1\"\n    ;;\n\n    dev1)\n        busid=\"1-1.3.3.1\"\n    ;;\n\n    dev2)\n        busid=\"1-1.3.4.2.1\"\n    ;;\n\n    dev3)\n        busid=\"1-1.3.3.2.1\"\n    ;;\n\n    dev4)\n        busid=\"1-1.3.4.2.2\"\n    ;;\n\n    dev5)\n        busid=\"1-1.3.3.2.2\"\n    ;;\n\n    dev6)\n        busid=\"1-1.3.4.3\"\n    ;;\n\n    dev7)\n        busid=\"1-1.3.3.3\"\n    ;;\n\n    dev8)\n        busid=\"1-1.3.4.2.3\"\n    ;;\n\n    dev9)\n        busid=\"1-1.3.3.2.3\"\n    ;;\n\n    dev10)\n        busid=\"1-1.3.4.4\"\n    ;;\n\n    dev11)\n        busid=\"1-1.3.3.2.4\"\n    ;;\n\n    *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n    ;;\n    esac\n}\n\nfunction get_2u_gpv3_bus_id_by_fru() {\n    if [ $exp != \"0x00\" ] && [ $exp != \"0x03\" ]; then\n        echo \"command not supported by this platform\"\n        exit -1\n    fi\n\n    if [ \"$fru\" = \"slot1-2U\" ]; then\n      case $dev in\n        dev0) # a\n        busid=\"1-1.1.3.4.1\"\n      ;;\n        dev1) # b\n        busid=\"1-1.1.3.3.1\"\n      ;;\n        dev2) # c\n        busid=\"1-1.1.3.4.2.1\"\n      ;;\n        dev3) # d\n        busid=\"1-1.1.3.3.2.1\"\n      ;;\n        dev4) # e\n        busid=\"1-1.1.3.4.2.2\"\n      ;;\n        dev5) # f\n        busid=\"1-1.1.3.3.2.2\"\n      ;;\n        dev6) # g\n        busid=\"1-1.1.3.4.3\"\n      ;;\n        dev7) # h\n        busid=\"1-1.1.3.3.3\"\n      ;;\n        dev8) # i\n        busid=\"1-1.1.3.4.2.3\"\n      ;;\n        dev9) # j\n        busid=\"1-1.1.3.3.2.3\"\n      ;;\n        dev10) # k\n        busid=\"1-1.1.3.4.4\"\n      ;;\n        dev11) # l\n        busid=\"1-1.1.3.3.2.4\"\n      ;;\n        *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n      ;;\n      esac\n    elif [ \"$fru\" = \"slot3-2U\" ]; then\n      case $dev in\n        dev0) # a\n        busid=\"1-1.3.3.4.1\"\n      ;;\n        dev1) # b\n        busid=\"1-1.3.3.3.1\"\n      ;;\n        dev2) # c\n        busid=\"1-1.3.3.4.2.1\"\n      ;;\n        dev3) # d\n        busid=\"1-1.3.3.3.2.1\"\n      ;;\n        dev4) # e\n        busid=\"1-1.3.3.4.2.2\"\n      ;;\n        dev5) # f\n        busid=\"1-1.3.3.3.2.2\"\n      ;;\n        dev6) # g\n        busid=\"1-1.3.3.4.3\"\n      ;;\n        dev7) # h\n        busid=\"1-1.3.3.3.3\"\n      ;;\n        dev8) # i\n        busid=\"1-1.3.3.4.2.3\"\n      ;;\n        dev9) # j\n        busid=\"1-1.3.3.3.2.3\"\n      ;;\n        dev10) # k\n        busid=\"1-1.3.3.4.4\"\n      ;;\n        dev11) # l\n        busid=\"1-1.3.3.3.2.4\"\n      ;;\n        *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n      ;;\n      esac\n    else\n      echo \"The $fru is invalid\"\n      exit -1;\n    fi\n\n}\n\n\nfunction get_cwc_bus_id() {\n    if [ $exp != \"0x04\" ]; then\n        echo \"command not supported by this platform\"\n        exit -1\n    fi\n\n    case $dev in\n    pesw-uart)\n        busid=\"1-1.3.2.2\"\n    ;;\n\n    *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n    ;;\n    esac\n}\n\nfunction get_top_gpv3_bus_id() {\n    if [ $exp != \"0x04\" ]; then\n        echo \"command not supported by this platform\"\n        exit -1\n    fi\n\n    case $dev in\n    pesw-uart)\n        busid=\"1-1.3.1.4.2.4\"\n    ;;\n\n    uart0)\n        busid=\"1-1.3.1.1\"\n    ;;\n\n    uart1)\n        busid=\"1-1.3.1.2.2\"\n    ;;\n\n    uart2)\n        busid=\"1-1.3.1.2.4\"\n    ;;\n\n    dev0)\n        busid=\"1-1.3.1.4.1\"\n    ;;\n\n    dev1)\n        busid=\"1-1.3.1.3.1\"\n    ;;\n\n    dev2)\n        busid=\"1-1.3.1.4.2.1\"\n    ;;\n\n    dev3)\n        busid=\"1-1.3.1.3.2.1\"\n    ;;\n\n    dev4)\n        busid=\"1-1.3.1.4.2.2\"\n    ;;\n\n    dev5)\n        busid=\"1-1.3.1.3.2.2\"\n    ;;\n\n    dev6)\n        busid=\"1-1.3.1.4.3\"\n    ;;\n\n    dev7)\n        busid=\"1-1.3.1.3.3\"\n    ;;\n\n    dev8)\n        busid=\"1-1.3.1.4.2.3\"\n    ;;\n\n    dev9)\n        busid=\"1-1.3.1.3.2.3\"\n    ;;\n\n    dev10)\n        busid=\"1-1.3.1.4.4\"\n    ;;\n\n    dev11)\n        busid=\"1-1.3.1.3.2.4\"\n    ;;\n\n    *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n    ;;\n    esac\n}\n\nfunction get_bot_gpv3_bus_id() {\n    if [ $exp != \"0x04\" ]; then\n        echo \"command not supported by this platform\"\n        exit -1\n    fi\n\n    case $dev in\n    pesw-uart)\n        busid=\"1-1.3.4.4.2.4\"\n    ;;\n\n    uart0)\n        busid=\"1-1.3.4.1\"\n    ;;\n\n    uart1)\n        busid=\"1-1.3.4.2.2\"\n    ;;\n\n    uart2)\n        busid=\"1-1.3.4.2.4\"\n    ;;\n\n    dev0)\n        busid=\"1-1.3.4.4.1\"\n    ;;\n\n    dev1)\n        busid=\"1-1.3.4.3.1\"\n    ;;\n\n    dev2)\n        busid=\"1-1.3.4.4.2.1\"\n    ;;\n\n    dev3)\n        busid=\"1-1.3.4.3.2.1\"\n    ;;\n\n    dev4)\n        busid=\"1-1.3.4.4.2.2\"\n    ;;\n\n    dev5)\n        busid=\"1-1.3.4.3.2.2\"\n    ;;\n\n    dev6)\n        busid=\"1-1.3.4.4.3\"\n    ;;\n\n    dev7)\n        busid=\"1-1.3.4.3.3\"\n    ;;\n\n    dev8)\n        busid=\"1-1.3.4.4.2.3\"\n    ;;\n\n    dev9)\n        busid=\"1-1.3.4.3.2.3\"\n    ;;\n\n    dev10)\n        busid=\"1-1.3.4.4.4\"\n    ;;\n\n    dev11)\n        busid=\"1-1.3.4.3.2.4\"\n    ;;\n\n    *)\n        echo \"dev:$dev is not supported by $fru\"\n        exit -1\n    ;;\n    esac\n}\n\nfunction bind_usb() {\n    if [ -z $fru ] || [ -z $dev ]; then\n        show_usage\n        exit -1\n    fi\n\n    if [ \"$fru\" = \"slot3-2U\" ]; then\n        exp=$(get_2ou_board_type 6)\n    else\n        exp=$(get_2ou_board_type 4)\n    fi\n\n    case $fru in\n    slot1-2U)\n        if [ \"$BOARD_ID\" -eq 9 ]; then\n            get_2u_gpv3_bus_id\n        else\n            get_2u_gpv3_bus_id_by_fru\n        fi\n    ;;\n\n    slot1-2U-exp)\n        get_cwc_bus_id\n    ;;\n\n    slot1-2U-top)\n        get_top_gpv3_bus_id\n    ;;\n\n    slot1-2U-bot)\n        get_bot_gpv3_bus_id\n    ;;\n\n    slot3-2U)\n        get_2u_gpv3_bus_id_by_fru\n    ;;\n\n    *)\n        show_usage\n        exit -1\n    ;;\n    esac\n\n    if [ $cmd == \"unbind\" ] ; then\n        usbip unbind --busid $busid\n    else\n        if [ \"$fru\" = \"slot3-2U\" ]; then\n            hub=$(/usr/bin/bic-util slot3 --get_gpio | grep 16 | awk '{print $3;}') # get gpio value\n        else\n            hub=$(/usr/bin/bic-util slot1 --get_gpio | grep 16 | awk '{print $3;}') # get gpio value\n        fi\n\n        if [ $hub -eq 0 ]; then\n            if [ \"$fru\" = \"slot3-2U\" ]; then\n                /usr/bin/bic-util slot3 --set_gpio 16 1 > /dev/null 2>&1\n            else\n                /usr/bin/bic-util slot1 --set_gpio 16 1 > /dev/null 2>&1\n            fi\n            retry=15\n            echo \"Initializing USB devs...\"\n            sleep 10\n        fi\n\n        check_file_exist\n\n        modprobe usbip-core\n        modprobe usbip-host\n        usbipd -D\n        sleep 1\n        usbip bind --busid $busid\n    fi\n}\n\nfunction get_bus_id() {\n    if [ \"$fru\" = \"slot3-2U\" ]; then\n        exp=$(get_2ou_board_type 6)\n    else\n        exp=$(get_2ou_board_type 4)\n    fi\n\n    case $fru in\n    slot1-2U)\n        if [ \"$BOARD_ID\" -eq 9 ]; then\n            get_2u_gpv3_bus_id\n        else\n            get_2u_gpv3_bus_id_by_fru\n        fi\n    ;;\n\n    slot1-2U-exp)\n        get_cwc_bus_id\n    ;;\n\n    slot1-2U-top)\n        get_top_gpv3_bus_id\n    ;;\n\n    slot1-2U-bot)\n        get_bot_gpv3_bus_id\n    ;;\n\n    slot3-2U)\n        get_2u_gpv3_bus_id_by_fru\n    ;;\n\n    *)\n        show_usage\n        exit -1\n    ;;\n    esac\n\n    echo \"$fru $dev usb bus id is $busid\"\n}\n\ncase $cmd in\n    bind)\n        bind_usb\n    ;;\n\n    unbind)\n        bind_usb\n    ;;\n\n    bus-id)\n        get_bus_id\n    ;;\n\n    *)\n        show_usage\n        exit -1\n    ;;\nesac\n", "num_lines": 545}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\necho -n \"Setup sensor monitoring for FBY3... \"\nSLOTS=\n\nfunction get_bus_num() {\n  local bus=0\n  case $1 in\n    slot1)\n      bus=4\n    ;;\n    slot2)\n      bus=5\n    ;;\n    slot3)\n      bus=6\n    ;;\n    slot4)\n      bus=7\n    ;;\n  esac\n\n  echo $bus\n}\n\nread_system_conf() {\n  slot_num=${1#\"slot\"}\n  val=$(get_m2_prsnt_sts \"$1\")\n  i2c_bus=$(get_bus_num $1)\n\n  system_type=\"Type_\"\n  #0 = 2ou and 1ou are present\n  #4 = 2ou is present\n  #8 = 1ou is present\n  #other = not present\n  if [ \"$val\" -eq 0 ]; then\n    exp_board=$(get_2ou_board_type $i2c_bus)\n\n    if [ \"$exp_board\" == \"0x04\" ] || [ \"$exp_board\" == \"0x00\" ] || [ \"$exp_board\" == \"0x03\" ]; then\n      system_type=${system_type}17\n    else\n      system_type=${system_type}10\n    fi      \n  elif [ \"$val\" -eq 4 ]; then\n    cpld_bus=$(get_cpld_bus \"$slot_num\")\n    type_2ou=$(get_2ou_board_type \"$cpld_bus\")\n    if [ \"$type_2ou\" = \"0x06\" ]; then\n      # DP slot\n      dp_type=$(/usr/bin/kv get \"sled_system_conf\" persistent)\n      if [ \"$dp_type\" = \"Type_DPB\" ]; then\n        system_type=${system_type}DPB\n      elif [ \"$dp_type\" = \"Type_DPF\" ]; then\n        system_type=${system_type}DPF\n      else\n        system_type=${system_type}DP\n      fi\n    elif [ \"$type_2ou\" == \"0x03\" ] ; then # Config D GPv3\n        system_type=${system_type}15\n    else\n      system_type=${system_type}1\n    fi\n  elif [ \"$val\" -eq 8 ]; then\n    system_type=${system_type}10\n  else\n    system_type=${system_type}1\n  fi\n\n  /usr/bin/kv set \"${1}_system_conf\" \"$system_type\" persistent\n}\n\ninit_class2_sensord() {\n  SLOTS=\"slot1 bmc nic\"\n  read_system_conf \"slot1\"\n\n  board=$(get_2ou_board_type 4)\n  if [ \"$board\" = \"0x04\" ]; then\n    SLOTS=\"$SLOTS slot1-2U-exp slot1-2U-top slot1-2U-bot\"\n  fi\n}\n\ninit_class1_sensord() {\n  # Check for the slots present and run sensord for those slots only.\n  if [ \"$(is_server_prsnt 1)\" = \"1\" ]; then\n    if [ \"$(is_slot_12v_on 1)\" = \"1\" ]; then\n      SLOTS=\"$SLOTS slot1\"\n      read_system_conf \"slot1\"\n    fi\n  fi\n\n  if [ \"$(is_server_prsnt 2)\" = \"1\" ]; then\n    if [ \"$(is_slot_12v_on 2)\" = \"1\" ]; then\n      SLOTS=\"$SLOTS slot2\"\n      read_system_conf \"slot2\"\n    fi\n  fi\n\n  if [ \"$(is_server_prsnt 3)\" = \"1\" ]; then\n    if [ \"$(is_slot_12v_on 3)\" = \"1\" ]; then\n      SLOTS=\"$SLOTS slot3\"\n      read_system_conf \"slot3\"\n    fi\n  fi\n\n  if [ \"$(is_server_prsnt 4)\" = \"1\" ]; then\n    if [ \"$(is_slot_12v_on 4)\" = \"1\" ]; then\n      SLOTS=\"$SLOTS slot4\"\n      read_system_conf \"slot4\"\n    fi\n  fi\n\n  SLOTS=\"$SLOTS bmc nic\"\n}\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq 9 ]; then\n  #The BMC of class2\n  init_class2_sensord\nelif [ \"$bmc_location\" -eq 14 ] || [ \"$bmc_location\" -eq 7 ]; then\n  #The BMC of class1\n  init_class1_sensord\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\nexec /usr/local/bin/sensord $SLOTS\n", "num_lines": 126}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util slotX --version\" once to store vr information before sensor monitoring \necho \"Get MB FW version... \"\n\nbmc_location=$(get_bmc_board_id)\nif ! [ $bmc_location -eq 9 ]; then\n  if [[ $(is_sb_bic_ready 1) == \"1\" ]]; then\n    /usr/bin/fw-util slot1 --version > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 2) == \"1\" ]]; then\n    /usr/bin/fw-util slot2 --version > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 3) == \"1\" ]]; then\n    /usr/bin/fw-util slot3 --version > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 4) == \"1\" ]]; then\n    /usr/bin/fw-util slot4 --version > /dev/null\n  fi\n\n  # Clear PEAK_PIN & PEAK_IOUT register\n  /usr/sbin/i2cset -y 11 0x40 0xd0 0x0000 w\n  /usr/sbin/i2cset -y 11 0x40 0xda 0x0000 w\nelse\n  /usr/bin/fw-util slot1 --version > /dev/null\nfi\n\necho -n \"Setup sensor monitoring for FBYV3... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 64}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 3\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\ninit_class1_ipmb() {\n  for slot_num in {1..4..2}; do\n    bus=$((slot_num-1))\n    echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-${bus}/new_device\n    runsv /etc/sv/ipmbd_${bus} > /dev/null 2>&1 &\n    slot_present=$(gpio_get PRSNT_MB_BMC_SLOT\"${slot_num}\"_BB_N)\n    if [ \"$slot_present\" = \"1\" ]; then\n      usleep 50000\n      sv stop ipmbd_${bus}\n      disable_server_12V_power \"${slot_num}\"\n    else\n      enable_server_i2c_bus \"${slot_num}\"\n    fi\n  done\n\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n}\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\nsleep 10\nulimit -q 1024000\n\ninit_class1_ipmb\n\necho \"Done.\"\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\ndump_sensor_history() \n{\n  l_SLOT=$1\n  l_SENSOR_HISTORY=180\n\n  /usr/local/bin/sensor-util \"$l_SLOT\" --history $l_SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util bmc --history $l_SENSOR_HISTORY \\\n   && /usr/local/bin/sensor-util nic --history $l_SENSOR_HISTORY \n}\n\ndump_sensor_threshold()\n{\n  l_SLOT=$1\n\n  /usr/local/bin/sensor-util \"$l_SLOT\" --threshold \\\n   && /usr/local/bin/sensor-util bmc --threshold \\\n   && /usr/local/bin/sensor-util nic --threshold\n}\n\nSLOT_NAME=$1\n\ncase $SLOT_NAME in\n  slot1)\n    SLOT_NUM=1\n    ;;\n  slot2)\n    SLOT_NUM=2\n    ;;\n  slot3)\n    SLOT_NUM=3\n    ;;\n  slot4)\n    SLOT_NUM=4\n    ;;\n  *)\n    N=${0##*/}\n    echo \"Usage: $N {slot1|slot2|slot3|slot4}\"\n    exit 1\n    ;;\nesac\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump${SLOT_NUM}.pid\"\nDUMP_DIR='/var/lib/amd-ras'\nCURRENT_INDEX_FILE=\"$DUMP_DIR/fru${SLOT_NUM}_current_index\"\nINFODUMP_FILE=\"$DUMP_DIR/fru${SLOT_NUM}_crashdump_info\"\nDUMP_UTIL='/usr/bin/amd-ras'\nFRUID_UTIL=\"/usr/local/bin/fruid-util\"\nFW_UTIL=\"/usr/bin/fw-util\"\n\n# check crashdump binary file exists\nif [ ! -f $DUMP_UTIL ]; then\n  logger -t \"ipmid\" -p daemon.crit \"AMD ADDC crashdump not supported\"\n  exit 1\nfi\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  logger -t \"ipmid\" -p daemon.warning \"Another crashdump for $SLOT_NAME is runnung\"\n  exit 1\nelse\n  touch $PID_FILE\nfi\n\n# Set crashdump timestamp\n# this timestamp is used by pal_is_crashdump_ongoing() and it can\n# prevent the power control when crashdump is ongoing\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\nkv set \"fru${SLOT_NUM}_crashdump\" \"$((sys_runtime+600))\"\n\n# check number of crashdump file exists\n[ -r $CURRENT_INDEX_FILE ] && PREVIOUS_INDEX=$(cat $CURRENT_INDEX_FILE) || PREVIOUS_INDEX=0\n\nCURT_DTIME=$(date +\"%Y%m%d-%H%M%S\")\nDUMP_FILE=\"$DUMP_DIR/fru${SLOT_NUM}_ras-error${PREVIOUS_INDEX}.cper\"\nLOG_ARCHIVE=\"/mnt/data/fru${SLOT_NUM}_ras-error${PREVIOUS_INDEX}_${CURT_DTIME}.tar.gz\"\n\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: $SLOT_NUM started\"\n\n#HEADER LINE for the dump\necho \"Crash Dump generated at $(date)\" > \"$INFODUMP_FILE\"\n{\n  # Get BMC version & hostname\n  echo \"Get BMC version info: \"\n  \"$FW_UTIL\" bmc --version\n  uname -a\n  cat /etc/issue\n\n  # Get fw info\n\n  echo \"Get firmware version info: \"\n  \"$FW_UTIL\" \"$SLOT_NAME\" \"--version\"\n\n  # Get FRUID info\n  echo \"Get FRUID Info:\"\n  \"$FRUID_UTIL\" \"$SLOT_NAME\"\n\n  # Sensors & sensor thresholds\n  echo \"Sensor history at dump:\"\n  dump_sensor_history \"$SLOT_NAME\"\n  echo \"Sensor threshold at dump:\"\n  dump_sensor_threshold \"$SLOT_NAME\"\n} >> \"$INFODUMP_FILE\"\n\nRAS_STATUS=$2\nNUM_OF_PROC=$3\nTARGET_CPU=$4\nCPUID_EAX=$5\nCPUID_EBX=$6\nCPUID_ECX=$7\nCPUID_EDX=$8\n\n$DUMP_UTIL --fru \"$SLOT_NUM\" --ras \"$RAS_STATUS\" --ncpu \"$NUM_OF_PROC\" --tcpu \"$TARGET_CPU\"  --bid 0 --cid \"$CPUID_EAX\" \"$CPUID_EBX\" \"$CPUID_ECX\" \"$CPUID_EDX\"\n\n[ -r $CURRENT_INDEX_FILE ] && CURRENT_INDEX=$(cat $CURRENT_INDEX_FILE) || CURRENT_INDEX=0\nif [ \"$PREVIOUS_INDEX\" == \"$CURRENT_INDEX\" ]; then\n  DUMP_FILE=\nfi\n\nIFS=\" \" read -r -a LOGS <<< \"$(basename \"$INFODUMP_FILE\") $(basename \"$DUMP_FILE\")\"\ntar zcf \"$LOG_ARCHIVE\" -C \"$DUMP_DIR\" \"${LOGS[@]}\" && rm -rf \"$DUMP_FILE\"\nif [ -f \"$LOG_ARCHIVE\" ]; then\n  logger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: $SLOT_NUM is generated at $LOG_ARCHIVE\"\nfi\n\n# Remove current pid file\nrm $PID_FILE\nexit 0\n", "num_lines": 133}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 2\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 3 \n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 4\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\ninit_class1_ipmb() {\n  for slot_num in {1..4}; do\n    bus=$((slot_num-1))\n    echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-${bus}/new_device\n    runsv /etc/sv/ipmbd_${bus} > /dev/null 2>&1 &\n    if [ \"$slot_num\" -eq 1 ] || [ \"$slot_num\" -eq 3 ]; then\n      slot_present=$(gpio_get PRSNT_MB_BMC_SLOT\"${slot_num}\"_BB_N)\n    else\n      slot_present=$(gpio_get PRSNT_MB_SLOT\"${slot_num}\"_BB_N)\n    fi\n    if [ \"$slot_present\" = \"1\" ]; then\n      usleep 50000\n      sv stop ipmbd_${bus}\n      disable_server_12V_power \"${slot_num}\"\n    else\n      enable_server_i2c_bus \"${slot_num}\"\n    fi\n  done\n\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n}\n\ninit_class2_ipmb() {\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-0/new_device\n  runsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\n}\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\nsleep 10\nulimit -q 1024000\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_ipmb\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_ipmb\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"Done.\"\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Starting MCTP Rx/Tx Daemon..\"\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device\n\nrunsv /etc/sv/mctpd_8 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nDEF_PWR_ON=1\nTO_PWR_ON=\nDEBUG_ENABLE=false\n\n\ncheck_por_config() {\n  TO_PWR_ON=0\n\n  if POR=$(kv get \"slot${1}_por_cfg\" persistent); then\n    if [ \"$POR\" = \"lps\" ]; then\n      if LS=$(kv get \"pwr_server${1}_last_state\" persistent); then\n        if [ \"$LS\" = \"on\" ]; then\n          TO_PWR_ON=1;\n        fi\n      else\n        TO_PWR_ON=$DEF_PWR_ON\n      fi\n    elif [ \"$POR\" = \"on\" ]; then\n      TO_PWR_ON=1;\n    fi\n  else\n    TO_PWR_ON=$DEF_PWR_ON\n  fi\n}\n\nupdate_ntp_config_from_kv() {\n  local ntp_server\n  ntp_server=$(/usr/bin/kv get ntp_server persistent)\n  if [ -z \"$ntp_server\" ]; then\n    return\n  fi\n\n  sed -i \"s/.*# REPLACE WITH KV.*/server $ntp_server iburst # REPLACE WITH KV/\" /etc/ntp.conf\n  /etc/init.d/ntpd restart\n}\n\nis_ntp_time_synced() {\n  local str\n  local ret\n\n  str=$(/usr/sbin/ntpq -np | grep '^\\*')\n  ret=$?\n\n  if [ \"$DEBUG_ENABLE\" = true ] ; then\n    echo \"==================================\"\n    echo \"ret: $ret\"\n    echo \"----------------------------------\"\n    echo \"$str\"\n    echo \"==================================\"\n  fi\n\n  # ret == 0, synced\n  # ret == 1, not synced\n  return $ret\n}\n\nntp_sync_delay() {\n    local NTP_DELAY_COUNT\n\n    NTP_DELAY_COUNT=0\n    echo \"[$(/bin/date)] ntp is enabled, ntp_server: $(/usr/bin/kv get ntp_server persistent)\"\n    while [ $NTP_DELAY_COUNT -lt 30 ];\n    do\n      if is_ntp_time_synced ; then\n        break\n      fi\n      ((NTP_DELAY_COUNT++))\n      [ \"$DEBUG_ENABLE\" = true ] && echo \"[$(/bin/date)] system time not synced, count: ${NTP_DELAY_COUNT}\"\n      sleep 1\n    done\n    if is_ntp_time_synced ; then\n      echo \"[$(/bin/date)] system time synced after $NTP_DELAY_COUNT sec\"\n    else\n      echo \"[$(/bin/date)] system time not synced after $NTP_DELAY_COUNT sec\"\n    fi\n}\n\n# Check whether it is fresh power on reset\nif [ \"$(is_bmc_por)\" -eq 1 ]; then\n  # Disable clearing of PWM block on WDT SoC Reset\n  devmem_clear_bit \"$(scu_addr 70)\" 13\n\n  # Wait for NTP sync\n  update_ntp_config_from_kv\n  ntp_sync_delay\n\n  # check POR config for each slot\n  check_por_config 1\n  if [ \"$(is_sb_bic_ready 1)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n    power-util slot1 on\n  fi\n\n  check_por_config 3\n  if [ \"$(is_sb_bic_ready 3)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n    power-util slot3 on\n  fi\n\nfi\n", "num_lines": 132}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nexp_addr=0x44\n\nif [ $exp_addr = 0x44 ]; then\n  addr=0x40\n  exp_frs=(0x00 0x00 0x11 0x00 0x00 0x00 0x00 0x00)\nelse\n  addr=0x44\n  exp_frs=(0x00 0x00 0x10 0x00 0x00 0x00 0x00 0x00)\nfi\nexp_idcode=\"0x61 0x2b 0xc0 0x43\"\nexp_fbs=(0x02 0x20)\nretcode=0\n\nslot=$1\n\ncheck_busy() {\n  dev=$1\n\n  for _ in {1..30}; do\n    usleep 100000\n    busy=$(i2ctransfer -y \"$bus\" w4@\"$dev\" 0xf0 0x00 0x00 0x00 r1 2>/dev/null)\n    if [[ \"$busy\" != \"\" && $((busy & 0x80)) = 0 ]]; then\n      break\n    fi\n  done\n  if [[ \"$busy\" == \"\" || $((busy & 0x80)) != 0 ]]; then\n    printf \"Failed\\n\"\n    exit 1\n  fi\n}\n\ncase $slot in\n  slot1)\n    bus=4\n    ;;\n  slot2)\n    bus=5\n    ;;\n  slot3)\n    bus=6\n    ;;\n  slot4)\n    bus=7\n    ;;\n  *)\n    N=${0##*/}\n    echo \"Usage: $N {slot1|slot2|slot3|slot4}\"\n    exit 1\n    ;;\nesac\n\n# Check if already programmed\nidcode=$(i2ctransfer -y $bus w4@$exp_addr 0xe0 0x00 0x00 0x00 r4 2>/dev/null)\nif [ \"$idcode\" = \"$exp_idcode\" ]; then\n  addr=$exp_addr\n  i2ctransfer -y $bus w3@$addr 0x74 0x08 0x00 >/dev/null 2>&1\n  frs=$(i2ctransfer -y $bus w4@$addr 0xe7 0x00 0x00 0x00 r8 2>/dev/null)\n  fbs=$(i2ctransfer -y $bus w4@$addr 0xfb 0x00 0x00 0x00 r2 2>/dev/null)\n  i2ctransfer -y $bus w3@$addr 0x26 0x00 0x00 >/dev/null 2>&1\n  if [[ \"$frs\" = \"${exp_frs[*]}\" && \"$fbs\" = \"${exp_fbs[*]}\" ]]; then\n    echo \"Already programmed!\"\n    echo \"Feature Rows: $frs\"\n    echo \"FEABITS: $fbs\"\n    exit 0\n  fi\nfi\n\n\n# Check the IDCODE\nidcode=$(i2ctransfer -y $bus w4@$addr 0xe0 0x00 0x00 0x00 r4)\necho \"IDCODE: $idcode\"\nif [ \"$idcode\" != \"$exp_idcode\" ]; then\n  echo \"Unexpected IDCODE!\"\n  exit 1\nfi\n\n# Check the STATUS\nread -r -a sts <<< \"$(i2ctransfer -y $bus w4@$addr 0x3c 0x00 0x00 0x00 r4)\"\necho \"Status Register: ${sts[*]}\"\nif [[ $((sts[2] & 0x70)) != 0 || $((sts[3] & 0x20)) != 0 ]]; then\n  echo \"Unexpected Status!\"\n  exit 1\nfi\n\n\nprintf \"Enable XPROGRAM mode...\"\nif ! i2ctransfer -y $bus w3@$addr 0x74 0x08 0x00 >/dev/null; then\n  printf \"Failed\\n\"\n  exit 1\nfi\nprintf \"OK\\n\"\n\nfrs=$(i2ctransfer -y $bus w4@$addr 0xe7 0x00 0x00 0x00 r8)\necho \"Feature Rows before programming: $frs\"\n\nfbs=$(i2ctransfer -y $bus w4@$addr 0xfb 0x00 0x00 0x00 r2)\necho \"FEABITS before programming: $fbs\"\n\n\nprintf \"Erase the Feature Rows...\"\ni2ctransfer -y $bus w4@$addr 0x0e 0x02 0x00 0x00 >/dev/null\naddr=0x40  # address become to default\ncheck_busy $addr\nprintf \"OK\\n\"\n\nprintf \"Program Feature Rows...\"\nif ! i2ctransfer -y $bus w4@$addr 0x46 0x02 0x00 0x00 >/dev/null; then\n  printf \"Failed\\n\"\n  exit 1\nfi\n\ni2ctransfer -y $bus w12@$addr 0xe4 0x00 0x00 0x00 \"${exp_frs[@]}\" >/dev/null\naddr=$exp_addr\ncheck_busy $addr\nfrs=$(i2ctransfer -y $bus w4@$addr 0xe7 0x00 0x00 0x00 r8)\n\ni2ctransfer -y $bus w6@$addr 0xf8 0x00 0x00 0x00 \"${exp_fbs[@]}\" >/dev/null\ncheck_busy $addr\nfbs=$(i2ctransfer -y $bus w4@$addr 0xfb 0x00 0x00 0x00 r2)\n\nif [[ \"$frs\" = \"${exp_frs[*]}\" && \"$fbs\" = \"${exp_fbs[*]}\" ]]; then\n  printf \"OK\\n\"\nelse\n  printf \"Failed\\n\"\n  retcode=1\nfi\necho \"Feature Rows after programming: $frs\"\necho \"FEABITS after programming: $fbs\"\n\n\nprintf \"Exit the programming mode...\"\nif ! i2ctransfer -y $bus w3@$addr 0x26 0x00 0x00 >/dev/null; then\n  printf \"Failed\\n\"\n  exit 1\nfi\nprintf \"OK\\n\"\nexit $retcode\n\n", "num_lines": 141}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\ninit_class2_sdr() {\n  /usr/local/bin/bic-cached -s slot1\n  /usr/local/bin/bic-cached -f slot1 > /dev/null 2>&1 &\n}\n\ninit_class1_sdr() {\n  # -f means `dump fru` only\n  if [ \"$(is_sb_bic_ready 1)\" = \"1\" ]; then\n    /usr/local/bin/bic-cached -s slot1\n    /usr/local/bin/bic-cached -f slot1 > /dev/null 2>&1 &\n  fi\n\n  if [ \"$(is_sb_bic_ready 2)\" = \"1\" ]; then\n    /usr/local/bin/bic-cached -s slot2\n    /usr/local/bin/bic-cached -f slot2 > /dev/null 2>&1 &\n  fi\n\n  if [ \"$(is_sb_bic_ready 3)\" = \"1\" ]; then\n    /usr/local/bin/bic-cached -s slot3\n    /usr/local/bin/bic-cached -f slot3 > /dev/null 2>&1 &\n  fi\n\n  if [ \"$(is_sb_bic_ready 4)\" = \"1\" ]; then\n    /usr/local/bin/bic-cached -s slot4\n    /usr/local/bin/bic-cached -f slot4 > /dev/null 2>&1 &\n  fi\n}\n\necho -n \"Setup Caching for Bridge IC info..\"\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_sdr\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_sdr\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"done.\"\n", "num_lines": 58}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nBOARD_ID=$(get_bmc_board_id)\nSLOT_NAME=$1\n\ncase $SLOT_NAME in\n  slot1)\n    SLOT_NUM=1\n    ;;\n  slot2)\n    SLOT_NUM=2\n    ;;\n  slot3)\n    SLOT_NUM=3\n    ;;\n  slot4)\n    SLOT_NUM=4\n    ;;\n  *)\n    N=${0##*/}\n    if [ \"$BOARD_ID\" = \"$BMC_ID_CLASS2\" ]; then\n      echo \"Usage: $N {slot1}\"\n    else\n      echo \"Usage: $N {slot1|slot2|slot3|slot4}\"\n    fi\n    exit 1\n    ;;\nesac\n\nif [ \"$BOARD_ID\" = \"$BMC_ID_CLASS2\" ] && [ \"$SLOT_NAME\" != \"slot1\" ]; then\n  # class2 checking\n  echo \"$SLOT_NAME not supported\"\n  exit 1\nfi\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID=$$\nPID_FILE=\"/var/run/autodump${SLOT_NUM}.pid\"\nDUMP_DIR='/tmp/crashdump/output'\nPARSE_FILE=\"$DUMP_DIR/bafi_${SLOT_NAME}.log\"\nDUMP_FILE=\"$DUMP_DIR/crashdump_${SLOT_NAME}.log\"\nDUMP_UTIL='/usr/bin/crashdump'\nPARSE_UTIL='/usr/bin/bafi'\nLOG_ARCHIVE=\"/mnt/data/crashdump_${SLOT_NAME}.tar.gz\"\nACD=true\n\nif [ ! -f $DUMP_UTIL ]; then\n  ACD=false\n  DUMP_UTIL=\"/usr/bin/dump.sh $SLOT_NAME\"\n  mkdir -p $DUMP_DIR\nfi\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=$(cat $PID_FILE) || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# kill previous autodump if exist\nif [ -n \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null); then\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  if [ \"$ACD\" = true ]; then\n    pkill -KILL -f \"$DUMP_UTIL $SLOT_NUM --type IERR\" >/dev/null 2>&1\n    pkill -KILL -f \"$PARSE_UTIL .*${SLOT_NAME}\" >/dev/null 2>&1\n  else\n    pkill -KILL -f \"$DUMP_UTIL\" >/dev/null 2>&1\n    pkill -KILL -f \"me-util $SLOT_NAME\" >/dev/null 2>&1\n    pkill -KILL -f \"bic-util $SLOT_NAME\" >/dev/null 2>&1\n\n    { echo -n \"(uncompleted) Auto Dump End at \"; date; } >> \"$DUMP_FILE\"\n    tar zcf \"/mnt/data/crashdump_uncompleted_${SLOT_NAME}.tar.gz\" -C $DUMP_DIR \"$(basename \"$DUMP_FILE\")\"\n  fi\nfi\nunset OLDPID\n\n# Set crashdump timestamp\n# this timestamp is used by pal_is_crashdump_ongoing() and it can\n# prevent the power control when crashdump is ongoing\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\nkv set \"fru${SLOT_NUM}_crashdump\" \"$((sys_runtime+600))\"\n\nDELAY_SEC=30\n\nwhile test $# -gt 1; do\n  case \"$2\" in\n  --now)\n    DELAY_SEC=0\n    ;;\n  *)\n    echo \"unknown argument $2\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n  sleep \"$DELAY_SEC\"\nfi\n\necho \"Auto Dump for $SLOT_NAME Started\"\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: $SLOT_NUM started\"\n\nLOGS=(\"$(basename \"$DUMP_FILE\")\")\nif [ \"$ACD\" = true ]; then\n  $DUMP_UTIL $SLOT_NUM --type IERR\n\n  # shellcheck disable=SC2012\n  LOG_FILE=$(ls $DUMP_DIR/crashdump_\"${SLOT_NAME}\"* -t1 |head -n 1)\n  $PARSE_UTIL \"$LOG_FILE\" > \"$PARSE_FILE\" 2>&1\n\n  LOGS=(\"$(basename \"$LOG_FILE\")\" \"$(basename \"$PARSE_FILE\")\")\nelse\n  { echo -n \"Auto Dump Start at \"; date; } > \"$DUMP_FILE\"\n  { $DUMP_UTIL coreid; $DUMP_UTIL msr; $DUMP_UTIL pcie; } >> \"$DUMP_FILE\" 2>&1\n  { echo -n \"Auto Dump End at \"; date; } >> \"$DUMP_FILE\"\nfi\n\ntar zcf \"$LOG_ARCHIVE\" -C $DUMP_DIR \"${LOGS[@]}\"\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: $SLOT_NUM is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"Auto Dump for $SLOT_NAME Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 133}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nME_UTIL=\"/usr/local/bin/me-util\"\nPECI_UTIL=\"/usr/bin/bic-util\"\nCMD_DIR=\"/usr/bin\"\nINTERFACE=\"PECI_INTERFACE\"\nSENSOR_UTIL=\"/usr/local/bin/sensor-util\"\nSENSOR_HISTORY=180\nSLOT=$1\n\n# read command from stdin\nfunction execute_via_me {\n  # if ME_UTIL cannot be executed, return\n  [ -x $ME_UTIL ] || return\n\n  # Adapt command to ME-UTIL format\n  cat | sed 's/^0x/0xb8 0x40 0x57 0x01 0x00 0x/g' | \\\n    $ME_UTIL \"$SLOT\" --file /dev/stdin | sed 's/^57 01 00 //g'\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || return\n\n  cat | sed 's/^0x/0xe0 0x29 0x15 0xa0 0x00 0x/g' | \\\n    $PECI_UTIL \"$SLOT\" --file /dev/stdin | sed 's/^15 A0 00 //g'\n}\n\nfunction execute_cmd {\n  if [ \"$INTERFACE\" == \"ME_INTERFACE\" ]; then\n    cat | execute_via_me\n  else\n    cat | execute_via_peci\n  fi\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12] (unit: bits)\n# OUT: PCI config address\nfunction PCI_Config_Addr {\n  # BUS\n  RESULT=$((($1 & 0xFF) << 20))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15)))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12)))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0)))\n  printf \"0x%x 0x%x 0x%x 0x%x\" \\\n    $((RESULT & 0xFF)) \\\n    $(((RESULT >> 8) & 0xFF)) \\\n    $(((RESULT >> 16) & 0xFF)) \\\n    $(((RESULT >> 24) & 0xFF))\n  return 0\n}\n\nfunction print_bus_device {\n  MAX_FUN=0\n  MAX_DEV=4\n  BUS=$(printf \"0x%02x\" \"$1\")\n  BUSM=$(($1 >> 4))\n  BUSL=$((($1 & 0xF) << 4))\n  for (( DEV=0; DEV<=MAX_DEV; DEV++ )); do\n    DEVM=$((DEV >> 1))\n    DEVL=$(((DEV & 0x1) << 3))\n    for (( FUN=0; FUN<=MAX_FUN; FUN++ )); do\n      printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x100 ~ 0x147\\\"\\n\" \"$1\" $DEV $FUN\n      BYTE1=$(((DEVL | FUN) << 4 | 0x1))\n      BYTE2=$((BUSL | DEVM))\n      for REG in {0..68..4}; do\n        printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n      done\n    done\n  done\n}\n\nfunction find_end_device {\n  echo \"Find Root Port Bus $1 Dev $2 Fun $3...\"\n  RES=$(echo 0x30 0x06 0x05 0x61 0x00 \"$(PCI_Config_Addr \"$1\" \"$2\" \"$3\" 0x18)\" | execute_cmd)\n  echo \"$RES\"\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n  SECONDARY_BUS=0x$(echo \"$RES\"| awk '{print $3;}')\n  SUBORDINATE_BUS=0x$(echo \"$RES\"| awk '{print $4;}')\n  if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n    for (( BUS=SECONDARY_BUS; BUS<=SUBORDINATE_BUS; BUS++ )); do\n      printf \"End Device on Bus 0x%02x\\n\" $BUS\n      print_bus_device $BUS | execute_cmd\n    done\n  fi\n}\n\nfunction pcie_dump {\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && execute_cmd < $CMD_DIR/crashdump_pcie\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n\n  # Completion Code\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    # CPU root port - Bus 0x16/0x64, Dev 0~3, Fun:0\n    # Root port buses\n    ROOT_BUSES=$(echo \"$RES\" | awk '{printf \"0x%s 0x%s\", $3, $4;}')\n    ROOT_BUS=$(echo \"$RES\" | awk '{printf \"0x%s\", $2;}')\n    echo ROOT_BUSES=\"$ROOT_BUSES\"\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        find_end_device \"$ROOT\" \"$DEV\" 0\n      done\n    done\n\n    # CPU root port - Bus 0,Dev 0, Fun:0\n    echo ROOT_BUS=\"$ROOT_BUS\"\n    find_end_device \"$ROOT_BUS\" 0 0\n\n    # PCH root port - Bus 0,Dev 0x1B, Fun:0\n    find_end_device \"$ROOT_BUS\" 0x1B 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:0\n    find_end_device \"$ROOT_BUS\" 0x1D 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:4\n    find_end_device \"$ROOT_BUS\" 0x1D 4\n  fi\n}\n\nfunction print_dump_help {\n  N=${0##*/}\n  echo \"Usage:\"\n  echo \"$N <slot#> coreid <INTERFACE> ==> for CPU CoreID\"\n  echo \"$N <slot#> msr    <INTERFACE> ==> for CPU MSR\"\n  echo \"$N <slot#> pcie   <INTERFACE> ==> for PCIe\"\n  echo \"$N <slot#> sensors            ==> for sensor history\"\n  echo \"$N <slot#> threshold          ==> for sensor threshold\"\n  exit 1\n}\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -eq 2 ] || [ \"$#\" -eq 3 ]; then\n  if [ \"$#\" -eq 3 ]; then\n    if [ \"$3\" != \"ME_INTERFACE\" ] && [ \"$3\" != \"PECI_INTERFACE\" ]; then\n      print_dump_help\n    fi\n    INTERFACE=\"$3\"\n  fi\n\n  case \"$2\" in\n    coreid)\n      [ -r $CMD_DIR/crashdump_coreid ] && execute_cmd < $CMD_DIR/crashdump_coreid\n      ;;\n    msr)\n      [ -r $CMD_DIR/crashdump_msr ] && execute_cmd < $CMD_DIR/crashdump_msr\n      ;;\n    pcie)\n      pcie_dump\n      ;;\n    sensors)\n      \"$SENSOR_UTIL\" \"$SLOT\" --history \"$SENSOR_HISTORY\" && \\\n      \"$SENSOR_UTIL\" bmc --history \"$SENSOR_HISTORY\" && \\\n      \"$SENSOR_UTIL\" nic --history \"$SENSOR_HISTORY\"\n      ;;\n    threshold)\n      \"$SENSOR_UTIL\" \"$SLOT\" --threshold && \\\n      \"$SENSOR_UTIL\" bmc --threshold && \\\n      \"$SENSOR_UTIL\" nic --threshold\n      ;;\n    *)\n      print_dump_help\n      ;;\n  esac\nelse\n  print_dump_help\nfi\n\nexit 0\n", "num_lines": 185}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\nTYPE_DUAL_FAN=0\nTYPE_SINGEL_FAN=1\nGET_FAN_RPM=\"/usr/bin/bic-util slot1 0xe0 0x2 \"\"$IANA_ID\"\" 0x10 0xe0 0x52 \"\"$IANA_ID\" # for config D\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\nsys_config=$(/usr/local/bin/show_sys_config | grep -i \"config:\" | awk -F \": \" '{print $3}')\nbmc_location=$(get_bmc_board_id)\n\n#For config A B C, we get the Baseboard revision from BB CPLD through i2cget.\nCLASS1_GET_BOARD_REVID=\"/usr/sbin/i2cget -y 12 0x0f 0x08\"\n#For config D, we get the Baseboard revision from BB BPLD. command: bic-util slot1 IPMI Send request message to BIC, IANA, BB bic, IPMI Master write read, CPLD i2cbus addr register\nCLASS2_GET_BOARD_REVID=\"/usr/bin/bic-util slot1 0xe0 0x2 \"\"$IANA_ID\"\" 0x10 0x18 0x52 0x1 0x1e 0x1 0x8 \"\n\ncheck_dvt_fan() {\n  local fan_type=$1\n  if [ \"$fan_type\" = \"$TYPE_DUAL_FAN\" ]; then\n    logger -t \"fan_check\" -p daemon.crit \"Fan slot $i is dual fan, please install single fan in DVT system\"\n  fi\n}\n\ncheck_evt_fan() {\n  local fan_type=$1\n  if [ \"$fan_type\" = \"$TYPE_DUAL_FAN\" ]; then\n    if [ \"$sys_config\" = \"A\" ]; then\n      logger -t \"fan_check\" -p daemon.crit \"Fan slot $i is dual fan, please install single fan on 1U system\"\n    fi\n  else\n    if [[ \"$sys_config\" = \"B\" || \"$sys_config\" = \"D\" ]]; then\n      logger -t \"fan_check\" -p daemon.crit \"Fan slot $i is single fan, please install dual fan on 2U system\"\n    fi\n  fi\n}\n\ncheck_fan_type() {\n  if [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n    # check CC of from BIC, if there is single fan TACH 1, 3, 5, 7 will not turn CC \"00\"\n    if [[ \"$($GET_FAN_RPM 1 | awk '{print $7;}')\" = \"00\" && \"$($GET_FAN_RPM 3 | awk '{print $7;}')\" = \"00\" ]]; then\n      fan0_type=$TYPE_DUAL_FAN\n    else\n      fan0_type=$TYPE_SINGEL_FAN\n    fi\n    if [[ \"$($GET_FAN_RPM 5 | awk '{print $7;}')\" = \"00\" && \"$($GET_FAN_RPM 7 | awk '{print $7;}')\" = \"00\" ]]; then\n      fan1_type=$TYPE_DUAL_FAN\n    else\n      fan1_type=$TYPE_SINGEL_FAN\n    fi\n  else\n    if [[ \"$(cat /sys/class/hwmon/hwmon*/fan2_input)\" = \"0\" && \"$(cat /sys/class/hwmon/hwmon*/fan4_input)\" = \"0\" ]]; then\n      fan0_type=$TYPE_SINGEL_FAN\n    else\n      fan0_type=$TYPE_DUAL_FAN\n    fi\n    if [[ \"$(cat /sys/class/hwmon/hwmon*/fan6_input)\" = \"0\" && \"$(cat /sys/class/hwmon/hwmon*/fan8_input)\" = \"0\" ]]; then\n      fan1_type=$TYPE_SINGEL_FAN\n    else\n      fan1_type=$TYPE_DUAL_FAN\n    fi\n  fi\n  fan_type=(\"$fan0_type\" \"$fan1_type\")\n  for ((i=0; i < ${#fan_type[@]}; i++))\n  do\n    if [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n      BOARD_REVID=$($CLASS1_GET_BOARD_REVID)\n      if [ \"$((0x${BOARD_REVID#*x}))\" -ge \"$DVT_REVID\" ]; then # for revision id >= 5 means the stage is DVT or after DVT\n        check_dvt_fan \"${fan_type[$i]}\"\n      else\n        check_evt_fan \"${fan_type[$i]}\"\n      fi\n    elif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n      BOARD_REVID=$($CLASS2_GET_BOARD_REVID | awk '{print $8;}')\n      if [ \"$((0x${BOARD_REVID#*x}))\" -ge \"$DVT_REVID\" ]; then\n        check_dvt_fan \"${fan_type[$i]}\"\n      else\n        check_evt_fan \"${fan_type[$i]}\"\n      fi\n    else\n      logger -t \"fan_check\" -p daemon.crit \"Cannot get the location of BMC\"\n    fi\n  done\n}\n\ninit_class1_fsc() {\n  target_fsc_config=\"\"\n  config_type=\"\"\n  server_type=$(get_server_type 1)\n  if [ \"$sys_config\" = \"A\" ]; then\n    if [[ $server_type -eq 4 ]]; then\n      config_type=\"GL\"\n      target_fsc_config=\"/etc/FSC_CLASS1_GL_config.json\"\n    else\n      config_type=\"1\"\n      target_fsc_config=\"/etc/FSC_CLASS1_type1_config.json\"\n    fi\n  elif [ \"$sys_config\" = \"B\" ]; then\n    if [[ $server_type -eq 2 ]]; then\n      board_type_1ou=$(get_1ou_board_type slot1)\n      case $board_type_1ou in\n      8)\n        config_type=\"8\"\n        target_fsc_config=\"/etc/FSC_CLASS1_type8_config.json\"\n        ;;\n      2)\n        config_type=\"HD\"\n        target_fsc_config=\"/etc/FSC_CLASS1_HD_RBF_config.json\"\n        ;;\n      *)\n        config_type=\"HD\"\n        target_fsc_config=\"/etc/FSC_CLASS1_HD_config.json\"\n        ;;\n      esac\n    else\n      config_type=\"DPV2\"\n      target_fsc_config=\"/etc/FSC_CLASS1_DPV2_config.json\"\n    fi\n  elif [ \"$sys_config\" = \"C\" ]; then\n    if [[ $server_type -eq 4 ]]; then\n      config_type=\"GL\"\n      target_fsc_config=\"/etc/FSC_CLASS1_GL_config.json\"\n    else\n      board_type_1ou=$(get_1ou_board_type slot1)\n      case $board_type_1ou in\n        4)\n          config_type=\"VF\"\n          target_fsc_config=\"/etc/FSC_CLASS1_type3_10_config.json\"\n          ;;\n        *)\n          logger -t \"fan_check\" -p daemon.crit \"Fail to get server type, run with the default fan config\"\n          config_type=\"1\"\n          target_fsc_config=\"/etc/FSC_CLASS1_type1_config.json\"\n          ;;\n      esac\n    fi\n  else\n    config_type=\"1\"\n    target_fsc_config=\"/etc/FSC_CLASS1_type1_config.json\"\n  fi\n\n  ### Greatlakes does not have formal fan table, run default fan table(fix 70% PWM)\n    # Todo: After get the Greatlakes formal fan table, need to Check the server type\n  if [[ $server_type -eq 4 ]]; then\n    config_type=\"GL\"\n    target_fsc_config=\"/etc/FSC_CLASS1_GL_config.json\"\n  fi\n\n  ln -s ${target_fsc_config} ${default_fsc_config_path}\n  $KV_CMD set sled_system_conf \"Type_${config_type}\" persistent\n}\n\ninit_class2_fsc() {\n  ln -s /etc/FSC_CLASS2_config.json ${default_fsc_config_path}\n  $KV_CMD set sled_system_conf \"Type_17\" persistent\n}\n\nstart_sled_fsc() {\n  check_fan_type\n\n  echo \"Setup fscd for fby35...\"\n  #Wait for sensord ready\n  for _ in {1..5}; do\n    sleep 3\n    if [ \"$($KV_CMD get bmc_sensor231)\" != \"\" ]; then\n      break\n    fi\n  done\n\n  runsv /etc/sv/fscd > /dev/null 2>&1 &\n\n  #boost fans if one of the blades is not present\n  reload_sled_fsc\n}\n\nreload_sled_fsc() {\n  if [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n    #The BMC of class2 need to check the present status from BB BIC\n    slot1_prsnt=$(bic-util slot1 0xe0 0x2 \"$IANA_ID\" 0x10 0xe0 0x41 \"$IANA_ID\" 0x0 15 | awk '{print $12}')\n    slot3_prsnt=$(bic-util slot1 0xe0 0x2 \"$IANA_ID\" 0x10 0xe0 0x41 \"$IANA_ID\" 0x0 3 | awk '{print $12}')\n    if [ \"$slot1_prsnt\" = \"01\" ] || [ \"$slot3_prsnt\" = \"01\" ]; then\n      run_fscd=false\n    else\n      run_fscd=true\n    fi\n  else\n    cnt=$(get_all_server_prsnt)\n\n    #Check number of slots\n    sys_config=\"$($KV_CMD get sled_system_conf persistent)\"\n    if [[ \"$sys_config\" =~ ^(Type_(1|10|VF))$ && \"$cnt\" -eq 4 ]]; then\n      run_fscd=true\n    elif [[ \"$sys_config\" =~ ^(Type_(DPV2|HD|GL))$ && \"$cnt\" -eq 2 ]]; then\n      run_fscd=true\n    elif [[ \"$sys_config\" == \"Type_8\" && \"$cnt\" -eq 1 ]]; then\n      run_fscd=true\n    else\n      run_fscd=false\n    fi\n  fi\n\n  if [ $run_fscd = false ]; then\n    echo \"mismatched system config, boost fans!\"\n    $KV_CMD set fan_mode_event 2 # boost_mode\n  else\n    $KV_CMD del fan_mode_event 2>/dev/null\n  fi\n\n  fscd_status=$(cat /etc/sv/fscd/supervise/stat)\n  if [ \"$fscd_status\" != \"run\" ]; then\n    sleep 1 && /usr/bin/sv restart fscd\n  fi\n}\n\nstart_fscd() {\n  if [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n    init_class1_fsc\n  elif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n    init_class2_fsc\n  else\n    echo -n \"Is board id correct(id=$bmc_location)?...\"\n    exit 255\n  fi\n\n  (start_sled_fsc &)\n}\n\ncase \"$1\" in\n  start)\n    echo \"Setup fan speed...\"\n    /usr/local/bin/fan-util --set 70\n    start_fscd\n  ;;\n\n  reload)\n    #boost fans if one of the blades is not present\n    reload_sled_fsc\n  ;;\n\n  *)\n    echo \"Usage: /etc/init.d/setup-fan.sh {start|reload}\"\n  ;;\nesac\n\nexit 0\n", "num_lines": 273}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\nSLOTS=\n\ninit_class2_gpiod() {\n  SLOTS=\"$SLOTS slot1\"\n}\n\ninit_class1_gpiod() {\n  if [ \"$(is_server_prsnt 1)\" = \"1\" ]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n\n  if [ \"$(is_server_prsnt 2)\" = \"1\" ]; then\n    SLOTS=\"$SLOTS slot2\"\n  fi\n\n  if [ \"$(is_server_prsnt 3)\" = \"1\" ]; then\n    SLOTS=\"$SLOTS slot3\"\n  fi\n\n  if [ \"$(is_server_prsnt 4)\" = \"1\" ]; then\n    SLOTS=\"$SLOTS slot4\"\n  fi\n}\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_gpiod\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_gpiod\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\nexec /usr/local/bin/gpiod $SLOTS\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for fby35... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          server-init\n# Required-Start:\n# Required-Stop:\n# Default-Start:\n# Default-Stop:\n# Short-Description: Provides a service to reinitialize the server\n#\n### END INIT INFO\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nclear_all_vr_cache(){\n  sb_vr_list=(\"c0h\" \"c4h\" \"ech\" \"c2h\" \"c6h\" \"c8h\" \"cch\" \"d0h\" \"96h\" \"9ch\" \"9eh\" \"8ah\" \"8ch\" \"8eh\")\n  rbf_vr_list=(\"b0h\" \"b4h\" \"c8h\")\n  for vr in \"${sb_vr_list[@]}\"; do\n    $KV_CMD del \"slot${slot_num}_vr_${vr}_crc\"\n    $KV_CMD del \"slot${slot_num}_vr_${vr}_new_crc\" persistent\n  done\n  for vr in \"${rbf_vr_list[@]}\"; do\n    $KV_CMD del \"slot${slot_num}_1ou_vr_${vr}_crc\"\n    $KV_CMD del \"slot${slot_num}_1ou_vr_${vr}_new_crc\" persistent\n  done\n}\n\n# stop the service first\nsv stop gpiod\n\nslot_num=$1\nPID=$$\nPID_FILE=\"/var/run/server-init.${slot_num}.pid\"\nbus=$((slot_num-1))\n\n# check if the script is running\n[ -r \"$PID_FILE\" ] && OLDPID=$(cat \"$PID_FILE\") || OLDPID=''\n\n# Set the current pid\necho \"$PID\" > \"$PID_FILE\"\n\n# kill the previous running script if it is existed\nif [ -n \"$OLDPID\" ] && (grep \"server-init\" /proc/$OLDPID/cmdline 1> /dev/null 2>&1) ; then\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 \"$OLDPID\"\n  pkill -KILL -f \"bic-cached -. slot${slot_num}\" >/dev/null 2>&1\n  pkill -KILL -f \"power-util slot${slot_num}\" >/dev/null 2>&1\n  pkill -KILL -f \"setup-fan\" >/dev/null 2>&1\nfi\nunset OLDPID\n\nprot_bus=$((slot_num+3))\nif [ \"$(is_server_prsnt \"$slot_num\")\" = \"0\" ]; then\n  disable_server_12V_power \"$slot_num\"\n  gpio_set_value \"FM_BMC_SLOT${slot_num}_ISOLATED_EN_R\" 0\n  rm -f \"/tmp/\"*\"fruid_slot${slot_num}\"*\n  rm -f \"/tmp/\"*\"sdr_slot${slot_num}\"*\n  $KV_CMD del \"slot${slot_num}_cpld_new_ver\"\n  $KV_CMD del \"slot${slot_num}_prot_ver\"\n  $KV_CMD del \"slot${slot_num}_is_m2_exp_prsnt\"\n  $KV_CMD del \"slot${slot_num}_get_1ou_type\"\n  $KV_CMD del \"fru${slot_num}_2ou_board_type\"\n  $KV_CMD del \"fru${slot_num}_sb_type\"\n  $KV_CMD del \"fru${slot_num}_sb_rev_id\"\n  $KV_CMD del \"fru${slot_num}_is_prot_prsnt\"\n  clear_all_vr_cache\n  i2c_device_delete \"${prot_bus}\" 0x50 > /dev/null 2>&1\n  set_nic_power\nelse\n  /usr/bin/sv start \"mctpd_${slot_num}\" > /dev/null 2>&1\n  /usr/bin/sv start ipmbd_${bus} > /dev/null 2>&1\n  /usr/local/bin/power-util \"slot${slot_num}\" 12V-on\n  i2c_device_add \"${prot_bus}\" 0x50 24c32 > /dev/null 2>&1\n  set_vf_gpio \"$slot_num\"\n  /usr/local/bin/bic-cached -s \"slot${slot_num}\"\n  /usr/local/bin/bic-cached -f \"slot${slot_num}\"\n  $KV_CMD set \"slot${slot_num}_sdr_thresh_update\" 1\n  /usr/bin/fw-util \"slot${slot_num}\" --version > /dev/null\nfi\n\n# reload fscd\n/etc/init.d/setup-fan.sh reload\n\n# start the services again\nsv start gpiod\n", "num_lines": 105}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start gpiointrd daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpiointrd for fby35...\"\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 20}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 5 \n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\ninit_class1_ipmb() {\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n}\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\nsleep 10\nulimit -q 1024000\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_ipmb\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"Done.\"\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd asti3c 0 7ec80010000\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd asti3c 1 7ec80010000\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd asti3c 2 7ec80010000\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd asti3c 3 7ec80010000\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd smbus 8 0x10\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Starting MCTP Rx/Tx Daemon..\"\n\ninit_class1_mctp() {\n  for slot_num in {1..4}; do\n    bus=$((slot_num))\n    runsv /etc/sv/mctpd_${bus} > /dev/null 2>&1 &\n    if [ \"$slot_num\" -eq 1 ] || [ \"$slot_num\" -eq 3 ]; then\n      slot_present=$(gpio_get PRSNT_MB_BMC_SLOT\"${slot_num}\"_BB_N)\n    else\n      slot_present=$(gpio_get PRSNT_MB_SLOT\"${slot_num}\"_BB_N)\n    fi\n    if [ \"$slot_present\" = \"1\" ]; then\n      usleep 50000\n      sv stop mctpd_${bus}\n      disable_server_12V_power \"${slot_num}\"\n    else\n      enable_server_i2c_bus \"${slot_num}\"\n    fi\n  done\n}\n\ninit_class2_mctp() {\n  runsv /etc/sv/mctpd_1 > /dev/null 2>&1 &\n}\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_mctp\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_mctp\nelse\n  echo -n \"setup_mctpd: Is board id correct(id=$bmc_location)?...\"\nfi\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device\n\nrunsv /etc/sv/mctpd_8 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\nBOARD_ID=$(get_bmc_board_id)\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\n\nif [ \"$BOARD_ID\" -eq \"$BMC_ID_CLASS1\" ]; then\n  runsv /etc/sv/mTerm2 > /dev/null 2>&1 &\n  runsv /etc/sv/mTerm3 > /dev/null 2>&1 &\n  runsv /etc/sv/mTerm4 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Address of SRAM that is used to store \"reboot by command\" flag. \nSRAM_BMC_REBOOT_BY_CMD=\"0x10015C04\"\n\n# Set 0x101 as flag for healthd logging reboot cause.\nval=$(devmem \"$SRAM_BMC_REBOOT_BY_CMD\" 32 2>/dev/null)\ndevmem \"$SRAM_BMC_REBOOT_BY_CMD\" 32 $((val | 0x101)) 2>/dev/null\n\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nMAX_RETRY=600         # wait 10 mins before give up\nNOT_READY_DAEMON=\"\"\n\ntotal_daemon=\"sensord ipmid fscd front-paneld gpiod gpiointrd ncsid healthd ipmbd_9\"\n\nsensord_list=\"flag_sensord_monitor flag_sensord_health\"\nipmid_list=\"flag_ipmid\"\nfront_paneld_list=\"flag_front_sys_status_led\"\ngpiod_list=\"flag_gpiod_server_pwr \"\ngpiointrd_list=\"flag_gpiointrd flag_gpiod_fru_miss\"\nncsid_list=\"flag_ncsid\"\nhealthd_list=\"flag_healthd_wtd flag_healthd_hb_led flag_healthd_crit_proc flag_healthd_cpu flag_healthd_mem flag_healthd_bmc_timestamp\"\nipmbd_9_list=\"flag_ipmbd_rx_9 flag_ipmbd_res_9 flag_ipmbd_req_9\"\n\ncheck_daemon_flag() {\n  flag_list=$1\n\n  for flag_name in $flag_list\n  do\n    result=\"$($KV_CMD get \"$flag_name\")\"\n    if [ \"$result\" != \"1\" ] || [ \"$result\" = \"\" ]; then\n      echo \"$flag_name\"\n      break\n    fi\n  done\n}\n\ncheck_daemon_status() {\n  daemon_name=$1\n\n  #check slot present & BIC ready\n  if [ \"$daemon_name\" = \"mctpd_1\" ]; then\n    if [ \"$(is_sb_bic_ready 1)\" != \"1\" ]; then\n      return\n    fi\n  elif [ \"$daemon_name\" = \"mctpd_2\" ]; then\n    if [ \"$(is_sb_bic_ready 2)\" != \"1\" ]; then\n      return\n    fi\n  elif [ \"$daemon_name\" = \"mctpd_3\" ]; then\n    if [ \"$(is_sb_bic_ready 3)\" != \"1\" ]; then\n      return\n    fi\n  elif [ \"$daemon_name\" = \"mctpd_4\" ]; then\n    if [ \"$(is_sb_bic_ready 4)\" != \"1\" ]; then\n      return\n    fi\n  fi\n\n  daemon_status=\"$(sv status \"$daemon_name\" | grep 'run')\"\n  if [ \"$daemon_status\" = \"\" ]; then\n    echo \"$daemon_name\"\n  else\n    # check ready flag of each thread\n    if [ \"$daemon_name\" = \"sensord\" ]; then\n      not_ready=\"$(check_daemon_flag \"$sensord_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"ipmid\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmid_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"front-paneld\" ]; then\n      not_ready=\"$(check_daemon_flag \"$front_paneld_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"gpiod\" ]; then\n      not_ready=\"$(check_daemon_flag \"$gpiod_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"gpiointrd\" ]; then\n      not_ready=\"$(check_daemon_flag \"$gpiointrd_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"ncsid\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ncsid_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"healthd\" ]; then\n      not_ready=\"$(check_daemon_flag \"$healthd_list\" \"$daemon_name\")\"\n    elif [ \"$daemon_name\" = \"ipmbd_9\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmbd_9_list\" \"$daemon_name\")\"\n    else\n      return\n    fi\n    echo \"$not_ready\"\n  fi\n}\n\ncheck_bmc_ready() {\n  retry=0\n\n  while [ \"$retry\" -lt \"$MAX_RETRY\" ]\n  do\n\n    for daemon in $total_daemon\n    do\n      result=\"$(check_daemon_status \"$daemon\")\"\n\n      # daemon not ready\n      if [ \"$result\" = \"$daemon\" ]; then\n        NOT_READY_DAEMON=$daemon\n        break\n      elif [ \"$result\" != \"\" ]; then\n        NOT_READY_DAEMON=$daemon\n        NOT_READY_FLAG=$result\n        break\n      else\n        NOT_READY_DAEMON=\n      fi\n    done\n\n    # all daemons are ready\n    if [ \"$NOT_READY_DAEMON\" = \"\" ]; then\n      break\n    else\n      sleep 1\n      retry=$((retry+1))\n    fi\n  done\n\n  if [ \"$NOT_READY_DAEMON\" = \"\" ]; then\n    \"$KV_CMD\" set bmc_ready_flag 1\n    logger -s -p user.info -t ready-flag \"BMC is ready\"\n  else\n    logger -s -p user.info -t ready-flag \"daemon: $NOT_READY_DAEMON ($NOT_READY_FLAG) is not ready\"\n  fi\n}\n\necho \"check bmc ready...\"\ncheck_bmc_ready &\n", "num_lines": 127}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#This is workaround for IPV4 lost There is slim chance ipv4 lost when AC cycle.\n#DHCP Client can't get OFFER package from server.\n#This script is for reinitial ipv4 to prevnet it lost.\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ncheck_eth0_ipv4() {\n  for i in {1..10};\n  do\n    ip=$(ifconfig eth0 |grep \"inet addr\")\n    if [[ -z \"$ip\" ]]; then\n      pid=$(cat /var/run/dhclient.eth0.pid)\n      kill $pid\n      dhclient -d -pf /var/run/dhclient.eth0.pid eth0 > /dev/null 2>&1 &\n      sleep 3\n    else\n      break;\n    fi\n  done\n}\n\necho \"check eth0 ipv4...\"\ncheck_eth0_ipv4 &\n", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2023-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck source=common/recipes-utils/openbmc-utils/files/openbmc-utils.sh\n. /usr/local/bin/openbmc-utils.sh\n\nFRUS=(slot1 slot2 slot3 slot4 bmc)\n\nclear_vr_cache() {\n  local fru=$1\n  local list\n  local cache\n\n  if list=$(ls /mnt/data/kv_store/\"${fru}\"_*vr_*_crc 2>/dev/null); then\n    mapfile list <<< \"$list\"\n    for cache in \"${list[@]}\"; do\n      /usr/bin/kv del \"$(basename \"$cache\")\" persistent\n    done\n  fi\n}\n\nif [ \"$(is_bmc_por)\" -eq 1 ]; then\n  for i in \"${FRUS[@]}\"; do\n    clear_vr_cache \"$i\"\n  done\nfi\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config() {\n  TO_PWR_ON=0\n\n  if POR=$(kv get \"slot${1}_por_cfg\" persistent); then\n    if [ \"$POR\" = \"lps\" ]; then\n      if LS=$(kv get \"pwr_server${1}_last_state\" persistent); then\n        if [ \"$LS\" = \"on\" ]; then\n          TO_PWR_ON=1;\n        fi\n      else\n        TO_PWR_ON=$DEF_PWR_ON\n      fi\n    elif [ \"$POR\" = \"on\" ]; then\n      TO_PWR_ON=1;\n    fi\n  else\n    TO_PWR_ON=$DEF_PWR_ON\n  fi\n}\n\ninit_class2_server() {\n  if [ \"$(is_bmc_por)\" -eq 1 ]; then\n    check_por_config 1\n    if [ \"$(is_sb_bic_ready 1)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n      power-util slot1 on\n    fi\n  fi\n\n  show_sys_config -r > /dev/null\n}\n\ninit_class1_server() {\n  # Check whether it is fresh power on reset\n  if [ \"$(is_bmc_por)\" -eq 1 ]; then\n    # Disable clearing of PWM block on WDT SoC Reset\n    devmem_clear_bit \"$(scu_addr 70)\" 13\n\n    check_por_config 1\n    if [ \"$(is_sb_bic_ready 1)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n      power-util slot1 on\n    fi\n\n    check_por_config 2\n    if [ \"$(is_sb_bic_ready 2)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n      power-util slot2 on\n    fi\n\n    check_por_config 3\n    if [ \"$(is_sb_bic_ready 3)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n      power-util slot3 on\n    fi\n\n    check_por_config 4\n    if [ \"$(is_sb_bic_ready 4)\" = \"1\" ] && [ $TO_PWR_ON -eq 1 ]; then\n      power-util slot4 on\n    fi\n  fi\n}\n\n/usr/local/bin/sync_date.sh\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_server\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_server\nelse\n  echo \"Is board id correct(id=$bmc_location)?...\"\nfi\n", "num_lines": 108}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nMEDUSA_HSC_BUS=\"11\"\nLTC4282_ADDR=\"0x44\"\nADM1272_ADDR=\"0x1f\"\nLTC4287_ADDR=\"0x11\"\nLTC4282_CONTROL_REG=\"0x00\"\nLTC4282_ADJUST_REG=\"0x11\"\nLTC4287_CONTROL_REG=\"0x47\"\nMEDUSA_48V_IO_EXP_ADDR=\"0x49\"\nLTC2992_ADDR=\"6e\"\nINA238_ADDR_PSU=\"44\"\nINA238_ADDR_GND=\"41\"\n\nfunction read_dev() {\n  local bus=$1\n  local addr=$2\n  local reg=$3\n  local val\n\n  for _ in {1..3}; do\n    if val=$(/usr/sbin/i2cget -f -y \"$bus\" \"$addr\" \"$reg\" 2>/dev/null); then\n      echo \"$val\"\n      return 0\n    fi\n  done\n\n  return 1\n}\n\nfunction init_48V_medusa() {\n  local medusa_adc_addr=(\"$INA238_ADDR_PSU\" \"$INA238_ADDR_GND\")\n  local medusa_adc_devs=(\"ina238\" \"ina238\")\n  local medusa_dev_addr=\"\"\n  local chip=\"\"\n\n  for i in \"${!medusa_adc_addr[@]}\"; do\n    if read_dev \"$MEDUSA_HSC_BUS\" 0x\"${medusa_adc_addr[\"$i\"]}\" 0 >/dev/null; then\n      medusa_dev_addr=\"$MEDUSA_HSC_BUS\"-00\"${medusa_adc_addr[\"$i\"]}\"\n      if [ ! -L \"${SYSFS_I2C_DEVICES}/$medusa_dev_addr/driver\" ]; then\n        chip=\"${medusa_adc_devs[\"$i\"]}\"\n        i2c_device_add \"$MEDUSA_HSC_BUS\" 0x\"${medusa_adc_addr[\"$i\"]}\" \"${medusa_adc_devs[\"$i\"]}\"\n      fi\n    else\n      chip=\"ltc2992\"\n    fi\n  done\n\n  kv set medusa_adc_chip \"$chip\"\n}\n\nfunction init_class1_dev() {\n  #create the device of the inlet/outlet temp.\n  i2c_device_add 12 0x4e lm75\n  i2c_device_add 12 0x4f lm75\n\n  #create the device of bmc/bb fru.\n  i2c_device_add 11 0x51 24c128\n  i2c_device_add 11 0x54 24c128\n\n  local medusa_addr=\"\"\n  local chip=\"\"\n  local load_driver=false\n\n  # Get register from different address to determine HSC chip\n\n  if read_dev $MEDUSA_HSC_BUS $LTC4287_ADDR 0x1 >/dev/null; then\n    if curr_val=$(read_dev $MEDUSA_HSC_BUS $LTC4287_ADDR $LTC4287_CONTROL_REG); then\n      set_oc_auto_retry=$((curr_val | (0x7 << 3)))\n      /usr/sbin/i2cset -y $MEDUSA_HSC_BUS $LTC4287_ADDR $LTC4287_CONTROL_REG \"$set_oc_auto_retry\"\n    fi\n    chip=\"ltc4287\"\n    medusa_addr=$LTC4287_ADDR\n    load_driver=true\n  elif read_dev $MEDUSA_HSC_BUS $ADM1272_ADDR 0x1 >/dev/null; then\n    chip=\"adm1272\"\n    medusa_addr=$ADM1272_ADDR\n    load_driver=true\n  elif read_dev $MEDUSA_HSC_BUS $LTC4282_ADDR 0 >/dev/null; then\n    if curr_val=$(read_dev $MEDUSA_HSC_BUS $LTC4282_ADDR $LTC4282_CONTROL_REG); then\n      set_oc_auto_retry=$((curr_val | (0x1 << 2)))\n      /usr/sbin/i2cset -y $MEDUSA_HSC_BUS $LTC4282_ADDR $LTC4282_CONTROL_REG \"$set_oc_auto_retry\"\n    fi\n    chip=\"ltc4282\"\n    medusa_addr=$LTC4282_ADDR\n    load_driver=true\n  else\n    load_driver=false\n  fi\n\n  if [ \"$load_driver\" = true ]; then\n    i2c_device_add $MEDUSA_HSC_BUS $medusa_addr $chip\n    if [ \"$chip\" == \"ltc4282\" ]; then\n      if curr_val=$(read_dev $MEDUSA_HSC_BUS $LTC4282_ADDR $LTC4282_ADJUST_REG); then\n        set_12bit_mode=$((curr_val & ~0x1))\n        /usr/sbin/i2cset -f -y $MEDUSA_HSC_BUS $LTC4282_ADDR $LTC4282_ADJUST_REG \"$set_12bit_mode\"\n      fi\n    fi\n  fi\n\n  kv set medusa_hsc_conf $chip persistent\n\n  # check nic power to see if it's need to be set to standby mode\n  set_nic_power\n}\n\nfunction init_class2_dev() {\n  #create the device of the outlet temp.\n  i2c_device_add 2 0x4f lm75\n  i2c_device_add 12 0x4f lm75\n\n  #create the device of bmc/nic fru.\n  i2c_device_add 11 0x51 24c128\n  i2c_device_add 11 0x54 24c128\n}\n\nfunction init_exp_dev() {\n  for i in {1..4}; do\n    bmc_location=$(get_bmc_board_id)\n    if [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n      if [ \"$(is_server_prsnt \"$i\")\" == \"0\" ]; then\n        continue\n      fi\n      enable_server_i2c_bus \"$i\"\n    fi\n    cpld_bus=$(get_cpld_bus \"$i\")\n    type_2ou=$(get_2ou_board_type \"$cpld_bus\")\n    # check DPv2 x8 present\n    prsnt_x8=$((type_2ou & 0x7))\n    if [ \"$prsnt_x8\" -eq \"7\" ]; then\n      i2c_device_add \"$cpld_bus\" 0x51 24c128\n    fi\n    # EEPROM on PRoT module\n    if [ \"$(is_prot_prsnt \"$i\")\" == \"1\" ]; then\n      i2c_device_add \"$cpld_bus\" 0x50 24c32\n    fi\n    # IO-exp on VF2\n    set_vf_gpio \"$i\"\n  done\n}\n\necho \"Setup devs for fby35...\"\n\n#create the device of mezz card\ni2c_device_add 8 0x1f tmp421\ni2c_device_add 8 0x50 24c32\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_dev\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_dev\nelse\n  echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\n# Check if the Medusa IO expender exist\nif read_dev $MEDUSA_HSC_BUS $MEDUSA_48V_IO_EXP_ADDR 0 >/dev/null; then\n  init_48V_medusa\nfi\n\ninit_exp_dev\n\necho \"Done.\"\n", "num_lines": 188}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nfunction get_sel_time_from_server {\n  local BOARD_ID=$(get_bmc_board_id)\n  local output=\"\"\n  local snum=0\n\n  if [ \"$BOARD_ID\" -eq \"$BMC_ID_CLASS2\" ]; then\n    output=\"$(/usr/local/bin/me-util slot1 0x28 0x48)\"\n    [ ${#output} == 12 ] && snum=1\n  else\n    for i in $(seq 1 4)\n    do\n      if [[ $(is_server_prsnt \"$i\") == \"1\" ]] ; then\n        # Use standard IPMI command 'get-sel-time' to read RTC time\n        output=$(/usr/local/bin/me-util \"slot$i\" 0x28 0x48)\n        if [ ${#output} == 12 ]; then\n          snum=$i\n          break\n        fi\n      fi\n    done\n  fi\n\n  # return IPMI \"Get sel time\" command output, or return empty string if command failed\n  [ ${#output} == 12 ] && echo \"$output\" || echo \"\"\n\n  return \"$snum\"\n}\n\nfunction do_sync {\n  local sel_time=$1\n  date -s @$((16#$(echo \"$sel_time\" | awk '{print $4$3$2$1}')))\n  test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  kv set date_sync 1\n}\n\n# Sync BMC's date with one of the four servers\nfunction sync_date {\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    output=\"$(/usr/bin/kv get time_sync)\"\n    if [ -n \"${output}\" ] ; then\n      # Server Time Sync by IPMI command\n      if [ ${#output} == 11 ] ; then\n        echo Syncing up BMC time with server...\n        do_sync \"$output\"\n      fi\n    else\n      output=$(get_sel_time_from_server)\n      num=$?\n      if [ -n \"$output\" ]; then\n        echo Syncing up BMC time with server$num...\n        do_sync \"$output\"\n      fi\n    fi\n  else\n    test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n    kv set date_sync 1\n  fi\n}\n\nsync_date\n", "num_lines": 84}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 0\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 2\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 3\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2022-present Facebook. All Rights Reserved\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\ninit_class1_pldm() {\n  for slot_num in {1..4}; do\n    bus=$((slot_num))\n    runsv /etc/sv/pldmd_${bus} > /dev/null 2>&1 &\n  done\n}\n\ninit_class2_pldm() {\n  runsv /etc/sv/pldmd_1 > /dev/null 2>&1 &\n}\n\necho -n \"Starting PLDMD Rx/Tx Daemon..\"\n\nulimit -q 1024000\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_pldm\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_pldm\nelse\n  echo -n \"setup-pldmd: Is board id correct(id=$bmc_location)?...\"\nfi\n\necho \"done.\"\n\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck source=meta-facebook/meta-fby35/recipes-fby35/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nSLOTS=\n\ninit_class2_sensord() {\n  SLOTS=(slot1 bmc nic)\n}\n\ninit_class1_sensord() {\n  sys_config=\"$($KV_CMD get sled_system_conf persistent)\"\n  if [[ \"$sys_config\" == \"Type_8\" ]]; then\n    SLOTS=(slot1)\n  elif [[ \"$sys_config\" =~ ^(Type_(DPV2|HD|GL))$ ]]; then\n    SLOTS=(slot1 slot3)\n  else\n    SLOTS=(slot1 slot2 slot3 slot4)\n  fi\n\n  SLOTS+=(bmc nic)\n}\n\nbmc_location=$(get_bmc_board_id)\nif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  #The BMC of class2\n  init_class2_sensord\nelif [ \"$bmc_location\" -eq \"$BMC_ID_CLASS1\" ]; then\n  #The BMC of class1\n  init_class1_sensord\nelse\n  /bin/echo -n \"Is board id correct(id=$bmc_location)?...\"\nfi\n\nSENSORD_HOTSWAP_SUPPORT=1 exec /usr/local/bin/sensord \"${SLOTS[@]}\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util slotX --version\" once to store vr information before sensor monitoring \necho \"Get MB FW version... \"\n\nbmc_location=$(get_bmc_board_id)\nif ! [ \"$bmc_location\" -eq \"$BMC_ID_CLASS2\" ]; then\n  if [[ $(is_sb_bic_ready 1) == \"1\" ]]; then\n    /usr/bin/fw-util slot1 --version vr > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 2) == \"1\" ]]; then\n    /usr/bin/fw-util slot2 --version vr > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 3) == \"1\" ]]; then\n    /usr/bin/fw-util slot3 --version vr > /dev/null\n  fi\n\n  if [[ $(is_sb_bic_ready 4) == \"1\" ]]; then\n    /usr/bin/fw-util slot4 --version vr > /dev/null\n  fi\n  # Get the MFR ID\n  MFR_ID=$(i2cget -y 11 0x40 0x99 i 4) > /dev/null\n  # For ADM1278, \"0x41 0x44 0x49\" = \"ADI\"\n  if [[ \"$MFR_ID\" == \"0x03 0x41 0x44 0x49\" ]]; then\n    #enable the register of the temperature of hsc\n    /usr/sbin/i2cset -y 11 0x40 0xd4 0x1c 0x3f i\n\n    # Clear PEAK_PIN & PEAK_IOUT register\n    /usr/sbin/i2cset -y 11 0x40 0xd0 0x0000 w\n    /usr/sbin/i2cset -y 11 0x40 0xda 0x0000 w\n  fi\nelse\n  /usr/bin/fw-util slot1 --version vr > /dev/null\nfi\n\necho -n \"Setup sensor monitoring for FBYV35... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 71}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Setting for reboot and clear GPIO\n# SCU60\nval=$(devmem 0x1e6e2060 2>/dev/null)\ndevmem 0x1e6e2060 32 $((val | 0x1000000))\n# SCU70\nval=$(devmem 0x1e6e2070 2>/dev/null)\ndevmem 0x1e6e2070 32 $((val | 0x200))\n# WDT1C\nval=$(devmem 0x1e78501C 2>/dev/null)\ndevmem 0x1e78501C 32 $((val | 0x1000000))\n# WDT20\nval=$(devmem 0x1e785020 2>/dev/null)\ndevmem 0x1e785020 32 $((val | 0x200))\n\nexec /usr/local/bin/setup-gpio\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\nexec /usr/local/bin/front-paneld", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon...\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 0 1\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\necho -n \"Starting IPMB Rx/Tx Daemon ...\"\nulimit -q 1024000\n\ndeclare -a ipmbd_list\nipmbd_list=(0 4)\nfor ipmb in \"${ipmbd_list[@]}\"\ndo\n    runsv \"/etc/sv/ipmbd_$ipmb\" &> /dev/null &\ndone\n\necho \"Done\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\nexec /usr/local/bin/pemd pem1 pem2 pem3 pem4\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# If either one pem is present, pemd will start\nif [ \"$(wedge_power_supply_type)\" != \"PEM\" ]; then\n    echo \"Skip pemd as PEM is not present\"\n    exit 0\nfi\n\n# shellcheck disable=SC2039\necho -n \"Setup pem monitoring for Fuji... \"\n\nrunsv /etc/sv/pemd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nexport SENSORD_HOTSWAP_SUPPORT=1\nARGS=\"scm smb pim1 pim2 pim3 pim4 pim5 pim6 pim7 pim8 psu1 psu2 psu3 psu4\"\n#shellcheck disable=SC2086\nexec /usr/local/bin/sensord $ARGS\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n#shellcheck disable=SC1091\nsource /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for FUJI... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..8)]\" >&2\n}\n\n# Top FCM    (BUS=64) PWM 1 ~ 4 control Fan 1 3 5 7\n# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fan 2 4 6 8\nshow_pwm()\n{\n    pwm=\"$(i2c_device_sysfs_abspath \"$1\"-0033)/fan$2_pwm\"\n    val=$(head -n 1 < \"$pwm\")\n\n    # Convert the percentage to our 1/64th level (0-63) and round.\n    echo \"$(( (val * 1000 / 63 + 5) /10 ))%\"\n}\n\nshow_rpm()\n{\n    front_rpm=\"$(i2c_device_sysfs_abspath \"$1\"-0033)/fan$((($2 * 2 - 1)))_input\"\n    rear_rpm=\"$(i2c_device_sysfs_abspath \"$1\"-0033)/fan$((($2 * 2)))_input\"\n    echo \"$(cat \"$front_rpm\"), $(cat \"$rear_rpm\")\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5 6 7 8\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 9 ]; then\n        echo \"Fan $1: not a valid Fan Unit\"\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    FAN=\"${fan}\"\n\n    if [ $((fan % 2)) -eq 0 ]; then\n      BUS=\"72\"\n      UNIT=$((FAN / 2 ))\n    else\n      BUS=\"64\"\n      FAN=$((FAN / 2 ))\n      UNIT=$((FAN + 1))\n    fi\n\n    echo \"Fan $fan RPMs: $(show_rpm $BUS $UNIT), ($(show_pwm $BUS $UNIT))\"\ndone\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC2034\ndefault_fsc_config=\"/etc/fsc-config.json\"\n\necho \"Setting fan speed to 50%...\"\n/usr/local/bin/set_fan_speed.sh 50\necho \"Done setting fan speed\"\n\nfscd_enable=1\n\nboard_ver=$(wedge_board_rev)\nif [ \"$board_ver\" == \"BOARD_FUJI_EVT1\" ] || \\\n[ \"$board_ver\" == \"BOARD_FUJI_EVT2\" ] || \\\n[ \"$board_ver\" == \"BOARD_FUJI_EVT3\" ]; then\n    fscd_enable=0\n    echo \"For EVT board, Setting fan speed to 70%...\"\n    /usr/local/bin/set_fan_speed.sh 70\nfi\n\nif [ $fscd_enable -eq 0 ]; then\n    echo \"Running fan at the fixed speed.\"\nelse\n    echo \"Starting fscd...\"\n    runsv /etc/sv/fscd > /dev/null 2>&1 &\nfi\necho \"done.\"\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..8)> \" >&2\n}\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# check percent argument be number\nif ! [[ $1 =~ ^[0-9]+$ ]]; then\n    echo \"Percent argument can be only integer number\"\n    usage\n    exit 1\nfi\n# check percent in range 0-100\nif [ $1 -lt 0 ] || [ $1 -gt 100 ]; then\n    echo \"Percent argument out of range\"\n    usage\n    exit 1\nfi\n\n# Top FCM    (BUS=64) PWM 1 ~ 4 control Fan 1 3 5 7\n# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fan 2 4 6 8\nBUS=\"64 72\"\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 9 ]; then\n        echo \"Fan $2: not a valid Fan Unit\"\n        exit 1\n    fi\n\n    FAN=\"$2\"\n\n    if [ $((FAN % 2)) -eq 0 ]; then\n      BUS=\"72\"\n      FAN_UNIT=$((FAN / 2 ))\n    else\n      BUS=\"64\"\n      FAN=$((FAN / 2 ))\n      FAN_UNIT=$((FAN + 1))\n    fi\nfi\n    # Convert the percentage to our 1/64th level (0-63).\n    step=$(( ($1 * 630 + 5) / 1000 ))\ncnt=1\n\nfor bus in ${BUS}; do\n    for unit in ${FAN_UNIT}; do\n        pwm=\"$(i2c_device_sysfs_abspath ${bus}-0033)/fan${unit}_pwm\"\n        echo \"$step\" > \"${pwm}\"\n\n    if [ \"$#\" -eq 1 ]; then\n        echo \"Successfully set fan $cnt speed to $1%\"\n        cnt=$((cnt+1))\n    else\n        echo \"Successfully set fan $2 speed to $1%\"\n    fi\n    done\ndone\n", "num_lines": 86}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# I2C paths of CPLDs\n#\n#shellcheck disable=SC2034\n#shellcheck disable=SC1091\n. /usr/local/bin/i2c-utils.sh\n\nSCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-0035)\nSMBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-003e)\nTOP_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 64-0033)\nBOTTOM_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 72-0033)\n\n#\n# FUJI PDB has different I2C address depending on its version, but\n# trying I2C address everytime we need to access, is not efficient and\n# it also breaks provisioning logic that runs with bash -x option.\n# So we will detect it once one the fly, and save the info in /tmp dir.\n#\n_PDB_L_OLD_CACHE=/tmp/pdb_l_old\n_PDB_L_NEW_CACHE=/tmp/pdb_l_new\n_PDB_R_OLD_CACHE=/tmp/pdb_r_old\n_PDB_R_NEW_CACHE=/tmp/pdb_r_new\n_PDB_L_OLD_ADDR=$(i2c_device_sysfs_abspath 53-0060)\n_PDB_L_NEW_ADDR=$(i2c_device_sysfs_abspath 55-0060)\n_PDB_R_OLD_ADDR=$(i2c_device_sysfs_abspath 61-0060)\n_PDB_R_NEW_ADDR=$(i2c_device_sysfs_abspath 63-0060)\n\n#\n# If previously Left PDB was detected, used that cached info,\n# otherwise try I2C to detect the Left PDB I2C address\n#\nif [ -f \"$_PDB_L_NEW_CACHE\" ]; then\n  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_NEW_ADDR\nelif [ -f \"$_PDB_L_OLD_CACHE\" ]; then\n  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_OLD_ADDR\nelif i2cget -y -f 55 0x60 > /dev/null;then\n  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_NEW_ADDR\n  touch $_PDB_L_NEW_CACHE\nelse\n  LEFT_PDBCPLD_SYSFS_DIR=$_PDB_L_OLD_ADDR\n  touch $_PDB_L_OLD_CACHE\nfi\n\n#\n# If previously Right PDB was detected, used that cached info,\n# otherwise try I2C to detect the Right PDB I2C address\n#\nif [ -f \"$_PDB_R_NEW_CACHE\" ]; then\n  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_NEW_ADDR\nelif [ -f \"$_PDB_R_OLD_CACHE\" ]; then\n  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_OLD_ADDR\nelif i2cget -y -f 63 0x60 > /dev/null;then\n  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_NEW_ADDR\n  touch $_PDB_R_NEW_CACHE\nelse\n  RIGHT_PDBCPLD_SYSFS_DIR=$_PDB_R_OLD_ADDR\n  touch $_PDB_R_OLD_CACHE\nfi\n\n#\n# I2C paths of FPGAs\n#\nIOBFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 13-0035)\nPIM1_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 80-0060)\nPIM2_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 88-0060)\nPIM3_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 96-0060)\nPIM4_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 104-0060)\nPIM5_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 112-0060)\nPIM6_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 120-0060)\nPIM7_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 128-0060)\nPIM8_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 136-0060)\n\nPWR_USRV_SYSFS=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable\"\nPWR_USRV_FORCE_OFF=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_force_off\"\nPIM_RST_SYSFS=\"${SMBCPLD_SYSFS_DIR}\"\n\n# 48V DC PSU P/N\nDELTA_48V=\"0x45 0x43 0x44 0x32 0x35 0x30 0x31 0x30 0x30 0x31 0x35\"\nLITEON_48V=\"0x44 0x44 0x2d 0x32 0x31 0x35 0x32 0x2d 0x32 0x4c\"\n\ni2c_detect_address() {\n   bus=\"$1\"\n   addr=\"$2\"\n   if [ -n \"$3\" ]; then\n      retries=\"$3\"\n   else\n      retries=5\n   fi\n\n   retry=0\n\n   while [ \"$retry\" -lt \"$retries\" ]; do\n      if i2cget -y -f \"$bus\" \"$addr\" &> /dev/null; then\n         return 0\n      fi\n      usleep 50000\n      retry=$((retry + 1))\n   done\n   \n   echo \"setup-i2c : i2c_detect not found $bus - $addr\" > /dev/kmsg\n   return 1\n}\n\nwedge_is_us_on() {\n    local val0 val1\n\n    val0=$(head -n 1 < \"$PWR_USRV_SYSFS\" 2> /dev/null)\n    val1=$(head -n 1 < \"$PWR_USRV_FORCE_OFF\" 2> /dev/null)\n\n    if [ \"$val0\" == \"0x1\" ] && [ \"$val1\" == \"0x1\" ] ; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n\n    return 0\n}\n\nwedge_board_rev() {\n    board_ver=$(i2cget -f -y 12 0x3e 0x0 | tr -d '\\n' ; \\\n                i2cget -f -y 13 0x35 0x3 | cut -d'x' -f2)\n    case $((board_ver)) in\n        $((0x0043)))  echo \"BOARD_FUJI_EVT1\"              ;;\n        $((0x0041)))  echo \"BOARD_FUJI_EVT2\"              ;;\n        $((0x0042)))  echo \"BOARD_FUJI_EVT3\"              ;;\n        $((0x0343)))  echo \"BOARD_FUJI_DVT1/DVT2\"         ;;\n        $((0x0545)))  echo \"BOARD_FUJI_PVT1/PVT2\"         ;;\n        $((0x0747)))\n          # MP0-SKU1, MP1-SKU7 have same value,\n          # need to indicate from UCD90160A address \n          if i2c_detect_address 5 0x35; then\n            echo \"BOARD_FUJI_MP0-SKU1\"\n          elif i2c_detect_address 5 0x66; then\n            echo \"BOARD_FUJI_MP1-SKU7\"\n          else\n            echo \"BOARD_FUJI_UNDEFINED_${board_ver}\"\n          fi\n          ;;\n        $((0x2747)))  \n          # MP0-SKU2, MP1-SKU6 have same value,\n          # need to indicate from UCD90160 address\n          if i2c_detect_address 5 0x35; then\n            echo \"BOARD_FUJI_MP0-SKU2\"\n          elif i2c_detect_address 5 0x68; then\n            echo \"BOARD_FUJI_MP1-SKU6\"\n          else\n            echo \"BOARD_FUJI_UNDEFINED_${board_ver}\"\n          fi\n          ;;\n        $((0x1747)))  echo \"BOARD_FUJI_MP1-SKU1\"          ;;\n        $((0x3747)))  echo \"BOARD_FUJI_MP1-SKU2\"          ;;\n        $((0x0757)))  echo \"BOARD_FUJI_MP1-SKU3\"          ;;\n        $((0x0767)))  echo \"BOARD_FUJI_MP1-SKU4\"          ;;\n        $((0x0777)))  echo \"BOARD_FUJI_MP1-SKU5\"          ;;\n        $((0x1040)))  echo \"BOARD_FUJI_MP2-SKU1\"          ;;\n        $((0x1044)))  echo \"BOARD_FUJI_MP2-SKU2\"          ;;\n        $((0x1042)))  echo \"BOARD_FUJI_MP2-SKU3\"          ;;\n        $((0x1046)))  echo \"BOARD_FUJI_MP2-SKU4\"          ;;\n        *)  # New board version need to be added here\n            echo \"BOARD_FUJI_UNDEFINED_${board_ver}\"\n            ;;\n    esac\n}\n\nwedge_power_supply_type() {\n\n    if i2cget -y -f 48 0x58 0x9a s &> /dev/null;then    # PSU1\n        is_psu1_48v=$(i2cget -y -f 48 0x58 0x9a s &)\n    elif i2cget -y -f 49 0x5a 0x9a s &> /dev/null;then  # PSU2\n        is_psu2_48v=$(i2cget -y -f 49 0x5a 0x9a s &)\n    elif i2cget -y -f 56 0x58 0x9a s &> /dev/null;then  # PSU3\n        is_psu3_48v=$(i2cget -y -f 56 0x58 0x9a s &)\n    elif i2cget -y -f 57 0x5a 0x9a s &> /dev/null;then  # PSU4\n        is_psu4_48v=$(i2cget -y -f 57 0x5a 0x9a s &)\n    fi\n\n    # Detect 48V DC PSU\n    if [[ \"$is_psu1_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu1_48v\" = \"$LITEON_48V\" ||\n        \"$is_psu2_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu2_48v\" = \"$LITEON_48V\" ||\n        \"$is_psu3_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu3_48v\" = \"$LITEON_48V\" ||\n        \"$is_psu4_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu4_48v\" = \"$LITEON_48V\" ]];then\n            power_type=\"PSU48\"\n    else\n            power_type=\"PSU\"\n    fi\n    echo $power_type\n}\n\nwedge_prepare_cpld_update() {\n    echo \"Stop fscd service.\"\n    if ! systemctl stop fscd ; then\n        echo \"Error: FSCD fails to exit properly!\"\n        return 1\n    fi\n\n    echo \"Disable watchdog.\"\n    if ! /usr/local/bin/wdtcli stop ; then\n        echo \"Error: Failed to disable watchdog!\"\n        return 1\n    fi\n\n    echo \"Set fan speed to 40%.\"\n    set_fan_speed.sh 40\n    \n    return 0\n}\n\nwdt_set_timeout() {\n    echo \"Stop fscd service.\"\n    /bin/systemctl stop fscd\n\n    echo \"Setting WTD1 timeout value to $1 seconds.\"\n    /usr/local/bin/wdtcli set-timeout \"$1\"\n\n    echo \"Restore fscd service.\"\n    /bin/systemctl start fscd\n}\n", "num_lines": 225}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nCPLD_TYPE=\"$2\"\nUPDATE_IMG=\"$4\"\n\nchip_ver=$(aspeed_g6_chip_ver)\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_gpio.so\nDLL_AST_JTAG_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\nusage() {\n    echo \"Usage: $prog -s <CPLD_TYPE> -f <img_file> <hw|sw|i2c>\"\n    echo\n    echo \"CPLD_TYPE: ( FCM-T | FCM-B | SCM | SMB | PWR-L | PWR-R | PFR)\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"  JBC file for Intel PFR FPGA update\"\n    echo \"  HEX file for i2c mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo \"  i2c: Program the CPLD using hardware IP core mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 5 ]; then\n    usage\n    exit 1\nfi\n\nenable_fct-t_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   0\n    gpio_set_value BMC_FCM_1_SEL          0\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n}\n\nenable_pfr_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       0\n}\n\nenable_fct-b_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   0\n    gpio_set_value BMC_FCM_2_SEL          0\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n}\n\nenable_smb_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     0\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n}\n\nenable_scm_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 0\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n}\n\nenable_pdb-l_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n    gpio_set_value PDB_L_HITLESS    0\n}\n\nenable_pdb-r_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        1\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n    gpio_set_value PDB_R_HITLESS    0\n}\n\ndisable_jtag_chain(){\n    gpio_set_value BMC_JTAG_MUX_IN        0\n    gpio_set_value FCM_1_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_1_SEL          1\n    gpio_set_value FCM_2_CPLD_JTAG_EN_N   1\n    gpio_set_value BMC_FCM_2_SEL          1\n    gpio_set_value SYS_CPLD_JTAG_EN_N     1\n    gpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\n    gpio_set_value BMC_FPGA_JTAG_EN       1\n    gpio_set_value PDB_L_HITLESS    1\n    gpio_set_value PDB_R_HITLESS    1\n}\n\n\ntrap 'rm -rf /tmp/fcmcpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/fcmcpld_update\n\nif ! wedge_prepare_cpld_update; then\n    echo \"Aborting CPLD upgrade\"\n    echo \"The FSCD may be closed incompletely,\"\n    echo \"Please check the watchdog timeout, to prevent system reboot.\"\n    exit 1\nfi\n\nif [ -e \"$UPDATE_IMG\" ];then\n    if [[  $CPLD_TYPE == \"FCM-T\" ]];then\n        enable_fct-t_jtag_chain\n    elif [[  $CPLD_TYPE == \"FCM-B\" ]];then\n        enable_fct-b_jtag_chain\n    elif [[  $CPLD_TYPE == \"PFR\" ]];then\n        enable_pfr_jtag_chain\n    elif [[  $CPLD_TYPE == \"SMB\" ]];then\n        enable_smb_jtag_chain\n    elif [[  $CPLD_TYPE == \"SCM\" ]];then\n        enable_scm_jtag_chain\n    elif [[  $CPLD_TYPE == \"PWR-L\" ]];then\n        enable_pdb-l_jtag_chain\n    elif [[  $CPLD_TYPE == \"PWR-R\" ]];then\n        enable_pdb-r_jtag_chain\n    else\n        echo 'argument '\"$CPLD_TYPE\"' is wrong'\n        exit 1\n    fi\nelse\n    echo 'argument '\"$UPDATE_IMG\"' not exist'\n    exit 1\nfi\n\nexpect=0\n\ncpld_update_sw_mode(){\n        for n in {1..5}\n        do\n                echo \"Program $CPLD_TYPE $n times\"\n                if [[  $CPLD_TYPE == \"PWR-L\" ]];then\n                # ispvm success return code is 1\n                expect=1\n                ispvm -f 1000 dll $DLL_PATH \"${UPDATE_IMG}\" --tdo PDB_L_JTAG_TDO --tdi PDB_L_JTAG_TDI --tms PDB_L_JTAG_TMS --tck PDB_L_JTAG_TCK\n                elif [[  $CPLD_TYPE == \"PWR-R\" ]];then\n                # ispvm success return code is 1\n                expect=1\n                ispvm -f 1000 dll $DLL_PATH \"${UPDATE_IMG}\" --tdo PDB_R_JTAG_TDO --tdi PDB_R_JTAG_TDI --tms PDB_R_JTAG_TMS --tck PDB_R_JTAG_TCK\n                elif [[  $CPLD_TYPE == \"PFR\" ]];then\n                jbi -aPROGRAM -ddo_real_time_isp=1 -W \"${UPDATE_IMG}\"\n                else\n                # ispvm success return code is 1\n                expect=1\n                ispvm -f 1000 dll $DLL_AST_JTAG_PATH \"${UPDATE_IMG}\"\n                fi\n\n                result=$?\n                if [ $result -eq $expect ]; then\n                        break\n                fi\n        done\n}\n\ncpld_update_i2c_mode(){\n        for n in {1..5}\n        do\n                echo \"Program $CPLD_TYPE $n times\"\n                if [[  $CPLD_TYPE == \"PWR-L\" ]];then\n                        cpldupdate-i2c 53 0x40 \"${UPDATE_IMG}\"\n                elif [[  $CPLD_TYPE == \"PWR-R\" ]];then\n                        cpldupdate-i2c 61 0x40 \"${UPDATE_IMG}\"\n                else\n                echo \"Only Power CPLD support I2C Mode !!!\"\n                fi\n                result=$?\n                if [ $result -eq $expect ]; then\n                        break\n                fi\n        done\n}\n\ncpld_update_hw_mode(){\n        if [ \"$chip_ver\" == \"A3\" ];then\n                cpldprog -p \"${UPDATE_IMG}\"\n        else\n                echo \"Only AST262x A3 chip can support HW Mode !!!\"\n                exit 1\n        fi\n        result=$?\n}\n\ncase $5 in\n    hw)\n        cpld_update_hw_mode\n        ;;\n    sw)\n        cpld_update_sw_mode\n        ;;\n    i2c)\n        cpld_update_i2c_mode\n        ;;\n    *)\n        # default: hw mode\n        cpld_update_hw_mode\n        ;;\nesac\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    echo \"Restarting fscd service.\"\n    systemctl start fscd\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    echo \"To prevent system reboot, keep watchdog disabled and fscd down.\"\n    exit 1\nfi\n", "num_lines": 270}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\n# shellcheck disable=SC2002\n. /usr/local/bin/openbmc-utils.sh\n\nfor index in 2 3 4 5 6 7 8 9\ndo\n    pim_path=${SMBCPLD_SYSFS_DIR}/pim$((index-1))_present_L\n    pim_prsnt=$(cat \"$pim_path\" 2> /dev/null | head -n 1)\n\n    #pimserial cache file doesn't exist, but pim is present\n    if [ ! -s /tmp/pim$((index))_serial.txt ] && [ \"${pim_prsnt}\" == 0x0 ]; then\n        /usr/local/bin/peutil $((index)) |grep Product|grep Serial|cut -d ' ' -f 4 > /tmp/pim$((index))_serial.txt\n    fi\n    serial=$(cat /tmp/pim$((index))_serial.txt)\n    echo PIM${index} : \"${serial}\"\ndone\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ninvalid_mac=\"00:00:00:00:00:00\"\n\n# From DVT Phase, MAC get from Chassis EEPROM\nmac=$(weutil  | grep '^Local MAC' | cut -d' ' -f3)\n\n# EVT Chassis can not get the MAC from Chassis EEPROM, insted of\n# get the MAC from SMB EEPROM.\nif [ \"$mac\" = \"$invalid_mac\" ]; then\n    mac=$(smbutil  | grep '^Local MAC' | cut -d' ' -f3)\nfi\n\n# get the MAC from u-boot environment\nethaddr=$(fw_printenv | grep \"^ethaddr=\" | cut -d'=' -f2)\n\nif [ -z \"$mac\" ]; then\n    if [ -n \"$ethaddr\" ]; then\n        # no MAC from EEPROM, use the one from u-boot environment\n        echo \"No MAC address from EEPROM: use $ethaddr from uboot-env\"\n        mac=\"$ethaddr\"\n    else\n        echo \"Error: unable to read MAC address from EEPROM or uboot-env!\"\n        exit 1\n    fi\nfi\n\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    # set the MAC from EEPROM back to u-boot environment so that\n    # u-boot can use it\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n\n#ifconfig eth0 hw ether $macifconfig\necho \"Update BMC eth0 MAC address to $mac\"\nip link set dev eth0 address \"$mac\"\nexit $?\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\nexitCode=0\n\ndump_fpga_version() {\n    local fpga_dir=$1\n    local fpga_name=$2\n\n    fpga_ver=$(head -n 1 \"${fpga_dir}/fpga_ver\" 2> /dev/null)\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        exit 1\n\n    fi\n    fpga_sub_ver=$(head -n 1 \"${fpga_dir}/fpga_sub_ver\" 2> /dev/null)\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        exit 1\n    fi\n\n    echo \"${fpga_name}: $((fpga_ver)).$((fpga_sub_ver))\"\n}\n\necho \"------IOBFPGA------\"\ndump_fpga_version \"${IOBFPGA_SYSFS_DIR}\" \"IOBFPGA\"\n\necho \"------DOMFPGA------\"\nfor num in $(seq 8); do\n    pim_var_name=\"PIM${num}_DOMFPGA_SYSFS_DIR\"\n    pim_fpga_dir=${!pim_var_name}\n\n    echo \"PIM $num:\"\n\n    pim_type=$(head -n1 \"${pim_fpga_dir}/board_ver\" 2> /dev/null)\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        echo \"DOMFPGA is not detected or PIM $num is not inserted\"\n    elif [ \"$((pim_type & 0x80))\" == 0 ]; then\n        dump_fpga_version \"${pim_fpga_dir}\" \"16Q DOMFPGA\"\n    elif [ \"$((pim_type & 0x80))\" == \"$((0x80))\" ]; then\n        dump_fpga_version \"${pim_fpga_dir}\" \"16O DOMFPGA\"\n    else\n        echo \"DOMFPGA is not detected or PIM $num is not inserted\"\n        exitCode=1\n    fi\n    usleep 50000\ndone\n\nif [ \"$exitCode\" -ne 0 ]; then\n    echo \"Not all DOMFPGA or PIM were detected/inserted. Please review the logs above.... exiting\"\n    exit 1\nfi\n\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# This tool is used to refresh dom fpga (parallel mode), after execution it will update all dom fpga firmware at the same time.\n# The command format is\n#\n# parallel_update_pims.sh <dom fpga image>\n#\n# SC2009: Consider using pgrep instead of grepping ps output.\n# because we dont have the pgrep, disable the SC2009 check\n# shellcheck disable=SC2009\n\nfpgaimg=$1\nlog_dir=/tmp/\ntmpfile=/tmp/domfpga\nDOM_FPGA_START=3\n\nparallel_fpga_update(){\n    # extend the image size to fit flash size\n    cp \"$fpgaimg\" \"$tmpfile\"\n    flashsize=$(flashrom -p linux_spi:dev=/dev/spidev$DOM_FPGA_START.0 | grep -i kB | xargs echo | cut -d '(' -f 2 | cut -d ' ' -f 0)\n    filesize=$(stat -c%s $tmpfile)\n    addsize=$(($((flashsize * 1024)) - filesize))\n\n    if [ $((addsize)) -gt 0 ];then\n        dd if=/dev/zero bs=\"$addsize\" count=1 | tr \"\\000\" \"\\377\" >> \"$tmpfile\"\n    fi\n\n    # start dom fpga update\n    printf \"\\nUsb-spi parallel dom fpga update:\\n\\n\"\n    for(( spidev=DOM_FPGA_START ; spidev<$((DOM_FPGA_START+8)) ; spidev++ ))\n    do\n        printf \" \\e[mstart pim %s dom fpga update.\\e[m\\n\" \"$((spidev-3))\"\n        ( flashrom -p linux_spi:dev=/dev/spidev\"$spidev\".0 -w \"$tmpfile\" > ${log_dir}flash_spidev${spidev}_multi_log )  &\n    done\n    printf \"\\n \\e[mwaitting for the update finished...\\e[m\"\n    while [ \"$(ps w | grep -i flashrom | grep -v grep)\" != \"\" ]\n    do\n        sleep 1\n    done\n    printf \"\\e[mdone.\\e[m\\n\"\n}\n\nif [ \"$1\" != \"\" ] && [ -f \"$1\" ];then\n    # switch pim mux from iob fpga to dom fpga\n    switch_pim_mux_to_fpga.sh\n    parallel_fpga_update\nelse\n    echo \"Usage:\"\n    echo \"$0 <dom fpga image>\"\nfi\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# This tool is used to update dom fpga (usb-spi mode)\n# The command format is\n#\n# Command to upgrade all pims in parallel:\n#  pim_upgrade.sh all <dom fpga image>\n#\n# Command to upgrade a single pim:\n#  pim_upgrade.sh pim1/pim2/pim3/pim4/pim5/pim6/pim7/pim8 <dom fpga image>\n#\n# SC2009: Consider using pgrep instead of grepping ps output.\n# because we dont have the pgrep, disable the SC2009 check\n# shellcheck disable=SC2009\n# shellcheck disable=SC1091\n. /usr/local/bin/flashrom-utils.sh\n\ntarget=$1\nfpgaimg=$2\nlog_dir=/tmp/\ntmpfile=/tmp/domfpga\nMAX_PIMNUM=8\n\nget_pim_spidev() {\n    pim_id=\"$1\"\n    pim_devmap_dir=/run/devmap/spi-devices\n    spidev_path=$(readlink \"${pim_devmap_dir}/PIM${pim_id}_FLASH\")\n    spidev_file=$(basename \"$spidev_path\")\n    echo \"$spidev_file\"\n}\n\nfpga_update(){\n    # extend the image size to fit flash size\n    cp \"$fpgaimg\" \"$tmpfile\"\n    filesize=$(stat -c%s $tmpfile)\n\n    # start dom fpga update\n    printf \"\\nUsb-spi dom fpga update:\\n\\n\"\n\n    pim1_flash=$(get_pim_spidev 1)\n    flash_size=$(flash_get_size \"$pim1_flash\")\n    addsize=$(($((flash_size * 1024)) - filesize))\n\n    if [ $((addsize)) -gt 0 ];then\n\tdd if=/dev/zero bs=\"$addsize\" count=1 | tr \"\\000\" \"\\377\" >> \"$tmpfile\"\n    fi\n\n    if [ \"$target\" == \"all\" ];then\n\n        for(( pimnum=1 ; pimnum<=MAX_PIMNUM ; pimnum++ ))\n        do\n\t    printf \" \\e[mstart pim %s dom fpga update.\\e[m\\n\" \"$((pimnum))\"\n\t    pim_flash=$(get_pim_spidev \"$pimnum\")\n\t    flash_model=$(flash_get_model \"$pim_flash\")\n\t    ( flash_write \"$pim_flash\" \"$tmpfile\" \"$flash_model\" > ${log_dir}flash_\"${pim_flash}\"_multi_log )  &\n        done\n    else\n\tpimnum=$(($(echo \"$target\" | cut -b 4)))\n\tprintf \" \\e[mstart pim %s dom fpga update.\\e[m\\n\" \"$((pimnum))\"\n\n\tpim_flash=$(get_pim_spidev \"$pimnum\")\n\tflash_model=$(flash_get_model \"$pim_flash\")\n\t( flash_write \"$pim_flash\" \"$tmpfile\" \"$flash_model\" > ${log_dir}flash_\"${pim_flash}\"_single_log )  &\n    fi\n\n    printf \"\\n \\e[mwaitting for the update finished...\\e[m\"\n\n    while [ \"$(ps w | grep -i flashrom | grep -v grep)\" != \"\" ]\n    do\n        sleep 1\n    done\n\n    printf \"\\e[mdone.\\e[m\\n\"\n}\n\ncase $target in\n    \"pim1\" | \"pim2\" | \"pim3\" | \"pim4\" | \"pim5\" | \"pim6\" | \"pim7\" | \"pim8\" | \"all\")\n        if [ \"$fpgaimg\" != \"\" ] && [ -f \"$fpgaimg\" ];then\n            # switch pim mux from dom fpga to dom fpga\n            switch_pim_mux_to_fpga.sh\n            fpga_update\n\t    exit 0\n        fi\n    ;;\n    *)\n    ;;\nesac\n\necho \"Usage:\"\necho \"Command to upgrade all pims in parallel:\"\necho \"  $0 all <dom fpga image>\"\necho \"\"\necho \"Command to upgrade a single pim:\"\necho \"  $0 pim1/pim2/pim3/pim4/pim5/pim6/pim7/pim8 <dom fpga image>\"\n\n", "num_lines": 113}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\necho \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 46}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nSCM_CMD=$SMBCPLD_SYSFS_DIR'/scm_present'\nPIM_CMD=$SMBCPLD_SYSFS_DIR'/*present_L'\nDEBUGCARD_CMD=$SMBCPLD_SYSFS_DIR'/debugcard_present'\n\nfunction usage\n{\n  program=$(basename \"$0\")\n  echo \"Usage:\"\n  echo \"     $program \"\n  echo \"     $program <TYPE>\"\n  echo \"     <TYPE>: scm/pim/fan/psu/debug_card\"\n}\n\n# Will return <key> : <val>\n# eg - scm : 1\nfunction get_presence\n{\n    local file=$1 key=$2\n    val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed 's/.x//')\n    if [ \"$val\" -eq 0 ]; then\n        val=1\n    else\n        val=0\n    fi\n    echo \"$key\" \":\" $val\n}\n\n# SCM\nfunction get_scm_presence\n{\n    key='scm'\n    get_presence \"$SCM_CMD\" $key\n}\n\n# PIMs\nfunction get_pim_presence\n{\n    local count=1\n    for file in $PIM_CMD; do\n        key='pim'$count\n        get_presence \"$file\" $key\n        (( count++ ))\n    done\n}\n\n# FANs\nfunction get_fan_presence\n{\n    local num=1\n    while [ $num -le 4 ]; do\n        count=$(((num * 2 ) - 1))\n        key='fan'$count\n        file=$TOP_FCMCPLD_SYSFS_DIR'/fan'$num'_present'\n        get_presence \"$file\" $key\n        count=$((num * 2 ))\n        key='fan'$count\n        file=$BOTTOM_FCMCPLD_SYSFS_DIR'/fan'$num'_present'\n        get_presence \"$file\" $key\n        (( num++ ))\n        (( count++ ))\n    done\n}\n\n# Power supplies\nfunction get_psu_presence\n{\n    for i in {1..4}; do\n        key=\"psu${i}\"\n        file=$SMBCPLD_SYSFS_DIR'/psu_prnst_'${i}'_N_status'\n        get_presence \"$file\" $key\n    done\n}\n\n# Debug card\nfunction get_debug_card_presence\n{\n  file=$DEBUGCARD_CMD\n  val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed 's/.x//')\n  if [ \"$val\" -eq 1 ]; then\n      val=1\n  else\n      val=0\n  fi\n\n  key=\"dbg0\"\n  echo $key \":\" $val\n}\n\n# get all info\nif [[ $1 = \"\" ]]; then\n  echo \"CARDS\"\n  get_scm_presence\n  get_pim_presence\n\n  echo \"FANS\"\n  get_fan_presence\n\n  echo \"POWER SUPPLIES\"\n  get_psu_presence\n\n  echo \"DEBUG CARD\"\n  get_debug_card_presence\n\nelse\n  if [[ $1 = \"scm\" ]]; then\n    get_scm_presence\n  elif [[ $1 = \"pim\" ]]; then\n    get_pim_presence\n  elif [[ $1 = \"fan\" ]]; then\n    get_fan_presence\n  elif [[ $1 = \"psu\" ]]; then\n    get_psu_presence\n  elif [[ $1 = \"debug_card\" ]]; then\n    get_debug_card_presence\n  else\n    usage\n  fi\nfi\n", "num_lines": 143}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n\tprogram=$(basename \"$0\")\n\techo \"Usage:\"\n\techo \"  $program <led>\"\n\techo \"  <led>: sys/fan/psu/smb\"\n\techo \"  $program without option to display all leds\"\n\techo\n\techo \"Output:\"\n\techo \"  <led>: color\"\n\texit 1\n}\n\nread_led_color_value() {\n\tcase $1 in\n\t\"sys\" | \"fan\" | \"psu\" | \"smb\")\n\t\tcat \"/sys/class/leds/$1/multi_intensity\"\n\t;;\n\t*)\n\t\tusage\n\t;;\n\tesac\n}\n\n# color: red-blue-green (value: 0-255)\n#   red(255 0 0)\n#   green(0 255 0)\n#   blue(0 0 255)\n#   amber(255 45 0)\nprint_led_color() {\n\tcolor=\"\"\n\tcase $(read_led_color_value \"$1\") in\n\t\"255 0 0\")\n\t\tcolor=\"red\"\n\t\t;;\n\t\"0 255 0\")\n\t\tcolor=\"green\"\n\t\t;;\n\t\"0 0 255\")\n\t\tcolor=\"blue\"\n\t\t;;\n\t\"255 45 0\")\n\t\tcolor=\"amber\"\n\t\t;;\n\t\"0 0 0\")\n\t\tcolor=\"off\"\n\t\t;;\n\t*)\n\t\tcolor=\"unknown\"\n\t\t;;\n\tesac\n\techo \"$1: $color\"\n}\n\nif [ $# -ge 1 ]; then\n\tled=$1\n\tcase $1 in\n\t\t\"?\" | \"help\")\n\t\t\tusage\n\t\t\t;;\n\t\t\"sys\" | \"fan\" | \"psu\" | \"smb\")\n\t\t\tprint_led_color \"$led\"\n\t\t\texit 0\n\t\t\t;;\n\t\t*)\n\t\t\tusage\n\t\t\t;;\n\tesac\nfi\n\nleds=(\"sys\" \"fan\" \"psu\" \"smb\")\nfor led in ${leds[*]}\ndo\n\tprint_led_color \"$led\"\ndone\n", "num_lines": 95}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# This tool will ask PIM to re-init and reload the firmware from Flash.\n# After we update the Flash of DOM FPGA, use this tool to make DOM FPGA\n# run the latest FPGA firmware without affecting the use of PIM.\n#\n\nset_pca9534_reload_pim_flash(){\n\n    flush_ucd_register\n\n    # Register 3 -  Configuration Register\n    set_pca9534_register \"0x03\" \"0xc0\"\n\n    flush_ucd_register\n\n    #\n    # Reset Register 1 - Output Port Register bit[2] - O2\n    #\n    # Register 1 -  Output Port Register\n    set_pca9534_register \"0x01\" \"0xd3\"\n\n    flush_ucd_register\n\n    # Register 1 - Output Port Register\n    set_pca9534_register \"0x01\" \"0xd7\"\n\n    flush_ucd_register\n}\n\nset_pca9534_register(){\n    register=$1\n    value=$2\n    # Set IOB FPGA indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x15 0x00 i\n    # Set IOB FPGA Write Data 0x0000fc03\n    i2cset -y -f 13 0x35 0xf4 0x00 0x00 \"$value\" \"$register\" i\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n}\n\nflush_ucd_register(){\n    # Set IOB FPGA indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x8c i\n    # Set IOB FPGA Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x00 0x00 0x00 0x03 i\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n    # Set IOB FPGA indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x84 i\n    # Set IOB FPGA Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80 0x22 0x02 0x00 i\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n}\n\necho 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n\nfor i in 0 1 2 3 4 5 6 7\ndo\n    cmd=$(printf \"i2cset -y -f 13 0x35 0x76 0x%02x 0x%02x i\\n\" \"$((i<<4))\" \"$((1<<i))\")\n    $cmd\n    set_pca9534_reload_pim_flash\ndone\n\n", "num_lines": 84}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nsetup_gpio_fuji_evt() {\n    # Export Group F GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF0 BMC_JTAG_MUX_IN\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF1 BMC_UART_SEL_0\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF2 BMC_FCM_1_SEL\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF3 FCM_2_CARD_PRESENT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF4 FCM_1_CARD_PRESENT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF5 BMC_SCM_CPLD_JTAG_EN_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF6 FCM_2_CPLD_JTAG_EN_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOF7 BMC_FCM_2_SEL\n\n    # Export Group G GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG0 FCM_1_CPLD_JTAG_EN_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG1 BMC_GPIO63\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG2 UCD90160A_CNTRL\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG3 BMC_UART_SEL_3\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG4 SYS_CPLD_JTAG_EN_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG6 BMC_I2C_SEL\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOG7 BMC_GPIO53\n\n    # Export Group I GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOI5 FPGA_BMC_CONFIG_DONE\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOI7 FPGA_NSTATUS\n\n    # Export Group M GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOM3 BMC_UART_SEL_1\n\n    # Export Group N GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPION0 LM75_ALERT\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPION2 CPU_RST#\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPION3 GPIO123_USB2BVBUSSNS\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPION4 GPIO126_USB2APWREN\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPION5 GPIO125_USB2AVBUSSNS\n   \n    # Export Group P GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOP0 BMC_UART_SEL_2\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOP6 BMC_GPIO61\n\n    # Export Group V GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV1 UCD90160A_2_GPI1\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV2 UCD90160A_1_GPI1\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV3 PWRMONITOR_BMC\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV4 BMC_PWRGD\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV5 FPGA_DEV_CLR_N\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV6 FPGA_DEV_OE\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV7 FPGA_CONFIG_SEL\n\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW0 LPCD0\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW1 LPCD1\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW2 LPCD2\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW3 LPCD3\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW4 LPCCLK\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW5 LPCFRAME#\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW6 LPCIRQ#\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOW7 LPCRST#\n\n    # Export Group X GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX6 BMC_FPGA_JTAG_EN\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX7 BMC_TPM_SPI_PIRQ_N\n\n    # Export Group Y GPIO\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOY2 BMC_GPIO57\n    gpio_export_by_name  \"${ASPEED_GPIO}\" GPIOY3 BMC_EMMC_RST_N\n}\n\nsetup_gpio_fuji_evt\n\ngpio_set_direction BMC_JTAG_MUX_IN out\ngpio_set_direction BMC_UART_SEL_0 out\ngpio_set_direction BMC_FCM_1_SEL out\ngpio_set_direction FCM_2_CARD_PRESENT in\ngpio_set_direction FCM_1_CARD_PRESENT in\ngpio_set_direction BMC_SCM_CPLD_JTAG_EN_N out\ngpio_set_direction FCM_2_CPLD_JTAG_EN_N out\ngpio_set_direction BMC_FCM_2_SEL out\ngpio_set_direction FCM_1_CPLD_JTAG_EN_N out\ngpio_set_direction BMC_GPIO63 out\ngpio_set_direction UCD90160A_CNTRL out\ngpio_set_direction BMC_UART_SEL_3 out\ngpio_set_direction BMC_I2C_SEL out\ngpio_set_direction BMC_GPIO53 out\ngpio_set_direction FPGA_BMC_CONFIG_DONE in\ngpio_set_direction FPGA_NSTATUS in\ngpio_set_direction BMC_UART_SEL_1 out\ngpio_set_direction SYS_CPLD_JTAG_EN_N out\ngpio_set_direction LM75_ALERT in\ngpio_set_direction CPU_RST# in\ngpio_set_direction GPIO123_USB2BVBUSSNS in\ngpio_set_direction GPIO125_USB2AVBUSSNS in\ngpio_set_direction GPIO126_USB2APWREN out\ngpio_set_direction BMC_UART_SEL_2 out\ngpio_set_direction BMC_GPIO61 out\ngpio_set_direction UCD90160A_2_GPI1 out\ngpio_set_direction UCD90160A_1_GPI1 out\ngpio_set_direction PWRMONITOR_BMC in\ngpio_set_direction BMC_PWRGD in\ngpio_set_direction FPGA_DEV_CLR_N out\ngpio_set_direction FPGA_DEV_OE out\ngpio_set_direction FPGA_CONFIG_SEL out\ngpio_set_direction LPCD0 in\ngpio_set_direction LPCD1 in\ngpio_set_direction LPCD2 in\ngpio_set_direction LPCD3 in\ngpio_set_direction LPCCLK in\ngpio_set_direction LPCFRAME# in\ngpio_set_direction LPCIRQ# in\ngpio_set_direction LPCRST# in\ngpio_set_direction BMC_FPGA_JTAG_EN out\ngpio_set_direction BMC_TPM_SPI_PIRQ_N in\ngpio_set_direction BMC_GPIO57 out\ngpio_set_direction BMC_EMMC_RST_N out\n\n# Once we set \"out\", output values will be random unless we set them\n# to something\n# Set UCD90160A_CNTRL high to provide the SMB power\ngpio_set_value UCD90160A_CNTRL 1\n# Set JTAG to Header (0:Header 1:BMC)\ngpio_set_value BMC_JTAG_MUX_IN 0\n# Set FPGA JTAG to Header (0:BMC 1:Header)\ngpio_set_value BMC_FPGA_JTAG_EN 1\n# Set PFR FPGA Image,Current Not Used,set Image1 as default (0:Image0 1:Image1)\ngpio_set_value FPGA_CONFIG_SEL 1\n# FPGA all register clear enable (0:enable 1:disable)\ngpio_set_value FPGA_DEV_CLR_N 1\n# FPGA all I/O pins tri-stated enable (0:enable 1:disbale)\ngpio_set_value FPGA_DEV_OE 1\n# USB Power Out enable(0:disable 1:enable)\ngpio_set_value GPIO126_USB2APWREN 1\n# UCD90160A set reserved\ngpio_set_value UCD90160A_2_GPI1 0\ngpio_set_value UCD90160A_1_GPI1 0\n# BMC UART SEL set reserved\ngpio_set_value BMC_UART_SEL_0 0\ngpio_set_value BMC_UART_SEL_1 0\ngpio_set_value BMC_UART_SEL_2 0\ngpio_set_value BMC_UART_SEL_3 0\n# BMC GPIO set reserved\ngpio_set_value BMC_GPIO53 0\n# set BMC_EMMC_RST_N High to prevent EMMC disable\ngpio_set_value BMC_EMMC_RST_N 1\ngpio_set_value BMC_GPIO57 0\ngpio_set_value BMC_GPIO61 0\ngpio_set_value BMC_GPIO63 0\n# CPLD JTAG Enable (0:enable 1:disable)\ngpio_set_value SYS_CPLD_JTAG_EN_N 1\ngpio_set_value FCM_2_CPLD_JTAG_EN_N 1\ngpio_set_value BMC_SCM_CPLD_JTAG_EN_N 1\ngpio_set_value FCM_1_CPLD_JTAG_EN_N 1\n# JTAG Connected (0:connected to JTAG 1:disconnected to JTAG)\ngpio_set_value BMC_FCM_1_SEL 1\ngpio_set_value BMC_FCM_2_SEL 1\n# PFR status by i2c bus (0:disconnect this bus 1:connect this bus)\ngpio_set_value BMC_I2C_SEL 0\n", "num_lines": 197}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Check board version. Only set avs VOUT from EVT3\n# Since the TH4 AVS feature can't be enabled on EVT1,2 hardware units because of hardware factors. \n# But we found the SMB EVT1 board ID is incorrect, it's the same as DVT1 board ID, \n# and there are 3 EVT1 units(F301220170001, F301220170002, F301220240001) shipped to FB. \n# So it seems FB can't upgrade the 3 EVT1 units to next package.\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nboard_ver=$(wedge_board_rev) #Get board version\n# VDD AVS need to config for DVT1 and later\nif [ \"$board_ver\" == \"BOARD_FUJI_EVT1\" ] || \\\n[ \"$board_ver\" == \"BOARD_FUJI_EVT2\" ] || \\\n[ \"$board_ver\" == \"BOARD_FUJI_EVT3\" ]; then\n    echo \"No need to set avs VOUT.\"\n    exit 1\nfi\n\n#\n# We have seen intermittent AVS voltage reading errors and root cause is\n# not clear as of now. Testing shows below retry will help to mitigate\n# such error.\n#\nfixup_avs_volt() {\n    echo \"Check AVS voltage...\"\n\n    for((i=1;i<=5;i++)); do\n        # some delay to minimize driver binding error potentially caused by\n        # dual-core or software race conditions. root cause not clear yet.\n        sleep 1\n\n        AVS_VOLT=$(cat \"${SYSFS_I2C_DEVICES}\"/1-0040/hwmon/hwmon*/in3_input)\n        ret=$?\n        #\n        # Note: below range (500, 1200) millivolts is confirmed by hardware\n        # team; please reach out to hardware team before making changes.\n        #\n        if [ $((ret)) -eq 0 ] && [ $((AVS_VOLT)) -gt 500 ] && [ $((AVS_VOLT)) -lt 1200 ]; then\n            echo \"AVS-Volt is normal, no fixup needed.\"\n            return\n        else\n            echo \"Invalid AVS-Volt $AVS_VOLT, re-create xdpe132g5c $i times\"\n\n            i2c_device_delete 1 0x40\n            i2c_device_add 1 0x40 xdpe132g5c\n        fi\n    done\n\n    logger -p user.err \"Unable to fix AVS voltage after 5 retries\"\n}\n\nfixup_avs_volt\n\nVID_VCC_MAX=(0xE6B 0xE0C 0xDB2 0xD58 0xCF6)\nXDPE_VOUT_PMBUS_COMMAND=0x21\n\nTH4_ROV=$(i2cget -f -y 12 0x3e 0x56 | awk '{printf \"%d\", $1}') # Get TH4 AVS value from SYSCPLD\n\ncase $TH4_ROV in\n    126|130|134|138|142) #0x7e,0x82,0x86,0x8a,0x8e\n        ;;\n    *)\n        echo \"Invalid AVS value[126,130,134,138,142]\"\n        exit 1\n        ;;\nesac\n\nTH4_INDEX=$(((TH4_ROV - 126) / 4))\n# Set VOUT to XDPE132G5C\ni2cset -f -y 1 0x40 0x00 0xff # Allows access all pages \nXDPE_VDD_MAX_VALUE=$((VID_VCC_MAX[TH4_INDEX]))\nXDPE_VDD_MAX_VALUE_HEX=$(printf \"0x%04x\" $XDPE_VDD_MAX_VALUE) # Convert to HEX\n\nif ! i2cset -f -y 1 0x40 $XDPE_VOUT_PMBUS_COMMAND \"$XDPE_VDD_MAX_VALUE_HEX\" w; then \n    echo \"Cannot communicate with XDPE132G5C.\"\n    exit 1\nfi\n# Change XDPE132G5C from all pages to page 0.\ni2cset -y -f 1 0x40 0x0 0x0\necho \"Setup AVS Success\"\n\n", "num_lines": 103}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ncmd_bic_ver=\"bic-util scm 0xe2 0x0b 0x15 0xa0 0x00 0x02\"\nCOUNTER=0\nMAX_RETRY=10\nrex='^[0-9]+$'\n\necho \"Initializing Bridge-IC I2C Frequency...\"\nwhile [ $COUNTER -lt $MAX_RETRY ]; do\n    readarray -td ' ' bic_data <<<\"$($cmd_bic_ver)\"\n    if [[ ${bic_data[4]} =~ $rex ]] ; then\n        break\n    fi\n    sleep 3\n    ((COUNTER+=1))\ndone\n\nif [ $COUNTER -eq $MAX_RETRY ];then\n    echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\nfi\n\nbic_major=$(( 10#${bic_data[3]} ))\nbic_minor=$(( 10#${bic_data[4]} ))\nbic_ver=\"$bic_major.${bic_data[4]}\"\n\necho Bridge-IC version is v\"$bic_ver\".\n\nif [ \"$bic_major\" -ge 1 ];then\n    if [ \"$bic_minor\" -ge 11 ];then\n        ret=$(bic-util scm 0xe0 0x2a 0x15 0xa0 0x00 0x01)\n        IANA=\"15 A0 00\"\n        if [ -z \"${ret##*$IANA*}\" ];then\n                echo Bridge-IC is initialized SCL to 1Mhz.\n        else\n                echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\n        fi\n    fi\nfi\n\nexit 0\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n\n#Read PSU type from eeprom and save to cache\npwr_type=$(wedge_power_supply_type)\n \nmkdir -p /tmp/cache_store\necho \"$pwr_type\" > /tmp/cache_store/power_type\n\n# Enable the isolation buffer between BMC and COMe i2c bus\necho 0 > \"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable\"\n\n# Make the backup BIOS flash connect to COMe instead of BMC\n#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_oe_n\n#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_sel\n\n# Setup management port LED\n/usr/local/bin/setup_mgmt.sh led &\n\n# Setup USB Serial to RS485\necho 0 > \"${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_0\"\necho 0 > \"${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_1\"\n\n# Init server_por_cfg\n#if [ ! -f \"/mnt/data/kv_store/server_por_cfg\" ]; then\n#    /usr/bin/kv set server_por_cfg on persistent\n#fi\n\n# Force COMe's UART connect to BMC UART-5 and FB USB debug\n# UART connect to BMC UART-2\necho 0x0 > \"$SMBCPLD_SYSFS_DIR/uart_selection\"\n\n# Read board type from SMB CPLD and keep in cache store\nbrd_type=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/board_type\")\nif [ ! -d /tmp/cache_store ]; then\n  mkdir /tmp/cache_store\nfi\necho \"$brd_type\" > /tmp/cache_store/board_type\n\n\ncp /etc/sensors.d/custom/fuji.conf /etc/sensors.d/fuji.conf\n\nkv set smb_update_flag 1\nkv set scm_update_flag 1\nkv set pim1_update_flag 1\nkv set pim2_update_flag 1\nkv set pim3_update_flag 1\nkv set pim4_update_flag 1\nkv set pim5_update_flag 1\nkv set pim6_update_flag 1\nkv set pim7_update_flag 1\nkv set pim8_update_flag 1\nkv set psu1_update_flag 1\nkv set psu2_update_flag 1\nkv set psu3_update_flag 1\nkv set psu4_update_flag 1\n\n# export_gpio_pin for PCA9534 54-0021\ngpiocli export -c 54-0021 -o 0 --shadow PDB_L_JTAG_TDO\ngpiocli export -c 54-0021 -o 1 --shadow PDB_L_JTAG_TDI\ngpiocli export -c 54-0021 -o 2 --shadow PDB_L_JTAG_TMS\ngpiocli export -c 54-0021 -o 3 --shadow PDB_L_JTAG_TCK\ngpiocli export -c 54-0021 -o 4 --shadow PDB_L_JTAG_PGM\ngpiocli export -c 54-0021 -o 7 --shadow PDB_L_HITLESS\ngpiocli export -c 62-0021 -o 0 --shadow PDB_R_JTAG_TDO\ngpiocli export -c 62-0021 -o 1 --shadow PDB_R_JTAG_TDI\ngpiocli export -c 62-0021 -o 2 --shadow PDB_R_JTAG_TMS\ngpiocli export -c 62-0021 -o 3 --shadow PDB_R_JTAG_TCK\ngpiocli export -c 62-0021 -o 4 --shadow PDB_R_JTAG_PGM\ngpiocli export -c 62-0021 -o 7 --shadow PDB_R_HITLESS\n\n", "num_lines": 103}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n# Board Version\nboard_ver=$(wedge_board_rev)\n\n# # Bus 0\ni2c_device_add 0 0x1010 slave-mqueue #IPMB 0\n\n# # Bus 1\ni2c_device_add 1 0x40 xdpe132g5c #ISL68137 DC-DC core\ni2c_device_add 1 0x53 mp2978\ni2c_device_add 1 0x59 mp2978\n\n# # Bus 2\ni2c_device_add 2 0x35 scmcpld  #SCM CPLD\n\n# # Bus 4\ni2c_device_add 4 0x1010 slave-mqueue #IPMB 1\ni2c_device_add 4 0x27 smb_debugcardcpld  # SMB DEBUGCARD CPLD\n\n# # Bus 13\ni2c_device_add 13 0x35 iobfpga #IOB FPGA\n\n# # Bus 3\ni2c_device_add 3 0x48 lm75     #LM75B_1# Thermal sensor\ni2c_device_add 3 0x49 lm75     #LM75B_2# Thermal sensor\ni2c_device_add 3 0x4a lm75     #LM75B_3# Thermal sensor\n\n# # Bus 5\n# # # SMB Power Sequence 1\n# # # for MP\n# # #   UCD90160    0x35\n# # # for Respin\n# # #   UCD90160A   0x66\n# # #   UCD90160    0x68\n# # #   UCD90124A   0x43\n# # #   ADM1266     0x44\nif i2c_detect_address 5 0x35; then\n   i2c_device_add 5 0x35 ucd90160\n   kv set smb_pwrseq_1_addr 0x35\nelif i2c_detect_address 5 0x66; then\n   i2c_device_add 5 0x66 ucd90160\n   kv set smb_pwrseq_1_addr 0x66\nelif i2c_detect_address 5 0x68; then\n   i2c_device_add 5 0x68 ucd90160\n   kv set smb_pwrseq_1_addr 0x68\nelif i2c_detect_address 5 0x43; then\n   i2c_device_add 5 0x43 ucd90124\n   kv set smb_pwrseq_1_addr 0x43\nelif i2c_detect_address 5 0x44; then\n   i2c_device_add 5 0x44 adm1266\n   kv set smb_pwrseq_1_addr 0x44\nelse\n   echo \"setup-i2c : not detect UCD90160 UCD9016A UCD90120 UCD90120A UCD90124 UCD90124A ADM1266\" > /dev/kmsg\nfi\n\n# # # SMB Power Sequence 2\n# # # for MP\n# # #   UCD90160    0x36\n# # # for Respin\n# # #   UCD90160A   0x67\n# # #   UCD90160    0x69\n# # #   UCD90124A   0x46\n# # #   ADM1266     0x47\nif i2c_detect_address 5 0x36; then\n   i2c_device_add 5 0x36 ucd90160\n   kv set smb_pwrseq_2_addr 0x36\nelif i2c_detect_address 5 0x67; then\n   i2c_device_add 5 0x67 ucd90160\n   kv set smb_pwrseq_2_addr 0x67\nelif i2c_detect_address 5 0x69; then\n   i2c_device_add 5 0x69 ucd90160\n   kv set smb_pwrseq_2_addr 0x69\nelif i2c_detect_address 5 0x46; then\n   i2c_device_add 5 0x46 ucd90124\n   kv set smb_pwrseq_2_addr 0x46\nelif i2c_detect_address 5 0x47; then\n   i2c_device_add 5 0x47 adm1266\n   kv set smb_pwrseq_2_addr 0x47\nelse\n   echo \"setup-i2c : not detect UCD90160 UCD9016A UCD90120 UCD90120A UCD90124 UCD90124A ADM1266\" > /dev/kmsg\nfi\n\n# Bus 8\ni2c_device_add 8 0x51 24c64\ni2c_device_add 8 0x4a lm75\n\n# net_brcm driver only support DVT1 and later\nif [ \"$board_ver\" != \"BOARD_FUJI_EVT1\" ] && \\\n[ \"$board_ver\" != \"BOARD_FUJI_EVT2\" ] && \\\n[ \"$board_ver\" != \"BOARD_FUJI_EVT3\" ]; then\n    i2c_device_add 29 0x47 net_brcm\nfi\n\n# # i2c-mux PCA9548 0x70, channel 1, mux PCA9548 0x71\ni2c_device_add 48 0x58 psu_driver\ni2c_device_add 49 0x5a psu_driver\ni2c_device_add 50 0x4c lm75     #SIM\ni2c_device_add 50 0x52 24c64 \t#SIM\ni2c_device_add 51 0x48 tmp75\ni2c_device_add 52 0x49 tmp75\ni2c_device_add 54 0x21 pca9534\t#PCA9534\nif i2c_detect_address 55 0x60; then\n    i2c_device_add 55 0x60 smb_pwrcpld \t#PDB-L\nelse\n    i2c_device_add 53 0x60 smb_pwrcpld \t#PDB-L\nfi\n\n# # i2c-mux PCA9548 0x70, channel 2, mux PCA9548 0x72\ni2c_device_add 56 0x58 psu_driver \t#PSU4\ni2c_device_add 57 0x5a psu_driver \t#PSU3\n\ni2c_device_add 59 0x48 tmp75\ni2c_device_add 60 0x49 tmp75\ni2c_device_add 62 0x21 pca9534\nif i2c_detect_address 63 0x60; then\n    i2c_device_add 63 0x60 smb_pwrcpld \t#PDB-R\nelse\n    i2c_device_add 61 0x60 smb_pwrcpld  #PDB-R\nfi\n\n# # i2c-mux PCA9548 0x70, channel 3, mux PCA9548 0x76\ni2c_device_add 64 0x33 fcbcpld #FCM CPLD\ni2c_device_add 65 0x53 24c64\ni2c_device_add 66 0x49 tmp75\ni2c_device_add 66 0x48 tmp75\ni2c_device_add 68 0x52 24c64    #fan 7 eeprom\ni2c_device_add 69 0x52 24c64    #fan 5 eeprom\ni2c_device_add 70 0x52 24c64    #fan 3 eeprom\ni2c_device_add 71 0x52 24c64    #fan 1 eeprom\n\n# # # FCM-T HSC\n# # #    ADM1278  0x10\n# # #    LM25066  0x44\nif i2c_detect_address 67 0x10; then\n   i2c_device_add 67 0x10 adm1278    # FCM ADM1278\n   kv set smb_fcm_t_hsc_addr 0x10\nelif i2c_detect_address 67 0x44; then\n   i2c_device_add 67 0x44 lm25066    # FCM LM25066\n   kv set smb_fcm_t_hsc_addr 0x44\nelse\n   echo \"setup-i2c : not detect ADM1278 LM25066 on FCM bus67\" > /dev/kmsg\nfi\n\n# # i2c-mux PCA9548 0x70, channel 4, mux PCA9548 0x76\ni2c_device_add 72 0x33 fcbcpld #FCM CPLD\ni2c_device_add 73 0x53 24c64\ni2c_device_add 74 0x49 tmp75\ni2c_device_add 74 0x48 tmp75\ni2c_device_add 76 0x52 24c64    #fan 8 eeprom\ni2c_device_add 77 0x52 24c64    #fan 6 eeprom\ni2c_device_add 78 0x52 24c64    #fan 4 eeprom\ni2c_device_add 79 0x52 24c64    #fan 2 eeprom\n\n# # # FCM-B HSC\n# # #    ADM1278  0x10\n# # #    LM25066  0x44\nif i2c_detect_address 75 0x10; then\n   i2c_device_add 75 0x10 adm1278    # FCM ADM1278\n   kv set smb_fcm_b_hsc_addr 0x10\nelif i2c_detect_address 75 0x44; then\n   i2c_device_add 75 0x44 lm25066    # FCM LM25066\n   kv set smb_fcm_b_hsc_addr 0x44\nelse\n   echo \"setup-i2c : not detect ADM1278 LM25066 on FCM bus75\" > /dev/kmsg\nfi\n\n# # i2c-mux PCA9548 0x70, channel 5\ni2c_device_add 28 0x50 24c02    #BMC54616S EEPROM\n\n# # Bus 12\ni2c_device_add 12 0x3e smb_syscpld     # SYSTEM CPLD\n\n#\n# Check if I2C devices are bound to drivers. A summary message (total #\n# of devices and # of devices without drivers) will be dumped at the end\n# of this function.\n#\ni2c_check_driver_binding \"fix-binding\"\n", "num_lines": 201}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nCOM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/come_pwr_ok_status\")\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"     $program led\"\n}\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# When COM-e power is not ready, it doesn't work to set PHY register.\n# Therefore, waiting for COM-e power ready, then start to set PHY register.\nwhile [ \"$COM_E_PWRGD\" = \"0x0\" ];\ndo\n    COM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/come_pwr_ok_status\")\n    sleep 5\ndone\n\nif [ \"$1\" = \"led\" ]; then\n    echo \"Wait a few seconds to setup management port LED...\"\n    # refer to BCM54616S Section 5, register 1C access\n    # Register 1C (Shadow 00010): Spare Control 1\n    # Bit0: 1: Enable link LED mode.\n    mdio-util -m 2 -p 0x0e -w 0x1c -d 0x8801\n    # Register 1C (Shadow 01110): LED Selector 2\n    # Bit7~4: LED4 Selector, b0011: Activity LED \n    # Bit3~0: LED4 Selector, b0101: Slave\n    mdio-util -m 2 -p 0x0e -w 0x1c -d 0xb435\n    echo \"Done!\"\nelse\n    usage\n    exit 1\nfi\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ndev=$1\ncolor=$2\n\nusage(){\n  program=$(basename \"$0\")\n  echo \"Usage:\"\n  echo \"     $program <dev> <color>\"\n  echo \"\"\n  echo \"     <dev>: sys/fan/psu/smb\"\n  echo \"     <color>: off/red/blue/green/amber\"\n}\n\nled=\"\"\ncase $dev in\n  \"sys\" | \"fan\" | \"psu\" | \"smb\")\n    led=\"/sys/class/leds/$dev\"\n  ;;\n  *)\n    usage\n    exit 1\n  ;;\nesac\n\n# color: red/green/blue value: 0-255\n# brightness: 0-255\nbrightness=\"255\"\ncase $color in\n  \"red\")\n    color=\"255 0 0\"\n  ;;\n  \"blue\")\n    color=\"0 0 255\"\n  ;;\n  \"green\")\n    color=\"0 255 0\"\n  ;;\n  \"amber\")\n    color=\"255 45 0\"\n  ;;\n  \"off\")\n    color=\"0 0 0\"\n    brightness=0\n  ;;\n  *)\n    usage\n    exit 1\n  ;;\nesac\n\necho \"$color\" > \"$led/multi_intensity\"\necho $brightness > \"$led/brightness\"\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS4\n# shellcheck disable=SC2009\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ \"$pid\" ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -a $FILE ]\n    then\n      read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 \"$TTY\"\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 66}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\n#shellcheck disable=SC2086\n. /usr/local/bin/openbmc-utils.sh\n\nret=0\ntrap cleanup_spi INT TERM QUIT EXIT\n\nPIDFILE=\"/var/run/spi_util.pid\"\ncheck_duplicate_process()\n{\n    exec 2>$PIDFILE\n    flock -n 2 || (echo \"Another process is running\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 1\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n\nremove_pid_file()\n{\n    if [ -f $PIDFILE ]; then\n        rm $PIDFILE\n    fi\n}\n\nSPI1_MTD_INDEX=7\nSPI1_DRIVER=\"1e630000.spi\"\nif [ -e /sys/bus/platform/drivers/spi-aspeed-smc ]; then\n    ASPEED_SMC_PATH=\"/sys/bus/platform/drivers/spi-aspeed-smc/\"\nelse\n    ASPEED_SMC_PATH=\"/sys/bus/platform/drivers/aspeed-smc/\"\nfi\n\nmtd_driver_unbind_spi1() {\n    [ -e ${ASPEED_SMC_PATH}${SPI1_DRIVER} ] && echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}unbind\n}\n\nmtd_driver_rebind_spi1() {\n    # Sometime kernel may complain \"vmap allocation for size 268439552 failed: use vmalloc=<size> to increase size\"\n    # until now the root cause is not clear, still need more investigation\n    mtd_driver_unbind_spi1\n    echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}bind\n}\n\nread_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Reading ${dev} to $file...\"\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -r \"$file\"\n}\n\nread_spi2_dev(){\n    dev=$1\n    file=$2\n    file_temp=\"$file\"_temp\n    echo \"Reading ${dev} to $file...\"\n    # Sometimes the read back BCM5387_EE image one bit fail.\n    # still not found the real root cause\n    for n in 1 2 3 4 5\n    do\n        echo \"Reading $file $n times\"\n        dd if=/sys/devices/platform/spi-gpio/spi_master/spi2/spi2.2/spi2.20/nvmem of=\"$file\"\n        sleep 1\n        dd if=/sys/devices/platform/spi-gpio/spi_master/spi2/spi2.2/spi2.20/nvmem of=\"$file_temp\"\n        if ! diff $file $file_temp >/dev/null; then\n            # read-back file differ\n            rm -rf \"$file\"*\n        else\n            # read-back file same\n            rm -rf $file_temp;\n            return;\n        fi\n    done\n    logger -p user.err \"Unable to read the correct $file after 5 retries\"\n    exit 1\n}\n\nwrite_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Writing $file to ${dev}...\"\n\n    tmpfile=\"$file\"_ext\n    flashsize=$(flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX | grep -i kB | xargs echo | cut -d '(' -f 2 | cut -d ' ' -f 0)\n    targetsize=$((flashsize * 1024))\n\n    case ${dev} in\n        \"PCIE_SW\"|\"TH4_PCIE_FLASH\"|\"COME_BIOS\"|\"DOM_FPGA_ALL\"|\"DOM_FPGA_PIM1\"|\"DOM_FPGA_PIM2\"|\"DOM_FPGA_PIM3\"|\"DOM_FPGA_PIM4\"|\"DOM_FPGA_PIM5\"|\"DOM_FPGA_PIM6\"|\"DOM_FPGA_PIM7\"|\"DOM_FPGA_PIM8\")\n        # store to the temp-file\n        cp \"$file\" \"$tmpfile\"\n        ;;\n\n\t\"IOB_FPGA\")\n        # remove fpga header size 112 and then store to the temp-file\n        dd if=\"$file\" skip=1 bs=112 of=\"$tmpfile\"\n        ;;\n    esac\n\n    #extend the temp-file\n    filesize=$(stat -c%s $tmpfile)\n    echo $filesize\n    add_size=$((targetsize - filesize))\n    echo $add_size\n    dd if=/dev/zero bs=\"$add_size\" count=1 | tr \"\\000\" \"\\377\" >> \"$tmpfile\"\n\n    echo flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -w \"$tmpfile\"\n\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -w \"$tmpfile\"\n\n    case ${dev} in\n        \"IOB_FPGA\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/sys_cpld_fpga_rst_n\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/sys_cpld_fpga_rst_n\n        ;;\n\n        \"DOM_FPGA_PIM1\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim1_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim1_smb_pg\n        ;;\n        \"DOM_FPGA_PIM2\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim2_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim2_smb_pg\n        ;;\n        \"DOM_FPGA_PIM3\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim3_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim3_smb_pg\n        ;;\n        \"DOM_FPGA_PIM4\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim4_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim4_smb_pg\n        ;;\n        \"DOM_FPGA_PIM5\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim5_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim5_smb_pg\n        ;;\n        \"DOM_FPGA_PIM6\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim6_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim6_smb_pg\n        ;;\n        \"DOM_FPGA_PIM7\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim7_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim7_smb_pg\n        ;;\n        \"DOM_FPGA_PIM8\")\n            echo 0 > /sys/bus/i2c/devices/12-003e/pim8_smb_pg\n            sleep 1\n            echo 1 > /sys/bus/i2c/devices/12-003e/pim8_smb_pg\n        ;;\n    esac\n}\n\nwrite_spi2_dev(){\n    dev=$1\n    file=$2\n    echo \"Writing $file to ${dev}...\"\n    dd if=\"$file\" of=/sys/devices/platform/spi-gpio/spi_master/spi2/spi2.2/spi2.20/nvmem \n}\n\nerase_spi1_dev(){\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -E\n}\n\nerase_spi2_dev(){\n    echo 1 > /sys/devices/platform/spi-gpio/spi_master/spi2/spi2.2/erase\n}\n\nsetup_pims_switch_mux(){\n\n#\n# This function is used to bypass the command through FPGA to PCA9534, to switch the mux from PIM FPGA to IOB FPGA that BMC can access PIM Flash through IOB FPGA via SPI protocol.\n#\n# The registers at address 0XF0 and above defined in this section is dedicated for BMC only.\n# CPU can\u00e2\u20ac\u2122t access 0XF0-0XFF registers in this section. BMC can use the address/data/command registers defined in address 0XF0- 0XFC to access FPGA full memory space.\n# 0xFF is a debug register.\n#\n# 0xF0\tRW\tIndirect Access Address register [31:24]\n# 0xF1\tRW\tIndirect Access Address register [23:16]\n# 0xF2\tRW\tIndirect Access Address register [15:8]\n# 0xF3\tRW\tIndirect Access Address register [7:0]\n#\n# 0xF4  RW      Indirect Access Write data register [31:24]\n# 0xF5  RW      Indirect Access Write data [23:16]\n# 0xF6  RW      Indirect Access Write data [15:8]\n# 0xF7  RW      Indirect Access Write data [7:0]\n#\n# 0xFC\tRW\tIndirect Access Command Register.\n# bit0 = 1 is for write; bit0 = 0 is for read.\n# Writing to this register will trigger an indirect access.\n#\n# Set 0x0000148c to 0x00000003\n#\n    # Set Indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x8c\n    # Set Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0x0\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001484 to 0x80220200\n#\n\n    # Set Indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x84\n    # Set Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80\n    i2cset -y -f 13 0x35 0xf5 0x22\n    i2cset -y -f 13 0x35 0xf6 0x2\n    i2cset -y -f 13 0x35 0xf7 0x0\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001500 to 0x0000fc03\n#\n\n    # Set Indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x15\n    i2cset -y -f 13 0x35 0xf3 0x0\n    # Set Write Data 0x0000fc03\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0xfc\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n    sleep 1\n\n#\n# Set 0x0000148c to 0x00000003\n#\n\n    # Set Indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x8c\n    # Set Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0x0\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001484 to 0x80220200\n#\n\n    # Set Indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x84\n    # Set Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80\n    i2cset -y -f 13 0x35 0xf5 0x22\n    i2cset -y -f 13 0x35 0xf6 0x2\n    i2cset -y -f 13 0x35 0xf7 0x0\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001500 to 0x0000d501\n#\n\n    # Set Indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x15\n    i2cset -y -f 13 0x35 0xf3 0x0\n    # Set Write Data 0x0000d501\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0xd5\n    i2cset -y -f 13 0x35 0xf7 0x01\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n    sleep 1\n\n#\n# Set 0x0000148c to 0x00000003\n#\n\n    # Set Indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x8c\n    # Set Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0x0\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001484 to 0x80220200\n#\n\n    # Set Indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x84\n    # Set Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80\n    i2cset -y -f 13 0x35 0xf5 0x22\n    i2cset -y -f 13 0x35 0xf6 0x2\n    i2cset -y -f 13 0x35 0xf7 0x0\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001500 to 0x0000fc03\n#\n\n    # Set Indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x15\n    i2cset -y -f 13 0x35 0xf3 0x0\n    # Set Write Data 0x0000fc03\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0xfc\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n    sleep 1\n\n#\n# Set 0x0000148c to 0x00000003\n#\n\n    # Set Indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x8c\n    # Set Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0x0\n    i2cset -y -f 13 0x35 0xf7 0x3\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001484 to 0x80220200\n#\n\n    # Set Indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x14\n    i2cset -y -f 13 0x35 0xf3 0x84\n    # Set Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80\n    i2cset -y -f 13 0x35 0xf5 0x22\n    i2cset -y -f 13 0x35 0xf6 0x2\n    i2cset -y -f 13 0x35 0xf7 0x0\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n#\n# Set 0x00001500 to 0x0000d501\n#\n\n    # Set Indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x0\n    i2cset -y -f 13 0x35 0xf1 0x0\n    i2cset -y -f 13 0x35 0xf2 0x15\n    i2cset -y -f 13 0x35 0xf3 0x0\n    # Set Write Data 0x0000d501\n    i2cset -y -f 13 0x35 0xf4 0x0\n    i2cset -y -f 13 0x35 0xf5 0x0\n    i2cset -y -f 13 0x35 0xf6 0xd5\n    i2cset -y -f 13 0x35 0xf7 0x01\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n}\n\nconfig_spi1_pin_and_path(){\n    dev=$1\n\n    case ${dev} in\n        \"TH4_PCIE_FLASH\")\n            echo \"[Setup] TH4_PCIE_FLASH\"\n            echo 0x00 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 1 - enable FPGA internal SPI masters\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0 - select none\n            i2cset -y -f 13 0x35 0x76 0x80 b\n            i2cset -y -f 13 0x35 0x77 0x00 b\n        ;;\n        \"IOB_FPGA\")\n            echo \"[Setup] IOB_FPGA\"\n            echo 0x01 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 1 - enable FPGA internal SPI masters\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0 - select none\n            i2cset -y -f 13 0x35 0x76 0x80 b\n            i2cset -y -f 13 0x35 0x77 0x00 b\n        ;;\n        \"PCIE_SW\")\n            echo \"[Setup] PCIE_SW\"\n            echo 0x02 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 1 - enable FPGA internal SPI masters\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0 - select none\n            i2cset -y -f 13 0x35 0x76 0x80 b\n            i2cset -y -f 13 0x35 0x77 0x00 b\n        ;;\n        \"COME_BIOS\")\n            echo \"[Setup] COME_BIOS\"\n            echo 0x03 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 1 - enable FPGA internal SPI masters\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0 - select none\n            i2cset -y -f 13 0x35 0x76 0x80 b\n            i2cset -y -f 13 0x35 0x77 0x00 b\n        ;;\n        \"DOM_FPGA_ALL\")\n            echo \"[Setup] DOM_FPGA_ALL\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x100 - Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            i2cset -y -f 13 0x35 0x76 0x01 b\n            i2cset -y -f 13 0x35 0x77 0x00 b\n        ;;\n        \"DOM_FPGA_PIM1\")\n            echo \"[Setup] DOM_FPGA_PIM1\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x01 - Bit0 is for PIM#1\n            i2cset -y -f 13 0x35 0x76 0x00 b\n            i2cset -y -f 13 0x35 0x77 0x01 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM2\")\n            echo \"[Setup] DOM_FPGA_PIM2\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x02 - Bit1 is for PIM#2\n            i2cset -y -f 13 0x35 0x76 0x10 b\n            i2cset -y -f 13 0x35 0x77 0x02 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM3\")\n            echo \"[Setup] DOM_FPGA_PIM3\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x04 - Bit2 is for PIM#3\n            i2cset -y -f 13 0x35 0x76 0x20 b\n            i2cset -y -f 13 0x35 0x77 0x04 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM4\")\n            echo \"[Setup] DOM_FPGA_PIM4\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x08 - Bit3 is for PIM#4\n            i2cset -y -f 13 0x35 0x76 0x30 b\n            i2cset -y -f 13 0x35 0x77 0x08 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM5\")\n            echo \"[Setup] DOM_FPGA_PIM5\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x10 - Bit4 is for PIM#5\n            i2cset -y -f 13 0x35 0x76 0x40 b\n            i2cset -y -f 13 0x35 0x77 0x10 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM6\")\n            echo \"[Setup] DOM_FPGA_PIM6\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x20 - Bit5 is for PIM#6\n            i2cset -y -f 13 0x35 0x76 0x50 b\n            i2cset -y -f 13 0x35 0x77 0x20 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM7\")\n            echo \"[Setup] DOM_FPGA_PIM7\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x40 - Bit6 is for PIM#7\n            i2cset -y -f 13 0x35 0x76 0x60 b\n            i2cset -y -f 13 0x35 0x77 0x40 b\n            setup_pims_switch_mux\n        ;;\n        \"DOM_FPGA_PIM8\")\n            echo \"[Setup] DOM_FPGA_PIM8\"\n            echo 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n            #\n            # FPGA 0x0074, [31:0] is 4 bytes address offset from 0x74 to 0x77 offset\n            #\n            # Set FPGA register offset 74h bit[15] SPI master mode to 0 - SPI legacy mode, SPI master is BMC.\n            #\n            # Bit0 is for PIM#1; bit7 is for PIM#8.\n            # Bit8 is for the SPI Flash attached on IOB FPGA. For testing\n            #\n            # Set FPGA register offset 74h bit[8:0] SPI selection bitmap to 0x80 - Bit7 is for PIM#8\n            i2cset -y -f 13 0x35 0x76 0x70 b\n            i2cset -y -f 13 0x35 0x77 0x80 b\n            setup_pims_switch_mux\n        ;;\n\n        *)\n            echo \"Please enter {TH4_PCIE_FLASH, IOB_FPGA, PCIE_SW, COME_BIOS, DOM_FPGA_ALL, DOM_FPGA_PIM1, DOM_FPGA_PIM2, DOM_FPGA_PIM3, DOM_FPGA_PIM4, DOM_FPGA_PIM5, DOM_FPGA_PIM6, DOM_FPGA_PIM7, DOM_FPGA_PIM8}\"\n            exit 1\n        ;;\n    esac\n\n    mtd_driver_rebind_spi1\n    echo \"Config SPI1 Done.\"\n}\n\nconfig_spi2_pin_and_path(){\n    dev=$1\n\n    case ${dev} in\n        \"BCM5387_EE\")\n            echo \"[Setup] BCM5387_EE\"\n            echo 0x05 > /sys/bus/i2c/devices/12-003e/spi2_sel\n        ;;\n        \"SMB_EE\")\n            echo \"[Setup] SMB_EE\"\n            echo 0x04 > /sys/bus/i2c/devices/12-003e/spi2_sel\n        ;;\n\n        *)\n            echo \"Please enter {BCM5387_EE, SMB_EE}\"\n            exit 1\n        ;;\n    esac\n    echo \"Config SPI2 Done.\"\n}\n\noperate_spi1_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n                read_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                if [ ! -f \"$file\" ]; then\n                    echo \"$file not exist!!!\"\n                    exit 1\n                fi\n                write_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi1_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n    mtd_driver_unbind_spi1\n}\n\noperate_spi2_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n                read_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                if [ ! -f \"$file\" ]; then\n                    echo \"$file not exist!!!\"\n                    exit 1\n                fi\n                write_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi2_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n}\n\n\ncleanup_spi(){\n    if [ $ret -eq 1 ]; then\n        exit 1\n    fi\n    echo 0 > \"$SMBCPLD_SYSFS_DIR/spi_1_sel\"\n\n    rm -rf /tmp/*_spi*_tmp\n    remove_pid_file\n}\n\nui(){\n    . /usr/local/bin/openbmc-utils.sh\n    op=$1\n    spi=$2\n\n    ## Open the path to device ##\n    case ${spi} in\n        \"spi1\")\n            dev=$3\n            file=$4\n            config_spi1_pin_and_path \"$dev\"\n            operate_spi1_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n\t\"spi2\")\n            dev=$3\n            file=$4\n            config_spi2_pin_and_path \"$dev\"\n            operate_spi2_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        *)\n            echo \"No such SPI bus.\"\n            return 1\n        ;;\n    esac\n}\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"  $program <op> <spi1|spi2> <spi device> <file>\"\n    echo \"    <op>          : read, write, erase\"\n    echo \"    <spi1 device> : TH4_PCIE_FLASH, IOB_FPGA, PCIE_SW, COME_BIOS, DOM_FPGA_ALL, DOM_FPGA_PIM1 ~ DOM_FPGA_PIM8\"\n    echo \"    <spi2 device> : BCM5387_EE, SMB_EE\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program write spi1 DOM_FPGA_PIM7 domfpga.bit\"\n    echo \"\"\n}\n\ncheck_parameter(){\n    program=$(basename \"$0\")\n    op=$1\n    spi=$2\n\n    # check operations.\n    case ${op} in\n        \"read\" | \"write\" | \"erase\")\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n\n    case ${spi} in\n        # check spi 1 device and parameters.\n        \"spi1\")\n            dev=$3\n            file=$4\n            case ${dev} in\n                \"TH4_PCIE_FLASH\"|\"IOB_FPGA\"|\"PCIE_SW\"|\"COME_BIOS\"|\"DOM_FPGA_ALL\"|\"DOM_FPGA_PIM1\"|\"DOM_FPGA_PIM2\"|\"DOM_FPGA_PIM3\"|\"DOM_FPGA_PIM4\"|\"DOM_FPGA_PIM5\"|\"DOM_FPGA_PIM6\"|\"DOM_FPGA_PIM7\"|\"DOM_FPGA_PIM8\")\n                    case ${op} in\n                        \"read\" | \"write\")\n                            if [ $# -ne 4 ]; then\n                                return 1\n                            fi\n                            ;;\n                    \"erase\")\n                            if [ $# -ne 3 ]; then\n                                return 1\n                            fi\n                            ;;\n                    esac\n                    ;;\n                *)\n                    return 1\n                    ;;\n            esac\n            ;;\n        # check spi 2 device and parameters.\n        \"spi2\")\n            dev=$3\n            file=$4\n\n            case ${dev} in\n                \"BCM5387_EE\"|\"SMB_EE\")\n                    case ${op} in\n                        \"read\" | \"write\")\n                            if [ $# -ne 4 ]; then\n                                return 1\n                            fi\n                            ;;\n                        \"erase\")\n                            if [ $# -ne 3 ]; then\n                                return 1\n                            fi\n                            ;;\n                    esac\n                    ;;\n                *)\n                    return 1\n                    ;;\n            esac\n\n            ;;\n\n        # check device and parameters fail.\n        *)\n            return 1\n            ;;\n    esac\n\n    return 0\n}\n\n\n# check_duplicate_process - to check if there is the duplicate spi util process, will return fail and stop execute command.\ncheck_duplicate_process\n\n# check_parameter - to check command parameters\ncheck_parameter \"$@\"\n\nis_par_ok=$?\n\nif [ $is_par_ok -eq 0 ]; then\n    ui \"$@\"\n    exit 0\nelse\n    usage\n    exit 1\nfi\n\n", "num_lines": 861}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# This tool is used to setup the SPI mux on the PIM from connecting to DOM FPGA to connecting to IOB FPGA,\n# so that IOB FPGA has the ability to read and write Flash on PIM.\n# Before updating the DOM FPGA, we must set the SPI mux of PIM to access the Flash of DOM FPGA.\n#\n\nset_pca9534_register(){\n\n    register=$1\n    value=$2\n\n    # Set IOB FPGA indirect Access Address 0x00001500\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x15 0x00 i\n    # Set IOB FPGA Write Data 0x0000fc03\n    i2cset -y -f 13 0x35 0xf4 0x00 0x00 \"$value\" \"$register\" i\n\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1 b\n}\n\nflush_ucd_register(){\n\n    # Set IOB FPGA indirect Access Address 0x0000148c\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x8c i\n    # Set IOB FPGA Write Data 0x00000003\n    i2cset -y -f 13 0x35 0xf4 0x00 0x00 0x00 0x03 i\n\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n\n    # Set IOB FPGA indirect Access Address 0x00001484\n    i2cset -y -f 13 0x35 0xf0 0x00 0x00 0x14 0x84 i\n    # Set IOB FPGA Write Data 0x80220200\n    i2cset -y -f 13 0x35 0xf4 0x80 0x22 0x02 0x00 i\n\n    # Set Command Write Action\n    i2cset -y -f 13 0x35 0xfc 0x1\n}\n\nsetup_pims_switch_mux(){\n\n    flush_ucd_register\n\n    # Register 3 -  Configuration Register\n    set_pca9534_register \"0x03\" \"0xc0\"\n\n    flush_ucd_register\n\n    #\n    # Set Register 1 - Output Port Register bit[1] - O1\n    #\n    # Register 1 -  Output Port Register\n    set_pca9534_register \"0x01\" \"0xd5\"\n\n    flush_ucd_register\n}\n\necho 0x06 > /sys/bus/i2c/devices/12-003e/spi1_sel\n\nfor i in 0 1 2 3 4 5 6 7\ndo\n    cmd=$(printf \"i2cset -y -f 13 0x35 0x76 0x%02x 0x%02x i\\n\" \"$(((i+8)<<4))\" \"$((1<<i))\")\n    $cmd\n    setup_pims_switch_mux\ndone\n\n", "num_lines": 85}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n#board_rev=$(wedge_board_rev)\n\nPWR_USRV_RST_SYSFS=\"${SCMCPLD_SYSFS_DIR}/sys_reset_n\"\nPWR_L_CYCLE_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_R_CYCLE_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_L_TIMER_BASE_1S_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_R_TIMER_BASE_1S_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_L_TIMER_BASE_10S_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_R_TIMER_BASE_10S_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_L_TIMER_COUNTER_SETTING_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_R_TIMER_COUNTER_SETTING_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_counter_setting_update\"\nPWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_counter_setting_update\"\n\nPIM_NAME=\"${PIM_RST_SYSFS}/pim\"\nCPLD_RESET=\"_hw_rst_l\"\nCPLD_PG=\"_smb_pg\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole fuji system ungracefully\"\n    echo \"      -s -t [1-2550]: Setting boot up time.\"\n    echo \"            From 1 to 249 the step is 1 second.\"\n    echo \"            From 250 to 2550 the step is 10 seconds\"\n    echo \"            and don't care ones-digits.\"\n    echo\n    echo \"  pimreset: Power-cycle one or all PIM(s)\"\n    echo \"    options:\"\n    echo \"      -a  : Reset all PIMs or \"\n    echo \"      -2 , -3 , ... , -9 : Reset a single PIM (2, 3 ... 9) \"\n    echo\n    echo \"  pim_power_on/off: Power-on/off one or all PIM(s)\"\n    echo \"    options:\"\n    echo \"      -a  : Power-on/off all PIMs or \"\n    echo \"      -2 , -3 , ... , -9 : Power-on/off a single PIM (2, 3 ... 9) \"\n    echo\n}\n\nmain_power_status() {\n    return 0\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on_com_e() {\n    echo 1 > \"$PWR_USRV_SYSFS\"\n    echo 1 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # power on sequence\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n\tlogger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    echo 0 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_config_reset_timer() {\n    # Check numeric\n    wake_t=$1\n    echo \"$wake_t\" | grep -E -q '^[0-9]+$'\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        usage\n        exit 1\n    else\n        if [ \"$wake_t\" -ge 1 ] && [ \"$wake_t\" -lt 250 ];then\n            echo 1 > \"$PWR_L_TIMER_BASE_1S_SYSFS\"\n            echo 1 > \"$PWR_R_TIMER_BASE_1S_SYSFS\"\n            echo 0 > \"$PWR_L_TIMER_BASE_10S_SYSFS\"\n            echo 0 > \"$PWR_R_TIMER_BASE_10S_SYSFS\"\n            logger \"Waiting $wake_t seconds for the system boot up\"\n            echo \"Waiting $wake_t seconds for the system boot up\"\n        elif [ \"$wake_t\" -ge 250 ] && [ \"$wake_t\" -le 2550 ];then\n            echo 0 > \"$PWR_L_TIMER_BASE_1S_SYSFS\"\n            echo 0 > \"$PWR_R_TIMER_BASE_1S_SYSFS\"\n            echo 1 > \"$PWR_L_TIMER_BASE_10S_SYSFS\"\n            echo 1 > \"$PWR_R_TIMER_BASE_10S_SYSFS\"\n            wake_t=$((wake_t/10))\n            logger \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n            echo \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n        else\n            usage\n            exit 1\n        fi\n        echo $wake_t > \"$PWR_L_TIMER_COUNTER_SETTING_SYSFS\"\n        echo $wake_t > \"$PWR_R_TIMER_COUNTER_SETTING_SYSFS\"\n        echo 1 > \"$PWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n        echo 1 > \"$PWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n        echo 0 > \"$PWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n        echo 0 > \"$PWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n    fi\n}\n\ndo_reset() {\n    local system timer wake_t opt\n    system=0\n    timer=0\n    wake_t=0\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            t)\n                timer=1\n                wake_t=$OPTARG\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n\n    if [ $system -eq 1 ]; then\n            if [ $timer -eq 1 ]; then\n                do_config_reset_timer \"$wake_t\"\n            fi\n            # Synchronize cached writes to persistent storage\n            # We found somethimes /mnt/data data lost after wedge_power.sh reset -s,\n            # add sync in case of file system will be broken by random power cycle.\n            sync\n            logger \"Power reset the whole system ...\"\n            echo  \"Power reset the whole system ...\"\n            echo 1 > \"$PWR_L_CYCLE_SYSFS\"\n            echo 1 > \"$PWR_R_CYCLE_SYSFS\"\n            sleep 3\n            # Control should not reach here, but if it failed to reset\n            # the system through PSU, then run a workaround to reset\n            # most of the system instead (if not all)\n            logger \"Failed to reset the system. Running a workaround\"\n            echo \"Failed to reset the system. Running a workaround\"\n            i2cset -f -y 1 0x3a 0x12 0\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return 1\n        fi\n        echo -n \"Power reset microserver ...\"\n        echo 0 > \"$PWR_USRV_RST_SYSFS\"\n        sleep 1\n        echo 1 > \"$PWR_USRV_RST_SYSFS\"\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\ntoggle_pim_reset() {\n    retval=0\n    pim=$1\n    for slot in 2 3 4 5 6 7 8 9; do\n      if [ \"$pim\" -eq 0 ] || [ $slot -eq \"$pim\" ]; then\n        index=$((slot - 1))\n         echo Power-cycling PIM in slot $slot\n         #i2cset -f -y ${PIM_CPLD_BUS[$index]} $CPLD_ADDR $CPLD_RESET_CMD\n         echo 0 > \"$PIM_NAME$index$CPLD_RESET\"\n         sleep 1\n         echo 1 > \"$PIM_NAME$index$CPLD_RESET\"\n         result=$?\n         if [ $result -ne 0 ]; then\n           retval=$result\n         fi\n      fi\n    done\n    return $retval\n}\n\ntoggle_pim_power_onoff() {\n\tretval=0\n\taction=$1\n\tpim=$2\n\tfor slot in 2 3 4 5 6 7 8 9; do\n\t\tif [ \"$pim\" -eq 0 ] || [ $slot -eq \"$pim\" ]; then\n\t\t\tindex=$((slot - 1))\n\t\t\tif [ \"$action\" = \"on\" ]; then\n\t\t\t\techo Power-on PIM in slot $slot\n\t\t\t\techo 1 > \"$PIM_NAME$index$CPLD_PG\"\n\t\t\t\tresult=$?\n\t\t\telif [ \"$action\" = \"off\" ]; then\n\t\t\t\techo Power-off PIM in slot $slot\n\t\t\t\techo 0 > \"$PIM_NAME$index$CPLD_PG\"\n\t\t\t\tresult=$?\n\t\t\tfi\n\t\t\tif [ \"$result\" -ne 0 ]; then\n\t\t\t\tretval=$result\n\t\t\tfi\n\t\tfi\n\tdone\n\treturn $retval\n}\n\ndo_pimreset() {\n    local pim opt retval\n    retval=0\n    pim=-1\n    while getopts \"23456789a\" opt; do\n        case $opt in\n            a)\n                pim=0\n                ;;\n            2)\n                pim=2\n                ;;\n            3)\n                pim=3\n                ;;\n            4)\n                pim=4\n                ;;\n            5)\n                pim=5\n                ;;\n            6)\n                pim=6\n                ;;\n            7)\n                pim=7\n                ;;\n            8)\n                pim=8\n                ;;\n            9)\n                pim=9\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    if [ $pim -eq -1 ]; then\n      usage\n      exit 1\n    fi\n\n    toggle_pim_reset $pim\n    retval=$?\n\n    return $retval\n}\n\ndo_pim_power_on() {\n\tlocal pim opt retval\n\tretval=0\n\tpim=-1\n\twhile getopts \"23456789a\" opt; do\n\t\tcase $opt in\n\t\t\ta)\n\t\t\t\tpim=0\n\t\t\t\t;;\n\t\t\t2)\n\t\t\t\tpim=2\n\t\t\t\t;;\n\t\t\t3)\n\t\t\t\tpim=3\n\t\t\t\t;;\n\t\t\t4)\n\t\t\t\tpim=4\n\t\t\t\t;;\n\t\t\t5)\n\t\t\t\tpim=5\n\t\t\t\t;;\n\t\t\t6)\n\t\t\t\tpim=6\n\t\t\t\t;;\n\t\t\t7)\n\t\t\t\tpim=7\n\t\t\t\t;;\n\t\t\t8)\n\t\t\t\tpim=8\n\t\t\t\t;;\n\t\t\t9)\n\t\t\t\tpim=9\n\t\t\t\t;;\n\t\t\t*)\n\t\t\t\tusage\n\t\t\t\texit 1\n\t\t\t\t;;\n\t\tesac\n\tdone\n\tif [ $pim -eq -1 ]; then\n\t\tusage\n\t\texit 1\n\tfi\n\n\ttoggle_pim_power_onoff on $pim\n\tretval=$?\n\n\treturn $retval\n}\n\ndo_pim_power_off() {\n\tlocal pim opt retval\n\tretval=0\n\tpim=-1\n\twhile getopts \"23456789a\" opt; do\n\t\tcase $opt in\n\t\t\ta)\n\t\t\t\tpim=0\n\t\t\t\t;;\n\t\t\t2)\n\t\t\t\tpim=2\n\t\t\t\t;;\n\t\t\t3)\n\t\t\t\tpim=3\n\t\t\t\t;;\n\t\t\t4)\n\t\t\t\tpim=4\n\t\t\t\t;;\n\t\t\t5)\n\t\t\t\tpim=5\n\t\t\t\t;;\n\t\t\t6)\n\t\t\t\tpim=6\n\t\t\t\t;;\n\t\t\t7)\n\t\t\t\tpim=7\n\t\t\t\t;;\n\t\t\t8)\n\t\t\t\tpim=8\n\t\t\t\t;;\n\t\t\t9)\n\t\t\t\tpim=9\n\t\t\t\t;;\n\t\t\t*)\n\t\t\t\tusage\n\t\t\t\texit 1\n\t\t\t\t;;\n\t\tesac\n\tdone\n\tif [ $pim -eq -1 ]; then\n\t\tusage\n\t\texit 1\n\tfi\n\n\ttoggle_pim_power_onoff off $pim\n\tretval=$?\n\n\treturn $retval\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\nset_bic=0\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        set_bic=1\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        set_bic=1\n        ;;\n    pimreset)\n        do_pimreset \"$@\"\n        exit $?\n        ;;\n\tpim_power_on)\n\t\tdo_pim_power_on \"$@\"\n\t\texit $?\n\t\t;;\n\tpim_power_off)\n\t\tdo_pim_power_off \"$@\"\n\t\texit $?\n\t\t;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nif [ $set_bic -ne 0 ]; then\n# sleep 10 second to wait BIC & COMe ready\n    (sleep 10; setup_bic.sh) &\nfi\n\nexit $?\n", "num_lines": 490}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get output from bic-util\nbic_output=$(bic-util scm --read_mac)\n\n# Check if the read was successful and output matches with our format\nmatch=$(echo \"$bic_output\" | grep -c 'MAC address: [0-9a-f][0-9a-f]:')\nif [ \"$match\" = \"1\" ]; then\n    # Mac address: xx:xx:xx:xx:xx:xx\n    echo \"$bic_output\" | cut -d ' ' -f 3\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit 1\nfi\n\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\n#\n# Main entry starts here\n#\n/usr/local/bin/setup_avs.sh\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n#At this way, it uses to GPIO mode\ndevmem_clear_bit 0x1e6e2070 12\ndevmem_clear_bit 0x1e6e2070 13\n\nif [ ! -L \"${SHADOW_GPIO}/BMC_EEPROM1_SPI_SS\" ]; then\n    gpio_export_by_name \"$ASPEED_GPIO\" GPIOI4 BMC_EEPROM1_SPI_SS\n    gpio_export_by_name \"$ASPEED_GPIO\" GPIOI5 BMC_EEPROM1_SPI_SCK\n    gpio_export_by_name \"$ASPEED_GPIO\" GPIOI6 BMC_EEPROM1_SPI_MOSI\n    gpio_export_by_name \"$ASPEED_GPIO\" GPIOI7 BMC_EEPROM1_SPI_MISO\nfi\n\ngpio_set_value SWITCH_EEPROM1_WRT 1\n\n/usr/local/bin/at93cx6_util_py3.py --cs BMC_EEPROM1_SPI_SS \\\n                                   --clk BMC_EEPROM1_SPI_SCK \\\n                                   --mosi BMC_EEPROM1_SPI_MOSI \\\n                                   --miso BMC_EEPROM1_SPI_MISO $@\n\n#resolve to SPI mode for another flash using(backup flash)\ndevmem_set_bit 0x1e6e2070 12\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nstatus_switch() {\n\tprompt=1\n\twhile getopts \"f\" opts; do\n\t\tcase $opts in\n\t\t\tf)\n\t\t\t\tprompt=0\n\t\t\t\tshift\n\t\t\t\t;;\n\t\t\t*)\n\t\t\t\tprompt=1\n\t\t\t\t;;\n\t\tesac\n\tdone\n\tif [ \"$1\" = \"mdio\" ]; then\n\t\tgpio_set_value SWITCH_EEPROM1_WRT 1\n\telif [ \"$1\" = \"eeprom\" ]; then\n\t\tgpio_set_value SWITCH_EEPROM1_WRT 0\n\telse\n\t\techo \"Mode doesn't support!\"\n\t\treturn 1\n\tfi\n\tif [ $prompt -eq 1 ]; then\n\t\tprintf \"Need to reset BCM5389(Y/n) \"\n\t\tread confirm\n\t\tif [ \"$confirm\" = \"Y\" ] || [ \"$confirm\" = \"y\" ]; then\n\t\t\tprintf \"Reset......\"\n\t\t\ti2cset -f -y 12 0x31 0x14 0xfb\n\t\t\tsleep 1\n\t\t\ti2cset -f -y 12 0x31 0x14 0xff\n\t\t\tprintf \"OK\\n\"\n\t\tfi\n\telse\n\t\tprintf \"Reset......\"\n\t\ti2cset -f -y 12 0x31 0x14 0xfb\n\t\tsleep 1\n\t\ti2cset -f -y 12 0x31 0x14 0xff\n\t\tprintf \"OK\\n\"\n\tfi\n\n\treturn 0\n}\n\ncommand=\"$1\"\ncase \"$command\" in\n\t--mode)\n\t\tshift\n\t\tstatus_switch $@\n\t\t;;\n\t*)\n\t\tbcm5396_util.py $@\n\t\t;;\nesac\n", "num_lines": 58}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\ni2cset -f -y 0 0x3e 0x16 0x01\nif [ ! -f /dev/spidev5 ]\nthen\n\tmknod /dev/spidev5.0 c 153 0\n\tmodprobe spidev\nfi\nflashrom -p linux_spi:dev=/dev/spidev5.0 -c W25Q64.V\n#flashrom -p linux_spi:dev=/dev/spidev5.0 -r bios\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n\nSYSCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-0031)\nSCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 0-003e)\nGALAXY_EC_SYSFS_DIR=$(i2c_device_sysfs_abspath 0-0033)\nSCM_EEPROM_SYSFS_DIR=$(i2c_device_sysfs_abspath 0-0052)\nMB_EEPROM_SYSFS_DIR=$(i2c_device_sysfs_abspath 6-0051)\nSCM_EEPROM=\"${SCM_EEPROM_SYSFS_DIR}/eeprom\"\nMB_EEPROM=\"${MB_EEPROM_SYSFS_DIR}/eeprom\"\nPWR_MAIN_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_main_n\"\nSCM_PRESENT_SYSFS=\"${SYSCPLD_SYSFS_DIR}/micro_srv_present\"\nPWR_BOARD_VER=\"${SYSCPLD_SYSFS_DIR}/board_ver\"\nSLOTID_SYSFS=\"${SYSCPLD_SYSFS_DIR}/slotid\"\nPWR_USRV_SYSFS=\"${SCMCPLD_SYSFS_DIR}/pwr_come_en\"\nrepower=0\n\nwedge_iso_buf_enable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_is_us_on() {\n    local val n retries prog\n    if [ $# -gt 0 ]; then\n        retries=\"$1\"\n    else\n        retries=1\n    fi\n    if [ $# -gt 1 ]; then\n        prog=\"$2\"\n    else\n        prog=\"\"\n    fi\n    if [ $# -gt 2 ]; then\n        default=$3              # value 0 means defaul is 'ON'\n    else\n        default=1\n    fi\n    #val=$(cat $PWR_USRV_SYSFS 2> /dev/null | head -n 1)\n\t((val=$(i2cget -f -y 0 0x3e 0x10 2> /dev/null | head -n 1)))\n    if [ -z \"$val\" ]; then\n        return $default\n    elif [ `expr $val % 2` == \"1\" ]; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n}\n\nwedge_board_type() {\n    echo 'Galaxy100'\n}\n\nwedge_slot_id() {\n    printf \"%d\\n\" $(cat $SLOTID_SYSFS)\n}\n\nwedge_board_rev() {\n    local val\n    val=$(cat $PWR_BOARD_VER 2> /dev/null | head -n 1)\n    echo $val\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    # wedge100 uses BMC MAC since beginning\n    return -1\n}\n\ngalaxy100_scm_is_present() {\n\t#check scm if is present\n\tpresent=$(cat $SCM_PRESENT_SYSFS | head -n 1)\n\tif [ \"$present\" != \"0x0\" ]; then\n\t\treturn 1\n\tfi\n\treturn 0\n}\n\nwedge_power_on_board() {\n    local val present\n    # power on main power, uServer power\n    val=$(cat $PWR_MAIN_SYSFS | head -n 1)\n    if [ \"$val\" != \"0x1\" ]; then\n        echo 1 > $PWR_MAIN_SYSFS\n        sleep 2\n    fi\n}\n\nwedge_power_off_board() {\n    # power off main power, uServer power\n    echo 0 > $PWR_MAIN_SYSFS\n    sleep 2\n}\n\ncome_recovery() {\n\t#repeater config\n\trepeater_config\n\tKR10G_repeater_config\n\twedge_power_on_board\n\t#disable the I2C buffer to EC first\n\ti2cset -f -y 0 0x3e 0x18 0x07 2> /dev/null\n\tsleep 1\n\ti2cset -f -y 0 0x3e 0x10 0xfd 2> /dev/null\n\tusleep 11000\n\ti2cset -f -y 0 0x3e 0x0b 0xff 2> /dev/null\n\tsleep 15\n\ti2cset -f -y 0 0x3e 0x0b 0xfe 2> /dev/null\n\tusleep 11000\n\ti2cset -f -y 0 0x3e 0x10 0xfe 2> /dev/null\n\tsleep 10\n\ti2cset -f -y 0 0x3e 0x10 0xff 2> /dev/null\n\tusleep 11000\n\t#enable I2c buffer to EC\n\ti2cset -f -y 0 0x3e 0x18 0x01 2> /dev/null\n\n\treturn 0\n}\n\nrestore_us_com() {\n\trepeater_config\n\tKR10G_repeater_config\n\twedge_power_on_board\n\t#reset LPC bridge\n\ti2cset -f -y 0 0x3e 0x31 0x0 2> /dev/null\n\tusleep 10000\n\ti2cset -f -y 0 0x3e 0x31 0x1 2> /dev/null\n\n\ti2cset -f -y 0 0x3e 0x10 0xff 2> /dev/null\n\t#enable I2c buffer to EC\n\ti2cset -f -y 0 0x3e 0x18 0x01 2> /dev/null\n}\n\nget_power_flag() {\n\treturn $repower\n}\nset_power_flag() {\n\trepower=$1\n}\n\ni2c_write() {\n\tlocal count=0\n\twhile [ $count -lt 10 ]; do\n\t\ti2cset -f -y $1 $2 $3 $4\n\t\tif [ $? -eq 0 ]; then\n\t\t\treturn 0\n\t\tfi\n\t\tcount=$(($count+1))\n\t\tusleep 11000\n\tdone\n\treturn -1\n}\n\ni2c_read() {\n\tlocal count=0\n\twhile [ $count -lt 10 ]; do\n\t\ttemp=`i2cget -f -y $1 $2 $3`\n\t\tif [ $? -eq 0 ]; then\n\t\t\treturn $(($temp))\n\t\tfi\n\t\tcount=$(($count+1))\n\t\tusleep 11000\n\tdone\n\treturn -1\n}\n#$1: bus\n#$2: addr\n#$3: reg\n#$4: value\n#$5: mask\ni2c_write_verify() {\n\tcount=0\n\twhile [ $count -lt 10 ]; do\n\t\t#echo \"i2c write $1 $2 $3 $4\"\n\t\ti2c_write $1 $2 $3 $4 2> /dev/null\n\t\tif [ $? -eq 255 ]; then\n\t\t\tcount=$(($count+1))\n\t\t\tcontinue\n\t\tfi\n\t\t((val=$4))\n\t\t((mask=$5))\n\t\t#echo -n \"i2c read $1 $2 $3  \"\n\t\ti2c_read $1 $2 $3 2> /dev/null\n\t\ttemp=$?\n\t\t#echo -n \"=$temp val=$val    \"\n\t\tif [ $temp -eq 255 ]; then\n\t\t\tcount=$(($count+1))\n\t\t\tcontinue\n\t\tfi\n\t\t((ret=temp))\n\t\t#echo -n \"ret=$ret  mask=$mask  \"\n\t\tif (((($ret & $mask)) == (($val)))); then\n\t\t\t#echo \"equal\"\n\t\t\treturn 0\n\t\tfi\n\t\tcount=$(($count+1))\n\tdone\n\t#echo \"Write bus $1 addr $2 reg $3 value $4 error!\"\n\treturn 1\n}\nrepeater_config() {\n\t((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\n\t((left=$(i2cget -f -y 12 0x31 0x5 2> /dev/null | head -n 1)))\n\tif [ $val -lt 8  -a $left -eq 0 ] || [ $val -ge 8 ]; then\n\t\ti2c_write_verify 0 0x58 0x01 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x0a 0x0 0x0\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x2c 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x33 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3a 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x41 0x00 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x2d 0xa8 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x34 0xa8 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3b 0xa9 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x42 0xa9 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x2e 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x35 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3c 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x43 0x02 0x1f\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x0f 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x16 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1d 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x24 0x0 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x10 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x17 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1e 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x25 0xaf 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x11 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x18 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1f 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x26 0x0 0x1f\n\t\tusleep 11000\n\telse\n\n\t\ti2c_write_verify 0 0x58 0x01 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x0a 0x0 0x0\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x2c 0x04 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x33 0x04 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3a 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x41 0x00 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x2d 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x34 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3b 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x42 0xab 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x2e 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x35 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x3c 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x43 0x02 0x1f\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x0f 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x16 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1d 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x24 0x01 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x10 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x17 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1e 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x25 0xaf 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x58 0x11 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x18 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x1f 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x58 0x26 0x0 0x1f\n\t\tusleep 11000\n\tfi\n}\n\nKR10G_repeater_config() {\n\t((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\n\t((left=$(i2cget -f -y 12 0x31 0x5 2> /dev/null | head -n 1)))\n\tif [ $val -lt 8  -a $left -eq 0 ] || [ $val -ge 8 ]; then\n\t\ti2c_write_verify 0 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x0f 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x11 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x23 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x16 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x18 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x2d 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 1 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x0f 0x02 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x11 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x23 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 1 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x16 0x04 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x18 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x2d 0x04 0xff\n\t\tusleep 11000\n\telse\n\t\ti2c_write_verify 0 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x0f 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x11 0x04 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x23 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 0 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x16 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x18 0x04 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 0 0x59 0x2d 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 1 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x0f 0x02 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x11 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x23 0x04 0xff\n\t\tusleep 11000\n\n\t\ti2c_write_verify 1 0x59 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x16 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x18 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_write_verify 1 0x59 0x2d 0x04 0xff\n\t\tusleep 11000\n\tfi\n}\n", "num_lines": 409}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#\n# A simple script to flush i2c clock signals to recover from I2C stuck issue.\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n#\n# Initialize variables, and define a helper function\n#\n\niteration=0\nrc=0\nI2C_CMD=\"${SYSCPLD_SYSFS_DIR}/i2c_sta_rst_raw\"\n\nforce_stop() {\n\techo \"Sending out START condition through I2C bus\"\n\techo 0x07 > $I2C_CMD\n  usleep 5000\n  echo 0x0F > $I2C_CMD\n  usleep 5000\n}\n\n#\n# Step 1. Hold both SDA and SCL high\n#\necho \"Holding SDA and SCL high\"\necho 0x0F > $I2C_CMD\n\n#\n# Step 2. Toggle SCL up to 10 times, until bus recovers\n#\nwhile [ $iteration -lt 10 ];\ndo\n\techo \"Toggling SCL for clock flushing. Iteration : $iteration\"\n  # SCL low\n\techo 0x0B > $I2C_CMD\n  usleep 5000\n  # SCL high\n\techo 0x0F > $I2C_CMD\n\tusleep 5000\n  # Check if bus recovered by looking at bit [5:4]\n\trc=$(cat $I2C_CMD | head -n 1 | awk -F \"0x\" '{print $2}')\n\tif (($rc & 0x30)); then\n\t\techo \"Bus recovery successful\"\n\t\trc=0\n\t\tbreak\n\tfi\n\techo \"I2C BUS not yet recovered\"\n\titeration=$(($iteration+1))\ndone\n\n#\n# Step 3. Handle the result, and run force_stop if asked to do so\n#         Setting return code to -1, if recovery is not successful\n#\nif [ $(($rc)) -ne 0 ]; then\n\techo \"Bus recovery failure\"\n  rc=-1\nfi\nif [ $# -eq 1 ] && [ $1 == \"-f\" ]; then\n\tforce_stop\nfi\n\n#\n# Step 4. Put the I2C block in normal operation mode\n#\necho \"Putting I2C master back to normal operation mode\"\necho 0x0D > $I2C_CMD\n\n#\n# Step 5. Finally, toggle reset CP2112, no matter recovery successful or not\n#\necho \"Toggle resetting CP2112\"\n/bin/bash /usr/local/bin/reset_cp2112.sh\n\n#\n# Step 6. Exit with the return code\n#\necho \"Exiting with rc $rc\"\nexit $rc\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.\u00c2\u00a0 See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nEC_VERSION=$(head -n 1 \"${GALAXY_EC_SYSFS_DIR}/version\")\n\nr=$(echo \"$EC_VERSION\" | awk '{print substr ($1, 2, 2)}')\ne=$(echo \"$EC_VERSION\" | awk '{print substr ($1, 5, 2)}')\n\nreleased_date=$(head -n 1 \"${GALAXY_EC_SYSFS_DIR}/build_date_input\")\n\necho \"EC Released Version: R$(printf '%02d' $r).E$(printf '%02d' $e)\"\necho \"EC Released Date: $released_date\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ndevmem_clear_bit 0x1e6e2080 20\ndevmem_clear_bit 0x1e6e208c 14\n\ni2cset -f -y 12 0x31 0x06 0x4 2>/dev/null #sysled light blue\ni2cset -f -y 0 0x3e 0x18 0x1 2>/dev/null #open EC buffer\n\ndevmem 0x1e78a044 32 0x77776f05 #increase thDDAT\n\n/usr/local/bin/us_refresh.sh &\n\nval=$(i2cget -f -y 12 0x31 0x22 2> /dev/null)\nif [ \"$val\" = \"0x11\" ] ; then\n\ti2cset -f -y 12 0x31 0x22 0x0\n\tsoft_reboot=0\nelse\n\tsoft_reboot=1\n\techo \"System boot by software reboot\"\nfi\n\nif galaxy100_scm_is_present && [ $soft_reboot -eq 0 ] ; then\n\t# First power on TH, and if Panther+ is used,\n\t# provide standby power to Panther+.\n\trepeater_config\n\twedge_power_on_board\n\n\techo -n \"Checking microserver present status ... \"\n\tif wedge_is_us_on 10 \".\"; then\n\t\techo \"on\"\n\t    on=1\n\t    # microsever reset\n\t    wedge_power.sh reset\n\telse\n\t    echo \"off\"\n\t\ton=0\n\tfi\n\n\tif [ $on -eq 0 ]; then\n\t    # Power on now\n\t    wedge_power.sh on -f\n\tfi\n\tKR10G_repeater_config\nelif ! galaxy100_scm_is_present ; then\n\techo \"SCM isn't present...\"\nfi\n\n\nif galaxy100_scm_is_present ; then\n\techo -n \"SCM CPLD access \"\n\tver=$(i2cget -f -y 0 0x3e 0x1 2> /dev/null)\n\tif [ $? -ne 0 ] || [ $ver = \"0xff\" ]; then\n\t\techo \"[Fail]\"\n\telse\n\t\techo \"[OK]\"\n\tfi\n\tif [ $soft_reboot -eq 1 ]; then\n\t\techo -n \"Checking microserver present status ... \"\n\t\tif wedge_is_us_on 10 \".\"; then\n\t\t\techo \"on\"\n\t\t    on=1\n\t\telse\n\t\t    echo \"off\"\n\t\t\ton=0\n\t\tfi\n\t\tif [ $on -eq 0 ]; then\n\t\t\trepeater_config\n\t\t\twedge_power_on_board\n\t\t    # Power on now\n\t\t    wedge_power.sh on -f\n\t\t\tKR10G_repeater_config\n\t\t\t#reset LPC bridge\n\t\t\ti2cset -f -y 0 0x3e 0x31 0x0 2> /dev/null\n\t\t\tusleep 10000\n\t\t\ti2cset -f -y 0 0x3e 0x31 0x1 2> /dev/null\n\t\tfi\n\n\t\tmac=$(/usr/local/bin/wedge_us_mac.sh)\n\t\techo -n \"COM-e MAC: $mac \"\n\t\tif [ $mac = \"00:00:00:00:00:00\" ]; then\n\t\t\techo \"[Warning]\"\n\t\telse\n\t\t\techo \"[OK]\"\n\t\tfi\n\t\t/usr/local/bin/repeater_verify.sh\n\tfi\nfi\n", "num_lines": 112}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n\nlc_qsfp_cpld_ver() {\n  card_type=$(weutil  | grep 'Product Name' | awk -F ':' '{print $2}')\n  card_type=${card_type,,}\n\n  major_rev=0\n  sub_rev=0\n  if [ $card_type == 'lc' ] || [ $card_type == 'galaxy-lc' ]; then\n    #QSFP CPLD version\n    ((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\n    if [ $val -lt 8 ]; then\n      old=$((`i2cget -f -y 12 0x74 0x01`))\n      if [ $old -eq 9 ] || [ $old -eq 12 ] || [ $old -eq 13 ]; then\n        i2cset -f -y 12 0x74 0x01 0x0\n      elif [ $old -eq 10 ] || [ $old -eq 14 ] || [ $old -eq 15 ]; then\n        i2cset -f -y 12 0x74 0x01 0x1\n      elif [ $old -eq 0 ] || [ $old -eq 1 ] || [ $old -eq 5 ]; then\n        i2cset -f -y 12 0x74 0x01 0x4\n      elif [ $old -eq 2 ] || [ $old -eq 3 ] || [ $old -eq 6 ]; then\n        i2cset -f -y 12 0x74 0x01 0x5\n      fi\n      temp=$((`i2cget -f -y 12 0x39 0x01 2> /dev/null`))\n      major_rev=$(($temp & 0x3f))\n      sub_rev=$(i2cget -f -y 12 0x39 0x02 2> /dev/null | awk -F \"0x\" '{print $2}')\n    fi\n  fi\n    printf \"%02x,%02d\\n\" ${major_rev} ${sub_rev}\n}\n\nlc_qsfp_cpld_ver\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\ni2c_read() {\n\tlocal count=0\n\twhile [ $count -lt 10 ]; do\n\t\ttemp=`i2cget -f -y $1 $2 $3`\n\t\tif [ $? -eq 0 ]; then\n\t\t\treturn $(($temp))\n\t\tfi\n\t\tcount=$(($count+1))\n\t\tusleep 11000\n\tdone\n\treturn -1\n}\n\n#$1: bus\n#$2: addr\n#$3: reg\n#$4: value\n#$5: mask\ni2c_read_verify() {\n\t((val=$4))\n\t((mask=$5))\n\t#echo -n \"i2c read $1 $2 $3  \"\n\ti2c_read $1 $2 $3 2> /dev/null\n\ttemp=$?\n\tprintf \"Verify bus:%d addr:0x%02x reg:0x%02x value:0x%02x (expect 0x%02x)   \" $1 $2 $3 $(($temp&$mask)) $4\n\t#echo -n \"=$temp val=$val    \"\n\tif [ $temp -eq 255 ]; then\n\t\techo -e \"\\033[41;37m[FAIL]\\033[0m\"\n\t\treturn 1\n\tfi\n\t((ret=temp))\n\t#echo -n \"ret=$ret  mask=$mask  \"\n\tif (((($ret & $mask)) == (($val)))); then\n\t\techo -e \"\\033[42;37m[PASS]\\033[0m\"\n\t\treturn 0\n\telse\n\t\techo -e \"\\033[41;37m[FAIL]\\033[0m\"\n\t\treturn 1\n\tfi\n\treturn 1\n}\n\nrepeater_config() {\n\t((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\n\t((left=$(i2cget -f -y 12 0x31 0x5 2> /dev/null | head -n 1)))\n\tif [ $val -lt 8  -a $left -eq 0 ] || [ $val -ge 8 ]; then\n\t\ti2c_read_verify 0 0x58 0x01 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x0a 0x0 0x0\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x2c 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x33 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3a 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x41 0x00 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x2d 0xa8 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x34 0xa8 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3b 0xa9 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x42 0xa9 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x2e 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x35 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3c 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x43 0x02 0x1f\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x0f 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x16 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1d 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x24 0x0 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x10 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x17 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1e 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x25 0xaf 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x11 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x18 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1f 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x26 0x0 0x1f\n\t\tusleep 11000\n\telse\n\n\t\ti2c_read_verify 0 0x58 0x01 0x0 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x0a 0x0 0x0\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x06 0x18 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x2c 0x04 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x33 0x04 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3a 0x00 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x41 0x00 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x2d 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x34 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3b 0xab 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x42 0xab 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x2e 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x35 0x01 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x3c 0x02 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x43 0x02 0x1f\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x0f 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x16 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1d 0x01 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x24 0x01 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x10 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x17 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1e 0xaf 0xff\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x25 0xaf 0xff\n\t\tusleep 11000\n\n\t\ti2c_read_verify 0 0x58 0x11 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x18 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x1f 0x0 0x1f\n\t\tusleep 11000\n\t\ti2c_read_verify 0 0x58 0x26 0x0 0x1f\n\t\tusleep 11000\n\tfi\n}\n\nrepeater_config\n", "num_lines": 177}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n#\n# A simple script to toggle reset CP2112 device\n#\n\nCP2112_RESET_CMD=\"${SYSCPLD_SYSFS_DIR}/cp2112_rst\"\n\n#\n# Toggle reset CP2112, with enough time in-between for chip status settle down\n#\necho 0x0 > $CP2112_RESET_CMD\nusleep 50000\necho 0x1 > $CP2112_RESET_CMD\nusleep 50000\n\n#\n# If the execution reached here, that means all writes went through\n# return 0.\n#\nexit 0\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nrev=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/cpld_rev\")\nsub_rev=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/cpld_sub_rev\")\n\necho $(($rev)).$(($sub_rev))\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\nif [ $val -ge 8 ]; then\n\tmv /etc/sensors.d/galaxy100_fab.conf /etc/sensors.d/galaxy100.conf\n\trm /etc/sensors.d/galaxy100_lc.conf\nelse\n\tmv /etc/sensors.d/galaxy100_lc.conf /etc/sensors.d/galaxy100.conf\n\trm /etc/sensors.d/galaxy100_fab.conf\nfi\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Bus 0\ni2c_device_add 0 0x10 adm1278\ni2c_device_add 0 0x18 ds110df111\ni2c_device_add 0 0x21 pca9534\ni2c_device_add 0 0x33 galaxy100_ec\ni2c_device_add 0 0x3e scmcpld\ni2c_device_add 0 0x54 24c02\ni2c_device_add 0 0x52 24c02\n\n# Bus 1\ni2c_device_add 1 0x18 ds110df111\ni2c_device_add 1 0x70 IR3581\ni2c_device_add 1 0x72 IR3584\n\n# Bus 2\ni2c_device_add 2 0x40 pwr1014a\n\n# Bus 5\ni2c_device_add 5 0x20 slb9645tt\n\n# Bus 6\ni2c_device_add 6 0x27 pcf8574\ni2c_device_add 6 0x51 24c64\n\n# Bus 9\ni2c_device_add 9 0x50 24c02\n\n# Bus 11\ni2c_device_add 11 0x10 adm1278\n\n# Bus 12\ni2c_device_add 12 0x31 syscpld\ni2c_device_add 12 0x39 qsfp_cpld\n\n#\n# setup ADC channels\n# This step is only needed in legacy kernel (v4.1), because the ADC\n# controller is configured in device tree in the latest kernel.\n#\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    modprobe ast_adc\n    # channel 3: r1:  2.0K; r2:  1.0K; v2: 0mv\n    # channel 4: r1:  4.7K; r2:  1.0K; v2: 0mv\n    # channel 8: r1:  1.0K; r2:  1.0K; v2: 0mv\n    # channel 9: r1:  1.0K; r2:  1.0K; v2: 0mv\n    ast_config_adc 3  2 1 0\n    ast_config_adc 4  47 10 0\n    ast_config_adc 8  1 1 0\n    ast_config_adc 9  1 1 0\nfi\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\n#reset MUX that uS console connects to UART1.\ni2cset -f -y 0 0x3e 0x30 0xfe 2>/dev/null\nusleep 100000\ni2cset -f -y 0 0x3e 0x30 0xff 2>/dev/null\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Because the voltage leak from uS COM pins could cause uS to struck when\n# transitting from S5 to S0, we will need to explicitely pull down uS COM\n# pins before powering off/reset and restoring COM pins after\n\nTH_SHUTDOWN_VOL=949\nTH_RESTORE_VOL=1028\nth_shutdown=0\n\nrestore_us_com() {\n    repeater_config\n    KR10G_repeater_config\n    wedge_power_on_board\n    i2cset -f -y 0 0x3e 0x10 0xff 2> /dev/null\n    logger \"Power on micro-server after inserting SCM\"\n}\n\nlm57_monitor() {\n    vol=$(cat /sys/devices/platform/ast_adc.0/in0_input 2> /dev/null)\n    if [ $vol -le ${TH_SHUTDOWN_VOL} ] && [ $th_shutdown -eq 0 ] ; then\n        echo \"Shut down TH power by LM57 over temperature...\"\n        echo \"ADC=$vol, standard=$TH_SHUTDOWN_VOL\"\n        wedge_power_off_board\n        th_shutdown=1\n        logger \"Power off micro-server due to LM57 over temperature (${vol} vs ${TH_SHUTDOWN_VOL})\"\n    fi\n    if [ $vol -ge ${TH_RESTORE_VOL} ] && [ $th_shutdown -eq 1 ] ; then\n        echo \"restore TH power by LM57 temperature drop...\"\n        echo \"ADC=$vol, standard=$TH_RESTORE_VOL\"\n        wedge_power_on_board\n        th_shutdown=0\n        logger \"Power on micro-server after LM57 temperature drop (${vol} vs ${TH_SHUTDOWN_VOL})\"\n    fi\n    cpld_val=$(i2cget -f -y 12 0x31 0x15 2> /dev/null)\n    if [ $vol -ge ${TH_RESTORE_VOL} ] && [ \"$cpld_val\" = \"0x11\" ] ; then\n        echo \"restore TH power which shutdown by CPLD...\"\n        i2cset -f -y 12 0x31 0x15 0x0 2> /dev/null\n        wedge_power_on_board\n        th_shutdown=0\n        logger \"Power on micro-server caused by CPLD (${cpld_val}, ${vol} vs ${TH_SHUTDOWN_VOL})\"\n    fi\n}\n\nval=0\nret=0\necho 1 > /sys/devices/platform/ast_adc.0/adc0_en\ncome_check=0\nwait_count=0\npower_ok=0\nscm_removed=0\nth_reset_delay=0\n((card_val=$(i2cget -f -y 12 0x31 0x0 2> /dev/null | head -n 1)))\ncard_val=$(($card_val % 16))\nif [ $card_val -le 1 ]; then\n    #EVT or DVT1 board\n    TH_SHUTDOWN_VOL=1296\n    TH_RESTORE_VOL=1402\nfi\nwhile true; do\n    galaxy100_scm_is_present\n    ret=$?\n    if [ $ret -eq 0 ] && [ $val -eq 1 ]; then\n        echo \"SCM is inserted, Power ON!\"\n\t\t    come_check=1\n\t\t    power_ok=1\n\t\t    wait_count=0\n\t\t    scm_removed=0\n\t\t    th_reset_delay=0\n\t  elif [ $ret -eq 0 ] && [ $come_check -eq 1 ] && [ $power_ok -eq 0 ]; then\n\t\t    ((temp=$(i2cget -f -y 0 0x3e 0x12 2> /dev/null | head -n 1)))\n\t\t    if [ $temp != 15 ] ; then\n\t\t\t      echo \"Power on COM-e fail, recovery...\"\n\t\t\t      come_recovery\n\t\t\t      wait_count=0\n\t\t\t      power_ok=0\n\t\t\t      come_check=0\n\t\t\t      logger \"Recovered COMe failed to power on\"\n\t\t    else\n\t\t\t      come_check=0\n\t\t\t      power_ok=1\n\t\t\t      echo \"Power on COM-e OK\"\n\t\t    fi\n\t  elif [ $ret -eq 1 -a $val -eq 0 ] || [ $scm_removed -eq 1 ]; then\n\t\t    scm_removed=1\n\t\t    if [ $th_reset_delay -ge 20 ]; then\n\t\t\t      #reset TH\n\t\t\t      i2cset -f -y 12 0x31 0x12 0xf2 2> /dev/null\n\t\t\t      usleep 500000\n\t\t\t      i2cset -f -y 12 0x31 0x12 0xf3 2> /dev/null\n\t\t\t      scm_remove=0\n\t\t\t      logger \"Reset Tomahawk after removing SCM\"\n\t\t    fi\n\t\t    th_reset_delay=$(($th_reset_delay + 1))\n\t  else\n\t\t    wait_count=$(($wait_count + 1))\n\t\t    if [ $ret -eq 0 ] && [ $wait_count -ge 30 ] && [ $come_check -eq 1 ] && [ $power_ok -eq 1 ]; then\n\t\t\t      if [ $wait_count -eq 30 ]; then\n\t\t\t\t        #after 15s, power on\n\t\t\t\t        restore_us_com\n\t\t\t      elif [ $wait_count -ge 70 ]; then\n\t\t\t\t        #after 20s, check status\n\t\t\t\t        power_ok=0\n\t\t\t      fi\n\t\t    fi\n\t\t    if [ $wait_count -ge 360 ]; then\n\t\t\t      wait_count=0\n\t\t\t      if [ $power_ok -eq 0 ]; then\n\t\t\t\t        #echo \"Check again\"\n\t\t\t\t        come_check=1\n\t\t\t      fi\n\t\t    fi\n    fi\n    val=$ret\n    lm57_monitor\n    usleep 500000\ndone\n", "num_lines": 134}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Because the voltage leak from uS COM pins could cause uS to struck when\n# transitting from S5 to S0, we will need to explicitely pull down uS COM\n# pins before powering off/reset and restoring COM pins after\n\n\n\nlc_r=0\n((val=$(i2cget -f -y 12 0x31 0x3 2> /dev/null | head -n 1)))\n((right=$(i2cget -f -y 12 0x31 0x5 2> /dev/null | head -n 1)))\nif [ $val -lt 8  -a $right -eq 1 ]; then\n\tlc_r=1\nfi\nlc_r_rec_msg() {\n\tif [ $lc_r -eq 1 ]; then\n\t\ti2cset -f -y 12 0x31 0x28 0x0 2> /dev/null\n\t\ttmp=$(i2cget -f -y 12 0x31 0x28 2> /dev/null)\n\t\tval=$(($tmp & 0x70))\n\t\ttmp2=$(i2cget -f -y 12 0x31 0x28 2> /dev/null) #double check\n\t\tif [ $val -eq $((0x50)) -a $tmp = $tmp2 ]; then\n\t\t\techo \"Receive msg to power on COMe because of SCM CPLD upgrading\"\n\t\t\ti2cset -f -y 12 0x31 0x28 0x05 2> /dev/null\n\t\t\t#power off COMe\n\t\t\t#i2cset -f -y 0 0x3e 0x10 0xfd 2> /dev/null\n\t\t\t#sleep 2\n\t\t\t#i2cset -f -y 0 0x3e 0x10 0xfe 2> /dev/null\n\n\t\t\t#reset TH\n\t\t\t#i2cset -f -y 12 0x31 0x12 0xf2 2> /dev/null\n\t\t\t#sleep 1\n\t\t\t#i2cset -f -y 12 0x31 0x12 0xf3 2> /dev/null\n\t\t\t\n\t\t\ti2cset -f -y 12 0x31 0x10 0xfd\t\t\t\n\n\t\t\tpower_status=1\n\t\t\tcount=0\n\t\t\tdelay_flag=0\n\t\tfi\n\tfi\n}\n\npower_status=0\ncount=0\ndelay_flag=0\nwhile true; do\n\tlc_r_rec_msg\n\tif [ $power_status -eq 1 -a $delay_flag -eq 1 ]; then\n\t\ti2cset -f -y 12 0x31 0x10 0xff\n\t\trestore_us_com\n\t\tpower_status=2\n\telif [ $power_status -eq 2 -a $delay_flag -eq 2 ]; then\n\t\t((temp=$(i2cget -f -y 0 0x3e 0x12 2> /dev/null | head -n 1)))\n\t\tif [ $temp != 15 ] ; then\n\t\t\techo \"Power on COM-e fail, recovery...\"\n\t\t\tcome_recovery\n\t\telse\n\t\t\techo \"Power on COM-e OK\"\n\t\t\tpower_status=0\n\t\t\tdelay_flag=0\n\t\tfi\n\tfi\n\tif [ $power_status -ne 0 ]; then\n\t\tif [ $count -eq 30 ]; then\n\t\t\tdelay_flag=1\n\t\telif [ $count -eq 70 ]; then\n\t\t\tdelay_flag=2\n\t\telif [ $count -ge 430 ]; then\n\t\t\tdelay_flag=2\n\t\t\tcount=71\n\t\telse\n\t\t\tdelay_flag=0\n\t\tfi\n\t\tcount=$(($count+1))\n\tfi\n\tusleep 500000\ndone\n", "num_lines": 94}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nPWR_SYSTEM_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_cyc_all_n\"\n#PWR_USRV_RST_SYSFS=\"${SCMCPLD_SYSFS_DIR}/come_rst_n\"\nALT_SYSRESET_SYSFS=\"/sys/bus/i2c/drivers/pwr1014a/2-0040/mod_hard_powercycle\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge system ungracefully\"\n    echo\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n    fi\n    return 0\n}\n\ndo_on_com_e() {\n    #echo 1 > $PWR_USRV_SYSFS\n    i2cset -f -y 0 0x3e 0x10 0xff 2> /dev/null\n    return $?\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on 10 \".\"; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # power on sequence\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        #enable I2c buffer to EC\n        i2cset -f -y 0 0x3e 0x18 0x01 2> /dev/null\n        echo \" Done\"\n        logger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    #echo 0 > $PWR_USRV_SYSFS\n    i2cset -f -y 0 0x3e 0x10 0xfd 2> /dev/null\n    sleep 15\n    i2cset -f -y 0 0x3e 0x10 0xfe 2> /dev/null\n    sleep 10\n    return 0\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver(about 30s) ...\"\n    #disable the I2C buffer to EC first\n    i2cset -f -y 0 0x3e 0x18 0x07 2> /dev/null\n    sleep 1\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n        logger \"Successfully power off micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power off micro-server\"\n    fi\n    return $ret\n}\n\ndo_reset() {\n    local system opt\n    system=0\n    while getopts \"s\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        logger \"Power reset the whole system ...\"\n        echo -n \"Power reset whole system ...\"\n        sleep 1\n        echo 0 > $PWR_SYSTEM_SYSFS\n        # In case the previous reset attempt fails, we try the alternative\n        # way - reset the entire module through PWR1014A\n        logger -s \"wedge_power.sh reset -s through CPLD failed. Using pwr1014a instead.\"\n        # Give rsyslog enough time to flush the log\n        sleep 5\n        echo 0 > $ALT_SYSRESET_SYSFS \n        sleep 1\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return -1\n        fi\n        echo -n \"Power reset microserver ...\"\n        #echo 0 > $PWR_USRV_RST_SYSFS\n        i2cset -f -y 0 0x3e 0x11 0x0 2> /dev/null\n        sleep 1\n        #echo 1 > $PWR_USRV_RST_SYSFS\n        i2cset -f -y 0 0x3e 0x11 0x1 2> /dev/null\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\ndo_recovery() {\n    local ret\n    echo -n \"Power on microserver recovery(about 30s) ...\"\n    come_recovery\n    echo \" Done\"\n    logger \"Successfully power recover micro-server\"\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit -1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    recovery)\n        do_recovery $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 211}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nif ! wedge_is_us_on; then\n    echo \"Cannot retrive microserver MAC when microserver is powered off.\" 1>&2\n    exit -2\nfi\n\ncount=0\nwhile [ $count -lt 10 ]\ndo\n  mac=$(cat \"${GALAXY_EC_SYSFS_DIR}/mac_addr\")\n\n\tif [ -n \"$mac\" -a \"${mac/X/}\" = \"${mac}\" ]; then\n\t    echo $mac\n\t    exit 0\n\tfi\n\tcount=$(($count + 1))\n\tsleep 1\ndone\n\nif [ $count -ge 10 ]; then\n\techo \"Cannot find out the microserver MAC\" 1>&2\n\texit -1\nfi\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-watchdogd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set watchdogd handler\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Disable the dual boot watch dog\ndevmem_clear_bit 0x1e78502c 0\n\n#\n# \"watchdogd\" is only needed in legacy kernel (v4.1), and the watchdog can\n# be automatically kicked by a kernel thread in the latest kernel.\n#\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    /usr/bin/watchdogd.sh > /dev/null 2>&1 &\nfi\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nfunction watchdog_handler\n{\n  while true; do\n    /usr/local/bin/wdtcli kick\n    sleep 5 # secs\n  done\n}\n\necho \"Watchdog pinging enabled\"\nwatchdog_handler\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# NC-SI version (0x15) field 52 contains the IANA of the vendor.\n# If this is 00000000, then we are running in QEMU and there is no point\n# to wait.\nif [[ \"$(ncsi-util 0x15 | grep 52:)\" == *\"0x00 0x00 0x00 0x00\"* ]]; then\n    exit 0\nfi\n\nlogger \"Update eth0 IPv6 link local address after NC-SI MAC address configured\"\n\n# shellcheck disable=SC2086\nmac_to_ll() {\n  IFS=':'; set $1; unset IFS\n  echo \"fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6\" | \\\n    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'\n}\n\nexp_ll=\nll=\n\nfor _ in {1..30}; do\n  # wait getting address from NC-SI\n  if [ \"$(cat /sys/class/net/eth0/addr_assign_type)\" = \"3\" ]; then\n    exp_ll=$(mac_to_ll \"$(cat /sys/class/net/eth0/address)\")\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break\n    fi\n    # re-generate link-local address\n    ip -6 addr flush dev eth0 scope link\n    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    break;\n  fi\n  sleep 1\ndone\n\nif [ \"$ll\" != \"$exp_ll\" ]; then\n  for _ in {1..100}; do\n    usleep 10000\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break;\n    fi\n  done\nfi\n\nlogger \"restart eth0 after MAC and Linklock addr update\"\nifdown eth0\nsleep 1\nifup eth0 &\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\necho \"Setup Caching for Bridge IC info..\"\n/usr/bin/bic-cached > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n. /usr/local/fbpackages/utils/ast-functions\n\nME_UTIL=\"/usr/bin/me-util\"\nFRUID_UTIL=\"/usr/local/bin/fruid-util\"\nFW_UTIL=\"/usr/bin/fw-util\"\nFRU_NAME=$1\nINTERFACE=\"PECI_INTERFACE\"\nPCIE_INTERFACE=\"PECI_INTERFACE\"\n\nfunction is_numeric {\n  if [ $(echo \"$1\" | grep -cE \"^\\-?([[:xdigit:]]+)(\\.[[:xdigit:]]+)?$\") -gt 0 ]; then\n    return 1\n  else\n    return 0\n  fi\n}\n\nif [ \"$FRU_NAME\" != \"server\" ]; then\n  echo \"FRU: $FRU_NAME is not supported\"\n  exit 1\nfi\n\n# File format autodump.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID=$$\nPID_FILE=\"/var/run/autodump.pid\"\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# kill previous autodump if exist\nif [ ! -z \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  # Check if 2nd dump is running\n  if [ ! -z \"$(ps | grep '{autodump.sh}' | grep \"server\" | grep \"second\\|dwr\")\" ]; then\n    echo $OLDPID > $PID_FILE\n    echo \"2nd DUMP or Demoted Warm Reset DUMP is running. exit.\"\n    exit 1\n  fi\n\n  LOG_FILE=\"/tmp/autodump.log\"\n  LOG_ARCHIVE=\"/mnt/data/autodump_uncompleted_server.tar.gz\"\n  echo -n \"(uncompleted) Auto Dump End at \" >> $LOG_FILE\n  date >> $LOG_FILE\n\n  tar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\n  rm -rf $LOG_FILE && \\\n\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  ps | grep '{dump.sh}' | grep \"server\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\n  ps | grep 'me-util' | grep \"server\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\n  ps | grep 'bic-util' | grep \"server\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\n  ps | grep 'fw-util' | grep \"server\" | grep \"version\" | awk '{print $1}'| xargs kill -s 9 &> /dev/null\nfi\nunset OLDPID\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\nkv set server_crashdump $((sys_runtime+1200))\n\nDUMP_SCRIPT=\"/usr/bin/crashdump/dump.sh\"\nCRASHDUMP_FILE=\"/mnt/data/crashdump_server\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_server.tar.gz\"\nLOG_MSG_PREFIX=\"\"\n\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\n\nwhile test $# -gt 1\ndo\n  case \"$2\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  *)\n    echo \"unknown argument $2\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  echo \"Auto Dump after System Reset or Demoted Warm Reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump for Server Started\"\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: server started\"\n\n#HEADER LINE for the dump\n$DUMP_SCRIPT \"time\" > $CRASHDUMP_FILE\n\n# Get BMC version & hostname\nstrings /dev/mtd0 | grep 2019.04 >> $CRASHDUMP_FILE\nuname -a >> $CRASHDUMP_FILE\ncat /etc/issue >> $CRASHDUMP_FILE\n\n# Get fw info\necho \"Get firmware version info: \" >> \"$CRASHDUMP_FILE\"\nRES=$(\"$FW_UTIL\" \"server\" \"--version\")\necho \"$RES\" >> \"$CRASHDUMP_FILE\"\n\n# Get FRUID info\necho \"Get FRUID Info:\" >> $CRASHDUMP_FILE\nRES=$($FRUID_UTIL server)\necho \"$RES\" >> $CRASHDUMP_FILE\n\n# Get Device ID\necho \"Get Device ID:\" >> $CRASHDUMP_FILE\nRES=$($ME_UTIL server 0x18 0x01)\necho \"$RES\" >> $CRASHDUMP_FILE\nRET=$?\n\n# if ME has response and in operational mode, PECI through ME\nif [ \"$RET\" -eq \"0\" ] && [ \"${RES:6:1}\" == \"0\" ]; then\n  RES=$($ME_UTIL server 0xb8 0x40 0x57 0x01 0x00 0x30 0x05 0x05 0xa1 0x00 0x00 0x00 0x00)\n  RET=$?\n  if [ \"$RET\" -eq \"0\" ] && [ \"${RES:0:11}\" == \"57 01 00 40\" ]; then\n    INTERFACE=\"ME_INTERFACE\"\n  else\n    INTERFACE=\"PECI_INTERFACE\"\n  fi\n  # else use wired PECI directly\nelse\n  # echo \"Use BIC wired PECI interface due to ME abnormal\"\n  INTERFACE=\"PECI_INTERFACE\"\nfi\nPCIE_INTERFACE=$INTERFACE\n\n# Major Firmware Revision\nREV=$(echo $RES| awk '{print $3;}')\n# Check whether the first parameter is numeric or not\n# If not, then it is an error message from me-util\nis_numeric $(echo $RES| awk '{print $1;}')\nif [ \"$?\" == 1 ] ;then\n  Mode=$(echo $(($REV & 0x80)))\n  if [ $Mode -ne 0 ] ;then\n    echo \"Device firmware update or Self-initialization in progress or Firmware in the recovery boot-loader mode\" >> $CRASHDUMP_FILE\n  fi\n  # Get Self-test result\n  echo \"Get Self-test result:\" >> $CRASHDUMP_FILE\n  RES=$($ME_UTIL server 0x18 0x04)\n  echo \"$RES\" >> $CRASHDUMP_FILE\n  CC=$(echo $RES| awk '{print $1;}')\n  # Check whether the first parameter is numeric or not\n  # If not, then it is an error message from me-util\n  is_numeric $CC\n  if [ \"$?\" == 1 ] ;then\n    if [ $CC -ne 55 ] ;then\n      if [ $CC -eq 56 ] ;then\n        echo \"Self Test function not implemented in this controller\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 57 ] ;then\n        echo \"Corrupted or inaccessible data or devices\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 58 ] ;then\n        echo \"Fatal hardware error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 80 ] ;then\n        echo \"PSU Monitoring service error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 81 ] ;then\n        echo \"Firmware entered Recovery boot-loader mode\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 82 ] ;then\n        echo \"HSC Monitoring service error\" >> $CRASHDUMP_FILE\n      elif [ $CC -eq 83 ] ;then\n        echo \"Firmware entered non-UMA restricted mode of operation\" >> $CRASHDUMP_FILE\n      else\n        echo \"Unknown error\" >> $CRASHDUMP_FILE\n      fi\n    fi\n  fi\n\n  # PCI config read is not support ME DMI interface\n  RES=$($ME_UTIL server 0xb8 0x40 0x57 0x01 0x00 0x30 0x06 0x05 0x61 0x00 0x00 0x81 0x0D 0x00)\n  RET=$?\n  if [ \"$RET\" -eq \"0\" ] && [ \"${RES:0:19}\" == \"Completion Code: AC\" ]; then\n    PCIE_INTERFACE=\"PECI_INTERFACE\"\n  fi\nfi\n\necho \"Set coreid msr interface = $INTERFACE\" >> $CRASHDUMP_FILE\necho \"Set pcie dwr interface = $PCIE_INTERFACE\" >> $CRASHDUMP_FILE\n\n# Sensors & sensor thresholds\necho \"Sensor history at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT server \"sensors\" >> $CRASHDUMP_FILE\necho \"Sensor threshold at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT server \"threshold\" >> $CRASHDUMP_FILE\n\n#COREID dump\n$DUMP_SCRIPT server \"coreid\" $INTERFACE >> $CRASHDUMP_FILE\n#MSR dump\n$DUMP_SCRIPT server \"msr\" $INTERFACE >> $CRASHDUMP_FILE\n#PCIe dump\n$DUMP_SCRIPT server \"pcie\" $PCIE_INTERFACE >> $CRASHDUMP_FILE\n\n# only second/dwr autodump need to rename accordingly\nif [ \"$DWR\" == \"1\" ] || [ \"$SECOND_DUMP\" == \"1\" ]; then\n  # dwr\n  $DUMP_SCRIPT server  \"dwr\" $PCIE_INTERFACE >> $CRASHDUMP_FILE\n\n  # rename the archieve file based on whether dump in DWR mode or not\n  if [ \"$?\" == \"2\" ]; then\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_dwr_server.tar.gz\"\n    LOG_MSG_PREFIX=\"DWR \"\n  else\n    CRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_second_server.tar.gz\"\n    LOG_MSG_PREFIX=\"SECOND_DUMP \"\n  fi\nfi\n\necho -n \"Auto Dump End at \" >> $CRASHDUMP_FILE\ndate >> $CRASHDUMP_FILE\n\ntar zcf $CRASHDUMP_LOG_ARCHIVE -C `dirname $CRASHDUMP_FILE` `basename $CRASHDUMP_FILE` && \\\nrm -rf $CRASHDUMP_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: server is generated at $CRASHDUMP_LOG_ARCHIVE\"\ncp -f \"$CRASHDUMP_LOG_ARCHIVE\" /tmp\necho \"Auto Dump for Server Completed\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $CRASHDUMP_LOG_ARCHIVE\"\nexit 0\n", "num_lines": 240}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nME_UTIL=\"/usr/bin/me-util\"\nPECI_UTIL=\"/usr/bin/bic-util\"\nCMD_DIR=\"/usr/bin/crashdump\"\nINTERFACE=$3\nSENSOR_HISTORY=180\n\n# read command from stdin\nfunction execute_via_me {\n  # if ME_UTIL cannot be executed, return\n  [ -x $ME_UTIL ] || \\\n    return\n\n  # Adapt command to ME-UTIL format\n  cat | \\\n    sed 's/^0x/0xb8 0x40 0x57 0x01 0x00 0x/g' $1 | \\\n      $ME_UTIL server --file /dev/stdin | \\\n        sed 's/^57 01 00 //g'\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    sed 's/^0x/0xe0 0x29 0x9c 0x9c 0x00 0x/g' $1 | \\\n      $PECI_UTIL server --file /dev/stdin | \\\n        sed 's/^9C 9C 00 //g'\n}\n\nfunction execute_cmd {\n  if [ \"$INTERFACE\" == \"ME_INTERFACE\" ]; then\n    cat | execute_via_me\n  else\n    cat | execute_via_peci\n  fi\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12] (unit: bits)\n# OUT: PCI config address\nfunction PCI_Config_Addr {\n  # BUS\n  RESULT=$((($1 & 0xFF) << 20))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15)))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12)))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0)))\n  printf \"0x%x 0x%x 0x%x 0x%x\" \\\n    $((RESULT & 0xFF)) \\\n    $(((RESULT >> 8) & 0xFF)) \\\n    $(((RESULT >> 16) & 0xFF)) \\\n    $(((RESULT >> 24) & 0xFF))\n  return 0\n}\n\nfunction print_bus_device {\n  MAX_FUN=0\n  MAX_DEV=4\n  BUS=$(printf \"0x%02x\" $1)\n  BUSM=$(($1 >> 4))\n  BUSL=$((($1 & 0xF) << 4))\n  for (( DEV=0; DEV<=$MAX_DEV; DEV++ )); do\n    DEVM=$((DEV >> 1))\n    DEVL=$(((DEV & 0x1) << 3))\n    for (( FUN=0; FUN<=$MAX_FUN; FUN++ )); do\n      printf \"echo \\\"BUS 0x%02x, Dev 0x%02x, Fun 0x%02x, Reg: 0x100 ~ 0x147\\\"\\n\" $1 $DEV $FUN\n      BYTE1=$(((DEVL | FUN) << 4 | 0x1))\n      BYTE2=$((BUSL | DEVM))\n      for REG in {0..68..4}; do\n        printf \"0x30 0x06 0x05 0x61 0x00 0x%02x 0x%02x 0x%02x 0x0%x\\n\" $REG $BYTE1 $BYTE2 $BUSM\n      done\n    done\n  done\n}\n\nfunction find_end_device {\n  echo \"Find Root Port Bus $1 Dev $2 Fun $3...\"\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr $1 $2 $3 0x18)\" | execute_cmd)\n  echo \"$RES\"\n  CC=$(echo $RES| awk '{print $1;}')\n  SECONDARY_BUS=0x$(echo $RES| awk '{print $3;}')\n  SUBORDINATE_BUS=0x$(echo $RES| awk '{print $4;}')\n  if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n    for (( BUS=$SECONDARY_BUS; BUS<=$SUBORDINATE_BUS; BUS++ )); do\n      printf \"End Device on Bus 0x%02x\\n\" $BUS\n      echo \"$(print_bus_device $BUS)\" | execute_cmd\n    done\n  fi\n}\n\nfunction pcie_dump {\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    # CPU root port - Bus 0x16/0x64, Dev 0~3, Fun:0\n    # Root port buses\n    ROOT_BUSES=$(echo $RES | awk '{printf \"0x%s 0x%s\", $3, $4;}')\n    ROOT_BUS=$(echo $RES | awk '{printf \"0x%s\", $2;}')\n    echo ROOT_BUSES=$ROOT_BUSES\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        find_end_device $ROOT $DEV 0\n      done\n    done\n\n    # CPU root port - Bus 0,Dev 0, Fun:0\n    echo ROOT_BUS=$ROOT_BUS\n    find_end_device $ROOT_BUS 0 0\n\n    # PCH root port - Bus 0,Dev 0x1B, Fun:0\n    find_end_device $ROOT_BUS 0x1B 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:0\n    find_end_device $ROOT_BUS 0x1D 0\n\n    # PCH root port - Bus 0,Dev 0x1D, Fun:4\n    find_end_device $ROOT_BUS 0x1D 4\n  fi\n\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    cat $CMD_DIR/crashdump_pcie | execute_cmd\n}\n\nfunction dwr_dump {\n\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo $RES| awk '{print $1;}')\n  DWR=0x$(echo $RES| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nfunction print_dump_help {\n  echo \"$0 server coreid <INTERFACE> ==> for CPU CoreID\"\n  echo \"$0 server msr    <INTERFACE> ==> for CPU MSR\"\n  echo \"$0 server sensors            ==> for sensor history\"\n  echo \"$0 server threshold          ==> for sensor threshold\"\n  echo \"$0 server pcie   <INTERFACE> ==> for PCIe\"\n  echo \"$0 server dwr    <INTERFACE> ==> for DWR check\"\n  exit 1\n}\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -eq 2 ]; then\n  if [ \"$2\" != \"sensors\" ] && [ \"$2\" != \"threshold\" ]; then\n    print_dump_help\n  fi\nelif [ \"$#\" -eq 3 ]; then\n  if [ \"$2\" != \"coreid\" ] && [ \"$2\" != \"msr\" ] && [ \"$2\" != \"pcie\" ] && [ \"$2\" != \"dwr\" ]; then\n    print_dump_help\n  fi\n  if [ \"$INTERFACE\" != \"ME_INTERFACE\" ] && [ \"$INTERFACE\" != \"PECI_INTERFACE\" ]; then\n    print_dump_help     \n  fi\nelse\n  print_dump_help\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r $CMD_DIR/crashdump_coreid ] && \\\n      cat $CMD_DIR/crashdump_coreid | execute_cmd\nelif [ \"$2\" = \"msr\" ]; then\n  [ -r $CMD_DIR/crashdump_msr ] && \\\n      cat $CMD_DIR/crashdump_msr | execute_cmd\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util all --threshold\nelif [ \"$2\" = \"pcie\" ]; then\n  pcie_dump\nelif [ \"$2\" = \"dwr\" ]; then\n  dwr_dump\n  exit $?\nfi\n\nexit 0\n", "num_lines": 221}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-exp-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for SCC expander info\n### END INIT INFO\n\necho \"Setup Caching for SCC Expander info..\"\n\n/usr/bin/exp-cached --booting > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho \"Setup fan speed... \"\n\nsh /usr/local/bin/setup-fsc-config.sh &\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\nFAN_SOURCE=\"DELTA\"\n\nwait_sensord_ready()\n{\n  RETRY=180   #timeout: 3 minutes\n  while [ $RETRY -gt 0 ]\n  do\n    ret=$($KV_CMD get flag_sensord_monitor)\n    if [ \"$ret\" = \"1\" ]; then\n      return 0\n    fi\n    RETRY=$((RETRY-1))\n    sleep 1\n  done\n\n  logger -s -p user.warn -t setup-fsc-config \"Waiting sensord ready timeout\"\n  return 1\n}\n\nwait_fan_fru_dumped()\n{\n  RETRY=180   #timeout: 3 minutes\n  i=0\n\n  #Check fan present\n  while [ $i -lt \"$FAN_FRU_CNT\" ]\n  do\n    if [ \"$(gpio_get FAN_${i}_INS_N)\" != \"$STR_VALUE_0\" ]; then\n      echo $i\n      return\n    fi\n    i=$((i+1))\n  done\n\n  #Check fan FRU dumped\n  i=0\n  for _ in $(seq $RETRY);  do\n    while [ $i -lt \"$FAN_FRU_CNT\" ]\n    do\n      ret=$($KV_CMD get fan${i}_dumped)\n      [ \"$ret\" != \"$STR_VALUE_1\" ] && break\n      i=$((i+1))\n    done\n    [ $i -eq \"$FAN_FRU_CNT\" ] && break\n    sleep 1\n  done\n\n  echo $i\n}\n\ncheck_fan_source()\n{\n  i=0\n  AVC_CNT=0\n\n  while [ $i -lt \"$FAN_FRU_CNT\" ]\n  do\n    fan_source=$($FRUIDUTIL_CMD fan${i} 2>/dev/null | grep 'Product Manufacturer')\n    ret=$?\n    # Get fan FRU failed\n    if [ \"$ret\" -ne \"0\" ]; then\n      logger -s -p user.warn -t setup-fsc-config \"Get fan${i} FRU failed, use DELTA fan table.\"\n      FAN_SOURCE=\"DELTA\"\n      return\n    fi\n\n    fan_source=${fan_source##*: }\n\n    if [ \"$fan_source\" = \"AVC\" ]; then\n      AVC_CNT=$((AVC_CNT+1))\n    fi\n    i=$((i+1))\n  done\n\n  if [ $AVC_CNT -eq \"$FAN_FRU_CNT\" ]; then\n    FAN_SOURCE=\"AVC\"\n  elif [ $AVC_CNT -gt 0 ]; then\n    logger -s -p user.warn -t setup-fsc-config \"Mix using fan source, use DELTA fan table.\"\n    FAN_SOURCE=\"DELTA\"\n  fi\n}\n\nset_default_fan_table=\"/usr/local/bin/set_default_fan_table.py\"\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\nfsc_type5_default_config_path=\"/etc/FSC_GC_PVT_default_config.json\"\nfsc_type5_avc_config_path=\"/etc/FSC_GC_Type5_PVT_AVC_v1_config.json\"\nfsc_type5_delta_config_path=\"/etc/FSC_GC_Type5_PVT_DELTA_v1_config.json\"\nfsc_type7_avc_config_path=\"/etc/FSC_GC_Type7_PVT_AVC_v1_config.json\"\nfsc_type7_delta_config_path=\"/etc/FSC_GC_Type7_PVT_DELTA_v1_config.json\"\n\nfsc_type5_zone_config_path=\"/etc/fsc/FSC_GC_Type5_PVT_v1_zone0.fsc\"\n\nget_uic_location\nuic_location=$?\n\nget_chassis_type\nchassis_type=$?\n\n# Check fan source to use different fan table\nfan_fru_dumped_cnt=$(wait_fan_fru_dumped)\nif [ \"$fan_fru_dumped_cnt\" -eq \"$FAN_FRU_CNT\" ]; then\n  check_fan_source\nelse\n  logger -s -p user.warn -t setup-fsc-config \"Waiting fan${fan_fru_dumped_cnt} dumped timeout or fan${fan_fru_dumped_cnt} not present, use DELTA fan table.\"\nfi\n\nif [ \"$chassis_type\" = \"$UIC_TYPE_7_HEADNODE\" ]; then\n  if [ \"$FAN_SOURCE\" = \"AVC\" ]; then\n    cp ${fsc_type7_avc_config_path} ${default_fsc_config_path}\n  else\n    cp ${fsc_type7_delta_config_path} ${default_fsc_config_path}\n  fi\n  echo \"Setup fscd: Use Type 7 ${FAN_SOURCE} fan table... \"\nelif [ \"$chassis_type\" = \"$UIC_TYPE_5\" ]; then\n  if [ \"$FAN_SOURCE\" = \"AVC\" ]; then\n    cp ${fsc_type5_avc_config_path} ${default_fsc_config_path}\n  else\n    cp ${fsc_type5_delta_config_path} ${default_fsc_config_path}\n  fi\n\n  if [ \"$uic_location\" = \"$UIC_LOCATION_A\" ]; then\n    sed -i \"s/_x/_a/g\" ${fsc_type5_zone_config_path}\n    echo \"Setup fscd: Use Type 5 side A ${FAN_SOURCE} fan table... \"\n  elif [ \"$uic_location\" = \"$UIC_LOCATION_B\" ]; then\n    sed -i \"s/_x/_b/g\" ${fsc_type5_zone_config_path}\n    echo \"Setup fscd: Use Type 5 side B ${FAN_SOURCE} fan table... \"\n  else\n    echo \"Setup fscd: UIC location is unknown. Please confirm the UIC location... \"\n  fi\nelse\n  python ${set_default_fan_table}\n  cp ${fsc_type5_default_config_path} ${default_fsc_config_path}\n  echo \"Setup fscd: Unknown chassis type. Use default fan table. Please confirm chassis type... \"\nfi\n\nwait_sensord_ready\n\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\n\necho \"Setup fan speed done... \"\n", "num_lines": 146}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/gpiod server\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start gpiod daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpiod for fbgc...\"\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start gpiointrd daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpiointrd for fbgc...\"\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/iocd 11\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/iocd 12\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-iocd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start IOC daemon\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup iocd for fbgc...\"\n\nget_chassis_type\nuic_type=$?\n\nrunsv /etc/sv/iocd_11 > /dev/null 2>&1 &\n\nif [ \"$uic_type\" = \"$UIC_TYPE_7_HEADNODE\" ]; then\n  runsv /etc/sv/iocd_12 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n\n", "num_lines": 29}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# for expander, payload id: FRU_SCC(5)\nexec /usr/local/bin/ipmbd 10 5\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# for BIC\nexec /usr/local/bin/ipmbd 2 1\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# for USB debug card\nexec /usr/local/bin/ipmbd 7 2\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-2/new_device\nrunsv /etc/sv/ipmbd_2 > /dev/null 2>&1 &\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-7/new_device\nrunsv /etc/sv/ipmbd_7 > /dev/null 2>&1 &\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-10/new_device\nrunsv /etc/sv/ipmbd_10 > /dev/null 2>&1 &\n\necho \"Done.\"\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm-scc_exp_smart > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm-scc_exp_sdb > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm-scc_ioc_smart > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm-server > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm-bic > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm-iocm_ioc_smart > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 13}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Address of SRAM that is used to store \"reboot by command\" flag. \nSRAM_BMC_REBOOT_BY_CMD=\"0x10015C04\"\n\n# Set 0x101 as flag for healthd logging reboot cause.\nval=$(devmem \"$SRAM_BMC_REBOOT_BY_CMD\" 32 2>/dev/null)\ndevmem \"$SRAM_BMC_REBOOT_BY_CMD\" 32 $((val | 0x101)) 2>/dev/null\n\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nI2CGET_CMD=/usr/sbin/i2cget\nI2C13_LTC2990_ADDR=0x4c\nI2C13_ADS1015_ADDR=0x49\nI2C9_LTC2991_ADDR=0x48\nI2C9_ADC128_ADDR=0x1d\nDPB_FRU_PATH=\"/tmp/fruid_dpb.bin\"\nIOCM_FRU_PATH=\"/tmp/fruid_iocm.bin\"\nDPB_KEY=\"dpb_source_info\"\nIOCM_KEY=\"iocm_source_info\"\n\nUNKNOWN_SRC=0\nMAIN_SRC=1\nSECOND_SRC=2\n\nFRU=$1\n\nif [ \"$FRU\" = \"dpb\" ]; then\n  I2C_BUS=9\n  I2C_ADDR_MAIN=$I2C9_ADC128_ADDR\n  I2C_ADDR_SECOND=$I2C9_LTC2991_ADDR\n  FRU_PATH=$DPB_FRU_PATH\n  KEY_SOURCE_INFO=$DPB_KEY\nelif [ \"$FRU\" = \"e1s_iocm\" ]; then\n  I2C_BUS=13\n  I2C_ADDR_MAIN=$I2C13_ADS1015_ADDR\n  I2C_ADDR_SECOND=$I2C13_LTC2990_ADDR\n  FRU_PATH=$IOCM_FRU_PATH\n  KEY_SOURCE_INFO=$IOCM_KEY\nelse\n  logger -s -p user.warn -t check_2nd_src \"Abort by invalid input\"\n  exit\nfi\n\ncheck_fru_content() {\n  RET=$UNKNOWN_SRC\n  RETRY=5\n  while [ $RETRY -gt 0 ]\n  do\n    if [ -f $FRU_PATH ]; then\n      PCD=$($FRUIDUTIL_CMD \"$FRU\" | grep \"Product Custom Data\")\n      if echo \"$PCD\" | grep -q \"Non-TI\"; then\n        echo $SECOND_SRC\n        return 0\n      else\n        echo $MAIN_SRC\n        return 0\n      fi\n    else\n      RETRY=$((RETRY-1))\n      sleep 1\n    fi\n  done\n  logger -s -p user.warn -t check_2nd_src \"Fail to read $FRU FRU: $FRU_PATH doesn't exist\"\n  echo $UNKNOWN_SRC\n}\n\ncheck_i2c_dev() {\n  RET_MAIN=$($I2CGET_CMD -y -f $I2C_BUS $I2C_ADDR_MAIN 0 2>&1 1>/dev/null)\n  RET_SECOND=$($I2CGET_CMD -y -f $I2C_BUS $I2C_ADDR_SECOND 0 2>&1 1>/dev/null)\n\n  if ! echo \"$RET_MAIN\" | grep -q \"Read failed\"; then\n    echo $MAIN_SRC\n  elif ! echo \"$RET_SECOND\" | grep -q \"Read failed\"; then\n     echo $SECOND_SRC\n  else\n    logger -s -p user.warn -t check_2nd_src \"i2c dev doesn't exist on $FRU\"\n    echo $UNKNOWN_SRC\n  fi\n}\n\nRET=$(check_fru_content)\nprintf \"Source checking by FRU: %s\\n\" \"$RET\"\n\nif [ \"$RET\" = \"$UNKNOWN_SRC\" ]; then\n  RET=$(check_i2c_dev)\n  printf \"Source checking by i2c dev: %s\\n\" \"$RET\"\nfi\n\nlogger -s -p user.warn -t check_2nd_src \"$FRU source: $RET\"\n\n$KV_CMD set $KEY_SOURCE_INFO \"$RET\"\n\nif [ -f /etc/modprobe.d/modprobe.conf ]; then\n  rm /etc/modprobe.d/modprobe.conf\nfi\n\nif [ \"$FRU\" = \"dpb\" ]; then\n  if [ ! -d /sys/bus/i2c/drivers/adc128d818 ] && [ \"$RET\" = \"$MAIN_SRC\" ]; then\n    modprobe adc128d818\n  fi\n  if [ ! -d /sys/bus/i2c/drivers/ltc2991 ] && [ \"$RET\" = \"$SECOND_SRC\" ]; then\n    modprobe ltc2991\n  fi\nfi\n\nif [ \"$FRU\" = \"e1s_iocm\" ]; then\n  if [ ! -d /sys/bus/i2c/drivers/ads1015 ] && [ \"$RET\" = \"$MAIN_SRC\" ]; then\n    modprobe ti_ads1015\n  fi\n  if [ ! -d /sys/bus/i2c/drivers/ltc2990 ] && [ \"$RET\" = \"$SECOND_SRC\" ]; then\n    modprobe ltc2990\n  fi\nfi\n", "num_lines": 126}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nMAX_RETRY=600         # wait 10 mins before give up\n\ntotal_daemon=\"sensord ipmid fscd front-paneld gpiod gpiointrd ncsid healthd ipmbd_2 ipmbd_7 ipmbd_10\"\n\nsensord_list=\"flag_sensord_monitor flag_sensord_health\"\nipmid_list=\"flag_ipmid\"\nfront_paneld_list=\"flag_front_led_sync flag_front_sys_status_led flag_front_health flag_front_err_code flag_front_hb\"\ngpiod_list=\"flag_gpiod_fru_miss flag_gpiod_server_pwr flag_gpiod_scc_pwr\"\ngpiointrd_list=\"flag_gpiointrd\"\nncsid_list=\"flag_ncsid\"\nhealthd_list=\"flag_healthd_wtd flag_healthd_hb_led flag_healthd_crit_proc flag_healthd_cpu flag_healthd_mem flag_healthd_ecc flag_healthd_bmc_timestamp flag_healthd_bic_health\"\nipmbd_2_list=\"flag_ipmbd_rx_2 flag_ipmbd_res_2 flag_ipmbd_req_2\"\nipmbd_7_list=\"flag_ipmbd_rx_7 flag_ipmbd_res_7 flag_ipmbd_req_7\"\nipmbd_10_list=\"flag_ipmbd_rx_10 flag_ipmbd_res_10 flag_ipmbd_req_10\"\n\ncheck_daemon_flag() {\n  flag_list=$1\n  \n  for flag_name in $flag_list\n  do\n    result=\"$($KV_CMD get \"$flag_name\")\"\n    if [ \"$result\" != \"1\" ] || [ \"$result\" = \"\" ]; then\n      echo \"$flag_name\"\n      break\n    fi\n  done\n}\n\ncheck_daemon_status() {\n  daemon_name=$1\n  \n  daemon_status=\"$(sv status \"$daemon_name\" | grep 'run')\"\n  if [ \"$daemon_status\" = \"\" ]; then\n    echo \"$daemon_name\"\n  else\n    # check ready flag of each thread\n    if [ \"$daemon_name\" = \"sensord\" ]; then\n      not_ready=\"$(check_daemon_flag \"$sensord_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"ipmid\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmid_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"front-paneld\" ]; then\n      not_ready=\"$(check_daemon_flag \"$front_paneld_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"gpiod\" ]; then\n      not_ready=\"$(check_daemon_flag \"$gpiod_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"gpiointrd\" ]; then\n      not_ready=\"$(check_daemon_flag \"$gpiointrd_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"ncsid\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ncsid_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"healthd\" ]; then\n      not_ready=\"$(check_daemon_flag \"$healthd_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"ipmbd_2\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmbd_2_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"ipmbd_7\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmbd_7_list\" \"$daemon_name\")\"\n    elif [ \"$daemon\" = \"ipmbd_10\" ]; then\n      not_ready=\"$(check_daemon_flag \"$ipmbd_10_list\" \"$daemon_name\")\"\n    fi\n    echo \"$not_ready\"\n  fi\n}\n\ncheck_bmc_ready() {\n  retry=0\n    \n  while [ \"$retry\" -lt \"$MAX_RETRY\" ]\n  do\n    NOT_READY_DAEMON=\"\"\n\n    for daemon in $total_daemon\n    do\n      result=\"$(check_daemon_status \"$daemon\")\"\n      \n      # daemon not ready\n      if [ \"$result\" = \"$daemon\" ]; then\n        NOT_READY_DAEMON=$daemon\n        break\n      elif [ \"$result\" != \"\" ]; then\n        NOT_READY_DAEMON=$daemon\n        NOT_READY_FLAG=$result\n        break\n      fi\n    done\n    \n    # all daemons are ready\n    if [ \"$NOT_READY_DAEMON\" = \"\" ]; then\n      break\n    else\n      sleep 1\n      retry=$((retry+1))\n    fi\n  done\n  \n  if [ \"$NOT_READY_DAEMON\" = \"\" ]; then\n    \"$KV_CMD\" set \"bmc_ready_flag\" \"$STR_VALUE_1\"\n    logger -s -p user.info -t ready-flag \"BMC is ready\"\n  else\n    logger -s -p user.info -t ready-flag \"daemon: $NOT_READY_DAEMON ($NOT_READY_FLAG) is not ready\"\n  fi\n}\n\necho \"check bmc ready...\"\ncheck_bmc_ready &\n", "num_lines": 109}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nget_sku()\n{\n  get_uic_location\n  uic_id=$?\n  get_chassis_type\n  uic_type=$?\n\n  if [ \"$uic_type\" = \"$UIC_TYPE_5\" ]; then\n    printf \"System: Type5\\n\"\n    if [ \"$uic_id\" = \"$UIC_LOCATION_A\" ]; then\n      printf \"UIC Location: Side A\\n\"\n    elif [ \"$uic_id\" = \"$UIC_LOCATION_B\" ]; then\n      printf \"UIC Location: Side B\\n\"\n    else\n      printf \"UIC Location: Unknown\\n\"\n    fi\n  elif [ \"$uic_type\" = \"$UIC_TYPE_7_HEADNODE\" ]; then\n    printf \"System: Type7 Headnode\\n\"\n  else\n    printf \"System: Unknown\\n\"\n  fi\n\n  pal_sku=$(((uic_id << UIC_TYPE_SIZE) | uic_type))\n\n  return $pal_sku\n}\n\n\nget_sku\npal_sku=$?\nprintf \"Platform SKU: %s (\" \"$pal_sku\"\n\ni=0\nwhile [ \"${i}\" -lt \"$PAL_SKU_SIZE\" ]\ndo\n  tmp_sku_bit=$(((pal_sku >> i) & 1))\n  sku_bit=$tmp_sku_bit$sku_bit\n  i=$((i+1))\ndone\n\nprintf \"%s\" \"$sku_bit\"\nprintf \")\\n\"\nprintf \"<SKU[5:0] = {UIC_ID0, UIC_ID1, UIC_TYPE0, UIC_TYPE1, UIC_TYPE2, UIC_TYPE3}>\\n\"\n\nexit $pal_sku\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nIS_NEEDED_SERVER_POWER_ON=true\nRETRY=0\nRETRY_TIME=30\nPOWER_12V_ON_TIMEOUT=0\nPOWER_12V_ON_COMPLETE=1\nSYNC_DATE=/usr/local/bin/sync_date.sh\n\n# Check power policy\ncheck_por_config()\n{\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/server_por_cfg\" ]; then\n    PWR_POLICY=\"on\"\n    IS_NEEDED_SERVER_POWER_ON=true\n  else\n    PWR_POLICY=$(cat ${KEYDIR}/server_por_cfg)\n\n    # Case ON\n    if [ \"$PWR_POLICY\" = \"on\" ]; then\n      IS_NEEDED_SERVER_POWER_ON=true\n\n    # Case OFF\n    elif [ \"$PWR_POLICY\" = \"off\" ]; then\n      IS_NEEDED_SERVER_POWER_ON=false\n\n    # Case LPS\n    elif [ \"$PWR_POLICY\" = \"lps\" ]; then\n      logger -s -p user.warn -t power-on \"LPS state is deprecated, set the power policy to be ON by default.\"\n      # LPS doesn't be supported, set power policy on\n      $KV_CMD set \"server_por_cfg\" \"on\" persistent\n\n      PWR_POLICY=\"on\"\n      IS_NEEDED_SERVER_POWER_ON=true\n      \n    fi\n  fi\n\n  logger -s -p user.info -t power-on \"Power Policy: $PWR_POLICY\"\n}\n\n# Check Server is present or not:\nif [ \"$(is_server_prsnt)\" = \"$SERVER_ABSENT\" ]; then\n  logger -s -p user.warn -t power-on \"The Server is absent, turn off Server HSC 12V.\"\n  $POWERUTIL_CMD server 12V-off\n  $SYNC_DATE\n  exit 1\nelif [ \"$(is_server_prsnt)\" = \"$SERVER_PRESENT\" ]; then\n  if [ \"$(is_bmc_por)\" = \"$STR_VALUE_0\" ]; then  # BMC is not Power-On-Reset (POR, AC-on)\n    logger -s -p user.info -t power-on \"BMC is not POR\"\n    $SYNC_DATE\n    exit 0\n  fi\n\n  logger -s -p user.info -t power-on \"Server 12V-On...\"\n  $POWERUTIL_CMD server 12V-on\n\n  RETRY=0\n  FINISH=\"$POWER_12V_ON_TIMEOUT\"\n  # Wait for server finish 12V-on\n  while [ $RETRY -lt $RETRY_TIME ]\n  do\n    if [ \"$(is_server_12v_on)\" = true ]; then\n      FINISH=\"$POWER_12V_ON_COMPLETE\"\n      logger -s -p user.info -t power-on \"Server 12V-On done\"\n      break\n    fi\n\n    RETRY=$((RETRY+1))\n    sleep 1\n  done\n\n  if [ \"$FINISH\" = \"$POWER_12V_ON_TIMEOUT\" ]; then\n    logger -s -p user.warn -t power-on \"Server 12V-On timeout\"\n    $SYNC_DATE\n    exit 1\n  fi\n\n  check_por_config\n  # Check server DC status according to power policy\n  if [ \"$IS_NEEDED_SERVER_POWER_ON\" = true ]; then\n    RETRY=0\n\n    while [ $RETRY -lt $RETRY_TIME ]\n    do\n      status=\"$(server_power_status)\"\n      if [ \"$status\" = \"$SERVER_STATUS_DC_ON\" ]; then\n        logger -s -p user.info -t power-on \"Server DC-On done\"\n        $SYNC_DATE\n        exit 0\n      fi\n\n      RETRY=$((RETRY+1))\n      sleep 1\n    done\n\n    logger -s -p user.warn -t power-on \"Server DC-On timeout\"\n    $SYNC_DATE\n    exit 1\n  fi\n  $SYNC_DATE\nfi\n\nexit 0\n", "num_lines": 111}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          run_power_on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\necho \"Run power-on.sh for FBGC...\"\n\nsh /usr/local/bin/power-on.sh &\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Get platform SKU\nsleep 1\nsh /usr/local/bin/check_pal_sku.sh > /dev/NULL\npal_sku=$?\n\n#Set pal_sku value to key value of system_info\n\"$CFGUTIL_CMD\" \"$KEY_SYSTEM_INFO\" \"$pal_sku\"\nret=$?\nif [ \"$ret\" != \"0\" ]; then\n  logger -s -p user.warn -t setup-platform \"Failed to set key value of $KEY_SYSTEM_INFO\"\n  exit 1\nfi\n\n# Record the platform SKU in syslog\nuic_type=$(($pal_sku & $UIC_TYPE_MASK))\nuic_id=$(($(($pal_sku >> $UIC_TYPE_SIZE)) & $UIC_LOCATION_MASK))\n\nif [ \"$uic_type\" = \"$UIC_TYPE_5\" ]; then\n  if [ \"$uic_id\" = \"$UIC_LOCATION_A\" ]; then\n    UIC_LOCAL=\"side A\"\n  elif [ \"$uic_id\" = \"$UIC_LOCATION_B\" ]; then\n    UIC_LOCAL=\"side B\"\n  else\n    UIC_LOCAL=\"unknown\"\n  fi\n  logger -s -p user.info -t setup-platform \"System: type 5, UIC location: $UIC_LOCAL\"\nelif [ \"$uic_type\" = \"$UIC_TYPE_7_HEADNODE\" ]; then\n  logger -s -p user.info -t setup-platform \"System: type 7\"\nelse\n  logger -s -p user.info -t setup-platform \"System: unknown\"\nfi\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nMAX_RETRY=15\n\n##### sync time from NTP server\nretry=0\nwhile [ $retry -lt \"$MAX_RETRY\" ]\ndo\n  if ! $NTP_CMD -p | grep '^\\*' > /dev/null ; then\n    retry=$((retry+1))\n    sleep 1\n  else\n    logger -s -p user.crit -t sync-date \"Syncing up BMC time from NTP\"\n    exit 0\n  fi\ndone\nlogger -s -p user.info -t sync-date \"Syncing up BMC time from NTP failed because NTP server not exist\"\n\n##### sync time from Host\nif [ \"$(is_server_prsnt)\" = \"$SERVER_PRESENT\" ] ; then\n  retry=0\n  while [ $retry -lt \"$MAX_RETRY\" ]\n  do\n    output=$(\"$ME_CMD\" server \"$NETFN_STORAGE_REQ\" \"$CMD_GET_SEL_TIME\")\n    \n    # sync BMC time only when ME returns correct response length\n    if [ \"$(echo $output | wc -c)\" = \"$SEL_TIME_RESPONSE_LEN\" ] ; then\n      time_hex0=$(echo \"$output\" | cut -d' ' -f1 | sed 's/^0*//') # get byte0\n      time_hex1=$(echo \"$output\" | cut -d' ' -f2 | sed 's/^0*//') # get byte1\n      time_hex2=$(echo \"$output\" | cut -d' ' -f3 | sed 's/^0*//') # get byte2\n      time_hex3=$(echo \"$output\" | cut -d' ' -f4 | sed 's/^0*//') # get byte3\n      \n      # change hexadecimal to decimal\n      time_dec=$((0x$time_hex3 << 24 | 0x$time_hex2 << 16 | 0x$time_hex1 << 8 | 0x$time_hex0))\n      \n      # change decimal number to date formate\n      sync_date=$(date -s @$time_dec +\"%Y.%m.%d-%H:%M:%S\")\n      ret=$?\n      if [ $ret = \"$SYNC_TIME_OK\" ]; then\n        logger -s -p user.crit -t sync-date \"Syncing up BMC time from Host(ME)\"\n        exit 0\n      else\n        # get invalid SEL time\n        logger -s -p user.info -t sync-date \"Syncing up BMC time from Host(ME) failed because get invalid SEL time: $output\"\n        retry=$((retry+1))\n      fi\n    else\n      retry=$((retry+1))\n    fi\n  done\n  logger -s -p user.info -t sync-date \"Syncing up BMC time from Host(ME) failed because get SEL time from ME failed\"\nfi\n\n##### sync time from default time\nlogger -s -p user.crit -t sync-date \"Syncing up BMC time from Default(OpenBMC build time)\"\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# shellcheck source=/usr/local/fbpackages/utils/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Setup sensor monitoring for FBGC... \"\n\nFRUS=\"dpb server uic scc nic e1s_iocm\"\n\nexec /usr/local/bin/sensord $FRUS\n", "num_lines": 11}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Setup sensor monitoring for FBGC... \"\n\n# Store vr information before sensor monitoring \nif [ \"$(is_sb_bic_ready 1)\" -eq \"1\" ]; then\n    /usr/bin/fw-util server --version vr > /dev/null\nfi\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/setup-gpio\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2023-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n/usr/local/bin/fan-util --set 100\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\ni2cset -y 9 0x71 0 0x05 # MUX to Channel 1 (MEB BIC)\nexec /usr/local/bin/mctpd smbus 9 0x10\n\n", "num_lines": 5}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2023-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Starting MCTPD Rx/Tx Daemon..\"\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-3/new_device  #BIC\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-4/new_device  #NIC\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device  #BIC\n\n#Set NIC1 EID to 0x22\n/usr/local/bin/mctp-util -d 0x4 0x64 0x00 0x00 0x80 0x01 0x00 0x22\n\nulimit -q 1024000\nrunsv /etc/sv/mctpd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/mctpd_4 > /dev/null 2>&1 &\nrunsv /etc/sv/mctpd_9 > /dev/null 2>&1 &\n\n\necho \"done.\"\n\n", "num_lines": 51}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2023-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nconnect_uart2_4() {\n  printf \"uart2\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart4\n  printf \"uart4\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart2\n}\n\nconnect_uart2_4\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n\nkv set mb_polling_status      1\nkv set nic0_polling_status    1\nkv set nic1_polling_status    1\nkv set scm_polling_status     1\nkv set vpdb_polling_status    1\nkv set hpdb_polling_status    1\nkv set fan_bp1_polling_status 1\nkv set fan_bp2_polling_status 1\n", "num_lines": 29}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 9\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2023-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\necho -n \"Starting PLDMD Rx/Tx Daemon..\"\n\nrunsv /etc/sv/pldmd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/pldmd_4 > /dev/null 2>&1 &\nrunsv /etc/sv/pldmd_9 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 29}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\nDUMP_DIR='/var/lib/amd-ras'\nCURRENT_INDEX_FILE=\"$DUMP_DIR/fru1_current_index\"\nINFODUMP_FILE=\"$DUMP_DIR/sensordump.log\"\nDUMP_UTIL='/usr/bin/amd-ras'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\n\nSENSOR_HISTORY=180\n\n# check crashdump binary file exists\nif [ ! -f $DUMP_UTIL ]; then\n  logger -t \"ipmid\" -p daemon.crit \"AMD ADDC crashdump not supported\"\n  exit 1\nfi\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  logger -t \"ipmid\" -p daemon.warning \"Another crashdump is runnung\"\n  exit 1\nelse\n  echo $PID > $PID_FILE\nfi\n\n# Set crashdump timestamp\n# this timestamp is used by pal_is_crashdump_ongoing() and it can\n# prevent the power control when crashdump is ongoing\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\nkv set fru1_crashdump $((sys_runtime+300))\n\n# check number of crashdump file exists\n[ -r $CURRENT_INDEX_FILE ] && PREVIOUS_INDEX=$(cat $CURRENT_INDEX_FILE) || PREVIOUS_INDEX=0\nDUMP_FILE=\"$DUMP_DIR/fru1_ras-error${PREVIOUS_INDEX}.cper\"\n\nfor i in {0..1}; do\n  if ! id[$i]=$(kv get cpu\"${i}\"_id persistent); then\n    id[$i]=\"0 0 0 0\"\n  fi\ndone\nIFS=\" \" read -r -a CPUID <<< \"${id[@]}\"\n\necho \"Auto Dump Started\"\n{ echo -n \"Sensor Dump Start at \"; date; } > $INFODUMP_FILE\n\n# Sensors\n{\n  echo \"\"\n  echo \"Sensor history of last ${SENSOR_HISTORY}s at dump:\"\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\n\n  echo \"Sensor threshold at dump:\"\n  /usr/local/bin/sensor-util all --threshold\n\n  echo -n \"Dump End at \"; date\n} >> $INFODUMP_FILE 2>&1\n\n$DUMP_UTIL --fru 1 --ncpu 2 --cid \"${CPUID[@]}\"\n\n[ -r $CURRENT_INDEX_FILE ] && CURRENT_INDEX=$(cat $CURRENT_INDEX_FILE) || CURRENT_INDEX=0\nif [ \"$PREVIOUS_INDEX\" == \"$CURRENT_INDEX\" ]; then\n  DUMP_FILE=\nfi\n\nIFS=\" \" read -r -a LOGS <<< \"$(basename \"$INFODUMP_FILE\") $(basename \"$DUMP_FILE\")\"\ntar zcf $LOG_ARCHIVE -C $DUMP_DIR \"${LOGS[@]}\"\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     5\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\n\ndefault_fsc_config=\"/etc/fsc-config.json\"\nif [[ -f ${default_fsc_config} ]]; then\n  rm ${default_fsc_config}\nfi\n\nrev_id=$(kv get mb_rev)\nif [[ \"$rev_id\" == \"2\" ]]; then\n  ln -s /etc/fsc-config-2-retimer.json ${default_fsc_config}\nelse\n  ln -s /etc/fsc-config-8-retimer.json ${default_fsc_config}\nfi\n\n/etc/init.d/check-fan-cache.sh &\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n. /usr/local/bin/openbmc-utils.sh\n\nRETRY=0\n\nrebind_i2c_dev() {\n  dev=\"$1-00$2\"\n  dri=$3\n\n  while [ ! -L \"${SYSFS_I2C_DEVICES}/$dev/driver\" ] && [ $RETRY -lt 10 ];\n  do\n    sleep 1\n    i2c_bind_driver \"$dri\" \"$dev\"\n    ((RETRY++))\n  done\n}\n\nrebind_i2c_dev 6 70 pca954x\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nfor retry in {1..20};\ndo\n    bp2_sensor238=$(kv get fan_bp2_sensor238)\n    if [ $? -ne 0 ]; then\n        sleep 3\n    else\n        break\n    fi\ndone\n\ni2cget -f -y 8 0x48 0x01\nrev=$?\nif [ \"$rev\" -ne 0 ]; then\n    val=$(i2cget -f -y 40 0x21 0x00)\n    fan_present1=$((\"$val\"))\n\n    val=$(i2cget -f -y 41 0x21 0x00)\n    fan_present2=$((\"$val\"))\n\n    if [ \"$fan_present1\" -eq 255 ] && [ \"$fan_present2\" -eq 255 ]; then\n      echo \"Don't enable fscd due to fan not present\"\n    else\n      echo \"Start fscd\"\n      runsv /etc/sv/fscd > /dev/null 2>&1 &\n    fi\nfi\necho \"done.\"\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nmb_sku=$(($(/usr/bin/kv get mb_sku) & 0x0F))\n# sku_id[3:0] | HSC     | ADC        | VR             | RT VR        |config\n# 0000        | MPS5990 | ADC128D818 | RAA229620      | ISL69260IRAZ |  0\n# 0100        | LTC4282 | MAXIM11617 | XDPE192C3B     | XDPE15284D   |  1\n# 0010        | TBD     | ADC128D818 | RAA229620      | TBD          |  2\n# 0110        | LTC4286 | MAXIM11617 | MP2857GQKT-001 | TBD          |  3\n# 0001        | MPS5990 | ADC128D818 | MP2857GQKT-001 | ISL69260IRAZ |  4\n\n# Artemis\n# 1001        | LTC4282 | ADC128D818 | XDPE192C3B     |   9\n\nconfig0=\"0\"\nconfig1=\"4\"\nconfig4=\"1\"\n\n# Artemis\nconfig9=\"9\"\n\n#TBD\n#config2=\"2\"\n#config3=\"6\"\n\n\nMB_1ST_SOURCE=\"0\"\nMB_2ND_SOURCE=\"1\"\nMB_3RD_SOURCE=\"2\"\n\nmbrev=$(kv get mb_rev)\nMB_DVT_BORAD_ID=\"2\"\n\n#HSC\nprobe_hsc_mp5990() {\n  i2c_device_add 6 0x20 mp5990\n  kv set mb_hsc_source \"$MB_1ST_SOURCE\"\n}\n\nprobe_hsc_ltc() {\n  val=$(i2cget -f -y 21 0x42 0x02)\n  data=$((\"$val\"))\n\n  #Read ADC 1.5v:LTC4286 1v:LTC4282\n  if [ \"$mbrev\" -ge \"$MB_DVT_BORAD_ID\" ]\n  then\n    if [ \"$data\" -ge 4 ]\n    then\n      i2c_device_add 6 0x41 ltc4286\n      kv set mb_hsc_source \"$MB_3RD_SOURCE\"\n    else\n      i2c_device_add 6 0x41 ltc4282\n      kv set mb_hsc_source \"$MB_2ND_SOURCE\"\n    fi\n  else\n    if [ \"$data\" -gt 4 ]\n    then\n      i2c_device_add 6 0x41 ltc4286\n      kv set mb_hsc_source \"$MB_3RD_SOURCE\"\n    else\n      i2c_device_add 6 0x41 ltc4282\n      kv set mb_hsc_source \"$MB_2ND_SOURCE\"\n    fi\n  fi\n\n  #HSC Temp\n  i2c_device_add 25 0x4C lm75\n  #HSC module's eeprom\n  i2c_device_add 6 0x51 24c64\n  kv set mb_hsc_module \"1\"\n}\n\n#ADC\nprobe_adc_ti() {\n  i2cset -f -y 20 0x1d 0x0b 0x02\n  i2c_device_add 20 0x1d adc128d818\n  i2cset -f -y 26 0x1d 0x0b 0x02\n  i2c_device_add 26 0x1d adc128d818\n  kv set mb_adc_source \"$MB_1ST_SOURCE\"\n\n}\n\nprobe_adc_maxim() {\n  i2c_device_add 20 0x35 max11617\n  i2c_device_add 26 0x35 max11617\n  kv set mb_adc_source \"$MB_2ND_SOURCE\"\n}\n\n#VR\nprobe_vr_raa() {\n  i2c_device_add 20 0x61 isl69260\n  i2c_device_add 20 0x62 isl69260\n  i2c_device_add 20 0x63 isl69260\n  i2c_device_add 20 0x72 isl69260\n  i2c_device_add 20 0x74 isl69260\n  i2c_device_add 20 0x75 isl69260\n  kv set mb_vr_source \"$MB_1ST_SOURCE\"\n}\n\nprobe_vr_xdpe() {\n  i2c_device_add 20 0x4a xdpe152c4\n  i2c_device_add 20 0x49 xdpe152c4\n  i2c_device_add 20 0x4c xdpe152c4\n  i2c_device_add 20 0x4d xdpe152c4\n  i2c_device_add 20 0x4e xdpe152c4\n  i2c_device_add 20 0x4f xdpe152c4\n  kv set mb_vr_source \"$MB_2ND_SOURCE\"\n}\n\nprobe_vr_mp2856() {\n  #To do - Probe mp2856 driver\n  i2c_device_add 20 0x49 mp2856\n  i2c_device_add 20 0x4a mp2856\n  i2c_device_add 20 0x4c mp2856\n  i2c_device_add 20 0x4d mp2856\n  i2c_device_add 20 0x4e mp2856\n  i2c_device_add 20 0x4f mp2856\n  kv set mb_vr_source \"$MB_3RD_SOURCE\"\n}\n\n#MB retimer VR\nprobe_mb_retimer_vr_isl() {\n  i2c_device_add 20 0x60 isl69260\n  i2c_device_add 20 0x76 isl69260\n}\n\nprobe_mb_retimer_vr_xdpe() {\n  i2c_device_add 20 0x60 xdpe152c4\n  i2c_device_add 20 0x76 xdpe152c4\n}\n\n#MB DPM\n# rev_id[2:0] | ID2 | ID1 | ID0 |\n# 000         |  0  |  0  |  0  | EVT  (no retimer)\n# 001         |  0  |  0  |  1  | DVT1 (8 retimer)\n# 010         |  0  |  1  |  0  | DVT2 (2 retimer)\n# 011         |  0  |  1  |  1  | PVT  (TBD)\n\nmbrev=$(kv get mb_rev)\nMB_DVT_BOARD_ID=\"1\"\nMB_PVT_BOARD_ID=\"3\"\n\nif [ \"$mbrev\" -ge \"$MB_DVT_BOARD_ID\" ]; then\n  if [ \"$mb_sku\" -ne \"$config9\" ]; then\n    i2c_device_add 34 0x41 ina230\n    i2c_device_add 34 0x42 ina230\n    i2c_device_add 34 0x43 ina230\n    i2c_device_add 34 0x44 ina230\n    i2c_device_add 34 0x45 ina230\n  fi\n  kv set mb_dpm_source \"$MB_1ST_SOURCE\"\nfi\n\nif [ \"$mbrev\" -eq \"$MB_DVT_BOARD_ID\" ] &&\n   [ \"$mbrev\" -ge \"$MB_PVT_BOARD_ID\" ]; then\n  probe_mb_retimer_vr\nfi\n\nif [ \"$mb_sku\" -eq \"$config0\" ]; then\n  probe_hsc_mp5990\n  probe_adc_ti\n  probe_vr_raa\n  probe_mb_retimer_vr_isl\nelif [ \"$mb_sku\" -eq \"$config1\" ]; then\n  probe_hsc_ltc\n  probe_adc_maxim\n  probe_vr_xdpe\n  probe_mb_retimer_vr_xdpe\nelif [ \"$mb_sku\" -eq \"$config4\" ]; then\n  probe_hsc_mp5990\n  probe_adc_ti\n  probe_vr_mp2856\n  probe_mb_retimer_vr_isl\n# Artemis config\nelif [ \"$mb_sku\" -eq \"$config9\" ]; then\n  probe_hsc_ltc\n  probe_adc_ti\n  probe_vr_xdpe\n  probe_mb_retimer_vr_xdpe\nfi\n\nif ! i2cget -f -y 0 0x70 0 >/dev/null 2>&1; then\n  kv set apml_mux 0\nelse\n  i2cset -f -y 0 0x70 0x46 0x01\n  i2cset -f -y 0 0x70 0x40 0xc0\n  i2cset -f -y 0 0x70 0x41 0xc0\n  kv set apml_mux 1\nfi\n", "num_lines": 211}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-cover\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set up GPIO pins as appropriate can be cover\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n\n\n# ==SGPIO Input Cover==\nsgpio_export PWRGD_OCP_SFF_PWR_GOOD 0\nsgpio_export IRQ_SML1_PMBUS_ALERT_N 2\nsgpio_export FM_PWRGD_PVDD18_S5_P0 4\n\nsgpio_export APML_CPU0_ALERT_R_N 10\nsgpio_export APML_CPU1_ALERT_R_N 12\nsgpio_export FM_PVDD11_S3_P0_OCP_N 14\nsgpio_export FM_PVDD11_S3_P1_OCP_N 16\n\nsgpio_export PRSNT_OCP_SFF_N 28\nsgpio_export PRSNT_OCP_V3_2_N 30\n\nsgpio_export GPU_FPGA_EROT_FATALERR_ISO_R_N 34\nsgpio_export IRQ_HSC_FAULT_R1_N 36\nsgpio_export FM_OCP_V3_2_PWR_GOOD 38\n\nsgpio_export FM_PWRGD_PVDD33_S5 44\n\nsgpio_export PWRGD_PVDD18_S5_R_P1 48\nsgpio_export OCP_V3_2_P3V3_PWRGD 50\n\nsgpio_export PWRGD_P3V3_R2 56\nsgpio_export PWRGD_PVDDCR_SOC_P0 58\n\nsgpio_export PWRGD_PVDDCR_CPU0_P0 66\nsgpio_export FM_PWRGD_PVDDIO_P0 68\nsgpio_export PWRGD_P3V3_AUX_R 70\nsgpio_export FM_PWRGD_PVDD11_S3_P0 72\nsgpio_export FM_PWRGD_PVDDIO_P1 74\nsgpio_export PWRGD_PS_PWROK_PLD_ISO_R 76\nsgpio_export FM_PWRGD_PVDDCR_CPU0_P1 78\nsgpio_export PWRGD_PVDDCR_SOC_P1 80\nsgpio_export FM_PWRGD_PVDD11_S3_P1 82\nsgpio_export FM_PWRGD_PVDDCR_CPU1_P1 84\nsgpio_export FM_PWRGD_PVDDCR_CPU1_P0 86\nsgpio_export PWRGD_P1V2_AUX_R 88\nsgpio_export PWRGD_P1V8_AUX_R 90\nsgpio_export SCM_SYS_PWROK 92\nsgpio_export PWRGD_P5V_AUX_R3 94\n\nsgpio_export FM_PRSNT_CPU0_R_N 112\nsgpio_export FM_PRSNT_CPU1_R_N 114\nsgpio_export CPU1_THERMTRIP_R_N 118\nsgpio_export FM_PVDDCR_CPU0_P0_OCP_N 122\nsgpio_export FM_PVDDCR_CPU0_P1_OCP_N 124\nsgpio_export FM_PVDDCR_CPU1_P0_OCP_N 126\nsgpio_export FM_PVDDCR_CPU1_P1_OCP_N 128\nsgpio_export PWRGD_CHGL_CPU0 130\nsgpio_export PWRGD_CHAF_CPU0 132\nsgpio_export PWRGD_CHAF_CPU1 134\nsgpio_export CPU0_THERMTRIP_R_N 136\nsgpio_export FM_CPU0_RSMRST_N 138\nsgpio_export FM_SCM_PRSNT1_N 140\nsgpio_export FM_CPU0_SMERR_N 142\nsgpio_export FM_CPU1_SMERR_N 144\nsgpio_export FM_BIOS_POST_CMPLT_BUF_R_N 146\nsgpio_export SWB_HSC_PWRGD_ISO_R 148\nsgpio_export FM_SMB_1_ALERT_GPU_ISO_R_N 150\nsgpio_export FM_SMB_2_ALERT_GPU_ISO_R_N 152\nsgpio_export PVDDCR_CPU0_P0_PMALERT 154\nsgpio_export PVDDCR_CPU0_P1_PMALERT 156\nsgpio_export PVDDCR_CPU1_P0_SMB_ALERT 158\nsgpio_export PVDDCR_CPU1_P1_SMB_ALERT 160\nsgpio_export PRSNT_HDT_N 162\nsgpio_export FM_CPU0_SLP_S3_N 164\nsgpio_export FM_CPU0_SLP_S5_N 166\nsgpio_export E1S_0_PRSNT_R_N 172\nsgpio_export P0_PWR_ERR 174\nsgpio_export P1_PWR_ERR 176\nsgpio_export OC_ALERT_N 178\nsgpio_export PWRGD_CHGL_CPU1 180\nsgpio_export PVDD11_S3_P0_PMALERT 182\nsgpio_export PVDD11_S3_P1_PMALERT 184\nsgpio_export FM_CPU1_PROCHOT_R_N 186\nsgpio_export UV_ALERT_N 188\n\nsgpio_export FM_SWB_PWRGD_ISO_R 192\nsgpio_export CPU0_PCC_N 194\nsgpio_export CPU1_PCC_N 196\nsgpio_export FM_RST_CPU0_RESETL_N 198\nsgpio_export FM_RST_CPU1_RESETL_N 200\nsgpio_export FM_CPU0_PROCHOT_R_N 202\n\nsgpio_export BMC_JTAG_SEL_R 228\nsgpio_export RST_PERST_CPUx_SWB_N 230\nsgpio_export P12V_HSC_TEMP_ALERT_R_N 232\nsgpio_export P12V_HSC_T_CRIT_R_N 234\nsgpio_export FM_CPU1_PWRGD_OUT 236\nsgpio_export FM_PWRGD_CPU0_PWROK 238\nsgpio_export FM_PWRGD_CPU1_PWROK 240\nsgpio_export PWRGD_P12V_MEM_R 242\nsgpio_export P12V_SCM_PWRGD_R 244\nsgpio_export P12V_E1S_0_PWRGD 246\nsgpio_export P3V3_E1S_PWRGD_0_R 248\nsgpio_export P12V_OCP_V3_1_PWRGD 250\nsgpio_export OCP_V3_1_P3V3_PWRGD 252\nsgpio_export HP_LVC3_OCP_V3_2_P12V_PWRGD_R 254\n\nsgpio_export CPLD_SGPIO_READY_ID0 18\nsgpio_export CPLD_SGPIO_READY_ID1 22\nsgpio_export CPLD_SGPIO_READY_ID2 116\nsgpio_export CPLD_SGPIO_READY_ID3 120\n\n\n\n\n# == SGPIO OUT Cover==\nsgpio_export RST_SMB_SWITCH_N 5\ngpio_set RST_SMB_SWITCH_N 1\n\nsgpio_export FM_SMM_CRASHDUMP_R 7\ngpio_set FM_SMM_CRASHDUMP_R 1\n\nsgpio_export FM_DEBUG_PORT_PRSNT_R1_N 9\ngpio_set FM_DEBUG_PORT_PRSNT_R1_N 1\n\nsgpio_export FM_JTAG_BMC_MUX_SEL_R1 15\ngpio_set FM_JTAG_BMC_MUX_SEL_R1 0\n\nsgpio_export FM_SMB_RT_ROM_SEL 29\ngpio_set FM_SMB_RT_ROM_SEL 0\n\nsgpio_export NV_DUMP_END 33\ngpio_set NV_DUMP_END 0\n\nsgpio_export FM_BIOS_DEBUG_EN_N 41\ngpio_set FM_BIOS_DEBUG_EN_N 1\n\nsgpio_export CLK_GEN2_BMC_RC_OE_R_N 47\ngpio_set CLK_GEN2_BMC_RC_OE_R_N 0\n\nsgpio_export USB_OC0_REAR_R_N 63\ngpio_set USB_OC0_REAR_R_N 1\n\nsgpio_export GPU_FPGA_RST_N 65\ngpio_set GPU_FPGA_RST_N 1\n\nsgpio_export CLK_GEN2_GPU_FPGA_OE_R_N 69\ngpio_set CLK_GEN2_GPU_FPGA_OE_R_N 0\n\nsgpio_export JTAG_SCM_TRST_R_N 91\ngpio_set JTAG_SCM_TRST_R_N 1\n\nsgpio_export FM_BMC_PWRBRK_N 95\ngpio_set FM_BMC_PWRBRK_N 1\n\nsgpio_export BMC_FORCE_NM_THROTTLE_N 99\ngpio_set BMC_FORCE_NM_THROTTLE_N 1\n\nsgpio_export FM_APML_MUX2_SEL_R 103\ngpio_set FM_APML_MUX2_SEL_R 1\n\nsgpio_export FM_SEC_MUX_R_SEL 107\ngpio_set FM_SEC_MUX_R_SEL 1\n\nsgpio_export IRQ_BMC_SMI_R_N 109\ngpio_set IRQ_BMC_SMI_R_N 1\n\nsgpio_export IRQ_CPU_BMC_NMI_R_N 111\ngpio_set IRQ_CPU_BMC_NMI_R_N 1\n\nsgpio_export IRQ_SMI_ACTIVE_N_R 113\ngpio_set IRQ_SMI_ACTIVE_N_R 1\n\nsgpio_export IRQ_TPM_SPI_R1_N 115\ngpio_set IRQ_TPM_SPI_R1_N 1\n\n", "num_lines": 202}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nconnect_uart2_4() {\n  echo -ne \"uart1\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart4\n  echo -ne \"uart4\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart1\n  echo -ne \"io1\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart2\n  echo -ne \"uart2\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/io1\n}\n\nconnect_uart2_4\n", "num_lines": 11}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nDEBUG_ENABLE=false\n\nupdate_ntp_config_from_kv() {\n  local ntp_server\n  ntp_server=$(/usr/bin/kv get ntp_server persistent)\n  if [ -z \"$ntp_server\" ]; then\n    return\n  fi\n\n  sed -i \"s/.*# REPLACE WITH KV.*/server $ntp_server iburst # REPLACE WITH KV/\" /etc/ntp.conf\n  /etc/init.d/ntpd restart\n}\n\nis_ntp_time_synced() {\n  local str\n  local ret\n\n  str=$(/usr/sbin/ntpq -np | grep '^\\*')\n  ret=$?\n  # logger -t \"ipmid\" -p daemon.crit \"ret: $ret\"\n  if [ \"$DEBUG_ENABLE\" = true ] ; then\n    echo \"==================================\"\n    echo \"ret: $ret\"\n    echo \"----------------------------------\"\n    echo \"$str\"\n    echo \"==================================\"\n  fi\n\n  # ret == 0, synced\n  # ret == 1, not synced\n  return $ret\n}\n\nntp_sync_delay() {\n    local NTP_DELAY_COUNT\n\n    NTP_DELAY_COUNT=0\n    echo \"[$(/bin/date)] ntp is enabled, ntp_server: $(/usr/bin/kv get ntp_server persistent)\"\n\n    while [ $NTP_DELAY_COUNT -lt 30 ];\n    do\n      if is_ntp_time_synced ; then\n        break\n      fi\n      ((NTP_DELAY_COUNT++))\n      [ \"$DEBUG_ENABLE\" = true ] && echo \"[$(/bin/date)] system time not synced, count: ${NTP_DELAY_COUNT}\"\n      sleep 1\n    done\n    if is_ntp_time_synced ; then\n      echo \"[$(/bin/date)] system time synced after $NTP_DELAY_COUNT sec\"\n    else\n      echo \"[$(/bin/date)] system time not synced after $NTP_DELAY_COUNT sec\"\n    fi\n}\n\nsync_date()\n{\n  if [ \"$(is_bmc_por)\" -eq 1 ]; then\n\n    sleep 5\n    update_ntp_config_from_kv\n    ntp_sync_delay\n    echo Syncing up BMC time with server...\n  fi\n}\n\nsync_date\n", "num_lines": 93}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\nDUMP_DIR='/tmp/crashdump/output'\nMAP_DIR='/var/bafi'\nPARSE_FILE=\"$DUMP_DIR/bafi.log\"\nDUMP_FILE=\"$DUMP_DIR/sensordump.log\"\nDUMP_UTIL='/usr/bin/crashdump'\nPARSE_UTIL='/usr/bin/bafi'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\nACD=true\n\nif [ ! -f $DUMP_UTIL ] ; then\n  # shellcheck disable=SC1091\n  . /usr/local/bin/gpio-utils.sh\n\n  ACD=false\n  DUMP_FILE=\"$DUMP_DIR/autodump.log\"\n  DUMP_UTIL='/usr/local/bin/dump.sh'\n  mkdir -p $DUMP_DIR\nfi\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=$(cat $PID_FILE) || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" \"$sys_runtime\")\nkv set fru1_crashdump $((sys_runtime+630))\n\n# kill previous autodump if exist\nif [ -n \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  killall -s 9 dump.sh >/dev/null 2>&1\n  killall -s 9 peci-util >/dev/null 2>&1\n  killall -s 9 crashdump >/dev/null 2>&1\n  killall -s 9 bafi >/dev/null 2>&1\n\n  if [ \"$ACD\" != true ] ; then\n    { echo -n \"(uncompleted) Auto Dump End at \"; date; } >> $DUMP_FILE\n    tar zcf '/mnt/data/autodump_uncompleted.tar.gz' -C $DUMP_DIR \"$(basename $DUMP_FILE)\"\n  fi\nfi\nunset OLDPID\n\nDELAY_SEC=30\nSENSOR_HISTORY=180\n\nwhile test $# -gt 0\ndo\n  case \"$1\" in\n  --now)\n    DELAY_SEC=0\n    ;;\n  *)\n    echo \"unknown argument $1\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump Started\"\nLOGS=$(basename $DUMP_FILE)\nif [ \"$ACD\" == true ] ; then\n  $DUMP_UTIL\n\n  # shellcheck disable=SC2012\n  LOG_FILE=$(ls $DUMP_DIR/crashdump_* -t1 |head -n 1)\n  ${PARSE_UTIL} \"$LOG_FILE\" > $PARSE_FILE 2>&1\n\n  LOGS=\"$LOGS $(basename \"$LOG_FILE\") $(basename $PARSE_FILE)\"\n  { echo -n \"Sensor Dump Start at \"; date; } > $DUMP_FILE\n\nelse\n\n  { echo -n \"Auto Dump Start at \"; date; } > $DUMP_FILE\n\n  # CPU0\n  { $DUMP_UTIL 48 coreid; $DUMP_UTIL 48 msr; } >> $DUMP_FILE 2>&1\n\n  # CPU1\n  if [ \"$(gpio_get_value FM_CPU1_SKTOCC_LVT3_PLD_N)\" -eq \"0\" ]; then\n    { $DUMP_UTIL 49 coreid; $DUMP_UTIL 49 msr; } >> $DUMP_FILE 2>&1\n  else\n    echo \"<<---------- CPU1 is not present, skip it. ---------->>\" >> $DUMP_FILE\n  fi\n\n  # PCIe\n  #$DUMP_UTIL pcie >> $DUMP_FILE 2>&1\nfi\n\n# Sensors\n{\n  echo \"\"\n  echo \"Sensor history of last ${SENSOR_HISTORY}s at dump:\"\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\n\n  echo \"Sensor threshold at dump:\"\n  /usr/local/bin/sensor-util all --threshold\n\n  echo -n \"Dump End at \"; date\n} >> $DUMP_FILE 2>&1\n\n# shellcheck disable=SC2086\ntar zcf $LOG_ARCHIVE -C $DUMP_DIR $LOGS\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 125}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROGRAM=$0\nPECI_UTIL=\"/usr/local/bin/peci-util\"\nCMD_DIR=\"/etc/peci\"\n\nCPU_ID=$(($1 - 48))\nDUMP_FILE=crashdump_p\"$CPU_ID\"_\n\n#2S:MODE=2, 4S_EX:MODE=1, 4S_EP:MODE=0\nMODE=$(($(/usr/bin/kv get mb_skt) >> 1))\nif [ \"$MODE\" -eq 2 ]; then\n  MAX_CPU=2;\nelse\n  MAX_CPU=4;\nfi\n\nfunction print_help_msg {\n  for ((i=0; i<MAX_CPU; i++))\n  do\n    addr=$((i+48))\n    echo \"$PROGRAM $addr coreid  ==> for CPU $i CoreID\"\n    echo \"$PROGRAM $addr msr     ==> for CPU $i MSR\"\n  done\n  echo \"$PROGRAM pcie       ==> for PCIe\"\n  echo \"$PROGRAM dwr        ==> for DWR check\"\n}\n\n# read command from stdin\nfunction execute_via_peci {\n  # if PECI_UTIL cannot be executed, return\n  [ -x $PECI_UTIL ] || \\\n    return\n\n  cat | \\\n    $PECI_UTIL -i 10 -r 5 --file /dev/stdin\n}\n\n# read command from stdin\nfunction execute_cmd {\n  # echo \"Use BMC wired PECI interface\"\n  cat | execute_via_peci\n}\n\n# ARG: Bus[8], Device[5], Function[3], Register[12]\nfunction PCI_Config_Addr {\n  RESULT=0\n  # BUS\n  RESULT=$((RESULT | (($1 & 0xFF) << 20) ))\n  # DEV\n  RESULT=$((RESULT | (($2 & 0x1F) << 15) ))\n  # FUN\n  RESULT=$((RESULT | (($3 & 0x7) << 12) ))\n  # REG\n  RESULT=$((RESULT | (($4 & 0xFFF) << 0) ))\n  printf \"0x%x 0x%x 0x%x 0x%x\"\\\n    $(( RESULT & 0xFF )) \\\n    $(( (RESULT >> 8) & 0xFF )) \\\n    $(( (RESULT >> 16) & 0xFF )) \\\n    $(( (RESULT >> 24) & 0xFF ))\n  return 0\n}\n\nfunction pcie_dump {\n  # CPU and PCH\n  [ -r $CMD_DIR/crashdump_pcie ] && \\\n    execute_cmd < $CMD_DIR/crashdump_pcie\n\n  # Buses\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xcc 0x20 0x04 0x00\" | execute_cmd)\n  echo \"Get CPUBUSNO: $RES\"\n  # Completion Code\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n  # Root port buses\n  ROOT_BUSES=$(echo \"$RES\" | awk '{printf \"0x%s 0x%s 0x%s\", $3, $4, $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    for ROOT in $ROOT_BUSES; do\n      for DEV in {0..3}; do\n        echo \"Find Root Port Bus $ROOT Dev $DEV...\"\n        RES=$(echo \"0x30 0x06 0x05 0x61 0x00 $(PCI_Config_Addr \"$ROOT\" $DEV 0x00 0x18)\" | execute_cmd)\n        echo \"$RES\"\n        CC=$(echo \"$RES\"| awk '{print $1;}')\n        SECONDARY_BUS=0x$(echo \"$RES\"| awk '{print $3;}')\n        SUBORDINATE_BUS=0x$(echo \"$RES\"| awk '{print $4;}')\n        if [ \"$CC\" == \"40\" ] && [ \"$SECONDARY_BUS\" != \"0x00\" ] && [ \"$SUBORDINATE_BUS\" != \"0x00\" ]; then\n          for (( BUS=SECONDARY_BUS; BUS<=SUBORDINATE_BUS; BUS++ )); do\n            BUS_MS_NIBBLE=$(printf \"%x\" $((BUS >> 4)) )\n            BUS_LS_NIBBLE=$(printf \"%x\" $((BUS & 0xF)) )\n            [ -r $CMD_DIR/crashdump_pcie_bus ] && \\\n              sed \"s/<BUSM>/$BUS_MS_NIBBLE/g; s/<BUSL>/$BUS_LS_NIBBLE/g\" $CMD_DIR/crashdump_pcie_bus | execute_cmd\n          done\n        fi\n      done\n    done\n  fi\n}\n\nfunction dwr_dump {\n  echo\n  echo DWR assert check:\n  echo =================\n  echo\n\n  # Get biosscratchpad7[26]: DWR assert check\n  RES=$(echo \"0x30 0x06 0x05 0x61 0x00 0xbc 0x20 0x04 0x00\" | execute_cmd)\n\n  echo \"< Get biosscratchpad7[26]: DWR assert check >\"\n  echo \"$RES\"\n  echo\n\n  # Completion Code\n  CC=$(echo \"$RES\"| awk '{print $1;}')\n  DWR=0x$(echo \"$RES\"| awk '{print $5;}')\n\n  # Success\n  if [ \"$CC\" == \"40\" ]; then\n    if [ $((DWR & 0x04)) == 4 ]; then\n      echo \"Auto Dump in DWR mode\"\n      return 2\n    else\n      echo \"Auto Dump in non-DWR mode\"\n      return 1\n    fi\n  else\n    echo \"get DWR mode fail\"\n    return 0\n  fi\n}\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\necho \"\"\n\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"pcie\" ]; then\n  pcie_dump\n  exit 0\nfi\n\nif [ \"$#\" -eq 1 ] && [ \"$1\" = \"dwr\" ]; then\n  dwr_dump\n  exit $?\nfi\n\nif [ \"$#\" -ne 2 ]; then\n\n  print_help_msg\n  exit 1\n\nelif [ \"$CPU_ID\" -ge \"$MAX_CPU\" ] || [ \"$CPU_ID\" -lt 0 ]; then\n\n  print_help_msg\n  exit 1\n\nelif [ \"$2\" = \"coreid\" ] || [ \"$2\" = \"msr\" ]; then\n\n  DUMP_FILE=\"$CMD_DIR/${DUMP_FILE}$2\"\n  if [ -r \"$DUMP_FILE\" ]; then\n    execute_cmd < \"$DUMP_FILE\"\n  else\n    echo \"$DUMP_FILE\" not exist\n  fi\n  exit 0\n\nfi\n\nexit 0\n", "num_lines": 174}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\n# shellcheck disable=SC2039\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 18}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n/etc/init.d/check-fan-cache.sh &\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n\ndump_nv_log() {\n  echo \"Start to dump NVDIA FPGA Register\"\n\n  TIME=$(date +\"%Y%m%d-%S\")\n  echo $TIME\n\n  DUMP_DIR='/tmp/nv_reg/output'\n  DUMP_REG0B=\"$DUMP_DIR/reg_0x0b.log\"\n  DUMP_REG13=\"$DUMP_DIR/reg_0x13.log\"\n  DUMP_REG14=\"$DUMP_DIR/reg_0x14.log\"\n  LOG_ARCHIVE=\"/mnt/data/nvlog/${TIME}_nvlog.tar.gz\"\n\n  mkdir -p \"/mnt/data/nvlog\"\n  mkdir -p $DUMP_DIR\n\n  /usr/sbin/i2cdump -y 11 0x0b > $DUMP_REG0B 2>&1\n  /usr/sbin/i2cdump -y 7  0x13 > $DUMP_REG13 2>&1\n  /usr/sbin/i2cdump -y 7  0x14 > $DUMP_REG14 2>&1\n\n\n  tar -zcvf $LOG_ARCHIVE -C $DUMP_DIR reg_0x0b.log reg_0x13.log reg_0x14.log\n\n  echo high > /tmp/gpionames/NV_DUMP_END/direction\n  sleep 1\n  echo low > /tmp/gpionames/NV_DUMP_END/direction\n\n  echo \"End of to dump NVDIA FPGA Register\"\n}\n\ndump_nv_log &\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiod\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# shellcheck disable=SC2039\necho \"Setup gpio monitoring for Grandteton \"\n\nsleep 1\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 14 5\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 6 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-14/new_device  #USB DBG\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_14 > /dev/null 2>&1 &\n\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-6/new_device   #ME\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_6 > /dev/null 2>&1 &\n\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd smbus 3 0x10\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/mctpd smbus 4 0x10\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n# shellcheck disable=SC1091,SC2039\n. /usr/local/fbpackages/utils/ast-functions\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-3/new_device  #BIC\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-4/new_device  #NIC\n\n#Set NIC1 EID to 0x22\nif ! /usr/local/bin/mctp-util -d 0x4 0x64 0x0 0x00 0x80 0x01 0x00 0x22 >/dev/null; then\n  echo \"Failed to set nic1 EID\"\nfi\n\n\necho -n \"Starting MCTPD Rx/Tx Daemon..\"\nulimit -q 1024000\nrunsv /etc/sv/mctpd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/mctpd_4 > /dev/null 2>&1 &\n\n\necho \"done.\"\n\n", "num_lines": 51}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\necho \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm2 > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\ndo_fscd_configure () {\n  default_fsc_config=\"/etc/fsc-config.json\"\n  hgx_ppn=$(/usr/local/bin/fruid-util hgx | grep 'Product Part Number' | grep -o '[0-9A-Za-z-]*$')\n\n  rm ${default_fsc_config}\n  if [[ $hgx_ppn == \"\" ]]; then\n    # If hgx not ready\n    echo probe 700w config\n    ln -s /etc/fsc-config-700w.json ${default_fsc_config}\n    return 1\n  elif [[ $hgx_ppn == \"935-24287-A510-300\" ]]; then\n    # If hgx is 500w\n    echo probe 500w config\n    ln -s /etc/fsc-config-500w.json ${default_fsc_config}\n    return 0\n  else\n    # If hgx is 700w\n    echo probe 700w config\n    ln -s /etc/fsc-config-700w.json ${default_fsc_config}\n    return 0\n  fi\n}\n\nfor retry in {1..20};\ndo\n    bp2_sensor238=$(kv get fan_bp2_sensor238)\n    if [ $? -ne 0 ]; then\n        sleep 3\n    else\n        break\n    fi\ndone\n\ni2cget -f -y 8 0x48 0x01\nrev=$?\nif [ \"$rev\" -ne 0 ]; then\n  val=$(i2cget -f -y 40 0x21 0x00)\n  fan_present1=$((\"$val\"))\n\n  val=$(i2cget -f -y 41 0x21 0x00)\n  fan_present2=$((\"$val\"))\n\n  if [ \"$fan_present1\" -eq 255 ] && [ \"$fan_present2\" -eq 255 ]; then\n    echo \"Don't enable fscd due to fan not present\"\n  else\n    echo \"Start fscd\"\n    do_fscd_configure\n    result=$?\n    runsv /etc/sv/fscd > /dev/null 2>&1 &\n\n    if [[ $result == 1 ]]; then\n      while true; do\n        if [[ $result == 0 ]]; then\n          sv restart fscd\n          break\n        else\n          sleep 5\n          do_fscd_configure\n          result=$?\n        fi\n      done\n    fi\n  fi\nfi\necho \"done.\"\n", "num_lines": 88}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck source=common/recipes-utils/openbmc-utils/files/openbmc-utils.sh\n. /usr/local/bin/openbmc-utils.sh\n# shellcheck source=meta-facebook/meta-grandteton/recipes-grandteton/plat-utils/files/ast-functions\n. /usr/local/fbpackages/utils/ast-functions\n\nread_dev() {\n  for _ in {1..3}; do\n    if /usr/sbin/i2cget -f -y \"$1\" \"$2\" \"$3\" 2>/dev/null; then\n      return 0\n    fi\n  done\n  return 1\n}\n\nrebind_i2c_dev() {\n  dev=\"$1-00$2\"\n  dri=$3\n\n  if [ ! -L \"${SYSFS_I2C_DEVICES}/$dev/driver\" ]; then\n    if i2c_bind_driver \"$dri\" \"$dev\" >/dev/null; then\n      echo \"rebind $dev to driver $dri successfully\"\n    fi\n  fi\n}\n#echo set SGPIO ready\ngpio_set FM_BMC_SGPIO_READY_N 1\n\necho \"Probe MB MUX\"\nrebind_i2c_dev 1 70 pca954x\nrebind_i2c_dev 5 70 pca954x\nrebind_i2c_dev 8 72 pca954x\n\necho \"Probe PDBH MUX\"\nrebind_i2c_dev 37 71 pca954x\n\n#MB TEMP Device\"\ni2c_device_add 21 0x48 stlm75\ni2c_device_add 22 0x48 stlm75\ni2c_device_add 23 0x48 stlm75\ni2c_device_add 24 0x48 stlm75\n\n\n#MB Expender\ni2c_device_add 29 0x74 pca9539\n# I/O Expander PCA9539 0xE8 BIC and GPU\ngpio_export_ioexp 29-0074 RST_USB_HUB             0\ngpio_export_ioexp 29-0074 RST_SWB_BIC_N           1\ngpio_export_ioexp 29-0074 SWB_CABLE_PRSNT_G_N     4\ngpio_export_ioexp 29-0074 GPU_CABLE_PRSNT_H_N     5\ngpio_export_ioexp 29-0074 SWB_CABLE_PRSNT_F_N     6\ngpio_export_ioexp 29-0074 SWB_CABLE_PRSNT_C_N     7\n\ngpio_export_ioexp 29-0074 GPU_CABLE_PRSNT_D_N     8\ngpio_export_ioexp 29-0074 SWB_CABLE_PRSNT_B_N     9\ngpio_export_ioexp 29-0074 GPU_BASE_ID0            10\ngpio_export_ioexp 29-0074 GPU_BASE_ID1            11\ngpio_export_ioexp 29-0074 GPU_PEX_STRAP0          12\ngpio_export_ioexp 29-0074 GPU_PEX_STRAP1          13\ngpio_export_ioexp 29-0074 GPU_CABLE_PRSNT_A_N     14\ngpio_export_ioexp 29-0074 GPU_CABLE_PRSNT_E_N     15\n\n#MB FRU\ni2c_device_add 33 0x51 24c64\n\n# Swith Board\necho \"Probe SWB Device\"\nSWB_1ST_SOURCE=\"0\"\nSWB_2ND_SOURCE=\"1\"\nSWB_3RD_SOURCE=\"2\"\nSWB_4TH_SOURCE=\"3\"\n\n# BIC I/O Expander PCA9539 0xEC BIC\ni2c_device_add 32 0x76 pca9539\n\ngpio_export_ioexp 32-0076 BIC_FWSPICK        0\ngpio_export_ioexp 32-0076 BIC_UART_BMC_SEL   1\n\n#Set IO Expender\ngpio_set BIC_FWSPICK 0\ngpio_set RST_SWB_BIC_N 1\ngpio_set BIC_UART_BMC_SEL 0\n\n\nbic_ready=$(gpio_get FM_SWB_BIC_READY_ISO_R_N)\n#SWB HSC\nif [ \"$bic_ready\" -eq 0 ]; then\n  cnt=3\n  while [ $cnt -ne 0 ]\n  do\n    sleep 1\n    str=$(pldmd-util --bus 3 -e 0x0a raw 0x02 0x11 0xf0 0x00 0x01 |grep \"PLDM Data\")\n    rev=$?\n    if [ \"$rev\" -eq 1 ]; then\n      cnt=$((\"$cnt\"-1))\n      val=0\n    else\n      IFS=' ' read -ra  array <<< \"$str\"\n      cnt=0\n      for i in \"${array[@]}\"\n      do\n        array[\"$cnt\"]=${i:2}\n        cnt=$((\"$cnt\"+1))\n      done\n\n      int=$(((16#${array[9]}|16#${array[10]} << 8)*1000))\n      dec=$((16#${array[11]}|16#${array[12]} << 8))\n      val=$((\"$int\"+\"$dec\"))\n      break;\n    fi\n  done\n\n#kv set swb_hsc_module \"0\"\n  if [ \"$val\" -gt 750 ] && [ \"$val\" -lt 1250 ]\n  then\n    kv set swb_hsc_source \"$SWB_2ND_SOURCE\" #ltc4282\n    kv set swb_hsc_module \"1\"\n  elif [ \"$val\" -gt 1250 ]\n  then\n    kv set swb_hsc_source \"$SWB_3RD_SOURCE\" #ltc4287\n    kv set swb_hsc_module \"1\"\n  else\n    kv set swb_hsc_source \"$SWB_1ST_SOURCE\" #mp5990\n  fi\n\n#SWB VR\n  cnt=3\n  while [ \"$cnt\" -ne 0 ]\n  do\n    sleep 1\n    str=$(pldmd-util --bus 3 -e 0x0a raw 0x02 0x11 0xf1 0x00 0x01 |grep \"PLDM Data\")\n    rev=$?\n    if [ \"$rev\" -eq 1 ]; then\n      cnt=$((\"$cnt\"-1))\n    else\n      IFS=' ' read -ra  array <<< \"$str\"\n      cnt=0\n      for i in \"${array[@]}\"\n      do\n        array[\"$cnt\"]=${i:2}\n        cnt=$((\"$cnt\"+1))\n      done\n\n      int=$(((16#${array[9]}|16#${array[10]} << 8)*1000))\n      dec=$((16#${array[11]}|16#${array[12]} << 8))\n      val=$((\"$int\"+\"$dec\"))\n      break;\n    fi\n  done\n\n  if [ \"$val\" -gt 250 ] && [ \"$val\" -lt 750 ]\n  then\n    kv set swb_vr_source \"$SWB_2ND_SOURCE\" #INF\n  elif [ \"$val\" -gt 750 ] && [ \"$val\" -lt 1250 ]\n  then\n    kv set swb_vr_source \"$SWB_3RD_SOURCE\" #MPS\n  elif [ \"$val\" -gt 1250 ] && [ \"$val\" -lt 1750 ]\n  then\n    kv set swb_vr_source \"$SWB_4TH_SOURCE\" #TI\n  else\n    kv set swb_vr_source \"$SWB_1ST_SOURCE\" #RAA\n  fi\nfi\n\nVPDB_EVT2=\"2\"\nVPDB_PVT=\"5\"\nVPDB_DISCRETE_PVT=\"3\"\nVPDB_1ST_SOURCE=\"0\"\nVPDB_2ND_SOURCE=\"1\"\nVPDB_3RD_SOURCE=\"2\"\nVPDB_HSC_MAIN=\"0\"\n#VPDB_HSC_SECOND=\"1\"\n\n# VPDB\necho \"Probe VPDB Device\"\n#VPDB Expender\ni2c_device_add 36 0x22 pca9555\ngpio_export_ioexp 36-0022  HPDB_PRESENT     9\ngpio_export_ioexp 36-0022  VPDB_BOARD_ID_0  10\ngpio_export_ioexp 36-0022  VPDB_BOARD_ID_1  11\ngpio_export_ioexp 36-0022  VPDB_BOARD_ID_2  12\ngpio_export_ioexp 36-0022  VPDB_SKU_ID_0    13\ngpio_export_ioexp 36-0022  VPDB_SKU_ID_1    14\ngpio_export_ioexp 36-0022  VPDB_SKU_ID_2    15\n\nif read_dev 36 0x25 0 >/dev/null; then\n  gpio_export_ioexp 36-0025  VPDB_BOARD_ID_3_IO   0\n  gpio_export_ioexp 36-0025  VPDB_SKU_ID_3_IO     15\n  VPDB_BOARD_ID_3=$VPDB_BOARD_ID_3_IO\n  VPDB_SKU_ID_3=$VPDB_SKU_ID_3_IO\nelse\n  VPDB_BOARD_ID_3=0\n  VPDB_SKU_ID_3=0\nfi\n\nkv set vpdb_rev \"$((VPDB_BOARD_ID_3 << 3 |\n                    $(gpio_get VPDB_BOARD_ID_2) << 2 |\n                    $(gpio_get VPDB_BOARD_ID_1) << 1 |\n                    $(gpio_get VPDB_BOARD_ID_0)))\"\n\nkv set vpdb_sku \"$((VPDB_SKU_ID_3 << 3 |\n                    $(gpio_get VPDB_SKU_ID_2) << 2 |\n                    $(gpio_get VPDB_SKU_ID_1) << 1 |\n                    $(gpio_get VPDB_SKU_ID_0)))\"\n\n#VPDB ADM1272/LTC4286 CONFIG\nvpdb_hsc=$(gpio_get VPDB_SKU_ID_2)\nvrev=$(kv get vpdb_rev)\n\n\nif [ \"$vpdb_hsc\" -eq \"$VPDB_HSC_MAIN\" ] && [ \"$vrev\" -gt 1 ]; then\n  i2c_device_add 38 0x44 ltc4286\n  kv set vpdb_hsc_source \"$VPDB_1ST_SOURCE\"\nelse\n  i2cset -y -f 38 0x10 0xd4 0x3F1F w\n  i2c_device_add 38 0x10 adm1272\n  kv set vpdb_hsc_source \"$VPDB_2ND_SOURCE\"\nfi\n\nvsku=$(kv get vpdb_sku)\n\nif [ \"$vsku\" -eq \"2\" ] || [ \"$vsku\" -eq \"5\" ]; then\n  brick_driver=\"raa228006\"\n  i2c_device_add 38 0x54 $brick_driver\n  kv set vpdb_brick_source \"$VPDB_3RD_SOURCE\"\n\n  if [ \"$vrev\" -gt \"$VPDB_DISCRETE_PVT\" ]; then\n    if [ \"$(gpio_get VPDB_SKU_ID_0)\" -eq $VPDB_1ST_SOURCE ]; then\n      i2c_device_add 36 0x67 ltc2945\n      i2c_device_add 36 0x68 ltc2945\n      kv set vpdb_adc_source \"$VPDB_1ST_SOURCE\"\n    else\n      i2c_device_add 36 0x40 ina238\n      i2c_device_add 36 0x41 ina238\n      kv set vpdb_adc_source \"$VPDB_2ND_SOURCE\"\n    fi\n  fi\nelse\n  brick_driver=\"bmr491\"\n  vpdb_brick=$(gpio_get VPDB_SKU_ID_1)\n\n  if [ \"$vpdb_brick\" -eq \"$VPDB_1ST_SOURCE\" ]; then\n    brick_driver=\"pmbus\"\n    kv set vpdb_brick_source \"$VPDB_1ST_SOURCE\"\n  else\n    kv set vpdb_brick_source \"$VPDB_2ND_SOURCE\"\n  fi\n\n  vpdb_rev=$(kv get vpdb_rev)\n  if [ \"$vpdb_rev\" -ge $VPDB_EVT2 ]; then\n    i2c_device_add 38 0x67 $brick_driver\n    i2c_device_add 38 0x68 $brick_driver\n    i2c_device_add 38 0x69 $brick_driver\n  else\n    i2c_device_add 38 0x69 $brick_driver\n    i2c_device_add 38 0x6a $brick_driver\n    i2c_device_add 38 0x6b $brick_driver\n  fi\n\n  #vpdb ADC sensors\n  if [ \"$vrev\" -gt \"$VPDB_PVT\" ]; then\n    if [ \"$(gpio_get VPDB_SKU_ID_0)\" -eq $VPDB_1ST_SOURCE ]; then\n      i2c_device_add 36 0x67 ltc2945\n      i2c_device_add 36 0x68 ltc2945\n      kv set vpdb_adc_source \"$VPDB_1ST_SOURCE\"\n    else\n      i2c_device_add 36 0x40 ina238\n      i2c_device_add 36 0x41 ina238\n      kv set vpdb_adc_source \"$VPDB_2ND_SOURCE\"\n    fi\n  fi\nfi\n# VPDB FRU\ni2c_device_add 36 0x52 24c64 #VPDB FRU\n\n\n\n#***HPDB Board Device Probe***\nHPDB_PVT=5\nHPDB_1ST_SOURCE=\"0\"\nHPDB_2ND_SOURCE=\"1\"\n#HPDB_3RD_SOURCE=\"2\"\nHPDB_HSC_MAIN=\"0\"\n#HPDB_HSC_SECOND=\"1\"\n\necho \"Probe HPDB Device\"\n#HPDB ID Expender\ni2c_device_add 37 0x23 pca9555\ngpio_export_ioexp 37-0023  FAN_BP1_PRSNT_N  2\ngpio_export_ioexp 37-0023  FAN_BP2_PRSNT_N  3\ngpio_export_ioexp 37-0023  HPDB_BOARD_ID_0  10\ngpio_export_ioexp 37-0023  HPDB_BOARD_ID_1  11\ngpio_export_ioexp 37-0023  HPDB_BOARD_ID_2  12\ngpio_export_ioexp 37-0023  HPDB_SKU_ID_0    13\ngpio_export_ioexp 37-0023  HPDB_SKU_ID_1    14\ngpio_export_ioexp 37-0023  HPDB_SKU_ID_2    15\n\ni2c_device_add 37 0x25 pca9555\ngpio_export_ioexp 37-0025  FM_HS1_EN_BUSBAR_BUF  1\ngpio_export_ioexp 37-0025  FM_HS2_EN_BUSBAR_BUF  3\n\nif read_dev 37 0x25 0 >/dev/null; then\n  gpio_export_ioexp 37-0025  HPDB_BOARD_ID_3_IO    15\n  HPDB_BOARD_ID_3=$HPDB_BOARD_ID_3_IO\nelse\n  HPDB_BOARD_ID_3=0\nfi\n\n\nhpdb_rc=\"$(($(gpio_get HPDB_BOARD_ID_2) << 2 |\n      $(gpio_get HPDB_BOARD_ID_1) << 1 |\n      $(gpio_get HPDB_BOARD_ID_0)))\"\n\n\nif [ $hpdb_rc -ge 11 ] && [ $hpdb_rc -le 15 ]; then\n   HPDB_BOARD_ID_3=0\nfi\n\nkv set hpdb_rev \"$((HPDB_BOARD_ID_3 << 3 | hpdb_rc))\"\n\n\n\nkv set hpdb_sku \"$(($(gpio_get HPDB_SKU_ID_2) << 2 |\n                    $(gpio_get HPDB_SKU_ID_1) << 1 |\n                    $(gpio_get HPDB_SKU_ID_0)))\"\n\n# HPDB ADM1272/LTC4286 CONFIG\nhpdb_hsc=$(gpio_get HPDB_SKU_ID_2)\nhrev=$(kv get hpdb_rev)\n\nif [ \"$hpdb_hsc\" -eq \"$HPDB_HSC_MAIN\" ] && [ \"$hrev\" -gt 1 ]; then\n  i2c_device_add 39 0x40 ltc4286\n  i2c_device_add 39 0x41 ltc4286\n  kv set hpdb_hsc_source \"$HPDB_1ST_SOURCE\"\nelse\n  i2cset -y -f 39 0x13 0xd4 0x3F1F w\n  i2cset -y -f 39 0x1c 0xd4 0x3F1F w\n  i2c_device_add 39 0x13 adm1272\n  i2c_device_add 39 0x1c adm1272\n  kv set hpdb_hsc_source \"$HPDB_2ND_SOURCE\"\nfi\n\nif [ \"$hrev\" -gt \"$HPDB_PVT\" ]; then\n  if [ \"$(gpio_get HPDB_SKU_ID_1)\" -eq \"$HPDB_1ST_SOURCE\" ]; then\n    i2c_device_add 37 0x69 ltc2945\n    i2c_device_add 37 0x6a ltc2945\n    i2c_device_add 37 0x6b ltc2945\n    i2c_device_add 37 0x6c ltc2945\n    kv set hpdb_adc_source \"$HPDB_1ST_SOURCE\"\n  else\n    i2c_device_add 37 0x42 ina238\n    i2c_device_add 37 0x43 ina238\n    i2c_device_add 37 0x44 ina238\n    i2c_device_add 37 0x45 ina238\n    kv set hpdb_adc_source \"$HPDB_2ND_SOURCE\"\n  fi\nfi\n\n# HPDB FRU\ni2c_device_add 37 0x51 24c64\n\n\n\n#***FAN Board Device Probe***\nBP_1ST_SOURCE=\"0\"\nBP_2ND_SOURCE=\"1\"\nBP_FAN_MAIN=\"0\"\necho \"Probe FAN Board Device\"\n# FAN_BP1 I/O Expander PCA9555\ni2c_device_add 40 0x21 pca9555\ngpio_export_ioexp 40-0021 FAN_BP1_SKU_ID_0    8\ngpio_export_ioexp 40-0021 FAN_BP1_SKU_ID_1    9\ngpio_export_ioexp 40-0021 FAN_BP1_SKU_ID_2    10\n\nkv set fan_bp1_fan_sku \"$(($(gpio_get FAN_BP1_SKU_ID_2) << 2 |\n                           $(gpio_get FAN_BP1_SKU_ID_1) << 1 |\n                           $(gpio_get FAN_BP1_SKU_ID_0)))\"\n\n\n\n# FAN_BP2 I/O Expander PCA9555\ni2c_device_add 41 0x21 pca9555\ngpio_export_ioexp 41-0021 FAN_BP2_SKU_ID_0    8\ngpio_export_ioexp 41-0021 FAN_BP2_SKU_ID_1    9\ngpio_export_ioexp 41-0021 FAN_BP2_SKU_ID_2    10\n\nkv set fan_bp2_fan_sku \"$(($(gpio_get FAN_BP2_SKU_ID_2) << 2 |\n                           $(gpio_get FAN_BP2_SKU_ID_1) << 1 |\n                           $(gpio_get FAN_BP2_SKU_ID_0)))\"\n\n\n\nfan_bp1_fan=$(gpio_get FAN_BP1_SKU_ID_0)\nif [ \"$fan_bp1_fan\" -eq \"$BP_FAN_MAIN\" ]; then\n# Max31790\n  # FAN_BP1 Max31790 FAN CHIP\n  i2cset -f -y 40 0x20 0x01 0xbb\n  i2cset -f -y 40 0x20 0x02 0x08\n  i2cset -f -y 40 0x20 0x03 0x19\n  i2cset -f -y 40 0x20 0x04 0x08\n  i2cset -f -y 40 0x20 0x05 0x08\n  i2cset -f -y 40 0x20 0x06 0x19\n  i2cset -f -y 40 0x20 0x07 0x08\n  i2cset -f -y 40 0x20 0x08 0x6C\n  i2cset -f -y 40 0x20 0x09 0x6C\n  i2cset -f -y 40 0x20 0x0A 0x6C\n  i2cset -f -y 40 0x20 0x0B 0x6C\n  i2cset -f -y 40 0x20 0x0C 0x6C\n  i2cset -f -y 40 0x20 0x0D 0x6C\n\n  i2cset -f -y 40 0x2f 0x01 0xbb\n  i2cset -f -y 40 0x2f 0x02 0x08\n  i2cset -f -y 40 0x2f 0x03 0x19\n  i2cset -f -y 40 0x2f 0x04 0x08\n  i2cset -f -y 40 0x2f 0x05 0x08\n  i2cset -f -y 40 0x2f 0x06 0x19\n  i2cset -f -y 40 0x2f 0x07 0x08\n  i2cset -f -y 40 0x2f 0x08 0x6C\n  i2cset -f -y 40 0x2f 0x09 0x6C\n  i2cset -f -y 40 0x2f 0x0A 0x6C\n  i2cset -f -y 40 0x2f 0x0B 0x6C\n  i2cset -f -y 40 0x2f 0x0C 0x6C\n  i2cset -f -y 40 0x2f 0x0D 0x6C\n\n  i2c_device_add 40 0x20 max31790\n  i2c_device_add 40 0x2f max31790\n  kv set fan_bp1_fan_chip_source \"$BP_1ST_SOURCE\"\nelse\n  # FAN_BP1 NCT3763Y FAN CHIP\n  # Config FAN PWM and FAIN FAN_BP1\n  i2cset -f -y -a 40 0x01 0x20 0xA9\n  i2cset -f -y -a 40 0x01 0x21 0x99\n  i2cset -f -y -a 40 0x01 0x22 0x9A\n  i2cset -f -y -a 40 0x01 0x38 0x51\n  i2cset -f -y -a 40 0x01 0x39 0x04\n  i2cset -f -y -a 40 0x01 0x41 0x0B\n  i2cset -f -y -a 40 0x01 0x42 0xAE\n\n  i2cset -f -y -a 40 0x02 0x20 0xA9\n  i2cset -f -y -a 40 0x02 0x21 0x99\n  i2cset -f -y -a 40 0x02 0x22 0x9A\n  i2cset -f -y -a 40 0x02 0x38 0x51\n  i2cset -f -y -a 40 0x02 0x39 0x04\n  i2cset -f -y -a 40 0x02 0x41 0x0B\n  i2cset -f -y -a 40 0x02 0x42 0xAE\n\n  # Set FAN 25KHZ\n  i2cset -f -y -a 40 0x01 0xB0 0x00\n  i2cset -f -y -a 40 0x01 0xB1 0x00\n  i2cset -f -y -a 40 0x01 0xB2 0x00\n  i2cset -f -y -a 40 0x01 0xB3 0x00\n  i2cset -f -y -a 40 0x01 0xB4 0x00\n  i2cset -f -y -a 40 0x01 0xB5 0x00\n  i2cset -f -y -a 40 0x01 0xB6 0x00\n  i2cset -f -y -a 40 0x01 0xB7 0x00\n\n  i2cset -f -y -a 40 0x01 0x91 0x04\n  i2cset -f -y -a 40 0x01 0x93 0x04\n  i2cset -f -y -a 40 0x01 0x97 0x04\n  i2cset -f -y -a 40 0x01 0xA3 0x04\n  i2cset -f -y -a 40 0x01 0xA5 0x04\n  i2cset -f -y -a 40 0x01 0xA7 0x04\n  i2cset -f -y -a 40 0x01 0xAB 0x04\n  i2cset -f -y -a 40 0x01 0xAF 0x04\n\n  i2cset -f -y -a 40 0x02 0xB0 0x00\n  i2cset -f -y -a 40 0x02 0xB1 0x00\n  i2cset -f -y -a 40 0x02 0xB2 0x00\n  i2cset -f -y -a 40 0x02 0xB3 0x00\n  i2cset -f -y -a 40 0x02 0xB4 0x00\n  i2cset -f -y -a 40 0x02 0xB5 0x00\n  i2cset -f -y -a 40 0x02 0xB6 0x00\n  i2cset -f -y -a 40 0x02 0xB7 0x00\n\n  i2cset -f -y -a 40 0x02 0x91 0x04\n  i2cset -f -y -a 40 0x02 0x93 0x04\n  i2cset -f -y -a 40 0x02 0x97 0x04\n  i2cset -f -y -a 40 0x02 0xA3 0x04\n  i2cset -f -y -a 40 0x02 0xA5 0x04\n  i2cset -f -y -a 40 0x02 0xA7 0x04\n  i2cset -f -y -a 40 0x02 0xAB 0x04\n  i2cset -f -y -a 40 0x02 0xAF 0x04\n  kv set fan_bp1_fan_chip_source \"$BP_2ND_SOURCE\"\nfi\n\nfan_bp2_fan=$(gpio_get FAN_BP2_SKU_ID_0)\nif [ \"$fan_bp2_fan\" -eq \"$BP_1ST_SOURCE\" ]; then\n  # FAN_BP2 MAX31790 FAN CHIP\n  i2cset -f -y 41 0x20 0x01 0xbb\n  i2cset -f -y 41 0x20 0x02 0x08\n  i2cset -f -y 41 0x20 0x03 0x19\n  i2cset -f -y 41 0x20 0x04 0x08\n  i2cset -f -y 41 0x20 0x05 0x08\n  i2cset -f -y 41 0x20 0x06 0x19\n  i2cset -f -y 41 0x20 0x07 0x08\n  i2cset -f -y 41 0x20 0x08 0x6C\n  i2cset -f -y 41 0x20 0x09 0x6C\n  i2cset -f -y 41 0x20 0x0A 0x6C\n  i2cset -f -y 41 0x20 0x0B 0x6C\n  i2cset -f -y 41 0x20 0x0C 0x6C\n  i2cset -f -y 41 0x20 0x0D 0x6C\n\n  i2cset -f -y 41 0x2f 0x01 0xbb\n  i2cset -f -y 41 0x2f 0x02 0x08\n  i2cset -f -y 41 0x2f 0x03 0x19\n  i2cset -f -y 41 0x2f 0x04 0x08\n  i2cset -f -y 41 0x2f 0x05 0x08\n  i2cset -f -y 41 0x2f 0x06 0x19\n  i2cset -f -y 41 0x2f 0x07 0x08\n  i2cset -f -y 41 0x2f 0x08 0x6C\n  i2cset -f -y 41 0x2f 0x09 0x6C\n  i2cset -f -y 41 0x2f 0x0A 0x6C\n  i2cset -f -y 41 0x2f 0x0B 0x6C\n  i2cset -f -y 41 0x2f 0x0C 0x6C\n  i2cset -f -y 41 0x2f 0x0D 0x6C\n\n  i2c_device_add 41 0x20 max31790\n  i2c_device_add 41 0x2f max31790\n  kv set fan_bp2_fan_chip_source \"$BP_1ST_SOURCE\"\nelse\n  # FAN_BP2 NCT3763Y FAN CHIP\n  # Config FAN PWM and FAIN FAN_BP2\n  i2cset -f -y -a 41 0x01 0x20 0xA9\n  i2cset -f -y -a 41 0x01 0x21 0x99\n  i2cset -f -y -a 41 0x01 0x22 0x9A\n  i2cset -f -y -a 41 0x01 0x38 0x51\n  i2cset -f -y -a 41 0x01 0x39 0x04\n  i2cset -f -y -a 41 0x01 0x41 0x0B\n  i2cset -f -y -a 41 0x01 0x42 0xAE\n\n  i2cset -f -y -a 41 0x02 0x20 0xA9\n  i2cset -f -y -a 41 0x02 0x21 0x99\n  i2cset -f -y -a 41 0x02 0x22 0x9A\n  i2cset -f -y -a 41 0x02 0x38 0x51\n  i2cset -f -y -a 41 0x02 0x39 0x04\n  i2cset -f -y -a 41 0x02 0x41 0x0B\n  i2cset -f -y -a 41 0x02 0x42 0xAE\n  # Set FAN 25KHZ\n  i2cset -f -y -a 41 0x01 0xB0 0x00\n  i2cset -f -y -a 41 0x01 0xB1 0x00\n  i2cset -f -y -a 41 0x01 0xB2 0x00\n  i2cset -f -y -a 41 0x01 0xB3 0x00\n  i2cset -f -y -a 41 0x01 0xB4 0x00\n  i2cset -f -y -a 41 0x01 0xB5 0x00\n  i2cset -f -y -a 41 0x01 0xB6 0x00\n  i2cset -f -y -a 41 0x01 0xB7 0x00\n\n  i2cset -f -y -a 41 0x01 0x91 0x04\n  i2cset -f -y -a 41 0x01 0x93 0x04\n  i2cset -f -y -a 41 0x01 0x97 0x04\n  i2cset -f -y -a 41 0x01 0xA3 0x04\n  i2cset -f -y -a 41 0x01 0xA5 0x04\n  i2cset -f -y -a 41 0x01 0xA7 0x04\n  i2cset -f -y -a 41 0x01 0xAB 0x04\n  i2cset -f -y -a 41 0x01 0xAF 0x04\n\n  i2cset -f -y -a 41 0x02 0xB0 0x00\n  i2cset -f -y -a 41 0x02 0xB1 0x00\n  i2cset -f -y -a 41 0x02 0xB2 0x00\n  i2cset -f -y -a 41 0x02 0xB3 0x00\n  i2cset -f -y -a 41 0x02 0xB4 0x00\n  i2cset -f -y -a 41 0x02 0xB5 0x00\n  i2cset -f -y -a 41 0x02 0xB6 0x00\n  i2cset -f -y -a 41 0x02 0xB7 0x00\n\n  i2cset -f -y -a 41 0x02 0x91 0x04\n  i2cset -f -y -a 41 0x02 0x93 0x04\n  i2cset -f -y -a 41 0x02 0x97 0x04\n  i2cset -f -y -a 41 0x02 0xA3 0x04\n  i2cset -f -y -a 41 0x02 0xA5 0x04\n  i2cset -f -y -a 41 0x02 0xA7 0x04\n  i2cset -f -y -a 41 0x02 0xAB 0x04\n  i2cset -f -y -a 41 0x02 0xAF 0x04\n  kv set fan_bp2_fan_chip_source \"$BP_2ND_SOURCE\"\nfi\n\nFAN_BP1_LED_SKU=$(gpio_get FAN_BP1_SKU_ID_1)\nFAN_BP2_LED_SKU=$(gpio_get FAN_BP2_SKU_ID_1)\n\n# FAN LED Device\"\nrebind_i2c_dev 40 62 leds-pca955x\nrebind_i2c_dev 41 62 leds-pca955x\n\n# FAN Board FRU\ni2c_device_add 40 0x56 24c64 #FAN_BP1 FRU\ni2c_device_add 41 0x56 24c64 #FAN_BP2 FRU\n\ngpio_export_ioexp 40-0021 FAN0_PRESENT   7\ngpio_export_ioexp 40-0021 FAN4_PRESENT   6\ngpio_export_ioexp 40-0021 FAN8_PRESENT   5\ngpio_export_ioexp 40-0021 FAN12_PRESENT  4\ngpio_export_ioexp 40-0021 FAN1_PRESENT   0\ngpio_export_ioexp 40-0021 FAN5_PRESENT   1\ngpio_export_ioexp 40-0021 FAN9_PRESENT   2\ngpio_export_ioexp 40-0021 FAN13_PRESENT  3\n\ngpio_export_ioexp 41-0021 FAN2_PRESENT   7\ngpio_export_ioexp 41-0021 FAN6_PRESENT   6\ngpio_export_ioexp 41-0021 FAN10_PRESENT  5\ngpio_export_ioexp 41-0021 FAN14_PRESENT  4\ngpio_export_ioexp 41-0021 FAN3_PRESENT   0\ngpio_export_ioexp 41-0021 FAN7_PRESENT   1\ngpio_export_ioexp 41-0021 FAN11_PRESENT  2\ngpio_export_ioexp 41-0021 FAN15_PRESENT  3\n\n\n# I/O Expander PCA955X FAN LED\ngpio_export_ioexp 40-0062  FAN1_LED_GOOD   0\ngpio_export_ioexp 40-0062  FAN1_LED_FAIL   1\ngpio_export_ioexp 40-0062  FAN5_LED_GOOD   2\ngpio_export_ioexp 40-0062  FAN5_LED_FAIL   3\ngpio_export_ioexp 40-0062  FAN9_LED_GOOD   4\ngpio_export_ioexp 40-0062  FAN9_LED_FAIL   5\ngpio_export_ioexp 40-0062  FAN13_LED_GOOD  6\ngpio_export_ioexp 40-0062  FAN13_LED_FAIL  7\ngpio_export_ioexp 40-0062  FAN12_LED_GOOD  8\ngpio_export_ioexp 40-0062  FAN12_LED_FAIL  9\ngpio_export_ioexp 40-0062  FAN8_LED_GOOD   10\ngpio_export_ioexp 40-0062  FAN8_LED_FAIL   11\ngpio_export_ioexp 40-0062  FAN4_LED_GOOD   12\ngpio_export_ioexp 40-0062  FAN4_LED_FAIL   13\ngpio_export_ioexp 40-0062  FAN0_LED_GOOD   14\ngpio_export_ioexp 40-0062  FAN0_LED_FAIL   15\n\ngpio_export_ioexp 41-0062  FAN3_LED_GOOD   0\ngpio_export_ioexp 41-0062  FAN3_LED_FAIL   1\ngpio_export_ioexp 41-0062  FAN7_LED_GOOD   2\ngpio_export_ioexp 41-0062  FAN7_LED_FAIL   3\ngpio_export_ioexp 41-0062  FAN11_LED_GOOD  4\ngpio_export_ioexp 41-0062  FAN11_LED_FAIL  5\ngpio_export_ioexp 41-0062  FAN15_LED_GOOD  6\ngpio_export_ioexp 41-0062  FAN15_LED_FAIL  7\ngpio_export_ioexp 41-0062  FAN14_LED_GOOD  8\ngpio_export_ioexp 41-0062  FAN14_LED_FAIL  9\ngpio_export_ioexp 41-0062  FAN10_LED_GOOD  10\ngpio_export_ioexp 41-0062  FAN10_LED_FAIL  11\ngpio_export_ioexp 41-0062  FAN6_LED_GOOD   12\ngpio_export_ioexp 41-0062  FAN6_LED_FAIL   13\ngpio_export_ioexp 41-0062  FAN2_LED_GOOD   14\ngpio_export_ioexp 41-0062  FAN2_LED_FAIL   15\n\nif [ \"$FAN_BP1_LED_SKU\" -eq \"$BP_FAN_MAIN\" ]; then\n  FAN_LED_GOOD=1\n  FAN_LED_FAIL=0\n  kv set fan_bp1_fan_led_source \"$BP_1ST_SOURCE\"\nelse\n  FAN_LED_GOOD=0\n  FAN_LED_FAIL=1\n  kv set fan_bp1_fan_led_source \"$BP_2ND_SOURCE\"\nfi\n\nif [ \"$FAN_BP2_LED_SKU\" -eq \"$BP_FAN_MAIN\" ]; then\n  FAN_LED_GOOD=1\n  FAN_LED_FAIL=0\n  kv set fan_bp2_fan_led_source \"$BP_1ST_SOURCE\"\nelse\n  FAN_LED_GOOD=0\n  FAN_LED_FAIL=1\n  kv set fan_bp2_fan_led_source \"$BP_2ND_SOURCE\"\nfi\n\ngpio_set  FAN0_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN1_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN2_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN3_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN4_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN5_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN6_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN7_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN8_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN9_LED_GOOD  $FAN_LED_GOOD\ngpio_set  FAN10_LED_GOOD $FAN_LED_GOOD\ngpio_set  FAN11_LED_GOOD $FAN_LED_GOOD\ngpio_set  FAN12_LED_GOOD $FAN_LED_GOOD\ngpio_set  FAN13_LED_GOOD $FAN_LED_GOOD\ngpio_set  FAN14_LED_GOOD $FAN_LED_GOOD\ngpio_set  FAN15_LED_GOOD $FAN_LED_GOOD\n\ngpio_set  FAN0_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN1_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN2_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN3_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN4_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN5_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN6_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN7_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN8_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN9_LED_FAIL  $FAN_LED_FAIL\ngpio_set  FAN10_LED_FAIL $FAN_LED_FAIL\ngpio_set  FAN11_LED_FAIL $FAN_LED_FAIL\ngpio_set  FAN12_LED_FAIL $FAN_LED_FAIL\ngpio_set  FAN13_LED_FAIL $FAN_LED_FAIL\ngpio_set  FAN14_LED_FAIL $FAN_LED_FAIL\ngpio_set  FAN15_LED_FAIL $FAN_LED_FAIL\n\n/usr/local/bin/fan-util --set 70\n\n#GPU Reset USB Hub\nif [ \"$(is_bmc_por)\" -eq 1 ]; then\n  echo \"Reset SWB USB Hub\"\n  # set gpio 98 LOW\n  pldmd-util -b 3 -e 0x0a raw 0x02 0x39 0x62 0xFF 0x02 0x00 0x00 0x01 0x01 >/dev/null\n  # add delay\n  sleep 0.5\n  # set gpio 98 HIGH\n  pldmd-util -b 3 -e 0x0a raw 0x02 0x39 0x62 0xFF 0x02 0x00 0x00 0x01 0x02 >/dev/null\n  sleep 3\nfi\n\n", "num_lines": 730}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nrebind_i2c_dev() {\n  dev=\"$1-00$2\"\n  dri=$3\n\n  if [ ! -L \"${SYSFS_I2C_DEVICES}/$dev/driver\" ]; then\n    if i2c_bind_driver \"$dri\" \"$dev\" >/dev/null; then\n      echo \"rebind $dev to driver $dri successfully\"\n    fi\n  fi\n}\n\nvr_sku=$(($(/usr/bin/kv get mb_sku) & 0x03))  #0x00 : RAA,\n                                              #0x01 : INF,\n                                              #0x10 : MPS,\n\n\nMB_1ST_SOURCE=\"0\"\nMB_2ND_SOURCE=\"1\"\nMB_3RD_SOURCE=\"2\"\nMB_4TH_SOURCE=\"3\"\n\nMB_VR_SECOND=\"1\"\nMB_VR_THIRD=\"2\"\n\nMB_ADC_MAIN=\"0\"\n#MB ADM128D\nif [ \"$(gpio_get FM_BOARD_BMC_SKU_ID1)\" -eq \"$MB_ADC_MAIN\" ]; then\n  i2cset -f -y 20 0x1d 0x0b 0x02\n  i2c_device_add 20 0x1d adc128d818\n  kv set mb_adc_source \"$MB_1ST_SOURCE\"\nelse\n  i2c_device_add 20 0x35 max11617\n  kv set mb_adc_source \"$MB_2ND_SOURCE\"\nfi\n\n# MB CPU VR Device\"\nif [ \"$vr_sku\" -eq \"$MB_VR_THIRD\" ]; then\n  i2c_device_add 20 0x60 mp2971\n  i2c_device_add 20 0x61 mp2971\n  i2c_device_add 20 0x63 mp2971\n  i2c_device_add 20 0x72 mp2971\n  i2c_device_add 20 0x74 mp2971\n  i2c_device_add 20 0x76 mp2971\n  kv set mb_vr_source \"$MB_3RD_SOURCE\"\nelif [ \"$vr_sku\" -eq \"$MB_VR_SECOND\"  ]; then\n  i2c_device_add 20 0x60 xdpe152c4\n  i2c_device_add 20 0x62 xdpe152c4\n  i2c_device_add 20 0x64 xdpe152c4\n  i2c_device_add 20 0x72 xdpe152c4\n  i2c_device_add 20 0x74 xdpe152c4\n  i2c_device_add 20 0x76 xdpe152c4\n  kv set mb_vr_source \"$MB_2ND_SOURCE\"\nelse\n  i2c_device_add 20 0x60 isl69260\n  i2c_device_add 20 0x61 isl69260\n  i2c_device_add 20 0x63 isl69260\n  i2c_device_add 20 0x72 isl69260\n  i2c_device_add 20 0x74 isl69260\n  i2c_device_add 20 0x76 isl69260\n  kv set mb_vr_source \"$MB_1ST_SOURCE\"\nfi\n\n# MB HSC Device\"\nmb_hsc=$(($(gpio_get FM_BOARD_BMC_SKU_ID3) << 1 |\n          $(gpio_get FM_BOARD_BMC_SKU_ID2)))\n\n#MB_HSC_MAIN=\"0\"   # mp5990\nMB_HSC_SECOND=\"1\"  # ltc4282/ltc4286\nMB_HSC_THIRD=\"2\"   # rs31380\nmbrev=$(kv get mb_rev)\nMB_DVT_BORAD_ID=\"3\"\n\n\n#kv set mb_hsc_module \"0\"\nif [ \"$mb_hsc\" -eq \"$MB_HSC_THIRD\" ]; then\n  kv set mb_hsc_source \"$MB_4TH_SOURCE\"\nelif [ \"$mb_hsc\" -eq \"$MB_HSC_SECOND\" ]; then\n  i2c_device_add 21 0x4C lm75\n  i2c_device_add 2 0x51 24c64\n  #Read ADC 1.5v:LTC4286 1v:LTC4282\n  #DVT ADC INA230; EVT ADC ISL28022\n  val=$(i2cget -f -y 21 0x42 0x02)\n  data=$((\"$val\"))\n\n  if [ \"$mbrev\" -ge \"$MB_DVT_BORAD_ID\" ]\n  then\n    if [ \"$data\" -ge 4 ]\n    then\n      i2c_device_add 2 0x41 ltc4286\n      kv set mb_hsc_source \"$MB_3RD_SOURCE\"\n    else\n      i2c_device_add 2 0x41 ltc4282\n      kv set mb_hsc_source \"$MB_2ND_SOURCE\"\n    fi\n  else\n    if [ \"$data\" -gt 4 ]\n    then\n      i2c_device_add 2 0x41 ltc4286\n      kv set mb_hsc_source \"$MB_3RD_SOURCE\"\n    else\n      i2c_device_add 2 0x41 ltc4282\n      kv set mb_hsc_source \"$MB_2ND_SOURCE\"\n    fi\n  fi\n  kv set mb_hsc_module \"1\"\nelse\n  i2c_device_add 2 0x20 mp5990\n  kv set mb_hsc_source \"$MB_1ST_SOURCE\"\nfi\n\n#MB DPM\nmbrev=$(kv get mb_rev)\nMB_DVT_BOARD_ID=\"3\"\n\nif [ \"$mbrev\" -ge \"$MB_DVT_BOARD_ID\" ]; then\n  i2c_device_add 34 0x41 ina230\n  i2c_device_add 34 0x42 ina230\n  i2c_device_add 34 0x43 ina230\n  i2c_device_add 34 0x44 ina230\n  i2c_device_add 34 0x45 ina230\n  kv set mb_dpm_source \"$MB_1ST_SOURCE\"\nfi", "num_lines": 146}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# ==GPIOA==\n\n\n# ==GPIOB==\n# FM_ME_BT_DONE\n#gpio_export FM_ME_BT_DONE GPIOB0\n\n# FM_BMC_MUX_CS_SPI_SEL_0\ngpio_export FM_BMC_MUX_CS_SPI_SEL_0 GPIOB4\ngpio_set FM_BMC_MUX_CS_SPI_SEL_0 0\n\n# FM_ID_LED_N\ngpio_export FM_ID_LED_N GPIOB5\ngpio_set FM_ID_LED_N 0\n\n# FM_ESPI_PLD_EN\ngpio_export FM_ESPI_PLD_EN GPIOB6\n\n# ==GPIOC==\n# RST_PLTRST_R_N\ngpio_export RST_PLTRST_R_N GPIOC0\n\n#RST_SGPIO_RESET_BMC_N\ngpio_export RST_SGPIO_RESET_BMC_N GPIOC3\ngpio_set RST_SGPIO_RESET_BMC_N 1\n\n#H_CPU_CATERR_LVC2_R2_N\ngpio_export H_CPU_CATERR_LVC2_R2_N GPIOC5\n\n#FM_JTAG_BMC_MUX_SEL\ngpio_export FM_JTAG_BMC_MUX_SEL GPIOC6\ngpio_set FM_JTAG_BMC_MUX_SEL 1;\n\n#IRQ_SGPIO_BMC_N\ngpio_export IRQ_SGPIO_BMC_N GPIOC7\n\n# ==GPIOD==\ngpio_export FM_BIC_DEBUG_SW_N GPIOD2\ngpio_set FM_BIC_DEBUG_SW_N 0\n\n# ==GPIOE==\n\n# ==GPIOF==\n\n# ==GPIOG==\n\n# ==GPIOH==\n\n# ==GPIOI==\n#FLASH_WP_STATUS_R1\ngpio_export FLASH_WP_STATUS_R1 GPIOI5\n\n# ==GPIOJ==\n\n\n# ==GPIOK==\n\n\n# ==GPIOL==\n# FM_DBP_CPU_PREQ_GF_N\ngpio_export FM_DBP_CPU_PREQ_GF_N GPIOL4\ngpio_set FM_DBP_CPU_PREQ_GF_N 1\n\n\n# ==GPIOM==\n# FM_VIRTUAL_RESEAT_BMC\ngpio_export FM_VIRTUAL_RESEAT_BMC GPIOM1\ngpio_set FM_VIRTUAL_RESEAT_BMC 0\n\n# PWRGD_PSU_AC_PWROK_BMC\ngpio_export PWRGD_PSU_AC_PWROK_BMC GPIOM2\n\n# FM_DBP_BMC_PRDY_N\ngpio_export FM_DBP_BMC_PRDY_N GPIOM5\n\n\n# ==GPION==\n# LED_POSTCODE_0\ngpio_export LED_POSTCODE_0 GPION0\n\n# LED_POSTCODE_1\ngpio_export LED_POSTCODE_1 GPION1\n\n# LED_POSTCODE_2\ngpio_export LED_POSTCODE_2 GPION2\n\n# LED_POSTCODE_3\ngpio_export LED_POSTCODE_3 GPION3\n\n# LED_POSTCODE_4\ngpio_export LED_POSTCODE_4 GPION4\n\n# LED_POSTCODE_5\ngpio_export LED_POSTCODE_5 GPION5\n\n# LED_POSTCODE_6\ngpio_export LED_POSTCODE_6 GPION6\n\n# LED_POSTCODE_7\ngpio_export LED_POSTCODE_7 GPION7\n\n\n# ==GPIOO==\n# FM_PCH_TPM_PRSNT\ngpio_export FM_BIOS_TPM_PRSNT_IN GPIOO5\n\n# ==GPIOP==\n# SYS_BMC_PWRBTN_IN\ngpio_export SYS_BMC_PWRBTN_IN GPIOP0\n\n# SYS_BMC_PWRBTN_OUT\ngpio_export SYS_BMC_PWRBTN_OUT GPIOP1\ngpio_set SYS_BMC_PWRBTN_OUT 1\n\n# SYS_BMC_RSTBTN_IN\ngpio_export ID_RST_BTN_BMC_IN GPIOP2\n\n# BMC_PWR_LED\ngpio_export BMC_PWR_LED GPIOP4\ngpio_set BMC_PWR_LED 0\n\n# ==GPIOQ==\n# IRQ_PCH_TPM_SPI_IN\ngpio_export IRQ_PCH_TPM_SPI_IN GPIOQ0\n\n# USB_OC0_REAR_R_IN\ngpio_export USB_OC0_REAR_R_IN GPIOQ1\n\n# FM_HDD_LED_OUT\ngpio_export FM_HDD_LED_N_OUT GPIOQ4\ngpio_set FM_HDD_LED_N_OUT 0\n\n# FM_P12V_HSC_ENABLE_R1\ngpio_export FM_P12V_HSC_ENABLE_R1 GPIOQ5\ngpio_set FM_P12V_HSC_ENABLE_R1 1\n\n# FM_PCH_BEEP_LED\ngpio_export FM_PCH_BEEP_LED_OUT GPIOQ6\ngpio_set FM_PCH_BEEP_LED_OUT 0\n\n# FM_SOL_UART_CH_SEL\ngpio_export FM_SOL_UART_CH_SEL GPIOQ7\n\n# ==GPIOR==\n\n\n# ==GPIOS==\n# FM_THERMTRIP_N\ngpio_export FM_THERMTRIP_N GPIOS2\n\n# FM_BMC_TPM_PRSNT\ngpio_export FM_BMC_TPM_PRSNT GPIOS3\n\n# FM_BMC_DEBUG_SW_N\ngpio_export FM_BMC_DEBUG_SW_N GPIOS4\n\n\n# ==GPIU==\n# BSM_PRSNT_R_N\ngpio_export BSM_PRSNT_R_N GPIOU4\n\n# ==GPIOV==\n# RST_RSMRST_R_N\ngpio_export RST_RSMRST_R_N GPIOV1\n\ngpio_export BMC_ID_BEEP_SEL_R1 GPIOV2\n#gpio_set BMC_ID_BEEP_SEL_R1 1\n\n# BATTERY_DETECT\ngpio_export BATTERY_DETECT GPIOV4\ngpio_set BATTERY_DETECT 0\n\n# IRQ_BMC_TPM_SPI_IN\ngpio_export IRQ_BMC_TPM_SPI_IN GPIOV7\n\n# ==GPIX==\n# IRQ_SMI_ACTIVE_BMC_N\ngpio_export IRQ_SMI_ACTIVE_BMC_N GPIOX2\n\n# ==GPIOY==\ngpio_export RST_WDTRST_PLD_R1_N GPIOY1\n\n#FM_FLASH_LATCH_N_R1\ngpio_export FM_FLASH_LATCH_N_R1 GPIOY2\n\n#FM BMC_EMMC_RST_R_N\ngpio_export BMC_EMMC_RST_R_N GPIOY3\n\n# ==GPIOZ==\n# BMC_READY_N\n#gpio_export BMC_READY_N GPIOZ0\n#gpio_set BMC_READY_N 0\n\n#FM_DEBUG_PORT_PRSNT_R1_N\ngpio_export FM_DEBUG_PORT_PRSNT_N_IN GPIOZ6\n\n\n# ==GPIO18D==\n# EMMC Func GPIO18D0 - GPIO18D7\ngpio1v8_export AC_PWR_BMC_BTN_N 0\n\n\n\ndevmem_set_bit 0x1e7800e0 8\ndevmem_clear_bit 0x1e7000e4 8\n\n\n# ==SGPIO Input Common==\nsgpio_export GPU_FPGA_READY_ISO_R 8\n\nsgpio_export FM_SYS_THROTTLE_R_N 20\nsgpio_export HPDB_HSC_PWRGD_ISO_R 24\nsgpio_export FM_UV_ADR_TRIGGER_R_N 26\n\nsgpio_export FM_SWB_BIC_READY_ISO_R_N 32\n\nsgpio_export GPU_FPGA_THERM_OVERT_ISO_R_N 40\nsgpio_export GPU_FPGA_OVERT_ISO_R_N 42\nsgpio_export BIC_MONITER_ISO_R 46\n\nsgpio_export GPU_HMC_PRSNT_ISO_R_N 52\nsgpio_export GPU_PRSNT_N_ISO_R 54\n\nsgpio_export FM_GPU_PWRGD_ISO_R 60\nsgpio_export RST_BMC_FROM_SWB_ISO_R_N 62\nsgpio_export GPU_BASE_HMC_READY_ISO_R 64\n\nsgpio_export E1S_0_P3V3_ADC_ALERT 96\nsgpio_export P12V_SCM_ADC_ALERT 98\n\nsgpio_export M2_0_P3V3_ADC_ALERT 100\nsgpio_export OCP_V3_2_P3V3_ADC_ALERT 102\nsgpio_export OCP_SFF_P3V3_ADC_ALERT 104\nsgpio_export FM_UARTSW_LSB_N 106\nsgpio_export FM_UARTSW_MSB_N 108\n\nsgpio_export FM_THERMAL_ALERT_R_N 110\n\nsgpio_export PCIE_M2_SSD0_PRSNT_N 190\n\nsgpio_export FM_SMB_2_ALERT_GPU_ISO_N 208\nsgpio_export FM_SMB_1_ALERT_GPU_ISO_N 210\n\nsgpio_export FM_BOARD_BMC_SKU_ID4 212\nsgpio_export FM_BOARD_BMC_SKU_ID3 214\nsgpio_export FM_BOARD_BMC_SKU_ID2 216\nsgpio_export FM_BOARD_BMC_SKU_ID1 218\nsgpio_export FM_BOARD_BMC_SKU_ID0 220\n\nsgpio_export FAB_BMC_REV_ID2 222\nsgpio_export FAB_BMC_REV_ID1 224\nsgpio_export FAB_BMC_REV_ID0 226\n\nkv set mb_rev \"$(($(gpio_get FAB_BMC_REV_ID2)<<2 |\n                  $(gpio_get FAB_BMC_REV_ID1)<<1 |\n                  $(gpio_get FAB_BMC_REV_ID0)))\"\n\nkv set mb_sku \"$(($(gpio_get FM_BOARD_BMC_SKU_ID4)<<4 |\n                  $(gpio_get FM_BOARD_BMC_SKU_ID3)<<3 |\n                  $(gpio_get FM_BOARD_BMC_SKU_ID2)<<2 |\n                  $(gpio_get FM_BOARD_BMC_SKU_ID1)<<1 |\n                  $(gpio_get FM_BOARD_BMC_SKU_ID0)))\"\n\n\n# == SGPIO OUT Common==\nsgpio_export IRQ_PCH_SCI_WHEA_R_N 11\ngpio_set IRQ_PCH_SCI_WHEA_R_N 1\n\nsgpio_export FM_SPD_REMOTE_EN_R 17\ngpio_set FM_SPD_REMOTE_EN_R 0\n\nsgpio_export RST_BMC_RSTBTN_OUT_R_N 21\ngpio_set RST_BMC_RSTBTN_OUT_R_N 1\n\nsgpio_export BMC_READY_N 23\ngpio_set BMC_READY_N 1\n\nsgpio_export FM_BMC_SGPIO_READY_N 37\n\nsgpio_export GPU_NVS_PWR_BRAKE_R_N 43\ngpio_set GPU_NVS_PWR_BRAKE_R_N 1\n\nsgpio_export GPU_WP_HW_CTRL_R_N 45\ngpio_set GPU_WP_HW_CTRL_R_N 0\n\nsgpio_export BMC_MONITER 51\ngpio_set BMC_MONITER 0\n\nsgpio_export FM_BIOS_TPM_PRSNT_OUT 57\ngpio_set FM_BIOS_TPM_PRSNT_OUT \"$(gpio_get FM_BIOS_TPM_PRSNT_IN)\"\n", "num_lines": 326}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-cover\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set up GPIO pins as appropriate can be cover\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n\n\n# ==SGPIO Input Cover==\nsgpio_export FM_OCP_SFF_PWR_GOOD_R 0\nsgpio_export IRQ_SML1_PMBUS_PLD_ALERT_N 2\nsgpio_export PWRGD_PVNN_MAIN_CPU0 4\nsgpio_export PWRGD_PVPP_HBM_CPU1 6\n\nsgpio_export FM_ADR_ACK_R 10\nsgpio_export IRQ_PVCCD_CPU0_VRHOT_LVC3_N 12\nsgpio_export FM_DIS_PS_PWROK_DLY 14\nsgpio_export IRQ_PSYS_CRIT_N 16\nsgpio_export IRQ_PVCCD_CPU1_VRHOT_LVC3_N 18\n\nsgpio_export FM_PCH_PLD_GLB_RST_WARN_N 22\n\nsgpio_export FM_PCH_BMC_THERMTRIP_N 28\nsgpio_export FM_PCHHOT_R_N 30\n\nsgpio_export FM_PCH_PRSNT_N 34\nsgpio_export IRQ_HSC_FAULT_N 36\nsgpio_export FM_OCP_V3_2_PWR_GOOD_R 38\n\nsgpio_export PWRGD_PVNN_PCH_AUX 44\n\nsgpio_export PWRGD_PVNN_MAIN_CPU1 48\nsgpio_export PWRGD_PVPP_HBM_CPU0 50\n\nsgpio_export PWRGD_P3V3 56\nsgpio_export PWRGD_PVCCFA_EHV_FIVRA_CPU0 58\n\nsgpio_export PWRGD_PVCCD_HV_CPU0 66\nsgpio_export PWRGD_PVCCIN_CPU0 68\nsgpio_export PWRGD_P3V3_AUX_PLD 70\nsgpio_export PWRGD_PVCCINFAON_CPU0 72\nsgpio_export PWRGD_PVCCIN_CPU1 74\nsgpio_export PWRGD_PS_PWROK_PLD_R 76\nsgpio_export PWRGD_PVCCD_HV_CPU1 78\nsgpio_export PWRGD_PVCCFA_EHV_FIVRA_CPU1 80\nsgpio_export PWRGD_PVCCINFAON_CPU1 82\nsgpio_export PWRGD_PVCCFA_EHV_CPU1 84\nsgpio_export PWRGD_PVCCFA_EHV_CPU0 86\nsgpio_export PWRGD_P1V05_PCH_AUX 88\nsgpio_export PWRGD_P1V8_PCH_AUX_PLD 90\nsgpio_export PWRGD_SYS_PWROK_R 92\nsgpio_export PWRGD_PCH_PWROK_R 94\n\nsgpio_export FM_CPU0_SKTOCC_LVT3_PLD_N 112\nsgpio_export FM_CPU1_SKTOCC_LVT3_PLD_N 114\nsgpio_export PWRGD_CPUPWRGD_LVC2_R1 116\nsgpio_export H_CPU1_THERMTRIP_LVC1_N 118\nsgpio_export IRQ_CPU1_VRHOT_N 120\nsgpio_export H_CPU0_MEMTRIP_LVC1_N 122\nsgpio_export H_CPU1_MEMHOT_OUT_LVC1_N 124\nsgpio_export PWRGD_FAIL_CPU1_CD_R 126\nsgpio_export PWRGD_FAIL_CPU1_GH_R 128\nsgpio_export PWRGD_FAIL_CPU0_EF_R 130\nsgpio_export PWRGD_FAIL_CPU0_AB_R 132\nsgpio_export PWRGD_FAIL_CPU0_CD_R 134\nsgpio_export H_CPU0_THERMTRIP_LVC1_N 136\nsgpio_export H_CPU0_MEMHOT_OUT_LVC1_N 138\nsgpio_export H_CPU_ERR2_LVC2_N 140\nsgpio_export H_CPU_ERR1_LVC2_N 142\nsgpio_export H_CPU_ERR0_LVC2_N 144\nsgpio_export FM_BIOS_POST_CMPLT_BMC_N 146\nsgpio_export FM_ME_BT_DONE 148\nsgpio_export PWRGD_FAIL_CPU1_AB_R 150\nsgpio_export PWRGD_FAIL_CPU1_EF_R 152\nsgpio_export IRQ_CPU0_VRHOT_N 154\nsgpio_export PWRGD_DSW_PWROK_R3 156\nsgpio_export H_CPU1_MEMTRIP_LVC1_N 158\nsgpio_export FM_ADR_COMPLETE 160\nsgpio_export FM_BMC_DBP_PRESENT_R_N 162\nsgpio_export FM_SLPS3_PLD_N 164\nsgpio_export FM_SLPS4_PLD_N 166\nsgpio_export FM_ADR_TRIGGER_N 168\nsgpio_export FM_REMOTE_DEBUG_DET 170\nsgpio_export E1S_0_PRSNT_N 172\nsgpio_export IRQ_PCH_CPU_NMI_EVENT_N 174\nsgpio_export FM_PS_EN_PLD_R 176\nsgpio_export IRQ_OC_DETECT_N  178\nsgpio_export PWRGD_FAIL_CPU0_GH_R 180\nsgpio_export H_CPU_RMCA_LVC2_R2_N 182\n#sgpio_export H_CPU_CATERR_LVC2_R2_N 184\nsgpio_export H_CPU1_PROCHOT_LVC1_N 186\nsgpio_export IRQ_UV_DETECT_N 188\n\nsgpio_export FM_ME_AUTHN_FAIL 192\nsgpio_export PRSNT_SWB_R_N 194\nsgpio_export IRQ_PSU_ALERT_R_N 196\nsgpio_export FM_THROTTLE_R_N 198\nsgpio_export RST_PLTRST_PLD_N 200\nsgpio_export H_CPU0_PROCHOT_LVC1_N 202\nsgpio_export FM_PCH_BEEP_LED 204\nsgpio_export FM_HDD_LED_N 206\n\nsgpio_export CPLD_POWER_FAIL_ALERT 240\n\nsgpio_export CPLD_SGPIO_READY_ID0 248\nsgpio_export CPLD_SGPIO_READY_ID1 250\nsgpio_export CPLD_SGPIO_READY_ID2 252\nsgpio_export CPLD_SGPIO_READY_ID3 254\n\n\n\n\n\n\n# == SGPIO OUT Cover==\nsgpio_export FM_ESPI_PLD_R1_EN 1\ngpio_set FM_ESPI_PLD_R1_EN 1\n\nsgpio_export IRQ_BMC_CPU_NMI 3\ngpio_set IRQ_BMC_CPU_NMI 0\n\nsgpio_export RST_PCA9548_SENSOR_R_N 5\ngpio_set RST_PCA9548_SENSOR_R_N 1\n\nsgpio_export FM_BMC_CRASHLOG_TRIG_R1_N 7\ngpio_set FM_BMC_CRASHLOG_TRIG_R1_N 1\n\nsgpio_export FM_DEBUG_PORT_PRSNT_N_OUT 9\ngpio_set FM_DEBUG_PORT_PRSNT_N_OUT \"$(gpio_get FM_DEBUG_PORT_PRSNT_N_IN)\"\n\nsgpio_export FM_PECI_SEL_R_N 13\ngpio_set FM_PECI_SEL_R_N 1\n\n#sgpio_export FM_JTAG_BMC_MUX_SEL 15\n#gpio_set FM_JTAG_BMC_MUX_SEL 0\n\nsgpio_export FM_ASD_ENABLE 19\ngpio_set FM_ASD_ENABLE 1\n\nsgpio_export TEST_SGPIO_EVENT_LOG 25\ngpio_set TEST_SGPIO_EVENT_LOG 0\n\nsgpio_export IRQ_BMC_PCH_NMI_N 27\ngpio_set IRQ_BMC_PCH_NMI_N 1\n\nsgpio_export BMC_FORCE_NM_THROTTLE_N 29\ngpio_set BMC_FORCE_NM_THROTTLE_N 1\n\nsgpio_export NV_DUMP_END 31\ngpio_set NV_DUMP_END 0\n\n#sgpio_export RST_RSMRST_R_N 33\n\nsgpio_export FM_BMC_ONCTL_R_N 35\ngpio_set FM_BMC_ONCTL_R_N 1\n\n#sgpio_export FM_BMC_SUSACK_R1_N 39\n\nsgpio_export FM_BIOS_DEBUG_EN_R_N 41\ngpio_set FM_BIOS_DEBUG_EN_R_N 1\n\nsgpio_export CLK_GEN2_BMC_RC_OE_N 47\ngpio_set CLK_GEN2_BMC_RC_OE_N 0\n\nsgpio_export IRQ_SML0_ALERT_R_N 49\ngpio_set IRQ_SML0_ALERT_R_N 1\n\nsgpio_export FM_PFR_DSW_PWROK_N 53\ngpio_set FM_PFR_DSW_PWROK_N 1\n\nsgpio_export FM_PFR_OVR_RTC_R 55\ngpio_set FM_PFR_OVR_RTC_R 0\n\nsgpio_export IRQ_PCH_TPM_SPI_OUT 61\ngpio_set IRQ_PCH_TPM_SPI_OUT 1\n\nsgpio_export USB_OC0_REAR_R_OUT 63\ngpio_set USB_OC0_REAR_R_OUT 1\n\nsgpio_export GPU_FPGA_RST_N 65\ngpio_set GPU_FPGA_RST_N 0\n\nsgpio_export FM_JTAG_TCK_MUX_BMC_SEL 67\ngpio_set FM_JTAG_TCK_MUX_BMC_SEL 0\n\nsgpio_export CLK_BUF1_GPU_FPGA_OE_R_N 69\ngpio_set CLK_BUF1_GPU_FPGA_OE_R_N 0\n\nsgpio_export FM_BMC_CPU_FBRK_OUT_N 71\ngpio_set FM_BMC_CPU_FBRK_OUT_N 1\n\n", "num_lines": 217}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nVPDB_EVT2_REV_ID=\"2\"\n\nif [ \"$(kv get vpdb_rev)\" -ge $VPDB_EVT2_REV_ID ]; then\n  ln -s /etc/sensors_cfg/evt2.conf /etc/sensors.d/rev.conf\nelse\n  ln -s /etc/sensors_cfg/evt.conf /etc/sensors.d/rev.conf\nfi\n\n\n#VPDB ADM1272 config\nfor i in {1..5}\ndo\n  rev=$(fruid-util vpdb 2>/dev/null |grep \"Board Part Number\" | awk -F \":\" '{print $2}' | awk '{gsub(/^ +| +$/,\"\")}1')\n  rc=$?\n\n  if [ \"$rc\" == 1 ] || [ -z \"$rev\" ]; then\n    sleep 1\n  elif [ \"$rev\" == \"35F0TPB0000\" ]; then\n    ln -s /etc/sensors_cfg/vpdb-adm1272-1.conf /etc/sensors.d/vpdb_adm1272.conf\n    break\n  elif [ \"$rev\" == \"35F0TPB0020\" ] || [ \"$rev\" == \"35F0TPB0040\" ]; then\n    ln -s /etc/sensors_cfg/vpdb-adm1272-2.conf /etc/sensors.d/vpdb_adm1272.conf\n    break\n  fi\n\n  if [ $i -eq 5 ]; then\n    ln -s /etc/sensors_cfg/vpdb-adm1272-1.conf /etc/sensors.d/vpdb_adm1272.conf\n  fi\ndone\n\n\n#HPDB ADM1272 config\nfor i in {1..5}\n  do\n  rev=$(fruid-util hpdb 2>/dev/null |grep \"Board Part Number\" | awk -F \":\" '{print $2}' | awk '{gsub(/^ +| +$/,\"\")}1')\n  rc=$?\n\n  if [ \"$rc\" == 1 ] || [ -z \"$rev\" ]; then\n    sleep 1\n  elif [ \"$rev\" == \"35F0TPB0060\" ]; then\n    ln -s /etc/sensors_cfg/hpdb-adm1272-2.conf /etc/sensors.d/hpdb_adm1272.conf\n    break\n  elif [ \"$rev\" == \"35F0TPB0010\" ] || [ \"$rev\" == \"35F0TPB0090\" ]; then\n    ln -s /etc/sensors_cfg/hpdb-adm1272-1.conf /etc/sensors.d/hpdb_adm1272.conf\n    break\n  fi\n\n  if [ $i -eq 5 ]; then\n    ln -s /etc/sensors_cfg/hpdb-adm1272-1.conf /etc/sensors.d/hpdb_adm1272.conf\n  fi\ndone\n", "num_lines": 58}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config() {\n  TO_PWR_ON=0\n\n  if POR=$(kv get \"server_por_cfg\" persistent); then\n    if [ \"$POR\" = \"lps\" ]; then\n      if LS=$(kv get \"pwr_server_last_state\" persistent); then\n        if [ \"$LS\" = \"on\" ]; then\n          TO_PWR_ON=1;\n        fi\n      else\n        TO_PWR_ON=$DEF_PWR_ON\n      fi\n    elif [ \"$POR\" = \"on\" ]; then\n      TO_PWR_ON=1;\n    fi\n  else\n    TO_PWR_ON=$DEF_PWR_ON\n  fi\n}\n\nmb_server_power_on() {\n  echo $TO_PWR_ON\n  if [ \"$(is_bmc_por)\" -eq 1 ]; then\n    check_por_config\n    if [ $TO_PWR_ON -eq 1 ]; then\n      power-util mb on\n    fi\n  fi\n}\n\nmb_server_power_on\n", "num_lines": 68}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\ngpio_set FM_BMC_SGPIO_READY_N 0\n\ncat /tmp/gpionames/FM_BMC_SGPIO_READY_N/value\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nconnect_uart2_4() {\n  echo -ne \"uart2\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart4\n  echo -ne \"uart4\" > /sys/devices/platform/ahb/ahb:apb/1e789000.lpc/1e789098.uart_routing/uart2\n}\n\nconnect_uart2_4\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n#MB_HSC_MODULE=\"1\"  # ltc4282/ltc4286\nif kv get mb_hsc_module >/dev/null; then\n  sed -i \"2{s/$/ hsc/}\" /etc/sv/sensord/run\nfi\n\n#SWB_HSC_MODULE=\"1\"  # ltc4282/ltc4286\nif kv get swb_hsc_module >/dev/null; then\n  sed -i \"2{s/$/ swb_hsc/}\" /etc/sv/sensord/run\nfi\n\n\nkv set mb_polling_status      1\nkv set swb_polling_status     1\nkv set hgx_polling_status     1\nkv set nic0_polling_status    1\nkv set nic1_polling_status    1\nkv set scm_polling_status     1\nkv set vpdb_polling_status    1\nkv set hpdb_polling_status,   1\nkv set fan_bp1_polling_status 1\nkv set fan_bp2_polling_status 1\nkv set hsc_polling_status     1\nkv set swb_hsc_polling_status 1\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/fbpackages/utils/ast-functions\n\nsetup_hgx_eeprom () {\n  if [ ! -L \"/sys/bus/i2c/drivers/at24/9-0053\" ];\n  then\n    i2c_device_add 9 0x53 24c64\n    sleep 1\n    dd if=/sys/class/i2c-dev/i2c-9/device/9-0053/eeprom of=/tmp/fruid_hgx.bin bs=512 count=1\n  fi\n}\n\n\nifconfig usb0 192.168.31.2 netmask 255.255.0.0\nkv set is_usbnet_ready 1\nsetup_hgx_eeprom\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# shellcheck disable=SC1091\n. /usr/local/fbpackages/utils/ast-functions\n\n# Sync BMC's date with the server\nsync_date()\n{\n  sleep 1\n  # if no ntp peer has been declared the system peer\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    echo Syncing up BMC time with server...\n    # Use standard IPMI command 'get-sel-time' to read RTC time\n    for i in {1..10};\n    do\n    #Master\n      output=$(/usr/local/bin/ipmb-util 6 0x2c 0x28 0x48)\n      if [ ${#output} == 12 ]\n      then\n        break;\n      fi\n\n      if [ ${i} == 10 ]\n      then\n        exit\n      fi\n      usleep 300\n    done\n\n    sys_date=$(date +%s)\n    set_date=$((16#$(echo \"$output\" | awk '{print $4$3$2$1}')))\n\n    if [ \"$sys_date\" -ge $set_date ]; then\n      echo \"Use BMC date\"\n      set_date=\"$sys_date\"\n    fi\n\n    date -s @\"$set_date\"\n    test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n  fi\n}\n\nsync_date\n", "num_lines": 64}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nkv set is_usbnet_ready 0\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 3\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/pldmd --bus 4\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\necho -n \"Starting PLDMD Rx/Tx Daemon..\"\n\nrunsv /etc/sv/pldmd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/pldmd_4 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 28}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n### BEGIN INIT INFO\n# Provides:          hwclock\n# Required-Start:    \n# Required-Stop:     $local_fs\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Set system clock\n# Description:       Set system clock to hardware clock, according to the UTC\n#                    setting in /etc/default/rcS (see also rcS(5)).\n### END INIT INFO\n#\n# WARNING:      If your hardware clock is not in UTC/GMT, this script\n#               must know the local time zone. This information is\n#               stored in /etc/localtime. This might be a problem if\n#               your /etc/localtime is a symlink to something in\n#               /usr/share/zoneinfo AND /usr isn't in the root\n#               partition! The workaround is to define TZ either\n#               in /etc/default/rcS, or in the proper place below.\n\n[ ! -x /sbin/hwclock ] && exit 0\n\n[ -f /etc/default/rcS ] && . /etc/default/rcS\n\n[ \"$UTC\" = \"yes\" ] && tz=\"--utc\" || tz=\"--localtime\"\ncase \"$1\" in\n        start)\n                if [ \"$VERBOSE\" != no ]\n                then\n                        echo \"System time was `date`.\"\n                        echo \"Setting the System Clock using the Hardware Clock as reference...\"\n                fi\n\n\t\tif [ \"$HWCLOCKACCESS\" != no ]\n\t\tthen\n\t\t\tif [ -z \"$TZ\" ]\n\t\t\tthen\n\t      hwclock $tz -f /dev/rtc1 --hctosys\n\t\t\telse\n\t\t\t   TZ=\"$TZ\" hwclock $tz -f /dev/rtc1 --hctosys\n\t\t\tfi\n\n      hwclock $tz -f /dev/rtc1 --systohc\n\t\tfi\n\n                if [ \"$VERBOSE\" != no ]\n                then\n                        echo \"System Clock set. System local time is now `date`.\"\n                fi\n                ;;\n        stop|restart|reload|force-reload)\n\t\t#\n\t\t# Updates the Hardware Clock with the System Clock time.\n\t\t# This will *override* any changes made to the Hardware Clock.\n\t\t#\n\t\t# WARNING: If you disable this, any changes to the system\n\t\t#          clock will not be carried across reboots.\n\t\t#\n\t\tif [ \"$VERBOSE\" != no ]\n\t\tthen\n\t\t\techo \"Saving the System Clock time to the Hardware Clock...\"\n\t\tfi\n\t\tif [ \"$HWCLOCKACCESS\" != no ]\n\t\tthen\n\t\t\thwclock -f /dev/rtc1 $tz --systohc\n\t\tfi\n\t\tif [ \"$VERBOSE\" != no ]\n\t\tthen\n\t\t\techo \"Hardware Clock updated to `date`.\"\n\t\tfi\n                exit 0\n                ;;\n\tshow)\n\t\tif [ \"$HWCLOCKACCESS\" != no ]\n\t\tthen\n\t\t\thwclock -f /dev/rtc1 $tz --show\n\t\tfi\n\t\t;;\n        *)\n                echo \"Usage: hwclock.sh {start|stop|show|reload|restart}\" >&2\n\t\techo \"       start sets kernel (system) clock from hardware (RTC) clock\" >&2\n\t\techo \"       stop and reload set hardware (RTC) clock from kernel (system) clock\" >&2\n                exit 1\n                ;;\nesac\n", "num_lines": 86}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. /usr/local/fbpackages/utils/ast-functions\n\nWDT2_CTRL_REG=0x1E78502C\n\n# Disable watchdog-2\ndevmem_clear_bit $WDT2_CTRL_REG 0\n\nexit 0\n", "num_lines": 11}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nKV_CMD=/usr/bin/kv\n\ni2c_scan9=$(i2cdetect -y 9)\ni2c_scan10=$(i2cdetect -y 10)\n\n# Scan the i2cbus 9 and 10 and check for PLX switch. If they do not exist, the PCie used is PMC\nif ([[ $i2c_scan9 == *\"5d\"* ]] && [[ $i2c_scan9 == *\"5e\"* ]] && [[ $i2c_scan9 == *\"5f\"* ]] \\\n  && [[ $i2c_scan10 == *\"5d\"* ]] && [[ $i2c_scan10 == *\"5e\"* ]] && [[ $i2c_scan10 == *\"5f\"* ]])\nthen\n  ${KV_CMD} set \"pcie_switch_vendor\" \"PLX\"\n  echo -e \"PLX switch selected\"\nelse\n  ${KV_CMD} set \"pcie_switch_vendor\" \"PMC\"\n  echo -e \"PMC switch selected\"\nfi\n\nexit 0\n", "num_lines": 20}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Function to set the less significant hex digit\ndisplay_lower() {  \n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n    \n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOJ[0...3].\n    # For GPIO bank J, SCU84[8..11] must be 0.\n    devmem_clear_bit $(scu_addr 84) 8\n    devmem_clear_bit $(scu_addr 84) 9\n    devmem_clear_bit $(scu_addr 84) 10\n    devmem_clear_bit $(scu_addr 84) 11\n\n    # Now set the GPIOs to the right binary values\n    gpio_set 72 $bit0\n    gpio_set 73 $bit1\n    gpio_set 74 $bit2\n    gpio_set 75 $bit3\n}\n\n# Function to set the more significant hex digit\ndisplay_upper() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOG[0...3].\n    # For GPIO bank G, SCU84[0..3] must be 0.\n    devmem_clear_bit $(scu_addr 84) 0\n    devmem_clear_bit $(scu_addr 84) 1\n    devmem_clear_bit $(scu_addr 84) 2\n    devmem_clear_bit $(scu_addr 84) 3\n\n    gpio_set 48 $bit0\n    gpio_set 49 $bit1\n    gpio_set 50 $bit2\n    gpio_set 51 $bit3\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\n# Get upper/lower decimal values\nLOWER_DEC_VALUE=$(expr $DEC_VALUE % 16)\nUPPER_DEC_VALUE=$(expr $DEC_VALUE / 16)\n\n# Display the results\ndisplay_lower $LOWER_DEC_VALUE\ndisplay_upper $UPPER_DEC_VALUE\n\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <slot#> <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 2 ]; then\n    usage $0\nfi\n\n# Slot#1: GPIOM1(97),Slot#2: GPIOM0(96),Slot#3: GPIOM3(99),Slot#4: GPIOM2(98)\nif [ $1 = \"1\" ]; then\n    gpio=M1\nelif [ $1 = \"2\" ]; then\n    gpio=M0\nelif [ $1 = \"3\" ]; then\n    gpio=M3\nelif [ $1 = \"4\" ]; then\n    gpio=M2\nelse\n    usage $0\nfi\n\n\nif [ $2 = \"on\" ]; then\n    val=1\nelif [ $2 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set $gpio $val\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n# channel 0 (ADC0_12V)     :  r1:  5.6K; r2:  1.0K; v2: 0mv\n# channel 1 (ADC_P5V_STBY) :  r1:  3.3K; r2:  1.0K; v2: 0mv\n# channel 2 (ADC_P3V3_STBY):  r1:  1.0K; r2:  1.0K; v2: 0mv\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\n\nconfig_adc 0 5600 1000 0\nconfig_adc 1 3300 1000 0\nconfig_adc 2 1000 1000 0\n\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. /usr/local/fbpackages/utils/ast-functions\nKV_CMD=/usr/bin/kv\n\nMUX_BASE=0x08\nI2C_7_MUX_ADDR=0x71\nI2C_8_MUX_ADDR=0x72\nI2C_M2_MUX_ADDR=0x73\nI2C_M2CARD_AMB_ADDR=0x4c\nM2_CHANNEL0=0x01\n\nM2_MUX_ADDR=$(echo $I2C_M2_MUX_ADDR | cut -c3-4)\nM2CARD_AMB_ADDR=$(echo $I2C_M2CARD_AMB_ADDR | cut -c3-4)\n\nfor (( i=0; i<7; i++ ))\ndo\n        NUM=$(($MUX_BASE + $i))\n        MUX=$(printf \"0x%x\" $NUM)\n \n        i2c_set7=$(i2cset -y 7 $I2C_7_MUX_ADDR $MUX 2>&1)\n        i2c_get7=$(i2cget -y 7 $I2C_7_MUX_ADDR 2>&1)\n        # if i2c command fail, reset ssd mux by enable GPIOQ6\n        if ([[ $i2c_set7 == *Error* || $i2c_get7 == *Error* ]])\n        then\n                gpio_set Q6 0\n                sleep 1\n                gpio_set Q6 1\n                if ([[ $i == 0 ]])\n                then\n                        break\n                fi\n                continue\n        fi\n\n        i2c_scan7=$(i2cdetect -y 7)\n        if ([[ $i2c_scan7 == *$M2_MUX_ADDR* ]])\n        then\n                i2cset -y 7 $I2C_M2_MUX_ADDR $M2_CHANNEL0\n                i2c_scan7=$(i2cdetect -y 7)\n                if ([[ $i2c_scan7 == *$M2CARD_AMB_ADDR* ]])\n                then\n                        ${KV_CMD} set \"ssd_sku_info\" \"M2\"\n                        exit 0\n                fi\n        fi\ndone\n\nfor (( i=0; i<8; i++ ))\ndo\n        NUM=$(($MUX_BASE + $i))\n        MUX=$(printf \"0x%x\" $NUM)\n\n        i2c_set8=$(i2cset -y 8 $I2C_8_MUX_ADDR $MUX 2>&1)\n        i2c_get8=$(i2cget -y 8 $I2C_8_MUX_ADDR 2>&1)\n        # if i2c command fail, reset ssd mux by enable GPIOQ6\n        if ([[ $i2c_set8 == *Error* || $i2c_get8 == *Error* ]])\n        then\n                gpio_set Q6 0\n                sleep 1\n                gpio_set Q6 1\n                if ([[ $i == 0 ]])\n                then\n                        break\n                fi\n                continue\n        fi\n\n        i2c_scan8=$(i2cdetect -y 8)\n        if ([[ $i2c_scan8 == *$M2_MUX_ADDR* ]])\n        then\n                i2cset -y 8 $I2C_M2_MUX_ADDR $M2_CHANNEL0\n                i2c_scan8=$(i2cdetect -y 8)\n                if ([[ $i2c_scan8 == *$M2CARD_AMB_ADDR* ]])\n                then\n                        ${KV_CMD} set \"ssd_sku_info\" \"M2\"\n                        exit 0\n                fi\n        fi\ndone\n\n${KV_CMD} set \"ssd_sku_info\" \"U2\"\n\nexit 0\n", "num_lines": 85}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n. /usr/local/fbpackages/utils/ast-functions\nKV_CMD=/usr/bin/kv\n\nMUX_BASE=0x08\nI2C_7_MUX_ADDR=0x71\nI2C_8_MUX_ADDR=0x72\nI2C_M2_MUX_ADDR=0x73\nI2C_NVME_INTF_ADDR=0x6a\nI2C_VID_ADDR=0x09\nM2_CHANNEL0=0x01\n\nINTEL=0x8680\nSEAGATE=0xb11b\nSAMSUNG=0x4d14\nTOSHIBA=0x7911\nWD=0x961b\n\nM2_MUX_ADDR=$(echo $I2C_M2_MUX_ADDR | cut -c3-4)\n\nfor (( i=0; i<7; i++ ))\ndo\n        NUM=$((MUX_BASE + i))\n        MUX=$(printf \"0x%x\" $NUM)\n\n        i2c_set7=$(i2cset -y 7 $I2C_7_MUX_ADDR \"$MUX\" 2>&1)\n        i2c_get7=$(i2cget -y 7 $I2C_7_MUX_ADDR 2>&1)\n        # if i2c command fail, reset ssd mux by enable GPIOQ6\n        if [[ $i2c_set7 == *Error* || $i2c_get7 == *Error* ]]\n        then\n                gpio_set Q6 0\n                sleep 1\n                gpio_set Q6 1\n                if [[ $i == 0 ]]\n                then\n                        break\n                fi\n                continue\n        fi\n\n        i2c_scan7=$(i2cdetect -y 7)\n        if [[ $i2c_scan7 == *$M2_MUX_ADDR* ]]\n        then\n                i2cset -y 7 $I2C_M2_MUX_ADDR $M2_CHANNEL0\n        fi\n        VID=$(i2cget -y 7 $I2C_NVME_INTF_ADDR $I2C_VID_ADDR w)\n        if [[ $VID == *$INTEL* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"intel\"\n            exit 0\n        elif [[ $VID == *$SEAGATE* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"seagate\"\n            exit 0\n        elif [[ $VID == *$SAMSUNG* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"samsung\"\n            exit 0\n        elif [[ $VID == *$TOSHIBA* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"toshiba\"\n            exit 0\n        elif [[ $VID == *$WD* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"wd\"\n            exit 0\n        fi\n\ndone\n\nfor (( i=0; i<8; i++ ))\ndo\n        NUM=$((MUX_BASE + i))\n        MUX=$(printf \"0x%x\" $NUM)\n\n        i2c_set8=$(i2cset -y 8 $I2C_8_MUX_ADDR \"$MUX\" 2>&1)\n        i2c_get8=$(i2cget -y 8 $I2C_8_MUX_ADDR 2>&1)\n        # if i2c command fail, reset ssd mux by enable GPIOQ6\n        if [[ $i2c_set8 == *Error* || $i2c_get8 == *Error* ]]\n        then\n                gpio_set Q6 0\n                sleep 1\n                gpio_set Q6 1\n                if [[ $i == 0 ]]\n                then\n                        break\n                fi\n                continue\n        fi\n\n        i2c_scan8=$(i2cdetect -y 8)\n        if [[ $i2c_scan8 == *$M2_MUX_ADDR* ]]\n        then\n                i2cset -y 8 $I2C_M2_MUX_ADDR $M2_CHANNEL0\n        fi\n        VID=$(i2cget -y 8 $I2C_NVME_INTF_ADDR $I2C_VID_ADDR w)\n        if [[ $VID == *$INTEL* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"intel\"\n            exit 0\n        elif [[ $VID == *$SEAGATE* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"seagate\"\n            exit 0\n        elif [[ $VID == *$SAMSUNG* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"samsung\"\n            exit 0\n        elif [[ $VID == *$TOSHIBA* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"toshiba\"\n            exit 0\n        elif [[ $VID == *$WD* ]]\n        then\n            ${KV_CMD} set \"ssd_vendor\" \"wd\"\n            exit 0\n        fi\ndone\n\n${KV_CMD} set \"ssd_vendor\" \"unknown\"\n\nexit 0\n", "num_lines": 124}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\nTACH_BUS=5\nTACH_ADDR=0x2d\nTACH_REGISTER_L=0x24\nTACH_REGISTER_H=0x25\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On Lightning, there are 6 fans which are driven by Tacho0.\n# Each fan uses same PWM input and provide one tacho output.\n# Here is the mapping between the fan and PWN/Tacho,\n# staring from the one from the edge\n# Fan 0: PWM 0, Tacho0\n\n# For each fan, setting the type, and 100% initially\necho 0 > $PWM_DIR/pwm0_type\necho 0 > $PWM_DIR/pwm0_rising\necho 0 > $PWM_DIR/pwm0_falling\necho 1 > $PWM_DIR/pwm0_en\n\n# Enable Tach 0\ni2cset -y $TACH_BUS $TACH_ADDR $TACH_REGISTER_L 0xFF b\ni2cset -y $TACH_BUS $TACH_ADDR $TACH_REGISTER_H 0x0F b\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\nKV_CMD=/usr/bin/kv\n\n# Get SSD type and vender_device ID from cache\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\n\n# get from cache\nflash_type=$(${KV_CMD} get \"ssd_sku_info\")\nssd_vendor=$(${KV_CMD} get \"ssd_vendor\")\n\ncase \"$flash_type\" in\n   \"U2\")\n        case \"$ssd_vendor\" in\n           \"intel\") cp /etc/FSC_Lightning_PVT_Intel_U2_4TB_v3_config.json ${default_fsc_config_path}\n           ;;\n           \"samsung\") cp /etc/FSC_Lightning_PVT_Samsung_U2_4TB_v3_config.json ${default_fsc_config_path}\n           ;;\n           *) echo \"Using default fan table - Unexpected U.2 SSD vendor.\"\n              cp /etc/FSC_Lightning_PVT_Intel_U2_4TB_v3_config.json ${default_fsc_config_path}\n           ;;\n        esac\n   ;;\n   \"M2\")\n        case \"$ssd_vendor\" in\n           \"seagate\") cp /etc/FSC_Lightning_PVT_Seagate_M2_2TB_v4_config.json ${default_fsc_config_path}\n           ;;\n           \"samsung\") cp /etc/FSC_Lightning_PVT_Samsung_M2_2TB_v4_config.json ${default_fsc_config_path}\n           ;;\n           \"toshiba\") cp /etc/FSC_Lightning_PVT_Toshiba_M2_2TB_v1_config.json ${default_fsc_config_path}\n           ;;\n           *) echo \"Using default fan table - Unexpected M.2 SSD vendor.\"\n              cp /etc/FSC_Lightning_PVT_Seagate_M2_2TB_v4_config.json ${default_fsc_config_path}\n           ;;\n         esac\n   ;;\n   *) echo \"Enter into transitional mode - Unexpected flash type!\"\n      /usr/local/bin/init_pwm.sh\n      /usr/local/bin/fan-util --set 70\n      exit 1\n   ;;\nesac\n\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2016-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nmodprobe lm75\nmodprobe pmbus\n\n# Enable the ADC inputs;  adc0 - adc7 are connected to various voltage sensors\n\necho 1 > /sys/devices/platform/ast_adc.0/adc0_en\necho 1 > /sys/devices/platform/ast_adc.0/adc1_en\necho 1 > /sys/devices/platform/ast_adc.0/adc2_en\necho 1 > /sys/devices/platform/ast_adc.0/adc3_en\necho 1 > /sys/devices/platform/ast_adc.0/adc4_en\necho 1 > /sys/devices/platform/ast_adc.0/adc5_en\necho 1 > /sys/devices/platform/ast_adc.0/adc6_en\necho 1 > /sys/devices/platform/ast_adc.0/adc7_en\n\n\nI2C_BUS_FCB=5\n\nI2C_BUS_PEB=4\n\n# NCT7904 is the fan controller on the FCB board\nI2C_ADDR_FCB_NCT7904=0x2d\n\n# ADM1276 is the HSC on FCB board\nI2C_ADDR_FCB_HSC=0x22\n\n# PCA9551 is the LED controller on the FCB board\nI2C_ADDR_FCB_LED=0x60\n\n# ADM1278 is the HSC on PEB board\nI2C_ADDR_PEB_HSC=0x11\n\n# Enable the Pins to sense the Temperature VSEN23_MD and VSEN45_MD\ni2cset -y $I2C_BUS_FCB $I2C_ADDR_FCB_NCT7904 0x2e 0x5 b\n\n# Enable the Power IN averaging setting\ni2cset -y $I2C_BUS_FCB $I2C_ADDR_FCB_HSC 0xd4 0xaf b\n\n# Light on FCB LED(turn blue)\ni2cset -y $I2C_BUS_FCB $I2C_ADDR_FCB_LED 0x05 0x00  #LED 0~3\ni2cset -y $I2C_BUS_FCB $I2C_ADDR_FCB_LED 0x06 0x00  #LED 4~5\n\n# Initialize the 7904 monitor_flag register\ni2cset -y $I2C_BUS_FCB $I2C_ADDR_FCB_NCT7904 0xba 0x00\n\n# Enable the Power IN averaging setting\ni2cset -y $I2C_BUS_PEB $I2C_ADDR_PEB_HSC 0xd4 0x3f1c w\n\n# Enable the PEB HSC\ni2cset -y $I2C_BUS_PEB $I2C_ADDR_PEB_HSC 0xd3 0x01 w\n\n#Enable the ADC controller for ADC0~ADC7\ndevmem 0x1e6e9000 32 0x00ff000f\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/fbpackages/utils/ast-functions\n\n/usr/local/bin/init_sensor.sh\nexec /usr/local/bin/sensord peb pdpb fcb\n", "num_lines": 7}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          usbcons\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Creates a virtual USB serial device and starts a console\n#                    on it.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=usbcons\nPIDFILE=/run/usbcons.pid\nDESC=\"USB Serial Console\"\n\n# source function library\n. /etc/init.d/functions\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    # Ability to prevent this from starting by editing cmdline in u-boot.\n    # Keeping this here until I get gadget switching working properly. (t4906522)\n    if grep \"nousbcons\" /proc/cmdline > /dev/null 2>&1\n    then\n      echo \"USB Console Disabled.\"\n      exit 0\n    fi\n    echo -n \"Starting $DESC: \"\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall usbmon.sh\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall usbmon.sh\n    sleep 1\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 81}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nmodprobe g_cdc host_addr=02:00:00:00:00:02 dev_addr=02:00:00:00:00:01\nwhile true; do\n    getty /dev/ttyGS0 57600\n    sleep 1\ndone\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) == \"0\" ]]; then\n  /usr/local/bin/bic-cached 1 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup_bios_util\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup bios-util config\n### END INIT INFO\n\necho -n \"Setup bios-util config... \"\n\nbios_util_config_path=\"/usr/local/fbpackages/bios-util/bios_support.json\"\nminilaketb_bios_config_path=\"/usr/local/fbpackages/bios-util/BIOS_UTIL_MINILAKETB.json\"\n\ncp -rf ${minilaketb_bios_config_path} ${bios_util_config_path}\n\necho \"done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On minilaketb, there are 2 fans connected.\n# Each fan uses same PWM input and provide one tacho output.\n# Here is the mapping between the fan and PWN/Tacho,\n# staring from the one from the edge\n# Fan 0: PWM 0, Tacho0\n# Fan 1: PWM 0, Tacho1\n\n# For each fan, setting the type, and 100% initially\nfor pwm in 0 1; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0..1\necho 0 > $PWM_DIR/tacho0_source\necho 1 > $PWM_DIR/tacho1_source\n\nt=0\nwhile [ $t -le 3 ]; do\n    echo 1 > $PWM_DIR/tacho${t}_en\n    t=$((t+1))\ndone\n", "num_lines": 65}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\ndefault_fsc_config_path=\"/etc/fsc-config.json\"\nsku_type=`cat /tmp/slot.bin`\nfull_config=1\n\necho \"Setup fan speed... \"\n\n#for i in `seq 1 1 4`\n#do\n#   if [ $(is_server_prsnt $i) == \"0\" ]; then\n#     echo \"slot$i is empty\"\n#     full_config=0\n#   fi\n#done\n\n#if [ $full_config -eq 0 ]; then\n#   echo \"Enter into transitional mode - Unexpected sku type (system is not full config)!\"\n#   /usr/local/bin/init_pwm.sh\n#   /usr/local/bin/fan-util --set 70\n#   exit 1\n#fi\n\ncase \"$sku_type\" in\n   \"0\")\n       echo \"Run FSC 4 TLs Config\"\n       cp /etc/FSC_MINILAKETB_DVT.json ${default_fsc_config_path}\n   ;;\n   *)  echo \"Unexpected sku type! Use default config\"\n       cp /etc/FSC_MINILAKETB_DVT.json ${default_fsc_config_path}\n   ;;\nesac\n\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\n\n# Check SLED in/out\nif [ $(gpio_get H5) = 1 ]; then\n   sv stop fscd\n   /usr/local/bin/fan-util --set 100\nfi\n\necho \"done.\"\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  #Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n  #get_slot_type is to get slot type to check if the slot type is server\n  if [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) == \"0\" ]]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n\nexec /usr/local/bin/gpiod $SLOTS\n", "num_lines": 13}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for minilaketb... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio interrupt monitoring for MINILAKETB... \"\n\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_2 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_4 > /dev/null 2>&1 &\n\n#Get slot type (0:TwinLakes, 1:Crace Flat, 2:Glacier Point 3:Empty Slot)\n#get_slot_type is to get slot type to check if the slot type is server\nif [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) != \"0\" ]]; then\n  sv stop ipmbd_2\nelif [ $(is_server_prsnt 1) == \"0\" ]; then\n  sv stop ipmbd_2\nfi\n", "num_lines": 46}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 7}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nget_server_sku()\n{\n   j=0\n   max_retry=3\n   server_type=0\n   for i in 1 2 3 4\n   do\n     if [[ $(is_server_prsnt $i) == \"1\" && $(get_slot_type $i) == \"0\" ]] ; then\n       tmp_server_type=3\n       j=0\n       while [ ${j} -lt ${max_retry} ]\n       do\n         # Use standard IPMI command 'get-device-id' to read product id of server board\n         output=$(/usr/bin/bic-util slot$i 0x18 0x01)\n         # if the command fails and the number of retry times reach max retry, continue to next slot\n         if [ $(echo $output | wc -c) == 45 ] ; then\n           product_id_l=`echo \"$output\" | cut -c 28-29`\n           product_id_h=`echo \"$output\" | cut -c 31-32`\n           if [[ \"$product_id_l\" == 43 && \"$product_id_h\" == 52 ]] ; then\n             #RC\n             tmp_server_type=1\n           elif [[ \"$product_id_l\" == 50 && \"$product_id_h\" == 45 ]] ; then\n             #EP\n             tmp_server_type=2\n           elif [[ \"$product_id_l\" == 39 && \"$product_id_h\" == 30 ]] ; then\n             #TL\n             tmp_server_type=0\n           else\n             #unknown\n             tmp_server_type=3\n           fi\n           break\n         fi\n         j=$(($j+1))\n       done\n     else\n       tmp_server_type=3\n     fi\n     server_type=$(($(($tmp_server_type << $((($i-1) * 2)))) + $server_type))\n   done\n\n   return $server_type\n}\n\nget_server_sku\nSERVER_TYPE=$?\necho \"Server Type: $SERVER_TYPE \"\necho \"<SERVER_TYPE[7:0] = {SLOT4, SLOT3, SLOT2, SLOT1}>\"\n\nexit $SERVER_TYPE\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nADC_VALUE=(adc12_value)\nVOL_ENABLE=(O4)\n\nget_sku()\n{\n   i=0\n   sku=0\n   while [ \"${i}\" -lt \"${#ADC_VALUE[@]}\" ]\n   do\n     SLOT_VOL=`cat /sys/devices/platform/ast_adc.0/\"${ADC_VALUE[$i]}\" | cut -d \\  -f 1 | awk '{printf (\"%.3f\\n\",$1)}'`\n     y=$(($i*2+1))\n     if [[ `awk -v a=1.9 -v b=$SLOT_VOL 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 &&  `awk -v a=$SLOT_VOL -v b=1.5 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 ]]; then\n        tmp_sku=2\n        i2cset -y $y 0x40 0x5 0xa w\n     elif [[ `awk -v a=1.4 -v b=$SLOT_VOL 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 && `awk -v a=$SLOT_VOL -v b=1.0 'BEGIN{print(a>b)?\"1\":\"0\"}'` == 1 ]]; then\n        tmp_sku=1\n        i2cset -y $y 0x70 0x5 c\n        usleep 10000\n        i2cset -y $y 0x40 0x5 0xa w\n     else\n        tmp_sku=0\n     fi\n\n     if [ $(is_server_prsnt $(($i+1))) == \"0\" ]; then\n        tmp_sku=3\n     fi\n\n     # Do not replace slotX type when it is 12V off\n     if [ -f /tmp/slot.bin ]; then\n        if [ $(gpio_get_val ${VOL_ENABLE[$i]}) == \"0\" ]; then\n           tmp_sku=$(get_slot_type $(($i+1)))\n        fi\n     fi\n\n     sku=$(($(($tmp_sku << $(($i * 2)))) + $sku))\n     i=$(($i+1))\n   done\n\n   return $sku\n}\n\nget_sku\nSLOT_TYPE=$?\necho \"Slot Type: $SLOT_TYPE \"\necho \"<SLOT_TYPE[7:0] = {SLOT4, SLOT3, SLOT2, SLOT1}>\"\n\nexit $SLOT_TYPE\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nmac=$(weutil  | grep '^Local MAC'  | cut -d' ' -f3 )\n\nif [ -n \"$mac\" ]; then\n    ifconfig eth0 hw ether $mac\n    # compare the 'ethaddr' from u-boot env\n    ethaddr=$(fw_printenv ethaddr  | cut -d'=' -f2 )\n    if [ \"$ethaddr\" != \"$mac\" ]; then\n        fw_setenv \"ethaddr\" \"$mac\"\n    fi\nfi\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          usbcons\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Creates a virtual USB serial device and starts a console\n#                    on it.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=\"FC Switcher\"\nDESC=\"FC Failover Daemon\"\n\n# source function library\n. /etc/init.d/functions\n\n. /usr/local/fbpackages/utils/ast-functions\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    if [ \"$(wedge_board_type)\" = \"LC\" ]; then\n      # Ability to prevent this from starting by editing cmdline in u-boot.\n      # Keeping this here until I get gadget switching working properly. (t4906522)\n      /usr/local/bin/watch-fc.sh > /dev/null 2>&1 &\n      echo \"$NAME.\"\n    else\n      echo 'skipping watch-fc.sh: only necessary on six-pack line cards.'\n    fi\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall watch-fc.sh\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall watch-fc.sh\n    if [ \"$(wedge_board_type)\" = \"LC\" ]; then\n      sleep 1\n      /usr/local/bin/watch-fc.sh > /dev/null 2>&1 &\n      echo \"$NAME.\"\n    else\n      echo 'skipping watch-fc.sh: only necessary on six-pack line cards.'\n    fi\n    ;;\n  status)\n    status watch-fc.sh\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 84}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Hot service is triggered, re-init process... \"\n\nfunction device_config() {\n      SLOT_N=$1\n      SLOT_B=$2\n\n      case $SLOT_N in\n          1)\n            I2C_REG=0x1e78a084\n          ;;\n          3)\n            I2C_REG=0x1e78a184\n          ;;\n      esac\n\n      # Delete devices on I2C bus 1 and bus 5 if there are device cards\n      # EEPROM, 0xA2\n      i2c_remove_device $SLOT_B 0x51\n      # Inlet temp sensor, 0x9A\n      i2c_remove_device $SLOT_B 0x4d\n      # outlet temp sensor, 0x9C\n      i2c_remove_device $SLOT_B 0x4e\n      # I2C mux, 0xE2\n      i2c_remove_device $SLOT_B 0x71\n      # I2C GPIO, 0x40\n      i2c_remove_device $SLOT_B 0x20\n      # Voltage sensor, 0x80\n      i2c_remove_device $SLOT_B 0x40\n\n      #if [ $(is_server_prsnt $(($SLOT_N+1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N+1))) == \"0\" ] ; then\n        if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] ; then\n\n           devmem $I2C_REG w 0xFFF77304\n\n           if [ $(get_slot_type $SLOT_N) == \"2\" ]; then\n              # I2C mux, 0xE2\n              i2c_add_device $SLOT_B 0x71 pca9551\n              # I2C GPIO, 0x40\n              i2c_add_device $SLOT_B 0x20 pca9551\n           fi\n\n           # EEPROM, 0xA2\n           i2c_add_device $SLOT_B 0x51 24c128\n           # Inlet temp sensor, 0x9A\n           i2c_add_device $SLOT_B 0x4d tmp75\n           # outlet temp sensor, 0x9C\n           i2c_add_device $SLOT_B 0x4e tmp75\n           # Voltage sensor, 0x80\n           i2c_add_device $SLOT_B 0x40 ina230\n        else\n\n           devmem $I2C_REG w 0xFFF5E700\n        fi\n      #fi\n}\n\nfunction set_sysconfig() {\n      SLOT_N=$1\n      SLOT_B=$2\n\n      case $SLOT_N in\n          1)\n            device_config $SLOT_N $SLOT_B\n          ;;\n          2)\n            # Detect invalid configuration and then power-down the 12V for that slot(e.g. GP/CF plugged in to slot#2/slot#4)\n            if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] ; then\n                  gpio_set O5 0\n                  logger -p user.crit \"Invalid configuration on SLOT$SLOT_N\"\n\n                  if [ $(is_server_prsnt $(($SLOT_N-1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N-1))) != \"0\" ] ; then\n                     gpio_set O4 0\n                  fi\n            fi\n          ;;\n          3)\n            device_config $SLOT_N $SLOT_B\n          ;;\n          4)\n            # Detect invalid configuration and then power-down the 12V for that slot(e.g. GP/CF plugged in to slot#2/slot#4)\n            if [ $(is_server_prsnt $SLOT_N) == \"1\" ] && [ $(get_slot_type $SLOT_N) != \"0\" ] ; then\n                  gpio_set O7 0\n                  logger -p user.crit \"Invalid configuration on SLOT$SLOT_N\"\n                  if [ $(is_server_prsnt $(($SLOT_N-1))) == \"1\" ] && [ $(get_slot_type $(($SLOT_N-1))) != \"0\" ] ; then\n                     gpio_set O6 0\n                  fi\n            fi\n          ;;\n      esac\n}\n\nSLOT=$1\nOPTION=$2\n\ncase $SLOT in\n    slot1)\n      SLOT_NUM=1\n      PE_BUFF_OE_0=B4\n      PE_BUFF_OE_1=B5\n      ;;\n    slot2)\n      SLOT_NUM=2\n      PE_BUFF_OE_0=B4\n      PE_BUFF_OE_1=B5\n      ;;\n    slot3)\n      SLOT_NUM=3\n      PE_BUFF_OE_0=B6\n      PE_BUFF_OE_1=B7\n      ;;\n    slot4)\n      SLOT_NUM=4\n      PE_BUFF_OE_0=B6\n      PE_BUFF_OE_1=B7\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {slot1|slot2|slot3|slot4} {start}\"\n      exit 1\n      ;;\nesac\n\nSLOT_BUS=$(get_slot_bus $SLOT_NUM)\n\ncase $OPTION in\n    start)\n      if [ $(is_server_prsnt $SLOT_NUM) == 0 ]; then\n         exit 1\n      fi\n      echo \"start to re-init for slot$SLOT_NUM insertion\"\n\n      # Delay 1 second for slot_type voltage ready\n      sleep 2\n\n      # System Configuration\n      echo \"reset system configuration for $SLOT $OPTION\"\n      /etc/init.d/setup-platform.sh\n\n      # Remove Service for new device/server\n      # Sensor\n      sv stop sensord\n      rm -rf /tmp/cache_store/$SLOT*\n      set_sysconfig $SLOT_NUM $SLOT_BUS\n\n      # GPIO\n      sv stop gpiod\n\n      # IPMB\n      sv stop ipmbd_$SLOT_BUS\n\n      # Console\n      sv stop mTerm$SLOT_NUM\n\n      # Delay to wait for sv stop\n      sleep 3\n\n      # Restart Service for new device/server\n      echo \"restart mTerm for $SLOT $OPTION\"\n      if [[ $(is_server_prsnt $SLOT_NUM) == \"1\" && $(get_slot_type $SLOT_NUM) == \"0\" ]] ; then\n         sv start mTerm$SLOT_NUM\n      fi\n\n      echo \"restart ipmbd for $SLOT $OPTION\"\n      if [[ $(is_server_prsnt $SLOT_NUM) == \"1\" && $(get_slot_type $SLOT_NUM) == \"0\" ]]; then\n         sv start ipmbd_$SLOT_BUS\n         /usr/local/bin/bic-cached $SLOT_NUM > /dev/null 2>&1 &\n      fi\n\n      echo \"restart gpiod for $SLOT $OPTION\"\n      sv start gpiod\n\n      echo \"restart sensord for $SLOT $OPTION\"\n      sv start sensord \n\n      echo \"restart rest-api for $SLOT $OPTION\"\n      ps | grep -v 'grep' | grep 'rest.py' |awk '{print $1}'| xargs kill\n      sh /usr/local/fbpackages/rest-api/setup-rest-api.sh\n\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {slot1|slot2|slot3|slot4} {start}\"\n      exit 1\n      ;;\nesac\n\necho \"done.\"\n", "num_lines": 193}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nLPS_PATH=/mnt/data/power/por/last_state\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <slot#> <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current 1S server power status\"\n    echo\n    echo \"  on: Power on 1S server if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if 1S server has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off 1S server ungracefully\"\n    echo\n    echo\n}\n\ndo_status() {\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo  \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is not server\"\n      return 0\n    fi\n\n    echo -n \"1S Server power for slot#$slot is \"\n    if [ $(minilaketb_is_server_on $slot) -eq 1 ] ; then\n        echo \"on\"\n    else\n        echo \"off\"\n    fi\n    return 0\n}\n\ndo_on() {\n\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is not server\"\n      return 0\n    fi\n\n    local force opt\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n\n        esac\n    done\n    echo -n \"Power on slot#$slot server ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if 1S Server is on or not\n        if [ $(minilaketb_is_server_on $slot) -eq 1 ]; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # TODO: State the power state change\n    echo \"on $(date +%s)\" > $LPS_PATH\n\n    # disable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 7c) 21\n\n    # first make sure, GPIO is high\n    gpio_set $gpio 1\n    # generate the power on pulse\n    gpio_set $gpio 0\n    sleep 1\n    gpio_set $gpio 1\n    sleep 1\n    # Turn on the power LED\n    /usr/local/bin/power_led.sh $slot on\n\n    # enable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 70) 21\n\n    echo \" Done\"\n    return 0\n}\n\ndo_off() {\n    if [ $(is_server_prsnt $slot) == \"0\" ]; then\n      echo \"The given slot is Empty\"\n      return 0\n    fi\n\n    if [[ $(get_slot_type $slot) == \"1\" || $(get_slot_type $slot) == \"2\" ]]; then\n      echo \"The given slot type is no server\"\n      return 0\n    fi\n\n    echo -n \"Power off slot#$slot server ...\"\n\n    #TODO: State the power state change\n    echo \"off $(date +%s)\" > $LPS_PATH\n\n    # disable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 7c) 21\n\n    # first make sure, GPIO is high\n    gpio_set $gpio 1\n    sleep 1\n    gpio_set $gpio 0\n    sleep 5\n    gpio_set $gpio 1\n    # Turn off the power LED\n    /usr/local/bin/power_led.sh $slot off\n\n    # enable GPIOD pass-though function\n    devmem_set_bit $(scu_addr 70) 21\n\n    echo \" Done\"\n    return 0\n}\n\n# Slot1: GPIOD1(25), Slot2: GPIOD3(27), Slot3: GPIOD5(29), Slot4: GPIOD7(31)\nslot=$1\n\ncase $slot in\n  1)\n    gpio=D1\n    ;;\n  2)\n    gpio=D3\n    ;;\n  3)\n    gpio=D5\n    ;;\n  4)\n    gpio=D7\n    ;;\n  *)\n    gpio=D1\n    ;;\nesac\n\ncommand=\"$2\"\nshift\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 200}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Function to set the less significant hex digit\ndisplay_lower() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOG[0...3].\n    # For GPIO bank G, SCU84[0..3] must be 0.\n    devmem_clear_bit $(scu_addr 84) 0\n    devmem_clear_bit $(scu_addr 84) 1\n    devmem_clear_bit $(scu_addr 84) 2\n    devmem_clear_bit $(scu_addr 84) 3\n\n    # Now set the GPIOs to the right binary values\n    gpio_set 48 $bit0\n    gpio_set 49 $bit1\n    gpio_set 50 $bit2\n    gpio_set 51 $bit3\n}\n\n# Function to set the more significant hex digit\ndisplay_upper() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    # Set the pins to the correct operating mode.\n    # The relevant pins are GPIOP[4...7].\n\n    gpio_set 124 $bit0\n    gpio_set 125 $bit1\n    gpio_set 126 $bit2\n    gpio_set 127 $bit3\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\n# Get upper/lower decimal values\nLOWER_DEC_VALUE=$(expr $DEC_VALUE % 16)\nUPPER_DEC_VALUE=$(expr $DEC_VALUE / 16)\n\n# Display the results\ndisplay_lower $LOWER_DEC_VALUE\ndisplay_upper $UPPER_DEC_VALUE\n\n", "num_lines": 97}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config()\n{\n\n  TO_PWR_ON=-1\n\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/slot${1}_por_cfg\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    POR=`cat ${KEYDIR}/slot${1}_por_cfg`\n\n    # Case ON\n    if [ $POR == \"on\" ]; then\n      TO_PWR_ON=1;\n\n    # Case OFF\n    elif [ $POR == \"off\" ]; then\n      TO_PWR_ON=0;\n\n    # Case LPS\n    elif [ $POR == \"lps\" ]; then\n\n      # Check if the file/key doesn't exist\n      if [ ! -f \"${KEYDIR}/pwr_server${1}_last_state\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        LS=`cat ${KEYDIR}/pwr_server${1}_last_state`\n        if [ $LS == \"on\" ]; then\n          TO_PWR_ON=1;\n        elif [ $LS == \"off\" ]; then\n          TO_PWR_ON=0;\n        fi\n      fi\n    fi\n  fi\n}\n\n# Sync BMC's date with one of the four servers\nsync_date()\n{\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    for i in 1\n    do\n      if [[ $(is_server_prsnt $i) == \"1\" && $(get_slot_type $i) == \"0\" ]] ; then\n        # Use standard IPMI command 'get-sel-time' to read RTC time\n        output=$(/usr/local/bin/me-util slot$i 0x28 0x48)\n        # if the command fails, continue to next slot\n        [ $(echo $output | wc -c) != 12 ] && continue\n        echo Syncing up BMC time with server$i...\n        date -s @$((16#$(echo $output | awk '{print $4$3$2$1}')))\n        test -x /etc/init.d/hwclock.sh && /etc/init.d/hwclock.sh stop\n        break\n      fi\n    done\n  fi\n}\n\nsync_date\n\n# Check whether it is fresh power on reset\nif [ $(is_bmc_por) -eq 1 ]; then\n\n  # Disable clearing of PWM block on WDT SoC Reset\n  devmem_clear_bit $(scu_addr 9c) 17\n\n  check_por_config 1\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) == \"0\" ] ; then\n    power-util slot1 on\n  fi\n\nfi\n", "num_lines": 107}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <slot#> <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 2 ]; then\n    usage $0\nfi\n\n# Slot#1: GPIOM0(96),Slot#2: GPIOM1(97),Slot#3: GPIOM2(98),Slot#4: GPIOM3(99)\nif [ $1 = \"1\" ]; then\n    gpio=M0\nelif [ $1 = \"2\" ]; then\n    gpio=M1\n#elif [ $1 = \"3\" ]; then\n#    gpio=M2\n#elif [ $1 = \"4\" ]; then\n#    gpio=M3\nelse\n    usage $0\nfi\n\n\nif [ $2 = \"on\" ]; then\n    val=1\nelif [ $2 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set $gpio $val\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\n#TODO: Add logic to control mux based on front panel switch\necho -n \"Set USB Mux to given slot ... \"\n\n# USB_MUX_SEL signals: GPIOE4(36), GPIOE5(37)\nslot=$1\n\ncase $slot in\n  1)\n    gpio_set E4 0\n    gpio_set E5 0\n    gpio_set AB3 0\n    ;;\n  2)\n    gpio_set E4 1\n    gpio_set E5 0\n    gpio_set AB3 0\n    ;;\n  3)\n    gpio_set E4 0\n    gpio_set E5 1\n    gpio_set AB3 0\n    ;;\n  4)\n    gpio_set E4 1\n    gpio_set E5 1\n    gpio_set AB3 0\n    ;;\n  *)\n    gpio_set AB3 1\n    ;;\nesac\n\necho \"Done\"\n", "num_lines": 56}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Set up GPIO pins.....\"\n\n# Set up to read the board revision pins, Y0, Y1, Y2\ndevmem_clear_scu70_bit 19\ndevmem_clear_bit $(scu_addr a4) 8\ndevmem_clear_bit $(scu_addr a4) 9\ndevmem_clear_bit $(scu_addr a4) 10\n\ngpio_export Y0\ngpio_export Y1\ngpio_export Y2\n\n# SLOT1_PRSNT_N, GPIOAA0 (208)\n# GPIOAA0(208): SCU90[31], SCUA4[24] shall be 0\ndevmem_clear_bit $(scu_addr 90) 31\ndevmem_clear_bit $(scu_addr a4) 24\n\ngpio_export AA0\n\n# SLOT2_PRSNT_N, GPIOAA1 (209)\n# GPIOAA1(209): SCU90[31], SCUA4[25] shall be 0\ndevmem_clear_bit $(scu_addr a4) 25\n#gpio_export AA1 no need in XG1\n\n# SLOT3_PRSNT_N, GPIOAA2 (210)\n# GPIOAA2(210): SCU90[31], SCUA4[26] shall be 0\ndevmem_clear_bit $(scu_addr a4) 26\n# T6A change to output gpio, default high\ngpio_set AA2 1\n\n# SLOT4_PRSNT_N, GPIOAA3 (211)\n# GPIOAA3(211): SCU90[6], SCUA4[27] shall be 0\ndevmem_clear_bit $(scu_addr a4) 27\n#gpio_export AA3 no need in XG1\n\n# BMC_PWR_BTN_IN_N, uServer power button in, on GPIO D0(24)\ngpio_export D0\n\n# PWR_SLOT1_BTN_N, 1S Server power out, on GPIO D1\n# GPIOD1(25): SCU90[1], SCU8C[8], SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8c) 8\ndevmem_clear_scu70_bit 21\ngpio_set D1 1\n\n# PWR_SLOT2_BTN_N, 1S Server power out, on GPIO D3\n# Make sure the Power Control Pin is Set properly\n# GPIOD3(27): SCU90[1], SCU8C[9], SCU[21] shall be 0\n\ndevmem_clear_bit $(scu_addr 8c) 9\n\ngpio_set D3 1\n\n# PWR_SLOT3_BTN_N, 1S Server power out, on GPIO D5\n# GPIOD5(29): SCU90[1], SCU8C[10], and SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 8c) 10\n\ngpio_set D5 1\n\n# PWR_SLOT4_BTN_N, 1S Server power out, on GPIO D7\n# GPIOD7(31): SCU90[1], SCU8C[11], and SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 8c) 11\n\ngpio_set D7 1\n\n# SMB_SLOT1_NIC_ALERT_N, alert for 1S Server NIC I2C, GPIO B0\ngpio_export B0\n# SMB_SLOT2_NIC_ALERT_N, alert for 1S Server NIC I2C, GPIO B1\ngpio_export B1\n# SMB_SLOT3_NIC_ALERT_N, alert for 1S Server NIC I2C, GPIO B2\ngpio_export B2\n# SMB_SLOT4_NIC_ALERT_N, alert for 1S Server NIC I2C, GPIO B3\ngpio_export B3\n\n# Enable P3V3: GPIOAB1(217)\n# To use GPIOAB1 (217), SCU90[31]=0, (SCUA8[1] or SCU94[1:0]) must be 0\ndevmem_clear_bit $(scu_addr a8) 1\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\n\ngpio_set AB1 1\n\n# BMC_SELF_HW_RST: GPIOAB2(218)\n# To use GPIOAB2 (218), SCUA8[2] must be 0\ndevmem_clear_bit $(scu_addr a8) 2\ngpio_set AB2 0\n\n# VGA Mux\n# To use GPIOJ2 (74), SCU84[10] must be 0\ndevmem_clear_bit $(scu_addr 84) 10\n# To use GPIOJ3 (75), SCU84[11] must be 0\ndevmem_clear_bit $(scu_addr 84) 11\n\ngpio_export J2\ngpio_export J3\n\n#========================================================================================================#\n# Setup GPIOs to Mux Enable: GPIOAB3(219), Channel Select: GPIOE4(36), GPIOE5(37)\n\n# To use GPIOAB3 (219), SCUA8[3] must be 0\ndevmem_clear_bit $(scu_addr a8) 3\n\n#To use GPIOE4 (36), SCU80[20], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 20\ndevmem_clear_bit $(scu_addr 8C) 14\ndevmem_clear_scu70_bit 22\n\n# To use GPIOE5 (37), SCU80[21], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 21\n\ngpio_export AB3\ngpio_export E4\ngpio_export E5\n#========================================================================================================#\n\n# USB_OC_N, resettable fuse tripped, GPIO Q6\ndevmem_clear_bit $(scu_addr 2c) 1\n\ngpio_export Q6\n\n# XG1 : GPIOQ7 : COME_BMC_GPI0\ngpio_set Q7 1\n\n\n# DEBUG UART Controls\n# 4 signals: DEBUG_UART_SEL_0/1/2 and DEBUG_UART_RX_SEL_N\n# GPIOE0 (32), GPIOE1 (33), GPIOE2 (34) and GPIOE3 (35)\n\n# To enable GPIOE0, SCU80[16], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 16\ndevmem_clear_bit $(scu_addr 8C) 12\ndevmem_clear_scu70_bit 22\n\ngpio_export E0\n\n# To enable GPIOE1, SCU80[17], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 17\n\ngpio_export E1\n\n# To enable GPIOE2, SCU80[18], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 18\ndevmem_clear_bit $(scu_addr 8C) 13\n\ngpio_export E2\n\n# To enable GPIOE3, SCU80[19], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 19\n\ngpio_export E3\n\n# Enable GPIOY3: BoardId(Test system)\ndevmem_clear_bit $(scu_addr a4) 11\ndevmem_clear_bit $(scu_addr 94) 11\n\ngpio_export Y3\n\n# Power LED for Slot#2:\n# To use GPIOM0 (96), SCU90[4], SCU90[5], and SCU84[24] must be 0\ndevmem_clear_bit $(scu_addr 90) 4\ndevmem_clear_bit $(scu_addr 90) 5\ndevmem_clear_bit $(scu_addr 84) 24\n\ngpio_set M0 1\n\n# Power LED for Slot#1:\n# To use GPIOM1 (97), SCU90[4], SCU90[5], and SCU84[25] must be 0\ndevmem_clear_bit $(scu_addr 84) 25\n\n# XG1 : GPIOM1 : BATLOW_BMC\ngpio_set M1 0\n\n# Power LED for Slot#4:\n# To use GPIOM2 (98), SCU90[4], SCU90[5], and SCU84[26] must be 0\ndevmem_clear_bit $(scu_addr 84) 26\n\n#gpio_set M2 1\ngpio_export M2\n\n# Power LED for Slot#3:\n# To use GPIOM3 (99), SCU90[4], SCU90[5], and SCU84[27] must be 0\ndevmem_clear_bit $(scu_addr 84) 27\n\n#gpio_set M3 1\ngpio_export M3\n\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\ndevmem_clear_bit $(scu_addr 84) 29\ngpio_export M5\n\ndevmem_clear_bit $(scu_addr 84) 30\ngpio_export M6\n\n# T6A : To use GPIOM7 as P12V_STBY_MB_BMC_PWROK , default output high.\ngpio_set M7 1\n\n# Identify LED for Slot#2:\n# To use GPIOF0 (40), SCU80[24], SCU90[30] must be 0\ndevmem_clear_bit $(scu_addr 80) 24\ndevmem_clear_bit $(scu_addr 90) 30\n\ngpio_set F0 1\n\n# Identify LED for Slot#1:\n# To use GPIOF1 (41), SCU80[25], SCU90[30], must be 0\ndevmem_clear_bit $(scu_addr 80) 25\ngpio_export F1\n\n# Identify LED for Slot#4:\n# To use GPIOF2 (42), SCU80[26], SCU90[30],  must be 0\ndevmem_clear_bit $(scu_addr 80) 26\ngpio_set F2 1\n\n# Identify LED for Slot#3:\n# To use GPIOF3 (43), SCU80[27], SCU90[30], must be 0\ndevmem_clear_bit $(scu_addr 80) 27\ngpio_set F3 1\n\n# Front Panel Hand Switch GPIO setup\n# HAND_SW_ID1: GPIOAA4(212)\n# To use GPIOAA4, SCUA4[28] must be 0\ndevmem_clear_bit $(scu_addr a4) 28\n\ngpio_export AA4\n\n# HAND_SW_ID2: GPIOAA5(213)\n# To use GPIOAA5,  SCUA4[29] must be 0\ndevmem_clear_bit $(scu_addr a4) 29\n\ngpio_export AA5\n\n# HAND_SW_ID4: GPIOAA6(214)\n# To use GPIOAA6, SCUA4[30] must be 0\ndevmem_clear_bit $(scu_addr a4) 30\n\ngpio_export AA6\n\n# HAND_SW_ID8: GPIOAA7(215)\n# To use GPIOAA7, SCUA4[31] must be 0\ndevmem_clear_bit $(scu_addr a4) 31\n\ngpio_export AA7\n\n\n# SLOT1_LED: GPIOAC0(224)\n# gpio_export AC0\n\n# SLOT2_LED: GPIOAC1(225)\n# gpio_export AC1\n\n# SLOT3_LED: GPIOAC2(226)\n# gpio_export AC2\n\n# SLOT4_LED: GPIOAC3(227)\n# gpio_export AC3\n\n# SLED_SEATED_N: GPIOAC7(231)\n# gpio_export AC7\n\n# LED POST CODES: 8 GPIO signals\n\n# LED_POSTCODE_0: GPIOG0 (48)\n# To use GPIOG0, SCU84[0] must be 0\ndevmem_clear_bit $(scu_addr 84) 0\n\ngpio_set G0 0\n\n# LED_POSTCODE_1: GPIOG1 (49)\n# To use GPIOG1, SCU84[1] must be 0\ndevmem_clear_bit $(scu_addr 84) 1\n\ngpio_set G1 0\n\n# LED_POSTCODE_2: GPIOG2 (50)\n# To use GPIOG2, SCU84[2] must be 0\ndevmem_clear_bit $(scu_addr 84) 2\n\ngpio_set G2 0\n\n# LED_POSTCODE_3: GPIOG3 (51)\n# To use GPIOG3, SCU84[3] must be 0\ndevmem_clear_bit $(scu_addr 84) 3\n\ngpio_set G3 0\n\n# LED_POSTCODE_4: GPIOP4 (124)\ngpio_set P4 0\n\n# LED_POSTCODE_5: GPIOP5 (125)\ngpio_set P5 0\n\n# LED_POSTCODE_6: GPIOP6 (126)\ngpio_set P6 0\n\n# LED_POSTCODE_7: GPIOP7 (127)\ngpio_set P7 0\n\n# BMC_READY_N: GPIOA0 (0)\n# To use GPIOA0, SCU80[0] must be 0\ndevmem_clear_bit $(scu_addr 80) 0\ngpio_set A0 0\n\n# BMC_RST_BTN_IN_N: GPIOAB0 (216)\n# To use GPIOS0, SCU90[31], (SCUA8[0] or SCU94[1:0]) must be 0\ngpio_export AB0\n\n# RESET for all Slots\n# RST_SLOT1_SYS_RESET_N: GPIOS0 (144)\n# To use GPIOS0, SCU8C[0] must be 0\ndevmem_clear_bit $(scu_addr 8c) 0\n\ngpio_set S0 1\n\n# RST_SLOT2_SYS_RESET_N: GPIOS1 (145)\n# To use GPIOS1, SCU8C[0] must be 0\ngpio_set S1 1\n\n# RST_SLOT3_SYS_RESET_N: GPIOS2 (146)\n# To use GPIOS2, SCU8C[0] must be 0\ngpio_set S2 1\n\n# RST_SLOT4_SYS_RESET_N: GPIOS3 (147)\n# To use GPIOS3, SCU8C[0] must be 0\ngpio_set S3 1\n\n# DBG_UART_SEL_N : GPIOO4 (116)\n# To use GPIOO4, SCU88[12] must be 0\ndevmem_clear_bit $(scu_addr 88) 12\ngpio_get O4\n\n# XG1 P12V_STBY_MB_EN_N is Z0\ngpio_export Z0\n\n# P12V_STBY_SLOT2_EN: GPIOO5 (117)\n# To use GPIOO5, SCU88[13] must be 0\ndevmem_clear_bit $(scu_addr 88) 13\n\ngpio_export O5\n\n# P12V_STBY_SLOT3_EN: GPIOO6 (118)\n# To use GPIOO6, SCU88[13] must be 0\ndevmem_clear_bit $(scu_addr 88) 14\n\ngpio_export O6\n\n# P12V_STBY_SLOT4_EN: GPIOO7 (119)\n# To use GPIOO7, SCU88[15] must be 0\ndevmem_clear_bit $(scu_addr 88) 15\n\ngpio_export O7\n\n# SLOT1_EJECTOR_LATCH_DETECT_N: GPIOP0 (120)\n# To use GPIOP0, SCU88[16] must be 0\ndevmem_clear_bit $(scu_addr 88) 16\ngpio_export P0\n\n# SLOT2_EJECTOR_LATCH_DETECT_N: GPIOP1 (121)\n# To use GPIOP1, SCU88[17] must be 0\ndevmem_clear_bit $(scu_addr 88) 17\ngpio_export P1\n\n# SLOT3_EJECTOR_LATCH_DETECT_N: GPIOP2 (122)\n# To use GPIOP2, SCU88[18] must be 0\ndevmem_clear_bit $(scu_addr 88) 18\ngpio_export P2\n\n# SLOT4_EJECTOR_LATCH_DETECT_N: GPIOP3 (123)\n# To use GPIOP3, SCU88[19] must be 0\ndevmem_clear_bit $(scu_addr 88) 19\ngpio_export P3\n\n# FAN_LATCH_DETECT : GPIOH5 (61)\n# To use GPIOH5, SCU94[7] and SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 90) 7\ndevmem_clear_bit $(scu_addr 94) 7\ngpio_export H5\n\n# Enable GPIO pins: I2C_SLOTx_ALERT_N pins for BIC firmware update\ndevmem_clear_bit $(scu_addr 88) 2\ngpio_export N2\ndevmem_clear_bit $(scu_addr 88) 3\ngpio_export N3\ndevmem_clear_bit $(scu_addr 88) 4\ngpio_export N4\ndevmem_clear_bit $(scu_addr 88) 5\ngpio_export N5\n\n# To use GPIOI0~GPIOI7, SCU70[13:12] must be 0\ndevmem_clear_scu70_bit 12\ndevmem_clear_scu70_bit 13\n\n# SLOT1_POWER_EN: GPIOI0 (64)\ngpio_export I0\n# SLOT2_POWER_EN: GPIOI1 (65)\ngpio_export I1\n# SLOT3_POWER_EN: GPIOI2 (66)\ngpio_export I2\n# SLOT4_POWER_EN: GPIOI3 (67)\ngpio_export I3\n\n# Set SLOT throttle pin\n# BMC_THROTTLE_SLOT1_N: GPIOI4 (68)\ngpio_set I4 1\n# BMC_THROTTLE_SLOT2_N: GPIOI5 (69)\ngpio_set I5 1\n# BMC_THROTTLE_SLOT3_N: GPIOI6 (70)\ngpio_set I6 1\n# BMC_THROTTLE_SLOT4_N: GPIOI7 (71)\ngpio_set I7 1\n\n# Set FAN disable pin\n# DISABLE_FAN_N: GPIOM4 (100)\ngpio_set M4 1\n\n# Set FAST PROCHOT pin (Default Enable)\n# FAST_PROCHOT_EN: GPIOR4 (140)\ngpio_set R4 1\n\n# PE_BUFF_OE_0_N: GPIOB4 (12)\n# To use GPIOB4, SCU70[23] must be 0\ndevmem_clear_scu70_bit 23\ngpio_export B4\n\n# PE_BUFF_OE_1_N: GPIOB5 (13)\n#To use GPIOB5, SCU80[13] must be 0\ndevmem_clear_bit $(scu_addr 80) 13\ngpio_export B5\n\n# PE_BUFF_OE_2_N: GPIOB6 (14)\ndevmem_clear_bit $(scu_addr 80) 14\ngpio_export B6\n\n# PE_BUFF_OE_3_N: GPIOB7 (15)\ngpio_export B7\n\n# CLK_BUFF1_PWR_EN_N: GPIOJ0 (72)\n# To use GPIOJ2 (72), SCU84[8] must be 0\ndevmem_clear_bit $(scu_addr 84) 8\ngpio_export J0\n\n# CLK_BUFF2_PWR_EN_N: GPIOJ1 (73)\n# To use GPIOJ3 (73), SCU84[9] must be 0\ndevmem_clear_bit $(scu_addr 84) 9\ngpio_export J1\n\n# Disable PWM reset during external reset\ndevmem_clear_bit $(scu_addr 9c) 17\n# Disable PWM reset during WDT1 reset\ndevmem_clear_bit 0x1e78501c 17\n\n# Set debounce timer #1 value to 0x179A7B0 ~= 2s\n$DEVMEM 0x1e780050 32 0x179A7B0\n\n# Select debounce timer #1 for GPIOZ0~GPIOZ3 and GPIOAA0~GPIOAA3\n# $DEVMEM 0x1e780194 32 0xF0F00\n\n# Set debounce timer #2 value to 0xF1B3 ~= 5ms\n$DEVMEM 0x1e780054 32 0xF1B3\n\n# Select debounce timer #2 for GPIOP0~GPIOP3\n$DEVMEM 0x1e780100 32 0xF000000\n\n# enable I2C ctrl reg (SCUA4),\ndevmem_set_bit $(scu_addr A4) 12 #SCL1 en\ndevmem_set_bit $(scu_addr A4) 13 #SDA1\ndevmem_set_bit $(scu_addr A4) 14 #SCL2\ndevmem_set_bit $(scu_addr A4) 15 #SDA2\n", "num_lines": 512}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get slot type\nsh /usr/local/bin/check_slot_type.sh > /dev/NULL\nSLOT_TYPE=$?\necho $SLOT_TYPE > /tmp/slot.bin\n\n\n# do init power\necho \"[ minilakeTB ] : Start setup PCA9555\"\ndo_init_power=0;\n\nret=$(i2cget -y 12 0x20  0x02 w)\nif [ \"$ret\" != \"0xd7fd\" ]; then\n    do_init_power=1;\nfi\n\nret=$(i2cget -y 12 0x20  0x06 w)\nif [ \"$ret\" != \"0xd18d\" ]; then\n    do_init_power=1;\nfi\n\nif [ \"$do_init_power\" -eq \"1\" ]; then\n    # set 0x02 output register, 0xFD port0, 0xD7 port1\n    i2cset -y 12 0x20  0x02 0xFD 0xD7 i\n    # set 0x06 dir register, 0xFD port0, 0xD3 port1\n    i2cset -y 12 0x20  0x06 0xFD 0xD3 i\n    usleep 10000;\n\n    # set P0V9 as high\n    i2cset -y 12 0x20  0x06 0xDD 0xD3 i\n    usleep 10000;\n\n    # set P1V8 as high\n    i2cset -y 12 0x20  0x06 0x9D 0xD3 i\n    usleep 10000;\n\n    # set OSC_OE as high\n    i2cset -y 12 0x20  0x06 0x9D 0xD1 i\n    usleep 10000;\n\n    # set RST_PLT_MEZZ_N as high\n    i2cset -y 12 0x20  0x06 0x8D 0xD1 i\n    usleep 10000;\n\n    echo \"[ minilakeTB ] : setup PCA9555 finish !!!\"\nelse\n    echo \"[ minilakeTB ] : no need to setup PCA9555 !!!\"\nfi\n\n\n# get MAC from EEPROM and set to BMC.\nSetMAC() {\n    rmmod at24\n    i2cset -y 8 0x51 0x18 0x10 || return 1;\n\n    MAC=$(i2cget -y 8 0x51)|| return 1;\n    MAC=$MAC':'$(i2cget -y 8 0x51)|| return 1;\n    MAC=$MAC':'$(i2cget -y 8 0x51)|| return 1;\n    MAC=$MAC':'$(i2cget -y 8 0x51)|| return 1;\n    MAC=$MAC':'$(i2cget -y 8 0x51)|| return 1;\n    MAC=$MAC':'$(i2cget -y 8 0x51)|| return 1;\n\n    MAC=$(echo $MAC | sed 's/0x//g');\n    #ifdown eth0\n    ifconfig eth0 hw ether $MAC\n    #ifup eth0\n    modprobe at24\n    return 0\n}\n\nretry=5;\nwhile [[ $retry -gt 0 ]]; do\n    SetMAC\n    if [ $? -eq 0 ]; then\n        echo setup MAC finish !\n        exit 0\n    else\n        retry=$(($retry-1))\n    fi\ndone\n# Finish MAC setting\n", "num_lines": 101}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get server type\nsh /usr/local/bin/check_server_type.sh > /dev/NULL\nSERVER_TYPE=$?\necho $SERVER_TYPE > /tmp/server_type.bin\n\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# This file contains definitions for the different system configurations. \n# We should probably move some more of the definitions to this file at some point.\n\necho -n \"Setup System Configuration ..\"\n\n. /usr/local/fbpackages/utils/ast-functions\n\nSPB_REV=$(($(($(($(gpio_get_val Y2) + $(gpio_get_val Y1))) * 2)) + $(gpio_get_val Y0)))\necho $SPB_REV > /tmp/spb_rev\n\nif [ $(is_server_prsnt 2) == \"1\" ] ; then\n   if [ $(get_slot_type 2) != \"0\" ] ; then\n      gpio_set O5 0\n      logger -p user.crit \"Invalid configuration on SLOT2\"\n      if [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) != \"0\" ] ; then\n         gpio_set O4 0\n      fi\n   fi\nelse\n   if [ $(is_server_prsnt 1) == \"1\" ] && [ $(get_slot_type 1) != \"0\" ] ; then\n      gpio_set O4 0\n   fi\nfi\n\nif [ $(is_server_prsnt 4) == \"1\" ] ; then\n   if [ $(get_slot_type 4) != \"0\" ] ; then\n      gpio_set O7 0\n      logger -p user.crit \"Invalid configuration on SLOT4\"\n      if [ $(is_server_prsnt 3) == \"1\" ] && [ $(get_slot_type 3) != \"0\" ] ; then\n         gpio_set O6 0\n      fi\n   fi\nelse\n   if [ $(is_server_prsnt 3) == \"1\" ] && [ $(get_slot_type 3) != \"0\" ] ; then\n      gpio_set O6 0\n   fi\nfi\n\n# Enable buffer to pass through signal by system configuration\nif [ $(is_server_prsnt 1) == \"1\" ] && [ $(is_server_prsnt 2) == \"1\" ] ; then\n   if [ $(get_slot_type 1) != \"0\" ] && [ $(get_slot_type 2) == \"0\" ] ; then\n      gpio_set J0 0\n      gpio_set B4 0\n      gpio_set B5 0\n   else\n      gpio_set B4 1\n      gpio_set B5 1\n   fi\nelse\n   gpio_set B4 1\n   gpio_set B5 1\nfi\n\nif [ $(is_server_prsnt 3) == \"1\" ] && [ $(is_server_prsnt 4) == \"1\" ] ; then\n   if [ $(get_slot_type 3) != \"0\" ] && [ $(get_slot_type 4) == \"0\" ] ; then\n      gpio_set J1 0\n      gpio_set B6 0\n      gpio_set B7 0\n   else\n      gpio_set B6 1\n      gpio_set B7 1\n   fi\nelse\n   gpio_set B6 1\n   gpio_set B7 1\nfi\n\n# create devices on I2C bus 1 and bus 5\n# Bus1,  Glacier Point\nif [[ $(is_server_prsnt 1) == \"1\" && $(get_slot_type 1) != \"0\" ]]; then\n\n   devmem 0x1e78a084 w 0xFFF77304\n\n   if [ $(get_slot_type 1) == \"2\" ]; then\n      # I2C mux, 0xE2\n      echo pca9551 0x71 > /sys/class/i2c-dev/i2c-1/device/new_device\n      # I2C GPIO, 0x40\n      echo pca9551 0x20 > /sys/class/i2c-dev/i2c-1/device/new_device\n   fi\n\n   # EEPROM, 0xA2\n   echo 24c128 0x51 > /sys/class/i2c-dev/i2c-1/device/new_device\n   # Inlet temp sensor, 0x9A\n   echo tmp75 0x4d > /sys/class/i2c-dev/i2c-1/device/new_device\n   # outlet temp sensor, 0x9C\n   echo tmp75 0x4e > /sys/class/i2c-dev/i2c-1/device/new_device\n   # Voltage sensor, 0x80\n   echo ina230 0x40 > /sys/class/i2c-dev/i2c-1/device/new_device\nelse\n   devmem 0x1e78a084 w 0xFFF5E700\nfi\n\n# Bus5,  Glacier Point\nif [[ $(is_server_prsnt 3) == \"1\" && $(get_slot_type 3) != \"0\" ]]; then\n\n   devmem 0x1e78a184 w 0xFFF77304\n\n   if [ $(get_slot_type 3) == \"2\" ]; then\n      # I2C mux, 0xE2\n      echo pca9551 0x71 > /sys/class/i2c-dev/i2c-5/device/new_device\n      # I2C GPIO, 0x40\n      echo pca9551 0x20 > /sys/class/i2c-dev/i2c-5/device/new_device\n   fi\n\n   # EEPROM, 0xA2\n   echo 24c128 0x51 > /sys/class/i2c-dev/i2c-5/device/new_device\n   # Inlet temp sensor, 0x9A\n   echo tmp75 0x4d > /sys/class/i2c-dev/i2c-5/device/new_device\n   # outlet temp sensor, 0x9C\n   echo tmp75 0x4e > /sys/class/i2c-dev/i2c-5/device/new_device\n   # Voltage sensor, 0x80\n   echo ina230 0x40 > /sys/class/i2c-dev/i2c-5/device/new_device\nelse\n   devmem 0x1e78a184 w 0xFFF5E700\nfi\n\necho \"done\"\n", "num_lines": 118}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# The T2 chip can prefer different input voltages, depending, presumably\n# of manufacturing variations.  We need to determine whether it wants\n# 0.95V or 1.025V, reset the T2 to reduce total power usage, set the\n# outgoing voltage on the first buck converter, and bring T2 up out of\n# reset.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# read the T2 ROV after the GPIOs are enabled\nt2_rov() {\n    local val0 val1 val2\n    # Note that the values are *not* read in order.\n    val0=$(cat /sys/class/gpio/gpio58/value 2>/dev/null)\n    val1=$(cat /sys/class/gpio/gpio56/value 2>/dev/null)\n    val2=$(cat /sys/class/gpio/gpio57/value 2>/dev/null)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nrov=$(t2_rov)\n\n# target_volts come from the data sheet and 18mV of loss and\n# some fudging based on actual measurements to get either 1.025V\n# or 0.95V at T2\nif [ $rov -eq 1 ]; then\n    target_volts=0x5a\nelif [ $rov -eq 2 ]; then\n    target_volts=0x65\nelse\n    echo \"Unrecognized T2 ROV value $rov, setting failed.\"\n    exit 1\nfi\ntarget_volts=$(( $target_volts * 1 ))  # normalize to decimal\n\n# We shouldn't have to rmmod pmbus, because it hasn't been loaded yet,\n# but if the script is rerun after the system is up, it may be necessary.\nrmmod pmbus\nreload=$?\n\n# Get current voltage value\ncur_volts=$(i2cget -y 1 0x60 0x8b w)\ncur_volts=$(( $cur_volts * 1 ))  # normalize to decimal\n\n# Only bounce the T2 if we actually need to modify the voltage\nif [ $cur_volts -ne $target_volts ]; then \n    # Set values before turning out output;  we're using \"PCIE, then MCS\"\n    echo 1 > /sys/class/gpio/gpio42/value\n    echo 1 > /sys/class/gpio/gpio43/value\n    echo out > /sys/class/gpio/gpio42/direction\n    echo out > /sys/class/gpio/gpio43/direction\n    echo 0 > /sys/class/gpio/gpio16/value\n    echo out > /sys/class/gpio/gpio16/direction\n    # T2 is in reset;  note that this may cause NMI messages on the uServer,\n    # which shouldn't be up anyway when this is first run.\n    \n    # Set the requested value to the current value to avoid rapid shifts\n    i2cset -y 1 0x60 0x21 $cur_volts w\n    # Enable the requested voltage\n    i2cset -y 1 0x60 0xd2 0x5a\n    i2cset -y 1 0x60 0xd3 0x5a\n    sleep 1\n\n    # Set the target voltage\n    i2cset -y 1 0x60 0x21 $target_volts w\n    \n    sleep 1\n\n    # Let T2 come out of reset\n    echo 1 > /sys/class/gpio/gpio16/value\n    echo \"T2 ROV value set based on $rov.\"\n    sleep 2\n    echo 0 > /sys/class/gpio/gpio42/value\n    echo 0 > /sys/class/gpio/gpio43/value\nelse\n    echo \"T2 ROV already correctly set.\"\nfi\n# Bring back pmbus if necessary\nif [ $reload -eq 0 ]; then\n    modprobe pmbus\nfi\n", "num_lines": 100}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\ngpio_set 32 $VALUE\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nMAC1LINK=0    # GPIOA0\nFAB0_PRES=20  # GPIOC4\nFAB1_PRES=21  # GPIOC5\nwhile true; do\n  # fabN_pres: active low.\n  if [ $(gpio_get $FAB0_PRES) = 0 ]; then\n    gpio_set $MAC1LINK 0\n  elif [ $(gpio_get $FAB1_PRES) = 0 ]; then\n    gpio_set $MAC1LINK 1\n  fi\n  sleep 1\ndone\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nmac=$(i2cdump -y 0x0 0x49 s 0xd4 | grep '^00: d4'| awk '{ print $3\":\"$4\":\"$5\":\"$6\":\"$7\":\"$8 }') 2>/dev/null\n\nif [ -n \"$mac\" ]; then\n    echo $mac\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\nfi\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for minilaketb... \"\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  if [ $(is_server_prsnt 1) == \"1\" ]; then\n    if [ $(is_slot_12v_on 1) == \"1\" ]; then\n      if [[ $(get_slot_type 1) != \"0\" || $(is_bic_ready 1) == \"1\" ]]; then\n        SLOTS=\"$SLOTS slot1\"\n      fi\n    else\n      SLOTS=\"$SLOTS slot1\"\n    fi\n  fi\n\n\nSLOTS=\"$SLOTS spb\"\nexec /usr/local/bin/sensord $SLOTS\n", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for minilaketb... \"\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe pmbus\n\n# Enable the ADC inputs;  adc0 - adc15 are connected to various voltage sensors\n# adc12 - adc15 are for SLOT_TYPE\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n# For MINILAKETB tyep V:\n# channel 0:  r1:  5.36K; r2:  2.0K; v2: 0mv\n# channel 1:  r1:  15.8K; r2:  2.0K; v2: 0mv\n# channel 2:  r1:  2.87K; r2:  2.0K; v2: 0mv\n# channel 3:  r1:  15.8K; r2:  2.0K; v2: 0mv\n# channel 4:  r1:  15.8K; r2:  2.0K; v2: 0mv\n# channel 5:  r1:  15.8K; r2:  2.0K; v2: 0mv\n# channel 6:  r1:  15.8K; r2:  2.0K; v2: 0mv\n# channel 7:  r1:  2.87K; r2:  2.0K; v2: 0mv\n# channel 8:  r1:     1K; r2:  0.0K; v2: 0mv\n# channel 9:  r1:     1K; r2:  0.0K; v2: 0mv\n# channel 10: r1:  1.69K; r2:  2.0K; v2: 0mv\n# channel 11: r1:    665; r2:  2.0K; v2: 0mv\n# channel 12: r1:     1K; r2:    0K; v2: 0mv\n# channel 13: r1:     1K; r2:    0K; v2: 0mv\n# channel 14: r1:     1K; r2:    0K; v2: 0mv\n# channel 15: r1:     1K; r2:    0K; v2: 0mv\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\n\nconfig_adc 0  5360  2000 0\nconfig_adc 1 15800  2000 0\nconfig_adc 2  2870  2000 0\nconfig_adc 3 15800  2000 0\nconfig_adc 4 15800  2000 0\nconfig_adc 5 15800  2000 0\nconfig_adc 6 15800  2000 0\nconfig_adc 7  2870  2000 0\nconfig_adc 8  \t 0  1000 0\nconfig_adc 9  \t 0  1000 0\nconfig_adc 10 1690  2000 0\nconfig_adc 11  665  2000 0\nconfig_adc 12    0  1000 0\nconfig_adc 13    0  1000 0\nconfig_adc 14    0  1000 0\nconfig_adc 15    0  1000 0\n", "num_lines": 98}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nSLOT_NAME=$1\n\ncase $SLOT_NAME in\n    scm)\n      SLOT_NUM=1\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {scm}\"\n      exit 1\n      ;;\nesac\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump$SLOT_NUM.pid\"\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  echo \"Another auto crashdump for $SLOT_NAME is runnung\"\n  exit 1\nelse\n  touch $PID_FILE\nfi\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\necho $((sys_runtime+630)) > /tmp/cache_store/fru${SLOT_NUM}_crashdump\n\nDUMP_SCRIPT=\"/usr/local/bin/dump.sh\"\nCRASHDUMP_FILE=\"/mnt/data/crashdump_$SLOT_NAME\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_$SLOT_NAME.tar.gz\"\n\necho \"Auto Dump for $SLOT_NAME Started\"\n\n#HEADER LINE for the dump\n$DUMP_SCRIPT \"time\" > $CRASHDUMP_FILE\n#COREID dump\n$DUMP_SCRIPT $SLOT_NAME \"coreid\" >> $CRASHDUMP_FILE\n#MSR dump\n$DUMP_SCRIPT $SLOT_NAME \"msr\" >> $CRASHDUMP_FILE\n# Sensors & sensor thresholds\necho \"Sensor history at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"sensors\" >> $CRASHDUMP_FILE\necho \"Sensor threshold at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"threshold\" >> $CRASHDUMP_FILE\n\ntar zcf $CRASHDUMP_LOG_ARCHIVE -C `dirname $CRASHDUMP_FILE` `basename $CRASHDUMP_FILE` && \\\nrm -rf $CRASHDUMP_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for $SLOT_NAME is generated at $CRASHDUMP_LOG_ARCHIVE\"\n\necho \"Auto Dump for $SLOT_NAME Completed\"\n\nrm $PID_FILE\nexit 0\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIC_UTIL=\"/usr/bin/bic-util\"\nSENSOR_HISTORY=180\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"$0 <slot#> coreid    ==> for CPU CoreID\"\n  echo \"$0 <slot#> msr       ==> for CPU MSR\"\n  echo \"$0 <slot#> sensors   ==> for sensor history\"\n  echo \"$0 <slot#> threshold ==> for sensor threshold\"\n  exit 1\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_coreid ] && $BIC_UTIL $1 --me_file /usr/local/fbpackages/crashdump/crashdump_coreid\nelif [ \"$2\" = \"msr\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_msr ] && $BIC_UTIL $1 --me_file /usr/local/fbpackages/crashdump/crashdump_msr\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util all --threshold \nfi\n\nexit 0\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 0 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_4 > /dev/null 2>&1 &\n\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\nARGS=\"scm smb pim1 pim2 pim3 pim4 pim5 pim6 pim7 pim8 psu1 psu2 psu3 psu4\"\nexec /usr/local/bin/sensord $ARGS\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for MINIPACK... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe pmbus\n", "num_lines": 44}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttcsd trousers\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tcsd\n# Description:\t\ttcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo \"Starting $DESC: \"\n\n    # If TPM chip has not been discovered, probe the chip here\n\t\tif [ ! -e /dev/tpm* ]\n\t\tthen\n      # Finally, register the device and install the driver\n      . /usr/local/bin/openbmc-utils.sh\n      i2c_device_add 7 0x20 tpm_i2c_infineon\n    fi\n\n    # Additionally, Generate symlink to tpm0 or tpm1, so that tcsd can use it\n    rm -f /dev/tpm\n\t\tif [ -e /dev/tpm0 ]\n    then\n      ln -s /dev/tpm0 /dev/tpm\n    else\n      ln -s /dev/tpm1 /dev/tpm\n    fi\n\n\t\tstart-stop-daemon --start --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nfcm_b_ver=`head -n1 ${BOTTOM_FCMCPLD_SYSFS_DIR}/cpld_ver 2> /dev/null`\nfcm_t_ver=`head -n1 ${TOP_FCMCPLD_SYSFS_DIR}/cpld_ver 2> /dev/null`\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..8)]\" >&2\n}\n\n# Top FCM    (BUS=64) PWM 1 ~ 4 control Fantray 1 3 5 7\n# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fantray 2 4 6 8\nshow_pwm()\n{\n    pwm=\"$(i2c_device_sysfs_abspath $1-0033)/fantray$2_pwm\"\n    val=$(cat $pwm | head -n 1)\n\n    if [ \"$fcm_b_ver\" == \"0x0\" ] || [ \"$fcm_t_ver\" == \"0x0\" ]; then\n        echo \"$((val * 100 / 31))%\"\n    else\n        echo \"$((val * 100 / 63))%\"\n    fi\n}\n\nshow_rpm()\n{\n    front_rpm=\"$(i2c_device_sysfs_abspath $1-0033)/fan$((($2 * 2 - 1)))_input\"\n    rear_rpm=\"$(i2c_device_sysfs_abspath $1-0033)/fan$((($2 * 2)))_input\"\n    echo \"$(cat $front_rpm), $(cat $rear_rpm)\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5 6 7 8\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 9 ]; then\n        echo \"Fan $1: not a valid Fan Unit\"\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    FAN=\"${fan}\"\n\n    if [ $(($fan % 2)) -eq 0 ]; then\n      BUS=\"72\"\n      UNIT=$((${FAN} / 2 ))\n    else\n      BUS=\"64\"\n      FAN=$((${FAN} / 2 ))\n      UNIT=$((${FAN} + 1))\n    fi\n\n    echo \"Fan $fan RPMs: $(show_rpm $BUS $UNIT), ($(show_pwm $BUS $UNIT))\"\ndone\n", "num_lines": 83}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/fbpackages/utils/ast-functions\n\ndefault_fsc_config=\"/etc/fsc-config.json\"\nfcm_b_ver=`head -n1 ${BOTTOM_FCMCPLD_SYSFS_DIR}/cpld_ver \\\n           2> /dev/null`\nfcm_b_sub_ver=`head -n1 ${BOTTOM_FCMCPLD_SYSFS_DIR}/cpld_sub_ver \\\n           2> /dev/null`\nfcm_t_ver=`head -n1 ${TOP_FCMCPLD_SYSFS_DIR}/cpld_ver \\\n           2> /dev/null`\nfcm_t_sub_ver=`head -n1 ${TOP_FCMCPLD_SYSFS_DIR}/cpld_sub_ver \\\n           2> /dev/null`\nfcm_b_maj=`echo $fcm_b_ver | awk '{printf \"%d\", $1;}'`\nfcm_b_min=`echo $fcm_b_sub_ver | awk '{printf \"%d\", $1;}'`\nfcm_t_maj=`echo $fcm_t_ver | awk '{printf \"%d\", $1;}'`\nfcm_t_min=`echo $fcm_t_sub_ver | awk '{printf \"%d\", $1;}'`\necho -n \"Setup fan speed... \"\n\nif [ \"$fcm_b_ver\" == \"0x0\" ] || [ \"$fcm_t_ver\" == \"0x0\" ]; then\n    echo \"Run FSC PWM 32 Levels Config\"\n    cp /etc/FSC-PWM-32-config.json ${default_fsc_config}\nelse\n    echo \"Run FSC PWM 64 Levels Config\"\n    cp /etc/FSC-PWM-64-config.json ${default_fsc_config}\nfi\necho \"Setting fan speed to 50%...\"\n/usr/local/bin/set_fan_speed.sh 50\necho \"Done setting fan speed\"\n# Currently, fcmcpld version 0.xx will cause BMC to \n# run into crash loop, due to fscd's own logic and \n# its failure to disarm bootup watchdog.\n# (this problem is only for fcmcpld 0.xx. Fcmcpld 1.9 and \n# above works well without any problem.)\n# Until we have fix, we will run fscd only if fcmcpld is 1.9 or higher.\nfcm_b_compatible=0\nfcm_t_compatible=0\nif [ $fcm_b_maj -eq 1 ] && [ $fcm_b_min -ge 9 ]; then \n   fcm_b_compatible=1\nfi\nif [ $fcm_b_maj -ge 2 ]; then\n   fcm_b_compatible=1\nfi\nif [ $fcm_t_maj -eq 1 ] && [ $fcm_t_min -ge 9 ]; then\n   fcm_t_compatible=1\nfi\nif [ $fcm_b_maj -ge 2 ]; then\n   fcm_t_compatible=1\nfi\necho fcm_b version : $fcm_b_maj $fcm_b_min compatible: $fcm_b_compatible\necho fcm_t version : $fcm_t_maj $fcm_t_min compatible: $fcm_t_compatible\nif [ $fcm_b_compatible -eq 0 ] || [ $fcm_t_compatible -eq 0 ]; then\n    echo \"Old FCM CPLD detected. Running fan at the fixed speed.\"\n    /usr/local/bin/wdtcli stop\nelse\n    echo \"Starting fscd...\"\n    runsv /etc/sv/fscd > /dev/null 2>&1 &\nfi\necho \"done.\"\n", "num_lines": 88}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nfcm_b_ver=`head -n1 ${BOTTOM_FCMCPLD_SYSFS_DIR}/cpld_ver 2> /dev/null`\nfcm_t_ver=`head -n1 ${TOP_FCMCPLD_SYSFS_DIR}/cpld_ver 2> /dev/null`\n\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..8)> \" >&2\n}\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# Top FCM    (BUS=64) PWM 1 ~ 4 control Fantray 1 3 5 7\n# Bottom FCM (BUS=72) PWM 1 ~ 4 control Fantray 2 4 6 8\nBUS=\"64 72\"\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 9 ]; then\n        echo \"Fan $2: not a valid Fan Unit\"\n        exit 1\n    fi\n\n    FAN=\"$2\"\n\n    if [ $(($FAN % 2)) -eq 0 ]; then\n      BUS=\"72\"\n      FAN_UNIT=$((${FAN} / 2 ))\n    else\n      BUS=\"64\"\n      FAN=$((${FAN} / 2 ))\n      FAN_UNIT=$((${FAN} + 1))\n    fi\nfi\n\nif [ \"$fcm_b_ver\" == \"0x0\" ] || [ \"$fcm_t_ver\" == \"0x0\" ]; then\n    # Convert the percentage to our 1/32th level (0-31).\n    step=$((($1 * 31) / 100))\nelse\n    # Convert the percentage to our 1/64th level (0-63).\n    step=$((($1 * 63) / 100))\nfi\ncnt=1\n\nfor bus in ${BUS}; do\n    for unit in ${FAN_UNIT}; do\n        pwm=\"$(i2c_device_sysfs_abspath ${bus}-0033)/fantray${unit}_pwm\"\n        echo \"$step\" > \"${pwm}\"\n\n    if [ \"$#\" -eq 1 ]; then\n        echo \"Successfully set fan $cnt speed to $1%\"\n        cnt=$(($cnt+1))\n    else\n        echo \"Successfully set fan $2 speed to $1%\"\n    fi\n    done\ndone\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2018-present Facebook. All Rights Reserved.\n\n#\n# I2C paths of CPLDs\n#\nSCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-0035)\nSMBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-003e)\nTOP_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 64-0033)\nBOTTOM_FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 72-0033)\nLEFT_PDBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 55-0060)\nRIGHT_PDBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 63-0060)\n\n#\n# I2C paths of FPGAs\n#\nIOBFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 13-0035)\nPIM1_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 80-0060)\nPIM2_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 88-0060)\nPIM3_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 96-0060)\nPIM4_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 104-0060)\nPIM5_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 112-0060)\nPIM6_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 120-0060)\nPIM7_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 128-0060)\nPIM8_DOMFPGA_SYSFS_DIR=$(i2c_device_sysfs_abspath 136-0060)\n\nPWR_USRV_SYSFS=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable\"\nPWR_TH_RST_SYSFS=\"${SMBCPLD_SYSFS_DIR}/cpld_mac_reset_n\"\n\nwedge_iso_buf_enable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_is_us_on() {\n    local val\n\n    val=$(cat $PWR_USRV_SYSFS 2> /dev/null | head -n 1)\n    if [ \"$val\" == \"0x1\" ]; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n\n    return 0\n}\n\nwedge_board_type() {\n    echo 'MINIPACK'\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    local val0 val1 val2\n    val0=$(gpio_get_value BMC_CPLD_BOARD_REV_ID0)\n    val1=$(gpio_get_value BMC_CPLD_BOARD_REV_ID1)\n    val2=$(gpio_get_value BMC_CPLD_BOARD_REV_ID2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    # minipack uses BMC MAC since beginning\n    return -1\n}\n\nwedge_power_on_board() {\n    # minipack SCM power is controlled by SCMCPLD\n    return 0\n}\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\nexitCode=0\n\ndump_cpld_version() {\n    local cpld_dir=$1\n    local cpld_name=$2\n\n    cpld_ver=`head -n 1 ${cpld_dir}/cpld_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${cpld_name} is not detected\"\n        exitCode=1\n    fi\n    cpld_sub_ver=`head -n 1 ${cpld_dir}/cpld_sub_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${cpld_name} is not detected\"\n        exitCode=1\n    fi\n    \n    if [ \"$exitCode\" -eq 0 ]; then \n      echo \"${cpld_name}: $(($cpld_ver)).$(($cpld_sub_ver))\"\n    fi\n}\n\ndump_cpld_version ${SMBCPLD_SYSFS_DIR} \"SMBCPLD\"\nusleep 50000\n\ndump_cpld_version ${SCMCPLD_SYSFS_DIR} \"SCMCPLD\"\nusleep 50000\n\ndump_cpld_version ${TOP_FCMCPLD_SYSFS_DIR} \"Top FCMCPLD\"\nusleep 50000\n\ndump_cpld_version ${BOTTOM_FCMCPLD_SYSFS_DIR} \"Bottom FCMCPLD\"\nusleep 50000\n\nboard_rev=$(wedge_board_rev)\nif [ $board_rev -ne 4 ]; then\n    dump_cpld_version ${LEFT_PDBCPLD_SYSFS_DIR} \"Left PDBCPLD\"\n    usleep 50000\n\n    dump_cpld_version ${RIGHT_PDBCPLD_SYSFS_DIR} \"Right PDBCPLD\"\nfi\n\nif [ \"$exitCode\" -ne 0 ]; then\n  echo \"since all the CPLDs didn't succeed with the  name listed above... so exiting\"\n  exit 1\nfi\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nfor index in 1 2 3 4 5 6 7 8\ndo\n    pim_path=${SMBCPLD_SYSFS_DIR}/pim_fpga_cpld_${index}_prsnt_n_status\n    pim_prsnt=$(cat $pim_path 2> /dev/null | head -n 1)\n    cache_file=\"/tmp/pim${index}_serial.txt\"\n    \n    # Refresh pimserial cache file when\n    #   1) the pim is present, and\n    #   2) the cache file doesn't exist or it doesn't contain valid strings\n    if [ ! -s \"$cache_file\" ] || [ -z \"$(cat $cache_file)\" ]; then\n        if [ \"${pim_prsnt}\" == 0x0 ]; then\n            /usr/local/bin/peutil $index |grep Product|grep Serial|cut -d ' ' -f 4 > \"$cache_file\"\n        fi\n    fi\n    serial=\"$(cat $cache_file)\"\n    echo PIM${index} : ${serial}\ndone\n\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nSMBCPLD=/sys/bus/i2c/devices/i2c-12/12-003e\n\nif [ $# -ne 1 ]; then\n    exit -1\nfi\n\nimg=\"$1\"\n\nsource /usr/local/bin/openbmc-utils.sh\n\ntop_fan_cpld=\"${SMBCPLD}/smb_cpld_fcm_b_cpld_sel\"\nbottom_fan_cpld=\"${SMBCPLD}/smb_cpld_fcm_b_cpld_sel\"\n\ntrap 'gpio_set_value BMC_FCM_T_MUX_SEL 0; \\\n      gpio_set_value BMC_FCM_B_MUX_SEL 0; \\\n      echo 0 > \"${top_fan_cpld}\"; \\\n      echo 0 > \"${bottom_fan_cpld}\"; \\\n      rm -rf /tmp/fcmcpld_update' INT TERM QUIT EXIT\n\n# change BMC_FCM_T_MUX_SEL and smb_cpld_fcm_t_cpld_sel to 1\n# to connect BMC to Top FANCPLD pins\ngpio_set_value BMC_FCM_T_MUX_SEL 1\necho 1 > \"${top_fan_cpld}\"\n\n# change BMC_FCM_B_MUX_SEL and smb_cpld_fcm_t_cpld_sel to 1\n# to connect BMC to Bottom FANCPLD pins\ngpio_set_value BMC_FCM_B_MUX_SEL 1\necho 1 > \"${bottom_fan_cpld}\"\n\necho 1 > /tmp/fcmcpld_update\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n    --tms BMC_FCM_CPLD_TMS \\\n    --tdo BMC_FCM_CPLD_TDI \\\n    --tdi BMC_FCM_CPLD_TDO \\\n    --tck BMC_FCM_CPLD_TCK\nresult=$?\n# 1 is returned upon upgrade success\nif [ $result -eq 1 ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    exit 1\nfi\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\nexitCode=0\n\ndump_fpga_version() {\n    local fpga_dir=$1\n    local fpga_name=$2\n\n    fpga_ver=`head -n 1 ${fpga_dir}/fpga_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        exit 1\n\n    fi\n    fpga_sub_ver=`head -n 1 ${fpga_dir}/fpga_sub_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        exit 1\n    fi\n\n    echo \"${fpga_name}: $(($fpga_ver)).$(($fpga_sub_ver))\"\n}\n\necho \"------IOBFPGA------\"\ndump_fpga_version ${IOBFPGA_SYSFS_DIR} \"IOBFPGA\"\n\necho \"------DOMFPGA------\"\nfor num in $(seq 8); do\n    pim_var_name=\"PIM${num}_DOMFPGA_SYSFS_DIR\"\n    pim_fpga_dir=${!pim_var_name}\n\n    echo \"PIM $num:\"\n\n    pim_type=`head -n1 ${pim_fpga_dir}/board_ver 2> /dev/null`\n    if [ \"${pim_type}\" == \"0x0\" ]; then\n        dump_fpga_version ${pim_fpga_dir} \"16Q DOMFPGA\"\n    elif [ \"$((pim_type & 0xf0))\" == \"$((0xf0))\" ]; then\n        dump_fpga_version ${pim_fpga_dir} \"16O DOMFPGA\"\n    elif [ \"${pim_type}\" == \"0x10\" ]; then\n        dump_fpga_version ${pim_fpga_dir} \"4DD DOMFPGA\"\n    else\n        echo \"DOMFPGA is not detected or PIM $num is not inserted\"\n        exitCode=1\n    fi\n    usleep 50000\ndone\n\nif [ \"$exitCode\" -ne 0 ]; then\n    echo \"Not all DOMFPGA or PIM were detected/inserted. Please review the logs above.... exiting\"\n    exit 1\nfi\n\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nboard_rev=$(wedge_board_rev)\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program jtag <Location> <*.vme>\"\n    echo \"     $program i2c <Location> <*.hex>\"\n    echo \"     <Location>  : left or right\"\n}\n\nif [ $board_rev -eq 4 ]; then\n    echo \"EVTA hardware doesn't have PDBCPLD\"\n    exit -1\nfi\n\nif [ \"$#\" -ne 3 ]; then\n    usage\n    exit -1\nfi\n\nif [ \"$2\" = \"left\" ]; then\n    IO_BUS=54\n    CPLD_BUS=53\nelif [ \"$2\" = \"right\" ]; then\n    IO_BUS=62\n    CPLD_BUS=61\nelse\n    echo \"$2: not a valid PDB location\"\n    exit -1\nfi\n\ninterface=\"$1\"\nimg=\"$3\"\n\nCPLD_PIN_OFFSETS=(0 1 2 3)\nCPLD_SHADOWS=(BMC_PDB_CPLD_TDO BMC_PDB_CPLD_TDI BMC_PDB_CPLD_TMS BMC_PDB_CPLD_TCK)\nHITLESS_OFFSET=7\nHITLESS_SHADOW=BMC_PDB_HITLESS\nPCA9534=`i2cdetect -y ${IO_BUS} 0x21 0x21 | grep \"\\-\\-\"` > /dev/null\n\npca9534_gpio_add()\n{\n    if [ \"${PCA9534}\" != \"\" ]; then\n        echo \"PDB $1 not insert or PCA9534 fail!\"\n        exit -1\n    fi\n\n    i2c_device_add ${IO_BUS} 0x21 pca9534\n    usleep 100000\n\n    gpio_export_by_offset ${IO_BUS}-0021 ${HITLESS_OFFSET} ${HITLESS_SHADOW}\n    gpio_set_value ${HITLESS_SHADOW} 0\n\n    if [ \"$interface\" = \"jtag\" ]; then\n        for i in {0..3}; do\n            gpio_export_by_offset ${IO_BUS}-0021 ${CPLD_PIN_OFFSETS[i]} ${CPLD_SHADOWS[i]}\n        done\n    fi\n}\n\npca9534_gpio_delete()\n{\n    if [ \"${PCA9534}\" != \"\" ]; then\n        exit -1\n    fi\n\n    gpio_set_value ${HITLESS_SHADOW} 1\n    gpio_unexport ${HITLESS_SHADOW}\n\n    if [ \"$interface\" = \"jtag\" ]; then\n        for i in {0..3}; do\n            gpio_unexport ${CPLD_SHADOWS[i]}\n        done\n    fi\n\n\n    i2c_device_delete ${IO_BUS} 0x21\n    rm -rf /tmp/pdbcpld_update\n}\n\ntrap pca9534_gpio_delete INT TERM QUIT EXIT\n\necho 1 > /tmp/pdbcpld_update\n\n# export pca9534 GPIO to connect BMC to PDB CPLD pins\npca9534_gpio_add $2\n\nif [ \"$interface\" = \"jtag\" ]; then\n    ispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n              --tms ${CPLD_SHADOWS[2]} --tdo ${CPLD_SHADOWS[0]} \\\n              --tdi ${CPLD_SHADOWS[1]} --tck ${CPLD_SHADOWS[3]}\n    result=$?\n    sleep 1\n    # 1 is returned upon upgrade success\n    if [ $result -eq 1 ]; then\n        echo \"Upgrade successful.\"\n        exit 0\n    else\n        echo \"Upgrade failure. Return code from utility : $result\"\n        exit 1\n    fi\nelif [ \"$interface\" = \"i2c\" ]; then\n    cpldupdate-i2c ${CPLD_BUS} 0x40 \"${img}\"\n    sleep 1\nelse\n    echo \"$1 is not a valid PDB interface\"\n    exit -1\nfi\n", "num_lines": 132}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program <PIM> <File Path>\"\n    echo \"     <PIM>: 1 ~ 8\"\n}\n\nif [ $# -ne 2 ]; then\n    usage\n    exit -1\nfi\nUNIT=$1\nIMAGE=\"$2\"\n\nif [ \"${UNIT}\" -le 0 ] || [ \"${UNIT}\" -ge 9 ]; then\n    echo \"PIM #${UNIT}: not a valid PIM Unit\"\n    exit -1\nfi\n\nsource /usr/local/bin/openbmc-utils.sh\n\nPIN_OFFSETS=(3 4 5 6)\nSHADOWS=(BMC_PIM${UNIT}_CPLD_TCK BMC_PIM${UNIT}_CPLD_TMS \\\n         BMC_PIM${UNIT}_CPLD_TDO BMC_PIM${UNIT}_CPLD_TDI)\nBUS=$(((${UNIT} - 1) * 8 + 85 ))\nPCA9534=`i2cdetect -y ${BUS} 0x26 0x26 | grep \"\\-\\-\"` > /dev/null\n\n# PIM1 -> BUS 85 ; PIM2 -> BUS 93 ; PIM3 -> BUS 101; PIM4 -> BUS 109\n# PIM5 -> BUS 117; PIM6 -> BUS 125; PIM7 -> BUS 133; PIM8 -> BUS 141\npca9534_gpio_add()\n{\n    if [ \"${PCA9534}\" != \"\" ]; then\n        echo \"PIM #${UNIT} not insert or PCA9534 fail!\"\n        exit -1\n    fi\n\n    i2c_device_add ${BUS} 0x26 pca9534\n    usleep 100000\n\n    for i in {0..3}; do\n        gpio_export_by_offset ${BUS}-0026 ${PIN_OFFSETS[i]} ${SHADOWS[i]}\n    done\n}\n\npca9534_gpio_delete()\n{\n    if [ \"${PCA9534}\" != \"\" ]; then\n        exit -1\n    fi\n\n    for i in {0..3}; do\n        gpio_unexport ${SHADOWS[i]}\n    done\n\n    i2c_device_delete ${BUS} 0x26\n    rm -rf /tmp/pimcpld_update\n}\n\ntrap pca9534_gpio_delete INT TERM QUIT EXIT\n\n# export pca9534 GPIO to connect BMC to PIM CPLD pins\npca9534_gpio_add ${UNIT}\n\necho 1 > /tmp/pimcpld_update\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${IMAGE}\" \\\n    --tms ${SHADOWS[1]} \\\n    --tdo ${SHADOWS[2]} \\\n    --tdi ${SHADOWS[3]} \\\n    --tck ${SHADOWS[0]}\nresult=$?\n# 1 is returned upon upgrade success\nif [ $result -eq 1 ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    exit 1\nfi\n", "num_lines": 101}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nwedge_power_on_board\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nsource /usr/local/bin/openbmc-utils.sh\n\nSCM_CMD=$SMBCPLD_SYSFS_DIR'/scm_presnt_status'\nPIM_CMD=$SMBCPLD_SYSFS_DIR'/*prsnt_n_status'\n\nfunction usage\n{\n  program=`basename \"$0\"`\n  echo \"Usage:\"\n  echo \"     $program \"\n  echo \"     $program <TYPE>\"\n  echo \"     <TYPE>: scm/pim/fan/psu\"\n}\n\n# Will return <key> : <val>\n# eg - scm : 1\nfunction get_presence\n{\n    local file=$1 key=$2\n    val=$(head -n1 $file | awk '{print substr($0,0,3) }' | sed 's/.x//')\n    if [ $val -eq 0 ]; then\n        val=1\n    else\n        val=0\n    fi\n    echo $key \":\" $val\n}\n\n# SCM\nfunction get_scm_presence\n{\n    key='scm'\n    get_presence $SCM_CMD $key\n}\n\n# PIMs\nfunction get_pim_presence\n{\n    local count=1\n    for file in $PIM_CMD; do\n        key='pim'$count\n        get_presence $file $key\n        (( count++ ))\n    done\n}\n\n# FANs\nfunction get_fan_presence\n{\n    local num=1\n    while [ $num -le 4 ]; do\n        count=$(((${num} * 2 ) - 1))\n        key='fan'$count\n        file=$TOP_FCMCPLD_SYSFS_DIR'/fantray'$num'_present'\n        get_presence $file $key\n        count=$((${num} * 2 ))\n        key='fan'$count\n        file=$BOTTOM_FCMCPLD_SYSFS_DIR'/fantray'$num'_present'\n        get_presence $file $key\n        (( num++ ))\n        (( count++ ))\n    done\n}\n\n# Power supplies\nfunction get_psu_presence\n{\n    for i in {2..1}; do\n        count=$((3 - ${i}))\n        key='psu'$count\n        file=$SMBCPLD_SYSFS_DIR'/psu_L'${i}'_present_L'\n        get_presence $file $key\n    done\n    for i in {2..1}; do\n        count=$((5 - ${i}))\n        key='psu'$count\n        file=$SMBCPLD_SYSFS_DIR'/psu_R'${i}'_present_L'\n        get_presence $file $key\n    done\n}\n\n# get all info\nif [[ $1 = \"\" ]]; then\n  echo \"CARDS\"\n  get_scm_presence\n  get_pim_presence\n\n  echo \"FANS\"\n  get_fan_presence\n\n  echo \"POWER SUPPLIES\"\n  get_psu_presence\n\nelse\n  if [[ $1 = \"scm\" ]]; then\n    get_scm_presence\n  elif [[ $1 = \"pim\" ]]; then\n    get_pim_presence\n  elif [[ $1 = \"fan\" ]]; then\n    get_fan_presence\n  elif [[ $1 = \"psu\" ]]; then\n    get_psu_presence\n  else\n    usage\n  fi\nfi\n", "num_lines": 129}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nIO0=$(i2cget -f -y 50 0x20 0x2)\nIO1=$(i2cget -f -y 50 0x20 0x3)\n\nusage(){\n  program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"     $program <brd_rev>\"\n    echo \"\"\n    echo \"     <brd_rev>: borad revision\"\n}\n\nprint_color_name(){\n  case $2 in\n      6)\n          color=\"red\"\n      ;;\n      3)\n          color=\"blue\"\n      ;;\n      4)\n          color=\"yellow\"\n      ;;\n      7)\n          color=\"off\"\n      ;;\n      *)\n      echo \"Read value that is not a valid color $1:$2\"\n      exit 1\n      ;;\n  esac\n  echo \"$1:$color\"\n}\n\nif [ \"$1\" = \"0\" ] || [ \"$1\" = \"4\" ]; then\n\n    PSU_VAL=$(((IO0 & 0x38) >> 3))\n    SMB_VAL=$(((IO1 & 0x38) >> 3))\n    FAN_VAL=$((IO0 & 0x7))\n    SYS_VAL=$((IO1 & 0x7))\n\nelse \n\n    FAN_VAL=$(((IO0 & 0x38) >> 3))\n    SMB_VAL=$(((IO1 & 0x38) >> 3))\n    SYS_VAL=$((IO0 & 0x7))\n    PSU_VAL=$((IO1 & 0x7))\n\nfi\n\nprint_color_name \"sys\" $SYS_VAL\nprint_color_name \"smb\" $SMB_VAL\nprint_color_name \"psu\" $PSU_VAL\nprint_color_name \"fan\" $FAN_VAL\n\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\n# There are two reset pins to ASIC. System reset and PCI reset.\n#\n# When PWR_TH_RST_SYSFS is set to 0, CPLD will drive both reset pins to trigger\n# reset.\n#\n# When PWR_TH_RST_SYSFS is set to 1, CPLD will drive system reset, followed by\n# PCI reset following the reset sequeence.\n#\n# There is another sysfs file, 'cpld_mac_pcie_perst_l', which can be used\n# to control the PCI reset pin separately. However, we don't use it for now\n# as we depend on the CPLD for the correct reset sequence.\necho 0 > $PWR_TH_RST_SYSFS\nsleep 1\necho 1 > $PWR_TH_RST_SYSFS\n\nlogger \"Reset Tomahawk\"\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nCMD=\"${SMBCPLD_SYSFS_DIR}/cpld_usb2112a_brdg_rst\"\n\necho -n \"Reset CP2112 Switch ... \"\necho 0 > $CMD\nusleep 50000\necho 1 > $CMD\n\necho \"Done\"\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif [ $# -ne 1 ]; then\n    exit -1\nfi\n\nimg=\"$1\"\n\nsource /usr/local/bin/openbmc-utils.sh\n\ntrap 'gpio_set_value BMC_SCM_CPLD_EN 1; \\\n      rm -rf /tmp/scmcpld_update' INT TERM QUIT EXIT\n\n# change BMC_SCM_CPLD_EN to 0 to connect BMC to SCM CPLD pins\ngpio_set_value BMC_SCM_CPLD_EN 0\n\necho 1 > /tmp/scmcpld_update\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n    --tms BMC_SCM_CPLD_TMS \\\n    --tdo BMC_SCM_CPLD_TDO \\\n    --tdi BMC_SCM_CPLD_TDI \\\n    --tck BMC_SCM_CPLD_TCK\nresult=$?\n# 1 is returned upon upgrade success\nif [ $result -eq 1 ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    exit 1\nfi\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nboard_rev=$(wedge_board_rev)\n\n# Enable the isolation buffer between BMC and COMe i2c bus\necho 1 > ${SCMCPLD_SYSFS_DIR}/i2c_bus_en\necho 0 > ${SCMCPLD_SYSFS_DIR}/iso_com_early_en\n\n# Make the backup BIOS flash connect to COMe instead of BMC\necho 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_oe_n\necho 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_sel\n\n# Setup management port LED\n/usr/local/bin/setup_mgmt.sh led &\n\n# Setup TH3 PCI-e repeater\n/usr/local/bin/setup_pcie_repeater.sh th3 write\n\n# Init server_por_cfg\nif [ ! -f \"/mnt/data/kv_store/server_por_cfg\" ]; then\n    /usr/bin/kv set server_por_cfg on persistent\nfi\n\n# Setup hotswap power monitor averaging for FCM-T and FCM-B\ni2cset -f -y 67 0x10 0xd4 0x3f1e w\ni2cset -f -y 75 0x10 0xd4 0x3f1e w\n\n/usr/bin/kv set smb_board_rev $board_rev\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nboard_rev=$(wedge_board_rev)\n\n#\n# instantiate all the i2c-muxes.\n# Note:\n#   - the function may be skipped if i2c switches were already created\n#     in kernel space.\n#   - please do not modify the order of i2c-mux creation unless you've\n#     decided to fix bus-number of leaf i2c-devices.\n#\nbulk_create_i2c_mux() {\n    i2c_mux_name=\"pca9548\"\n    mux_channels=8\n\n    # The first-level i2c-muxes which are directly connected to aspeed\n    # i2c adapters are described in device tree, and the bus number of\n    # these i2c-muxes' channels are hardcoded (as below) to avoid\n    # breaking the existing applications.\n    #    i2c-mux 2-0070: child bus 16-23\n    #    i2c-mux 8-0070: child bus 24-31\n    #    i2c-mux 9-0070: child bus 32-39\n    #    i2c-mux 11-0070: child bus 40-47\n\n    # Create second-level i2c-muxes which are connected to first level\n    # mux \"8-0070\". \"8-0070\" has 8 channels and the first 4 channels\n    # are connected with 1 extra level of i2c-mux. So total 32 child\n    # buses (48-79) will be registered.\n    i2c_mux_add_sync 24 0x71 \"$i2c_mux_name\" \"$mux_channels\"\n\n    i2c_mux_add_sync 25 0x72 \"$i2c_mux_name\" \"$mux_channels\"\n\n    i2c_mux_add_sync 26 0x76 \"$i2c_mux_name\" \"$mux_channels\"\n\n    i2c_mux_add_sync 27 0x76 \"$i2c_mux_name\" \"$mux_channels\"\n\n\n    # Create second-level i2c-muxes which are connected to first level\n    # mux \"11-0070\". \"11-0070\" has 8 channels and each channel is\n    # connected with 1 extra level of i2c-mux (@ address 0x73), thus\n    # totally 64 i2c buses (80-143) will be registered.\n    parent_buses=\"40 41 42 43 44 45 46 47\"\n    for bus in ${parent_buses}; do\n        i2c_mux_add_sync \"$bus\" 0x73 \"$i2c_mux_name\" \"$mux_channels\"\n    done\n}\n\n#\n# Let's check a few i2c switches to determine if these switches were\n# already created in kernel space.\n#\nI2C_MUX_PDB_LEFT=\"${SYSFS_I2C_DEVICES}/24-0071\"\nI2C_MUX_FCM_TOP=\"${SYSFS_I2C_DEVICES}/26-0076\"\nI2C_MUX_PIM1=\"${SYSFS_I2C_DEVICES}/40-0073\"\nI2C_MUX_PIM6=\"${SYSFS_I2C_DEVICES}/45-0073\"\nif [ ! -e \"${I2C_MUX_PDB_LEFT}\" ] && [ ! -e \"${I2C_MUX_FCM_TOP}\" ] && \\\n   [ ! -e \"${I2C_MUX_PIM1}\" ] && [ ! -e \"${I2C_MUX_PIM6}\" ]; then\n    bulk_create_i2c_mux\nfi\n\nKERNEL_VERSION=`uname -r`\nif [[ ${KERNEL_VERSION} != 4.1.* ]]; then\n    # Create i2c slave backend on bus 0 and 4.\n    i2c_mslave_add 0 0x10\n    i2c_mslave_add 4 0x10\nfi\n\n# # Bus 2\ni2c_device_add 2 0x35 scmcpld          # SCMCPLD\n\n# # Bus 12\ni2c_device_add 12 0x3e smbcpld         # SMBCPLD\n\n# # Bus 13\ni2c_device_add 13 0x35 iobfpga         # IOBFPGA\n\n# # Bus 1\ni2c_device_add 1 0x3a powr1220         # SMB power sequencer\ni2c_device_add 1 0x12 ir3595           # TH3 core voltage/current monitor\ni2c_device_add 1 0x60 isl68127         # TH3 serdes voltage/current monitor\n\n# # Bus 3\ni2c_device_add 3 0x48 tmp75            # SMB temp. sensor\ni2c_device_add 3 0x49 tmp75            # SMB temp. sensor\ni2c_device_add 3 0x4a tmp75            # SMB temp. sensor\ni2c_device_add 3 0x4b tmp75            # SMB temp. sensor\n\n# # Bus 30\ni2c_device_add 30 0x4c tmp422          # TH3 temp. sensor\n\n# # Bus 16\ni2c_device_add 16 0x10 adm1278         # SCM Hotswap\n\n# # Bus 17\ni2c_device_add 17 0x4c tmp421          # SCM temp. sensor\ni2c_device_add 17 0x4d tmp421          # SCM temp. sensor\n\nif [ $board_rev -ne 4 ]; then\n    # # Bus 55\n    i2c_device_add 55 0x60 pdbcpld         # Left PDBCPLD\n\n    # # Bus 63\n    i2c_device_add 63 0x60 pdbcpld         # Right PDBCPLD\nfi\n\n# # Bus 49\ni2c_device_add 49 0x59 psu_driver      # PDB-L PSU1 Driver\n\n# # Bus 48\ni2c_device_add 48 0x58 psu_driver      # PDB-L PSU2 Driver\n\n# # Bus 57\ni2c_device_add 57 0x59 psu_driver      # PDB-R PSU3 Driver\n\n# # Bus 56\ni2c_device_add 56 0x58 psu_driver      # PDB-R PSU4 Driver\n\n# # Bus 51\ni2c_device_add 51 0x48 tmp75           # PDB-L temp. sensor\n\n# # Bus 52\ni2c_device_add 52 0x49 tmp75           # PDB-L temp. sensor\n\n# # Bus 59\ni2c_device_add 59 0x48 tmp75           # PDB-R temp. sensor\n\n# # Bus 60\ni2c_device_add 60 0x49 tmp75           # PDB-R temp. sensor\n\n# # Bus 64\ni2c_device_add 64 0x33 fcmcpld         # Top FCMCPLD\n\n# # Bus 72\ni2c_device_add 72 0x33 fcmcpld         # Bottom FCMCPLD\n\n# # Bus 66\ni2c_device_add 66 0x48 tmp75           # FCM-T temp. sensor\ni2c_device_add 66 0x49 tmp75           # FCM-T temp. sensor\n\n# # Bus 67\ni2c_device_add 67 0x10 adm1278         # FCM-T Hotswap\n\n# # Bus 74\ni2c_device_add 74 0x48 tmp75           # FCM-B temp. sensor\ni2c_device_add 74 0x49 tmp75           # FCM-B temp. sensor\n\n# # Bus 67\ni2c_device_add 75 0x10 adm1278         # FCM-T Hotswap\n\n# # Bus 6\ni2c_device_add 6 0x51 24c64            # Board fru EEPROM\n\n# # Bus 18\ni2c_device_add 18 0x52 24c64           # SCM fru eeprom\n\n# # Bus 65\ni2c_device_add 65 0x51 24c02           # FCM-T fru eeprom\n\n# # Bus 73\ni2c_device_add 73 0x51 24c02           # FCM-B fru eeprom\n\n# # Bus 68 ~ 71                        # Fantray 7 5 3 1  fru eeprom\n# # Bus 76 ~ 79                        # Fantray 8 6 4 2  fru eeprom\nBUS=\"68 69 70 71 76 77 78 79\"\nfor bus in ${BUS}; do\n    i2c_device_add $bus 0x52 24c64\ndone\n\n# # Bus 81 89 97 105 113 121 129 137   # PIM1 ~ PIM8 fru eeprom\nBUS=\"81 89 97 105 113 121 129 137\"\nfor bus in ${BUS}; do\n    i2c_device_add $bus 0x53 24c64     # 4DD\n    i2c_device_add $bus 0x56 24c64     # 16Q\ndone\n\n# # Bus 80 88 96 104 112 120 128 136  # PIM1 ~ PIM8 DOMFPGA\nBUS=\"80 88 96 104 112 120 128 136\"\nfor bus in ${BUS}; do\n    i2c_device_add $bus 0x60 domfpga\ndone\n", "num_lines": 203}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nsource /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nSFP_AUTO_DETECT=\"${SCMCPLD_SYSFS_DIR}/sfp_auto_detect\"\nCOM_E_PWRGD=`head -n 1 ${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok`\nTX_DISABLE=\"${SCMCPLD_SYSFS_DIR}/tx_disable\"\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program led/combo/all\"\n}\n\nif [ $# -ne 1 ]; then\n    usage\n    exit -1\nfi\n\n# When COM-e power is not ready, it doesn't work to set PHY register.\n# Therefore, waiting for COM-e power ready, then start to set PHY register.\nwhile [ \"$COM_E_PWRGD\" == \"0x0\" ];\ndo\n    COM_E_PWRGD=`head -n 1 ${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok`\n    sleep 5\ndone\n\ndevmem_set_bit $(scu_addr 88) 30\ndevmem_set_bit $(scu_addr 88) 31\n\nif [ \"$1\" == \"led\" ]; then\n    echo \"Wait a few seconds to setup management port LED...\"\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x01d\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x3453\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x012\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0xa03\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x019\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x2418\n    echo \"Done!\"\nelif [ \"$1\" == \"combo\" ]; then\n    echo \"Wait a few minutes to setup management combo port...\"\n    ast-mdio.py --mac 1 --phy 0x9 write 0x17 0x0f7e\n    ast-mdio.py --mac 1 --phy 0x9 write 0x15 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x083c\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x2f\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7167\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x21\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7c05\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1140\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x21\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7c04\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x09\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x0200\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x04\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x01e1\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1340\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x234\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0xd18f\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0xb00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1140\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x23e\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7ae2\n    echo 1 > $SFP_AUTO_DETECT\n    echo 0 > $TX_DISABLE\n    echo \"Done!\"\nelif [ \"$1\" == \"all\" ]; then\n    echo \"Wait a few minutes to setup management port...\"\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x01d\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x3453\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x012\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0xa03\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x019\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x2418\n    ast-mdio.py --mac 1 --phy 0x9 write 0x17 0x0f7e\n    ast-mdio.py --mac 1 --phy 0x9 write 0x15 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x083c\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x2f\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7167\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x21\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7c05\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1140\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x21\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7c04\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x09\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x0200\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x04\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x01e1\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1340\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x234\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0xd18f\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0xb00\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x1140\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1e 0x23e\n    ast-mdio.py --mac 1 --phy 0x9 write 0x1f 0x7ae2\n    echo 1 > $SFP_AUTO_DETECT\n    echo 0 > $TX_DISABLE\nelse\n    usage\n    exit -1\nfi\n", "num_lines": 127}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program <Device> <Operation>\"\n    echo \"     <Device>:    th3\"\n    echo \"     <Operation>: read / write\"\n}\n\nif [ $# -ne 2 ]; then\n    usage\n    exit -1\nfi\n\nREG=(0x00 0x01 0x02 0x06 0x07 0x08 0x0A 0x28 \\\n     0x51 0x0E 0x0F 0x10 0x11 0x12 0x15 0x16 \\\n     0x17 0x18 0x19 0x1C 0x1D 0x1E 0x1F 0x20 \\\n     0x23 0x24 0x25 0x26 0x27 0x2B 0x2C 0x2D \\\n     0x2E 0x2F 0x32 0x33 0x34 0x35 0x36 0x39 \\\n     0x3A 0x3B 0x3C 0x3D 0x40 0x41 0x42 0x43 \\\n     0x44 0x03 0x04 0x05 0x09 0x0B 0x0C 0x0D \\\n     0x13 0x14 0x1A 0x1B 0x21 0x22 0x29 0x2A \\\n     0x30 0x31 0x37 0x38 0x3E 0x3F 0x45 0x46 \\\n     0x47 0x48 0x49 0x4A 0x4B 0x4C 0x4D 0x4E \\\n     0x4F 0x50 0x52 0x53 0x54 0x55 0x56 0x57 \\\n     0x58 0x59 0x5A 0x5B 0x5C 0x5D 0x5E 0x5F \\\n     0x60 0x61 \\\n     )\n\nif [ \"$1\" == \"th3\" ]; then\n    VAL=(0x08 0x00 0x00 0x18 0x01 0x00 0xFF 0x0C \\\n         0x44 0x00 0x00 0xAD 0x01 0x00 0x00 0x00 \\\n         0xAD 0x01 0x00 0x00 0x00 0xAD 0x01 0x00 \\\n         0x00 0x00 0xAD 0x01 0x00 0x00 0x00 0xAD \\\n         0x00 0x00 0x00 0x00 0xAD 0x00 0x00 0x00 \\\n         0x00 0xAD 0x00 0x00 0x00 0x00 0xAD 0x00 \\\n         0x00 0x00 0x00 0x00 0x00 0x70 0x00 0x00 \\\n         0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 \\\n         0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x38 \\\n         0x00 0x05 0x00 0x00 0x00 0x00 0x00 0x00 \\\n         0x00 0x00 0x00 0x00 0x00 0x00 0x10 0x44 \\\n         0x21 0x00 0x54 0x54 0x00 0x00 0x00 0x00 \\\n         0x00 0x00 \\\n         )\n    # TH3 PCI-e repeater slave mode\n    echo 0 > ${SCMCPLD_SYSFS_DIR}/iso_th3rp_en\n    echo 1 > ${SCMCPLD_SYSFS_DIR}/a_ds80_ensmb\n    th3_repeater=`i2cdetect -y 21 0x58 0x58 | grep \"\\-\\-\" 2> /dev/null`\n\n    if [ \"${th3_repeater}\" != \"\" ]; then\n        echo \"TH3 PCI-e repeater is not detected\"\n    else\n        if [ \"$2\" == \"write\" ]; then\n            echo -n \"Setup TH3 PCI-e repeater... \"\n            for i in {0..97}; do\n                i2cset -f -y 21 0x58 ${REG[i]} ${VAL[i]} 2> /dev/null\n                usleep 11000\n            done\n            echo \"Done\"\n        elif [ \"$2\" == \"read\" ]; then\n            echo \"Bus:21 Addr:0x58\"\n            for i in {0..97}; do\n                echo -n \"Reg:${REG[i]} Val:\"\n                i2cget -f -y 21 0x58 ${REG[i]} 2> /dev/null\n                if [ $? -ne 0 ]; then\n                    echo \"\"\n                fi\n                usleep 11000\n            done\n        fi\n    fi\nfi\n", "num_lines": 95}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program reset <PIM>\"\n    echo \"     $program data  <PIM> <Operation>\"\n    echo \"     <PIM>: all, 1 ~ 8\"\n    echo \"     <Operation>: enable / disable\"\n}\n\nif [ $# -le 1 ] || [ $# -ge 4 ]; then\n    usage\n    exit -1\nfi\n\n# Bus 80 88 96 104 112 120 128 136   # PIM1 ~ PIM8 FPGA\nif [ \"$2\" == \"all\" ]; then\n    FPGA_BUS=\"80 88 96 104 112 120 128 136\"\nelif [ \"$2\" -ge 1 ] || [ \"$2\" -le 8 ]; then\n    FPGA_BUS=$((($2 - 1) * 8 + 80 ))\nelse\n    usage\n    exit -1 \nfi\n\nif [ \"$1\" == \"reset\" ]; then\n    echo -n \"Reset QSFP ... \"\n    for bus in ${FPGA_BUS}; do\n        i2c_path=$(i2c_device_sysfs_abspath ${bus}-0060)\n        reset=\"${i2c_path}/qsfp_reset\"\n        echo 0xffff > \"${reset}\"\n        usleep 1000\n        echo 0x0 > \"${reset}\"\n    done\n    echo \"Done\"\nelif [ \"$1\" == \"data\" ]; then\n    echo -n \"DOM data collection \"$3\" ... \"\n    for bus in ${FPGA_BUS}; do\n        i2c_path=$(i2c_device_sysfs_abspath ${bus}-0060)\n        config=\"${i2c_path}/dom_ctrl_config\"\n        if [ \"$3\" == \"enable\" ]; then\n            echo 0x5000001 > \"${config}\"\n        elif [ \"$3\" == \"disable\" ]; then\n            echo 0xf00 > \"${config}\"\n        else\n            usage\n            exit -1\n        fi\n    done\n    echo \"Done\"\nelse\n    usage\n    exit -1\nfi\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_sensors_conf.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup lm-sensors config\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKERNEL_VERSION=$(uname -r)\nSENSORS_CONF_PATH=\"/etc/sensors.d\"\nFCM_T_BOARD_REV=$(head -n1 \"$TOP_FCMCPLD_SYSFS_DIR\"/board_ver)\nFCM_B_BOARD_REV=$(head -n1 \"$BOTTOM_FCMCPLD_SYSFS_DIR\"/board_ver)\n\n# In kernel version 4.1.x -\n# pmbus_core.c use milliwatt for direct format power output,\n# so we need to multiply power output by 1000.\n# In higher kernel version -\n# pmbus_core.c use microwatt for direct format power output,\n# so we need to multiply power output by 1.\nif [[ \"$KERNEL_VERSION\" != 4.1.* ]]; then\n    div=1\nelse\n    div=1000\nfi\n\nsed -i \"s/power_factor/$div/g\" \"$SENSORS_CONF_PATH\"/custom/*.conf\ncp \"$SENSORS_CONF_PATH\"/custom/adm1278-SCM.conf \"$SENSORS_CONF_PATH\"/scm.conf\n\n# Config FCM Rsense value at different hardware version.\n# Kernel driver use Rsense equal to 1 milliohm. We need to correct Rsense\n# value, and all value are from hardware team.\nif [ \"$FCM_T_BOARD_REV\" = \"0x4\" ] || [ \"$FCM_T_BOARD_REV\" = \"0x5\" ]; then\n    # For R0D or R01 FCM\n    fcm_t_rsense=2.651\nelif [ \"$FCM_T_BOARD_REV\" = \"0x7\" ] || [ \"$FCM_T_BOARD_REV\" = \"0x2\" ]; then\n    # For R0A, R0B or R0C FCM\n    fcm_t_rsense=3.03\nelse\n    # Default, keep Rsense to 1, if we have new FCM version, we can use default\n    # Rsense value as a base to correct real value.\n    fcm_t_rsense=1\nfi\n\n# Config FCM Rsense value at different hardware version.\n# Kernel driver use Rsense equal to 1 milliohm. We need to correct Rsense\n# value, and all value are from hardware team.\nif [ \"$FCM_B_BOARD_REV\" = \"0x4\" ] || [ \"$FCM_B_BOARD_REV\" = \"0x5\" ]; then\n    # For R0D or R01 FCM\n    fcm_b_rsense=2.659\nelif [ \"$FCM_B_BOARD_REV\" = \"0x7\" ] || [ \"$FCM_B_BOARD_REV\" = \"0x2\" ]; then\n    # For R0A, R0B or R0C FCM\n    fcm_b_rsense=3.03\nelse\n    # Default, keep Rsense to 1, if we have new FCM version, we can use default\n    # Rsense value as a base to correct real value.\n    fcm_b_rsense=1\nfi\n\nsed \"s/rsense/$fcm_t_rsense/g\" \"$SENSORS_CONF_PATH\"/custom/adm1278-FCM-T.conf \\\n> \"$SENSORS_CONF_PATH\"/fcm-t.conf\n\nsed \"s/rsense/$fcm_b_rsense/g\" \"$SENSORS_CONF_PATH\"/custom/adm1278-FCM-B.conf \\\n> \"$SENSORS_CONF_PATH\"/fcm-b.conf\n", "num_lines": 88}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program all <Operation>\"\n    echo \"     $program <PIM> <Operation>\"\n    echo \"     <PIM>: 1 ~ 8\"\n    echo \"     <Operation>: load / unload\"\n}\n\nif [ $# -ne 2 ]; then\n    usage\n    exit -1\nfi\n\ncount=0\n\n# Bus 80 88 96 104 112 120 128 136   # PIM1 ~ PIM8 FPGA\n# Bus 82 90 98 106 114 122 130 138   # PIM1 ~ PIM8 temp. sensor\n# Bus 83 91 99 107 115 123 131 139   # PIM1 ~ PIM8 temp. sensor\n# Bus 84 92 100 108 116 124 132 140  # PIM1 ~ PIM8 Hotswap\n# Bus 86 94 102 110 118 126 134 142  # PIM1 ~ PIM8 MAX34461\nif [ \"$1\" == \"all\" ]; then\n    FPGA_BUS=\"80 88 96 104 112 120 128 136\"\nelse\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 9 ]; then\n        echo \"PIM$1: not a valid PIM Unit\"\n        exit -1\n    fi\n    FPGA_BUS=$((($1 - 1) * 8 + 80 ))\nfi\n\nif [ \"$2\" == \"unload\" ]; then\n    for bus in ${FPGA_BUS}; do\n        i2c_device_delete $(($bus + 4)) 0x10 2> /dev/null\n        i2c_device_delete $(($bus + 6)) 0x74 2> /dev/null\n        i2c_device_delete $(($bus + 2)) 0x48 2> /dev/null\n        i2c_device_delete $(($bus + 3)) 0x4b 2> /dev/null\n    done\nelif [ \"$2\" == \"load\" ]; then\n    #Sleep to avoid mount max34461 fail.\n    #It needs 3~4 seconds to initialize.\n    #Thus, we sleep 5 seconds to be on the save side.\n    sleep 5\n    for bus in ${FPGA_BUS}; do\n        i2c_device_add $(($bus + 4)) 0x10 adm1278 2> /dev/null\n        i2c_device_add $(($bus + 2)) 0x48 tmp75 2> /dev/null\n        i2c_device_add $(($bus + 3)) 0x4b tmp75 2> /dev/null\n\n        dev_sysfs_dir=$(i2c_device_sysfs_abspath $bus-0060)\n        pim_type=$(head -n1 \"${dev_sysfs_dir}\"/board_ver 2> /dev/null)\n        if [ \"${pim_type}\" == \"0x0\" ]; then   #PIM16Q\n            i2c_device_add $(($bus + 6)) 0x74 max34461 2> /dev/null\n        elif [ \"${pim_type}\" == \"0xf0\" ]; then #PIM16O\n            i2c_device_add $(($bus + 6)) 0x74 max34460 2> /dev/null\n        elif [ \"${pim_type}\" == \"0x10\" ]; then #PIM4DD\n            i2c_device_add $(($bus + 6)) 0x74 max34461 2> /dev/null\n        else\n            echo \"DOMFPGA is not detected or PIM $num is not inserted\"\n        fi\n    done\nelse\n    echo \"Wrong operation\"\n    usage\n    exit -1\nfi\n", "num_lines": 89}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Set all IO direction to output\ni2cset -f -y 50 0x20 0x06 0x00\ni2cset -f -y 50 0x20 0x07 0x00\n\nIO0=`i2cget -f -y 50 0x20 0x2`\nIO1=`i2cget -f -y 50 0x20 0x3`\n\ncolor=$2\n\nusage(){\n    program=`basename \"$0\"`\n    echo \"Usage:\"\n    echo \"     $program <dev> <color>\"\n    echo \"\"\n    echo \"     <dev>: sys/smb/psu/fan\"\n    echo \"     <color>: off/red/blue/yellow\"\n}\n\ncase $color in\n    \"red\")\n        val=0x6\n    ;;\n    \"blue\")\n        val=0x3\n    ;;\n    \"yellow\")\n        val=0x4\n    ;;\n    \"off\")\n        val=0x7\n    ;;\n    *)\n    usage\n    exit -1\n    ;;\nesac\n\nif [ \"$3\" == \"0\" ] || [ \"$3\" == \"4\" ]; then\n\n  if [ \"$1\" == \"smb\" ] || [ \"$1\" == \"psu\" ]; then\n    val=$(($val << 3))\n    IO0_VAL=$((($IO0 & 0x7) | $val))\n    IO1_VAL=$((($IO1 & 0x7) | $val))\n  elif [ \"$1\" == \"sys\" ] || [ \"$1\" == \"fan\" ]; then\n    IO0_VAL=$((($IO0 & 0x38) | $val))\n    IO1_VAL=$((($IO1 & 0x38) | $val))\n  else\n    usage\n    exit -1\n  fi\n\n  if [ \"$1\" == \"psu\" ] || [ \"$1\" == \"fan\" ]; then\n    i2cset -f -y 50 0x20 0x2 $IO0_VAL\n  else\n    i2cset -f -y 50 0x20 0x3 $IO1_VAL\n  fi\n\nelse \n\n  if [ \"$1\" == \"fan\" ] || [ \"$1\" == \"smb\" ]; then\n    val=$(($val << 3))\n    IO0_VAL=$((($IO0 & 0x7) | $val))\n    IO1_VAL=$((($IO1 & 0x7) | $val))\n  elif [ \"$1\" == \"sys\" ] || [ \"$1\" == \"psu\" ]; then\n    IO0_VAL=$((($IO0 & 0x38) | $val))\n    IO1_VAL=$((($IO1 & 0x38) | $val))\n  else\t\n    usage\n    exit -1\n  fi\n\n  if [ \"$1\" == \"sys\" ] || [ \"$1\" == \"fan\" ]; then\n    i2cset -f -y 50 0x20 0x2 $IO0_VAL\n  else\n    i2cset -f -y 50 0x20 0x3 $IO1_VAL\n  fi\n\nfi\n\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nif [ $# -ne 1 ]; then\n    exit -1\nfi\n\nimg=\"$1\"\n\nsource /usr/local/bin/openbmc-utils.sh\n\ntrap 'gpio_set_value BMC_SYSCPLD_JTAG_MUX_SEL 0; \\\n      rm -rf /tmp/smbcpld_update' INT TERM QUIT EXIT\n\n# change BMC_SYSCPLD_JTAG_MUX_SEL to 1 to connect BMC to SMB CPLD pins\ngpio_set_value BMC_SYSCPLD_JTAG_MUX_SEL 1\n\necho 1 > /tmp/smbcpld_update\n\nispvm dll /usr/lib/libcpldupdate_dll_gpio.so \"${img}\" \\\n    --tms BMC_CPLD_TMS \\\n    --tdo BMC_CPLD_TDO \\\n    --tdi BMC_CPLD_TDI \\\n    --tck BMC_CPLD_TCK\nresult=$?\n# 1 is returned upon upgrade success\nif [ $result -eq 1 ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    exit 1\nfi\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS0\n\nmTerm_server_running() {\n  pid=$(ps w | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ $pid ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -a $FILE ]\n    then\n      read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 $TTY\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/bin/flashrom-utils.sh\n\npca9534_ee_sel=0x22\npca9534_spi_sel=0x26\noutput_reg=0x1\nmode_reg=0x3\ndebug=0\nm95m02_page_size=256\nm95m02_page_count=1024\nSPI_PIN_ARGS=(--cs BMC_SPI1_CS0 --clk BMC_SPI1_CLK \\\n              --mosi BMC_SPI1_MOSI --miso BMC_SPI1_MISO)\nPIDFILE=/var/run/spi_util.pid\n\ntrap cleanup_spi INT TERM QUIT EXIT\n\ncheck_duplicate_process() {\n    exec 2> \"$PIDFILE\"\n    flock -n 2 || (echo \"Another process is running...\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 2\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n\nremove_pid_file() {\n    if [ -f $PIDFILE ]; then\n        rm $PIDFILE\n    fi\n}\n\n# $1: sysfs path, $2: value\nset_sysfs_value() {\n    local path=$1\n    local val=$2\n    local ret_val=-1\n    local retry=3\n\n    while [ \"$((ret_val))\" != \"$((val))\" ] && [ \"$retry\" -gt 0 ];\n    do\n        echo \"$val\" > \"$path\"\n        usleep 100\n        ret_val=$(head -n1 \"$path\" 2> /dev/null)\n        retry=$((retry - 1))\n    done\n    if [ \"$((ret_val))\" != \"$((val))\" ]; then\n        echo \"Set sysfs value fail\"\n        echo \"debug cmd: echo $val > $path, ret_val=$ret_val\"\n        exit 1\n    fi\n}\n\n# $1: bus number, $2: device address, $3: register, $4: value\nset_i2c_dev_value() {\n    local bus=$1\n    local addr=$2\n    local reg=$3\n    local val=$4\n    local ret_val=-1\n    local retry=3\n\n    while [ \"$((ret_val))\" != \"$((val))\" ] && [ \"$retry\" -gt 0 ];\n    do\n        exec_and_print \"i2cset -y $bus $addr $reg $val\"\n        usleep 100\n        ret_val=$(i2cget -y \"$bus\" \"$addr\" \"$reg\" 2> /dev/null)\n        retry=$((retry - 1))\n    done\n    if [ \"$((ret_val))\" != \"$((val))\" ]; then\n        echo \"Set I2C device value fail\"\n        echo \"debug cmd: i2cset -y $bus $addr $reg $val, ret_val: $ret_val\"\n        exit 1\n    fi\n}\n\n# $1: input file size $2: flash size $3: output file path\npad_ff() {\n    out_file=$3\n    pad_size=$(($2 - $1))\n    dd if=/dev/zero bs=\"$pad_size\" count=1 | tr \"\\000\" \"\\377\" >> \"$out_file\"\n}\n\nresize_file() {\n    in_file=$1\n    out_file=$2\n    spi_no=$3\n    storage_type=$4\n    in_file_sz=$(stat -c%s \"$in_file\")\n    storage_sz=0\n    if [ \"$storage_type\" ] && [ \"$storage_type\" = \"m95m02\" ]; then\n        storage_sz=$((m95m02_page_count * m95m02_page_size))\n    else\n        spi_dev=$(flash_device_name \"$spi_no\" 0)\n        flash_sz=$(flash_get_size \"$spi_dev\")\n        ret=$?\n        if [ \"$ret\" -eq 0 ]; then\n            storage_sz=$((flash_sz * 1024))\n        else\n            echo \"Get flash size error: [$flash_sz]\"\n            exit 1\n        fi\n    fi\n\n    if [ \"$in_file_sz\" -ne \"$storage_sz\" ]; then\n        cp \"$in_file\" \"$out_file\"\n        pad_ff \"$in_file_sz\" \"$storage_sz\" \"$out_file\"\n    else\n        ln -s \"$(realpath \"$in_file\")\" \"$out_file\"\n    fi\n}\n\ndump_gpio_config() {\n    if [ \"$debug\" = 0 ]; then\n        return 0\n    fi\n    echo \"Dump SPI configurations...\"\n    if [ \"$1\" = \"SPI1\" ]; then\n        openbmc_gpio_util.py dump | grep SPI1\n    else\n        openbmc_gpio_util.py dump | grep SPI2\n    fi\n}\n\n# currently only BCM5396 EEPROM\nset_spi1_to_gpio() {\n    devmem_set_bit \"$(scu_addr 7C)\" 12\n    devmem_set_bit \"$(scu_addr 7C)\" 13\n    devmem_set_bit \"$(scu_addr 80)\" 15\n    gpio_set_direction BMC_SPI1_CLK out\n    gpio_set_direction BMC_SPI1_CS0 out\n    gpio_set_direction BMC_SPI1_MISO in\n    gpio_set_direction BMC_SPI1_MOSI out\n    dump_gpio_config SPI1\n}\n\nset_spi1_to_spi() {\n    devmem_set_bit \"$(scu_addr 70)\" 12\n    dump_gpio_config SPI1\n}\n\n# currently no use\nset_spi2_to_spi_cs() {\n    cs=$1\n    if [ \"$cs\" = 0 ]; then\n        # spi2 cs0\n        devmem_set_bit \"$(scu_addr 88)\" 26\n        devmem_set_bit \"$(scu_addr 88)\" 27\n        devmem_set_bit \"$(scu_addr 88)\" 28\n        devmem_set_bit \"$(scu_addr 88)\" 29\n    else\n        # spi2 cs1\n        devmem_set_bit \"$(scu_addr 8C)\" 0\n        devmem_set_bit \"$(scu_addr 88)\" 27\n        devmem_set_bit \"$(scu_addr 88)\" 28\n        devmem_set_bit \"$(scu_addr 88)\" 29\n    fi\n    dump_gpio_config SPI2\n}\n\nread_flash_to_file() {\n    spi_no=$1\n    file=$2\n    spi_dev=$(flash_device_name \"$spi_no\" 0)\n\n    modprobe -r spidev\n    modprobe spidev\n    type=$(flash_get_model \"$spi_dev\")\n    flashrom -p linux_spi:dev=/dev/\"$spi_dev\" -r \"$file\" -c \"$type\"\n    ret=$?\n    if [ \"$ret\" -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/$spi_dev -r $file -c $type]\"\n        exit 1\n    fi\n}\n\nwrite_flash_to_file() {\n    spi_no=$1\n    in_file=$2\n    out_file=\"/tmp/${3}_spi${1}_tmp\"\n    spi_dev=$(flash_device_name \"$spi_no\" 0)\n\n    modprobe -r spidev\n    modprobe spidev\n    resize_file \"$in_file\" \"$out_file\" \"$spi_no\"\n    type=$(flash_get_model \"$spi_dev\")\n    flashrom -p linux_spi:dev=/dev/\"$spi_dev\" -w \"$out_file\" -c \"$type\"\n    ret=$?\n    if [ \"$ret\" -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/$spi_dev -w $out_file -c $type]\"\n        exit 1\n    fi\n}\n\nerase_flash() {\n    spi_no=$1\n    spi_dev=$(flash_device_name \"$spi_no\" 0)\n\n    modprobe -r spidev\n    modprobe spidev\n    type=$(flash_get_model \"$spi_dev\")\n    flashrom -p linux_spi:dev=/dev/\"$spi_dev\" -E -c \"$type\"\n    ret=$?\n    if [ \"$ret\" -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/$spi_dev -E -c $type]\"\n        exit 1\n    fi\n}\n\nread_m95m02_to_file() {\n    spi_no=$1\n    file=$2\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    dd if=\"$eeprom_node\" of=\"$file\" count=\"$m95m02_page_count\" bs=\"$m95m02_page_size\"\n}\n\nwrite_m95m02() {\n    spi_no=$1\n    file=$2\n    out_file=\"/tmp/${3}_spi${1}_tmp\"\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    tr '\\0' '\\377' < /dev/zero | dd count=\"$m95m02_page_count\" bs=\"$m95m02_page_size\" of=\"$eeprom_node\"\n    resize_file \"$file\" \"$out_file\" \"$spi_no\" 'm95m02'\n    dd of=\"$eeprom_node\" if=\"$out_file\" count=\"$m95m02_page_count\" bs=\"$m95m02_page_size\"\n}\n\nerase_m95m02() {\n    spi_no=$1\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    tr '\\0' '\\377' < /dev/zero | dd count=\"$m95m02_page_count\" bs=\"$m95m02_page_size\" of=\"$eeprom_node\"\n}\n\nread_spi1_dev() {\n    spi_no=1\n    dev=$1\n    file=$2\n    case \"$dev\" in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BACKUP_BIOS\" | \"IOB_FPGA_FLASH\" | \"TH3_FLASH\")\n            read_flash_to_file \"$spi_no\" \"$file\"\n        ;;\n        \"BCM5396_EE\")\n            echo \"Reading BCM5396 eeprom to $file...\"\n            at93cx6_util_py3.py \"${SPI_PIN_ARGS[@]}\" chip read --file \"$file\"\n        ;;\n    esac\n}\n\nwrite_spi1_dev() {\n    spi_no=1\n    dev=$1\n    file=$2\n    case \"$dev\" in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BACKUP_BIOS\" | \"IOB_FPGA_FLASH\" | \"TH3_FLASH\")\n            write_flash_to_file \"$spi_no\" \"$file\" \"$dev\"\n        ;;\n        \"BCM5396_EE\")\n            echo \"Writing $file to BCM5396 eeprom...\"\n            at93cx6_util_py3.py \"${SPI_PIN_ARGS[@]}\" chip write --file \"$file\"\n        ;;\n    esac\n}\n\nerase_spi1_dev() {\n    spi_no=1\n    dev=$1\n    file=$2\n    case \"$dev\" in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BACKUP_BIOS\" | \"IOB_FPGA_FLASH\" | \"TH3_FLASH\")\n            erase_flash \"$spi_no\"\n        ;;\n        \"BCM5396_EE\")\n            echo \"Erasing BCM5396 eeprom...\"\n            at93cx6_util_py3.py \"${SPI_PIN_ARGS[@]}\" chip erase\n        ;;\n    esac\n}\n\nset_smb_cpld_spi_1b() {\n    if [ \"$#\" = 3 ]; then\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_1_b0 \"$3\"\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_1_b1 \"$2\"\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_1_b2 \"$1\"\n    else\n        echo \"Set SPI1 BIT FAILED\"\n    fi\n}\n\nconfig_spi1_pin_and_path() {\n    dev=$1\n\n    echo \"Select SPI1 Device: $dev\"\n    case \"$dev\" in\n        \"BACKUP_BIOS\")\n            set_spi1_to_spi\n            set_smb_cpld_spi_1b 0 1 1\n            set_sysfs_value \"$SCMCPLD_SYSFS_DIR\"/iso_spi_en 0\n            set_sysfs_value \"$SCMCPLD_SYSFS_DIR\"/com_spi_oe_n 0\n            set_sysfs_value \"$SCMCPLD_SYSFS_DIR\"/com_spi_sel 1\n        ;;\n        \"IOB_FPGA_FLASH\")\n            set_spi1_to_spi\n            set_smb_cpld_spi_1b 0 0 0\n            set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/fpga_spi_mux_sel 1\n        ;;\n        \"TH3_FLASH\")\n            set_spi1_to_spi\n            set_smb_cpld_spi_1b 0 0 1\n            set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/th3_spi_mux_sel 1\n        ;;\n        \"BCM5396_EE\")\n            set_spi1_to_gpio\n            set_smb_cpld_spi_1b 0 1 0\n            set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/cpld_bcm5396_mux_sel 1\n            gpio_set_value BMC_BCM5396_MUX_SEL 1\n        ;;\n        *)\n            echo \"Please enter {IOB_FPGA_FLASH, TH3_FLASH, BCM5396_EE, BACKUP_BIOS}\"\n            exit 1\n        ;;\n    esac\n    echo \"Config SPI1 Done.\"\n}\n\nconfig_spi2_pin_and_path() {\n    pim=$1\n    dev=$2\n    pim_no=${pim:3:3}\n    bus=$(((pim_no-1)*8 + 85))\n    echo \"Select SPI2 Device: PIM$pim_no $dev\"\n    config_spi2_pim_path \"$pim_no\" \"$dev\"\n    config_spi2_pim_dev_path \"$bus\" \"$dev\"\n    echo \"Config SPI2 Done.\"\n}\n\nset_smb_cpld_spi_2b() {\n    if [ \"$#\" = 4 ]; then\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_2_b0 \"$4\"\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_2_b1 \"$3\"\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_2_b2 \"$2\"\n        set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/spi_2_b3 \"$1\"\n    else\n        echo \"Set SPI2 BIT FAILED\"\n    fi\n}\n\nconfig_spi2_pim_path() {\n    pim_no=$1\n    local dev=$2\n    dev=${dev:0:3}  # Detect PHY EEPROM to change CS1\n    # Not PHY means CS0 FPGA, else CS1 PHY#_EE\n    case \"$pim_no\" in\n        \"1\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 0 0 0\n            else\n                set_smb_cpld_spi_2b 1 0 0 0\n            fi\n        ;;\n        \"2\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 0 0 1\n            else\n                set_smb_cpld_spi_2b 1 0 0 1\n            fi\n        ;;\n        \"3\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 0 1 0\n            else\n                set_smb_cpld_spi_2b 1 0 1 0\n            fi\n        ;;\n        \"4\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 0 1 1\n            else\n                set_smb_cpld_spi_2b 1 0 1 1\n            fi\n        ;;\n        \"5\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 1 0 0\n            else\n                set_smb_cpld_spi_2b 1 1 0 0\n            fi\n        ;;\n        \"6\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 1 0 1\n            else\n                set_smb_cpld_spi_2b 1 1 0 1\n            fi\n        ;;\n        \"7\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 1 1 0\n            else\n                set_smb_cpld_spi_2b 1 1 1 0\n            fi\n        ;;\n        \"8\")\n            if [ \"$dev\" != \"PHY\" ]; then\n                set_smb_cpld_spi_2b 0 1 1 1\n            else\n                set_smb_cpld_spi_2b 1 1 1 1\n            fi\n        ;;\n        *)\n            exit 1\n        ;;\n    esac\n}\n\nexec_and_print() {\n    if [ \"$debug\" = 1 ]; then\n        echo \"$1\"\n    fi\n    $1\n}\n\ndetect_pca9534() {\n    bus=$1\n    dev_addr=$2\n    dev_no=${dev_addr:2:3}\n    i2cdetect -y \"$bus\" \"$dev_addr\" \"$dev_addr\" | grep \"$dev_no\" > /dev/null\n}\n\nconfig_spi2_pim_dev_path() {\n    bus=$1\n    dev=$2\n\n    # Configure output pin(0) to [0:2] 1111 1000 -> 0xf8\n    spi_sel_output_bit=0xf8\n    # Configure output pin(0) to [1:5] 1100 0001 -> 0xc1\n    ee_sel_output_bit=0xc1\n\n    detect_pca9534 \"$bus\" \"$pca9534_spi_sel\"\n    spi_sel_ret=$?\n    detect_pca9534 \"$bus\" \"$pca9534_ee_sel\"\n    ee_sel_ret=$?\n    if [ \"$spi_sel_ret\" != 0 ]; then\n        echo \"Cannot detect I2C device bus[$bus] addr[$pca9534_spi_sel]\"\n        exit 1\n    elif [ \"$ee_sel_ret\" != 0 ]; then\n        echo \"Cannot detect I2C device bus[$bus] addr[$pca9534_ee_sel]\"\n        exit 1\n    fi\n\n    i2c_ret=$(i2cget -y \"$bus\" \"$pca9534_spi_sel\" \"$mode_reg\")\n    if [ \"$i2c_ret\" = \"\" ]; then\n        echo \"Cannot read bus:$bus addr:$pca9534_spi_sel\"\n        exit 1\n    fi\n    # Current value and with 0xf8\n    config_val=$(printf \"0x%x\" $((spi_sel_output_bit & \"$i2c_ret\")))\n    set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$mode_reg\" \"$config_val\"\n\n    i2c_ret=$(i2cget -y \"$bus\" \"$pca9534_ee_sel\" \"$mode_reg\")\n    if [ \"$i2c_ret\" = \"\" ]; then\n        echo \"Cannot read bus:$bus addr:$pca9534_ee_sel\"\n        exit 1\n    fi\n    config_val=$(printf \"0x%x\" $((ee_sel_output_bit & \"$i2c_ret\")))\n    set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$mode_reg\" \"$config_val\"\n\n    read_spi_sel_val=$(i2cget -y \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\")\n    read_spi_sel_val=$((read_spi_sel_val | 0x7))\n\n    read_spi_ee_val=$(i2cget -y \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\")\n    read_spi_ee_val=$((read_spi_ee_val | 0x3e))\n\n    case \"$dev\" in\n        \"PHY1_EE\")\n            set_spi2_to_spi_cs 1\n            write_val=$(printf \"0x%x\" $((read_spi_sel_val & 0xf8)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\" \"$write_val\"\n            write_val=$(printf \"0x%x\" $((read_spi_ee_val & 0xfb)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_val\"\n        ;;\n        \"PHY2_EE\")\n            set_spi2_to_spi_cs 1\n            write_val=$(printf \"0x%x\" $((read_spi_sel_val & 0xf9)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\" \"$write_val\"\n            write_val=$(printf \"0x%x\" $((read_spi_ee_val & 0xf7)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_val\"\n        ;;\n        \"PHY3_EE\")\n            set_spi2_to_spi_cs 1\n            write_val=$(printf \"0x%x\" $((read_spi_sel_val & 0xfa)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\" \"$write_val\"\n            write_val=$(printf \"0x%x\" $((read_spi_ee_val & 0xef)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_val\"\n        ;;\n        \"PHY4_EE\")\n            set_spi2_to_spi_cs 1\n            write_val=$(printf \"0x%x\" $((read_spi_sel_val & 0xfb)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\" \"$write_val\"\n            write_val=$(printf \"0x%x\" $((read_spi_ee_val & 0xdf)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_val\"\n        ;;\n        \"DOM_FPGA_FLASH\")\n            set_spi2_to_spi_cs 0\n            write_val=$(printf \"0x%x\" $((read_spi_sel_val & 0xfc)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_spi_sel\" \"$output_reg\" \"$write_val\"\n            write_val=$(printf \"0x%x\" $((read_spi_ee_val & 0xfd)))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_val\"\n        ;;\n        *)\n            echo \"Please enter with {PHY#_EE, DOM_FPGA_FLASH}\"\n            exit 1\n        ;;\n    esac\n}\n\nread_spi2_dev() {\n    spi_no=2\n    dev=$1\n    file=$2\n\n    case \"$dev\" in\n        \"PHY\"[1-4]\"_EE\")\n            # M95M02 EEPROM\n            echo \"Reading PHY eeprom to $file...\"\n            read_m95m02_to_file \"$spi_no\" \"$file\"\n        ;;\n        \"DOM_FPGA_FLASH\")\n            # W25Q32\n            read_flash_to_file \"$spi_no\" \"$file\"\n        ;;\n        *)\n            echo \"SPI2 without this device [$dev]\"\n        ;;\n    esac\n}\n\nwrite_spi2_dev() {\n    spi_no=2\n    dev=$1\n    case \"$dev\" in\n        \"PHY\"[1-4]\"_EE\")\n            # M95M02 EEPROM\n            echo \"Writing $file to PHY eeprom...\"\n            write_m95m02 \"$spi_no\" \"$file\" \"$dev\"\n        ;;\n        \"DOM_FPGA_FLASH\")\n            # W25Q32\n            write_flash_to_file \"$spi_no\" \"$file\" \"$dev\"\n        ;;\n        *)\n            echo \"SPI2 without this device [$dev]\"\n        ;;\n    esac\n}\n\nerase_spi2_dev() {\n    spi_no=2\n    dev=$1\n    case \"$dev\" in\n        \"PHY\"[1-4]\"_EE\")\n            # M95M02 EEPROM\n            echo \"Erasing PHY eeprom...\"\n            erase_m95m02 \"$spi_no\"\n        ;;\n        \"DOM_FPGA_FLASH\")\n            # W25Q32\n            erase_flash \"$spi_no\"\n        ;;\n        *)\n            echo \"SPI2 without this device [$dev]\"\n        ;;\n    esac\n}\n\noperate_spi1_dev() {\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case \"$op\" in\n        \"read\")\n                read_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                write_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi1_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n}\n\noperate_spi2_dev() {\n    op=$1\n    dev=$2\n    file=$3\n\t## Operate devices ##\n    case \"$op\" in\n        \"read\")\n                read_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                write_spi2_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi2_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n}\n\ncleanup_spi() {\n    if [ \"$?\" -eq 2 ]; then\n        exit 1\n    fi\n\n    set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/fpga_spi_mux_sel 0\n    set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/th3_spi_mux_sel 0\n    set_sysfs_value \"$SMBCPLD_SYSFS_DIR\"/cpld_bcm5396_mux_sel 0\n    set_sysfs_value \"$SCMCPLD_SYSFS_DIR\"/com_spi_sel 0\n\n    for i in {1..8}\n    do\n        bus=$(((i-1)*8 + 85))\n        detect_pca9534 \"$bus\" \"$pca9534_ee_sel\"\n        ret=$?\n        if [ \"$ret\" = 0 ]; then\n            read_spi_ee_val=$(i2cget -y \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\")\n            write_ee_val=$((read_spi_ee_val | 0x3e))\n            set_i2c_dev_value \"$bus\" \"$pca9534_ee_sel\" \"$output_reg\" \"$write_ee_val\"\n        fi\n    done\n    rm -rf /tmp/*_spi*_tmp\n    remove_pid_file \"$SPI_INF\"\n}\n\nui() {\n    op=$1\n    spi=$2\n\n    # SPI 1.0 speed\n    devmem 0x1e630010 32 0x407\n    # SPI 2.0 speed\n    devmem 0x1e631010 32 0x407\n    # SPI 2.1 speed\n    devmem 0x1e631014 32 0x2007\n\t## Open the path to device ##\n    case \"$spi\" in\n        \"spi1\")\n            dev=$3\n            file=$4\n            config_spi1_pin_and_path \"$dev\"\n            operate_spi1_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        \"spi2\")\n            pim=$3\n            dev=$4\n            file=$5\n            config_spi2_pin_and_path \"$pim\" \"$dev\"\n            operate_spi2_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        *)\n            echo \"No such SPI bus.\"\n            exit 1\n        ;;\n    esac\n}\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <op> spi1 <spi1 device> <file>\"\n    echo \"$program <op> spi2 <pim#> <spi2 device> <file>\"\n    echo \"  <op>          : read, write, erase\"\n    echo \"  <spi1 device> : IOB_FPGA_FLASH, TH3_FLASH, BCM5396_EE, BACKUP_BIOS\"\n    echo \"  <pim#>        : PIM1, PIM2, PIM3, PIM4, PIM5, PIM6, PIM7, PIM8\"\n    echo \"  <spi2 device> : PHY1_EE, PHY2_EE, PH3_EE, PHY4_EE, DOM_FPGA_FLASH\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program write spi1 IOB_FPGA_FLASH iob.bit\"\n    echo \"  $program read spi2 PIM1 PHY1_EE image.bin\"\n    echo \"  $program erase spi2 PIM1 DOM_FPGA_FLASH\"\n    echo \"\"\n}\n\ncheck_parameter() {\n    program=$(basename \"$0\")\n    op=$1\n    spi=$2\n    case \"$op\" in\n        \"read\" | \"write\" | \"erase\")\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n    if [ \"$spi\" ] && [ \"$spi\" = \"spi1\" ]; then\n        dev=$3\n        file=$4\n        ## Check device\n        case \"$dev\" in\n            \"IOB_FPGA_FLASH\" | \"TH3_FLASH\" | \"BCM5396_EE\" | \"BACKUP_BIOS\")\n                ## Check operation\n                case \"$op\" in\n                    \"read\" | \"write\")\n                        if [ \"$#\" -ne 4 ]; then\n                            return 1\n                        fi\n                        ;;\n                    \"erase\")\n                        if [ \"$#\" -ne 3 ]; then\n                            return 1\n                        fi\n                        ;;\n                esac\n                ;;\n            *)\n                return 1\n                ;;\n        esac\n    elif [ \"$spi\" ] && [ \"$spi\" = \"spi2\" ]; then\n        pim=$3\n        dev=$4\n        file=$5\n        ## Check device\n        case ${pim} in\n            \"PIM\"[1-8])\n                case \"$dev\" in\n                    \"PHY\"[1-4]\"_EE\" | \"DOM_FPGA_FLASH\")\n                        ## Check operation\n                        case \"$op\" in\n                            \"read\" | \"write\")\n                                if [ \"$#\" -ne 5 ]; then\n                                    return 1\n                                fi\n                                ;;\n                            \"erase\")\n                                if [ \"$#\" -ne 4 ]; then\n                                    return 1\n                                fi\n                                ;;\n                        esac\n                        ;;\n                    *)\n                        return 1\n                        ;;\n                esac\n                ;;\n            *)\n                return 1\n                ;;\n        esac\n    else\n        return 1\n    fi\n\n    return 0\n}\n\ncheck_duplicate_process\ncheck_parameter \"$@\"\nis_par_ok=$?\n\nif [ \"$is_par_ok\" -eq 0 ]; then\n    ui \"$@\"\nelse\n    usage\n    exit 2\nfi\n", "num_lines": 804}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\n# GPIOS5 (32) controls if uS console connects to UART5 or not.\n# To enable GPIOS5, SCU8C[5] must be 0\ndevmem_clear_bit $(scu_addr 8C) 5\n\ngpio_set_value BMC_UART_SEL5 \"$VALUE\"\n", "num_lines": 46}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\nboard_rev=$(wedge_board_rev)\n\nPWR_USRV_RST_SYSFS=\"${SCMCPLD_SYSFS_DIR}/iso_com_rst_n\"\nPWR_L_CYCLE_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_R_CYCLE_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_L_TIMER_BASE_1S_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_R_TIMER_BASE_1S_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_L_TIMER_BASE_10S_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_R_TIMER_BASE_10S_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_L_TIMER_COUNTER_SETTING_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_R_TIMER_COUNTER_SETTING_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${LEFT_PDBCPLD_SYSFS_DIR}/timer_counter_setting_update\"\nPWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${RIGHT_PDBCPLD_SYSFS_DIR}/timer_counter_setting_update\"\nSCM_CPLD_BUS=16\nPIM_CPLD_BUS=(84 92 100 108 116 124 132 140)\nCPLD_ADDR=0x10\nCPLD_RESET_CMD=0xd9\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole minipack system ungracefully\"\n    echo \"      -s -t [1-2550]: Setting boot up time.\"\n    echo \"            From 1 to 249 the step is 1 second.\"\n    echo \"            From 250 to 2550 the step is 10 seconds\"\n    echo \"            and don't care ones-digits.\"\n    echo\n    echo \"  pimreset: Power-cycle one or all PIM(s)\"\n    echo \"    options:\"\n    echo \"      -a  : Reset all PIMs or \"\n    echo \"      -2 , -3 , ... , -9 : Reset a single PIM (2, 3 ... 9) \"\n    echo\n}\n\nmain_power_status() {\n    return 0\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on_com_e() {\n    echo 1 > $PWR_USRV_SYSFS\n    return $?\n}\n\ndo_on_main_pwr() {\n    # minipack com-e main power is controlled by SCMCPLD\n    return 0\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # power on sequence\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n\tlogger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    echo 0 > $PWR_USRV_SYSFS\n    return $?\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_config_reset_timer() {\n    # Check numeric\n    wake_t=$1\n    echo $wake_t | egrep -q '^[0-9]+$'\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        usage\n        exit -1\n    else\n        if [ $wake_t -ge 1 -a $wake_t -lt 250 ];then\n            echo 1 > $PWR_L_TIMER_BASE_1S_SYSFS\n            echo 1 > $PWR_R_TIMER_BASE_1S_SYSFS\n            echo 0 > $PWR_L_TIMER_BASE_10S_SYSFS\n            echo 0 > $PWR_R_TIMER_BASE_10S_SYSFS\n            logger \"Waiting $wake_t seconds for the system boot up\"\n            echo \"Waiting $wake_t seconds for the system boot up\"\n        elif [ $wake_t -ge 250 -a $wake_t -le 2550 ];then\n            echo 0 > $PWR_L_TIMER_BASE_1S_SYSFS\n            echo 0 > $PWR_R_TIMER_BASE_1S_SYSFS\n            echo 1 > $PWR_L_TIMER_BASE_10S_SYSFS\n            echo 1 > $PWR_R_TIMER_BASE_10S_SYSFS\n            wake_t=$((wake_t/10))\n            logger \"Waiting $(($wake_t * 10)) seconds for the system boot up\"\n            echo \"Waiting $(($wake_t * 10)) seconds for the system boot up\"\n        else\n            usage\n            exit -1\n        fi\n        echo $wake_t > $PWR_L_TIMER_COUNTER_SETTING_SYSFS\n        echo $wake_t > $PWR_R_TIMER_COUNTER_SETTING_SYSFS\n        echo 1 > $PWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS\n        echo 1 > $PWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS\n        echo 0 > $PWR_L_TIMER_COUNTER_SETTING_UPDATE_SYSFS\n        echo 0 > $PWR_R_TIMER_COUNTER_SETTING_UPDATE_SYSFS\n    fi\n}\n\ndo_reset() {\n    local system timer wake_t opt pulse_us\n    system=0\n    timer=0\n    wake_t=0\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            t)\n                timer=1\n                wake_t=$OPTARG\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n\n    if [ $system -eq 1 ]; then\n        logger -p user.crit \"Power reset the whole system ...\"\n        if [ $board_rev -eq 4 ]; then\n            logger \"EVTA is not supported, running a workaround instead\"\n            echo \"EVTA is not supported, running a workaround instead\"\n\n            #\n            # Sync cached writes to persistent storage before chassis\n            # power cycle.\n            #\n            sync\n\n            i2cset -f -y 1 0x3a 0x12 0\n        else\n            if [ $timer -eq 1 ]; then\n                do_config_reset_timer $wake_t\n            fi\n            echo  \"Power reset the whole system ...\"\n\n            #\n            # Sync cached writes to persistent storage before chassis\n            # power cycle.\n            #\n            sync\n\n            echo 1 > $PWR_L_CYCLE_SYSFS\n            sleep 1\n            echo 1 > $PWR_R_CYCLE_SYSFS\n            sleep 3\n            # Control should not reach here, but if it failed to reset\n            # the system through PSU, then run a workaround to reset\n            # most of the system instead (if not all)\n            logger \"Failed to reset the system. Running a workaround\"\n            echo \"Failed to reset the system. Running a workaround\"\n            i2cset -f -y 1 0x3a 0x12 0\n        fi\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return -1\n        fi\n        echo -n \"Power reset microserver ...\"\n        echo 0 > $PWR_USRV_RST_SYSFS\n        sleep 1\n        echo 1 > $PWR_USRV_RST_SYSFS\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\ntoggle_pim_reset() {\n    retval=0\n    pim=$1\n    for slot in 2 3 4 5 6 7 8 9; do\n      if [ $pim -eq 0 ] || [ $slot -eq $pim ]; then\n        index=$(expr $slot - 2)\n         # We don't have PIM CPLD driver for now,\n         # so we will use raw i2c access for the time being\n         echo Power-cycling PIM in slot $slot\n         i2cset -f -y ${PIM_CPLD_BUS[$index]} $CPLD_ADDR $CPLD_RESET_CMD\n         result=$?\n         if [ $result -ne 0 ]; then\n           retval=$result\n         fi\n      fi\n    done\n    return $retval\n}\n\ndo_pimreset() {\n    local pim opt retval rc\n    retval=0\n    pim=-1\n    while getopts \"23456789a\" opt; do\n        case $opt in\n            a)\n                pim=0\n                ;;\n            2)\n                pim=2\n                ;;\n            3)\n                pim=3\n                ;;\n            4)\n                pim=4\n                ;;\n            5)\n                pim=5\n                ;;\n            6)\n                pim=6\n                ;;\n            7)\n                pim=7\n                ;;\n            8)\n                pim=8\n                ;;\n            9)\n                pim=9\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $pim -eq -1 ]; then\n      usage\n      exit -1\n    fi\n\n    toggle_pim_reset $pim\n    retval=$?\n\n    return $retval\n}\n\n\nif [ $# -lt 1 ]; then\n    usage\n    exit -1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    pimreset)\n        do_pimreset $@\n        exit $?\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 366}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get output from bic-util\nbic_output=`bic-util scm --read_mac`\n\n# Check if the read was successful and output matches with our format\nmatch=`echo $bic_output| grep -e 'MAC address: [0-9a-f][0-9a-f]:'|wc -l`\nif [ \"$match\" == \"1\" ]; then\n    # Mac address: xx:xx:xx:xx:xx:xx\n    echo $bic_output| cut -d ' ' -f 3\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit -1\nfi\n\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#shellcheck disable=SC1091,SC2034\n# Do not change this line to openbmc-utils.sh, or it will generate a source loop.\n. /usr/local/bin/i2c-utils.sh\n\nMCBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-0060)\n\nPWR_FORCE_OFF=\"${MCBCPLD_SYSFS_DIR}/pwr_force_off\"\nPWR_COME_EN=\"${MCBCPLD_SYSFS_DIR}/pwr_come_en\"\nPWR_COME_CYCLE_N=\"${MCBCPLD_SYSFS_DIR}/pwr_come_cycle_n\"\n\nTIMER_BASE_10S=\"${MCBCPLD_SYSFS_DIR}/timer_base_10s\"\nTIMER_BASE_1S=\"${MCBCPLD_SYSFS_DIR}/timer_base_1s\"\nTIMER_BASE_100MS=\"${MCBCPLD_SYSFS_DIR}/timer_base_100ms\"\nTIMER_BASE_10MS=\"${MCBCPLD_SYSFS_DIR}/timer_base_10ms\"\nTIMER_COUNTER_SETTING=\"${MCBCPLD_SYSFS_DIR}/timer_counter_setting\"\nTIMER_COUNTER_SETTING_UPDATE=\"${MCBCPLD_SYSFS_DIR}/timer_counter_setting_update\"\nPOWER_CYCLE_GO=\"${MCBCPLD_SYSFS_DIR}/power_cycle_go\"\n\nBOARD_ID=\"${MCBCPLD_SYSFS_DIR}/board_id\"\nVERSION_ID=\"${MCBCPLD_SYSFS_DIR}/version_id\"\n\nwedge_board_type() {\n    echo 'MONTBLANC'\n}\n\n# read hardware revision from MCB CPLD register\nwedge_board_rev() {\n    board_id=$(head -n 1 < \"$BOARD_ID\" 2> /dev/null)\n    version_id=$(head -n 1 < \"$VERSION_ID\" 2> /dev/null)\n\n    case \"$((board_id))\" in\n        1)\n            echo \"Board type: Minipack3 Switching System\"\n            ;;\n        *)\n            echo \"Board type: unknown value [$board_id]\"\n            ;;\n    esac\n\n    case \"$((version_id))\" in\n        0)\n            echo \"Revision: EVT-1\"\n            ;;\n        *) \n            echo \"Revision: unknown value [$version_id]\"\n            ;;\n    esac\n\n    return 0\n}\n\nuserver_power_is_on() {\n    val1=$(head -n 1 < \"$PWR_FORCE_OFF\" 2> /dev/null)\n    val2=$(head -n 1 < \"$PWR_COME_EN\" 2> /dev/null)\n\n    if [ $((val1)) -eq $((0x1)) ] && [ $((val2)) -eq $((0x1)) ] ; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n}\n\nuserver_power_on() {\n    echo 1 > \"$PWR_FORCE_OFF\"\n    echo 1 > \"$PWR_COME_EN\"\n    return 0\n}\n\nuserver_power_off() {\n    echo 0 > \"$PWR_FORCE_OFF\"\n    return 0\n}\n\nuserver_reset() {\n    # write 0 to trigger CPLD power cycling COMe\n    # then this bit will auto set to 1 after Power cycle finish\n    echo 0 > \"$PWR_COME_CYCLE_N\"\n    \n    timeout=10 #timeout 10 second\n    while [ $((timeout)) -ge 0 ]; do\n        val=$(head -n 1 < \"$PWR_COME_CYCLE_N\" 2> /dev/null)\n        if [ $((val)) -eq 1 ]; then\n            # reset successful\n            return 0   \n        fi\n        sleep 1\n        timeout=$((timeout-1))\n    done\n    # reset fail\n    echo \" userver reset failed.\"\n    return 1\n}\n\nchassis_power_cycle() {\n    # TIME_COUTER will be calculated \n    # based on register TIMER_BASE (10S,1S,100MS,10MS)\n    #\n    # eg. TIMER_BASE set as 100MS\n    #     TIMER_COUNTER_SETTING set as 50\n    #     timer is 50 x 100ms = 5 sec.\n\n    echo 0 > \"$TIMER_BASE_10S\"\n    echo 0 > \"$TIMER_BASE_1S\"\n    echo 1 > \"$TIMER_BASE_100MS\"\n    echo 0 > \"$TIMER_BASE_10MS\"\n\n    echo 50 > \"$TIMER_COUNTER_SETTING\"\n\n    echo 1 > \"$TIMER_COUNTER_SETTING_UPDATE\"\n    echo 1 > \"$POWER_CYCLE_GO\"\n\n    return 0\n}\n\nbmc_mac_addr() {\n    weutil_output=$(weutil -e chassis_eeprom | grep 'Local MAC:' | cut -d ' ' -f 3)\n\n    if [ -n \"$weutil_output\" ]; then\n        # Mac address: xx:xx:xx:xx:xx:xx\n        echo \"$weutil_output\" \n        return 0\n    else\n        echo \"Cannot find out the BMC MAC\" 1>&2\n        return 1\n    fi\n}\n\nuserver_mac_addr() {\n    weutil_output=$(weutil -e scm_eeprom | grep 'Local MAC:' | cut -d ' ' -f 3)\n\n    if [ -n \"$weutil_output\" ]; then\n        # Mac address: xx:xx:xx:xx:xx:xx\n        echo \"$weutil_output\" \n        return 0\n    else\n        echo \"Cannot find out the microserver MAC\" 1>&2\n        return 1\n    fi\n}\n", "num_lines": 159}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n# shellcheck disable=SC1091,SC3046\n. /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nCPLD_TYPE=\"$2\"\nUPDATE_IMG=\"$4\"\n\nchip_ver=$(aspeed_g6_chip_ver | cut -c 2)\n\nDLL_AST_JTAG_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\nusage() {\n    echo \"Usage: $prog -s <CPLD_TYPE> -f <img_file> <hw|sw>\"\n    echo\n    echo \"CPLD_TYPE: ( COME )\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"  JBC file for Intel PFR FPGA update software mode\"\n    echo \"  HEX file for i2c mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 5 ]; then\n    usage\n    exit 1\nfi\n\n#  Multiplex diagram\n#                         SEL_0\n#       from HEADER  >>> |0\\  |\n#                        |  >C| >> SCM CPLD\n#              |  /0| >> |1/  |\n#  BMC SPI1 >> |C<  |\n#              |  \\1| >>>  COMe CPLD \n#               SEL_1\n\nenable_scm_jtag_chain(){\n    gpiocli -s MUX_JTAG_SEL_0 set-value 1\n    gpiocli -s MUX_JTAG_SEL_1 set-value 0\n}\n\nenable_come_jtag_chain(){\n    gpiocli -s MUX_JTAG_SEL_0 set-value 0\n    gpiocli -s MUX_JTAG_SEL_1 set-value 1\n}\n\ndisable_jtag_chain(){\n    gpiocli -s MUX_JTAG_SEL_0 set-value 0\n    gpiocli -s MUX_JTAG_SEL_1 set-value 0\n}\n\ncpld_update_sw_mode(){\n    n=1\n    while [ \"${n}\" -le 5 ]; do\n        echo \"Program $CPLD_TYPE $n times\"\n        if [ \"$CPLD_TYPE\" = \"COME\" ];then\n            expect=0\n            jbi -aPROGRAM -ddo_real_time_isp=1 -W \"${UPDATE_IMG}\"\n        else\n            # ispvm success return code is 1\n            expect=1\n            ispvm -f 1000 dll $DLL_AST_JTAG_PATH \"${UPDATE_IMG}\"\n        fi\n\n        result=$?\n        if [ $result -eq $expect ]; then\n                break\n        fi\n        n=$((n + 1))\n    done\n}\n\ncpld_update_hw_mode(){\n    if [ $((chip_ver)) -ge 3 ];then\n        cpldprog -p \"${UPDATE_IMG}\"\n    else\n        echo \"Only AST262x A3 chip can support HW Mode !!!\"\n        exit 1\n    fi\n    result=$?\n}\n\ntrap 'rm -rf /tmp/cpld_update && disable_jtag_chain' INT TERM QUIT EXIT\n\necho 1 > /tmp/cpld_update\n\nexpect=0\n\nif [ -e \"$UPDATE_IMG\" ];then\n    if [ \"$CPLD_TYPE\" = \"SCM\" ];then\n        #enable_scm_jtag_chain\n        echo \"SCM CPLD didn't support yet\"\n        exit 1\n    elif [ \"$CPLD_TYPE\" = \"COME\" ];then\n        enable_come_jtag_chain\n    else\n        echo 'argument '\"$CPLD_TYPE\"' is wrong'\n        exit 1\n    fi\nelse\n    echo 'argument '\"$UPDATE_IMG\"' not exist'\n    exit 1\nfi\n\ncase $5 in\n    hw)\n        cpld_update_hw_mode\n        ;;\n    sw)\n        cpld_update_sw_mode\n        ;;\n    *)\n        # default: sw mode\n        cpld_update_sw_mode\n        ;;\nesac\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $((result)) -eq $((expect)) ]; then\n    echo \"Upgrade successful.\"\n    exit 0\nfi\n", "num_lines": 152}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\ncmd=\"ipmb-util 0x5 0x2c 0xb8 0xc8 0x57 0x01 0x00 0x01 0x00 0x00\"\n\nval=$($cmd)\nret=$?\n\nif [ $((ret)) -ne 0 ]; then\n    echo \"command failed : $cmd\"\n    echo \"  return value : $ret\"\n    exit 1\nfi\n\n# ref : Capture3 Intel ME Intel NM IPMI Interface\n#       Intelz Intelligent Power Node Manager 3.0 External Interface Specification Using IPMI\n#  NetFn 0x2E cmd 0xC8\n# example response : 57 01 00 1E 00 0D 00 27 00 1E 00 FF FF FF FF EF 39 01 00 50\n# [1:3]   - MFG ID\n# [4:5]   - Current value\n# [6:7]   - Minimum value\n# [8:9]   - Maximum value\n# [10:11] - Average value\n# [12:15] - Timestamp\n# [16:19]\n# [20]    Domain Id | Policy\n\ncur_power=\"0x$(echo \"$val\" | cut -d' ' -f5)$(echo \"$val\" | cut -d' ' -f4)\"\nmin_power=\"0x$(echo \"$val\" | cut -d' ' -f7)$(echo \"$val\" | cut -d' ' -f6)\"\nmax_power=\"0x$(echo \"$val\" | cut -d' ' -f9)$(echo \"$val\" | cut -d' ' -f8)\"\navr_power=\"0x$(echo \"$val\" | cut -d' ' -f11)$(echo \"$val\" | cut -d' ' -f10)\"\n\nprintf \"INA230 Current power : %d Watts\\n\" \"$cur_power\"\nprintf \"INA230 Minimum power : %d Watts\\n\" \"$min_power\"\nprintf \"INA230 Maximum power : %d Watts\\n\" \"$max_power\"\nprintf \"INA230 Average power : %d Watts\\n\" \"$avr_power\"", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# arg: NAME PIN DIR [DEFAULT VALUE]\nsetup_gpio() {\n    NAME=\"$1\"\n    PIN=\"$2\"\n    DIR=\"$3\"\n\n    gpio_export_by_name \"${ASPEED_GPIO}\" \"$PIN\" \"$NAME\"\n    if [ \"$DIR\" = \"out\" ]; then\n        gpio_set_direction \"$NAME\" out\n        if [ $# -ge 4 ]; then\n            VALUE=\"$4\"\n            gpio_set_value \"$NAME\" \"$VALUE\"\n        else\n            echo \"ERROR: setup-gpio $NAME output default value not defined\" > /dev/kmsg\n        fi\n    elif [ \"$DIR\" = \"in\" ]; then\n        gpio_set_direction \"$NAME\" in\n    else\n        echo \"ERROR: setup-gpio $NAME invalid direction [$DIR] not (in,out)\" > /dev/kmsg\n    fi\n}\n\n# To debug jumper\nsetup_gpio BMC_DEBUG_JUMPER1                GPIOG5 in\nsetup_gpio BMC_DEBUG_JUMPER2                GPIOB1 in\nsetup_gpio BMC_DEBUG_JUMPER3                GPIOB2 in\n# OCP Debug Card present event, high active\nsetup_gpio DEBUG_PRSNT                      GPIOG2 in\n\n# Indicate the PCH power good on the Netlake. From COME D83\nsetup_gpio PWRGD_PCH_PWROK                  GPIOF4 in\n# Reserved for power button event input, also pass through to BMC Pin40\nsetup_gpio PWR_BTN_L                        GPIOP4 in\n# Reserved for reset button event input, also pass through to BMC Pin76\nsetup_gpio RST_BTN_L                        GPIOP2 in\n\n# BMC Power Good, output to CPLD \nsetup_gpio BMC_PWRGD_R                      GPIOV4 out 1\n# BMC ready event to COME (COME A85)\nsetup_gpio FM_BMC_READY_R_L                 GPIOP0 out 0\n# Reserved for Power button event output, which pass through from BMC Pin160\nsetup_gpio BMC_PTH_PWR_BTN_L                GPIOP5 out 1\n# Reserved for reset button event output, which pass through from BMC Pin121\nsetup_gpio BMC_PTH_RST_BTN_L                GPIOP3 out 1\n\nsetup_gpio BMC_I2C1_EN                      GPIOG0 out 0\nsetup_gpio BMC_I2C2_EN                      GPIOF1 out 0\n# JTAG MUX\nsetup_gpio MUX_JTAG_SEL_0                   GPIOF0 out 0\nsetup_gpio MUX_JTAG_SEL_1                   GPIOF5 out 0\n# Mux select signal for BMC to program IOB flash (SPI)\nsetup_gpio IOB_FLASH_SEL                    GPIOG4 out 0\n# SPI Mux select to COME (B89) and PROT module\nsetup_gpio SPI_MUX_SEL                      GPIOQ6 out 0\n\n# BMC CPU_RST#\nsetup_gpio BMC_CPU_RST                      GPION2 in\n# To SCM CPLD, reserved.\nsetup_gpio BMC_GPIO126_USB2APWREN           GPION4 in\n# CPU power good event indicates to BMC\nsetup_gpio COME_ISO_PWRGD_CPU_LVC3          GPIOO2 in\n# CATERR/MSMI event from SOC\nsetup_gpio FM_CPU_MSMI_CATERR_LVT3_BUF_N    GPIOM3 in\n# Non-maskable Interrupt to BMC, from COMe B95\nsetup_gpio ISO_FM_BMC_NMI_L                 GPIOO3 in\n# Reserve for BMC to enable Netlake power, to COMe A93\nsetup_gpio ISO_FM_BMC_ONCTL_L               GPIOG6 out 0\n# COMe FPGA CRC error event indication, from COMe C69\nsetup_gpio ISO_FPGA_CRC_ERROR               GPIOQ0 in\n# Netlake FPGA asset it to inform BMC for PCIe hot plug (From COME A16)\nsetup_gpio ISO_SMB_FPGA_VPP_ALERT_L         GPIOG3 in", "num_lines": 103}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# FRU EEPROM\ni2c_device_add 3 0x56 24c64    # SCM FRU EEPROM#2\ni2c_device_add 6 0x53 24c64    # FCB_B EEPROM\ni2c_device_add 8 0x51 24c64    # BMC EEPROM\n\n# FPGA / CPLD\ni2c_device_add 12 0x60 mcbcpld\n\n# CPU IPMI\nulimit -q 1024000\ni2c_device_add 5 0x1010 slave-mqueue  # mqueue for ipmi from COMe CPU", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n#shellcheck disable=SC1091\n#shellcheck disable=SC2086\n. /usr/local/bin/openbmc-utils.sh\n\nret=0\ntrap cleanup_spi INT TERM QUIT EXIT\n\nPIDFILE=\"/var/run/spi_util.pid\"\ncheck_duplicate_process()\n{\n    exec 2>$PIDFILE\n    flock -n 2 || (echo \"Another process is running\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 1\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n\nremove_pid_file()\n{\n    if [ -f $PIDFILE ]; then\n        rm $PIDFILE\n    fi\n}\n\nSPI1_DRIVER=\"1e630000.spi\"\nASPEED_SMC_PATH=\"/sys/bus/platform/drivers/spi-aspeed-smc/\"\n\nmtd_driver_unbind_spi1() {\n    [ -e ${ASPEED_SMC_PATH}${SPI1_DRIVER} ] && echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}unbind\n}\n\nmtd_driver_rebind_spi1() {\n    # Sometime kernel may complain \"vmap allocation for size 268439552 failed: use vmalloc=<size> to increase size\"\n    # until now the root cause is not clear, still need more investigation\n    mtd_driver_unbind_spi1\n    echo ${SPI1_DRIVER} > ${ASPEED_SMC_PATH}bind\n\n    # add more delay to make sure the driver has probe done. \n    sleep 1;\n\n    SPI1_MTD_PATH=$(realpath /run/devmap/spi-devices/spi1-flash)\n    if [ ! -e \"$SPI1_MTD_PATH\" ]; then\n        echo \"cannot find SPI1 MTD path [$SPI1_MTD_PATH]\"\n        exit 1\n    fi\n    SPI1_MTD_INDEX=$(echo \"$SPI1_MTD_PATH\" | sed 's_/dev/mtd__g')\n}\n\nread_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Reading ${dev} to $file...\"\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -r \"$file\"\n}\n\nwrite_spi1_dev(){\n    dev=$1\n    file=$2\n    echo \"Writing $file to ${dev}...\"\n\n    tmpfile=\"/tmp/temp_image\"\n    flashsize=$(flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX | grep -i kB | xargs echo | cut -d '(' -f 2 | cut -d ' ' -f 0)\n    targetsize=$((flashsize * 1024))\n\n    case ${dev} in\n        \"COME_BIOS\"|\"PROT\"|\"IOB_FPGA\")\n        # store to the temp-file\n        cp \"$file\" \"$tmpfile\"\n        ;;        \n    esac\n\n    #extend the temp-file\n    filesize=$(stat -c%s $tmpfile)\n    echo $filesize\n    add_size=$((targetsize - filesize))\n    echo $add_size\n    dd if=/dev/zero bs=\"$add_size\" count=1 | tr \"\\000\" \"\\377\" >> \"$tmpfile\"\n\n    echo flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -w \"$tmpfile\"\n\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -w \"$tmpfile\"\n\n    case ${dev} in\n        \"IOB_FPGA\")\n            # TODO: add reset signal component after programed\n        ;;\n        \"COME_BIOS\")\n            # no need action, let user run command to reset COMe [wedge_power.sh reset]\n        ;;\n        \"PROT\")\n            # TODO: need confirm, this path use only for debuging\n        ;;\n    esac\n}\n\nerase_spi1_dev(){\n    flashrom -p linux_mtd:dev=$SPI1_MTD_INDEX -E\n}\n\nconfig_spi1_pin_and_path(){\n    dev=$1\n\n    # enable i2c buff BMC able to access \n    #  i2c-0  for COME CPLD  (0x1f)\n    #  i2c-1  for SCM CPLD   (0x35)\n    gpiocli -s BMC_I2C1_EN set-value 1\n    gpiocli -s BMC_I2C2_EN set-value 1\n    case ${dev} in\n        \"IOB_FPGA\")\n            # SCM CPLD: BMC_SPI1 \n            #                    to (X) IOB_FPGA   0\n            #                       ( ) COME_BIOS  1\n            #                       ( ) PRoT       2\n            i2cset -f -y 1 0x35 0x34 0x0\n\n            # BMC GPIO: IOB_FLASH \n            #                    to ( ) IOB_FPGA 0\n            #                       (X) BMC_SPI1 1\n            gpiocli -s IOB_FLASH_SEL set-value 1\n        ;;\n        \"COME_BIOS\")\n            # SCM CPLD: BMC_SPI1 \n            #                    to ( ) IOB_FPGA   0\n            #                       (X) COME_BIOS  1\n            #                       ( ) PRoT       2\n            i2cset -f -y 1 0x35 0x34 0x1\n            \n            # BMC GPIO: BIOS_FLASH \n            #                    to ( ) NetLake CPU 0\n            #                       (X) BMC_SPI1    1\n            gpiocli -s SPI_MUX_SEL set-value 1\n            \n            # COME CPLD: BIOS_FLASH_CS0\n            #                    to ( ) BMC_SPI1_CS1 0x7\n            #                       (X) BMC_SPI1_CS0 0x5\n            #                       ( ) SPI_PCH_CS0 0x4\n            #                       ( ) SPI_PCH_CS1 0x6\n            i2cset -f -y 0 0x1f 0xa 0x5\n        ;;\n        \"PROT\")\n            # TODO: need confirm, this path use only for debuging\n            # SCM CPLD: set BMC_SPI1 \n            #                    to ( ) IOB_FPGA   0\n            #                       (X) COME_BIOS  1\n            #                       ( ) PRoT       2\n            i2cset -f -y 1 0x35 0x34 0x2\n        ;;\n    esac\n    mtd_driver_rebind_spi1\n}\n\ncleanup_spi(){\n    if [ $ret -eq 1 ]; then\n        exit 1\n    fi\n\n    # select muxing FLASH to normal mode\n    # BMC GPIO: IOB_FLASH \n    #                    to (X) IOB_FPGA    0\n    #                       ( ) BMC_SPI1    1\n    gpiocli -s IOB_FLASH_SEL set-value 0\n    # BMC GPIO: BIOS_FLASH \n    #                    to (X) NetLake CPU 0\n    #                       ( ) BMC_SPI1    1\n    gpiocli -s SPI_MUX_SEL set-value 0\n\n    rm -rf /tmp/*_spi*_tmp\n    remove_pid_file\n}\n\noperate_spi1_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n                read_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                if [ ! -f \"$file\" ]; then\n                    echo \"$file not exist!!!\"\n                    exit 1\n                fi\n                write_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi1_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n    mtd_driver_unbind_spi1\n}\n\nui(){\n    . /usr/local/bin/openbmc-utils.sh\n    op=$1\n    spi=$2\n\n    ## Open the path to device ##\n    case ${spi} in\n        \"spi1\")\n            dev=$3\n            file=$4\n            config_spi1_pin_and_path \"$dev\"\n            operate_spi1_dev \"$op\" \"$dev\" \"$file\"\n        ;;\n        *)\n            echo \"No such SPI bus.\"\n            return 1\n        ;;\n    esac\n}\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"  $program <op> <spi> <spi device> <file>\"\n    echo \"    <op>          : read, write, erase\"\n    echo \"    <spi>         : spi1\"\n    echo \"    <spi1 device> : IOB_FPGA, COME_BIOS\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  $program write spi1 IOB_FPGA iofpga.bit\"\n    echo \"\"\n}\n\ncheck_parameter(){\n    program=$(basename \"$0\")\n    op=$1\n    spi=$2\n\n    # check operations.\n    case ${op} in\n        \"read\" | \"write\" | \"erase\")\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n\n    case ${spi} in\n        # check spi 1 device and parameters.\n        \"spi1\")\n            dev=$3\n            file=$4\n            case ${dev} in\n                \"IOB_FPGA\"|\"COME_BIOS\")\n                    case ${op} in\n                        \"read\" | \"write\")\n                            if [ $# -ne 4 ]; then\n                                return 1\n                            fi\n                            ;;\n                        \"erase\")\n                            if [ $# -ne 3 ]; then\n                                return 1\n                            fi\n                            ;;\n                    esac\n                    ;;\n                \"PROT\")\n                    echo \"PRoT upgrade not support yet\"\n                    return 1\n                    ;;\n                *)\n                    return 1\n                    ;;\n            esac\n            ;;\n\n        # check device and parameters fail.\n        *)\n            return 1\n            ;;\n    esac\n\n    return 0\n}\n\n\n# check_duplicate_process - to check if there is the duplicate spi util process, will return fail and stop execute command.\ncheck_duplicate_process\n\n# check_parameter - to check command parameters\ncheck_parameter \"$@\"\nis_par_ok=$?\n\nif [ $is_par_ok -eq 0 ]; then\n    ui \"$@\"\n    exit 0\nelse\n    usage\n    exit 1\nfi", "num_lines": 319}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Read AST2620 register SCU014 [23:16] to retrieve the board hardware revision.\n\nSCU014_REG=0x1e6e2014\nHW_REV_BIT=16\nBOARD_REV=$(($(($(devmem \"${SCU014_REG}\") >> \"${HW_REV_BIT}\")) & 0xff))\necho \"ASPEED Chip Revision: A${BOARD_REV}\"\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# read the Hardware revision from MCB CPLD register\n. /usr/local/bin/openbmc-utils.sh\n\nwedge_board_rev", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nprintf \"%-1s | %-3s | %-30s\\n\" \"v\" \"dir\" \"GPIONAME\"\nfor i in /tmp/gpionames/*\ndo\n   gpio=\"$(basename \"$i\")\"\n   val=\"$(gpio_get_value \"$gpio\")\"\n   direction=\"$(gpio_get_direction \"$gpio\")\"\n   printf \"%-1s | %-3s | %-30s\\n\" \"$val\" \"$direction\" \"$gpio\"\ndone\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# This utility prints the meta information for specified boot flash\n# mtd partition\nSTART_OFFSET_KB=960\nLEN_KB=64\n\nusage() {\n    echo \"Usage $0 [flash0|flash1]\"\n}\n\ncase \"$1\" in\n    flash0)\n        mtd=\"$(grep flash0 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    flash1)\n        mtd=\"$(grep flash1 /proc/mtd | awk '{print $1}' | tr -d ':')\"\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\ndd if=/dev/\"$mtd\" of=/tmp/.\"$1\"_meta bs=1K skip=\"$START_OFFSET_KB\" count=\"$LEN_KB\"\nstrings /tmp/.\"$1\"_meta\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nOOB_MDIO_BUS=2\nOOB_PHY_ADDR=0x12\n\nmode=$1\nport=$2\nreg_addr=$3\n\nusage() {\n    echo \"OOB MDIO Utility to access Marvell 88E6321 OOB Switch\"\n    echo \"Usage:\"\n    echo \"$0 read <port> <reg_addr> \"\n    echo \"$0 write <port> <reg_addr> <data>\"\n}\n\nif [ $# -lt 3 ]; then\n    usage\n    exit 1;\nfi \n\nif [ \"$mode\" = \"write\" ]; then\n    if [ $# -ne 4 ]; then\n        usage\n        exit 1;\n    fi\n    ctrl_cmd=$(( 0x9000 | (0x1 << 10) | ( (0x10 + port) << 5) | reg_addr ))\n    data=$3\n    mdio-util -m \"$OOB_MDIO_BUS\" -p \"$OOB_PHY_ADDR\" -w 0x1 -d \"$data\"\n    mdio-util -m \"$OOB_MDIO_BUS\" -p \"$OOB_PHY_ADDR\" -w 0x0 -d \"$ctrl_cmd\"\nelif [ \"$mode\" = \"read\" ]; then\n    if [ $# -ne 3 ]; then\n        usage\n        exit 1;\n    fi\n    ctrl_cmd=$(( 0x9000 | (0x2 << 10) | ( (0x10 + port) << 5) | reg_addr ))\n    ctrl_cmd=$(printf \"0x%08X\" \"$ctrl_cmd\")\n    mdio-util -m \"$OOB_MDIO_BUS\" -p \"$OOB_PHY_ADDR\" -w 0x0 -d \"$ctrl_cmd\"\n    mdio-util -m \"$OOB_MDIO_BUS\" -p \"$OOB_PHY_ADDR\" -r 0x1    \nelse\n    usage\n    exit 1;\nfi\n\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates. (http://www.meta.com)\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2235\n. /usr/local/bin/openbmc-utils.sh\n\ntrap handle_signal INT TERM QUIT\n\n# mdio prints in the format \n# \"Write to PHY 0x12.0x0, value is 0x9a00\"\n# \"Read from PHY 0x12.0x1, value is 0x4e09\"\nMDIO_READ_PATTERN_DETECT=\"^Read .* value is 0x[a-fA-F0-9]*$\"\nMDIO_READ_PATTERN_EXTRACT=\"^Read .* value is (0x[a-fA-F0-9]*)$\"\n\n# Global variable to stack tabs for formatting\ntab=\"\"\n\nusage() {\n    echo \"Read 88E6321 (oob switch) port status registers\"\n    echo \"\"\n    echo \"# To dump all port status\"\n    echo \"oob-status.sh\"\n    echo \"# To dump port status for ports in 0, 1, 2, 3, 4, 5, 6\"\n    echo \"oob-status.sh [Port(s)]\"\n    echo \"# To print only link status\"\n    echo \"oob-status.sh link_status [Port(s)]\"\n    echo \"# To print only link speed\"\n    echo \"oob-status.sh link_speed [Port(s)]\"\n    echo \"\"\n    echo \"Example:\"\n    echo \"\"\n    echo \"oob-status.sh link_status 0 3\"\n    echo \"Link Status:\"\n    echo \"\tPort 0: Link Up\"\n    echo \"\tPort 3: Link Up\"\n\n}\n\nhandle_signal() {\n    echo \"Exiting because of signal\" >&2\n    exit 1\n}\n\ncheck_sts_args() {\n    # Convert arguments to port numbers\n    local port\n    ret=\"$*\"\n    if [ $# -lt 1 ]; then\n       # No arguments: do all ports\n       ret=\"0 1 2 3 4 5 6\"\n    else\n        for port in \"$@\"; do\n            if [ \"$port\" -lt 0 ] || [ \"$port\" -gt 6 ]; then\n                echo \"Invalid port $port\"\n                exit 1\n            fi\n        done\n    fi\n    echo \"$ret\"\n}\n\ndo_read_lnksts() {\n    local result ports port val\n    ports=\"$*\"\n\n    printf \"%sLink status:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        result=$(oob-mdio-util.sh read \"$port\" 0x0 \\\n            | grep -e \"$MDIO_READ_PATTERN_DETECT\" \\\n            | sed -E \"s/$MDIO_READ_PATTERN_EXTRACT/\\1/\")\n        val=$(( (result >> 11) & 0x1 ))\n        case \"$val\" in\n            0)\n                link_state=\"Link Down\"\n                ;;\n            1)\n                link_state=\"Link Up  \"\n                ;;\n        esac\n        printf \"%sPort: %s - %s\\n\" \"$tab\" \"$port\" \"$link_state\"\n    done\n    tab=${tab:1}\n}\n\ndo_read_spdsts() {\n    local result ports port val\n    ports=\"$*\"\n\n    printf \"%sLink speed:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n\n    for port in $ports; do\n        port=${port^^}\n        result=$(oob-mdio-util.sh read \"$port\" 0x0 \\\n            | grep -e \"$MDIO_READ_PATTERN_DETECT\" \\\n            | sed -E \"s/$MDIO_READ_PATTERN_EXTRACT/\\1/\")\n        val=$(( (result >> 10) & 0x1 ))\n        case \"$val\" in\n            0)\n                duplex=\"half-duplex\"\n                ;;\n            1)\n                duplex=\"full-duplex\"\n                ;;\n        esac\n        \n        val=$(( (result >> 8) & 0x3 ))\n        case \"$val\" in\n            0)\n                speed=\"10   Mb/s\"\n                ;;\n            1)\n                speed=\"100  Mb/s\"\n                ;;\n            2)\n                speed=\"1000 Mb/s\"\n                ;;\n        esac\n        printf \"%sPort: %s - %s %s \\n\" \"$tab\" \"$port\" \"$speed\" \"$duplex\"\n    done\n    tab=${tab:1}\n}\n\nread_lnksts() {\n    ports=$(check_sts_args \"$@\")\n    do_read_lnksts \"$ports\"\n}\n\nread_spdsts() {\n    ports=$(check_sts_args \"$@\")\n    do_read_spdsts \"$ports\"\n}\n\nread_status() {\n    ports=$(check_sts_args \"$@\")\n    printf \"%sStatus:\\n\" \"$tab\"\n    tab=\"\t$tab\"\n    do_read_lnksts \"$ports\"\n    do_read_spdsts \"$ports\"\n    tab=${tab:1}\n}\n\n# Only allow one instance of script to run at a time.\nscript=$(realpath \"$0\")\nexec 100< \"$script\"\nflock -n 100 || { echo \"ERROR: $0 already running\" && exit 1; }\n\ncommand=\"$1\"\n\ncase \"$command\" in\n    link_status)\n        shift\n        read_lnksts \"$@\"\n        ;;\n    link_speed)\n        shift\n        read_spdsts \"$@\"\n        ;;\n    \"--help\")\n        usage\n        exit 1\n        ;;\n    *)\n        read_status \"$@\"\n        ;;\nesac\n", "num_lines": 188}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nlogger \"Update eth0 IPv6 link local address after NC-SI MAC address configured\"\n\n# shellcheck disable=SC2086\nmac_to_ll() {\n  IFS=':'; set $1; unset IFS\n  echo \"fe80::$(printf %x $((0x$1 ^ 2)))$2:${3}ff:fe$4:$5$6\" | \\\n    sed -E 's/:0+/:/g; s/:{3,}/::/; s/:$/:0/'\n}\n\nexp_ll=\"\"\nll=\"\"\n\nfor _ in {1..30}; do\n  # wait getting address from NC-SI\n  if [ \"$(cat /sys/class/net/eth0/addr_assign_type)\" = \"3\" ]; then\n    exp_ll=$(mac_to_ll \"$(cat /sys/class/net/eth0/address)\")\n    rc_exp_ll=$?\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    rc_ll=$?\n\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break;\n    fi\n    # re-generate link-local address\n    ip -6 addr flush dev eth0 scope link\n    echo 1 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    echo 0 > /proc/sys/net/ipv6/conf/eth0/addr_gen_mode\n    break;\n  fi\n  sleep 1\ndone\n\nif [ \"$ll\" != \"$exp_ll\" ]; then\n  for i in {1..100}; do\n    usleep 10000\n    ll=$(ip -6 addr show dev eth0 scope link | sed -e's/^.*inet6 \\([^ ]*\\)\\/.*$/\\1/;t;d')\n    if [ \"$ll\" = \"$exp_ll\" ]; then\n      break;\n    elif [ \"$ll\" != \"$exp_ll\" ] && [ \"$i\" -eq 100 ]; then\n      logger \"Failed to set address from MAC\"\n    else\n      continue;\n    fi\n  done\nfi\n\nlogger \"Restart eth0 after MAC and Linklock addr update\"\nifdown eth0\nsleep 1\nifup eth0 &\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/front-paneld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon...\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/fan-util --set 100\necho \"Setup fan speed done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/bin/gpiod\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup gpio monitoring for netlakeMTP... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# first byte: ME i2c-address is 0x10, second byte: 0x10 as BMC's slave address when get response\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-1/new_device\nexec /usr/local/bin/ipmbd 1 1\n\n", "num_lines": 6}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\nsleep 10\nulimit -q 1024000\n\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\n\necho \"Done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 7}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ncsid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup ncsid for BMC \"\n\n./usr/local/bin/fruid-util nic > /dev/null\nif [ $? == 0 ]; then\nrunsv /etc/sv/ncsid > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\nKV_STORE=/mnt/data/kv_store\n\n#get power on reset config\npower_on_reset_conf=\"$KV_STORE/server_power_on_reset_cfg\"\nlast_power_state_conf=\"$KV_STORE/server_last_power_state\"\n\n# control the system power based on $power_on_reset_conf\npower_on_reset_cfg_val=$(cat $power_on_reset_conf)\nlast_power_state_val=$(cat $last_power_state_conf)\n\nif [ \"$(is_bmc_power_on_reset)\" -eq 1 ]; then\n    if [ \"$power_on_reset_cfg_val\" = \"on\" ]; then\n      /usr/local/bin/power-util server on\n    elif [ \"$power_on_reset_cfg_val\" = \"lps\" ] && [ \"$last_power_state_val\" = \"on\" ]; then\n      /usr/local/bin/power-util server on\n    fi\nfi\necho \"Done\"\n", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\naddr=$(/usr/bin/mac-util --get)\n\nif ! [ \"$addr\" = \"ff:ff:ff:ff:ff:ff\" ]\nthen\n  ifconfig eth1 hw ether \"$addr\"\nfi\n\ndhclient eth1 > /dev/null 2>&1 &\n\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nMAX_RETRY=5\nNTP_CMD=/usr/sbin/ntpq\n\n##### sync time from NTP server\nretry=0\nwhile [ $retry -lt \"$MAX_RETRY\" ]\ndo\n  if ! $NTP_CMD -p | grep '^\\*' > /dev/null ; then\n    retry=$((retry+1))\n    sleep 1\n  else\n    logger -s -p user.crit -t sync-date \"Syncing up BMC time from NTP\"\n    exit 0\n  fi\ndone\nlogger -s -p user.info -t sync-date \"Syncing up BMC time from NTP failed because NTP server not exist\"\n\necho Syncing up BMC time with server...\n\n# Use standard IPMI command 'get-sel-time' to read RTC time\ntime=$(/usr/local/bin/me-util 0x28 0x48)\nret=$?\nif [ $ret = \"0\" ] ; then\n  date -s @$((16#$(echo \"$time\" | awk '{print $4$3$2$1}')))\n  ret=$?\n  if [ $ret = \"0\" ]; then\n      logger -s -p user.crit -t sync-date \"Syncing up BMC time from Host(ME)\"\n      exit 0\n  fi\nfi\n\n##### sync time from default time\nlogger -s -p user.crit -t sync-date \"Syncing up BMC time from Default(OpenBMC build time)\"\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#TODO: Add functions as shell's lib in /usr/local/fbpackages/utils/ast-functions#\necho \"Setup sensor monitoring for NETLAKEMTP... \"\n\nFRUS=\"server bmc pdb fio nic\"\n\nexec /usr/local/bin/sensord $FRUS\n", "num_lines": 9}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho \"Setup sensor monitoring for NETLAKEMTP... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n#enable the register of VIN sampling of ADM1278\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/setup-gpio\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2022-present Facebook. All Rights Reserved.\n\n#\n# Protect against multiple power requests\n#\nBOARD_UTILS_TIMEOUT=20\n# Worst case in FPGA design is 10 seconds for power to drain before power on\n# again. Add some buffer for time variation, errors, and serializing\n# simultaneous requests.\nif [[ \"${FLOCKER}\" != \"$0\" ]]; then\n    exec env FLOCKER=\"$0\" flock -w \"$BOARD_UTILS_TIMEOUT\" \"$0\" \"$0\" \"$@\"\nfi\n\nwedge_board_type() {\n    echo 'SANDIA'\n}\n\nSEQ_STR=\"sequenced\"\nON_STR=\"powered on\"\n\nwait_for_sequencing() {\n    PSEQ=/sys/bus/platform/devices/pseq\n    TIMEOUT=12\n    COUNT=0\n    if [ -e ${PSEQ} ]; then\n        while grep -q \"${SEQ_STR}\" ${PSEQ}/power_state;\n        do\n            if [ ${COUNT} -ge ${TIMEOUT} ]; then\n                #Error: Time out\n                return 1\n            fi\n            sleep 1\n            COUNT=$(( COUNT + 1 ))\n        done\n    fi\n\n    return 0\n}\n\nuserver_power_is_on() {\n    PSEQ=/sys/bus/platform/devices/pseq\n    if [ -e ${PSEQ} ]; then\n        if grep -q \"${ON_STR}\" ${PSEQ}/power_state; then\n            return 0 #powered on\n        fi\n    else\n        i2cset -f -y 2 0x21 0x90\n        i2cset -f -y 2 0x22 0x40\n        i2cset -f -y 2 0x23 0x01\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x20 0x01\n        power_state=$(i2cget -f -y 2 0x26)\n        power_state=$((power_state >> 1))\n        power_state=$((power_state & 0x03))\n        if [ $power_state -eq 2 ]; then\n            return 0 #powered on\n        fi\n    fi\n\n    return 1 # not powered on\n}\n\nuserver_power_on() {\n    if ! wait_for_sequencing; then\n        return 1\n    fi\n\n    # Safe to perform power operation\n    MSD=/sys/bus/platform/devices/msd\n    for ((i=0; i<20; i++)); do\n        if [ -w ${MSD} ]; then\n            echo 0 > ${MSD}/cfg7\n            echo power-on > ${MSD}/control\n            break\n        else\n            # Write 0x00000000 at Cyclonus 0x0000103c\n            if ! i2cset -f -y 2 0x21 0x3c &> /dev/null; then\n                sleep 10\n                continue\n            fi\n            i2cset -f -y 2 0x22 0x10\n            i2cset -f -y 2 0x23 0x00\n            i2cset -f -y 2 0x24 0x00\n            i2cset -f -y 2 0x25 0x00\n            i2cset -f -y 2 0x26 0x00\n            i2cset -f -y 2 0x27 0x00\n            i2cset -f -y 2 0x28 0x00\n            i2cset -f -y 2 0x20 0x00\n\n\t    # Trigger rising edge of bit 5 at Cyclonus 0x0000103c\n            i2cset -f -y 2 0x25 0x20\n            i2cset -f -y 2 0x20 0x00\n            break\n        fi\n    done\n\n    if wait_for_sequencing; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nuserver_power_off() {\n    if ! wait_for_sequencing; then\n        return 1\n    fi\n\n    # Safe to perform power operation\n    MSD=/sys/bus/platform/devices/msd\n    XIL=/sys/bus/platform/devices/xil\n    if [ -w ${MSD} ]; then\n        echo 0 > ${MSD}/cfg7\n        echo power-off > ${MSD}/control\n        if [ -w ${XIL} ]; then\n            # Reset SMB power\n            echo 0 > ${XIL}/cfg7\n            echo 0x400 > ${XIL}/cfg7\n        else\n            #Error: XIL driver not loaded\n            return 1\n        fi\n    else\n        # Write 0x00000000 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x21 0x3c\n        i2cset -f -y 2 0x22 0x10\n        i2cset -f -y 2 0x23 0x00\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x00\n        i2cset -f -y 2 0x26 0x00\n        i2cset -f -y 2 0x27 0x00\n        i2cset -f -y 2 0x28 0x00\n        i2cset -f -y 2 0x20 0x00\n\n        # Trigger rising edge of bit 3 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x25 0x08\n        i2cset -f -y 2 0x20 0x00\n    fi\n\n    if wait_for_sequencing; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nuserver_reset() {\n    if ! wait_for_sequencing; then\n        return 1\n    fi\n\n    MSD=/sys/bus/platform/devices/msd\n    XIL=/sys/bus/platform/devices/xil\n    if [ -w ${MSD} ]; then\n        echo 0 > ${MSD}/cfg7\n        echo cold-reset > ${MSD}/control\n        if [ -w ${XIL} ]; then\n            # Reset SMB power\n            echo 0 > ${XIL}/cfg7\n            echo 0x400 > ${XIL}/cfg7\n        else\n            #Error: XIL driver not loaded\n            return 1\n        fi\n    else\n        # Write 0x00000000 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x21 0x3c\n        i2cset -f -y 2 0x22 0x10\n        i2cset -f -y 2 0x23 0x00\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x00\n        i2cset -f -y 2 0x26 0x00\n        i2cset -f -y 2 0x27 0x00\n        i2cset -f -y 2 0x28 0x00\n        i2cset -f -y 2 0x20 0x00\n\n        # Trigger rising edge of bit 6 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x25 0x40\n        i2cset -f -y 2 0x20 0x00\n    fi\n\n    if wait_for_sequencing; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nchassis_power_cycle() {\n    if ! wait_for_sequencing; then\n        return 1\n    fi\n\n    MSD=/sys/bus/platform/devices/msd\n    if [ -w ${MSD} ]; then\n        echo 0 > ${MSD}/cfg7\n        echo 0x400 > ${MSD}/cfg7\n    else\n        # Write 0x00000000 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x21 0x3c\n        i2cset -f -y 2 0x22 0x10\n        i2cset -f -y 2 0x23 0x00\n        i2cset -f -y 2 0x24 0x00\n        i2cset -f -y 2 0x25 0x00\n        i2cset -f -y 2 0x26 0x00\n        i2cset -f -y 2 0x27 0x00\n        i2cset -f -y 2 0x28 0x00\n        i2cset -f -y 2 0x20 0x00\n\n        # Trigger rising edge of bit 10 at Cyclonus 0x0000103c\n        i2cset -f -y 2 0x26 0x04\n        i2cset -f -y 2 0x20 0x00\n    fi\n\n    # Power sequncers take 10 seconds to complete.\n    if wait_for_sequencing; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nbmc_mac_addr() {\n    mac=00:00:00:00:00:00\n\n    hexdump -ve '1/1 \"%.2x\"' \"$SYSFS_I2C_DEVICES\"/8-0054/eeprom > /tmp/eeprom_data\n\n    ((i = 0))\n    while [[ $i -lt 512 ]]; do\n        var=$( dd skip=$i count=4 if=/tmp/eeprom_data bs=1 2> /dev/null )\n        if [ \"$var\" = \"cf06\" ];then\n            ((i = i + 4))\n            mac1=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n            ((i = i + 2))\n            mac2=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n            ((i = i + 2))\n            mac3=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n            ((i = i + 2))\n            mac4=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n            ((i = i + 2))\n            mac5=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n            ((i = i + 2))\n            mac6=$( dd skip=$i count=2 if=/tmp/eeprom_data bs=1 2> /dev/null)\n\n            mac=$mac1:$mac2:$mac3:$mac4:$mac5:$mac6\n            break\n        fi\n        ((i = i + 1))\n    done\n\n    rm /tmp/eeprom_data\n    echo \"$mac\"\n}\n\nuserver_mac_addr() {\n    weutil --json | jq -r '.\"Extended MAC Base\"'\n}\n", "num_lines": 260}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n#shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\n#\n# Will need to move some devices to dts later.\n#\ni2c_device_add 8 0x50 24c04\ni2c_device_add 8 0x54 24c64\n\n# Setup Chassis/PDB IDPROM\nsetup_chassis_idprom() {\n    idp_path=$(i2cdetect -l | grep SCM_IDPROM)\n    if [ -n \"${idp_path}\" ]; then\n        bus=$(echo \"${idp_path}\" | tr \"-\" \" \" | awk '{print $2}')\n        i2c_device_add \"${bus}\" 0xa0d0 24c64 #Chassis IDPROM\n    fi\n}\n\nsetup_chassis_idprom\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 2\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 11 3\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 2 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 6 4\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 7 5\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 8 6\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 7\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/plat-functions\n\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\nulimit -q 2048000\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-1/new_device\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-2/new_device\nrunsv /etc/sv/ipmbd_2 > /dev/null 2>&1 &\n\necho slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-11/new_device\nrunsv /etc/sv/ipmbd_11 > /dev/null 2>&1 &\n\nsys_sku_id=$(get_sys_sku)\nif [ \"$sys_sku_id\" = \"$SKU_SINGLE_COMPUTE\" ]; then\n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-6/new_device\n  runsv /etc/sv/ipmbd_6 > /dev/null 2>&1 &\n  \n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-7/new_device\n  runsv /etc/sv/ipmbd_7 > /dev/null 2>&1 &\n  \n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-8/new_device\n  runsv /etc/sv/ipmbd_8 > /dev/null 2>&1 &\n  \n  echo slave-mqueue 0x1010 > /sys/bus/i2c/devices/i2c-9/new_device\n  runsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\nfi\n\necho \"Done.\"\n", "num_lines": 62}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\necho Probe Ex-GPIO device\ni2c_device_add 1 0x21 pca9555 #SCB Expender\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n\n# FM_BMC_PWRBTN_OUT_N\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOP0 FM_BMC_PWRBTN_OUT_N\ngpio_set_value FM_BMC_PWRBTN_OUT_N 1\n\n# GPIOP1\n# set GPIOP1 output high to prevent GPIOP0 from being affected\n# if GPIOP1 is set to input, GPIOP0 only 1.7V when set to output high\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOP1 GPIOP1\ngpio_set_value GPIOP1 1\n\n# FM_BMC_RSTBTN_OUT_N\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOP3 FM_BMC_RSTBTN_OUT_N\ngpio_set_value FM_BMC_RSTBTN_OUT_N 1\n\n# SYS_SKU_ID0_R\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOC4 SYS_SKU_ID0_R\n\n# SYS_SKU_ID1_R\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOX2 SYS_SKU_ID1_R\n\n# MB_P12V_HS_EN_N\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOC5 MB_P12V_HS_EN_N\ngpio_set_value MB_P12V_HS_EN_N 0\n\n# FM_BIC_DEBUG_SW_N_R\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOD2 FM_BIC_DEBUG_SW_N_R\ngpio_set_value FM_BIC_DEBUG_SW_N_R 0\n\n# PWRGD_CPUPWRGD_LVC1\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOR6 PWRGD_CPUPWRGD_LVC1\n\n# BIC_EXTRST\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOS6 BIC_EXTRST\ngpio_set_value BIC_EXTRST 1\n\n# BIC_FWSPICK\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOD0 BIC_FWSPICK\ngpio_set_value BIC_FWSPICK 0\n\n# BIC_SRST\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOD1 BIC_SRST\ngpio_set_value BIC_SRST 1\n\n#SCB IO-Expender\ngpio_export_by_offset 1-0021 0 BMC_UART_SEL0\ngpio_set  BMC_UART_SEL0  0\ngpio_export_by_offset 1-0021 1 BMC_UART_SEL1\ngpio_set  BMC_UART_SEL1  0\ngpio_export_by_offset 1-0021 2 BMC_UART_SEL2\ngpio_set  BMC_UART_SEL2  0\ngpio_export_by_offset 1-0021 3 BMC_UART_SEL3\ngpio_set  BMC_UART_SEL3  0\ngpio_export_by_offset 1-0021 4 BMC_UART_SEL4\ngpio_export_by_offset 1-0021 5 BMC_UART_MUX_SEL_N\ngpio_set  BMC_UART_MUX_SEL_N  0\ngpio_export_by_offset 1-0021 6 FM_PWRGD_SCB_R_PWRGD_BUF\ngpio_export_by_offset 1-0021 7 FP_PWR_LED_BMC\ngpio_export_by_offset 1-0021 8 FP_STS_LED_BMC\ngpio_export_by_offset 1-0021 9 BMC_FP_LED_MUX_SEL_N\ngpio_export_by_offset 1-0021 10 PWR_BTN_QS_N_BMC\ngpio_export_by_offset 1-0021 11 RST_BTN_QS_N_BMC\ngpio_export_by_offset 1-0021 12 DC_SCM_FW_RDY_R_N\n\n\n\n# FM_BMC_READY_PLD_R\ngpio_export_by_name  \"${ASPEED_GPIO}\" GPIOV5 FM_BMC_READY_PLD_R\ngpio_set_value FM_BMC_READY_PLD_R 0\n", "num_lines": 102}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config() {\n  TO_PWR_ON=0\n\n  if POR=$(kv get \"server_por_cfg\" persistent); then\n    echo \"server_por_cfg = $POR\"\n    if [ \"$POR\" = \"lps\" ]; then\n      if LS=$(kv get \"pwr_server_last_state\" persistent); then\n        if [ \"$LS\" = \"on\" ]; then\n          TO_PWR_ON=1;\n        fi\n      else\n        TO_PWR_ON=$DEF_PWR_ON\n      fi\n    elif [ \"$POR\" = \"on\" ]; then\n      TO_PWR_ON=1;\n    fi\n  else\n    echo \"cannot get server_por_cfg\"\n    TO_PWR_ON=$DEF_PWR_ON\n  fi\n}\n\nmb_server_power_on() {\n  if [ \"$(is_bmc_por)\" -eq 1 ]; then\n    check_por_config\n    if [ $TO_PWR_ON -eq 1 ]; then\n      /usr/local/bin/power-util mb on\n    fi\n  fi\n}\n\nmb_server_power_on\n", "num_lines": 67}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nMAX_RETRY=15\nNTP_CMD=/usr/sbin/ntpq\nME_CMD=/usr/local/bin/me-util\nSEL_TIME_RESPONSE_LEN=12\nSYNC_TIME_OK=0\n\nNETFN_STORAGE_REQ=\"0x28\" #after shift left 2 bits\nCMD_GET_SEL_TIME=\"0x48\"\n\n##### sync time from NTP server\nretry=0\nwhile [ $retry -lt \"$MAX_RETRY\" ]\ndo\n  if ! $NTP_CMD -p | grep '^\\*' > /dev/null ; then\n    retry=$((retry+1))\n    sleep 1\n  else\n    logger -s -p user.info -t sync-date \"Syncing up BMC time from NTP\"\n    exit 0\n  fi\ndone\n\n##### sync time from Host\n\nretry=0\nwhile [ $retry -lt \"$MAX_RETRY\" ]\ndo\n  output=$(\"$ME_CMD\" mb \"$NETFN_STORAGE_REQ\" \"$CMD_GET_SEL_TIME\")\n  \n  # sync BMC time only when ME returns correct response length\n  if [ ${#output} = \"$SEL_TIME_RESPONSE_LEN\" ] ; then\n    time_hex0=$(echo \"$output\" | cut -d' ' -f1 | sed 's/^0*//') # get byte0\n    time_hex1=$(echo \"$output\" | cut -d' ' -f2 | sed 's/^0*//') # get byte1\n    time_hex2=$(echo \"$output\" | cut -d' ' -f3 | sed 's/^0*//') # get byte2\n    time_hex3=$(echo \"$output\" | cut -d' ' -f4 | sed 's/^0*//') # get byte3\n\n    # change hexadecimal to decimal\n    time_dec=$((0x$time_hex3 << 24 | 0x$time_hex2 << 16 | 0x$time_hex1 << 8 | 0x$time_hex0))\n\n    # change decimal number to date formate\n    date -s @$time_dec +\"%Y.%m.%d-%H:%M:%S\"\n    ret=$?\n    if [ $ret = \"$SYNC_TIME_OK\" ]; then\n      logger -s -p user.info -t sync-date \"Syncing up BMC time from Host(ME)\"\n      exit 0\n    else\n      # get invalid SEL time\n      logger -s -p user.info -t sync-date \"Syncing up BMC time from Host(ME) failed because get invalid SEL time: $output\"\n      retry=$((retry+1))\n    fi\n  else\n    retry=$((retry+1))\n  fi\ndone\nlogger -s -p user.info -t sync-date \"Syncing up BMC time from Host(ME) failed because get SEL time from ME failed\"\n\n\n##### sync time from default time\nlogger -s -p user.info -t sync-date \"Syncing up BMC time from Default(OpenBMC build time)\"\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2014-present Facebook. All Rights Reserved.\n\n#\n# Functions to enable/disable isolation buffer:\n#\n# An Isolation Buffer is a 8-bit bus switch (TI SN74CBT3245APWR):\n#  - when OE (controlled by ISO_BUF_EN GPIO) is low, 8 input ports are\n#    connected to the 8 output ports.\n#  - when OE (controlled by ISO_BUF_EN GPIO) is high, input and output\n#    prots are disconnected.\n#\n# For more details, please refer to:\n#  - wedge schematics, \"BMC SIGNAL ISOLATION BUFFERS\" in page 61.\n#  - https://www.ti.com/store/ti/en/p/product/?p=SN74CBT3245APWR\n#\nwedge_iso_buf_enable() {\n    gpio_set_value ISO_BUF_EN 0\n}\n\nwedge_iso_buf_disable() {\n    gpio_set_value ISO_BUF_EN 1\n}\n\nwedge_is_us_on() {\n    local val n retries prog\n    if [ $# -gt 0 ]; then\n        retries=\"$1\"\n    else\n        retries=1\n    fi\n    if [ $# -gt 1 ]; then\n        prog=\"$2\"\n    else\n        prog=\"\"\n    fi\n    if [ $# -gt 2 ]; then\n        default=$3              # value 0 means defaul is 'ON'\n    else\n        default=1\n    fi\n    n=1\n    while true; do\n        val=$(cat \"${SYSFS_I2C_DEVICES}/4-0040/gpio_inputs\" 2>/dev/null)\n        if [ -n \"$val\" ]; then\n            break\n        fi\n        n=$((n+1))\n        if [ $n -gt $retries ]; then\n            echo -n \" failed to read GPIO. \"\n            return $default\n            break\n        fi\n        echo -n \"$prog\"\n        sleep 1\n    done\n    if [ \"$((val & (0x1 << 14)))\" != \"0\" ]; then\n        # powered on already\n        return 0\n    else\n        return 1\n    fi\n}\n\n\n# Return the board type, 'LC', 'FC-LEFT', 'FC-RIGHT', or, 'WEDGE'\nwedge_board_type() {\n    local pn\n    pn=$(/usr/bin/weutil 2> /dev/null | grep -i '^Location on Fabric:')\n    case \"$pn\" in\n        *LEFT*)\n            echo 'FC-LEFT'\n            ;;\n        *RIGHT*)\n            echo 'FC-RIGHT'\n            ;;\n        *LC*)\n            echo 'LC'\n            ;;\n        *)\n            echo 'WEDGE'\n            ;;\n    esac\n}\n\n# On FC,\n#   board rev < 2:\n#     FAB_SLOT_ID (GPIOU0), low == FC0; high == FC1\n#   else:\n#     FAB_SLOT_ID (GPIOU6), low == FC0; high == FC1\n## On LC, Wedge,\n#   board rev < 3:\n#     GPIOU0(ID0), GPIOU1(ID1), GPIOU2(ID2), GPIOU3(ID3)\n#   else:\n#     GPIOU6(ID0), GPIOU7(ID1), GPIOV0(ID2), GPIOV1(ID3)\n#\n# ID[2:0] ID3 Slot#\n# 000      0   1\n# 000      1   2\n# 001      0   3\n# 001      1   4\n# 010      0   5\n# 010      1   6\n# 011      0   7\n# 011      1   8\n\nwedge_slot_id() {\n    local type slot id3 id2 id1 id0 FC_CARD_BASE board_rev\n    FC_CARD_BASE=100\n    # need to check the board rev\n    board_rev=$(wedge_board_rev)\n    case \"$1\" in\n        FC-LEFT|FC-RIGHT)\n            # On FC\n            slot=$(gpio_get_value FAB_SLOT_ID)\n            if [ \"$1\" = \"FC-LEFT\" ]; then\n                # fabric card left\n                slot=$((FC_CARD_BASE * (slot + 1) + 1))\n            else\n                # fabric card right\n                slot=$((FC_CARD_BASE * (slot + 1) + 2))\n            fi\n            ;;\n        *)\n            # either edge or LC\n            id0=$(gpio_get_value BP_SLOT_ID0)\n            id1=$(gpio_get_value BP_SLOT_ID1)\n            id2=$(gpio_get_value BP_SLOT_ID2)\n            id3=$(gpio_get_value BP_SLOT_ID3)\n            slot=$(((id2 * 4 + id1 * 2 + id0) * 2 + id3 + 1))\n    esac\n    echo \"$slot\"\n}\n\n# wedge_board_rev() is only valid after GPIO Y0, Y1, and Y2 are enabled\nwedge_board_rev() {\n    local val0 val1 val2\n    val0=$(gpio_get_value BOARD_REV_ID0)\n    val1=$(gpio_get_value BOARD_REV_ID1)\n    val2=$(gpio_get_value BOARD_REV_ID2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    board_rev=$(wedge_board_rev)\n    board_type=$(wedge_board_type)\n    case \"$board_type\" in\n        FC-LEFT|FC-RIGHT)\n            if [ $board_rev -lt 2 ]; then\n                return 0\n            fi\n            ;;\n        *)\n            if [ $board_rev -lt 3 ]; then\n                return 0\n            fi\n            ;;\n    esac\n    return 1\n}\n", "num_lines": 162}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Function to set the less significant hex digit\ndisplay_lower() {  \n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n    \n    # Now set the GPIOs to the right binary values\n    gpio_set_value LED_POSTCODE_0 \"$bit0\"\n    gpio_set_value LED_POSTCODE_1 \"$bit1\"\n    gpio_set_value LED_POSTCODE_2 \"$bit2\"\n    gpio_set_value LED_POSTCODE_3 \"$bit3\"\n}\n\n# Function to set the more significant hex digit\ndisplay_upper() {\n    local bit0=$(expr $1 % 2)\n    local bit1=$(expr $1 / 2 % 2)\n    local bit2=$(expr $1 / 4 % 2)\n    local bit3=$(expr $1 / 8 % 2)\n\n    gpio_set_value LED_POSTCODE_4 \"$bit0\"\n    gpio_set_value LED_POSTCODE_5 \"$bit1\"\n    gpio_set_value LED_POSTCODE_6 \"$bit2\"\n    gpio_set_value LED_POSTCODE_7 \"$bit3\"\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\n# Get upper/lower decimal values\nLOWER_DEC_VALUE=$(expr $DEC_VALUE % 16)\nUPPER_DEC_VALUE=$(expr $DEC_VALUE / 16)\n\n# Display the results\ndisplay_lower $LOWER_DEC_VALUE\ndisplay_upper $UPPER_DEC_VALUE\n", "num_lines": 85}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Reset USB hub\n    /usr/local/bin/reset_usb.sh\n    # Set up ROV\n    /usr/local/bin/setup_rov.sh\n    # Configure the management switch on LEFT side of FC.\n    # Must do so after setup_rov.sh, as setup_rov.sh might reset\n    # T2, which also resets the switch.\n    if [ \"$(wedge_board_type)\" = \"FC-LEFT\" ]; then\n        echo -n \"Configure management switch ... \"\n        if [ $(wedge_board_rev) -gt 1 ]; then\n            echo \"skip. Need new switch setup script!!!\"\n        else\n            # configure MDIO as GPIO output\n            gpio_set_value BMC_MAC2_MDC 1\n            gpio_set_value BMC_MAC2_MDIO 1\n            # set the switch to be configured by CPU\n            gpio_set_value SWITCH_EEPROM1_WRT 1\n            # set the switch to be configured by CPU, then reset the switch,\n            # which also cause T2 reset in the current board\n            gpio_set_value SWITCH_EEPROM1_WRT 1\n            gpio_set_value T2_RESET_N 0\n            sleep 1\n            gpio_set_value T2_RESET_N 1\n            # configure the switch\n            setup_switch.py\n            echo \"done\"\n        fi\n    fi\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <on | off>\"\n    exit 1\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 1 ]; then\n    usage $0\nfi\n\nif [ $1 = \"on\" ]; then\n    val=1\nelif [ $1 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set_value LED_PWR_BLUE $val\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Make sure RESET_SEQ0 and RESET_SEQ1 are 0\ngpio_set_value RESET_SEQ0 0\ngpio_set_value RESET_SEQ1 0\n\n# Now toggle T2_RESET_N\ngpio_set_value T2_RESET_N 0\nsleep 1\ngpio_set_value T2_RESET_N 1\n\nlogger \"Reset T2 with both SEQ0 and SEQ1 low\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nsource /usr/local/bin/openbmc-utils.sh \n\necho -n \"Reset CP2112 Switch ... \"\n\ngpio_set_value USB_BRDG_RST 0\nusleep 50000\ngpio_set_value USB_BRDG_RST 1\n\necho \"Done\"\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\necho -n \"Reset USB Switch ... \"\n\ngpio_set_value BMC_USB_RESET_N 1\nsleep 1\ngpio_set_value BMC_USB_RESET_N 0\nsleep 1\ngpio_set_value BMC_USB_RESET_N 1\n\necho \"Done\"\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n\n. /usr/local/bin/openbmc-utils.sh\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    LEGACY_KERNEL=\"legacy-4.1\"\nfi\n\ndevmem_cond_set() {\n    local addr=$1\n    local bit=$2\n\n    if [ -n \"${LEGACY_KERNEL}\" ]; then\n        devmem_set_bit \"${addr}\" \"${bit}\"\n    fi\n}\n\ndevmem_cond_clear() {\n    local addr=$1\n    local bit=$2\n\n    if [ -n \"${LEGACY_KERNEL}\" ]; then\n        devmem_clear_bit \"${addr}\" \"${bit}\"\n    fi\n}\n\nsetup_gpio_fc_evt() {\n    local board_type=$1\n\n    # FAB_SLOT_ID is GPIOU0\n    # PEER_FAB_PRSNT is GPIOU1\n    devmem_cond_set \"$(scu_addr a0)\" 8\n    devmem_cond_set \"$(scu_addr a0)\" 9\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU0 FAB_SLOT_ID\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU1 PEER_FAB_PRSNT\n\n    # T2_POWER_UP is GPIOT6\n    devmem_cond_set \"$(scu_addr a0)\" 6\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT6 T2_POWER_UP\n\n    # HS_FAULT_N is GPIOT7\n    devmem_cond_set \"$(scu_addr a0)\" 7\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT7 HS_FAULT_N\n\n    if [ \"$board_type\" = \"FC-LEFT\" ]; then\n        # GPIOE2 is CPU_EEPROM_SEL, on FC-LEFT\n        devmem_cond_clear \"$(scu_addr 80)\" 18\n        devmem_cond_clear \"$(scu_addr 8c)\" 13\n        devmem_cond_clear \"$(scu_addr 70)\" 22\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOE2 CPU_EEPROM_SEL\n\n        # GPIOA6 and GPIOA7 are MAC2 MDIO pins, we use them as\n        # GPIO for bitbang driver\n        devmem_cond_clear \"$(scu_addr 90)\" 2\n        devmem_cond_clear \"$(scu_addr 80)\" 6\n        devmem_cond_clear \"$(scu_addr 80)\" 7\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOA6 BMC_MAC2_MDC\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOA7 BMC_MAC2_MDIO\n    fi\n}\n\nsetup_gpio_fc_dvt() {\n    local board_type=$1\n\n    if [ \"$board_type\" = \"FC-LEFT\" ]; then # Left FC\n        # BMC_SW_RST is GPIOL0, 16p switch\n        # SCU84[16] must be 0\n        devmem_cond_clear \"$(scu_addr 84)\" 16\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOL0 BMC_SW_RST\n        gpio_set_value BMC_SW_RST 1\n\n        # MDC|MDIO_CONT are GPIOR6 and GPIOR7, 16p switch\n        # SCU88[30:31] must be 0\n        devmem_cond_clear \"$(scu_addr 88)\" 30\n        devmem_cond_clear \"$(scu_addr 88)\" 31\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOR6 BMC_MAC1_MDC\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOR7 BMC_MAC1_MDIO\n        gpio_set_value BMC_MAC1_MDC 1\n        gpio_set_value BMC_MAC1_MDIO 1\n\n        # SWITCH_EEPROM1_WRT is GPIOE2, 16p switch EEPROM (U61)\n        # SCU80[18], SCU8C[13], and SCU70[22] must be 0\n        devmem_cond_clear \"$(scu_addr 80)\" 18\n        devmem_cond_clear \"$(scu_addr 8C)\" 13\n        devmem_cond_clear \"$(scu_addr 70)\" 22\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOE2 SWITCH_EEPROM1_WRT\n\n        # SPI bus to 16p switch EEPROM\n        # GPIOI4 <--> BMC_EEPROM1_SPI_SS\n        # GPIOI5 <--> BMC_EEPROM1_SPI_SCK\n        # GPIOI6 <--> BMC_EEPROM1_SPI_MOSI\n        # GPIOI7 <--> BMC_EEPROM1_SPI_MISO\n        # The EEPROM SPI clk does not match with the BMC SPI master.\n        # Have to configure these pins as GPIO to use with\n        # SPI bitbang driver.\n        # SCU70[13:12,5] must be 0\n        devmem_cond_clear \"$(scu_addr 70)\" 5\n        devmem_cond_clear \"$(scu_addr 70)\" 12\n        devmem_cond_clear \"$(scu_addr 70)\" 13\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI4 BMC_EEPROM1_SPI_SS\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI5 BMC_EEPROM1_SPI_SCK\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI6 BMC_EEPROM1_SPI_MOSI\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI7 BMC_EEPROM1_SPI_MISO\n\n        # BMC_PHY_RST is GPIOT0, Front Panel Port PHY on the 16p switch\n        # SCUA0[0] must be 1\n        devmem_cond_set \"$(scu_addr a0)\" 0\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT0 BMC_PHY_RST\n        gpio_set_value BMC_PHY_RST 1\n\n        # BMC_5PORTSW_RST is GPIOT1, 5p switch\n        # SCUA0[1] must be 1\n        devmem_cond_set \"$(scu_addr a0)\" 1\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT1 BMC_5PORTSW_RST\n        gpio_set_value BMC_5PORTSW_RST 1\n\n        # ISO_SWITCH1_MDC|MDIO are GPIOT4 and GPIOT5, 5p switch\n        # SCUA0[4:5] must be 1\n        devmem_cond_set \"$(scu_addr a0)\" 4\n        devmem_cond_set \"$(scu_addr a0)\" 5\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT4 ISO_SWITCH1_MDC\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT5 ISO_SWITCH1_MDIO\n        gpio_set_value ISO_SWITCH1_MDC 1\n        gpio_set_value ISO_SWITCH1_MDIO 1\n\n        # ISO_SWITCH_EEPROM2_WRT is GPIOV0, 5p switch EEPROM (U114)\n        # SCUA0[16] must be 1\n        devmem_cond_set \"$(scu_addr a0)\" 16\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOV0 ISO_SWITCH_EEPROM2_WRT\n\n        # SPI bus to 5p switch EEPROM (U114)\n        # GPIOI0 <--> ISO_BMC_EEPROM2_SPI_SS\n        # GPIOI1 <--> ISO_BMC_EEPROM2_SPI_SCK\n        # GPIOI2 <--> ISO_BMC_EEPROM2_SPI_MOSI\n        # GPIOI3 <--> ISO_BMC_EEPROM2_SPI_MISO\n        # The EEPROM SPI clk does not match with the BMC SPI master.\n        # Have to configure these pins as GPIO to use with\n        # SPI bitbang driver.\n        # SCU70[13] must be 0, has already been set when\n        # preparing for GPIOI4-GPIOI7\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI0 ISO_BMC_EEPROM2_SPI_SS\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI1 ISO_BMC_EEPROM2_SPI_SCK\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI2 ISO_BMC_EEPROM2_SPI_MOSI\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOI3 ISO_BMC_EEPROM2_SPI_MISO\n\n        # BMC_PHYL_RST is GPIOF0, Left BMC PHY\n        # SCU80[24] must be 0\n        devmem_cond_clear \"$(scu_addr 80)\" 24\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOF0 BMC_PHYL_RST\n        gpio_set_value BMC_PHYL_RST 1\n    else # Right FC\n        # BMC_PHYR_RST is GPIOL1, Right BMC PHY\n        # SCU84[17] must be 0\n        devmem_cond_clear \"$(scu_addr 84)\" 17\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOL1 BMC_PHYR_RST\n        gpio_set_value BMC_PHYR_RST 1\n    fi\n\n    # T2_POWER_UP is GPIOU4\n    # SCUA0[12] must be 1\n    devmem_cond_set \"$(scu_addr a0)\" 12\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU4 T2_POWER_UP\n\n    # HS_FAULT_N is GPIOU5\n    # SCUA0[13] must be 1\n    devmem_cond_set \"$(scu_addr a0)\" 13\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU5 HS_FAULT_N\n\n    # FAB_SLOT_ID is GPIOU6\n    # SCUA0[14] must be 1\n    devmem_cond_set \"$(scu_addr a0)\" 14\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU6 FAB_SLOT_ID\n\n    # PEER_FAB_PRSNT is GPIOU7\n    # SCUA0[15] must be 1\n    devmem_cond_set \"$(scu_addr a0)\" 15\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU7 PEER_FAB_PRSNT\n}\n\nsetup_gpio_lc_wedge() {\n    local board_rev=$1\n\n    # Set up to watch for FC presence, and switch between interfaces.\n    # GPIOC0..C7, interested in C4, C5\n    devmem_cond_clear \"$(scu_addr 90)\" 0\n    devmem_cond_clear \"$(scu_addr 90)\" 25\n\n    if [ \"$board_rev\" -lt 3 ]; then\n        # Prior to DVTC\n        # BP_SLOT_ID GPIO pins are U0, U1, U2, U3\n        devmem_cond_set \"$(scu_addr a0)\" 8\n        devmem_cond_set \"$(scu_addr a0)\" 9\n        devmem_cond_set \"$(scu_addr a0)\" 10\n        devmem_cond_set \"$(scu_addr a0)\" 11\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU0 BP_SLOT_ID0\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU1 BP_SLOT_ID1\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU2 BP_SLOT_ID2\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU3 BP_SLOT_ID3\n\n        # T2_POWER_UP is GPIOT6\n        devmem_cond_set \"$(scu_addr a0)\" 6\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT6 T2_POWER_UP\n\n        # HS_FAULT_N is GPIOT7\n        devmem_cond_set \"$(scu_addr a0)\" 7\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOT7 HS_FAULT_N\n    else\n        # Starting from DVTC\n        # BP_SLOT_ID GPIO pins are U6, U7, V0, V1\n        devmem_cond_set \"$(scu_addr 70)\" 6\n        devmem_cond_set \"$(scu_addr a0)\" 14\n        devmem_cond_set \"$(scu_addr a0)\" 15\n        devmem_cond_set \"$(scu_addr a0)\" 16\n        devmem_cond_set \"$(scu_addr a0)\" 17\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU6 BP_SLOT_ID0\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU7 BP_SLOT_ID1\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOV0 BP_SLOT_ID2\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOV1 BP_SLOT_ID3\n\n        # T2_POWER_UP is GPIOU4\n        devmem_cond_set \"$(scu_addr a0)\" 12\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU4 T2_POWER_UP\n\n        # HS_FAULT_N is GPIOU5\n        devmem_cond_set \"$(scu_addr a0)\" 13\n        gpio_export_by_name \"${ASPEED_GPIO}\" GPIOU5 HS_FAULT_N\n    fi\n}\n\n# Set up to read the board revision pins, Y0, Y1, Y2\ndevmem_cond_set \"$(scu_addr 70)\" 19\ndevmem_cond_clear \"$(scu_addr a4)\" 8\ndevmem_cond_clear \"$(scu_addr a4)\" 9\ndevmem_cond_clear \"$(scu_addr a4)\" 10\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY0 BOARD_REV_ID0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY1 BOARD_REV_ID1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY2 BOARD_REV_ID2\n\n# enabled Y0, Y1, Y2, we can use wedge_board_rev() now\nboard_rev=$(wedge_board_rev)\n\n# Set up ISO_SVR_ID[0-3], GPION[2-5]\n# On wedge, these 4 GPIOs are not connected. And the corresponding\n# 4 pins from uS are strapped to low.\n# On fabic, these 4 pins are connected to uS SVR_ID pins,\n# which are used to set the uS FPGA i2c address.\n# Force all pins to low to have the same uS FPGA i2c address on wedge\n# and fabric\n# To use GPION[2-5], SCU90[4:5] must be 0, and SCU88[2-5] must be 0 also\ndevmem_cond_clear \"$(scu_addr 90)\" 4\ndevmem_cond_clear \"$(scu_addr 90)\" 5\ndevmem_cond_clear \"$(scu_addr 88)\" 2\ndevmem_cond_clear \"$(scu_addr 88)\" 3\ndevmem_cond_clear \"$(scu_addr 88)\" 4\ndevmem_cond_clear \"$(scu_addr 88)\" 5\ngpio_export_by_name \"${ASPEED_GPIO}\" GPION2 ISO_SVR_ID0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPION3 ISO_SVR_ID1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPION4 ISO_SVR_ID2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPION5 ISO_SVR_ID3\nfor i in 0 1 2 3; do\n    gpio_set_value ISO_SVR_ID${i} 0\ndone\n\n## CARD_EN, GPIO C3\n#devmem_cond_clear \"$(scu_addr 90)\" 0\n#devmem_cond_clear \"$(scu_addr 90)\" 24\n#echo 18 > /sys/class/gpio/export\n\n# T2_RESET_N, RESET_SEQ0, RESET_SEQ1, on GPIO C0, F3, and F2\ndevmem_cond_clear \"$(scu_addr 90)\" 0\ndevmem_cond_clear \"$(scu_addr 90)\" 23\ndevmem_cond_clear \"$(scu_addr 80)\" 26\ndevmem_cond_clear \"$(scu_addr a4)\" 13\ndevmem_cond_clear \"$(scu_addr 80)\" 27\ndevmem_cond_clear \"$(scu_addr a4)\" 14\ndevmem_cond_set \"$(scu_addr 70)\" 19\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOC0 T2_RESET_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF2 RESET_SEQ1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF3 RESET_SEQ0\n\n# PANTHER_PRSNT_N, uServer presence, on GPIO E4\ndevmem_cond_clear \"$(scu_addr 80)\" 20\ndevmem_cond_clear \"$(scu_addr 8c)\" 14\ndevmem_cond_clear \"$(scu_addr 70)\" 22\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOE4 PANTHER_PRSNT_N\n\n# MRSRVR_SYS_RST, reset the uServer, on GPIO C1\ndevmem_cond_clear \"$(scu_addr 90)\" 0\ndevmem_cond_clear \"$(scu_addr 90)\" 23\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOC1 MRSRVR_SYS_RST\n# output\n\n# BMC_PWR_BTN_IN_N, uServer power button in, on GPIO D0\n# BMC_PWR_BTN_OUT_N, uServer power button out, on GPIO D1\ndevmem_cond_clear \"$(scu_addr 90)\" 1\ndevmem_cond_clear \"$(scu_addr 8c)\" 8\ndevmem_cond_clear \"$(scu_addr 70)\" 21\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOD0 BMC_PWR_BTN_IN_N\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOD1 BMC_PWR_BTN_OUT_N\n# we have to ensure that BMC_PWR_BTN_OUT_N is high so that\n# when we enable the isolation buffer, uS will not be powered down\ngpio_set_value BMC_PWR_BTN_OUT_N 1\n\n## BMC_READY_IN, BMC signal that it's up, on GPIO P7\n# To use GPIOP7 (127), SCU88[23] must be 0\ndevmem_cond_clear \"$(scu_addr 88)\" 23\n# Put GPIOP7 (127) to low so that we can control uS power now\n# This must be after 'gpio_set 25 1'\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOP7 BMC_READY_IN\ngpio_set_value BMC_READY_IN 0\n\n# PANTHER_I2C_ALERT_N, alert for uServer I2C, GPIO B0\ndevmem_cond_clear \"$(scu_addr 80)\" 8\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB0 PANTHER_I2C_ALERT_N\n\n# MNSERV_NIC_SMBUS_ALRT, alert for uServer NIC, GPIO B1\ndevmem_cond_clear \"$(scu_addr 80)\" 9\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB1 MNSERV_NIC_SMBUS_ALRT\n\n# LED_PWR_BLUE, blue power light, GPIO E5\ndevmem_cond_clear \"$(scu_addr 80)\" 21\ndevmem_cond_clear \"$(scu_addr 8c)\" 14\ndevmem_cond_clear \"$(scu_addr 70)\" 22\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOE5 LED_PWR_BLUE\n# output\n\n# BMC_HEARTBEAT_N, heartbeat LED, GPIO Q7\ndevmem_cond_clear \"$(scu_addr 90)\" 28\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ7 BMC_HEARTBEAT_N\n# output\n\n# XXX:  setting those causes the system to lock up on reboot\n## T2 ROV1, ROV2, ROV3 -- voltage reading, GPIOs H0, H1, and H2\n#devmem_cond_clear \"$(scu_addr 90)\" 6\n#devmem_cond_clear \"$(scu_addr 90)\" 7\n#devmem_cond_clear \"$(scu_addr 70)\" 4\n## Do I need to set 70:1 and 70:0 to 1?\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH0 T2_ROV1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH1 T2_ROV2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOH2 T2_ROV3\n\n# HOTSWAP_PG, hotswap issues, GPIO L3\ndevmem_cond_clear \"$(scu_addr 90)\" 5\ndevmem_cond_clear \"$(scu_addr 90)\" 4\ndevmem_cond_clear \"$(scu_addr 84)\" 19\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOL3 HOTSWAP_PG\n\n# XXX:  These interfere with i2c bus 11 (on Linux, it's 12 on the hardware)\n# which we need to talk to the power supplies on certain hardware.\n## Hardware presence pins C4 and C5\n#devmem_cond_clear \"$(scu_addr 90)\" 0\n#devmem_cond_clear \"$(scu_addr 90)\" 24\n#echo 20 > /sys/class/gpio/export\n#echo 21 > /sys/class/gpio/export\n\n# FAB_GE_SEL, uServer GE connection, GPIO A0\ndevmem_cond_clear \"$(scu_addr 80)\" 0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOA0 FAB_GE_SEL\n# output\n\n# USB_OCS_N1, resettable fuse tripped, GPIO Q6\ndevmem_cond_clear \"$(scu_addr 90)\" 28\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ6 USB_OCS_N1\n\n# RX loss signal?\n\n# System SPI\n# Strap 12 must be 0 and Strape 13 must be 1\ndevmem_cond_clear \"$(scu_addr 70)\" 12\ndevmem_cond_set \"$(scu_addr 70)\" 13\n# GPIOQ4 is ISO_FLASH_WP, must be 1 to avoid write protection\n# GPIOQ5 is ISO_FLASH_HOLD, must be 1 to be out of reset\n# To use GPIOQ4 and GPIOQ5, SCU90[27] must be 0\ndevmem_cond_clear \"$(scu_addr 90)\" 27\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ4 ISO_FLASH_WP\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOQ5 ISO_FLASH_HOLD\ngpio_set_value ISO_FLASH_WP 1\ngpio_set_value ISO_FLASH_HOLD 1\n# GPIOD6 is ISO_FL_PRG_SEL, set it to 0 so that BMC does not have control\n# on the EEPROM by default.\n# To use GPIOD6, SCU90[1] must be 0, SCU8C[21] must be 0, and Strap[21] must be 0\ndevmem_cond_clear \"$(scu_addr 90)\" 1\ndevmem_cond_clear \"$(scu_addr 8c)\" 8\ndevmem_cond_clear \"$(scu_addr 70)\" 21\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOD6 ISO_FL_PRG_SEL\ngpio_set_value ISO_FL_PRG_SEL 0\n\n# DEBUG_RST_BTN_N, Debug Reset button on front panel, GPIO R2\ndevmem_cond_clear \"$(scu_addr 88)\" 26\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOR2 DEBUG_RST_BTN_N\n\n# DEBUG_PORT_UART_SEL_N, Debug Select button, GPIO B2\ndevmem_cond_clear \"$(scu_addr 80)\" 10\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB2 DEBUG_PORT_UART_SEL_N\n\n# DEBUG_UART_SEL_0, select uServer UART to the debug header, GPIO E0\ndevmem_cond_clear \"$(scu_addr 80)\" 16\ndevmem_cond_clear \"$(scu_addr 8c)\" 12\ndevmem_cond_clear \"$(scu_addr 70)\" 22\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOE0 DEBUG_UART_SEL_0\n# output\n\n# USB_BRDG_RST , GPIO D4\ndevmem_cond_clear \"$(scu_addr 90)\" 1\ndevmem_cond_clear \"$(scu_addr 8c)\" 10\ndevmem_cond_clear \"$(scu_addr 70)\" 21\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOD4 USB_BRDG_RST\n\n# Bloodhound GPIOs, P0-6, G4, J1-3, Y3\n# Make sure GPIOP0,1,2,3,6 are enabled.\nfor i in {16..19} 22; do\n  devmem_cond_clear \"$(scu_addr 88)\" $i\ndone\n# Enable GPIOY3\ndevmem_cond_clear \"$(scu_addr a4)\" 11\n# GPIOG4\ndevmem_cond_clear \"$(scu_addr 2c)\" 1\n# GPIOJ1\ndevmem_cond_clear \"$(scu_addr 84)\" 9\n# GPIOJ2\ndevmem_cond_clear \"$(scu_addr 84)\" 10\n# GPIOJ11\ndevmem_cond_clear \"$(scu_addr 84)\" 11\n\n# Export all the GPIOs\nfor i in {0..6}; do\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOP${i} BLOODHOUND_GPIOP${i}\ndone\nfor i in {1..3}; do\n    gpio_export_by_name \"${ASPEED_GPIO}\" GPIOJ${i} BLOODHOUND_GPIOJ${i}\ndone\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG4 BLOODHOUND_GPIOG4\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOY3 BLOODHOUND_GPIOY3\n\n# ISO_BUF_EN, GPIOC2, SCU90[0] and SCU90[24] must be 0\ndevmem_cond_clear \"$(scu_addr 90)\" 0\ndevmem_cond_clear \"$(scu_addr 90)\" 24\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOC2 ISO_BUF_EN\n\n# Enable the isolation buffer\nwedge_iso_buf_enable\n\n# load the EEPROM\ni2c_device_add 6 0x50 24c64\n\n# Get the board type by parsing the EEPROM.\n# This must be after enabling isolation buffer as the i2c bus\n# is isolated by the buffer\nboard_type=$(wedge_board_type)\n\ncase \"$board_type\" in\n    FC-LEFT|FC-RIGHT)\n        # On FC\n        if [ \"$board_rev\" -lt 2 ]; then\n            # EVT board\n            setup_gpio_fc_evt \"$board_type\"\n        else\n            # DVT board\n            setup_gpio_fc_dvt \"$board_type\"\n        fi\n        ;;\n    *)\n        setup_gpio_lc_wedge \"$board_rev\"\n        ;;\nesac\n\n# Make it possible to turn off T2 if fand sees overheating via GPIOF1\n# Do not change the GPIO direction here as the default value of this GPIO\n# is low, which causes a Non-maskable interrupt to the uS.\ndevmem_cond_clear \"$(scu_addr 80)\" 25\ndevmem_cond_clear \"$(scu_addr a4)\" 12\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOF1 BMC_GPIOF1\n\n# Allow us to set the fan LEDs boards.\n# This is GPIO G5, G6, G7, and J0\n\ndevmem_cond_clear \"$(scu_addr 70)\" 23\ndevmem_cond_clear \"$(scu_addr 84)\" 5\ndevmem_cond_clear \"$(scu_addr 84)\" 6\ndevmem_cond_clear \"$(scu_addr 84)\" 7\ndevmem_cond_clear \"$(scu_addr 84)\" 8\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG5 FAN_LED_GPIOG5\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG6 FAN_LED_GPIOG6\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG7 FAN_LED_GPIOG7\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOJ0 FAN_LED_GPIOJ0\n\ngpio_set_direction FAN_LED_GPIOG5 out\ngpio_set_direction FAN_LED_GPIOG6 out\ngpio_set_direction FAN_LED_GPIOG7 out\ngpio_set_direction FAN_LED_GPIOJ0 out\n\n# Once we set \"out\", output values will be random unless we set them\n# to something\ngpio_set_value FAN_LED_GPIOG5 0\ngpio_set_value FAN_LED_GPIOG6 0\ngpio_set_value FAN_LED_GPIOG7 0\ngpio_set_value FAN_LED_GPIOJ0 0\n\n#\n# Setup LED_POSTCODE_[0..3], connected to GPIOG[0..3]:\n#   - GPIOG[0..3]: SCU84[0..3] = 0\n#\ndevmem_cond_clear $(scu_addr 84) 0\ndevmem_cond_clear $(scu_addr 84) 1\ndevmem_cond_clear $(scu_addr 84) 2\ndevmem_cond_clear $(scu_addr 84) 3\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG0 LED_POSTCODE_0\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG1 LED_POSTCODE_1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG2 LED_POSTCODE_2\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOG3 LED_POSTCODE_3\n\n#\n# Setup LED_POSTCODE_[4..7], connected to GPIOB[4..7]:\n#   - GPIOB4: SCU80[12] = 0 and Strap[14] = 0\n#   - GPIOB[5..7]: SCU80[13..15] = 0\n#\ndevmem_cond_clear $(scu_addr 70) 14\ndevmem_cond_clear $(scu_addr 80) 12\ndevmem_cond_clear $(scu_addr 80) 13\ndevmem_cond_clear $(scu_addr 80) 14\ndevmem_cond_clear $(scu_addr 80) 15\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB4 LED_POSTCODE_4\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB5 LED_POSTCODE_5\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB6 LED_POSTCODE_6\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOB7 LED_POSTCODE_7\n\n#\n# Setup BMC_USB_RESET_N, connected to GPIOD7\n#   - GPIOD7: SCU90[1], SCU8C[11], and SCU70[21] must be 0\n#\ndevmem_cond_clear $(scu_addr 8C) 11\ndevmem_cond_clear $(scu_addr 70) 21\ndevmem_cond_clear $(scu_addr 90) 1\ngpio_export_by_name \"${ASPEED_GPIO}\" GPIOD7 BMC_USB_RESET_N\n", "num_lines": 574}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Bus 1\ni2c_device_add 1 0x60 ncp4200\n\n# Bus 2\ni2c_device_add 2 0x60 ncp4200\n\n# Bus 3\ni2c_device_add 3 0x48 tmp75\ni2c_device_add 3 0x49 tmp75\ni2c_device_add 3 0x4a tmp75\n\n# Bus 4\ni2c_device_add 4 0x40 fb_panther_plus\ni2c_device_add 4 0x51 24c128\n\n# Bus 6, trouble\ni2c_device_add 6 0x28 max127\ni2c_device_add 6 0x3f pcf8574\n\n# Bus 7\ni2c_device_add 7 0x50 24c64         # 6pack power supply EEPROM\ni2c_device_add 7 0x51 24c64         # wedge power supply EEPROM\ni2c_device_add 7 0x52 24c64         # wedge power supply EEPROM\ni2c_device_add 7 0x59 pfe1100       # wedge power supply\ni2c_device_add 7 0x5a pfe1100       # wedge power supply\n\n# Bus 8\ni2c_device_add 8 0x60 ncp4200\n\n# Bus 12\ni2c_device_add 12 0x10 adm1278\n\ni2c_check_driver_binding\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# The T2 chip can prefer different input voltages, depending, presumably\n# of manufacturing variations.  We need to determine whether it wants\n# 0.95V or 1.025V, reset the T2 to reduce total power usage, set the\n# outgoing voltage on the first buck converter, and bring T2 up out of\n# reset.\n\n. /usr/local/bin/openbmc-utils.sh\n\nPMBUS_DRIVER_DIR=\"${SYSFS_I2C_DRIVERS}/pmbus\"\n\n# read the T2 ROV after the GPIOs are enabled\nt2_rov() {\n    local val0 val1 val2\n    # Note that the values are *not* read in order.\n    val0=$(gpio_get_value T2_ROV3)\n    val1=$(gpio_get_value T2_ROV1)\n    val2=$(gpio_get_value T2_ROV2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nrov=$(t2_rov)\n\n# target_volts come from the data sheet and 18mV of loss and\n# some fudging based on actual measurements to get either 1.025V\n# or 0.95V at T2\nif [ $rov -eq 1 ]; then\n    target_volts=0x5a\nelif [ $rov -eq 2 ]; then\n    target_volts=0x65\nelse\n    echo \"Unrecognized T2 ROV value $rov, setting failed.\"\n    exit 1\nfi\ntarget_volts=$((target_volts * 1))  # normalize to decimal\n\n#\n# Unbind pmbus driver from 1-0060, otherwise, following i2cget could\n# fail with EBUSY.\n#\necho 1-0060 > \"${PMBUS_DRIVER_DIR}/unbind\"\n\n# Get current voltage value.\n# The device here is NCP4200. It turns out the first i2c transaction to this\n# device always fails. The spec does not mention anything about NCP4200 i2c\n# engine start delay. However, each time, when the isolation buffer between the\n# BMC i2c controller and NCP4200 is disabled and re-enabled, the first i2c\n# transaction to NCP4200 always fails.\n# To workaround this issue, we are doing the first read twice.\ncur_volts=$(i2cget -y 1 0x60 0x8b w 2> /dev/null)\ncur_volts=$(i2cget -y 1 0x60 0x8b w)\ncur_volts=$((cur_volts * 1))  # normalize to decimal\n\n# Only bounce the T2 if we actually need to modify the voltage\nif [ $cur_volts -ne $target_volts ]; then\n    # Set values before turning out output;  we're using \"PCIE, then MCS\"\n    gpio_set_value RESET_SEQ1 1\n    gpio_set_value RESET_SEQ0 1\n    gpio_set_direction RESET_SEQ1 out\n    gpio_set_direction RESET_SEQ0 out\n    gpio_set_value T2_RESET_N 0\n    gpio_set_direction T2_RESET_N out\n    # T2 is in reset;  note that this may cause NMI messages on the uServer,\n    # which shouldn't be up anyway when this is first run.\n\n    # Set the requested value to the current value to avoid rapid shifts\n    i2cset -y 1 0x60 0x21 $cur_volts w\n    # Enable the requested voltage\n    i2cset -y 1 0x60 0xd2 0x5a\n    i2cset -y 1 0x60 0xd3 0x5a\n    sleep 1\n\n    # Set the target voltage\n    i2cset -y 1 0x60 0x21 $target_volts w\n\n    sleep 1\n\n    # Let T2 come out of reset\n    gpio_set_value T2_RESET_N 1\n    echo \"T2 ROV value set based on $rov.\"\n    sleep 2\n    gpio_set_value RESET_SEQ1 0\n    gpio_set_value RESET_SEQ0 0\nelse\n    echo \"T2 ROV already correctly set.\"\nfi\n\n#\n# Bind pmbus driver to 1-0060.\n#\necho 1-0060 > \"${PMBUS_DRIVER_DIR}/bind\"\n", "num_lines": 111}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS1\n\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ $pid ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -a $FILE ]\n    then\n      read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 $TTY\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          us-monitor\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Start the microserver reset monitoring script\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=\"us_monitor\"\nDESC=\"monitoring microserver reset\"\nDAEMON=\"us_monitor.sh\"\n\n# source function library\n. /etc/init.d/functions\n\n. /usr/local/bin/openbmc-utils.sh\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    echo -n \"Starting $DESC: \"\n    /usr/local/bin/${DAEMON} > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall ${DAEMON}\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall ${DAEMON}\n    /usr/local/bin/${DAEMON} > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status ${DAEMON}\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 74}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\n# GPIOE0 (DEBUG_UART_SEL_0) controls if uS console connects to UART1 or not.\ngpio_set_value DEBUG_UART_SEL_0 $VALUE\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Because the voltage leak from uS COM pins could cause uS to struck when\n# transitting from S5 to S0, we will need to explicitely pull down uS COM\n# pins before powering off/reset and restoring COM pins after\n\n_logger() {\n    logger \"USMON: \" $*\n}\n\npull_down_us_com() {\n    if [ $connected -eq 0 || $down -eq 0 ]; then\n        _logger \"Connect console pins with pull down\"\n        connected=1\n        down=1\n    fi\n\n    #\n    # XXX do we need to configure GPIOL6/GPIOL7 (BMC_UART1_TX/RX) as GPIO\n    # and set them to low?\n    #\n\n    # now, connect uart from BMC to the uS\n    gpio_set_value DEBUG_UART_SEL_0 1\n}\n\nrestore_us_com() {\n    # if sol.sh or terminal server is running, keep uServer console UART\n    # connected with BMC\n    if pidof -x sol.sh > /dev/null 2>&1 || pidof -x mTerm_server > /dev/null 2>&1; then\n        if [ $connected -eq 0 ]; then\n            _logger \"Restore console. Keep connected\"\n            connected=1\n        fi\n        gpio_set_value DEBUG_UART_SEL_0 1\n    else\n        if [ $connected -eq 1 ]; then\n            _logger \"Restore console. Keep disconnected\"\n            connected=0\n        fi\n        gpio_set_value DEBUG_UART_SEL_0 0\n    fi\n    down=0\n}\n\nconnected=0\ndown=1\nwhile true; do\n    if ! wedge_is_us_on 1 '' 0 > /dev/null 2>&1; then\n        pull_down_us_com\n    else\n        restore_us_com\n    fi\n    usleep 400000               # 400ms\ndone\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge system ungracefully\"\n    echo\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n    fi\n    return 0\n}\n\ndo_on() {\n    local force opt pulse_us n retries\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on 10 \".\"; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n    # start with resetting T2\n    reset_brcm.sh\n    # first make sure, GPIOD1 (25) is high\n    gpio_set_value BMC_PWR_BTN_OUT_N 1\n    sleep 1\n    # then, put GPIOP7 (127) to low\n    gpio_set_value BMC_READY_IN 0\n    pulse_us=500000             # 500ms\n    retries=3\n    n=1\n    while true; do\n        # first make sure, GPIOD1 (25) is high\n        gpio_set_value BMC_PWR_BTN_OUT_N 1\n        usleep $pulse_us\n        # generate the power on pulse\n        gpio_set_value BMC_PWR_BTN_OUT_N 0\n        usleep $pulse_us\n        gpio_set_value BMC_PWR_BTN_OUT_N 1\n        sleep 3\n        if wedge_is_us_on 1 '' 1; then\n            break\n        fi\n        n=$((n+1))\n        if [ $n -gt $retries ]; then\n            echo \" Failed\"\n            logger \"Failed to power on micro-server\"\n            return 1\n        fi\n        echo -n \"...\"\n    done\n    # Turn on the power LED (GPIOE5)\n    /usr/local/bin/power_led.sh on\n    echo \" Done\"\n    logger \"Successfully power on micro-server\"\n    return 0\n}\n\ndo_off() {\n    echo -n \"Power off microserver ...\"\n    # first make sure, GPIOD1 (25) is high\n    gpio_set_value BMC_PWR_BTN_OUT_N 1\n    # then, put GPIOP7 (127) to low\n    gpio_set_value BMC_READY_IN 0\n    gpio_set_value BMC_PWR_BTN_OUT_N 0\n    sleep 5\n    gpio_set_value BMC_PWR_BTN_OUT_N 1\n    # Turn off the power LED (GPIOE5)\n    /usr/local/bin/power_led.sh off\n    echo \" Done\"\n    logger \"Successfully power off micro-server\"\n    return 0\n}\n\ndo_reset() {\n    local system opt\n    system=0\n    while getopts \"s\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        logger \"Power reset the whole system ...\"\n        echo -n \"Power reset the whole system ...\"\n        sleep 1             # give some time for the message to go out\n        i2cset -f -y 12 0x10 0xd9 c\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return -1\n        fi\n        # reset T2 first\n        reset_brcm.sh\n        echo -n \"Power reset microserver ...\"\n        # then, put GPIOP7 (127) to low\n        gpio_set_value BMC_READY_IN 0\n        gpio_set_value MRSRVR_SYS_RST 0\n        sleep 1\n        gpio_set_value MRSRVR_SYS_RST 1\n        sleep 1\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nexit $?\n", "num_lines": 200}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nmac=$(i2cdump -y 0x0 0x49 s 0xd4 | grep '^00: d4'| awk '{ print $3\":\"$4\":\"$5\":\"$6\":\"$7\":\"$8 }') 2>/dev/null\n\nif [ -n \"$mac\" ]; then\n    echo $mac\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\nfi\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          bmc-log\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Collect micro-server kernel logs through serial port\n### END INIT INFO\n\n. /etc/default/bmc-log\n. /etc/init.d/functions\n\nDAEMON=/usr/sbin/bmc-log\nNAME=bmc-log\nDESC=\"Micro-Server log collection\"\n\nTTY=${US_TTY:-/dev/ttyS1}\nIP=${LOG_SERVER_IP_VERSION:-4}\nLOG_SERVER=${LOG_SERVER_NAME:-}\nPORT=${LOG_SERVER_PORT:-}\nBAUD_RATE=${TTY_BAUD_RATE:-}\n\nif [ -z \"$LOG_SERVER\" ] || [ -z \"$PORT\" ]\nthen\n\techo \"Error: Server and/or port not set\"\n\texit 0\nfi\n\n\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n  \techo -e \"Starting $DESC\"\n\t$DAEMON $TTY $IP $LOG_SERVER $PORT $BAUD_RATE\n    ;;\n  stop)\n    echo -e \"Stopping $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    ;;\n   restart|force-reload)\n    echo -e \"Restarting $DESC: \"\n    start-stop-daemon --stop --quiet --exec $DAEMON\n    sleep 1\n    $DAEMON $TTY $IP $LOG_SERVER $PORT $BAUD_RATE\n    ;;\n  status)\n    stat $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n", "num_lines": 78}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\n\n. \"/usr/local/bin/pwm_common.sh\"\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    PWM_SYSFS_DIR=\"/sys/devices/platform/ast_pwm_tacho.0\"\n\n    #\n    # Refer to \"init_pwm.sh\" for more details about fan-tacho mapping.\n    #\n    FAN_TACHO_MAP=\"0:3,7 1:2,6 2:0,4 3:1,5\"\nelse\n    PWM_SYSFS_DIR=$(hwmon_lookup_by_name \"aspeed_pwm_tacho\")\n    if [ -z \"$PWM_SYSFS_DIR\" ]; then\n        echo \"unable to find hwmon directory for aspeed_pwm_tacho. Exiting!\"\n        exit 1\n    fi\n    FAN_TACHO_MAP=\"0:4,8 1:3,7 2:1,5 3:2,6\"\nfi\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (0..3)]\" >&2\n}\n\nget_fan_speed_41() {\n    fan_id=\"$1\"\n    front_tacho=\"$2\"\n    rear_tacho=\"$3\"\n\n    front_rpm=$(cat \"${PWM_SYSFS_DIR}/tacho${front_tacho}_rpm\")\n    rear_rpm=$(cat \"${PWM_SYSFS_DIR}/tacho${rear_tacho}_rpm\")\n    echo \"Fan $fan_id RPMs: $front_rpm, $rear_rpm\"\n}\n\nget_fan_speed_5x() {\n    fan_id=\"$1\"\n    front_tacho=\"$2\"\n    rear_tacho=\"$3\"\n\n    front_rpm=$(cat \"${PWM_SYSFS_DIR}/fan${front_tacho}_input\")\n    rear_rpm=$(cat \"${PWM_SYSFS_DIR}/fan${rear_tacho}_input\")\n    echo \"Fan $fan_id RPMs: $front_rpm, $rear_rpm\"\n}\n\nget_fan_speed() {\n    fan_id=\"$1\"\n    tacho_list=\"$2\"\n\n    front_tacho=${tacho_list%%,*}\n    rear_tacho=${tacho_list##*,}\n    if uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n        get_fan_speed_41 \"$fan_id\" \"$front_tacho\" \"$rear_tacho\"\n    else\n        get_fan_speed_5x \"$fan_id\" \"$front_tacho\" \"$rear_tacho\"\n    fi\n}\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FAN_TACHOS=\"$FAN_TACHO_MAP\"\nelif [ \"$#\" -eq 1 ]; then\n    case \"$1\" in\n    \"0\")\n        FAN_TACHOS=$(echo \"$FAN_TACHO_MAP\" | cut -d' ' -f1)\n        ;;\n    \"1\")\n        FAN_TACHOS=$(echo \"$FAN_TACHO_MAP\" | cut -d' ' -f2)\n        ;;\n    \"2\")\n        FAN_TACHOS=$(echo \"$FAN_TACHO_MAP\" | cut -d' ' -f3)\n        ;;\n    \"3\")\n        FAN_TACHOS=$(echo \"$FAN_TACHO_MAP\" | cut -d' ' -f4)\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\n    esac\nelse\n    usage\n    exit 1\nfi\n\nfor fan_tacho in $FAN_TACHOS; do\n    fan_id=${fan_tacho%%:*}\n    tacho_list=${fan_tacho##*:}\n\n    get_fan_speed \"$fan_id\" \"$tacho_list\"\ndone\n", "num_lines": 111}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/bin/openbmc-utils.sh\n\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n#\n# Note: the script is only needed for kernel 4.1, as pwm/tacho is already\n# initialized in device tree in kernel 5.x.\n#\nif ! uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    exit 0\nfi\n\n# Enable PWM 0, 1, 6, 7\ndevmem_set_bit $(scu_addr 88) 0\ndevmem_set_bit $(scu_addr 88) 1\ndevmem_set_bit $(scu_addr 88) 6\ndevmem_set_bit $(scu_addr 88) 7\n\n# Eable tacho 0-7\ndevmem_clear_bit $(scu_addr 88) 8\ndevmem_clear_bit $(scu_addr 88) 9\ndevmem_clear_bit $(scu_addr 88) 10\ndevmem_clear_bit $(scu_addr 88) 11\ndevmem_clear_bit $(scu_addr 88) 12\ndevmem_clear_bit $(scu_addr 88) 13\ndevmem_clear_bit $(scu_addr 88) 14\ndevmem_clear_bit $(scu_addr 88) 15\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On wedge, there are 4 fans connected.\n# Each fan has one PWM input and 2 tacho outputs.\n# Here is the mapping between the fan and PWN/Tacho,\n# staring from the one from the edge\n# Fan 0: PWM 7, Tacho3, Tacho7\n# Fan 1: PWM 6, Tacho2, Tacho6\n# Fan 2: PWM 0, Tacho0, Tacho4\n# Fan 3: PWM 1, Tacho1, Tacho5\n\n# For each fan, setting the type, and 100% initially\nfor pwm in 0 1 6 7; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0..7\necho 0 > $PWM_DIR/tacho0_source\necho 0 > $PWM_DIR/tacho4_source\necho 1 > $PWM_DIR/tacho1_source\necho 1 > $PWM_DIR/tacho5_source\necho 6 > $PWM_DIR/tacho2_source\necho 6 > $PWM_DIR/tacho6_source\necho 7 > $PWM_DIR/tacho3_source\necho 7 > $PWM_DIR/tacho7_source\nt=0\nwhile [ $t -le 7 ]; do\n    echo 1 > $PWM_DIR/tacho${t}_en\n    t=$((t+1))\ndone\n", "num_lines": 98}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\n\nHWMON_SYSFS_ROOT=\"/sys/class/hwmon\"\n\n#\n# Lookup pwm sysfs directory, used in kernel 5.x or higher versions.\n#\nhwmon_lookup_by_name() {\n    hwmon_name=\"$1\"\n    pwm_dir=\"\"\n\n    for entry in \"${HWMON_SYSFS_ROOT}\"/*; do\n        if echo \"$entry\" | grep \"/hwmon/hwmon\" > /dev/null 2>&1; then\n            if grep \"$hwmon_name\" \"${entry}/name\" > /dev/null 2>&1; then\n                pwm_dir=\"$entry\"\n                break\n            fi\n        fi\n    done\n\n    echo \"$pwm_dir\"\n}\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\n# Enable the isolation buffer\nwedge_iso_buf_enable\n\necho -n \"Setup fan speed... \"\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    /usr/local/bin/init_pwm.sh\nfi\n/usr/local/bin/set_fan_speed.sh 50\n/usr/local/bin/fand\necho \"done.\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\n\n. \"/usr/local/bin/pwm_common.sh\"\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    PWM_SYSFS_DIR=\"/sys/devices/platform/ast_pwm_tacho.0\"\n\n    #\n    # Refer to \"init_pwm.sh\" for more details about pwm configuration as\n    # well as fan-pwm mapping.\n    #\n    PWM_UNIT_MAX=96\n    FAN_PWM_MAP=\"0:7 1:6 2:0 3:1\"\nelse\n    # kernel 5.x and higher versions\n    PWM_SYSFS_DIR=$(hwmon_lookup_by_name \"aspeed_pwm_tacho\")\n    if [ -z \"$PWM_SYSFS_DIR\" ]; then\n        echo \"unable to find hwmon directory for aspeed_pwm_tacho. Exiting!\"\n        exit 1\n    fi\n    PWM_UNIT_MAX=256\n    FAN_PWM_MAP=\"0:8 1:7 2:1 3:2\"\nfi\n\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (0..3)> \" >&2\n}\n\nset_fan_pwm_41() {\n    pwm_id=\"$1\"\n    unit=\"$2\"\n\n    if [ \"$unit\" -eq 0 ]; then\n        # For 0%, turn off the PWM entirely\n        echo 0 > \"$PWM_SYSFS_DIR/pwm${pwm_id}_en\"\n    else\n        if [ \"$unit\" -eq $PWM_UNIT_MAX ]; then\n            # For 100%, set falling and rising to the same value\n            unit=0\n        fi\n\n        # always use type M. refer to the comments in init_pwm.sh\n        echo 0 > \"$PWM_SYSFS_DIR/pwm${pwm_id}_type\"\n        echo 0 > \"$PWM_SYSFS_DIR/pwm${pwm_id}_rising\"\n        echo \"$unit\" > \"$PWM_SYSFS_DIR/pwm${pwm_id}_falling\"\n        echo 1 > \"$PWM_SYSFS_DIR/pwm${pwm_id}_en\"\n    fi\n}\n\nset_fan_pwm_5x() {\n    pwm_id=\"$1\"\n    unit=\"$2\"\n\n    echo \"$unit\" > \"${PWM_SYSFS_DIR}/pwm${pwm_id}\"\n}\n\nset_fan_speed() {\n    pwm_id=\"$1\"\n    percent=\"$2\"\n    unit=$((percent * PWM_UNIT_MAX / 100))\n\n    if uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n        set_fan_pwm_41 \"$pwm_id\" \"$unit\"\n    else\n        set_fan_pwm_5x \"$pwm_id\" \"$unit\"\n    fi\n}\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\nPERCENT=\"$1\"\nFAN_ID=\"$2\"\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and PWM mapping\nif [ \"$#\" -eq 1 ]; then\n    FAN_PWMS=\"${FAN_PWM_MAP}\"\nelse\n    case \"$FAN_ID\" in\n    \"0\")\n        FAN_PWMS=$(echo \"$FAN_PWM_MAP\" | cut -d' ' -f1)\n        ;;\n    \"1\")\n        FAN_PWMS=$(echo \"$FAN_PWM_MAP\" | cut -d' ' -f2)\n        ;;\n    \"2\")\n        FAN_PWMS=$(echo \"$FAN_PWM_MAP\" | cut -d' ' -f3)\n        ;;\n    \"3\")\n        FAN_PWMS=$(echo \"$FAN_PWM_MAP\" | cut -d' ' -f4)\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\n    esac\nfi\n\nfor fan_pwm in $FAN_PWMS; do\n    fan_id=${fan_pwm%%:*}\n    pwm_id=${fan_pwm##*:}\n\n    set_fan_speed \"$pwm_id\" \"$PERCENT\"\n    echo \"Successfully set fan ${fan_id} (PWM: $pwm_id) speed to $percent%\"\ndone\n", "num_lines": 127}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ipmid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set IPMI Message handler\n### END INIT INFO\n\necho -n \"Setup IPMI message handler... \"\n/usr/local/bin/ipmid\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    # Eventually, this will be used to configure the various (mostly\n    # i2c-based) sensors, once we have a kernel version that supports\n    # doing this more dynamically.\n    #\n    # For now, we're using it to install the lm75 and pmbus module so that it\n    # can detect the fourth temperature sensor, which is located\n    # on the uServer, which doesn't get power until power-on executes.\n    #\n    # Similarly, the pmbus sensor seems to have an easier time of\n    # detecting the NCP4200 buck converters after poweron.  This has not\n    # been carefully explored.\n\n    modprobe lm75\n    modprobe pmbus\n\n    modprobe ast_adc\n\n    # channel 5: r1:  1.0K; r2:  1.0K; v2: 1000mv\n    # channel 6: r1:  1.0K; r2:  1.0K; v2: 1000mv\n    # channel 7: r1:  1.0K; r2:  1.0K; v2: 0mv\n    # channel 8: r1:  1.0K; r2:  1.0K; v2: 0mv\n    # channel 9: r1:  1.0K; r2:  1.0K; v2: 0mv\n    ast_config_adc 5  1 1 1000\n    ast_config_adc 6  1 1 1000\n    ast_config_adc 7  1 1 0\n    ast_config_adc 8  1 1 0\n    ast_config_adc 9  1 1 0\n\n    # Enable the ADC inputs;  adc5 - adc9 should be connected to\n    # 1V, 1.03V, 5V, 3.3V, and 2.5V.\n    echo 1 > /sys/devices/platform/ast_adc.0/adc5_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc6_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc7_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc8_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc9_en\nelse\n    #\n    # Increase max127 (6-0028) input channel 6 (+5V voltage) max range\n    # from default 5V to 10V (1000 mv).\n    #\n    max127_hwmon_dir=\"${SYSFS_I2C_DEVICES}/6-0028/hwmon\"\n    hwmon_idx=$(ls \"$max127_hwmon_dir\")\n    in6_max_path=\"${max127_hwmon_dir}/${hwmon_idx}/in6_max\"\n    if [ -e \"$in6_max_path\" ]; then\n        echo 10000 > \"$in6_max_path\"\n    fi\nfi\n", "num_lines": 80}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sms-kcs\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set SMS KCS handler\n### END INIT INFO\n\necho -n \"Setup SMS KCS message handler... \"\n/usr/local/bin/sms-kcsd\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..5)]\" >&2\n}\n\nFAN_DIR=$(i2c_device_sysfs_abspath 8-0033)\n\nshow_pwm()\n{\n    pwm=\"${FAN_DIR}/fantray${1}_pwm\"\n    val=$(cat $pwm | head -n 1)\n    echo \"$((val * 100 / 31))%\"\n}\n\nshow_rpm()\n{\n    front_rpm=\"${FAN_DIR}/fan$((($1 * 2 - 1)))_input\"\n    rear_rpm=\"${FAN_DIR}/fan$((($1 * 2)))_input\"\n    echo \"$(cat $front_rpm), $(cat $rear_rpm)\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ $1 -gt 5 ]; then\n        usage\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\nfor fan in $FANS; do\n    echo \"Fan $fan RPMs: $(show_rpm $fan), ($(show_pwm $fan))\"\ndone\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/set_fan_speed.sh 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..5)> \" >&2\n}\n\nFAN_DIR=$(i2c_device_sysfs_abspath 8-0033)\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$#\" -eq 1 ]; then\n    FANS=\"1 2 3 4 5\"\nelse\n    FANS=\"$2\"\nfi\n\n# Convert the percentage to our 1/32th unit (0-31).\nunit=$(( ( $1 * 31 ) / 100 ))\n\nfor fan in $FANS; do\n    pwm=\"${FAN_DIR}/fantray${fan}_pwm\"\n    echo \"$unit\" > $pwm\n    echo \"Successfully set fan ${fan} speed to $1%\"\ndone\n", "num_lines": 50}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright 2015-present Facebook. All Rights Reserved.\n\nSYSCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-0031)\nFANCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 8-0033)\nCOME_SYSFS_DIR=$(i2c_device_sysfs_abspath 4-0033)\n\nPWR_MAIN_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_main_n\"\nPWR_USRV_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_usrv_en\"\nPWR_USRV_BTN_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_usrv_btn_en\"\nSLOTID_SYSFS=\"${SYSCPLD_SYSFS_DIR}/slotid\"\n\nwedge_iso_buf_enable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    # TODO, no isolation buffer\n    return 0\n}\n\nwedge_is_us_on() {\n    local val n retries prog\n    if [ $# -gt 0 ]; then\n        retries=\"$1\"\n    else\n        retries=1\n    fi\n    if [ $# -gt 1 ]; then\n        prog=\"$2\"\n    else\n        prog=\"\"\n    fi\n    if [ $# -gt 2 ]; then\n        default=$3              # value 0 means defaul is 'ON'\n    else\n        default=1\n    fi\n    val=$(cat $PWR_USRV_SYSFS 2> /dev/null | head -n 1)\n    if [ -z \"$val\" ]; then\n        return $default\n    elif [ \"$val\" == \"0x1\" ]; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n}\n\nwedge_board_type() {\n    echo 'WEDGE100'\n}\n\nwedge_slot_id() {\n    printf \"%d\\n\" $(cat $SLOTID_SYSFS)\n}\n\nwedge_board_rev() {\n    local val0 val1 val2\n    val0=$(gpio_get_value BOARD_REV_ID0)\n    val1=$(gpio_get_value BOARD_REV_ID1)\n    val2=$(gpio_get_value BOARD_REV_ID2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    # wedge100 uses BMC MAC since beginning\n    return -1\n}\n\nwedge_power_on_board() {\n    local val\n    # power on main power, uServer power, and enable power button\n    val=$(cat $PWR_MAIN_SYSFS | head -n 1)\n    if [ \"$val\" != \"0x1\" ]; then\n        echo 1 > $PWR_MAIN_SYSFS\n        sleep 2\n    fi\n    val=$(cat $PWR_USRV_BTN_SYSFS | head -n 1)\n    if [ \"$val\" != \"0x1\" ]; then\n        echo 1 > $PWR_USRV_BTN_SYSFS\n        sleep 1\n    fi\n}\n\n#\n# Helper function to check if AC PSU (#1 or #2) is present/plugged by\n# reading syscpld \"psu1|2_present\" sysfs node.\n#\n# $1 - PSU ID/Index (1 or 2)\n#\nwedge_psu_is_present() {\n    psu_id=\"$1\"\n    pathname=\"${SYSCPLD_SYSFS_DIR}/psu${psu_id}_present\"\n\n    # Return false if the according syscpld register is not accessible\n    if ! val=$(head -n 1 \"$pathname\"); then\n        return 1\n    fi\n\n    # Note: 0 means the PSU is present.\n    if [ \"$val\" = \"0x0\" ]; then\n        return 0\n    fi\n\n    return 1\n}\n", "num_lines": 108}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nCMD=\"${SYSCPLD_SYSFS_DIR}/i2c_flush_en\"\n\necho -n \"I2c flush to CP2112...\"\necho 1 > $CMD\nusleep 50000\necho 0 > $CMD\necho \"Done\"\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\nset -o pipefail\n\n. /usr/local/bin/openbmc-utils.sh\n\nBASEDIR=${SYSCPLD_SYSFS_DIR}\nif [[ $# -gt 0 && \"$1\" != \"--fan\" ]]; then\n    echo \"Prints SYS CPLD version information when called with no arguments\" >&2\n    echo \"Prints FAN CPLD version if called with --fan\" >&2\n    echo \"Usage: $0 [--fan]\" >&2\n    exit 2\nfi\n\nif [[ \"$1\" == \"--fan\" ]]; then\n    BASEDIR=${FANCPLD_SYSFS_DIR}\nfi\nrev=$(head -n 1 ${BASEDIR}/cpld_rev)\nsub_rev=$(head -n 1 ${BASEDIR}/cpld_sub_rev)\n\necho $(($rev)).$(($sub_rev))\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nset -x\nset -e\nset -u\nset -o pipefail\n\nupgrade_syscpld() {\n  echo \"Started SYSCPLD upgrade ..\"\n  echo out > /tmp/gpionames/CPLD_JTAG_SEL/direction\n  echo 1 > /tmp/gpionames/CPLD_JTAG_SEL/value\n  sys_usercode=$(jbi -r -aREAD_USERCODE -gc102 -gi101 -go103 -gs100 \"$1\" |\\\n                 grep -i \"USERCODE code is\" | awk '{ print $6 }')\n  new_usercode=$(jbi -i \"$1\" | grep -i \"\\\"USERCODE\"\\\" | awk -F '\"' '{ print $4 }')\n  if [[ $sys_usercode != \"$new_usercode\" ]];\n  then\n      #program syscpld\n      jbi -r -aPROGRAM -dDO_REAL_TIME_ISP=1 -gc102 -gi101 -go103 -gs100 \"$1\"\n      echo \"Finished SYSCPLD upgrade: Pass\"\n  else\n    echo \"Finished SYSCPLD upgrade: No Action (Same usercode)\"\n  fi\n}\n\nupgrade_fancpld() {\n  echo \"Started FANCPLD upgrade ..\"\n  echo out > /tmp/gpionames/CPLD_UPD_EN/direction\n  echo 0 > /tmp/gpionames/CPLD_UPD_EN/value\n  #get usercode from system\n  sys_usercode=$(jbi -r -aREAD_USERCODE -gc77 -gi78 -go79 -gs76 \"$1\" |\\\n                 grep -i \"USERCODE code is\" | awk '{ print $6 }')\n  #get usercode from file\n  new_usercode=$(jbi -i \"$1\" | grep -i \"\\\"USERCODE\"\\\" | awk -F '\"' '{ print $4 }')\n  if [[ $sys_usercode != \"$new_usercode\" ]];\n  then\n      #program fancpld\n      jbi -aPROGRAM -dDO_REAL_TIME_ISP=1 -gc77 -gi78 -go79 -gs76 \"$1\"\n      echo \"Finished FANCPLD upgrade: Pass\"\n  else\n    echo \"Finished FANCPLD upgrade: No Action (Same usercode)\"\n  fi\n}\n\n# Check the number of arguments provided, should get atleast 1 for file path\nif [ $# -lt 1 ]; then\n  echo \"Provide FAN or SYSCPLD path\"\n  exit 1\nfi\n\n# Check the file path provided is a valid one.\njbcfile=\"$1\"\nif [[ ! -f $jbcfile ]]; then\n    echo \"$jbcfile does not exist\"\n    exit 1\nfi\n\n# Check the file path extension is .jbc\nfilename=\"$(basename \"$jbcfile\")\"\nif [[ ${filename: -4} != \".jbc\" ]]; then\n    echo \"Must pass in a .jbc file\"\n    exit 1\nfi\n\n# Check the file name and upgrade accordingly\ncase $filename in\n  *FAN*)\n    upgrade_fancpld \"$jbcfile\"\n    ;;\n  *SYSCPLD*)\n    upgrade_syscpld \"$jbcfile\"\n    ;;\n  *)\n    echo \"Provide FAN or SYSCPLD path\"\n    exit 1\n    ;;\nesac\n", "num_lines": 94}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.\u00c2\u00a0 See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nversion=$(cat \"${COME_SYSFS_DIR}/version\")\nreleased_date=$(cat \"${COME_SYSFS_DIR}/date\")\n\nif [ \"${version:(-4)}\" == \"0x80\" ]; then\n  echo \"EC Test Version\"\n  echo \"EC Released Date: $released_date\"\nelse\n  r=$((16#${version:15:2}))\n  e=$((16#${version:22:2}))\n  echo \"EC Released Version: R$(printf '%02d' $r).E$(printf '%02d' $e)\"\n  echo \"EC Released Date: $released_date\"\nfi\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. /usr/local/bin/openbmc-utils.sh\n\n# select WDTRST\ndevmem_clear_bit $(scu_addr 2C) 1\ndevmem_set_bit $(scu_addr 84) 4\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\nset -o pipefail\nexit_code=2  \n\n. /usr/local/bin/openbmc-utils.sh\n\nEEPROM_FILE=\"/tmp/.tmp_oob_eeprom.bin\"\n\ncleanup () {\n  rm -f \"$EEPROM_FILE\"\n  exit $exit_code\n}\ntrap cleanup EXIT ERR INT TERM\n\nif ! out=$(/usr/local/bin/spi_util.sh read spi2 OOB_SWITCH_EEPROM \"$EEPROM_FILE\" > /dev/null 2>&1); then\n    echo \"Error: failed to read the switch eeprom!\"\n    echo \"$out\"\n    exit 1\nfi\n\nsha256sum < \"$EEPROM_FILE\" | head -c 64\nexit_code=$?\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2004-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Displays values onto the debug header LEDs.\"\n    echo \"Hex and decimal accepted.\"\n    echo \"Usage: $0 <value>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\ndisplay_value() {\n    num=0\n    input=$1\n    while [ $num -lt 8 ]; do  {\n        gpio_set_value \"LED_POSTCODE_$num\" $((input & 1))\n        input=$((input >> 1))\n        num=$((num + 1))\n    }\n    done\n}\n\n# Check number of parameters\nif [ $# -ne 1 ]\nthen\n    usage\n    exit 1\nfi\n\n# Make sure input is actually numeric\nDEC_VALUE=$(printf \"%d\" $1 2>/dev/null)\nif [ $? -eq 1 ]\nthen\n    echo \"Unable to parse input as numeric value.\"\n    exit 1\nfi\n\n# Make sure input is within proper range\nif [ $DEC_VALUE -lt 0 ] || [ $DEC_VALUE -gt 255 ]\nthen\n    echo \"Value $DEC_VALUE is outside of displayable range 0 - 0xff (255).\"\n    exit 1\nfi\n\ndisplay_value $DEC_VALUE\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# make power button high to prepare for power on sequence\ngpio_set_value BMC_PWR_BTN_OUT_N 1\n\n# First power on TH, and if Panther+ is used,\n# provide standby power to Panther+.\nwedge_power_on_board\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPWR_TH_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/th_sys_rst_n\"\n\necho 0 > $PWR_TH_RST_SYSFS\nsleep 1\necho 1 > $PWR_TH_RST_SYSFS\n\nlogger -p user.crit \"Reset Tomahawk\"\n", "num_lines": 30}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nCMD=\"${SYSCPLD_SYSFS_DIR}/usb2cp2112_rst_n\"\n\necho -n \"Reset CP2112 Switch ... \"\necho 0 > $CMD\nusleep 50000\necho 1 > $CMD\n\necho \"Done\"\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nset -e\n\n. /usr/local/bin/openbmc-utils.sh\n\n#\n# We prefer writing to sysfs nodes (generated by syscpld driver) rather\n# than \"i2cset\", because i2cset could potentially conflict with syscpld\n# driver (who may be talking to 12-0031 at the same time).\n#\nFANCPLD_RST_N=\"${SYSCPLD_SYSFS_DIR}/fan_rackmon_rst_n\"\n\necho \"Reseting fancpld..\"\nif [ -f \"$FANCPLD_RST_N\" ]; then\n    echo 0 > \"$FANCPLD_RST_N\"  # write 0 to trigger FAN_RACKMON card reset\n    echo 1 > \"$FANCPLD_RST_N\"  # write 1 for normal operation\nelse\n    echo \"Warning: unable to locate $FANCPLD_RST_N: use i2cset instead..\"\n    i2cset -f -y 12 0x31 0x39 0xfe\n    i2cset -f -y 12 0x31 0x39 0xff\nfi\n\nexit 0\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#\n# This script resets the OOB switch BCM5387, and it's designed to reload\n# the new settings from OOB switch EEPROM without power cycling the whole\n# chassis.\n#\n# WARNING:\n#   1. Both uServer and OpenBMC OOB connection would be down for a few\n#      seconds when the command is executed.\n#   2. DO NOT run the script from ssh terminal because of #1: run the\n#      command from OpenBMC console instead.\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nSYSCPLD_OOB_RST=\"${SYSCPLD_SYSFS_DIR}/oob_bcm5387_rst_n\"\n\necho \"This command disrupts uServer and OpenBMC OOB connection!\"\nread -r -t 8 -p \"Do you want to continue? [y/n] \" user_input\nif [ \"$user_input\" != \"y\" ] && [ \"$user_input\" != \"Y\" ] ; then\n    exit 0\nfi\n\nif [ ! -L \"${SHADOW_GPIO}/SWITCH_EEPROM1_WRT\" ]; then\n    gpio_export_by_name \"$ASPEED_GPIO\" GPIOE2 SWITCH_EEPROM1_WRT\nfi\ngpio_set_direction SWITCH_EEPROM1_WRT \"in\"\n\n# The OOB switch enters reset state after below command!!!\nlogger -p user.crit \"Reset OOB switch BCM5387..\"\necho \"Reset OOB switch BCM5387..\"\necho 0 > \"$SYSCPLD_OOB_RST\"\n\n# Now let's bring the OOB switch out of reset after small delay.\nsleep 2\necho \"Bring BCM5387 out of reset..\"\necho 1 > \"$SYSCPLD_OOB_RST\"\n\ngpio_unexport SWITCH_EEPROM1_WRT\nexit 0\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nfunction reset_to_mux\n{\n  local num=0 val=$1\n  while [ $num -lt 4 ]; do\n    CMD=\"${SYSCPLD_SYSFS_DIR}/i2c_mux${num}_rst_n\"\n    echo $val > $CMD\n    (( num++ ))\n  done\n}\n\necho -n \"Reset QSFP i2c-mux ... \"\nreset_to_mux 0                  # write 0 to put mux into reset\nusleep 50000\nreset_to_mux 1                  # write 1 to bring mux out of reset\necho \"Done\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\necho -n \"Reset USB Switch ... \"\n\nfile=\"${SYSCPLD_SYSFS_DIR}/usb_hub_rst_n\"\n\necho 0 > $file                  # write 0 to put hub into reset\nsleep 1\necho 1 > $file                  # write 1 to bring hub out of reset\n\necho \"Done\"\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nboard_rev=$(wedge_board_rev)\n\nif [ $board_rev -ge 2 ]; then\n    # DVT or later\n    # Enable the isolation buffer between BMC and COMe i2c bus\n    echo 1 > ${SYSCPLD_SYSFS_DIR}/com-e_i2c_isobuf_en\n    # Enable the COM6_BUF_EN to open the isolation buffer between COMe BIOS\n    # EEPROM with COMe\n    gpio_set_value COM6_BUF_EN 0\n    # Make the BIOS EEPROM connect to COMe instead of BMC\n    gpio_set_value COM_SPI_SEL 0\nfi\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n#\n# Create i2c switches at the beginning so all the channels are properly\n# initialized when the child devices are created: the step is only needed\n# for kernel 4.1 as i2c switches are handled in device tree for newer\n# kernel versions.\n#\n# 7-0070 is the i2c-switch for ltc power supply in DC deployment. It has\n# 8 child channels which are assigned i2c bus 14-21. 2 PFE1100 power\n# supplies are connected to channel #0 (14-005a) and #1 (15-0059).\n#\nPSU_MUX_DEV=\"7-0070\"\nPSU_MUX_PATH=$(i2c_device_sysfs_abspath \"$PSU_MUX_DEV\")\nif [ ! -d \"$PSU_MUX_PATH\" ]; then\n    i2c_mux_add_sync 7 0x70 pca9548 8\nfi\n\n# Bus 2\ni2c_device_add 2 0x3a pwr1014a\n\n# Bus 3\ni2c_device_add 3 0x48 tmp75\ni2c_device_add 3 0x49 tmp75\ni2c_device_add 3 0x4a tmp75\ni2c_device_add 3 0x4b tmp75\ni2c_device_add 3 0x4c tmp75\n\n# Bus 4\ni2c_device_add 4 0x33 com_e_driver\n\n# Bus 6\ni2c_device_add 6 0x2f pcf8574\ni2c_device_add 6 0x51 24c64\n\n# Bus 7\ni2c_device_add 7 0x50 24c02         # BMC PHY EEPROM\n\n# Bus 8\ni2c_device_add 8 0x33 fancpld\ni2c_device_add 8 0x48 tmp75\ni2c_device_add 8 0x49 tmp75\n\n# Bus 9   TPM driver for TCSD service\ni2c_device_add 9 0x20 tpm_i2c_infineon\n\n# Bus 12\ni2c_device_add 12 0x31 syscpld\n\ni2c_check_driver_binding\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All rights reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#\n# The script is designed to access BACKUP_BIOS and OOB_SWITCH_EEPROM. The\n# 2 devices should never be accessed simultaneously because they share\n# exactly the same SPI pins/lines. Chip select is done by external bus\n# switch (controlled by GPIO), and details as below:\n#\n# - BACKUP_BIOS:\n#   The flash is registered under spi1 and paired with aspeed-spi master\n#   for better performance.\n#   The chip is selected by setting COM_SPI_SEL (aspeed GPIOO0) to 1.\n#\n# - OOB_SWITCH_EEPROM:\n#   The eeprom is registered under spi2 and controlled by spi-gpio. It's\n#   not compatible with aspeed-spi controller due to clock/speed mismatch:\n#   aspeed-spi controller's mimimum frequency is greater than the eeprom's\n#   max frequency.\n#   The chip is selected by setting SWITCH_EEPROM1_WRT (aspeed GPIOE2)\n#   to 1.\n#\n# WARNING:\n#   Please DO NOT invent new scripts to operate above 2 devices, because\n#   concurrent access could potentially corrupt the devices. Check S221767\n#   for details.\n#\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n. /usr/local/bin/flashrom-utils.sh\n\nPID_FILE='/var/run/spi_util.pid'\n\n#\n# Kernel modules used to talk to backup BIOS.\n# The module name is changed to spi_aspeed_user since linux-aspeed-5.15.\n#\nif modinfo spi_aspeed_user > /dev/null 2>&1; then\n    SPI_ASPEED_MODULE=spi_aspeed_user\nelse\n    SPI_ASPEED_MODULE=spi_aspeed\nfi\n\n#\n# Kernel modules for eeprom access. We decided to use the legacy script\n# to read/write eeprom, so these modules will be unloaded. For details,\n# please check S235340.\n#\nSPI_GPIO_MODULE=spi_gpio\nSPI_EEPROM_MODULE=eeprom_93xx46\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    LEGACY_KERNEL=\"true\"\nfi\n\ncheck_duplicate_process() {\n    exec 99>\"$PID_FILE\"\n    if ! flock -n 99; then\n        echo \"Another instance is running. Exiting!!\"\n        exit 1\n    fi\n}\n\n#\n# Helper function to generate pathname of a temporary file.\n# Please always use this function to generate temp files so they can be\n# removed at cleanup.\n#\n# $1 - reference file name.\n#\nspi_tmp_file() {\n    name=$(basename \"$1\")\n    echo \"/tmp/.spitmp_$name\"\n}\n\n#\n# Helper function to append more bytes to the given file.\n#\n# $1 - file to be updated.\n# $2 - pad size\n#\npad_file() {\n    out_file=\"$1\"\n    pad_size=\"$2\"\n    if ! dd if=/dev/zero bs=\"$pad_size\" count=1 | tr \"\\000\" \"\\377\" >> \"$out_file\"; then\n        echo \"Error: failed to pad $out_file (pad_size=$pad_size)!\"\n        exit 1\n    fi\n}\n\n#\n# Helper function to resize a file ($1) to target size ($3).\n#\n# $1 - input/reference file\n# $2 - output file\n# $3 - expected size of the output file.\n#\nresize_file() {\n    in_file=\"$1\"\n    out_file=\"$2\"\n    target_size=\"$3\"\n\n    in_file_sz=$(stat -c%s \"$in_file\")\n    if [ \"$in_file_sz\" -lt \"$target_size\" ]; then\n        cp \"$in_file\" \"$out_file\"\n        pad_size=$((target_size - in_file_sz))\n        pad_file \"$out_file\" \"$pad_size\"\n    elif [ \"$in_file_sz\" -eq \"$target_size\" ]; then\n        ln -s \"$(realpath \"$in_file\")\" \"$out_file\"\n    else\n        echo \"Input file too big: $in_file_sz > $target_size\"\n        exit 1\n    fi\n}\n\nkmod_unload() {\n    if lsmod | grep \"$1\" > /dev/null 2>&1; then\n        modprobe -r \"$1\"\n    fi\n}\n\nkmod_reload() {\n    kmod_unload \"$1\"\n    modprobe \"$1\"\n}\n\n#\n############################################################\n# Functions to deal with spi1.0: the backup BIOS flash.\n############################################################\n#\n\nspi1_connect() {\n    echo \"enable spi1 (bios) connection..\"\n\n    # Enable SPI master in SCU register\n    devmem_set_bit \"$(scu_addr 70)\" 12\n\n    gpio_set_value COM6_BUF_EN 0\n\n    if [ ! -L \"${SHADOW_GPIO}/COM_SPI_SEL\" ]; then\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOO0 COM_SPI_SEL\n    fi\n    gpio_set_value COM_SPI_SEL 1\n\n    if [ -z \"$LEGACY_KERNEL\" ]; then\n        kmod_reload \"$SPI_ASPEED_MODULE\"\n    fi\n}\n\nspi1_disconnect() {\n    echo \"disable spi1 (bios) connection..\"\n    if [ -L \"${SHADOW_GPIO}/COM_SPI_SEL\" ]; then\n        gpio_set_value COM_SPI_SEL 0\n        gpio_unexport COM_SPI_SEL\n    fi\n\n    kmod_unload \"$SPI_ASPEED_MODULE\"\n\n    # Disable SPI interface\n    devmem_clear_bit \"$(scu_addr 70)\" 12\n}\n\nspi1_flash_write() {\n    flash_dev=\"$1\"\n    in_file=\"$2\"\n    flash_model=\"$3\"\n\n    out_file=$(spi_tmp_file \"$in_file\")\n    rm -rf \"$out_file\"\n\n    if ! flash_size=$(flash_get_size \"$flash_dev\"); then\n        exit 1\n    fi\n\n    target_size=$((flash_size * 1024))\n    resize_file \"$in_file\" \"$out_file\" \"$target_size\"\n\n    flash_write \"$flash_dev\" \"$out_file\" \"$flash_model\"\n}\n\nspi1_flash_detect() {\n    if ! flash_dump_summary \"$1\"; then\n        exit 1\n    fi\n}\n\nspi1_launch_io() {\n    op=\"$1\"\n    flash_dev=\"$2\"\n    image_file=\"$3\"\n\n    if ! flash_model=$(flash_get_model \"$flash_dev\"); then\n        exit 1\n    fi\n\n    case \"$op\" in\n        \"read\")\n            flash_read \"$flash_dev\" \"$image_file\" \"$flash_model\"\n        ;;\n        \"write\")\n            spi1_flash_write \"$flash_dev\" \"$image_file\" \"$flash_model\"\n        ;;\n        \"erase\")\n            flash_erase \"$flash_dev\" \"$flash_model\"\n        ;;\n        \"detect\")\n            spi1_flash_detect \"$flash_dev\"\n        ;;\n        *)\n            echo \"Operation $op is not supported!\"\n            exit 1\n        ;;\n    esac\n}\n\n#\n############################################################\n# Functions to deal with spi2.0: the internal switch eeprom.\n############################################################\n#\n\nspi2_setup_bitbang() {\n    if [ ! -L \"${SHADOW_GPIO}/BMC_EEPROM1_SPI_SS\" ]; then\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOI4 BMC_EEPROM1_SPI_SS\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOI5 BMC_EEPROM1_SPI_SCK\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOI6 BMC_EEPROM1_SPI_MOSI\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOI7 BMC_EEPROM1_SPI_MISO\n    fi\n}\n\nspi2_connect() {\n    echo \"enable spi2 (eeprom) connection..\"\n\n    kmod_unload \"$SPI_EEPROM_MODULE\"\n    kmod_unload \"$SPI_GPIO_MODULE\"\n\n    if [ ! -L \"${SHADOW_GPIO}/SWITCH_EEPROM1_WRT\" ]; then\n        gpio_export_by_name \"$ASPEED_GPIO\" GPIOE2 SWITCH_EEPROM1_WRT\n    fi\n\n    gpio_set_value SWITCH_EEPROM1_WRT 1\n    if [ \"$(gpio_get_value SWITCH_EEPROM1_WRT)\" -ne \"1\" ]; then\n        echo \"Error: unable to set SWITCH_EEPROM1_WRT pin\"\n        exit 1\n    fi\n\n    spi2_setup_bitbang\n}\n\nspi2_disconnect() {\n    echo \"disable spi2 (eeprom) connection..\"\n\n    if [ -L \"${SHADOW_GPIO}/BMC_EEPROM1_SPI_SS\" ]; then\n        gpio_unexport BMC_EEPROM1_SPI_SS\n        gpio_unexport BMC_EEPROM1_SPI_SCK\n        gpio_unexport BMC_EEPROM1_SPI_MOSI\n        gpio_unexport BMC_EEPROM1_SPI_MISO\n    fi\n\n    kmod_unload \"$SPI_EEPROM_MODULE\"\n    kmod_unload \"$SPI_GPIO_MODULE\"\n\n    if [ -L \"${SHADOW_GPIO}/SWITCH_EEPROM1_WRT\" ]; then\n        gpio_set_value SWITCH_EEPROM1_WRT 0\n        gpio_set_direction SWITCH_EEPROM1_WRT \"in\"\n        gpio_unexport SWITCH_EEPROM1_WRT\n    fi\n}\n\nspi2_legacy_io() {\n    echo \"running at93cx6_util_py3.py..\"\n    /usr/local/bin/at93cx6_util_py3.py --cs BMC_EEPROM1_SPI_SS \\\n                                       --clk BMC_EEPROM1_SPI_SCK \\\n                                       --mosi BMC_EEPROM1_SPI_MOSI \\\n                                       --miso BMC_EEPROM1_SPI_MISO $@\n}\n\ncleanup_spi() {\n    spi1_disconnect\n    spi2_disconnect\n\n    rm -rf /tmp/.spitmp_*\n}\n\nui() {\n    op=\"$1\"\n    spi_bus=\"$2\"\n    file=\"$4\"\n\n    case \"$spi_bus\" in\n        \"spi1\")\n            spi2_disconnect\n            spi1_connect\n\n            flash_dev=$(flash_device_name 1 0)\n            flash_path=\"/dev/$flash_dev\"\n            if [ ! -e \"$flash_path\" ]; then\n                echo \"Error: unable to find $flash_path!\"\n                exit 1\n            fi\n\n            spi1_launch_io \"$op\" \"$flash_dev\" \"$file\"\n        ;;\n        \"spi2\")\n            spi1_disconnect\n            spi2_connect\n\n            spi2_legacy_io chip \"$op\" --file \"$file\"\n        ;;\n        *)\n            echo \"Error: no such SPI bus ($spi_bus)!\"\n            exit 1\n        ;;\n    esac\n}\n\nusage() {\n    local prog\n    prog=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$prog <op> spi1/spi2 <spi device> <file>\"\n    echo \"  <op>          : read, write, erase, detect\"\n    echo \"  <spi1 device> : BACKUP_BIOS\"\n    echo \"  <spi2 device> : OOB_SWITCH_EEPROM\"\n    echo \"Examples:\"\n    echo \"  $prog write spi1 BACKUP_BIOS bios.bin\"\n    echo \"  $prog read spi2 OOB_SWITCH_EEPROM eeprom.bin\"\n    echo \"\"\n}\n\ncheck_parameter() {\n    op=\"$1\"\n    spi=\"$2\"\n    dev=\"$3\"\n    file=\"$4\"\n\n    case \"$op\" in\n        \"read\")\n            if [ $# -ne 4 ]; then\n                echo \"Error: <image-file> argument is required!\"\n                return 1\n            fi\n            ;;\n        \"write\")\n            if [ $# -ne 4 ] || [ ! -f \"$file\" ]; then\n                echo \"Error: unable to find image file ${file}!\"\n                return 1\n            fi\n            ;;\n        \"erase\" | \"detect\")\n            if [ $# -ne 3 ]; then\n                echo \"Error: please specific spi device!\"\n                return 1\n            fi\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n\n    case \"$spi\" in\n        \"spi1\")\n            if [ \"$dev\" != \"BACKUP_BIOS\" ]; then\n                echo \"Error: supported spi1 devices: BACKUP_BIOS!\"\n                return 1\n            fi\n            ;;\n        \"spi2\")\n            if [ \"$dev\" != \"OOB_SWITCH_EEPROM\" ]; then\n                echo \"Error: supported spi2 devices: OOB_SWITCH_EEPROM!\"\n                return 1\n            fi\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n\n    return 0\n}\n\ncheck_duplicate_process\n\nif ! check_parameter \"$@\"; then\n    usage\n    exit 1\nfi\n\ntrap cleanup_spi INT TERM QUIT EXIT\n\nui \"$@\"\n", "num_lines": 411}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nPWD1014A_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-003a)\nPWR_SYSTEM_SYSFS=\"${SYSCPLD_SYSFS_DIR}/pwr_cyc_all_n\"\nPWR_USRV_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/usrv_rst_n\"\nPWR_TH_RST_SYSFS=\"${SYSCPLD_SYSFS_DIR}/th_sys_rst_n\"\nALT_SYSRESET_SYSFS=\"${PWD1014A_SYSFS_DIR}/mod_hard_powercycle\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current power status\"\n    echo\n    echo \"  on: Power on microserver and main power if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver and main power ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge system ungracefully\"\n    echo\n}\n\nis_main_power_on() {\n  status=$(cat $PWR_MAIN_SYSFS | head -1 )\n  if [ \"$status\" == \"0x1\" ]; then\n      return 0            # powered on\n  else\n      return 1\n  fi\n}\n\ndo_status() {\n    return_code=0\n\n    echo -n \"Microserver power is \"\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    echo -n \"System main power is \"\n    if is_main_power_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on_com_e() {\n    logger -p user.crit \"Powering on microserver...\"\n    echo 1 > $PWR_USRV_SYSFS\n}\n\ndo_on_main_pwr() {\n    logger -p user.crit \"Turning on main power...\"\n    echo 1 > $PWR_MAIN_SYSFS\n}\n\ndo_on() {\n    local force opt ret\n    ret=0\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n\n        esac\n    done\n\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on 10 \".\"; then\n            echo \"Skipping because microserver is already on. Use -f to force.\"\n            return 1\n        fi\n    fi\n\n    # reset TH\n    reset_brcm.sh\n\n    # power on sequence\n    if ! is_main_power_on; then\n      do_on_main_pwr || ret=1\n    fi\n\n    do_on_com_e || ret=1\n\n    return $ret\n}\n\ndo_off_com_e() {\n    logger -p user.crit \"Powering off microserver...\"\n    echo 0 > $PWR_USRV_SYSFS\n}\n\ndo_off_main_pwr() {\n    logger -p user.crit \"Turning off main power...\"\n    echo 0 > $PWR_MAIN_SYSFS\n}\n\ndo_off() {\n    local ret\n    ret=0\n\n    do_off_com_e || ret=1\n    do_off_main_pwr || ret=1\n\n    return $ret\n}\n\ndo_reset() {\n    local system opt pulse_us\n    system=0\n    while getopts \"s\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        pulse_us=100000             # 100ms\n        logger -p user.crit \"Power reset the whole system...\"\n        echo -n \"Power reset the whole system ...\"\n        sleep 1\n        echo 0 > $PWR_SYSTEM_SYSFS\n        # Echo 0 above should work already. However, after CPLD upgrade,\n        # We need to re-generate the pulse to make this work\n        usleep $pulse_us\n        echo 1 > $PWR_SYSTEM_SYSFS\n        usleep $pulse_us\n        echo 0 > $PWR_SYSTEM_SYSFS\n        usleep $pulse_us\n        echo 1 > $PWR_SYSTEM_SYSFS\n        logger -p user.crit \"Chassis power failed through CPLD. Will try pwr1014a in 5 sec...\"\n        sleep 5\n        echo 0 > $ALT_SYSRESET_SYSFS\n        sleep 1\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return -1\n        fi\n        # reset TH first\n        reset_brcm.sh\n\n        logger -p user.crit \"Power reset microserver...\"\n        echo -n \"Power reset microserver ...\"\n        echo 0 > $PWR_USRV_RST_SYSFS\n        sleep 1\n        echo 1 > $PWR_USRV_RST_SYSFS\n        logger \"Successfully power reset micro-server\"\n    fi\n    echo \" Done\"\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit -1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n", "num_lines": 229}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# SAMPLE_SIZE reached by testing in several wedge100 with noisy mac address results\nSAMPLE_SIZE=18\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\nif ! wedge_is_us_on; then\n    echo \"Cannot retrive microserver MAC when microserver is powered off.\" 1>&2\n    exit -2\nfi\n\n# Workaround wedge100 noisy mac address hw bug (in which some mac octets sometimes\n# are 'ff') by querying for the mac address several times and getting the min()\n# of each octet\nsample=\"$(for i in $(seq 1 ${SAMPLE_SIZE}); do\n  cat \"${COME_SYSFS_DIR}/mac\"\ndone)\"\n\nmac=\"\"\nfor i in {1..6}; do\n  min_octet=$(echo \"$sample\" | cut -f$i -d':' | sort | head -n1)\n  mac+=\":$min_octet\"\ndone\nmac=\"${mac:1}\" # strip leading ':'\n\nif [ -n \"$mac\" -a \"${mac/X/}\" = \"${mac}\" ]; then\n    echo $mac\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit -1\nfi\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nSENSORS_CONF_PATH=\"/etc/sensors.d\"\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    LEGACY_KERNEL=\"true\"\nfi\n\n#\n# Configure ADC channels: the step is only needed in kernel 4.1 because\n# ADC channels have been configured in device tree in kernel 5.x.\n#\nconfig_adc_channels() {\n    echo \"Configure ADC Channels..\"\n\n    modprobe ast_adc\n\n    # channel 5: r1:  1.0K; r2:  1.0K; v2: 1000mv\n    # channel 6: r1:  1.0K; r2:  1.0K; v2: 1000mv\n    # channel 7: r1:  1.0K; r2:  1.0K; v2: 0mv\n    # channel 8: r1:  1.0K; r2:  1.0K; v2: 0mv\n    # channel 9: r1:  1.0K; r2:  1.0K; v2: 0mv\n    ast_config_adc 5  1 1 1000\n    ast_config_adc 6  1 1 1000\n    ast_config_adc 7  1 1 0\n    ast_config_adc 8  1 1 0\n    ast_config_adc 9  1 1 0\n\n    # Enable the ADC inputs;  adc5 - adc9 should be connected to\n    # 1V, 1.03V, 5V, 3.3V, and 2.5V.\n    echo 1 > /sys/devices/platform/ast_adc.0/adc5_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc6_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc7_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc8_en\n    echo 1 > /sys/devices/platform/ast_adc.0/adc9_en\n}\n\n#\n# Some I2C devices may not get power until after power-on.sh, and it\n# usually happens when the chassis is power cycled. Let's probe such devices\n# again in this case.\n#\nfixup_i2c_devices() {\n    mux_driver=\"pca954x\"\n    mux_device=\"7-0070\"\n\n    if [ ! -e \"${SYSFS_I2C_DRIVERS}/${mux_driver}/${mux_device}\" ]; then\n        echo \"Re-probe i2c switch $mux_device..\"\n        i2c_bind_driver \"$mux_driver\" \"$mux_device\"\n    fi\n}\n\nget_ltc4151_version() {\n    bus=\"$1\"\n    addr=\"$2\"\n\n    i2cset -f -y \"$bus\" \"$addr\" 0x00 2> /dev/null\n    usleep 50000\n    i2cset -f -y \"$bus\" \"$addr\" 0x4D 2> /dev/null\n    usleep 50000\n    if output=$(i2cget -f -y \"$bus\" \"$addr\" 2> /dev/null); then\n        echo \"$output\"\n    else\n        echo \"-1\"\n    fi\n}\n\n#\n# Adjust LTC4151 Rsense value depending on hardware version.\n# Kernel driver use Rsense equal to 1 milliohm. We need to correct Rsense\n# value, and all the value are from hardware team.\n#\npem_sensor_calibration() {\n    echo \"Calibrate PEM sensors...\"\n\n    # mux-channel-1 (14-0056) and mux-channel-2 (15-0055)\n    fru1_version=\"$(get_ltc4151_version 14 0x56)\"\n    fru2_version=\"$(get_ltc4151_version 15 0x55)\"\n\n    if [ \"$((fru1_version))\" -ge \"$((0x02))\" ] || \\\n       [ \"$((fru2_version))\" -ge \"$((0x02))\" ]; then\n        rsense_val=1.55\n        rsense_val2=1.55\n    else\n        rsense_val=1.465\n        rsense_val2=1.35\n    fi\n\n    sed \"s/rsense/$rsense_val/1\" \"${SENSORS_CONF_PATH}/custom/ltc4151.conf\" \\\n        > \"/tmp/ltc4151.conf\"\n\n    sed \"s/rsense/$rsense_val2/1\" \"/tmp/ltc4151.conf\" \\\n         > \"${SENSORS_CONF_PATH}/ltc4151.conf\"\n\n    # remove temporary file\n    rm -rf /tmp/ltc4151.conf\n    \n}\n\n#\n# Main entry starts here\n#\nif [ -n \"$LEGACY_KERNEL\" ]; then\n    config_adc_channels\nfi\n\nfixup_i2c_devices\n\npem_sensor_calibration\n", "num_lines": 139}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nfcb_ver=$(head -n1 \"$FCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\n\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..4)]\" >&2\n}\n\n# FCB    PWM 1 ~ 4 control Fantray 1 2 3 4\nshow_pwm()\n{\n    pwm=\"$FCMCPLD_SYSFS_DIR/fan$1_pwm\"\n    val=$(head -n 1 \"$pwm\")\n\n    if [ \"$fcb_ver\" = \"0x0\" ]; then\n        echo \"$((val * 100 / 31))%\"\n    else\n        # Convert the percentage to our 1/64th level (0-63) and round.\n        echo \"$(( (val * 1000 / 63 + 5) /10 ))%\"\n    fi\n}\n\nshow_rpm()\n{\n    front_rpm=\"$FCMCPLD_SYSFS_DIR/fan$((($1 * 2 - 1)))_input\"\n    rear_rpm=\"$FCMCPLD_SYSFS_DIR/fan$((($1 * 2)))_input\"\n    echo \"$(cat \"$front_rpm\"), $(cat \"$rear_rpm\")\"\n}\n\nset -e\n\n# refer to the comments in init_pwn.sh regarding\n# the fan unit and tacho mapping\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 9 ]; then\n        echo \"Fan $1: not a valid Fan Unit\"\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    FAN=\"${fan}\"\n    UNIT=${FAN}\n\n    echo \"Fan $fan RPMs: $(show_rpm \"$UNIT\"), ($(show_pwm \"$UNIT\"))\"\ndone\n", "num_lines": 75}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# if fcm version or higher, enable fscd\nFSCD_ENABLE_FCM_MAJ=3\nFSCD_ENABLE_FCM_MIN=5\n\ndefault_fsc_config=\"/etc/fsc-config.json\"\nfcm_maj=$((FCM_CPLD_VER))\nfcm_min=$((FCM_CPLD_SUB_VER))\n\necho -n \"Setup fan speed... \"\n\nif [ $(wedge_board_type) -eq 0 ]; then\n    echo \"Run FSC Wedge400 Config\"\n    cp /etc/FSC-W400-config.json ${default_fsc_config}\nelif [ $(wedge_board_type) -eq 1 ]; then\n    echo \"Run FSC Wedge400C Config\"\n    cp /etc/FSC-W400C-config.json ${default_fsc_config}\nfi\necho \"Setting fan speed to 50%...\"\n/usr/local/bin/set_fan_speed.sh 50\necho \"Done setting fan speed\"\n\nif fw_printenv | grep \"disable_fscd=yes\" > /dev/null 2>&1; then\n    echo \"fscd is disabled in uboot_env: fans are running at fixed speed.\"\n    exit 0\nfi\n\n# Currently, fcmcpld version 0.xx will cause BMC to \n# run into crash loop, due to fscd's own logic and \n# its failure to disarm bootup watchdog.\n# (this problem is only for fcmcpld 0.xx. Fcmcpld 3.5 and\n# above works well without any problem.)\n# Until we have fix, we will run fscd only if fcmcpld is 3.5 or higher.\nfcm_compatible=0\nif [ $((fcm_maj)) -eq $FSCD_ENABLE_FCM_MAJ ] &&\n   [ $((fcm_min)) -ge $FSCD_ENABLE_FCM_MIN ] ||\n   [ $((fcm_maj)) -ge $((FSCD_ENABLE_FCM_MAJ + 1)) ]; then\n   fcm_compatible=1\nfi\n\n#WEDGE400 EVT   wedge_board_rev = 0  smb_board_rev = 00 disable\n#WEDGE400 EVT3  wedge_board_rev = 0  smb_board_rev = 01 enable\nif [ \"$(wedge_board_type)\" = \"0\" ] &&\n   [ \"$(wedge_board_rev)\" = \"0\" ] &&\n   [ \"$SMB_CPLD_BOARD_REV\" = \"0x0\" ]; then #WEDGE400 EVT\n    fcm_compatible=0\n#WEDGE400-C EVT wedge_board_rev = 0  disable\nelif [ \"$(wedge_board_type)\" = \"1\" ] &&\n     [ \"$(wedge_board_rev)\" = \"0\" ]; then #WEDGE400C EVT\n    fcm_compatible=0 #fcm_compatible = 0 means fscd not ready.\nfi\n\nif [ $fcm_compatible -eq 0 ]; then\n    echo \"Running fan at the fixed speed.\"\n    /usr/local/bin/wdtcli stop\nelse\n    echo \"Starting fscd...\"\n    runsv /etc/sv/fscd > /dev/null 2>&1 &\nfi\necho \"done.\"\n", "num_lines": 94}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nfcb_ver=$(head -n1 \"$FCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\n\nusage() {\n    echo \"Usage: $0 <PERCENT (0..100)> <Fan Unit (1..4)> \" >&2\n}\n\nset -e\n\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# check percent argument be number\ncheck_number=$(echo \"$1\" | grep -E \"^[0-9]+$\") \nif [ \"$check_number\" = '' ]; then\n    echo \"Percent argument can be only integer number\"\n    usage\n    exit 1\nfi\n# check percent in range 0-100\nif [ \"$1\" -lt 0 ] || [ \"$1\" -gt 100 ]; then\n    echo \"Percent argument out of range\"\n    usage\n    exit 1\nfi\n\n# FCB    PWM 1 ~ 4 control Fantray 1 2 3 4\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -gt 4 ]; then\n        echo \"Fan $2: not a valid Fan Unit\"\n        exit 1\n    fi\n\n    FAN=\"$2\"\n    FAN_UNIT=$((FAN / 1))\nfi\n\nif [ \"$fcb_ver\" = \"0x0\" ]; then\n    # Convert the percentage to our 1/32th level (0-31).\n    step=$((($1 * 31) / 100))\nelse\n    # Convert the percentage to our 1/64th level (0-63) and round.\n    step=$(( ($1 * 630 + 5) / 1000 ))\nfi\ncnt=1\n\nfor unit in ${FAN_UNIT}; do\n    pwm=\"$FCMCPLD_SYSFS_DIR/fan${unit}_pwm\"\n    echo \"$step\" > \"${pwm}\"\n    if [ \"$#\" -eq 1 ]; then\n        echo \"Successfully set fan $cnt speed to $1%\"\n        cnt=$((cnt + 1))\n    else\n        echo \"Successfully set fan $2 speed to $1%\"\n    fi\ndone\n", "num_lines": 83}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091,SC2034\n# Do not change this line to openbmc-utils.sh, or it will generate a source loop.\n. /usr/local/bin/i2c-utils.sh\n\nSCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 2-003e)\nSMBCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-003e)\nif [[ ${KERNEL_VERSION} != 4.1.* ]]; then\n    PWRCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 31-003e)\n    FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 32-003e)\nelse\n    PWRCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 33-003e)\n    FCMCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 34-003e)\nfi\nPWR_USRV_SYSFS=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_enable\"\nPWR_USRV_FORCE_OFF=\"${SCMCPLD_SYSFS_DIR}/com_exp_pwr_force_off\"\nPWR_TH_RST_SYSFS=\"${SMBCPLD_SYSFS_DIR}/mac_reset_n\"\n\n# CPLD version\nSMB_CPLD_VER=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nSMB_CPLD_SUB_VER=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nPWR_CPLD_VER=$(head -n 1 \"$PWRCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nPWR_CPLD_SUB_VER=$(head -n 1 \"$PWRCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nSCM_CPLD_VER=$(head -n 1 \"$SCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nSCM_CPLD_SUB_VER=$(head -n 1 \"$SCMCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\nFCM_CPLD_VER=$(head -n 1 \"$FCMCPLD_SYSFS_DIR/cpld_ver\" 2> /dev/null)\nFCM_CPLD_SUB_VER=$(head -n 1 \"$FCMCPLD_SYSFS_DIR/cpld_sub_ver\" 2> /dev/null)\n\n# SMB Board Rev\nSMB_CPLD_BOARD_REV=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/board_ver\" 2> /dev/null)\n\n# 48V DC PSU P/N\nDELTA_48V=\"0x45 0x43 0x44 0x32 0x35 0x30 0x31 0x30 0x30 0x31 0x35\"\nLITEON_48V=\"0x44 0x44 0x2d 0x32 0x31 0x35 0x32 0x2d 0x32 0x4c\"\n\nwedge_is_us_on() {\n    local val0 val1\n\n    val0=$(head -n 1 < \"$PWR_USRV_SYSFS\" 2> /dev/null)\n    val1=$(head -n 1 < \"$PWR_USRV_FORCE_OFF\" 2> /dev/null)\n    \n    if [ \"$val0\" == \"0x1\" ] && [ \"$val1\" == \"0x1\" ] ; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n\n    return 0\n}\n\nwedge_board_type_rev(){\n    full_board_type=$(wedge_full_board_type)\n    board_type=$(wedge_board_type)\n    rev=$(wedge_board_rev)\n    if [ $((board_type)) -eq 0 ]; then\n        if [ $(( full_board_type&2 )) -ne 0 ]; then\n            case $rev in\n                6)\n                    echo \"WEDGE400_MP_RESPIN\"\n                    ;;\n                *)\n                    echo \"WEDGE400 (Undefine $rev)\"\n                    ;;\n            esac\n        else\n            case $rev in\n                0)\n                    echo \"WEDGE400_EVT/EVT3\"\n                    ;;\n                2)\n                    echo \"WEDGE400_DVT\"\n                    ;;\n                3)\n                    echo \"WEDGE400_DVT2/PVT1/PV2\"\n                    ;;\n                4)\n                    echo \"WEDGE400_PVT3\"\n                    ;;\n                5)\n                    echo \"WEDGE400_MP\"\n                    ;;\n                *)\n                    echo \"WEDGE400 (Undefine $rev)\"\n                    ;;\n            esac\n        fi\n    elif [ $((board_type)) -eq 1 ]; then\n        if [ $(( full_board_type&2 )) -ne 0 ]; then\n            case $rev in\n                4)\n                    echo \"WEDGE400-C_MP_RESPIN\"\n                    ;;\n                *)\n                    echo \"WEDGE400-C (Undefine $rev)\"\n                    ;;\n            esac\n        else\n            case $rev in\n                0)\n                    echo \"WEDGE400-C_EVT\"\n                    ;;\n                1)\n                    echo \"WEDGE400-C_EVT2\"\n                    ;;\n                2)\n                    echo \"WEDGE400-C_DVT\"\n                    ;;\n                3)\n                    echo \"WEDGE400-C_DVT2\"\n                    ;;\n                *)\n                    echo \"WEDGE400-C_(Undefine $rev)\"\n                    ;;\n            esac\n        fi\n    else\n        echo \"Undefine_($board_type,$rev)\"\n    fi\n}\n\nwedge_board_type() {\n    rev=$(gpio_get BMC_CPLD_BOARD_TYPE_0)\n    if [ $((rev)) -eq 0 ]; then\n        echo 1  # Wedge400-C\n    else\n        echo 0  # Wedge400\n    fi\n}\n\nwedge_full_board_type() {\n    # Wedge400 MP respin or later is added more 2 pins to indicate new board type\n    local val0 val1 val2\n    val0=$(gpio_get BMC_CPLD_BOARD_TYPE_0)\n    val1=$(gpio_get BMC_CPLD_BOARD_TYPE_1)\n    val2=$(gpio_get BMC_CPLD_BOARD_TYPE_2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    local val0 val1 val2\n    val0=$(gpio_get BMC_CPLD_BOARD_REV_ID0)\n    val1=$(gpio_get BMC_CPLD_BOARD_REV_ID1)\n    val2=$(gpio_get BMC_CPLD_BOARD_REV_ID2)\n    echo $((val0 | (val1 << 1) | (val2 << 2)))\n}\n\nboard_type_is_wedge400() {\n    brd_type=$(wedge_board_type)\n    if [ \"$brd_type\" -eq \"0\" ]; then\n        return 0\n    fi\n\n    return 1\n}\n\nboard_type_is_wedge400c() {\n    brd_type=$(wedge_board_type)\n    if [ \"$brd_type\" -eq \"1\" ]; then\n        return 0\n    fi\n\n    return 1\n}\n\nwedge400_rev_is_mp() {\n    if ! board_type_is_wedge400; then\n        return 1\n    fi\n\n    brd_rev=$(wedge_board_rev)\n    if [ \"$brd_rev\" -ge \"6\" ]; then\n        return 1\n    fi\n\n    return 0\n}\n\nwedge400_rev_is_respin() {\n    if ! board_type_is_wedge400; then\n        return 1\n    fi\n\n    brd_rev=$(wedge_board_rev)\n    if [ \"$brd_rev\" -lt \"6\" ]; then\n        return 1\n    fi\n\n    return 0\n}\n\nwedge400c_rev_is_mp() {\n    if ! board_type_is_wedge400c; then\n        return 1\n    fi\n\n    brd_rev=$(wedge_board_rev)\n    if [ \"$brd_rev\" -ge \"4\" ]; then\n        return 1\n    fi\n\n    return 0\n}\n\nwedge400c_rev_is_respin() {\n    if ! board_type_is_wedge400c; then\n        return 1\n    fi\n\n    brd_rev=$(wedge_board_rev)\n    if [ \"$brd_rev\" -lt \"4\" ]; then\n        return 1\n    fi\n\n    return 0\n}\n\nboard_rev_is_respin() {\n    if wedge400_rev_is_respin || wedge400c_rev_is_respin; then\n        return 0\n    fi\n\n    return 1\n}\n\nwedge_power_on_board() {\n    # wedge400 SCM power is controlled by SCMCPLD\n    return 0\n}\n\nwedge_prepare_cpld_update() {\n    echo \"Stop fscd service.\"\n    sv stop fscd\n\n    # from stress test found sometime sv stop fscd has timeout\n    # and wdtcli can't stop watchdog, that do BMC reboot while CPLD updating.\n    # Add fuser to check /dev/watchdog ready to used after fscd release it.\n    watchdog_ok=0\n    MAX_RETRY=5\n    for ((retry=1; retry <= MAX_RETRY; retry++))\n    do\n        /usr/bin/fuser /dev/watchdog &> /dev/null\n        # return code is 1 when no one hold /dev/watchdog\n        if [ $? -eq 1 ]; then\n            echo \"/dev/watchdog available\"\n            watchdog_ok=1\n            break\n        fi\n        echo \"waiting for /dev/watchdog, retry $retry/$MAX_RETRY\"\n        sleep 2\n    done;\n    if [ $watchdog_ok -ne 1 ]; then\n        echo \"Watchdog could not be stopped. Retry later\"\n        return 1;\n    fi\n\n    echo \"Disable watchdog.\"\n    /usr/local/bin/wdtcli stop\n\n    echo \"Set fan speed 40%.\"\n    set_fan_speed.sh 40\n\n    return 0\n}\n\nwedge_power_supply_type() {\n    # Only PEM has max6615 which I2C slave address is 0x18\n    is_pem1=$(i2cget -f -y 24 0x18 0x0 &> /dev/null; echo $?)\n    is_pem2=$(i2cget -f -y 25 0x18 0x0 &> /dev/null; echo $?)\n    if i2cget -y -f 24 0x58 0x9a s &> /dev/null;then    # PSU1\n        is_psu1_48v=$(i2cget -y -f 24 0x58 0x9a s)\n    elif i2cget -y -f 25 0x58 0x9a s &> /dev/null;then  # PSU2\n        is_psu2_48v=$(i2cget -y -f 25 0x58 0x9a s)\n    fi\n    power_type=\"\"\n    if [ $# -eq 1 ]; then\n        if [ \"$1\" = \"1\" ]; then\n            if [ \"$is_pem1\" -eq 0 ]; then\n                power_type=\"PEM\"\n            else\n                power_type=\"PSU\"\n            fi\n        elif [ \"$1\" = \"2\" ]; then\n            if [ \"$is_pem2\" -eq 0 ]; then\n                power_type=\"PEM\"\n            else\n                power_type=\"PSU\"\n            fi\n        else\n            echo \"wedge_power_supply_type < 1 | 2 >\"\n            return\n        fi\n    else\n        if [ \"$is_pem1\" -eq 0 ] || [ \"$is_pem2\" -eq 0 ]; then\n            power_type=\"PEM\"\n        else\n            power_type=\"PSU\"\n        fi\n    fi\n\n    # Detect 48V DC PSU\n    if [[ \"$is_psu1_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu1_48v\" = \"$LITEON_48V\" ||\n        \"$is_psu2_48v\" = \"$DELTA_48V\" ||\n        \"$is_psu2_48v\" = \"$LITEON_48V\" ]];then\n            power_type=\"PSU48\"\n    fi\n    echo $power_type\n}\n", "num_lines": 332}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\necho \"SMB_SYSCPLD: $((SMB_CPLD_VER)).$((SMB_CPLD_SUB_VER))\"\necho \"SMB_PWRCPLD: $((PWR_CPLD_VER)).$((PWR_CPLD_SUB_VER))\"\necho \"SCMCPLD: $((SCM_CPLD_VER)).$((SCM_CPLD_SUB_VER))\"\necho \"FCMCPLD: $((FCM_CPLD_VER)).$((FCM_CPLD_SUB_VER))\"\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nimg=\"$1\"\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\n\nusage() {\n    echo \"Usage: $prog <img_file> <options: hw|sw>\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\nenable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        1\n    gpio_set PWR_CPLD_JTAG_EN_N     1\n    gpio_set SYS_CPLD_JTAG_EN_N     1\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     0\n    gpio_set PWR_CPLD_HITLESS       0\n    gpio_set FCM_CPLD_HITLESS       1\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       0\n    gpio_set BMC_FCM_SEL            0\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ndisable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        0\n    gpio_set PWR_CPLD_JTAG_EN_N     1\n    gpio_set SYS_CPLD_JTAG_EN_N     1\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     1\n    gpio_set PWR_CPLD_HITLESS       0\n    gpio_set FCM_CPLD_HITLESS       0\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       0\n    gpio_set BMC_FCM_SEL            1\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ntrap 'rm -rf /tmp/fcmcpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/fcmcpld_update\n\nif ! wedge_prepare_cpld_update; then\n    echo \"Aborting CPLD upgrade\"\n    echo \"The FSCD may be closed incompletely,\"\n    echo \"Please check the watchdog timeout, to prevent system reboot.\"\n    exit 1\nfi\n\nenable_jtag_chain\n\ncase $2 in\n    hw)\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\n    sw)\n        ispvm -f 1000 dll $DLL_PATH \"${img}\"\n        ;;\n    *)\n        # default: hw mode\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\nesac\n\nresult=$?\n\nif [ \"$2\" = \"sw\" ]; then\n    expect=1\nelse\n    expect=0\nfi\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    echo \"Re-start fscd service.\"\n    sv start fscd\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    echo \"To prevent system reboot. Keep fscd stop & watchdog disable.\"\n    exit 1\nfi\n", "num_lines": 128}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ndump_fpga_version() {\n    local fpga_dir=$1\n    local fpga_name=$2\n\n    fpga_ver=`head -n 1 ${fpga_dir}/fpga_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        return\n    fi\n    fpga_sub_ver=`head -n 1 ${fpga_dir}/fpga_sub_ver 2> /dev/null`\n    if [ $? -ne 0 ]; then\n        echo \"${fpga_name} is not detected\"\n        return\n    fi\n\n    echo \"${fpga_name}: $(($fpga_ver)).$(($fpga_sub_ver))\"\n}\n\necho -n \"DOMFPGA1: \"\nbus=13\naddr=0x60\ndom_fpga1_ver=$(i2cget -f -y $bus $addr 0x01 2>/dev/null)\ndom_fpga1_ver_sub=$(i2cget -f -y $bus $addr 0x02 2>/dev/null)\nif [ ! -z $dom_fpga1_ver ]; then\n    echo \"$(($dom_fpga1_ver)).$(($dom_fpga1_ver_sub))\"\nelse\n    echo \"Not found\"\nfi\n\necho -n \"DOMFPGA2: \"\nbus=5\naddr=0x60\ndom_fpga2_ver=$(i2cget -f -y $bus $addr 0x01 2>/dev/null)\ndom_fpga2_ver_sub=$(i2cget -f -y $bus $addr 0x02 2>/dev/null)\nif [ ! -z $dom_fpga2_ver ]; then\n    echo \"$(($dom_fpga2_ver)).$(($dom_fpga2_ver_sub))\"\nelse\n    echo \"Not found\"\nfi\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nwedge_power_on_board\n\necho -n \"Checking microserver power status ... \"\nif wedge_is_us_on 10 \".\"; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    wedge_power.sh on -f\nfi\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nSMB_DIR=$SMBCPLD_SYSFS_DIR\nSCM_CMD=$SMB_DIR\"/scm_present_int_status\"\nFAN_CMD=$FCMCPLD_SYSFS_DIR\nDEBUG_CARD_PRSNT_GPIO=\"/tmp/gpionames/DEBUG_PRESENT_N/value\"\n\n\nfunction usage\n{\n  program=$(basename \"$0\")\n  echo \"Usage:\"\n  echo \"     $program \"\n  echo \"     $program <TYPE>\"\n  echo \"     <TYPE>: scm/fan/psu/pem/debug_card\"\n}\n\n# Will return <key> : <val>\n# eg - scm : 1\nfunction get_presence\n{\n  local file=$1 key=$2\n  val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n  if [ \"$val\" = \"0\" ]; then\n      val=1\n  else\n      val=0\n  fi\n  echo \"$key : $val\"\n}\n\n# SCM\nfunction get_scm_presence\n{\n  key=\"scm\"\n  get_presence \"$SCM_CMD\" \"$key\"\n}\n\n# FANs\nfunction get_fan_presence\n{\n  local num=1\n  while [ $num -le 4 ]; do\n      key=\"fan${num}\"\n      file=\"$FAN_CMD/fan${num}_present\"\n      get_presence \"$file\" \"$key\"\n      (( num++ ))\n  done\n}\n\n# Power supplies\nfunction get_psu_presence\n{\n  for i in {1..2}; do\n    key=\"psu${i}\"\n    file=\"$SMB_DIR/psu_present_${i}_N_int_status\"\n    val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n    if [ \"$val\" = \"0\" ]; then\n      type=$(wedge_power_supply_type \"$i\")\n      if [[ \"$type\" = \"PSU\" || \"$type\" = \"PSU48\" ]]; then\n        echo \"$key : 1\"\n        continue\n      fi\n    fi\n    echo \"$key : 0\"\n  done\n}\n\n# Pem \nfunction get_pem_presence\n{\n  for i in {1..2}; do\n    key=\"pem${i}\"\n    file=\"$SMB_DIR/psu_present_${i}_N_int_status\"\n    val=$(head -n1 \"$file\" | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n    if [ \"$val\" = \"0\" ]; then\n      type=$(wedge_power_supply_type \"$i\")\n      if [ \"$type\" = \"PEM\" ]; then\n        echo \"$key : 1\"\n        continue\n      fi\n    fi\n    echo \"$key : 0\"\n  done\n}\n\n# Debug card\nfunction get_debug_card_presence\n{\n  key=\"debug_card\"\n  val=$(head -n1 $DEBUG_CARD_PRSNT_GPIO | awk '{print substr($0,0,3) }' | sed \"s/.x//\")\n  if [ \"$val\" = \"0\" ]; then\n      val=0\n  else\n      val=1\n  fi\n  echo $key \":\" $val\n}\n\n# get all info\nif [[ $1 = \"\" ]]; then\n  echo \"CARDS\"\n  get_scm_presence\n\n  echo \"FANS\"\n  get_fan_presence\n\n  echo \"POWER SUPPLIES\"\n  get_psu_presence\n  get_pem_presence\n\n  echo \"DEBUG CARD\"\n  get_debug_card_presence\n\n  exit 0\nelse\n  if [[ $1 = \"scm\" ]]; then\n    get_scm_presence\n  elif [[ $1 = \"fan\" ]]; then\n    get_fan_presence\n  elif [[ $1 = \"psu\" ]]; then\n    get_psu_presence\n  elif [[ $1 = \"pem\" ]]; then\n    get_pem_presence\n  elif [[ $1 = \"debug_card\" ]]; then\n    get_debug_card_presence\n  else\n    usage\n  fi\n  exit 0\nfi\n", "num_lines": 155}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nimg=\"$1\"\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\n\nusage() {\n    echo \"Usage: $prog <img_file> <options: hw|sw>\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\nenable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        1\n    gpio_set PWR_CPLD_JTAG_EN_N     0\n    gpio_set SYS_CPLD_JTAG_EN_N     1\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     1\n    gpio_set PWR_CPLD_HITLESS       1\n    gpio_set FCM_CPLD_HITLESS       0\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       0\n    gpio_set BMC_FCM_SEL            1\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ndisable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        0\n    gpio_set PWR_CPLD_JTAG_EN_N     1\n    gpio_set SYS_CPLD_JTAG_EN_N     1\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     1\n    gpio_set PWR_CPLD_HITLESS       0\n    gpio_set FCM_CPLD_HITLESS       0\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       0\n    gpio_set BMC_FCM_SEL            1\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ntrap 'rm -rf /tmp/pwrcpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/pwrcpld_update\n\nif ! wedge_prepare_cpld_update; then\n    echo \"Aborting CPLD upgrade\"\n    echo \"The FSCD may be closed incompletely,\"\n    echo \"Please check the watchdog timeout, to prevent system reboot.\"\n    exit 1\nfi\n\nenable_jtag_chain\n\ncase $2 in\n    hw)\n        # enable CPLD immediately after cpld update done\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -R -f 12000000\n        ;;\n    sw)\n        ispvm -f 1000 dll $DLL_PATH \"${img}\"\n        ;;\n    *)\n        # default: hw mode\n        # enable CPLD immediately after cpld update done\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -R -f 12000000\n        ;;\nesac\n\nresult=$?\n\nif [ \"$2\" = \"sw\" ]; then\n    expect=1\nelse\n    expect=0\nfi\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    echo \"Re-start fscd service.\"\n    sv start fscd\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    echo \"To prevent system reboot. Keep fscd stop & watchdog disable.\"\n    exit 1\nfi\n\n", "num_lines": 131}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n\n# This script is a workaround for the I2C PMBUS vout sensor reading issue given\n# the root cause has not been found. When the issue happened, we measured the voltage\n# and it was normal, also reload the pmbus device driver will fix the issue.\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprintf \"Check special sensors and rebind driver...\"\n\nretry=0\nwhile [ $retry -lt 5 ]; do\n    sensor_ok=$(/usr/local/bin/sensor-util smb 0x55 --force | grep ok &> /dev/null; echo $?)\n    if [ $((sensor_ok)) -eq 0 ]; then\n        echo \"Done\"\n        exit 0\n    fi\n    retry=$((retry + 1))\n    echo \"trying rebind driver pxe1211 for i2c device 1-0e, time $retry\"\n    i2c_device_delete 1 0x0e\n    i2c_device_add 1 0x0e pxe1211\ndone\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\n# There are two reset pins to ASIC. System reset and PCI reset.\n#\n# When PWR_TH_RST_SYSFS is set to 0, CPLD will drive both reset pins to trigger\n# reset.\n#\n# When PWR_TH_RST_SYSFS is set to 1, CPLD will drive system reset, followed by\n# PCI reset following the reset sequeence.\n#\n# There is another sysfs file, 'cpld_mac_pcie_perst_l', which can be used\n# to control the PCI reset pin separately. However, we don't use it for now\n# as we depend on the CPLD for the correct reset sequence.\n\necho 0 > $PWR_TH_RST_SYSFS\nsleep 1\necho 1 > $PWR_TH_RST_SYSFS\n\nlogger \"Reset Tomahawk\"\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nimg=\"$1\"\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\nusage() {\n    echo \"Usage: $prog <img_file> <options: hw|sw>\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\nenable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN  1\n    gpio_set PWR_CPLD_JTAG_EN_N  1\n    gpio_set SYS_CPLD_JTAG_EN_N  1\n    gpio_set SCM_CPLD_JTAG_EN_N  0\n    gpio_set FCM_CPLD_JTAG_EN_N  1\n    gpio_set PWR_CPLD_HITLESS  0\n    gpio_set FCM_CPLD_HITLESS  0\n    gpio_set SCM_CPLD_HITLESS  1\n    gpio_set SMB_CPLD_HITLESS  0\n    gpio_set BMC_FCM_SEL  1\n    gpio_set BMC_SCM_CPLD_EN 0\n}\n\ndisable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN  0\n    gpio_set PWR_CPLD_JTAG_EN_N  1\n    gpio_set SYS_CPLD_JTAG_EN_N  1\n    gpio_set SCM_CPLD_JTAG_EN_N  1\n    gpio_set FCM_CPLD_JTAG_EN_N  1\n    gpio_set PWR_CPLD_HITLESS  0\n    gpio_set FCM_CPLD_HITLESS  0\n    gpio_set SCM_CPLD_HITLESS  0\n    gpio_set SMB_CPLD_HITLESS  0\n    gpio_set BMC_FCM_SEL  1\n    gpio_set BMC_SCM_CPLD_EN 1\n}\n\ntrap 'rm -rf /tmp/scmcpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/scmcpld_update\n\nif ! wedge_prepare_cpld_update; then\n    echo \"Aborting CPLD upgrade\"\n    echo \"The FSCD may be closed incompletely,\"\n    echo \"Please check the watchdog timeout, to prevent system reboot.\"\n    exit 1\nfi\n\nenable_jtag_chain\n\ncase $2 in\n    hw)\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\n    sw)\n        ispvm -f 1000 dll $DLL_PATH \"${img}\"\n        ;;\n    *)\n        # default: hw mode\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\nesac\n\nresult=$?\n\nif [ \"$2\" = \"sw\" ]; then\n    expect=1\nelse\n    expect=0\nfi\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    echo \"Re-start fscd service.\"\n    sv start fscd\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    echo \"To prevent system reboot. Keep fscd service stop & watchdog disable.\"\n    exit 1\nfi\n", "num_lines": 127}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n. /usr/local/bin/openbmc-utils.sh\n\n# Skip AVS setup on Wedge400C unit\nif [ \"$(wedge_board_type)\" != \"0\" ]; then\n    exit 0\nfi\n\nVID_START=1.6 # Unit Voltage\nVID_STEP=0.00625 # Unit Voltage\nISL_VOUT_PMBUS_COMMAND=0x21\n\nVALID_MAX=0x8A\nVALID_MIN=0x72\n\nMAX_RETRY=5\npower_count=0\navs_count=0\nwhile true; do\n    th3_power_on=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/th3_turn_on\" 2> /dev/null)\n    th3_power_good=$(head -n 1 \"$SMBCPLD_SYSFS_DIR/vddcore_th3_power_good\" 2> /dev/null)\n    if [ \"$((th3_power_good))\" != \"1\" ] || [ \"$((th3_power_on))\" != \"1\" ]; then\n        sleep 1\n        power_count=$((power_count + 1))\n        if [ $power_count -ge $MAX_RETRY ]; then\n            if [ $power_count -eq $MAX_RETRY ]; then\n                echo \"$0 timeout, set AVS directly\"\n            fi\n        else\n            continue\n        fi\n    fi\n\n    sleep 0.5\n\n    TH3_ROV=$(i2cget -f -y 12 0x3e 0x46) # Get TH3 AVS value from SYSCPLD\n    if [ $((TH3_ROV)) -lt $((VALID_MIN)) ] || [ $((TH3_ROV)) -gt $((VALID_MAX)) ]; then \n        avs_count=$((avs_count + 1))\n        if [ $avs_count -ge $MAX_RETRY ]; then\n            echo \"Invalid AVS value: $TH3_ROV out of range: ($VALID_MIN - $VALID_MAX)\"\n            echo \"Will not set AVS voltage, use ISL68317 default output voltage\"\n            exit 1\n        else\n            continue\n        fi\n    fi\n\n    TH3_ROV_DEC=$(printf \"%d\" \"$TH3_ROV\") \n\n    VRM_VCC_MAX=$(echo $VID_START \"$TH3_ROV_DEC\" $VID_STEP | awk '{printf \"%.5f\", $1-(($2-2)*$3)}')\n\n    ISL_VOUT_mV=$(echo \"$VRM_VCC_MAX\" | awk '{printf \"%d\", $1*1000}') # Convert to mV\n\n    ISL_VOUT_PMBUS_VALUE=$(printf \"0x%04x\" \"$ISL_VOUT_mV\") # Convert to HEX\n\n    # Set VOUT to ISL68317\n    # AVS connect to isl68137 channel 2\n    i2cset -f -y 1 0x60 0x0 0x1\n    if [ \"$(i2cset -f -y 1 0x60 $ISL_VOUT_PMBUS_COMMAND $((ISL_VOUT_PMBUS_VALUE)) w)\" ]; then\n        echo \"Cannot communicate with ISL68317.\"\n        continue\n    fi\n\n    ISL_VOUT_READBACK=$(i2cget -f -y 1 0x60 0x21 w | awk '{printf \"%d\", $1}') # Readback ISL68317 VOUT\n\n    if [ $((ISL_VOUT_READBACK)) -ne $((ISL_VOUT_mV)) ]; then\n        echo \"Failed to write the value to ISL68317.\"\n        continue\n    fi\n    echo \"Set AVS voltage to $ISL_VOUT_mV mV, read back is $ISL_VOUT_READBACK mV\"\n    exit 0\ndone\n", "num_lines": 94}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\ncmd_bic_ver=\"bic-util scm 0xe2 0x0b 0x15 0xa0 0x00 0x02\"\nCOUNTER=0\nMAX_RETRY=10\nrex='^[0-9]+$'\n\necho \"Initializing Bridge-IC I2C Frequency...\"\nwhile [ $COUNTER -lt $MAX_RETRY ]; do\n    readarray -td ' ' bic_data <<<\"$($cmd_bic_ver)\"\n    if [[ ${bic_data[4]} =~ $rex ]] ; then\n        break\n    fi\n    sleep 3\n    ((COUNTER+=1))\ndone\n\nif [ $COUNTER -eq $MAX_RETRY ];then\n    echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\nfi\n\nbic_major=$(( 10#${bic_data[3]} ))\nbic_minor=$(( 10#${bic_data[4]} ))\nbic_ver=\"$bic_major.${bic_data[4]}\"\n\necho Bridge-IC version is v\"$bic_ver\".\n\nif [ \"$bic_major\" -ge 1 ];then\n    if [ \"$bic_minor\" -ge 11 ];then\n        ret=$(bic-util scm 0xe0 0x2a 0x15 0xa0 0x00 0x01)\n        IANA=\"15 A0 00\"\n        if [ -z \"${ret##*$IANA*}\" ];then\n                echo Bridge-IC is initialized SCL to 1Mhz.\n        else\n                echo \"Error: Cannot access Bridge-IC.\" >&2; exit 1\n        fi\n    fi\nfi\n\nexit 0\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Make the backup BIOS flash connect to COMe instead of BMC\n#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_oe_n\n#echo 0 > ${SCMCPLD_SYSFS_DIR}/com_spi_sel\n\n# Setup management port LED\n/usr/local/bin/setup_mgmt.sh led &\n\n# Setup USB Serial to RS485\necho 0 > \"${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_0\"\necho 0 > \"${SMBCPLD_SYSFS_DIR}/cpld_usb_mux_sel_1\"\n\n# Init server_por_cfg\n#if [ ! -f \"/mnt/data/kv_store/server_por_cfg\" ]; then\n#    /usr/bin/kv set server_por_cfg on persistent\n#fi\n\n# Force COMe's UART connect to BMC UART-5 and FB USB debug\n# UART connect to BMC UART-2\necho 0x3 > \"$SMBCPLD_SYSFS_DIR/uart_selection\"\n\n# Read board type from Board type GPIO pin and save to cache\nbrd_type=$(wedge_board_type)\nbrd_rev=$(wedge_board_rev)\n\n#Read PSU type from eeprom and save to cache\npwr_type=$(wedge_power_supply_type)\n\n/usr/bin/kv set \"board_type\" \"$brd_type\"\n/usr/bin/kv set \"power_type\" \"$pwr_type\"\n\n# Check board type to select lmsensor configuration\nif [ $((brd_type)) -eq 0 ]; then\n  cp /etc/sensors.d/custom/wedge400.conf /etc/sensors.d/wedge400.conf\n  # Check board revision\n  if [ $((brd_rev)) -ge 6 ]; then # for respin or newer\n    cp /etc/sensors.d/custom/wedge400-respin.conf /etc/sensors.d/wedge400-respin.conf\n  else\n    cp /etc/sensors.d/custom/wedge400-evt-mp.conf /etc/sensors.d/wedge400-evt-mp.conf\n  fi;\nelif  [ $((brd_type)) -eq 1 ]; then\n  cp /etc/sensors.d/custom/wedge400c.conf /etc/sensors.d/wedge400c.conf\n  # Check board revision\n  if [ $((brd_rev)) -ge 4 ]; then # for respin or newer\n    cp /etc/sensors.d/custom/wedge400c-respin.conf /etc/sensors.d/wedge400c-respin.conf\n  else\n    cp /etc/sensors.d/custom/wedge400c-evt-dvt2.conf /etc/sensors.d/wedge400c-evt-dvt2.conf\n  fi;\nfi\n\n# For the time being, we set GB VDD Core to 825mv, to take care of\n# some of the early DVT W400c devices whose VRD default value upon power-up\n# is NOT 825. This will not harm newer devices with correct default value.\nif [ $((brd_type)) -eq 1 ]; then\n  echo \"Running GB VDD Core fix routine.\"\n  /usr/local/bin/set_vdd.sh 825\nfi\n\n# export_gpio_pin for PCA9555 4-0027\ngpiocli export -c 4-0027 -o 8 --shadow ISO_DEBUG_RST_BTN_N\ngpiocli export -c 4-0027 -o 9 --shadow ISO_PWR_BTN_N\ngpiocli export -c 4-0027 -o 10 --shadow PWRGD_PCH_PWROK\ngpiocli export -c 4-0027 -o 11 --shadow ISO_CB_RESET_N\ngpiocli export -c 4-0027 -o 12 --shadow COM_PWROK\ngpiocli export -c 4-0027 -o 13 --shadow CPU_CATERR_MSMI_EXT\ngpiocli export -c 4-0027 -o 14 --shadow ISO_COM_SUS_S3_N\ngpiocli export -c 4-0027 -o 15 --shadow DEBUG_UART_SELECT\n", "num_lines": 100}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\necho -n \"Setting up Default GPIOs value... \"\n\n# Set all reset pin to high, keep in normal mode\ngpio_set_value BMC_EMMC_RST_N_R 1\ngpio_set_value SYS_CPLD_RST_N 1\ngpio_set_value BMC_DOM_FPGA1_RST 1\ngpio_set_value BMC_DOM_FPGA2_RST 1\n\necho \"done.\"\n", "num_lines": 43}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\ni2c_detect_address() {\n   bus=\"$1\"\n   addr=\"$2\"\n   if [ -n \"$3\" ]; then\n      retries=\"$3\"\n   else\n      retries=5\n   fi\n\n   retry=0\n\n   while [ \"$retry\" -lt \"$retries\" ]; do\n      if i2cget -y -f \"$bus\" \"$addr\" &> /dev/null; then\n         return 0\n      fi\n      usleep 50000\n      retry=$((retry + 1))\n   done\n   \n   echo \"setup-i2c : i2c_detect not found $bus - $addr\" > /dev/kmsg\n   return 1\n}\n\nget_mux_bus_num() {\n    i2c_switch=$1\n    channel=$2\n\n    if [ \"$i2c_switch\" = \"2-0070\" ]; then\n        start_bus_num=16\n    elif [ \"$i2c_switch\" = \"8-0070\" ]; then\n        start_bus_num=24\n    elif [ \"$i2c_switch\" = \"11-0076\" ]; then\n        start_bus_num=32\n    else\n        echo \"Error: i2c switch $i2c_switch does not exist\"\n        start_bus_num=200\n    fi\n\n    echo $((start_bus_num + channel))\n}\n\nbrd_type_rev=$(wedge_board_type_rev)\necho \"Board Type/Revision: $brd_type_rev\"\n\nbrd_type=$(wedge_board_type)\nbrd_rev=$(wedge_board_rev)\n\n# # Bus 2\ni2c_device_add 2 0x3e scmcpld          # SCMCPLD\n\n# # Bus 12\ni2c_device_add 12 0x3e smb_syscpld     # SMB_SYSCPLD\n\n# # i2c-mux 8-0070, channel 8\ni2c_device_add \"$(get_mux_bus_num 8-0070 7)\" 0x3e smb_pwrcpld # SMB_PWRCPLD\n\n# # Bus 13\ni2c_device_add 13 0x60 domfpga        # DOM FPGA 1\n\n# # Bus 4\ni2c_device_add 4 0x27 pca9555         # PCA9555\n\n# # Bus 5\ni2c_device_add 5 0x60 domfpga         # DOM FPGA 2\n\n# # Bus 6\ni2c_device_add 6 0x51 24c64            # SMB EEPROM\ni2c_device_add 6 0x21 pca9534          # PCA9534\n\n# # Bus 1\ni2c_device_add 1 0x3a powr1220          # SMB power sequencer\ni2c_device_add 1 0x4d ir35215           # TH3 serdes voltage/current monitor on the left\ni2c_device_add 1 0x47 ir35215           # TH3 serdes voltage/current monitor on the right\n\n# # Bus 3\ni2c_device_add 3 0x48 tmp75            # SMB temp. sensor\ni2c_device_add 3 0x4b tmp75            # SMB temp. sensor\n\n# # i2c-mux 2-0070, channel 1, support dual footprint\nif i2c_detect_address \"$(get_mux_bus_num 2-0070 0)\" 0x10; then\n    i2c_device_add \"$(get_mux_bus_num 2-0070 0)\" 0x10 adm1278 # SCM Hotswap\nelse\n    i2c_device_add \"$(get_mux_bus_num 2-0070 0)\" 0x44 lm25066 # SCM Hotswap\nfi\n\n# # i2c-mux 2-0070, channel 2\ni2c_device_add \"$(get_mux_bus_num 2-0070 1)\" 0x4d tmp75   # SCM temp. sensor\n\n# # i2c-mux 2-0070, channel 4\ni2c_device_add \"$(get_mux_bus_num 2-0070 3)\" 0x52 24c64   # EEPROM\n\n# # i2c-mux 2, channel 5\ni2c_device_add \"$(get_mux_bus_num 2-0070 4)\" 0x50 24c02   # BMC54616S EEPROM\n\n# # i2c-mux 8-0070, channel 1\nif [ \"$(wedge_power_supply_type 1)\" = \"PSU\" ] ||\n   [ \"$(wedge_power_supply_type 1)\" = \"PSU48\" ]; then\n    i2c_device_add \"$(get_mux_bus_num 8-0070 0)\" 0x58 psu_driver   # PSU1 Driver\nelse\n    i2c_device_add \"$(get_mux_bus_num 8-0070 0)\" 0x58 ltc4282      # PEM1 Driver\n    i2c_device_add \"$(get_mux_bus_num 8-0070 0)\" 0x18 max6615      # PEM1 Driver\nfi\n\n# # i2c-mux 8-0070, channel 2\nif [ \"$(wedge_power_supply_type 2)\" = \"PSU\" ] ||\n   [ \"$(wedge_power_supply_type 2)\" = \"PSU48\" ]; then\n    i2c_device_add \"$(get_mux_bus_num 8-0070 1)\" 0x58 psu_driver   # PSU2 Driver\nelse\n    i2c_device_add \"$(get_mux_bus_num 8-0070 1)\" 0x58 ltc4282      # PEM2 Driver\n    i2c_device_add \"$(get_mux_bus_num 8-0070 1)\" 0x18 max6615      # PEM2 Driver\nfi\n\n# # i2c-mux 11-0076, channel 1\ni2c_device_add \"$(get_mux_bus_num 11-0076 0)\" 0x3e fcbcpld # FCB CPLD\n\n# # i2c-mux 11-0076, channel 2\ni2c_device_add \"$(get_mux_bus_num 11-0076 1)\" 0x51 24c64           # FCM EEPROM\n\n# # i2c-mux 11-0076, channel 3\ni2c_device_add \"$(get_mux_bus_num 11-0076 2)\" 0x48 tmp75           # Temp. sensor\ni2c_device_add \"$(get_mux_bus_num 11-0076 2)\" 0x49 tmp75           # Temp. sensor\n\n# # i2c-mux 11-0076, channel 4, support dual footprint\nif i2c_detect_address \"$(get_mux_bus_num 11-0076 3)\" 0x10; then\n    i2c_device_add \"$(get_mux_bus_num 11-0076 3)\" 0x10 adm1278     # FCB hot swap\nelse\n    i2c_device_add \"$(get_mux_bus_num 11-0076 3)\" 0x44 lm25066     # FCB hot swap\nfi\n\n# # i2c-mux 11-0076, channel 5\ni2c_device_add \"$(get_mux_bus_num 11-0076 4)\" 0x52 24c64           # FAN tray\n\n# # i2c-mux 11-0076, channel 6\ni2c_device_add \"$(get_mux_bus_num 11-0076 5)\" 0x52 24c64           # FAN tray\n\n# # i2c-mux 11-0076, channel 7\ni2c_device_add \"$(get_mux_bus_num 11-0076 6)\" 0x52 24c64           # FAN tray\n\n# # i2c-mux 11-0076, channel 8\ni2c_device_add \"$(get_mux_bus_num 11-0076 7)\" 0x52 24c64           # FAN tray\n\nfixup_board_revisions() {\n    if board_rev_is_respin; then\n        # RACKMON EEPROM, added in Wedge400 MP Respin and Wedge400C Respin\n        i2c_device_add 6 0x50 24c64            # RACKMON EEPROM\n    else\n        # below sensors are removed from Wedge400 MP Respin (type=0,rev=6)\n        # and Wedge400C Respin (type=1,rev=4).\n        i2c_device_add 3 0x4c tmp421           # SMB temp. sensor\n        i2c_device_add 3 0x4e tmp421           # SMB temp. sensor\n        i2c_device_add \"$(get_mux_bus_num 2-0070 1)\" 0x4c tmp75  # SCM temp sensor\n\n        # TH3 EEPROM is removed from Wedge400 MP Respin (type=0,rev=6) and\n        # Wedge400C Respin (type=1,rev=4).\n        i2c_device_add \"$(get_mux_bus_num 8-0070 4)\" 0x54 24c02  # TH3 EEPROM\n    fi\n\n    if board_type_is_wedge400; then         # Only Wedge400 (type=0)\n        i2c_device_add 1 0x60 isl68137      # TH3 core voltage/current monitor\n        if wedge400_rev_is_mp; then\n            i2c_device_add 3 0x4f tmp422    # TH3 temp. sensor Remove from Respin version(rev=6)\n        fi\n    else                                    # Only Wedge400-C (type=1)\n        i2c_device_add 1 0x40 xdpe132g5c    # Wedge400-C GB core voltage/current monitor\n        i2c_device_add 3 0x2a net_casic     # GB temp. sensor\n        if [  $((brd_rev)) -eq 0 ]; then\n            i2c_device_add 1 0x43 ir35215   # Wedge400-C GB serdes voltage/current monitor\n        else\n            i2c_device_add 1 0x0e pxe1211   # Wedge400-C EVT2(rev=0) or later GB serdes voltage/current monitor\n        fi\n    fi\n\n    #\n    # For wedge400 MP respin(type=0,rev=6) and later.\n    # Dual footprint will mount either one temp sensor for each bus.\n    # i2c-mux 8-0070, channel 3-5 and 7\n    #\n    if wedge400_rev_is_respin; then\n        # i2c-mux 8-0070, channel 3\n        if i2c_detect_address \"$(get_mux_bus_num 8-0070 2)\" 0x4d; then\n            i2c_device_add \"$(get_mux_bus_num 8-0070 2)\" 0x4d tmp421      # TMP421_4\n        else\n            i2c_device_add \"$(get_mux_bus_num 8-0070 2)\" 0x4c adm1032     # ADM1032_4\n        fi\n\n        # i2c-mux 8-0070, channel 4\n        if i2c_detect_address \"$(get_mux_bus_num 8-0070 3)\" 0x4d; then\n            i2c_device_add \"$(get_mux_bus_num 8-0070 3)\" 0x4d tmp421      # TMP421_3\n        else\n            i2c_device_add \"$(get_mux_bus_num 8-0070 3)\" 0x4c adm1032     # ADM1032_3\n        fi\n\n        # i2c-mux 8-0070, channel 5\n        if i2c_detect_address \"$(get_mux_bus_num 8-0070 4)\" 0x4d; then\n            i2c_device_add \"$(get_mux_bus_num 8-0070 4)\" 0x4d tmp421      # TMP421_2\n        else\n            i2c_device_add \"$(get_mux_bus_num 8-0070 4)\" 0x4c adm1032     # ADM1032_2\n        fi\n\n        # i2c-mux 8-0070, channel 7\n        if i2c_detect_address \"$(get_mux_bus_num 8-0070 6)\" 0x4d; then\n            i2c_device_add \"$(get_mux_bus_num 8-0070 6)\" 0x4d tmp421      # TMP421_1\n        else\n            i2c_device_add \"$(get_mux_bus_num 8-0070 6)\" 0x4c adm1032     # ADM1032_1\n        fi\n    else\n        i2c_device_add 3 0x49 tmp75            # SMB temp. sensor\n        i2c_device_add 3 0x4a tmp75            # SMB temp. sensor\n    fi\n\n    # BCM54616 EEPROMs are removed physically from:\n    #   - Wedge400 MP Respin(type=0,rev=6) and later\n    #   - Wedge400-C DVT(type=1,rev=2) and later\n    if [[ \"$brd_type\" -eq 0 && \"$brd_rev\" -lt 6 ]] || \\\n       [[ \"$brd_type\" -eq 1 && \"$brd_rev\" -lt 2 ]]; then\n        # # i2c-mux 8-0070, channel 3\n        i2c_device_add \"$(get_mux_bus_num 8-0070 2)\" 0x50 24c02          # BCM54616 EEPROM\n        # # i2c-mux 8-0070, channel 4\n        i2c_device_add \"$(get_mux_bus_num 8-0070 3)\" 0x50 24c02          # BCM54616 EEPROM\n    fi\n\n    # BSM EEPROM were added:\n    #   - Wedge400 DVT2(type=0,rev=3) or later,\n    #   - Wedge400c EVT2(type=1,rev=1) or later\n    if [[ \"$brd_type\" -eq 0 && \"$brd_rev\" -ge 3 ]] || \\\n       [[ \"$brd_type\" -eq 1 && \"$brd_rev\" -ge 1 ]]; then\n        i2c_device_add \"$(get_mux_bus_num 2-0070 6)\" 0x56 24c64   # BSM EEPROM\n    fi\n}\n\nfixup_board_revisions\n\n# Hack only needed for wedge400c.\nif board_type_is_wedge400c; then\n    /usr/local/bin/rebind-driver.sh\nfi\n\n#\n# Check if I2C devices are bound to drivers. A summary message (total #\n# of devices and # of devices without drivers) will be dumped at the end\n# of this function.\n#\ni2c_check_driver_binding\n", "num_lines": 268}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nCOM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok\")\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"     $program led\"\n}\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# When COM-e power is not ready, it doesn't work to set PHY register.\n# Therefore, waiting for COM-e power ready, then start to set PHY register.\nwhile [ \"$COM_E_PWRGD\" = \"0x0\" ];\ndo\n    COM_E_PWRGD=$(head -n 1 \"${SCMCPLD_SYSFS_DIR}/pwrgd_pch_pwrok\")\n    sleep 5\ndone\n\n# Enable MAC#1 Clock, refer to ast2500-v16.pdf Page 355\n# SCU 0x04 register: Bit[11] Reset MAC1 controller\n#     0: No operation, 1: Reset MAC1 controller\n# SCU 0x0C register: Bit20 MAC#1 Clock:\n#     0 Enable clock running, 1 disable clock running\ndevmem_set_bit \"$(scu_addr 04)\" 11\ndevmem_clear_bit \"$(scu_addr 0C)\" 20\ndevmem_clear_bit \"$(scu_addr 04)\" 11\n\n# Enable MAC#1 MDIO function, refer to ast2500-v16.pdf Page 376\n# SCU 0x88 register: Bit31 Enable MAC#1 MDIO1 function pin\n# SCU 0x88 register: Bit30 Enable MAC#1 MDC1 function pin\ndevmem_set_bit \"$(scu_addr 88)\" 30\ndevmem_set_bit \"$(scu_addr 88)\" 31\n\nif [ \"$1\" = \"led\" ]; then\n    echo -n \"Wait a few seconds to setup management port LED...\"\n\n    # Because the addresses of the PHY and OOB switch are different, so not need to differentiate \n    # the platform \n\n    # configure the platform with Marvell PHY and OOB swich:\n\n    # Setup Port 3 MGMT\n    mdio-util -m 1 -p 0x12 -w 0x1 -d 0x8088    # Write Config LED mode Data into Reg 0x01\n    mdio-util -m 1 -p 0x12 -w 0x0 -d 0x9676    #  Read Port3.Reg 0x16\n    mdio-util -m 1 -p 0x12 -w 0x0 -d 0x9a76    # Config Reg 0x01 value into Port3.Reg 0x16\n    mdio-util -m 1 -p 0x12 -r 0x1    # Read Reg 0x01\n\n    # Setup Port4 Rackmon port\n    mdio-util -m 1 -p 0x12 -w 0x1 -d 0x8088\n    mdio-util -m 1 -p 0x12 -w 0x0 -d 0x9696\n    mdio-util -m 1 -p 0x12 -w 0x0 -d 0x9a96\n    mdio-util -m 1 -p 0x12 -r 0x1\n\n    # Setup Copper Mode for SCM Management Port\n    mdio-util -m 1 -p 0x1 -w 0x16 -d 0x12\n    mdio-util -m 1 -p 0x1 -w 0x14 -d 0x8001\n    mdio-util -m 1 -p 0x1 -w 0x16 -d 0x0\n\n    #  configure the platform with Broadcom OOB swich:\n\n    # refer to BCM54616S Section 5, register 1C access\n    # Register 1C (Shadow 00010): Spare Control 1\n    # Bit0: 1: Enable link LED mode.\n    mdio-util -m 1 -p 0xe -w 0x1c -d 0x8801 &> /dev/null\n\n    # Register 1C (Shadow 01110): LED Selector 2\n    # Bit7~4: LED4 Selector, b0011: Activity LED \n    # Bit3~0: LED4 Selector, b0101: Slave\n    mdio-util -m 1 -p 0xe -w 0x1c -d 0xb435 &> /dev/null\n    echo \"Done!\"\nelse\n    usage\n    exit 1\nfi\n", "num_lines": 103}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# Set all IO direction to output\ni2cset -f -y 6 0x20 0x06 0x00\ni2cset -f -y 6 0x20 0x07 0x00\n\nIO0=$(i2cget -f -y 6 0x20 0x2)\nIO1=$(i2cget -f -y 6 0x20 0x3)\n\ncolor=$2\nname=$1\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"     $program <dev> <color>\"\n    echo \"\"\n    echo \"     <dev>: sts/smb/psu/fan\"\n    echo \"     <color>: off/red/blue/yellow/green\"\n}\n\nbrd_type=$(wedge_board_type)\nbrd_rev=$(wedge_board_rev)\n# In Wedge400 MP Respin and Wedge400C Respin\n# the led location are swaped\nif [ $((brd_type)) -eq 0 ] && [ $((brd_rev)) -ge 6 ] || \n   [ $((brd_type)) -eq 1 ] && [ $((brd_rev)) -ge 4 ]; then\n  case $name in\n    \"sts\")\n      led_id=2\n    ;;\n    \"fan\")\n      led_id=4\n    ;;\n    \"psu\")\n      led_id=3\n    ;;\n    \"smb\")\n      led_id=1\n    ;;\n    *)\n      usage\n      exit 1\n    ;;\n  esac\nelse\n  case $name in\n    \"sts\")\n      led_id=1\n    ;;\n    \"fan\")\n      led_id=2\n    ;;\n    \"psu\")\n      led_id=3\n    ;;\n    \"smb\")\n      led_id=4\n    ;;\n    *)\n      usage\n      exit 1\n    ;;\n  esac\nfi\n\ncase $color in\n    \"red\")\n        val=0x6\n    ;;\n    \"blue\")\n        val=0x3\n    ;;\n    \"yellow\")\n        val=0x4\n    ;;\n    \"green\")\n        val=0x5\n    ;;\n    \"off\")\n        val=0x7\n    ;;\n    *)\n    usage\n    exit 1\n    ;;\nesac\n\nif [ $((led_id)) -eq 2 ] || [ $((led_id)) -eq 4 ]; then\n  val=$((val << 3))\n  IO0_VAL=$(((IO0 & 0x7) | val))\n  IO1_VAL=$(((IO1 & 0x7) | val))\nelif [ $((led_id)) -eq 1 ] || [ $((led_id)) -eq 3 ]; then\n  IO0_VAL=$(((IO0 & 0x38) | val))\n  IO1_VAL=$(((IO1 & 0x38) | val))\nelse\n  usage\n  exit 1\nfi\n\nif [ $((led_id)) -eq 1 ] || [ $((led_id)) -eq 2 ]; then\n  i2cset -f -y 6 0x20 0x2 $IO0_VAL\nelse\n  i2cset -f -y 6 0x20 0x3 $IO1_VAL\nfi\n\n\n", "num_lines": 131}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nusage()\n{\n  echo \"usage :\"\n  echo \"   $0 <voltage in mv>\"\n  echo \"   eg. $0 850\"\n  echo \" limit : max 930 mV\"\n}\n\n\nif [ $# -ne 1 ]; then\n  usage\n  exit 255\nfi\n\nif [ $(($1)) -gt 931 ]; then\n  usage\n  exit 255\nfi\n\ni2cset -f -y 1 0x40 0x00 0x00\ni2cset -f -y 1 0x40 0x20 0x14    # linear mode  ,, N = 0x12\nvalue=$(( $1 * 1000 / 244 ))\ni2cset -f -y 1 0x40 0x21 $value w\n\nif [ $? -eq 0 ]; then\n  echo \"$1\"\n  exit 0\nelse\n  echo \"setting error\"\n  exit 254\nfi\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# shellcheck disable=SC1091\nsource /usr/local/bin/openbmc-utils.sh\n\nprog=\"$0\"\nimg=\"$1\"\n\nDLL_PATH=/usr/lib/libcpldupdate_dll_ast_jtag.so\n\n\nusage() {\n    echo \"Usage: $prog <img_file> <options: hw|sw>\"\n    echo\n    echo \"img_file: Image file for lattice CPLD\"\n    echo \"  VME file for software mode\"\n    echo \"  JED file for hardware mode\"\n    echo \"options:\"\n    echo \"  hw: Program the CPLD using JTAG hardware mode\"\n    echo \"  sw: Program the CPLD using JTAG software mode\"\n    echo\n    echo\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\nenable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        1\n    gpio_set PWR_CPLD_JTAG_EN_N     1\n    gpio_set SYS_CPLD_JTAG_EN_N     0\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     1\n    gpio_set PWR_CPLD_HITLESS       0\n    gpio_set FCM_CPLD_HITLESS       0\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       1\n    gpio_set BMC_FCM_SEL            1\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ndisable_jtag_chain(){\n    gpio_set BMC_JTAG_MUX_IN        0\n    gpio_set PWR_CPLD_JTAG_EN_N     1\n    gpio_set SYS_CPLD_JTAG_EN_N     1\n    gpio_set SCM_CPLD_JTAG_EN_N     1\n    gpio_set FCM_CPLD_JTAG_EN_N     1\n    gpio_set PWR_CPLD_HITLESS       0\n    gpio_set FCM_CPLD_HITLESS       0\n    gpio_set SCM_CPLD_HITLESS       0\n    gpio_set SMB_CPLD_HITLESS       0\n    gpio_set BMC_FCM_SEL            1\n    gpio_set BMC_SCM_CPLD_EN        1\n}\n\ntrap 'rm -rf /tmp/smbcpld_update' INT TERM QUIT EXIT\n\necho 1 > /tmp/smbcpld_update\n\nif ! wedge_prepare_cpld_update; then\n    echo \"Aborting CPLD upgrade\"\n    echo \"The FSCD may be closed incompletely,\"\n    echo \"Please check the watchdog timeout, to prevent system reboot.\"\n    exit 1\nfi\n\nenable_jtag_chain\n\ncase $2 in\n    hw)\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\n    sw)\n        ispvm -f 1000 dll $DLL_PATH \"${img}\"\n        ;;\n    *)\n        # default: hw mode\n        # CPLD update randomly failed with kernel 5.6, the issue can be fixed by\n        # customizing jtag frequency to 12MHz.\n        cpldprog -p \"${img}\" -f 12000000\n        ;;\nesac\n\nresult=$?\n\nif [ \"$2\" = \"sw\" ]; then\n    expect=1\nelse\n    expect=0\nfi\n\ndisable_jtag_chain\n\n# 0 is returned upon upgrade success\nif [ $result -eq $expect ]; then\n    echo \"Upgrade successful.\"\n    echo \"Re-start fscd service.\"\n    sv start fscd\n    exit 0\nelse\n    echo \"Upgrade failure. Return code from utility : $result\"\n    echo \"To prevent system reboot. Keep fscd stop & watchdog disable.\"\n    exit 1\nfi\n\n", "num_lines": 129}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n. /usr/local/bin/openbmc-utils.sh\n\nCONSOLE_SH=/usr/local/bin/us_console.sh\nFILE=/etc/us_pseudo_tty\nTTY=/dev/ttyS0\n\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ $pid ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  if [ -a $FILE ]\n    then\n      read -r TTY<$FILE\n  fi\n  $CONSOLE_SH connect\n\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  trap '\"$CONSOLE_SH\" disconnect' INT TERM QUIT EXIT\n\n  /usr/bin/microcom -s 57600 $TTY\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\necho 0x3 > $SMBCPLD_SYSFS_DIR/uart_selection\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 65}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\ndebug=0\nm95m02_page_size=256\nm95m02_page_count=1024\nfpga_header_size=112\n\nret=0\ntrap cleanup_spi INT TERM QUIT EXIT\n\nPIDFILE=\"/var/run/spi_util.pid\"\ncheck_duplicate_process()\n{\n    exec 2>$PIDFILE\n    flock -n 2 || (echo \"Another process is running\" && exit 1)\n    ret=$?\n    if [ $ret -eq 1 ]; then\n      exit 1\n    fi\n    pid=$$\n    echo $pid 1>&200\n}\n\nremove_pid_file()\n{\n    if [ -f $PIDFILE ]; then\n        rm $PIDFILE\n    fi\n}\n\ncheck_board_type()\n{\n    board_type=$(wedge_board_type)\n    if [ \"$((board_type))\" -eq 0 ]; then # Wedge400 any version\n        SWITCH_PCIE_FLASH=\"TH3_PCIE_FLASH\"\n        MAC_TYPE=\"W400\"\n    elif [ \"$((board_type))\" -eq 1 ]; then # Wedge400-C any version\n        SWITCH_PCIE_FLASH=\"GB_PCIE_FLASH\"\n        MAC_TYPE=\"W400C\"\n    else\n        SWITCH_PCIE_FLASH=\"GB_PCIE_FLASH\"\n        MAC_TYPE=\"W400?\"\n    fi\n}\n\ncheck_flash_info()\n{\n    spi_no=$1\n    flashrom -p linux_spi:dev=/dev/spidev\"$spi_no\".0\n}\n\nget_flash_first_type()\n{\n    ori_str=$(check_flash_info \"$spi_no\")\n    type=$(echo \"$ori_str\" | grep -m 1 '\"' | cut -d '\"' -f 2)\n    if [ \"$type\" ]; then\n        echo \"$type\"\n        return 0\n    else\n        echo \"Get flash type error: [$ori_str]\"\n        exit 1\n    fi\n}\n\nget_flash_size()\n{\n    spi_no=$1\n    ori_str=$(check_flash_info \"$spi_no\")\n    flash_sz=$(echo \"$ori_str\" | grep -m 1 '\"' | cut -d '(' -f 2 | cut -d ' ' -f 1)\n    echo \"$flash_sz\" | grep -E -q '^[0-9]+$'\n    num_ret=$?\n    if [ $num_ret -eq 0 ]; then\n        echo \"$flash_sz\"\n        return 0\n    else\n        echo \"Get flash size error: [$ori_str]\"\n        return 1\n    fi\n}\n\n# $1: input file size $2: flash size $3: output file path\npad_ff()\n{\n    out_file=$3\n    pad_size=$(($2 - $1))\n    dd if=/dev/zero bs=$pad_size count=1 | tr \"\\000\" \"\\377\" >> \"$out_file\"\n}\n\nresize_file()\n{\n    in_file=$1\n    out_file=$2\n    spi_no=$3\n    storage_type=$4\n    in_file_sz=$(stat -c%s \"$in_file\")\n    storage_sz=0\n    if [ \"$storage_type\" ] && [ \"$storage_type\" = \"m95m02\" ]; then\n        storage_sz=$((m95m02_page_count * m95m02_page_size))\n    else\n        flash_sz=$(get_flash_size \"$spi_no\")\n        ret=$?\n        if [ $((ret)) -eq 0 ]; then\n            storage_sz=$((flash_sz * 1024))\n        else\n            echo \"debug message: $flash_sz\"\n            exit 1\n        fi\n    fi\n\n    if [ $((in_file_sz)) -ne $((storage_sz)) ]; then\n        cp \"$in_file\" \"$out_file\"\n        pad_ff \"$in_file_sz\" \"$storage_sz\" \"$out_file\"\n    else\n        ln -s \"$(realpath \"$in_file\")\" \"$out_file\"\n    fi\n}\n\ndump_gpio_config(){\n    if [ $debug = 0 ]; then\n        return 0\n    fi\n    echo \"Dump SPI configurations...\"\n    if [ \"$1\" = \"SPI1\" ]; then\n        openbmc_gpio_util.py dump | grep SPI1\n    else\n        openbmc_gpio_util.py dump | grep SPI2\n    fi\n}\n\nexport_spi1_pins(){\n    gpiocli --shadow BMC_SPI1_CS0 -c aspeed-gpio -n GPIOI4 export > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_CLK -c aspeed-gpio -n GPIOI5 export > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_MOSI -c aspeed-gpio -n GPIOI6 export > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_MISO -c aspeed-gpio -n GPIOI7 export > /dev/null 2>&1\n}\n\nunexport_spi1_pins(){\n    gpiocli --shadow BMC_SPI1_CS0 -c aspeed-gpio -n GPIOI4 unexport > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_CLK -c aspeed-gpio -n GPIOI5 unexport > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_MOSI -c aspeed-gpio -n GPIOI6 unexport > /dev/null 2>&1\n    gpiocli --shadow BMC_SPI1_MISO -c aspeed-gpio -n GPIOI7 unexport > /dev/null 2>&1\n}\n\n# currently only EEPROM\nset_spi1_to_gpio(){\n    devmem_set_bit \"$(scu_addr 7C)\" 12\n    devmem_set_bit \"$(scu_addr 7C)\" 13\n    devmem_set_bit \"$(scu_addr 80)\" 15\n    export_spi1_pins\n    gpiocli --shadow BMC_SPI1_CLK set-direction out\n    gpiocli --shadow BMC_SPI1_CS0 set-direction out\n    gpiocli --shadow BMC_SPI1_MISO set-direction in\n    gpiocli --shadow BMC_SPI1_MOSI set-direction out\n    dump_gpio_config SPI1\n}\n\nset_spi1_to_spi(){\n    devmem_set_bit \"$(scu_addr 70)\" 12\n    unexport_spi1_pins\n    dump_gpio_config SPI1\n}\n\n# currently no use\nset_spi2_to_spi_cs(){\n    cs=$1\n    if [ $((cs)) -eq 0 ]; then\n        # spi2 cs0\n        devmem_set_bit \"$(scu_addr 88)\" 26\n        devmem_set_bit \"$(scu_addr 88)\" 27\n        devmem_set_bit \"$(scu_addr 88)\" 28\n        devmem_set_bit \"$(scu_addr 88)\" 29\n    else\n        # spi2 cs1\n        devmem_set_bit \"$(scu_addr 8C)\" 0\n        devmem_set_bit \"$(scu_addr 88)\" 27\n        devmem_set_bit \"$(scu_addr 88)\" 28\n        devmem_set_bit \"$(scu_addr 88)\" 29\n    fi\n    dump_gpio_config SPI2\n}\n\n# currently no use\nset_spi2_to_gpio(){\n    devmem_clear_bit \"$(scu_addr 88)\" 26\n    devmem_clear_bit \"$(scu_addr 88)\" 27\n    devmem_clear_bit \"$(scu_addr 88)\" 28\n    devmem_clear_bit \"$(scu_addr 88)\" 29\n    devmem_clear_bit \"$(scu_addr 8C)\" 0\n    gpiocli --shadow BMC_SPI2_CLK set-direction out\n    gpiocli --shadow BMC_SPI2_CS0 set-direction out\n    gpiocli --shadow BMC_SPI2_CS1 set-direction out\n    gpiocli --shadow BMC_SPI2_MISO set-direction in\n    gpiocli --shadow BMC_SPI2_MOSI set-direction out\n    dump_gpio_config SPI2\n}\n\nread_flash_to_file()\n{\n    spi_no=$1\n    tmp_file=$2\n    type=$(get_flash_first_type \"$spi_no\")\n    flashrom -p linux_spi:dev=/dev/spidev\"$spi_no\".0 -r \"$tmp_file\" -c \"$type\"\n    ret=$?\n    if [ $((ret)) -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/spidev${spi_no}.0 -r $tmp_file -c $type]\"\n        exit 1\n    fi\n}\n\nwrite_flash_to_file(){\n    spi_no=$1\n    in_file=$2\n    out_file=\"/tmp/${3}_spi${1}_tmp\"\n    resize_file \"$in_file\" \"$out_file\" \"$spi_no\"\n    type=$(get_flash_first_type \"$spi_no\")\n    flashrom -p linux_spi:dev=/dev/spidev\"${spi_no}\".0 -w \"$out_file\" -c \"$type\"\n    ret=$?\n    if [ $((ret)) -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/spidev${spi_no}.0 -w $out_file -c $type]\"\n        exit 1\n    fi\n}\n\nerase_flash(){\n    spi_no=$1\n    type=$(get_flash_first_type \"$spi_no\")\n    flashrom -p linux_spi:dev=/dev/spidev\"${spi_no}\".0 -E -c \"$type\"\n    ret=$?\n    if [ $((ret)) -ne 0 ]; then\n        echo \"debug cmd: [flashrom -p linux_spi:dev=/dev/spidev${spi_no}.0 -E -c $type]\"\n        exit 1\n    fi\n}\n\nread_m95m02_to_file(){\n    spi_no=$1\n    file=$2\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    dd if=\"$eeprom_node\" of=\"$file\" count=$m95m02_page_count bs=$m95m02_page_size\n}\n\nwrite_m95m02(){\n    spi_no=$1\n    file=$2\n    out_file=\"/tmp/${3}_spi${1}_tmp\"\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    tr '\\0' '\\377' < /dev/zero | dd count=$m95m02_page_count bs=$m95m02_page_size of=\"$eeprom_node\"\n    resize_file \"$file\" \"$out_file\" \"$spi_no\" 'm95m02'\n    dd of=\"$eeprom_node\" if=\"$out_file\" count=$m95m02_page_count bs=$m95m02_page_size\n}\n\nerase_m95m02(){\n    spi_no=$1\n    eeprom_node=\"/sys/bus/spi/devices/spi${spi_no}.1/eeprom\"\n    modprobe -r at25\n    modprobe at25\n    tr '\\0' '\\377' < /dev/zero | dd count=$m95m02_page_count bs=$m95m02_page_size of=\"$eeprom_node\"\n}\n\nbios_flash_pre_operate() {\n    curr_flash=$(boot_info.sh bios)\n    if [ \"$curr_flash\" = \"slave\" ]; then\n        wedge_power.sh off > /dev/null\n    fi\n}\n\nbios_flash_post_operate() {\n    curr_flash=$(boot_info.sh bios)\n    if [ \"$curr_flash\" = \"slave\" ]; then\n        wedge_power.sh on > /dev/null\n    fi\n}\n\nread_spi1_dev(){\n    spi_no=1\n    dev=$1\n    file=$2\n    case ${dev} in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BIOS\" | \"TH3_PCIE_FLASH\" | \"GB_PCIE_FLASH\")\n            echo \"Reading flash to $file...\"\n            read_flash_to_file $spi_no \"$file\"\n        ;;\n        \"SYSTEM_EE\" | \"BCM5389_EE\")\n            echo \"Reading eeprom to $file...\"\n            # read_flash_to_file $spi_no $file\n            cs=$(gpio_name2value BMC_SPI1_CS0)\n            clk=$(gpio_name2value BMC_SPI1_CLK)\n            miso=$(gpio_name2value BMC_SPI1_MISO)\n            mosi=$(gpio_name2value BMC_SPI1_MOSI)\n            at93cx6_util_py3.py --cs \"$cs\" --clk \"$clk\" --mosi \"$mosi\" --miso \"$miso\" chip read --file \"$file\"\n        ;;\n        \"DOM_FPGA_FLASH1\" | \"DOM_FPGA_FLASH2\")\n            echo \"Reading flash to $file...\"\n            read_flash_to_file $spi_no /tmp/fpga_fw_tmp\n            in_file_sz=$(stat -c%s /tmp/fpga_fw_tmp)\n            if [ -e \"$file\" ]; then\n                rm \"$file\"\n            fi\n            pad_ff 0 $fpga_header_size \"$file\"\n            dd if=/tmp/fpga_fw_tmp bs=\"$in_file_sz\" count=1 >> \"$file\"\n            rm /tmp/fpga_fw_tmp\n        ;;\n    esac\n}\n\nwrite_spi1_dev(){\n    spi_no=1\n    dev=$1\n    file=$2\n    case ${dev} in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BIOS\")\n            echo \"Writing $file to flash...\"\n            bios_flash_pre_operate\n            write_flash_to_file \"$spi_no\" \"$file\" \"$dev\"\n            bios_flash_post_operate\n        ;;\n        \"TH3_PCIE_FLASH\" | \"GB_PCIE_FLASH\")\n            echo \"Writing $file to flash...\"\n            write_flash_to_file \"$spi_no\" \"$file\" \"$dev\"\n        ;;\n        \"SYSTEM_EE\" | \"BCM5389_EE\")\n            # write_flash_to_file $spi_no $file\n            echo \"Writing $file to eeprom...\"\n            cs=$(gpio_name2value BMC_SPI1_CS0)\n            clk=$(gpio_name2value BMC_SPI1_CLK)\n            miso=$(gpio_name2value BMC_SPI1_MISO)\n            mosi=$(gpio_name2value BMC_SPI1_MOSI)\n            at93cx6_util_py3.py --cs \"$cs\" --clk \"$clk\" --mosi \"$mosi\" --miso \"$miso\" chip write --file \"$file\"\n        ;;\n        \"DOM_FPGA_FLASH1\" | \"DOM_FPGA_FLASH2\")\n            echo \"Writing $file to flash...\"\n            if [ -e /tmp/fpga_fw_tmp ]; then\n                rm /tmp/fpga_fw_tmp\n            fi\n            # remove header unused of fpga bit file\n            dd if=\"$file\" skip=1 bs=$fpga_header_size of=/tmp/fpga_fw_tmp\n            write_flash_to_file \"$spi_no\" /tmp/fpga_fw_tmp \"$dev\"\n            rm /tmp/fpga_fw_tmp\n        ;;\n    esac\n}\n\nerase_spi1_dev(){\n    spi_no=1\n    dev=$1\n    file=$2\n    case ${dev} in\n        ## W25Q128 , W25Q128 , W25Q257\n        \"BIOS\" | \"DOM_FPGA_FLASH1\" | \"DOM_FPGA_FLASH2\" | \"TH3_PCIE_FLASH\" | \"GB_PCIE_FLASH\")\n            echo \"Erasing flash...\"\n            erase_flash \"$spi_no\"\n        ;;\n        \"SYSTEM_EE\" | \"BCM5389_EE\")\n            echo \"Erasing eeprom...\"\n            # erase_flash $spi_no\n            cs=$(gpio_name2value BMC_SPI1_CS0)\n            clk=$(gpio_name2value BMC_SPI1_CLK)\n            miso=$(gpio_name2value BMC_SPI1_MISO)\n            mosi=$(gpio_name2value BMC_SPI1_MOSI)\n            at93cx6_util_py3.py --cs \"$cs\" --clk \"$clk\" --mosi \"$mosi\" --miso \"$miso\" chip erase\n        ;;\n    esac\n}\n\nget_smb_cpld_spi_1b(){\n    b0=$(cat \"$SMBCPLD_SYSFS_DIR\"/spi_1_b0)\n    b1=$(cat \"$SMBCPLD_SYSFS_DIR\"/spi_1_b1)\n    b2=$(cat \"$SMBCPLD_SYSFS_DIR\"/spi_1_b2)\n    echo \"spi_1b [ $b2 $b1 $b0 ]\"\n}\n\nset_smb_cpld_spi_1b(){\n    if [ $# = 3 ]; then\n        echo \"$3\" > \"$SMBCPLD_SYSFS_DIR\"/spi_1_b0\n        echo \"$2\" > \"$SMBCPLD_SYSFS_DIR\"/spi_1_b1\n        echo \"$1\" > \"$SMBCPLD_SYSFS_DIR\"/spi_1_b2\n    else\n        echo \"Set SPI1 BIT FAILED\"\n    fi\n}\n\nconfig_spi1_pin_and_path(){\n    dev=$1\n\n    case ${dev} in\n        \"SYSTEM_EE\")\n            set_spi1_to_gpio\n            echo 0 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n        \"BIOS\")\n            set_spi1_to_spi\n            echo 1 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n        \"BCM5389_EE\")\n            set_spi1_to_gpio\n            echo 2 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n        \"TH3_PCIE_FLASH\" | \"GB_PCIE_FLASH\")\n            set_spi1_to_spi\n            echo 3 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n        \"DOM_FPGA_FLASH1\")\n            set_spi1_to_spi\n            echo 4 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n        \"DOM_FPGA_FLASH2\")\n            set_spi1_to_spi\n            echo 5 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n        ;;\n\n        *)\n            echo \"Please enter {SYSTEM_EE, BIOS, BCM5389_EE, $SWITCH_PCIE_FLASH, DOM_FPGA_FLASH1, DOM_FPGA_FLASH2}\"\n            exit 1\n        ;;\n    esac\n    echo \"Config SPI1 Done.\"\n}\n\noperate_spi1_dev(){\n    op=$1\n    dev=$2\n    file=$3\n    ## Operate devices ##\n    case ${op} in\n        \"read\")\n                read_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"write\")\n                write_spi1_dev \"$dev\" \"$file\"\n        ;;\n        \"erase\")\n                erase_spi1_dev \"$dev\"\n        ;;\n        *)\n            echo \"Operation $op is not defined.\"\n        ;;\n    esac\n}\n\ncleanup_spi(){\n    if [ $ret -eq 1 ]; then\n        exit 1\n    fi\n    echo 0 > \"$SMBCPLD_SYSFS_DIR\"/spi_1_sel\n\n    rm -rf /tmp/*_spi*_tmp\n    remove_pid_file\n}\n\nui(){\n    . /usr/local/bin/openbmc-utils.sh\n    op=$1\n    spi=$2\n\n    # SPI 1.0 speed\n    devmem 0x1e630010 32 0x07\n    # SPI 2.0 speed\n    devmem 0x1e631010 32 0x407\n    # SPI 2.1 speed\n    devmem 0x1e631014 32 0x2007\n\t## Open the path to device ##\n    case ${spi} in\n        \"spi1\")\n            dev=$3\n            file=$4\n            config_spi1_pin_and_path \"$dev\"\n            operate_spi1_dev \"$op\" \"$dev\" \"$file\"\n            # set gpio to normal mode\n            set_spi1_to_gpio\n        ;;\n        *)\n            echo \"No such SPI bus.\"\n            return 1\n        ;;\n    esac\n}\n\nusage(){\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <op> spi1 <spi1 device> <file>\"\n    echo \"  <op>          : read, write, erase\"\n    echo \"  <spi1 device> : SYSTEM_EE, BIOS, BCM5389_EE, $SWITCH_PCIE_FLASH, DOM_FPGA_FLASH1, DOM_FPGA_FLASH2\"\n    echo \"                  (SYSTEM_EE not support for Wedge400-C)\"\n    echo \"Examples:\"\n    echo \"  $program write spi1 DOM_FPGA_FLASH domfpga.bit\"\n    echo \"\"\n}\n\ncheck_parameter(){\n    program=$(basename \"$0\")\n    op=$1\n    spi=$2\n    case ${op} in\n        \"read\" | \"write\" | \"erase\")\n            ;;\n        *)\n            return 1\n            ;;\n    esac\n    if [ \"$spi\" ] && [ \"$spi\" = \"spi1\" ]; then\n        dev=$3\n        file=$4\n\n        # SYSTEM_EE disable on Wedge400-C\n        if [ \"$dev\" = \"SYSTEM_EE\" ] && [ \"$MAC_TYPE\" = \"W400C\" ]; then\n            return 1\n        fi\n\n        ## Check device\n        case ${dev} in\n            \"SYSTEM_EE\"|\"BIOS\"|\"BCM5389_EE\"|\"TH3_PCIE_FLASH\"|\"GB_PCIE_FLASH\"|\"DOM_FPGA_FLASH1\"|\"DOM_FPGA_FLASH2\")\n                ## Check operation\n                case ${op} in\n                    \"read\" | \"write\")\n                        if [ $# -ne 4 ]; then\n                            return 1\n                        fi\n                        ;;\n                    \"erase\")\n                        if [ $# -ne 3 ]; then\n                            return 1\n                        fi\n                        ;;\n                esac\n                ;;\n            *)\n                return 1\n                ;;\n        esac\n    else\n        return 1\n    fi\n\n    return 0\n}\n\ncheck_board_type\ncheck_duplicate_process\ncheck_parameter \"$@\"\nis_par_ok=$?\n\nif [ $is_par_ok -eq 0 ]; then\n    ui \"$@\"\nelse\n    usage\n    exit 1\nfi\n\n", "num_lines": 577}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\nif [ \"$(wedge_board_type)\" != \"1\" ]; then\n    echo \"$(basename \"$0\") only support on Wedge400C\"\n    exit 1\nfi\n\nSMB_CPLD_I2C_BUS=\"12\"\nSMB_CPLD_I2C_ADDR=\"0x3e\"\n\ni2c_wr() {\n    i2cset \"$@\"; sleep 0.01;\n}\n\n# Wedge400-C GB switch reset commands collection\ngb_reset() {\n    if [ \"$1\" = \"cycle\" ];then\n        # gb power off\n        i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x42 0x0e\n        sleep 0.5\n        # gb power on\n        i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x42 0x0f\n        sleep 1\n    fi\n\n    # [3] mux_ps=1, ps=1, scan=0, tri_l=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    # [0] a_rstn=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xfe\n    # [0] tri_l=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xc\n    # [1] scan_mode=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xe\n    # [1] scan_mode=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xc\n    # [0] tri_l=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    # [0] a_rstn=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xff\n    # [0] a_rstn=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xfe\n    # [2] ps=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0x9\n    # [2] ps=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0xd\n    sleep 0.5\n    # [0] a_rstn=1\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x05 0xff\n    # [3] mux_ps=0\n    i2c_wr -f -y $SMB_CPLD_I2C_BUS $SMB_CPLD_I2C_ADDR 0x60 0x5\n}\n\ncase \"$1\" in\n    \"--help\" | \"?\" | \"-h\")\n        program=$(basename \"$0\")\n        echo \"Usage: switch chip reset command\"\n        echo \"  <$program> only reset switch without switch power cycle\"\n        echo \"  <$program cycle> to reset switch after switch power cycle\"\n    ;;\n\n    *)\n        shift\n        gb_reset \"$1\"\n    ;;\nesac\n", "num_lines": 86}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"$0 <connect | disconnect>\"\n}\n\n. /usr/local/bin/openbmc-utils.sh\n\nif [ $# -ne 1 ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$1\" == \"connect\" ]; then\n    VALUE=1\nelif [ \"$1\" == \"disconnect\" ]; then\n    VALUE=0\nelse\n    usage\n    exit 1\nfi\n\n# GPIOS5 (32) controls if uS console connects to UART5 or not.\n# To enable GPIOS5, SCU8C[5] must be 0\ndevmem_clear_bit $(scu_addr 8C) 5\n\ngpiocli --shadow BMC_UART_SEL5 set-direction out\ngpiocli --shadow BMC_UART_SEL5 set-value $VALUE", "num_lines": 46}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nPWR_USRV_RST_SYSFS=\"${SCMCPLD_SYSFS_DIR}/iso_com_rst_n\"\nPWR_CYCLE_SYSFS=\"${PWRCPLD_SYSFS_DIR}/power_cycle_go\"\nPWR_TIMER_BASE_1S_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_base_1s\"\nPWR_TIMER_BASE_10S_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_base_10s\"\nPWR_TIMER_COUNTER_SETTING_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_counter_setting\"\nPWR_TIMER_COUNTER_SETTING_UPDATE_SYSFS=\"${PWRCPLD_SYSFS_DIR}/timer_counter_setting_update\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole wedge400 system ungracefully\"\n    echo \"      -s -t [1-2550]: Setting boot up time.\"\n    echo \"            From 1 to 249 the step is 1 second.\"\n    echo \"            From 250 to 2550 the step is 10 seconds\"\n    echo \"            and don't care ones-digits.\"\n    echo\n    echo\n}\n\nmain_power_status() {\n    return 0\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on_com_e() {\n    echo 1 > \"$PWR_USRV_SYSFS\"\n    echo 1 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n    logger -p user.crit \"Power on microserver ...\"\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    # reset TH\n    # reset_brcm.sh\n    # power on sequence\n    do_on_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_off_com_e() {\n    echo 0 > \"$PWR_USRV_FORCE_OFF\"\n    return $?\n}\n\ndo_off() {\n    local ret\n    logger -p user.crit \"Power off microserver ...\"\n    echo -n \"Power off microserver ...\"\n    do_off_com_e\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n    else\n        echo \" Failed\"\n    fi\n    return $ret\n}\n\ndo_config_reset_timer() {\n    # Check numeric\n    wake_t=$1\n    echo \"$wake_t\" | grep -E -q '^[0-9]+$'\n    ret=$?\n    if [ $ret -ne 0 ]; then\n        usage\n        exit 1\n    else\n        if [ \"$wake_t\" -ge 1 ] && [ \"$wake_t\" -lt 250 ];then\n            echo 1 > \"$PWR_TIMER_BASE_1S_SYSFS\"\n            echo 0 > \"$PWR_TIMER_BASE_10S_SYSFS\"\n            logger \"Waiting $wake_t seconds for the system boot up\"\n            echo \"Waiting $wake_t seconds for the system boot up\"\n        elif [ \"$wake_t\" -ge 250 ] && [ \"$wake_t\" -le 2550 ];then\n            echo 0 > \"$PWR_TIMER_BASE_1S_SYSFS\"\n            echo 1 > \"$PWR_TIMER_BASE_10S_SYSFS\"\n            wake_t=$((wake_t/10))\n            logger \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n            echo \"Waiting $((wake_t * 10)) seconds for the system boot up\"\n        else\n            usage\n            exit 1\n        fi\n        echo $wake_t > \"$PWR_TIMER_COUNTER_SETTING_SYSFS\"\n        echo 1 > \"$PWR_TIMER_COUNTER_SETTING_UPDATE_SYSFS\"\n    fi\n}\n\ndo_reset() {\n    local system timer wake_t opt\n    system=0\n    timer=0\n    wake_t=0\n    while getopts \"st:\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            t)\n                timer=1\n                wake_t=$OPTARG\n                ;;\n            *)\n                usage\n                exit 1\n                ;;\n        esac\n    done\n\n    if [ $system -eq 1 ]; then\n        if [ $timer -eq 1 ]; then\n            do_config_reset_timer \"$wake_t\"\n        fi\n        logger -p user.crit \"Power reset the whole system ...\"\n        echo  \"Power reset the whole system ...\"\n        # Synchronize cached writes to persistent storage\n        # We found somethimes /mnt/data data lost after wedge_power.sh reset -s,\n        # add sync in case of file system will be broken by random power cycle.\n        sync\n        mmc hwreset enable /dev/mmcblk0\n        gpio_set_value BMC_EMMC_RST_N_R 1\n        gpio_set_value BMC_EMMC_RST_N_R 0\n        sleep 0.01\n        gpio_set_value BMC_EMMC_RST_N_R 1\n        echo 1 > \"$PWR_CYCLE_SYSFS\"\n        sleep 3\n        # Control should not reach here, but if it failed to reset\n        # the system through PSU, then run a workaround to reset\n        # most of the system instead (if not all)\n        logger -p user.crit \"Failed to reset the system. Will start workaround in 3 sec..\"\n        echo \"Failed to reset the system. Will start workaround in 3 sec..\"\n        i2cset -f -y 1 0x3a 0x12 0\n    else\n        if ! wedge_is_us_on; then\n            echo \"Power resetting microserver that is powered off has no effect.\"\n            echo \"Use '$prog on' to power the microserver on\"\n            return 1\n        fi\n        # reset TH first\n        # reset_brcm.sh\n        logger -p user.crit \"Power reset microserver ...\"\n        echo -n \"Power reset microserver ...\"\n        echo 0 > \"$PWR_USRV_RST_SYSFS\"\n        sleep 1\n        echo 1 > \"$PWR_USRV_RST_SYSFS\"\n        echo \"Done\"\n    fi\n    return 0\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit 1\nfi\n\ncommand=\"$1\"\nshift\n\nset_bic=0\ncase \"$command\" in\n    status)\n        do_status \"$@\"\n        ;;\n    on)\n        do_on \"$@\"\n        set_bic=1\n        ;;\n    off)\n        do_off \"$@\"\n        ;;\n    reset)\n        do_reset \"$@\"\n        set_bic=1\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\nesac\n\nif [ $set_bic -ne 0 ]; then\n    (sleep 10; setup_bic.sh) &\nfi\n\nexit $?\n", "num_lines": 264}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# Get output from bic-util\nbic_output=`bic-util scm --read_mac`\n\n# Check if the read was successful and output matches with our format\nmatch=`echo $bic_output| grep -e 'MAC address: [0-9a-f][0-9a-f]:'|wc -l`\nif [ \"$match\" == \"1\" ]; then\n    # Mac address: xx:xx:xx:xx:xx:xx\n    echo $bic_output| cut -d ' ' -f 3\n    exit 0\nelse\n    echo \"Cannot find out the microserver MAC\" 1>&2\n    exit -1\nfi\n\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\n\n/usr/local/bin/bic-cached 0 > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nSLOT_NAME=$1\n\ncase $SLOT_NAME in\n    scm)\n      SLOT_NUM=1\n      ;;\n    *)\n      N=${0##*/}\n      N=${N#[SK]??}\n      echo \"Usage: $N {scm}\"\n      exit 1\n      ;;\nesac\n\n# File format autodump<slot_id>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE=\"/var/run/autodump$SLOT_NUM.pid\"\n\n# check if auto crashdump is already running\nif [ -f $PID_FILE ]; then\n  echo \"Another auto crashdump for $SLOT_NAME is runnung\"\n  exit 1\nelse\n  touch $PID_FILE\nfi\n\n# Set crashdump timestamp\nsys_runtime=$(awk '{print $1}' /proc/uptime)\nsys_runtime=$(printf \"%0.f\" $sys_runtime)\necho $((sys_runtime+630)) > /tmp/cache_store/fru${SLOT_NUM}_crashdump\n\nDUMP_SCRIPT=\"/usr/local/bin/dump.sh\"\nCRASHDUMP_FILE=\"/mnt/data/crashdump_$SLOT_NAME\"\nCRASHDUMP_LOG_ARCHIVE=\"/mnt/data/crashdump_$SLOT_NAME.tar.gz\"\n\necho \"Auto Dump for $SLOT_NAME Started\"\n\n#HEADER LINE for the dump\n$DUMP_SCRIPT \"time\" > $CRASHDUMP_FILE\n#COREID dump\n$DUMP_SCRIPT $SLOT_NAME \"coreid\" >> $CRASHDUMP_FILE\n#MSR dump\n$DUMP_SCRIPT $SLOT_NAME \"msr\" >> $CRASHDUMP_FILE\n# Sensors & sensor thresholds\necho \"Sensor history at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"sensors\" >> $CRASHDUMP_FILE\necho \"Sensor threshold at dump:\" >> $CRASHDUMP_FILE 2>&1\n$DUMP_SCRIPT $SLOT_NAME \"threshold\" >> $CRASHDUMP_FILE\n\ntar zcf $CRASHDUMP_LOG_ARCHIVE -C `dirname $CRASHDUMP_FILE` `basename $CRASHDUMP_FILE` && \\\nrm -rf $CRASHDUMP_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"Crashdump for $SLOT_NAME is generated at $CRASHDUMP_LOG_ARCHIVE\"\n\necho \"Auto Dump for $SLOT_NAME Completed\"\n\nrm $PID_FILE\nexit 0\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIC_UTIL=\"/usr/bin/bic-util\"\nSENSOR_HISTORY=180\n\nif [ \"$#\" -eq 1 ] && [ $1 = \"time\" ]; then\n  now=$(date)\n  echo \"Crash Dump generated at $now\"\n  exit 0\nfi\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"$0 <slot#> coreid    ==> for CPU CoreID\"\n  echo \"$0 <slot#> msr       ==> for CPU MSR\"\n  echo \"$0 <slot#> sensors   ==> for sensor history\"\n  echo \"$0 <slot#> threshold ==> for sensor threshold\"\n  exit 1\nfi\n\necho \"\"\n\nif [ \"$2\" = \"coreid\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_coreid ] && $BIC_UTIL $1 --me_file /usr/local/fbpackages/crashdump/crashdump_coreid\nelif [ \"$2\" = \"msr\" ]; then\n  [ -r /usr/local/fbpackages/crashdump/crashdump_msr ] && $BIC_UTIL $1 --me_file /usr/local/fbpackages/crashdump/crashdump_msr\nelif [ \"$2\" = \"sensors\" ]; then\n  /usr/local/bin/sensor-util all --history $SENSOR_HISTORY\nelif [ \"$2\" = \"threshold\" ]; then\n  /usr/local/bin/sensor-util all --threshold \nfi\n\nexit 0\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nexec /usr/local/bin/front-paneld\n", "num_lines": 21}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/gpiod\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup gpio monitoring for wedge400... \"\n\nrunsv /etc/sv/gpiod > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\nif [ -e /sys/bus/i2c/devices/0-1010 ]; then\n    i2c_device_delete 0 0x1010\nfi\ni2c_device_add 0 0x1010 slave-mqueue\nexec /usr/local/bin/ipmbd 0 1\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\nif [ -e /sys/bus/i2c/devices/4-1010 ]; then\n    i2c_device_delete 4 0x1010\nfi\ni2c_device_add 4 0x1010 slave-mqueue\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 27}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nulimit -q 1024000\nrunsv /etc/sv/ipmbd_0 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_4 > /dev/null 2>&1 &\n\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nexec /usr/local/bin/ipmid\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-ipmid\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set IPMI Message handler\n### END INIT INFO\n\necho -n \"Setup IPMI message handler... \"\nrunsv /etc/sv/ipmid > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\nexec /usr/local/bin/pemd pem1 pem2\n", "num_lines": 23}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\n\n# If either one pem is present, pemd will start\nif [ \"$(wedge_power_supply_type)\" != \"PEM\" ]; then\n    echo \"Skip pemd as PEM is not present\"\n    exit 0\nfi\n\n# shellcheck disable=SC2039\necho -n \"Setup pem monitoring for wedge400... \"\n\nrunsv /etc/sv/pemd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\nbrd_type=$(wedge_full_board_type)\n\n# Wedge400 MP Respin or newer, change to use FT4232 for rackmon uart\nif [ $((brd_type)) -ge $((0x2)) ]; then\n    \n    # Detect FTDI chip\n    /usr/local/bin/ftdi_control -L\n    ftdi_detected=$?\n    # exit when can't detect FTDI Chip\n    if [ $((ftdi_detected)) -ne 0 ]; then\n        echo \"run-rackmond.sh : cannot detect FTDI chip\" > /dev/kmsg\n        exit 1\n    fi\n\n    # set FT4232 port 1 to GPIO Input\n    /usr/local/bin/ftdi_bitbang -I 1 -i 0 -i 1 -i 2 -i 4 -i 5 -i 6\n\n    rs485_cfg=0\n    rs485_cfg=$((rs485_cfg + $(/usr/local/bin/ftdi_control -o | grep CHANNEL_B_RS485 | grep -c 1 ) ))\n    rs485_cfg=$((rs485_cfg + $(/usr/local/bin/ftdi_control -o | grep CHANNEL_C_RS485 | grep -c 1 ) ))\n    rs485_cfg=$((rs485_cfg + $(/usr/local/bin/ftdi_control -o | grep CHANNEL_D_RS485 | grep -c 1 ) ))\n    if [ $((rs485_cfg)) -lt 3 ]; then\n        /usr/local/bin/ftdi_control -N -B1 -C1 -D1\n        touch /tmp/need_to_pwrcycle\n        echo \"run-rackmond.sh : Need to power cycle to reload the FTDI configuration\" > /dev/kmsg\n        exit 1\n    fi\n    if [ -e /tmp/need_to_pwrcycle ]; then\n        echo \"run-rackmond.sh : Need to power cycle to reload the FTDI configuration\" > /dev/kmsg\n        exit 1\n    fi\n    # Replace with multiport configuration.\n    ln -s /etc/usb_ft4232.conf /etc/rackmon.conf\nelse\n  ln -s /etc/usb_ft232.conf /etc/rackmon.conf\nfi\n\n\nexec /usr/local/bin/rackmond\n\n", "num_lines": 45}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-rackmond\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start Rackmon service\n### END INIT INFO\n\n#\n# No need to start rackmond if the according tty device cannot be found:\n#\n\n#shellcheck disable=SC1091\n\n. /usr/local/bin/openbmc-utils.sh\nbrd_type=$(wedge_full_board_type)\n\nif [ $((brd_type)) -ge $((0x2)) ]; then\n    # workaround on Respin SKU2 USB mux default isn't BMC\n    # need force it to select BMC <--> RACK\n    echo 1 > $SMBCPLD_SYSFS_DIR/cpld_usb_mux2_sel\n    sleep 5\nfi\n\nBMC_PSU_TTY=\"/dev/ttyUSB0\"\nif ! [ -e \"$BMC_PSU_TTY\" ]; then\n    echo \"rackmond not started: $BMC_PSU_TTY does not exist!\"\n    exit 1\nfi\n\nrunsv /etc/sv/rackmond > /dev/null 2>&1 &\nsv \"$1\" rackmond\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nARGS=\"scm smb fan1 fan2 fan3 fan4\"\n\n#\n# PSU and PEM will never be plugged to a switch at the same time, and\n# they won't be hotswapped. So we only need to mointor the power units\n# that are plugged at present.\n#\n# TODO: improve the logic to monitor only one PEM.\n#\nif [ \"$(wedge_power_supply_type)\" = \"PEM\" ]; then\n    ARGS=\"$ARGS pem1 pem2\"\nelse\n    ARGS=\"$ARGS psu1 psu2\"\nfi\n\n#shellcheck disable=SC2086\nexec /usr/local/bin/sensord $ARGS\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2019-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\necho -n \"Setup sensor monitoring for WEDGE400... \"\n\nrunsv /etc/sv/sensord > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttcsd trousers\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tcsd\n# Description:\t\ttcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n# shellcheck disable=SC1090\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo \"Starting $DESC: \"\n\n    # If TPM chip has not been discovered, probe the chip here\n\t    for file in /dev/tpm*\n\t\tdo\n\t\t  if [ ! -e \"$file\" ]\n\t\t  then\n      # Finally, register the device and install the driver\n            # shellcheck disable=SC1091\n            . /usr/local/bin/openbmc-utils.sh\n            i2c_device_add 7 0x20 tpm_i2c_infineon\n          fi\n\t\tdone\n\n    # Additionally, Generate symlink to tpm0 or tpm1, so that tcsd can use it\n    rm -f /dev/tpm\n\t\tif [ -e /dev/tpm0 ]\n    then\n      ln -s /dev/tpm0 /dev/tpm\n    else\n      ln -s /dev/tpm1 /dev/tpm\n    fi\n                # shellcheck disable=SC2086\n\t\tstart-stop-daemon --start --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nTTY=/dev/ttyS1\n\nmTerm_server_running() {\n  pid=$(ps | grep -v grep | grep '/usr/local/bin/mTerm_server' -m 1 |\n      awk '{print $1}')\n  if [ $pid ] ; then\n    return 0\n  fi\n  return 1\n}\n\nstart_sol_session() {\n  echo \"You are in SOL session.\"\n  echo \"Use ctrl-x to quit.\"\n  echo \"-----------------------\"\n  echo\n\n  /usr/bin/microcom -s 57600 $TTY\n\n  echo\n  echo\n  echo \"-----------------------\"\n  echo \"Exit from SOL session.\"\n}\n\n# if mTerm server is running use mTerm_client to connect to userver\n# otherwise fallback to the old method\n\nif mTerm_server_running; then\n  exec /usr/local/bin/mTerm_client wedge\nelse\n  start_sol_session\nfi\n", "num_lines": 53}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# YAMP get_fan : the fan configuration of YAMP is totally different \n# from Minipack (1x5 vs 2x4), therefore logic for reading fan RPM\n# is also very different, but the output of this function will be\n# of the same format as Minipack, so as to reuse the existing code\n# as much as possible\nusage() {\n    echo \"Usage: $0 [Fan Unit (1..5)]\" >&2\n}\n\nFCMCPLD=\"/sys/bus/i2c/drivers/fancpld/13-0060\"\n\nshow_pwm()\n{\n    pwm=\"$FCMCPLD/fan$1_pwm\"\n    val=$(cat $pwm | head -n 1)\n    # Val is [0,255], so let's scale the value down to [0,100]\n    float_val=$(echo \"$val 100 * 255 / p\" | dc)\n    rounded=`printf '%.*f' 0 $float_val`\n    echo \"$rounded%\"\n}\n\nshow_rpm()\n{\n    rpm=`cat $FCMCPLD/fan$1_input|head -n 1`\n    # Keep the output in the same format as Minipack\n    echo \"$rpm, $rpm\"\n}\n\nset -e\n\n# If user input is given, use it as FAN TRAY instance\n# Otherwise, read all\nif [ \"$#\" -eq 0 ]; then\n    FANS=\"1 2 3 4 5\"\nelif [ \"$#\" -eq 1 ]; then\n    if [ \"$1\" -le 0 ] || [ \"$1\" -ge 6 ]; then\n        echo \"Fan $1: Should be between 1 and 5\"\n        exit 1\n    fi\n    FANS=\"$1\"\nelse\n    usage\n    exit 1\nfi\n\n\nfor fan in $FANS; do\n    echo \"Fan $fan RPMs: $(show_rpm $fan), ($(show_pwm $fan))\"\ndone\n", "num_lines": 70}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/set_fan_speed.sh 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 36}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n# YAMP fan set utility for fscd.\n\nusage() {\n  echo \"Usage: $0 <PWM_PERCENT> [FAN_TRAY] \"\n  echo \"<PWM_PERCENT> : From 0 to 100 \"\n  echo \"[FAN_TRAY] : 1, 2, 3, 4 or 5.\"\n  echo \"If no FAN_TRAY is specified, all FANs will be programmed\"\n}\n\nset -e\n\n# Make sure we only have 1 or 2 arguments\nif [ \"$#\" -ne 2 ] && [ \"$#\" -ne 1 ]; then\n    usage\n    exit 1\nfi\n\n# Also make sure that percent value is really between 0 and 100\nif [ \"$1\" -lt 0 ] || [ \"$1\" -gt 100 ]; then\n    echo \"PWM_PERCENT $1: should be between 0 and 100\"\n    exit 1\nfi\n\n# Read FAN_TRAY value from user argument.\n# If no FAN_TRAY is given, configure all FANs\nif [ \"$#\" -eq 1 ]; then\n    FAN_UNIT=\"1 2 3 4 5\"\nelse\n    if [ \"$2\" -le 0 ] || [ \"$2\" -ge 6 ]; then\n        echo \"Fan $2: should be between 1 and 5\"\n        exit 1\n    fi\n    FAN_UNIT=\"$2\"\nfi\n\n# Convert the percentage to our 1/32th level (0-31).\n# The user input is given in percent (0-100),\n# but YAMP FANCPLD takes PWM as 8bit value (0-255)\n# So scale the value by multiplying 2.5\nfloat_step=$(echo \"$1 255 * 100 / p\" | dc)\nstep=`printf '%.*f' 0 $float_step`\n\nfor unit in ${FAN_UNIT}; do\n    pwm=\"/sys/bus/i2c/drivers/fancpld/13-0060/fan${unit}_pwm\"\n    echo \"$step\" > \"${pwm}\"\n    echo \"$step will be set to ${pwm} !!!!\"\n    echo \"Successfully set fan ${unit} speed to $1%\"\ndone\n", "num_lines": 69}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# shellcheck disable=SC1091\n# shellcheck disable=SC2012\n# shellcheck disable=SC2039\nsource /usr/local/bin/openbmc-utils.sh\n\ntrap cleanup INT TERM QUIT EXIT\n\nABOOT_CONF_START=$((0x9FA000))\nFLASH_SIZE=$((0x1000000))\nABOOT_CONF_SIZE=$((0x5000))\nSECTION_BLOCK_SIZE=$((0x1000))\n\n# Temp files for storing bios file.\nTEMP_BIOS_IMAGE=\"/tmp/tmp_bios_image\"\n# Temp file for storing aboot_conf data\nTEMP_ABOOT_CONF=\"/tmp/aboot_conf.bin\"\n\nDEFAULT_ABOOT_CONF=\"BOOT_METHOD1=IPV6_PXE,BOOT_METHOD2=LOCAL,BOOT_METHOD3=ARISTA\"\n\ncleanup() {\n    disconnect_spi\n    rm -f $TEMP_ABOOT_CONF $TEMP_BIOS_IMAGE\n}\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <OP> <bios file>\"\n    echo \"      <OP> : read, write, erase, recover\"\n    exit 1\n}\n\ndisconnect_spi() {\n    # connect through CPLD\n    echo 0x0 > \"${SUPCPLD_SYSFS_DIR}/bios_select\"\n}\n\nconnect_spi() {\n    # spi2 cs0\n    devmem_set_bit \"$(scu_addr 88)\" 26\n    devmem_set_bit \"$(scu_addr 88)\" 27\n    devmem_set_bit \"$(scu_addr 88)\" 28\n    devmem_set_bit \"$(scu_addr 88)\" 29\n\n    # connect through CPLD\n    echo 0x1 > \"${SUPCPLD_SYSFS_DIR}/bios_select\"\n}\n\n# Arista added a 3rd source, so this function is needed in case we are dealing with the 3rd source\ndo_retry(){\n  if [ \"$1\" = \"write\" ]; then\n    if ! flashrom --layout /etc/yamp_bios.layout --image header --image payload -p linux_spi:dev=/dev/spidev2.0 -w \"$2\"; then\n      echo \"flashrom without -c failed\"\n    fi\n  elif [ \"$1\" = \"erase\" ]; then\n    if ! flashrom -p linux_spi:dev=/dev/spidev2.0 -E; then\n       echo \"flashrom without -c option failed as well\"\n    fi\n  else # reading\n    if ! flashrom -p linux_spi:dev=/dev/spidev2.0 -r \"$2\"; then\n      echo \"flashrom without -c option failed\"\n    fi\n  fi\n}\n\ncreate_bios_image() {\n    start_block=\"$(($1 / SECTION_BLOCK_SIZE))\"\n    num_blocks=\"$(($2 / SECTION_BLOCK_SIZE))\"\n    rm -f \"$TEMP_BIOS_IMAGE\"\n    dd if=\"$3\" of=\"$TEMP_BIOS_IMAGE\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$start_block\" \\\n       2> /dev/null\n    dd if=\"$4\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$num_blocks\" >> \"$TEMP_BIOS_IMAGE\" \\\n       2> /dev/null\n    end_blocks=$(( (FLASH_SIZE / SECTION_BLOCK_SIZE) - start_block - num_blocks ))\n    dd if=\"$3\" bs=\"$SECTION_BLOCK_SIZE\" count=\"$end_blocks\" skip=$((start_block + num_blocks)) \\\n       >> \"$TEMP_BIOS_IMAGE\" 2> /dev/null\n}\n\ncreate_aboot_conf() {\n    echo \"Using Aboot conf: $1\"\n\n    nvs=\"$1,\"\n\n    rm -f \"$TEMP_ABOOT_CONF\"\n    touch \"$TEMP_ABOOT_CONF\"\n    while [ -n \"${nvs%%,*}\" ]; do\n        nv=\"${nvs%%,*}\"\n        name=\"${nv%%=*}\"\n        if [ \"$name\" == \"$nv\" ]; then\n            echo \"Invalid name-value argument $nv\" >&2\n            return 1\n        fi\n        echo -n \"${nv%%=*}=\" >> \"$TEMP_ABOOT_CONF\"\n        echo -n \"${nv#*=}\" | base64 >> \"$TEMP_ABOOT_CONF\"\n        nvs=\"${nvs#*,}\"\n    done\n\n    size=\"$(ls -l \"$TEMP_ABOOT_CONF\" | awk '{print $5}')\"\n    pad_size=\"$((ABOOT_CONF_SIZE - size))\"\n    dd if=/dev/zero bs=1 count=\"$pad_size\" >> \"$TEMP_ABOOT_CONF\" 2> /dev/null\n}\n\naboot_version() {\n    grep -a CONFIG_LOCALVERSION \"$1\" 2> /dev/null | awk -F'\"' '{print $2}'\n}\n\ndo_erase() {\n    # Layout is not supported in Erase. \n    # So we need to manually recover pdr (which include idprom) after erase.\n    if [ ! -e /mnt/data/header_pdr.data ]; then\n      backup_image\n    fi\n\n    # Do the erase\n    echo \"Erasing the flash\"\n    if ! flashrom -p linux_spi:dev=/dev/spidev2.0 -E -c \"MX25L12835F/MX25L12845E/MX25L12865E\"; then\n      echo \"flashrom failed. Retrying without -c\"\n      do_retry \"erase\" \n    fi\n    \n    # Recover header and pdr (which includes the idprom)\n    do_recover\n}\n\ndo_read() {\n    echo \"Reading flash content...\"\n    if ! flashrom -p linux_spi:dev=/dev/spidev2.0 -r \"$1\" -c \"MX25L12835F/MX25L12845E/MX25L12865E\"; then\n      echo \"flashrom failed. Retrying without -c\"\n      do_retry \"read\" \"$1\"\n    fi\n}\n\nbackup_image(){\n    echo \"Backing up pdr\"\n\n    # Get complete image\n    if ! tempfile=$(mktemp); then\n      echo \"Running mktemp in backup_image failed\"\n      exit 1\n    fi\n    \n    # /mnt/data should always exist\n    if [ ! -d /mnt/data ]; then\n      echo \"Partition /mnt/data doesn't exist\"\n      exit 1\n    fi\n    \n    # Create /mnt/data fixed name which will be used to recover later\n    header_pdr_file=\"/mnt/data/header_pdr.data\"\n\n    if ! flashrom -p linux_spi:dev=/dev/spidev2.0 -r \"${tempfile}\" -c \"MX25L12835F/MX25L12845E/MX25L12865E\"; then\n      echo \"Flashrom failed. Retrying without -c\"\n      do_retry \"read\" \"${tempfile}\"\n    fi\n\n    # Make sure data is fully read\n    datasize=$(stat -c%s \"${tempfile}\")\n    if [ \"${datasize}\" -lt \"${FLASH_SIZE}\" ]; then\n       echo \"Unable to store all the data. Will not erase SPI\"\n       rm \"${tempfile}\"\n       exit 1\n    fi \n    \n    # saving header, and pdr.\n    # conv option not available in bmc busybox dd (can't do conv=nosync to prevent file from being truncated), so saving header as well.\n    # we are backing from 00000000 to 00020fff which is 18 bits total. so we will use 9 bits for bs and 9 bits for count to get to the needed regions.\n    if ! /bin/dd if=\"${tempfile}\" of=\"${header_pdr_file}\" bs=512 count=512; then\n      echo \"Running dd in backup_image failed\"\n      exit 1\n    fi\n    \n    # The full image is no longer needed, so removed it\n    rm \"${tempfile}\"\n\n}\n\ndo_write() {\n    bios_image=\"$1\"\n    if [ -n \"$(aboot_version \"$bios_image\")\" ]; then\n        create_aboot_conf \"$DEFAULT_ABOOT_CONF\" || exit 1\n        create_bios_image \"$ABOOT_CONF_START\" \"$ABOOT_CONF_SIZE\" \\\n                          \"$bios_image\" \"$TEMP_ABOOT_CONF\" || exit 1\n        bios_image=\"$TEMP_BIOS_IMAGE\"\n    fi\n\n    if [ ! -e /mnt/data/header_pdr.data ]; then\n      backup_image\n    fi\n    echo \" writing header and payload ... \"\n    if ! flashrom --layout /etc/yamp_bios.layout --image header --image payload -p linux_spi:dev=/dev/spidev2.0 -w \"$bios_image\" -c \"MX25L12835F/MX25L12845E/MX25L12865E\"; then\n      echo \"flashrom failed. Retrying without -c\"\n      do_retry \"write\" \"$bios_image\"\n    fi\n}\n\ndo_recover() {\n  echo \"Recovering PDR region\"\n  if [ ! -e /mnt/data/header_pdr.data ]; then\n    echo \"recovery data /mnt/data/header_pdr.data doesn't exist. Exiting ...\"\n    exit 1\n  fi\n\n  # Getting full image ready. Image must be the same as original size\n  if ! file=$(mktemp); then\n    echo \"Running mktemp in do_recover failed\"\n    exit 1\n  fi\n  cp /mnt/data/header_pdr.data \"${file}\"\n\n  # So we have 16515072 bytes left which we will pad with zero so that we can get to the flashsize which is 16777216 bytes\n  # Therefore, we will use a bs of 512 with a 32256 as count\n  if ! /bin/dd if=/dev/zero bs=512 count=32256 >> \"${file}\"; then\n    echo \"Running dd in do_recover failed\"\n    exit 1\n  fi\n\n  #Recover pdr region which includes the idprom region\n  if ! flashrom --layout /etc/yamp_bios.layout --image header --image pdr -p linux_spi:dev=/dev/spidev2.0 -w \"${file}\" -c \"MX25L12835F/MX25L12845E/MX25L12865E\"; then\n    echo \"flashrom failed. Retrying without the -c\"\n    do_retry \"write\" \"${file}\"\n  fi\n  rm \"${file}\"\n}\n\nconnect_spi\n\nif [ \"$1\" == \"erase\" ]; then\n    do_erase\nelif [ \"$1\" == \"read\" ]; then\n    do_read \"$2\"\nelif [ \"$1\" == \"write\" ]; then\n    do_write \"$2\"\nelif [ \"${1}\" == \"recover\" ]; then\n    do_recover\nelse\n    usage\nfi\n\n", "num_lines": 241}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2018-present Facebook. All Rights Reserved.\n\nSUPCPLD_SYSFS_DIR=\"/sys/bus/i2c/devices/12-0043\"\nSCDCPLD_SYSFS_DIR=\"/sys/bus/i2c/devices/4-0023\"\nSUP_PWR_ON_SYSFS=\"${SUPCPLD_SYSFS_DIR}/cpu_control\"\nPWR_SYSTEM_SYSFS=\"${SUPCPLD_SYSFS_DIR}/chassis_power_cycle\"\nSCD_TH3_RST_ON_SYSFS=\"${SCDCPLD_SYSFS_DIR}/th3_reset\"\nSCD_TH3_PCI_RST_ON_SYSFS=\"${SCDCPLD_SYSFS_DIR}/th3_pci_reset\"\nSCD_RST=\"${SCDCPLD_SYSFS_DIR}/scd_reset\"\nLC_SMB_MUX_RST=\"${SCDCPLD_SYSFS_DIR}/lc_smb_mux_rst\"\n\nwedge_iso_buf_enable() {\n    return 0\n}\n\nwedge_iso_buf_disable() {\n    return 0\n}\n\nwedge_is_us_on() {\n    local val\n    val=$(cat $SUP_PWR_ON_SYSFS 2> /dev/null | head -n 1)\n    if [ -z \"$val\" ]; then\n        return $default\n    elif [ \"$val\" == \"0x1\" ]; then\n        return 0            # powered on\n    else\n        return 1\n    fi\n}\n\nwedge_board_type() {\n    echo 'YAMP'\n}\n\nwedge_slot_id() {\n    printf \"1\\n\"\n}\n\nwedge_board_rev() {\n    # assume P2\n    return 2\n}\n\n# Should we enable OOB interface or not\nwedge_should_enable_oob() {\n    # YAMP uses BMC MAC since beginning\n    return 1\n}\n\nwedge_power_off_asic() {\n    # It is not exact power off.\n    # Instead, the ASIC is kept in reset in this case.\n    echo 1 > $SCD_TH3_RST_ON_SYSFS\n    echo 1 > $SCD_RST\n    sleep 1\n    echo 1 > $SCD_TH3_PCI_RST_ON_SYSFS\n}\n\nwedge_power_on_asic() {\n    # Order matters here\n    echo 0 > $SCD_TH3_RST_ON_SYSFS\n    echo 0 > $SCD_RST\n    usleep 250000\n    echo 0 > $SCD_TH3_PCI_RST_ON_SYSFS\n}\n\nwedge_power_on_board() {\n    # Order matters here\n    echo 1 > $SUP_PWR_ON_SYSFS\n    sleep 1\n    wedge_power_off_asic\n    sleep 1\n    wedge_power_on_asic\n    sleep 1\n}\n\nwedge_power_off_board() {\n    # Order matters here\n    echo 0 > $SUP_PWR_ON_SYSFS\n    sleep 1\n    wedge_power_off_asic\n    sleep 1\n}\n", "num_lines": 87}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\ndpm_path=\"/sys/bus/i2c/drivers/ucd9000/3-004e\"\nlogfile=\"/mnt/data1/log/dpm_log\"\nlogfile_old=\"${logfile}.1\"\nmax_loglines=1000\n\ntrap cleanup INT TERM QUIT EXIT\n\nREBIND=false\n\nif [ -d \"$dpm_path\" ]; then\n    REBIND=true\n    echo \"# Unbinding SWITCHCARD DPM from ucd9000 driver\"\n    echo \"3-004e\" > /sys/bus/i2c/drivers/ucd9000/unbind\nfi\n\n# Check to see if the log file needs to be rotated\ntouch $logfile $logfile_old\nlines=\"$(wc -l $logfile|cut -d' ' -f1)\"\nif [ \"$lines\" -gt $max_loglines ]\nthen\n    echo \"Rotating DPM log file\"\n    rm -f \"$logfile_old\"\n    cp \"$logfile\" \"$logfile_old\"\n    rm -f \"$logfile\"\nfi\n\necho \"Reading DPM logs...\"\n\nlog=''\nlog=\"$log{'Date':'$(date -u \"+%Y-%m-%d %T\")'\"\nlog=\"$log,'Log':'$(i2cget -y 3 0x4e 0xea i | tail -n 1)'\"\n\neb=\"$(i2cget -y 3 0x4e 0xeb w)\"\n\nlen=\"${eb:2:2}\"\n\nfor (( i = 0 ; i < \"$len\" ; i++ ))\ndo\n  i2cset -y 3 0x4e 0xeb 0x\"$len\"\"$(printf '%02x' \"$i\")\" w\n  man=\"$(i2cget -y 3 0x4e 0xec i | tail -n 1)\"\n  exp=\"$(i2cget -y 3 0x4e 0x20 | tail -n 1)\"\n  log=\"$log,'detail_$i':{'m':'$man','e':'$exp'}\"\ndone\n\nlog=\"$log}\"\n\necho \"$log\" >> \"$logfile\"\n\necho \"Clearing DPM logs...\"\ni2cset -y 3 0x4e 0xea 0 0 0 0 0 0 0 0 0 0 0 0 0 0 s\n\ncleanup() {\n    if [ \"$REBIND\" = true ]; then\n        echo \"# Re-Binding SWITCHCARD DPM to ucd9000 driver\"\n        echo \"3-004e\" > /sys/bus/i2c/drivers/ucd9000/bind\n    fi\n}\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n. /usr/local/bin/openbmc-utils.sh\n\nshow_dps_ver() {\n  name=$1\n  bus=$2\n  addr=$3\n  drvload=$4\n  if [ $drvload -eq 1 ]; then\n     i2c_device_delete $bus $addr\n     sleep 1\n  fi\n  dump=`i2cdump -y ${bus} ${addr} s 0x9e |grep -v abcdef`\n  dps_ver=`echo ${dump##* }`\n  echo $name $dps_ver\n  if [ $drvload -eq 1 ]; then\n     i2c_device_add $bus $addr ucd90120\n  fi\n}\necho \"!!!\"\necho \"!!! WARNING: Displaying DSP version will disrupt sensor reading !!!\"\necho \"!!!\"\nshow_dps_ver \"SUP.:\" 9 0x11 0\nshow_dps_ver \"SCD.:\" 3 0x4e 1\nshow_dps_ver \"PIM1:\" 14 0x4e 1\nshow_dps_ver \"PIM2:\" 15 0x4e 1\nshow_dps_ver \"PIM3:\" 16 0x4e 1\nshow_dps_ver \"PIM4:\" 17 0x4e 1\nshow_dps_ver \"PIM5:\" 18 0x4e 1\nshow_dps_ver \"PIM6:\" 19 0x4e 1\nshow_dps_ver \"PIM7:\" 20 0x4e 1\nshow_dps_ver \"PIM8:\" 21 0x4e 1\necho \"!!! Done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nfor index in 1 2 3 4 5 6 7 8\ndo\n    cache_file=\"/tmp/pim${index}_serial.txt\"\n\n    if [ ! -s \"$cache_file\" ] || [ -z \"$(cat $cache_file)\" ]; then\n        /usr/bin/weutil lc${index} |grep Product|grep Serial|cut -d ' ' -f 4 > \"$cache_file\"\n    fi\n    serial=\"$(cat $cache_file)\"\n    echo PIM${index} : ${serial}\ndone\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n#\n# FIXME restart eth0 interface to refresh ipv6 link-local address. The\n# workaround is needed for yamp mainly because ipv6 link-local address\n# might be derived from the \"random\" mac address which leads to DHCP\n# request failures.\n#\n# Below explains why the problem happens. We are still investigating the\n# official fix, which most likely goes to kernel space.\n#   1) when \"ftgmac100\" driver is binded to BMC's MAC Controller, the\n#      controller is assigned with a \"random\" MAC address.\n#   2) later when \"/etc/init.d/networking start\" is executed for the first\n#      time, \"ftgmac100\" driver starts to communicate with (Broadcom) NCSI\n#      NIC, including issuing \"GET_MAC_ADDR\" command to NCSI NIC.\n#   3) given ftgmac100->ndo_open() and NCSI command-handling are running\n#      asynchronously, BMC's ipv6 link-local address is \"undefined\": it may\n#      be derived from the \"random\" mac address, or the permanent one (from\n#      NCSI NIC), depending on which task (ipv6 link-local address generation\n#      or handling \"GET_DMA_ADDR\" response from NCSI NIC) happens first.\n#   4) If unfortunately random MAC is used (which happens most times), DHCP\n#      server will ignore BMC's DHCP request due to UUID mismatch.\n#\n# Note:\n#   1) the workaround is not needed by kernel 4.1 because ftgmac100->ndo_open\n#      won't return until \"GET_MAC_ADDR\" NSCI command is handled.\n#\nKERNEL_VERSION=`uname -r`\nif [[ ${KERNEL_VERSION} != 4.1.* ]]; then\n  echo \"fixup eth0 interface..\"\n  sleep 1\n  ifdown eth0\n  ifup eth0\nfi\n\n# set the MAC from ifconfig back to u-boot environment so that u-boot\n# can use it\nmac=$(ifconfig eth0  |grep HWaddr  |awk '{ print $5 }')\nethaddr=$(fw_printenv ethaddr  | cut -d'=' -f2 )\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nsource /usr/local/bin/openbmc-utils.sh\n\nCPLD_JTAG_SEL_L=\"CPLD_JTAG_SEL_L\"\nJTAG_EN=\"${SUPCPLD_SYSFS_DIR}/jtag_en\"\nJTAG_SEL=\"${SUPCPLD_SYSFS_DIR}/jtag_sel\"\nJTAG_LC_FAN_CTRL=\"${SCDCPLD_SYSFS_DIR}/jtag_ctrl\"\nJTAG_FAN_WP=\"${SCDCPLD_SYSFS_DIR}/fancpld_wp\"\n\nLINECARD=0\n\nSUP_PROGRAM=false\nSCD_PROGRAM=false\n\ntrap disconnect_jtag INT TERM QUIT EXIT\n\nusage() {\n    program=$(basename \"$0\")\n    echo \"Usage:\"\n    echo \"$program <fpga> <action> <fpga file>\"\n    echo \"      <fpga> : sup, scd, lc1, lc2, ..., lc8, fan\"\n    echo \"      <action> : program, verify\"\n    exit 1\n}\n\ndisconnect_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    if [ \"$SUP_PROGRAM\" = false ]; then\n        echo 0 > \"$JTAG_EN\"\n        echo 0 > \"$JTAG_SEL\"\n    fi\n    if [ \"$SCD_PROGRAM\" = false ]; then\n        # enable fancpld write protection\n        echo 1 > \"$JTAG_FAN_WP\"\n        # do not select any linecard or fan\n        echo 0x0 > \"$JTAG_LC_FAN_CTRL\"\n    fi\n    if [ $LINECARD -ne 0 ]; then\n        # cycle the linecard FPGA\n        gpio_set_value LC${LINECARD}_FAST_JTAG_EN 0\n        gpio_set_value LC${LINECARD}_SCD_CONFIG_L 0\n        sleep 1\n        gpio_set_value LC${LINECARD}_SCD_CONFIG_L 1\n    fi\n}\n\nconnect_scd_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 1 > \"$JTAG_SEL\"\n}\n\nconnect_sup_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 0\n    echo 0 > \"$JTAG_EN\"\n}\n\nconnect_linecard_jtag() {\n    lc=$1\n    LINECARD=${lc}\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 0 > \"$JTAG_SEL\"\n    # choose correct LC\n    echo \"${lc}\" > \"$JTAG_LC_FAN_CTRL\"\n    gpio_set_value LC\"${lc}\"_FAST_JTAG_EN 1\n}\n\nconnect_fan_jtag() {\n    gpio_set_value $CPLD_JTAG_SEL_L 1\n    echo 1 > \"$JTAG_EN\"\n    echo 0 > \"$JTAG_SEL\"\n    echo 0xa > \"$JTAG_LC_FAN_CTRL\"\n}\n\ndo_scd() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*scd\" \"$2\" > /dev/null; then\n        echo \"$2 is not a vaild SCD FPGA file\"\n        exit 1\n    fi\n    SCD_PROGRAM=true\n    connect_scd_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl RUN_CYCLE\n}\n\ndo_sup() {\n    # verify the fpga file\n    if ! grep \"DESIGN.*son\" \"$2\" > /dev/null; then\n        echo \"$2 is not a vaild SUP FPGA file\"\n        exit 1\n    fi\n    SUP_PROGRAM=true\n    connect_sup_jtag\n    jam -l/usr/lib/libcpldupdate_dll_ioctl.so -v -a\"${1^^}\" \"$2\" \\\n      --ioctl RUN_CYCLE\n}\n\ndo_fan() {\n    echo \"Fan CPLD upgrade is not supported\"\n    exit 1\n}\n\ndo_linecard() {\n    lc=\"$1\"\n    action=\"${2,,}\"\n\n    if [ \"$action\" != \"program\" ]; then\n        echo \"Only 'program' action is supported for linecard\"\n        exit 1\n    fi\n\n    if [ ${#lc} -ne 3 ]; then\n        echo \"'$lc' is not a valid linecard. Expect 'lc1', 'lc2', ..., 'lc8'\"\n        exit 1\n    fi\n\n    lc=${lc:2:1}\n    if [[ $lc -lt 1 || $lc -gt 8 ]]; then\n        echo \"'$lc' is not a valid linecard. Expect 'lc1', 'lc2', ..., 'lc8'\"\n        exit 1\n    fi\n\n    connect_linecard_jtag \"$lc\"\n\n    xapp -l /usr/lib/libcpldupdate_dll_ast_jtag.so \"$3\"\n}\n\nif [ $# -ne 3 ]; then\n    usage\nfi\n\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n  modprobe ast_jtag\nfi\n\nif [ \"$1\" = \"scd\" ]; then\n    shift 1\n    do_scd \"$@\"\nelif [ \"$1\" = \"sup\" ]; then\n    shift 1\n    do_sup \"$@\"\nelif [ \"$1\" = \"fan\" ]; then\n    shift 1\n    do_fan \"$@\"\nelif [[ \"$1\" = \"lc\"* ]]; then\n    do_linecard \"$@\"\nelse\n    usage\nfi\n", "num_lines": 153}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nsource /usr/local/bin/openbmc-utils.sh\n\nmaj_ver=\"cpld_ver_major\"\nmin_ver=\"cpld_ver_minor\"\nexitCode=0\n\necho \"------SUP-FPGA------\"\n\nif [ ! -d $SUPCPLD_SYSFS_DIR ]; then\n    echo \"SUP FPGA is not detected\"\nelse\n    val_major=$(head -n 1 $SUPCPLD_SYSFS_DIR/$maj_ver)\n    val_minor=$(head -n 1 $SUPCPLD_SYSFS_DIR/$min_ver)\n    echo \"SUP_FPGA: $(($val_major)).$(($val_minor))\"\nfi\n\necho \"------SCD-FPGA------\"\nif [ ! -d $SCDCPLD_SYSFS_DIR ]; then\n    echo \"SCD FPGA is not detected\"\n    echo \"Unable to retrieve PIM FPGA versions eihter\"\nelse\n    val_major=$(head -n 1 $SCDCPLD_SYSFS_DIR/$maj_ver)\n    val_minor=$(head -n 1 $SCDCPLD_SYSFS_DIR/$min_ver)\n    echo \"SCD_FPGA: $(($val_major)).$(($val_minor))\"\n\n    echo \"------PIM-FPGA------\"\n    pim_list=\"1 2 3 4 5 6 7 8\"\n    for pim in ${pim_list}; do\n      pim_maj_ver_file=\"lc${pim}_fpga_rev_major\"\n      pim_min_ver_file=\"lc${pim}_fpga_rev_minor\"\n      val1=$(head -n 1 $SCDCPLD_SYSFS_DIR/$pim_maj_ver_file)\n      val2=$(head -n 1 $SCDCPLD_SYSFS_DIR/$pim_min_ver_file)\n      if [ \"$((val1))\" -eq 255 ]; then\n        # Print all the PIM status then exit\n        echo \"PIM $pim: NOT DETECTED\"\n        exitCode=1\n      else\n        # val1 can never be 0 under normal operation\n        # so let's set the exitCode to 1 in case val1\n        # is 0\n        if [ \"$((val1))\" -eq 0 ]; then\n          exitCode=1\n        fi\n        echo \"PIM $pim : $((val1)).$((val2))\"\n      fi\n    done\nfi\n\nif [ \"$exitCode\" -ne 0 ]; then\n    echo \"Since all the PIMs detection didn't succeed as listed above... exiting\"\n    exit 1\nfi\n", "num_lines": 73}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n# This script will wake up every 10 seconds and do the following\n#    1. Try to discover any new PIM(s) plugged in\n#    2. For all discovered PIMs, attempt to turn on the PIM and\n#       the gearbox chip on it\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\npim_list=$(seq 0 7)\npim_found=(0 0 0 0 0 0 0 0)\npim_bus=(14 15 16 17 18 19 20 21)\npca_addr=20\n\ncreate_pim_gpio() {\n  local base lc\n  lc=$1\n  chip=$2\n\n  if [ -e LC${lc}_STATUS_GREEN_L ]; then\n      # already created GPIOs for such pim\n      return\n  fi\n\n  gpio_export_by_offset ${chip} 1 LC${lc}_DPM_POWER_UP\n  gpio_export_by_offset ${chip} 4 LC${lc}_SCD_RESET_L\n  gpio_export_by_offset ${chip} 5 LC${lc}_SCD_CONFIG_L\n  gpio_export_by_offset ${chip} 6 LC${lc}_SATELLITE_PROG\n  gpio_export_by_offset ${chip} 7 LC${lc}_LC_PWR_CYC\n  gpio_export_by_offset ${chip} 8 LC${lc}_BAB_SYS_RESET_L\n  gpio_export_by_offset ${chip} $((8 + 5)) LC${lc}_FAST_JTAG_EN\n  gpio_export_by_offset ${chip} $((8 + 6)) LC${lc}_STATUS_RED_L\n  gpio_export_by_offset ${chip} $((8 + 7)) LC${lc}_STATUS_GREEN_L\n  logger pim_enable: registered PIM${lc} with GPIO chip ${chip}\n}\n\npower_on_pim() {\n  local lc old ver\n  lc=$1\n  old=$(gpio_get LC${lc}_DPM_POWER_UP keepdirection)\n  if [ $old -eq 1 ]; then\n      # already powered on, skip\n      return\n  fi\n  gpio_set LC${lc}_DPM_POWER_UP 1 # all power on\n  sleep 1\n  gpio_set LC${lc}_SCD_RESET_L 1     # scd out of reset\n  gpio_set LC${lc}_SCD_CONFIG_L 1    # scd not in config\n  gpio_set LC${lc}_BAB_SYS_RESET_L 1 # gearbox out of reset\n  # If linecard FPGA version is before v6, need to set SATELLITE_PROG to 0.\n  # Otherwise, need to set it to 1.\n  # However, the reading of the linecard FPGA version is not reliable,\n  # we will set SATELLITE_PROG to 1 at all time, assuming the linecard FPGA\n  # is upgraded to the latest.\n  gpio_set LC${lc}_SATELLITE_PROG 1\n  gpio_set LC${lc}_STATUS_RED_L 1 # turn off red\n  gpio_set LC${lc}_STATUS_GREEN_L 0 # turn on green\n  logger pim_enbale: powered on PIM${lc}\n}\n\n#clear pimserial endpoint cache if pim doesn't exist but the pimserial file does.\nclear_pimserial_cache(){\n  for i in \"${pim_list[@]}\"\n  do\n    pimserial_number=\"${1}\"\n    pimserial_path=\"$SCDCPLD_SYSFS_DIR/lc${pimserial_number}_prsnt_sta\"\n    pimserial_present=\"$(cat ${pimserial_path} 2> /dev/null | head -n 1)\"\n    pimserial_cache_path=/tmp/pim${pimserial_number}_serial.txt\n    \n    if [ \"${pimserial_present}\" == 0x0 ] && [ -f \"${pimserial_cache_path}\" ]; then\n      #pim device doesn't exist but pimserial cache txt file exist, so remove it.\n      rm -rf \"${pimserial_cache_path}\"\n    fi\n  done\n}\n\nwhile true; do\n  # 1. For any uncovered PIM, try to discover\n  for i in ${pim_list[@]}\n  do\n    if [ \"${pim_found[$i]}\" -eq \"0\" ]; then\n      pim_number=$(expr $i + 1)\n      pim_addr=${pim_bus[$i]}-00$pca_addr  # 14-0020 for example\n      # Check if Switch card senses the PIM presence\n      pim_path=\"$SCDCPLD_SYSFS_DIR/lc${pim_number}_prsnt_sta\"\n      pim_present=`cat $pim_path 2> /dev/null | head -n 1`\n      # There is a HW bug which makes pim presence unreliable.\n      #if [ \"$pim_present\" == \"0x1\" ]; then\n      if true; then\n         dev_path=/sys/bus/i2c/devices/$pim_addr\n         drv_path=/sys/bus/i2c/drivers/pca953x/$pim_addr\n         if [ ! -e $drv_path ]; then\n           # Driver doesn't exist\n           if [ -e $dev_path ]; then\n              # Device exists. Meaning previous probe failed. Clean up previous failure first\n              i2c_device_delete ${pim_bus[$i]} 0x$pca_addr\n              # Give some time to kernel\n              sleep 1\n           fi\n           # Probe this device\n           reg0_val=`i2cget -y ${pim_bus[$i]} 0x$pca_addr 0 2>&1`\n           if [[ ! \"$reg0_val\" == *\"Error\"* ]]; then\n              i2c_device_add ${pim_bus[$i]} 0x$pca_addr pca9555\n           fi\n         fi\n         # Check if device was probed and driver was installed\n         if [ -e $drv_path/gpio ]; then\n           create_pim_gpio $((i+1)) ${pim_addr}\n           pim_found[$i]=1\n         fi\n      fi\n    fi\n  done\n  # 2. For discovered gpios, try turning it on\n  for i in ${pim_list[@]}\n  do\n    if [ \"${pim_found[$i]}\" -eq \"1\" ]; then\n       power_on_pim $((i + 1))\n    fi\n    \n    #clear pimserial endpoint cache\n    clear_pimserial_cache $((i+1))\n\n\n  done\n  # Sleep 5 seconds until the next loop.\n  # reduce to 5 seconds for faster scan.\n  sleep 5\ndone\n", "num_lines": 148}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# Power-on script now includes TH3 toggle.That is, when BMC is booting up\n# while TH3 is already running, it should not blindly toggle reset TH3.\n# Otherwise (if we blindly toggle reset TH3), BMC upgrade will become \n# disruptive upgrade. Therefore we will run board power up sequence only \n# if CPU is currently turned off.\nif wedge_is_us_on; then\n    echo \"uServer is already up. Skipping board power-on sequence\"\nelse\n    echo \"uServer is not up. Running board power-on sequence\"\n    wedge_power_on_board\nfi\n\n# Now, double check if power is on, and do forced power up ad needed.\necho  \"Checking microserver power status ... \"\nif wedge_is_us_on; then\n    echo \"on\"\n    on=1\nelse\n    echo \"off\"\n    on=0\nfi\n\nif [ $on -eq 0 ]; then\n    # Power on now\n    echo \"uServer still not up. Running forced power-up sequence\"\n    wedge_power.sh on -f\nfi\n\npim_enable.sh > /dev/null 2>&1 &\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nlogger \"Power off TH3\"\necho \"Power off TH3\"\nwedge_power_off_asic\nsleep 1\nlogger \"Power on TH3\"\necho \"Power on TH3\"\nwedge_power_on_asic\nsleep 1\n", "num_lines": 31}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup_board.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup the board\n### END INIT INFO\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# TODO: Light up sys led\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n. /usr/local/bin/openbmc-utils.sh\n\n# First, we will Enable write in WRITE_PROTECT(0x10) reg before adding the i2c\n# pmbus device for dps1900. This will prevent some sysfs node from disappearing\n# when we powercycle\ni2c_dsp1900_create(){\n  if ! i2cset -f -y \"$1\" 0x58 0x10 0; then\n    echo \"Fail to clear PSU pmbus WRITE_PROTECT(0x10) register\"\n  fi\n  i2c_device_add \"$1\" 0x58 pmbus\n}\n\n# if applicable, saved the debug log for ir35223\nir35223_dbg_log(){\n  log_data=(\"${!1}\")\n  if [ ${#log_data[@]} != 0 ]; then\n    touch /var/log/failed_ir35223_log.txt\n    for cmd in \"${log_data[@]}\"\n    do\n      echo \"${cmd}\" >> /var/log/failed_ir35223_log.txt;\n    done\n  fi\n}\n\n# There are some registers that need to be initialized in IR35223\n# prior to loading PMBus module for yamp devices\ni2c_ir35223_init(){\n  # Array to hold failed data\n  declare -a failed_ir35223_cmds\n\n  # Step 1:0x005C [15:0] = 0x0102\n  if ! i2cset -y 3 0x12 0xff 0x00; then\n    failed_ir35223_cmds+=(\"Running i2cset -y 3 0x12 0xff 0x00 failed\")\n  fi\n  if ! i2cset -y 3 0x12 0x5c 0x0102 w; then \n    failed_ir35223_cmds+=(\"Running i2cset -y 3 0x12 0x5c 0x0102 w failed\")\n  fi\n\n  # Step 2: 0x043A [7:4] = 0xD\n  if ! i2cset -y 3 0x12 0xff 0x04; then\n    echo \"Running i2cset -y 3 0x12 0xff 0x04 failed\"\n  fi\n  if ! i2cset -y -m 0xf0 3 0x12 0x3a 0xd0; then \n    echo \"Running i2cset -y -m 0xf0 3 0x12 0x3a 0xd0 failed\"\n  fi\n\n  # Step 3: 0x0040 [7:0] = 0xFF\n  if ! i2cset -y 3 0x12 0xff 0x00; then\n    echo \"Running i2cset -y 3 0x12 0xff 0x00 failed\"\n  fi\n  if ! i2cset -y 3 0x12 0x40 0xff; then\n    echo \"Running i2cset -y 3 0x12 0x40 0xff failed\"\n  fi\n\n  # Step 4: 0x0428 [3:0] = 0x2\n  if ! i2cset -y 3 0x12 0xff 0x04; then\n    echo \"Running i2cset -y 3 0x12 0xff 0x04 failed\"\n  fi\n  if ! i2cset -y -m 0x0f 3 0x12 0x28 0x02; then\n    echo \"Running i2cset -y -m 0x0f 3 0x12 0x28 0x02\"\n  fi\n\n  # Step 5: 0x042E [5:0] = 0x0D\n  if ! i2cset -y 3 0x12 0xff 0x04; then\n    echo \"Running i2cset -y 3 0x12 0xff 0x04\"\n  fi\n  if ! i2cset -y -m 0x1f 3 0x12 0x2e 0x0d; then\n    echo \"i2cset -y -m 0x1f 3 0x12 0x2e 0x0d failed\"\n  fi\n\n  # Step 6: 0x0444 [7:7] = 0x1\n  if ! i2cset -y 3 0x12 0xff 0x04; then\n    echo \"Running i2cset -y -m 0x1f 3 0x12 0x2e 0x0d failed\"\n  fi\n  if ! i2cset -y -m 0x80 3 0x12 0x44 0x80; then\n    echo \"Running i2cset -y -m 0x80 3 0x12 0x44 0x80 failed\"\n  fi\n\n  # Step 7: Set Page back to 0\n  if ! i2cset -y 3 0x12 0xff 0x00; then\n    echo \"i2cset -y 3 0x12 0xff 0x00\"\n  fi\n\n  # Saved debug log\n  ir35223_dbg_log failed_ir35223_cmds[@]\n}\n\n# First, take TPM out of reset, so that we can probe it later\n# Active low - 1 means out of reset, 0 means in reset\ngpio_set TPM_RST_N 1\n\n# Probe the devices used by fscd first, just in case probing \n# taking too long, when one of modules are not in good shape.\n# 1. Probe SUP Inlet1/2 sensor, used for fscd \ni2c_device_add 11 0x4c max6658\n# 2. Probe TH3 temp sensor, also used for fscd\ni2c_device_add 4 0x4d max6581\n\n# Bus  0 - SMBus 1\ni2c_device_add 0 0x20 tpm_i2c_infineon\n\n# Bus  1 - SMBus 2\ni2c_device_add 1 0x50 supsfp\n\n# Bus  3 - SMBus 4 - SCB ECB/VRD and sensors\ni2c_device_add 3 0x40 pmbus\ni2c_device_add 3 0x41 pmbus\ni2c_device_add 3 0x4e ucd90120\ni2c_ir35223_init\ni2c_device_add 3 0x42 pmbus\ni2c_device_add 3 0x44 pmbus\n\n# Bus  4 - SMBus 5 SCD\ni2c_device_add 4 0x23 scdcpld\ni2c_device_add 4 0x50 24c512\n\n#\n# Bus  2 - SMBus 3 - LC, MUXED as Bus 14-21\n#\n# Note:\n#  1) 2-0075 may not be created if yamp is running an older kernel, so\n#     let's check and create the device if needed.\n#  2) if 2-0075 is already created (in device tree) but driver binding\n#     failed, then we will need to bind the driver manually. The failure\n#     usually happens when the chassis is power cycled, because 2-0075\n#     cannot be detected until it's taken out of reset (by writing scdcpld\n#     register LC_SMB_MUX_RST).\n#\necho 0 > \"$LC_SMB_MUX_RST\"  # take the mux (2-0075) out of reset\n\nSMB_MUX_DEV=\"2-0075\"\nSMB_MUX_PATH=$(i2c_device_sysfs_abspath \"$SMB_MUX_DEV\")\nif [ ! -d \"$SMB_MUX_PATH\" ]; then\n    i2c_mux_add_sync 2 0x75 pca9548 8\nelif [ ! -L \"${SMB_MUX_PATH}/driver\" ]; then\n    mux_driver=\"pca954x\"\n    echo \"Manually bind $mux_driver to $SMB_MUX_DEV..\"\n    i2c_bind_driver \"$mux_driver\" \"$SMB_MUX_DEV\"\n\n    # Wait till all the 8 channels (0-7) are populated; otherwise devices\n    # behind the switch cannot be created.\n    MUX_RETRY=0\n    until [ -d \"${SMB_MUX_PATH}/channel-7\" ]; do\n        usleep 10000 # sleep for 10 milliseconds\n        MUX_RETRY=$((MUX_RETRY + 1))\n        if [ \"$MUX_RETRY\" -gt 3 ]; then\n            break\n        fi\n    done\nfi\n\n# Bus  5 - SMBus 6 PSU1\ni2c_dsp1900_create 5\n\n# For now, we assume that PSU2 and PSU3 are not present\n#i2c_device_add 6 0x58 pmbus\n#i2c_device_add 7 0x58 pmbus\n\n# Bus  8 - SMBus 9 PSU4\ni2c_dsp1900_create 8\n\n# Bus  9 - SMBus 10 SUP DPM\n#i2c_device_add 9 0x11 pmbus\n\n# Bus  10 - SMBus 11 SUP POWER\ni2c_device_add 10 0x21 cpupwr\ni2c_device_add 10 0x27 mempwr\n\n# Bus  11 - SMBus 12 SUP TEMP\ni2c_device_add 11 0x40 pmbus\n\n# Bus  12 - SMBus 13 SUP CPLD\ni2c_device_add 12 0x43 supcpld\n\n# Bus  13 - SMBus 14 FAN CTRL\ni2c_device_add 13 0x4c max6658\ni2c_device_add 13 0x52 24c512\ni2c_device_add 13 0x60 fancpld\n\n# Bus  14 - Muxed LC1\ni2c_device_add 14 0x4e ucd90120\ni2c_device_add 14 0x42 pmbus\ni2c_device_add 14 0x20 pca9555\ni2c_device_add 14 0x4c max6658\ni2c_device_add 14 0x50 24c512\n\n# Bus  15 - Muxed LC2\ni2c_device_add 15 0x4e ucd90120\ni2c_device_add 15 0x42 pmbus\ni2c_device_add 15 0x20 pca9555\ni2c_device_add 15 0x4c max6658\ni2c_device_add 15 0x50 24c512\n\n# Bus  16 - Muxed LC3\ni2c_device_add 16 0x4e ucd90120\ni2c_device_add 16 0x42 pmbus\ni2c_device_add 16 0x20 pca9555\ni2c_device_add 16 0x4c max6658\ni2c_device_add 16 0x50 24c512\n\n# Bus  17 - Muxed LC4\ni2c_device_add 17 0x4e ucd90120\ni2c_device_add 17 0x42 pmbus\ni2c_device_add 17 0x20 pca9555\ni2c_device_add 17 0x4c max6658\ni2c_device_add 17 0x50 24c512\n\n# Bus  18 - Muxed LC5\ni2c_device_add 18 0x4e ucd90120\ni2c_device_add 18 0x42 pmbus\ni2c_device_add 18 0x20 pca9555\ni2c_device_add 18 0x4c max6658\ni2c_device_add 18 0x50 24c512\n\n# Bus  19 - Muxed LC6\ni2c_device_add 19 0x4e ucd90120\ni2c_device_add 19 0x42 pmbus\ni2c_device_add 19 0x20 pca9555\ni2c_device_add 19 0x4c max6658\ni2c_device_add 19 0x50 24c512\n\n# Bus  20 - Muxed LC7\ni2c_device_add 20 0x4e ucd90120\ni2c_device_add 20 0x42 pmbus\ni2c_device_add 20 0x20 pca9555\ni2c_device_add 20 0x4c max6658\ni2c_device_add 20 0x50 24c512\n\n# Bus  21 - Muxed LC8\ni2c_device_add 21 0x4e ucd90120\ni2c_device_add 21 0x42 pmbus\ni2c_device_add 21 0x20 pca9555\ni2c_device_add 21 0x4c max6658\ni2c_device_add 21 0x50 24c512\n", "num_lines": 256}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shellcheck disable=SC1091\n. /usr/local/bin/openbmc-utils.sh\nSUPCPLD_SYSFS_DIR=$(i2c_device_sysfs_abspath 12-0043)\nSUP_PWR_ON_SYSFS=\"${SUPCPLD_SYSFS_DIR}/cpu_control\"\n\necho \"=== USERVER PWR STATUS ===\"\nif ! val=$(head -n 1 2>/dev/null < \"${SUP_PWR_ON_SYSFS}\"); then\n  echo \"Error when trying to read $SUP_PWR_ON_SYSFS, exiting...\"\n  exit 1\nfi\n\nif [ -z \"$val\" ]; then\n  echo \"cpu_control register is 0\"\nelse\n  echo \"cpu_control register is 1\"\nfi\necho \"=== BMC SYSTEM TIME ===\"\ndate\necho \"=== BMC VERSION ===\"\ncat /etc/issue\necho \"=== BMC UPTIME ===\"\nuptime\necho \"=== FPGA VERSIONS ===\"\nfpga_ver.sh\necho \"=== CHASSIS SERIAL NUMBER ===\"\nweutil CHASSIS\necho \"=== SWITCH CARD SERIAL NUMBER ===\"\nweutil SCD\necho \"=== SUP SERIAL NUMBER ===\"\nweutil SUP\necho \"=== LC1 SERIAL NUMBER ===\"\nweutil LC1\necho \"=== LC2 SERIAL NUMBER ===\"\nweutil LC2\necho \"=== LC3 SERIAL NUMBER ===\"\nweutil LC3\necho \"=== LC4 SERIAL NUMBER ===\"\nweutil LC4\necho \"=== LC5 SERIAL NUMBER ===\"\nweutil LC5\necho \"=== LC6 SERIAL NUMBER ===\"\nweutil LC6\necho \"=== LC7 SERIAL NUMBER ===\"\nweutil LC7\necho \"=== LC8 SERIAL NUMBER ===\"\nweutil LC8\necho \"=== PSU SHOWTECH AT BUS 5 ===\"\npython /usr/local/bin/psu_show_tech.py 5 0x58 -c dps1900\necho \"=== PSU SHOWTECH AT BUS 8 ===\"\npython /usr/local/bin/psu_show_tech.py 8 0x58 -c dps1900\n\n", "num_lines": 54}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nweutil SUP > /tmp/sup_weutil.txt\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/bin/openbmc-utils.sh\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nprog=\"$0\"\n\nusage() {\n    echo \"Usage: $prog <command> [command options]\"\n    echo\n    echo \"Commands:\"\n    echo \"  status: Get the current microserver power status\"\n    echo\n    echo \"  on: Power on microserver if not powered on already\"\n    echo \"    options:\"\n    echo \"      -f: Re-do power on sequence no matter if microserver has \"\n    echo \"          been powered on or not.\"\n    echo\n    echo \"  off: Power off microserver ungracefully\"\n    echo\n    echo \"  reset: Power reset microserver ungracefully\"\n    echo \"    options:\"\n    echo \"      -s: Power reset whole yamp system ungracefully\"\n    echo\n    echo \"  lcreset: Power-cycle one or all LC(s)\"\n    echo \"    options:\"\n    echo \"      -a  : Reset all LCs or \"\n    echo \"      -1 , -2 , ... , -8 : Reset a single LC (1, 2 ... 8) \"\n    echo\n}\n\ndo_status() {\n    echo -n \"Microserver power is \"\n    return_code=0\n\n    if wedge_is_us_on; then\n        echo \"on\"\n    else\n        echo \"off\"\n        return_code=1\n    fi\n\n    return $return_code\n}\n\ndo_on() {\n    local force opt ret\n    force=0\n    while getopts \"f\" opt; do\n        case $opt in\n            f)\n                force=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    echo -n \"Power on microserver ...\"\n    if [ $force -eq 0 ]; then\n        # need to check if uS is on or not\n        if wedge_is_us_on; then\n            echo \" Already on. Skip!\"\n            return 1\n        fi\n    fi\n\n    wedge_power_on_board\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n        logger \"Successfully power on micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power on micro-server\"\n    fi\n    return $ret\n}\n\ndo_off() {\n    local ret\n    echo -n \"Power off microserver ...\"\n    wedge_power_off_board\n    ret=$?\n    if [ $ret -eq 0 ]; then\n        echo \" Done\"\n        logger \"Successfully power off micro-server\"\n    else\n        echo \" Failed\"\n        logger \"Failed to power off micro-server\"\n    fi\n    return $ret\n}\n\ndo_reset() {\n    local system opt\n    system=0\n    while getopts \"s\" opt; do\n        case $opt in\n            s)\n                system=1\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $system -eq 1 ]; then\n        logger \"Power reset the whole system ...\"\n        echo -n \"Power reset the whole system ...\"\n        sleep 1\n        echo 0xde > $PWR_SYSTEM_SYSFS\n        sleep 8\n        # The chassis shall be reset now... if not, we are in trouble\n        echo \" Failed\"\n        return 254\n    else\n        do_off\n        sleep 1\n        do_on\n    fi\n}\n\ntoggle_pim_reset() {\n  pim=$1\n  # First, put the PIMs we want into reset\n  for slot in 1 2 3 4 5 6 7 8; do\n    if [ $pim -eq 0 ] || [ $slot -eq $pim ]; then\n      # Unlike Minipack, YAMP pim index is 1 based\n      index=$slot\n      # Unlike Minipack, YAMP uses GPIO\n      echo Power-cycling LC in slot $slot\n      echo out > /tmp/gpionames/LC${index}_LC_PWR_CYC/direction\n      echo high > /tmp/gpionames/LC${index}_LC_PWR_CYC/direction\n    fi\n  done\n  # Sleep 1 sec\n  sleep 1\n  # Finally, put the LC_PWR_CYC bit to 0\n  for slot in 1 2 3 4 5 6 7 8; do\n    if [ $pim -eq 0 ] || [ $slot -eq $pim ]; then\n      # Unlike Minipack, YAMP pim index is 1 based\n      index=$slot\n      # Unlike Minipack, YAMP uses GPIO\n      echo Putting LC in $slot into normal operation\n      echo low > /tmp/gpionames/LC${index}_LC_PWR_CYC/direction\n    fi\n  done\n}\ndo_pimreset() {\n    local pim opt retval rc\n    retval=0\n    pim=-1\n    while getopts \"12345678a\" opt; do\n        case $opt in\n            a)\n                pim=0\n                ;;\n            1)\n                pim=1\n                ;;\n            2)\n                pim=2\n                ;;\n            3)\n                pim=3\n                ;;\n            4)\n                pim=4\n                ;;\n            5)\n                pim=5\n                ;;\n            6)\n                pim=6\n                ;;\n            7)\n                pim=7\n                ;;\n            8)\n                pim=8\n                ;;\n            *)\n                usage\n                exit -1\n                ;;\n        esac\n    done\n    if [ $pim -eq -1 ]; then\n      usage\n      exit -1\n    fi\n\n    toggle_pim_reset $pim\n\n    return $retval\n}\n\nif [ $# -lt 1 ]; then\n    usage\n    exit -1\nfi\n\ncommand=\"$1\"\nshift\n\ncase \"$command\" in\n    status)\n        do_status $@\n        ;;\n    on)\n        do_on $@\n        ;;\n    off)\n        do_off $@\n        ;;\n    reset)\n        do_reset $@\n        ;;\n    pimreset)\n        do_pimreset $@\n        ;;\n    lcreset)\n        do_pimreset $@\n        ;;\n    *)\n        usage\n        exit -1\n        ;;\nesac\n\nexit $?\n", "num_lines": 254}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# YAMP's SUP MAC address is the first address of the block\n# allocated from \"Extended MAC Base\" field in SUP's EEPROM.\n# That is, SUP's MAC address is the same as \"Extended MAC Base\" \n# field in SUP's EEPROM\n# Any error in reading SUP's EEPROM will result in empty output,\n# which will be caught in the provisioning script.\nweutil SUP 2>&1 | grep \"MAC Base\" | cut -d ' ' -f 4\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/led-controld\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\nrunsv /etc/sv/led-controld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe lm90\nmodprobe max6697\nmodprobe pmbus\nmodprobe ucd9000\n\n", "num_lines": 48}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n### BEGIN INIT INFO\n# Provides:\t\ttcsd trousers\n# Required-Start:\t$local_fs $remote_fs $network\n# Required-Stop:\t$local_fs $remote_fs $network\n# Should-Start:\n# Should-Stop:\n# Default-Start:\t2 3 4 5\n# Default-Stop:\t\t0 1 6\n# Short-Description:\tstarts tcsd\n# Description:\t\ttcsd belongs to the TrouSerS TCG Software Stack\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/sbin/tcsd\nNAME=tcsd\nDESC=\"Trusted Computing daemon\"\nUSER=\"root\"\n\ntest -x \"${DAEMON}\" || exit 0\n\n# Read configuration variable file if it is present\n[ -r /etc/default/$NAME ] && . /etc/default/$NAME\n\ncase \"${1}\" in\n\tstart)\n\t\techo \"Starting $DESC: \"\n\n    # For YAMP platform, it has separate TPM for BMC only - it's probed during \n    # BMC start up. So there is no need for additional device probe / addition\n\n    # Generate symlink for tcsd\n    rm -f /dev/tpm\n\t\tif [ -e /dev/tpm0 ]\n    then\n      ln -s /dev/tpm0 /dev/tpm\n    else\n      ln -s /dev/tpm1 /dev/tpm\n    fi\n\n\t\tstart-stop-daemon --start --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --chuid ${USER} --exec ${DAEMON} -- ${DAEMON_OPTS}\n\t\tRETVAL=\"$?\"\n\t\techo \"$NAME.\"\n\t\t[ \"$RETVAL\" = 0 ] && pidof $DAEMON > /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\tstop)\n\t\techo \"Stopping $DESC: \"\n\n\t\tstart-stop-daemon --stop --quiet --oknodo --pidfile /var/run/${NAME}.pid --user ${USER} --exec ${DAEMON}\n\t\tRETVAL=\"$?\"\n                echo  \"$NAME.\"\n\t\trm -f /var/run/${NAME}.pid\n\t\texit $RETVAL\n\t\t;;\n\n\trestart|force-reload)\n\t\t\"${0}\" stop\n\t\tsleep 1\n\t\t\"${0}\" start\n\t\texit $?\n\t\t;;\n\t*)\n\t\techo \"Usage: ${NAME} {start|stop|restart|force-reload|status}\" >&2\n\t\texit 3\n\t\t;;\nesac\n\nexit 0\n", "num_lines": 72}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-bic-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for Bridge IC info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for Bridge IC info..\"\nif [ $(is_server_prsnt 1) == \"1\" ]; then\n  /usr/local/bin/bic-cached 1 > /dev/null 2>&1 &\nfi\n\nif [ $(is_server_prsnt 2) == \"1\" ]; then\n/usr/local/bin/bic-cached 2 > /dev/null 2>&1 &\nfi\n\nif [ $(is_server_prsnt 3) == \"1\" ]; then\n/usr/local/bin/bic-cached 3 > /dev/null 2>&1 &\nfi\n\nif [ $(is_server_prsnt 4) == \"1\" ]; then\n/usr/local/bin/bic-cached 4 > /dev/null 2>&1 &\nfi\n\necho \"done.\"\n", "num_lines": 34}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2016-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-confg\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: setup configure files.\n# The file format should be src:dest\n### END INIT INFO\n\nACTION=\"$1\"\ncase \"$ACTION\" in\n  start)\n  if [ -e /etc/config ] && [ \"$(ls -A /etc/config)\" ]; then\n    echo \"Start to copy configure files....\"\n    for file in /etc/config/* \n    do\n       while IFS='' read -r line || [[ -n \"$line\" ]]; do\n         src=$(echo $line | awk -F\":\" '{print $1}')\n         dest=$(echo $line | awk -F\":\" '{print $2}')\n         if [ -e $src ]; then\n\t         mkdir -p $dest\n           cp -r $src $dest\n         fi\n       done < \"$file\"\n    done\n    echo \"Copying is done.\"\n  fi\nesac\n\nexit 0\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          fw_env_config\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Replace /etc/fw_env.config by /etc/fw_env.config.full\n### END INIT INFO\n\nACTION=\"$1\"\ncase \"$ACTION\" in\n  start)\n    CFG_FULL=`grep \"Partition_000\" /proc/mtd`\n    if [ \"$CFG_FULL\" != \"\" ]; then\n      cp /etc/fw_env.config.full /etc/fw_env.config\n    fi\n    ;;\nesac\n\nexit 0\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          mount_data0\n# Required-Start:    mountvirtfs\n# Required-Stop: \n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Mount data0 partition from flash chip.\n# Description:\n### END INIT INFO\n\n. /etc/default/rcS\n\n# Find out which device maps to 'data0' on mtd\n# Note: /proc/mtd lists partitions using mtdX, where X is a number,\n#       but we mount using /dev/mtdblockX. We'll do some magic here\n#       to get the mtdX (char device) and mtdblockX (block device) \n#       names.\nMOUNT_POINT=\"/mnt/data\"\nDATA_CHAR_DEV=$(cat /proc/mtd | awk '{ if ($4 == \"\\\"data0\\\"\") print $1 }' |\n  cut -d ':' -f 1 | awk '{ print \"/dev/\" $1 }')\nif [ -z \"$DATA_CHAR_DEV\" ]\nthen\n  echo \"No data0 partition found. Not mounting anything to $MOUNT_POINT.\"\nelse\n  DEVICE_ID=$(echo $DATA_CHAR_DEV | tail -c 2)\n  DATA_BLOCK_DEV=${DATA_CHAR_DEV/mtd/mtdblock}\n\n  echo \"data0 partition found on $DATA_BLOCK_DEV; mounting to $MOUNT_POINT.\"\n  mount -t jffs2 $DATA_BLOCK_DEV $MOUNT_POINT\n\n  # if the mount failed, format the partition and remount\n  if [ $? -ne 0 ]\n  then\n    echo \"Mount failed; formatting $DATA_BLOCK_DEV and remounting.\"\n    flash_eraseall $DATA_CHAR_DEV\n    mount -t jffs2 $DATA_BLOCK_DEV $MOUNT_POINT\n  fi\nfi\n\n: exit 0\n\n", "num_lines": 62}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config()\n{\n\n  TO_PWR_ON=-1\n\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/slot${1}_por_cfg\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    POR=`cat ${KEYDIR}/slot${1}_por_cfg`\n\n    # Case ON\n    if [ $POR == \"on\" ]; then\n      TO_PWR_ON=1;\n\n    # Case OFF\n    elif [ $POR == \"off\" ]; then\n      TO_PWR_ON=0;\n\n    # Case LPS\n    elif [ $POR == \"lps\" ]; then\n\n      # Check if the file/key doesn't exist\n      if [ ! -f \"${KEYDIR}/pwr_server${1}_last_state\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        LS=`cat ${KEYDIR}/pwr_server${1}_last_state`\n        if [ $LS == \"on\" ]; then\n          TO_PWR_ON=1;\n        elif [ $LS == \"off\" ]; then\n          TO_PWR_ON=0;\n        fi\n      fi\n    fi\n  fi\n}\n\n# Sync BMC's date with one of the four servers\nsync_date()\n{\n  for i in 1 2 3 4\n  do\n    if [ $(is_server_prsnt $i) == \"1\" ] ; then\n      # Use standard IPMI command 'get-sel-time' to read RTC time\n      output=$(/usr/local/bin/me-util slot$i 0x28 0x48)\n      # if the command fails, continue to next slot\n      [ $(echo $output | wc -c) != 12 ] && continue\n      col1=$(echo $output | cut -d' ' -f1 | sed 's/^0*//')\n      col2=$(echo $output | cut -d' ' -f2 | sed 's/^0*//')\n      col3=$(echo $output | cut -d' ' -f3 | sed 's/^0*//')\n      col4=$(echo $output | cut -d' ' -f4 | sed 's/^0*//')\n\n      # create the integer from the hex bytes returned\n      val=$((0x$col4 << 24 | 0x$col3 << 16 | 0x$col2 << 8 | 0x$col1))\n\n      # create the timestamp required for busybox's date command\n      ts=$(date -d @$val +\"%Y.%m.%d-%H:%M:%S\")\n\n      # set the command\n      echo Syncing up BMC time with server$i...\n      date $ts\n      break\n    fi\n  done\n}\n\n# Check whether it is fresh power on reset\nif [ $(is_bmc_por) -eq 1 ]; then\n\n  # Disable clearing of PWM block on WDT SoC Reset\n  devmem_clear_bit $(scu_addr 9c) 17\n\n  sync_date\n\n  check_por_config 1\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 1) == \"1\" ] ; then\n    power-util slot1 on\n  fi\n\n  check_por_config 2\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 2) == \"1\" ] ; then\n    power-util slot2 on\n  fi\n\n  check_por_config 3\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 3) == \"1\" ] ; then\n    power-util slot3 on\n  fi\n\n  check_por_config 4\n  if [ $TO_PWR_ON -eq 1 ] && [ $(is_server_prsnt 4) == \"1\" ] ; then\n    power-util slot4 on\n  fi\nfi\n", "num_lines": 130}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <slot#> <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 2 ]; then\n    usage $0\nfi\n\n# Slot#1: GPIOM1(97),Slot#2: GPIOM0(96),Slot#3: GPIOM3(99),Slot#4: GPIOM2(98)\nif [ $1 = \"1\" ]; then\n    gpio=M1\nelif [ $1 = \"2\" ]; then\n    gpio=M0\nelif [ $1 = \"3\" ]; then\n    gpio=M3\nelif [ $1 = \"4\" ]; then\n    gpio=M2\nelse\n    usage $0\nfi\n\n\nif [ $2 = \"on\" ]; then\n    val=1\nelif [ $2 = \"off\" ]; then\n    val=0\nelse\n    usage $0\nfi\n\ngpio_set $gpio $val\n", "num_lines": 59}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Set up to read the board revision pins, Y0, Y1, Y2\ndevmem_set_bit $(scu_addr 70) 19\ndevmem_clear_bit $(scu_addr a4) 8\ndevmem_clear_bit $(scu_addr a4) 9\ndevmem_clear_bit $(scu_addr a4) 10\n\ngpio_export Y0\ngpio_export Y1\ngpio_export Y2\n\n# SLOT1_PRSNT_N, GPIOH5 (61)\n# GPIOH5(61): SCU90[6], SCU90[7] shall be 0\ndevmem_clear_bit $(scu_addr 90) 6\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_export H5\n\n# SLOT2_PRSNT_N, GPIOH4 (60)\n# GPIOH4(60): SCU90[6], SCU90[7] shall be 0\ngpio_export H4\n\n# SLOT3_PRSNT_N, GPIOH7 (63)\n# GPIOH7(63): SCU90[6], SCU90[7] shall be 0\ngpio_export H7\n\n# SLOT4_PRSNT_N, GPIOH6 (62)\n# GPIOH6(62): SCU90[6], SCU90[7] shall be 0\ngpio_export H6\n\n# BMC_PWR_BTN_IN_N, uServer power button in, on GPIO D0(24)\ngpio_export D0\n\n# PWR_SLOT1_BTN_N, 1S Server power out, on GPIO D3\n# GPIOD3(27): SCU90[1], SCU8C[9], and SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 8c) 9\ndevmem_clear_bit $(scu_addr 70) 21\n\ngpio_set D3 1\n\n# PWR_SLOT2_BTN_N, 1S Server power out, on GPIO D1\n# Make sure the Power Control Pin is Set properly\n# GPIOD1(25): SCU90[1], SCU8C[8], and SCU70[21] shall be 0\n\ndevmem_clear_bit $(scu_addr 8c) 8\n\ngpio_set D1 1\n\n# PWR_SLOT3_BTN_N, 1S Server power out, on GPIO D7\n# GPIOD7(31): SCU90[1], SCU8C[11], and SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 8c) 11\n\ngpio_set D7 1\n\n# PWR_SLOT4_BTN_N, 1S Server power out, on GPIO D5\n# GPIOD5(29): SCU90[1], SCU8C[10], and SCU70[21] shall be 0\ndevmem_clear_bit $(scu_addr 8c) 10\n\ngpio_set D5 1\n\n# SMB_SLOT0_NIC_ALERT_N, alert for 1S Server NIC I2C, GPIO B0\ndevmem_clear_bit $(scu_addr 80) 8\n\ngpio_export B0\n\n# Enable P3V3: GPIOS1(145)\n# To use GPIOS1 (145), SCU8C[1], SCU94[0], and SCU94[1] must be 0\ndevmem_clear_bit $(scu_addr 8C) 1\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\n\ngpio_set S1 1\n\n# PWRGD_P3V3: GPIOS2(146)\n# To use GPIOS2 (146), SCU8C[2], SCU94[0], and SCU94[1] must be 0\ndevmem_clear_bit $(scu_addr 8C) 2\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\n\n# Setup GPIOs to Mux Enable: GPIOS3(147), Channel Select: GPIOE4(36), GPIOE5(37)\n\n# To use GPIOS3 (147), SCU8C[3], SCU94[0], and SCU94[1] must be 0\ndevmem_clear_bit $(scu_addr 8C) 3\ndevmem_clear_bit $(scu_addr 94) 0\ndevmem_clear_bit $(scu_addr 94) 1\n\n# To use GPIOE4 (36), SCU80[20], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 20\ndevmem_clear_bit $(scu_addr 8C) 14\ndevmem_clear_bit $(scu_addr 70) 22\n\n# To use GPIOE5 (37), SCU80[21], SCU8C[14], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 21\ndevmem_clear_bit $(scu_addr 8C) 14\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_set S3 0\ngpio_set E4 1\ngpio_set E5 0\n\n# BMC_HEARTBEAT_N, heartbeat LED, GPIO Q7(135)\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_set Q7 0\n\n# USB_OC_N, resettable fuse tripped, GPIO Q6\ndevmem_clear_bit $(scu_addr 90) 28\n\ngpio_export Q6\n\n# System SPI\n# Strap 12 must be 0 and Strape 13 must be 1\ndevmem_clear_bit $(scu_addr 70) 12\ndevmem_set_bit $(scu_addr 70) 13\n\n# DEBUG_PORT_UART_SEL_BMC_N: GPIOR1(137)\n# To use GPIOR1, SCU88[25] must be 0\ndevmem_clear_bit $(scu_addr 88) 25\n\ngpio_export R1\n\n# DEBUG UART Controls\n# 4 signals: DEBUG_UART_SEL_0/1/2 and DEBUG_UART_RX_SEL_N\n# GPIOE0 (32), GPIOE1 (33), GPIOE2 (34) and GPIOE3 (35)\n\n# To enable GPIOE0, SCU80[16], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 16\ndevmem_clear_bit $(scu_addr 8C) 12\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export_out E0\n\n# To enable GPIOE1, SCU80[17], SCU8C[12], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 17\n\ngpio_export_out E1\n\n# To enable GPIOE2, SCU80[18], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 18\ndevmem_clear_bit $(scu_addr 8C) 13\n\ngpio_export_out E2\n\n# To enable GPIOE3, SCU80[19], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 19\n\ngpio_export_out E3\n\n# Enable GPIOY3: BoardId(Yosemite or Test system)\ndevmem_clear_bit $(scu_addr a4) 11\n\n# Power LED for Slot#2:\n# To use GPIOM0 (96), SCU90[4], SCU90[5], and SCU84[24] must be 0\ndevmem_clear_bit $(scu_addr 90) 4\ndevmem_clear_bit $(scu_addr 90) 5\ndevmem_clear_bit $(scu_addr 84) 24\n\ngpio_set M0 1\n\n# Power LED for Slot#1:\n# To use GPIOM1 (97), SCU90[4], SCU90[5], and SCU84[25] must be 0\ndevmem_clear_bit $(scu_addr 84) 25\n\ngpio_set M1 1\n\n# Power LED for Slot#4:\n# To use GPIOM2 (98), SCU90[4], SCU90[5], and SCU84[26] must be 0\ndevmem_clear_bit $(scu_addr 84) 26\n\ngpio_set M2 1\n\n# Power LED for Slot#3:\n# To use GPIOM3 (99), SCU90[4], SCU90[5], and SCU84[27] must be 0\ndevmem_clear_bit $(scu_addr 84) 27\n\ngpio_set M3 1\n\n\n# Identify LED for Slot#2:\n# To use GPIOF0 (40), SCU80[24] must be 0\ndevmem_clear_bit $(scu_addr 80) 24\n\ngpio_set F0 1\n\n# Identify LED for Slot#1:\n# To use GPIOF1 (41), SCU80[25], SCUA4[12], must be 0\ndevmem_clear_bit $(scu_addr 80) 25\ndevmem_clear_bit $(scu_addr A4) 12\n\ngpio_set F1 1\n\n# Identify LED for Slot#4:\n# To use GPIOF2 (42), SCU80[26], SCUA4[13],  must be 0\ndevmem_clear_bit $(scu_addr 80) 26\ndevmem_clear_bit $(scu_addr A4) 13\n\ngpio_set F2 1\n\n# Identify LED for Slot#3:\n# To use GPIOF3 (43), SCU80[27], SCUA4[14], must be 0\ndevmem_clear_bit $(scu_addr 80) 27\ndevmem_clear_bit $(scu_addr A4) 14\n\ngpio_set F3 1\n\n# Front Panel Hand Switch GPIO setup\n# HAND_SW_ID1: GPIOR2(138)\n# To use GPIOR2, SCU88[26] must be 0\ndevmem_clear_bit $(scu_addr 88) 26\n\ngpio_export R2\n\n# HAND_SW_ID2: GPIOR3(139)\n# To use GPIOR3, SCU88[27] must be 0\ndevmem_clear_bit $(scu_addr 88) 27\n\ngpio_export R3\n\n# HAND_SW_ID4: GPIOR4(140)\n# To use GPIOR4, SCU88[28] must be 0\ndevmem_clear_bit $(scu_addr 88) 28\n\ngpio_export R4\n\n\n# HAND_SW_ID8: GPIOR5(141)\n# To use GPIOR5, SCU88[29] must be 0\ndevmem_clear_bit $(scu_addr 88) 29\n\ngpio_export R5\n\n# LED POST CODES: 8 GPIO signals\n\n# LED_POSTCODE_0: GPIOG0 (48)\n# To use GPIOG0, SCU84[0] must be 0\ndevmem_clear_bit $(scu_addr 84) 0\n\ngpio_set G0 0\n\n# LED_POSTCODE_1: GPIOG1 (49)\n# To use GPIOG1, SCU84[1] must be 0\ndevmem_clear_bit $(scu_addr 84) 1\n\ngpio_set G1 0\n\n# LED_POSTCODE_2: GPIOG2 (50)\n# To use GPIOG2, SCU84[2] must be 0\ndevmem_clear_bit $(scu_addr 84) 2\n\ngpio_set G2 0\n\n# LED_POSTCODE_3: GPIOG3 (51)\n# To use GPIOG3, SCU84[3] must be 0\ndevmem_clear_bit $(scu_addr 84) 3\n\ngpio_set G3 0\n\n# LED_POSTCODE_4: GPIOP4 (124)\ngpio_set P4 0\n\n# LED_POSTCODE_5: GPIOP5 (125)\ngpio_set P5 0\n\n# LED_POSTCODE_6: GPIOP6 (126)\n# To use GPIOP6, SCU88[22] must be 0\ndevmem_clear_bit $(scu_addr 88) 22\n\ngpio_set P6 0\n\n# LED_POSTCODE_7: GPIOP7 (127)\n# To use GPIOP7, SCU88[23] must be 0\ndevmem_clear_bit $(scu_addr 88) 23\n\ngpio_set P7 0\n\n# BMC_READY_N: GPIOG6 (54)\n# To use GPIOG6, SCU84[6] must be 0\ndevmem_clear_bit $(scu_addr 84) 6\n\ngpio_set G6 0\n\n# BMC_RST_BTN_IN_N: GPIOS0 (144)\n# To use GPIOS0, SCU8C[0]\ndevmem_clear_bit $(scu_addr 8c) 0\n\ngpio_export S0\n\n# RESET for all Slots\n# RST_SLOT1_SYS_RESET_N: GPIOH1 (57)\n# To use GPIOH1, SCU90[6], SCU90[7] must be 0\ndevmem_clear_bit $(scu_addr 90) 6\ndevmem_clear_bit $(scu_addr 90) 7\n\ngpio_set H1 1\n\n# RST_SLOT2_SYS_RESET_N: GPIOH0 (56)\n# To use GPIOH0, SCU90[6], SCU90[7] must be 0\ngpio_set H0 1\n\n# RST_SLOT3_SYS_RESET_N: GPIOH3 (59)\n# To use GPIOH3, SCU90[6], SCU90[7] must be 0\ngpio_set H3 1\n\n# RST_SLOT4_SYS_RESET_N: GPIOH2 (58)\n# To use GPIOH2, SCU90[6], SCU90[7] must be 0\ngpio_set H2 1\n\n# 12V_STBY Enable for Slots\n\n# P12V_STBY_SLOT1_EN: GPIOO5 (117)\n# To use GPIOO5, SCU88[13] must be 0\ndevmem_clear_bit $(scu_addr 88) 13\n\ngpio_set O5 1\n\n# P12V_STBY_SLOT2_EN: GPIOO4 (116)\n# To use GPIOO4, SCU88[12] must be 0\ndevmem_clear_bit $(scu_addr 88) 12\n\ngpio_set O4 1\n\n# P12V_STBY_SLOT3_EN: GPIOO7 (119)\n# To use GPIOO7, SCU88[15] must be 0\ndevmem_clear_bit $(scu_addr 88) 15\n\ngpio_set O7 1\n\n# P12V_STBY_SLOT4_EN: GPIOO6 (118)\n# To use GPIOO6, SCU88[13] must be 0\ndevmem_clear_bit $(scu_addr 88) 14\n\ngpio_set O6 1\n\n# PWRGD_P12V_STBY_SLOT1: GPIOP1 (121)\n# To use GPIOP1, SCU88[17] must be 0\ndevmem_clear_bit $(scu_addr 88) 17\ngpio_export P1\n\n# PWRGD_P12V_STBY_SLOT2: GPIOP0 (120)\n# To use GPIOP0, SCU88[16] must be 0\ndevmem_clear_bit $(scu_addr 88) 16\ngpio_export P0\n\n# PWRGD_P12V_STBY_SLOT3: GPIOP3 (123)\n# To use GPIOP3, SCU88[19] must be 0\ndevmem_clear_bit $(scu_addr 88) 19\ngpio_export P3\n\n# PWRGD_P12V_STBY_SLOT4: GPIOP2 (122)\n# To use GPIOP2, SCU88[18] must be 0\ndevmem_clear_bit $(scu_addr 88) 18\ngpio_export P2\n\n# Enable the the EXTRST functionality of GPIOB7\ndevmem_set_bit $(scu_addr 80) 15\ndevmem_clear_bit $(scu_addr 90) 31\ndevmem_set_bit $(scu_addr 3c) 3\n\n# Enable GPIO pins: I2C_SLOTx_ALERT_N pins for BIC firmware update\ndevmem_clear_bit $(scu_addr 88) 2\ngpio_export N2\ndevmem_clear_bit $(scu_addr 88) 3\ngpio_export N3\ndevmem_clear_bit $(scu_addr 88) 4\ngpio_export N4\ndevmem_clear_bit $(scu_addr 88) 5\ngpio_export N5\n\n\n\n# Yosemite OOM remediation\n#   enable kernel panic (force reboot)\necho 1 >> /proc/sys/vm/panic_on_oom\n", "num_lines": 417}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\n  /usr/local/bin/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On Yosemite, there are 2 fans connected.\n# Each fan uses same PWM input and provide one tacho output.\n# Here is the mapping between the fan and PWN/Tacho,\n# staring from the one from the edge\n# Fan 0: PWM 0, Tacho0\n# Fan 1: PWM 0, Tacho1\n\n# For each fan, setting the type, and 100% initially\nfor pwm in 0 1; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0..1\necho 0 > $PWM_DIR/tacho0_source\necho 1 > $PWM_DIR/tacho1_source\n\nt=0\nwhile [ $t -le 1 ]; do\n    echo 1 > $PWM_DIR/tacho${t}_en\n    t=$((t+1))\ndone\n", "num_lines": 65}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for yosemite... \"\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  if [ $(is_server_prsnt 1) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n\n  if [ $(is_server_prsnt 2) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot2\"\n  fi\n\n  if [ $(is_server_prsnt 3) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot3\"\n  fi\n\n  if [ $(is_server_prsnt 4) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot4\"\n  fi\n\n/usr/local/bin/gpiod $SLOTS\n\necho \"done.\"\n", "num_lines": 55}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/gpiointrd\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiointrd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio interrupt monitoring for Yosemite... \"\n\nrunsv /etc/sv/gpiointrd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 2\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 3 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 5 4\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 7 3\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho \"Starting IPMB Rx/Tx Daemon\"\n\nrunsv /etc/sv/ipmbd_3 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_7 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_5 > /dev/null 2>&1 &\n\nif [ $(is_server_prsnt 1) == \"0\" ]; then\n  sv stop ipmbd_3\nfi\n\nif [ $(is_server_prsnt 2) == \"0\" ]; then\n  sv stop ipmbd_1\nfi\n\nif [ $(is_server_prsnt 3) == \"0\" ]; then\n  sv stop ipmbd_7\nfi\n\nif [ $(is_server_prsnt 4) == \"0\" ]; then\n  sv stop ipmbd_5\nfi\n\n", "num_lines": 56}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm1 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm2 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm3 > /dev/null 2>&1 &\nrunsv /etc/sv/mTerm4 > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 10}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup sensor monitoring for yosemite... \"\n\n# Check for the slots present and run sensord for those slots only.\nSLOTS=\n  if [ $(is_server_prsnt 1) == \"1\" ] && [ $(is_bic_ready 1) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot1\"\n  fi\n\n  if [ $(is_server_prsnt 2) == \"1\" ] && [ $(is_bic_ready 2) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot2\"\n  fi\n\n  if [ $(is_server_prsnt 3) == \"1\" ] && [ $(is_bic_ready 3) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot3\"\n  fi\n\n  if [ $(is_server_prsnt 4) == \"1\" ] && [ $(is_bic_ready 4) == \"1\" ]; then\n    SLOTS=\"$SLOTS slot4\"\n  fi\n\nSLOTS=\"$SLOTS spb nic\"\nexec /usr/local/bin/sensord $SLOTS\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe pmbus\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n\n# Enable the ADC inputs;  adc0 - adc7 are connected to various voltage sensors\n#\n#  adc0 P5V_STBY_SCALED           r1: 5.11k,   r2: 3.48k,  v2: 0mv\n#  adc1 P12V_STBY_SCALED          r1: 5.11k,   r2: 1.02k,  v2: 0mv\n#  adc2 P3V3_STBY_SCALED          r1: 5.11k,   r2: 8.25k,  v2: 0mv\n#  adc3 P12V_STBY_SLOT2_SCALED    r1: 5.11k,   r2: 1.02k,  v2: 0mv\n#  adc4 P12V_STBY_SLOT1_SCALED    r1: 5.11k,   r2: 1.02k,  v2: 0mv\n#  adc5 P12V_STBY_SLOT4_SCALED    r1: 5.11k,   r2: 1.02k,  v2: 0mv\n#  adc6 P12V_STBY_SLOT3_SCALED    r1: 5.11k,   r2: 1.02k,  v2: 0mv\n#  adc7 P3V3_SCALED               r1: 5.11k,   r2: 8.25k,  v2: 0mv\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\n\nconfig_adc 0  5110  3480 0\nconfig_adc 1  5110  1020 0\nconfig_adc 2  5110  8250 0\nconfig_adc 3  5110  1020 0\nconfig_adc 4  5110  1020 0\nconfig_adc 5  5110  1020 0\nconfig_adc 6  5110  1020 0\nconfig_adc 7  5110  8250 0\n\n\n#echo 1 > /sys/devices/platform/ast_adc.0/adc0_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc1_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc2_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc3_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc4_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc5_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc6_en\n#echo 1 > /sys/devices/platform/ast_adc.0/adc7_en\n\ni2cset -y -f 10 0x40 0xd4 0x3f1c w\nrmmod adm1275\nmodprobe adm1275\n", "num_lines": 93}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-crond\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup crond history buffering\n### END INIT INFO\n\n# TODO: check for the if slot/server is present before starting the daemon\necho -n \"Setup crond...\"\n  mkdir /etc/cron\n  mkdir /etc/cron/crontabs\n  echo \"0 * * * * run-parts /etc/cron.hourly\" > /etc/cron/crontabs/root\n  echo \"0 0 * * * run-parts /etc/cron.daily\" >> /etc/cron/crontabs/root\n  /etc/init.d/busybox-cron start\necho \"done.\"\n", "num_lines": 38}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Config\n\nEXPIRE_SECONDS=$(( 3600 * 3 ))\n\n# Code\nset -e\n\nNOW=\"$(date +%s)\"\n\nis_expired() {\n\tIMAGE_DIRPATH=\"$1\"; shift\n\tif [ -f \"$IMAGE_DIRPATH\"/image ]; then\n\t\tUPDATE_TS=\"$(stat -c %Y \"$IMAGE_DIRPATH\"/image)\"\n\telse\n\t\tUPDATE_TS=\"$(stat -c %Y \"$IMAGE_DIRPATH\")\"\n\tfi\n\n\tif [ \"$(( UPDATE_TS + EXPIRE_SECONDS ))\" -lt \"$NOW\" ]; then\n\t\treturn 0\n\telse\n\t\treturn 1\n\tfi\n}\n\nset -f\nIFS=\"\n\"\nDIRS=($(find /tmp/restapi-bios_images -type d -mindepth 2 -maxdepth 2))\nset +f\n\nfor DIR in \"${DIRS[@]}\"; do\n\tif is_expired \"$DIR\"; then\n\t\trm -f \"$DIR\"/*\n\t\trmdir \"$DIR\"\n\tfi\ndone\n", "num_lines": 39}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          usbcons\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Creates a virtual USB serial device and starts a console\n#                    on it.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=usbcons\nPIDFILE=/run/usbcons.pid\nDESC=\"USB Serial Console\"\n\n# source function library\n. /etc/init.d/functions\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    # Ability to prevent this from starting by editing cmdline in u-boot.\n    # Keeping this here until I get gadget switching working properly. (t4906522)\n    if grep \"nousbcons\" /proc/cmdline > /dev/null 2>&1\n    then\n      echo \"USB Console Disabled.\"\n      exit 0\n    fi\n    echo -n \"Starting $DESC: \"\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall usbmon.sh\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall usbmon.sh\n    sleep 1\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 81}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n#\n# Load USB gadget drivers in case they are compiled as modules.\n# Note: \"ast-udc\" only exists in kernel 4.1. The driver is renamed to\n# \"aspeed_vhub\" in kernel 5.x, and it will be auto-loaded at bootup time.\n#\nif uname -r | grep \"4\\.1\\.*\" > /dev/null 2>&1; then\n    modprobe ast-udc\nfi\nmodprobe g_cdc host_addr=02:00:00:00:00:02 dev_addr=02:00:00:00:00:01\n\n# For g-ether interface, if the remote side brings down the interface, BMC side\n# still treats it as up. In this case, all packets through usb0 (i.e. NDP) will\n# be queued in the kernel for this interface. Ether interface has the default\n# TX queue length as 1000, which means there could be up to 1000 package queued\n# in kernel for that. In our case, kmalloc-192 is exhausted when 298 packets\n# are queued.\n# To solve this issue, we change the TX queue length for usb0 to 64 to avoid\n# memory exhaust.\nifconfig usb0 txqueuelen 64\n\n#\n# Below logic is required to handle \"getty\" command line differences on\n# different platforms:\n#\n#   - yocto rocko:\n#     \"getty\" is from BusyBox, and tty_name can be a relative path (such\n#     as ttyGS0) or absolute path (/dev/ttyGS0).\n#     Given we've been using \"/dev/ttyGS0\" for long time, let's just keep it.\n#\n#   - yocto warrior (or newer versions):\n#     \"getty\" is from util-linux, and tty_name must be a relative path (under\n#     \"/dev\").\n#\nif getty 2>&1 | grep \"BusyBox v1\" > /dev/null 2>&1; then\n    tty_name=\"/dev/ttyGS0\"\nelse\n    tty_name=\"ttyGS0\"\nfi\n\nwhile true; do\n    getty \"$tty_name\" 57600\n    sleep 1\ndone\n", "num_lines": 64}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-consoled\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup console history buffering\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Enable AST SNOOP DMA with default port 80\necho 1 > /sys/devices/platform/ast-snoop-dma.0/enable\n\n\n# TODO: check for the if slot/server is present before starting the daemon\necho -n \"Setup console  buffering...\"\n\n/usr/local/bin/consoled mb --buffer\n\necho \"done.\"\n", "num_lines": 42}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-front-paneld\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Start front panel control daemon\n### END INIT INFO\n\necho -n \"Setup Front Panel Daemon..\"\n  /usr/local/bin/front-paneld > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 17}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\nPWM_DIR=/sys/devices/platform/ast_pwm_tacho.0\n\nset -e\n\n# The PWM frequency is\n\n#   clk_source / ((2 ^ division_) * (2 * division_l) * (unit + 1))\n#\n# Our clk_source is 24Mhz.  4-pin fans are generally supposed to be driven with\n# a 25Khz PWM control signal.  Therefore we want the divisor to equal 960.\n#\n# We also want the unit to be as large as possible, since this controls the\n# granularity with which we can modulate the PWM signal.  The following\n# settings allow us to set the fan from 0 to 100% in increments of 1/96th.\n#\n# The AST chip supports 3 different PWM clock configurations, but we only use\n# type M for now.\necho 0 > $PWM_DIR/pwm_type_m_division_h\necho 5 > $PWM_DIR/pwm_type_m_division_l\necho 95 > $PWM_DIR/pwm_type_m_unit\n\n# On FBTP, there are 2 fans connected.\n# Here is the mapping between the fan and PWN/Tacho,\n# Fan 0: PWM 0, Tacho0\n# Fan 1: PWM 1, Tacho2\n\n# For each fan, setting the type, and 100% initially\nfor pwm in 0 1; do\n    echo 0 > $PWM_DIR/pwm${pwm}_type\n    echo 0 > $PWM_DIR/pwm${pwm}_rising\n    echo 0 > $PWM_DIR/pwm${pwm}_falling\n    echo 1 > $PWM_DIR/pwm${pwm}_en\ndone\n\n# Enable Tach 0, 2\necho 0 > $PWM_DIR/tacho0_source\necho 1 > $PWM_DIR/tacho0_en\n\necho 1 > $PWM_DIR/tacho2_source\necho 1 > $PWM_DIR/tacho2_en\n", "num_lines": 60}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-fan\n# Required-Start:    board-id\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set fan speed\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup fan speed... \"\n/usr/local/bin/init_pwm.sh\n/usr/local/bin/fan-util --set 50\nrunsv /etc/sv/fscd > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-gpiod\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup gpio monitoring for FBTP... \"\n\n/usr/local/bin/gpiod\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 1 1\n\n", "num_lines": 4}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 4 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nexec /usr/local/bin/ipmbd 9 1\n", "num_lines": 3}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          ipmbd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Provides ipmb message tx/rx service\n#\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\necho -n \"Starting IPMB Rx/Tx Daemon..\"\n\nrunsv /etc/sv/ipmbd_1 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_4 > /dev/null 2>&1 &\nrunsv /etc/sv/ipmbd_9 > /dev/null 2>&1 &\n\necho \"done.\"\n\n", "num_lines": 40}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n### BEGIN INIT INFO\n# Provides:          setup-me-cached\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Set Cachcing for ME info\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup Caching for MEinfo..\"\n/usr/local/bin/me-cached > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 19}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# PLATFORM MAY CHOOSE TO OVERRIDE THIS FILE\necho -n \"Starting mTerm console server...\"\nrunsv /etc/sv/mTerm > /dev/null 2>&1 &\nrunsv /etc/sv/mTermBMC > /dev/null 2>&1 &\necho \"done.\"\n", "num_lines": 8}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nPID=$$\n# File format autodump<fru>.pid (See pal_is_crashdump_ongoing()\n# function definition)\nPID_FILE='/var/run/autodump1.pid'\n\n# check if running auto dump\n[ -r $PID_FILE ] && OLDPID=`cat $PID_FILE` || OLDPID=''\n\n# Set current pid\necho $PID > $PID_FILE\n\n# kill previous autodump if exist\nif [ ! -z \"$OLDPID\" ] && (grep \"autodump\" /proc/$OLDPID/cmdline &> /dev/null) ; then\n\n  LOG_FILE='/tmp/autodump.log'\n  LOG_ARCHIVE='/mnt/data/autodump_uncompleted.tar.gz'\n  echo -n \"(uncompleted) Auto Dump End at \" >> $LOG_FILE\n  date >> $LOG_FILE\n\n  tar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\n  rm -rf $LOG_FILE && \\\n\n  echo \"kill pid $OLDPID...\"\n  kill -s 9 $OLDPID\n  killall peci-util &> /dev/null\n  killall me-util &> /dev/null\nfi\nunset OLDPID\n\nDUMP_SCRIPT='/usr/local/bin/dump.sh'\nLOG_FILE='/tmp/autodump.log'\nLOG_ARCHIVE='/mnt/data/autodump.tar.gz'\nLOG_MSG_PREFIX=\"\"\n\nCPU0_SKTOCC_N=\"/sys/class/gpio/gpio51/value\"\nCPU1_SKTOCC_N=\"/sys/class/gpio/gpio208/value\"\nDWR=0\nSECOND_DUMP=0\nDELAY_SEC=30\nSENSOR_HISTORY=180\n\nwhile test $# -gt 0\ndo\n  case \"$1\" in\n  --dwr)\n    DWR=1\n    ;;\n  --now)\n    DELAY_SEC=0\n    ;;\n  --second)\n    SECOND_DUMP=1\n    ;;\n  *)\n    echo \"unknown argument $1\"\n    ;;\n  esac\n  shift\ndone\n\nif [ \"$DWR\" == \"1\" ]; then\n  LOG_ARCHIVE='/mnt/data/autodump_dwr.tar.gz'\n  LOG_MSG_PREFIX=\"DWR \"\n  echo \"Auto Dump after Demoted Warm Reset\"\nfi\n\nif [ \"$SECOND_DUMP\" == \"1\" ]; then\n  LOG_ARCHIVE='/mnt/data/autodump_second.tar.gz'\n  LOG_MSG_PREFIX=\"SECOND_DUMP \"\n  echo \"Auto Dump after system reset\"\nfi\n\nif [ \"$DELAY_SEC\" != \"0\" ]; then\n  echo \"Auto Dump will start after ${DELAY_SEC}s...\"\n\n  sleep ${DELAY_SEC}\nfi\n\necho \"Auto Dump Started\"\n\n# Start to dump and clear LOG_FILE\necho -n \"Auto Dump Start at \" > $LOG_FILE\ndate >> $LOG_FILE\n\n# CPU0\n$DUMP_SCRIPT 48 coreid >> $LOG_FILE 2>&1\n$DUMP_SCRIPT 48 msr >> $LOG_FILE 2>&1\n\n# CPU1\nif [ \"`cat $CPU1_SKTOCC_N`\" -eq \"0\" ]; then\n  $DUMP_SCRIPT 49 coreid >> $LOG_FILE 2>&1\n  $DUMP_SCRIPT 49 msr >> $LOG_FILE 2>&1\nelse\n  echo \"<<---------- CPU1 is not present, skip it. ---------->>\" >> $LOG_FILE\nfi\n\n# PCIe\n$DUMP_SCRIPT pcie >> $LOG_FILE 2>&1\n\n# Sensors\necho \"Sensor history of last ${SENSOR_HISTORY}s at dump:\" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --history $SENSOR_HISTORY >> $LOG_FILE 2>&1\n\necho \"Sensor threshold at dump: \" >> $LOG_FILE 2>&1\n/usr/local/bin/sensor-util all --threshold >> $LOG_FILE 2>&1\n\n# dwr\n$DUMP_SCRIPT dwr >> $LOG_FILE 2>&1\n\n# rename the archieve file based on whether dump in DWR mode or not\nif [ \"$?\" == \"2\" ]; then\n  LOG_ARCHIVE='/mnt/data/autodump_dwr.tar.gz'\n  LOG_MSG_PREFIX=\"DWR \"\nelse\n  LOG_ARCHIVE='/mnt/data/autodump_second.tar.gz'\n  LOG_MSG_PREFIX=\"SECOND_DUMP \"\nfi\n\necho -n \"Auto Dump End at \" >> $LOG_FILE\ndate >> $LOG_FILE\n\ntar zcf $LOG_ARCHIVE -C `dirname $LOG_FILE` `basename $LOG_FILE` && \\\nrm -rf $LOG_FILE && \\\nlogger -t \"ipmid\" -p daemon.crit \"${LOG_MSG_PREFIX}Crashdump for FRU: 1 is generated at $LOG_ARCHIVE\"\n\n# Remove current pid file\nrm $PID_FILE\n\necho \"${LOG_MSG_PREFIX}Auto Dump Stored in $LOG_ARCHIVE\"\nexit 0\n", "num_lines": 133}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          eth0_mac_fixup.sh\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Fixup the MAC address for eth0 based on wedge EEPROM\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\necho \"eth0 mac fixup\"\n# get the MAC from u-boot environment\nethaddr=$(fw_printenv ethaddr 2>/dev/null | cut -d'=' -f2 2>/dev/null)\n\nif [ -n \"$ethaddr\" ]; then\n    echo \"ethaddr=\" $ethaddr\n    #  use the one from u-boot environment\n    mac=\"$ethaddr\"\nfi\n\nif [ -n \"$mac\" ]; then\n    echo \"use u-boot mac addr\"\n    ifconfig eth0 hw ether $mac\nelse\n    echo \"no MAC in u-boot environment,  use randomly generated one\"\n    # no MAC in u-boot environment, use randomly generated one\n    mac=$(ifconfig eth0 2>/dev/null |grep HWaddr 2>/dev/null |awk '{ print $5 }')\n\nfi\n\nif [ \"$ethaddr\" != \"$mac\" ]; then\n    # set the MAC from ifconfig back to u-boot environment so that u-boot\n    # can use it\n    echo \"save mac addr\" $mac \"to u-boot\"\n    fw_setenv \"ethaddr\" \"$mac\"\nfi\n", "num_lines": 57}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          power-on\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\nKEYDIR=/mnt/data/kv_store\nDEF_PWR_ON=1\nTO_PWR_ON=\n\ncheck_por_config()\n{\n\n  TO_PWR_ON=-1\n\n  # Check if the file/key doesn't exist\n  if [ ! -f \"${KEYDIR}/server_por_cfg\" ]; then\n    TO_PWR_ON=$DEF_PWR_ON\n  else\n    POR=`cat ${KEYDIR}/server_por_cfg`\n\n    # Case ON\n    if [ $POR == \"on\" ]; then\n      TO_PWR_ON=1;\n\n    # Case OFF\n    elif [ $POR == \"off\" ]; then\n      TO_PWR_ON=0;\n\n    # Case LPS\n    elif [ $POR == \"lps\" ]; then\n\n      # Check if the file/key doesn't exist\n      if [ ! -f \"${KEYDIR}/pwr_server_last_state\" ]; then\n        TO_PWR_ON=$DEF_PWR_ON\n      else\n        LS=`cat ${KEYDIR}/pwr_server_last_state`\n        if [ $LS == \"on\" ]; then\n          TO_PWR_ON=1;\n        elif [ $LS == \"off\" ]; then\n          TO_PWR_ON=0;\n        fi\n      fi\n    fi\n  fi\n  logger -s \"TO_PWR_ON:$TO_PWR_ON, POR:$POR, LS:$LS\"\n}\n\n# Check whether it is fresh power on reset\n#if [ $(is_bmc_por) -eq 1 ]; then\n  ## Move por to U-boot\n  #check_por_config\n  #if [ $TO_PWR_ON -eq 1 ] ; then\n  #  power-util mb on\n  #fi\n#fi\n", "num_lines": 82}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nusage() {\n    echo \"Usage: $1 <on | off>\"\n    exit -1\n}\n\n. /usr/local/fbpackages/utils/ast-functions\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\nset -e\n\nif [ $# != 1 ]; then\n    usage $0\nfi\n\n# S: GPIOAA2()??\ngpio=AA2\n\n\nif [ $1 = \"on\" ]; then\n    val=0\nelif [ $1 = \"off\" ]; then\n    val=1\nelse\n    usage $0\nfi\n\ngpio_set $gpio $val\n", "num_lines": 49}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          gpio-setup\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description:  Set up GPIO pins as appropriate\n### END INIT INFO\n\n# This file contains definitions for the GPIO pins that were not otherwise\n# defined in other files.  We should probably move some more of the\n# definitions to this file at some point.\n\n# The commented-out sections are generally already defined elsewhere,\n# and defining them twice generates errors.\n\n# The exception to this is the definition of the GPIO H0, H1, and H2\n# pins, which seem to adversely affect the rebooting of the system.\n# When defined, the system doesn't reboot cleanly.  We're still\n# investigating this.\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Set up to read the board revision pins, GPIOD1(25), GPIOD3 (27), GPIOD5 (29)\ndevmem_clear_bit $(scu_addr 90) 1\ndevmem_clear_bit $(scu_addr 70) 21\n\ndevmem_clear_bit $(scu_addr 8c) 8\ndevmem_clear_bit $(scu_addr 8c) 9\ndevmem_clear_bit $(scu_addr 8c) 10\n\ngpio_export D1\ngpio_export D3\ngpio_export D5\n\nBOARD_REV=$(( $(gpio_get D1) + ($(gpio_get D3)<<1) + ($(gpio_get D5)<<2) ))\n\n# FM_PWR_BTN_N, Server power button in, on GPIO E2(34)\n# To enable GPIOE2, SCU80[18], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 18\ndevmem_clear_bit $(scu_addr 8C) 13\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export E2\n\n# FM_BMC_PWRBTN_OUT_N, power button to Server, on GPIO E3(35)\n# To enable GPIOE3, SCU80[19], SCU8C[13], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 19\n\ngpio_set E3 1\n\n# PWRGD_SYS_PWROK, power GOOD , on GPIO B6(14)\n# To enable GPIOB6, SCU80[14] must be 0\ndevmem_clear_bit $(scu_addr 80) 14\n\ngpio_export B6\n\n# LED_POST_CODE_0: GPIOH0 (56)\n# To use GPIOH0, SCU90[6], SCU90[7], SCU10[8], SCU94[5] must be 0\ndevmem_clear_bit $(scu_addr 90) 6\ndevmem_clear_bit $(scu_addr 90) 7\ndevmem_clear_bit $(scu_addr 10) 8\ndevmem_clear_bit $(scu_addr 94) 5\n\ngpio_set H0 1\n\n# LED_POST_CODE_1: GPIOH1 (57)\n# To use GPIOH1, SCU90[6], SCU90[7], SCU10[8], SCU94[5]  must be 0\ngpio_set H1 1\n\n# LED_POST_CODE_2: GPIOH2 (58)\n# To use GPIOH2, SCU90[6], SCU90[7], SCU10[8], SCU94[6]  must be 0\ndevmem_clear_bit $(scu_addr 94) 6\ngpio_set H2 1\n\n# LED_POST_CODE_3: GPIOH3 (59)\n# To use GPIOH3, SCU90[6], SCU90[7], SCU10[8], SCU94[6] must be 0\ngpio_set H3 1\n\n# LED_POST_CODE_4, GPIOH4 (60)\n# GPIOH4(60): SCU90[6], SCU90[7], SCU10[8], SCU94[7] shall be 0\ndevmem_clear_bit $(scu_addr 94) 7\ngpio_set H4 1\n\n#LED_POST_CODE_5, GPIOH5 (61)\n# GPIOH5(61): SCU90[6], SCU90[7], SCU10[8], SCU94[7] shall be 0\ngpio_set H5 1\n\n# LED_POST_CODE_6, GPIOH6 (62)\n# GPIOH6(62): SCU90[6], SCU90[7], SCU10[8] shall be 0\ngpio_set H6 1\n\n# LED_POST_CODE_7, GPIOH7 (63)\n# GPIOH7(63): SCU90[6], SCU90[7], SCU10[8] shall be 0\ngpio_set H7 1\n\n# FM_POST_CARD_PRES_BMC_N: GPIOQ6 (134)\ndevmem_clear_bit $(scu_addr 90) 28\n\n# Set debounce timer #1 value to 0x12E1FC ~= 100ms\n$DEVMEM 0x1e780050 32 0x12E1FC\n\n# Select debounce timer #1 for GPIOQ6\ndevmem_clear_bit 0x1e780130 6\ndevmem_set_bit 0x1e780134 6\n\ngpio_export Q6\n\n# BMC_HEARTBEAT_N, heartbeat LED, GPIO U5(165)\n# GPIOU5(165): SCUA0[13] shall be 1\n\n# U5 is shared with RGMII1RXCTL - do not make it a GPIO\n# devmem_set_bit $(scu_addr A0) 13\n\n# U5 is shared with RGMII1RXCTL - do not make it a GPIO\n# gpio_set U5 1\n\n#gpio_set Q7 0\n\n# System SPI\n# Strap 12 must be 0 and Strape 13 must be 1\n#devmem_clear_bit $(scu_addr 70) 12\n#devmem_set_bit $(scu_addr 70) 13\n\n# Power LED for Server:\n# To use GPIOAA2 (210), SCUA4[26],  must be 0\ndevmem_clear_bit $(scu_addr A4) 26\n\ngpio_set AA2 1\n\n# Identify LED for Slot#1:\n# To use GPIOF1 (41), SCU80[25], SCUA4[12], must be 0\n#devmem_clear_bit $(scu_addr 80) 25\n#devmem_clear_bit $(scu_addr A4) 12\n\n#gpio_set F1 1\n# Front Panel Hand Switch GPIO setup\n# HAND_SW_ID1: GPIOR2(138)\n# To use GPIOR2, SCU88[26] must be 0\n#devmem_clear_bit $(scu_addr 88) 26\n\n#gpio_export R2\n\n# HAND_SW_ID2: GPIOR3(139)\n# To use GPIOR3, SCU88[27] must be 0\n#devmem_clear_bit $(scu_addr 88) 27\n\n#gpio_export R3\n\n# HAND_SW_ID4: GPIOR4(140)\n# To use GPIOR4, SCU88[28] must be 0\n#devmem_clear_bit $(scu_addr 88) 28\n\n#gpio_export R4\n\n\n# HAND_SW_ID8: GPIOR5(141)\n# To use GPIOR5, SCU88[29] must be 0\n#devmem_clear_bit $(scu_addr 88) 29\n\n#gpio_export R5\n\n# LED POST CODES: 8 GPIO signals\n\n# LED_POSTCODE_0: GPIOG0 (48)\n# To use GPIOG0, SCU84[0] must be 0\n#devmem_clear_bit $(scu_addr 84) 0\n\n#gpio_set G0 0\n\n# LED_POSTCODE_1: GPIOG1 (49)\n# To use GPIOG1, SCU84[1] must be 0\n#devmem_clear_bit $(scu_addr 84) 1\n\n#gpio_set G1 0\n\n# LED_POSTCODE_2: GPIOG2 (50)\n# To use GPIOG2, SCU84[2] must be 0\n#devmem_clear_bit $(scu_addr 84) 2\n\n#gpio_set G2 0\n\n# LED_POSTCODE_4: GPIOP4 (124)\n#gpio_set P4 0\n\n# LED_POSTCODE_5: GPIOP5 (125)\n#gpio_set P5 0\n\n# LED_POSTCODE_6: GPIOP6 (126)\n# To use GPIOP6, SCU88[22] must be 0\n#devmem_clear_bit $(scu_addr 88) 22\n\n#gpio_set P6 0\n\n# LED_POSTCODE_7: GPIOP7 (127)\n# To use GPIOP7, SCU88[23] must be 0\n#devmem_clear_bit $(scu_addr 88) 23\n\n#gpio_set P7 0\n\n# BMC_READY_N: GPIOS1 (145)\n# To use GPIOS1, SCU8C[1] must be 0\ndevmem_clear_bit $(scu_addr 8C) 1\n\n# Disable GPIO and enable it from\n# KCS\ngpio_set S1 1\n\n# BMC_RST_BTN_IN_N: GPIOS0 (144)\n# To use GPIOS0, SCU8C[0]\n#devmem_clear_bit $(scu_addr 8c) 0\n\n#gpio_export S0\n\n# RESET for all Slots\n# RST_SLOT1_SYS_RESET_N: GPIOH1 (57)\n# To use GPIOH1, SCU90[6], SCU90[7] must be 0\n#devmem_clear_bit $(scu_addr 90) 6\n#devmem_clear_bit $(scu_addr 90) 7\n\n#gpio_set H1 1\n\n# 12V_STBY Enable for Slots\n\n# P12V_STBY_SLOT1_EN: GPIOO5 (117)\n# To use GPIOO5, SCU88[13] must be 0\n#devmem_clear_bit $(scu_addr 88) 13\n\n#gpio_set O5 1\n\n# PWRGD_P12V_STBY_SLOT1: GPIOP1 (121)\n# To use GPIOP1, SCU88[17] must be 0\n#devmem_clear_bit $(scu_addr 88) 17\n#gpio_export P1\n\n# Enable the the EXTRST functionality of GPIOB7\n#devmem_set_bit $(scu_addr 80) 15\n#devmem_clear_bit $(scu_addr 90) 31\n#devmem_set_bit $(scu_addr 3c) 3\n\n\n# Disable PWM reset during external reset\ndevmem_clear_bit $(scu_addr 9c) 17\n# Disable PWM reset during WDT1 reset\ndevmem_clear_bit 0x1e78501c 17\n\n# FM_BATTERY_SENSE_EN_N: GPIOF6 (46)\n# To use GJPIOF6, SCU80[30] must be 0\ndevmem_clear_bit $(scu_addr 80) 30\ngpio_set F6 1\n\n# FM_BIOS_MRC_DEBUG_MSG_DIS_N: GPIOD0 (24)\n# To use GJPIOD0, SCU90[1] must be 0\ndevmem_clear_bit $(scu_addr 90) 1\ngpio_set D0 1\n\n# Platform ID check pin\ndevmem_clear_bit $(scu_addr 88) 16\ndevmem_clear_bit $(scu_addr 88) 17\ndevmem_clear_bit $(scu_addr 88) 18\ndevmem_clear_bit $(scu_addr 88) 19\ndevmem_clear_bit $(scu_addr 88) 20\n\n# R6 and R7 are used for RGMII1RXD,\n#  Do not make them GPIO\n#devmem_clear_bit $(scu_addr 88) 30\n#devmem_clear_bit $(scu_addr 88) 31\n\ngpio_export P0\ngpio_export P1\ngpio_export P2\ngpio_export P3\ngpio_export P4\n\n# R6 and R7 are used for RGMII1RXD,\n#  Do not make them GPIO\n#gpio_export R6\n#gpio_export R7\n\n# HSC_SMBUS_SWITCH_EN: GPIOS3 (147)\n# To use GPIOS3, SCU8C[3] must be 0\ndevmem_clear_bit $(scu_addr 8C) 3\n\ngpio_export S3\n\n# FM_FAST_PROCHOT_EN_N: GPIOV3 (171)\n# To use GPIOV3, SCUA0[19] must be 1\ndevmem_set_bit $(scu_addr A0) 19\n\ngpio_set V3 0\n\n# FM_OC_DETECT_EN_N: GPIOM3 (99)\n# To use GPIOM3, SCU84[27] must be 0\ndevmem_clear_bit $(scu_addr 84) 27\n\ngpio_set M3 0\n\n# UV_HIGH_SET: GPIOAA5(???)\n# To use GIOAA5, SCUA4[29] must be 0\ndevmem_clear_bit $(scu_addr A4) 29\n\ngpio_export AA5\n\n# FM_PCH_BMC_THERMTRIP_N: GPIOG2 (50)\n# To use GPIOG2, SCU84[2] must be 0\ndevmem_clear_bit $(scu_addr 84) 2\n\ngpio_export G2\n\n# FM_BIOS_SMI_ACTIVE_N: GPIOG7 (55)\ngpio_export G7\n\n# FM_PMBUS_ALERT_BUF_EN_N: GPIOL5 (93)\n# To use GPIOG2, SCU84[21] and SCU90[5] must be 0\ndevmem_clear_bit $(scu_addr 84) 21\ndevmem_clear_bit $(scu_addr 90) 5\n\ngpio_set L5 0\n\n# FM_CPU0_PROCHOT_LVT3_ BMC_N, on GPIO E6(38)\n# To enable GPIOE6, SCU80[22], SCU8C[15], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 22\ndevmem_clear_bit $(scu_addr 8C) 15\ndevmem_clear_bit $(scu_addr 70) 22\n\ngpio_export E6\n\n# FM_CPU1_PROCHOT_LVT3_ BMC_N, on GPIO E7(39)\n# To enable GPIOE7, SCU80[23], SCU8C[15], and SCU70[22] must be 0\ndevmem_clear_bit $(scu_addr 80) 23\n\ngpio_export E7\n\n# RST_BMC_SYSRST_BTN_OUT_N, power reset to Server, on GPIO E1(33)\ndevmem_clear_bit $(scu_addr 80) 17\n\ngpio_set E1 1\n\n# Disable JTAG Engine\ndevmem_clear_bit $(jtag_addr 08) 30\ndevmem_clear_bit $(jtag_addr 08) 31\n\n# FM_CPU_MSMI_LVT3_N\ndevmem_clear_bit $(scu_addr 88) 3\ngpio_export N3\n\n# FM_CPU_CATERR_LVT3_N\ndevmem_clear_bit $(scu_addr 84) 1\ngpio_export G1\n\n# FM_GLOBAL_RST_WARN_N\ndevmem_set_bit $(scu_addr A4) 3\n# H_CPU0_MEMABC_MEMHOT_LVT3_BMC_N\ndevmem_set_bit $(scu_addr A4) 4\n# H_CPU0_MEMDEF_MEMHOT_LVT3_BMC_N\ndevmem_set_bit $(scu_addr A4) 5\n# H_CPU1_MEMGHJ_MEMHOT_LVT3_BMC_N\ndevmem_set_bit $(scu_addr A4) 6\n# H_CPU1_MEMKLM_MEMHOT_LVT3_BMC_N\ndevmem_set_bit $(scu_addr A4) 7\n\n# Intel remote BMC debug function pins\n# GPIOP5 BMC_PREQ_N\ndevmem_clear_bit $(scu_addr 88) 21\ngpio_set P5 1\n# GPIOP6 BMC_PWR_DEBUG_N\ndevmem_clear_bit $(scu_addr 88) 22\n# gpio_set P6 1\n\n# GPIOP7 RST_RSMRST_N\ndevmem_clear_bit $(scu_addr 88) 23\ngpio_export P7\n# GPIOB1 BMC_DEBUG_EN_N\ngpio_export B1\n# GPIOR2 BMC_TCK_MUX_SEL\ndevmem_clear_bit $(scu_addr 88) 26\ngpio_export R2\n# GPIOR3 BMC_PRDY_N\ndevmem_clear_bit $(scu_addr 88) 27\ngpio_export R3\n# GPIOR4 BMC_XDP_PRSNT_IN_N\ndevmem_clear_bit $(scu_addr 88) 28\ngpio_export R4\n# GPIOR5 RST_BMC_PLTRST_BUF_N\ndevmem_clear_bit $(scu_addr 88) 29\ngpio_export R5\n# GPIOY2 BMC_JTAG_SEL\ndevmem_clear_bit $(scu_addr A4) 10\ndevmem_clear_bit $(scu_addr 94) 11\ngpio_set Y2 1\n\n# FM_CPU0_SKTOCC_LVT3_N\ndevmem_clear_bit $(scu_addr 84) 3\ngpio_export G3\n\n# FM_CPU1_SKTOCC_LVT3_N\ndevmem_clear_bit $(scu_addr A4) 24\ngpio_export AA0\n\n# FM_BIOS_POST_CMPLT_N\ndevmem_clear_bit $(scu_addr A4) 31\ngpio_export AA7\n\n# PECI_MUX_SELECT\nif [ $BOARD_REV -le 2 ]; then\n  # Power-On, EVT, preDVT\n  devmem_clear_bit $(scu_addr A8) 2\n  gpio_set AB2 0\nelse\n  # DVT or newer\n  devmem_clear_bit $(scu_addr A4) 28\n  gpio_set AA4 0\nfi\n\n# BMC_CPLD_FPGA_SEL: GPIOA0\ndevmem_clear_bit $(scu_addr 80) 0\ngpio_set A0 1\n\n# FM_SLPS4_N: GPIOY1\ndevmem_clear_bit $(scu_addr A4) 9\ndevmem_clear_bit $(scu_addr 94) 10\ngpio_export Y1\n\n# FW_UV_ADR_TRIGGER_EN: GPIOI3\ngpio_set I3 1\n\n# FW_FORCE_ADR_N: GPIOI2\ngpio_set I2 1\n\n# IRQ_DIMM_SAVE_LVT3_N\ngpio_export D4\n\n# FM_OCP_MEZZA_PRES: GPIOAB1\ndevmem_clear_bit $(scu_addr A8) 1\ngpio_export AB1\n\n# FM_UARTSW_MSB_N:\ndevmem_clear_bit $(scu_addr 90) 27\n\ngpio_export Q4\ngpio_export Q5\n", "num_lines": 462}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n### BEGIN INIT INFO\n# Provides:          setup-por\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on Server\n### END INIT INFO\n. /usr/local/fbpackages/utils/ast-functions\n\nstore_clear_por\n\n", "num_lines": 32}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-consoled\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup console history buffering\n### END INIT INFO\n\n# Enable AST SNOOP DMA with default port 80\necho 1 > /sys/devices/platform/ast-snoop-dma.0/enable\n\n", "num_lines": 33}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\n\n# Sync BMC's date with the server\nsync_date()\n{\n  # if no ntp peer has been declared the system peer\n  if ! /usr/sbin/ntpq -p | grep '^\\*' > /dev/null ; then\n    echo Syncing up BMC time with server...\n    # Use standard IPMI command 'get-sel-time' to read RTC time\n    date -s @$((16#$(/usr/local/bin/me-util 0x28 0x48 | awk '{print $4$3$2$1}')))\n  fi\n}\n\nsync_date\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nARGS=\"--json /etc/platform-svcd-config.json\"\nexec /usr/local/bin/platform-svcd $ARGS\n", "num_lines": 25}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          platform-svcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: dbus based platform service\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\necho -n \"Setup platform svcd for Portwell Neptune... \"\n\nrunsv /etc/sv/platform-svcd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-sensord\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup sensor monitoring\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util mb --version\" once before sensor monitoring to store vr information\n# echo \"Get MB FW version... \"\n# /usr/bin/fw-util mb --version > /dev/null\n\nif [ $(cat /sys/class/gpio/gpio120/value) == \"0\" ]; then\n  ln -s /etc/sensor-correction-sku0-conf.json /etc/sensor-correction-conf.json\nelse\n  ln -s /etc/sensor-correction-sku1-conf.json /etc/sensor-correction-conf.json\nfi\n\n# echo -n \"Setup sensor monitoring for FBTP... \"\n\n# runsv /etc/sv/sensord > /dev/null 2>&1 &\n\n# echo \"done.\"\n", "num_lines": 47}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-setup\n# Required-Start:    power-on\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Power on micro-server\n### END INIT INFO\n\n# Eventually, this will be used to configure the various (mostly\n# i2c-based) sensors, once we have a kernel version that supports\n# doing this more dynamically.\n#\n# For now, we're using it to install the lm75 and pmbus module so that it\n# can detect the fourth temperature sensor, which is located\n# on the uServer, which doesn't get power until power-on executes.\n#\n# Similarly, the pmbus sensor seems to have an easier time of\n# detecting the NCP4200 buck converters after poweron.  This has not\n# been carefully explored.\n\nmodprobe lm75\nmodprobe pmbus\n\n# Enable the ADC inputs;  adc0 - adc7 are connected to various voltage sensors\n\necho 1 > /sys/devices/platform/ast_adc.0/adc0_en\necho 1 > /sys/devices/platform/ast_adc.0/adc1_en\necho 1 > /sys/devices/platform/ast_adc.0/adc2_en\necho 1 > /sys/devices/platform/ast_adc.0/adc3_en\necho 1 > /sys/devices/platform/ast_adc.0/adc4_en\necho 1 > /sys/devices/platform/ast_adc.0/adc5_en\necho 1 > /sys/devices/platform/ast_adc.0/adc6_en\necho 1 > /sys/devices/platform/ast_adc.0/adc7_en\n", "num_lines": 55}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n. /usr/local/fbpackages/utils/ast-functions\n\nexec /usr/local/bin/sensor-svcd\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          sensor-svcd\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: dbus based sensor service\n### END INIT INFO\n\n. /usr/local/fbpackages/utils/ast-functions\n\n# Call \"fw-util mb --version\" once before sensor monitoring to store vr information\necho \"Get MB FW version... \"\n/usr/bin/fw-util mb --version > /dev/null\n\necho -n \"Setup sensor svcd for FBTP... \"\n\nrunsv /etc/sv/sensor-svcd > /dev/null 2>&1 &\n\necho \"done.\"\n", "num_lines": 41}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          usbcons\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:      0 6\n# Short-Description: Creates a virtual USB serial device and starts a console\n#                    on it.\n#\n### END INIT INFO\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin\nNAME=usbcons\nPIDFILE=/run/usbcons.pid\nDESC=\"USB Serial Console\"\n\n# source function library\n. /etc/init.d/functions\n\nSTOPPER=\nACTION=\"$1\"\n\ncase \"$ACTION\" in\n  start)\n    # Ability to prevent this from starting by editing cmdline in u-boot.\n    # Keeping this here until I get gadget switching working properly. (t4906522)\n    if grep \"nousbcons\" /proc/cmdline > /dev/null 2>&1\n    then\n      echo \"USB Console Disabled.\"\n      exit 0\n    fi\n    echo -n \"Starting $DESC: \"\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  stop)\n    echo -n \"Stopping $DESC: \"\n    killall usbmon.sh\n    echo \"$NAME.\"\n    ;;\n  restart|force-reload)\n    echo -n \"Restarting $DESC: \"\n    killall usbmon.sh\n    sleep 1\n    /usr/local/bin/usbmon.sh > /dev/null 2>&1 &\n    echo \"$NAME.\"\n    ;;\n  status)\n    status $DAEMON\n    exit $?\n    ;;\n  *)\n    N=${0##*/}\n    N=${N#[SK]??}\n    echo \"Usage: $N {start|stop|status|restart|force-reload}\" >&2\n    exit 1\n    ;;\nesac\n\nexit 0\n", "num_lines": 81}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\nmodprobe g_cdc host_addr=02:00:00:00:00:02 dev_addr=02:00:00:00:00:01\n# For g-ether interface, if the remote side brings down the interface, BMC side\n# still treats it as up. In this case, all packets through usb0 (i.e. NDP) will\n# be queued in the kernel for this interface. Ether interface has the default\n# TX queue length as 1000, which means there could be up to 1000 package queued\n# in kernel for that. In our case, kmalloc-192 is exhausted when 298 packets\n# are queued.\n# To solve this issue, we change the TX queue length for usb0 to 64 to avoid\n# memory exhaust.\nifconfig usb0 txqueuelen 64\nwhile true; do\n    getty /dev/ttyGS0 57600\n    sleep 1\ndone\n", "num_lines": 35}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2014-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nPATH=/sbin:/bin:/usr/sbin:/usr/bin:/usr/local/bin\n\n# setup ADC channels\n\nADC_PATH=\"/sys/devices/platform/ast_adc.0\"\n# channel 0: r1: 2.87K; r2:  2.0K; v2: 0mv\n# channel 1: r1: 5.36K; r2:  2.0K; v2: 0mv\n# channel 2: r1: 15.8K; r2:  2.0K; v2: 0mv\n# channel 3: r1:  1.0K; r2:    NA; v2: 0mv # No voltage divider\n# channel 4: r1:  1.0K; r2:    NA; v2: 0mv # No voltage divider\n# channel 5: r1: 2.87K; r2:  2.0K; v2: 0mv\n# channel 6: r1: 5.36K; r2:  2.0K; v2: 0mv\n# channel 7: r1:  200K; r2:  100K; v2: 0mv\n\nconfig_adc() {\n    channel=$1\n    r1=$2\n    r2=$3\n    v2=$4\n    echo $r1 > ${ADC_PATH}/adc${channel}_r1\n    echo $r2 > ${ADC_PATH}/adc${channel}_r2\n    echo $v2 > ${ADC_PATH}/adc${channel}_v2\n    echo 1 > ${ADC_PATH}/adc${channel}_en\n}\nconfig_adc 0  287 200 0\nconfig_adc 1  536 200 0\nconfig_adc 2 1580 200 0\nconfig_adc 3    0   1 0\nconfig_adc 4    0   1 0\nconfig_adc 5  287 200 0\nconfig_adc 6  536 200 0\nconfig_adc 7  400 200 0\n", "num_lines": 52}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2015-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n#\n\n### BEGIN INIT INFO\n# Provides:          setup-crond\n# Required-Start:\n# Required-Stop:\n# Default-Start:     S\n# Default-Stop:\n# Short-Description: Setup crond history buffering\n### END INIT INFO\n\n# TODO: check for the if slot/server is present before starting the daemon\necho -n \"Setup crond...\"\n  mkdir /etc/cron\n  mkdir /etc/cron/crontabs\n  echo \"0 * * * * run-parts /etc/cron.daily\" > /etc/cron/crontabs/root\n  /etc/init.d/busybox-cron start\necho \"done.\"\n", "num_lines": 37}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#  Copyright (c) 2014-present, Facebook, Inc.\n#  All rights reserved.\n#\n#  This source code is licensed under the BSD-style license found in the\n#  LICENSE file in the root directory of this source tree. An additional grant\n#  of patent rights can be found in the PATENTS file in the same directory.\n\nset -e\n\nSOURCE=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nSCRIPTS=\"$SOURCE/../tools/signing\"\n\n# Option parsing.\nif [ \"$#\" -lt 3 ]; then\n  echo \"Invalid parameters:\"\n  echo \"./build.sh POKY_BUILD INPUT_FLASH OUTPUT_DIR [-e]\"\n  echo \"\"\n  echo \"  POKY_BUILD: Directory of build-dir within poky\"\n  echo \"  INPUT_FLASH: The input flash-BOARD file\"\n  echo \"  OUTPUT_DIR: Existing directory that will contain output flashes\"\n  echo \"  [-e] Create failure tests from a signed input-flash\"\n  exit 1\nfi\n\n# Run a series of tests for installed applications.\nPYTHON=`which python2 || true`\nif [ \"$PYTHON\" = \"\" ]; then\n  echo \"Error: cannot find 'python2'\"\n  exit 1\nfi\n\nDTC=`which dtc || true`\nif [ \"$DTC\" = \"\" ]; then\n  echo \"Error: cannot find 'dtc' (please install device-tree-compiler)\"\n  exit 1\nfi\n\nOPENSSL=`which openssl || true`\nif [ \"$OPENSSL\" = \"\" ]; then\n  echo \"Error: cannot find 'openssl'\"\n  exit 1\nfi\n\nPYCRYPTO=`$PYTHON -c 'import Crypto' 2>&1 &> /dev/null; echo $?`\nif [ ! \"$PYCRYPTO\" = \"0\" ]; then\n  echo \"Error: Python ($PYTHON) cannot import 'Crypto' (install python-crypto)\"\n  exit 1\nfi\n\nJINJA2=`$PYTHON -c 'import jinja2' 2>&1 &> /dev/null; echo $?`\nif [ ! \"$JINJA2\" = \"0\" ]; then\n  echo \"Error: Python ($PYTHON) cannot import 'jinja2' (install python-jinja2)\"\n  exit 1\nfi\n\nPOKY_BUILD=\"$1\"\nif [ ! -d \"$POKY_BUILD\" ]; then\n  echo \"Error: the POKY_BUILD argument ($POKY_BUILD) does not exist?\"\n  exit 1\nfi\n\nMKIMAGE=\"$POKY_BUILD/tmp/sysroots/x86_64-linux/usr/bin/mkimage\"\nif [ ! -f \"$MKIMAGE\" ]; then\n  echo \"Error: cannot find mkimage at ($MKIMAGE) have you run 'bitbake MACHINE-image'?\"\n  echo \"Error: you should run 'bitbake' in the ($POKY_BUILD) directory first\"\n  exit 1\nfi\n\nINPUT_FLASH=\"$2\"\nif [ ! -f \"$INPUT_FLASH\" ]; then\n  echo \"Error: the INPUT_FLASH argument ($INPUT_FLASH) does not exist?\"\n  exit 1\nfi\nINPUT_NAME=`basename $INPUT_FLASH`\n\nOUTPUT_DIR=\"$3\"\nOUTPUT_DIR=`realpath $OUTPUT_DIR || echo $OUTPUT_DIR`\n\nEASY_TESTS=0\nif [ ! -z \"$4\" ]; then\n  EASY_TESTS=1\nfi\n\nDIRTY=`find $OUTPUT_DIR | wc -l`\nif [ ! \"$DIRTY\" = \"1\" ]; then\n  echo \"Note: the OUTPUT_DIR ($OUTPUT_DIR) is not empty...\"\nfi\n\nif [ ! -d \"$OUTPUT_DIR\" ]; then\n  echo \"Error: the OUTPUT_DIR argument ($OUTPUT_DIR) does not exist?\"\n  exit 1\nfi\n\n# Output all of the discovered paths.\necho -e \"Using scripts: \\t$SCRIPTS\"\necho -e \"Using build: \\t$POKY_BUILD\"\necho -e \"Using flash: \\t$INPUT_FLASH\"\necho -e \"Using output: \\t$OUTPUT_DIR\"\necho -e \"Using python2: \\t$PYTHON\"\necho -e \"Using dtc: \\t$DTC\"\necho -e \"Using openssl: \\t$OPENSSL\"\necho \"\"\n\nfunction easy_corrupt_uboot() {\n  INPUT=$1\n  OUTPUT=$2\n  cp $INPUT $OUTPUT\n  dd if=/dev/random of=$OUTPUT bs=1 seek=540772 count=16 conv=notrunc\n}\n\nfunction easy_corrupt_kernel() {\n  INPUT=$1\n  OUTPUT=$2\n  cp $INPUT $OUTPUT\n  dd if=/dev/random of=$OUTPUT bs=1 seek=921600 count=16 conv=notrunc\n\n}\n\nif [ \"$EASY_TESTS\" = \"1\" ]; then\n  echo \"[+] Creating simple failure case tests\"\n  echo \"\"\n  easy_corrupt_uboot $INPUT_FLASH $OUTPUT_DIR/$INPUT_NAME.corrupt_uboot\n  easy_corrupt_kernel $INPUT_FLASH $OUTPUT_DIR/$INPUT_NAME.corrupt_kernel\n  echo \" Wrote: $OUTPUT_DIR/$INPUT_NAME.corrupt_uboot\"\n  echo \" Wrote: $OUTPUT_DIR/$INPUT_NAME.corrupt_kernel\"\n  exit 0\nfi\n\n# Create the example KEK (ROM root key).\nmkdir -p \"$OUTPUT_DIR/kek\"\nopenssl genrsa -F4 -out \"$OUTPUT_DIR/kek/kek.key\" 4096\nopenssl rsa -in \"$OUTPUT_DIR/kek/kek.key\" -pubout > \"$OUTPUT_DIR/kek/kek.pub\"\necho -e \"\\nCreated KEK (ROM key): $OUTPUT_DIR/kek/kek.{key,pub}\\n\"\n\n# Create the example ODM keypair (U-Boot, Kernel, rootfs signing key).\nmkdir -p \"$OUTPUT_DIR/odm0\"\nopenssl genrsa -F4 -out \"$OUTPUT_DIR/odm0/odm0.key\" 4096\nopenssl rsa -in \"$OUTPUT_DIR/odm0/odm0.key\" -pubout > \"$OUTPUT_DIR/odm0/odm0.pub\"\necho -e \"\\nCreated ODM0 key (used to signed U-Boot and Linux): $OUTPUT_DIR/odm0/odm0.{key,pub}\\n\"\n\nmkdir -p \"$OUTPUT_DIR/odm1\"\nopenssl genrsa -F4 -out \"$OUTPUT_DIR/odm1/odm1.key\" 4096\nopenssl rsa -in \"$OUTPUT_DIR/odm1/odm1.key\" -pubout > \"$OUTPUT_DIR/odm1/odm1.pub\"\necho -e \"\\nCreated (optional) ODM key (used to signed U-Boot and Linux): $OUTPUT_DIR/odm1/odm1.{key,pub}\\n\"\n\nmkdir -p \"$OUTPUT_DIR/subordinates\"\ncp \"$OUTPUT_DIR/odm0/odm0.pub\" \"$OUTPUT_DIR/subordinates\"\ncp \"$OUTPUT_DIR/odm1/odm1.pub\" \"$OUTPUT_DIR/subordinates\"\n\n# Create certificate stores and the signed subordinate store.\n$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in $OUTPUT_DIR/kek $OUTPUT_DIR/kek/kek.dtb\n$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in --subordinate --subtemplate $SCRIPTS/sub.dts.in \\\n  $OUTPUT_DIR/subordinates $OUTPUT_DIR/subordinates/subordinates.dtb\n$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/kek \\\n  $OUTPUT_DIR/subordinates/subordinates.dtb $OUTPUT_DIR/subordinates/subordinates.dtb.signed\n\nmkdir -p $OUTPUT_DIR/flashes\nrm -f $OUTPUT_DIR/flashes/*\n\nFLASH_UNSIGNED=$OUTPUT_DIR/flashes/$INPUT_NAME.unsigned\nFLASH_SIGNED=$OUTPUT_DIR/flashes/${INPUT_NAME}.signed\ncp $INPUT_FLASH $FLASH_UNSIGNED\n\n# Sign the input flash.\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --sign-os \\\n  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm0 $FLASH_UNSIGNED $FLASH_SIGNED\n\n# Time to generate all test cases.\nFLASH_SIGNED=$INPUT_NAME.signed\nFLASH_UNSIGNED=$INPUT_NAME.unsigned\nSIZE=$(ls -l $OUTPUT_DIR/flashes/$FLASH_SIGNED | cut -d \" \" -f5)\nSIZE=$(expr $SIZE / 1024)\n\n# Place all error intermediate assets in ./error\nmkdir -p \"$OUTPUT_DIR/error\"\n\n# 0.0 Success case\necho \"[+] Creating 0.0...\"\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.0.0\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0\n\n# 3.30 Blank CS1\necho \"[+] Creating 3.30...\"\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.3.30\ntouch $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.3.30\ndd if=/dev/zero of=$OUTPUT_DIR/flashes/$INPUT_NAME.CS1.3.30 bs=1k count=$SIZE\n\n# Extract 0x8:0000 - 0x8:4000 (U-Boot FIT) for modifications\ndd if=$OUTPUT_DIR/flashes/$FLASH_SIGNED of=$OUTPUT_DIR/error/u-boot.dtb bs=1k skip=512 count=16\nUBOOT_DTS=$OUTPUT_DIR/error/u-boot.dts\ndtc -I dtb -O dts $OUTPUT_DIR/error/u-boot.dtb -o $UBOOT_DTS\n\n# Extract the OS for modifications\ndd if=$OUTPUT_DIR/flashes/$FLASH_SIGNED of=$OUTPUT_DIR/error/os.dtb bs=1k skip=896\nOS_DTS=$OUTPUT_DIR/error/os.dts\ndtc -I dtb -O dts $OUTPUT_DIR/error/os.dtb -o $OS_DTS\n\nfunction edit_dtb() {\n  SEEK=$1\n  FLASH=$2\n  DTS=$3\n  dtc -f -I dts -O dtb $DTS -o /tmp/edit.dtb\n  dd if=/tmp/edit.dtb of=$FLASH seek=$SEEK bs=1k conv=notrunc\n  rm /tmp/edit.dtb\n}\n\nfunction create_bad_fit() {\n  T=$1\n  N=$2\n  EXPR=\"$3\"\n  if [ \"$T\" = \"os\" ]; then\n    D=$OS_DTS\n    S=896\n  else\n    D=$UBOOT_DTS\n    S=512\n  fi\n\n  echo \"[+] Creating ($T) $N...\"\n  cp $D $OUTPUT_DIR/error/$T.$N.dts\n  sed -i \"$EXPR\" $OUTPUT_DIR/error/$T.$N.dts\n  cp $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.$N\n  edit_dtb $S $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.$N $OUTPUT_DIR/error/$T.$N.dts\n  ln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.$N\n}\n\ncreate_bad_fit \"u-boot\" \"3.31\" 's/images {/images1 {/g'\ncreate_bad_fit \"u-boot\" \"3.32\" 's/images {/images { }; noimages {/g'\ncreate_bad_fit \"u-boot\" \"3.33\" 's/configurations {/configurations1 {/g'\n\n# 34 is difficult, need to remove gd() from CS0\n\ncreate_bad_fit \"u-boot\" \"3.35\" 's/keys {/keys1 {/g'\ncreate_bad_fit \"u-boot\" \"3.36\" 's/data = <0xd00dfeed/data2 = <0xd00dfeed/g'\ncreate_bad_fit \"u-boot\" \"3.37.1\" 's/data-position =/data2-position =/g'\ncreate_bad_fit \"u-boot\" \"3.37.2\" 's/data-size =/data2-size =/g'\ncreate_bad_fit \"u-boot\" \"3.37.3\" 's/data-size = <\\(.*\\)>;/data-size = <0xDDDDDDDD>;/g'\ncreate_bad_fit \"u-boot\" \"3.38\" 's/data = <\\(.*\\)>;/data = <\\1 \\1 \\1 \\1 \\1 \\1 \\1 \\1\\ \\1 \\1 \\1>;/g'\n\n# Generate keys needed for failure cases.\nmkdir -p \"$OUTPUT_DIR/error/kek\"\nopenssl genrsa -F4 -out \"$OUTPUT_DIR/error/kek/kek.key\" 4096\nopenssl rsa -in \"$OUTPUT_DIR/error/kek/kek.key\" -pubout > \"$OUTPUT_DIR/error/kek/kek.pub\"\necho -e \"\\nCreated error-KEK (ROM key): $OUTPUT_DIR/error/kek/kek.{key,pub}\\n\"\n\nmkdir -p \"$OUTPUT_DIR/error/subordinates\"\n$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/error/kek \\\n  $OUTPUT_DIR/subordinates/subordinates.dtb $OUTPUT_DIR/error/subordinates/subordinates.dtb.signed\n\necho \"[+] Creating 4.40...\"\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --signed-subordinate $OUTPUT_DIR/error/subordinates/subordinates.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm0 $OUTPUT_DIR/flashes/$FLASH_UNSIGNED \\\n  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.4.40.1\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.4.40.1\n\ncreate_bad_fit \"u-boot\" \"4.40.2\" 's/key-name-hint = \"kek\"/key-name-hint = \"not-kek\"/g'\ncreate_bad_fit \"u-boot\" \"4.40.3\" 's/data = <0xd00dfeed/data = <0xd00dfefd/g'\n\n# Test-tests\n# create_bad_fit \"u-boot\" \"0.0.1\" 's/key-name-hint = \"odm0\"/key-name-hint = \"odm0\"/g'\n# create_bad_fit \"os\" \"0.0.2\" 's/key-name-hint = \"odm0\"/key-name-hint = \"odm0\"/g'\n\necho \"[+] Creating 4.43...\"\neasy_corrupt_uboot $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.4.43.1\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.4.43.1\n\ncreate_bad_fit \"u-boot\" \"4.43.2\" 's/key-name-hint = \"odm0\"/key-name-hint = \"kek\"/g'\ncreate_bad_fit \"u-boot\" \"4.43.3\" 's/key-name-hint = \"odm0\"/key-name-hint = \"odm1\"/g'\ncreate_bad_fit \"u-boot\" \"4.43.4\" 's/compression = \"none\";/compression = \"none\";\\n\\n\\t\\t\\thash@2 { algo = \"sha256\"; };/g'\n\n# The timestamp is part of the signature.\ncreate_bad_fit \"u-boot\" \"4.43.5\" 's/timestamp = <\\(.*\\)>;/timestamp = <0x10>;/g'\n\nBAD_HASH=\"0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\"\nMATCH='compression = \"none\";\\(.*\\)value = <\\(.*\\)>;\\n\\t\\t\\t\\talgo\\(.*\\)config'\nMATCH=\":a;N;\\$!ba;s/${MATCH}/compression = \\\"none\\\";\\\\1value = \"\nMATCH=\"${MATCH}<${BAD_HASH}>;\\\\n\\\\t\\\\t\\\\t\\\\talgo\\\\3/g\"\ncreate_bad_fit \"u-boot\" \"4.43.6\" \"$MATCH\"\n\ncreate_bad_fit \"os\" \"6.60.1\" 's/key-name-hint = \"odm0\"/key-name-hint = \"bad\"/g'\ncreate_bad_fit \"os\" \"6.60.2\" 's/key-name-hint = \"odm0\"/key-name-hint = \"odm1\"/g'\ncreate_bad_fit \"os\" \"6.60.3\" 's/timestamp = <\\(.*\\)>;/timestamp = <0x10>;/g'\n\necho \"[+] Creating 6.60.4...\"\neasy_corrupt_kernel $OUTPUT_DIR/flashes/$FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.6.60.4\n\necho \"[+] Creating ODM1 signed 0.0.3\"\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm1 $OUTPUT_DIR/flashes/$FLASH_UNSIGNED \\\n  --sign-os \\\n  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0.3\nln -sf $FLASH_SIGNED $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.0.0.3\n\n# Create newly-signed (correct) firmware for fallback checks\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --sign-os \\\n  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm0 \\\n  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0 $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.next.1\n\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --sign-os \\\n  --signed-subordinate $OUTPUT_DIR/subordinates/subordinates.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm0 \\\n  $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.0.0 $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.next.2\n\n# This invalidates the signature but sets the timestamp too far into the future.\ncreate_bad_fit \"u-boot\" \"4.43.5.1\" 's/timestamp = <\\(.*\\)>;/timestamp = <0xEE6B2800>;/g'\n\n# Create a subordinate that does not include the ODM1 key.\n$SCRIPTS/fit-cs --template $SCRIPTS/store.dts.in --subordinate --subtemplate $SCRIPTS/sub.dts.in \\\n  $OUTPUT_DIR/odm0 $OUTPUT_DIR/odm0/odm0.dtb\n$SCRIPTS/fit-signsub --mkimage $MKIMAGE --keydir $OUTPUT_DIR/kek \\\n  $OUTPUT_DIR/odm0/odm0.dtb $OUTPUT_DIR/odm0/odm0.dtb.signed\n\n# Sign an image that does not include the ODM1 key at least 1s into the future.\n$SCRIPTS/fit-sign --mkimage $MKIMAGE --kek $OUTPUT_DIR/kek/kek.dtb \\\n  --sign-os \\\n  --signed-subordinate $OUTPUT_DIR/odm0/odm0.dtb.signed \\\n  --keydir $OUTPUT_DIR/odm0 \\\n  $OUTPUT_DIR/flashes/$INPUT_NAME.unsigned $OUTPUT_DIR/flashes/$INPUT_NAME.CS1.future\nln -sf $INPUT_NAME.CS1.future $OUTPUT_DIR/flashes/$INPUT_NAME.CS0.future\n\necho -e \"\\n\\nThe test firmware images are now located in $OUTPUT_DIR/flashes\"\n", "num_lines": 331}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# This is expected to run in Jenkins.\n# This script is not idempotent.\n\nexport CACHE=\"/var/jenkins/sstate-cache\"\nexport BRANCH=\"krogoth\"\n\nsudo DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::=\"--force-confdef\" -o Dpkg::Options::=\"--force-confold\" dist-upgrade\nsudo apt-get install -y build-essential wget diffstat chrpath texinfo bzip2 libthread-queue-perl cmake bc libgmp-dev device-tree-compiler\n\nmkdir -p \"${CACHE}\"\n\n# Build the TPM emulator\nexport TPM_EMULATOR_BRANCH=hardware-model\n\ngit clone -b $TPM_EMULATOR_BRANCH --depth 1 https://github.com/theopolis/tpm-emulator\n(cd tpm-emulator; ./build.sh)\n\n# Build QEMU.\nexport QEMU_BRANCH=aspeed-mods-i2c-tpm\n\nsudo apt-get install -y libpixman-1-dev zlib1g-dev flex bison libfdt1 libfdt-dev python-pip python-dev python-pexpect pkg-config libglib2.0-dev\nsudo pip install pycrypto jinja2\n\ngit clone -b $QEMU_BRANCH --depth 1 https://github.com/theopolis/qemu\n(\n  cd qemu\n  git clone https://github.com/qemu/dtc\n  ./configure --target-list=arm-softmmu\n  make -j 4\n  cd dtc\n  make clean\n  make dtc\n  sudo ln -fns $(realpath dtc) /usr/local/bin/dtc\n)\nexport QEMU=$PWD/qemu/arm-softmmu/qemu-system-arm\n\n# Checkout and build OpenBMC.\nexport BOARD=fbtp\nexport OPENBMC=$PWD\n\nmkdir -p yocto/$BRANCH\n\n# Clone and change directory into Poky.\ngit clone -b $BRANCH --depth 1 https://git.yoctoproject.org/git/poky yocto/$BRANCH/poky\ngit clone -b $BRANCH --depth 1 https://github.com/openembedded/meta-openembedded.git yocto/$BRANCH/meta-openembedded\ngit clone -b $BRANCH --depth 1 https://git.yoctoproject.org/git/meta-security yocto/$BRANCH/meta-security\n\nsource openbmc-init-build-env meta-facebook/meta-${BOARD} build-${BOARD}\n\necho \"SSTATE_DIR ?= \\\"${CACHE}\\\"\" >> ./conf/local.conf\n\n# Stage the U-Boot build.\nbitbake -f -c fetch u-boot\nbitbake -f -c unpack u-boot\n\n# Patch the code to run in our emulator.\nexport BUILD_DIR=$PWD\nexport UBOOT_WORK=$BUILD_DIR/tmp/work/armv6-fb-linux-gnueabi/u-boot/v2016.07-r0/git\ncp $OPENBMC/tests/verified-boot/qemu-rom.patch ${UBOOT_WORK}/\n(cd $UBOOT_WORK; patch -p1 < qemu-rom.patch)\n\n# Build U-Boot and the image.\nbitbake -f u-boot\nbitbake ${BOARD}-image\n\n# Get back to the OpenBMC checkout.\ncd $OPENBMC\n\n# Run the TPM-emulator.\n(cd tpm-emulator; sudo ./build/tpmd/unix/tpmd -d -s ./data -E)\n\n# Create tests from the output.\nrm -rf /tmp/outputs\nmkdir -p /tmp/outputs\n(cd tests/verified-boot; ./create-tests.sh $BUILD_DIR $BUILD_DIR/tmp/deploy/images/fbtp/flash-${BOARD} /tmp/outputs)\n\n# Run the unit-tests.\n(cd tests/verified-boot; sudo ./run-tests.py --tpm $QEMU /tmp/outputs flash-${BOARD})\n\n# Clean up the TPM-emulator.\npgrep tpmd | sudo xargs kill\n\n", "num_lines": 87}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nINSTALL_LOCATION=~/bin\nif [ ! -z \"$1\" ]; then\n  INSTALL_LOCATION=$1\nfi\n\nif [ ! -d $INSTALL_LOCATION ]; then\n  echo \"WARNING: Creating $INSTALL_LOCATION\"\n  mkdir -p $INSTALL_LOCATION\nfi\n\ndir=$(dirname ${BASH_SOURCE[0]})\nfiles=$(find $dir -name 'bmc*')\nfor file in ${files}; do\n  if [ ! -d $file ]; then\n    cp $file $INSTALL_LOCATION/\n    name=$(basename $file)\n    chmod +x $INSTALL_LOCATION/$name\n  fi\ndone\n", "num_lines": 22}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\nwedge_board_type() {\n    echo '@FBMODEL@'\n}\n\nwedge_board_rev() {\n    # FIXME if needed.\n    return 1\n}\n\nuserver_power_is_on() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n\nuserver_power_on() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n\nuserver_power_off() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n\nuserver_reset() {\n    return 1\n    echo \"FIXME: feature not implemented!!\"\n}\n\nchassis_power_cycle() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n\nbmc_mac_addr() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n\nuserver_mac_addr() {\n    echo \"FIXME: feature not implemented!!\"\n    return 1\n}\n", "num_lines": 63}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n#\n# Create \"pwrcpld\" and scm/chassis EEPROMs.\n#\necho \"FIXME: instantiate I2C client devices in setup_i2c.sh!!\"\n", "num_lines": 24}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script to build flashy for OpenBMC\nset -e\n\n# Ensure we're in the project root\ncd \"$(dirname \"$0\")\"\nrm -rf build\nGOOS=linux GOARCH=arm GOARM=5 go build -ldflags=\"-w -s\" -gcflags=all=\"-l\" -o build/flashy\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script to build flashy for a local system.\nset -e\n\n# Ensure we're in the project root\ncd \"$(dirname \"$0\")\"\nrm -rf build_dev\ngo build -ldflags=\"-w -s\" -gcflags=all=\"-l\" -o build_dev/flashy\n", "num_lines": 26}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script to calculate test coverage in percentage\nset -e\n\n# Ensure we're in the project root\ncd \"$(dirname \"$0\")\" && cd ..\n\n\n# patterns of package paths to exclude\n# NOTE: Please add a comment on why a package is excluded\nexcluded_packages=(\n    # main package, no tests\n    \"github.com/facebook/openbmc/tools/flashy\"\n    # framework code (install)\n    \"github.com/facebook/openbmc/tools/flashy/install\"\n    # file-system side-effect code\n    \"github.com/facebook/openbmc/tools/flashy/lib/fileutils\"\n    # framework code (step)\n    \"github.com/facebook/openbmc/tools/flashy/lib/step\"\n    # test utilities\n    \"github.com/facebook/openbmc/tools/flashy/tests\"\n    # facebook-specific tests\n    \"github.com/facebook/openbmc/tools/flashy/tests/facebook\"\n    # framework code (logger)\n    \"github.com/facebook/openbmc/tools/flashy/lib/logger\"\n    # utilities (wrapper code)\n    \"github.com/facebook/openbmc/tools/flashy/utilities\"\n\n)\n\ninvert_filters=()\nfor i in \"${excluded_packages[@]}\"; do\n    invert_filters+=( \"-e \\\"^${i}$\\\"\" )\ndone\n\nmapfile -t included_packages < \\\n    <(eval \"go list ./... | grep -v ${invert_filters[*]}\")\n\ntmp_dir=$(mktemp -d -t flashy-XXXXXXXXXXX)\n\ngo test ${included_packages[*]} -coverprofile \"${tmp_dir}/cover.out\" > /dev/null\ngo tool cover -func \"${tmp_dir}/cover.out\" | grep total | awk '{print substr($3, 1, length($3)-1)}'\nrm -r \"${tmp_dir}\"\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script on an OpenBMC to upgrade via flashy.\nset -eo pipefail\n\nif [ -d /run/flashy -o ! -d /opt/flashy ]; then\n    # Path to image on OpenBMC\n    openbmc_image_path=\"/run/upgrade/image\"\n    # Path to Flashy on OpenBMC\n    openbmc_flashy_path=\"/run/flashy\"\nelse\n    # Path to image on OpenBMC\n    openbmc_image_path=\"/opt/upgrade/image\"\n    # Path to Flashy on OpenBMC\n    openbmc_flashy_path=\"/opt/flashy\"\nfi\n\nusage=\"Usage:\n$(basename \"$0\") --device DEVICE_ID\n\nRun this script on an OpenBMC to upgrade via flashy.\n\nExample DEVICE_ID: \\\"mtd:flash0\\\"\nFlashy and the image file must already be present in\n$openbmc_flashy_path and $openbmc_image_path respectively.\n\"\n\n# error exit codes for flashy\n# defined in OpenBMC tools/flashy/lib/step/error.go\nFLASHY_ERROR_SAFE_TO_REBOOT=42\nFLASHY_ERROR_UNSAFE_TO_REBOOT=52\nFLASHY_ERROR_BROKEN_SYSTEM=53\nhandle_flashy_error() {\ncase $1 in\n    0)\n    return 0\n    ;;\n    $FLASHY_ERROR_SAFE_TO_REBOOT)\n    echo \"Flashy exited with safe to reboot error $1\" >&2\n    exit \"$1\"\n    ;;\n    $FLASHY_ERROR_UNSAFE_TO_REBOOT)\n    echo \"Flashy exited with unsafe to reboot error $1\" >&2\n    exit \"$1\"\n    ;;\n    $FLASHY_ERROR_BROKEN_SYSTEM)\n    echo \"Flashy exited with broken system error $1\" >&2\n    exit \"$1\"\n    ;;\n    *)\n    echo \"Unknown flashy exit code $1\" >&2\n    exit \"$1\"\n    ;;\nesac\n}\n\n# OpenBMC buildname obtained from /etc/issue\nbuildname=\"\"\ninitialize() {\n    echo \"Getting buildname of device\" >&2\n    buildname=$(sed -n 's/OpenBMC Release //; s/-.*//p' < /etc/issue)\n    echo \"Buildname: $buildname\" >&2\n\n    echo \"Installing flashy\" >&2\n    ${openbmc_flashy_path}/flashy --install \\\n        || handle_flashy_error \"$?\"\n}\n\nrun_checks_and_remediations() {\n    echo \"Getting common checks and remediations...\" >&2\n    local common_steps_output=\"\"\n    common_steps_output=$(find \"${openbmc_flashy_path}/checks_and_remediations/common\" \\\n        -type l -maxdepth 1 | sort) \\\n        || (echo \"Error: no common checks and remediations found\" >&2 \\\n        && exit 1)\n\n    local common_steps=()\n    readarray -t common_steps <<<\"$common_steps_output\"\n\n    echo \"Common checks and remediations:\" >&2\n    echo \"${common_steps[@]}\" | tr ' ' '\\n' >&2\n\n    echo \"Running common checks and remediations\" >&2\n    for step in \"${common_steps[@]}\"\n    do\n        \"$step\" --imagepath \"$openbmc_image_path\" --device \"$device_id\"\\\n        || handle_flashy_error \"$?\"\n    done\n\n\n    echo \"Getting platform-specific checks and remediations...\" >&2\n    local platform_steps_output=\"\"\n    platdir=\"${openbmc_flashy_path}/checks_and_remediations/$buildname\"\n    if [ -d \"$platdir\" ]; then\n        platform_steps_output=\"$(find \"$platdir\" -type l -maxdepth 1 | sort)\"\n    else\n        platform_steps_output=\"\"\n    fi\n\n    if ! [[ $platform_steps_output ]]; then\n        echo \"No platform-specific checks and remediations found\" >&2\n        return 0\n    fi\n\n    local platform_steps=()\n    readarray -t platform_steps <<<\"$platform_steps_output\"\n\n    echo \"Platform-specific checks and remediations:\" >&2\n    echo \"${platform_steps[@]}\" | tr ' ' '\\n' >&2\n\n    echo \"Running platform-specific checks and remediations\" >&2\n    for step in \"${platform_steps[@]}\"\n    do\n        \"$step\" --imagepath \"$openbmc_image_path\" --device \"$device_id\" \\\n        || handle_flashy_error \"$?\"\n    done\n}\n\nrun_flash() {\n    echo \"Starting to flash...\" >&2\n    \"${openbmc_flashy_path}/flash_procedure/flash_$buildname\" \\\n    --imagepath \"$openbmc_image_path\" --device \"$device_id\" \\\n    || handle_flashy_error \"$?\"\n    echo \"Flashing succeeded. It is safe to reboot this system.\" >&2\n}\n\nexit_with_usage() {\n    echo -e \"$usage\" >&2\n    exit 1\n}\n\nexit_argument_required() {\n    echo \"$1 argument is required\" >&2\n    exit_with_usage\n}\n\nexit_file_required() {\n    echo \"$1 not found in '$2'\" >&2\n    exit_with_usage\n}\n\n# Flash device ID to flash (e.g. mtd:flash0)\ndevice_id=\"\"\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n[ -n \"$2\" ] || exit_argument_required \"$1\"\ncase $key in\n    -h|-help|--help)\n    echo -e \"$usage\"\n    exit 0\n    ;;\n    --device)\n    device_id=\"$2\"\n    shift\n    shift\n    ;;\n    *)\n    printf \"Illegal argument %s\\n\" \"$1\" >&2\n    exit_with_usage\n    ;;\nesac\ndone\n\n[ -n \"$device_id\" ] || exit_argument_required \"device\"\n[ -f \"${openbmc_flashy_path}/flashy\" ] || \\\n    exit_file_required \"Flashy\" $openbmc_flashy_path\n[ -f \"$openbmc_image_path\" ] || \\\n    exit_file_required \"Image\" $openbmc_image_path\n\ninitialize\nrun_checks_and_remediations\nrun_flash\n", "num_lines": 190}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script to upgrade a remote OpenBMC.\nset -eo pipefail\n\n# Path to image on OpenBMC\nopenbmc_image_path=\"/run/upgrade/image\"\n# Path to Flashy on OpenBMC\nopenbmc_flashy_path=\"/run/flashy/flashy\"\n# Path to run_flashy upgrade script from project root/release folder\nrun_flashy_script_path=\"scripts/run_flashy.sh\"\n# Path to flashy, empty means build from project root\npath_to_flashy=\"\"\n# Dry run, skips running flashy\ndry_run=\"false\"\n\noptions=\"\"\nsshpassCmd=\"\"\nsshcmd=\"\"\n\nusage=\"Usage:\n$(basename \"$0\") \\\n--device DEVICE_ID --imagepath IMAGE_PATH --host OPENBMC_HOSTNAME --port OPENBMC_HOSTPORT --path-to-flashy PATH_TO_FLASHY (--dry_run)\n\nRun this script to upgrade a remote OpenBMC.\n\nExample DEVICE_ID: \\\"mtd:flash0\\\"\n\nSupply --dry_run to only run the initialize step (does not actually run flashy on the device,\nbut copies over required files.)\n\nIf --port is supplied, it will connect to BMC on that specific host port.\n\nIf --path-to-flashy is supplied, it is assumed that flashy is already built--this is true if you\nare using the prebuilt released flashy.\n\nOtherwise, please run this script in the repository checkout and let the script build\nflashy. Go >= 1.14 must be available on your system.\n\"\n\nscpfile() {\n    file=${1:?Please specify file to scp}\n    dst=${2:?Please specify destination directory}\n    local target=\"\"\n    local scpOptions=(\"${options[@]}\")\n    target=$host\n\n    if [[ \"$target\" =~ .*:.* ]]\n    then\n        target=\"[$host]\"\n    fi\n\n    if [[ -n \"$port\" ]]\n    then\n\t    scpOptions+=(-P \"$port\")\n    fi\n\n    \"${sshpassCmd[@]}\" scp \"${scpOptions[@]}\" \"$file\" \"root@$target:$dst\"\n}\n\ninitialize() {\n    if [[ -z \"$path_to_flashy\" ]]\n    then\n        echo \"path-to-flashy not provided, building flashy...\" >&2\n        ./build.sh\n        path_to_flashy=\"$(realpath \"./build/flashy\")\"\n    else\n        printf \"path-to-flashy provided: %s\\n\" \"$path_to_flashy\" >&2\n    fi\n\n    echo \"Making installation directories on OpenBMC...\" >&2\n    \"${sshcmd[@]}\" \"mkdir -p /run/flashy /run/upgrade\"\n\n    echo \"Copying flashy...\" >&2\n    scpfile \"$path_to_flashy\" \"$openbmc_flashy_path\"\n\n    echo \"Copying image...\" >&2\n    scpfile \"$imagepath\" \"$openbmc_image_path\"\n\n    echo \"Copying upgrade script...\" >&2\n    scpfile \"$run_flashy_script_path\" \"/tmp\"\n}\n\nrun_upgrade() {\n    echo \"Running upgrade...\" >&2\n    \"${sshcmd[@]}\" \"/tmp/run_flashy.sh --device $device_id\"\n}\n\nreboot_and_check_upgrade() {\n    echo \"Flashing complete, rebooting the device...\" >&2\n    \"${sshcmd[@]}\" \"reboot\"\n\n    check_cmd=\"head -n 1 /etc/issue; uptime\"\n\n    while true\n    do\n        echo \"Waiting for reboot...\" >&2\n        sleep 15\n        \"${sshcmd[@]}\" -o ConnectTimeout=15 \"$check_cmd\" && break\n    done\n    echo \"Upgrade done!\" >&2\n}\n\nexit_with_usage() {\n    echo -e \"$usage\" >&2\n    exit 1\n}\n\nexit_argument_required() {\n    echo \"$1 argument is required\" >&2\n    exit_with_usage\n}\n\nexit_file_required() {\n    echo \"$1 not found in '$2'\" >&2\n    exit_with_usage\n}\n\ncheck_second_argument_supplied() {\n    [ -n \"$2\" ] || exit_argument_required \"$1\"\n}\n\n# Flash device ID to flash (e.g. mtd:flash0)\ndevice_id=\"\"\n# Path to OpenBMC image on local system\n# i.e. what we scp to $host as \"/run/upgrade/image\"\nimagepath=\"\"\n# OpenBMC hostname\nhost=\"\"\nport=\"\"\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\ncase $key in\n    -h|-help|--help)\n    echo -e \"$usage\"\n    exit 0\n    ;;\n    --device)\n    check_second_argument_supplied \"$@\"\n    device_id=\"$2\"\n    shift\n    shift\n    ;;\n    --imagepath)\n    check_second_argument_supplied \"$@\"\n    imagepath=\"$(realpath \"$2\")\"\n    shift\n    shift\n    ;;\n    --host)\n    check_second_argument_supplied \"$@\"\n    host=\"$2\"\n    shift\n    shift\n    ;;\n    --port)\n    check_second_argument_supplied \"$@\"\n    port=\"$2\"\n    shift\n    shift\n    ;;\n    --path-to-flashy)\n    check_second_argument_supplied \"$@\"\n    path_to_flashy=\"$(realpath \"$2\")\"\n    shift\n    shift\n    ;;\n    --dry-run)\n    dry_run=\"true\"\n    shift\n    ;;\n    *)\n    printf \"Illegal argument %s\\n\" \"$1\" >&2\n    exit_with_usage\n    ;;\nesac\ndone\n\nconfirm_continue() {\n    read -rp \"Continue (y/n)?\" choice\n    case \"$choice\" in\n    y|Y)\n    ;;\n    *)\n    echo \"Exiting\"\n    exit 1\n    ;;\n    esac\n}\n\n# make sure we're in flashy's project/release root\ncd \"$(dirname \"$0\")\" && cd ..\n\nif [[ \"$dry_run\" == \"true\" ]]\nthen\n    echo \"Running in dry-run mode\" >&2\nfi\n\n[ -n \"$device_id\" ] || exit_argument_required \"device\"\n[ -n \"$host\" ] || exit_argument_required \"host\"\n[ -n \"$imagepath\" ] || exit_argument_required \"imagepath\"\n[ -f \"$imagepath\" ] || exit_file_required \"Image\" \"$imagepath\"\n\noptions=(-o \"LogLevel=error\" -o \"StrictHostKeyChecking=no\")\noptions+=(-o \"UserKnownHostsFile=/dev/null\")\nsshCmdOptions=(\"${options[@]}\")\nif [[ -n \"$port\" ]]\nthen\n    sshCmdOptions+=(-p \"$port\")\nfi\nsshpassCmd=(sshpass -p0penBmc)\nsshcmd=(\"${sshpassCmd[@]}\" ssh \"${sshCmdOptions[@]}\")\nsshcmd+=(\"root@$host\")\n\necho \"Running a remote upgrade on '$host' $port with image '$imagepath'\"\nif [ -t 0 ]\nthen\n    confirm_continue\nfi\n\ninitialize\nif [[ \"$dry_run\" == \"true\" ]]\nthen\n    echo \"Finished dry run\" >&2\nelse\n    run_upgrade\n    reboot_and_check_upgrade\nfi\n", "num_lines": 246}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020-present Facebook. All Rights Reserved.\n#\n# This program file is free software; you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by the\n# Free Software Foundation; version 2 of the License.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License\n# for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program in a file named COPYING; if not, write to the\n# Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor,\n# Boston, MA 02110-1301 USA\n\n# Run this script to run each unit tests individually\nset -euo pipefail\n\n# Ensure we're in the project root\ncd \"$(dirname \"$0\")\" && cd ..\n\necho \"Running build test\" >&2\nif output=$(./build.sh); then\n    echo \"Build succeeded!\"\nelse\n    echo \"Build failed!\"\n    echo \"$output\" >&2\n    exit 1\nfi\n\necho \"Running unit tests\" >&2\necho \"Getting all packages...\" >&2\nall_packages=$(go list ./...)\n\necho \"Getting list of tests...\" >&2\nfor pkg in $all_packages\ndo\n    pkg_tests=$(go test \"${pkg}\" -list .* | grep Test || true)\n    for pkg_test in $pkg_tests\n    do\n        all_test_cmds+=(\"go test -v ${pkg} -run \\\"^${pkg_test}$\\\"\")\n    done\ndone\n\nnum_tests=\"${#all_test_cmds[@]}\"\necho \"Found $num_tests tests.\" >&2\n\necho \"Starting to run tests\" >&2\n\npassed=0\nfailed=0\nidx=1\nfor test_cmd in \"${all_test_cmds[@]}\"\ndo\n    echo -n \"[$idx/$num_tests] '$test_cmd': \"\n\n    if output=$(eval \"$test_cmd\" 2>&1); then\n        echo \"PASSED\"\n        ((++passed))\n    else\n        echo \"FAILED\"\n        ((++failed))\n        echo \"$output\" >&2\n    fi\n\n    ((++idx))\ndone\n\necho \"$passed/$num_tests unit tests passed\"\n\n\n[[ $failed -ne 0 ]] && exit 1\nexit 0\n", "num_lines": 77}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Throw everything to stdout so that svlogd can capture it\nexec 2>&1\n\nset -x\nset -e\nset -u\nset -o pipefail\nexport PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:.\n\nspi_util_cmd=\"/usr/local/bin/spi_util.sh\"\n\n\nfunction open_isolation_buffer() {\n    echo 0x1 > /sys/bus/i2c/devices/12-0031/com-e_i2c_isobuf_en\n}\n\nfunction change_gpios() {\n    # These paths in /tmp are human-readable symlinks to GPIO numbers\n    # in /sys/class/gp\u00c3\u00aco\n    echo out > /tmp/gpionames/SWITCH_EEPROM1_WRT/direction\n    echo 1 > /tmp/gpionames/SWITCH_EEPROM1_WRT/value\n}\n\neeprom_io_legacy() {\n    io_type=\"$1\"\n    image_file=\"$2\"\n\n    at93cx6_util_py3.py chip \"$io_type\" --file \"$image_file\"\n}\n\neeprom_io_new() {\n    io_type=\"$1\"\n    image_file=\"$2\"\n\n    \"$spi_util_cmd\" \"$io_type\" spi2 OOB_SWITCH_EEPROM \"$image_file\"\n}\n\noob_switch_eeprom_program() {\n    input_image=\"$1\"\n    tmp_file=\"/tmp/.oob_eeprom.tmp\"\n\n    if grep OOB_SWITCH_EEPROM \"$spi_util_cmd\"; then\n        eeprom_io_new write \"$input_image\"\n        eeprom_io_new read \"$tmp_file\"\n    else\n        change_gpios\n        eeprom_io_legacy write \"$input_image\"\n        eeprom_io_legacy read \"$tmp_file\"\n    fi\n\n    diff \"$input_image\" \"$tmp_file\"\n    rm -f \"$tmp_file\"\n}\n\nopen_isolation_buffer\n\noob_switch_eeprom_program $1\n\n", "num_lines": 61}
{"repo_name": "openbmc", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# shellcheck disable=SC2044\n\npardir=$(git rev-parse --show-toplevel)\ncommon_src_dir=\"$pardir/common/recipes-rest/rest-api/files\"\n\nfunction validate_environment(){\n    if [[ ! \"$BBPATH\" ]]; then echo \"No BBPATH in environment. Have you entered a bitbake build-env?\" >&2; return 1; fi\n    if [[ ! -x  /bin/inotifywait ]]; then echo \"inotifywait is not available.  Install inotify-tools\" >&2; return 1; fi\n}\n\nfunction  get_build_platform(){\n    BUILD_PLATFORM=$(grep BBFILE_COLLECTIONS \"$TEMPLATECONF/../../layer.conf\"| cut -d'\"' -f 2)\n    echo \"$BUILD_PLATFORM\"\n}\n\n\nfunction get_platform_parent_name(){\n    # returns either platform parent name or just platrom name if not derived\n    platform_name=$1\n\n    case \"$platform_name\" in\n      \"fby2-nd\")\n        echo \"fby2\"\n        ;;\n      *)\n        echo \"$platform_name\"\n        ;;\n    esac\n}\n\nfunction get_platform_meta_path(){\n    if [[ $# != 1 ]]; then echo \"Usage: get_platform_meta_path <build_name> [<subplatform_name>]\" >&2; return 1; fi\n\n    subplat=\"\"\n    plat=\"$1\"\n\n    parent_platform_name=$(get_platform_parent_name $platform_name)\n    if [[ \"$parent_platform_name\" ]] && [[ \"$parent_platform_name\" != \"$plat\" ]]; then\n      subplat=\"$plat\"\n      plat=$parent_platform_name\n    fi\n\n    if [[ \"$subplat\" ]] && [[ -d \"$pardir/meta-facebook/meta-$plat/meta-$subplat\" ]]; then\n        echo \"$pardir/meta-facebook/meta-$plat/meta-$subplat\"\n        return 0\n    fi\n    if [[ -d \"$pardir/meta-facebook/meta-$plat\" ]]; then\n        echo \"$pardir/meta-facebook/meta-$plat\"\n        return 0\n    fi\n    echo \"ERROR: Could not find meta-files path for platform '$plat'\" >&2\n    return 1\n}\n\nfunction get_platform_recipe_path(){\n    plat=$1\n    meta_path=\"$(get_platform_meta_path $plat)\"\n    retval=$?\n\n    if [[ $retval -gt 0 ]]; then\n        return $retval\n    fi\n\n    if [[ -d \"$meta_path/recipes-utils\" ]]; then\n        # network device\n        echo \"$meta_path/recipes-utils\"\n        return 0\n    fi\n    if [[ -d \"$meta_path/recipes-$plat\" ]]; then\n        # compute device\n        echo \"$meta_path/recipes-$plat\"\n        return 0\n    fi\n\n    return 1\n}\n\nfunction get_machine_name(){\n    platform_name=$1\n    meta_path=\"$(get_platform_meta_path $1)\"\n    retval=$?\n\n    if [[ $retval -ne 0 ]]; then\n        return $retval\n    fi\n\n    machine_name=$(grep ^MACHINE \"$meta_path/conf/local.conf.sample\" | awk '{print $NF}' | tr -d '\"')\n    retval=$?\n\n    if [[ $retval -ne 0 ]]; then\n        return 1\n    fi\n\n    echo \"$machine_name\"\n}\n\nfunction prepare_working_directory(){\n    (\n        if [[ $# != 1 ]]; then echo \"Usage: prepare_working_directory <plat_specific_src_dir>\">&2; return 1; fi\n        cd \"$pardir\" || exit 1\n        plat_specific_src_dir=$1\n        outdir=\"$BBPATH/tmp/workarmv*-fb-linux-gnueabi/rest-api/0.1-r1/rest-api-0.1\"\n        # Remove old symlinks\n        if [[ -e \"$outdir\" ]]; then\n            for file in $(find \"$outdir\" -type l -iname '*.py'); do\n                org=$(readlink -f \"$file\" || true)\n                rm \"$file\"\n                if [[ -e \"$org\" ]]; then\n                    cp -f \"$org\" \"$file\"\n                fi\n            done\n        fi\n\n        # Build test once\n        bitbake rest-api --force  >/dev/null 2>/dev/null || true\n\n        # Link source files to the output directory so that source changes are reflected immediately\n        set +x\n        for src_file in $(find \"$common_src_dir\" -type f | grep -Po '(?<=/rest-api/files/).+$'); do\n            src_file_abs=\"$common_src_dir/$src_file\"\n            if diff -q \"$src_file_abs\" \"$outdir/\"*\"/$src_file\" >/dev/null 2>/dev/null; then\n                ln -svf \"$src_file_abs\" \"$outdir/\"*\"/$src_file\" >/dev/null\n            fi\n        done\n        for src_file in $(find \"$plat_specific_src_dir\" -type f | grep -Po '(?<=/rest-api/files/).+$'); do\n            src_file_abs=\"$plat_specific_src_dir/$src_file\"\n            if diff -q \"$src_file_abs\" \"$outdir/\"*\"/$src_file\" >/dev/null 2>/dev/null; then\n                ln -svf \"$src_file_abs\" \"$outdir/\"*\"/$src_file\" >/dev/null\n            fi\n        done\n\n    )\n}\n", "num_lines": 135}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# script to generate FIT image source for i.MX8MQ boards with\n# ARM Trusted Firmware and multiple device trees (given on the command line)\n#\n# usage: $0 <dt_name> [<dt_name> [<dt_name] ...]\n\n[ -z \"$BL31\" ] && BL31=\"bl31.bin\"\n[ -z \"$TEE_LOAD_ADDR\" ] && TEE_LOAD_ADDR=\"0xfe000000\"\n[ -z \"$ATF_LOAD_ADDR\" ] && ATF_LOAD_ADDR=\"0x00910000\"\n[ -z \"$BL33_LOAD_ADDR\" ] && BL33_LOAD_ADDR=\"0x40200000\"\n\nif [ ! -f $BL31 ]; then\n\techo \"ERROR: BL31 file $BL31 NOT found\" >&2\n\texit 0\nelse\n\techo \"$BL31 size: \" >&2\n\tstat -c %s $BL31 >&2\nfi\n\nBL32=\"tee.bin\"\n\nif [ ! -f $BL32 ]; then\n\tBL32=/dev/null\nelse\n\techo \"Building with TEE support, make sure your $BL31 is compiled with spd. If you do not want tee, please delete $BL31\" >&2\n\techo \"$BL32 size: \" >&2\n\tstat -c %s $BL32 >&2\nfi\n\nBL33=\"u-boot-nodtb.bin\"\n\nif [ ! -f $BL33 ]; then\n\techo \"ERROR: $BL33 file NOT found\" >&2\n\texit 0\nelse\n\techo \"u-boot-nodtb.bin size: \" >&2\n\tstat -c %s u-boot-nodtb.bin >&2\nfi\n\nfor dtname in $*\ndo\n\techo \"$dtname size: \" >&2\n\tstat -c %s $dtname >&2\ndone\n\n\ncat << __HEADER_EOF\n/dts-v1/;\n\n/ {\n\tdescription = \"Configuration to load ATF before U-Boot\";\n\n\timages {\n\t\tuboot@1 {\n\t\t\tdescription = \"U-Boot (64-bit)\";\n\t\t\tos = \"u-boot\";\n\t\t\tdata = /incbin/(\"$BL33\");\n\t\t\ttype = \"standalone\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$BL33_LOAD_ADDR>;\n\t\t};\n__HEADER_EOF\n\ncnt=1\nfor dtname in $*\ndo\n\tcat << __FDT_IMAGE_EOF\n\t\tfdt@$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tdata = /incbin/(\"$dtname\");\n\t\t\ttype = \"flat_dt\";\n\t\t\tcompression = \"none\";\n\t\t};\n__FDT_IMAGE_EOF\ncnt=$((cnt+1))\ndone\n\ncat << __HEADER_EOF\n\t\tatf@1 {\n\t\t\tdescription = \"ARM Trusted Firmware\";\n\t\t\tos = \"arm-trusted-firmware\";\n\t\t\tdata = /incbin/(\"$BL31\");\n\t\t\ttype = \"firmware\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$ATF_LOAD_ADDR>;\n\t\t\tentry = <$ATF_LOAD_ADDR>;\n\t\t};\n__HEADER_EOF\n\nif [ -f $BL32 ]; then\ncat << __HEADER_EOF\n\t\ttee@1 {\n\t\t\tdescription = \"TEE firmware\";\n\t\t\tdata = /incbin/(\"$BL32\");\n\t\t\ttype = \"firmware\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$TEE_LOAD_ADDR>;\n\t\t\tentry = <$TEE_LOAD_ADDR>;\n\t\t};\n__HEADER_EOF\nfi\n\ncat << __CONF_HEADER_EOF\n\t};\n\tconfigurations {\n\t\tdefault = \"config@1\";\n\n__CONF_HEADER_EOF\n\ncnt=1\nfor dtname in $*\ndo\nif [ -f $BL32 ]; then\ncat << __CONF_SECTION_EOF\n\t\tconfig@$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"uboot@1\";\n\t\t\tloadables = \"atf@1\", \"tee@1\";\n\t\t\tfdt = \"fdt@$cnt\";\n\t\t};\n__CONF_SECTION_EOF\nelse\ncat << __CONF_SECTION1_EOF\n\t\tconfig@$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"uboot@1\";\n\t\t\tloadables = \"atf@1\";\n\t\t\tfdt = \"fdt@$cnt\";\n\t\t};\n__CONF_SECTION1_EOF\nfi\ncnt=$((cnt+1))\ndone\n\ncat << __ITS_EOF\n\t};\n};\n__ITS_EOF\n", "num_lines": 144}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# helper function to convert from DOS to Unix, if necessary, and handle\n# lines ending in '\\'.\n#\nfix_newlines_in_macros() {\n\tsed -n ':next;s/\\r$//;/[^\\\\]\\\\$/ {N;s/\\\\\\n//;b next};p' $1\n}\n\n#filter out only what we need from a10 hps.xml\ngrep_a10_hps_config() {\n\tegrep \"clk_hz|i_clk_mgr|i_io48_pin_mux|AXI_SLAVE|AXI_MASTER\"\n}\n\n#\n# Process hps.xml\n# $1:\thps.xml\n# $2:\tOutput File\n#\nprocess_a10_hps_config() {\n\thps_xml=\"$1\"\n\toutfile=\"$2\"\n\n\t(cat << EOF\n// SPDX-License-Identifier: BSD-3-Clause\n/*\n * Intel Arria 10 SoCFPGA configuration\n */\n\n#ifndef __SOCFPGA_ARRIA10_CONFIG_H__\n#define __SOCFPGA_ARRIA10_CONFIG_H__\n\nEOF\n\n\techo \"/* Clocks */\"\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"clk_hz\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/\\.[0-9]//' |\n\t\t\tsed 's/I_CLK_MGR_//' |\n\t\t\tsort\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"i_clk_mgr_mainpll\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/\\.[0-9]//' |\n\t\t\tsed 's/I_CLK_MGR_//' |\n\t\t\tsort\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"i_clk_mgr_perpll\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/\\.[0-9]//' |\n\t\t\tsed 's/I_CLK_MGR_//' |\n\t\t\tsort\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"i_clk_mgr_clkmgr\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/\\.[0-9]//' |\n\t\t\tsed 's/I_CLK_MGR_//' |\n\t\t\tsort\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"i_clk_mgr_alteragrp\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/\\.[0-9]//' |\n\t\t\tsed 's/I_CLK_MGR_//' |\n\t\t\tsort\n\techo \"#define ALTERAGRP_MPUCLK ((ALTERAGRP_MPUCLK_PERICNT << 16) | \\\\\"\n\techo \"\t(ALTERAGRP_MPUCLK_MAINCNT))\"\n\techo \"#define ALTERAGRP_NOCCLK ((ALTERAGRP_NOCCLK_PERICNT << 16) | \\\\\"\n\techo \"\t(ALTERAGRP_NOCCLK_MAINCNT))\"\n\n\techo\n\techo \"/* Pin Mux Configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"i_io48_pin_mux\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/I_IO48_PIN_MUX_//' |\n\t\t\tsed 's/SHARED_3V_IO_GRP_//' |\n\t\t\tsed 's/FPGA_INTERFACE_GRP_//' |\n\t\t\tsed 's/DEDICATED_IO_GRP_//' |\n\t\t\tsed 's/CONFIGURATION_DEDICATED/CONFIG/' |\n\t\t\tsort\n\n\techo\n\techo \"/* Bridge Configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${hps_xml} | egrep \"AXI_SLAVE|AXI_MASTER\" |\n\t\t\tawk -F\"'\" '{ gsub(\"\\\\.\",\"_\",$2) ; \\\n\t\t\t\tprint \"#define\" \" \" toupper($2) \" \" $4}' |\n\t\t\tsed 's/true/1/' |\n\t\t\tsed 's/false/0/' |\n\t\t\tsort\n\n\techo\n\techo \"/* Voltage Select for Config IO */\"\n\techo \"#define CONFIG_IO_BANK_VSEL \\\\\"\n\techo \"\t(((CONFIG_IO_BANK_VOLTAGE_SEL_CLKRST_IO & 0x3) << 8) | \\\\\"\n\techo \"\t(CONFIG_IO_BANK_VOLTAGE_SEL_PERI_IO & 0x3))\"\n\n\techo\n\techo \"/* Macro for Config IO bit mapping */\"\n\techo -n \"#define CONFIG_IO_MACRO(NAME) \"\n\techo \"(((NAME ## _RTRIM & 0xff) << 19) | \\\\\"\n\techo \"\t((NAME ## _INPUT_BUF_EN & 0x3) << 17) | \\\\\"\n\techo \"\t((NAME ## _WK_PU_EN & 0x1) << 16) | \\\\\"\n\techo \"\t((NAME ## _PU_SLW_RT & 0x1) << 13) | \\\\\"\n\techo \"\t((NAME ## _PU_DRV_STRG & 0xf) << 8) | \\\\\"\n\techo \"\t((NAME ## _PD_SLW_RT & 0x1) << 5) | \\\\\"\n\techo \"\t(NAME ## _PD_DRV_STRG & 0x1f))\"\n\n\tcat << EOF\n\n#endif /* __SOCFPGA_ARRIA10_CONFIG_H__ */\nEOF\n\t) > \"${outfile}\"\n}\n\nusage() {\n\techo \"$0 [hps_xml] [output_file]\"\n\techo \"Process QTS-generated hps.xml into devicetree header.\"\n\techo \"\"\n\techo \"  hps_xml      - hps.xml file from hps_isw_handoff\"\n\techo \"  output_file  - Output header file for dtsi include\"\n\techo \"\"\n}\n\nhps_xml=\"$1\"\noutfile=\"$2\"\n\nif [ \"$#\" -ne 2 ] ; then\n\tusage\n\texit 1\nfi\n\nprocess_a10_hps_config \"${hps_xml}\" \"${outfile}\"\n", "num_lines": 142}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#\n# helper function to convert from DOS to Unix, if necessary, and handle\n# lines ending in '\\'.\n#\nfix_newlines_in_macros() {\n\tsed -n ':next;s/\\r$//;/[^\\\\]\\\\$/ {N;s/\\\\\\n//;b next};p' $1\n}\n\n#\n# Process iocsr_config_*.[ch]\n# $1:\tSoC type\n# $2:\tInput handoff directory\n# $3:\tInput BSP Generated directory\n# $4:\tOutput directory\n#\nprocess_iocsr_config() {\n\tsoc=\"$1\"\n\tin_qts_dir=\"$2\"\n\tin_bsp_dir=\"$3\"\n\tout_dir=\"$4\"\n\n\t(\n\tcat << EOF\n/* SPDX-License-Identifier: BSD-3-Clause */\n/*\n * Altera SoCFPGA IOCSR configuration\n */\n\n#ifndef __SOCFPGA_IOCSR_CONFIG_H__\n#define __SOCFPGA_IOCSR_CONFIG_H__\n\nEOF\n\n\t# Retrieve the scan chain lengths\n\tfix_newlines_in_macros \\\n\t\t${in_bsp_dir}/generated/iocsr_config_${soc}.h |\n\tgrep 'CONFIG_HPS_IOCSR_SCANCHAIN[0-9]\\+_LENGTH'\t| tr -d \"()\"\n\n\techo \"\"\n\n\t# Retrieve the scan chain config and zap the ad-hoc length encoding\n\tfix_newlines_in_macros \\\n\t\t${in_bsp_dir}/generated/iocsr_config_${soc}.c |\n\tsed -n '/^const/ !b; :next {/^const/ s/(.*)//;p;n;b next}'\n\n\tcat << EOF\n\n#endif /* __SOCFPGA_IOCSR_CONFIG_H__ */\nEOF\n\t) > \"${out_dir}/iocsr_config.h\"\n}\n\n#\n# Process pinmux_config_*.c (and ignore pinmux_config.h)\n# $1:\tSoC type\n# $2:\tInput directory\n# $3:\tOutput directory\n#\nprocess_pinmux_config() {\n\tsoc=\"$1\"\n\tin_qts_dir=\"$2\"\n\tin_bsp_dir=\"$3\"\n\tout_dir=\"$4\"\n\n\t(\n\tcat << EOF\n/* SPDX-License-Identifier: BSD-3-Clause */\n/*\n * Altera SoCFPGA PinMux configuration\n */\n\n#ifndef __SOCFPGA_PINMUX_CONFIG_H__\n#define __SOCFPGA_PINMUX_CONFIG_H__\n\nEOF\n\n\t# Retrieve the pinmux config and zap the ad-hoc length encoding\n\tfix_newlines_in_macros \\\n\t\t${in_bsp_dir}/generated/pinmux_config_${soc}.c |\n\tsed -n '/^unsigned/ !b; :next {/^unsigned/ {s/\\[.*\\]/[]/;s/unsigned long/const u8/};p;n;b next}'\n\n\tcat << EOF\n\n#endif /* __SOCFPGA_PINMUX_CONFIG_H__ */\nEOF\n\t) > \"${out_dir}/pinmux_config.h\"\n}\n\n#\n# Process pll_config.h\n# $1:\tSoC type (not used)\n# $2:\tInput directory\n# $3:\tOutput directory\n#\nprocess_pll_config() {\n\tsoc=\"$1\"\n\tin_qts_dir=\"$2\"\n\tin_bsp_dir=\"$3\"\n\tout_dir=\"$4\"\n\n\t(\n\tcat << EOF\n/* SPDX-License-Identifier: BSD-3-Clause */\n/*\n * Altera SoCFPGA Clock and PLL configuration\n */\n\n#ifndef __SOCFPGA_PLL_CONFIG_H__\n#define __SOCFPGA_PLL_CONFIG_H__\n\nEOF\n\n\t# Retrieve the pll config and zap parenthesis\n\tfix_newlines_in_macros \\\n\t\t${in_bsp_dir}/generated/pll_config.h |\n\tsed -n '/CONFIG_HPS/ !b; :next {/CONFIG_HPS/ s/[()]//g;/endif/ b;p;n;b next}'\n\n\tcat << EOF\n\n#endif /* __SOCFPGA_PLL_CONFIG_H__ */\nEOF\n\t) > \"${out_dir}/pll_config.h\"\n}\n\n#\n# Filter out only the macros which are actually used by the code\n#\ngrep_sdram_config() {\n\tegrep \"#define (CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_MEMTYPE|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_MEMBL|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ADDRORDER|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ECCEN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_ECCCORREN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_REORDEREN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_STARVELIMIT|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_DQSTRKEN|CONFIG_HPS_SDR_CTRLCFG_CTRLCFG_NODMPINS|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TCWL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_AL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TCL|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TRRD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TFAW|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING1_TRFC|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TREFI|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TRCD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TRP|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TWR|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING2_IF_TWTR|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRTP|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRAS|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TRC|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TMRD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING3_TCCD|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING4_SELFRFSHEXIT|CONFIG_HPS_SDR_CTRLCFG_DRAMTIMING4_PWRDOWNEXIT|CONFIG_HPS_SDR_CTRLCFG_LOWPWRTIMING_AUTOPDCYCLES|CONFIG_HPS_SDR_CTRLCFG_LOWPWRTIMING_CLKDISABLECYCLES|CONFIG_HPS_SDR_CTRLCFG_DRAMODT_READ|CONFIG_HPS_SDR_CTRLCFG_DRAMODT_WRITE|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_COLBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_ROWBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_BANKBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMADDRW_CSBITS|CONFIG_HPS_SDR_CTRLCFG_DRAMIFWIDTH_IFWIDTH|CONFIG_HPS_SDR_CTRLCFG_DRAMDEVWIDTH_DEVWIDTH|CONFIG_HPS_SDR_CTRLCFG_DRAMINTR_INTREN|CONFIG_HPS_SDR_CTRLCFG_LOWPWREQ_SELFRFSHMASK|CONFIG_HPS_SDR_CTRLCFG_STATICCFG_MEMBL|CONFIG_HPS_SDR_CTRLCFG_STATICCFG_USEECCASDATA|CONFIG_HPS_SDR_CTRLCFG_CTRLWIDTH_CTRLWIDTH|CONFIG_HPS_SDR_CTRLCFG_CPORTWIDTH_CPORTWIDTH|CONFIG_HPS_SDR_CTRLCFG_CPORTWMAP_CPORTWMAP|CONFIG_HPS_SDR_CTRLCFG_CPORTRMAP_CPORTRMAP|CONFIG_HPS_SDR_CTRLCFG_RFIFOCMAP_RFIFOCMAP|CONFIG_HPS_SDR_CTRLCFG_WFIFOCMAP_WFIFOCMAP|CONFIG_HPS_SDR_CTRLCFG_CPORTRDWR_CPORTRDWR|CONFIG_HPS_SDR_CTRLCFG_PORTCFG_AUTOPCHEN|CONFIG_HPS_SDR_CTRLCFG_FPGAPORTRST|CONFIG_HPS_SDR_CTRLCFG_FIFOCFG_SYNCMODE|CONFIG_HPS_SDR_CTRLCFG_FIFOCFG_INCSYNC|CONFIG_HPS_SDR_CTRLCFG_MPPRIORITY_USERPRIORITY|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_0_STATICWEIGHT_31_0|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_1_STATICWEIGHT_49_32|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_1_SUMOFWEIGHT_13_0|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_2_SUMOFWEIGHT_45_14|CONFIG_HPS_SDR_CTRLCFG_MPWIEIGHT_3_SUMOFWEIGHT_63_46|CONFIG_HPS_SDR_CTRLCFG_PHYCTRL_PHYCTRL_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_0_THRESHOLD1_31_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_1_THRESHOLD1_59_32|CONFIG_HPS_SDR_CTRLCFG_MPPACING_1_THRESHOLD2_3_0|CONFIG_HPS_SDR_CTRLCFG_MPPACING_2_THRESHOLD2_35_4|CONFIG_HPS_SDR_CTRLCFG_MPPACING_3_THRESHOLD2_59_36|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_0_THRESHOLDRSTCYCLES_31_0|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_1_THRESHOLDRSTCYCLES_63_32|CONFIG_HPS_SDR_CTRLCFG_MPTHRESHOLDRST_2_THRESHOLDRSTCYCLES_79_64|RW_MGR_ACTIVATE_0_AND_1|RW_MGR_ACTIVATE_0_AND_1_WAIT1|RW_MGR_ACTIVATE_0_AND_1_WAIT2|RW_MGR_ACTIVATE_1|RW_MGR_CLEAR_DQS_ENABLE|RW_MGR_EMR_OCD_ENABLE|RW_MGR_EMR|RW_MGR_EMR2|RW_MGR_EMR3|RW_MGR_GUARANTEED_READ|RW_MGR_GUARANTEED_READ_CONT|RW_MGR_GUARANTEED_WRITE|RW_MGR_GUARANTEED_WRITE_WAIT0|RW_MGR_GUARANTEED_WRITE_WAIT1|RW_MGR_GUARANTEED_WRITE_WAIT2|RW_MGR_GUARANTEED_WRITE_WAIT3|RW_MGR_IDLE|RW_MGR_IDLE_LOOP1|RW_MGR_IDLE_LOOP2|RW_MGR_INIT_RESET_0_CKE_0|RW_MGR_INIT_RESET_1_CKE_0|RW_MGR_INIT_CKE_0|RW_MGR_LFSR_WR_RD_BANK_0|RW_MGR_LFSR_WR_RD_BANK_0_DATA|RW_MGR_LFSR_WR_RD_BANK_0_DQS|RW_MGR_LFSR_WR_RD_BANK_0_NOP|RW_MGR_LFSR_WR_RD_BANK_0_WAIT|RW_MGR_LFSR_WR_RD_BANK_0_WL_1|RW_MGR_LFSR_WR_RD_DM_BANK_0|RW_MGR_LFSR_WR_RD_DM_BANK_0_DATA|RW_MGR_LFSR_WR_RD_DM_BANK_0_DQS|RW_MGR_LFSR_WR_RD_DM_BANK_0_NOP|RW_MGR_LFSR_WR_RD_DM_BANK_0_WAIT|RW_MGR_LFSR_WR_RD_DM_BANK_0_WL_1|RW_MGR_MR_CALIB|RW_MGR_MR_USER|RW_MGR_MR_DLL_RESET|RW_MGR_MRS0_DLL_RESET|RW_MGR_MRS0_DLL_RESET_MIRR|RW_MGR_MRS0_USER|RW_MGR_MRS0_USER_MIRR|RW_MGR_MRS1|RW_MGR_MRS1_MIRR|RW_MGR_MRS2|RW_MGR_MRS2_MIRR|RW_MGR_MRS3|RW_MGR_MRS3_MIRR|RW_MGR_NOP|RW_MGR_PRECHARGE_ALL|RW_MGR_READ_B2B|RW_MGR_READ_B2B_WAIT1|RW_MGR_READ_B2B_WAIT2|RW_MGR_REFRESH|RW_MGR_REFRESH_ALL|RW_MGR_RETURN|RW_MGR_SGLE_READ|RW_MGR_ZQCL|RW_MGR_TRUE_MEM_DATA_MASK_WIDTH|RW_MGR_MEM_ADDRESS_MIRRORING|RW_MGR_MEM_DATA_MASK_WIDTH|RW_MGR_MEM_DATA_WIDTH|RW_MGR_MEM_DQ_PER_READ_DQS|RW_MGR_MEM_DQ_PER_WRITE_DQS|RW_MGR_MEM_IF_READ_DQS_WIDTH|RW_MGR_MEM_IF_WRITE_DQS_WIDTH|RW_MGR_MEM_NUMBER_OF_CS_PER_DIMM|RW_MGR_MEM_NUMBER_OF_RANKS|RW_MGR_MEM_VIRTUAL_GROUPS_PER_READ_DQS|RW_MGR_MEM_VIRTUAL_GROUPS_PER_WRITE_DQS|IO_DELAY_PER_DCHAIN_TAP|IO_DELAY_PER_DQS_EN_DCHAIN_TAP|IO_DELAY_PER_OPA_TAP|IO_DLL_CHAIN_LENGTH|IO_DQDQS_OUT_PHASE_MAX|IO_DQS_EN_DELAY_MAX|IO_DQS_EN_DELAY_OFFSET|IO_DQS_EN_PHASE_MAX|IO_DQS_IN_DELAY_MAX|IO_DQS_IN_RESERVE|IO_DQS_OUT_RESERVE|IO_IO_IN_DELAY_MAX|IO_IO_OUT1_DELAY_MAX|IO_IO_OUT2_DELAY_MAX|IO_SHIFT_DQS_EN_WHEN_SHIFT_DQS|AFI_RATE_RATIO|AFI_CLK_FREQ|CALIB_LFIFO_OFFSET|CALIB_VFIFO_OFFSET|ENABLE_SUPER_QUICK_CALIBRATION|MAX_LATENCY_COUNT_WIDTH|READ_VALID_FIFO_SIZE|REG_FILE_INIT_SEQ_SIGNATURE|TINIT_CNTR0_VAL|TINIT_CNTR1_VAL|TINIT_CNTR2_VAL|TRESET_CNTR0_VAL|TRESET_CNTR1_VAL|TRESET_CNTR2_VAL|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR_BC|CONFIG_HPS_SDR_CTRLCFG_EXTRATIME1_CFG_EXTRA_CTL_CLK_RD_TO_WR_DIFF_CHIP)[[:space:]]\"\n}\n\n#\n# Process sdram_config.h, sequencer_auto*h and sequencer_defines.h\n# $1:\tSoC type (not used)\n# $2:\tInput directory\n# $3:\tOutput directory\n#\nprocess_sdram_config() {\n\tsoc=\"$1\"\n\tin_qts_dir=\"$2\"\n\tin_bsp_dir=\"$3\"\n\tout_dir=\"$4\"\n\n\t(\n\tcat << EOF\n/* SPDX-License-Identifier: BSD-3-Clause */\n/*\n * Altera SoCFPGA SDRAM configuration\n *\n */\n\n#ifndef __SOCFPGA_SDRAM_CONFIG_H__\n#define __SOCFPGA_SDRAM_CONFIG_H__\n\nEOF\n\n\techo \"/* SDRAM configuration */\"\n\t# Retrieve the sdram config, zap broken lines and zap parenthesis\n\tfix_newlines_in_macros \\\n\t\t${in_bsp_dir}/generated/sdram/sdram_config.h |\n\tsed -n \"/\\\\\\\\$/ {N;s/ \\\\\\\\\\n/\\t/};p\" |\n\tsed -n '/CONFIG_HPS/ !b; :next {/CONFIG_HPS/ s/[()]//g;/endif/ b;p;n;b next}' |\n\t\tsort -u | grep_sdram_config\n\n\techo \"\"\n\techo \"/* Sequencer auto configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${in_qts_dir}/hps_isw_handoff/*/sequencer_auto.h |\n\tsed -n \"/__RW_MGR/ {s/__//;s/ \\+\\([^ ]\\+\\)$/\\t\\1/p}\" |\n\t\tsort -u | grep_sdram_config\n\n\techo \"\"\n\techo \"/* Sequencer defines configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${in_qts_dir}/hps_isw_handoff/*/sequencer_defines.h |\n\tsed -n \"/^#define [^_]/ {s/__//;s/ \\+\\([^ ]\\+\\)$/\\t\\1/p}\" |\n\t\tsort -u | grep_sdram_config\n\n\techo \"\"\n\techo \"/* Sequencer ac_rom_init configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${in_qts_dir}/hps_isw_handoff/*/sequencer_auto_ac_init.c |\n\tsed -n '/^const.*\\[/ !b; :next {/^const.*\\[/ {N;s/\\n//;s/alt_u32/u32/;s/\\[.*\\]/[]/};/endif/ b;p;n;b next}'\n\n\techo \"\"\n\techo \"/* Sequencer inst_rom_init configuration */\"\n\tfix_newlines_in_macros \\\n\t\t${in_qts_dir}/hps_isw_handoff/*/sequencer_auto_inst_init.c |\n\tsed -n '/^const.*\\[/ !b; :next {/^const.*\\[/ {N;s/\\n//;s/alt_u32/u32/;s/\\[.*\\]/[]/};/endif/ b;p;n;b next}'\n\n\tcat << EOF\n\n#endif /* __SOCFPGA_SDRAM_CONFIG_H__ */\nEOF\n\t) > \"${out_dir}/sdram_config.h\"\n}\n\nusage() {\n\techo \"$0 [soc_type] [input_qts_dir] [input_bsp_dir] [output_dir]\"\n\techo \"Process QTS-generated headers into U-Boot compatible ones.\"\n\techo \"\"\n\techo \"  soc_type      - Type of SoC, either 'cyclone5' or 'arria5'.\"\n\techo \"  input_qts_dir - Directory with compiled Quartus project\"\n\techo \"                  and containing the Quartus project file (QPF).\"\n\techo \"  input_bsp_dir - Directory with generated bsp containing\"\n\techo \"                  the settings.bsp file.\"\n\techo \"  output_dir    - Directory to store the U-Boot compatible\"\n\techo \"                  headers.\"\n\techo \"\"\n}\n\nsoc=\"$1\"\nin_qts_dir=\"$2\"\nin_bsp_dir=\"$3\"\nout_dir=\"$4\"\n\nif [ \"$#\" -ne 4 ] ; then\n\tusage\n\texit 1\nfi\n\nif [ ! -d \"${in_qts_dir}\" -o ! -d \"${in_bsp_dir}\" -o \\\n\t! -d \"${out_dir}\" -o -z \"${soc}\" ] ; then\n\tusage\n\texit 3\nfi\n\nprocess_iocsr_config  \"${soc}\" \"${in_qts_dir}\" \"${in_bsp_dir}\" \"${out_dir}\"\nprocess_pinmux_config \"${soc}\" \"${in_qts_dir}\" \"${in_bsp_dir}\" \"${out_dir}\"\nprocess_pll_config    \"${soc}\" \"${in_qts_dir}\" \"${in_bsp_dir}\" \"${out_dir}\"\nprocess_sdram_config  \"${soc}\" \"${in_qts_dir}\" \"${in_bsp_dir}\" \"${out_dir}\"\n", "num_lines": 234}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# script to generate FIT image source for Xilinx ZynqMP boards with\n# ARM Trusted Firmware and multiple device trees (given on the command line)\n#\n# usage: $0 <dt_name> [<dt_name> [<dt_name] ...]\n\nBL33=\"u-boot-nodtb.bin\"\n[ -z \"$BL31\" ] && BL31=\"bl31.bin\"\nBL31_ELF=\"${BL31%.*}.elf\"\n[ -f ${BL31_ELF} ] && ATF_LOAD_ADDR=`${CROSS_COMPILE}readelf -l \"${BL31_ELF}\" | \\\nawk '/Entry point/ { print $3 }'`\n\n[ -z \"$ATF_LOAD_ADDR\" ] && ATF_LOAD_ADDR=\"0xfffea000\"\nATF_LOAD_ADDR_LOW=`printf 0x%x $((ATF_LOAD_ADDR & 0xffffffff))`\nATF_LOAD_ADDR_HIGH=`printf 0x%x $((ATF_LOAD_ADDR >> 32))`\n\n[ -z \"$BL32\" ] && BL32=\"tee.bin\"\nBL32_ELF=\"${BL32%.*}.elf\"\n[ -f ${BL32_ELF} ] && TEE_LOAD_ADDR=`${CROSS_COMPILE}readelf -l \"${BL32_ELF}\" | \\\nawk '/Entry point/ { print $3 }'`\n\n[ -z \"$TEE_LOAD_ADDR\" ] && TEE_LOAD_ADDR=\"0x60000000\"\nTEE_LOAD_ADDR_LOW=`printf 0x%x $((TEE_LOAD_ADDR & 0xffffffff))`\nTEE_LOAD_ADDR_HIGH=`printf 0x%x $((TEE_LOAD_ADDR >> 32))`\n\nif [ -z \"$BL33_LOAD_ADDR\" ];then\n\tBL33_LOAD_ADDR=`awk '/CONFIG_SYS_TEXT_BASE/ { print $3 }' include/generated/autoconf.h`\nfi\nBL33_LOAD_ADDR_LOW=`printf 0x%x $((BL33_LOAD_ADDR & 0xffffffff))`\nBL33_LOAD_ADDR_HIGH=`printf 0x%x $((BL33_LOAD_ADDR >> 32))`\n\nDTB_LOAD_ADDR=`awk '/CONFIG_XILINX_OF_BOARD_DTB_ADDR/ { print $3 }' include/generated/autoconf.h`\nif [ ! -z \"$DTB_LOAD_ADDR\" ]; then\n\tDTB_LOAD_ADDR_LOW=`printf 0x%x $((DTB_LOAD_ADDR & 0xffffffff))`\n\tDTB_LOAD_ADDR_HIGH=`printf 0x%x $((DTB_LOAD_ADDR >> 32))`\n\tDTB_LOAD=\"load = <$DTB_LOAD_ADDR_HIGH $DTB_LOAD_ADDR_LOW>;\"\nelse\n\tDTB_LOAD=\"\"\nfi\n\nif [ -z \"$*\" ]; then\n\tDT=arch/arm/dts/${DEVICE_TREE}.dtb\nelse\n\tDT=$*\nfi\n\nif [ ! -f $BL31 ]; then\n\techo \"WARNING: BL31 file $BL31 NOT found, U-Boot will run in EL3\" >&2\n\tBL31=/dev/null\nfi\n\ncat << __HEADER_EOF\n// SPDX-License-Identifier: (GPL-2.0-only OR BSD-2-Clause)\n\n/dts-v1/;\n\n/ {\n\tdescription = \"Configuration to load ATF before U-Boot\";\n\n\timages {\n\t\tuboot {\n\t\t\tdescription = \"U-Boot (64-bit)\";\n\t\t\tdata = /incbin/(\"$BL33\");\n\t\t\ttype = \"firmware\";\n\t\t\tos = \"u-boot\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$BL33_LOAD_ADDR_HIGH $BL33_LOAD_ADDR_LOW>;\n\t\t\tentry = <$BL33_LOAD_ADDR_HIGH $BL33_LOAD_ADDR_LOW>;\n\t\t\thash {\n\t\t\t\talgo = \"md5\";\n\t\t\t};\n\t\t};\n__HEADER_EOF\n\nif [ -f $BL31 ]; then\ncat << __ATF\n\t\tatf {\n\t\t\tdescription = \"ARM Trusted Firmware\";\n\t\t\tdata = /incbin/(\"$BL31\");\n\t\t\ttype = \"firmware\";\n\t\t\tos = \"arm-trusted-firmware\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$ATF_LOAD_ADDR_HIGH $ATF_LOAD_ADDR_LOW>;\n\t\t\tentry = <$ATF_LOAD_ADDR_HIGH $ATF_LOAD_ADDR_LOW>;\n\t\t\thash {\n\t\t\t\talgo = \"md5\";\n\t\t\t};\n\t\t};\n__ATF\nfi\n\nif [ -f $BL32 ]; then\ncat << __TEE\n\t\ttee {\n\t\t\tdescription = \"TEE firmware\";\n\t\t\tdata = /incbin/(\"$BL32\");\n\t\t\ttype = \"firmware\";\n\t\t\tos = \"tee\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <$TEE_LOAD_ADDR_HIGH $TEE_LOAD_ADDR_LOW>;\n\t\t\tentry = <$TEE_LOAD_ADDR_HIGH $TEE_LOAD_ADDR_LOW>;\n\t\t\thash {\n\t\t\t\talgo = \"md5\";\n\t\t\t};\n\t\t};\n__TEE\nfi\n\nDEFAULT=1\ncnt=1\nfor dtname in $DT\ndo\n\tcat << __FDT_IMAGE_EOF\n\t\tfdt_$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tdata = /incbin/(\"$dtname\");\n\t\t\ttype = \"flat_dt\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\t$DTB_LOAD\n\t\t\thash {\n\t\t\t\talgo = \"md5\";\n\t\t\t};\n\t\t};\n__FDT_IMAGE_EOF\n\n[ \"x$(basename $dtname .dtb)\" = \"x${DEVICE_TREE}\" ] && DEFAULT=$cnt\n\ncnt=$((cnt+1))\ndone\n\ncat << __CONF_HEADER_EOF\n\t};\n\tconfigurations {\n\t\tdefault = \"config_$DEFAULT\";\n\n__CONF_HEADER_EOF\n\ncnt=1\nfor dtname in $DT\ndo\nif [ ! -f $BL31 ]; then\ncat << __CONF_SECTION1_EOF\n\t\tconfig_$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"uboot\";\n\t\t\tfdt = \"fdt_$cnt\";\n\t\t};\n__CONF_SECTION1_EOF\nelse\nif [ -f $BL32 ]; then\ncat << __CONF_SECTION1_EOF\n\t\tconfig_$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"atf\";\n\t\t\tloadables = \"uboot\", \"tee\";\n\t\t\tfdt = \"fdt_$cnt\";\n\t\t};\n__CONF_SECTION1_EOF\nelse\ncat << __CONF_SECTION1_EOF\n\t\tconfig_$cnt {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"atf\";\n\t\t\tloadables = \"uboot\";\n\t\t\tfdt = \"fdt_$cnt\";\n\t\t};\n__CONF_SECTION1_EOF\nfi\nfi\n\ncnt=$((cnt+1))\ndone\n\ncat << __ITS_EOF\n\t};\n};\n__ITS_EOF\n", "num_lines": 184}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# Figure out if we should follow a specific parallelism from the make\n# environment (as exported by scripts/jobserver-exec), or fall back to\n# the \"auto\" parallelism when \"-jN\" is not specified at the top-level\n# \"make\" invocation.\n\nsphinx=\"$1\"\nshift || true\n\nparallel=\"$PARALLELISM\"\nif [ -z \"$parallel\" ] ; then\n\t# If no parallelism is specified at the top-level make, then\n\t# fall back to the expected \"-jauto\" mode that the \"htmldocs\"\n\t# target has had.\n\tauto=$(perl -e 'open IN,\"'\"$sphinx\"' --version 2>&1 |\";\n\t\t\twhile (<IN>) {\n\t\t\t\tif (m/([\\d\\.]+)/) {\n\t\t\t\t\tprint \"auto\" if ($1 >= \"1.7\")\n\t\t\t\t}\n\t\t\t}\n\t\t\tclose IN')\n\tif [ -n \"$auto\" ] ; then\n\t\tparallel=\"$auto\"\n\tfi\nfi\n# Only if some parallelism has been determined do we add the -jN option.\nif [ -n \"$parallel\" ] ; then\n\tparallel=\"-j$parallel\"\nfi\n\nexec \"$sphinx\" $parallel \"$@\"\n", "num_lines": 34}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nusage() {\n\techo \"Usage: $0 lzmaVERSION.tar.bz2\" >&2\n\techo >&2\n\texit 1\n}\n\nif [ \"$1\" = \"\" ] ; then\n\t usage\nfi\n\nif [ ! -f $1 ] ; then\n\techo \"$1 doesn't exist!\" >&2\n\texit 1\nfi\n\nBASENAME=`basename $1 .tar.bz2`\nTMPDIR=/tmp/tmp_lib_$BASENAME\nFILES=\"C/LzmaDec.h\n      C/Types.h\n      C/LzmaDec.c\n      history.txt\n      lzma.txt\"\n\nmkdir -p $TMPDIR\necho \"Untar $1 -> $TMPDIR\"\ntar -jxf $1 -C $TMPDIR\n\nfor i in $FILES; do\n\techo Copying  $TMPDIR/$i \\-\\> `basename $i`\n\tcp $TMPDIR/$i .\n\tchmod -x `basename $i`\ndone\n\necho \"done!\"\n", "num_lines": 37}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# binutils-version [-p] gas-command\n#\n# Prints the binutils version of `gas-command' in a canonical 4-digit form\n# such as `0222' for binutils 2.22\n#\n\ngas=\"$*\"\n\nif [ ${#gas} -eq 0 ]; then\n\techo \"Error: No assembler specified.\"\n\tprintf \"Usage:\\n\\t$0 <gas-command>\\n\"\n\texit 1\nfi\n\nversion_string=$($gas --version | head -1 | \\\n\tsed -e 's/(.*)//; s/[^0-9.]*\\([0-9.]*\\).*/\\1/')\n\nMAJOR=$(echo $version_string | cut -d . -f 1)\nMINOR=$(echo $version_string | cut -d . -f 2)\n\nprintf \"%02d%02d\\\\n\" $MAJOR $MINOR\n", "num_lines": 24}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2016 Google, Inc\n# Written by Simon Glass <sjg@chromium.org>\n#\n\n# This script creates the configuration whitelist file. This file contains\n# all the config options which are allowed to be used outside Kconfig.\n# Please do not add things to the whitelist. Instead, add your new option\n# to Kconfig.\n#\nexport LC_ALL=C LC_COLLATE=C\n\n# There are two independent greps. The first pulls out the component parts\n# of CONFIG_SYS_EXTRA_OPTIONS. An example is:\n#\n#\tSUN7I_GMAC,AHCI,SATAPWR=SUNXI_GPB(8)\n#\n# We want this to produce:\n#\tCONFIG_SUN7I_GMAC\n#\tCONFIG_AHCI\n#\tCONFIG_SATAPWR\n#\n# The second looks for the rest of the CONFIG options, but excludes those in\n# Kconfig and defconfig files.\n#\n(\ngit grep CONFIG_SYS_EXTRA_OPTIONS |sed -n \\\n\t's/.*CONFIG_SYS_EXTRA_OPTIONS=\"\\(.*\\)\"/\\1/ p' \\\n\t| tr , '\\n' \\\n\t| sed 's/ *\\([A-Za-z0-9_]*\\).*/CONFIG_\\1/'\n\ngit grep CONFIG_ | \\\n\tegrep -vi \"(Kconfig:|defconfig:|README|\\.py|\\.pl:)\" \\\n\t| tr ' \\t' '\\n\\n' \\\n\t| sed -n 's/^\\(CONFIG_[A-Za-z0-9_]*\\).*/\\1/p'\n) \\\n\t|sort |uniq >scripts/config_whitelist.txt.tmp1;\n\n# Finally, we need a list of the valid Kconfig options to exclude these from\n# the whitelist.\ncat `find . -name \"Kconfig*\"` |sed -n \\\n\t-e 's/^\\s*config *\\([A-Za-z0-9_]*\\).*$/CONFIG_\\1/p' \\\n\t-e 's/^\\s*menuconfig *\\([A-Za-z0-9_]*\\).*$/CONFIG_\\1/p' \\\n\t|sort |uniq >scripts/config_whitelist.txt.tmp2\n\n# Use only the options that are present in the first file but not the second.\ncomm -23 scripts/config_whitelist.txt.tmp1 scripts/config_whitelist.txt.tmp2 \\\n\t|sort |uniq >scripts/config_whitelist.txt.tmp3\n\n# If scripts/config_whitelist.txt already exists, take the intersection of the\n# current list and the new one.  We do not want to increase whitelist options.\nif [ -r scripts/config_whitelist.txt ]; then\n\tcomm -12 scripts/config_whitelist.txt.tmp3 scripts/config_whitelist.txt \\\n\t\t> scripts/config_whitelist.txt.tmp4\n\tmv scripts/config_whitelist.txt.tmp4 scripts/config_whitelist.txt\nelse\n\tmv scripts/config_whitelist.txt.tmp3 scripts/config_whitelist.txt\nfi\n\nrm scripts/config_whitelist.txt.tmp*\n\nunset LC_ALL LC_COLLATE\n", "num_lines": 63}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2016 Google, Inc\n# Written by Simon Glass <sjg@chromium.org>\n#\n# Check that the u-boot.cfg file provided does not introduce any new\n# ad-hoc CONFIG options\n#\n# Use scripts/build-whitelist.sh to generate the list of current ad-hoc\n# CONFIG options (those which are not in Kconfig).\n\n# Usage\n#    check-config.sh <path to u-boot.cfg> <path to whitelist file> <source dir>\n#\n# For example:\n#   scripts/check-config.sh b/chromebook_link/u-boot.cfg kconfig_whitelist.txt .\n\nset -e\nset -u\n\nPROG_NAME=\"${0##*/}\"\n\nusage() {\n\techo \"$PROG_NAME <path to u-boot.cfg> <path to whitelist file> <source dir>\"\n\texit 1\n}\n\n[ $# -ge 3 ] || usage\n\npath=\"$1\"\nwhitelist=\"$2\"\nsrctree=\"$3\"\n\n# Temporary files\nconfigs=\"${path}.configs\"\nsuspects=\"${path}.suspects\"\nok=\"${path}.ok\"\nnew_adhoc=\"${path}.adhoc\"\n\nexport LC_ALL=C\nexport LC_COLLATE=C\n\ncat ${path} |sed -nr 's/^#define (CONFIG_[A-Za-z0-9_]*).*/\\1/p' |sort |uniq \\\n\t>${configs}\n\ncomm -23 ${configs} ${whitelist} > ${suspects}\n\ncat `find ${srctree} -name \"Kconfig*\"` |sed -nr \\\n\t-e 's/^[[:blank:]]*config *([A-Za-z0-9_]*).*$/CONFIG_\\1/p' \\\n\t-e 's/^[[:blank:]]*menuconfig ([A-Za-z0-9_]*).*$/CONFIG_\\1/p' \\\n\t|sort |uniq > ${ok}\ncomm -23 ${suspects} ${ok} >${new_adhoc}\nif [ -s ${new_adhoc} ]; then\n\techo >&2 \"Error: You must add new CONFIG options using Kconfig\"\n\techo >&2 \"The following new ad-hoc CONFIG options were detected:\"\n\tcat >&2 ${new_adhoc}\n\techo >&2\n\techo >&2 \"Please add these via Kconfig instead. Find a suitable Kconfig\"\n\techo >&2 \"file and add a 'config' or 'menuconfig' option.\"\n\t# Don't delete the temporary files in case they are useful\n\texit 1\nelse\n\trm ${suspects} ${ok} ${new_adhoc}\nfi\n", "num_lines": 64}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n#\n# clang-version [-p] clang-command\n#\n# Prints the compiler version of `clang-command' in a canonical 4-digit form\n# such as `0500' for clang-5.0 etc.\n#\n# With the -p option, prints the patchlevel as well, for example `050001' for\n# clang-5.0.1 etc.\n#\n\ncompiler=\"$*\"\n\nif ! ( $compiler --version | grep -q clang) ; then\n\techo 0\n\texit 1\nfi\n\nMAJOR=$(echo __clang_major__ | $compiler -E -x c - | tail -n 1)\nMINOR=$(echo __clang_minor__ | $compiler -E -x c - | tail -n 1)\nPATCHLEVEL=$(echo __clang_patchlevel__ | $compiler -E -x c - | tail -n 1)\nprintf \"%d%02d%02d\\\\n\" $MAJOR $MINOR $PATCHLEVEL\n", "num_lines": 24}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n# Test for gcc '-fstack-usage' support\n# Copyright (C) 2013, Masahiro Yamada <yamada.m@jp.panasonic.com>\n#\n\nTMP=\"$$\"\n\ncat <<END | $@ -Werror -fstack-usage -x c - -c -o $TMP >/dev/null 2>&1 \\\n\t\t\t\t\t\t\t&& echo \"y\"\nint main(void)\n{\n\treturn 0;\n}\nEND\n\nrm -f $TMP $TMP.su\n", "num_lines": 18}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n#\n# gcc-version [-p] gcc-command\n#\n# Prints the gcc version of `gcc-command' in a canonical 4-digit form\n# such as `0295' for gcc-2.95, `0303' for gcc-3.3, etc.\n#\n# With the -p option, prints the patchlevel as well, for example `029503' for\n# gcc-2.95.3, `030301' for gcc-3.3.1, etc.\n#\n\nif [ \"$1\" = \"-p\" ] ; then\n\twith_patchlevel=1;\n\tshift;\nfi\n\ncompiler=\"$*\"\n\nif [ ${#compiler} -eq 0 ]; then\n\techo \"Error: No compiler specified.\"\n\tprintf \"Usage:\\n\\t$0 <gcc-command>\\n\"\n\texit 1\nfi\n\nMAJOR=$(echo __GNUC__ | $compiler -E -x c - | tail -n 1)\nMINOR=$(echo __GNUC_MINOR__ | $compiler -E -x c - | tail -n 1)\nif [ \"x$with_patchlevel\" != \"x\" ] ; then\n\tPATCHLEVEL=$(echo __GNUC_PATCHLEVEL__ | $compiler -E -x c - | tail -n 1)\n\tprintf \"%02d%02d%02d\\\\n\" $MAJOR $MINOR $PATCHLEVEL\nelse\n\tprintf \"%02d%02d\\\\n\" $MAJOR $MINOR\nfi\n", "num_lines": 34}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n# Copyright (C) 2020 Marek Beh\u00c3\u00ban <marek.behun@nic.cz>\n\n# Generate __ADDRESSABLE(symbol) for every linker list entry symbol, so that LTO\n# does not optimize these symbols away\n\n# The expected parameter of this script is the command requested to have\n# the U-Boot symbols to parse, for example: $(NM) $(u-boot-main)\n\nset -e\n\necho '#include <common.h>'\n$@ 2>/dev/null | grep -oe '_u_boot_list_2_[a-zA-Z0-9_]*_2_[a-zA-Z0-9_]*' | \\\n\tsort -u | sed -e 's/^\\(.*\\)/extern char \\1[];\\n__ADDRESSABLE(\\1);/'\n", "num_lines": 16}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n#\n# Copyright (C) 2016, Lukasz Majewski <l.majewski@majess.pl>\n#\n\n# This file extracts default envs from built u-boot\n# usage: get_default_envs.sh [build dir] > u-boot-env-default.txt\nset -ue\n\n: \"${OBJCOPY:=${CROSS_COMPILE:-}objcopy}\"\n\nENV_OBJ_FILE=\"common.o\"\nENV_OBJ_FILE_COPY=\"copy_${ENV_OBJ_FILE}\"\n\nechoerr() { echo \"$@\" 1>&2; }\n\nif [ \"$#\" -eq 1 ]; then\n    path=${1}\nelse\n    path=$(readlink -f $0)\n    path=${path%/scripts*}\nfi\n\nenv_obj_file_path=$(find ${path} -path \"*/env/*\" -not -path \"*/spl/*\" \\\n\t\t\t -not -path \"*/tools/*\" -name \"${ENV_OBJ_FILE}\")\n[ -z \"${env_obj_file_path}\" ] && \\\n    { echoerr \"File '${ENV_OBJ_FILE}' not found!\"; exit 1; }\n\ncp ${env_obj_file_path} ${ENV_OBJ_FILE_COPY}\n\n# NOTE: objcopy saves its output to file passed in\n# (copy_${ENV_OBJ_FILE} in this case)\n\n${OBJCOPY} --dump-section .rodata.default_environment=${ENV_OBJ_FILE_COPY} \\\n\t${env_obj_file_path}\n\n# Replace default '\\0' with '\\n' and sort entries\ntr '\\0' '\\n' < ${ENV_OBJ_FILE_COPY} | sort --field-separator== -k1,1 --stable\n\nrm ${ENV_OBJ_FILE_COPY}\n\nexit 0\n", "num_lines": 44}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/awk -f\n# SPDX-License-Identifier: GPL-2.0\n# extract linker version number from stdin and turn into single number\n\t{\n\tgsub(\".*\\\\)\", \"\");\n\tgsub(\".*version \", \"\");\n\tgsub(\"-.*\", \"\");\n\tsplit($1,a, \".\");\n\tprint a[1]*100000000 + a[2]*1000000 + a[3]*10000;\n\texit\n\t}\n", "num_lines": 12}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n# Simple script to update the version of DTC carried by the Linux kernel\n#\n# This script assumes that the dtc and the linux git trees are in the\n# same directory. After building dtc in the dtc directory, it copies the\n# source files and generated source file(s) into the scripts/dtc directory\n# in the kernel and creates a git commit updating them to the new\n# version.\n#\n# Usage: from the top level Linux source tree, run:\n# $ ./scripts/dtc/update-dtc-source.sh\n#\n# The script will change into the dtc tree, build and test dtc, copy the\n# relevant files into the kernel tree and create a git commit. The commit\n# message will need to be modified to reflect the version of DTC being\n# imported\n#\n# TODO:\n# This script is pretty basic, but it is seldom used so a few manual tasks\n# aren't a big deal. If anyone is interested in making it more robust, the\n# the following would be nice:\n# * Actually fail to complete if any testcase fails.\n#   - The dtc \"make check\" target needs to return a failure\n# * Extract the version number from the dtc repo for the commit message\n# * Build dtc in the kernel tree\n# * run 'make check\" on dtc built from the kernel tree\n\nset -ev\n\nDTC_UPSTREAM_PATH=`pwd`/../dtc\nDTC_LINUX_PATH=`pwd`/scripts/dtc\n\nDTC_SOURCE=\"checks.c data.c dtc.c dtc.h flattree.c fstree.c livetree.c srcpos.c \\\n\t\tsrcpos.h treesource.c util.c util.h version_gen.h Makefile.dtc \\\n\t\tdtc-lexer.l dtc-parser.y\"\nLIBFDT_SOURCE=\"Makefile.libfdt fdt.c fdt.h fdt_addresses.c fdt_empty_tree.c \\\n\t\tfdt_overlay.c fdt_ro.c fdt_rw.c fdt_strerror.c fdt_sw.c \\\n\t\tfdt_wip.c libfdt.h libfdt_env.h libfdt_internal.h\"\n\nget_last_dtc_version() {\n\tgit log --oneline scripts/dtc/ | grep 'upstream' | head -1 | sed -e 's/^.* \\(.*\\)/\\1/'\n}\n\nlast_dtc_ver=$(get_last_dtc_version)\n\n# Build DTC\ncd $DTC_UPSTREAM_PATH\nmake clean\nmake check\ndtc_version=$(git describe HEAD)\ndtc_log=$(git log --oneline ${last_dtc_ver}..)\n\n\n# Copy the files into the Linux tree\ncd $DTC_LINUX_PATH\nfor f in $DTC_SOURCE; do\n\tcp ${DTC_UPSTREAM_PATH}/${f} ${f}\n\tgit add ${f}\ndone\nfor f in $LIBFDT_SOURCE; do\n       cp ${DTC_UPSTREAM_PATH}/libfdt/${f} libfdt/${f}\n       git add libfdt/${f}\ndone\n\nsed -i -- 's/#include <libfdt_env.h>/#include \"libfdt_env.h\"/g' ./libfdt/libfdt.h\nsed -i -- 's/#include <fdt.h>/#include \"fdt.h\"/g' ./libfdt/libfdt.h\ngit add ./libfdt/libfdt.h\n\ncommit_msg=$(cat << EOF\nscripts/dtc: Update to upstream version ${dtc_version}\n\nThis adds the following commits from upstream:\n\n${dtc_log}\nEOF\n)\n\ngit commit -e -v -s -m \"${commit_msg}\"\n", "num_lines": 80}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n\nPKG=\"gtk+-2.0 gmodule-2.0 libglade-2.0\"\n\nif [ -z \"$(command -v pkg-config)\" ]; then\n\techo >&2 \"*\"\n\techo >&2 \"* 'make gconfig' requires 'pkg-config'. Please install it.\"\n\techo >&2 \"*\"\n\texit 1\nfi\n\nif ! pkg-config --exists $PKG; then\n\techo >&2 \"*\"\n\techo >&2 \"* Unable to find the GTK+ installation. Please make sure that\"\n\techo >&2 \"* the GTK+ 2.0 development package is correctly installed.\"\n\techo >&2 \"* You need $PKG\"\n\techo >&2 \"*\"\n\texit 1\nfi\n\nif ! pkg-config --atleast-version=2.0.0 gtk+-2.0; then\n\techo >&2 \"*\"\n\techo >&2 \"* GTK+ is present but version >= 2.0.0 is required.\"\n\techo >&2 \"*\"\n\texit 1\nfi\n\necho cflags=\\\"$(pkg-config --cflags $PKG)\\\"\necho libs=\\\"$(pkg-config --libs $PKG)\\\"\n", "num_lines": 31}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n\nPKG=\"ncursesw\"\nPKG2=\"ncurses\"\n\nif [ -n \"$(command -v pkg-config)\" ]; then\n\tif pkg-config --exists $PKG; then\n\t\techo cflags=\\\"$(pkg-config --cflags $PKG)\\\"\n\t\techo libs=\\\"$(pkg-config --libs $PKG)\\\"\n\t\texit 0\n\tfi\n\n\tif pkg-config --exists $PKG2; then\n\t\techo cflags=\\\"$(pkg-config --cflags $PKG2)\\\"\n\t\techo libs=\\\"$(pkg-config --libs $PKG2)\\\"\n\t\texit 0\n\tfi\nfi\n\n# Check the default paths in case pkg-config is not installed.\n# (Even if it is installed, some distributions such as openSUSE cannot\n# find ncurses by pkg-config.)\nif [ -f /usr/include/ncursesw/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE -I/usr/include/ncursesw\\\"\n\techo libs=\\\"-lncursesw\\\"\n\texit 0\nfi\n\nif [ -f /usr/include/ncurses/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE -I/usr/include/ncurses\\\"\n\techo libs=\\\"-lncurses\\\"\n\texit 0\nfi\n\nif [ -f /usr/include/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE\\\"\n\techo libs=\\\"-lncurses\\\"\n\texit 0\nfi\n\necho >&2 \"*\"\necho >&2 \"* Unable to find the ncurses package.\"\necho >&2 \"* Install ncurses (ncurses-devel or libncurses-dev\"\necho >&2 \"* depending on your distribution).\"\necho >&2 \"*\"\nexit 1\n", "num_lines": 48}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#  merge_config.sh - Takes a list of config fragment values, and merges\n#  them one by one. Provides warnings on overridden values, and specified\n#  values that did not make it to the resulting .config file (due to missed\n#  dependencies or config symbol removal).\n#\n#  Portions reused from kconf_check and generate_cfg:\n#  http://git.yoctoproject.org/cgit/cgit.cgi/yocto-kernel-tools/tree/tools/kconf_check\n#  http://git.yoctoproject.org/cgit/cgit.cgi/yocto-kernel-tools/tree/tools/generate_cfg\n#\n#  Copyright (c) 2009-2010 Wind River Systems, Inc.\n#  Copyright 2011 Linaro\n#\n#  This program is free software; you can redistribute it and/or modify\n#  it under the terms of the GNU General Public License version 2 as\n#  published by the Free Software Foundation.\n#\n#  This program is distributed in the hope that it will be useful,\n#  but WITHOUT ANY WARRANTY; without even the implied warranty of\n#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#  See the GNU General Public License for more details.\n\nclean_up() {\n\trm -f $TMP_FILE\n\texit\n}\ntrap clean_up HUP INT TERM\n\nusage() {\n\techo \"Usage: $0 [OPTIONS] [CONFIG [...]]\"\n\techo \"  -h    display this help text\"\n\techo \"  -m    only merge the fragments, do not execute the make command\"\n\techo \"  -n    use allnoconfig instead of alldefconfig\"\n\techo \"  -r    list redundant entries when merging fragments\"\n\techo \"  -O    dir to put generated output files.  Consider setting \\$KCONFIG_CONFIG instead.\"\n\techo\n\techo \"Used prefix: '$CONFIG_PREFIX'. You can redefine it with \\$CONFIG_ environment variable.\"\n}\n\nRUNMAKE=true\nALLTARGET=alldefconfig\nWARNREDUN=false\nOUTPUT=.\nCONFIG_PREFIX=${CONFIG_-CONFIG_}\n\nwhile true; do\n\tcase $1 in\n\t\"-n\")\n\t\tALLTARGET=allnoconfig\n\t\tshift\n\t\tcontinue\n\t\t;;\n\t\"-m\")\n\t\tRUNMAKE=false\n\t\tshift\n\t\tcontinue\n\t\t;;\n\t\"-h\")\n\t\tusage\n\t\texit\n\t\t;;\n\t\"-r\")\n\t\tWARNREDUN=true\n\t\tshift\n\t\tcontinue\n\t\t;;\n\t\"-O\")\n\t\tif [ -d $2 ];then\n\t\t\tOUTPUT=$(echo $2 | sed 's/\\/*$//')\n\t\telse\n\t\t\techo \"output directory $2 does not exist\" 1>&2\n\t\t\texit 1\n\t\tfi\n\t\tshift 2\n\t\tcontinue\n\t\t;;\n\t*)\n\t\tbreak\n\t\t;;\n\tesac\ndone\n\nif [ \"$#\" -lt 1 ] ; then\n\tusage\n\texit\nfi\n\nif [ -z \"$KCONFIG_CONFIG\" ]; then\n\tif [ \"$OUTPUT\" != . ]; then\n\t\tKCONFIG_CONFIG=$(readlink -m -- \"$OUTPUT/.config\")\n\telse\n\t\tKCONFIG_CONFIG=.config\n\tfi\nfi\n\nINITFILE=$1\nshift;\n\nif [ ! -r \"$INITFILE\" ]; then\n\techo \"The base file '$INITFILE' does not exist.  Exit.\" >&2\n\texit 1\nfi\n\nMERGE_LIST=$*\nSED_CONFIG_EXP1=\"s/^\\(${CONFIG_PREFIX}[a-zA-Z0-9_]*\\)=.*/\\1/p\"\nSED_CONFIG_EXP2=\"s/^# \\(${CONFIG_PREFIX}[a-zA-Z0-9_]*\\) is not set$/\\1/p\"\n\nTMP_FILE=$(mktemp ./.tmp.config.XXXXXXXXXX)\n\necho \"Using $INITFILE as base\"\ncat $INITFILE > $TMP_FILE\n\n# Merge files, printing warnings on overridden values\nfor MERGE_FILE in $MERGE_LIST ; do\n\techo \"Merging $MERGE_FILE\"\n\tif [ ! -r \"$MERGE_FILE\" ]; then\n\t\techo \"The merge file '$MERGE_FILE' does not exist.  Exit.\" >&2\n\t\texit 1\n\tfi\n\tCFG_LIST=$(sed -n -e \"$SED_CONFIG_EXP1\" -e \"$SED_CONFIG_EXP2\" $MERGE_FILE)\n\n\tfor CFG in $CFG_LIST ; do\n\t\tgrep -q -w $CFG $TMP_FILE || continue\n\t\tPREV_VAL=$(grep -w $CFG $TMP_FILE)\n\t\tNEW_VAL=$(grep -w $CFG $MERGE_FILE)\n\t\tif [ \"x$PREV_VAL\" != \"x$NEW_VAL\" ] ; then\n\t\t\techo Value of $CFG is redefined by fragment $MERGE_FILE:\n\t\t\techo Previous  value: $PREV_VAL\n\t\t\techo New value:       $NEW_VAL\n\t\t\techo\n\t\telif [ \"$WARNREDUN\" = \"true\" ]; then\n\t\t\techo Value of $CFG is redundant by fragment $MERGE_FILE:\n\t\tfi\n\t\tsed -i \"/$CFG[ =]/d\" $TMP_FILE\n\tdone\n\tcat $MERGE_FILE >> $TMP_FILE\ndone\n\nif [ \"$RUNMAKE\" = \"false\" ]; then\n\tcp -T -- \"$TMP_FILE\" \"$KCONFIG_CONFIG\"\n\techo \"#\"\n\techo \"# merged configuration written to $KCONFIG_CONFIG (needs make)\"\n\techo \"#\"\n\tclean_up\n\texit\nfi\n\n# If we have an output dir, setup the O= argument, otherwise leave\n# it blank, since O=. will create an unnecessary ./source softlink\nOUTPUT_ARG=\"\"\nif [ \"$OUTPUT\" != \".\" ] ; then\n\tOUTPUT_ARG=\"O=$OUTPUT\"\nfi\n\n\n# Use the merged file as the starting point for:\n# alldefconfig: Fills in any missing symbols with Kconfig default\n# allnoconfig: Fills in any missing symbols with # CONFIG_* is not set\nmake KCONFIG_ALLCONFIG=$TMP_FILE $OUTPUT_ARG $ALLTARGET\n\n\n# Check all specified config values took (might have missed-dependency issues)\nfor CFG in $(sed -n -e \"$SED_CONFIG_EXP1\" -e \"$SED_CONFIG_EXP2\" $TMP_FILE); do\n\n\tREQUESTED_VAL=$(grep -w -e \"$CFG\" $TMP_FILE)\n\tACTUAL_VAL=$(grep -w -e \"$CFG\" \"$KCONFIG_CONFIG\")\n\tif [ \"x$REQUESTED_VAL\" != \"x$ACTUAL_VAL\" ] ; then\n\t\techo \"Value requested for $CFG not in final .config\"\n\t\techo \"Requested value:  $REQUESTED_VAL\"\n\t\techo \"Actual value:     $ACTUAL_VAL\"\n\t\techo \"\"\n\tfi\ndone\n\nclean_up\n", "num_lines": 176}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n\nPKG=\"ncursesw menuw panelw\"\nPKG2=\"ncurses menu panel\"\n\nif [ -n \"$(command -v pkg-config)\" ]; then\n\tif pkg-config --exists $PKG; then\n\t\techo cflags=\\\"$(pkg-config --cflags $PKG)\\\"\n\t\techo libs=\\\"$(pkg-config --libs $PKG)\\\"\n\t\texit 0\n\tfi\n\n\tif pkg-config --exists $PKG2; then\n\t\techo cflags=\\\"$(pkg-config --cflags $PKG2)\\\"\n\t\techo libs=\\\"$(pkg-config --libs $PKG2)\\\"\n\t\texit 0\n\tfi\nfi\n\n# Check the default paths in case pkg-config is not installed.\n# (Even if it is installed, some distributions such as openSUSE cannot\n# find ncurses by pkg-config.)\nif [ -f /usr/include/ncursesw/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE -I/usr/include/ncursesw\\\"\n\techo libs=\\\"-lncursesw -lmenuw -lpanelw\\\"\n\texit 0\nfi\n\nif [ -f /usr/include/ncurses/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE -I/usr/include/ncurses\\\"\n\techo libs=\\\"-lncurses -lmenu -lpanel\\\"\n\texit 0\nfi\n\nif [ -f /usr/include/ncurses.h ]; then\n\techo cflags=\\\"-D_GNU_SOURCE\\\"\n\techo libs=\\\"-lncurses -lmenu -lpanel\\\"\n\texit 0\nfi\n\necho >&2 \"*\"\necho >&2 \"* Unable to find the ncurses package.\"\necho >&2 \"* Install ncurses (ncurses-devel or libncurses-dev\"\necho >&2 \"* depending on your distribution).\"\necho >&2 \"*\"\nexit 1\n", "num_lines": 48}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0\n\nPKG=\"Qt5Core Qt5Gui Qt5Widgets\"\nPKG2=\"QtCore QtGui\"\n\nif [ -z \"$(command -v pkg-config)\" ]; then\n\techo >&2 \"*\"\n\techo >&2 \"* 'make xconfig' requires 'pkg-config'. Please install it.\"\n\techo >&2 \"*\"\n\texit 1\nfi\n\nif pkg-config --exists $PKG; then\n\techo cflags=\\\"-std=c++11 -fPIC $(pkg-config --cflags Qt5Core Qt5Gui Qt5Widgets)\\\"\n\techo libs=\\\"$(pkg-config --libs $PKG)\\\"\n\techo moc=\\\"$(pkg-config --variable=host_bins Qt5Core)/moc\\\"\n\texit 0\nfi\n\nif pkg-config --exists $PKG2; then\n\techo cflags=\\\"$(pkg-config --cflags $PKG2)\\\"\n\techo libs=\\\"$(pkg-config --libs $PKG2)\\\"\n\techo moc=\\\"$(pkg-config --variable=moc_location QtCore)\\\"\n\texit 0\nfi\n\necho >&2 \"*\"\necho >&2 \"* Could not find Qt via pkg-config.\"\necho >&2 \"* Please install either Qt 4.8 or 5.x. and make sure it's in PKG_CONFIG_PATH\"\necho >&2 \"*\"\nexit 1\n", "num_lines": 33}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nOUTPUT_DIR=sandbox\n\nfail() {\n\techo \"Test failed: $1\"\n\tif [ -n ${tmp} ]; then\n\t\trm ${tmp}\n\tfi\n\texit 1\n}\n\nbuild_uboot() {\n\techo \"Build sandbox\"\n\tOPTS=\"O=${OUTPUT_DIR} $1\"\n\tNUM_CPUS=$(nproc)\n\techo ${OPTS}\n\tmake ${OPTS} sandbox_config\n\tmake ${OPTS} -s -j${NUM_CPUS}\n}\n", "num_lines": 21}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# SPDX-License-Identifier: GPL-2.0+\n# (C) 2020 Pali Roh\u00c3\u00a1r <pali@kernel.org>\n\n# External tools needed for this test:\necho '\n\twget\n\tgit\n\ttruncate\n\ttar\n\tdpkg\n\tdd\n\tmake\n\tgcc\n\tarm-linux-gnueabi-gcc\n\tfakeroot\t\t(homepage http://fakeroot-ng.lingnu.com/)\n\tmcopy\t\t\t(from mtools, homepage http://www.gnu.org/software/mtools/)\n\tmformat\t\t\t(from mtools, homepage http://www.gnu.org/software/mtools/)\n\t/usr/sbin/mkfs.ubifs\t(from mtd-utils, homepage http://www.linux-mtd.infradead.org/)\n\t/usr/sbin/ubinize\t(from mtd-utils, homepage http://www.linux-mtd.infradead.org/)\n\t/lib/ld-linux.so.2\t(32-bit x86 version of LD loader, needed for qflasher)\n' | while read tool info; do\n\tif test -z \"$tool\"; then continue; fi\n\tif ! which $tool 1>/dev/null 2>&1; then\n\t\techo \"Tool $tool was not found and is required to run this test\"\n\t\techo \"First install $tool $info\"\n\t\texit 1\n\tfi\ndone || exit 1\n\necho\necho \"============================================================\"\necho \"========== Compiling U-Boot for Nokia RX-51 board ==========\"\necho \"============================================================\"\necho\n\n# First compile u-boot.bin binary for Nokia RX-51 board\nmake nokia_rx51_config\nmake -j4 u-boot.bin ARCH=arm CROSS_COMPILE=arm-linux-gnueabi-\n\n# And then do all stuff in temporary directory\nmkdir -p nokia_rx51_tmp\ncd nokia_rx51_tmp\n\ntest -f mkimage || ln -s ../tools/mkimage .\ntest -f u-boot.bin || ln -s ../u-boot.bin .\n\necho\necho \"==========================================================================\"\necho \"========== Downloading and compiling qemu from qemu-linaro fork ==========\"\necho \"==========================================================================\"\necho\n\n# Download and compile linaro version qemu which has support for n900 machine\n# Last working commit is 8f8d8e0796efe1a6f34cdd83fb798f3c41217ec1\nif ! test -f qemu-system-arm; then\n\ttest -d qemu-linaro || git clone https://git.linaro.org/qemu/qemu-linaro.git\n\tcd qemu-linaro\n\tgit checkout 8f8d8e0796efe1a6f34cdd83fb798f3c41217ec1\n\t./configure --enable-system --target-list=arm-softmmu --python=/usr/bin/python2.7 --disable-sdl --disable-gtk --disable-curses --audio-drv-list= --audio-card-list= --disable-werror --disable-xen --disable-xen-pci-passthrough --disable-brlapi --disable-vnc --disable-curl --disable-slirp --disable-kvm --disable-user --disable-linux-user --disable-bsd-user --disable-guest-base --disable-uuid --disable-vde --disable-linux-aio --disable-cap-ng --disable-attr --disable-blobs --disable-docs --disable-spice --disable-libiscsi --disable-smartcard-nss --disable-usb-redir --disable-guest-agent --disable-seccomp --disable-glusterfs --disable-nptl --disable-fdt\n\tmake -j4\n\tcd ..\n\tln -s qemu-linaro/arm-softmmu/qemu-system-arm .\nfi\n\necho\necho \"===================================================\"\necho \"========== Downloading external binaries ==========\"\necho \"===================================================\"\necho\n\n# Download qflasher and nolo images\n# This is proprietary qemu flasher tool with first stage images, but license allows non-commercial redistribution\nwget -c http://repository.maemo.org/qemu-n900/qemu-n900.tar.gz\ntar -xf qemu-n900.tar.gz\n\n# Download Maemo script u-boot-gen-combined\nif ! test -f u-boot-gen-combined; then\n\ttest -d u-boot-maemo || git clone https://github.com/pali/u-boot-maemo.git\n\tchmod +x u-boot-maemo/debian/u-boot-gen-combined\n\tln -s u-boot-maemo/debian/u-boot-gen-combined .\nfi\n\n# Download Maemo fiasco kernel\nwget -c http://repository.maemo.org/pool/maemo5.0/free/k/kernel/kernel_2.6.28-20103103+0m5_armel.deb\ndpkg -x kernel_2.6.28-20103103+0m5_armel.deb kernel_2.6.28\n\n# Download Maemo libc\nwget -c http://repository.maemo.org/pool/maemo5.0/free/g/glibc/libc6_2.5.1-1eglibc27+0m5_armel.deb\ndpkg -x libc6_2.5.1-1eglibc27+0m5_armel.deb libc6_2.5.1\n\n# Download Maemo busybox\nwget -c http://repository.maemo.org/pool/maemo5.0/free/b/busybox/busybox_1.10.2.legal-1osso30+0m5_armel.deb\ndpkg -x busybox_1.10.2.legal-1osso30+0m5_armel.deb busybox_1.10.2\n\necho\necho \"=======================================\"\necho \"========== Generating images ==========\"\necho \"=======================================\"\necho\n\n# Generate rootfs directory\nmkdir -p rootfs\nmkdir -p rootfs/dev/\nmkdir -p rootfs/bin/\nmkdir -p rootfs/sbin/\nmkdir -p rootfs/lib/\ncp -a busybox_1.10.2/bin/busybox rootfs/bin/\ncp -a libc6_2.5.1/lib/ld-linux.so.3 rootfs/lib/\ncp -a libc6_2.5.1/lib/ld-2.5.so rootfs/lib/\ncp -a libc6_2.5.1/lib/libc.so.6 rootfs/lib/\ncp -a libc6_2.5.1/lib/libc-2.5.so rootfs/lib/\ncp -a libc6_2.5.1/lib/libcrypt.so.1 rootfs/lib/\ncp -a libc6_2.5.1/lib/libcrypt-2.5.so rootfs/lib/\ntest -f rootfs/bin/sh || ln -sf busybox rootfs/bin/sh\ntest -f rootfs/sbin/poweroff || ln -sf ../bin/busybox rootfs/sbin/poweroff\ncat > rootfs/sbin/preinit << EOF\n#!/bin/sh\necho\necho \"Successfully booted\"\necho\n/sbin/poweroff -f\nEOF\nchmod +x rootfs/sbin/preinit\n\n# Generate ubi config file for ubi rootfs image\ncat > ubi.ini << EOF\n[rootfs]\nmode=ubi\nimage=ubifs.img\nvol_id=0\nvol_size=160MiB\nvol_type=dynamic\nvol_name=rootfs\nvol_alignment=1\nvol_flags=autoresize\nEOF\n\n# Generate ubi rootfs image from rootfs directory\n# NOTE: Character device on host filesystem can be created only by root\n#       But we do not need it on host filesystem, just in ubifs image\n#       So run mknod and mkfs.ubifs commands under fakeroot program\n#       which via LD_PRELOAD simulate mknod() and stat() functions\n#       so mkfs.ubifs will see dev/console as character device and\n#       put it correctly as character device into final ubifs image\n#       Therefore we can run whole script as non-root nobody user\nfakeroot sh -c '\n\trm -f rootfs/dev/console;\n\tmknod rootfs/dev/console c 5 1;\n\t/usr/sbin/mkfs.ubifs -m 2048 -e 129024 -c 2047 -r rootfs ubifs.img;\n'\n/usr/sbin/ubinize -o ubi.img -p 128KiB -m 2048 -s 512 ubi.ini\n\n# Generate bootmenu for U-Boot serial console testing\ncat > bootmenu_uboot << EOF\nsetenv bootmenu_0 'Serial console test=echo; echo \"Testing serial console\"; echo; echo \"Successfully booted\"; echo; poweroff';\nsetenv bootmenu_1;\nsetenv bootmenu_delay 1;\nsetenv bootdelay 1;\nEOF\n./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_uboot -d bootmenu_uboot bootmenu_uboot.scr\n\n# Generate bootmenu for eMMC booting (uImage)\ncat > bootmenu_emmc << EOF\nsetenv bootmenu_0 'uImage-2.6.28-omap1 from eMMC=setenv mmcnum 1; setenv mmcpart 1; setenv mmctype fat; setenv bootargs; setenv setup_omap_atag 1; setenv mmckernfile uImage-2.6.28-omap1; run trymmckernboot';\nsetenv bootmenu_1;\nsetenv bootmenu_delay 1;\nsetenv bootdelay 1;\nEOF\n./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_emmc -d bootmenu_emmc bootmenu_emmc.scr\n\n# Generate bootmenu for eMMC booting (zImage)\ncat > bootmenu_emmc2 << EOF\nsetenv bootmenu_0 'zImage-2.6.28-omap1 from eMMC=setenv mmcnum 1; setenv mmcpart 1; setenv mmctype fat; setenv bootargs; setenv setup_omap_atag 1; setenv mmckernfile zImage-2.6.28-omap1; run trymmckernboot';\nsetenv bootmenu_1;\nsetenv bootmenu_delay 1;\nsetenv bootdelay 1;\nEOF\n./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_emmc2 -d bootmenu_emmc2 bootmenu_emmc2.scr\n\n# Generate bootmenu for OneNAND booting\ncat > bootmenu_nand << EOF\nsetenv bootmenu_0 'uImage-2.6.28-omap1 from OneNAND=mtd read initfs \\${kernaddr}; setenv bootargs; setenv setup_omap_atag 1; bootm \\${kernaddr}';\nsetenv bootmenu_1;\nsetenv bootmenu_delay 1;\nsetenv bootdelay 1;\nEOF\n./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_nand -d bootmenu_nand bootmenu_nand.scr\n\n# Generate bootmenu for default booting\ncat > bootmenu_default << EOF\nsetenv bootmenu_delay 1;\nsetenv bootdelay 1;\nEOF\n./mkimage -A arm -O linux -T script -C none -a 0 -e 0 -n bootmenu_default -d bootmenu_default bootmenu_default.scr\n\n# Generate combined image from u-boot and Maemo fiasco kernel\ndd if=kernel_2.6.28/boot/zImage-2.6.28-20103103+0m5.fiasco of=zImage-2.6.28-omap1 skip=95 bs=1\n./u-boot-gen-combined u-boot.bin zImage-2.6.28-omap1 combined_zimage.bin\n./mkimage -A arm -O linux -T kernel -C none -a 80008000 -e 80008000 -n zImage-2.6.28-omap1 -d zImage-2.6.28-omap1 uImage-2.6.28-omap1\n./u-boot-gen-combined u-boot.bin uImage-2.6.28-omap1 combined_uimage.bin\n\n# Generate combined hack image from u-boot and Maemo fiasco kernel (kernel starts at 2MB offset and qflasher puts 2kB header before supplied image)\ncp u-boot.bin combined_hack.bin\ndd if=uImage-2.6.28-omap1 of=combined_hack.bin bs=1024 seek=$((2048-2))\n\n# Generate FAT32 eMMC image for U-Boot serial console testing\ntruncate -s 50MiB emmc_uboot.img\nmformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_uboot.img\nmcopy bootmenu_uboot.scr ::/bootmenu.scr -i emmc_uboot.img\n\n# Generate FAT32 eMMC image for eMMC booting (uImage)\ntruncate -s 50MiB emmc_emmc.img\nmformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_emmc.img\nmcopy uImage-2.6.28-omap1 ::/uImage-2.6.28-omap1 -i emmc_emmc.img\nmcopy bootmenu_emmc.scr ::/bootmenu.scr -i emmc_emmc.img\n\n# Generate FAT32 eMMC image for eMMC booting (zImage)\ntruncate -s 50MiB emmc_emmc2.img\nmformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_emmc2.img\nmcopy zImage-2.6.28-omap1 ::/zImage-2.6.28-omap1 -i emmc_emmc2.img\nmcopy bootmenu_emmc2.scr ::/bootmenu.scr -i emmc_emmc2.img\n\n# Generate FAT32 eMMC image for OneNAND booting\ntruncate -s 50MiB emmc_nand.img\nmformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_nand.img\nmcopy bootmenu_nand.scr ::/bootmenu.scr -i emmc_nand.img\n\n# Generate FAT32 eMMC image for default booting\ntruncate -s 50MiB emmc_default.img\nmformat -m 0xf8 -F -h 4 -s 16 -c 1 -t $((50*1024*1024/(4*16*512))) :: -i emmc_default.img\nmcopy bootmenu_default.scr ::/bootmenu.scr -i emmc_default.img\n\n# Generate MTD image for U-Boot serial console testing\nrm -f mtd_uboot.img\n./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k u-boot.bin -m rx51 -o mtd_uboot.img\n\n# Generate MTD image for RAM booting from bootloader nolo images, compiled image and rootfs image\nrm -f mtd_ram.img\n./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_uimage.bin -r ubi.img -m rx51 -o mtd_ram.img\nrm -f mtd_ram2.img\n./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_zimage.bin -r ubi.img -m rx51 -o mtd_ram2.img\n\n# Generate MTD image for eMMC booting from bootloader nolo images, u-boot image and rootfs image\nrm -f mtd_emmc.img\n./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k u-boot.bin -r ubi.img -m rx51 -o mtd_emmc.img\n\n# Generate MTD image for OneNAND booting from bootloader nolo images, combined hacked image and rootfs image\n# Kernel image is put into initfs area, but qflasher reject to copy kernel image into initfs area because it does not have initfs signature\n# This is hack to workaround this problem, tell qflasher that kernel area for u-boot is bigger and put big combined hacked image (u-boot + kernel with correct offset)\nrm -f mtd_nand.img\n./qflasher -v -x xloader-qemu.bin -s secondary-qemu.bin -k combined_hack.bin -r ubi.img -m rx51 -p k=4094,i=2 -o mtd_nand.img\n\necho\necho \"======================================================\"\necho \"========== Running test images in n900 qemu ==========\"\necho \"======================================================\"\necho\n\n# Run MTD image in qemu and wait for 300s if U-Boot prints testing string to serial console and poweroff\nrm -f qemu_uboot.log\n./qemu-system-arm -M n900 -mtdblock mtd_uboot.img -sd emmc_uboot.img -serial /dev/stdout -display none > qemu_uboot.log &\nqemu_pid=$!\ntail -F qemu_uboot.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\n# Run MTD image in qemu and wait for 300s if uImage kernel from RAM is correctly booted\nrm -f qemu_ram.log\n./qemu-system-arm -M n900 -mtdblock mtd_ram.img -serial /dev/stdout -display none > qemu_ram.log &\nqemu_pid=$!\ntail -F qemu_ram.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\n# Run MTD image in qemu and wait for 300s if zImage kernel from RAM is correctly booted\nrm -f qemu_ram2.log\n./qemu-system-arm -M n900 -mtdblock mtd_ram2.img -sd emmc_default.img -serial /dev/stdout -display none > qemu_ram2.log &\nqemu_pid=$!\ntail -F qemu_ram2.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\n# Run MTD image in qemu and wait for 300s if uImage kernel from eMMC is correctly booted\nrm -f qemu_emmc.log\n./qemu-system-arm -M n900 -mtdblock mtd_emmc.img -sd emmc_emmc.img -serial /dev/stdout -display none > qemu_emmc.log &\nqemu_pid=$!\ntail -F qemu_emmc.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\n# Run MTD image in qemu and wait for 300s if zImage kernel from eMMC is correctly booted\nrm -f qemu_emmc2.log\n./qemu-system-arm -M n900 -mtdblock mtd_emmc.img -sd emmc_emmc2.img -serial /dev/stdout -display none > qemu_emmc2.log &\nqemu_pid=$!\ntail -F qemu_emmc2.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\n# Run MTD image in qemu and wait for 300s if kernel from OneNAND is correctly booted\nrm -f qemu_nand.log\n./qemu-system-arm -M n900 -mtdblock mtd_nand.img -sd emmc_nand.img -serial /dev/stdout -display none > qemu_nand.log &\nqemu_pid=$!\ntail -F qemu_nand.log &\ntail_pid=$!\nsleep 300 &\nsleep_pid=$!\nwait -n $sleep_pid $qemu_pid || true\nkill -9 $tail_pid $sleep_pid $qemu_pid 2>/dev/null || true\nwait || true\n\necho\necho \"=============================\"\necho \"========== Results ==========\"\necho \"=============================\"\necho\n\nif grep -q 'Successfully booted' qemu_uboot.log; then echo \"U-Boot serial console is working\"; else echo \"U-Boot serial console test failed\"; fi\nif grep -q 'Successfully booted' qemu_ram.log; then echo \"Kernel (uImage) was successfully booted from RAM\"; else echo \"Failed to boot kernel (uImage) from RAM\"; fi\nif grep -q 'Successfully booted' qemu_ram2.log; then echo \"Kernel (zImage) was successfully booted from RAM\"; else echo \"Failed to boot kernel (zImage) from RAM\"; fi\nif grep -q 'Successfully booted' qemu_emmc.log; then echo \"Kernel (uImage) was successfully booted from eMMC\"; else echo \"Failed to boot kernel (uImage) from eMMC\"; fi\nif grep -q 'Successfully booted' qemu_emmc2.log; then echo \"Kernel (zImage) was successfully booted from eMMC\"; else echo \"Failed to boot kernel (zImage) from eMMC\"; fi\nif grep -q 'Successfully booted' qemu_nand.log; then echo \"Kernel (uImage) was successfully booted from OneNAND\"; else echo \"Failed to boot kernel (uImage) from OneNAND\"; fi\n\necho\n\nif grep -q 'Successfully booted' qemu_uboot.log && grep -q 'Successfully booted' qemu_ram.log && grep -q 'Successfully booted' qemu_ram2.log && grep -q 'Successfully booted' qemu_emmc.log && grep -q 'Successfully booted' qemu_emmc2.log && grep -q 'Successfully booted' qemu_nand.log; then\n\techo \"All tests passed\"\n\texit 0\nelse\n\techo \"Some tests failed\"\n\texit 1\nfi\n", "num_lines": 354}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n\n# (C) Copyright 2015 Stephen Warren\n\n# This script tests U-Boot's FAT filesystem code's ability to read non-\n# contiguous files.\n\n# When porting the ff.c FAT parsing code into U-Boot, it was found that ff.c\n# always reads files cluster-by-cluster, which results in poor performance.\n# This was solved by adding a patch to ff.c to coalesce reads of adjacent\n# clusters. Since this patch needed to correctly handle non-contiguous files,\n# this test was written to validate that.\n#\n# To execute the test, simply run it from the U-Boot source root directory:\n#\n#    cd u-boot\n#    ./test/fs/fat-noncontig-test.sh\n#\n# The test will create a FAT filesystem image, record the CRC of a randomly\n# generated file in the image, build U-Boot sandbox, invoke U-Boot sandbox to\n# read the file and validate that the CRCs match. Expected output is shown\n# below. The important part of the log is the penultimate line that contains\n# either \"PASS\" or \"FAILURE\".\n#\n#    mkfs.fat 3.0.26 (2014-03-07)\n#\n#\n#    U-Boot 2015.10-rc4-00018-g4b22a3e5513f (Oct 03 2015 - 13:49:23 -0600)\n#\n#    DRAM:  128 MiB\n#    Using default environment\n#\n#    In:    serial\n#    Out:   lcd\n#    Err:   lcd\n#    Net:   No ethernet found.\n#    => host bind 0 sandbox/fat-noncontig.img\n#    => load host 0:0 1000 noncontig.img\n#    33584964 bytes read in 18 ms (1.7 GiB/s)\n#    => crc32 1000 $filesize 0\n#    crc32 for 00001000 ... 02008743 ==> 6a080523\n#    => if itest.l *0 != 2305086a; then echo FAILURE; else echo PASS; fi\n#    PASS\n#    => reset\n#\n# All temporary files used by this script are created in ./sandbox to avoid\n# polluting the source tree. test/fs/fs-test.sh also uses this directory for\n# the same purpose.\n#\n# TODO: Integrate this (and many other corner-cases e.g. different types of\n# FAT) with fs-test.sh so that a single script tests everything filesystem-\n# related.\n\nodir=sandbox\nimg=${odir}/fat-noncontig.img\nmnt=${odir}/mnt\nfill=/dev/urandom\ntestfn=noncontig.img\nmnttestfn=${mnt}/${testfn}\ncrcaddr=0\nloadaddr=1000\n\nfor prereq in fallocate mkfs.fat dd crc32; do\n    if [ ! -x \"`which $prereq`\" ]; then\n        echo \"Missing $prereq binary. Exiting!\"\n        exit 1\n    fi\ndone\n\nmake O=${odir} -s sandbox_defconfig && make O=${odir} -s -j8\n\nmkdir -p ${mnt}\nif [ ! -f ${img} ]; then\n    fallocate -l 40M ${img}\n    if [ $? -ne 0 ]; then\n        echo fallocate failed - using dd instead\n        dd if=/dev/zero of=${img} bs=1024 count=$((40 * 1024))\n        if [ $? -ne 0 ]; then\n            echo Could not create empty disk image\n            exit $?\n        fi\n    fi\n    mkfs.fat ${img}\n    if [ $? -ne 0 ]; then\n        echo Could not create FAT filesystem\n        exit $?\n    fi\n\n    sudo mount -o loop,uid=$(id -u) ${img} ${mnt}\n    if [ $? -ne 0 ]; then\n        echo Could not mount test filesystem\n        exit $?\n    fi\n\n    for ((sects=8; sects < 512; sects += 8)); do\n        fn=${mnt}/keep-${sects}.img\n        dd if=${fill} of=${fn} bs=512 count=${sects} >/dev/null 2>&1\n        fn=${mnt}/remove-${sects}.img\n        dd if=${fill} of=${fn} bs=512 count=${sects} >/dev/null 2>&1\n    done\n\n    rm -f ${mnt}/remove-*.img\n\n    # 511 deliberately to trigger a file size that's not a multiple of the\n    # sector size (ignoring sizes that are multiples of both).\n    dd if=${fill} of=${mnttestfn} bs=511 >/dev/null 2>&1\n\n    sudo umount ${mnt}\n    if [ $? -ne 0 ]; then\n        echo Could not unmount test filesystem\n        exit $?\n    fi\nfi\n\nsudo mount -o ro,loop,uid=$(id -u) ${img} ${mnt}\nif [ $? -ne 0 ]; then\n    echo Could not mount test filesystem\n    exit $?\nfi\ncrc=0x`crc32 ${mnttestfn}`\nsudo umount ${mnt}\nif [ $? -ne 0 ]; then\n    echo Could not unmount test filesystem\n    exit $?\nfi\n\ncrc=`printf %02x%02x%02x%02x \\\n    $((${crc} & 0xff)) \\\n    $(((${crc} >> 8) & 0xff)) \\\n    $(((${crc} >> 16) & 0xff)) \\\n    $((${crc} >> 24))`\n\n./sandbox/u-boot << EOF\nhost bind 0 ${img}\nload host 0:0 ${loadaddr} ${testfn}\ncrc32 ${loadaddr} \\$filesize ${crcaddr}\nif itest.l *${crcaddr} != ${crc}; then echo FAILURE; else echo PASS; fi\nreset\nEOF\nif [ $? -ne 0 ]; then\n    echo U-Boot exit status indicates an error\n    exit $?\nfi\n", "num_lines": 145}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n#\n# (C) Copyright 2014 Suriyan Ramasami\n\n# Invoke this test script from U-Boot base directory as ./test/fs/fs-test.sh\n# It currently tests the fs/sb and native commands for ext4 and fat partitions\n# Expected results are as follows:\n# EXT4 tests:\n# fs-test.sb.ext4\tSummary: PASS: 24 FAIL: 0\n# fs-test.nonfs.ext4\tSummary: PASS: 24 FAIL: 0\n# fs-test.fs.ext4\tSummary: PASS: 24 FAIL: 0\n# FAT16 tests:\n# fs-test.sb.fat16\tSummary: PASS: 24 FAIL: 0\n# fs-test.nonfs.fat16\tSummary: PASS: 24 FAIL: 0\n# fs-test.fs.fat16\tSummary: PASS: 24 FAIL: 0\n# FAT32 tests:\n# fs-test.sb.fat32\tSummary: PASS: 24 FAIL: 0\n# fs-test.nonfs.fat32\tSummary: PASS: 24 FAIL: 0\n# fs-test.fs.fat32\tSummary: PASS: 24 FAIL: 0\n# --------------------------------------------\n# Total Summary: TOTAL PASS: 216 TOTAL FAIL: 0\n# --------------------------------------------\n\n# pre-requisite binaries list.\nPREREQ_BINS=\"md5sum mkfs mount umount dd fallocate mkdir\"\n\n# All generated output files from this test will be in $OUT_DIR\n# Hence everything is sandboxed.\nOUT_DIR=\"sandbox/test/fs\"\n\n# Location of generated sandbox u-boot\nUBOOT=\"./sandbox/u-boot\"\n\n# Our mount directory will be in the sandbox\nMOUNT_DIR=\"${OUT_DIR}/mnt\"\n\n# The file system image we create will have the $IMG prefix.\nIMG=\"${OUT_DIR}/3GB\"\n\n# $SMALL_FILE is the name of the 1MB file in the file system image\nSMALL_FILE=\"1MB.file\"\n\n# $BIG_FILE is the name of the 2.5GB file in the file system image\nBIG_FILE=\"2.5GB.file\"\n\n# $MD5_FILE will have the expected md5s when we do the test\n# They shall have a suffix which represents their file system (ext4/fat16/...)\nMD5_FILE=\"${OUT_DIR}/md5s.list\"\n\n# $OUT shall be the prefix of the test output. Their suffix will be .out\nOUT=\"${OUT_DIR}/fs-test\"\n\n# Full Path of the 1 MB file that shall be created in the fs image.\nMB1=\"${MOUNT_DIR}/${SMALL_FILE}\"\nGB2p5=\"${MOUNT_DIR}/${BIG_FILE}\"\n\n# ************************\n# * Functions start here *\n# ************************\n\n# Check if the prereq binaries exist, or exit\nfunction check_prereq() {\n\tfor prereq in $PREREQ_BINS; do\n\t\tif [ ! -x \"`which $prereq`\" ]; then\n\t\t\techo \"Missing $prereq binary. Exiting!\"\n\t\t\texit\n\t\tfi\n\tdone\n\n\t# We use /dev/urandom to create files. Check if it exists.\n\tif [ ! -c /dev/urandom ]; then\n\t\techo \"Missing character special /dev/urandom. Exiting!\"\n\t\texit\n\tfi\n}\n\n# If 1st param is \"clean\", then clean out the generated files and exit\nfunction check_clean() {\n\tif [ \"$1\" = \"clean\" ]; then\n\t\trm -rf \"$OUT_DIR\"\n\t\techo \"Cleaned up generated files. Exiting\"\n\t\texit\n\tfi\n}\n\n# Generate sandbox U-Boot - gleaned from /test/dm/test-dm.sh\nfunction compile_sandbox() {\n\tunset CROSS_COMPILE\n\tNUM_CPUS=$(nproc)\n\tmake O=sandbox sandbox_config\n\tmake O=sandbox -s -j${NUM_CPUS}\n\n\t# Check if U-Boot exists\n\tif [ ! -x \"$UBOOT\" ]; then\n\t\techo \"$UBOOT does not exist or is not executable\"\n\t\techo \"Build error?\"\n\t\techo \"Please run this script as ./test/fs/`basename $0`\"\n\t\texit\n\tfi\n}\n\n# Clean out all generated files other than the file system images\n# We save time by not deleting and recreating the file system images\nfunction prepare_env() {\n\trm -f ${MD5_FILE}.* ${OUT}.*\n\tmkdir -p ${OUT_DIR}\n}\n\n# 1st parameter is the name of the image file to be created\n# 2nd parameter is the filesystem - fat16 ext4 etc\n# -F cant be used with fat as it means something else.\nfunction create_image() {\n\t# Create image if not already present - saves time, while debugging\n\tcase \"$2\" in\n\t\tfat16)\n\t\tMKFS_OPTION=\"-F 16\"\n\t\tFS_TYPE=\"fat\"\n\t\t;;\n\t\tfat32)\n\t\tMKFS_OPTION=\"-F 32\"\n\t\tFS_TYPE=\"fat\"\n\t\t;;\n\t\text4)\n\t\tMKFS_OPTION=\"-F\"\n\t\tFS_TYPE=\"ext4\"\n\t\t;;\n\tesac\n\n\tif [ ! -f \"$1\" ]; then\n\t\tfallocate -l 3G \"$1\" &> /dev/null\n\t\tif [ $? -ne 0 ]; then\n\t\t\techo fallocate failed - using dd instead\n\t\t\tdd if=/dev/zero of=$1 bs=1024 count=$((3 * 1024 * 1024))\n\t\t\tif [ $? -ne 0 ]; then\n\t\t\t\techo Could not create empty disk image\n\t\t\t\texit $?\n\t\t\tfi\n\t\tfi\n\t\tmkfs -t \"$FS_TYPE\" $MKFS_OPTION \"$1\" &> /dev/null\n\t\tif [ $? -ne 0 -a \"$FS_TYPE\" = \"fat\" ]; then\n\t\t\t# If we fail and we did fat, try vfat.\n\t\t\tmkfs -t vfat $MKFS_OPTION \"$1\" &> /dev/null\n\t\tfi\n\t\tif [ $? -ne 0 ]; then\n\t\t\techo Could not create filesystem\n\t\t\texit $?\n\t\tfi\n\tfi\n}\n\n# 1st parameter is image file\n# 2nd parameter is file system type - fat16/ext4/...\n# 3rd parameter is name of small file\n# 4th parameter is name of big file\n# 5th parameter is fs/nonfs/sb - to dictate generic fs commands or\n# otherwise or sb hostfs\n# 6th parameter is the directory path for the files. Its \"\" for generic\n# fs and ext4/fat and full patch for sb hostfs\n# UBOOT is set in env\nfunction test_image() {\n\taddr=\"0x01000008\"\n\tlength=\"0x00100000\"\n\n\tcase \"$2\" in\n\t\tfat*)\n\t\tFPATH=\"\"\n\t\tPREFIX=\"fat\"\n\t\tWRITE=\"write\"\n\t\t;;\n\n\t\text4)\n\t\t# ext4 needs absolute path\n\t\tFPATH=\"/\"\n\t\tPREFIX=\"ext4\"\n\t\tWRITE=\"write\"\n\t\t;;\n\n\t\t*)\n\t\techo \"Unhandled filesystem $2. Exiting!\"\n\t\texit\n\t\t;;\n\tesac\n\n\tcase \"$5\" in\n\t\tfs)\n\t\tPREFIX=\"\"\n\t\tWRITE=\"save\"\n\t\tSUFFIX=\" 0:0\"\n\t\t;;\n\n\t\tnonfs)\n\t\tSUFFIX=\" 0:0\"\n\t\t;;\n\n\t\tsb)\n\t\tPREFIX=\"host \"\n\t\tWRITE=\"save\"\n\t\tSUFFIX=\"fs -\"\n\t\t;;\n\n\t\t*)\n\t\techo \"Unhandled mode $5. Exiting!\"\n\t\texit\n\t\t;;\n\n\tesac\n\n\t# sb always uses full path to mointpoint, irrespective of filesystem\n\tif [ \"$5\" = \"sb\" ]; then\n\t\tFPATH=${6}/\n\tfi\n\n\tFILE_WRITE=${3}.w\n\tFILE_SMALL=$3\n\tFILE_BIG=$4\n\n\t# In u-boot commands, <interface> stands for host or hostfs\n\t# hostfs maps to the host fs.\n\t# host maps to the \"host bind\" that we do\n\n\t$UBOOT << EOF\nsb=$5\nsetenv bind 'if test \"\\$sb\" != sb; then host bind 0 \"$1\"; fi'\nrun bind\n# Test Case 1 - ls\n${PREFIX}ls host${SUFFIX} $6\n# In addition, test with a nonexistent directory to see if we crash.\n${PREFIX}ls host${SUFFIX} invalid_d\n#\n# We want ${PREFIX}size host 0:0 $3 for host commands and\n# host size hostfs - $3 for hostfs commands.\n# 1MB is 0x0010 0000\n# Test Case 2a - size of small file\n${PREFIX}size host${SUFFIX} ${FPATH}$FILE_SMALL\nprintenv filesize\nsetenv filesize\n# Test Case 2b - size of small file via a path using '..'\n${PREFIX}size host${SUFFIX} ${FPATH}SUBDIR/../$FILE_SMALL\nprintenv filesize\nsetenv filesize\n\n# 2.5GB (1024*1024*2500) is 0x9C40 0000\n# Test Case 3 - size of big file\n${PREFIX}size host${SUFFIX} ${FPATH}$FILE_BIG\nprintenv filesize\nsetenv filesize\n\n# Notes about load operation\n# If I use 0x01000000 I get DMA misaligned error message\n# Last two parameters are size and offset.\n\n# Test Case 4a - Read full 1MB of small file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL\nprintenv filesize\n# Test Case 4b - Read full 1MB of small file\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# Test Case 5a - First 1MB of big file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x0\nprintenv filesize\n# Test Case 5b - First 1MB of big file\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# fails for ext as no offset support\n# Test Case 6a - Last 1MB of big file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x9C300000\nprintenv filesize\n# Test Case 6b - Last 1MB of big file\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# fails for ext as no offset support\n# Test Case 7a - One from the last 1MB chunk of 2GB\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x7FF00000\nprintenv filesize\n# Test Case 7b - One from the last 1MB chunk of 2GB\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# fails for ext as no offset support\n# Test Case 8a - One from the start 1MB chunk from 2GB\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x80000000\nprintenv filesize\n# Test Case 8b - One from the start 1MB chunk from 2GB\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# fails for ext as no offset support\n# Test Case 9a - One 1MB chunk crossing the 2GB boundary\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG $length 0x7FF80000\nprintenv filesize\n# Test Case 9b - One 1MB chunk crossing the 2GB boundary\nmd5sum $addr \\$filesize\nsetenv filesize\n\n# Generic failure case\n# Test Case 10 - 2MB chunk from the last 1MB of big file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_BIG 0x00200000 0x9C300000\nprintenv filesize\n#\n\n# Read 1MB from small file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL\n# Write it back to test the writes\n# Test Case 11a - Check that the write succeeded\n${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}$FILE_WRITE \\$filesize\nmw.b $addr 00 100\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_WRITE\n# Test Case 11b - Check md5 of written to is same as the one read from\nmd5sum $addr \\$filesize\nsetenv filesize\n#\n\n# Next test case checks writing a file whose dirent\n# is the first in the block, which is always true for \".\"\n# The write should fail, but the lookup should work\n# Test Case 12 - Check directory traversal\n${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}. 0x10\n\n# Read 1MB from small file\n${PREFIX}load host${SUFFIX} $addr ${FPATH}$FILE_SMALL\n# Write it via \"same directory\", i.e. \".\" dirent\n# Test Case 13a - Check directory traversal\n${PREFIX}${WRITE} host${SUFFIX} $addr ${FPATH}./${FILE_WRITE}2 \\$filesize\nmw.b $addr 00 100\n${PREFIX}load host${SUFFIX} $addr ${FPATH}./${FILE_WRITE}2\n# Test Case 13b - Check md5 of written to is same as the one read from\nmd5sum $addr \\$filesize\nsetenv filesize\nmw.b $addr 00 100\n${PREFIX}load host${SUFFIX} $addr ${FPATH}${FILE_WRITE}2\n# Test Case 13c - Check md5 of written to is same as the one read from\nmd5sum $addr \\$filesize\nsetenv filesize\n#\nreset\n\nEOF\n}\n\n# 1st argument is the name of the image file.\n# 2nd argument is the file where we generate the md5s of the files\n# generated with the appropriate start and length that we use to test.\n# It creates the necessary files in the image to test.\n# $GB2p5 is the path of the big file (2.5 GB)\n# $MB1 is the path of the small file (1 MB)\n# $MOUNT_DIR is the path we can use to mount the image file.\nfunction create_files() {\n\t# Mount the image so we can populate it.\n\tmkdir -p \"$MOUNT_DIR\"\n\tsudo mount -o loop,rw \"$1\" \"$MOUNT_DIR\"\n\n\t# Create a subdirectory.\n\tsudo mkdir -p \"$MOUNT_DIR/SUBDIR\"\n\n\t# Create big file in this image.\n\t# Note that we work only on the start 1MB, couple MBs in the 2GB range\n\t# and the last 1 MB of the huge 2.5GB file.\n\t# So, just put random values only in those areas.\n\tif [ ! -f \"${GB2p5}\" ]; then\n\t\tsudo dd if=/dev/urandom of=\"${GB2p5}\" bs=1M count=1 \\\n\t\t\t&> /dev/null\n\t\tsudo dd if=/dev/urandom of=\"${GB2p5}\" bs=1M count=2 seek=2047 \\\n\t\t\t&> /dev/null\n\t\tsudo dd if=/dev/urandom of=\"${GB2p5}\" bs=1M count=1 seek=2499 \\\n\t\t\t&> /dev/null\n\tfi\n\n\t# Create a small file in this image.\n\tif [ ! -f \"${MB1}\" ]; then\n\t\tsudo dd if=/dev/urandom of=\"${MB1}\" bs=1M count=1 \\\n\t\t\t&> /dev/null\n\tfi\n\n\t# Delete the small file copies which possibly are written as part of a\n\t# previous test.\n\tsudo rm -f \"${MB1}.w\"\n\tsudo rm -f \"${MB1}.w2\"\n\n\t# Generate the md5sums of reads that we will test against small file\n\tdd if=\"${MB1}\" bs=1M skip=0 count=1 2> /dev/null | md5sum > \"$2\"\n\n\t# Generate the md5sums of reads that we will test against big file\n\t# One from beginning of file.\n\tdd if=\"${GB2p5}\" bs=1M skip=0 count=1 \\\n\t\t2> /dev/null | md5sum >> \"$2\"\n\n\t# One from end of file.\n\tdd if=\"${GB2p5}\" bs=1M skip=2499 count=1 \\\n\t\t2> /dev/null | md5sum >> \"$2\"\n\n\t# One from the last 1MB chunk of 2GB\n\tdd if=\"${GB2p5}\" bs=1M skip=2047 count=1 \\\n\t\t2> /dev/null | md5sum >> \"$2\"\n\n\t# One from the start 1MB chunk from 2GB\n\tdd if=\"${GB2p5}\" bs=1M skip=2048 count=1 \\\n\t\t2> /dev/null | md5sum >> \"$2\"\n\n\t# One 1MB chunk crossing the 2GB boundary\n\tdd if=\"${GB2p5}\" bs=512K skip=4095 count=2 \\\n\t\t2> /dev/null | md5sum >> \"$2\"\n\n\tsync\n\tsudo umount \"$MOUNT_DIR\"\n\trmdir \"$MOUNT_DIR\"\n}\n\n# 1st parameter is the text to print\n# if $? is 0 its a pass, else a fail\n# As a side effect it shall update env variable PASS and FAIL\nfunction pass_fail() {\n\tif [ $? -eq 0 ]; then\n\t\techo pass - \"$1\"\n\t\tPASS=$((PASS + 1))\n\telse\n\t\techo FAIL - \"$1\"\n\t\tFAIL=$((FAIL + 1))\n\tfi\n}\n\n# 1st parameter is the string which leads to an md5 generation\n# 2nd parameter is the file we grep, for that string\n# 3rd parameter is the name of the file which has md5s in it\n# 4th parameter is the line # in the md5 file that we match it against\n# This function checks if the md5 of the file in the sandbox matches\n# that calculated while generating the file\n# 5th parameter is the string to print with the result\ncheck_md5() {\n\t# md5sum in u-boot has output of form:\n\t# md5 for 01000008 ... 01100007 ==> <md5>\n\t# the 7th field is the actual md5\n\tmd5_src=`grep -A2 \"$1\" \"$2\" | grep \"md5 for\" | tr -d '\\r'`\n\tmd5_src=($md5_src)\n\tmd5_src=${md5_src[6]}\n\n\t# The md5 list, each line is of the form:\n\t# - <md5>\n\t# the 2nd field is the actual md5\n\tmd5_dst=`sed -n $4p $3`\n\tmd5_dst=($md5_dst)\n\tmd5_dst=${md5_dst[0]}\n\n\t# For a pass they should match.\n\t[ \"$md5_src\" = \"$md5_dst\" ]\n\tpass_fail \"$5\"\n}\n\n# 1st parameter is the name of the output file to check\n# 2nd parameter is the name of the file containing the md5 expected\n# 3rd parameter is the name of the small file\n# 4th parameter is the name of the big file\n# 5th paramter is the name of the written file\n# This function checks the output file for correct results.\nfunction check_results() {\n\techo \"** Start $1\"\n\n\tPASS=0\n\tFAIL=0\n\n\t# Check if the ls is showing correct results for 2.5 gb file\n\tgrep -A7 \"Test Case 1 \" \"$1\" | egrep -iq \"2621440000 *$4\"\n\tpass_fail \"TC1: ls of $4\"\n\n\t# Check if the ls is showing correct results for 1 mb file\n\tgrep -A7 \"Test Case 1 \" \"$1\" | egrep -iq \"1048576 *$3\"\n\tpass_fail \"TC1: ls of $3\"\n\n\t# Check size command on 1MB.file\n\tegrep -A3 \"Test Case 2a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC2: size of $3\"\n\t# Check size command on 1MB.file via a path using '..'\n\tegrep -A3 \"Test Case 2b \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC2: size of $3 via a path using '..'\"\n\n\t# Check size command on 2.5GB.file\n\tegrep -A3 \"Test Case 3 \" \"$1\" | grep -q \"filesize=9c400000\"\n\tpass_fail \"TC3: size of $4\"\n\n\t# Check read full mb of 1MB.file\n\tgrep -A4 \"Test Case 4a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC4: load of $3 size\"\n\tcheck_md5 \"Test Case 4b \" \"$1\" \"$2\" 1 \"TC4: load from $3\"\n\n\t# Check first mb of 2.5GB.file\n\tgrep -A4 \"Test Case 5a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC5: load of 1st MB from $4 size\"\n\tcheck_md5 \"Test Case 5b \" \"$1\" \"$2\" 2 \"TC5: load of 1st MB from $4\"\n\n\t# Check last mb of 2.5GB.file\n\tgrep -A4 \"Test Case 6a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC6: load of last MB from $4 size\"\n\tcheck_md5 \"Test Case 6b \" \"$1\" \"$2\" 3 \"TC6: load of last MB from $4\"\n\n\t# Check last 1mb chunk of 2gb from 2.5GB file\n\tgrep -A4 \"Test Case 7a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC7: load of last 1mb chunk of 2GB from $4 size\"\n\tcheck_md5 \"Test Case 7b \" \"$1\" \"$2\" 4 \\\n\t\t\"TC7: load of last 1mb chunk of 2GB from $4\"\n\n\t# Check first 1mb chunk after 2gb from 2.5GB file\n\tgrep -A4 \"Test Case 8a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC8: load 1st MB chunk after 2GB from $4 size\"\n\tcheck_md5 \"Test Case 8b \" \"$1\" \"$2\" 5 \\\n\t\t\"TC8: load 1st MB chunk after 2GB from $4\"\n\n\t# Check 1mb chunk crossing the 2gb boundary from 2.5GB file\n\tgrep -A4 \"Test Case 9a \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC9: load 1MB chunk crossing 2GB boundary from $4 size\"\n\tcheck_md5 \"Test Case 9b \" \"$1\" \"$2\" 6 \\\n\t\t\"TC9: load 1MB chunk crossing 2GB boundary from $4\"\n\n\t# Check 2mb chunk from the last 1MB of 2.5GB file loads 1MB\n\tgrep -A5 \"Test Case 10 \" \"$1\" | grep -q \"filesize=100000\"\n\tpass_fail \"TC10: load 2MB from the last 1MB of $4 loads 1MB\"\n\n\t# Check 1mb chunk write\n\tgrep -A2 \"Test Case 11a \" \"$1\" | grep -q '1048576 bytes written'\n\tpass_fail \"TC11: 1MB write to $3.w - write succeeded\"\n\tcheck_md5 \"Test Case 11b \" \"$1\" \"$2\" 1 \\\n\t\t\"TC11: 1MB write to $3.w - content verified\"\n\n\t# Check lookup of 'dot' directory\n\tgrep -A4 \"Test Case 12 \" \"$1\" | grep -q 'Unable to write'\n\tpass_fail \"TC12: 1MB write to . - write denied\"\n\n\t# Check directory traversal\n\tgrep -A2 \"Test Case 13a \" \"$1\" | grep -q '1048576 bytes written'\n\tpass_fail \"TC13: 1MB write to ./$3.w2 - write succeeded\"\n\tcheck_md5 \"Test Case 13b \" \"$1\" \"$2\" 1 \\\n\t\t\"TC13: 1MB read from ./$3.w2 - content verified\"\n\tcheck_md5 \"Test Case 13c \" \"$1\" \"$2\" 1 \\\n\t\t\"TC13: 1MB read from $3.w2 - content verified\"\n\n\techo \"** End $1\"\n}\n\n# Takes in one parameter which is \"fs\" or \"nonfs\", which then dictates\n# if a fs test (size/load/save) or a nonfs test (fatread/extread) needs to\n# be performed.\nfunction test_fs_nonfs() {\n\techo \"Creating files in $fs image if not already present.\"\n\tcreate_files $IMAGE $MD5_FILE_FS\n\n\tOUT_FILE=\"${OUT}.$1.${fs}.out\"\n\ttest_image $IMAGE $fs $SMALL_FILE $BIG_FILE $1 \"\" \\\n\t\t> ${OUT_FILE} 2>&1\n\t# strip out noise from fs code\n\tgrep -v -e \"File System is consistent\\|update journal finished\" \\\n\t\t-e \"reading .*\\.file\\|writing .*\\.file.w\" \\\n\t\t< ${OUT_FILE} > ${OUT_FILE}_clean\n\tcheck_results ${OUT_FILE}_clean $MD5_FILE_FS $SMALL_FILE \\\n\t\t$BIG_FILE\n\tTOTAL_FAIL=$((TOTAL_FAIL + FAIL))\n\tTOTAL_PASS=$((TOTAL_PASS + PASS))\n\techo \"Summary: PASS: $PASS FAIL: $FAIL\"\n\techo \"--------------------------------------------\"\n}\n\n# ********************\n# * End of functions *\n# ********************\n\ncheck_clean \"$1\"\ncheck_prereq\ncompile_sandbox\nprepare_env\n\n# Track TOTAL_FAIL and TOTAL_PASS\nTOTAL_FAIL=0\nTOTAL_PASS=0\n\n# In each loop, for a given file system image, we test both the\n# fs command, like load/size/write, the file system specific command\n# like: ext4load/ext4size/ext4write and the host load/ls/save commands.\nfor fs in ext4 fat16 fat32; do\n\n\techo \"Creating $fs image if not already present.\"\n\tIMAGE=${IMG}.${fs}.img\n\tMD5_FILE_FS=\"${MD5_FILE}.${fs}\"\n\tcreate_image $IMAGE $fs\n\n\t# host commands test\n\techo \"Creating files in $fs image if not already present.\"\n\tcreate_files $IMAGE $MD5_FILE_FS\n\n\t# Lets mount the image and test host hostfs commands\n\tmkdir -p \"$MOUNT_DIR\"\n\tcase \"$fs\" in\n\t\tfat*)\n\t\tuid=\"uid=`id -u`\"\n\t\t;;\n\t\t*)\n\t\tuid=\"\"\n\t\t;;\n\tesac\n\tsudo mount -o loop,rw,$uid \"$IMAGE\" \"$MOUNT_DIR\"\n\tsudo chmod 777 \"$MOUNT_DIR\"\n\n\tOUT_FILE=\"${OUT}.sb.${fs}.out\"\n\ttest_image $IMAGE $fs $SMALL_FILE $BIG_FILE sb `pwd`/$MOUNT_DIR \\\n\t\t> ${OUT_FILE} 2>&1\n\tsudo umount \"$MOUNT_DIR\"\n\trmdir \"$MOUNT_DIR\"\n\n\tcheck_results $OUT_FILE $MD5_FILE_FS $SMALL_FILE $BIG_FILE\n\tTOTAL_FAIL=$((TOTAL_FAIL + FAIL))\n\tTOTAL_PASS=$((TOTAL_PASS + PASS))\n\techo \"Summary: PASS: $PASS FAIL: $FAIL\"\n\techo \"--------------------------------------------\"\n\n\ttest_fs_nonfs nonfs\n\ttest_fs_nonfs fs\ndone\n\necho \"Total Summary: TOTAL PASS: $TOTAL_PASS TOTAL FAIL: $TOTAL_FAIL\"\necho \"--------------------------------------------\"\nif [ $TOTAL_FAIL -eq 0 ]; then\n\techo \"PASSED\"\n\texit 0\nelse\n\techo \"FAILED\"\n\texit 1\nfi\n", "num_lines": 628}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n#\n# Written by Guilherme Maciel Ferreira <guilherme.maciel.ferreira@gmail.com>\n#\n# Sanity check for mkimage and dumpimage tools\n#\n# To run this:\n#\n# make O=sandbox sandbox_config\n# make O=sandbox\n# ./test/image/test-imagetools.sh\n\nBASEDIR=sandbox\nSRCDIR=${BASEDIR}/boot\nIMAGE_NAME=\"v1.0-test\"\nIMAGE_MULTI=linux.img\nIMAGE_FIT_ITS=linux.its\nIMAGE_FIT_ITB=linux.itb\nDATAFILE0=vmlinuz\nDATAFILE1=initrd.img\nDATAFILE2=System.map\nDATAFILES=\"${DATAFILE0} ${DATAFILE1} ${DATAFILE2}\"\nTEST_OUT=test_output\nMKIMAGE=${BASEDIR}/tools/mkimage\nDUMPIMAGE=${BASEDIR}/tools/dumpimage\nMKIMAGE_LIST=mkimage.list\nDUMPIMAGE_LIST=dumpimage.list\n\n# Remove all the files we created\ncleanup()\n{\n\tlocal file\n\n\tfor file in ${DATAFILES}; do\n\t\trm -f ${file} ${SRCDIR}/${file}\n\tdone\n\trm -f ${IMAGE_MULTI}\n\trm -f ${DUMPIMAGE_LIST}\n\trm -f ${MKIMAGE_LIST}\n\trm -f ${TEST_OUT}\n\trmdir ${SRCDIR}\n}\n\n# Check that two files are the same\nassert_equal()\n{\n\tif ! diff -u $1 $2; then\n\t\techo \"Failed.\"\n\t\tcleanup\n\t\texit 1\n\tfi\n}\n\n# Create some test files\ncreate_files()\n{\n\tlocal file\n\n\tmkdir -p ${SRCDIR}\n\tfor file in ${DATAFILES}; do\n\t\thead -c $RANDOM /dev/urandom >${SRCDIR}/${file}\n\tdone\n}\n\n# Run a command, echoing it first\ndo_cmd()\n{\n\tlocal cmd=\"$@\"\n\n\techo \"# ${cmd}\"\n\t${cmd} 2>&1\n}\n\n# Run a command, redirecting output\n# Args:\n#    redirect_file\n#    command...\ndo_cmd_redir()\n{\n\tlocal redir=\"$1\"\n\tshift\n\tlocal cmd=\"$@\"\n\n\techo \"# ${cmd}\"\n\t${cmd} >${redir}\n}\n\n# Write files into an multi-file image\ncreate_multi_image()\n{\n\tlocal files=\"${SRCDIR}/${DATAFILE0}:${SRCDIR}/${DATAFILE1}\"\n\tfiles+=\":${SRCDIR}/${DATAFILE2}\"\n\n\techo -e \"\\nBuilding multi-file image...\"\n\tdo_cmd ${MKIMAGE} -A x86 -O linux -T multi -n \\\"${IMAGE_NAME}\\\" \\\n\t\t-d ${files} ${IMAGE_MULTI}\n\techo \"done.\"\n}\n\n# Extract files from an multi-file image\nextract_multi_image()\n{\n\techo -e \"\\nExtracting multi-file image contents...\"\n\tdo_cmd ${DUMPIMAGE} -T multi -p 0 -o ${DATAFILE0} ${IMAGE_MULTI}\n\tdo_cmd ${DUMPIMAGE} -T multi -p 1 -o ${DATAFILE1} ${IMAGE_MULTI}\n\tdo_cmd ${DUMPIMAGE} -T multi -p 2 -o ${DATAFILE2} ${IMAGE_MULTI}\n\tdo_cmd ${DUMPIMAGE} -T multi -p 2 -o ${TEST_OUT} ${IMAGE_MULTI}\n\techo \"done.\"\n}\n\n# Write files into a FIT image\ncreate_fit_image()\n{\n\techo \" \\\n\t/dts-v1/; \\\n\t/ { \\\n\t    description = \\\"FIT image\\\"; \\\n\t    #address-cells = <1>; \\\n\t\\\n\t    images { \\\n\t        kernel@1 { \\\n\t            description = \\\"kernel\\\"; \\\n\t            data = /incbin/(\\\"${DATAFILE0}\\\"); \\\n\t            type = \\\"kernel\\\"; \\\n\t            arch = \\\"sandbox\\\"; \\\n\t            os = \\\"linux\\\"; \\\n\t            compression = \\\"gzip\\\"; \\\n\t            load = <0x40000>; \\\n\t            entry = <0x8>; \\\n\t        }; \\\n\t        ramdisk@1 { \\\n\t            description = \\\"filesystem\\\"; \\\n\t            data = /incbin/(\\\"${DATAFILE1}\\\"); \\\n\t            type = \\\"ramdisk\\\"; \\\n\t            arch = \\\"sandbox\\\"; \\\n\t            os = \\\"linux\\\"; \\\n\t            compression = \\\"none\\\"; \\\n\t            load = <0x80000>; \\\n\t            entry = <0x16>; \\\n\t        }; \\\n\t        fdt@1 { \\\n\t            description = \\\"device tree\\\"; \\\n\t            data = /incbin/(\\\"${DATAFILE2}\\\"); \\\n\t            type = \\\"flat_dt\\\"; \\\n\t            arch = \\\"sandbox\\\"; \\\n\t            compression = \\\"none\\\"; \\\n\t        }; \\\n\t    }; \\\n\t    configurations { \\\n\t        default = \\\"conf@1\\\"; \\\n\t        conf@1 { \\\n\t            kernel = \\\"kernel@1\\\"; \\\n\t            fdt = \\\"fdt@1\\\"; \\\n\t        }; \\\n\t    }; \\\n\t}; \\\n\t\" > ${IMAGE_FIT_ITS}\n\n\techo -e \"\\nBuilding FIT image...\"\n\tdo_cmd ${MKIMAGE} -f ${IMAGE_FIT_ITS} ${IMAGE_FIT_ITB}\n\techo \"done.\"\n}\n\n# Extract files from a FIT image\nextract_fit_image()\n{\n\techo -e \"\\nExtracting FIT image contents...\"\n\tdo_cmd ${DUMPIMAGE} -T flat_dt -p 0 -o ${DATAFILE0} ${IMAGE_FIT_ITB}\n\tdo_cmd ${DUMPIMAGE} -T flat_dt -p 1 -o ${DATAFILE1} ${IMAGE_FIT_ITB}\n\tdo_cmd ${DUMPIMAGE} -T flat_dt -p 2 -o ${DATAFILE2} ${IMAGE_FIT_ITB}\n\tdo_cmd ${DUMPIMAGE} -T flat_dt -p 2 -o ${TEST_OUT} ${IMAGE_FIT_ITB}\n\techo \"done.\"\n}\n\n# List the contents of a file\n# Args:\n#    image filename\nlist_image()\n{\n\tlocal image=\"$1\"\n\n\techo -e \"\\nListing image contents...\"\n\tdo_cmd_redir ${MKIMAGE_LIST} ${MKIMAGE} -l ${image}\n\tdo_cmd_redir ${DUMPIMAGE_LIST} ${DUMPIMAGE} -l ${image}\n\techo \"done.\"\n}\n\nmain()\n{\n\tlocal file\n\n\tcreate_files\n\n\t# Compress and extract multi-file images, compare the result\n\tcreate_multi_image\n\textract_multi_image\n\tfor file in ${DATAFILES}; do\n\t\tassert_equal ${file} ${SRCDIR}/${file}\n\tdone\n\tassert_equal ${TEST_OUT} ${DATAFILE2}\n\n\t# List contents of multi-file image and compares output from tools\n\tlist_image ${IMAGE_MULTI}\n\tassert_equal ${DUMPIMAGE_LIST} ${MKIMAGE_LIST}\n\n\t# Compress and extract FIT images, compare the result\n\tcreate_fit_image\n\textract_fit_image\n\tfor file in ${DATAFILES}; do\n\t\tassert_equal ${file} ${SRCDIR}/${file}\n\tdone\n\tassert_equal ${TEST_OUT} ${DATAFILE2}\n\n\t# List contents of FIT image and compares output from tools\n\tlist_image ${IMAGE_FIT_ITB}\n\tassert_equal ${DUMPIMAGE_LIST} ${MKIMAGE_LIST}\n\n\t# Remove files created\n\tcleanup\n\n\techo \"Tests passed.\"\n}\n\nmain\n", "num_lines": 226}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Test script to check uintptr_t and 64-bit types for warnings\n#\n# It builds a few boards with different toolchains. If there are no warnings\n# then all is well.\n#\n# Usage:\n#\n# Make sure that your toolchains are correct at the bottom of this file\n#\n# Then:\n#\t./test/stdint/test-includes.sh\n\nout=/tmp/test-includes.tmp\n\ntry_test() {\n\tlocal board=$1\n\tlocal arch=$2\n\tlocal soc=$3\n\tlocal gcc=$4\n\tlocal flags=\"$5\"\n\n\techo $@\n\tif ! which ${gcc} >/dev/null 2>&1; then\n\t\techo \"Not found: ${gcc}\"\n\t\treturn\n\tfi\n\n\trm -rf ${out}\n\tmkdir -p ${out}\n\ttouch ${out}/config.h\n\tmkdir -p ${out}/generated\n\ttouch ${out}/generated/generic-asm-offsets.h\n\tmkdir -p ${out}/include/asm\n\tln -s $(pwd)/arch/${arch}/include/asm/arch-${soc} \\\n\t\t\t${out}/include/asm/arch\n\n\tcmd=\"${gcc} -c -D__KERNEL__ ${flags} \\\n\t\t-fno-builtin -ffreestanding \\\n\t\t-Iarch/${arch}/include \\\n\t\t-Iinclude \\\n\t\t-I${out} -I${out}/include \\\n\t\t-include configs/${board}.h test/stdint/int-types.c \\\n\t\t-o /dev/null\"\n\t$cmd\n}\n\ntry_both() {\n\ttry_test $@\n}\n\n# board arch soc path-to-gcc\ntry_both sandbox sandbox - gcc\ntry_both coreboot x86 - x86_64-linux-gnu-gcc\ntry_both seaboard arm tegra20 /opt/linaro/gcc-linaro-arm-linux-gnueabihf-4.8-2013.08_linux/bin/arm-linux-gnueabihf-gcc\n", "num_lines": 57}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n# Copyright (c) 2013 The Chromium OS Authors.\n#\n\n# Simple test script for tracing with sandbox\n\nTRACE_OPT=\"FTRACE=1\"\n\nBASE=\"$(dirname $0)/..\"\n. $BASE/common.sh\n\nrun_trace() {\n\techo \"Run trace\"\n\t./${OUTPUT_DIR}/u-boot <<END\ntrace stats\nhash sha256 0 10000\ntrace pause\ntrace stats\nhash sha256 0 10000\ntrace stats\ntrace resume\nhash sha256 0 10000\ntrace pause\ntrace stats\nreset\nEND\n}\n\ncheck_results() {\n\techo \"Check results\"\n\n\t# Expect sha256 to run 3 times, so we see the string 6 times\n\tif [ $(grep -c sha256 ${tmp}) -ne 6 ]; then\n\t\tfail \"sha256 error\"\n\tfi\n\n\t# 4 sets of results (output of 'trace stats')\n\tif [ $(grep -c \"traced function calls\" ${tmp}) -ne 4 ]; then\n\t\tfail \"trace output error\"\n\tfi\n\n\t# Check trace counts. We expect to see an increase in the number of\n\t# traced function calls between each 'trace stats' command, except\n\t# between calls 2 and 3, where tracing is paused.\n\t# This code gets the sign of the difference between each number and\n\t# its predecessor.\n\tcounts=\"$(tr -d ',\\r' <${tmp} | awk \\\n\t\t'/traced function calls/ { diff = $1 - upto; upto = $1; \\\n\t\tprintf \"%d \", diff < 0 ? -1 : (diff > 0 ? 1 : 0)}')\"\n\n\tif [ \"${counts}\" != \"1 1 0 1 \" ]; then\n\t\tfail \"trace collection error: ${counts}\"\n\tfi\n}\n\necho \"Simple trace test / sanity check using sandbox\"\necho\ntmp=\"$(tempfile)\"\nbuild_uboot \"${TRACE_OPT}\"\nrun_trace >${tmp}\ncheck_results ${tmp}\nrm ${tmp}\necho \"Test passed\"\n", "num_lines": 65}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# script to check whether the file exists in imximage.cfg for i.MX8M\n#\n\nfile=$1\n\npost_process=$2\n\nblobs=`awk '/^SIGNED_HDMI/ {print $2} /^LOADER/ {print $2} /^SECOND_LOADER/ {print $2} /^DDR_FW/ {print $2}' $file`\nfor f in $blobs; do\n\tif [ $f = \"spl/u-boot-spl-ddr.bin\" ] || [ $f = \"u-boot.itb\" ]; then\n\t\tcontinue\n\tfi\n\n\tif [ ! -f $f ]; then\n\t\techo \"WARNING '$f' not found, resulting binary is not-functional\" >&2\n\t\texit 1\n\tfi\ndone\n\nif [ $post_process = 1 ]; then\n\tif [ -f lpddr4_pmu_train_1d_imem.bin ]; then\n\t\tobjcopy -I binary -O binary --pad-to 0x8000 --gap-fill=0x0 lpddr4_pmu_train_1d_imem.bin lpddr4_pmu_train_1d_imem_pad.bin\n\t\tobjcopy -I binary -O binary --pad-to 0x4000 --gap-fill=0x0 lpddr4_pmu_train_1d_dmem.bin lpddr4_pmu_train_1d_dmem_pad.bin\n\t\tobjcopy -I binary -O binary --pad-to 0x8000 --gap-fill=0x0 lpddr4_pmu_train_2d_imem.bin lpddr4_pmu_train_2d_imem_pad.bin\n\t\tcat lpddr4_pmu_train_1d_imem_pad.bin lpddr4_pmu_train_1d_dmem_pad.bin > lpddr4_pmu_train_1d_fw.bin\n\t\tcat lpddr4_pmu_train_2d_imem_pad.bin lpddr4_pmu_train_2d_dmem.bin > lpddr4_pmu_train_2d_fw.bin\n\t\tdd if=spl/u-boot-spl.bin of=spl/u-boot-spl-pad.bin bs=4 conv=sync\n\t\tcat spl/u-boot-spl-pad.bin lpddr4_pmu_train_1d_fw.bin lpddr4_pmu_train_2d_fw.bin > spl/u-boot-spl-ddr.bin\n\t\trm -f lpddr4_pmu_train_1d_fw.bin lpddr4_pmu_train_2d_fw.bin lpddr4_pmu_train_1d_imem_pad.bin lpddr4_pmu_train_1d_dmem_pad.bin lpddr4_pmu_train_2d_imem_pad.bin spl/u-boot-spl-pad.bin\n\tfi\n\tif [ -f ddr4_imem_1d.bin ]; then\n\t\tobjcopy -I binary -O binary --pad-to 0x8000 --gap-fill=0x0 ddr4_imem_1d.bin ddr4_imem_1d_pad.bin\n\t\tobjcopy -I binary -O binary --pad-to 0x4000 --gap-fill=0x0 ddr4_dmem_1d.bin ddr4_dmem_1d_pad.bin\n\t\tobjcopy -I binary -O binary --pad-to 0x8000 --gap-fill=0x0 ddr4_imem_2d.bin ddr4_imem_2d_pad.bin\n\t\tcat ddr4_imem_1d_pad.bin ddr4_dmem_1d_pad.bin > ddr4_1d_fw.bin\n\t\tcat ddr4_imem_2d_pad.bin ddr4_dmem_2d.bin > ddr4_2d_fw.bin\n\t\tdd if=spl/u-boot-spl.bin of=spl/u-boot-spl-pad.bin bs=4 conv=sync\n\t\tcat spl/u-boot-spl-pad.bin ddr4_1d_fw.bin ddr4_2d_fw.bin > spl/u-boot-spl-ddr.bin\n\t\trm -f ddr4_1d_fw.bin ddr4_2d_fw.bin ddr4_imem_1d_pad.bin ddr4_dmem_1d_pad.bin ddr4_imem_2d_pad.bin spl/u-boot-spl-pad.bin\n\tfi\nfi\n\nexit 0\n", "num_lines": 47}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# script to check whether the file exists in imximage.cfg for i.MX8\n#\n# usage: $0 <imximage.cfg>\n\nfile=$1\n\nblobs=`awk '/^APPEND/ {print $2} /^IMAGE/ || /^DATA/ {print $3}' $file`\nfor f in $blobs; do\n\ttmp=$srctree/$f\n\tif [ $f = \"u-boot-dtb.bin\" ]; then\n\t\tcontinue\n\tfi\n\n\tif [ -f $f ]; then\n\t\tcontinue\n\tfi\n\n\tif [ ! -f $tmp ]; then\n\t\techo \"WARNING '$tmp' not found, resulting binary is not-functional\" >&2\n\t\texit 1\n\tfi\n\n\tsed -in \"s;$f;$tmp;\" $file\ndone\n\nexit 0\n", "num_lines": 30}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# SPDX-License-Identifier: GPL-2.0+\n#\n# script to generate FIT image source for K3 Family boards with\n# ATF, OPTEE, SPL and multiple device trees (given on the command line).\n# Inspired from board/sunxi/mksunxi_fit_atf.sh\n#\n# usage: $0 <atf_load_addr> <dt_name> [<dt_name> [<dt_name] ...]\n\n[ -z \"$ATF\" ] && ATF=\"bl31.bin\"\n\nif [ ! -f $ATF ]; then\n\techo \"WARNING ATF file $ATF NOT found, resulting binary is non-functional\" >&2\n\tATF=/dev/null\nfi\n\n[ -z \"$TEE\" ] && TEE=\"bl32.bin\"\n\nif [ ! -f $TEE ]; then\n\techo \"WARNING OPTEE file $TEE NOT found, resulting might be non-functional\" >&2\n\tTEE=/dev/null\nfi\n\n[ -z \"$DM\" ] && DM=\"dm.bin\"\n\nif [ ! -e $DM ]; then\n\techo \"WARNING DM file $DM NOT found, resulting might be non-functional\" >&2\n\tDM=/dev/null\nfi\n\nif [ ! -z \"$IS_HS\" ]; then\n\tHS_APPEND=_HS\nfi\n\ncat << __HEADER_EOF\n/dts-v1/;\n\n/ {\n\tdescription = \"Configuration to load ATF and SPL\";\n\t#address-cells = <1>;\n\n\timages {\n\t\tatf {\n\t\t\tdescription = \"ARM Trusted Firmware\";\n\t\t\tdata = /incbin/(\"$ATF\");\n\t\t\ttype = \"firmware\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tos = \"arm-trusted-firmware\";\n\t\t\tload = <$1>;\n\t\t\tentry = <$1>;\n\t\t};\n\t\ttee {\n\t\t\tdescription = \"OPTEE\";\n\t\t\tdata = /incbin/(\"$TEE\");\n\t\t\ttype = \"tee\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tos = \"tee\";\n\t\t\tload = <0x9e800000>;\n\t\t\tentry = <0x9e800000>;\n\t\t};\n\t\tdm {\n\t\t\tdescription = \"DM binary\";\n\t\t\tdata = /incbin/(\"$DM\");\n\t\t\ttype = \"firmware\";\n\t\t\tarch = \"arm32\";\n\t\t\tcompression = \"none\";\n\t\t\tos = \"DM\";\n\t\t\tload = <0xa0000000>;\n\t\t\tentry = <0xa0000000>;\n\t\t};\n\t\tspl {\n\t\t\tdescription = \"SPL (64-bit)\";\n\t\t\tdata = /incbin/(\"spl/u-boot-spl-nodtb.bin$HS_APPEND\");\n\t\t\ttype = \"standalone\";\n\t\t\tos = \"U-Boot\";\n\t\t\tarch = \"arm64\";\n\t\t\tcompression = \"none\";\n\t\t\tload = <0x80080000>;\n\t\t\tentry = <0x80080000>;\n\t\t};\n__HEADER_EOF\n\n# shift through ATF load address in the command line arguments\nshift\n\nfor dtname in $*\ndo\n\tcat << __FDT_IMAGE_EOF\n\t\t$(basename $dtname) {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tdata = /incbin/(\"$dtname$HS_APPEND\");\n\t\t\ttype = \"flat_dt\";\n\t\t\tarch = \"arm\";\n\t\t\tcompression = \"none\";\n\t\t};\n__FDT_IMAGE_EOF\ndone\n\ncat << __CONF_HEADER_EOF\n\t};\n\tconfigurations {\n\t\tdefault = \"$(basename $1)\";\n\n__CONF_HEADER_EOF\n\nfor dtname in $*\ndo\n\tcat << __CONF_SECTION_EOF\n\t\t$(basename $dtname) {\n\t\t\tdescription = \"$(basename $dtname .dtb)\";\n\t\t\tfirmware = \"atf\";\n\t\t\tloadables = \"tee\", \"dm\", \"spl\";\n\t\t\tfdt = \"$(basename $dtname)\";\n\t\t};\n__CONF_SECTION_EOF\ndone\n\ncat << __ITS_EOF\n\t};\n};\n__ITS_EOF\n", "num_lines": 124}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+ OR BSD-3-Clause\n#\n# Script to add K3 specific x509 cetificate to a binary.\n#\n\n# Variables\nOUTPUT=tiboot3.bin\nTEMP_X509=x509-temp.cert\nCERT=certificate.bin\nRAND_KEY=eckey.pem\nLOADADDR=0x41c00000\nBOOTCORE_OPTS=0\nBOOTCORE=16\nDEBUG_TYPE=0\n\ngen_degen_template() {\ncat << 'EOF' > degen-template.txt\n\nasn1=SEQUENCE:rsa_key\n\n[rsa_key]\nversion=INTEGER:0\nmodulus=INTEGER:0xDEGEN_MODULUS\npubExp=INTEGER:1\nprivExp=INTEGER:1\np=INTEGER:0xDEGEN_P\nq=INTEGER:0xDEGEN_Q\ne1=INTEGER:1\ne2=INTEGER:1\ncoeff=INTEGER:0xDEGEN_COEFF\nEOF\n}\n\n# Generate x509 Template\ngen_template() {\ncat << 'EOF' > x509-template.txt\n [ req ]\n distinguished_name     = req_distinguished_name\n x509_extensions        = v3_ca\n prompt                 = no\n dirstring_type         = nobmp\n\n [ req_distinguished_name ]\n C                      = US\n ST                     = TX\n L                      = Dallas\n O                      = Texas Instruments Incorporated\n OU                     = Processors\n CN                     = TI support\n emailAddress           = support@ti.com\n\n [ v3_ca ]\n basicConstraints = CA:true\n 1.3.6.1.4.1.294.1.1 = ASN1:SEQUENCE:boot_seq\n 1.3.6.1.4.1.294.1.2 = ASN1:SEQUENCE:image_integrity\n 1.3.6.1.4.1.294.1.3 = ASN1:SEQUENCE:swrv\n# 1.3.6.1.4.1.294.1.4 = ASN1:SEQUENCE:encryption\n 1.3.6.1.4.1.294.1.8 = ASN1:SEQUENCE:debug\n\n [ boot_seq ]\n certType = INTEGER:TEST_CERT_TYPE\n bootCore = INTEGER:TEST_BOOT_CORE\n bootCoreOpts = INTEGER:TEST_BOOT_CORE_OPTS\n destAddr = FORMAT:HEX,OCT:TEST_BOOT_ADDR\n imageSize = INTEGER:TEST_IMAGE_LENGTH\n\n [ image_integrity ]\n shaType = OID:2.16.840.1.101.3.4.2.3\n shaValue = FORMAT:HEX,OCT:TEST_IMAGE_SHA_VAL\n\n [ swrv ]\n swrv = INTEGER:0\n\n# [ encryption ]\n# initalVector = FORMAT:HEX,OCT:TEST_IMAGE_ENC_IV\n# randomString = FORMAT:HEX,OCT:TEST_IMAGE_ENC_RS\n# iterationCnt = INTEGER:TEST_IMAGE_KEY_DERIVE_INDEX\n# salt = FORMAT:HEX,OCT:TEST_IMAGE_KEY_DERIVE_SALT\n\n [ debug ]\n debugUID = FORMAT:HEX,OCT:0000000000000000000000000000000000000000000000000000000000000000\n debugType = INTEGER:TEST_DEBUG_TYPE\n coreDbgEn = INTEGER:0\n coreDbgSecEn = INTEGER:0\nEOF\n}\n\nparse_key() {\n\tsed '/\\ \\ \\ \\ /s/://g' key.txt | awk  '!/\\ \\ \\ \\ / {printf(\"\\n%s\\n\", $0)}; /\\ \\ \\ \\ / {printf(\"%s\", $0)}' | sed 's/\\ \\ \\ \\ //g' | awk \"/$1:/{getline; print}\"\n}\n\ngen_degen_key() {\n# Generate a 4096 bit RSA Key\n\topenssl genrsa -out key.pem 1024 >>/dev/null 2>&1\n\topenssl rsa -in key.pem -text -out key.txt >>/dev/null 2>&1\n\tDEGEN_MODULUS=$( parse_key 'modulus' )\n\tDEGEN_P=$( parse_key 'prime1' )\n\tDEGEN_Q=$( parse_key 'prime2' )\n\tDEGEN_COEFF=$( parse_key 'coefficient' )\n\tgen_degen_template\n\n\tsed -e \"s/DEGEN_MODULUS/$DEGEN_MODULUS/\"\\\n\t\t-e \"s/DEGEN_P/$DEGEN_P/\" \\\n\t\t-e \"s/DEGEN_Q/$DEGEN_Q/\" \\\n\t\t-e \"s/DEGEN_COEFF/$DEGEN_COEFF/\" \\\n\t\t degen-template.txt > degenerateKey.txt\n\n\topenssl asn1parse -genconf degenerateKey.txt -out degenerateKey.der >>/dev/null 2>&1\n\topenssl rsa -in degenerateKey.der -inform DER -outform PEM -out $RAND_KEY >>/dev/null 2>&1\n\tKEY=$RAND_KEY\n\trm key.pem key.txt degen-template.txt degenerateKey.txt degenerateKey.der\n}\n\ndeclare -A options_help\nusage() {\n\tif [ -n \"$*\" ]; then\n\t\techo \"ERROR: $*\"\n\tfi\n\techo -n \"Usage: $0 \"\n\tfor option in \"${!options_help[@]}\"\n\tdo\n\t\targ=`echo ${options_help[$option]}|cut -d ':' -f1`\n\t\tif [ -n \"$arg\" ]; then\n\t\t\targ=\" $arg\"\n\t\tfi\n\t\techo -n \"[-$option$arg] \"\n\tdone\n\techo\n\techo -e \"\\nWhere:\"\n\tfor option in \"${!options_help[@]}\"\n\tdo\n\t\targ=`echo ${options_help[$option]}|cut -d ':' -f1`\n\t\ttxt=`echo ${options_help[$option]}|cut -d ':' -f2`\n\t\ttb=\"\\t\\t\\t\"\n\t\tif [ -n \"$arg\" ]; then\n\t\t\targ=\" $arg\"\n\t\t\ttb=\"\\t\"\n\t\tfi\n\t\techo -e \"   -$option$arg:$tb$txt\"\n\tdone\n\techo\n\techo \"Examples of usage:-\"\n\techo \"# Example of signing the SYSFW binary with rsa degenerate key\"\n\techo \"    $0 -c 0 -b ti-sci-firmware-am6x.bin -o sysfw.bin -l 0x40000\"\n\techo \"# Example of signing the SPL binary with rsa degenerate key\"\n\techo \"    $0 -c 16 -b spl/u-boot-spl.bin -o tiboot3.bin -l 0x41c00000\"\n}\n\noptions_help[b]=\"bin_file:Bin file that needs to be signed\"\noptions_help[k]=\"key_file:file with key inside it. If not provided script generates a rsa degenerate key.\"\noptions_help[o]=\"output_file:Name of the final output file. default to $OUTPUT\"\noptions_help[c]=\"core_id:target core id on which the image would be running. Default to $BOOTCORE\"\noptions_help[l]=\"loadaddr: Target load address of the binary in hex. Default to $LOADADDR\"\noptions_help[d]=\"debug_type: Debug type, set to 4 to enable early JTAG. Default to $DEBUG_TYPE\"\n\nwhile getopts \"b:k:o:c:l:d:h\" opt\ndo\n\tcase $opt in\n\tb)\n\t\tBIN=$OPTARG\n\t;;\n\tk)\n\t\tKEY=$OPTARG\n\t;;\n\to)\n\t\tOUTPUT=$OPTARG\n\t;;\n\tl)\n\t\tLOADADDR=$OPTARG\n\t;;\n\tc)\n\t\tBOOTCORE=$OPTARG\n\t;;\n\td)\n\t\tDEBUG_TYPE=$OPTARG\n\t;;\n\th)\n\t\tusage\n\t\texit 0\n\t;;\n\t\\?)\n\t\tusage \"Invalid Option '-$OPTARG'\"\n\t\texit 1\n\t;;\n\t:)\n\t\tusage \"Option '-$OPTARG' Needs an argument.\"\n\t\texit 1\n\t;;\n\tesac\ndone\n\nif [ \"$#\" -eq 0 ]; then\n\tusage \"Arguments missing\"\n\texit 1\nfi\n\nif [ -z \"$BIN\" ]; then\n\tusage \"Bin file missing in arguments\"\n\texit 1\nfi\n\n# Generate rsa degenerate key if user doesn't provide a key\nif [ -z \"$KEY\" ]; then\n\tgen_degen_key\nfi\n\nif [ $BOOTCORE == 0 ]; then\t# BOOTCORE M3, loaded by ROM\n\tCERTTYPE=2\nelif [ $BOOTCORE == 16 ]; then\t# BOOTCORE R5, loaded by ROM\n\tCERTTYPE=1\nelse\t\t\t\t# Non BOOTCORE, loaded by SYSFW\n\tBOOTCORE_OPTS_VER=$(printf \"%01x\" 1)\n\t# Add input args option for SET and CLR flags.\n\tBOOTCORE_OPTS_SETFLAG=$(printf \"%08x\" 0)\n\tBOOTCORE_OPTS_CLRFLAG=$(printf \"%08x\" 0x100) # Clear FLAG_ARMV8_AARCH32\n\tBOOTCORE_OPTS=\"0x$BOOTCORE_OPTS_VER$BOOTCORE_OPTS_SETFLAG$BOOTCORE_OPTS_CLRFLAG\"\n\t# Set the cert type to zero.\n\t# We are not using public/private key store now\n\tCERTTYPE=$(printf \"0x%08x\" 0)\nfi\n\nSHA_VAL=`openssl dgst -sha512 -hex $BIN | sed -e \"s/^.*= //g\"`\nBIN_SIZE=`cat $BIN | wc -c`\nADDR=`printf \"%08x\" $LOADADDR`\n\ngen_cert() {\n\t#echo \"Certificate being generated :\"\n\t#echo \"\tLOADADDR = 0x$ADDR\"\n\t#echo \"\tIMAGE_SIZE = $BIN_SIZE\"\n\t#echo \"\tCERT_TYPE = $CERTTYPE\"\n\t#echo \"\tDEBUG_TYPE = $DEBUG_TYPE\"\n\tsed -e \"s/TEST_IMAGE_LENGTH/$BIN_SIZE/\"\t\\\n\t\t-e \"s/TEST_IMAGE_SHA_VAL/$SHA_VAL/\" \\\n\t\t-e \"s/TEST_CERT_TYPE/$CERTTYPE/\" \\\n\t\t-e \"s/TEST_BOOT_CORE_OPTS/$BOOTCORE_OPTS/\" \\\n\t\t-e \"s/TEST_BOOT_CORE/$BOOTCORE/\" \\\n\t\t-e \"s/TEST_BOOT_ADDR/$ADDR/\" \\\n\t\t-e \"s/TEST_DEBUG_TYPE/$DEBUG_TYPE/\" \\\n\t\tx509-template.txt > $TEMP_X509\n\topenssl req -new -x509 -key $KEY -nodes -outform DER -out $CERT -config $TEMP_X509 -sha512\n}\n\ngen_template\ngen_cert\ncat $CERT $BIN > $OUTPUT\n\n# Remove all intermediate files\nrm $TEMP_X509 $CERT x509-template.txt\nif [ \"$KEY\" == \"$RAND_KEY\" ]; then\n\trm $RAND_KEY\nfi\n", "num_lines": 253}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0\n#\n######################################################\n# Copyright (C) 2016 Marvell International Ltd.\n#\n# https://spdx.org/licenses\n#\n# Author: Konstantin Porotchkin kostap@marvell.com\n#\n# Version 0.3\n#\n# UART recovery downloader for Armada SoCs\n#\n######################################################\n\nport=$1\nfile=$2\nspeed=$3\n\npattern_repeat=1500\ndefault_baudrate=115200\ntmpfile=/tmp/xmodem.pattern\ntools=( dd stty sx minicom )\n\ncase \"$3\" in\n    2)\n        fast_baudrate=230400\n        prefix=\"\\xF2\"\n        ;;\n    4)\n        fast_baudrate=460800\n        prefix=\"\\xF4\"\n        ;;\n    8)\n    \tfast_baudrate=921600\n        prefix=\"\\xF8\"\n        ;;\n    *)\n    \tfast_baudrate=$default_baudrate\n        prefix=\"\\xBB\"\nesac\n\nif [[ -z \"$port\" || -z \"$file\" ]]\nthen\n    echo -e \"\\nMarvell recovery image downloader for Armada SoC family.\"\n    echo -e \"Command syntax:\"\n    echo -e \"\\t$(basename $0) <port> <file> [2|4|8]\"\n    echo -e \"\\tport  - serial port the target board is connected to\"\n    echo -e \"\\tfile  - recovery boot image for target download\"\n    echo -e \"\\t2|4|8 - times to increase the default serial port speed by\"\n    echo -e \"For example - load the image over ttyUSB0 @ 460800 baud:\"\n    echo -e \"$(basename $0) /dev/ttyUSB0 /tmp/flash-image.bin 4\\n\"\n    echo -e \"=====WARNING=====\"\n    echo -e \"- The speed-up option is not available in SoC families prior to A8K+\"\n    echo -e \"- This utility is not compatible with Armada 37xx SoC family\\n\"\nfi\n\n# Sanity checks\nif [ -c \"$port\" ]\nthen\n   echo -e \"Using device connected on serial port \\\"$port\\\"\"\nelse\n   echo \"Wrong serial port name!\"\n   exit 1\nfi\n\nif [ -f \"$file\" ]\nthen\n   echo -e \"Loading flash image file \\\"$file\\\"\"\nelse\n   echo \"File $file does not exist!\"\n   exit 1\nfi\n\n# Verify required tools installation\nfor tool in ${tools[@]}\ndo\n    toolname=`which $tool`\n    if [ -z \"$toolname\" ]\n    then\n        echo -e \"Missing installation of \\\"$tool\\\" --> Exiting\"\n        exit 1\n    fi\ndone\n\n\necho -e \"Recovery will run at $fast_baudrate baud\"\necho -e \"========================================\"\n\nif [ -f \"$tmpfile\" ]\nthen\n    rm -f $tmpfile\nfi\n\n# Send the escape sequence to target board using default debug port speed\nstty -F $port raw ignbrk time 5 $default_baudrate\ncounter=0\nwhile [ $counter -lt $pattern_repeat ]; do\n    echo -n -e \"$prefix\\x11\\x22\\x33\\x44\\x55\\x66\\x77\" >> $tmpfile\n    let counter=counter+1\ndone\n\necho -en \"Press the \\\"Reset\\\" button on the target board and \"\necho -en \"the \\\"Enter\\\" key on the host keyboard simultaneously\"\nread\ndd if=$tmpfile of=$port &>/dev/null\n\n# Speed up the binary image transfer\nstty -F $port raw ignbrk time 5 $fast_baudrate\nsx -vv $file > $port < $port\n#sx-at91 $port $file\n\n# Return the port to the default speed\nstty -F $port raw ignbrk time 5 $default_baudrate\n\n# Optional - fire up Minicom\nminicom -D $port -b $default_baudrate\n\n", "num_lines": 120}
{"repo_name": "openbmc-uboot", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# SPDX-License-Identifier: GPL-2.0+\n# Copyright (C) 2018 Michal Simek <michal.simek@xilinx.com>\n# Copyright (C) 2019 Luca Ceresoli <luca@lucaceresoli.net>\n\nusage()\n{\n    cat <<EOF\n\nTransform a pair of psu_init_gpl.c and .h files produced by the Xilinx\nVivado tool for ZynqMP into a smaller psu_init_gpl.c file that is almost\ncheckpatch compliant. Minor coding style might still be needed. Must be\nrun from the top-level U-Boot source directory.\n\nUsage:   zynqmp_psu_init_minimize.sh INPUT_DIR OUTPUT_DIR\nExample: zynqmp_psu_init_minimize.sh \\\\\n                 /path/to/original/psu_init_gpl_c_and_h/ \\\\\n                 board/xilinx/zynqmp/<my_board>/\n\nNotes:   INPUT_DIR must contain both .c and .h files.\n         If INPUT_DIR and OUTPUT_DIR are the same directory,\n         psu_init_gpl.c will be overwritten.\n\nEOF\n}\n\nset -o errexit -o errtrace\nset -o nounset\n\nif [ $# -ne 2 ]\nthen\n    usage >&2\n    exit 1\nfi\n\nIN=\"${1}/psu_init_gpl.c\"\nOUT=\"${2}/psu_init_gpl.c\"\nTMP=$(mktemp /tmp/psu_init_gpl.XXXXXX)\ntrap \"rm ${TMP}\" ERR\n\n# Step through a temp file to allow both $IN!=$OUT and $IN==$OUT\nsed -e '/sleep.h/d' \\\n    -e '/xil_io.h/d' \\\n    ${IN} >${TMP}\ncp ${TMP} ${OUT}\n\n# preprocess to expand defines, then remove cpp lines starting with '#'\ngcc -I${1} -E ${OUT} -o ${TMP}\nsed '/^#/d' ${TMP} >${OUT}\n\n# Remove trivial code before psu_pll_init_data()\nsed -ni '/psu_pll_init_data/,$p' ${OUT}\n\n# Functions are lowercase in U-Boot, rename them\nsed -i 's/PSU_Mask_Write/psu_mask_write/g' ${OUT}\nsed -i 's/mask_pollOnValue/mask_pollonvalue/g' ${OUT}\nsed -i 's/RegValue/regvalue/g' ${OUT}\nsed -i 's/MaskStatus/maskstatus/g' ${OUT}\n\nsed -i '/&= psu_peripherals_powerdwn_data()/d' ${OUT}\n\nFUNCS_TO_REMOVE=\"psu_protection\npsu_..._protection\npsu_init_xppu_aper_ram\nmask_delay(u32\nmask_read(u32\nmask_poll(u32\nmask_pollonvalue(u32\npsu_ps_pl_reset_config_data\npsu_ps_pl_isolation_removal_data\npsu_apply_master_tz\npsu_post_config_data\npsu_post_config_data\npsu_peripherals_powerdwn_data\npsu_init_ddr_self_refresh\nxmpu\nxppu\n\"\nfor i in $FUNCS_TO_REMOVE; do\nsed -i \"/$i/,/^}$/d\" ${OUT}\ndone\n\nscripts/Lindent ${OUT}\n\n# Prepend 'static' to internal functions\nsed -i 's/^.*data(void)$/static &/g' ${OUT}\nsed -i 's/^.*psu_afi_config(void)$/static &/g' ${OUT}\nsed -i 's/^void init_peripheral/static &/g' ${OUT}\nsed -i 's/^int serdes/static &/g' ${OUT}\nsed -i 's/^int init_serdes/static &/g' ${OUT}\nsed -i 's/^unsigned long /static &/g' ${OUT}\n\nsed -i 's/()$/(void)/g' ${OUT}\nsed -i 's/0X/0x/g' ${OUT}\n\n# return (0) -> return 0\nsed -ri 's/return \\(([0-9]+)\\)/return \\1/g' ${OUT}\n\n# Add header\ncat << EOF >${TMP}\n// SPDX-License-Identifier: GPL-2.0+\n/*\n * (c) Copyright 2015 Xilinx, Inc. All rights reserved.\n */\n\n#include <asm/arch/psu_init_gpl.h>\n#include <xil_io.h>\n\nEOF\n\ncat ${OUT} >>${TMP}\ncp ${TMP} ${OUT}\n\n# Temporarily convert newlines to do some mangling across lines\ntr \"\\n\" \"\\r\" <${OUT} >${TMP}\n\n# Cleanup empty loops. E.g.:\n# |while (e) {|\n# |           | ==> |while (e)|\n# |    }      |     |    ;    |\n# |           |\nsed -i -r 's| \\{\\r+(\\t*)\\}\\r\\r|\\n\\1\\t;\\n|g' ${TMP}\n\n# Remove empty line between variable declaration\nsed -i -r 's|\\r(\\r\\t(unsigned )?int )|\\1|g' ${TMP}\n\n# Remove empty lines at function beginning/end\nsed -i -e 's|\\r{\\r\\r|\\r{\\r|g' ${TMP}\nsed -i -e 's|\\r\\r}\\r|\\r}\\r|g' ${TMP}\n\n# Remove empty lines after '{' line\nsed -i -e 's| {\\r\\r| {\\r|g' ${TMP}\n\n# Remove braces {} around single statement blocks. E.g.:\n# | while (e) { |    | while (e) |\n# |     stg();  | => |     stg();|\n# | }           |\nsed -i -r 's| \\{(\\r[^\\r]*;)\\r\\t*\\}|\\1|g' ${TMP}\n\n# Remove Unnecessary parentheses around 'n_code <= 0x3C' and similar. E.g.:\n# if ((p_code >= 0x26) && ...) -> if (p_code >= 0x26 && ...)\nsed -i -r 's|\\((._code .= [x[:xdigit:]]+)\\)|\\1|g' ${TMP}\n\n# Convert back newlines\ntr \"\\r\" \"\\n\" <${TMP} >${OUT}\n\nrm ${TMP}\n", "num_lines": 148}
{"repo_name": "openr", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC1090\nsource \"$(dirname \"$0\")/common.sh\"\n\nalias thrift1=/opt/facebook/fbthrift/bin/thrift1\n\n# Step 1: Stage compilation\n\n# folly Cython\nmkdir ./folly\ncp -r \\\n/tmp/fbcode_builder_getdeps-ZsrcZbuildZfbcode_builder-root/repos/github.com-facebook-folly.git/folly/python/* ./folly\n\n# fb303 thrift\nmkdir -p ./fb303-thrift\ncp -r  /opt/facebook/fb303/include/thrift-files/fb303 ./fb303-thrift/\n\n# fbthrift Cython and thrift\ncp -r  /opt/facebook/fbthrift/include/thrift/lib/ ./thrift\ntouch ./thrift/py3/__init__.py\ntouch ./thrift/__init__.py\n\nmkdir /src/fbthrift-thrift\ncp -r \\\n/tmp/fbcode_builder_getdeps-ZsrcZbuildZfbcode_builder-root/repos/github.com-facebook-fbthrift.git/thrift/lib/thrift/* \\\n/src/fbthrift-thrift\n\nmkdir -p /src/thrift/py3\nchown -R root /tmp/fbcode_builder_getdeps-ZsrcZbuildZfbcode_builder-root/repos/github.com-facebook-fbthrift.git/thrift/lib/py3/\ncp -r \\\n/tmp/fbcode_builder_getdeps-ZsrcZbuildZfbcode_builder-root/repos/github.com-facebook-fbthrift.git/thrift/lib/py3/* \\\n/src/thrift/py3\ntouch /src/thrift/__init__.py\n\n# Open/R thrift\nmkdir -p ./openr-thrift/openr\ncp -r /src/openr/if/ ./openr-thrift/openr/\n\n# Neteng thrift\nmkdir -p neteng-thrift/configerator/structs/neteng/config/\ncp -r \\\n/tmp/fbcode_builder_getdeps-ZsrcZbuildZfbcode_builder-root/repos/github.com-facebook-openr.git/configerator/structs/neteng/config/routing_policy.thrift \\\nneteng-thrift/configerator/structs/neteng/config/\n\n# HACK TO FIX CYTHON .pxd\ncp /cython/Cython/Includes/libcpp/utility.pxd /usr/lib/python3/dist-packages/Cython/Includes/libcpp/utility.pxd\n\n# Step 2. Generate mstch_cpp2 and mstch_py3 bindings\n\npython3 /src/build/gen.py\n\n# HACK TO FIX fbthrift-py/gen-cpp2/\necho \" \" > /src/fbthrift-thrift/gen-cpp2/metadata_metadata.h\necho \" \" > /src/fbthrift-thrift/gen-cpp2/metadata_types.h\necho \" \" > /src/fbthrift-thrift/gen-cpp2/metadata_types_custom_protocol.h\n\n# Step 3. Generate clients.cpp\n\npython3 /src/build/cython_compile.py\n\n# Step 4. Compile .so\n\n# shellcheck disable=SC2097,SC2098\nenv \\\nCC=\"/usr/bin/gcc-10\" \\\nCXX=\"/usr/bin/g++-10\" \\\nCFLAGS=\"-I. -Iopenr-thrift -Ifb303-thrift -Ineteng-thrift -std=c++20 -fcoroutines \" \\\nCFLAGS=\"$CFLAGS -w -D_CPPLIB_VER=20\" \\\nCXXFLAGS=\"$CFLAGS\" \\\npython3 openr/py/setup.py build -j10\n", "num_lines": 76}
{"repo_name": "openr", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck disable=SC1090\nsource \"$(dirname \"$0\")/common.sh\"\n\n# TODO: Get apt deb installing working - dies in Docker container with libzstd-dev fixed\n# \"$PYTHON3\" \"$GETDEPS\" --allow-system-packages install-system-deps --recursive openr\n# errorCheck \"Failed to install-system-deps for openr\"\n\n\"$PYTHON3\" \"$GETDEPS\" --allow-system-packages build --no-tests --install-prefix \"$INSTALL_PREFIX\" \\\n--extra-cmake-defines \"$EXTRA_CMAKE_DEFINES\" openr\nerrorCheck \"Failed to build openr\"\n\n# TODO: Maybe fix src-dir to be absolute reference to dirname $0's parent\n\"$PYTHON3\" \"$GETDEPS\" fixup-dyn-deps --strip --src-dir=. openr _artifacts/linux  --project-install-prefix openr:\"$INSTALL_PREFIX\" --final-install-prefix \"$INSTALL_PREFIX\"\nerrorCheck \"Failed to fixup-dyn-deps for openr\"\n", "num_lines": 21}
{"repo_name": "openr", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nGETDEPS=\"$(dirname \"$0\")/fbcode_builder/getdeps.py\"\nINSTALL_PREFIX=\"/opt/facebook\"\nPYTHON3=$(command -v python3)\nPIP3=$(command -v pip3)\n# shellcheck disable=SC2089\nEXTRA_CMAKE_DEFINES='{\"CMAKE_POSITION_INDEPENDENT_CODE\": \"ON\"}'\n\n# shellcheck disable=SC2090\nexport GETDEPS INSTALL_PREFIX PYTHON3 PIP3 EXTRA_CMAKE_DEFINES\n\nerrorCheck() {\n  return_code=$?\n  if [ $return_code -ne 0 ]; then\n    echo \"[ERROR]: $1\"\n    exit $return_code\n  fi\n}\n\nif [ \"$PYTHON3\" == \"\" ]; then\n  echo \"ERROR: No \\`python3\\` in PATH\"\n  exit 1\nfi\n\nif [ \"$PIP3\" == \"\" ]; then\n  echo \"ERROR: No \\`pip3\\` in PATH\"\n  exit 2\nfi\n", "num_lines": 34}
{"repo_name": "openr", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nCFG_BASE=\"/config\"\nDEFAULT_CFG=\"/etc/openr.conf\"\nFB_BASE=\"/opt/facebook\"\nOPENR_CFG=\"${CFG_BASE}/openr.conf\"\n\nLIBSODIUM=\"${FB_BASE}/libsodium-*/lib/\"\nGLOG=\"${FB_BASE}/glog-*/lib/\"\nGFLAGS=\"${FB_BASE}/gflags-*/lib/\"\nSNAPPY=\"${FB_BASE}/snappy-*/lib/\"\n\n\n# Hack to fix environment for openr linking\nfor dep in $LIBSODIUM $GLOG $GFLAGS $SNAPPY\ndo\n  evaled_path=$(eval echo \"${dep}\")\n  export LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:$evaled_path\"\ndone\nexport PATH=\"${PATH}:${FB_BASE}/openr/sbin\"\n\nmkdir -p \"$CFG_BASE\"\nif [ ! -s \"$OPENR_CFG\" ]\nthen\n  echo \"Copying default Open/R config - Please check settings!\"\n  cp -vp \"$DEFAULT_CFG\" \"$CFG_BASE\"\nfi\n\necho \"[$(date)] Attempting to start Open/R using $OPENR_CFG $*\"\nopenr_bin -v 2 --config \"$OPENR_CFG\" \"$@\"\n", "num_lines": 35}
{"repo_name": "openr", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n#\n# Simple Script to copy configs + start openr\n#\n\n\nCONFIG_DIR=\"/tmp/orie_configs\"\n\n\nif [ \"$1\" == \"copy-conf\" ]; then\n    # No need to copy cofigs as root\n    if [ \"$USER\" == \"root\" ]; then\n        echo \"!!-> Don't copy as root ...\"\n        exit 1\n    fi\n\n    # Copy configs to /tmp\n    # Have to copy due to eden behviours\n\n    config_dir=\"$HOME/fbsource/fbcode/openr/orie/labs/$2\"\n    if [ ! -e \"$config_dir\" ]; then\n        echo \"!!-> $config_dir does not exist\"\n        exit 2\n    fi\n\n    config_src=\"$(find \"$config_dir\" -name '*.conf' | tr '\\n' ' ')\"\n    echo \"--> Configuration being copied: $config_src to $CONFIG_DIR\"\n    mkdir -pv \"$CONFIG_DIR\"\n    sudo chown \"$USER\" \"$CONFIG_DIR\"\n    # shellcheck disable=SC2086\n    cp -v $config_src \"$CONFIG_DIR\"\n    exit $?\nelif [ \"$1\" == \"start\" ]; then\n    # Automagically selects config file depending on your netns name\n    openr_binary=\"$HOME/fbsource/fbcode/buck-out/gen/openr/openr\"\n    config=\"$CONFIG_DIR/$(ip netns identify).conf\"\n    echo \"--> Starting Open/R using --config=$config\"\n    \"$openr_binary\" \\\n        --config=\"$config\" \\\n        --logtostderr \\\n        --v=2 \\\n        --enable_secure_thrift_server=false |& tee \"/tmp/$(ip netns identify).log\"\n    exit $?\nfi\n\necho \"!!--> ERROR: Specify an option: copy-conf|start !!\"\nexit 69\n", "num_lines": 53}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "```\nsudo yum update &&\nsudo yum -y upgrade &&\nsudo yum -y install python36 python36-devel python36-libs &&\nwget https://nodejs.org/dist/latest-v9.x/node-v9.11.2-linux-x64.tar.gz &&\ntar -xzvf node-v9.11.2-linux-x64.tar.gz &&\ncd node-v9.11.2-linux-x64 &&\nsudo cp -r bin/* /usr/local/bin/ && sudo cp -r lib/* /usr/local/lib && sudo cp -r share/* /usr/local/share &&\ncd .. &&\nsudo yum install -y postgresql95 && sudo yum install postgresql95-server &&\nsudo yum install -y libxml2 libxml2-devel &&\nsudo yum install -y geos geos-devel &&\n\n\n```\n", "num_lines": 16}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n/bin/systemctl start tasking-manager.service\n/bin/sleep 10\n", "num_lines": 5}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n/bin/systemctl stop tasking-manager.service\n/bin/sleep 10\n", "num_lines": 5}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# Node.JS 10\n# PostgreSQL 9.5\n\n# Do not prompt to trust Github.com\n/usr/bin/ssh-keyscan -t rsa github.com | sudo /usr/bin/tee -a /etc/ssh/ssh_known_hosts\n\n# Do not prompt for answers\nexport DEBIAN_FRONTEND=noninteractive\nexport LC_ALL=\"en_US.UTF-8\"\nexport LC_CTYPE=\"en_US.UTF-8\"\nexport LC_ALL=C\nsudo dpkg-reconfigure --frontend=noninteractive locales\n\nsudo apt-get -y install \\\n    make build-essential \\\n    libssl-dev zlib1g-dev libbz2-dev \\\n    libreadline-dev libsqlite3-dev \\\n    llvm libncurses5-dev libncursesw5-dev \\\n    xz-utils tk-dev libffi-dev liblzma-dev\n\nsudo apt-get -y update\n\necho \"Upgrade Ubuntu packages..\"\nsudo DEBIAN_FRONTEND=noninteractive apt-get -y \\\n    -o Dpkg::Options::=\"--force-confdef\" \\\n    -o Dpkg::Options::=\"--force-confold\" upgrade\n\necho \"Install basic utilities..\"\nsudo apt-get -y install \\\n    awscli \\\n    curl \\\n    git \\\n    ruby \\\n    unzip \\\n    wget \\\n    grub kpartx             # Dependencies for ec2-ami-tools\n\n# Install Python3.6\nwget https://www.python.org/ftp/python/3.6.9/Python-3.6.9.tgz\ntar -xf Python-3.6.9.tgz && \\\n    cd Python-3.6.9 && \\\n    sudo ./configure --enable-optimizations --with-ensurepip=install && \\\n    sudo make altinstall\n\n# Install mapping related stuff\n# libgdal* - Geospatial Data Abstraction Library (GDAL)\n# libgeos* - Geometry engine\n# libproj* - Cartographic projects & translations between CRS\nsudo apt-get -y install \\\n    libgdal-dev \\\n    libgeos-3.5.1 libgeos-dev \\\n    libproj12 libproj-dev \\\n    libxml2 libxml2-dev \\\n    libjson-c-dev\n\nsudo apt-get -y install \\\n    postgresql-9.5 \\\n    postgresql-server-dev-9.5 \\\n    libpq-dev                    # PostgreSQL Library to C\n\n# Setup Node.JS v10.x\ncurl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -\nsudo apt-get -y install nodejs\n\n# Install dependencies\nsudo npm install gulp -g\nsudo npm install browser-sync --save # Probably add this to package.json?\n\n# sudo git clone --recursive https://github.com/hotosm/tasking-manager.git /tasking-manager\nsudo git clone --recursive --single-branch \\\n    --branch deployment/hot-tasking-manager \\\n    https://github.com/hotosm/tasking-manager.git /tasking-manager\n\n\n# inotify watches for filesystem (why?)\necho fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf\n\n# Local install of aws-cfn-bootstrap template\nwget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\nsudo pip2 install aws-cfn-bootstrap-latest.tar.gz\n\n# EC2 AMI tools installation (why?)\nwget https://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.zip\nsudo mkdir -p /usr/local/ec2\nsudo unzip -qq ec2-ami-tools.zip -d /usr/local/ec2\n\n# add to etc/profile.d/myenvvars.sh export variable EC2_AMITOOL_HOME\nsudo touch /etc/profile.d/myenvvars.sh\necho \"export EC2_AMITOOL_HOME=/usr/local/ec2/ec2-ami-tools-1.5.7\" | sudo tee -a /etc/profile.d/myenvvars.sh\necho \"export PATH=/usr/local/ec2/ec2-ami-tools-1.5.7/bin:$PATH:\" | sudo tee -a /etc/profile.d/myenvvars.sh\n", "num_lines": 93}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# Node.JS 10\n# PostgreSQL 9.5\n\n# Do not prompt to trust Github.com\n/usr/bin/ssh-keyscan -t rsa github.com | sudo /usr/bin/tee -a /etc/ssh/ssh_known_hosts\n\n# Do not prompt for answers\nexport DEBIAN_FRONTEND=noninteractive\nexport LC_ALL=\"en_US.UTF-8\"\nexport LC_CTYPE=\"en_US.UTF-8\"\nexport LC_ALL=C\nsudo dpkg-reconfigure --frontend=noninteractive locales\n\n\n# Add Third-party repository for Python 3.6 distribution \n# Ubuntu 16.04 does not provide via repos.\nsudo add-apt-repository ppa:jonathonf/python-3.6 -y\nsudo apt-get -y update\n\necho \"Upgrade Ubuntu packages..\"\nsudo DEBIAN_FRONTEND=noninteractive apt-get -y \\\n    -o Dpkg::Options::=\"--force-confdef\" \\\n    -o Dpkg::Options::=\"--force-confold\" upgrade\n\necho \"Install basic utilities..\"\nsudo apt-get -y install \\\n    awscli \\\n    curl \\\n    git \\\n    ruby \\\n    unzip \\\n    wget \\\n    grub kpartx             # Dependencies for ec2-ami-tools\n\nsudo apt-get -y install \\\n    python3.6 python3.6-dev \\\n    python3.6-venv \\\n    python-pip                 # Default python pip (why?)\n\n# Install mapping related stuff\n# libgdal1* - Geospatial Data Abstraction Library (GDAL)\n# libgeos* - Geometry engine\n# libproj* - Cartographic projects & translations between CRS\nsudo apt-get -y install \\\n    libgdal1-dev \\\n    libgeos-3.5.0 libgeos-dev \\\n    libproj9 libproj-dev \\\n    libxml2 libxml2-dev \\\n    libjson-c-dev\n\nsudo apt-get -y install \\\n    postgresql-9.5 \\\n    postgresql-server-dev-9.5 \\\n    libpq-dev                    # PostgreSQL Library to C\n\n# Setup Node.JS v10.x\ncurl -sL https://deb.nodesource.com/setup_10.x | sudo -E bash -\nsudo apt-get -y install nodejs\n\n# sudo git clone --recursive https://github.com/hotosm/tasking-manager.git /tasking-manager\nsudo git clone --recursive --single-branch \\\n    --branch deployment/hot-tasking-manager \\\n    https://github.com/hotosm/tasking-manager.git /tasking-manager\n\n\n# inotify watches for filesystem (why?)\necho fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf\n\n# Local install of aws-cfn-bootstrap template\nwget https://s3.amazonaws.com/cloudformation-examples/aws-cfn-bootstrap-latest.tar.gz\nsudo pip2 install aws-cfn-bootstrap-latest.tar.gz\n\n# EC2 AMI tools installation (why?)\nwget https://s3.amazonaws.com/ec2-downloads/ec2-ami-tools.zip\nsudo mkdir -p /usr/local/ec2\nsudo unzip -qq ec2-ami-tools.zip -d /usr/local/ec2\n\n# add to etc/profile.d/myenvvars.sh export variable EC2_AMITOOL_HOME\nsudo touch /etc/profile.d/myenvvars.sh\necho \"export EC2_AMITOOL_HOME=/usr/local/ec2/ec2-ami-tools-1.5.7\" | sudo tee -a /etc/profile.d/myenvvars.sh\necho \"export PATH=/usr/local/ec2/ec2-ami-tools-1.5.7/bin:$PATH:\" | sudo tee -a /etc/profile.d/myenvvars.sh\n", "num_lines": 84}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "NEW_DB='tm_new'\n\necho $NEW_DB\npsql -U $DB_USER -d $DB -c \"DROP DATABASE $NEW_DB\"\npsql -U $DB_USER -d $DB -c \"CREATE DATABASE $NEW_DB\"\npsql -U $DB_USER -d $NEW_DB -c \"CREATE EXTENSION postgis;\"", "num_lines": 6}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "\ndo_dash() {\n   echo \"---------------------------------------------------------------\"\n}\n\ndo_dash; echo \"\\n Defining variables\"\n\nRDS_LIST=( \"prod-05-jun\" \"prod-06-jun\" \"prod-07-jun\" \"prod-08-jun\" \"prod-09-jun\"\n           \"prod-10-jun\" \"prod-11-jun\" \"prod-snapshot-before-12-jun-deploy\" \"prod-12-jun\" )\nFOLDER_PATH=dump/lost_projects\n\nfor HOST in \"${RDS_LIST[@]}\"; do\n  echo $HOST\n  do_dash; echo \"Priority areas tables\"\n  TABLE=priority_areas\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Projects table\"\n  TABLE=projects\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project allowed users\"\n  TABLE=project_allowed_users\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Tasks table\"\n  TABLE=tasks\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Task history\"\n  TABLE=task_history\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Task invalidation history\"\n  TABLE=task_invalidation_history\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project priority areas\"\n  TABLE=project_priority_areas\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project chat\"\n  TABLE=project_chat\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project info\"\n  TABLE=project_info\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy $TABLE FROM '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Messages\"\n  TABLE=messages\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"CREATE TABLE temp_$TABLE(LIKE messages);\"\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n    \t\"\\copy temp_$TABLE FROM '$FILE' DELIMITER ',' CSV HEADER;\"\n  psql \"host=$TARGET_HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n      \t\"UPDATE $TABLE SET\n      \t\ttask_id=temp_$TABLE.task_id,\n      \t\tproject_id=temp_$TABLE.project_id\n      \tFROM temp_$TABLE\n      \tWHERE\n      \t\ttemp_$TABLE.id=$TABLE.id\n      \tAND\n      \t\ttemp_$TABLE.id IN (SELECT id FROM $TABLE);\n      \tINSERT INTO $TABLE SELECT * FROM temp_$TABLE WHERE id NOT IN (SELECT id FROM messages);\n      \tDROP TABLE temp_$TABLE;\"\n\n\ndone\n", "num_lines": 107}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "\ndo_dash() {\n   echo \"---------------------------------------------------------------\"\n}\n\nSAVE=true\n\n# 983,523,5780,286,1088,5014,4626,2854,1125,1858,2169,4443,3035,4179,3866,1774,1308,5667,3156,5498,4992,5831,4828,5639,3566,4811,3518,2014,3271,2871,5655,5447,4324,2338,2283,1770,3736,3605,1702,704,2843,1179,5580,2679,4083,5601,2051,2893,1999,546,4226,3109,6035,4465,4090,1707,1019,2157,4983,2156,886,4153,553,2543,1970,2759,2632,5839,4539,4531,4746,1783,3323,2199,5958,830,2638,2072,5417,1367,1192,5059,2890,1877,1782,5651,4743,4111,897,339,5583,3562,3448,3098,188,5523,5582,4784,2770,6127\ndo_dash; echo \"\\n Defining variables\"\n\nRDS_LIST=( \"prod-05-jun\" \"prod-06-jun\" \"prod-07-jun\" \"prod-08-jun\" \"prod-09-jun\"\n           \"prod-10-jun\" \"prod-11-jun\" \"prod-snapshot-before-12-jun-deploy\" \"prod-12-jun\" )\nPROJECT_IDS=( \"(4995)\" \"(4413,5365,5401,5402,5474,5501,5604,5605,5740,5773,5795,5840,5890,5999,6000,6002)\"\n             \"(1945,3744,5127,5375,5685,5762,5956,5968,5969,5978,6067)\"\n             \"(3901,5808,5844)\" \"(5953,5692,5169,4166,3904)\"\n             \"(6015,6005,5948,5274,4411,4392,4259)\"\n             \"(2742,3389,5340,5455,5652)\" \"(5942,4351)\"\n             \"(2469,4597,5509,5660,5831,5895,5907,5964,6059,6061)\" )\nIDX=0\n\n# Create folder.\necho \"Creating folders\"\nFOLDER_PATH=dump/lost_projects\nmkdir -p $FOLDER_PATH\n\n\nfor HOST in \"${RDS_LIST[@]}\"; do\n  do_dash; echo \"Priority areas tables\"\n  TABLE=priority_areas\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  echo $HOST\n  echo ${PROJECT_IDS[IDX]}\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE id in\n  \t\t(SELECT priority_area_id from project_priority_areas where project_id in ${PROJECT_IDS[IDX]}))\n  \t\tto '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Projects table\"\n  TABLE=projects\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project allowed users\"\n  TABLE=project_allowed_users\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Tasks table\"\n  TABLE=tasks\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Task history\"\n  TABLE=task_history\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Task invalidation history\"\n  TABLE=task_invalidation_history\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project priority areas\"\n  TABLE=project_priority_areas\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project chat\"\n  TABLE=project_chat\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Project info\"\n  TABLE=project_info\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ###############################################################################################\n\n  do_dash; echo \"Messages\"\n  TABLE=messages\n  mkdir -p $FOLDER_PATH/$HOST\n  FILE=$FOLDER_PATH/$HOST/$TABLE.csv\n  psql \"host=$HOST.$ENDPOINT dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n  \t\"\\copy (SELECT * FROM $TABLE WHERE project_id in ${PROJECT_IDS[IDX]}) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n  ((IDX++))\ndone\n\n\n\n###############################################################################################\n# TABLE=users\n# do_dash; echo \"users from tables\"\n# psql \"host=$HOST dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n# \t\"copy(SELECT * FROM $TABLE WHERE id in\n# \t\t(select author_id from projects where id in $PROJECT_IDS)\n# \t\tOR id in (select users.id from users,project_allowed_users where users.id=project_allowed_users.user_id AND project_allowed_users.project_id in $PROJECT_IDS)\n# \t\tOR id in (select users.id from users,task_history where users.id=task_history.user_id AND task_history.project_id in $PROJECT_IDS)\n# \t\tOR id in (select users.id from users,tasks where users.id in (tasks.locked_by, tasks.validated_by, tasks.mapped_by) AND tasks.project_id in $PROJECT_IDS))\n# \t\tto '$FILE' DELIMITER ',' CSV HEADER\"\n\n# if $SAVE; then\n# \tsave_to_db\n# fi\n\n\n# ###############################################################################################\n\n# do_dash; echo \"licenses from tables\"\n# TABLE=licenses\n# psql \"host=$HOST dbname=$DB user=$DB_USER password=$DB_PASSWORD\" -c \\\n# \t\"copy(SELECT * FROM $TABLE WHERE id in (select license_id from projects where id in $PROJECT_IDS)) to '$FILE' DELIMITER ',' CSV HEADER\"\n\n# if $SAVE; then\n# \tsave_to_db\n# fi\n\n###############################################################################################\n", "num_lines": 153}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to install the Tasking Manager on Debian 10 Buster\n# The script must be executed from the root of the project\n\n# Ensure being run on the supported operating system\ndistribution=$(lsb_release -si)\nversion=$(lsb_release -sc)\n\nif [ \"$distribution\" != \"Debian\" ] || [ \"$version\" != \"buster\" ]; then\n  echo -e \"ERROR: Your operating system is not supported by this installation script\"\n  exit\nfi\n\n# Make sure the system is up-to-date\nsudo apt update && sudo apt -y upgrade &&\n\n## Install general tools\nsudo apt install -y build-essential curl git libgeos-dev software-properties-common &&\n\n# Install Python and Node\ncurl -sL https://deb.nodesource.com/setup_10.x | sudo bash -\nsudo apt install -y python3 python3-dev python3-venv nodejs &&\n\n# Install the database\nsudo apt install -y postgresql-10 libpq-dev postgresql-server-dev-10 postgresql-10-postgis-2.4 postgresql-10-postgis-scripts &&\n\n## Obtain the tasking manager\ngit clone https://github.com/hotosm/tasking-manager.git &&\n\n## Prepare the tasking manager\ncd tasking-manager/ &&\npython3 -m venv ./venv &&\n. ./venv/bin/activate &&\npip install --upgrade pip &&\npip install -r requirements.txt &&\n\n# Set up configuration\n# Sets db endpoint to localhost.\nif ! test -f tasking-manager.env\n\tthen\n    cp example.env tasking-manager.env\nfi\n. ./tasking-manager.env &&\nsed -i '/POSTGRES_ENDPOINT/s/^# //g' tasking-manager.env &&\n\n# Set up data base\nif ! sudo -u postgres psql -c \"SELECT u.usename FROM pg_catalog.pg_user u;\" | grep -w -q $POSTGRES_USER\n\tthen\n\t\tsudo -u postgres psql -c \"CREATE USER $POSTGRES_USER WITH PASSWORD '$POSTGRES_PASSWORD';\"\nfi\nif ! sudo -u postgres psql -c \"SELECT datname FROM pg_database WHERE datistemplate = false;\" | grep -w -q $POSTGRES_DB\n\tthen\n    sudo -u postgres createdb -T template0 $POSTGRES_DB -E UTF8 -O $POSTGRES_USER &&\n    sudo -u postgres psql -d $POSTGRES_DB -c \"CREATE EXTENSION postgis;\"\nfi\n\n\n# Populate database\ncd tests/database/ &&\nsudo -u postgres psql -d $POSTGRES_DB -c \"\\i tasking-manager.sql\" &&\nfor tbl in `sudo -u postgres psql -qAt -c \"select tablename from pg_tables where schemaname = 'public';\" $POSTGRES_DB`;\ndo  sudo -u postgres psql -c \"alter table \\\"$tbl\\\" owner to $POSTGRES_USER\" $POSTGRES_DB ; done &&\nfor tbl in `sudo -u postgres psql -qAt -c \"select tablename from pg_tables where schemaname = 'topology';\" $POSTGRES_DB`;\ndo  sudo -u postgres psql -c \"alter table \\\"$tbl\\\" owner to $POSTGRES_USER\" $POSTGRES_DB ; done &&\ncd ../../ &&\n\n# Upgrade database\n./venv/bin/python3 manage.py db upgrade &&\n\n# Assamble the tasking manager interface\ncd frontend/ &&\nnpm install &&\nnpm run build &&\ncd ../ &&\n\n## Please edit the tasking-manager.env as indicated in the README.md ##\n\n# Start the tasking manager\n./venv/bin/python manage.py runserver -d\n", "num_lines": 81}
{"repo_name": "OSM-HOT-Tasking-Manager", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to install the Tasking Manager on Ubuntu 18.04\n#\n\n# Ensure being run on the supported operating system\ndistribution=$(lsb_release -si)\nversion=$(lsb_release -sc)\n\nif [ \"$distribution\" != \"Ubuntu\" ] || [ \"$version\" != \"bionic\" ]; then\n  echo -e \"ERROR: Your operating system is not supported by this installation script\"\n  exit\nfi\n\n# Make sure the system is up-to-date\nsudo apt update && sudo apt -y upgrade &&\n\n# Install general tools\nsudo apt install -y build-essential curl git &&\n\n# Install Python and Node\ncurl -sL https://deb.nodesource.com/setup_10.x | sudo bash -\nsudo apt install -y python3 python3-dev python3-venv nodejs &&\n\n# Install the database\nsudo apt install -y postgresql-10 libpq-dev postgresql-server-dev-10 postgresql-10-postgis-2.4 postgresql-10-postgis-scripts &&\n\n## Obtain the tasking manager\ngit clone https://github.com/hotosm/tasking-manager.git &&\n\n## Prepare the tasking manager\ncd tasking-manager/ &&\npython3 -m venv ./venv &&\n. ./venv/bin/activate &&\npip install --upgrade pip &&\npip install -r requirements.txt &&\necho fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p &&\n\n# Set up configuration\n# Sets db endpoint to localhost.\nif ! test -f tasking-manager.env\n\tthen\n    cp example.env tasking-manager.env\nfi\n. ./tasking-manager.env &&\nsed -i '/POSTGRES_ENDPOINT/s/^# //g' tasking-manager.env &&\n\n# Set up data base\nif ! sudo -u postgres psql -c \"SELECT u.usename FROM pg_catalog.pg_user u;\" | grep -w -q $POSTGRES_USER\n\tthen\n\t\tsudo -u postgres psql -c \"CREATE USER $POSTGRES_USER WITH PASSWORD '$POSTGRES_PASSWORD';\"\nfi\nif ! sudo -u postgres psql -c \"SELECT datname FROM pg_database WHERE datistemplate = false;\" | grep -w -q $POSTGRES_DB\n\tthen\n    sudo -u postgres createdb -T template0 $POSTGRES_DB -E UTF8 -O $POSTGRES_USER &&\n    sudo -u postgres psql -d $POSTGRES_DB -c \"CREATE EXTENSION postgis;\"\nfi\n\n\n# Populate database\ncd tests/database/ &&\nsudo -u postgres psql -d $POSTGRES_DB -c \"\\i tasking-manager.sql\" &&\nfor tbl in `sudo -u postgres psql -qAt -c \"select tablename from pg_tables where schemaname = 'public';\" $POSTGRES_DB`;\ndo  sudo -u postgres psql -c \"alter table \\\"$tbl\\\" owner to $POSTGRES_USER\" $POSTGRES_DB ; done &&\nfor tbl in `sudo -u postgres psql -qAt -c \"select tablename from pg_tables where schemaname = 'topology';\" $POSTGRES_DB`;\ndo  sudo -u postgres psql -c \"alter table \\\"$tbl\\\" owner to $POSTGRES_USER\" $POSTGRES_DB ; done &&\ncd ../../ &&\n\n# Upgrade database\n./venv/bin/python3 manage.py db upgrade &&\n\n# Assamble the tasking manager interface\ncd frontend/ &&\nnpm install &&\nnpm run build &&\ncd ../ &&\n\n## Please edit the tasking-manager.env as indicated in the README.md ##\n\n# Start the tasking manager\n./venv/bin/python manage.py runserver -d\n", "num_lines": 82}
{"repo_name": "PathPicker", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nPTH=\"$(pwd)\"\nVERSION=\"$(python3 \"$PTH/../src/version.py\")\"\nDATETIME=$(date '+%a, %d %b %Y %H:%M:%S %z')\n\necho \"Building fpp version $VERSION at $DATETIME\"\nmkdir -p \"$PTH/usr/bin\" &&\n  mkdir -p \"$PTH/usr/share/pathpicker/src/\"\n\nsed s#__version__#\"$VERSION\"# < \"$PTH/DEBIAN/control\" > \"$PTH/DEBIAN/control.modif\"\nmv \"$PTH/DEBIAN/control.modif\" \"$PTH/DEBIAN/control\"\n\necho \"====================\"\necho \"Control file is:\"\necho \"====================\"\ncat \"$PTH/DEBIAN/control\"\necho \"====================\"\n\ncp -R \"$PTH/../src\" \"$PTH/usr/share/pathpicker\" &&\n  cp \"$PTH/../fpp\" \"$PTH/usr/share/pathpicker/fpp\" &&\n  cd \"$PTH/usr/bin/\"\n\necho \"Creating symlink...\"\nln -f -s ../share/pathpicker/fpp fpp\nsed s#__version__#\"$VERSION\"# < \"$PTH/usr/share/doc/pathpicker/changelog\" > \"$PTH/usr/share/doc/pathpicker/changelog.modif\"\nsed s#__date_timestamp__#\"$DATETIME\"# < \"$PTH/usr/share/doc/pathpicker/changelog.modif\" > \"$PTH/usr/share/doc/pathpicker/changelog\"\n\necho \"====================\"\necho \"Changelog is:\"\necho \"====================\"\ncat  \"$PTH/usr/share/doc/pathpicker/changelog\"\necho \"====================\"\n\necho \"Gziping...\"\ngzip -9 \"$PTH/usr/share/doc/pathpicker/changelog\" &&\n  rm \"$PTH/usr/share/doc/pathpicker/changelog.modif\"\n\necho \"Setting permissions...\"\ncd \"$PTH\"\nfind . -type d -exec chmod 755 {} \\;\nfind . -type f -exec chmod 644 {} \\;\n\necho \"Building package...\"\nrm \"$PTH/package.sh\"\nchmod 755 usr/share/pathpicker/fpp\nfakeroot -- sh -c \"chown -R root:root * && dpkg --build ./ ../pathpicker_${VERSION}_all.deb ;\"\necho \"Restoring template files...\"\ncd -\ngit checkout HEAD -- \"$PTH/DEBIAN/control\" \"$PTH/usr/share/doc/pathpicker/changelog\" \"$PTH/package.sh\"\nchmod 777 \"$PTH/package.sh\"\n\necho 'Done! Check out fpp.deb'\n", "num_lines": 57}
{"repo_name": "PathPicker", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\nVERSION=\"$(python3 ./src/version.py)\"\nDEST=\"./dist/fpp.$VERSION.tar.gz\"\nmkdir -p ./dist/\ntar -czf $DEST src/*.py fpp\n\nsed -i '' -e \"s#url .*#url \\\"https://github.com/facebook/PathPicker/releases/download/$VERSION/fpp.$VERSION.tar.gz\\\"#g\" ./fpp.rb\nHASH=$(cat $DEST | shasum -a 256 | cut -d \" \" -f 1)\nsed -i '' -e \"s#^  sha256 .*#  sha256 \\\"$HASH\\\"#g\" ./fpp.rb\n\necho \"Recipe updated with hash from $DEST\"\n", "num_lines": 16}
{"repo_name": "PathPicker", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\ncommand -v a2x >/dev/null 2>&1 || { echo >&2 \"I require a2x provided by asciidoc, but it's not installed.  Aborting.\"; exit 1; }\n(cd src && python3 -m pathpicker.usage_strings > manpage.adoc)\na2x --format manpage \"src/manpage.adoc\" --destination-dir debian/usr/share/man/man1/\n", "num_lines": 9}
{"repo_name": "PathPicker", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# get the directory of this script so we can execute the related python\n# http://stackoverflow.com/a/246128/212110\nSOURCE=$0\n# resolve $SOURCE until the file is no longer a symlink\nwhile [ -h \"$SOURCE\" ]; do\n  BASEDIR=\"$(cd -P \"$(dirname \"$SOURCE\")\" && pwd)\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  # if $SOURCE was a relative symlink, we need to resolve it relative to\n  # the path where the symlink file was located\n  [[ $SOURCE != /* ]] && SOURCE=\"$BASEDIR/$SOURCE\"\ndone\nBASEDIR=\"$(cd -P \"$(dirname \"$SOURCE\")\" && pwd)\"\nREPO_ROOT=\"$BASEDIR/..\"\n\ncd \"$REPO_ROOT\"\n\npoetry install\npoetry run mypy src\npoetry run flake8 src\npoetry run pylint src\npoetry run pytest src/tests\npoetry run vulture src\n", "num_lines": 31}
{"repo_name": "proxygen", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -xeo pipefail\n\nTOOLCHAIN_DIR=/opt/rh/devtoolset-8/root/usr/bin\nif [[ -d \"$TOOLCHAIN_DIR\" ]]; then\n    PATH=\"$TOOLCHAIN_DIR:$PATH\"\nfi\n\nPROJECT_DIR=$(dirname \"$0\")\nGETDEPS_PATHS=(\n    \"$PROJECT_DIR/build/fbcode_builder/getdeps.py\"\n    \"$PROJECT_DIR/../../opensource/fbcode_builder/getdeps.py\"\n)\n\nROOT_DIR=$(pwd)\nSTAGE=${ROOT_DIR}/_build/\nmkdir -p \"$STAGE\"\n\nfor getdeps in \"${GETDEPS_PATHS[@]}\"; do\n    if [[ -x \"$getdeps\" ]]; then\n        \"$getdeps\" build proxygen --current-project proxygen \"$@\" --install-prefix=${STAGE}\n        exit 0\n    fi\ndone\n\necho \"Could not find getdeps.py!?\" >&2\nexit 1\n", "num_lines": 34}
{"repo_name": "proxygen", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n## Run this script to build proxygen and run the tests. If you want to\n## install proxygen to use in another C++ project on this machine, run\n## the sibling file `reinstall.sh`.\n\n# Obtain the base directory this script resides in.\nBASE_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\n# Useful constants\nCOLOR_RED=\"\\033[0;31m\"\nCOLOR_GREEN=\"\\033[0;32m\"\nCOLOR_OFF=\"\\033[0m\"\n\nfunction detect_platform() {\n  unameOut=\"$(uname -s)\"\n  case \"${unameOut}\" in\n      Linux*)     PLATFORM=Linux;;\n      Darwin*)    PLATFORM=Mac;;\n      *)          PLATFORM=\"UNKNOWN:${unameOut}\"\n  esac\n  echo -e \"${COLOR_GREEN}Detected platform: $PLATFORM ${COLOR_OFF}\"\n}\n\nfunction install_dependencies_linux() {\n  sudo apt-get install -yq \\\n    git \\\n    cmake \\\n    m4 \\\n    g++ \\\n    flex \\\n    bison \\\n    libgflags-dev \\\n    libgoogle-glog-dev \\\n    libkrb5-dev \\\n    libsasl2-dev \\\n    libnuma-dev \\\n    pkg-config \\\n    libssl-dev \\\n    libcap-dev \\\n    gperf \\\n    libevent-dev \\\n    libtool \\\n    libboost-all-dev \\\n    libjemalloc-dev \\\n    libsnappy-dev \\\n    wget \\\n    unzip \\\n    libiberty-dev \\\n    liblz4-dev \\\n    liblzma-dev \\\n    make \\\n    zlib1g-dev \\\n    binutils-dev \\\n    libsodium-dev \\\n    libdouble-conversion-dev\n}\n\nfunction install_dependencies_mac() {\n  # install the default dependencies from homebrew\n  brew install -f            \\\n    cmake                    \\\n    m4                       \\\n    boost                    \\\n    double-conversion        \\\n    gflags                   \\\n    glog                     \\\n    gperf                    \\\n    libevent                 \\\n    lz4                      \\\n    snappy                   \\\n    xz                       \\\n    openssl                  \\\n    libsodium\n\n  brew link                 \\\n    cmake                   \\\n    boost                   \\\n    double-conversion       \\\n    gflags                  \\\n    glog                    \\\n    gperf                   \\\n    libevent                \\\n    lz4                     \\\n    snappy                  \\\n    openssl                 \\\n    xz                      \\\n    libsodium\n}\n\nfunction install_dependencies() {\n  echo -e \"${COLOR_GREEN}[ INFO ] install dependencies ${COLOR_OFF}\"\n  if [ \"$PLATFORM\" = \"Linux\" ]; then\n    install_dependencies_linux\n  elif [ \"$PLATFORM\" = \"Mac\" ]; then\n    install_dependencies_mac\n  else\n    echo -e \"${COLOR_RED}[ ERROR ] Unknown platform: $PLATFORM ${COLOR_OFF}\"\n    exit 1\n  fi\n}\n\nfunction synch_dependency_to_commit() {\n  # Utility function to synch a dependency to a specific commit. Takes two arguments:\n  #   - $1: folder of the dependency's git repository\n  #   - $2: path to the text file containing the desired commit hash\n  if [ \"$FETCH_DEPENDENCIES\" = false ] ; then\n    return\n  fi\n  DEP_REV=$(sed 's/Subproject commit //' \"$2\")\n  pushd \"$1\"\n  git fetch\n  # Disable git warning about detached head when checking out a specific commit.\n  git -c advice.detachedHead=false checkout \"$DEP_REV\"\n  popd\n}\n\nfunction setup_fmt() {\n  FMT_DIR=$DEPS_DIR/fmt\n  FMT_BUILD_DIR=$DEPS_DIR/fmt/build/\n  FMT_TAG=$(grep \"subdir = \" ../../build/fbcode_builder/manifests/fmt | cut -d \"-\" -f 2)\n  if [ ! -d \"$FMT_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning fmt repo ${COLOR_OFF}\"\n    git clone https://github.com/fmtlib/fmt.git  \"$FMT_DIR\"\n  fi\n  cd \"$FMT_DIR\"\n  git fetch --tags\n  git checkout \"${FMT_TAG}\"\n  echo -e \"${COLOR_GREEN}Building fmt ${COLOR_OFF}\"\n  mkdir -p \"$FMT_BUILD_DIR\"\n  cd \"$FMT_BUILD_DIR\" || exit\n\n  cmake                                           \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"               \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"            \\\n    -DCMAKE_BUILD_TYPE=RelWithDebInfo             \\\n    \"$MAYBE_OVERRIDE_CXX_FLAGS\"                   \\\n    -DFMT_DOC=OFF                                 \\\n    -DFMT_TEST=OFF                                \\\n    ..\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}fmt is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_googletest() {\n  GTEST_DIR=$DEPS_DIR/googletest\n  GTEST_BUILD_DIR=$DEPS_DIR/googletest/build/\n  GTEST_TAG=$(grep \"subdir = \" ../../build/fbcode_builder/manifests/googletest | cut -d \"-\" -f 2,3)\n  if [ ! -d \"$GTEST_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning googletest repo ${COLOR_OFF}\"\n    git clone https://github.com/google/googletest.git  \"$GTEST_DIR\"\n  fi\n  cd \"$GTEST_DIR\"\n  git fetch --tags\n  git checkout \"${GTEST_TAG}\"\n  echo -e \"${COLOR_GREEN}Building googletest ${COLOR_OFF}\"\n  mkdir -p \"$GTEST_BUILD_DIR\"\n  cd \"$GTEST_BUILD_DIR\" || exit\n\n  cmake                                           \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"               \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"            \\\n    -DCMAKE_BUILD_TYPE=RelWithDebInfo             \\\n    ..\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}googletest is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_zstd() {\n  ZSTD_DIR=$DEPS_DIR/zstd\n  ZSTD_BUILD_DIR=$DEPS_DIR/zstd/build/cmake/builddir\n  ZSTD_INSTALL_DIR=$DEPS_DIR\n  ZSTD_TAG=$(grep \"subdir = \" ../../build/fbcode_builder/manifests/zstd | cut -d \"-\" -f 2 | cut -d \"/\" -f 1)\n  if [ ! -d \"$ZSTD_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning zstd repo ${COLOR_OFF}\"\n    git clone https://github.com/facebook/zstd.git \"$ZSTD_DIR\"\n  fi\n  cd \"$ZSTD_DIR\"\n  git fetch --tags\n  git checkout \"v${ZSTD_TAG}\"\n  echo -e \"${COLOR_GREEN}Building Zstd ${COLOR_OFF}\"\n  mkdir -p \"$ZSTD_BUILD_DIR\"\n  cd \"$ZSTD_BUILD_DIR\" || exit\n  cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo           \\\n    -DBUILD_TESTS=OFF                               \\\n    -DCMAKE_PREFIX_PATH=\"$ZSTD_INSTALL_DIR\"         \\\n    -DCMAKE_INSTALL_PREFIX=\"$ZSTD_INSTALL_DIR\"      \\\n    ${CMAKE_EXTRA_ARGS[@]+\"${CMAKE_EXTRA_ARGS[@]}\"} \\\n    ..\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}Zstd is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_folly() {\n  FOLLY_DIR=$DEPS_DIR/folly\n  FOLLY_BUILD_DIR=$DEPS_DIR/folly/build/\n\n  if [ ! -d \"$FOLLY_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning folly repo ${COLOR_OFF}\"\n    git clone https://github.com/facebook/folly.git \"$FOLLY_DIR\"\n  fi\n  synch_dependency_to_commit \"$FOLLY_DIR\" \"$BASE_DIR\"/../build/deps/github_hashes/facebook/folly-rev.txt\n  if [ \"$PLATFORM\" = \"Mac\" ]; then\n    # Homebrew installs OpenSSL in a non-default location on MacOS >= Mojave\n    # 10.14 because MacOS has its own SSL implementation.  If we find the\n    # typical Homebrew OpenSSL dir, load OPENSSL_ROOT_DIR so that cmake\n    # will find the Homebrew version.\n    dir=/usr/local/opt/openssl\n    if [ -d $dir ]; then\n        export OPENSSL_ROOT_DIR=$dir\n    fi\n  fi\n  echo -e \"${COLOR_GREEN}Building Folly ${COLOR_OFF}\"\n  mkdir -p \"$FOLLY_BUILD_DIR\"\n  cd \"$FOLLY_BUILD_DIR\" || exit\n  MAYBE_DISABLE_JEMALLOC=\"\"\n  if [ \"$NO_JEMALLOC\" == true ] ; then\n    MAYBE_DISABLE_JEMALLOC=\"-DFOLLY_USE_JEMALLOC=0\"\n  fi\n\n  MAYBE_USE_STATIC_DEPS=\"\"\n  MAYBE_USE_STATIC_BOOST=\"\"\n  MAYBE_BUILD_SHARED_LIBS=\"\"\n  if [ \"$BUILD_FOR_FUZZING\" == true ] ; then\n    MAYBE_USE_STATIC_DEPS=\"-DUSE_STATIC_DEPS_ON_UNIX=ON\"\n    MAYBE_USE_STATIC_BOOST=\"-DBOOST_LINK_STATIC=ON\"\n    MAYBE_BUILD_SHARED_LIBS=\"-DBUILD_SHARED_LIBS=OFF\"\n  fi\n\n  cmake                                           \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"               \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"            \\\n    -DCMAKE_BUILD_TYPE=RelWithDebInfo             \\\n    -DBUILD_TESTS=OFF                             \\\n    \"$MAYBE_USE_STATIC_DEPS\"                      \\\n    \"$MAYBE_USE_STATIC_BOOST\"                     \\\n    \"$MAYBE_BUILD_SHARED_LIBS\"                    \\\n    \"$MAYBE_OVERRIDE_CXX_FLAGS\"                   \\\n    $MAYBE_DISABLE_JEMALLOC                       \\\n    ..\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}Folly is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_fizz() {\n  FIZZ_DIR=$DEPS_DIR/fizz\n  FIZZ_BUILD_DIR=$DEPS_DIR/fizz/build/\n  if [ ! -d \"$FIZZ_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning fizz repo ${COLOR_OFF}\"\n    git clone https://github.com/facebookincubator/fizz \"$FIZZ_DIR\"\n  fi\n  synch_dependency_to_commit \"$FIZZ_DIR\" \"$BASE_DIR\"/../build/deps/github_hashes/facebookincubator/fizz-rev.txt\n  echo -e \"${COLOR_GREEN}Building Fizz ${COLOR_OFF}\"\n  mkdir -p \"$FIZZ_BUILD_DIR\"\n  cd \"$FIZZ_BUILD_DIR\" || exit\n\n  MAYBE_USE_STATIC_DEPS=\"\"\n  MAYBE_USE_SODIUM_STATIC_LIBS=\"\"\n  MAYBE_BUILD_SHARED_LIBS=\"\"\n  if [ \"$BUILD_FOR_FUZZING\" == true ] ; then\n    MAYBE_USE_STATIC_DEPS=\"-DUSE_STATIC_DEPS_ON_UNIX=ON\"\n    MAYBE_USE_SODIUM_STATIC_LIBS=\"-Dsodium_USE_STATIC_LIBS=ON\"\n    MAYBE_BUILD_SHARED_LIBS=\"-DBUILD_SHARED_LIBS=OFF\"\n  fi\n\n  cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo       \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"             \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"          \\\n    -DBUILD_TESTS=OFF                           \\\n    \"$MAYBE_USE_STATIC_DEPS\"                    \\\n    \"$MAYBE_BUILD_SHARED_LIBS\"                  \\\n    \"$MAYBE_OVERRIDE_CXX_FLAGS\"                 \\\n    \"$MAYBE_USE_SODIUM_STATIC_LIBS\"             \\\n    \"$FIZZ_DIR/fizz\"\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}Fizz is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_wangle() {\n  WANGLE_DIR=$DEPS_DIR/wangle\n  WANGLE_BUILD_DIR=$DEPS_DIR/wangle/build/\n  if [ ! -d \"$WANGLE_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning wangle repo ${COLOR_OFF}\"\n    git clone https://github.com/facebook/wangle \"$WANGLE_DIR\"\n  fi\n  synch_dependency_to_commit \"$WANGLE_DIR\" \"$BASE_DIR\"/../build/deps/github_hashes/facebook/wangle-rev.txt\n  echo -e \"${COLOR_GREEN}Building Wangle ${COLOR_OFF}\"\n  mkdir -p \"$WANGLE_BUILD_DIR\"\n  cd \"$WANGLE_BUILD_DIR\" || exit\n\n  MAYBE_USE_STATIC_DEPS=\"\"\n  MAYBE_BUILD_SHARED_LIBS=\"\"\n  if [ \"$BUILD_FOR_FUZZING\" == true ] ; then\n    MAYBE_USE_STATIC_DEPS=\"-DUSE_STATIC_DEPS_ON_UNIX=ON\"\n    MAYBE_BUILD_SHARED_LIBS=\"-DBUILD_SHARED_LIBS=OFF\"\n  fi\n\n  cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo       \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"             \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"          \\\n    -DBUILD_TESTS=OFF                           \\\n    \"$MAYBE_USE_STATIC_DEPS\"                    \\\n    \"$MAYBE_BUILD_SHARED_LIBS\"                  \\\n    \"$MAYBE_OVERRIDE_CXX_FLAGS\"                 \\\n    \"$WANGLE_DIR/wangle\"\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}Wangle is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\nfunction setup_mvfst() {\n  MVFST_DIR=$DEPS_DIR/mvfst\n  MVFST_BUILD_DIR=$DEPS_DIR/mvfst/build/\n  if [ ! -d \"$MVFST_DIR\" ] ; then\n    echo -e \"${COLOR_GREEN}[ INFO ] Cloning mvfst repo ${COLOR_OFF}\"\n    git clone https://github.com/facebookincubator/mvfst \"$MVFST_DIR\"\n  fi\n  synch_dependency_to_commit \"$MVFST_DIR\" \"$BASE_DIR\"/../build/deps/github_hashes/facebookincubator/mvfst-rev.txt\n  echo -e \"${COLOR_GREEN}Building Mvfst ${COLOR_OFF}\"\n  mkdir -p \"$MVFST_BUILD_DIR\"\n  cd \"$MVFST_BUILD_DIR\" || exit\n\n  MAYBE_USE_STATIC_DEPS=\"\"\n  MAYBE_BUILD_SHARED_LIBS=\"\"\n  if [ \"$BUILD_FOR_FUZZING\" == true ] ; then\n    MAYBE_USE_STATIC_DEPS=\"-DUSE_STATIC_DEPS_ON_UNIX=ON\"\n    MAYBE_BUILD_SHARED_LIBS=\"-DBUILD_SHARED_LIBS=OFF\"\n  fi\n\n\n  cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo       \\\n    -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"             \\\n    -DCMAKE_INSTALL_PREFIX=\"$DEPS_DIR\"          \\\n    -DBUILD_TESTS=OFF                           \\\n    \"$MAYBE_USE_STATIC_DEPS\"                    \\\n    \"$MAYBE_BUILD_SHARED_LIBS\"                  \\\n    \"$MAYBE_OVERRIDE_CXX_FLAGS\"                 \\\n    \"$MVFST_DIR\"\n  make -j \"$JOBS\"\n  make install\n  echo -e \"${COLOR_GREEN}Mvfst is installed ${COLOR_OFF}\"\n  cd \"$BWD\" || exit\n}\n\n# Parse args\nJOBS=8\nWITH_QUIC=false\nINSTALL_DEPENDENCIES=true\nFETCH_DEPENDENCIES=true\nPREFIX=\"\"\nCOMPILER_FLAGS=\"\"\nUSAGE=\"./build.sh [-j num_jobs] [-q|--with-quic] [-m|--no-jemalloc] [--no-install-dependencies] [-p|--prefix] [-x|--compiler-flags] [--no-fetch-dependencies]\"\nwhile [ \"$1\" != \"\" ]; do\n  case $1 in\n    -j | --jobs ) shift\n                  JOBS=$1\n                  ;;\n    -q | --with-quic )\n                  WITH_QUIC=true\n                  ;;\n    -m | --no-jemalloc )\n                  NO_JEMALLOC=true\n                  ;;\n    --no-install-dependencies )\n                  INSTALL_DEPENDENCIES=false\n          ;;\n    --no-fetch-dependencies )\n                  FETCH_DEPENDENCIES=false\n          ;;\n    --build-for-fuzzing )\n                  BUILD_FOR_FUZZING=true\n      ;;\n    -t | --no-tests )\n                  NO_BUILD_TESTS=true\n      ;;\n    -p | --prefix )\n                  shift\n                  PREFIX=$1\n      ;;\n    -x | --compiler-flags )\n                  shift\n                  COMPILER_FLAGS=$1\n      ;;\n    * )           echo $USAGE\n                  exit 1\nesac\nshift\ndone\n\ndetect_platform\n\nif [ \"$INSTALL_DEPENDENCIES\" == true ] ; then\n  install_dependencies\nfi\n\nMAYBE_OVERRIDE_CXX_FLAGS=\"\"\nif [ -n \"$COMPILER_FLAGS\" ] ; then\n  MAYBE_OVERRIDE_CXX_FLAGS=\"-DCMAKE_CXX_FLAGS=$COMPILER_FLAGS\"\nfi\n\nBUILD_DIR=_build\nmkdir -p $BUILD_DIR\n\nset -e nounset\ntrap 'cd $BASE_DIR' EXIT\ncd $BUILD_DIR || exit\nBWD=$(pwd)\nDEPS_DIR=$BWD/deps\nmkdir -p \"$DEPS_DIR\"\n\n# Must execute from the directory containing this script\ncd \"$(dirname \"$0\")\"\n\nsetup_fmt\nsetup_googletest\nsetup_zstd\nsetup_folly\nsetup_fizz\nsetup_wangle\nMAYBE_BUILD_QUIC=\"\"\nif [ \"$WITH_QUIC\" == true ] ; then\n  setup_mvfst\n  MAYBE_BUILD_QUIC=\"-DBUILD_QUIC=On\"\nfi\n\nMAYBE_BUILD_FUZZERS=\"\"\nMAYBE_USE_STATIC_DEPS=\"\"\nMAYBE_LIB_FUZZING_ENGINE=\"\"\nMAYBE_BUILD_SHARED_LIBS=\"\"\nMAYBE_BUILD_TESTS=\"-DBUILD_TESTS=ON\"\nif [ \"$NO_BUILD_TESTS\" == true ] ; then\n  MAYBE_BUILD_TESTS=\"-DBUILD_TESTS=OFF\"\nfi\nif [ \"$BUILD_FOR_FUZZING\" == true ] ; then\n  MAYBE_BUILD_FUZZERS=\"-DBUILD_FUZZERS=ON\"\n  MAYBE_USE_STATIC_DEPS=\"-DUSE_STATIC_DEPS_ON_UNIX=ON\"\n  MAYBE_LIB_FUZZING_ENGINE=\"-DLIB_FUZZING_ENGINE='$LIB_FUZZING_ENGINE'\"\n  MAYBE_BUILD_SHARED_LIBS=\"-DBUILD_SHARED_LIBS=OFF\"\nfi\n\nif [ -z \"$PREFIX\" ]; then\n  PREFIX=$BWD\nfi\n\n# Build proxygen with cmake\ncd \"$BWD\" || exit\ncmake                                     \\\n  -DCMAKE_BUILD_TYPE=RelWithDebInfo       \\\n  -DCMAKE_PREFIX_PATH=\"$DEPS_DIR\"         \\\n  -DCMAKE_INSTALL_PREFIX=\"$PREFIX\"        \\\n  \"$MAYBE_BUILD_QUIC\"                     \\\n  \"$MAYBE_BUILD_TESTS\"                    \\\n  \"$MAYBE_BUILD_FUZZERS\"                  \\\n  \"$MAYBE_BUILD_SHARED_LIBS\"              \\\n  \"$MAYBE_OVERRIDE_CXX_FLAGS\"             \\\n  \"$MAYBE_USE_STATIC_DEPS\"                \\\n  \"$MAYBE_LIB_FUZZING_ENGINE\"             \\\n  ../..\n\nmake -j \"$JOBS\"\necho -e \"${COLOR_GREEN}Proxygen build is complete. To run unit test: \\\n  cd _build/ && make test ${COLOR_OFF}\"\n", "num_lines": 479}
{"repo_name": "proxygen", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n## Run this script to (re)install proxygen and its dependencies (fbthrift\n## and folly). You must first compile all the dependencies before running this. This\n## Usually this is done by first running `deps.sh`.\n\nset -e\nstart_dir=$(pwd)\ntrap 'cd $start_dir' EXIT\n\n# Must execute from the directory containing this script\ncd \"$(dirname \"$0\")\"\n\ncd _build\n# Uninstall is expected to fail the first time\nmake uninstall || true\nmake install\n\n# Make sure the libraries are available\n# Linux only\n/sbin/ldconfig || true\n", "num_lines": 27}
{"repo_name": "proxygen", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# Setup and validate arguments\n\nif [ \"x$1\" != \"x\" ]; then\n  ENUM_FILE_LIST=\"$1\"\nfi\nif [ \"x$2\" != \"x\" ];then\n  FBCODE_DIR=\"$2\"\nfi\nif [ \"x$3\" != \"x\" ]; then\n  OUTPUT_DIR=\"$3\"\nfi\nif [ \"x$4\" != \"x\" ]; then\n  GPERF=\"$4\"\nfi\n\n# The `awk` scripts aren't nearly as hairy as it seems. The only real trick is\n# the first line. We're processing two files -- the result of a `cat` pipeline\n# above, plus a template. The \"NR == FNR\" compares the current file's\n# line number with the total number of lines we've processed -- i.e., that test\n# means \"am I in the first file?\" So we suck those lines aside. Then we process\n# the second file, replacing \"%%%%%\" with some munging of the lines we sucked\n# aside from the `cat` pipeline. They are written in awk since it isn't really\n# worth the build system BS of calling out to Python (which is unfortunately\n# particularly annoying in Facebook's internal build system) and more portable\n# (and less hairy honestly) than the massive `sed` pipeline which used to be\n# here. And it really isn't that bad, this is the sort of thing `awk` was\n# designed for.\n\nAWK_HEADER_SCRIPT='\n  NR == FNR {\n    n[FNR] = $1;\n    max = FNR;\n    next\n  }\n  $1 == \"%%%%%\" {\n    for (i in n) {\n      h = n[i];\n      gsub(\"-\", \"_\", h);\n      gsub(\":\", \"COLON_\", h);\n      print \"  HTTP_HEADER_\" toupper(h) \" = \" i+1 \",\"\n    };\n    next\n  }\n  $1 == \"$$$$$\" {\n    print \"  constexpr static uint64_t num_codes = \" max+2 \";\";\n    next\n  }\n  {\n    gsub(\"%%name%%\", \"HTTPCommonHeaders\");\n    gsub(\"%%name_enum%%\", \"HTTPHeaderCode\");\n    gsub(\"%%enum_prefix%%\", \"HTTP_HEADER\");\n    gsub(\"%%table_type_name%%\", \"HTTPCommonHeaderTableType\");\n    print\n  }\n'\n\nAWK_SOURCE_SCRIPT='\n  NR == FNR {\n    n[FNR] = $1;\n    next\n  }\n  $1 == \"%%%%%\" {\n    print \"%%\";\n    for (i in n) {\n      h = n[i];\n      gsub(\"-\", \"_\", h);\n      gsub(\":\", \"COLON_\", h);\n      print n[i] \", HTTP_HEADER_\" toupper(h)\n    };\n    print \"%%\";\n    next\n  }\n  {\n    gsub(\"%%name%%\", \"HTTPCommonHeaders\");\n    gsub(\"%%name_internal%%\", \"HTTPCommonHeadersInternal\");\n    gsub(\"%%name_container%%\", \"HTTPCommonHeaderName\");\n    gsub(\"%%name_enum%%\", \"HTTPHeaderCode\");\n    gsub(\"%%header%%\", \"proxygen/lib/http/HTTPCommonHeaders.h\");\n    gsub(\"%%enum_other%%\", \"HTTP_HEADER_OTHER\");\n    gsub(\"%%table_type_name%%\", \"HTTPCommonHeaderTableType\");\n    print\n  }\n'\n\n# Load up the utility method for generating our desired perfect hash table\n# shellcheck source=/dev/null\n. \"${FBCODE_DIR?}/proxygen/lib/utils/gen_perfect_hash_table.sh\"\n\ngenerate_perfect_hash_table \\\n  \"${ENUM_FILE_LIST}\" \\\n  \"${FBCODE_DIR}/proxygen/lib/utils/perfect_hash_table_template.h\" \\\n  \"${AWK_HEADER_SCRIPT}\" \\\n  \"${OUTPUT_DIR}/HTTPCommonHeaders.h\" \\\n  \"${FBCODE_DIR}/proxygen/lib/utils/perfect_hash_table_template.cpp.gperf\" \\\n  \"${AWK_SOURCE_SCRIPT}\" \\\n  \"${OUTPUT_DIR?}/HTTPCommonHeaders.cpp\" \\\n  \"${GPERF}\"\n", "num_lines": 107}
{"repo_name": "proxygen", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Utility method for generating the header and source code for a generic perfect\n# hash table data structure by leveraging gperf, input template header and gperf\n# source files, and input word list files that respresent the enum fields.\nfunction generate_perfect_hash_table {\n\n  # $1 is a space separated list of files that store words that will correspond\n  #    to output enum fields.\n  # $2 is the path to the input template header file.\n  # $3 is the path to the 'awk' script that will output format the template\n  #    header file.\n  # $4 is the desired output path of the generated header file.\n  # $5 is the path to the input template gperf file.\n  # $6 is the path to the 'awk' script that will format the template gperf file\n  #    prior to it being passed to the gperf binary.\n  # $7 is the desired output path of the generated source file.\n  # $8 is the optional path to the gperf binary to use.\n\n  # The inputs to 'cat' below are not quoted as they are space separated lists\n  # of strings (files); 'cat' will concatenate them (if applicable) and pipe the\n  # combined output onwards to 'awk'.\n\n  # Generate output header file.\n  LC_ALL=C sort -u ${1?} | awk \"${3?}\" - \"${2?}\" > \"${4?}\"\n\n  # Generate output source file.\n  # We also sub out the default 'FALLTHROUGH' comment statements as modern\n  # compilers will raise warnings unless the fallthrough is explicit.\n  LC_ALL=C sort -u ${1?} | awk \"${6?}\" - \"${5?}\" | \\\n  ${8:-gperf} -m5 -D --output-file=\"${7?}\"\n  perl -p -i -e \"s/\\/\\*FALLTHROUGH\\*\\//FOLLY_FALLTHROUGH;/g\" \"${7?}\"\n\n  # Here we delete one of the comment lines gperf adds to the top of the file.\n  # i.e. /* Command-line: .../gperf -m5 --output-file=...  */\n  # The reason this line is removed is the '...'s are actually expanded to\n  # absolute paths on the build machine which prevents buck's cache from being\n  # used effectively.\n  # Prefer perl to sed so that it works on both Mac and Linux.\n  perl -n -i -e \"print unless m /\\\\/* Command-line: /\" \"${7?}\"\n}\n", "num_lines": 47}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset +e\npython3 ../../tools/pysa_integration_tests/run.py \\\n    --skip-model-verification \\\n    --run-from-source\n\nexit_code=$?\n\nif [[ \"$exit_code\" != \"0\" ]]; then\n    echo \"--- raw_results.json --\"\n    cat raw_results.json\n    echo \"---\"\nfi\n\nexit $exit_code\n", "num_lines": 21}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Source this file to run it:\n# . ./setup.sh\n\npip install -r requirements.txt\nrm ../../.pyre_configuration\necho '{\n    \"source_directories\": [\".\"],\n    \"search_path\": [\n        \"../../stubs/integration_test/fixture_stubs\",\n        {\"site-package\": \"flask\"},\n        {\"site-package\": \"werkzeug\"},\n        {\"site-package\": \"jsonpickle\"}\n    ],\n    \"taint_models_path\": \"../../stubs\"\n}' > ./.pyre_configuration\n", "num_lines": 22}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# Compatibility settings with MacOS.\nif [[ \"${MACHTYPE}\" = *apple* ]]; then\n  READLINK=greadlink\nelse\n  READLINK=readlink\nfi\n\nSCRIPTS_DIRECTORY=\"$(dirname \"$(\"${READLINK}\" -f \"$0\")\")\"\n\n# Gather build information.\nif [[ \"${1}\" == 'development' ]]; then\n  # Use a less precise date to avoid rebuilding the binary at every\n  # 'make' invocation during development.\n  BUILD_INFO=\"$(uname -s -m) @ $(date \"+%a %b %d %Y\") (development build)\"\n  shift\nelse\n  BUILD_INFO=\"$(uname -s -m) @ $(date)\"\nfi\necho \"Build info: ${BUILD_INFO}\"\n\n# Buck builds pass a `--out-dir <DIR>` argument indicating where to write\n# artifacts.\nwhile [ $# -gt 0 ]; do\n  if [[ \"$1\" =~ ^--out-dir=(.*)$ ]]; then\n    _OUT_DIR=\"${BASH_REMATCH[1]}\"\n  else\n    echo \"Unexpected arg: $1\" && exit 1\n  fi\n  shift\ndone\n\n# Gather version information.\nVERSION=\"\"\nif HG_VERSION=\"$(hg log -r . -T '{node}')\"; then\n  VERSION=\"${HG_VERSION}\"\n  echo \"HG revision: ${VERSION}\"\nelif GIT_VERSION=\"$(git rev-parse HEAD)\"; then\n  VERSION=\"${GIT_VERSION}\"\n  echo \"Git commit: ${VERSION}\"\nelse\n  echo 'Cannot determine version information'\n  exit 1\nfi\n\nOUT_DIR=\"${_OUT_DIR:-\"$SCRIPTS_DIRECTORY\"/../source}\"\ncat > \"$OUT_DIR\"/version.ml <<EOF\nopen Core\n\nlet build_info () =\n  \"${BUILD_INFO}\"\n\nlet version () =\n  \"${VERSION}\"\n\nlet log_version_banner () =\n  Log.info \"Running as pid: %d\" (Pid.to_int (Core_unix.getpid ()));\n  Log.info \"Version: %s\" (version ());\n  Log.info \"Build info: %s\" (build_info ())\nEOF\n\n# Note: [Embedded Build Info]\n# ===========================\n#\n# Buck executables automatically link build info that defines the symbols\n# `BuildInfo_kRevision` and `BuildInfo_kRevisionCommitTimeUnix` and so there's\n# no need to generate `get_build_id.c` for buck builds.\n#\n# See [1^] for details. For example, try\n# ```\n#  buck2 build @fbcode//mode/opt \\\n#   -c build_info.revision=\"$(hg log -r . -T {node})\" \\\n#      fbcode//tools/pyre/source:main --show-output\n# ```\n# and inspect the results with something like\n# ```\n#  fbcode/tools/build_info/build_info -binary \\\n#     buck-out/v2/gen/fbcode/ca1f7c2b2d91f85d/tools/pyre/source/__main__/main.opt\n# ```\n#\n# [^1]: [Build Info](https://www.internalfb.com/intern/wiki/Buck-users/fbcode-build-info/).\n\nif [[ -n \"$_OUT_DIR\" ]]; then\n  :\nelse\n  OUT_DIR=\"$SCRIPTS_DIRECTORY\"/../source/hack_parallel/hack_parallel/utils\n  cat > \"$OUT_DIR\"/get_build_id.c <<EOF\nconst char* const BuildInfo_kRevision = \"${VERSION}\";\nconst unsigned long BuildInfo_kRevisionCommitTimeUnix = 0ul;\nEOF\nfi\n", "num_lines": 99}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nSCRIPTS_DIRECTORY=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\n# For open-source tests to work, we have to run them from one directory\n# higher than the project root, so that the project root is treated as a\n# valid package for relative imports.\n#\n# We also want to be sure the tests work regardless of the project directory name\n# (particularly because both `pyre-check` and `pyre` are sometimes used).\ncd \"${SCRIPTS_DIRECTORY}/..\"\nROOT_DIRECTORY=\"$(pwd)\"\nROOT_DIRECTORY_BASE=\"$(basename \"${ROOT_DIRECTORY}\")\"\n\n\n# run pyre-extensions tests first: we want to test lower-level code\n# first since higher-level test failures are less informative\n\ncd \"${ROOT_DIRECTORY}\"\n\nfiles=$(find pyre_extensions -name '*_test.py')\necho \"Found these test files in the pyre_extensions code:\n${files}\n---\"\nif [[ -z \"${files}\" ]]; then\n  echo 'No test files found, exiting.'\n  exit 2\nfi\n\necho ' Running all tests:'\necho \"${files}\" | xargs testslide\n\n\n# Test pyre client code last since that's the highest-level code.\n\ncd \"${ROOT_DIRECTORY}/..\"\n\nfiles=$(find \"${ROOT_DIRECTORY_BASE}/client\" -name '*_test.py' ! -name 'watchman_test.py')\necho \"Found these test files in the client code:\n${files}\n---\"\nif [[ -z \"${files}\" ]]; then\n  echo 'No test files found, exiting.'\n  exit 2\nfi\n\necho ' Running client tests:'\necho \"${files}\" | xargs testslide\n", "num_lines": 55}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Switch to pyre directory.\ncd \"$(dirname \"$0\")/..\"\n\n./scripts/setup.py \"${@}\"\n", "num_lines": 11}
{"repo_name": "pyre-check", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Script to install pyre playground on a fresh ubuntu server.\n\nset -e\nset -x\n\nsudo apt-get update\n\nsudo apt-get install -y \\\n  build-essential \\\n  python3 \\\n  python3-venv \\\n  python3-dev \\\n  watchman \\\n  git \\\n  nginx\n\n# Grab the code and link it to ~/playground\ngit clone https://github.com/facebook/pyre-check.git\nln -s pyre-check/tools/playground/ ~/playground\ncd ~/playground\n\n# Set up the environment. You can verify the python app works with:\n#   python application.py --debug\npython3 -m venv ~/play-env\nsource ~/play-env/bin/activate\npip install -r requirements.txt\n\n# Start the service. You can verify it is up with:\n#   curl \"http://0.0.0.0:5000/check?input=reveal_type(1)\"\nsudo cp system/playground.service /etc/systemd/system/\nsudo systemctl start playground\nsudo systemctl enable playground\n\n# Set up nginx proxy. We need to remove the default config for\n# it to take effect. You can verify it is up with:\n#    curl \"http://0.0.0.0:80/check?input=reveal_type(1)\"\nsudo cp system/playground.nginx /etc/nginx/sites-available/playground\nsudo ln -s /etc/nginx/sites-{available,enabled}/playground\nsudo rm /etc/nginx/sites-enabled/default\nsudo systemctl restart nginx\n\n# verify that it is up\nsleep 5\ncurl \"http://0.0.0.0:80/check?input=reveal_type(1)\"\necho \"Server is up!\"\n", "num_lines": 52}
{"repo_name": "Rapid", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This is an example script that shows how to pull the latest version\n# of Rapid and replace the version string with a git short hash.\n#\n# To use this on your own site, you'll want to change the `cp` and `chgrp`\n# lines at the end to match your web server's documentroot folder and security group.\n\ngit checkout -q main\ngit remote update > /dev/null\n\nrev=`git rev-parse --short HEAD`\norig=`git rev-parse --short origin/main`\n\n# pull latest code\nif [[ \"${rev}\" != \"${orig}\" ]] ; then\n  # avoid issues with local untracked locale files\n  rm -f dist/locales/*.json\n  git reset --hard HEAD\n  git pull origin main\n\n  rev=`git rev-parse --short HEAD`\n  sed -i \"s/context.version = .*;/context.version = '${rev}';/\" modules/core/context.js\n\n  npm prune\n  npm install > /dev/null 2>&1\nfi\n\n# pull latest imagery\nrm -rf node_modules/editor-layer-index/\ngit clone https://github.com/osmlab/editor-layer-index.git node_modules/editor-layer-index > /dev/null 2>&1\nrm -rf node_modules/editor-layer-index/.git/\n\n# build everything\nnpm run imagery\nnpm run all\n\n# pull latest translations\nif [[ -f transifex.auth ]] ; then\n  npm run translations\nfi\n\ncp -Rf dist/* /var/www/path/to/rapid/\nchgrp -R www-data /var/www/path/to/rapid/", "num_lines": 44}
{"repo_name": "react", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n(cd ../.. && yarn build eslint --type=NODE_DEV)\n(cd ../.. && watchman-make --make 'yarn build eslint --type=NODE_DEV' -p 'packages/eslint-plugin-*/**/*' -t ignored)\n", "num_lines": 4}
{"repo_name": "react", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# Make sure we don't introduce accidental references to PATENTS.\nEXPECTED='scripts/circleci/check_license.sh'\nACTUAL=$(git grep -l PATENTS)\n\nif [ \"$EXPECTED\" != \"$ACTUAL\" ]; then\n  echo \"PATENTS crept into some new files?\"\n  diff -u <(echo \"$EXPECTED\") <(echo \"$ACTUAL\") || true\n  exit 1\nfi\n", "num_lines": 14}
{"repo_name": "react", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# Make sure we don't introduce accidental @providesModule annotations.\nEXPECTED='scripts/rollup/wrappers.js'\nACTUAL=$(git grep -l @providesModule -- './*.js' ':!scripts/rollup/shims/*.js')\n\n# Colors\nred=$'\\e[1;31m'\nend=$'\\e[0m'\n\nif [ \"$EXPECTED\" != \"$ACTUAL\" ]; then\n  printf \"%s\\n\" \"${red}ERROR: @providesModule crept into some new files?${end}\"\n  diff -u <(echo \"$EXPECTED\") <(echo \"$ACTUAL\") || true\n  exit 1\nfi\n", "num_lines": 18}
{"repo_name": "react", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nmkdir -p build/devtools\n\ncd packages/react-devtools\nnpm pack\nmv ./react-devtools*.tgz ../../build/devtools/\n\ncd ../react-devtools-core\nnpm pack\nmv ./react-devtools-core*.tgz ../../build/devtools/\n\ncd ../react-devtools-inline\nnpm pack\nmv ./react-devtools-inline*.tgz ../../build/devtools/\n\ncd ../react-devtools-extensions\nyarn build\nmv ./chrome/build/ReactDevTools.zip ../../build/devtools/chrome-extension.zip\nmv ./firefox/build/ReactDevTools.zip ../../build/devtools/firefox-extension.zip\n\n# Compress all DevTools artifacts into a single tarball for easy download\ncd ../../build/devtools\ntar -zcvf ../devtools.tgz .", "num_lines": 26}
{"repo_name": "react", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nWARNINGS=$(node scripts/print-warnings/print-warnings.js)\necho \"$WARNINGS\"\ntest ! -z \"$WARNINGS\"\n", "num_lines": 8}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script should be run from the react-native root\n\nTHIS_DIR=$(cd -P \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\nsource \"scripts/.tests.env\"\n\nif [ -n \"$1\" ]\n  then\n    echo \"Overriding...\"\n    IOS_TARGET_OS=\"${1}\"\n    SDK=\"iphonesimulator${1}\"\n    DESTINATION=\"platform=iOS Simulator,OS=${IOS_TARGET_OS},name=${IOS_DEVICE}\"\nfi\n\nxcodebuild \\\n  -workspace \"packages/rn-tester/RNTesterPods.xcworkspace\" \\\n  -scheme $SCHEME \\\n  -sdk $SDK \\\n  -destination \"$DESTINATION\" \\\n  build test\n", "num_lines": 26}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ndot -Tpdf InspectorFSM.gv -o InspectorFSM.pdf\n", "num_lines": 8}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nTHIS_DIR=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\nsource \"$THIS_DIR/setup.sh\"\n\nbuck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:chrome &&\n  buck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:detail &&\n  buck test //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:inspectorlib &&\n  buck build //xplat/js/react-native-github/packages/react-native/ReactCommon/hermes/inspector:hermes-chrome-debug-server\n", "num_lines": 14}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n#\n# Basic setup for xplat testing in sandcastle. Based on\n# xplat/hermes/facebook/sandcastle/setup.sh.\n\nset -x\nset -e\nset -o pipefail\n\nTHIS_DIR=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\nROOT_DIR=$(cd \"$THIS_DIR\" && hg root)\n\n# Enter xplat\ncd \"$ROOT_DIR\"/xplat || exit 1\n\n# Setup env\nexport TITLE\nTITLE=$(hg log -l 1 --template \"{desc|strip|firstline}\")\nexport REV\nREV=$(hg log -l 1 --template \"{node}\")\nexport AUTHOR\nAUTHOR=$(hg log -l 1 --template \"{author|emailuser}\")\n\nif [ -n \"$SANDCASTLE\" ]; then\n  source automation/setup_buck.sh\nfi\n", "num_lines": 32}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n#\u00c2\u00a0WHY WE NEED THIS:\n# This script is used to find a valid instance of `node` installed in the machine.\n# This script is sourced by other scripts to get access to node.\n# Specifically, it is used by the `react-native-xcode.sh` script, invoked by a\n# post-build phase in Xcode, to build the js files required by React Native.\n#\n# DEPRECATION NOTE:\n# React Native should not make assumptions on your current node environment.\n# This file is deprecated and will be removed in a future release in favor of something\n# node-agnostic and configurable by the developers.\n\n# remove global prefix if it's already set\n# the running shell process will choose a node binary and a global package directory breaks version managers\nunset PREFIX\n\n# Support Homebrew on M1\nHOMEBREW_M1_BIN=/opt/homebrew/bin\nif [[ -d $HOMEBREW_M1_BIN && ! $PATH =~ $HOMEBREW_M1_BIN ]]; then\n  export PATH=\"$HOMEBREW_M1_BIN:$PATH\"\nfi\n\n# Define NVM_DIR and source the nvm.sh setup script\n[ -z \"$NVM_DIR\" ] && export NVM_DIR=\"$HOME/.nvm\"\n\n# Source nvm with '--no-use' and then `nvm use` to respect .nvmrc\n# See: https://github.com/nvm-sh/nvm/issues/2053\nif [[ -s \"$HOME/.nvm/nvm.sh\" ]]; then\n  # shellcheck source=/dev/null\n  . \"$HOME/.nvm/nvm.sh\" --no-use\n  nvm use 2> /dev/null || nvm use default\nelif [[ -x \"$(command -v brew)\" && -s \"$(brew --prefix nvm)/nvm.sh\" ]]; then\n  # shellcheck source=/dev/null\n  . \"$(brew --prefix nvm)/nvm.sh\" --no-use\n  nvm use 2> /dev/null || nvm use default\nfi\n\n# Set up the nodenv node version manager if present\nif [[ -x \"$HOME/.nodenv/bin/nodenv\" ]]; then\n  eval \"$(\"$HOME/.nodenv/bin/nodenv\" init -)\"\nelif [[ -x \"$(command -v brew)\" && -x \"$(brew --prefix nodenv)/bin/nodenv\" ]]; then\n  eval \"$(\"$(brew --prefix nodenv)/bin/nodenv\" init -)\"\nfi\n\n# Set up the ndenv of anyenv if preset\nif [[ ! -x node && -d ${HOME}/.anyenv/bin ]]; then\n  export PATH=${HOME}/.anyenv/bin:${PATH}\n  if [[ \"$(anyenv envs | grep -c ndenv )\" -eq 1 ]]; then\n    eval \"$(anyenv init -)\"\n  fi\nfi\n\n# Set up asdf-vm if present\nif [[ -f \"$ASDF_DIR/asdf.sh\" ]]; then\n  # shellcheck source=/dev/null\n  . \"$ASDF_DIR/asdf.sh\"\nelif [[ -f \"$HOME/.asdf/asdf.sh\" ]]; then\n  # shellcheck source=/dev/null\n  . \"$HOME/.asdf/asdf.sh\"\nelif [[ -x \"$(command -v brew)\" && -f \"$(brew --prefix asdf)/asdf.sh\" ]]; then\n  # shellcheck source=/dev/null\n  . \"$(brew --prefix asdf)/asdf.sh\"\nfi\n\n# Set up volta if present\nif [[ -x \"$HOME/.volta/bin/node\" ]]; then\n  export VOLTA_HOME=\"$HOME/.volta\"\n  export PATH=\"$VOLTA_HOME/bin:$PATH\"\nfi\n\n# Set up the fnm node version manager if present\nif [[ -x \"$HOME/.fnm/fnm\" ]]; then\n  eval \"$(\"$HOME/.fnm/fnm\" env)\"\nelif [[ -x \"$(command -v brew)\" && -x \"$(brew --prefix fnm)/bin/fnm\" ]]; then\n  eval \"$(\"$(brew --prefix fnm)/bin/fnm\" env)\"\nfi\n", "num_lines": 84}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nPLATFORM_NAME=\"${PLATFORM_NAME:-iphoneos}\"\nCURRENT_ARCH=\"${CURRENT_ARCH}\"\n\nif [ -z \"$CURRENT_ARCH\" ] || [ \"$CURRENT_ARCH\" == \"undefined_arch\" ]; then\n    # Xcode 10 beta sets CURRENT_ARCH to \"undefined_arch\", this leads to incorrect linker arg.\n    # it's better to rely on platform name as fallback because architecture differs between simulator and device\n\n    if [[ \"$PLATFORM_NAME\" == *\"simulator\"* ]]; then\n        CURRENT_ARCH=\"x86_64\"\n    else\n        CURRENT_ARCH=\"arm64\"\n    fi\nfi\n\n# @lint-ignore-every TXT2 Tab Literal\nif [ \"$CURRENT_ARCH\" == \"arm64\" ]; then\n    cat <<\\EOF >>fix_glog_0.3.5_apple_silicon.patch\ndiff --git a/config.sub b/config.sub\nindex 1761d8b..43fa2e8 100755\n--- a/config.sub\n+++ b/config.sub\n@@ -1096,6 +1096,9 @@ case $basic_machine in\n \t\tbasic_machine=z8k-unknown\n \t\tos=-sim\n \t\t;;\n+\tarm64-*)\n+\t\tbasic_machine=$(echo $basic_machine | sed 's/arm64/aarch64/')\n+\t\t;;\n \tnone)\n \t\tbasic_machine=none-none\n \t\tos=-none\nEOF\n\n    patch -p1 config.sub fix_glog_0.3.5_apple_silicon.patch\nfi\n\nexport CC=\"$(xcrun -find -sdk $PLATFORM_NAME cc) -arch $CURRENT_ARCH -isysroot $(xcrun -sdk $PLATFORM_NAME --show-sdk-path)\"\nexport CXX=\"$CC\"\n\n# Remove automake symlink if it exists\nif [ -h \"test-driver\" ]; then\n    rm test-driver\nfi\n\n# Manually disable gflags include to fix issue https://github.com/facebook/react-native/issues/28446\nsed -i.bak -e 's/\\@ac_cv_have_libgflags\\@/0/' src/glog/logging.h.in && rm src/glog/logging.h.in.bak\nsed -i.bak -e 's/HAVE_LIB_GFLAGS/HAVE_LIB_GFLAGS_DISABLED/' src/config.h.in && rm src/config.h.in.bak\n\n./configure --host arm-apple-darwin\n\ncat << EOF >> src/config.h\n/* Add in so we have Apple Target Conditionals */\n#ifdef __APPLE__\n#include <TargetConditionals.h>\n#include <Availability.h>\n#endif\n\n/* Special configuration for ucontext */\n#undef HAVE_UCONTEXT_H\n#undef PC_FROM_UCONTEXT\n#if defined(__x86_64__)\n#define PC_FROM_UCONTEXT uc_mcontext->__ss.__rip\n#elif defined(__i386__)\n#define PC_FROM_UCONTEXT uc_mcontext->__ss.__eip\n#endif\nEOF\n\n# Prepare exported header include\nEXPORTED_INCLUDE_DIR=\"exported/glog\"\nmkdir -p exported/glog\ncp -f src/glog/log_severity.h \"$EXPORTED_INCLUDE_DIR/\"\ncp -f src/glog/logging.h \"$EXPORTED_INCLUDE_DIR/\"\ncp -f src/glog/raw_logging.h \"$EXPORTED_INCLUDE_DIR/\"\ncp -f src/glog/stl_logging.h \"$EXPORTED_INCLUDE_DIR/\"\ncp -f src/glog/vlog_is_on.h \"$EXPORTED_INCLUDE_DIR/\"\n", "num_lines": 84}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n[ -z \"$NODE_BINARY\" ] && export NODE_BINARY=\"node\"\n\nnodejs_not_found()\n{\n  echo \"error: Can't find the '$NODE_BINARY' binary to build the React Native bundle. \" \\\n       \"If you have a non-standard Node.js installation, select your project in Xcode, find \" \\\n       \"'Build Phases' - 'Bundle React Native code and images' and change NODE_BINARY to an \" \\\n       \"absolute path to your node executable. You can find it by invoking 'which node' in the terminal.\" >&2\n  exit 2\n}\n\ntype \"$NODE_BINARY\" >/dev/null 2>&1 || nodejs_not_found\n", "num_lines": 19}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# scripts directory\nTHIS_DIR=$(cd -P \"$(dirname \"$(readlink \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\nREACT_NATIVE_ROOT=\"$THIS_DIR/..\"\n# Application root directory - General use case: react-native is a dependency\nPROJECT_ROOT=${PROJECT_ROOT:-\"$THIS_DIR/../../..\"}\n\n# check and assign NODE_BINARY env\n# shellcheck disable=SC1090\nsource \"${THIS_DIR}/node-binary.sh\"\n\n# Start packager from PROJECT_ROOT\ncd \"$PROJECT_ROOT\" || exit\n\"$NODE_BINARY\" \"$REACT_NATIVE_ROOT/cli.js\" start --custom-log-reporter-path \"$THIS_DIR/packager-reporter.js\" \"$@\"\n", "num_lines": 20}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Bundle React Native app's code and image assets.\n# This script is supposed to be invoked as part of Xcode build process\n# and relies on environment variables (including PWD) set by Xcode\n\n# Print commands before executing them (useful for troubleshooting)\nset -x\nDEST=$CONFIGURATION_BUILD_DIR/$UNLOCALIZED_RESOURCES_FOLDER_PATH\n\n# Enables iOS devices to get the IP address of the machine running Metro\nif [[ ! \"$SKIP_BUNDLING_METRO_IP\" && \"$CONFIGURATION\" = *Debug* && ! \"$PLATFORM_NAME\" == *simulator ]]; then\n  for num in 0 1 2 3 4 5 6 7 8; do\n    IP=$(ipconfig getifaddr en${num})\n    if [ ! -z \"$IP\" ]; then\n      break\n    fi\n  done\n  if [ -z \"$IP\" ]; then\n    IP=$(ifconfig | grep 'inet ' | grep -v ' 127.' | grep -v ' 169.254.' |cut -d\\   -f2  | awk 'NR==1{print $1}')\n  fi\n\n  echo \"$IP\" > \"$DEST/ip.txt\"\nfi\n\nif [[ \"$SKIP_BUNDLING\" ]]; then\n  echo \"SKIP_BUNDLING enabled; skipping.\"\n  exit 0;\nfi\n\ncase \"$CONFIGURATION\" in\n  *Debug*)\n    if [[ \"$PLATFORM_NAME\" == *simulator ]]; then\n      if [[ \"$FORCE_BUNDLING\" ]]; then\n        echo \"FORCE_BUNDLING enabled; continuing to bundle.\"\n      else\n        echo \"Skipping bundling in Debug for the Simulator (since the packager bundles for you). Use the FORCE_BUNDLING flag to change this behavior.\"\n        exit 0;\n      fi\n    else\n      echo \"Bundling for physical device. Use the SKIP_BUNDLING flag to change this behavior.\"\n    fi\n\n    DEV=true\n    ;;\n  \"\")\n    echo \"$0 must be invoked by Xcode\"\n    exit 1\n    ;;\n  *)\n    DEV=false\n    ;;\nesac\n\n# Path to react-native folder inside node_modules\nREACT_NATIVE_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd)\"\n# Most projects have their project root, one level up from their Xcode project dir (the \"ios\" directory)\nPROJECT_ROOT=${PROJECT_ROOT:-\"$PROJECT_DIR/..\"}\n\ncd \"$PROJECT_ROOT\" || exit\n\n# Define entry file\nif [[ \"$ENTRY_FILE\" ]]; then\n  # Use ENTRY_FILE defined by user\n  :\nelif [[ -s \"index.ios.js\" ]]; then\n  ENTRY_FILE=${1:-index.ios.js}\nelse\n  ENTRY_FILE=${1:-index.js}\nfi\n\n# check and assign NODE_BINARY env\n# shellcheck source=/dev/null\nsource \"$REACT_NATIVE_DIR/scripts/node-binary.sh\"\n\n# If hermes-engine is in the Podfile.lock, it means that Hermes is a dependency of the project\n# and it is enabled. If not, it means that hermes is disabled.\nHERMES_ENABLED=$(grep hermes-engine $PODS_PODFILE_DIR_PATH/Podfile.lock)\n\n# If hermes-engine is not in the Podfile.lock, it means that the app is not using Hermes.\n# Setting USE_HERMES is no the only way to set whether the app can use hermes or not: users\n# can also modify manually the Podfile.\nif [[ -z \"$HERMES_ENABLED\" ]]; then\n  USE_HERMES=false\nfi\n\nHERMES_ENGINE_PATH=\"$PODS_ROOT/hermes-engine\"\n[ -z \"$HERMES_CLI_PATH\" ] && HERMES_CLI_PATH=\"$HERMES_ENGINE_PATH/destroot/bin/hermesc\"\n\n# Hermes is enabled in new projects by default, so we cannot assume that USE_HERMES=1 is set as an envvar.\n# If hermes-engine is found in Pods, we can assume Hermes has not been disabled.\n# If hermesc is not available and USE_HERMES is either unset or true, show error.\nif [[  ! -z \"$HERMES_ENABLED\" && -f \"$HERMES_ENGINE_PATH\" && ! -f \"$HERMES_CLI_PATH\" ]]; then\n  echo \"error: Hermes is enabled but the hermesc binary could not be found at ${HERMES_CLI_PATH}.\" \\\n       \"Perhaps you need to run 'bundle exec pod install' or otherwise \" \\\n       \"point the HERMES_CLI_PATH variable to your custom location.\" >&2\n  exit 2\nfi\n\n[ -z \"$NODE_ARGS\" ] && export NODE_ARGS=\"\"\n\n[ -z \"$CLI_PATH\" ] && export CLI_PATH=\"$REACT_NATIVE_DIR/cli.js\"\n\n[ -z \"$BUNDLE_COMMAND\" ] && BUNDLE_COMMAND=\"bundle\"\n\n[ -z \"$COMPOSE_SOURCEMAP_PATH\" ] && COMPOSE_SOURCEMAP_PATH=\"$REACT_NATIVE_DIR/scripts/compose-source-maps.js\"\n\nif [[ -z \"$BUNDLE_CONFIG\" ]]; then\n  CONFIG_ARG=\"\"\nelse\n  CONFIG_ARG=\"--config $BUNDLE_CONFIG\"\nfi\n\nBUNDLE_FILE=\"$CONFIGURATION_BUILD_DIR/main.jsbundle\"\n\nEXTRA_ARGS=\n\ncase \"$PLATFORM_NAME\" in\n  \"macosx\")\n    BUNDLE_PLATFORM=\"macos\"\n    ;;\n  *)\n    BUNDLE_PLATFORM=\"ios\"\n    ;;\nesac\n\nif [ \"${IS_MACCATALYST}\" = \"YES\" ]; then\n  BUNDLE_PLATFORM=\"ios\"\nfi\n\nEMIT_SOURCEMAP=\nif [[ ! -z \"$SOURCEMAP_FILE\" ]]; then\n  EMIT_SOURCEMAP=true\nfi\n\nPACKAGER_SOURCEMAP_FILE=\nif [[ $EMIT_SOURCEMAP == true ]]; then\n  if [[ $USE_HERMES != false ]]; then\n    PACKAGER_SOURCEMAP_FILE=\"$CONFIGURATION_BUILD_DIR/$(basename $SOURCEMAP_FILE)\"\n  else\n    PACKAGER_SOURCEMAP_FILE=\"$SOURCEMAP_FILE\"\n  fi\n  EXTRA_ARGS=\"$EXTRA_ARGS --sourcemap-output $PACKAGER_SOURCEMAP_FILE\"\nfi\n\n# Hermes doesn't require JS minification.\nif [[ $USE_HERMES != false && $DEV == false ]]; then\n  EXTRA_ARGS=\"$EXTRA_ARGS --minify false\"\nfi\n\n\"$NODE_BINARY\" $NODE_ARGS \"$CLI_PATH\" $BUNDLE_COMMAND \\\n  $CONFIG_ARG \\\n  --entry-file \"$ENTRY_FILE\" \\\n  --platform \"$BUNDLE_PLATFORM\" \\\n  --dev $DEV \\\n  --reset-cache \\\n  --bundle-output \"$BUNDLE_FILE\" \\\n  --assets-dest \"$DEST\" \\\n  $EXTRA_ARGS \\\n  $EXTRA_PACKAGER_ARGS\n\nif [[ $USE_HERMES == false ]]; then\n  cp \"$BUNDLE_FILE\" \"$DEST/\"\n  BUNDLE_FILE=\"$DEST/main.jsbundle\"\nelse\n  EXTRA_COMPILER_ARGS=\n  if [[ $DEV == true ]]; then\n    EXTRA_COMPILER_ARGS=-Og\n  else\n    EXTRA_COMPILER_ARGS=-O\n  fi\n  if [[ $EMIT_SOURCEMAP == true ]]; then\n    EXTRA_COMPILER_ARGS=\"$EXTRA_COMPILER_ARGS -output-source-map\"\n  fi\n  \"$HERMES_CLI_PATH\" -emit-binary -max-diagnostic-width=80 \"$EXTRA_COMPILER_ARGS\" -out \"$DEST/main.jsbundle\" \"$BUNDLE_FILE\"\n  if [[ $EMIT_SOURCEMAP == true ]]; then\n    HBC_SOURCEMAP_FILE=\"$DEST/main.jsbundle.map\"\n    \"$NODE_BINARY\" \"$COMPOSE_SOURCEMAP_PATH\" \"$PACKAGER_SOURCEMAP_FILE\" \"$HBC_SOURCEMAP_FILE\" -o \"$SOURCEMAP_FILE\"\n    rm \"$HBC_SOURCEMAP_FILE\"\n    rm \"$PACKAGER_SOURCEMAP_FILE\"\n  fi\n  BUNDLE_FILE=\"$DEST/main.jsbundle\"\nfi\n\nif [[ $DEV != true && ! -f \"$BUNDLE_FILE\" ]]; then\n  echo \"error: File $BUNDLE_FILE does not exist. Your environment is misconfigured as Metro was not able to produce the bundle so your release application won't work!\" >&2\n  exit 2\nfi\n", "num_lines": 193}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -f\n\nbasepath=$(dirname \"${0}\")\n\n# shellcheck disable=SC2207\nfiles=( $(find . -name '*-test.rb') )\n\ntest_suite=\"${basepath}/all_tests.rb\"\ntouch \"${test_suite}\"\n\necho \"require \\\"test/unit\\\"\" > \"${test_suite}\"\necho \"discovered the following files:\"\nfor i in \"${files[@]}\"\ndo\n    filename=\"${i#\"${basepath}/\"}\"\n    echo \"${filename}\"\n    echo \"require_relative \\\"${filename}\\\"\" >> \"${test_suite}\"\ndone\n\nruby -Itest \"${test_suite}\"\nRES=$?\nrm \"${test_suite}\"\nexit $RES\n", "num_lines": 30}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -o pipefail\nset -e\n\nGENERATED_SRCS_DIR=\"$DERIVED_FILE_DIR/generated/source/codegen\"\nTEMP_OUTPUT_DIR=\"$GENERATED_SRCS_DIR/out\"\nGENERATED_SCHEMA_FILE=\"$GENERATED_SRCS_DIR/schema.json\"\n\ncd \"$RCT_SCRIPT_RN_DIR\"\n\nCODEGEN_CLI_PATH=\"\"\n\nerror () {\n    echo \"$1\"\n    \"[Codegen] $1\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n    exit 1\n}\n\nfind_node () {\n    NODE_BINARY=\"${NODE_BINARY:-$(command -v node || true)}\"\n    if [ -z \"$NODE_BINARY\" ]; then\n        error \"[Error] Could not find node. It looks like that the .xcode.env or .xcode.env.local \" \\\n\"files are misconfigured. Please check that they are exporting a valid NODE_BINARY \" \\\n\"variable, pointing to a node executable.\"\n    fi\n}\n\nfind_codegen () {\n    CODEGEN_CLI_PATH=$(\"$NODE_BINARY\" --print \"require('path').dirname(require.resolve('@react-native/codegen/package.json'))\")\n    if ! [ -d \"$CODEGEN_CLI_PATH\" ]; then\n        error \"error: Could not determine @react-native/codegen location, using node module resolution. Try running 'yarn install' or 'npm install' in your project root.\"\n    fi\n}\n\nsetup_dirs () {\n    set +e\n    rm -rf \"$GENERATED_SRCS_DIR\"\n    set -e\n\n    mkdir -p \"$GENERATED_SRCS_DIR\" \"$TEMP_OUTPUT_DIR\"\n\n    # Clear output files\n    true > \"${SCRIPT_OUTPUT_FILE_0}\"\n}\n\ndescribe () {\n    message=\"\n\n    >>>>> $1\n\n    \"\n    echo \"$message\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n}\n\nrunSpecCodegen () {\n    \"$NODE_BINARY\" \"scripts/generate-specs-cli.js\" --platform ios --schemaPath \"$GENERATED_SCHEMA_FILE\" --outputDir \"$1\" --libraryName \"$RCT_SCRIPT_LIBRARY_NAME\" --libraryType \"$2\"\n}\n\ngenerateCodegenSchemaFromJavaScript () {\n    describe \"Generating codegen schema from JavaScript\"\n\n    SRCS_PATTERN=\"$RCT_SCRIPT_JS_SRCS_PATTERN\"\n    SRCS_DIR=\"$RCT_SCRIPT_JS_SRCS_DIR\"\n    if [ \"$SRCS_PATTERN\" ]; then\n        JS_SRCS=$(find \"$PODS_TARGET_SRCROOT/$SRCS_DIR\" -type f -name \"$SRCS_PATTERN\" -print0 | xargs -0)\n        echo \"$RCT_SCRIPT_FILE_LIST\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n    else\n        JS_SRCS=\"$PODS_TARGET_SRCROOT/$SRCS_DIR\"\n        echo \"$RCT_SCRIPT_JS_SRCS_DIR\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n    fi\n\n    # shellcheck disable=SC2086\n    # $JS_SRCS not having double quotations is intentional\n    \"$NODE_BINARY\" \"$CODEGEN_CLI_PATH/lib/cli/combine/combine-js-to-schema-cli.js\" \"$GENERATED_SCHEMA_FILE\" $JS_SRCS\n}\n\ngenerateCodegenArtifactsFromSchema () {\n    describe \"Generating codegen artifacts from schema\"\n    pushd \"$RN_DIR\" >/dev/null || exit 1\n        if [ \"$RCT_SCRIPT_LIBRARY_TYPE\" = \"all\" ]; then\n            runSpecCodegen \"$TEMP_OUTPUT_DIR\" \"modules\"\n            runSpecCodegen \"$TEMP_OUTPUT_DIR\" \"components\"\n        elif [ \"$RCT_SCRIPT_LIBRARY_TYPE\" = \"components\" ]; then\n            runSpecCodegen \"$TEMP_OUTPUT_DIR\" \"$RCT_SCRIPT_LIBRARY_TYPE\"\n        elif [ \"$RCT_SCRIPT_LIBRARY_TYPE\" = \"modules\" ]; then\n            runSpecCodegen \"$TEMP_OUTPUT_DIR\" \"$RCT_SCRIPT_LIBRARY_TYPE\"\n        fi\n    popd >/dev/null || exit 1\n}\n\ngenerateArtifacts () {\n    describe \"Generating codegen artifacts\"\n    pushd \"$RCT_SCRIPT_RN_DIR\" >/dev/null || exit 1\n        \"$NODE_BINARY\" \"scripts/generate-codegen-artifacts.js\" --path \"$RCT_SCRIPT_APP_PATH\" --outputPath \"$TEMP_OUTPUT_DIR\" --fabricEnabled \"$RCT_SCRIPT_FABRIC_ENABLED\" --configFileDir \"$RCT_SCRIPT_CONFIG_FILE_DIR\" --nodeBinary \"$NODE_BINARY\"\n    popd >/dev/null || exit 1\n}\n\nmoveOutputs () {\n    mkdir -p \"$RCT_SCRIPT_OUTPUT_DIR\"\n\n    # Copy all output to output_dir\n    cp -R \"$TEMP_OUTPUT_DIR/.\" \"$RCT_SCRIPT_OUTPUT_DIR\" || exit 1\n    echo \"$LIBRARY_NAME output has been written to $RCT_SCRIPT_OUTPUT_DIR:\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n    ls -1 \"$RCT_SCRIPT_OUTPUT_DIR\" >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n}\n\nwithCodegenDiscovery () {\n    setup_dirs\n    find_node\n    find_codegen\n    generateArtifacts\n    moveOutputs\n}\n\nnoCodegenDiscovery () {\n    setup_dirs\n    find_node\n    find_codegen\n    generateCodegenSchemaFromJavaScript\n    generateCodegenArtifactsFromSchema\n    moveOutputs\n}\n\nif [ \"$RCT_SCRIPT_TYPE\" = \"withCodegenDiscovery\" ]; then\n    withCodegenDiscovery \"$@\"\nelse\n    noCodegenDiscovery \"$@\"\nfi\n\necho 'Done.' >> \"${SCRIPT_OUTPUT_FILE_0}\" 2>&1\n", "num_lines": 136}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script is used to source in Xcode the environment settings required to run properly.\n#\u00c2\u00a0The script first sources the base `.xcode.env` file.\n# Then it sources the `.xcode.env.local` file if present, to override some local config\n# Finally, it will execute the command passed i input if any.\n#\n# USAGE:\n# ./with-environment.sh command\n\n# Start with a default\nNODE_BINARY=$(command -v node)\nexport NODE_BINARY\n\n# Override the default with the global environment\nENV_PATH=\"$PODS_ROOT/../.xcode.env\"\nif [ -f \"$ENV_PATH\" ]; then\n    source \"$ENV_PATH\"\nfi\n\n# Override the global with the local environment\nLOCAL_ENV_PATH=\"${ENV_PATH}.local\"\nif [ -f \"$LOCAL_ENV_PATH\" ]; then\n    source \"$LOCAL_ENV_PATH\"\nfi\n\n# Check whether NODE_BINARY has been properly set, otherwise help the users with a meaningful error.\nif [ -n \"$NODE_BINARY\" ]; then\n    echo \"Node found at: ${NODE_BINARY}\"\nelse\n    echo '[Warning] You need to configure your node path in the `\".xcode.env\" file` environment. ' \\\n       'You can set it up quickly by running: ' \\\n       '`echo export NODE_BINARY=$(command -v node) > .xcode.env` ' \\\n       'in the ios folder. This is needed by React Native to work correctly. ' \\\n       'We fallback to the DEPRECATED behavior of finding `node`. This will be REMOVED in a future version. ' \\\n       'You can read more about this here: https://reactnative.dev/docs/environment-setup#optional-configuring-your-environment' >&2\n    source \"${REACT_NATIVE_PATH}/scripts/find-node-for-xcode.sh\"\nfi\n\n# Execute argument, if present\nif [ -n \"$1\" ]; then\n  $1\nfi\n", "num_lines": 48}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Defines functions for building various Hermes frameworks.\n# See build-ios-framework.sh and build-mac-framework.sh for usage examples.\n\nCURR_SCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nIMPORT_HERMESC_PATH=${HERMES_OVERRIDE_HERMESC_PATH:-$PWD/build_host_hermesc/ImportHermesc.cmake}\nBUILD_TYPE=${BUILD_TYPE:-Debug}\n\nHERMES_PATH=\"$CURR_SCRIPT_DIR/..\"\nREACT_NATIVE_PATH=${REACT_NATIVE_PATH:-$CURR_SCRIPT_DIR/../../..}\n\nNUM_CORES=$(sysctl -n hw.ncpu)\n\nif [[ -z \"$JSI_PATH\" ]]; then\n  JSI_PATH=\"$REACT_NATIVE_PATH/ReactCommon/jsi\"\nfi\n\nfunction use_env_var_or_ruby_prop {\n  if [[ -n \"$1\" ]]; then\n    echo \"$1\"\n  else\n    ruby -rcocoapods-core -rjson -e \"puts Pod::Specification.from_file('hermes-engine.podspec').$2\"\n  fi\n}\n\nfunction get_release_version {\n  use_env_var_or_ruby_prop \"${RELEASE_VERSION}\" \"version\"\n}\n\nfunction get_ios_deployment_target {\n  use_env_var_or_ruby_prop \"${IOS_DEPLOYMENT_TARGET}\" \"deployment_target('ios')\"\n}\n\nfunction get_mac_deployment_target {\n  use_env_var_or_ruby_prop \"${MAC_DEPLOYMENT_TARGET}\" \"deployment_target('osx')\"\n}\n\n# Build host hermes compiler for internal bytecode\nfunction build_host_hermesc {\n  echo \"Building hermesc\"\n  pushd \"$HERMES_PATH\" > /dev/null || exit 1\n    cmake -S . -B build_host_hermesc -DJSI_DIR=\"$JSI_PATH\"\n    cmake --build ./build_host_hermesc --target hermesc -j \"${NUM_CORES}\"\n  popd > /dev/null || exit 1\n}\n\n# Utility function to configure an Apple framework\nfunction configure_apple_framework {\n  local enable_debugger cmake_build_type\n\n  if [[ $BUILD_TYPE == \"Debug\" ]]; then\n    enable_debugger=\"true\"\n  else\n    enable_debugger=\"false\"\n  fi\n  if [[ $BUILD_TYPE == \"Debug\" ]]; then\n    # JS developers aren't VM developers.\n    # Therefore we're passing as build type Release, to provide a faster build.\n    cmake_build_type=\"Release\"\n  else\n    cmake_build_type=\"MinSizeRel\"\n  fi\n\n  pushd \"$HERMES_PATH\" > /dev/null || exit 1\n    cmake -S . -B \"build_$1\" \\\n      -DHERMES_APPLE_TARGET_PLATFORM:STRING=\"$1\" \\\n      -DCMAKE_OSX_ARCHITECTURES:STRING=\"$2\" \\\n      -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=\"$3\" \\\n      -DHERMES_ENABLE_DEBUGGER:BOOLEAN=\"$enable_debugger\" \\\n      -DHERMES_ENABLE_INTL:BOOLEAN=true \\\n      -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \\\n      -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \\\n      -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \\\n      -DHERMES_ENABLE_BITCODE:BOOLEAN=false \\\n      -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \\\n      -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \\\n      -DIMPORT_HERMESC:PATH=\"$IMPORT_HERMESC_PATH\" \\\n      -DJSI_DIR=\"$JSI_PATH\" \\\n      -DHERMES_RELEASE_VERSION=\"for RN $(get_release_version)\" \\\n      -DCMAKE_BUILD_TYPE=\"$cmake_build_type\"\n    popd > /dev/null || exit 1\n}\n\n# Utility function to build an Apple framework\nfunction build_apple_framework {\n  # Only build host HermesC if no file found at $IMPORT_HERMESC_PATH\n  [ ! -f \"$IMPORT_HERMESC_PATH\" ] &&\n  build_host_hermesc\n\n  # Confirm ImportHermesc.cmake is now available.\n  [ ! -f \"$IMPORT_HERMESC_PATH\" ] &&\n  echo \"Host hermesc is required to build apple frameworks!\"\n\n  # $1: platform, $2: architectures, $3: deployment target\n  echo \"Building $BUILD_TYPE framework for $1 with architectures: $2\"\n  configure_apple_framework \"$1\" \"$2\" \"$3\"\n\n  pushd \"$HERMES_PATH\" > /dev/null || exit 1\n    mkdir -p \"destroot/Library/Frameworks/$1\"\n    cmake --build \"./build_$1\" --target libhermes -j \"${NUM_CORES}\"\n    cp -R \"./build_$1\"/API/hermes/hermes.framework* \"destroot/Library/Frameworks/$1\"\n\n    # In a MacOS build, also produce the hermes and hermesc CLI tools.\n    if [[ $1 == macosx ]]; then\n      cmake --build \"./build_$1\" --target hermesc hermes -j \"${NUM_CORES}\"\n      mkdir -p destroot/bin\n      cp \"./build_$1/bin\"/* \"destroot/bin\"\n    fi\n\n    # Copy over Hermes and JSI API headers.\n    mkdir -p destroot/include/hermes/Public destroot/include/jsi\n    cp public/hermes/Public/*.h destroot/include/hermes/Public\n    cp API/hermes/*.h destroot/include/hermes\n    cp \"$JSI_PATH\"/jsi/*.h destroot/include/jsi\n  popd > /dev/null || exit 1\n}\n\n# Accepts an array of frameworks and will place all of\n# the architectures into an universal folder and then remove\n# the merged frameworks from destroot\nfunction create_universal_framework {\n  pushd \"$HERMES_PATH/destroot/Library/Frameworks\" > /dev/null || exit 1\n\n  local platforms=(\"$@\")\n  local args=\"\"\n\n  echo \"Creating universal framework for platforms: ${platforms[*]}\"\n\n  for i in \"${!platforms[@]}\"; do\n    local platform=\"${platforms[$i]}\"\n    local hermes_framework_path=\"${platform}/hermes.framework\"\n    local dSYM_path=\"$hermes_framework_path\"\n    local dSYM_base_path=\"$HERMES_PATH/destroot/Library/Frameworks\"\n\n    # If the dSYM rename has failed, the dSYM are generated as 0.dSYM\n    # (Apple default name) rather then hermes.framework.dSYM.\n    if [[ -e \"$dSYM_base_path/${platform}/0.dSYM\" ]]; then\n      dSYM_path=\"${platform}/0\"\n    fi\n\n    args+=\"-framework $hermes_framework_path \"\n\n    # Path to dSYM must be absolute\n    args+=\"-debug-symbols $dSYM_base_path/$dSYM_path.dSYM \"\n  done\n\n  mkdir -p universal\n  # shellcheck disable=SC2086\n  if xcodebuild -create-xcframework $args -output \"universal/hermes.xcframework\"\n  then\n    # # Remove the thin iOS hermes.frameworks that are now part of the universal\n    # XCFramework\n    for platform in \"${platforms[@]}\"; do\n      rm -r \"$platform\"\n    done\n  fi\n\n  popd > /dev/null || exit 1\n}\n", "num_lines": 166}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\n\nrelease_version=\"$1\"; shift\nhermesc_path=\"$1\"; shift\n\nenable_debugger=\"false\"\nif [[ \"$CONFIGURATION\" == \"Debug\" ]]; then\n  enable_debugger=\"true\"\nfi\n\ncmake_build_type=\"\"\nif [[ $CONFIGURATION == \"Debug\" ]]; then\n  # JS developers aren't VM developers.\n  # Therefore we're passing as build type Release, to provide a faster build.\n  cmake_build_type=\"Release\"\nelse\n  cmake_build_type=\"MinSizeRel\"\nfi\n\ndeployment_target=${IPHONEOS_DEPLOYMENT_TARGET}\nif [ -z \"$deployment_target\" ]; then\n  deployment_target=${MACOSX_DEPLOYMENT_TARGET}\nfi\n\narchitectures=$( echo \"$ARCHS\" | tr  \" \" \";\" )\n\necho \"Configure Apple framework\"\n\n\"$CMAKE_BINARY\" \\\n  -S \"${PODS_ROOT}/hermes-engine\" \\\n  -B \"${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}\" \\\n  -DHERMES_APPLE_TARGET_PLATFORM:STRING=\"$PLATFORM_NAME\" \\\n  -DCMAKE_OSX_ARCHITECTURES:STRING=\"$architectures\" \\\n  -DCMAKE_OSX_DEPLOYMENT_TARGET:STRING=\"$deployment_target\" \\\n  -DHERMES_ENABLE_DEBUGGER:BOOLEAN=\"$enable_debugger\" \\\n  -DHERMES_ENABLE_INTL:BOOLEAN=true \\\n  -DHERMES_ENABLE_LIBFUZZER:BOOLEAN=false \\\n  -DHERMES_ENABLE_FUZZILLI:BOOLEAN=false \\\n  -DHERMES_ENABLE_TEST_SUITE:BOOLEAN=false \\\n  -DHERMES_ENABLE_BITCODE:BOOLEAN=false \\\n  -DHERMES_BUILD_APPLE_FRAMEWORK:BOOLEAN=true \\\n  -DHERMES_BUILD_APPLE_DSYM:BOOLEAN=true \\\n  -DIMPORT_HERMESC:PATH=\"${hermesc_path}\" \\\n  -DHERMES_RELEASE_VERSION=\"for RN $release_version\" \\\n  -DCMAKE_BUILD_TYPE=\"$cmake_build_type\"\n\necho \"Build Apple framework\"\n\n\"$CMAKE_BINARY\" \\\n  --build \"${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}\" \\\n  --target libhermes \\\n  -j \"$(sysctl -n hw.ncpu)\"\n\necho \"Copy Apple framework to destroot/Library/Frameworks\"\n\ncp -pfR \\\n  \"${PODS_ROOT}/hermes-engine/build/${PLATFORM_NAME}/API/hermes/hermes.framework\" \\\n  \"${PODS_ROOT}/hermes-engine/destroot/Library/Frameworks/ios\"\n", "num_lines": 65}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\n\nhermesc_dir_path=\"$1\"\n\n# This script is supposed to be executed from Xcode \"run script\" phase.\n# Xcode sets up its build environment based on the build target.\n# Here we override relevant envvars to make sure that we build hermesc for macosx,\n# even if Xcode build target is iphone, iponesimulator, etc.\nMACOSX_DEPLOYMENT_TARGET=$(sw_vers -productVersion)\nexport MACOSX_DEPLOYMENT_TARGET=$MACOSX_DEPLOYMENT_TARGET\nSDKROOT=$(xcode-select -p)/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk\nexport SDKROOT=$SDKROOT\n\nif ! \"$CMAKE_BINARY\" -S \"${PODS_ROOT}/hermes-engine\" -B \"$hermesc_dir_path\"\nthen\n    echo \"Failed to configure Hermesc cmake project.\"\n    exit 1\nfi\nif ! \"$CMAKE_BINARY\" --build \"$hermesc_dir_path\" --target hermesc -j \"$(sysctl -n hw.ncpu)\"\nthen\n    echo \"Failed to build Hermesc cmake project.\"\n    exit 1\nfi\n", "num_lines": 30}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck source=xplat/js/react-native-github/sdks/hermes-engine/utils/build-apple-framework.sh\nCURR_SCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n. \"${CURR_SCRIPT_DIR}/build-apple-framework.sh\"\n\nif [ ! -d destroot/Library/Frameworks/universal/hermes.xcframework ]; then\n    ios_deployment_target=$(get_ios_deployment_target)\n\n    build_apple_framework \"iphoneos\" \"arm64\" \"$ios_deployment_target\"\n    build_apple_framework \"iphonesimulator\" \"x86_64;arm64\" \"$ios_deployment_target\"\n    build_apple_framework \"catalyst\" \"x86_64;arm64\" \"$ios_deployment_target\"\n\n    create_universal_framework \"iphoneos\" \"iphonesimulator\" \"catalyst\"\nelse\n    echo \"Skipping; Clean \\\"destroot\\\" to rebuild\".\nfi\n", "num_lines": 22}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# shellcheck source=xplat/js/react-native-github/sdks/hermes-engine/utils/build-apple-framework.sh\nCURR_SCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n. \"${CURR_SCRIPT_DIR}/build-apple-framework.sh\"\n\nif [ ! -d destroot/Library/Frameworks/macosx/hermes.framework ]; then\n    mac_deployment_target=$(get_mac_deployment_target)\n\n    build_apple_framework \"macosx\" \"x86_64;arm64\" \"$mac_deployment_target\"\nelse\n    echo \"Skipping; Clean \\\"destroot\\\" to rebuild\".\nfi\n", "num_lines": 18}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\necho \"This file is no-op now. Remove \\\"[RN] Copy Hermes Framework\\\" script phase from your main target if you don't want to see this message.\"\n", "num_lines": 8}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\n\n# CocoaPods requires vendored frameworks to exist before `pod install` is run,\n# and to be proper Moch-O binaries in order to auto-link them to the user's Xcode project.\n# This script creates dummy hermes.framework for macosx and ios.\n# They are then get rewritten by `build-hermes-xcode.sh` during Xcode build.\n\nrm -rf destroot\n\nmkdir -p destroot/Library/Frameworks\n\npushd destroot/Library/Frameworks > /dev/null || exit 1\n\necho '' > dummy.c\n\nmkdir -p macosx/hermes.framework\nclang dummy.c -dynamiclib -o macosx/hermes.framework/hermes\n\nmkdir -p ios/hermes.framework\nclang dummy.c -dynamiclib -o ios/hermes.framework/hermes\n\nrm dummy.c\n\npopd > /dev/null || exit 1\n", "num_lines": 31}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Note: To be invoked by Buck sh_binary() in OSS environment.\n# DO NOT USE outside of Buck!\n\nset -e\nset -u\n\npushd \"$BUCK_DEFAULT_RUNTIME_RESOURCES\" >/dev/null\nnode \"build/lib/cli/combine/combine-js-to-schema-cli.js\" \"$@\"\npopd >/dev/null\n", "num_lines": 16}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Note: To be invoked by Buck sh_binary() in OSS environment.\n# DO NOT USE outside of Buck!\n\nset -e\nset -u\n\npushd \"$BUCK_DEFAULT_RUNTIME_RESOURCES\" >/dev/null\nnode \"build/lib/cli/generators/generate-all.js\" \"$@\"\npopd >/dev/null\n", "num_lines": 16}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script assumes yarn is already installed.\n\nTHIS_DIR=$(cd -P \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\n\nset -e\nset -u\n\nCODEGEN_DIR=\"$THIS_DIR/../..\"\n\nrm -rf \"${CODEGEN_DIR:?}/lib\" \"${CODEGEN_DIR:?}/node_modules\"\n\n# Fallback to npm if yarn is not available\nif [ -x \"$(command -v yarn)\" ]; then\n  YARN_OR_NPM=$(command -v yarn)\nelse\n  YARN_OR_NPM=$(command -v npm)\nfi\nYARN_BINARY=\"${YARN_BINARY:-$YARN_OR_NPM}\"\n\nif [[ ${FBSOURCE_ENV:-0} -eq 1 ]]; then\n  # Custom FB-specific setup\n  pushd \"$CODEGEN_DIR\" >/dev/null\n\n  \"$YARN_BINARY\" install 2> >(grep -v '^warning' 1>&2)\n  # Note: Within FBSOURCE_ENV, this has to explicitly run build.\n  \"$YARN_BINARY\" run build\n\n  popd >/dev/null\n\nelse\n  # Run yarn install in a separate tmp dir to avoid conflict with the rest of the repo.\n  # Note: OSS-only.\n  TMP_DIR=$(mktemp -d)\n\n  # On Windows this script gets run by a seprate Git Bash instance, which cannot perform the copy\n  # due to file locks created by the host process. Need to exclude .lock files while copying.\n  # Using in-memory tar operation because piping `find` and `grep` doesn't preserve folder structure\n  # during recursive copying, and `rsync` is not installed by default in Git Bash.\n  # As an added benefit, blob copy is faster.\n  if [ \"$OSTYPE\" = \"msys\" ] || [ \"$OSTYPE\" = \"cygwin\" ]; then\n    tar cf - --exclude='*.lock' \"$CODEGEN_DIR\" | (cd \"$TMP_DIR\" && tar xvf - );\n  else\n    cp -R \"$CODEGEN_DIR/.\" \"$TMP_DIR\";\n  fi\n\n  pushd \"$TMP_DIR\" >/dev/null\n\n  # Note: this automatically runs build as well.\n  \"$YARN_BINARY\" install 2> >(grep -v '^warning' 1>&2)\n\n  popd >/dev/null\n\n  mv \"$TMP_DIR/lib\" \"$TMP_DIR/node_modules\" \"$CODEGEN_DIR\"\n  rm -rf \"$TMP_DIR\"\nfi\n", "num_lines": 62}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\nset -u\n\nTHIS_DIR=$(cd -P \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\n\n# shellcheck source=xplat/js/env-utils/setup_env_vars.sh\nsource \"$THIS_DIR/../../../../../../env-utils/setup_env_vars.sh\"\n\nexec \"$FLOW_NODE_BINARY\" \"$THIS_DIR/parser.js\" \"$@\"\n", "num_lines": 16}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nTHIS_DIR=$(cd -P \"$(dirname \"$(readlink \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\npushd \"$THIS_DIR\" || exit\n./websocket_integration_test_server.js\npopd || exit\n\necho \"Process terminated.\"\n", "num_lines": 13}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# inspired by https://github.com/Originate/guide/blob/master/android/guide/Continuous%20Integration.md\n\n# shellcheck disable=SC1091\nsource \"scripts/.tests.env\"\n\n# NOTE: This doesn't run in Circle CI currently!\nfunction getAndroidPackages {\n  export PATH=\"$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$ANDROID_HOME/tools.bin:$PATH\"\n\n  DEPS=\"$ANDROID_HOME/installed-dependencies\"\n\n  # Package names can be obtained using `sdkmanager --list`\n  if [ ! -e \"$DEPS\" ] || [ ! \"$CI\" ]; then\n    echo \"Installing Android API level $ANDROID_SYSTEM_IMAGE_API_LEVEL, Google APIs, $AVD_ABI system image...\"\n    sdkmanager \"system-images;android-$ANDROID_SYSTEM_IMAGE_API_LEVEL;google_apis;$AVD_ABI\"\n    echo \"Installing build SDK for Android API level $ANDROID_SDK_BUILD_API_LEVEL...\"\n    sdkmanager \"platforms;android-$ANDROID_SDK_BUILD_API_LEVEL\"\n    echo \"Installing target SDK for Android API level $ANDROID_SDK_TARGET_API_LEVEL...\"\n    sdkmanager \"platforms;android-$ANDROID_SDK_TARGET_API_LEVEL\"\n    echo \"Installing SDK build tools, revision $ANDROID_SDK_BUILD_TOOLS_REVISION...\"\n    sdkmanager \"build-tools;$ANDROID_SDK_BUILD_TOOLS_REVISION\"\n    # These moved to \"system-images;android-$ANDROID_SDK_BUILD_API_LEVEL;google_apis;x86\" starting with API level 25, but there is no ARM version.\n    echo \"Installing Google APIs $ANDROID_GOOGLE_API_LEVEL...\"\n    sdkmanager \"add-ons;addon-google_apis-google-$ANDROID_GOOGLE_API_LEVEL\"\n    echo \"Installing Android Support Repository\"\n    sdkmanager \"extras;android;m2repository\"\n    $CI && touch \"$DEPS\"\n  fi\n}\n\nfunction getAndroidNDK {\n  NDK_HOME=\"/opt/ndk\"\n  DEPS=\"$NDK_HOME/installed-dependencies\"\n\n  if [ ! -e $DEPS ]; then\n    cd $NDK_HOME || exit\n    echo \"Downloading NDK...\"\n    curl -o ndk.zip https://dl.google.com/android/repository/android-ndk-r19c-linux-x86_64.zip\n    unzip -o -q ndk.zip\n    echo \"Installed Android NDK at $NDK_HOME\"\n    touch $DEPS\n    rm ndk.zip\n  fi\n}\n\nfunction createAVD {\n  if [ -z \"$ANDROID_DISABLE_AVD_TESTS\" ]\n  then\n    AVD_PACKAGES=\"system-images;android-$ANDROID_IMAGE_API_LEVEL;google_apis;$AVD_ABI\"\n    echo \"Creating AVD with packages $AVD_PACKAGES\"\n    echo no | avdmanager create avd --name \"$AVD_NAME\" --force --package \"$AVD_PACKAGES\" --tag google_apis --abi \"$AVD_ABI\"\n  else\n    echo \"Skipping AVD-related test setup...\"\n  fi\n}\n\nfunction launchAVD {\n  # Force start adb server\n  adb start-server\n\n  if [ -z \"$ANDROID_DISABLE_AVD_TESTS\" ]\n  then\n    # The AVD name here should match the one created in createAVD\n    if [ \"$CI\" ]\n    then\n      \"$ANDROID_HOME/emulator/emulator\" -avd \"$AVD_NAME\" -no-audio -no-window\n    else\n      \"$ANDROID_HOME/emulator/emulator\" -avd \"$AVD_NAME\"\n    fi\n  else\n    echo \"Skipping AVD-related test setup...\"\n  fi\n}\n\nfunction waitForAVD {\n  if [ -z \"$ANDROID_DISABLE_AVD_TESTS\" ]\n  then\n    echo \"Waiting for Android Virtual Device to finish booting...\"\n    local bootanim=\"\"\n    export PATH=$(dirname $(dirname $(command -v android)))/platform-tools:$PATH\n    until [[ \"$bootanim\" =~ \"stopped\" ]]; do\n      sleep 5\n      bootanim=$(adb -e shell getprop init.svc.bootanim 2>&1)\n      echo \"boot animation status=$bootanim\"\n    done\n    echo \"Android Virtual Device is ready.\"\n  else\n    echo \"Skipping AVD-related test setup...\"\n  fi\n}\n", "num_lines": 97}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Script used to run iOS tests.\n# If no arguments are passed to the script, it will only compile\n# the RNTester.\n# If the script is called with a single argument \"test\", we'll\n# run the RNTester unit and integration tests\n# ./objc-test.sh test\n\nSCRIPTS=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\nROOT=$(dirname \"$SCRIPTS\")\n\nSKIPPED_TESTS=()\nSKIPPED_TESTS+=(\"-skip-testing:RNTesterIntegrationTests/RNTesterSnapshotTests\")\n# TODO: T60408036 This test crashes iOS 13 for bad access, please investigate\n# and re-enable. See https://gist.github.com/0xced/56035d2f57254cf518b5.\nSKIPPED_TESTS+=(\"-skip-testing:RNTesterUnitTests/RCTJSONTests/testNotUTF8Convertible\")\n\n# Create cleanup handler\ncleanup() {\n  EXIT=$?\n  set +e\n\n  if [ $EXIT -ne 0 ];\n  then\n    WATCHMAN_LOGS=/usr/local/Cellar/watchman/3.1/var/run/watchman/$USER.log\n    [ -f \"$WATCHMAN_LOGS\" ] && cat \"$WATCHMAN_LOGS\"\n  fi\n  # kill whatever is occupying port 8081 (packager)\n  lsof -i tcp:8081 | awk 'NR!=1 {print $2}' | xargs kill\n  # kill whatever is occupying port 5555 (web socket server)\n  lsof -i tcp:5555 | awk 'NR!=1 {print $2}' | xargs kill\n}\n\n# Wait for the package to start\nwaitForPackager() {\n  local -i max_attempts=60\n  local -i attempt_num=1\n\n  until curl -s http://localhost:8081/status | grep \"packager-status:running\" -q; do\n    if (( attempt_num == max_attempts )); then\n      echo \"Packager did not respond in time. No more attempts left.\"\n      exit 1\n    else\n      (( attempt_num++ ))\n      echo \"Packager did not respond. Retrying for attempt number $attempt_num...\"\n      sleep 1\n    fi\n  done\n\n  echo \"Packager is ready!\"\n}\n\nwaitForWebSocketServer() {\n  local -i max_attempts=60\n  local -i attempt_num=1\n\n  until curl -s http://localhost:5555 | grep \"Upgrade Required\" -q; do\n    if (( attempt_num == max_attempts )); then\n      echo \"WebSocket Server did not respond in time. No more attempts left.\"\n      exit 1\n    else\n      (( attempt_num++ ))\n      echo \"WebSocket Server did not respond. Retrying for attempt number $attempt_num...\"\n      sleep 1\n    fi\n  done\n\n  echo \"WebSocket Server is ready!\"\n}\n\nrunTests() {\n  # shellcheck disable=SC1091\n  source \"$ROOT/scripts/.tests.env\"\n  xcodebuild build test \\\n    -workspace RNTesterPods.xcworkspace \\\n    -scheme RNTester \\\n    -sdk iphonesimulator \\\n    -destination \"platform=iOS Simulator,name=$IOS_DEVICE,OS=$IOS_TARGET_OS\" \\\n      \"${SKIPPED_TESTS[@]}\"\n}\n\nbuildProject() {\n  xcodebuild build \\\n    -workspace RNTesterPods.xcworkspace \\\n    -scheme RNTester \\\n    -sdk iphonesimulator\n}\n\nxcbeautifyFormat() {\n  if [ \"$CI\" ]; then\n    # Circle CI expects JUnit reports to be available here\n    REPORTS_DIR=\"$HOME/react-native/reports/junit\"\n  else\n    THIS_DIR=$(cd -P \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\n\n    # Write reports to the react-native root dir\n    REPORTS_DIR=\"$THIS_DIR/../build/reports\"\n  fi\n\n  xcbeautify --report junit --report-path \"$REPORTS_DIR/ios/results.xml\"\n}\n\npreloadBundlesRNIntegrationTests() {\n  # Preload IntegrationTests bundles (packages/rn-tester/)\n  curl -s 'http://localhost:8081/IntegrationTests/IntegrationTestsApp.bundle?platform=ios&dev=true' -o /dev/null\n  curl -s 'http://localhost:8081/IntegrationTests/RCTRootViewIntegrationTestApp.bundle?platform=ios&dev=true' -o /dev/null\n}\n\npreloadBundlesRNTester() {\n  # Preload RNTesterApp bundles (packages/rn-tester/)\n  curl -s 'http://localhost:8081/js/RNTesterApp.ios.bundle?platform=ios&dev=true' -o /dev/null\n  curl -s 'http://localhost:8081/js/RNTesterApp.ios.bundle?platform=ios&dev=true&minify=false' -o /dev/null\n}\n\nmain() {\n  cd \"$ROOT/packages/rn-tester\" || exit\n\n  # If first argument is \"test\", actually start the packager and run tests.\n  # Otherwise, just build RNTester and exit\n  if [ \"$1\" = \"test\" ]; then\n\n    # Start the WebSocket test server\n    echo \"Launch WebSocket Server\"\n    sh \"./IntegrationTests/launchWebSocketServer.sh\" &\n    waitForWebSocketServer\n\n    # Start the packager\n    yarn start --max-workers=1 || echo \"Can't start packager automatically\" &\n    waitForPackager\n    preloadBundlesRNTester\n    preloadBundlesRNIntegrationTests\n\n    # Build and run tests.\n    if [ -x \"$(command -v xcbeautify)\" ]; then\n      runTests | xcbeautifyFormat && exit \"${PIPESTATUS[0]}\"\n    else\n      echo 'Warning: xcbeautify is not installed. Install xcbeautify to generate JUnit reports.'\n      runTests\n    fi\n  else\n    # Build without running tests.\n    if [ -x \"$(command -v xcbeautify)\" ]; then\n      buildProject | xcbeautifyFormat && exit \"${PIPESTATUS[0]}\"\n    else\n      buildProject\n    fi\n  fi\n}\n\ntrap cleanup EXIT\nmain \"$@\"\n", "num_lines": 157}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -ex\n\nSCRIPTS=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nROOT=\"$(dirname \"$SCRIPTS\")\"\n\n# Specify `SPEC_REPO` as an env variable if you want to push to a specific spec repo.\n# Defaults to `react-test`, which is meant to be a dummy repo used to test that the specs fully lint.\n: \"${SPEC_REPO:=react-test}\"\nSPEC_REPO_DIR=\"$HOME/.cocoapods/repos/$SPEC_REPO\"\n\n# If the `SPEC_REPO` does not exist yet, assume this is purely for testing and create a dummy repo.\nif ! [ -d \"$SPEC_REPO_DIR\" ]; then\n  mkdir -p \"$SPEC_REPO_DIR\"\n  cd \"$SPEC_REPO_DIR\"\n  touch .gitkeep\n  git init\n  git add .\n  git commit -m \"init\"\n  git remote add origin \"https://example.com/$SPEC_REPO.git\"\nfi\n\ncd \"$SPEC_REPO_DIR\"\nSPEC_REPOS=\"$(git remote get-url origin),https://github.com/CocoaPods/Specs.git\"\n\nPOD_LINT_OPT=(--verbose --allow-warnings --fail-fast --private \"--swift-version=3.0\" \"--sources=$SPEC_REPOS\")\n\n# Get the version from a podspec.\nversion() {\n  ruby -rcocoapods-core -rjson -e \"puts Pod::Specification.from_file('$1').version\"\n}\n\n# Lint both framework and static library builds.\nlint() {\n  local SUBSPEC=\"$1\"\n  if [ \"${SUBSPEC:-}\" ]; then\n    local SUBSPEC_OPT=\"--subspec=$SUBSPEC\"\n  fi\n  bundle exec pod lib lint \"$SUBSPEC_OPT\" \"${POD_LINT_OPT[@]}\"\n  bundle exec pod lib lint \"$SUBSPEC_OPT\" \"${POD_LINT_OPT[@]}\" --use-libraries\n}\n\n# Push the spec in arg `$1`, which is expected to be in the cwd, to the `SPEC_REPO` in JSON format.\npush() {\n  local SPEC_NAME POD_NAME SPEC_DIR SPEC_PATH\n  SPEC_NAME=\"$1\"\n  POD_NAME=$(basename \"$SPEC_NAME\" .podspec)\n  SPEC_DIR=\"$SPEC_REPO_DIR/$POD_NAME/$(version \"$SPEC_NAME\")\"\n  SPEC_PATH=\"$SPEC_DIR/$SPEC_NAME.json\"\n  mkdir -p \"$SPEC_DIR\"\n  env INSTALL_YOGA_WITHOUT_PATH_OPTION=1 INSTALL_YOGA_FROM_LOCATION=\"$ROOT\" bundle exec pod ipc spec \"$SPEC_NAME\" > \"$SPEC_PATH\"\n}\n\n# Perform linting and publishing of podspec in cwd.\n# Skip linting with `SKIP_LINT` if e.g. publishing to a private spec repo.\nprocess() {\n  cd \"$1\"\n  if [ -z \"$SKIP_LINT\" ]; then\n    lint \"$2\"\n  fi\n  local SPEC_NAME=(*.podspec)\n  push \"${SPEC_NAME[0]}\"\n}\n\n# Make third-party deps accessible\ncd \"$ROOT/third-party-podspecs\"\npush Folly.podspec\npush DoubleConversion.podspec\npush glog.podspec\n\nprocess \"$ROOT/ReactCommon/yoga\"\nprocess \"$ROOT\" _ignore_me_subspec_for_linting_\n", "num_lines": 78}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Runs an Android emulator locally.\n# If there already is a running emulator, this just uses that.\n# The only reason to use this config is that it represents a known-good\n# virtual device configuration.\n# This is useful for running integration tests on a local machine.\n\nTHIS_DIR=$(cd -P \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\" || echo \"${BASH_SOURCE[0]}\")\")\" && pwd)\n\nSTATE=`adb get-state`\n\nif [ -n \"$STATE\" ]; then\n    echo \"An emulator is already running.\"\n    exit 1\nfi\n\necho \"Installing packages\"\nsource \"${THIS_DIR}/android-setup.sh\" && getAndroidPackages\n\necho \"Creating Android virtual device...\"\nsource \"${THIS_DIR}/android-setup.sh\" && createAVD\n\necho \"Launching Android virtual device...\"\nsource \"${THIS_DIR}/android-setup.sh\" && launchAVD\n", "num_lines": 30}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Runs all Android integration tests locally.\n# See https://reactnative.dev/docs/testing\n\nsource $(dirname $0)/validate-android-sdk.sh\nsource $(dirname $0)/validate-android-test-env.sh\nsource $(dirname $0)/validate-android-device-env.sh\n\nset -e\n\necho \"Compiling native code...\"\n./gradlew :ReactAndroid:packageReactNdkLibsForBuck\n\necho \"Building JS bundle...\"\nnode cli.js bundle --platform android --dev true --entry-file ReactAndroid/src/androidTest/js/TestBundle.js --bundle-output ReactAndroid/src/androidTest/assets/AndroidTestBundle.js\n\necho \"Installing test app on the device...\"\nbuck fetch ReactAndroid/src/androidTest/buck-runner:instrumentation-tests\nbuck install ReactAndroid/src/androidTest/buck-runner:instrumentation-tests\n\necho \"Running integration tests...\"\n# Use the JS script that runs all tests in a loop and is easy to tweak\nnode ./scripts/run-android-ci-instrumentation-tests.js --path ./ReactAndroid/src/androidTest/java/com/facebook/react/tests --package com.facebook.react.tests\n", "num_lines": 29}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Runs all Android unit tests locally.\n# See https://reactnative.dev/docs/testing\n\nsource $(dirname $0)/validate-android-sdk.sh\nsource $(dirname $0)/validate-android-test-env.sh\n\nset -e\n\necho \"Fetching dependencies...\"\nbuck fetch ReactAndroid/src/test/...\n\necho \"Running unit tests...\"\nbuck test ReactAndroid/src/test/...\n", "num_lines": 20}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Python script to run instrumentation tests, copied from https://github.com/circleci/circle-dummy-android\n# Example: ./scripts/run-android-instrumentation-tests.sh com.facebook.react.tests com.facebook.react.tests.ReactPickerTestCase\n\nexport PATH=\"$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH\"\n\n# clear the logs\nadb logcat -c\n\n# run tests and check output\npython - $1 $2 << END\n\nimport re\nimport subprocess as sp\nimport sys\nimport threading\nimport time\n\ndone = False\n\ntest_app = sys.argv[1]\ntest_class = None\n\nif len(sys.argv) > 2:\n  test_class = sys.argv[2]\n\ndef update():\n  # prevent CircleCI from killing the process for inactivity\n  while not done:\n    time.sleep(5)\n    print \"Running in background.  Waiting for 'adb' command response...\"\n\nt = threading.Thread(target=update)\nt.dameon = True\nt.start()\n\ndef run():\n  sp.Popen(['adb', 'wait-for-device']).communicate()\n  if (test_class != None):\n    p = sp.Popen('adb shell am instrument -w -e class %s %s/androidx.test.runner.AndroidJUnitRunner'\n      % (test_class, test_app), shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n  else :\n    p = sp.Popen('adb shell am instrument -w %s/androidx.test.runner.AndroidJUnitRunner'\n      % (test_app), shell=True, stdout=sp.PIPE, stderr=sp.PIPE, stdin=sp.PIPE)\n  return p.communicate()\n\nsuccess = re.compile(r'OK \\(\\d+ test(s)?\\)')\nstdout, stderr = run()\n\ndone = True\nprint stderr\nprint stdout\n\nif success.search(stderr + stdout):\n  sys.exit(0)\nelse:\n  # dump the logs\n  sp.Popen(['adb', 'logcat', '-d']).communicate()\n  sys.exit(1) # make sure we fail if the test failed\nEND\n\nRETVAL=$?\n\nexit $RETVAL\n", "num_lines": 70}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n\nfunction usage {\n  echo \"usage: sync-css-layout.sh <pathToGithubRepo> <pathToFbSourceRepo>\";\n}\n\nfunction patchfile {\n  # Add React Native copyright\n  printf \"/**\\n\"  > /tmp/yogasync.tmp\n  printf \" * Copyright (c) 2014-present, Facebook, Inc.\\n\"  >> /tmp/yogasync.tmp\n  printf \" *\\n\" >> /tmp/yogasync.tmp\n  printf \" * This source code is licensed under the MIT license found in the\\n\"  >> /tmp/yogasync.tmp\n  printf \" * LICENSE file in the root directory of this source tree.\\n\"  >> /tmp/yogasync.tmp\n  printf \" */\\n\\n\"  >> /tmp/yogasync.tmp\n  printf \"// NOTE: this file is auto-copied from https://github.com/facebook/css-layout\\n\" >> /tmp/yogasync.tmp\n  # The following is split over four lines so Phabricator doesn't think this file is generated\n  printf \"// @g\" >> /tmp/yogasync.tmp\n  printf \"enerated <<S\" >> /tmp/yogasync.tmp\n  printf \"ignedSource::*O*zOeWoEQle#+L\" >> /tmp/yogasync.tmp\n  printf \"!plEphiEmie@IsG>>\\n\\n\" >> /tmp/yogasync.tmp\n  tail -n +9 $1 >> /tmp/yogasync.tmp\n  mv /tmp/yogasync.tmp $1\n  \"$ROOT\"/tools/signedsource.py sign \"$1\"\n}\n\nif [ -z $1 ]; then\n  usage\n  exit 1\nfi\n\nif [ -z $2 ]; then\n  usage\n  exit 1\nfi\n\nGITHUB=$1\nROOT=$2\n\nset -e # exit if any command fails\n\necho \"Making github project...\"\npushd $GITHUB\nCOMMIT_ID=$(git rev-parse HEAD)\npopd\n\nC_SRC=$GITHUB/src/\nJAVA_SRC=$GITHUB/src/java/src/com/facebook/yoga\nTESTS=$GITHUB/src/java/tests/com/facebook/yoga\nFBA_SRC=$ROOT/xplat/js/react-native-github/packages/react-native/ReactAndroid/src/main/java/com/facebook/yoga/\nFBA_TESTS=$ROOT/fbandroid/javatests/com/facebook/yoga/\nFBO_SRC=$ROOT/xplat/js/react-native-github/packages/react-native/React/Layout/\n\necho \"Copying fbandroid src files over...\"\ncp $JAVA_SRC/*.java $FBA_SRC\necho \"Copying fbandroid test files over...\"\ncp $TESTS/*.java $FBA_TESTS\necho \"Copying fbobjc src files over...\"\ncp $C_SRC/Layout.{c,h} $FBO_SRC\n\necho \"Patching files...\"\nfor sourcefile in $FBA_SRC/*.java; do\n  patchfile $sourcefile\ndone\nfor testfile in $FBA_TESTS/*.java; do\n  patchfile $testfile\ndone\nfor sourcefile in $FBO_SRC/Layout.{c,h}; do\n  patchfile $sourcefile\ndone\n\necho \"Writing README\"\n\necho \"The source of truth for css-layout is: https://github.com/facebook/css-layout\n\nThe code here should be kept in sync with GitHub.\nHEAD at the time this code was synced: https://github.com/facebook/css-layout/commit/$COMMIT_ID\n\nThere is generated code in:\n - README (this file)\n - fbandroid/java/com/facebook/yoga\n - fbandroid/javatests/com/facebook/yoga\n - xplat/js/react-native-github/React/Layout\n\nThe code was generated by running 'make' in the css-layout folder and running:\n\n  scripts/sync-css-layout.sh <pathToGithubRepo> <pathToFbSourceRepo>\n\" > /tmp/yogasync.tmp\n\ncp /tmp/yogasync.tmp \"$FBA_SRC/README\"\ncp /tmp/yogasync.tmp \"$FBO_SRC/README\"\n", "num_lines": 96}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script updates RNTester Podfile.lock after verifying the CocoaPods environment.\n# Usage:\n#   source scripts/update_podfile_lock && update_pods\n\nTHIS_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nRNTESTER_DIR=\"$THIS_DIR/../packages/rn-tester\"\n\n# Keep this separate for FB internal access.\nvalidate_env () {\n  cd \"$RNTESTER_DIR\" || exit\n  bundle check || exit\n  cd \"$THIS_DIR\" || exit\n}\n\nupdate_pods () {\n  cd \"$RNTESTER_DIR\" || exit\n  bundle install || exit\n  bundle check || exit\n  bundle exec pod install\n  cd \"$THIS_DIR\" || exit\n}\n", "num_lines": 28}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script validates that the Android environment is set up to run\n# tests on a device or emulator (as opposed to a plain Java environment).\n\n# This requires that the Android NDK is set up correctly and it also\n# requires that you are currently either running an emulator or have\n# an Android device plugged in.\n\nif [ -z \"$ANDROID_NDK\" ]; then\n  echo \"Error: \\$ANDROID_NDK is not configured.\"\n  echo \"You must first install the Android NDK and then set \\$ANDROID_NDK.\"\n  echo \"If you already installed the Android SDK, well, the NDK is a different thing that you also need to install.\"\n  echo \"See https://reactnative.dev/contributing/how-to-build-from-source for instructions.\"\n  exit 1\nfi\n\nif [ -z \"$(adb get-state)\" ]; then\n  echo \"Error: you must either run an emulator or connect a device.\"\n  echo \"You can check what devices are running with 'adb get-state'.\"\n  echo \"You can run scripts/run-android-emulator.sh to get a known-good emulator config.\"\n  exit 1\nfi\n\nwhile :\ndo\n    BOOTANIM=$(adb -e shell getprop init.svc.bootanim)\n    # shellcheck disable=SC2143\n    if [[ -n $(echo \"$BOOTANIM\" | grep stopped) ]]; then\n        break\n    fi\n    echo \"Waiting for the emulator to finish booting...\"\n    sleep 3\ndone\n", "num_lines": 39}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script validates that the Android SDK is installed correctly.\n# This means setting ANDROID_HOME and adding its subdirectories to PATH.\n# If the Android SDK is not installed correctly, this script exits\n# with an error and a helpful message is printed.\n\nif [ -z \"$ANDROID_HOME\" ]; then\n  echo \"Error: \\$ANDROID_HOME is not configured.\"\n  echo \"You must first install the Android SDK and then set \\$ANDROID_HOME.\"\n  echo \"If you already installed the Android SDK, the problem is that you need to export ANDROID_HOME from your .bashrc or equivalent.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\nif [ ! -d \"$ANDROID_HOME\" ]; then\n  echo \"Error: \\$ANDROID_HOME = $ANDROID_HOME but that directory does not exist.\"\n  echo \"It is possible that you installed then uninstalled the Android SDK.\"\n  echo \"In that case, you should reinstall it.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\nif [ ! -e \"$ANDROID_HOME/tools/emulator\" ]; then\n  echo \"Error: could not find an emulator at \\$ANDROID_HOME/tools/emulator.\"\n  echo \"Specifically, $ANDROID_HOME/tools/emulator does not exist.\"\n  echo \"This indicates something is broken with your Android SDK install.\"\n  echo \"One possibility is that you have \\$ANDROID_HOME set to the wrong value.\"\n  echo \"If that seems correct, you might want to try reinstalling the Android SDK.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\nif [ -z `which emulator` ]; then\n  echo \"Error: could not find 'emulator'. Specifically, 'which emulator' was empty.\"\n  echo \"However, the emulator seems to be installed at \\$ANDROID_HOME/tools/emulator already.\"\n  echo \"This means that the problem is that you are not adding \\$ANDROID_HOME/tools to your \\$PATH.\"\n  echo \"You should do that, and then rerun this command.\"\n  echo \"Sorry for not fixing this automatically - we just didn't want to mess with your \\$PATH automatically because that can break things.\"\n  exit 1\nfi\n\nif [ -z `which adb` ]; then\n  echo \"Error: could not find 'adb'. Specifically, 'which adb' was empty.\"\n  echo \"This indicates something is broken with your Android SDK install.\"\n  echo \"The most likely problem is that you are not adding \\$ANDROID_HOME/platform-tools to your \\$PATH.\"\n  echo \"If all else fails, try reinstalling the Android SDK.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n", "num_lines": 55}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script validates that Android is set up correctly for the\n# testing environment.\n#\n# In particular, the config in ReactAndroid/build.gradle must match\n# the android sdk that is actually installed. Also, we must have the\n# right version of Java.\n\n# Check that Buck is working.\nif [ -z \"$(which buck)\" ]; then\n  echo \"You need to install Buck.\"\n  echo \"See https://buckbuild.com/setup/getting_started.html for instructions.\"\n  exit 1\nfi\n\nif [ -z \"$(buck --version)\" ]; then\n  echo \"Your Buck install is broken.\"\n\n  if [ -d \"/opt/facebook\" ]; then\n    BUCK_SUGGESTED_COMMIT_FB=\"b9b76a3a5a086eb440a26d1db9b0731875975099\"\n    echo \"FB laptops ship with a Buck config that is not compatible with open \"\n    echo \"source. FB Buck requires the environment to set a buck version, but \"\n    echo \"the open source version of Buck forbids that.\"\n    echo\n    echo \"You can try setting:\"\n    echo\n    echo \"export BUCKVERSION=${BUCK_SUGGESTED_COMMIT_FB}\"\n    echo\n    echo \"in your .bashrc or .bash_profile to fix this.\"\n    echo\n    echo \"If you don't want to alter BUCKVERSION for other things running on\"\n    echo \"your machine, you can just scope it to a single script, for example\"\n    echo \"by running something like:\"\n    echo\n    echo \"BUCKVERSION=${BUCK_SUGGESTED_COMMIT_FB} $0\"\n    echo\n  else\n    echo \"I don't know what's wrong, but calling 'buck --version' should work.\"\n  fi\n  exit 1\nelse\n  BUCK_EXPECTED_VERSION=\"buck version d743d2d0229852ce7c029ec257532d8916f6b2b7\"\n  if [ \"$(buck --version)\" != \"$BUCK_EXPECTED_VERSION\" ]; then\n    if [ ! -d \"/opt/facebook\" ]; then\n      echo \"Warning: The test suite expects ${BUCK_EXPECTED_VERSION} to be installed\"\n    fi\n  fi\nfi\n\n# MAJOR is something like \"23\"\nMAJOR=`grep compileSdkVersion $(dirname $0)/../ReactAndroid/build.gradle | sed 's/[^[:digit:]]//g'`\n\n# Check that we have the right major version of the Android SDK.\nPLATFORM_DIR=\"$ANDROID_HOME/platforms/android-$MAJOR\"\nif [ ! -e \"$PLATFORM_DIR\" ]; then\n  echo \"Error: could not find version $ANDROID_VERSION of the Android SDK.\"\n  echo \"Specifically, the directory $PLATFORM_DIR does not exist.\"\n  echo \"You probably need to specify the right version using the SDK Manager from within Android Studio.\"\n  echo \"See https://reactnative.dev/docs/getting-started.html for details.\"\n  echo \"If you are using Android SDK Tools from the command line, you may need to run:\"\n  echo\n  echo \"  sdkmanager \\\"platform-tools\\\" \\\"platform-tools;android-$MAJOR\\\"\"\n  echo\n  echo \"Check out https://developer.android.com/studio/command-line/sdkmanager.html for details.\"\n  exit 1\nfi\n\n# Check that we have the right version of the build tools.\nBT_DIR=\"$ANDROID_HOME/build-tools/$ANDROID_SDK_BUILD_TOOLS_REVISION\"\nif [ ! -e \"$BT_DIR\" ]; then\n  echo \"Error: could not find version $ANDROID_SDK_BUILD_TOOLS_REVISION of the Android build tools.\"\n  echo \"Specifically, the directory $BT_DIR does not exist.\"\n  echo \"You probably need to explicitly install the correct version of the Android SDK Build Tools from within Android Studio.\"\n  echo \"See https://reactnative.dev/docs/getting-started.html for details.\"\n  echo \"If you are using Android SDK Tools from the command line, you may need to run:\"\n  echo\n  echo \"  sdkmanager \\\"platform-tools\\\" \\\"build-tools;android-$ANDROID_SDK_BUILD_TOOLS_REVISION\\\"\"\n  echo\n  echo \"Check out https://developer.android.com/studio/command-line/sdkmanager.html for details.\"\n  exit 1\nfi\n\nif [ -n \"$(which csrutil)\" ]; then\n  # This is a SIP-protected machine (recent OSX).\n  # Check that we are not using SIP-protected Java.\n  JAVA=`which java`\n  if [ \"$JAVA\" = \"/usr/bin/java\" ]; then\n    echo \"Error: we can't use this Java version.\"\n    echo \"Currently, Java runs from $JAVA.\"\n    echo \"The operating-system-provided Java doesn't work with React Native because of SIP protection.\"\n    echo \"Please install the Oracle Java Development Kit 8.\"\n    if [ -d \"/opt/facebook\" ]; then\n      echo \"See https://our.intern.facebook.com/intern/dex/installing-java-8/ for instructions on installing Java 8 on FB laptops.\"\n    else\n      echo \"Check out http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html .\"\n      echo \"Be sure that you set JAVA_HOME and PATH correctly in your .bashrc or equivalent. Example:\"\n      echo\n      echo \"  export JAVA_HOME=path/to/java\"\n      echo \"  export PATH=\\$PATH:\\$JAVA_HOME/bin\"\n      echo\n    fi\n    echo \"After installing Java, run 'buck kill' and 'buck clean'.\"\n    exit 1\n  fi\nfi\n\nif [ -z \"$JAVA_HOME\" ]; then\n  echo \"Error: \\$JAVA_HOME is not configured.\"\n  echo \"Try adding export JAVA_HOME=\\$(/usr/libexec/java_home) to your .bashrc or equivalent.\"\n  echo \"You will also want to add \\$JAVA_HOME/bin to your path.\"\n  exit 1\nfi\n", "num_lines": 118}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This script validates that iOS is set up correctly for the\n# testing environment.\n#\n# In particular, it checks that the minimum required Xcode version is installed.\n# It also checks that the correct Node version is installed.\n\n# Function used to compare dot separated version numbers\nfunction version_gt() { test \"$(printf '%s\\n' \"$@\" | sort -V | head -n 1)\" != \"$1\"; }\n\n# Check that node is installed.\nif [ -z \"$(which node)\" ]; then\n  echo \"Could not find Node binary. Please check your nodejs install.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\n# Check that the correct version of node is installed\nNODE_VERSION=\"$(command node --version | sed 's/[-/a-zA-Z]//g' |sed 's/.\\{2\\}$//')\"\n\nif (( $(echo \"${NODE_VERSION} < 14.0\" | bc -l) )); then\n  echo \"Node ${NODE_VERSION} detected. This version of Node is not supported.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\n# Check that Xcode is installed.\nif [ -z \"$(which xcodebuild)\" ]; then\n  echo \"Could not find Xcode build tools. Please check your Xcode install.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n\nMIN_XCODE_VERSION=9.4\n# Check that the correct version of Xcode is installed\nXCODE_VERSION=\"$(command xcodebuild -version | sed '$ d' | sed 's/[-/a-zA-Z]//g')\"\nif (version_gt $MIN_XCODE_VERSION $XCODE_VERSION) && [ \"$XCODE_VERSION\" != \"$MIN_XCODE_VERSION\" ]; then\n  echo \"Xcode ${XCODE_VERSION} detected. React Native requires ${MIN_XCODE_VERSION} or newer.\"\n  echo \"Older versions of Xcode may cause cryptic build errors.\"\n  echo \"See https://reactnative.dev/docs/getting-started for instructions.\"\n  exit 1\nfi\n", "num_lines": 48}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nGITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook}\nGITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native}\nexport GITHUB_OWNER\nexport GITHUB_REPO\n\ncat <(echo eslint; npm run lint --silent -- --format=json; echo flow; npm run flow-check-ios --silent --json; echo flow; npm run flow-check-android --silent --json; echo google-java-format; node scripts/lint-java.js --diff) | GITHUB_PR_NUMBER=\"$CIRCLE_PR_NUMBER\" node packages/react-native-bots/code-analysis-bot.js\n\nSTATUS=$?\nif [ $STATUS == 0 ]; then\n  echo \"Code analyzed successfully.\"\nelse\n  echo \"Code analysis failed, error status $STATUS.\"\nfi\n", "num_lines": 20}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nGITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook}\nGITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native}\nexport GITHUB_OWNER\nexport GITHUB_REPO\n\nif [ -x \"$(command -v shellcheck)\" ]; then\n  IFS=$'\\n'\n\n  if [ -n \"$CIRCLE_CI\" ]; then\n    results=( \"$(find . -type f -not -path \"*node_modules*\" -not -path \"*third-party*\" -name '*.sh' -exec sh -c  'shellcheck \"$1\" -f json' -- {} \\;)\" )\n\n    cat <(echo shellcheck; printf '%s\\n' \"${results[@]}\" | jq .,[] | jq -s . | jq --compact-output --raw-output '[ (.[] | .[] | . ) ]') | GITHUB_PR_NUMBER=\"$CIRCLE_PR_NUMBER\" node scripts/circleci/code-analysis-bot.js\n\n    # check status\n    STATUS=$?\n    if [ $STATUS == 0 ]; then\n      echo \"Shell scripts analyzed successfully.\"\n    else\n      echo \"Shell script analysis failed, error status $STATUS.\"\n    fi\n\n  else\n    find . \\\n      -type f \\\n      -not -path \"*node_modules*\" \\\n      -not -path \"*third-party*\" \\\n      -name '*.sh' \\\n    -exec sh -c 'shellcheck \"$1\"' -- {} \\;\n  fi\n\nelse\n  echo 'shellcheck is not installed. See https://github.com/facebook/react-native/wiki/Development-Dependencies#shellcheck for instructions.'\n  exit 1\nfi\n\n", "num_lines": 42}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\necho \"Downloading package lists...\"\nsudo apt-get update -y\n\nif ! [[ -d ~/vendor/apt ]]; then\n  mkdir -p ~/vendor/apt\nfi\n\n# First check for archives cache\nif ! [[ -d ~/vendor/apt/archives ]]; then\n  # It doesn't so download the packages\n  echo \"Downloading build dependencies...\"\n  sudo apt-get install --download-only ant autoconf automake g++ gcc libqt5widgets5 lib32z1 lib32stdc++6 make maven python-dev python3-dev qml-module-qtquick-controls qtdeclarative5-dev libpulse0 file -y\n  # Then move them to our cache directory\n  sudo cp -R /var/cache/apt ~/vendor/\n  # Making sure our user has ownership, in order to cache\n  sudo chown -R ${USER:=$(/usr/bin/id -run)}:$USER ~/vendor/apt\nfi\n\n# Install all packages in the cache\necho \"Installing build dependencies...\"\nsudo dpkg -i ~/vendor/apt/archives/*.deb\n", "num_lines": 30}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# Make sure we don't introduce accidental references to PATENTS.\nEXPECTED='scripts/circleci/check_license.sh'\nACTUAL=$(git grep -l PATENTS)\n\nif [ \"$EXPECTED\" != \"$ACTUAL\" ]; then\n  echo \"PATENTS crept into some new files?\"\n  diff -u <(echo \"$EXPECTED\") <(echo \"$ACTUAL\") || true\n  exit 1\nfi\n", "num_lines": 18}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# execute command\n\"$@\"\n\n# check status\nSTATUS=$?\nif [ $STATUS == 0 ]; then\n  echo \"Command \" \"$@\" \" completed successfully\"\nelse\n  echo \"Command \" \"$@\" \" exited with error status $STATUS\"\nfi\n", "num_lines": 17}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nGITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook} \\\nGITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native} \\\nGITHUB_PR_NUMBER=\"${CIRCLE_PR_NUMBER:-${CIRCLE_PULL_REQUEST##*/}}\" \\\nGITHUB_REF=${CIRCLE_BRANCH} \\\nGITHUB_SHA=${CIRCLE_SHA1} \\\nexec node packages/react-native-bots/post-artifacts-link.js\n", "num_lines": 13}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncase $1 in\n  \"android\" | \"ios\")\n    GITHUB_OWNER=${CIRCLE_PROJECT_USERNAME:-facebook} \\\n    GITHUB_REPO=${CIRCLE_PROJECT_REPONAME:-react-native} \\\n    GITHUB_PR_NUMBER=\"${CIRCLE_PR_NUMBER:-${CIRCLE_PULL_REQUEST##*/}}\" \\\n    GITHUB_REF=${CIRCLE_BRANCH} \\\n    GITHUB_SHA=${CIRCLE_SHA1} \\\n    exec node packages/react-native-bots/report-bundle-size.js \"$1\"\n    ;;\n  *)\n    echo \"Syntax: $0 [android | ios]\"\n    exit 1\nesac\n", "num_lines": 20}
{"repo_name": "react-native", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Abort the mission if any command fails\nset -e\n\n# Allow the script to be invoked from various environments\nif [[ -z \"${OVERRIDE_YARN_BINARY}\" ]]; then\n  YARN_BINARY=$(command -v yarn)\nelse\n  YARN_BINARY=\"${OVERRIDE_YARN_BINARY}\"\nfi\n\nREACT_NATIVE_TEMP_DIR=$(mktemp -d /tmp/react-native-XXXXXXXX)\n\nfunction cleanup {\n  set +e\n  rm -rf \"$REACT_NATIVE_TEMP_DIR\"\n  set -e\n}\n\nfunction msg {\n  echo -e \" \"\n  echo -e \"\\\\x1B[36m${1}\\\\x1B[0m\";\n  echo -e \"\\\\x1B[36m${1//?/=}\\\\x1B[0m\"\n}\n\ntrap cleanup EXIT\n\ncp -R ./package.json \"$REACT_NATIVE_TEMP_DIR\"\ncp -R ./yarn.lock \"$REACT_NATIVE_TEMP_DIR\"\npushd \"$REACT_NATIVE_TEMP_DIR\" >/dev/null\n\nif ! $YARN_BINARY --ignore-scripts --silent --non-interactive --mutex network --frozen-lockfile; then\n  msg \"Yarn validation failed.\"\n  echo \"This means the package.json and yarn.lock disagree in some way.\"\n  echo \"Try fixing it by running \\`yarn\\` and committing the changes.\"\nfi\n\npopd >/dev/null\n", "num_lines": 44}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ -f \"generated_apilevels.py\" ] ; then\n  GEN_APILEVELS_INPUT=\"generated_apilevels.py\"\nelse\n  GEN_APILEVELS_INPUT=\nfi\n\ntar czf redex.tar.gz redex-all redex.py pyredex/*.py $GEN_APILEVELS_INPUT\ncat selfextract.sh redex.tar.gz > redex\nchmod +x redex\n", "num_lines": 16}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nBOOST_VERSION=\"1.71.0\"\n\nBOOST_VERSION_UNDERSCORE=\"${BOOST_VERSION//./_}\"\nBOOST_FILE=\"boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2\"\nBOOST_TAR_URL=\"https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION}/source/${BOOST_FILE}\"\nBOOST_CACHE_DIR=\"boost_cache\"\nBOOST_TAR_LOCAL=\"${BOOST_CACHE_DIR}/${BOOST_FILE}\"\nBOOST_DIR=\"boost_${BOOST_VERSION_UNDERSCORE}\"\n\nset -e\n\n# Check for cached artifacts.\nif [ ! -d \"$BOOST_CACHE_DIR\" ] ; then\n  mkdir boost_cache\nfi\nif [ ! -f \"$BOOST_TAR_LOCAL\" ] ; then\n  wget \"$BOOST_TAR_URL\" -O \"$BOOST_TAR_LOCAL\"\nfi\n\ntar --bzip2 -xf \"$BOOST_TAR_LOCAL\"\n\ncd \"$BOOST_DIR\"\n./bootstrap.sh --with-libraries=filesystem,iostreams,program_options,regex,system,thread\n./b2 -j 4 -d0 install\n", "num_lines": 31}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nexport TMPDIR=`mktemp -d /tmp/redex.XXXXXX`\nARCHIVE=`awk '/^__ARCHIVE_BELOW__/ { print NR + 1; exit 0 }' $0`\ntail -n+$ARCHIVE $0 | tar xz -C $TMPDIR\n\n$TMPDIR/redex.py $@\n\nrm -rf $TMPDIR\nexit 0\n\n__ARCHIVE_BELOW__\n", "num_lines": 17}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Set-up the dependencies necessary to build and run Redex on Ubuntu 16.04\n# Xenial, using APT for software management.\n\n# Exit on any command failing\nset -e\n\n# Root directory of repository\nROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null 2>&1 && pwd)\"\n\n# Temporary directory for toolchain sources. Build artifacts will be\n# installed to /usr/local.\nTMP=$(mktemp -d 2>/dev/null)\ntrap 'rm -r $TMP' EXIT\n\nif [ \"$1\" = \"32\" ] ; then\n  BITNESS=\"32\"\n  BITNESS_SUFFIX=\":i386\"\n  BITNESS_CONFIGURE=\"--host=i686-linux-gnu CFLAGS=-m32 CXXFLAGS=-m32 LDFLAGS=-m32\"\n  BITNESS_PKGS=\"gcc-multilib g++-multilib\"\n\n  echo \"Use --host=i686-linux-gnu CFLAGS=-m32 CXXFLAGS=-m32 LDFLAGS=-m32 for ./configure\"\nelse\n  BITNESS=\"64\"  # Assumption here, really means host-preferred arch.\n  BITNESS_SUFFIX=\":\"\n  BITNESS_CONFIGURE=\"\"\n  BITNESS_PKGS=\"\"\nfi\n\nBOOST_DEB_UBUNTU_PKGS=\"libboost-filesystem-dev$BITNESS_SUFFIX\n                       libboost-iostreams-dev$BITNESS_SUFFIX\n                       libboost-program-options-dev$BITNESS_SUFFIX\n                       libboost-regex-dev$BITNESS_SUFFIX\n                       libboost-system-dev$BITNESS_SUFFIX\n                       libboost-thread-dev$BITNESS_SUFFIX\"\n\nfunction install_python36_from_source {\n    pushd \"$TMP\"\n    wget https://www.python.org/ftp/python/3.6.10/Python-3.6.10.tgz\n    tar -xvf Python-3.6.10.tgz\n    pushd Python-3.6.10\n\n    # Always compile Python as host-preferred.\n    ./configure\n    make V=0 && make install V=0\n}\n\nfunction install_boost_from_source {\n    pushd \"$TMP\"\n    \"$ROOT\"/get_boost.sh\n}\n\nfunction install_protobuf3_from_source {\n    pushd \"$TMP\"\n    wget https://github.com/protocolbuffers/protobuf/releases/download/v3.17.3/protobuf-cpp-3.17.3.tar.gz\n    tar -xvf protobuf-cpp-3.17.3.tar.gz --no-same-owner\n\n    pushd protobuf-3.17.3\n    ./configure $BITNESS_CONFIGURE\n    make -j 4 V=0 && make install V=0\n}\n\nfunction install_from_apt {\n  PKGS=\"autoconf\n        autoconf-archive\n        automake\n        binutils-dev\n        bzip2\n        ca-certificates\n        g++\n        libiberty-dev$BITNESS_SUFFIX\n        libjemalloc-dev$BITNESS_SUFFIX\n        libjsoncpp-dev$BITNESS_SUFFIX\n        liblz4-dev$BITNESS_SUFFIX\n        liblzma-dev$BITNESS_SUFFIX\n        libtool\n        make\n        wget\n        zlib1g-dev$BITNESS_SUFFIX $BITNESS_PKGS $*\"\n  apt-get update\n  apt-get install --no-install-recommends -y ${PKGS}\n}\n\nfunction handle_debian {\n    case $1 in\n        [1-9])\n            echo \"Unsupported Debian version $1\"\n            exit 1\n            ;;\n        10)\n            if [ \"$BITNESS\" == \"32\" ] ; then\n                echo \"32-bit compile unsupported because of boost\"\n                exit 1\n            fi\n            install_from_apt python3\n            install_boost_from_source\n            install_protobuf3_from_source\n            ;;\n        *)\n            install_from_apt ${BOOST_DEB_UBUNTU_PKGS} python3\n            install_protobuf3_from_source\n            ;;\n    esac\n}\n\nfunction handle_ubuntu {\n    case $1 in\n        1[7-9]*)\n            if [ \"$BITNESS\" == \"32\" ] ; then\n                echo \"32-bit compile unsupported because of boost\"\n                exit 1\n            fi\n            install_from_apt python3\n            install_boost_from_source\n            install_protobuf3_from_source\n            ;;\n        2*)\n            install_from_apt ${BOOST_DEB_UBUNTU_PKGS} python3\n            install_protobuf3_from_source\n            ;;\n        *)\n            echo \"Unsupported Ubuntu version $1\"\n            exit 1\n            ;;\n    esac\n}\n\n# Read ID and VERSION_ID from /etc/os-release.\ndeclare $(grep -E '^(ID|VERSION_ID)=' /etc/os-release | xargs)\n\ncase $ID in\nubuntu)\n    handle_ubuntu \"$VERSION_ID\"\n    ;;\ndebian)\n    handle_debian \"$VERSION_ID\"\n    ;;\n*)\n    echo \"Unsupported OS $ID - $VERSION_ID\"\n    exit 1\nesac\n", "num_lines": 147}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Ensure the toolchain has been set-up on entry into the container.  Intended\n# for use with the \"run\" script, which correctly sets up the volume.\n\n[[ -f \"$HOME/.setup_complete\" ]] || (\n  pushd /redex >/dev/null &&\n  ./setup_oss_toolchain.sh &&\n  autoreconf -ivf &&\n  ./configure CXX='g++-5' &&\n  touch \"$HOME/.setup_complete\"\n)\n\nexec \"$@\"\n", "num_lines": 19}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nBOOST_VERSION=\"1.71.0\"\n\nBOOST_VERSION_UNDERSCORE=\"${BOOST_VERSION//./_}\"\nBOOST_FILE=\"boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2\"\nBOOST_TAR_URL=\"https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION}/source/${BOOST_FILE}\"\nBOOST_DIR=\"boost_${BOOST_VERSION_UNDERSCORE}\"\n\nset -e\n\nwget \"$BOOST_TAR_URL\" -O \"$BOOST_FILE\"\ntar --bzip2 -xf \"$BOOST_FILE\"\ncd \"$BOOST_DIR\"\n./bootstrap.sh --with-libraries=thread\n./b2 -d0 install\n", "num_lines": 21}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -x\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\npwd\n\nPASSES=$(../redex-all --show-passes | grep 'Registered passes' | sed -e 's/.* //')\nif [ \"$PASSES\" -eq 0 ] ; then\n  echo \"No passes!\"\n  exit 1\nfi\n", "num_lines": 16}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nREDEX=$(dirname $0)/../redex.py\nif [ ! -f \"$REDEX\" ]; then\n    echo \"Couldn't find redex\"\n    exit 1\nfi\n\nif [ $# != 2 ]; then\n    echo \"Usage: compare_bits.sh apk1 apk2\"\n    exit 1\nfi\n\nDEX1=$($REDEX -u $1 2>&1 | grep ^DEX | cut -d' ' -f 2)\nDEX2=$($REDEX -u $2 2>&1 | grep ^DEX | cut -d' ' -f 2)\n\ndiff -r $DEX1 $DEX2\n", "num_lines": 22}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nif [ $# -ne 1 ]; then\n  echo \"usage: compare_diff_bits.sh <apk>\"\n  exit 1\nfi\n\nAPK=$1\n\n# REDEX_ROOT will be \"native/redex\" or \"native/redex-stable\"\nREDEX_ROOT=native/$(basename \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\")\nif [ \"$REDEX_ROOT\" != \"native/redex\" ] && [ \"$REDEX_ROOT\" != \"native/redex-stable\" ]; then\n  echo \"Unexpected REDEX_ROOT: $REDEX_ROOT\"\n  exit 1\nfi\n\nSCRIPT_PATH=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nDIFF_HASH=\"$(hg log -l1 -T{node})\"\nDIFF_OUT=\"$(mktemp).diff.apk\"\n\nhg up -q -r 'ancestor(master, .)'\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to hg up to base commit\"\n  exit 1\nfi\n\nBASE_HASH=\"$(hg log -l1 -T{node})\"\nBASE_OUT=\"$(mktemp).base.apk\"\n\necho \"Will compare base $BASE_HASH to diff $DIFF_HASH\"\n\necho \"Redexing with base $BASE_HASH\"\n\nbuck build $REDEX_ROOT:redex-all 2> /dev/null > /dev/null\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to build base redex\"\n  exit 1\nfi\n\n$REDEX_ROOT/facebook/fb-redex  --redex-binary buck-out/gen/$REDEX_ROOT/redex-all  -c $REDEX_ROOT/facebook/config/fb4a.config --o $BASE_OUT $APK 2> /dev/null > /dev/null\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to redex apk with base\"\n  exit 1\nfi\n\nhg up -q -r $DIFF_HASH\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to hg up to diff commit\"\n  exit 1\nfi\n\necho \"Redexing with diff $DIFF_HASH\"\n\nbuck build $REDEX_ROOT:redex-all 2> /dev/null > /dev/null\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to build diff redex\"\n  exit 1\nfi\n\n$REDEX_ROOT/facebook/fb-redex  --redex-binary buck-out/gen/$REDEX_ROOT/redex-all  -c $REDEX_ROOT/facebook/config/fb4a.config --o $DIFF_OUT $APK 2> /dev/null > /dev/null\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to redex apk with diff\"\n  exit 1\nfi\n\necho \"Comparing bits of base apk $BASE_OUT to diff apk $DIFF_OUT\"\n\nESC=\"\\x1b[\"\nRESET=\"39;49;00m\"\nRED=\"31;01m\"\nGREEN=\"32;01m\"\n\n$SCRIPT_PATH/compare_bits.sh $BASE_OUT $DIFF_OUT 2> /dev/null > /dev/null\n\nif [ $? -ne 0 ]; then\n    echo -e $ESC$RED\"Diff changes the output APK relative to base.\"$ESC$RESET\nelse\n    echo -e $ESC$GREEN\"Diff does not change the output APK relative to base.\"$ESC$RESET\nfi\n", "num_lines": 91}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -o pipefail\n\n# This script takes either two dexes, two APKs, or two text files which have\n# the output of dexdump, and returns a diff of the two with extraneous info\n# (like addresses) filtered out .\n\nINPUT_A=$1\nINPUT_B=$2\n\nIGNORE_RENAME=false\nif [[ \"$3\" == '--ignore-rename' ]]\nthen\n  IGNORE_RENAME=true\nfi\n\n# The script requires dexdump.\ncommand -v dexdump >/dev/null 2>&1 || { echo \"Dexdump not found!\" ; exit 2; }\n\nTEMPDIR=`mktemp -d 2>/dev/null || mktemp -d -t 'extractdexdump'`\n\nfunction strip_cruft() {\n    local GET_DUMP_CMD=\"$1\"\n    local OUT=\"$2\"\n    local RENAME_CLASS=''\n    local RENAME_CLASS_DEFINITION=''\n    if [ $IGNORE_RENAME == true ]\n    then\n        RENAME_CLASS='s/LX\\/...;/LX\\/xxx;/g'\n        RENAME_CLASS_DEFINITION='s/X\\..../X\\.xxx/g'\n    fi\n    echo Running $GET_DUMP_CMD\n    $GET_DUMP_CMD | \\\n        sed 's/^Processing .*dex//' | \\\n        sed 's/^Opened .*dex//' | \\\n        sed 's/^  source_file_idx   : [0-9]* /  source_file_idx   : /' | \\\n        sed 's/^.*|/|/' | \\\n        sed 's/|\\[[0-9a-f]*\\]/|\\[\\]/' | \\\n        sed 's/^Class #[0-9]*/Class/' | \\\n        sed 's/type@[0-9a-f]*/type@/' | \\\n        sed 's/string@[0-9a-f]*/string@/' | \\\n        sed 's/method@[0-9a-f]*/method@/' | \\\n        sed 's/field@[0-9a-f]*/field@/' | \\\n        sed \"$RENAME_CLASS\" | \\\n        sed \"$RENAME_CLASS_DEFINITION\" | \\\n        sed 's/0x[0-9a-f]* line=[0-9]*//' | \\\n        sed 's/^|[0-9a-f]*:/|:/' | \\\n        sed '/^\\s*$/d' \\\n        > \"$OUT\"\n}\n\n# Compare dexfiles in the folder1 and folder2.\nfunction compare_ir_folder() {\n    folder1=$1\n    folder2=$2\n    dex_count1=$(find \"$folder1\" -name '*.dex'|wc -l)\n    dex_count2=$(find \"$folder2\" -name '*.dex'|wc -l)\n    if [ \"$dex_count1\" -ne \"$dex_count2\" ]\n    then\n        echo \"[x] Different dex files count, $dex_count1 in $folder1, $dex_count2 in $folder2\"\n        exit 1\n    fi\n\n    for folder in $folder1 $folder2\n    do\n        for file in irmeta.bin entry.json\n        do\n            if [ ! -f \"$folder/$file\" ]\n            then\n                echo \"[x] $folder/$file is missing\"\n                exit 1\n            fi\n        done\n    done\n\n    # Compare dex files and irmeta.bin. Check md5sum before running dexdump.\n    EXIT_STATUS=0\n    cd \"$folder1\" || exit\n    md5sum ./*.dex irmeta.bin > \"$TEMPDIR/md5.txt\"\n    cd \"$folder2\" || exit\n    files=$(md5sum -c \"$TEMPDIR/md5.txt\" --quiet 2>/dev/null | awk -F: '{print $1}')\n\n    cd \"$TEMPDIR\" || exit\n    for f in $files\n    do\n        if [ \"$f\" = irmeta.bin ]; then\n            echo \"[x] irmeta.bin are different\"\n            EXIT_STATUS=1\n            continue\n        fi\n        strip_cruft \"dexdump -d $folder1/$f\" \"$f.txt.1\" >/dev/null\n        strip_cruft \"dexdump -d $folder2/$f\" \"$f.txt.2\" >/dev/null\n        if ! diff --speed-large-files -u \"$f.txt.1\" \"$f.txt.2\" > \"$f.txt.diff\"\n        then\n            echo \"[x] See difference in $TEMPDIR/$f.txt.diff\"\n            EXIT_STATUS=1\n        fi\n    done\n\n    test $EXIT_STATUS -eq 0 && echo \"[OK] All the dex files and meta data are the same!\"\n    exit $EXIT_STATUS\n}\n\nexport LC_ALL=C\n\nif [ -d \"$INPUT_A\" ]; then\n    # Inputs are IR folders, compare the files in the folders and exit.\n    compare_ir_folder \"$INPUT_A\" \"$INPUT_B\"\n    exit 1;\nelif [ ! -f \"$INPUT_A\" ]; then\n    echo \"No such file $INPUT_A, bailing\"\n    exit 1;\nfi\n\nOUTA=$TEMPDIR/alpha.filt.dexdump\nOUTB=$TEMPDIR/beta.filt.dexdump\nOUTDIFF=$TEMPDIR/diff\nDEXDUMP=\nif [[ \"$INPUT_A\" =~ dex$ ]]; then\n    DEXDUMP=\"dexdump -d\"\nelif [[ \"$INPUT_A\" =~ apk$ ]]; then\n    FBANDROID=\"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\")\")/../../..\"\n    DEXDUMP=\"$(realpath \"$FBANDROID/scripts/ordering/extractdexdump\")\"\nelse\n    DEXDUMP=\"cat\"\nfi\n\nstrip_cruft \"$DEXDUMP $INPUT_A\" \"$OUTA\"\nstrip_cruft \"$DEXDUMP $INPUT_B\" \"$OUTB\"\n\ndiff --speed-large-files -u $OUTA $OUTB > $OUTDIFF\nif [ $? == 0 ]; then\n\techo \"The dexes are equivalent\"\n\texit 0;\nelse\n\techo \"The dexes have significant differences\"\n\techo \"The differences are recorded in $OUTDIFF\"\n\texit 1;\nfi\n", "num_lines": 145}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -x\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nTEST_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null 2>&1 && pwd)\"\npushd \"$TEST_DIR\"\n\n# Note: Use at least 1.10 as we need googlemock, too.\n\ntest -e gtest-1.10.0.zip || {\n    curl https://codeload.github.com/google/googletest/zip/release-1.10.0 \\\n         -o gtest-1.10.0.zip\n    unzip -o gtest-1.10.0.zip\n}\n", "num_lines": 19}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# Take a zip file path, and a variable number of file paths that should be\n# tested to make sure they are not entries in the zip.\nif [ \"$#\" -le 1 ]; then\n    echo \"Zip and target file(s) required\"\n    exit 1\nfi\nZIP_FILE=$1\nshift\nTMP_FILE=$(mktemp)\nunzip -l \"$ZIP_FILE\" > \"$TMP_FILE\"\nwhile test $# -gt 0\ndo\n    if grep -q \"$1\" \"$TMP_FILE\"; then\n      echo \"File $1 was found in zip and should not be there.\" >&2\n      echo \"\" >&2\n      cat \"$TMP_FILE\" >&2\n      exit 1\n    fi\n    shift\ndone\n", "num_lines": 29}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\n# Expects the executable and an .apk file, which will have its manifest\n# attribute values rewritten to new values\nif [ \"$#\" -le 1 ]; then\n    echo \"xml_editor binary and target apk required\"\n    exit 1\nfi\nEDITOR_BIN=$1\nAPK=$2\nTMP_DIR=$(mktemp -d)\n\nunzip \"$APK\" AndroidManifest.xml -d \"$TMP_DIR\"\nMANIFEST=\"$TMP_DIR/AndroidManifest.xml\"\n\necho \"Rewriting package attribute\"\n\"$EDITOR_BIN\" \"$MANIFEST\" manifest package com.facebook.bananas\npushd \"$TMP_DIR\"\nzip test_str.zip AndroidManifest.xml\npopd\n\naapt d --values xmltree \"$TMP_DIR/test_str.zip\" AndroidManifest.xml | grep -q \"package=\\\"com.facebook.bananas\\\"\"\necho \"package attribute was rewritten successfully\"\n\necho \"Rewriting versionCode\"\n\"$EDITOR_BIN\" \"$MANIFEST\" manifest 0x0101021b 0x200\npushd \"$TMP_DIR\"\nzip test_ver.zip AndroidManifest.xml\npopd\n\naapt d --values xmltree \"$TMP_DIR/test_ver.zip\" AndroidManifest.xml | grep -q -E \"android:versionCode.*0x200$\"\necho \"versionCode was rewritten successfully\"\n\nrm -rf \"$TMP_DIR\"\n", "num_lines": 41}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# XXX(jezng): I tried running these commands as part of the Buck build, but I'm\n# having trouble getting the Buck-given versions of AAPT and the SDK libraries\n# to work together -- in particular, running the AAPT from v23 against the SDK\n# from v26 causes AAPT to crash. Rather than spending time figuring out how to\n# get Buck to use the versions I want, I'm just going to run the command\n# locally and commit the result...\n\nSCRIPT_DIR=$(dirname \"$(realpath \"${BASH_SOURCE[0]}\")\")\n\nfor SRC in $(find \"$SCRIPT_DIR\" -type f -name \"*.xml\"); do\n  TMP=$(mktemp -d)\n  MANIFEST=\"$TMP/AndroidManifest.xml\"\n  cp \"$SRC\" \"$MANIFEST\"\n  /opt/android_sdk/build-tools/23.0.1/aapt package -M \"$MANIFEST\" -F \"$TMP/out.apk\" -I /opt/android_sdk/platforms/android-25/android.jar\n  unzip \"$TMP/out.apk\" -d \"$TMP/out\"\n  mv \"$TMP/out/AndroidManifest.xml\" \"$SRC.bin\"\n  rm -rf \"$TMP\"\ndone\n", "num_lines": 25}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Tar and upload a test-data directory to dewey.\n#\n# Usage:\n#\n# $ ./commit-test-data.sh /path/to/test/dir\n#\n# You generally don't want to run this manually. Start by\n# running ./fetch-test-data.sh and follow the instructions.\n\ncd \"$(dirname \"$0\")\"\n\ntest_data_dir=$1\nif [ -z \"$test_data_dir\" ]; then\n  echo \"Usage: commit-test-data.sh path/to/testdata\"\n  exit 1\nfi\n\ncommit=$(cd \"$test_data_dir\" && find . -type f | sort | xargs sha1sum | sha1sum \\\n  | cut -f1 -d' ')\n\ntemp_dir=$(mktemp -d)\ntar_file=$temp_dir/test-data.$commit.tar.xz\n\npushd \"$(dirname \"$test_data_dir\")\" > /dev/null\nXZ_OPT=\"-9e -T16\" tar -cfJ - \"$(basename \"$test_data_dir\")\" > $tar_file\npopd > /dev/null\n\nmanifold put \"$tar_file\" \"oatmeal/tree/test-data.$commit.tar.xz\"\n\necho \"Edit fetch-test-data.sh file with new commit id? (save changes first)\"\nselect yn in \"Yes\" \"No\"; do\n  case $yn in\n      Yes )\n        echo \"Editing fetch file...\"\n        sed -i.bak -e \"s/commit=.*/commit=$commit/\" fetch-test-data.sh\n        rm fetch-test-data.sh.bak\n        break;;\n      No )\n        echo \"Leaving fetch file alone. You probably want to update to\"\n        echo \"commit $commit manually.\"\n        break;;\n  esac\ndone\n", "num_lines": 50}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Fetches the current test-data tarball from dewey.\n#\n# Usage:\n#\n# $ ./fetch-test-data.sh\n\ncd \"$(dirname \"$0\")\"\n\ncommit=7b81421c26124ab77061feb27cf1e17470dda27a\n\ntemp_dir=$(mktemp -d)\ntar_file=$temp_dir/test-data.$commit.tar.xz\n\necho \"Fetching $commit to $temp_dir\"\n\nmanifold get \"oatmeal/tree/test-data.$commit.tar.xz\" \"$tar_file\"\n\ntar -C \"$temp_dir\" -xf \"$tar_file\"\n\nrm \"$tar_file\"\n\necho \"Test data extracted to $temp_dir\"\necho \"\"\necho \"To generate new test data, copy new input to $temp_dir and run:\"\necho \"\"\necho \"  ORIG_TTY=\\`tty\\` UPDATE_OATMEAL_TESTDATA=1 buck run //native/redex/tools/oatmeal/test:regression-test -- $temp_dir\"\necho \"\"\necho \"This simply writes whatever output the current oatmeal binary happens\"\necho \"to generate to the test dir. Make sure the output is correct before continuing!\"\n", "num_lines": 36}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Regression test for oatmeal.\n#\n# To add new test data, run ./fetch-test-data.sh, then follow the\n# instructions it prints.\n#\n# To update existing test data after making changes, run\n# ./update-test-data.sh\n\n# buck run leaves stdout/stderr alone, but it takes away our tty.\nif [ -n \"$ORIG_TTY\" ]; then\n  exec < $ORIG_TTY\nfi\n\n# for consistent sorting between linux/mac.\nLC_ALL=C\nexport LC_ALL\n\n# <argument-parsing type=\"janky\">\n\noatmeal_binary=$1\n\n# Note: test data can be a tarball or a directory.\ntest_data=$2\n\n# directory can be overridden when running\n# buck run //native/redex/tools/oatmeal/test:regression-test -- <test dir>\nif [ -n \"$3\" ]; then\n  test_data=$3\nfi\n\n# </argument-parsing>\n\nif [ -z \"$test_data\" ]; then\n  echo \"Usage: regression-test.sh <oatmeal binary> <test-data-location>\"\n  exit 1\nfi\n\nif [ -f \"$test_data\" ]; then\n  test_data_dir=`mktemp -d`\n  tar -C $test_data_dir -zxf $test_data\nelse\n  test_data_dir=$test_data\nfi\n\ntest_output_dir=`mktemp -d`\n\npushd $test_data_dir > /dev/null\n\noat_files=`find test-data -type f -name '*.oat.rodata'`\n\nfor f in $oat_files; do\n  actual=$test_output_dir/$f.actual\n  expected=$f.expected\n  mkdir -p `dirname $actual`\n  if [ -z \"$UPDATE_OATMEAL_TESTDATA\" ]; then\n    $oatmeal_binary -c -m -t -d -o $f > $actual || \\\n      echo -e \"==============\\nExit status $?\" >> $actual\n    if ! diff $actual $expected > /dev/null; then\n      echo \"Output differed for expected for $f\"\n      echo \"Delta:\"\n      diff $actual $expected | head -50\n      exit 1\n    fi\n  else\n    echo \"Updating expected output for $f\"\n    new_output=`mktemp`\n    $oatmeal_binary -c -m -t -d -o $f > $new_output || \\\n      echo -e \"==============\\nExit status $?\" >> $new_output\n    if [ -f $expected ] && ! diff $expected $new_output > /dev/null; then\n      echo \"\\$ diff $expected $new_output\"\n      diff $expected $new_output | head -50\n      echo \"Accept these changes?\"\n      select yn in \"Yes\" \"No\"; do\n          case $yn in\n              Yes ) mv $new_output $expected; break;;\n              No ) break;;\n          esac\n      done\n    else\n      mv $new_output $expected\n    fi\n  fi\ndone\n\ndex_dirs=`find $test_data_dir/test-data -type d -name '*.dexdir'`\n\nfor d in $dex_dirs; do\n  dex_files=`find $d -type f -name '*.dex' | sort`\n  dex_files_arg=`echo $dex_files | xargs -n1 | sed 's/^/-x /' | xargs`\n  dex_locations_args=`echo $dex_files | xargs -n1 | sed 's/^.*\\//-l /' | xargs`\n\n  for version in samsung5 039 045 064 079 088; do\n\n    if [ \"$version\" == \"samsung5\" ]; then\n      version_arg=039\n      samsung_flag=\"--samsung-oatformat\"\n    else\n      version_arg=$version\n      samsung_flag=\"\"\n    fi\n\n    actual=$test_output_dir/$d.$version.actual.oat.rodata.out\n    expected=$d.$version.expected.oat.rodata.out\n    mkdir -p `dirname $actual`\n\n    if [ -z \"$UPDATE_OATMEAL_TESTDATA\" ]; then\n      tmp_oat=`mktemp`\n      $oatmeal_binary $samsung_flag -v ${version_arg} -a x86 -b -e -o $tmp_oat $dex_files_arg $dex_locations_args > $tmp_oat.output 2>&1 || \\\n        echo -e \"==============\\nExit status $?\" >> $tmp_oat.output 2>&1\n      xxd $tmp_oat | awk '{ printf \"%08x\", strtonum(\"0x\" $1); $1=\"\"; printf \":%s\\n\", $0 }' > $actual\n      cat $tmp_oat.output >> $actual\n      if ! diff $actual $expected > /dev/null; then\n        echo \"Output differed for expected for $f\"\n        echo \"Delta:\"\n        diff $actual $expected | head -50\n        exit 1\n      fi\n    else\n      echo \"Updating expected output for $f\"\n\n      new_output=`mktemp`\n      tmp_oat=`mktemp`\n      $oatmeal_binary $samsung_flag -v ${version_arg} -a x86 -b -e -o $tmp_oat $dex_files_arg $dex_locations_args > $tmp_oat.output 2>&1 || \\\n        echo -e \"==============\\nExit status $?\" >> $tmp_oat.output 2>&1\n      xxd $tmp_oat | awk '{ printf \"%08x\", strtonum(\"0x\" $1); $1=\"\"; printf \":%s\\n\", $0 }' > $new_output\n      cat $tmp_oat.output >> $new_output\n\n      if [ -f $expected ] && ! diff $expected $new_output > /dev/null; then\n        echo \"\\$ diff $expected $new_output\"\n        diff $expected $new_output | head -50\n        echo \"Accept these changes?\"\n        select yn in \"Yes\" \"No\"; do\n            case $yn in\n                Yes ) mv $new_output $expected; break;;\n                No ) break;;\n            esac\n        done\n      else\n        mv $new_output $expected\n      fi\n    fi\n  done\ndone\n\nif [ -n \"$UPDATE_OATMEAL_TESTDATA\" ]; then\n  echo \"New test output is in $test_data_dir. To commit this data run:\"\n  echo \"\"\n  echo \"  ./commit-test-data.sh $test_data_dir/test-data\"\n  echo \"\"\n  echo \"Be sure to check in the BUCK file changes, which contain the new commit id\"\n  echo \"\"\n  echo \"Test is now failing, because UPDATE_OATMEAL_TESTDATA is set\"\n  exit 1\nfi\n\necho \"PASSED\"\nexit 0\n", "num_lines": 164}
{"repo_name": "redex", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Runs the regtest, overwriting previous output, and prompts user with diffs\n# showing the changes.\n#\n# Usage:\n# ./update-test-data.sh\n\nif tty > /dev/null; then\n  cur_tty=`tty`\nfi\n\nORIG_TTY=$cur_tty UPDATE_OATMEAL_TESTDATA=1 buck run //native/redex/tools/oatmeal/test:regression-test\n", "num_lines": 18}
{"repo_name": "regenerator", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -u\n\ncd $(dirname $0)/..\nROOT_DIR=$(pwd)\n\nnpm install\n\ninstall() {\n    npm install ./packages/$1\n    pushd node_modules/regenerator-$1\n    npm install\n    # Force the child packages to look in $ROOT_DIR/node_modules to find\n    # one another.\n    rm -rf node_modules\n    popd\n}\n\nPKG=$(<package.json)\nPKG_LOCK=$(<package-lock.json)\n\n# Link local packages into node_modules.\ninstall runtime\ninstall transform\ninstall preset\n\necho \"$PKG\" > package.json\necho \"$PKG_LOCK\" > package-lock.json\n\n# We need to use the symlink paths rather than the real paths, so that the\n# regenerator-* packages appear to reside in node_modules.\nnode test/run.js\n", "num_lines": 35}
{"repo_name": "relay", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$(git status --porcelain)\" ]; then\n  # Working directory clean\n  exit 0\nelse\n  echo \"Detected changes in the working directory:\"\n  git --no-pager diff --stat\n  exit 1\nfi\n", "num_lines": 17}
{"repo_name": "relay", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\nGITHUB_ROOT=$(dirname \"$SCRIPT_DIR\")\n\ncd \"$GITHUB_ROOT\"/compiler || exit\ncargo run --bin relay --release -- \"$GITHUB_ROOT\"/scripts/config.tests.json\n", "num_lines": 14}
{"repo_name": "relay", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Compile and run the OSS compiler binary. Useful for testing and for using the\n# VSCode extension on our test files. An example VSCode project settings.json file:\n#\n# {\n#    \"relay.pathToConfig\": \"./scripts/config.tests.json\",\n#    \"relay.pathToRelay\": \"./scripts/dev-compiler.sh\",\n#    \"relay.autoStartCompiler\": true\n# }\n\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\nGITHUB_ROOT=$(dirname \"$SCRIPT_DIR\")\n\ncd \"$GITHUB_ROOT\"/compiler || exit\ncargo run --bin relay --release -- \"$@\"\n", "num_lines": 22}
{"repo_name": "relay", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Regenerate Rust tests from fixture files.\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &> /dev/null && pwd)\nGITHUB_ROOT=$(dirname \"$SCRIPT_DIR\")\n\ncd \"$GITHUB_ROOT\"/compiler || exit\ncargo run --bin fixture_tests_bin --release --  $(cat \"$GITHUB_ROOT\"/compiler/fixture_dirs.txt)\n", "num_lines": 16}
{"repo_name": "robolectric", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script builds the AOSP Android jars, and installs them in your local\n# Maven repository. See: http://source.android.com/source/building.html for\n# more information on building AOSP.\n#\n# Usage:\n#   build-android-artifacts.sh <android version> <robolectric version>\n#\n# Signing Artifacts:\n# The end of the script will prompt you to sign the new artifacts.  You will\n# be prompted a total of 4 times (once for each artifact).  To make this\n# easier, run this command beforehand:\n#\n#   gpg-agent --daemon\n#\n# It will spit out a command that you can then run in your shell to remember\n# the password for the current session.\n#\n# Supported Versions:\n#   4.1.2_r1    - Jelly Bean\n#   4.2.2_r1.2  - Jelly Bean MR1\n#   4.3_r2      - Jelly Bean MR2\n#   4.4_r1      - Kit Kat\n#   5.0.0_r2    - Lollipop\n#   5.1.1_r9    - Lollipop MR1\n#\n# Environment Variables:\n#   BUILD_ROOT        - Path to AOSP source directory\n#   SIGNING_PASSWORD  - Passphrase for GPG signing key\n#\n# Assumptions:\n#   1. You've got the full AOSP checked out on a case-sensitive file system at /Volumes/android/android-build\n#   2. repo init -u https://android.googlesource.com/platform/manifest -b <android-version>\n#   3. repo sync\n#   4. source build/envsetup.sh\n#   5. lunch aosp_x86-eng (or something like android_x86-eng)\n#   6. make -j8  # probably can just run 'make -j8 snod', but we haven't tested it http://elinux.org/Android_Build_System#Make_targets\n#   7. run this script\n#   8. Profit!\n#\nif [[ $# -eq 0 ]]; then\n    echo \"Usage: ${0} <android-version> <robolectric-sub-version>\"\n    exit 1\nfi\n\nif [[ -z \"${BUILD_ROOT}\" ]]; then\n    echo \"Please set the AOSP build root path as BUILD_ROOT\"\n    exit 1\nfi\n\nif [[ -z \"${SIGNING_PASSWORD}\" ]]; then\n    echo \"Please set the GPG passphrase as SIGNING_PASSWORD\"\n    exit 1\nfi\n\nANDROID_VERSION=$1\nif [[ -z \"$2\" ]]; then\n    ROBOLECTRIC_SUB_VERSION=0\nelse\n    ROBOLECTRIC_SUB_VERSION=$2\nfi\n\nSCRIPT_DIR=$(cd $(dirname \"$0\"); pwd)\n\nANDROID_SOURCES_BASE=${BUILD_ROOT}\nFRAMEWORKS_BASE_DIR=${ANDROID_SOURCES_BASE}/frameworks/base\nROBOLECTRIC_VERSION=${ANDROID_VERSION}-robolectric-${ROBOLECTRIC_SUB_VERSION}\n\n# Intermediate artifacts\nANDROID_RES=android-res-${ANDROID_VERSION}.jar\nANDROID_EXT=android-ext-${ANDROID_VERSION}.jar\nANDROID_CLASSES=android-classes-${ANDROID_VERSION}.jar\n\n# Final artifact names\nANDROID_ALL=android-all-${ROBOLECTRIC_VERSION}.jar\nANDROID_ALL_POM=android-all-${ROBOLECTRIC_VERSION}.pom\nANDROID_ALL_SRC=android-all-${ROBOLECTRIC_VERSION}-sources.jar\nANDROID_ALL_DOC=android-all-${ROBOLECTRIC_VERSION}-javadoc.jar\nANDROID_BUNDLE=android-all-${ROBOLECTRIC_VERSION}-bundle.jar\n\nbuild_platform() {\n    if [[ \"${ANDROID_VERSION}\" == \"4.1.2_r1\" ]]; then\n        ARTIFACTS=(\"core\" \"services\" \"framework\" \"android.policy\" \"ext\")\n    elif [[ \"${ANDROID_VERSION}\" == \"4.2.2_r1.2\" ]]; then\n        ARTIFACTS=(\"core\" \"services\" \"telephony-common\" \"framework\" \"android.policy\" \"ext\")\n    elif [[ \"${ANDROID_VERSION}\" == \"4.3_r2\" ]]; then\n        ARTIFACTS=(\"core\" \"services\" \"telephony-common\" \"framework\" \"android.policy\" \"ext\")\n    elif [[ \"${ANDROID_VERSION}\" == \"4.4_r1\" ]]; then\n        ARTIFACTS=(\"core\" \"services\" \"telephony-common\" \"framework\" \"framework2\" \"framework-base\" \"android.policy\" \"ext\" \"webviewchromium\")\n    elif [[ \"${ANDROID_VERSION}\" == \"5.0.0_r2\" ]]; then\n        ARTIFACTS=(\"core-libart\" \"services\" \"telephony-common\" \"framework\" \"android.policy\" \"ext\")\n    elif [[ \"${ANDROID_VERSION}\" == \"5.1.1_r9\" ]]; then\n        ARTIFACTS=(\"core-libart\" \"services\" \"telephony-common\" \"framework\" \"android.policy\" \"ext\")\n    else\n        echo \"Robolectric: No match for version: ${ANDROID_VERSION}\"\n        exit 1\n    fi\n\n    cd ${ANDROID_SOURCES_BASE}\n    if [ ! -d out/target/common/obj/JAVA_LIBRARIES ]; then\n      echo \"Robolectric: You need to run 'make -j8' first\"\n      exit 1\n    fi\n}\n\nbuild_android_res() {\n    echo \"Robolectric: Building android-res...\"\n    cd ${FRAMEWORKS_BASE_DIR}/core/res; jar cf ${OUT}/${ANDROID_RES} .\n}\n\nbuild_android_ext() {\n    echo \"Robolectric: Building android-ext...\"\n    local PHONE_NUMBERS_DIR=com/android/i18n/phonenumbers\n    mkdir -p ${OUT}/ext-classes-modified/${PHONE_NUMBERS_DIR}\n    cd ${OUT}/ext-classes-modified; jar xf ${ANDROID_SOURCES_BASE}/out/target/common/obj/JAVA_LIBRARIES/ext_intermediates/classes.jar\n    cp -R ${ANDROID_SOURCES_BASE}/external/libphonenumber/java/src/${PHONE_NUMBERS_DIR}/data ${OUT}/ext-classes-modified/${PHONE_NUMBERS_DIR}\n    cd ${OUT}/ext-classes-modified; jar cf ${OUT}/${ANDROID_EXT} .\n    rm -rf ${OUT}/ext-classes-modified\n}\n\nbuild_android_classes() {\n    echo \"Robolectric: Building android-classes...\"\n    mkdir ${OUT}/android-all-classes\n    for artifact in \"${ARTIFACTS[@]}\"; do\n        src=${ANDROID_SOURCES_BASE}/out/target/common/obj/JAVA_LIBRARIES/${artifact}_intermediates\n        cd ${OUT}/android-all-classes; jar xf ${src}/classes.jar\n    done\n    build_tzdata\n    build_jarjared_classes\n    cd ${OUT}/android-all-classes; jar cf ${OUT}/${ANDROID_CLASSES} .\n    rm -rf ${OUT}/android-all-classes\n}\n\nbuild_tzdata() {\n    echo \"Robolectric: Building tzdata...\"\n    mkdir -p ${OUT}/android-all-classes/usr/share/zoneinfo\n    cp ${ANDROID_SOURCES_BASE}/out/target/product/generic_x86_64/system/usr/share/zoneinfo/tzdata ${OUT}/android-all-classes/usr/share/zoneinfo\n}\n\nbuild_jarjared_classes() {\n    echo \"Robolectric: jarjaring classes...\"\n    mkdir ${OUT}/android-jarjar-workspace\n    cd ${OUT}/android-jarjar-workspace\n    wget https://jarjar.googlecode.com/files/jarjar-1.4.jar\n    echo \"rule com.squareup.** com.android.**\" >> rules\n    echo \"rule org.conscrypt.** com.android.**\" >> rules\n\n    java -jar jarjar-1.4.jar process rules ${ANDROID_SOURCES_BASE}/out/target/common/obj/JAVA_LIBRARIES/okhttp_intermediates/classes.jar okhttp-classes.jar\n    java -jar jarjar-1.4.jar process rules ${ANDROID_SOURCES_BASE}/out/target/common/obj/JAVA_LIBRARIES/conscrypt_intermediates/classes.jar conscrypt-classes.jar\n\n    cd ${OUT}/android-all-classes;\n    jar xf ${OUT}/android-jarjar-workspace/okhttp-classes.jar\n    jar xf ${OUT}/android-jarjar-workspace/conscrypt-classes.jar\n}\n\nbuild_android_all_jar() {\n    echo \"Robolectric: Building android-all...\"\n    mkdir ${OUT}/android-all\n    cd ${OUT}/android-all; jar xf ${OUT}/${ANDROID_RES}\n    cd ${OUT}/android-all; jar xf ${OUT}/${ANDROID_EXT}\n    cd ${OUT}/android-all; jar xf ${OUT}/${ANDROID_CLASSES}\n\n    # Remove unused files\n    rm -rf ${OUT}/android-all/Android.mk\n    rm -rf ${OUT}/android-all/AndroidManifest.xml\n    rm -rf ${OUT}/android-all/META-INF\n    rm -rf ${OUT}/android-all/MODULE_LICENSE_APACHE2\n    rm -rf ${OUT}/android-all/MakeJavaSymbols.sed\n    rm -rf ${OUT}/android-all/NOTICE\n    rm -rf ${OUT}/android-all/lint.xml\n    rm -rf ${OUT}/android-all/java/lang\n\n    # Build the new JAR file\n    cd ${OUT}/android-all; jar cf ${OUT}/${ANDROID_ALL} .\n    rm ${OUT}/${ANDROID_RES} ${OUT}/${ANDROID_EXT} ${OUT}/${ANDROID_CLASSES}\n}\n\nbuild_android_src_jar() {\n    echo \"Robolectric: Building android-all-source...\"\n    local src=${ANDROID_SOURCES_BASE}/frameworks/base\n    local tmp=${OUT}/sources\n    mkdir ${tmp}\n    rsync -va ${src}/core/java/ ${tmp}/\n    rsync -va ${src}/graphics/java/ ${tmp}/\n    rsync -va ${src}/media/java/ ${tmp}/\n    rsync -va ${src}/location/java/ ${tmp}/\n    rsync -va ${src}/opengl/java/ ${tmp}/\n    rsync -va ${src}/policy/src/ ${tmp}/\n    rsync -va ${src}/sax/java/ ${tmp}/\n    rsync -va ${src}/services/java/ ${tmp}/\n    rsync -va ${src}/telephony/java/ ${tmp}/\n    rsync -va ${src}/wifi/java/ ${tmp}/\n    rsync -va ${ANDROID_SOURCES_BASE}/libcore/luni/src/main/java/ ${tmp}/ # this is new\n    cd ${tmp}; jar cf ${OUT}/${ANDROID_ALL_SRC} .\n    rm -rf ${tmp}\n}\n\nbuild_android_doc_jar() {\n    # TODO: Actually build the docs\n    echo \"Robolectric: Building android-all-javadoc...\"\n    mkdir ${OUT}/javadoc\n    cd ${OUT}/javadoc; jar cf ${OUT}/${ANDROID_ALL_DOC} .\n    rm -rf ${OUT}/javadoc\n}\n\nbuild_signed_packages() {\n    echo \"Robolectric: Building android-all.pom...\"\n    sed s/VERSION/${ROBOLECTRIC_VERSION}/ ${SCRIPT_DIR}/pom_template.xml | sed s/ARTIFACT_ID/android-all/ > ${OUT}/${ANDROID_ALL_POM}\n\n    echo \"Robolectric: Signing files with gpg...\"\n    for ext in \".jar\" \"-javadoc.jar\" \"-sources.jar\" \".pom\"; do\n        ( cd ${OUT} && gpg -ab --passphrase ${SIGNING_PASSWORD} android-all-${ROBOLECTRIC_VERSION}$ext )\n    done\n\n    echo \"Robolectric: Creating bundle for Sonatype upload...\"\n    cd ${OUT}; jar cf ${ANDROID_BUNDLE} *.jar *.pom *.asc\n}\n\nmavenize() {\n    local FILE_NAME_BASE=android-all-${ROBOLECTRIC_VERSION}\n    mvn install:install-file \\\n      -Dfile=${OUT}/${FILE_NAME_BASE}.jar \\\n      -DgroupId=org.robolectric \\\n      -DartifactId=android-all \\\n      -Dversion=${ROBOLECTRIC_VERSION} \\\n      -Dpackaging=jar\n\n    mvn install:install-file \\\n      -Dfile=${OUT}/${FILE_NAME_BASE}-sources.jar \\\n      -DgroupId=org.robolectric \\\n      -DartifactId=android-all \\\n      -Dversion=${ROBOLECTRIC_VERSION} \\\n      -Dpackaging=jar \\\n      -Dclassifier=sources\n\n    mvn install:install-file \\\n      -Dfile=${OUT}/${FILE_NAME_BASE}-javadoc.jar \\\n      -DgroupId=org.robolectric \\\n      -DartifactId=android-all \\\n      -Dversion=${ROBOLECTRIC_VERSION} \\\n      -Dpackaging=jar \\\n      -Dclassifier=javadoc\n}\n\nOUT=`mktemp --directory`\nmkdir -p ${OUT}\n\nbuild_platform\nbuild_android_res\nbuild_android_ext\nbuild_android_classes\nbuild_android_all_jar\nbuild_android_src_jar\nbuild_android_doc_jar\nbuild_signed_packages\nmavenize\n\necho \"DONE!!\"\necho \"Your artifacts are located here: ${OUT}\"\n\n", "num_lines": 262}
{"repo_name": "robolectric", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Deploy a release build to Sonatype.\n#\n\nset -e\n\nPROJECT=$(cd $(dirname \"$0\")/..; pwd)\n\necho \"Building Robolectric...\"\ncd \"$PROJECT\"; mvn -P release -D skipTests clean deploy\n\necho \"Building shadows for API 16...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P release,android-16 -D skipTests clean deploy\n\necho \"Building shadows for API 17...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P release,android-17 -D skipTests clean deploy\n\necho \"Building shadows for API 18...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P release,android-18 -D skipTests clean deploy\n\necho \"Building shadows for API 19...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P release,android-19 -D skipTests clean deploy\n\necho \"Building shadows for API 21...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P release,android-21 -D skipTests clean deploy\n", "num_lines": 27}
{"repo_name": "robolectric", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Deploy a snapshot build to Sonatype.\n#\n\nset -e\n\nPROJECT=$(cd $(dirname \"$0\")/..; pwd)\nARGUMENTS=\"--settings $PROJECT/scripts/mvn_settings.xml -D skipTests\"\n\necho \"Pull request: '${TRAVIS_PULL_REQUEST}' on branch '${TRAVIS_BRANCH}' with JDK '${TRAVIS_JDK_VERSION}'\"\nif [ \"${TRAVIS_PULL_REQUEST}\" = \"false\" ] && [ \"${TRAVIS_BRANCH}\" = \"master\" ] && [ \"${TRAVIS_JDK_VERSION}\" = \"oraclejdk8\" ]; then\n\n    echo \"Building Robolectric...\"\n    cd \"$PROJECT\"; mvn ${ARGUMENTS} -P snapshot clean deploy\n\n    echo \"Building shadows for API 16...\"\n    cd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn ${ARGUMENTS} -P snapshot,android-16 clean package\n\n    echo \"Building shadows for API 17...\"\n    cd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn ${ARGUMENTS} -P snapshot,android-17 clean package\n\n    echo \"Building shadows for API 18...\"\n    cd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn ${ARGUMENTS} -P snapshot,android-18 clean package\n\n    echo \"Building shadows for API 19...\"\n    cd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn ${ARGUMENTS} -P snapshot,android-19 clean package\n\n    echo \"Building shadows for API 21...\"\n    cd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn ${ARGUMENTS} -P snapshot,android-21 clean package\n\n    echo \"Uploading SNAPSHOT...\"\n    cd \"$PROJECT\"; mvn ${ARGUMENTS} -P snapshot,android-latest,upload deploy\nfi\n", "num_lines": 35}
{"repo_name": "robolectric", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Install Robolectric into the local Maven repository.\n#\nset -e\n\nPROJECT=$(cd $(dirname \"$0\")/..; pwd)\nif [ -z ${INCLUDE_SOURCE+x} ]; then SOURCE_ARG=\"\"; else SOURCE_ARG=\"source:jar\"; fi\nif [ -z ${INCLUDE_JAVADOC+x} ]; then JAVADOC_ARG=\"\"; else JAVADOC_ARG=\"javadoc:jar\"; fi\n\necho \"Building Robolectric...\"\ncd \"$PROJECT\"; mvn -D skipTests clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 16...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-16 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 17...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-17 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 18...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-18 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 19...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-19 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 21...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-21 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Building shadows for API 22...\"\ncd \"$PROJECT\"/robolectric-shadows/shadows-core; mvn -P android-22 clean $SOURCE_ARG $JAVADOC_ARG install\n\necho \"Running Tests...\"\ncd \"$PROJECT\"; mvn test\n", "num_lines": 34}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# If clang_format_diff.py command is not specfied, we assume we are able to\n# access directly without any path.\n\nTGT_DIFF=`git diff TARGETS | head -n 1`\n\nif [ ! -z \"$TGT_DIFF\" ]\nthen\n  echo \"TARGETS file has uncommitted changes. Skip this check.\"\n  exit 0\nfi\n\necho Backup original TARGETS file.\n\ncp TARGETS TARGETS.bkp\n\n${PYTHON:-python3} buckifier/buckify_rocksdb.py\n\nTGT_DIFF=`git diff TARGETS | head -n 1`\n\nif [ -z \"$TGT_DIFF\" ]\nthen\n  mv TARGETS.bkp TARGETS\n  exit 0\nelse\n  echo \"Please run '${PYTHON:-python3} buckifier/buckify_rocksdb.py' to update TARGETS file.\"\n  echo \"Do not manually update TARGETS file.\"\n  ${PYTHON:-python3} --version\n  mv TARGETS.bkp TARGETS\n  exit 1\nfi\n", "num_lines": 33}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# Create a tmp directory for the test to use\nTEST_DIR=$(mktemp -d /dev/shm/fbcode_rocksdb_XXXXXXX)\n# shellcheck disable=SC2068\nTEST_TMPDIR=\"$TEST_DIR\" $@ && rm -rf \"$TEST_DIR\"\n", "num_lines": 7}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# Check for some simple mistakes that should prevent commit or push\n\nBAD=\"\"\n\ngit grep -n 'namespace rocksdb' -- '*.[ch]*'\nif [ \"$?\" != \"1\" ]; then\n  echo \"^^^^^ Do not hardcode namespace rocksdb. Use ROCKSDB_NAMESPACE\"\n  BAD=1\nfi\n\ngit grep -n -i 'nocommit' -- ':!build_tools/check-sources.sh'\nif [ \"$?\" != \"1\" ]; then\n  echo \"^^^^^ Code was not intended to be committed\"\n  BAD=1\nfi\n\ngit grep -n 'include <rocksdb/' -- ':!build_tools/check-sources.sh'\nif [ \"$?\" != \"1\" ]; then\n  echo '^^^^^ Use double-quotes as in #include \"rocksdb/something.h\"'\n  BAD=1\nfi\n\ngit grep -n 'include \"include/rocksdb/' -- ':!build_tools/check-sources.sh'\nif [ \"$?\" != \"1\" ]; then\n  echo '^^^^^ Use #include \"rocksdb/something.h\" instead of #include \"include/rocksdb/something.h\"'\n  BAD=1\nfi\n\ngit grep -n 'using namespace' -- ':!build_tools' ':!docs' \\\n    ':!third-party/folly/folly/lang/Align.h' \\\n    ':!third-party/gtest-1.8.1/fused-src/gtest/gtest.h'\nif [ \"$?\" != \"1\" ]; then\n  echo '^^^^ Do not use \"using namespace\"'\n  BAD=1\nfi\n\ngit grep -n -P \"[\\x80-\\xFF]\" -- ':!docs' ':!*.md'\nif [ \"$?\" != \"1\" ]; then\n  echo '^^^^ Use only ASCII characters in source files'\n  BAD=1\nfi\n\nif [ \"$BAD\" ]; then\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# The file is generated using update_dependencies.sh.\nGCC_BASE=/mnt/gvfs/third-party2/gcc/e40bde78650fa91b8405a857e3f10bf336633fb0/11.x/centos7-native/886b5eb\nCLANG_BASE=/mnt/gvfs/third-party2/llvm-fb/2043340983c032915adbb6f78903dc855b65aee8/12/platform010/9520e0f\nLIBGCC_BASE=/mnt/gvfs/third-party2/libgcc/c00dcc6a3e4125c7e8b248e9a79c14b78ac9e0ca/11.x/platform010/5684a5a\nGLIBC_BASE=/mnt/gvfs/third-party2/glibc/0b9c8e4b060eda62f3bc1c6127bbe1256697569b/2.34/platform010/f259413\nSNAPPY_BASE=/mnt/gvfs/third-party2/snappy/bc9647f7912b131315827d65cb6189c21f381d05/1.1.3/platform010/76ebdda\nZLIB_BASE=/mnt/gvfs/third-party2/zlib/a6f5f3f1d063d2d00cd02fc12f0f05fc3ab3a994/1.2.11/platform010/76ebdda\nBZIP2_BASE=/mnt/gvfs/third-party2/bzip2/09703139cfc376bd8a82642385a0e97726b28287/1.0.6/platform010/76ebdda\nLZ4_BASE=/mnt/gvfs/third-party2/lz4/60220d6a5bf7722b9cc239a1368c596619b12060/1.9.1/platform010/76ebdda\nZSTD_BASE=/mnt/gvfs/third-party2/zstd/50eace8143eaaea9473deae1f3283e0049e05633/1.4.x/platform010/64091f4\nGFLAGS_BASE=/mnt/gvfs/third-party2/gflags/5d27e5919771603da06000a027b12f799e58a4f7/2.2.0/platform010/76ebdda\nJEMALLOC_BASE=/mnt/gvfs/third-party2/jemalloc/b62912d333ef33f9760efa6219dbe3fe6abb3b0e/master/platform010/f57cc4a\nNUMA_BASE=/mnt/gvfs/third-party2/numa/6b412770957aa3c8a87e5e0dcd8cc2f45f393bc0/2.0.11/platform010/76ebdda\nLIBUNWIND_BASE=/mnt/gvfs/third-party2/libunwind/52f69816e936e147664ad717eb71a1a0e9dc973a/1.4/platform010/5074a48\nTBB_BASE=/mnt/gvfs/third-party2/tbb/c9cc192099fa84c0dcd0ffeedd44a373ad6e4925/2018_U5/platform010/76ebdda\nLIBURING_BASE=/mnt/gvfs/third-party2/liburing/a98e2d137007e3ebf7f33bd6f99c2c56bdaf8488/20210212/platform010/76ebdda\nBENCHMARK_BASE=/mnt/gvfs/third-party2/benchmark/780c7a0f9cf0967961e69ad08e61cddd85d61821/trunk/platform010/76ebdda\nKERNEL_HEADERS_BASE=/mnt/gvfs/third-party2/kernel-headers/02d9f76aaaba580611cf75e741753c800c7fdc12/fb/platform010/da39a3e\nBINUTILS_BASE=/mnt/gvfs/third-party2/binutils/938dc3f064ef3a48c0446f5b11d788d50b3eb5ee/2.37/centos7-native/da39a3e\nVALGRIND_BASE=/mnt/gvfs/third-party2/valgrind/429a6b3203eb415f1599bd15183659153129188e/3.15.0/platform010/76ebdda\nLUA_BASE=/mnt/gvfs/third-party2/lua/363787fa5cac2a8aa20638909210443278fa138e/5.3.4/platform010/9079c97\n", "num_lines": 23}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\ndocker run -v $PWD:/rocks -w /rocks buildpack-deps make\n", "num_lines": 4}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# Set environment variables so that we can compile rocksdb using\n# fbcode settings.  It uses the latest g++ and clang compilers and also\n# uses jemalloc\n# Environment variables that change the behavior of this script:\n# PIC_BUILD -- if true, it will only take pic versions of libraries from fbcode. libraries that don't have pic variant will not be included\n\n\nBASEDIR=`dirname $BASH_SOURCE`\nsource \"$BASEDIR/dependencies.sh\"\n\nCFLAGS=\"\"\n\n# libgcc\nLIBGCC_INCLUDE=\"$LIBGCC_BASE/include\"\nLIBGCC_LIBS=\" -L $LIBGCC_BASE/lib\"\n\n# glibc\nGLIBC_INCLUDE=\"$GLIBC_BASE/include\"\nGLIBC_LIBS=\" -L $GLIBC_BASE/lib\"\n\nif ! test $ROCKSDB_DISABLE_SNAPPY; then\n  # snappy\n  SNAPPY_INCLUDE=\" -I $SNAPPY_BASE/include/\"\n  if test -z $PIC_BUILD; then\n    SNAPPY_LIBS=\" $SNAPPY_BASE/lib/libsnappy.a\"\n  else\n    SNAPPY_LIBS=\" $SNAPPY_BASE/lib/libsnappy_pic.a\"\n  fi\n  CFLAGS+=\" -DSNAPPY\"\nfi\n\nif test -z $PIC_BUILD; then\n  if ! test $ROCKSDB_DISABLE_ZLIB; then\n    # location of zlib headers and libraries\n    ZLIB_INCLUDE=\" -I $ZLIB_BASE/include/\"\n    ZLIB_LIBS=\" $ZLIB_BASE/lib/libz.a\"\n    CFLAGS+=\" -DZLIB\"\n  fi\n\n  if ! test $ROCKSDB_DISABLE_BZIP; then\n    # location of bzip headers and libraries\n    BZIP_INCLUDE=\" -I $BZIP2_BASE/include/\"\n    BZIP_LIBS=\" $BZIP2_BASE/lib/libbz2.a\"\n    CFLAGS+=\" -DBZIP2\"\n  fi\n\n  if ! test $ROCKSDB_DISABLE_LZ4; then\n    LZ4_INCLUDE=\" -I $LZ4_BASE/include/\"\n    LZ4_LIBS=\" $LZ4_BASE/lib/liblz4.a\"\n    CFLAGS+=\" -DLZ4\"\n  fi\nfi\n\nif ! test $ROCKSDB_DISABLE_ZSTD; then\n  ZSTD_INCLUDE=\" -I $ZSTD_BASE/include/\"\n  if test -z $PIC_BUILD; then\n    ZSTD_LIBS=\" $ZSTD_BASE/lib/libzstd.a\"\n  else\n    ZSTD_LIBS=\" $ZSTD_BASE/lib/libzstd_pic.a\"\n  fi\n  CFLAGS+=\" -DZSTD -DZSTD_STATIC_LINKING_ONLY\"\nfi\n\n# location of gflags headers and libraries\nGFLAGS_INCLUDE=\" -I $GFLAGS_BASE/include/\"\nif test -z $PIC_BUILD; then\n  GFLAGS_LIBS=\" $GFLAGS_BASE/lib/libgflags.a\"\nelse\n  GFLAGS_LIBS=\" $GFLAGS_BASE/lib/libgflags_pic.a\"\nfi\nCFLAGS+=\" -DGFLAGS=gflags\"\n\n# location of jemalloc\nJEMALLOC_INCLUDE=\" -I $JEMALLOC_BASE/include/\"\nJEMALLOC_LIB=\" $JEMALLOC_BASE/lib/libjemalloc.a\"\n\nif test -z $PIC_BUILD; then\n  # location of numa\n  NUMA_INCLUDE=\" -I $NUMA_BASE/include/\"\n  NUMA_LIB=\" $NUMA_BASE/lib/libnuma.a\"\n  CFLAGS+=\" -DNUMA\"\n\n  # location of libunwind\n  LIBUNWIND=\"$LIBUNWIND_BASE/lib/libunwind.a\"\nfi\n\n# location of TBB\nTBB_INCLUDE=\" -isystem $TBB_BASE/include/\"\nif test -z $PIC_BUILD; then\n  TBB_LIBS=\"$TBB_BASE/lib/libtbb.a\"\nelse\n  TBB_LIBS=\"$TBB_BASE/lib/libtbb_pic.a\"\nfi\nCFLAGS+=\" -DTBB\"\n\ntest \"$USE_SSE\" || USE_SSE=1\nexport USE_SSE\ntest \"$PORTABLE\" || PORTABLE=1\nexport PORTABLE\n\nBINUTILS=\"$BINUTILS_BASE/bin\"\nAR=\"$BINUTILS/ar\"\n\nDEPS_INCLUDE=\"$SNAPPY_INCLUDE $ZLIB_INCLUDE $BZIP_INCLUDE $LZ4_INCLUDE $ZSTD_INCLUDE $GFLAGS_INCLUDE $NUMA_INCLUDE $TBB_INCLUDE\"\n\nSTDLIBS=\"-L $GCC_BASE/lib64\"\n\nCLANG_BIN=\"$CLANG_BASE/bin\"\nCLANG_LIB=\"$CLANG_BASE/lib\"\nCLANG_SRC=\"$CLANG_BASE/../../src\"\n\nCLANG_ANALYZER=\"$CLANG_BIN/clang++\"\nCLANG_SCAN_BUILD=\"$CLANG_SRC/llvm/tools/clang/tools/scan-build/bin/scan-build\"\n\nif [ -z \"$USE_CLANG\" ]; then\n  # gcc\n  CC=\"$GCC_BASE/bin/gcc\"\n  CXX=\"$GCC_BASE/bin/g++\"\n  AR=\"$GCC_BASE/bin/gcc-ar\"\n\n  CFLAGS+=\" -B$BINUTILS/gold\"\n  CFLAGS+=\" -isystem $GLIBC_INCLUDE\"\n  CFLAGS+=\" -isystem $LIBGCC_INCLUDE\"\n  JEMALLOC=1\nelse\n  # clang\n  CLANG_INCLUDE=\"$CLANG_LIB/clang/stable/include\"\n  CC=\"$CLANG_BIN/clang\"\n  CXX=\"$CLANG_BIN/clang++\"\n  AR=\"$CLANG_BIN/llvm-ar\"\n\n  KERNEL_HEADERS_INCLUDE=\"$KERNEL_HEADERS_BASE/include\"\n\n  CFLAGS+=\" -B$BINUTILS/gold -nostdinc -nostdlib\"\n  CFLAGS+=\" -isystem $LIBGCC_BASE/include/c++/5.x \"\n  CFLAGS+=\" -isystem $LIBGCC_BASE/include/c++/5.x/x86_64-facebook-linux \"\n  CFLAGS+=\" -isystem $GLIBC_INCLUDE\"\n  CFLAGS+=\" -isystem $LIBGCC_INCLUDE\"\n  CFLAGS+=\" -isystem $CLANG_INCLUDE\"\n  CFLAGS+=\" -isystem $KERNEL_HEADERS_INCLUDE/linux \"\n  CFLAGS+=\" -isystem $KERNEL_HEADERS_INCLUDE \"\n  CFLAGS+=\" -Wno-expansion-to-defined \"\n  CXXFLAGS=\"-nostdinc++\"\nfi\n\nCFLAGS+=\" $DEPS_INCLUDE\"\nCFLAGS+=\" -DROCKSDB_PLATFORM_POSIX -DROCKSDB_LIB_IO_POSIX -DROCKSDB_FALLOCATE_PRESENT -DROCKSDB_MALLOC_USABLE_SIZE -DROCKSDB_RANGESYNC_PRESENT -DROCKSDB_SCHED_GETCPU_PRESENT\"\nCXXFLAGS+=\" $CFLAGS\"\n\nEXEC_LDFLAGS=\" $SNAPPY_LIBS $ZLIB_LIBS $BZIP_LIBS $LZ4_LIBS $ZSTD_LIBS $GFLAGS_LIBS $NUMA_LIB $TBB_LIBS\"\nEXEC_LDFLAGS+=\" -B$BINUTILS/gold\"\nEXEC_LDFLAGS+=\" -Wl,--dynamic-linker,/usr/local/fbcode/gcc-5-glibc-2.23/lib/ld.so\"\nEXEC_LDFLAGS+=\" $LIBUNWIND\"\nEXEC_LDFLAGS+=\" -Wl,-rpath=/usr/local/fbcode/gcc-5-glibc-2.23/lib\"\n# required by libtbb\nEXEC_LDFLAGS+=\" -ldl\"\n\nPLATFORM_LDFLAGS=\"$LIBGCC_LIBS $GLIBC_LIBS $STDLIBS -lgcc -lstdc++\"\n\nEXEC_LDFLAGS_SHARED=\"$SNAPPY_LIBS $ZLIB_LIBS $BZIP_LIBS $LZ4_LIBS $ZSTD_LIBS $GFLAGS_LIBS $TBB_LIBS\"\n\nVALGRIND_VER=\"$VALGRIND_BASE/bin/\"\n\nLUA_PATH=\"$LUA_BASE\"\n\nif test -z $PIC_BUILD; then\n  LUA_LIB=\" $LUA_PATH/lib/liblua.a\"\nelse\n  LUA_LIB=\" $LUA_PATH/lib/liblua_pic.a\"\nfi\n\nexport CC CXX AR CFLAGS CXXFLAGS EXEC_LDFLAGS EXEC_LDFLAGS_SHARED VALGRIND_VER JEMALLOC_LIB JEMALLOC_INCLUDE CLANG_ANALYZER CLANG_SCAN_BUILD LUA_PATH LUA_LIB\n", "num_lines": 176}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# Set environment variables so that we can compile rocksdb using\n# fbcode settings.  It uses the latest g++ and clang compilers and also\n# uses jemalloc\n# Environment variables that change the behavior of this script:\n# PIC_BUILD -- if true, it will only take pic versions of libraries from fbcode. libraries that don't have pic variant will not be included\n\n\nBASEDIR=`dirname $BASH_SOURCE`\nsource \"$BASEDIR/dependencies_platform010.sh\"\n\n# Disallow using libraries from default locations as they might not be compatible with platform010 libraries.\nCFLAGS=\" --sysroot=/DOES/NOT/EXIST\"\n\n# libgcc\nLIBGCC_INCLUDE=\"$LIBGCC_BASE/include/c++/trunk\"\nLIBGCC_LIBS=\" -L $LIBGCC_BASE/lib -B$LIBGCC_BASE/lib/gcc/x86_64-facebook-linux/trunk/\"\n\n# glibc\nGLIBC_INCLUDE=\"$GLIBC_BASE/include\"\nGLIBC_LIBS=\" -L $GLIBC_BASE/lib\"\nGLIBC_LIBS+=\" -B$GLIBC_BASE/lib\"\n\nif test -z $PIC_BUILD; then\n  MAYBE_PIC=\nelse\n  MAYBE_PIC=_pic\nfi\n\nif ! test $ROCKSDB_DISABLE_SNAPPY; then\n  # snappy\n  SNAPPY_INCLUDE=\" -I $SNAPPY_BASE/include/\"\n  SNAPPY_LIBS=\" $SNAPPY_BASE/lib/libsnappy${MAYBE_PIC}.a\"\n  CFLAGS+=\" -DSNAPPY\"\nfi\n\nif ! test $ROCKSDB_DISABLE_ZLIB; then\n  # location of zlib headers and libraries\n  ZLIB_INCLUDE=\" -I $ZLIB_BASE/include/\"\n  ZLIB_LIBS=\" $ZLIB_BASE/lib/libz${MAYBE_PIC}.a\"\n  CFLAGS+=\" -DZLIB\"\nfi\n\nif ! test $ROCKSDB_DISABLE_BZIP; then\n  # location of bzip headers and libraries\n  BZIP_INCLUDE=\" -I $BZIP2_BASE/include/\"\n  BZIP_LIBS=\" $BZIP2_BASE/lib/libbz2${MAYBE_PIC}.a\"\n  CFLAGS+=\" -DBZIP2\"\nfi\n\nif ! test $ROCKSDB_DISABLE_LZ4; then\n  LZ4_INCLUDE=\" -I $LZ4_BASE/include/\"\n  LZ4_LIBS=\" $LZ4_BASE/lib/liblz4${MAYBE_PIC}.a\"\n  CFLAGS+=\" -DLZ4\"\nfi\n\nif ! test $ROCKSDB_DISABLE_ZSTD; then\n  ZSTD_INCLUDE=\" -I $ZSTD_BASE/include/\"\n  ZSTD_LIBS=\" $ZSTD_BASE/lib/libzstd${MAYBE_PIC}.a\"\n  CFLAGS+=\" -DZSTD\"\nfi\n\n# location of gflags headers and libraries\nGFLAGS_INCLUDE=\" -I $GFLAGS_BASE/include/\"\nGFLAGS_LIBS=\" $GFLAGS_BASE/lib/libgflags${MAYBE_PIC}.a\"\nCFLAGS+=\" -DGFLAGS=gflags\"\n\nBENCHMARK_INCLUDE=\" -I $BENCHMARK_BASE/include/\"\nBENCHMARK_LIBS=\" $BENCHMARK_BASE/lib/libbenchmark${MAYBE_PIC}.a\"\n\n# location of jemalloc\nJEMALLOC_INCLUDE=\" -I $JEMALLOC_BASE/include/\"\nJEMALLOC_LIB=\" $JEMALLOC_BASE/lib/libjemalloc${MAYBE_PIC}.a\"\n\n# location of numa\nNUMA_INCLUDE=\" -I $NUMA_BASE/include/\"\nNUMA_LIB=\" $NUMA_BASE/lib/libnuma${MAYBE_PIC}.a\"\nCFLAGS+=\" -DNUMA\"\n\n# location of libunwind\nLIBUNWIND=\"$LIBUNWIND_BASE/lib/libunwind${MAYBE_PIC}.a\"\n\n# location of TBB\nTBB_INCLUDE=\" -isystem $TBB_BASE/include/\"\nTBB_LIBS=\"$TBB_BASE/lib/libtbb${MAYBE_PIC}.a\"\nCFLAGS+=\" -DTBB\"\n\n# location of LIBURING\nLIBURING_INCLUDE=\" -isystem $LIBURING_BASE/include/\"\nLIBURING_LIBS=\"$LIBURING_BASE/lib/liburing${MAYBE_PIC}.a\"\nCFLAGS+=\" -DLIBURING\"\n\ntest \"$USE_SSE\" || USE_SSE=1\nexport USE_SSE\ntest \"$PORTABLE\" || PORTABLE=1\nexport PORTABLE\n\nBINUTILS=\"$BINUTILS_BASE/bin\"\nAR=\"$BINUTILS/ar\"\nAS=\"$BINUTILS/as\"\n\nDEPS_INCLUDE=\"$SNAPPY_INCLUDE $ZLIB_INCLUDE $BZIP_INCLUDE $LZ4_INCLUDE $ZSTD_INCLUDE $GFLAGS_INCLUDE $NUMA_INCLUDE $TBB_INCLUDE $LIBURING_INCLUDE $BENCHMARK_INCLUDE\"\n\nSTDLIBS=\"-L $GCC_BASE/lib64\"\n\nCLANG_BIN=\"$CLANG_BASE/bin\"\nCLANG_LIB=\"$CLANG_BASE/lib\"\nCLANG_SRC=\"$CLANG_BASE/../../src\"\n\nCLANG_ANALYZER=\"$CLANG_BIN/clang++\"\nCLANG_SCAN_BUILD=\"$CLANG_SRC/llvm/clang/tools/scan-build/bin/scan-build\"\n\nif [ -z \"$USE_CLANG\" ]; then\n  # gcc\n  CC=\"$GCC_BASE/bin/gcc\"\n  CXX=\"$GCC_BASE/bin/g++\"\n  AR=\"$GCC_BASE/bin/gcc-ar\"\n\n  CFLAGS+=\" -B$BINUTILS -nostdinc -nostdlib\"\n  CFLAGS+=\" -I$GCC_BASE/include\"\n  CFLAGS+=\" -isystem $GCC_BASE/lib/gcc/x86_64-redhat-linux-gnu/11.2.1/include\"\n  CFLAGS+=\" -isystem $GCC_BASE/lib/gcc/x86_64-redhat-linux-gnu/11.2.1/install-tools/include\"\n  CFLAGS+=\" -isystem $GCC_BASE/lib/gcc/x86_64-redhat-linux-gnu/11.2.1/include-fixed/\"\n  CFLAGS+=\" -isystem $LIBGCC_INCLUDE\"\n  CFLAGS+=\" -isystem $GLIBC_INCLUDE\"\n  CFLAGS+=\" -I$GLIBC_INCLUDE\"\n  CFLAGS+=\" -I$LIBGCC_BASE/include\"\n  CFLAGS+=\" -I$LIBGCC_BASE/include/c++/11.x/\"\n  CFLAGS+=\" -I$LIBGCC_BASE/include/c++/11.x/x86_64-facebook-linux/\"\n  CFLAGS+=\" -I$LIBGCC_BASE/include/c++/11.x/backward\"\n  CFLAGS+=\" -isystem $GLIBC_INCLUDE -I$GLIBC_INCLUDE\"\n  JEMALLOC=1\nelse\n  # clang\n  CLANG_INCLUDE=\"$CLANG_LIB/clang/stable/include\"\n  CC=\"$CLANG_BIN/clang\"\n  CXX=\"$CLANG_BIN/clang++\"\n  AR=\"$CLANG_BIN/llvm-ar\"\n\n  CFLAGS+=\" -B$BINUTILS -nostdinc -nostdlib\"\n  CFLAGS+=\" -isystem $LIBGCC_BASE/include/c++/trunk \"\n  CFLAGS+=\" -isystem $LIBGCC_BASE/include/c++/trunk/x86_64-facebook-linux \"\n  CFLAGS+=\" -isystem $GLIBC_INCLUDE\"\n  CFLAGS+=\" -isystem $LIBGCC_INCLUDE\"\n  CFLAGS+=\" -isystem $CLANG_INCLUDE\"\n  CFLAGS+=\" -Wno-expansion-to-defined \"\n  CXXFLAGS=\"-nostdinc++\"\nfi\n\nKERNEL_HEADERS_INCLUDE=\"$KERNEL_HEADERS_BASE/include\"\nCFLAGS+=\" -isystem $KERNEL_HEADERS_INCLUDE/linux \"\nCFLAGS+=\" -isystem $KERNEL_HEADERS_INCLUDE \"\n\nCFLAGS+=\" $DEPS_INCLUDE\"\nCFLAGS+=\" -DROCKSDB_PLATFORM_POSIX -DROCKSDB_LIB_IO_POSIX -DROCKSDB_FALLOCATE_PRESENT -DROCKSDB_MALLOC_USABLE_SIZE -DROCKSDB_RANGESYNC_PRESENT -DROCKSDB_SCHED_GETCPU_PRESENT -DROCKSDB_IOURING_PRESENT\"\nCXXFLAGS+=\" $CFLAGS\"\n\nEXEC_LDFLAGS=\" $SNAPPY_LIBS $ZLIB_LIBS $BZIP_LIBS $LZ4_LIBS $ZSTD_LIBS $GFLAGS_LIBS $NUMA_LIB $TBB_LIBS $LIBURING_LIBS $BENCHMARK_LIBS\"\nEXEC_LDFLAGS+=\" -Wl,--dynamic-linker,/usr/local/fbcode/platform010/lib/ld.so\"\nEXEC_LDFLAGS+=\" $LIBUNWIND\"\nEXEC_LDFLAGS+=\" -Wl,-rpath=/usr/local/fbcode/platform010/lib\"\nEXEC_LDFLAGS+=\" -Wl,-rpath=$GCC_BASE/lib64\"\n# required by libtbb\nEXEC_LDFLAGS+=\" -ldl\"\n\nPLATFORM_LDFLAGS=\"$LIBGCC_LIBS $GLIBC_LIBS $STDLIBS -lgcc -lstdc++\"\nPLATFORM_LDFLAGS+=\" -B$BINUTILS\"\n\nEXEC_LDFLAGS_SHARED=\"$SNAPPY_LIBS $ZLIB_LIBS $BZIP_LIBS $LZ4_LIBS $ZSTD_LIBS $GFLAGS_LIBS $TBB_LIBS $LIBURING_LIBS $BENCHMARK_LIBS\"\n\nVALGRIND_VER=\"$VALGRIND_BASE/bin/\"\n\nexport CC CXX AR AS CFLAGS CXXFLAGS EXEC_LDFLAGS EXEC_LDFLAGS_SHARED VALGRIND_VER JEMALLOC_LIB JEMALLOC_INCLUDE CLANG_ANALYZER CLANG_SCAN_BUILD LUA_PATH LUA_LIB\n", "num_lines": 176}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# fail early\nset -e\n\nif test -z $ROCKSDB_PATH; then\n  ROCKSDB_PATH=~/rocksdb\nfi\nsource $ROCKSDB_PATH/build_tools/fbcode_config4.8.1.sh\n\nEXTRA_LDFLAGS=\"\"\n\nif test -z $ALLOC; then\n  # default\n  ALLOC=tcmalloc\nelif [[ $ALLOC == \"jemalloc\" ]]; then\n  ALLOC=system\n  EXTRA_LDFLAGS+=\" -Wl,--whole-archive $JEMALLOC_LIB -Wl,--no-whole-archive\"\nfi\n\n# we need to force mongo to use static library, not shared\nSTATIC_LIB_DEP_DIR='build/static_library_dependencies'\ntest -d $STATIC_LIB_DEP_DIR || mkdir $STATIC_LIB_DEP_DIR\ntest -h $STATIC_LIB_DEP_DIR/`basename $SNAPPY_LIBS` || ln -s $SNAPPY_LIBS $STATIC_LIB_DEP_DIR\ntest -h $STATIC_LIB_DEP_DIR/`basename $LZ4_LIBS` || ln -s $LZ4_LIBS $STATIC_LIB_DEP_DIR\n\nEXTRA_LDFLAGS+=\" -L $STATIC_LIB_DEP_DIR\"\n\nset -x\n\nEXTRA_CMD=\"\"\nif ! test -e version.json; then\n  # this is Mongo 3.0\n  EXTRA_CMD=\"--rocksdb \\\n    --variant-dir=linux2/norm\n    --cxx=${CXX} \\\n    --cc=${CC} \\\n    --use-system-zlib\"  # add this line back to normal code path\n                        # when https://jira.mongodb.org/browse/SERVER-19123 is resolved\nfi\n\nscons \\\n  LINKFLAGS=\"$EXTRA_LDFLAGS $EXEC_LDFLAGS $PLATFORM_LDFLAGS\" \\\n  CCFLAGS=\"$CXXFLAGS -L $STATIC_LIB_DEP_DIR\" \\\n  LIBS=\"lz4 gcc stdc++\" \\\n  LIBPATH=\"$ROCKSDB_PATH\" \\\n  CPPPATH=\"$ROCKSDB_PATH/include\" \\\n  -j32 \\\n  --allocator=$ALLOC \\\n  --nostrip \\\n  --opt=on \\\n  --disable-minimum-compiler-version-enforcement \\\n  --use-system-snappy \\\n  --disable-warnings-as-errors \\\n  $EXTRA_CMD $*\n", "num_lines": 56}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# If clang_format_diff.py command is not specfied, we assume we are able to\n# access directly without any path.\n\nprint_usage () {\n  echo \"Usage:\"\n  echo \"format-diff.sh [OPTIONS]\"\n  echo \"-c: check only.\"\n  echo \"-h: print this message.\"\n}\n\nwhile getopts ':ch' OPTION; do\n  case \"$OPTION\" in\n    c)\n      CHECK_ONLY=1\n      ;;\n    h)\n      print_usage\n      exit 1\n      ;;\n    ?)\n      print_usage\n      exit 1\n      ;;\n  esac\ndone\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel)\"\n\nif [ \"$CLANG_FORMAT_DIFF\" ]; then\n  echo \"Note: CLANG_FORMAT_DIFF='$CLANG_FORMAT_DIFF'\"\n  # Dry run to confirm dependencies like argparse\n  if $CLANG_FORMAT_DIFF --help >/dev/null < /dev/null; then\n    true #Good\n  else\n    exit 128\n  fi\nelse\n  # First try directly executing the possibilities\n  if clang-format-diff --help &> /dev/null < /dev/null; then\n    CLANG_FORMAT_DIFF=clang-format-diff\n  elif clang-format-diff.py --help &> /dev/null < /dev/null; then\n    CLANG_FORMAT_DIFF=clang-format-diff.py\n  elif $REPO_ROOT/clang-format-diff.py --help &> /dev/null < /dev/null; then\n    CLANG_FORMAT_DIFF=$REPO_ROOT/clang-format-diff.py\n  else\n    # This probably means we need to directly invoke the interpreter.\n    # But first find clang-format-diff.py\n    if [ -f \"$REPO_ROOT/clang-format-diff.py\" ]; then\n      CFD_PATH=\"$REPO_ROOT/clang-format-diff.py\"\n    elif which clang-format-diff.py &> /dev/null; then\n      CFD_PATH=\"$(which clang-format-diff.py)\"\n    else\n      echo \"You didn't have clang-format-diff.py and/or clang-format available in your computer!\"\n      echo \"You can download clang-format-diff.py by running: \"\n      echo \"    curl --location https://raw.githubusercontent.com/llvm/llvm-project/main/clang/tools/clang-format/clang-format-diff.py -o ${REPO_ROOT}/clang-format-diff.py\"\n      echo \"You should make sure the downloaded script is not compromised.\"\n      echo \"You can download clang-format by running:\"\n      echo \"    brew install clang-format\"\n      echo \"  Or\"\n      echo \"    apt install clang-format\"\n      echo \"  This might work too:\"\n      echo \"    yum install git-clang-format\"\n      echo \"Then make sure clang-format is available and executable from \\$PATH:\"\n      echo \"    clang-format --version\"\n      exit 128\n    fi\n    # Check argparse pre-req on interpreter, or it will fail\n    if echo import argparse | ${PYTHON:-python3}; then\n      true # Good\n    else\n      echo \"To run clang-format-diff.py, we'll need the library \"argparse\" to be\"\n      echo \"installed. You can try either of the follow ways to install it:\"\n      echo \"  1. Manually download argparse: https://pypi.python.org/pypi/argparse\"\n      echo \"  2. easy_install argparse (if you have easy_install)\"\n      echo \"  3. pip install argparse (if you have pip)\"\n      exit 129\n    fi\n    # Unfortunately, some machines have a Python2 clang-format-diff.py\n    # installed but only a Python3 interpreter installed. Unfortunately,\n    # automatic 2to3 migration is insufficient, so suggest downloading latest.\n    if grep -q \"print '\" \"$CFD_PATH\" && \\\n       ${PYTHON:-python3} --version | grep -q 'ython 3'; then\n      echo \"You have clang-format-diff.py for Python 2 but are using a Python 3\"\n      echo \"interpreter (${PYTHON:-python3}).\"\n      echo \"You can download clang-format-diff.py for Python 3 by running: \"\n      echo \"    curl --location https://raw.githubusercontent.com/llvm/llvm-project/main/clang/tools/clang-format/clang-format-diff.py -o ${REPO_ROOT}/clang-format-diff.py\"\n      echo \"You should make sure the downloaded script is not compromised.\"\n      exit 130\n    fi\n    CLANG_FORMAT_DIFF=\"${PYTHON:-python3} $CFD_PATH\"\n    # This had better work after all those checks\n    if $CLANG_FORMAT_DIFF --help >/dev/null < /dev/null; then\n      true #Good\n    else\n      exit 128\n    fi\n  fi\nfi\n\n# TODO(kailiu) following work is not complete since we still need to figure\n# out how to add the modified files done pre-commit hook to git's commit index.\n#\n# Check if this script has already been added to pre-commit hook.\n# Will suggest user to add this script to pre-commit hook if their pre-commit\n# is empty.\n# PRE_COMMIT_SCRIPT_PATH=\"`git rev-parse --show-toplevel`/.git/hooks/pre-commit\"\n# if ! ls $PRE_COMMIT_SCRIPT_PATH &> /dev/null\n# then\n#   echo \"Would you like to add this script to pre-commit hook, which will do \"\n#   echo -n \"the format check for all the affected lines before you check in (y/n):\"\n#   read add_to_hook\n#   if [ \"$add_to_hook\" == \"y\" ]\n#   then\n#     ln -s `git rev-parse --show-toplevel`/build_tools/format-diff.sh $PRE_COMMIT_SCRIPT_PATH\n#   fi\n# fi\nset -e\n\nuncommitted_code=`git diff HEAD`\n\n# If there's no uncommitted changes, we assume user are doing post-commit\n# format check, in which case we'll try to check the modified lines vs. the\n# facebook/rocksdb.git main branch. Otherwise, we'll check format of the\n# uncommitted code only.\nif [ -z \"$uncommitted_code\" ]\nthen\n  # Attempt to get name of facebook/rocksdb.git remote.\n  [ \"$FORMAT_REMOTE\" ] || FORMAT_REMOTE=\"$(LC_ALL=POSIX LANG=POSIX git remote -v | grep 'facebook/rocksdb.git' | head -n 1 | cut -f 1)\"\n  # Fall back on 'origin' if that fails\n  [ \"$FORMAT_REMOTE\" ] || FORMAT_REMOTE=origin\n  # Use main branch from that remote\n  [ \"$FORMAT_UPSTREAM\" ] || FORMAT_UPSTREAM=\"$FORMAT_REMOTE/$(LC_ALL=POSIX LANG=POSIX git remote show $FORMAT_REMOTE | sed -n '/HEAD branch/s/.*: //p')\"\n  # Get the common ancestor with that remote branch. Everything after that\n  # common ancestor would be considered the contents of a pull request, so\n  # should be relevant for formatting fixes.\n  FORMAT_UPSTREAM_MERGE_BASE=\"$(git merge-base \"$FORMAT_UPSTREAM\" HEAD)\"\n  # Get the differences\n  diffs=$(git diff -U0 \"$FORMAT_UPSTREAM_MERGE_BASE\" | $CLANG_FORMAT_DIFF -p 1)\n  echo \"Checking format of changes not yet in $FORMAT_UPSTREAM...\"\nelse\n  # Check the format of uncommitted lines,\n  diffs=$(git diff -U0 HEAD | $CLANG_FORMAT_DIFF -p 1)\n  echo \"Checking format of uncommitted changes...\"\nfi\n\nif [ -z \"$diffs\" ]\nthen\n  echo \"Nothing needs to be reformatted!\"\n  exit 0\nelif [ $CHECK_ONLY ]\nthen\n  echo \"Your change has unformatted code. Please run make format!\"\n  if [ $VERBOSE_CHECK ]; then\n    clang-format --version\n    echo \"$diffs\"\n  fi\n  exit 1\nfi\n\n# Highlight the insertion/deletion from the clang-format-diff.py's output\nCOLOR_END=\"\\033[0m\"\nCOLOR_RED=\"\\033[0;31m\"\nCOLOR_GREEN=\"\\033[0;32m\"\n\necho -e \"Detect lines that doesn't follow the format rules:\\r\"\n# Add the color to the diff. lines added will be green; lines removed will be red.\necho \"$diffs\" |\n  sed -e \"s/\\(^-.*$\\)/`echo -e \\\"$COLOR_RED\\1$COLOR_END\\\"`/\" |\n  sed -e \"s/\\(^+.*$\\)/`echo -e \\\"$COLOR_GREEN\\1$COLOR_END\\\"`/\"\n\necho -e \"Would you like to fix the format automatically (y/n): \\c\"\n\n# Make sure under any mode, we can read user input.\nexec < /dev/tty\nread to_fix\n\nif [ \"$to_fix\" != \"y\" ]\nthen\n  exit 1\nfi\n\n# Do in-place format adjustment.\nif [ -z \"$uncommitted_code\" ]\nthen\n  git diff -U0 \"$FORMAT_UPSTREAM_MERGE_BASE\" | $CLANG_FORMAT_DIFF -i -p 1\nelse\n  git diff -U0 HEAD | $CLANG_FORMAT_DIFF -i -p 1\nfi\necho \"Files reformatted!\"\n\n# Amend to last commit if user do the post-commit format check\nif [ -z \"$uncommitted_code\" ]; then\n  echo -e \"Would you like to amend the changes to last commit (`git log HEAD --oneline | head -1`)? (y/n): \\c\"\n  read to_amend\n\n  if [ \"$to_amend\" == \"y\" ]\n  then\n    git commit -a --amend --reuse-message HEAD\n    echo \"Amended to last commit\"\n  fi\nfi\n", "num_lines": 204}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC1113\n#/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n\nfunction log() {\n  echo \"[+] $1\"\n}\n\nfunction fatal() {\n  echo \"[!] $1\"\n  exit 1\n}\n\nfunction platform() {\n  local  __resultvar=$1\n  if [[ -f \"/etc/yum.conf\" ]]; then\n    eval $__resultvar=\"centos\"\n  elif [[ -f \"/etc/dpkg/dpkg.cfg\" ]]; then\n    eval $__resultvar=\"ubuntu\"\n  else\n    fatal \"Unknwon operating system\"\n  fi\n}\nplatform OS\n\nfunction package() {\n  if [[ $OS = \"ubuntu\" ]]; then\n    if dpkg --get-selections | grep --quiet $1; then\n      log \"$1 is already installed. skipping.\"\n    else\n      # shellcheck disable=SC2068\n      apt-get install $@ -y\n    fi\n  elif [[ $OS = \"centos\" ]]; then\n    if rpm -qa | grep --quiet $1; then\n      log \"$1 is already installed. skipping.\"\n    else\n      # shellcheck disable=SC2068\n      yum install $@ -y\n    fi\n  fi\n}\n\nfunction detect_fpm_output() {\n  if [[ $OS = \"ubuntu\" ]]; then\n    export FPM_OUTPUT=deb\n  elif [[ $OS = \"centos\" ]]; then\n    export FPM_OUTPUT=rpm\n  fi\n}\ndetect_fpm_output\n\nfunction gem_install() {\n  if gem list | grep --quiet $1; then\n    log \"$1 is already installed. skipping.\"\n  else\n    # shellcheck disable=SC2068\n    gem install $@\n  fi\n}\n\nfunction main() {\n  if [[ $# -ne 1 ]]; then\n    fatal \"Usage: $0 <rocksdb_version>\"\n  else\n    log \"using rocksdb version: $1\"\n  fi\n\n  if [[ -d /vagrant ]]; then\n    if [[ $OS = \"ubuntu\" ]]; then\n      package g++-4.8\n      export CXX=g++-4.8\n\n      # the deb would depend on libgflags2, but the static lib is the only thing\n      # installed by make install\n      package libgflags-dev\n\n      package ruby-all-dev\n    elif [[ $OS = \"centos\" ]]; then\n      pushd /etc/yum.repos.d\n      if [[ ! -f /etc/yum.repos.d/devtools-1.1.repo ]]; then\n        wget http://people.centos.org/tru/devtools-1.1/devtools-1.1.repo\n      fi\n      package devtoolset-1.1-gcc --enablerepo=testing-1.1-devtools-6\n      package devtoolset-1.1-gcc-c++ --enablerepo=testing-1.1-devtools-6\n      export CC=/opt/centos/devtoolset-1.1/root/usr/bin/gcc\n      export CPP=/opt/centos/devtoolset-1.1/root/usr/bin/cpp\n      export CXX=/opt/centos/devtoolset-1.1/root/usr/bin/c++\n      export PATH=$PATH:/opt/centos/devtoolset-1.1/root/usr/bin\n      popd\n      if ! rpm -qa | grep --quiet gflags; then\n        rpm -i https://github.com/schuhschuh/gflags/releases/download/v2.1.0/gflags-devel-2.1.0-1.amd64.rpm\n      fi\n\n      package ruby\n      package ruby-devel\n      package rubygems\n      package rpm-build\n    fi\n  fi\n  gem_install fpm\n\n  make static_lib\n  LIBDIR=/usr/lib\n  if [[ $FPM_OUTPUT = \"rpm\" ]]; then\n      LIBDIR=$(rpm --eval '%_libdir')\n  fi\n\n  rm -rf package\n  make install DESTDIR=package PREFIX=/usr LIBDIR=$LIBDIR\n\n  fpm \\\n    -s dir \\\n    -t $FPM_OUTPUT \\\n    -C package \\\n    -n rocksdb \\\n    -v $1 \\\n    --url http://rocksdb.org/ \\\n    -m rocksdb@fb.com \\\n    --license BSD \\\n    --vendor Facebook \\\n    --description \"RocksDB is an embeddable persistent key-value store for fast storage.\" \\\n    usr\n}\n\n# shellcheck disable=SC2068\nmain $@\n", "num_lines": 130}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n\nNUM=10000000\n\nif [ $# -eq 1 ];then\n  DATA_DIR=$1\nelif [ $# -eq 2 ];then\n  DATA_DIR=$1\n  STAT_FILE=$2\nfi\n\n# On the production build servers, set data and stat\n# files/directories not in /tmp or else the tempdir cleaning\n# scripts will make you very unhappy.\nDATA_DIR=${DATA_DIR:-$(mktemp -t -d rocksdb_XXXX)}\nSTAT_FILE=${STAT_FILE:-$(mktemp -t -u rocksdb_test_stats_XXXX)}\n\nfunction cleanup {\n  rm -rf $DATA_DIR\n  rm -f $STAT_FILE.*\n}\n\ntrap cleanup EXIT\n\nmake release\n\n# measure fillseq + fill up the DB for overwrite benchmark\n./db_bench \\\n    --benchmarks=fillseq \\\n    --db=$DATA_DIR \\\n    --use_existing_db=0 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --writes=$NUM \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0  > ${STAT_FILE}.fillseq\n\n# measure overwrite performance\n./db_bench \\\n    --benchmarks=overwrite \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --writes=$((NUM / 10)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6  \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=8 > ${STAT_FILE}.overwrite\n\n# fill up the db for readrandom benchmark (1GB total size)\n./db_bench \\\n    --benchmarks=fillseq \\\n    --db=$DATA_DIR \\\n    --use_existing_db=0 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --writes=$NUM \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=1 > /dev/null\n\n# measure readrandom with 6GB block cache\n./db_bench \\\n    --benchmarks=readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --reads=$((NUM / 5)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readrandom\n\n# measure readrandom with 6GB block cache and tailing iterator\n./db_bench \\\n    --benchmarks=readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --reads=$((NUM / 5)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --use_tailing_iterator=1 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readrandomtailing\n\n# measure readrandom with 100MB block cache\n./db_bench \\\n    --benchmarks=readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --reads=$((NUM / 5)) \\\n    --cache_size=104857600 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readrandomsmallblockcache\n\n# measure readrandom with 8k data in memtable\n./db_bench \\\n    --benchmarks=overwrite,readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$NUM \\\n    --reads=$((NUM / 5)) \\\n    --writes=512 \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --write_buffer_size=1000000000 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readrandom_mem_sst\n\n\n# fill up the db for readrandom benchmark with filluniquerandom (1GB total size)\n./db_bench \\\n    --benchmarks=filluniquerandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=0 \\\n    --bloom_bits=10 \\\n    --num=$((NUM / 4)) \\\n    --writes=$((NUM / 4)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=1 > /dev/null\n\n# dummy test just to compact the data\n./db_bench \\\n    --benchmarks=readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$((NUM / 1000)) \\\n    --reads=$((NUM / 1000)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > /dev/null\n\n# measure readrandom after load with filluniquerandom with 6GB block cache\n./db_bench \\\n    --benchmarks=readrandom \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$((NUM / 4)) \\\n    --reads=$((NUM / 4)) \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --disable_auto_compactions=1 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readrandom_filluniquerandom\n\n# measure readwhilewriting after load with filluniquerandom with 6GB block cache\n./db_bench \\\n    --benchmarks=readwhilewriting \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --bloom_bits=10 \\\n    --num=$((NUM / 4)) \\\n    --reads=$((NUM / 4)) \\\n    --benchmark_write_rate_limit=$(( 110 * 1024 )) \\\n    --write_buffer_size=100000000 \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=16 > ${STAT_FILE}.readwhilewriting\n\n# measure memtable performance -- none of the data gets flushed to disk\n./db_bench \\\n    --benchmarks=fillrandom,readrandom, \\\n    --db=$DATA_DIR \\\n    --use_existing_db=0 \\\n    --num=$((NUM / 10)) \\\n    --reads=$NUM \\\n    --cache_size=6442450944 \\\n    --cache_numshardbits=6 \\\n    --table_cache_numshardbits=4 \\\n    --write_buffer_size=1000000000 \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --value_size=10 \\\n    --threads=16 > ${STAT_FILE}.memtablefillreadrandom\n\ncommon_in_mem_args=\"--db=/dev/shm/rocksdb \\\n    --num_levels=6 \\\n    --key_size=20 \\\n    --prefix_size=12 \\\n    --keys_per_prefix=10 \\\n    --value_size=100 \\\n    --compression_type=none \\\n    --compression_ratio=1 \\\n    --write_buffer_size=134217728 \\\n    --max_write_buffer_number=4 \\\n    --level0_file_num_compaction_trigger=8 \\\n    --level0_slowdown_writes_trigger=16 \\\n    --level0_stop_writes_trigger=24 \\\n    --target_file_size_base=134217728 \\\n    --max_bytes_for_level_base=1073741824 \\\n    --disable_wal=0 \\\n    --wal_dir=/dev/shm/rocksdb \\\n    --sync=0 \\\n    --verify_checksum=1 \\\n    --delete_obsolete_files_period_micros=314572800 \\\n    --use_plain_table=1 \\\n    --open_files=-1 \\\n    --mmap_read=1 \\\n    --mmap_write=0 \\\n    --bloom_bits=10 \\\n    --bloom_locality=1 \\\n    --perf_level=0\"\n\n# prepare a in-memory DB with 50M keys, total DB size is ~6G\n./db_bench \\\n    $common_in_mem_args \\\n    --statistics=0 \\\n    --max_background_compactions=16 \\\n    --max_background_flushes=16 \\\n    --benchmarks=filluniquerandom \\\n    --use_existing_db=0 \\\n    --num=52428800 \\\n    --threads=1 > /dev/null\n\n# Readwhilewriting\n./db_bench \\\n    $common_in_mem_args \\\n    --statistics=1 \\\n    --max_background_compactions=4 \\\n    --max_background_flushes=0 \\\n    --benchmarks=readwhilewriting\\\n    --use_existing_db=1 \\\n    --duration=600 \\\n    --threads=32 \\\n    --benchmark_write_rate_limit=9502720 > ${STAT_FILE}.readwhilewriting_in_ram\n\n# Seekrandomwhilewriting\n./db_bench \\\n    $common_in_mem_args \\\n    --statistics=1 \\\n    --max_background_compactions=4 \\\n    --max_background_flushes=0 \\\n    --benchmarks=seekrandomwhilewriting \\\n    --use_existing_db=1 \\\n    --use_tailing_iterator=1 \\\n    --duration=600 \\\n    --threads=32 \\\n    --benchmark_write_rate_limit=9502720 > ${STAT_FILE}.seekwhilewriting_in_ram\n\n# measure fillseq with bunch of column families\n./db_bench \\\n    --benchmarks=fillseq \\\n    --num_column_families=500 \\\n    --write_buffer_size=1048576 \\\n    --db=$DATA_DIR \\\n    --use_existing_db=0 \\\n    --num=$NUM \\\n    --writes=$NUM \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0  > ${STAT_FILE}.fillseq_lots_column_families\n\n# measure overwrite performance with bunch of column families\n./db_bench \\\n    --benchmarks=overwrite \\\n    --num_column_families=500 \\\n    --write_buffer_size=1048576 \\\n    --db=$DATA_DIR \\\n    --use_existing_db=1 \\\n    --num=$NUM \\\n    --writes=$((NUM / 10)) \\\n    --open_files=55000 \\\n    --statistics=1 \\\n    --histogram=1 \\\n    --disable_wal=1 \\\n    --sync=0 \\\n    --threads=8 > ${STAT_FILE}.overwrite_lots_column_families\n\n# send data to ods\nfunction send_to_ods {\n  key=\"$1\"\n  value=\"$2\"\n\n  if [ -z $JENKINS_HOME ]; then\n    # running on devbox, just print out the values\n    echo $1 $2\n    return\n  fi\n\n  if [ -z \"$value\" ];then\n    echo >&2 \"ERROR: Key $key doesn't have a value.\"\n    return\n  fi\n  curl --silent \"https://www.facebook.com/intern/agent/ods_set.php?entity=rocksdb_build&key=$key&value=$value\" \\\n    --connect-timeout 60\n}\n\nfunction send_benchmark_to_ods {\n  bench=\"$1\"\n  bench_key=\"$2\"\n  file=\"$3\"\n\n  QPS=$(grep $bench $file | awk '{print $5}')\n  P50_MICROS=$(grep $bench $file -A 6 | grep \"Percentiles\" | awk '{print $3}' )\n  P75_MICROS=$(grep $bench $file -A 6 | grep \"Percentiles\" | awk '{print $5}' )\n  P99_MICROS=$(grep $bench $file -A 6 | grep \"Percentiles\" | awk '{print $7}' )\n\n  send_to_ods rocksdb.build.$bench_key.qps $QPS\n  send_to_ods rocksdb.build.$bench_key.p50_micros $P50_MICROS\n  send_to_ods rocksdb.build.$bench_key.p75_micros $P75_MICROS\n  send_to_ods rocksdb.build.$bench_key.p99_micros $P99_MICROS\n}\n\nsend_benchmark_to_ods overwrite overwrite $STAT_FILE.overwrite\nsend_benchmark_to_ods fillseq fillseq $STAT_FILE.fillseq\nsend_benchmark_to_ods readrandom readrandom $STAT_FILE.readrandom\nsend_benchmark_to_ods readrandom readrandom_tailing $STAT_FILE.readrandomtailing\nsend_benchmark_to_ods readrandom readrandom_smallblockcache $STAT_FILE.readrandomsmallblockcache\nsend_benchmark_to_ods readrandom readrandom_memtable_sst $STAT_FILE.readrandom_mem_sst\nsend_benchmark_to_ods readrandom readrandom_fillunique_random $STAT_FILE.readrandom_filluniquerandom\nsend_benchmark_to_ods fillrandom memtablefillrandom $STAT_FILE.memtablefillreadrandom\nsend_benchmark_to_ods readrandom memtablereadrandom $STAT_FILE.memtablefillreadrandom\nsend_benchmark_to_ods readwhilewriting readwhilewriting $STAT_FILE.readwhilewriting\nsend_benchmark_to_ods readwhilewriting readwhilewriting_in_ram ${STAT_FILE}.readwhilewriting_in_ram\nsend_benchmark_to_ods seekrandomwhilewriting seekwhilewriting_in_ram ${STAT_FILE}.seekwhilewriting_in_ram\nsend_benchmark_to_ods fillseq fillseq_lots_column_families ${STAT_FILE}.fillseq_lots_column_families\nsend_benchmark_to_ods overwrite overwrite_lots_column_families ${STAT_FILE}.overwrite_lots_column_families\n", "num_lines": 397}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nset -ex\n\nROCKSDB_VERSION=\"6.7.3\"\nZSTD_VERSION=\"1.4.4\"\n\necho \"This script configures CentOS with everything needed to build and run RocksDB\"\n\nyum update -y && yum install epel-release -y\n\nyum install -y \\\n  wget \\\n  gcc-c++ \\\n  snappy snappy-devel \\\n  zlib zlib-devel \\\n  bzip2 bzip2-devel \\\n  lz4-devel \\\n  libasan \\\n  gflags\n\nmkdir -pv /usr/local/rocksdb-${ROCKSDB_VERSION}\nln -sfT /usr/local/rocksdb-${ROCKSDB_VERSION} /usr/local/rocksdb\n\nwget -qO /tmp/zstd-${ZSTD_VERSION}.tar.gz https://github.com/facebook/zstd/archive/v${ZSTD_VERSION}.tar.gz\nwget -qO /tmp/rocksdb-${ROCKSDB_VERSION}.tar.gz https://github.com/facebook/rocksdb/archive/v${ROCKSDB_VERSION}.tar.gz\n\ncd /tmp\n\ntar xzvf zstd-${ZSTD_VERSION}.tar.gz\ntar xzvf rocksdb-${ROCKSDB_VERSION}.tar.gz -C /usr/local/\n\necho \"Installing ZSTD...\"\npushd zstd-${ZSTD_VERSION}\nmake && make install\npopd\n\necho \"Compiling RocksDB...\"\ncd /usr/local/rocksdb\nchown -R vagrant:vagrant /usr/local/rocksdb/\nsudo -u vagrant make static_lib\ncd examples/\nsudo -u vagrant LD_LIBRARY_PATH=/usr/local/lib/ make all\nsudo -u vagrant LD_LIBRARY_PATH=/usr/local/lib/ ./c_simple_example\n\n", "num_lines": 46}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# Update dependencies.sh file with the latest avaliable versions\n\nBASEDIR=$(dirname $0)\nOUTPUT=\"\"\n\nfunction log_header()\n{\n  echo \"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\" >> \"$OUTPUT\"\n  echo \"# The file is generated using update_dependencies.sh.\" >> \"$OUTPUT\"\n}\n\n\nfunction log_variable()\n{\n  echo \"$1=${!1}\" >> \"$OUTPUT\"\n}\n\n\nTP2_LATEST=\"/data/users/$USER/fbsource/fbcode/third-party2/\"\n## $1 => lib name\n## $2 => lib version (if not provided, will try to pick latest)\n## $3 => platform (if not provided, will try to pick latest gcc)\n##\n## get_lib_base will set a variable named ${LIB_NAME}_BASE to the lib location\nfunction get_lib_base()\n{\n  local lib_name=$1\n  local lib_version=$2\n  local lib_platform=$3\n\n  local result=\"$TP2_LATEST/$lib_name/\"\n  \n  # Lib Version\n  if [ -z \"$lib_version\" ] || [ \"$lib_version\" = \"LATEST\" ]; then\n    # version is not provided, use latest\n    result=`ls -dr1v $result/*/ | head -n1`\n  else\n    result=\"$result/$lib_version/\"\n  fi\n  \n  # Lib Platform\n  if [ -z \"$lib_platform\" ]; then\n    # platform is not provided, use latest gcc\n    result=`ls -dr1v $result/gcc-*[^fb]/ | head -n1`\n  else\n    echo $lib_platform\n    result=\"$result/$lib_platform/\"\n  fi\n  \n  result=`ls -1d $result/*/ | head -n1`\n\n  echo Finding link $result\n  \n  # lib_name => LIB_NAME_BASE\n  local __res_var=${lib_name^^}\"_BASE\"\n  __res_var=`echo $__res_var | tr - _`\n  # LIB_NAME_BASE=$result\n  eval $__res_var=`readlink -f $result`\n  \n  log_variable $__res_var\n}\n\n###########################################################\n#                platform010 dependencies                 #\n###########################################################\n\nOUTPUT=\"$BASEDIR/dependencies_platform010.sh\"\n\nrm -f \"$OUTPUT\"\ntouch \"$OUTPUT\"\n\necho \"Writing dependencies to $OUTPUT\"\n\n# Compilers locations\nGCC_BASE=`readlink -f $TP2_LATEST/gcc/11.x/centos7-native/*/`\nCLANG_BASE=`readlink -f $TP2_LATEST/llvm-fb/12/platform010/*/`\n\nlog_header\nlog_variable GCC_BASE\nlog_variable CLANG_BASE\n\n# Libraries locations\nget_lib_base libgcc     11.x    platform010\nget_lib_base glibc      2.34    platform010\nget_lib_base snappy     LATEST  platform010\nget_lib_base zlib       LATEST  platform010\nget_lib_base bzip2      LATEST  platform010\nget_lib_base lz4        LATEST  platform010\nget_lib_base zstd       LATEST  platform010\nget_lib_base gflags     LATEST  platform010\nget_lib_base jemalloc   LATEST  platform010\nget_lib_base numa       LATEST  platform010\nget_lib_base libunwind  LATEST  platform010\nget_lib_base tbb        2018_U5 platform010\nget_lib_base liburing   LATEST  platform010\nget_lib_base benchmark  LATEST  platform010\n\nget_lib_base kernel-headers fb platform010\nget_lib_base binutils   LATEST centos7-native\nget_lib_base valgrind   LATEST platform010\nget_lib_base lua        5.3.4  platform010\n\ngit diff $OUTPUT\n", "num_lines": 107}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nif [ \"$#\" = \"0\" ]; then\n  echo \"Usage: $0 major|minor|patch|full\"\n  exit 1\nfi\n\nif [ \"$1\" = \"major\" ]; then\n  cat include/rocksdb/version.h  | grep MAJOR | head -n1 | awk '{print $3}'\nfi\nif [ \"$1\" = \"minor\" ]; then\n  cat include/rocksdb/version.h  | grep MINOR | head -n1 | awk '{print $3}'\nfi\nif [ \"$1\" = \"patch\" ]; then\n  cat include/rocksdb/version.h  | grep PATCH | head -n1 | awk '{print $3}'\nfi\nif [ \"$1\" = \"full\" ]; then\n  awk '/#define ROCKSDB/ { env[$2] = $3 }\n       END { printf \"%s.%s.%s\\n\", env[\"ROCKSDB_MAJOR\"],\n                                  env[\"ROCKSDB_MINOR\"],\n                                  env[\"ROCKSDB_PATCH\"] }'  \\\n      include/rocksdb/version.h\nfi\n", "num_lines": 24}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\n# Exit on error.\nset -e\n\nif [ -n \"$USE_CLANG\" ]; then\n  echo \"Error: Coverage test is supported only for gcc.\"\n  exit 1\nfi\n\nROOT=\"..\"\n# Fetch right version of gcov\nif [ -d /mnt/gvfs/third-party -a -z \"$CXX\" ]; then\n  source $ROOT/build_tools/fbcode_config_platform010.sh\n  GCOV=$GCC_BASE/bin/gcov\nelse\n  GCOV=$(which gcov)\nfi\necho -e \"Using $GCOV\"\n\nCOVERAGE_DIR=\"$PWD/COVERAGE_REPORT\"\nmkdir -p $COVERAGE_DIR\n\n# Find all gcno files to generate the coverage report\n\nPYTHON=${1:-`which python3`}\necho -e \"Using $PYTHON\"\nGCNO_FILES=`find $ROOT -name \"*.gcno\"`\n$GCOV --preserve-paths --relative-only --no-output $GCNO_FILES 2>/dev/null |\n  # Parse the raw gcov report to more human readable form.\n  $PYTHON $ROOT/coverage/parse_gcov_output.py |\n  # Write the output to both stdout and report file.\n  tee $COVERAGE_DIR/coverage_report_all.txt &&\necho -e \"Generated coverage report for all files: $COVERAGE_DIR/coverage_report_all.txt\\n\"\n\n# TODO: we also need to get the files of the latest commits.\n# Get the most recently committed files.\nLATEST_FILES=`\n  git show --pretty=\"format:\" --name-only HEAD |\n  grep -v \"^$\" |\n  paste -s -d,`\nRECENT_REPORT=$COVERAGE_DIR/coverage_report_recent.txt\n\necho -e \"Recently updated files: $LATEST_FILES\\n\" > $RECENT_REPORT\n$GCOV --preserve-paths --relative-only --no-output $GCNO_FILES 2>/dev/null |\n  $PYTHON $ROOT/coverage/parse_gcov_output.py -interested-files $LATEST_FILES |\n  tee -a $RECENT_REPORT &&\necho -e \"Generated coverage report for recently updated files: $RECENT_REPORT\\n\"\n\n# Unless otherwise specified, we'll not generate html report by default\nif [ -z \"$HTML\" ]; then\n  exit 0\nfi\n\n# Generate the html report. If we cannot find lcov in this machine, we'll simply\n# skip this step.\necho \"Generating the html coverage report...\"\n\nLCOV=$(which lcov || true 2>/dev/null)\nif [ -z $LCOV ]\nthen\n  echo \"Skip: Cannot find lcov to generate the html report.\"\n  exit 0\nfi\n\nLCOV_VERSION=$(lcov -v | grep 1.1 || true)\nif [ $LCOV_VERSION ]\nthen\n  echo \"Not supported lcov version. Expect lcov 1.1.\"\n  exit 0\nfi\n\n(cd $ROOT; lcov --no-external \\\n     --capture  \\\n     --directory $PWD \\\n     --gcov-tool $GCOV \\\n     --output-file $COVERAGE_DIR/coverage.info)\n\ngenhtml $COVERAGE_DIR/coverage.info -o $COVERAGE_DIR\n\necho \"HTML Coverage report is generated in $COVERAGE_DIR\"\n", "num_lines": 83}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC2148\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nPLATFORM=64\nif [ `getconf LONG_BIT` != \"64\" ]\nthen\n  PLATFORM=32\nfi\n\nROCKS_JAR=`find target -name rocksdbjni*.jar`\n\necho \"Running benchmark in $PLATFORM-Bit mode.\"\n# shellcheck disable=SC2068\njava -server -d$PLATFORM -XX:NewSize=4m -XX:+AggressiveOpts -Djava.library.path=target -cp \"${ROCKS_JAR}:benchmark/target/classes\" org.rocksdb.benchmark.DbBenchmark $@\n", "num_lines": 14}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n\n# update Alpine with latest versions\necho '@edge http://nl.alpinelinux.org/alpine/edge/main' >> /etc/apk/repositories\necho '@community http://nl.alpinelinux.org/alpine/edge/community' >> /etc/apk/repositories\napk update\napk upgrade\n\n# install CA certificates\napk add ca-certificates\n\n# install build tools\napk add \\\n  build-base \\\n  coreutils \\\n  file \\\n  git \\\n  perl \\\n  automake \\\n  autoconf \\\n  cmake\n\n# install tool dependencies for building RocksDB static library\napk add \\\n  curl \\\n  bash \\\n  wget \\\n  tar \\\n  openssl\n\n# install RocksDB dependencies\napk add \\\n  snappy snappy-dev \\\n  zlib zlib-dev \\\n  bzip2 bzip2-dev \\\n  lz4 lz4-dev \\\n  zstd zstd-dev \\\n  linux-headers \\\n  jemalloc jemalloc-dev\n\n# install OpenJDK7\napk add openjdk7 \\\n  && apk add java-cacerts \\\n  && rm /usr/lib/jvm/java-1.7-openjdk/jre/lib/security/cacerts \\\n  && ln -s /etc/ssl/certs/java/cacerts /usr/lib/jvm/java-1.7-openjdk/jre/lib/security/cacerts\n\n# cleanup\nrm -rf /var/cache/apk/*\n\n# puts javac in the PATH\nexport JAVA_HOME=/usr/lib/jvm/java-1.7-openjdk\nexport PATH=/usr/lib/jvm/java-1.7-openjdk/bin:$PATH\n\n# gflags from source\ncd /tmp &&\\\n  git clone -b v2.0 --single-branch https://github.com/gflags/gflags.git &&\\\n  cd gflags &&\\\n  ./configure --prefix=/usr && make && make install &&\\\n  rm -rf /tmp/*\n\n\n# build rocksdb\ncd /rocksdb\nmake jclean clean\nPORTABLE=1 make -j8 rocksdbjavastatic\ncp /rocksdb/java/target/librocksdbjni-* /rocksdb-build\ncp /rocksdb/java/target/rocksdbjni-* /rocksdb-build\n", "num_lines": 71}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n\n# remove fixed relesever variable present in the hanscode boxes\nsudo rm -f /etc/yum/vars/releasever\n\n# enable EPEL\nsudo yum -y install epel-release\n\n# install all required packages for rocksdb that are available through yum\nsudo yum -y install openssl java-1.7.0-openjdk-devel zlib-devel bzip2-devel lz4-devel snappy-devel libzstd-devel jemalloc-devel cmake3\n\n# set up cmake3 as cmake binary\nsudo alternatives --install /usr/local/bin/cmake cmake /usr/bin/cmake 10 --slave /usr/local/bin/ctest ctest /usr/bin/ctest --slave /usr/local/bin/cpack cpack /usr/bin/cpack --slave /usr/local/bin/ccmake ccmake /usr/bin/ccmake\nsudo alternatives --install /usr/local/bin/cmake cmake /usr/bin/cmake3 20 --slave /usr/local/bin/ctest ctest /usr/bin/ctest3 --slave /usr/local/bin/cpack cpack /usr/bin/cpack3 --slave /usr/local/bin/ccmake ccmake /usr/bin/ccmake3\n\n# install gcc/g++ 4.8.2 from tru/devtools-2\nsudo wget -O /etc/yum.repos.d/devtools-2.repo https://people.centos.org/tru/devtools-2/devtools-2.repo\nsudo yum -y install devtoolset-2-binutils devtoolset-2-gcc devtoolset-2-gcc-c++\n\n# install gflags\nwget https://github.com/gflags/gflags/archive/v2.0.tar.gz -O gflags-2.0.tar.gz\ntar xvfz gflags-2.0.tar.gz; cd gflags-2.0; scl enable devtoolset-2 ./configure; scl enable devtoolset-2 make; sudo make install\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/lib\n\n# set java home so we can build rocksdb jars\nexport JAVA_HOME=/usr/lib/jvm/java-1.7.0\n\nexport PATH=$JAVA_HOME:/usr/local/bin:$PATH\n\n# build rocksdb\ncd /rocksdb\nscl enable devtoolset-2 'make clean-not-downloaded'\nscl enable devtoolset-2 'PORTABLE=1 make -j8 rocksdbjavastatic'\ncp /rocksdb/java/target/librocksdbjni-* /rocksdb-build\ncp /rocksdb/java/target/rocksdbjni-* /rocksdb-build\n", "num_lines": 39}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# install all required packages for rocksdb\nsudo apt-get update\nsudo apt-get -y install git make gcc g++ libgflags-dev libsnappy-dev zlib1g-dev libbz2-dev default-jdk\n\n# set java home so we can build rocksdb jars\nexport JAVA_HOME=$(echo /usr/lib/jvm/java-7-openjdk*)\ncd /rocksdb\nmake jclean clean\nmake -j 4 rocksdbjavastatic\ncp /rocksdb/java/target/librocksdbjni-* /rocksdb-build\ncp /rocksdb/java/target/rocksdbjni-* /rocksdb-build\nsudo shutdown -h now\n\n", "num_lines": 16}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n#set -x\n\n# just in-case this is run outside Docker\nmkdir -p /rocksdb-local-build\n\nrm -rf /rocksdb-local-build/*\ncp -r /rocksdb-host/* /rocksdb-local-build\ncd /rocksdb-local-build\n\nmake clean-not-downloaded\nPORTABLE=1 make -j2 rocksdbjavastatic\n\ncp java/target/librocksdbjni-linux*.so java/target/rocksdbjni-*-linux*.jar java/target/rocksdbjni-*-linux*.jar.sha1 /rocksdb-java-target\n", "num_lines": 18}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n\nset -e\n#set -x\n\n# just in-case this is run outside Docker\nmkdir -p /rocksdb-local-build\n\nrm -rf /rocksdb-local-build/*\ncp -r /rocksdb-host/* /rocksdb-local-build\ncd /rocksdb-local-build\n\n# Use scl devtoolset if available\nif hash scl 2>/dev/null; then\n  if scl --list | grep -q 'devtoolset-8'; then\n                # CentOS 6+\n                scl enable devtoolset-8 'make clean-not-downloaded'\n                scl enable devtoolset-8 'PORTABLE=1 make -j2 rocksdbjavastatic'\n  elif scl --list | grep -q 'devtoolset-7'; then\n    # CentOS 6+\n    scl enable devtoolset-7 'make clean-not-downloaded'\n    scl enable devtoolset-7 'PORTABLE=1 make -j2 rocksdbjavastatic'\n  elif scl --list | grep -q 'devtoolset-2'; then\n    # CentOS 5 or 6\n    scl enable devtoolset-2 'make clean-not-downloaded'\n    scl enable devtoolset-2 'PORTABLE=1 make -j2 rocksdbjavastatic'\n  else\n    echo \"Could not find devtoolset\"\n    exit 1;\n  fi\nelse\n  make clean-not-downloaded\n  PORTABLE=1 make -j2 rocksdbjavastatic\nfi\n\ncp java/target/librocksdbjni-linux*.so java/target/rocksdbjni-*-linux*.jar java/target/rocksdbjni-*-linux*.jar.sha1 /rocksdb-java-target\n\n", "num_lines": 39}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# Usage:\n# 1. Enable ROCKS_LOG_DETAILS in util/logging.h\n# 2. Run ./transaction_test --gtest_filter=\"MySQLStyleTransactionTest/MySQLStyleTransactionTest.TransactionStressTest/*\" --gtest_break_on_failure\n# 3. SET=1 # 2 or 3\n# 4. LOG=/dev/shm/transaction_testdb_8600601584148590297/LOG\n# 5. grep RandomTransactionVerify $LOG | cut -d' ' -f 12 | sort -n # to find verify snapshots\n# 5. vn=1345\n# 6. vn_1=1340\n# 4. . tools/tools/analyze_txn_stress_test.sh\necho Input params:\n# The rocksdb LOG path\necho $LOG\n# Snapshot at which we got RandomTransactionVerify failure\necho $vn\n# The snapshot before that where RandomTransactionVerify passed\necho $vn_1\n# The stress tests use 3 sets, one or more might have shown inconsistent results.\nSET=${SET-1} # 1 or 2 or 3\necho Checking set number $SET\n\n# Find the txns that committed between the two snapshots, and gather their changes made by them in /tmp/changes.txt\n# 2019/02/28-15:25:51.655477 7fffec9ff700 [DEBUG] [ilities/transactions/write_prepared_txn_db.cc:416] Txn 68497 Committing with 68498\ngrep Committing $LOG | awk '{if ($9 <= vn && $9 > vn_1) print $0}' vn=$vn vn_1=${vn_1} > /tmp/txn.txt\n# 2019/02/28-15:25:49.046464 7fffe81f5700 [DEBUG] [il/transaction_test_util.cc:216] Commit of 65541 OK (txn12936193128775589751-9089)\nfor i in `cat /tmp/txn.txt | awk '{print $6}'`; do grep \"Commit of $i \" $LOG; done > /tmp/names.txt\nfor n in `cat /tmp/names.txt | awk '{print $9}'`; do grep $n $LOG; done > /tmp/changes.txt\necho \"Sum of the changes:\"\ncat /tmp/changes.txt | grep Insert | awk '{print $12}' | cut -d= -f1 | cut -d+ -f2 | awk '{sum+=$1} END{print sum}'\n\n# Gather read values at each snapshot\n# 2019/02/28-15:25:51.655926 7fffebbff700 [DEBUG] [il/transaction_test_util.cc:347] VerifyRead at 67972 (67693): 000230 value: 15983\ngrep \"VerifyRead at ${vn_1} (.*): 000${SET}\" $LOG | cut -d' ' -f 9- > /tmp/va.txt\ngrep \"VerifyRead at ${vn} (.*): 000${SET}\" $LOG | cut -d' ' -f 9- > /tmp/vb.txt\n\n# For each key in the 2nd snapshot, find the value read by 1st, do the adds, and see if the results match.\nIFS=$'\\n'\nfor l in `cat /tmp/vb.txt`; \ndo\n  grep $l /tmp/va.txt > /dev/null ; \n  if [[ $? -ne 0 ]]; then \n    #echo $l\n    k=`echo $l | awk '{print $1}'`;\n    v=`echo $l | awk '{print $3}'`;\n    # 2019/02/28-15:25:19.350111 7fffe81f5700 [DEBUG] [il/transaction_test_util.cc:194] Insert (txn12936193128775589751-2298) OK snap: 16289 key:000219 value: 3772+95=3867\n    exp=`grep \"\\<$k\\>\" /tmp/changes.txt | tail -1 | cut -d= -f2`;\n    if [[ $v -ne $exp ]]; then echo $l; fi\n  else\n    k=`echo $l | awk '{print $1}'`;\n    grep \"\\<$k\\>\" /tmp/changes.txt\n  fi;\ndone\n\n# Check that all the keys read in the 1st snapshot are still visible in the 2nd\nfor l in `cat /tmp/va.txt`; \ndo\n  k=`echo $l | awk '{print $1}'`;\n  grep \"\\<$k\\>\" /tmp/vb.txt > /dev/null\n  if [[ $? -ne 0 ]]; then\n    echo missing key $k\n  fi\ndone\n\n# The following found a bug in ValidateSnapshot. It checks if the adds on each key match up.\ngrep Insert /tmp/changes.txt | cut -d' ' -f 10 | sort | uniq > /tmp/keys.txt\nfor k in `cat /tmp/keys.txt`;\ndo\n  grep \"\\<$k\\>\" /tmp/changes.txt > /tmp/adds.txt;\n  # 2019/02/28-15:25:19.350111 7fffe81f5700 [DEBUG] [il/transaction_test_util.cc:194] Insert (txn12936193128775589751-2298) OK snap: 16289 key:000219 value: 3772+95=3867\n  START=`head -1 /tmp/adds.txt | cut -d' ' -f 12 | cut -d+ -f1`\n  END=`tail -1 /tmp/adds.txt | cut -d' ' -f 12 | cut -d= -f2`\n  ADDS=`cat /tmp/adds.txt | grep Insert | awk '{print $12}' | cut -d= -f1 | cut -d+ -f2 | awk '{sum+=$1} END{print sum}'`\n  EXP=$((START+ADDS))\n  # If first + all the adds != last then there was an issue with ValidateSnapshot.\n  if [[ $END -ne $EXP ]]; then echo inconsistent txn: $k $START+$ADDS=$END; cat /tmp/adds.txt; return 1; fi\ndone\n", "num_lines": 78}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC2148\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nTMP_DIR=\"${TMPDIR:-/tmp}/rocksdb-sanity-test\"\n\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: ./auto_sanity_test.sh [new_commit] [old_commit]\"\n  echo \"Missing either [new_commit] or [old_commit], perform sanity check with the latest and 10th latest commits.\"\n  recent_commits=`git log | grep -e \"^commit [a-z0-9]\\+$\"| head -n10 | sed -e 's/commit //g'`\n  commit_new=`echo \"$recent_commits\" | head -n1`\n  commit_old=`echo \"$recent_commits\" | tail -n1`\n  echo \"the most recent commits are:\"\n  echo \"$recent_commits\"\nelse\n  commit_new=$1\n  commit_old=$2\nfi\n\nif [ ! -d $TMP_DIR ]; then\n  mkdir $TMP_DIR\nfi\ndir_new=\"${TMP_DIR}/${commit_new}\"\ndir_old=\"${TMP_DIR}/${commit_old}\"\n\nfunction makestuff() {\n  echo \"make clean\"\n  make clean > /dev/null\n  echo \"make db_sanity_test -j32\"\n  make db_sanity_test -j32 > /dev/null\n  if [ $? -ne 0 ]; then\n    echo \"[ERROR] Failed to perform 'make db_sanity_test'\"\n    exit 1\n  fi\n}\n\nrm -r -f $dir_new\nrm -r -f $dir_old\n\necho \"Running db sanity check with commits $commit_new and $commit_old.\"\n\necho \"=============================================================\"\necho \"Making build $commit_new\"\ngit checkout $commit_new\nif [ $? -ne 0 ]; then\n  echo \"[ERROR] Can't checkout $commit_new\"\n  exit 1\nfi\nmakestuff\nmv db_sanity_test new_db_sanity_test\necho \"Creating db based on the new commit --- $commit_new\"\n./new_db_sanity_test $dir_new create\ncp ./tools/db_sanity_test.cc $dir_new\ncp ./tools/auto_sanity_test.sh $dir_new\n\necho \"=============================================================\"\necho \"Making build $commit_old\"\ngit checkout $commit_old\nif [ $? -ne 0 ]; then\n  echo \"[ERROR] Can't checkout $commit_old\"\n  exit 1\nfi\ncp -f $dir_new/db_sanity_test.cc ./tools/.\ncp -f $dir_new/auto_sanity_test.sh ./tools/.\nmakestuff\nmv db_sanity_test old_db_sanity_test\necho \"Creating db based on the old commit --- $commit_old\"\n./old_db_sanity_test $dir_old create\n\necho \"=============================================================\"\necho \"[Backward Compatibility Check]\"\necho \"Verifying old db $dir_old using the new commit --- $commit_new\"\n./new_db_sanity_test $dir_old verify\nif [ $? -ne 0 ]; then\n  echo \"[ERROR] Backward Compatibility Check fails:\"\n  echo \"    Verification of $dir_old using commit $commit_new failed.\"\n  exit 2\nfi\n\necho \"=============================================================\"\necho \"[Forward Compatibility Check]\"\necho \"Verifying new db $dir_new using the old commit --- $commit_old\"\n./old_db_sanity_test $dir_new verify\nif [ $? -ne 0 ]; then\n  echo \"[ERROR] Forward Compatibility Check fails:\"\n  echo \"    $dir_new using commit $commit_old failed.\"\n  exit 2\nfi\n\nrm old_db_sanity_test\nrm new_db_sanity_test\nrm -rf $dir_new\nrm -rf $dir_old\n\necho \"Auto sanity test passed!\"\n", "num_lines": 94}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n#\n\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: ${BASH_SOURCE[0]} <DB Path> <Backup Dir>\"\n  exit 1\nfi\n\ndb_dir=\"$1\"\nbackup_dir=\"$2\"\n\necho \"== Backing up DB $db_dir to $backup_dir\"\n./ldb backup --db=\"$db_dir\" --backup_dir=\"$backup_dir\"\n", "num_lines": 16}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# REQUIRE: db_bench binary exists in the current directory\n\n# Exit Codes\nEXIT_INVALID_ARGS=1\nEXIT_NOT_COMPACTION_TEST=2\nEXIT_UNKNOWN_JOB=3\n\n# Size Constants\nK=1024\nM=$((1024 * K))\nG=$((1024 * M))\nT=$((1024 * G))\n\nfunction display_usage() {\n  echo \"usage: benchmark.sh [--help] <test>\"\n  echo \"\"\n  echo \"These are the available benchmark tests:\"\n  echo -e \"\\tbulkload\"\n  echo -e \"\\tfillseq_disable_wal\\t\\tSequentially fill the database with no WAL\"\n  echo -e \"\\tfillseq_enable_wal\\t\\tSequentially fill the database with WAL\"\n  echo -e \"\\toverwrite\"\n  echo -e \"\\tupdaterandom\"\n  echo -e \"\\treadrandom\"\n  echo -e \"\\tmergerandom\"\n  echo -e \"\\tfilluniquerandom\"\n  echo -e \"\\tmultireadrandom\"\n  echo -e \"\\tfwdrange\"\n  echo -e \"\\trevrange\"\n  echo -e \"\\treadwhilewriting\"\n  echo -e \"\\treadwhilemerging\"\n  echo -e \"\\tfwdrangewhilewriting\"\n  echo -e \"\\trevrangewhilewriting\"\n  echo -e \"\\tfwdrangewhilemerging\"\n  echo -e \"\\trevrangewhilemerging\"\n  echo -e \"\\trandomtransaction\"\n  echo -e \"\\tuniversal_compaction\"\n  echo -e \"\\tdebug\"\n  echo \"\"\n  echo \"Generic enviroment Variables:\"\n  echo -e \"\\tJOB_ID\\t\\t\\t\\tAn identifier for the benchmark job, will appear in the results\"\n  echo -e \"\\tDB_DIR\\t\\t\\t\\tPath to write the database data directory\"\n  echo -e \"\\tWAL_DIR\\t\\t\\t\\tPath to write the database WAL directory\"\n  echo -e \"\\tOUTPUT_DIR\\t\\t\\tPath to write the benchmark results to (default: /tmp)\"\n  echo -e \"\\tNUM_KEYS\\t\\t\\tThe number of keys to use in the benchmark\"\n  echo -e \"\\tKEY_SIZE\\t\\t\\tThe size of the keys to use in the benchmark (default: 20 bytes)\"\n  echo -e \"\\tVALUE_SIZE\\t\\t\\tThe size of the values to use in the benchmark (default: 400 bytes)\"\n  echo -e \"\\tBLOCK_SIZE\\t\\t\\tThe size of the database blocks in the benchmark (default: 8 KB)\"\n  echo -e \"\\tDB_BENCH_NO_SYNC\\t\\tDisable fsync on the WAL\"\n  echo -e \"\\tNUMACTL\\t\\t\\t\\tWhen defined use numactl --interleave=all\"\n  echo -e \"\\tNUM_THREADS\\t\\t\\tThe number of threads to use (default: 64)\"\n  echo -e \"\\tMB_WRITE_PER_SEC\\t\\t\\tRate limit for background writer\"\n  echo -e \"\\tNUM_NEXTS_PER_SEEK\\t\\t(default: 10)\"\n  echo -e \"\\tCACHE_SIZE\\t\\t\\tSize of the block cache (default: 16GB)\"\n  echo -e \"\\tCACHE_NUMSHARDBITS\\t\\t\\tNumber of shards for the block cache is 2 ** cache_numshardbits (default: 6)\"\n  echo -e \"\\tCOMPRESSION_MAX_DICT_BYTES\"\n  echo -e \"\\tCOMPRESSION_TYPE\\t\\tDefault compression(default: zstd)\"\n  echo -e \"\\tBOTTOMMOST_COMPRESSION\\t\\t(default: none)\"\n  echo -e \"\\tMIN_LEVEL_TO_COMPRESS\\t\\tValue for min_level_to_compress for Leveled\"\n  echo -e \"\\tCOMPRESSION_SIZE_PERCENT\\tValue for compression_size_percent for Universal\"\n  echo -e \"\\tDURATION\\t\\t\\tNumber of seconds for which the test runs\"\n  echo -e \"\\tWRITES\\t\\t\\t\\tNumber of writes for which the test runs\"\n  echo -e \"\\tWRITE_BUFFER_SIZE_MB\\t\\tThe size of the write buffer in MB (default: 128)\"\n  echo -e \"\\tTARGET_FILE_SIZE_BASE_MB\\tThe value for target_file_size_base in MB (default: 128)\"\n  echo -e \"\\tMAX_BYTES_FOR_LEVEL_BASE_MB\\tThe value for max_bytes_for_level_base in MB (default: 128)\"\n  echo -e \"\\tMAX_BACKGROUND_JOBS\\t\\tThe value for max_background_jobs (default: 16)\"\n  echo -e \"\\tCACHE_INDEX_AND_FILTER_BLOCKS\\tThe value for cache_index_and_filter_blocks (default: 0)\"\n  echo -e \"\\tUSE_O_DIRECT\\t\\t\\tUse O_DIRECT for user reads and compaction\"\n  echo -e \"\\tBYTES_PER_SYNC\\t\\t\\tValue for bytes_per_sync, set to zero when USE_O_DIRECT is true\"\n  echo -e \"\\tSTATS_INTERVAL_SECONDS\\t\\tValue for stats_interval_seconds\"\n  echo -e \"\\tREPORT_INTERVAL_SECONDS\\t\\tValue for report_interval_seconds\"\n  echo -e \"\\tSUBCOMPACTIONS\\t\\t\\tValue for subcompactions\"\n  echo -e \"\\tCOMPACTION_STYLE\\t\\tOne of leveled, universal, blob. Default is leveled.\"\n  echo -e \"\\nEnvironment variables (mostly) for leveled compaction:\"\n  echo -e \"\\tLEVEL0_FILE_NUM_COMPACTION_TRIGGER\\t\\tValue for level0_file_num_compaction_trigger\"\n  echo -e \"\\tLEVEL0_SLOWDOWN_WRITES_TRIGGER\\t\\t\\tValue for level0_slowdown_writes_trigger\"\n  echo -e \"\\tLEVEL0_STOP_WRITES_TRIGGER\\t\\t\\tValue for level0_stop_writes_trigger\"\n  echo -e \"\\tPER_LEVEL_FANOUT\\t\\t\\t\\tValue for max_bytes_for_level_multiplier\"\n  echo -e \"\\tSOFT_PENDING_COMPACTION_BYTES_LIMIT_IN_GB\\tThe value for soft_pending_compaction_bytes_limit in GB\"\n  echo -e \"\\tHARD_PENDING_COMPACTION_BYTES_LIMIT_IN_GB\\tThe value for hard_pending_compaction_bytes_limit in GB\"\n  echo -e \"\\nEnvironment variables for universal compaction:\"\n  echo -e \"\\tUNIVERSAL_MIN_MERGE_WIDTH\\tValue of min_merge_width option for universal\"\n  echo -e \"\\tUNIVERSAL_MAX_MERGE_WIDTH\\tValue of min_merge_width option for universal\"\n  echo -e \"\\tUNIVERSAL_SIZE_RATIO\\t\\tValue of size_ratio option for universal\"\n  echo -e \"\\tUNIVERSAL_MAX_SIZE_AMP\\t\\tmax_size_amplification_percent for universal\"\n  echo -e \"\\tUNIVERSAL_ALLOW_TRIVIAL_MOVE\\tSet allow_trivial_move to true for universal, default is false\"\n  echo -e \"\\nOptions for integrated BlobDB\"\n  echo -e \"\\tMIN_BLOB_SIZE\\tValue for min_blob_size\"\n  echo -e \"\\tBLOB_FILE_SIZE\\tValue for blob_file_size\"\n  echo -e \"\\tBLOB_COMPRESSION_TYPE\\tValue for blob_compression_type\"\n  echo -e \"\\tBLOB_GC_AGE_CUTOFF\\tValue for blob_garbage_collection_age_cutoff\"\n  echo -e \"\\tBLOB_GC_FORCE_THRESHOLD\\tValue for blob_garbage_collection_force_threshold\"\n  echo -e \"\\tBLOB_FILE_STARTING_LEVEL\\t\\tBlob file starting level (default: 0)\"\n  echo -e \"\\tUSE_BLOB_CACHE\\t\\t\\tEnable blob cache (default: 1)\"\n  echo -e \"\\tUSE_SHARED_BLOCK_AND_BLOB_CACHE\\t\\t\\tUse the same backing cache for block cache and blob cache (default: 1)\"\n  echo -e \"\\tBLOB_CACHE_SIZE\\t\\t\\tSize of the blob cache (default: 16GB)\"\n  echo -e \"\\tBLOB_CACHE_NUMSHARDBITS\\t\\t\\tNumber of shards for the blob cache is 2 ** blob_cache_numshardbits (default: 6)\"\n  echo -e \"\\tPREPOPULATE_BLOB_CACHE\\t\\t\\tPre-populate hot/warm blobs in blob cache (default: 0)\"\n}\n\nif [ $# -lt 1 ]; then\n  display_usage\n  exit $EXIT_INVALID_ARGS\nfi\nbench_cmd=$1\nshift\nbench_args=$*\n\nif [[ \"$bench_cmd\" == \"--help\" ]]; then\n  display_usage\n  exit\nfi\n\njob_id=${JOB_ID}\n\n# Make it easier to run only the compaction test. Getting valid data requires\n# a number of iterations and having an ability to run the test separately from\n# rest of the benchmarks helps.\nif [ \"$COMPACTION_TEST\" == \"1\" -a \"$bench_cmd\" != \"universal_compaction\" ]; then\n  echo \"Skipping $1 because it's not a compaction test.\"\n  exit $EXIT_NOT_COMPACTION_TEST\nfi\n\nif [ -z $DB_DIR ]; then\n  echo \"DB_DIR is not defined\"\n  exit $EXIT_INVALID_ARGS\nfi\n\nif [ -z $WAL_DIR ]; then\n  echo \"WAL_DIR is not defined\"\n  exit $EXIT_INVALID_ARGS\nfi\n\noutput_dir=${OUTPUT_DIR:-/tmp}\nif [ ! -d $output_dir ]; then\n  mkdir -p $output_dir\nfi\n\nreport=\"$output_dir/report.tsv\"\nschedule=\"$output_dir/schedule.txt\"\n\n# all multithreaded tests run with sync=1 unless\n# $DB_BENCH_NO_SYNC is defined\nsyncval=\"1\"\nif [ ! -z $DB_BENCH_NO_SYNC ]; then\n  echo \"Turning sync off for all multithreaded tests\"\n  syncval=\"0\";\nfi\n\ncompaction_style=${COMPACTION_STYLE:-leveled}\nif [ $compaction_style = \"leveled\" ]; then\n  echo Use leveled compaction\nelif [ $compaction_style = \"universal\" ]; then\n  echo Use universal compaction\nelif [ $compaction_style = \"blob\" ]; then\n  echo Use blob compaction\nelse\n  echo COMPACTION_STYLE is :: $COMPACTION_STYLE :: and must be one of leveled, universal, blob\n  exit $EXIT_INVALID_ARGS\nfi\n\nnum_threads=${NUM_THREADS:-64}\nmb_written_per_sec=${MB_WRITE_PER_SEC:-0}\n# Only for tests that do range scans\nnum_nexts_per_seek=${NUM_NEXTS_PER_SEEK:-10}\ncache_size=${CACHE_SIZE:-$(( 16 * $G ))}\ncache_numshardbits=${CACHE_NUMSHARDBITS:-6}\ncompression_max_dict_bytes=${COMPRESSION_MAX_DICT_BYTES:-0}\ncompression_type=${COMPRESSION_TYPE:-zstd}\nmin_level_to_compress=${MIN_LEVEL_TO_COMPRESS:-\"-1\"}\ncompression_size_percent=${COMPRESSION_SIZE_PERCENT:-\"-1\"}\n\nduration=${DURATION:-0}\nwrites=${WRITES:-0}\n\nnum_keys=${NUM_KEYS:-8000000000}\nkey_size=${KEY_SIZE:-20}\nvalue_size=${VALUE_SIZE:-400}\nblock_size=${BLOCK_SIZE:-8192}\nwrite_buffer_mb=${WRITE_BUFFER_SIZE_MB:-128}\ntarget_file_mb=${TARGET_FILE_SIZE_BASE_MB:-128}\nl1_mb=${MAX_BYTES_FOR_LEVEL_BASE_MB:-1024}\nmax_background_jobs=${MAX_BACKGROUND_JOBS:-16}\nstats_interval_seconds=${STATS_INTERVAL_SECONDS:-60}\nreport_interval_seconds=${REPORT_INTERVAL_SECONDS:-1}\nsubcompactions=${SUBCOMPACTIONS:-1}\nper_level_fanout=${PER_LEVEL_FANOUT:-8}\n\ncache_index_and_filter=${CACHE_INDEX_AND_FILTER_BLOCKS:-0}\nif [[ $cache_index_and_filter -eq 0 ]]; then\n  cache_meta_flags=\"\"\nelif [[ $cache_index_and_filter -eq 1 ]]; then\n  cache_meta_flags=\"\\\n  --cache_index_and_filter_blocks=$cache_index_and_filter \\\n  --cache_high_pri_pool_ratio=0.5 --cache_low_pri_pool_ratio=0\"\nelse\n  echo CACHE_INDEX_AND_FILTER_BLOCKS was $CACHE_INDEX_AND_FILTER_BLOCKS but must be 0 or 1\n  exit $EXIT_INVALID_ARGS\nfi\n\nsoft_pending_arg=\"\"\nif [ ! -z $SOFT_PENDING_COMPACTION_BYTES_LIMIT_IN_GB ]; then\n  soft_pending_bytes=$( echo $SOFT_PENDING_COMPACTION_BYTES_LIMIT_IN_GB | \\\n    awk '{ printf \"%.0f\", $1 * GB }' GB=$G )\n  soft_pending_arg=\"--soft_pending_compaction_bytes_limit=$soft_pending_bytes\"\nfi\n\nhard_pending_arg=\"\"\nif [ ! -z $HARD_PENDING_COMPACTION_BYTES_LIMIT_IN_GB ]; then\n  hard_pending_bytes=$( echo $HARD_PENDING_COMPACTION_BYTES_LIMIT_IN_GB | \\\n    awk '{ printf \"%.0f\", $1 * GB }' GB=$G )\n  hard_pending_arg=\"--hard_pending_compaction_bytes_limit=$hard_pending_bytes\"\nfi\n\no_direct_flags=\"\"\nif [ ! -z $USE_O_DIRECT ]; then\n  # Some of these flags are only supported in new versions and --undefok makes that work\n  o_direct_flags=\"--use_direct_reads --use_direct_io_for_flush_and_compaction --prepopulate_block_cache=1\"\n  bytes_per_sync=0\nelse\n  bytes_per_sync=${BYTES_PER_SYNC:-$(( 1 * M ))}\nfi\n\nuniv_min_merge_width=${UNIVERSAL_MIN_MERGE_WIDTH:-2}\nuniv_max_merge_width=${UNIVERSAL_MAX_MERGE_WIDTH:-20}\nuniv_size_ratio=${UNIVERSAL_SIZE_RATIO:-1}\nuniv_max_size_amp=${UNIVERSAL_MAX_SIZE_AMP:-200}\n\nif [ ! -z $UNIVERSAL_ALLOW_TRIVIAL_MOVE ]; then\n  univ_allow_trivial_move=1\nelse\n  univ_allow_trivial_move=0\nfi\n\nmin_blob_size=${MIN_BLOB_SIZE:-0}\nblob_file_size=${BLOB_FILE_SIZE:-$(( 256 * $M ))}\nblob_compression_type=${BLOB_COMPRESSION_TYPE:-${compression_type}}\nblob_gc_age_cutoff=${BLOB_GC_AGE_CUTOFF:-\"0.25\"}\nblob_gc_force_threshold=${BLOB_GC_FORCE_THRESHOLD:-1}\nblob_file_starting_level=${BLOB_FILE_STARTING_LEVEL:-0}\nuse_blob_cache=${USE_BLOB_CACHE:-1}\nuse_shared_block_and_blob_cache=${USE_SHARED_BLOCK_AND_BLOB_CACHE:-1}\nblob_cache_size=${BLOB_CACHE_SIZE:-$(( 16 * $G ))}\nblob_cache_numshardbits=${BLOB_CACHE_NUMSHARDBITS:-6}\nprepopulate_blob_cache=${PREPOPULATE_BLOB_CACHE:-0}\n\n# This script still works back to RocksDB 6.0\nundef_params=\"\\\nuse_blob_cache,\\\nuse_shared_block_and_blob_cache,\\\nblob_cache_size,blob_cache_numshardbits,\\\nprepopulate_blob_cache,\\\nmultiread_batched,\\\ncache_low_pri_pool_ratio,\\\nprepopulate_block_cache\"\n\nconst_params_base=\"\n  --undefok=$undef_params \\\n  --db=$DB_DIR \\\n  --wal_dir=$WAL_DIR \\\n  \\\n  --num=$num_keys \\\n  --key_size=$key_size \\\n  --value_size=$value_size \\\n  --block_size=$block_size \\\n  --cache_size=$cache_size \\\n  --cache_numshardbits=$cache_numshardbits \\\n  --compression_max_dict_bytes=$compression_max_dict_bytes \\\n  --compression_ratio=0.5 \\\n  --compression_type=$compression_type \\\n  --bytes_per_sync=$bytes_per_sync \\\n  $cache_meta_flags \\\n  $o_direct_flags \\\n  --benchmark_write_rate_limit=$(( 1024 * 1024 * $mb_written_per_sec )) \\\n  \\\n  --write_buffer_size=$(( $write_buffer_mb * M)) \\\n  --target_file_size_base=$(( $target_file_mb * M)) \\\n  --max_bytes_for_level_base=$(( $l1_mb * M)) \\\n  \\\n  --verify_checksum=1 \\\n  --delete_obsolete_files_period_micros=$((60 * M)) \\\n  --max_bytes_for_level_multiplier=$per_level_fanout \\\n  \\\n  --statistics=0 \\\n  --stats_per_interval=1 \\\n  --stats_interval_seconds=$stats_interval_seconds \\\n  --report_interval_seconds=$report_interval_seconds \\\n  --histogram=1 \\\n  \\\n  --memtablerep=skip_list \\\n  --bloom_bits=10 \\\n  --open_files=-1 \\\n  --subcompactions=$subcompactions \\\n  \\\n  $bench_args\"\n\nlevel_const_params=\"\n  $const_params_base \\\n  --compaction_style=0 \\\n  --num_levels=8 \\\n  --min_level_to_compress=$min_level_to_compress \\\n  --level_compaction_dynamic_level_bytes=true \\\n  --pin_l0_filter_and_index_blocks_in_cache=1 \\\n  $soft_pending_arg \\\n  $hard_pending_arg \\\n\"\n\n# These inherit level_const_params because the non-blob LSM tree uses leveled compaction.\nblob_const_params=\"\n  $level_const_params \\\n  --enable_blob_files=true \\\n  --min_blob_size=$min_blob_size \\\n  --blob_file_size=$blob_file_size \\\n  --blob_compression_type=$blob_compression_type \\\n  --enable_blob_garbage_collection=true \\\n  --blob_garbage_collection_age_cutoff=$blob_gc_age_cutoff \\\n  --blob_garbage_collection_force_threshold=$blob_gc_force_threshold \\\n  --blob_file_starting_level=$blob_file_starting_level \\\n  --use_blob_cache=$use_blob_cache \\\n  --use_shared_block_and_blob_cache=$use_shared_block_and_blob_cache \\\n  --blob_cache_size=$blob_cache_size \\\n  --blob_cache_numshardbits=$blob_cache_numshardbits \\\n  --prepopulate_blob_cache=$prepopulate_blob_cache \\\n\"\n\n# TODO:\n#   pin_l0_filter_and..., is this OK?\nuniv_const_params=\"\n  $const_params_base \\\n  --compaction_style=1 \\\n  --num_levels=40 \\\n  --universal_compression_size_percent=$compression_size_percent \\\n  --pin_l0_filter_and_index_blocks_in_cache=1 \\\n  --universal_min_merge_width=$univ_min_merge_width \\\n  --universal_max_merge_width=$univ_max_merge_width \\\n  --universal_size_ratio=$univ_size_ratio \\\n  --universal_max_size_amplification_percent=$univ_max_size_amp \\\n  --universal_allow_trivial_move=$univ_allow_trivial_move \\\n\"\n\nif [ $compaction_style == \"leveled\" ]; then\n  const_params=\"$level_const_params\"\n  l0_file_num_compaction_trigger=${LEVEL0_FILE_NUM_COMPACTION_TRIGGER:-4}\n  l0_slowdown_writes_trigger=${LEVEL0_SLOWDOWN_WRITES_TRIGGER:-20}\n  l0_stop_writes_trigger=${LEVEL0_STOP_WRITES_TRIGGER:-30}\nelif [ $compaction_style == \"universal\" ]; then\n  const_params=\"$univ_const_params\"\n  l0_file_num_compaction_trigger=${LEVEL0_FILE_NUM_COMPACTION_TRIGGER:-8}\n  l0_slowdown_writes_trigger=${LEVEL0_SLOWDOWN_WRITES_TRIGGER:-20}\n  l0_stop_writes_trigger=${LEVEL0_STOP_WRITES_TRIGGER:-30}\nelse\n  # compaction_style == \"blob\"\n  const_params=\"$blob_const_params\"\n  l0_file_num_compaction_trigger=${LEVEL0_FILE_NUM_COMPACTION_TRIGGER:-4}\n  l0_slowdown_writes_trigger=${LEVEL0_SLOWDOWN_WRITES_TRIGGER:-20}\n  l0_stop_writes_trigger=${LEVEL0_STOP_WRITES_TRIGGER:-30}\nfi\n\nl0_config=\"\n  --level0_file_num_compaction_trigger=$l0_file_num_compaction_trigger \\\n  --level0_slowdown_writes_trigger=$l0_slowdown_writes_trigger \\\n  --level0_stop_writes_trigger=$l0_stop_writes_trigger\"\n\n# You probably don't want to set both --writes and --duration\nif [ $duration -gt 0 ]; then\n  const_params=\"$const_params --duration=$duration\"\nfi\nif [ $writes -gt 0 ]; then\n  const_params=\"$const_params --writes=$writes\"\nfi\n\nparams_w=\"$l0_config \\\n          --max_background_jobs=$max_background_jobs \\\n          --max_write_buffer_number=8 \\\n          $const_params\"\n\nparams_bulkload=\"--max_background_jobs=$max_background_jobs \\\n                 --max_write_buffer_number=8 \\\n                 --allow_concurrent_memtable_write=false \\\n                 --level0_file_num_compaction_trigger=$((10 * M)) \\\n                 --level0_slowdown_writes_trigger=$((10 * M)) \\\n                 --level0_stop_writes_trigger=$((10 * M)) \\\n                 $const_params \"\n\nparams_fillseq=\"--allow_concurrent_memtable_write=false \\\n                $params_w \"\n\n#\n# Tune values for level and universal compaction.\n# For universal compaction, these level0_* options mean total sorted of runs in\n# LSM. In level-based compaction, it means number of L0 files.\n#\nparams_level_compact=\"$const_params \\\n                --max_background_flushes=4 \\\n                --max_write_buffer_number=4 \\\n                --level0_file_num_compaction_trigger=4 \\\n                --level0_slowdown_writes_trigger=16 \\\n                --level0_stop_writes_trigger=20\"\n\nparams_univ_compact=\"$const_params \\\n                --max_background_flushes=4 \\\n                --max_write_buffer_number=4 \\\n                --level0_file_num_compaction_trigger=8 \\\n                --level0_slowdown_writes_trigger=16 \\\n                --level0_stop_writes_trigger=20\"\n\ntsv_header=\"ops_sec\\tmb_sec\\tlsm_sz\\tblob_sz\\tc_wgb\\tw_amp\\tc_mbps\\tc_wsecs\\tc_csecs\\tb_rgb\\tb_wgb\\tusec_op\\tp50\\tp99\\tp99.9\\tp99.99\\tpmax\\tuptime\\tstall%\\tNstall\\tu_cpu\\ts_cpu\\trss\\ttest\\tdate\\tversion\\tjob_id\\tgithash\"\n\nfunction get_cmd() {\n  output=$1\n\n  numa=\"\"\n  if [ ! -z $NUMACTL ]; then\n    numa=\"numactl --interleave=all \"\n  fi\n\n  # Try to use timeout when duration is set because some tests (revrange*) hang\n  # for some versions (v6.10, v6.11).\n  timeout_cmd=\"\"\n  if [ $duration -gt 0 ]; then\n    if hash timeout ; then\n      timeout_cmd=\"timeout $(( $duration + 600 ))\"\n    fi\n  fi\n\n  echo \"/usr/bin/time -f '%e %U %S' -o $output $numa $timeout_cmd\"\n}\n\nfunction month_to_num() {\n    local date_str=$1\n    date_str=\"${date_str/Jan/01}\"\n    date_str=\"${date_str/Feb/02}\"\n    date_str=\"${date_str/Mar/03}\"\n    date_str=\"${date_str/Apr/04}\"\n    date_str=\"${date_str/May/05}\"\n    date_str=\"${date_str/Jun/06}\"\n    date_str=\"${date_str/Jul/07}\"\n    date_str=\"${date_str/Aug/08}\"\n    date_str=\"${date_str/Sep/09}\"\n    date_str=\"${date_str/Oct/10}\"\n    date_str=\"${date_str/Nov/11}\"\n    date_str=\"${date_str/Dec/12}\"\n    echo $date_str\n}\n\nfunction start_stats {\n  output=$1\n  iostat -y -mx 1  >& $output.io &\n  vmstat 1 >& $output.vm &\n  # tail -1 because \"ps | grep db_bench\" returns 2 entries and we want the second\n  while :; do ps aux | grep db_bench | grep -v grep | tail -1; sleep 10; done >& $output.ps &\n  # This sets a global value\n  pspid=$!\n\n  while :; do\n    b_gb=$( ls -l $DB_DIR 2> /dev/null | grep blob | awk '{ c += 1; b += $5 } END { printf \"%.1f\", b / (1024*1024*1024) }' )\n    s_gb=$( ls -l $DB_DIR 2> /dev/null | grep sst | awk '{ c += 1; b += $5 } END { printf \"%.1f\", b / (1024*1024*1024) }' )\n    l_gb=$( ls -l $WAL_DIR 2> /dev/null | grep log | awk '{ c += 1; b += $5 } END { printf \"%.1f\", b / (1024*1024*1024) }' )\n    a_gb=$( ls -l $DB_DIR 2> /dev/null | awk '{ c += 1; b += $5 } END { printf \"%.1f\", b / (1024*1024*1024) }' )\n    ts=$( date +%H%M%S )\n    echo -e \"${a_gb}\\t${s_gb}\\t${l_gb}\\t${b_gb}\\t${ts}\"\n    sleep 10\n  done >& $output.sizes &\n  # This sets a global value\n  szpid=$!\n}\n\nfunction stop_stats {\n  output=$1\n  kill $pspid\n  kill $szpid\n  killall iostat\n  killall vmstat\n  sleep 1\n  gzip $output.io\n  gzip $output.vm\n\n  am=$( sort -nk 1,1 $output.sizes | tail -1 | awk '{ print $1 }' )\n  sm=$( sort -nk 2,2 $output.sizes | tail -1 | awk '{ print $2 }' )\n  lm=$( sort -nk 3,3 $output.sizes | tail -1 | awk '{ print $3 }' )\n  bm=$( sort -nk 4,4 $output.sizes | tail -1 | awk '{ print $4 }' )\n  echo -e \"max sizes (GB): $am all, $sm sst, $lm log, $bm blob\" >> $output.sizes\n}\n\nfunction units_as_gb {\n  size=$1\n  units=$2\n\n  case $units in\n    MB)\n      echo \"$size\" | awk '{ printf \"%.1f\", $1 / 1024.0 }'\n      ;;\n    GB)\n      echo \"$size\"\n      ;;\n    TB)\n      echo \"$size\" | awk '{ printf \"%.1f\", $1 * 1024.0 }'\n      ;;\n    *)\n      echo \"NA\"\n      ;;\n  esac\n}\n\nfunction summarize_result {\n  test_out=$1\n  test_name=$2\n  bench_name=$3\n\n  # In recent versions these can be found directly via db_bench --version, --build_info but\n  # grepping from the log lets this work on older versions.\n  version=\"$( grep \"RocksDB version:\" \"$DB_DIR\"/LOG | head -1 | awk '{ printf \"%s\", $5 }' )\"\n  git_hash=\"$( grep \"Git sha\" \"$DB_DIR\"/LOG | head -1 | awk '{ printf \"%s\", substr($5, 1, 10) }' )\"\n\n  # Note that this function assumes that the benchmark executes long enough so\n  # that \"Compaction Stats\" is written to stdout at least once. If it won't\n  # happen then empty output from grep when searching for \"Sum\" will cause\n  # syntax errors.\n  date=$( grep ^Date: $test_out | awk '{ print $6 \"-\" $3 \"-\" $4 \"T\" $5 }' )\n  my_date=$( month_to_num $date )\n  uptime=$( grep ^Uptime\\(secs $test_out | tail -1 | awk '{ printf \"%.0f\", $2 }' )\n  stall_pct=$( grep \"^Cumulative stall\" $test_out| tail -1  | awk '{  print $5 }' )\n  nstall=$( grep ^Stalls\\(count\\):  $test_out | tail -1 | awk '{ print $2 + $6 + $10 + $14 + $18 + $20 }' )\n\n  if ! grep ^\"$bench_name\" \"$test_out\" > /dev/null 2>&1 ; then\n    echo -e \"failed\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t$test_name\\t$my_date\\t$version\\t$job_id\\t$git_hash\"\n    return\n  fi\n\n  # Output formats\n  # V1: readrandom   :      10.218 micros/op 3131616 ops/sec; 1254.3 MB/s (176144999 of 176144999 found)\n  # The MB/s is mssing for multireadrandom\n  # V1a: multireadrandom :      10.164 micros/op 3148272 ops/sec; (177099990 of 177099990 found)\n  # V1: overwrite    :       7.939 micros/op 125963 ops/sec;   50.5 MB/s\n  # V2: overwrite    :       7.854 micros/op 127320 ops/sec 1800.001 seconds 229176999 operations;   51.0 MB/s\n\n  format_version=$( grep ^\"$bench_name\" \"$test_out\" \\\n    | awk '{ if (NF >= 10 && $8 == \"seconds\") { print \"V2\" } else { print \"V1\" } }' )\n  if [ $format_version == \"V1\" ]; then\n    ops_sec=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ print $5 }' )\n    usecs_op=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ printf \"%.1f\", $3 }' )\n    if [ \"$bench_name\" == \"multireadrandom\" ]; then\n      mb_sec=\"NA\"\n    else\n      mb_sec=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ print $7 }' )\n    fi\n  else\n    ops_sec=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ print $5 }' )\n    usecs_op=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ printf \"%.1f\", $3 }' )\n    mb_sec=$( grep ^\"$bench_name\" \"$test_out\" | awk '{ print $11 }' )\n  fi\n\n  # For RocksDB version 4.x there are fewer fields but this still parses correctly\n  # Cumulative writes: 242M writes, 242M keys, 18M commit groups, 12.9 writes per commit group, ingest: 95.96 GB, 54.69 MB/s\n  cum_writes_gb_orig=$( grep \"^Cumulative writes\" \"$test_out\" | tail -1 | awk '{ for (x=1; x<=NF; x++) { if ($x == \"ingest:\") { printf \"%.1f\", $(x+1) } } }' )\n  cum_writes_units=$( grep \"^Cumulative writes\" \"$test_out\" | tail -1 | awk '{ for (x=1; x<=NF; x++) { if ($x == \"ingest:\") { print $(x+2) } } }' | sed 's/,//g' )\n  cum_writes_gb=$( units_as_gb \"$cum_writes_gb_orig\" \"$cum_writes_units\" )\n\n  # Cumulative compaction: 1159.74 GB write, 661.03 MB/s write, 1108.89 GB read, 632.04 MB/s read, 6284.3 seconds\n  cmb_ps=$( grep \"^Cumulative compaction\" \"$test_out\" | tail -1 | awk '{ printf \"%.1f\", $6 }' )\n  sum_wgb_orig=$( grep \"^Cumulative compaction\" \"$test_out\" | tail -1 | awk '{ printf \"%.1f\", $3 }' )\n  sum_wgb_units=$( grep \"^Cumulative compaction\" \"$test_out\" | tail -1 | awk '{ print $4 }' )\n  sum_wgb=$( units_as_gb \"$sum_wgb_orig\" \"$sum_wgb_units\" )\n\n  # Flush(GB): cumulative 97.193, interval 1.247\n  flush_wgb=$( grep \"^Flush(GB)\" \"$test_out\" | tail -1 | awk '{ print $3 }' | tr ',' ' ' | awk '{ print $1 }' )\n\n  if [[ \"$sum_wgb\" == \"NA\" || \\\n        \"$cum_writes_gb\" == \"NA\" || \\\n        \"$cum_writes_gb_orig\" == \"0.0\" || \\\n        -z \"$cum_writes_gb_orig\" || \\\n        -z \"$flush_wgb\" ]]; then\n    wamp=\"NA\"\n  else\n    wamp=$( echo \"( $sum_wgb + $flush_wgb ) / $cum_writes_gb\" | bc -l | awk '{ printf \"%.1f\", $1 }' )\n  fi\n\n  c_wsecs=$( grep \"^ Sum\" $test_out | tail -1 | awk '{ printf \"%.0f\", $15 }' )\n  c_csecs=$( grep \"^ Sum\" $test_out | tail -1 | awk '{ printf \"%.0f\", $16 }' )\n\n  lsm_size=$( grep \"^ Sum\" \"$test_out\" | tail -1 | awk '{ printf \"%.0f%s\", $3, $4 }' )\n  blob_size=$( grep \"^Blob file count:\" \"$test_out\" | tail -1 | awk '{ printf \"%.0f%s\", $7, $8 }' )\n  # Remove the trailing comma from blob_size: 3.0GB, -> 3.0GB\n  blob_size=\"${blob_size/,/}\"\n\n  b_rgb=$( grep \"^ Sum\" $test_out | tail -1 | awk '{ printf \"%.0f\", $21 }' )\n  b_wgb=$( grep \"^ Sum\" $test_out | tail -1 | awk '{ printf \"%.0f\", $22 }' )\n\n  p50=$( grep \"^Percentiles:\" $test_out | tail -1 | awk '{ printf \"%.1f\", $3 }' )\n  p99=$( grep \"^Percentiles:\" $test_out | tail -1 | awk '{ printf \"%.0f\", $7 }' )\n  p999=$( grep \"^Percentiles:\" $test_out | tail -1 | awk '{ printf \"%.0f\", $9 }' )\n  p9999=$( grep \"^Percentiles:\" $test_out | tail -1 | awk '{ printf \"%.0f\", $11 }' )\n  pmax=$( grep \"^Min: \" $test_out | grep Median: | grep Max: | awk '{ printf \"%.0f\", $6 }' )\n\n  # Use the last line because there might be extra lines when the db_bench process exits with an error\n  time_out=\"$test_out\".time\n  u_cpu=$( tail -1 \"$time_out\" | awk '{ printf \"%.1f\", $2 / 1000.0 }' )\n  s_cpu=$( tail -1 \"$time_out\" | awk '{ printf \"%.1f\", $3 / 1000.0  }' )\n\n  rss=\"NA\"\n  if [ -f $test_out.stats.ps ]; then\n    rss=$( awk '{ printf \"%.1f\\n\", $6 / (1024 * 1024) }' \"$test_out\".stats.ps | sort -n | tail -1 )\n  fi\n\n  # if the report TSV (Tab Separate Values) file does not yet exist, create it and write the header row to it\n  if [ ! -f \"$report\" ]; then\n    echo -e \"# ops_sec - operations per second\" >> \"$report\"\n    echo -e \"# mb_sec - ops_sec * size-of-operation-in-MB\" >> \"$report\"\n    echo -e \"# lsm_sz - size of LSM tree\" >> \"$report\"\n    echo -e \"# blob_sz - size of BlobDB logs\" >> \"$report\"\n    echo -e \"# c_wgb - GB written by compaction\" >> \"$report\"\n    echo -e \"# w_amp - Write-amplification as (bytes written by compaction / bytes written by memtable flush)\" >> \"$report\"\n    echo -e \"# c_mbps - Average write rate for compaction\" >> \"$report\"\n    echo -e \"# c_wsecs - Wall clock seconds doing compaction\" >> \"$report\"\n    echo -e \"# c_csecs - CPU seconds doing compaction\" >> \"$report\"\n    echo -e \"# b_rgb - Blob compaction read GB\" >> \"$report\"\n    echo -e \"# b_wgb - Blob compaction write GB\" >> \"$report\"\n    echo -e \"# usec_op - Microseconds per operation\" >> \"$report\"\n    echo -e \"# p50, p99, p99.9, p99.99 - 50th, 99th, 99.9th, 99.99th percentile response time in usecs\" >> \"$report\"\n    echo -e \"# pmax - max response time in usecs\" >> \"$report\"\n    echo -e \"# uptime - RocksDB uptime in seconds\" >> \"$report\"\n    echo -e \"# stall% - Percentage of time writes are stalled\" >> \"$report\"\n    echo -e \"# Nstall - Number of stalls\" >> \"$report\"\n    echo -e \"# u_cpu - #seconds/1000 of user CPU\" >> \"$report\"\n    echo -e \"# s_cpu - #seconds/1000 of system CPU\" >> \"$report\"\n    echo -e \"# rss - max RSS in GB for db_bench process\" >> \"$report\"\n    echo -e \"# test - Name of test\" >> \"$report\"\n    echo -e \"# date - Date/time of test\" >> \"$report\"\n    echo -e \"# version - RocksDB version\" >> \"$report\"\n    echo -e \"# job_id - User-provided job ID\" >> \"$report\"\n    echo -e \"# githash - git hash at which db_bench was compiled\" >> \"$report\"\n    echo -e $tsv_header >> \"$report\"\n  fi\n\n  echo -e \"$ops_sec\\t$mb_sec\\t$lsm_size\\t$blob_size\\t$sum_wgb\\t$wamp\\t$cmb_ps\\t$c_wsecs\\t$c_csecs\\t$b_rgb\\t$b_wgb\\t$usecs_op\\t$p50\\t$p99\\t$p999\\t$p9999\\t$pmax\\t$uptime\\t$stall_pct\\t$nstall\\t$u_cpu\\t$s_cpu\\t$rss\\t$test_name\\t$my_date\\t$version\\t$job_id\\t$git_hash\" \\\n    >> \"$report\"\n}\n\nfunction run_bulkload {\n  # This runs with a vector memtable and the WAL disabled to load faster. It is still crash safe and the\n  # client can discover where to restart a load after a crash. I think this is a good way to load.\n  echo \"Bulk loading $num_keys random keys\"\n  log_file_name=$output_dir/benchmark_bulkload_fillrandom.log\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=fillrandom,stats \\\n       --use_existing_db=0 \\\n       --disable_auto_compactions=1 \\\n       --sync=0 \\\n       $params_bulkload \\\n       --threads=1 \\\n       --memtablerep=vector \\\n       --allow_concurrent_memtable_write=false \\\n       --disable_wal=1 \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  eval $cmd\n  summarize_result $log_file_name bulkload fillrandom\n\n  echo \"Compacting...\"\n  log_file_name=$output_dir/benchmark_bulkload_compact.log\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=compact,stats \\\n       --use_existing_db=1 \\\n       --disable_auto_compactions=1 \\\n       --sync=0 \\\n       $params_w \\\n       --threads=1 \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  eval $cmd\n}\n\n#\n# Parameter description:\n#\n# $1 - 1 if I/O statistics should be collected.\n# $2 - compaction type to use (level=0, universal=1).\n# $3 - number of subcompactions.\n# $4 - number of maximum background compactions.\n#\nfunction run_manual_compaction_worker {\n  # This runs with a vector memtable and the WAL disabled to load faster.\n  # It is still crash safe and the client can discover where to restart a\n  # load after a crash. I think this is a good way to load.\n  echo \"Bulk loading $num_keys random keys for manual compaction.\"\n\n  log_file_name=$output_dir/benchmark_man_compact_fillrandom_$3.log\n\n  if [ \"$2\" == \"1\" ]; then\n    extra_params=$params_univ_compact\n  else\n    extra_params=$params_level_compact\n  fi\n\n  # Make sure that fillrandom uses the same compaction options as compact.\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=fillrandom,stats \\\n       --use_existing_db=0 \\\n       --disable_auto_compactions=0 \\\n       --sync=0 \\\n       $extra_params \\\n       --threads=$num_threads \\\n       --compaction_measure_io_stats=$1 \\\n       --compaction_style=$2 \\\n       --subcompactions=$3 \\\n       --memtablerep=vector \\\n       --allow_concurrent_memtable_write=false \\\n       --disable_wal=1 \\\n       --max_background_compactions=$4 \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $log_file_name\"\n\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  eval $cmd\n\n  summarize_result $log_file_namefillrandom_output_file man_compact_fillrandom_$3 fillrandom\n\n  echo \"Compacting with $3 subcompactions specified ...\"\n\n  log_file_name=$output_dir/benchmark_man_compact_$3.log\n\n  # This is the part we're really interested in. Given that compact benchmark\n  # doesn't output regular statistics then we'll just use the time command to\n  # measure how long this step takes.\n  cmd=\"{ \\\n       time ./db_bench --benchmarks=compact,stats \\\n       --use_existing_db=1 \\\n       --disable_auto_compactions=0 \\\n       --sync=0 \\\n       $extra_params \\\n       --threads=$num_threads \\\n       --compaction_measure_io_stats=$1 \\\n       --compaction_style=$2 \\\n       --subcompactions=$3 \\\n       --max_background_compactions=$4 \\\n       ;}\n       2>&1 | tee -a $log_file_name\"\n\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  eval $cmd\n\n  # Can't use summarize_result here. One way to analyze the results is to run\n  # \"grep real\" on the resulting log files.\n}\n\nfunction run_univ_compaction {\n  # Always ask for I/O statistics to be measured.\n  io_stats=1\n\n  # Values: kCompactionStyleLevel = 0x0, kCompactionStyleUniversal = 0x1.\n  compaction_style=1\n\n  # Define a set of benchmarks.\n  subcompactions=(1 2 4 8 16)\n  max_background_compactions=(16 16 8 4 2)\n\n  i=0\n  total=${#subcompactions[@]}\n\n  # Execute a set of benchmarks to cover variety of scenarios.\n  while [ \"$i\" -lt \"$total\" ]\n  do\n    run_manual_compaction_worker $io_stats $compaction_style ${subcompactions[$i]} \\\n      ${max_background_compactions[$i]}\n    ((i++))\n  done\n}\n\nfunction run_fillseq {\n  # This runs with a vector memtable. WAL can be either disabled or enabled\n  # depending on the input parameter (1 for disabled, 0 for enabled). The main\n  # benefit behind disabling WAL is to make loading faster. It is still crash\n  # safe and the client can discover where to restart a load after a crash. I\n  # think this is a good way to load.\n\n  # Make sure that we'll have unique names for all the files so that data won't\n  # be overwritten.\n  if [ $1 == 1 ]; then\n    log_file_name=\"${output_dir}/benchmark_fillseq.wal_disabled.v${value_size}.log\"\n    test_name=fillseq.wal_disabled.v${value_size}\n  else\n    log_file_name=\"${output_dir}/benchmark_fillseq.wal_enabled.v${value_size}.log\"\n    test_name=fillseq.wal_enabled.v${value_size}\n  fi\n\n  # For Leveled compaction hardwire this to 0 so that data that is trivial-moved\n  # to larger levels (3, 4, etc) will be compressed.\n  if [ $compaction_style == \"leveled\" ]; then\n    comp_arg=\"--min_level_to_compress=0\"\n  elif [ $compaction_style == \"universal\" ]; then\n    if [ ! -z $UNIVERSAL_ALLOW_TRIVIAL_MOVE ]; then\n      # See GetCompressionFlush where compression_size_percent < 1 means use the default\n      # compression which is needed because trivial moves are enabled\n      comp_arg=\"--universal_compression_size_percent=-1\"\n    else\n      # See GetCompressionFlush where compression_size_percent > 0 means no compression.\n      # Don't set anything here because compression_size_percent is set in univ_const_params\n      comp_arg=\"\"\n    fi\n  else\n    # compaction_style == \"blob\"\n    comp_arg=\"--min_level_to_compress=0\"\n  fi\n\n  echo \"Loading $num_keys keys sequentially\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=fillseq,stats \\\n       $params_fillseq \\\n       $comp_arg \\\n       --use_existing_db=0 \\\n       --sync=0 \\\n       --threads=1 \\\n       --memtablerep=vector \\\n       --allow_concurrent_memtable_write=false \\\n       --disable_wal=$1 \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n\n  # The constant \"fillseq\" which we pass to db_bench is the benchmark name.\n  summarize_result $log_file_name $test_name fillseq\n}\n\nfunction run_lsm {\n  # This flushes the memtable and L0 to get the LSM tree into a deterministic\n  # state for read-only tests that will follow.\n  echo \"Flush memtable, wait, compact L0, wait\"\n  job=$1\n\n  if [ $job = flush_mt_l0 ]; then\n    benchmarks=levelstats,flush,waitforcompaction,compact0,waitforcompaction,memstats,levelstats\n  elif [ $job = waitforcompaction ]; then\n    benchmarks=levelstats,waitforcompaction,memstats,levelstats\n  else\n    echo Job unknown: $job\n    exit $EXIT_NOT_COMPACTION_TEST\n  fi\n\n  log_file_name=$output_dir/benchmark_${job}.log\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=$benchmarks,stats \\\n       --use_existing_db=1 \\\n       --sync=0 \\\n       $params_w \\\n       --threads=1 \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  # waitforcompaction can hang with universal (compaction_style=1)\n  # see bug https://github.com/facebook/rocksdb/issues/9275\n  eval $cmd\n  stop_stats $log_file_name.stats\n  # Don't summarize, the log doesn't have the output needed for it\n}\n\nfunction run_change {\n  output_name=$1\n  grep_name=$2\n  benchmarks=$3\n  echo \"Do $num_keys random $output_name\"\n  log_file_name=\"$output_dir/benchmark_${output_name}.t${num_threads}.s${syncval}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=$benchmarks,stats \\\n       --use_existing_db=1 \\\n       --sync=$syncval \\\n       $params_w \\\n       --threads=$num_threads \\\n       --merge_operator=\\\"put\\\" \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name ${output_name}.t${num_threads}.s${syncval} $grep_name\n}\n\nfunction run_filluniquerandom {\n  echo \"Loading $num_keys unique keys randomly\"\n  log_file_name=$output_dir/benchmark_filluniquerandom.log\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=filluniquerandom,stats \\\n       --use_existing_db=0 \\\n       --sync=0 \\\n       $params_w \\\n       --threads=1 \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name filluniquerandom filluniquerandom\n}\n\nfunction run_readrandom {\n  echo \"Reading $num_keys random keys\"\n  log_file_name=\"${output_dir}/benchmark_readrandom.t${num_threads}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=readrandom,stats \\\n       --use_existing_db=1 \\\n       $params_w \\\n       --threads=$num_threads \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name readrandom.t${num_threads} readrandom\n}\n\nfunction run_multireadrandom {\n  echo \"Multi-Reading $num_keys random keys\"\n  log_file_name=\"${output_dir}/benchmark_multireadrandom.t${num_threads}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=multireadrandom,stats \\\n       --use_existing_db=1 \\\n       --threads=$num_threads \\\n       --batch_size=10 \\\n       $params_w \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name multireadrandom.t${num_threads} multireadrandom\n}\n\nfunction run_readwhile {\n  operation=$1\n  echo \"Reading $num_keys random keys while $operation\"\n  log_file_name=\"${output_dir}/benchmark_readwhile${operation}.t${num_threads}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench --benchmarks=readwhile${operation},stats \\\n       --use_existing_db=1 \\\n       --sync=$syncval \\\n       $params_w \\\n       --threads=$num_threads \\\n       --merge_operator=\\\"put\\\" \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name readwhile${operation}.t${num_threads} readwhile${operation}\n}\n\nfunction run_rangewhile {\n  operation=$1\n  full_name=$2\n  reverse_arg=$3\n  log_file_name=\"${output_dir}/benchmark_${full_name}.t${num_threads}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  echo \"Range scan $num_keys random keys while ${operation} for reverse_iter=${reverse_arg}\"\n  cmd=\"$time_cmd ./db_bench --benchmarks=seekrandomwhile${operation},stats \\\n       --use_existing_db=1 \\\n       --sync=$syncval \\\n       $params_w \\\n       --threads=$num_threads \\\n       --merge_operator=\\\"put\\\" \\\n       --seek_nexts=$num_nexts_per_seek \\\n       --reverse_iterator=$reverse_arg \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  echo $cmd | tee $log_file_name\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name ${full_name}.t${num_threads} seekrandomwhile${operation}\n}\n\nfunction run_range {\n  full_name=$1\n  reverse_arg=$2\n  log_file_name=\"${output_dir}/benchmark_${full_name}.t${num_threads}.log\"\n  time_cmd=$( get_cmd $log_file_name.time )\n  echo \"Range scan $num_keys random keys for reverse_iter=${reverse_arg}\"\n  cmd=\"$time_cmd ./db_bench --benchmarks=seekrandom,stats \\\n       --use_existing_db=1 \\\n       $params_w \\\n       --threads=$num_threads \\\n       --seek_nexts=$num_nexts_per_seek \\\n       --reverse_iterator=$reverse_arg \\\n       --seed=$( date +%s ) \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee -a $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n  summarize_result $log_file_name ${full_name}.t${num_threads} seekrandom\n}\n\nfunction run_randomtransaction {\n  echo \"...\"\n  log_file_name=$output_dir/benchmark_randomtransaction.log\n  time_cmd=$( get_cmd $log_file_name.time )\n  cmd=\"$time_cmd ./db_bench $params_w --benchmarks=randomtransaction,stats \\\n       --num=$num_keys \\\n       --transaction_db \\\n       --threads=5 \\\n       --transaction_sets=5 \\\n       --report_file=${log_file_name}.r.csv \\\n       2>&1 | tee $log_file_name\"\n  if [[ \"$job_id\" != \"\" ]]; then\n    echo \"Job ID: ${job_id}\" > $log_file_name\n    echo $cmd | tee -a $log_file_name\n  else\n    echo $cmd | tee $log_file_name\n  fi\n  start_stats $log_file_name.stats\n  eval $cmd\n  stop_stats $log_file_name.stats\n}\n\nfunction now() {\n  echo `date +\"%s\"`\n}\n\n\necho \"===== Benchmark =====\"\n\n# Run!!!\nIFS=',' read -a jobs <<< $bench_cmd\n# shellcheck disable=SC2068\nfor job in ${jobs[@]}; do\n\n  if [ $job != debug ]; then\n    echo \"Starting $job (ID: $job_id) at `date`\" | tee -a $schedule\n  fi\n\n  start=$(now)\n  if [ $job = bulkload ]; then\n    run_bulkload\n  elif [ $job = flush_mt_l0 ]; then\n    run_lsm flush_mt_l0\n  elif [ $job = waitforcompaction ]; then\n    run_lsm waitforcompaction\n  elif [ $job = fillseq_disable_wal ]; then\n    run_fillseq 1\n  elif [ $job = fillseq_enable_wal ]; then\n    run_fillseq 0\n  elif [ $job = overwrite ]; then\n    run_change overwrite overwrite overwrite\n  elif [ $job = overwritesome ]; then\n    # This uses a different name for overwrite results so it can be run twice in one benchmark run.\n    run_change overwritesome overwrite overwrite\n  elif [ $job = overwriteandwait ]; then\n    run_change overwriteandwait overwrite overwrite,waitforcompaction\n  elif [ $job = updaterandom ]; then\n    run_change updaterandom updaterandom updaterandom\n  elif [ $job = mergerandom ]; then\n    run_change mergerandom mergerandom mergerandom\n  elif [ $job = filluniquerandom ]; then\n    run_filluniquerandom\n  elif [ $job = readrandom ]; then\n    run_readrandom\n  elif [ $job = multireadrandom ]; then\n    run_multireadrandom\n  elif [ $job = fwdrange ]; then\n    run_range $job false\n  elif [ $job = revrange ]; then\n    run_range $job true\n  elif [ $job = readwhilewriting ]; then\n    run_readwhile writing\n  elif [ $job = readwhilemerging ]; then\n    run_readwhile merging\n  elif [ $job = fwdrangewhilewriting ]; then\n    run_rangewhile writing $job false\n  elif [ $job = revrangewhilewriting ]; then\n    run_rangewhile writing $job true\n  elif [ $job = fwdrangewhilemerging ]; then\n    run_rangewhile merging $job false\n  elif [ $job = revrangewhilemerging ]; then\n    run_rangewhile merging $job true\n  elif [ $job = randomtransaction ]; then\n    run_randomtransaction\n  elif [ $job = universal_compaction ]; then\n    run_univ_compaction\n  elif [ $job = debug ]; then\n    num_keys=1000; # debug\n    echo \"Setting num_keys to $num_keys\"\n  else\n    echo \"unknown job $job\"\n    exit $EXIT_UNKNOWN_JOB\n  fi\n  end=$(now)\n\n  if [ $job != debug ]; then\n    echo \"Completed $job (ID: $job_id) in $((end-start)) seconds\" | tee -a $schedule\n  fi\n\n  echo -e $tsv_header\n  tail -1 $report\n\ndone\n", "num_lines": 1174}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# REQUIRE: db_bench binary exists in the current directory\n\ndbdir=$1\nodir=$2\n\n# Size Constants\nK=1024\nM=$((1024 * K))\n\n# Dynamic loader configuration\nld_library_path=${LD_LIBRARY_PATH:-\"\"}\n\n# Benchmark configuration\nduration_rw=${DURATION_RW:-65}\nduration_ro=${DURATION_RO:-65}\nnum_keys=${NUM_KEYS:-1000000}\nnum_threads=${NUM_THREADS:-16}\nkey_size=${KEY_SIZE:-20}\nvalue_size=${VALUE_SIZE:-400}\nmb_write_per_sec=${MB_WRITE_PER_SEC:-2}\nci_tests_only=${CI_TESTS_ONLY:-\"false\"}\n\n# RocksDB configuration\ncompression_type=${COMPRESSION_TYPE:-lz4}\nsubcompactions=${SUBCOMPACTIONS:-1}\nwrite_buffer_size_mb=${WRITE_BUFFER_SIZE_MB:-32}\ntarget_file_size_base_mb=${TARGET_FILE_SIZE_BASE_MB:-32}\nmax_bytes_for_level_base_mb=${MAX_BYTES_FOR_LEVEL_BASE_MB:-128}\nmax_background_jobs=${MAX_BACKGROUND_JOBS:-8}\nstats_interval_seconds=${STATS_INTERVAL_SECONDS:-20}\ncache_index_and_filter_blocks=${CACHE_INDEX_AND_FILTER_BLOCKS:-0}\n# USE_O_DIRECT doesn't need a default\nbytes_per_sync=${BYTES_PER_SYNC:-$(( 1 * M ))}\n# CACHE_SIZE_MB doesn't need a default\nmin_level_to_compress=${MIN_LEVEL_TO_COMPRESS:-\"-1\"}\n\ncompaction_style=${COMPACTION_STYLE:-leveled}\nif [ \"$compaction_style\" = \"leveled\" ]; then\n  echo Use leveled compaction\nelif [ \"$compaction_style\" = \"universal\" ]; then\n  echo Use universal compaction\nelif [ \"$compaction_style\" = \"blob\" ]; then\n  echo Use blob compaction\nelse\n  echo COMPACTION_STYLE is :: \"$COMPACTION_STYLE\" :: and must be one of leveled, universal, blob\n  exit 1\nfi\n\n# Leveled compaction configuration\nlevel0_file_num_compaction_trigger=${LEVEL0_FILE_NUM_COMPACTION_TRIGGER:-4}\nlevel0_slowdown_writes_trigger=${LEVEL0_SLOWDOWN_WRITES_TRIGGER:-20}\nlevel0_stop_writes_trigger=${LEVEL0_STOP_WRITES_TRIGGER:-30}\nper_level_fanout=${PER_LEVEL_FANOUT:-8}\n\n# Universal compaction configuration\nuniversal_min_merge_width=${UNIVERSAL_MIN_MERGE_WIDTH:-2}\nuniversal_max_merge_width=${UNIVERSAL_MAX_MERGE_WIDTH:-20}\nuniversal_size_ratio=${UNIVERSAL_SIZE_RATIO:-1}\nuniversal_max_size_amp=${UNIVERSAL_MAX_SIZE_AMP:-200}\nuniversal_compression_size_percent=${UNIVERSAL_COMPRESSION_SIZE_PERCENT:-\"-1\"}\n\n# Integrated BlobDB configuration\n\nmin_blob_size=${MIN_BLOB_SIZE:-0}\nblob_file_size=${BLOB_FILE_SIZE:-$(( 256 * M ))}\nblob_compression_type=${BLOB_COMPRESSION_TYPE:-${compression_type}}\nblob_gc_age_cutoff=${BLOB_GC_AGE_CUTOFF:-\"0.25\"}\nblob_gc_force_threshold=${BLOB_GC_FORCE_THRESHOLD:-1}\n\n# Arguments for dynamic loading\nbase_args=( LD_LIBRARY_PATH=\"$ld_library_path\" )\n\n# Arguments used for all tests\nbase_args+=( NUM_KEYS=\"$num_keys\" )\nbase_args+=( NUM_THREADS=\"$num_threads\" )\nbase_args+=( KEY_SIZE=\"$key_size\" )\nbase_args+=( VALUE_SIZE=\"$value_size\" )\n\nbase_args+=( SUBCOMPACTIONS=\"$subcompactions\" )\nbase_args+=( COMPRESSION_TYPE=\"$compression_type\" )\nbase_args+=( WRITE_BUFFER_SIZE_MB=\"$write_buffer_size_mb\" )\nbase_args+=( TARGET_FILE_SIZE_BASE_MB=\"$target_file_size_base_mb\" )\nbase_args+=( MAX_BYTES_FOR_LEVEL_BASE_MB=\"$max_bytes_for_level_base_mb\" )\nbase_args+=( MAX_BACKGROUND_JOBS=\"$max_background_jobs\" )\nbase_args+=( STATS_INTERVAL_SECONDS=\"$stats_interval_seconds\" )\nbase_args+=( CACHE_INDEX_AND_FILTER_BLOCKS=\"$cache_index_and_filter_blocks\" )\nbase_args+=( COMPACTION_STYLE=\"$compaction_style\" )\nbase_args+=( BYTES_PER_SYNC=\"$bytes_per_sync\" )\n\nif [ -n \"$USE_O_DIRECT\" ]; then\n  base_args+=( USE_O_DIRECT=1 )\nfi\n\nif [ -n \"$NUMA\" ]; then\n  base_args+=( NUMACTL=1 )\nfi\n\nif [ -n \"$CACHE_SIZE_MB\" ]; then\n  cacheb=$(( CACHE_SIZE_MB * M ))\n  base_args+=( CACHE_SIZE=\"$cacheb\" )\nfi\n\nif [ \"$compaction_style\" == \"leveled\" ]; then\n  base_args+=( LEVEL0_FILE_NUM_COMPACTION_TRIGGER=\"$level0_file_num_compaction_trigger\" )\n  base_args+=( LEVEL0_SLOWDOWN_WRITES_TRIGGER=\"$level0_slowdown_writes_trigger\" )\n  base_args+=( LEVEL0_STOP_WRITES_TRIGGER=\"$level0_stop_writes_trigger\" )\n  base_args+=( PER_LEVEL_FANOUT=\"$per_level_fanout\" )\nelif [ \"$compaction_style\" == \"universal\" ]; then\n  base_args+=( LEVEL0_FILE_NUM_COMPACTION_TRIGGER=\"$level0_file_num_compaction_trigger\" )\n  base_args+=( LEVEL0_SLOWDOWN_WRITES_TRIGGER=\"$level0_slowdown_writes_trigger\" )\n  base_args+=( LEVEL0_STOP_WRITES_TRIGGER=\"$level0_stop_writes_trigger\" )\n  base_args+=( UNIVERSAL_MIN_MERGE_WIDTH=\"$universal_min_merge_width\" )\n  base_args+=( UNIVERSAL_MAX_MERGE_WIDTH=\"$universal_max_merge_width\" )\n  base_args+=( UNIVERSAL_SIZE_RATIO=\"$universal_size_ratio\" )\n  base_args+=( UNIVERSAL_MAX_SIZE_AMP=\"$universal_max_size_amp\" )\n  if [ -n \"$UNIVERSAL_ALLOW_TRIVIAL_MOVE\" ]; then\n    base_args+=( UNIVERSAL_ALLOW_TRIVIAL_MOVE=1 )\n  fi\nelse\n  # Inherit settings for leveled because index uses leveled LSM\n  base_args+=( LEVEL0_FILE_NUM_COMPACTION_TRIGGER=\"$level0_file_num_compaction_trigger\" )\n  base_args+=( LEVEL0_SLOWDOWN_WRITES_TRIGGER=\"$level0_slowdown_writes_trigger\" )\n  base_args+=( LEVEL0_STOP_WRITES_TRIGGER=\"$level0_stop_writes_trigger\" )\n  base_args+=( PER_LEVEL_FANOUT=\"$per_level_fanout\" )\n  # Then add BlobDB specific settings\n  base_args+=( MIN_BLOB_SIZE=\"$min_blob_size\" )\n  base_args+=( BLOB_FILE_SIZE=\"$blob_file_size\" )\n  base_args+=( BLOB_COMPRESSION_TYPE=\"$blob_compression_type\" )\n  base_args+=( BLOB_GC_AGE_CUTOFF=\"$blob_gc_age_cutoff\" )\n  base_args+=( BLOB_GC_FORCE_THRESHOLD=\"$blob_gc_force_threshold\" )\nfi\n\nfunction usage {\n  echo \"usage: benchmark_compare.sh db_dir output_dir version+\"\n  echo -e \"\\tdb_dir\\t\\tcreate RocksDB database in this directory\"\n  echo -e \"\\toutput_dir\\twrite output from performance tests in this directory\"\n  echo -e \"\\tversion+\\tspace separated sequence of RocksDB versions to test.\"\n  echo -e \"\\nThis expects that db_bench.\\$version exists in \\$PWD for each version in the sequence.\"\n  echo -e \"An example value for version+ is 6.23.0 6.24.0\"\n  echo \"\"\n  echo -e \"Environment variables for options\"\n  echo -e \"\\tNUM_KEYS\\t\\t\\tnumber of keys to load\"\n  echo -e \"\\tKEY_SIZE\\t\\t\\tsize of key\"\n  echo -e \"\\tVALUE_SIZE\\t\\t\\tsize of value\"\n  echo -e \"\\tCACHE_SIZE_MB\\t\\t\\tsize of block cache in MB\"\n  echo -e \"\\tDURATION_RW\\t\\t\\tnumber of seconds for which each test runs, except for read-only tests\"\n  echo -e \"\\tDURATION_RO\\t\\t\\tnumber of seconds for which each read-only test runs\"\n  echo -e \"\\tMB_WRITE_PER_SEC\\t\\trate limit for writer that runs concurrent with queries for some tests\"\n  echo -e \"\\tNUM_THREADS\\t\\t\\tnumber of user threads\"\n  echo -e \"\\tCOMPRESSION_TYPE\\t\\tcompression type (zstd, lz4, none, etc)\"\n  echo -e \"\\tMIN_LEVEL_TO_COMPRESS\\t\\tmin_level_to_compress for leveled\"\n  echo -e \"\\tWRITE_BUFFER_SIZE_MB\\t\\tsize of write buffer in MB\"\n  echo -e \"\\tTARGET_FILE_SIZE_BASE_MB\\tvalue for target_file_size_base in MB\"\n  echo -e \"\\tMAX_BYTES_FOR_LEVEL_BASE_MB\\tvalue for max_bytes_for_level_base in MB\"\n  echo -e \"\\tMAX_BACKGROUND_JOBS\\t\\tvalue for max_background_jobs\"\n  echo -e \"\\tCACHE_INDEX_AND_FILTER_BLOCKS\\tvalue for cache_index_and_filter_blocks\"\n  echo -e \"\\tUSE_O_DIRECT\\t\\t\\tUse O_DIRECT for user reads and compaction\"\n  echo -e \"\\tBYTES_PER_SYNC\\t\\t\\tValue for bytes_per_sync\"\n  echo -e \"\\tSTATS_INTERVAL_SECONDS\\t\\tvalue for stats_interval_seconds\"\n  echo -e \"\\tSUBCOMPACTIONS\\t\\t\\tvalue for subcompactions\"\n  echo -e \"\\tCOMPACTION_STYLE\\t\\tCompaction style to use, one of: leveled, universal, blob\"\n  echo -e \"\\tCI_TESTS_ONLY\\t\\tRun a subset of tests tailored to a CI regression job, one of: true, false (default)\"\n  echo \"\"\n  echo -e \"\\tOptions specific to leveled compaction:\"\n  echo -e \"\\t\\tLEVEL0_FILE_NUM_COMPACTION_TRIGGER\\tvalue for level0_file_num_compaction_trigger\"\n  echo -e \"\\t\\tLEVEL0_SLOWDOWN_WRITES_TRIGGER\\t\\tvalue for level0_slowdown_writes_trigger\"\n  echo -e \"\\t\\tLEVEL0_STOP_WRITES_TRIGGER\\t\\tvalue for level0_stop_writes_trigger\"\n  echo -e \"\\t\\tPER_LEVEL_FANOUT\\t\\t\\tvalue for max_bytes_for_level_multiplier\"\n  echo \"\"\n  echo -e \"\\tOptions specific to universal compaction:\"\n  echo -e \"\\t\\tSee LEVEL0_*_TRIGGER above\"\n  echo -e \"\\t\\tUNIVERSAL_MIN_MERGE_WIDTH\\t\\tvalue of min_merge_width option for universal\"\n  echo -e \"\\t\\tUNIVERSAL_MAX_MERGE_WIDTH\\t\\tvalue of min_merge_width option for universal\"\n  echo -e \"\\t\\tUNIVERSAL_SIZE_RATIO\\t\\t\\tvalue of size_ratio option for universal\"\n  echo -e \"\\t\\tUNIVERSAL_MAX_SIZE_AMP\\t\\t\\tmax_size_amplification_percent for universal\"\n  echo -e \"\\t\\tUNIVERSAL_ALLOW_TRIVIAL_MOVE\\t\\tSet allow_trivial_move to true for universal, default is false\"\n  echo -e \"\\t\\tUNIVERSAL_COMPRESSION_SIZE_PERCENT\\tpercentage of LSM tree that should be compressed\"\n  echo \"\"\n  echo -e \"\\tOptions for integrated BlobDB:\"\n  echo -e \"\\t\\tMIN_BLOB_SIZE\\t\\t\\t\\tvalue for min_blob_size\"\n  echo -e \"\\t\\tBLOB_FILE_SIZE\\t\\t\\t\\tvalue for blob_file_size\"\n  echo -e \"\\t\\tBLOB_COMPRESSION_TYPE\\t\\t\\tvalue for blob_compression_type\"\n  echo -e \"\\t\\tBLOB_GC_AGE_CUTOFF\\t\\t\\tvalue for blog_garbage_collection_age_cutoff\"\n  echo -e \"\\t\\tBLOB_GC_FORCE_THRESHOLD\\t\\t\\tvalue for blog_garbage_collection_force_threshold\"\n}\n\nfunction dump_env {\n  echo \"Base args\" > \"$odir\"/args\n  echo \"${base_args[@]}\" | tr ' ' '\\n' >> \"$odir\"/args\n\n  echo -e \"\\nOther args\" >> \"$odir\"/args\n  echo -e \"dbdir\\t$dbdir\" >> \"$odir\"/args\n  echo -e \"duration_rw\\t$duration_rw\" >> \"$odir\"/args\n  echo -e \"duration_ro\\t$duration_ro\" >> \"$odir\"/args\n  echo -e \"per_level_fanout\\t$per_level_fanout\" >> \"$odir\"/args\n\n  echo -e \"\\nargs_load:\" >> \"$odir\"/args\n  echo \"${args_load[@]}\" | tr ' ' '\\n' >> \"$odir\"/args\n  echo -e \"\\nargs_nolim:\" >> \"$odir\"/args\n  echo \"${args_nolim[@]}\" | tr ' ' '\\n' >> \"$odir\"/args\n  echo -e \"\\nargs_lim:\" >> \"$odir\"/args\n  echo \"${args_lim[@]}\" | tr ' ' '\\n' >> \"$odir\"/args\n}\n\nif [ $# -lt 3 ]; then\n  usage\n  echo\n  echo \"Need at least 3 arguments\"\n  exit 1\nfi\n\nshift 2\n\nmkdir -p \"$odir\"\n\necho Test versions: \"$@\"\necho Test versions: \"$@\" >> \"$odir\"/args\n\nfor v in \"$@\" ; do\n  my_odir=\"$odir\"/\"$v\"\n\n  if [ -d \"$my_odir\" ]; then\n    echo Exiting because the output directory exists: \"$my_odir\"\n    exit 1\n  fi\n\n  args_common=(\"${base_args[@]}\")\n\n  args_common+=( OUTPUT_DIR=\"$my_odir\" DB_DIR=\"$dbdir\" WAL_DIR=\"$dbdir\" DB_BENCH_NO_SYNC=1 )\n\n  if [ \"$compaction_style\" == \"leveled\" ]; then\n    args_common+=( MIN_LEVEL_TO_COMPRESS=\"$min_level_to_compress\" )\n  elif [ \"$compaction_style\" == \"universal\" ]; then\n    args_common+=( UNIVERSAL=1 COMPRESSION_SIZE_PERCENT=\"$universal_compression_size_percent\" )\n  else\n    args_common+=( MIN_LEVEL_TO_COMPRESS=\"$min_level_to_compress\" )\n  fi\n\n  args_load=(\"${args_common[@]}\")\n\n  args_nolim=(\"${args_common[@]}\")\n\n  args_lim=(\"${args_nolim[@]}\")\n  args_lim+=( MB_WRITE_PER_SEC=\"$mb_write_per_sec\" )\n\n  dump_env\n\n  echo Run benchmark for \"$v\" at \"$( date )\" with results at \"$my_odir\"\n  rm -f db_bench\n  echo ln -s db_bench.\"$v\" db_bench\n  ln -s db_bench.\"$v\" db_bench\n\n  find \"$dbdir\" -type f -exec rm \\{\\} \\;\n\n  # Load in key order\n  echo env \"${args_load[@]}\" bash ./benchmark.sh fillseq_disable_wal\n  env -i \"${args_load[@]}\" bash ./benchmark.sh fillseq_disable_wal\n\n  # Read-only tests. The LSM tree shape is in a deterministic state if trivial move\n  # was used during the load.\n\n  # Add revrange with a fixed duration and hardwired number of keys and threads to give\n  # compaction debt leftover from fillseq a chance at being removed. Not using waitforcompaction\n  # here because it isn't supported on older db_bench versions.\n  env -i \"${args_nolim[@]}\" DURATION=300 NUM_KEYS=100 NUM_THREADS=1 bash ./benchmark.sh revrange\n  env -i \"${args_nolim[@]}\" DURATION=\"$duration_ro\" bash ./benchmark.sh readrandom\n\n  # Skipped for CI - a single essentail readrandom is enough to set up for other tests\n  if [ \"$ci_tests_only\" != \"true\" ]; then\n    env -i \"${args_nolim[@]}\" DURATION=\"$duration_ro\" bash ./benchmark.sh fwdrange\n    env -i \"${args_lim[@]}\"   DURATION=\"$duration_ro\" bash ./benchmark.sh multireadrandom --multiread_batched\n  else\n    echo \"CI_TESTS_ONLY is set, skipping optional read steps.\"\n  fi\n\n  # Write 10% of the keys. The goal is to randomize keys prior to Lmax\n  p10=$( echo \"$num_keys\" \"$num_threads\" | awk '{ printf \"%.0f\", $1 / $2 / 10.0 }' )\n  env -i \"${args_nolim[@]}\" WRITES=\"$p10\"        bash ./benchmark.sh overwritesome\n\n  if [ \"$compaction_style\" == \"leveled\" ]; then\n    # These are not supported by older versions\n    # Flush memtable & L0 to get LSM tree into deterministic state\n    env -i \"${args_nolim[@]}\"                  bash ./benchmark.sh flush_mt_l0\n  elif [ \"$compaction_style\" == \"universal\" ]; then\n    # For universal don't compact L0 as can have too many sorted runs\n    # waitforcompaction can hang, see https://github.com/facebook/rocksdb/issues/9275\n    # While this is disabled the test that follows will have more variance from compaction debt.\n    # env -i \"${args_nolim[@]}\"                    bash ./benchmark.sh waitforcompaction\n    echo TODO enable when waitforcompaction hang is fixed\n  else\n    # These are not supported by older versions\n    # Flush memtable & L0 to get LSM tree into deterministic state\n    env -i \"${args_nolim[@]}\"                  bash ./benchmark.sh flush_mt_l0\n  fi\n\n  # Read-mostly tests with a rate-limited writer\n  env -i \"${args_lim[@]}\" DURATION=\"$duration_rw\" bash ./benchmark.sh revrangewhilewriting\n  env -i \"${args_lim[@]}\" DURATION=\"$duration_rw\" bash ./benchmark.sh fwdrangewhilewriting\n  env -i \"${args_lim[@]}\" DURATION=\"$duration_rw\" bash ./benchmark.sh readwhilewriting\n\n  # Write-only tests\n\n  # This creates much compaction debt which will be a problem for tests added after it.\n  # Also, the compaction stats measured at test end can underestimate write-amp depending\n  # on how much compaction debt is allowed.\n  if [ \"$compaction_style\" == \"leveled\" ] && ./db_bench --benchmarks=waitforcompaction ; then\n    # Use waitforcompaction to get more accurate write-amp measurement\n    env -i \"${args_nolim[@]}\" DURATION=\"$duration_rw\" bash ./benchmark.sh overwriteandwait\n  else\n    # waitforcompaction hangs with universal, see https://github.com/facebook/rocksdb/issues/9275\n    env -i \"${args_nolim[@]}\" DURATION=\"$duration_rw\" bash ./benchmark.sh overwrite\n  fi\n\n  cp \"$dbdir\"/LOG* \"$my_odir\"\n  gzip -9 \"$my_odir\"/LOG*\n\ndone\n\n# Generate a file that groups lines from the same test for all versions\nbasev=$1\nnlines=$( awk '/^ops_sec/,/END/' \"$odir\"/\"$basev\"/report.tsv | grep -v ops_sec | wc -l )\nhline=$( awk '/^ops_sec/ { print NR }' \"$odir\"/\"$basev\"/report.tsv )\nsline=$(( hline + 1 ))\neline=$(( sline + nlines - 1 ))\n\nsum_file=\"$odir\"/summary.tsv\n\nfor v in \"$@\" ; do\n  echo \"$odir\"/\"$v\"/report.tsv\ndone >> \"$sum_file\"\necho >> \"$sum_file\"\n\nfor x in $( seq \"$sline\" \"$eline\" ); do\n  awk '{ if (NR == lno) { print $0 } }' lno=\"$hline\" \"$odir\"/\"$basev\"/report.tsv >> \"$sum_file\"\n  for v in \"$@\" ; do\n    r=\"$odir\"/\"$v\"/report.tsv\n    awk '{ if (NR == lno) { print $0 } }' lno=\"$x\" \"$r\" >> \"$sum_file\"\n  done\necho >> \"$sum_file\"\ndone\n", "num_lines": 343}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# REQUIRE: db_bench binary exists in the current directory\n#\n# This should be used with the LevelDB fork listed here to use additional test options.\n# For more details on the changes see the blog post listed below.\n#   https://github.com/mdcallag/leveldb-1\n#   http://smalldatum.blogspot.com/2015/04/comparing-leveldb-and-rocksdb-take-2.html\n\nif [ $# -ne 1 ]; then\n  echo -n \"./benchmark.sh [fillseq/overwrite/readrandom/readwhilewriting]\"\n  exit 0\nfi\n\n# size constants\nK=1024\nM=$((1024 * K))\nG=$((1024 * M))\n\nif [ -z $DB_DIR ]; then\n  echo \"DB_DIR is not defined\"\n  exit 0\nfi\n\noutput_dir=${OUTPUT_DIR:-/tmp/}\nif [ ! -d $output_dir ]; then\n  mkdir -p $output_dir\nfi\n\n# all multithreaded tests run with sync=1 unless\n# $DB_BENCH_NO_SYNC is defined\nsyncval=\"1\"\nif [ ! -z $DB_BENCH_NO_SYNC ]; then\n  echo \"Turning sync off for all multithreaded tests\"\n  syncval=\"0\";\nfi\n\nnum_threads=${NUM_THREADS:-16}\n# Only for *whilewriting, *whilemerging\nwrites_per_second=${WRITES_PER_SECOND:-$((10 * K))}\ncache_size=${CACHE_SIZE:-$((1 * G))}\n\nnum_keys=${NUM_KEYS:-$((1 * G))}\nkey_size=20\nvalue_size=${VALUE_SIZE:-400}\nblock_size=${BLOCK_SIZE:-4096}\n\nconst_params=\"\n  --db=$DB_DIR \\\n  \\\n  --num=$num_keys \\\n  --value_size=$value_size \\\n  --cache_size=$cache_size \\\n  --compression_ratio=0.5 \\\n  \\\n  --write_buffer_size=$((2 * M)) \\\n  \\\n  --histogram=1 \\\n  \\\n  --bloom_bits=10 \\\n  --open_files=$((20 * K))\"\n\nparams_w=\"$const_params \"\n\nfunction summarize_result {\n  test_out=$1\n  test_name=$2\n  bench_name=$3\n  nthr=$4\n\n  usecs_op=$( grep ^${bench_name} $test_out | awk '{ printf \"%.1f\", $3 }' )\n  mb_sec=$( grep ^${bench_name} $test_out | awk '{ printf \"%.1f\", $5 }' )\n  ops=$( grep \"^Count:\" $test_out | awk '{ print $2 }' )\n  ops_sec=$( echo \"scale=0; (1000000.0 * $nthr) / $usecs_op\" | bc )\n  avg=$( grep \"^Count:\" $test_out | awk '{ printf \"%.1f\", $4 }' )\n  p50=$( grep \"^Min:\" $test_out | awk '{ printf \"%.1f\", $4 }' )\n  echo -e \"$ops_sec\\t$mb_sec\\t$usecs_op\\t$avg\\t$p50\\t$test_name\" \\\n    >> $output_dir/report.txt\n}\n\nfunction run_fillseq {\n  # This runs with a vector memtable and the WAL disabled to load faster. It is still crash safe and the\n  # client can discover where to restart a load after a crash. I think this is a good way to load.\n  echo \"Loading $num_keys keys sequentially\"\n  cmd=\"./db_bench --benchmarks=fillseq \\\n       --use_existing_db=0 \\\n       --sync=0 \\\n       $params_w \\\n       --threads=1 \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $output_dir/benchmark_fillseq.v${value_size}.log\"\n  echo $cmd | tee $output_dir/benchmark_fillseq.v${value_size}.log\n  eval $cmd\n  summarize_result $output_dir/benchmark_fillseq.v${value_size}.log fillseq.v${value_size} fillseq 1\n}\n\nfunction run_change {\n  operation=$1\n  echo \"Do $num_keys random $operation\"\n  out_name=\"benchmark_${operation}.t${num_threads}.s${syncval}.log\"\n  cmd=\"./db_bench --benchmarks=$operation \\\n       --use_existing_db=1 \\\n       --sync=$syncval \\\n       $params_w \\\n       --threads=$num_threads \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $output_dir/${out_name}\"\n  echo $cmd | tee $output_dir/${out_name}\n  eval $cmd\n  summarize_result $output_dir/${out_name} ${operation}.t${num_threads}.s${syncval} $operation $num_threads\n}\n\nfunction run_readrandom {\n  echo \"Reading $num_keys random keys\"\n  out_name=\"benchmark_readrandom.t${num_threads}.log\"\n  cmd=\"./db_bench --benchmarks=readrandom \\\n       --use_existing_db=1 \\\n       $params_w \\\n       --threads=$num_threads \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $output_dir/${out_name}\"\n  echo $cmd | tee $output_dir/${out_name}\n  eval $cmd\n  summarize_result $output_dir/${out_name} readrandom.t${num_threads} readrandom $num_threads\n}\n\nfunction run_readwhile {\n  operation=$1\n  echo \"Reading $num_keys random keys while $operation\"\n  out_name=\"benchmark_readwhile${operation}.t${num_threads}.log\"\n  cmd=\"./db_bench --benchmarks=readwhile${operation} \\\n       --use_existing_db=1 \\\n       --sync=$syncval \\\n       $params_w \\\n       --threads=$num_threads \\\n       --writes_per_second=$writes_per_second \\\n       --seed=$( date +%s ) \\\n       2>&1 | tee -a $output_dir/${out_name}\"\n  echo $cmd | tee $output_dir/${out_name}\n  eval $cmd\n  summarize_result $output_dir/${out_name} readwhile${operation}.t${num_threads} readwhile${operation} $num_threads\n}\n\nfunction now() {\n  echo `date +\"%s\"`\n}\n\nreport=\"$output_dir/report.txt\"\nschedule=\"$output_dir/schedule.txt\"\n\necho \"===== Benchmark =====\"\n\n# Run!!!\nIFS=',' read -a jobs <<< $1\n# shellcheck disable=SC2068\nfor job in ${jobs[@]}; do\n\n  if [ $job != debug ]; then\n    echo \"Start $job at `date`\" | tee -a $schedule\n  fi\n\n  start=$(now)\n  if [ $job = fillseq ]; then\n    run_fillseq\n  elif [ $job = overwrite ]; then\n    run_change overwrite\n  elif [ $job = readrandom ]; then\n    run_readrandom\n  elif [ $job = readwhilewriting ]; then\n    run_readwhile writing\n  elif [ $job = debug ]; then\n    num_keys=1000; # debug\n    echo \"Setting num_keys to $num_keys\"\n  else\n    echo \"unknown job $job\"\n    exit\n  fi\n  end=$(now)\n\n  if [ $job != debug ]; then\n    echo \"Complete $job in $((end-start)) seconds\" | tee -a $schedule\n  fi\n\n  echo -e \"ops/sec\\tmb/sec\\tusec/op\\tavg\\tp50\\tTest\"\n  tail -1 $output_dir/report.txt\n\ndone\n", "num_lines": 188}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# A shell script to build and run different versions of ldb to check for\n# expected forward and backward compatibility with \"current\" version. The\n# working copy must have no uncommitted changes.\n#\n# Usage: <SCRIPT> [ref_for_current]\n# `ref_for_current` can be a revision, tag, commit or branch name. Default is HEAD.\n#\n# Return value 0 means all regression tests pass. 1 if not pass.\n#\n# Environment options:\n#  SHORT_TEST=1 - Test only the oldest branch for each kind of test. This is\n#    a good choice for PR validation as it is relatively fast and will find\n#    most issues.\n#  USE_SSH=1 - Connect to GitHub with ssh instead of https\n\nif ! git diff-index --quiet HEAD; then\n  echo \"You have uncommitted changes. Aborting.\"\n  exit 1\nfi\n\ncurrent_checkout_name=${1:-HEAD}\n# This allows the script to work even if with transient refs like \"HEAD\"\ncurrent_checkout_hash=\"$(git rev-parse --quiet --verify $current_checkout_name)\"\n\nif [ \"$current_checkout_hash\" == \"\" ]; then\n  echo \"Not a recognized ref: $current_checkout_name\"\n  exit 1\nfi\n\n# To restore to prior branch at the end\norig_branch=\"$(git rev-parse --abbrev-ref HEAD)\"\ntmp_branch=_tmp_format_compatible\ntmp_origin=_tmp_origin\n\n# Don't depend on what current \"origin\" might be\nset -e\ngit remote remove $tmp_origin 2>/dev/null || true\nif [ \"$USE_SSH\" ]; then\n  git remote add $tmp_origin \"git@github.com:facebook/rocksdb.git\"\nelse\n  git remote add $tmp_origin \"https://github.com/facebook/rocksdb.git\"\nfi\ngit fetch $tmp_origin\n\n# Used in building some ancient RocksDB versions where by default it tries to\n# use a precompiled libsnappy.a checked in to the repo.\nexport SNAPPY_LDFLAGS=-lsnappy\n\ncleanup() {\n  echo \"== Cleaning up\"\n  git reset --hard || true\n  git checkout \"$orig_branch\" || true\n  git branch -D $tmp_branch || true\n  git remote remove $tmp_origin || true\n}\ntrap cleanup EXIT # Always clean up, even on failure or Ctrl+C\n\nscriptpath=`dirname ${BASH_SOURCE[0]}`\n\ntest_dir=${TEST_TMPDIR:-\"/tmp\"}\"/rocksdb_format_compatible_$USER\"\nrm -rf ${test_dir:?}\n\n# Prevent 'make clean' etc. from wiping out test_dir\nexport TEST_TMPDIR=$test_dir\"/misc\"\n\n# For saving current version of scripts as we checkout different versions to test\nscript_copy_dir=$test_dir\"/script_copy\"\nmkdir -p $script_copy_dir\ncp -f $scriptpath/*.sh $script_copy_dir\n\n# For shared raw input data\ninput_data_path=$test_dir\"/test_data_input\"\nmkdir -p $input_data_path\n# For external sst ingestion test\next_test_dir=$test_dir\"/ext\"\nmkdir -p $ext_test_dir\n# For DB dump test\ndb_test_dir=$test_dir\"/db\"\nmkdir -p $db_test_dir\n# For backup/restore test (uses DB test)\nbak_test_dir=$test_dir\"/bak\"\nmkdir -p $bak_test_dir\n\npython_bin=$(which python3 || which python || echo python3)\n\n# Generate random files.\nfor i in {1..6}\ndo\n  input_data[$i]=$input_data_path/data$i\n  echo == Generating random input file ${input_data[$i]}\n  $python_bin - <<EOF\nimport random\nrandom.seed($i)\nsymbols=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nwith open('${input_data[$i]}', 'w') as f:\n  for i in range(1,1024):\n    k = \"\"\n    for j in range(1, random.randint(1,32)):\n      k=k + symbols[random.randint(0, len(symbols) - 1)]\n    vb = \"\"\n    for j in range(1, random.randint(0,128)):\n      vb = vb + symbols[random.randint(0, len(symbols) - 1)]\n    v = \"\"\n    for j in range(1, random.randint(1, 5)):\n      v = v + vb\n    print(k + \" ==> \" + v, file=f)\nEOF\ndone\n\n# Generate file(s) with sorted keys.\nsorted_input_data=$input_data_path/sorted_data\necho == Generating file with sorted keys ${sorted_input_data}\n$python_bin - <<EOF\nwith open('${sorted_input_data}', 'w') as f:\n  for i in range(0,10):\n    k = str(i)\n    v = \"value\" + k\n    print(k + \" ==> \" + v, file=f)\nEOF\n\n# db_backward_only_refs defined below the rest\n\n# To check for DB forward compatibility with loading options (old version\n# reading data from new), as well as backward compatibility\ndeclare -a db_forward_with_options_refs=(\"6.27.fb\" \"6.28.fb\" \"6.29.fb\" \"7.0.fb\" \"7.1.fb\" \"7.2.fb\" \"7.3.fb\" \"7.4.fb\" \"7.5.fb\" \"7.6.fb\" \"7.7.fb\" \"7.8.fb\" \"7.9.fb\" \"7.10.fb\" \"8.0.fb\" \"8.1.fb\" \"8.2.fb\" \"8.3.fb\" \"8.4.fb\")\n# To check for DB forward compatibility without loading options (in addition\n# to the \"with loading options\" set), as well as backward compatibility\ndeclare -a db_forward_no_options_refs=() # N/A at the moment\n\n# To check for SST ingestion backward compatibility (new version reading\n# data from old) (ldb ingest_extern_sst added in 5.16.x, back-ported to\n# 5.14.x, 5.15.x)\ndeclare -a ext_backward_only_refs=(\"5.14.fb\" \"5.15.fb\" \"5.16.fb\" \"5.17.fb\" \"5.18.fb\" \"6.0.fb\" \"6.1.fb\" \"6.2.fb\" \"6.3.fb\" \"6.4.fb\" \"6.5.fb\" \"6.6.fb\" \"6.7.fb\" \"6.8.fb\" \"6.9.fb\" \"6.10.fb\" \"6.11.fb\" \"6.12.fb\" \"6.13.fb\" \"6.14.fb\" \"6.15.fb\" \"6.16.fb\" \"6.17.fb\" \"6.18.fb\" \"6.19.fb\" \"6.20.fb\" \"6.21.fb\" \"6.22.fb\" \"6.23.fb\" \"6.24.fb\" \"6.25.fb\" \"6.26.fb\")\n# To check for SST ingestion forward compatibility (old version reading\n# data from new) as well as backward compatibility\ndeclare -a ext_forward_refs=(\"${db_forward_no_options_refs[@]}\" \"${db_forward_with_options_refs[@]}\")\n\n# To check for backup backward compatibility (new version reading data\n# from old) (ldb backup/restore added in 4.11.x)\ndeclare -a bak_backward_only_refs=(\"4.11.fb\" \"4.12.fb\" \"4.13.fb\" \"5.0.fb\" \"5.1.fb\" \"5.2.fb\" \"5.3.fb\" \"5.4.fb\" \"5.5.fb\" \"5.6.fb\" \"5.7.fb\" \"5.8.fb\" \"5.9.fb\" \"5.10.fb\" \"5.11.fb\" \"5.12.fb\" \"5.13.fb\" \"${ext_backward_only_refs[@]}\")\n# To check for backup forward compatibility (old version reading data\n# from new) as well as backward compatibility\ndeclare -a bak_forward_refs=(\"${db_forward_no_options_refs[@]}\" \"${db_forward_with_options_refs[@]}\")\n\n# Branches (git refs) to check for DB backward compatibility (new version\n# reading data from old) (in addition to the \"forward compatible\" list)\n# NOTE: 2.7.fb.branch shows assertion violation in some configurations\ndeclare -a db_backward_only_refs=(\"2.2.fb.branch\" \"2.3.fb.branch\" \"2.4.fb.branch\" \"2.5.fb.branch\" \"2.6.fb.branch\" \"2.7.fb.branch\" \"2.8.1.fb\" \"3.0.fb.branch\" \"3.1.fb\" \"3.2.fb\" \"3.3.fb\" \"3.4.fb\" \"3.5.fb\" \"3.6.fb\" \"3.7.fb\" \"3.8.fb\" \"3.9.fb\" \"4.2.fb\" \"4.3.fb\" \"4.4.fb\" \"4.5.fb\" \"4.6.fb\" \"4.7.fb\" \"4.8.fb\" \"4.9.fb\" \"4.10.fb\" \"${bak_backward_only_refs[@]}\")\n\nif [ \"$SHORT_TEST\" ]; then\n  # Use only the first (if exists) of each list\n  db_backward_only_refs=(${db_backward_only_refs[0]})\n  db_forward_no_options_refs=(${db_forward_no_options_refs[0]})\n  db_forward_with_options_refs=(${db_forward_with_options_refs[0]})\n  ext_backward_only_refs=(${ext_backward_only_refs[0]})\n  ext_forward_refs=(${ext_forward_refs[0]})\n  bak_backward_only_refs=(${bak_backward_only_refs[0]})\n  bak_forward_refs=(${bak_forward_refs[0]})\nfi\n\n# De-duplicate & accumulate\ndeclare -a checkout_refs=()\nfor checkout_ref in \"${db_backward_only_refs[@]}\" \"${db_forward_no_options_refs[@]}\" \"${db_forward_with_options_refs[@]}\" \"${ext_backward_only_refs[@]}\" \"${ext_forward_refs[@]}\" \"${bak_backward_only_refs[@]}\" \"${bak_forward_refs[@]}\"\ndo\n  if [ ! -e $db_test_dir/$checkout_ref ]; then\n    mkdir -p $db_test_dir/$checkout_ref\n    checkout_refs+=($checkout_ref)\n  fi\ndone\n\ngenerate_db()\n{\n    set +e\n    bash \"$script_copy_dir\"/generate_random_db.sh \"$1\" \"$2\"\n    if [ $? -ne 0 ]; then\n        echo ==== Error loading data from $2 to $1 ====\n        exit 1\n    fi\n    set -e\n}\n\ncompare_db()\n{\n    set +e\n    bash \"$script_copy_dir\"/verify_random_db.sh \"$1\" \"$2\" \"$3\" \"$4\" \"$5\"\n    if [ $? -ne 0 ]; then\n        echo ==== Read different content from $1 and $2 or error happened. ====\n        exit 1\n    fi\n    set -e\n}\n\nwrite_external_sst()\n{\n    set +e\n    bash \"$script_copy_dir\"/write_external_sst.sh \"$1\" \"$2\" \"$3\"\n    if [ $? -ne 0 ]; then\n        echo ==== Error writing external SST file using data from $1 to $3 ====\n        exit 1\n    fi\n    set -e\n}\n\ningest_external_sst()\n{\n    set +e\n    bash \"$script_copy_dir\"/ingest_external_sst.sh \"$1\" \"$2\"\n    if [ $? -ne 0 ]; then\n        echo ==== Error ingesting external SST in $2 to DB at $1 ====\n        exit 1\n    fi\n    set -e\n}\n\nbackup_db()\n{\n    set +e\n    bash \"$script_copy_dir\"/backup_db.sh \"$1\" \"$2\"\n    if [ $? -ne 0 ]; then\n        echo ==== Error backing up DB $1 to $2 ====\n        exit 1\n    fi\n    set -e\n}\n\nrestore_db()\n{\n    set +e\n    bash \"$script_copy_dir\"/restore_db.sh \"$1\" \"$2\"\n    if [ $? -ne 0 ]; then\n        echo ==== Error restoring from $1 to $2 ====\n        exit 1\n    fi\n    set -e\n}\n\nmember_of_array()\n{\n  local e match=\"$1\"\n  shift\n  for e; do [[ \"$e\" == \"$match\" ]] && return 0; done\n  return 1\n}\n\nforce_no_fbcode()\n{\n  # Not all branches recognize ROCKSDB_NO_FBCODE and we should not need\n  # to patch old branches for changes to available FB compilers.\n  sed -i -e 's|-d /mnt/gvfs/third-party|\"$ROCKSDB_FORCE_FBCODE\"|' build_tools/build_detect_platform\n}\n\n# General structure from here:\n# * Check out, build, and do stuff with the \"current\" branch.\n# * For each older branch under consideration,\n#   * Check out, build, and do stuff with it, potentially using data\n#     generated from \"current\" branch.\n# * (Again) check out, build, and do (other) stuff with the \"current\"\n#    branch, potentially using data from older branches.\n#\n# This way, we only do at most n+1 checkout+build steps, without the\n# need to stash away executables.\n\n# Decorate name\ncurrent_checkout_name=\"$current_checkout_name ($current_checkout_hash)\"\n\necho \"== Building $current_checkout_name debug\"\ngit checkout -B $tmp_branch $current_checkout_hash\nforce_no_fbcode\nmake clean\nDISABLE_WARNING_AS_ERROR=1 make ldb -j32\n\necho \"== Using $current_checkout_name, generate DB with extern SST and ingest\"\ncurrent_ext_test_dir=$ext_test_dir\"/current\"\nwrite_external_sst $input_data_path ${current_ext_test_dir}_pointless $current_ext_test_dir\ningest_external_sst ${current_ext_test_dir}_ingest $current_ext_test_dir\n\necho \"== Generating DB from $current_checkout_name ...\"\ncurrent_db_test_dir=$db_test_dir\"/current\"\ngenerate_db $input_data_path $current_db_test_dir\n\necho \"== Creating backup of DB from $current_checkout_name ...\"\ncurrent_bak_test_dir=$bak_test_dir\"/current\"\nbackup_db $current_db_test_dir $current_bak_test_dir\n\nfor checkout_ref in \"${checkout_refs[@]}\"\ndo\n  echo \"== Building $checkout_ref debug\"\n  git reset --hard $tmp_origin/$checkout_ref\n  force_no_fbcode\n  make clean\n  DISABLE_WARNING_AS_ERROR=1 make ldb -j32\n\n  # We currently assume DB backward compatibility for every branch listed\n  echo \"== Use $checkout_ref to generate a DB ...\"\n  generate_db $input_data_path $db_test_dir/$checkout_ref\n\n  if member_of_array \"$checkout_ref\" \"${ext_backward_only_refs[@]}\" ||\n    member_of_array \"$checkout_ref\" \"${ext_forward_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to generate DB with extern SST file\"\n    write_external_sst $input_data_path $ext_test_dir/${checkout_ref}_pointless $ext_test_dir/$checkout_ref\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${ext_forward_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to ingest extern SST file and compare vs. $current_checkout_name\"\n    ingest_external_sst $ext_test_dir/${checkout_ref}_ingest $ext_test_dir/$checkout_ref\n    compare_db $ext_test_dir/${checkout_ref}_ingest ${current_ext_test_dir}_ingest db_dump.txt 1 1\n\n    rm -rf ${ext_test_dir:?}/${checkout_ref}_ingest\n    echo \"== Use $checkout_ref to ingest extern SST file from $current_checkout_name\"\n    ingest_external_sst $ext_test_dir/${checkout_ref}_ingest $current_ext_test_dir\n    compare_db $ext_test_dir/${checkout_ref}_ingest ${current_ext_test_dir}_ingest db_dump.txt 1 1\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${db_forward_no_options_refs[@]}\" ||\n    member_of_array \"$checkout_ref\" \"${db_forward_with_options_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to open DB generated using $current_checkout_name...\"\n    compare_db $db_test_dir/$checkout_ref $current_db_test_dir forward_${checkout_ref}_dump.txt 0\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${db_forward_with_options_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to open DB generated using $current_checkout_name with its options...\"\n    compare_db $db_test_dir/$checkout_ref $current_db_test_dir forward_${checkout_ref}_dump.txt 1 1\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${bak_backward_only_refs[@]}\" ||\n    member_of_array \"$checkout_ref\" \"${bak_forward_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to backup DB\"\n    backup_db $db_test_dir/$checkout_ref $bak_test_dir/$checkout_ref\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${bak_forward_refs[@]}\"\n  then\n    echo \"== Use $checkout_ref to restore DB from $current_checkout_name\"\n    rm -rf ${db_test_dir:?}/$checkout_ref\n    restore_db $current_bak_test_dir $db_test_dir/$checkout_ref\n    compare_db $db_test_dir/$checkout_ref $current_db_test_dir forward_${checkout_ref}_dump.txt 0\n  fi\ndone\n\necho \"== Building $current_checkout_name debug (again, final)\"\ngit reset --hard $current_checkout_hash\nforce_no_fbcode\nmake clean\nDISABLE_WARNING_AS_ERROR=1 make ldb -j32\n\nfor checkout_ref in \"${checkout_refs[@]}\"\ndo\n  # We currently assume DB backward compatibility for every branch listed\n  echo \"== Use $current_checkout_name to open DB generated using $checkout_ref...\"\n  compare_db $db_test_dir/$checkout_ref $current_db_test_dir db_dump.txt 1 0\n\n  if member_of_array \"$checkout_ref\" \"${ext_backward_only_refs[@]}\" ||\n    member_of_array \"$checkout_ref\" \"${ext_forward_refs[@]}\"\n  then\n    rm -rf ${ext_test_dir:?}/${checkout_ref}_ingest\n    echo \"== Use $current_checkout_name to ingest extern SST file from $checkout_ref\"\n    ingest_external_sst $ext_test_dir/${checkout_ref}_ingest $current_ext_test_dir\n    compare_db $ext_test_dir/${checkout_ref}_ingest ${current_ext_test_dir}_ingest db_dump.txt 1 1\n  fi\n\n  if member_of_array \"$checkout_ref\" \"${bak_backward_only_refs[@]}\" ||\n    member_of_array \"$checkout_ref\" \"${bak_forward_refs[@]}\"\n  then\n    echo \"== Use $current_checkout_name to restore DB from $checkout_ref\"\n    rm -rf ${db_test_dir:?}/$checkout_ref\n    restore_db $bak_test_dir/$checkout_ref $db_test_dir/$checkout_ref\n    compare_db $db_test_dir/$checkout_ref $current_db_test_dir db_dump.txt 1 0\n  fi\ndone\n\necho ==== Compatibility Test PASSED ====\n", "num_lines": 380}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# A shell script to load some pre generated data file to a DB using ldb tool\n# ./ldb needs to be avaible to be executed.\n#\n# Usage: <SCRIPT> <input_data_path> <DB Path>\n\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: $BASH_SOURCE <input_data_path> <DB Path>\"\n  exit 1\nfi\n\ninput_data_dir=$1\ndb_dir=$2\nrm -rf $db_dir\n\necho == Loading data from $input_data_dir to $db_dir\n\ndeclare -a compression_opts=(\"no\" \"snappy\" \"zlib\" \"bzip2\")\n\nset -e\n\nn=0\n\nfor f in `ls -1 $input_data_dir`\ndo\n  echo == Loading $f with compression ${compression_opts[n % 4]}\n  ./ldb load --db=$db_dir --compression_type=${compression_opts[n % 4]} --bloom_bits=10 --auto_compaction=false --create_if_missing < $input_data_dir/$f\n  let \"n = n + 1\"\ndone\n", "num_lines": 32}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n#\n\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: $BASH_SOURCE <DB Path> <External SST Dir>\"\n  exit 1\nfi\n\ndb_dir=$1\nexternal_sst_dir=$2\n\nfor f in `find $external_sst_dir -name extern_sst*`\ndo\n  echo == Ingesting external SST file $f to DB at $db_dir\n  ./ldb --db=$db_dir --create_if_missing ingest_extern_sst $f\ndone\n", "num_lines": 19}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# The RocksDB regression test script.\n# REQUIREMENT: must be able to run make db_bench in the current directory\n#\n# This script will do the following things in order:\n#\n# 1. check out the specified rocksdb commit.\n# 2. build db_bench using the specified commit\n# 3. setup test directory $TEST_PATH.  If not specified, then the test directory\n#    will be \"/tmp/rocksdb/regression_test\"\n# 4. run set of benchmarks on the specified host\n#    (can be either locally or remotely)\n# 5. generate report in the $RESULT_PATH.  If RESULT_PATH is not specified,\n#    RESULT_PATH will be set to $TEST_PATH/current_time\n#\n# = Examples =\n# * Run the regression test using rocksdb commit abcdef that outputs results\n#   and temp files in \"/my/output/dir\"\n#r\n#   TEST_PATH=/my/output/dir COMMIT_ID=abcdef ./tools/regression_test.sh\n#\n# * Run the regression test on a remost host under \"/my/output/dir\" directory\n#   and stores the result locally in \"/my/benchmark/results\" using commit\n#   abcdef and with the rocksdb options specified in /my/path/to/OPTIONS-012345\n#   with 1000000000 keys in each benchmark in the regression test where each\n#   key and value are 100 and 900 bytes respectively:\n#\n#   REMOTE_USER_AT_HOST=yhchiang@my.remote.host \\\n#       TEST_PATH=/my/output/dir \\\n#       RESULT_PATH=/my/benchmark/results \\\n#       COMMIT_ID=abcdef \\\n#       OPTIONS_FILE=/my/path/to/OPTIONS-012345 \\\n#       NUM_KEYS=1000000000 \\\n#       KEY_SIZE=100 \\\n#       VALUE_SIZE=900 \\\n#       ./tools/regression_test.sh\n#\n# = Regression test environmental parameters =\n#   DEBUG: If true, then the script will not build db_bench if db_bench already\n#       exists\n#       Default: 0\n#   TEST_MODE: If 1, run fillseqdeterminstic and benchmarks both\n#       if 0, only run fillseqdeterministc\n#       if 2, only run benchmarks\n#       Default: 1\n#   TEST_PATH: the root directory of the regression test.\n#       Default: \"/tmp/rocksdb/regression_test\"\n#       !!! NOTE !!! - a DB will also be saved in $TEST_PATH/../db\n#   RESULT_PATH: the directory where the regression results will be generated.\n#       Default: \"$TEST_PATH/current_time\"\n#   REMOTE_USER_AT_HOST: If set, then test will run on the specified host under\n#       TEST_PATH directory and outputs test results locally in RESULT_PATH\n#       The REMOTE_USER_AT_HOST should follow the format user-id@host.name\n#   DB_PATH: the path where the rocksdb database will be created during the\n#       regression test.  Default:  $TEST_PATH/db\n#   WAL_PATH: the path where the rocksdb WAL will be outputed.\n#       Default:  $TEST_PATH/wal\n#   OPTIONS_FILE:  If specified, then the regression test will use the specified\n#       file to initialize the RocksDB options in its benchmarks.  Note that\n#       this feature only work for commits after 88acd93 or rocksdb version\n#       later than 4.9.\n#   DELETE_TEST_PATH: If true, then the test directory will be deleted\n#       after the script ends.\n#       Default: 0\n#\n# = db_bench parameters =\n#   NUM_THREADS:  The number of concurrent foreground threads that will issue\n#       database operations in the benchmark.  Default: 16.\n#   NUM_KEYS:  The key range that will be used in the entire regression test.\n#       Default: 1G.\n#   NUM_OPS:  The number of operations (reads, writes, or deletes) that will\n#       be issued in EACH thread.\n#       Default: $NUM_KEYS / $NUM_THREADS\n#   KEY_SIZE:  The size of each key in bytes in db_bench.  Default: 100.\n#   VALUE_SIZE:  The size of each value in bytes in db_bench.  Default: 900.\n#   CACHE_SIZE:  The size of RocksDB block cache used in db_bench.  Default: 1G\n#   STATISTICS:  If 1, then statistics is on in db_bench.  Default: 0.\n#   COMPRESSION_RATIO:  The compression ratio of the key generated in db_bench.\n#       Default: 0.5.\n#   HISTOGRAM:  If 1, then the histogram feature on performance feature is on.\n#   STATS_PER_INTERVAL:  If 1, then the statistics will be reported for every\n#       STATS_INTERVAL_SECONDS seconds.  Default 1.\n#   STATS_INTERVAL_SECONDS:  If STATS_PER_INTERVAL is set to 1, then statistics\n#       will be reported for every STATS_INTERVAL_SECONDS.  Default 60.\n#   MAX_BACKGROUND_FLUSHES:  The maxinum number of concurrent flushes in\n#       db_bench.  Default: 4.\n#   MAX_BACKGROUND_COMPACTIONS:  The maximum number of concurrent compactions\n#       in db_bench.  Default: 16.\n#   NUM_HIGH_PRI_THREADS:  The number of high-pri threads available for\n#       concurrent flushes in db_bench.  Default: 4.\n#   NUM_LOW_PRI_THREADS:  The number of low-pri threads available for\n#       concurrent compactions in db_bench.  Default: 16.\n#   SEEK_NEXTS:  Controls how many Next() will be called after seek.\n#       Default: 10.\n#   SEED:  random seed that controls the randomness of the benchmark.\n#       Default: $( date +%s )\n\n#==============================================================================\n#  CONSTANT\n#==============================================================================\nTITLE_FORMAT=\"%40s,%25s,%30s,%7s,%9s,%8s,\"\nTITLE_FORMAT+=\"%10s,%13s,%14s,%11s,%12s,\"\nTITLE_FORMAT+=\"%7s,%11s,\"\nTITLE_FORMAT+=\"%9s,%10s,%10s,%10s,%10s,%10s,%5s,\"\nTITLE_FORMAT+=\"%5s,%5s,%5s\" # time\nTITLE_FORMAT+=\"\\n\"\n\nDATA_FORMAT=\"%40s,%25s,%30s,%7s,%9s,%8s,\"\nDATA_FORMAT+=\"%10s,%13.0f,%14s,%11s,%12s,\"\nDATA_FORMAT+=\"%7s,%11s,\"\nDATA_FORMAT+=\"%9.0f,%10.0f,%10.0f,%10.0f,%10.0f,%10.0f,%5.0f,\"\nDATA_FORMAT+=\"%5.0f,%5.0f,%5.0f\" # time\nDATA_FORMAT+=\"\\n\"\n\n# In case of async_io, $1 is benchmark_asyncio\nMAIN_PATTERN=\"${1%%_*}\"\"[[:blank:]]+:.*[[:blank:]]+([0-9\\.]+)[[:blank:]]+ops/sec\"\nPERC_PATTERN=\"Percentiles: P50: ([0-9\\.]+) P75: ([0-9\\.]+) \"\nPERC_PATTERN+=\"P99: ([0-9\\.]+) P99.9: ([0-9\\.]+) P99.99: ([0-9\\.]+)\"\n#==============================================================================\n\nfunction main {\n  TEST_ROOT_DIR=${TEST_PATH:-\"/tmp/rocksdb/regression_test\"}\n  init_arguments $TEST_ROOT_DIR\n\n  build_db_bench_and_ldb\n\n  setup_test_directory\n  if [ $TEST_MODE -le 1 ]; then\n      test_remote \"test -d $ORIGIN_PATH\"\n      if [[ $? -ne 0 ]]; then\n          echo \"Building DB...\"\n          # compactall alone will not print ops or threads, which will fail update_report\n          run_db_bench \"fillseq,compactall\" $NUM_KEYS 1 0 0\n          # only save for future use on success\n          test_remote \"mv $DB_PATH $ORIGIN_PATH\"\n      fi\n  fi\n  if [ $TEST_MODE -ge 1 ]; then\n      build_checkpoint\n      # run_db_bench benchmark_name NUM_OPS NUM_THREADS USED_EXISTING_DB UPDATE_REPORT ASYNC_IO\n      run_db_bench \"seekrandom_asyncio\" $NUM_OPS $NUM_THREADS  1 1 true\n      run_db_bench \"multireadrandom_asyncio\" $NUM_OPS $NUM_THREADS  1 1 true\n      run_db_bench \"readrandom\"\n      run_db_bench \"readwhilewriting\"\n      run_db_bench \"deleterandom\"\n      run_db_bench \"seekrandom\"\n      run_db_bench \"seekrandomwhilewriting\"\n      run_db_bench \"multireadrandom\"\n  fi\n\n  cleanup_test_directory $TEST_ROOT_DIR\n  echo \"\"\n  echo \"Benchmark completed!  Results are available in $RESULT_PATH\"\n}\n\n############################################################################\nfunction init_arguments {\n  K=1024\n  M=$((1024 * K))\n  G=$((1024 * M))\n\n  current_time=$(date +\"%F-%H:%M:%S\")\n  RESULT_PATH=${RESULT_PATH:-\"$1/results/$current_time\"}\n  COMMIT_ID=`hg id -i 2>/dev/null || git rev-parse HEAD 2>/dev/null || echo 'unknown'`\n  SUMMARY_FILE=\"$RESULT_PATH/SUMMARY.csv\"\n\n  DB_PATH=${3:-\"$1/db\"}\n  ORIGIN_PATH=${ORIGIN_PATH:-\"$(dirname $(dirname $DB_PATH))/db\"}\n  WAL_PATH=${4:-\"\"}\n  if [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n    DB_BENCH_DIR=${5:-\".\"}\n  else\n    DB_BENCH_DIR=${5:-\"$1/db_bench\"}\n  fi\n\n  DEBUG=${DEBUG:-0}\n  TEST_MODE=${TEST_MODE:-1}\n  SCP=${SCP:-\"scp\"}\n  SSH=${SSH:-\"ssh\"}\n  NUM_THREADS=${NUM_THREADS:-16}\n  NUM_KEYS=${NUM_KEYS:-$((1 * G))}  # key range\n  NUM_OPS=${NUM_OPS:-$(($NUM_KEYS / $NUM_THREADS))}\n  KEY_SIZE=${KEY_SIZE:-100}\n  VALUE_SIZE=${VALUE_SIZE:-900}\n  CACHE_SIZE=${CACHE_SIZE:-$((1 * G))}\n  STATISTICS=${STATISTICS:-0}\n  COMPRESSION_RATIO=${COMPRESSION_RATIO:-0.5}\n  HISTOGRAM=${HISTOGRAM:-1}\n  NUM_MULTI_DB=${NUM_MULTI_DB:-1}\n  STATS_PER_INTERVAL=${STATS_PER_INTERVAL:-1}\n  STATS_INTERVAL_SECONDS=${STATS_INTERVAL_SECONDS:-600}\n  MAX_BACKGROUND_FLUSHES=${MAX_BACKGROUND_FLUSHES:-4}\n  MAX_BACKGROUND_COMPACTIONS=${MAX_BACKGROUND_COMPACTIONS:-16}\n  NUM_HIGH_PRI_THREADS=${NUM_HIGH_PRI_THREADS:-4}\n  NUM_LOW_PRI_THREADS=${NUM_LOW_PRI_THREADS:-16}\n  DELETE_TEST_PATH=${DELETE_TEST_PATH:-0}\n  SEEK_NEXTS=${SEEK_NEXTS:-10}\n  SEED=${SEED:-$( date +%s )}\n  MULTIREAD_BATCH_SIZE=${MULTIREAD_BATCH_SIZE:-128}\n  MULTIREAD_STRIDE=${MULTIREAD_STRIDE:-12}\n  PERF_LEVEL=${PERF_LEVEL:-1}\n}\n\n# $1 --- benchmark name\n# $2 --- number of operations.  Default: $NUM_OPS\n# $3 --- number of threads.  Default $NUM_THREADS\n# $4 --- use_existing_db.  Default: 1\n# $5 --- update_report. Default: 1\n# $6 --- async_io. Default: False\nfunction run_db_bench {\n  # Make sure no other db_bench is running. (Make sure command succeeds if pidof\n  # command exists but finds nothing.)\n  pids_cmd='pidof db_bench || pidof --version > /dev/null'\n  # But first, make best effort to kill any db_bench that have run for more\n  # than 12 hours, as that indicates a hung or runaway process.\n  kill_old_cmd='for PID in $(pidof db_bench); do [ \"$(($(stat -c %Y /proc/$PID) + 43200))\" -lt \"$(date +%s)\" ] && echo \"Killing old db_bench $PID\" && kill $PID && sleep 5 && kill -9 $PID && sleep 5; done; pidof --version > /dev/null'\n  if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n    pids_cmd=\"$SSH $REMOTE_USER_AT_HOST '$pids_cmd'\"\n    kill_old_cmd=\"$SSH $REMOTE_USER_AT_HOST '$kill_old_cmd'\"\n  fi\n\n  eval $kill_old_cmd\n  exit_on_error $? \"$kill_old_cmd\"\n\n  pids_output=\"$(eval $pids_cmd)\"\n  exit_on_error $? \"$pids_cmd\"\n\n  if [ \"$pids_output\" != \"\" ]; then\n    echo \"Stopped regression_test.sh as there're still recent db_bench \"\n    echo \"processes running: $pids_output\"\n    echo \"Clean up test directory\"\n    cleanup_test_directory $TEST_ROOT_DIR\n    exit 2\n  fi\n\n  # Build db_bench command\n  ops=${2:-$NUM_OPS}\n  threads=${3:-$NUM_THREADS}\n  USE_EXISTING_DB=${4:-1}\n  UPDATE_REPORT=${5:-1}\n  async_io=${6:-false}\n  seek_nexts=$SEEK_NEXTS\n\n  if [ \"$async_io\" == \"true\" ]; then\n    if ! [ -z \"$SEEK_NEXTS_ASYNC_IO\" ]; then\n      seek_nexts=$SEEK_NEXTS_ASYNC_IO\n    fi\n  fi\n\n\n  echo \"\"\n  echo \"=======================================================================\"\n  echo \"Benchmark $1\"\n  echo \"=======================================================================\"\n  echo \"\"\n  db_bench_error=0\n  options_file_arg=$(setup_options_file)\n  echo \"$options_file_arg\"\n\n  # In case of async_io, benchmark is benchmark_asyncio\n  db_bench_type=${1%%_*}\n\n  # use `which time` to avoid using bash's internal time command\n  db_bench_cmd=\"\\$(which time) -p $DB_BENCH_DIR/db_bench \\\n      --benchmarks=$db_bench_type --db=$DB_PATH --wal_dir=$WAL_PATH \\\n      --use_existing_db=$USE_EXISTING_DB \\\n      --perf_level=$PERF_LEVEL \\\n      --disable_auto_compactions \\\n      --threads=$threads \\\n      --num=$NUM_KEYS \\\n      --reads=$ops \\\n      --writes=$ops \\\n      --deletes=$ops \\\n      --key_size=$KEY_SIZE \\\n      --value_size=$VALUE_SIZE \\\n      --cache_size=$CACHE_SIZE \\\n      --statistics=$STATISTICS \\\n      $options_file_arg \\\n      --compression_ratio=$COMPRESSION_RATIO \\\n      --histogram=$HISTOGRAM \\\n      --seek_nexts=$seek_nexts \\\n      --stats_per_interval=$STATS_PER_INTERVAL \\\n      --stats_interval_seconds=$STATS_INTERVAL_SECONDS \\\n      --max_background_flushes=$MAX_BACKGROUND_FLUSHES \\\n      --num_multi_db=$NUM_MULTI_DB \\\n      --max_background_compactions=$MAX_BACKGROUND_COMPACTIONS \\\n      --num_high_pri_threads=$NUM_HIGH_PRI_THREADS \\\n      --num_low_pri_threads=$NUM_LOW_PRI_THREADS \\\n      --seed=$SEED \\\n      --multiread_batched=true \\\n      --batch_size=$MULTIREAD_BATCH_SIZE \\\n      --multiread_stride=$MULTIREAD_STRIDE \\\n      --async_io=$async_io\"\n\n  if [ \"$async_io\" == \"true\" ]; then\n    db_bench_cmd=\"$db_bench_cmd $(set_async_io_parameters) \"\n  fi\n\n  db_bench_cmd=\" $db_bench_cmd 2>&1\"\n\n  if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n    echo \"Running benchmark remotely on $REMOTE_USER_AT_HOST\"\n    db_bench_cmd=\"$SSH $REMOTE_USER_AT_HOST '$db_bench_cmd'\"\n  fi\n  echo db_bench_cmd=\"$db_bench_cmd\"\n\n  # Run the db_bench command\n  eval $db_bench_cmd | tee -a \"$RESULT_PATH/$1\"\n  exit_on_error ${PIPESTATUS[0]} db_bench\n  if [ $UPDATE_REPORT -ne 0 ]; then\n    update_report \"$1\" \"$RESULT_PATH/$1\" $ops $threads\n  fi\n}\n\nfunction set_async_io_parameters {\n  options=\" --duration=500\"\n  # Below parameters are used in case of async_io only.\n  # 1. If you want to run below parameters for all benchmarks, it should be\n  #    specify in OPTIONS_FILE instead of exporting them.\n  # 2. Below exported var takes precedence over OPTIONS_FILE.\n  if ! [ -z \"$MAX_READAHEAD_SIZE\" ]; then\n    options=\"$options --max_auto_readahead_size=$MAX_READAHEAD_SIZE \"\n  fi\n  if ! [ -z \"$INITIAL_READAHEAD_SIZE\" ]; then\n    options=\"$options --initial_auto_readahead_size=$INITIAL_READAHEAD_SIZE \"\n  fi\n  if ! [ -z \"$NUM_READS_FOR_READAHEAD_SIZE\" ]; then\n    options=\"$options --num_file_reads_for_auto_readahead=$NUM_READS_FOR_READAHEAD_SIZE \"\n  fi\n  echo $options\n}\n\nfunction build_checkpoint {\n    cmd_prefix=\"\"\n    if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n        cmd_prefix=\"$SSH $REMOTE_USER_AT_HOST \"\n    fi\n    if [ $NUM_MULTI_DB -gt 1 ]; then\n        dirs=$($cmd_prefix find $ORIGIN_PATH -type d -links 2)\n        for dir in $dirs; do\n            db_index=$(basename $dir)\n            echo \"Building checkpoints: $ORIGIN_PATH/$db_index -> $DB_PATH/$db_index ...\"\n            $cmd_prefix $DB_BENCH_DIR/ldb checkpoint --checkpoint_dir=$DB_PATH/$db_index \\\n                        --db=$ORIGIN_PATH/$db_index --try_load_options 2>&1\n            exit_on_error $?\n        done\n    else\n        # checkpoint cannot build in directory already exists\n        $cmd_prefix rm -rf $DB_PATH\n        echo \"Building checkpoint: $ORIGIN_PATH -> $DB_PATH ...\"\n        $cmd_prefix $DB_BENCH_DIR/ldb checkpoint --checkpoint_dir=$DB_PATH \\\n                    --db=$ORIGIN_PATH --try_load_options 2>&1\n        exit_on_error $?\n    fi\n}\n\nfunction multiply {\n  echo \"$1 * $2\" | bc\n}\n\n# $1 --- name of the benchmark\n# $2 --- the filename of the output log of db_bench\nfunction update_report {\n  # In case of async_io, benchmark is benchmark_asyncio\n  db_bench_type=${1%%_*}\n\n  main_result=`cat $2 | grep $db_bench_type`\n  exit_on_error $?\n  perc_statement=`cat $2 | grep Percentile`\n  exit_on_error $?\n\n  # Obtain micros / op\n\n  [[ $main_result =~ $MAIN_PATTERN ]]\n  ops_per_s=${BASH_REMATCH[1]}\n\n  # Obtain percentile information\n  [[ $perc_statement =~ $PERC_PATTERN ]]\n  perc[0]=${BASH_REMATCH[1]}  # p50\n  perc[1]=${BASH_REMATCH[2]}  # p75\n  perc[2]=${BASH_REMATCH[3]}  # p99\n  perc[3]=${BASH_REMATCH[4]}  # p99.9\n  perc[4]=${BASH_REMATCH[5]}  # p99.99\n\n  # Parse the output of the time command\n  real_sec=`tail -3 $2 | grep real | awk '{print $2}'`\n  user_sec=`tail -3 $2 | grep user | awk '{print $2}'`\n  sys_sec=`tail -3 $2 | grep sys | awk '{print $2}'`\n\n  (printf \"$DATA_FORMAT\" \\\n    $COMMIT_ID $1 $REMOTE_USER_AT_HOST $NUM_MULTI_DB $NUM_KEYS $KEY_SIZE $VALUE_SIZE \\\n       $(multiply $COMPRESSION_RATIO 100) \\\n       $3 $4 $CACHE_SIZE \\\n       $MAX_BACKGROUND_FLUSHES $MAX_BACKGROUND_COMPACTIONS \\\n       $ops_per_s \\\n       $(multiply ${perc[0]} 1000) \\\n       $(multiply ${perc[1]} 1000) \\\n       $(multiply ${perc[2]} 1000) \\\n       $(multiply ${perc[3]} 1000) \\\n       $(multiply ${perc[4]} 1000) \\\n       $DEBUG \\\n       $real_sec \\\n       $user_sec \\\n       $sys_sec \\\n       >> $SUMMARY_FILE)\n  exit_on_error $?\n}\n\nfunction exit_on_error {\n  if [ $1 -ne 0 ]; then\n    echo \"\"\n    echo \"ERROR: Benchmark did not complete successfully.\"\n    if ! [ -z \"$2\" ]; then\n      echo \"Failure command: $2\"\n    fi\n    echo \"Partial results are output to $RESULT_PATH\"\n    echo \"ERROR\" >> $SUMMARY_FILE\n    exit $1\n  fi\n}\n\nfunction build_db_bench_and_ldb {\n  echo \"Building db_bench & ldb ...\"\n\n  make clean\n  exit_on_error $?\n\n  DEBUG_LEVEL=0 make db_bench ldb -j32\n  exit_on_error $?\n}\n\nfunction run_remote {\n  test_remote \"$1\"\n  exit_on_error $? \"$1\"\n}\n\nfunction test_remote {\n  if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n      cmd=\"$SSH $REMOTE_USER_AT_HOST '$1'\"\n  else\n      cmd=\"$1\"\n  fi\n  eval \"$cmd\"\n}\n\nfunction run_local {\n  eval \"$1\"\n  exit_on_error $? \"$1\"\n}\n\nfunction setup_options_file {\n if ! [ -z \"$OPTIONS_FILE\" ]; then\n    if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n      options_file=\"$DB_BENCH_DIR/OPTIONS_FILE\"\n      run_local \"$SCP $OPTIONS_FILE $REMOTE_USER_AT_HOST:$options_file\"\n    else\n      options_file=\"$OPTIONS_FILE\"\n    fi\n    echo \"--options_file=$options_file\"\n  fi\n  echo \"\"\n}\n\nfunction setup_test_directory {\n  echo \"Deleting old regression test directories and creating new ones\"\n\n  run_local 'test \"$DB_PATH\" != \".\"'\n  run_remote \"rm -rf $DB_PATH\"\n\n  if [ \"$DB_BENCH_DIR\" != \".\" ]; then\n    run_remote \"rm -rf $DB_BENCH_DIR\"\n  fi\n\n  run_local 'test \"$RESULT_PATH\" != \".\"'\n  run_local \"rm -rf $RESULT_PATH\"\n\n  if ! [ -z \"$WAL_PATH\" ]; then\n    run_remote \"rm -rf $WAL_PATH\"\n    run_remote \"mkdir -p $WAL_PATH\"\n  fi\n\n  run_remote \"mkdir -p $DB_PATH\"\n\n  run_remote \"mkdir -p $DB_BENCH_DIR\"\n  run_remote \"ls -l $DB_BENCH_DIR\"\n\n  if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n      shopt -s nullglob # allow missing librocksdb*.so* for static lib build\n      run_local \"tar cz db_bench ldb librocksdb*.so* | $SSH $REMOTE_USER_AT_HOST 'cd $DB_BENCH_DIR/ && tar xzv'\"\n      shopt -u nullglob\n  fi\n\n  run_local \"mkdir -p $RESULT_PATH\"\n\n  (printf $TITLE_FORMAT \\\n      \"commit id\" \"benchmark\" \"user@host\" \"num-dbs\" \"key-range\" \"key-size\" \\\n      \"value-size\" \"compress-rate\" \"ops-per-thread\" \"num-threads\" \"cache-size\" \\\n      \"flushes\" \"compactions\" \\\n      \"ops-per-s\" \"p50\" \"p75\" \"p99\" \"p99.9\" \"p99.99\" \"debug\" \\\n      \"real-sec\" \"user-sec\" \"sys-sec\" \\\n      >> $SUMMARY_FILE)\n  exit_on_error $?\n}\n\nfunction cleanup_test_directory {\n\n  if [ $DELETE_TEST_PATH -ne 0 ]; then\n    echo \"Clear old regression test directories and creating new ones\"\n    run_remote \"rm -rf $DB_PATH\"\n    run_remote \"rm -rf $WAL_PATH\"\n    if ! [ -z \"$REMOTE_USER_AT_HOST\" ]; then\n      run_remote \"rm -rf $DB_BENCH_DIR\"\n    fi\n    run_remote \"rm -rf $1\"\n  else\n    echo \"------------ DEBUG MODE ------------\"\n    echo \"DB  PATH: $DB_PATH\"\n    echo \"WAL PATH: $WAL_PATH\"\n  fi\n}\n\n############################################################################\n\n# shellcheck disable=SC2068\nmain $@\n", "num_lines": 527}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n#\n\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: ${BASH_SOURCE[0]} <Backup Dir> <DB Path>\"\n  exit 1\nfi\n\nbackup_dir=\"$1\"\ndb_dir=\"$2\"\n\necho \"== Restoring latest from $backup_dir to $db_dir\"\n./ldb restore --db=\"$db_dir\" --backup_dir=\"$backup_dir\"\n", "num_lines": 16}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC2148\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\nTESTDIR=`mktemp -d ${TMPDIR:-/tmp}/rocksdb-dump-test.XXXXX`\nDUMPFILE=\"tools/sample-dump.dmp\"\n\n# Verify that the sample dump file is undumpable and then redumpable.\n./rocksdb_undump --dump_location=$DUMPFILE --db_path=$TESTDIR/db\n./rocksdb_dump --anonymous --db_path=$TESTDIR/db --dump_location=$TESTDIR/dump\ncmp $DUMPFILE $TESTDIR/dump\n", "num_lines": 10}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# BlobDB benchmark script\n#\n# REQUIRES: benchmark.sh is in the tools subdirectory\n#\n# After the execution of this script, log files are available in $output_dir.\n# report.tsv provides high level statistics.\n#\n# Should be run from the parent of the tools directory. The command line is:\n#   [$env_vars] tools/run_blob_bench.sh\n#\n# This runs the following sequence of BlobDB performance tests:\n#   phase 1) write-only - bulkload+compact, overwrite+waitforcompaction\n#   phase 2) read-write - readwhilewriting, fwdrangewhilewriting\n#   phase 3) read-only - readrandom, fwdrange\n#\n\n# Exit Codes\nEXIT_INVALID_ARGS=1\n\n# Size constants\nK=1024\nM=$((1024 * K))\nG=$((1024 * M))\nT=$((1024 * G))\n\nfunction display_usage() {\n  echo \"usage: run_blob_bench.sh [--help]\"\n  echo \"\"\n  echo \"Runs the following sequence of BlobDB benchmark tests using tools/benchmark.sh:\"\n  echo -e \"\\tPhase 1: write-only tests: bulkload+compact, overwrite+waitforcompaction\"\n  echo -e \"\\tPhase 2: read-write tests: readwhilewriting, fwdrangewhilewriting\"\n  echo -e \"\\tPhase 3: read-only tests: readrandom, fwdrange\"\n  echo \"\"\n  echo \"Environment Variables:\"\n  echo -e \"\\tJOB_ID\\t\\t\\t\\tIdentifier for the benchmark job, will appear in the results (default: empty)\"\n  echo -e \"\\tDB_DIR\\t\\t\\t\\tPath for the RocksDB data directory (mandatory)\"\n  echo -e \"\\tWAL_DIR\\t\\t\\t\\tPath for the RocksDB WAL directory (mandatory)\"\n  echo -e \"\\tOUTPUT_DIR\\t\\t\\tPath for the benchmark results (mandatory)\"\n  echo -e \"\\tNUM_THREADS\\t\\t\\tNumber of threads (default: 16)\"\n  echo -e \"\\tCOMPRESSION_TYPE\\t\\tCompression type for the SST files (default: lz4)\"\n  echo -e \"\\tDB_SIZE\\t\\t\\t\\tRaw (uncompressed) database size (default: 1 TB)\"\n  echo -e \"\\tVALUE_SIZE\\t\\t\\tValue size (default: 1 KB)\"\n  echo -e \"\\tNUM_KEYS\\t\\t\\tNumber of keys (default: raw database size divided by value size)\"\n  echo -e \"\\tDURATION\\t\\t\\tIndividual duration for read-write/read-only tests in seconds (default: 1800)\"\n  echo -e \"\\tWRITE_BUFFER_SIZE\\t\\tWrite buffer (memtable) size (default: 1 GB)\"\n  echo -e \"\\tENABLE_BLOB_FILES\\t\\tEnable blob files (default: 1)\"\n  echo -e \"\\tMIN_BLOB_SIZE\\t\\t\\tSize threshold for storing values in blob files (default: 0)\"\n  echo -e \"\\tBLOB_FILE_SIZE\\t\\t\\tBlob file size (default: same as write buffer size)\"\n  echo -e \"\\tBLOB_COMPRESSION_TYPE\\t\\tCompression type for the blob files (default: lz4)\"\n  echo -e \"\\tENABLE_BLOB_GC\\t\\t\\tEnable blob garbage collection (default: 1)\"\n  echo -e \"\\tBLOB_GC_AGE_CUTOFF\\t\\tBlob garbage collection age cutoff (default: 0.25)\"\n  echo -e \"\\tBLOB_GC_FORCE_THRESHOLD\\t\\tThreshold for forcing garbage collection of the oldest blob files (default: 1.0)\"\n  echo -e \"\\tBLOB_COMPACTION_READAHEAD_SIZE\\tBlob compaction readahead size (default: 0)\"\n  echo -e \"\\tBLOB_FILE_STARTING_LEVEL\\t\\tBlob file starting level (default: 0)\"\n  echo -e \"\\tUSE_BLOB_CACHE\\t\\t\\tEnable blob cache. (default: 1)\"\n  echo -e \"\\tUSE_SHARED_BLOCK_AND_BLOB_CACHE\\t\\t\\tUse the same backing cache for block cache and blob cache. (default: 1)\"\n  echo -e \"\\tBLOB_CACHE_SIZE\\t\\t\\tSize of the blob cache (default: 16GB)\"\n  echo -e \"\\tBLOB_CACHE_NUMSHARDBITS\\t\\t\\tNumber of shards for the blob cache is 2 ** blob_cache_numshardbits (default: 6)\"\n  echo -e \"\\tPREPOPULATE_BLOB_CACHE\\t\\t\\tPre-populate hot/warm blobs in blob cache (default: 0)\"\n  echo -e \"\\tTARGET_FILE_SIZE_BASE\\t\\tTarget SST file size for compactions (default: write buffer size, scaled down if blob files are enabled)\"\n  echo -e \"\\tMAX_BYTES_FOR_LEVEL_BASE\\tMaximum size for the base level (default: 8 * target SST file size)\"\n}\n\nif [ $# -ge 1 ]; then\n  display_usage\n\n  if [ \"$1\" == \"--help\" ]; then\n    exit\n  else\n    exit $EXIT_INVALID_ARGS\n  fi\nfi\n\n# shellcheck disable=SC2153\nif [ -z \"$DB_DIR\" ]; then\n  echo \"DB_DIR is not defined\"\n  exit $EXIT_INVALID_ARGS\nfi\n\n# shellcheck disable=SC2153\nif [ -z \"$WAL_DIR\" ]; then\n  echo \"WAL_DIR is not defined\"\n  exit $EXIT_INVALID_ARGS\nfi\n\n# shellcheck disable=SC2153\nif [ -z \"$OUTPUT_DIR\" ]; then\n  echo \"OUTPUT_DIR is not defined\"\n  exit $EXIT_INVALID_ARGS\nfi\n\n# shellcheck disable=SC2153\njob_id=$JOB_ID\n\ndb_dir=$DB_DIR\nwal_dir=$WAL_DIR\noutput_dir=$OUTPUT_DIR\n\nnum_threads=${NUM_THREADS:-16}\n\ncompression_type=${COMPRESSION_TYPE:-lz4}\n\ndb_size=${DB_SIZE:-$((1 * T))}\nvalue_size=${VALUE_SIZE:-$((1 * K))}\nnum_keys=${NUM_KEYS:-$((db_size / value_size))}\n\nduration=${DURATION:-1800}\n\nwrite_buffer_size=${WRITE_BUFFER_SIZE:-$((1 * G))}\n\nenable_blob_files=${ENABLE_BLOB_FILES:-1}\nmin_blob_size=${MIN_BLOB_SIZE:-0}\nblob_file_size=${BLOB_FILE_SIZE:-$write_buffer_size}\nblob_compression_type=${BLOB_COMPRESSION_TYPE:-lz4}\nenable_blob_garbage_collection=${ENABLE_BLOB_GC:-1}\nblob_garbage_collection_age_cutoff=${BLOB_GC_AGE_CUTOFF:-0.25}\nblob_garbage_collection_force_threshold=${BLOB_GC_FORCE_THRESHOLD:-1.0}\nblob_compaction_readahead_size=${BLOB_COMPACTION_READAHEAD_SIZE:-0}\nblob_file_starting_level=${BLOB_FILE_STARTING_LEVEL:-0}\nuse_blob_cache=${USE_BLOB_CACHE:-1}\nuse_shared_block_and_blob_cache=${USE_SHARED_BLOCK_AND_BLOB_CACHE:-1}\nblob_cache_size=${BLOB_CACHE_SIZE:-$((16 * G))}\nblob_cache_numshardbits=${BLOB_CACHE_NUMSHARDBITS:-6}\nprepopulate_blob_cache=${PREPOPULATE_BLOB_CACHE:-0}\n\nif [ \"$enable_blob_files\" == \"1\" ]; then\n  target_file_size_base=${TARGET_FILE_SIZE_BASE:-$((32 * write_buffer_size / value_size))}\nelse\n  target_file_size_base=${TARGET_FILE_SIZE_BASE:-$write_buffer_size}\nfi\n\nmax_bytes_for_level_base=${MAX_BYTES_FOR_LEVEL_BASE:-$((8 * target_file_size_base))}\n\necho \"======================== Benchmark setup ========================\"\necho -e \"Job ID:\\t\\t\\t\\t\\t$job_id\"\necho -e \"Data directory:\\t\\t\\t\\t$db_dir\"\necho -e \"WAL directory:\\t\\t\\t\\t$wal_dir\"\necho -e \"Output directory:\\t\\t\\t$output_dir\"\necho -e \"Number of threads:\\t\\t\\t$num_threads\"\necho -e \"Compression type for SST files:\\t\\t$compression_type\"\necho -e \"Raw database size:\\t\\t\\t$db_size\"\necho -e \"Value size:\\t\\t\\t\\t$value_size\"\necho -e \"Number of keys:\\t\\t\\t\\t$num_keys\"\necho -e \"Duration of read-write/read-only tests:\\t$duration\"\necho -e \"Write buffer size:\\t\\t\\t$write_buffer_size\"\necho -e \"Blob files enabled:\\t\\t\\t$enable_blob_files\"\necho -e \"Blob size threshold:\\t\\t\\t$min_blob_size\"\necho -e \"Blob file size:\\t\\t\\t\\t$blob_file_size\"\necho -e \"Compression type for blob files:\\t$blob_compression_type\"\necho -e \"Blob GC enabled:\\t\\t\\t$enable_blob_garbage_collection\"\necho -e \"Blob GC age cutoff:\\t\\t\\t$blob_garbage_collection_age_cutoff\"\necho -e \"Blob GC force threshold:\\t\\t$blob_garbage_collection_force_threshold\"\necho -e \"Blob compaction readahead size:\\t\\t$blob_compaction_readahead_size\"\necho -e \"Blob file starting level:\\t\\t$blob_file_starting_level\"\necho -e \"Blob cache enabled:\\t\\t\\t$use_blob_cache\"\necho -e \"Blob cache and block cache shared:\\t\\t\\t$use_shared_block_and_blob_cache\"\necho -e \"Blob cache size:\\t\\t$blob_cache_size\"\necho -e \"Blob cache number of shard bits:\\t\\t$blob_cache_numshardbits\"\necho -e \"Blob cache prepopulated:\\t\\t\\t$prepopulate_blob_cache\"\necho -e \"Target SST file size:\\t\\t\\t$target_file_size_base\"\necho -e \"Maximum size of base level:\\t\\t$max_bytes_for_level_base\"\necho \"=================================================================\"\n\nrm -rf \"$db_dir\"\nrm -rf \"$wal_dir\"\nrm -rf \"$output_dir\"\n\nENV_VARS=\"\\\n  JOB_ID=$job_id \\\n  DB_DIR=$db_dir \\\n  WAL_DIR=$wal_dir \\\n  OUTPUT_DIR=$output_dir \\\n  NUM_THREADS=$num_threads \\\n  COMPRESSION_TYPE=$compression_type \\\n  VALUE_SIZE=$value_size \\\n  NUM_KEYS=$num_keys\"\n\nENV_VARS_D=\"$ENV_VARS DURATION=$duration\"\n\nPARAMS=\"\\\n  --enable_blob_files=$enable_blob_files \\\n  --min_blob_size=$min_blob_size \\\n  --blob_file_size=$blob_file_size \\\n  --blob_compression_type=$blob_compression_type \\\n  --blob_file_starting_level=$blob_file_starting_level \\\n  --use_blob_cache=$use_blob_cache \\\n  --use_shared_block_and_blob_cache=$use_shared_block_and_blob_cache \\\n  --blob_cache_size=$blob_cache_size \\\n  --blob_cache_numshardbits=$blob_cache_numshardbits \\\n  --prepopulate_blob_cache=$prepopulate_blob_cache \\\n  --write_buffer_size=$write_buffer_size \\\n  --target_file_size_base=$target_file_size_base \\\n  --max_bytes_for_level_base=$max_bytes_for_level_base\"\n\nPARAMS_GC=\"$PARAMS \\\n  --enable_blob_garbage_collection=$enable_blob_garbage_collection \\\n  --blob_garbage_collection_age_cutoff=$blob_garbage_collection_age_cutoff \\\n  --blob_garbage_collection_force_threshold=$blob_garbage_collection_force_threshold \\\n  --blob_compaction_readahead_size=$blob_compaction_readahead_size\"\n\n# bulk load (using fillrandom) + compact\nenv -u DURATION -S \"$ENV_VARS\" ./tools/benchmark.sh bulkload \"$PARAMS\"\n\n# overwrite + waitforcompaction\nenv -u DURATION -S \"$ENV_VARS\" ./tools/benchmark.sh overwrite \"$PARAMS_GC\"\n\n# readwhilewriting\nenv -S \"$ENV_VARS_D\" ./tools/benchmark.sh readwhilewriting \"$PARAMS_GC\"\n\n# fwdrangewhilewriting\nenv -S \"$ENV_VARS_D\" ./tools/benchmark.sh fwdrangewhilewriting \"$PARAMS_GC\"\n\n# readrandom\nenv -S \"$ENV_VARS_D\" ./tools/benchmark.sh readrandom \"$PARAMS_GC\"\n\n# fwdrange\nenv -S \"$ENV_VARS_D\" ./tools/benchmark.sh fwdrange \"$PARAMS_GC\"\n\n# save logs to output directory\ncp \"$db_dir\"/LOG* \"$output_dir/\"\n", "num_lines": 224}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# REQUIRE: benchmark.sh exists in the current directory\n# After execution of this script, log files are generated in $output_dir.\n# report.txt provides a high level statistics\n\n# This should be run from the parent of the tools directory. The command line is:\n#   [$env_vars] tools/run_flash_bench.sh [list-of-threads]\n#\n# This runs a sequence of tests in the following sequence:\n#   step 1) load - bulkload, compact, fillseq, overwrite\n#   step 2) read-only for each number of threads\n#   step 3) read-write for each number of threads\n#   step 4) merge for each number of threads\n#\n# The list of threads is optional and when not set is equivalent to \"24\". \n# Were list-of-threads specified as \"1 2 4\" then the tests in steps 2, 3 and\n# 4 above would be repeated for 1, 2 and 4 threads. The tests in step 1 are\n# only run for 1 thread.\n\n# Test output is written to $OUTPUT_DIR, currently /tmp/output. The performance\n# summary is in $OUTPUT_DIR/report.txt. There is one file in $OUTPUT_DIR per\n# test and the tests are listed below.\n#\n# The environment variables are also optional. The variables are:\n#\n#   NKEYS         - number of key/value pairs to load\n#   BG_MBWRITEPERSEC - write rate limit in MB/second for tests in which\n#                   there is one thread doing writes and stats are\n#                   reported for read threads. \"BG\" stands for background.\n#                   If this is too large then the non-writer threads can get\n#                   starved. This is used for the \"readwhile\" tests.\n#   FG_MBWRITEPERSEC - write rate limit in MB/second for tests like overwrite\n#                   where stats are reported for the write threads.\n#   NSECONDS      - number of seconds for which to run each test in steps 2,\n#                   3 and 4. There are currently 15 tests in those steps and\n#                   they are repeated for each entry in list-of-threads so\n#                   this variable lets you control the total duration to\n#                   finish the benchmark.\n#   RANGE_LIMIT   - the number of rows to read per range query for tests that\n#                   do range queries.\n#   VAL_SIZE      - the length of the value in the key/value pairs loaded.\n#                   You can estimate the size of the test database from this,\n#                   NKEYS and the compression rate (--compression_ratio) set\n#                   in tools/benchmark.sh\n#   BLOCK_LENGTH  - value for db_bench --block_size\n#   CACHE_BYTES   - the size of the RocksDB block cache in bytes\n#   DATA_DIR      - directory in which to create database files\n#   LOG_DIR       - directory in which to create WAL files, may be the same\n#                   as DATA_DIR\n#   DO_SETUP      - when set to 0 then a backup of the database is copied from\n#                   $DATA_DIR.bak to $DATA_DIR and the load tests from step 1\n#                   The WAL directory is also copied from a backup if\n#                   DATA_DIR != LOG_DIR. This allows tests from steps 2, 3, 4\n#                   to be repeated faster.\n#   SAVE_SETUP    - saves a copy of the database at the end of step 1 to\n#                   $DATA_DIR.bak. When LOG_DIR != DATA_DIR then it is copied\n#                   to $LOG_DIR.bak.\n#   SKIP_LOW_PRI_TESTS - skip some of the tests which aren't crucial for getting\n#                   actionable benchmarking data (look for keywords \"bulkload\",\n#                   \"sync=1\", and \"while merging\").\n#\n\n# Size constants\nK=1024\nM=$((1024 * K))\nG=$((1024 * M))\n\nnum_keys=${NKEYS:-$((1 * G))}\n# write rate for readwhile... tests\nbg_mbwps=${BG_MBWRITEPERSEC:-4}\n# write rate for tests other than readwhile, 0 means no limit\nfg_mbwps=${FG_MBWRITEPERSEC:-0}\nduration=${NSECONDS:-$((60 * 60))}\nnps=${RANGE_LIMIT:-10}\nvs=${VAL_SIZE:-400}\ncs=${CACHE_BYTES:-$(( 1 * G ))}\nbs=${BLOCK_LENGTH:-8192}\n\n# If no command line arguments then run for 24 threads.\nif [[ $# -eq 0 ]]; then\n  nthreads=( 24 )\nelse\n  nthreads=( \"$@\" )\nfi\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  echo Will run for $num_thr threads\ndone\n\n# Update these parameters before execution !!!\ndb_dir=${DATA_DIR:-\"/tmp/rocksdb/\"}\nwal_dir=${LOG_DIR:-\"/tmp/rocksdb/\"}\n\ndo_setup=${DO_SETUP:-1}\nsave_setup=${SAVE_SETUP:-0}\n\n# By default we'll run all the tests. Set this to skip a set of tests which\n# aren't critical for getting key metrics.\nskip_low_pri_tests=${SKIP_LOW_PRI_TESTS:-0}\n\nif [[ $skip_low_pri_tests == 1 ]]; then\n  echo \"Skipping some non-critical tests because SKIP_LOW_PRI_TESTS is set.\"\nfi\n\noutput_dir=\"${TMPDIR:-/tmp}/output\"\n\nARGS=\"\\\nOUTPUT_DIR=$output_dir \\\nNUM_KEYS=$num_keys \\\nDB_DIR=$db_dir \\\nWAL_DIR=$wal_dir \\\nVALUE_SIZE=$vs \\\nBLOCK_SIZE=$bs \\\nCACHE_SIZE=$cs\"\n\nmkdir -p $output_dir\necho -e \"ops/sec\\tmb/sec\\tSize-GB\\tL0_GB\\tSum_GB\\tW-Amp\\tW-MB/s\\tusec/op\\tp50\\tp75\\tp99\\tp99.9\\tp99.99\\tUptime\\tStall-time\\tStall%\\tTest\" \\\n  > $output_dir/report.txt\n\n# Notes on test sequence:\n#   step 1) Setup database via sequential fill followed by overwrite to fragment it.\n#           Done without setting DURATION to make sure that overwrite does $num_keys writes\n#   step 2) read-only tests for all levels of concurrency requested\n#   step 3) non read-only tests for all levels of concurrency requested\n#   step 4) merge tests for all levels of concurrency requested. These must come last.\n\n###### Setup the database\n\nif [[ $do_setup != 0 ]]; then\n  echo Doing setup\n\n  if [[ $skip_low_pri_tests != 1 ]]; then\n    # Test 1: bulk load\n    env $ARGS ./tools/benchmark.sh bulkload\n  fi\n\n  # Test 2a: sequential fill with large values to get peak ingest\n  #          adjust NUM_KEYS given the use of larger values\n  env $ARGS BLOCK_SIZE=$((1 * M)) VALUE_SIZE=$((32 * K)) NUM_KEYS=$(( num_keys / 64 )) \\\n       ./tools/benchmark.sh fillseq_disable_wal\n\n  # Test 2b: sequential fill with the configured value size\n  env $ARGS ./tools/benchmark.sh fillseq_disable_wal\n\n  # Test 2c: same as 2a, but with WAL being enabled.\n  env $ARGS BLOCK_SIZE=$((1 * M)) VALUE_SIZE=$((32 * K)) NUM_KEYS=$(( num_keys / 64 )) \\\n       ./tools/benchmark.sh fillseq_enable_wal\n\n  # Test 2d: same as 2b, but with WAL being enabled.\n  env $ARGS ./tools/benchmark.sh fillseq_enable_wal\n\n  # Test 3: single-threaded overwrite\n  env $ARGS NUM_THREADS=1 DB_BENCH_NO_SYNC=1 ./tools/benchmark.sh overwrite\n\nelse\n  echo Restoring from backup\n\n  rm -rf $db_dir\n\n  if [ ! -d ${db_dir}.bak ]; then\n    echo Database backup does not exist at ${db_dir}.bak\n    exit -1\n  fi\n\n  echo Restore database from ${db_dir}.bak\n  cp -p -r ${db_dir}.bak $db_dir\n\n  if [[ $db_dir != $wal_dir ]]; then\n    rm -rf $wal_dir\n\n    if [ ! -d ${wal_dir}.bak ]; then\n      echo WAL backup does not exist at ${wal_dir}.bak\n      exit -1\n    fi\n\n    echo Restore WAL from ${wal_dir}.bak\n    cp -p -r ${wal_dir}.bak $wal_dir\n  fi\nfi\n\nif [[ $save_setup != 0 ]]; then\n  echo Save database to ${db_dir}.bak\n  cp -p -r $db_dir ${db_dir}.bak\n\n  if [[ $db_dir != $wal_dir ]]; then\n    echo Save WAL to ${wal_dir}.bak\n    cp -p -r $wal_dir ${wal_dir}.bak\n  fi\nfi\n\n###### Read-only tests\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  # Test 4: random read\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr ./tools/benchmark.sh readrandom\n\n  # Test 5: random range scans\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr NUM_NEXTS_PER_SEEK=$nps \\\n    ./tools/benchmark.sh fwdrange\n\n  # Test 6: random reverse range scans\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr NUM_NEXTS_PER_SEEK=$nps \\\n    ./tools/benchmark.sh revrange\ndone\n\n###### Non read-only tests\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  # Test 7: overwrite with sync=0\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$fg_mbwps \\\n    DB_BENCH_NO_SYNC=1 ./tools/benchmark.sh overwrite\n\n  if [[ $skip_low_pri_tests != 1 ]]; then\n    # Test 8: overwrite with sync=1\n    env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$fg_mbwps \\\n      ./tools/benchmark.sh overwrite\n  fi\n\n  # Test 9: random update with sync=0\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr DB_BENCH_NO_SYNC=1 \\\n      ./tools/benchmark.sh updaterandom\n\n  if [[ $skip_low_pri_tests != 1 ]]; then\n    # Test 10: random update with sync=1\n   env $ARGS DURATION=$duration NUM_THREADS=$num_thr ./tools/benchmark.sh updaterandom\n  fi\n\n  # Test 11: random read while writing\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n    DB_BENCH_NO_SYNC=1 ./tools/benchmark.sh readwhilewriting\n\n  # Test 12: range scan while writing\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n    DB_BENCH_NO_SYNC=1 NUM_NEXTS_PER_SEEK=$nps ./tools/benchmark.sh fwdrangewhilewriting\n\n  # Test 13: reverse range scan while writing\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n    DB_BENCH_NO_SYNC=1 NUM_NEXTS_PER_SEEK=$nps ./tools/benchmark.sh revrangewhilewriting\ndone\n\n###### Merge tests\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  # Test 14: random merge with sync=0\n  env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$fg_mbwps \\\n    DB_BENCH_NO_SYNC=1 ./tools/benchmark.sh mergerandom\n\n  if [[ $skip_low_pri_tests != 1 ]]; then\n    # Test 15: random merge with sync=1\n    env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$fg_mbwps \\\n      ./tools/benchmark.sh mergerandom\n\n    # Test 16: random read while merging \n    env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n      DB_BENCH_NO_SYNC=1 ./tools/benchmark.sh readwhilemerging\n\n    # Test 17: range scan while merging \n    env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n      DB_BENCH_NO_SYNC=1 NUM_NEXTS_PER_SEEK=$nps ./tools/benchmark.sh fwdrangewhilemerging\n\n    # Test 18: reverse range scan while merging \n    env $ARGS DURATION=$duration NUM_THREADS=$num_thr MB_WRITE_PER_SEC=$bg_mbwps \\\n      DB_BENCH_NO_SYNC=1 NUM_NEXTS_PER_SEEK=$nps ./tools/benchmark.sh revrangewhilemerging\n  fi\ndone\n\n###### Universal compaction tests.\n\n# Use a single thread to reduce the variability in the benchmark.\nenv $ARGS COMPACTION_TEST=1 NUM_THREADS=1 ./tools/benchmark.sh universal_compaction\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo bulkload > $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep bulkload $output_dir/report.txt >> $output_dir/report2.txt\nfi\n\necho fillseq_wal_disabled >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep fillseq.wal_disabled $output_dir/report.txt >> $output_dir/report2.txt\n\necho fillseq_wal_enabled >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep fillseq.wal_enabled $output_dir/report.txt >> $output_dir/report2.txt\n\necho overwrite sync=0 >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep overwrite $output_dir/report.txt | grep \\.s0  >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo overwrite sync=1 >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep overwrite $output_dir/report.txt | grep \\.s1  >> $output_dir/report2.txt\nfi\n\necho updaterandom sync=0 >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep updaterandom $output_dir/report.txt | grep \\.s0 >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo updaterandom sync=1 >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep updaterandom $output_dir/report.txt | grep \\.s1 >> $output_dir/report2.txt\nfi\n\necho mergerandom sync=0 >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep mergerandom $output_dir/report.txt | grep \\.s0 >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo mergerandom sync=1 >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep mergerandom $output_dir/report.txt | grep \\.s1 >> $output_dir/report2.txt\nfi\n\necho readrandom >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep readrandom $output_dir/report.txt  >> $output_dir/report2.txt\n\necho fwdrange >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep fwdrange\\.t $output_dir/report.txt >> $output_dir/report2.txt\n\necho revrange >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep revrange\\.t $output_dir/report.txt >> $output_dir/report2.txt\n\necho readwhile >> $output_dir/report2.txt >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep readwhilewriting $output_dir/report.txt >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo readwhile >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep readwhilemerging $output_dir/report.txt >> $output_dir/report2.txt\nfi\n\necho fwdreadwhilewriting >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep fwdrangewhilewriting $output_dir/report.txt >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo fwdreadwhilemerging >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep fwdrangewhilemerg $output_dir/report.txt >> $output_dir/report2.txt\nfi\n\necho revreadwhilewriting >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep revrangewhilewriting $output_dir/report.txt >> $output_dir/report2.txt\n\nif [[ $skip_low_pri_tests != 1 ]]; then\n  echo revreadwhilemerging >> $output_dir/report2.txt\n  head -1 $output_dir/report.txt >> $output_dir/report2.txt\n  grep revrangewhilemerg $output_dir/report.txt >> $output_dir/report2.txt\nfi\n\ncat $output_dir/report2.txt\n", "num_lines": 360}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n# REQUIRE: benchmark_leveldb.sh exists in the current directory\n# After execution of this script, log files are generated in $output_dir.\n# report.txt provides a high level statistics\n#\n# This should be used with the LevelDB fork listed here to use additional test options.\n# For more details on the changes see the blog post listed below.\n#   https://github.com/mdcallag/leveldb-1\n#   http://smalldatum.blogspot.com/2015/04/comparing-leveldb-and-rocksdb-take-2.html\n#\n# This should be run from the parent of the tools directory. The command line is:\n#   [$env_vars] tools/run_flash_bench.sh [list-of-threads]\n#\n# This runs a sequence of tests in the following sequence:\n#   step 1) load - bulkload, compact, fillseq, overwrite\n#   step 2) read-only for each number of threads\n#   step 3) read-write for each number of threads\n#\n# The list of threads is optional and when not set is equivalent to \"24\". \n# Were list-of-threads specified as \"1 2 4\" then the tests in steps 2, 3 and\n# 4 above would be repeated for 1, 2 and 4 threads. The tests in step 1 are\n# only run for 1 thread.\n\n# Test output is written to $OUTPUT_DIR, currently /tmp/output. The performance\n# summary is in $OUTPUT_DIR/report.txt. There is one file in $OUTPUT_DIR per\n# test and the tests are listed below.\n#\n# The environment variables are also optional. The variables are:\n#   NKEYS         - number of key/value pairs to load\n#   NWRITESPERSEC - the writes/second rate limit for the *whilewriting* tests.\n#                   If this is too large then the non-writer threads can get\n#                   starved.\n#   VAL_SIZE      - the length of the value in the key/value pairs loaded.\n#                   You can estimate the size of the test database from this,\n#                   NKEYS and the compression rate (--compression_ratio) set\n#                   in tools/benchmark_leveldb.sh\n#   BLOCK_LENGTH  - value for db_bench --block_size\n#   CACHE_BYTES   - the size of the RocksDB block cache in bytes\n#   DATA_DIR      - directory in which to create database files\n#   DO_SETUP      - when set to 0 then a backup of the database is copied from\n#                   $DATA_DIR.bak to $DATA_DIR and the load tests from step 1\n#                   This allows tests from steps 2, 3 to be repeated faster.\n#   SAVE_SETUP    - saves a copy of the database at the end of step 1 to\n#                   $DATA_DIR.bak.\n\n# Size constants\nK=1024\nM=$((1024 * K))\nG=$((1024 * M))\n\nnum_keys=${NKEYS:-$((1 * G))}\nwps=${NWRITESPERSEC:-$((10 * K))}\nvs=${VAL_SIZE:-400}\ncs=${CACHE_BYTES:-$(( 1 * G ))}\nbs=${BLOCK_LENGTH:-4096}\n\n# If no command line arguments then run for 24 threads.\nif [[ $# -eq 0 ]]; then\n  nthreads=( 24 )\nelse\n  nthreads=( \"$@\" )\nfi\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  echo Will run for $num_thr threads\ndone\n\n# Update these parameters before execution !!!\ndb_dir=${DATA_DIR:-\"/tmp/rocksdb/\"}\n\ndo_setup=${DO_SETUP:-1}\nsave_setup=${SAVE_SETUP:-0}\n\noutput_dir=\"${TMPDIR:-/tmp}/output\"\n\nARGS=\"\\\nOUTPUT_DIR=$output_dir \\\nNUM_KEYS=$num_keys \\\nDB_DIR=$db_dir \\\nVALUE_SIZE=$vs \\\nBLOCK_SIZE=$bs \\\nCACHE_SIZE=$cs\"\n\nmkdir -p $output_dir\necho -e \"ops/sec\\tmb/sec\\tusec/op\\tavg\\tp50\\tTest\" \\\n  > $output_dir/report.txt\n\n# Notes on test sequence:\n#   step 1) Setup database via sequential fill followed by overwrite to fragment it.\n#           Done without setting DURATION to make sure that overwrite does $num_keys writes\n#   step 2) read-only tests for all levels of concurrency requested\n#   step 3) non read-only tests for all levels of concurrency requested\n\n###### Setup the database\n\nif [[ $do_setup != 0 ]]; then\n  echo Doing setup\n\n  # Test 2a: sequential fill with large values to get peak ingest\n  #          adjust NUM_KEYS given the use of larger values\n  env $ARGS BLOCK_SIZE=$((1 * M)) VALUE_SIZE=$((32 * K)) NUM_KEYS=$(( num_keys / 64 )) \\\n       ./tools/benchmark_leveldb.sh fillseq\n\n  # Test 2b: sequential fill with the configured value size\n  env $ARGS ./tools/benchmark_leveldb.sh fillseq\n\n  # Test 3: single-threaded overwrite\n  env $ARGS NUM_THREADS=1 DB_BENCH_NO_SYNC=1 ./tools/benchmark_leveldb.sh overwrite\n\nelse\n  echo Restoring from backup\n\n  rm -rf $db_dir\n\n  if [ ! -d ${db_dir}.bak ]; then\n    echo Database backup does not exist at ${db_dir}.bak\n    exit -1\n  fi\n\n  echo Restore database from ${db_dir}.bak\n  cp -p -r ${db_dir}.bak $db_dir\nfi\n\nif [[ $save_setup != 0 ]]; then\n  echo Save database to ${db_dir}.bak\n  cp -p -r $db_dir ${db_dir}.bak\nfi\n\n###### Read-only tests\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  # Test 4: random read\n  env $ARGS NUM_THREADS=$num_thr ./tools/benchmark_leveldb.sh readrandom\n\ndone\n\n###### Non read-only tests\n\nfor num_thr in \"${nthreads[@]}\" ; do\n  # Test 7: overwrite with sync=0\n  env $ARGS NUM_THREADS=$num_thr DB_BENCH_NO_SYNC=1 \\\n    ./tools/benchmark_leveldb.sh overwrite\n\n  # Test 8: overwrite with sync=1\n  # Not run for now because LevelDB db_bench doesn't have an option to limit the\n  # test run to X seconds and doing sync-per-commit for --num can take too long.\n  # env $ARGS NUM_THREADS=$num_thr ./tools/benchmark_leveldb.sh overwrite\n\n  # Test 11: random read while writing\n  env $ARGS NUM_THREADS=$num_thr WRITES_PER_SECOND=$wps \\\n    ./tools/benchmark_leveldb.sh readwhilewriting\n\ndone\n\necho bulkload > $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep bulkload $output_dir/report.txt >> $output_dir/report2.txt\necho fillseq >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep fillseq $output_dir/report.txt >> $output_dir/report2.txt\necho overwrite sync=0 >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep overwrite $output_dir/report.txt | grep \\.s0  >> $output_dir/report2.txt\necho overwrite sync=1 >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep overwrite $output_dir/report.txt | grep \\.s1  >> $output_dir/report2.txt\necho readrandom >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep readrandom $output_dir/report.txt  >> $output_dir/report2.txt\necho readwhile >> $output_dir/report2.txt >> $output_dir/report2.txt\nhead -1 $output_dir/report.txt >> $output_dir/report2.txt\ngrep readwhilewriting $output_dir/report.txt >> $output_dir/report2.txt\n\ncat $output_dir/report2.txt\n", "num_lines": 176}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# A shell script to verify DB generated by generate_random_db.sh cannot opened and read correct data.\n# ./ldb needs to be avaible to be executed.\n#\n# Usage: <SCRIPT> <DB Path>\n\nscriptpath=`dirname $BASH_SOURCE`\nif [ \"$#\" -lt 2 ]; then\n  echo \"usage: $BASH_SOURCE <db_directory> <compare_base_db_directory> [dump_file_name] [if_try_load_options] [if_ignore_unknown_options]\"\n  exit 1\nfi\n\ndb_dir=$1\nbase_db_dir=$2\ndump_file_name=${3:-\"dump_file.txt\"}\ntry_load_options=${4:-\"1\"}\nignore_unknown_options=${5:-\"0\"}\ndb_dump=$db_dir\"/\"$dump_file_name\nbase_db_dump=$base_db_dir\"/\"$dump_file_name\nextra_params=\n\nif [ \"$try_load_options\" = \"0\" ]; then\n extra_params=\" --try_load_options=false\"\nelif [ \"$try_load_options\" = \"1\" ]; then\n extra_params=\" --try_load_options=true\"\nfi\n\nif [ \"$ignore_unknown_options\" = \"1\" ]; then\n extra_params=\"$extra_params --ignore_unknown_options\"\nfi\n\nset -e\necho == Dumping data from $db_dir to $db_dump\n./ldb dump --db=$db_dir $extra_params > $db_dump\n\necho == Dumping data from $base_db_dir to $base_db_dump\n./ldb dump --db=$base_db_dir $extra_params > $base_db_dump\n\ndiff $db_dump $base_db_dump\n", "num_lines": 42}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n#\n\nif [ \"$#\" -lt 3 ]; then\n  echo \"usage: $BASH_SOURCE <input_data_path> <DB Path> <extern SST dir>\"\n  exit 1\nfi\n\ninput_data_dir=$1\ndb_dir=$2\nextern_sst_dir=$3\nrm -rf $db_dir\nmkdir -p $extern_sst_dir\n\nset -e\n\nn=0\n\nfor f in `find $input_data_dir -name sorted_data*`\ndo\n  echo == Writing external SST file $f to $extern_sst_dir/extern_sst${n}\n  ./ldb --db=$db_dir --create_if_missing write_extern_sst $extern_sst_dir/extern_sst${n} < $f\n  let \"n = n + 1\"\ndone\n", "num_lines": 27}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.\n#\n# A shell script to run a batch of pysims and combine individual pysim output files.\n#\n# Usage: bash block_cache_pysim.sh trace_file_path result_dir downsample_size warmup_seconds max_jobs\n# trace_file_path: The file path that stores the traces.\n# result_dir: The directory to store pysim results. The output files from a pysim is stores in result_dir/ml\n# downsample_size: The downsample size used to collect the trace.\n# warmup_seconds: The number of seconds used for warmup.\n# max_jobs: The max number of concurrent pysims to run.\n\n# Install required packages to run simulations.\n# sudo dnf install -y numpy scipy python-matplotlib ipython python-pandas sympy python-nose atlas-devel\nulimit -c 0\n\nif [ $# -ne 5 ]; then\n  echo \"Usage: ./block_cache_pysim.sh trace_file_path result_dir downsample_size warmup_seconds max_jobs\"\n  exit 0\nfi\n\ntrace_file=\"$1\"\nresult_dir=\"$2\"\ndownsample_size=\"$3\"\nwarmup_seconds=\"$4\"\nmax_jobs=\"$5\"\nmax_num_accesses=100000000\ncurrent_jobs=1\n\nml_tmp_result_dir=\"$result_dir/ml\"\nrm -rf \"$ml_tmp_result_dir\"\nmkdir -p \"$result_dir\"\nmkdir -p \"$ml_tmp_result_dir\"\n\n# Report miss ratio in the trace.\ncurrent_jobs=$(ps aux | grep pysim | grep python | grep -cv grep)\nfor cf_name in \"all\"\ndo\nfor cache_size in \"1G\" \"2G\" \"4G\" \"8G\" \"16G\" #\"12G\" \"16G\" \"1T\"\ndo\nfor cache_type in \"opt\" \"lru\" \"pylru\" \"pycctbbt\" \"pyhb\" \"ts\" \"trace\" \"lru_hybrid\"  #\"pycctblevelbt\" #\"lru_hybridn\" \"opt\" #\"pylru\" \"pylru_hybrid\" \"pycctbbt\" \"pycccfbt\" \"trace\"\ndo\n    if [[ $cache_type == \"trace\" && $cache_size != \"16G\" ]]; then\n      # We only need to collect miss ratios observed in the trace once.\n      continue\n    fi\n    while [ \"$current_jobs\" -ge \"$max_jobs\" ]\n    do\n      sleep 10\n      echo \"Waiting jobs to complete. Number of running jobs: $current_jobs\"\n      current_jobs=$(ps aux | grep pysim | grep python | grep -cv grep)\n      echo \"Waiting jobs to complete. Number of running jobs: $current_jobs\"\n    done\n    output=\"log-ml-$cache_type-$cache_size-$cf_name\"\n    echo \"Running simulation for $cache_type, cache size $cache_size, and cf_name $cf_name. Number of running jobs: $current_jobs. \"\n    nohup python block_cache_pysim.py \"$cache_type\" \"$cache_size\" \"$downsample_size\" \"$warmup_seconds\" \"$trace_file\" \"$ml_tmp_result_dir\" \"$max_num_accesses\" \"$cf_name\" >& \"$ml_tmp_result_dir/$output\" &\n    current_jobs=$((current_jobs+1))\ndone\ndone\ndone\n\n# Wait for all jobs to complete.\nwhile [ $current_jobs -gt 0 ]\ndo\n  sleep 10\n  echo \"Waiting jobs to complete. Number of running jobs: $current_jobs\"\n  current_jobs=$(ps aux | grep pysim | grep python | grep -cv grep)\n  echo \"Waiting jobs to complete. Number of running jobs: $current_jobs\"\ndone\n\necho \"Combine individual pysim output files\"\n\nrm -rf \"$result_dir/ml_*\"\nfor header in \"header-\" \"data-\"\ndo\nfor fn in \"$ml_tmp_result_dir\"/*\ndo\n  sum_file=\"\"\n  time_unit=\"\"\n  capacity=\"\"\n  target_cf_name=\"\"\n  if [[ $fn == *\"timeline\"* ]]; then\n    tmpfn=\"$fn\"\n    IFS='-' read -ra elements <<< \"$tmpfn\"\n    time_unit_index=0\n    capacity_index=0\n    for i in \"${elements[@]}\"\n    do\n       if [[ $i == \"timeline\" ]]; then\n         break\n       fi\n       time_unit_index=$((time_unit_index+1))\n    done\n    time_unit_index=$((time_unit_index+1))\n    capacity_index=$((time_unit_index+2))\n    target_cf_name_index=$((time_unit_index+3))\n    time_unit=\"${elements[$time_unit_index]}_\"\n    capacity=\"${elements[$capacity_index]}_\"\n    target_cf_name=\"${elements[$target_cf_name_index]}_\"\n  fi\n\n  if [[ $fn == *\"${header}ml-policy-timeline\"* ]]; then\n    sum_file=\"$result_dir/ml_${target_cf_name}${capacity}${time_unit}policy_timeline\"\n  fi\n  if [[ $fn == *\"${header}ml-policy-ratio-timeline\"* ]]; then\n    sum_file=\"$result_dir/ml_${target_cf_name}${capacity}${time_unit}policy_ratio_timeline\"\n  fi\n  if [[ $fn == *\"${header}ml-miss-timeline\"* ]]; then\n    sum_file=\"$result_dir/ml_${target_cf_name}${capacity}${time_unit}miss_timeline\"\n  fi\n  if [[ $fn == *\"${header}ml-miss-ratio-timeline\"* ]]; then\n    sum_file=\"$result_dir/ml_${target_cf_name}${capacity}${time_unit}miss_ratio_timeline\"\n  fi\n  if [[ $fn == *\"${header}ml-mrc\"* ]]; then\n    tmpfn=\"$fn\"\n    IFS='-' read -ra elements <<< \"$tmpfn\"\n    target_cf_name=${elements[-1]}\n    sum_file=\"${result_dir}/ml_${target_cf_name}_mrc\"\n  fi\n  if [[ $fn == *\"${header}ml-avgmb\"* ]]; then\n    tmpfn=\"$fn\"\n    IFS='-' read -ra elements <<< \"$tmpfn\"\n    time_unit=${elements[3]}\n    target_cf_name=${elements[-1]}\n    sum_file=\"${result_dir}/ml_${time_unit}_${target_cf_name}_avgmb\"\n  fi\n  if [[ $fn == *\"${header}ml-p95mb\"* ]]; then\n    tmpfn=\"$fn\"\n    IFS='-' read -ra elements <<< \"$tmpfn\"\n    time_unit=${elements[3]}\n    target_cf_name=${elements[-1]}\n    sum_file=\"${result_dir}/ml_${time_unit}_${target_cf_name}_p95mb\"\n  fi\n  if [[ $sum_file == \"\" ]]; then\n    continue\n  fi\n  if [[ $header == \"header-\" ]]; then\n    if [ -e \"$sum_file\" ]; then\n      continue\n    fi\n  fi\n  cat \"$fn\" >> \"$sum_file\"\ndone\ndone\n\necho \"Done\"\nfor fn in $result_dir/*\ndo\n  if [[ $fn == *\"_mrc\" || $fn == *\"_avgmb\" || $fn == *\"_p95mb\" ]]; then\n    # Sort MRC file by cache_type and cache_size.\n    tmp_file=\"$result_dir/tmp_mrc\"\n    cat \"$fn\" | sort -t ',' -k1,1 -k4,4n > \"$tmp_file\"\n    cat \"$tmp_file\" > \"$fn\"\n    rm -rf \"$tmp_file\"\n  fi\ndone\n", "num_lines": 157}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nset -e\nset -o pipefail\n\nif [ \"$1\" ]; then\n  # Target file specified on command line\n  TARGET=\"$1\"\nelse\n  # Interactively choose a group and file name\n  DIRS=\"`find unreleased_history/ -mindepth 1 -maxdepth 1 -type d`\"\n  echo \"Choose a group for new release note:\"\n  echo \"$DIRS\" | grep -nEo '[^/]+$'\n  echo -n \"Enter a number: \"\n  while [ ! \"$DIRNUM\" ]; do read -r DIRNUM; done\n  DIR=\"$(echo \"$DIRS\" | head -n \"$DIRNUM\" | tail -1)\"\n  echo \"Choose a file name for new release note (e.g. improved_whatever.md):\"\n  while [ ! \"$FNAME\" ]; do read -re FNAME; done\n  # Replace spaces with underscores\n  TARGET=\"$(echo \"$DIR/$FNAME\" | tr ' ' '_')\"\nfi\n\n# Edit/create the file\n${EDITOR:-nano} \"$TARGET\"\n# Add to version control (easy to forget!)\ngit add \"$TARGET\"\n", "num_lines": 28}
{"repo_name": "rocksdb", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nset -e\n\nif [ ! -d unreleased_history ]; then\n  echo \"Can't find unreleased_history/ directory\"\n  exit 1\nfi\n\nGIT_PATHS=\"unreleased_history/ HISTORY.md\"\nif [ ! \"$DRY_RUN\" ]; then\n  # Check for uncommitted changes\n  UNCOMMITTED=\"$(git diff -- $GIT_PATHS)\"\n  if [ \"$UNCOMMITTED\" ]; then\n    echo 'Uncommitted changes to files to be modified. Please commit first to'\n    echo 'ensure a clean revert path. You can always `git commit -a --amend`'\n    echo 'to add more changes to your commit.'\n    exit 2\n  fi\nfi\n\n# Add first part of existing HISTORY file to new version\nawk '{ print } /NOTE/ { exit(0) }' < HISTORY.md > HISTORY.new\n\n# And a blank line separator\necho >> HISTORY.new\n\n# Add new version header\nawk '/#define ROCKSDB_MAJOR/ { major = $3 }\n     /#define ROCKSDB_MINOR/ { minor = $3 }\n     /#define ROCKSDB_PATCH/ { patch = $3 }\n     END { printf \"## \" major \".\" minor \".\" patch }' < include/rocksdb/version.h >> HISTORY.new\necho \" (`date +%x`)\" >> HISTORY.new\n\nfunction process_file () {\n  # use awk to correct extra or missing newlines, missing '* ' on first line\n  awk '/./ { if (notfirstline || $1 == \"*\") print;\n             else print \"* \" $0;\n             notfirstline=1; }' < $1 >> HISTORY.new\n  echo git rm $1\n  if [ ! \"$DRY_RUN\" ]; then\n    git rm $1\n  fi\n}\n\nPROCESSED_DIRECTORIES=\"\"\n\nfunction process_dir () {\n  PROCESSED_DIRECTORIES=\"$PROCESSED_DIRECTORIES $1\"\n  # ls will sort the files, including the permanent header file\n  FILES=\"$(ls unreleased_history/$1/)\"\n  if [ \"$FILES\" ]; then\n    echo \"### $2\" >> HISTORY.new\n    for FILE in $FILES; do\n      process_file \"unreleased_history/$1/$FILE\"\n    done\n    echo >> HISTORY.new\n    echo \"Saved entries from $1\"\n  else\n    echo \"Nothing new in $1\"\n  fi\n}\n\n# Process dirs and files\nprocess_dir new_features \"New Features\"\nprocess_dir public_api_changes \"Public API Changes\"\nprocess_dir behavior_changes \"Behavior Changes\"\nprocess_dir bug_fixes \"Bug Fixes\"\nprocess_dir performance_improvements \"Performance Improvements\"\n\n# Check for unexpected files or dirs at top level. process_dir/process_file\n# will deal with contents of these directories\nEXPECTED_REGEX=\"[^/]*[.]sh|README[.]txt|$(echo $PROCESSED_DIRECTORIES | tr ' ' '|')\"\nplatform=`uname`\nif [ $platform = 'Darwin' ]; then\n  UNEXPECTED=\"$(find -E unreleased_history -mindepth 1 -maxdepth 1 -not -regex \"[^/]*/($EXPECTED_REGEX)\")\"\nelse\n  UNEXPECTED=\"$(find unreleased_history/ -mindepth 1 -maxdepth 1 -regextype egrep -not -regex \"[^/]*/($EXPECTED_REGEX)\")\"\nfi\nif [ \"$UNEXPECTED\" ]; then\n  echo \"Unexpected files I don't know how to process:\"\n  echo \"$UNEXPECTED\"\n  rm HISTORY.new\n  exit 3\nfi\n\n# Add rest of existing HISTORY file to new version (collapsing newlines)\nawk '/./ { if (note) pr=1 }\n     /NOTE/ { note=1 }\n     { if (pr) print }' < HISTORY.md >> HISTORY.new\n\nif [ \"$DRY_RUN\" ]; then\n  echo '==========================================='\n  diff -U3 HISTORY.md HISTORY.new || true\n  rm HISTORY.new\nelse\n  mv HISTORY.new HISTORY.md\n  echo \"Done. Revert command: git checkout HEAD -- $GIT_PATHS\"\nfi\n", "num_lines": 101}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nTOOLCHAIN_DIR=/opt/rh/devtoolset-8/root/usr/bin\nif [[ -d \"$TOOLCHAIN_DIR\" ]]; then\n    PATH=\"$TOOLCHAIN_DIR:$PATH\"\nfi\n\nSCRIPT_DIR=$(dirname \"${BASH_SOURCE[0]}\")\nGETDEPS_PATHS=(\n    \"$SCRIPT_DIR/build/fbcode_builder/getdeps.py\"\n    \"$SCRIPT_DIR/../../opensource/fbcode_builder/getdeps.py\"\n)\nfor getdeps in \"${GETDEPS_PATHS[@]}\"; do\n    if [[ -x \"$getdeps\" ]]; then\n        exec \"$getdeps\" build eden \"$@\"\n    fi\ndone\necho \"Could not find getdeps.py\" >&2\nexit 1\n", "num_lines": 24}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This file removes all internal-only files and deletes @fb-only commented lines from code\n# This is only used in our internal CI tests, the actual removing when syncing to GitHub is done by shipit.\n\ncd \"$(dirname \"$0\")\" || exit\n\nfunction findAllSourceFiles() {\n  find . \\\n    \\( -name '*.ts' -o -name '*.tsx' -o -name '*.js' \\) \\\n    -type f \\\n    \\( -not -path '*/node_modules/*' -not -path '*/dist/*' -not -path '*/build/*' -not -path '.vscode-build' -not -path '*/coverage/*' \\) \\\n    -print0\n}\n\necho \"replacing all fb-only comments...\"\n\nfbOnlyRegex='s/^([[:space:]]*).* \\/\\/ @fb-only/\\1\\/\\/ @fb-only/g'\nOS=$(uname)\nif [ \"$OS\" = 'Darwin' ]; then\n  # macOS ships with BSD version of sed, where -i '' is required to not create backup files,\n  # but -i '' doesn't work on linux.\n  findAllSourceFiles | xargs -0 sed -i '' -r \"$fbOnlyRegex\"\nelse\n  findAllSourceFiles | xargs -0 sed -i'' -r \"$fbOnlyRegex\"\nfi\n\necho \"deleting all facebook/ directories...\"\nfind . -path '*/facebook' -type d -print0 | xargs -0 rm -rf\n", "num_lines": 34}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"$0\" )\" &> /dev/null && pwd )\n# Facilitate redefining NODE in terms of SCRIPT_DIR via a regex.\nNODE=node\n\nif [ ! -x \"$(command -v $NODE)\" ]; then\n  # shellcheck disable=SC2016\n  echo 'ERROR: `node` is required to run Interactive Smartlog, but it was not'\n  # shellcheck disable=SC2016\n  echo 'found on the $PATH. For information on installing Node.js, see:'\n  echo 'https://nodejs.dev/en/learn/how-to-install-nodejs/'\n  exit 1\nfi\n\n\"$NODE\" \"$SCRIPT_DIR/isl-server/dist/run-proxy.js\" \"$@\"\n", "num_lines": 21}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\" || exit\n\n# Tauri doesn't like being run with the node configured by our repo's .yarnrc\n# Instead of yarn tauri dev, we have to run it from node_modules.\n# Additionally, in dev mode, we also want to use a dev run of the ISL server.\n# We run this by invoking run-proxy directly rather than `yarn serve`, since\n# we're not in the isl-server directory.\n# You can pass additional arguments to run-proxy, but not all of them make sense,\n# such as --foreground.\n\n./node_modules/.bin/tauri dev -- -- node ../../isl-server/dist/run-proxy.js --dev \"$@\"\n", "num_lines": 18}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\nname=\"$1\"\ngh release view \"$name\" || gh release create --prerelease --title \"$name\" \"$name\"\n", "num_lines": 10}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\nset -e\n\nmax_attempts=4\nattempt=1\n\nuntil \"$@\"\ndo\n  if (( attempt == max_attempts ))\n  then\n    echo \"Failed after $max_attempts attempts\"\n    exit 1\n  fi\n\n  sleep 5\n  : $(( attempt++ ))\ndone\n", "num_lines": 24}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nDIR=$(dirname -- \"$0\")\nVERSION=$(<\"$DIR\"/../SAPLING_VERSION)\n\n# Create the commit info using either sl or git, whichever way we cloned this repo\nif ! command -v sl &> /dev/null; then\n  COMMIT_INFO=$(git -c \"core.abbrev=8\" show -s \"--format=%cd+%h\" \"--date=format:%Y%m%d-%H%M%S\")\nelse\n  COMMIT_INFO=$(sl log --rev . --template '{date(date, \"%Y%m%d-%H%M%S\")}+{shortest(node, 8)}')\nfi\n\necho \"$VERSION\".\"$COMMIT_INFO\"\n", "num_lines": 18}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Verifies a Sapling .deb on Ubuntu 20.04 or 22.04.\n#\n# This script takes the URL to a .deb from the Releases page such as:\n#\n#     https://github.com/bolinfest/eden/releases/download/20220831-124726-b53cb8ea/sapling_0.0-20220831.124726.b53cb8ea_amd64.Ubuntu20.04.deb\n#\n# and creates a barebones Docker container to install and run it.\n#\n# If the file has already been download locally (perhaps from a private\n# GitHub repo?), then the local path can also be used as an argument:\n#\n#     verify_release.sh ~/Downloads/sapling_0.0-20220831.124726.b53cb8ea_amd64.Ubuntu20.04.deb\n#\n# Note that a sapling.deb should not assume the user has `apt install`'d\n# anything else.\n\nset -e\nset -x\n\nFILE_OR_URL=\"$1\"\necho \"$FILE_OR_URL\"\n\ntmp_dir=$(mktemp -d -t ci-XXXXXXXXXX)\necho \"$tmp_dir\"\ncd \"$tmp_dir\"\n\nif [[ \"$FILE_OR_URL\" == *\"Ubuntu20.04.deb\" ]]; then\n  UBUNTU_VERSION=20.04\nelse\n  if [[ \"$FILE_OR_URL\" == *\"Ubuntu22.04.deb\" ]]; then\n    UBUNTU_VERSION=22.04\n  else\n    echo \"could not determine Ubuntu version from arg '${FILE_OR_URL}'\" >> /dev/stderr\n    exit 1\n  fi\nfi\n\nif [ ! -f \"$FILE_OR_URL\" ]; then\n  curl --location -O \"$FILE_OR_URL\"\nelse\n  cp \"$FILE_OR_URL\" .\nfi\n\ncat > Dockerfile <<EOF\nFROM ubuntu:${UBUNTU_VERSION}\nCOPY *.deb /root/sapling.deb\n\n# https://serverfault.com/a/1016972 to ensure installing tzdata does not\n# result in a prompt that hangs forever.\nARG DEBIAN_FRONTEND=noninteractive\nENV TZ=Etc/UTC\n\nRUN apt update -y\nRUN apt install -y /root/sapling.deb\nRUN which sl\nRUN sl clone https://github.com/bolinfest/opensnoop-native\nRUN cd /opensnoop-native && sl isl --no-open --json\nEOF\n\nIMAGE_ID=$(echo $RANDOM | shasum | head -c 8)\nIMAGE_NAME=\"sapling-test-${IMAGE_ID}\"\ndocker build --progress=plain -t \"$IMAGE_NAME\" .\ndocker run -it \"$IMAGE_NAME\" /bin/bash\n", "num_lines": 70}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\nNAME=$1\nif [[ \"$NAME\" == facebook/* ]]; then\n    SUBDIR=\"/facebook\"\n    # Strip facebook prefix\n    NAME=\"${NAME#*/}\"\nelse\n    SUBDIR=\"\"\nfi\nshift 1\nfbsource=$(hg root)\n\nset -x\n\"$fbsource/buck-out/v2/gen/fbcode/eden/mononoke/tests/integration/integration_runner_real.par\" \"$fbsource/buck-out/v2/gen/fbcode/eden/mononoke/tests/integration$SUBDIR/$NAME-manifest.json\" \"$@\"\n", "num_lines": 22}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\nBUCK=buck2\n\nif [[ \"$1\" == facebook/* ]]; then\n    # Strip facebook prefix\n    TARGET=\"/facebook:${1#*/}-manifest\"\nelse\n    TARGET=\":$1-manifest\"\nfi\n\nshift\n\nset -x\n\n$BUCK build \"$@\" //eden/mononoke/tests/integration:integration_runner_real \"//eden/mononoke/tests/integration$TARGET\" \"//eden/mononoke/tests/integration${TARGET}[deps]\"\n", "num_lines": 23}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# Library routines for generating or interacting with commits\n\n# shellcheck source=fbcode/eden/mononoke/tests/integration/library.sh\n. \"${TEST_FIXTURES}/library.sh\"\n\nfunction whereami() {\n  hg log -r . -T \"{node}\"\n}\n\nfunction add_triangle_merge_commits_and_push() {\n  # Add multiple merge commits in a triangle like shape:\n  # o\n  # |\\\n  # o o\n  # | |\\\n  # o o o\n  # | |/\n  # o o\n  # |/\n  # o\n  # The first argument represents how many merges to add.\n  # The second argument is optional and represents a unique identifier for the\n  # current invocation of the function.\n  count=\"$1\"\n  shift\n  local seed tomerge topush st commit i j\n  seed=${1:-$(wherami)}\n  for i in $(seq 1 \"$count\"); do\n    echo \"i=${i}\" >> \"${seed}_${i}\"\n    hg ci -Am \"${seed}: base branch ${i}\"\n  done\n  tomerge=\"$(whereami)\"\n  topush=()\n  for i in $(seq 1 \"$count\"); do\n    hg prev\n    st=\"$(whereami)\"\n    for j in $(seq 1 $((2 * i - 1))); do\n      echo \"j=$j\" >> \"${seed}_${i}_${j}\"\n      hg ci -Am \"${seed}: commit ${j} for branch ${i}\"\n      if [ \"${i}\" == \"${count}\" ]; then\n        topush+=( \"$(whereami)\" )\n      fi\n    done\n    hg merge -r \"${tomerge}\"\n    hg commit -Am \"${seed}: merge branch ${i}\"\n    tomerge=\"$(whereami)\"\n    hg co -r \"${st}\"\n  done\n  topush+=( \"$tomerge\" )\n\n  # simulate updating master with several single parents commits then a merge\n  for commit in \"${topush[@]}\"; do\n    hg co \"${commit}\"\n    hgmn push -r . --to master_bookmark --pushvar NON_FAST_FORWARD=true\n  done\n}\n", "num_lines": 63}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# shellcheck source=fbcode/eden/mononoke/tests/integration/library.sh\n. \"${TEST_FIXTURES}/library.sh\"\n\nfunction verify_wc() {\n   local large_repo_commit\n   large_repo_commit=\"$1\"\n   \"$MONONOKE_ADMIN\" \\\n     \"${CACHE_ARGS[@]}\" \\\n     \"${COMMON_ARGS[@]}\" --log-level ERROR \\\n     --mononoke-config-path  \"$TESTTMP\"/mononoke-config \\\n     --source-repo-id=\"$REPOIDLARGE\" --target-repo-id=\"$REPOIDSMALL\" \\\n     crossrepo verify-wc \"$large_repo_commit\"\n}\n\nfunction validate_commit_sync() {\n  local entry_id\n  entry_id=\"$1\"\n  shift\n  \"$COMMIT_VALIDATOR\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" --debug --repo-id \"$REPOIDLARGE\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --master-bookmark=master_bookmark \\\n    once --entry-id \"$entry_id\" \"$@\"\n}\n\nfunction large_small_megarepo_config() {\ncat >> \"$TESTTMP/mononoke-config/common/commitsyncmap.toml\" <<EOF\n[megarepo_test]\nlarge_repo_id = 0\ncommon_pushrebase_bookmarks = [\"master_bookmark\"]\n [[megarepo_test.small_repos]]\n repoid = 1\n bookmark_prefix = \"bookprefix/\"\n default_action = \"prepend_prefix\"\n default_prefix = \"smallrepofolder\"\n direction = \"large_to_small\"\n    [megarepo_test.small_repos.mapping]\n    \"non_path_shifting\" = \"non_path_shifting\"\nEOF\n\n  if [ -n \"$COMMIT_SYNC_CONF\" ]; then\n    cat > \"$COMMIT_SYNC_CONF/current\" << EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n      \"large_repo_id\": 0,\n      \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n      \"small_repos\": [\n        {\n          \"repoid\": 1,\n          \"bookmark_prefix\": \"bookprefix/\",\n          \"default_action\": \"prepend_prefix\",\n          \"default_prefix\": \"smallrepofolder\",\n          \"direction\": \"large_to_small\",\n          \"mapping\": {\n            \"non_path_shifting\": \"non_path_shifting\"\n          }\n        }\n      ],\n      \"version_name\": \"test_version\"\n    }\n  }\n}\nEOF\n\n    cat > \"$COMMIT_SYNC_CONF/all\" << EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n      \"versions\": [\n        {\n          \"large_repo_id\": 0,\n          \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n          \"small_repos\": [\n            {\n              \"repoid\": 1,\n              \"bookmark_prefix\": \"bookprefix/\",\n              \"default_action\": \"prepend_prefix\",\n              \"default_prefix\": \"smallrepofolder\",\n              \"direction\": \"large_to_small\",\n              \"mapping\": {\n                \"non_path_shifting\": \"non_path_shifting\"\n              }\n            }\n          ],\n          \"version_name\": \"test_version\"\n        }\n      ],\n      \"common\": {\n        \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n        \"large_repo_id\": 0,\n        \"small_repos\": {\n          1: {\n            \"bookmark_prefix\": \"bookprefix/\"\n          }\n        }\n      }\n    }\n  }\n}\nEOF\n\n  fi\n\n\n}\n\nfunction large_small_config() {\n  REPOTYPE=\"blob_files\"\n  INFINITEPUSH_ALLOW_WRITES=true REPOID=0 REPONAME=large-mon setup_common_config \"$REPOTYPE\"\n  INFINITEPUSH_ALLOW_WRITES=true REPOID=1 REPONAME=small-mon setup_common_config \"$REPOTYPE\"\n  large_small_megarepo_config\n}\n\nfunction large_small_setup() {\n  quiet testtool_drawdag -R small-mon <<'EOF'\nS_B\n|\nS_A\n# message: S_A \"pre-move commit\"\n# author: S_A test\n# modify: S_A file.txt \"1\\n\"\n# forget: S_A S_A\n# message: S_B \"first post-move commit\"\n# author: S_B test\n# modify: S_B filetoremove \"1\\n\"\n# bookmark: S_B master_bookmark\n# forget: S_B S_B\nEOF\n\n  export SMALL_MASTER_BONSAI\n  SMALL_MASTER_BONSAI=$S_B\n\n  quiet testtool_drawdag -R large-mon <<'EOF'\nL_C\n|\nL_B\n|\nL_A\n# message: L_A \"pre-move commit\"\n# author: L_A test\n# modify: L_A file.txt \"1\\n\"\n# message: L_B \"move commit\"\n# author: L_B test\n# forget: L_A L_A\n# copy: L_B smallrepofolder/file.txt \"1\\n\" L_A file.txt\n# delete: L_B file.txt\n# forget: L_B L_B\n# message: L_C \"first post-move commit\"\n# author: L_C test\n# modify: L_C smallrepofolder/filetoremove \"1\\n\"\n# bookmark: L_C master_bookmark\n# forget: L_C L_C\nEOF\n\n  export LARGE_MASTER_BONSAI\n  LARGE_MASTER_BONSAI=$L_C\n\n  echo \"Adding synced mapping entry\"\n  export REPOIDLARGE=0\n  export REPOIDSMALL=1\n  add_synced_commit_mapping_entry \"$REPOIDSMALL\" \"$SMALL_MASTER_BONSAI\" \\\n   \"$REPOIDLARGE\" \"$LARGE_MASTER_BONSAI\" \"test_version\"\n\n}\n\nfunction create_large_small_repo() {\n  large_small_config\n  large_small_setup\n}\n\nfunction update_mapping_version {\n  local small_repo_id large_repo_id small_bcs_id large_bcs_id version\n  small_repo_id=\"$1\"\n  small_bcs_id=\"$2\"\n  large_repo_id=\"$3\"\n  large_bcs_id=\"$4\"\n  version=\"$5\"\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" <<EOF\n    REPLACE INTO synced_commit_mapping (small_repo_id, small_bcs_id, large_repo_id, large_bcs_id, sync_map_version_name)\n    VALUES ('$small_repo_id', X'$small_bcs_id', '$large_repo_id', X'$large_bcs_id', '$version');\nEOF\n\n}\n\nfunction update_commit_sync_map_first_option {\n  cat > \"$COMMIT_SYNC_CONF/current\" << EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n      \"large_repo_id\": 0,\n      \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n      \"small_repos\": [\n        {\n          \"repoid\": 1,\n          \"bookmark_prefix\": \"bookprefix/\",\n          \"default_action\": \"prepend_prefix\",\n          \"default_prefix\": \"smallrepofolder_after\",\n          \"direction\": \"large_to_small\",\n          \"mapping\": {\n            \"non_path_shifting\": \"non_path_shifting\"\n          }\n        }\n      ],\n      \"version_name\": \"new_version\"\n    }\n  }\n}\nEOF\n\n  cat > \"$COMMIT_SYNC_CONF/all\" << EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n      \"versions\": [\n        {\n          \"large_repo_id\": 0,\n          \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n          \"small_repos\": [\n            {\n              \"repoid\": 1,\n              \"bookmark_prefix\": \"bookprefix/\",\n              \"default_action\": \"prepend_prefix\",\n              \"default_prefix\": \"smallrepofolder\",\n              \"direction\": \"large_to_small\",\n              \"mapping\": {\n                \"non_path_shifting\": \"non_path_shifting\"\n              }\n            }\n          ],\n          \"version_name\": \"test_version\"\n        },\n      {\n        \"large_repo_id\": 0,\n        \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n        \"small_repos\": [\n          {\n            \"repoid\": 1,\n            \"bookmark_prefix\": \"bookprefix/\",\n            \"default_action\": \"prepend_prefix\",\n            \"default_prefix\": \"smallrepofolder_after\",\n            \"direction\": \"large_to_small\",\n            \"mapping\": {\n              \"non_path_shifting\": \"non_path_shifting\"\n            }\n          }\n        ],\n        \"version_name\": \"new_version\"\n      }\n      ],\n      \"common\": {\n        \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n        \"large_repo_id\": 0,\n        \"small_repos\": {\n          1: {\n            \"bookmark_prefix\": \"bookprefix/\"\n          }\n        }\n      }\n    }\n  }\n}\nEOF\n\n}\n\nfunction update_commit_sync_map_second_option {\n  cat > \"$COMMIT_SYNC_CONF/current\" <<EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n        \"large_repo_id\": 0,\n        \"common_pushrebase_bookmarks\": [\n          \"master_bookmark\"\n        ],\n        \"small_repos\": [\n          {\n            \"repoid\": 1,\n            \"default_action\": \"prepend_prefix\",\n            \"default_prefix\": \"smallrepofolder1\",\n            \"bookmark_prefix\": \"bookprefix1/\",\n            \"mapping\": {\n              \"special\": \"specialsmallrepofolder_after_change\"\n            },\n            \"direction\": \"large_to_small\"\n          }\n        ],\n        \"version_name\": \"TEST_VERSION_NAME_LIVE_V2\"\n    }\n  }\n}\nEOF\n\n  cat > \"$COMMIT_SYNC_CONF/all\" << EOF\n{\n  \"repos\": {\n    \"megarepo_test\": {\n      \"versions\": [\n        {\n          \"large_repo_id\": 0,\n          \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n          \"small_repos\": [\n            {\n              \"repoid\": 1,\n              \"default_action\": \"prepend_prefix\",\n              \"default_prefix\": \"smallrepofolder1\",\n              \"bookmark_prefix\": \"bookprefix1/\",\n              \"mapping\": {\n                \"special\": \"specialsmallrepofolder1\"\n              },\n              \"direction\": \"large_to_small\"\n            }\n          ],\n          \"version_name\": \"TEST_VERSION_NAME_LIVE_V1\"\n        },\n        {\n          \"large_repo_id\": 0,\n          \"common_pushrebase_bookmarks\": [\n            \"master_bookmark\"\n          ],\n          \"small_repos\": [\n            {\n              \"repoid\": 1,\n              \"default_action\": \"prepend_prefix\",\n              \"default_prefix\": \"smallrepofolder1\",\n              \"bookmark_prefix\": \"bookprefix1/\",\n              \"mapping\": {\n                \"special\": \"specialsmallrepofolder_after_change\"\n              },\n              \"direction\": \"large_to_small\"\n            }\n          ],\n          \"version_name\": \"TEST_VERSION_NAME_LIVE_V2\"\n        }\n      ],\n      \"common\": {\n        \"common_pushrebase_bookmarks\": [\"master_bookmark\"],\n        \"large_repo_id\": 0,\n        \"small_repos\": {\n          1: {\n            \"bookmark_prefix\": \"bookprefix1/\"\n          }\n        }\n      }\n    }\n  }\n}\nEOF\n\n}\n\nfunction init_large_small_repo() {\n  create_large_small_repo\n  start_large_small_repo \"$@\"\n  init_local_large_small_clones\n}\n\nfunction init_local_large_small_clones {\n  cd \"$TESTTMP\" || exit 1\n  REPONAME=small-mon hgmn_clone \"mononoke://$(mononoke_address)/small-mon\" small-hg-client --config extensions.remotenames=\n  cat >> small-hg-client/.hg/hgrc <<EOF\n[extensions]\npushrebase =\nEOF\n  REPONAME=large-mon hgmn_clone \"mononoke://$(mononoke_address)/large-mon\" large-hg-client --config extensions.remotenames=\n  cat >> large-hg-client/.hg/hgrc <<EOF\n[extensions]\npushrebase =\nEOF\n}\n\nfunction start_large_small_repo {\n  echo \"Starting Mononoke server\"\n  mononoke \"$@\"\n  wait_for_mononoke\n  # Setting XREPOSYNC allows the user of this fn to set x-repo sync mutable counter instead of the backsync one\n  # This is useful, if the intention is to use x-repo sync instead of backsync after the setup\n  if [[ -v XREPOSYNC ]]; then\n    sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"INSERT INTO mutable_counters (repo_id, name, value) VALUES ($REPOIDLARGE, 'xreposync_from_$REPOIDSMALL', 1)\";\n  else\n    sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"INSERT INTO mutable_counters (repo_id, name, value) VALUES ($REPOIDSMALL, 'backsync_from_$REPOIDLARGE', 1)\";\n  fi\n}\n\nfunction createfile {\n  mkdir -p \"$(dirname \"$1\")\" && echo \"$1\" > \"$1\" && hg add -q \"$1\";\n}\n\nfunction create_first_post_move_commit {\n echo 1 > \"$1/filetoremove\" && hg add \"$1/filetoremove\" && hg ci -m 'first post-move commit'\n hg revert -r .^ \"$1/filetoremove\"\n}\n\nfunction init_client() {\n  cd \"$TESTTMP\" || exit 1\n  hgclone_treemanifest ssh://user@dummy/\"$1\" \"$2\" --noupdate --config extensions.remotenames=\n  cd \"$TESTTMP/$2\" || exit 1\n  cat >> .hg/hgrc <<EOF\n[extensions]\npushrebase =\nremotenames =\nEOF\n}\n\nfunction backsync_large_to_small() {\n  if [[ ! -d \"$SCRIBE_LOGS_DIR\" ]]; then\n    mkdir \"$SCRIBE_LOGS_DIR\"\n  fi\n\n  \"$BACKSYNCER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" --debug --source-repo-id \"$REPOIDLARGE\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    --target-repo-id \"$REPOIDSMALL\" \\\n    backsync-all\n}\n\nfunction backsync_large_to_small_forever {\n  if [[ ! -d \"$SCRIBE_LOGS_DIR\" ]]; then\n    mkdir \"$SCRIBE_LOGS_DIR\"\n  fi\n\n  \"$BACKSYNCER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" --debug \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    --source-repo-id \"$REPOIDLARGE\" \\\n    --target-repo-id \"$REPOIDSMALL\" \\\n    \"$@\" \\\n    backsync-forever >> \"$TESTTMP/backsyncer.out\" 2>&1 &\n\n  export BACKSYNCER_PID=$!\n  echo \"$BACKSYNCER_PID\" >> \"$DAEMON_PIDS\"\n}\n\nfunction mononoke_x_repo_sync_forever() {\n  source_repo_id=$1\n  target_repo_id=$2\n  shift\n  shift\n  GLOG_minloglevel=5 \"$MONONOKE_X_REPO_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    --source-repo-id \"$source_repo_id\" \\\n    --target-repo-id \"$target_repo_id\" \\\n    \"$@\" \\\n    tail --sleep-secs=1 >> \"$TESTTMP/xreposync.out\" 2>&1 &\n\n  export XREPOSYNC_PID=$!\n  echo \"$XREPOSYNC_PID\" >> \"$DAEMON_PIDS\"\n}\n\n# Wait for xrepo sync (15s at most)\nfunction wait_for_xrepo_sync {\n  bookmark_update_log_entry=\"$1\"\n  local attempts=150\n  for _ in $(seq 1 $attempts); do\n    grep -q \"successful sync bookmark update log #$bookmark_update_log_entry\" \"$TESTTMP/xreposync.out\" && break\n    sleep 0.1\n  done\n\n  if ! grep -q \"successful sync bookmark update log #$bookmark_update_log_entry\" \"$TESTTMP/xreposync.out\"; then\n    echo \"xrepo sync of bookmark update log entry $1 did not finish\" >&2\n    cat \"$TESTTMP/xreposync.out\"\n    exit 1\n  fi\n}\n\n\nfunction init_two_small_one_large_repo() {\n  # setup configuration\n  # Disable bookmarks cache because bookmarks are modified by two separate processes\n  REPOTYPE=\"blob_files\"\n  REPOID=0 REPONAME=meg-mon setup_common_config $REPOTYPE\n  REPOID=1 REPONAME=fbs-mon setup_common_config $REPOTYPE\n  REPOID=2 REPONAME=ovr-mon setup_common_config $REPOTYPE\n\n  cat >> \"$HGRCPATH\" <<EOF\n[ui]\nssh=\"$DUMMYSSH\"\n[extensions]\namend=\npushrebase=\nremotenames=\nEOF\n\n  setup_commitsyncmap\n  setup_configerator_configs\n\n  # setup hg server repos\n\n  function createfile { mkdir -p \"$(dirname  \"$1\")\" && echo \"$1\" > \"$1\" && hg add -q \"$1\"; }\n  function createfile_with_content { mkdir -p \"$(dirname  \"$1\")\" && echo \"$2\" > \"$1\" && hg add -q \"$1\"; }\n\n  # init fbsource\n  cd \"$TESTTMP\" || exit 1\n  hginit_treemanifest fbs-hg-srv\n  cd fbs-hg-srv || exit 1\n  # create an initial commit, which will be the last_synced_commit\n  createfile fbcode/fbcodefile_fbsource\n  createfile arvr/arvrfile_fbsource\n  createfile otherfile_fbsource\n  hg -q ci -m \"fbsource commit 1\" && hg book -ir . master_bookmark\n\n  # init ovrsource\n  cd \"$TESTTMP\" || exit 1\n  hginit_treemanifest ovr-hg-srv\n  cd ovr-hg-srv || exit 1\n  createfile fbcode/fbcodefile_ovrsource\n  createfile arvr/arvrfile_ovrsource\n  createfile otherfile_ovrsource\n  createfile Research/researchfile_ovrsource\n  hg -q ci -m \"ovrsource commit 1\" && hg book -r . master_bookmark\n\n  # init megarepo - note that some paths are shifted, but content stays the same\n  cd \"$TESTTMP\" || exit 1\n  hginit_treemanifest meg-hg-srv\n  cd meg-hg-srv || exit 1\n  createfile fbcode/fbcodefile_fbsource\n  createfile_with_content .fbsource-rest/arvr/arvrfile_fbsource arvr/arvrfile_fbsource\n  createfile otherfile_fbsource\n  createfile_with_content .ovrsource-rest/fbcode/fbcodefile_ovrsource fbcode/fbcodefile_ovrsource\n  createfile arvr/arvrfile_ovrsource\n  createfile_with_content arvr-legacy/otherfile_ovrsource otherfile_ovrsource\n  createfile_with_content arvr-legacy/Research/researchfile_ovrsource Research/researchfile_ovrsource\n  hg -q ci -m \"megarepo commit 1\"\n  hg book -r . master_bookmark\n\n  # blobimport hg servers repos into Mononoke repos\n  cd \"$TESTTMP\"\n  REPOID=0 blobimport meg-hg-srv/.hg meg-mon\n  REPOID=1 blobimport fbs-hg-srv/.hg fbs-mon\n  REPOID=2 blobimport ovr-hg-srv/.hg ovr-mon\n}\n\nfunction enable_pushredirect {\n  repo_id=$1\n  shift\n\n  cat >\"$PUSHREDIRECT_CONF/enable\" << EOF\n{\"per_repo\": {\"$repo_id\": {\"public_push\": true, \"draft_push\": false}}}\nEOF\n}\n", "num_lines": 555}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# shellcheck source=fbcode/eden/mononoke/tests/integration/library.sh\n. \"${TEST_FIXTURES}/library.sh\"\n\nfunction base_snapshot_repo_setup {\n    if [ $# -eq  0 ]; then\n        echo \"Must provide at least one clone name\"\n        exit 1\n    fi\n    ENABLE_API_WRITES=true INFINITEPUSH_ALLOW_WRITES=true setup_common_config\n    cd \"$TESTTMP\"\n    cat >> \"$HGRCPATH\" <<EOF\n[extensions]\nsnapshot =\ncommitcloud =\ninfinitepush =\namend =\nEOF\n\n    hginit_treemanifest repo\n    cd repo\n    mkcommit \"base_commit\"\n\n    cd \"$TESTTMP\"\n    for clone in \"$@\"; do\n        hgclone_treemanifest ssh://user@dummy/repo \"$clone\"\n    done\n    blobimport repo/.hg repo\n\n    # start mononoke\n    mononoke\n    wait_for_mononoke\n}\n\nfunction base_commit_and_snapshot {\n    export BASE_SNAPSHOT_COMMIT\n    export BASE_SNAPSHOT\n    # Make an interesting commit and snapshot that tests all types of file changes\n    echo a > modified_file\n    echo a > missing_file\n    echo a > untouched_file\n    echo a > deleted_file\n    echo a > deleted_file_then_untracked_modify\n    mkdir dir\n    echo a > dir/file_in_dir\n    hg addremove -q\n    hg commit -m \"Add base files\"\n    BASE_SNAPSHOT_COMMIT=$(hg log -T \"{node}\" -r .)\n    EDENSCM_LOG=edenapi::client=error hgedenapi cloud upload -q\n    # Create snapshot\n    echo b > modified_file\n    echo b > untracked_file\n    echo b > added_file\n    hg add added_file\n    echo b > added_file_then_missing\n    hg add added_file_then_missing\n    rm added_file_then_missing\n    rm missing_file\n    hg rm deleted_file\n    hg rm deleted_file_then_untracked_modify\n    echo b > deleted_file_then_untracked_modify\n    ln -s symlink_target symlink_file\n    BASE_SNAPSHOT=$(HGPLAIN=1 hgedenapi snapshot create --labels testing,labels)\n}\n\nfunction assert_on_base_snapshot {\n    # Using subshell to set pipefail\n    (\n    set -e -o pipefail\n    [[ \"$(hg log -T \"{node}\" -r .)\" = \"$BASE_SNAPSHOT_COMMIT\" ]] || ( echo wrong parent && hg log -T \"{node}\" -r . )\n    [[ \"$(cat untouched_file)\" = \"a\" ]] || echo wrong untouched_file\n    [[ \"$(cat dir/file_in_dir)\" = \"a\" ]] || echo wrong file_in_dir\n    [[ \"$(cat modified_file)\" = \"b\" ]] || echo wrong modified_file\n    [[ \"$(cat added_file)\" = \"b\" ]] || echo wrong added_file\n    [[ \"$(cat deleted_file_then_untracked_modify)\" = \"b\" ]] || wrong deleted_file_then_untracked_modify\n    [[ \"$(cat untracked_file)\" = \"b\" ]] || echo wrong untracked_file\n    [[ \"$(readlink symlink_file)\" = \"symlink_target\" ]] || echo wrong symlink target\n    [[ ! -f deleted_file ]] || echo Existing deleted_file\n    [[ ! -f added_file_then_missing ]] || echo Existing added_file_then_missing\n    [[ ! -f missing_file ]] || echo Existing missing_file\n    )\n}\n", "num_lines": 88}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# Library routines and initial setup for Mononoke-related tests.\n\nif [ -n \"$FB_TEST_FIXTURES\" ] && [ -f \"$FB_TEST_FIXTURES/fb_library.sh\" ]; then\n  # shellcheck source=fbcode/eden/mononoke/tests/integration/facebook/fb_library.sh\n  . \"$FB_TEST_FIXTURES/fb_library.sh\"\nfi\n\nPROXY_ID_TYPE=\"${FB_PROXY_ID_TYPE:-X509_SUBJECT_NAME}\"\nPROXY_ID_DATA=\"${FB_PROXY_ID_DATA:-CN=proxy,O=Mononoke,C=US,ST=CA}\"\nCLIENT0_ID_TYPE=\"${FB_CLIENT0_ID_TYPE:-X509_SUBJECT_NAME}\"\nCLIENT0_ID_DATA=\"${FB_CLIENT0_ID_DATA:-CN=client0,O=Mononoke,C=US,ST=CA}\"\n# shellcheck disable=SC2034\nCLIENT1_ID_TYPE=\"${FB_CLIENT1_ID_TYPE:-X509_SUBJECT_NAME}\"\n# shellcheck disable=SC2034\nCLIENT1_ID_DATA=\"${FB_CLIENT1_ID_DATA:-CN=client1,O=Mononoke,C=US,ST=CA}\"\n# shellcheck disable=SC2034\nCLIENT2_ID_TYPE=\"${FB_CLIENT2_ID_TYPE:-X509_SUBJECT_NAME}\"\n# shellcheck disable=SC2034\nCLIENT2_ID_DATA=\"${FB_CLIENT2_ID_DATA:-CN=client2,O=Mononoke,C=US,ST=CA}\"\n# shellcheck disable=SC2034\nJSON_CLIENT_ID=\"${FB_JSON_CLIENT_ID:-[\\\"X509_SUBJECT_NAME:CN=client0,O=Mononoke,C=US,ST=CA\\\"]}\"\n\nSCRIBE_LOGS_DIR=\"$TESTTMP/scribe_logs\"\n\nif [[ -n \"$DB_SHARD_NAME\" ]]; then\n  MONONOKE_DEFAULT_START_TIMEOUT=600\n  MONONOKE_LFS_DEFAULT_START_TIMEOUT=60\n  MONONOKE_SCS_DEFAULT_START_TIMEOUT=120\n  MONONOKE_LAND_SERVICE_DEFAULT_START_TIMEOUT=120\nelse\n  MONONOKE_DEFAULT_START_TIMEOUT=60\n  MONONOKE_LFS_DEFAULT_START_TIMEOUT=60\n  # First scsc call takes a while as scs server is doing derivation\n  MONONOKE_SCS_DEFAULT_START_TIMEOUT=120\n  MONONOKE_LAND_SERVICE_DEFAULT_START_TIMEOUT=120\n  MONONOKE_DDS_DEFAULT_START_TIMEOUT=120\nfi\nVI_SERVICE_DEFAULT_START_TIMEOUT=60\n\nfunction urlencode {\n  \"$URLENCODE\" \"$@\"\n}\n\nREPOID=0\nREPONAME=${REPONAME:-repo}\n\n# Where we write host:port information after servers bind to :0\nMONONOKE_SERVER_ADDR_FILE=\"$TESTTMP/mononoke_server_addr.txt\"\nDDS_SERVER_ADDR_FILE=\"$TESTTMP/dds_server_addr.txt\"\n\nexport LOCAL_CONFIGERATOR_PATH=\"$TESTTMP/configerator\"\nmkdir -p \"${LOCAL_CONFIGERATOR_PATH}\"\n\nexport ACL_FILE=\"$TESTTMP/acls.json\"\n\n# The path for tunables. Do not write directly to this! Use merge_tunables instead.\nexport MONONOKE_TUNABLES_PATH=\"${LOCAL_CONFIGERATOR_PATH}/mononoke_tunables.json\"\n\nfunction get_configerator_relative_path {\n  realpath --relative-to \"${LOCAL_CONFIGERATOR_PATH}\" \"$1\"\n}\n\nif [[ -n \"$ENABLE_LOCAL_CACHE\" ]]; then\n  CACHE_ARGS=(\n    --cache-mode=local-only\n    --cache-size-gb=1\n    --cachelib-disable-cacheadmin\n  )\nelse\n  CACHE_ARGS=( --cache-mode=disabled )\nfi\n\nCOMMON_ARGS=(\n  --mysql-master-only\n  --tunables-config \"$(get_configerator_relative_path \"${MONONOKE_TUNABLES_PATH}\")\"\n  --local-configerator-path \"${LOCAL_CONFIGERATOR_PATH}\"\n  --log-exclude-tag \"futures_watchdog\"\n  --with-test-megarepo-configs-client=true\n  --acl-file \"${ACL_FILE}\"\n)\n\nexport TEST_CERTDIR\nTEST_CERTDIR=\"${HGTEST_CERTDIR:-\"$TEST_CERTS\"}\"\nif [[ -z \"$TEST_CERTDIR\" ]]; then\n  echo \"TEST_CERTDIR is not set\" 1>&2\n  exit 1\nfi\n\ncase \"$(uname -s)\" in\n  # Workarounds for running tests on MacOS\n  Darwin*)\n    prefix=\"${HOMEBREW_PREFIX:-/usr/local}\"\n\n    # Use the brew installed versions of GNU utils\n    PATH=\"$prefix/opt/gnu-sed/libexec/gnubin:\\\n$prefix/opt/grep/libexec/gnubin:\\\n$prefix/opt/coreutils/libexec/gnubin:\\\n$PATH\"\n  ;;\nesac\n\nfunction killandwait {\n  # sends KILL to the given process and waits for it so that nothing is printed\n  # to the terminal on MacOS\n  { kill -9 \"$1\" && wait \"$1\"; } > /dev/null 2>&1\n  # We don't care for wait exit code\n  true\n}\n\nfunction get_free_socket {\n  \"$GET_FREE_SOCKET\"\n}\n\nfunction mononoke_host {\n  if [[ $LOCALIP == *\":\"* ]]; then\n    # ipv6, surround in brackets\n    echo -n \"[$LOCALIP]\"\n  else\n    echo -n \"$LOCALIP\"\n  fi\n}\n\nfunction mononoke_address {\n  if [[ $LOCALIP == *\":\"* ]]; then\n    # ipv6, surround in brackets\n    echo -n \"[$LOCALIP]:$MONONOKE_SOCKET\"\n  else\n    echo -n \"$LOCALIP:$MONONOKE_SOCKET\"\n  fi\n}\n\nfunction scs_address {\n  echo -n \"$(mononoke_host):$SCS_PORT\"\n}\n\nfunction land_service_address {\n  echo -n \"$(mononoke_host):$LAND_SERVICE_PORT\"\n}\n\nfunction dds_address {\n  echo -n \"$(mononoke_host):$DDS_PORT\"\n}\n\n# return random value from [1, max_value]\nfunction random_int() {\n  max_value=$1\n\n  VAL=$RANDOM\n  (( VAL %= max_value ))\n  (( VAL += 1 ))\n\n  echo $VAL\n}\n\nfunction sslcurlas {\n  local name=\"$1\"\n  shift\n  curl --noproxy localhost --cert \"$TEST_CERTDIR/$name.crt\" --cacert \"$TEST_CERTDIR/root-ca.crt\" --key \"$TEST_CERTDIR/$name.key\" \"$@\"\n}\n\nfunction sslcurl {\n  sslcurlas proxy \"$@\"\n}\n\nfunction mononoke {\n  if [[ ! -d \"$SCRIBE_LOGS_DIR\" ]]; then\n    mkdir \"$SCRIBE_LOGS_DIR\"\n  fi\n\n  setup_configerator_configs\n\n  local BIND_ADDR\n  if [[ $LOCALIP == *\":\"* ]]; then\n    # ipv6, surround in brackets\n    BIND_ADDR=\"[$LOCALIP]:0\"\n  else\n    BIND_ADDR=\"$LOCALIP:0\"\n  fi\n\n  # Stop any confusion from previous runs\n  rm -f \"$MONONOKE_SERVER_ADDR_FILE\"\n\n  # Ignore specific Python warnings to make tests predictable.\n  PYTHONWARNINGS=\"ignore:::requests,ignore::SyntaxWarning\" \\\n  GLOG_minloglevel=5 \\\n    \"$MONONOKE_SERVER\" \"$@\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    --ca-pem \"$TEST_CERTDIR/root-ca.crt\" \\\n    --private-key \"$TEST_CERTDIR/localhost.key\" \\\n    --cert \"$TEST_CERTDIR/localhost.crt\" \\\n    --ssl-ticket-seeds \"$TEST_CERTDIR/server.pem.seeds\" \\\n    --land-service-client-cert=\"$TEST_CERTDIR/proxy.crt\" \\\n    --land-service-client-private-key=\"$TEST_CERTDIR/proxy.key\" \\\n    --debug \\\n    --listening-host-port \"$BIND_ADDR\" \\\n    --bound-address-file \"$MONONOKE_SERVER_ADDR_FILE\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --no-default-scuba-dataset \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" >> \"$TESTTMP/mononoke.out\" 2>&1 &\n  export MONONOKE_PID=$!\n  echo \"$MONONOKE_PID\" >> \"$DAEMON_PIDS\"\n}\n\nfunction mononoke_hg_sync {\n  HG_REPO=\"$1\"\n  shift\n  START_ID=\"$1\"\n  shift\n\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --verify-server-bookmark-on-failure \\\n     ssh://user@dummy/\"$HG_REPO\" \"$@\" sync-once --start-id \"$START_ID\"\n}\n\nfunction mononoke_backup_sync {\n  HG_REPO=\"$1\"\n  SYNC_MODE=\"$2\"\n  START_ID=\"$3\"\n  shift\n  shift\n  shift\n\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --verify-server-bookmark-on-failure \\\n    --darkstorm-backup-repo-id \"$BACKUP_REPO_ID\" \\\n    \"mononoke://$(mononoke_address)/$HG_REPO\" \"$@\" \"$SYNC_MODE\" --start-id \"$START_ID\"\n}\n\nfunction mononoke_backup_sync_loop_forever {\n  HG_REPO=\"$1\"\n  START_ID=\"$2\"\n  shift\n  shift\n\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --verify-server-bookmark-on-failure \\\n    --darkstorm-backup-repo-id \"$BACKUP_REPO_ID\" \\\n    \"mononoke://$(mononoke_address)/$HG_REPO\" \"$@\" \\\n    sync-loop \\\n    --start-id \"$START_ID\" \\\n    --loop-forever  >> \"$TESTTMP/backup_sync.out\" 2>&1 &\n  export BACKUP_SYNC_PID=$!\n  echo \"$BACKUP_SYNC_PID\" >> \"$DAEMON_PIDS\"\n}\n\n\nfunction megarepo_tool {\n  GLOG_minloglevel=5 \"$MEGAREPO_TOOL\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    \"$@\"\n}\n\n\nfunction megarepo_tool_multirepo {\n  GLOG_minloglevel=5 \"$MEGAREPO_TOOL\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    \"$@\"\n}\n\nfunction mononoke_walker {\n  GLOG_minloglevel=5 \"$MONONOKE_WALKER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    \"$@\"\n}\n\nfunction mononoke_blobstore_healer {\n  GLOG_minloglevel=5 \"$MONONOKE_BLOBSTORE_HEALER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    \"$@\" 2>&1 | grep -v \"Could not connect to a replica\"\n}\n\nfunction mononoke_sqlblob_gc {\n  GLOG_minloglevel=5 \"$MONONOKE_SQLBLOB_GC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    \"$@\" 2>&1 | grep -v \"Could not connect to a replica\"\n}\n\nfunction mononoke_x_repo_sync() {\n  source_repo_id=$1\n  target_repo_id=$2\n  shift\n  shift\n  GLOG_minloglevel=5 \"$MONONOKE_X_REPO_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --source-repo-id \"$source_repo_id\" \\\n    --target-repo-id \"$target_repo_id\" \\\n    \"$@\"\n}\n\nfunction mononoke_hg_sync_with_retry {\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --base-retry-delay-ms 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    --verify-server-bookmark-on-failure \\\n     ssh://user@dummy/\"$1\" sync-once --start-id \"$2\"\n}\n\nfunction mononoke_hg_sync_with_failure_handler {\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    --verify-server-bookmark-on-failure \\\n    --lock-on-failure \\\n     ssh://user@dummy/\"$1\" sync-once --start-id \"$2\"\n}\n\nfunction create_books_sqlite3_db {\n  cat >> \"$TESTTMP\"/bookmarks.sql <<SQL\n  CREATE TABLE IF NOT EXISTS bookmarks_update_log (\n  id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n  repo_id INT UNSIGNED NOT NULL,\n  name VARCHAR(512) NOT NULL,\n  from_changeset_id VARBINARY(32),\n  to_changeset_id VARBINARY(32),\n  reason VARCHAR(32) NOT NULL, -- enum is used in mysql\n  category VARCHAR(32) NOT NULL DEFAULT 'branch',\n  timestamp BIGINT NOT NULL\n);\nSQL\n\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" < \"$TESTTMP\"/bookmarks.sql\n}\n\nfunction mononoke_hg_sync_loop {\n  local repo=\"$1\"\n  local start_id=\"$2\"\n  shift\n  shift\n\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    ssh://user@dummy/\"$repo\" sync-loop --start-id \"$start_id\" \"$@\"\n}\n\nfunction mononoke_hg_sync_loop_regenerate {\n  local repo=\"$1\"\n  local start_id=\"$2\"\n  shift\n  shift\n\n  GLOG_minloglevel=5 \"$MONONOKE_HG_SYNC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --retry-num 1 \\\n    --repo-id 0 \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \\\n    ssh://user@dummy/\"$repo\" sync-loop --start-id \"$start_id\" \"$@\"\n}\n\nfunction mononoke_admin {\n  GLOG_minloglevel=5 \"$MONONOKE_ADMIN\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id $REPOID \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\nfunction mononoke_newadmin {\n  GLOG_minloglevel=5 \"$MONONOKE_NEWADMIN\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\nfunction mononoke_import {\n  GLOG_minloglevel=5 \"$MONONOKE_IMPORT\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\nfunction mononoke_testtool {\n  GLOG_minloglevel=5 \"$MONONOKE_TESTTOOL\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\nfunction mononoke_admin_source_target {\n  local source_repo_id=$1\n  shift\n  local target_repo_id=$1\n  shift\n  GLOG_minloglevel=5 \"$MONONOKE_ADMIN\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --source-repo-id \"$source_repo_id\" \\\n    --target-repo-id \"$target_repo_id\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\n# Remove the glog prefix\nfunction strip_glog {\n  # based on https://our.internmc.facebook.com/intern/wiki/LogKnock/Log_formats/#regex-for-glog\n  sed -E -e 's%^[VDIWECF][[:digit:]]{4} [[:digit:]]{2}:?[[:digit:]]{2}:?[[:digit:]]{2}(\\.[[:digit:]]+)?\\s+(([0-9a-f]+)\\s+)?(\\[([^]]+)\\]\\s+)?(\\(([^\\)]+)\\)\\s+)?(([a-zA-Z0-9_./-]+):([[:digit:]]+))\\]\\s+%%'\n}\n\nfunction wait_for_json_record_count {\n  # We ask jq to count records for us, so that we're a little more robust ot\n  # newlines and such.\n  local file count\n  file=\"$1\"\n  count=\"$2\"\n\n  for _ in $(seq 1 50); do\n    if [[ \"$(jq 'true' < \"$file\" | wc -l)\" -eq \"$count\" ]] ; then\n      return 0\n    fi\n\n    sleep 0.1\n  done\n\n  echo \"File $file did not contain $count records, it had $(jq 'true' < \"$file\" | wc -l)\" >&2\n  jq -S . < \"$file\" >&2\n  return 1\n}\n\nfunction wait_for_server {\n  local service_description port_env_var log_file timeout_secs bound_addr_file\n  service_description=\"$1\"; shift\n  port_env_var=\"$1\"; shift\n  log_file=\"$1\"; shift\n  timeout_secs=\"$1\"; shift\n  bound_addr_file=\"$1\"; shift\n\n  local start\n  start=$(date +%s)\n\n  local found_port\n  while [[ $(($(date +%s) - start)) -lt \"$timeout_secs\" ]]; do\n    if [[ -z \"$found_port\" && -r \"$bound_addr_file\" ]]; then\n      found_port=$(sed 's/^.*:\\([^:]*\\)$/\\1/' \"$bound_addr_file\")\n      eval \"$port_env_var\"=\"$found_port\"\n    fi\n    if [[ -n \"$found_port\" ]] && \"$@\" >/dev/null 2>&1 ; then\n      return 0\n    fi\n    sleep 1\n  done\n\n  echo \"$service_description did not start in $timeout_secs seconds, took $(($(date +%s) - start))\" >&2\n  if [[ -n \"$found_port\" ]]; then\n    echo \"Running check: $* >/dev/null\"\n    \"$@\" >/dev/null\n    echo \"exited with $?\" 1>&2\n  else\n    echo \"Port was never written to $bound_addr_file\" 1>&2\n  fi\n  echo \"\" 1>&2\n  echo \"Log of $service_description\" 1>&2\n  cat \"$log_file\" 1>&2\n  exit 1\n}\n\nfunction mononoke_health {\n  sslcurl -q \"https://localhost:$MONONOKE_SOCKET/health_check\"\n}\n\n# Wait until a Mononoke server is available for this repo.\nfunction wait_for_mononoke {\n  export MONONOKE_SOCKET\n  wait_for_server \"Mononoke\" MONONOKE_SOCKET \"$TESTTMP/mononoke.out\" \\\n    \"${MONONOKE_START_TIMEOUT:-\"$MONONOKE_DEFAULT_START_TIMEOUT\"}\" \"$MONONOKE_SERVER_ADDR_FILE\" \\\n    mononoke_health\n}\n\nfunction flush_mononoke_bookmarks {\n  sslcurl -X POST -fsS \"https://localhost:$MONONOKE_SOCKET/control/drop_bookmarks_cache\"\n}\n\nfunction force_update_configerator {\n  sslcurl -X POST -fsS \"https://localhost:$MONONOKE_SOCKET/control/force_update_configerator\"\n}\n\nfunction start_and_wait_for_mononoke_server {\n    mononoke \"$@\"\n    wait_for_mononoke\n}\n\n# Wait until cache warmup finishes\nfunction wait_for_mononoke_cache_warmup {\n  local attempts=150\n  for _ in $(seq 1 $attempts); do\n    grep -q \"finished initial warmup\" \"$TESTTMP/mononoke.out\" && break\n    sleep 0.1\n  done\n\n  if ! grep -q \"finished initial warmup\" \"$TESTTMP/mononoke.out\"; then\n    echo \"Mononoke warmup did not finished\" >&2\n    cat \"$TESTTMP/mononoke.out\"\n    exit 1\n  fi\n}\n\nfunction setup_common_hg_configs {\n  cat >> \"$HGRCPATH\" <<EOF\n[ui]\nssh=\"$DUMMYSSH\"\n[devel]\nsegmented-changelog-rev-compat=True\n[extensions]\nremotefilelog=\n[remotefilelog]\ncachepath=$TESTTMP/cachepath\n[extensions]\ncommitextras=\n[hint]\nack=*\n[experimental]\nchangegroup3=True\n[mutation]\nrecord=False\n[web]\ncacerts=$TEST_CERTDIR/root-ca.crt\n[auth]\nmononoke.cert=$TEST_CERTDIR/${OVERRIDE_CLIENT_CERT:-client0}.crt\nmononoke.key=$TEST_CERTDIR/${OVERRIDE_CLIENT_CERT:-client0}.key\nmononoke.prefix=mononoke://*\nmononoke.cn=localhost\nedenapi.cert=$TEST_CERTDIR/${OVERRIDE_CLIENT_CERT:-client0}.crt\nedenapi.key=$TEST_CERTDIR/${OVERRIDE_CLIENT_CERT:-client0}.key\nedenapi.prefix=localhost\nedenapi.cacerts=$TEST_CERTDIR/root-ca.crt\n[workingcopy]\nuse-rust=False\nruststatus=False\n[status]\nuse-rust=False\nEOF\n}\n\nfunction setup_common_config {\n    setup_mononoke_config \"$@\"\n    setup_common_hg_configs\n    setup_configerator_configs\n}\n\nfunction get_bonsai_svnrev_mapping {\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"select hex(bcs_id), svnrev from bonsai_svnrev_mapping order by id\";\n}\n\nfunction get_bonsai_git_mapping {\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"select hex(bcs_id), hex(git_sha1) from bonsai_git_mapping order by id\";\n}\n\nfunction get_bonsai_hg_mapping {\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"select hex(bcs_id), hex(hg_cs_id) from bonsai_hg_mapping order by repo_id, bcs_id\";\n}\n\nfunction get_bonsai_globalrev_mapping {\n  sqlite3 \"$TESTTMP/monsql/sqlite_dbs\" \"select hex(bcs_id), globalrev from bonsai_globalrev_mapping order by globalrev\";\n}\n\nfunction setup_mononoke_config {\n  cd \"$TESTTMP\" || exit\n\n  mkdir -p mononoke-config\n  REPOTYPE=\"blob_sqlite\"\n  if [[ $# -gt 0 ]]; then\n    REPOTYPE=\"$1\"\n    shift\n  fi\n  local blobstorename=blobstore\n  if [[ $# -gt 0 ]]; then\n    blobstorename=\"$1\"\n    shift\n  fi\n\n  cd mononoke-config || exit 1\n  mkdir -p common\n  touch common/common.toml\n  touch common/commitsyncmap.toml\n\n  # We have some tests that call this twice...\n  truncate -s 0 common/common.toml\n\n  if [[ -n \"$SCUBA_CENSORED_LOGGING_PATH\" ]]; then\n  cat > common/common.toml <<CONFIG\nscuba_local_path_censored=\"$SCUBA_CENSORED_LOGGING_PATH\"\nCONFIG\n  fi\n\n  if [[ -z \"$DISABLE_HTTP_CONTROL_API\" ]]; then\n  cat >> common/common.toml <<CONFIG\nenable_http_control_api=true\nCONFIG\n  fi\n\n  cat >> common/common.toml <<CONFIG\n[internal_identity]\nidentity_type = \"SERVICE_IDENTITY\"\nidentity_data = \"proxy\"\n\n[redaction_config]\nblobstore = \"$blobstorename\"\ndarkstorm_blobstore = \"$blobstorename\"\nredaction_sets_location = \"scm/mononoke/redaction/redaction_sets\"\n\n[[trusted_parties_allowlist]]\nidentity_type = \"$PROXY_ID_TYPE\"\nidentity_data = \"$PROXY_ID_DATA\"\nCONFIG\n\n  cat >> common/common.toml <<CONFIG\n${ADDITIONAL_MONONOKE_COMMON_CONFIG}\nCONFIG\n\n  echo \"# Start new config\" > common/storage.toml\n  setup_mononoke_storage_config \"$REPOTYPE\" \"$blobstorename\"\n\n  setup_mononoke_repo_config \"$REPONAME\" \"$blobstorename\"\n\n  setup_acls\n}\n\nfunction setup_acls() {\n  if [[ ! -f \"$ACL_FILE\" ]]; then\n    cat > \"$ACL_FILE\" <<ACLS\n{\n  \"repos\": {\n    \"default\": {\n      \"actions\": {\n        \"read\": [\"$CLIENT0_ID_TYPE:$CLIENT0_ID_DATA\"],\n        \"write\": [\"$CLIENT0_ID_TYPE:$CLIENT0_ID_DATA\"]\n      }\n    }\n  }\n}\nACLS\n  fi\n}\n\nfunction db_config() {\n  local blobstorename=\"$1\"\n  if [[ -n \"$DB_SHARD_NAME\" ]]; then\n    echo \"[$blobstorename.metadata.remote]\"\n    echo \"primary = { db_address = \\\"$DB_SHARD_NAME\\\" }\"\n    echo \"filenodes = { unsharded = { db_address = \\\"$DB_SHARD_NAME\\\" } }\"\n    echo \"mutation = { db_address = \\\"$DB_SHARD_NAME\\\" }\"\n  else\n    echo \"[$blobstorename.metadata.local]\"\n    echo \"local_db_path = \\\"$TESTTMP/monsql\\\"\"\n  fi\n}\n\nfunction ephemeral_db_config() {\n  local blobstorename=\"$1\"\n  if [[ -n \"$DB_SHARD_NAME\" ]]; then\n    echo \"[$blobstorename.metadata.remote]\"\n    echo \"db_address = \\\"$DB_SHARD_NAME\\\"\"\n  else\n    echo \"[$blobstorename.metadata.local]\"\n    echo \"local_db_path = \\\"$TESTTMP/monsql\\\"\"\n  fi\n}\n\nfunction blobstore_db_config() {\n  if [[ -n \"$DB_SHARD_NAME\" ]]; then\n    echo \"queue_db = { unsharded = { db_address = \\\"$DB_SHARD_NAME\\\" } }\"\n  else\n    local blobstore_db_path=\"$TESTTMP/blobstore_sync_queue\"\n    mkdir -p \"$blobstore_db_path\"\n    echo \"queue_db = { local = { local_db_path = \\\"$blobstore_db_path\\\" } }\"\n  fi\n}\n\nfunction setup_mononoke_storage_config {\n  local underlyingstorage=\"$1\"\n  local blobstorename=\"$2\"\n  local blobstorepath=\"$TESTTMP/$blobstorename\"\n  local bubble_deletion_mode=0 # Bubble deletion is disabled by default\n  if [[ -n ${BUBBLE_DELETION_MODE:-} ]]; then\n    bubble_deletion_mode=${BUBBLE_DELETION_MODE}\n  fi\n  local bubble_lifespan_secs=1000\n  if [[ -n ${BUBBLE_LIFESPAN_SECS:-} ]]; then\n    bubble_lifespan_secs=${BUBBLE_LIFESPAN_SECS}\n  fi\n  local bubble_expiration_secs=1000\n  if [[ -n ${BUBBLE_EXPIRATION_SECS:-} ]]; then\n    bubble_expiration_secs=${BUBBLE_EXPIRATION_SECS}\n  fi\n\n  if [[ -n \"${MULTIPLEXED:-}\" ]]; then\n    local quorum\n    local btype\n    local scuba\n    quorum=\"write_quorum\"\n    btype=\"multiplexed_wal\"\n    scuba=\"multiplex_scuba_table = \\\"file://$TESTTMP/blobstore_trace_scuba.json\\\"\"\n    cat >> common/storage.toml <<CONFIG\n$(db_config \"$blobstorename\")\n\n[$blobstorename.blobstore.${btype}]\nmultiplex_id = 1\n$(blobstore_db_config)\n${quorum} = ${MULTIPLEXED}\n${scuba}\ncomponents = [\nCONFIG\n\n    local i\n    for ((i=0; i<=MULTIPLEXED; i++)); do\n      mkdir -p \"$blobstorepath/$i/blobs\"\n      if [[ -n \"${PACK_BLOB:-}\" && $i -le \"$PACK_BLOB\" ]]; then\n        echo \"  { blobstore_id = $i, blobstore = { pack = { blobstore = { $underlyingstorage = { path = \\\"$blobstorepath/$i\\\" } } } } },\" >> common/storage.toml\n      else\n        echo \"  { blobstore_id = $i, blobstore = { $underlyingstorage = { path = \\\"$blobstorepath/$i\\\" } } },\" >> common/storage.toml\n      fi\n    done\n    echo ']' >> common/storage.toml\n  else\n    mkdir -p \"$blobstorepath/blobs\"\n    # Using FileBlob instead of SqlBlob as the backing blobstore for ephemeral\n    # store since SqlBlob current doesn't support enumeration.\n    cat >> common/storage.toml <<CONFIG\n$(db_config \"$blobstorename\")\n\n[$blobstorename.ephemeral_blobstore]\ninitial_bubble_lifespan_secs = $bubble_lifespan_secs\nbubble_expiration_grace_secs = $bubble_expiration_secs\nbubble_deletion_mode = $bubble_deletion_mode\nblobstore = { blob_files = { path = \"$blobstorepath\" } }\n\n$(ephemeral_db_config \"$blobstorename.ephemeral_blobstore\")\n\n\n[$blobstorename.blobstore]\nCONFIG\n    if [[ -n \"${PACK_BLOB:-}\" ]]; then\n      echo \"  pack = { blobstore = { $underlyingstorage = { path = \\\"$blobstorepath\\\" } } }\" >> common/storage.toml\n    else\n      echo \"  $underlyingstorage = { path = \\\"$blobstorepath\\\" }\" >> common/storage.toml\n    fi\n  fi\n}\n\nfunction setup_commitsyncmap {\n  cp \"$TEST_FIXTURES/commitsync/current.toml\" \"$TESTTMP/mononoke-config/common/commitsyncmap.toml\"\n}\n\nfunction setup_configerator_configs {\n  export RATE_LIMIT_CONF\n  RATE_LIMIT_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/ratelimiting\"\n  mkdir -p \"$RATE_LIMIT_CONF\"\n\n  if [[ ! -f \"$RATE_LIMIT_CONF/ratelimits\" ]]; then\n    cat >> \"$RATE_LIMIT_CONF/ratelimits\" <<EOF\n{\n  \"rate_limits\": [],\n  \"load_shed_limits\": [],\n  \"datacenter_prefix_capacity\": {},\n  \"commits_per_author\": {\n    \"status\": 0,\n    \"limit\": 300,\n    \"window\": 1800\n  },\n  \"total_file_changes\": {\n    \"status\": 0,\n    \"limit\": 80000,\n    \"window\": 5\n  }\n}\nEOF\n  fi\n\n  export PUSHREDIRECT_CONF\n  PUSHREDIRECT_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/pushredirect\"\n  mkdir -p \"$PUSHREDIRECT_CONF\"\n\n  if [[ ! -f \"$PUSHREDIRECT_CONF/enable\" ]]; then\n    cat >> \"$PUSHREDIRECT_CONF/enable\" <<EOF\n{\n  \"per_repo\": {}\n}\nEOF\n  fi\n\n  COMMIT_SYNC_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/repos/commitsyncmaps\"\n  mkdir -p \"$COMMIT_SYNC_CONF\"\n  export COMMIT_SYNC_CONF\n  if [[ -n $SKIP_CROSS_REPO_CONFIG ]]; then\n    cat > \"$COMMIT_SYNC_CONF/all\" <<EOF\n{\n}\nEOF\n    cat > \"$COMMIT_SYNC_CONF/current\" <<EOF\n{\n}\nEOF\n  else\n    if [[ ! -f \"$COMMIT_SYNC_CONF/all\" ]]; then\n      cp \"$TEST_FIXTURES/commitsync/all.json\" \"$COMMIT_SYNC_CONF/all\"\n    fi\n    if [[ ! -f \"$COMMIT_SYNC_CONF/current\" ]]; then\n      cp \"$TEST_FIXTURES/commitsync/current.json\" \"$COMMIT_SYNC_CONF/current\"\n    fi\n  fi\n\n  export XDB_GC_CONF\n  XDB_GC_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/xdb_gc\"\n  mkdir -p \"$XDB_GC_CONF\"\n  if [[ ! -f \"$XDB_GC_CONF/default\" ]]; then\n    cat >> \"$XDB_GC_CONF/default\" <<EOF\n{\n  \"put_generation\": 2,\n  \"mark_generation\": 1,\n  \"delete_generation\": 0\n}\nEOF\n  fi\n\n  export OBSERVABILITY_CONF\n  OBSERVABILITY_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/observability\"\n  mkdir -p \"$OBSERVABILITY_CONF\"\n  if [[ ! -f \"$OBSERVABILITY_CONF/observability_config\" ]]; then\n  cat >> \"$OBSERVABILITY_CONF/observability_config\" <<EOF\n{\n  \"slog_config\": {\n    \"level\": 4\n  },\n  \"scuba_config\": {\n    \"level\": 1,\n    \"verbose_sessions\": [],\n    \"verbose_unixnames\": [],\n    \"verbose_source_hostnames\": []\n  }\n}\nEOF\n  fi\n\n  export REDACTION_CONF\n  REDACTION_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/redaction\"\n  mkdir -p \"$REDACTION_CONF\"\n\n  if [[ ! -f \"$REDACTION_CONF/redaction_sets\" ]]; then\n    cat >> \"$REDACTION_CONF/redaction_sets\" <<EOF\n{\n  \"all_redactions\": []\n}\nEOF\n  fi\n\n\n  export REPLICATION_LAG_CONF\n  REPLICATION_LAG_CONF=\"${LOCAL_CONFIGERATOR_PATH}/scm/mononoke/mysql/replication_lag/config\"\n  mkdir -p \"$REPLICATION_LAG_CONF\"\n  for CONF in \"healer\" \"derived_data_backfiller\" \"derived_data_tailer\"; do\n    if [[ ! -f \"$REPLICATION_LAG_CONF/$CONF\" ]]; then\n      cat >> \"$REPLICATION_LAG_CONF/$CONF\" <<EOF\n {\n }\nEOF\n    fi\n  done\n}\n\nfunction setup_mononoke_repo_config {\n  cd \"$TESTTMP/mononoke-config\" || exit\n  local reponame=\"$1\"\n  local reponame_urlencoded\n  reponame_urlencoded=\"$(urlencode encode \"$reponame\")\"\n  local storageconfig=\"$2\"\n  mkdir -p \"repos/$reponame_urlencoded\"\n  mkdir -p \"repo_definitions/$reponame_urlencoded\"\n  mkdir -p \"$TESTTMP/monsql\"\n  mkdir -p \"$TESTTMP/$reponame_urlencoded\"\n  mkdir -p \"$TESTTMP/traffic-replay-blobstore\"\n  cat > \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nhash_validation_percentage=100\nCONFIG\n\n  cat > \"repo_definitions/$reponame_urlencoded/server.toml\" <<CONFIG\nrepo_id=$REPOID\nrepo_name=\"$reponame\"\nrepo_config=\"$reponame\"\nenabled=${ENABLED:-true}\nhipster_acl=\"${ACL_NAME:-default}\"\nCONFIG\n\n\nif [[ -n \"${READ_ONLY_REPO:-}\" ]]; then\n  cat >> \"repo_definitions/$reponame_urlencoded/server.toml\" <<CONFIG\nreadonly=true\nCONFIG\nfi\n\nif [[ -n \"${SCUBA_LOGGING_PATH:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nscuba_local_path=\"$SCUBA_LOGGING_PATH\"\nCONFIG\nfi\n\nif [[ -n \"${ENFORCE_LFS_ACL_CHECK:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nenforce_lfs_acl_check=true\nCONFIG\nfi\n\nif [[ -n \"${REPO_CLIENT_USE_WARM_BOOKMARKS_CACHE:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nrepo_client_use_warm_bookmarks_cache=true\nCONFIG\nfi\n\n# Normally point to common storageconfig, but if none passed, create per-repo\nif [[ -z \"$storageconfig\" ]]; then\n  storageconfig=\"blobstore_$reponame_urlencoded\"\n  setup_mononoke_storage_config \"$REPOTYPE\" \"$storageconfig\"\nfi\ncat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nstorage_config = \"$storageconfig\"\n\nCONFIG\n\nif [[ -n \"${FILESTORE:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[filestore]\nchunk_size = ${FILESTORE_CHUNK_SIZE:-10}\nconcurrency = 24\nCONFIG\nfi\n\nif [[ -n \"${REDACTION_DISABLED:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nredaction=false\nCONFIG\nfi\n\nif [[ -n \"${LIST_KEYS_PATTERNS_MAX:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nlist_keys_patterns_max=$LIST_KEYS_PATTERNS_MAX\nCONFIG\nfi\n\nif [[ -n \"${ONLY_FAST_FORWARD_BOOKMARK:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[[bookmarks]]\nname=\"$ONLY_FAST_FORWARD_BOOKMARK\"\nonly_fast_forward=true\nCONFIG\nfi\n\nif [[ -n \"${ONLY_FAST_FORWARD_BOOKMARK_REGEX:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[[bookmarks]]\nregex=\"$ONLY_FAST_FORWARD_BOOKMARK_REGEX\"\nonly_fast_forward=true\nCONFIG\nfi\n\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[pushrebase]\nforbid_p2_root_rebases=false\nCONFIG\n\nif [[ -n \"${ALLOW_CASEFOLDING:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\ncasefolding_check=false\nCONFIG\nfi\n\nif [[ -n \"${BLOCK_MERGES:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nblock_merges=true\nCONFIG\nfi\n\nif [[ -n \"${PUSHREBASE_REWRITE_DATES:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nrewritedates=true\nCONFIG\nelse\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nrewritedates=false\nCONFIG\nfi\n\nif [[ -n \"${EMIT_OBSMARKERS:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nemit_obsmarkers=true\nCONFIG\nfi\n\nif [[ -n \"${GLOBALREVS_PUBLISHING_BOOKMARK:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nglobalrevs_publishing_bookmark = \"${GLOBALREVS_PUBLISHING_BOOKMARK}\"\nCONFIG\nfi\n\nif [[ -n \"${GLOBALREVS_SMALL_REPO_ID:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nglobalrevs_small_repo_id = ${GLOBALREVS_SMALL_REPO_ID}\nCONFIG\nfi\n\nif [[ -n \"${POPULATE_GIT_MAPPING:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\npopulate_git_mapping=true\nCONFIG\nfi\n\nif [[ -n \"${ALLOW_CHANGE_XREPO_MAPPING_EXTRA:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nallow_change_xrepo_mapping_extra=true\nCONFIG\nfi\n\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n\n[hook_manager_params]\ndisable_acl_checker=true\nCONFIG\n\nif [[ -n \"${DISALLOW_NON_PUSHREBASE:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[push]\npure_push_allowed = false\nCONFIG\nelse\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[push]\npure_push_allowed = true\nCONFIG\nfi\n\nif [[ -n \"${CACHE_WARMUP_BOOKMARK:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[cache_warmup]\nbookmark=\"$CACHE_WARMUP_BOOKMARK\"\nCONFIG\n\n  if [[ -n \"${CACHE_WARMUP_MICROWAVE:-}\" ]]; then\n    cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nmicrowave_preload = true\nCONFIG\n  fi\nfi\n\n\nif [[ -n \"${LFS_THRESHOLD:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[lfs]\nthreshold=$LFS_THRESHOLD\nrollout_percentage=${LFS_ROLLOUT_PERCENTAGE:-100}\ngenerate_lfs_blob_in_hg_sync_job=${LFS_BLOB_HG_SYNC_JOB:-true}\nCONFIG\nfi\n\nwrite_infinitepush_config \"$reponame\"\n\ncat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n  [derived_data_config]\n  enabled_config_name = \"default\"\n  scuba_table = \"file://$TESTTMP/derived_data_scuba.json\"\nCONFIG\n\nif [[ -n \"${ENABLED_DERIVED_DATA:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[derived_data_config.available_configs.default]\ntypes = $ENABLED_DERIVED_DATA\nCONFIG\nelse\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[derived_data_config.available_configs.default]\ntypes=[\"blame\", \"changeset_info\", \"deleted_manifest\", \"fastlog\", \"filenodes\", \"fsnodes\", \"unodes\", \"hgchangesets\", \"skeleton_manifests\", \"bssm\"]\nCONFIG\nfi\n\nif [[ -n \"${BLAME_VERSION}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nblame_version = $BLAME_VERSION\nCONFIG\nfi\n\nif [[ -n \"${HG_SET_COMMITTER_EXTRA}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nhg_set_committer_extra = true\nCONFIG\nfi\n\nif [[ -n \"${SEGMENTED_CHANGELOG_ENABLE:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[segmented_changelog_config]\nenabled=true\nheads_to_include = [\n   { bookmark = \"master_bookmark\" },\n]\nskip_dag_load_at_startup=true\nCONFIG\nfi\n\nif [[ -n \"${BACKUP_FROM:-}\" ]]; then\n  cat >> \"repo_definitions/$reponame_urlencoded/server.toml\" <<CONFIG\nbackup_source_repo_name=\"$BACKUP_FROM\"\nCONFIG\nfi\n\nif [[ -n \"${ENABLE_API_WRITES:-}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[source_control_service]\npermit_writes = true\n[[bookmarks]]\nregex=\".*\"\nhooks_skip_ancestors_of=[\"master_bookmark\"]\nCONFIG\nfi\n\nif [[ -n \"${SPARSE_PROFILES_LOCATION}\" ]]; then\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[sparse_profiles_config]\nsparse_profiles_location=\"$SPARSE_PROFILES_LOCATION\"\nCONFIG\nfi\n\nif [[ -n \"${COMMIT_SCRIBE_CATEGORY:-${BOOKMARK_SCRIBE_CATEGORY:-}}\" ]]; then\n  cat >> \"repos/$reponame/server.toml\" <<CONFIG\n[update_logging_config]\nCONFIG\nfi\n\nif [[ -n \"${BOOKMARK_SCRIBE_CATEGORY:-}\" ]]; then\n  cat >> \"repos/$reponame/server.toml\" <<CONFIG\nbookmark_logging_destination = { scribe = { scribe_category = \"$BOOKMARK_SCRIBE_CATEGORY\" } }\nCONFIG\nfi\nif [[ -n \"${COMMIT_SCRIBE_CATEGORY:-}\" ]]; then\n    cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nnew_commit_logging_destination = { scribe = { scribe_category = \"$COMMIT_SCRIBE_CATEGORY\" } }\nCONFIG\nfi\n\n}\n\nfunction write_infinitepush_config {\n  local reponame=\"$1\"\n  local reponame_urlencoded\n  reponame_urlencoded=$(urlencode encode \"$reponame\")\n\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[infinitepush]\nCONFIG\n\n  if [[ -n \"${INFINITEPUSH_ALLOW_WRITES:-}\" ]] || \\\n     [[ -n \"${INFINITEPUSH_NAMESPACE_REGEX:-}\" ]];\n  then\n    namespace=\"\"\n    if [[ -n \"${INFINITEPUSH_NAMESPACE_REGEX:-}\" ]]; then\n      namespace=\"namespace_pattern=\\\"$INFINITEPUSH_NAMESPACE_REGEX\\\"\"\n    fi\n\n    cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\nallow_writes = ${INFINITEPUSH_ALLOW_WRITES:-true}\n${namespace}\nCONFIG\n  fi\n}\n\nfunction register_hook {\n  hook_name=\"$1\"\n\n  shift 1\n  EXTRA_CONFIG_DESCRIPTOR=\"\"\n  if [[ $# -gt 0 ]]; then\n    EXTRA_CONFIG_DESCRIPTOR=\"$1\"\n  fi\n\n  reponame_urlencoded=\"$(urlencode encode \"$REPONAME\")\"\n  (\n    cat <<CONFIG\n[[bookmarks.hooks]]\nhook_name=\"$hook_name\"\n[[hooks]]\nname=\"$hook_name\"\nCONFIG\n    [ -n \"$EXTRA_CONFIG_DESCRIPTOR\" ] && cat \"$EXTRA_CONFIG_DESCRIPTOR\"\n  ) >> \"repos/$reponame_urlencoded/server.toml\"\n}\n\nfunction register_hook_limit_filesize_global_limit {\nglobal_limit=$1\nshift 1\n\nregister_hook limit_filesize <(\ncat <<CONF\nconfig_string_lists={filesize_limits_regexes=[\".*\"]}\nconfig_int_lists={filesize_limits_values=[$global_limit]}\n$@\nCONF\n)\n\n}\n\nfunction backfill_mapping {\n  GLOG_minloglevel=5 \"$MONONOKE_BACKFILL_MAPPING\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction blobimport {\n  local always_log=\n  if [[ \"$1\" == \"--log\" ]]; then\n    always_log=1\n    shift\n  fi\n  input=\"$1\"\n  output=\"$2\"\n  shift 2\n  #   input (repo in new format)\n  # --debugexportrevlog--> revlog (repo in old format)\n  # --blobimport--> Mononoke repo\n  local revlog=\"$input/revlog-export\"\n  rm -rf \"$revlog\"\n  hgedenapi --cwd \"$input\" debugexportrevlog revlog-export\n  mkdir -p \"$output\"\n  $MONONOKE_BLOBIMPORT \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n     --repo-id $REPOID \\\n     --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n     \"$revlog/.hg\" \\\n     \"$@\" > \"$TESTTMP/blobimport.out\" 2>&1\n  BLOBIMPORT_RC=\"$?\"\n  if [[ $BLOBIMPORT_RC -ne 0 ]]; then\n    cat \"$TESTTMP/blobimport.out\"\n    # set exit code, otherwise previous cat sets it to 0\n    return \"$BLOBIMPORT_RC\"\n  elif [[ -n \"$always_log\" ]]; then\n    cat \"$TESTTMP/blobimport.out\"\n  fi\n}\n\nfunction bonsai_verify {\n  GLOG_minloglevel=5 \"$MONONOKE_BONSAI_VERIFY\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction s_client {\n    /usr/local/fbcode/platform010/bin/openssl s_client \\\n        -connect \"$(mononoke_address)\" \\\n        -CAfile \"${TEST_CERTDIR}/root-ca.crt\" \\\n        -cert \"${TEST_CERTDIR}/client0.crt\" \\\n        -key \"${TEST_CERTDIR}/client0.key\" \\\n        -ign_eof \"$@\"\n}\n\nfunction scs {\n  if [[ ! -d \"$SCRIBE_LOGS_DIR\" ]]; then\n    mkdir \"$SCRIBE_LOGS_DIR\"\n  fi\n\n  rm -f \"$TESTTMP/scs_server_addr.txt\"\n  GLOG_minloglevel=5 \\\n    THRIFT_TLS_SRV_CERT=\"$TEST_CERTDIR/localhost.crt\" \\\n    THRIFT_TLS_SRV_KEY=\"$TEST_CERTDIR/localhost.key\" \\\n    THRIFT_TLS_CL_CA_PATH=\"$TEST_CERTDIR/root-ca.crt\" \\\n    THRIFT_TLS_CL_CERT_PATH=\"$TEST_CERTDIR/proxy.crt\" \\\n    THRIFT_TLS_CL_KEY_PATH=\"$TEST_CERTDIR/proxy.key\" \\\n    THRIFT_TLS_TICKETS=\"$TEST_CERTDIR/server.pem.seeds\" \\\n    \"$SCS_SERVER\" \"$@\" \\\n    --host \"$LOCALIP\" \\\n    --port 0 \\\n    --log-level DEBUG \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --bound-address-file \"$TESTTMP/scs_server_addr.txt\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" >> \"$TESTTMP/scs_server.out\" 2>&1 &\n  export SCS_SERVER_PID=$!\n  echo \"$SCS_SERVER_PID\" >> \"$DAEMON_PIDS\"\n}\n\nfunction land_service {\n  if [[ ! -d \"$SCRIBE_LOGS_DIR\" ]]; then\n    mkdir \"$SCRIBE_LOGS_DIR\"\n  fi\n  rm -f \"$TESTTMP/land_service_addr.txt\"\n  GLOG_minloglevel=5 \\\n    THRIFT_TLS_SRV_CERT=\"$TEST_CERTDIR/localhost.crt\" \\\n    THRIFT_TLS_SRV_KEY=\"$TEST_CERTDIR/localhost.key\" \\\n    THRIFT_TLS_CL_CA_PATH=\"$TEST_CERTDIR/root-ca.crt\" \\\n    THRIFT_TLS_TICKETS=\"$TEST_CERTDIR/server.pem.seeds\" \\\n    \"$LAND_SERVICE\" \"$@\" \\\n    --host \"$LOCALIP\" \\\n    --port 0 \\\n    --log-level DEBUG \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --scribe-logging-directory \"$TESTTMP/scribe_logs\" \\\n    --bound-address-file \"$TESTTMP/land_service_addr.txt\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" >> \"$TESTTMP/land_service.out\" 2>&1 &\n  export LAND_SERVICE_PID=$!\n  echo \"$LAND_SERVICE_PID\" >> \"$DAEMON_PIDS\"\n}\n\nfunction wait_for_scs {\n  export SCS_PORT\n  wait_for_server \"SCS server\" SCS_PORT \"$TESTTMP/scs_server.out\" \\\n    \"${MONONOKE_SCS_START_TIMEOUT:-\"$MONONOKE_SCS_DEFAULT_START_TIMEOUT\"}\" \"$TESTTMP/scs_server_addr.txt\" \\\n    scsc repos\n}\n\n# Because of warm bookmark cache the SCS bookmark updates are async.\n# This function allows to wait for them.\nfunction wait_for_bookmark_update() {\n  local repo=$1\n  local bookmark=$2\n  local target=$3\n  local attempt=1\n  sleep 2\n  while [[ \"$(scsc lookup -R $repo -B $bookmark)\" != \"$target\" ]]\n  do\n    attempt=$((attempt + 1))\n    if [[ $attempt -gt 5 ]]\n    then\n        echo \"bookmark move of $bookmark to $target has not happened\"\n        return 1\n    fi\n    sleep 2\n  done\n}\n\nfunction wait_for_bookmark_delete() {\n  local repo=$1\n  local bookmark=$2\n  local attempt=1\n  sleep 2\n  while scsc lookup -R $repo -B $bookmark 2>/dev/null\n  do\n    attempt=$((attempt + 1))\n    if [[ $attempt -gt 5 ]]\n    then\n       echo \"bookmark deletion of $bookmark has not happened\"\n       return 1\n    fi\n    sleep 2\n  done\n}\n\nfunction get_bookmark_value_edenapi {\n  local repo=\"$1\"\n  local bookmark=\"$2\"\n  REPONAME=\"$repo\" hgedenapi debugapi -e bookmarks -i \"[\\\"$bookmark\\\"]\" | jq \".$bookmark\"\n}\n\nfunction wait_for_bookmark_move_away_edenapi() {\n  local repo=\"$1\"\n  local bookmark=\"$2\"\n  local prev=\"$3\"\n  local attempt=1\n  sleep 1\n  flush_mononoke_bookmarks\n  while [[ \"$(get_bookmark_value_edenapi \"$repo\" \"$bookmark\")\" == \"$prev\" ]]\n  do\n    attempt=$((attempt + 1))\n    if [[ $attempt -gt 30 ]]\n    then\n        echo \"bookmark move of $bookmark away from $prev has not happened\"\n        return 1\n    fi\n    sleep 2\n    flush_mononoke_bookmarks\n  done\n}\n\n\nfunction wait_for_land_service {\n  export LAND_SERVICE_PORT\n  wait_for_server \"Land service\" LAND_SERVICE_PORT \"$TESTTMP/land_service.out\" \\\n    \"${MONONOKE_LAND_SERVICE_START_TIMEOUT:-\"$MONONOKE_LAND_SERVICE_DEFAULT_START_TIMEOUT\"}\" \"$TESTTMP/land_service_addr.txt\" \\\n    sleep 5\n}\n\nfunction start_and_wait_for_scs_server {\n  scs \"$@\"\n  wait_for_scs\n}\n\nfunction start_and_wait_for_land_service {\n  land_service \"$@\"\n  wait_for_land_service\n}\n\nfunction megarepo_async_worker {\n  GLOG_minloglevel=5 \"$ASYNC_REQUESTS_WORKER\" \"$@\" \\\n    --log-level INFO \\\n    --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n    --scuba-dataset \"file://$TESTTMP/async-worker.json\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" >> \"$TESTTMP/megarepo_async_worker.out\" 2>&1 &\n  export MEGAREPO_ASYNC_WORKER_PID=$!\n  echo \"$MEGAREPO_ASYNC_WORKER_PID\" >> \"$DAEMON_PIDS\"\n}\n\nfunction scsc_as {\n  local name=\"$1\"\n  shift\n  GLOG_minloglevel=5 \\\n    THRIFT_TLS_CL_CERT_PATH=\"$TEST_CERTDIR/$name.crt\" \\\n    THRIFT_TLS_CL_KEY_PATH=\"$TEST_CERTDIR/$name.key\" \\\n    THRIFT_TLS_CL_CA_PATH=\"$TEST_CERTDIR/root-ca.crt\" \\\n    \"$SCS_CLIENT\" --host \"$LOCALIP:$SCS_PORT\" \"$@\"\n}\n\nfunction scsc {\n  scsc_as client0 \"$@\"\n}\n\nfunction lfs_health {\n  local poll proto bound_addr_file\n  poll=\"$1\"; shift\n  proto=\"$1\";shift\n  bound_addr_file=\"$1\"; shift\n  \"$poll\" \"${proto}://$(cat \"$bound_addr_file\")/health_check\"\n}\n\nfunction lfs_server {\n  local uri log opts args proto poll lfs_server_pid bound_addr_file lfs_instance instance_count_file\n  proto=\"http\"\n  poll=\"curl\"\n\n  # Used to separate log files etc when multiple lfs servers started in a test\n  instance_count_file=\"$TESTTMP/lfs_instance_count.txt\"\n\n  # lfs_server is started from subshells in the .t tests\n  # so use a file rather than env var to keep count\n  if [[ ! -r \"$instance_count_file\" ]]; then\n    echo 0 > \"$instance_count_file\"\n  fi\n\n  lfs_instance=$(($(cat \"$instance_count_file\") + 1))\n  echo \"$lfs_instance\" > \"$instance_count_file\"\n\n  log=\"${TESTTMP}/lfs_server.$lfs_instance\"\n\n  bound_addr_file=\"$TESTTMP/lfs_server_addr.$lfs_instance\"\n  rm -f \"$bound_addr_file\"\n\n  opts=(\n    \"${CACHE_ARGS[@]}\"\n    \"${COMMON_ARGS[@]}\"\n    --mononoke-config-path \"$TESTTMP/mononoke-config\"\n    --listen-port 0\n    --bound-address-file \"$bound_addr_file\"\n    --test-friendly-logging\n  )\n  args=()\n\n  while [[ \"$#\" -gt 0 ]]; do\n    if [[ \"$1\" = \"--upstream\" ]]; then\n      shift\n      args=(\"${args[@]}\" --upstream-url \"$1\") # Upstream URL is now a named parameter.\n      shift\n    elif [[ \"$1\" = \"--live-config\" ]]; then\n      opts=(\"${opts[@]}\" \"$1\" \"$2\") # --live-config-fetch-interval is no longer used.\n      shift\n      shift\n    elif [[ \"$1\" = \"--tls\" ]]; then\n      proto=\"https\"\n      poll=\"sslcurl\"\n      opts=(\n        \"${opts[@]}\"\n        --tls-ca \"$TEST_CERTDIR/root-ca.crt\"\n        --tls-private-key \"$TEST_CERTDIR/localhost.key\"\n        --tls-certificate \"$TEST_CERTDIR/localhost.crt\"\n        --tls-ticket-seeds \"$TEST_CERTDIR/server.pem.seeds\"\n      )\n      shift\n    elif\n      [[ \"$1\" = \"--always-wait-for-upstream\" ]] ||\n      [[ \"$1\" = \"--readonly\" ]] ||\n      [[ \"$1\" = \"--git-blob-upload-allowed\" ]]\n    then\n      opts=(\"${opts[@]}\" \"$1\")\n      shift\n    elif\n      [[ \"$1\" = \"--scuba-dataset\" ]] ||\n      [[ \"$1\" = \"--max-upload-size\" ]]\n    then\n      opts=(\"${opts[@]}\" \"$1\" \"$2\")\n      shift\n      shift\n    elif [[ \"$1\" = \"--log\" ]]; then\n      shift\n      log=\"$1\"\n      shift\n    else\n      echo \"invalid argument: $1\" >&2\n      return 1\n    fi\n  done\n\n  if [[ \"$proto\" = \"https\" ]]; then\n    # need to use localhost to match test certs\n    listen_host=\"localhost\"\n  else\n    # use local IP as its more stable for test expectations when localhost is multihomed\n    listen_host=\"$(mononoke_host)\"\n  fi\n  opts=(\"${opts[@]}\" \"--listen-host\" \"$listen_host\")\n\n  GLOG_minloglevel=5 \"$LFS_SERVER\" \\\n    \"${opts[@]}\" \"${args[@]}\" >> \"$log\" 2>&1 &\n\n  lfs_server_pid=\"$!\"\n  echo \"$lfs_server_pid\" >> \"$DAEMON_PIDS\"\n\n  export LFS_PORT\n  wait_for_server \"lfs_server\" \"LFS_PORT\" \"$log\" \\\n    \"${MONONOKE_LFS_START_TIMEOUT:-\"$MONONOKE_LFS_DEFAULT_START_TIMEOUT\"}\" \"$bound_addr_file\" \\\n    lfs_health \"$poll\" \"$proto\" \"$bound_addr_file\"\n\n  export LFS_HOST_PORT\n  LFS_HOST_PORT=\"$listen_host:$LFS_PORT\"\n  uri=\"${proto}://$LFS_HOST_PORT\"\n  echo \"$uri\"\n\n  cp \"$log\" \"$log.saved\"\n  truncate -s 0 \"$log\"\n}\n\n# Run an hg binary configured with the settings required to talk to Mononoke\nfunction hgmn {\n  reponame_urlencoded=\"$(urlencode encode \"$REPONAME\")\"\n  hg --config paths.default=\"mononoke://$(mononoke_address)/$reponame_urlencoded\" \"$@\"\n}\n\n# Run an hg binary configured with the settings require to talk to Mononoke\n# via EdenAPI\nfunction hgedenapi {\n  hgmn \\\n    --config \"edenapi.url=https://localhost:$MONONOKE_SOCKET/edenapi\" \\\n    --config \"edenapi.enable=true\" \\\n    --config \"remotefilelog.http=true\" \\\n    --config \"remotefilelog.reponame=$REPONAME\" \\\n    \"$@\"\n}\n\nfunction hginit_treemanifest() {\n  hg init \"$@\"\n  cat >> \"$1\"/.hg/hgrc <<EOF\n[extensions]\ntreemanifest=!\ntreemanifestserver=\nremotefilelog=\nsmartlog=\nclienttelemetry=\n[treemanifest]\nflatcompat=False\nserver=True\nsendtrees=True\ntreeonly=True\n[remotefilelog]\nreponame=$1\ncachepath=$TESTTMP/cachepath\nserver=True\nshallowtrees=True\n[workingcopy]\nruststatus=False\nuse-rust=False\n[status]\nuse-rust=False\nEOF\n}\n\nfunction hgclone_treemanifest() {\n  hg clone -q --shallow --config remotefilelog.reponame=\"$2\" --config extensions.treemanifest= --config treemanifest.treeonly=True \"$@\"\n  cat >> \"$2\"/.hg/hgrc <<EOF\n[extensions]\ntreemanifest=\nremotefilelog=\nsmartlog=\nclienttelemetry=\n[treemanifest]\nflatcompat=False\nsendtrees=True\ntreeonly=True\n[remotefilelog]\nreponame=$2\ncachepath=$TESTTMP/cachepath\nshallowtrees=True\nEOF\n}\n\nfunction hgmn_init() {\n  hg init \"$@\"\n  cat >> \"$1\"/.hg/hgrc <<EOF\n[extensions]\ntreemanifest=\nremotefilelog=\nremotenames=\nsmartlog=\nclienttelemetry=\nlz4revlog=\n[treemanifest]\nflatcompat=False\nsendtrees=True\ntreeonly=True\n[remotefilelog]\nreponame=$1\ncachepath=$TESTTMP/cachepath\nshallowtrees=True\nEOF\n}\n\nfunction hgmn_clone() {\n  quiet hgmn clone --shallow  --config remotefilelog.reponame=\"$REPONAME\" \"$@\" --config extensions.treemanifest= --config treemanifest.treeonly=True --config extensions.lz4revlog= && \\\n  cat >> \"$2\"/.hg/hgrc <<EOF\n[extensions]\ntreemanifest=\nremotefilelog=\nremotenames=\nsmartlog=\nclienttelemetry=\nlz4revlog=\n[treemanifest]\nflatcompat=False\nsendtrees=True\ntreeonly=True\n[remotefilelog]\nreponame=$REPONAME\ncachepath=$TESTTMP/cachepath\nshallowtrees=True\nEOF\n}\n\nfunction enableextension() {\n  cat >> .hg/hgrc <<EOF\n[extensions]\n$1=\nEOF\n}\n\nfunction setup_hg_server() {\n  cat >> .hg/hgrc <<EOF\n[extensions]\ncommitextras=\ntreemanifest=!\ntreemanifestserver=\nremotefilelog=\nclienttelemetry=\n[treemanifest]\nserver=True\n[remotefilelog]\nserver=True\nshallowtrees=True\nEOF\n}\n\nfunction setup_hg_client() {\n  cat >> .hg/hgrc <<EOF\n[extensions]\ntreemanifest=\nremotefilelog=\nclienttelemetry=\n[treemanifest]\nflatcompat=False\nserver=False\ntreeonly=True\n[remotefilelog]\nserver=False\nreponame=$REPONAME\n[mutation]\nrecord=False\nEOF\n}\n\n# Does all the setup necessary for hook tests\nfunction hook_test_setup() {\n  setup_mononoke_config\n  cd \"$TESTTMP/mononoke-config\" || exit 1\n\n  reponame_urlencoded=\"$(urlencode encode \"$REPONAME\")\"\n  HOOKBOOKMARK=\"${HOOKBOOKMARK:-master_bookmark}\"\n  cat >> \"repos/$reponame_urlencoded/server.toml\" <<CONFIG\n[[bookmarks]]\nname=\"$HOOKBOOKMARK\"\nCONFIG\n\n  while [[ \"$#\" -gt 0 ]]; do\n    HOOK_NAME=\"$1\"\n    shift 1\n    EXTRA_CONFIG_DESCRIPTOR=\"\"\n    if [[ $# -gt 0 ]]; then\n      EXTRA_CONFIG_DESCRIPTOR=\"$1\"\n      shift 1\n    fi\n    register_hook \"$HOOK_NAME\" \"$EXTRA_CONFIG_DESCRIPTOR\"\n  done\n\n  setup_common_hg_configs\n  cd \"$TESTTMP\" || exit 1\n\n  cat >> \"$HGRCPATH\" <<EOF\n[ui]\nssh=\"$DUMMYSSH\"\nEOF\n\n  hg init repo-hg\n  cd repo-hg || exit 1\n  setup_hg_server\n  drawdag <<EOF\nC\n|\nB\n|\nA\nEOF\n\n  hg bookmark \"$HOOKBOOKMARK\" -r tip\n\n  cd ..\n  blobimport repo-hg/.hg \"$REPONAME\"\n\n  start_and_wait_for_mononoke_server\n\n  hgclone_treemanifest ssh://user@dummy/repo-hg repo2 --noupdate --config extensions.remotenames= -q\n  cd repo2 || exit 1\n  setup_hg_client\n  cat >> .hg/hgrc <<EOF\n[extensions]\npushrebase =\namend=\nremotenames =\nEOF\n}\n\nfunction setup_hg_lfs() {\n  cat >> .hg/hgrc <<EOF\n[extensions]\nlfs=\n[lfs]\nurl=$1\nthreshold=$2\nusercache=$3\nEOF\n}\n\nfunction setup_hg_modern_lfs() {\n  cat >> .hg/hgrc <<EOF\n[remotefilelog]\nlfs=True\nuseruststore=True\ngetpackversion = 2\n[worker]\nrustworkers=True\n[extensions]\nlfs=!\n[lfs]\nurl=$1\nthreshold=$2\nbackofftimes=0\nEOF\n}\n\nfunction setup_hg_edenapi() {\n  local repo\n  repo=\"$1\"\n\n  cat >> .hg/hgrc <<EOF\n[edenapi]\nenable=true\nurl=https://localhost:$MONONOKE_SOCKET/edenapi/$repo\n[remotefilelog]\nhttp=True\nuseruststore=True\ngetpackversion = 2\n[treemanifest]\nhttp=True\nuseruststore=True\n[auth]\nedenapi.cert=$TEST_CERTDIR/client0.crt\nedenapi.key=$TEST_CERTDIR/client0.key\nedenapi.prefix=localhost\nedenapi.schemes=https\nedenapi.cacerts=$TEST_CERTDIR/root-ca.crt\nEOF\n}\n\nfunction aliasverify() {\n  mode=\"$1\"\n  alias_type=\"$2\"\n  shift 2\n  GLOG_minloglevel=5 \"$MONONOKE_ALIAS_VERIFY\" --repo-id $REPOID \\\n     \"${CACHE_ARGS[@]}\" \\\n     \"${COMMON_ARGS[@]}\" \\\n     --mononoke-config-path \"$TESTTMP/mononoke-config\" \\\n     --alias-type \"$alias_type\" \\\n     --mode \"$mode\" \"$@\"\n}\n\n# Without rev\nfunction tglogpnr() {\n  hg log -G -T \"{node|short} {phase} '{desc}' {bookmarks} {remotenames}\" \"$@\"\n}\n\nfunction mkcommit() {\n   echo \"$1\" > \"$1\"\n   hg add \"$1\"\n   hg ci -m \"$1\"\n}\n\nfunction mkcommitedenapi() {\n   echo \"$1\" > \"$1\"\n   hgedenapi add \"$1\"\n   hgedenapi ci -m \"$1\"\n}\n\nfunction mkgitcommit() {\n  echo \"$1\" > \"$1\"\n  git add \"$1\"\n  git commit -aqm \"$1\"\n}\n\nfunction enable_replay_verification_hook {\n\ncat >> \"$TESTTMP\"/replayverification.py <<EOF\ndef verify_replay(ui, repo, *args, **kwargs):\n     EXP_ONTO = \"EXPECTED_ONTOBOOK\"\n     EXP_HEAD = \"EXPECTED_REBASEDHEAD\"\n     expected_book = kwargs.get(EXP_ONTO)\n     expected_head = kwargs.get(EXP_HEAD)\n     actual_book = kwargs.get(\"key\")\n     actual_head = kwargs.get(\"new\")\n     allowed_replay_books = ui.configlist(\"facebook\", \"hooks.unbundlereplaybooks\", [])\n     # If there is a problem with the mononoke -> hg sync job we need a way to\n     # quickly disable the replay verification to let unsynced bundles\n     # through.\n     # Disable this hook by placing a file in the .hg directory.\n     if repo.localvfs.exists('REPLAY_BYPASS'):\n         ui.note(\"[ReplayVerification] Bypassing check as override file is present\\n\")\n         return 0\n     if expected_book is None and expected_head is None:\n         # We are allowing non-unbundle-replay pushes to go through\n         return 0\n     if allowed_replay_books and actual_book not in allowed_replay_books:\n         ui.warn(\"[ReplayVerification] only allowed to unbundlereplay on %r\\n\" % (allowed_replay_books, ))\n         return 1\n     expected_head = expected_head or None\n     actual_head = actual_head or None\n     if expected_book == actual_book and expected_head == actual_head:\n        ui.note(\"[ReplayVerification] Everything seems in order\\n\")\n        return 0\n\n     ui.warn(\"[ReplayVerification] Expected: (%r, %r). Actual: (%r, %r)\\n\" % (expected_book, expected_head, actual_book, actual_head))\n     return 1\nEOF\n\ncat >> \"$TESTTMP\"/repo_lock.py << EOF\ndef run(ui, repo, *args, **kwargs):\n   \"\"\"Repo is locked for everything except replays\n   In-process style hook.\"\"\"\n   if kwargs.get(\"EXPECTED_ONTOBOOK\"):\n       return 0\n   ui.warn(\"[RepoLock] Repo locked for non-unbundlereplay pushes\\n\")\n   return 1\nEOF\n\n[[ -f .hg/hgrc ]] || echo \".hg/hgrc does not exists!\"\n\ncat >>.hg/hgrc <<CONFIG\n[hooks]\nprepushkey = python:$TESTTMP/replayverification.py:verify_replay\nprepushkey.lock = python:$TESTTMP/repo_lock.py:run\nCONFIG\n\n}\n\nfunction get_bonsai_bookmark() {\n  local bookmark repoid_backup\n  repoid_backup=\"$REPOID\"\n  export REPOID=\"$1\"\n  bookmark=\"$2\"\n  mononoke_admin bookmarks get -c bonsai \"$bookmark\" 2>/dev/null | cut -d' ' -f2\n  export REPOID=\"$repoid_backup\"\n}\n\nfunction add_synced_commit_mapping_entry() {\n  local small_repo_id large_repo_id small_bcs_id large_bcs_id version\n  small_repo_id=\"$1\"\n  small_bcs_id=\"$2\"\n  large_repo_id=\"$3\"\n  large_bcs_id=\"$4\"\n  version=\"$5\"\n  quiet mononoke_admin_source_target \"$small_repo_id\" \"$large_repo_id\" crossrepo insert rewritten --source-hash \"$small_bcs_id\" \\\n    --target-hash \"$large_bcs_id\" \\\n    --version-name \"$version\"\n}\n\nfunction read_blobstore_wal_queue_size() {\n  if [[ -n \"$DB_SHARD_NAME\" ]]; then\n    echo \"SELECT COUNT(*) FROM blobstore_write_ahead_log;\" | db \"$DB_SHARD_NAME\" 2> /dev/null | grep -v COUNT\n  else\n    local attempts timeout ret\n    timeout=\"100\"\n    attempts=\"$((timeout * 10))\"\n    for _ in $(seq 1 $attempts); do\n      ret=\"$(sqlite3 \"$TESTTMP/blobstore_sync_queue/sqlite_dbs\" \"select count(*) from blobstore_write_ahead_log\" 2>/dev/null)\"\n      if [[ -n \"$ret\" ]]; then\n        echo \"$ret\"\n        return 0\n      fi\n      sleep 0.1\n    done\n    return 1\n  fi\n\n}\n\nfunction log() {\n  # Prepend \"$\" to the end of the log output to prevent having trailing whitespaces\n  hg log -G -T \"{desc} [{phase};rev={rev};{node|short}] {remotenames}\" \"$@\" | sed 's/^[ \\t]*$/$/'\n}\n\n# Default setup that many of the test use\nfunction default_setup_pre_blobimport() {\n  setup_common_config \"$@\"\n\n  cd \"$TESTTMP\" || exit 1\n\n  cat >> \"$HGRCPATH\" <<EOF\n[ui]\nssh=\"$DUMMYSSH\"\n[extensions]\namend=\nEOF\n\nhg init repo-hg\ncd repo-hg || exit 1\nsetup_hg_server\ndrawdag <<EOF\nC\n|\nB\n|\nA\nEOF\n\n  hg bookmark master_bookmark -r tip\n\n  echo \"hg repo\"\n  log -r \":\"\n\n  cd .. || exit 1\n}\n\nfunction default_setup_blobimport() {\n  default_setup_pre_blobimport \"$@\"\n  echo \"blobimporting\"\n  blobimport repo-hg/.hg \"$REPONAME\"\n}\n\nfunction default_setup() {\n  default_setup_blobimport \"$BLOB_TYPE\"\n  echo \"starting Mononoke\"\n\n  start_and_wait_for_mononoke_server \"$@\"\n\n  echo \"cloning repo in hg client 'repo2'\"\n  hgclone_treemanifest ssh://user@dummy/repo-hg repo2 --noupdate --config extensions.remotenames= -q\n  cd repo2 || exit 1\n  setup_hg_client\n  cat >> .hg/hgrc <<EOF\n[extensions]\npushrebase =\nremotenames =\nEOF\n}\n\nfunction gitimport() {\n  log=\"$TESTTMP/gitimport.out\"\n\n  \"$MONONOKE_GITIMPORT\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction git() {\n  local date name email\n  date=\"01/01/0000 00:00 +0000\"\n  name=\"mononoke\"\n  email=\"mononoke@mononoke\"\n  GIT_COMMITTER_DATE=\"${GIT_COMMITTER_DATE:-$date}\" \\\n  GIT_COMMITTER_NAME=\"$name\" \\\n  GIT_COMMITTER_EMAIL=\"$email\" \\\n  GIT_AUTHOR_DATE=\"${GIT_AUTHOR_DATE:-$date}\" \\\n  GIT_AUTHOR_NAME=\"$name\" \\\n  GIT_AUTHOR_EMAIL=\"$email\" \\\n  command git \"$@\"\n}\n\nfunction git_set_only_author() {\n  local date name email\n  date=\"01/01/0000 00:00 +0000\"\n  name=\"mononoke\"\n  email=\"mononoke@mononoke\"\n  GIT_AUTHOR_DATE=\"$date\" \\\n  GIT_AUTHOR_NAME=\"$name\" \\\n  GIT_AUTHOR_EMAIL=\"$email\" \\\n  command git \"$@\"\n}\n\nfunction summarize_scuba_json() {\n  local interesting_tags\n  local key_spec\n  interesting_tags=\"$1\"\n  shift\n  key_spec=\"\"\n  for key in \"$@\"\n  do\n     key_spec=\"$key_spec + (if (${key} != null) then {${key##*.}: ${key}} else {} end)\"\n  done\n  jq -S \"if (.normal.log_tag | match(\\\"^($interesting_tags)\\$\\\")) then ${key_spec:3} else empty end\"\n}\n\nif [ -z \"$HAS_FB\" ]; then\n  function format_single_scuba_sample() {\n    jq -S .\n  }\n\n  function format_single_scuba_sample_strip_server_info {\n      jq -S 'del(.[].server_tier, .[].tw_task_id, .[].tw_handle)'\n  }\nfi\n\nfunction segmented_changelog_tailer_reseed() {\n  \"$MONONOKE_SEGMENTED_CHANGELOG_TAILER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    --force-reseed \\\n    \"$@\"\n}\n\nfunction segmented_changelog_tailer_once() {\n  \"$MONONOKE_SEGMENTED_CHANGELOG_TAILER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    --once \\\n    \"$@\"\n}\n\nfunction background_segmented_changelog_tailer() {\n  out_file=$1\n  shift\n  # short delay here - we don't want to wait too much during tests\n  \"$MONONOKE_SEGMENTED_CHANGELOG_TAILER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\" >> \"$TESTTMP/$out_file\" 2>&1 &\n  pid=$!\n  echo \"$pid\" >> \"$DAEMON_PIDS\"\n}\n\nfunction microwave_builder() {\n  \"$MONONOKE_MICROWAVE_BUILDER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction backfill_derived_data() {\n  \"$MONONOKE_BACKFILL_DERIVED_DATA\" \\\n    --debug \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction backfill_derived_data_multiple_repos() {\n  IFS=':' read -r -a ids <<< \"${REPOS[*]}\"\n  \"$MONONOKE_BACKFILL_DERIVED_DATA\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    \"${ids[@]}\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction hook_tailer() {\n  \"$MONONOKE_HOOK_TAILER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\n# quiet <command> - run command and supress all output in case of success\n#\n# This helper function allows to supress overly verbose logging when there\n# are no errors but print all the useful stacktraces when there are errors.\n#\n# The function always returns the original command return code.\n#\n# The function behaviour can be tweaked further by tweaking the following env\n# variables:\n# * QUIET_LOGGING_LOG_FILE - the file where the command output is stored (default: $TESTTMP/quiet.last.log)\n# * EXPECTED_RC - the return code that's expected and considered success (default: 0)\nfunction quiet() {\n  local log=${QUIET_LOGGING_LOG_FILE:=\"$TESTTMP/quiet.last.log\"}\n  \"$@\" >\"$log\" 2>&1\n  ret=\"$?\"\n  expected_ret=${EXPECTED_RC:=0}\n  if [[ \"$ret\" != \"$expected_ret\" ]]; then\n    cat \"$log\" >&2\n  fi\n  return \"$ret\"\n}\n\n# quiet_grep <grep_args> -- <command> - run command and supress all output in case of success\n#\n# This helper function allows to supress overly verbose logging when the output\n# matches grep expression but display full output otherwise.\n#\n# Full command output is always printed to stderr.\n#\n# The function always returns the original command return code (so if you count\n# or sort the lines of grepped output) the full output won't be affected.\n#\n# The function behaviour can be tweaked further by tweaking the following env\n# variables:\n# * QUIET_LOGGING_LOG_FILE - the file where the command output is stored (default: $TESTTMP/quiet.last.log)\nfunction quiet_grep() {\n  ret=\"$?\"\n  local log=${QUIET_LOGGING_LOG_FILE:=\"$TESTTMP/quiet.last.log\"}\n  GREP_ARGS=()\n  while [[ $# -gt 0 ]]; do\n    case $1 in\n      --)\n        shift\n        break\n        ;;\n      *)\n        GREP_ARGS+=(\"$1\")\n        shift\n        ;;\n    esac\n  done\n  \"$@\" >\"$log\" 2>&1\n  ret=\"$?\"\n  if grep \"${GREP_ARGS[@]}\" < \"$log\" 2>&1 > /dev/null; then\n    grep \"${GREP_ARGS[@]}\" < \"$log\"\n  else\n    cat \"$log\" >&2\n  fi\n  return \"$ret\"\n}\n\nfunction copy_blobstore_keys() {\n  SOURCE_REPO_ID=\"$1\"\n  shift\n  TARGET_REPO_ID=\"$1\"\n  shift\n\n  GLOG_minloglevel=5 \"$COPY_BLOBSTORE_KEYS\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --source-repo-id \"$SOURCE_REPO_ID\" \\\n    --target-repo-id \"$TARGET_REPO_ID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction streaming_clone() {\n  GLOG_minloglevel=5 \"$MONONOKE_STREAMING_CLONE\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction repo_import() {\n  log=\"$TESTTMP/repo_import.out\"\n\n  \"$MONONOKE_REPO_IMPORT\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction sqlite3() {\n  # Set a longer timeout so that we don't break if Mononoke currently has a\n  # handle on the DB.\n  command sqlite3 -cmd '.timeout 1000' \"$@\"\n}\n\nfunction merge_tunables() {\n  local new\n  new=\"$(jq -s '.[0] * .[1]' \"$MONONOKE_TUNABLES_PATH\" -)\"\n  printf \"%s\" \"$new\" > \"$MONONOKE_TUNABLES_PATH\"\n  # This may fail if Mononoke is not started. No big deal.\n  force_update_configerator >/dev/null 2>&1 || true\n}\n\nfunction init_tunables() {\n  if [[ ! -f \"$MONONOKE_TUNABLES_PATH\" ]]; then\n    cat >> \"$MONONOKE_TUNABLES_PATH\" <<EOF\n{\n  \"ints\": {\n    \"commit_graph_writes_timeout_ms\": 10000\n  }\n}\nEOF\n  fi\n}\n\n# Always initialize tunables, since they're required by our binaries to start\n# unless explicitly disabled (but we don't do that in tests).\ninit_tunables\n\nfunction packer() {\n  \"$MONONOKE_PACKER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction check_git_wc() {\n  \"$MONONOKE_CHECK_GIT_WC\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --repo-id \"$REPOID\" \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    \"$@\"\n}\n\nfunction derived_data_service() {\n  export DDS_PORT\n\n  rm -rf \"$DDS_SERVER_ADDR_FILE\"\n\n  THRIFT_TLS_SRV_CERT=\"$TEST_CERTDIR/localhost.crt\" \\\n  THRIFT_TLS_SRV_KEY=\"$TEST_CERTDIR/localhost.key\" \\\n  THRIFT_TLS_CL_CA_PATH=\"$TEST_CERTDIR/root-ca.crt\" \\\n  THRIFT_TLS_TICKETS=\"$TEST_CERTDIR/server.pem.seeds\" \\\n  GLOG_minloglevel=1 \"$DERIVED_DATA_SERVICE\" \"$@\" \\\n    -p 0 \\\n    --mononoke-config-path \"${TESTTMP}/mononoke-config\" \\\n    --bound-address-file \"$DDS_SERVER_ADDR_FILE\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" >> \"$TESTTMP/derived_data_service.out\" 2>&1 &\n\n  pid=$!\n  echo \"$pid\" >> \"$DAEMON_PIDS\"\n}\n\nfunction start_and_wait_for_dds() {\n  derived_data_service \"$@\"\n  wait_for_dds\n}\n\nfunction wait_for_dds() {\n  export DDS_PORT\n  wait_for_server \"Derived data service\" DDS_PORT \"$TESTTMP/derived_data_service.out\" \\\n    \"${MONONOKE_DDS_START_TIMEOUT:-\"$MONONOKE_DDS_DEFAULT_START_TIMEOUT\"}\" \"$DDS_SERVER_ADDR_FILE\" \\\n    derived_data_client get-status\n}\n\nfunction derived_data_client() {\n  GLOG_minloglevel=5 \\\n  THRIFT_TLS_CL_CERT_PATH=\"$TEST_CERTDIR/client0.crt\" \\\n  THRIFT_TLS_CL_KEY_PATH=\"$TEST_CERTDIR/client0.key\" \\\n  THRIFT_TLS_CL_CA_PATH=\"$TEST_CERTDIR/root-ca.crt\" \\\n  GLOG_minloglevel=5 \"$DERIVED_DATA_CLIENT\" \\\n  -h \"localhost:$DDS_PORT\" \\\n  \"$@\"\n}\n\nfunction derivation_worker() {\n  GLOG_minloglevel=5 \"$DERIVED_DATA_WORKER\" \\\n    \"${CACHE_ARGS[@]}\" \\\n    \"${COMMON_ARGS[@]}\" \\\n    --mononoke-config-path \"$TESTTMP\"/mononoke-config \"$@\"\n}\n\nfunction verify_integrity_service_health() {\n  $THRIFTDBG sendRequest getStatus \"{}\" --host \"localhost\" --port \"$VI_SERVICE_PORT\"\n}\n\nfunction verify_integrity_service() {\n  export VI_SERVICE_PORT\n  local VI_SERVICE_ADDR_FILE\n  VI_SERVICE_ADDR_FILE=\"$TESTTMP/verify_integrity_service_addr.txt\"\n  \"$VERIFY_INTEGRITY_SERVICE\" \"$@\" \\\n    --service.port 0 \\\n    --bound-address-file \"$VI_SERVICE_ADDR_FILE\" \\\n    >> \"$TESTTMP/verify_integrity_service.out\" 2>&1 &\n\n  pid=$!\n  echo \"$pid\" >> \"$DAEMON_PIDS\"\n\n  wait_for_server \"Verify Integrity service\" VI_SERVICE_PORT \"$TESTTMP/verify_integrity_service.out\" \\\n    \"${VI_SERVICE_START_TIMEOUT:-\"$VI_SERVICE_DEFAULT_START_TIMEOUT\"}\" \"$VI_SERVICE_ADDR_FILE\" \\\n    verify_integrity_service_health\n}\n\n# Wrapper for drawdag that loads all the commit aliases to env variables\n# so they can be used to refer to commits instead of hashes.\nfunction testtool_drawdag() {\n  out=\"$(mononoke_testtool drawdag \"$@\" | tee /dev/fd/2)\"\n  rc=\"${PIPESTATUS[0]}\"\n  # shellcheck disable=SC2046,SC2163,SC2086\n  export $out\n  return \"$rc\"\n}\n\nfunction start_zelos_server() {\n  PORT=$1\n  rm -f \"$TESTTMP/local-zelos\"\n  \"$ZELOSCLI\" --x server \"$PORT\" \"$TESTTMP/local-zelos\" > /dev/null 2>&1 &\n  pid=$!\n  echo \"$pid\" >> \"$DAEMON_PIDS\"\n}\n\nfunction zeloscli() {\n  PORT=$1\n  shift\n  \"$ZELOSCLI\" --server localhost:\"$PORT\" -x \"$@\" 2>/dev/null\n}\n", "num_lines": 2387}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -x\n\nif [[ -z \"$1\" ]]; then\n    echo \"Provide names of certificates (e.g. localhost client0)\"\n    exit 1\nfi\n\nif [[ \"$1\" = \"--keep-root\" ]]; then\n  echo \"Using existing root certificate\"\n  shift\nelse\n  # Generate private key for root certificate\n  openssl genrsa -out root-ca.key 2048\n  # Generate root certificate\n  openssl req -x509 -new -nodes -key root-ca.key -subj \"/C=US/ST=CA/O=TestRoot/CN=mononoke.test\" -sha256 -days 3650 -out root-ca.crt\nfi\n\n# For each certificate name:\nfor name in \"$@\"; do\n  # Generate private key for certificate\n  openssl genrsa -out \"$name.key\" 2048\n  # Generate certificate signing request for server certificate\n  openssl req -new -sha256 -key \"$name.key\" -config \"$name-openssl.cnf\" -out \"$name.csr\"\n\n  # Sign certificate with root certificate\n  if grep -q '\\[ v3_ca \\]' \"$name-openssl.cnf\"; then\n    # ...and apply custom v3_ca extensions\n    openssl x509 -extfile \"$name-openssl.cnf\" -extensions v3_ca -req -in \"$name.csr\" -CA root-ca.crt -CAkey root-ca.key -CAcreateserial -out \"$name.crt\" -days 3650 -sha256\n  else\n    openssl x509 -req -in \"$name.csr\" -CA root-ca.crt -CAkey root-ca.key -CAcreateserial -out \"$name.crt\" -days 3650 -sha256\n  fi\ndone\n", "num_lines": 39}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\nREAL_PATH=$(realpath \"$0\")\nDIR_NAME=$(dirname \"$REAL_PATH\")\nFSPROBE=${DIR_NAME}/build/cargo-target/release/fsprobe\n\nif [ ! -f \"$FSPROBE\" ]; then\n    echo \"Cannot find release version of fsprobe at $FSPROBE\"\n    echo \"Make sure you build fsprobe first by running cargo build --release in eden/scm/exec/fsprobe\"\n    exit 1\nfi\n\nCOMMAND=$1\nPLANS=~/.fsprobe/\ncd \"$(hg root)\"\n\nshift || :\ncase $COMMAND in\n  \"generate\")\n    echo \"Plans are stored in $PLANS\"\n    mkdir -p $PLANS\n    find . -name TARGETS | awk '$0=\"cat \"$0' > \"$PLANS/cat.targets\"\n    echo \"Generated read files plan with$(wc -l $PLANS/cat.targets) actions\"\n    head -20000 \"$PLANS/cat.targets\" > \"$PLANS/cat.targets.20k\"\n    head -10000 \"$PLANS/cat.targets\" > \"$PLANS/cat.targets.10k\"\n  ;;\n  \"list\")\n    ls \"$PLANS\" | cat\n  ;;\n  \"run\")\n    PLAN=$1\n    shift || :\n    echo \"Running $PLAN\"\n    $FSPROBE \"$PLANS/$PLAN\" \"$@\"\n  ;;\n  *)\n    echo \"Usage: fsprobe.sh generate | list | run | help\"\n    echo\n    echo \"Note: you must run fsprobe.sh in the repository that you want to test\"\n    echo \"For example, if you have eden mount at ~/fbsource, you need to cd ~/fbsource and run fsprobe.sh from there to test speed of this directory\"\n    exit 1\n    ;;\nesac\n", "num_lines": 50}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# Maintained by Ryan McElroy <rm@fb.com>\n#\n# Inspiration and derivation from git-completion.bash by Shawn O. Pearce.\n#\n# ========================================================================\n#\n# Quickly determines the and emits some useful information about the state\n# of your current mercurial or git repository. Useful for PS1 prompts.\n#\n# Design goals:\n#  * Useful for both git and mercurial\n#  * Portable to both zsh and bash\n#  * Portable to both Mac (BSD-based utils) and Linux (GNU-based utils)\n#  * As fast as possible given the above constraints (few command invocations)\n#  * Avoids invoking git or mercurial, which may be slow on large repositories\n#\n# To use from zsh:\n#\n#   NOTE! the single quotes are important; if you use double quotes\n#   then the prompt won't change when you chdir or checkout different\n#   branches!\n#\n#   setopt PROMPT_SUBST\n#   source /path/to/scm-prompt\n#   export PS1='$(_scm_prompt)$USER@%m:%~%% '\n#\n# To use from bash:\n#\n#   source /path/to/scm-prompt\n#   export PS1=\"\\$(_scm_prompt)\\u@\\h:\\W\\$ \"\n#\n#   NOTE! You *EITHER* need to single-quote the whole thing *OR* back-slash\n#   the $(...) (as above), but not both. Which one you use depends on if\n#   you need the rest of your PS1 to interpolate variables.\n#\n# You may additionally pass a format-string to the scm_info command. This\n# allows you to control the format of the prompt string without interfering\n# with the prompt outside of a mercurial or git repository. For example:\n#\n#   $(_scm_prompt \"%s\")\n#\n# The default format string is \" (%s)\" (note the space)\n#\n# Options: you may want to set these environment variables\n#  * HOME_IS_NOT_A_REPO : Stop walking up the filesystem looking for a git or\n#    hg repo at (but not including) /home instead of /.  This helps when /home\n#    is a remote or autofs mount point.\n#  * WANT_OLD_SCM_PROMPT : Use '%s' as the formatting for the prompt instead\n#    of ' (%s)'\n#  * SHOW_DIRTY_STATE : Show dirty state of the working directory of a\n#    repo with a star *. In addition, for hg, show untracked files with ?.\n#    For git, show staged change with +.  When SHOW_DIRTY_STATE is set,\n#    you can opt out invidivual repo by setting shell.showDirtyState to false\n#    in .hg/hgrc or .git/config.\n#\n# Notes to developers:\n#\n#  * Aliases can screw up the default commands. To prevent this issue, use\n#    the 'builtin' prefix for built-in shell commands (eg, 'cd' and 'echo')\n#    and use the 'command' prefix for external commands that you do not want\n#    to invoke aliases for (eg, 'grep', 'cut').\n#\n# =========================================================================\n#\n\n_find_most_relevant() {\n    # We don't want to output all remote bookmarks because there can be many\n    # of them. This function finds the most relevant remote bookmark using this\n    # algorithm:\n    # 1. If 'master' or '@' bookmark is available then output it\n    # 2. Sort remote bookmarks and output the first in reverse sorted order (\n    # it's a heuristic that tries to find the newest bookmark. It will work well\n    # with bookmarks like 'release20160926' and 'release20161010').\n    relevantbook=\"$(command grep -m1 -E -o \"^[^/]+/(master|@)$\" <<< \"$1\")\"\n    if [[ -n $relevantbook ]]; then\n        builtin echo $relevantbook\n        return 0\n    fi\n\n    builtin echo \"$(command sort -r <<< \"$1\" | command head -n 1)\"\n}\n\n_hg_prompt() {\n  local hg br extra\n  hg=\"$1\"\n\n  if [[ -f \"$hg/bisect.state\" ]]; then\n    extra=\"|BISECT\"\n  elif [[ -f \"$hg/histedit-state\" ]]; then\n    extra=\"|HISTEDIT\"\n  elif [[ -f \"$hg/graftstate\" ]]; then\n    extra=\"|GRAFT\"\n  elif [[ -f \"$hg/unshelverebasestate\" ]]; then\n    extra=\"|UNSHELVE\"\n  elif [[ -f \"$hg/rebasestate\" ]]; then\n    extra=\"|REBASE\"\n  elif [[ -d \"$hg/merge\" ]]; then\n    extra=\"|MERGE\"\n  elif [[ -L \"$hg/store/lock\" ]]; then\n    extra=\"|STORE-LOCKED\"\n  elif [[ -L \"$hg/wlock\" ]]; then\n    extra=\"|WDIR-LOCKED\"\n  fi\n\n  local dirstate=\"$( \\\n    ( [[ -f \"$hg/dirstate\" ]] && \\\n    command hexdump -vn 20 -e '1/1 \"%02x\"' \"$hg/dirstate\") || \\\n    builtin echo \"empty\")\"\n\n  local shared_hg=\"$hg\"\n  if [[ -f \"$hg/sharedpath\" ]]; then\n    shared_hg=\"$(command cat $hg/sharedpath)\"\n  fi\n  local remote=\"$shared_hg/store/remotenames\"\n\n  local active=\"$hg/bookmarks.current\"\n  if  [[ -f \"$active\" ]]; then\n    br=\"$(command cat \"$active\")\"\n    # check to see if active bookmark needs update (eg, moved after pull)\n    local marks=\"$shared_hg/store/bookmarks\"\n    if [[ -z \"$extra\" ]] && [[ -f \"$marks\" ]]; then\n      local markstate=\"$(command grep \" $br$\" \"$marks\" | \\\n        command cut -f 1 -d ' ')\"\n      if [[ $markstate != \"$dirstate\" ]]; then\n        extra=\"|UPDATE_NEEDED\"\n      fi\n    fi\n  else\n    br=\"$(builtin echo \"$dirstate\" | command cut -c 1-9)\"\n  fi\n  if [[ -f \"$remote\" ]]; then\n    local allremotemarks=\"$(command grep \"^$dirstate bookmarks\" \"$remote\" | \\\n      command cut -f 3 -d ' ')\"\n\n    if [[ -n \"$allremotemarks\" ]]; then\n        local remotemark=\"$(_find_most_relevant \"$allremotemarks\")\"\n        if [[ -n \"$remotemark\" ]]; then\n          br=\"$br|$remotemark\"\n          if [[ \"$remotemark\" != \"$allremotemarks\" ]]; then\n            # if there is more than one, let the user know with an elipsis\n            br=\"${br}...\"\n          fi\n        fi\n    fi\n  fi\n  local branch\n  if [[ -f \"$hg/branch\" ]]; then\n    branch=\"$(command cat \"$hg/branch\")\"\n    if [[ \"$branch\" != \"default\" ]]; then\n      br=\"$br|$branch\"\n    fi\n  fi\n  br=\"$br$extra$(_hg_dirty)\"\n  builtin printf \"%s\" \"$br\"\n}\n\n# cf. https://www.internalfb.com/intern/qa/4964/how-do-i-show-the-mercurial-bookmarkgit-branch-in?answerID=540621130023036\n_hg_dirty() {\n  if [ -n \"${SHOW_DIRTY_STATE}\" ] &&\n     [ \"$(command sl config shell.showDirtyState)\" != \"false\" ]; then\n       command sl status 2> /dev/null \\\n         | command awk '{print $1}'\\\n         | command sort\\\n         | command uniq\\\n         | command paste -sd ' ' -\n  fi\n}\n\n_git_dirty() {\n  # cf. git contrib/completion/git-prompt.sh\n  if [ -n \"${SHOW_DIRTY_STATE}\" ] &&\n     [ \"$(git config --bool shell.showDirtyState)\" != \"false\" ]; then\n       command git diff --no-ext-diff --quiet || w=\"*\"\n       command git diff --no-ext-diff --cached --quiet || i=\"+\"\n       builtin printf \"%s\" \"$w$i\"\n  fi\n}\n\n_git_prompt() {\n  local git br\n  git=\"$1\"\n  if [[ -f \"$git\" ]]; then\n      git=$(awk '/^gitdir:/ {print $2}' < \"$git\")\n  fi\n  if [[ -f \"$git/HEAD\" ]]; then\n    read br < \"$git/HEAD\"\n    case $br in\n      ref:\\ refs/heads/*) br=${br#ref: refs/heads/} ;;\n      *) br=\"$(builtin echo \"$br\" | command cut -c 1-8)\" ;;\n    esac\n    if [[ -f \"$git/rebase-merge/interactive\" ]]; then\n      b=\"$(command cat \"$git/rebase-merge/head-name\")\"\n      b=\"${b#refs/heads/}\"\n      br=\"$br|REBASE-i|$b\"\n    elif [[ -d \"$git/rebase-merge\" ]]; then\n      b=\"$(command cat \"$git/rebase-merge/head-name\")\"\n      b=\"${b#refs/heads/}\"\n      br=\"$br|REBASE-m|$b\"\n    else\n      if [[ -d \"$git/rebase-apply\" ]]; then\n        if [[ -f \"$git/rebase-apply/rebasing\" ]]; then\n          b=\"$(command cat \"$git/rebase-apply/head-name\")\"\n          b=\"${b#refs/heads/}\"\n          br=\"$br|REBASE|$b\"\n        elif [[ -f \"$git/rebase-apply/applying\" ]]; then\n          br=\"$br|AM\"\n        else\n          br=\"$br|AM/REBASE\"\n        fi\n      elif [[ -f \"$git/CHERRY_PICK_HEAD\" ]]; then\n        br=\"$br|CHERRY-PICKING\"\n      elif [[ -f \"$git/REVERT_HEAD\" ]]; then\n        br=\"$br|REVERTING\"\n      elif [[ -f \"$git/MERGE_HEAD\" ]]; then\n        br=\"$br|MERGE\"\n      elif [[ -f \"$git/BISECT_LOG\" ]]; then\n        br=\"$br|BISECT\"\n      fi\n    fi\n  fi\n  br=\"$br$(_git_dirty)\"\n  builtin printf \"%s\" \"$br\"\n}\n\n_scm_prompt() {\n  local dir fmt br\n  # Default to be compatable with __git_ps1. In particular:\n  # - provide a space for the user so that they don't have to have\n  #   random extra spaces in their prompt when not in a repo\n  # - provide parens so it's differentiated from other crap in their prompt\n  fmt=\"${1:- (%s)}\"\n\n  # find out if we're in a git or hg repo by looking for the control dir\n  dir=\"$PWD\"\n  while : ; do\n    [[ -n \"$HOME_IS_NOT_A_REPO\" ]] && [[ \"$dir\" = \"/home\" ]] && break\n    if [[ -r \"$dir/.git\" ]]; then\n      br=\"$(_git_prompt \"$dir/.git\")\"\n      break\n    elif [[ -d \"$dir/.hg\" ]]; then\n      br=\"$(_hg_prompt \"$dir/.hg\")\"\n      break\n    elif [[ -d \"$dir/.sl\" ]]; then\n      br=\"$(_hg_prompt \"$dir/.sl\")\"\n      break\n    fi\n    [[ \"$dir\" = \"/\" ]] && break\n    # portable \"realpath\" equivalent\n    dir=\"$(builtin cd -P \"$dir/..\" && builtin echo \"$PWD\")\"\n  done\n\n  if [[ -n \"$br\" ]]; then\n    builtin printf \"$fmt\" \"$br\"\n  fi\n}\n\n#\n# Backwards-compatibility layer for odl scm-prompt script\n#\n# Older versions of this file at Facebook used a longer function name.\n# These versions also included support for an environmental directive\n# called $WANT_OLD_SCM_PROMPT. Support this to remain compatible.\n#\n\n_dotfiles_scm_info() {\n  local fmt\n  fmt=$1\n  if [[ -z \"$fmt\" ]]; then\n    if [[ -n \"$WANT_OLD_SCM_PROMPT\" ]]; then\n      fmt=\"%s\"\n    else\n      fmt=' (%s)'\n    fi\n  fi\n  _scm_prompt \"$fmt\"\n}\n", "num_lines": 282}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# use 'python3.8 -m pip install cogapp' to install cog\npython3.8 -m cogapp -r TARGETS Cargo.toml src/modules.rs\n", "num_lines": 9}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n#\n# This is a helper tool to help you generate C interface from the Rust code\n# using cbindgen. You will need to install cbindgen manually:\n#\n#   cargo install --force cbindgen\n\ncd \"$(dirname \"$0\")\"/..\n\nset -e\n\nCONFIG=\"cbindgen.toml\"\nOUTPUT=\"c_api/BackingStoreBindings.h\"\n\nmain() {\n  cbindgen --config \"$CONFIG\" --output \"$OUTPUT\"\n  python3 \"$(hg root)/xplat/python/signedsource_lib/signedsource.py\" sign \"$OUTPUT\"\n}\n\nmain\n", "num_lines": 26}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\nbuck build //eden/scm/lib/xdiff:diff\nREPO_ROOT=$(hg root)\nXDIFF=\"$REPO_ROOT/fbcode/$(buck targets //eden/scm/lib/xdiff:diff --show-output | cut -d' ' -f2)\"\nexport XDIFF\nbuck run fbsource//third-party/cram:cram -- \"$@\"\n", "num_lines": 14}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# shellcheck shell=bash\n\nif [[ -z \"$XDIFF\" ]]; then\n    echo \"Required XDIFF is not set.\" >&2\n      exit 1\nfi\n\n# So bash expands our aliases.\n[ \"$TESTSHELL\" = \"/bin/bash\" ] && shopt -s expand_aliases\n\nalias xdiff=\"$XDIFF\"\n", "num_lines": 17}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nSRC=../third-party/xdiff/xdiff.h\n\n# Use allowlist to skip noise from stddef.h and stdint.h\nbindgen \\\n  --allowlist-file $SRC \\\n  --with-derive-default \\\n  $SRC -o src/bindgen.rs\n", "num_lines": 14}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\n# Determine the version of Ubuntu by sourcing /etc/os-release. While there is\n# debate about whether source'ing the file creates a security issue:\n#\n# https://unix.stackexchange.com/questions/432816/grab-id-of-os-from-etc-os-release\n#\n# It is worth noting that this is how lsb_release gets its data from /etc/lsb-release:\n#\n# https://github.com/OpenMandrivaSoftware/lsb-release/blob/fd23738b8411/lsb_release#L194\nif [ -f /etc/os-release ]; then\n  UBUNTU_VERSION=$(bash -c 'source /etc/os-release; echo $VERSION_ID')\nelse\n  echo \"could not find /etc/os-release\" >> /dev/stderr\n  exit 1\nfi\n\n# Values of GIT_DEB_DEP below are based on running the following on \"pristine\"\n# Docker containers for the various versions of Ubuntu:\n#\n# apt update -y\n# apt install -y git\n# apt list --installed | grep -E '^git/'\ncase \"$UBUNTU_VERSION\" in\n  20.04)\n    # For Ubuntu 20.04, target Python 3.8.\n    export PY_VERSION=38\n    GIT_DEB_DEP=\"git (>= 1:2.25.1)\"\n    ;;\n\n  22.04)\n    # For Ubuntu 22.04, target Python 3.10.\n    export PY_VERSION=310\n    GIT_DEB_DEP=\"git (>= 1:2.34.1)\"\n    ;;\n\n  *)\n    echo \"unsupported Ubuntu version: '${UBUNTU_VERSION}'\" >> /dev/stderr\n    exit 1\n    ;;\nesac\n\nDESTDIR=install make PREFIX=/usr install-oss\n\n# For simplicity, we currently use `dpkg-deb --build`, though we should\n# ultimately migrate to dpkg-buildpackage. Because we are going to mess with\n# the contents of the install folder, we create a copy to work with instead.\npkg_dir=$(mktemp -d -t sapling-XXXXXXXX)\ncp --recursive install \"$pkg_dir\"\nmkdir \"${pkg_dir}/install/debian\"\ncp packaging/debian/control \"${pkg_dir}/install/debian/control\"\n\n# dpkg-shlibdeps requires the file `debian/control` to exist in the folder\n# in which it is run.\npushd \"$pkg_dir/install\"\nDEB_DEPS=$(dpkg-shlibdeps -O -e usr/bin/*)\n# dpkg-shlibdeps does not know about the runtime dependency on Git,\n# so it must be added explicitly.\nDEB_DEPS=\"${DEB_DEPS}, ${GIT_DEB_DEP}\"\npopd\n\n# In contrast to dpkg-shlibdeps, dpkg-deb requires the file to be named\n# `DEBIAN/control`, so we rename the directory and proceed.\npushd \"$pkg_dir\"\nmv install/debian install/DEBIAN\necho \"$DEB_DEPS\" | sed -e 's/shlibs:Depends=/Depends: /' >> install/DEBIAN/control\nsed -i \"s/%VERSION%/$VERSION/g\" install/DEBIAN/control\ndpkg-deb --build --root-owner-group install\npopd\n\ncp \"${pkg_dir}/install.deb\" .\ndpkg-name install.deb\n", "num_lines": 79}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/zsh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nPYTHON_VERSION=3.8\nPYTHON_VERSION_SHORT=38\n\nROOT=$(cd ../.. && pwd)\n\nrpmbuild --target i386 \\\n    --define \"py_version $PYTHON_VERSION\" \\\n    --define \"_bindir /opt/sapling-beta/bin\" \\\n    --define \"_libdir /opt/sapling-beta/lib\" \\\n    --define \"_sysconfdir /etc\" \\\n    --define \"_datadir /opt/sapling-beta/share\" \\\n    --define \"_docdir /opt/sapling-beta/share/doc\" \\\n    --define \"extra_setup_py_args --prefix=/opt/sapling-beta\" \\\n    --define \"_prefix /opt/sapling-beta\" \\\n    --define \"python_prefix /opt/sapling-beta\" \\\n    --define \"python_sitepackage /opt/sapling-beta/lib/python$PYTHON_VERSION/site-packages\" \\\n    --define \"python_sitelib /opt/sapling-beta/lib/python$PYTHON_VERSION/site-packages\" \\\n    --define \"python_sitearch /opt/sapling-beta/lib/python$PYTHON_VERSION/site-packages\" \\\n    --define \"__python /opt/homebrew/opt/python$PYTHON_VERSION_SHORT/bin/python$PYTHON_VERSION\" \\\n    --define \"_tmppath /var/tmp\" \\\n    --define \"version $VERSION\" \\\n    --define \"sapling_root $ROOT\" \\\n    -v -bb sapling.spec\n", "num_lines": 30}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# reset git environment variables\nexport GIT_AUTHOR_NAME=\"test\"\nexport GIT_AUTHOR_EMAIL=\"test@example.org\"\nexport GIT_AUTHOR_DATE=\"2007-01-01 00:00:10 +0000\"\nexport GIT_COMMITTER_NAME=\"test\"\nexport GIT_COMMITTER_EMAIL=\"test@example.org\"\nexport GIT_COMMITTER_DATE=\"2007-01-01 00:00:10 +0000\"\nunset GIT_DIR\n\n# preserve test compatibility\nsetconfig git.committer='test'\nsetconfig git.committer-date='0 0'\n", "num_lines": 18}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# Copyright 2006, 2007 Olivia Mackall <olivia@selenic.com>\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2 or any later version.\n\n# Avoid interference from actual test env:\n\nunset HGTEST_JOBS\nunset HGTEST_TIMEOUT\nunset HGTEST_PORT\nunset HGTEST_SHELL\n", "num_lines": 17}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# In most cases, the mercurial repository can be read by the bundled hg, but\n# that isn't always true because third-party extensions may change the store\n# format, for example. In which case, the system hg installation is used.\n#\n# We want to use the hg version being tested when interacting with the test\n# repository, and the system hg when interacting with the mercurial source code\n# repository.\n#\n# The mercurial source repository was typically orignally cloned with the\n# system mercurial installation, and may require extensions or settings from\n# the system installation.\n\n# Revert the environment so that running \"hg\" runs the system hg\n# rather than the test hg installation.\nsyshgenv () {\n    . \"$HGTEST_RESTOREENV\"\n    HGPLAIN=1\n    export HGPLAIN\n}\n\n# The test-repo is a live hg repository which may have evolution markers\n# created, e.g. when a ~/.hgrc enabled evolution.\n#\n# Tests may be run using a custom HGRCPATH, which do not enable evolution\n# markers by default.\n#\n# If test-repo includes evolution markers, and we do not enable evolution\n# markers, hg will occasionally complain when it notices them, which disrupts\n# tests resulting in sporadic failures.\n#\n# Since we aren't performing any write operations on the test-repo, there's\n# no harm in telling hg that we support evolution markers, which is what the\n# following lines for the hgrc file do:\ncat >> \"$HGRCPATH\" << EOF\n[experimental]\nevolution = createmarkers\nEOF\n\n# Unconditionally use the system hg to avoid auto migration logic from\n# the in-repo hg.\ntestrepohgenv () {\n    syshgenv\n}\n\ntestrepohg () {\n    (\n        testrepohgenv\n        # Silent potential stderr like \"remove: served by Mononoke\".\n        exec hg \"$@\" 2>/dev/null\n    )\n}\n", "num_lines": 52}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "capturewireprotologs() {\n  cat >> \"$TESTTMP/uilog.py\" <<EOF\nfrom edenscm import extensions\nfrom edenscm import ui as uimod\n\ndef uisetup(ui):\n    extensions.wrapfunction(uimod.ui, 'log', mylog)\n\ndef mylog(orig, self, service, *msg, **opts):\n    if service in ['wireproto_requests']:\n        kw = []\n        for k, v in sorted(opts.items()):\n          if k == 'args':\n            v = eval(v)\n            for arg in v:\n              if isinstance(arg, dict):\n                v = sorted(list(arg.items()))\n            v = str(v)\n          kw.append(\"%s=%s\" % (k, v))\n        kwstr = \", \".join(kw)\n        msgstr = msg[0] % msg[1:]\n        self.warn('%s: %s (%s)\\n' % (service, msgstr, kwstr))\n        with open('$TESTTMP/loggedrequests', 'a') as f:\n          f.write('%s: %s (%s)\\n' % (service, msgstr, kwstr))\n    return orig(self, service, *msg, **opts)\nEOF\n\n  cat >> \"$HGRCPATH\" <<EOF\n[extensions]\nuilog=$TESTTMP/uilog.py\n\n[wireproto]\nlogrequests=batch,branchmap,getbundle,hello,listkeys,lookup,between,unbundle\nloggetpack=True\nEOF\n}\n", "num_lines": 37}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "fixbundle() {\n    grep -v 'saving bundle' | grep -v 'saved backup' | \\\n        grep -v added | grep -v adding | \\\n        grep -v \"unable to find 'e' for patching\" | \\\n        grep -v \"e: No such file or directory\" | \\\n    cat\n}\n", "num_lines": 8}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nCACHEDIR=\"$TESTTMP/hgcache\"\nexport DUMMYSSH_STABLE_ORDER=1\ncat >> $HGRCPATH <<EOF\n[remotefilelog]\ncachepath=$CACHEDIR\ndebug=True\nhistorypackv1=True\n[extensions]\nremotefilelog=\nrebase=\n[ui]\nssh=$(dummysshcmd)\n[server]\npreferuncompressed=True\n[experimental]\nchangegroup3=True\n[rebase]\nsingletransaction=True\nEOF\n\n_cachecount=0\n\nnewcachedir() {\n  _cachecount=$((_cachecount+1))\n  CACHEDIR=\"$TESTTMP/hgcache$_cachecount\"\n  setconfig remotefilelog.cachepath=\"$CACHEDIR\"\n}\n\nhgcloneshallow() {\n  local name\n  local dest\n  orig=$1\n  shift\n  dest=$1\n  shift\n  hg clone --shallow --config remotefilelog.reponame=master $orig $dest $@\n  cat >> $dest/.hg/hgrc <<EOF\n[remotefilelog]\nreponame=master\n[phases]\npublish=False\nEOF\n}\n\nhgcloneshallowlfs() {\n  local name\n  local dest\n  local lfsdir\n  orig=$1\n  shift\n  dest=$1\n  shift\n  lfsdir=$1\n  shift\n  hg clone --shallow --config \"extensions.lfs=\" --config \"lfs.url=$lfsdir\" --config remotefilelog.reponame=master $orig $dest $@\n  cat >> $dest/.hg/hgrc <<EOF\n[extensions]\nlfs=\n[lfs]\nurl=$lfsdir\n[remotefilelog]\nreponame=master\n[phases]\npublish=False\nEOF\n}\n\nhginit() {\n  local name\n  name=$1\n  shift\n  hg init $name $@ --config remotefilelog.reponame=master\n}\n\nclearcache() {\n  rm -rf $CACHEDIR/*\n}\n\nmkcommit() {\n  echo \"$1\" > \"$1\"\n  hg add \"$1\"\n  hg ci -m \"$1\"\n}\n\nls_l() {\n  $PYTHON $TESTDIR/ls-l.py \"$@\"\n}\n\nfindfilessorted() {\n  find \"$1\" -type f | sort\n}\n\ngetmysqldb() {\n  source \"$TESTDIR/hgsql/library.sh\"\n}\n\ncreatepushrebaserecordingdb() {\nmysql -h $DBHOST -P $DBPORT -u $DBUSER $DBPASSOPT -e \"CREATE DATABASE IF NOT EXISTS $DBNAME;\" 2>/dev/null\nmysql -h $DBHOST -P $DBPORT -D $DBNAME -u $DBUSER $DBPASSOPT <<EOF\nDROP TABLE IF EXISTS pushrebaserecording;\n$(cat $TESTDIR/pushrebase_replay_schema.sql)\nEOF\n}\n", "num_lines": 109}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# This file will be sourced by all .t tests. Put general purposed functions\n# here.\n\n_repocount=0\n\nif [ -n \"$USE_MONONOKE\" ] ; then\n  . \"$TESTDIR/../../mononoke/tests/integration/library.sh\"\nfi\n\nsl() {\n  HGIDENTITY=sl hg \"$@\"\n}\n\ndummysshcmd() {\n  if [ -n \"$DUMMYSSH\" ]\n  then\n    echo \"$DUMMYSSH\"\n  else\n    echo \"$PYTHON $TESTDIR/dummyssh\"\n  fi\n}\n\n# Create a new repo\nnewrepo() {\n  reponame=\"$1\"\n  shift\n  if [ -z \"$reponame\" ]; then\n    _repocount=$((_repocount+1))\n    reponame=repo$_repocount\n  fi\n  mkdir \"$TESTTMP/$reponame\"\n  cd \"$TESTTMP/$reponame\"\n  hg init \"$@\"\n}\n\nnewclientrepo() {\n  reponame=\"$1\"\n  server=\"$2\"\n  shift\n  shift\n  bookmarks=\"$@\"\n  if [ -z \"$reponame\" ]; then\n    _repocount=$((_repocount+1))\n    reponame=repo$_repocount\n  fi\n  if [ -z \"$server\" ]; then\n      server=\"test:${reponame}_server\"\n  fi\n  hg clone --config \"init.use-rust=True\" --config \"clone.use-rust=True\" --shallow -q \"$server\" \"$TESTTMP/$reponame\"\n\n  cd \"$TESTTMP/$reponame\"\n  for book in $bookmarks ; do\n      hg pull -q -B $book\n  done\n  hg up -q tip\n}\n\n# create repo connected to remote repo ssh://user@dummy/server.\n# `newserver server` needs to be called at least once before this call to setup ssh repo\nnewremoterepo() {\n  newrepo \"$@\"\n  echo remotefilelog >> .hg/requires\n  enable treemanifest remotefilelog pushrebase remotenames\n  setconfig treemanifest.sendtrees=True treemanifest.treeonly=True\n  if [ -n \"$USE_MONONOKE\" ] ; then\n    setconfig paths.default=mononoke://$(mononoke_address)/server\n  else\n    setconfig paths.default=ssh://user@dummy/server\n  fi\n}\n\nnewserver() {\n  local reponame=\"$1\"\n  if [ -n \"$USE_MONONOKE\" ] ; then\n    REPONAME=$reponame setup_common_config\n    mononoke\n    MONONOKE_START_TIMEOUT=60 wait_for_mononoke \"$TESTTMP/$reponame\"\n  elif [ -f \"$TESTTMP/.eagerepo\" ] ; then\n    # Do nothing, it will be setup at access time\n    true\n  else\n    mkdir \"$TESTTMP/$reponame\"\n    cd \"$TESTTMP/$reponame\"\n    hg --config extensions.lz4revlog= \\\n      --config extensions.treemanifest=$TESTDIR/../edenscm/ext/treemanifestserver.py \\\n      --config experimental.narrow-heads=false \\\n      --config visibility.enabled=false \\\n      init\n    enable lz4revlog remotefilelog remotenames\n    setconfig \\\n       remotefilelog.reponame=\"$reponame\" remotefilelog.server=True \\\n       treemanifest.rustmanifest=True \\\n       treemanifest.server=True treemanifest.treeonly=True \\\n       infinitepush.server=yes infinitepush.reponame=\"$reponame\" \\\n       infinitepush.indextype=disk infinitepush.storetype=disk \\\n       experimental.narrow-heads=false \\\n       extensions.treemanifest=$TESTDIR/../edenscm/ext/treemanifestserver.py\n  fi\n}\n\nclone() {\n  servername=\"$1\"\n  clientname=\"$2\"\n  shift 2\n  cd \"$TESTTMP\"\n  remotecmd=\"hg\"\n  if [ -f \"$TESTTMP/.eagerepo\" ] ; then\n      serverurl=\"test:$servername\"\n  elif [ -n \"$USE_MONONOKE\" ] ; then\n      serverurl=\"mononoke://$(mononoke_address)/$servername\"\n  else\n      serverurl=\"ssh://user@dummy/$servername\"\n  fi\n\n  hg clone -q --shallow \"$serverurl\" \"$clientname\" \"$@\" \\\n    --config \"init.use-rust=True\" \\\n    --config \"extensions.lz4revlog=\" \\\n    --config \"extensions.remotefilelog=\" \\\n    --config \"extensions.remotenames=\" \\\n    --config \"extensions.treemanifest=\" \\\n    --config \"remotefilelog.reponame=$servername\" \\\n    --config \"treemanifest.treeonly=True\" \\\n    --config \"ui.ssh=$(dummysshcmd)\" \\\n    --config \"ui.remotecmd=$remotecmd\"\n\n  cat >> $clientname/.hg/hgrc <<EOF\n[extensions]\nremotenames=\ntreemanifest=\ntweakdefaults=\n\n[phases]\npublish=False\n\n[remotefilelog]\nreponame=$servername\n\n[treemanifest]\nrustmanifest=True\nsendtrees=True\ntreeonly=True\n\n[ui]\nssh=$(dummysshcmd)\n\n[tweakdefaults]\nrebasekeepdate=True\nEOF\n\n  if [ -n \"$COMMITCLOUD\" ]; then\n    hg --cwd $clientname cloud join -q\n  fi\n}\n\nswitchrepo() {\n    reponame=\"$1\"\n    cd $TESTTMP/$reponame\n}\n\n# Set configuration for feature\nconfigure() {\n  for name in \"$@\"\n  do\n    case \"$name\" in\n      dummyssh)\n        export DUMMYSSH_STABLE_ORDER=1\n        setconfig ui.ssh=\"$(dummysshcmd)\"\n        ;;\n      mutation)\n        setconfig \\\n            experimental.evolution=obsolete \\\n            mutation.enabled=true mutation.record=true mutation.date=\"0 0\" \\\n            visibility.enabled=true\n        ;;\n      mutation-norecord)\n        setconfig \\\n            experimental.evolution=obsolete \\\n            mutation.enabled=true mutation.record=false mutation.date=\"0 0\" \\\n            visibility.enabled=true\n        ;;\n      evolution)\n         setconfig \\\n            experimental.evolution=\"createmarkers, allowunstable\" \\\n            mutation.enabled=false \\\n            visibility.enabled=false\n        ;;\n      noevolution)\n         setconfig \\\n            experimental.evolution=obsolete \\\n            mutation.enabled=false \\\n            visibility.enabled=false\n        ;;\n      commitcloud)\n        enable commitcloud infinitepush\n        setconfig commitcloud.hostname=testhost\n        setconfig commitcloud.servicetype=local commitcloud.servicelocation=$TESTTMP\n        setconfig commitcloud.remotebookmarkssync=True\n        COMMITCLOUD=1\n        ;;\n      narrowheads)\n        configure noevolution mutation-norecord\n        setconfig experimental.narrow-heads=true\n        ;;\n      selectivepull)\n        enable remotenames\n        setconfig remotenames.selectivepull=True\n        setconfig remotenames.selectivepulldefault=master\n        ;;\n      modern)\n        enable amend\n        setconfig remotenames.rename.default=remote\n        setconfig remotenames.hoist=remote\n        setconfig experimental.changegroup3=True\n        configure dummyssh commitcloud narrowheads selectivepull\n        ;;\n      modernclient)\n        touch $TESTTMP/.eagerepo\n        setconfig remotefilelog.http=True\n        setconfig treemanifest.http=True\n        configure modern\n    esac\n  done\n}\n\neagerepo() {\n  configure modernclient\n  setconfig format.use-eager-repo=True\n}\n\n# Enable extensions\nenable() {\n  for name in \"$@\"\n  do\n    setconfig \"extensions.$name=\"\n  done\n}\n\n# Disable extensions\ndisable() {\n  for name in \"$@\"\n  do\n    setconfig \"extensions.$name=!\"\n    if [[ $name == \"treemanifest\" ]]; then\n        setconfig treemanifest.sendtrees=False treemanifest.treeonly=False\n    fi\n  done\n}\n\n# Like \"hg debugdrawdag\", but do not leave local tags in the repo and define\n# nodes as environment variables.\n_drawdagcount=0\ndrawdag() {\n  _drawdagcount=$((_drawdagcount+1))\n  local env_path=\"$TESTTMP/.drawdag-${_drawdagcount}\"\n  hg debugdrawdag --config remotenames.autopullhoistpattern= --no-bookmarks --write-env=\"$env_path\" \"$@\"\n  local _exitcode=\"$?\"\n  [[ -f \"$env_path\" ]] && source \"$env_path\"\n  return $_exitcode\n}\n\n# Simplify error reporting so crash does not show a traceback.\n# This is useful to match error messages without the traceback.\nshorttraceback() {\n  enable errorredirect\n  setconfig errorredirect.script='printf \"%s\" \"$TRACE\" | tail -1 1>&2'\n}\n\n# Set config items like --config way, instead of using cat >> $HGRCPATH\nsetconfig() {\n  python \"$RUNTESTDIR/setconfig.py\" \"$@\"\n}\n\n# Set config item, but always in the main hgrc\nsetglobalconfig() {\n  ( cd \"$TESTTMP\" ; setconfig \"$@\" )\n}\n\n# Set config items that enable modern features.\nsetmodernconfig() {\n  enable remotenames amend\n  setconfig experimental.narrow-heads=true visibility.enabled=true mutation.record=true mutation.enabled=true mutation.date=\"0 0\" experimental.evolution=obsolete remotenames.rename.default=remote\n}\n\n# Read config from stdin (usually a heredoc).\nreadconfig() {\n  local hgrcpath\n  if [ -e \".hg\" ]\n  then\n    hgrcpath=\".hg/hgrc\"\n  else\n    hgrcpath=\"$HGRCPATH\"\n  fi\n  cat >> \"$hgrcpath\"\n}\n\n# Read global config from stdin (usually a heredoc).\nreadglobalconfig() {\n  cat >> \"$HGRCPATH\"\n}\n\n# Create a new extension\nnewext() {\n  extname=\"$1\"\n  if [ -z \"$extname\" ]; then\n    _extcount=$((_extcount+1))\n    extname=ext$_extcount\n  fi\n  cat > \"$TESTTMP/$extname.py\"\n  setconfig \"extensions.$extname=$TESTTMP/$extname.py\"\n}\n\nshowgraph() {\n  hg log --graph -T \"{node|short} {desc|firstline}\" | sed \\$d\n}\n\ntglog() {\n  hg log -G -T \"{node|short} '{desc}' {bookmarks}\" \"$@\"\n}\n\ntglogp() {\n  hg log -G -T \"{node|short} {phase} '{desc}' {bookmarks}\" \"$@\"\n}\n\ntglogm() {\n  hg log -G -T \"{node|short} '{desc|firstline}' {bookmarks} {join(mutations % '(Rewritten using {operation} into {join(successors % \\'{node|short}\\', \\', \\')})', ' ')}\" \"$@\"\n}\n", "num_lines": 332}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Portions Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\n# Copyright 2006, 2007 Olivia Mackall <olivia@selenic.com>\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2 or any later version.\n\nhg init rebase\ncd rebase\n\n#  @  7: 'H'\n#  |\n#  | o  6: 'G'\n#  |/|\n#  o |  5: 'F'\n#  | |\n#  | o  4: 'E'\n#  |/\n#  | o  3: 'D'\n#  | |\n#  | o  2: 'C'\n#  | |\n#  | o  1: 'B'\n#  |/\n#  o  0: 'A'\n\necho A > A\nhg ci -Am A\necho B > B\nhg ci -Am B\necho C > C\nhg ci -Am C\necho D > D\nhg ci -Am D\nhg up -q -C 0\necho E > E\nhg ci -Am E\nhg up -q -C 0\necho F > F\nhg ci -Am F\nhg merge -r 4\nhg ci -m G\nhg up -q -C 5\necho H > H\nhg ci -Am H\n\nhg bundle -a ../rebase.hg\n\ncd ..\nrm -Rf rebase\n", "num_lines": 55}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nhg init remote\ncd remote\n\necho \"0\" >> afile\nhg add afile\nhg commit -m \"0.0\"\necho \"1\" >> afile\nhg commit -m \"0.1\"\necho \"2\" >> afile\nhg commit -m \"0.2\"\necho \"3\" >> afile\nhg commit -m \"0.3\"\nhg update -C 0\necho \"1\" >> afile\nhg commit -m \"1.1\"\necho \"2\" >> afile\nhg commit -m \"1.2\"\necho \"a line\" > fred\necho \"3\" >> afile\nhg add fred\nhg commit -m \"1.3\"\nhg mv afile adifferentfile\nhg commit -m \"1.3m\"\nhg update -C 3\nhg mv afile anotherfile\nhg commit -m \"0.3m\"\n\nhg bundle -a ../remote.hg\n\ncd ..\nrm -Rf remote\n", "num_lines": 38}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  @  3: 'move2'\n#  |\n#  o  2: 'move1'\n#  |\n#  | o  1: 'change'\n#  |/\n#  o  0: 'add'\n\nhg init copies\ncd copies\necho a > a\necho b > b\necho c > c\nhg ci -Am add\necho a >> a\necho b >> b\necho c >> c\nhg ci -m change\nhg up -qC 0\nhg cp a d\nhg mv b e\nhg mv c f\nhg ci -m move1\nhg mv e g\nhg mv f c\nhg ci -m move2\nhg bundle -a ../renames.hg\ncd ..\n", "num_lines": 31}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\ncat >> $HGRCPATH << EOF\n[experimental]\nnarrow-heads = false\nEOF\n\nHGSQL_TESTDIR=\"${RUN_TESTS_LIBRARY:-\"${TESTDIR:-.}\"}\"\n\nGETDB_PATH=\"${HGTEST_GETDB_SH:-$HGSQL_TESTDIR}/getdb.sh\"\nexport DUMMYSSH_STABLE_ORDER=1\n\nif [[ ! -f \"$GETDB_PATH\" ]]; then\n  echo \"skipped: getdb.sh missing. copy from getdb.sh.example and edit it\"\n  exit 80\nfi\n\nif ! hg debugpython -- -c \"import mysql.connector\" 2>/dev/null; then\n  echo \"skipped: mysql-connector-python missing\"\n  exit 80\nfi\n\nsource \"$GETDB_PATH\" >/dev/null\n\n[[ -z $DBHOST ]] && DBHOST=localhost\n[[ -z $DBPORT ]] && DBPORT=3306\n[[ -z $DBENGINE ]] && DBENGINE=innodb\n[[ -z $DBPASS && -n $PASSWORD ]] && DBPASS=\"$PASSWORD\"\n[[ -z $DBUSER && -n $USER ]] && DBUSER=\"$USER\"\n[[ -z $DBNAME ]] && DBNAME=\"testdb_hgsql_$$_$(date +%s)\" && DBAUTODROP=1\n[[ -n $DBPASS ]] && DBPASSOPT=\"-p$DBPASS\"\n\nMYSQLLOG=\"${MYSQLLOG:-/dev/null}\"\n\n# skip if DBENGINE is not supported\n( mysql -h \"$DBHOST\" -P \"$DBPORT\" -u \"$DBUSER\" \"$DBPASSOPT\" \\\n  --execute='SHOW ENGINES' --silent --skip-column-names  | \\\n  egrep -iq \"^$DBENGINE[[:space:]](default|yes)[[:space:]]\" )\n\nif [[ $? != 0 ]]; then\n  echo \"skipped: $DBENGINE unsupported\"\n  exit 80\nfi\n\nmysql -h \"$DBHOST\" -P \"$DBPORT\" -u \"$DBUSER\" \"$DBPASSOPT\" &>> \"$MYSQLLOG\" <<EOF\nCREATE DATABASE IF NOT EXISTS $DBNAME;\nUSE $DBNAME;\nDROP TABLE IF EXISTS revisions;\nDROP TABLE IF EXISTS revision_references;\n$(cat $HGSQL_TESTDIR/hgsql/schema.$DBENGINE.sql)\nEOF\n\nif [[ $? != 0 ]]; then\n  echo \"skipped: unable to initialize the database. check your getdb.sh\"\n  exit 80\nfi\n\nfunction droptestdb() {\nmysql -h \"$DBHOST\" -P \"$DBPORT\" -u \"$DBUSER\" \"$DBPASSOPT\" &>> \"$MYSQLLOG\" <<EOF\nDROP DATABASE $DBNAME;\nEOF\n}\n\n[[ $DBAUTODROP == 1 ]] && trap droptestdb EXIT\n\nfunction initserver() {\n  hg init --config extensions.hgsql= $1\n  configureserver $1 $2\n}\n\nconfigureserver() {\n  cat >> $1/.hg/hgrc <<EOF\n[extensions]\nhgsql=\n\n[hgsql]\nenabled = True\nhost = $DBHOST\ndatabase = $DBNAME\nuser = $DBUSER\npassword = $DBPASS\nport = $DBPORT\nreponame = $2\nengine = $DBENGINE\n\n[server]\npreferuncompressed=True\nuncompressed=True\n\n[ui]\nssh=$(dummysshcmd)\nEOF\n}\n\nfunction initclient() {\n  hg init --config extensions.hgsql=! --config format.usehgsql=false $1\n  configureclient $1\n}\n\nconfigureclient() {\n  cat >> $1/.hg/hgrc <<EOF\n[ui]\nssh=$(dummysshcmd)\nEOF\n}\n", "num_lines": 109}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nINFINITEPUSH_TESTDIR=\"${RUN_TESTS_LIBRARY:-\"$TESTDIR\"}\"\n\nscratchnodes() {\n  for node in `find ../repo/.hg/scratchbranches/index/nodemap -type f | LC_ALL=C sort`; do\n     echo ${node##*/} `cat $node`\n  done\n}\n\nscratchbookmarks() {\n  for bookmark in `find ../repo/.hg/scratchbranches/index/bookmarkmap -type f | LC_ALL=C sort`; do\n     echo \"${bookmark##*/bookmarkmap/} `cat $bookmark`\"\n  done\n}\n\nsetupcommon() {\n  cat >> $HGRCPATH << EOF\n[extensions]\ncommitcloud=\ninfinitepush=\npullcreatemarkers=\n[ui]\nssh=$(dummysshcmd)\n[infinitepush]\nbranchpattern=re:scratch/.*\nbgssh=$(dummysshcmd) -bgssh\n[remotenames]\nautopullhoistpattern=re:^[a-z0-9A-Z/]*$\nhoist=default\nEOF\n}\n\nsetupserver() {\ncat >> .hg/hgrc << EOF\n[infinitepush]\nserver=yes\nEOF\n}\n\nwaitbgbackup() {\n  sleep 1\n  hg debugwaitbackup\n}\n\nmkcommitautobackup() {\n    echo $1 > $1\n    hg add $1\n    hg ci -m $1 --config infinitepushbackup.autobackup=True\n}\n\nsetuplogdir() {\n  mkdir $TESTTMP/logs\n  chmod 0755 $TESTTMP/logs\n  chmod +t $TESTTMP/logs\n}\n\ndebugsshcall() {\n  sed -n '/^running .*dummyssh.*$/p'\n}\n", "num_lines": 65}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Use this script to generate branches.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\nmkdir branches\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\necho a > trunk/a\necho b > trunk/b\necho c > trunk/c\nmkdir trunk/dir\necho e > trunk/dir/e\n# Add a file within branches, used to confuse branch detection\necho d > branches/notinbranch\nsvn add trunk/a trunk/b trunk/c trunk/dir branches/notinbranch\nsvn ci -m hello\nsvn up\n\n# Branch to old\nsvn copy trunk branches/old\nsvn rm branches/old/c\nsvn rm branches/old/dir\nsvn ci -m \"branch trunk, remove c and dir\"\nsvn up\n\n# Update trunk\necho a >> trunk/a\nsvn ci -m \"change a\"\n\n# Update old branch\necho b >> branches/old/b\nsvn ci -m \"change b\"\n\n# Create a cross-branch revision\nsvn move trunk/b branches/old/c\necho c >> branches/old/c\nsvn ci -m \"move and update c\"\n\n# Update old branch again\necho b >> branches/old/b\nsvn ci -m \"change b again\"\n\n# Move back and forth between branch of similar names\n# This used to generate fake copy records\nsvn up\nsvn move branches/old branches/old2\nsvn ci -m \"move to old2\"\nsvn move branches/old2 branches/old\nsvn ci -m \"move back to old\"\n\n# Update trunk again\necho a > trunk/a\nsvn ci -m \"last change to a\"\n\n# Branch again from a converted revision\nsvn copy -r 1 $svnurl/trunk branches/old3\nsvn ci -m \"branch trunk@1 into old3\"\ncd ..\n\nsvnadmin dump svn-repo > ../branches.svndump\n", "num_lines": 74}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Use this script to generate empty.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\nmkdir branches\nmkdir tags\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\nmkdir trunk/dir\necho a > trunk/dir/a\nsvn add trunk/dir\nsvn ci -m adddir\n\necho b > trunk/b\nsvn add trunk/b\nsvn ci -m addb\n\necho c > c\nsvn add c\nsvn ci -m addc\ncd ..\n\n# svnsync repo/trunk/dir only so the last two revisions are empty\nsvnadmin create svn-empty\ncat > svn-empty/hooks/pre-revprop-change <<EOF\n#!/bin/sh\nexit 0\nEOF\nchmod +x svn-empty/hooks/pre-revprop-change\nsvnsync init --username svnsync file://`pwd`/svn-empty file://`pwd`/svn-repo/trunk/dir\nsvnsync sync file://`pwd`/svn-empty\nsvn log -v file://`pwd`/svn-empty\n\nsvnadmin dump svn-empty > ../empty.svndump\n", "num_lines": 48}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# -*- coding: utf-8 -*-\n#\n# Use this script to generate encoding.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\nmkdir branches\nmkdir tags\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\necho e > trunk/\u00c3\u00a9\nmkdir trunk/\u00c3\u00a0\necho d > trunk/\u00c3\u00a0/\u00c3\u00a9\nsvn add trunk/\u00c3\u00a9 trunk/\u00c3\u00a0\nsvn ci -m hello\n\n# Copy files and directories\nsvn mv trunk/\u00c3\u00a9 trunk/\u00c3\u00a8\nsvn mv trunk/\u00c3\u00a0 trunk/\u00c3\u00b9\nsvn ci -m \"copy files\"\n\n# Remove files\nsvn rm trunk/\u00c3\u00a8\nsvn rm trunk/\u00c3\u00b9\nsvn ci -m 'remove files'\n\n# Create branches with and from weird names\nsvn up\nsvn cp trunk branches/branch\u00c3\u00a9\necho a > branches/branch\u00c3\u00a9/a\nsvn ci -m 'branch to branch\u00c3\u00a9'\nsvn up\nsvn cp branches/branch\u00c3\u00a9 branches/branch\u00c3\u00a9e\necho a >> branches/branch\u00c3\u00a9/a\nsvn ci -m 'branch to branch\u00c3\u00a9e'\n\n# Create tag with weird name\nsvn up\nsvn cp trunk tags/branch\u00c3\u00a9\nsvn ci -m 'tag trunk'\nsvn cp branches/branch\u00c3\u00a9e tags/branch\u00c3\u00a9e\nsvn ci -m 'tag branch\u00c3\u00a9'\ncd ..\n\nsvnadmin dump svn-repo > ../encoding.svndump\n", "num_lines": 58}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Use this script to generate move.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\necho a > trunk/a\nmkdir trunk/d1\nmkdir trunk/d2\necho b > trunk/d1/b\necho c > trunk/d1/c\necho d > trunk/d2/d\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\n# Build a module renaming chain which used to confuse the converter.\n# Update svn repository\necho a >> trunk/a\necho c >> trunk/d1/c\nsvn ci -m commitbeforemove\nsvn mv $svnurl/trunk $svnurl/subproject -m movedtrunk\nsvn up\nmkdir subproject/trunk\nsvn add subproject/trunk\nsvn ci -m createtrunk\nmkdir subproject/branches\nsvn add subproject/branches\nsvn ci -m createbranches\nsvn mv $svnurl/subproject/d1 $svnurl/subproject/trunk/d1 -m moved1\nsvn mv $svnurl/subproject/d2 $svnurl/subproject/trunk/d2 -m moved2\nsvn up\necho b >> subproject/trunk/d1/b\n\nsvn rm subproject/trunk/d2\nsvn ci -m \"changeb and rm d2\"\nsvn mv $svnurl/subproject/trunk/d1 $svnurl/subproject/branches/d1 -m moved1again\n\nif svn help copy | grep 'SRC\\[@REV\\]' > /dev/null 2>&1; then\n    # SVN >= 1.5 replaced the -r REV syntax with @REV\n    # Copy a file from a past revision\n    svn copy $svnurl/subproject/trunk/d2/d@7 $svnurl/subproject/trunk -m copyfilefrompast\n    # Copy a directory from a past revision\n    svn copy $svnurl/subproject/trunk/d2@7 $svnurl/subproject/trunk -m copydirfrompast\nelse\n    # Copy a file from a past revision\n    svn copy -r 7 $svnurl/subproject/trunk/d2/d $svnurl/subproject/trunk -m copyfilefrompast\n    # Copy a directory from a past revision\n    svn copy -r 7 $svnurl/subproject/trunk/d2 $svnurl/subproject/trunk -m copydirfrompast\nfi\n\n# Copy a directory while removing a subdirectory\nsvn up\nmkdir -p subproject/trunk/d3/d31\necho e > subproject/trunk/d3/d31/e\necho f > subproject/trunk/d3/f\nsvn add subproject/trunk/d3\nsvn ci -m \"add d3\"\nsvn copy subproject/trunk/d3 subproject/trunk/d4\nsvn rm subproject/trunk/d3/d31\nsvn ci -m \"copy dir and remove subdir\"\n\n# Test directory moves\nsvn up\nmkdir -p subproject/trunk/d4old\necho g > subproject/trunk/d4old/g\nsvn add subproject/trunk/d4old\nsvn ci -m \"add d4old\"\nsvn mv subproject/trunk/d4old subproject/trunk/d4new\nsvn ci -m \"rename d4old into d4new\"\n\ncd ..\n\nsvnadmin dump svn-repo > ../move.svndump", "num_lines": 83}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nRSVN=\"`pwd`/rsvn.py\"\nexport PATH=/bin:/usr/bin\nmkdir temp\ncd temp\n\nsvnadmin create repo\nsvn co file://`pwd`/repo wc\n\ncd wc\nmkdir trunk branches\ncd trunk\necho a > a\nmkdir d\necho b > d/b\nln -s d dlink\nln -s d dlink2\nln -s d dlink3\nmkdir d2\necho a > d2/a\ncd ..\nsvn add *\nsvn ci -m 'initial'\n# Clobber symlink with file with similar content\ncd trunk\nls -Alh\nreadlink dlink3 > dlink3tmp\nrm dlink3\nmv dlink3tmp dlink3\nsvn propdel svn:special dlink3\nsvn ci -m 'clobber symlink'\ncd ..\nsvn up\n\n# Clobber files and symlink with directories\ncd ..\ncat > clobber.rsvn <<EOF\nrdelete trunk/a\nrdelete trunk/dlink\nrcopy trunk/d trunk/a\nrcopy trunk/d trunk/dlink\nEOF\n\npython $RSVN --message=clobber1 --username=evil `pwd`/repo < clobber.rsvn\n\n# Clobber non-symlink with symlink with same content (kudos openwrt)\ncat > clobber.rsvn <<EOF\nrdelete trunk/dlink3\nrcopy trunk/dlink2 trunk/dlink3\nEOF\n\npython $RSVN --message=clobber2 --username=evil `pwd`/repo < clobber.rsvn\n\n# Create d2 in branch so d2 has 'a' is in branch/d2 and trunk/d2,\n# 'b' is in trunk/d2 and 'c' is in branch/d2\ncd wc/trunk\necho b > d2/b\nsvn add d2/b\nsvn ci -m adddb\ncd ..\nsvn up\nsvn cp trunk branches/branch\ncd branches/branch\nsvn rm d2/b\necho c > d2/c\nsvn add d2/c\ncd ../..\nsvn ci -m branch\nsvn up\ncd ..\n\ncat > clobber.rsvn <<EOF\nrdelete trunk/d2\nrcopy branches/branch/d2 trunk/d2\nEOF\npython $RSVN --message=clobberdir --username=evil `pwd`/repo < clobber.rsvn\n\nsvn log -v file://`pwd`/repo\n\nsvnadmin dump repo > ../replace.svndump\n", "num_lines": 82}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Use this script to generate startrev.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\nmkdir branches\nmkdir tags\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\necho a > trunk/a\necho b > trunk/b\nsvn add trunk/a trunk/b\nsvn ci -m createab\nsvn rm trunk/b\nsvn ci -m removeb\nsvn up\necho a >> trunk/a\nsvn ci -m changeaa\n\n# Branch\nsvn up\nsvn copy trunk branches/branch1\necho a >> branches/branch1/a\nsvn ci -m \"branch, changeaaa\"\n\necho a >> branches/branch1/a\necho c > branches/branch1/c\nsvn add branches/branch1/c\nsvn ci -m \"addc,changeaaaa\"\nsvn up\ncd ..\n\nsvnadmin dump svn-repo > ../startrev.svndump", "num_lines": 45}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Use this script to generate tags.svndump\n#\n\nmkdir temp\ncd temp\n\nmkdir project-orig\ncd project-orig\nmkdir trunk\nmkdir branches\nmkdir tags\nmkdir unrelated\ncd ..\n\nsvnadmin create svn-repo\nsvnurl=file://`pwd`/svn-repo\nsvn import project-orig $svnurl -m \"init projA\"\n\nsvn co $svnurl project\ncd project\necho a > trunk/a\nsvn add trunk/a\nsvn ci -m adda\necho a >> trunk/a\nsvn ci -m changea\necho a >> trunk/a\nsvn ci -m changea2\n# Add an unrelated commit to test that tags are bound to the\n# correct \"from\" revision and not a dummy one\necho a >> unrelated/dummy\nsvn add unrelated/dummy\nsvn ci -m unrelatedchange\n# Tag current revision\nsvn up\nsvn copy trunk tags/trunk.v1\nsvn copy trunk tags/trunk.badtag\nsvn ci -m \"tagging trunk.v1 trunk.badtag\"\necho a >> trunk/a\nsvn ci -m changea3\n# Fix the bad tag\n# trunk.badtag should not show in converted tags\nsvn up\nsvn mv tags/trunk.badtag tags/trunk.goodtag\nsvn ci -m \"fix trunk.badtag\"\necho a >> trunk/a\nsvn ci -m changea\n# Delete goodtag and recreate it, to test we pick the good one\nsvn rm tags/trunk.goodtag\nsvn ci -m removegoodtag\nsvn up\nsvn copy trunk tags/trunk.goodtag\nsvn ci -m recreategoodtag\ncd ..\n\nsvnadmin dump svn-repo > ../tags.svndump", "num_lines": 57}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This software may be used and distributed according to the terms of the\n# GNU General Public License version 2.\n\nset -e\n\n./run-tests.py --with-hg=../hg3 --json || true\n./update-to-py3-utils/retry-skipped.py\n./run-tests.py --with-hg=../hg3 --json || true\n./update-to-py3-utils/revert-failed.py\narc f\n", "num_lines": 14}
{"repo_name": "sapling", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -xe\n\n# Treat the wasm file as a static asset so it can be \"fetch()\"-ed\n# client-side. See also why we use '-t web' below.\nPACK_OUT_DIR=../../static/wasm\n\n[[ -d $PACK_OUT_DIR ]] && rm -rf $PACK_OUT_DIR\n\n# Use '-t web' instead of '-t bundler' for server compatibility.\n# Some servers (ex. internaldocs) use application/octet-stream not\n# application/wasm for .wasm files which breaks native client-side\n# import. '-t web' generates code with WebAssembly.instantiate\n# fallback to be compatible with it [1].\n# [1]: https://github.com/rustwasm/wasm-bindgen/blob/564ce74168904e95a7905a828488ec3029bcaad4/crates/cli-support/src/js/mod.rs#L799\nwasm-pack build -t web -d $PACK_OUT_DIR\nrm $PACK_OUT_DIR/README.md $PACK_OUT_DIR/package.json $PACK_OUT_DIR/wasm_bindings_bg.wasm.d.ts\n\n# wasm-pack can run wasm-opt, but it is buggy [2] and wasm-opt bundled by\n# wasm-pack is outdated (slow, 30s vs 1s). So we disabled wasm-opt feature\n# of wasm-pack in Cargo.toml. However wasm-opt is useful. It can shrink\n# the binary from 1.1MB to 0.7MB.\n# Assume wasm-opt is in PATH and is newer. wasm-opt can be built from\n# source [3].\n# [2]: https://github.com/rustwasm/wasm-pack/issues/1190\n# [3]: https://github.com/WebAssembly/binaryen\nwasm-opt $PACK_OUT_DIR/wasm_bindings_bg.wasm -o $PACK_OUT_DIR/wasm_bindings_bg.wasm.opt -Os\nmv $PACK_OUT_DIR/wasm_bindings_bg.wasm.opt $PACK_OUT_DIR/wasm_bindings_bg.wasm\n\n# See src/utils/importBindings.js for client-side logic to import the module.\n", "num_lines": 36}
{"repo_name": "sapp", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# Script to publish package to PyPI. Note that version bump\n# in `setup.py` is manual\n\nset -e\nset -x\n\ncd \"$(dirname \"$0\")/..\" || exit 1\n\n(cd sapp/ui/frontend && npm install && npm run build)\n\nrm -rf dist\npip install wheel twine\npython setup.py sdist bdist_wheel\npython -m twine upload dist/*\n", "num_lines": 21}
{"repo_name": "sapp", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nSCRIPTS_DIRECTORY=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\ncd \"${SCRIPTS_DIRECTORY}/..\"\n\necho '  Enumerating backend test files:'\nfiles=$(find sapp -name '*_test.py' ! -name 'sharded_files_test.py' ! -name 'cli_test.py')\necho \"${files}\"\nif [[ -z \"${files}\" ]]; then\n  echo 'No test files found, exiting.'\n  exit 2\nfi\n\nif [ \"$1\" == \"--with-coverage\" ]; then\n  echo '  Running backend tests with coverage results:'\n  echo \"${files}\" | sed 's/.py$//' | sed 's:/:.:g' | xargs python -m coverage run -m unittest -v\n  python -m coverage report --show-missing --ignore-errors --skip-empty\nelse\n  echo '  Running backend tests'\n  echo \"${files}\" | sed 's/.py$//' | sed 's:/:.:g' | xargs python -m unittest -v\nfi\n\ncd \"$(dirname \"$0\")/..\" || exit 1\nif [ \"$1\" == \"--with-coverage\" ]; then\n  echo '  Running frontend tests with coverage results:'\n  (cd sapp/ui/frontend && npm install && npm run ui-test)\nelse\n  echo '  Running frontend tests:'\n  (cd sapp/ui/frontend && npm install && npm run ui-test -- --coverage=false)\nfi\n", "num_lines": 37}
{"repo_name": "SPARTA", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nBOOST_VERSION=\"1.71.0\"\n\nBOOST_VERSION_UNDERSCORE=\"${BOOST_VERSION//./_}\"\nBOOST_FILE=\"boost_${BOOST_VERSION_UNDERSCORE}.tar.bz2\"\nBOOST_TAR_URL=\"https://boostorg.jfrog.io/artifactory/main/release/${BOOST_VERSION}/source/${BOOST_FILE}\"\nBOOST_DIR=\"boost_${BOOST_VERSION_UNDERSCORE}\"\n\nset -e\n\nwget \"$BOOST_TAR_URL\" -O \"$BOOST_FILE\"\ntar --bzip2 -xf \"$BOOST_FILE\"\ncd \"$BOOST_DIR\"\n./bootstrap.sh --with-libraries=thread\n./b2 -d0 install\n", "num_lines": 21}
{"repo_name": "tac_plus", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /usr/bin/env sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2019-02-19.15\n\n# libtool (GNU libtool) 2.4.7\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=2.4.7\npackage_revision=2.4.7\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2019-02-19.15; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# This is free software.  There is NO warranty; not even for\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# Copyright (C) 2004-2019, 2021 Bootstrap Authors\n#\n# This file is dual licensed under the terms of the MIT license\n# <https://opensource.org/license/MIT>, and GPL version 2 or later\n# <http://www.gnu.org/licenses/gpl-2.0.html>.  You must apply one of\n# these licenses when using or redistributing this software or any of\n# the files within it.  See the URLs above, or the file `LICENSE`\n# included in the Bootstrap distribution for the full license texts.\n\n# Please report bugs or propose patches to:\n# <https://github.com/gnulib-modules/bootstrap/issues>\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n# These NLS vars are set unconditionally (bootstrap issue #24).  Unset those\n# in case the environment reset is needed later and the $save_* variant is not\n# defined (see the code above).\nLC_ALL=C\nLANGUAGE=C\nexport LANGUAGE LC_ALL\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n# func_unset VAR\n# --------------\n# Portably unset VAR.\n# In some shells, an 'unset VAR' statement leaves a non-zero return\n# status if VAR is already unset, which might be problematic if the\n# statement is used at the end of a function (thus poisoning its return\n# value) or when 'set -e' is active (causing even a spurious abort of\n# the script in this case).\nfunc_unset ()\n{\n    { eval $1=; (eval unset $1) >/dev/null 2>&1 && eval unset $1 || : ; }\n}\n\n\n# Make sure CDPATH doesn't cause `cd` commands to output the target dir.\nfunc_unset CDPATH\n\n# Make sure ${,E,F}GREP behave sanely.\nfunc_unset GREP_OPTIONS\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed \"$PATH:/usr/xpg4/bin\"\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep \"$PATH:/usr/xpg4/bin\"\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n# require_check_ifs_backslash\n# ---------------------------\n# Check if we can use backslash as IFS='\\' separator, and set\n# $check_ifs_backshlash_broken to ':' or 'false'.\nrequire_check_ifs_backslash=func_require_check_ifs_backslash\nfunc_require_check_ifs_backslash ()\n{\n  _G_save_IFS=$IFS\n  IFS='\\'\n  _G_check_ifs_backshlash='a\\\\b'\n  for _G_i in $_G_check_ifs_backshlash\n  do\n  case $_G_i in\n  a)\n    check_ifs_backshlash_broken=false\n    ;;\n  '')\n    break\n    ;;\n  *)\n    check_ifs_backshlash_broken=:\n    break\n    ;;\n  esac\n  done\n  IFS=$_G_save_IFS\n  require_check_ifs_backslash=:\n}\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='eval echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_arg pretty \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_arg_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_arg pretty \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_arg_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_portable EVAL ARG\n# ----------------------------\n# Internal function to portably implement func_quote_arg.  Note that we still\n# keep attention to performance here so we as much as possible try to avoid\n# calling sed binary (so far O(N) complexity as long as func_append is O(1)).\nfunc_quote_portable ()\n{\n    $debug_cmd\n\n    $require_check_ifs_backslash\n\n    func_quote_portable_result=$2\n\n    # one-time-loop (easy break)\n    while true\n    do\n      if $1; then\n        func_quote_portable_result=`$ECHO \"$2\" | $SED \\\n          -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"`\n        break\n      fi\n\n      # Quote for eval.\n      case $func_quote_portable_result in\n        *[\\\\\\`\\\"\\$]*)\n          # Fallback to sed for $func_check_bs_ifs_broken=:, or when the string\n          # contains the shell wildcard characters.\n          case $check_ifs_backshlash_broken$func_quote_portable_result in\n            :*|*[\\[\\*\\?]*)\n              func_quote_portable_result=`$ECHO \"$func_quote_portable_result\" \\\n                  | $SED \"$sed_quote_subst\"`\n              break\n              ;;\n          esac\n\n          func_quote_portable_old_IFS=$IFS\n          for _G_char in '\\' '`' '\"' '$'\n          do\n            # STATE($1) PREV($2) SEPARATOR($3)\n            set start \"\" \"\"\n            func_quote_portable_result=dummy\"$_G_char$func_quote_portable_result$_G_char\"dummy\n            IFS=$_G_char\n            for _G_part in $func_quote_portable_result\n            do\n              case $1 in\n              quote)\n                func_append func_quote_portable_result \"$3$2\"\n                set quote \"$_G_part\" \"\\\\$_G_char\"\n                ;;\n              start)\n                set first \"\" \"\"\n                func_quote_portable_result=\n                ;;\n              first)\n                set quote \"$_G_part\" \"\"\n                ;;\n              esac\n            done\n          done\n          IFS=$func_quote_portable_old_IFS\n          ;;\n        *) ;;\n      esac\n      break\n    done\n\n    func_quote_portable_unquoted_result=$func_quote_portable_result\n    case $func_quote_portable_result in\n      # double-quote args containing shell metacharacters to delay\n      # word splitting, command substitution and variable expansion\n      # for a subsequent eval.\n      # many bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        func_quote_portable_result=\\\"$func_quote_portable_result\\\"\n        ;;\n    esac\n}\n\n\n# func_quotefast_eval ARG\n# -----------------------\n# Quote one ARG (internal).  This is equivalent to 'func_quote_arg eval ARG',\n# but optimized for speed.  Result is stored in $func_quotefast_eval.\nif test xyes = `(x=; printf -v x %q yes; echo x\"$x\") 2>/dev/null`; then\n  printf -v _GL_test_printf_tilde %q '~'\n  if test '\\~' = \"$_GL_test_printf_tilde\"; then\n    func_quotefast_eval ()\n    {\n      printf -v func_quotefast_eval_result %q \"$1\"\n    }\n  else\n    # Broken older Bash implementations.  Make those faster too if possible.\n    func_quotefast_eval ()\n    {\n      case $1 in\n        '~'*)\n          func_quote_portable false \"$1\"\n          func_quotefast_eval_result=$func_quote_portable_result\n          ;;\n        *)\n          printf -v func_quotefast_eval_result %q \"$1\"\n          ;;\n      esac\n    }\n  fi\nelse\n  func_quotefast_eval ()\n  {\n    func_quote_portable false \"$1\"\n    func_quotefast_eval_result=$func_quote_portable_result\n  }\nfi\n\n\n# func_quote_arg MODEs ARG\n# ------------------------\n# Quote one ARG to be evaled later.  MODEs argument may contain zero or more\n# specifiers listed below separated by ',' character.  This function returns two\n# values:\n#   i) func_quote_arg_result\n#      double-quoted (when needed), suitable for a subsequent eval\n#  ii) func_quote_arg_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.  Available only if 'unquoted' is specified.\n#\n# Available modes:\n# ----------------\n# 'eval' (default)\n#       - escape shell special characters\n# 'expand'\n#       - the same as 'eval';  but do not quote variable references\n# 'pretty'\n#       - request aesthetic output, i.e. '\"a b\"' instead of 'a\\ b'.  This might\n#         be used later in func_quote to get output like: 'echo \"a b\"' instead\n#         of 'echo a\\ b'.  This is slower than default on some shells.\n# 'unquoted'\n#       - produce also $func_quote_arg_unquoted_result which does not contain\n#         wrapping double-quotes.\n#\n# Examples for 'func_quote_arg pretty,unquoted string':\n#\n#   string      | *_result              | *_unquoted_result\n#   ------------+-----------------------+-------------------\n#   \"           | \\\"                    | \\\"\n#   a b         | \"a b\"                 | a b\n#   \"a b\"       | \"\\\"a b\\\"\"             | \\\"a b\\\"\n#   *           | \"*\"                   | *\n#   z=\"${x-$y}\" | \"z=\\\"\\${x-\\$y}\\\"\"     | z=\\\"\\${x-\\$y}\\\"\n#\n# Examples for 'func_quote_arg pretty,unquoted,expand string':\n#\n#   string        |   *_result          |  *_unquoted_result\n#   --------------+---------------------+--------------------\n#   z=\"${x-$y}\"   | \"z=\\\"${x-$y}\\\"\"     | z=\\\"${x-$y}\\\"\nfunc_quote_arg ()\n{\n    _G_quote_expand=false\n    case ,$1, in\n      *,expand,*)\n        _G_quote_expand=:\n        ;;\n    esac\n\n    case ,$1, in\n      *,pretty,*|*,expand,*|*,unquoted,*)\n        func_quote_portable $_G_quote_expand \"$2\"\n        func_quote_arg_result=$func_quote_portable_result\n        func_quote_arg_unquoted_result=$func_quote_portable_unquoted_result\n        ;;\n      *)\n        # Faster quote-for-eval for some shells.\n        func_quotefast_eval \"$2\"\n        func_quote_arg_result=$func_quotefast_eval_result\n        ;;\n    esac\n}\n\n\n# func_quote MODEs ARGs...\n# ------------------------\n# Quote all ARGs to be evaled later and join them into single command.  See\n# func_quote_arg's description for more info.\nfunc_quote ()\n{\n    $debug_cmd\n    _G_func_quote_mode=$1 ; shift\n    func_quote_result=\n    while test 0 -lt $#; do\n      func_quote_arg \"$_G_func_quote_mode\" \"$1\"\n      if test -n \"$func_quote_result\"; then\n        func_append func_quote_result \" $func_quote_arg_result\"\n      else\n        func_append func_quote_result \"$func_quote_arg_result\"\n      fi\n      shift\n    done\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_arg pretty,expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_arg_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_arg expand,pretty \"$_G_cmd\"\n      eval \"func_echo $func_quote_arg_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# This is free software.  There is NO warranty; not even for\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# Copyright (C) 2010-2019, 2021 Bootstrap Authors\n#\n# This file is dual licensed under the terms of the MIT license\n# <https://opensource.org/license/MIT>, and GPL version 2 or later\n# <http://www.gnu.org/licenses/gpl-2.0.html>.  You must apply one of\n# these licenses when using or redistributing this software or any of\n# the files within it.  See the URLs above, or the file `LICENSE`\n# included in the Bootstrap distribution for the full license texts.\n\n# Please report bugs or propose patches to:\n# <https://github.com/gnulib-modules/bootstrap/issues>\n\n# Set a version string for this script.\nscriptversion=2019-02-19.15; # UTC\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# Copyright'.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug in processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# in the main code.  A hook is just a list of function names that can be\n# run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of hook functions to be called by\n# FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_propagate_result FUNC_NAME_A FUNC_NAME_B\n# ---------------------------------------------\n# If the *_result variable of FUNC_NAME_A _is set_, assign its value to\n# *_result variable of FUNC_NAME_B.\nfunc_propagate_result ()\n{\n    $debug_cmd\n\n    func_propagate_result_result=:\n    if eval \"test \\\"\\${${1}_result+set}\\\" = set\"\n    then\n      eval \"${2}_result=\\$${1}_result\"\n    else\n      func_propagate_result_result=false\n    fi\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It's assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook functions.\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      func_unset \"${_G_hook}_result\"\n      eval $_G_hook '${1+\"$@\"}'\n      func_propagate_result $_G_hook func_run_hooks\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n      fi\n    done\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list from your hook function.  You may remove\n# or edit any options that you action, and then pass back the remaining\n# unprocessed options in '<hooked_function_name>_result', escaped\n# suitably for 'eval'.\n#\n# The '<hooked_function_name>_result' variable is automatically unset\n# before your hook gets called; for best performance, only set the\n# *_result variable when necessary (i.e. don't call the 'func_quote'\n# function unnecessarily because it can be an expensive operation on some\n# machines).\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  Leave\n#        # my_options_prep_result variable intact.\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that, for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\" in case we need it later,\n#                         # if $args_changed was set to 'true'.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        # Only call 'func_quote' here if we processed at least one argument.\n#        if $args_changed; then\n#          func_quote eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_result\n#        fi\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    func_run_hooks func_options ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_options_finish\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_options_quoted=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      func_unset func_${my_func}_result\n      func_unset func_run_hooks_result\n      eval func_$my_func '${1+\"$@\"}'\n      func_propagate_result func_$my_func func_options\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_options_result\"; shift\n        _G_options_quoted=:\n      fi\n    done\n\n    $_G_options_quoted || {\n      # As we (func_options) are top-level options-parser function and\n      # nobody quoted \"$@\" for us yet, we need to do it explicitly for\n      # caller.\n      func_quote eval ${1+\"$@\"}\n      func_options_result=$func_quote_result\n    }\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before returning.\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    func_run_hooks func_options_prep ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    _G_parse_options_requote=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      func_run_hooks func_parse_options ${1+\"$@\"}\n      func_propagate_result func_run_hooks func_parse_options\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_parse_options_result\"; shift\n        # Even though we may have changed \"$@\", we passed the \"$@\" array\n        # down into the hook and it quoted it for us (because we are in\n        # this if-branch).  No need to quote it again.\n        _G_parse_options_requote=false\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      # We expect that one of the options parsed in this function matches\n      # and thus we remove _G_opt from \"$@\" and need to re-quote.\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\" >&2\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_parse_options_requote=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_parse_options_requote=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      if $_G_match_parse_options; then\n        _G_parse_options_requote=:\n      fi\n    done\n\n    if $_G_parse_options_requote; then\n      # save modified positional parameters for caller\n      func_quote eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_result\n    fi\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    func_run_hooks func_validate_options ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_validate_options\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables\n# after splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      if test \"x$func_split_equals_lhs\" = \"x$1\"; then\n        func_split_equals_rhs=\n      fi\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs=\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x\\(-.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\n# The version message is extracted from the calling file's header\n# comments, with leading '# ' stripped:\n#   1. First display the progname and version\n#   2. Followed by the header comment line matching  /^# Written by /\n#   3. Then a blank line followed by the first following line matching\n#      /^# Copyright /\n#   4. Immediately followed by any lines between the previous matches,\n#      except lines preceding the intervening completely blank line.\n# For example, see the header comments of this file.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /^# Written by /!b\n        s|^# ||; p; n\n\n        :fwd2blnk\n        /./ {\n          n\n          b fwd2blnk\n        }\n        p; n\n\n        :holdwrnt\n        s|^# ||\n        s|^# *$||\n        /^Copyright /!{\n          /./H\n          n\n          b holdwrnt\n        }\n\n        s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n        G\n        s|\\(\\n\\)\\n*|\\1|g\n        p; q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"30/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.7'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname (GNU libtool) 2.4.7\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/software/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func_fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_result\n    fi\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_result\n    fi\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    # Keeping compiler generated duplicates in $postdeps and $predeps is not\n    # harmful, and is necessary in a majority of systems that use it to satisfy\n    # symbol dependencies.\n    opt_duplicate_compiler_generated_deps=:\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_arg pretty \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_arg_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_arg pretty \"$srcfile\"\n    qsrcfile=$func_quote_arg_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG\n  -Xcompiler FLAG   pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wa,FLAG\n  -Xassembler FLAG  pass linker-specific FLAG directly to the assembler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_arg pretty \"$nonopt\"\n      install_prog=\"$func_quote_arg_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_arg pretty \"$arg\"\n    func_append install_prog \"$func_quote_arg_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_arg pretty \"$arg\"\n      func_append install_prog \" $func_quote_arg_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_arg pretty \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_arg_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_arg pretty \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_arg_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_arg expand,pretty \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_arg_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    func_quote_arg pretty \"$ECHO\"\n    qECHO=$func_quote_arg_result\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=$qECHO\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_arg pretty,unquoted \"$arg\"\n      qarg=$func_quote_arg_unquoted_result\n      func_append libtool_args \" $func_quote_arg_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txassembler)\n\t  func_append compiler_flags \" -Xassembler $qarg\"\n\t  prev=\n\t  func_append compile_command \" -Xassembler $qarg\"\n\t  func_append finalize_command \" -Xassembler $qarg\"\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n     # Solaris ld rejects as of 11.4. Refer to Oracle bug 22985199.\n     -pthread)\n\tcase $host in\n\t  *solaris2*) ;;\n\t  *)\n\t    case \"$new_inherited_linker_flags \" in\n\t        *\" $arg \"*) ;;\n\t        * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\t    esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n      -mt|-mthreads|-kthread|-Kthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_arg pretty \"$flag\"\n\t  func_append arg \" $func_quote_arg_result\"\n\t  func_append compiler_flags \" $func_quote_arg_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_arg pretty \"$flag\"\n\t  func_append arg \" $wl$func_quote_arg_result\"\n\t  func_append compiler_flags \" $wl$func_quote_arg_result\"\n\t  func_append linker_flags \" $func_quote_arg_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xassembler)\n        prev=xassembler\n        continue\n        ;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -Wa,*                Pass flags directly to the assembler\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-Wa,*)\n        func_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_arg pretty \"$arg\"\n\t  arg=$func_quote_arg_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink) libs=\"$deplibs %DEPLIBS% $dependency_libs\" ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    deplibs=\"$deplib $deplibs\"\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | $SED 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|midnightbsd-elf|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf | midnightbsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_arg expand,pretty \"$cmd\"\n\t\t  eval \"func_echo $func_quote_arg_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_arg expand,pretty \"$cmd\"\n\t    eval \"func_echo $func_quote_arg_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_arg pretty \"$var_value\"\n\t    relink_command=\"$var=$func_quote_arg_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\tfunc_quote eval cd \"`pwd`\"\n\tfunc_quote_arg pretty,unquoted \"($func_quote_result; $relink_command)\"\n\trelink_command=$func_quote_arg_unquoted_result\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_arg pretty,unquoted \"$var_value\"\n\t  relink_command=\"$var=$func_quote_arg_unquoted_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      func_quote eval cd \"`pwd`\"\n      relink_command=\"($func_quote_result; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      func_quote_arg pretty,unquoted \"$relink_command\"\n      relink_command=$func_quote_arg_unquoted_result\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11430}
{"repo_name": "taste-tester", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# #     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o verbose\nrm -rf /tmp/ops\n\nfunction tt {\n  bundle exec ./bin/taste-tester test -s localhost -y -c $1\n}\n(\n  mkdir /tmp/ops\n)\ntt ./test/tt-auto.rb\nif [ $? -ne 0 ]; then\n  exit 0\nfi\n", "num_lines": 31}
{"repo_name": "taste-tester", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o verbose\nrm -rf /tmp/ops\nGIT=\"git -c user.email='foo@bar.com' -c user.name='foobar'\"\n\nfunction tt {\n  bundle exec ./bin/taste-tester test -s localhost -y -c $1 -v\n}\n(\n  git init /tmp/ops\n  cd /tmp/ops\n  mkdir chef/cookbooks/cookbook1/recipes -p\n  touch chef/cookbooks/cookbook1/recipes/default.rb\n  echo \"name 'cookbook1'\" > chef/cookbooks/cookbook1/metadata.rb\n  $GIT add . -A\n  $GIT commit -m \"Add cookbook1\"\n)\ntt ./test/tt-git.rb\ntt ./test/tt-auto.rb\n", "num_lines": 38}
{"repo_name": "taste-tester", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o verbose\nrm -rf /tmp/ops\nHG=\"hg --config ui.username=foo@bar.com\"\n\nfunction tt {\n  bundle exec ./bin/taste-tester test -s localhost -y -c $1 -v\n}\n(\n  mkdir /tmp/ops\n  cd /tmp/ops\n  hg init\n  mkdir chef/cookbooks/cookbook1/recipes -p\n  touch chef/cookbooks/cookbook1/recipes/default.rb\n  echo \"name 'cookbook1'\" > chef/cookbooks/cookbook1/metadata.rb\n  $HG add .\n  $HG commit -m \"Add cookbook1\"\n)\ntt ./test/tt-hg.rb\ntt ./test/tt-auto.rb\n", "num_lines": 39}
{"repo_name": "taste-tester", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# vim: syntax=ruby:expandtab:shiftwidth=2:softtabstop=2:tabstop=2\n\n# Copyright 2013-present Facebook\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o verbose\n./test/run-git.sh\n./test/run-hg.sh\n./test/run-broken.sh\n", "num_lines": 24}
{"repo_name": "TestSlide", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -euxo pipefail\n\nrelease_version=${1?\"Usage: $0 <release_version>\"}\n\ngit checkout main\ngit pull\n\necho $release_version > testslide/version\nsed -i -e \"s/Version .*/Version $release_version/\" \\\n    util/testslide-snippets/README.md \\\n    util/testslide-snippets/CHANGELOG.md\nsed -i -e \"s/\\\"version\\\":.*/\\\"version\\\": \\\"$release_version\\\",/\" util/testslide-snippets/package.json\necho $release_version > pytest-testslide/testslide-version\ngit add testslide/version util/testslide-snippets\ngit add pytest-testslide/testslide-version\ngit commit -m \"v$release_version\"\ngit push origin main:release_v$release_version\n\ngit tag $release_version\ngit push origin $release_version\n", "num_lines": 28}
{"repo_name": "ThreatExchange", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\n# Add all the values from terraform/outputs.tf to the local env (call upcase with prefix HMA_)\n# usage:\n#    $ source scripts/set_tf_outputs_in_local_env.sh\n\n[[ $_ != $0 ]] && echo \"Error: this script needs to be 'source'd not run.\" && exit\nfor s in $(terraform -chdir=terraform output -json | jq -r \"to_entries|map(\\\"HMA_\\(.key|ascii_upcase)=\\(.value.value|tostring)\\\")|.[]\"); do\n    export $s\ndone\n", "num_lines": 12}
{"repo_name": "ThreatExchange", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nset -e\n\nSCRIPT_NAME=\"$(basename \\\"$0\\\")\"\n\nif [[ -z \"${DOCKER_TAG}\" ]]; then\n    echo \"Please rerun with a DOCKER_TAG set in your local environment\" >&2\n    echo \"e.g., DOCKER_TAG=my_prefix $0\" >&2\n    exit 1\nfi\n\nif [ -d \"local-threatexchange\" ]; then\n    echo \"################### WARNING ######################\"\n    echo \"  Using a local copy of threatexchange from the   \"\n    echo \"  local-threatexchange directory to build the \"\n    echo \"  docker image.\"\n    echo \" Run './scripts/set_threatexchange_source pypi' if \"\n    echo \" this is not what you want. \"\n    echo \"##################################################\"\nfi\n\nREPOSITORY_NAME=\"hma-lambda-dev\"\n\nECS_PASSWORD=\"$(aws ecr get-login-password --region us-east-1)\"\nECR_REPOSITORY_URI=\"$(aws ecr describe-repositories --repository-names hma-lambda-dev | jq -r '.repositories[0].repositoryUri')\"\n\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\necho \"$ECS_PASSWORD\" | docker login --username AWS --password-stdin \"$ECR_REPOSITORY_URI\"\ndocker build -f Dockerfile -t \"$REPOSITORY_NAME\" .\ndocker tag \"$REPOSITORY_NAME\" \"${ECR_REPOSITORY_URI}:${DOCKER_TAG}\"\ndocker push \"${ECR_REPOSITORY_URI}:${DOCKER_TAG}\"\n", "num_lines": 34}
{"repo_name": "ThreatExchange", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\n[[ ! -z \"$TF_STATE_S3_BUCKET\" ]] && s3_bucket=\"$TF_STATE_S3_BUCKET\" || s3_bucket=\"threatexchange-tf-state\"\n[[ ! -z \"$TF_STATE_S3_KEY\" ]] && s3_key=\"$TF_STATE_S3_KEY\" || s3_key=\"state\\/hasher-matcher-actioner-$(whoami).tfstate\"\n[[ ! -z \"$TF_STATE_AWS_REGION\" ]] && aws_region=\"$TF_STATE_AWS_REGION\" || aws_region=\"us-east-1\"\n[[ ! -z \"$TF_STATE_LOCKING_TABLE\" ]] && table_name=\"$TF_STATE_LOCKING_TABLE\" || table_name=\"terraform-state-locking\"\n\nsed \\\n    -e \"s/# TERRAFORM_STATE_S3_BUCKET/\\\"${s3_bucket}\\\"/\" \\\n    -e \"s/# TERRAFORM_STATE_KEY/\\\"${s3_key}\\\"/\" \\\n    -e \"s/# TERRAFORM_BUCKET_REGION/\\\"${aws_region}\\\"/\" \\\n    -e \"s/# TERRAFORM_STATE_LOCKING_TABLE/\\\"${table_name}\\\"/\" \\\n    terraform/backend.tf.example\n", "num_lines": 15}
{"repo_name": "ThreatExchange", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nset -e\n\nmake clean\nphpize\n./configure --enable-pdq\nmake\necho\necho REBUILT\n", "num_lines": 12}
{"repo_name": "ThreatExchange", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n\nfor mp4 in ../sample-videos/*.mp4; do\n  tmk=$(echo $(basename $mp4) | sed 's/mp4/tmk/')\n  ../cpp/tmk-hash-video -i $mp4 -o $tmk -f /usr/local/bin/ffmpeg\ndone\n", "num_lines": 8}
{"repo_name": "usort", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -eu\n\ndie() { echo \"$1\"; exit 1; }\n\nwhile read filename; do \\\n  grep -q \"^# Copyright (c) Meta Platforms, Inc. and affiliates.\" \"$filename\" ||\n    die \"Missing copyright in $filename\"\ndone < <( git ls-tree -r --name-only HEAD | grep \"\\(.py\\|\\.sh\\)$\" )\n\n", "num_lines": 17}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# vim:ts=2:sw=2:et:\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\"\n\nset -x\nPREFIX=${PREFIX:-/usr/local}\npython3 build/fbcode_builder/getdeps.py build \\\n        --allow-system-packages \\\n        --src-dir=. \\\n        \"--project-install-prefix=watchman:$PREFIX\" \\\n        watchman\npython3 build/fbcode_builder/getdeps.py fixup-dyn-deps \\\n        --allow-system-packages \\\n        --src-dir=. \\\n        \"--project-install-prefix=watchman:$PREFIX\" \\\n        --final-install-prefix \"$PREFIX\" \\\n        watchman built\n\nfind built -ls\n", "num_lines": 25}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# vim:ts=2:sw=2:et:\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\npython3 \"$(dirname \"$0\")/build/fbcode_builder/getdeps.py\" install-system-deps --recursive watchman\n", "num_lines": 10}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# vim:ts=2:sw=2:et:\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -x\npython3 \"$(dirname \"$0\")/build/fbcode_builder/getdeps.py\" test --allow-system-packages --no-testpilot watchman\n", "num_lines": 10}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\"\n\ncd /__w/watchman/watchman\n\ncd \"$(git rev-parse --show-toplevel)\"\n\n# Why /usr/local? This .deb does not hold to any rigorous packaging\n# standards (e.g. Debian), and is intended to replace existing ad hoc\n# Watchman installations.\n#\n# Until we have a reason otherwise, let's remain compatible with\n# legacy installation paths.\nPREFIX=\"/usr/local\"\n\n# Generated by the prior invocation of ./autogen.sh\nBUILT=\"/__w/watchman/watchman/built\"\n\nfind \"$BUILT\"\n\nset -x\n\n# This is an implicit assertion that the `lib` directory is empty.\n# We statically link dependencies for packaging purposes.\nrmdir \"$BUILT/lib\"\n\n# TODO: make a debuginfo package\nstrip \"$BUILT/bin/watchman\"\nstrip \"$BUILT/bin/watchmanctl\"\n\nPACKAGE_VERSION=$(\"$BUILT/bin/watchman\" --version)\n\nPACKAGE_WORKDIR=$(mktemp -d)\ntrap 'rm -rf -- \"$PACKAGE_WORKDIR\"' EXIT\n\nmkdir -p \"$PACKAGE_WORKDIR$PREFIX\"\ncp -ar \"$BUILT/bin\" \"$PACKAGE_WORKDIR$PREFIX/bin\"\n\ncp -ar /__w/watchman/watchman/watchman/build/package/watchman-deb/DEBIAN \"$PACKAGE_WORKDIR\"\n\npython3 /__w/watchman/watchman/watchman/build/package/substcontrol.py \"$PACKAGE_WORKDIR/DEBIAN/control\" \"$PACKAGE_VERSION\" \"$UBUNTU_VERSION\"\n\nmkdir -p /_debs\n\nDEB_OUTPUT=\"/_debs/watchman.deb\"\n\ndpkg-deb -b \"$PACKAGE_WORKDIR\" \"$DEB_OUTPUT\"\n", "num_lines": 53}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\"\n\n# buildkit truncates log output.\n# https://stackoverflow.com/questions/65819424/is-there-a-way-to-increase-the-log-size-in-docker-when-building-a-container\nexport DOCKER_BUILDKIT=0\n\nDB=\"docker build --progress plain\"\n\nUBUNTU_VERSIONS=\"18 20 22\"\n\n# There may be an opportunity to run some of these in parallel.\nfor uv in $UBUNTU_VERSIONS; do\n    $DB --build-arg \"UBUNTU_VERSION=$uv.04\" -t \"watchman-ubuntu-$uv-env\" ubuntu-env\n\n    $DB --build-arg \"BASE_IMAGE=watchman-ubuntu-$uv-env\" -t \"watchman-ubuntu-$uv-build\" watchman-build\n\n    $DB --build-arg \"BASE_IMAGE=watchman-ubuntu-$uv-build\" -t \"watchman-ubuntu-$uv-deb\" watchman-deb\n\n    mkdir -p \"_debs/ubuntu-$uv\"\n\n    docker run --rm --mount \"type=bind,source=$(pwd)/_debs,target=/_out\" \"watchman-ubuntu-$uv-deb\" sh -c \"cp /_debs/* /_out/ubuntu-$uv\"\ndone\n", "num_lines": 29}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\"\n\ncd /__w/watchman/watchman\n\ncd \"$(git rev-parse --show-toplevel)\"\n\n# Why /usr/local? This .deb does not hold to any rigorous packaging\n# standards (e.g. Debian), and is intended to replace existing ad hoc\n# Watchman installations.\n#\n# Until we have a reason otherwise, let's remain compatible with\n# legacy installation paths.\nPREFIX=\"/usr/local\"\n\n# Generated by the prior invocation of ./autogen.sh\nBUILT=\"/__w/watchman/watchman/built\"\n\nfind \"$BUILT\"\n\nset -x\n\n# This is an implicit assertion that the `lib` directory is empty.\n# We statically link dependencies for packaging purposes.\nrmdir \"$BUILT/lib\"\n\nPACKAGE_VERSION=$(\"$BUILT/bin/watchman\" --version)\n\nPACKAGE_WORKDIR=$(mktemp -d)\ntrap 'rm -rf -- \"$PACKAGE_WORKDIR\"' EXIT\n\nSPECS=\"$PACKAGE_WORKDIR/SPECS\"\n\nmkdir -p \"$SPECS\"\n\ncp watchman/build/package/watchman.spec \"$SPECS/watchman.spec\"\n\nrpmbuild \\\n    -bb \\\n    --define \"dist .fc$FEDORA_VERSION\" \\\n    --define \"_rpmdir $PACKAGE_WORKDIR/RPMS\" \\\n    --define \"version $PACKAGE_VERSION\" \\\n    --define \"prefix $PREFIX/\" \\\n    --define \"image $BUILT\" \\\n    \"$SPECS/watchman.spec\"\n\nmkdir -p /_rpms\ncp -a \"$PACKAGE_WORKDIR\"/RPMS/x86_64/*.rpm /_rpms\n\nfind /_rpms\n\nfor rpm in /_rpms/*.rpm; do\n    echo \"::set-output name=rpm_path::$rpm\"\n    echo \"::set-output name=rpm_name::$(basename \"$rpm\")\"\n    break\ndone\n", "num_lines": 62}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\ncd \"$(dirname \"$0\")\"\ncd \"$(git rev-parse --show-toplevel)\"\n\n# Why /usr/local? This .deb does not hold to any rigorous packaging\n# standards (e.g. Debian), and is intended to replace existing ad hoc\n# Watchman installations.\n#\n# Until we have a reason otherwise, let's remain compatible with\n# legacy installation paths.\nPREFIX=\"/usr/local\"\n\nset -x\n\nif [[ $BUILT = \"\" ]]; then\n    BUILT=$(mktemp -d)\n    trap 'rm -rf -- \"$BUILT\"' EXIT\n\n    sudo python3 build/fbcode_builder/getdeps.py install-system-deps \\\n         --recursive watchman\n\n    python3 build/fbcode_builder/getdeps.py build \\\n            --allow-system-packages \\\n            --src-dir=. \\\n            \"--project-install-prefix=watchman:$PREFIX\" \\\n            watchman\n\n    python3 build/fbcode_builder/getdeps.py fixup-dyn-deps \\\n            --allow-system-packages \\\n            --src-dir=. \\\n            \"--project-install-prefix=watchman:$PREFIX\" \\\n            --final-install-prefix \"$PREFIX\" \\\n            watchman \\\n            \"$BUILT\"\nfi\n\n# This is an implicit assertion that the `lib` directory is empty.\n# We statically link dependencies for packaging purposes.\nrmdir \"$BUILT/lib\"\n\nPACKAGE_VERSION=$(\"$BUILT/bin/watchman\" --version)\n\nPACKAGE_WORKDIR=$(mktemp -d)\ntrap 'rm -rf -- \"$PACKAGE_WORKDIR\"' EXIT\n\nmkdir -p \"$PACKAGE_WORKDIR$PREFIX\"\ncp -ar \"$BUILT/bin\" \"$PACKAGE_WORKDIR$PREFIX/bin\"\ncp -ar watchman/build/package/DEBIAN \"$PACKAGE_WORKDIR\"\n\nsed -i \"s/%VERSION%/$PACKAGE_VERSION/\" \"$PACKAGE_WORKDIR/DEBIAN/control\"\n\nmkdir -p /_debs\n\nDEB_OUTPUT=\"/_debs/watchman_$PACKAGE_VERSION.deb\"\n\n# TODO: use dpkg-shlibdeps to automate generation of the runtime\n# dependency list\n\ndpkg-deb -b \"$PACKAGE_WORKDIR\" \"$DEB_OUTPUT\"\n", "num_lines": 65}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n#\n# ===============================\n# pywatchman pypi publishing tool\n# ===============================\n#\n# this publishes the watchman python module to the pypi project\n# index located at https://pypi.python.org/pypi/pywatchman. the\n# metadata used for this process comes directly from setup.py.\n#\n# this requires write access to the pywatchman project on pypi\n# as well as a ~/.pypirc of the following form:\n#\n#    [distutils]\n#    index-servers = pypi\n#\n#    [pypi]\n#    repository: https://pypi.python.org/pypi\n#    username: <pypi_username>\n#    password: <pypi_password>\n#\n\npython setup.py sdist bdist_wheel upload -r pypi\n", "num_lines": 29}
{"repo_name": "watchman", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n#\n# This source code is licensed under the MIT license found in the\n# LICENSE file in the root directory of this source tree.\n\n# This is a dumb wrapper to satisfy the buck_sh_test rule\nexec \"$@\"\n", "num_lines": 9}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Quick hack to figure out where is the space coming from\n\nFILE=$1\nif [ -z \"$FILE\" -o \"$FILE\" = \"-h\" ] ; then\n  echo \"Usage: $0 binary\"\n  exit 1\nfi\n\nTMPRESULT=`mktemp /tmp/nm_out.XXX`\n\nRESULT=$TMPRESULT\n\necho \"Working on $FILE, intermediate nm result in $RESULT\"\n\nnm -C --defined-only --print-size -l $FILE > $RESULT\n\necho \"nm done... analyzing...\"\n#RESULT=/dev/shm/nm.out\n\ngawk '\n{sizeHex=\"0x\" $2; size=strtonum(sizeHex); sum+=size}\n/:[0-9]+$/ {\n  if (size) {\n    ssum += size;\n    # not all lines of nm output do find a file with line number this finds\n    # lines like    \"xxxx/blah.cc:123\" and returns \"xxxx/blah\"\n    # for the xxx part it tries to keep it shorter by not allowing .\n    # (nm sometimes outputs  path/./tmp/morepath)\n    match($0, \"([^ \\t.]+)(\\\\.(h|c|cc|tcc|cpp|hpp|S|rl|ipp|y))?:[0-9]+$\", arr);\n    src=arr[1]\n    # unknown extensions...\n    if (length(src) < 5) print src, \"  XXXX \", $0;\n    # get rid of irrelevant stuff\n    sub(\"/tmp/\", \"/\", src)\n    # somehow lots of ....fbcode...////////morestuf\n    sub(\".*///\", \"\", src)\n    # x/ or y/ ...\n    sub(\"^./\", \"\", src)\n    # 20/....\n    sub(\"^[0-9/]+\", \"\", src)\n    sizes[src] += size;\n    match(src, \"(.*)/[^/]*$\", pkg);\n    sizes[pkg[1] \"/*\"]+= size;\n  }\n}\nEND {\n  print \"Extracted file attribution for\", ssum/1024/1024., \"Mb out of\",\n     sum/1024/1024., \"Mb :\", int((1000*ssum/sum+.5))/10, \"%\"\n  n = asorti(sizes, siter)\n  for (s in sizes) {\n    print s, sizes[s]\n  }\n}' $RESULT | sort -k 2 -n\n\nrm $TMPRESULT\n", "num_lines": 57}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/bash\nfind . -type f -a \\( -name \"*.h\" -o -name \"*.cpp\" \\) | xargs clang-format -i\n", "num_lines": 3}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nfind . \\( -name \"*~\" -o -name \"*.orig\" -o -name \"*.rej\" -o -name \"#*#\" \\\n    -o -name \".#*\" \\) -print0 | xargs -0 rm -v\n", "num_lines": 4}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n\ncat <<EOF\n[{\n    \"alias\": \"wdt-opensource-linux\",\n    \"command\": \"SandcastleUniversalCommand\",\n    \"vcsType\": \"fbcode-fbsource\",\n    \"capabilities\": {\n        \"vcs\": \"fbcode-fbsource\",\n        \"type\": \"lego-linux\",\n        \"os\": \"ubuntu_16.04\"\n    },\n    \"priority\": 3,\n    \"args\": {\n        \"name\": \"wdt-opensource-linux\",\n        \"oncall\": \"wdt\",\n        \"timeout\": 10800,\n        \"steps\": [\n            {\n                \"user\": \"facebook\",\n                \"name\": \"Build Wdt OpenSource Linux\",\n                \"shell\": \"wdt/build/lego-linux-build.sh\",\n                \"required\": true\n            },\n            {\n                \"user\": \"facebook\",\n                \"name\": \"Run Wdt OpenSource Linux Tests\",\n                \"shell\": \"cd wdt_build; CTEST_OUTPUT_ON_FAILURE=1 make test\",\n                \"required\": true\n            }\n        ]\n    }\n},\n{\n    \"alias\": \"wdt-opensource-mac\",\n    \"command\": \"SandcastleUniversalCommand\",\n    \"vcsType\": \"fbcode-fbsource\",\n    \"capabilities\": {\n        \"vcs\": \"fbcode-fbsource\",\n        \"type\": \"lego-mac\",\n    },\n    \"priority\": 3,\n    \"args\": {\n        \"name\": \"wdt-opensource-mac\",\n        \"oncall\": \"wdt\",\n        \"timeout\": 10800,\n        \"steps\": [\n            {\n                \"user\": \"facebook\",\n                \"name\": \"Build Wdt OpenSource Mac\",\n                \"shell\": \"wdt/build/lego-mac-build.sh\",\n                \"required\": true\n            },\n            {\n                \"user\": \"facebook\",\n                \"name\": \"Run Wdt OpenSource Mac Tests\",\n                \"shell\": \"cd wdt_build; CTEST_OUTPUT_ON_FAILURE=1 make test\",\n                \"required\": true\n            }\n        ]\n    }\n}]\nEOF\n", "num_lines": 64}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# If using variables directly from the spec, the variables are replaced by the\n# wrong value (from initial step)\necho \"BOX_DIR=$BOX_DIR\"\nset -x\npwd\nuname -a\nmkdir wdt_build\ncd wdt_build || exit 1\nls -l \"$BOX_DIR\"\ncmake ../wdt -DFOLLY_SOURCE_DIR=\"$BOX_DIR\" -DBUILD_TESTING=on && make -j\n", "num_lines": 12}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Remove the double-conversion part when Task#10922468 is done\n\nset -x\npwd\nuname -a\nmkdir wdt_build\ncd wdt_build || exit 1\ncmake --version\nexport https_proxy=fwdproxy:8080\ngit clone https://github.com/floitsch/double-conversion.git\nmkdir double-conversion-build\n(cd double-conversion-build && \\\n cmake -DBUILD_SHARED_LIBS=on \\\n       -DCMAKE_INSTALL_PREFIX=\"$HOME\" \\\n       ../double-conversion; \\\n make -j 4 && make install)\n\ncmake ../wdt -DFOLLY_SOURCE_DIR=\"$(cd ..;pwd)\" -DBUILD_TESTING=on \\\n      -DDOUBLECONV_INCLUDE_DIR=\"$HOME/include\" \\\n      -DDOUBLECONV_LIBRARY=\"$HOME/lib/libdouble-conversion.dylib\" && make -j\n", "num_lines": 23}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Script to setup the travis build env - changes here are likely needed\n# in wdt_cont_build_setup*.sh too\nset -x\nset -e\n\ndate\nuname -a\necho $HOSTNAME\nmkdir $HOME/bin || true\nexport PATH=$HOME/bin:$PATH\nexport LD_LIBRARY_PATH=$HOME/lib:$LD_LIBRARY_PATH\nexport CMAKE_PREFIX_PATH=$HOME\nopenssl version\ncd ..\ngit clone https://github.com/google/double-conversion.git\n(mkdir double-conversion-build; cd double-conversion-build; cmake -DBUILD_SHARED_LIBS=on -DCMAKE_INSTALL_PREFIX=$HOME ../double-conversion; make -j 4 && make install)\ngit clone https://github.com/gflags/gflags.git\n(mkdir gflags-build; cd gflags-build; cmake -DCMAKE_INSTALL_PREFIX=$HOME -DGFLAGS_NAMESPACE=google -DBUILD_SHARED_LIBS=on ../gflags && make -j 4 && make install)\ngit clone https://github.com/google/glog.git\n( cd glog && ./autogen.sh && ./configure --with-gflags=$HOME --prefix=$HOME && make -j 4 && make install )\ngit clone https://github.com/facebook/folly.git\npwd ; ls -l\ncd wdt\n#set +e\nset +x\n", "num_lines": 27}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# Sets up MacOS build environment (for travis but can be used on other mac too)\nset -x\n#set -e\n\ndate\nuname -a\necho $HOSTNAME\nmkdir $HOME/bin || true\nbrew update\nbrew install openssl || true\ncd ..\nexport PATH=/usr/local/opt/openssl/bin:$HOME/bin:$PATH\nexport LD_LIBRARY_PATH=/usr/local/opt/openssl/lib:$HOME/lib:$LD_LIBRARY_PATH\nexport OPENSSL_ROOT_DIR=/usr/local/opt/openssl\nexport CMAKE_PREFIX_PATH=$HOME\nopenssl version -a\ngit clone https://github.com/google/double-conversion.git\n(mkdir double-conversion-build; cd double-conversion-build; cmake -DBUILD_SHARED_LIBS=on -DCMAKE_INSTALL_PREFIX=$HOME ../double-conversion; make -j 4 && make install)\ngit clone https://github.com/gflags/gflags.git\n(mkdir gflags-build; cd gflags-build; cmake -DCMAKE_INSTALL_PREFIX=$HOME -DGFLAGS_NAMESPACE=google -DBUILD_SHARED_LIBS=on ../gflags && make -j 4 && make install)\ngit clone https://github.com/google/glog.git\n( cd glog && ./autogen.sh && ./configure --with-gflags=$HOME --prefix=$HOME && make -j 4 && make install )\ngit clone https://github.com/facebook/folly.git\npwd ; ls -l\ncd wdt\n#set +e\nset +x\n", "num_lines": 29}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n# A lot of this is facebook specific but can give an idea of how\n# to setup custom tests for WDT - Very similar to travis_linux.sh\n# run this once and then _run will run a loop and email results\necho \"if sending email later fails, you might need:\"\necho \"sudo sed -ie 's#^\\(mailhub\\).*$#\\1=localhost#' /etc/ssmtp/ssmtp.conf\"\necho \"but that shouldn't be necessary anymore\"\nset -x\nsudo yum install iproute-tc devtoolset-4-gcc-c++ automake autoconf boost-devel libtool\nexport PATH=/opt/rh/devtoolset-4/root/bin:$PATH\nwhile sh -c \"g++ --version | fgrep 4.8.\" ; do\n  smcc add-services -e hhvm.oss $HOSTNAME:22\n  date\n  echo \"you have an old g++ let see if chefctl can upgrade it\"\n  sleep 1\n  sudo chefctl -i\ndone\necho congrats on\nset -e\ng++ --version\nCDIR=/data/users/${USER}_wdt_contbuild\nBINDIR=/data/users/${USER}_wdt_contbuild/bin\nLIBDIR=/data/users/${USER}_wdt_contbuild/lib\nsudo sh -c \"mkdir -p $BINDIR || true\"\nsudo sh -c \"mkdir -p $LIBDIR || true\"\nsudo chown -R $USER $CDIR\nexport PATH=$BINDIR:$PATH\nexport LD_LIBRARY_PATH=$LIBDIR:$LD_LIBRARY_PATH\n\ncd $CDIR\nhg-clone-fbsource --sparse .hgsparse-fbcode --simple\n\n# open source part\nexport https_proxy=http://fwdproxy:8080\ngit clone https://cmake.org/cmake.git\ncd cmake\n./bootstrap --prefix=$CDIR --parallel=16\nmake -j 16\nmake install\ncd ..\n\n# should be same:\nwhich cmake\nls -l $BINDIR/cmake\n\n# similar as travis_linux.sh\ngit clone https://github.com/floitsch/double-conversion.git\n(cd double-conversion; cmake -DBUILD_SHARED_LIBS=on -DCMAKE_INSTALL_PREFIX=$CDIR .; make -j 16 && make install)\ngit clone https://github.com/schuhschuh/gflags.git\n(mkdir gflags/build; cd gflags/build; cmake -DCMAKE_INSTALL_PREFIX=$CDIR -DGFLAGS_NAMESPACE=google -DBUILD_SHARED_LIBS=on .. && make -j 16 && make install)\ngit clone https://github.com/google/glog.git\necho \"if this fails with aclocal error; run autoreconf\"\n( cd glog && ./configure --with-gflags=$CDIR --prefix=$CDIR && autoreconf -vfi && make -j 16 && make install )\nOPENSSL_VERSION=openssl-1.0.1u\nwget https://www.openssl.org/source/$OPENSSL_VERSION.tar.gz\ntar xfz $OPENSSL_VERSION.tar.gz\n( cd $OPENSSL_VERSION ; ./config --prefix=$CDIR threads shared; make ; make install )\n$CDIR/bin/openssl version\nldd $CDIR/bin/openssl\nexport OPENSSL_ROOT_DIR=$CDIR\n\nmkdir cmake_wdt_build\ncd cmake_wdt_build\ncmake ../fbsource/fbcode/wdt -DFOLLY_SOURCE_DIR=$CDIR/fbsource/fbcode\\\n        -DBUILD_TESTING=1\n\ntime make -j 16\n\nCTEST_OUTPUT_ON_FAILURE=1 time make test\n", "num_lines": 70}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Mac version of wdt_cont_build_setup.sh\nset -x\nset -e\nCDIR=/data/users/${USER}_wdt_contbuild\nsudo sh -c \"mkdir -p $CDIR || true\"\nsudo chown $USER $CDIR\n( echo p | svn list https://googlemock.googlecode.com ) || true\ncd $CDIR\nhg-clone-fbsource --sparse fbcode/wdt/.hgsparse --simple\nmkdir cmake_wdt_build\ncd cmake_wdt_build\necho \"might need to get a new enough cmake if this fails:\"\ncmake ../fbsource/fbcode/wdt -DBUILD_TESTING=1 \\\n    -DFOLLY_SOURCE_DIR=$(cd ../fbsource/fbcode;pwd)\nmake -j 4\nCTEST_OUTPUT_ON_FAILURE=1 make test\n", "num_lines": 18}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Very inneficient way to colorize log input\nawk '/^I/ {system(\"tput setaf 2\"); print $0} /^W/ {system(\"tput setaf 3\"); print $0} /^E/ {system(\"tput setaf 1\"); print $0} /^C/ {system(\"tput setaf 5\"); print $0} /^[^IWEC]/ {system(\"tput sgr0\"); print $0}'\n", "num_lines": 4}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#### TODO : make this work on  MacOS\n\nIPTABLE_LOCK_FILE=\"/tmp/wdt.iptable.lock\"\n\nsetTcOptions() {\n  sudo tc qdisc add dev lo root netem delay 20ms 10ms duplicate 1% corrupt 0.1%\n}\n\nclearTcOptions() {\n  sudo tc qdisc del dev lo root\n}\n\nrunIptableCmd() {\n  flock -x \"$IPTABLE_LOCK_FILE\" -c \"$1\"\n}\n\nblockSportByDropping() {\n  UNBLOCK_CMD=\"sudo ip6tables -D INPUT -p tcp --sport $1 -j DROP\"\n  CMD=\"sudo ip6tables -A INPUT -p tcp --sport $1 -j DROP\"\n  runIptableCmd \"$CMD\"\n}\n\nblockDportByDropping() {\n  UNBLOCK_CMD=\"sudo ip6tables -D INPUT -p tcp --dport $1 -j DROP\"\n  CMD=\"sudo ip6tables -A INPUT -p tcp --dport $1 -j DROP\"\n  runIptableCmd \"$CMD\"\n}\n\nblockSportByRejecting() {\n  UNBLOCK_CMD=\"sudo ip6tables -D INPUT -p tcp --sport $1 -j REJECT\"\n  CMD=\"sudo ip6tables -A INPUT -p tcp --sport $1 -j REJECT\"\n  runIptableCmd \"$CMD\"\n}\n\nblockDportByRejecting() {\n  UNBLOCK_CMD=\"sudo ip6tables -D INPUT -p tcp --dport $1 -j REJECT\"\n  CMD=\"sudo ip6tables -A INPUT -p tcp --dport $1 -j REJECT\"\n  runIptableCmd \"$CMD\"\n}\n\nundoLastIpTableChange() {\n  if [ ! -z \"$UNBLOCK_CMD\" ]; then\n    CMD=\"eval $UNBLOCK_CMD\"\n    runIptableCmd \"$CMD\"\n    unset UNBLOCK_CMD\n  fi\n}\n\nsetBinaries() {\n  if [ -z \"$WDT_BINARY\" ]; then\n    # Inside fb, building with buck, look there:\n    WDT_BINARY=\"./buck-out/gen/wdt/wdt\"\n    if [ ! -x \"$WDT_BINARY\" ]; then\n      # Open source / Cmake / old fbmake path:\n      WDT_BINARY=\"./_bin/wdt/wdt\"\n    fi\n  fi\n  if [ -z \"$WDT_SENDER\" ]; then\n    WDT_SENDER=$WDT_BINARY\n  fi\n  if [ -z \"$WDT_RECEIVER\" ]; then\n    WDT_RECEIVER=$WDT_BINARY\n  fi\n  if [ -z \"$WDT_GEN_FILES\" ]; then\n    WDT_GEN_FILES=\"./buck-out/gen/wdt/bench/wdt_gen_files\"\n    if [ ! -x \"$WDT_GEN_FILES\" ]; then\n      WDT_GEN_FILES=\"./_bin/wdt/bench/wdt_gen_files\"\n    fi\n  fi\n  if [ -z \"$WDT_GEN_BIGRAMS\" ]; then\n    WDT_GEN_BIGRAMS=\"$(dirname \"$0\")/../bench/book1.bigrams\"\n  fi\n  echo \"Wdt binary: $WDT_BINARY, Sender: $WDT_SENDER, Receiver: $WDT_RECEIVER\"\n  echo \"wdt_gen_files: $WDT_GEN_FILES - bigram data $WDT_GEN_BIGRAMS\"\n}\n\nsetDirectory() {\n  if [ -z \"$BASEDIR\" ]; then\n      BASEDIR=\"/dev/shm/wdtTest_$USER\"\n  fi\n  mkdir -p \"$BASEDIR\"\n  DIR=$(mktemp -d \"$BASEDIR/XXXXX\")\n  SRC_DIR=\"$DIR/src\"\n  echo \"Testing in $DIR - src dir $SRC_DIR\"\n  mkdir \"$SRC_DIR\"\n}\n\nsimulateNetworkGlitchesByRejecting() {\n  for ((i = 1; i <= ERROR_COUNT; i++))\n  do\n    sleep 0.3 # sleep for 300ms\n    port=$((STARTING_PORT + RANDOM % threads))\n    echo \"blocking $port\"\n    if [ $((i % 2)) -eq 0 ]; then\n      blockSportByRejecting $port\n      sleep 0.7 # sleep for 700ms, read/write timeout is 500ms, so must sleep\n                # more than that\n      echo \"unblocking $port\"\n      undoLastIpTableChange\n    else\n      blockDportByRejecting $port\n      sleep 0.7 # sleep for 700ms, read/write timeout is 500ms, so must sleep\n                # more than that\n      echo \"unblocking $port\"\n      undoLastIpTableChange\n    fi\n  done\n}\n\nsimulateNetworkGlitchesByDropping() {\n  for ((i = 1; i <= ERROR_COUNT; i++))\n  do\n    sleep 0.3 # sleep for 300ms\n    port=$((STARTING_PORT + RANDOM % threads))\n    echo \"blocking $port\"\n    if [ $((i % 2)) -eq 0 ]; then\n      blockSportByDropping $port\n      sleep 0.7 # sleep for 700ms, read/write timeout is 500ms, so must sleep\n                # more than that\n      echo \"unblocking $port\"\n      undoLastIpTableChange\n    else\n      blockDportByDropping $port\n      sleep 0.7 # sleep for 700ms, read/write timeout is 500ms, so must sleep\n                # more than that\n      echo \"unblocking $port\"\n      undoLastIpTableChange\n    fi\n  done\n}\n\nprintServerLog() {\n  echo \"Server log($DIR/server${TEST_COUNT}.log):\"\n  cat $DIR/server${TEST_COUNT}.log\n}\n\nwdtExit() {\n  undoLastIpTableChange\n  if [ $1 -ne 0 ] ; then\n      echo \"Failing test $0 : Test#${TEST_COUNT} - Logs in $DIR\"\n  fi\n  exit $1\n}\n\ncheckLastCmdStatus() {\n  LAST_STATUS=$?\n  if [ $LAST_STATUS -ne 0 ] ; then\n    echo \"exiting abnormally with status $LAST_STATUS - aborting/failing test\"\n    printServerLog\n    wdtExit $LAST_STATUS\n  fi\n}\n\ncheckLastCmdStatusExpectingFailure() {\n  LAST_STATUS=$?\n  if [ $LAST_STATUS -eq 0 ] ; then\n    echo \"expecting wdt failure, but transfer was successful, failing test\"\n    printServerLog\n    wdtExit 1\n  fi\n}\n\nwaitForTransferEnd() {\n  wait \"$pidofreceiver\"\n  checkLastCmdStatus\n  wait \"$pidofsender\"\n  checkLastCmdStatus\n}\n\nwaitForTransferEndWithoutCheckingStatus() {\n  wait \"$pidofreceiver\"\n  wait \"$pidofsender\"\n}\n\nwaitForTransferEndExpectingFailure() {\n  wait \"$pidofreceiver\"\n  checkLastCmdStatusExpectingFailure\n  wait \"$pidofsender\"\n  checkLastCmdStatusExpectingFailure\n}\n\nkillCurrentTransfer() {\n  kill -9 \"$pidofsender\"\n  kill -9 \"$pidofreceiver\"\n  wait \"$pidofsender\"\n  wait \"$pidofreceiver\"\n}\n\ngenerateRandomFiles() {\n  if [ -z \"$1\" ]; then\n    echo \"generateRandomFile expects the directory to be passed as first \\\n      argument\"\n    wdtExit 1\n  fi\n  if [ -z \"$2\" ]; then\n    echo \"generateRandomFile expects base file size to be passed as second \\\n      argument\"\n    wdtExit 1\n  fi\n  mkdir -p \"$1\"\n  fourx=$(echo \"$2* 4\" | bc -l)\n  echo \"Generating 4 files of $2 MBytes and 16 of $fourx Mbytes\"\n  for ((i = 0; i < 4; i++))\n  do\n    $WDT_GEN_FILES -stats_source=\"$WDT_GEN_BIGRAMS\" \\\n        -directory=\"$1\" -filename=\"sample${i}\" -gen_size_mb=\"$2\"\n  done\n  # we will generate 1G of random data. 16 files each of size 64mb.\n  for ((i = 0; i < 16; i++))\n  do\n    $WDT_GEN_FILES -stats_source=\"$WDT_GEN_BIGRAMS\" \\\n        -directory=\"$1\" -filename=\"file${i}\" -gen_size_mb=\"$fourx\"\n  done\n}\n\nremoveDestination() {\n  echo \"Removing destination directory $DIR/dst${TEST_COUNT}\"\n  rm -rf \"$DIR/dst${TEST_COUNT}\"\n}\n\nverifyTransferAndCleanup() {\n  if [ -z \"$MD5SUM\" ]; then\n    MD5SUM=$(which md5sum)\n    STATUS=$?\n    if [ $STATUS -ne 0 ] ; then\n      MD5SUM=$(which md5)\n    fi\n    echo \"Found md5sum as $MD5SUM\"\n  fi\n\n  stat $DIR/dst${TEST_COUNT}/.wdt.log 2> /dev/null\n  if [ $? -eq 0 ]; then\n    # transfer log present, verify for correctness\n    echo \"Verifying transfer log in $DIR/dst${TEST_COUNT}\"\n    $WDT_RECEIVER -directory $DIR/dst${TEST_COUNT} -parse_transfer_log\n    checkLastCmdStatus\n  fi\n\n  if [ ! -f \"$DIR/src.md5s\" ]; then\n    (cd \"$DIR/src\" ; ( find . -type f -print0 | xargs -0 \"$MD5SUM\" | sort ) \\\n      > ../src.md5s )\n  fi\n\n  if [ -d \"$DIR/src1\" ] && [ ! -f \"$DIR/src1.md5s\" ]; then\n    (cd \"$DIR/src1\" ; ( find . -type f -print0 | xargs -0 \"$MD5SUM\" | sort ) \\\n      > ../src1.md5s )\n  fi\n\n  STATUS=0\n  (cd \"$DIR/dst${TEST_COUNT}\" ; ( find . -type f -print0 | xargs -0 \"$MD5SUM\" \\\n    | sort | grep -v \"\\.wdt\\.log\\$\") > \"../dst${TEST_COUNT}.md5s\" )\n  echo \"Verifying correctness for test $TEST_COUNT\"\n  echo \"Should be no diff\"\n  USE_OTHER_SRC=$1\n  if [ \"$USE_OTHER_SRC\" == \"true\" ]; then\n    SRC_MD5=src1.md5s\n  else\n    SRC_MD5=src.md5s\n  fi\n  (cd \"$DIR\"; diff -u \"$SRC_MD5\" \"dst${TEST_COUNT}.md5s\")\n  STATUS=$?\n  # treating PROTOCOL_ERROR as errors\n  grep \"PROTOCOL_ERROR\" \"$DIR/server${TEST_COUNT}.log\" > /dev/null\n  if [ $? -eq 0 ]; then\n    echo \"server has PROTOCOL ERROR\"\n    STATUS=1\n  fi\n  grep \"PROTOCOL_ERROR\" \"$DIR/client${TEST_COUNT}.log\" > /dev/null\n  if [ $? -eq 0 ]; then\n    echo \"client has PROTOCOL ERROR\"\n    STATUS=1\n  fi\n\n  if [ $STATUS -eq 0 ] ; then\n    echo \"Test $TEST_COUNT succeeded\"\n    removeDestination\n  else\n    printServerLog\n    echo \"Test $TEST_COUNT failed\"\n    wdtExit $STATUS\n  fi\n}\n\nsignalHandler() {\n  echo \"Caught signal, exiting...\"\n  wdtExit 1\n}\n\nextendWdtOptions() {\n  WDTBIN_OPTS+=\" $EXTRA_WDT_OPTIONS\"\n  WDTBIN_OPTS+=\" $EXTRA_ENCRYPTION_CMD\"\n  if [ ! -z \"$ENCRYPTION_TYPE\" ]; then\n    echo \"encryption_type $ENCRYPTION_TYPE\"\n    WDTBIN_OPTS+=\" -encryption_type=$ENCRYPTION_TYPE\"\n  fi\n  if [ ! -z \"$ENABLE_CHECKSUM\" ]; then\n    echo \"enable_checksum $ENABLE_CHECKSUM\"\n    WDTBIN_OPTS+=\" -enable_checksum=$ENABLE_CHECKSUM\"\n  fi\n  WDTBIN_OPTS+=\" -iv_change_interval_mb=32\"\n}\n\n# without the following line, wdt piped to tee effectively has exit status of\n# tee. source : http://petereisentraut.blogspot.com/2010/11/pipefail.html\nset -o pipefail\n\ntrap signalHandler SIGINT SIGTERM\n# Note this is not meant to be an example of a secure key, it's just for tests\n# (thus the test_only in the option name) - the normal way is through the URL\n# which generates a crypto. Add _secret for _secr in case of single digit pid.\nTEST_ONLY_ENCRYPTION_KEY=$(echo not_a_key_$$_secret | fold -b -w 16 | head -n 1)\nEXTRA_ENCRYPTION_CMD=\"-test_only_encryption_secret $TEST_ONLY_ENCRYPTION_KEY\"\n", "num_lines": 313}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\nsetBinaries\n\n$WDT_RECEIVER -skip_writes -avg_mbytes_per_sec=10 -max_accept_retries=10\nSTATUS=$?\nif [ $STATUS -ne 3 ]; then\n  echo \"Receiver should exit with status 3, but it exited with $STATUS\"\n  exit 1\nfi\necho \"Test passed\"\n", "num_lines": 13}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Wrapper shell to ease use of WDT command line for remote cp\n# Source of this file is fbcode/wdt/wcp.sh\n\n# todo: make it work for multiple files and remote src/dir (full(er) scp syntax)\n# and remove pkill once we have support for picking available ports\n# (remote wdt will exit on its own after succesfull transfer)\n\nusage=\"Usage:\\n\n`basename $0` [-p portbase] [-l loglevel] [-n] sourcefile\n[user@]desthost:directory\\n\n  p : port base to use (8 sockets used by default from that port or 22356\\n\n  l : logging verbosity level to use\\n\n  n : no compression (gzip by default)\\n\nThe wdt binary should be in the path on both source and destination\\n\nAnd wdt ports (22356-22364 unless specified with -p) should be available\non the destination\"\n\n# Defaults\nMINLOGLEVEL=2\nPORTBASE=22356\nDOCOMPRESSION=1\n\nwhile getopts \"p:l:hn\" opt\ndo case \"$opt\" in\n        p)  PORTBASE=\"$OPTARG\";;\n        l)  MINLOGLEVEL=\"$OPTARG\";;\n        n)  DOCOMPRESSION=0;;\n        h)  echo -e $usage; exit 1;;\n        \\?) echo -e $usage; exit 1;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [ $# -ne 2 ] ; then\n    echo -e $usage\n    exit 1\nfi\n\nSRCPATH=$1\nif [ ! -r $SRCPATH ] ; then\n    echo \"First argument ($SRCPATH) must be a readable file\"\n    exit 2\nfi\n\nDIR=`mktemp -d`\nREMOTE=`echo $2|sed -e 's/^.*@//' -e 's/:.*//'`\nSSHREMOTE=`echo $2|sed -e 's/:.*//'`\nREMOTEDIR=`echo $2|sed -e 's/.*://'`\nif [ -z \"$REMOTEDIR\" ] ; then\n  REMOTEDIR=.\nfi\n\nFILENAME=`basename $SRCPATH`\nSIZE=`stat -L -c %s $SRCPATH`\nif [ $? -ne 0 ] ; then\n  echo \"Error stating $SRCPATH. aborting.\"\n  exit 1\nfi\n\nTRANSFERID=$$\n\necho \"Copying $FILENAME ($SRCPATH) to $REMOTE (using $SSHREMOTE in $REMOTEDIR)\"\n\n# Here we try to start asynchronously - the effect is things may fail on the\n# server side and we won't know - also pkill may not be fast enough and\n# data may still be sent to the previous process\necho \"Starting destination side server\"\nif [ $DOCOMPRESSION -eq 1 ] ; then\n    # Gzip compression:\n    ssh -f $SSHREMOTE \"pkill wdt; mkdir -p $REMOTEDIR; cd $REMOTEDIR; wdt --run_as_daemon=false --minloglevel=$MINLOGLEVEL --start_port $PORTBASE --transfer_id=$TRANSFERID && time gunzip $FILENAME.gz && echo 'Complete!';date; echo 'Dst checksum'; md5sum $FILENAME\"\nelse\n    # No compression:\n    ssh -f $SSHREMOTE \"pkill wdt; mkdir -p $REMOTEDIR; cd $REMOTEDIR; wdt --run_as_daemon=false --minloglevel=$MINLOGLEVEL --start_port $PORTBASE --transfer_id=$TRANSFERID; echo 'Complete!';date; echo 'Dst checksum'; md5sum $FILENAME\"\nfi\n#REMOTEPID=$!\n\n# Start counting time after ssh because ssh can ask for credentials/take a while\nSTART_NANO=`date +%s%N`\nSTART_MS=`expr $START_NANO / 1000000`\necho \"Starting at `date` ($START_MS)\"\n\nif [ $DOCOMPRESSION -eq 1 ] ; then\n  # Gzip\n  echo \"Compressing $SRCPATH ($SIZE)\"\n  time gzip -1 -c $SRCPATH > $DIR/$FILENAME.gz\n  # LZ4\n  #time lz4 -3 -z $SRCPATH - | (cd $DIR ; time split -b ${SPLIT}K - wdtTMP )\nelse\n  # No compression\n  ln -s $SRCPATH $DIR/$FILENAME\nfi\n\ndate \"+%s.%N\"\ntime wdt --minloglevel=$MINLOGLEVEL --directory $DIR \\\n    --follow_symlinks --transfer_id=$TRANSFERID\\\n    --destination $REMOTE  --start_port $PORTBASE --ipv6=false # try both v4 and v6\nSTATUS=$?\n\nEND_NANO=`date +%s%N`\nEND_MS=`expr $END_NANO / 1000000`\nDURATION=`expr $END_MS - $START_MS`\nRATE=`expr 1000 \\* $SIZE / 1024 / 1024 / $DURATION`\n\nif [ $STATUS -eq 0 ] ; then\n    echo \"Succesfull transfer\"\nelse\n    echo \"Failure (code $STATUS)\"\nfi\n\necho \"All done client side! cleanup...\"\nrm -r $DIR &\n#echo -n \"e\" | nc $REMOTE $PORTBASE\n\necho \"Overall transfer @ $RATE Mbytes/sec ($DURATION ms for $SIZE uncompressed)\"\n\necho \"Source checksum:\"\nmd5sum $SRCPATH\n\nexit $STATUS\n", "num_lines": 122}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Modified version of wdt_max_send_test.sh to test crypto speed\n\necho \"Run this sender performance test from fbcode/ directory\"\necho \"or give full path to wdt binary to use and staging directory\"\n\nset -o pipefail\n\nif [ -z \"$1\" ]; then\n  WDTBIN=\"_bin/wdt/wdt\"\nelse\n  WDTBIN=\"$1\"\nfi\n\nif [ -z \"$2\" ]; then\n    BASEDIR=/dev/shm/wdtTest_$USER\nelse\n    BASEDIR=$2\nfi\n\nAWK=gawk\n\n# TEST_COUNT is an environment variable. It is set up by the python benchmarking\n# script.\nif [ -z $TEST_COUNT ]; then\n  TEST_COUNT=4\nfi\n\n# WDT_THROUGHPUT is an env var. Set it to overwrite the expected 16Gbyte/sec\nif [ -z $WDT_THROUGHPUT ]; then\n  WDT_THROUGHPUT=5000\nfi\n\n\nif [ -z \"$HOSTNAME\" ] ; then\n    echo \"HOSTNAME not set, will try with 'localhost'\"\n    HOSTNAME=localhost\nelse\n    echo \"Will self connect to HOSTNAME=$HOSTNAME\"\nfi\n\nENC_TYPE=aes128gcm\nCRC=false\n\nREMOTE=$HOSTNAME\nSKIP_WRITES=\"true\"\n\n# Without throttling:\n#WDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_sockets 13\"\n\n#CPU normalization\nNUM_CPU=`grep processor /proc/cpuinfo|wc -l`\n# leave one cpu alone for the rest (or typically 2 because of /2)\nNUM_THREADS=`echo $NUM_CPU/2|bc`\necho \"Using $NUM_THREADS threads (on each sender, receiver) for $NUM_CPU CPUs\"\n\n# With, still gets almost same max (21G) with throttling set high enough\nWDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_ports $NUM_THREADS\n-transfer_id=$$ -encryption_type=$ENC_TYPE --enable_checksum=$CRC\n-exit_on_bad_flags=false\"\n\n\nWDTNAME=`basename $WDTBIN`\nWDTCMD=\"$WDTBIN $WDTBIN_OPTS\"\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing $WDTBIN in $DIR\"\nif [ -z \"$DIR\" ]; then\n  echo \"Unable to create dir in $BASEDIR\"\n  exit 1\nfi\n\npkill -x wdt\npkill -x wdt_fb\npkill -x $WDTNAME\n\nmkdir $DIR/src\n\nfor size in 1k 64K 512K 1M 16M 256M 512M\ndo\n    base=inp$size\n    echo dd if=/dev/... of=$DIR/src/$base.1 bs=$size count=1\n    dd if=/dev/zero of=$DIR/src/$base.1 bs=$size count=1\n    for i in {2..32}\n    do\n        cp $DIR/src/$base.1 $DIR/src/$base.$i\n    done\ndone\necho \"Done with staging src test files\"\n\n#set -e\n\n# wait for server to be up\n#while [ `/bin/true | nc $REMOTE 22356; echo $?` -eq 1 ]\n#do\n#  echo \"Server not up yet...`date`...\"\n#  sleep 0.5\n#done\n#echo \"Server is up on $REMOTE 22356 - `date` - starting client run\"\n\nfor ((i = 1; i <= TEST_COUNT; i++))\ndo\n  echo \"starting ${i}th run\"\n  TWO_PHASE_ARG=\"\"\n  # every other run will be two_phases\n  [ $(($i % 2)) -eq 0 ] && TWO_PHASE_ARG=\"-two_phases\"\n\n  set -x\n  time $WDTCMD -directory $DIR/dst$i -skip_writes=$SKIP_WRITES 2> \\\n    $DIR/server$i.log | time $WDTCMD -directory $DIR/src \\\n  $TWO_PHASE_ARG - |& tee $DIR/client$i.log\n  set +x\n  THROUGHPUT=`$AWK 'match($0, /.*Total sender throughput = ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"Server log:\"\n  cat $DIR/server$i.log\n  echo \"THROUGHPUT $THROUGHPUT\"\n  TRANSFER_TIME=`$AWK 'match($0, /.*Total sender time = ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"TRANSFER_TIME $TRANSFER_TIME\"\ndone\n\n\nMAXRATE=`$AWK 'BEGIN {max=0} match($0, /.*Total sender throughput = ([0-9.]+)/, res) {rate=res[1]; if (rate>max) max=rate} END {print int(max+.5)}' $DIR/client*.log`\n\nALLSPEEDS=`$AWK 'match($0, /.*Total sender throughput = ([0-9.]+)/, res) {printf(\"%s \", res[1])}' $DIR/client*.log`\n\necho \"Deleting logs and staging in $DIR\"\nrm -rf $DIR\n\necho \"Speed for all runs: $ALLSPEEDS\"\n\n# Normalize by CPU / number of threads\n# (32 cores leaves 15 threads and can do ~20-22G, use 16 for margin of noise)\nEXPECTED_SPEED=`echo $WDT_THROUGHPUT*$NUM_THREADS/16|bc`\n\necho \"Best throughput for $WDTBIN\"\nif [ \"$MAXRATE\" -lt \"$EXPECTED_SPEED\" ]; then\n    echo \"Regression: $MAXRATE is too slow - before top\"\n    atop -l 1 1 | head -40\n    echo \"Regression: $MAXRATE is too slow for $NUM_CPU cpus ($EXPECTED_SPEED)\"\n    exit 1\nelse\n    echo \"Good rate $MAXRATE for $NUM_CPU cpus (threshold $EXPECTED_SPEED)\"\n    exit 0\nfi\n\n# all done\n", "num_lines": 151}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\n\nstartNewTransfer() {\n  if [ \"$1\" == \"add\" ] && [ $DELETE_EXTRA_FILES == \"true\" ]; then\n    echo \"Adding extra files for test ${TEST_COUNT}\"\n    fallocate -l 20M $SRC_DIR/extra_file${TEST_COUNT}_1\n    fallocate -l 80M $SRC_DIR/extra_file${TEST_COUNT}_2\n  fi\n  if [ \"$1\" == \"remove\" ] && [ $DELETE_EXTRA_FILES == \"true\" ]; then\n    echo \"Removing extra files for test ${TEST_COUNT}\"\n    rm $SRC_DIR/extra_file${TEST_COUNT}_1 $SRC_DIR/extra_file${TEST_COUNT}_2\n  fi\n  $WDTBIN_SERVER -directory $DIR/dst${TEST_COUNT} -start_port=$STARTING_PORT \\\n  -transfer_id=$RECEIVER_ID -protocol_version=$RECEIVER_PROTOCOL_VERSION \\\n  -recovery_id=$RECOVERY_ID -disable_preallocation=$DISABLE_PREALLOCATION \\\n  >> $DIR/server${TEST_COUNT}.log 2>&1 &\n  pidofreceiver=$!\n  $WDTBIN_CLIENT -directory $SRC_DIR -destination $HOSTNAME \\\n  -start_port=$STARTING_PORT -block_size_mbytes=$BLOCK_SIZE_MBYTES \\\n  -transfer_id=$SENDER_ID -protocol_version=$SENDER_PROTOCOL_VERSION \\\n  -two_phases=$TWO_PHASES \\\n  |& tee -a $DIR/client${TEST_COUNT}.log &\n  pidofsender=$!\n}\n\nusage=\"\nThe possible options to this script are\n-s sender protocol version\n-r receiver protocol version\n-p start port\n-d turns on file deletion\n-c combination of options to run. Valid values are 1, 2, 3 and 4.\n   1. pre-allocation and block-mode enabled, resumption done using transfer log\n   2. pre-allocation disabled, block-mode enabled, resumption done using\n      directory tree. This effectively disables resumption.\n   3. pre-allocation and block-mode disabled, resumption done using directory\n      tree\n   4. pre-allocation enabled and block-mode disabled, resumption done using\n      transfer log\n\"\n\n#protocol versions, used to check version verification\n#version 0 represents default version\nSENDER_PROTOCOL_VERSION=0\nRECEIVER_PROTOCOL_VERSION=0\n\nDISABLE_PREALLOCATION=false\nBLOCK_SIZE_MBYTES=10\nRESUME_USING_DIR_TREE=false\n\nRECOVERY_ID=\"foo\"\n\nSTARTING_PORT=25000\n\nDELETE_EXTRA_FILES=false\n\nwhile getopts \":c:s:p:r:dh\" opt; do\n  case $opt in\n    s) SENDER_PROTOCOL_VERSION=\"$OPTARG\"\n    ;;\n    r) RECEIVER_PROTOCOL_VERSION=\"$OPTARG\"\n    ;;\n    p) STARTING_PORT=\"$OPTARG\"\n    ;;\n    d) DELETE_EXTRA_FILES=true\n    ;;\n    c)\n      case $OPTARG in\n        1) echo \"pre-allocation and block-mode enabled, resumption using \\\ntransfer log\"\n        # no need to change anything, settings are initialized for this case\n        ;;\n        2) echo \"pre-allocation disabled, block-mode enabled, resumption done \\\nusing directory tree, resumption is effectively disabled\"\n           DISABLE_PREALLOCATION=true\n           RESUME_USING_DIR_TREE=true\n        ;;\n        3) echo \"pre-allocation and block-mode disabled, resumption done \\\nusing directory tree\"\n           BLOCK_SIZE_MBYTES=0\n           DISABLE_PREALLOCATION=true\n           RESUME_USING_DIR_TREE=true\n        ;;\n        4) echo \"pre-allocation enabled, block-mode disabled, resumption done \\\nusing transfer log\"\n        BLOCK_SIZE_MBYTES=0\n        ;;\n        *) echo \"Invalid combination, valid values are 1, 2, 3 and 4\"\n           wdtExit 1\n        ;;\n      esac\n    ;;\n    h) echo \"$usage\"\n        wdtExit\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\nsetBinaries\n\nif [ -z \"$TWO_PHASES\" ]; then\n  TWO_PHASES=false\nfi\n\necho \"sender protocol version $SENDER_PROTOCOL_VERSION, receiver protocol \\\nversion $RECEIVER_PROTOCOL_VERSION\"\n\nif [ $RECEIVER_PROTOCOL_VERSION -ne 0 ] && [ $RECEIVER_PROTOCOL_VERSION -lt 23 \\\n] && [ -z $NO_ENCRYPT ]; then\n  echo \"Can not support encryption for receiver with version \\\n$RECEIVER_PROTOCOL_VERSION\"\n  # exit with 0 to make the test pass\n  exit 0\nfi\n\nthreads=4\nERROR_COUNT=5\n\n#sender and receiver id, used to check transfer-id verification\nSENDER_ID=\"123456\"\nRECEIVER_ID=\"123456\"\n\nWDTBIN_OPTS=\"-ipv6 -num_ports=$threads -full_reporting \\\n-max_mbytes_per_sec=25 -run_as_daemon=false \\\n-full_reporting -read_timeout_millis=500 -write_timeout_millis=500 \\\n-enable_download_resumption -treat_fewer_port_as_error \\\n-resume_using_dir_tree=$RESUME_USING_DIR_TREE -enable_perf_stat_collection \\\n-connect_timeout_millis 100 -delete_extra_files=$DELETE_EXTRA_FILES \\\n-exit_on_bad_flags=false\"\nextendWdtOptions\nWDTBIN_CLIENT=\"$WDT_SENDER $WDTBIN_OPTS -buffer_size=2097152\"\nWDTBIN_SERVER=\"$WDT_RECEIVER $WDTBIN_OPTS -avg_mbytes_per_sec=80 \"\n\nBASEDIR=/dev/shm/wdtTest_$USER\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d $BASEDIR/XXXXXX`\necho \"Testing in $DIR\"\n\n#pkill -x wdt\n\nSRC_DIR=$DIR/src\n\ngenerateRandomFiles \"$SRC_DIR\" 4 # 4 Mb for smallest file\n\nTEST_COUNT=0\n\necho \"Testing that connection failure results in failed transfer\"\n# first create a deep directory structure\n# this is done so that directory thread gets aborted before discovering any\n# file\nCURDIR=`pwd`\ncd $DIR\nfor ((i = 0; i < 100; i++))\ndo\n  mkdir d\n  cd d\ndone\ntouch file\ncd $CURDIR\n# start the sender without starting receiver and set connect retries to 1\n$WDT_SENDER -directory $DIR/d -destination $HOSTNAME -max_retries 1 \\\n-start_port $STARTING_PORT -num_ports $threads\ncheckLastCmdStatusExpectingFailure\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Download resumption test(1)\"\nstartNewTransfer add\nsleep 5\nkillCurrentTransfer\n# rm a file to create an invalid log entry\nrm -f $DIR/dst${TEST_COUNT}/file0\nstartNewTransfer remove\nsleep 5\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Download resumption test(2)\"\nstartNewTransfer add\nsleep 5\nkillCurrentTransfer\n# change the file size in the receiver side\nfallocate -l 70M $DIR/dst${TEST_COUNT}/file0\nstartNewTransfer remove\nsleep 5\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Download resumption test with log truncation\"\nstartNewTransfer\nsleep 5\nkillCurrentTransfer\nLOG_FILE=$DIR/dst${TEST_COUNT}/.wdt.log\nLOG_SIZE=`stat --printf=\"%s\" $LOG_FILE`\nNEW_LOG_SIZE=$(( LOG_SIZE / 2 ))\ntruncate -s $NEW_LOG_SIZE $LOG_FILE\nstartNewTransfer\nwaitForTransferEnd\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Download resumption test with log corruption\"\nstartNewTransfer\nsleep 5\nkillCurrentTransfer\nLOG_FILE=$DIR/dst${TEST_COUNT}/.wdt.log\n# write some garbage at the end of the log\necho \"abc\" >> $LOG_FILE\nstartNewTransfer\nsleep 2\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\n\n# check whether we have .wdt.log.bug present or not\nstat \"${LOG_FILE}.bug\"\nif [ $? -ne 0 ]; then\n  printServerLog\n  echo \"Transfer log corrupted, but not detected by wdt, failing test\"\n  wdtExit 1\nfi\nrm \"${LOG_FILE}.bug\"\n\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\nchangePreallocationSettings() {\n  if [ $DISABLE_PREALLOCATION == \"false\" ]; then\n    DISABLE_PREALLOCATION=\"true\"\n  else\n    DISABLE_PREALLOCATION=\"false\"\n  fi\n}\n\nif [ $RESUME_USING_DIR_TREE == \"false\" ]; then\n  echo \"Download resumption with pre-allocation settings changed in the middle\"\n  startNewTransfer\n  sleep 5\n  killCurrentTransfer\n  # change pre-allocation settings\n  changePreallocationSettings\n  startNewTransfer\n  sleep 5\n  killCurrentTransfer\n  # change it back\n  changePreallocationSettings\n  startNewTransfer\n  waitForTransferEnd\n  verifyTransferAndCleanup\n  TEST_COUNT=$((TEST_COUNT + 1))\nfi\n\necho \"Download resumption with network error test\"\nstartNewTransfer add\nsleep 10\nkillCurrentTransfer\nstartNewTransfer remove\nsimulateNetworkGlitchesByDropping\nwaitForTransferEnd\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\nif [ $BLOCK_SIZE_MBYTES -gt 0 ]; then\n  # try to change the block size and also disable block mode\n  NEW_BLOCK_SIZES=(8 0)\nelse\n  # try to enable block mode\n  NEW_BLOCK_SIZES=(8)\nfi\n\nfor NEW_BLOCK_SIZE in ${NEW_BLOCK_SIZES[*]}\ndo\n  echo \"Download resumption with network error and block size change test(1)\"\n  startNewTransfer\n  simulateNetworkGlitchesByDropping\n  killCurrentTransfer\n  # change the block size for next transfer\n  PRE_BLOCK_SIZE=$BLOCK_SIZE_MBYTES\n  echo \"Changing block size to $NEW_BLOCK_SIZE\"\n  BLOCK_SIZE_MBYTES=$NEW_BLOCK_SIZE\n  startNewTransfer\n  waitForTransferEnd\n  verifyTransferAndCleanup\n  echo \"Resetting block size to $PRE_BLOCK_SIZE\"\n  BLOCK_SIZE_MBYTES=$PRE_BLOCK_SIZE\n  TEST_COUNT=$((TEST_COUNT + 1))\n\n  echo \"Download resumption with network error and block size change test(2)\"\n  startNewTransfer\n  simulateNetworkGlitchesByDropping\n  killCurrentTransfer\n  # change the block size for next transfer\n  PRE_BLOCK_SIZE=$BLOCK_SIZE_MBYTES\n  echo \"Changing block size to $NEW_BLOCK_SIZE\"\n  BLOCK_SIZE_MBYTES=$NEW_BLOCK_SIZE\n  startNewTransfer\n  sleep 5\n  killCurrentTransfer\n  echo \"Resetting block size to $PRE_BLOCK_SIZE\"\n  BLOCK_SIZE_MBYTES=$PRE_BLOCK_SIZE\n  startNewTransfer\n  waitForTransferEnd\n  verifyTransferAndCleanup\n  TEST_COUNT=$((TEST_COUNT + 1))\ndone\n\necho \"Download resumption test for append-only file\"\n# truncate file0\ncp $DIR/src/file0 $DIR/file0.bak\ntruncate -s 10M $DIR/src/file0\nstartNewTransfer\nsleep 5\nkillCurrentTransfer\n# restore file0\nmv $DIR/file0.bak $DIR/src/file0\nstartNewTransfer\nsleep 5\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\nverifyTransferAndCleanup\nTEST_COUNT=$((TEST_COUNT + 1))\n\nif [ $RESUME_USING_DIR_TREE == \"true\" ] && [ $BLOCK_SIZE_MBYTES -eq 0 ]; then\n  # combination 3\n  echo \"Test with download resumption disabled and block mode enabled \\\nfor the sender in the middle\"\n  startNewTransfer\n  sleep 2\n  killCurrentTransfer\n  PREV_WDT_CLIENT=$WDTBIN_CLIENT\n  BLOCK_SIZE_MBYTES=1\n  WDTBIN_CLIENT=\"$WDTBIN_CLIENT -enable_download_resumption=false\"\n  startNewTransfer\n  simulateNetworkGlitchesByDropping\n  killCurrentTransfer\n  WDTBIN_CLIENT=$PREV_WDT_CLIENT\n  BLOCK_SIZE_MBYTES=0\n  startNewTransfer\n  waitForTransferEnd\n  verifyTransferAndCleanup\n  TEST_COUNT=$((TEST_COUNT + 1))\nfi\n\n# abort set-up\nABORT_AFTER_SECONDS=5\nABORT_CHECK_INTERVAL_MILLIS=100\nABORT_AFTER_MILLIS=$((ABORT_AFTER_SECONDS * 1000))\nEXPECTED_TRANSFER_DURATION_MILLIS=$((ABORT_AFTER_MILLIS + \\\nABORT_CHECK_INTERVAL_MILLIS))\n# add 800ms overhead. We need this because we can not control timeouts for disk\n# writes\nEXPECTED_TRANSFER_DURATION_MILLIS=$((EXPECTED_TRANSFER_DURATION_MILLIS + 800))\n\necho \"Abort timing test(1) - Sender side abort\"\nWDTBIN_CLIENT_OLD=$WDTBIN_CLIENT\nWDTBIN_CLIENT+=\" -abort_check_interval_millis=$ABORT_CHECK_INTERVAL_MILLIS \\\n-abort_after_seconds=$ABORT_AFTER_SECONDS\"\nSTART_TIME_MILLIS=`date +%s%3N`\nstartNewTransfer\nwait $pidofsender\nEND_TIME_MILLIS=`date +%s%3N`\nwait $pidofreceiver\nDURATION=$((END_TIME_MILLIS - START_TIME_MILLIS))\necho \"Abort timing test, transfer duration ${DURATION} ms, expected duration \\\n${EXPECTED_TRANSFER_DURATION_MILLIS} ms.\"\nif (( $DURATION > $EXPECTED_TRANSFER_DURATION_MILLIS \\\n  || $DURATION < $ABORT_AFTER_MILLIS )); then\n  echo \"Abort timing test failed, exiting\"\n  printServerLog\n  wdtExit 1\nfi\nWDTBIN_CLIENT=$WDTBIN_CLIENT_OLD\nremoveDestination\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Abort timing test(2) - Receiver side abort\"\nWDTBIN_SERVER_OLD=$WDTBIN_SERVER\nWDTBIN_SERVER+=\" -abort_check_interval_millis=$ABORT_CHECK_INTERVAL_MILLIS \\\n-abort_after_seconds=$ABORT_AFTER_SECONDS\"\n# Block a port to the beginning\nblockDportByDropping \"$STARTING_PORT\"\nSTART_TIME_MILLIS=`date +%s%3N`\nstartNewTransfer\nwait $pidofreceiver\nEND_TIME_MILLIS=`date +%s%3N`\nwait $pidofsender\nDURATION=$((END_TIME_MILLIS - START_TIME_MILLIS))\necho \"Abort timing test, transfer duration ${DURATION} ms, expected duration \\\n${EXPECTED_TRANSFER_DURATION_MILLIS} ms.\"\nundoLastIpTableChange\nif (( $DURATION > $EXPECTED_TRANSFER_DURATION_MILLIS \\\n  || $DURATION < $ABORT_AFTER_MILLIS )); then\n  echo \"Abort timing test failed, exiting\"\n  printServerLog\n  wdtExit 1\nfi\nWDTBIN_SERVER=$WDTBIN_SERVER_OLD\nremoveDestination\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Transfer-id mismatch test\"\nSENDER_ID_OLD=$SENDER_ID\nSENDER_ID=\"abcdef\"\nstartNewTransfer\nwaitForTransferEndExpectingFailure\nSENDER_ID=$SENDER_ID_OLD\nremoveDestination\nTEST_COUNT=$((TEST_COUNT + 1))\n\n# create another src directory full of files with the same name and size as the\n# actual src directory\nmkdir -p $DIR/src1\ncd $DIR/src1\nfor ((i = 0; i < 4; i++))\ndo\n  fallocate -l 16M sample${i}\ndone\nfor ((i = 0; i < 16; i++))\ndo\n  fallocate -l 64M file${i}\ndone\ncd -\n\nstartAndKillIpv4Transfer() {\n  PREV_WDT_CLIENT=$WDTBIN_CLIENT\n  PREV_WDT_SERVER=$WDTBIN_SERVER\n  WDTBIN_CLIENT+=\" -ipv6=false -ipv4\"\n  WDTBIN_SERVER+=\" -ipv6=false -ipv4\"\n  startNewTransfer\n  sleep 5\n  killCurrentTransfer\n  # change it back to IPV6\n  WDTBIN_CLIENT=$PREV_WDT_CLIENT\n  WDTBIN_SERVER=$PREV_WDT_SERVER\n}\n\necho \"Test hostname mismatch(1)\"\n# start first transfer\nstartAndKillIpv4Transfer\n# change src directory\nSRC_DIR=$DIR/src1\nstartNewTransfer\nwaitForTransferEnd\nSRC_DIR=$DIR/src\nverifyTransferAndCleanup true\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Test hostname mismatch(2)\"\n# start first transfer\nstartAndKillIpv4Transfer\n# change src directory\nSRC_DIR=$DIR/src1\nstartNewTransfer\nsleep 2\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\nSRC_DIR=$DIR/src\nverifyTransferAndCleanup true\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Test recovery-id mismatch\"\nstartNewTransfer\nsleep 5\nkillCurrentTransfer\n# change recovery-id and src directory\nRECOVERY_ID=\"bar\"\nSRC_DIR=$DIR/src1\nstartNewTransfer\nsleep 2\nkillCurrentTransfer\nstartNewTransfer\nwaitForTransferEnd\nSRC_DIR=$DIR/src\nverifyTransferAndCleanup true\nTEST_COUNT=$((TEST_COUNT + 1))\n\necho \"Good run, deleting logs in $DIR\"\nrm -rf \"$DIR\"\n\nwdtExit 0\n", "num_lines": 493}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n#\n# Smaller/minimal version of wdt_e2e_simple_test.sh\n#\n\nsource `dirname \"$0\"`/common_functions.sh\nsetBinaries\n\necho \"Run from the cmake build dir (or ~/fbcode - or fbmake runtests)\"\n\nBASEDIR=/tmp/wdtTest_$USER\nUSE_ODIRECT=false\nusage=\"\nThe possible options to this script are\n-d base directory to use (defaults to $BASEDIR)\n-o if the value is true, o_direct read is used\n\"\n\nif [ \"$1\" == \"-h\" ]; then\n  echo \"$usage\"\n  exit 0\nfi\nwhile getopts \":d:h:o:\" opt; do\n  case $opt in\n    d) BASEDIR=\"$OPTARG\"\n    ;;\n    o)\n    if [ \"$OPTARG\" == \"true\" ]; then\n      echo \"Testing with o_direct reads\"\n      USE_ODIRECT=true\n    fi\n    ;;\n    h) echo \"$usage\"\n       exit\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\n# Set DO_VERIFY:\n# to 1 : slow/expensive but checks correctness\n# to 0 : fast for repeated benchmarking not for correctness\nDO_VERIFY=1\n\nif [ -z \"$WDT_TEST_SYMLINKS\" ] ; then\n  WDT_TEST_SYMLINKS=1\nfi\necho \"WDT_TEST_SYMLINKS=$WDT_TEST_SYMLINKS\"\n\n# Verbose / to debug failure:\n#WDTBIN=\"_bin/wdt/wdt -minloglevel 0 -v 99\"\n# Normal:\nWDTBIN_OPTS=\"-minloglevel=0 -sleep_millis 1 -max_retries 999 -full_reporting \"\\\n\"-avg_mbytes_per_sec=3000 -max_mbytes_per_sec=3500 \"\\\n\"-num_ports=4 -throttler_log_time_millis=200\"\nextendWdtOptions\nWDTBIN=\"$WDT_BINARY $WDTBIN_OPTS\"\nMD5SUM=`which md5sum`\nSTATUS=$?\nif [ $STATUS -ne 0 ] ; then\n  MD5SUM=`which md5`\nfi\necho \"Found md5sum as $MD5SUM\"\n\nif [ -z \"$HOSTNAME\" ] ; then\n    echo \"HOSTNAME not set, will try with 'localhost'\"\n    HOSTNAME=localhost\nelse\n    echo \"Will self connect to HOSTNAME=$HOSTNAME\"\nfi\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d $BASEDIR/XXXXXX`\necho \"Testing in $DIR\"\n\n#pkill -x wdt\n\nmkdir $DIR/src\nmkdir $DIR/extsrc\n\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec /usr/share $DIR/src\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec $DIR/src\n#cp -R wdt $DIR/src\n\n#for size in 1k 64K 512K 1M 16M 256M 512M 1G\n#for size in 512K 1M 16M 256M 512M 1G\n# In megabytes\nfor size in .0009765625 .0625 0.5 1 20\ndo\n    base=inp$size\n    for i in {1..8}\n    do\n        $WDT_GEN_FILES -stats_source=\"$WDT_GEN_BIGRAMS\" \\\n                 -directory=\"$DIR/src\" -filename=\"$base.$i\" -gen_size_mb=\"$size\"\n    done\ndone\necho \"done with setup\"\n\nif [ $WDT_TEST_SYMLINKS -eq 1 ]; then\n  # test symlink issues\n  (cd $DIR/src ; touch a; ln -s doesntexist badlink; dd if=/dev/zero of=c bs=1024 count=1; mkdir d; ln -s ../d d/e; ln -s ../c d/a)\n  (cd $DIR/extsrc; mkdir TestDir; mkdir TestDir/test; cd TestDir; echo \"Text1\" >> file1; cd test; echo \"Text2\" >> file1; ln -s $DIR/extsrc/TestDir; cp -R $DIR/extsrc/TestDir $DIR/src)\nfi\n\n\nCMD=\"$WDTBIN -minloglevel=0 -directory $DIR/dst 2> $DIR/server.log | \\\n    $WDTBIN -directory $DIR/src -odirect_reads=$USE_ODIRECT - 2>&1 | \\\n    tee $DIR/client1.log\"\necho \"First transfer: $CMD\"\neval $CMD\nSTATUS=$?\n# TODO check for $? / crash... though diff will indirectly find that case\n\nif [ $WDT_TEST_SYMLINKS -eq 1 ]; then\n  CMD=\"$WDTBIN -minloglevel=0 -directory $DIR/dst_symlinks 2>> $DIR/server.log \\\n   | $WDTBIN -follow_symlinks -directory $DIR/src \\\n    -odirect_reads=$USE_ODIRECT - 2>&1 | tee $DIR/client2.log\"\n  echo \"Second transfer: $CMD\"\n  eval $CMD\n  # TODO check for $? / crash... though diff will indirectly find that case\nfi\n\nif [ $DO_VERIFY -eq 1 ] ; then\n    echo \"Verifying for run without follow_symlinks\"\n    echo \"Checking for difference `date`\"\n\n    NUM_FILES=`(cd $DIR/dst && ( find . -type f | wc -l))`\n    echo \"Transfered `du -ks $DIR/dst` kbytes across $NUM_FILES files\"\n\n    (cd $DIR/src ; ( find . -type f -print0 | xargs -0 $MD5SUM | sort ) \\\n        > ../src.md5s )\n    (cd $DIR/dst ; ( find . -type f -print0 | xargs -0 $MD5SUM | sort ) \\\n        > ../dst.md5s )\n\n    echo \"Should be no diff\"\n    (cd $DIR; diff -u src.md5s dst.md5s)\n    STATUS=$?\n\n\n  if [ $WDT_TEST_SYMLINKS -eq 1 ]; then\n    echo \"Verifying for run with follow_symlinks\"\n    echo \"Checking for difference `date`\"\n\n    NUM_FILES=`(cd $DIR/dst_symlinks && ( find . -type f | wc -l))`\n    echo \"Transfered `du -ks $DIR/dst_symlinks` kbytes across $NUM_FILES files\"\n\n    (cd $DIR/src ; ( find -L . -type f -print0 | xargs -0 $MD5SUM | sort ) \\\n        > ../src_symlinks.md5s )\n    (cd $DIR/dst_symlinks ; ( find . -type f -print0 | xargs -0 $MD5SUM \\\n        | sort ) > ../dst_symlinks.md5s )\n\n    echo \"Should be no diff\"\n    (cd $DIR; diff -u src_symlinks.md5s dst_symlinks.md5s)\n    SYMLINK_STATUS=$?\n    if [ $STATUS -eq 0 ] ; then\n      STATUS=$SYMLINK_STATUS\n    fi\n  fi\nelse\n    echo \"Skipping independant verification\"\nfi\n\n\necho \"Server logs:\"\ncat $DIR/server.log\n\nif [ $STATUS -eq 0 ] ; then\n  echo \"Good run, deleting logs in $DIR\"\n  find $DIR -type d | xargs chmod 755 # cp -r can make some unreadable dir\n  rm -rf $DIR\nelse\n  echo \"Bad run ($STATUS) - keeping full logs and partial transfer in $DIR\"\nfi\n\nexit $STATUS\n", "num_lines": 178}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Multiple benchmarks - set DO_VERIFY=0 and\n#\n# wdt/wdt_e2e_test.sh |& awk '/All data.*Total throughput/ \\\n# {print $30} /^(real|user|sys)/ {print $0}'\n\n# 100 loops:\n#\n# for i in {1..100} ;do date; wdt/wdt_e2e_test.sh \\\n# |& awk '/All data.*Total throughput/ {print int($30+.5)}' \\\n# >> ~/wdt_perfRes100; done &\n#\n# $ histogram -offset 7000 -divider 100 -percentile1 25 -percentile2 50 < ~/wdt_perfRes100\n# # count,avg,min,max,stddev,100,8433.43,6506,9561,690.083\n# # range, mid point, percentile, count\n# < 7100 , 7050 , 3, 3\n# >= 7100 < 7200 , 7150 , 7, 4\n# >= 7200 < 7300 , 7250 , 10, 3\n# >= 7300 < 7400 , 7350 , 10, 0\n# >= 7400 < 7500 , 7450 , 11, 1\n# >= 7500 < 7600 , 7550 , 12, 1\n# >= 7600 < 7700 , 7650 , 14, 2\n# >= 7700 < 7800 , 7750 , 15, 1\n# >= 7800 < 7900 , 7850 , 15, 0\n# >= 7900 < 8000 , 7950 , 19, 4\n# >= 8000 < 8100 , 8050 , 27, 8\n# >= 8100 < 8200 , 8150 , 35, 8\n# >= 8200 < 8400 , 8300 , 43, 8\n# >= 8400 < 8600 , 8500 , 59, 16\n# >= 8600 < 8800 , 8700 , 68, 9\n# >= 8800 < 9000 , 8900 , 80, 12\n# >= 9000 < 9500 , 9250 , 97, 17\n# >= 9500 < 10000 , 9750 , 100, 3\n# # target 25.0%,8075.0\n# # target 50.0%,8487.5\nusage=\"\nThe possible options to this script are\n-t #threads\n-s specify 1 to save client logs to local dir\n-a Average transfer rate to achieve\n-p Peak Rate for Token Bucket\n-d Delay (seconds) to introduce at receiver\n\"\n\necho \"Run from ~/fbcode - or fbmake runtests\"\n\nsource `dirname \"$0\"`/common_functions.sh\nsetBinaries\n\n# Set DO_VERIFY:\n# to 1 : slow/expensive but checks correctness\n# to 0 : fast for repeated benchmarking not for correctness\nDO_VERIFY=1\n# echo e | $NC was used to stop daemon servers\n#NC=\"nc -4\" # ipv4 only\n\n# Verbose:\n#WDTBIN=\"_bin/wdt/wdt -minloglevel 0\"\n# Fastest:\nBS=`expr 256 \\* 1024`\nthreads=8\n# set a default value for avg rate to test throttler\navg_rate=3000\nmax_rate=-1\nkeeplog=0\ndelay=0\nif [ \"$1\" == \"-h\" ]; then\n  echo \"$usage\"\n  exit 0\nfi\nwhile getopts \":t:a:p:s:d:h:\" opt; do\n  case $opt in\n    t) threads=\"$OPTARG\"\n    ;;\n    s) keeplog=\"$OPTARG\"\n    ;;\n    a) avg_rate=\"$OPTARG\"\n    ;;\n    p) max_rate=\"$OPTARG\"\n    ;;\n    d) delay=\"$OPTARG\"\n    ;;\n    h) echo \"$usage\"\n       exit\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\nprintf \"(Sockets,Average rate, Max_rate, Save local?, Delay)=%s,%s,%s,%s,%s\\n\" \"$threads\" \"$avg_rate\" \"$max_rate\" \"$keeplog\" \"$delay\"\n#WDTBIN_OPTS=\"-buffer_size=$BS -num_sockets=8 -minloglevel 2 -sleep_ms 1 -max_retries 999\"\nWDTBIN_OPTS=\"-minloglevel=0 -sleep_millis 1 -max_retries 999 -full_reporting \"\\\n\"-static_ports -avg_mbytes_per_sec=$avg_rate -max_mbytes_per_sec=$max_rate \"\\\n\"-num_ports=$threads -throttler_log_time_millis=200 \"\\\n\"-transfer_id=$$\"\nextendWdtOptions\nWDTBIN=\"$WDT_BINARY $WDTBIN_OPTS\"\n\nBASEDIR=/dev/shm/wdtTest_$USER\n#BASEDIR=/data/wdt/tmpWDT\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing in $DIR\"\n\n#pkill -x wdt\n\nmkdir $DIR/src\nmkdir $DIR/extsrc\n\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec /usr/share $DIR/src\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec $DIR/src\n#cp -R wdt folly /usr/bin /usr/lib $DIR/src\ncp -R wdt folly /usr/bin $DIR/src\n#cp -R wdt folly $DIR/src\n# Removing symlinks which point to the same source tree\nfor link in `find -L $DIR/src -xtype l`\ndo\n  real_path=`readlink -e $link`;\n  if [[ $real_path =~ ^$DIR/src/* ]]\n  then\n    echo \"Removing symlink $link\"\n    rm $link\n  fi\ndone\n#cp -R wdt $DIR/src\n\n#for size in 1k 64K 512K 1M 16M 256M 512M 1G\n#for size in 512K 1M 16M 256M 512M 1G\n# In Mbytes\nfor size in .0009765625 .0625 0.5 1 16 256\ndo\n    base=inp$size\n    for i in {1..8}\n    do\n      $WDT_GEN_FILES -stats_source=\"$WDT_GEN_BIGRAMS\" \\\n        -directory=\"$DIR/src\" -filename=\"$base.$i\" -gen_size_mb=\"$size\"\n    done\ndone\nfallocate -l 3G $DIR/src/file_big\necho \"done with setup\"\n\n# test symlink issues\n(cd $DIR/src ; touch a; ln -s doesntexist badlink; dd if=/dev/zero of=c bs=1024 count=1; mkdir d; ln -s ../d d/e; ln -s ../c d/a)\n(cd $DIR/extsrc; mkdir TestDir; mkdir TestDir/test; cd TestDir; echo \"Text1\" >> file1; cd test; echo \"Text2\" >> file1; ln -s $DIR/extsrc/TestDir; cp -R $DIR/extsrc/TestDir $DIR/src)\n\n# Various smaller tests if the bigger one fails and logs are too hard to read:\n#cp wdt/wdtlib.cpp wdt/wdtlib.h $DIR/src\n#cp wdt/*.cpp $DIR/src\n#cp /usr/bin/* $DIR/src\n#cp wdt/wdtlib.cpp $DIR/src/a\n#cp wdt/wdtlib.h  $DIR/src/b\n#head -30 wdt/wdtlib.cpp >  $DIR/src/c\n# Can't have both client and server send to stdout in parallel or log lines\n# get mangled/are missing - so we redirect the server one\n$WDTBIN -minloglevel=1 -directory $DIR/dst > $DIR/server.log 2>&1 &\n# client now retries connects so no need wait for server to be up\npidofreceiver=$!\n# Only 1 socket (single threaded send/receive)\n#$WDTBIN -num_sockets=1 -directory $DIR/src -destination ::1\n# Normal\n\n#time trickle -d 1000 -u 1000 $WDTBIN -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\nif [ $delay -gt 0 ] ; then\n  (sleep 3; kill -STOP $pidofreceiver; sleep $delay; kill -CONT $pidofreceiver ) &\nfi\necho \"$WDTBIN -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\"\ntime $WDTBIN -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\n\n$WDTBIN -directory $DIR/dst_symlinks >> $DIR/server.log 2>&1 &\necho \"$WDTBIN -follow_symlinks -directory $DIR/src -destination $HOSTNAME |& tee -a $DIR/client.log\"\ntime $WDTBIN -follow_symlinks -directory $DIR/src -destination $HOSTNAME |& tee -a $DIR/client.log\n\n# rsync test:\n#time rsync --stats -v -W -r $DIR/src/ $DIR/dst/\n\n# No need to wait for transfer to finish, client now exits when last byte is saved\n\n\nif [ $DO_VERIFY -eq 1 ] ; then\n    echo \"Verifying for run without follow_symlinks\"\n    echo \"Checking for difference `date`\"\n\n    NUM_FILES=`(cd $DIR/dst ; ( find . -type f | wc -l))`\n    echo \"Transfered `du -ks $DIR/dst` kbytes across $NUM_FILES files\"\n\n    (cd $DIR/src ; ( find . -type f -print0 | xargs -0 md5sum | sort ) \\\n        > ../src.md5s )\n    (cd $DIR/dst ; ( find . -type f -print0 | xargs -0 md5sum | sort ) \\\n        > ../dst.md5s )\n\n    echo \"Should be no diff\"\n    (cd $DIR; diff -u src.md5s dst.md5s)\n    STATUS=$?\n\n\n    echo \"Verifying for run with follow_symlinks\"\n    echo \"Checking for difference `date`\"\n\n    NUM_FILES=`(cd $DIR/dst_symlinks; ( find . -type f | wc -l))`\n    echo \"Transfered `du -ks $DIR/dst_symlinks` kbytes across $NUM_FILES files\"\n\n    (cd $DIR/src ; ( find -L . -type f -print0 | xargs -0 md5sum | sort ) \\\n        > ../src_symlinks.md5s )\n    (cd $DIR/dst_symlinks ; ( find . -type f -print0 | xargs -0 md5sum \\\n        | sort ) > ../dst_symlinks.md5s )\n\n    echo \"Should be no diff\"\n    (cd $DIR; diff -u src_symlinks.md5s dst_symlinks.md5s)\n    SYMLINK_STATUS=$?\n    if [ $STATUS -eq 0 ] ; then\n      STATUS=$SYMLINK_STATUS\n    fi\n#(cd $DIR; ls -lR src/ dst/ )\nelse\n    echo \"Skipping independant verification\"\n    STATUS=0\nfi\n\n\necho \"Server logs:\"\ncat $DIR/server.log\nif [ $keeplog -ne 0 ]; then\n  cp $DIR/client.log client.log\nfi\nif [ $STATUS -eq 0 ] ; then\n  echo \"Good run, deleting logs in $DIR\"\n  find $DIR -type d | xargs chmod 755 # cp -r makes lib/locale not writeable somehow\n  rm -rf $DIR\nelse\n  echo \"Bad run ($STATUS) - keeping full logs and partial transfer in $DIR\"\nfi\n\nexit $STATUS\n", "num_lines": 235}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Invoke the regular script after finding an XFS dir to write to\n\nXFS=`df -T 2> /dev/null | awk '$2==\"xfs\" {print $7}'|head -1`\n\nif [ -z \"$XFS\" ] ; then\n    echo \"No XFS fs found. Skipping test.\"\n    exit 0\nfi\n\necho \"Found XFS on $XFS\"\n\nif [ ! -w $XFS ] ; then\n    XFS=$XFS/users/$USER\n    if [ ! -w $XFS ] ; then\n        echo \"Can't write to either base xfs nor $XFS. Skipping test.\"\n        exit 0\n    fi\n    DIR=$XFS/wdtTest\nelse\n    DIR=$XFS/wdtTest_$USER\nfi\n\nset -x\nexec `dirname $0`/wdt_e2e_simple_test.sh -d $DIR\n", "num_lines": 26}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\nsetBinaries\n\ntransfer() {\n  $WDT_BIN -skip_writes > $DIR/server${TEST_COUNT}.log 2>&1 &\n  pidofreceiver=$!\n  $WDT_BIN -destination=$HOSTNAME -directory=$SRC_DIR \\\n    2>&1 | tee $DIR/client${TEST_COUNT}.log\n  SENDER_STATUS=$?\n  wait $pidofreceiver\n  RECEIVER_STATUS=$?\n  if [ $SENDER_STATUS -ne $1 ]; then\n    printServerLog\n    echo \"Expected sender status to be $1, but got $SENDER_STATUS\"\n    wdtExit 1\n  fi\n  if [ $RECEIVER_STATUS -ne $2 ]; then\n    printServerLog\n    echo \"Expected receiver status to be $2, but got $RECEIVER_STATUS\"\n    wdtExit 1\n  fi\n  TEST_COUNT=$((TEST_COUNT + 1))\n}\n\nSTARTING_PORT=22356\nWDTBIN_OPTS=\"-ipv6 -start_port=$STARTING_PORT -read_timeout_millis=100 \\\n-write_timeout_millis=100 -connect_timeout_millis=100 -transfer_id=wdt \\\n-max_accept_retries=10\"\nextendWdtOptions\nWDT_BIN=\"$WDT_BINARY $WDTBIN_OPTS\"\n\nBASEDIR=/tmp/wdtTest_$USER\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d $BASEDIR/XXXXXX`\necho \"Testing in $DIR\"\n\nTEST_COUNT=0\n\necho \"Testing directory permission error\"\nSRC_DIR=$DIR/inaccessible_dir\nmkdir $SRC_DIR\nchmod 000 $SRC_DIR\ntransfer 7 7  # BYTE_SOURCE_READ_ERROR\n\necho \"Testing file permission error\"\nSRC_DIR=$DIR/src1\nmkdir $SRC_DIR\ntouch $SRC_DIR/inaccessible_file\nchmod 000 $SRC_DIR/inaccessible_file\ntransfer 7 7  # BYTE_SOURCE_READ_ERROR\n\necho \"Testing port block and file permission issue\"\nblockDportByRejecting $STARTING_PORT\ntransfer 7 7 # read error more \"interesting\" than transient network error\nundoLastIpTableChange\n\necho \"Test passed, removing $DIR\"\nrm -rf $DIR\nwdtExit 0\n", "num_lines": 63}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\n\nsetBinaries\nsetDirectory\n\n# create a big file\ndd if=/dev/zero of=\"$SRC_DIR/file\" bs=536870912 count=1\n\nWDTBIN_OPTS=\"-static_ports -num_ports=2 -transfer_id=wdt\"\nextendWdtOptions\n\nTEST_COUNT=0\n# start the server\n$WDT_RECEIVER $WDTBIN_OPTS -skip_writes \\\n-connect_timeout_millis 100 \\\n-read_timeout_millis=200 > \"$DIR/server${TEST_COUNT}.log\" 2>&1 &\npidofreceiver=$!\n\n# block 22356 for small duration so that file is transferred through 22357\nblockDportByDropping 22356\n# start client\n$WDT_SENDER $WDTBIN_OPTS -destination localhost -directory \"$DIR/src\" \\\n-block_size_mbytes=-1 -avg_mbytes_per_sec=100 \\\n2>&1 | tee \"$DIR/client${TEST_COUNT}.log\" &\npidofsender=$!\nsleep 0.1\nundoLastIpTableChange\nsleep 5\n# block 22357 in the middle\nblockDportByDropping 22357\nwaitForTransferEnd\n\necho \"Test passed, deleting directory $DIR\"\nrm -rf \"$DIR\"\nwdtExit 0\n", "num_lines": 38}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\nsetBinaries\nBASEDIR=/tmp/wdtTest_$USER\nsetDirectory\n\n# Simple error test for 2 receiver\n\nWDTBIN_OPTS=\"-num_ports=1 -enable_download_resumption\"\nWDTBIN_OPTS+=\" -directory $DIR/dst\"\nWDTBIN=\"$WDT_BINARY $WDTBIN_OPTS\"\n\n# Use -fork so this blocks until url is generated/receiver started\n$WDTBIN -fork -abort_after_seconds=3 > \"$DIR/url1\"\n# Second transfer\n$WDTBIN -abort_after_seconds=5 > \"$DIR/url2\"\n\nSTATUS=$?\n\necho \"2nd transfer status $STATUS - should be TRANSFER_LOG_ACQUIRE_ERROR 25\"\n\nls -l $DIR/url*\n\nURL2=$(cat \"$DIR/url2\")\n\nif [ ! -z \"$URL2\" ] ; then\n  echo \"There shouldn't be a url in 2nd run - there was $URL2\"\n  STATUS=-1\nfi\n\nrm -rf \"$DIR\"\n\n\nif [ $STATUS -eq 25 ] ; then\n  echo \"Good run!\"\n  exit 0\nelse\n  echo \"Bad run! $STATUS\"\n  exit 1\nfi\n", "num_lines": 42}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# This is to regress/test the max ~22000Mbytes/sec transfer rate\n# to get the highest (> 20G) rates you need:\n# a) /dev/shm to be almost empty\n# b) nothing else much running on your dev server\n# c) run this a couple times\n\n# modified from wdt_e2e_test.sh and fbonly/wdt_prof.sh\n\nsource `dirname \"$0\"`/common_functions.sh\n\necho \"Run this sender performance test from fbcode/ directory\"\necho \"or give full path to wdt binary to use and staging directory\"\n\n#set -x\n#set -o pipefail\n\nif [ -z \"$1\" ]; then\n  WDTBIN=\"_bin/wdt/wdt\"\nelse\n  WDTBIN=\"$1\"\nfi\n\nif [ -z \"$2\" ]; then\n    BASEDIR=/dev/shm/wdtTest_$USER\nelse\n    BASEDIR=$2\nfi\n\nAWK=gawk\n\n# TEST_COUNT is an environment variable. It is set up by the python benchmarking\n# script.\nif [ -z $TEST_COUNT ]; then\n  TEST_COUNT=16\nfi\n\n# WDT_THROUGHPUT is an env var. Set it to overwrite the expected 16Gbyte/sec\nif [ -z $WDT_THROUGHPUT ]; then\n  WDT_THROUGHPUT=16000\nfi\n\n\nif [ -z \"$HOSTNAME\" ] ; then\n    echo \"HOSTNAME not set, will try with 'localhost'\"\n    HOSTNAME=localhost\nelse\n    echo \"Will self connect to HOSTNAME=$HOSTNAME\"\nfi\n\nREMOTE=$HOSTNAME\nSKIP_WRITES=\"true\"\n\n# TODO: switch to url\n\n# Without throttling:\n#WDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_sockets 13\"\n\n#CPU normalization\nNUM_CPU=`grep processor /proc/cpuinfo|wc -l`\n# leave one cpu alone for the rest (or typically 2 because of /2)\nNUM_THREADS=`echo $NUM_CPU/2|bc`\necho \"Using $NUM_THREADS threads (on each sender, receiver) for $NUM_CPU CPUs\"\n\n# With, still gets almost same max (21G) with throttling set high enough\nWDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_ports $NUM_THREADS\n-transfer_id=$$ -encryption_type=none\n-exit_on_bad_flags=false -skip_fadvise\n--avg_mbytes_per_sec=26000 --max_mbytes_per_sec=26001 --enable_checksum=false\"\nextendWdtOptions\nCLIENT_PROFILE_FORMAT=\"%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata \\\n%Mmax)k\\n%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps\\nCLIENT_PROFILE %U \\\n%S %e\"\nSERVER_PROFILE_FORMAT=\"%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata \\\n%Mmax)k\\n%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps\\nSERVER_PROFILE %U \\\n%S %e\"\n\nWDTNAME=`basename $WDTBIN`\nWDTCMD=\"$WDTBIN $WDTBIN_OPTS\"\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing $WDTBIN in $DIR\"\nif [ -z \"$DIR\" ]; then\n  echo \"Unable to create dir in $BASEDIR\"\n  exit 1\nfi\n\npkill -x wdt\npkill -x wdt_fb\npkill -x $WDTNAME\n\nmkdir $DIR/src\n\nfor size in 1k 64K 512K 1M 16M 256M 512M\ndo\n    base=inp$size\n    echo dd if=/dev/... of=$DIR/src/$base.1 bs=$size count=1\n    dd if=/dev/zero of=$DIR/src/$base.1 bs=$size count=1\n    for i in {2..32}\n    do\n        cp $DIR/src/$base.1 $DIR/src/$base.$i\n    done\ndone\necho \"Done with staging src test files\"\n\n#set -e\n\n# TODO: add a test that will fail if the listening socket is closed in\n# long running mode upon error (to make sure the code doesn't\n# regress/handles that case ok) by adding: but that fails for other reasons\n#             -max_accept_retries=1 -accept_timeout_millis=1 \\\n\n/usr/bin/time -f \"$SERVER_PROFILE_FORMAT\" $WDTCMD -directory $DIR/dst \\\n              -run_as_daemon=true -skip_writes=$SKIP_WRITES  \\\n                       > $DIR/server.log 2>&1 &\n\n# wait for server to be up\n#while [ `/bin/true | nc $REMOTE 22356; echo $?` -eq 1 ]\n#do\n#  echo \"Server not up yet...`date`...\"\n#  sleep 0.5\n#done\n#echo \"Server is up on $REMOTE 22356 - `date` - starting client run\"\n\nfor ((i = 1; i <= TEST_COUNT; i++))\ndo\n  echo \"starting ${i}th run\"\n  TWO_PHASE_ARG=\"\"\n  # every other run will be two_phases\n  [ $(($i % 2)) -eq 0 ] && TWO_PHASE_ARG=\"-two_phases\"\n\n  /usr/bin/time -f \"$CLIENT_PROFILE_FORMAT\" $WDTCMD -directory $DIR/src \\\n  -destination $REMOTE $TWO_PHASE_ARG |& tee $DIR/client$i.log\n  THROUGHPUT=`$AWK 'match($0, /.*Total sender throughput = ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"THROUGHPUT $THROUGHPUT\"\n  TRANSFER_TIME=`$AWK 'match($0, /.*Total sender time = ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"TRANSFER_TIME $TRANSFER_TIME\"\ndone\n\npkill -x $WDTNAME\n# echo -n e | nc $REMOTE 22356 # end command is gone\n\necho \"Server logs:\"\ncat $DIR/server.log\n\n# Todo : count how many runs are above X... and which\n\nMAXRATE=`$AWK 'BEGIN {max=0} match($0, /.*Total sender throughput = ([0-9.]+)/, res) {rate=res[1]; if (rate>max) max=rate} END {print int(max+.5)}' $DIR/client*.log`\n\nALLSPEEDS=`$AWK 'match($0, /.*Total sender throughput = ([0-9.]+)/, res) {printf(\"%s \", res[1])}' $DIR/client*.log`\n\necho \"Deleting logs and staging in $DIR\"\nrm -rf $DIR\n\necho \"Speed for all runs: $ALLSPEEDS\"\n\n# Normalize by CPU / number of threads\n# (32 cores leaves 15 threads and can do ~20-22G, use 16 for margin of noise)\nEXPECTED_SPEED=`echo $WDT_THROUGHPUT*$NUM_THREADS/16|bc`\n\necho \"Best throughput for $WDTBIN\"\nif [ \"$MAXRATE\" -lt \"$EXPECTED_SPEED\" ]; then\n    echo \"Regression: $MAXRATE is too slow - before top\"\n    atop -l 1 1 | head -40\n    echo \"Regression: $MAXRATE is too slow for $NUM_CPU cpus ($EXPECTED_SPEED)\"\n    exit 1\nelse\n    echo \"Good rate $MAXRATE for $NUM_CPU cpus (threshold $EXPECTED_SPEED)\"\n    exit 0\nfi\n\n# all done\n", "num_lines": 177}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n\n# This script is mostly copied from wdt_e2e_test script. It has the same set up\n# procedure. It is modified to support windtunnel integration.\n# TODO: refactor this and e2e script to remove duplication of set up code\n\n# TEST_COUNT is an environment variable. It is set up by the python benchmarking\n# script.\nif [ -z $TEST_COUNT ]; then\n  TEST_COUNT=1\nfi\n\nWDTBIN_OPTS=\"-minloglevel=0 -num_ports=8 -enable_checksum=false\"\nif [ -z \"$1\" ]; then\n  WDTBIN=\"_bin/wdt/wdt $WDTBIN_OPTS\"\nelse\n  WDTBIN=\"$1 $WDTBIN_OPTS\"\nfi\nCLIENT_PROFILE_FORMAT=\"%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata \\\n%Mmax)k\\n%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps\\nCLIENT_PROFILE %U \\\n%S %e\"\nSERVER_PROFILE_FORMAT=\"%Uuser %Ssystem %Eelapsed %PCPU (%Xtext+%Ddata \\\n%Mmax)k\\n%Iinputs+%Ooutputs (%Fmajor+%Rminor)pagefaults %Wswaps\\nSERVER_PROFILE %U \\\n%S %e\"\n\nBASEDIR=/dev/shm/tmpWDT\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing in $DIR\"\n\npkill -x wdt\n\nmkdir $DIR/src\n\ncp -R wdt folly $DIR/src\nfor size in 1k 64K 512K 1M 16M 256M 512M\ndo\n    base=inp$size\n    echo dd if=/dev/... of=$DIR/src/$base.1 bs=$size count=1\n    dd if=/dev/zero of=$DIR/src/$base.1 bs=$size count=1\n    for i in {2..8}\n    do\n        cp $DIR/src/$base.1 $DIR/src/$base.$i\n    done\ndone\necho \"done with setup\"\n\nfor ((i = 1; i <= TEST_COUNT; i++))\ndo\n  TWO_PHASE_ARG=\"\"\n  # every other run will be two_phases\n  [ $(($i % 2)) -eq 0 ] && TWO_PHASE_ARG=\"-two_phases\"\n  /usr/bin/time -f \"$SERVER_PROFILE_FORMAT\" $WDTBIN -directory $DIR/dst$i > \\\n  $DIR/server$i.log 2>&1 &\n\n  # wait for server to be up\n  #while [ `/bin/true | nc $HOSTNAME 22356; echo $?` -eq 1 ]\n  #do\n  #  echo \"Server not up yet...`date`...\"\n  #  sleep 0.5\n  #done\n  #echo \"Server is up on $HOSTNAME 22356 - `date` - starting client run\"\n\n  /usr/bin/time -f \"$CLIENT_PROFILE_FORMAT\" $WDTBIN -directory $DIR/src \\\n  -destination $HOSTNAME $TWO_PHASE_ARG |& tee $DIR/client$i.log\n  echo -n e | nc -4 $HOSTNAME 22356\n  rm -rf $DIR/dst$i\n  THROUGHPUT=`awk 'match($0, /.*Total sender throughput = ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"THROUGHPUT $THROUGHPUT\"\n  TRANSFER_TIME=`awk 'match($0, /.*Total sender time =  ([0-9.]+)/, res) \\\n  {print res[1]} END {}' $DIR/client$i.log`\n  echo \"TRANSFER_TIME $TRANSFER_TIME\"\ndone\n\necho \"Server logs:\"\nfor ((i = 1; i <= TEST_COUNT; i++))\ndo\n  cat $DIR/server$i.log\ndone\n\nfind $DIR -type d | xargs chmod 755 # cp -r makes lib/locale not writeable somehow\necho \"Deleting $DIR\"\nrm -rf $DIR\n", "num_lines": 85}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\n\nstartNewTransfer() {\n  echo \"Starting receiver:\"\n  echo \"$WDTBIN_SERVER $EXTRA_SERVER_ARGS -directory $DIR/dst${TEST_COUNT}\"\n  $WDTBIN_SERVER $EXTRA_SERVER_ARGS -directory $DIR/dst${TEST_COUNT} > \\\n  $DIR/server${TEST_COUNT}.log 2>&1 &\n  pidofreceiver=$!\n  echo \"Starting sender:\"\n  echo \"$WDTBIN_CLIENT $EXTRA_CLIENT_ARGS\"\n  $WDTBIN_CLIENT $EXTRA_CLIENT_ARGS |& tee -a $DIR/client${TEST_COUNT}.log &\n  pidofsender=$!\n  unset EXTRA_SERVER_ARGS\n  unset EXTRA_CLIENT_ARGS\n}\n\nprocessTransferFinish() {\n  waitForTransferEnd\n  verifyTransferAndCleanup\n  undoLastIpTableChange\n  TEST_COUNT=$((TEST_COUNT + 1))\n}\n\nusage=\"\nThe possible options to this script are\n-s sender protocol version\n-r receiver protocol version\n-p start port\n-x extraoptions\n\"\n\n#protocol versions, used to check version negotiation\n#version 0 represents default version\nSENDER_PROTOCOL_VERSION=0\nRECEIVER_PROTOCOL_VERSION=0\nSTARTING_PORT=24000\n\nwhile getopts \":s:p:r:h\" opt; do\n  case $opt in\n    s) SENDER_PROTOCOL_VERSION=\"$OPTARG\"\n    ;;\n    r) RECEIVER_PROTOCOL_VERSION=\"$OPTARG\"\n    ;;\n    p) STARTING_PORT=\"$OPTARG\"\n    ;;\n    h) echo \"$usage\"\n       exit 0\n    ;;\n    \\?) echo \"$usage\"\n       exit 1\n    ;;\n  esac\ndone\n\nsetBinaries\n\necho \"sender protocol version $SENDER_PROTOCOL_VERSION, receiver protocol \\\nversion $RECEIVER_PROTOCOL_VERSION\"\n\nif [ $RECEIVER_PROTOCOL_VERSION -ne 0 ] && [ $RECEIVER_PROTOCOL_VERSION -lt 23 \\\n] && [ -z $NO_ENCRYPT ]; then\n  echo \"Can not support encryption for receiver with version \\\n$RECEIVER_PROTOCOL_VERSION\"\n  # exit with 0 to make the test pass\n  exit 0\nfi\n\nthreads=4\nERROR_COUNT=25\nTEST_COUNT=0\n\nBASEDIR=/dev/shm/wdtTest_$USER\n\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing in $DIR\"\n\nWDTBIN_OPTS=\"-enable_perf_stat_collection -ipv6 -start_port=$STARTING_PORT \\\n-avg_mbytes_per_sec=15 -max_mbytes_per_sec=20 -run_as_daemon=false \\\n-full_reporting -read_timeout_millis=495 -write_timeout_millis=495 \\\n-progress_report_interval_millis=-1 -abort_check_interval_millis=100 \\\n-treat_fewer_port_as_error -exit_on_bad_flags=false -skip_fadvise \\\n-connect_timeout_millis 100 -transfer_id $$ -num_ports=$threads\"\nextendWdtOptions\nWDTBIN_SERVER=\"$WDT_RECEIVER $WDTBIN_OPTS \\\n  -protocol_version=$RECEIVER_PROTOCOL_VERSION\"\nWDTBIN_CLIENT=\"$WDT_SENDER $WDTBIN_OPTS -destination $HOSTNAME \\\n  -protocol_version=$SENDER_PROTOCOL_VERSION -directory $DIR/src\"\n#pkill -x wdt\n\nmkdir -p $DIR/src/dir1\ncp -R folly $DIR/src/dir1\nfor ((i = 2; i <= 50; i++))\ndo\n  mkdir $DIR/src/dir${i}\n  cp -R $DIR/src/dir1 $DIR/src/dir${i}\ndone\n\n\n# Testing with different start ports\necho \"Testing with different start ports in sender and receiver\"\nEXTRA_CLIENT_ARGS=\"-start_port=$((STARTING_PORT + 1))\"\nstartNewTransfer\nprocessTransferFinish\n\n\n# Testing with different less number of threads in sender\necho \"Testing with less number of threads in client\"\nEXTRA_CLIENT_ARGS=\"-num_ports=$((threads - 1))\"\nstartNewTransfer\nprocessTransferFinish\n\n\necho \"Testing with more number of threads in client\"\nEXTRA_CLIENT_ARGS=\"-num_ports=$((threads + 1))\"\nstartNewTransfer\nprocessTransferFinish\n\n\n# Blocking sender port before transfer by\necho \"Testing with port blocked before transfer(1)\"\nblockSportByDropping \"$STARTING_PORT\"\nstartNewTransfer\nprocessTransferFinish\n\n\necho \"Testing with port blocked before transfer(2)\"\nblockDportByDropping \"$STARTING_PORT\"\nstartNewTransfer\nprocessTransferFinish\n\n\n# Blocking a port in the middle of the transfer\necho \"Testing by blocking a port in the middle of the transfer(1)\"\nstartNewTransfer\nsleep 5\necho \"blocking $STARTING_PORT\"\nblockSportByDropping \"$STARTING_PORT\"\nprocessTransferFinish\n\n\necho \"Testing by blocking a port in the middle of the transfer(2)\"\nstartNewTransfer\nsleep 5\nPORT_TO_BLOCK=$((STARTING_PORT + 1))\necho \"blocking $PORT_TO_BLOCK\"\nblockDportByDropping \"$PORT_TO_BLOCK\"\nprocessTransferFinish\n\n\necho \"Testing by blocking a port in the middle of the transfer and more \\\nclient threads\"\nEXTRA_CLIENT_ARGS=\"-num_ports=$((threads + 1))\"\nstartNewTransfer\nsleep 5\nPORT_TO_BLOCK=$((STARTING_PORT + 1))\necho \"blocking $PORT_TO_BLOCK\"\nblockDportByDropping \"$PORT_TO_BLOCK\"\nprocessTransferFinish\n\n\necho \"Testing by blocking a port in the middle of the transfer and less \\\nclient threads\"\nEXTRA_CLIENT_ARGS=\"-num_ports=$((threads - 1))\"\nstartNewTransfer\nsleep 5\nPORT_TO_BLOCK=$((STARTING_PORT + 1))\necho \"blocking $PORT_TO_BLOCK\"\nblockDportByDropping \"$PORT_TO_BLOCK\"\nprocessTransferFinish\n\n\n# Simulating network glitches by rejecting packets\necho \"Simulating network glitches by rejecting packets\"\nstartNewTransfer\nsimulateNetworkGlitchesByRejecting\nprocessTransferFinish\n\n\n# Simulating network glitches by dropping packets\necho \"Simulating network glitches by dropping packets\"\nstartNewTransfer\nsimulateNetworkGlitchesByDropping\nprocessTransferFinish\n\necho \"Good run, deleting logs in $DIR\"\nrm -rf \"$DIR\"\n\nwdtExit 0\n", "num_lines": 192}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Tests for option types can not be run in the same process because gflags\n# can not be reset to default condition. This script runs all the tests one by\n# one in separate processes\n\nset -e\nset -o pipefail\n\nif [ \"$#\" -eq 0 ]; then\n  binaries=(_bin/wdt/option_type_test_long_flags \\\n    _bin/wdt/short_flags/option_type_test_short_flags)\nelse\n  binaries=$*\nfi\n\nfor binary in \"${binaries[@]}\"\ndo\n  ALL_TESTS=$($binary --gtest_list_tests|tail -n +2 |  sed 's/^ *//g')\n  for test_name in $ALL_TESTS\n  do\n    echo \"$binary --gtest_filter=*.$test_name\"\n    $binary --gtest_filter=\"*.$test_name\"\n    LAST_STATUS=$?\n    if [ $LAST_STATUS -ne 0 ] ; then\n      exit $LAST_STATUS\n    fi\n  done\ndone\nexit 0\n", "num_lines": 31}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\n\nif [ \"$#\" -eq 0 ]; then\n  binary=_bin/wdt/wdt_url_test\nelse\n  binary=$1\nfi\n\nset -o pipefail\nset -e\n\nsearchStr='Generated a transfer id'\ntransferId1=$($binary -v=1 2>&1 | grep \"$searchStr\" | head -1 | \\\n  awk '{print $10}')\ntransferId2=$($binary -v=1 2>&1 | grep \"$searchStr\" | head -1 | \\\n  awk '{print $10}')\n\nif [ \"$transferId1\" == \"$transferId2\" ]; then\n  echo \"Failed to get different transfer-id $transferId1\"\n  exit 1\nfi\necho \"Test successful $transferId1 $transferId2\"\nexit 0\n", "num_lines": 25}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n\n#set -e\n# modified from wdt_e2e_test.sh and fbonly/wdt_prof.sh\n\nSRCHOST=$1\nDSTHOST=$2\nif [ -z $DSTHOST ] ; then\n    echo \"Usage: $0 srchost desthost\"\n    exit 1\nfi\n\n#SKIP_WRITES=\"false\"\nSKIP_WRITES=\"true\"\n\necho \"Run from ~fbcode (wdt's parent dir). Skip writes is $SKIP_WRITES\"\n\n#WDTBIN_OPTS=\"-minloglevel 2 -sleep_millis 10 -max_retries 5 -num_sockets 15\"\nWDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_ports 16\"\n#WDTBIN_OPTS=\"-sleep_millis 1 -max_retries 3 -num_sockets 16 -ipv4=true\"\n\nBASEDIR=/dev/shm/wdtTest_$USER\n\n\n# Version with profiler:\n#WDTNAME=\"wdt_prof\"\n#WDTDIR=\"_bin/wdt/fbonly\"\n# Non profiler version\nWDTNAME=\"wdt\"\nWDTORIGDIR=\"_bin/wdt\"\nWDTDIR=\"$BASEDIR/_bin/wdt\"\nWDTBIN=\"$WDTDIR/$WDTNAME\"\nWDTCMD=\"$WDTBIN $WDTBIN_OPTS\"\n\n# For prod\nREMOTEUSER=\"root\"\nRSHDST=\"ssh -l $REMOTEUSER $DSTHOST\"\nRSHSRC=\"ssh -l $REMOTEUSER $SRCHOST\"\nSCP=\"scp\"\nNC=\"nc -4\" # ipv4 only\n\n#BASEDIR=/data/wdt/tmpWDT\nmkdir -p $BASEDIR\nDIR=`mktemp -d --tmpdir=$BASEDIR`\necho \"Testing in $DIR\"\n\nCMD=\"pkill -x $WDTNAME; mkdir -p $DIR/src ; mkdir -p $WDTDIR\"\n$RSHSRC $CMD\n$RSHDST $CMD\n$SCP $WDTORIGDIR/$WDTNAME $REMOTEUSER@$DSTHOST:$WDTBIN\n$SCP $WDTORIGDIR/$WDTNAME $REMOTEUSER@$SRCHOST:$WDTBIN\n\n# Start server/recipient first (so it's likely ready by the time we are done\n# staging the src)\necho \"Starting server on destination side $DSTHOST\"\n$RSHDST \"date; $WDTCMD -directory $DIR/dst -skip_writes=$SKIP_WRITES > $DIR/server.log 2>&1 &\"\n\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec /usr/share $DIR/src\n#cp -R wdt folly /usr/bin /usr/lib /usr/lib64 /usr/libexec $DIR/src\n# TODO get a better test/load generation - remote execute the for below for ex\n#$RSHSRC \"cp -R /usr/bin /usr/share $DIR/src\"\n\n#$RSHSRC \"cp -R /usr/bin /usr/lib /usr/lib64 $DIR/src\"\necho \"Staging on source side\"\n$RSHSRC \"dd if=/dev/zero of=$DIR/src/big.1 bs=16M count=1; for i in {2..64} ; do ln $DIR/src/big.1 $DIR/src/big.\\$i; done; ls -lh $DIR/src\"\n\necho 'done with setup'\n\necho \"Staging copy done on $SRCHOST, checking $DSTHOST\"\n\n# wait for server to be up\nwhile [ `$RSHSRC \"/bin/true | $NC $DSTHOST 22356; echo $?\"` -eq 1 ]\ndo\n echo \"Destination server not up yet...`date`...\"\n sleep 0.5\ndone\necho \"Server is up on $DSTHOST 22356 - `date`\"\n\n\n# Only 1 socket (single threaded send/receive)\n#$WDTCMD -num_sockets=1 -directory $DIR/src -destination ::1\n# Normal\n\n#time trickle -d 1000 -u 1000 $WDTCMD -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\n$RSHSRC \"time $WDTCMD -directory $DIR/src -destination $DSTHOST |& tee $DIR/client.log\"\n\necho \"2nd run of client\"\n$RSHSRC \"time $WDTCMD -directory $DIR/src -destination $DSTHOST |& tee $DIR/client2.log\"\n\necho \"3nd run of client with 2 phases\"\n$RSHSRC \"time  $WDTCMD -directory $DIR/src -destination $DSTHOST -two_phases |& tee $DIR/client3.log\"\n\necho \"Skipping independant verification\"\nSTATUS=0\n\necho \"Making the server end gracefully\"\n$RSHSRC \"echo -n e | $NC $DSTHOST 22356\"\n\necho \"Server logs:\"\n$RSHDST \"cat $DIR/server.log\"\n\necho \"Deleting logs in $DIR\"\n$RSHSRC \"find $DIR -type d | xargs chmod 755; rm -rf $DIR\"\n$RSHDST \"pkill -x wdt; rm -rf $DIR\"\n\necho \"All done with testing from $SRCHOST to $DSTHOST\"\n\nexit $STATUS\n", "num_lines": 109}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource `dirname \"$0\"`/common_functions.sh\n\nsetBinaries\nsetDirectory\ngenerateRandomFiles \"$SRC_DIR\" .015625 # in Mbytes: 16k smallest file\n\nWDTBIN_OPTS=\"-fork -abort_after_seconds 8\"\nextendWdtOptions\n\nTEST_COUNT=0\n# Test stdin pipe:\n\n( $WDT_RECEIVER $WDTBIN_OPTS -directory $DIR/dst${TEST_COUNT} \\\n    2> \"$DIR/server${TEST_COUNT}.log\" ; cd $SRC_DIR; ls -1) \\\n | $WDT_SENDER $WDTBIN_OPTS -directory $SRC_DIR -manifest - - \\\n    2>&1 | tee \"$DIR/client${TEST_COUNT}.log\"\n\ncheckLastCmdStatus\nverifyTransferAndCleanup\n\nTEST_COUNT=1\n\n( $WDT_RECEIVER $WDTBIN_OPTS -directory $DIR/dst${TEST_COUNT} \\\n    2> \"$DIR/server${TEST_COUNT}.log\" ; cd $SRC_DIR ) \\\n | $WDT_SENDER $WDTBIN_OPTS -directory $SRC_DIR -manifest - - \\\n    2>&1 | tee \"$DIR/client${TEST_COUNT}.log\"\n\ncheckLastCmdStatus\n\nif [ $(ls -1 $DIR/dst${TEST_COUNT} | wc -l) -ne 0 ] ; then\n  echo \"This shouldnt have transferred any files (empty fileInfo)\"\n  wdtExit 1\nfi\n\necho \"Test passed, deleting directory $DIR\"\nrm -rf \"$DIR\"\nwdtExit 0\n", "num_lines": 40}
{"repo_name": "wdt", "repo_creator": "facebook", "programming_language": "Shell", "code": "# shellcheck disable=SC2148\n# runs wdt with certain parameters for thread, average transfer rate, and peak rate\n# peak rate is just a multiplier over average rate here\n# This thread can be used by specifying a multiplier and the results of the\n# logs for this experiment can be plotted.\nBASE_DIR=\"/tmp/wdt_plots\"\nDATADIR=/dev/shm/tmpWDT\nmkdir -p $BASE_DIR\nDIR=`mktemp -d --tmpdir=$DATADIR`\necho \"Testing in $DIR\"\npkill -x wdt\nmkdir $DIR/src\ncp -R wdt folly /usr/share $DIR/src\n# Removing symlinks which point to the same source tree\nfor link in `find -L $DIR/src -xtype l`\ndo\n  real_path=`$REALPATH $link`;\n  if [[ $real_path =~ ^$DIR/src/* ]]\n  then\n    rm $link\n  fi\ndone\nfor size in 1k 64K 512K 1M 16M 256M 512M\ndo\n    base=inp$size\n    echo dd if=/dev/... of=$DIR/src/$base.1 bs=$size count=1\n    dd if=/dev/zero of=$DIR/src/$base.1 bs=$size count=1\n    for i in {2..8}\n    do\n        cp $DIR/src/$base.1 $DIR/src/$base.$i\n    done\ndone\necho \"done with setup\"\nprintf \"Starting the receiver\"\nWDTBIN=\"_bin/wdt/wdt -directory=$DIR/dst\"\n$WDTBIN -minloglevel=1 -directory $DIR/dst > $DIR/server.log 2>&1 &\npidofreceiver=$!\ndoit() {\n  transfer_rate=$1\n  peak_rate=\"$(echo \"$transfer_rate*$2\" | bc -l)\"\n  delay=$3\n  printf \"Running experiment with (Avg_Rate, Peak_Rate, Delay)=%s,%s,%s\\n\" \"$transfer_rate\" \"$peak_rate\" \"$delay\"\n  echo $transfer_rate\n  WDTBIN_OPTS=\"-minloglevel=0 -sleep_millis 1 -max_retries 999 -full_reporting -avg_mbytes_per_sec=$transfer_rate -max_mbytes_per_sec=$peak_rate -throttler_log_time_millis=200\"\n  if [ $delay -gt 0 ] ; then\n    (sleep 3; kill -STOP $pidofreceiver; sleep $delay; kill -CONT $pidofreceiver ) &\n  fi\n  echo \"$WDTBIN $WDTBIN_OPTS -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\"\n  time $WDTBIN $WDTBIN_OPTS -directory $DIR/src -destination $HOSTNAME |& tee $DIR/client.log\n  grep  Throttler:Transfer_Rates \"$DIR/client.log\" | awk -F '::' '{print $2}' > wdt_run_plot\n  gnuplot << EOF\n    set xlabel \"Time(sec)\"\n    set ylabel \"Throughput (MB)\"\n    set term png\n    set output \"plot_{$transfer_rate}_{$peak_rate}.png\"\n    plot \"wdt_run_plot\" using 1:2 with lines title \"Avg Throughput\", \"wdt_run_plot\" using 1:3 with lines title \"Instant throughput\"\nEOF\n  mv \"plot_{$transfer_rate}_{$peak_rate}.png\" \"$BASE_DIR/plot_{$transfer_rate}_{$peak_rate}.png\"\n  cp \"$DIR/client.log\" \"$BASE_DIR/plot_{$transfer_rate}_{$peak_rate}.logs\"\n  rm \"wdt_run_plot\"\n  printf \"Created the plot at $BASE_DIR/plot_{$transfer_rate}_{$peak_rate}.png\"\n  rm -rf \"$DIR/dst/*\"\n  sleep 2\n}\nif [[ ! -d \"$BASE_DIR\" ]] ; then\n  mkdir \"$BASE_DIR\"\n  printf \"Creating a directory $BASE_DIR\"\nelse\n  rm -rf \"$BASE_DIR/*\"\n  printf \"Deleteing contents of $BASE_DIR\"\nfi\ndelay=5 #introduce delay of 5 seconds\nmax_runs=1 #number of runs for averaging\nstart=100\nend=200\nfor (( num_runs=1; num_runs<=$max_runs; num_runs+=1 ))\ndo\n  for (( t=$start; t<= $end; t+=100))\n  do\n    for mul in {1.1,1.2,1.3,1.5}\n    do\n      doit $t $mul $delay\n    done\n  done\ndone\nprintf \"Killing the receiver\"\nkill -9 $pidofreceiver\nrm -rf \"$DIR/src\"\nrm -rf \"$DIR/dst\"\n", "num_lines": 90}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Temporary compiled binary\nOUT_FILE=\"tempbin\"\n\n# Optional temporary compiled WebAssembly\nOUT_WASM=\"temp.wasm\"\n\n# Source files to compile using Emscripten.\nIN_FILES=\"examples/emscripten.c\"\n\n# Emscripten build using emcc.\nemscripten_emcc_build() {\n  # Compile the same example as above\n  CC_FLAGS=\"-Wall -Wextra -Wshadow -Werror -Os -g0 -flto\"\n  emcc $CC_FLAGS -s WASM=1 -I. -o $OUT_WASM $IN_FILES\n  # Did compilation work?\n  if [ $? -ne 0 ]; then\n    echo \"Compiling ${IN_FILES}: FAILED\"\n    exit 1\n  fi\n  echo \"Compiling ${IN_FILES}: PASSED\"\n  rm -f $OUT_WASM\n}\n\n# Emscripten build using docker.\nemscripten_docker_build() {\n  docker container run --rm \\\n    --volume $PWD:/code \\\n    --workdir /code \\\n    emscripten/emsdk:latest \\\n    emcc $CC_FLAGS -s WASM=1 -I. -o $OUT_WASM $IN_FILES\n  # Did compilation work?\n  if [ $? -ne 0 ]; then\n      echo \"Compiling ${IN_FILES} (using docker): FAILED\"\n    exit 1\n  fi\n  echo \"Compiling ${IN_FILES} (using docker): PASSED\"\n  rm -f $OUT_WASM\n}\n\n# Try Emscripten build using emcc or docker.\ntry_emscripten_build() {\n  which emcc > /dev/null\n  if [ $? -eq 0 ]; then\n    emscripten_emcc_build\n    return $?\n  fi\n\n  which docker > /dev/null\n  if [ $? -eq 0 ]; then\n    emscripten_docker_build\n    return $?\n  fi\n\n  echo \"(Skipping Emscripten test)\"\n}\n\n# Amalgamate the sources\n./create_single_file_decoder.sh\n# Did combining work?\nif [ $? -ne 0 ]; then\n  echo \"Single file decoder creation script: FAILED\"\n  exit 1\nfi\necho \"Single file decoder creation script: PASSED\"\n\n# Compile the generated output\ncc -Wall -Wextra -Wshadow -Werror -Os -g0 -o $OUT_FILE examples/simple.c\n# Did compilation work?\nif [ $? -ne 0 ]; then\n  echo \"Compiling simple.c: FAILED\"\n  exit 1\nfi\necho \"Compiling simple.c: PASSED\"\n\n# Run then delete the compiled output\n./$OUT_FILE\nretVal=$?\nrm -f $OUT_FILE\n# Did the test work?\nif [ $retVal -ne 0 ]; then\n  echo \"Running simple.c: FAILED\"\n  exit 1\nfi\necho \"Running simple.c: PASSED\"\n\n# Try Emscripten build if emcc or docker command is available.\ntry_emscripten_build\n\nexit 0\n", "num_lines": 92}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Where to find the sources (only used to copy zstd.h)\nZSTD_SRC_ROOT=\"../../lib\"\n\n# Temporary compiled binary\nOUT_FILE=\"tempbin\"\n\n# Optional temporary compiled WebAssembly\nOUT_WASM=\"temp.wasm\"\n\n# Source files to compile using Emscripten.\nIN_FILES=\"zstd.c examples/roundtrip.c\"\n\n# Emscripten build using emcc.\nemscripten_emcc_build() {\n  # Compile the same example as above\n  CC_FLAGS=\"-Wall -Wextra -Wshadow -Werror -Os -g0 -flto\"\n  emcc $CC_FLAGS -s WASM=1 -I. -o $OUT_WASM $IN_FILES\n  # Did compilation work?\n  if [ $? -ne 0 ]; then\n    echo \"Compiling ${IN_FILES}: FAILED\"\n    exit 1\n  fi\n  echo \"Compiling ${IN_FILES}: PASSED\"\n  rm -f $OUT_WASM\n}\n\n# Emscripten build using docker.\nemscripten_docker_build() {\n  docker container run --rm \\\n    --volume $PWD:/code \\\n    --workdir /code \\\n    emscripten/emsdk:latest \\\n    emcc $CC_FLAGS -s WASM=1 -I. -o $OUT_WASM $IN_FILES\n  # Did compilation work?\n  if [ $? -ne 0 ]; then\n      echo \"Compiling ${IN_FILES} (using docker): FAILED\"\n    exit 1\n  fi\n  echo \"Compiling ${IN_FILES} (using docker): PASSED\"\n  rm -f $OUT_WASM\n}\n\n# Try Emscripten build using emcc or docker.\ntry_emscripten_build() {\n  which emcc > /dev/null\n  if [ $? -eq 0 ]; then\n    emscripten_emcc_build\n    return $?\n  fi\n\n  which docker > /dev/null\n  if [ $? -eq 0 ]; then\n    emscripten_docker_build\n    return $?\n  fi\n\n  echo \"(Skipping Emscripten test)\"\n}\n\n# Amalgamate the sources\n./create_single_file_library.sh\n# Did combining work?\nif [ $? -ne 0 ]; then\n  echo \"Single file library creation script: FAILED\"\n  exit 1\nfi\necho \"Single file library creation script: PASSED\"\n\n# Copy the header to here (for the tests)\ncp \"$ZSTD_SRC_ROOT/zstd.h\" examples/zstd.h\n\n# Compile the generated output\ncc -Wall -Wextra -Werror -Wshadow -pthread -I. -Os -g0 -o $OUT_FILE zstd.c examples/roundtrip.c\n# Did compilation work?\nif [ $? -ne 0 ]; then\n  echo \"Compiling roundtrip.c: FAILED\"\n  exit 1\nfi\necho \"Compiling roundtrip.c: PASSED\"\n\n# Run then delete the compiled output\n./$OUT_FILE\nretVal=$?\nrm -f $OUT_FILE\n# Did the test work?\nif [ $retVal -ne 0 ]; then\n  echo \"Running roundtrip.c: FAILED\"\n  exit 1\nfi\necho \"Running roundtrip.c: PASSED\"\n\n# Try Emscripten build if emcc or docker command is available.\ntry_emscripten_build\n\nexit 0\n", "num_lines": 98}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -e\n\n# Tool to bundle multiple C/C++ source files, inlining any includes.\n# \n# TODO: ROOTS, FOUND, etc., as arrays (since they fail on paths with spaces)\n# \n# Author: Carl Woffenden, Numfum GmbH (this script is released under a CC0 license/Public Domain)\n\n# Common file roots\nROOTS=\".\"\n\n# -x option excluded includes\nXINCS=\"\"\n\n# -k option includes to keep as include directives\nKINCS=\"\"\n\n# Files previously visited\nFOUND=\"\"\n\n# Optional destination file (empty string to write to stdout)\nDESTN=\"\"\n\n# Whether the \"#pragma once\" directives should be written to the output\nPONCE=0\n\n# Prints the script usage then exits\nusage() {\n  echo \"Usage: $0 [-r <path>] [-x <header>] [-k <header>] [-o <outfile>] infile\"\n  echo \"  -r file root search path\"\n  echo \"  -x file to completely exclude from inlining\"\n  echo \"  -k file to exclude from inlining but keep the include directive\"\n  echo \"  -p keep any '#pragma once' directives (removed by default)\"\n  echo \"  -o output file (otherwise stdout)\"\n  echo \"Example: $0 -r ../my/path - r ../other/path -o out.c in.c\"\n  exit 1\n}\n\n# Tests that the grep implementation works as expected (older OSX grep fails)\ntest_deps() {\n  if ! echo '#include \"foo\"' | grep -Eq '^\\s*#\\s*include\\s*\".+\"'; then\n    echo \"Aborting: the grep implementation fails to parse include lines\"\n    exit 1\n  fi\n  if ! echo '\"foo.h\"' | sed -E 's/\"([^\"]+)\"/\\1/' | grep -Eq '^foo\\.h$'; then\n    echo \"Aborting: sed is unavailable or non-functional\"\n    exit 1\n  fi\n}\n\n# Test if glob pattern $1 matches subject $2 (see fnmatch(3))\nfnmatch() {\n  case \"$2\" in\n  $1)\n    return 0\n    ;;\n  esac\n  return 1\n}\n\n# Test if line $1 is local include directive\nis_include_line() {\n  fnmatch \"*#*include*\" \"$1\" || return 1\n  printf \"%s\\n\" \"$1\" | grep -Eq '^\\s*#\\s*include\\s*\".+\"'\n}\n\n# Test if line $1 is pragma once directive\nis_pragma_once_line() {\n  fnmatch \"*#*pragma*once*\" \"$1\" || return 1\n  printf \"%s\\n\" \"$1\" | grep -Eq '^\\s*#\\s*pragma\\s*once\\s*'\n}\n\n# Tests if list $1 has item $2 (returning zero on a match)\n# (originally used grep -Eq \"(^|\\s*)$2(\\$|\\s*))\nreadonly list_FS=\"$IFS\"\nlist_has_item() {\n  # Re: escaping glob pattern special characters in item string:\n  #\n  # bash (tested 3.2.57, 5.1.4), dash (tested 0.5.10.2), NetBSD /bin/sh\n  # (tested 8.2), and Solaris /bin/sh (tested 11.4) require escaping\n  # backslashes in a bracket expression despite POSIX specifying that\n  # backslash loses significance in a bracket expression.\n  #\n  # Conversely, neither FreeBSD /bin/sh (tested 12.2) nor OpenBSD /bin/sh\n  # (tested 7.1) obey backslash-escaping in case statement patterns even\n  # outside bracket expressions, so escape special characters using bracket\n  # expressions.\n  #\n  # Solaris /bin/sh (tested 11.4) requires vertical bar (|) to be escaped.\n  #\n  # All accommodations should behave as expected under strict POSIX semantics.\n  if fnmatch \"*[\\\\*?[|]*\" \"$2\"; then\n    set -- \"$1\" \"$(printf '%s\\n' \"$2\" | sed -e 's/[*?[|]/[&]/g; s/[\\]/[\\\\&]/g')\"\n  fi\n  for item_P in \"*[$list_FS]$2[$list_FS]*\" \"*[$list_FS]$2\" \"$2[$list_FS]*\" \"$2\"; do\n    fnmatch \"${item_P}\" \"$1\" && return 0\n  done\n  return 1\n}\n\n# Adds a new line with the supplied arguments to $DESTN (or stdout)\nwrite_line() {\n  if [ -n \"$DESTN\" ]; then\n    printf '%s\\n' \"$@\" >> \"$DESTN\"\n  else\n    printf '%s\\n' \"$@\"\n  fi\n}\n\nlog_line() {\n  echo $@ >&2\n}\n\n# Find this file!\nresolve_include() {\n  local srcdir=$1\n  local inc=$2\n  for root in $srcdir $ROOTS; do\n    if [ -f \"$root/$inc\" ]; then\n      # Try to reduce the file path into a canonical form (so that multiple)\n      # includes of the same file are successfully deduplicated, even if they\n      # are expressed differently.\n      local relpath=\"$(realpath --relative-to . \"$root/$inc\" 2>/dev/null)\"\n      if [ \"$relpath\" != \"\" ]; then # not all realpaths support --relative-to\n        echo \"$relpath\"\n        return 0\n      fi\n      local relpath=\"$(realpath \"$root/$inc\" 2>/dev/null)\"\n      if [ \"$relpath\" != \"\" ]; then # not all distros have realpath...\n        echo \"$relpath\"\n        return 0\n      fi\n      # Fallback on Python to reduce the path if the above fails.\n      local relpath=$(python -c \"import os,sys; print os.path.relpath(sys.argv[1])\" \"$root/$inc\" 2>/dev/null)\n      if [ \"$relpath\" != \"\" ]; then # not all distros have realpath...\n        echo \"$relpath\"\n        return 0\n      fi\n      # Worst case, fall back to just the root + relative include path. The\n      # problem with this is that it is possible to emit multiple different\n      # resolved paths to the same file, depending on exactly how its included.\n      # Since the main loop below keeps a list of the resolved paths it's\n      # already included, in order to avoid repeated includes, this failure to\n      # produce a canonical/reduced path can lead to multiple inclusions of the\n      # same file. But it seems like the resulting single file library still\n      # works (hurray include guards!), so I guess it's ok.\n      echo \"$root/$inc\"\n      return 0\n    fi\n  done\n  return 1\n}\n\n# Adds the contents of $1 with any of its includes inlined\nadd_file() {\n  local file=$1\n  if [ -n \"$file\" ]; then\n    log_line \"Processing: $file\"\n    # Get directory of the current so we can resolve relative includes\n    local srcdir=\"$(dirname \"$file\")\"\n    # Read the file\n    local line=\n    while IFS= read -r line; do\n      if is_include_line \"$line\"; then\n        # We have an include directive so strip the (first) file\n        local inc=$(echo \"$line\" | grep -Eo '\".*\"' | sed -E 's/\"([^\"]+)\"/\\1/' | head -1)\n        local res_inc=\"$(resolve_include \"$srcdir\" \"$inc\")\"\n        if list_has_item \"$XINCS\" \"$inc\"; then\n          # The file was excluded so error if the source attempts to use it\n          write_line \"#error Using excluded file: $inc (re-amalgamate source to fix)\"\n          log_line \"Excluding: $inc\"\n        else\n          if ! list_has_item \"$FOUND\" \"$res_inc\"; then\n            # The file was not previously encountered\n            FOUND=\"$FOUND $res_inc\"\n            if list_has_item \"$KINCS\" \"$inc\"; then\n              # But the include was flagged to keep as included\n              write_line \"/**** *NOT* inlining $inc ****/\"\n              write_line \"$line\"\n              log_line \"Not Inlining: $inc\"\n            else\n              # The file was neither excluded nor seen before so inline it\n              write_line \"/**** start inlining $inc ****/\"\n              add_file \"$res_inc\"\n              write_line \"/**** ended inlining $inc ****/\"\n            fi\n          else\n            write_line \"/**** skipping file: $inc ****/\"\n          fi\n        fi\n      else\n        # Skip any 'pragma once' directives, otherwise write the source line\n        local write=$PONCE\n        if [ $write -eq 0 ]; then\n          if ! is_pragma_once_line \"$line\"; then\n            write=1\n          fi\n        fi\n        if [ $write -ne 0 ]; then\n          write_line \"$line\"\n        fi\n      fi\n    done < \"$file\"\n  else\n    write_line \"#error Unable to find \\\"$1\\\"\"\n    log_line \"Error: Unable to find: \\\"$1\\\"\"\n  fi\n}\n\nwhile getopts \":r:x:k:po:\" opts; do\n  case $opts in\n  r)\n    ROOTS=\"$ROOTS $OPTARG\"\n    ;;\n  x)\n    XINCS=\"$XINCS $OPTARG\"\n    ;;\n  k)\n    KINCS=\"$KINCS $OPTARG\"\n    ;;\n  p)\n    PONCE=1\n    ;;\n  o)\n    DESTN=\"$OPTARG\"\n    ;;\n  *)\n    usage\n    ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [ -n \"$1\" ]; then\n  if [ -f \"$1\" ]; then\n    if [ -n \"$DESTN\" ]; then\n      printf \"\" > \"$DESTN\"\n    fi\n    test_deps\n    log_line \"Processing using the slower shell script; this might take a while\"\n    add_file \"$1\"\n  else\n    echo \"Input file not found: \\\"$1\\\"\"\n    exit 1\n  fi\nelse\n  usage\nfi\nexit 0\n", "num_lines": 250}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Where to find the sources\nZSTD_SRC_ROOT=\"../../lib\"\n\n# Amalgamate the sources\necho \"Amalgamating files...\"\n# Using the faster Python script if we have 3.8 or higher\nif python3 -c 'import sys; assert sys.version_info >= (3,8)' 2>/dev/null; then\n  ./combine.py -r \"$ZSTD_SRC_ROOT\" -x legacy/zstd_legacy.h -o zstddeclib.c zstddeclib-in.c\nelse\n  ./combine.sh -r \"$ZSTD_SRC_ROOT\" -x legacy/zstd_legacy.h -o zstddeclib.c zstddeclib-in.c\nfi\n# Did combining work?\nif [ $? -ne 0 ]; then\n  echo \"Combine script: FAILED\"\n  exit 1\nfi\necho \"Combine script: PASSED\"\n", "num_lines": 20}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Where to find the sources\nZSTD_SRC_ROOT=\"../../lib\"\n\n# Amalgamate the sources\necho \"Amalgamating files...\"\n# Using the faster Python script if we have 3.8 or higher\nif python3 -c 'import sys; assert sys.version_info >= (3,8)' 2>/dev/null; then\n  ./combine.py -r \"$ZSTD_SRC_ROOT\" -x legacy/zstd_legacy.h -o zstd.c zstd-in.c\nelse\n  ./combine.sh -r \"$ZSTD_SRC_ROOT\" -x legacy/zstd_legacy.h -o zstd.c zstd-in.c\nfi\n# Did combining work?\nif [ $? -ne 0 ]; then\n  echo \"Combine script: FAILED\"\n  exit 1\nfi\necho \"Combine script: PASSED\"\n", "num_lines": 20}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nLIBVER_MAJOR_SCRIPT=`sed -n '/define ZSTD_VERSION_MAJOR/s/.*[[:blank:]]\\([0-9][0-9]*\\).*/\\1/p' < ../../lib/zstd.h`\nLIBVER_MINOR_SCRIPT=`sed -n '/define ZSTD_VERSION_MINOR/s/.*[[:blank:]]\\([0-9][0-9]*\\).*/\\1/p' < ../../lib/zstd.h`\nLIBVER_PATCH_SCRIPT=`sed -n '/define ZSTD_VERSION_RELEASE/s/.*[[:blank:]]\\([0-9][0-9]*\\).*/\\1/p' < ../../lib/zstd.h`\nLIBVER_SCRIPT=$LIBVER_MAJOR_SCRIPT.$LIBVER_MINOR_SCRIPT.$LIBVER_PATCH_SCRIPT\n\necho ZSTD_VERSION=$LIBVER_SCRIPT\n./gen_html $LIBVER_SCRIPT ../../lib/zstd.h ./zstd_manual.html\n", "num_lines": 10}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "# !/bin/sh\nset -e\n\n# Benchmarks run on a Ubuntu 14.04 VM with 2 cores and 4 GiB of RAM.\n# The VM is running on a Macbook Pro with a 3.1 GHz Intel Core i7 processor and\n# 16 GB of RAM and an SSD.\n\n# silesia is a directory that can be downloaded from\n# http://mattmahoney.net/dc/silesia.html\n# ls -l silesia/\n# total 203M\n# -rwxr-xr-x 1 terrelln 9.8M Apr 12  2002 dickens\n# -rwxr-xr-x 1 terrelln  49M May 31  2002 mozilla\n# -rwxr-xr-x 1 terrelln 9.6M Mar 20  2003 mr\n# -rwxr-xr-x 1 terrelln  32M Apr  2  2002 nci\n# -rwxr-xr-x 1 terrelln 5.9M Jul  4  2002 ooffice\n# -rwxr-xr-x 1 terrelln 9.7M Apr 11  2002 osdb\n# -rwxr-xr-x 1 terrelln 6.4M Apr  2  2002 reymont\n# -rwxr-xr-x 1 terrelln  21M Mar 25  2002 samba\n# -rwxr-xr-x 1 terrelln 7.0M Mar 24  2002 sao\n# -rwxr-xr-x 1 terrelln  40M Mar 25  2002 webster\n# -rwxr-xr-x 1 terrelln 8.1M Apr  4  2002 x-ray\n# -rwxr-xr-x 1 terrelln 5.1M Nov 30  2000 xml\n\n# $HOME is on a ext4 filesystem\nBENCHMARK_DIR=\"$HOME/silesia/\"\nN=10\n\n# Normalize the environment\nsudo umount /mnt/btrfs 2> /dev/null > /dev/null || true\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\nsudo rm -rf /mnt/btrfs/*\nsync\nsudo umount /mnt/btrfs\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\n\n# Run the benchmark\necho \"Compression\"\ntime sh -c \"for i in \\$(seq $N); do sudo cp -r $BENCHMARK_DIR /mnt/btrfs/\\$i; done; sync\"\n\necho \"Approximate compression ratio\"\nprintf \"%d / %d\\n\"                                                             \\\n  $(df /mnt/btrfs --output=used -B 1 | tail -n 1)                              \\\n  $(sudo du /mnt/btrfs -b -d 0 | tr '\\t' '\\n' | head -n 1);\n\n# Unmount and remount to avoid any caching\nsudo umount /mnt/btrfs\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\n\necho \"Decompression\"\ntime sudo tar -c /mnt/btrfs 2> /dev/null | wc -c > /dev/null\n\nsudo rm -rf /mnt/btrfs/*\nsudo umount /mnt/btrfs\n\n# Run for each of -o compress-force={none, lzo, zlib, zstd} 5 times and take the\n# min time and ratio.\n# Ran zstd with compression levels {1, 3, 6, 9, 12, 15}.\n# Original size: 2119415342 B (using du /mnt/btrfs)\n\n# none\n# compress: 4.205 s\n# decompress: 3.090 s\n# ratio: 0.99\n\n# lzo\n# compress: 5.328 s\n# decompress: 4.793 s\n# ratio: 1.66\n\n# zlib\n# compress: 32.588 s\n# decompress: 8.791 s\n# ratio : 2.58\n\n# zstd 1\n# compress: 8.147 s\n# decompress: 5.527 s\n# ratio : 2.57\n\n# zstd 3\n# compress: 12.207 s\n# decompress: 5.195 s\n# ratio : 2.71\n\n# zstd 6\n# compress: 30.253 s\n# decompress: 5.324 s\n# ratio : 2.87\n\n# zstd 9\n# compress: 49.659 s\n# decompress: 5.220 s\n# ratio : 2.92\n\n# zstd 12\n# compress: 99.245 s\n# decompress: 5.193 s\n# ratio : 2.93\n\n# zstd 15\n# compress: 196.997 s\n# decompress: 5.992 s\n# ratio : 3.01\n", "num_lines": 105}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "# !/bin/sh\nset -e\n\n# Benchmarks run on a Ubuntu 14.04 VM with 2 cores and 4 GiB of RAM.\n# The VM is running on a Macbook Pro with a 3.1 GHz Intel Core i7 processor and\n# 16 GB of RAM and an SSD.\n\n# silesia is a directory that can be downloaded from\n# http://mattmahoney.net/dc/silesia.html\n# ls -l silesia/\n# total 203M\n# -rwxr-xr-x 1 terrelln 9.8M Apr 12  2002 dickens\n# -rwxr-xr-x 1 terrelln  49M May 31  2002 mozilla\n# -rwxr-xr-x 1 terrelln 9.6M Mar 20  2003 mr\n# -rwxr-xr-x 1 terrelln  32M Apr  2  2002 nci\n# -rwxr-xr-x 1 terrelln 5.9M Jul  4  2002 ooffice\n# -rwxr-xr-x 1 terrelln 9.7M Apr 11  2002 osdb\n# -rwxr-xr-x 1 terrelln 6.4M Apr  2  2002 reymont\n# -rwxr-xr-x 1 terrelln  21M Mar 25  2002 samba\n# -rwxr-xr-x 1 terrelln 7.0M Mar 24  2002 sao\n# -rwxr-xr-x 1 terrelln  40M Mar 25  2002 webster\n# -rwxr-xr-x 1 terrelln 8.1M Apr  4  2002 x-ray\n# -rwxr-xr-x 1 terrelln 5.1M Nov 30  2000 xml\n\n# $HOME is on a ext4 filesystem\nBENCHMARK_FILE=\"linux-4.11.6.tar\"\nBENCHMARK_DIR=\"$HOME/$BENCHMARK_FILE\"\n\n# Normalize the environment\nsudo umount /mnt/btrfs 2> /dev/null > /dev/null || true\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\nsudo rm -rf /mnt/btrfs/*\nsync\nsudo umount /mnt/btrfs\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\n\n# Run the benchmark\necho \"Copy\"\ntime sh -c \"sudo cp -r $BENCHMARK_DIR /mnt/btrfs/$BENCHMARK_FILE && sync\"\n\necho \"Approximate tarred compression ratio\"\nprintf \"%d / %d\\n\"                                                             \\\n  $(df /mnt/btrfs --output=used -B 1 | tail -n 1)                              \\\n  $(sudo du /mnt/btrfs -b -d 0 | tr '\\t' '\\n' | head -n 1);\n\n# Unmount and remount to avoid any caching\nsudo umount /mnt/btrfs\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\n\necho \"Extract\"\ntime sh -c \"sudo tar -C /mnt/btrfs -xf /mnt/btrfs/$BENCHMARK_FILE && sync\"\n\n# Remove the tarball, leaving only the extracted data\nsudo rm /mnt/btrfs/$BENCHMARK_FILE\n# Unmount and remount to avoid any caching\nsudo umount /mnt/btrfs\nsudo mount -t btrfs $@ /dev/sda3 /mnt/btrfs\n\necho \"Approximate extracted compression ratio\"\nprintf \"%d / %d\\n\"                                                             \\\n  $(df /mnt/btrfs --output=used -B 1 | tail -n 1)                              \\\n  $(sudo du /mnt/btrfs -b -d 0 | tr '\\t' '\\n' | head -n 1);\n\necho \"Read\"\ntime sudo tar -c /mnt/btrfs 2> /dev/null | wc -c > /dev/null\n\nsudo rm -rf /mnt/btrfs/*\nsudo umount /mnt/btrfs\n\n# Run for each of -o compress-force={none, lzo, zlib, zstd} 5 times and take the\n# min time and ratio.\n\n# none\n# copy: 0.981 s\n# extract: 5.501 s\n# read: 8.807 s\n# tarball ratio: 0.97\n# extracted ratio: 0.78\n\n# lzo\n# copy: 1.631 s\n# extract: 8.458 s\n# read: 8.585 s\n# tarball ratio: 2.06\n# extracted ratio: 1.38\n\n# zlib\n# copy: 7.750 s\n# extract: 21.544 s\n# read: 11.744 s\n# tarball ratio : 3.40\n# extracted ratio: 1.86\n\n# zstd 1\n# copy: 2.579 s\n# extract: 11.479 s\n# read: 9.389 s\n# tarball ratio : 3.57\n# extracted ratio: 1.85\n", "num_lines": 100}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "# !/bin/sh\nset -e\n\n# Benchmarks run on a Ubuntu 14.04 VM with 2 cores and 4 GiB of RAM.\n# The VM is running on a Macbook Pro with a 3.1 GHz Intel Core i7 processor and\n# 16 GB of RAM and an SSD.\n\n# $BENCHMARK_DIR is generated with the following commands, from the Ubuntu image\n# ubuntu-16.10-desktop-amd64.iso.\n# > mkdir mnt\n# > sudo mount -o loop ubuntu-16.10-desktop-amd64.iso mnt\n# > cp mnt/casper/filesystem.squashfs .\n# > sudo unsquashfs filesystem.squashfs\n\n# $HOME is on a ext4 filesystem\nBENCHMARK_DIR=\"$HOME/squashfs-root/\"\nBENCHMARK_FS=\"$HOME/filesystem.squashfs\"\n\n# Normalize the environment\nsudo rm -f $BENCHMARK_FS 2> /dev/null > /dev/null || true\nsudo umount /mnt/squashfs 2> /dev/null > /dev/null || true\n\n# Run the benchmark\necho \"Compression\"\necho \"sudo mksquashfs $BENCHMARK_DIR $BENCHMARK_FS $@\"\ntime sudo mksquashfs $BENCHMARK_DIR $BENCHMARK_FS $@ 2> /dev/null > /dev/null\n\necho \"Approximate compression ratio\"\nprintf \"%d / %d\\n\"                                                             \\\n  $(sudo du -sx --block-size=1 $BENCHMARK_DIR | cut -f1)                       \\\n  $(sudo du -sx --block-size=1 $BENCHMARK_FS  | cut -f1);\n\n# Mount the filesystem\nsudo mount -t squashfs $BENCHMARK_FS /mnt/squashfs\n\necho \"Decompression\"\ntime sudo tar -c /mnt/squashfs 2> /dev/null | wc -c > /dev/null\n\nsudo umount /mnt/squashfs\n", "num_lines": 40}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n\nset -e\n\nSCRIPT_DIR=$(cd \"$(dirname \"$0\")\" && pwd)\nINCLUDE_DIR=\"$SCRIPT_DIR/../linux/include\"\nLIB_DIR=\"$SCRIPT_DIR/../linux/lib\"\n\n\nprint() {\n    printf '%b' \"${*}\"\n}\n\nprintln() {\n    printf '%b\\n' \"${*}\"\n}\n\ndie() {\n    println \"$@\" 1>&2\n    exit 1\n}\n\ntest_not_present() {\n    print \"Testing that '$1' is not present... \"\n    grep -r $1 \"$INCLUDE_DIR\" \"$LIB_DIR\" && die \"Fail!\"\n    println \"Okay\"\n}\n\nprintln \"This test checks that the macro removal process worked as expected\"\nprintln \"If this test fails, then freestanding.py wasn't able to remove one of these\"\nprintln \"macros from the source code completely. You'll either need to rewrite the check\"\nprintln \"or improve freestanding.py.\"\nprintln \"\"\n\ntest_not_present \"ZSTD_NO_INTRINSICS\"\ntest_not_present \"ZSTD_NO_UNUSED_FUNCTIONS\"\ntest_not_present \"ZSTD_LEGACY_SUPPORT\"\ntest_not_present \"STATIC_BMI2\"\ntest_not_present \"ZSTD_DLL_EXPORT\"\ntest_not_present \"ZSTD_DLL_IMPORT\"\ntest_not_present \"__ICCARM__\"\ntest_not_present \"_MSC_VER\"\ntest_not_present \"_WIN32\"\ntest_not_present \"__linux__\"\n", "num_lines": 45}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nECHO=echo\nRM=\"rm -f\"\nGREP=\"grep\"\nINTOVOID=\"/dev/null\"\n\ndie() {\n    $ECHO \"$@\" 1>&2\n    exit 1\n}\n\nisPresent() {\n    $GREP $@ tmplog || die \"$@\" \"should be present\"\n}\n\nmustBeAbsent() {\n    $GREP $@ tmplog && die \"$@ should not be there !!\"\n    $ECHO \"$@ correctly not present\"  # for some reason, this $ECHO must exist, otherwise mustBeAbsent() always fails (??)\n}\n\n# default compilation : all features enabled - no zbuff\n$ECHO \"testing default library compilation\"\nCFLAGS= make -C $DIR/../lib libzstd libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nisPresent \"zstd_decompress.o\"\nisPresent \"zdict.o\"\nisPresent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM tmplog\n\n# Check that the exec-stack bit isn't set\nreadelf -lW $DIR/../lib/libzstd.so | $GREP \"GNU_STACK\" > tmplog\nmustBeAbsent \"RWE\"\n$RM $DIR/../lib/libzstd.a $DIR/../lib/libzstd.so* tmplog\n\n# compression disabled => also disable zdict\n$ECHO \"testing with compression disabled\"\nZSTD_LIB_COMPRESSION=0 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nmustBeAbsent \"zstd_compress.o\"\nisPresent \"zstd_decompress.o\"\nmustBeAbsent \"zdict.o\"\nisPresent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n\n# decompression disabled => also disable legacy\n$ECHO \"testing with decompression disabled\"\nZSTD_LIB_DECOMPRESSION=0 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nmustBeAbsent \"zstd_decompress.o\"\nisPresent \"zdict.o\"\nmustBeAbsent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n\n# deprecated function disabled => only remove zbuff\n$ECHO \"testing with deprecated functions disabled\"\nZSTD_LIB_DEPRECATED=0 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nisPresent \"zstd_decompress.o\"\nisPresent \"zdict.o\"\nisPresent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n\n# deprecated function enabled => zbuff present\n$ECHO \"testing with deprecated functions enabled\"\nZSTD_LIB_DEPRECATED=1 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nisPresent \"zstd_decompress.o\"\nisPresent \"zdict.o\"\nisPresent \"zstd_v07.o\"\nisPresent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n\n# dictionary builder disabled => only remove zdict\n$ECHO \"testing with dictionary builder disabled\"\nZSTD_LIB_DICTBUILDER=0 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nisPresent \"zstd_decompress.o\"\nmustBeAbsent \"zdict.o\"\nisPresent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n\n# both decompression and dictionary builder disabled => only compression remains\n$ECHO \"testing with both decompression and dictionary builder disabled (only compression remains)\"\nZSTD_LIB_DECOMPRESSION=0 ZSTD_LIB_DICTBUILDER=0 CFLAGS= make -C $DIR/../lib libzstd.a > $INTOVOID\nnm $DIR/../lib/libzstd.a | $GREP \"\\.o\" > tmplog\nisPresent \"zstd_compress.o\"\nmustBeAbsent \"zstd_decompress.o\"\nmustBeAbsent \"zdict.o\"\nmustBeAbsent \"zstd_v07.o\"\nmustBeAbsent \"zbuff_compress.o\"\n$RM $DIR/../lib/libzstd.a tmplog\n", "num_lines": 105}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nunset ZSTD_CLEVEL\nunset ZSTD_NBTHREADS\n\n\ndie() {\n    println \"$@\" 1>&2\n    exit 1\n}\n\ndatagen() {\n    \"$DATAGEN_BIN\" \"$@\"\n}\n\nzstd() {\n    if [ -z \"$EXEC_PREFIX\" ]; then\n        \"$ZSTD_BIN\" \"$@\"\n    else\n        \"$EXEC_PREFIX\" \"$ZSTD_BIN\" \"$@\"\n    fi\n}\n\nsudoZstd() {\n    if [ -z \"$EXEC_PREFIX\" ]; then\n        sudo \"$ZSTD_BIN\" \"$@\"\n    else\n        sudo \"$EXEC_PREFIX\" \"$ZSTD_BIN\" \"$@\"\n    fi\n}\n\nroundTripTest() {\n    if [ -n \"$3\" ]; then\n        cLevel=\"$3\"\n        proba=\"$2\"\n    else\n        cLevel=\"$2\"\n        proba=\"\"\n    fi\n    if [ -n \"$4\" ]; then\n        dLevel=\"$4\"\n    else\n        dLevel=\"$cLevel\"\n    fi\n\n    rm -f tmp1 tmp2\n    println \"roundTripTest: datagen $1 $proba | zstd -v$cLevel | zstd -d$dLevel\"\n    datagen $1 $proba | $MD5SUM > tmp1\n    datagen $1 $proba | zstd --ultra -v$cLevel | zstd -d$dLevel  | $MD5SUM > tmp2\n    $DIFF -q tmp1 tmp2\n}\n\nfileRoundTripTest() {\n    if [ -n \"$3\" ]; then\n        local_c=\"$3\"\n        local_p=\"$2\"\n    else\n        local_c=\"$2\"\n        local_p=\"\"\n    fi\n    if [ -n \"$4\" ]; then\n        local_d=\"$4\"\n    else\n        local_d=\"$local_c\"\n    fi\n\n    rm -f tmp.zst tmp.md5.1 tmp.md5.2\n    println \"fileRoundTripTest: datagen $1 $local_p > tmp && zstd -v$local_c -c tmp | zstd -d$local_d\"\n    datagen $1 $local_p > tmp\n    < tmp $MD5SUM > tmp.md5.1\n    zstd --ultra -v$local_c -c tmp | zstd -d$local_d | $MD5SUM > tmp.md5.2\n    $DIFF -q tmp.md5.1 tmp.md5.2\n}\n\ntruncateLastByte() {\n    dd bs=1 count=$(($(wc -c < \"$1\") - 1)) if=\"$1\"\n}\n\nprintln() {\n    printf '%b\\n' \"${*}\"\n}\n\nif [ -z \"${size}\" ]; then\n    size=\nelse\n    size=${size}\nfi\n\nSCRIPT_DIR=$(cd \"$(dirname \"$0\")\" && pwd)\nPRGDIR=\"$SCRIPT_DIR/../programs\"\nTESTDIR=\"$SCRIPT_DIR/../tests\"\nUNAME=$(uname)\n\ndetectedTerminal=false\nif [ -t 0 ] && [ -t 1 ]\nthen\n    detectedTerminal=true\nfi\nisTerminal=${isTerminal:-$detectedTerminal}\n\nisWindows=false\nINTOVOID=\"/dev/null\"\ncase \"$UNAME\" in\n  GNU) DEVDEVICE=\"/dev/random\" ;;\n  *) DEVDEVICE=\"/dev/zero\" ;;\nesac\ncase \"$OS\" in\n  Windows*)\n    isWindows=true\n    INTOVOID=\"NUL\"\n    DEVDEVICE=\"NUL\"\n    ;;\nesac\n\ncase \"$UNAME\" in\n  Darwin) MD5SUM=\"md5 -r\" ;;\n  FreeBSD) MD5SUM=\"gmd5sum\" ;;\n  NetBSD) MD5SUM=\"md5 -n\" ;;\n  OpenBSD) MD5SUM=\"md5\" ;;\n  *) MD5SUM=\"md5sum\" ;;\nesac\n\nMTIME=\"stat -c %Y\"\ncase \"$UNAME\" in\n    Darwin | FreeBSD | OpenBSD | NetBSD) MTIME=\"stat -f %m\" ;;\nesac\n\nassertSameMTime() {\n    MT1=$($MTIME \"$1\")\n    MT2=$($MTIME \"$2\")\n    echo MTIME $MT1 $MT2\n    [ \"$MT1\" = \"$MT2\" ] || die \"mtime on $1 doesn't match mtime on $2 ($MT1 != $MT2)\"\n}\n\nGET_PERMS=\"stat -c %a\"\ncase \"$UNAME\" in\n    Darwin | FreeBSD | OpenBSD | NetBSD) GET_PERMS=\"stat -f %Lp\" ;;\nesac\n\nassertFilePermissions() {\n    STAT1=$($GET_PERMS \"$1\")\n    STAT2=$2\n    [ \"$STAT1\" = \"$STAT2\" ] || die \"permissions on $1 don't match expected ($STAT1 != $STAT2)\"\n}\n\nassertSamePermissions() {\n    STAT1=$($GET_PERMS \"$1\")\n    STAT2=$($GET_PERMS \"$2\")\n    [ \"$STAT1\" = \"$STAT2\" ] || die \"permissions on $1 don't match those on $2 ($STAT1 != $STAT2)\"\n}\n\nDIFF=\"diff\"\ncase \"$UNAME\" in\n  SunOS) DIFF=\"gdiff\" ;;\nesac\n\n\n# check if ZSTD_BIN is defined. if not, use the default value\nif [ -z \"${ZSTD_BIN}\" ]; then\n  println \"\\nZSTD_BIN is not set. Using the default value...\"\n  ZSTD_BIN=\"$PRGDIR/zstd\"\nfi\n\n# check if DATAGEN_BIN is defined. if not, use the default value\nif [ -z \"${DATAGEN_BIN}\" ]; then\n  println \"\\nDATAGEN_BIN is not set. Using the default value...\"\n  DATAGEN_BIN=\"$TESTDIR/datagen\"\nfi\n\n# Why was this line here ? Generates a strange ZSTD_BIN when EXE_PREFIX is non empty\n# ZSTD_BIN=\"$EXE_PREFIX$ZSTD_BIN\"\n\n# assertions\n[ -n \"$ZSTD_BIN\" ] || die \"zstd not found at $ZSTD_BIN! \\n Please define ZSTD_BIN pointing to the zstd binary. You might also consider rebuilding zstd following the instructions in README.md\"\n[ -n \"$DATAGEN_BIN\" ] || die \"datagen not found at $DATAGEN_BIN! \\n Please define DATAGEN_BIN pointing to the datagen binary. You might also consider rebuilding zstd tests following the instructions in README.md. \"\nprintln \"\\nStarting playTests.sh isWindows=$isWindows EXE_PREFIX='$EXE_PREFIX' ZSTD_BIN='$ZSTD_BIN' DATAGEN_BIN='$DATAGEN_BIN'\"\n\nif echo hello | zstd -v -T2 2>&1 > $INTOVOID | grep -q 'multi-threading is disabled'\nthen\n    hasMT=\"\"\nelse\n    hasMT=\"true\"\nfi\n\n\nzstd -vvV\n\nprintln \"\\n===>  simple tests \"\n\ndatagen > tmp\nzstd -h\nzstd -H\nzstd -V\nprintln \"test : basic compression \"\nzstd -f tmp                      # trivial compression case, creates tmp.zst\nzstd -f -z tmp\nzstd -f -k tmp\nzstd -f -C tmp\nprintln \"test : basic decompression\"\nzstd -df tmp.zst                 # trivial decompression case (overwrites tmp)\nprintln \"test : too large compression level => auto-fix\"\nzstd -99 -f tmp  # too large compression level, automatic sized down\nzstd -5000000000 -f tmp && die \"too large numeric value : must fail\"\nprintln \"test : --fast aka negative compression levels\"\nzstd --fast -f tmp  # == -1\nzstd --fast=3 -f tmp  # == -3\nzstd --fast=200000 -f tmp  # too low compression level, automatic fixed\nzstd --fast=5000000000 -f tmp && die \"too large numeric value : must fail\"\nzstd -c --fast=0 tmp > $INTOVOID && die \"--fast must not accept value 0\"\nprintln \"test : too large numeric argument\"\nzstd --fast=9999999999 -f tmp  && die \"should have refused numeric value\"\nprintln \"test : set compression level with environment variable ZSTD_CLEVEL\"\n\nZSTD_CLEVEL=12  zstd -f tmp # positive compression level\nZSTD_CLEVEL=-12 zstd -f tmp # negative compression level\nZSTD_CLEVEL=+12 zstd -f tmp # valid: verbose '+' sign\nZSTD_CLEVEL=''  zstd -f tmp # empty env var, warn and revert to default setting\nZSTD_CLEVEL=-   zstd -f tmp # malformed env var, warn and revert to default setting\nZSTD_CLEVEL=a   zstd -f tmp # malformed env var, warn and revert to default setting\nZSTD_CLEVEL=+a  zstd -f tmp # malformed env var, warn and revert to default setting\nZSTD_CLEVEL=3a7 zstd -f tmp # malformed env var, warn and revert to default setting\nZSTD_CLEVEL=50000000000 zstd -f tmp # numeric value too large, warn and revert to default setting\nprintln \"test : override ZSTD_CLEVEL with command line option\"\nZSTD_CLEVEL=12  zstd --fast=3 -f tmp # overridden by command line option\n\n# temporary envvar changes in the above tests would actually persist in macos /bin/sh\nunset ZSTD_CLEVEL\n\n\nprintln \"test : compress to stdout\"\nzstd tmp -c > tmpCompressed\nzstd tmp --stdout > tmpCompressed       # long command format\nprintln \"test : compress to named file\"\nrm -f tmpCompressed\nzstd tmp -o tmpCompressed\ntest -f tmpCompressed   # file must be created\nprintln \"test : force write, correct order\"\nzstd tmp -fo tmpCompressed\nprintln \"test : forgotten argument\"\ncp tmp tmp2\nzstd tmp2 -fo && die \"-o must be followed by filename \"\nprintln \"test : implied stdout when input is stdin\"\nprintln bob | zstd | zstd -d\nif [ \"$isTerminal\" = true ]; then\nprintln \"test : compressed data to terminal\"\nprintln bob | zstd && die \"should have refused : compressed data to terminal\"\nprintln \"test : compressed data from terminal (a hang here is a test fail, zstd is wrongly waiting on data from terminal)\"\nzstd -d > $INTOVOID && die \"should have refused : compressed data from terminal\"\nfi\nprintln \"test : null-length file roundtrip\"\nprintln -n '' | zstd - --stdout | zstd -d --stdout\nprintln \"test : ensure small file doesn't add 3-bytes null block\"\ndatagen -g1 > tmp1\nzstd tmp1 -c | wc -c | grep \"14\"\nzstd < tmp1  | wc -c | grep \"14\"\nprintln \"test : decompress file with wrong suffix (must fail)\"\nzstd -d tmpCompressed && die \"wrong suffix error not detected!\"\nzstd -df tmp && die \"should have refused : wrong extension\"\nprintln \"test : decompress into stdout\"\nzstd -d tmpCompressed -c > tmpResult    # decompression using stdout\nzstd --decompress tmpCompressed -c > tmpResult\nzstd --decompress tmpCompressed --stdout > tmpResult\nprintln \"test : decompress from stdin into stdout\"\nzstd -dc   < tmp.zst > $INTOVOID   # combine decompression, stdin & stdout\nzstd -dc - < tmp.zst > $INTOVOID\nzstd -d    < tmp.zst > $INTOVOID   # implicit stdout when stdin is used\nzstd -d  - < tmp.zst > $INTOVOID\nprintln \"test : impose memory limitation (must fail)\"\ndatagen -g500K > tmplimit\nzstd -f tmplimit\nzstd -d -f tmplimit.zst -M2K -c > $INTOVOID && die \"decompression needs more memory than allowed\"\nzstd -d -f tmplimit.zst --memlimit=2K -c > $INTOVOID && die \"decompression needs more memory than allowed\"  # long command\nzstd -d -f tmplimit.zst --memory=2K -c > $INTOVOID && die \"decompression needs more memory than allowed\"  # long command\nzstd -d -f tmplimit.zst --memlimit-decompress=2K -c > $INTOVOID && die \"decompression needs more memory than allowed\"  # long command\nrm -f tmplimit tmplimit.zst\nprintln \"test : overwrite protection\"\nzstd -q tmp && die \"overwrite check failed!\"\nprintln \"test : force overwrite\"\nzstd -q -f tmp\nzstd -q --force tmp\nprintln \"test : overwrite readonly file\"\nrm -f tmpro tmpro.zst\nprintln foo > tmpro.zst\nprintln foo > tmpro\nchmod 400 tmpro.zst\nzstd -q tmpro && die \"should have refused to overwrite read-only file\"\nzstd -q -f tmpro\nprintln \"test: --no-progress flag\"\nzstd tmpro -c --no-progress | zstd -d -f -o \"$INTOVOID\" --no-progress\nzstd tmpro -cv --no-progress | zstd -dv -f -o \"$INTOVOID\" --no-progress\nprintln \"test: --progress flag\"\nzstd tmpro -c | zstd -d -f -o \"$INTOVOID\" --progress 2>&1 | grep -E \"[A-Za-z0-9._ ]+: [0-9]+ bytes\"\nzstd tmpro -c | zstd -d -f -q -o \"$INTOVOID\" --progress 2>&1 | grep -E \"[A-Za-z0-9._ ]+: [0-9]+ bytes\"\nzstd tmpro -c | zstd -d -f -v -o \"$INTOVOID\" 2>&1 | grep -E \"[A-Za-z0-9._ ]+: [0-9]+ bytes\"\nrm -f tmpro tmpro.zst\nprintln \"test: overwrite input file (must fail)\"\nzstd tmp -fo tmp && die \"zstd compression overwrote the input file\"\nzstd tmp.zst -dfo tmp.zst && die \"zstd decompression overwrote the input file\"\nprintln \"test: detect that input file does not exist\"\nzstd nothere && die \"zstd hasn't detected that input file does not exist\"\nprintln \"test: --[no-]compress-literals\"\nzstd tmp -c --no-compress-literals -1       | zstd -t\nzstd tmp -c --no-compress-literals --fast=1 | zstd -t\nzstd tmp -c --no-compress-literals -19      | zstd -t\nzstd tmp -c --compress-literals    -1       | zstd -t\nzstd tmp -c --compress-literals    --fast=1 | zstd -t\nzstd tmp -c --compress-literals    -19      | zstd -t\nzstd -b --fast=1 -i0e1 tmp --compress-literals\nzstd -b --fast=1 -i0e1 tmp --no-compress-literals\nprintln \"test: --no-check for decompression\"\nzstd -f tmp -o tmp_corrupt.zst --check\nzstd -f tmp -o tmp.zst --no-check\nprintf '\\xDE\\xAD\\xBE\\xEF' | dd of=tmp_corrupt.zst bs=1 seek=$(($(wc -c < \"tmp_corrupt.zst\") - 4)) count=4 conv=notrunc # corrupt checksum in tmp\nzstd -d -f tmp_corrupt.zst --no-check\nzstd -d -f tmp_corrupt.zst --check --no-check # final flag overrides\nzstd -d -f tmp.zst --no-check\n\nif [ \"$isWindows\" = false ] && [ \"$UNAME\" != \"AIX\" ]; then\n  if [ -n \"$(which readelf)\" ]; then\n    println \"test: check if binary has executable stack (#2963)\"\n    readelf -lW \"$ZSTD_BIN\" | grep 'GNU_STACK .* RW ' || die \"zstd binary has executable stack!\"\n  fi\nfi\n\nprintln \"\\n===>  --exclude-compressed flag\"\nrm -rf precompressedFilterTestDir\nmkdir -p precompressedFilterTestDir\ndatagen $size > precompressedFilterTestDir/input.5\ndatagen $size > precompressedFilterTestDir/input.6\nzstd --exclude-compressed --long --rm -r precompressedFilterTestDir\ndatagen $size > precompressedFilterTestDir/input.7\ndatagen $size > precompressedFilterTestDir/input.8\nzstd --exclude-compressed --long --rm -r precompressedFilterTestDir\ntest ! -f precompressedFilterTestDir/input.5.zst.zst\ntest ! -f precompressedFilterTestDir/input.6.zst.zst\nfile1timestamp=`$MTIME precompressedFilterTestDir/input.5.zst`\nfile2timestamp=`$MTIME precompressedFilterTestDir/input.7.zst`\nif [ $file2timestamp -ge $file1timestamp ]; then\n  println \"Test is successful. input.5.zst is precompressed and therefore not compressed/modified again.\"\nelse\n  println \"Test is not successful\"\nfi\n# File Extension check.\ndatagen $size > precompressedFilterTestDir/input.zstbar\nzstd --exclude-compressed --long --rm -r precompressedFilterTestDir\n# zstd should compress input.zstbar\ntest -f precompressedFilterTestDir/input.zstbar.zst\n# Check without the --exclude-compressed flag\nzstd --long --rm -r precompressedFilterTestDir\n# Files should get compressed again without the --exclude-compressed flag.\ntest -f precompressedFilterTestDir/input.5.zst.zst\ntest -f precompressedFilterTestDir/input.6.zst.zst\nrm -rf precompressedFilterTestDir\nprintln \"Test completed\"\n\n\n\nprintln \"\\n===>  warning prompts should not occur if stdin is an input\"\nprintln \"y\" > tmpPrompt\nprintln \"hello world\" >> tmpPrompt\nzstd tmpPrompt -f\nzstd < tmpPrompt -o tmpPrompt.zst && die \"should have aborted immediately and failed to overwrite\"\nzstd < tmpPrompt -o tmpPrompt.zst -f    # should successfully overwrite with -f\nzstd -q -d -f tmpPrompt.zst -o tmpPromptRegenerated\n$DIFF tmpPromptRegenerated tmpPrompt    # the first 'y' character should not be swallowed\n\necho 'yes' | zstd tmpPrompt -v -o tmpPrompt.zst  # accept piped \"y\" input to force overwrite when using files\necho 'yes' | zstd < tmpPrompt -v -o tmpPrompt.zst && die \"should have aborted immediately and failed to overwrite\"\nzstd tmpPrompt - < tmpPrompt -o tmpPromp.zst --rm && die \"should have aborted immediately and failed to remove\"\n\nprintln \"Test completed\"\n\n\nprintln \"\\n===>  recursive mode test \"\n# combination of -r with empty list of input file\nzstd -c -r < tmp > tmp.zst\n\n# combination of -r with empty folder\nmkdir -p tmpEmptyDir\nzstd -r tmpEmptyDir\nrm -rf tmpEmptyDir\n\n\nprintln \"\\n===>  file removal\"\nzstd -f --rm tmp\ntest ! -f tmp  # tmp should no longer be present\nzstd -f -d --rm tmp.zst\ntest ! -f tmp.zst  # tmp.zst should no longer be present\nprintln \"test: --rm is disabled when output is stdout\"\ntest -f tmp\nzstd --rm tmp -c > $INTOVOID\ntest -f tmp # tmp shall still be there\nzstd -f --rm tmp -c > $INTOVOID\ntest -f tmp # tmp shall still be there\nzstd -f tmp -c > $INTOVOID --rm\ntest -f tmp # tmp shall still be there\nprintln \"test: --rm is disabled when multiple inputs are concatenated into a single output\"\ncp tmp tmp2\nzstd --rm tmp tmp2 -c > $INTOVOID\ntest -f tmp\ntest -f tmp2\nrm -f tmp3.zst\necho 'y' | zstd -v tmp tmp2 -o tmp3.zst --rm # prompt for confirmation\ntest -f tmp\ntest -f tmp2\nzstd -f tmp tmp2 -o tmp3.zst --rm # just warns, no prompt\ntest -f tmp\ntest -f tmp2\nzstd -q tmp tmp2 -o tmp3.zst --rm && die \"should refuse to concatenate\"\n\nprintln \"test : should quietly not remove non-regular file\"\nprintln hello > tmp\nzstd tmp -f -o \"$DEVDEVICE\" 2>tmplog > \"$INTOVOID\"\ngrep \"Refusing to remove non-regular file\" tmplog && die\nrm -f tmplog\nzstd tmp -f -o \"$INTOVOID\" 2>&1 | grep \"Refusing to remove non-regular file\" && die\nprintln \"test : --rm on stdin\"\nprintln a | zstd --rm > $INTOVOID   # --rm should remain silent\nrm -f tmp\nzstd -f tmp && die \"tmp not present : should have failed\"\ntest ! -f tmp.zst  # tmp.zst should not be created\nprintln \"test : -d -f do not delete destination when source is not present\"\ntouch tmp    # create destination file\nzstd -d -f tmp.zst && die \"attempt to decompress a non existing file\"\ntest -f tmp  # destination file should still be present\nprintln \"test : -f do not delete destination when source is not present\"\nrm -f tmp         # erase source file\ntouch tmp.zst  # create destination file\nzstd -f tmp && die \"attempt to compress a non existing file\"\ntest -f tmp.zst  # destination file should still be present\nrm -rf tmp*  # may also erase tmp* directory from previous failed run\n\n\nprintln \"\\n===>  decompression only tests \"\n# the following test verifies that the decoder is compatible with RLE as first block\n# older versions of zstd cli are not able to decode such corner case.\n# As a consequence, the zstd cli do not generate them, to maintain compatibility with older versions.\ndd bs=1048576 count=1 if=/dev/zero of=tmp\nzstd -d -o tmp1 \"$TESTDIR/golden-decompression/rle-first-block.zst\"\n$DIFF -s tmp1 tmp\n\ntouch tmp_empty\nzstd -d -o tmp2 \"$TESTDIR/golden-decompression/empty-block.zst\"\n$DIFF -s tmp2 tmp_empty\n\nzstd -t \"$TESTDIR/golden-decompression/zeroSeq_2B.zst\"\n\nzstd -t \"$TESTDIR/golden-decompression-errors/zeroSeq_extraneous.zst\" && die \"invalid Sequences section should have been detected\"\n\nrm -f tmp*\n\nprintln \"\\n===>  compress multiple files\"\nprintln hello > tmp1\nprintln world > tmp2\nzstd tmp1 tmp2 -o \"$INTOVOID\" -f\nzstd tmp1 tmp2 -c | zstd -t\necho 'y' | zstd -v tmp1 tmp2 -o tmp.zst\ntest ! -f tmp1.zst\ntest ! -f tmp2.zst\nzstd tmp1 tmp2\nzstd -t tmp1.zst tmp2.zst\nzstd -dc tmp1.zst tmp2.zst\nzstd tmp1.zst tmp2.zst -o \"$INTOVOID\" -f\necho 'y' | zstd -v -d tmp1.zst tmp2.zst -o tmp\ntouch tmpexists\nzstd tmp1 tmp2 -f -o tmpexists\nzstd tmp1 tmp2 -q -o tmpexists && die \"should have refused to overwrite\"\nprintln gooder > tmp_rm1\nprintln boi > tmp_rm2\nprintln worldly > tmp_rm3\necho 'y' | zstd -v tmp_rm1 tmp_rm2 -v -o tmp_rm3.zst\ntest -f tmp_rm1\ntest -f tmp_rm2\ncp tmp_rm3.zst tmp_rm4.zst\necho 'Y' | zstd -v -d tmp_rm3.zst tmp_rm4.zst -v -o tmp_rm_out --rm\ntest -f tmp_rm3.zst\ntest -f tmp_rm4.zst\nprintln gooder > tmpexists1\nzstd tmpexists1 tmpexists -c --rm -f > $INTOVOID\n# Bug: PR #972\nif [ \"$?\" -eq 139 ]; then\n  die \"should not have segfaulted\"\nfi\ntest -f tmpexists1\ntest -f tmpexists\nprintln \"\\n===>  multiple files and shell completion \"\ndatagen -s1        > tmp1 2> $INTOVOID\ndatagen -s2 -g100K > tmp2 2> $INTOVOID\ndatagen -s3 -g1M   > tmp3 2> $INTOVOID\nprintln \"compress tmp* : \"\nzstd -f tmp*\ntest -f tmp1.zst\ntest -f tmp2.zst\ntest -f tmp3.zst\nrm -f tmp1 tmp2 tmp3\nprintln \"decompress tmp* : \"\nzstd -df ./*.zst\ntest -f tmp1\ntest -f tmp2\ntest -f tmp3\nprintln \"compress tmp* into stdout > tmpall : \"\nzstd -c tmp1 tmp2 tmp3 > tmpall\ntest -f tmpall  # should check size of tmpall (should be tmp1.zst + tmp2.zst + tmp3.zst)\nprintln \"decompress tmpall* into stdout > tmpdec : \"\ncp tmpall tmpall2\nzstd -dc tmpall* > tmpdec\ntest -f tmpdec  # should check size of tmpdec (should be 2*(tmp1 + tmp2 + tmp3))\nprintln \"compress multiple files including a missing one (notHere) : \"\nzstd -f tmp1 notHere tmp2 && die \"missing file not detected!\"\nrm -f tmp*\n\n\nif [ \"$isWindows\" = false ] ; then\n    println \"\\n===>  zstd fifo named pipe test \"\n    echo \"Hello World!\" > tmp_original\n    mkfifo tmp_named_pipe\n    # note : fifo test doesn't work in combination with `dd` or `cat`\n    echo \"Hello World!\" > tmp_named_pipe &\n    zstd tmp_named_pipe -o tmp_compressed\n    zstd -d -o tmp_decompressed tmp_compressed\n    $DIFF -s tmp_original tmp_decompressed\n    rm -rf tmp*\nfi\n\nprintln \"\\n===>  zstd created file permissions tests\"\nif [ \"$isWindows\" = false ] ; then\n    rm -f tmp1 tmp2 tmp1.zst tmp2.zst tmp1.out tmp2.out # todo: remove\n\n    ORIGINAL_UMASK=$(umask)\n    umask 0000\n\n    datagen > tmp1\n    datagen > tmp2\n    assertFilePermissions tmp1 666\n    assertFilePermissions tmp2 666\n\n    println \"test : copy 666 permissions in file -> file compression \"\n    zstd -f tmp1 -o tmp1.zst\n    assertSamePermissions tmp1 tmp1.zst\n    println \"test : copy 666 permissions in file -> file decompression \"\n    zstd -f -d tmp1.zst -o tmp1.out\n    assertSamePermissions tmp1.zst tmp1.out\n\n    rm -f tmp1.zst tmp1.out\n\n    println \"test : copy 400 permissions in file -> file compression (write to a read-only file) \"\n    chmod 0400 tmp1\n    assertFilePermissions tmp1 400\n    zstd -f tmp1 -o tmp1.zst\n    assertSamePermissions tmp1 tmp1.zst\n    println \"test : copy 400 permissions in file -> file decompression (write to a read-only file) \"\n    zstd -f -d tmp1.zst -o tmp1\n    assertSamePermissions tmp1.zst tmp1\n\n    rm -f tmp1.zst tmp1.out\n\n    println \"test : check created permissions from stdin input in compression \"\n    zstd -f -o tmp1.zst < tmp1\n    assertFilePermissions tmp1.zst 666\n    println \"test : check created permissions from stdin input in decompression \"\n    zstd -f -d -o tmp1.out < tmp1.zst\n    assertFilePermissions tmp1.out 666\n\n    rm -f tmp1.zst tmp1.out\n\n    println \"test : check created permissions from multiple inputs in compression \"\n    zstd -f tmp1 tmp2 -o tmp1.zst\n    assertFilePermissions tmp1.zst 666\n    println \"test : check created permissions from multiple inputs in decompression \"\n    cp tmp1.zst tmp2.zst\n    zstd -f -d tmp1.zst tmp2.zst -o tmp1.out\n    assertFilePermissions tmp1.out 666\n\n    rm -f tmp1.zst tmp2.zst tmp1.out tmp2.out\n\n    println \"test : check permissions on pre-existing output file in compression \"\n    chmod 0600 tmp1\n    touch tmp1.zst\n    chmod 0400 tmp1.zst\n    zstd -f tmp1 -o tmp1.zst\n    assertFilePermissions tmp1.zst 600\n    println \"test : check permissions on pre-existing output file in decompression \"\n    chmod 0400 tmp1.zst\n    touch tmp1.out\n    chmod 0200 tmp1.out\n    zstd -f -d tmp1.zst -o tmp1.out\n    assertFilePermissions tmp1.out 400\n\n    umask 0666\n    chmod 0666 tmp1 tmp2\n\n    rm -f tmp1.zst tmp1.out\n\n    println \"test : respect umask when compressing from stdin input \"\n    zstd -f -o tmp1.zst < tmp1\n    assertFilePermissions tmp1.zst 0\n    println \"test : respect umask when decompressing from stdin input \"\n    chmod 0666 tmp1.zst\n    zstd -f -d -o tmp1.out < tmp1.zst\n    assertFilePermissions tmp1.out 0\n\n    rm -f tmp1 tmp2 tmp1.zst tmp2.zst tmp1.out tmp2.out\n    umask $ORIGINAL_UMASK\nfi\n\nif [ -n \"$DEVNULLRIGHTS\" ] ; then\n    # these tests requires sudo rights, which is uncommon.\n    # they are only triggered if DEVNULLRIGHTS macro is defined.\n    println \"\\n===> checking /dev/null permissions are unaltered \"\n    datagen > tmp\n    sudoZstd tmp -o $INTOVOID   # sudo rights could modify /dev/null permissions\n    sudoZstd tmp -c > $INTOVOID\n    zstd tmp -f -o tmp.zst\n    sudoZstd -d tmp.zst -c > $INTOVOID\n    sudoZstd -d tmp.zst -o $INTOVOID\n    ls -las $INTOVOID | grep \"rw-rw-rw-\"\nfi\n\nif [ -n \"$READFROMBLOCKDEVICE\" ] ; then\n    # This creates a temporary block device, which is only possible on unix-y\n    # systems, is somewhat invasive, and requires sudo. For these reasons, you\n    # have to specifically ask for this test.\n    println \"\\n===> checking that zstd can read from a block device\"\n    datagen -g65536 > tmp.img\n    sudo losetup -fP tmp.img\n    LOOP_DEV=$(losetup -a | grep 'tmp\\.img' | cut -f1 -d:)\n    [ -z \"$LOOP_DEV\" ] && die \"failed to get loopback device\"\n    sudoZstd $LOOP_DEV -c > tmp.img.zst && die \"should fail without -f\"\n    sudoZstd -f $LOOP_DEV -c > tmp.img.zst\n    zstd -d tmp.img.zst -o tmp.img.copy\n    sudo losetup -d $LOOP_DEV\n    $DIFF -s tmp.img tmp.img.copy || die \"round trip failed\"\n    rm -f tmp.img tmp.img.zst tmp.img.copy\nfi\n\nprintln \"\\n===>  zstd created file timestamp tests\"\ndatagen > tmp\ntouch -m -t 200001010000.00 tmp\nprintln \"test : copy mtime in file -> file compression \"\nzstd -f tmp -o tmp.zst\nassertSameMTime tmp tmp.zst\nprintln \"test : copy mtime in file -> file decompression \"\nzstd -f -d tmp.zst -o tmp.out\nassertSameMTime tmp.zst tmp.out\nrm -f tmp\n\nprintln \"\\n===>  compress multiple files into an output directory, --output-dir-flat\"\nprintln henlo > tmp1\nmkdir tmpInputTestDir\nmkdir tmpInputTestDir/we\nmkdir tmpInputTestDir/we/must\nmkdir tmpInputTestDir/we/must/go\nmkdir tmpInputTestDir/we/must/go/deeper\nprintln cool > tmpInputTestDir/we/must/go/deeper/tmp2\nmkdir tmpOutDir\nzstd tmp1 tmpInputTestDir/we/must/go/deeper/tmp2 --output-dir-flat tmpOutDir\ntest -f tmpOutDir/tmp1.zst\ntest -f tmpOutDir/tmp2.zst\nprintln \"test : decompress multiple files into an output directory, --output-dir-flat\"\nmkdir tmpOutDirDecomp\nzstd tmpOutDir -r -d --output-dir-flat tmpOutDirDecomp\ntest -f tmpOutDirDecomp/tmp2\ntest -f tmpOutDirDecomp/tmp1\nrm -f tmpOutDirDecomp/*\nzstd tmpOutDir -r -d --output-dir-flat=tmpOutDirDecomp\ntest -f tmpOutDirDecomp/tmp2\ntest -f tmpOutDirDecomp/tmp1\nrm -rf tmp*\n\nif [ \"$isWindows\" = false ] ; then\n    println \"\\n===>  compress multiple files into an output directory and mirror input folder, --output-dir-mirror\"\n    println \"test --output-dir-mirror\" > tmp1\n    mkdir -p tmpInputTestDir/we/.../..must/go/deeper..\n    println cool > tmpInputTestDir/we/.../..must/go/deeper../tmp2\n    zstd tmp1 -r tmpInputTestDir --output-dir-mirror tmpOutDir\n    test -f tmpOutDir/tmp1.zst\n    test -f tmpOutDir/tmpInputTestDir/we/.../..must/go/deeper../tmp2.zst\n\n    println \"test: compress input dir will be ignored if it has '..'\"\n    zstd  -r tmpInputTestDir/we/.../..must/../..mustgo/deeper.. --output-dir-mirror non-exist && die \"input cannot contain '..'\"\n    zstd  -r tmpInputTestDir/we/.../..must/deeper../.. --output-dir-mirror non-exist && die \"input cannot contain '..'\"\n    zstd  -r ../tests/tmpInputTestDir/we/.../..must/deeper.. --output-dir-mirror non-exist && die \"input cannot contain '..'\"\n    test ! -d non-exist\n\n    println \"test: compress input dir should succeed with benign uses of '..'\"\n    zstd  -r tmpInputTestDir/we/.../..must/go/deeper.. --output-dir-mirror tmpout\n    test -d tmpout\n\n    println \"test : decompress multiple files into an output directory, --output-dir-mirror\"\n    zstd tmpOutDir -r -d --output-dir-mirror tmpOutDirDecomp\n    test -f tmpOutDirDecomp/tmpOutDir/tmp1\n    test -f tmpOutDirDecomp/tmpOutDir/tmpInputTestDir/we/.../..must/go/deeper../tmp2\n\n    println \"test: decompress input dir will be ignored if it has '..'\"\n    zstd  -r tmpOutDir/tmpInputTestDir/we/.../..must/../..must --output-dir-mirror non-exist && die \"input cannot contain '..'\"\n    test ! -d non-exist\n\n    rm -rf tmp*\nfi\n\n\nprintln \"test : compress multiple files reading them from a file, --filelist=FILE\"\nprintln \"Hello world!, file1\" > tmp1\nprintln \"Hello world!, file2\" > tmp2\nprintln tmp1 > tmp_fileList\nprintln tmp2 >> tmp_fileList\nzstd -f --filelist=tmp_fileList\ntest -f tmp2.zst\ntest -f tmp1.zst\n\nprintln \"test : alternate syntax: --filelist FILE\"\nzstd -f --filelist tmp_fileList\ntest -f tmp2.zst\ntest -f tmp1.zst\n\nprintln \"test : reading file list from a symlink, --filelist=FILE\"\nrm -f *.zst\nln -s tmp_fileList tmp_symLink\nzstd -f --filelist=tmp_symLink\ntest -f tmp2.zst\ntest -f tmp1.zst\n\nprintln \"test : compress multiple files reading them from multiple files, --filelist=FILE\"\nrm -f *.zst\nprintln \"Hello world!, file3\" > tmp3\nprintln \"Hello world!, file4\" > tmp4\nprintln tmp3 > tmp_fileList2\nprintln tmp4 >> tmp_fileList2\nzstd -f --filelist=tmp_fileList --filelist=tmp_fileList2\ntest -f tmp1.zst\ntest -f tmp2.zst\ntest -f tmp3.zst\ntest -f tmp4.zst\n\nprintln \"test : decompress multiple files reading them from a file, --filelist=FILE\"\nrm -f tmp1 tmp2\nprintln tmp1.zst > tmpZst\nprintln tmp2.zst >> tmpZst\nzstd -d -f --filelist=tmpZst\ntest -f tmp1\ntest -f tmp2\n\nprintln \"test : decompress multiple files reading them from multiple files, --filelist=FILE\"\nrm -f tmp1 tmp2 tmp3 tmp4\nprintln tmp3.zst > tmpZst2\nprintln tmp4.zst >> tmpZst2\nzstd -d -f --filelist=tmpZst --filelist=tmpZst2\ntest -f tmp1\ntest -f tmp2\ntest -f tmp3\ntest -f tmp4\n\nprintln \"test : survive the list of files with too long filenames (--filelist=FILE)\"\ndatagen -g5M > tmp_badList\nzstd -qq -f --filelist=tmp_badList && die \"should have failed : file name length is too long\"  # printing very long text garbage on console will cause CI failure\n\nprintln \"test : survive a list of files which is text garbage (--filelist=FILE)\"\ndatagen > tmp_badList\nzstd -qq -f --filelist=tmp_badList && die \"should have failed : list is text garbage\"  # printing very long text garbage on console will cause CI failure\n\nprintln \"test : survive a list of files which is binary garbage (--filelist=FILE)\"\ndatagen -P0 -g1M > tmp_badList\nzstd -qq -f --filelist=tmp_badList && die \"should have failed : list is binary garbage\"  # let's avoid printing binary garbage on console\n\nprintln \"test : try to overflow internal list of files (--filelist=FILE)\"\ntouch tmp1 tmp2 tmp3 tmp4 tmp5 tmp6\nls tmp* > tmpList\nzstd -f tmp1 --filelist=tmpList --filelist=tmpList tmp2 tmp3  # can trigger an overflow of internal file list\nrm -rf tmp*\n\nprintln \"\\n===> --[no-]content-size tests\"\n\ndatagen > tmp_contentsize\nzstd -f tmp_contentsize\nzstd -lv tmp_contentsize.zst | grep \"Decompressed Size:\"\nzstd -f --no-content-size tmp_contentsize\nzstd -lv tmp_contentsize.zst | grep \"Decompressed Size:\" && die\nzstd -f --content-size tmp_contentsize\nzstd -lv tmp_contentsize.zst | grep \"Decompressed Size:\"\nzstd -f --content-size --no-content-size tmp_contentsize\nzstd -lv tmp_contentsize.zst | grep \"Decompressed Size:\" && die\nrm -rf tmp*\n\nprintln \"test : show-default-cparams regular\"\ndatagen > tmp\nzstd --show-default-cparams -f tmp\nzstd --show-default-cparams -d tmp.zst && die \"error: can't use --show-default-cparams in decompression mode\"\nrm -rf tmp*\n\nprintln \"test : show-default-cparams recursive\"\nmkdir tmp_files\ndatagen -g15000 > tmp_files/tmp1\ndatagen -g129000 > tmp_files/tmp2\ndatagen -g257000 > tmp_files/tmp3\nzstd --show-default-cparams -f -r tmp_files\nrm -rf tmp*\n\nprintln \"test : show compression parameters in verbose mode\"\ndatagen > tmp\nzstd -vv tmp 2>&1 | \\\ngrep -q -E -- \"--zstd=wlog=[[:digit:]]+,clog=[[:digit:]]+,hlog=[[:digit:]]+,\\\nslog=[[:digit:]]+,mml=[[:digit:]]+,tlen=[[:digit:]]+,strat=[[:digit:]]+\"\nrm -rf tmp*\n\nprintln \"\\n===>  Advanced compression parameters \"\nprintln \"Hello world!\" | zstd --zstd=windowLog=21,      - -o tmp.zst && die \"wrong parameters not detected!\"\nprintln \"Hello world!\" | zstd --zstd=windowLo=21        - -o tmp.zst && die \"wrong parameters not detected!\"\nprintln \"Hello world!\" | zstd --zstd=windowLog=21,slog  - -o tmp.zst && die \"wrong parameters not detected!\"\nprintln \"Hello world!\" | zstd --zstd=strategy=10        - -o tmp.zst && die \"parameter out of bound not detected!\"  # > btultra2 : does not exist\ntest ! -f tmp.zst  # tmp.zst should not be created\nroundTripTest -g512K\nroundTripTest -g512K \" --zstd=mml=3,tlen=48,strat=6\"\nroundTripTest -g512K \" --zstd=strat=6,wlog=23,clog=23,hlog=22,slog=6\"\nroundTripTest -g512K \" --zstd=windowLog=23,chainLog=23,hashLog=22,searchLog=6,minMatch=3,targetLength=48,strategy=6\"\nroundTripTest -g512K \" --single-thread --long --zstd=ldmHashLog=20,ldmMinMatch=64,ldmBucketSizeLog=1,ldmHashRateLog=7\"\nroundTripTest -g512K \" --single-thread --long --zstd=lhlog=20,lmml=64,lblog=1,lhrlog=7\"\nroundTripTest -g64K  \"19 --zstd=strat=9\"   # btultra2\n\n\nprintln \"\\n===>  Pass-Through mode \"\nprintln \"Hello world 1!\" | zstd -df\nprintln \"Hello world 2!\" | zstd -dcf\nprintln \"Hello world 3!\" > tmp1\nzstd -dcf tmp1\nprintln \"\" | zstd -df > tmp1\nprintln \"\" > tmp2\n$DIFF -q tmp1 tmp2\nprintln \"1\" | zstd -df > tmp1\nprintln \"1\" > tmp2\n$DIFF -q tmp1 tmp2\nprintln \"12\" | zstd -df > tmp1\nprintln \"12\" > tmp2\n$DIFF -q tmp1 tmp2\nrm -rf tmp*\n\n\nprintln \"\\n===>  frame concatenation \"\nprintln \"hello \" > hello.tmp\nprintln \"world!\" > world.tmp\ncat hello.tmp world.tmp > helloworld.tmp\nzstd -c hello.tmp > hello.zst\nzstd -c world.tmp > world.zst\nzstd -c hello.tmp world.tmp > helloworld.zst\nzstd -dc helloworld.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\ncat hello.zst world.zst > helloworld.zst\nzstd -dc helloworld.zst > result.tmp\ncat result.tmp\n$DIFF helloworld.tmp result.tmp\nprintln \"frame concatenation without checksum\"\nzstd -c hello.tmp > hello.zst --no-check\nzstd -c world.tmp > world.zst --no-check\ncat hello.zst world.zst > helloworld.zstd\nzstd -dc helloworld.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\nprintln \"testing zstdcat symlink\"\nln -sf \"$ZSTD_BIN\" zstdcat\n$EXE_PREFIX ./zstdcat helloworld.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\nln -s helloworld.zst helloworld.link.zst\n$EXE_PREFIX ./zstdcat helloworld.link.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\nrm -f zstdcat\nrm -f result.tmp\nprintln \"testing zcat symlink\"\nln -sf \"$ZSTD_BIN\" zcat\n$EXE_PREFIX ./zcat helloworld.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\n$EXE_PREFIX ./zcat helloworld.link.zst > result.tmp\n$DIFF helloworld.tmp result.tmp\nrm -f zcat\nrm -f ./*.tmp ./*.zstd\nprintln \"frame concatenation tests completed\"\n\n\nif [ \"$isWindows\" = false ] && [ \"$UNAME\" != 'SunOS' ] && [ \"$UNAME\" != \"OpenBSD\" ] && [ \"$UNAME\" != \"AIX\" ]; then\nprintln \"\\n**** flush write error test **** \"\n\nprintln \"println foo | zstd > /dev/full\"\nprintln foo | zstd > /dev/full && die \"write error not detected!\"\nprintln \"println foo | zstd | zstd -d > /dev/full\"\nprintln foo | zstd | zstd -d > /dev/full && die \"write error not detected!\"\n\nfi\n\n\nif [ \"$isWindows\" = false ] && [ \"$UNAME\" != 'SunOS' ] ; then\n\nprintln \"\\n===>  symbolic link test \"\n\nrm -f hello.tmp world.tmp world2.tmp hello.tmp.zst world.tmp.zst\nprintln \"hello world\" > hello.tmp\nln -s hello.tmp world.tmp\nln -s hello.tmp world2.tmp\nzstd world.tmp hello.tmp || true\ntest -f hello.tmp.zst  # regular file should have been compressed!\ntest ! -f world.tmp.zst  # symbolic link should not have been compressed!\nzstd world.tmp || true\ntest ! -f world.tmp.zst  # symbolic link should not have been compressed!\nzstd world.tmp world2.tmp || true\ntest ! -f world.tmp.zst  # symbolic link should not have been compressed!\ntest ! -f world2.tmp.zst  # symbolic link should not have been compressed!\nzstd world.tmp hello.tmp -f\ntest -f world.tmp.zst  # symbolic link should have been compressed with --force\nrm -f hello.tmp world.tmp world2.tmp hello.tmp.zst world.tmp.zst\n\nfi\n\n\nprintln \"\\n===>  test sparse file support \"\n\ndatagen -g5M  -P100 > tmpSparse\nzstd tmpSparse -c | zstd -dv -o tmpSparseRegen\n$DIFF -s tmpSparse tmpSparseRegen\nzstd tmpSparse -c | zstd -dv --sparse -c > tmpOutSparse\n$DIFF -s tmpSparse tmpOutSparse\nzstd tmpSparse -c | zstd -dv --no-sparse -c > tmpOutNoSparse\n$DIFF -s tmpSparse tmpOutNoSparse\nls -ls tmpSparse*  # look at file size and block size on disk\ndatagen -s1 -g1200007 -P100 | zstd | zstd -dv --sparse -c > tmpSparseOdd   # Odd size file (to not finish on an exact nb of blocks)\ndatagen -s1 -g1200007 -P100 | $DIFF -s - tmpSparseOdd\nls -ls tmpSparseOdd  # look at file size and block size on disk\nprintln \"\\n Sparse Compatibility with Console :\"\nprintln \"Hello World 1 !\" | zstd | zstd -d -c\nprintln \"Hello World 2 !\" | zstd | zstd -d | cat\nprintln \"\\n Sparse Compatibility with Append :\"\ndatagen -P100 -g1M > tmpSparse1M\ncat tmpSparse1M tmpSparse1M > tmpSparse2M\nzstd -v -f tmpSparse1M -o tmpSparseCompressed\nzstd -d -v -f tmpSparseCompressed -o tmpSparseRegenerated\nzstd -d -v -f tmpSparseCompressed -c >> tmpSparseRegenerated\nls -ls tmpSparse*  # look at file size and block size on disk\n$DIFF tmpSparse2M tmpSparseRegenerated\nrm -f tmpSparse*\n\n\nprintln \"\\n===>  stream-size mode\"\n\ndatagen -g11000 > tmp\nprintln \"test : basic file compression vs sized streaming compression\"\nfile_size=$(zstd -14 -f tmp -o tmp.zst && wc -c < tmp.zst)\nstream_size=$(cat tmp | zstd -14 --stream-size=11000 | wc -c)\nif [ \"$stream_size\" -gt \"$file_size\" ]; then\n  die \"hinted compression larger than expected\"\nfi\nprintln \"test : sized streaming compression and decompression\"\ncat tmp | zstd -14 -f tmp -o tmp.zst --stream-size=11000\nzstd -df tmp.zst -o tmp_decompress\ncmp tmp tmp_decompress || die \"difference between original and decompressed file\"\nprintln \"test : incorrect stream size\"\ncat tmp | zstd -14 -f -o tmp.zst --stream-size=11001 && die \"should fail with incorrect stream size\"\n\nprintln \"\\n===>  zstd zero weight dict test \"\nrm -f tmp*\ncp \"$TESTDIR/dict-files/zero-weight-dict\" tmp_input\nzstd -D \"$TESTDIR/dict-files/zero-weight-dict\" tmp_input\nzstd -D \"$TESTDIR/dict-files/zero-weight-dict\" -d tmp_input.zst -o tmp_decomp\n$DIFF tmp_decomp tmp_input\nrm -rf tmp*\n\nprintln \"\\n===>  zstd (valid) zero weight dict test \"\nrm -f tmp*\n# 0 has a non-zero weight in the dictionary\necho \"0000000000000000000000000\" > tmp_input\nzstd -D \"$TESTDIR/dict-files/zero-weight-dict\" tmp_input\nzstd -D \"$TESTDIR/dict-files/zero-weight-dict\" -d tmp_input.zst -o tmp_decomp\n$DIFF tmp_decomp tmp_input\nrm -rf tmp*\n\nprintln \"\\n===>  size-hint mode\"\n\ndatagen -g11000 > tmp\ndatagen -g11000 > tmp2\ndatagen > tmpDict\nprintln \"test : basic file compression vs hinted streaming compression\"\nfile_size=$(zstd -14 -f tmp -o tmp.zst && wc -c < tmp.zst)\nstream_size=$(cat tmp | zstd -14 --size-hint=11000 | wc -c)\nif [ \"$stream_size\" -ge \"$file_size\" ]; then\n  die \"hinted compression larger than expected\"\nfi\nprintln \"test : hinted streaming compression and decompression\"\ncat tmp | zstd -14 -f -o tmp.zst --size-hint=11000\nzstd -df tmp.zst -o tmp_decompress\ncmp tmp tmp_decompress || die \"difference between original and decompressed file\"\nprintln \"test : hinted streaming compression with dictionary\"\ncat tmp | zstd -14 -f -D tmpDict --size-hint=11000 | zstd -t -D tmpDict\nprintln \"test : multiple file compression with hints and dictionary\"\nzstd -14 -f -D tmpDict --size-hint=11000 tmp tmp2\nzstd -14 -f -o tmp1_.zst -D tmpDict --size-hint=11000 tmp\nzstd -14 -f -o tmp2_.zst -D tmpDict --size-hint=11000 tmp2\ncmp tmp.zst tmp1_.zst || die \"first file's output differs\"\ncmp tmp2.zst tmp2_.zst || die \"second file's output differs\"\nprintln \"test : incorrect hinted stream sizes\"\ncat tmp | zstd -14 -f --size-hint=11050 | zstd -t  # slightly too high\ncat tmp | zstd -14 -f --size-hint=10950 | zstd -t  # slightly too low\ncat tmp | zstd -14 -f --size-hint=22000 | zstd -t  # considerably too high\ncat tmp | zstd -14 -f --size-hint=5500  | zstd -t  # considerably too low\nprintln \"test : allows and interprets K,KB,KiB,M,MB and MiB suffix\"\ncat tmp | zstd -14 -f --size-hint=11K | zstd -t\ncat tmp | zstd -14 -f --size-hint=11KB | zstd -t\ncat tmp | zstd -14 -f --size-hint=11KiB | zstd -t\ncat tmp | zstd -14 -f --size-hint=1M  | zstd -t\ncat tmp | zstd -14 -f --size-hint=1MB  | zstd -t\ncat tmp | zstd -14 -f --size-hint=1MiB  | zstd -t\n\n\nprintln \"\\n===>  dictionary tests \"\nprintln \"- Test high/low compressibility corpus training\"\ndatagen -g12M -P90 > tmpCorpusHighCompress\ndatagen -g12M -P5 > tmpCorpusLowCompress\nzstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress\nzstd --train -B2K tmpCorpusLowCompress -o tmpDictLowCompress\nrm -f tmpCorpusHighCompress tmpCorpusLowCompress tmpDictHighCompress tmpDictLowCompress\nprintln \"- Test with raw dict (content only) \"\ndatagen > tmpDict\ndatagen -g1M | $MD5SUM > tmp1\ndatagen -g1M | zstd -D tmpDict | zstd -D tmpDict -dvq | $MD5SUM > tmp2\n$DIFF -q tmp1 tmp2\nprintln \"- Create first dictionary \"\nTESTFILE=\"$PRGDIR\"/zstdcli.c\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict\ncp \"$TESTFILE\" tmp\nprintln \"- Test dictionary compression with tmpDict as an input file and dictionary\"\nzstd -f tmpDict -D tmpDict && die \"compression error not detected!\"\nprintln \"- Dictionary compression roundtrip\"\nzstd -f tmp -D tmpDict\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nprintln \"- Dictionary compression with hlog < clog\"\nzstd -6f tmp -D tmpDict --zstd=clog=25,hlog=23\nprintln \"- Dictionary compression with btlazy2 strategy\"\nzstd -f tmp -D tmpDict --zstd=strategy=6\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nif [ -e /proc/self/fd/0 ]; then\n    println \"- Test rejecting irregular dictionary file\"\n    cat tmpDict | zstd -f tmp -D /proc/self/fd/0 && die \"Piped dictionary should fail!\"\n    cat tmpDict | zstd -d tmp.zst -D /proc/self/fd/0 -f && die \"Piped dictionary should fail!\"\nfi\nif [ -n \"$hasMT\" ]\nthen\n    println \"- Test dictionary compression with multithreading \"\n    datagen -g5M | zstd -T2 -D tmpDict | zstd -t -D tmpDict   # fails with v1.3.2\nfi\nprintln \"- Create second (different) dictionary \"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c \"$PRGDIR\"/*.h -o tmpDictC\nzstd -d tmp.zst -D tmpDictC -fo result && die \"wrong dictionary not detected!\"\nprintln \"- Create dictionary with short dictID\"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpDict1\ncmp tmpDict tmpDict1 && die \"dictionaries should have different ID !\"\nprintln \"- Create dictionary with wrong dictID parameter order (must fail)\"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID -o 1 tmpDict1 && die \"wrong order : --dictID must be followed by argument \"\nprintln \"- Create dictionary with size limit\"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict2 --maxdict=4K -v\nprintln \"- Create dictionary with small size limit\"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict3 --maxdict=1K -v\nprintln \"- Create dictionary with wrong parameter order (must fail)\"\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict3 --maxdict -v 4K && die \"wrong order : --maxdict must be followed by argument \"\nprintln \"- Compress without dictID\"\nzstd -f tmp -D tmpDict1 --no-dictID\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nprintln \"- Compress multiple files with dictionary\"\nrm -rf dirTestDict\nmkdir dirTestDict\ncp \"$TESTDIR\"/*.c dirTestDict\ncp \"$PRGDIR\"/*.c dirTestDict\ncp \"$PRGDIR\"/*.h dirTestDict\n$MD5SUM dirTestDict/* > tmph1\nzstd -f --rm dirTestDict/* -D tmpDictC\nzstd -d --rm dirTestDict/*.zst -D tmpDictC  # note : use internal checksum by default\ncase \"$UNAME\" in\n  Darwin) println \"md5sum -c not supported on OS-X : test skipped\" ;;  # not compatible with OS-X's md5\n  *) $MD5SUM -c tmph1 ;;\nesac\nrm -rf dirTestDict\nprintln \"- dictionary builder on bogus input\"\nprintln \"Hello World\" > tmp\nzstd --train-legacy -q tmp && die \"Dictionary training should fail : not enough input source\"\ndatagen -P0 -g10M > tmp\nzstd --train-legacy -q tmp && die \"Dictionary training should fail : source is pure noise\"\nprintln \"- Test -o before --train\"\nrm -f tmpDict dictionary\nzstd -o tmpDict --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f tmpDict\nzstd --train \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f dictionary\nif [ -n \"$hasMT\" ]\nthen\n  println \"- Create dictionary with multithreading enabled\"\n  zstd --train -T0 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict\nfi\nrm -f tmp* dictionary\n\nprintln \"- Test --memory for dictionary compression\"\ndatagen -g12M -P90 > tmpCorpusHighCompress\nzstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=10K && die \"Dictionary training should fail : --memory too low (10K)\"\nzstd --train -B2K tmpCorpusHighCompress -o tmpDictHighCompress --memory=5MB 2> zstTrainWithMemLimitStdErr\ncat zstTrainWithMemLimitStdErr | grep \"setting manual memory limit for dictionary training data at 5 MB\"\ncat zstTrainWithMemLimitStdErr | grep \"Training samples set too large (12 MB); training on 5 MB only...\"\nrm zstTrainWithMemLimitStdErr\n\nprintln \"\\n===>  fastCover dictionary builder : advanced options \"\nTESTFILE=\"$PRGDIR\"/zstdcli.c\ndatagen > tmpDict\nprintln \"- Create first dictionary\"\nzstd --train-fastcover=k=46,d=8,f=15,split=80 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict\ncp \"$TESTFILE\" tmp\nzstd -f tmp -D tmpDict\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nprintln \"- Create second (different) dictionary\"\nzstd --train-fastcover=k=56,d=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c \"$PRGDIR\"/*.h -o tmpDictC\nzstd -d tmp.zst -D tmpDictC -fo result && die \"wrong dictionary not detected!\"\nzstd --train-fastcover=k=56,d=8 && die \"Create dictionary without input file\"\nprintln \"- Create dictionary with short dictID\"\nzstd --train-fastcover=k=46,d=8,f=15,split=80 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpDict1\ncmp tmpDict tmpDict1 && die \"dictionaries should have different ID !\"\nprintln \"- Create dictionaries with shrink-dict flag enabled\"\nzstd --train-fastcover=steps=1,shrink \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpShrinkDict\nzstd --train-fastcover=steps=1,shrink=1 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpShrinkDict1\nzstd --train-fastcover=steps=1,shrink=5 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpShrinkDict2\nzstd --train-fastcover=shrink=5,steps=1 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpShrinkDict3\nprintln \"- Create dictionary with size limit\"\nzstd --train-fastcover=steps=1 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict2 --maxdict=4K\nprintln \"- Create dictionary using all samples for both training and testing\"\nzstd --train-fastcover=k=56,d=8,split=100 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Create dictionary using f=16\"\nzstd --train-fastcover=k=56,d=8,f=16 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nzstd --train-fastcover=k=56,d=8,accel=15 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c && die \"Created dictionary using accel=15\"\nprintln \"- Create dictionary using accel=2\"\nzstd --train-fastcover=k=56,d=8,accel=2 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Create dictionary using accel=10\"\nzstd --train-fastcover=k=56,d=8,accel=10 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Create dictionary with multithreading\"\nzstd --train-fastcover -T4 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Test -o before --train-fastcover\"\nrm -f tmpDict dictionary\nzstd -o tmpDict --train-fastcover=k=56,d=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f tmpDict\nzstd --train-fastcover=k=56,d=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f dictionary\nrm -f tmp* dictionary\n\n\nprintln \"\\n===>  legacy dictionary builder \"\n\nTESTFILE=\"$PRGDIR\"/zstdcli.c\ndatagen > tmpDict\nprintln \"- Create first dictionary\"\nzstd --train-legacy=selectivity=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict\ncp \"$TESTFILE\" tmp\nzstd -f tmp -D tmpDict\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nzstd --train-legacy=s=8 && die \"Create dictionary without input files (should error)\"\nprintln \"- Create second (different) dictionary\"\nzstd --train-legacy=s=5 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c \"$PRGDIR\"/*.h -o tmpDictC\nzstd -d tmp.zst -D tmpDictC -fo result && die \"wrong dictionary not detected!\"\nprintln \"- Create dictionary with short dictID\"\nzstd --train-legacy -s5 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpDict1\ncmp tmpDict tmpDict1 && die \"dictionaries should have different ID !\"\nprintln \"- Create dictionary with size limit\"\nzstd --train-legacy -s9 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict2 --maxdict=4K\nprintln \"- Test -o before --train-legacy\"\nrm -f tmpDict dictionary\nzstd -o tmpDict --train-legacy \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f tmpDict\nzstd --train-legacy \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f dictionary\nrm -f tmp* dictionary\n\n\nprintln \"\\n===>  integrity tests \"\n\nprintln \"test one file (tmp1.zst) \"\ndatagen > tmp1\nzstd tmp1\nzstd -t tmp1.zst\nzstd --test tmp1.zst\nprintln \"test multiple files (*.zst) \"\nzstd -t ./*.zst\nprintln \"test bad files (*) \"\nzstd -t ./* && die \"bad files not detected !\"\nzstd -t tmp1 && die \"bad file not detected !\"\ncp tmp1 tmp2.zst\nzstd -t tmp2.zst && die \"bad file not detected !\"\ndatagen -g0 > tmp3\nzstd -t tmp3 && die \"bad file not detected !\"   # detects 0-sized files as bad\nprintln \"test --rm and --test combined \"\nzstd -t --rm tmp1.zst\ntest -f tmp1.zst   # check file is still present\ncp tmp1.zst tmp2.zst\nzstd -t tmp1.zst tmp2.zst --rm\ntest -f tmp1.zst   # check file is still present\ntest -f tmp2.zst   # check file is still present\nsplit -b16384 tmp1.zst tmpSplit.\nzstd -t tmpSplit.* && die \"bad file not detected !\"\ndatagen | zstd -c | zstd -t\n\n\nprintln \"\\n===>  golden files tests \"\n\nzstd -t -r \"$TESTDIR/golden-decompression\"\nzstd -c -r \"$TESTDIR/golden-compression\" | zstd -t\nzstd -D \"$TESTDIR/golden-dictionaries/http-dict-missing-symbols\" \"$TESTDIR/golden-compression/http\" -c | zstd -D \"$TESTDIR/golden-dictionaries/http-dict-missing-symbols\" -t\n\n\nprintln \"\\n===>  benchmark mode tests \"\n\nprintln \"bench one file\"\ndatagen > tmp1\nzstd -bi0 tmp1\nprintln \"bench multiple levels\"\nzstd -i0b0e3 tmp1\nprintln \"bench negative level\"\nzstd -bi0 --fast tmp1\nprintln \"with recursive and quiet modes\"\nzstd -rqi0b1e2 tmp1\nprintln \"benchmark decompression only\"\nzstd -f tmp1\nzstd -b -d -i0 tmp1.zst\nprintln \"benchmark can fail - decompression on invalid data\"\nzstd -b -d -i0 tmp1 && die \"invalid .zst data => benchmark should have failed\"\n\nGZIPMODE=1\nzstd --format=gzip -V || GZIPMODE=0\nif [ $GZIPMODE -eq 1 ]; then\n    println \"benchmark mode is only compatible with zstd\"\n    zstd --format=gzip -b tmp1 && die \"-b should be incompatible with gzip format!\"\nfi\n\nprintln \"\\n===>  zstd compatibility tests \"\n\ndatagen > tmp\nrm -f tmp.zst\nzstd --format=zstd -f tmp\ntest -f tmp.zst\n\n\nprintln \"\\n===>  gzip compatibility tests \"\n\nGZIPMODE=1\nzstd --format=gzip -V || GZIPMODE=0\nif [ $GZIPMODE -eq 1 ]; then\n    println \"gzip support detected\"\n    GZIPEXE=1\n    gzip -V || GZIPEXE=0\n    if [ $GZIPEXE -eq 1 ]; then\n        datagen > tmp\n        zstd --format=gzip -f tmp\n        gzip -t -v tmp.gz\n        gzip -f tmp\n        zstd -d -f -v tmp.gz\n        rm -f tmp*\n    else\n        println \"gzip binary not detected\"\n    fi\nelse\n    println \"gzip mode not supported\"\nfi\n\n\nprintln \"\\n===>  gzip frame tests \"\n\nif [ $GZIPMODE -eq 1 ]; then\n    datagen > tmp\n    zstd -f --format=gzip tmp\n    zstd -f tmp\n    cat tmp.gz tmp.zst tmp.gz tmp.zst | zstd -d -f -o tmp\n    truncateLastByte tmp.gz | zstd -t > $INTOVOID && die \"incomplete frame not detected !\"\n    rm -f tmp*\nelse\n    println \"gzip mode not supported\"\nfi\n\nif [ $GZIPMODE -eq 1 ]; then\n    datagen > tmp\n    rm -f tmp.zst\n    zstd --format=gzip --format=zstd -f tmp\n    test -f tmp.zst\nfi\n\nprintln \"\\n===>  xz compatibility tests \"\n\nLZMAMODE=1\nzstd --format=xz -V || LZMAMODE=0\nif [ $LZMAMODE -eq 1 ]; then\n    println \"xz support detected\"\n    XZEXE=1\n    xz -Q -V && lzma -Q -V || XZEXE=0\n    if [ $XZEXE -eq 1 ]; then\n        println \"Testing zstd xz and lzma support\"\n        datagen > tmp\n        zstd --format=lzma -f tmp\n        zstd --format=xz -f tmp\n        xz -Q -t -v tmp.xz\n        xz -Q -t -v tmp.lzma\n        xz -Q -f -k tmp\n        lzma -Q -f -k --lzma1 tmp\n        zstd -d -f -v tmp.xz\n        zstd -d -f -v tmp.lzma\n        rm -f tmp*\n        println \"Creating symlinks\"\n        ln -s \"$ZSTD_BIN\" ./xz\n        ln -s \"$ZSTD_BIN\" ./unxz\n        ln -s \"$ZSTD_BIN\" ./lzma\n        ln -s \"$ZSTD_BIN\" ./unlzma\n        println \"Testing xz and lzma symlinks\"\n        datagen > tmp\n        ./xz tmp\n        xz -Q -d tmp.xz\n        ./lzma tmp\n        lzma -Q -d tmp.lzma\n        println \"Testing unxz and unlzma symlinks\"\n        xz -Q tmp\n        ./xz -d tmp.xz\n        lzma -Q tmp\n        ./lzma -d tmp.lzma\n        rm -f xz unxz lzma unlzma\n        rm -f tmp*\n    else\n        println \"xz binary not detected\"\n    fi\nelse\n    println \"xz mode not supported\"\nfi\n\n\nprintln \"\\n===>  xz frame tests \"\n\nif [ $LZMAMODE -eq 1 ]; then\n    datagen > tmp\n    zstd -f --format=xz tmp\n    zstd -f --format=lzma tmp\n    zstd -f tmp\n    cat tmp.xz tmp.lzma tmp.zst tmp.lzma tmp.xz tmp.zst | zstd -d -f -o tmp\n    truncateLastByte tmp.xz | zstd -t > $INTOVOID && die \"incomplete frame not detected !\"\n    truncateLastByte tmp.lzma | zstd -t > $INTOVOID && die \"incomplete frame not detected !\"\n    rm -f tmp*\nelse\n    println \"xz mode not supported\"\nfi\n\nprintln \"\\n===>  lz4 compatibility tests \"\n\nLZ4MODE=1\nzstd --format=lz4 -V || LZ4MODE=0\nif [ $LZ4MODE -eq 1 ]; then\n    println \"lz4 support detected\"\n    LZ4EXE=1\n    lz4 -V || LZ4EXE=0\n    if [ $LZ4EXE -eq 1 ]; then\n        datagen > tmp\n        zstd --format=lz4 -f tmp\n        lz4 -t -v tmp.lz4\n        lz4 -f -m tmp   # ensure result is sent into tmp.lz4, not stdout\n        zstd -d -f -v tmp.lz4\n        rm -f tmp*\n    else\n        println \"lz4 binary not detected\"\n    fi\nelse\n    println \"lz4 mode not supported\"\nfi\n\n\nif [ $LZ4MODE -eq 1 ]; then\n    println \"\\n===>  lz4 frame tests \"\n    datagen > tmp\n    zstd -f --format=lz4 tmp\n    zstd -f tmp\n    cat tmp.lz4 tmp.zst tmp.lz4 tmp.zst | zstd -d -f -o tmp\n    truncateLastByte tmp.lz4 | zstd -t > $INTOVOID && die \"incomplete frame not detected !\"\n    rm -f tmp*\nelse\n    println \"\\nlz4 mode not supported\"\nfi\n\n\nprintln \"\\n===> suffix list test\"\n\n! zstd -d tmp.abc 2> tmplg\n\nif [ $GZIPMODE -ne 1 ]; then\n    grep \".gz\" tmplg > $INTOVOID && die \"Unsupported suffix listed\"\nfi\n\nif [ $LZMAMODE -ne 1 ]; then\n    grep \".lzma\" tmplg > $INTOVOID && die \"Unsupported suffix listed\"\n    grep \".xz\" tmplg > $INTOVOID && die \"Unsupported suffix listed\"\nfi\n\nif [ $LZ4MODE -ne 1 ]; then\n    grep \".lz4\" tmplg > $INTOVOID && die \"Unsupported suffix listed\"\nfi\n\ntouch tmp1\nzstd tmp1 -o tmp1.zstd\nzstd -d -f tmp1.zstd   # support .zstd suffix even though it's not the default suffix\n\nprintln \"\\n===>  tar extension tests \"\n\nrm -f tmp tmp.tar tmp.tzst tmp.tgz tmp.txz tmp.tlz4 tmp1.zstd\n\ndatagen > tmp\ntar -cf tmp.tar tmp\nzstd tmp.tar -o tmp.tzst\nrm -f tmp.tar\nzstd -d tmp.tzst\n[ -e tmp.tar ] || die \".tzst failed to decompress to .tar!\"\nrm -f tmp.tar tmp.tzst\n\nif [ $GZIPMODE -eq 1 ]; then\n    tar -f - -c tmp | gzip > tmp.tgz\n    zstd -d tmp.tgz\n    [ -e tmp.tar ] || die \".tgz failed to decompress to .tar!\"\n    rm -f tmp.tar tmp.tgz\nfi\n\nif [ $LZMAMODE -eq 1 ]; then\n    tar -f - -c tmp | zstd --format=xz > tmp.txz\n    zstd -d tmp.txz\n    [ -e tmp.tar ] || die \".txz failed to decompress to .tar!\"\n    rm -f tmp.tar tmp.txz\nfi\n\nif [ $LZ4MODE -eq 1 ]; then\n    tar -f - -c tmp | zstd --format=lz4 > tmp.tlz4\n    zstd -d tmp.tlz4\n    [ -e tmp.tar ] || die \".tlz4 failed to decompress to .tar!\"\n    rm -f tmp.tar tmp.tlz4\nfi\n\ntouch tmp.t tmp.tz tmp.tzs\n! zstd -d tmp.t\n! zstd -d tmp.tz\n! zstd -d tmp.tzs\n\n\nprintln \"\\n===>  zstd round-trip tests \"\n\nroundTripTest\nroundTripTest -g15K       # TableID==3\nroundTripTest -g127K      # TableID==2\nroundTripTest -g255K      # TableID==1\nroundTripTest -g522K      # TableID==0\nroundTripTest -g519K 6    # greedy, hash chain\nroundTripTest -g517K 16   # btlazy2\nroundTripTest -g516K 19   # btopt\n\nfileRoundTripTest -g500K\n\nprintln \"\\n===>  zstd long distance matching round-trip tests \"\nroundTripTest -g0 \"2 --single-thread --long\"\nroundTripTest -g1000K \"1 --single-thread --long\"\nroundTripTest -g517K \"6 --single-thread --long\"\nroundTripTest -g516K \"16 --single-thread --long\"\nroundTripTest -g518K \"19 --single-thread --long\"\nroundTripTest -g2M \"22 --single-thread --ultra --long\"\nfileRoundTripTest -g5M \"3 --single-thread --long\"\n\n\nroundTripTest -g96K \"5 --single-thread\"\nif [ -n \"$hasMT\" ]\nthen\n    println \"\\n===>  zstdmt round-trip tests \"\n    roundTripTest -g4M \"1 -T0\"\n    roundTripTest -g4M \"1 -T0 --auto-threads=physical\"\n    roundTripTest -g4M \"1 -T0 --auto-threads=logical\"\n    roundTripTest -g8M \"3 -T2\"\n    roundTripTest -g8M \"19 --long\"\n    roundTripTest -g8000K \"2 --threads=2\"\n    fileRoundTripTest -g4M \"19 -T2 -B1M\"\n\n    println \"\\n===>  zstdmt long distance matching round-trip tests \"\n    roundTripTest -g8M \"3 --long=24 -T2\"\n\n    println \"\\n===>  zstdmt environment variable tests \"\n    echo \"multifoo\" >> mt_tmp\n    ZSTD_NBTHREADS=-3 zstd -f mt_tmp # negative value, warn and revert to default setting\n    ZSTD_NBTHREADS=''  zstd -f mt_tmp # empty env var, warn and revert to default setting\n    ZSTD_NBTHREADS=-   zstd -f mt_tmp # malformed env var, warn and revert to default setting\n    ZSTD_NBTHREADS=a   zstd -f mt_tmp # malformed env var, warn and revert to default setting\n    ZSTD_NBTHREADS=+a  zstd -f mt_tmp # malformed env var, warn and revert to default setting\n    ZSTD_NBTHREADS=3a7 zstd -f mt_tmp # malformed env var, warn and revert to default setting\n    ZSTD_NBTHREADS=50000000000 zstd -f mt_tmp # numeric value too large, warn and revert to default setting=\n    ZSTD_NBTHREADS=2  zstd -f mt_tmp # correct usage\n    ZSTD_NBTHREADS=1  zstd -f mt_tmp # correct usage: single thread\n    # temporary envvar changes in the above tests would actually persist in macos /bin/sh\n    unset ZSTD_NBTHREADS\n    rm -f mt_tmp*\n\n    println \"\\n===>  ovLog tests \"\n    datagen -g2MB > tmp\n    refSize=$(zstd tmp -6 -c --zstd=wlog=18         | wc -c)\n    ov9Size=$(zstd tmp -6 -c --zstd=wlog=18,ovlog=9 | wc -c)\n    ov1Size=$(zstd tmp -6 -c --zstd=wlog=18,ovlog=1 | wc -c)\n    if [ \"$refSize\" -eq \"$ov9Size\" ]; then\n        echo ov9Size should be different from refSize\n        exit 1\n    fi\n    if [ \"$refSize\" -eq \"$ov1Size\" ]; then\n        echo ov1Size should be different from refSize\n        exit 1\n    fi\n    if [ \"$ov9Size\" -ge \"$ov1Size\" ]; then\n        echo ov9Size=\"$ov9Size\" should be smaller than ov1Size=\"$ov1Size\"\n        exit 1\n    fi\n\nelse\n    println \"\\n===>  no multithreading, skipping zstdmt tests \"\nfi\n\nrm -f tmp*\n\nprintln \"\\n===>  zstd --list/-l single frame tests \"\ndatagen > tmp1\ndatagen > tmp2\ndatagen > tmp3\nzstd tmp*\nzstd -l ./*.zst\nzstd -lv ./*.zst | grep \"Decompressed Size:\"  # check that decompressed size is present in header\nzstd --list ./*.zst\nzstd --list -v ./*.zst\n\nprintln \"\\n===>  zstd --list/-l multiple frame tests \"\ncat tmp1.zst tmp2.zst > tmp12.zst\ncat tmp12.zst tmp3.zst > tmp123.zst\nzstd -l ./*.zst\nzstd -lv ./*.zst\n\nprintln \"\\n===>  zstd --list/-l error detection tests \"\nzstd -l tmp1 tmp1.zst && die \"-l must fail on non-zstd file\"\nzstd --list tmp* && die \"-l must fail on non-zstd file\"\nzstd -lv tmp1* && die \"-l must fail on non-zstd file\"\nzstd --list -v tmp2 tmp12.zst && die \"-l must fail on non-zstd file\"\n\nprintln \"test : detect truncated compressed file \"\nTEST_DATA_FILE=truncatable-input.txt\nFULL_COMPRESSED_FILE=${TEST_DATA_FILE}.zst\nTRUNCATED_COMPRESSED_FILE=truncated-input.txt.zst\ndatagen -g50000 > $TEST_DATA_FILE\nzstd -f $TEST_DATA_FILE -o $FULL_COMPRESSED_FILE\ndd bs=1 count=100 if=$FULL_COMPRESSED_FILE of=$TRUNCATED_COMPRESSED_FILE\nzstd --list $TRUNCATED_COMPRESSED_FILE && die \"-l must fail on truncated file\"\n\nrm -f $TEST_DATA_FILE\nrm -f $FULL_COMPRESSED_FILE\nrm -f $TRUNCATED_COMPRESSED_FILE\n\nprintln \"\\n===>  zstd --list/-l errors when presented with stdin / no files\"\nzstd -l && die \"-l must fail on empty list of files\"\nzstd -l - && die \"-l does not work on stdin\"\nzstd -l < tmp1.zst && die \"-l does not work on stdin\"\nzstd -l - < tmp1.zst && die \"-l does not work on stdin\"\nzstd -l - tmp1.zst && die \"-l does not work on stdin\"\nzstd -l - tmp1.zst < tmp1.zst && die \"-l does not work on stdin\"\nzstd -l tmp1.zst < tmp2.zst # this will check tmp1.zst, but not tmp2.zst, which is not an error : zstd simply doesn't read stdin in this case. It must not error just because stdin is not a tty\n\nprintln \"\\n===>  zstd --list/-l test with null files \"\ndatagen -g0 > tmp5\nzstd tmp5\nzstd -l tmp5.zst\nzstd -l tmp5* && die \"-l must fail on non-zstd file\"\nzstd -lv tmp5.zst | grep \"Decompressed Size: 0 B (0 B)\"  # check that 0 size is present in header\nzstd -lv tmp5* && die \"-l must fail on non-zstd file\"\n\nprintln \"\\n===>  zstd --list/-l test with no content size field \"\ndatagen -g513K | zstd > tmp6.zst\nzstd -l tmp6.zst\nzstd -lv tmp6.zst | grep \"Decompressed Size:\"  && die \"Field :Decompressed Size: should not be available in this compressed file\"\n\nprintln \"\\n===>   zstd --list/-l test with no checksum \"\nzstd -f --no-check tmp1\nzstd -l tmp1.zst\nzstd -lv tmp1.zst\n\nprintln \"\\n===>  zstd trace tests \"\nzstd -f --trace tmp.trace tmp1\nzstd -f --trace tmp.trace tmp1 tmp2 tmp3\nzstd -f --trace tmp.trace tmp1 tmp2 tmp3 -o /dev/null\nzstd -f --trace tmp.trace tmp1 tmp2 tmp3 --single-thread\nzstd -f --trace tmp.trace -D tmp1 tmp2 tmp3 -o /dev/null\nzstd -f --trace tmp.trace -D tmp1 tmp2 tmp3 -o /dev/null --single-thread\nzstd --trace tmp.trace -t tmp1.zst\nzstd --trace tmp.trace -t tmp1.zst tmp2.zst\nzstd -f --trace tmp.trace -d tmp1.zst\nzstd -f --trace tmp.trace -d tmp1.zst tmp2.zst tmp3.zst\nzstd -D tmp1 tmp2 -c | zstd --trace tmp.trace -t -D tmp1\nzstd -b1e10i0 --trace tmp.trace tmp1\nzstd -b1e10i0 --trace tmp.trace tmp1 tmp2 tmp3\n\nrm -f tmp*\n\n\nprintln \"\\n===>   zstd long distance matching tests \"\nroundTripTest -g0 \" --single-thread --long\"\nroundTripTest -g9M \"2 --single-thread --long\"\n# Test parameter parsing\nroundTripTest -g1M -P50 \"1 --single-thread --long=29\" \" --memory=512MB\"\nroundTripTest -g1M -P50 \"1 --single-thread --long=29 --zstd=wlog=28\" \" --memory=256MB\"\nroundTripTest -g1M -P50 \"1 --single-thread --long=29\" \" --long=28 --memory=512MB\"\nroundTripTest -g1M -P50 \"1 --single-thread --long=29\" \" --zstd=wlog=28 --memory=512MB\"\n\n\nif [ \"$ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP\" -ne \"1\" ]; then\n    println \"\\n===>  zstd long distance matching with optimal parser compressed size tests \"\n    optCSize16=$(datagen -g511K | zstd -16 -c | wc -c)\n    longCSize16=$(datagen -g511K | zstd -16 --long -c | wc -c)\n    optCSize19=$(datagen -g2M | zstd -19 -c | wc -c)\n    longCSize19=$(datagen -g2M | zstd -19 --long -c | wc -c)\n    optCSize19wlog23=$(datagen -g2M | zstd -19 -c  --zstd=wlog=23 | wc -c)\n    longCSize19wlog23=$(datagen -g2M | zstd -19 -c --long=23 | wc -c)\n    if [ \"$longCSize16\" -gt \"$optCSize16\" ]; then\n        echo using --long on compression level 16 should not cause compressed size regression\n        exit 1\n    elif [ \"$longCSize19\" -gt \"$optCSize19\" ]; then\n        echo using --long on compression level 19 should not cause compressed size regression\n        exit 1\n    elif [ \"$longCSize19wlog23\" -gt \"$optCSize19wlog23\" ]; then\n        echo using --long on compression level 19 with wLog=23 should not cause compressed size regression\n        exit 1\n    fi\nfi\n\nprintln \"\\n===>  zstd asyncio tests \"\n\naddFrame() {\n    datagen -g2M -s$2 >> tmp_uncompressed\n    datagen -g2M -s$2 | zstd -1 --format=$1 >> tmp_compressed.zst\n}\n\naddTwoFrames() {\n  addFrame $1 1\n  addFrame $1 2\n}\n\ntestAsyncIO() {\n  roundTripTest -g2M \"3 --asyncio --format=$1\"\n  roundTripTest -g2M \"3 --no-asyncio --format=$1\"\n}\n\nrm -f tmp_compressed tmp_uncompressed\ntestAsyncIO zstd\naddTwoFrames zstd\nif [ $GZIPMODE -eq 1 ]; then\n  testAsyncIO gzip\n  addTwoFrames gzip\nfi\nif [ $LZMAMODE -eq 1 ]; then\n  testAsyncIO lzma\n  addTwoFrames lzma\nfi\nif [ $LZ4MODE -eq 1 ]; then\n  testAsyncIO lz4\n  addTwoFrames lz4\nfi\ncat tmp_uncompressed | $MD5SUM > tmp2\nzstd -d tmp_compressed.zst --asyncio -c | $MD5SUM > tmp1\n$DIFF -q tmp1 tmp2\nrm tmp1\nzstd -d tmp_compressed.zst --no-asyncio -c | $MD5SUM > tmp1\n$DIFF -q tmp1 tmp2\n\nif [ \"$1\" != \"--test-large-data\" ]; then\n    println \"Skipping large data tests\"\n    exit 0\nfi\n\n\n#############################################################################\n\n\nif [ -n \"$hasMT\" ]\nthen\n    println \"\\n===>   adaptive mode \"\n    roundTripTest -g270000000 \" --adapt\"\n    roundTripTest -g27000000 \" --adapt=min=1,max=4\"\n    roundTripTest -g27000000 \" --adapt=min=-2,max=-1\"\n    println \"===>   test: --adapt must fail on incoherent bounds \"\n    datagen > tmp\n    zstd --adapt= tmp && die \"invalid compression parameter\"\n    zstd -f -vv --adapt=min=10,max=9 tmp && die \"--adapt must fail on incoherent bounds\"\n\n    println \"\\n===>   rsyncable mode \"\n    roundTripTest -g10M \" --rsyncable\"\n    roundTripTest -g10M \" --rsyncable -B100K\"\n    println \"===>   test: --rsyncable must fail with --single-thread\"\n    zstd -f -vv --rsyncable --single-thread tmp && die \"--rsyncable must fail with --single-thread\"\nfi\n\nprintln \"\\n===> patch-from=origin tests\"\ndatagen -g1000 -P50 > tmp_dict\ndatagen -g1000 -P10 > tmp_patch\nzstd --patch-from=tmp_dict tmp_patch -o tmp_patch_diff\nzstd -d --patch-from=tmp_dict tmp_patch_diff -o tmp_patch_recon\n$DIFF -s tmp_patch_recon tmp_patch\n\nprintln \"\\n===> alternate syntax: patch-from origin\"\nzstd -f --patch-from tmp_dict tmp_patch -o tmp_patch_diff\nzstd -df --patch-from tmp_dict tmp_patch_diff -o tmp_patch_recon\n$DIFF -s tmp_patch_recon tmp_patch\nrm -rf tmp_*\n\nprintln \"\\n===> patch-from recursive tests\"\nmkdir tmp_dir\ndatagen > tmp_dir/tmp1\ndatagen > tmp_dir/tmp2\ndatagen > tmp_dict\nzstd --patch-from=tmp_dict -r tmp_dir && die\nrm -rf tmp*\n\nprintln \"\\n===> patch-from long mode trigger larger file test\"\nif [ \"$ZSTD_LIB_EXCLUDE_COMPRESSORS_DFAST_AND_UP\" -eq \"1\" ]; then\n    # if binary tree strategies are excluded, the threshold is different\n    datagen -g10000000 > tmp_dict\n    datagen -g10000000 > tmp_patch\nelse\n    datagen -g5000000 > tmp_dict\n    datagen -g5000000 > tmp_patch\nfi\nzstd -15 --patch-from=tmp_dict tmp_patch 2>&1 | grep \"long mode automatically triggered\"\nrm -rf tmp*\n\nprintln \"\\n===> patch-from very large dictionary and file test\"\ndatagen -g550000000 -P0 > tmp_dict\ndatagen -g100000000 -P1 > tmp_patch\nzstd --long=30 -1f --patch-from tmp_dict tmp_patch\nzstd --long=30 -df --patch-from tmp_dict tmp_patch.zst -o tmp_patch_recon\n$DIFF -s tmp_patch_recon tmp_patch\nrm -rf tmp*\n\nprintln \"\\n===> patch-from --stream-size test\"\ndatagen -g1000 -P50 > tmp_dict\ndatagen -g1000 -P10 > tmp_patch\ncat tmp_patch | zstd -f --patch-from=tmp_dict -c -o tmp_patch_diff && die\ncat tmp_patch | zstd -f --patch-from=tmp_dict --stream-size=1000 -c -o tmp_patch_diff\nrm -rf tmp*\n\nprintln \"\\n===>   large files tests \"\n\nroundTripTest -g270000000 1\nroundTripTest -g250000000 2\nroundTripTest -g230000000 3\n\nroundTripTest -g140000000 -P60 4\nroundTripTest -g130000000 -P62 5\nroundTripTest -g120000000 -P65 6\n\nroundTripTest -g70000000 -P70 7\nroundTripTest -g60000000 -P71 8\nroundTripTest -g50000000 -P73 9\n\nroundTripTest -g35000000 -P75 10\nroundTripTest -g30000000 -P76 11\nroundTripTest -g25000000 -P78 12\n\nroundTripTest -g18000013 -P80 13\nroundTripTest -g18000014 -P80 14\nroundTripTest -g18000015 -P81 15\nroundTripTest -g18000016 -P84 16\nroundTripTest -g18000017 -P88 17\nroundTripTest -g18000018 -P94 18\nroundTripTest -g18000019 -P96 19\n\nroundTripTest -g5000000000 -P99 \"1 --zstd=wlog=25\"\nroundTripTest -g3700000000 -P0 \"1 --zstd=strategy=6,wlog=25\"   # ensure btlazy2 can survive an overflow rescale\n\nfileRoundTripTest -g4193M -P99 1\n\n\nprintln \"\\n===>   zstd long, long distance matching round-trip tests \"\nroundTripTest -g270000000 \"1 --single-thread --long\"\nroundTripTest -g130000000 -P60 \"5 --single-thread --long\"\nroundTripTest -g35000000 -P70 \"8 --single-thread --long\"\nroundTripTest -g18000001 -P80  \"18 --single-thread --long\"\n# Test large window logs\nroundTripTest -g700M -P50 \"1 --single-thread --long=29\"\nroundTripTest -g600M -P50 \"1 --single-thread --long --zstd=wlog=29,clog=28\"\n\n\nif [ -n \"$hasMT\" ]\nthen\n    println \"\\n===>   zstdmt long round-trip tests \"\n    roundTripTest -g80000000 -P99 \"19 -T2\" \" \"\n    roundTripTest -g5000000000 -P99 \"1 -T2\" \" \"\n    roundTripTest -g500000000 -P97 \"1 -T999\" \" \"\n    fileRoundTripTest -g4103M -P98 \" -T0\" \" \"\n    roundTripTest -g400000000 -P97 \"1 --long=24 -T2\" \" \"\n    # Exposes the bug in https://github.com/facebook/zstd/pull/1678\n    # This test fails on 4 different travis builds at the time of writing\n    # because it needs to allocate 8 GB of memory.\n    # roundTripTest -g10G -P99 \"1 -T1 --long=31 --zstd=clog=27 --fast=1000\"\nelse\n    println \"\\n**** no multithreading, skipping zstdmt tests **** \"\nfi\n\n\nprintln \"\\n===>  cover dictionary builder : advanced options \"\n\nTESTFILE=\"$PRGDIR\"/zstdcli.c\ndatagen > tmpDict\nprintln \"- Create first dictionary\"\nzstd --train-cover=k=46,d=8,split=80 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict\ncp \"$TESTFILE\" tmp\nzstd -f tmp -D tmpDict\nzstd -f tmp -D tmpDict --patch-from=tmpDict && die \"error: can't use -D and --patch-from=#at the same time\"\nzstd -d tmp.zst -D tmpDict -fo result\n$DIFF \"$TESTFILE\" result\nzstd --train-cover=k=56,d=8 && die \"Create dictionary without input file (should error)\"\nprintln \"- Create second (different) dictionary\"\nzstd --train-cover=k=56,d=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c \"$PRGDIR\"/*.h -o tmpDictC\nzstd -d tmp.zst -D tmpDictC -fo result && die \"wrong dictionary not detected!\"\nprintln \"- Create dictionary using shrink-dict flag\"\nzstd --train-cover=steps=256,shrink \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpShrinkDict\nzstd --train-cover=steps=256,shrink=1 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpShrinkDict1\nzstd --train-cover=steps=256,shrink=5 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpShrinkDict2\nzstd --train-cover=shrink=5,steps=256 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpShrinkDict3\nprintln \"- Create dictionary with short dictID\"\nzstd --train-cover=k=46,d=8,split=80 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c --dictID=1 -o tmpDict1\ncmp tmpDict tmpDict1 && die \"dictionaries should have different ID !\"\nprintln \"- Create dictionary with size limit\"\nzstd --train-cover=steps=8 \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c -o tmpDict2 --maxdict=4K\nprintln \"- Compare size of dictionary from 90% training samples with 80% training samples\"\nzstd --train-cover=split=90 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nzstd --train-cover=split=80 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Create dictionary using all samples for both training and testing\"\nzstd --train-cover=split=100 -r \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\nprintln \"- Test -o before --train-cover\"\nrm -f tmpDict dictionary\nzstd -o tmpDict --train-cover \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f tmpDict\nzstd --train-cover \"$TESTDIR\"/*.c \"$PRGDIR\"/*.c\ntest -f dictionary\nrm -f tmp* dictionary\n\nrm -f tmp*\n", "num_lines": 1842}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\nset -u\nset -x\n\n\nSCRIPT_DIR=$(cd \"$(dirname \"$0\")\" && pwd)\nPROG_DIR=\"$SCRIPT_DIR/../programs\"\n\nZSTD=\"$PROG_DIR/zstd\"\nZSTD_COMPRESS=\"$PROG_DIR/zstd-compress\"\nZSTD_DECOMPRESS=\"$PROG_DIR/zstd-decompress\"\nZSTD_NOLEGACY=\"$PROG_DIR/zstd-nolegacy\"\nZSTD_DICTBUILDER=\"$PROG_DIR/zstd-dictBuilder\"\nZSTD_FRUGAL=\"$PROG_DIR/zstd-frugal\"\nZSTD_NOMT=\"$PROG_DIR/zstd-nomt\"\n\nprintln() {\n    printf '%b\\n' \"${*}\"\n}\n\ndie() {\n    println \"$@\" 1>&2\n    exit 1\n}\n\nsymbol_present() {\n\t(nm $1 || echo \"symbol_present $@ failed\") | grep $2\n}\n\nsymbol_not_present() {\n\tsymbol_present $@ && die \"Binary '$1' mistakenly contains symbol '$2'\" ||:\n}\n\ncompress_not_present() {\n\tsymbol_not_present \"$1\" ZSTD_compress\n}\n\ndecompress_not_present() {\n\tsymbol_not_present \"$1\" ZSTD_decompress\n}\n\ndict_not_present() {\n\tsymbol_not_present \"$1\" ZDICT_\n\tsymbol_not_present \"$1\" COVER_\n}\n\ncliextra_not_present() {\n\tsymbol_not_present \"$1\" TRACE_\n\tsymbol_not_present \"$1\" BMK_\n}\n\nlegacy_not_present() {\n\tsymbol_not_present \"$1\" ZSTDv0\n}\n\ntest_help() {\n\t\"$1\" --help | grep -- \"$2\"\n}\n\ntest_no_help() {\n\ttest_help $@ && die \"'$1' supports '$2' when it shouldn't\" ||:\n}\n\nextras_not_present() {\n\tdict_not_present $@\n\tlegacy_not_present $@\n\tcliextra_not_present $@\n\ttest_no_help $@ \"--train\"\n\ttest_no_help $@ \"-b#\"\n}\n\ntest_compress() {\n\techo \"hello\" | \"$1\" | \"$ZSTD\" -t\n}\n\ntest_decompress() {\n\techo \"hello\" | \"$ZSTD\" | \"$1\" -t\n}\n\ntest_zstd() {\n\ttest_compress $@\n\ttest_decompress $@\n}\n\nextras_not_present \"$ZSTD_FRUGAL\"\nextras_not_present \"$ZSTD_COMPRESS\"\nextras_not_present \"$ZSTD_DECOMPRESS\"\n\ncompress_not_present \"$ZSTD_DECOMPRESS\"\n\ndecompress_not_present \"$ZSTD_COMPRESS\"\ndecompress_not_present \"$ZSTD_DICTBUILDER\"\n\ncliextra_not_present \"$ZSTD_DICTBUILDER\"\n\nlegacy_not_present \"$ZSTD_DICTBUILDER\"\nlegacy_not_present \"$ZSTD_NOLEGACY\"\n\nsymbol_not_present \"$ZSTD\" ZSTDv01\nsymbol_not_present \"$ZSTD\" ZSTDv02\nsymbol_not_present \"$ZSTD\" ZSTDv03\nsymbol_not_present \"$ZSTD\" ZSTDv04\n\ntest_compress \"$ZSTD_COMPRESS\"\ntest_decompress \"$ZSTD_DECOMPRESS\"\n\ntest_zstd \"$ZSTD_FRUGAL\"\ntest_zstd \"$ZSTD_NOLEGACY\"\n\ntest_help \"$ZSTD\" '-b#'\ntest_help \"$ZSTD\" --train\ntest_help \"$ZSTD_DICTBUILDER\" --train\n\nprintln \"Success!\"\n", "num_lines": 116}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nprintln \"+ zstd -h\"\nzstd -h\nprintln \"+ zstd -H\"\nzstd -H\nprintln \"+ zstd --help\"\nzstd --help\n", "num_lines": 11}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"some data\" > file\n\nprintln \"+ zstd --memory=32LB file\"\nzstd --memory=32LB file && die \"Should not allow bogus suffix\"\nprintln \"+ zstd --memory=32LiB file\"\nzstd --memory=32LiB file && die \"Should not allow bogus suffix\"\nprintln \"+ zstd --memory=32A file\"\nzstd --memory=32A file && die \"Should not allow bogus suffix\"\nprintln \"+ zstd --memory=32r82347dn83 file\"\nzstd --memory=32r82347dn83 file && die \"Should not allow bogus suffix\"\nprintln \"+ zstd --memory=32asbdf file\"\nzstd --memory=32asbdf file && die \"Should not allow bogus suffix\"\nprintln \"+ zstd --memory=hello file\"\nzstd --memory=hello file && die \"Should not allow non-numeric parameter\"\nprintln \"+ zstd --memory=1 file\"\nzstd -q --memory=1 file && die \"Should allow numeric parameter without suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1K file\"\nzstd -q --memory=1K file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1KB file\"\nzstd -q --memory=1KB file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1KiB file\"\nzstd -q --memory=1KiB file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1M file\"\nzstd -q --memory=1M file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1MB file\"\nzstd -q --memory=1MB file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\nprintln \"+ zstd --memory=1MiB file\"\nzstd -q --memory=1MiB file && die \"Should allow numeric parameter with expected suffix\"\nrm file.zst\n\nrm file\nexit 0\n", "num_lines": 41}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nprintln \"+ zstd -r * --output-dir-mirror=\\\"\\\"\"\nzstd -r * --output-dir-mirror=\"\" && die \"Should not allow empty output dir!\"\nprintln \"+ zstd -r * --output-dir-flat=\\\"\\\"\"\nzstd -r * --output-dir-flat=\"\" && die \"Should not allow empty output dir!\"\nexit 0\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nzstd -V\nzstd --version\n", "num_lines": 7}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nprintln \"+ good path\"\nzstdgrep \"1234\" file file.zst\nprintln \"+ bad path\"\nzstdgrep \"1234\" bad.zst\n", "num_lines": 9}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nprintln \"+ good path\"\nzstdless file.zst\nprintln \"+ pass parameters\"\nzstdless -N file.zst # This parameter does not produce line #s when piped, but still serves to test that the flag went to less and not zstd\nprintln \"+ bad path\"\nzstdless bad.zst >&2\n", "num_lines": 11}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. \"$COMMON/platform.sh\"\n\nzstd_supports_format()\n{\n\tzstd -h | grep > $INTOVOID -- \"--format=$1\"\n}\n\nformat_extension()\n{\n\tif [ \"$1\" = \"zstd\" ]; then\n\t\tprintf \"zst\"\n\telif [ \"$1\" = \"gzip\" ]; then\n\t\tprintf \"gz\"\n\telse\n\t\tprintf \"$1\"\n\tfi\n}\n", "num_lines": 20}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": ". \"$COMMON/platform.sh\"\n\nMTIME=\"stat -c %Y\"\ncase \"$UNAME\" in\n    Darwin | FreeBSD | OpenBSD | NetBSD) MTIME=\"stat -f %m\" ;;\nesac\n\nassertSameMTime() {\n    MT1=$($MTIME \"$1\")\n    MT2=$($MTIME \"$2\")\n    echo MTIME $MT1 $MT2\n    [ \"$MT1\" = \"$MT2\" ] || die \"mtime on $1 doesn't match mtime on $2 ($MT1 != $MT2)\"\n}\n", "num_lines": 14}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": ". \"$COMMON/platform.sh\"\n\nGET_PERMS=\"stat -c %a\"\ncase \"$UNAME\" in\n    Darwin | FreeBSD | OpenBSD | NetBSD) GET_PERMS=\"stat -f %Lp\" ;;\nesac\n\nassertFilePermissions() {\n    STAT1=$($GET_PERMS \"$1\")\n    STAT2=$2\n    [ \"$STAT1\" = \"$STAT2\" ] || die \"permissions on $1 don't match expected ($STAT1 != $STAT2)\"\n}\n\nassertSamePermissions() {\n    STAT1=$($GET_PERMS \"$1\")\n    STAT2=$($GET_PERMS \"$2\")\n    [ \"$STAT1\" = \"$STAT2\" ] || die \"permissions on $1 don't match those on $2 ($STAT1 != $STAT2)\"\n}\n", "num_lines": 19}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nUNAME=$(uname)\n\nisWindows=false\nINTOVOID=\"/dev/null\"\ncase \"$UNAME\" in\n  GNU) DEVDEVICE=\"/dev/random\" ;;\n  *) DEVDEVICE=\"/dev/zero\" ;;\nesac\ncase \"$OS\" in\n  Windows*)\n    isWindows=true\n    INTOVOID=\"NUL\"\n    DEVDEVICE=\"NUL\"\n    ;;\nesac\n\ncase \"$UNAME\" in\n  Darwin) MD5SUM=\"md5 -r\" ;;\n  FreeBSD) MD5SUM=\"gmd5sum\" ;;\n  NetBSD) MD5SUM=\"md5 -n\" ;;\n  OpenBSD) MD5SUM=\"md5\" ;;\n  *) MD5SUM=\"md5sum\" ;;\nesac\n\nDIFF=\"diff\"\ncase \"$UNAME\" in\n  SunOS) DIFF=\"gdiff\" ;;\nesac\n\nif echo hello | zstd -v -T2 2>&1 > $INTOVOID | grep -q 'multi-threading is disabled'\nthen\n    hasMT=\"\"\nelse\n    hasMT=\"true\"\nfi\n", "num_lines": 38}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test --adapt\nzstd -f file --adapt -c | zstd -t\n\ndatagen -g100M > file100M\n\n# Pick parameters to force fast adaptation, even on slow systems\nzstd --adapt -vvvv -19 --zstd=wlog=10 file100M -o /dev/null 2>&1 | grep -q \"faster speed , lighter compression\"\n\n# Adaption still happens with --no-progress\nzstd --no-progress --adapt -vvvv -19 --zstd=wlog=10 file100M -o /dev/null 2>&1 | grep -q \"faster speed , lighter compression\"\n", "num_lines": 15}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Uncomment the set -v line for debugging\n# set -v\n\n# Test compression flags and check that they work\nzstd file                 ; zstd -t file.zst\nzstd -f file              ; zstd -t file.zst\nzstd -f -z file           ; zstd -t file.zst\nzstd -f -k file           ; zstd -t file.zst\nzstd -f -C file           ; zstd -t file.zst\nzstd -f --check file      ; zstd -t file.zst\nzstd -f --no-check file   ; zstd -t file.zst\nzstd -f -- file           ; zstd -t file.zst\n\n# Test output file compression\nzstd -o file-out.zst ; zstd -t file-out.zst\nzstd -fo file-out.zst; zstd -t file-out.zst\n\n# Test compression to stdout\nzstd -c file       | zstd -t\nzstd --stdout file | zstd -t\nprintln bob | zstd | zstd -t\n\n# Test keeping input file when compressing to stdout in gzip mode\nif $(command -v $ZSTD_SYMLINK_DIR/gzip); then\n    $ZSTD_SYMLINK_DIR/gzip -c file       | zstd -t ; test -f file\n    $ZSTD_SYMLINK_DIR/gzip --stdout file | zstd -t ; test -f file\nfi\n\n# Test --rm\ncp file file-rm\nzstd --rm file-rm; zstd -t file-rm.zst\ntest ! -f file-rm\n", "num_lines": 37}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test --[no-]compress-literals\nzstd file --no-compress-literals -1 -c       | zstd -t\nzstd file --no-compress-literals -19 -c      | zstd -t\nzstd file --no-compress-literals --fast=1 -c | zstd -t\nzstd file --compress-literals -1 -c          | zstd -t\nzstd file --compress-literals --fast=1 -c    | zstd -t\n", "num_lines": 11}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. \"$COMMON/format.sh\"\n\nset -e\n\n# Test --format\nzstd --format=zstd file -f\nzstd -t file.zst\nfor format in \"gzip\" \"lz4\" \"xz\" \"lzma\"; do\n\tif zstd_supports_format $format; then\n\t\tzstd --format=$format file\n\t\tzstd -t file.$(format_extension $format)\n\t\tzstd -c --format=$format file | zstd -t --format=$format\n\tfi\ndone\n", "num_lines": 17}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nGOLDEN_DIR=\"$ZSTD_REPO_DIR/tests/golden-compression/\"\ncp -r \"$GOLDEN_DIR\" golden/\n\nzstd -rf golden/ --output-dir-mirror golden-compressed/\nzstd -r -t golden-compressed/\n\nzstd --target-compressed-block-size=1024 -rf golden/ --output-dir-mirror golden-compressed/\nzstd -r -t golden-compressed/\n\n# PR #3517 block splitter corruption test\nzstd -rf -19 --zstd=mml=7 golden/ --output-dir-mirror golden-compressed/\nzstd -r -t golden-compressed/", "num_lines": 16}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Uncomment the set -v line for debugging\n# set -v\n\n# Test gzip specific compression option\nif $(command -v $ZSTD_SYMLINK_DIR/gzip); then\n    $ZSTD_SYMLINK_DIR/gzip --fast file ; $ZSTD_SYMLINK_DIR/gzip -d file.gz\n    $ZSTD_SYMLINK_DIR/gzip --best file ; $ZSTD_SYMLINK_DIR/gzip -d file.gz\n\n    # Test -n / --no-name: do not embed original filename in archive\n    $ZSTD_SYMLINK_DIR/gzip -n file           ; grep -qv file file.gz  ; $ZSTD_SYMLINK_DIR/gzip -d file.gz\n    $ZSTD_SYMLINK_DIR/gzip --no-name file    ; grep -qv file file.gz  ; $ZSTD_SYMLINK_DIR/gzip -d file.gz\n    $ZSTD_SYMLINK_DIR/gzip -c --no-name file | grep -qv file\nfi\n", "num_lines": 18}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -v\n\ndatagen > file\n\n# Compress with various levels and ensure that their sizes are ordered\nzstd --fast=10 file -o file-f10.zst -q\nzstd --fast=1 file -o file-f1.zst -q\nzstd -1 file -o file-1.zst -q\nzstd -19 file -o file-19.zst -q\n\nzstd -t file-f10.zst file-f1.zst file-1.zst file-19.zst\n\ncmp_size -lt file-19.zst file-1.zst\ncmp_size -lt file-1.zst file-f1.zst\ncmp_size -lt file-f1.zst file-f10.zst\n\n# Test default levels\nzstd --fast file -f -q\ncmp file.zst file-f1.zst || die \"--fast is not level -1\"\n\nzstd -0 file -o file-0.zst -q\nzstd -f file -q\ncmp file.zst file-0.zst || die \"Level 0 is not the default level\"\n\n# Test level clamping\nzstd -99 file -o file-99.zst -q\ncmp file-19.zst file-99.zst || die \"Level 99 is clamped to 19\"\nzstd --fast=200000 file -c | zstd -t\n\nzstd -5000000000 -f file       && die \"Level too large, must fail\" ||:\nzstd --fast=5000000000 -f file && die \"Level too large, must fail\" ||:\n\n# Test setting a level through the environment variable\nZSTD_CLEVEL=-10 zstd file -o file-f10-env.zst -q\nZSTD_CLEVEL=1 zstd file -o file-1-env.zst -q\nZSTD_CLEVEL=+19 zstd file -o file-19-env.zst -q\nZSTD_CLEVEL=+99 zstd file -o file-99-env.zst -q\n\ncmp file-f10.zst file-f10-env.zst || die \"Environment variable failed to set level\"\ncmp file-1.zst file-1-env.zst || die \"Environment variable failed to set level\"\ncmp file-19.zst file-19-env.zst || die \"Environment variable failed to set level\"\ncmp file-99.zst file-99-env.zst || die \"Environment variable failed to set level\"\n\n# Test invalid environment clevel is the default level\nzstd -f file -q\nZSTD_CLEVEL=- zstd -f file -o file-env.zst -q      ; cmp file.zst file-env.zst\nZSTD_CLEVEL=+ zstd -f file -o file-env.zst -q      ; cmp file.zst file-env.zst\nZSTD_CLEVEL=a zstd -f file -o file-env.zst -q      ; cmp file.zst file-env.zst\nZSTD_CLEVEL=-a zstd -f file -o file-env.zst -q     ; cmp file.zst file-env.zst\nZSTD_CLEVEL=+a zstd -f file -o file-env.zst -q     ; cmp file.zst file-env.zst\nZSTD_CLEVEL=3a7 zstd -f file -o file-env.zst -q    ; cmp file.zst file-env.zst\nZSTD_CLEVEL=5000000000 zstd -f file -o file-env.zst -q ; cmp file.zst file-env.zst\n\n# Test environment clevel is overridden by command line\nZSTD_CLEVEL=10 zstd -f file -1 -o file-1-env.zst -q\nZSTD_CLEVEL=10 zstd -f file --fast=1 -o file-f1-env.zst -q\n\ncmp file-1.zst file-1-env.zst  || die \"Environment variable not overridden\"\ncmp file-f1.zst file-f1-env.zst || die \"Environment variable not overridden\"\n", "num_lines": 63}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test --long\nzstd -f file --long   ; zstd -t file.zst\nzstd -f file --long=20; zstd -t file.zst\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test multi-threaded flags\nzstd --single-thread file -f -q         ; zstd -t file.zst\nzstd -T2 -f file -q                     ; zstd -t file.zst\nzstd --rsyncable -f file -q             ; zstd -t file.zst\nzstd -T0 -f file -q                     ; zstd -t file.zst\nzstd -T0 --auto-threads=logical -f file -q ; zstd -t file.zst\nzstd -T0 --auto-threads=physical -f file -q ; zstd -t file.zst\n\n# multi-thread decompression warning test\nzstd -T0 -f file -q                     ; zstd -t file.zst; zstd -T0 -d file.zst -o file3\nzstd -T0 -f file -q                     ; zstd -t file.zst; zstd -T2 -d file.zst -o file4\n", "num_lines": 16}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n# setup\necho \"file1\" > file1\necho \"file2\" > file2\n\necho \"Test zstd ./file1 - file2\"\nrm -f ./file*.zst\necho \"stdin\" | zstd ./file1 - ./file2 | zstd -d\ncat file1.zst | zstd -d\ncat file2.zst | zstd -d\n\necho \"Test zstd -d ./file1.zst - file2.zst\"\nrm ./file1 ./file2\necho \"stdin\" | zstd - | zstd -d ./file1.zst - file2.zst\ncat file1\ncat file2\n\necho \"zstd -d ./file1.zst - file2.zst -c\"\necho \"stdin\" | zstd | zstd -d ./file1.zst - file2.zst -c\n", "num_lines": 22}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test --[no-]row-match-finder\nzstd file -7f --row-match-finder\nzstd file -7f --no-row-match-finder\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n# Test stream size & hint\ndatagen -g7654 | zstd --stream-size=7654 | zstd -t\ndatagen -g7654 | zstd --size-hint=7000   | zstd -t\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n. \"$COMMON/platform.sh\"\n\nzstd < file -vv -19 -o file.19.zst\nzstd -vv -l file.19.zst\n\nzstd < file -vv -19 --long -o file.19.long.zst\nzstd -vv -l file.19.long.zst\n", "num_lines": 12}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\ndatagen -g1G > file\nzstd --long=30 -1 --single-thread --no-content-size -f file\nzstd -l -v file.zst\n\n# We want to ignore stderr (its outputting \"*** zstd command line interface\n# 64-bits v1.5.3, by Yann Collet ***\")\n\nrm file file.zst\n", "num_lines": 10}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nGOLDEN_DIR=\"$ZSTD_REPO_DIR/tests/golden-decompression-errors/\"\n\nfor file in \"$GOLDEN_DIR\"/*; do\n    zstd -t $file && die \"should have detected an error\"\ndone\nexit 0\n\n", "num_lines": 12}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nGOLDEN_DIR=\"$ZSTD_REPO_DIR/tests/golden-decompression/\"\n\nzstd -r -t \"$GOLDEN_DIR\"\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\n. \"$COMMON/platform.sh\"\n\necho \"\" > 1\necho \"2\" > 2\necho \"23\" > 3\necho \"234\" > 4\necho \"some data\" > file\n\nprintln \"+ passthrough enabled\"\n\nzstd file\n\n# Test short files\nzstd -dc --pass-through 1 2 3 4\n\n# Test *cat symlinks\nzstdcat file\n\"$ZSTD_SYMLINK_DIR/zcat\" file\n\"$ZSTD_SYMLINK_DIR/gzcat\" file\n\n# Test multiple files with mix of compressed & not\nzstdcat file file.zst\nzstdcat file.zst file\n\n# Test --pass-through\nzstd -dc --pass-through file\nzstd -d --pass-through file -o pass-through-file\n\n# Test legacy implicit passthrough with -fc\nzstd -dcf file\nzstd -dcf file file.zst\nzstd -df < file\nzstd -dcf < file file.zst -\nzstd -dcf < file.zst file -\n\n$DIFF file pass-through-file\n\nprintln \"+ passthrough disabled\"\n\n# Test *cat\nzstdcat --no-pass-through file && die \"should fail\"\n\"$ZSTD_SYMLINK_DIR/zcat\" --no-pass-through file && die \"should fail\"\n\"$ZSTD_SYMLINK_DIR/gzcat\" --no-pass-through file && die \"should fail\"\n# Test zstd without implicit passthrough\nzstd -d file -o no-pass-through-file && die \"should fail\"\nzstd -d < file && die \"should fail\"\n\n# Test legacy implicit passthrough with -fc\nzstd --no-pass-through -dcf file && die \"should fail\"\nzstd --no-pass-through -dcf file file.zst && die \"should fail\"\nzstd --no-pass-through -df < file && die \"should fail\"\nzstd --no-pass-through -dcf < file file.zst - && die \"should fail\"\nzstd --no-pass-through -dcf < file.zst file - && die \"should fail\" ||:\n", "num_lines": 58}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\nfor i in $(seq 50); do\n    datagen -s$i > file$i\ndone\ntouch empty\n\nset -v\nzstd -q --train empty file*\n", "num_lines": 10}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nset -v\nzstd --train\n", "num_lines": 4}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. \"$COMMON/platform.sh\"\n\nset -e\n\nif [ false ]; then\n\tfor seed in $(seq 100); do\n\t\tdatagen -g1000 -s$seed > file$seed\n\tdone\n\n\tzstd --train -r . -o dict0 -qq\n\n\tfor seed in $(seq 101 200); do\n\t\tdatagen -g1000 -s$seed > file$seed\n\tdone\n\n\tzstd --train -r . -o dict1 -qq\n\n\t[ \"$($MD5SUM < dict0)\" != \"$($MD5SUM < dict1)\" ] || die \"dictionaries must not match\"\n\n\tdatagen -g1000 -s0 > file0\nfi\n\nset -v\nzstd files/0 -D dicts/0 -q\nzstd -t files/0.zst -D dicts/0\nzstd -t files/0.zst -D dicts/1 && die \"Must fail\" ||:\nzstd -t files/0.zst            && die \"Must fail\" ||:\n", "num_lines": 30}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nGOLDEN_COMP_DIR=\"$ZSTD_REPO_DIR/tests/golden-compression/\"\nGOLDEN_DICT_DIR=\"$ZSTD_REPO_DIR/tests/golden-dictionaries/\"\n\nzstd -D \"$GOLDEN_DICT_DIR/http-dict-missing-symbols\" \"$GOLDEN_COMP_DIR/http\" -o http.zst\nzstd -D \"$GOLDEN_DICT_DIR/http-dict-missing-symbols\" -t http.zst\n", "num_lines": 10}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n# motivated by issue #3523\n\ndatagen > file\nmkdir out\nchmod 000 out\n\nzstd file -q --trace-file-stat -o out/file.zst\nzstd -tq out/file.zst\n\nchmod 777 out\n", "num_lines": 13}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen > file\nchmod 642 file\n\nzstd file -q --trace-file-stat -o file.zst\nzstd -tq file.zst\n", "num_lines": 10}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen > file\n\nzstd file -cq --trace-file-stat > file.zst\nzstd -tq file.zst\n", "num_lines": 9}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen > file\n\nzstd < file -q --trace-file-stat -o file.zst\nzstd -tq file.zst\n", "num_lines": 9}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen > file\n\nzstd < file -cq --trace-file-stat > file.zst\nzstd -tq file.zst\n", "num_lines": 9}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen | zstd -q > file.zst\nchmod 642 file.zst\n\nzstd -dq --trace-file-stat file.zst\n", "num_lines": 9}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen | zstd -q > file.zst\n\nzstd -dcq --trace-file-stat file.zst > file\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen | zstd -q > file.zst\n\nzstd -dcq --trace-file-stat < file.zst -o file\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\ndatagen | zstd -q > file.zst\n\nzstd -dcq --trace-file-stat < file.zst > file\n", "num_lines": 8}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n#!/bin/sh\n\n. \"$COMMON/platform.sh\"\n\nset -e\n\necho hello > hello\necho world > world\n\nzstd -q hello world\n\nprintln >&2 \"Tests cases where progress information should not be printed\"\n\nfor args in \\\n\t\"\" \\\n\t\"--fake-stderr-is-console -q\" \\\n\t\"--fake-stderr-is-console -qq --progress\" \\\n\t\"--no-progress --fake-stderr-is-console\" \\\n\t\"--no-progress --fake-stderr-is-console -v\"\ndo\n\tprintln >&2 \"args = $args\"\n\tprintln >&2 \"compress file to file\"\n\tzstd $args -f hello\n\tprintln >&2 \"compress pipe to pipe\"\n\tzstd $args < hello > $INTOVOID\n\tprintln >&2 \"compress pipe to file\"\n\tzstd $args < hello -fo hello.zst\n\tprintln >&2 \"compress file to pipe\"\n\tzstd $args hello -c > $INTOVOID\n\tprintln >&2 \"compress 2 files\"\n\tzstd $args -f hello world\n\n\tprintln >&2 \"decompress file to file\"\n\tzstd $args -d -f hello.zst\n\tprintln >&2 \"decompress pipe to pipe\"\n\tzstd $args -d < hello.zst > $INTOVOID\n\tprintln >&2 \"decompress pipe to file\"\n\tzstd $args -d < hello.zst -fo hello\n\tprintln >&2 \"decompress file to pipe\"\n\tzstd $args -d hello.zst -c > $INTOVOID\n\tprintln >&2 \"decompress 2 files\"\n\tzstd $args -d -f hello.zst world.zst\n\tprintln >&2 \"\"\ndone\n", "num_lines": 47}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n\n. \"$COMMON/platform.sh\"\n\nset -e\n\nprintln >&2 \"Tests cases where progress information should be printed\"\n\necho hello > hello\necho world > world\n\nzstd -q hello world\n\nfor args in \\\n\t\"--progress\" \\\n\t\"--fake-stderr-is-console\" \\\n\t\"--progress --fake-stderr-is-console -q\"; do\n\tprintln >&2 \"args = $args\"\n\tprintln >&2 \"compress file to file\"\n\tzstd $args -f hello\n\tprintln >&2 \"compress pipe to pipe\"\n\tzstd $args < hello > $INTOVOID\n\tprintln >&2 \"compress pipe to file\"\n\tzstd $args < hello -fo hello.zst\n\tprintln >&2 \"compress file to pipe\"\n\tzstd $args hello -c > $INTOVOID\n\tprintln >&2 \"compress 2 files\"\n\tzstd $args -f hello world\n\n\tprintln >&2 \"decompress file to file\"\n\tzstd $args -d -f hello.zst\n\tprintln >&2 \"decompress pipe to pipe\"\n\tzstd $args -d < hello.zst > $INTOVOID\n\tprintln >&2 \"decompress pipe to file\"\n\tzstd $args -d < hello.zst -fo hello\n\tprintln >&2 \"decompress file to pipe\"\n\tzstd $args -d hello.zst -c > $INTOVOID\n\tprintln >&2 \"decompress 2 files\"\n\tzstd $args -d -f hello.zst world.zst\n\tprintln >&2 \"\"\ndone\n", "num_lines": 42}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n# Test zstdcat symlink in bin/\nzstdcat hello.zst\nzstdcat hello.zst world\nzstdcat hello world.zst\nzstdcat hello.zst world.zst\n\n# Test local zstdcat symlink\nln -s $(which zstd) ./zstdcat\n./zstdcat hello.zst\n", "num_lines": 13}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Test the obsolescent GZIP environment variable.\n\n# Copyright 2015-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\n#echo PATH=$PATH\n#gzip --version\n\necho a >exp || framework_failure_\ngzip <exp >in || framework_failure_\n\nfail=0\nGZIP=-qv gzip -d <in >out 2>err || fail=1\ncompare exp out || fail=1\n\nfor badopt in -- -c --stdout -d --decompress -f --force -h --help -k --keep \\\n  -l --list -L --license -r --recursive -Sxxx --suffix=xxx '--suffix xxx' \\\n  -t --test -V --version\ndo\n  GZIP=$badopt gzip -d <in >out 2>err && fail=1\ndone\n\nfor goodopt in -n --no-name -N --name -q --quiet -v --verbose \\\n  -1 --fast -2 -3 -4 -5 -6 -7 -8 -9 --best\ndo\n  GZIP=$goodopt gzip -d <in >out 2>err || fail=1\n  compare exp out || fail=1\ndone\n\nExit $fail\n", "num_lines": 47}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Before gzip-1.4, gzip -d would segfault on some inputs.\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\n# This test case was provided by Aki Helin.\nprintf '\\037\\235\\220\\0\\0\\0\\304' > helin.gz || framework_failure_\nprintf '\\0\\0' > exp || framework_failure_\n\nfail=0\n\ngzip -dc helin.gz > out || fail=1\ncompare exp out || fail=1\n\nExit $fail\n", "num_lines": 32}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# Make sure all these programs work properly\n# when invoked with --help or --version.\n\n# Copyright (C) 2000-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n# Ensure that $SHELL is set to *some* value and exported.\n# This is required for dircolors, which would fail e.g., when\n# invoked via debuild (which removes SHELL from the environment).\ntest \"x$SHELL\" = x && SHELL=/bin/sh\nexport SHELL\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nexpected_failure_status_chroot=125\nexpected_failure_status_env=125\nexpected_failure_status_nice=125\nexpected_failure_status_nohup=125\nexpected_failure_status_stdbuf=125\nexpected_failure_status_su=125\nexpected_failure_status_timeout=125\nexpected_failure_status_printenv=2\nexpected_failure_status_tty=3\nexpected_failure_status_sort=2\nexpected_failure_status_expr=3\nexpected_failure_status_lbracket=2\nexpected_failure_status_dir=2\nexpected_failure_status_ls=2\nexpected_failure_status_vdir=2\n\nexpected_failure_status_cmp=2\nexpected_failure_status_zcmp=2\nexpected_failure_status_sdiff=2\nexpected_failure_status_diff3=2\nexpected_failure_status_diff=2\nexpected_failure_status_zdiff=2\nexpected_failure_status_zgrep=2\nexpected_failure_status_zegrep=2\nexpected_failure_status_zfgrep=2\n\nexpected_failure_status_grep=2\nexpected_failure_status_egrep=2\nexpected_failure_status_fgrep=2\n\ntest \"$built_programs\" \\\n  || fail_ \"built_programs not specified!?!\"\n\ntest \"$VERSION\" \\\n  || fail_ \"set envvar VERSION; it is required for a PATH sanity-check\"\n\n# Extract version from --version output of the first program\nfor i in $built_programs; do\n  v=$(env $i --version | sed -n '1s/.* //p;q')\n  break\ndone\n\n# Ensure that it matches $VERSION.\ntest \"x$v\" = \"x$VERSION\" \\\n  || fail_ \"--version-\\$VERSION mismatch\"\n\nfor lang in C fr da; do\n  for i in $built_programs; do\n\n    # Skip `test'; it doesn't accept --help or --version.\n    test $i = test && continue;\n\n    # false fails even when invoked with --help or --version.\n    if test $i = false; then\n      env LC_MESSAGES=$lang $i --help >/dev/null && fail=1\n      env LC_MESSAGES=$lang $i --version >/dev/null && fail=1\n      continue\n    fi\n\n    args=\n\n    # The just-built install executable is always named `ginstall'.\n    test $i = install && i=ginstall\n\n    # Make sure they exit successfully, under normal conditions.\n    eval \"env \\$i $args --help    > h-\\$i   \" || fail=1\n    eval \"env \\$i $args --version >/dev/null\" || fail=1\n\n    # Make sure they mention the bug-reporting address in --help output.\n    grep \"$PACKAGE_BUGREPORT\" h-$i > /dev/null || fail=1\n    rm -f h-$i\n\n    # Make sure they fail upon `disk full' error.\n    if test -w /dev/full && test -c /dev/full; then\n      eval \"env \\$i $args --help    >/dev/full 2>/dev/null\" && fail=1\n      eval \"env \\$i $args --version >/dev/full 2>/dev/null\" && fail=1\n      status=$?\n      test $i = [ && prog=lbracket || prog=$i\n      eval \"expected=\\$expected_failure_status_$prog\"\n      test x$expected = x && expected=1\n      if test $status = $expected; then\n        : # ok\n      else\n        fail=1\n        echo \"*** $i: bad exit status \\`$status' (expected $expected),\" 1>&2\n        echo \"  with --help or --version output redirected to /dev/full\" 1>&2\n      fi\n    fi\n  done\ndone\n\nbigZ_in=bigZ-in.Z\nzin=zin.gz\nzin2=zin2.gz\n\ntmp=tmp-$$\ntmp_in=in-$$\ntmp_in2=in2-$$\ntmp_dir=dir-$$\ntmp_out=out-$$\nmkdir $tmp || fail=1\ncd $tmp || fail=1\n\ncomm_setup () { args=\"$tmp_in $tmp_in\"; }\ncsplit_setup () { args=\"$tmp_in //\"; }\ncut_setup () { args='-f 1'; }\njoin_setup () { args=\"$tmp_in $tmp_in\"; }\ntr_setup () { args='a a'; }\n\nchmod_setup () { args=\"a+x $tmp_in\"; }\n# Punt on these.\nchgrp_setup () { args=--version; }\nchown_setup () { args=--version; }\nmkfifo_setup () { args=--version; }\nmknod_setup () { args=--version; }\n# Punt on uptime, since it fails (e.g., failing to get boot time)\n# on some systems, and we shouldn't let that stop `make check'.\nuptime_setup () { args=--version; }\n\n# Create a file in the current directory, not in $TMPDIR.\nmktemp_setup () { args=mktemp.XXXX; }\n\ncmp_setup () { args=\"$tmp_in $tmp_in2\"; }\n\n# Tell dd not to print the line with transfer rate and total.\n# The transfer rate would vary between runs.\ndd_setup () { args=status=noxfer; }\n\nzdiff_setup () { args=\"$args $zin $zin2\"; }\nzcmp_setup () { zdiff_setup; }\nzcat_setup () { args=\"$args $zin\"; }\ngunzip_setup () { zcat_setup; }\nzmore_setup () { zcat_setup; }\nzless_setup () { zcat_setup; }\nznew_setup () { args=\"$args $bigZ_in\"; }\nzforce_setup () { zcat_setup; }\nzgrep_setup () { args=\"$args z $zin\"; }\nzegrep_setup () { zgrep_setup; }\nzfgrep_setup () { zgrep_setup; }\ngzexe_setup () { args=\"$args $tmp_in\"; }\n\n# We know that $tmp_in contains a \"0\"\ngrep_setup () { args=\"0 $tmp_in\"; }\negrep_setup () { args=\"0 $tmp_in\"; }\nfgrep_setup () { args=\"0 $tmp_in\"; }\n\ndiff_setup () { args=\"$tmp_in $tmp_in2\"; }\nsdiff_setup () { args=\"$tmp_in $tmp_in2\"; }\ndiff3_setup () { args=\"$tmp_in $tmp_in2 $tmp_in2\"; }\ncp_setup () { args=\"$tmp_in $tmp_in2\"; }\nln_setup () { args=\"$tmp_in ln-target\"; }\nginstall_setup () { args=\"$tmp_in $tmp_in2\"; }\nmv_setup () { args=\"$tmp_in $tmp_in2\"; }\nmkdir_setup () { args=$tmp_dir/subdir; }\nrmdir_setup () { args=$tmp_dir; }\nrm_setup () { args=$tmp_in; }\nshred_setup () { args=$tmp_in; }\ntouch_setup () { args=$tmp_in2; }\ntruncate_setup () { args=\"--reference=$tmp_in $tmp_in2\"; }\n\nbasename_setup () { args=$tmp_in; }\ndirname_setup () { args=$tmp_in; }\nexpr_setup () { args=foo; }\n\n# Punt, in case GNU `id' hasn't been installed yet.\ngroups_setup () { args=--version; }\n\npathchk_setup () { args=$tmp_in; }\nyes_setup () { args=--version; }\nlogname_setup () { args=--version; }\nnohup_setup () { args=--version; }\nprintf_setup () { args=foo; }\nseq_setup () { args=10; }\nsleep_setup () { args=0; }\nsu_setup () { args=--version; }\nstdbuf_setup () { args=\"-oL true\"; }\ntimeout_setup () { args=--version; }\n\n# I'd rather not run sync, since it spins up disks that I've\n# deliberately caused to spin down (but not unmounted).\nsync_setup () { args=--version; }\n\ntest_setup () { args=foo; }\n\n# This is necessary in the unusual event that there is\n# no valid entry in /etc/mtab.\ndf_setup () { args=/; }\n\n# This is necessary in the unusual event that getpwuid (getuid ()) fails.\nid_setup () { args=-u; }\n\n# Use env to avoid invoking built-in sleep of Solaris 11's /bin/sh.\nkill_setup () {\n  env sleep 10m &\n  args=$!\n}\n\nlink_setup () { args=\"$tmp_in link-target\"; }\nunlink_setup () { args=$tmp_in; }\n\nreadlink_setup () {\n  ln -s . slink\n  args=slink;\n}\n\nstat_setup () { args=$tmp_in; }\nunlink_setup () { args=$tmp_in; }\nlbracket_setup () { args=\": ]\"; }\n\n# Ensure that each program \"works\" (exits successfully) when doing\n# something more than --help or --version.\nfor i in $built_programs; do\n  # Skip these.\n  case $i in chroot|stty|tty|false|chcon|runcon) continue;; esac\n\n  rm -rf $tmp_in $tmp_in2 $tmp_dir $tmp_out $bigZ_in $zin $zin2\n  echo z |gzip > $zin\n  cp $zin $zin2\n  cp $zin $bigZ_in\n\n  # This is sort of kludgey: use numbers so this is valid input for factor,\n  # and two tokens so it's valid input for tsort.\n  echo 2147483647 0 > $tmp_in\n  # Make $tmp_in2 identical. Then, using $tmp_in and $tmp_in2 as arguments\n  # to the likes of cmp and diff makes them exit successfully.\n  cp $tmp_in $tmp_in2\n  mkdir $tmp_dir\n  # echo ================== $i\n  test $i = [ && prog=lbracket || prog=$i\n  args=\n  if type ${prog}_setup > /dev/null 2>&1; then\n    ${prog}_setup\n  fi\n  if eval \"env \\$i $args < \\$tmp_in > \\$tmp_out\"; then\n    : # ok\n  else\n    echo FAIL: $i\n    fail=1\n  fi\n  rm -rf $tmp_in $tmp_in2 $tmp_out $tmp_dir\ndone\n\nExit $fail\n", "num_lines": 271}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Exercise a bug whereby an invalid input could make gzip -d misbehave.\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf '\\n...: invalid compressed data--format violated\\n' > exp \\\n  || framework_failure_\n\nfail=0\ngzip -dc \"$abs_srcdir/hufts-segv.gz\" > out 2> err\ntest $? = 1 || fail=1\n\ncompare /dev/null out || fail=1\n\nsed 's/.*hufts-segv.gz: /...: /' err > k; mv k err || fail=1\ncompare exp err || fail=1\n\nExit $fail\n", "num_lines": 35}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "# source this file; set up for tests\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n# Using this file in a test\n# =========================\n#\n# The typical skeleton of a test looks like this:\n#\n#   #!/bin/sh\n#   . \"${srcdir=.}/init.sh\"; path_prepend_ .\n#   Execute some commands.\n#   Note that these commands are executed in a subdirectory, therefore you\n#   need to prepend \"../\" to relative filenames in the build directory.\n#   Note that the \"path_prepend_ .\" is useful only if the body of your\n#   test invokes programs residing in the initial directory.\n#   For example, if the programs you want to test are in src/, and this test\n#   script is named tests/test-1, then you would use \"path_prepend_ ../src\",\n#   or perhaps export PATH='$(abs_top_builddir)/src$(PATH_SEPARATOR)'\"$$PATH\"\n#   to all tests via automake's TESTS_ENVIRONMENT.\n#   Set the exit code 0 for success, 77 for skipped, or 1 or other for failure.\n#   Use the skip_ and fail_ functions to print a diagnostic and then exit\n#   with the corresponding exit code.\n#   Exit $?\n\n# Executing a test that uses this file\n# ====================================\n#\n# Running a single test:\n#   $ make check TESTS=test-foo.sh\n#\n# Running a single test, with verbose output:\n#   $ make check TESTS=test-foo.sh VERBOSE=yes\n#\n# Running a single test, with single-stepping:\n#   1. Go into a sub-shell:\n#   $ bash\n#   2. Set relevant environment variables from TESTS_ENVIRONMENT in the\n#      Makefile:\n#   $ export srcdir=../../tests # this is an example\n#   3. Execute the commands from the test, copy&pasting them one by one:\n#   $ . \"$srcdir/init.sh\"; path_prepend_ .\n#   ...\n#   4. Finally\n#   $ exit\n\nME_=`expr \"./$0\" : '.*/\\(.*\\)$'`\n\n# We use a trap below for cleanup.  This requires us to go through\n# hoops to get the right exit status transported through the handler.\n# So use 'Exit STATUS' instead of 'exit STATUS' inside of the tests.\n# Turn off errexit here so that we don't trip the bug with OSF1/Tru64\n# sh inside this function.\nExit () { set +e; (exit $1); exit $1; }\n\n# Print warnings (e.g., about skipped and failed tests) to this file number.\n# Override by defining to say, 9, in init.cfg, and putting say,\n#   export ...ENVVAR_SETTINGS...; $(SHELL) 9>&2\n# in the definition of TESTS_ENVIRONMENT in your tests/Makefile.am file.\n# This is useful when using automake's parallel tests mode, to print\n# the reason for skip/failure to console, rather than to the .log files.\n: ${stderr_fileno_=2}\n\n# Note that correct expansion of \"$*\" depends on IFS starting with ' '.\n# Always write the full diagnostic to stderr.\n# When stderr_fileno_ is not 2, also emit the first line of the\n# diagnostic to that file descriptor.\nwarn_ ()\n{\n  # If IFS does not start with ' ', set it and emit the warning in a subshell.\n  case $IFS in\n    ' '*) printf '%s\\n' \"$*\" >&2\n          test $stderr_fileno_ = 2 \\\n            || { printf '%s\\n' \"$*\" | sed 1q >&$stderr_fileno_ ; } ;;\n    *) (IFS=' '; warn_ \"$@\");;\n  esac\n}\nfail_ () { warn_ \"$ME_: failed test: $@\"; Exit 1; }\nskip_ () { warn_ \"$ME_: skipped test: $@\"; Exit 77; }\nfatal_ () { warn_ \"$ME_: hard error: $@\"; Exit 99; }\nframework_failure_ () { warn_ \"$ME_: set-up failure: $@\"; Exit 99; }\n\n# This is used to simplify checking of the return value\n# which is useful when ensuring a command fails as desired.\n# I.e., just doing `command ... &&fail=1` will not catch\n# a segfault in command for example.  With this helper you\n# instead check an explicit exit code like\n#   returns_ 1 command ... || fail\nreturns_ () {\n  # Disable tracing so it doesn't interfere with stderr of the wrapped command\n  { set +x; } 2>/dev/null\n\n  local exp_exit=\"$1\"\n  shift\n  \"$@\"\n  test $? -eq $exp_exit && ret_=0 || ret_=1\n\n  if test \"$VERBOSE\" = yes && test \"$gl_set_x_corrupts_stderr_\" = false; then\n    set -x\n  fi\n  { return $ret_; } 2>/dev/null\n}\n\n# Sanitize this shell to POSIX mode, if possible.\nDUALCASE=1; export DUALCASE\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in\n    *posix*) set -o posix ;;\n  esac\nfi\n\n# We require $(...) support unconditionally.\n# We require a few additional shell features only when $EXEEXT is nonempty,\n# in order to support automatic $EXEEXT emulation:\n# - hyphen-containing alias names\n# - we prefer to use ${var#...} substitution, rather than having\n#   to work around lack of support for that feature.\n# The following code attempts to find a shell with support for these features.\n# If the current shell passes the test, we're done.  Otherwise, test other\n# shells until we find one that passes.  If one is found, re-exec it.\n# If no acceptable shell is found, skip the current test.\n#\n# The \"...set -x; P=1 true 2>err...\" test is to disqualify any shell that\n# emits \"P=1\" into err, as /bin/sh from SunOS 5.11 and OpenBSD 4.7 do.\n#\n# Use \"9\" to indicate success (rather than 0), in case some shell acts\n# like Solaris 10's /bin/sh but exits successfully instead of with status 2.\n\n# Eval this code in a subshell to determine a shell's suitability.\n# 10 - passes all tests; ok to use\n#  9 - ok, but enabling \"set -x\" corrupts app stderr; prefer higher score\n#  ? - not ok\ngl_shell_test_script_='\ntest $(echo y) = y || exit 1\nf_local_() { local v=1; }; f_local_ || exit 1\nscore_=10\nif test \"$VERBOSE\" = yes; then\n  test -n \"$( (exec 3>&1; set -x; P=1 true 2>&3) 2> /dev/null)\" && score_=9\nfi\ntest -z \"$EXEEXT\" && exit $score_\nshopt -s expand_aliases\nalias a-b=\"echo zoo\"\nv=abx\n     test ${v%x} = ab \\\n  && test ${v#a} = bx \\\n  && test $(a-b) = zoo \\\n  && exit $score_\n'\n\nif test \"x$1\" = \"x--no-reexec\"; then\n  shift\nelse\n  # Assume a working shell.  Export to subshells (setup_ needs this).\n  gl_set_x_corrupts_stderr_=false\n  export gl_set_x_corrupts_stderr_\n\n  # Record the first marginally acceptable shell.\n  marginal_=\n\n  # Search for a shell that meets our requirements.\n  for re_shell_ in __current__ \"${CONFIG_SHELL:-no_shell}\" \\\n      /bin/sh bash dash zsh pdksh fail\n  do\n    test \"$re_shell_\" = no_shell && continue\n\n    # If we've made it all the way to the sentinel, \"fail\" without\n    # finding even a marginal shell, skip this test.\n    if test \"$re_shell_\" = fail; then\n      test -z \"$marginal_\" && skip_ failed to find an adequate shell\n      re_shell_=$marginal_\n      break\n    fi\n\n    # When testing the current shell, simply \"eval\" the test code.\n    # Otherwise, run it via $re_shell_ -c ...\n    if test \"$re_shell_\" = __current__; then\n      # 'eval'ing this code makes Solaris 10's /bin/sh exit with\n      # $? set to 2.  It does not evaluate any of the code after the\n      # \"unexpected\" first '('.  Thus, we must run it in a subshell.\n      ( eval \"$gl_shell_test_script_\" ) > /dev/null 2>&1\n    else\n      \"$re_shell_\" -c \"$gl_shell_test_script_\" 2>/dev/null\n    fi\n\n    st_=$?\n\n    # $re_shell_ works just fine.  Use it.\n    if test $st_ = 10; then\n      gl_set_x_corrupts_stderr_=false\n      break\n    fi\n\n    # If this is our first marginally acceptable shell, remember it.\n    if test \"$st_:$marginal_\" = 9: ; then\n      marginal_=\"$re_shell_\"\n      gl_set_x_corrupts_stderr_=true\n    fi\n  done\n\n  if test \"$re_shell_\" != __current__; then\n    # Found a usable shell.  Preserve -v and -x.\n    case $- in\n      *v*x* | *x*v*) opts_=-vx ;;\n      *v*) opts_=-v ;;\n      *x*) opts_=-x ;;\n      *) opts_= ;;\n    esac\n    re_shell=$re_shell_\n    export re_shell\n    exec \"$re_shell_\" $opts_ \"$0\" --no-reexec \"$@\"\n    echo \"$ME_: exec failed\" 1>&2\n    exit 127\n  fi\nfi\n\n# If this is bash, turn off all aliases.\ntest -n \"$BASH_VERSION\" && unalias -a\n\n# Note that when supporting $EXEEXT (transparently mapping from PROG_NAME to\n# PROG_NAME.exe), we want to support hyphen-containing names like test-acos.\n# That is part of the shell-selection test above.  Why use aliases rather\n# than functions?  Because support for hyphen-containing aliases is more\n# widespread than that for hyphen-containing function names.\ntest -n \"$EXEEXT\" && shopt -s expand_aliases\n\n# Enable glibc's malloc-perturbing option.\n# This is useful for exposing code that depends on the fact that\n# malloc-related functions often return memory that is mostly zeroed.\n# If you have the time and cycles, use valgrind to do an even better job.\n: ${MALLOC_PERTURB_=87}\nexport MALLOC_PERTURB_\n\n# This is a stub function that is run upon trap (upon regular exit and\n# interrupt).  Override it with a per-test function, e.g., to unmount\n# a partition, or to undo any other global state changes.\ncleanup_ () { :; }\n\n# Emit a header similar to that from diff -u;  Print the simulated \"diff\"\n# command so that the order of arguments is clear.  Don't bother with @@ lines.\nemit_diff_u_header_ ()\n{\n  printf '%s\\n' \"diff -u $*\" \\\n    \"--- $1\t1970-01-01\" \\\n    \"+++ $2\t1970-01-01\"\n}\n\n# Arrange not to let diff or cmp operate on /dev/null,\n# since on some systems (at least OSF/1 5.1), that doesn't work.\n# When there are not two arguments, or no argument is /dev/null, return 2.\n# When one argument is /dev/null and the other is not empty,\n# cat the nonempty file to stderr and return 1.\n# Otherwise, return 0.\ncompare_dev_null_ ()\n{\n  test $# = 2 || return 2\n\n  if test \"x$1\" = x/dev/null; then\n    test -s \"$2\" || return 0\n    emit_diff_u_header_ \"$@\"; sed 's/^/+/' \"$2\"\n    return 1\n  fi\n\n  if test \"x$2\" = x/dev/null; then\n    test -s \"$1\" || return 0\n    emit_diff_u_header_ \"$@\"; sed 's/^/-/' \"$1\"\n    return 1\n  fi\n\n  return 2\n}\n\nif diff_out_=`exec 2>/dev/null; diff -u \"$0\" \"$0\" < /dev/null` \\\n   && diff -u Makefile \"$0\" 2>/dev/null | grep '^[+]#!' >/dev/null; then\n  # diff accepts the -u option and does not (like AIX 7 'diff') produce an\n  # extra space on column 1 of every content line.\n  if test -z \"$diff_out_\"; then\n    compare_ () { diff -u \"$@\"; }\n  else\n    compare_ ()\n    {\n      if diff -u \"$@\" > diff.out; then\n        # No differences were found, but Solaris 'diff' produces output\n        # \"No differences encountered\". Hide this output.\n        rm -f diff.out\n        true\n      else\n        cat diff.out\n        rm -f diff.out\n        false\n      fi\n    }\n  fi\nelif\n  for diff_opt_ in -U3 -c '' no; do\n    test \"$diff_opt_\" = no && break\n    diff_out_=`exec 2>/dev/null; diff $diff_opt_ \"$0\" \"$0\" </dev/null` && break\n  done\n  test \"$diff_opt_\" != no\nthen\n  if test -z \"$diff_out_\"; then\n    compare_ () { diff $diff_opt_ \"$@\"; }\n  else\n    compare_ ()\n    {\n      if diff $diff_opt_ \"$@\" > diff.out; then\n        # No differences were found, but AIX and HP-UX 'diff' produce output\n        # \"No differences encountered\" or \"There are no differences between the\n        # files.\". Hide this output.\n        rm -f diff.out\n        true\n      else\n        cat diff.out\n        rm -f diff.out\n        false\n      fi\n    }\n  fi\nelif cmp -s /dev/null /dev/null 2>/dev/null; then\n  compare_ () { cmp -s \"$@\"; }\nelse\n  compare_ () { cmp \"$@\"; }\nfi\n\n# Usage: compare EXPECTED ACTUAL\n#\n# Given compare_dev_null_'s preprocessing, defer to compare_ if 2 or more.\n# Otherwise, propagate $? to caller: any diffs have already been printed.\ncompare ()\n{\n  # This looks like it can be factored to use a simple \"case $?\"\n  # after unchecked compare_dev_null_ invocation, but that would\n  # fail in a \"set -e\" environment.\n  if compare_dev_null_ \"$@\"; then\n    return 0\n  else\n    case $? in\n      1) return 1;;\n      *) compare_ \"$@\";;\n    esac\n  fi\n}\n\n# An arbitrary prefix to help distinguish test directories.\ntestdir_prefix_ () { printf gt; }\n\n# Run the user-overridable cleanup_ function, remove the temporary\n# directory and exit with the incoming value of $?.\nremove_tmp_ ()\n{\n  __st=$?\n  cleanup_\n  # cd out of the directory we're about to remove\n  cd \"$initial_cwd_\" || cd / || cd /tmp\n  chmod -R u+rwx \"$test_dir_\"\n  # If removal fails and exit status was to be 0, then change it to 1.\n  rm -rf \"$test_dir_\" || { test $__st = 0 && __st=1; }\n  exit $__st\n}\n\n# Given a directory name, DIR, if every entry in it that matches *.exe\n# contains only the specified bytes (see the case stmt below), then print\n# a space-separated list of those names and return 0.  Otherwise, don't\n# print anything and return 1.  Naming constraints apply also to DIR.\nfind_exe_basenames_ ()\n{\n  feb_dir_=$1\n  feb_fail_=0\n  feb_result_=\n  feb_sp_=\n  for feb_file_ in $feb_dir_/*.exe; do\n    # If there was no *.exe file, or there existed a file named \"*.exe\" that\n    # was deleted between the above glob expansion and the existence test\n    # below, just skip it.\n    test \"x$feb_file_\" = \"x$feb_dir_/*.exe\" && test ! -f \"$feb_file_\" \\\n      && continue\n    # Exempt [.exe, since we can't create a function by that name, yet\n    # we can't invoke [ by PATH search anyways due to shell builtins.\n    test \"x$feb_file_\" = \"x$feb_dir_/[.exe\" && continue\n    case $feb_file_ in\n      *[!-a-zA-Z/0-9_.+]*) feb_fail_=1; break;;\n      *) # Remove leading file name components as well as the .exe suffix.\n         feb_file_=${feb_file_##*/}\n         feb_file_=${feb_file_%.exe}\n         feb_result_=\"$feb_result_$feb_sp_$feb_file_\";;\n    esac\n    feb_sp_=' '\n  done\n  test $feb_fail_ = 0 && printf %s \"$feb_result_\"\n  return $feb_fail_\n}\n\n# Consider the files in directory, $1.\n# For each file name of the form PROG.exe, create an alias named\n# PROG that simply invokes PROG.exe, then return 0.  If any selected\n# file name or the directory name, $1, contains an unexpected character,\n# define no alias and return 1.\ncreate_exe_shims_ ()\n{\n  case $EXEEXT in\n    '') return 0 ;;\n    .exe) ;;\n    *) echo \"$0: unexpected \\$EXEEXT value: $EXEEXT\" 1>&2; return 1 ;;\n  esac\n\n  base_names_=`find_exe_basenames_ $1` \\\n    || { echo \"$0 (exe_shim): skipping directory: $1\" 1>&2; return 0; }\n\n  if test -n \"$base_names_\"; then\n    for base_ in $base_names_; do\n      alias \"$base_\"=\"$base_$EXEEXT\"\n    done\n  fi\n\n  return 0\n}\n\n# Use this function to prepend to PATH an absolute name for each\n# specified, possibly-$initial_cwd_-relative, directory.\npath_prepend_ ()\n{\n  while test $# != 0; do\n    path_dir_=$1\n    case $path_dir_ in\n      '') fail_ \"invalid path dir: '$1'\";;\n      /*) abs_path_dir_=$path_dir_;;\n      *) abs_path_dir_=$initial_cwd_/$path_dir_;;\n    esac\n    case $abs_path_dir_ in\n      *:*) fail_ \"invalid path dir: '$abs_path_dir_'\";;\n    esac\n    PATH=\"$abs_path_dir_:$PATH\"\n\n    # Create an alias, FOO, for each FOO.exe in this directory.\n    create_exe_shims_ \"$abs_path_dir_\" \\\n      || fail_ \"something failed (above): $abs_path_dir_\"\n    shift\n  done\n  export PATH\n}\n\nsetup_ ()\n{\n  if test \"$VERBOSE\" = yes; then\n    # Test whether set -x may cause the selected shell to corrupt an\n    # application's stderr.  Many do, including zsh-4.3.10 and the /bin/sh\n    # from SunOS 5.11, OpenBSD 4.7 and Irix 5.x and 6.5.\n    # If enabling verbose output this way would cause trouble, simply\n    # issue a warning and refrain.\n    if $gl_set_x_corrupts_stderr_; then\n      warn_ \"using SHELL=$SHELL with 'set -x' corrupts stderr\"\n    else\n      set -x\n    fi\n  fi\n\n  initial_cwd_=$PWD\n\n  pfx_=`testdir_prefix_`\n  test_dir_=`mktempd_ \"$initial_cwd_\" \"$pfx_-$ME_.XXXX\"` \\\n    || fail_ \"failed to create temporary directory in $initial_cwd_\"\n  cd \"$test_dir_\" || fail_ \"failed to cd to temporary directory\"\n\n  # As autoconf-generated configure scripts do, ensure that IFS\n  # is defined initially, so that saving and restoring $IFS works.\n  gl_init_sh_nl_='\n'\n  IFS=\" \"\"\t$gl_init_sh_nl_\"\n\n  # This trap statement, along with a trap on 0 below, ensure that the\n  # temporary directory, $test_dir_, is removed upon exit as well as\n  # upon receipt of any of the listed signals.\n  for sig_ in 1 2 3 13 15; do\n    eval \"trap 'Exit $(expr $sig_ + 128)' $sig_\"\n  done\n}\n\n# Create a temporary directory, much like mktemp -d does.\n# Written by Jim Meyering.\n#\n# Usage: mktempd_ /tmp phoey.XXXXXXXXXX\n#\n# First, try to use the mktemp program.\n# Failing that, we'll roll our own mktemp-like function:\n#  - try to get random bytes from /dev/urandom\n#  - failing that, generate output from a combination of quickly-varying\n#      sources and gzip.  Ignore non-varying gzip header, and extract\n#      \"random\" bits from there.\n#  - given those bits, map to file-name bytes using tr, and try to create\n#      the desired directory.\n#  - make only $MAX_TRIES_ attempts\n\n# Helper function.  Print $N pseudo-random bytes from a-zA-Z0-9.\nrand_bytes_ ()\n{\n  n_=$1\n\n  # Maybe try openssl rand -base64 $n_prime_|tr '+/=\\012' abcd first?\n  # But if they have openssl, they probably have mktemp, too.\n\n  chars_=abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n  dev_rand_=/dev/urandom\n  if test -r \"$dev_rand_\"; then\n    # Note: 256-length($chars_) == 194; 3 copies of $chars_ is 186 + 8 = 194.\n    dd ibs=$n_ count=1 if=$dev_rand_ 2>/dev/null \\\n      | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_\n    return\n  fi\n\n  n_plus_50_=`expr $n_ + 50`\n  cmds_='date; date +%N; free; who -a; w; ps auxww; ps ef; netstat -n'\n  data_=` (eval \"$cmds_\") 2>&1 | gzip `\n\n  # Ensure that $data_ has length at least 50+$n_\n  while :; do\n    len_=`echo \"$data_\"|wc -c`\n    test $n_plus_50_ -le $len_ && break;\n    data_=` (echo \"$data_\"; eval \"$cmds_\") 2>&1 | gzip `\n  done\n\n  echo \"$data_\" \\\n    | dd bs=1 skip=50 count=$n_ 2>/dev/null \\\n    | LC_ALL=C tr -c $chars_ 01234567$chars_$chars_$chars_\n}\n\nmktempd_ ()\n{\n  case $# in\n  2);;\n  *) fail_ \"Usage: mktempd_ DIR TEMPLATE\";;\n  esac\n\n  destdir_=$1\n  template_=$2\n\n  MAX_TRIES_=4\n\n  # Disallow any trailing slash on specified destdir:\n  # it would subvert the post-mktemp \"case\"-based destdir test.\n  case $destdir_ in\n  / | //) destdir_slash_=$destdir;;\n  */) fail_ \"invalid destination dir: remove trailing slash(es)\";;\n  *) destdir_slash_=$destdir_/;;\n  esac\n\n  case $template_ in\n  *XXXX) ;;\n  *) fail_ \\\n       \"invalid template: $template_ (must have a suffix of at least 4 X's)\";;\n  esac\n\n  # First, try to use mktemp.\n  d=`unset TMPDIR; { mktemp -d -t -p \"$destdir_\" \"$template_\"; } 2>/dev/null` &&\n\n  # The resulting name must be in the specified directory.\n  case $d in \"$destdir_slash_\"*) :;; *) false;; esac &&\n\n  # It must have created the directory.\n  test -d \"$d\" &&\n\n  # It must have 0700 permissions.  Handle sticky \"S\" bits.\n  perms=`ls -dgo \"$d\" 2>/dev/null` &&\n  case $perms in drwx--[-S]---*) :;; *) false;; esac && {\n    echo \"$d\"\n    return\n  }\n\n  # If we reach this point, we'll have to create a directory manually.\n\n  # Get a copy of the template without its suffix of X's.\n  base_template_=`echo \"$template_\"|sed 's/XX*$//'`\n\n  # Calculate how many X's we've just removed.\n  template_length_=`echo \"$template_\" | wc -c`\n  nx_=`echo \"$base_template_\" | wc -c`\n  nx_=`expr $template_length_ - $nx_`\n\n  err_=\n  i_=1\n  while :; do\n    X_=`rand_bytes_ $nx_`\n    candidate_dir_=\"$destdir_slash_$base_template_$X_\"\n    err_=`mkdir -m 0700 \"$candidate_dir_\" 2>&1` \\\n      && { echo \"$candidate_dir_\"; return; }\n    test $MAX_TRIES_ -le $i_ && break;\n    i_=`expr $i_ + 1`\n  done\n  fail_ \"$err_\"\n}\n\n# If you want to override the testdir_prefix_ function,\n# or to add more utility functions, use this file.\ntest -f \"$srcdir/init.cfg\" \\\n  && . \"$srcdir/init.cfg\"\n\nsetup_ \"$@\"\n# This trap is here, rather than in the setup_ function, because some\n# shells run the exit trap at shell function exit, rather than script exit.\ntrap remove_tmp_ 0\n", "num_lines": 617}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Exercise the --keep option.\n\n# Copyright (C) 2013-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\necho fooooooooo > in || framework_failure_\ncp in orig || framework_failure_\n\nfail=0\n\n# Compress and decompress both with and without --keep.\nfor k in --keep ''; do\n  # With --keep, the source must be retained, otherwise, it must be removed.\n  case $k in --keep) op='||' ;; *) op='&&' ;; esac\n\n  gzip $k in || fail=1\n  eval \"test -f in $op fail=1\"\n  test -f in.gz || fail=1\n  rm -f in || fail=1\n\n  gzip -d $k in.gz || fail=1\n  eval \"test -f in.gz $op fail=1\"\n  test -f in || fail=1\n  compare in orig || fail=1\n  rm -f in.gz || fail=1\ndone\n\ncp orig in || framework_failure_\nlog=$(gzip -kv in 2>&1) || fail=1\ncase $log in\n  *'created in.gz'*) ;;\n  *) fail=1;;\nesac\n\nExit $fail\n", "num_lines": 52}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Exercise the --list option.\n\n# Copyright 2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\necho zoology zucchini > in || framework_failure_\ncp in orig || framework_failure_\n\ngzip -l in && fail=1\ngzip -9 in || fail=1\ngzip -l in.gz >out1 || fail=1\ngzip -l in.gz | cat >out2 || fail=1\ncompare out1 out2 || fail=1\n\nExit $fail\n", "num_lines": 32}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Before gzip-1.4, this the use of memcpy in inflate_codes could\n# mistakenly operate on overlapping regions.  Exercise that code.\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\n# The input must be larger than 32KiB and slightly\n# less uniform than e.g., all zeros.\nprintf wxy%032767d 0 | tee in | gzip > in.gz || framework_failure_\n\nfail=0\n\n# Before the fix, this would call memcpy with overlapping regions.\ngzip -dc in.gz > out || fail=1\n\ncompare in out || fail=1\n\nExit $fail\n", "num_lines": 35}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Ensure that gzip -cdf handles mixed compressed/not-compressed data\n# Before gzip-1.5, it would produce invalid output.\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf 'xxx\\nyyy\\n'      > exp2 || framework_failure_\nprintf 'aaa\\nbbb\\nccc\\n' > exp3 || framework_failure_\n\nfail=0\n\n(echo xxx; echo yyy) > in || fail=1\ngzip -cdf < in > out || fail=1\ncompare exp2 out || fail=1\n\n# Uncompressed input, followed by compressed data.\n# Currently fails, so skip it.\n# (echo xxx; echo yyy|gzip) > in || fail=1\n# gzip -cdf < in > out || fail=1\n# compare exp2 out || fail=1\n\n# Compressed input, followed by regular (not-compressed) data.\n(echo xxx|gzip; echo yyy) > in || fail=1\ngzip -cdf < in > out || fail=1\ncompare exp2 out || fail=1\n\n(echo xxx|gzip; echo yyy|gzip) > in || fail=1\ngzip -cdf < in > out || fail=1\ncompare exp2 out || fail=1\n\nin_str=0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_-+=%\nfor i in 0 1 2 3 4 5 6 7 8 9 a; do in_str=\"$in_str$in_str\" ;done\n\n# Start with some small sizes.  $(seq 64)\nsizes=$(i=0; while :; do echo $i; test $i = 64 && break; i=$(expr $i + 1); done)\n\n# gzip's internal buffer size is 32KiB + 64 bytes:\nsizes=\"$sizes 32831 32832 32833\"\n\n# 128KiB, +/- 1\nsizes=\"$sizes 131071 131072 131073\"\n\n# Ensure that \"gzip -cdf\" acts like cat, for a range of small input files.\ni=0\nfor i in $sizes; do\n  echo $i\n  printf %$i.${i}s $in_str > in\n  gzip -cdf < in > out\n  compare in out || fail=1\ndone\n\nExit $fail\n", "num_lines": 69}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Before gzip-1.5, gzip -d -S '' k.gz would delete F.gz and not create \"F\"\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf anything | gzip > F.gz || framework_failure_\necho y > yes || framework_failure_\necho \"gzip: invalid suffix ''\" > expected-err || framework_failure_\n\nfail=0\n\ngzip ---presume-input-tty -d -S '' F.gz < yes > out 2>err && fail=1\n\ncompare /dev/null out || fail=1\ncompare expected-err err || fail=1\n\ntest -f F.gz || fail=1\n\nExit $fail\n", "num_lines": 36}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Ensure that gzip interprets \"-\" as stdin.\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf a | gzip > in || framework_failure_\nprintf aaa > exp || framework_failure_\n\nfail=0\ngzip -dc in - in < in > out 2>err || fail=1\n\ncompare exp out || fail=1\ncompare /dev/null err || fail=1\n\nExit $fail\n", "num_lines": 32}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#! /bin/sh\n# test-driver - basic testsuite driver script.\n\nscriptversion=2016-01-11.22; # UTC\n\n# Copyright (C) 2011-2015 Free Software Foundation, Inc.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2, or (at your option)\n# any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\n# As a special exception to the GNU General Public License, if you\n# distribute this file as part of a program that contains a\n# configuration script generated by Autoconf, you may include it under\n# the same distribution terms that you use for the rest of that program.\n\n# This file is maintained in Automake, please report\n# bugs to <bug-automake@gnu.org> or send patches to\n# <automake-patches@gnu.org>.\n\n# Make unconditional expansion of undefined variables an error.  This\n# helps a lot in preventing typo-related bugs.\nset -u\n\nusage_error ()\n{\n  echo \"$0: $*\" >&2\n  print_usage >&2\n  exit 2\n}\n\nprint_usage ()\n{\n  cat <<END\nUsage:\n  test-driver --test-name=NAME --log-file=PATH --trs-file=PATH\n              [--expect-failure={yes|no}] [--color-tests={yes|no}]\n              [--enable-hard-errors={yes|no}] [--]\n              TEST-SCRIPT [TEST-SCRIPT-ARGUMENTS]\nThe '--test-name', '--log-file' and '--trs-file' options are mandatory.\nEND\n}\n\ntest_name= # Used for reporting.\nlog_file=  # Where to save the output of the test script.\ntrs_file=  # Where to save the metadata of the test run.\nexpect_failure=no\ncolor_tests=no\nenable_hard_errors=yes\nwhile test $# -gt 0; do\n  case $1 in\n  --help) print_usage; exit $?;;\n  --version) echo \"test-driver $scriptversion\"; exit $?;;\n  --test-name) test_name=$2; shift;;\n  --log-file) log_file=$2; shift;;\n  --trs-file) trs_file=$2; shift;;\n  --color-tests) color_tests=$2; shift;;\n  --expect-failure) expect_failure=$2; shift;;\n  --enable-hard-errors) enable_hard_errors=$2; shift;;\n  --) shift; break;;\n  -*) usage_error \"invalid option: '$1'\";;\n   *) break;;\n  esac\n  shift\ndone\n\nmissing_opts=\ntest x\"$test_name\" = x && missing_opts=\"$missing_opts --test-name\"\ntest x\"$log_file\"  = x && missing_opts=\"$missing_opts --log-file\"\ntest x\"$trs_file\"  = x && missing_opts=\"$missing_opts --trs-file\"\nif test x\"$missing_opts\" != x; then\n  usage_error \"the following mandatory options are missing:$missing_opts\"\nfi\n\nif test $# -eq 0; then\n  usage_error \"missing argument\"\nfi\n\nif test $color_tests = yes; then\n  # Keep this in sync with 'lib/am/check.am:$(am__tty_colors)'.\n  red='\u001b[0;31m' # Red.\n  grn='\u001b[0;32m' # Green.\n  lgn='\u001b[1;32m' # Light green.\n  blu='\u001b[1;34m' # Blue.\n  mgn='\u001b[0;35m' # Magenta.\n  std='\u001b[m'     # No color.\nelse\n  red= grn= lgn= blu= mgn= std=\nfi\n\ndo_exit='rm -f $log_file $trs_file; (exit $st); exit $st'\ntrap \"st=129; $do_exit\" 1\ntrap \"st=130; $do_exit\" 2\ntrap \"st=141; $do_exit\" 13\ntrap \"st=143; $do_exit\" 15\n\n# Test script is run here.\n\"$@\" >$log_file 2>&1\nestatus=$?\n\nif test $enable_hard_errors = no && test $estatus -eq 99; then\n  tweaked_estatus=1\nelse\n  tweaked_estatus=$estatus\nfi\n\ncase $tweaked_estatus:$expect_failure in\n  0:yes) col=$red res=XPASS recheck=yes gcopy=yes;;\n  0:*)   col=$grn res=PASS  recheck=no  gcopy=no;;\n  77:*)  col=$blu res=SKIP  recheck=no  gcopy=yes;;\n  99:*)  col=$mgn res=ERROR recheck=yes gcopy=yes;;\n  *:yes) col=$lgn res=XFAIL recheck=no  gcopy=yes;;\n  *:*)   col=$red res=FAIL  recheck=yes gcopy=yes;;\nesac\n\n# Report the test outcome and exit status in the logs, so that one can\n# know whether the test passed or failed simply by looking at the '.log'\n# file, without the need of also peaking into the corresponding '.trs'\n# file (automake bug#11814).\necho \"$res $test_name (exit status: $estatus)\" >>$log_file\n\n# Report outcome to console.\necho \"${col}${res}${std}: $test_name\"\n\n# Register the test result, and other relevant metadata.\necho \":test-result: $res\" > $trs_file\necho \":global-test-result: $res\" >> $trs_file\necho \":recheck: $recheck\" >> $trs_file\necho \":copy-in-global-log: $gcopy\" >> $trs_file\n\n# Local Variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'write-file-hooks 'time-stamp)\n# time-stamp-start: \"scriptversion=\"\n# time-stamp-format: \"%:y-%02m-%02d.%02H\"\n# time-stamp-time-zone: \"UTC0\"\n# time-stamp-end: \"; # UTC\"\n# End:\n\nexit $tweaked_estatus\n", "num_lines": 151}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# gzip accepts trailing NUL bytes; don't fail if there is exactly one.\n# Before gzip-1.4, this would fail.\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\n(echo 0 | gzip; printf '\\0') > 0.gz || framework_failure_\n(echo 00 | gzip; printf '\\0\\0') > 00.gz || framework_failure_\n(echo 1 | gzip; printf '\\1') > 1.gz || framework_failure_\n\nfail=0\n\nfor i in 0 00 1; do\n  gzip -d $i.gz; ret=$?\n  test $ret -eq $i || fail=1\n  test $ret = 1 && continue\n  echo $i > exp || fail=1\n  compare exp $i || fail=1\ndone\n\nExit $fail\n", "num_lines": 38}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# gzip should report invalid 'unpack' input when uncompressing.\n# With gzip-1.5, it would output invalid data instead.\n\n# Copyright (C) 2012-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nfor input in \\\n  '\\037\\036\\000\\000\\037\\213\\010\\000\\000\\000\\000\\000\\002\\003\\036\\000\\000\\000\\002\\003\\037\\213\\010\\000\\000\\000\\000\\000\\002\\003\\355\\301\\001\\015\\000\\000\\000\\302\\240\\037\\000\\302\\240\\037\\213\\010\\000\\000\\000\\000\\000\\002\\003\\355\\301' \\\n  '\\037\\213\\010\\000\\000\\000\\000\\000\\002\\003\\355\\301\\001\\015\\000\\000\\000\\302\\240\\076\\366\\017\\370\\036\\016\\030\\000\\000\\000\\000\\000\\000\\000\\000\\000\\034\\010\\105\\140\\104\\025\\020\\047\\000\\000\\037\\036\\016\\030\\000\\000\\000'; do\n\n  printf \"$input\" >in || framework_failure_\n\n  if gzip -d <in >out 2>err; then\n    fail=1\n  else\n    fail=0\n  fi\ndone\n\nExit $fail\n", "num_lines": 37}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Check that -Sz works.\n\n# Copyright 2014-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf anything > F && cp F G || framework_failure_\ngzip -Sz F || fail=1\ntest ! -f F || fail=1\ntest -f Fz || fail=1\ngzip -dSz F || fail=1\ntest ! -f Fz || fail=1\ncompare F G || fail\\1\n\nExit $fail\n", "num_lines": 31}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Exercise zdiff with two compressed inputs.\n# Before gzip-1.4, this would fail.\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\necho a > a || framework_failure_\necho b > b || framework_failure_\ngzip a b || framework_failure_\n\ncat <<EOF > exp\n1c1\n< a\n---\n> b\nEOF\n\nfail=0\nzdiff a.gz b.gz > out 2>&1\ntest $? = 1 || fail=1\n\ncompare exp out || fail=1\n\nrm -f out\n# expect success, for equal files\nzdiff a.gz a.gz > out 2> err || fail=1\n# expect no output\ntest -s out && fail=1\n# expect no stderr\ntest -s err && fail=1\n\nExit $fail\n", "num_lines": 49}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Ensure that zgrep -15 works.  Before gzip-1.5, it would fail.\n\n# Copyright (C) 2012-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\n# A limited replacement for seq: handle 1 or 2 args; increment must be 1\nseq()\n{\n  case $# in\n    1) start=1  final=$1;;\n    2) start=$1 final=$2;;\n    *) echo you lose 1>&2; exit 1;;\n  esac\n  awk 'BEGIN{for(i='$start';i<='$final';i++) print i}' < /dev/null\n}\n\nseq 40 > in || framework_failure_\ngzip < in > in.gz || framework_failure_\nseq 2 32 > exp || framework_failure_\n\n: ${GREP=grep}\n$GREP -15 17 - < in > out && compare exp out || {\n  echo >&2 \"$0: $GREP does not support context options; skipping this test\"\n  exit 77\n}\n\nfail=0\nzgrep -15 17 - < in.gz > out || fail=1\ncompare exp out || fail=1\n\nExit $fail\n", "num_lines": 48}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Ensure that zgrep -f - works like grep -f -\n# Before gzip-1.4, it would fail.\n\n# Copyright (C) 2009-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\nprintf 'needle\\nn2\\n' > n || framework_failure_\ncp n haystack || framework_failure_\ngzip haystack || framework_failure_\n\nfail=0\nzgrep -f - haystack.gz < n > out 2>&1 || fail=1\n\ncompare out n || fail=1\n\nif ${BASH_VERSION+:} false; then\n  set +o posix\n  # This failed with gzip 1.6.\n  cat n n >nn || framework_failure_\n  eval 'zgrep -h -f <(cat n) haystack.gz haystack.gz' >out || fail=1\n  compare out nn || fail=1\nfi\n\n# This failed with gzip 1.4.\necho a-b | zgrep -e - > /dev/null || fail=1\n\nExit $fail\n", "num_lines": 44}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Check that zgrep is terminated gracefully by signal when\n# its grep/sed pipeline is terminated by a signal.\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\necho a | gzip -c > f.gz || framework_failure_\n\ntest \"x$PERL\" = x && PERL=perl\n(\"$PERL\" -e 'use POSIX qw(dup2)') >/dev/null 2>&1 ||\n   skip_ \"no suitable perl found\"\n\n# Run the arguments as a command, in a process where stdout is a\n# dangling pipe and SIGPIPE has the default signal-handling action.\n# This can't be done portably in the shell, because if SIGPIPE is\n# ignored when the shell is entered, the shell might refuse to trap\n# it.  Fall back on Perl+POSIX, if available.  Take care to close the\n# pipe's read end before running the program; the equivalent of the\n# shell's \"command | :\" has a race condition in that COMMAND could\n# write before \":\" exits.\nwrite_to_dangling_pipe () {\n  program=${1?}\n  shift\n  args=\n  for arg; do\n    args=\"$args, '$arg'\"\n  done\n  \"$PERL\" -e '\n     use POSIX qw(dup2);\n     $SIG{PIPE} = \"DEFAULT\";\n     pipe my ($read_end, $write_end) or die \"pipe: $!\\n\";\n     dup2 fileno $write_end, 1 or die \"dup2: $!\\n\";\n     close $read_end or die \"close: $!\\n\";\n     exec '\"'$program'$args\"';\n  '\n}\n\nwrite_to_dangling_pipe cat f.gz f.gz\nsignal_status=$?\ntest 128 -lt $signal_status ||\n  framework_failure_ 'signal handling busted on this host'\n\nfail=0\n\nwrite_to_dangling_pipe zgrep a f.gz f.gz\ntest $? -eq $signal_status || fail=1\n\nExit $fail\n", "num_lines": 65}
{"repo_name": "zstd", "repo_creator": "facebook", "programming_language": "Shell", "code": "#!/bin/sh\n# Check that znew -K works without compress(1).\n\n# Copyright (C) 2010-2016 Free Software Foundation, Inc.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <https://www.gnu.org/licenses/>.\n# limit so don't run it by default.\n\n. \"${srcdir=.}/init.sh\"; path_prepend_ .\n\ncat <<'EOF' >compress || framework_failure_\n#!/bin/sh\necho >&2 'compress has been invoked'\nexit 1\nEOF\nchmod +x compress || framework_failure_\n\n# Note that the basename must have a length of 6 or greater.\n# Otherwise, \"test -f $name\" below would fail.\nname=123456.Z\n\nprintf '%1012977s' ' ' | gzip -c > $name || framework_failure_\n\nfail=0\n\nznew -K $name || fail=1\ntest -f $name || fail=1\n\nExit $fail\n", "num_lines": 41}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "source bin/credentials.sh\n\n# this doesnt seem to work\n# https://developer.gitter.im/docs/authentication\n\n\nset -x\necho \"client_id=${GITTER_APP_KEY}\\n\"\n\ncurl -i -X POST https://gitter.im/login/oauth/token \\\n  -d\"client_id=${GITTER_APP_KEY}\" \\\n  -d\"client_secret=${GITTER_APP_SECRET}\" \\\n  -d\"code=CODE\" \\\n  -d\"grant_type=authorization_code\" \\\n  -d\"redirect_uri=${GITTER_APP_REDIRECT_URL}\"", "num_lines": 15}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "\n\n\nsource bin/credentials-camperbot.sh\n\nset -x\n\nSERVER_ENV=prod \\\nBOT_APP_HOST=bot.freecodecamp.org \\\nGITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\nGITTER_APP_KEY=${GITTER_APP_KEY} \\\nGITTER_APP_SECRET=${GITTER_APP_SECRET} \\\nLOG_LEVEL=10 \\\nPORT=7891 \\\n    nodemon app.js\n", "num_lines": 16}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# get these keys from here\n# https://developer.gitter.im/apps\n\n# Personal Access Token\nGITTER_USER_TOKEN=1ac342045f5a57d99fe537e58da78f6cba94f7db\n\n# Your Apps\n# OAUTH KEY\nGITTER_APP_KEY=63ece8ac0eeed9b17b1cc9867f65d4857ec6e5fc\n\n# OAUTH SECRET\nGITTER_APP_SECRET=9026e3b3a74357035ee15a9591f31b2de5cfd3a6\n# REDIRECT URL\nGITTER_APP_REDIRECT_URL=http://localhost:7891/login/callback\n", "num_lines": 16}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# edit this file and save it as credentials.sh\n# \n# or, create a new file like credentials-ENV.sh\n# and symlink it\n# $ ln -s credentials-ENV.sh credentials.sh\n# this file is included in other run commands\n\nGITTER_APP_KEY=XXXX\nGITTER_APP_SECRET=XXXX\nGITTER_APP_REDIRECT_URL=http://localhost:7000/login/callback\n\nGITTER_USER_TOKEN=XXXX\n", "num_lines": 13}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "open \"http://localhost:8080/?ws=localhost:8080&port=5858\" &\n\nsource bin/credentials-bothelp.sh\n\nset -x\n\nSERVER_ENV=${SERVER_ENV} \\\nGITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\nGITTER_APP_KEY=${GITTER_APP_KEY} \\\nGITTER_APP_SECRET=${GITTER_APP_SECRET} \\\nLOG_LEVEL=10 \\\nPORT=7891 \\\n    node-debug app.js\n\n    # node debug app.js\n\n    # node-debug app.js\n    # nodemon -x node app.js\n    # nodemon app.js\n    # node-debug app.js\n", "num_lines": 21}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nbin/wiki-update.sh\nssh freecodecamp@104.131.2.16 \"cd /home/freecodecamp/www/gitterbot/nap && \\\n    git clean -f && \\\n    git checkout . && \\\n    git pull && \\\n    pm2 restart all\"\n\n\n    # bin/pm2-update.sh\"\n", "num_lines": 13}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "git checkout .\ngit clean -f\ngit reset --hard HEAD\n\ngit pull\n", "num_lines": 6}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "git reset --hard HEAD\ngit clean -f\n", "num_lines": 3}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "open \"http://localhost:8080/?ws=localhost:8080&port=5858\" &\n\nsource bin/credentials.sh\n\nset -x\n\nGITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\n    GITTER_APP_KEY=${GITTER_APP_KEY} \\\n    GITTER_APP_SECRET=${GITTER_APP_SECRET} \\\n    mocha --debug-brk --harmony\n\n", "num_lines": 12}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "\n\n\n\nsource bin/credentials-camperbot.sh\n\nset -x\n\nSERVER_ENV=prod \\\nGITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\nGITTER_APP_KEY=${GITTER_APP_KEY} \\\nGITTER_APP_SECRET=${GITTER_APP_SECRET} \\\nLOG_LEVEL=10 \\\nPORT=7891 \\\n    pm2 start --name bot --interpreter node app.js\n\n    # node app.js\n    # node app.js\n    # nodemon -x node app.js\n\npm2 list\npm2 logs all\n", "num_lines": 23}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x\n\napproot=\"/home/freecodecamp/www/gitterbot/nap\"\nlogpath=\"${approot}/logs/bot.log\"\n\ngit pull && pm2 restart all && pm2 logs > $logpath &&\ntail -f $logpath\n", "num_lines": 9}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "source bin/credentials.sh\n\nBOTZYROOM=\"55b1a9030fc9f982beaac901\"\n\ncurl -X POST -i -H \"Content-Type: application/json\" \\\n    -H \"Accept: application/json\" \\\n    -H \"Authorization: Bearer ${GITTER_USER_TOKEN}\" \\\n    \"https://api.gitter.im/v1/rooms/${BOTZYROOM}/chatMessages\" \\\n    -d '{\"text\":\"curl test\"}'\n", "num_lines": 10}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "\n\n# bin/update-wiki.sh\n\n#source bin/credentials-bothelp.sh\n\n#set -x\n#\n#SERVER_ENV=local \\\n#GITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\n#GITTER_APP_KEY=${GITTER_APP_KEY} \\\n#GITTER_APP_SECRET=${GITTER_APP_SECRET} \\\n#LOG_LEVEL=10 \\\n#PORT=7891 \\\n\n# nodemon -x node app.js\n\n    # nodemon app.js\n\nnodemon app.js\n", "num_lines": 21}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# open \"http://localhost:8080/?ws=localhost:8080&port=5858\" &\n\nsource bin/credentials-bothelp.sh\n\nset -x\n\nSERVER_ENV=${SERVER_ENV} \\\nGITTER_USER_TOKEN=${GITTER_USER_TOKEN} \\\nGITTER_APP_KEY=${GITTER_APP_KEY} \\\nGITTER_APP_SECRET=${GITTER_APP_SECRET} \\\nLOG_LEVEL=10 \\\nPORT=7891 \\\n    node-debug app.js\n    # node debug app.js\n    # nodemon -x node app.js\n    # nodemon app.js\n", "num_lines": 17}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# \nbin/update-wiki.sh\nbin/run-dev-bothelp.sh", "num_lines": 3}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# pull down wiki files\n# don't commit them back\n# just used on prod server\n#\n# used on the production server only\n\nAPPDIR=/home/freecodecamp/www/gitterbot\n\nGITPATH=/usr/bin/git\n\n\ncd $APPDIR/data/fcc.wiki\n$GITPATH fetch\n$GITPATH checkout master\n$GITPATH pull origin master\ncd $APPDIR\n", "num_lines": 17}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# pull down wiki files\n# don't commit them back\n# just used on prod server\n\n# set -x\n\ngit submodule init\ngit submodule update --init --checkout --recursive --remote\n# cd data/fcc.wiki\n# git fetch\n# git checkout master\n# git pull origin master\n", "num_lines": 13}
{"repo_name": "camper-gitter-bot", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# pull down wiki files\n\ncd data/fcc.wiki\ngit fetch\ngit checkout master\ngit pull origin master\n", "num_lines": 7}
{"repo_name": "chapter", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "set -o pipefail\ngit diff --exit-code HEAD | cat\nif [ $? -eq 1 ]; then\necho \"\nGenerated code must be commited.\nIf the above diff is of graphql.tsx you'll need run 'npm run gen'.\nIf it's anything else, a bit of investigation is required.\n\nOnce you've done that, you can commit the changes and all should be well.\"\nexit 1\nfi\n", "num_lines": 12}
{"repo_name": "chapter", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "set -o pipefail\ngit add .\ngit diff --exit-code HEAD > /dev/null\nif [ $? -eq 1 ]; then\necho \"\nChanges to the schema must be saved as migrations.\n\nRun npm run db:migrate:dev and follow the instructions to generate a new migration file.\nOnce you've done that, commit and push the changes.\"\nexit 1\nfi\n", "num_lines": 12}
{"repo_name": "chapter", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nif [[ $(git remote -v | grep 'upstream' | wc -l) -eq 0 ]]; then\n  echo \"Upstream remote not found, adding one\"\n  git remote add upstream https://github.com/freeCodeCamp/chapter.git\nfi\n\ngit fetch upstream\n\ngit checkout main\ngit reset --hard upstream/main\n\necho \"\"\necho \"Git remotes have been setup successfully\"\n", "num_lines": 17}
{"repo_name": "fcc-expressworks", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\n# The script will set up expressworks on c9.io\n\necho \"Setting up nvm...\"\nsource ~/.nvm/nvm.sh\nV11_LEVEL=v4.1\n\n# Install node\nnvm install ${V11_LEVEL}\n\n# Set that level as default\nnvm use ${V11_LEVEL}\n\n# Set current level to latest v0.11.* level\nnvm alias default ${V11_LEVEL}\n\n# Update c9 express to > v4 due to JSON spacing issue\necho \"Updating express...\"\n\nnpm uninstall express && npm install express@'>=4.0.0'\n\necho \"Setting up expressworks...\"\n\n# Pull expressworks with a longer timeout\ncd ~/workspace\ngit clone http://github.com/reddock/expressworks\n\n# Install expressworks\nnpm install -g expressworks/\n\necho \"Done.\"\n", "num_lines": 32}
{"repo_name": "freeCodeCamp", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "InstallCypress() {\n    sudo apt-get update && sudo apt-get install -y \\\n        libgtk2.0-0 \\\n        libgtk-3-0 \\\n        libgbm-dev \\\n        libnotify-dev \\\n        libgconf-2-4 \\\n        libnss3 \\\n        libxss1 \\\n        libasound2 \\\n        libxtst6 \\\n        xauth \\\n        xvfb\n}\n\nInstallPuppeteer() {\n    sudo apt-get install -y \\\n        ca-certificates \\\n        fonts-liberation \\\n        libappindicator3-1 \\\n        libatk-bridge2.0-0 \\\n        libatk1.0-0 \\\n        libc6 \\\n        libcairo2 \\\n        libcups2 \\\n        libdbus-1-3 \\\n        libexpat1 \\\n        libfontconfig1 \\\n        libgbm1 \\\n        libgcc1 \\\n        libglib2.0-0 \\\n        libnspr4 \\\n        libpango-1.0-0 \\\n        libpangocairo-1.0-0 \\\n        libstdc++6 \\\n        libx11-6 \\\n        libx11-xcb1 \\\n        libxcb1 \\\n        libxcomposite1 \\\n        libxcursor1 \\\n        libxdamage1 \\\n        libxext6 \\\n        libxfixes3 \\\n        libxi6 \\\n        libxrandr2 \\\n        libxrender1 \\\n        lsb-release \\\n        wget \\\n        xdg-utils\n}\n\nInstallCypress\nInstallPuppeteer\n", "num_lines": 54}
{"repo_name": "freeCodeCampOS", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nsource ./bash/.bashrc\necho \"BashRC Sourced\"\n", "num_lines": 4}
{"repo_name": "hackathon-leaderboard", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# --build: Build images before starting containers.\n# --abort-on-container-exit: Stops all containers if any container is stopped\ndocker-compose up --build --abort-on-container-exit\n", "num_lines": 6}
{"repo_name": "hackathon-leaderboard", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# --build: Build images before starting containers.\n# --abort-on-container-exit: Stops all containers if any container is stopped\ndocker-compose -f 'docker-compose.test.yml' -p ci up --build --abort-on-container-exit\nexit $(docker wait ci_express-mongoose-es6-rest-api_1)\n", "num_lines": 7}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nuser_name=$(cat /tmp/install-user.txt)\n\n## This wrapper file re-uses scripts in the /templates directory\n## of this repo. These are the same that are used by the user_data functionality\n## to bootstrap the instance if it is started from an existing AMI.\n${install_runner}\n", "num_lines": 9}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash -e\nexec > >(tee /var/log/runner-startup.log | logger -t user-data -s 2>/dev/console) 2>&1\n\ncd /opt/actions-runner\n\n## This wrapper file re-uses scripts in the /templates directory\n## of this repo. These are the same that are used by the user_data functionality\n## to bootstrap the instance if it is started from an existing AMI.\n${start_runner}\n", "num_lines": 10}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# shellcheck shell=bash\n\n## install the runner\n\ns3_location=${S3_LOCATION_RUNNER_DISTRIBUTION}\narchitecture=${RUNNER_ARCHITECTURE}\n\nif [ -z \"$RUNNER_TARBALL_URL\" ] && [ -z \"$s3_location\" ]; then\n  echo \"Neither RUNNER_TARBALL_URL or s3_location are set\"\n  exit 1\nfi\n\nfile_name=\"actions-runner.tar.gz\"\n\necho \"Setting up GH Actions runner tool cache\"\n# Required for various */setup-* actions to work, location is also know by various environment\n# variable names in the actions/runner software : RUNNER_TOOL_CACHE / RUNNER_TOOLSDIRECTORY / AGENT_TOOLSDIRECTORY\n# Warning, not all setup actions support the env vars and so this specific path must be created regardless\nmkdir -p /opt/hostedtoolcache\n\necho \"Creating actions-runner directory for the GH Action installation\"\ncd /opt/\nmkdir -p actions-runner && cd actions-runner\n\nif [[ -n \"$RUNNER_TARBALL_URL\" ]]; then\n  echo \"Downloading the GH Action runner from $RUNNER_TARBALL_URL to $file_name\"\n  curl -o $file_name -L \"$RUNNER_TARBALL_URL\"\nelse\n  echo \"Retrieving TOKEN from AWS API\"\n  token=$(curl -f -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 180\")\n\n  region=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)\n  echo \"Retrieved REGION from AWS API ($region)\"\n\n  echo \"Downloading the GH Action runner from s3 bucket $s3_location\"\n  aws s3 cp \"$s3_location\" \"$file_name\" --region \"$region\"\nfi\n\necho \"Un-tar action runner\"\ntar xzf ./$file_name\necho \"Delete tar file\"\nrm -rf $file_name\n\nif [[ \"$architecture\" == \"arm64\" ]]; then\n  yum install -y libicu60\nfi\n\nos_id=$(awk -F= '/^ID/{print $2}' /etc/os-release)\nif [[ \"$os_id\" =~ ^ubuntu.* ]]; then\n  echo \"Installing dependencies\"\n  ./bin/installdependencies.sh\nfi\n\necho \"Set file ownership of action runner\"\nchown -R \"$user_name\":\"$user_name\" .\nchown -R \"$user_name\":\"$user_name\" /opt/hostedtoolcache\n", "num_lines": 57}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "# shellcheck shell=bash\n\n## Retrieve instance metadata\n\necho \"Retrieving TOKEN from AWS API\"\ntoken=$(curl -f -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 180\")\n\nami_id=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/meta-data/ami-id)\n\nregion=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/dynamic/instance-identity/document | jq -r .region)\necho \"Retrieved REGION from AWS API ($region)\"\n\ninstance_id=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/meta-data/instance-id)\necho \"Retrieved INSTANCE_ID from AWS API ($instance_id)\"\n\nenvironment=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:environment)\necho \"Retrieved ghr:environment tag - ($environment)\"\n\nssm_config_path=$(curl -f -H \"X-aws-ec2-metadata-token: $token\" -v http://169.254.169.254/latest/meta-data/tags/instance/ghr:ssm_config_path)\necho \"Retrieved ghr:ssm_config_path tag - ($ssm_config_path)\"\n\n\nparameters=$(aws ssm get-parameters-by-path --path \"$ssm_config_path\" --region \"$region\" --query \"Parameters[*].{Name:Name,Value:Value}\")\necho \"Retrieved parameters from AWS SSM ($parameters)\"\n\nrun_as=$(echo \"$parameters\" | jq -r '.[] | select(.Name == \"'$ssm_config_path'/run_as\") | .Value')\necho \"Retrieved /$ssm_config_path/run_as parameter - ($run_as)\"\n\nenable_cloudwatch_agent=$(echo \"$parameters\" | jq --arg ssm_config_path \"$ssm_config_path\" -r '.[] | select(.Name == \"'$ssm_config_path'/enable_cloudwatch\") | .Value')\necho \"Retrieved /$ssm_config_path/enable_cloudwatch parameter - ($enable_cloudwatch_agent)\"\n\nagent_mode=$(echo \"$parameters\" | jq --arg ssm_config_path \"$ssm_config_path\" -r '.[] | select(.Name == \"'$ssm_config_path'/agent_mode\") | .Value')\necho \"Retrieved /$ssm_config_path/agent_mode parameter - ($agent_mode)\"\n\ntoken_path=$(echo \"$parameters\" | jq --arg ssm_config_path \"$ssm_config_path\" -r '.[] | select(.Name == \"'$ssm_config_path'/token_path\") | .Value')\necho \"Retrieved /$ssm_config_path/token_path parameter - ($token_path)\"\n\nif [[ \"$enable_cloudwatch_agent\" == \"true\" ]]; then\n  echo \"Cloudwatch is enabled\"\n  amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c \"ssm:$ssm_config_path/cloudwatch_agent_config_runner\"\nfi\n\n## Configure the runner\n\necho \"Get GH Runner config from AWS SSM\"\nconfig=$(aws ssm get-parameter --name \"$token_path\"/\"$instance_id\" --with-decryption --region \"$region\" | jq -r \".Parameter | .Value\")\nwhile [[ -z \"$config\" ]]; do\n  echo \"Waiting for GH Runner config to become available in AWS SSM\"\n  sleep 1\n  config=$(aws ssm get-parameter --name \"$token_path\"/\"$instance_id\" --with-decryption --region \"$region\" | jq -r \".Parameter | .Value\")\ndone\n\necho \"Delete GH Runner token from AWS SSM\"\naws ssm delete-parameter --name \"$token_path\"/\"$instance_id\" --region \"$region\"\n\nif [ -z \"$run_as\" ]; then\n  echo \"No user specified, using default ec2-user account\"\n  run_as=\"ec2-user\"\nfi\n\nif [[ \"$run_as\" == \"root\" ]]; then\n  echo \"run_as is set to root - export RUNNER_ALLOW_RUNASROOT=1\"\n  export RUNNER_ALLOW_RUNASROOT=1\nfi\n\nchown -R $run_as .\n\necho \"Configure GH Runner as user $run_as\"\nsudo --preserve-env=RUNNER_ALLOW_RUNASROOT -u \"$run_as\" -- ./config.sh --unattended --name \"$instance_id\" --work \"_work\" $${config}\n\ninfo_arch=$(uname -p)\ninfo_os=$(( lsb_release -ds || cat /etc/*release || uname -om ) 2>/dev/null | head -n1 | cut -d \"=\" -f2- | tr -d '\"')\n\ntee /opt/actions-runner/.setup_info <<EOL\n[\n  {\n    \"group\": \"Operating System\",\n    \"detail\": \"Distribution: $info_os\\nArchitecture: $info_arch\"\n  },\n  {\n    \"group\": \"Runner Image\",\n    \"detail\": \"AMI id: $ami_id\"\n  }\n]\nEOL\n\n\n## Start the runner\necho \"Starting runner after $(awk '{print int($1/3600)\":\"int(($1%3600)/60)\":\"int($1%60)}' /proc/uptime)\"\necho \"Starting the runner as user $run_as\"\n\nif [[ $agent_mode = \"ephemeral\" ]]; then\n\ncat >/opt/start-runner-service.sh <<-EOF\n  echo \"Starting the runner in ephemeral mode\"\n  sudo --preserve-env=RUNNER_ALLOW_RUNASROOT -u \"$run_as\" -- ./run.sh\n  echo \"Runner has finished\"\n\n  echo \"Stopping cloudwatch service\"\n  systemctl stop amazon-cloudwatch-agent.service\n  echo \"Terminating instance\"\n  aws ec2 terminate-instances --instance-ids \"$instance_id\" --region \"$region\"\nEOF\n  chmod 755 /opt/start-runner-service.sh\n  # Starting the runner via a own process to ensure this process terminates\n  nohup /opt/start-runner-service.sh &\n\nelse\n  echo \"Installing the runner as a service\"\n  ./svc.sh install \"$run_as\"\n  echo \"Starting the runner in persistent mode\"\n  ./svc.sh start\nfi\n", "num_lines": 114}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT do-cleanup.sh: $1\"\n}\n\nlogger \"Executing\"\n\nDEBIAN_FRONTEND=noninteractive\n\nlogger \"Cleanup\"\napt-get -y autoremove\napt-get -y autoclean\napt-get -y clean\napt-get -y purge\n\nrm -rf /tmp/*\nrm -rf /ops\n\nlogger \"Completed\"\n", "num_lines": 23}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Waiting for cloud-init to update /etc/apt/sources.list\"\ntimeout 180 /bin/bash -c \\\n  'until stat /var/lib/cloud/instance/boot-finished 2>/dev/null; do echo waiting ...; sleep 1; done'\n\n# Disable interactive apt prompts\nexport DEBIAN_FRONTEND=noninteractive\necho 'debconf debconf/frontend select Noninteractive' | sudo debconf-set-selections\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT do-presetup.sh: $1\"\n}\n\nlogger \"Executing\"\n\nlogger \"Update the base operating system\"\napt-get -y update\napt-get -y upgrade\n\nlogger \"Install common dependencies\"\napt-get -y install build-essential\napt-get -y install curl\napt-get -y install git\napt-get -y install jq\napt-get -y install software-properties-common\napt-get -y install tar\napt-get -y install unzip\napt-get -y install zip\n\nlogger \"Completed\"\n", "num_lines": 35}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT consul.sh: $1\"\n}\n\nlogger \"Executing\"\nexport DEBIAN_FRONTEND=noninteractive\n\nlogger \"Adding Hashicorp apt keys\"\ncd /tmp\ncurl --fail --silent --show-error --location https://apt.releases.hashicorp.com/gpg |\n  gpg --dearmor |\n  sudo dd of=/usr/share/keyrings/hashicorp-archive-keyring.gpg\n\nFILE=/etc/apt/sources.list.d/hashicorp.list\nif test -f \"$FILE\"; then\n  logger \"Warn: sources list $FILE already exists. Skipping sources configuration.\"\nelse\n  logger \"Info: sources list $FILE does not exit. Configuring sources.\"\n  echo \"deb [arch=amd64 signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main\" |\n    sudo tee -a /etc/apt/sources.list.d/hashicorp.list >/dev/null\nfi\n\nlogger \"Installing Consul\"\nexport CONSUL_VERSION=\"1.8.3\"\nsudo apt-get update\nsudo apt-get install -y consul=$CONSUL_VERSION\n\nlogger \"Checking Consul version\"\nconsul version\n\nlogger \"Completed\"\n", "num_lines": 36}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT docker.sh: $1\"\n}\n\nlogger \"Executing\"\nexport DEBIAN_FRONTEND=noninteractive\n\nlogger \"Adding Docker apt keys\"\ncd /tmp\ncurl --fail --silent --show-error --location https://download.docker.com/linux/ubuntu/gpg |\n  gpg --dearmor |\n  sudo dd of=/usr/share/keyrings/docker.gpg\n\nFILE=/etc/apt/sources.list.d/docker.list\nif test -f \"$FILE\"; then\n  logger \"Warn: sources list $FILE already exists. Skipping sources configuration.\"\nelse\n  logger \"Info: sources list $FILE does not exit. Configuring sources.\"\n  echo \\\n    \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \\\n    $(lsb_release -cs) stable\" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null\nfi\n\nlogger \"Installing Docker\"\napt-get update -y\napt-get install -y docker-ce docker-ce-cli containerd.io\n\nsystemctl start docker\nsystemctl enable docker\n\nsh -c \"echo \\\"DOCKER_OPTS='--dns 127.0.0.1 --dns 8.8.8.8 --dns-search service.consul'\\\" >> /etc/default/docker\"\n\nservice docker restart\n\nlogger \"Completed\"\n", "num_lines": 40}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT golang.sh: $1\"\n}\n\nlogger \"Executing\"\n\nexport DEBIAN_FRONTEND=noninteractive\n\ncd /tmp\n\nGOVERSION=1.6\nGODOWNLOAD=https://storage.googleapis.com/golang/go${GOVERSION}.linux-amd64.tar.gz\nPROFILE=/etc/profile\nGODIR=/usr/local\nGOROOT=$GODIR/go\nGOPATH=/opt/go\n\nexport GOROOT=$GOROOT\nexport GOPATH=$GOPATH\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\n\nlogger \"Fetching Go\"\ncurl -L $GODOWNLOAD > go.tar.gz\n\nlogger \"Installing Go\"\ntar -C $GODIR -xzf go.tar.gz\nchmod 0755 $GOROOT\nchown root:root $GOROOT\n\nlogger \"Configuring Go\"\ncat <<EOF >>${PROFILE}\n\nexport GOROOT=$GOROOT\nexport GOPATH=$GOPATH\nexport PATH=$PATH:$GOROOT/bin:$GOPATH/bin\nEOF\n\nmkdir -p \"$GOPATH/bin\"\nchmod 0755 $GOPATH/bin\nchown root:root $GOPATH/bin\n\nlogger \"Completed\"\n", "num_lines": 47}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT nginx.sh: $1\"\n}\n\nlogger \"Executing\"\n\nexport DEBIAN_FRONTEND=noninteractive\n\nlogger \"Update the box\"\napt-get -y update\napt-get -y upgrade\n\nlogger \"Install Nginx\"\n\napt-get -y install nginx\n\nlogger \"Configure Nginx\"", "num_lines": 21}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nlogger() {\n  DT=$(date '+%Y/%m/%d %H:%M:%S')\n  echo \"$DT nomad.sh: $1\"\n}\n\nlogger \"Executing\"\nexport DEBIAN_FRONTEND=noninteractive\n\nlogger \"Adding Hashicorp apt keys\"\ncd /tmp\ncurl --fail --silent --show-error --location https://apt.releases.hashicorp.com/gpg |\n  gpg --dearmor |\n  sudo dd of=/usr/share/keyrings/hashicorp-archive-keyring.gpg\n\nFILE=/etc/apt/sources.list.d/hashicorp.list\nif test -f \"$FILE\"; then\n  logger \"Warn: sources list $FILE already exists. Skipping sources configuration.\"\nelse\n  logger \"Info: sources list $FILE does not exit. Configuring sources.\"\n  echo \"deb [arch=amd64 signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main\" |\n    sudo tee -a /etc/apt/sources.list.d/hashicorp.list >/dev/null\nfi\n\nlogger \"Installing Nomad\"\nexport NOMAD_VERSION=\"1.4.4-1\"\nsudo apt-get update\nsudo apt-get install -y nomad=$NOMAD_VERSION\n\nlogger \"Checking Nomad version\"\nnomad version\n\nlogger \"Completed\"\n", "num_lines": 36}
{"repo_name": "infra", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/sh\n# <UDF name=\"userdata\" label=\"user-data file contents (base64 encoded)\" />\nset +e +x\nFILE_USERDATA=\"/var/lib/cloud/seed/nocloud-net/user-data\"\nFILE_METADATA=\"/var/lib/cloud/seed/nocloud-net/meta-data\"\n# vendor-data and network-config are optional\n\necho \"Configuring cloud-init...\"\necho \"set cloud-init/datasources NoCloud\" | debconf-communicate\nmkdir -p /etc/cloud/cloud.cfg.d /var/lib/cloud/seed/nocloud-net/\n\nif [ -n \"$LINODE_ID\" ]; then\ncat > /etc/cloud/cloud.cfg.d/01-instanceid.cfg <<'EOS'\ndatasource:\n  NoCloud:\n    meta-data:\n       instance-id: linode$LINODE_ID\nEOS\nfi\n\ncat > /etc/cloud/cloud.cfg.d/99-warnings.cfg <<'EOS'\n#cloud-config\nwarnings:\n  dsid_missing_source: off\nEOS\n\nUMASK=$(umask)\numask 0066\necho \"Creating $FILE_METADATA...\"\ntouch \"${FILE_METADATA}\"\n\necho \"Creating $FILE_USERDATA...\"\ntouch \"${FILE_USERDATA}\"\necho \"${USERDATA}\" | base64 -d > \"${FILE_USERDATA}\"\numask \"${UMASK}\"\n\necho \"Installing cloud-init...\"\napt-get -q=2 update\napt-get -q=2 install -y cloud-init\n\necho \"Running cloud-init... (init, config, and final)\"\ncloud-init init\ncloud-init modules --mode=config\ncloud-init modules --mode=final\n", "num_lines": 45}
{"repo_name": "LearnToCodeRPG", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "butler push ../LearnToCodeRPG-1.5-dists/LearnToCodeRPG-1.5-linux.tar.bz2 freecodecamp/learn-to-code-rpg:linux --userversion-file game/version.txt\nbutler push ../LearnToCodeRPG-1.5-dists/LearnToCodeRPG-1.5-mac.zip freecodecamp/learn-to-code-rpg:mac --userversion-file game/version.txt\nbutler push ../LearnToCodeRPG-1.5-dists/LearnToCodeRPG-1.5-pc.zip freecodecamp/learn-to-code-rpg:win --userversion-file game/version.txt\n", "num_lines": 4}
{"repo_name": "near-curriculum", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nsource ./bash/.bashrc\necho \"BashRC Sourced\"\n", "num_lines": 4}
{"repo_name": "open-api", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nBRANCH=${TRAVIS_BRANCH:-$(git rev-parse --abbrev-ref HEAD)}\n\nif [[ $BRANCH == 'master' ]]; then\n  STAGE=\"prod\"\n  export AUTH0_CLIENT_ID=$AUTH0_CLIENT_ID_PROD\n  export AUTH0_CLIENT_SECRET=$AUTH0_CLIENT_SECRET_PROD\n  export AUTH0_NAMESPACE=$AUTH0_NAMESPACE_PROD\n  export GRAPHQL_ENDPOINT_URL=$GRAPHQL_ENDPOINT_URL_PROD\n  export JWT_CERT=$JWT_CERT_PROD\n  export MONGODB_URL=$MONGODB_URL_PROD\nelif [[ $BRANCH == 'staging' ]]; then\n  STAGE=\"stage\"\n  export AUTH0_CLIENT_ID=$AUTH0_CLIENT_ID_STAGE\n  export AUTH0_CLIENT_SECRET=$AUTH0_CLIENT_SECRET_STAGE\n  export AUTH0_NAMESPACE=$AUTH0_NAMESPACE_STAGE\n  export GRAPHQL_ENDPOINT_URL=$GRAPHQL_ENDPOINT_URL_STAGE\n  export JWT_CERT=$JWT_CERT_STAGE\n  export MONGODB_URL=$MONGODB_URL_STAGE\nfi\n\nif [ -z ${STAGE+x} ]; then\n  echo \"Only deploying for staging or production branches\"\n  exit 0\nfi\n\nif [[ $STAGE != 'stage' ]]; then\n  echo \"Only stage deployments for now, sorry!\"\n  exit 0\nfi\n\n\necho \"Deploying from branch $BRANCH to stage $STAGE\"\nyarn prepare-production\nsls deploy --stage $STAGE --region $AWS_REGION\n", "num_lines": 38}
{"repo_name": "react-notification", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Description: run tests normally, for local testing\n# Param 1: the reporter to use, defaults to spec\nrunTests()\n{\n  node_modules/.bin/mocha \\\n  --compilers js:babel-core/register \\\n  --reporter ${1-spec} \\\n  --recursive --timeout 5000 \\\n  test/setup.js test/**/*.js\n}\n\n# Description: run tests with Istanbul coverage\nrunIstanbul()\n{\n  NODE_ENV=test `npm bin`/istanbul cover \\\n  node_modules/.bin/_mocha \\\n  -- -u exports --compilers js:babel-core/register \\\n  --report lcovonly \\\n  test/polyfills.js test/*.js\n}\n\n# If on Travis, run tests with Istanbul\n# TODO: setup code coverage\n#if [ -n \"${TRAVIS_JOB_ID}\" ]; then\n\n  #echo -e \"Travis CI job id set to ${TRAVIS_JOB_ID}. \\nRunning tests with Istanbul...\"\n  #NODE_ENV=test runIstanbul\n\n  #echo \"Sending coverage information to Coveralls...\"\n  #cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js || true\n  #rm -rf ./coverage\n\n# Otherwise, when local, run tests normally without Istanbul\n#else\n  NODE_ENV=test runTests ${REPORTER}\n#fi\n", "num_lines": 39}
{"repo_name": "redirects", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "mkdir $1.freecodecamp.org\necho \"/* https://www.freecodecamp.org/news/$1/:splat\" >> $1.freecodecamp.org/_redirects", "num_lines": 2}
{"repo_name": "solana-curriculum", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nsource ./bash/.bashrc\necho \"BashRC Sourced\"\n", "num_lines": 4}
{"repo_name": "stock-price-checker-proxy", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "ulimit -n 128\nnode ./test_lac/openFds.test.js\n", "num_lines": 3}
{"repo_name": "store.js", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ncd \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\" # scripts/\ncd ../ # store.js project root\n\nVERSION=$1\nif [[ ! $VERSION =~ ^[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n\techo \"$VERSION is not a valid semver (e.g 2.1.3)\"\n\texit -1\nfi\n\nGIT_BRANCH=`git rev-parse --abbrev-ref HEAD`\nif [ \"$GIT_BRANCH\" != \"master\" ]; then\n\techo \"release.sh must be called from branch master (current: $GIT_BRANCH)\"\n\texit -1\nfi\n\nif ! git diff-index --quiet HEAD --; then\n\techo \"git repo is dirty. Commit all changes before using release.sh\"\n\texit -1\nfi\n\necho\necho \"> Bump package.json version:\"\necho\nsed -E s/'\"version\"\\: \"[0-9]+\\.[0-9]+\\.[0-9]+\"'/'\"version\"\\: \"'$VERSION'\"'/ package.json \\\n\t> /tmp/package.json && \\\n\tmv /tmp/package.json package.json\ncat package.json | grep $VERSION -C 1\n\necho\necho \"> Bump store-engine.js version:\"\necho\nsed -E s/\"version\\: '[0-9]+\\.[0-9]+\\.[0-9]+'\"/\"version\\: '$VERSION'\"/ src/store-engine.js \\\n\t> /tmp/store-engine.js && \\\n\tmv /tmp/store-engine.js src/store-engine.js\ncat src/store-engine.js | grep $VERSION -C 1\n\nif [[ ! `git diff --stat` =~ \"2 files changed, 2 insertions(+), 2 deletions(-)\" ]]; then\n\techo \"WARNING! Expected exactly 2 changes in 2 files after replacing version number. Bailing! (check git status and git diff)\"\n\texit -1\nfi\n\necho\nwhile true; do\n    read -p \"> Ready to build, commit, tag and release v$VERSION? (y/n): \" yn\n    case $yn in\n        [Yy]* )   break;;\n        [NnQq]* ) exit;;\n\t\t* ) echo \"Please answer yes or no.\";;\n    esac\ndone\n\necho\necho \"> Build dists\"\nnode scripts/compile-builds.js\n\necho\necho \"> git commit/push/tag/push --tags\"\nset -x\ngit add dist/* package.json src/store-engine.js\ngit commit -m \"v$VERSION\"\ngit push $ORIGIN $BRANCH\ngit tag -a \"v$VERSION\" -m \"Tag v$VERSION\"\ngit push --tags\nset +x\n\necho\necho \"> npm publish\"\nnpm publish\n", "num_lines": 72}
{"repo_name": "web3-curriculum", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nsource ./bash/.bashrc\necho \"BashRC Sourced\"\n", "num_lines": 4}
{"repo_name": "wiki", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\nrm -rf ../pages/*\n", "num_lines": 3}
{"repo_name": "wiki", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Automate Deployment -- bash script\n# - run clearPages.sh\u00ef\u0153\u00a9\n# - run\n# - git checkout master\n# - Pull down the Wiki\n# - Run Conversion  (See above)\n# - Run Cleanup (See above)\n# - Run Gatsby Build Operation\n# - git checkout gh-pages\n# - Copy files to `gh-pages`\n# - Commit files to that branch\n# - Git push\n\nupstream=\"live-gatsby\"\n\n./clearPages.sh\ngit pull ${upstream} master\nnode create_structure.js\nnode convert_files.js\ngit checkout gh-pages\ncd ..\ngatsby build --prefix-links\ncp -r public/docs/* docs/\ncp public/bundle.js ./\ncp public/index.html ./\ncp public/bundle.js.map ./\ngit add docs\ngit add bundle.js.map\ngit add bundle.js\ngit add index.html\ngit commit -m \"Page built on `date +\"%d-%m-%Y %T\"`\"\ngit push ${upstream} gh-pages\ngit checkout master\ngit push live master\n", "num_lines": 37}
{"repo_name": "ZiplineStatusChecker", "repo_creator": "freeCodeCamp", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -e server.js ]\nthen\n\techo \"Error: could not find main application server.js file\"\n\techo \"You should run the generate-ssl-certs.sh script from the main MEAN application root directory\"\n\techo \"i.e: bash scripts/generate-ssl-cers.sh\"\n\texit -1\nfi\n\necho \"Generating self-signed certificates...\"\nmkdir -p ./config/sslcerts\nopenssl genrsa -out ./config/sslcerts/key.pem -aes256 1024\nopenssl req -new -key ./config/sslcerts/key.pem -out ./config/sslcerts/csr.pem\nopenssl x509 -req -days 9999 -in ./config/sslcerts/csr.pem -signkey ./config/sslcerts/key.pem -out ./config/sslcerts/cert.pem\nrm ./config/sslcerts/csr.pem\nchmod 600 ./config/sslcerts/key.pem ./config/sslcerts/cert.pem\n", "num_lines": 18}
{"repo_name": "assign-one-project-github-action", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh -l\n\nPROJECT_URL=\"$INPUT_PROJECT\"\nif [ -z \"$PROJECT_URL\" ]; then\n  echo \"PROJECT_URL is not defined.\" >&2\n  exit 1\nfi\n\nget_project_type() {\n  _PROJECT_URL=\"$1\"\n\n  case \"$_PROJECT_URL\" in\n    https://github.com/orgs/*)\n      echo \"org\"\n      ;;\n    https://github.com/users/*)\n      echo \"user\"\n      ;;\n    https://github.com/*/projects/*)\n      echo \"repo\"\n      ;;\n    *)\n      echo \"Invalid PROJECT_URL: $_PROJECT_URL\" >&2\n      exit 1\n      ;;\n  esac\n\n  unset _PROJECT_URL\n}\n\nfind_project_id() {\n  _PROJECT_TYPE=\"$1\"\n  _PROJECT_URL=\"$2\"\n\n  case \"$_PROJECT_TYPE\" in\n    org)\n      _ORG_NAME=$(echo \"$_PROJECT_URL\" | sed -e 's@https://github.com/orgs/\\([^/]\\+\\)/projects/[0-9]\\+@\\1@')\n      _ENDPOINT=\"https://api.github.com/orgs/$_ORG_NAME/projects\"\n      ;;\n    user)\n      _USER_NAME=$(echo \"$_PROJECT_URL\" | sed -e 's@https://github.com/users/\\([^/]\\+\\)/projects/[0-9]\\+@\\1@')\n      _ENDPOINT=\"https://api.github.com/users/$_USER_NAME/projects\"\n      ;;\n    repo)\n      _ENDPOINT=\"https://api.github.com/repos/$GITHUB_REPOSITORY/projects\"\n      ;;\n  esac\n\n  _PROJECTS=$(curl -s -X GET -u \"$GITHUB_ACTOR:$TOKEN\" --retry 3 \\\n           -H 'Accept: application/vnd.github.inertia-preview+json' \\\n           \"$_ENDPOINT\")\n\n  _PROJECTID=$(echo \"$_PROJECTS\" | jq -r \".[] | select(.html_url == \\\"$_PROJECT_URL\\\").id\")\n\n  if [ \"$_PROJECTID\" != \"\" ]; then\n    echo \"$_PROJECTID\"\n  else\n    echo \"No project was found.\" >&2\n    exit 1\n  fi\n\n  unset _PROJECT_TYPE _PROJECT_URL _ORG_NAME _USER_NAME _ENDPOINT _PROJECTS _PROJECTID\n}\n\nfind_column_id() {\n  _PROJECT_ID=\"$1\"\n  _INITIAL_COLUMN_NAME=\"$2\"\n\n  _COLUMNS=$(curl -s -X GET -u \"$GITHUB_ACTOR:$TOKEN\" --retry 3 \\\n          -H 'Accept: application/vnd.github.inertia-preview+json' \\\n          \"https://api.github.com/projects/$_PROJECT_ID/columns\")\n\n\n  echo \"$_COLUMNS\" | jq -r \".[] | select(.name == \\\"$_INITIAL_COLUMN_NAME\\\").id\"\n  unset _PROJECT_ID _INITIAL_COLUMN_NAME _COLUMNS\n}\n\nPROJECT_TYPE=$(get_project_type \"${PROJECT_URL:?<Error> required this environment variable}\")\n\nif [ \"$PROJECT_TYPE\" = org ] || [ \"$PROJECT_TYPE\" = user ]; then\n  if [ -z \"$MY_GITHUB_TOKEN\" ]; then\n    echo \"MY_GITHUB_TOKEN not defined\" >&2\n    exit 1\n  fi\n\n  TOKEN=\"$MY_GITHUB_TOKEN\" # It's User's personal access token. It should be secret.\nelse\n  if [ -z \"$GITHUB_TOKEN\" ]; then\n    echo \"GITHUB_TOKEN not defined\" >&2\n    exit 1\n  fi\n\n  TOKEN=\"$GITHUB_TOKEN\"    # GitHub sets. The scope in only the repository containing the workflow file.\nfi\n\nINITIAL_COLUMN_NAME=\"$INPUT_COLUMN_NAME\"\nif [ -z \"$INITIAL_COLUMN_NAME\" ]; then\n  # assing the column name by default\n  INITIAL_COLUMN_NAME='To do'\n  if [ \"$GITHUB_EVENT_NAME\" == \"pull_request\" ]; then\n    echo \"changing col name for PR event\"\n    INITIAL_COLUMN_NAME='In progress'\n  fi\nfi\n\n\nPROJECT_ID=$(find_project_id \"$PROJECT_TYPE\" \"$PROJECT_URL\")\nINITIAL_COLUMN_ID=$(find_column_id \"$PROJECT_ID\" \"${INITIAL_COLUMN_NAME:?<Error> required this environment variable}\")\n\nif [ -z \"$INITIAL_COLUMN_ID\" ]; then\n  echo \"INITIAL_COLUMN_ID is not found.\" >&2\n  exit 1\nfi\n\ncase \"$GITHUB_EVENT_NAME\" in\n  issues)\n    ISSUE_ID=$(jq -r '.issue.id' < \"$GITHUB_EVENT_PATH\")\n\n    # Add this issue to the project column\n    curl -s -X POST -u \"$GITHUB_ACTOR:$TOKEN\" --retry 3 \\\n     -H 'Accept: application/vnd.github.inertia-preview+json' \\\n     -d \"{\\\"content_type\\\": \\\"Issue\\\", \\\"content_id\\\": $ISSUE_ID}\" \\\n     \"https://api.github.com/projects/columns/$INITIAL_COLUMN_ID/cards\"\n    ;;\n  pull_request)\n    PULL_REQUEST_ID=$(jq -r '.pull_request.id' < \"$GITHUB_EVENT_PATH\")\n\n    # Add this pull_request to the project column\n    curl -s -X POST -u \"$GITHUB_ACTOR:$TOKEN\" --retry 3 \\\n     -H 'Accept: application/vnd.github.inertia-preview+json' \\\n     -d \"{\\\"content_type\\\": \\\"PullRequest\\\", \\\"content_id\\\": $PULL_REQUEST_ID}\" \\\n     \"https://api.github.com/projects/columns/$INITIAL_COLUMN_ID/cards\"\n    ;;\n  *)\n    echo \"Nothing to be done on this action: $GITHUB_EVENT_NAME\" >&2\n    exit 1\n    ;;\nesac\n", "num_lines": 139}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nif [ $(uname) == 'Linux' ] || [ $(uname) == 'Darwin' ]; then\n    ./multibuild.sh\nelse\n    ./win_build.sh\nfi\n", "num_lines": 9}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nfunction pre_build {\n    set -ex\n    build_zlib\n    pip install cmake\n}\n\nfunction run_tests {\n    python -c \"import atari_py; ale = atari_py.ALEInterface(); ale.loadROM(atari_py.get_game_path('tetris'))\"\n    pip install pytest\n    pytest --pyargs atari_py.tests\n}\n\n", "num_lines": 14}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "set -ex\nif [[ ! -z \"$TRAVIS_TAG\" ]]; then\n    pip install twine\n   twine upload --verbose wheelhouse/atari_py*\n\n    if [[ ! -z \"$DEPLOY_SDIST\" ]]; then\n        python setup.py sdist\n        twine upload dist/*\n    fi\nfi\n\n", "num_lines": 12}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# TRAVIS_TAG=0.1.14\n\nif [[ -z \"$TRAVIS_TAG\" ]]; then\n    echo \"Not a tagged commit, quitting\"\n    exit 0\nfi\n\npip install virtualenv --user\npython -m virtualenv --python=python3 .venv\nsource .venv/bin/activate\n\npip install awscli twine\n# make and deploy source archive\npython setup.py sdist\ntwine upload --verbose dist/atari*\n\n# get the wheels generated at the previous stages and upload them as well \nmkdir -p wheelhouse\nenv\n# ugh something in awscli does not work on travis we'll download objects via curl\n# aws s3 cp --recursive s3://games-wheels/atari-py/${TRAVIS_TAG} wheelhouse/\nSUFFIXES=\"-manylinux1_x86_64.whl -win_amd64.whl -macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl\"\n# SUFFIXES=\"-manylinux1_x86_64.whl\"\nPY_VERS=\"-cp36-cp36m -cp37-cp37m -cp35-cp35m\"\nURLPREFIX=\"https://s3-${AWS_DEFAULT_REGION}.amazonaws.com/${S3_BUCKET}/${S3_PREFIX}atari-py/${TRAVIS_TAG}/atari_py-${TRAVIS_TAG}\"\n\ncd wheelhouse\nfor s in $SUFFIXES; do\n  for p in $PY_VERS; do\n    curl -O -f ${URLPREFIX}${p}${s} || echo \"${URLPREFIX}${p}{s} not found\"\n  done;\ndone\n\ntwine upload --verbose atari*\n", "num_lines": 38}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "set -ex\nCONDA_VER=3.7.0\ncurl https://repo.continuum.io/miniconda/Miniconda3-${CONDA_VER}-MacOSX-x86_64.sh -o ~/miniconda.sh\nbash ~/miniconda.sh -b -p $HOME/miniconda\nexport PATH=\"$HOME/miniconda/bin:$PATH\"\n\nconda install pip\npython --version\npip --version\n", "num_lines": 10}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "set -ex\nexport REPO_DIR=.\nexport BUILD_COMMIT=$TRAVIS_COMMIT\nexport PLAT=x86_64\nexport MB_PYTHON_VERSION=$PY_VER\nexport MB_ML_VER=2014\nif [[ $TRAVIS_CPU_ARCH == \"arm64\" ]]\nthen\n  export PLAT=aarch64\n  export DOCKER_TEST_IMAGE=multibuild/xenial_arm64v8\nfi\n\ngit clone https://github.com/matthew-brett/multibuild && cd multibuild && git checkout 45d97819e7d39dd2264b2c3cd353c26c4e1ebb74 && cd ..\nsource multibuild/common_utils.sh\nsource multibuild/travis_steps.sh\nbefore_install\nbuild_wheel $REPO_DIR $PLAT\ninstall_run $PLAT\n\n", "num_lines": 20}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "set -ex\nchoco install --yes python3 --version $PY_VER\nexport PYROOT=/c/Python${PY_VER//./}\nexport PATH=$PYROOT:$PYROOT/Scripts:$PATH\npip install cmake pytest\n./installzlib.bat\nmkdir -p atari_py/ale_interface/build\n\ncd atari_py/ale_interface/build\ncmake -DCMAKE_GENERATOR_PLATFORM=x64 ..\ncmake --build .\ncp Debug/ale_c.dll ../\ncd ../../../\n\npip install wheel && pip wheel . -w wheelhouse --no-deps -vvv\nls wheelhouse/atari_py* \nrm -rf atari_py*\npip install $(ls wheelhouse/atari_py*)\npytest --pyargs atari_py.tests\n\n", "num_lines": 21}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# A script to generate an ALE video with FFMpeg, Mac OS X.\n\n# -r ## specifies the frame rate\n# -i record/%06d.png indicates we should use sequentially numbered frames in directory 'record'\n# -i sound.wav indicates the location of the sound file\n# -f mov specifies a MOV format\n# -c:a mp3 specifies the sound codec \n# -c:v libx264 specifies the video codec\n# -pix_fmt yuv420p is needed on Mac OS X for playback with QuickTime Player\n# \nffmpeg -r 60 -i record/%06d.png -i record/sound.wav -f mov -c:a mp3 -c:v libx264 -pix_fmt yuv420p agent.mov \n", "num_lines": 13}
{"repo_name": "atari-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# A script to generate an ALE video with FFMpeg, *nix systems. \n\n# -r ## specifies the frame rate\n# -i record/%06d.png indicates we should use sequentially numbered frames in directory 'record'\n# -i sound.wav indicates the location of the sound file\n# -f mov specifies a MOV format\n# -c:a mp3 specifies the sound codec \n# -c:v libx264 specifies the video codec\n# \n\n\n# Attempt to use ffmpeg. If this fails, use avconv (fix for Ubuntu 14.04). \n{\n    ffmpeg -r 60 -i record/%06d.png -i record/sound.wav -f mov -c:a mp3 -c:v libx264 agent.mov\n} || {\n    avconv -r 60 -i record/%06d.png -i record/sound.wav -f mov -c:a mp3 -c:v libx264 agent.mov\n}\n\n", "num_lines": 20}
{"repo_name": "blocksparse", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ \"$PMIX_RANK\" == \"0\" ]; then\n    nvprof -f -o nccl_test.nvvp python nccl_test.py\nelse\n    python nccl_test.py\nfi\n\n# nvprof -f -o \"dota_%p.nvvp\" --profile-child-processes", "num_lines": 9}
{"repo_name": "box2d-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nfunction pre_build {\n    set -ex\n    build_swig\n    pip install .\n    pip install nose coverage\n    nosetests -v -w tests/ --with-coverage --cover-package=Box2D\n}\n\nfunction run_tests {\n    pip install gym[box2d]\n    python -c \"import gym; gym.make('LunarLander-v2')\"\n}\n\n", "num_lines": 15}
{"repo_name": "box2d-py", "repo_creator": "openai", "programming_language": "Shell", "code": "set -ex\n\nif [[ ! -z \"$TRAVIS_TAG\" ]]; then\n    ls -lht ./wheelhouse\n    pip install twine\n    twine upload ./wheelhouse/box2d_py-*\n\n    if [[ ! -z \"$DEPLOY_SDIST\" ]]; then\n        python setup.py sdist       \n        twine upload dist/*\n    fi\nfi\n\n", "num_lines": 14}
{"repo_name": "ceph-chef", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Author:: Hans Chris Jones <chris.jones@lambdastack.io>\n#\n# Copyright 2017, Bloomberg Finance L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# IMPORTANT: DANGER - DANGER - DANGER\n# Can only be ran from a Ceph node\n\nfor pool in $(rados lspools); do\n  for obj in $(rados -p $pool ls); do\n    echo \"Removing $obj from pool $pool\"\n    rados -p $pool rm $obj\n  done\ndone\n", "num_lines": 30}
{"repo_name": "ceph-chef", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Author:: Hans Chris Jones <chris.jones@lambdastack.io>\n#\n# Copyright 2017, Bloomberg Finance L.P.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script takes 2 parameters: option and device\n# It uses the ceph-disk script to make things easier. You can also use\n# partx -s <device> to get a list of partitions without using ceph-disk\n# NOTE: If you delete a journal partition (assuming journals are on device\n# different than ceph data) then update the kernel with partprobe or partx\n# so that ceph-disk does not pickup something that says something like\n# 'other...' in journal partition descriptions.\n\n# OUTPUT: The ceph-disk script may output a warning message. This will\n# have no impact on the results of the script.\n\nopt=$1\ndev=$2\n\njournal=$(ceph-disk list | grep $dev | awk -F',' '{print $5}' 2>/dev/null)\n\n# returns the full journal output line from ceph-disk for the given device\nif [[ $opt == 0 ]]; then\n  echo $journal\nfi\n\n# NOTE: If you have not run partx or partprobe after removing a journal partition\n# (again only if the journals are not on the same device as the data) then\n# you may see output that looks like 'option' which will not format well.\n# returns the full device/partition of the given device\nif [[ $opt == 1 ]]; then\n  echo $journal | sed 's/journal //g'\nfi\n\n# Different 'if' clauses for 'opt' options\n# returns only the partition number. This is good for using in sgdisk or partx\n# for removing a specific journal partition.\nif [[ $opt == 2 ]]; then\n  echo $journal | sed 's/[a-Z]*[//]*//g'\nfi\n", "num_lines": 54}
{"repo_name": "consistency_models", "repo_creator": "openai", "programming_language": "Shell", "code": "####################################################################\n# Training EDM models on class-conditional ImageNet-64, and LSUN 256\n####################################################################\n\nmpiexec -n 8 python edm_train.py --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.1 --ema_rate 0.999,0.9999,0.9999432189950708 --global_batch_size 4096 --image_size 64 --lr 0.0001 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --schedule_sampler lognormal --use_fp16 True --weight_decay 0.0 --weight_schedule karras --data_dir /path/to/imagenet\n\npython -m orc.diffusion.scripts.train_imagenet_edm --attention_resolutions 32,16,8 --class_cond False --dropout 0.1 --ema_rate 0.999,0.9999,0.9999432189950708 --global_batch_size 256 --image_size 256 --lr 0.0001 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --schedule_sampler lognormal --use_fp16 True --use_scale_shift_norm False --weight_decay 0.0 --weight_schedule karras --data_dir /path/to/lsun_bedroom\n\n#########################################################################\n# Sampling from EDM models on class-conditional ImageNet-64, and LSUN 256\n#########################################################################\n\nmpiexec -n 8 python image_sample.py --training_mode edm --batch_size 64 --sigma_max 80 --sigma_min 0.002 --s_churn 0 --steps 40 --sampler heun --model_path edm_imagenet64_ema.pt --attention_resolutions 32,16,8  --class_cond True --dropout 0.1 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 50000 --resblock_updown True --use_fp16 True --use_scale_shift_norm True --weight_schedule karras\n\nmpiexec -n 8 python image_sample.py --training_mode edm --generator determ-indiv --batch_size 8 --sigma_max 80 --sigma_min 0.002 --s_churn 0 --steps 40 --sampler heun --model_path /path/to/edm_bedroom256_ema.pt --attention_resolutions 32,16,8  --class_cond False --dropout 0.1 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 50000 --resblock_updown True --use_fp16 True --use_scale_shift_norm False --weight_schedule karras\n\n#########################################################################\n# Consistency distillation on class-conditional ImageNet-64, and LSUN 256\n#########################################################################\n\n## L_CD^N (l2) on ImageNet-64\nmpiexec -n 8 python cm_train.py --training_mode consistency_distillation --target_ema_mode fixed --start_ema 0.95 --scale_mode fixed --start_scales 40 --total_training_steps 600000 --loss_norm l2 --lr_anneal_steps 0 --teacher_model_path /path/to/edm_imagenet64_ema.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.999,0.9999,0.9999432189950708 --global_batch_size 2048 --image_size 64 --lr 0.000008 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/data\n\n## L_CD^N (LPIPS) on ImageNet-64\nmpiexec -n 8 python cm_train.py --training_mode consistency_distillation --target_ema_mode fixed --start_ema 0.95 --scale_mode fixed --start_scales 40 --total_training_steps 600000 --loss_norm lpips --lr_anneal_steps 0 --teacher_model_path /path/to/edm_imagenet64_ema.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.999,0.9999,0.9999432189950708 --global_batch_size 2048 --image_size 64 --lr 0.000008 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/data\n\n## L_CD^N (l2) on LSUN 256\nmpiexec -n 8 python cm_train.py --training_mode consistency_distillation --sigma_max 80 --sigma_min 0.002 --target_ema_mode fixed --start_ema 0.95 --scale_mode fixed --start_scales 40 --total_training_steps 600000 --loss_norm l2 --lr_anneal_steps 0 --teacher_model_path /path/to/edm_bedroom256_ema.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.9999,0.99994,0.9999432189950708 --global_batch_size 256 --image_size 256 --lr 0.00001 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/bedroom256\n\n## L_CD^N (LPIPS) on LSUN 256\nmpiexec -n 8 python cm_train.py --training_mode consistency_distillation --sigma_max 80 --sigma_min 0.002 --target_ema_mode fixed --start_ema 0.95 --scale_mode fixed --start_scales 40 --total_training_steps 600000 --loss_norm lpips --lr_anneal_steps 0 --teacher_model_path /path/to/edm_bedroom256_ema.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.9999,0.99994,0.9999432189950708 --global_batch_size 256 --image_size 256 --lr 0.00001 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/bedroom256\n\n#########################################################################\n# Consistency training on class-conditional ImageNet-64, and LSUN 256\n#########################################################################\n\n## L_CT^N on ImageNet-64\nmpiexec -n 8 python cm_train.py --training_mode consistency_training --target_ema_mode adaptive --start_ema 0.95 --scale_mode progressive --start_scales 2 --end_scales 200 --total_training_steps 800000 --loss_norm lpips --lr_anneal_steps 0 --teacher_model_path /path/to/edm_imagenet64_ema.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.999,0.9999,0.9999432189950708 --global_batch_size 2048 --image_size 64 --lr 0.0001 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/imagenet64\n\n## L_CT^N on LSUN 256\nmpiexec -n 8 python cm_train.py --training_mode consistency_training --target_ema_mode adaptive --start_ema 0.95 --scale_mode progressive --start_scales 2 --end_scales 150 --total_training_steps 1000000 --loss_norm lpips --lr_anneal_steps 0 --teacher_model_path /path/to/edm_bedroom256_ema.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --teacher_dropout 0.1 --ema_rate 0.9999,0.99994,0.9999432189950708 --global_batch_size 256 --image_size 256 --lr 0.00005 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --resblock_updown True --schedule_sampler uniform --use_fp16 True --weight_decay 0.0 --weight_schedule uniform --data_dir /path/to/bedroom256\n\n#################################################################################\n# Sampling from consistency models on class-conditional ImageNet-64, and LSUN 256\n#################################################################################\n\n## ImageNet-64\nmpiexec -n 8 python image_sample.py --batch_size 256 --training_mode consistency_distillation --sampler onestep --model_path /path/to/checkpoint --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## LSUN-256\nmpiexec -n 8 python image_sample.py --batch_size 32 --generator determ-indiv --training_mode consistency_distillation --sampler onestep --model_path /root/consistency/ct_bedroom256.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 100 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n######################################################################################\n# Tenary search for multi-step sampling on class-conditional ImageNet-64, and LSUN 256\n######################################################################################\n\n## CD on ImageNet-64\nmpiexec -n 8 python ternary_search.py --begin 0 --end 39 --steps 40 --generator determ --ref_batch /root/consistency/ref_batches/imagenet64.npz --batch_size 256 --model_path /root/consistency/cd_imagenet64_lpips.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 50000 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## CT on ImageNet-64\nmpiexec -n 8 python ternary_search.py --begin 0 --end 200 --steps 201 --generator determ --ref_batch /root/consistency/ref_batches/imagenet64.npz --batch_size 256 --model_path /root/consistency/ct_imagenet64.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 50000 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## CD on LSUN-256\nmpiexec -n 8 python ternary_search.py --begin 0 --end 39 --steps 40 --generator determ-indiv --ref_batch /root/consistency/ref_batches/bedroom256.npz --batch_size 32 --model_path /root/consistency/cd_bedroom256_lpips.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 50000 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## CT on LSUN-256\nmpiexec -n 8 python ternary_search.py --begin 0 --end 150 --steps 151 --generator determ-indiv --ref_batch /root/consistency/ref_batches/bedroom256.npz --batch_size 32 --model_path /root/consistency/ct_bedroom256.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 50000 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n###################################################################\n# Multistep sampling on class-conditional ImageNet-64, and LSUN 256\n###################################################################\n\n## Two-step sampling for CD (LPIPS) on ImageNet-64\nmpiexec -n 8 python image_sample.py --batch_size 256 --training_mode consistency_distillation --sampler multistep --ts 0,22,39 --steps 40 --model_path /path/to/cd_imagenet64_lpips.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CD (L2) on ImageNet-64\nmpiexec -n 8 python image_sample.py --batch_size 256 --training_mode consistency_distillation --sampler multistep --ts 0,22,39 --steps 40 --model_path /path/to/cd_imagenet64_l2.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CT on ImageNet-64\nmpiexec -n 8 python image_sample.py --batch_size 256 --training_mode consistency_training --sampler multistep --ts 0,106,200 --steps 201 --model_path /path/to/ct_imagenet64.pt --attention_resolutions 32,16,8 --class_cond True --use_scale_shift_norm True --dropout 0.0 --image_size 64 --num_channels 192 --num_head_channels 64 --num_res_blocks 3 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CD (LPIPS) on LSUN-256\nmpiexec -n 8 python image_sample.py --batch_size 32 --training_mode consistency_distillation --sampler multistep --ts 0,17,39 --steps 40 --model_path /path/to/cd_bedroom256_lpips.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CD (l2) on LSUN-256\nmpiexec -n 8 python image_sample.py --batch_size 32 --training_mode consistency_distillation --sampler multistep --ts 0,18,39 --steps 40 --model_path /path/to/cd_bedroom256_l2.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CT on LSUN Bedroom-256\nmpiexec -n 8 python image_sample.py --batch_size 32 --training_mode consistency_distillation --sampler multistep --ts 0,67,150 --steps 151 --model_path /path/to/ct_bedroom256.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n\n## Two-step sampling for CT on LSUN Cat-256\nmpiexec -n 8 python image_sample.py --batch_size 32 --training_mode consistency_distillation --sampler multistep --ts 0,62,150 --steps 151 --model_path /path/to/ct_cat256.pt --attention_resolutions 32,16,8 --class_cond False --use_scale_shift_norm False --dropout 0.0 --image_size 256 --num_channels 256 --num_head_channels 64 --num_res_blocks 2 --num_samples 500 --resblock_updown True --use_fp16 True --weight_schedule uniform\n", "num_lines": 93}
{"repo_name": "consistency_models_cifar10", "repo_creator": "openai", "programming_language": "Shell", "code": "#################\n# EDM on CIFAR-10\n#################\n\n## Model training\npython -m jcm.main --config configs/cifar10_k_ve.py --workdir cifar10-kve-score-loss --mode train\n## Model evaluation (loss computation, sampling, and likelihood computation)\npython -m jcm.main --config configs/cifar10_k_ve.py --workdir cifar10-kve-score-loss --mode eval --eval_folder eval\n## Model metrics (FID & IS)\npython -m jcm.main --config configs/cifar10_k_ve.py --workdir cifar10-kve-score-loss --mode metrics --eval_folder eval\n\n######################################\n# Consistency distillation on CIFAR-10\n######################################\n\n## CD with the l1 metric\npython -m jcm.main --config configs/cifar10_ve_cd.py --workdir /path/to/cd-l1 --mode train --config.optim.lr=0.0002 --config.training.loss_norm='l1'\n\n## CD with the l2 metric\npython -m jcm.main --config configs/cifar10_ve_cd.py --workdir /path/to/cd-l2 --mode train --config.optim.lr=0.0004 --config.training.loss_norm='l2'\n\n## CD with the LPIPS metric\npython -m jcm.main --config configs/cifar10_ve_cd.py --workdir /path/to/cd-lpips --mode train --config.optim.lr=0.0004 --config.training.loss_norm='lpips'\n\n## Sampling for CD (LPIPS)\npython -m jcm.main --config configs/cifar10_ve_cd.py --workdir /path/to/cd-lpips --mode eval --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --eval_folder eval --config.eval.begin_ckpt=80\n\n## Computing FID for CD (LPIPS)\npython -m jcm.main --config configs/cifar10_ve_cd.py --workdir /path/to/cd-lpips --mode metrics --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --eval_folder eval --config.eval.begin_ckpt=80\n\n######################################################\n# Continuous-time consistency distillation on CIFAR-10\n######################################################\n\n## Continuous-time CD with the l2 metric\npython -m jcm.main --config configs/cifar10_ve_continuous.py --workdir /path/to/cifar10-continuous-cd-l2 --mode train --config.optim.lr=0.001 --config.model.dropout=0.3 --config.training.loss_norm='l2'\n\n## Continuous-time CD with stopgrad and the l2 metric\npython -m jcm.main --config configs/cifar10_ve_continuous.py --workdir /path/to/cifar10-continuous-cd-l2-stopgrad --mode train --config.optim.lr=0.000005 --config.training.stopgrad=True --config.training.loss_norm='l2'\n\n## Continuous-time CD with stopgrad and the LPIPS metric\npython -m jcm.main --config configs/cifar10_ve_continuous.py --workdir /path/to/cifar10-continuous-cd-lpips-stopgrad --mode train --config.optim.lr=0.000005 --config.training.stopgrad=True --config.training.loss_norm='lpips'\n\n##################################\n# Consistency training on CIFAR-10\n##################################\n\n## CT with fixed N and mu, and the LPIPS metric\npython -m jcm.main --config configs/cifar10_ve_ct_ema.py --mode train --workdir /path/to/ct-n-120-mu-0.99 --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --config.model.num_scales=120 --config.training.dsm_target --config.training.target_ema=0.99\n\n## CT with adaptive schedules and the LPIPS metric\npython -m jcm.main --config configs/cifar10_ve_ct_adaptive.py --workdir /path/to/ct --mode train --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --config.training.dsm_target --config.training.start_scales=2 --config.training.end_scales=150 --config.training.start_ema=0.9\n\n## Sampling for CT\npython -m jcm.main --config configs/cifar10_ve_ct_adaptive.py --workdir /path/to/ct --mode eval --eval_folder eval --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --config.training.dsm_target --config.training.start_scales=2 --config.training.end_scales=150 --config.training.start_ema=0.9 --config.eval.begin_ckpt=74 --config.eval.end_ckpt=74\n\n## FID computation for CT\npython -m jcm.main --config configs/cifar10_ve_ct_adaptive.py --workdir /path/to/ct --mode metrics --eval_folder eval --config.optim.lr=0.0004 --config.training.loss_norm='lpips' --config.training.dsm_target --config.training.start_scales=2 --config.training.end_scales=150 --config.training.start_ema=0.9 --config.eval.begin_ckpt=74 --config.eval.end_ckpt=74\n\n##################################################\n# Continuous-time consistency training on CIFAR-10\n##################################################\n\n## Continuous-time CT with the l2 metric\npython -m jcm.main --config configs/cifar10_ve_continuous.py --workdir /path/to/continuous-ct-l2 --mode train --config.optim.lr=0.000005 --config.training.loss_norm='l2' --config.training.dsm_target=True --config.training.stopgrad=True --config.training.finetune=True\n\n## Continuous-time CT with the LPIPS metric\npython -m jcm.main --config configs/cifar10_ve_continuous.py --workdir /path/to/continuous-ct-lpips --mode train --config.optim.lr=0.000005 --config.training.loss_norm='lpips' --config.training.dsm_target=True --config.training.stopgrad=True --config.training.finetune=True\n", "num_lines": 69}
{"repo_name": "consul-helm", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n############################################################################\n# WARNING: This script is experimental and is not meant for production use #\n############################################################################\n#\n# Script to retrieve configuration from Hashicorp Consul Service on Azure,\n# bootstrap ACLs, and create Kubernetes secrets and Helm config file\n# to install this Helm chart.\n\nset -euo pipefail\n\n: \"${subscription_id?subscription_id environment variable required}\"\n: \"${resource_group?resource_group environment variable required}\"\n: \"${managed_app_name?managed_app_name environment variable required}\"\n: \"${cluster_name?cluster_name environment variable required}\"\n\nGREEN='\\033[0;32m'\nRED='\\033[0;31m'\nYELLOW='\\033[0;93m'\nNOCOLOR='\\033[0m'\n\necho -e \"${YELLOW}-> Fetching cluster configuration from Azure${NOCOLOR}\"\ncluster_resource=$(az resource show --ids \"/subscriptions/${subscription_id}/resourceGroups/${resource_group}/providers/Microsoft.Solutions/applications/${managed_app_name}/customconsulClusters/${cluster_name}\" --api-version 2018-09-01-preview)\ncluster_config_file_base64=$(echo \"${cluster_resource}\" | jq -r .properties.consulConfigFile)\nca_file_base64=$(echo \"${cluster_resource}\" | jq -r .properties.consulCaFile)\n\necho \"Writing cluster configuration to consul.json\"\necho \"${cluster_config_file_base64}\" | base64 --decode | jq . > consul.json\n\necho \"Writing CA certificate chain to ca.pem\"\necho \"${ca_file_base64}\" | base64 --decode > ca.pem\necho\n\necho -e \"${YELLOW}-> Bootstrapping ACLs${NOCOLOR}\"\n\n# Extract the URL for the servers.\n# First, check if the external endpoint is enabled and if yes, use the external endpoint URL.\n# Otherwise, use the private endpoint URL.\nexternal_endpoint_enabled=$(echo \"${cluster_resource}\" | jq -r .properties.consulExternalEndpoint)\nif [ \"$external_endpoint_enabled\" == \"enabled\" ]; then\n  server_url=$(echo \"${cluster_resource}\" | jq -r .properties.consulExternalEndpointUrl)\nelse\n  server_url=$(echo \"${cluster_resource}\" | jq -r .properties.consulPrivateEndpointUrl)\nfi\n\n# Use managed_app_name as a resource prefix for Kubernetes resources\n# We need to convert it to lower case because of Kubernetes resource restrictions.\n# https://kubernetes.io/docs/concepts/overview/working-with-objects/names/\nkube_resource_prefix=$(echo \"${managed_app_name}\" | tr '[:upper:]' '[:lower:]')\n\n# Call Consul bootstrap API and save the bootstrap secret\n# to a Kubernetes secret if successful.\noutput=$(curl --connect-timeout 30 -sSX PUT \"${server_url}\"/v1/acl/bootstrap)\nif grep -i \"permission denied\" <<< \"$output\"; then\n  echo \"ACL system already bootstrapped.\"\n  echo -e \"${RED}Please update 'global.acls.bootstrapToken' values in the generated Helm config to point to the Kubernetes secret containing the bootstrap token.${NOCOLOR}\"\n  echo -e \"${RED}You can create a secret like so:${NOCOLOR}\"\n  echo -e \"${RED}kubectl create secret generic ${kube_resource_prefix}-bootstrap-token \\ ${NOCOLOR}\"\n  echo -e \"${RED}   --from-literal='token=<your bootstrap secret>'${NOCOLOR}\"\nelif  grep -i \"ACL support disabled\" <<< \"$output\"; then\n  echo -e \"${RED}ACLs not enabled on this cluster.${NOCOLOR}\"\n  exit 1\nelse\n  echo \"Successfully bootstrapped ACLs. Writing ACL bootstrap output to acls.json\"\n  echo \"$output\" > acls.json\n\n  echo \"Creating Kubernetes secret for the bootstrap token ${kube_resource_prefix}-bootstrap-token\"\n  kubectl create secret generic \"${kube_resource_prefix}\"-bootstrap-token \\\n          --from-literal=\"token=$(echo \"${output}\" | jq -r .SecretID)\"\nfi\n\necho\necho -e \"${YELLOW}-> Creating Kubernetes secret ${kube_resource_prefix}-consul-ca-cert${NOCOLOR}\"\nkubectl create secret generic \"${kube_resource_prefix}\"-consul-ca-cert --from-file='tls.crt=./ca.pem'\n\necho\necho -e \"${YELLOW}-> Creating Kubernetes secret ${kube_resource_prefix}-gossip-key${NOCOLOR}\"\ngossip_key=$(jq -r .encrypt consul.json)\nkubectl create secret generic \"${kube_resource_prefix}\"-gossip-key --from-literal=key=\"${gossip_key}\"\n\nretry_join=$(jq -r --compact-output .retry_join consul.json)\nkube_api_server=$(kubectl config view -o jsonpath=\"{.clusters[?(@.name == \\\"$(kubectl config current-context)\\\")].cluster.server}\")\n\necho\necho -e \"${YELLOW}-> Writing Helm config to config.yaml${NOCOLOR}\"\ncat > config.yaml << EOF\nglobal:\n  enabled: false\n  name: consul\n  datacenter: $(jq -r .datacenter consul.json)\n  acls:\n    manageSystemACLs: true\n    bootstrapToken:\n      secretName: ${kube_resource_prefix}-bootstrap-token\n      secretKey: token\n  gossipEncryption:\n    secretName: ${kube_resource_prefix}-gossip-key\n    secretKey: key\n  tls:\n    enabled: true\n    enableAutoEncrypt: true\n    caCert:\n      secretName: ${kube_resource_prefix}-consul-ca-cert\n      secretKey: tls.crt\nexternalServers:\n  enabled: true\n  hosts: ${retry_join}\n  httpsPort: 443\n  useSystemRoots: true\n  k8sAuthMethodHost: ${kube_api_server}\nclient:\n  enabled: true\n  # If you are using Kubenet in your AKS cluster (the default network),\n  # uncomment the line below.\n  # exposeGossipPorts: true\n  join: ${retry_join}\nconnectInject:\n  enabled: true\nsyncCatalog:\n  enabled: true\nEOF\n\necho\necho -e \"${GREEN}Done${GREEN}\"\n", "num_lines": 126}
{"repo_name": "deeptype", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# stop script on error and print it\nset -e\n# inform me of undefined variables\nset -u\n# handle cascading failures well\nset -o pipefail\n\nfunction ensure_dir {\n    if [ \"${1: -1}\" != \"/\" ]; then\n        echo \"${1}/\"\n    else\n        echo $1\n    fi\n}\n\nif [ \"$#\" -lt 2 ]; then\n    echo \"Not enough arguments.\"\n    echo \"Usage: $0 DATA_DIR LANGUAGE [LANGUAGE ...]\"\n    exit\nfi\n\nDATA_DIR=$1\nDATA_DIR=\"$(ensure_dir $DATA_DIR)\"\necho \"Downloading wikidata into ${DATA_DIR}.\"\nLANGUAGES=${@:2}\n\nfor LANGUAGE in $LANGUAGES\ndo\n    echo \"Will prepare language: ${LANGUAGE}\"\ndone\n\necho \"Creating data directory\"\nmkdir -p $DATA_DIR\necho \"Done.\"\n\necho \"Downloading and preparing Wikidata:\"\nif [ -f \"${DATA_DIR}latest-all.mp\" ]\nthen\n    echo \"Already compressed Wikidata\"\nelse\n    if [ -f \"${DATA_DIR}latest-all.json\" ]\n    then\n        echo \"Already decompressed Wikidata\"\n        python3 extraction/compress_wikidata_msgpack.py ${DATA_DIR}latest-all.json ${DATA_DIR}latest-all.mp\n        rm ${DATA_DIR}latest-all.json\n    else\n        if [ -f \"${DATA_DIR}latest-all.json.bz2\" ]\n        then\n            echo \"Already downloaded ${DATA_DIR}latest-all.json.bz2\"\n            bzip2 -d -v4 ${DATA_DIR}latest-all.json.bz2\n            python3 extraction/compress_wikidata_msgpack.py ${DATA_DIR}latest-all.json ${DATA_DIR}latest-all.mp\n            rm ${DATA_DIR}latest-all.json\n        else\n            wget -O ${DATA_DIR}latest-all.json.bz2 https://dumps.wikimedia.org/wikidatawiki/entities/latest-all.json.bz2\n            bzip2 -d -v4 ${DATA_DIR}latest-all.json.bz2\n            python3 extraction/compress_wikidata_msgpack.py ${DATA_DIR}latest-all.json ${DATA_DIR}latest-all.mp\n            rm ${DATA_DIR}latest-all.json\n        fi\n    fi\nfi\nmkdir -p ${DATA_DIR}wikidata/\npython3 extraction/get_wikiname_to_wikidata.py ${DATA_DIR}latest-all.mp ${DATA_DIR}wikidata/\necho \"Done with wikidata.\"\n\nfor LANGUAGE in $LANGUAGES\ndo\n    echo \"Preparing language: ${LANGUAGE}\"\n    if [ -f \"${DATA_DIR}${LANGUAGE}wiki-latest-pages-articles.xml\" ]\n    then\n        echo \"Already downloaded and extracted ${LANGUAGE}wiki-latest-pages-articles.xml.\"\n    else\n        wget -O ${DATA_DIR}${LANGUAGE}wiki-latest-pages-articles.xml.bz2 https://dumps.wikimedia.org/${LANGUAGE}wiki/latest/${LANGUAGE}wiki-latest-pages-articles.xml.bz2\n        bzip2 -d -v4 ${DATA_DIR}${LANGUAGE}wiki-latest-pages-articles.xml.bz2\n    fi\n    python3 extraction/get_redirection_category_links.py ${DATA_DIR}${LANGUAGE}wiki-latest-pages-articles.xml ${DATA_DIR}${LANGUAGE}_anchors.tsv ${DATA_DIR}${LANGUAGE}_redirections.tsv ${DATA_DIR}${LANGUAGE}_category_links.tsv\n    python3 extraction/convert_category_links_to_wikidata.py ${DATA_DIR}wikidata/wikititle2wikidata.marisa ${DATA_DIR}wikidata/wikidata_ids.txt ${LANGUAGE}wiki ${DATA_DIR}${LANGUAGE}_category_links.tsv ${DATA_DIR}wikidata/\n    python3 extraction/convert_anchor_tags_to_wikidata.py ${DATA_DIR}wikidata/wikititle2wikidata.marisa ${LANGUAGE}wiki ${DATA_DIR}${LANGUAGE}_anchors.tsv ${DATA_DIR}${LANGUAGE}_redirections.tsv ${DATA_DIR}${LANGUAGE}_trie\n    # apply link fixing strategy here:\n    python3 extraction/fast_link_fixer.py ${DATA_DIR}wikidata ${DATA_DIR}${LANGUAGE}_trie ${DATA_DIR}${LANGUAGE}_trie_fixed\ndone\n", "num_lines": 83}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-rot-tr-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-58m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-58m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-randaugment-data-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-randaugment-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-tr-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-tr-c-js-dist-aug.npz\n\nfor dataset in cifar10; do\nfor partition in test; do\n  args=\"--eval_test --no_sample_during_eval --dataset $dataset\"\n\n  # c10 15m runs\n  python train.py --desc c10-15m-baseline-${partition} --hps c10_15m --restore_path c10-15m-baseline.npz $args\n  python train.py --desc c10-15m-rot-${partition} --hps c10_15m_rot --restore_path c10-15m-rot-dist-aug.npz $args\n  python train.py --desc c10-15m-rot-tr-${partition} --hps c10_15m_rot_tr --restore_path c10-15m-rot-tr-dist-aug.npz $args\n\n  # c10 58m runs\n  python train.py --desc c10-58m-baseline-${partition} --hps c10-58m --restore_path c10-58m-baseline.npz $args\n  python train.py --desc c10-58m-rot-${partition} --hps c10-58m-rot --restore_path c10-58m-rot-dist-aug.npz $args\n\n  # c10 150m runs\n  python train.py --desc c10-150m-baseline-${partition} --hps c10_150m_baseline --restore_path c10-150m-baseline.npz $args\n\n  # randaugment runs\n  python train.py --desc c10-150m-randaugment-dataaug-${partition} --hps c10_150m_randaugment_dataaug --restore_path c10-150m-randaugment-data-aug.npz $args\n  python train.py --desc c10-150m-randaugment-distaug-${partition} --hps c10_150m_randaugment_distaug --restore_path c10-150m-randaugment-dist-aug.npz $args\n\n  # permutation runs\n  python train.py --desc c10-150m-rot-${partition} --hps c10-150m-rot --restore_path c10-150m-rot-dist-aug.npz $args\n  python train.py --desc c10-150m-rot-tr-${partition} --hps c10-150m-rot-tr --restore_path c10-150m-rot-tr-dist-aug.npz $args\n  python train.py --desc c10-150m-rot-c-tr-js-${partition} --hps c10-150m-rot-c-tr-js --restore_path c10-150m-rot-tr-c-js-dist-aug.npz $args\ndone\ndone\n", "num_lines": 41}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-15m-rot-tr-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-58m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-58m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-baseline.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-randaugment-data-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-randaugment-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-tr-dist-aug.npz\nwget https://openaipublic.blob.core.windows.net/distribution-augmentation-assets/models/c10-150m-rot-tr-c-js-dist-aug.npz\n\nargs=\"--sample_and_exit --samples_to_generate 4 --sample_batch 4\"\n\n# c10 15m runs\npython train.py --desc samples-c10-15m-baseline --hps c10_15m --restore_path c10-15m-baseline.npz $args\npython train.py --desc samples-c10-15m-rot --hps c10_15m_rot --restore_path c10-15m-rot-dist-aug.npz $args\npython train.py --desc samples-c10-15m-rot-tr --hps c10_15m_rot_tr --restore_path c10-15m-rot-tr-dist-aug.npz $args\n\n# c10 58m runs\npython train.py --desc samples-c10-58m-baseline --hps c10-58m --restore_path c10-58m-baseline.npz $args\npython train.py --desc samples-c10-58m-rot --hps c10-58m-rot --restore_path c10-58m-rot-dist-aug.npz $args\n\n# c10 150m baseline and randaugment runs\npython train.py --desc samples-c10-150m-baseline --hps c10_150m_baseline --restore_path c10-150m-baseline.npz $args\npython train.py --desc samples-c10-150m-randaugment-dataaug --hps c10_150m_randaugment_dataaug --restore_path c10-150m-randaugment-data-aug.npz $args\npython train.py --desc samples-c10-150m-randaugment-distaug --hps c10_150m_randaugment_distaug --restore_path c10-150m-randaugment-dist-aug.npz $args\n\n# c10 150m perm runs\npython train.py --desc samples-c10-150m-rot --hps c10-150m-rot --restore_path c10-150m-rot-dist-aug.npz $args\npython train.py --desc samples-c10-150m-rot-tr --hps c10-150m-rot-tr --restore_path c10-150m-rot-tr-dist-aug.npz $args\npython train.py --desc samples-c10-150m-rot-c-tr-js --hps c10-150m-rot-c-tr-js --restore_path c10-150m-rot-tr-c-js-dist-aug.npz $args\n", "num_lines": 34}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\n# Baseline\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --desc c10-small --hps c10_small --resid_pdrop 0.005 &> logs/c10-small.out &\n\n# Horizontal flips\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --desc c10-small-lr-rp05 --hps c10_small_lr --resid_pdrop 0.05 &> logs/c10-small-lr-rp05.out &\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --desc c10-small-lr-rp10 --hps c10_small_lr --resid_pdrop 0.10 &> logs/c10-small-lr-rp10.out &\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --desc c10-small-lr-rp20 --hps c10_small_lr --resid_pdrop 0.20 &> logs/c10-small-lr-rp20.out &\n\n# Rand-augment\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-ra-n2-m3-nocond --hps c10_small_ra_n2_m3 --resid_pdrop 0.005 &> logs/c10-small-ra-n2-m3-nocond.out &\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-ra-n2-m3-cond --hps c10_small_ra_n2_m3 --resid_pdrop 0.005 --rand_augment_conditioning &> logs/c10-small-ra-n2-m3-cond.out &\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-ra-n1-m2-nocond --hps c10_small_ra_n1_m2 --resid_pdrop 0.005 &> logs/c10-small-ra-n1-m2-nocond.out &\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-ra-n1-m2-cond --hps c10_small_ra_n1_m2 --resid_pdrop 0.005 --rand_augment_conditioning &> logs/c10-small-ra-n1-m2-cond.out &\n", "num_lines": 18}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nfunction multiply() {\n  echo $(( $1 * $2 ))\n}\n\n# Baseline\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --desc c10-small-rp10 --hps c10_small --resid_pdrop 0.10 &> logs/c10-small-rp10.out &\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --desc c10-small-rp25 --hps c10_small --resid_pdrop 0.25 &> logs/c10-small-rp25.out &\n\n# without prompting\n\n# equivalent to rot/tr/c => 4 x 2 x 6 = 48. 1 / 48 ~= 0.02.\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f98-nocond --hps c10_small_ss_i32_nocond --auxiliary_dataset_fraction 0.98 --auxiliary_dataset_subset_size `multiply 48000 47` --resid_pdrop 0.005 &> logs/c10-small-i32-f98-nocond.out &\n# equivalent to rot/tr\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f875-nocond --hps c10_small_ss_i32_nocond --auxiliary_dataset_fraction 0.875 --auxiliary_dataset_subset_size `multiply 48000 7` --resid_pdrop 0.005 &> logs/c10-small-i32-f875-nocond.out &\n# equivalent to rot\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f75-nocond --hps c10_small_ss_i32_nocond --auxiliary_dataset_fraction 0.75 --auxiliary_dataset_subset_size `multiply 48000 3` --resid_pdrop 0.005 &> logs/c10-small-i32-f75-nocond.out &\n\n# with prompting\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f98-cond --hps c10_small_ss_i32_cond --auxiliary_dataset_fraction 0.98 --auxiliary_dataset_subset_size `multiply 48000 47` --resid_pdrop 0.005 &> logs/c10-small-i32-f98-cond.out &\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f875-cond --hps c10_small_ss_i32_cond --auxiliary_dataset_fraction 0.875 --auxiliary_dataset_subset_size `multiply 48000 7` --resid_pdrop 0.005 &> logs/c10-small-i32-f875-cond.out &\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-i32-f75-cond --hps c10_small_ss_i32_cond --auxiliary_dataset_fraction 0.75 --auxiliary_dataset_subset_size `multiply 48000 3` --resid_pdrop 0.005 &> logs/c10-small-i32-f75-cond.out &\n", "num_lines": 26}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --desc c10-small-c-nocond-nope --hps c10_small_c --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-c-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --desc c10-small-c-nocond-pe --hps c10_small_c --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-c-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --desc c10-small-c-cond-nope --hps c10_small_c --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-c-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --desc c10-small-c-cond-pe --hps c10_small_c --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-c-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-js-nocond-nope-a1 --hps c10_small_js --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-js-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-js-nocond-pe-a1 --hps c10_small_js --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-js-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-js-cond-nope-a1 --hps c10_small_js --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-js-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-js-cond-pe-a1 --hps c10_small_js --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-js-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-rd-s42-lhd-nocond-nope-a1 --hps c10_small_rd --randomly_determined_order_use_lookahead --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rd-s42-lhd-nocond-nope.out &\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-rd-s42-lhd-nocond-pe-a1 --hps c10_small_rd --randomly_determined_order_use_lookahead --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rd-s42-lhd-nocond-pe.out &\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-rd-s42-lhd-cond-nope-a1 --hps c10_small_rd --randomly_determined_order_use_lookahead --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rd-s42-lhd-cond-nope.out &\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-rd-s42-lhd-cond-pe-a1 --hps c10_small_rd --randomly_determined_order_use_lookahead --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rd-s42-lhd-cond-pe.out &\n\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-rd-s42-nocond-nope-a1 --hps c10_small_rd --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rd-s42-nocond-nope.out &\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-rd-s42-nocond-pe-a1 --hps c10_small_rd --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rd-s42-nocond-pe.out &\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-rd-s42-cond-nope-a1 --hps c10_small_rd --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rd-s42-cond-nope.out &\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-rd-s42-cond-pe-a1 --hps c10_small_rd --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rd-s42-cond-pe.out &\n", "num_lines": 14}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-lhd-nocond-nope --hps c10_small_dense_rd --randomly_determined_order_use_lookahead --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-dense-rd-s42-lhd-nocond-nope.out &\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-lhd-nocond-pe --hps c10_small_dense_rd --randomly_determined_order_use_lookahead --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-dense-rd-s42-lhd-nocond-pe.out &\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-lhd-cond-nope --hps c10_small_dense_rd --randomly_determined_order_use_lookahead --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-dense-rd-s42-lhd-cond-nope.out &\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-lhd-cond-pe --hps c10_small_dense_rd --randomly_determined_order_use_lookahead --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-dense-rd-s42-lhd-cond-pe.out &\n\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-nocond-nope --hps c10_small_dense_rd --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-dense-rd-s42-nocond-nope.out &\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-nocond-pe --hps c10_small_dense_rd --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-dense-rd-s42-nocond-pe.out &\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-cond-nope --hps c10_small_dense_rd --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-dense-rd-s42-cond-nope.out &\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --no_sample_during_eval --desc c10-small-dense-rd-s42-cond-pe --hps c10_small_dense_rd --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-dense-rd-s42-cond-pe.out &\n", "num_lines": 14}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --desc c10-small-rev-nocond-nope --hps c10_small_rev --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rev-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --desc c10-small-rev-nocond-pe --hps c10_small_rev --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rev-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --desc c10-small-rev-cond-nope --hps c10_small_rev --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rev-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --desc c10-small-rev-cond-pe --hps c10_small_rev --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rev-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=0 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-nocond-nope --hps c10_small_rot --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rot-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=1 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-nocond-pe --hps c10_small_rot --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rot-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=2 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-cond-nope --hps c10_small_rot --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rot-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=3 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-cond-pe --hps c10_small_rot --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rot-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-tr-nocond-nope --hps c10_small_rot_tr --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rot-tr-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-tr-nocond-pe --hps c10_small_rot_tr --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-rot-tr-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-tr-cond-nope --hps c10_small_rot_tr --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rot-tr-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-rot-tr-cond-pe --hps c10_small_rot_tr --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-rot-tr-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "distribution_augmentation", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p logs\n\nCUDA_VISIBLE_DEVICES=4 python train.py --seed 43 --aug_seed 314 --desc c10-small-tr-nocond-nope --hps c10_small_tr --no_permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-tr-nocond-nope.out &\n\nCUDA_VISIBLE_DEVICES=5 python train.py --seed 43 --aug_seed 314 --desc c10-small-tr-nocond-pe --hps c10_small_tr --permute_embeddings --resid_pdrop 0.005 --use_unconditional_augmentation &> logs/c10-small-tr-nocond-pe.out &\n\nCUDA_VISIBLE_DEVICES=6 python train.py --seed 43 --aug_seed 314 --desc c10-small-tr-cond-nope --hps c10_small_tr --no_permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-tr-cond-nope.out &\n\nCUDA_VISIBLE_DEVICES=7 python train.py --seed 43 --aug_seed 314 --desc c10-small-tr-cond-pe --hps c10_small_tr --permute_embeddings --resid_pdrop 0.005 &> logs/c10-small-tr-cond-pe.out &\n", "num_lines": 12}
{"repo_name": "doom-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\t\ncmake -DCMAKE_BUILD_TYPE=Release -DBUILD_PYTHON=ON -DBUILD_JAVA=ON", "num_lines": 2}
{"repo_name": "doom-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nfor NAME in Makefile CMakeCache.txt CMakeFiles cmake_install.cmake\ndo\n\tfind . -name \"$NAME\" -exec rm -rf {} 2>/dev/null \\;\ndone\n", "num_lines": 6}
{"repo_name": "doom-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# Checks if scenarios/freedoom2.wad is in place and downloads and extracts it if not.\n\nFREEDOM_LINK=\"https://github.com/freedoom/freedoom/releases/download/v0.10.1/freedoom-0.10.1.zip\"\n\nif [ ! -e  \"./scenarios/freedoom2.wad\" ]\nthen \n\tif [ ! -e \"./bin/freedoom-0.10.1.zip\" ]\n\tthen\n\t\twget $FREEDOM_LINK -P ./bin\n\tfi\n\tunzip -j -d ./scenarios ./bin/freedoom-0.10.1.zip freedoom-0.10.1/freedoom2.wad\nfi\n\n", "num_lines": 15}
{"repo_name": "doom-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\t\ncmake -DCMAKE_BUILD_TYPE=Release -DBUILD_PYTHON=ON -DBUILD_JAVA=ON", "num_lines": 2}
{"repo_name": "evolution-strategies-starter", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# from ami-d8bdebb8\n\nset -x\n\nsudo apt-get update\nsudo apt-get install -y build-essential cmake git wget htop\n\n# Build and install a new version of redis\n# https://www.digitalocean.com/community/tutorials/how-to-install-and-configure-redis-on-ubuntu-16-04\nwget --quiet http://download.redis.io/releases/redis-3.2.7.tar.gz -O redis-3.2.7.tar.gz\ntar -xvzf redis-3.2.7.tar.gz\ncd redis-3.2.7\nmake\nsudo make install\nsudo mkdir /etc/redis\nsudo cp redis.conf /etc/redis\ncd ..\nrm -rf redis-3.2.7 redis-3.2.7.tar.gz\n\n# Set up redis working directory\nsudo sed -ie 's/dir \\.\\//dir \\/var\\/lib\\/redis/' /etc/redis/redis.conf\nsudo mkdir /var/lib/redis\nsudo chown ubuntu:ubuntu /var/lib/redis\n\n# rely on firewall for security\nsudo sed -ie \"s/bind 127.0.0.1//\" /etc/redis/redis.conf\nsudo sed -ie \"s/protected-mode yes/protected-mode no/\" /etc/redis/redis.conf\n\n# System settings for redis\necho \"vm.overcommit_memory=1\" | sudo tee -a /etc/sysctl.conf\nsudo sysctl vm.overcommit_memory=1\nsudo apt-get install -y hugepages\necho \"sudo hugeadm --thp-never\" | sudo tee /etc/profile.d/disable_thp.sh > /dev/null\n. /etc/profile.d/disable_thp.sh\n\n# Start redis with systemctl\n# sudo sed -ie \"s/supervised no/supervised systemd/\" /etc/redis/redis.conf\n# ^ doesn't seem to matter; if it's enabled, the logs show \"systemd supervision requested, but NOTIFY_SOCKET not found\"\necho \"\n[Unit]\nDescription=Redis In-Memory Data Store\nAfter=network.target\n\n[Service]\nUser=ubuntu\nGroup=ubuntu\nExecStart=/usr/local/bin/redis-server /etc/redis/redis.conf\nExecStop=/usr/local/bin/redis-cli shutdown\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\n\" | sudo tee /etc/systemd/system/redis.service > /dev/null\nsudo systemctl start redis\n\n# anaconda\nsudo echo 'export PATH=/opt/conda/bin:$PATH' | sudo tee /etc/profile.d/conda.sh > /dev/null\nsudo wget --quiet https://repo.continuum.io/archive/Anaconda3-4.2.0-Linux-x86_64.sh -O ~/anaconda.sh\nsudo /bin/bash ~/anaconda.sh -b -p /opt/conda\nsudo rm -f ~/anaconda.sh\n. /etc/profile.d/conda.sh\nsudo /opt/conda/bin/conda update -y --all\n\n# additional python dependencies\nsudo /opt/conda/bin/conda install -y numpy scipy opencv\n\n# Mujoco\nsudo mkdir -p /opt/mujoco\n\n#######################################################\n# WRITE CODE HERE TO PLACE MUJOCO 1.31 in /opt/mujoco #\n# The key file should be in /opt/mujoco/mjkey.txt     #\n# Mujoco should be installed in /opt/mujoco/mjpro131  #\n#######################################################\n\nsudo echo 'export MUJOCO_PY_MJKEY_PATH=/opt/mujoco/mjkey.txt' | sudo tee /etc/profile.d/mujoco.sh > /dev/null\nsudo echo 'export MUJOCO_PY_MJPRO_PATH=/opt/mujoco/mjpro131' | sudo tee -a /etc/profile.d/mujoco.sh > /dev/null\n. /etc/profile.d/mujoco.sh\n\n# ALE\nsudo /opt/conda/bin/conda install -y libgcc # ALE needs this for some reason\nsudo apt-get install -y libsdl1.2-dev\ngit clone https://github.com/mgbellemare/Arcade-Learning-Environment\ncd Arcade-Learning-Environment\nmkdir build\ncd build\ncmake .. -DUSE_SDL=on\nmake\ncd ..\nsudo /opt/conda/bin/pip install .\ncd ..\nrm -rf Arcade-Learning-Environment\n\n# Tensorflow 0.11.0\nsudo /opt/conda/bin/conda install -c conda-forge -y tensorflow=0.11.0\n\n# Gym\nsudo apt-get install -y zlib1g-dev libjpeg-dev xvfb libav-tools xorg-dev libboost-all-dev libsdl2-dev swig freeglut3 libgl1 libglu1\nsudo /opt/conda/bin/conda install -y pyopengl\nsudo /opt/conda/bin/pip install \\\n    'gym[atari,classic_control,mujoco]' \\\n    PyYAML \\\n    six==1.10.0 \\\n    awscli\n\n# pip redis\nsudo /opt/conda/bin/pip install redis\n\n# cleanup\nsudo /opt/conda/bin/conda clean -y --all\nsudo apt-get clean\nsudo rm -rf /var/lib/apt/lists/*\n# cleanup pip cache?\n\nset +x\n", "num_lines": 118}
{"repo_name": "evolution-strategies-starter", "repo_creator": "openai", "programming_language": "Shell", "code": "# your environment setup for a new shell window\n", "num_lines": 2}
{"repo_name": "evolution-strategies-starter", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nNAME=exp_`date \"+%m_%d_%H_%M_%S\"`\nEXP_FILE=$1\ntmux new -s $NAME -d\ntmux send-keys -t $NAME '. scripts/local_env_setup.sh' C-m\ntmux send-keys -t $NAME 'python -m es_distributed.main master --master_host localhost --exp_file '\"$EXP_FILE\" C-m\ntmux split-window -t $NAME\ntmux send-keys -t $NAME '. scripts/local_env_setup.sh' C-m\ntmux send-keys -t $NAME 'python -m es_distributed.main workers --master_host localhost --relay_socket_path /tmp/redis.sock --num_workers 1' C-m\ntmux a -t $NAME\n", "num_lines": 11}
{"repo_name": "evolution-strategies-starter", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\ntmux new -s redis -d\ntmux send-keys -t redis 'redis-server redis_config/redis_master.conf' C-m\ntmux split-window -t redis\ntmux send-keys -t redis 'redis-server redis_config/redis_local_mirror.conf' C-m\ntmux a -t redis\n", "num_lines": 7}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest swagger spec.\n# Puts the updated spec at api/swagger-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Run this script on the root of the repo to automatically\n# detect the language and update its client. Assumptions are:\n# - the repo name is the language name.\n# - the output folder is named \"kubernetes\" at the root of the repo\n# - setting file is named \"settings\" at the root of the repo\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\nREPO_NAME=$(basename `git rev-parse --show-toplevel`)\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\nif [[ ! -f \"${SCRIPT_ROOT}/${REPO_NAME}.sh\" ]]; then\n  echo \"Repo name \\\"${REPO_NAME}\\\" is not a supported language.\"\n  exit 1\nfi\n\nif [[ ! -d \"${REPO_ROOT}/kubernetes\" ]]; then\n  echo \"Expected folder named \\\"kubernetes\\\" at the root of the repo\"\n  exit 1\nfi\n\nif [[ ! -f \"${REPO_ROOT}/settings\" ]]; then\n  echo \"Expected setting file to be at the root of the repo\"\n  exit 1\nfi\n\necho \"Running command \\\"${SCRIPT_ROOT}/${REPO_NAME}.sh\\\" \\\"${REPO_ROOT}/kubernetes\\\" \\\"${REPO_ROOT}/settings\\\"\"\n\n\"${SCRIPT_ROOT}/${REPO_NAME}.sh\" \"${REPO_ROOT}/kubernetes\" \"${REPO_ROOT}/settings\"\n\n\n", "num_lines": 58}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-master}\" \\\nCLIENT_LANGUAGE=c; \\\nCLEANUP_DIRS=(pkg); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\necho \"---Done.\"\n", "num_lines": 55}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest swagger spec.\n# Puts the updated spec at api/swagger-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\n# this is to ensure sed after docker build has perm to modify files generated\nmkdir -p ${OUTPUT_DIR}/Models/\n\n# TODO(brendandburns): Update CLEANUP_DIRS\nCLIENT_LANGUAGE=csharp; CLEANUP_DIRS=(docs src target gradle); kubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\n# hack for generating empty host url\nsed -i '/BaseUri = new System.Uri(\\\"\\\");/ d' ${OUTPUT_DIR}/Kubernetes.cs\n\n# remove public prop from Quantity, (autorest cannot generate empty class)\nsed -i '/JsonProperty/ d' ${OUTPUT_DIR}/Models/ResourceQuantity.cs\nsed -i 's/public string Value/private string Value/' ${OUTPUT_DIR}/Models/ResourceQuantity.cs\nsed -i 's/; set/; private set/' ${OUTPUT_DIR}/Models/V1Patch.cs\nsed -i 's/_httpRequest.Content.Headers.ContentType.*$/_httpRequest.Content.Headers.ContentType = GetHeader(body);/' ${OUTPUT_DIR}/Kubernetes.cs", "num_lines": 65}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v3.3.4}\" \\\nCLIENT_LANGUAGE=go; \\\nCLEANUP_DIRS=(pkg); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\necho \"---Done.\"\n", "num_lines": 55}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\n# Latest version as of Mar 15, 2019\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-a979fd8e13c86431831b0c769ba7b484e744afa5}\"; \\\nCLIENT_LANGUAGE=haskell-http-client; \\\nCLEANUP_DIRS=(lib/Kubernetes/OpenAPI/API); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\nCABAL_OVERRIDES=(homepage https://github.com/kubernetes-client/haskell\n           author \"Auto Generated\"\n           maintainer \"Shimin Guo <smguo2001@gmail.com>, Akshay Mankar <itsakshaymankar@gmail.com>\"\n           license Apache-2.0)\n\npatch_cabal_file() {\n    while [[ $# -gt 1 ]]; do\n        sed -i 's|^\\('$1':[[:space:]]*\\).*|\\1'\"$2\"'|' ${OUTPUT_DIR}/*.cabal\n        shift 2\n    done\n}\n\npatch_cabal_file \"${CABAL_OVERRIDES[@]}\"\n\n# Add license-file after license\nsed -i '/^license:/a license-file:   LICENSE' ${OUTPUT_DIR}/*.cabal\n\nln -sf ../LICENSE ${OUTPUT_DIR}/LICENSE\n\nsed -i '/^copyright:/d' ${OUTPUT_DIR}/*.cabal\necho \"---Done.\"\n", "num_lines": 76}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nPACKAGE_NAME=${PACKAGE_NAME:-io.kubernetes.client}\nCLIENT_VERSION=${CLIENT_VERSION:-5.0-SNAPSHOT}\nGENERATE_APIS=${GENERATE_APIS:-false}\nOUTPUT_DIR=${OUTPUT_DIR:-java}\nOPENAPI_MODEL_LENGTH=${OPENAPI_MODEL_LENGTH:-}\nHIDE_GENERATION_TIMESTAMP=${HIDE_GENERATION_TIMESTAMP:-false}\nLIBRARY=${LIBRARY:-okhttp-gson}\nOPENAPI_SKIP_BASE_INTERFACE=\nKUBERNETES_CRD_GROUP_PREFIX=\n\nprint_usage() {\n  echo \"Usage: generate a java project using input openapi spec from stdin\" >& 2\n  echo \" -c: project version of the generated java project.\" >& 2\n  echo \" -x: skips implementing kubernetes common interface (this is for backward compatibility w/ client-java lower than 9.0.0)\" >& 2\n  echo \" -n: the prefix of the target CRD's api group to generate.\" >& 2\n  echo \" -g: generate crd apis.\" >& 2\n  echo \" -p: the base package name of the generated java project. \" >& 2\n  echo \" -o: output directory of the generated java project. \" >& 2\n  echo \" -l: keep the n last segments for the generated class name. \" >& 2\n  echo \" -h: hide generation timestamp\" >& 2\n  echo \" -i: client library\" >& 2\n}\n\nwhile getopts 'c:g:h:i:n:l:p:o:x' flag; do\n  case \"${flag}\" in\n    c) CLIENT_VERSION=\"${CLIENT_VERSION}\" ;;\n    g) GENERATE_APIS=\"${OPTARG}\" ;;\n    h) HIDE_GENERATION_TIMESTAMP=\"${OPTARG}\" ;;\n    i) LIBRARY=\"${OPTARG}\" ;;\n    n) KUBERNETES_CRD_GROUP_PREFIX=\"${OPTARG}\" ;;\n    l) OPENAPI_MODEL_LENGTH=\"${OPTARG}\" ;;\n    p) PACKAGE_NAME=\"${OPTARG}\" ;;\n    o) OUTPUT_DIR=\"${OPTARG}\" ;;\n    x) OPENAPI_SKIP_BASE_INTERFACE=1 ;;\n    *) print_usage\n       exit 1 ;;\n  esac\ndone\n\necho \"KUBERNETES_CRD_GROUP_PREFIX: $KUBERNETES_CRD_GROUP_PREFIX\" >& 2\necho \"OPENAPI_MODEL_LENGTH: $OPENAPI_MODEL_LENGTH\" >& 2\necho \"PACKAGE_NAME: $PACKAGE_NAME\" >& 2\necho \"GENERATE_APIS: $GENERATE_APIS\" >& 2\necho \"CLIENT_VERSION: $CLIENT_VERSION\" >& 2\necho \"OUTPUT_DIR: $OUTPUT_DIR\" >& 2\necho \"HIDE_GENERATION_TIMESTAMP: $HIDE_GENERATION_TIMESTAMP\" >& 2\necho \"LIBRARY: $LIBRARY\" >& 2\necho \"\" >& 2 # empty line\n\n\nmkdir -p \"${OUTPUT_DIR}\"\n\necho 'rendering settings file to /tmp/settings' >& 2\nread -d '' settings << EOF\nexport KUBERNETES_BRANCH=\"${KUBERNETES_BRANCH}\"\n\nexport CLIENT_VERSION=\"${CLIENT_VERSION}\"\n\nexport PACKAGE_NAME=\"${PACKAGE_NAME}\"\nEOF\n\necho ${settings} > /tmp/settings\n\necho 'reading input openapi specs' >& 2\ncat > ${OUTPUT_DIR}/swagger.json.unprocessed\n\n\nsource \"/tmp/settings\"\n\nKUBERNETES_CRD_MODE=true \\\nGENERATE_APIS=${GENERATE_APIS} \\\nOPENAPI_SKIP_FETCH_SPEC=true \\\nOPENAPI_MODEL_LENGTH=${OPENAPI_MODEL_LENGTH} \\\nKUBERNETES_CRD_GROUP_PREFIX=${KUBERNETES_CRD_GROUP_PREFIX} \\\nOPENAPI_SKIP_BASE_INTERFACE=${OPENAPI_SKIP_BASE_INTERFACE} \\\nHIDE_GENERATION_TIMESTAMP=${HIDE_GENERATION_TIMESTAMP} \\\nLIBRARY=${LIBRARY} \\\n$(pwd)/java.sh ${OUTPUT_DIR} /tmp/settings\n", "num_lines": 81}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest swagger spec.\n# Puts the updated spec at api/swagger-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v4.3.1}\" \\\nCLIENT_LANGUAGE=java; \\\nCLEANUP_DIRS=(docs src/test/java/io/kubernetes/client/openapi/apis src/main/java/io/kubernetes/client/openapi/apis src/main/java/io/kubernetes/client/openapi/models src/main/java/io/kubernetes/client/openapi/auth gradle); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n", "num_lines": 56}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nCLIENT_LANGUAGE=perl; \\\nCLEANUP_DIRS=(docs lib); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n", "num_lines": 52}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"    python-asyncio.sh OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SETTING_FILE}\"\n\n# use openapi-generator to generate library\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v4.2.3}\"\n\nCLIENT_LANGUAGE=python-asyncio\nCLEANUP_DIRS=(client/apis client/models docs test)\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\n# Generic patches to the generated Python code, most notably renaming the library.\necho \"--- Patching generated code...\"\n\nif [ ${PACKAGE_NAME} == \"client\" ]; then\n\n  # Post-processing of the generated Python wrapper.\n  find \"${OUTPUT_DIR}/test\" -type f -name \\*.py -exec sed -i 's/\\bclient/kubernetes_asyncio.client/g' {} +\n  find \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i 's/\\bclient/kubernetes_asyncio.client/g' {} +\n  find \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i 's/kubernetes_asyncio.client-python/client-python/g' {} +\n\n  # fix imports\n  find \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/import client\\./import kubernetes_asyncio.client./g' {} +\n  find \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/from client/from kubernetes_asyncio.client/g' {} +\n  find \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/getattr(client\\.models/getattr(kubernetes_asyncio.client.models/g' {} +\n\nelse\n\n  # Post-processing of the generated Python wrapper.\n  find \"${OUTPUT_DIR}/test\" -type f -name \\*.py -exec sed -i \"s/\\\\bclient/${PACKAGE_NAME}.client/g\" {} +\n  find \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i \"s/\\\\bclient/${PACKAGE_NAME}.client/g\" {} +\n  find \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i \"s/${PACKAGE_NAME}.client-python/client-python/g\" {} +\n\nfi\n\necho \"---Done.\"\n", "num_lines": 79}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nPACKAGE_NAME=${PACKAGE_NAME:-client}\nCLIENT_VERSION=${CLIENT_VERSION:-17.0.0-snapshot}\nGENERATE_APIS=${GENERATE_APIS:-false}\nOUTPUT_DIR=${OUTPUT_DIR:-python}\nOPENAPI_MODEL_LENGTH=${OPENAPI_MODEL_LENGTH:-}\nHIDE_GENERATION_TIMESTAMP=${HIDE_GENERATION_TIMESTAMP:-false}\nOPENAPI_SKIP_BASE_INTERFACE=\nKUBERNETES_CRD_GROUP_PREFIX=\n\nprint_usage() {\n  echo \"Usage: generate a python project using input openapi spec from stdin\" >& 2\n  echo \" -c: project version of the generated python project.\" >& 2\n  echo \" -n: the prefix of the target CRD's api group to generate.\" >& 2\n  echo \" -g: generate crd apis.\" >& 2\n  echo \" -p: the base package name of the generated python project. \" >& 2\n  echo \" -o: output directory of the generated python project. \" >& 2\n  echo \" -l: keep the n last segments for the generated class name. \" >& 2\n  echo \" -h: hide generation timestamp\" >& 2\n}\n\nwhile getopts 'c:g:h:n:l:p:o' flag; do\n  case \"${flag}\" in\n    c) CLIENT_VERSION=\"${CLIENT_VERSION}\" ;;\n    g) GENERATE_APIS=\"${OPTARG}\" ;;\n    h) HIDE_GENERATION_TIMESTAMP=\"${OPTARG}\" ;;\n    n) KUBERNETES_CRD_GROUP_PREFIX=\"${OPTARG}\" ;;\n    l) OPENAPI_MODEL_LENGTH=\"${OPTARG}\" ;;\n    p) PACKAGE_NAME=\"${OPTARG}\" ;;\n    o) OUTPUT_DIR=\"${OPTARG}\" ;;\n    *) print_usage\n       exit 1 ;;\n  esac\ndone\n\necho \"KUBERNETES_CRD_GROUP_PREFIX: $KUBERNETES_CRD_GROUP_PREFIX\" >& 2\necho \"OPENAPI_MODEL_LENGTH: $OPENAPI_MODEL_LENGTH\" >& 2\necho \"PACKAGE_NAME: $PACKAGE_NAME\" >& 2\necho \"GENERATE_APIS: $GENERATE_APIS\" >& 2\necho \"CLIENT_VERSION: $CLIENT_VERSION\" >& 2\necho \"OUTPUT_DIR: $OUTPUT_DIR\" >& 2\necho \"HIDE_GENERATION_TIMESTAMP: $HIDE_GENERATION_TIMESTAMP\" >& 2\necho \"\" >& 2 # empty line\n\n\nmkdir -p \"${OUTPUT_DIR}\"\n\necho 'rendering settings file to /tmp/settings' >& 2\nread -d '' settings << EOF\nexport KUBERNETES_BRANCH=\"${KUBERNETES_BRANCH}\"\nexport CLIENT_VERSION=\"${CLIENT_VERSION}\"\nexport PACKAGE_NAME=\"${PACKAGE_NAME}\"\nEOF\n\necho ${settings} > /tmp/settings\n\necho 'reading input openapi specs' >& 2\ncat swagger.json > ${OUTPUT_DIR}/swagger.json.unprocessed\n\nsource \"/tmp/settings\"\n\nKUBERNETES_CRD_MODE=true \\\nGENERATE_APIS=${GENERATE_APIS} \\\nOPENAPI_SKIP_FETCH_SPEC=true \\\nOPENAPI_MODEL_LENGTH=${OPENAPI_MODEL_LENGTH} \\\nKUBERNETES_CRD_GROUP_PREFIX=${KUBERNETES_CRD_GROUP_PREFIX} \\\nHIDE_GENERATION_TIMESTAMP=${HIDE_GENERATION_TIMESTAMP} \\\n$(pwd)/python.sh ${OUTPUT_DIR} /tmp/settings\n", "num_lines": 70}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v4.3.0}\"\n\nCLIENT_LANGUAGE=python; \\\nCLEANUP_DIRS=(client/api client/apis client/models docs test); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n\necho \"--- Patching generated code...\"\n\n# Post-processing of the generated Python wrapper.\nfind \"${OUTPUT_DIR}/test\" -type f -name \\*.py -exec sed -i 's/\\bclient/kubernetes.client/g' {} +\nfind \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i 's/\\bclient/kubernetes.client/g' {} +\nfind \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i 's/kubernetes.client-python/client-python/g' {} +\nfind \"${OUTPUT_DIR}\" -path \"${OUTPUT_DIR}/base\" -prune -o -type f -a -name \\*.md -exec sed -i 's/kubernetes-kubernetes.client/kubernetes-client/g' {} +\n\n# fix imports\nfind \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/import client\\./import kubernetes.client./g' {} +\nfind \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/from client/from kubernetes.client/g' {} +\nfind \"${OUTPUT_DIR}/client/\" -type f -name \\*.py -exec sed -i 's/getattr(client\\.models/getattr(kubernetes.client.models/g' {} +\n\necho \"---Done.\"\n", "num_lines": 68}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nCLIENT_LANGUAGE=ruby; \\\nCLEANUP_DIRS=(docs lib); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n", "num_lines": 52}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v4.0.3}\"; \\\nCLIENT_LANGUAGE=typescript-jquery; \\\nCLEANUP_DIRS=(api model); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n", "num_lines": 53}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARGC=$#\n\nif [ $# -ne 2 ]; then\n    echo \"Usage:\"\n    echo \"  $(basename ${0}) OUTPUT_DIR SETTING_FILE_PATH\"\n    echo \"    Setting file should define KUBERNETES_BRANCH, CLIENT_VERSION, and PACKAGE_NAME\"\n    echo \"    Setting file can define an optional USERNAME if you're working on a fork\"\n    echo \"    Setting file can define an optional REPOSITORY if you're working on a ecosystem project\"\n    exit 1\nfi\n\n\nOUTPUT_DIR=$1\nSETTING_FILE=$2\nmkdir -p \"${OUTPUT_DIR}\"\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\npushd \"${OUTPUT_DIR}\" > /dev/null\nOUTPUT_DIR=`pwd`\npopd > /dev/null\n\nsource \"${SCRIPT_ROOT}/openapi-generator/client-generator.sh\"\nsource \"${SETTING_FILE}\"\n\nOPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v4.0.3}\"; \\\nCLIENT_LANGUAGE=typescript; \\\nCLEANUP_DIRS=(api model); \\\nkubeclient::generator::generate_client \"${OUTPUT_DIR}\"\n", "num_lines": 53}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "echo \"TODO!!!\"", "num_lines": 1}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest swagger spec.\n# Puts the updated spec at api/swagger-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Generates client.\n# Required env vars:\n#   CLEANUP_DIRS: List of directories to cleanup before generation for this language\n#   KUBERNETES_BRANCH: Kubernetes branch name to get the swagger spec from\n#   CLIENT_VERSION: Client version. Will be used in the comment sections of the generated code\n#   PACKAGE_NAME: Name of the client package.\n#   CLIENT_LANGUAGE: Language of the client. ${CLIENT_LANGUAGE}.xml should exists.\n# Optional env vars:\n#   OPENAPI_GENERATOR_USER_ORG: openapi-generator-user-org\n#   OPENAPI_GENERATOR_COMMIT: openapi-generator-version\n# Input vars:\n#   $1: output directory\nkubeclient::generator::generate_client() {\n    : \"${CLEANUP_DIRS?Must set CLEANUP_DIRS env var}\"\n    : \"${KUBERNETES_BRANCH?Must set KUBERNETES_BRANCH env var}\"\n    : \"${CLIENT_VERSION?Must set CLIENT_VERSION env var}\"\n    : \"${PACKAGE_NAME?Must set PACKAGE_NAME env var}\"\n    : \"${CLIENT_LANGUAGE?Must set CLIENT_LANGUAGE env var}\"\n\n    OPENAPI_GENERATOR_USER_ORG=\"${OPENAPI_GENERATOR_USER_ORG:-OpenAPITools}\"\n    OPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT:-v5.1.0}\"\n    OPENAPI_MODEL_LENGTH=\"${OPENAPI_MODEL_LENGTH:-}\"\n    OPENAPI_SKIP_FETCH_SPEC=\"${OPENAPI_SKIP_FETCH_SPEC:-}\"\n    OPENAPI_SKIP_BASE_INTERFACE=\"${OPENAPI_SKIP_BASE_INTERFACE:-}\"\n    KUBERNETES_CRD_MODE=\"${KUBERNETES_CRD_MODE:-}\"\n    KUBERNETES_CRD_GROUP_PREFIX=\"${KUBERNETES_CRD_GROUP_PREFIX:-}\"\n    GENERATE_APIS=\"${GENERATE_APIS:-true}\"\n    HIDE_GENERATION_TIMESTAMP=\"${HIDE_GENERATION_TIMESTAMP:-false}\"\n    USERNAME=\"${USERNAME:-kubernetes}\"\n    REPOSITORY=\"${REPOSITORY:-kubernetes}\"\n    # LIBRARY is used by Java client generation.\n    LIBRARY=\"${LIBRARY:-okhttp-gson}\"\n\n    local output_dir=$1\n    pushd \"${output_dir}\" > /dev/null\n    local output_dir=`pwd`\n    popd > /dev/null\n    local SCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\n    pushd \"${SCRIPT_ROOT}\" > /dev/null\n    local SCRIPT_ROOT=`pwd`\n    popd > /dev/null\n\n    mkdir -p \"${output_dir}\"\n\n    if [ \"${USERNAME}\" != \"kubernetes\" ]; then\n        image_name=\"${USERNAME}-${REPOSITORY}-${CLIENT_LANGUAGE}-client-gen-with-openapi-generator:v1\"\n    else\n        image_name=\"${REPOSITORY}-${CLIENT_LANGUAGE}-client-gen-with-openapi-generator:v1\"\n    fi\n\n    echo \"--- Building docker image ${image_name}...\"\n    docker build \"${SCRIPT_ROOT}\"/../ -f \"${SCRIPT_ROOT}/Dockerfile\" -t \"${image_name}\" \\\n        --build-arg OPENAPI_GENERATOR_USER_ORG=\"${OPENAPI_GENERATOR_USER_ORG}\" \\\n        --build-arg OPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT}\" \\\n        --build-arg GENERATION_XML_FILE=\"${CLIENT_LANGUAGE}.xml\"\n\n    # Docker does not support passing arrays, pass the string representation\n    # of the array instead (space separated)\n    CLEANUP_DIRS_STRING=\"${CLEANUP_DIRS[@]}\"\n\n    echo \"--- Running generator inside container...\"\n    docker run --security-opt=\"label=disable\" -u $(id -u) \\\n        -e CLEANUP_DIRS=\"${CLEANUP_DIRS_STRING}\" \\\n        -e KUBERNETES_BRANCH=\"${KUBERNETES_BRANCH}\" \\\n        -e CLIENT_VERSION=\"${CLIENT_VERSION}\" \\\n        -e CLIENT_LANGUAGE=\"${CLIENT_LANGUAGE}\" \\\n        -e PACKAGE_NAME=\"${PACKAGE_NAME}\" \\\n        -e OPENAPI_GENERATOR_USER_ORG=\"${OPENAPI_GENERATOR_USER_ORG}\" \\\n        -e OPENAPI_GENERATOR_COMMIT=\"${OPENAPI_GENERATOR_COMMIT}\" \\\n        -e OPENAPI_MODEL_LENGTH=\"${OPENAPI_MODEL_LENGTH}\" \\\n        -e OPENAPI_SKIP_FETCH_SPEC=\"${OPENAPI_SKIP_FETCH_SPEC}\" \\\n        -e KUBERNETES_CRD_MODE=\"${KUBERNETES_CRD_MODE}\" \\\n        -e KUBERNETES_CRD_GROUP_PREFIX=\"${KUBERNETES_CRD_GROUP_PREFIX}\" \\\n        -e GENERATE_APIS=\"${GENERATE_APIS}\" \\\n        -e OPENAPI_SKIP_BASE_INTERFACE=\"${OPENAPI_SKIP_BASE_INTERFACE}\" \\\n        -e HIDE_GENERATION_TIMESTAMP=\"${HIDE_GENERATION_TIMESTAMP}\" \\\n        -e LIBRARY=\"${LIBRARY}\" \\\n        -e USERNAME=\"${USERNAME}\" \\\n        -e REPOSITORY=\"${REPOSITORY}\" \\\n        -v \"${output_dir}:/output_dir\" \\\n        \"${image_name}\" \"/output_dir\"\n\n    echo \"---Done.\"\n}\n", "num_lines": 108}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest swagger spec.\n# Puts the updated spec at api/swagger-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Generates client.\n# Required env vars:\n#   CLEANUP_DIRS: List of directories (string separated by space) to cleanup before generation for this language\n#   KUBERNETES_BRANCH: Kubernetes branch name to get the swagger spec from\n#   CLIENT_VERSION: Client version. Will be used in the comment sections of the generated code\n#   PACKAGE_NAME: Name of the client package.\n#   OPENAPI_GENERATOR_COMMIT: openapi-generator commit sha or tag/branch name. Will only be used as a reference in docs.\n# Input vars:\n#   $1: output directory\n: \"${CLEANUP_DIRS?Must set CLEANUP_DIRS env var}\"\n: \"${KUBERNETES_BRANCH?Must set KUBERNETES_BRANCH env var}\"\n: \"${CLIENT_VERSION?Must set CLIENT_VERSION env var}\"\n: \"${CLIENT_LANGUAGE?Must set CLIENT_LANGUAGE env var}\"\n: \"${PACKAGE_NAME?Must set PACKAGE_NAME env var}\"\n: \"${OPENAPI_GENERATOR_COMMIT?Must set OPENAPI_GENERATOR_COMMIT env var}\"\n\noutput_dir=$1\npushd \"${output_dir}\" > /dev/null\noutput_dir=`pwd`\npopd > /dev/null\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\npushd \"${SCRIPT_ROOT}\" > /dev/null\nSCRIPT_ROOT=`pwd`\npopd > /dev/null\n\nif ! which mvn > /dev/null 2>&1; then\n    echo \"Maven is not installed.\"\n    exit\nfi\n\n# There should be only one version of openapi-generator-maven-plugin.\nunset PLUGIN_VERSION\nshopt -s nullglob\nFOLDERS=(/root/.m2/repository/org/openapitools/openapi-generator-maven-plugin/*)\nfor folder in \"${FOLDERS[@]}\"; do\n    if [[ -d \"${folder}\" ]]; then\n        folder=$(basename \"${folder}\")\n        if [[ ! -z \"${PLUGIN_VERSION:-}\" ]]; then\n            echo \"Multiple openapi-generator-maven-plugin version exists: ${PLUGIN_VERSION} & ${folder}\"\n            exit 1\n        fi\n        PLUGIN_VERSION=\"${folder}\"\n    fi\ndone\nif [[ -z \"${PLUGIN_VERSION:-}\" ]]; then\n    echo \"Cannot find openapi-generator-maven-plugin version\"\n    exit 1\nfi\nshopt -u nullglob\n\n# To make sure we can reproduce generation, we would also log code-gen exact commit\npushd /source/openapi-generator\n  OPENAPI_GENERATOR_COMMIT_ACTUAL=$(git rev-parse HEAD)\npopd\n\nmkdir -p \"${output_dir}\"\n\necho \"--- Downloading and pre-processing OpenAPI spec\"\npython \"${SCRIPT_ROOT}/preprocess_spec.py\" \"${CLIENT_LANGUAGE}\" \"${KUBERNETES_BRANCH}\" \"${output_dir}/swagger.json\" \"${USERNAME}\" \"${REPOSITORY}\"\n\necho \"--- Cleaning up previously generated folders\"\nfor i in ${CLEANUP_DIRS}; do\n    echo \"--- Cleaning up ${output_dir}/${i}\"\n    rm -rf \"${output_dir}/${i}\"\ndone\n\necho \"--- Generating client ...\"\nmvn -f \"${SCRIPT_ROOT}/generation_params.xml\" clean generate-sources \\\n    -Dgenerator.spec.path=\"${output_dir}/swagger.json\" \\\n    -Dgenerator.output.path=\"${output_dir}\" \\\n    -D=generator.client.version=\"${CLIENT_VERSION}\" \\\n    -D=generator.package.name=\"${PACKAGE_NAME}\" \\\n    -D=openapi-generator-version=\"${PLUGIN_VERSION}\" \\\n    -Duser.home=/root\n\nmkdir -p \"${output_dir}/.openapi-generator\"\necho \"Requested Commit: ${OPENAPI_GENERATOR_COMMIT}\" > \"${output_dir}/.openapi-generator/COMMIT\"\necho \"Actual Commit: ${OPENAPI_GENERATOR_COMMIT_ACTUAL}\" >> \"${output_dir}/.openapi-generator/COMMIT\"\n\necho \"---Done.\"\n", "num_lines": 104}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nrelease=${1:-\"master\"}\n\necho Downloading proto files for ${release}\n\nmkdir -p k8s.io/apimachinery/pkg/api/resource\nmkdir -p k8s.io/apimachinery/pkg/apis/meta/v1\nmkdir -p k8s.io/apimachinery/pkg/util/intstr\nmkdir -p k8s.io/apimachinery/pkg/runtime/schema\nmkdir -p k8s.io/apis/meta/v1\n\nmkdir -p k8s.io/api/rbac/v1alpha1\nmkdir -p k8s.io/api/rbac/v1\nmkdir -p k8s.io/api/rbac/v1beta1\nmkdir -p k8s.io/api/networking/v1\nmkdir -p k8s.io/api/settings/v1alpha1\nmkdir -p k8s.io/api/admissionregistration/v1beta1\nmkdir -p k8s.io/api/scheduling/v1alpha1\nmkdir -p k8s.io/api/storage/v1\nmkdir -p k8s.io/api/storage/v1beta1\nmkdir -p k8s.io/api/batch/v2alpha1\nmkdir -p k8s.io/api/batch/v1\nmkdir -p k8s.io/api/batch/v1beta1\nmkdir -p k8s.io/api/apps/v1beta2\nmkdir -p k8s.io/api/apps/v1\nmkdir -p k8s.io/api/apps/v1beta1\nmkdir -p k8s.io/api/authentication/v1\nmkdir -p k8s.io/api/authentication/v1beta1\nmkdir -p k8s.io/api/admission/v1beta1\nmkdir -p k8s.io/api/policy/v1beta1\nmkdir -p k8s.io/api/core/v1\nmkdir -p k8s.io/api/autoscaling/v1\nmkdir -p k8s.io/api/autoscaling/v2beta1\nmkdir -p k8s.io/api/autoscaling/v2beta2\nmkdir -p k8s.io/api/extensions/v1beta1\nmkdir -p k8s.io/api/certificates/v1beta1\nmkdir -p k8s.io/api/imagepolicy/v1alpha1\nmkdir -p k8s.io/api/authorization/v1\nmkdir -p k8s.io/api/authorization/v1beta1\nmkdir -p k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1\n\nbase=https://raw.githubusercontent.com/kubernetes\nmachinery_base=${base}/apimachinery/${release}\ncurl -s ${machinery_base}/pkg/api/resource/generated.proto \\\n\t> k8s.io/apimachinery/pkg/api/resource/generated.proto\n\ncurl -s ${machinery_base}/pkg/apis/meta/v1/generated.proto \\\n\t> k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto\n\ncurl -s ${machinery_base}/pkg/util/intstr/generated.proto \\\n\t> k8s.io/apimachinery/pkg/util/intstr/generated.proto\n\ncurl -s ${machinery_base}/pkg/runtime/generated.proto \\\n\t> k8s.io/apimachinery/pkg/runtime/generated.proto\n\ncurl -s ${machinery_base}/pkg/runtime/schema/generated.proto \\\n\t> k8s.io/apimachinery/pkg/runtime/schema/generated.proto\n\n# There are currently no release branches for these files.\ncurl -s ${base}/api/master/rbac/v1alpha1/generated.proto > k8s.io/api/rbac/v1alpha1/generated.proto\ncurl -s ${base}/api/master/rbac/v1/generated.proto > k8s.io/api/rbac/v1/generated.proto\ncurl -s ${base}/api/master/rbac/v1beta1/generated.proto > k8s.io/api/rbac/v1beta1/generated.proto\ncurl -s ${base}/api/master/networking/v1/generated.proto > k8s.io/api/networking/v1/generated.proto\ncurl -s ${base}/api/master/settings/v1alpha1/generated.proto > k8s.io/api/settings/v1alpha1/generated.proto\ncurl -s ${base}/api/master/admissionregistration/v1beta1/generated.proto > k8s.io/api/admissionregistration/v1beta1/generated.proto\ncurl -s ${base}/api/master/scheduling/v1alpha1/generated.proto > k8s.io/api/scheduling/v1alpha1/generated.proto\ncurl -s ${base}/api/master/storage/v1/generated.proto > k8s.io/api/storage/v1/generated.proto\ncurl -s ${base}/api/master/storage/v1beta1/generated.proto > k8s.io/api/storage/v1beta1/generated.proto\ncurl -s ${base}/api/master/batch/v2alpha1/generated.proto > k8s.io/api/batch/v2alpha1/generated.proto\ncurl -s ${base}/api/master/batch/v1/generated.proto > k8s.io/api/batch/v1/generated.proto\ncurl -s ${base}/api/master/batch/v1beta1/generated.proto > k8s.io/api/batch/v1beta1/generated.proto\ncurl -s ${base}/api/master/apps/v1beta2/generated.proto > k8s.io/api/apps/v1beta2/generated.proto\ncurl -s ${base}/api/master/apps/v1/generated.proto > k8s.io/api/apps/v1/generated.proto\ncurl -s ${base}/api/master/apps/v1beta1/generated.proto > k8s.io/api/apps/v1beta1/generated.proto\ncurl -s ${base}/api/master/authentication/v1/generated.proto > k8s.io/api/authentication/v1/generated.proto\ncurl -s ${base}/api/master/authentication/v1beta1/generated.proto > k8s.io/api/authentication/v1beta1/generated.proto\ncurl -s ${base}/api/master/admission/v1beta1/generated.proto > k8s.io/api/admission/v1beta1/generated.proto\ncurl -s ${base}/api/master/policy/v1beta1/generated.proto > k8s.io/api/policy/v1beta1/generated.proto\ncurl -s ${base}/api/master/core/v1/generated.proto > k8s.io/api/core/v1/generated.proto\ncurl -s ${base}/api/master/autoscaling/v1/generated.proto > k8s.io/api/autoscaling/v1/generated.proto\ncurl -s ${base}/api/master/autoscaling/v2beta1/generated.proto > k8s.io/api/autoscaling/v2beta1/generated.proto\ncurl -s ${base}/api/master/autoscaling/v2beta2/generated.proto > k8s.io/api/autoscaling/v2beta2/generated.proto\ncurl -s ${base}/api/master/extensions/v1beta1/generated.proto > k8s.io/api/extensions/v1beta1/generated.proto\ncurl -s ${base}/api/master/certificates/v1beta1/generated.proto > k8s.io/api/certificates/v1beta1/generated.proto\ncurl -s ${base}/api/master/imagepolicy/v1alpha1/generated.proto > k8s.io/api/imagepolicy/v1alpha1/generated.proto\ncurl -s ${base}/api/master/authorization/v1/generated.proto > k8s.io/api/authorization/v1/generated.proto\ncurl -s ${base}/api/master/authorization/v1beta1/generated.proto > k8s.io/api/authorization/v1beta1/generated.proto\ncurl -s ${base}/apiextensions-apiserver/master/pkg/apis/apiextensions/v1beta1/generated.proto > k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto\n", "num_lines": 104}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# usage: generate.sh $LANGUAGE $OUTPUT_DIR\n#  current tested languages:\n#   * java\n\ndir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif ! which protoc > /dev/null; then\n  ${dir}/install.sh\n  proto=./bin/protoc\nelse\n  proto=$(which protoc)\nfi\n\n${dir}/dependencies.sh\n\n# The format here is <file-name>;<generated-class-name>\nfiles=\"k8s.io/apimachinery/pkg/api/resource/generated.proto;Resource \\\n       k8s.io/apimachinery/pkg/apis/meta/v1/generated.proto;Meta \\\n       k8s.io/apimachinery/pkg/runtime/generated.proto;Runtime \\\n       k8s.io/apimachinery/pkg/runtime/schema/generated.proto;RuntimeSchema \\\n       k8s.io/apimachinery/pkg/util/intstr/generated.proto;IntStr \\\n       k8s.io/api/rbac/v1alpha1/generated.proto;V1alpha1Rbac \\\n       k8s.io/api/rbac/v1/generated.proto;V1Rbac \\\n       k8s.io/api/rbac/v1beta1/generated.proto;V1beta1Rbac \\\n       k8s.io/api/networking/v1/generated.proto;V1Networking \\\n       k8s.io/api/settings/v1alpha1/generated.proto;V1alpha1Settings \\\n       k8s.io/api/admissionregistration/v1beta1/generated.proto;V1beta1Admissionregistration \\\n       k8s.io/api/scheduling/v1alpha1/generated.proto;V1alpha1Scheduling \\\n       k8s.io/api/storage/v1/generated.proto;V1Storage \\\n       k8s.io/api/storage/v1beta1/generated.proto;V1beta1Storage \\\n       k8s.io/api/batch/v2alpha1/generated.proto;V2alpha1Batch \\\n       k8s.io/api/batch/v1/generated.proto;V1Batch \\\n       k8s.io/api/batch/v1beta1/generated.proto;V1beta1Batch \\\n       k8s.io/api/apps/v1beta2/generated.proto;V1beta2Apps \\\n       k8s.io/api/apps/v1/generated.proto;V1Apps \\\n       k8s.io/api/apps/v1beta1/generated.proto;V1beta1Apps \\\n       k8s.io/api/authentication/v1/generated.proto;V1Authentication \\\n       k8s.io/api/authentication/v1beta1/generated.proto;V1beta1Authentication \\\n       k8s.io/api/admission/v1beta1/generated.proto;V1beta1Admission \\\n       k8s.io/api/policy/v1beta1/generated.proto;V1beta1Policy \\\n       k8s.io/api/core/v1/generated.proto;V1 \\\n       k8s.io/api/autoscaling/v1/generated.proto;V1Autoscaling \\\n       k8s.io/api/autoscaling/v2beta1/generated.proto;V2beta1Autoscaling \\\n       k8s.io/api/autoscaling/v2beta2/generated.proto;V2beta2Autoscaling \\\n       k8s.io/api/extensions/v1beta1/generated.proto;V1beta1Extensions \\\n       k8s.io/api/certificates/v1beta1/generated.proto;V1beta1Certificates \\\n       k8s.io/api/imagepolicy/v1alpha1/generated.proto;V1alpha1Imagepolicy \\\n       k8s.io/api/authorization/v1/generated.proto;V1Authorization \\\n       k8s.io/api/authorization/v1beta1/generated.proto;V1beta1Authorization \\\n       k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1/generated.proto;V1beta1Apiextensions\"\n\nproto_files=\"\"\n\necho 'Munging proto file packages'\n\n# This is a little hacky, but we know the go_package directive is in the\n# right place, so add a marker, and then append more package declarations.\n# Sorry, I like perl.\nfor info in ${files}; do\n  file=$(echo ${info} | cut -d \";\" -f 1)\n  class=$(echo ${info} | cut -d \";\" -f 2)\n  proto_files=\"${file} ${proto_files}\"\n  perl -pi -e \\\n    's/option go_package = \"(.*)\";/option go_package = \"$1\";\\n\\/\\/ PKG/' \\\n    ${file} \n  perl -pi -e \\\n    's/\\/\\/ PKG/\\/\\/ PKG\\noption java_package = \"io.kubernetes.client.proto\";/' \\\n    ${file}\n  perl -pi -e \\\n    \"s/\\/\\/ PKG/\\/\\/ PKG\\noption java_outer_classname = \\\"${class}\\\";/\" \\\n    ${file}\n  \n  # Other package declarations can go here.\ndone\n\necho \"Generating code for $1\"\n${proto} -I${dir} ${proto_files} --${1}_out=${2}\n", "num_lines": 94}
{"repo_name": "gen", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\necho 'Installing proto compiler'\n\nversion=3.6.1\nfile=protoc-${version}-linux-x86_64.zip\n\nwget https://github.com/google/protobuf/releases/download/v${version}/${file}\nunzip ${file}\nrm ${file}\n\n\n", "num_lines": 27}
{"repo_name": "glow", "repo_creator": "openai", "programming_language": "Shell", "code": "apt update && \\\napt install -y locales cmake libsm6 libxext6 libxrender-dev && \\\nlocale-gen en_US.UTF-8\n\nexport LC_ALL=en_US.UTF-8\n\n# Pip packages for running server and face-aligned (dlib takes a while to install)\npip install flask flask_cors tqdm opencv-python imutils dlib imageio\n\n# Get model weights\ncurl https://openaipublic.azureedge.net/glow-demo/large3/graph_optimized.pb > graph_optimized.pb\n\n# Get manipulation vectors\ncurl https://openaipublic.azureedge.net/glow-demo/z_manipulate.npy > z_manipulate.npy\n\n# Get facial landmarks for aligning input faces\ncurl https://openaipublic.azureedge.net/glow-demo/shape_predictor_68_face_landmarks.dat > shape_predictor_68_face_landmarks.dat\n\n# Pip package for running optimized model with fused kernels\ncurl https://openaipublic.azureedge.net/glow-demo/blocksparse-1.0.0-py2.py3-none-any.whl > blocksparse-1.0.0-py2.py3-none-any.whl\npip install blocksparse-1.0.0-py2.py3-none-any.whl\n\n# If blocksparse doesn't install, use unoptimized model (and set optimized=False in model.py)\n# curl https://openaipublic.azureedge.net/glow-demo/large3/graph_unoptimized.pb > graph_unoptimized.pb\n\n", "num_lines": 26}
{"repo_name": "go-vncdriver", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# This file is deprecated. Will be removed shortly.\n\n./build.py\n", "num_lines": 6}
{"repo_name": "go-vncdriver", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh -eux\n\nif [ \"$1\" != \"\" ]; then\n  cd /tmp\n  wget http://downloads.sourceforge.net/project/libjpeg-turbo/1.3.1/libjpeg-turbo-official_$1_amd64.deb\n  sudo dpkg -i libjpeg-turbo-official_$1_amd64.deb\n  find /opt/libjpeg-turbo/lib64\n  find /opt/libjpeg-turbo/include\nfi\n", "num_lines": 10}
{"repo_name": "go-vncdriver-feedstock", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# Update PR refs for testing.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/head:pr/${CIRCLE_PR_NUMBER}/head\"\n    FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/merge:pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Retrieve the refs.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    git fetch -u origin ${FETCH_REFS}\nfi\n\n# Checkout the PR merge ref.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    git checkout -qf \"pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Check for merge conflicts.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    git branch --merged | grep \"pr/${CIRCLE_PR_NUMBER}/head\" > /dev/null\nfi\n", "num_lines": 28}
{"repo_name": "go-vncdriver-feedstock", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# PLEASE NOTE: This script has been automatically generated by conda-smithy. Any changes here\n# will be lost next time ``conda smithy rerender`` is run. If you would like to make permanent\n# changes to this script, consider a proposal to conda-smithy so that other feedstocks can also\n# benefit from the improvement.\n\nFEEDSTOCK_ROOT=$(cd \"$(dirname \"$0\")/..\"; pwd;)\nRECIPE_ROOT=$FEEDSTOCK_ROOT/recipe\n\ndocker info\n\nconfig=$(cat <<CONDARC\n\nchannels:\n - conda-forge\n - defaults # As we need conda-build\n\nconda-build:\n root-dir: /feedstock_root/build_artefacts\n\nshow_channel_urls: true\n\nCONDARC\n)\n\ncat << EOF | docker run -i \\\n                        -v ${RECIPE_ROOT}:/recipe_root \\\n                        -v ${FEEDSTOCK_ROOT}:/feedstock_root \\\n                        -a stdin -a stdout -a stderr \\\n                        condaforge/linux-anvil \\\n                        bash || exit $?\n\nexport BINSTAR_TOKEN=${BINSTAR_TOKEN}\nexport PYTHONUNBUFFERED=1\n\necho \"$config\" > ~/.condarc\n# A lock sometimes occurs with incomplete builds. The lock file is stored in build_artefacts.\nconda clean --lock\n\nconda install --yes --quiet conda-forge-build-setup\nsource run_conda_forge_build_setup\n\n# Embarking on 3 case(s).\n    set -x\n    export CONDA_PY=27\n    set +x\n    conda build /recipe_root --quiet || exit 1\n    upload_or_check_non_existence /recipe_root jeremyschlatter --channel=main || exit 1\n\n    set -x\n    export CONDA_PY=34\n    set +x\n    conda build /recipe_root --quiet || exit 1\n    upload_or_check_non_existence /recipe_root jeremyschlatter --channel=main || exit 1\n\n    set -x\n    export CONDA_PY=35\n    set +x\n    conda build /recipe_root --quiet || exit 1\n    upload_or_check_non_existence /recipe_root jeremyschlatter --channel=main || exit 1\nEOF\n", "num_lines": 63}
{"repo_name": "go-vncdriver-feedstock", "repo_creator": "openai", "programming_language": "Shell", "code": "GOOS=$(uname | tr '[:upper:]' '[:lower:]')\nif [ $ARCH = '64' ]; then\n    GOARCH=amd64\nelse\n    GOARCH=386\nfi\ncurl -o go.tar.gz https://storage.googleapis.com/golang/go1.7.4.$GOOS-$GOARCH.tar.gz\ntar xf go.tar.gz\nexport GOROOT=$(pwd)/go\nexport PATH=$GOROOT/bin:$PATH\n\nexport GO_VNCDRIVER_PYTHON=\"$PYTHON\"\nexport LIBJPG=\"-L$PREFIX/lib -lturbojpeg\"\n$PREFIX/bin/pip install .\n\nif [ -n $TWINE_USERNAME ]; then\n    echo \"Building and uploading wheel to PyPI\"\n    $PYTHON setup.py bdist_wheel\n    twine upload --skip-existing dist/go_vncdriver-*.whl -r https://testpypi.python.org/pypi --repository-url https://testpypi.python.org/pypi\nfi\n", "num_lines": 21}
{"repo_name": "grok", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Set up torch with magma support\n\nDIR=\"`mktemp -d`\"\ncd $DIR\n\n# Install deps\nconda install -y numpy ninja pyyaml mkl mkl-include setuptools cmake cffi typing_extensions future six requests dataclasses\n\n# Install torch, magma\nconda install -y -c pytorch magma-cuda110\n\n# Build torch from scratch\ngit clone --recursive https://github.com/pytorch/pytorch\ncd pytorch\n\n# If updating an existing checkout\n# git submodule sync\n# git submodule update --init --recursive\n\nexport CMAKE_PREFIX_PATH=${CONDA_PREFIX:-\"$(dirname $(which conda))/../\"}\npython setup.py install", "num_lines": 23}
{"repo_name": "gym-http-api", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# If these dependencies do not exist, install them\nhash gulp 2>/dev/null || npm i -g gulp\nhash tsfmt 2>/dev/null || npm i -g typescript-formatter\nhash typings 2>/dev/null || npm i -g typings\n\n(cd src && typings install)\n", "num_lines": 9}
{"repo_name": "gym-http-api", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\ntsfmt -r $(find . -name \"*.ts*\" ! -name \"*.d.ts\" ! -path \"./node_modules/*\") || true\n", "num_lines": 3}
{"repo_name": "improved-gan", "repo_creator": "openai", "programming_language": "Shell", "code": "export word=imagenet\nexport pixels=128\necho $HOSTNAME >> ${word}.record.txt\nCUDA_VISIBLE_DEVICES=$GPUS python train_${word}.py --dataset imagenet_train --is_train True --checkpoint_dir gan/checkpoint_${word} --image_size ${pixels} --is_crop True --sample_dir gan/samples_${word} --image_width ${pixels} --batch_size 16\n", "num_lines": 5}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\npython -m torch.distributed.launch --nproc_per_node=2 distributed_data_parallel.py\n", "num_lines": 3}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\npython -m torch.distributed.launch --nproc_per_node=2 amp_master_params.py\n\npython compare.py\n", "num_lines": 5}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nCUDA_VISIBLE_DEVICES=0,1 python -m torch.distributed.launch --nproc_per_node=2 ddp_race_condition_test.py\n", "num_lines": 4}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "python single_gpu_unit_test.py\npython -m torch.distributed.launch --nproc_per_node=2 two_gpu_unit_test.py\npython -m torch.distributed.launch --nproc_per_node=2 two_gpu_unit_test.py --fp64\n#beware, you need a system with at least 4 gpus to test group_size<world_size\npython -m torch.distributed.launch --nproc_per_node=4 test_groups.py --group_size=2\n", "num_lines": 6}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nprint_banner() {\n  printf \"\\n\\n\\n\\e[30m\\e[42m$1\\e[0m\\n\\n\\n\\n\"\n}\n\nprint_green() {\n  printf \"\\e[30m\\e[42m$1\\e[0m\\n\"\n}\n\nprint_red() {\n  printf \"\\e[30m\\e[41m$1\\e[0m\\n\"\n}\n\nimages=(\n\"gitlab-master.nvidia.com:5005/dl/dgx/pytorch:19.03-py3-devel\"\n\"gitlab-master.nvidia.com:5005/dl/dgx/pytorch:master-py3-devel\"\n\"pytorch/pytorch:nightly-devel-cuda10.0-cudnn7\"\n\"pytorch/pytorch:1.1.0-cuda10.0-cudnn7.5-devel\"\n\"pytorch/pytorch:1.0.1-cuda10.0-cudnn7-devel\"\n\"pytorch/pytorch:1.0-cuda10.0-cudnn7-devel\"\n\"pytorch/pytorch:nightly-devel-cuda9.2-cudnn7\"\n)\n\nbranch=\"master\"\n\n# Associative array for exit codes\ndeclare -A exit_codes\nfor image in images\ndo\n  exit_codes[$image]=\"None\"\ndone\n\nfor image in \"${images[@]}\"\ndo\n  print_banner \"$image\"\n  set -x\n  docker pull $image\n  # Trying python setup.py install instead of pip install to ensure direct access to error codes.\n  # Maybe pip install would be ok too but this works.\n  docker run --runtime=nvidia --rm $image /bin/bash -c \"yes | pip uninstall apex; yes | pip uninstall apex; git clone https://github.com/NVIDIA/apex.git; cd apex; git checkout $branch; set -e;  python setup.py install --cuda_ext --cpp_ext\"\n  exit_code=$?\n  set +x\n  if [ $exit_code != 0 ]\n  then\n    print_red \"Exit code: $exit_code\"\n  else\n    print_green \"Exit code: $exit_code\"\n  fi\n  exit_codes[$image]=$exit_code\ndone\n\nsuccess=0\nfor image in \"${images[@]}\"\ndo\n  exit_code=${exit_codes[$image]}\n  if [ $exit_code != 0 ]\n  then\n    print_red \"$image : $exit_code\"\n    success=1\n  else\n    print_green \"$image : $exit_code\"\n  fi\ndone\n\nif [ $success != 0 ]\nthen\n  print_red \"Overall status:  failure\"\nelse\n  print_green \"Overall status:  success\"\nfi\n\nexit $success\n", "num_lines": 74}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nprint_banner() {\n  printf \"\\n\\n\\n\\e[30m\\e[42m$1\\e[0m\\n\\n\\n\\n\"\n}\n\nprint_banner \"Distributed status:  $1\"\n\necho $2\nDATADIR=$2\n\nif [ -n \"$3\" ]\nthen\n  USE_BASELINE=\"\"\nelse\n  USE_BASELINE=\"--use_baseline\"\nfi\n\nif [ \"$1\" == \"single_gpu\" ]\nthen\n  BASE_CMD=\"python main_amp.py -a resnet50 --b 128 --workers 4 --deterministic --prints-to-process 5\"\nfi\n\nif [ \"$1\" == \"distributed\" ]\nthen\n  BASE_CMD=\"python -m torch.distributed.launch --nproc_per_node=2 main_amp.py -a resnet50 --b 128 --workers 4 --deterministic --prints-to-process 5\"\nfi\n\nADAM_ARGS=\"--opt-level O2 --keep-batchnorm-fp32 False --fused-adam\"\n\nkeep_batchnorms=(\n\"\"\n\"--keep-batchnorm-fp32 True\"\n\"--keep-batchnorm-fp32 False\"\n)\n\nloss_scales=(\n\"\"\n\"--loss-scale 1.0\"\n\"--loss-scale 128.0\"\n\"--loss-scale dynamic\"\n)\n\nopt_levels=(\n\"O0\"\n\"O1\"\n\"O2\"\n\"O3\"\n)\n\nrm True*\nrm False*\n\nset -e\n\nprint_banner \"Installing Apex with --cuda_ext and --cpp_ext\"\n\npushd ../../..\npip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" .\npopd\n\nfor opt_level in \"${opt_levels[@]}\"\ndo\n  for loss_scale in \"${loss_scales[@]}\"\n  do\n    for keep_batchnorm in \"${keep_batchnorms[@]}\"\n    do\n      if [ \"$opt_level\" == \"O1\" ] && [ -n \"${keep_batchnorm}\" ]\n      then\n        print_banner \"Skipping ${opt_level} ${loss_scale} ${keep_batchnorm}\"\n        continue\n      fi\n      print_banner \"${BASE_CMD} --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} --has-ext $DATADIR\"\n      set -x\n      ${BASE_CMD} --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} --has-ext $DATADIR\n      set +x\n    done\n  done\ndone\n\n# Handle FusedAdam separately due to limited support.\n# FusedAdam will not be tested for bitwise accuracy against the Python implementation.\n# The L0 tests already do so.  These tests are here to ensure that it actually runs,\n# and get an idea of performance.\nfor loss_scale in \"${loss_scales[@]}\"\ndo\n  print_banner \"${BASE_CMD} ${ADAM_ARGS} ${loss_scale} --has-ext $DATADIR\"\n  set -x\n  ${BASE_CMD} ${ADAM_ARGS} ${loss_scale} --has-ext $DATADIR\n  set +x\ndone\n\nprint_banner \"Reinstalling apex without extensions\"\n\npushd ../../..\npip install -v --no-cache-dir .\npopd\n\nfor opt_level in \"${opt_levels[@]}\"\ndo\n  for loss_scale in \"${loss_scales[@]}\"\n  do\n    for keep_batchnorm in \"${keep_batchnorms[@]}\"\n    do\n      if [ \"$opt_level\" == \"O1\" ] && [ -n \"${keep_batchnorm}\" ]\n      then\n        print_banner \"Skipping ${opt_level} ${loss_scale} ${keep_batchnorm}\"\n        continue\n      fi\n      print_banner \"${BASE_CMD} --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} $DATADIR\"\n      set -x\n      ${BASE_CMD} --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} $DATADIR\n      set +x\n    done\n  done\ndone\n\nprint_banner \"Checking for bitwise accuracy between Python-only and cpp/cuda extension installs\"\n\nfor opt_level in \"${opt_levels[@]}\"\ndo\n  for loss_scale in \"${loss_scales[@]}\"\n  do\n    for keep_batchnorm in \"${keep_batchnorms[@]}\"\n    do\n      echo \"\"\n      if [ \"$opt_level\" == \"O1\" ] && [ -n \"${keep_batchnorm}\" ]\n      then\n        echo \"Skipping ${opt_level} ${loss_scale} ${keep_batchnorm}\"\n        continue\n      fi\n      echo \"${BASE_CMD} --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} [--has-ext] $DATADIR\"\n      set -x\n      python compare.py --opt-level ${opt_level} ${loss_scale} ${keep_batchnorm} --use_baseline\n      set +x\n    done\n  done\ndone\n\nprint_banner \"Reinstalling Apex with --cuda_ext and --cpp_ext\"\n\npushd ../../..\npip install -v --no-cache-dir --global-option=\"--cpp_ext\" --global-option=\"--cuda_ext\" .\npopd\n", "num_lines": 145}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nDATADIR=\"/home/mcarilli/Desktop/pt18data/apex_stale/examples/imagenet/bare_metal_train_val/\"\n# DATADIR=\"/opt/home/apex/examples/imagenet/\"\ncp ../common/* .\nbash run_test.sh single_gpu $1 $DATADIR yes\n", "num_lines": 7}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ncp ../common/* .\nbash run_test.sh distributed $1\n", "num_lines": 5}
{"repo_name": "jukebox", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Exit on error\n# set -e\n\nDESIRED_PROTO_VERSION=\"3.6.1\"\n\n# call protoc direclty, if version is not the desired one, download the desired vesrion.\n\n\nif [ -f \"protoc/bin/protoc\" ]; then\n  PROTOC_BIN=\"protoc/bin/protoc\"\nelse\n  PROTOC_BIN=`which protoc`\nfi\n\necho \"using\" $PROTOC_BIN\n\nCURRENT_PROTOC_VER=`${PROTOC_BIN} --version`\nif [ -z ${PROTOC_BIN} ] || [[ \"$CURRENT_PROTOC_VER\" != \"libprotoc \"$DESIRED_PROTO_VERSION ]]; then\n  # Download and use the latest version of protoc.\n  if [ \"$(uname)\" == \"Darwin\" ]; then\n    PROTOC_ZIP=\"protoc-\"$DESIRED_PROTO_VERSION\"-osx-x86_64.zip\"\n  else\n    PROTOC_ZIP=\"protoc-\"$DESIRED_PROTO_VERSION\"-linux-x86_64.zip\"\n  fi\n  WGET_BIN=`which wget`\n  if [[ ! -z ${WGET_BIN} ]]; then\n    ${WGET_BIN} https://github.com/protocolbuffers/protobuf/releases/download/v\"$DESIRED_PROTO_VERSION\"/${PROTOC_ZIP}\n    rm -rf protoc\n    python -c \"import zipfile; zipfile.ZipFile('\"${PROTOC_ZIP}\"','r').extractall('protoc')\"\n    PROTOC_BIN=protoc/bin/protoc\n    chmod +x ${PROTOC_BIN}\n  fi\nfi\n\n# Regenerate\nif [[ ! -z ${PROTOC_BIN} ]]; then\n  # Delete all existing Python protobuf (*_pb2.py) output\n  rm -rf tensorboardX/proto/*pb2*.py\n  ${PROTOC_BIN} tensorboardX/proto/*.proto --python_out=.\n\n  echo \"Done generating tensorboardX/proto/*pb2*.py\"\nelse\n  echo \"protoc not installed so can't regenerate tensorboardX/proto/*pb2*.py, using precompiled version.\"\nfi\n\n", "num_lines": 48}
{"repo_name": "junit-annotate-buildkite-plugin", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\ngem install nokogiri --quiet --silent\n\nruby junit.rb /junits/*\n", "num_lines": 8}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# shellcheck disable=SC2034 # Variables sourced in other scripts.\n\n# Common utilities, variables and checks for all build scripts.\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Unset CDPATH, having it set messes up with script import paths\nunset CDPATH\n\nUSER_ID=$(id -u)\nGROUP_ID=$(id -g)\n\nDOCKER_OPTS=${DOCKER_OPTS:-\"\"}\nIFS=\" \" read -r -a DOCKER <<< \"docker ${DOCKER_OPTS}\"\nDOCKER_HOST=${DOCKER_HOST:-\"\"}\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. && pwd -P)\n\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Constants\nreadonly KUBE_BUILD_IMAGE_REPO=kube-build\nreadonly KUBE_BUILD_IMAGE_CROSS_TAG=\"$(cat \"${KUBE_ROOT}/build/build-image/cross/VERSION\")\"\n\nreadonly KUBE_DOCKER_REGISTRY=\"${KUBE_DOCKER_REGISTRY:-k8s.gcr.io}\"\nreadonly KUBE_BASE_IMAGE_REGISTRY=\"${KUBE_BASE_IMAGE_REGISTRY:-k8s.gcr.io/build-image}\"\n\n# This version number is used to cause everyone to rebuild their data containers\n# and build image.  This is especially useful for automated build systems like\n# Jenkins.\n#\n# Increment/change this number if you change the build image (anything under\n# build/build-image) or change the set of volumes in the data container.\nreadonly KUBE_BUILD_IMAGE_VERSION_BASE=\"$(cat \"${KUBE_ROOT}/build/build-image/VERSION\")\"\nreadonly KUBE_BUILD_IMAGE_VERSION=\"${KUBE_BUILD_IMAGE_VERSION_BASE}-${KUBE_BUILD_IMAGE_CROSS_TAG}\"\n\n# Here we map the output directories across both the local and remote _output\n# directories:\n#\n# *_OUTPUT_ROOT    - the base of all output in that environment.\n# *_OUTPUT_SUBPATH - location where golang stuff is built/cached.  Also\n#                    persisted across docker runs with a volume mount.\n# *_OUTPUT_BINPATH - location where final binaries are placed.  If the remote\n#                    is really remote, this is the stuff that has to be copied\n#                    back.\n# OUT_DIR can come in from the Makefile, so honor it.\nreadonly LOCAL_OUTPUT_ROOT=\"${KUBE_ROOT}/${OUT_DIR:-_output}\"\nreadonly LOCAL_OUTPUT_SUBPATH=\"${LOCAL_OUTPUT_ROOT}/dockerized\"\nreadonly LOCAL_OUTPUT_BINPATH=\"${LOCAL_OUTPUT_SUBPATH}/bin\"\nreadonly LOCAL_OUTPUT_GOPATH=\"${LOCAL_OUTPUT_SUBPATH}/go\"\nreadonly LOCAL_OUTPUT_IMAGE_STAGING=\"${LOCAL_OUTPUT_ROOT}/images\"\n\n# This is a symlink to binaries for \"this platform\" (e.g. build tools).\nreadonly THIS_PLATFORM_BIN=\"${LOCAL_OUTPUT_ROOT}/bin\"\n\nreadonly REMOTE_ROOT=\"/go/src/${KUBE_GO_PACKAGE}\"\nreadonly REMOTE_OUTPUT_ROOT=\"${REMOTE_ROOT}/_output\"\nreadonly REMOTE_OUTPUT_SUBPATH=\"${REMOTE_OUTPUT_ROOT}/dockerized\"\nreadonly REMOTE_OUTPUT_BINPATH=\"${REMOTE_OUTPUT_SUBPATH}/bin\"\nreadonly REMOTE_OUTPUT_GOPATH=\"${REMOTE_OUTPUT_SUBPATH}/go\"\n\n# This is the port on the workstation host to expose RSYNC on.  Set this if you\n# are doing something fancy with ssh tunneling.\nreadonly KUBE_RSYNC_PORT=\"${KUBE_RSYNC_PORT:-}\"\n\n# This is the port that rsync is running on *inside* the container. This may be\n# mapped to KUBE_RSYNC_PORT via docker networking.\nreadonly KUBE_CONTAINER_RSYNC_PORT=8730\n\n# These are the default versions (image tags) for their respective base images.\nreadonly __default_debian_iptables_version=buster-v1.6.5\nreadonly __default_go_runner_version=v2.3.1-go1.16.5-buster.0\nreadonly __default_setcap_version=buster-v2.0.3\n\n# These are the base images for the Docker-wrapped binaries.\nreadonly KUBE_GORUNNER_IMAGE=\"${KUBE_GORUNNER_IMAGE:-$KUBE_BASE_IMAGE_REGISTRY/go-runner:$__default_go_runner_version}\"\nreadonly KUBE_APISERVER_BASE_IMAGE=\"${KUBE_APISERVER_BASE_IMAGE:-$KUBE_GORUNNER_IMAGE}\"\nreadonly KUBE_CONTROLLER_MANAGER_BASE_IMAGE=\"${KUBE_CONTROLLER_MANAGER_BASE_IMAGE:-$KUBE_GORUNNER_IMAGE}\"\nreadonly KUBE_SCHEDULER_BASE_IMAGE=\"${KUBE_SCHEDULER_BASE_IMAGE:-$KUBE_GORUNNER_IMAGE}\"\nreadonly KUBE_PROXY_BASE_IMAGE=\"${KUBE_PROXY_BASE_IMAGE:-$KUBE_BASE_IMAGE_REGISTRY/debian-iptables:$__default_debian_iptables_version}\"\n\n# This is the image used in a multi-stage build to apply capabilities to Docker-wrapped binaries.\nreadonly KUBE_BUILD_SETCAP_IMAGE=\"${KUBE_BUILD_SETCAP_IMAGE:-$KUBE_BASE_IMAGE_REGISTRY/setcap:$__default_setcap_version}\"\n\n# Get the set of master binaries that run in Docker (on Linux)\n# Entry format is \"<binary-name>,<base-image>\".\n# Binaries are placed in /usr/local/bin inside the image.\n# `make` users can override any or all of the base images using the associated\n# environment variables.\n#\n# $1 - server architecture\nkube::build::get_docker_wrapped_binaries() {\n  ### If you change any of these lists, please also update DOCKERIZED_BINARIES\n  ### in build/BUILD. And kube::golang::server_image_targets\n  local targets=(\n    \"kube-apiserver,${KUBE_APISERVER_BASE_IMAGE}\"\n    \"kube-controller-manager,${KUBE_CONTROLLER_MANAGER_BASE_IMAGE}\"\n    \"kube-scheduler,${KUBE_SCHEDULER_BASE_IMAGE}\"\n    \"kube-proxy,${KUBE_PROXY_BASE_IMAGE}\"\n  )\n\n  echo \"${targets[@]}\"\n}\n\n# ---------------------------------------------------------------------------\n# Basic setup functions\n\n# Verify that the right utilities and such are installed for building Kube. Set\n# up some dynamic constants.\n# Args:\n#   $1 - boolean of whether to require functioning docker (default true)\n#\n# Vars set:\n#   KUBE_ROOT_HASH\n#   KUBE_BUILD_IMAGE_TAG_BASE\n#   KUBE_BUILD_IMAGE_TAG\n#   KUBE_BUILD_IMAGE\n#   KUBE_BUILD_CONTAINER_NAME_BASE\n#   KUBE_BUILD_CONTAINER_NAME\n#   KUBE_DATA_CONTAINER_NAME_BASE\n#   KUBE_DATA_CONTAINER_NAME\n#   KUBE_RSYNC_CONTAINER_NAME_BASE\n#   KUBE_RSYNC_CONTAINER_NAME\n#   DOCKER_MOUNT_ARGS\n#   LOCAL_OUTPUT_BUILD_CONTEXT\nfunction kube::build::verify_prereqs() {\n  local -r require_docker=${1:-true}\n  kube::log::status \"Verifying Prerequisites....\"\n  kube::build::ensure_tar || return 1\n  kube::build::ensure_rsync || return 1\n  if ${require_docker}; then\n    kube::build::ensure_docker_in_path || return 1\n    if kube::build::is_osx; then\n        kube::build::docker_available_on_osx || return 1\n    fi\n    kube::util::ensure_docker_daemon_connectivity || return 1\n\n    if (( KUBE_VERBOSE > 6 )); then\n      kube::log::status \"Docker Version:\"\n      \"${DOCKER[@]}\" version | kube::log::info_from_stdin\n    fi\n  fi\n\n  KUBE_GIT_BRANCH=$(git symbolic-ref --short -q HEAD 2>/dev/null || true)\n  KUBE_ROOT_HASH=$(kube::build::short_hash \"${HOSTNAME:-}:${KUBE_ROOT}:${KUBE_GIT_BRANCH}\")\n  KUBE_BUILD_IMAGE_TAG_BASE=\"build-${KUBE_ROOT_HASH}\"\n  KUBE_BUILD_IMAGE_TAG=\"${KUBE_BUILD_IMAGE_TAG_BASE}-${KUBE_BUILD_IMAGE_VERSION}\"\n  KUBE_BUILD_IMAGE=\"${KUBE_BUILD_IMAGE_REPO}:${KUBE_BUILD_IMAGE_TAG}\"\n  KUBE_BUILD_CONTAINER_NAME_BASE=\"kube-build-${KUBE_ROOT_HASH}\"\n  KUBE_BUILD_CONTAINER_NAME=\"${KUBE_BUILD_CONTAINER_NAME_BASE}-${KUBE_BUILD_IMAGE_VERSION}\"\n  KUBE_RSYNC_CONTAINER_NAME_BASE=\"kube-rsync-${KUBE_ROOT_HASH}\"\n  KUBE_RSYNC_CONTAINER_NAME=\"${KUBE_RSYNC_CONTAINER_NAME_BASE}-${KUBE_BUILD_IMAGE_VERSION}\"\n  KUBE_DATA_CONTAINER_NAME_BASE=\"kube-build-data-${KUBE_ROOT_HASH}\"\n  KUBE_DATA_CONTAINER_NAME=\"${KUBE_DATA_CONTAINER_NAME_BASE}-${KUBE_BUILD_IMAGE_VERSION}\"\n  DOCKER_MOUNT_ARGS=(--volumes-from \"${KUBE_DATA_CONTAINER_NAME}\")\n  LOCAL_OUTPUT_BUILD_CONTEXT=\"${LOCAL_OUTPUT_IMAGE_STAGING}/${KUBE_BUILD_IMAGE}\"\n\n  kube::version::get_version_vars\n  kube::version::save_version_vars \"${KUBE_ROOT}/.dockerized-kube-version-defs\"\n\n  # Without this, the user's umask can leak through.\n  umask 0022\n}\n\n# ---------------------------------------------------------------------------\n# Utility functions\n\nfunction kube::build::docker_available_on_osx() {\n  if [[ -z \"${DOCKER_HOST}\" ]]; then\n    if [[ -S \"/var/run/docker.sock\" ]]; then\n      kube::log::status \"Using Docker for MacOS\"\n      return 0\n    fi\n\n    kube::log::status \"No docker host is set.\"\n    kube::log::status \"It looks like you're running Mac OS X, but Docker for Mac cannot be found.\"\n    kube::log::status \"See: https://docs.docker.com/engine/installation/mac/ for installation instructions.\"\n    return 1\n  fi\n}\n\nfunction kube::build::is_osx() {\n  [[ \"$(uname)\" == \"Darwin\" ]]\n}\n\nfunction kube::build::is_gnu_sed() {\n  [[ $(sed --version 2>&1) == *GNU* ]]\n}\n\nfunction kube::build::ensure_rsync() {\n  if [[ -z \"$(which rsync)\" ]]; then\n    kube::log::error \"Can't find 'rsync' in PATH, please fix and retry.\"\n    return 1\n  fi\n}\n\nfunction kube::build::ensure_docker_in_path() {\n  if [[ -z \"$(which docker)\" ]]; then\n    kube::log::error \"Can't find 'docker' in PATH, please fix and retry.\"\n    kube::log::error \"See https://docs.docker.com/installation/#installation for installation instructions.\"\n    return 1\n  fi\n}\n\nfunction kube::build::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  else\n      if which gnutar &>/dev/null; then\n\t  TAR=gnutar\n      fi\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\nfunction kube::build::has_docker() {\n  which docker &> /dev/null\n}\n\nfunction kube::build::has_ip() {\n  which ip &> /dev/null && ip -Version | grep 'iproute2' &> /dev/null\n}\n\n# Detect if a specific image exists\n#\n# $1 - image repo name\n# $2 - image tag\nfunction kube::build::docker_image_exists() {\n  [[ -n $1 && -n $2 ]] || {\n    kube::log::error \"Internal error. Image not specified in docker_image_exists.\"\n    exit 2\n  }\n\n  [[ $(\"${DOCKER[@]}\" images -q \"${1}:${2}\") ]]\n}\n\n# Delete all images that match a tag prefix except for the \"current\" version\n#\n# $1: The image repo/name\n# $2: The tag base. We consider any image that matches $2*\n# $3: The current image not to delete if provided\nfunction kube::build::docker_delete_old_images() {\n  # In Docker 1.12, we can replace this with\n  #    docker images \"$1\" --format \"{{.Tag}}\"\n  for tag in $(\"${DOCKER[@]}\" images \"${1}\" | tail -n +2 | awk '{print $2}') ; do\n    if [[ \"${tag}\" != \"${2}\"* ]] ; then\n      V=3 kube::log::status \"Keeping image ${1}:${tag}\"\n      continue\n    fi\n\n    if [[ -z \"${3:-}\" || \"${tag}\" != \"${3}\" ]] ; then\n      V=2 kube::log::status \"Deleting image ${1}:${tag}\"\n      \"${DOCKER[@]}\" rmi \"${1}:${tag}\" >/dev/null\n    else\n      V=3 kube::log::status \"Keeping image ${1}:${tag}\"\n    fi\n  done\n}\n\n# Stop and delete all containers that match a pattern\n#\n# $1: The base container prefix\n# $2: The current container to keep, if provided\nfunction kube::build::docker_delete_old_containers() {\n  # In Docker 1.12 we can replace this line with\n  #   docker ps -a --format=\"{{.Names}}\"\n  for container in $(\"${DOCKER[@]}\" ps -a | tail -n +2 | awk '{print $NF}') ; do\n    if [[ \"${container}\" != \"${1}\"* ]] ; then\n      V=3 kube::log::status \"Keeping container ${container}\"\n      continue\n    fi\n    if [[ -z \"${2:-}\" || \"${container}\" != \"${2}\" ]] ; then\n      V=2 kube::log::status \"Deleting container ${container}\"\n      kube::build::destroy_container \"${container}\"\n    else\n      V=3 kube::log::status \"Keeping container ${container}\"\n    fi\n  done\n}\n\n# Takes $1 and computes a short has for it. Useful for unique tag generation\nfunction kube::build::short_hash() {\n  [[ $# -eq 1 ]] || {\n    kube::log::error \"Internal error.  No data based to short_hash.\"\n    exit 2\n  }\n\n  local short_hash\n  if which md5 >/dev/null 2>&1; then\n    short_hash=$(md5 -q -s \"$1\")\n  else\n    short_hash=$(echo -n \"$1\" | md5sum)\n  fi\n  echo \"${short_hash:0:10}\"\n}\n\n# Pedantically kill, wait-on and remove a container. The -f -v options\n# to rm don't actually seem to get the job done, so force kill the\n# container, wait to ensure it's stopped, then try the remove. This is\n# a workaround for bug https://github.com/docker/docker/issues/3968.\nfunction kube::build::destroy_container() {\n  \"${DOCKER[@]}\" kill \"$1\" >/dev/null 2>&1 || true\n  if [[ $(\"${DOCKER[@]}\" version --format '{{.Server.Version}}') = 17.06.0* ]]; then\n    # Workaround https://github.com/moby/moby/issues/33948.\n    # TODO: remove when 17.06.0 is not relevant anymore\n    DOCKER_API_VERSION=v1.29 \"${DOCKER[@]}\" wait \"$1\" >/dev/null 2>&1 || true\n  else\n    \"${DOCKER[@]}\" wait \"$1\" >/dev/null 2>&1 || true\n  fi\n  \"${DOCKER[@]}\" rm -f -v \"$1\" >/dev/null 2>&1 || true\n}\n\n# ---------------------------------------------------------------------------\n# Building\n\n\nfunction kube::build::clean() {\n  if kube::build::has_docker ; then\n    kube::build::docker_delete_old_containers \"${KUBE_BUILD_CONTAINER_NAME_BASE}\"\n    kube::build::docker_delete_old_containers \"${KUBE_RSYNC_CONTAINER_NAME_BASE}\"\n    kube::build::docker_delete_old_containers \"${KUBE_DATA_CONTAINER_NAME_BASE}\"\n    kube::build::docker_delete_old_images \"${KUBE_BUILD_IMAGE_REPO}\" \"${KUBE_BUILD_IMAGE_TAG_BASE}\"\n\n    V=2 kube::log::status \"Cleaning all untagged docker images\"\n    \"${DOCKER[@]}\" rmi \"$(\"${DOCKER[@]}\" images -q --filter 'dangling=true')\" 2> /dev/null || true\n  fi\n\n  if [[ -d \"${LOCAL_OUTPUT_ROOT}\" ]]; then\n    kube::log::status \"Removing _output directory\"\n    rm -rf \"${LOCAL_OUTPUT_ROOT}\"\n  fi\n}\n\n# Set up the context directory for the kube-build image and build it.\nfunction kube::build::build_image() {\n  mkdir -p \"${LOCAL_OUTPUT_BUILD_CONTEXT}\"\n  # Make sure the context directory owned by the right user for syncing sources to container.\n  chown -R \"${USER_ID}\":\"${GROUP_ID}\" \"${LOCAL_OUTPUT_BUILD_CONTEXT}\"\n\n  cp /etc/localtime \"${LOCAL_OUTPUT_BUILD_CONTEXT}/\"\n  chmod u+w \"${LOCAL_OUTPUT_BUILD_CONTEXT}/localtime\"\n\n  cp \"${KUBE_ROOT}/build/build-image/Dockerfile\" \"${LOCAL_OUTPUT_BUILD_CONTEXT}/Dockerfile\"\n  cp \"${KUBE_ROOT}/build/build-image/rsyncd.sh\" \"${LOCAL_OUTPUT_BUILD_CONTEXT}/\"\n  dd if=/dev/urandom bs=512 count=1 2>/dev/null | LC_ALL=C tr -dc 'A-Za-z0-9' | dd bs=32 count=1 2>/dev/null > \"${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password\"\n  chmod go= \"${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password\"\n\n  kube::build::docker_build \"${KUBE_BUILD_IMAGE}\" \"${LOCAL_OUTPUT_BUILD_CONTEXT}\" 'false' \"--build-arg=KUBE_BUILD_IMAGE_CROSS_TAG=${KUBE_BUILD_IMAGE_CROSS_TAG} --build-arg=KUBE_BASE_IMAGE_REGISTRY=${KUBE_BASE_IMAGE_REGISTRY}\"\n\n  # Clean up old versions of everything\n  kube::build::docker_delete_old_containers \"${KUBE_BUILD_CONTAINER_NAME_BASE}\" \"${KUBE_BUILD_CONTAINER_NAME}\"\n  kube::build::docker_delete_old_containers \"${KUBE_RSYNC_CONTAINER_NAME_BASE}\" \"${KUBE_RSYNC_CONTAINER_NAME}\"\n  kube::build::docker_delete_old_containers \"${KUBE_DATA_CONTAINER_NAME_BASE}\" \"${KUBE_DATA_CONTAINER_NAME}\"\n  kube::build::docker_delete_old_images \"${KUBE_BUILD_IMAGE_REPO}\" \"${KUBE_BUILD_IMAGE_TAG_BASE}\" \"${KUBE_BUILD_IMAGE_TAG}\"\n\n  kube::build::ensure_data_container\n  kube::build::sync_to_container\n}\n\n# Build a docker image from a Dockerfile.\n# $1 is the name of the image to build\n# $2 is the location of the \"context\" directory, with the Dockerfile at the root.\n# $3 is the value to set the --pull flag for docker build; true by default\n# $4 is the set of --build-args for docker.\nfunction kube::build::docker_build() {\n  local -r image=$1\n  local -r context_dir=$2\n  local -r pull=\"${3:-true}\"\n  local build_args\n  IFS=\" \" read -r -a build_args <<< \"$4\"\n  readonly build_args\n  local -ra build_cmd=(\"${DOCKER[@]}\" buildx build --load -t \"${image}\" \"--pull=${pull}\" \"${build_args[@]}\" \"${context_dir}\")\n\n  kube::log::status \"Building Docker image ${image}\"\n  local docker_output\n  docker_output=$(DOCKER_CLI_EXPERIMENTAL=enabled \"${build_cmd[@]}\" 2>&1) || {\n    cat <<EOF >&2\n+++ Docker build command failed for ${image}\n\n${docker_output}\n\nTo retry manually, run:\n\nDOCKER_CLI_EXPERIMENTAL=enabled ${build_cmd[*]}\n\nEOF\n    return 1\n  }\n}\n\nfunction kube::build::ensure_data_container() {\n  # If the data container exists AND exited successfully, we can use it.\n  # Otherwise nuke it and start over.\n  local ret=0\n  local code=0\n\n  code=$(docker inspect \\\n      -f '{{.State.ExitCode}}' \\\n      \"${KUBE_DATA_CONTAINER_NAME}\" 2>/dev/null) || ret=$?\n  if [[ \"${ret}\" == 0 && \"${code}\" != 0 ]]; then\n    kube::build::destroy_container \"${KUBE_DATA_CONTAINER_NAME}\"\n    ret=1\n  fi\n  if [[ \"${ret}\" != 0 ]]; then\n    kube::log::status \"Creating data container ${KUBE_DATA_CONTAINER_NAME}\"\n    # We have to ensure the directory exists, or else the docker run will\n    # create it as root.\n    mkdir -p \"${LOCAL_OUTPUT_GOPATH}\"\n    # We want this to run as root to be able to chown, so non-root users can\n    # later use the result as a data container.  This run both creates the data\n    # container and chowns the GOPATH.\n    #\n    # The data container creates volumes for all of the directories that store\n    # intermediates for the Go build. This enables incremental builds across\n    # Docker sessions. The *_cgo paths are re-compiled versions of the go std\n    # libraries for true static building.\n    local -ra docker_cmd=(\n      \"${DOCKER[@]}\" run\n      --volume \"${REMOTE_ROOT}\"   # white-out the whole output dir\n      --volume /usr/local/go/pkg/linux_386_cgo\n      --volume /usr/local/go/pkg/linux_amd64_cgo\n      --volume /usr/local/go/pkg/linux_arm_cgo\n      --volume /usr/local/go/pkg/linux_arm64_cgo\n      --volume /usr/local/go/pkg/linux_ppc64le_cgo\n      --volume /usr/local/go/pkg/darwin_amd64_cgo\n      --volume /usr/local/go/pkg/darwin_386_cgo\n      --volume /usr/local/go/pkg/windows_amd64_cgo\n      --volume /usr/local/go/pkg/windows_386_cgo\n      --name \"${KUBE_DATA_CONTAINER_NAME}\"\n      --hostname \"${HOSTNAME}\"\n      \"${KUBE_BUILD_IMAGE}\"\n      chown -R \"${USER_ID}\":\"${GROUP_ID}\"\n        \"${REMOTE_ROOT}\"\n        /usr/local/go/pkg/\n    )\n    \"${docker_cmd[@]}\"\n  fi\n}\n\n# Run a command in the kube-build image.  This assumes that the image has\n# already been built.\nfunction kube::build::run_build_command() {\n  kube::log::status \"Running build command...\"\n  kube::build::run_build_command_ex \"${KUBE_BUILD_CONTAINER_NAME}\" -- \"$@\"\n}\n\n# Run a command in the kube-build image.  This assumes that the image has\n# already been built.\n#\n# Arguments are in the form of\n#  <container name> <extra docker args> -- <command>\nfunction kube::build::run_build_command_ex() {\n  [[ $# != 0 ]] || { echo \"Invalid input - please specify a container name.\" >&2; return 4; }\n  local container_name=\"${1}\"\n  shift\n\n  local -a docker_run_opts=(\n    \"--name=${container_name}\"\n    \"--user=$(id -u):$(id -g)\"\n    \"--hostname=${HOSTNAME}\"\n    \"${DOCKER_MOUNT_ARGS[@]}\"\n  )\n\n  local detach=false\n\n  [[ $# != 0 ]] || { echo \"Invalid input - please specify docker arguments followed by --.\" >&2; return 4; }\n  # Everything before \"--\" is an arg to docker\n  until [ -z \"${1-}\" ] ; do\n    if [[ \"$1\" == \"--\" ]]; then\n      shift\n      break\n    fi\n    docker_run_opts+=(\"$1\")\n    if [[ \"$1\" == \"-d\" || \"$1\" == \"--detach\" ]] ; then\n      detach=true\n    fi\n    shift\n  done\n\n  # Everything after \"--\" is the command to run\n  [[ $# != 0 ]] || { echo \"Invalid input - please specify a command to run.\" >&2; return 4; }\n  local -a cmd=()\n  until [ -z \"${1-}\" ] ; do\n    cmd+=(\"$1\")\n    shift\n  done\n\n  docker_run_opts+=(\n    --env \"KUBE_FASTBUILD=${KUBE_FASTBUILD:-false}\"\n    --env \"KUBE_BUILDER_OS=${OSTYPE:-notdetected}\"\n    --env \"KUBE_VERBOSE=${KUBE_VERBOSE}\"\n    --env \"KUBE_BUILD_WITH_COVERAGE=${KUBE_BUILD_WITH_COVERAGE:-}\"\n    --env \"KUBE_BUILD_PLATFORMS=${KUBE_BUILD_PLATFORMS:-}\"\n    --env \"GOFLAGS=${GOFLAGS:-}\"\n    --env \"GOGCFLAGS=${GOGCFLAGS:-}\"\n    --env \"SOURCE_DATE_EPOCH=${SOURCE_DATE_EPOCH:-}\"\n  )\n\n  # use GOLDFLAGS only if it is set explicitly.\n  if [[ -v GOLDFLAGS ]]; then\n    docker_run_opts+=(\n      --env \"GOLDFLAGS=${GOLDFLAGS:-}\"\n    )\n  fi\n\n  if [[ -n \"${DOCKER_CGROUP_PARENT:-}\" ]]; then\n    kube::log::status \"Using ${DOCKER_CGROUP_PARENT} as container cgroup parent\"\n    docker_run_opts+=(--cgroup-parent \"${DOCKER_CGROUP_PARENT}\")\n  fi\n\n  # If we have stdin we can run interactive.  This allows things like 'shell.sh'\n  # to work.  However, if we run this way and don't have stdin, then it ends up\n  # running in a daemon-ish mode.  So if we don't have a stdin, we explicitly\n  # attach stderr/stdout but don't bother asking for a tty.\n  if [[ -t 0 ]]; then\n    docker_run_opts+=(--interactive --tty)\n  elif [[ \"${detach}\" == false ]]; then\n    docker_run_opts+=(\"--attach=stdout\" \"--attach=stderr\")\n  fi\n\n  local -ra docker_cmd=(\n    \"${DOCKER[@]}\" run \"${docker_run_opts[@]}\" \"${KUBE_BUILD_IMAGE}\")\n\n  # Clean up container from any previous run\n  kube::build::destroy_container \"${container_name}\"\n  \"${docker_cmd[@]}\" \"${cmd[@]}\"\n  if [[ \"${detach}\" == false ]]; then\n    kube::build::destroy_container \"${container_name}\"\n  fi\n}\n\nfunction kube::build::rsync_probe {\n  # Wait unil rsync is up and running.\n  local tries=20\n  while (( tries > 0 )) ; do\n    if rsync \"rsync://k8s@${1}:${2}/\" \\\n         --password-file=\"${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password\" \\\n         &> /dev/null ; then\n      return 0\n    fi\n    tries=$(( tries - 1))\n    sleep 0.1\n  done\n\n  return 1\n}\n\n# Start up the rsync container in the background. This should be explicitly\n# stopped with kube::build::stop_rsyncd_container.\n#\n# This will set the global var KUBE_RSYNC_ADDR to the effective port that the\n# rsync daemon can be reached out.\nfunction kube::build::start_rsyncd_container() {\n  IPTOOL=ifconfig\n  if kube::build::has_ip ; then\n    IPTOOL=\"ip address\"\n  fi\n  kube::build::stop_rsyncd_container\n  V=3 kube::log::status \"Starting rsyncd container\"\n  kube::build::run_build_command_ex \\\n    \"${KUBE_RSYNC_CONTAINER_NAME}\" -p 127.0.0.1:\"${KUBE_RSYNC_PORT}\":\"${KUBE_CONTAINER_RSYNC_PORT}\" -d \\\n    -e ALLOW_HOST=\"$(${IPTOOL} | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1')\" \\\n    -- /rsyncd.sh >/dev/null\n\n  local mapped_port\n  if ! mapped_port=$(\"${DOCKER[@]}\" port \"${KUBE_RSYNC_CONTAINER_NAME}\" ${KUBE_CONTAINER_RSYNC_PORT} 2> /dev/null | cut -d: -f 2) ; then\n    kube::log::error \"Could not get effective rsync port\"\n    return 1\n  fi\n\n  local container_ip\n  container_ip=$(\"${DOCKER[@]}\" inspect --format '{{ .NetworkSettings.IPAddress }}' \"${KUBE_RSYNC_CONTAINER_NAME}\")\n\n  # Sometimes we can reach rsync through localhost and a NAT'd port.  Other\n  # times (when we are running in another docker container on the Jenkins\n  # machines) we have to talk directly to the container IP.  There is no one\n  # strategy that works in all cases so we test to figure out which situation we\n  # are in.\n  if kube::build::rsync_probe 127.0.0.1 \"${mapped_port}\"; then\n    KUBE_RSYNC_ADDR=\"127.0.0.1:${mapped_port}\"\n    return 0\n  elif kube::build::rsync_probe \"${container_ip}\" ${KUBE_CONTAINER_RSYNC_PORT}; then\n    KUBE_RSYNC_ADDR=\"${container_ip}:${KUBE_CONTAINER_RSYNC_PORT}\"\n    return 0\n  fi\n\n  kube::log::error \"Could not connect to rsync container.\"\n  return 1\n}\n\nfunction kube::build::stop_rsyncd_container() {\n  V=3 kube::log::status \"Stopping any currently running rsyncd container\"\n  unset KUBE_RSYNC_ADDR\n  kube::build::destroy_container \"${KUBE_RSYNC_CONTAINER_NAME}\"\n}\n\nfunction kube::build::rsync {\n  local -a rsync_opts=(\n    --archive\n    \"--password-file=${LOCAL_OUTPUT_BUILD_CONTEXT}/rsyncd.password\"\n  )\n  if (( KUBE_VERBOSE >= 6 )); then\n    rsync_opts+=(\"-iv\")\n  fi\n  if (( KUBE_RSYNC_COMPRESS > 0 )); then\n     rsync_opts+=(\"--compress-level=${KUBE_RSYNC_COMPRESS}\")\n  fi\n  V=3 kube::log::status \"Running rsync\"\n  rsync \"${rsync_opts[@]}\" \"$@\"\n}\n\n# This will launch rsyncd in a container and then sync the source tree to the\n# container over the local network.\nfunction kube::build::sync_to_container() {\n  kube::log::status \"Syncing sources to container\"\n\n  kube::build::start_rsyncd_container\n\n  # rsync filters are a bit confusing.  Here we are syncing everything except\n  # output only directories and things that are not necessary like the git\n  # directory and generated files. The '- /' filter prevents rsync\n  # from trying to set the uid/gid/perms on the root of the sync tree.\n  # As an exception, we need to sync generated files in staging/, because\n  # they will not be re-generated by 'make'. Note that the 'H' filtered files\n  # are hidden from rsync so they will be deleted in the target container if\n  # they exist. This will allow them to be re-created in the container if\n  # necessary.\n  kube::build::rsync \\\n    --delete \\\n    --filter='H /.git' \\\n    --filter='- /.make/' \\\n    --filter='- /_tmp/' \\\n    --filter='- /_output/' \\\n    --filter='- /' \\\n    --filter='H zz_generated.*' \\\n    --filter='H generated.proto' \\\n    \"${KUBE_ROOT}/\" \"rsync://k8s@${KUBE_RSYNC_ADDR}/k8s/\"\n\n  kube::build::stop_rsyncd_container\n}\n\n# Copy all build results back out.\nfunction kube::build::copy_output() {\n  kube::log::status \"Syncing out of container\"\n\n  kube::build::start_rsyncd_container\n\n  # The filter syntax for rsync is a little obscure. It filters on files and\n  # directories.  If you don't go in to a directory you won't find any files\n  # there.  Rules are evaluated in order.  The last two rules are a little\n  # magic. '+ */' says to go in to every directory and '- /**' says to ignore\n  # any file or directory that isn't already specifically allowed.\n  #\n  # We are looking to copy out all of the built binaries along with various\n  # generated files.\n  kube::build::rsync \\\n    --prune-empty-dirs \\\n    --filter='- /_temp/' \\\n    --filter='+ /vendor/' \\\n    --filter='+ /staging/***/Godeps/**' \\\n    --filter='+ /_output/dockerized/bin/**' \\\n    --filter='+ zz_generated.*' \\\n    --filter='+ generated.proto' \\\n    --filter='+ *.pb.go' \\\n    --filter='+ types.go' \\\n    --filter='+ */' \\\n    --filter='- /**' \\\n    \"rsync://k8s@${KUBE_RSYNC_ADDR}/k8s/\" \"${KUBE_ROOT}\"\n\n  kube::build::stop_rsyncd_container\n}\n", "num_lines": 700}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Copies any built binaries (and other generated files) out of the Docker build container.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\n\nkube::build::verify_prereqs\nkube::build::copy_output\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Build the docker image necessary for building Kubernetes\n#\n# This script will package the parts of the repo that we need to build\n# Kubernetes into a tar file and put it in the right place in the output\n# directory.  It will then copy over the Dockerfile and build the kube-build\n# image.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=\"$(dirname \"${BASH_SOURCE[0]}\")/..\"\nsource \"${KUBE_ROOT}/build/common.sh\"\n\nkube::build::verify_prereqs\nkube::build::build_image\n", "num_lines": 32}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Clean out the output directory on the docker host.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\n\nkube::build::verify_prereqs false\nkube::build::clean\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Complete the release with the standard env\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\nsource \"${KUBE_ROOT}/build/lib/release.sh\"\n\nkube::build::ensure_tar\nkube::version::get_version_vars\nkube::release::package_tarballs\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Build Kubernetes release images. This will build the server target binaries,\n# and create wrap them in Docker images, see `make release` for full releases\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\nsource \"${KUBE_ROOT}/build/lib/release.sh\"\n\nCMD_TARGETS=\"${KUBE_SERVER_IMAGE_TARGETS[*]}\"\nif [[ \"${KUBE_BUILD_CONFORMANCE}\" =~ [yY] ]]; then\n    CMD_TARGETS=\"${CMD_TARGETS} ${KUBE_CONFORMANCE_IMAGE_TARGETS[*]}\"\nfi\n# include extra WHAT if specified so you can build docker images + binaries\n# in one call with a single pass of syncing to the container + generating code\nif [[ -n \"${KUBE_EXTRA_WHAT:-}\" ]]; then\n    CMD_TARGETS=\"${CMD_TARGETS} ${KUBE_EXTRA_WHAT}\"\nfi\n\nkube::build::verify_prereqs\nkube::build::build_image\nkube::build::run_build_command make all WHAT=\"${CMD_TARGETS}\" KUBE_BUILD_PLATFORMS=\"${KUBE_SERVER_PLATFORMS[*]}\"\n\nkube::build::copy_output\n\nkube::release::build_server_images\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Complete the release with the standard env\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# Check and error if not \"in-a-container\"\nif [[ ! -f /.dockerenv ]]; then\n  echo\n  echo \"'make release-in-a-container' can only be used from a docker container.\"\n  echo\n  exit 1\nfi\n\n# Other dependencies: Your container should contain docker\nif ! type -p docker >/dev/null 2>&1; then\n  echo\n  echo \"'make release-in-a-container' requires a container with\" \\\n       \"docker installed.\"\n  echo\n  exit 1\nfi\n\n\n# First run make cross-in-a-container\nmake cross-in-a-container\n\n# at the moment only make test is supported.\nif [[ $KUBE_RELEASE_RUN_TESTS =~ ^[yY]$ ]]; then\n  make test\nfi\n\n\"${KUBE_ROOT}/build/package-tarballs.sh\"\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Build a Kubernetes release.  This will build the binaries, create the Docker\n# images and other build artifacts.\n#\n# For pushing these artifacts publicly to Google Cloud Storage or to a registry\n# please refer to the kubernetes/release repo at\n# https://github.com/kubernetes/release.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\nsource \"${KUBE_ROOT}/build/lib/release.sh\"\n\nKUBE_RELEASE_RUN_TESTS=${KUBE_RELEASE_RUN_TESTS-y}\n\nkube::build::verify_prereqs\nkube::build::build_image\nkube::build::run_build_command make cross\n\nif [[ $KUBE_RELEASE_RUN_TESTS =~ ^[yY]$ ]]; then\n  kube::build::run_build_command make test\n  kube::build::run_build_command make test-integration\nfi\n\nkube::build::copy_output\n\nkube::release::package_tarballs\n", "num_lines": 46}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run a command in the docker build container.  Typically this will be one of\n# the commands in `hack/`.  When running in the build container the user is sure\n# to have a consistent reproducible build environment.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"$KUBE_ROOT/build/common.sh\"\n\nKUBE_RUN_COPY_OUTPUT=\"${KUBE_RUN_COPY_OUTPUT:-y}\"\n\nkube::build::verify_prereqs\nkube::build::build_image\n\nif [[ ${KUBE_RUN_COPY_OUTPUT} =~ ^[yY]$ ]]; then\n  kube::log::status \"Output from this container will be rsynced out upon completion. Set KUBE_RUN_COPY_OUTPUT=n to disable.\"\nelse\n  kube::log::status \"Output from this container will NOT be rsynced out upon completion. Set KUBE_RUN_COPY_OUTPUT=y to enable.\"\nfi\n\nkube::build::run_build_command \"$@\"\n\nif [[ ${KUBE_RUN_COPY_OUTPUT} =~ ^[yY]$ ]]; then\n  kube::build::copy_output\nfi\n", "num_lines": 44}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run a bash script in the Docker build image.\n#\n# This container will have a snapshot of the current sources.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/build/common.sh\"\n\nKUBE_RUN_COPY_OUTPUT=\"${KUBE_RUN_COPY_OUTPUT:-n}\" \"${KUBE_ROOT}/build/run.sh\" bash \"$@\"\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Common utility functions for build scripts\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nfunction kube::release::semantic_version() {\n  # This takes:\n  # Client Version: version.Info{Major:\"1\", Minor:\"1+\", GitVersion:\"v1.1.0-alpha.0.2328+3c0a05de4a38e3\", GitCommit:\"3c0a05de4a38e355d147dbfb4d85bad6d2d73bb9\", GitTreeState:\"clean\"}\n  # and spits back the GitVersion piece in a way that is somewhat\n  # resilient to the other fields changing (we hope)\n  \"${KUBE_ROOT}/cluster/kubectl.sh\" version --client | sed \"s/, */\\\\\n/g\" | grep -E \"^GitVersion:\" | cut -f2 -d: | cut -f2 -d\\\"\n}\n\nfunction kube::release::semantic_image_tag_version() {\n    printf \"%s\" \"$(kube::release::semantic_version)\" | tr + _\n}\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script will set up and run rsyncd to allow data to move into and out of\n# our dockerized build system.  This is used for syncing sources and changes of\n# sources into the docker-build-container.  It is also used to transfer built binaries\n# and generated files back out.\n#\n# When run as root (rare) it'll preserve the file ids as sent from the client.\n# Usually it'll be run as non-dockerized UID/GID and end up translating all file\n# ownership to that.\n\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# The directory that gets sync'd\nVOLUME=${HOME}\n\n# Assume that this is running in Docker on a bridge.  Allow connections from\n# anything on the local subnet.\nALLOW=$(ip route | awk  '/^default via/ { reg = \"^[0-9./]+ dev \"$5 } ; $0 ~ reg { print $1 }')\n\nCONFDIR=\"/tmp/rsync.k8s\"\nPIDFILE=\"${CONFDIR}/rsyncd.pid\"\nCONFFILE=\"${CONFDIR}/rsyncd.conf\"\nSECRETS=\"${CONFDIR}/rsyncd.secrets\"\n\nmkdir -p \"${CONFDIR}\"\n\nif [[ -f \"${PIDFILE}\" ]]; then\n  PID=$(cat \"${PIDFILE}\")\n  echo \"Cleaning up old PID file: ${PIDFILE}\"\n  kill \"${PID}\" &> /dev/null || true\n  rm \"${PIDFILE}\"\nfi\n\nPASSWORD=$(</rsyncd.password)\n\ncat <<EOF >\"${SECRETS}\"\nk8s:${PASSWORD}\nEOF\nchmod go= \"${SECRETS}\"\n\nUSER_CONFIG=\nif [[ \"$(id -u)\" == \"0\" ]]; then\n  USER_CONFIG=\"  uid = 0\"$'\\n'\"  gid = 0\"\nfi\n\ncat <<EOF >\"${CONFFILE}\"\npid file = ${PIDFILE}\nuse chroot = no\nlog file = /dev/stdout\nreverse lookup = no\nmunge symlinks = no\nport = 8730\n[k8s]\n  numeric ids = true\n  $USER_CONFIG\n  hosts deny = *\n  hosts allow = ${ALLOW} ${ALLOW_HOST-}\n  auth users = k8s\n  secrets file = ${SECRETS}\n  read only = false\n  path = ${VOLUME}\n  filter = - /.make/ - /_tmp/\nEOF\n\nexec /usr/bin/rsync --no-detach --daemon --config=\"${CONFFILE}\" \"$@\"\n", "num_lines": 84}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file creates release artifacts (tar files, container images) that are\n# ready to distribute to install or distribute to end users.\n\n###############################################################################\n# Most of the ::release:: namespace functions have been moved to\n# github.com/kubernetes/release.  Have a look in that repo and specifically in\n# lib/releaselib.sh for ::release::-related functionality.\n###############################################################################\n\n# This is where the final release artifacts are created locally\nreadonly RELEASE_STAGE=\"${LOCAL_OUTPUT_ROOT}/release-stage\"\nreadonly RELEASE_TARS=\"${LOCAL_OUTPUT_ROOT}/release-tars\"\nreadonly RELEASE_IMAGES=\"${LOCAL_OUTPUT_ROOT}/release-images\"\n\nKUBE_BUILD_CONFORMANCE=${KUBE_BUILD_CONFORMANCE:-n}\nKUBE_BUILD_PULL_LATEST_IMAGES=${KUBE_BUILD_PULL_LATEST_IMAGES:-y}\n\n# Validate a ci version\n#\n# Globals:\n#   None\n# Arguments:\n#   version\n# Returns:\n#   If version is a valid ci version\n# Sets:                    (e.g. for '1.2.3-alpha.4.56+abcdef12345678')\n#   VERSION_MAJOR          (e.g. '1')\n#   VERSION_MINOR          (e.g. '2')\n#   VERSION_PATCH          (e.g. '3')\n#   VERSION_PRERELEASE     (e.g. 'alpha')\n#   VERSION_PRERELEASE_REV (e.g. '4')\n#   VERSION_BUILD_INFO     (e.g. '.56+abcdef12345678')\n#   VERSION_COMMITS        (e.g. '56')\nfunction kube::release::parse_and_validate_ci_version() {\n  # Accept things like \"v1.2.3-alpha.4.56+abcdef12345678\" or \"v1.2.3-beta.4\"\n  local -r version_regex=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)-([a-zA-Z0-9]+)\\\\.(0|[1-9][0-9]*)(\\\\.(0|[1-9][0-9]*)\\\\+[0-9a-f]{7,40})?$\"\n  local -r version=\"${1-}\"\n  [[ \"${version}\" =~ ${version_regex} ]] || {\n    kube::log::error \"Invalid ci version: '${version}', must match regex ${version_regex}\"\n    return 1\n  }\n\n  # The VERSION variables are used when this file is sourced, hence\n  # the shellcheck SC2034 'appears unused' warning is to be ignored.\n\n  # shellcheck disable=SC2034\n  VERSION_MAJOR=\"${BASH_REMATCH[1]}\"\n  # shellcheck disable=SC2034\n  VERSION_MINOR=\"${BASH_REMATCH[2]}\"\n  # shellcheck disable=SC2034\n  VERSION_PATCH=\"${BASH_REMATCH[3]}\"\n  # shellcheck disable=SC2034\n  VERSION_PRERELEASE=\"${BASH_REMATCH[4]}\"\n  # shellcheck disable=SC2034\n  VERSION_PRERELEASE_REV=\"${BASH_REMATCH[5]}\"\n  # shellcheck disable=SC2034\n  VERSION_BUILD_INFO=\"${BASH_REMATCH[6]}\"\n  # shellcheck disable=SC2034\n  VERSION_COMMITS=\"${BASH_REMATCH[7]}\"\n}\n\n# ---------------------------------------------------------------------------\n# Build final release artifacts\nfunction kube::release::clean_cruft() {\n  # Clean out cruft\n  find \"${RELEASE_STAGE}\" -name '*~' -exec rm {} \\;\n  find \"${RELEASE_STAGE}\" -name '#*#' -exec rm {} \\;\n  find \"${RELEASE_STAGE}\" -name '.DS*' -exec rm {} \\;\n}\n\nfunction kube::release::package_tarballs() {\n  # Clean out any old releases\n  rm -rf \"${RELEASE_STAGE}\" \"${RELEASE_TARS}\" \"${RELEASE_IMAGES}\"\n  mkdir -p \"${RELEASE_TARS}\"\n  kube::release::package_src_tarball &\n  kube::release::package_client_tarballs &\n  kube::release::package_kube_manifests_tarball &\n  kube::util::wait-for-jobs || { kube::log::error \"previous tarball phase failed\"; return 1; }\n\n  # _node and _server tarballs depend on _src tarball\n  kube::release::package_node_tarballs &\n  kube::release::package_server_tarballs &\n  kube::util::wait-for-jobs || { kube::log::error \"previous tarball phase failed\"; return 1; }\n\n  kube::release::package_final_tarball & # _final depends on some of the previous phases\n  kube::release::package_test_tarballs & # _test doesn't depend on anything\n  kube::util::wait-for-jobs || { kube::log::error \"previous tarball phase failed\"; return 1; }\n}\n\n# Package the source code we built, for compliance/licensing/audit/yadda.\nfunction kube::release::package_src_tarball() {\n  local -r src_tarball=\"${RELEASE_TARS}/kubernetes-src.tar.gz\"\n  kube::log::status \"Building tarball: src\"\n  if [[ \"${KUBE_GIT_TREE_STATE-}\" = 'clean' ]]; then\n    git archive -o \"${src_tarball}\" HEAD\n  else\n    find \"${KUBE_ROOT}\" -mindepth 1 -maxdepth 1 \\\n      ! \\( \\\n        \\( -path \"${KUBE_ROOT}\"/_\\*       -o \\\n           -path \"${KUBE_ROOT}\"/.git\\*    -o \\\n           -path \"${KUBE_ROOT}\"/.config\\* -o \\\n           -path \"${KUBE_ROOT}\"/.gsutil\\*    \\\n        \\) -prune \\\n      \\) -print0 \\\n    | \"${TAR}\" czf \"${src_tarball}\" --transform \"s|${KUBE_ROOT#/*}|kubernetes|\" --null -T -\n  fi\n}\n\n# Package up all of the cross compiled clients. Over time this should grow into\n# a full SDK\nfunction kube::release::package_client_tarballs() {\n  # Find all of the built client binaries\n  local long_platforms=(\"${LOCAL_OUTPUT_BINPATH}\"/*/*)\n  if [[ -n ${KUBE_BUILD_PLATFORMS-} ]]; then\n    read -ra long_platforms <<< \"${KUBE_BUILD_PLATFORMS}\"\n  fi\n\n  for platform_long in \"${long_platforms[@]}\"; do\n    local platform\n    local platform_tag\n    platform=${platform_long##${LOCAL_OUTPUT_BINPATH}/} # Strip LOCAL_OUTPUT_BINPATH\n    platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n    kube::log::status \"Starting tarball: client $platform_tag\"\n\n    (\n      local release_stage=\"${RELEASE_STAGE}/client/${platform_tag}/kubernetes\"\n      rm -rf \"${release_stage}\"\n      mkdir -p \"${release_stage}/client/bin\"\n\n      local client_bins=(\"${KUBE_CLIENT_BINARIES[@]}\")\n      if [[ \"${platform%/*}\" = 'windows' ]]; then\n        client_bins=(\"${KUBE_CLIENT_BINARIES_WIN[@]}\")\n      fi\n\n      # This fancy expression will expand to prepend a path\n      # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n      # client_bins array.\n      cp \"${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n        \"${release_stage}/client/bin/\"\n\n      kube::release::clean_cruft\n\n      local package_name=\"${RELEASE_TARS}/kubernetes-client-${platform_tag}.tar.gz\"\n      kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n    ) &\n  done\n\n  kube::log::status \"Waiting on tarballs\"\n  kube::util::wait-for-jobs || { kube::log::error \"client tarball creation failed\"; exit 1; }\n}\n\n# Package up all of the node binaries\nfunction kube::release::package_node_tarballs() {\n  local platform\n  for platform in \"${KUBE_NODE_PLATFORMS[@]}\"; do\n    local platform_tag\n    local arch\n    platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n    arch=$(basename \"${platform}\")\n    kube::log::status \"Building tarball: node $platform_tag\"\n\n    local release_stage=\"${RELEASE_STAGE}/node/${platform_tag}/kubernetes\"\n    rm -rf \"${release_stage}\"\n    mkdir -p \"${release_stage}/node/bin\"\n\n    local node_bins=(\"${KUBE_NODE_BINARIES[@]}\")\n    if [[ \"${platform%/*}\" = 'windows' ]]; then\n      node_bins=(\"${KUBE_NODE_BINARIES_WIN[@]}\")\n    fi\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # node_bins array.\n    cp \"${node_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/node/bin/\"\n\n    # TODO: Docker images here\n    # kube::release::create_docker_images_for_server \"${release_stage}/server/bin\" \"${arch}\"\n\n    # Include the client binaries here too as they are useful debugging tools.\n    local client_bins=(\"${KUBE_CLIENT_BINARIES[@]}\")\n    if [[ \"${platform%/*}\" = 'windows' ]]; then\n      client_bins=(\"${KUBE_CLIENT_BINARIES_WIN[@]}\")\n    fi\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # client_bins array.\n    cp \"${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/node/bin/\"\n\n    cp -R \"${KUBE_ROOT}/LICENSES\" \"${release_stage}/\"\n\n    cp \"${RELEASE_TARS}/kubernetes-src.tar.gz\" \"${release_stage}/\"\n\n    kube::release::clean_cruft\n\n    local package_name=\"${RELEASE_TARS}/kubernetes-node-${platform_tag}.tar.gz\"\n    kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n  done\n}\n\n# Package up all of the server binaries in docker images\nfunction kube::release::build_server_images() {\n  # Clean out any old images\n  rm -rf \"${RELEASE_IMAGES}\"\n  local platform\n  for platform in \"${KUBE_SERVER_PLATFORMS[@]}\"; do\n    local platform_tag\n    local arch\n    platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n    arch=$(basename \"${platform}\")\n    kube::log::status \"Building images: $platform_tag\"\n\n    local release_stage\n    release_stage=\"${RELEASE_STAGE}/server/${platform_tag}/kubernetes\"\n    rm -rf \"${release_stage}\"\n    mkdir -p \"${release_stage}/server/bin\"\n\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # KUBE_SERVER_IMAGE_BINARIES array.\n    cp \"${KUBE_SERVER_IMAGE_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/server/bin/\"\n\n    kube::release::create_docker_images_for_server \"${release_stage}/server/bin\" \"${arch}\"\n  done\n}\n\n# Package up all of the server binaries\nfunction kube::release::package_server_tarballs() {\n  kube::release::build_server_images\n  local platform\n  for platform in \"${KUBE_SERVER_PLATFORMS[@]}\"; do\n    local platform_tag\n    local arch\n    platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n    arch=$(basename \"${platform}\")\n    kube::log::status \"Building tarball: server $platform_tag\"\n\n    # NOTE: this directory was setup in kube::release::build_server_images\n    local release_stage\n    release_stage=\"${RELEASE_STAGE}/server/${platform_tag}/kubernetes\"\n    mkdir -p \"${release_stage}/addons\"\n\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # KUBE_SERVER_BINARIES array.\n    cp \"${KUBE_SERVER_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/server/bin/\"\n\n    # Include the client binaries here too as they are useful debugging tools.\n    local client_bins\n    client_bins=(\"${KUBE_CLIENT_BINARIES[@]}\")\n    if [[ \"${platform%/*}\" = 'windows' ]]; then\n      client_bins=(\"${KUBE_CLIENT_BINARIES_WIN[@]}\")\n    fi\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # client_bins array.\n    cp \"${client_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/server/bin/\"\n\n    cp -R \"${KUBE_ROOT}/LICENSES\" \"${release_stage}/\"\n\n    cp \"${RELEASE_TARS}/kubernetes-src.tar.gz\" \"${release_stage}/\"\n\n    kube::release::clean_cruft\n\n    local package_name\n    package_name=\"${RELEASE_TARS}/kubernetes-server-${platform_tag}.tar.gz\"\n    kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n  done\n}\n\nfunction kube::release::md5() {\n  if which md5 >/dev/null 2>&1; then\n    md5 -q \"$1\"\n  else\n    md5sum \"$1\" | awk '{ print $1 }'\n  fi\n}\n\nfunction kube::release::sha1() {\n  if which sha1sum >/dev/null 2>&1; then\n    sha1sum \"$1\" | awk '{ print $1 }'\n  else\n    shasum -a1 \"$1\" | awk '{ print $1 }'\n  fi\n}\n\nfunction kube::release::build_conformance_image() {\n  local -r arch=\"$1\"\n  local -r registry=\"$2\"\n  local -r version=\"$3\"\n  local -r save_dir=\"${4-}\"\n  kube::log::status \"Building conformance image for arch: ${arch}\"\n  ARCH=\"${arch}\" REGISTRY=\"${registry}\" VERSION=\"${version}\" \\\n    make -C cluster/images/conformance/ build >/dev/null\n\n  local conformance_tag\n  conformance_tag=\"${registry}/conformance-${arch}:${version}\"\n  if [[ -n \"${save_dir}\" ]]; then\n    \"${DOCKER[@]}\" save \"${conformance_tag}\" > \"${save_dir}/conformance-${arch}.tar\"\n  fi\n  kube::log::status \"Deleting conformance image ${conformance_tag}\"\n  \"${DOCKER[@]}\" rmi \"${conformance_tag}\" &>/dev/null || true\n}\n\n# This builds all the release docker images (One docker image per binary)\n# Args:\n#  $1 - binary_dir, the directory to save the tared images to.\n#  $2 - arch, architecture for which we are building docker images.\nfunction kube::release::create_docker_images_for_server() {\n  # Create a sub-shell so that we don't pollute the outer environment\n  (\n    local binary_dir\n    local arch\n    local binaries\n    local images_dir\n    binary_dir=\"$1\"\n    arch=\"$2\"\n    binaries=$(kube::build::get_docker_wrapped_binaries)\n    images_dir=\"${RELEASE_IMAGES}/${arch}\"\n    mkdir -p \"${images_dir}\"\n\n    # k8s.gcr.io is the constant tag in the docker archives, this is also the default for config scripts in GKE.\n    # We can use KUBE_DOCKER_REGISTRY to include and extra registry in the docker archive.\n    # If we use KUBE_DOCKER_REGISTRY=\"k8s.gcr.io\", then the extra tag (same) is ignored, see release_docker_image_tag below.\n    local -r docker_registry=\"k8s.gcr.io\"\n    # Docker tags cannot contain '+'\n    local docker_tag=\"${KUBE_GIT_VERSION/+/_}\"\n    if [[ -z \"${docker_tag}\" ]]; then\n      kube::log::error \"git version information missing; cannot create Docker tag\"\n      return 1\n    fi\n\n    # provide `--pull` argument to `docker build` if `KUBE_BUILD_PULL_LATEST_IMAGES`\n    # is set to y or Y; otherwise try to build the image without forcefully\n    # pulling the latest base image.\n    local docker_build_opts\n    docker_build_opts=\n    if [[ \"${KUBE_BUILD_PULL_LATEST_IMAGES}\" =~ [yY] ]]; then\n        docker_build_opts='--pull'\n    fi\n\n    for wrappable in $binaries; do\n\n      local binary_name=${wrappable%%,*}\n      local base_image=${wrappable##*,}\n      local binary_file_path=\"${binary_dir}/${binary_name}\"\n      local docker_build_path=\"${binary_file_path}.dockerbuild\"\n      local docker_image_tag=\"${docker_registry}/${binary_name}-${arch}:${docker_tag}\"\n\n      local docker_file_path=\"${KUBE_ROOT}/build/server-image/Dockerfile\"\n      # If this binary has its own Dockerfile use that else use the generic Dockerfile.\n      if [[ -f \"${KUBE_ROOT}/build/server-image/${binary_name}/Dockerfile\" ]]; then\n          docker_file_path=\"${KUBE_ROOT}/build/server-image/${binary_name}/Dockerfile\"\n      fi\n\n      kube::log::status \"Starting docker build for image: ${binary_name}-${arch}\"\n      (\n        rm -rf \"${docker_build_path}\"\n        mkdir -p \"${docker_build_path}\"\n        ln \"${binary_file_path}\" \"${docker_build_path}/${binary_name}\"\n\n        local build_log=\"${docker_build_path}/build.log\"\n        if ! DOCKER_CLI_EXPERIMENTAL=enabled \"${DOCKER[@]}\" buildx build \\\n          -f \"${docker_file_path}\" \\\n          --platform linux/\"${arch}\" \\\n          --load ${docker_build_opts:+\"${docker_build_opts}\"} \\\n          -t \"${docker_image_tag}\" \\\n          --build-arg BASEIMAGE=\"${base_image}\" \\\n          --build-arg SETCAP_IMAGE=\"${KUBE_BUILD_SETCAP_IMAGE}\" \\\n          --build-arg BINARY=\"${binary_name}\" \\\n          \"${docker_build_path}\" >\"${build_log}\" 2>&1; then\n            cat \"${build_log}\"\n            exit 1\n        fi\n        rm \"${build_log}\"\n\n        # If we are building an official/alpha/beta release we want to keep\n        # docker images and tag them appropriately.\n        local -r release_docker_image_tag=\"${KUBE_DOCKER_REGISTRY-$docker_registry}/${binary_name}-${arch}:${KUBE_DOCKER_IMAGE_TAG-$docker_tag}\"\n        if [[ \"${release_docker_image_tag}\" != \"${docker_image_tag}\" ]]; then\n          kube::log::status \"Tagging docker image ${docker_image_tag} as ${release_docker_image_tag}\"\n          \"${DOCKER[@]}\" rmi \"${release_docker_image_tag}\" 2>/dev/null || true\n          \"${DOCKER[@]}\" tag \"${docker_image_tag}\" \"${release_docker_image_tag}\" 2>/dev/null\n        fi\n        \"${DOCKER[@]}\" save -o \"${binary_file_path}.tar\" \"${docker_image_tag}\" \"${release_docker_image_tag}\"\n        echo \"${docker_tag}\" > \"${binary_file_path}.docker_tag\"\n        rm -rf \"${docker_build_path}\"\n        ln \"${binary_file_path}.tar\" \"${images_dir}/\"\n\n        kube::log::status \"Deleting docker image ${docker_image_tag}\"\n        \"${DOCKER[@]}\" rmi \"${docker_image_tag}\" &>/dev/null || true\n      ) &\n    done\n\n    if [[ \"${KUBE_BUILD_CONFORMANCE}\" =~ [yY] ]]; then\n      kube::release::build_conformance_image \"${arch}\" \"${docker_registry}\" \\\n        \"${docker_tag}\" \"${images_dir}\" &\n    fi\n\n    kube::util::wait-for-jobs || { kube::log::error \"previous Docker build failed\"; return 1; }\n    kube::log::status \"Docker builds done\"\n  )\n\n}\n\n# This will pack kube-system manifests files for distros such as COS.\nfunction kube::release::package_kube_manifests_tarball() {\n  kube::log::status \"Building tarball: manifests\"\n\n  local src_dir=\"${KUBE_ROOT}/cluster/gce/manifests\"\n\n  local release_stage=\"${RELEASE_STAGE}/manifests/kubernetes\"\n  rm -rf \"${release_stage}\"\n\n  local dst_dir=\"${release_stage}/gci-trusty\"\n  mkdir -p \"${dst_dir}\"\n  cp \"${src_dir}/kube-proxy.manifest\" \"${dst_dir}/\"\n  cp \"${src_dir}/cluster-autoscaler.manifest\" \"${dst_dir}/\"\n  cp \"${src_dir}/etcd.manifest\" \"${dst_dir}\"\n  cp \"${src_dir}/kube-scheduler.manifest\" \"${dst_dir}\"\n  cp \"${src_dir}/kube-apiserver.manifest\" \"${dst_dir}\"\n  cp \"${src_dir}/konnectivity-server.yaml\" \"${dst_dir}\"\n  cp \"${src_dir}/abac-authz-policy.jsonl\" \"${dst_dir}\"\n  cp \"${src_dir}/kube-controller-manager.manifest\" \"${dst_dir}\"\n  cp \"${src_dir}/kube-addon-manager.yaml\" \"${dst_dir}\"\n  cp \"${src_dir}/glbc.manifest\" \"${dst_dir}\"\n  find \"${src_dir}\" -name 'internal-*' -exec cp {} \"${dst_dir}\" \\;\n  cp \"${KUBE_ROOT}/cluster/gce/gci/configure-helper.sh\" \"${dst_dir}/gci-configure-helper.sh\"\n  cp \"${KUBE_ROOT}/cluster/gce/gci/configure-kubeapiserver.sh\" \"${dst_dir}/configure-kubeapiserver.sh\"\n  if [[ -e \"${KUBE_ROOT}/cluster/gce/gci/gke-internal-configure-helper.sh\" ]]; then\n    cp \"${KUBE_ROOT}/cluster/gce/gci/gke-internal-configure-helper.sh\" \"${dst_dir}/\"\n  fi\n  cp \"${KUBE_ROOT}/cluster/gce/gci/health-monitor.sh\" \"${dst_dir}/health-monitor.sh\"\n  # Merge GCE-specific addons with general purpose addons.\n  for d in cluster/addons cluster/gce/addons; do\n    find \"${KUBE_ROOT}/${d}\" \\( \\( -name \\*.yaml -o -name \\*.yaml.in -o -name \\*.json \\) -a ! \\( -name \\*demo\\* \\) \\) -print0 | \"${TAR}\" c --transform \"s|${KUBE_ROOT#/*}/${d}||\" --null -T - | \"${TAR}\" x -C \"${dst_dir}\"\n  done\n\n  kube::release::clean_cruft\n\n  local package_name=\"${RELEASE_TARS}/kubernetes-manifests.tar.gz\"\n  kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n}\n\n# Builds tarballs for each test platform containing the appropriate binaries.\nfunction kube::release::package_test_platform_tarballs() {\n  local platform\n  rm -rf \"${RELEASE_STAGE}/test\"\n  # KUBE_TEST_SERVER_PLATFORMS is a subset of KUBE_TEST_PLATFORMS,\n  # so process it first.\n  for platform in \"${KUBE_TEST_SERVER_PLATFORMS[@]}\"; do\n    local platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n    local release_stage=\"${RELEASE_STAGE}/test/${platform_tag}/kubernetes\"\n    mkdir -p \"${release_stage}/test/bin\"\n    # This fancy expression will expand to prepend a path\n    # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n    # KUBE_TEST_SERVER_BINARIES array.\n    cp \"${KUBE_TEST_SERVER_BINARIES[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n      \"${release_stage}/test/bin/\"\n  done\n  for platform in \"${KUBE_TEST_PLATFORMS[@]}\"; do\n    (\n      local platform_tag=${platform/\\//-} # Replace a \"/\" for a \"-\"\n      kube::log::status \"Starting tarball: test $platform_tag\"\n      local release_stage=\"${RELEASE_STAGE}/test/${platform_tag}/kubernetes\"\n      mkdir -p \"${release_stage}/test/bin\"\n\n      local test_bins=(\"${KUBE_TEST_BINARIES[@]}\")\n      if [[ \"${platform%/*}\" = 'windows' ]]; then\n        test_bins=(\"${KUBE_TEST_BINARIES_WIN[@]}\")\n      fi\n      # This fancy expression will expand to prepend a path\n      # (${LOCAL_OUTPUT_BINPATH}/${platform}/) to every item in the\n      # test_bins array.\n      cp \"${test_bins[@]/#/${LOCAL_OUTPUT_BINPATH}/${platform}/}\" \\\n        \"${release_stage}/test/bin/\"\n\n      local package_name=\"${RELEASE_TARS}/kubernetes-test-${platform_tag}.tar.gz\"\n      kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n    ) &\n  done\n\n  kube::log::status \"Waiting on test tarballs\"\n  kube::util::wait-for-jobs || { kube::log::error \"test tarball creation failed\"; exit 1; }\n}\n\n\n# This is the stuff you need to run tests from the binary distribution.\nfunction kube::release::package_test_tarballs() {\n  kube::release::package_test_platform_tarballs\n\n  kube::log::status \"Building tarball: test portable\"\n\n  local release_stage=\"${RELEASE_STAGE}/test/kubernetes\"\n  rm -rf \"${release_stage}\"\n  mkdir -p \"${release_stage}\"\n\n  # First add test image files and other portable sources so we can create\n  # the portable test tarball.\n  mkdir -p \"${release_stage}/test/images\"\n  cp -fR \"${KUBE_ROOT}/test/images\" \"${release_stage}/test/\"\n  \"${TAR}\" c \"${KUBE_TEST_PORTABLE[@]}\" | \"${TAR}\" x -C \"${release_stage}\"\n\n  kube::release::clean_cruft\n\n  local portable_tarball_name=\"${RELEASE_TARS}/kubernetes-test-portable.tar.gz\"\n  kube::release::create_tarball \"${portable_tarball_name}\" \"${release_stage}/..\"\n}\n\n# This is all the platform-independent stuff you need to run/install kubernetes.\n# Arch-specific binaries will need to be downloaded separately (possibly by\n# using the bundled cluster/get-kube-binaries.sh script).\n# Included in this tarball:\n#   - Cluster spin up/down scripts and configs for various cloud providers\n#   - Tarballs for manifest configs that are ready to be uploaded\n#   - Examples (which may or may not still work)\n#   - The remnants of the docs/ directory\nfunction kube::release::package_final_tarball() {\n  kube::log::status \"Building tarball: final\"\n\n  # This isn't a \"full\" tarball anymore, but the release lib still expects\n  # artifacts under \"full/kubernetes/\"\n  local release_stage=\"${RELEASE_STAGE}/full/kubernetes\"\n  rm -rf \"${release_stage}\"\n  mkdir -p \"${release_stage}\"\n\n  mkdir -p \"${release_stage}/client\"\n  cat <<EOF > \"${release_stage}/client/README\"\nClient binaries are no longer included in the Kubernetes final tarball.\n\nRun cluster/get-kube-binaries.sh to download client and server binaries.\nEOF\n\n  # We want everything in /cluster.\n  cp -R \"${KUBE_ROOT}/cluster\" \"${release_stage}/\"\n\n  mkdir -p \"${release_stage}/server\"\n  cp \"${RELEASE_TARS}/kubernetes-manifests.tar.gz\" \"${release_stage}/server/\"\n  cat <<EOF > \"${release_stage}/server/README\"\nServer binary tarballs are no longer included in the Kubernetes final tarball.\n\nRun cluster/get-kube-binaries.sh to download client and server binaries.\nEOF\n\n  # Include hack/lib as a dependency for the cluster/ scripts\n  mkdir -p \"${release_stage}/hack\"\n  cp -R \"${KUBE_ROOT}/hack/lib\" \"${release_stage}/hack/\"\n\n  cp -R \"${KUBE_ROOT}/docs\" \"${release_stage}/\"\n  cp \"${KUBE_ROOT}/README.md\" \"${release_stage}/\"\n  cp -R \"${KUBE_ROOT}/LICENSES\" \"${release_stage}/\"\n\n  echo \"${KUBE_GIT_VERSION}\" > \"${release_stage}/version\"\n\n  kube::release::clean_cruft\n\n  local package_name=\"${RELEASE_TARS}/kubernetes.tar.gz\"\n  kube::release::create_tarball \"${package_name}\" \"${release_stage}/..\"\n}\n\n# Build a release tarball.  $1 is the output tar name.  $2 is the base directory\n# of the files to be packaged.  This assumes that ${2}/kubernetes is what is\n# being packaged.\nfunction kube::release::create_tarball() {\n  kube::build::ensure_tar\n\n  local tarfile=$1\n  local stagingdir=$2\n\n  \"${TAR}\" czf \"${tarfile}\" -C \"${stagingdir}\" kubernetes --owner=0 --group=0\n}\n", "num_lines": 591}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Common utilities for kube-up/kube-down\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. && pwd)\n\nDEFAULT_KUBECONFIG=\"${HOME:-.}/.kube/config\"\n\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n# KUBE_RELEASE_VERSION_REGEX matches things like \"v1.2.3\" or \"v1.2.3-alpha.4\"\n#\n# NOTE This must match the version_regex in build/common.sh\n# kube::release::parse_and_validate_release_version()\n#\n# KUBE_RELEASE_VERSION_REGEX is used in hack/get-build.sh and cluster/gce/util.sh and KUBE_RELEASE_VERSION_DASHED_REGEX is used in cluster/gce/util.sh,\n# make sure to remove these vars when not used anymore\nexport KUBE_RELEASE_VERSION_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(-([a-zA-Z0-9]+)\\\\.(0|[1-9][0-9]*))?$\"\nexport KUBE_RELEASE_VERSION_DASHED_REGEX=\"v(0|[1-9][0-9]*)-(0|[1-9][0-9]*)-(0|[1-9][0-9]*)(-([a-zA-Z0-9]+)-(0|[1-9][0-9]*))?\"\n\n# KUBE_CI_VERSION_REGEX matches things like \"v1.2.3-alpha.4.56+abcdefg\" This\n#\n# NOTE This must match the version_regex in build/common.sh\n# kube::release::parse_and_validate_ci_version()\n#\n# TODO: KUBE_CI_VERSION_REGEX is used in hack/get-build.sh and KUBE_CI_VERSION_DASHED_REGEX is used in cluster/gce/util.sh,\n# make sure to remove these vars when not used anymore\nexport KUBE_CI_VERSION_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)-([a-zA-Z0-9]+)\\\\.(0|[1-9][0-9]*)(\\\\.(0|[1-9][0-9]*)\\\\+[-0-9a-z]*)?$\"\nexport KUBE_CI_VERSION_DASHED_REGEX=\"^v(0|[1-9][0-9]*)-(0|[1-9][0-9]*)-(0|[1-9][0-9]*)-([a-zA-Z0-9]+)-(0|[1-9][0-9]*)(-(0|[1-9][0-9]*)\\\\+[-0-9a-z]*)?\"\n\n# Generate kubeconfig data for the created cluster.\n# Assumed vars:\n#   KUBE_USER\n#   KUBE_PASSWORD\n#   KUBE_MASTER_IP\n#   KUBECONFIG\n#   CONTEXT\n#\n# If the apiserver supports bearer auth, also provide:\n#   KUBE_BEARER_TOKEN\n#\n# If the kubeconfig context being created should NOT be set as the current context\n# SECONDARY_KUBECONFIG=true\n#\n# To explicitly name the context being created, use OVERRIDE_CONTEXT\n#\n# The following can be omitted for --insecure-skip-tls-verify\n#   KUBE_CERT\n#   KUBE_KEY\n#   CA_CERT\nfunction create-kubeconfig() {\n  KUBECONFIG=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\n  local kubectl=\"${KUBE_ROOT}/cluster/kubectl.sh\"\n  SECONDARY_KUBECONFIG=${SECONDARY_KUBECONFIG:-}\n  OVERRIDE_CONTEXT=${OVERRIDE_CONTEXT:-}\n\n  if [[ \"$OVERRIDE_CONTEXT\" != \"\" ]];then\n      CONTEXT=$OVERRIDE_CONTEXT\n  fi\n\n  # KUBECONFIG determines the file we write to, but it may not exist yet\n  OLD_IFS=$IFS\n  IFS=':'\n  for cfg in ${KUBECONFIG} ; do\n    if [[ ! -e \"${cfg}\" ]]; then\n      mkdir -p \"$(dirname \"${cfg}\")\"\n      touch \"${cfg}\"\n    fi\n  done\n  IFS=$OLD_IFS\n\n  local cluster_args=(\n      \"--server=${KUBE_SERVER:-https://${KUBE_MASTER_IP}}\"\n  )\n  if [[ -z \"${CA_CERT:-}\" ]]; then\n    cluster_args+=(\"--insecure-skip-tls-verify=true\")\n  else\n    cluster_args+=(\n      \"--certificate-authority=${CA_CERT}\"\n      \"--embed-certs=true\"\n    )\n  fi\n\n  local user_args=()\n  if [[ -n \"${KUBE_BEARER_TOKEN:-}\" ]]; then\n    user_args+=(\n     \"--token=${KUBE_BEARER_TOKEN}\"\n    )\n  elif [[ -n \"${KUBE_USER:-}\" && -n \"${KUBE_PASSWORD:-}\" ]]; then\n    user_args+=(\n     \"--username=${KUBE_USER}\"\n     \"--password=${KUBE_PASSWORD}\"\n    )\n  fi\n  if [[ -n \"${KUBE_CERT:-}\" && -n \"${KUBE_KEY:-}\" ]]; then\n    user_args+=(\n     \"--client-certificate=${KUBE_CERT}\"\n     \"--client-key=${KUBE_KEY}\"\n     \"--embed-certs=true\"\n    )\n  fi\n\n  KUBECONFIG=\"${KUBECONFIG}\" \"${kubectl}\" config set-cluster \"${CONTEXT}\" \"${cluster_args[@]}\"\n  if [[ -n \"${user_args[*]:-}\" ]]; then\n    KUBECONFIG=\"${KUBECONFIG}\" \"${kubectl}\" config set-credentials \"${CONTEXT}\" \"${user_args[@]}\"\n  fi\n  KUBECONFIG=\"${KUBECONFIG}\" \"${kubectl}\" config set-context \"${CONTEXT}\" --cluster=\"${CONTEXT}\" --user=\"${CONTEXT}\"\n\n  if [[ \"${SECONDARY_KUBECONFIG}\" != \"true\" ]];then\n      KUBECONFIG=\"${KUBECONFIG}\" \"${kubectl}\" config use-context \"${CONTEXT}\"  --cluster=\"${CONTEXT}\"\n  fi\n\n  # If we have a bearer token, also create a credential entry with basic auth\n  # so that it is easy to discover the basic auth password for your cluster\n  # to use in a web browser.\n  if [[ -n \"${KUBE_BEARER_TOKEN:-}\" && -n \"${KUBE_USER:-}\" && -n \"${KUBE_PASSWORD:-}\" ]]; then\n    KUBECONFIG=\"${KUBECONFIG}\" \"${kubectl}\" config set-credentials \"${CONTEXT}-basic-auth\" \"--username=${KUBE_USER}\" \"--password=${KUBE_PASSWORD}\"\n  fi\n\n   echo \"Wrote config for ${CONTEXT} to ${KUBECONFIG}\"\n}\n\n# Clear kubeconfig data for a context\n# Assumed vars:\n#   KUBECONFIG\n#   CONTEXT\n#\n# To explicitly name the context being removed, use OVERRIDE_CONTEXT\nfunction clear-kubeconfig() {\n  export KUBECONFIG=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\n  OVERRIDE_CONTEXT=${OVERRIDE_CONTEXT:-}\n\n  if [[ \"$OVERRIDE_CONTEXT\" != \"\" ]];then\n      CONTEXT=$OVERRIDE_CONTEXT\n  fi\n\n  local kubectl=\"${KUBE_ROOT}/cluster/kubectl.sh\"\n  # Unset the current-context before we delete it, as otherwise kubectl errors.\n  local cc\n  cc=$(\"${kubectl}\" config view -o jsonpath='{.current-context}')\n  if [[ \"${cc}\" == \"${CONTEXT}\" ]]; then\n    \"${kubectl}\" config unset current-context\n  fi\n  \"${kubectl}\" config unset \"clusters.${CONTEXT}\"\n  \"${kubectl}\" config unset \"users.${CONTEXT}\"\n  \"${kubectl}\" config unset \"users.${CONTEXT}-basic-auth\"\n  \"${kubectl}\" config unset \"contexts.${CONTEXT}\"\n\n  echo \"Cleared config for ${CONTEXT} from ${KUBECONFIG}\"\n}\n\n# Gets username, password for the current-context in kubeconfig, if they exist.\n# Assumed vars:\n#   KUBECONFIG  # if unset, defaults to global\n#   KUBE_CONTEXT  # if unset, defaults to current-context\n#\n# Vars set:\n#   KUBE_USER\n#   KUBE_PASSWORD\n#\n# KUBE_USER,KUBE_PASSWORD will be empty if no current-context is set, or\n# the current-context user does not exist or contain basicauth entries.\nfunction get-kubeconfig-basicauth() {\n  export KUBECONFIG=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\n\n  local cc\n  cc=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.current-context}\")\n  if [[ -n \"${KUBE_CONTEXT:-}\" ]]; then\n    cc=\"${KUBE_CONTEXT}\"\n  fi\n  local user\n  user=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.contexts[?(@.name == \\\"${cc}\\\")].context.user}\")\n  get-kubeconfig-user-basicauth \"${user}\"\n\n  if [[ -z \"${KUBE_USER:-}\" || -z \"${KUBE_PASSWORD:-}\" ]]; then\n    # kube-up stores username/password in a an additional kubeconfig section\n    # suffixed with \"-basic-auth\". Cloudproviders like GKE store in directly\n    # in the top level section along with the other credential information.\n    # TODO: Handle this uniformly, either get rid of \"basic-auth\" or\n    # consolidate its usage into a function across scripts in cluster/\n    get-kubeconfig-user-basicauth \"${user}-basic-auth\"\n  fi\n}\n\n# Sets KUBE_USER and KUBE_PASSWORD to the username and password specified in\n# the kubeconfig section corresponding to $1.\n#\n# Args:\n#   $1 kubeconfig section to look for basic auth (eg: user or user-basic-auth).\n# Assumed vars:\n#   KUBE_ROOT\n# Vars set:\n#   KUBE_USER\n#   KUBE_PASSWORD\nfunction get-kubeconfig-user-basicauth() {\n  KUBE_USER=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.users[?(@.name == \\\"$1\\\")].user.username}\")\n  KUBE_PASSWORD=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.users[?(@.name == \\\"$1\\\")].user.password}\")\n}\n\n# Generate basic auth user and password.\n\n# Vars set:\n#   KUBE_USER\n#   KUBE_PASSWORD\nfunction gen-kube-basicauth() {\n    KUBE_USER='admin'\n    KUBE_PASSWORD=$(python3 -c 'import string,random; print(\"\".join(random.SystemRandom().choice(string.ascii_letters + string.digits) for _ in range(16)))')\n}\n\n# Get the bearer token for the current-context in kubeconfig if one exists.\n# Assumed vars:\n#   KUBECONFIG  # if unset, defaults to global\n#   KUBE_CONTEXT  # if unset, defaults to current-context\n#\n# Vars set:\n#   KUBE_BEARER_TOKEN\n#\n# KUBE_BEARER_TOKEN will be empty if no current-context is set, or the\n# current-context user does not exist or contain a bearer token entry.\nfunction get-kubeconfig-bearertoken() {\n  export KUBECONFIG=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\n\n  local cc\n  cc=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.current-context}\")\n  if [[ -n \"${KUBE_CONTEXT:-}\" ]]; then\n    cc=\"${KUBE_CONTEXT}\"\n  fi\n  local user\n  user=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.contexts[?(@.name == \\\"${cc}\\\")].context.user}\")\n  KUBE_BEARER_TOKEN=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.users[?(@.name == \\\"${user}\\\")].user.token}\")\n}\n\n# Generate bearer token.\n#\n# Vars set:\n#   KUBE_BEARER_TOKEN\nfunction gen-kube-bearertoken() {\n    KUBE_BEARER_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n}\n\nfunction load-or-gen-kube-basicauth() {\n  if [[ -n \"${KUBE_CONTEXT:-}\" ]]; then\n    get-kubeconfig-basicauth\n  fi\n\n  if [[ -z \"${KUBE_USER:-}\" || -z \"${KUBE_PASSWORD:-}\" ]]; then\n    gen-kube-basicauth\n  fi\n\n  # Make sure they don't contain any funny characters.\n  if ! [[ \"${KUBE_USER}\" =~ ^[-._@a-zA-Z0-9]+$ ]]; then\n    echo \"Bad KUBE_USER string.\"\n    exit 1\n  fi\n  if ! [[ \"${KUBE_PASSWORD}\" =~ ^[-._@#%/a-zA-Z0-9]+$ ]]; then\n    echo \"Bad KUBE_PASSWORD string.\"\n    exit 1\n  fi\n}\n\n# Sets KUBE_VERSION variable to the proper version number (e.g. \"v1.0.6\",\n# \"v1.2.0-alpha.1.881+376438b69c7612\") or a version' publication of the form\n# <path>/<version> (e.g. \"release/stable\",' \"ci/latest-1\").\n#\n# See the docs on getting builds for more information about version\n# publication.\n#\n# Args:\n#   $1 version string from command line\n# Vars set and exported for external reference:\n#   KUBE_VERSION\nfunction set_binary_version() {\n  if [[ \"${1}\" =~ \"/\" ]]; then\n    IFS='/' read -r -a path <<< \"${1}\"\n    if [[ \"${path[0]}\" == \"release\" ]]; then\n      KUBE_VERSION=$(gsutil cat \"gs://kubernetes-release/${1}.txt\")\n    else\n      KUBE_VERSION=$(gsutil cat \"gs://kubernetes-release-dev/${1}.txt\")\n    fi\n  else\n    KUBE_VERSION=${1}\n  fi\n  export KUBE_VERSION\n}\n\n# Search for the specified tarball in the various known output locations,\n# echoing the location if found.\n#\n# Assumed vars:\n#   KUBE_ROOT\n#\n# Args:\n#   $1 name of tarball to search for\nfunction find-tar() {\n  local -r tarball=$1\n  locations=(\n    \"${KUBE_ROOT}/node/${tarball}\"\n    \"${KUBE_ROOT}/server/${tarball}\"\n    \"${KUBE_ROOT}/_output/release-tars/${tarball}\"\n  )\n  location=$( (ls -t \"${locations[@]}\" 2>/dev/null || true) | head -1 )\n\n  if [[ ! -f \"${location}\" ]]; then\n    echo \"!!! Cannot find ${tarball}\" >&2\n    exit 1\n  fi\n  echo \"${location}\"\n}\n\n# Verify and find the various tar files that we are going to use on the server.\n#\n# Assumed vars:\n#   KUBE_ROOT\n# Vars set and exported:\n#   NODE_BINARY_TAR\n#   SERVER_BINARY_TAR\n#   KUBE_MANIFESTS_TAR\nfunction find-release-tars() {\n  SERVER_BINARY_TAR=$(find-tar kubernetes-server-linux-amd64.tar.gz)\n  if [[ -z \"${SERVER_BINARY_TAR}\" ]]; then\n\t  exit 1\n  fi\n  export SERVER_BINARY_TAR\n\n  local find_result\n  if [[ \"${NUM_WINDOWS_NODES}\" -gt \"0\" ]]; then\n    if NODE_BINARY_TAR=$(find-tar kubernetes-node-windows-amd64.tar.gz); then\n      find_result=0\n    else\n      find_result=1\n    fi\n    export NODE_BINARY_TAR\n  fi\n\n  # This tarball is used by GCI, Ubuntu Trusty, and Container Linux.\n  KUBE_MANIFESTS_TAR=\n  if [[ \"${MASTER_OS_DISTRIBUTION:-}\" == \"trusty\" || \"${MASTER_OS_DISTRIBUTION:-}\" == \"gci\" || \"${MASTER_OS_DISTRIBUTION:-}\" == \"ubuntu\" ]] || \\\n     [[ \"${NODE_OS_DISTRIBUTION:-}\" == \"trusty\" || \"${NODE_OS_DISTRIBUTION:-}\" == \"gci\" || \"${NODE_OS_DISTRIBUTION:-}\" == \"ubuntu\" || \"${NODE_OS_DISTRIBUTION:-}\" == \"custom\" ]] ; then\n    if KUBE_MANIFESTS_TAR=$(find-tar kubernetes-manifests.tar.gz); then\n      find_result=0\n    else\n      find_result=1\n    fi\n    export KUBE_MANIFESTS_TAR\n  fi\n\n  # the function result is used in function `verify-release-tars`\n  if [[ $find_result == 0 ]]; then\n    return 0\n  else\n    return 1\n  fi\n}\n\n# Run the cfssl command to generates certificate files for etcd service, the\n# certificate files will save in $1 directory.\n#\n# Optional vars:\n#   GEN_ETCD_CA_CERT (CA cert encode with base64 and ZIP compression)\n#   GEN_ETCD_CA_KEY (CA key encode with base64)\n#   ca_cert (require when GEN_ETCD_CA_CERT and GEN_ETCD_CA_KEY is set)\n#   ca_key (require when GEN_ETCD_CA_CERT and GEN_ETCD_CA_KEY is set)\n# If GEN_ETCD_CA_CERT or GEN_ETCD_CA_KEY is not specified, it will generates certs for CA.\n#\n# Args:\n#   $1 (the directory that certificate files to save)\n#   $2 (the ip of etcd member)\n#   $3 (the type of etcd certificates, must be one of client, server, peer)\n#   $4 (the prefix of the certificate filename, default is $3)\nfunction generate-etcd-cert() {\n  local cert_dir=${1}\n  local member_ip=${2}\n  local type_cert=${3}\n  local prefix=${4:-\"${type_cert}\"}\n\n  local GEN_ETCD_CA_CERT=${GEN_ETCD_CA_CERT:-}\n  local GEN_ETCD_CA_KEY=${GEN_ETCD_CA_KEY:-}\n\n  mkdir -p \"${cert_dir}\"\n  pushd \"${cert_dir}\"\n\n  kube::util::ensure-cfssl .\n\n  if [ ! -r \"ca-config.json\" ]; then\n    cat >ca-config.json <<EOF\n{\n    \"signing\": {\n        \"default\": {\n            \"expiry\": \"43800h\"\n        },\n        \"profiles\": {\n            \"server\": {\n                \"expiry\": \"43800h\",\n                \"usages\": [\n                    \"signing\",\n                    \"key encipherment\",\n                    \"server auth\",\n                    \"client auth\"\n                ]\n            },\n            \"client\": {\n                \"expiry\": \"43800h\",\n                \"usages\": [\n                    \"signing\",\n                    \"key encipherment\",\n                    \"client auth\"\n                ]\n            },\n            \"peer\": {\n                \"expiry\": \"43800h\",\n                \"usages\": [\n                    \"signing\",\n                    \"key encipherment\",\n                    \"server auth\",\n                    \"client auth\"\n                ]\n            }\n        }\n    }\n}\nEOF\n  fi\n\n  if [ ! -r \"ca-csr.json\" ]; then\n    cat >ca-csr.json <<EOF\n{\n    \"CN\": \"Kubernetes\",\n    \"key\": {\n        \"algo\": \"ecdsa\",\n        \"size\": 256\n    },\n    \"names\": [\n        {\n            \"C\": \"US\",\n            \"L\": \"CA\",\n            \"O\": \"kubernetes.io\"\n        }\n    ]\n}\nEOF\n  fi\n\n  if [[ -n \"${GEN_ETCD_CA_CERT}\" && -n \"${GEN_ETCD_CA_KEY}\" ]]; then\n    # ca_cert and ca_key are optional external vars supplied in cluster/gce/util.sh,\n    # so it's ok to disable shellcheck here\n    # shellcheck disable=SC2154\n    echo \"${ca_cert}\" | base64 --decode | gunzip > ca.pem\n    # shellcheck disable=SC2154\n    echo \"${ca_key}\" | base64 --decode > ca-key.pem\n  fi\n\n  if [[ ! -r \"ca.pem\" || ! -r \"ca-key.pem\" ]]; then\n    ${CFSSL_BIN} gencert -initca ca-csr.json | ${CFSSLJSON_BIN} -bare ca -\n  fi\n\n  case \"${type_cert}\" in\n    client)\n      echo \"Generate client certificates...\"\n      echo '{\"CN\":\"client\",\"hosts\":[\"*\"],\"key\":{\"algo\":\"ecdsa\",\"size\":256}}' \\\n       | ${CFSSL_BIN} gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=client - \\\n       | ${CFSSLJSON_BIN} -bare \"${prefix}\"\n      ;;\n    server)\n      echo \"Generate server certificates...\"\n      echo '{\"CN\":\"'\"${member_ip}\"'\",\"hosts\":[\"\"],\"key\":{\"algo\":\"ecdsa\",\"size\":256}}' \\\n       | ${CFSSL_BIN} gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=server -hostname=\"${member_ip},127.0.0.1\" - \\\n       | ${CFSSLJSON_BIN} -bare \"${prefix}\"\n      ;;\n    peer)\n      echo \"Generate peer certificates...\"\n      echo '{\"CN\":\"'\"${member_ip}\"'\",\"hosts\":[\"\"],\"key\":{\"algo\":\"ecdsa\",\"size\":256}}' \\\n       | ${CFSSL_BIN} gencert -ca=ca.pem -ca-key=ca-key.pem -config=ca-config.json -profile=peer -hostname=\"${member_ip},127.0.0.1\" - \\\n       | ${CFSSLJSON_BIN} -bare \"${prefix}\"\n      ;;\n    *)\n      echo \"Unknow, unsupported etcd certs type: ${type_cert}\" >&2\n      echo \"Supported type: client, server, peer\" >&2\n      exit 2\n  esac\n\n  # the popd will access `directory stack`, no `real` parameters is actually needed\n  # shellcheck disable=SC2119\n  popd\n}\n\n# Check whether required binaries exist, prompting to download\n# if missing.\n# If KUBERNETES_SKIP_CONFIRM is set to y, we'll automatically download binaries\n# without prompting.\nfunction verify-kube-binaries() {\n  if ! \"${KUBE_ROOT}/cluster/kubectl.sh\" version --client >&/dev/null; then\n    echo \"!!! kubectl appears to be broken or missing\"\n    download-release-binaries\n  fi\n}\n\n# Check whether required release artifacts exist, prompting to download\n# if missing.\n# If KUBERNETES_SKIP_CONFIRM is set to y, we'll automatically download binaries\n# without prompting.\nfunction verify-release-tars() {\n  if ! find-release-tars; then\n    download-release-binaries\n  fi\n}\n\n# Download release artifacts.\nfunction download-release-binaries() {\n  get_binaries_script=\"${KUBE_ROOT}/cluster/get-kube-binaries.sh\"\n  local resp=\"y\"\n  if [[ ! \"${KUBERNETES_SKIP_CONFIRM:-n}\" =~ ^[yY]$ ]]; then\n    echo \"Required release artifacts appear to be missing. Do you wish to download them? [Y/n]\"\n    read -r resp\n  fi\n  if [[ \"${resp}\" =~ ^[nN]$ ]]; then\n    echo \"You must download release artifacts to continue. You can use \"\n    echo \"  ${get_binaries_script}\"\n    echo \"to do this for your automatically.\"\n    exit 1\n  fi\n  \"${get_binaries_script}\"\n}\n\n# Run pushd without stack output\nfunction pushd() {\n  command pushd \"$@\" > /dev/null\n}\n\n# Run popd without stack output\n# the popd will access `directory stack`, no `real` parameters is actually needed\n# shellcheck disable=SC2120\nfunction popd() {\n  command popd \"$@\" > /dev/null\n}\n", "num_lines": 552}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script downloads and installs the Kubernetes client and server\n# (and optionally test) binaries,\n# It is intended to be called from an extracted Kubernetes release tarball.\n#\n# We automatically choose the correct client binaries to download.\n#\n# Options:\n#  Set KUBERNETES_SERVER_ARCH to choose the server (Kubernetes cluster)\n#  architecture to download:\n#    * amd64 [default]\n#    * arm\n#    * arm64\n#    * ppc64le\n#    * s390x\n#\n#  Set KUBERNETES_CLIENT_OS to choose the client OS to download:\n#    * current OS [default]\n#    * linux\n#    * darwin\n#    * windows\n#\n#  Set KUBERNETES_CLIENT_ARCH to choose the client architecture to download:\n#    * current architecture [default]\n#    * amd64\n#    * arm\n#    * arm64\n#    * ppc64le\n#    * s390x\n#    * windows\n#\n#  Set KUBERNETES_SKIP_CONFIRM to skip the installation confirmation prompt.\n#  Set KUBERNETES_RELEASE_URL to choose where to download binaries from.\n#    (Defaults to https://storage.googleapis.com/kubernetes-release/release).\n#  Set KUBERNETES_DOWNLOAD_TESTS to additionally download and extract the test\n#    binaries tarball.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd)\n\nKUBERNETES_RELEASE_URL=\"${KUBERNETES_RELEASE_URL:-https://dl.k8s.io}\"\n\nfunction detect_kube_release() {\n  if [[ -n \"${KUBE_VERSION:-}\" ]]; then\n    return 0  # Allow caller to explicitly set version\n  fi\n\n  if [[ ! -e \"${KUBE_ROOT}/version\" ]]; then\n    echo \"Can't determine Kubernetes release.\" >&2\n    echo \"${BASH_SOURCE[0]} should only be run from a prebuilt Kubernetes release.\" >&2\n    echo \"Did you mean to use get-kube.sh instead?\" >&2\n    exit 1\n  fi\n\n  KUBE_VERSION=$(cat \"${KUBE_ROOT}/version\")\n}\n\nfunction detect_client_info() {\n  if [ -n \"${KUBERNETES_CLIENT_OS-}\" ]; then\n    CLIENT_PLATFORM=\"${KUBERNETES_CLIENT_OS}\"\n  else\n    local kernel\n    kernel=\"$(uname -s)\"\n    case \"${kernel}\" in\n      Darwin)\n        CLIENT_PLATFORM=\"darwin\"\n        ;;\n      Linux)\n        CLIENT_PLATFORM=\"linux\"\n        ;;\n      *)\n        echo \"Unknown, unsupported platform: ${kernel}.\" >&2\n        echo \"Supported platforms: Linux, Darwin.\" >&2\n        echo \"Bailing out.\" >&2\n        exit 2\n    esac\n  fi\n\n  if [ -n \"${KUBERNETES_CLIENT_ARCH-}\" ]; then\n    CLIENT_ARCH=\"${KUBERNETES_CLIENT_ARCH}\"\n  else\n    # TODO: migrate the kube::util::host_platform function out of hack/lib and\n    # use it here.\n    local machine\n    machine=\"$(uname -m)\"\n    case \"${machine}\" in\n      x86_64*|i?86_64*|amd64*)\n        CLIENT_ARCH=\"amd64\"\n        ;;\n      aarch64*|arm64*)\n        CLIENT_ARCH=\"arm64\"\n        ;;\n      arm*)\n        CLIENT_ARCH=\"arm\"\n        ;;\n      i?86*)\n        CLIENT_ARCH=\"386\"\n        ;;\n      ppc64le*)\n        CLIENT_ARCH=\"ppc64le\"\n        ;;\n      s390x*)\n        CLIENT_ARCH=\"s390x\"\n        ;;\n      *)\n        echo \"Unknown, unsupported architecture (${machine}).\" >&2\n        echo \"Supported architectures x86_64, i686, arm, arm64, ppc64le, s390x.\" >&2\n        echo \"Bailing out.\" >&2\n        exit 3\n        ;;\n    esac\n  fi\n}\n\nfunction md5sum_file() {\n  if which md5 >/dev/null 2>&1; then\n    md5 -q \"$1\"\n  else\n    md5sum \"$1\" | awk '{ print $1 }'\n  fi\n}\n\nfunction sha512sum_file() {\n  if which sha512sum >/dev/null 2>&1; then\n    sha512sum \"$1\" | awk '{ print $1 }'\n  else\n    shasum -a512 \"$1\" | awk '{ print $1 }'\n  fi\n}\n\nfunction download_tarball() {\n  local -r download_path=\"$1\"\n  local -r file=\"$2\"\n  local trace_on=\"off\"\n  if [[ -o xtrace ]]; then\n    trace_on=\"on\"\n    set +x\n  fi\n  url=\"${DOWNLOAD_URL_PREFIX}/${file}\"\n  mkdir -p \"${download_path}\"\n\n  if [[ $(which gsutil) ]] && [[ \"$url\" =~ ^https://storage.googleapis.com/.* ]]; then\n    gsutil cp \"${url//'https://storage.googleapis.com/'/gs://}\" \"${download_path}/${file}\"\n  elif [[ $(which curl) ]]; then\n    # if the url belongs to GCS API we should use oauth2_token in the headers\n    curl_headers=\"\"\n    if { [[ \"${KUBERNETES_PROVIDER:-gce}\" == \"gce\" ]] || [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]] ; } &&\n       [[ \"$url\" =~ ^https://storage.googleapis.com.* ]]; then\n      curl_headers=\"Authorization: Bearer $(gcloud auth print-access-token)\"\n    fi\n    curl ${curl_headers:+-H \"${curl_headers}\"} -fL --retry 3 --keepalive-time 2 \"${url}\" -o \"${download_path}/${file}\"\n  elif [[ $(which wget) ]]; then\n    wget \"${url}\" -O \"${download_path}/${file}\"\n  else\n    echo \"Couldn't find gsutil, curl, or wget.  Bailing out.\" >&2\n    exit 4\n  fi\n  echo\n  local md5sum sha512sum\n  md5sum=$(md5sum_file \"${download_path}/${file}\")\n  echo \"md5sum(${file})=${md5sum}\"\n  sha512sum=$(sha512sum_file \"${download_path}/${file}\")\n  echo \"sha512sum(${file})=${sha512sum}\"\n  echo\n  # TODO: add actual verification\n  if [[ \"${trace_on}\" == \"on\" ]]; then\n    set -x\n  fi\n}\n\nfunction extract_arch_tarball() {\n  local -r tarfile=\"$1\"\n  local -r platform=\"$2\"\n  local -r arch=\"$3\"\n\n  platforms_dir=\"${KUBE_ROOT}/platforms/${platform}/${arch}\"\n  echo \"Extracting ${tarfile} into ${platforms_dir}\"\n  mkdir -p \"${platforms_dir}\"\n  # Tarball looks like kubernetes/{client,server,test}/bin/BINARY\"\n  tar -xzf \"${tarfile}\" --strip-components 3 -C \"${platforms_dir}\"\n}\n\ndetect_kube_release\nDOWNLOAD_URL_PREFIX=\"${KUBERNETES_RELEASE_URL}/${KUBE_VERSION}\"\n\nSERVER_PLATFORM=\"linux\"\nSERVER_ARCH=\"${KUBERNETES_SERVER_ARCH:-amd64}\"\nSERVER_TAR=\"kubernetes-server-${SERVER_PLATFORM}-${SERVER_ARCH}.tar.gz\"\nif [[ -n \"${KUBERNETES_NODE_PLATFORM-}\" || -n \"${KUBERNETES_NODE_ARCH-}\" ]]; then\n  NODE_PLATFORM=\"${KUBERNETES_NODE_PLATFORM:-${SERVER_PLATFORM}}\"\n  NODE_ARCH=\"${KUBERNETES_NODE_ARCH:-${SERVER_ARCH}}\"\n  NODE_TAR=\"kubernetes-node-${NODE_PLATFORM}-${NODE_ARCH}.tar.gz\"\nfi\n\ndetect_client_info\nCLIENT_TAR=\"kubernetes-client-${CLIENT_PLATFORM}-${CLIENT_ARCH}.tar.gz\"\n\necho \"Kubernetes release: ${KUBE_VERSION}\"\necho \"Server: ${SERVER_PLATFORM}/${SERVER_ARCH}  (to override, set KUBERNETES_SERVER_ARCH)\"\nprintf \"Client: %s/%s\" \"${CLIENT_PLATFORM}\" \"${CLIENT_ARCH}\"\nif [ -z \"${KUBERNETES_CLIENT_OS-}\" ] && [ -z \"${KUBERNETES_CLIENT_ARCH-}\" ]; then\n  printf \"  (autodetected)\"\nfi\necho \"  (to override, set KUBERNETES_CLIENT_OS and/or KUBERNETES_CLIENT_ARCH)\"\necho\n\necho \"Will download ${SERVER_TAR} from ${DOWNLOAD_URL_PREFIX}\"\necho \"Will download and extract ${CLIENT_TAR} from ${DOWNLOAD_URL_PREFIX}\"\n\nDOWNLOAD_NODE_TAR=false\nif [[ -n \"${NODE_TAR:-}\" ]]; then\n  DOWNLOAD_NODE_TAR=true\n  echo \"Will download and extract ${NODE_TAR} from ${DOWNLOAD_URL_PREFIX}\"\nfi\n\nDOWNLOAD_TESTS_TAR=false\nif [[ -n \"${KUBERNETES_DOWNLOAD_TESTS-}\" ]]; then\n  DOWNLOAD_TESTS_TAR=true\n  echo \"Will download and extract kubernetes-test tarball(s) from ${DOWNLOAD_URL_PREFIX}\"\nfi\n\nif [[ -z \"${KUBERNETES_SKIP_CONFIRM-}\" ]]; then\n  echo \"Is this ok? [Y]/n\"\n  read -r confirm\n  if [[ \"${confirm}\" =~ ^[nN]$ ]]; then\n    echo \"Aborting.\"\n    exit 1\n  fi\nfi\n\ndownload_tarball \"${KUBE_ROOT}/server\" \"${SERVER_TAR}\"\n\nif \"${DOWNLOAD_NODE_TAR}\"; then\n  download_tarball \"${KUBE_ROOT}/node\" \"${NODE_TAR}\"\nfi\n\ndownload_tarball \"${KUBE_ROOT}/client\" \"${CLIENT_TAR}\"\nextract_arch_tarball \"${KUBE_ROOT}/client/${CLIENT_TAR}\" \"${CLIENT_PLATFORM}\" \"${CLIENT_ARCH}\"\nln -s \"${KUBE_ROOT}/platforms/${CLIENT_PLATFORM}/${CLIENT_ARCH}\" \"${KUBE_ROOT}/client/bin\"\necho \"Add '${KUBE_ROOT}/client/bin' to your PATH to use newly-installed binaries.\"\n\nif \"${DOWNLOAD_TESTS_TAR}\"; then\n  TESTS_PORTABLE_TAR=\"kubernetes-test-portable.tar.gz\"\n  download_tarball \"${KUBE_ROOT}/test\" \"${TESTS_PORTABLE_TAR}\" || true\n  if [[ -f \"${KUBE_ROOT}/test/${TESTS_PORTABLE_TAR}\" ]]; then\n    echo \"Extracting ${TESTS_PORTABLE_TAR} into ${KUBE_ROOT}\"\n    # Strip leading \"kubernetes/\"\n    tar -xzf \"${KUBE_ROOT}/test/${TESTS_PORTABLE_TAR}\" --strip-components 1 -C \"${KUBE_ROOT}\"\n\n    # Next, download platform-specific test tarballs for all relevant platforms\n    TEST_PLATFORM_TUPLES=(\n      \"${CLIENT_PLATFORM}/${CLIENT_ARCH}\"\n      \"${SERVER_PLATFORM}/${SERVER_ARCH}\"\n      )\n    if [[ -n \"${NODE_PLATFORM:-}\" && -n \"${NODE_ARCH:-}\" ]]; then\n      TEST_PLATFORM_TUPLES+=(\"${NODE_PLATFORM}/${NODE_ARCH}\")\n    fi\n    # Loop over only the unique tuples\n    for TUPLE in $(printf \"%s\\n\" \"${TEST_PLATFORM_TUPLES[@]}\" | sort -u); do\n        OS=$(echo \"${TUPLE}\" | cut -d/ -f1)\n        ARCH=$(echo \"${TUPLE}\" | cut -d/ -f2)\n        TEST_PLATFORM_TAR=\"kubernetes-test-${OS}-${ARCH}.tar.gz\"\n        download_tarball \"${KUBE_ROOT}/test\" \"${TEST_PLATFORM_TAR}\"\n        extract_arch_tarball \"${KUBE_ROOT}/test/${TEST_PLATFORM_TAR}\" \"${OS}\" \"${ARCH}\"\n    done\n  else\n    echo \"Failed to download portable test tarball, falling back to mondo test tarball.\"\n    TESTS_MONDO_TAR=\"kubernetes-test.tar.gz\"\n    download_tarball \"${KUBE_ROOT}/test\" \"${TESTS_MONDO_TAR}\"\n    echo \"Extracting ${TESTS_MONDO_TAR} into ${KUBE_ROOT}\"\n    # Strip leading \"kubernetes/\"\n    tar -xzf \"${KUBE_ROOT}/test/${TESTS_MONDO_TAR}\" --strip-components 1 -C \"${KUBE_ROOT}\"\n  fi\nfi\n", "num_lines": 293}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Bring up a Kubernetes cluster.\n# Usage:\n#   wget -q -O - https://get.k8s.io | bash\n# or\n#   curl -fsSL https://get.k8s.io | bash\n#\n# Advanced options\n#  Set KUBERNETES_PROVIDER to choose between different providers:\n#  Google Compute Engine [default]\n#   * export KUBERNETES_PROVIDER=gce; wget -q -O - https://get.k8s.io | bash\n#\n#  Set KUBERNETES_RELEASE to choose a specific release instead of the current\n#    stable release, (e.g. 'v1.3.7').\n#    See https://github.com/kubernetes/kubernetes/releases for release options.\n#  Set KUBERNETES_RELEASE_URL to choose where to download binaries from.\n#    (Defaults to https://storage.googleapis.com/kubernetes-release/release).\n#\n#  Set KUBERNETES_SERVER_ARCH to choose the server (Kubernetes cluster)\n#  architecture to download:\n#    * amd64 [default]\n#    * arm\n#    * arm64\n#    * ppc64le\n#\n#  Set KUBERNETES_NODE_PLATFORM to choose the platform for which to download\n#  the node binaries. If none of KUBERNETES_NODE_PLATFORM and\n#  KUBERNETES_NODE_ARCH is set, no node binaries will be downloaded. If only\n#  one of the two is set, the other will be defaulted to the\n#  KUBERNETES_SERVER_PLATFORM/ARCH.\n#    * linux\n#    * windows\n#\n#  Set KUBERNETES_NODE_ARCH to choose the node architecture to download the\n#  node binaries. If none of KUBERNETES_NODE_PLATFORM and\n#  KUBERNETES_NODE_ARCH is set, no node binaries will be downloaded. If only\n#  one of the two is set, the other will be defaulted to the\n#  KUBERNETES_SERVER_PLATFORM/ARCH.\n#    * amd64 [default]\n#    * arm\n#    * arm64\n#    * ppc64le\n#\n#  Set KUBERNETES_SKIP_DOWNLOAD to skip downloading a release.\n#  Set KUBERNETES_SKIP_CONFIRM to skip the installation confirmation prompt.\n#  Set KUBERNETES_SKIP_CREATE_CLUSTER to skip starting a cluster.\n#  Set KUBERNETES_SKIP_RELEASE_VALIDATION to skip trying to validate the\n#      Kubernetes release string. This implies that you know what you're doing\n#      and have set KUBERNETES_RELEASE and KUBERNETES_RELEASE_URL properly.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# If KUBERNETES_RELEASE_URL is overridden but KUBERNETES_CI_RELEASE_URL is not then set KUBERNETES_CI_RELEASE_URL to KUBERNETES_RELEASE_URL.\nKUBERNETES_CI_RELEASE_URL=\"${KUBERNETES_CI_RELEASE_URL:-${KUBERNETES_RELEASE_URL:-https://dl.k8s.io/ci}}\"\nKUBERNETES_RELEASE_URL=\"${KUBERNETES_RELEASE_URL:-https://dl.k8s.io}\"\n\nKUBE_RELEASE_VERSION_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(-([a-zA-Z0-9]+)\\\\.(0|[1-9][0-9]*))?$\"\nKUBE_CI_VERSION_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)-([a-zA-Z0-9]+)\\\\.(0|[1-9][0-9]*)(\\\\.(0|[1-9][0-9]*)\\\\+[-0-9a-z]*)?$\"\n\n# Sets KUBE_VERSION variable if an explicit version number was provided (e.g. \"v1.0.6\",\n# \"v1.2.0-alpha.1.881+376438b69c7612\") or resolves the \"published\" version\n# <path>/<version> (e.g. \"release/stable\",' \"ci/latest-1\") by reading from GCS.\n#\n# See the docs on getting builds for more information about version\n# publication.\n#\n# Args:\n#   $1 version string from command line\n# Vars set:\n#   KUBE_VERSION\nfunction set_binary_version() {\n  if [[ \"${1}\" =~ \"/\" ]]; then\n    KUBE_VERSION=$(curl -fsSL --retry 5 \"https://dl.k8s.io/${1}.txt\")\n  else\n    KUBE_VERSION=${1}\n  fi\n  export KUBE_VERSION\n}\n\n# Use the script from inside the Kubernetes tarball to fetch the client and\n# server binaries (if not included in kubernetes.tar.gz).\nfunction download_kube_binaries {\n  (\n    cd kubernetes\n    if [[ -x ./cluster/get-kube-binaries.sh ]]; then\n      # Make sure to use the same download URL in get-kube-binaries.sh\n      KUBERNETES_RELEASE_URL=\"${KUBERNETES_RELEASE_URL}\" \\\n        ./cluster/get-kube-binaries.sh\n    fi\n  )\n}\n\nfunction create_cluster {\n  if [[ -n \"${KUBERNETES_SKIP_CREATE_CLUSTER-}\" ]]; then\n    exit 0\n  fi\n  echo \"Creating a kubernetes on ${KUBERNETES_PROVIDER:-gce}...\"\n  (\n    cd kubernetes\n    ./cluster/kube-up.sh\n    echo \"Kubernetes binaries at ${PWD}/cluster/\"\n    if [[ \":$PATH:\" != *\":${PWD}/cluster:\"* ]]; then\n      echo \"You may want to add this directory to your PATH in \\$HOME/.profile\"\n    fi\n\n    echo \"Installation successful!\"\n  )\n}\n\nfunction valid-storage-scope {\n  curl \"${GCE_METADATA_INTERNAL}/service-accounts/default/scopes\" -H \"Metadata-Flavor: Google\" -s | grep -E \"auth/devstorage|auth/cloud-platform\"\n}\n\nif [[ -n \"${KUBERNETES_SKIP_DOWNLOAD-}\" ]]; then\n  create_cluster\n  exit 0\nfi\n\nif [[ -d \"./kubernetes\" ]]; then\n  if [[ -z \"${KUBERNETES_SKIP_CONFIRM-}\" ]]; then\n    echo \"'kubernetes' directory already exist. Should we skip download step and start to create cluster based on it? [Y]/n\"\n    read -r confirm\n    if [[ ! \"${confirm}\" =~ ^[nN]$ ]]; then\n      echo \"Skipping download step.\"\n      create_cluster\n      exit 0\n    fi\n  fi\nfi\n\n# TODO: remove client checks once kubernetes.tar.gz no longer includes client\n# binaries by default.\nkernel=$(uname -s)\ncase \"${kernel}\" in\n  Darwin)\n    ;;\n  Linux)\n    ;;\n  *)\n    echo \"Unknown, unsupported platform: ${kernel}.\" >&2\n    echo \"Supported platforms: Linux, Darwin.\" >&2\n    echo \"Bailing out.\" >&2\n    exit 2\nesac\n\nmachine=$(uname -m)\ncase \"${machine}\" in\n  x86_64*|i?86_64*|amd64*)\n    ;;\n  aarch64*|arm64*)\n    ;;\n  ppc64le*)\n    ;;\n  arm*)\n    ;;\n  i?86*)\n    ;;\n  *)\n    echo \"Unknown, unsupported architecture (${machine}).\" >&2\n    echo \"Supported architectures x86_64, i686, arm, arm64, ppc64le.\" >&2\n    echo \"Bailing out.\" >&2\n    exit 3\n    ;;\nesac\n\nfile=kubernetes.tar.gz\nrelease=${KUBERNETES_RELEASE:-\"release/stable\"}\n\n# Validate Kubernetes release version.\n# Translate a published version <bucket>/<version> (e.g. \"release/stable\") to version number.\nset_binary_version \"${release}\"\nif [[ -z \"${KUBERNETES_SKIP_RELEASE_VALIDATION-}\" ]]; then\n  if [[ ${KUBE_VERSION} =~ ${KUBE_RELEASE_VERSION_REGEX} ]]; then\n    # Use KUBERNETES_RELEASE_URL for Releases and Pre-Releases\n    # ie. 1.18.0 or 1.19.0-beta.0\n    KUBERNETES_RELEASE_URL=\"${KUBERNETES_RELEASE_URL}\"\n  elif [[ ${KUBE_VERSION} =~ ${KUBE_CI_VERSION_REGEX} ]]; then\n    # Override KUBERNETES_RELEASE_URL to point to the CI bucket;\n    # this will be used by get-kube-binaries.sh.\n    # ie. v1.19.0-beta.0.318+b618411f1edb98\n    KUBERNETES_RELEASE_URL=\"${KUBERNETES_CI_RELEASE_URL}\"\n  else\n    echo \"Version doesn't match regexp\" >&2\n    exit 1\n  fi\nfi\nkubernetes_tar_url=\"${KUBERNETES_RELEASE_URL}/${KUBE_VERSION}/${file}\"\n\nneed_download=true\nif [[ -r \"${PWD}/${file}\" ]]; then\n  downloaded_version=$(tar -xzOf \"${PWD}/${file}\" kubernetes/version 2>/dev/null || true)\n  echo \"Found preexisting ${file}, release ${downloaded_version}\"\n  if [[ \"${downloaded_version}\" == \"${KUBE_VERSION}\" ]]; then\n    echo \"Using preexisting kubernetes.tar.gz\"\n    need_download=false\n  fi\nfi\n\nif \"${need_download}\"; then\n  echo \"Downloading kubernetes release ${KUBE_VERSION}\"\n  echo \"  from ${kubernetes_tar_url}\"\n  echo \"  to ${PWD}/${file}\"\nfi\n\nif [[ -e \"${PWD}/kubernetes\" ]]; then\n  # Let's try not to accidentally nuke something that isn't a kubernetes\n  # release dir.\n  if [[ ! -f \"${PWD}/kubernetes/version\" ]]; then\n    echo \"${PWD}/kubernetes exists but does not look like a Kubernetes release.\"\n    echo \"Aborting!\"\n    exit 5\n  fi\n  echo \"Will also delete preexisting 'kubernetes' directory.\"\nfi\n\nif [[ -z \"${KUBERNETES_SKIP_CONFIRM-}\" ]]; then\n  echo \"Is this ok? [Y]/n\"\n  read -r confirm\n  if [[ \"${confirm}\" =~ ^[nN]$ ]]; then\n    echo \"Aborting.\"\n    exit 0\n  fi\nfi\n\nif \"${need_download}\"; then\n  if [[ $(which gsutil) ]] && [[ \"$kubernetes_tar_url\" =~ ^https://storage.googleapis.com/.* ]]; then\n    gsutil cp \"${kubernetes_tar_url//'https://storage.googleapis.com/'/gs://}\" \"${file}\"\n  elif [[ $(which curl) ]]; then\n    # if the url belongs to GCS API we should use oauth2_token in the headers\n    curl_headers=\"\"\n    if { [[ \"${KUBERNETES_PROVIDER:-gce}\" == \"gce\" ]] || [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]] ; } &&\n       [[ \"$kubernetes_tar_url\" =~ ^https://storage.googleapis.com.* ]] ; then\n      curl_headers=\"Authorization: Bearer $(gcloud auth print-access-token)\"\n    fi\n    curl ${curl_headers:+-H \"${curl_headers}\"} -fL --retry 3 --keepalive-time 2 \"${kubernetes_tar_url}\" -o \"${file}\"\n  elif [[ $(which wget) ]]; then\n    wget \"${kubernetes_tar_url}\"\n  else\n    echo \"Couldn't find gsutil, curl, or wget.  Bailing out.\"\n    exit 1\n  fi\nfi\n\necho \"Unpacking kubernetes release ${KUBE_VERSION}\"\nrm -rf \"${PWD}/kubernetes\"\ntar -xzf ${file}\n\ndownload_kube_binaries\ncreate_cluster\n", "num_lines": 267}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Tear down a Kubernetes cluster.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nif [ -f \"${KUBE_ROOT}/cluster/env.sh\" ]; then\n    source \"${KUBE_ROOT}/cluster/env.sh\"\nfi\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\necho \"Bringing down cluster using provider: $KUBERNETES_PROVIDER\"\n\necho \"... calling verify-prereqs\" >&2\nverify-prereqs\necho \"... calling verify-kube-binaries\" >&2\nverify-kube-binaries\necho \"... calling kube-down\" >&2\nkube-down\n\necho \"Done\"\n", "num_lines": 41}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Bring up a Kubernetes cluster.\n#\n# If the full release name (gs://<bucket>/<release>) is passed in then we take\n# that directly.  If not then we assume we are doing development stuff and take\n# the defaults in the release config.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nif [ -f \"${KUBE_ROOT}/cluster/env.sh\" ]; then\n    source \"${KUBE_ROOT}/cluster/env.sh\"\nfi\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nif [ -z \"${ZONE-}\" ]; then\n  echo \"... Starting cluster using provider: ${KUBERNETES_PROVIDER}\" >&2\nelse\n  echo \"... Starting cluster in ${ZONE} using provider ${KUBERNETES_PROVIDER}\" >&2\nfi\n\necho \"... calling verify-prereqs\" >&2\nverify-prereqs\necho \"... calling verify-kube-binaries\" >&2\nverify-kube-binaries\necho \"... calling verify-release-tars\" >&2\nverify-release-tars\n\necho \"... calling kube-up\" >&2\nkube-up\n\necho \"... calling validate-cluster\" >&2\n# Override errexit\n(validate-cluster) && validate_result=\"$?\" || validate_result=\"$?\"\n\n# We have two different failure modes from validate cluster:\n# - 1: fatal error - cluster won't be working correctly\n# - 2: weak error - something went wrong, but cluster probably will be working correctly\n# We just print an error message in case 2).\nif [[ \"${validate_result}\" == \"1\" ]]; then\n\texit 1\nelif [[ \"${validate_result}\" == \"2\" ]]; then\n\techo \"...ignoring non-fatal errors in validate-cluster\" >&2\nfi\n\nif [[ \"${ENABLE_PROXY:-}\" == \"true\" ]]; then\n  # shellcheck disable=SC1091\n  . /tmp/kube-proxy-env\n  echo \"\"\n  echo \"*** Please run the following to add the kube-apiserver endpoint to your proxy white-list ***\"\n  cat /tmp/kube-proxy-env\n  echo \"***                                                                                      ***\"\n  echo \"\"\nfi\n\necho -e \"Done, listing cluster services:\\n\" >&2\n\"${KUBE_ROOT}/cluster/kubectl.sh\" cluster-info\necho\n\nexit 0\n", "num_lines": 80}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script will source the default skeleton helper functions, then sources\n# cluster/${KUBERNETES_PROVIDER}/util.sh where KUBERNETES_PROVIDER, if unset,\n# will use its default value (gce).\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nsource \"${KUBE_ROOT}/cluster/skeleton/util.sh\"\n\nif [[ -n \"${KUBERNETES_CONFORMANCE_TEST:-}\" ]]; then\n    KUBERNETES_PROVIDER=\"\"\nelse\n    KUBERNETES_PROVIDER=\"${KUBERNETES_PROVIDER:-gce}\"\nfi\n\n# PROVIDER_VARS is a list of cloud provider specific variables. Note:\n# this is a list of the _names_ of the variables, not the value of the\n# variables. Providers can add variables to be appended to kube-env.\n# (see `build-kube-env`).\n\nPROVIDER_UTILS=\"${KUBE_ROOT}/cluster/${KUBERNETES_PROVIDER}/util.sh\"\nif [ -f \"${PROVIDER_UTILS}\" ]; then\n    source \"${PROVIDER_UTILS}\"\nfi\n", "num_lines": 40}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Stop the bleeding, turn off the warning until we fix token gen.\n# echo \"-=-=-=-=-=-=-=-=-=-=\"\n# echo \"NOTE:\"\n# echo \"kubectl.sh is deprecated and will be removed soon.\"\n# echo \"please replace all usage with calls to the kubectl\"\n# echo \"binary and ensure that it is in your PATH.\"\n# echo \"\"\n# echo \"Please see 'kubectl help config' for more details\"\n# echo \"about configuring kubectl for your cluster.\"\n# echo \"-=-=-=-=-=-=-=-=-=-=\"\n\n\nKUBE_ROOT=${KUBE_ROOT:-$(dirname \"${BASH_SOURCE[0]}\")/..}\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# If KUBECTL_PATH isn't set, gather up the list of likely places and use ls\n# to find the latest one.\nif [[ -z \"${KUBECTL_PATH:-}\" ]]; then\n  kubectl=$( kube::util::find-binary \"kubectl\" )\n\n  if [[ ! -x \"$kubectl\" ]]; then\n    {\n      echo \"It looks as if you don't have a compiled kubectl binary\"\n      echo\n      echo \"If you are running from a clone of the git repo, please run\"\n      echo \"'./build/run.sh make cross'. Note that this requires having\"\n      echo \"Docker installed.\"\n      echo\n      echo \"If you are running from a binary release tarball, something is wrong. \"\n      echo \"Look at http://kubernetes.io/ for information on how to contact the \"\n      echo \"development team for help.\"\n    } >&2\n    exit 1\n  fi\nelif [[ ! -x \"${KUBECTL_PATH}\" ]]; then\n  {\n    echo \"KUBECTL_PATH environment variable set to '${KUBECTL_PATH}', but \"\n    echo \"this doesn't seem to be a valid executable.\"\n  } >&2\n  exit 1\nfi\nkubectl=\"${KUBECTL_PATH:-${kubectl}}\"\n\nif [[ \"$KUBERNETES_PROVIDER\" == \"gke\" ]]; then\n  detect-project &> /dev/null\nelif [[ \"$KUBERNETES_PROVIDER\" == \"ubuntu\" ]]; then\n  detect-master > /dev/null\n  config=(\n    \"--server=http://${KUBE_MASTER_IP}:8080\"\n  )\nfi\n\n\nif false; then\n  # disable these debugging messages by default\n  echo \"current-context: \\\"$(${kubectl} \"${config[@]:+${config[@]}}\" config view -o template --template='{{index . \"current-context\"}}')\\\"\" >&2\n  echo \"Running:\" \"${kubectl}\" \"${config[@]:+${config[@]}}\" \"${@+$@}\" >&2\nfi\n\nif [[ \"${1:-}\" =~ ^(path)$ ]]; then\n  echo \"${kubectl}\"\n  exit 0\nfi\n\n\"${kubectl}\" \"${config[@]:+${config[@]}}\" \"${@+$@}\"\n\n", "num_lines": 88}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Validates that the cluster is healthy.\n# Error codes are:\n# 0 - success\n# 1 - fatal (cluster is unlikely to work)\n# 2 - non-fatal (encountered some errors, but cluster should be working correctly)\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nif [ -f \"${KUBE_ROOT}/cluster/env.sh\" ]; then\n  source \"${KUBE_ROOT}/cluster/env.sh\"\nfi\n\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\n# Run kubectl and retry upon failure.\nfunction kubectl_retry() {\n  tries=3\n  while ! \"${KUBE_ROOT}/cluster/kubectl.sh\" \"$@\"; do\n    tries=$((tries-1))\n    if [[ ${tries} -le 0 ]]; then\n      echo \"('kubectl $*' failed, giving up)\" >&2\n      return 1\n    fi\n    echo \"(kubectl failed, will retry ${tries} times)\" >&2\n    sleep 1\n  done\n}\n\nALLOWED_NOTREADY_NODES=\"${ALLOWED_NOTREADY_NODES:-0}\"\nCLUSTER_READY_ADDITIONAL_TIME_SECONDS=\"${CLUSTER_READY_ADDITIONAL_TIME_SECONDS:-30}\"\n\nif [[ \"${KUBERNETES_PROVIDER:-}\" == \"gce\" ]]; then\n  if [[ \"${KUBE_CREATE_NODES}\" == \"true\" ]]; then\n    EXPECTED_NUM_NODES=\"$(get-num-nodes)\"\n  else\n    EXPECTED_NUM_NODES=\"0\"\n  fi\n  echo \"Validating gce cluster, MULTIZONE=${MULTIZONE:-}\"\n  # In multizone mode we need to add instances for all nodes in the region.\n  if [[ \"${MULTIZONE:-}\" == \"true\" ]]; then\n    EXPECTED_NUM_NODES=$(gcloud -q compute instances list --project=\"${PROJECT}\" --format=\"[no-heading]\" \\\n      --filter=\"(name ~ '${NODE_INSTANCE_PREFIX}.*' OR name ~ '${WINDOWS_NODE_INSTANCE_PREFIX}.*') AND zone:($(gcloud -q compute zones list --project=\"${PROJECT}\" --filter=region=\"${REGION}\" --format=\"csv[no-heading](name)\" | tr \"\\n\" \",\" | sed  \"s/,$//\"))\" | wc -l)\n    echo \"Computing number of nodes, NODE_INSTANCE_PREFIX=${NODE_INSTANCE_PREFIX}, REGION=${REGION}, EXPECTED_NUM_NODES=${EXPECTED_NUM_NODES}\"\n  fi\nelse\n  EXPECTED_NUM_NODES=\"${NUM_NODES}\"\nfi\n\nif [[ \"${REGISTER_MASTER_KUBELET:-}\" == \"true\" ]]; then\n  if [[ \"${KUBERNETES_PROVIDER:-}\" == \"gce\" ]]; then\n    NUM_MASTERS=$(get-master-replicas-count)\n  else\n    NUM_MASTERS=1\n  fi\n  EXPECTED_NUM_NODES=$((EXPECTED_NUM_NODES+NUM_MASTERS))\nfi\n\nREQUIRED_NUM_NODES=$((EXPECTED_NUM_NODES - ALLOWED_NOTREADY_NODES))\n# Make several attempts to deal with slow cluster birth.\nreturn_value=0\nattempt=0\n# Set the timeout to ~25minutes (100 x 15 second) to avoid timeouts for 1000-node clusters.\nPAUSE_BETWEEN_ITERATIONS_SECONDS=15\nMAX_ATTEMPTS=100\nADDITIONAL_ITERATIONS=$(((CLUSTER_READY_ADDITIONAL_TIME_SECONDS + PAUSE_BETWEEN_ITERATIONS_SECONDS - 1)/PAUSE_BETWEEN_ITERATIONS_SECONDS))\nwhile true; do\n  # Pause between iterations of this large outer loop.\n  if [[ ${attempt} -gt 0 ]]; then\n    sleep 15\n  fi\n  attempt=$((attempt+1))\n\n  # The \"kubectl get nodes -o template\" exports node information.\n  #\n  # Echo the output and gather 2 counts:\n  #  - Total number of nodes.\n  #  - Number of \"ready\" nodes.\n  #\n  # Suppress errors from kubectl output because during cluster bootstrapping\n  # for clusters where the master node is registered, the apiserver will become\n  # available and then get restarted as the kubelet configures the docker bridge.\n  #\n  # We are assigning the result of kubectl_retry get nodes operation to the res\n  # variable in that way, to prevent stopping the whole script on an error.\n  #\n  # Bash command substitution $(kubectl_...) removes all trailing whitespaces\n  # which are important for line counting.\n  # Use trick from https://unix.stackexchange.com/a/383411 to avoid\n  # newline truncation.\n  node=$(kubectl_retry get nodes --no-headers; ret=$?; echo .; exit \"$ret\") && res=\"$?\" || res=\"$?\"\n  node=\"${node%.}\"\n  if [ \"${res}\" -ne \"0\" ]; then\n    if [[ \"${attempt}\" -gt \"${last_run:-$MAX_ATTEMPTS}\" ]]; then\n      echo -e \"${color_red:-} Failed to get nodes.${color_norm:-}\"\n      exit 1\n    else\n      continue\n    fi\n  fi\n  found=$(echo -n \"${node}\" | wc -l)\n  # Use grep || true so that empty result doesn't return nonzero exit code.\n  ready=$(echo -n \"${node}\" | grep -c -v \"NotReady\" || true)\n\n  if (( \"${found}\" == \"${EXPECTED_NUM_NODES}\" )) && (( \"${ready}\" == \"${EXPECTED_NUM_NODES}\")); then\n    break\n  elif (( \"${found}\" > \"${EXPECTED_NUM_NODES}\" )); then\n    if [[ \"${KUBE_USE_EXISTING_MASTER:-}\" != \"true\" ]]; then\n      echo -e \"${color_red}Found ${found} nodes, but expected ${EXPECTED_NUM_NODES}. Your cluster may not behave correctly.${color_norm}\"\n    fi\n    break\n  elif (( \"${ready}\" > \"${EXPECTED_NUM_NODES}\")); then\n    echo -e \"${color_red}Found ${ready} ready nodes, but expected ${EXPECTED_NUM_NODES}. Your cluster may not behave correctly.${color_norm}\"\n    break\n  else\n    if [[ \"${REQUIRED_NUM_NODES}\" -le \"${ready}\" ]]; then\n      echo -e \"${color_green:-}Found ${REQUIRED_NUM_NODES} Nodes, allowing additional ${ADDITIONAL_ITERATIONS} iterations for other Nodes to join.${color_norm}\"\n      last_run=\"${last_run:-$((attempt + ADDITIONAL_ITERATIONS - 1))}\"\n    fi\n    if [[ \"${attempt}\" -gt \"${last_run:-$MAX_ATTEMPTS}\" ]]; then\n      echo -e \"${color_yellow:-}Detected ${ready} ready nodes, found ${found} nodes out of expected ${EXPECTED_NUM_NODES}. Your cluster may not be fully functional.${color_norm}\"\n      kubectl_retry get nodes\n      if [[ \"${REQUIRED_NUM_NODES}\" -gt \"${ready}\" ]]; then\n        exit 1\n      else\n        return_value=2\n        break\n      fi\n    else\n      echo -e \"${color_yellow}Waiting for ${EXPECTED_NUM_NODES} ready nodes. ${ready} ready nodes, ${found} registered. Retrying.${color_norm}\"\n    fi\n  fi\ndone\necho \"Found ${found} node(s).\"\nkubectl_retry get nodes\n\nattempt=0\nwhile true; do\n  # The \"kubectl componentstatuses -o template\" exports components health information.\n  #\n  # Echo the output and gather 2 counts:\n  #  - Total number of componentstatuses.\n  #  - Number of \"healthy\" components.\n  cs_status=$(kubectl_retry get componentstatuses -o template --template='{{range .items}}{{with index .conditions 0}}{{.type}}:{{.status}}{{end}}{{\"\\n\"}}{{end}}') || true\n  componentstatuses=$(echo \"${cs_status}\" | grep -c 'Healthy:') || true\n  healthy=$(echo \"${cs_status}\" | grep -c 'Healthy:True') || true\n\n  if ((componentstatuses > healthy)) || ((componentstatuses == 0)); then\n    if ((attempt < 5)); then\n      echo -e \"${color_yellow}Cluster not working yet.${color_norm}\"\n      attempt=$((attempt+1))\n      sleep 30\n    else\n      echo -e \" ${color_yellow}Validate output:${color_norm}\"\n      kubectl_retry get cs\n      echo -e \"${color_red}Validation returned one or more failed components. Cluster is probably broken.${color_norm}\"\n      exit 1\n    fi\n  else\n    break\n  fi\ndone\n\necho \"Validate output:\"\nkubectl_retry get cs || true\nif [ \"${return_value}\" == \"0\" ]; then\n  echo -e \"${color_green}Cluster validation succeeded${color_norm}\"\nelse\n  echo -e \"${color_yellow}Cluster validation encountered some problems, but cluster should be in working order${color_norm}\"\nfi\n\nexit \"${return_value}\"\n", "num_lines": 193}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Import required functions. The addon manager is installed to /opt in\n# production use (see the Dockerfile)\n# Disabling shellcheck following files as the full path would be required.\nif [ -f \"kube-addons.sh\" ]; then\n  # shellcheck disable=SC1091\n  source \"kube-addons.sh\"\nelif [ -f \"/opt/kube-addons.sh\" ]; then\n  # shellcheck disable=SC1091\n  source \"/opt/kube-addons.sh\"\nelse\n  # If the required source is missing, we have to fail.\n  log ERR \"== Could not find kube-addons.sh (not in working directory or /opt) at $(date -Is) ==\"\n  exit 1\nfi\n\n# The business logic for whether a given object should be created\n# was already enforced by salt, and /etc/kubernetes/addons is the\n# managed result of that. Start everything below that directory.\nlog INFO \"== Kubernetes addon manager started at $(date -Is) with ADDON_CHECK_INTERVAL_SEC=${ADDON_CHECK_INTERVAL_SEC} ==\"\n\n# Wait for the default service account to be created in the kube-system namespace.\ntoken_found=\"\"\nwhile [ -z \"${token_found}\" ]; do\n  sleep .5\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  if ! token_found=$(${KUBECTL} ${KUBECTL_OPTS} get --namespace=\"${SYSTEM_NAMESPACE}\" serviceaccount default -o go-template=\"{{with index .secrets 0}}{{.name}}{{end}}\"); then\n    token_found=\"\";\n    log WRN \"== Error getting default service account, retry in 0.5 second ==\"\n  fi\ndone\n\nlog INFO \"== Default service account in the ${SYSTEM_NAMESPACE} namespace has token ${token_found} ==\"\n\n# Create admission_control objects if defined before any other addon services. If the limits\n# are defined in a namespace other than default, we should still create the limits for the\n# default namespace.\nwhile IFS=$'\\n' read -r obj; do\n  start_addon \"${obj}\" 100 10 default &\n  log INFO \"++ obj ${obj} is created ++\"\ndone < <(find /etc/kubernetes/admission-controls \\( -name \\*.yaml -o -name \\*.json \\))\n\n# Start the apply loop.\n# Check if the configuration has changed recently - in case the user\n# created/updated/deleted the files on the master.\nlog INFO \"== Entering periodical apply loop at $(date -Is) ==\"\nwhile true; do\n  start_sec=$(date +\"%s\")\n  if is_leader; then\n    ensure_addons\n    reconcile_addons\n  else\n    log INFO \"Not elected leader, going back to sleep.\"\n  fi\n  end_sec=$(date +\"%s\")\n  len_sec=$((end_sec-start_sec))\n  # subtract the time passed from the sleep time\n  if [[ ${len_sec} -lt ${ADDON_CHECK_INTERVAL_SEC} ]]; then\n    sleep_time=$((ADDON_CHECK_INTERVAL_SEC-len_sec))\n    sleep ${sleep_time}\n  fi\ndone\n", "num_lines": 79}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# These tests enforce behavior of kube-addon-manager functions against a real\n# cluster. A working Kubernetes cluster must be set up with kubectl configured.\n# To run with the released version of kubectl, use `make test`.\n\nset -o errexit\nset -o pipefail\nset -o nounset\n\n# Default kubectl to the test users installation if needed.\nKUBECTL_BIN=\"${KUBECTL_BIN:-kubectl}\"\n\n# Disabling shellcheck following files as the full path would be required.\n# shellcheck disable=SC1091\nsource \"kube-addons.sh\"\n\nTEST_NS=\"kube-addon-manager-test\"\n\nfunction retry() {\n  local tries=10\n  while [ \"${tries}\" -gt 0 ]; do\n    \"$@\" && return 0;\n    (( tries-- ))\n    sleep 1\n  done\n}\n\nfunction setup(){\n  retry kubectl create namespace \"${TEST_NS}\"\n}\n\nfunction teardown() {\n  retry kubectl delete namespace \"${TEST_NS}\"\n}\n\nfunction error() {\n  echo -e \"\\e[31m$*\\e[0m\"\n}\n\nfunction echo_green() {\n  echo -e \"\\e[32m$*\\e[0m\"\n}\n\nfunction echo_blue() {\n  echo -e \"\\e[34m$*\\e[0m\"\n}\n\nfunction test_create_resource_reconcile() {\n  local limitrange\n  read -r -d '' limitrange << EOF\napiVersion: \"v1\"\nkind: \"LimitRange\"\nmetadata:\n  name: \"limits\"\n  namespace: \"${TEST_NS}\"\n  labels:\n    addonmanager.kubernetes.io/mode: Reconcile\nspec:\n  limits:\n    - type: \"Container\"\n      defaultRequest:\n        cpu: \"100m\"\nEOF\n\n  # arguments are yaml text, number of tries, delay, name of file, and namespace\n  echo_blue \"Creating initial resource to test Reconcile mode\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! (kubectl get limits/limits -n \"${TEST_NS}\"); then\n    error \"failed to create limits w/ reconcile\"\n    return 1\n  elif ! (kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"); then\n    error \"limits does not match applied config\"\n    return 1\n  fi\n\n  # Changes to addons with mode reconcile should be reflected.\n  echo_blue \"Changes to manifest should be reflected in the cluster\"\n  limitrange=\"${limitrange//100m/50m}\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"; then\n    error \"failed to update resource, still has 100m\"\n    return 1\n  elif ! (kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"50m\"); then\n    error \"failed to update resource, 50m limit was not reflected\"\n    return 1\n  fi\n\n  # Finally, the users configuration will not be respected.\n  echo_blue \"Changes the user makes should be overwritten by kube-addon-manager\"\n  EDITOR=\"sed -i 's/50m/600m/'\" kubectl edit limits/limits -n ${TEST_NS}\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"50m\"; then\n    error \"failed to edit resource with sed -- test is broken\"\n    return 1\n  fi\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! ( kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"50m\"); then\n    error \"failed to update resource, user config was respected when it should have been rewritten\"\n    return 1\n  fi\n}\n\nfunction test_create_resource_ensureexists() {\n  local limitrange\n  read -r -d '' limitrange << EOF\napiVersion: \"v1\"\nkind: \"LimitRange\"\nmetadata:\n  name: \"limits\"\n  namespace: \"${TEST_NS}\"\n  labels:\n    addonmanager.kubernetes.io/mode: EnsureExists\nspec:\n  limits:\n    - type: \"Container\"\n      defaultRequest:\n        cpu: \"100m\"\nEOF\n\n  # arguments are yaml text, number of tries, delay, name of file, and namespace\n  echo_blue \"Creating initial resource to test mode EnsureExists\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! (kubectl get limits/limits -n \"${TEST_NS}\"); then\n    error \"failed to create limits w/ EnsureExists\"\n    return 1\n  elif ! (kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"); then\n    error \"limits does not match applied config\"\n    return 1\n  fi\n\n  # Changes to addons with mode EnsureExists should NOT be reflected.\n  echo_blue \"Changes to the manifest should not be reconciled with the cluster\"\n  limitrange=\"${limitrange//100m/50m}\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"50m\"; then\n    error \"failed to respect existing resource, was overwritten despite EnsureExists\"\n    return 1\n  fi\n\n  # the users configuration must be respected\n  echo_blue \"User configuration will be persisted for EnsureExists\"\n  EDITOR=\"sed -i 's/100m/600m/'\" kubectl edit limits/limits -n ${TEST_NS}\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"; then\n    error \"failed to edit resource with sed -- test is broken\"\n    return 1\n  fi\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"; then\n    error \"failed to respect user changes to EnsureExists object\"\n    return 1\n  fi\n\n  # unless they delete the object, in which case it should return\n  echo_blue \"Missing EnsureExists resources will be re-created\"\n  kubectl delete limits/limits -n ${TEST_NS}\n  if kubectl get limits/limits -n ${TEST_NS}; then\n    error \"failed to delete limitrange\"\n    return 1\n  fi\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! kubectl get limits/limits -n ${TEST_NS}; then\n    error \"failed to recreate deleted EnsureExists resource\"\n    return 1\n  fi\n}\n\nfunction test_create_multiresource() {\n  local limitrange\n  read -r -d '' limitrange << EOF\napiVersion: \"v1\"\nkind: \"LimitRange\"\nmetadata:\n  name: \"limits\"\n  namespace: \"${TEST_NS}\"\n  labels:\n    addonmanager.kubernetes.io/mode: EnsureExists\nspec:\n  limits:\n    - type: \"Container\"\n      defaultRequest:\n        cpu: \"100m\"\n---\napiVersion: \"v1\"\nkind: \"LimitRange\"\nmetadata:\n  name: \"limits2\"\n  namespace: \"${TEST_NS}\"\n  labels:\n    addonmanager.kubernetes.io/mode: Reconcile\nspec:\n  limits:\n    - type: \"Container\"\n      defaultRequest:\n        cpu: \"100m\"\nEOF\n\n  # arguments are yaml text, number of tries, delay, name of file, and namespace\n  echo_blue \"Creating initial resources from multi-resource manifest\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! (kubectl get limits/limits -n \"${TEST_NS}\"); then\n    error \"failed to create limits w/ EnsureExists\"\n    return 1\n  elif ! (kubectl get limits/limits2 -n \"${TEST_NS}\"); then\n    error \"failed to create limits2 w/ Reconcile\"\n    return 1\n  fi\n\n  # Changes to addons with mode EnsureExists should NOT be reflected.\n  # However, the mode=Reconcile addon should be changed.\n  echo_blue \"Multi-resource manifest changes should apply to EnsureExists, not Reconcile\"\n  limitrange=\"${limitrange//100m/50m}\"\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"50m\"; then\n    error \"failed to respect existing resource, was overwritten despite EnsureExists\"\n    return 1\n  elif kubectl get limits/limits2 -n ${TEST_NS} | grep --silent \"100m\"; then\n    error \"failed to update resource with mode Reconcile\"\n    return 1\n  fi\n\n  # the users configuration must be respected for EnsureExists\n  echo_blue \"Multi-resource manifest should not overwrite user config in EnsureExists\"\n  EDITOR=\"sed -i 's/100m/600m/'\" kubectl edit limits/limits -n ${TEST_NS}\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"; then\n    error \"failed to edit resource with sed -- test is broken\"\n    return 1\n  fi\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if kubectl get limits/limits -n ${TEST_NS} -o yaml | grep --silent \"100m\"; then\n    error \"failed to respect user changes to EnsureExists object\"\n    return 1\n  fi\n\n  # But not for Reconcile.\n  echo_blue \"Multi-resource manifest should overwrite user config in EnsureExists\"\n  EDITOR=\"sed -i 's/50m/600m/'\" kubectl edit limits/limits2 -n ${TEST_NS}\n  if kubectl get limits/limits2 -n ${TEST_NS} -o yaml | grep --silent \"50m\"; then\n    error \"failed to edit resource with sed -- test is broken\"\n    return 1\n  fi\n  create_resource_from_string \"${limitrange}\" \"10\" \"1\" \"limitrange.yaml\" \"${TEST_NS}\"\n  if ! ( kubectl get limits/limits2 -n ${TEST_NS} -o yaml | grep --silent \"50m\"); then\n    error \"failed to update resource, user config was respected when it should have been rewritten\"\n    return 1\n  fi\n}\n\nfunction test_func() {\n  local -r name=\"${1}\"\n\n  echo_blue \"=== TEST ${name}\"\n  setup\n  if ! \"${name}\"; then\n    failures=$((failures+1))\n    error \"=== FAIL\"\n  else\n    echo_green \"=== PASS\"\n  fi\n  teardown\n}\n\nfailures=0\ntest_func test_create_resource_reconcile\ntest_func test_create_resource_ensureexists\ntest_func test_create_multiresource\nif [ \"${failures}\" -gt 0 ]; then\n  error \"no. failed tests: ${failures}\"\n  error \"FAIL\"\n  exit 1\nelse\n  echo_green \"PASS\"\nfi\n", "num_lines": 287}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# LIMITATIONS\n# 1. Exit code is probably not always correct.\n# 2. There are no unittests.\n# 3. Will not work if the total length of paths to addons is greater than\n#    bash can handle. Probably it is not a problem: ARG_MAX=2097152 on GCE.\n\n# cosmetic improvements to be done\n# 1. Improve the log function; add timestamp, file name, etc.\n# 2. Logging doesn't work from files that print things out.\n# 3. Kubectl prints the output to stderr (the output should be captured and then\n#    logged)\n\nKUBECTL=${KUBECTL_BIN:-/usr/local/bin/kubectl}\nKUBECTL_OPTS=${KUBECTL_OPTS:-}\n# KUBECTL_PRUNE_WHITELIST is a list of resources whitelisted by default.\n# This is currently the same with the default in:\n# https://github.com/kubernetes/kubectl/blob/master/pkg/cmd/apply/prune.go.\n# To override the default list with other values, set\n# KUBECTL_PRUNE_WHITELIST_OVERRIDE environment variable to space-separated\n# names of resources to whitelist.\nif [ -z \"${KUBECTL_PRUNE_WHITELIST_OVERRIDE:-}\" ]; then\n  KUBECTL_PRUNE_WHITELIST=(\n    core/v1/ConfigMap\n    core/v1/Endpoints\n    core/v1/Namespace\n    core/v1/PersistentVolumeClaim\n    core/v1/PersistentVolume\n    core/v1/Pod\n    core/v1/ReplicationController\n    core/v1/Secret\n    core/v1/Service\n    batch/v1/Job\n    batch/v1/CronJob\n    apps/v1/DaemonSet\n    apps/v1/Deployment\n    apps/v1/ReplicaSet\n    apps/v1/StatefulSet\n    networking.k8s.io/v1/Ingress\n  )\nelse\n  read -ra KUBECTL_PRUNE_WHITELIST <<< \"${KUBECTL_PRUNE_WHITELIST_OVERRIDE}\"\nfi\n\n# This variable is unused in this file, but not in those that source it.\n# shellcheck disable=SC2034\nADDON_CHECK_INTERVAL_SEC=${TEST_ADDON_CHECK_INTERVAL_SEC:-60}\nADDON_PATH=${ADDON_PATH:-/etc/kubernetes/addons}\n\n# This variable is unused in this file, but not in those that source it.\n# shellcheck disable=SC2034\nSYSTEM_NAMESPACE=kube-system\n\n# Addons could use this label with two modes:\n# - ADDON_MANAGER_LABEL=Reconcile\n# - ADDON_MANAGER_LABEL=EnsureExists\nADDON_MANAGER_LABEL=\"addonmanager.kubernetes.io/mode\"\n# This label is deprecated (only for Addon Manager). In future release\n# addon-manager may not respect it anymore. Addons with\n# CLUSTER_SERVICE_LABEL=true and without ADDON_MANAGER_LABEL=EnsureExists\n# will be reconciled for now.\nCLUSTER_SERVICE_LABEL=\"kubernetes.io/cluster-service\"\n\n# Whether only one addon manager should be running in a multi-master setup.\n# Disabling this flag will force all addon managers to assume they are the\n# leaders.\nADDON_MANAGER_LEADER_ELECTION=${ADDON_MANAGER_LEADER_ELECTION:-true}\n\n# Remember that you can't log from functions that print some output (because\n# logs are also printed on stdout).\n# $1 level\n# $2 message\nfunction log() {\n  # manage log levels manually here\n\n  # add the timestamp if you find it useful\n  case $1 in\n    DB3 )\n#        echo \"$1: $2\"\n        ;;\n    DB2 )\n#        echo \"$1: $2\"\n        ;;\n    DBG )\n#        echo \"$1: $2\"\n        ;;\n    INFO )\n        echo \"$1: $2\"\n        ;;\n    WRN )\n        echo \"$1: $2\"\n        ;;\n    ERR )\n        echo \"$1: $2\"\n        ;;\n    * )\n        echo \"INVALID_LOG_LEVEL $1: $2\"\n        ;;\n  esac\n}\n\n# Generate kubectl prune-whitelist flags from provided resource list.\nfunction generate_prune_whitelist_flags() {\n  local -r resources=( \"$@\" )\n  for resource in \"${resources[@]}\"; do\n    # Check if $resource isn't composed just of whitespaces by replacing ' '\n    # with '' and checking whether the resulting string is not empty.\n    if [[ -n \"${resource// /}\" ]]; then\n      printf \"%s\" \"--prune-whitelist ${resource} \"\n    fi\n  done\n}\n\n# KUBECTL_EXTRA_PRUNE_WHITELIST is a list of extra whitelisted resources\n# besides the default ones.\nextra_prune_whitelist=\nif [ -n \"${KUBECTL_EXTRA_PRUNE_WHITELIST:-}\" ]; then\n  read -ra extra_prune_whitelist <<< \"${KUBECTL_EXTRA_PRUNE_WHITELIST}\"\nfi\nprune_whitelist=( \"${KUBECTL_PRUNE_WHITELIST[@]}\"  \"${extra_prune_whitelist[@]}\" )\nprune_whitelist_flags=$(generate_prune_whitelist_flags \"${prune_whitelist[@]}\")\n\nlog INFO \"== Generated kubectl prune whitelist flags: $prune_whitelist_flags ==\"\n\n# $1 filename of addon to start.\n# $2 count of tries to start the addon.\n# $3 delay in seconds between two consecutive tries\n# $4 namespace\nfunction start_addon() {\n  local -r addon_filename=$1;\n  local -r tries=$2;\n  local -r delay=$3;\n  local -r namespace=$4\n\n  create_resource_from_string \"$(cat \"${addon_filename}\")\" \"${tries}\" \"${delay}\" \"${addon_filename}\" \"${namespace}\"\n}\n\n# $1 string with json or yaml.\n# $2 count of tries to start the addon.\n# $3 delay in seconds between two consecutive tries\n# $4 name of this object to use when logging about it.\n# $5 namespace for this object\nfunction create_resource_from_string() {\n  local -r config_string=$1;\n  local tries=$2;\n  local -r delay=$3;\n  local -r config_name=$4;\n  local -r namespace=$5;\n  while [ \"${tries}\" -gt 0 ]; do\n    reconcile_resource_from_string \"${config_string}\" \"${config_name}\" \"${namespace}\" && \\\n      ensure_resource_from_string \"${config_string}\" \"${config_name}\" \"${namespace}\" && \\\n      return 0;\n    (( tries-- ))\n    log WRN \"== Failed to start ${config_name} in namespace ${namespace} at $(date -Is). ${tries} tries remaining. ==\"\n    sleep \"${delay}\";\n  done\n  return 1;\n}\n\n# Creates resources with addon mode Reconcile for create_resource_from_string.\n# Does not perform pruning.\n# $1 string with json or yaml.\n# $2 name of this object for logging\n# $3 namespace for the object\nfunction reconcile_resource_from_string() {\n  local -r config_string=$1;\n  local -r config_name=$2;\n  local -r namespace=$3;\n\n  # kubectl_output must be declared ahead of time to allow capturing kubectl's exit code and not local's exit code.\n  local kubectl_output;\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  kubectl_output=$(echo \"${config_string}\" | ${KUBECTL} ${KUBECTL_OPTS} apply -f - \\\n    --namespace=\"${namespace}\" -l ${ADDON_MANAGER_LABEL}=Reconcile 2>&1) && \\\n      log INFO \"== Successfully reconciled ${config_name} in namespace ${namespace} at $(date -Is)\" && \\\n      return 0;\n  if echo \"${kubectl_output}\" | grep --silent \"no objects\"; then\n    # Nothing to do.\n    return 0;\n  fi\n  echo \"${kubectl_output}\" # for visibility of errors\n  return 1;\n}\n\n# Creates resources with addon mode EnsureExists for create_resource_from_string.\n# Does not perform pruning.\n# $1 string with json or yaml.\n# $2 name of this object for logging\n# $3 namespace for the object\nfunction ensure_resource_from_string() {\n  local -r config_string=$1;\n  local -r config_name=$2;\n  local -r namespace=$3;\n\n  # Resources that are set to the addon mode EnsureExists should not be overwritten if they already exist.\n  local kubectl_output;\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  kubectl_output=$(echo \"${config_string}\" | ${KUBECTL} ${KUBECTL_OPTS} create -f - \\\n    --namespace=\"${namespace}\" -l ${ADDON_MANAGER_LABEL}=EnsureExists 2>&1) && \\\n      log INFO \"== Successfully started ${config_name} in namespace ${namespace} at $(date -Is)\" && \\\n      return 0;\n  # Detect an already exists failure for creating EnsureExists resources.\n  # All other errors should result in a retry.\n  if echo \"${kubectl_output}\" | grep --silent \"AlreadyExists\"; then\n    log INFO \"== Skipping start ${config_name} in namespace ${namespace}, already exists at $(date -Is)\"\n    return 0;\n  elif echo \"${kubectl_output}\" | grep --silent \"no objects\"; then\n    # Nothing to do.\n    return 0;\n  fi\n  echo \"${kubectl_output}\" # for visibility of errors\n  return 1;\n}\n\nfunction reconcile_addons() {\n  # TODO: Remove the first command in future release.\n  # Adding this for backward compatibility. Old addons have CLUSTER_SERVICE_LABEL=true and don't have\n  # ADDON_MANAGER_LABEL=EnsureExists will still be reconciled.\n  # Filter out `configured` message to not noisily log.\n  # `created`, `pruned` and errors will be logged.\n  log INFO \"== Reconciling with deprecated label ==\"\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  ${KUBECTL} ${KUBECTL_OPTS} apply -f ${ADDON_PATH} \\\n    -l ${CLUSTER_SERVICE_LABEL}=true,${ADDON_MANAGER_LABEL}!=EnsureExists \\\n    --prune=true ${prune_whitelist_flags} --recursive | grep -v configured\n\n  log INFO \"== Reconciling with addon-manager label ==\"\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  ${KUBECTL} ${KUBECTL_OPTS} apply -f ${ADDON_PATH} \\\n    -l ${CLUSTER_SERVICE_LABEL}!=true,${ADDON_MANAGER_LABEL}=Reconcile \\\n    --prune=true ${prune_whitelist_flags} --recursive | grep -v configured\n\n  log INFO \"== Kubernetes addon reconcile completed at $(date -Is) ==\"\n}\n\nfunction ensure_addons() {\n  # Create objects already exist should fail.\n  # Filter out `AlreadyExists` message to not noisily log.\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  ${KUBECTL} ${KUBECTL_OPTS} create -f ${ADDON_PATH} \\\n    -l ${ADDON_MANAGER_LABEL}=EnsureExists --recursive 2>&1 | grep -v AlreadyExists\n\n  log INFO \"== Kubernetes addon ensure completed at $(date -Is) ==\"\n}\n\nfunction is_leader() {\n  # In multi-master setup, only one addon manager should be running. We use\n  # existing leader election in kube-controller-manager instead of implementing\n  # a separate mechanism here.\n  if ! $ADDON_MANAGER_LEADER_ELECTION; then\n    log INFO \"Leader election disabled.\"\n    return 0;\n  fi\n  # shellcheck disable=SC2086\n  # Disabling because \"${KUBECTL_OPTS}\" needs to allow for expansion here\n  KUBE_CONTROLLER_MANAGER_LEADER=$(${KUBECTL} ${KUBECTL_OPTS} -n kube-system get leases.v1.coordination.k8s.io kube-controller-manager -o \"jsonpath={.spec.holderIdentity}\")\n\n  case \"${KUBE_CONTROLLER_MANAGER_LEADER}\" in\n  \"\")\n    log ERR \"No leader election info found.\"\n    return 1\n    ;;\n\n  \"${HOSTNAME}\"_*)\n    log INFO \"Leader is $KUBE_CONTROLLER_MANAGER_LEADER\"\n    return 0\n    ;;\n\n  *)\n    log INFO \"Leader is $KUBE_CONTROLLER_MANAGER_LEADER, not ${HOSTNAME}_*\"\n    return 1\n    ;;\n  esac\n}\n", "num_lines": 295}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -ex\n\nexport NODE_NAME=${NODE_NAME:-${HOSTNAME}}\nexport NODE_MASTER=${NODE_MASTER:-true}\nexport NODE_DATA=${NODE_DATA:-true}\nexport HTTP_PORT=${HTTP_PORT:-9200}\nexport TRANSPORT_PORT=${TRANSPORT_PORT:-9300}\nexport MINIMUM_MASTER_NODES=${MINIMUM_MASTER_NODES:-2}\n\nchown -R elasticsearch:elasticsearch /data\n\n./bin/elasticsearch_logging_discovery >> ./config/elasticsearch.yml\nexec su elasticsearch -c /usr/local/bin/docker-entrypoint.sh\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# These steps must be executed once the host /var and /lib volumes have\n# been mounted, and therefore cannot be done in the docker build stage.\n\n# For systems without journald\nmkdir -p /var/log/journal\n\n# set ld preload\nif dpkg --print-architecture | grep -q amd64;then\n    export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libjemalloc.so.2\nelse\n    export LD_PRELOAD=/usr/lib/aarch64-linux-gnu/libjemalloc.so.2\nfi\n\n# Use exec to get the signal\n# A non-quoted string and add the comment to prevent shellcheck failures on this line.\n# See https://github.com/koalaman/shellcheck/wiki/SC2086\n# shellcheck disable=SC2086\nexec /usr/local/bundle/bin/fluentd $FLUENTD_ARGS\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Returns the total number of Linux and Windows nodes in the cluster.\n#\n# Vars assumed:\n#   NUM_NODES\n#   NUM_WINDOWS_NODES\nfunction get-num-nodes {\n  echo \"$((NUM_NODES + NUM_WINDOWS_NODES))\"\n}\n\n# Vars assumed:\n#   NUM_NODES\n#   NUM_WINDOWS_NODES\nfunction get-master-size {\n  local suggested_master_size=1\n  if [[ \"$(get-num-nodes)\" -gt \"5\" ]]; then\n    suggested_master_size=2\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"10\" ]]; then\n    suggested_master_size=4\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"50\" ]]; then\n    suggested_master_size=8\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"100\" ]]; then\n    suggested_master_size=16\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"500\" ]]; then\n    suggested_master_size=32\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"2000\" ]]; then\n    suggested_master_size=64\n  fi\n  echo \"${suggested_master_size}\"\n}\n\n# Vars assumed:\n#   NUM_NODES\n#   NUM_WINDOWS_NODES\nfunction get-master-root-disk-size() {\n  local suggested_master_root_disk_size=\"20GB\"\n  if [[ \"$(get-num-nodes)\" -gt \"500\" ]]; then\n    suggested_master_root_disk_size=\"100GB\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"3000\" ]]; then\n    suggested_master_root_disk_size=\"500GB\"\n  fi\n  echo \"${suggested_master_root_disk_size}\"\n}\n\n# Vars assumed:\n#   NUM_NODES\n#   NUM_WINDOWS_NODES\nfunction get-master-disk-size() {\n  local suggested_master_disk_size=\"20GB\"\n  if [[ \"$(get-num-nodes)\" -gt \"500\" ]]; then\n    suggested_master_disk_size=\"100GB\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt \"3000\" ]]; then\n    suggested_master_disk_size=\"200GB\"\n  fi\n  echo \"${suggested_master_disk_size}\"\n}\n\nfunction get-node-ip-range {\n  if [[ -n \"${NODE_IP_RANGE:-}\" ]]; then\n    echo \"${NODE_IP_RANGE}\"\n    return\n  fi\n  local suggested_range=\"10.40.0.0/22\"\n  if [[ \"$(get-num-nodes)\" -gt 1000 ]]; then\n    suggested_range=\"10.40.0.0/21\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 2000 ]]; then\n    suggested_range=\"10.40.0.0/20\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 4000 ]]; then\n    suggested_range=\"10.40.0.0/19\"\n  fi\n  echo \"${suggested_range}\"\n}\n\nfunction get-cluster-ip-range {\n  local suggested_range=\"10.64.0.0/14\"\n  if [[ \"$(get-num-nodes)\" -gt 1000 ]]; then\n    suggested_range=\"10.64.0.0/13\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 2000 ]]; then\n    suggested_range=\"10.64.0.0/12\"\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 4000 ]]; then\n    suggested_range=\"10.64.0.0/11\"\n  fi\n  echo \"${suggested_range}\"\n}\n\n# Calculate ip alias range based on max number of pods.\n# Let pow be the smallest integer which is bigger or equal to log2($1 * 2).\n# (32 - pow) will be returned.\n#\n# $1: The number of max pods limitation.\nfunction get-alias-range-size() {\n  for pow in {0..31}; do\n    if (( 1 << pow >= $1 * 2 )); then\n      echo $((32 - pow))\n      return 0\n    fi\n  done\n}\n# NOTE: Avoid giving nodes empty scopes, because kubelet needs a service account\n# in order to initialize properly.\nNODE_SCOPES=\"${NODE_SCOPES:-monitoring,logging-write,storage-ro}\"\n\n# Below exported vars are used in cluster/gce/util.sh (or maybe somewhere else),\n# please remove those vars when not needed any more.\n\n# Root directory for Kubernetes files on Windows nodes.\nWINDOWS_K8S_DIR=\"C:\\etc\\kubernetes\"\n# Directory where Kubernetes binaries will be installed on Windows nodes.\nexport WINDOWS_NODE_DIR=\"${WINDOWS_K8S_DIR}\\node\\bin\"\n# Directory where Kubernetes log files will be stored on Windows nodes.\nexport WINDOWS_LOGS_DIR=\"${WINDOWS_K8S_DIR}\\logs\"\n# Directory where CNI binaries will be stored on Windows nodes.\nexport WINDOWS_CNI_DIR=\"${WINDOWS_K8S_DIR}\\cni\"\n# Directory where CNI config files will be stored on Windows nodes.\nexport WINDOWS_CNI_CONFIG_DIR=\"${WINDOWS_K8S_DIR}\\cni\\config\"\n# CNI storage path for Windows nodes\nexport WINDOWS_CNI_STORAGE_PATH=\"https://storage.googleapis.com/k8s-artifacts-cni/release\"\n# CNI version for Windows nodes\nexport WINDOWS_CNI_VERSION=\"v0.9.1\"\n# Pod manifests directory for Windows nodes on Windows nodes.\nexport WINDOWS_MANIFESTS_DIR=\"${WINDOWS_K8S_DIR}\\manifests\"\n# Directory where cert/key files will be stores on Windows nodes.\nexport WINDOWS_PKI_DIR=\"${WINDOWS_K8S_DIR}\\pki\"\n# Location of the certificates file on Windows nodes.\nexport WINDOWS_CA_FILE=\"${WINDOWS_PKI_DIR}\\ca-certificates.crt\"\n# Path for kubelet config file on Windows nodes.\nexport WINDOWS_KUBELET_CONFIG_FILE=\"${WINDOWS_K8S_DIR}\\kubelet-config.yaml\"\n# Path for kubeconfig file on Windows nodes.\nexport WINDOWS_KUBECONFIG_FILE=\"${WINDOWS_K8S_DIR}\\kubelet.kubeconfig\"\n# Path for bootstrap kubeconfig file on Windows nodes.\nexport WINDOWS_BOOTSTRAP_KUBECONFIG_FILE=\"${WINDOWS_K8S_DIR}\\kubelet.bootstrap-kubeconfig\"\n# Path for kube-proxy kubeconfig file on Windows nodes.\nexport WINDOWS_KUBEPROXY_KUBECONFIG_FILE=\"${WINDOWS_K8S_DIR}\\kubeproxy.kubeconfig\"\n# Path for kube-proxy kubeconfig file on Windows nodes.\nexport WINDOWS_NODEPROBLEMDETECTOR_KUBECONFIG_FILE=\"${WINDOWS_K8S_DIR}\\node-problem-detector.kubeconfig\"\n# Pause container image for Windows container.\nexport WINDOWS_INFRA_CONTAINER=\"k8s.gcr.io/pause:3.5\"\n# Storage Path for csi-proxy. csi-proxy only needs to be installed for Windows.\nexport CSI_PROXY_STORAGE_PATH=\"https://storage.googleapis.com/gke-release/csi-proxy\"\n# Version for csi-proxy\nexport CSI_PROXY_VERSION=\"${CSI_PROXY_VERSION:-v0.2.2-gke.0}\"\n", "num_lines": 168}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# TODO(jbeda): Provide a way to override project\n# gcloud multiplexing for shared GCE/GKE tests.\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/cluster/gce/config-common.sh\"\n\n# Specifying KUBE_GCE_API_ENDPOINT will override the default GCE Compute API endpoint (https://www.googleapis.com/compute/v1/).\n# This endpoint has to be pointing to v1 api. For example, https://www.googleapis.com/compute/staging_v1/\nexport GCE_API_ENDPOINT=${KUBE_GCE_API_ENDPOINT:-}\nexport GCLOUD=gcloud\nZONE=${KUBE_GCE_ZONE:-us-central1-b}\nexport REGION=${ZONE%-*}\nRELEASE_REGION_FALLBACK=${RELEASE_REGION_FALLBACK:-false}\nREGIONAL_KUBE_ADDONS=${REGIONAL_KUBE_ADDONS:-true}\n# TODO: Migrate to e2-standard machine family.\nNODE_SIZE=${NODE_SIZE:-n1-standard-2}\nNUM_NODES=${NUM_NODES:-3}\nNUM_WINDOWS_NODES=${NUM_WINDOWS_NODES:-0}\n# TODO: Migrate to e2-standard machine family.\nMASTER_SIZE=${MASTER_SIZE:-n1-standard-$(get-master-size)}\nMASTER_MIN_CPU_ARCHITECTURE=${MASTER_MIN_CPU_ARCHITECTURE:-} # To allow choosing better architectures.\nexport MASTER_DISK_TYPE=pd-ssd\nMASTER_DISK_SIZE=${MASTER_DISK_SIZE:-$(get-master-disk-size)}\nMASTER_ROOT_DISK_SIZE=${MASTER_ROOT_DISK_SIZE:-$(get-master-root-disk-size)}\nNODE_DISK_TYPE=${NODE_DISK_TYPE:-pd-standard}\nNODE_DISK_SIZE=${NODE_DISK_SIZE:-100GB}\nNODE_LOCAL_SSDS=${NODE_LOCAL_SSDS:-0}\nNODE_LABELS=\"${KUBE_NODE_LABELS:-}\"\nWINDOWS_NODE_LABELS=\"${WINDOWS_NODE_LABELS:-}\"\nNODE_LOCAL_SSDS_EPHEMERAL=${NODE_LOCAL_SSDS_EPHEMERAL:-}\n\n# KUBE_CREATE_NODES can be used to avoid creating nodes, while master will be sized for NUM_NODES nodes.\n# Firewalls and node templates are still created.\nKUBE_CREATE_NODES=\"${KUBE_CREATE_NODES:-true}\"\n\n# An extension to local SSDs allowing users to specify block/fs and SCSI/NVMe devices\n# Format of this variable will be \"#,scsi/nvme,block/fs\" you can specify multiple\n# configurations by separating them by a semi-colon ex. \"2,scsi,fs;1,nvme,block\"\n# is a request for 2 SCSI formatted and mounted SSDs and 1 NVMe block device SSD.\nNODE_LOCAL_SSDS_EXT=${NODE_LOCAL_SSDS_EXT:-}\n# Accelerators to be attached to each node. Format \"type=<accelerator-type>,count=<accelerator-count>\"\n# More information on available GPUs here - https://cloud.google.com/compute/docs/gpus/\nNODE_ACCELERATORS=${NODE_ACCELERATORS:-\"\"}\nexport REGISTER_MASTER_KUBELET=${REGISTER_MASTER:-true}\nPREEMPTIBLE_NODE=${PREEMPTIBLE_NODE:-false}\nPREEMPTIBLE_MASTER=${PREEMPTIBLE_MASTER:-false}\nKUBE_DELETE_NODES=${KUBE_DELETE_NODES:-true}\nKUBE_DELETE_NETWORK=${KUBE_DELETE_NETWORK:-} # default value calculated below\nCREATE_CUSTOM_NETWORK=${CREATE_CUSTOM_NETWORK:-false}\nMIG_WAIT_UNTIL_STABLE_TIMEOUT=${MIG_WAIT_UNTIL_STABLE_TIMEOUT:-1800}\n\nMASTER_OS_DISTRIBUTION=${KUBE_MASTER_OS_DISTRIBUTION:-${KUBE_OS_DISTRIBUTION:-gci}}\nNODE_OS_DISTRIBUTION=${KUBE_NODE_OS_DISTRIBUTION:-${KUBE_OS_DISTRIBUTION:-gci}}\nWINDOWS_NODE_OS_DISTRIBUTION=${WINDOWS_NODE_OS_DISTRIBUTION:-win2019}\n\nif [[ \"${MASTER_OS_DISTRIBUTION}\" == \"cos\" ]]; then\n    MASTER_OS_DISTRIBUTION=\"gci\"\nfi\n\nif [[ \"${NODE_OS_DISTRIBUTION}\" == \"cos\" ]]; then\n    NODE_OS_DISTRIBUTION=\"gci\"\nfi\n\n# GPUs supported in GCE do not have compatible drivers in Debian 7.\nif [[ \"${NODE_OS_DISTRIBUTION}\" == \"debian\" ]]; then\n    NODE_ACCELERATORS=\"\"\nfi\n\n# By default a cluster will be started with the master and nodes\n# on Container-optimized OS (cos, previously known as gci). If\n# you are updating the os image versions, update this variable.\n# Also please update corresponding image for node e2e at:\n# https://github.com/kubernetes/kubernetes/blob/master/test/e2e_node/jenkins/image-config.yaml\nGCI_VERSION=${KUBE_GCI_VERSION:-cos-85-13310-1041-9}\nexport MASTER_IMAGE=${KUBE_GCE_MASTER_IMAGE:-}\nexport MASTER_IMAGE_PROJECT=${KUBE_GCE_MASTER_PROJECT:-cos-cloud}\nexport NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${GCI_VERSION}}\nexport NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-cos-cloud}\nexport NODE_SERVICE_ACCOUNT=${KUBE_GCE_NODE_SERVICE_ACCOUNT:-default}\n\n# KUBELET_TEST_ARGS are extra arguments passed to kubelet.\nexport KUBELET_TEST_ARGS=${KUBE_KUBELET_EXTRA_ARGS:-}\n\n# Default container runtime\nexport CONTAINER_RUNTIME=${KUBE_CONTAINER_RUNTIME:-containerd}\n# Default container runtime for windows\nexport WINDOWS_CONTAINER_RUNTIME=${KUBE_WINDOWS_CONTAINER_RUNTIME:-docker}\n\n# Set default values with override\nif [[ \"${CONTAINER_RUNTIME}\" == \"docker\" ]]; then\n  export CONTAINER_RUNTIME_ENDPOINT=${KUBE_CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}\n  export CONTAINER_RUNTIME_NAME=${KUBE_CONTAINER_RUNTIME_NAME:-docker}\n  export LOAD_IMAGE_COMMAND=${KUBE_LOAD_IMAGE_COMMAND:-}\nelif [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ||  \"${CONTAINER_RUNTIME}\" == \"remote\" ]]; then\n  export CONTAINER_RUNTIME_ENDPOINT=${KUBE_CONTAINER_RUNTIME_ENDPOINT:-unix:///run/containerd/containerd.sock}\n  export CONTAINER_RUNTIME_NAME=${KUBE_CONTAINER_RUNTIME_NAME:-containerd}\n  export LOG_DUMP_SYSTEMD_SERVICES=${LOG_DUMP_SYSTEMD_SERVICES:-containerd}\n  export LOAD_IMAGE_COMMAND=${KUBE_LOAD_IMAGE_COMMAND:-ctr -n=k8s.io images import}\nfi\n\n# Ability to inject custom versions (Ubuntu OS images ONLY)\n# if KUBE_UBUNTU_INSTALL_CONTAINERD_VERSION or KUBE_UBUNTU_INSTALL_RUNC_VERSION\n# is set to empty then we do not override the version(s) and just\n# use whatever is in the default installation of containerd package\nexport UBUNTU_INSTALL_CONTAINERD_VERSION=${KUBE_UBUNTU_INSTALL_CONTAINERD_VERSION:-}\nexport UBUNTU_INSTALL_RUNC_VERSION=${KUBE_UBUNTU_INSTALL_RUNC_VERSION:-}\n\n# MASTER_EXTRA_METADATA is the extra instance metadata on master instance separated by commas.\nexport MASTER_EXTRA_METADATA=${KUBE_MASTER_EXTRA_METADATA:-${KUBE_EXTRA_METADATA:-}}\n# MASTER_EXTRA_METADATA is the extra instance metadata on node instance separated by commas.\nexport NODE_EXTRA_METADATA=${KUBE_NODE_EXTRA_METADATA:-${KUBE_EXTRA_METADATA:-}}\n\nNETWORK=${KUBE_GCE_NETWORK:-default}\n# Enable network deletion by default (for kube-down), unless we're using 'default' network.\nif [[ \"${NETWORK}\" == \"default\" ]]; then\n  KUBE_DELETE_NETWORK=${KUBE_DELETE_NETWORK:-false}\nelse\n  KUBE_DELETE_NETWORK=${KUBE_DELETE_NETWORK:-true}\nfi\nif [[ \"${CREATE_CUSTOM_NETWORK}\" == true ]]; then\n  SUBNETWORK=\"${SUBNETWORK:-${NETWORK}-custom-subnet}\"\nfi\nINSTANCE_PREFIX=\"${KUBE_GCE_INSTANCE_PREFIX:-kubernetes}\"\nCLUSTER_NAME=\"${CLUSTER_NAME:-${INSTANCE_PREFIX}}\"\nMASTER_NAME=\"${INSTANCE_PREFIX}-master\"\nexport AGGREGATOR_MASTER_NAME=\"${INSTANCE_PREFIX}-aggregator\"\nexport INITIAL_ETCD_CLUSTER=\"${MASTER_NAME}\"\nexport MASTER_TAG=\"${INSTANCE_PREFIX}-master\"\nexport NODE_TAG=\"${INSTANCE_PREFIX}-minion\"\n\nCLUSTER_IP_RANGE=\"${CLUSTER_IP_RANGE:-$(get-cluster-ip-range)}\"\nMASTER_IP_RANGE=\"${MASTER_IP_RANGE:-10.246.0.0/24}\"\n# NODE_IP_RANGE is used when ENABLE_IP_ALIASES=true or CREATE_CUSTOM_NETWORK=true.\n# It is the primary range in the subnet and is the range used for node instance IPs.\nNODE_IP_RANGE=\"$(get-node-ip-range)\"\nexport NODE_IP_RANGE\n\n# NOTE: Avoid giving nodes empty scopes, because kubelet needs a service account\n# in order to initialize properly.\nNODE_SCOPES=\"${NODE_SCOPES:-monitoring,logging-write,storage-ro}\"\n\n# Extra docker options for nodes.\nEXTRA_DOCKER_OPTS=\"${EXTRA_DOCKER_OPTS:-}\"\n\nVOLUME_PLUGIN_DIR=\"${VOLUME_PLUGIN_DIR:-/home/kubernetes/flexvolume}\"\n\nSERVICE_CLUSTER_IP_RANGE=\"${SERVICE_CLUSTER_IP_RANGE:-10.0.0.0/16}\"  # formerly PORTAL_NET\nexport ALLOCATE_NODE_CIDRS=true\n\n# When set to true, Docker Cache is enabled by default as part of the cluster bring up.\nexport ENABLE_DOCKER_REGISTRY_CACHE=true\n\n# Optional: Deploy a L7 loadbalancer controller to fulfill Ingress requests:\n#   glbc           - CE L7 Load Balancer Controller\nexport ENABLE_L7_LOADBALANCING=\"${KUBE_ENABLE_L7_LOADBALANCING:-glbc}\"\n\n# Optional: Enable Metrics Server. Metrics Server should be enable everywhere,\n# since it's a critical component, but in the first release we need a way to disable\n# this in case of stability issues.\n# TODO(piosz) remove this option once Metrics Server became a stable thing.\nexport ENABLE_METRICS_SERVER=\"${KUBE_ENABLE_METRICS_SERVER:-true}\"\n\n# Optional: Metadata agent to setup as part of the cluster bring up:\n#   none        - No metadata agent\n#   stackdriver - Stackdriver metadata agent\n# Metadata agent is a daemon set that provides metadata of kubernetes objects\n# running on the same node for exporting metrics and logs.\nexport ENABLE_METADATA_AGENT=\"${KUBE_ENABLE_METADATA_AGENT:-none}\"\n\n# One special node out of NUM_NODES would be created of this type if specified.\n# Useful for scheduling heapster in large clusters with nodes of small size.\nHEAPSTER_MACHINE_TYPE=\"${HEAPSTER_MACHINE_TYPE:-}\"\n\n# Optional: Additional nodes would be created if their type and number is specified.\n# NUM_NODES would be lowered respectively.\n# Useful for running cluster-level addons that needs more resources than would fit\n# on small nodes, like network plugins.\nNUM_ADDITIONAL_NODES=\"${NUM_ADDITIONAL_NODES:-}\"\nADDITIONAL_MACHINE_TYPE=\"${ADDITIONAL_MACHINE_TYPE:-}\"\n\nexport MASTER_NODE_LABELS=\"${KUBE_MASTER_NODE_LABELS:-}\"\n# NON_MASTER_NODE_LABELS are labels will only be applied on non-master nodes.\nNON_MASTER_NODE_LABELS=\"${KUBE_NON_MASTER_NODE_LABELS:-}\"\nWINDOWS_NON_MASTER_NODE_LABELS=\"${WINDOWS_NON_MASTER_NODE_LABELS:-}\"\n\nif [[ \"${PREEMPTIBLE_MASTER}\" == \"true\" ]]; then\n    NODE_LABELS=\"${NODE_LABELS},cloud.google.com/gke-preemptible=true\"\n    WINDOWS_NODE_LABELS=\"${WINDOWS_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\nelif [[ \"${PREEMPTIBLE_NODE}\" == \"true\" ]]; then\n    NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\n    WINDOWS_NON_MASTER_NODE_LABELS=\"${WINDOWS_NON_MASTER_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\nfi\n\n# To avoid running Calico on a node that is not configured appropriately,\n# label each Node so that the DaemonSet can run the Pods only on ready Nodes.\n# Windows nodes do not support Calico.\nif [[ ${NETWORK_POLICY_PROVIDER:-} == \"calico\" ]]; then\n\tNON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS:+${NON_MASTER_NODE_LABELS},}projectcalico.org/ds-ready=true\"\nfi\n\n# Optional: Enable netd.\nENABLE_NETD=\"${KUBE_ENABLE_NETD:-false}\"\nexport CUSTOM_NETD_YAML=\"${KUBE_CUSTOM_NETD_YAML:-}\"\nexport CUSTOM_CALICO_NODE_DAEMONSET_YAML=\"${KUBE_CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}\"\nexport CUSTOM_TYPHA_DEPLOYMENT_YAML=\"${KUBE_CUSTOM_TYPHA_DEPLOYMENT_YAML:-}\"\n\n# To avoid running netd on a node that is not configured appropriately,\n# label each Node so that the DaemonSet can run the Pods only on ready Nodes.\n# Windows nodes do not support netd.\nif [[ ${ENABLE_NETD:-} == \"true\" ]]; then\n\tNON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS:+${NON_MASTER_NODE_LABELS},}cloud.google.com/gke-netd-ready=true\"\nfi\n\nexport ENABLE_NODELOCAL_DNS=\"${KUBE_ENABLE_NODELOCAL_DNS:-false}\"\nexport LOCAL_DNS_IP=\"${KUBE_LOCAL_DNS_IP:-169.254.20.10}\"\n\n# Enable metadata concealment by firewalling pod traffic to the metadata server\n# and run a proxy daemonset on nodes.\n#\n# TODO(#8867) Enable by default.\nENABLE_METADATA_CONCEALMENT=\"${ENABLE_METADATA_CONCEALMENT:-false}\" # true, false\nMETADATA_CONCEALMENT_NO_FIREWALL=\"${METADATA_CONCEALMENT_NO_FIREWALL:-false}\" # true, false\nif [[ ${ENABLE_METADATA_CONCEALMENT:-} == \"true\" ]]; then\n  # Put the necessary label on the node so the daemonset gets scheduled.\n  NODE_LABELS=\"${NODE_LABELS},cloud.google.com/metadata-proxy-ready=true\"\n  # Add to the provider custom variables.\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_METADATA_CONCEALMENT METADATA_CONCEALMENT_NO_FIREWALL\"\nfi\n\n# Optional: Enable node logging.\nexport ENABLE_NODE_LOGGING=\"${KUBE_ENABLE_NODE_LOGGING:-true}\"\nexport LOGGING_DESTINATION=\"${KUBE_LOGGING_DESTINATION:-gcp}\" # options: elasticsearch, gcp\n\n# Optional: When set to true, Elasticsearch and Kibana will be setup as part of the cluster bring up.\nexport ENABLE_CLUSTER_LOGGING=\"${KUBE_ENABLE_CLUSTER_LOGGING:-true}\"\nexport ELASTICSEARCH_LOGGING_REPLICAS=1\n\n# Optional: Don't require https for registries in our local RFC1918 network\nif [[ ${KUBE_ENABLE_INSECURE_REGISTRY:-false} == \"true\" ]]; then\n  EXTRA_DOCKER_OPTS=\"${EXTRA_DOCKER_OPTS} --insecure-registry 10.0.0.0/8\"\nfi\n\n# Optional: customize runtime config\nRUNTIME_CONFIG=\"${KUBE_RUNTIME_CONFIG:-}\"\n\nif [[ \"${KUBE_FEATURE_GATES:-}\" == \"AllAlpha=true\" ]]; then\n  export RUNTIME_CONFIG=\"${KUBE_RUNTIME_CONFIG:-api/all=true}\"\nfi\n\n# If feature gates includes AllAlpha or EndpointSlice, and EndpointSlice has not been disabled, add EndpointSlice controller to list of controllers to run.\nif [[ (( \"${KUBE_FEATURE_GATES:-}\" == *\"AllAlpha=true\"* ) || ( \"${KUBE_FEATURE_GATES:-}\" == *\"EndpointSlice=true\"* )) && \"${KUBE_FEATURE_GATES:-}\" != *\"EndpointSlice=false\"* ]]; then\n  RUN_CONTROLLERS=\"${RUN_CONTROLLERS:-*,endpointslice}\"\nfi\n\n# Optional: set feature gates\nFEATURE_GATES=\"${KUBE_FEATURE_GATES:-}\"\n\nif [[ -n \"${NODE_ACCELERATORS}\" ]]; then\n    if [[ -z \"${FEATURE_GATES:-}\" ]]; then\n        FEATURE_GATES=\"DevicePlugins=true\"\n    else\n        FEATURE_GATES=\"${FEATURE_GATES},DevicePlugins=true\"\n    fi\n    if [[ \"${NODE_ACCELERATORS}\" =~ .*type=([a-zA-Z0-9-]+).* ]]; then\n        NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS},cloud.google.com/gke-accelerator=${BASH_REMATCH[1]}\"\n    fi\nfi\n\n# Optional: Install cluster DNS.\n# Set CLUSTER_DNS_CORE_DNS to 'false' to install kube-dns instead of CoreDNS.\nCLUSTER_DNS_CORE_DNS=\"${CLUSTER_DNS_CORE_DNS:-true}\"\nexport ENABLE_CLUSTER_DNS=\"${KUBE_ENABLE_CLUSTER_DNS:-true}\"\nexport DNS_SERVER_IP=\"${KUBE_DNS_SERVER_IP:-10.0.0.10}\"\nexport DNS_DOMAIN=\"${KUBE_DNS_DOMAIN:-cluster.local}\"\nexport DNS_MEMORY_LIMIT=\"${KUBE_DNS_MEMORY_LIMIT:-170Mi}\"\n\n# Optional: Enable DNS horizontal autoscaler\nexport ENABLE_DNS_HORIZONTAL_AUTOSCALER=\"${KUBE_ENABLE_DNS_HORIZONTAL_AUTOSCALER:-true}\"\n\n# Optional: Install Kubernetes UI\nexport ENABLE_CLUSTER_UI=\"${KUBE_ENABLE_CLUSTER_UI:-true}\"\n\n# Optional: Install node problem detector.\n#   none           - Not run node problem detector.\n#   daemonset      - Run node problem detector as daemonset.\n#   standalone     - Run node problem detector as standalone system daemon.\nif [[ \"${NODE_OS_DISTRIBUTION}\" == \"gci\" ]]; then\n  # Enable standalone mode by default for gci.\n  ENABLE_NODE_PROBLEM_DETECTOR=\"${KUBE_ENABLE_NODE_PROBLEM_DETECTOR:-standalone}\"\nelse\n  export ENABLE_NODE_PROBLEM_DETECTOR=\"${KUBE_ENABLE_NODE_PROBLEM_DETECTOR:-daemonset}\"\nfi\nNODE_PROBLEM_DETECTOR_VERSION=\"${NODE_PROBLEM_DETECTOR_VERSION:-}\"\nNODE_PROBLEM_DETECTOR_TAR_HASH=\"${NODE_PROBLEM_DETECTOR_TAR_HASH:-}\"\nNODE_PROBLEM_DETECTOR_RELEASE_PATH=\"${NODE_PROBLEM_DETECTOR_RELEASE_PATH:-}\"\nNODE_PROBLEM_DETECTOR_CUSTOM_FLAGS=\"${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\"\n\nCNI_HASH=\"${CNI_HASH:-}\"\nCNI_TAR_PREFIX=\"${CNI_TAR_PREFIX:-cni-plugins-linux-amd64-}\"\nCNI_STORAGE_URL_BASE=\"${CNI_STORAGE_URL_BASE:-https://storage.googleapis.com/k8s-artifacts-cni/release}\"\n\n# Optional: Create autoscaler for cluster's nodes.\nENABLE_CLUSTER_AUTOSCALER=\"${KUBE_ENABLE_CLUSTER_AUTOSCALER:-false}\"\nif [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n  export AUTOSCALER_MIN_NODES=\"${KUBE_AUTOSCALER_MIN_NODES:-}\"\n  export AUTOSCALER_MAX_NODES=\"${KUBE_AUTOSCALER_MAX_NODES:-}\"\n  export AUTOSCALER_ENABLE_SCALE_DOWN=\"${KUBE_AUTOSCALER_ENABLE_SCALE_DOWN:-true}\"\n  export AUTOSCALER_EXPANDER_CONFIG=\"${KUBE_AUTOSCALER_EXPANDER_CONFIG:---expander=price}\"\nfi\n\n# Optional: Enable allocation of pod IPs using IP aliases.\n#\n# BETA FEATURE.\n#\n# IP_ALIAS_SIZE is the size of the podCIDR allocated to a node.\n# IP_ALIAS_SUBNETWORK is the subnetwork to allocate from. If empty, a\n#   new subnetwork will be created for the cluster.\nENABLE_IP_ALIASES=${KUBE_GCE_ENABLE_IP_ALIASES:-false}\nNODE_IPAM_MODE=${KUBE_GCE_NODE_IPAM_MODE:-RangeAllocator}\nif [ \"${ENABLE_IP_ALIASES}\" = true ]; then\n  # Number of Pods that can run on this node.\n  MAX_PODS_PER_NODE=${MAX_PODS_PER_NODE:-110}\n  # Size of ranges allocated to each node.\n  IP_ALIAS_SIZE=\"/$(get-alias-range-size \"${MAX_PODS_PER_NODE}\")\"\n  export IP_ALIAS_SIZE\n  IP_ALIAS_SUBNETWORK=${KUBE_GCE_IP_ALIAS_SUBNETWORK:-${INSTANCE_PREFIX}-subnet-default}\n  # If we're using custom network, use the subnet we already create for it as the one for ip-alias.\n  # Note that this means SUBNETWORK would override KUBE_GCE_IP_ALIAS_SUBNETWORK in case of custom network.\n  if [[ \"${CREATE_CUSTOM_NETWORK}\" == true ]]; then\n    export IP_ALIAS_SUBNETWORK=\"${SUBNETWORK}\"\n  fi\n  export NODE_IPAM_MODE=${KUBE_GCE_NODE_IPAM_MODE:-CloudAllocator}\n  SECONDARY_RANGE_NAME=${SECONDARY_RANGE_NAME:-}\n  # Add to the provider custom variables.\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_IP_ALIASES\"\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} NODE_IPAM_MODE\"\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} SECONDARY_RANGE_NAME\"\nelse\n  if [[ -n \"${MAX_PODS_PER_NODE:-}\" ]]; then\n    # Should not have MAX_PODS_PER_NODE set for route-based clusters.\n    echo -e \"${color_red:-}Cannot set MAX_PODS_PER_NODE for route-based projects for ${PROJECT}.\" >&2\n    exit 1\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 100 ]]; then\n    echo -e \"${color_red:-}Cannot create cluster with more than 100 nodes for route-based projects for ${PROJECT}.\" >&2\n    exit 1\n  fi\nfi\n\n# Enable GCE Alpha features.\nif [[ -n \"${GCE_ALPHA_FEATURES:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} GCE_ALPHA_FEATURES\"\nfi\n\n# Disable Docker live-restore.\nif [[ -n \"${DISABLE_DOCKER_LIVE_RESTORE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} DISABLE_DOCKER_LIVE_RESTORE\"\nfi\n\n# Override default GLBC image\nif [[ -n \"${GCE_GLBC_IMAGE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} GCE_GLBC_IMAGE\"\nfi\nCUSTOM_INGRESS_YAML=\"${CUSTOM_INGRESS_YAML:-}\"\n\n# Admission Controllers to invoke prior to persisting objects in cluster\nADMISSION_CONTROL=NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,PersistentVolumeClaimResize,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection,RuntimeClass\n\nif [[ \"${ENABLE_POD_SECURITY_POLICY:-}\" == \"true\" ]]; then\n  ADMISSION_CONTROL=\"${ADMISSION_CONTROL},PodSecurityPolicy\"\nfi\n\n# MutatingAdmissionWebhook should be the last controller that modifies the\n# request object, otherwise users will be confused if the mutating webhooks'\n# modification is overwritten.\nADMISSION_CONTROL=\"${ADMISSION_CONTROL},MutatingAdmissionWebhook,ValidatingAdmissionWebhook\"\n\n# ResourceQuota must come last, or a creation is recorded, but the pod was forbidden.\nADMISSION_CONTROL=\"${ADMISSION_CONTROL},ResourceQuota\"\n\n# Optional: if set to true kube-up will automatically check for existing resources and clean them up.\nKUBE_UP_AUTOMATIC_CLEANUP=${KUBE_UP_AUTOMATIC_CLEANUP:-false}\n\n# Storage backend. 'etcd2' supported, 'etcd3' experimental.\nSTORAGE_BACKEND=${STORAGE_BACKEND:-}\n\n# Networking plugin specific settings.\nNETWORK_PROVIDER=\"${NETWORK_PROVIDER:-kubenet}\" # none, kubenet\n\n# Network Policy plugin specific settings.\nNETWORK_POLICY_PROVIDER=\"${NETWORK_POLICY_PROVIDER:-none}\" # calico\n\nexport NON_MASQUERADE_CIDR=\"0.0.0.0/0\"\n\n# How should the kubelet configure hairpin mode?\nHAIRPIN_MODE=\"${HAIRPIN_MODE:-hairpin-veth}\" # promiscuous-bridge, hairpin-veth, none\n# Optional: if set to true, kube-up will configure the cluster to run e2e tests.\nexport E2E_STORAGE_TEST_ENVIRONMENT=\"${KUBE_E2E_STORAGE_TEST_ENVIRONMENT:-false}\"\n\n# Evict pods whenever compute resource availability on the nodes gets below a threshold.\nEVICTION_HARD=\"${EVICTION_HARD:-memory.available<250Mi,nodefs.available<10%,nodefs.inodesFree<5%}\"\n\n# Optional: custom scheduling algorithm\nSCHEDULING_ALGORITHM_PROVIDER=\"${SCHEDULING_ALGORITHM_PROVIDER:-}\"\n\n# Optional: install a default StorageClass\nENABLE_DEFAULT_STORAGE_CLASS=\"${ENABLE_DEFAULT_STORAGE_CLASS:-true}\"\n\n# Optional: install volume snapshot CRDs\nENABLE_VOLUME_SNAPSHOTS=\"${ENABLE_VOLUME_SNAPSHOTS:-true}\"\n\n# Optional: Enable legacy ABAC policy that makes all service accounts superusers.\nENABLE_LEGACY_ABAC=\"${ENABLE_LEGACY_ABAC:-false}\" # true, false\n\n# Indicates if the values (i.e. KUBE_USER and KUBE_PASSWORD for basic\n# authentication) in metadata should be treated as canonical, and therefore disk\n# copies ought to be recreated/clobbered.\nMETADATA_CLOBBERS_CONFIG=\"${METADATA_CLOBBERS_CONFIG:-false}\"\n\nENABLE_BIG_CLUSTER_SUBNETS=\"${ENABLE_BIG_CLUSTER_SUBNETS:-false}\"\n\n# Optional: Enable log rotation for k8s services\nENABLE_LOGROTATE_FILES=\"${ENABLE_LOGROTATE_FILES:-true}\"\nPROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_LOGROTATE_FILES\"\nif [[ -n \"${LOGROTATE_FILES_MAX_COUNT:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} LOGROTATE_FILES_MAX_COUNT\"\nfi\nif [[ -n \"${LOGROTATE_MAX_SIZE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} LOGROTATE_MAX_SIZE\"\nfi\n\n# Optional: Enable log rotation for pod logs\nENABLE_POD_LOG=\"${ENABLE_POD_LOG:-false}\"\nPROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_POD_LOG\"\n\nif [[ -n \"${POD_LOG_MAX_FILE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} POD_LOG_MAX_FILE\"\nfi\n\nif [[ -n \"${POD_LOG_MAX_SIZE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} POD_LOG_MAX_SIZE\"\nfi\n\n# Fluentd requirements\n# YAML exists to trigger a configuration refresh when changes are made.\nexport FLUENTD_GCP_YAML_VERSION=\"v3.2.0\"\nFLUENTD_GCP_VERSION=\"${FLUENTD_GCP_VERSION:-1.6.17}\"\nFLUENTD_GCP_MEMORY_LIMIT=\"${FLUENTD_GCP_MEMORY_LIMIT:-}\"\nFLUENTD_GCP_CPU_REQUEST=\"${FLUENTD_GCP_CPU_REQUEST:-}\"\nFLUENTD_GCP_MEMORY_REQUEST=\"${FLUENTD_GCP_MEMORY_REQUEST:-}\"\n\n# Heapster requirements\nHEAPSTER_GCP_BASE_MEMORY=\"${HEAPSTER_GCP_BASE_MEMORY:-140Mi}\"\nHEAPSTER_GCP_MEMORY_PER_NODE=\"${HEAPSTER_GCP_MEMORY_PER_NODE:-4}\"\nHEAPSTER_GCP_BASE_CPU=\"${HEAPSTER_GCP_BASE_CPU:-80m}\"\nHEAPSTER_GCP_CPU_PER_NODE=\"${HEAPSTER_GCP_CPU_PER_NODE:-0.5}\"\n\n# Optional: custom system banner for dashboard addon\nCUSTOM_KUBE_DASHBOARD_BANNER=\"${CUSTOM_KUBE_DASHBOARD_BANNER:-}\"\n\n# Default Stackdriver resources version exported by Fluentd-gcp addon\nLOGGING_STACKDRIVER_RESOURCE_TYPES=\"${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}\"\n\n# Adding to PROVIDER_VARS, since this is GCP-specific.\nPROVIDER_VARS=\"${PROVIDER_VARS:-} FLUENTD_GCP_YAML_VERSION FLUENTD_GCP_VERSION FLUENTD_GCP_MEMORY_LIMIT FLUENTD_GCP_CPU_REQUEST FLUENTD_GCP_MEMORY_REQUEST HEAPSTER_GCP_BASE_MEMORY HEAPSTER_GCP_MEMORY_PER_NODE HEAPSTER_GCP_BASE_CPU HEAPSTER_GCP_CPU_PER_NODE CUSTOM_KUBE_DASHBOARD_BANNER LOGGING_STACKDRIVER_RESOURCE_TYPES\"\n\n# Fluentd configuration for node-journal\nENABLE_NODE_JOURNAL=\"${ENABLE_NODE_JOURNAL:-false}\"\n\n# prometheus-to-sd configuration\nPROMETHEUS_TO_SD_ENDPOINT=\"${PROMETHEUS_TO_SD_ENDPOINT:-https://monitoring.googleapis.com/}\"\nPROMETHEUS_TO_SD_PREFIX=\"${PROMETHEUS_TO_SD_PREFIX:-custom.googleapis.com}\"\nENABLE_PROMETHEUS_TO_SD=\"${ENABLE_PROMETHEUS_TO_SD:-false}\"\n\n# TODO(#51292): Make kube-proxy Daemonset default and remove the configuration here.\n# Optional: [Experiment Only] Run kube-proxy as a DaemonSet if set to true, run as static pods otherwise.\nKUBE_PROXY_DAEMONSET=\"${KUBE_PROXY_DAEMONSET:-false}\" # true, false\n\n# Control whether the startup scripts manage the lifecycle of kube-proxy\n# When true, the startup scripts do not enable kube-proxy either as a daemonset addon or as a static pod\n# regardless of the value of KUBE_PROXY_DAEMONSET.\n# When false, the value of KUBE_PROXY_DAEMONSET controls whether kube-proxy comes up as a static pod or\n# as an addon daemonset.\nKUBE_PROXY_DISABLE=\"${KUBE_PROXY_DISABLE:-false}\" # true, false\n\n# Will be passed into the kube-proxy via `--detect-local-mode`\nDETECT_LOCAL_MODE=\"${DETECT_LOCAL_MODE:-}\"\n\n# Optional: duration of cluster signed certificates.\nCLUSTER_SIGNING_DURATION=\"${CLUSTER_SIGNING_DURATION:-}\"\n\n# Optional: enable certificate rotation of the kubelet certificates.\nROTATE_CERTIFICATES=\"${ROTATE_CERTIFICATES:-}\"\n\n# The number of services that are allowed to sync concurrently. Will be passed\n# into kube-controller-manager via `--concurrent-service-syncs`\nCONCURRENT_SERVICE_SYNCS=\"${CONCURRENT_SERVICE_SYNCS:-}\"\n\nexport SERVICEACCOUNT_ISSUER=\"https://kubernetes.io/${CLUSTER_NAME}\"\n\n# Taint Windows nodes by default to prevent Linux workloads from being\n# scheduled onto them.\nWINDOWS_NODE_TAINTS=\"${WINDOWS_NODE_TAINTS:-node.kubernetes.io/os=win1809:NoSchedule}\"\n\n# Whether to set up a private GCE cluster, i.e. a cluster where nodes have only private IPs.\nexport GCE_PRIVATE_CLUSTER=\"${KUBE_GCE_PRIVATE_CLUSTER:-false}\"\nexport GCE_PRIVATE_CLUSTER_PORTS_PER_VM=\"${KUBE_GCE_PRIVATE_CLUSTER_PORTS_PER_VM:-}\"\n\n# When KUBE_ENABLE_KONNECTIVITY_SERVICE is enabled, the three variables below will\n# default to true to enable the konnectivity network proxy and start the required pods.\n# Their values can be overridden for more granular control of the proxy.\n\n# Optional: Whether to do the setup for the konnectivity service\n# Includes setting up kubeconfig, tokens, egress files, and firewall rules\nexport PREPARE_KONNECTIVITY_SERVICE=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\n# Optional: Whether to use konnectivity network proxy for all egress from apiserver.\nexport EGRESS_VIA_KONNECTIVITY=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\n# Optional: Whether to start the konnectivity server and agent pods.\nexport RUN_KONNECTIVITY_PODS=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\n# Proxy Protocol Mode determines the protocol to use to communicate between apiserver and network proxy.\n# Valid options are grpc and http-connect. Default is grpc.\nexport KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE=\"${KUBE_KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\"\n\n# Optional: Enable Windows CSI-Proxy\nexport ENABLE_CSI_PROXY=\"${ENABLE_CSI_PROXY:-true}\"\n\n# KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP decides whether\n# kube-apiserver is healthchecked on host IP instead of 127.0.0.1.\nexport KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP=\"${KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP:-false}\"\n\n# ETCD_PROGRESS_NOTIFY_INTERVAL defines the interval for etcd watch progress notify events.\nexport ETCD_PROGRESS_NOTIFY_INTERVAL=\"${ETCD_PROGRESS_NOTIFY_INTERVAL:-5s}\"\n\n# Optional: Install Pigz on Windows.\n# Pigz is a multi-core optimized version of unzip.exe.\n# It improves container image pull performance since most time is spent\n# unzipping the image layers to disk.\nexport WINDOWS_ENABLE_PIGZ=\"${WINDOWS_ENABLE_PIGZ:-true}\"\n\n# Enable Windows DSR (Direct Server Return)\nexport WINDOWS_ENABLE_DSR=\"${WINDOWS_ENABLE_DSR:-false}\"\n\n# Install Node Problem Detector (NPD) on Windows nodes.\n# NPD analyzes the host for problems that can disrupt workloads.\nexport WINDOWS_ENABLE_NODE_PROBLEM_DETECTOR=\"${WINDOWS_ENABLE_NODE_PROBLEM_DETECTOR:-none}\"\nexport WINDOWS_NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS=\"${WINDOWS_NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\"\n\n# TLS_CIPHER_SUITES defines cipher suites allowed to be used by kube-apiserver.\n# If this variable is unset or empty, kube-apiserver will allow its default set of cipher suites.\nexport TLS_CIPHER_SUITES=\"\"\n", "num_lines": 566}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# TODO(jbeda): Provide a way to override project\n# gcloud multiplexing for shared GCE/GKE tests.\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/cluster/gce/config-common.sh\"\n\n# Specifying KUBE_GCE_API_ENDPOINT will override the default GCE Compute API endpoint (https://www.googleapis.com/compute/v1/).\n# This endpoint has to be pointing to v1 api. For example, https://www.googleapis.com/compute/staging_v1/\nexport GCE_API_ENDPOINT=${KUBE_GCE_API_ENDPOINT:-}\nZONE=${KUBE_GCE_ZONE:-us-central1-b}\nexport REGION=${ZONE%-*}\nRELEASE_REGION_FALLBACK=${RELEASE_REGION_FALLBACK:-false}\nREGIONAL_KUBE_ADDONS=${REGIONAL_KUBE_ADDONS:-true}\n# TODO: Migrate to e2-standard machine family.\nNODE_SIZE=${NODE_SIZE:-n1-standard-2}\nNUM_NODES=${NUM_NODES:-3}\nNUM_WINDOWS_NODES=${NUM_WINDOWS_NODES:-0}\n# TODO: Migrate to e2-standard machine family.\nMASTER_SIZE=${MASTER_SIZE:-n1-standard-$(get-master-size)}\nMASTER_MIN_CPU_ARCHITECTURE=${MASTER_MIN_CPU_ARCHITECTURE:-} # To allow choosing better architectures.\nexport MASTER_DISK_TYPE=pd-ssd\nMASTER_DISK_SIZE=${MASTER_DISK_SIZE:-$(get-master-disk-size)}\nMASTER_ROOT_DISK_SIZE=${MASTER_ROOT_DISK_SIZE:-$(get-master-root-disk-size)}\nNODE_DISK_TYPE=${NODE_DISK_TYPE:-pd-standard}\nNODE_DISK_SIZE=${NODE_DISK_SIZE:-100GB}\nNODE_LOCAL_SSDS=${NODE_LOCAL_SSDS:-0}\nNODE_LABELS=${KUBE_NODE_LABELS:-}\nWINDOWS_NODE_LABELS=${WINDOWS_NODE_LABELS:-}\nNODE_LOCAL_SSDS_EPHEMERAL=${NODE_LOCAL_SSDS_EPHEMERAL:-}\n# Turning GRPC based Konnectivity testing on id advance of\n# removing the SSHTunnel code.\nexport KUBE_ENABLE_EGRESS_VIA_KONNECTIVITY_SERVICE=true\nexport PREPARE_KONNECTIVITY_SERVICE=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\nexport EGRESS_VIA_KONNECTIVITY=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\nexport RUN_KONNECTIVITY_PODS=\"${KUBE_ENABLE_KONNECTIVITY_SERVICE:-true}\"\nexport KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE=\"${KUBE_KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\"\n\n# KUBE_CREATE_NODES can be used to avoid creating nodes, while master will be sized for NUM_NODES nodes.\n# Firewalls and node templates are still created.\nKUBE_CREATE_NODES=${KUBE_CREATE_NODES:-true}\n\n# An extension to local SSDs allowing users to specify block/fs and SCSI/NVMe devices\n# Format of this variable will be \"#,scsi/nvme,block/fs\" you can specify multiple\n# configurations by separating them by a semi-colon ex. \"2,scsi,fs;1,nvme,block\"\n# is a request for 2 SCSI formatted and mounted SSDs and 1 NVMe block device SSD.\nNODE_LOCAL_SSDS_EXT=${NODE_LOCAL_SSDS_EXT:-}\nNODE_ACCELERATORS=${NODE_ACCELERATORS:-''}\nexport REGISTER_MASTER_KUBELET=${REGISTER_MASTER:-true}\nexport KUBE_APISERVER_REQUEST_TIMEOUT=300\n# Increase initial delay for the apiserver liveness probe, to avoid prematurely tearing it down\nKUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC=${KUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC:-45}\n# Also increase the initial delay for etcd just to be safe\nETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC=${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC:-45}\nPREEMPTIBLE_NODE=${PREEMPTIBLE_NODE:-false}\nPREEMPTIBLE_MASTER=${PREEMPTIBLE_MASTER:-false}\nKUBE_DELETE_NODES=${KUBE_DELETE_NODES:-true}\nKUBE_DELETE_NETWORK=${KUBE_DELETE_NETWORK:-true}\nCREATE_CUSTOM_NETWORK=${CREATE_CUSTOM_NETWORK:-false}\nMIG_WAIT_UNTIL_STABLE_TIMEOUT=${MIG_WAIT_UNTIL_STABLE_TIMEOUT:-1800}\n\nMASTER_OS_DISTRIBUTION=${KUBE_MASTER_OS_DISTRIBUTION:-${KUBE_OS_DISTRIBUTION:-gci}}\nNODE_OS_DISTRIBUTION=${KUBE_NODE_OS_DISTRIBUTION:-${KUBE_OS_DISTRIBUTION:-gci}}\nWINDOWS_NODE_OS_DISTRIBUTION=${WINDOWS_NODE_OS_DISTRIBUTION:-win2019}\n\nif [[ \"${MASTER_OS_DISTRIBUTION}\" = 'cos' ]]; then\n  MASTER_OS_DISTRIBUTION='gci'\nfi\n\nif [[ \"${NODE_OS_DISTRIBUTION}\" = 'cos' ]]; then\n  NODE_OS_DISTRIBUTION='gci'\nfi\n\n# GPUs supported in GCE do not have compatible drivers in Debian 7.\nif [[ \"${NODE_OS_DISTRIBUTION}\" = 'debian' ]]; then\n  NODE_ACCELERATORS=''\nfi\n\n# To avoid failing large tests due to some flakes in starting nodes, allow\n# for a small percentage of nodes to not start during cluster startup.\nALLOWED_NOTREADY_NODES=${ALLOWED_NOTREADY_NODES:-$(($(get-num-nodes) / 100))}\n\n# By default a cluster will be started with the master and nodes\n# on Container-optimized OS (cos, previously known as gci). If\n# you are updating the os image versions, update this variable.\n# Also please update corresponding image for node e2e at:\n# https://github.com/kubernetes/kubernetes/blob/master/test/e2e_node/jenkins/image-config.yaml\nGCI_VERSION=${KUBE_GCI_VERSION:-cos-85-13310-1041-9}\nexport MASTER_IMAGE=${KUBE_GCE_MASTER_IMAGE:-}\nexport MASTER_IMAGE_PROJECT=${KUBE_GCE_MASTER_PROJECT:-cos-cloud}\nexport NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${GCI_VERSION}}\nexport NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-cos-cloud}\nexport NODE_SERVICE_ACCOUNT=${KUBE_GCE_NODE_SERVICE_ACCOUNT:-default}\n\n# Default container runtime for linux\nexport CONTAINER_RUNTIME=${KUBE_CONTAINER_RUNTIME:-containerd}\n# Default container runtime for windows\nexport WINDOWS_CONTAINER_RUNTIME=${KUBE_WINDOWS_CONTAINER_RUNTIME:-docker}\n\n# Set default values with override\nif [[ \"${CONTAINER_RUNTIME}\" == \"docker\" ]]; then\n  export CONTAINER_RUNTIME_ENDPOINT=${KUBE_CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}\n  export CONTAINER_RUNTIME_NAME=${KUBE_CONTAINER_RUNTIME_NAME:-docker}\n  export LOAD_IMAGE_COMMAND=${KUBE_LOAD_IMAGE_COMMAND:-}\nelif [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" || \"${CONTAINER_RUNTIME}\" == \"remote\" ]]; then\n  export CONTAINER_RUNTIME_ENDPOINT=${KUBE_CONTAINER_RUNTIME_ENDPOINT:-unix:///run/containerd/containerd.sock}\n  export CONTAINER_RUNTIME_NAME=${KUBE_CONTAINER_RUNTIME_NAME:-containerd}\n  export LOAD_IMAGE_COMMAND=${KUBE_LOAD_IMAGE_COMMAND:-ctr -n=k8s.io images import}\n  export LOG_DUMP_SYSTEMD_SERVICES=${LOG_DUMP_SYSTEMD_SERVICES:-containerd}\n  export CONTAINER_RUNTIME_TEST_HANDLER=\"true\"\nfi\n\nexport GCI_DOCKER_VERSION=${KUBE_GCI_DOCKER_VERSION:-}\n\n# Ability to inject custom versions (Ubuntu OS images ONLY)\n# if KUBE_UBUNTU_INSTALL_CONTAINERD_VERSION or KUBE_UBUNTU_INSTALL_RUNC_VERSION\n# is set to empty then we do not override the version(s) and just\n# use whatever is in the default installation of containerd package\nexport UBUNTU_INSTALL_CONTAINERD_VERSION=${KUBE_UBUNTU_INSTALL_CONTAINERD_VERSION:-}\nexport UBUNTU_INSTALL_RUNC_VERSION=${KUBE_UBUNTU_INSTALL_RUNC_VERSION:-}\n\n# MASTER_EXTRA_METADATA is the extra instance metadata on master instance separated by commas.\nexport MASTER_EXTRA_METADATA=${KUBE_MASTER_EXTRA_METADATA:-${KUBE_EXTRA_METADATA:-}}\n# MASTER_EXTRA_METADATA is the extra instance metadata on node instance separated by commas.\nexport NODE_EXTRA_METADATA=${KUBE_NODE_EXTRA_METADATA:-${KUBE_EXTRA_METADATA:-}}\n\nNETWORK=${KUBE_GCE_NETWORK:-e2e-test-${USER}}\nif [[ \"${CREATE_CUSTOM_NETWORK}\" = true ]]; then\n  SUBNETWORK=${SUBNETWORK:-${NETWORK}-custom-subnet}\nfi\nINSTANCE_PREFIX=${KUBE_GCE_INSTANCE_PREFIX:-e2e-test-${USER}}\nCLUSTER_NAME=${CLUSTER_NAME:-${INSTANCE_PREFIX}}\nMASTER_NAME=\"${INSTANCE_PREFIX}-master\"\nexport AGGREGATOR_MASTER_NAME=\"${INSTANCE_PREFIX}-aggregator\"\nexport INITIAL_ETCD_CLUSTER=${MASTER_NAME}\nexport MASTER_TAG=\"${INSTANCE_PREFIX}-master\"\nexport NODE_TAG=\"${INSTANCE_PREFIX}-minion\"\n\nCLUSTER_IP_RANGE=${CLUSTER_IP_RANGE:-$(get-cluster-ip-range)}\nMASTER_IP_RANGE=${MASTER_IP_RANGE:-10.246.0.0/24}\n# NODE_IP_RANGE is used when ENABLE_IP_ALIASES=true or CREATE_CUSTOM_NETWORK=true.\n# It is the primary range in the subnet and is the range used for node instance IPs.\nNODE_IP_RANGE=$(get-node-ip-range)\nexport NODE_IP_RANGE\n\nexport RUNTIME_CONFIG=${KUBE_RUNTIME_CONFIG:-}\n\nif [[ \"${KUBE_FEATURE_GATES:-}\" = 'AllAlpha=true' ]]; then\n  RUNTIME_CONFIG=${KUBE_RUNTIME_CONFIG:-api/all=true}\nfi\n\n# If feature gates includes AllAlpha or EndpointSlice, and EndpointSlice has not been disabled, add EndpointSlice controller to list of controllers to run.\nif [[ (( \"${KUBE_FEATURE_GATES:-}\" = *\"AllAlpha=true\"* ) || ( \"${KUBE_FEATURE_GATES:-}\" = *\"EndpointSlice=true\"* )) && \"${KUBE_FEATURE_GATES:-}\" != *\"EndpointSlice=false\"* ]]; then\n  RUN_CONTROLLERS=${RUN_CONTROLLERS:-*,endpointslice}\nfi\n\n# Optional: set feature gates\nFEATURE_GATES=${KUBE_FEATURE_GATES:-}\n\nTERMINATED_POD_GC_THRESHOLD=${TERMINATED_POD_GC_THRESHOLD:-100}\n\n# Extra docker options for nodes.\nEXTRA_DOCKER_OPTS=${EXTRA_DOCKER_OPTS:-}\n\n# Enable the docker debug mode.\nEXTRA_DOCKER_OPTS=\"${EXTRA_DOCKER_OPTS} --debug\"\n\nexport SERVICE_CLUSTER_IP_RANGE='10.0.0.0/16'  # formerly PORTAL_NET\n\n# When set to true, Docker Cache is enabled by default as part of the cluster bring up.\nexport ENABLE_DOCKER_REGISTRY_CACHE=true\n\n# Optional: Deploy a L7 loadbalancer controller to fulfill Ingress requests:\n#   glbc           - CE L7 Load Balancer Controller\nexport ENABLE_L7_LOADBALANCING=${KUBE_ENABLE_L7_LOADBALANCING:-glbc}\n\n# Optional: Enable Metrics Server. Metrics Server should be enable everywhere,\n# since it's a critical component, but in the first release we need a way to disable\n# this in case of stability issues.\n# TODO(piosz) remove this option once Metrics Server became a stable thing.\nexport ENABLE_METRICS_SERVER=${KUBE_ENABLE_METRICS_SERVER:-true}\n\n# Optional: Metadata agent to setup as part of the cluster bring up:\n#   none        - No metadata agent\n#   stackdriver - Stackdriver metadata agent\n# Metadata agent is a daemon set that provides metadata of kubernetes objects\n# running on the same node for exporting metrics and logs.\nexport ENABLE_METADATA_AGENT=${KUBE_ENABLE_METADATA_AGENT:-none}\n\n# One special node out of NUM_NODES would be created of this type if specified.\n# Useful for scheduling heapster in large clusters with nodes of small size.\nHEAPSTER_MACHINE_TYPE=${HEAPSTER_MACHINE_TYPE:-}\n\n# Optional: Additional nodes would be created if their type and number is specified.\n# NUM_NODES would be lowered respectively.\n# Useful for running cluster-level addons that needs more resources than would fit\n# on small nodes, like network plugins.\nNUM_ADDITIONAL_NODES=${NUM_ADDITIONAL_NODES:-}\nADDITIONAL_MACHINE_TYPE=${ADDITIONAL_MACHINE_TYPE:-}\n\n# Set etcd image (e.g. k8s.gcr.io/etcd) and version (e.g. v3.5.0-rc.0-0) if you need\n# non-default version.\nexport ETCD_IMAGE=${TEST_ETCD_IMAGE:-}\nexport ETCD_DOCKER_REPOSITORY=${TEST_ETCD_DOCKER_REPOSITORY:-}\nexport ETCD_VERSION=${TEST_ETCD_VERSION:-}\n\n# Default Log level for all components in test clusters and variables to override it in specific components.\nTEST_CLUSTER_LOG_LEVEL=${TEST_CLUSTER_LOG_LEVEL:---v=4}\nKUBELET_TEST_LOG_LEVEL=${KUBELET_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\nDOCKER_TEST_LOG_LEVEL=${DOCKER_TEST_LOG_LEVEL:---log-level=info}\nAPI_SERVER_TEST_LOG_LEVEL=${API_SERVER_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\nCONTROLLER_MANAGER_TEST_LOG_LEVEL=${CONTROLLER_MANAGER_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\nSCHEDULER_TEST_LOG_LEVEL=${SCHEDULER_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\nKUBEPROXY_TEST_LOG_LEVEL=${KUBEPROXY_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\n\nVOLUME_PLUGIN_DIR=${VOLUME_PLUGIN_DIR:-/home/kubernetes/flexvolume}\n\nTEST_CLUSTER_DELETE_COLLECTION_WORKERS=${TEST_CLUSTER_DELETE_COLLECTION_WORKERS:---delete-collection-workers=1}\nTEST_CLUSTER_MAX_REQUESTS_INFLIGHT=${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT:-}\nTEST_CLUSTER_RESYNC_PERIOD=${TEST_CLUSTER_RESYNC_PERIOD:---min-resync-period=3m}\n\n# ContentType used by all components to communicate with apiserver.\nTEST_CLUSTER_API_CONTENT_TYPE=${TEST_CLUSTER_API_CONTENT_TYPE:-}\n\nKUBELET_TEST_ARGS=\"${KUBELET_TEST_ARGS:-} --serialize-image-pulls=false ${TEST_CLUSTER_API_CONTENT_TYPE}\"\nif [[ \"${NODE_OS_DISTRIBUTION}\" = 'gci' ]] || [[ \"${NODE_OS_DISTRIBUTION}\" = 'ubuntu' ]] || [[ \"${NODE_OS_DISTRIBUTION}\" = 'custom' ]]; then\n  NODE_KUBELET_TEST_ARGS=\"${NODE_KUBELET_TEST_ARGS:-} --kernel-memcg-notification=true\"\nfi\nif [[ \"${MASTER_OS_DISTRIBUTION}\" = 'gci' ]] || [[ \"${MASTER_OS_DISTRIBUTION}\" = 'ubuntu' ]]; then\n  MASTER_KUBELET_TEST_ARGS=\"${MASTER_KUBELET_TEST_ARGS:-} --kernel-memcg-notification=true\"\nfi\nAPISERVER_TEST_ARGS=\"${APISERVER_TEST_ARGS:-} --runtime-config=extensions/v1beta1,scheduling.k8s.io/v1alpha1 ${TEST_CLUSTER_DELETE_COLLECTION_WORKERS} ${TEST_CLUSTER_MAX_REQUESTS_INFLIGHT}\"\nCONTROLLER_MANAGER_TEST_ARGS=\"${CONTROLLER_MANAGER_TEST_ARGS:-} ${TEST_CLUSTER_RESYNC_PERIOD} ${TEST_CLUSTER_API_CONTENT_TYPE}\"\nSCHEDULER_TEST_ARGS=\"${SCHEDULER_TEST_ARGS:-} ${TEST_CLUSTER_API_CONTENT_TYPE}\"\nKUBEPROXY_TEST_ARGS=\"${KUBEPROXY_TEST_ARGS:-} ${TEST_CLUSTER_API_CONTENT_TYPE}\"\n\nexport MASTER_NODE_LABELS=${KUBE_MASTER_NODE_LABELS:-}\n# NON_MASTER_NODE_LABELS are labels will only be applied on non-master nodes.\nNON_MASTER_NODE_LABELS=${KUBE_NON_MASTER_NODE_LABELS:-}\nWINDOWS_NON_MASTER_NODE_LABELS=${WINDOWS_NON_MASTER_NODE_LABELS:-}\n\nif [[ \"${PREEMPTIBLE_MASTER}\" = 'true' ]]; then\n  NODE_LABELS=\"${NODE_LABELS},cloud.google.com/gke-preemptible=true\"\n  WINDOWS_NODE_LABELS=\"${WINDOWS_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\nelif [[ \"${PREEMPTIBLE_NODE}\" = 'true' ]]; then\n  NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\n  WINDOWS_NON_MASTER_NODE_LABELS=\"${WINDOWS_NON_MASTER_NODE_LABELS},cloud.google.com/gke-preemptible=true\"\nfi\n\n# Optional: Enable netd.\nENABLE_NETD=${KUBE_ENABLE_NETD:-false}\nexport CUSTOM_NETD_YAML=${KUBE_CUSTOM_NETD_YAML:-}\nexport CUSTOM_CALICO_NODE_DAEMONSET_YAML=${KUBE_CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}\nexport CUSTOM_TYPHA_DEPLOYMENT_YAML=${KUBE_CUSTOM_TYPHA_DEPLOYMENT_YAML:-}\n\n# To avoid running netd on a node that is not configured appropriately,\n# label each Node so that the DaemonSet can run the Pods only on ready Nodes.\n# Windows nodes do not support netd.\nif [[ ${ENABLE_NETD:-} = 'true' ]]; then\n  NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS:+${NON_MASTER_NODE_LABELS},}cloud.google.com/gke-netd-ready=true\"\nfi\n\nexport ENABLE_NODELOCAL_DNS=${KUBE_ENABLE_NODELOCAL_DNS:-false}\n\n# To avoid running Calico on a node that is not configured appropriately,\n# label each Node so that the DaemonSet can run the Pods only on ready Nodes.\n# Windows nodes do not support Calico.\nif [[ ${NETWORK_POLICY_PROVIDER:-} = 'calico' ]]; then\n  NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS:+${NON_MASTER_NODE_LABELS},}projectcalico.org/ds-ready=true\"\nfi\n\n# Enable metadata concealment by firewalling pod traffic to the metadata server\n# and run a proxy daemonset on nodes.\nENABLE_METADATA_CONCEALMENT=${ENABLE_METADATA_CONCEALMENT:-true} # true, false\nMETADATA_CONCEALMENT_NO_FIREWALL=${METADATA_CONCEALMENT_NO_FIREWALL:-false} # true, false\nif [[ ${ENABLE_METADATA_CONCEALMENT:-} = 'true' ]]; then\n  # Put the necessary label on the node so the daemonset gets scheduled.\n  NODE_LABELS=\"${NODE_LABELS},cloud.google.com/metadata-proxy-ready=true\"\n  # Add to the provider custom variables.\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_METADATA_CONCEALMENT METADATA_CONCEALMENT_NO_FIREWALL\"\nfi\n\n# Optional: Enable node logging.\nexport ENABLE_NODE_LOGGING=${KUBE_ENABLE_NODE_LOGGING:-true}\nexport LOGGING_DESTINATION=${KUBE_LOGGING_DESTINATION:-gcp} # options: elasticsearch, gcp\n\n# Optional: When set to true, Elasticsearch and Kibana will be setup as part of the cluster bring up.\nexport ENABLE_CLUSTER_LOGGING=${KUBE_ENABLE_CLUSTER_LOGGING:-true}\nexport ELASTICSEARCH_LOGGING_REPLICAS=1\n\n# Optional: Don't require https for registries in our local RFC1918 network\nif [[ ${KUBE_ENABLE_INSECURE_REGISTRY:-false} = 'true' ]]; then\n  EXTRA_DOCKER_OPTS=\"${EXTRA_DOCKER_OPTS} --insecure-registry 10.0.0.0/8\"\nfi\n\nif [[ -n \"${NODE_ACCELERATORS}\" ]]; then\n    if [[ -z \"${FEATURE_GATES:-}\" ]]; then\n        FEATURE_GATES='DevicePlugins=true'\n    else\n        FEATURE_GATES=\"${FEATURE_GATES},DevicePlugins=true\"\n    fi\n    if [[ \"${NODE_ACCELERATORS}\" =~ .*type=([a-zA-Z0-9-]+).* ]]; then\n        NON_MASTER_NODE_LABELS=\"${NON_MASTER_NODE_LABELS},cloud.google.com/gke-accelerator=${BASH_REMATCH[1]}\"\n    fi\nfi\n\n# Optional: Install cluster DNS.\n# Set CLUSTER_DNS_CORE_DNS to 'false' to install kube-dns instead of CoreDNS.\nCLUSTER_DNS_CORE_DNS=${CLUSTER_DNS_CORE_DNS:-true}\nexport ENABLE_CLUSTER_DNS=${KUBE_ENABLE_CLUSTER_DNS:-true}\nexport DNS_SERVER_IP='10.0.0.10'\nexport LOCAL_DNS_IP=${KUBE_LOCAL_DNS_IP:-169.254.20.10}\nexport DNS_DOMAIN='cluster.local'\nexport DNS_MEMORY_LIMIT=${KUBE_DNS_MEMORY_LIMIT:-170Mi}\n\n# Optional: Enable DNS horizontal autoscaler\nexport ENABLE_DNS_HORIZONTAL_AUTOSCALER=${KUBE_ENABLE_DNS_HORIZONTAL_AUTOSCALER:-true}\n\n# Optional: Install Kubernetes UI\nexport ENABLE_CLUSTER_UI=${KUBE_ENABLE_CLUSTER_UI:-true}\n\n# Optional: Install node problem detector.\n#   none           - Not run node problem detector.\n#   daemonset      - Run node problem detector as daemonset.\n#   standalone     - Run node problem detector as standalone system daemon.\nif [[ \"${NODE_OS_DISTRIBUTION}\" = 'gci' ]]; then\n  # Enable standalone mode by default for gci.\n  ENABLE_NODE_PROBLEM_DETECTOR=${KUBE_ENABLE_NODE_PROBLEM_DETECTOR:-standalone}\nelse\n  ENABLE_NODE_PROBLEM_DETECTOR=${KUBE_ENABLE_NODE_PROBLEM_DETECTOR:-daemonset}\nfi\nexport ENABLE_NODE_PROBLEM_DETECTOR\nNODE_PROBLEM_DETECTOR_VERSION=${NODE_PROBLEM_DETECTOR_VERSION:-}\nNODE_PROBLEM_DETECTOR_TAR_HASH=${NODE_PROBLEM_DETECTOR_TAR_HASH:-}\nNODE_PROBLEM_DETECTOR_RELEASE_PATH=${NODE_PROBLEM_DETECTOR_RELEASE_PATH:-}\nNODE_PROBLEM_DETECTOR_CUSTOM_FLAGS=${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\n\nCNI_HASH=${CNI_HASH:-}\nCNI_TAR_PREFIX=${CNI_TAR_PREFIX:-cni-plugins-linux-amd64-}\nCNI_STORAGE_URL_BASE=${CNI_STORAGE_URL_BASE:-https://storage.googleapis.com/k8s-artifacts-cni/release}\n\n# Optional: Create autoscaler for cluster's nodes.\nexport ENABLE_CLUSTER_AUTOSCALER=${KUBE_ENABLE_CLUSTER_AUTOSCALER:-false}\nif [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" = 'true' ]]; then\n  export AUTOSCALER_MIN_NODES=${KUBE_AUTOSCALER_MIN_NODES:-}\n  export AUTOSCALER_MAX_NODES=${KUBE_AUTOSCALER_MAX_NODES:-}\n  export AUTOSCALER_ENABLE_SCALE_DOWN=${KUBE_AUTOSCALER_ENABLE_SCALE_DOWN:-false}\n  export AUTOSCALER_EXPANDER_CONFIG=${KUBE_AUTOSCALER_EXPANDER_CONFIG:---expander=price}\nfi\n\n# Optional: Enable allocation of pod IPs using IP aliases.\n#\n# BETA FEATURE.\n#\n# IP_ALIAS_SIZE is the size of the podCIDR allocated to a node.\n# IP_ALIAS_SUBNETWORK is the subnetwork to allocate from. If empty, a\n#   new subnetwork will be created for the cluster.\nENABLE_IP_ALIASES=${KUBE_GCE_ENABLE_IP_ALIASES:-false}\nexport NODE_IPAM_MODE=${KUBE_GCE_NODE_IPAM_MODE:-RangeAllocator}\nif [ \"${ENABLE_IP_ALIASES}\" = true ]; then\n  # Number of Pods that can run on this node.\n  MAX_PODS_PER_NODE=${MAX_PODS_PER_NODE:-110}\n  # Size of ranges allocated to each node.\n  IP_ALIAS_SIZE=\"/$(get-alias-range-size \"${MAX_PODS_PER_NODE}\")\"\n  IP_ALIAS_SUBNETWORK=${KUBE_GCE_IP_ALIAS_SUBNETWORK:-${INSTANCE_PREFIX}-subnet-default}\n  # If we're using custom network, use the subnet we already create for it as the one for ip-alias.\n  # Note that this means SUBNETWORK would override KUBE_GCE_IP_ALIAS_SUBNETWORK in case of custom network.\n  if [[ \"${CREATE_CUSTOM_NETWORK}\" = true ]]; then\n    IP_ALIAS_SUBNETWORK=${SUBNETWORK}\n  fi\n  export IP_ALIAS_SIZE\n  export IP_ALIAS_SUBNETWORK\n  # Reserve the services IP space to avoid being allocated for other GCP resources.\n  export SERVICE_CLUSTER_IP_SUBNETWORK=${KUBE_GCE_SERVICE_CLUSTER_IP_SUBNETWORK:-${INSTANCE_PREFIX}-subnet-services}\n  NODE_IPAM_MODE=${KUBE_GCE_NODE_IPAM_MODE:-CloudAllocator}\n  SECONDARY_RANGE_NAME=${SECONDARY_RANGE_NAME:-}\n  # Add to the provider custom variables.\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_IP_ALIASES\"\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} NODE_IPAM_MODE\"\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} SECONDARY_RANGE_NAME\"\nelse\n  if [[ -n \"${MAX_PODS_PER_NODE:-}\" ]]; then\n    # Should not have MAX_PODS_PER_NODE set for route-based clusters.\n    echo -e \"${color_red:-}Cannot set MAX_PODS_PER_NODE for route-based projects for ${PROJECT}.\" >&2\n    exit 1\n  fi\n  if [[ \"$(get-num-nodes)\" -gt 100 ]]; then\n    echo -e \"${color_red:-}Cannot create cluster with more than 100 nodes for route-based projects for ${PROJECT}.\" >&2\n    exit 1\n  fi\nfi\n\n# Enable GCE Alpha features.\nif [[ -n \"${GCE_ALPHA_FEATURES:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} GCE_ALPHA_FEATURES\"\nfi\n\n# Disable Docker live-restore.\nif [[ -n \"${DISABLE_DOCKER_LIVE_RESTORE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} DISABLE_DOCKER_LIVE_RESTORE\"\nfi\n\n# Override default GLBC image\nif [[ -n \"${GCE_GLBC_IMAGE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} GCE_GLBC_IMAGE\"\nfi\nCUSTOM_INGRESS_YAML=${CUSTOM_INGRESS_YAML:-}\n\nif [[ -z \"${KUBE_ADMISSION_CONTROL:-}\" ]]; then\n  ADMISSION_CONTROL='NamespaceLifecycle,LimitRanger,ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,NodeRestriction,Priority,StorageObjectInUseProtection,PersistentVolumeClaimResize,RuntimeClass'\n  if [[ \"${ENABLE_POD_SECURITY_POLICY:-}\" = 'true' ]]; then\n    ADMISSION_CONTROL=\"${ADMISSION_CONTROL},PodSecurityPolicy\"\n  fi\n  # ResourceQuota must come last, or a creation is recorded, but the pod may be forbidden.\n  ADMISSION_CONTROL=\"${ADMISSION_CONTROL},MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota\"\nelse\n  ADMISSION_CONTROL=${KUBE_ADMISSION_CONTROL}\nfi\n\nENABLE_APISERVER_DYNAMIC_AUDIT=${ENABLE_APISERVER_DYNAMIC_AUDIT:-false}\n\n# Optional: if set to true kube-up will automatically check for existing resources and clean them up.\nKUBE_UP_AUTOMATIC_CLEANUP=${KUBE_UP_AUTOMATIC_CLEANUP:-false}\n\n# Optional: setting it to true denotes this is a testing cluster,\n# so that we can use pulled kubernetes binaries, even if binaries\n# are pre-installed in the image. Note that currently this logic\n# is only supported in trusty or GCI.\nTEST_CLUSTER=${TEST_CLUSTER:-true}\n\n# Storage backend. 'etcd2' and 'etcd3' are supported.\nSTORAGE_BACKEND=${STORAGE_BACKEND:-}\n# Storage media type: application/json and application/vnd.kubernetes.protobuf are supported.\nSTORAGE_MEDIA_TYPE=${STORAGE_MEDIA_TYPE:-}\n\nNETWORK_PROVIDER=${NETWORK_PROVIDER:-kubenet} # none, kubenet\n\n# Network Policy plugin specific settings.\nNETWORK_POLICY_PROVIDER=${NETWORK_POLICY_PROVIDER:-none} # calico\n\nexport NON_MASQUERADE_CIDR='0.0.0.0/0'\n\n# How should the kubelet configure hairpin mode?\nHAIRPIN_MODE=${HAIRPIN_MODE:-hairpin-veth} # promiscuous-bridge, hairpin-veth, none\n\n# Optional: if set to true, kube-up will configure the cluster to run e2e tests.\nexport E2E_STORAGE_TEST_ENVIRONMENT=${KUBE_E2E_STORAGE_TEST_ENVIRONMENT:-false}\n\n# Evict pods whenever compute resource availability on the nodes gets below a threshold.\nEVICTION_HARD=${EVICTION_HARD:-memory.available<250Mi,nodefs.available<10%,nodefs.inodesFree<5%}\n\n# Optional: custom scheduling algorithm\nSCHEDULING_ALGORITHM_PROVIDER=${SCHEDULING_ALGORITHM_PROVIDER:-}\n\n# Optional: install a default StorageClass\nENABLE_DEFAULT_STORAGE_CLASS=${ENABLE_DEFAULT_STORAGE_CLASS:-true}\n\n# Optional: install volume snapshot CRDs\nENABLE_VOLUME_SNAPSHOTS=${ENABLE_VOLUME_SNAPSHOTS:-true}\n\n# Optional: Enable legacy ABAC policy that makes all service accounts superusers.\n# Disabling this by default in tests ensures default RBAC policies are sufficient from 1.6+\n# Upgrade test jobs that go from a version < 1.6 to a version >= 1.6 should override this to be true.\nENABLE_LEGACY_ABAC=${ENABLE_LEGACY_ABAC:-false} # true, false\n\n# Enable a simple \"AdvancedAuditing\" setup for testing.\nENABLE_APISERVER_ADVANCED_AUDIT=${ENABLE_APISERVER_ADVANCED_AUDIT:-true} # true, false\nADVANCED_AUDIT_LOG_MODE=${ADVANCED_AUDIT_LOG_MODE:-batch} # batch, blocking\n\nENABLE_BIG_CLUSTER_SUBNETS=${ENABLE_BIG_CLUSTER_SUBNETS:-false}\n\n# Optional: Enable log rotation for k8s services\nENABLE_LOGROTATE_FILES=\"${ENABLE_LOGROTATE_FILES:-true}\"\nPROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_LOGROTATE_FILES\"\nif [[ -n \"${LOGROTATE_FILES_MAX_COUNT:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} LOGROTATE_FILES_MAX_COUNT\"\nfi\nif [[ -n \"${LOGROTATE_MAX_SIZE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} LOGROTATE_MAX_SIZE\"\nfi\n\n# Optional: Enable log rotation for pod logs\nENABLE_POD_LOG=\"${ENABLE_POD_LOG:-false}\"\nPROVIDER_VARS=\"${PROVIDER_VARS:-} ENABLE_POD_LOG\"\n\nif [[ -n \"${POD_LOG_MAX_FILE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} POD_LOG_MAX_FILE\"\nfi\n\nif [[ -n \"${POD_LOG_MAX_SIZE:-}\" ]]; then\n  PROVIDER_VARS=\"${PROVIDER_VARS:-} POD_LOG_MAX_SIZE\"\nfi\n\n# Fluentd requirements\n# YAML exists to trigger a configuration refresh when changes are made.\nexport FLUENTD_GCP_YAML_VERSION='v3.2.0'\nFLUENTD_GCP_VERSION=${FLUENTD_GCP_VERSION:-1.6.17}\nFLUENTD_GCP_MEMORY_LIMIT=${FLUENTD_GCP_MEMORY_LIMIT:-}\nFLUENTD_GCP_CPU_REQUEST=${FLUENTD_GCP_CPU_REQUEST:-}\nFLUENTD_GCP_MEMORY_REQUEST=${FLUENTD_GCP_MEMORY_REQUEST:-}\n\n# Heapster requirements\nHEAPSTER_GCP_BASE_MEMORY=${HEAPSTER_GCP_BASE_MEMORY:-140Mi}\nHEAPSTER_GCP_MEMORY_PER_NODE=${HEAPSTER_GCP_MEMORY_PER_NODE:-4}\nHEAPSTER_GCP_BASE_CPU=${HEAPSTER_GCP_BASE_CPU:-80m}\nHEAPSTER_GCP_CPU_PER_NODE=${HEAPSTER_GCP_CPU_PER_NODE:-0.5}\n\n# Optional: custom system banner for dashboard addon\nCUSTOM_KUBE_DASHBOARD_BANNER=${CUSTOM_KUBE_DASHBOARD_BANNER:-}\n\n# Default Stackdriver resources version exported by Fluentd-gcp addon\nLOGGING_STACKDRIVER_RESOURCE_TYPES=${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}\n\n# Adding to PROVIDER_VARS, since this is GCP-specific.\nPROVIDER_VARS=\"${PROVIDER_VARS:-} FLUENTD_GCP_YAML_VERSION FLUENTD_GCP_VERSION FLUENTD_GCP_MEMORY_LIMIT FLUENTD_GCP_CPU_REQUEST FLUENTD_GCP_MEMORY_REQUEST HEAPSTER_GCP_BASE_MEMORY HEAPSTER_GCP_MEMORY_PER_NODE HEAPSTER_GCP_BASE_CPU HEAPSTER_GCP_CPU_PER_NODE CUSTOM_KUBE_DASHBOARD_BANNER LOGGING_STACKDRIVER_RESOURCE_TYPES\"\n\n# Fluentd configuration for node-journal\nENABLE_NODE_JOURNAL=${ENABLE_NODE_JOURNAL:-false}\n\n# prometheus-to-sd configuration\nPROMETHEUS_TO_SD_ENDPOINT=${PROMETHEUS_TO_SD_ENDPOINT:-https://monitoring.googleapis.com/}\nPROMETHEUS_TO_SD_PREFIX=${PROMETHEUS_TO_SD_PREFIX:-custom.googleapis.com}\nENABLE_PROMETHEUS_TO_SD=${ENABLE_PROMETHEUS_TO_SD:-true}\n\n# TODO(#51292): Make kube-proxy Daemonset default and remove the configuration here.\n# Optional: [Experiment Only] Run kube-proxy as a DaemonSet if set to true, run as static pods otherwise.\nKUBE_PROXY_DAEMONSET=${KUBE_PROXY_DAEMONSET:-false} # true, false\n\n# Control whether the startup scripts manage the lifecycle of kube-proxy\n# When true, the startup scripts do not enable kube-proxy either as a daemonset addon or as a static pod\n# regardless of the value of KUBE_PROXY_DAEMONSET.\n# When false, the value of KUBE_PROXY_DAEMONSET controls whether kube-proxy comes up as a static pod or\n# as an addon daemonset.\nKUBE_PROXY_DISABLE=\"${KUBE_PROXY_DISABLE:-false}\" # true, false\n\n# Optional: Change the kube-proxy implementation. Choices are [iptables, ipvs].\nKUBE_PROXY_MODE=${KUBE_PROXY_MODE:-iptables}\n\n# Will be passed into the kube-proxy via `--detect-local-mode`\nDETECT_LOCAL_MODE=\"${DETECT_LOCAL_MODE:-NodeCIDR}\"\n\n# Optional: duration of cluster signed certificates.\nCLUSTER_SIGNING_DURATION=${CLUSTER_SIGNING_DURATION:-}\n\n# Optional: enable certificate rotation of the kubelet certificates.\nROTATE_CERTIFICATES=${ROTATE_CERTIFICATES:-}\n\n# The number of services that are allowed to sync concurrently. Will be passed\n# into kube-controller-manager via `--concurrent-service-syncs`\nCONCURRENT_SERVICE_SYNCS=${CONCURRENT_SERVICE_SYNCS:-}\n\n# The value kubernetes.default.svc.cluster.local is only usable for full\n# OIDC discovery flows in Pods in the same cluster. For some providers\n# with configurations that support non-traditional KSA authentication methods,\n# this value may make sense, but if the expectation is traditional OIDC, don't\n# use this value in production. If you do use it, the FQDN is preferred to\n# kubernetes.default.svc, to avoid something outside the cluster attempting\n# to resolve the partially qualified name.\nexport SERVICEACCOUNT_ISSUER='https://kubernetes.default.svc.cluster.local'\n\n# Taint Windows nodes by default to prevent Linux workloads from being\n# scheduled onto them.\nWINDOWS_NODE_TAINTS=${WINDOWS_NODE_TAINTS:-node.kubernetes.io/os=win1809:NoSchedule}\n\n# Whether to set up a private GCE cluster, i.e. a cluster where nodes have only private IPs.\nexport GCE_PRIVATE_CLUSTER=${KUBE_GCE_PRIVATE_CLUSTER:-false}\nexport GCE_PRIVATE_CLUSTER_PORTS_PER_VM=${KUBE_GCE_PRIVATE_CLUSTER_PORTS_PER_VM:-}\n\nexport ETCD_LISTEN_CLIENT_IP=0.0.0.0\n\nexport GCE_UPLOAD_KUBCONFIG_TO_MASTER_METADATA=true\n\n# Optoinal: Enable Windows CSI-Proxy\nexport ENABLE_CSI_PROXY=\"${ENABLE_CSI_PROXY:-true}\"\n\n# KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP decides whether\n# kube-apiserver is healthchecked on host IP instead of 127.0.0.1.\nexport KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP=\"${KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP:-false}\"\n\n# ETCD_PROGRESS_NOTIFY_INTERVAL defines the interval for etcd watch progress notify events.\nexport ETCD_PROGRESS_NOTIFY_INTERVAL=\"${ETCD_PROGRESS_NOTIFY_INTERVAL:-5s}\"\n\n# Optional: Install Pigz on Windows.\n# Pigz is a multi-core optimized version of unzip.exe.\n# It improves container image pull performance since most time is spent\n# unzipping the image layers to disk.\nexport WINDOWS_ENABLE_PIGZ=\"${WINDOWS_ENABLE_PIGZ:-true}\"\n\n# Enable Windows DSR (Direct Server Return)\nexport WINDOWS_ENABLE_DSR=\"${WINDOWS_ENABLE_DSR:-false}\"\n\n# Install Node Problem Detector (NPD) on Windows nodes.\n# NPD analyzes the host for problems that can disrupt workloads.\nexport WINDOWS_ENABLE_NODE_PROBLEM_DETECTOR=\"${WINDOWS_ENABLE_NODE_PROBLEM_DETECTOR:-none}\"\nexport WINDOWS_NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS=\"${WINDOWS_NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\"\n\n# TLS_CIPHER_SUITES defines cipher suites allowed to be used by kube-apiserver.\n# If this variable is unset or empty, kube-apiserver will allow its default set of cipher suites.\nexport TLS_CIPHER_SUITES=\"\"\n", "num_lines": 614}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A utility for deleting target pools and forwarding rules that are unattached to VMs\nPROJECT=${PROJECT:-kubernetes-jenkins}\nREGION=${REGION:-us-central1}\n\nLIST=$(gcloud --project=\"${PROJECT}\" compute target-pools list --format='value(name)')\n\nresult=0\nfor x in ${LIST}; do\n    if ! gcloud compute --project=\"${PROJECT}\" target-pools get-health \"${x}\" --region=\"${REGION}\" 2>/dev/null >/dev/null; then\n\techo DELETING \"${x}\"\n\tgcloud compute --project=\"${PROJECT}\" firewall-rules delete \"k8s-fw-${x}\" -q\n\tgcloud compute --project=\"${PROJECT}\" forwarding-rules delete \"${x}\" --region=\"${REGION}\" -q\n\tgcloud compute --project=\"${PROJECT}\" addresses delete \"${x}\" --region=\"${REGION}\" -q\n\tgcloud compute --project=\"${PROJECT}\" target-pools delete \"${x}\" --region=\"${REGION}\" -q\n        result=1\n    fi\ndone\nexit ${result}\n\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Calls gcloud to print out a variety of Google Cloud Platform resources used by\n# Kubernetes. Can be run before/after test runs and compared to track leaking\n# resources.\n\n# PROJECT must be set in the environment.\n# If ZONE, KUBE_GCE_INSTANCE_PREFIX, CLUSTER_NAME, KUBE_GCE_NETWORK, or\n# KUBE_GKE_NETWORK is set, they will be used to filter the results.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nZONE=${ZONE:-}\nREGION=${ZONE%-*}\nINSTANCE_PREFIX=${KUBE_GCE_INSTANCE_PREFIX:-${CLUSTER_NAME:-}}\nNETWORK=${KUBE_GCE_NETWORK:-${KUBE_GKE_NETWORK:-}}\n\n# In GKE the instance prefix starts with \"gke-\".\nif [[ \"${KUBERNETES_PROVIDER:-}\" == \"gke\" ]]; then\n  INSTANCE_PREFIX=\"gke-${CLUSTER_NAME}\"\n  # Truncate to 26 characters for route prefix matching.\n  INSTANCE_PREFIX=\"${INSTANCE_PREFIX:0:26}\"\nfi\n\n# Usage: gcloud-list <group> <resource> <additional parameters to gcloud...>\n# GREP_REGEX is applied to the output of gcloud if set\nGREP_REGEX=\"\"\nfunction gcloud-list() {\n  local -r group=$1\n  local -r resource=$2\n  local -r filter=${3:-}\n  echo -e \"\\n\\n[ ${group} ${resource} ]\"\n  local attempt=1\n  local result=\"\"\n  while true; do\n    if result=$(gcloud \"${group}\" \"${resource}\" list --project=\"${PROJECT}\" ${filter:+--filter=\"$filter\"} \"${@:4}\"); then\n      if [[ -n \"${GREP_REGEX:-}\" ]]; then\n        result=$(echo \"${result}\" | grep \"${GREP_REGEX}\" || true)\n      fi\n      echo \"${result}\"\n      return\n    fi\n    echo -e \"Attempt ${attempt} failed to list ${resource}. Retrying.\" >&2\n    attempt=$((attempt + 1))\n    if [[ ${attempt} -gt 5 ]]; then\n      echo -e \"List ${resource} failed!\" >&2\n      exit 2\n    fi\n    sleep $((5 * attempt))\n  done\n}\n\necho \"Project: ${PROJECT}\"\necho \"Region: ${REGION}\"\necho \"Zone: ${ZONE}\"\necho \"Instance prefix: ${INSTANCE_PREFIX:-}\"\necho \"Network: ${NETWORK}\"\necho \"Provider: ${KUBERNETES_PROVIDER:-}\"\n\n# List resources related to instances, filtering by the instance prefix if\n# provided.\n\nset +e # do not stop on error\n\ngcloud-list compute instance-templates \"name ~ '${INSTANCE_PREFIX}.*'\"\ngcloud-list compute instance-groups \"${ZONE:+\"zone:(${ZONE}) AND \"}name ~ '${INSTANCE_PREFIX}.*'\"\ngcloud-list compute instances \"${ZONE:+\"zone:(${ZONE}) AND \"}name ~ '${INSTANCE_PREFIX}.*'\"\n\n# List disk resources, filtering by instance prefix if provided.\ngcloud-list compute disks \"${ZONE:+\"zone:(${ZONE}) AND \"}name ~ '${INSTANCE_PREFIX}.*'\"\n\n# List network resources. We include names starting with \"a\", corresponding to\n# those that Kubernetes creates.\ngcloud-list compute addresses \"${REGION:+\"region=(${REGION}) AND \"}name ~ 'a.*|${INSTANCE_PREFIX}.*'\"\n# Match either the header or a line with the specified e2e network.\n# This assumes that the network name is the second field in the output.\nGREP_REGEX=\"^NAME\\|^[^ ]\\+[ ]\\+\\(default\\|${NETWORK}\\) \"\ngcloud-list compute routes \"name ~ 'default.*|${INSTANCE_PREFIX}.*'\"\ngcloud-list compute firewall-rules \"name ~ 'default.*|k8s-fw.*|${INSTANCE_PREFIX}.*'\"\nGREP_REGEX=\"\"\ngcloud-list compute forwarding-rules ${REGION:+\"region=(${REGION})\"}\ngcloud-list compute target-pools ${REGION:+\"region=(${REGION})\"}\n\ngcloud-list logging sinks\n\nset -e\n", "num_lines": 103}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# !!!EXPERIMENTAL!!! Upgrade a K8s cluster from routes to IP aliases for\n# node connectivity on GCE. This is only for migration.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ \"${KUBERNETES_PROVIDER:-gce}\" != \"gce\" ]]; then\n  echo \"ERR: KUBERNETES_PROVIDER must be gce\" >&2\n  exit 1\nfi\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\n# Print the number of routes used for K8s cluster node connectivity.\n#\n# Assumed vars:\n#   PROJECT\nfunction get-k8s-node-routes-count() {\n  local k8s_node_routes_count\n  k8s_node_routes_count=$(gcloud compute routes list \\\n    --project=\"${PROJECT}\" --filter='description=k8s-node-route' \\\n    --format='value(name)' | wc -l)\n  echo -n \"${k8s_node_routes_count}\"\n}\n\n# Detect the subnetwork where the K8s cluster resides.\n#\n# Assumed vars:\n#  KUBE_MASTER\n#  PROJECT\n#  ZONE\n# Vars set:\n#  IP_ALIAS_SUBNETWORK\nfunction detect-k8s-subnetwork() {\n  local subnetwork_url\n  subnetwork_url=$(gcloud compute instances describe \\\n    \"${KUBE_MASTER}\" --project=\"${PROJECT}\" --zone=\"${ZONE}\" \\\n    --format='value(networkInterfaces[0].subnetwork)')\n  if [[ -n ${subnetwork_url} ]]; then\n    IP_ALIAS_SUBNETWORK=${subnetwork_url##*/}\n  fi\n}\n\n# Set IP_ALIAS_SUBNETWORK's allowSubnetCidrRoutesOverlap to a boolean value.\n# $1: true or false for the desired allowSubnetCidrRoutesOverlap.\n#\n# Assumed vars:\n#   IP_ALIAS_SUBNETWORK\n#   GCE_API_ENDPOINT\n#   PROJECT\n#   REGION\nfunction set-allow-subnet-cidr-routes-overlap() {\n  local allow_subnet_cidr_routes_overlap\n  allow_subnet_cidr_routes_overlap=$(gcloud compute networks subnets \\\n    describe \"${IP_ALIAS_SUBNETWORK}\" --project=\"${PROJECT}\" --region=\"${REGION}\" \\\n    --format='value(allowSubnetCidrRoutesOverlap)')\n  local allow_overlap=$1\n  if [ \"${allow_subnet_cidr_routes_overlap,,}\" = \"${allow_overlap}\" ]; then\n    echo \"Subnet ${IP_ALIAS_SUBNETWORK}'s allowSubnetCidrRoutesOverlap is already set as $1\"\n    return\n  fi\n\n  echo \"Setting subnet \\\"${IP_ALIAS_SUBNETWORK}\\\" allowSubnetCidrRoutesOverlap to $1\"\n  local fingerprint\n  fingerprint=$(gcloud compute networks subnets describe \\\n    \"${IP_ALIAS_SUBNETWORK}\" --project=\"${PROJECT}\" --region=\"${REGION}\" \\\n    --format='value(fingerprint)')\n  local access_token\n  access_token=$(gcloud auth print-access-token)\n  local request=\"{\\\"allowSubnetCidrRoutesOverlap\\\":$1, \\\"fingerprint\\\":\\\"${fingerprint}\\\"}\"\n  local subnetwork_url\n  subnetwork_url=\"${GCE_API_ENDPOINT}projects/${PROJECT}/regions/${REGION}/subnetworks/${IP_ALIAS_SUBNETWORK}\"\n  until curl -s --header \"Content-Type: application/json\" --header \"Authorization: Bearer ${access_token}\" \\\n    -X PATCH -d \"${request}\" \"${subnetwork_url}\" --output /dev/null; do\n    printf \".\"\n    sleep 1\n  done\n}\n\n# Add secondary ranges to K8s subnet.\n#\n# Assumed vars:\n#   IP_ALIAS_SUBNETWORK\n#   PROJECT\n#   REGION\n#   CLUSTER_IP_RANGE\n#   SERVICE_CLUSTER_IP_RANGE\nfunction add-k8s-subnet-secondary-ranges() {\n  local secondary_ranges\n  secondary_ranges=$(gcloud compute networks subnets describe \"${IP_ALIAS_SUBNETWORK}\" \\\n    --project=\"${PROJECT}\" --region=\"${REGION}\" \\\n    --format='value(secondaryIpRanges)')\n  if [[ \"${secondary_ranges}\" =~ \"pods-default\" && \"${secondary_ranges}\" =~ \"services-default\" ]]; then\n    echo \"${secondary_ranges} already contains both pods-default and services-default secondary ranges\"\n    return\n  fi\n\n  echo \"Adding secondary ranges: pods-default (${CLUSTER_IP_RANGE}), services-default (${SERVICE_CLUSTER_IP_RANGE})\"\n  until gcloud compute networks subnets update \"${IP_ALIAS_SUBNETWORK}\" \\\n    --project=\"${PROJECT}\" --region=\"${REGION}\" \\\n    --add-secondary-ranges=\"pods-default=${CLUSTER_IP_RANGE},services-default=${SERVICE_CLUSTER_IP_RANGE}\"; do\n    printf \".\"\n    sleep 1\n  done\n}\n\n# Delete all K8s node routes.\n#\n# Assumed vars:\n#   PROJECT\nfunction delete-k8s-node-routes() {\n  local -a routes\n  local -r batch=200\n  routes=()\n  while IFS=$'\\n' read -r route; do\n    routes+=( \"${route}\" )\n  done < <(gcloud compute routes list \\\n    --project=\"${PROJECT}\" --filter='description=k8s-node-route' \\\n    --format='value(name)')\n  while (( \"${#routes[@]}\" > 0 )); do\n      echo Deleting k8s node routes \"${routes[*]::${batch}}\"\n      gcloud compute routes delete --project \"${PROJECT}\" --quiet \"${routes[@]::${batch}}\"\n      routes=( \"${routes[@]:${batch}}\" )\n  done\n}\n\ndetect-project\ndetect-master\n\nk8s_node_routes_count=$(get-k8s-node-routes-count)\nif [[ \"${k8s_node_routes_count}\" -eq 0 ]]; then\n  echo \"No k8s node routes found and IP alias should already be enabled. Exiting...\"\n  exit 0\nfi\necho \"Found ${k8s_node_routes_count} K8s node routes. Proceeding to upgrade them to IP aliases based connectivity...\"\n\ndetect-k8s-subnetwork\nif [ -z \"${IP_ALIAS_SUBNETWORK}\" ]; then\n  echo \"No k8s cluster subnetwork found. Exiting...\"\n  exit 1\nfi\necho \"k8s cluster sits on subnetwork \\\"${IP_ALIAS_SUBNETWORK}\\\"\"\n\nset-allow-subnet-cidr-routes-overlap true\nadd-k8s-subnet-secondary-ranges\n\necho \"Changing K8s master envs and restarting...\"\nexport KUBE_GCE_IP_ALIAS_SUBNETWORK=${IP_ALIAS_SUBNETWORK}\nexport KUBE_GCE_NODE_IPAM_MODE=\"IPAMFromCluster\"\nexport KUBE_GCE_ENABLE_IP_ALIASES=true\nexport SECONDARY_RANGE_NAME=\"pods-default\"\nexport STORAGE_BACKEND=\"etcd3\"\nexport STORAGE_MEDIA_TYPE=\"application/vnd.kubernetes.protobuf\"\nexport ETCD_IMAGE=3.5.0-rc.0-0\nexport ETCD_VERSION=3.5.0-rc.0\n\n# Upgrade master with updated kube envs\n\"${KUBE_ROOT}/cluster/gce/upgrade.sh\" -M -l\n\ndelete-k8s-node-routes\nset-allow-subnet-cidr-routes-overlap false\n", "num_lines": 181}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# !!!EXPERIMENTAL !!! Upgrade script for GCE. Expect this to get\n# rewritten in Go in relatively short order, but it allows us to start\n# testing the concepts.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ \"${KUBERNETES_PROVIDER:-gce}\" != \"gce\" ]]; then\n  echo \"!!! ${1} only works on GCE\" >&2\n  exit 1\nfi\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nfunction usage() {\n  echo \"!!! EXPERIMENTAL !!!\"\n  echo \"!!! This upgrade script is not meant to be run in production !!!\"\n  echo \"\"\n  echo \"${0} [-M | -N | -P] [-o] (-l | <version number or publication>)\"\n  echo \"  Upgrades master and nodes by default\"\n  echo \"  -M:  Upgrade master only\"\n  echo \"  -N:  Upgrade nodes only\"\n  echo \"  -P:  Node upgrade prerequisites only (create a new instance template)\"\n  echo \"  -c:  Upgrade NODE_UPGRADE_PARALLELISM nodes in parallel (default=1) within a single instance group. The MIGs themselves are dealt serially.\"\n  echo \"  -o:  Use os distro specified in KUBE_NODE_OS_DISTRIBUTION for new nodes. Options include 'debian' or 'gci'\"\n  echo \"  -l:  Use local(dev) binaries. This is only supported for master upgrades.\"\n  echo \"\"\n  echo '  Version number or publication is either a proper version number'\n  echo '  (e.g. \"v1.0.6\", \"v1.2.0-alpha.1.881+376438b69c7612\") or a version'\n  echo '  publication of the form <bucket>/<version> (e.g. \"release/stable\",'\n  echo '  \"ci/latest-1\").  Some common ones are:'\n  echo '    - \"release/stable\"'\n  echo '    - \"release/latest\"'\n  echo '    - \"ci/latest\"'\n  echo '  See the docs on getting builds for more information about version publication.'\n  echo \"\"\n  echo \"(... Fetching current release versions ...)\"\n  echo \"\"\n\n  # NOTE: IF YOU CHANGE THE FOLLOWING LIST, ALSO UPDATE test/e2e/cluster_upgrade.go\n  local release_stable\n  local release_latest\n  local ci_latest\n\n  release_stable=$(gsutil cat gs://kubernetes-release/release/stable.txt)\n  release_latest=$(gsutil cat gs://kubernetes-release/release/latest.txt)\n  ci_latest=$(gsutil cat gs://kubernetes-release-dev/ci/latest.txt)\n\n  echo \"Right now, versions are as follows:\"\n  echo \"  release/stable: ${0} ${release_stable}\"\n  echo \"  release/latest: ${0} ${release_latest}\"\n  echo \"  ci/latest:      ${0} ${ci_latest}\"\n}\n\nfunction print-node-version-info() {\n  echo \"== $1 Node OS and Kubelet Versions ==\"\n  \"${KUBE_ROOT}/cluster/kubectl.sh\" get nodes -o=jsonpath='{range .items[*]}name: \"{.metadata.name}\", osImage: \"{.status.nodeInfo.osImage}\", kubeletVersion: \"{.status.nodeInfo.kubeletVersion}\"{\"\\n\"}{end}'\n}\n\nfunction upgrade-master() {\n  local num_masters\n  num_masters=$(get-master-replicas-count)\n  if [[ \"${num_masters}\" -gt 1 ]]; then\n    echo \"Upgrade of master not supported if more than one master replica present. The current number of master replicas: ${num_masters}\"\n    exit 1\n  fi\n\n  echo \"== Upgrading master to '${SERVER_BINARY_TAR_URL}'. Do not interrupt, deleting master instance. ==\"\n\n  # Tries to figure out KUBE_USER/KUBE_PASSWORD by first looking under\n  # kubeconfig:username, and then under kubeconfig:username-basic-auth.\n  # TODO: KUBE_USER is used in generating ABAC policy which the\n  # apiserver may not have enabled. If it's enabled, we must have a user\n  # to generate a valid ABAC policy. If the username changes, should\n  # the script fail? Should we generate a default username and password\n  # if the section is missing in kubeconfig? Handle this better in 1.5.\n  get-kubeconfig-basicauth\n  get-kubeconfig-bearertoken\n\n  detect-master\n  parse-master-env\n  upgrade-master-env\n\n  # Delete the master instance. Note that the master-pd is created\n  # with auto-delete=no, so it should not be deleted.\n  gcloud compute instances delete \\\n    --project \"${PROJECT}\" \\\n    --quiet \\\n    --zone \"${ZONE}\" \\\n    \"${MASTER_NAME}\"\n\n  create-master-instance \"${MASTER_NAME}-ip\"\n  wait-for-master\n}\n\nfunction upgrade-master-env() {\n  echo \"== Upgrading master environment variables. ==\"\n  # Generate the node problem detector token if it isn't present on the original\n  # master.\n if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" && \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\" == \"\" ]]; then\n    NODE_PROBLEM_DETECTOR_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n  fi\n}\n\nfunction wait-for-master() {\n  echo \"== Waiting for new master to respond to API requests ==\"\n\n  local curl_auth_arg\n  if [[ -n ${KUBE_BEARER_TOKEN:-} ]]; then\n    curl_auth_arg=(-H \"Authorization: Bearer ${KUBE_BEARER_TOKEN}\")\n  elif [[ -n ${KUBE_PASSWORD:-} ]]; then\n    curl_auth_arg=(--user \"${KUBE_USER}:${KUBE_PASSWORD}\")\n  else\n    echo \"can't get auth credentials for the current master\"\n    exit 1\n  fi\n\n  until curl --insecure \"${curl_auth_arg[@]}\" --max-time 5 \\\n    --fail --output /dev/null --silent \"https://${KUBE_MASTER_IP}/healthz\"; do\n    printf \".\"\n    sleep 2\n  done\n\n  echo \"== Done ==\"\n}\n\n# Perform common upgrade setup tasks\n#\n# Assumed vars\n#   KUBE_VERSION\nfunction prepare-upgrade() {\n  kube::util::ensure-temp-dir\n  detect-project\n  detect-subnetworks\n  detect-node-names # sets INSTANCE_GROUPS\n  write-cluster-location\n  write-cluster-name\n  tars_from_version\n}\n\n# Reads kube-env metadata from first node in NODE_NAMES.\n#\n# Assumed vars:\n#   NODE_NAMES\n#   PROJECT\n#   ZONE\nfunction get-node-env() {\n  # TODO(zmerlynn): Make this more reliable with retries.\n  gcloud compute --project \"${PROJECT}\" ssh --zone \"${ZONE}\" \"${NODE_NAMES[0]}\" --command \\\n    \"curl --fail --silent -H 'Metadata-Flavor: Google' \\\n      'http://metadata/computeMetadata/v1/instance/attributes/kube-env'\" 2>/dev/null\n}\n\n# Read os distro information from /os/release on node.\n# $1: The name of node\n#\n# Assumed vars:\n#   PROJECT\n#   ZONE\nfunction get-node-os() {\n  gcloud compute ssh \"$1\" \\\n    --project \"${PROJECT}\" \\\n    --zone \"${ZONE}\" \\\n    --command \\\n    \"cat /etc/os-release | grep \\\"^ID=.*\\\" | cut -c 4-\"\n}\n\n# Assumed vars:\n#   KUBE_VERSION\n#   NODE_SCOPES\n#   NODE_INSTANCE_PREFIX\n#   PROJECT\n#   ZONE\n#\n# Vars set:\n#   KUBE_PROXY_TOKEN\n#   NODE_PROBLEM_DETECTOR_TOKEN\n#   CA_CERT_BASE64\n#   EXTRA_DOCKER_OPTS\n#   KUBELET_CERT_BASE64\n#   KUBELET_KEY_BASE64\nfunction upgrade-nodes() {\n  prepare-node-upgrade\n  do-node-upgrade\n}\n\nfunction setup-base-image() {\n  if [[ \"${env_os_distro}\" == \"false\" ]]; then\n    echo \"== Ensuring that new Node base OS image matched the existing Node base OS image\"\n    NODE_OS_DISTRIBUTION=$(get-node-os \"${NODE_NAMES[0]}\")\n\n    if [[ \"${NODE_OS_DISTRIBUTION}\" == \"cos\" ]]; then\n        NODE_OS_DISTRIBUTION=\"gci\"\n    fi\n\n    source \"${KUBE_ROOT}/cluster/gce/${NODE_OS_DISTRIBUTION}/node-helper.sh\"\n    # Reset the node image based on current os distro\n    set-linux-node-image\n  fi\n}\n\n# prepare-node-upgrade creates a new instance template suitable for upgrading\n# to KUBE_VERSION and echos a single line with the name of the new template.\n#\n# Assumed vars:\n#   KUBE_VERSION\n#   NODE_SCOPES\n#   NODE_INSTANCE_PREFIX\n#   PROJECT\n#   ZONE\n#\n# Vars set:\n#   SANITIZED_VERSION\n#   INSTANCE_GROUPS\n#   KUBE_PROXY_TOKEN\n#   NODE_PROBLEM_DETECTOR_TOKEN\n#   CA_CERT_BASE64\n#   EXTRA_DOCKER_OPTS\n#   KUBELET_CERT_BASE64\n#   KUBELET_KEY_BASE64\nfunction prepare-node-upgrade() {\n  echo \"== Preparing node upgrade (to ${KUBE_VERSION}). ==\" >&2\n  setup-base-image\n\n  SANITIZED_VERSION=\"${KUBE_VERSION//[\\.\\+]/-}\"\n\n  # TODO(zmerlynn): Refactor setting scope flags.\n  local scope_flags=\n  if [ -n \"${NODE_SCOPES}\" ]; then\n    scope_flags=\"--scopes ${NODE_SCOPES}\"\n  else\n    # shellcheck disable=SC2034 # 'scope_flags' is used by upstream\n    scope_flags=\"--no-scopes\"\n  fi\n\n  # Get required node env vars from exiting template.\n  local node_env\n  node_env=$(get-node-env)\n  KUBE_PROXY_TOKEN=$(get-env-val \"${node_env}\" \"KUBE_PROXY_TOKEN\")\n  export KUBE_PROXY_TOKEN\n  NODE_PROBLEM_DETECTOR_TOKEN=$(get-env-val \"${node_env}\" \"NODE_PROBLEM_DETECTOR_TOKEN\")\n  CA_CERT_BASE64=$(get-env-val \"${node_env}\" \"CA_CERT\")\n  export CA_CERT_BASE64\n  EXTRA_DOCKER_OPTS=$(get-env-val \"${node_env}\" \"EXTRA_DOCKER_OPTS\")\n  export EXTRA_DOCKER_OPTS\n  KUBELET_CERT_BASE64=$(get-env-val \"${node_env}\" \"KUBELET_CERT\")\n  export KUBELET_CERT_BASE64\n  KUBELET_KEY_BASE64=$(get-env-val \"${node_env}\" \"KUBELET_KEY\")\n  export KUBELET_KEY_BASE64\n\n  upgrade-node-env\n\n  # TODO(zmerlynn): How do we ensure kube-env is written in a ${version}-\n  #                 compatible way?\n  write-linux-node-env\n\n  # TODO(zmerlynn): Get configure-vm script from ${version}. (Must plumb this\n  #                 through all create-linux-node-instance-template implementations).\n  local template_name\n  template_name=$(get-template-name-from-version \"${SANITIZED_VERSION}\" \"${NODE_INSTANCE_PREFIX}\")\n  create-linux-node-instance-template \"${template_name}\"\n  # The following is echo'd so that callers can get the template name.\n  echo \"Instance template name: ${template_name}\"\n  echo \"== Finished preparing node upgrade (to ${KUBE_VERSION}). ==\" >&2\n}\n\nfunction upgrade-node-env() {\n  echo \"== Upgrading node environment variables. ==\"\n  # Get the node problem detector token from master if it isn't present on\n  # the original node.\n  if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" && \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\" == \"\" ]]; then\n    detect-master\n    local master_env\n    master_env=$(get-master-env)\n    NODE_PROBLEM_DETECTOR_TOKEN=$(get-env-val \"${master_env}\" \"NODE_PROBLEM_DETECTOR_TOKEN\")\n  fi\n}\n\n# Upgrades a single node.\n# $1: The name of the node\n#\n# Note: This is called multiple times from do-node-upgrade() in parallel, so should be thread-safe.\nfunction do-single-node-upgrade() {\n  local -r instance=\"$1\"\n  local kubectl_rc\n  local boot_id\n  boot_id=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" get node \"${instance}\" --output=jsonpath='{.status.nodeInfo.bootID}' 2>&1) && kubectl_rc=$? || kubectl_rc=$?\n  if [[ \"${kubectl_rc}\" != 0 ]]; then\n    echo \"== FAILED to get bootID ${instance} ==\"\n    echo \"${boot_id}\"\n    return ${kubectl_rc}\n  fi\n\n  # Drain node\n  echo \"== Draining ${instance}. == \" >&2\n  local drain_rc\n  \"${KUBE_ROOT}/cluster/kubectl.sh\" drain --delete-emptydir-data --force --ignore-daemonsets \"${instance}\" \\\n    && drain_rc=$? || drain_rc=$?\n  if [[ \"${drain_rc}\" != 0 ]]; then\n    echo \"== FAILED to drain ${instance} ==\"\n    return ${drain_rc}\n  fi\n\n  # Recreate instance\n  echo \"== Recreating instance ${instance}. ==\" >&2\n  local recreate_rc\n  local recreate\n  recreate=$(gcloud compute instance-groups managed recreate-instances \"${group}\" \\\n    --project=\"${PROJECT}\" \\\n    --zone=\"${ZONE}\" \\\n    --instances=\"${instance}\" 2>&1) && recreate_rc=$? || recreate_rc=$?\n  if [[ \"${recreate_rc}\" != 0 ]]; then\n    echo \"== FAILED to recreate ${instance} ==\"\n    echo \"${recreate}\"\n    return ${recreate_rc}\n  fi\n\n  # Wait for node status to reflect a new boot ID. This guarantees us\n  # that the node status in the API is from a different boot. This\n  # does not guarantee that the status is from the upgraded node, but\n  # it is a best effort approximation.\n  echo \"== Waiting for new node to be added to k8s.  ==\" >&2\n  while true; do\n    local new_boot_id\n    new_boot_id=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" get node \"${instance}\" --output=jsonpath='{.status.nodeInfo.bootID}' 2>&1) && kubectl_rc=$? || kubectl_rc=$?\n    if [[ \"${kubectl_rc}\" != 0 ]]; then\n      echo \"== FAILED to get node ${instance} ==\"\n      echo \"${boot_id}\"\n      echo \"  (Will retry.)\"\n    elif [[ \"${boot_id}\" != \"${new_boot_id}\" ]]; then\n      echo \"Node ${instance} recreated.\"\n      break\n    else\n      echo -n .\n    fi\n    sleep 1\n  done\n\n  # Wait for the node to have Ready=True.\n  echo \"== Waiting for ${instance} to become ready. ==\" >&2\n  while true; do\n    local ready\n    ready=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" get node \"${instance}\" --output='jsonpath={.status.conditions[?(@.type == \"Ready\")].status}')\n    if [[ \"${ready}\" != 'True' ]]; then\n      echo \"Node ${instance} is still not ready: Ready=${ready}\"\n    else\n      echo \"Node ${instance} Ready=${ready}\"\n      break\n    fi\n    sleep 1\n  done\n\n  # Uncordon the node.\n  echo \"== Uncordon ${instance}. == \" >&2\n  local uncordon_rc\n  \"${KUBE_ROOT}/cluster/kubectl.sh\" uncordon \"${instance}\" \\\n    && uncordon_rc=$? || uncordon_rc=$?\n  if [[ \"${uncordon_rc}\" != 0 ]]; then\n    echo \"== FAILED to uncordon ${instance} ==\"\n    return ${uncordon_rc}\n  fi\n}\n\n# Prereqs:\n# - prepare-node-upgrade should have been called successfully\nfunction do-node-upgrade() {\n  echo \"== Upgrading nodes to ${KUBE_VERSION} with max parallelism of ${node_upgrade_parallelism}. ==\" >&2\n  # Do the actual upgrade.\n  # NOTE(zmerlynn): If you are changing this gcloud command, update\n  #                 test/e2e/cluster_upgrade.go to match this EXACTLY.\n  local template_name\n  template_name=$(get-template-name-from-version \"${SANITIZED_VERSION}\" \"${NODE_INSTANCE_PREFIX}\")\n  local old_templates=()\n  for group in \"${INSTANCE_GROUPS[@]}\"; do\n    while IFS='' read -r line; do old_templates+=(\"$line\"); done < <(gcloud compute instance-groups managed list \\\n        --project=\"${PROJECT}\" \\\n        --filter=\"name ~ '${group}' AND zone:(${ZONE})\" \\\n        --format='value(instanceTemplate)' || true)\n    set_instance_template_out=$(gcloud compute instance-groups managed set-instance-template \"${group}\" \\\n      --template=\"${template_name}\" \\\n      --project=\"${PROJECT}\" \\\n      --zone=\"${ZONE}\" 2>&1) && set_instance_template_rc=$? || set_instance_template_rc=$?\n    if [[ \"${set_instance_template_rc}\" != 0 ]]; then\n      echo \"== FAILED to set-instance-template for ${group} to ${template_name} ==\"\n      echo \"${set_instance_template_out}\"\n      return ${set_instance_template_rc}\n    fi\n    instances=()\n    while IFS='' read -r line; do instances+=(\"$line\"); done < <(gcloud compute instance-groups managed list-instances \"${group}\" \\\n        --format='value(instance)' \\\n        --project=\"${PROJECT}\" \\\n        --zone=\"${ZONE}\" 2>&1) && list_instances_rc=$? || list_instances_rc=$?\n    if [[ \"${list_instances_rc}\" != 0 ]]; then\n      echo \"== FAILED to list instances in group ${group} ==\"\n      echo \"${instances[@]}\"\n      return ${list_instances_rc}\n    fi\n\n    process_count_left=${node_upgrade_parallelism}\n    pids=()\n    ret_code_sum=0  # Should stay 0 in the loop iff all parallel node upgrades succeed.\n    for instance in \"${instances[@]}\"; do\n      do-single-node-upgrade \"${instance}\" & pids+=(\"$!\")\n\n      # We don't want to run more than ${node_upgrade_parallelism} upgrades at a time,\n      # so wait once we hit that many nodes. This isn't ideal, since one might take much\n      # longer than the others, but it should help.\n      process_count_left=$((process_count_left - 1))\n      if [[ process_count_left -eq 0 || \"${instance}\" == \"${instances[-1]}\" ]]; then\n        # Wait for each of the parallel node upgrades to finish.\n        for pid in \"${pids[@]}\"; do\n          wait \"$pid\"\n          ret_code_sum=$(( ret_code_sum + $? ))\n        done\n        # Return even if at least one of the node upgrades failed.\n        if [[ ${ret_code_sum} != 0 ]]; then\n          echo \"== Some of the ${node_upgrade_parallelism} parallel node upgrades failed. ==\"\n          return ${ret_code_sum}\n        fi\n        process_count_left=${node_upgrade_parallelism}\n      fi\n    done\n  done\n\n  # Remove the old templates.\n  echo \"== Deleting old templates in ${PROJECT}. ==\" >&2\n  for tmpl in \"${old_templates[@]}\"; do\n    gcloud compute instance-templates delete \\\n        --quiet \\\n        --project=\"${PROJECT}\" \\\n        \"${tmpl}\" || true\n  done\n\n  echo \"== Finished upgrading nodes to ${KUBE_VERSION}. ==\" >&2\n}\n\n\nfunction update-coredns-config() {\n  # Get the current CoreDNS version\n  local -r coredns_addon_path=\"/etc/kubernetes/addons/0-dns/coredns\"\n  local -r tmpdir=/tmp\n  local -r download_dir=$(mktemp --tmpdir=${tmpdir} -d coredns-migration.XXXXXXXXXX) || exit 1\n\n  # clean up\n  cleanup() {\n    if [ -n \"${download_dir:-}\" ]; then\n      rm -rf \"${download_dir}\"\n    fi\n  }\n  trap cleanup RETURN\n\n  # Get the new installed CoreDNS version\n  echo \"== Waiting for CoreDNS to update ==\"\n  local -r endtime=$(date -ud \"3 minute\" +%s)\n  until [[ $(\"${KUBE_ROOT}\"/cluster/kubectl.sh -n kube-system get deployment coredns -o=jsonpath='{$.metadata.resourceVersion}') -ne ${COREDNS_DEPLOY_RESOURCE_VERSION} ]] || [[ $(date -u +%s) -gt $endtime ]]; do\n     sleep 1\n  done\n\n  if [[ $(\"${KUBE_ROOT}\"/cluster/kubectl.sh -n kube-system get deployment coredns -o=jsonpath='{$.metadata.resourceVersion}') -ne ${COREDNS_DEPLOY_RESOURCE_VERSION} ]]; then\n    echo \"== CoreDNS ResourceVersion changed ==\"\n  fi\n\n  echo \"== Fetching the latest installed CoreDNS version ==\"\n  NEW_COREDNS_VERSION=$(\"${KUBE_ROOT}\"/cluster/kubectl.sh -n kube-system get deployment coredns -o=jsonpath='{$.spec.template.spec.containers[:1].image}' | sed -r 's/.+:v?(.+)/\\1/')\n\n  case \"$(uname -m)\" in\n      x86_64*)\n        host_arch=amd64\n        corefile_tool_SHA=\"9f2027243e40c939b119684e26c393e06ef6c5a4a4894d3bcfce5be8179ccb24\"\n        ;;\n      i?86_64*)\n        host_arch=amd64\n        corefile_tool_SHA=\"9f2027243e40c939b119684e26c393e06ef6c5a4a4894d3bcfce5be8179ccb24\"\n        ;;\n      amd64*)\n        host_arch=amd64\n        corefile_tool_SHA=\"9f2027243e40c939b119684e26c393e06ef6c5a4a4894d3bcfce5be8179ccb24\"\n        ;;\n      aarch64*)\n        host_arch=arm64\n        corefile_tool_SHA=\"970860aeb9f9dfb83f5b2debd812ac2fe3e147e6120b94d3e92eb3421edb51d0\"\n        ;;\n      arm64*)\n        host_arch=arm64\n        corefile_tool_SHA=\"970860aeb9f9dfb83f5b2debd812ac2fe3e147e6120b94d3e92eb3421edb51d0\"\n        ;;\n      arm*)\n        host_arch=arm\n        corefile_tool_SHA=\"43a0aaab91a5f8911c689daeeb3237f4630124cc2c92c8d74d3667d88786a93d\"\n        ;;\n      s390x*)\n        host_arch=s390x\n        corefile_tool_SHA=\"303835430e9bf7c35c387a35018e8da3c12585968934d5dccd9190145efa2fda\"\n        ;;\n      ppc64le*)\n        host_arch=ppc64le\n        corefile_tool_SHA=\"0900b74f6ae5631aca953dd126dd0463fc6cff8ecb92094b2b283373951b572f\"\n        ;;\n      *)\n        echo \"Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le.\" >&2\n        exit 1\n        ;;\n    esac\n\n  # Download the CoreDNS migration tool\n  echo \"== Downloading the CoreDNS migration tool ==\"\n  wget -P \"${download_dir}\" \"https://github.com/coredns/corefile-migration/releases/download/v1.0.11/corefile-tool-${host_arch}\" >/dev/null 2>&1\n\n  local -r checkSHA=$(sha256sum \"${download_dir}/corefile-tool-${host_arch}\" | cut -d \" \" -f 1)\n  if [[ \"${checkSHA}\" != \"${corefile_tool_SHA}\" ]]; then\n    echo \"!!! CheckSum for the CoreDNS migration tool did not match !!!\" >&2\n    exit 1\n  fi\n\n  chmod +x \"${download_dir}/corefile-tool-${host_arch}\"\n\n  # Migrate the CoreDNS ConfigMap depending on whether it is being downgraded or upgraded.\n  \"${KUBE_ROOT}/cluster/kubectl.sh\" -n kube-system get cm coredns -o jsonpath='{.data.Corefile}' > \"${download_dir}/Corefile-old\"\n\n  if test \"$(printf '%s\\n' \"${CURRENT_COREDNS_VERSION}\" \"${NEW_COREDNS_VERSION}\" | sort -V | head -n 1)\" != \"${NEW_COREDNS_VERSION}\"; then\n     echo \"== Upgrading the CoreDNS ConfigMap ==\"\n     \"${download_dir}/corefile-tool-${host_arch}\" migrate --from \"${CURRENT_COREDNS_VERSION}\" --to \"${NEW_COREDNS_VERSION}\" --corefile \"${download_dir}/Corefile-old\" > \"${download_dir}/Corefile\"\n     \"${KUBE_ROOT}/cluster/kubectl.sh\" -n kube-system create configmap coredns --from-file \"${download_dir}/Corefile\" -o yaml --dry-run=client | \"${KUBE_ROOT}/cluster/kubectl.sh\" apply -f -\n  else\n     # In case of a downgrade, a custom CoreDNS Corefile will be overwritten by a default Corefile. In that case,\n     # the user will need to manually modify the resulting (default) Corefile after the downgrade is complete.\n     echo \"== Applying the latest default CoreDNS configuration ==\"\n     gcloud compute --project \"${PROJECT}\"  scp --zone \"${ZONE}\" \"${MASTER_NAME}:${coredns_addon_path}/coredns.yaml\" \"${download_dir}/coredns-manifest.yaml\" > /dev/null\n     \"${KUBE_ROOT}/cluster/kubectl.sh\" apply -f \"${download_dir}/coredns-manifest.yaml\"\n  fi\n\n  echo \"== The CoreDNS Config has been updated ==\"\n}\n\necho \"Fetching the previously installed CoreDNS version\"\nCURRENT_COREDNS_VERSION=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" -n kube-system get deployment coredns -o=jsonpath='{$.spec.template.spec.containers[:1].image}' | sed -r 's/.+:v?(.+)/\\1/')\nCOREDNS_DEPLOY_RESOURCE_VERSION=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" -n kube-system get deployment coredns -o=jsonpath='{$.metadata.resourceVersion}')\n\nmaster_upgrade=true\nnode_upgrade=true\nnode_prereqs=false\nlocal_binaries=false\nenv_os_distro=false\nnode_upgrade_parallelism=1\n\nwhile getopts \":MNPlcho\" opt; do\n  case \"${opt}\" in\n    M)\n      node_upgrade=false\n      ;;\n    N)\n      master_upgrade=false\n      ;;\n    P)\n      node_prereqs=true\n      ;;\n    l)\n      local_binaries=true\n      ;;\n    c)\n      node_upgrade_parallelism=${NODE_UPGRADE_PARALLELISM:-1}\n      ;;\n    o)\n      env_os_distro=true\n      ;;\n    h)\n      usage\n      exit 0\n      ;;\n    \\?)\n      echo \"Invalid option: -$OPTARG\" >&2\n      usage\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [[ $# -gt 1 ]]; then\n  echo \"Error: Only one parameter (<version number or publication>) may be passed after the set of flags!\" >&2\n  usage\n  exit 1\nfi\n\nif [[ $# -lt 1 ]] && [[ \"${local_binaries}\" == \"false\" ]]; then\n  usage\n  exit 1\nfi\n\nif [[ \"${master_upgrade}\" == \"false\" ]] && [[ \"${node_upgrade}\" == \"false\" ]]; then\n  echo \"Can't specify both -M and -N\" >&2\n  exit 1\nfi\n\n# prompt if etcd storage media type isn't set unless using etcd2 when doing master upgrade\nif [[ -z \"${STORAGE_MEDIA_TYPE:-}\" ]] && [[ \"${STORAGE_BACKEND:-}\" != \"etcd2\" ]] && [[ \"${master_upgrade}\" == \"true\" ]]; then\n  echo \"The default etcd storage media type in 1.6 has changed from application/json to application/vnd.kubernetes.protobuf.\"\n  echo \"Documentation about the change can be found at https://kubernetes.io/docs/admin/etcd_upgrade.\"\n  echo \"\"\n  echo \"ETCD2 DOES NOT SUPPORT PROTOBUF: If you wish to have to ability to downgrade to etcd2 later application/json must be used.\"\n  echo \"\"\n  echo \"It's HIGHLY recommended that etcd be backed up before this step!!\"\n  echo \"\"\n  echo \"To enable using json, before running this script set:\"\n  echo \"export STORAGE_MEDIA_TYPE=application/json\"\n  echo \"\"\n  if [ -t 0 ] && [ -t 1 ]; then\n    read -r -p \"Would you like to continue with the new default, and lose the ability to downgrade to etcd2? [y/N] \" confirm\n    if [[ \"${confirm}\" != \"y\" ]]; then\n      exit 1\n    fi\n  else\n    echo \"To enable using protobuf, before running this script set:\"\n    echo \"export STORAGE_MEDIA_TYPE=application/vnd.kubernetes.protobuf\"\n    echo \"\"\n    echo \"STORAGE_MEDIA_TYPE must be specified when run non-interactively.\" >&2\n    exit 1\n  fi\nfi\n\n# Prompt if etcd image/version is unspecified when doing master upgrade.\n# In e2e tests, we use TEST_ALLOW_IMPLICIT_ETCD_UPGRADE=true to skip this\n# prompt, simulating the behavior when the user confirms interactively.\n# All other automated use of this script should explicitly specify a version.\nif [[ \"${master_upgrade}\" == \"true\" ]]; then\n  if [[ -z \"${ETCD_IMAGE:-}\" && -z \"${TEST_ETCD_IMAGE:-}\" ]] || [[ -z \"${ETCD_VERSION:-}\" && -z \"${TEST_ETCD_VERSION:-}\" ]]; then\n    echo\n    echo \"***WARNING***\"\n    echo \"Upgrading Kubernetes with this script might result in an upgrade to a new etcd version.\"\n    echo \"Some etcd version upgrades, such as 3.0.x to 3.1.x, DO NOT offer a downgrade path.\"\n    echo \"To pin the etcd version to your current one (e.g. v3.0.17), set the following variables\"\n    echo \"before running this script:\"\n    echo\n    echo \"# example: pin to etcd v3.0.17\"\n    echo \"export ETCD_IMAGE=3.0.17\"\n    echo \"export ETCD_VERSION=3.0.17\"\n    echo\n    echo \"Alternatively, if you choose to allow an etcd upgrade that doesn't support downgrade,\"\n    echo \"you might still be able to downgrade Kubernetes by pinning to the newer etcd version.\"\n    echo \"In all cases, it is strongly recommended to have an etcd backup before upgrading.\"\n    echo\n    if [ -t 0 ] && [ -t 1 ]; then\n      read -r -p \"Continue with default etcd version, which might upgrade etcd? [y/N] \" confirm\n      if [[ \"${confirm}\" != \"y\" ]]; then\n        exit 1\n      fi\n    elif [[ \"${TEST_ALLOW_IMPLICIT_ETCD_UPGRADE:-}\" != \"true\" ]]; then\n      echo \"ETCD_IMAGE and ETCD_VERSION must be specified when run non-interactively.\" >&2\n      exit 1\n    fi\n  fi\nfi\n\nprint-node-version-info \"Pre-Upgrade\"\n\nif [[ \"${local_binaries}\" == \"false\" ]]; then\n  set_binary_version \"${1}\"\nfi\n\nprepare-upgrade\n\nif [[ \"${node_prereqs}\" == \"true\" ]]; then\n  prepare-node-upgrade\n  exit 0\nfi\n\nif [[ \"${master_upgrade}\" == \"true\" ]]; then\n  upgrade-master\nfi\n\nif [[ \"${node_upgrade}\" == \"true\" ]]; then\n  if [[ \"${local_binaries}\" == \"true\" ]]; then\n    echo \"Upgrading nodes to local binaries is not yet supported.\" >&2\n    exit 1\n  else\n    upgrade-nodes\n  fi\nfi\n\nif [[ \"${CLUSTER_DNS_CORE_DNS:-}\" == \"true\" ]]; then\n  update-coredns-config\nfi\n\necho \"== Validating cluster post-upgrade ==\"\n\"${KUBE_ROOT}/cluster/validate-cluster.sh\"\n\nprint-node-version-info \"Post-Upgrade\"\n", "num_lines": 707}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions and constant for the local config.\n\n# Use the config file specified in $KUBE_CONFIG_FILE, or default to\n# config-default.sh.\nreadonly GCE_MAX_LOCAL_SSD=8\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/cluster/gce/${KUBE_CONFIG_FILE-\"config-default.sh\"}\"\nsource \"${KUBE_ROOT}/cluster/common.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nif [[ \"${NODE_OS_DISTRIBUTION}\" == \"gci\" || \"${NODE_OS_DISTRIBUTION}\" == \"ubuntu\" || \"${NODE_OS_DISTRIBUTION}\" == \"custom\" ]]; then\n  source \"${KUBE_ROOT}/cluster/gce/${NODE_OS_DISTRIBUTION}/node-helper.sh\"\nelse\n  echo \"Cannot operate on cluster using node os distro: ${NODE_OS_DISTRIBUTION}\" >&2\n  exit 1\nfi\n\nsource \"${KUBE_ROOT}/cluster/gce/windows/node-helper.sh\"\n\nif [[ \"${MASTER_OS_DISTRIBUTION}\" == \"trusty\" || \"${MASTER_OS_DISTRIBUTION}\" == \"gci\" || \"${MASTER_OS_DISTRIBUTION}\" == \"ubuntu\" ]]; then\n  source \"${KUBE_ROOT}/cluster/gce/${MASTER_OS_DISTRIBUTION}/master-helper.sh\"\nelse\n  echo \"Cannot operate on cluster using master os distro: ${MASTER_OS_DISTRIBUTION}\" >&2\n  exit 1\nfi\n\nif [[ ${NODE_LOCAL_SSDS:-} -ge 1 ]] && [[ -n ${NODE_LOCAL_SSDS_EXT:-} ]] ; then\n  echo -e \"${color_red:-}Local SSD: Only one of NODE_LOCAL_SSDS and NODE_LOCAL_SSDS_EXT can be specified at once${color_norm:-}\" >&2\n  exit 2\nfi\n\nif [[ \"${MASTER_OS_DISTRIBUTION}\" == \"gci\" ]]; then\n    DEFAULT_GCI_PROJECT=google-containers\n    if [[ \"${GCI_VERSION}\" == \"cos\"* ]]; then\n        DEFAULT_GCI_PROJECT=cos-cloud\n    fi\n    export MASTER_IMAGE_PROJECT=${KUBE_GCE_MASTER_PROJECT:-${DEFAULT_GCI_PROJECT}}\n    # If the master image is not set, we use the latest GCI image.\n    # Otherwise, we respect whatever is set by the user.\n    export MASTER_IMAGE=${KUBE_GCE_MASTER_IMAGE:-${GCI_VERSION}}\nfi\n\n# Sets node image based on the specified os distro. Currently this function only\n# supports gci and debian.\n#\n# Requires:\n#   NODE_OS_DISTRIBUTION\n# Sets:\n#   DEFAULT_GCI_PROJECT\n#   NODE_IMAGE\n#   NODE_IMAGE_PROJECT\nfunction set-linux-node-image() {\n  if [[ \"${NODE_OS_DISTRIBUTION}\" == \"gci\" ]]; then\n    DEFAULT_GCI_PROJECT=google-containers\n    if [[ \"${GCI_VERSION}\" == \"cos\"* ]]; then\n      DEFAULT_GCI_PROJECT=cos-cloud\n    fi\n\n    # If the node image is not set, we use the latest GCI image.\n    # Otherwise, we respect whatever is set by the user.\n    NODE_IMAGE=${KUBE_GCE_NODE_IMAGE:-${GCI_VERSION}}\n    NODE_IMAGE_PROJECT=${KUBE_GCE_NODE_PROJECT:-${DEFAULT_GCI_PROJECT}}\n  fi\n}\n\n# Requires:\n#   WINDOWS_NODE_OS_DISTRIBUTION\n# Sets:\n#   WINDOWS_NODE_IMAGE_PROJECT\n#   WINDOWS_NODE_IMAGE\nfunction set-windows-node-image() {\n  WINDOWS_NODE_IMAGE_PROJECT=\"windows-cloud\"\n  if [[ \"${WINDOWS_NODE_OS_DISTRIBUTION}\" == \"win2019\" ]]; then\n    WINDOWS_NODE_IMAGE=\"windows-server-2019-dc-core-v20210413\"\n  elif [[ \"${WINDOWS_NODE_OS_DISTRIBUTION}\" == \"win1909\" ]]; then\n    WINDOWS_NODE_IMAGE=\"windows-server-1909-dc-core-v20210413\"\n  elif [[ \"${WINDOWS_NODE_OS_DISTRIBUTION}\" == \"win2004\" ]]; then\n    WINDOWS_NODE_IMAGE=\"windows-server-2004-dc-core-v20210413\"\n  elif [[ \"${WINDOWS_NODE_OS_DISTRIBUTION,,}\" == \"win20h2\" ]]; then\n    WINDOWS_NODE_IMAGE=\"windows-server-20h2-dc-core-v20210413\"\n  else\n    echo \"Unknown WINDOWS_NODE_OS_DISTRIBUTION ${WINDOWS_NODE_OS_DISTRIBUTION}\" >&2\n    exit 1\n  fi\n}\n\nset-linux-node-image\nset-windows-node-image\n\n# Verify cluster autoscaler configuration.\nif [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n  if [[ -z $AUTOSCALER_MIN_NODES ]]; then\n    echo \"AUTOSCALER_MIN_NODES not set.\"\n    exit 1\n  fi\n  if [[ -z $AUTOSCALER_MAX_NODES ]]; then\n    echo \"AUTOSCALER_MAX_NODES not set.\"\n    exit 1\n  fi\nfi\n\n# These prefixes must not be prefixes of each other, so that they can be used to\n# detect mutually exclusive sets of nodes.\nNODE_INSTANCE_PREFIX=${NODE_INSTANCE_PREFIX:-\"${INSTANCE_PREFIX}-minion\"}\nWINDOWS_NODE_INSTANCE_PREFIX=${WINDOWS_NODE_INSTANCE_PREFIX:-\"${INSTANCE_PREFIX}-windows-node\"}\n\n# NODE_TAG (expected to be) defined by caller\n# shellcheck disable=SC2153\nNODE_TAGS=\"${NODE_TAG}\"\n\nALLOCATE_NODE_CIDRS=true\nPREEXISTING_NETWORK=false\nPREEXISTING_NETWORK_MODE=\"\"\n\nKUBE_PROMPT_FOR_UPDATE=${KUBE_PROMPT_FOR_UPDATE:-\"n\"}\n# How long (in seconds) to wait for cluster initialization.\nKUBE_CLUSTER_INITIALIZATION_TIMEOUT=${KUBE_CLUSTER_INITIALIZATION_TIMEOUT:-300}\n\nfunction join_csv() {\n  local IFS=','; echo \"$*\";\n}\n\n# This function returns the first string before the comma\nfunction split_csv() {\n  echo \"$*\" | cut -d',' -f1\n}\n\n# Verify prereqs\nfunction verify-prereqs() {\n  local cmd\n\n  # we use openssl to generate certs\n  kube::util::test_openssl_installed\n\n  # ensure a version supported by easyrsa is installed\n  if [ \"$(openssl version | cut -d\\  -f1)\" == \"LibreSSL\" ]; then\n    echo \"LibreSSL is not supported. Please ensure openssl points to an OpenSSL binary\"\n    if [ \"$(uname -s)\" == \"Darwin\" ]; then\n      # We want this print just the way it is\n      # shellcheck disable=SC2016\n      echo 'On macOS we recommend using homebrew and adding \"$(brew --prefix openssl)/bin\" to your PATH'\n    fi\n    exit 1\n  fi\n\n  # we use gcloud to create the cluster, gsutil to stage binaries and data\n  for cmd in gcloud gsutil; do\n    if ! which \"${cmd}\" >/dev/null; then\n      local resp=\"n\"\n      if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" == \"y\" ]]; then\n        echo \"Can't find ${cmd} in PATH.  Do you wish to install the Google Cloud SDK? [Y/n]\"\n        read -r resp\n      fi\n      if [[ \"${resp}\" != \"n\" && \"${resp}\" != \"N\" ]]; then\n        curl https://sdk.cloud.google.com | bash\n      fi\n      if ! which \"${cmd}\" >/dev/null; then\n        echo \"Can't find ${cmd} in PATH, please fix and retry. The Google Cloud \" >&2\n        echo \"SDK can be downloaded from https://cloud.google.com/sdk/.\" >&2\n        exit 1\n      fi\n    fi\n  done\n  update-or-verify-gcloud\n}\n\n# Use the gcloud defaults to find the project.  If it is already set in the\n# environment then go with that.\n#\n# Vars set:\n#   PROJECT\n#   NETWORK_PROJECT\n#   PROJECT_REPORTED\nfunction detect-project() {\n  if [[ -z \"${PROJECT-}\" ]]; then\n    PROJECT=$(gcloud config list project --format 'value(core.project)')\n  fi\n\n  NETWORK_PROJECT=${NETWORK_PROJECT:-${PROJECT}}\n\n  if [[ -z \"${PROJECT-}\" ]]; then\n    echo \"Could not detect Google Cloud Platform project.  Set the default project using \" >&2\n    echo \"'gcloud config set project <PROJECT>'\" >&2\n    exit 1\n  fi\n  if [[ -z \"${PROJECT_REPORTED-}\" ]]; then\n    echo \"Project: ${PROJECT}\" >&2\n    echo \"Network Project: ${NETWORK_PROJECT}\" >&2\n    echo \"Zone: ${ZONE}\" >&2\n    PROJECT_REPORTED=true\n  fi\n}\n\n# Use gsutil to get the md5 hash for a particular tar\nfunction gsutil_get_tar_md5() {\n  # location_tar could be local or in the cloud\n  # local tar_location example ./_output/release-tars/kubernetes-server-linux-amd64.tar.gz\n  # cloud tar_location example gs://kubernetes-staging-PROJECT/kubernetes-devel/kubernetes-server-linux-amd64.tar.gz\n  local -r tar_location=$1\n  #parse the output and return the md5 hash\n  #the sed command at the end removes whitespace\n  local -r tar_md5=$(gsutil hash -h -m \"${tar_location}\" 2>/dev/null | grep \"Hash (md5):\" | awk -F ':' '{print $2}' | sed 's/^[[:space:]]*//g')\n  echo \"${tar_md5}\"\n}\n\n# Copy a release tar and its accompanying hash.\nfunction copy-to-staging() {\n  local -r staging_path=$1\n  local -r gs_url=$2\n  local -r tar=$3\n  local -r hash=$4\n  local -r basename_tar=$(basename \"${tar}\")\n\n  #check whether this tar alread exists and has the same hash\n  #if it matches, then don't bother uploading it again\n\n  #remote_tar_md5 checks the remote location for the existing tarball and its md5\n  #staging_path example gs://kubernetes-staging-PROJECT/kubernetes-devel\n  #basename_tar example kubernetes-server-linux-amd64.tar.gz\n  local -r remote_tar_md5=$(gsutil_get_tar_md5 \"${staging_path}/${basename_tar}\")\n  if [[ -n ${remote_tar_md5} ]]; then\n    #local_tar_md5 checks the remote location for the existing tarball and its md5 hash\n    #tar example ./_output/release-tars/kubernetes-server-linux-amd64.tar.gz\n    local -r local_tar_md5=$(gsutil_get_tar_md5 \"${tar}\")\n    if [[ \"${remote_tar_md5}\" == \"${local_tar_md5}\" ]]; then\n      echo \"+++ ${basename_tar} uploaded earlier, cloud and local file md5 match (md5 = ${local_tar_md5})\"\n      return 0\n    fi\n  fi\n\n  echo \"${hash}\" > \"${tar}.sha512\"\n  gsutil -m -q -h \"Cache-Control:private, max-age=0\" cp \"${tar}\" \"${tar}.sha512\" \"${staging_path}\"\n  gsutil -m acl ch -g all:R \"${gs_url}\" \"${gs_url}.sha512\" >/dev/null 2>&1 || true\n  echo \"+++ ${basename_tar} uploaded (sha512 = ${hash})\"\n}\n\n\n# Given the cluster zone, return the list of regional GCS release\n# bucket suffixes for the release in preference order. GCS doesn't\n# give us an API for this, so we hardcode it.\n#\n# Assumed vars:\n#   RELEASE_REGION_FALLBACK\n#   REGIONAL_KUBE_ADDONS\n#   ZONE\n# Vars set:\n#   PREFERRED_REGION\nfunction set-preferred-region() {\n  case ${ZONE} in\n    asia-*)\n      PREFERRED_REGION=(\"asia\" \"us\" \"eu\")\n      ;;\n    europe-*)\n      PREFERRED_REGION=(\"eu\" \"us\" \"asia\")\n      ;;\n    *)\n      PREFERRED_REGION=(\"us\" \"eu\" \"asia\")\n      ;;\n  esac\n\n  if [[ \"${RELEASE_REGION_FALLBACK}\" != \"true\" ]]; then\n    PREFERRED_REGION=( \"${PREFERRED_REGION[0]}\" )\n  fi\n}\n\n# Take the local tar files and upload them to Google Storage.  They will then be\n# downloaded by the master as part of the start up script for the master.\n#\n# Assumed vars:\n#   PROJECT\n#   SERVER_BINARY_TAR\n#   KUBE_MANIFESTS_TAR\n#   ZONE\n# Vars set:\n#   SERVER_BINARY_TAR_URL\n#   SERVER_BINARY_TAR_HASH\n#   NODE_BINARY_TAR_URL\n#   NODE_BINARY_TAR_HASH\n#   KUBE_MANIFESTS_TAR_URL\n#   KUBE_MANIFESTS_TAR_HASH\nfunction upload-tars() {\n  SERVER_BINARY_TAR_URL=\n  SERVER_BINARY_TAR_HASH=\n  NODE_BINARY_TAR_URL=\n  NODE_BINARY_TAR_HASH=\n  KUBE_MANIFESTS_TAR_URL=\n  KUBE_MANIFESTS_TAR_HASH=\n\n  local project_hash\n  if which md5 > /dev/null 2>&1; then\n    project_hash=$(md5 -q -s \"$PROJECT\")\n  else\n    project_hash=$(echo -n \"$PROJECT\" | md5sum)\n    project_hash=${project_hash%%[[:blank:]]*}\n  fi\n\n  # This requires 1 million projects before the probability of collision is 50%\n  # that's probably good enough for now :P\n  project_hash=${project_hash:0:10}\n\n  set-preferred-region\n\n  if [[ \"${ENABLE_DOCKER_REGISTRY_CACHE:-}\" == \"true\" ]]; then\n    DOCKER_REGISTRY_MIRROR_URL=\"https://mirror.gcr.io\"\n  fi\n\n  SERVER_BINARY_TAR_HASH=$(sha512sum-file \"${SERVER_BINARY_TAR}\")\n\n  if [[ -n \"${NODE_BINARY_TAR:-}\" ]]; then\n    NODE_BINARY_TAR_HASH=$(sha512sum-file \"${NODE_BINARY_TAR}\")\n  fi\n  if [[ -n \"${KUBE_MANIFESTS_TAR:-}\" ]]; then\n    KUBE_MANIFESTS_TAR_HASH=$(sha512sum-file \"${KUBE_MANIFESTS_TAR}\")\n  fi\n\n  local server_binary_tar_urls=()\n  local node_binary_tar_urls=()\n\n  for region in \"${PREFERRED_REGION[@]}\"; do\n    suffix=\"-${region}\"\n    if [[ \"${suffix}\" == \"-us\" ]]; then\n      suffix=\"\"\n    fi\n    local staging_bucket=\"gs://kubernetes-staging-${project_hash}${suffix}\"\n\n    # Ensure the buckets are created\n    if ! gsutil ls \"${staging_bucket}\" >/dev/null; then\n      echo \"Creating ${staging_bucket}\"\n      gsutil mb -l \"${region}\" -p \"${PROJECT}\" \"${staging_bucket}\"\n    fi\n\n    local staging_path=\"${staging_bucket}/${INSTANCE_PREFIX}-devel\"\n\n    echo \"+++ Staging tars to Google Storage: ${staging_path}\"\n    local server_binary_gs_url=\"${staging_path}/${SERVER_BINARY_TAR##*/}\"\n    copy-to-staging \"${staging_path}\" \"${server_binary_gs_url}\" \"${SERVER_BINARY_TAR}\" \"${SERVER_BINARY_TAR_HASH}\"\n\n    if [[ -n \"${NODE_BINARY_TAR:-}\" ]]; then\n      local node_binary_gs_url=\"${staging_path}/${NODE_BINARY_TAR##*/}\"\n      copy-to-staging \"${staging_path}\" \"${node_binary_gs_url}\" \"${NODE_BINARY_TAR}\" \"${NODE_BINARY_TAR_HASH}\"\n    fi\n\n    # Convert from gs:// URL to an https:// URL\n    server_binary_tar_urls+=(\"${server_binary_gs_url/gs:\\/\\//https://storage.googleapis.com/}\")\n    if [[ -n \"${NODE_BINARY_TAR:-}\" ]]; then\n      node_binary_tar_urls+=(\"${node_binary_gs_url/gs:\\/\\//https://storage.googleapis.com/}\")\n    fi\n    if [[ -n \"${KUBE_MANIFESTS_TAR:-}\" ]]; then\n      local kube_manifests_gs_url=\"${staging_path}/${KUBE_MANIFESTS_TAR##*/}\"\n      copy-to-staging \"${staging_path}\" \"${kube_manifests_gs_url}\" \"${KUBE_MANIFESTS_TAR}\" \"${KUBE_MANIFESTS_TAR_HASH}\"\n      # Convert from gs:// URL to an https:// URL\n      kube_manifests_tar_urls+=(\"${kube_manifests_gs_url/gs:\\/\\//https://storage.googleapis.com/}\")\n    fi\n  done\n\n  SERVER_BINARY_TAR_URL=$(join_csv \"${server_binary_tar_urls[@]}\")\n  if [[ -n \"${NODE_BINARY_TAR:-}\" ]]; then\n    NODE_BINARY_TAR_URL=$(join_csv \"${node_binary_tar_urls[@]}\")\n  fi\n  if [[ -n \"${KUBE_MANIFESTS_TAR:-}\" ]]; then\n    KUBE_MANIFESTS_TAR_URL=$(join_csv \"${kube_manifests_tar_urls[@]}\")\n  fi\n}\n\n# Detect Linux and Windows nodes created in the instance group.\n#\n# Assumed vars:\n#   NODE_INSTANCE_PREFIX\n#   WINDOWS_NODE_INSTANCE_PREFIX\n# Vars set:\n#   NODE_NAMES\n#   INSTANCE_GROUPS\n#   WINDOWS_NODE_NAMES\n#   WINDOWS_INSTANCE_GROUPS\nfunction detect-node-names() {\n  detect-project\n  INSTANCE_GROUPS=()\n  kube::util::read-array INSTANCE_GROUPS < <(gcloud compute instance-groups managed list \\\n    --project \"${PROJECT}\" \\\n    --filter \"name ~ '${NODE_INSTANCE_PREFIX}-.+' AND zone:(${ZONE})\" \\\n    --format='value(name)' || true)\n  WINDOWS_INSTANCE_GROUPS=()\n  kube::util::read-array WINDOWS_INSTANCE_GROUPS < <(gcloud compute instance-groups managed list \\\n    --project \"${PROJECT}\" \\\n    --filter \"name ~ '${WINDOWS_NODE_INSTANCE_PREFIX}-.+' AND zone:(${ZONE})\" \\\n    --format='value(name)' || true)\n\n  NODE_NAMES=()\n  if [[ -n \"${INSTANCE_GROUPS[*]:-}\" ]]; then\n    for group in \"${INSTANCE_GROUPS[@]}\"; do\n      kube::util::read-array NODE_NAMES < <(gcloud compute instance-groups managed list-instances \\\n        \"${group}\" --zone \"${ZONE}\" --project \"${PROJECT}\" \\\n        --format='value(instance)')\n    done\n  fi\n  # Add heapster node name to the list too (if it exists).\n  if [[ -n \"${HEAPSTER_MACHINE_TYPE:-}\" ]]; then\n    NODE_NAMES+=(\"${NODE_INSTANCE_PREFIX}-heapster\")\n  fi\n  export NODE_NAMES\n  WINDOWS_NODE_NAMES=()\n  if [[ -n \"${WINDOWS_INSTANCE_GROUPS[*]:-}\" ]]; then\n    for group in \"${WINDOWS_INSTANCE_GROUPS[@]}\"; do\n      kube::util::read-array WINDOWS_NODE_NAMES < <(gcloud compute instance-groups managed \\\n        list-instances \"${group}\" --zone \"${ZONE}\" --project \"${PROJECT}\" \\\n        --format='value(instance)')\n    done\n  fi\n  export WINDOWS_NODE_NAMES\n\n  echo \"INSTANCE_GROUPS=${INSTANCE_GROUPS[*]:-}\" >&2\n  echo \"NODE_NAMES=${NODE_NAMES[*]:-}\" >&2\n}\n\n# Detect the information about the minions\n#\n# Assumed vars:\n#   ZONE\n# Vars set:\n#   NODE_NAMES\n#   KUBE_NODE_IP_ADDRESSES (array)\nfunction detect-nodes() {\n  detect-project\n  detect-node-names\n  KUBE_NODE_IP_ADDRESSES=()\n  for (( i=0; i<${#NODE_NAMES[@]}; i++)); do\n    local node_ip\n    node_ip=$(gcloud compute instances describe --project \"${PROJECT}\" --zone \"${ZONE}\" \\\n      \"${NODE_NAMES[$i]}\" --format='value(networkInterfaces[0].accessConfigs[0].natIP)')\n    if [[ -z \"${node_ip-}\" ]] ; then\n      echo \"Did not find ${NODE_NAMES[$i]}\" >&2\n    else\n      echo \"Found ${NODE_NAMES[$i]} at ${node_ip}\"\n      KUBE_NODE_IP_ADDRESSES+=(\"${node_ip}\")\n    fi\n  done\n  if [[ -z \"${KUBE_NODE_IP_ADDRESSES-}\" ]]; then\n    echo \"Could not detect Kubernetes minion nodes.  Make sure you've launched a cluster with 'kube-up.sh'\" >&2\n    exit 1\n  fi\n}\n\n# Detect the IP for the master\n#\n# Assumed vars:\n#   MASTER_NAME\n#   ZONE\n#   REGION\n# Vars set:\n#   KUBE_MASTER\n#   KUBE_MASTER_IP\nfunction detect-master() {\n  detect-project\n  KUBE_MASTER=${MASTER_NAME}\n  echo \"Trying to find master named '${MASTER_NAME}'\" >&2\n  if [[ -z \"${KUBE_MASTER_IP-}\" ]]; then\n    local master_address_name=\"${MASTER_NAME}-ip\"\n    echo \"Looking for address '${master_address_name}'\" >&2\n    if ! KUBE_MASTER_IP=$(gcloud compute addresses describe \"${master_address_name}\" \\\n      --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)') || \\\n      [[ -z \"${KUBE_MASTER_IP-}\" ]]; then\n      echo \"Could not detect Kubernetes master node.  Make sure you've launched a cluster with 'kube-up.sh'\" >&2\n      exit 1\n    fi\n  fi\n  if [[ -z \"${KUBE_MASTER_INTERNAL_IP-}\" ]] && [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      local master_address_name=\"${MASTER_NAME}-internal-ip\"\n      echo \"Looking for address '${master_address_name}'\" >&2\n      if ! KUBE_MASTER_INTERNAL_IP=$(gcloud compute addresses describe \"${master_address_name}\" \\\n        --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)') || \\\n        [[ -z \"${KUBE_MASTER_INTERNAL_IP-}\" ]]; then\n        echo \"Could not detect Kubernetes master node.  Make sure you've launched a cluster with 'kube-up.sh'\" >&2\n        exit 1\n      fi\n  fi\n  echo \"Using master: $KUBE_MASTER (external IP: $KUBE_MASTER_IP; internal IP: ${KUBE_MASTER_INTERNAL_IP:-(not set)})\" >&2\n}\n\nfunction load-or-gen-kube-bearertoken() {\n  if [[ -n \"${KUBE_CONTEXT:-}\" ]]; then\n    get-kubeconfig-bearertoken\n  fi\n  if [[ -z \"${KUBE_BEARER_TOKEN:-}\" ]]; then\n    gen-kube-bearertoken\n  fi\n}\n\n# Figure out which binary use on the server and assure it is available.\n# If KUBE_VERSION is specified use binaries specified by it, otherwise\n# use local dev binaries.\n#\n# Assumed vars:\n#   KUBE_VERSION\n#   KUBE_RELEASE_VERSION_REGEX\n#   KUBE_CI_VERSION_REGEX\n# Vars set:\n#   KUBE_TAR_HASH\n#   SERVER_BINARY_TAR_URL\n#   SERVER_BINARY_TAR_HASH\nfunction tars_from_version() {\n  local sha512sum=\"\"\n  if which sha512sum >/dev/null 2>&1; then\n    sha512sum=\"sha512sum\"\n  else\n    sha512sum=\"shasum -a512\"\n  fi\n\n  if [[ -z \"${KUBE_VERSION-}\" ]]; then\n    find-release-tars\n    upload-tars\n  elif [[ ${KUBE_VERSION} =~ ${KUBE_RELEASE_VERSION_REGEX} ]]; then\n    SERVER_BINARY_TAR_URL=\"https://storage.googleapis.com/kubernetes-release/release/${KUBE_VERSION}/kubernetes-server-linux-amd64.tar.gz\"\n    # TODO: Clean this up.\n    KUBE_MANIFESTS_TAR_URL=\"${SERVER_BINARY_TAR_URL/server-linux-amd64/manifests}\"\n    KUBE_MANIFESTS_TAR_HASH=$(curl \"${KUBE_MANIFESTS_TAR_URL}\" --silent --show-error | ${sha512sum})\n    KUBE_MANIFESTS_TAR_HASH=${KUBE_MANIFESTS_TAR_HASH%%[[:blank:]]*}\n  elif [[ ${KUBE_VERSION} =~ ${KUBE_CI_VERSION_REGEX} ]]; then\n    SERVER_BINARY_TAR_URL=\"https://storage.googleapis.com/kubernetes-release-dev/ci/${KUBE_VERSION}/kubernetes-server-linux-amd64.tar.gz\"\n    # TODO: Clean this up.\n    KUBE_MANIFESTS_TAR_URL=\"${SERVER_BINARY_TAR_URL/server-linux-amd64/manifests}\"\n    KUBE_MANIFESTS_TAR_HASH=$(curl \"${KUBE_MANIFESTS_TAR_URL}\" --silent --show-error | ${sha512sum})\n    KUBE_MANIFESTS_TAR_HASH=${KUBE_MANIFESTS_TAR_HASH%%[[:blank:]]*}\n  else\n    echo \"Version doesn't match regexp\" >&2\n    exit 1\n  fi\n  if ! SERVER_BINARY_TAR_HASH=$(curl -Ss --fail \"${SERVER_BINARY_TAR_URL}.sha512\"); then\n    echo \"Failure trying to curl release .sha512\"\n  fi\n\n  if ! curl -Ss --head \"${SERVER_BINARY_TAR_URL}\" >&/dev/null; then\n    echo \"Can't find release at ${SERVER_BINARY_TAR_URL}\" >&2\n    exit 1\n  fi\n}\n\n# Reads kube-env metadata from master\n#\n# Assumed vars:\n#   KUBE_MASTER\n#   PROJECT\n#   ZONE\nfunction get-master-env() {\n  # TODO(zmerlynn): Make this more reliable with retries.\n  gcloud compute --project \"${PROJECT}\" ssh --zone \"${ZONE}\" \"${KUBE_MASTER}\" --command \\\n    \"curl --fail --silent -H 'Metadata-Flavor: Google' \\\n      'http://metadata/computeMetadata/v1/instance/attributes/kube-env'\" 2>/dev/null\n  gcloud compute --project \"${PROJECT}\" ssh --zone \"${ZONE}\" \"${KUBE_MASTER}\" --command \\\n    \"curl --fail --silent -H 'Metadata-Flavor: Google' \\\n      'http://metadata/computeMetadata/v1/instance/attributes/kube-master-certs'\" 2>/dev/null\n}\n\n# Quote something appropriate for a yaml string.\n#\n# TODO(zmerlynn): Note that this function doesn't so much \"quote\" as\n# \"strip out quotes\", and we really should be using a YAML library for\n# this, but PyYAML isn't shipped by default, and *rant rant rant ... SIGH*\nfunction yaml-quote {\n  echo \"${@:-}\" | sed -e \"s/'/''/g;s/^/'/i;s/$/'/i\"\n}\n\n# Writes the cluster location into a temporary file.\n# Assumed vars\n#   ZONE\nfunction write-cluster-location {\n  cat >\"${KUBE_TEMP}/cluster-location.txt\" << EOF\n${ZONE}\nEOF\n}\n\n# Writes the cluster name into a temporary file.\n# Assumed vars\n#   CLUSTER_NAME\nfunction write-cluster-name {\n  cat >\"${KUBE_TEMP}/cluster-name.txt\" << EOF\n${CLUSTER_NAME}\nEOF\n}\n\nfunction write-master-env {\n  # If the user requested that the master be part of the cluster, set the\n  # environment variable to program the master kubelet to register itself.\n  if [[ \"${REGISTER_MASTER_KUBELET:-}\" == \"true\" && -z \"${KUBELET_APISERVER:-}\" ]]; then\n    KUBELET_APISERVER=\"${MASTER_NAME}\"\n  fi\n  if [[ -z \"${KUBERNETES_MASTER_NAME:-}\" ]]; then\n    KUBERNETES_MASTER_NAME=\"${MASTER_NAME}\"\n  fi\n\n  construct-linux-kubelet-flags \"master\"\n  build-linux-kube-env true \"${KUBE_TEMP}/master-kube-env.yaml\"\n  build-kubelet-config true \"linux\" \"${KUBE_TEMP}/master-kubelet-config.yaml\"\n  build-kube-master-certs \"${KUBE_TEMP}/kube-master-certs.yaml\"\n}\n\nfunction write-linux-node-env {\n  if [[ -z \"${KUBERNETES_MASTER_NAME:-}\" ]]; then\n    KUBERNETES_MASTER_NAME=\"${MASTER_NAME}\"\n  fi\n\n  construct-linux-kubelet-flags \"heapster\"\n  build-linux-kube-env false \"${KUBE_TEMP}/heapster-kube-env.yaml\"\n  construct-linux-kubelet-flags \"node\"\n  build-linux-kube-env false \"${KUBE_TEMP}/node-kube-env.yaml\"\n  build-kubelet-config false \"linux\" \"${KUBE_TEMP}/node-kubelet-config.yaml\"\n}\n\nfunction write-windows-node-env {\n  construct-windows-kubelet-flags\n  construct-windows-kubeproxy-flags\n  build-windows-kube-env \"${KUBE_TEMP}/windows-node-kube-env.yaml\"\n  build-kubelet-config false \"windows\" \"${KUBE_TEMP}/windows-node-kubelet-config.yaml\"\n}\n\nfunction build-linux-node-labels {\n  local node_type=$1\n  local node_labels=\"\"\n  if [[ \"${KUBE_PROXY_DAEMONSET:-}\" == \"true\" && \"${node_type}\" != \"master\" ]]; then\n    # Add kube-proxy daemonset label to node to avoid situation during cluster\n    # upgrade/downgrade when there are two instances of kube-proxy running on a node.\n    node_labels=\"node.kubernetes.io/kube-proxy-ds-ready=true\"\n  fi\n  if [[ -n \"${NODE_LABELS:-}\" ]]; then\n    node_labels=\"${node_labels:+${node_labels},}${NODE_LABELS}\"\n  fi\n  if [[ -n \"${NON_MASTER_NODE_LABELS:-}\" && \"${node_type}\" != \"master\" ]]; then\n    node_labels=\"${node_labels:+${node_labels},}${NON_MASTER_NODE_LABELS}\"\n  fi\n  if [[ -n \"${MASTER_NODE_LABELS:-}\" && \"${node_type}\" == \"master\" ]]; then\n    node_labels=\"${node_labels:+${node_labels},}${MASTER_NODE_LABELS}\"\n  fi\n  echo \"$node_labels\"\n}\n\nfunction build-windows-node-labels {\n  local node_labels=\"\"\n  if [[ -n \"${WINDOWS_NODE_LABELS:-}\" ]]; then\n    node_labels=\"${node_labels:+${node_labels},}${WINDOWS_NODE_LABELS}\"\n  fi\n  if [[ -n \"${WINDOWS_NON_MASTER_NODE_LABELS:-}\" ]]; then\n    node_labels=\"${node_labels:+${node_labels},}${WINDOWS_NON_MASTER_NODE_LABELS}\"\n  fi\n  echo \"$node_labels\"\n}\n\n# yaml-map-string-stringarray converts the encoded structure to yaml format, and echoes the result\n# under the provided name. If the encoded structure is empty, echoes nothing.\n# 1: name to be output in yaml\n# 2: encoded map-string-string (which may contain duplicate keys - resulting in map-string-stringarray)\n# 3: key-value separator (defaults to ':')\n# 4: item separator (defaults to ',')\nfunction yaml-map-string-stringarray {\n  declare -r name=\"${1}\"\n  declare -r encoded=\"${2}\"\n  declare -r kv_sep=\"${3:-:}\"\n  declare -r item_sep=\"${4:-,}\"\n\n  declare -a pairs # indexed array\n  declare -A map # associative array\n  IFS=\"${item_sep}\" read -ra pairs <<<\"${encoded}\" # split on item_sep\n  for pair in \"${pairs[@]}\"; do\n    declare key\n    declare value\n    IFS=\"${kv_sep}\" read -r key value <<<\"${pair}\" # split on kv_sep\n    map[$key]=\"${map[$key]+${map[$key]}${item_sep}}${value}\" # append values from duplicate keys\n  done\n  # only output if there is a non-empty map\n  if [[ ${#map[@]} -gt 0 ]]; then\n    echo \"${name}:\"\n    for k in \"${!map[@]}\"; do\n      echo \"  ${k}:\"\n      declare -a values\n      IFS=\"${item_sep}\" read -ra values <<<\"${map[$k]}\"\n      for val in \"${values[@]}\"; do\n        # declare across two lines so errexit can catch failures\n        declare v\n        v=$(yaml-quote \"${val}\")\n        echo \"    - ${v}\"\n      done\n    done\n  fi\n}\n\n# yaml-map-string-string converts the encoded structure to yaml format, and echoes the result\n# under the provided name. If the encoded structure is empty, echoes nothing.\n# 1: name to be output in yaml\n# 2: encoded map-string-string (no duplicate keys)\n# 3: bool, whether to yaml-quote the value string in the output (defaults to true)\n# 4: key-value separator (defaults to ':')\n# 5: item separator (defaults to ',')\nfunction yaml-map-string-string {\n  declare -r name=\"${1}\"\n  declare -r encoded=\"${2}\"\n  declare -r quote_val_string=\"${3:-true}\"\n  declare -r kv_sep=\"${4:-:}\"\n  declare -r item_sep=\"${5:-,}\"\n\n  declare -a pairs # indexed array\n  declare -A map # associative array\n  IFS=\"${item_sep}\" read -ra pairs <<<\"${encoded}\" # split on item_sep # TODO(mtaufen): try quoting this too\n  for pair in \"${pairs[@]}\"; do\n    declare key\n    declare value\n    IFS=\"${kv_sep}\" read -r key value <<<\"${pair}\" # split on kv_sep\n    map[$key]=\"${value}\" # add to associative array\n  done\n  # only output if there is a non-empty map\n  if [[ ${#map[@]} -gt 0 ]]; then\n    echo \"${name}:\"\n    for k in \"${!map[@]}\"; do\n      if [[ \"${quote_val_string}\" == \"true\" ]]; then\n        # declare across two lines so errexit can catch failures\n        declare v\n        v=$(yaml-quote \"${map[$k]}\")\n        echo \"  ${k}: ${v}\"\n      else\n        echo \"  ${k}: ${map[$k]}\"\n      fi\n    done\n  fi\n}\n\n# Returns kubelet flags used on both Linux and Windows nodes.\nfunction construct-common-kubelet-flags {\n  local flags=\"${KUBELET_TEST_LOG_LEVEL:-\"--v=2\"} ${KUBELET_TEST_ARGS:-}\"\n  flags+=\" --cloud-provider=gce\"\n  # TODO(mtaufen): ROTATE_CERTIFICATES seems unused; delete it?\n  if [[ -n \"${ROTATE_CERTIFICATES:-}\" ]]; then\n    flags+=\" --rotate-certificates=true\"\n  fi\n  if [[ -n \"${MAX_PODS_PER_NODE:-}\" ]]; then\n    flags+=\" --max-pods=${MAX_PODS_PER_NODE}\"\n  fi\n  echo \"$flags\"\n}\n\n# Sets KUBELET_ARGS with the kubelet flags for Linux nodes.\n# $1: if 'true', we're rendering flags for a master, else a node\nfunction construct-linux-kubelet-flags {\n  local node_type=\"$1\"\n  local flags\n  flags=\"$(construct-common-kubelet-flags)\"\n  # Keep in sync with CONTAINERIZED_MOUNTER_HOME in configure-helper.sh\n  flags+=\" --experimental-mounter-path=/home/kubernetes/containerized_mounter/mounter\"\n  flags+=\" --experimental-check-node-capabilities-before-mount=true\"\n  # Keep in sync with the mkdir command in configure-helper.sh (until the TODO is resolved)\n  flags+=\" --cert-dir=/var/lib/kubelet/pki/\"\n  # Configure the directory that the Kubelet should use to store dynamic config checkpoints\n  flags+=\" --dynamic-config-dir=/var/lib/kubelet/dynamic-config\"\n\n\n  if [[ \"${node_type}\" == \"master\" ]]; then\n    flags+=\" ${MASTER_KUBELET_TEST_ARGS:-}\"\n    if [[ \"${REGISTER_MASTER_KUBELET:-false}\" == \"true\" ]]; then\n      #TODO(mikedanese): allow static pods to start before creating a client\n      #flags+=\" --bootstrap-kubeconfig=/var/lib/kubelet/bootstrap-kubeconfig\"\n      #flags+=\" --kubeconfig=/var/lib/kubelet/kubeconfig\"\n      flags+=\" --register-with-taints=node-role.kubernetes.io/master=:NoSchedule\"\n      flags+=\" --kubeconfig=/var/lib/kubelet/bootstrap-kubeconfig\"\n      flags+=\" --register-schedulable=false\"\n    fi\n    if [[ \"${MASTER_OS_DISTRIBUTION}\" == \"ubuntu\" ]]; then\n      # Configure the file path for host dns configuration\n      # as ubuntu uses systemd-resolved\n      flags+=\" --resolv-conf=/run/systemd/resolve/resolv.conf\"\n    fi\n  else # For nodes\n    flags+=\" ${NODE_KUBELET_TEST_ARGS:-}\"\n    flags+=\" --bootstrap-kubeconfig=/var/lib/kubelet/bootstrap-kubeconfig\"\n    flags+=\" --kubeconfig=/var/lib/kubelet/kubeconfig\"\n    if [[ \"${node_type}\" == \"heapster\" ]]; then\n        flags+=\" ${HEAPSTER_KUBELET_TEST_ARGS:-}\"\n    fi\n    if [[ \"${NODE_OS_DISTRIBUTION}\" == \"ubuntu\" ]]; then\n      # Configure the file path for host dns configuration\n      # as ubuntu uses systemd-resolved\n      flags+=\" --resolv-conf=/run/systemd/resolve/resolv.conf\"\n    fi\n  fi\n  # Network plugin\n  if [[ -n \"${NETWORK_PROVIDER:-}\" || -n \"${NETWORK_POLICY_PROVIDER:-}\" ]]; then\n    flags+=\" --cni-bin-dir=/home/kubernetes/bin\"\n    if [[ \"${NETWORK_POLICY_PROVIDER:-}\" == \"calico\" || \"${ENABLE_NETD:-}\" == \"true\" ]]; then\n      # Calico uses CNI always.\n      # Note that network policy won't work for master node.\n      if [[ \"${node_type}\" == \"master\" ]]; then\n        flags+=\" --network-plugin=${NETWORK_PROVIDER}\"\n      else\n        flags+=\" --network-plugin=cni\"\n      fi\n    else\n      # Otherwise use the configured value.\n      flags+=\" --network-plugin=${NETWORK_PROVIDER}\"\n\n    fi\n  fi\n  if [[ -n \"${NON_MASQUERADE_CIDR:-}\" ]]; then\n    flags+=\" --non-masquerade-cidr=${NON_MASQUERADE_CIDR}\"\n  fi\n  flags+=\" --volume-plugin-dir=${VOLUME_PLUGIN_DIR}\"\n  local node_labels\n  node_labels=\"$(build-linux-node-labels \"${node_type}\")\"\n  if [[ -n \"${node_labels:-}\" ]]; then\n    flags+=\" --node-labels=${node_labels}\"\n  fi\n  if [[ -n \"${NODE_TAINTS:-}\" ]]; then\n    flags+=\" --register-with-taints=${NODE_TAINTS}\"\n  fi\n  if [[ \"${CONTAINER_RUNTIME:-}\" != \"docker\" ]]; then\n    flags+=\" --container-runtime=remote\"\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n      CONTAINER_RUNTIME_ENDPOINT=${KUBE_CONTAINER_RUNTIME_ENDPOINT:-unix:///run/containerd/containerd.sock}\n      flags+=\" --runtime-cgroups=/system.slice/containerd.service\"\n    fi\n  fi\n\n  if [[ -n \"${CONTAINER_RUNTIME_ENDPOINT:-}\" ]]; then\n    flags+=\" --container-runtime-endpoint=${CONTAINER_RUNTIME_ENDPOINT}\"\n  fi\n\n  KUBELET_ARGS=\"${flags}\"\n}\n\n# Sets KUBELET_ARGS with the kubelet flags for Windows nodes.\n# Note that to configure flags with explicit empty string values, we can't escape\n# double-quotes, because they still break sc.exe after expansion in the\n# binPath parameter, and single-quotes get parsed as characters instead of\n# string delimiters.\nfunction construct-windows-kubelet-flags {\n  local flags\n  flags=\"$(construct-common-kubelet-flags)\"\n\n  # Note: NODE_KUBELET_TEST_ARGS is empty in typical kube-up runs.\n  flags+=\" ${NODE_KUBELET_TEST_ARGS:-}\"\n\n  local node_labels\n  node_labels=\"$(build-windows-node-labels)\"\n  if [[ -n \"${node_labels:-}\" ]]; then\n    flags+=\" --node-labels=${node_labels}\"\n  fi\n\n  # Concatenate common and windows-only node taints and apply them.\n  local node_taints=\"${NODE_TAINTS:-}\"\n  if [[ -n \"${node_taints}\" && -n \"${WINDOWS_NODE_TAINTS:-}\" ]]; then\n    node_taints+=\":${WINDOWS_NODE_TAINTS}\"\n  else\n    node_taints=\"${WINDOWS_NODE_TAINTS:-}\"\n  fi\n  if [[ -n \"${node_taints}\" ]]; then\n    flags+=\" --register-with-taints=${node_taints}\"\n  fi\n\n  # Many of these flags were adapted from\n  # https://github.com/Microsoft/SDN/blob/master/Kubernetes/windows/start-kubelet.ps1.\n  flags+=\" --config=${WINDOWS_KUBELET_CONFIG_FILE}\"\n  flags+=\" --kubeconfig=${WINDOWS_KUBECONFIG_FILE}\"\n\n  # The directory where the TLS certs are located.\n  flags+=\" --cert-dir=${WINDOWS_PKI_DIR}\"\n\n  flags+=\" --network-plugin=cni\"\n  flags+=\" --cni-bin-dir=${WINDOWS_CNI_DIR}\"\n  flags+=\" --cni-conf-dir=${WINDOWS_CNI_CONFIG_DIR}\"\n  flags+=\" --pod-manifest-path=${WINDOWS_MANIFESTS_DIR}\"\n\n  # Windows images are large and we don't have gcr mirrors yet. Allow longer\n  # pull progress deadline.\n  flags+=\" --image-pull-progress-deadline=5m\"\n  flags+=\" --enable-debugging-handlers=true\"\n\n  # Configure kubelet to run as a windows service.\n  flags+=\" --windows-service=true\"\n\n  # TODO(mtaufen): Configure logging for kubelet running as a service. I haven't\n  # been able to figure out how to direct stdout/stderr into log files when\n  # configuring it to run via sc.exe, so we just manually override logging\n  # config here.\n  flags+=\" --log-file=${WINDOWS_LOGS_DIR}\\kubelet.log\"\n  # klog sets this to true internally, so need to override to false so we\n  # actually log to the file\n  flags+=\" --logtostderr=false\"\n\n  # Configure the file path for host dns configuration\n  flags+=\" --resolv-conf=${WINDOWS_CNI_DIR}\\hostdns.conf\"\n\n  # Both --cgroups-per-qos and --enforce-node-allocatable should be disabled on\n  # windows; the latter requires the former to be enabled to work.\n  flags+=\" --cgroups-per-qos=false --enforce-node-allocatable=\"\n\n  # Turn off kernel memory cgroup notification.\n  flags+=\" --kernel-memcg-notification=false\"\n\n  # TODO(#78628): Re-enable KubeletPodResources when the issue is fixed.\n  # Force disable KubeletPodResources feature on Windows until #78628 is fixed.\n  flags+=\" --feature-gates=KubeletPodResources=false\"\n\n  if [[ \"${WINDOWS_CONTAINER_RUNTIME:-}\" != \"docker\" ]]; then\n    flags+=\" --container-runtime=remote\"\n    if [[ \"${WINDOWS_CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n      WINDOWS_CONTAINER_RUNTIME_ENDPOINT=${KUBE_WINDOWS_CONTAINER_RUNTIME_ENDPOINT:-npipe:////./pipe/containerd-containerd}\n      flags+=\" --container-runtime-endpoint=${WINDOWS_CONTAINER_RUNTIME_ENDPOINT}\"\n    fi\n  fi\n\n  KUBELET_ARGS=\"${flags}\"\n}\n\nfunction construct-windows-kubeproxy-flags {\n  local flags=\"\"\n\n  # Use the same log level as the Kubelet during tests.\n  flags+=\" ${KUBELET_TEST_LOG_LEVEL:-\"--v=2\"}\"\n\n  # Windows uses kernelspace proxymode\n  flags+=\" --proxy-mode=kernelspace\"\n\n  # Configure kube-proxy to run as a windows service.\n  flags+=\" --windows-service=true\"\n\n  # TODO(mtaufen): Configure logging for kube-proxy running as a service.\n  # I haven't been able to figure out how to direct stdout/stderr into log\n  # files when configuring it to run via sc.exe, so we just manually\n  # override logging config here.\n  flags+=\" --log-file=${WINDOWS_LOGS_DIR}\\kube-proxy.log\"\n\n  # klog sets this to true internally, so need to override to false\n  # so we actually log to the file\n  flags+=\" --logtostderr=false\"\n\n  # Enabling Windows DSR mode unlocks newer network features and reduces\n  # port usage for services.\n  # https://techcommunity.microsoft.com/t5/networking-blog/direct-server-return-dsr-in-a-nutshell/ba-p/693710\n  if [[ \"${WINDOWS_ENABLE_DSR:-}\" == \"true\" ]]; then\n    flags+=\" --feature-gates=WinDSR=true --enable-dsr=true \"\n  fi\n\n  # Configure flags with explicit empty string values. We can't escape\n  # double-quotes, because they still break sc.exe after expansion in the\n  # binPath parameter, and single-quotes get parsed as characters instead\n  # of string delimiters.\n\n  KUBEPROXY_ARGS=\"${flags}\"\n}\n\n# $1: if 'true', we're rendering config for a master, else a node\nfunction build-kubelet-config {\n  local master=\"$1\"\n  local os=\"$2\"\n  local file=\"$3\"\n\n  rm -f \"${file}\"\n  {\n    print-common-kubelet-config\n    if [[ \"${master}\" == \"true\" ]]; then\n      print-master-kubelet-config\n    else\n      print-common-node-kubelet-config\n      if [[ \"${os}\" == \"linux\" ]]; then\n        print-linux-node-kubelet-config\n      elif [[ \"${os}\" == \"windows\" ]]; then\n        print-windows-node-kubelet-config\n      else\n        echo \"Unknown OS ${os}\" >&2\n        exit 1\n      fi\n    fi\n  } > \"${file}\"\n}\n\n# cat the Kubelet config yaml in common between masters, linux nodes, and\n# windows nodes\nfunction print-common-kubelet-config {\n  declare quoted_dns_server_ip\n  declare quoted_dns_domain\n  quoted_dns_server_ip=$(yaml-quote \"${DNS_SERVER_IP}\")\n  quoted_dns_domain=$(yaml-quote \"${DNS_DOMAIN}\")\n  cat <<EOF\nkind: KubeletConfiguration\napiVersion: kubelet.config.k8s.io/v1beta1\ncgroupRoot: /\nclusterDNS:\n  - ${quoted_dns_server_ip}\nclusterDomain: ${quoted_dns_domain}\nreadOnlyPort: 10255\nEOF\n\n  # Note: ENABLE_MANIFEST_URL is used by GKE.\n  # TODO(mtaufen): remove this since it's not used in kubernetes/kubernetes nor\n  # kubernetes/test-infra.\n  if [[ \"${ENABLE_MANIFEST_URL:-}\" == \"true\" ]]; then\n    declare quoted_manifest_url\n    quoted_manifest_url=$(yaml-quote \"${MANIFEST_URL}\")\n    cat <<EOF\nstaticPodURL: ${quoted_manifest_url}\nEOF\n    yaml-map-string-stringarray 'staticPodURLHeader' \"${MANIFEST_URL_HEADER}\"\n  fi\n\n  if [[ -n \"${EVICTION_HARD:-}\" ]]; then\n    yaml-map-string-string 'evictionHard' \"${EVICTION_HARD}\" true '<'\n  fi\n\n  if [[ -n \"${FEATURE_GATES:-}\" ]]; then\n    yaml-map-string-string 'featureGates' \"${FEATURE_GATES}\" false '='\n  fi\n}\n\n# cat the Kubelet config yaml for masters\nfunction print-master-kubelet-config {\n  cat <<EOF\nenableDebuggingHandlers: false\nhairpinMode: none\nstaticPodPath: /etc/kubernetes/manifests\nauthentication:\n  webhook:\n    enabled: false\n  anonymous:\n    enabled: true\nauthorization:\n  mode: AlwaysAllow\nEOF\n  if [[ \"${REGISTER_MASTER_KUBELET:-false}\" == \"false\" ]]; then\n     # Note: Standalone mode is used by GKE\n    declare quoted_master_ip_range\n    quoted_master_ip_range=$(yaml-quote \"${MASTER_IP_RANGE}\")\n     cat <<EOF\npodCidr: ${quoted_master_ip_range}\nEOF\n  fi\n}\n\n# cat the Kubelet config yaml in common between linux nodes and windows nodes\nfunction print-common-node-kubelet-config {\n  cat <<EOF\nenableDebuggingHandlers: true\nEOF\n  if [[ \"${HAIRPIN_MODE:-}\" == \"promiscuous-bridge\" ]] || \\\n     [[ \"${HAIRPIN_MODE:-}\" == \"hairpin-veth\" ]] || \\\n     [[ \"${HAIRPIN_MODE:-}\" == \"none\" ]]; then\n      declare quoted_hairpin_mode\n      quoted_hairpin_mode=$(yaml-quote \"${HAIRPIN_MODE}\")\n      cat <<EOF\nhairpinMode: ${quoted_hairpin_mode}\nEOF\n  fi\n}\n\n# cat the Kubelet config yaml for linux nodes\nfunction print-linux-node-kubelet-config {\n  # Keep authentication.x509.clientCAFile in sync with CA_CERT_BUNDLE_PATH in configure-helper.sh\n  cat <<EOF\nstaticPodPath: /etc/kubernetes/manifests\nauthentication:\n  x509:\n    clientCAFile: /etc/srv/kubernetes/pki/ca-certificates.crt\nEOF\n}\n\n# cat the Kubelet config yaml for windows nodes\nfunction print-windows-node-kubelet-config {\n  # Notes:\n  # - We don't run any static pods on Windows nodes yet.\n\n  # TODO(mtaufen): Does it make any sense to set eviction thresholds for inodes\n  # on Windows?\n\n  # TODO(pjh, mtaufen): It may make sense to use a different hairpin mode on\n  # Windows. We're currently using hairpin-veth, but\n  # https://github.com/Microsoft/SDN/blob/master/Kubernetes/windows/start-kubelet.ps1#L121\n  # uses promiscuous-bridge.\n\n  # TODO(pjh, mtaufen): Does cgroupRoot make sense for Windows?\n\n  # Keep authentication.x509.clientCAFile in sync with CA_CERT_BUNDLE_PATH in\n  # k8s-node-setup.psm1.\n  cat <<EOF\nauthentication:\n  x509:\n    clientCAFile: '${WINDOWS_CA_FILE}'\nEOF\n}\n\nfunction build-kube-master-certs {\n  local file=$1\n  rm -f \"$file\"\n  cat >\"$file\" <<EOF\nKUBEAPISERVER_CERT: $(yaml-quote \"${KUBEAPISERVER_CERT_BASE64:-}\")\nKUBEAPISERVER_KEY: $(yaml-quote \"${KUBEAPISERVER_KEY_BASE64:-}\")\nCA_KEY: $(yaml-quote \"${CA_KEY_BASE64:-}\")\nAGGREGATOR_CA_KEY: $(yaml-quote \"${AGGREGATOR_CA_KEY_BASE64:-}\")\nREQUESTHEADER_CA_CERT: $(yaml-quote \"${REQUESTHEADER_CA_CERT_BASE64:-}\")\nPROXY_CLIENT_CERT: $(yaml-quote \"${PROXY_CLIENT_CERT_BASE64:-}\")\nPROXY_CLIENT_KEY: $(yaml-quote \"${PROXY_CLIENT_KEY_BASE64:-}\")\nETCD_APISERVER_CA_KEY: $(yaml-quote \"${ETCD_APISERVER_CA_KEY_BASE64:-}\")\nETCD_APISERVER_CA_CERT: $(yaml-quote \"${ETCD_APISERVER_CA_CERT_BASE64:-}\")\nETCD_APISERVER_SERVER_KEY: $(yaml-quote \"${ETCD_APISERVER_SERVER_KEY_BASE64:-}\")\nETCD_APISERVER_SERVER_CERT: $(yaml-quote \"${ETCD_APISERVER_SERVER_CERT_BASE64:-}\")\nETCD_APISERVER_CLIENT_KEY: $(yaml-quote \"${ETCD_APISERVER_CLIENT_KEY_BASE64:-}\")\nETCD_APISERVER_CLIENT_CERT: $(yaml-quote \"${ETCD_APISERVER_CLIENT_CERT_BASE64:-}\")\nEOF\n}\n\n# $1: if 'true', we're building a master yaml, else a node\nfunction build-linux-kube-env {\n  local master=\"$1\"\n  local file=\"$2\"\n\n  local server_binary_tar_url=$SERVER_BINARY_TAR_URL\n  local kube_manifests_tar_url=\"${KUBE_MANIFESTS_TAR_URL:-}\"\n  if [[ \"${master}\" == \"true\" && \"${MASTER_OS_DISTRIBUTION}\" == \"ubuntu\" ]] || \\\n     [[ \"${master}\" == \"false\" && (\"${NODE_OS_DISTRIBUTION}\" == \"ubuntu\" || \"${NODE_OS_DISTRIBUTION}\" == \"custom\") ]]; then\n    # TODO: Support fallback .tar.gz settings on Container Linux\n    server_binary_tar_url=$(split_csv \"${SERVER_BINARY_TAR_URL}\")\n    kube_manifests_tar_url=$(split_csv \"${KUBE_MANIFESTS_TAR_URL}\")\n  fi\n\n  rm -f \"$file\"\n  cat >\"$file\" <<EOF\nCLUSTER_NAME: $(yaml-quote \"${CLUSTER_NAME}\")\nENV_TIMESTAMP: $(yaml-quote \"$(date -u +%Y-%m-%dT%T%z)\")\nINSTANCE_PREFIX: $(yaml-quote \"${INSTANCE_PREFIX}\")\nNODE_INSTANCE_PREFIX: $(yaml-quote \"${NODE_INSTANCE_PREFIX}\")\nNODE_TAGS: $(yaml-quote \"${NODE_TAGS:-}\")\nNODE_NETWORK: $(yaml-quote \"${NETWORK:-}\")\nNODE_SUBNETWORK: $(yaml-quote \"${SUBNETWORK:-}\")\nCLUSTER_IP_RANGE: $(yaml-quote \"${CLUSTER_IP_RANGE:-10.244.0.0/16}\")\nSERVER_BINARY_TAR_URL: $(yaml-quote \"${server_binary_tar_url}\")\nSERVER_BINARY_TAR_HASH: $(yaml-quote \"${SERVER_BINARY_TAR_HASH}\")\nPROJECT_ID: $(yaml-quote \"${PROJECT}\")\nNETWORK_PROJECT_ID: $(yaml-quote \"${NETWORK_PROJECT}\")\nSERVICE_CLUSTER_IP_RANGE: $(yaml-quote \"${SERVICE_CLUSTER_IP_RANGE}\")\nKUBERNETES_MASTER_NAME: $(yaml-quote \"${KUBERNETES_MASTER_NAME}\")\nALLOCATE_NODE_CIDRS: $(yaml-quote \"${ALLOCATE_NODE_CIDRS:-false}\")\nENABLE_METRICS_SERVER: $(yaml-quote \"${ENABLE_METRICS_SERVER:-false}\")\nENABLE_METADATA_AGENT: $(yaml-quote \"${ENABLE_METADATA_AGENT:-none}\")\nMETADATA_AGENT_CPU_REQUEST: $(yaml-quote \"${METADATA_AGENT_CPU_REQUEST:-}\")\nMETADATA_AGENT_MEMORY_REQUEST: $(yaml-quote \"${METADATA_AGENT_MEMORY_REQUEST:-}\")\nMETADATA_AGENT_CLUSTER_LEVEL_CPU_REQUEST: $(yaml-quote \"${METADATA_AGENT_CLUSTER_LEVEL_CPU_REQUEST:-}\")\nMETADATA_AGENT_CLUSTER_LEVEL_MEMORY_REQUEST: $(yaml-quote \"${METADATA_AGENT_CLUSTER_LEVEL_MEMORY_REQUEST:-}\")\nDOCKER_REGISTRY_MIRROR_URL: $(yaml-quote \"${DOCKER_REGISTRY_MIRROR_URL:-}\")\nENABLE_L7_LOADBALANCING: $(yaml-quote \"${ENABLE_L7_LOADBALANCING:-none}\")\nENABLE_CLUSTER_LOGGING: $(yaml-quote \"${ENABLE_CLUSTER_LOGGING:-false}\")\nENABLE_CLUSTER_UI: $(yaml-quote \"${ENABLE_CLUSTER_UI:-false}\")\nENABLE_NODE_PROBLEM_DETECTOR: $(yaml-quote \"${ENABLE_NODE_PROBLEM_DETECTOR:-none}\")\nNODE_PROBLEM_DETECTOR_VERSION: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_VERSION:-}\")\nNODE_PROBLEM_DETECTOR_TAR_HASH: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_TAR_HASH:-}\")\nNODE_PROBLEM_DETECTOR_RELEASE_PATH: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_RELEASE_PATH:-}\")\nNODE_PROBLEM_DETECTOR_CUSTOM_FLAGS: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\")\nCNI_STORAGE_URL_BASE: $(yaml-quote \"${CNI_STORAGE_URL_BASE:-}\")\nCNI_TAR_PREFIX: $(yaml-quote \"${CNI_TAR_PREFIX:-}\")\nCNI_VERSION: $(yaml-quote \"${CNI_VERSION:-}\")\nCNI_HASH: $(yaml-quote \"${CNI_HASH:-}\")\nENABLE_NODE_LOGGING: $(yaml-quote \"${ENABLE_NODE_LOGGING:-false}\")\nLOGGING_DESTINATION: $(yaml-quote \"${LOGGING_DESTINATION:-}\")\nELASTICSEARCH_LOGGING_REPLICAS: $(yaml-quote \"${ELASTICSEARCH_LOGGING_REPLICAS:-}\")\nENABLE_CLUSTER_DNS: $(yaml-quote \"${ENABLE_CLUSTER_DNS:-false}\")\nCLUSTER_DNS_CORE_DNS: $(yaml-quote \"${CLUSTER_DNS_CORE_DNS:-true}\")\nENABLE_NODELOCAL_DNS: $(yaml-quote \"${ENABLE_NODELOCAL_DNS:-false}\")\nDNS_SERVER_IP: $(yaml-quote \"${DNS_SERVER_IP:-}\")\nLOCAL_DNS_IP: $(yaml-quote \"${LOCAL_DNS_IP:-}\")\nDNS_DOMAIN: $(yaml-quote \"${DNS_DOMAIN:-}\")\nDNS_MEMORY_LIMIT: $(yaml-quote \"${DNS_MEMORY_LIMIT:-}\")\nENABLE_DNS_HORIZONTAL_AUTOSCALER: $(yaml-quote \"${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-false}\")\nKUBE_PROXY_DAEMONSET: $(yaml-quote \"${KUBE_PROXY_DAEMONSET:-false}\")\nKUBE_PROXY_TOKEN: $(yaml-quote \"${KUBE_PROXY_TOKEN:-}\")\nKUBE_PROXY_MODE: $(yaml-quote \"${KUBE_PROXY_MODE:-iptables}\")\nDETECT_LOCAL_MODE: $(yaml-quote \"${DETECT_LOCAL_MODE:-}\")\nNODE_PROBLEM_DETECTOR_TOKEN: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\")\nADMISSION_CONTROL: $(yaml-quote \"${ADMISSION_CONTROL:-}\")\nENABLE_POD_SECURITY_POLICY: $(yaml-quote \"${ENABLE_POD_SECURITY_POLICY:-}\")\nMASTER_IP_RANGE: $(yaml-quote \"${MASTER_IP_RANGE}\")\nRUNTIME_CONFIG: $(yaml-quote \"${RUNTIME_CONFIG}\")\nCA_CERT: $(yaml-quote \"${CA_CERT_BASE64:-}\")\nKUBELET_CERT: $(yaml-quote \"${KUBELET_CERT_BASE64:-}\")\nKUBELET_KEY: $(yaml-quote \"${KUBELET_KEY_BASE64:-}\")\nNETWORK_PROVIDER: $(yaml-quote \"${NETWORK_PROVIDER:-}\")\nNETWORK_POLICY_PROVIDER: $(yaml-quote \"${NETWORK_POLICY_PROVIDER:-}\")\nHAIRPIN_MODE: $(yaml-quote \"${HAIRPIN_MODE:-}\")\nE2E_STORAGE_TEST_ENVIRONMENT: $(yaml-quote \"${E2E_STORAGE_TEST_ENVIRONMENT:-}\")\nKUBE_DOCKER_REGISTRY: $(yaml-quote \"${KUBE_DOCKER_REGISTRY:-}\")\nKUBE_ADDON_REGISTRY: $(yaml-quote \"${KUBE_ADDON_REGISTRY:-}\")\nMULTIZONE: $(yaml-quote \"${MULTIZONE:-}\")\nMULTIMASTER: $(yaml-quote \"${MULTIMASTER:-}\")\nNON_MASQUERADE_CIDR: $(yaml-quote \"${NON_MASQUERADE_CIDR:-}\")\nENABLE_DEFAULT_STORAGE_CLASS: $(yaml-quote \"${ENABLE_DEFAULT_STORAGE_CLASS:-}\")\nENABLE_VOLUME_SNAPSHOTS: $(yaml-quote \"${ENABLE_VOLUME_SNAPSHOTS:-}\")\nENABLE_APISERVER_ADVANCED_AUDIT: $(yaml-quote \"${ENABLE_APISERVER_ADVANCED_AUDIT:-}\")\nENABLE_APISERVER_DYNAMIC_AUDIT: $(yaml-quote \"${ENABLE_APISERVER_DYNAMIC_AUDIT:-}\")\nENABLE_CACHE_MUTATION_DETECTOR: $(yaml-quote \"${ENABLE_CACHE_MUTATION_DETECTOR:-false}\")\nENABLE_PATCH_CONVERSION_DETECTOR: $(yaml-quote \"${ENABLE_PATCH_CONVERSION_DETECTOR:-false}\")\nADVANCED_AUDIT_POLICY: $(yaml-quote \"${ADVANCED_AUDIT_POLICY:-}\")\nADVANCED_AUDIT_BACKEND: $(yaml-quote \"${ADVANCED_AUDIT_BACKEND:-log}\")\nADVANCED_AUDIT_TRUNCATING_BACKEND: $(yaml-quote \"${ADVANCED_AUDIT_TRUNCATING_BACKEND:-true}\")\nADVANCED_AUDIT_LOG_MODE: $(yaml-quote \"${ADVANCED_AUDIT_LOG_MODE:-}\")\nADVANCED_AUDIT_LOG_BUFFER_SIZE: $(yaml-quote \"${ADVANCED_AUDIT_LOG_BUFFER_SIZE:-}\")\nADVANCED_AUDIT_LOG_MAX_BATCH_SIZE: $(yaml-quote \"${ADVANCED_AUDIT_LOG_MAX_BATCH_SIZE:-}\")\nADVANCED_AUDIT_LOG_MAX_BATCH_WAIT: $(yaml-quote \"${ADVANCED_AUDIT_LOG_MAX_BATCH_WAIT:-}\")\nADVANCED_AUDIT_LOG_THROTTLE_QPS: $(yaml-quote \"${ADVANCED_AUDIT_LOG_THROTTLE_QPS:-}\")\nADVANCED_AUDIT_LOG_THROTTLE_BURST: $(yaml-quote \"${ADVANCED_AUDIT_LOG_THROTTLE_BURST:-}\")\nADVANCED_AUDIT_LOG_INITIAL_BACKOFF: $(yaml-quote \"${ADVANCED_AUDIT_LOG_INITIAL_BACKOFF:-}\")\nADVANCED_AUDIT_WEBHOOK_MODE: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_MODE:-}\")\nADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE:-}\")\nADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE:-}\")\nADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT:-}\")\nADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS:-}\")\nADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST:-}\")\nADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF: $(yaml-quote \"${ADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF:-}\")\nGCE_API_ENDPOINT: $(yaml-quote \"${GCE_API_ENDPOINT:-}\")\nGCE_GLBC_IMAGE: $(yaml-quote \"${GCE_GLBC_IMAGE:-}\")\nCUSTOM_INGRESS_YAML: |\n${CUSTOM_INGRESS_YAML//\\'/\\'\\'}\nENABLE_NODE_JOURNAL: $(yaml-quote \"${ENABLE_NODE_JOURNAL:-false}\")\nPROMETHEUS_TO_SD_ENDPOINT: $(yaml-quote \"${PROMETHEUS_TO_SD_ENDPOINT:-}\")\nPROMETHEUS_TO_SD_PREFIX: $(yaml-quote \"${PROMETHEUS_TO_SD_PREFIX:-}\")\nENABLE_PROMETHEUS_TO_SD: $(yaml-quote \"${ENABLE_PROMETHEUS_TO_SD:-false}\")\nDISABLE_PROMETHEUS_TO_SD_IN_DS: $(yaml-quote \"${DISABLE_PROMETHEUS_TO_SD_IN_DS:-false}\")\nCONTAINER_RUNTIME: $(yaml-quote \"${CONTAINER_RUNTIME:-}\")\nCONTAINER_RUNTIME_ENDPOINT: $(yaml-quote \"${CONTAINER_RUNTIME_ENDPOINT:-}\")\nCONTAINER_RUNTIME_NAME: $(yaml-quote \"${CONTAINER_RUNTIME_NAME:-}\")\nCONTAINER_RUNTIME_TEST_HANDLER: $(yaml-quote \"${CONTAINER_RUNTIME_TEST_HANDLER:-}\")\nUBUNTU_INSTALL_CONTAINERD_VERSION: $(yaml-quote \"${UBUNTU_INSTALL_CONTAINERD_VERSION:-}\")\nUBUNTU_INSTALL_RUNC_VERSION: $(yaml-quote \"${UBUNTU_INSTALL_RUNC_VERSION:-}\")\nNODE_LOCAL_SSDS_EXT: $(yaml-quote \"${NODE_LOCAL_SSDS_EXT:-}\")\nNODE_LOCAL_SSDS_EPHEMERAL: $(yaml-quote \"${NODE_LOCAL_SSDS_EPHEMERAL:-}\")\nLOAD_IMAGE_COMMAND: $(yaml-quote \"${LOAD_IMAGE_COMMAND:-}\")\nZONE: $(yaml-quote \"${ZONE}\")\nREGION: $(yaml-quote \"${REGION}\")\nVOLUME_PLUGIN_DIR: $(yaml-quote \"${VOLUME_PLUGIN_DIR}\")\nKUBELET_ARGS: $(yaml-quote \"${KUBELET_ARGS}\")\nREQUIRE_METADATA_KUBELET_CONFIG_FILE: $(yaml-quote true)\nENABLE_NETD: $(yaml-quote \"${ENABLE_NETD:-false}\")\nCUSTOM_NETD_YAML: |\n${CUSTOM_NETD_YAML//\\'/\\'\\'}\nCUSTOM_CALICO_NODE_DAEMONSET_YAML: |\n${CUSTOM_CALICO_NODE_DAEMONSET_YAML//\\'/\\'\\'}\nCUSTOM_TYPHA_DEPLOYMENT_YAML: |\n${CUSTOM_TYPHA_DEPLOYMENT_YAML//\\'/\\'\\'}\nCONCURRENT_SERVICE_SYNCS: $(yaml-quote \"${CONCURRENT_SERVICE_SYNCS:-}\")\nEOF\n  if [[ \"${master}\" == \"true\" && \"${MASTER_OS_DISTRIBUTION}\" == \"gci\" ]] || \\\n     [[ \"${master}\" == \"false\" && \"${NODE_OS_DISTRIBUTION}\" == \"gci\" ]]  || \\\n     [[ \"${master}\" == \"true\" && \"${MASTER_OS_DISTRIBUTION}\" == \"cos\" ]] || \\\n     [[ \"${master}\" == \"false\" && \"${NODE_OS_DISTRIBUTION}\" == \"cos\" ]]; then\n    cat >>\"$file\" <<EOF\nREMOUNT_VOLUME_PLUGIN_DIR: $(yaml-quote \"${REMOUNT_VOLUME_PLUGIN_DIR:-true}\")\nEOF\n  fi\n  if [[ \"${master}\" == \"false\" ]]; then\n    cat >>\"$file\" <<EOF\nEOF\n  fi\n  if [ -n \"${KUBE_APISERVER_REQUEST_TIMEOUT:-}\" ]; then\n    cat >>\"$file\" <<EOF\nKUBE_APISERVER_REQUEST_TIMEOUT: $(yaml-quote \"${KUBE_APISERVER_REQUEST_TIMEOUT}\")\nEOF\n  fi\n  if [ -n \"${TERMINATED_POD_GC_THRESHOLD:-}\" ]; then\n    cat >>\"$file\" <<EOF\nTERMINATED_POD_GC_THRESHOLD: $(yaml-quote \"${TERMINATED_POD_GC_THRESHOLD}\")\nEOF\n  fi\n  if [[ \"${master}\" == \"true\" && (\"${MASTER_OS_DISTRIBUTION}\" == \"trusty\" || \"${MASTER_OS_DISTRIBUTION}\" == \"gci\" || \"${MASTER_OS_DISTRIBUTION}\" == \"ubuntu\") ]] || \\\n     [[ \"${master}\" == \"false\" && (\"${NODE_OS_DISTRIBUTION}\" == \"trusty\" || \"${NODE_OS_DISTRIBUTION}\" == \"gci\" || \"${NODE_OS_DISTRIBUTION}\" = \"ubuntu\" || \"${NODE_OS_DISTRIBUTION}\" = \"custom\") ]] ; then\n    cat >>\"$file\" <<EOF\nKUBE_MANIFESTS_TAR_URL: $(yaml-quote \"${kube_manifests_tar_url}\")\nKUBE_MANIFESTS_TAR_HASH: $(yaml-quote \"${KUBE_MANIFESTS_TAR_HASH}\")\nEOF\n  fi\n  if [ -n \"${TEST_CLUSTER:-}\" ]; then\n    cat >>\"$file\" <<EOF\nTEST_CLUSTER: $(yaml-quote \"${TEST_CLUSTER}\")\nEOF\n  fi\n  if [ -n \"${DOCKER_TEST_LOG_LEVEL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nDOCKER_TEST_LOG_LEVEL: $(yaml-quote \"${DOCKER_TEST_LOG_LEVEL}\")\nEOF\n  fi\n  if [ -n \"${DOCKER_LOG_DRIVER:-}\" ]; then\n      cat >>\"$file\" <<EOF\nDOCKER_LOG_DRIVER: $(yaml-quote \"${DOCKER_LOG_DRIVER}\")\nEOF\n  fi\n  if [ -n \"${DOCKER_LOG_MAX_SIZE:-}\" ]; then\n      cat >>\"$file\" <<EOF\nDOCKER_LOG_MAX_SIZE: $(yaml-quote \"${DOCKER_LOG_MAX_SIZE}\")\nEOF\n  fi\n  if [ -n \"${DOCKER_LOG_MAX_FILE:-}\" ]; then\n      cat >>\"$file\" <<EOF\nDOCKER_LOG_MAX_FILE: $(yaml-quote \"${DOCKER_LOG_MAX_FILE}\")\nEOF\n  fi\n  if [ -n \"${FEATURE_GATES:-}\" ]; then\n    cat >>\"$file\" <<EOF\nFEATURE_GATES: $(yaml-quote \"${FEATURE_GATES}\")\nEOF\n  fi\n  if [ -n \"${RUN_CONTROLLERS:-}\" ]; then\n    cat >>\"$file\" <<EOF\nRUN_CONTROLLERS: $(yaml-quote \"${RUN_CONTROLLERS}\")\nEOF\n  fi\n  if [ -n \"${PROVIDER_VARS:-}\" ]; then\n    local var_name\n    local var_value\n\n    for var_name in ${PROVIDER_VARS}; do\n      eval \"local var_value=\\$(yaml-quote \\${${var_name}})\"\n      cat >>\"$file\" <<EOF\n${var_name}: ${var_value}\nEOF\n    done\n  fi\n\n  if [[ \"${master}\" == \"true\" ]]; then\n    # Master-only env vars.\n    cat >>\"$file\" <<EOF\nKUBERNETES_MASTER: $(yaml-quote 'true')\nKUBE_USER: $(yaml-quote \"${KUBE_USER}\")\nKUBE_PASSWORD: $(yaml-quote \"${KUBE_PASSWORD}\")\nKUBE_BEARER_TOKEN: $(yaml-quote \"${KUBE_BEARER_TOKEN}\")\nMASTER_CERT: $(yaml-quote \"${MASTER_CERT_BASE64:-}\")\nMASTER_KEY: $(yaml-quote \"${MASTER_KEY_BASE64:-}\")\nKUBECFG_CERT: $(yaml-quote \"${KUBECFG_CERT_BASE64:-}\")\nKUBECFG_KEY: $(yaml-quote \"${KUBECFG_KEY_BASE64:-}\")\nKUBELET_APISERVER: $(yaml-quote \"${KUBELET_APISERVER:-}\")\nNUM_NODES: $(yaml-quote \"${NUM_NODES}\")\nSTORAGE_BACKEND: $(yaml-quote \"${STORAGE_BACKEND:-etcd3}\")\nSTORAGE_MEDIA_TYPE: $(yaml-quote \"${STORAGE_MEDIA_TYPE:-}\")\nENABLE_GARBAGE_COLLECTOR: $(yaml-quote \"${ENABLE_GARBAGE_COLLECTOR:-}\")\nENABLE_LEGACY_ABAC: $(yaml-quote \"${ENABLE_LEGACY_ABAC:-}\")\nMASTER_ADVERTISE_ADDRESS: $(yaml-quote \"${MASTER_ADVERTISE_ADDRESS:-}\")\nETCD_CA_KEY: $(yaml-quote \"${ETCD_CA_KEY_BASE64:-}\")\nETCD_CA_CERT: $(yaml-quote \"${ETCD_CA_CERT_BASE64:-}\")\nETCD_PEER_KEY: $(yaml-quote \"${ETCD_PEER_KEY_BASE64:-}\")\nETCD_PEER_CERT: $(yaml-quote \"${ETCD_PEER_CERT_BASE64:-}\")\nSERVICEACCOUNT_ISSUER: $(yaml-quote \"${SERVICEACCOUNT_ISSUER:-}\")\nKUBECTL_PRUNE_WHITELIST_OVERRIDE: $(yaml-quote \"${KUBECTL_PRUNE_WHITELIST_OVERRIDE:-}\")\nKUBE_SCHEDULER_RUNASUSER: 2001\nKUBE_SCHEDULER_RUNASGROUP: 2001\nKUBE_ADDON_MANAGER_RUNASUSER: 2002\nKUBE_ADDON_MANAGER_RUNASGROUP: 2002\nKUBE_CONTROLLER_MANAGER_RUNASUSER: 2003\nKUBE_CONTROLLER_MANAGER_RUNASGROUP: 2003\nKUBE_API_SERVER_RUNASUSER: 2004\nKUBE_API_SERVER_RUNASGROUP: 2004\nKUBE_PKI_READERS_GROUP: 2005\nETCD_RUNASUSER: 2006\nETCD_RUNASGROUP: 2006\nKUBE_POD_LOG_READERS_GROUP: 2007\nKONNECTIVITY_SERVER_RUNASUSER: 2008\nKONNECTIVITY_SERVER_RUNASGROUP: 2008\nKONNECTIVITY_SERVER_SOCKET_WRITER_GROUP: 2008\nEOF\n    # KUBE_APISERVER_REQUEST_TIMEOUT_SEC (if set) controls the --request-timeout\n    # flag\n    if [ -n \"${KUBE_APISERVER_REQUEST_TIMEOUT_SEC:-}\" ]; then\n      cat >>\"$file\" <<EOF\nKUBE_APISERVER_REQUEST_TIMEOUT_SEC: $(yaml-quote \"${KUBE_APISERVER_REQUEST_TIMEOUT_SEC}\")\nEOF\n    fi\n    # ETCD_IMAGE (if set) allows to use a custom etcd image.\n    if [ -n \"${ETCD_IMAGE:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_IMAGE: $(yaml-quote \"${ETCD_IMAGE}\")\nEOF\n    fi\n    # ETCD_DOCKER_REPOSITORY (if set) allows to use a custom etcd docker repository to pull the etcd image from.\n    if [ -n \"${ETCD_DOCKER_REPOSITORY:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_DOCKER_REPOSITORY: $(yaml-quote \"${ETCD_DOCKER_REPOSITORY}\")\nEOF\n    fi\n    # ETCD_VERSION (if set) allows you to use custom version of etcd.\n    # The main purpose of using it may be rollback of etcd v3 API,\n    # where we need 3.0.* image, but are rolling back to 2.3.7.\n    if [ -n \"${ETCD_VERSION:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_VERSION: $(yaml-quote \"${ETCD_VERSION}\")\nEOF\n    fi\n    if [ -n \"${ETCD_HOSTNAME:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_HOSTNAME: $(yaml-quote \"${ETCD_HOSTNAME}\")\nEOF\n    fi\n    if [ -n \"${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC: $(yaml-quote \"${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC}\")\nEOF\n    fi\n    if [ -n \"${KUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC:-}\" ]; then\n      cat >>\"$file\" <<EOF\nKUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC: $(yaml-quote \"${KUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC}\")\nEOF\n    fi\n    if [ -n \"${ETCD_COMPACTION_INTERVAL_SEC:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_COMPACTION_INTERVAL_SEC: $(yaml-quote \"${ETCD_COMPACTION_INTERVAL_SEC}\")\nEOF\n    fi\n    if [ -n \"${ETCD_QUOTA_BACKEND_BYTES:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_QUOTA_BACKEND_BYTES: $(yaml-quote \"${ETCD_QUOTA_BACKEND_BYTES}\")\nEOF\n    fi\n    if [ -n \"${ETCD_EXTRA_ARGS:-}\" ]; then\n    cat >>\"$file\" <<EOF\nETCD_EXTRA_ARGS: $(yaml-quote \"${ETCD_EXTRA_ARGS}\")\nEOF\n    fi\n    if [ -n \"${ETCD_SERVERS:-}\" ]; then\n    cat >>\"$file\" <<EOF\nETCD_SERVERS: $(yaml-quote \"${ETCD_SERVERS}\")\nEOF\n    fi\n    if [ -n \"${ETCD_SERVERS_OVERRIDES:-}\" ]; then\n    cat >>\"$file\" <<EOF\nETCD_SERVERS_OVERRIDES: $(yaml-quote \"${ETCD_SERVERS_OVERRIDES}\")\nEOF\n    fi\n    if [ -n \"${APISERVER_TEST_ARGS:-}\" ]; then\n      cat >>\"$file\" <<EOF\nAPISERVER_TEST_ARGS: $(yaml-quote \"${APISERVER_TEST_ARGS}\")\nEOF\n    fi\n    if [ -n \"${CONTROLLER_MANAGER_TEST_ARGS:-}\" ]; then\n      cat >>\"$file\" <<EOF\nCONTROLLER_MANAGER_TEST_ARGS: $(yaml-quote \"${CONTROLLER_MANAGER_TEST_ARGS}\")\nEOF\n    fi\n    if [ -n \"${CONTROLLER_MANAGER_TEST_LOG_LEVEL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nCONTROLLER_MANAGER_TEST_LOG_LEVEL: $(yaml-quote \"${CONTROLLER_MANAGER_TEST_LOG_LEVEL}\")\nEOF\n    fi\n    if [ -n \"${SCHEDULER_TEST_ARGS:-}\" ]; then\n      cat >>\"$file\" <<EOF\nSCHEDULER_TEST_ARGS: $(yaml-quote \"${SCHEDULER_TEST_ARGS}\")\nEOF\n    fi\n    if [ -n \"${SCHEDULER_TEST_LOG_LEVEL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nSCHEDULER_TEST_LOG_LEVEL: $(yaml-quote \"${SCHEDULER_TEST_LOG_LEVEL}\")\nEOF\n    fi\n    if [ -n \"${INITIAL_ETCD_CLUSTER:-}\" ]; then\n      cat >>\"$file\" <<EOF\nINITIAL_ETCD_CLUSTER: $(yaml-quote \"${INITIAL_ETCD_CLUSTER}\")\nEOF\n    fi\n    if [ -n \"${INITIAL_ETCD_CLUSTER_STATE:-}\" ]; then\n      cat >>\"$file\" <<EOF\nINITIAL_ETCD_CLUSTER_STATE: $(yaml-quote \"${INITIAL_ETCD_CLUSTER_STATE}\")\nEOF\n    fi\n    if [ -n \"${CLUSTER_SIGNING_DURATION:-}\" ]; then\n      cat >>\"$file\" <<EOF\nCLUSTER_SIGNING_DURATION: $(yaml-quote \"${CLUSTER_SIGNING_DURATION}\")\nEOF\n    fi\n    if [[ \"${NODE_ACCELERATORS:-}\" == *\"type=nvidia\"* ]]; then\n      cat >>\"$file\" <<EOF\nENABLE_NVIDIA_GPU_DEVICE_PLUGIN: $(yaml-quote \"true\")\nEOF\n    fi\n    if [ -n \"${ADDON_MANAGER_LEADER_ELECTION:-}\" ]; then\n      cat >>\"$file\" <<EOF\nADDON_MANAGER_LEADER_ELECTION: $(yaml-quote \"${ADDON_MANAGER_LEADER_ELECTION}\")\nEOF\n    fi\n    if [ -n \"${API_SERVER_TEST_LOG_LEVEL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nAPI_SERVER_TEST_LOG_LEVEL: $(yaml-quote \"${API_SERVER_TEST_LOG_LEVEL}\")\nEOF\n    fi\n    if [ -n \"${ETCD_LISTEN_CLIENT_IP:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_LISTEN_CLIENT_IP: $(yaml-quote \"${ETCD_LISTEN_CLIENT_IP}\")\nEOF\n    fi\n    if [ -n \"${ETCD_PROGRESS_NOTIFY_INTERVAL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nETCD_PROGRESS_NOTIFY_INTERVAL: $(yaml-quote \"${ETCD_PROGRESS_NOTIFY_INTERVAL}\")\nEOF\n    fi\n\n  else\n    # Node-only env vars.\n    cat >>\"$file\" <<EOF\nKUBERNETES_MASTER: $(yaml-quote \"false\")\nEXTRA_DOCKER_OPTS: $(yaml-quote \"${EXTRA_DOCKER_OPTS:-}\")\nEOF\n    if [ -n \"${KUBEPROXY_TEST_ARGS:-}\" ]; then\n      cat >>\"$file\" <<EOF\nKUBEPROXY_TEST_ARGS: $(yaml-quote \"${KUBEPROXY_TEST_ARGS}\")\nEOF\n    fi\n    if [ -n \"${KUBEPROXY_TEST_LOG_LEVEL:-}\" ]; then\n      cat >>\"$file\" <<EOF\nKUBEPROXY_TEST_LOG_LEVEL: $(yaml-quote \"${KUBEPROXY_TEST_LOG_LEVEL}\")\nEOF\n    fi\n  fi\n  if [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n      cat >>\"$file\" <<EOF\nENABLE_CLUSTER_AUTOSCALER: $(yaml-quote \"${ENABLE_CLUSTER_AUTOSCALER}\")\nAUTOSCALER_MIG_CONFIG: $(yaml-quote \"${AUTOSCALER_MIG_CONFIG}\")\nAUTOSCALER_EXPANDER_CONFIG: $(yaml-quote \"${AUTOSCALER_EXPANDER_CONFIG}\")\nEOF\n      if [[ \"${master}\" == \"false\" ]]; then\n          # TODO(kubernetes/autoscaler#718): AUTOSCALER_ENV_VARS is a hotfix for cluster autoscaler,\n          # which reads the kube-env to determine the shape of a node and was broken by #60020.\n          # This should be removed as soon as a more reliable source of information is available!\n          local node_labels\n          local node_taints\n          local autoscaler_env_vars\n          node_labels=\"$(build-linux-node-labels node)\"\n          node_taints=\"${NODE_TAINTS:-}\"\n          autoscaler_env_vars=\"node_labels=${node_labels};node_taints=${node_taints}\"\n          cat >>\"$file\" <<EOF\nAUTOSCALER_ENV_VARS: $(yaml-quote \"${autoscaler_env_vars}\")\nEOF\n      fi\n  fi\n  if [ -n \"${SCHEDULING_ALGORITHM_PROVIDER:-}\" ]; then\n    cat >>\"$file\" <<EOF\nSCHEDULING_ALGORITHM_PROVIDER: $(yaml-quote \"${SCHEDULING_ALGORITHM_PROVIDER}\")\nEOF\n  fi\n  if [ -n \"${MAX_PODS_PER_NODE:-}\" ]; then\n    cat >>\"$file\" <<EOF\nMAX_PODS_PER_NODE: $(yaml-quote \"${MAX_PODS_PER_NODE}\")\nEOF\n  fi\n  if [[ \"${PREPARE_KONNECTIVITY_SERVICE:-false}\" == \"true\" ]]; then\n      cat >>\"$file\" <<EOF\nPREPARE_KONNECTIVITY_SERVICE: $(yaml-quote \"${PREPARE_KONNECTIVITY_SERVICE}\")\nEOF\n  fi\n  if [[ \"${EGRESS_VIA_KONNECTIVITY:-false}\" == \"true\" ]]; then\n      cat >>\"$file\" <<EOF\nEGRESS_VIA_KONNECTIVITY: $(yaml-quote \"${EGRESS_VIA_KONNECTIVITY}\")\nEOF\n  fi\n  if [[ \"${RUN_KONNECTIVITY_PODS:-false}\" == \"true\" ]]; then\n      cat >>\"$file\" <<EOF\nRUN_KONNECTIVITY_PODS: $(yaml-quote \"${RUN_KONNECTIVITY_PODS}\")\nEOF\n  fi\n  if [[ -n \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-}\" ]]; then\n      cat >>\"$file\" <<EOF\nKONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE: $(yaml-quote \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE}\")\nEOF\n  fi\n}\n\n\nfunction build-windows-kube-env {\n  local file=\"$1\"\n  # For now the Windows kube-env is a superset of the Linux kube-env.\n  build-linux-kube-env false \"$file\"\n\n  cat >>\"$file\" <<EOF\nWINDOWS_NODE_INSTANCE_PREFIX: $(yaml-quote \"${WINDOWS_NODE_INSTANCE_PREFIX}\")\nNODE_BINARY_TAR_URL: $(yaml-quote \"${NODE_BINARY_TAR_URL}\")\nNODE_BINARY_TAR_HASH: $(yaml-quote \"${NODE_BINARY_TAR_HASH}\")\nCSI_PROXY_STORAGE_PATH: $(yaml-quote \"${CSI_PROXY_STORAGE_PATH}\")\nCSI_PROXY_VERSION: $(yaml-quote \"${CSI_PROXY_VERSION}\")\nENABLE_CSI_PROXY: $(yaml-quote \"${ENABLE_CSI_PROXY}\")\nK8S_DIR: $(yaml-quote \"${WINDOWS_K8S_DIR}\")\nNODE_DIR: $(yaml-quote \"${WINDOWS_NODE_DIR}\")\nLOGS_DIR: $(yaml-quote \"${WINDOWS_LOGS_DIR}\")\nCNI_DIR: $(yaml-quote \"${WINDOWS_CNI_DIR}\")\nCNI_CONFIG_DIR: $(yaml-quote \"${WINDOWS_CNI_CONFIG_DIR}\")\nWINDOWS_CNI_STORAGE_PATH: $(yaml-quote \"${WINDOWS_CNI_STORAGE_PATH}\")\nWINDOWS_CNI_VERSION: $(yaml-quote \"${WINDOWS_CNI_VERSION}\")\nWINDOWS_CONTAINER_RUNTIME: $(yaml-quote \"${WINDOWS_CONTAINER_RUNTIME}\")\nWINDOWS_CONTAINER_RUNTIME_ENDPOINT: $(yaml-quote \"${WINDOWS_CONTAINER_RUNTIME_ENDPOINT:-}\")\nMANIFESTS_DIR: $(yaml-quote \"${WINDOWS_MANIFESTS_DIR}\")\nPKI_DIR: $(yaml-quote \"${WINDOWS_PKI_DIR}\")\nCA_FILE_PATH: $(yaml-quote \"${WINDOWS_CA_FILE}\")\nKUBELET_CONFIG_FILE: $(yaml-quote \"${WINDOWS_KUBELET_CONFIG_FILE}\")\nKUBEPROXY_ARGS: $(yaml-quote \"${KUBEPROXY_ARGS}\")\nKUBECONFIG_FILE: $(yaml-quote \"${WINDOWS_KUBECONFIG_FILE}\")\nBOOTSTRAP_KUBECONFIG_FILE: $(yaml-quote \"${WINDOWS_BOOTSTRAP_KUBECONFIG_FILE}\")\nKUBEPROXY_KUBECONFIG_FILE: $(yaml-quote \"${WINDOWS_KUBEPROXY_KUBECONFIG_FILE}\")\nWINDOWS_INFRA_CONTAINER: $(yaml-quote \"${WINDOWS_INFRA_CONTAINER}\")\nWINDOWS_ENABLE_PIGZ: $(yaml-quote \"${WINDOWS_ENABLE_PIGZ}\")\nENABLE_NODE_PROBLEM_DETECTOR: $(yaml-quote \"${WINDOWS_ENABLE_NODE_PROBLEM_DETECTOR}\")\nNODE_PROBLEM_DETECTOR_VERSION: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_VERSION}\")\nNODE_PROBLEM_DETECTOR_TAR_HASH: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_TAR_HASH}\")\nNODE_PROBLEM_DETECTOR_RELEASE_PATH: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_RELEASE_PATH}\")\nNODE_PROBLEM_DETECTOR_CUSTOM_FLAGS: $(yaml-quote \"${WINDOWS_NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS}\")\nNODE_PROBLEM_DETECTOR_TOKEN: $(yaml-quote \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\")\nWINDOWS_NODEPROBLEMDETECTOR_KUBECONFIG_FILE: $(yaml-quote \"${WINDOWS_NODEPROBLEMDETECTOR_KUBECONFIG_FILE}\")\nEOF\n}\n\nfunction sha512sum-file() {\n  local shasum\n  if which sha512sum >/dev/null 2>&1; then\n    shasum=$(sha512sum \"$1\")\n  else\n    shasum=$(shasum -a512 \"$1\")\n  fi\n  echo \"${shasum%%[[:blank:]]*}\"\n}\n\n# Create certificate pairs for the cluster.\n# $1: The public IP for the master.\n#\n# These are used for static cert distribution (e.g. static clustering) at\n# cluster creation time. This will be obsoleted once we implement dynamic\n# clustering.\n#\n# The following certificate pairs are created:\n#\n#  - ca (the cluster's certificate authority)\n#  - server\n#  - kubelet\n#  - kubecfg (for kubectl)\n#\n# TODO(roberthbailey): Replace easyrsa with a simple Go program to generate\n# the certs that we need.\n#\n# Assumed vars\n#   KUBE_TEMP\n#   MASTER_NAME\n#\n# Vars set:\n#   CERT_DIR\n#   CA_CERT_BASE64\n#   MASTER_CERT_BASE64\n#   MASTER_KEY_BASE64\n#   KUBELET_CERT_BASE64\n#   KUBELET_KEY_BASE64\n#   KUBECFG_CERT_BASE64\n#   KUBECFG_KEY_BASE64\nfunction create-certs {\n  local -r primary_cn=\"${1}\"\n\n  # Determine extra certificate names for master\n\n  # Create service_ip by stripping the network mask part from\n  # SERVICE_CLUSTER_IP_RANGE and incrementing the host part with 1\n  service_ip=${SERVICE_CLUSTER_IP_RANGE%/*}\n  service_ip=\"${service_ip%.*}.$((${service_ip##*.} + 1))\"\n  local sans=\"\"\n  for extra in \"$@\"; do\n    if [[ -n \"${extra}\" ]]; then\n      sans=\"${sans}IP:${extra},\"\n    fi\n  done\n  sans=\"${sans}IP:${service_ip},DNS:kubernetes,DNS:kubernetes.default,DNS:kubernetes.default.svc,DNS:kubernetes.default.svc.${DNS_DOMAIN},DNS:${MASTER_NAME}\"\n\n  echo \"Generating certs for alternate-names: ${sans}\"\n\n  setup-easyrsa\n  PRIMARY_CN=\"${primary_cn}\" SANS=\"${sans}\" generate-certs\n  AGGREGATOR_PRIMARY_CN=\"${primary_cn}\" AGGREGATOR_SANS=\"${sans}\" generate-aggregator-certs\n\n  # By default, linux wraps base64 output every 76 cols, so we use 'tr -d' to remove whitespaces.\n  # Note 'base64 -w0' doesn't work on Mac OS X, which has different flags.\n  CA_KEY_BASE64=$(base64 \"${CERT_DIR}/pki/private/ca.key\" | tr -d '\\r\\n')\n  CA_CERT_BASE64=$(base64 \"${CERT_DIR}/pki/ca.crt\" | tr -d '\\r\\n')\n  MASTER_CERT_BASE64=$(base64 \"${CERT_DIR}/pki/issued/${MASTER_NAME}.crt\" | tr -d '\\r\\n')\n  MASTER_KEY_BASE64=$(base64 \"${CERT_DIR}/pki/private/${MASTER_NAME}.key\" | tr -d '\\r\\n')\n  KUBELET_CERT_BASE64=$(base64 \"${CERT_DIR}/pki/issued/kubelet.crt\" | tr -d '\\r\\n')\n  KUBELET_KEY_BASE64=$(base64 \"${CERT_DIR}/pki/private/kubelet.key\" | tr -d '\\r\\n')\n  KUBECFG_CERT_BASE64=$(base64 \"${CERT_DIR}/pki/issued/kubecfg.crt\" | tr -d '\\r\\n')\n  KUBECFG_KEY_BASE64=$(base64 \"${CERT_DIR}/pki/private/kubecfg.key\" | tr -d '\\r\\n')\n  KUBEAPISERVER_CERT_BASE64=$(base64 \"${CERT_DIR}/pki/issued/kube-apiserver.crt\" | tr -d '\\r\\n')\n  KUBEAPISERVER_KEY_BASE64=$(base64 \"${CERT_DIR}/pki/private/kube-apiserver.key\" | tr -d '\\r\\n')\n\n  # Setting up an addition directory (beyond pki) as it is the simplest way to\n  # ensure we get a different CA pair to sign the proxy-client certs and which\n  # we can send CA public key to the user-apiserver to validate communication.\n  AGGREGATOR_CA_KEY_BASE64=$(base64 \"${AGGREGATOR_CERT_DIR}/pki/private/ca.key\" | tr -d '\\r\\n')\n  REQUESTHEADER_CA_CERT_BASE64=$(base64 \"${AGGREGATOR_CERT_DIR}/pki/ca.crt\" | tr -d '\\r\\n')\n  PROXY_CLIENT_CERT_BASE64=$(base64 \"${AGGREGATOR_CERT_DIR}/pki/issued/proxy-client.crt\" | tr -d '\\r\\n')\n  PROXY_CLIENT_KEY_BASE64=$(base64 \"${AGGREGATOR_CERT_DIR}/pki/private/proxy-client.key\" | tr -d '\\r\\n')\n}\n\n# Set up easy-rsa directory structure.\n#\n# Assumed vars\n#   KUBE_TEMP\n#\n# Vars set:\n#   CERT_DIR\n#   AGGREGATOR_CERT_DIR\nfunction setup-easyrsa {\n  local -r cert_create_debug_output=$(mktemp \"${KUBE_TEMP}/cert_create_debug_output.XXX\")\n  # Note: This was heavily cribbed from make-ca-cert.sh\n  (set -x\n    cd \"${KUBE_TEMP}\"\n    curl -L -O --connect-timeout 20 --retry 6 --retry-delay 2 https://storage.googleapis.com/kubernetes-release/easy-rsa/easy-rsa.tar.gz\n    tar xzf easy-rsa.tar.gz\n    mkdir easy-rsa-master/kubelet\n    cp -r easy-rsa-master/easyrsa3/* easy-rsa-master/kubelet\n    mkdir easy-rsa-master/aggregator\n    cp -r easy-rsa-master/easyrsa3/* easy-rsa-master/aggregator) &>\"${cert_create_debug_output}\" || true\n  CERT_DIR=\"${KUBE_TEMP}/easy-rsa-master/easyrsa3\"\n  AGGREGATOR_CERT_DIR=\"${KUBE_TEMP}/easy-rsa-master/aggregator\"\n  if [ ! -x \"${CERT_DIR}/easyrsa\" ] || [ ! -x \"${AGGREGATOR_CERT_DIR}/easyrsa\" ]; then\n    # TODO(roberthbailey,porridge): add better error handling here,\n    # see https://github.com/kubernetes/kubernetes/issues/55229\n    cat \"${cert_create_debug_output}\" >&2\n    echo \"=== Failed to setup easy-rsa: Aborting ===\" >&2\n    exit 2\n  fi\n}\n\n# Runs the easy RSA commands to generate certificate files.\n# The generated files are IN ${CERT_DIR}\n#\n# Assumed vars (see shellcheck disable directives below)\n#   KUBE_TEMP\n#   MASTER_NAME\n#   CERT_DIR\n#   PRIMARY_CN: Primary canonical name\n#   SANS: Subject alternate names\n#\n#\nfunction generate-certs {\n  local -r cert_create_debug_output=$(mktemp \"${KUBE_TEMP}/cert_create_debug_output.XXX\")\n  # Note: This was heavily cribbed from make-ca-cert.sh\n  (set -x\n    cd \"${CERT_DIR}\"\n    ./easyrsa init-pki\n    # this puts the cert into pki/ca.crt and the key into pki/private/ca.key\n    # PRIMARY_CN (expected to be) defined by caller\n    # shellcheck disable=SC2153\n    ./easyrsa --batch \"--req-cn=${PRIMARY_CN}@$(date +%s)\" build-ca nopass\n    # SANS (expected to be) defined by caller\n    # shellcheck disable=SC2153\n    ./easyrsa --subject-alt-name=\"${SANS}\" build-server-full \"${MASTER_NAME}\" nopass\n    ./easyrsa build-client-full kube-apiserver nopass\n\n    kube::util::ensure-cfssl \"${KUBE_TEMP}/cfssl\"\n\n    # make the config for the signer\n    echo '{\"signing\":{\"default\":{\"expiry\":\"43800h\",\"usages\":[\"signing\",\"key encipherment\",\"client auth\"]}}}' > \"ca-config.json\"\n    # create the kubelet client cert with the correct groups\n    echo '{\"CN\":\"kubelet\",\"names\":[{\"O\":\"system:nodes\"}],\"hosts\":[\"\"],\"key\":{\"algo\":\"rsa\",\"size\":2048}}' | \"${CFSSL_BIN}\" gencert -ca=pki/ca.crt -ca-key=pki/private/ca.key -config=ca-config.json - | \"${CFSSLJSON_BIN}\" -bare kubelet\n    mv \"kubelet-key.pem\" \"pki/private/kubelet.key\"\n    mv \"kubelet.pem\" \"pki/issued/kubelet.crt\"\n    rm -f \"kubelet.csr\"\n\n    # Make a superuser client cert with subject \"O=system:masters, CN=kubecfg\"\n    ./easyrsa --dn-mode=org \\\n      --req-cn=kubecfg --req-org=system:masters \\\n      --req-c= --req-st= --req-city= --req-email= --req-ou= \\\n      build-client-full kubecfg nopass) &>\"${cert_create_debug_output}\" || true\n  local output_file_missing=0\n  local output_file\n  for output_file in \\\n    \"${CERT_DIR}/pki/private/ca.key\" \\\n    \"${CERT_DIR}/pki/ca.crt\" \\\n    \"${CERT_DIR}/pki/issued/${MASTER_NAME}.crt\" \\\n    \"${CERT_DIR}/pki/private/${MASTER_NAME}.key\" \\\n    \"${CERT_DIR}/pki/issued/kubelet.crt\" \\\n    \"${CERT_DIR}/pki/private/kubelet.key\" \\\n    \"${CERT_DIR}/pki/issued/kubecfg.crt\" \\\n    \"${CERT_DIR}/pki/private/kubecfg.key\" \\\n    \"${CERT_DIR}/pki/issued/kube-apiserver.crt\" \\\n    \"${CERT_DIR}/pki/private/kube-apiserver.key\"\n  do\n    if [[ ! -s \"${output_file}\" ]]; then\n      echo \"Expected file ${output_file} not created\" >&2\n      output_file_missing=1\n    fi\n  done\n  if [ $output_file_missing -ne 0 ]; then\n    # TODO(roberthbailey,porridge): add better error handling here,\n    # see https://github.com/kubernetes/kubernetes/issues/55229\n    cat \"${cert_create_debug_output}\" >&2\n    echo \"=== Failed to generate master certificates: Aborting ===\" >&2\n    exit 2\n  fi\n}\n\n# Runs the easy RSA commands to generate aggregator certificate files.\n# The generated files are in ${AGGREGATOR_CERT_DIR}\n#\n# Assumed vars\n#   KUBE_TEMP\n#   AGGREGATOR_MASTER_NAME\n#   AGGREGATOR_CERT_DIR\n#   AGGREGATOR_PRIMARY_CN: Primary canonical name\n#   AGGREGATOR_SANS: Subject alternate names\n#\n#\nfunction generate-aggregator-certs {\n  local -r cert_create_debug_output=$(mktemp \"${KUBE_TEMP}/cert_create_debug_output.XXX\")\n  # Note: This was heavily cribbed from make-ca-cert.sh\n  (set -x\n    cd \"${KUBE_TEMP}/easy-rsa-master/aggregator\"\n    ./easyrsa init-pki\n    # this puts the cert into pki/ca.crt and the key into pki/private/ca.key\n    ./easyrsa --batch \"--req-cn=${AGGREGATOR_PRIMARY_CN}@$(date +%s)\" build-ca nopass\n    ./easyrsa --subject-alt-name=\"${AGGREGATOR_SANS}\" build-server-full \"${AGGREGATOR_MASTER_NAME}\" nopass\n    ./easyrsa build-client-full aggregator-apiserver nopass\n\n    kube::util::ensure-cfssl \"${KUBE_TEMP}/cfssl\"\n\n    # make the config for the signer\n    echo '{\"signing\":{\"default\":{\"expiry\":\"43800h\",\"usages\":[\"signing\",\"key encipherment\",\"client auth\"]}}}' > \"ca-config.json\"\n    # create the aggregator client cert with the correct groups\n    echo '{\"CN\":\"aggregator\",\"hosts\":[\"\"],\"key\":{\"algo\":\"rsa\",\"size\":2048}}' | \"${CFSSL_BIN}\" gencert -ca=pki/ca.crt -ca-key=pki/private/ca.key -config=ca-config.json - | \"${CFSSLJSON_BIN}\" -bare proxy-client\n    mv \"proxy-client-key.pem\" \"pki/private/proxy-client.key\"\n    mv \"proxy-client.pem\" \"pki/issued/proxy-client.crt\"\n    rm -f \"proxy-client.csr\"\n\n    # Make a superuser client cert with subject \"O=system:masters, CN=kubecfg\"\n    ./easyrsa --dn-mode=org \\\n      --req-cn=proxy-clientcfg --req-org=system:aggregator \\\n      --req-c= --req-st= --req-city= --req-email= --req-ou= \\\n      build-client-full proxy-clientcfg nopass) &>\"${cert_create_debug_output}\" || true\n  local output_file_missing=0\n  local output_file\n  for output_file in \\\n    \"${AGGREGATOR_CERT_DIR}/pki/private/ca.key\" \\\n    \"${AGGREGATOR_CERT_DIR}/pki/ca.crt\" \\\n    \"${AGGREGATOR_CERT_DIR}/pki/issued/proxy-client.crt\" \\\n    \"${AGGREGATOR_CERT_DIR}/pki/private/proxy-client.key\"\n  do\n    if [[ ! -s \"${output_file}\" ]]; then\n      echo \"Expected file ${output_file} not created\" >&2\n      output_file_missing=1\n    fi\n  done\n  if [ $output_file_missing -ne 0 ]; then\n    # TODO(roberthbailey,porridge): add better error handling here,\n    # see https://github.com/kubernetes/kubernetes/issues/55229\n    cat \"${cert_create_debug_output}\" >&2\n    echo \"=== Failed to generate aggregator certificates: Aborting ===\" >&2\n    exit 2\n  fi\n}\n\n# Using provided master env, extracts value from provided key.\n#\n# Args:\n# $1 master env (kube-env of master; result of calling get-master-env)\n# $2 env key to use\nfunction get-env-val() {\n  local match\n  match=$( (echo \"${1}\" | grep -E \"^${2}:\") || echo '')\n  if [[ -z \"${match}\" ]]; then\n    echo \"\"\n  fi\n  echo \"${match}\" | cut -d : -f 2 | cut -d \\' -f 2\n}\n\n# Load the master env by calling get-master-env, and extract important values\nfunction parse-master-env() {\n  # Get required master env vars\n  local master_env\n  master_env=$(get-master-env)\n  KUBE_PROXY_TOKEN=$(get-env-val \"${master_env}\" \"KUBE_PROXY_TOKEN\")\n  NODE_PROBLEM_DETECTOR_TOKEN=$(get-env-val \"${master_env}\" \"NODE_PROBLEM_DETECTOR_TOKEN\")\n  CA_CERT_BASE64=$(get-env-val \"${master_env}\" \"CA_CERT\")\n  CA_KEY_BASE64=$(get-env-val \"${master_env}\" \"CA_KEY\")\n  KUBEAPISERVER_CERT_BASE64=$(get-env-val \"${master_env}\" \"KUBEAPISERVER_CERT\")\n  KUBEAPISERVER_KEY_BASE64=$(get-env-val \"${master_env}\" \"KUBEAPISERVER_KEY\")\n  EXTRA_DOCKER_OPTS=$(get-env-val \"${master_env}\" \"EXTRA_DOCKER_OPTS\")\n  KUBELET_CERT_BASE64=$(get-env-val \"${master_env}\" \"KUBELET_CERT\")\n  KUBELET_KEY_BASE64=$(get-env-val \"${master_env}\" \"KUBELET_KEY\")\n  MASTER_CERT_BASE64=$(get-env-val \"${master_env}\" \"MASTER_CERT\")\n  MASTER_KEY_BASE64=$(get-env-val \"${master_env}\" \"MASTER_KEY\")\n  AGGREGATOR_CA_KEY_BASE64=$(get-env-val \"${master_env}\" \"AGGREGATOR_CA_KEY\")\n  REQUESTHEADER_CA_CERT_BASE64=$(get-env-val \"${master_env}\" \"REQUESTHEADER_CA_CERT\")\n  PROXY_CLIENT_CERT_BASE64=$(get-env-val \"${master_env}\" \"PROXY_CLIENT_CERT\")\n  PROXY_CLIENT_KEY_BASE64=$(get-env-val \"${master_env}\" \"PROXY_CLIENT_KEY\")\n  ENABLE_LEGACY_ABAC=$(get-env-val \"${master_env}\" \"ENABLE_LEGACY_ABAC\")\n  ETCD_APISERVER_CA_KEY_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_CA_KEY\")\n  ETCD_APISERVER_CA_CERT_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_CA_CERT\")\n  ETCD_APISERVER_SERVER_KEY_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_SERVER_KEY\")\n  ETCD_APISERVER_SERVER_CERT_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_SERVER_CERT\")\n  ETCD_APISERVER_CLIENT_KEY_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_CLIENT_KEY\")\n  ETCD_APISERVER_CLIENT_CERT_BASE64=$(get-env-val \"${master_env}\" \"ETCD_APISERVER_CLIENT_CERT\")\n}\n\n# Update or verify required gcloud components are installed\n# at minimum required version.\n# Assumed vars\n#   KUBE_PROMPT_FOR_UPDATE\nfunction update-or-verify-gcloud() {\n  local sudo_prefix=\"\"\n  if [ ! -w \"$(dirname \"$(which gcloud)\")\" ]; then\n    sudo_prefix=\"sudo\"\n  fi\n  # update and install components as needed\n  # (deliberately word split $gcloud_prompt)\n  # shellcheck disable=SC2086\n  if [[ \"${KUBE_PROMPT_FOR_UPDATE}\" == \"y\" ]]; then\n    ${sudo_prefix} gcloud ${gcloud_prompt:-} components install alpha\n    ${sudo_prefix} gcloud ${gcloud_prompt:-} components install beta\n    ${sudo_prefix} gcloud ${gcloud_prompt:-} components update\n  else\n    local version\n    version=$(gcloud version --format=json)\n    python3 -c\"\nimport json,sys\nfrom distutils import version\n\nminVersion = version.LooseVersion('1.3.0')\nrequired = [ 'alpha', 'beta', 'core' ]\ndata = json.loads(sys.argv[1])\nrel = data.get('Google Cloud SDK')\nif 'CL @' in rel:\n  print('Using dev version of gcloud: %s' %rel)\n  exit(0)\nif rel != 'HEAD' and version.LooseVersion(rel) < minVersion:\n  print('gcloud version out of date ( < %s )' % minVersion)\n  exit(1)\nmissing = []\nfor c in required:\n  if not data.get(c):\n    missing += [c]\nif missing:\n  for c in missing:\n    print ('missing required gcloud component \\\"{0}\\\"'.format(c))\n    print ('Try running \\$(gcloud components install {0})'.format(c))\n  exit(1)\n    \" \"${version}\"\n  fi\n}\n\n# Robustly try to create a static ip.\n# $1: The name of the ip to create\n# $2: The name of the region to create the ip in.\nfunction create-static-ip() {\n  detect-project\n  local attempt=0\n  local REGION=\"$2\"\n  while true; do\n    if gcloud compute addresses create \"$1\" \\\n      --project \"${PROJECT}\" \\\n      --region \"${REGION}\" -q > /dev/null; then\n      # successful operation - wait until it's visible\n      start=\"$(date +%s)\"\n      while true; do\n        now=\"$(date +%s)\"\n        # Timeout set to 15 minutes\n        if [[ $((now - start)) -gt 900 ]]; then\n          echo \"Timeout while waiting for master IP visibility\"\n          exit 2\n        fi\n        if gcloud compute addresses describe \"$1\" --project \"${PROJECT}\" --region \"${REGION}\" >/dev/null 2>&1; then\n          break\n        fi\n        echo \"Master IP not visible yet. Waiting...\"\n        sleep 5\n      done\n      break\n    fi\n\n    if gcloud compute addresses describe \"$1\" \\\n      --project \"${PROJECT}\" \\\n      --region \"${REGION}\" >/dev/null 2>&1; then\n      # it exists - postcondition satisfied\n      break\n    fi\n\n    if (( attempt > 4 )); then\n      echo -e \"${color_red}Failed to create static ip $1 ${color_norm}\" >&2\n      exit 2\n    fi\n    attempt=$((attempt + 1))\n    echo -e \"${color_yellow:-}Attempt $attempt failed to create static ip $1. Retrying.${color_norm:-}\" >&2\n    sleep $((attempt * 5))\n  done\n}\n\n# Robustly try to create a firewall rule.\n# $1: The name of firewall rule.\n# $2: IP ranges.\n# $3: Target tags for this firewall rule.\nfunction create-firewall-rule() {\n  detect-project\n  local attempt=0\n  while true; do\n    if ! gcloud compute firewall-rules create \"$1\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --source-ranges \"$2\" \\\n      --target-tags \"$3\" \\\n      --allow tcp,udp,icmp,esp,ah,sctp; then\n      if (( attempt > 4 )); then\n        echo -e \"${color_red}Failed to create firewall rule $1 ${color_norm}\" >&2\n        exit 2\n      fi\n      echo -e \"${color_yellow}Attempt $((attempt + 1)) failed to create firewall rule $1. Retrying.${color_norm}\" >&2\n      attempt=$((attempt + 1))\n      sleep $((attempt * 5))\n    else\n        break\n    fi\n  done\n}\n\n# Format the string argument for gcloud network.\nfunction make-gcloud-network-argument() {\n  local network_project=\"$1\"\n  local region=\"$2\"\n  local network=\"$3\"\n  local subnet=\"$4\"\n  local address=\"$5\"          # optional\n  local enable_ip_alias=\"$6\"  # optional\n  local alias_size=\"$7\"       # optional\n\n  local networkURL=\"projects/${network_project}/global/networks/${network}\"\n  local subnetURL=\"projects/${network_project}/regions/${region}/subnetworks/${subnet:-}\"\n\n  local ret=\"\"\n\n  if [[ \"${enable_ip_alias}\" == 'true' ]]; then\n    ret=\"--network-interface\"\n    ret=\"${ret} network=${networkURL}\"\n    if [[ \"${address:-}\" == \"no-address\" ]]; then\n      ret=\"${ret},no-address\"\n    else\n      ret=\"${ret},address=${address:-}\"\n    fi\n    ret=\"${ret},subnet=${subnetURL}\"\n    ret=\"${ret},aliases=pods-default:${alias_size}\"\n    ret=\"${ret} --no-can-ip-forward\"\n  else\n    if [[ -n ${subnet:-} ]]; then\n      ret=\"${ret} --subnet ${subnetURL}\"\n    else\n      ret=\"${ret} --network ${networkURL}\"\n    fi\n\n    ret=\"${ret} --can-ip-forward\"\n    if [[ -n ${address:-} ]] && [[ \"$address\" != \"no-address\" ]]; then\n      ret=\"${ret} --address ${address}\"\n    fi\n  fi\n\n  echo \"${ret}\"\n}\n\n# $1: version (required)\n# $2: Prefix for the template name, i.e. NODE_INSTANCE_PREFIX or\n#     WINDOWS_NODE_INSTANCE_PREFIX.\nfunction get-template-name-from-version() {\n  local -r version=${1}\n  local -r template_prefix=${2}\n  # trim template name to pass gce name validation\n  echo \"${template_prefix}-template-${version}\" | cut -c 1-63 | sed 's/[\\.\\+]/-/g;s/-*$//g'\n}\n\n# validates the NODE_LOCAL_SSDS_EXT variable\nfunction validate-node-local-ssds-ext(){\n  ssdopts=\"${1}\"\n\n  if [[ -z \"${ssdopts[0]}\" || -z \"${ssdopts[1]}\" || -z \"${ssdopts[2]}\" ]]; then\n    echo -e \"${color_red}Local SSD: NODE_LOCAL_SSDS_EXT is malformed, found ${ssdopts[0]-_},${ssdopts[1]-_},${ssdopts[2]-_} ${color_norm}\" >&2\n    exit 2\n  fi\n  if [[ \"${ssdopts[1]}\" != \"scsi\" && \"${ssdopts[1]}\" != \"nvme\" ]]; then\n    echo -e \"${color_red}Local SSD: Interface must be scsi or nvme, found: ${ssdopts[1]} ${color_norm}\" >&2\n    exit 2\n  fi\n  if [[ \"${ssdopts[2]}\" != \"fs\" && \"${ssdopts[2]}\" != \"block\" ]]; then\n    echo -e \"${color_red}Local SSD: Filesystem type must be fs or block, found: ${ssdopts[2]} ${color_norm}\"  >&2\n    exit 2\n  fi\n  local_ssd_ext_count=$((local_ssd_ext_count+ssdopts[0]))\n  if [[ \"${local_ssd_ext_count}\" -gt \"${GCE_MAX_LOCAL_SSD}\" || \"${local_ssd_ext_count}\" -lt 1 ]]; then\n    echo -e \"${color_red}Local SSD: Total number of local ssds must range from 1 to 8, found: ${local_ssd_ext_count} ${color_norm}\" >&2\n    exit 2\n  fi\n}\n\n# Robustly try to create an instance template.\n# $1: The name of the instance template.\n# $2: The scopes flag.\n# $3: String of comma-separated metadata-from-file entries.\n# $4: String of comma-separated metadata (key=value) entries.\n# $5: the node OS (\"linux\" or \"windows\").\nfunction create-node-template() {\n  detect-project\n  detect-subnetworks\n  local template_name=\"$1\"\n  local metadata_values=\"$4\"\n  local os=\"$5\"\n  local machine_type=\"$6\"\n\n  # First, ensure the template doesn't exist.\n  # TODO(zmerlynn): To make this really robust, we need to parse the output and\n  #                 add retries. Just relying on a non-zero exit code doesn't\n  #                 distinguish an ephemeral failed call from a \"not-exists\".\n  if gcloud compute instance-templates describe \"${template_name}\" --project \"${PROJECT}\" &>/dev/null; then\n    echo \"Instance template ${1} already exists; deleting.\" >&2\n    if ! gcloud compute instance-templates delete \"${template_name}\" --project \"${PROJECT}\" --quiet &>/dev/null; then\n      echo -e \"${color_yellow}Failed to delete existing instance template${color_norm}\" >&2\n      exit 2\n    fi\n  fi\n\n  local gcloud=\"gcloud\"\n\n  local accelerator_args=()\n  # VMs with Accelerators cannot be live migrated.\n  # More details here - https://cloud.google.com/compute/docs/gpus/add-gpus#create-new-gpu-instance\n  if [[ -n \"${NODE_ACCELERATORS}\" ]]; then\n    accelerator_args+=(--maintenance-policy TERMINATE --restart-on-failure --accelerator \"${NODE_ACCELERATORS}\")\n    gcloud=\"gcloud beta\"\n  fi\n\n  local preemptible_minions=()\n  if [[ \"${PREEMPTIBLE_NODE}\" == \"true\" ]]; then\n    preemptible_minions+=(--preemptible --maintenance-policy TERMINATE)\n  fi\n\n  local local_ssds=()\n  local_ssd_ext_count=0\n  if [[ -n \"${NODE_LOCAL_SSDS_EXT:-}\" ]]; then\n    IFS=\";\" read -r -a ssdgroups <<< \"${NODE_LOCAL_SSDS_EXT:-}\"\n    for ssdgroup in \"${ssdgroups[@]}\"\n    do\n      IFS=\",\" read -r -a ssdopts <<< \"${ssdgroup}\"\n      validate-node-local-ssds-ext \"${ssdopts[@]}\"\n      for ((i=1; i<=ssdopts[0]; i++)); do\n        local_ssds+=(\"--local-ssd=interface=${ssdopts[1]}\")\n      done\n    done\n  fi\n\n  if [[ -n ${NODE_LOCAL_SSDS+x} ]]; then\n    # The NODE_LOCAL_SSDS check below fixes issue #49171\n    for ((i=1; i<=NODE_LOCAL_SSDS; i++)); do\n      local_ssds+=('--local-ssd=interface=SCSI')\n    done\n  fi\n\n  local address=\"\"\n  if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n    address=\"no-address\"\n  fi\n\n  local network\n  network=$(make-gcloud-network-argument \\\n    \"${NETWORK_PROJECT}\" \\\n    \"${REGION}\" \\\n    \"${NETWORK}\" \\\n    \"${SUBNETWORK:-}\" \\\n    \"${address}\" \\\n    \"${ENABLE_IP_ALIASES:-}\" \\\n    \"${IP_ALIAS_SIZE:-}\")\n\n  local node_image_flags=()\n  if [[ \"${os}\" == 'linux' ]]; then\n      node_image_flags+=(--image-project \"${NODE_IMAGE_PROJECT}\" --image \"${NODE_IMAGE}\")\n  elif [[ \"${os}\" == 'windows' ]]; then\n      node_image_flags+=(--image-project \"${WINDOWS_NODE_IMAGE_PROJECT}\" --image \"${WINDOWS_NODE_IMAGE}\")\n  else\n      echo \"Unknown OS ${os}\" >&2\n      exit 1\n  fi\n\n  local metadata_flag=\"${metadata_values:+--metadata ${metadata_values}}\"\n\n  local attempt=1\n  while true; do\n    echo \"Attempt ${attempt} to create ${1}\" >&2\n    # Deliberately word split ${network}, $2 and ${metadata_flag}\n    # shellcheck disable=SC2086\n    if ! ${gcloud} compute instance-templates create \\\n      \"${template_name}\" \\\n      --project \"${PROJECT}\" \\\n      --machine-type \"${machine_type}\" \\\n      --boot-disk-type \"${NODE_DISK_TYPE}\" \\\n      --boot-disk-size \"${NODE_DISK_SIZE}\" \\\n      \"${node_image_flags[@]}\" \\\n      --service-account \"${NODE_SERVICE_ACCOUNT}\" \\\n      --tags \"${NODE_TAG}\" \\\n      \"${accelerator_args[@]}\" \\\n      \"${local_ssds[@]}\" \\\n      --region \"${REGION}\" \\\n      ${network} \\\n      \"${preemptible_minions[@]}\" \\\n      $2 \\\n      --metadata-from-file \"$3\" \\\n      ${metadata_flag} >&2; then\n        if (( attempt > 5 )); then\n          echo -e \"${color_red}Failed to create instance template ${template_name} ${color_norm}\" >&2\n          exit 2\n        fi\n        echo -e \"${color_yellow}Attempt ${attempt} failed to create instance template ${template_name}. Retrying.${color_norm}\" >&2\n        attempt=$((attempt + 1))\n        sleep $((attempt * 5))\n\n        # In case the previous attempt failed with something like a\n        # Backend Error and left the entry laying around, delete it\n        # before we try again.\n        gcloud compute instance-templates delete \"${template_name}\" --project \"${PROJECT}\" &>/dev/null || true\n    else\n        break\n    fi\n  done\n}\n\n# Instantiate a kubernetes cluster\n#\n# Assumed vars\n#   KUBE_ROOT\n#   <Various vars set in config file>\nfunction kube-up() {\n  kube::util::ensure-temp-dir\n  detect-project\n\n  load-or-gen-kube-basicauth\n  load-or-gen-kube-bearertoken\n\n  # Make sure we have the tar files staged on Google Storage\n  find-release-tars\n  upload-tars\n\n  # ensure that environmental variables specifying number of migs to create\n  set_num_migs\n\n  if [[ ${KUBE_USE_EXISTING_MASTER:-} == \"true\" ]]; then\n    detect-master\n    parse-master-env\n    create-subnetworks\n    detect-subnetworks\n    # Windows nodes take longer to boot and setup so create them first.\n    create-windows-nodes\n    create-linux-nodes\n  elif [[ ${KUBE_REPLICATE_EXISTING_MASTER:-} == \"true\" ]]; then\n    detect-master\n    if  [[ \"${MASTER_OS_DISTRIBUTION}\" != \"gci\" && \"${MASTER_OS_DISTRIBUTION}\" != \"ubuntu\" ]]; then\n      echo \"Master replication supported only for gci and ubuntu\"\n      return 1\n    fi\n    if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      create-internal-loadbalancer\n    fi\n    create-loadbalancer\n    # If replication of master fails, we need to ensure that the replica is removed from etcd clusters.\n    if ! replicate-master; then\n      remove-replica-from-etcd 2379 true || true\n      remove-replica-from-etcd 4002 false || true\n    fi\n  else\n    check-existing\n    create-network\n    create-subnetworks\n    detect-subnetworks\n    create-cloud-nat-router\n    write-cluster-location\n    write-cluster-name\n    create-autoscaler-config\n    create-master\n    create-nodes-firewall\n    create-nodes-template\n    if [[ \"${KUBE_CREATE_NODES}\" == \"true\" ]]; then\n      # Windows nodes take longer to boot and setup so create them first.\n      create-windows-nodes\n      create-linux-nodes\n    fi\n    check-cluster\n  fi\n}\n\nfunction check-existing() {\n  local running_in_terminal=false\n  # May be false if tty is not allocated (for example with ssh -T).\n  if [[ -t 1 ]]; then\n    running_in_terminal=true\n  fi\n\n  if [[ ${running_in_terminal} == \"true\" || ${KUBE_UP_AUTOMATIC_CLEANUP} == \"true\" ]]; then\n    if ! check-resources; then\n      local run_kube_down=\"n\"\n      echo \"${KUBE_RESOURCE_FOUND} found.\" >&2\n      # Get user input only if running in terminal.\n      if [[ ${running_in_terminal} == \"true\" && ${KUBE_UP_AUTOMATIC_CLEANUP} == \"false\" ]]; then\n        read -r -p \"Would you like to shut down the old cluster (call kube-down)? [y/N] \" run_kube_down\n      fi\n      if [[ ${run_kube_down} == \"y\" || ${run_kube_down} == \"Y\" || ${KUBE_UP_AUTOMATIC_CLEANUP} == \"true\" ]]; then\n        echo \"... calling kube-down\" >&2\n        kube-down\n      fi\n    fi\n  fi\n}\n\nfunction check-network-mode() {\n  local mode\n  mode=$(gcloud compute networks list --filter=\"name=('${NETWORK}')\" --project \"${NETWORK_PROJECT}\" --format='value(x_gcloud_subnet_mode)' || true)\n  # The deprecated field uses lower case. Convert to upper case for consistency.\n  echo \"$mode\" | tr '[:lower:]' '[:upper:]'\n}\n\nfunction create-network() {\n  if ! gcloud compute networks --project \"${NETWORK_PROJECT}\" describe \"${NETWORK}\" &>/dev/null; then\n    # The network needs to be created synchronously or we have a race. The\n    # firewalls can be added concurrent with instance creation.\n    local network_mode=\"auto\"\n    if [[ \"${CREATE_CUSTOM_NETWORK:-}\" == \"true\" ]]; then\n      network_mode=\"custom\"\n    fi\n    echo \"Creating new ${network_mode} network: ${NETWORK}\"\n    gcloud compute networks create --project \"${NETWORK_PROJECT}\" \"${NETWORK}\" --subnet-mode=\"${network_mode}\"\n  else\n    PREEXISTING_NETWORK=true\n    PREEXISTING_NETWORK_MODE=\"$(check-network-mode)\"\n    echo \"Found existing network ${NETWORK} in ${PREEXISTING_NETWORK_MODE} mode.\"\n  fi\n\n  if ! gcloud compute firewall-rules --project \"${NETWORK_PROJECT}\" describe \"${CLUSTER_NAME}-default-internal-master\" &>/dev/null; then\n    gcloud compute firewall-rules create \"${CLUSTER_NAME}-default-internal-master\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --source-ranges \"10.0.0.0/8\" \\\n      --allow \"tcp:1-2379,tcp:2382-65535,udp:1-65535,icmp\" \\\n      --target-tags \"${MASTER_TAG}\"&\n  fi\n\n  if ! gcloud compute firewall-rules --project \"${NETWORK_PROJECT}\" describe \"${CLUSTER_NAME}-default-internal-node\" &>/dev/null; then\n    gcloud compute firewall-rules create \"${CLUSTER_NAME}-default-internal-node\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --source-ranges \"10.0.0.0/8\" \\\n      --allow \"tcp:1-65535,udp:1-65535,icmp\" \\\n      --target-tags \"${NODE_TAG}\"&\n  fi\n\n  if ! gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${NETWORK}-default-ssh\" &>/dev/null; then\n    gcloud compute firewall-rules create \"${NETWORK}-default-ssh\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --source-ranges \"0.0.0.0/0\" \\\n      --allow \"tcp:22\" &\n  fi\n\n  # Open up TCP 3389 to allow RDP connections.\n  if [[ ${NUM_WINDOWS_NODES} -gt 0 ]]; then\n    if ! gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${NETWORK}-default-rdp\" &>/dev/null; then\n      gcloud compute firewall-rules create \"${NETWORK}-default-rdp\" \\\n        --project \"${NETWORK_PROJECT}\" \\\n        --network \"${NETWORK}\" \\\n        --source-ranges \"0.0.0.0/0\" \\\n        --allow \"tcp:3389\" &\n    fi\n  fi\n}\n\nfunction expand-default-subnetwork() {\n  gcloud compute networks update \"${NETWORK}\" \\\n    --switch-to-custom-subnet-mode \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --quiet || true\n  gcloud compute networks subnets expand-ip-range \"${NETWORK}\" \\\n    --region=\"${REGION}\" \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --prefix-length=19 \\\n    --quiet\n}\n\nfunction create-subnetworks() {\n  case ${ENABLE_IP_ALIASES} in\n    true) echo \"IP aliases are enabled. Creating subnetworks.\";;\n    false)\n      echo \"IP aliases are disabled.\"\n      if [[ \"${ENABLE_BIG_CLUSTER_SUBNETS}\" = \"true\" ]]; then\n        if [[  \"${PREEXISTING_NETWORK}\" != \"true\" ]]; then\n          expand-default-subnetwork\n        else\n          echo \"${color_yellow}Using pre-existing network ${NETWORK}, subnets won't be expanded to /19!${color_norm}\"\n        fi\n      elif [[ \"${CREATE_CUSTOM_NETWORK:-}\" == \"true\" && \"${PREEXISTING_NETWORK}\" != \"true\" ]]; then\n          gcloud compute networks subnets create \"${SUBNETWORK}\" --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" --network \"${NETWORK}\" --range \"${NODE_IP_RANGE}\"\n      fi\n      return;;\n    *) echo \"${color_red}Invalid argument to ENABLE_IP_ALIASES${color_norm}\"\n       exit 1;;\n  esac\n\n  # Look for the alias subnet, it must exist and have a secondary\n  # range configured.\n  local subnet\n  subnet=$(gcloud compute networks subnets describe \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --region \"${REGION}\" \\\n    \"${IP_ALIAS_SUBNETWORK}\" 2>/dev/null || true)\n  if [[ -z \"${subnet}\" ]]; then\n    echo \"Creating subnet ${NETWORK}:${IP_ALIAS_SUBNETWORK}\"\n    gcloud compute networks subnets create \\\n      \"${IP_ALIAS_SUBNETWORK}\" \\\n      --description \"Automatically generated subnet for ${INSTANCE_PREFIX} cluster. This will be removed on cluster teardown.\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --region \"${REGION}\" \\\n      --range \"${NODE_IP_RANGE}\" \\\n      --secondary-range \"pods-default=${CLUSTER_IP_RANGE}\" \\\n      --secondary-range \"services-default=${SERVICE_CLUSTER_IP_RANGE}\"\n    echo \"Created subnetwork ${IP_ALIAS_SUBNETWORK}\"\n  else\n    if ! echo \"${subnet}\" | grep --quiet secondaryIpRanges; then\n      echo \"${color_red}Subnet ${IP_ALIAS_SUBNETWORK} does not have a secondary range${color_norm}\"\n      exit 1\n    fi\n  fi\n}\n\n# detect-subnetworks sets the SUBNETWORK var if not already set\n# Assumed vars:\n#   NETWORK\n#   REGION\n#   NETWORK_PROJECT\n#\n# Optional vars:\n#   SUBNETWORK\n#   IP_ALIAS_SUBNETWORK\nfunction detect-subnetworks() {\n  if [[ -n ${SUBNETWORK:-} ]]; then\n    echo \"Using subnet ${SUBNETWORK}\"\n    return 0\n  fi\n\n  if [[ -n ${IP_ALIAS_SUBNETWORK:-} ]]; then\n    SUBNETWORK=${IP_ALIAS_SUBNETWORK}\n    echo \"Using IP Alias subnet ${SUBNETWORK}\"\n    return 0\n  fi\n\n  SUBNETWORK=$(gcloud compute networks subnets list \\\n    --network=\"${NETWORK}\" \\\n    --regions=\"${REGION}\" \\\n    --project=\"${NETWORK_PROJECT}\" \\\n    --limit=1 \\\n    --format='value(name)' 2>/dev/null)\n\n  if [[ -n ${SUBNETWORK:-} ]]; then\n    echo \"Found subnet for region ${REGION} in network ${NETWORK}: ${SUBNETWORK}\"\n    return 0\n  fi\n\n  echo \"${color_red}Could not find subnetwork with region ${REGION}, network ${NETWORK}, and project ${NETWORK_PROJECT}\"\n}\n\n# Sets up Cloud NAT for the network.\n# Assumed vars:\n#   NETWORK_PROJECT\n#   REGION\n#   NETWORK\nfunction create-cloud-nat-router() {\n  if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n    if gcloud compute routers describe \"$NETWORK-nat-router\" --project \"$NETWORK_PROJECT\" --region \"$REGION\" &>/dev/null; then\n      echo \"Cloud nat already exists\"\n      return 0\n    fi\n    gcloud compute routers create \"$NETWORK-nat-router\" \\\n      --project \"$NETWORK_PROJECT\" \\\n      --region \"$REGION\" \\\n      --network \"$NETWORK\"\n    gcloud compute routers nats create \"$NETWORK-nat-config\" \\\n      --project \"$NETWORK_PROJECT\" \\\n      --router-region \"$REGION\" \\\n      --router \"$NETWORK-nat-router\" \\\n      --nat-primary-subnet-ip-ranges \\\n      --auto-allocate-nat-external-ips \\\n      ${GCE_PRIVATE_CLUSTER_PORTS_PER_VM:+--min-ports-per-vm ${GCE_PRIVATE_CLUSTER_PORTS_PER_VM}}\n  fi\n}\n\nfunction delete-all-firewall-rules() {\n  if fws=$(gcloud compute firewall-rules list --project \"${NETWORK_PROJECT}\" --filter=\"network=${NETWORK}\" --format=\"value(name)\"); then\n    echo \"Deleting firewall rules remaining in network ${NETWORK}: ${fws}\"\n    delete-firewall-rules \"$fws\"\n  else\n    echo \"Failed to list firewall rules from the network ${NETWORK}\"\n  fi\n}\n\n# Ignores firewall rule arguments that do not exist in NETWORK_PROJECT.\nfunction delete-firewall-rules() {\n  for fw in \"$@\"; do\n    if [[ -n $(gcloud compute firewall-rules --project \"${NETWORK_PROJECT}\" describe \"${fw}\" --format='value(name)' 2>/dev/null || true) ]]; then\n      gcloud compute firewall-rules delete --project \"${NETWORK_PROJECT}\" --quiet \"${fw}\" &\n    fi\n  done\n  kube::util::wait-for-jobs || {\n    echo -e \"${color_red}Failed to delete firewall rules.${color_norm}\" >&2\n  }\n}\n\nfunction delete-network() {\n  if [[ -n $(gcloud compute networks --project \"${NETWORK_PROJECT}\" describe \"${NETWORK}\" --format='value(name)' 2>/dev/null || true) ]]; then\n    if ! gcloud compute networks delete --project \"${NETWORK_PROJECT}\" --quiet \"${NETWORK}\"; then\n      echo \"Failed to delete network '${NETWORK}'. Listing firewall-rules:\"\n      gcloud compute firewall-rules --project \"${NETWORK_PROJECT}\" list --filter=\"network=${NETWORK}\"\n      return 1\n    fi\n  fi\n}\n\nfunction delete-cloud-nat-router() {\n  if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n    if [[ -n $(gcloud compute routers describe --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" \"${NETWORK}-nat-router\" --format='value(name)' 2>/dev/null || true) ]]; then\n      echo \"Deleting Cloud NAT router...\"\n      gcloud compute routers delete --project \"${NETWORK_PROJECT}\" --region \"${REGION}\" --quiet \"${NETWORK}-nat-router\"\n    fi\n  fi\n}\n\nfunction delete-subnetworks() {\n  # If running in custom mode network we need to delete subnets manually.\n  mode=\"$(check-network-mode)\"\n  if [[ \"${mode}\" == \"CUSTOM\" ]]; then\n    if [[ \"${ENABLE_BIG_CLUSTER_SUBNETS}\" = \"true\" ]]; then\n      echo \"Deleting default subnets...\"\n      # This value should be kept in sync with number of regions.\n      local parallelism=9\n      gcloud compute networks subnets list --network=\"${NETWORK}\" --project \"${NETWORK_PROJECT}\" --format='value(region.basename())' | \\\n        xargs -i -P ${parallelism} gcloud --quiet compute networks subnets delete \"${NETWORK}\" --project \"${NETWORK_PROJECT}\" --region=\"{}\" || true\n    elif [[ \"${CREATE_CUSTOM_NETWORK:-}\" == \"true\" ]]; then\n      echo \"Deleting custom subnet...\"\n      gcloud --quiet compute networks subnets delete \"${SUBNETWORK}\" --project \"${NETWORK_PROJECT}\" --region=\"${REGION}\" || true\n    fi\n    return\n  fi\n\n  # If we reached here, it means we're not using custom network.\n  # So the only thing we need to check is if IP-aliases was turned\n  # on and we created a subnet for it. If so, we should delete it.\n  if [[ ${ENABLE_IP_ALIASES:-} == \"true\" ]]; then\n    # Only delete the subnet if we created it (i.e it's not pre-existing).\n    if [[ -z \"${KUBE_GCE_IP_ALIAS_SUBNETWORK:-}\" ]]; then\n      echo \"Removing auto-created subnet ${NETWORK}:${IP_ALIAS_SUBNETWORK}\"\n      if [[ -n $(gcloud compute networks subnets describe \\\n            --project \"${NETWORK_PROJECT}\" \\\n            --region \"${REGION}\" \\\n            \"${IP_ALIAS_SUBNETWORK}\" 2>/dev/null) ]]; then\n        gcloud --quiet compute networks subnets delete \\\n          --project \"${NETWORK_PROJECT}\" \\\n          --region \"${REGION}\" \\\n          \"${IP_ALIAS_SUBNETWORK}\"\n      fi\n    fi\n  fi\n}\n\n# Generates SSL certificates for etcd cluster peer to peer communication. Uses cfssl program.\n#\n# Assumed vars:\n#   KUBE_TEMP: temporary directory\n#\n# Args:\n#  $1: host name\n#  $2: CA certificate\n#  $3: CA key\n#\n# If CA cert/key is empty, the function will also generate certs for CA.\n#\n# Vars set:\n#   ETCD_CA_KEY_BASE64\n#   ETCD_CA_CERT_BASE64\n#   ETCD_PEER_KEY_BASE64\n#   ETCD_PEER_CERT_BASE64\n#\nfunction create-etcd-certs {\n  local host=${1}\n  local ca_cert=${2:-}\n  local ca_key=${3:-}\n\n  GEN_ETCD_CA_CERT=\"${ca_cert}\" GEN_ETCD_CA_KEY=\"${ca_key}\" \\\n    generate-etcd-cert \"${KUBE_TEMP}/cfssl\" \"${host}\" \"peer\" \"peer\"\n\n  pushd \"${KUBE_TEMP}/cfssl\"\n  ETCD_CA_KEY_BASE64=$(base64 \"ca-key.pem\" | tr -d '\\r\\n')\n  ETCD_CA_CERT_BASE64=$(gzip -c \"ca.pem\" | base64 | tr -d '\\r\\n')\n  ETCD_PEER_KEY_BASE64=$(base64 \"peer-key.pem\" | tr -d '\\r\\n')\n  ETCD_PEER_CERT_BASE64=$(gzip -c \"peer.pem\" | base64 | tr -d '\\r\\n')\n  popd\n}\n\n# Generates SSL certificates for etcd-client and kube-apiserver communication. Uses cfssl program.\n#\n# Assumed vars:\n#   KUBE_TEMP: temporary directory\n#\n# Args:\n#  $1: host server name\n#  $2: host client name\n#  $3: CA certificate\n#  $4: CA key\n#\n# If CA cert/key is empty, the function will also generate certs for CA.\n#\n# Vars set:\n#   ETCD_APISERVER_CA_KEY_BASE64\n#   ETCD_APISERVER_CA_CERT_BASE64\n#   ETCD_APISERVER_SERVER_KEY_BASE64\n#   ETCD_APISERVER_SERVER_CERT_BASE64\n#   ETCD_APISERVER_CLIENT_KEY_BASE64\n#   ETCD_APISERVER_CLIENT_CERT_BASE64\n#\nfunction create-etcd-apiserver-certs {\n  local hostServer=${1}\n  local hostClient=${2}\n  local etcd_apiserver_ca_cert=${3:-}\n  local etcd_apiserver_ca_key=${4:-}\n\n  GEN_ETCD_CA_CERT=\"${etcd_apiserver_ca_cert}\" GEN_ETCD_CA_KEY=\"${etcd_apiserver_ca_key}\" \\\n    generate-etcd-cert \"${KUBE_TEMP}/cfssl\" \"${hostServer}\" \"server\" \"etcd-apiserver-server\"\n    generate-etcd-cert \"${KUBE_TEMP}/cfssl\" \"${hostClient}\" \"client\" \"etcd-apiserver-client\"\n\n  pushd \"${KUBE_TEMP}/cfssl\"\n  ETCD_APISERVER_CA_KEY_BASE64=$(base64 \"ca-key.pem\" | tr -d '\\r\\n')\n  ETCD_APISERVER_CA_CERT_BASE64=$(gzip -c \"ca.pem\" | base64 | tr -d '\\r\\n')\n  ETCD_APISERVER_SERVER_KEY_BASE64=$(base64 \"etcd-apiserver-server-key.pem\" | tr -d '\\r\\n')\n  ETCD_APISERVER_SERVER_CERT_BASE64=$(gzip -c \"etcd-apiserver-server.pem\" | base64 | tr -d '\\r\\n')\n  ETCD_APISERVER_CLIENT_KEY_BASE64=$(base64 \"etcd-apiserver-client-key.pem\" | tr -d '\\r\\n')\n  ETCD_APISERVER_CLIENT_CERT_BASE64=$(gzip -c \"etcd-apiserver-client.pem\" | base64 | tr -d '\\r\\n')\n  popd\n}\n\n\nfunction create-master() {\n  echo \"Starting master and configuring firewalls\"\n  gcloud compute firewall-rules create \"${MASTER_NAME}-https\" \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --network \"${NETWORK}\" \\\n    --target-tags \"${MASTER_TAG}\" \\\n    --allow tcp:443 &\n\n  echo \"Configuring firewall for apiserver konnectivity server\"\n  if [[ \"${PREPARE_KONNECTIVITY_SERVICE:-false}\" == \"true\" ]]; then\n    gcloud compute firewall-rules create \"${MASTER_NAME}-konnectivity-server\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --target-tags \"${MASTER_TAG}\" \\\n      --allow tcp:8132 &\n  fi\n\n  # We have to make sure the disk is created before creating the master VM, so\n  # run this in the foreground.\n  gcloud compute disks create \"${MASTER_NAME}-pd\" \\\n    --project \"${PROJECT}\" \\\n    --zone \"${ZONE}\" \\\n    --type \"${MASTER_DISK_TYPE}\" \\\n    --size \"${MASTER_DISK_SIZE}\"\n\n  # Create rule for accessing and securing etcd servers.\n  if ! gcloud compute firewall-rules --project \"${NETWORK_PROJECT}\" describe \"${MASTER_NAME}-etcd\" &>/dev/null; then\n    gcloud compute firewall-rules create \"${MASTER_NAME}-etcd\" \\\n      --project \"${NETWORK_PROJECT}\" \\\n      --network \"${NETWORK}\" \\\n      --source-tags \"${MASTER_TAG}\" \\\n      --allow \"tcp:2380,tcp:2381\" \\\n      --target-tags \"${MASTER_TAG}\" &\n  fi\n\n  # Generate a bearer token for this cluster. We push this separately\n  # from the other cluster variables so that the client (this\n  # computer) can forget it later. This should disappear with\n  # http://issue.k8s.io/3168\n  KUBE_PROXY_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n  if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" ]]; then\n    NODE_PROBLEM_DETECTOR_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n  fi\n\n  # Reserve the master's IP so that it can later be transferred to another VM\n  # without disrupting the kubelets.\n  create-static-ip \"${MASTER_NAME}-ip\" \"${REGION}\"\n  MASTER_RESERVED_IP=$(gcloud compute addresses describe \"${MASTER_NAME}-ip\" \\\n    --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)')\n\n  if [[ \"${REGISTER_MASTER_KUBELET:-}\" == \"true\" ]]; then\n    KUBELET_APISERVER=\"${MASTER_RESERVED_IP}\"\n  fi\n\n  KUBERNETES_MASTER_NAME=\"${MASTER_RESERVED_IP}\"\n  MASTER_ADVERTISE_ADDRESS=\"${MASTER_RESERVED_IP}\"\n\n  MASTER_INTERNAL_IP=\"\"\n  if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n    gcloud compute addresses create \"${MASTER_NAME}-internal-ip\" --project \"${PROJECT}\" --region \"$REGION\" --subnet \"$SUBNETWORK\"\n    MASTER_INTERNAL_IP=$(gcloud compute addresses describe \"${MASTER_NAME}-internal-ip\" --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)')\n    echo \"Master internal ip is: $MASTER_INTERNAL_IP\"\n    KUBERNETES_MASTER_NAME=\"${MASTER_INTERNAL_IP}\"\n    MASTER_ADVERTISE_ADDRESS=\"${MASTER_INTERNAL_IP}\"\n  fi\n\n  create-certs \"${MASTER_RESERVED_IP}\" \"${MASTER_INTERNAL_IP}\"\n  create-etcd-certs \"${MASTER_NAME}\"\n  create-etcd-apiserver-certs \"etcd-${MASTER_NAME}\" \"${MASTER_NAME}\"\n\n  if [[ \"$(get-num-nodes)\" -ge \"50\" ]]; then\n    # We block on master creation for large clusters to avoid doing too much\n    # unnecessary work in case master start-up fails (like creation of nodes).\n    create-master-instance \"${MASTER_RESERVED_IP}\" \"${MASTER_INTERNAL_IP}\"\n  else\n    create-master-instance \"${MASTER_RESERVED_IP}\" \"${MASTER_INTERNAL_IP}\" &\n  fi\n\n}\n\n# Adds master replica to etcd cluster.\n#\n# Assumed vars:\n#   REPLICA_NAME\n#   PROJECT\n#   EXISTING_MASTER_NAME\n#   EXISTING_MASTER_ZONE\n#\n# $1: etcd client port\n# $2: etcd internal port\n# $3: whether etcd communication should use mtls\n# returns the result of ssh command which adds replica\nfunction add-replica-to-etcd() {\n  local -r client_port=\"${1}\"\n  local -r internal_port=\"${2}\"\n  local -r use_mtls=\"${3}\"\n\n  TLSARG=\"\"\n  PROTO=\"http://\"\n  if [[ \"${use_mtls}\" == \"true\" ]]; then\n    # Keep in sync with ETCD_APISERVER_CA_CERT_PATH, ETCD_APISERVER_CLIENT_CERT_PATH and ETCD_APISERVER_CLIENT_KEY_PATH in configure-helper.sh.\n    TLSARG=\"--cacert /etc/srv/kubernetes/pki/etcd-apiserver-ca.crt --cert /etc/srv/kubernetes/pki/etcd-apiserver-client.crt --key /etc/srv/kubernetes/pki/etcd-apiserver-client.key\"\n    PROTO=\"https://\"\n  fi\n  run-gcloud-command \"${EXISTING_MASTER_NAME}\" \"${EXISTING_MASTER_ZONE}\" \"curl ${TLSARG} ${PROTO}127.0.0.1:${client_port}/v2/members -XPOST -H \\\"Content-Type: application/json\\\" -d '{\\\"peerURLs\\\":[\\\"https://${REPLICA_NAME}:${internal_port}\\\"]}' -s\"\n  return $?\n}\n\n# Sets EXISTING_MASTER_NAME and EXISTING_MASTER_ZONE variables.\n#\n# Assumed vars:\n#   PROJECT\n#\n# NOTE: Must be in sync with get-replica-name-regexp\nfunction set-existing-master() {\n  local existing_master\n  existing_master=$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter \"name ~ '$(get-replica-name-regexp)'\" \\\n    --format \"value(name,zone)\" | head -n1)\n  EXISTING_MASTER_NAME=\"$(echo \"${existing_master}\" | cut -f1)\"\n  EXISTING_MASTER_ZONE=\"$(echo \"${existing_master}\" | cut -f2)\"\n}\n\nfunction replicate-master() {\n  set-replica-name\n  set-existing-master\n\n  echo \"Experimental: replicating existing master ${EXISTING_MASTER_ZONE}/${EXISTING_MASTER_NAME} as ${ZONE}/${REPLICA_NAME}\"\n\n  # Before we do anything else, we should configure etcd to expect more replicas.\n  if ! add-replica-to-etcd 2379 2380 true; then\n    echo \"Failed to add master replica to etcd cluster.\"\n    return 1\n  fi\n  if ! add-replica-to-etcd 4002 2381 false; then\n    echo \"Failed to add master replica to etcd events cluster.\"\n    return 1\n  fi\n\n  # We have to make sure the disk is created before creating the master VM, so\n  # run this in the foreground.\n  gcloud compute disks create \"${REPLICA_NAME}-pd\" \\\n    --project \"${PROJECT}\" \\\n    --zone \"${ZONE}\" \\\n    --type \"${MASTER_DISK_TYPE}\" \\\n    --size \"${MASTER_DISK_SIZE}\"\n\n  local existing_master_replicas\n  existing_master_replicas=\"$(get-all-replica-names)\"\n  replicate-master-instance \"${EXISTING_MASTER_ZONE}\" \"${EXISTING_MASTER_NAME}\" \"${existing_master_replicas}\"\n\n  # Add new replica to the load balancer.\n  gcloud compute target-pools add-instances \"${MASTER_NAME}\" \\\n    --project \"${PROJECT}\" \\\n    --zone \"${ZONE}\" \\\n    --instances \"${REPLICA_NAME}\"\n\n  if [[ \"${GCE_PRIVATE_CLUSTER:-}\" == \"true\" ]]; then\n    add-to-internal-loadbalancer \"${REPLICA_NAME}\" \"${ZONE}\"\n  fi\n}\n\n# Detaches old and ataches new external IP to a VM.\n#\n# Arguments:\n#   $1 - VM name\n#   $2 - VM zone\n#   $3 - external static IP; if empty will use an ephemeral IP address.\nfunction attach-external-ip() {\n  local NAME=${1}\n  local ZONE=${2}\n  local IP_ADDR=${3:-}\n  local ACCESS_CONFIG_NAME\n  ACCESS_CONFIG_NAME=$(gcloud compute instances describe \"${NAME}\" \\\n    --project \"${PROJECT}\" --zone \"${ZONE}\" \\\n    --format=\"value(networkInterfaces[0].accessConfigs[0].name)\")\n  gcloud compute instances delete-access-config \"${NAME}\" \\\n    --project \"${PROJECT}\" --zone \"${ZONE}\" \\\n    --access-config-name \"${ACCESS_CONFIG_NAME}\"\n  if [[ -z \"${IP_ADDR}\" ]]; then\n    gcloud compute instances add-access-config \"${NAME}\" \\\n      --project \"${PROJECT}\" --zone \"${ZONE}\" \\\n      --access-config-name \"${ACCESS_CONFIG_NAME}\"\n  else\n    gcloud compute instances add-access-config \"${NAME}\" \\\n      --project \"${PROJECT}\" --zone \"${ZONE}\" \\\n      --access-config-name \"${ACCESS_CONFIG_NAME}\" \\\n      --address \"${IP_ADDR}\"\n  fi\n}\n\n# Creates load balancer in front of apiserver if it doesn't exists already. Assumes there's only one\n# existing master replica.\n#\n# Assumes:\n#   PROJECT\n#   MASTER_NAME\n#   ZONE\n#   REGION\nfunction create-loadbalancer() {\n  # Step 0: Return early if LB is already configured.\n  if gcloud compute forwarding-rules describe \"${MASTER_NAME}\" \\\n    --project \"${PROJECT}\" --region \"${REGION}\" > /dev/null 2>&1; then\n    echo \"Load balancer already exists\"\n    return\n  fi\n\n  local EXISTING_MASTER_NAME\n  local EXISTING_MASTER_ZONE\n  EXISTING_MASTER_NAME=\"$(get-all-replica-names)\"\n  EXISTING_MASTER_ZONE=$(gcloud compute instances list \"${EXISTING_MASTER_NAME}\" \\\n    --project \"${PROJECT}\" --format='value(zone)')\n\n  echo \"Creating load balancer in front of an already existing master in ${EXISTING_MASTER_ZONE}\"\n\n  # Step 1: Detach master IP address and attach ephemeral address to the existing master\n  attach-external-ip \"${EXISTING_MASTER_NAME}\" \"${EXISTING_MASTER_ZONE}\"\n\n  # Step 2: Create target pool.\n  gcloud compute target-pools create \"${MASTER_NAME}\" --project \"${PROJECT}\" --region \"${REGION}\"\n  # TODO: We should also add master instances with suffixes\n  gcloud compute target-pools add-instances \"${MASTER_NAME}\" --instances \"${EXISTING_MASTER_NAME}\" --project \"${PROJECT}\" --zone \"${EXISTING_MASTER_ZONE}\"\n\n  # Step 3: Create forwarding rule.\n  # TODO: This step can take up to 20 min. We need to speed this up...\n  gcloud compute forwarding-rules create \"${MASTER_NAME}\" \\\n    --project \"${PROJECT}\" --region \"${REGION}\" \\\n    --target-pool \"${MASTER_NAME}\" --address=\"${KUBE_MASTER_IP}\" --ports=443\n\n  echo -n \"Waiting for the load balancer configuration to propagate...\"\n  local counter=0\n  until curl -k -m1 \"https://${KUBE_MASTER_IP}\" &> /dev/null; do\n    counter=$((counter+1))\n    echo -n .\n    if [[ ${counter} -ge 1800 ]]; then\n      echo -e \"${color_red}TIMEOUT${color_norm}\" >&2\n      echo -e \"${color_red}Load balancer failed to initialize within ${counter} seconds.${color_norm}\" >&2\n      exit 2\n    fi\n  done\n  echo \"DONE\"\n}\n\n\n# attach-internal-master-ip attach internal ip to existing master.\n#\n# Assumes:\n# * PROJECT\nfunction attach-internal-master-ip() {\n  local name=\"${1}\"\n  local zone=\"${2}\"\n  local ip=\"${3}\"\n\n  local aliases\n  aliases=$(gcloud compute instances describe \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --flatten='networkInterfaces[0].aliasIpRanges[]' --format='value[separator=':'](networkInterfaces[0].aliasIpRanges.subnetworkRangeName,networkInterfaces[0].aliasIpRanges.ipCidrRange)' | sed 's/^://' | paste -s -d';' -)\n  aliases=\"${aliases:+${aliases};}${ip}/32\"\n  echo \"Setting ${name}'s aliases to '${aliases}' (added ${ip})\"\n  # Attach ${ip} to ${name}\n  gcloud compute instances network-interfaces update \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --aliases=\"${aliases}\"\n  gcloud compute instances add-metadata \"${name}\" --zone \"${zone}\" --metadata=kube-master-internal-ip=\"${ip}\"\n  run-gcloud-command \"${name}\" \"${zone}\" 'sudo /bin/bash /home/kubernetes/bin/kube-master-internal-route.sh' || true\n  return $?\n}\n\n\n# detach-internal-master-ip detaches internal ip from existing master.\n#\n# Assumes:\n# * PROJECT\nfunction detach-internal-master-ip() {\n  local name=\"${1}\"\n  local zone=\"${2}\"\n  local ip=\"${3}\"\n\n  local aliases\n  aliases=$(gcloud compute instances describe \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --flatten='networkInterfaces[0].aliasIpRanges[]' --format='value[separator=':'](networkInterfaces[0].aliasIpRanges.subnetworkRangeName,networkInterfaces[0].aliasIpRanges.ipCidrRange)' | sed 's/^://' | grep -v \"${ip}\" | paste -s -d';' -)\n  echo \"Setting ${name}'s aliases to '${aliases}' (removed ${ip})\"\n  # Detach ${MASTER_NAME}-internal-ip from ${name}\n  gcloud compute instances network-interfaces update \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --aliases=\"${aliases}\"\n  gcloud compute instances remove-metadata \"${name}\" --zone \"${zone}\" --keys=kube-master-internal-ip\n  # We want `ip route` to be run in the cloud and not this host\n  run-gcloud-command \"${name}\" \"${zone}\" \"sudo ip route del to local ${ip}/32 dev \\$(ip route | grep default | while read -r _ _ _ _ dev _; do echo \\$dev; done)\" || true\n  return $?\n}\n\n# create-internal-loadbalancer creates an internal load balacer in front of existing master.\n#\n# Assumes:\n# * MASTER_NAME\n# * PROJECT\n# * REGION\nfunction create-internal-loadbalancer() {\n  if gcloud compute forwarding-rules describe \"${MASTER_NAME}-internal\" \\\n    --project \"${PROJECT}\" --region \"${REGION}\" > /dev/null 2>&1; then\n    echo \"Load balancer already exists\"\n    return\n  fi\n\n  local EXISTING_MASTER_NAME\n  local EXISTING_MASTER_ZONE\n  EXISTING_MASTER_NAME=\"$(get-all-replica-names)\"\n  EXISTING_MASTER_ZONE=$(gcloud compute instances list \"${EXISTING_MASTER_NAME}\" \\\n    --project \"${PROJECT}\" --format='value(zone)')\n\n  echo \"Detaching ${KUBE_MASTER_INTERNAL_IP} from ${EXISTING_MASTER_NAME}/${EXISTING_MASTER_ZONE}\"\n  detach-internal-master-ip \"${EXISTING_MASTER_NAME}\" \"${EXISTING_MASTER_ZONE}\" \"${KUBE_MASTER_INTERNAL_IP}\"\n\n  echo \"Creating internal load balancer with IP: ${KUBE_MASTER_INTERNAL_IP}\"\n  gcloud compute health-checks --project \"${PROJECT}\" create tcp \"${MASTER_NAME}-hc\" --port=443\n\n  gcloud compute backend-services create \"${MASTER_NAME}\" \\\n    --project \"${PROJECT}\" \\\n    --region \"${REGION}\" \\\n    --protocol tcp \\\n    --region \"${REGION}\" \\\n    --load-balancing-scheme internal \\\n    --health-checks \"${MASTER_NAME}-hc\"\n\n  gcloud compute forwarding-rules create \"${MASTER_NAME}-internal\" \\\n    --project \"${PROJECT}\" \\\n    --region \"${REGION}\" \\\n    --load-balancing-scheme internal \\\n    --network \"${NETWORK}\" \\\n    --subnet \"${SUBNETWORK}\" \\\n    --address \"${KUBE_MASTER_INTERNAL_IP}\" \\\n    --ip-protocol TCP \\\n    --ports 443 \\\n    --backend-service \"${MASTER_NAME}\" \\\n    --backend-service-region \"${REGION}\"\n\n  echo \"Adding ${EXISTING_MASTER_NAME}/${EXISTING_MASTER_ZONE} to the load balancer\"\n  add-to-internal-loadbalancer \"${EXISTING_MASTER_NAME}\" \"${EXISTING_MASTER_ZONE}\"\n}\n\n# add-to-internal-loadbalancer adds an instance to ILB.\n# Assumes:\n# * MASTER_NAME\n# * PROJECT\n# * REGION\nfunction add-to-internal-loadbalancer() {\n  local name=\"${1}\"\n  local zone=\"${2}\"\n\n  gcloud compute instance-groups unmanaged create \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\"\n  gcloud compute instance-groups unmanaged add-instances \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --instances \"${name}\"\n  gcloud compute backend-services add-backend \"${MASTER_NAME}\" \\\n    --project \"${PROJECT}\" \\\n    --region \"${REGION}\" \\\n    --instance-group \"${name}\" \\\n    --instance-group-zone \"${zone}\"\n}\n\n# remove-from-internal-loadbalancer removes an instance from ILB.\n# Assumes:\n# * MASTER_NAME\n# * PROJECT\n# * REGION\nfunction remove-from-internal-loadbalancer() {\n  local name=\"${1}\"\n  local zone=\"${2}\"\n\n  if gcloud compute instance-groups unmanaged describe \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" &>/dev/null; then\n    gcloud compute backend-services remove-backend \"${MASTER_NAME}\" \\\n          --project \"${PROJECT}\" \\\n          --region \"${REGION}\" \\\n          --instance-group \"${name}\" \\\n          --instance-group-zone \"${zone}\"\n    gcloud compute instance-groups unmanaged delete \"${name}\" --project \"${PROJECT}\" --zone \"${zone}\" --quiet\n  fi\n}\n\nfunction delete-internal-loadbalancer() {\n  if gcloud compute forwarding-rules describe \"${MASTER_NAME}-internal\" --project \"${PROJECT}\" --region \"${REGION}\" &>/dev/null; then\n    gcloud compute forwarding-rules delete \"${MASTER_NAME}-internal\" --project \"${PROJECT}\" --region \"${REGION}\" --quiet\n  fi\n\n  if gcloud compute backend-services describe \"${MASTER_NAME}\" --project \"${PROJECT}\" --region \"${REGION}\" &>/dev/null; then\n    gcloud compute backend-services delete \"${MASTER_NAME}\" --project \"${PROJECT}\" --region \"${REGION}\" --quiet\n  fi\n  if gcloud compute health-checks describe \"${MASTER_NAME}-gc\" --project \"${PROJECT}\" &>/dev/null; then\n    gcloud compute health-checks delete \"${MASTER_NAME}-gc\" --project \"${PROJECT}\" --quiet\n  fi\n}\n\nfunction create-nodes-firewall() {\n  # Create a single firewall rule for all minions.\n  create-firewall-rule \"${NODE_TAG}-all\" \"${CLUSTER_IP_RANGE}\" \"${NODE_TAG}\" &\n\n  # Report logging choice (if any).\n  if [[ \"${ENABLE_NODE_LOGGING-}\" == \"true\" ]]; then\n    echo \"+++ Logging using Fluentd to ${LOGGING_DESTINATION:-unknown}\"\n  fi\n\n  # Wait for last batch of jobs\n  kube::util::wait-for-jobs || {\n    echo -e \"${color_red}Some commands failed.${color_norm}\" >&2\n  }\n}\n\nfunction get-scope-flags() {\n  local scope_flags=\n  if [[ -n \"${NODE_SCOPES}\" ]]; then\n    scope_flags=\"--scopes ${NODE_SCOPES}\"\n  else\n    scope_flags=\"--no-scopes\"\n  fi\n  echo \"${scope_flags}\"\n}\n\nfunction create-nodes-template() {\n  echo \"Creating nodes.\"\n\n  local scope_flags\n  scope_flags=$(get-scope-flags)\n\n  write-linux-node-env\n  write-windows-node-env\n\n  # NOTE: these template names and their format must match\n  # create-[linux,windows]-nodes() as well as get-template()!\n  local linux_template_name=\"${NODE_INSTANCE_PREFIX}-template\"\n  local windows_template_name=\"${WINDOWS_NODE_INSTANCE_PREFIX}-template\"\n  create-linux-node-instance-template \"$linux_template_name\"\n  create-windows-node-instance-template \"$windows_template_name\" \"${scope_flags[*]}\"\n  if [[ -n \"${ADDITIONAL_MACHINE_TYPE:-}\" ]]; then\n    local linux_extra_template_name=\"${NODE_INSTANCE_PREFIX}-extra-template\"\n    create-linux-node-instance-template \"$linux_extra_template_name\" \"${ADDITIONAL_MACHINE_TYPE}\"\n  fi\n}\n\n# Assumes:\n# - MAX_INSTANCES_PER_MIG\n# - NUM_NODES\n# - NUM_WINDOWS_NODES\n# exports:\n# - NUM_MIGS\n# - NUM_WINDOWS_MIGS\nfunction set_num_migs() {\n  local defaulted_max_instances_per_mig=${MAX_INSTANCES_PER_MIG:-1000}\n\n  if [[ ${defaulted_max_instances_per_mig} -le \"0\" ]]; then\n    echo \"MAX_INSTANCES_PER_MIG cannot be negative. Assuming default 1000\"\n    defaulted_max_instances_per_mig=1000\n  fi\n  export NUM_MIGS=$(((NUM_NODES + defaulted_max_instances_per_mig - 1) / defaulted_max_instances_per_mig))\n  export NUM_WINDOWS_MIGS=$(((NUM_WINDOWS_NODES + defaulted_max_instances_per_mig - 1) / defaulted_max_instances_per_mig))\n}\n\n# Assumes:\n# - NUM_MIGS\n# - NODE_INSTANCE_PREFIX\n# - NUM_NODES\n# - PROJECT\n# - ZONE\nfunction create-linux-nodes() {\n  local template_name=\"${NODE_INSTANCE_PREFIX}-template\"\n  local extra_template_name=\"${NODE_INSTANCE_PREFIX}-extra-template\"\n\n  local nodes=\"${NUM_NODES}\"\n  if [[ -n \"${HEAPSTER_MACHINE_TYPE:-}\" ]]; then\n    echo \"Creating a special node for heapster with machine-type ${HEAPSTER_MACHINE_TYPE}\"\n    create-heapster-node\n    nodes=$(( nodes - 1 ))\n  fi\n\n  if [[ -n \"${ADDITIONAL_MACHINE_TYPE:-}\" && \"${NUM_ADDITIONAL_NODES:-}\" -gt 0 ]]; then\n    local num_additional=\"${NUM_ADDITIONAL_NODES}\"\n    if [[ \"${NUM_ADDITIONAL_NODES:-}\" -gt \"${nodes}\" ]]; then\n      echo \"Capping NUM_ADDITIONAL_NODES to ${nodes}\"\n      num_additional=\"${nodes}\"\n    fi\n    if [[ \"${num_additional:-}\" -gt 0 ]]; then\n      echo \"Creating ${num_additional} special nodes with machine-type ${ADDITIONAL_MACHINE_TYPE}\"\n      local extra_group_name=\"${NODE_INSTANCE_PREFIX}-extra\"\n      gcloud compute instance-groups managed \\\n          create \"${extra_group_name}\" \\\n          --project \"${PROJECT}\" \\\n          --zone \"${ZONE}\" \\\n          --base-instance-name \"${extra_group_name}\" \\\n          --size \"${num_additional}\" \\\n          --template \"${extra_template_name}\" || true;\n      gcloud compute instance-groups managed wait-until --stable \\\n          \"${extra_group_name}\" \\\n          --zone \"${ZONE}\" \\\n          --project \"${PROJECT}\" \\\n          --timeout \"${MIG_WAIT_UNTIL_STABLE_TIMEOUT}\" || true\n      nodes=$(( nodes - num_additional ))\n    fi\n  fi\n\n  local instances_left=${nodes}\n\n  for ((i=1; i<=NUM_MIGS; i++)); do\n    local group_name=\"${NODE_INSTANCE_PREFIX}-group-$i\"\n    if [[ $i -eq ${NUM_MIGS} ]]; then\n      # TODO: We don't add a suffix for the last group to keep backward compatibility when there's only one MIG.\n      # We should change it at some point, but note #18545 when changing this.\n      group_name=\"${NODE_INSTANCE_PREFIX}-group\"\n    fi\n    # Spread the remaining number of nodes evenly\n    this_mig_size=$((instances_left / (NUM_MIGS - i + 1)))\n    instances_left=$((instances_left - this_mig_size))\n\n    # Run instance-groups creation in parallel.\n    {\n      gcloud compute instance-groups managed \\\n          create \"${group_name}\" \\\n          --project \"${PROJECT}\" \\\n          --zone \"${ZONE}\" \\\n          --base-instance-name \"${group_name}\" \\\n          --size \"${this_mig_size}\" \\\n          --template \"${template_name}\" || true;\n      gcloud compute instance-groups managed wait-until --stable \\\n          \"${group_name}\" \\\n          --zone \"${ZONE}\" \\\n          --project \"${PROJECT}\" \\\n          --timeout \"${MIG_WAIT_UNTIL_STABLE_TIMEOUT}\" || true\n    } &\n  done\n  wait\n}\n\n# Assumes:\n# - NUM_WINDOWS_MIGS\n# - WINDOWS_NODE_INSTANCE_PREFIX\n# - NUM_WINDOWS_NODES\n# - PROJECT\n# - ZONE\nfunction create-windows-nodes() {\n  local template_name=\"${WINDOWS_NODE_INSTANCE_PREFIX}-template\"\n\n  local -r nodes=\"${NUM_WINDOWS_NODES}\"\n  local instances_left=${nodes}\n\n  for ((i=1; i <= NUM_WINDOWS_MIGS; i++)); do\n    local group_name=\"${WINDOWS_NODE_INSTANCE_PREFIX}-group-$i\"\n    if [[ $i -eq ${NUM_WINDOWS_MIGS} ]]; then\n      # TODO: We don't add a suffix for the last group to keep backward compatibility when there's only one MIG.\n      # We should change it at some point, but note #18545 when changing this.\n      group_name=\"${WINDOWS_NODE_INSTANCE_PREFIX}-group\"\n    fi\n    # Spread the remaining number of nodes evenly\n    this_mig_size=$((instances_left / (NUM_WINDOWS_MIGS - i + 1)))\n    instances_left=$((instances_left - this_mig_size))\n\n    gcloud compute instance-groups managed \\\n        create \"${group_name}\" \\\n        --project \"${PROJECT}\" \\\n        --zone \"${ZONE}\" \\\n        --base-instance-name \"${group_name}\" \\\n        --size \"${this_mig_size}\" \\\n        --template \"${template_name}\" || true;\n    gcloud compute instance-groups managed wait-until --stable \\\n        \"${group_name}\" \\\n        --zone \"${ZONE}\" \\\n        --project \"${PROJECT}\" \\\n        --timeout \"${MIG_WAIT_UNTIL_STABLE_TIMEOUT}\" || true;\n  done\n}\n\n# Assumes:\n# - NODE_INSTANCE_PREFIX\n# - PROJECT\n# - NETWORK_PROJECT\n# - REGION\n# - ZONE\n# - HEAPSTER_MACHINE_TYPE\n# - NODE_DISK_TYPE\n# - NODE_DISK_SIZE\n# - NODE_IMAGE_PROJECT\n# - NODE_IMAGE\n# - NODE_SERVICE_ACCOUNT\n# - NODE_TAG\n# - NETWORK\n# - ENABLE_IP_ALIASES\n# - SUBNETWORK\n# - IP_ALIAS_SIZE\nfunction create-heapster-node() {\n  local gcloud=\"gcloud\"\n\n  local network\n  network=$(make-gcloud-network-argument \\\n      \"${NETWORK_PROJECT}\" \\\n      \"${REGION}\" \\\n      \"${NETWORK}\" \\\n      \"${SUBNETWORK:-}\" \\\n      \"\" \\\n      \"${ENABLE_IP_ALIASES:-}\" \\\n      \"${IP_ALIAS_SIZE:-}\")\n\n  # Deliberately word split ${network} and $(get-scope-flags)\n  # shellcheck disable=SC2086 disable=SC2046\n  ${gcloud} compute instances \\\n      create \"${NODE_INSTANCE_PREFIX}-heapster\" \\\n      --project \"${PROJECT}\" \\\n      --zone \"${ZONE}\" \\\n      --machine-type=\"${HEAPSTER_MACHINE_TYPE}\" \\\n      --boot-disk-type \"${NODE_DISK_TYPE}\" \\\n      --boot-disk-size \"${NODE_DISK_SIZE}\" \\\n      --image-project=\"${NODE_IMAGE_PROJECT}\" \\\n      --image \"${NODE_IMAGE}\" \\\n      --service-account \"${NODE_SERVICE_ACCOUNT}\" \\\n      --tags \"${NODE_TAG}\" \\\n      ${network} \\\n      $(get-scope-flags) \\\n      --metadata-from-file \"$(get-node-instance-metadata-from-file \"heapster-kube-env\")\"\n}\n\n# Assumes:\n# - NUM_MIGS\n# - NODE_INSTANCE_PREFIX\n# - PROJECT\n# - ZONE\n# - AUTOSCALER_MAX_NODES\n# - AUTOSCALER_MIN_NODES\n# Exports\n# - AUTOSCALER_MIG_CONFIG\nfunction create-cluster-autoscaler-mig-config() {\n\n  # Each MIG must have at least one node, so the min number of nodes\n  # must be greater or equal to the number of migs.\n  if [[ ${AUTOSCALER_MIN_NODES} -lt 0 ]]; then\n    echo \"AUTOSCALER_MIN_NODES must be greater or equal 0\"\n    exit 2\n  fi\n\n  # Each MIG must have at least one node, so the min number of nodes\n  # must be greater or equal to the number of migs.\n  if [[ ${AUTOSCALER_MAX_NODES} -lt ${NUM_MIGS} ]]; then\n    echo \"AUTOSCALER_MAX_NODES must be greater or equal ${NUM_MIGS}\"\n    exit 2\n  fi\n  if [[ ${NUM_WINDOWS_MIGS} -gt 0 ]]; then\n    # TODO(pjh): implement Windows support in this function.\n    echo \"Not implemented yet: autoscaler config for Windows MIGs\"\n    exit 2\n  fi\n\n  # The code assumes that the migs were created with create-nodes\n  # function which tries to evenly spread nodes across the migs.\n  AUTOSCALER_MIG_CONFIG=\"\"\n\n  local left_min=${AUTOSCALER_MIN_NODES}\n  local left_max=${AUTOSCALER_MAX_NODES}\n\n  for ((i=1; i <= NUM_MIGS; i++)); do\n    local group_name=\"${NODE_INSTANCE_PREFIX}-group-$i\"\n    if [[ $i -eq ${NUM_MIGS} ]]; then\n      # TODO: We don't add a suffix for the last group to keep backward compatibility when there's only one MIG.\n      # We should change it at some point, but note #18545 when changing this.\n      group_name=\"${NODE_INSTANCE_PREFIX}-group\"\n    fi\n\n    this_mig_min=$((left_min/(NUM_MIGS-i+1)))\n    this_mig_max=$((left_max/(NUM_MIGS-i+1)))\n    left_min=$((left_min-this_mig_min))\n    left_max=$((left_max-this_mig_max))\n\n    local mig_url=\"https://www.googleapis.com/compute/v1/projects/${PROJECT}/zones/${ZONE}/instanceGroups/${group_name}\"\n    AUTOSCALER_MIG_CONFIG=\"${AUTOSCALER_MIG_CONFIG} --nodes=${this_mig_min}:${this_mig_max}:${mig_url}\"\n  done\n\n  AUTOSCALER_MIG_CONFIG=\"${AUTOSCALER_MIG_CONFIG} --scale-down-enabled=${AUTOSCALER_ENABLE_SCALE_DOWN}\"\n}\n\n# Assumes:\n# - NUM_MIGS\n# - NODE_INSTANCE_PREFIX\n# - PROJECT\n# - ZONE\n# - ENABLE_CLUSTER_AUTOSCALER\n# - AUTOSCALER_MAX_NODES\n# - AUTOSCALER_MIN_NODES\nfunction create-autoscaler-config() {\n  # Create autoscaler for nodes configuration if requested\n  if [[ \"${ENABLE_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n    create-cluster-autoscaler-mig-config\n    echo \"Using autoscaler config: ${AUTOSCALER_MIG_CONFIG} ${AUTOSCALER_EXPANDER_CONFIG}\"\n  fi\n}\n\nfunction check-cluster() {\n  detect-node-names\n  detect-master\n\n  echo \"Waiting up to ${KUBE_CLUSTER_INITIALIZATION_TIMEOUT} seconds for cluster initialization.\"\n  echo\n  echo \"  This will continually check to see if the API for kubernetes is reachable.\"\n  echo \"  This may time out if there was some uncaught error during start up.\"\n  echo\n\n  # curl in mavericks is borked.\n  secure=\"\"\n  if which sw_vers >& /dev/null; then\n    if [[ $(sw_vers | grep ProductVersion | awk '{print $2}') = \"10.9.\"* ]]; then\n      secure=\"--insecure\"\n    fi\n  fi\n\n  local start_time\n  local curl_out\n  start_time=$(date +%s)\n  curl_out=$(mktemp)\n  kube::util::trap_add \"rm -f ${curl_out}\" EXIT\n  until curl -vsS --cacert \"${CERT_DIR}/pki/ca.crt\" \\\n          -H \"Authorization: Bearer ${KUBE_BEARER_TOKEN}\" \\\n          ${secure} \\\n          --max-time 5 --fail \\\n          \"https://${KUBE_MASTER_IP}/api/v1/pods?limit=100\" > \"${curl_out}\" 2>&1; do\n      local elapsed\n      elapsed=$(($(date +%s) - start_time))\n      if [[ ${elapsed} -gt ${KUBE_CLUSTER_INITIALIZATION_TIMEOUT} ]]; then\n          echo -e \"${color_red}Cluster failed to initialize within ${KUBE_CLUSTER_INITIALIZATION_TIMEOUT} seconds.${color_norm}\" >&2\n          echo \"Last output from querying API server follows:\" >&2\n          echo \"-----------------------------------------------------\" >&2\n          cat \"${curl_out}\" >&2\n          echo \"-----------------------------------------------------\" >&2\n          exit 2\n      fi\n      printf \".\"\n      sleep 2\n  done\n\n  echo \"Kubernetes cluster created.\"\n\n  export KUBE_CERT=\"${CERT_DIR}/pki/issued/kubecfg.crt\"\n  export KUBE_KEY=\"${CERT_DIR}/pki/private/kubecfg.key\"\n  export CA_CERT=\"${CERT_DIR}/pki/ca.crt\"\n  export CONTEXT=\"${PROJECT}_${INSTANCE_PREFIX}\"\n  (\n   umask 077\n\n   # Update the user's kubeconfig to include credentials for this apiserver.\n   create-kubeconfig\n  )\n\n  # ensures KUBECONFIG is set\n  get-kubeconfig-basicauth\n\n  if [[ ${GCE_UPLOAD_KUBCONFIG_TO_MASTER_METADATA:-} == \"true\" ]]; then\n    gcloud compute instances add-metadata \"${MASTER_NAME}\" --project=\"${PROJECT}\" --zone=\"${ZONE}\"  --metadata-from-file=\"kubeconfig=${KUBECONFIG}\" || true\n  fi\n\n  echo\n  echo -e \"${color_green:-}Kubernetes cluster is running.  The master is running at:\"\n  echo\n  echo -e \"${color_yellow}  https://${KUBE_MASTER_IP}\"\n  echo\n  echo -e \"${color_green}The user name and password to use is located in ${KUBECONFIG}.${color_norm}\"\n  echo\n\n}\n\n# Removes master replica from etcd cluster.\n#\n# Assumed vars:\n#   REPLICA_NAME\n#   PROJECT\n#   EXISTING_MASTER_NAME\n#   EXISTING_MASTER_ZONE\n#\n# $1: etcd client port\n# $2: whether etcd communication should use mtls\n# returns the result of ssh command which removes replica\nfunction remove-replica-from-etcd() {\n  local -r port=\"${1}\"\n  local -r use_mtls=\"${2}\"\n\n  TLSARG=\"\"\n  PROTO=\"http://\"\n  if [[ \"${use_mtls}\" == \"true\" ]]; then\n    # Keep in sync with ETCD_APISERVER_CA_CERT_PATH, ETCD_APISERVER_CLIENT_CERT_PATH and ETCD_APISERVER_CLIENT_KEY_PATH in configure-helper.sh.\n    TLSARG=\"--cacert /etc/srv/kubernetes/pki/etcd-apiserver-ca.crt --cert /etc/srv/kubernetes/pki/etcd-apiserver-client.crt --key /etc/srv/kubernetes/pki/etcd-apiserver-client.key\"\n    PROTO=\"https://\"\n  fi\n  [[ -n \"${EXISTING_MASTER_NAME}\" ]] || return\n  run-gcloud-command \"${EXISTING_MASTER_NAME}\" \"${EXISTING_MASTER_ZONE}\" \"curl -s ${TLSARG} ${PROTO}127.0.0.1:${port}/v2/members/\\$(curl -s ${TLSARG} ${PROTO}127.0.0.1:${port}/v2/members -XGET | sed 's/{\\\\\\\"id/\\n/g' | grep ${REPLICA_NAME}\\\\\\\" | cut -f 3 -d \\\\\\\") -XDELETE -L 2>/dev/null\"\n  local -r res=$?\n  echo \"Removing etcd replica, name: ${REPLICA_NAME}, port: ${port}, result: ${res}\"\n  return \"${res}\"\n}\n\n# Delete a kubernetes cluster. This is called from test-teardown.\n#\n# Assumed vars:\n#   MASTER_NAME\n#   NODE_INSTANCE_PREFIX\n#   WINDOWS_NODE_INSTANCE_PREFIX\n#   ZONE\n# This function tears down cluster resources 10 at a time to avoid issuing too many\n# API calls and exceeding API quota. It is important to bring down the instances before bringing\n# down the firewall rules and routes.\nfunction kube-down() {\n  local -r batch=200\n\n  detect-project\n  detect-node-names # For INSTANCE_GROUPS and WINDOWS_INSTANCE_GROUPS\n\n  echo \"Bringing down cluster\"\n  set +e  # Do not stop on error\n\n  if [[ \"${KUBE_DELETE_NODES:-}\" != \"false\" ]]; then\n    # Get the name of the managed instance group template before we delete the\n    # managed instance group. (The name of the managed instance group template may\n    # change during a cluster upgrade.)\n    local templates\n    templates=$(get-template \"${PROJECT}\")\n\n    # Deliberately allow globbing, do not change unless a bug is found\n    # shellcheck disable=SC2206\n    local all_instance_groups=(${INSTANCE_GROUPS[@]:-} ${WINDOWS_INSTANCE_GROUPS[@]:-})\n    # Deliberately do not quote, do not change unless a bug is found\n    # shellcheck disable=SC2068\n    for group in ${all_instance_groups[@]:-}; do\n      {\n        if gcloud compute instance-groups managed describe \"${group}\" --project \"${PROJECT}\" --zone \"${ZONE}\" &>/dev/null; then\n          gcloud compute instance-groups managed delete \\\n            --project \"${PROJECT}\" \\\n            --quiet \\\n            --zone \"${ZONE}\" \\\n            \"${group}\"\n        fi\n      } &\n    done\n\n    # Wait for last batch of jobs\n    kube::util::wait-for-jobs || {\n      echo -e \"Failed to delete instance group(s).\" >&2\n    }\n\n    # Deliberately do not quote, do not change unless a bug is found\n    # shellcheck disable=SC2068\n    for template in ${templates[@]:-}; do\n      {\n        if gcloud compute instance-templates describe --project \"${PROJECT}\" \"${template}\" &>/dev/null; then\n          gcloud compute instance-templates delete \\\n            --project \"${PROJECT}\" \\\n            --quiet \\\n            \"${template}\"\n        fi\n      } &\n    done\n\n    # Wait for last batch of jobs\n    kube::util::wait-for-jobs || {\n      echo -e \"Failed to delete instance template(s).\" >&2\n    }\n\n    # Delete the special heapster node (if it exists).\n    if [[ -n \"${HEAPSTER_MACHINE_TYPE:-}\" ]]; then\n      local -r heapster_machine_name=\"${NODE_INSTANCE_PREFIX}-heapster\"\n      if gcloud compute instances describe \"${heapster_machine_name}\" --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then\n        # Now we can safely delete the VM.\n        gcloud compute instances delete \\\n          --project \"${PROJECT}\" \\\n          --quiet \\\n          --delete-disks all \\\n          --zone \"${ZONE}\" \\\n          \"${heapster_machine_name}\"\n      fi\n    fi\n  fi\n\n  local -r REPLICA_NAME=\"${KUBE_REPLICA_NAME:-$(get-replica-name)}\"\n\n  set-existing-master\n\n  # Un-register the master replica from etcd and events etcd.\n  remove-replica-from-etcd 2379 true\n  remove-replica-from-etcd 4002 false\n\n  # Delete the master replica (if it exists).\n  if gcloud compute instances describe \"${REPLICA_NAME}\" --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then\n    # If there is a load balancer in front of apiservers we need to first update its configuration.\n    if gcloud compute target-pools describe \"${MASTER_NAME}\" --region \"${REGION}\" --project \"${PROJECT}\" &>/dev/null; then\n      gcloud compute target-pools remove-instances \"${MASTER_NAME}\" \\\n        --project \"${PROJECT}\" \\\n        --zone \"${ZONE}\" \\\n        --instances \"${REPLICA_NAME}\"\n    fi\n    # Detach replica from LB if needed.\n    if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      remove-from-internal-loadbalancer \"${REPLICA_NAME}\" \"${ZONE}\"\n    fi\n    # Now we can safely delete the VM.\n    gcloud compute instances delete \\\n      --project \"${PROJECT}\" \\\n      --quiet \\\n      --delete-disks all \\\n      --zone \"${ZONE}\" \\\n      \"${REPLICA_NAME}\"\n  fi\n\n  # Delete the master replica pd (possibly leaked by kube-up if master create failed).\n  # TODO(jszczepkowski): remove also possibly leaked replicas' pds\n  local -r replica_pd=\"${REPLICA_NAME:-${MASTER_NAME}}-pd\"\n  if gcloud compute disks describe \"${replica_pd}\" --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then\n    gcloud compute disks delete \\\n      --project \"${PROJECT}\" \\\n      --quiet \\\n      --zone \"${ZONE}\" \\\n      \"${replica_pd}\"\n  fi\n\n  # Check if this are any remaining master replicas.\n  local REMAINING_MASTER_COUNT\n  REMAINING_MASTER_COUNT=$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"name ~ '$(get-replica-name-regexp)'\" \\\n    --format \"value(zone)\" | wc -l)\n\n  # In the replicated scenario, if there's only a single master left, we should also delete load balancer in front of it.\n  if [[ \"${REMAINING_MASTER_COUNT}\" -eq 1 ]]; then\n    detect-master\n    local REMAINING_REPLICA_NAME\n    local REMAINING_REPLICA_ZONE\n    REMAINING_REPLICA_NAME=\"$(get-all-replica-names)\"\n    REMAINING_REPLICA_ZONE=$(gcloud compute instances list \"${REMAINING_REPLICA_NAME}\" \\\n      --project \"${PROJECT}\" --format='value(zone)')\n    if gcloud compute forwarding-rules describe \"${MASTER_NAME}\" --region \"${REGION}\" --project \"${PROJECT}\" &>/dev/null; then\n      gcloud compute forwarding-rules delete \\\n        --project \"${PROJECT}\" \\\n        --region \"${REGION}\" \\\n        --quiet \\\n        \"${MASTER_NAME}\"\n      attach-external-ip \"${REMAINING_REPLICA_NAME}\" \"${REMAINING_REPLICA_ZONE}\" \"${KUBE_MASTER_IP}\"\n      gcloud compute target-pools delete \\\n        --project \"${PROJECT}\" \\\n        --region \"${REGION}\" \\\n        --quiet \\\n        \"${MASTER_NAME}\"\n    fi\n\n    if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      remove-from-internal-loadbalancer \"${REMAINING_REPLICA_NAME}\" \"${REMAINING_REPLICA_ZONE}\"\n      delete-internal-loadbalancer\n      attach-internal-master-ip \"${REMAINING_REPLICA_NAME}\" \"${REMAINING_REPLICA_ZONE}\" \"${KUBE_MASTER_INTERNAL_IP}\"\n    fi\n  fi\n\n  # If there are no more remaining master replicas, we should delete all remaining network resources.\n  if [[ \"${REMAINING_MASTER_COUNT}\" -eq 0 ]]; then\n    # Delete firewall rule for the master, etcd servers, and nodes.\n    delete-firewall-rules \"${MASTER_NAME}-https\" \"${MASTER_NAME}-etcd\" \"${NODE_TAG}-all\" \"${MASTER_NAME}-konnectivity-server\"\n    # Delete the master's reserved IP\n    if gcloud compute addresses describe \"${MASTER_NAME}-ip\" --region \"${REGION}\" --project \"${PROJECT}\" &>/dev/null; then\n      gcloud compute addresses delete \\\n        --project \"${PROJECT}\" \\\n        --region \"${REGION}\" \\\n        --quiet \\\n        \"${MASTER_NAME}-ip\"\n    fi\n\n    if gcloud compute addresses describe \"${MASTER_NAME}-internal-ip\" --region \"${REGION}\" --project \"${PROJECT}\" &>/dev/null; then\n      gcloud compute addresses delete \\\n        --project \"${PROJECT}\" \\\n        --region \"${REGION}\" \\\n        --quiet \\\n        \"${MASTER_NAME}-internal-ip\"\n    fi\n  fi\n\n  if [[ \"${KUBE_DELETE_NODES:-}\" != \"false\" ]]; then\n    # Find out what minions are running.\n    local -a minions\n    kube::util::read-array minions < <(gcloud compute instances list \\\n      --project \"${PROJECT}\" \\\n      --filter=\"(name ~ '${NODE_INSTANCE_PREFIX}-.+' OR name ~ '${WINDOWS_NODE_INSTANCE_PREFIX}-.+') AND zone:(${ZONE})\" \\\n      --format='value(name)')\n    # If any minions are running, delete them in batches.\n    while (( \"${#minions[@]}\" > 0 )); do\n      echo Deleting nodes \"${minions[*]::${batch}}\"\n      gcloud compute instances delete \\\n        --project \"${PROJECT}\" \\\n        --quiet \\\n        --delete-disks boot \\\n        --zone \"${ZONE}\" \\\n        \"${minions[@]::${batch}}\"\n      minions=( \"${minions[@]:${batch}}\" )\n    done\n  fi\n\n  # If there are no more remaining master replicas: delete routes, pd for influxdb and update kubeconfig\n  if [[ \"${REMAINING_MASTER_COUNT}\" -eq 0 ]]; then\n    # Delete routes.\n    local -a routes\n    # Clean up all routes w/ names like \"<cluster-name>-<node-GUID>\"\n    # e.g. \"kubernetes-12345678-90ab-cdef-1234-567890abcdef\". The name is\n    # determined by the node controller on the master.\n    # Note that this is currently a noop, as synchronously deleting the node MIG\n    # first allows the master to cleanup routes itself.\n    local TRUNCATED_PREFIX=\"${INSTANCE_PREFIX:0:26}\"\n    kube::util::read-array routes < <(gcloud compute routes list --project \"${NETWORK_PROJECT}\" \\\n      --filter=\"name ~ '${TRUNCATED_PREFIX}-.{8}-.{4}-.{4}-.{4}-.{12}'\" \\\n      --format='value(name)')\n    while (( \"${#routes[@]}\" > 0 )); do\n      echo Deleting routes \"${routes[*]::${batch}}\"\n      gcloud compute routes delete \\\n        --project \"${NETWORK_PROJECT}\" \\\n        --quiet \\\n        \"${routes[@]::${batch}}\"\n      routes=( \"${routes[@]:${batch}}\" )\n    done\n\n    # Delete persistent disk for influx-db.\n    if gcloud compute disks describe \"${INSTANCE_PREFIX}\"-influxdb-pd --zone \"${ZONE}\" --project \"${PROJECT}\" &>/dev/null; then\n      gcloud compute disks delete \\\n        --project \"${PROJECT}\" \\\n        --quiet \\\n        --zone \"${ZONE}\" \\\n        \"${INSTANCE_PREFIX}\"-influxdb-pd\n    fi\n\n    # Delete all remaining firewall rules and network.\n    delete-firewall-rules \\\n      \"${CLUSTER_NAME}-default-internal-master\" \\\n      \"${CLUSTER_NAME}-default-internal-node\" \\\n      \"${NETWORK}-default-ssh\" \\\n      \"${NETWORK}-default-rdp\" \\\n      \"${NETWORK}-default-internal\"  # Pre-1.5 clusters\n\n    if [[ \"${KUBE_DELETE_NETWORK}\" == \"true\" ]]; then\n      delete-cloud-nat-router\n      # Delete all remaining firewall rules in the network.\n      delete-all-firewall-rules || true\n      delete-subnetworks || true\n      delete-network || true  # might fail if there are leaked resources that reference the network\n    fi\n\n    # If there are no more remaining master replicas, we should update kubeconfig.\n    export CONTEXT=\"${PROJECT}_${INSTANCE_PREFIX}\"\n    clear-kubeconfig\n  else\n  # If some master replicas remain: cluster has been changed, we need to re-validate it.\n    echo \"... calling validate-cluster\" >&2\n    # Override errexit\n    (validate-cluster) && validate_result=\"$?\" || validate_result=\"$?\"\n\n    # We have two different failure modes from validate cluster:\n    # - 1: fatal error - cluster won't be working correctly\n    # - 2: weak error - something went wrong, but cluster probably will be working correctly\n    # We just print an error message in case 2).\n    if [[ \"${validate_result}\" -eq 1 ]]; then\n      exit 1\n    elif [[ \"${validate_result}\" -eq 2 ]]; then\n      echo \"...ignoring non-fatal errors in validate-cluster\" >&2\n    fi\n  fi\n  set -e\n}\n\n# Prints name of one of the master replicas in the current zone. It will be either\n# just MASTER_NAME or MASTER_NAME with a suffix for a replica (see get-replica-name-regexp).\n#\n# Assumed vars:\n#   PROJECT\n#   ZONE\n#   MASTER_NAME\n#\n# NOTE: Must be in sync with get-replica-name-regexp and set-replica-name.\nfunction get-replica-name() {\n  # Ignore if gcloud compute fails and successfully echo any outcome\n  # shellcheck disable=SC2005\n  echo \"$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"name ~ '$(get-replica-name-regexp)' AND zone:(${ZONE})\" \\\n    --format \"value(name)\" | head -n1)\"\n}\n\n# Prints comma-separated names of all of the master replicas in all zones.\n#\n# Assumed vars:\n#   PROJECT\n#   MASTER_NAME\n#\n# NOTE: Must be in sync with get-replica-name-regexp and set-replica-name.\nfunction get-all-replica-names() {\n  # Ignore if gcloud compute fails and successfully echo any outcome\n  # shellcheck disable=SC2005\n  echo \"$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"name ~ '$(get-replica-name-regexp)'\" \\\n    --format \"value(name)\" | tr \"\\n\" \",\" | sed 's/,$//')\"\n}\n\n# Prints the number of all of the master replicas in all zones.\n#\n# Assumed vars:\n#   MASTER_NAME\nfunction get-master-replicas-count() {\n  detect-project\n  local num_masters\n  num_masters=$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"name ~ '$(get-replica-name-regexp)'\" \\\n    --format \"value(zone)\" | wc -l)\n  echo -n \"${num_masters}\"\n}\n\n# Prints regexp for full master machine name. In a cluster with replicated master,\n# VM names may either be MASTER_NAME or MASTER_NAME with a suffix for a replica.\nfunction get-replica-name-regexp() {\n  echo \"^${MASTER_NAME}(-...)?\"\n}\n\n# Sets REPLICA_NAME to a unique name for a master replica that will match\n# expected regexp (see get-replica-name-regexp).\n#\n# Assumed vars:\n#   PROJECT\n#   ZONE\n#   MASTER_NAME\n#\n# Sets:\n#   REPLICA_NAME\nfunction set-replica-name() {\n  local instances\n  instances=$(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"name ~ '$(get-replica-name-regexp)'\" \\\n    --format \"value(name)\")\n\n  suffix=\"\"\n  while echo \"${instances}\" | grep \"${suffix}\" &>/dev/null; do\n    suffix=\"$(date | md5sum | head -c3)\"\n  done\n  REPLICA_NAME=\"${MASTER_NAME}-${suffix}\"\n}\n\n# Gets the instance templates in use by the cluster. It echos the template names\n# so that the function output can be used.\n# Assumed vars:\n#   NODE_INSTANCE_PREFIX\n#   WINDOWS_NODE_INSTANCE_PREFIX\n#\n# $1: project\nfunction get-template() {\n  local linux_filter=\"${NODE_INSTANCE_PREFIX}-(extra-)?template(-(${KUBE_RELEASE_VERSION_DASHED_REGEX}|${KUBE_CI_VERSION_DASHED_REGEX}))?\"\n  local windows_filter=\"${WINDOWS_NODE_INSTANCE_PREFIX}-template(-(${KUBE_RELEASE_VERSION_DASHED_REGEX}|${KUBE_CI_VERSION_DASHED_REGEX}))?\"\n\n  gcloud compute instance-templates list \\\n    --filter=\"name ~ '${linux_filter}' OR name ~ '${windows_filter}'\" \\\n    --project=\"${1}\" --format='value(name)'\n}\n\n# Checks if there are any present resources related kubernetes cluster.\n#\n# Assumed vars:\n#   MASTER_NAME\n#   NODE_INSTANCE_PREFIX\n#   WINDOWS_NODE_INSTANCE_PREFIX\n#   ZONE\n#   REGION\n# Vars set:\n#   KUBE_RESOURCE_FOUND\nfunction check-resources() {\n  detect-project\n  detect-node-names\n\n  echo \"Looking for already existing resources\"\n  KUBE_RESOURCE_FOUND=\"\"\n\n  if [[ -n \"${INSTANCE_GROUPS[*]:-}\" ]]; then\n    KUBE_RESOURCE_FOUND=\"Managed instance groups ${INSTANCE_GROUPS[*]}\"\n    return 1\n  fi\n  if [[ -n \"${WINDOWS_INSTANCE_GROUPS[*]:-}\" ]]; then\n    KUBE_RESOURCE_FOUND=\"Managed instance groups ${WINDOWS_INSTANCE_GROUPS[*]}\"\n    return 1\n  fi\n\n  if gcloud compute instance-templates describe --project \"${PROJECT}\" \"${NODE_INSTANCE_PREFIX}-template\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Instance template ${NODE_INSTANCE_PREFIX}-template\"\n    return 1\n  fi\n  if gcloud compute instance-templates describe --project \"${PROJECT}\" \"${WINDOWS_NODE_INSTANCE_PREFIX}-template\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Instance template ${WINDOWS_NODE_INSTANCE_PREFIX}-template\"\n    return 1\n  fi\n\n  if gcloud compute instances describe --project \"${PROJECT}\" \"${MASTER_NAME}\" --zone \"${ZONE}\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Kubernetes master ${MASTER_NAME}\"\n    return 1\n  fi\n\n  if gcloud compute disks describe --project \"${PROJECT}\" \"${MASTER_NAME}\"-pd --zone \"${ZONE}\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Persistent disk ${MASTER_NAME}-pd\"\n    return 1\n  fi\n\n  # Find out what minions are running.\n  local -a minions\n  kube::util::read-array minions < <(gcloud compute instances list \\\n    --project \"${PROJECT}\" \\\n    --filter=\"(name ~ '${NODE_INSTANCE_PREFIX}-.+' OR name ~ '${WINDOWS_NODE_INSTANCE_PREFIX}-.+') AND zone:(${ZONE})\" \\\n    --format='value(name)')\n  if (( \"${#minions[@]}\" > 0 )); then\n    KUBE_RESOURCE_FOUND=\"${#minions[@]} matching ${NODE_INSTANCE_PREFIX}-.+ or ${WINDOWS_NODE_INSTANCE_PREFIX}-.+\"\n    return 1\n  fi\n\n  if gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${MASTER_NAME}-https\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Firewall rules for ${MASTER_NAME}-https\"\n    return 1\n  fi\n\n  if gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${NODE_TAG}-all\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Firewall rules for ${MASTER_NAME}-all\"\n    return 1\n  fi\n\n  local -a routes\n  kube::util::read-array routes < <(gcloud compute routes list --project \"${NETWORK_PROJECT}\" \\\n    --filter=\"name ~ '${INSTANCE_PREFIX}-minion-.{4}'\" --format='value(name)')\n  if (( \"${#routes[@]}\" > 0 )); then\n    KUBE_RESOURCE_FOUND=\"${#routes[@]} routes matching ${INSTANCE_PREFIX}-minion-.{4}\"\n    return 1\n  fi\n\n  if gcloud compute addresses describe --project \"${PROJECT}\" \"${MASTER_NAME}-ip\" --region \"${REGION}\" &>/dev/null; then\n    KUBE_RESOURCE_FOUND=\"Master's reserved IP\"\n    return 1\n  fi\n\n  # No resources found.\n  return 0\n}\n\n# -----------------------------------------------------------------------------\n# Cluster specific test helpers\n\n# Execute prior to running tests to build a release if required for env.\n#\n# Assumed Vars:\n#   KUBE_ROOT\nfunction test-build-release() {\n  # Make a release\n  \"${KUBE_ROOT}/build/release.sh\"\n}\n\n# Execute prior to running tests to initialize required structure.\n#\n# Assumed vars:\n#   Variables from config.sh\nfunction test-setup() {\n  # Detect the project into $PROJECT if it isn't set\n  detect-project\n\n  if [[ ${MULTIZONE:-} == \"true\" && -n ${E2E_ZONES:-} ]]; then\n    for KUBE_GCE_ZONE in ${E2E_ZONES}; do\n      KUBE_GCE_ZONE=\"${KUBE_GCE_ZONE}\" KUBE_USE_EXISTING_MASTER=\"${KUBE_USE_EXISTING_MASTER:-}\" \"${KUBE_ROOT}/cluster/kube-up.sh\"\n      KUBE_USE_EXISTING_MASTER=\"true\" # For subsequent zones we use the existing master\n    done\n  else\n    \"${KUBE_ROOT}/cluster/kube-up.sh\"\n  fi\n\n  # Open up port 80 & 8080 so common containers on minions can be reached\n  # TODO(roberthbailey): Remove this once we are no longer relying on hostPorts.\n  local start\n  start=$(date +%s)\n  gcloud compute firewall-rules create \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --target-tags \"${NODE_TAG}\" \\\n    --allow tcp:80,tcp:8080 \\\n    --network \"${NETWORK}\" \\\n    \"${NODE_TAG}-http-alt\" 2> /dev/null || true\n  # As there is no simple way to wait longer for this operation we need to manually\n  # wait some additional time (20 minutes altogether).\n  while ! gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${NODE_TAG}-http-alt\" 2> /dev/null; do\n    if [[ $((start + 1200)) -lt $(date +%s) ]]; then\n      echo -e \"${color_red:-}Failed to create firewall ${NODE_TAG}-http-alt in ${NETWORK_PROJECT}\" >&2\n      exit 1\n    fi\n    sleep 5\n  done\n\n  # Open up the NodePort range\n  # TODO(justinsb): Move to main setup, if we decide whether we want to do this by default.\n  start=$(date +%s)\n  gcloud compute firewall-rules create \\\n    --project \"${NETWORK_PROJECT}\" \\\n    --target-tags \"${NODE_TAG}\" \\\n    --allow tcp:30000-32767,udp:30000-32767 \\\n    --network \"${NETWORK}\" \\\n    \"${NODE_TAG}-nodeports\" 2> /dev/null || true\n  # As there is no simple way to wait longer for this operation we need to manually\n  # wait some additional time (20 minutes altogether).\n  while ! gcloud compute firewall-rules describe --project \"${NETWORK_PROJECT}\" \"${NODE_TAG}-nodeports\" 2> /dev/null; do\n    if [[ $((start + 1200)) -lt $(date +%s) ]]; then\n      echo -e \"${color_red}Failed to create firewall ${NODE_TAG}-nodeports in ${PROJECT}\" >&2\n      exit 1\n    fi\n    sleep 5\n  done\n}\n\n# Execute after running tests to perform any required clean-up.\nfunction test-teardown() {\n  detect-project\n  echo \"Shutting down test cluster in background.\"\n  delete-firewall-rules \\\n    \"${NODE_TAG}-http-alt\" \\\n    \"${NODE_TAG}-nodeports\"\n  if [[ ${MULTIZONE:-} == \"true\" && -n ${E2E_ZONES:-} ]]; then\n    local zones\n    read -r -a zones <<< \"${E2E_ZONES}\"\n    # tear them down in reverse order, finally tearing down the master too.\n    for ((zone_num=${#zones[@]}-1; zone_num>0; zone_num--)); do\n      KUBE_GCE_ZONE=\"${zones[zone_num]}\" KUBE_USE_EXISTING_MASTER=\"true\" \"${KUBE_ROOT}/cluster/kube-down.sh\"\n    done\n    KUBE_GCE_ZONE=\"${zones[0]}\" KUBE_USE_EXISTING_MASTER=\"false\" \"${KUBE_ROOT}/cluster/kube-down.sh\"\n  else\n    \"${KUBE_ROOT}/cluster/kube-down.sh\"\n  fi\n}\n\n# SSH to a node by name ($1) and run a command ($2).\nfunction ssh-to-node() {\n  local node=\"$1\"\n  local cmd=\"$2\"\n  # Loop until we can successfully ssh into the box\n  for (( i=0; i<5; i++)); do\n    if gcloud compute ssh --ssh-flag='-o LogLevel=quiet' --ssh-flag='-o ConnectTimeout=30' --project \"${PROJECT}\" --zone=\"${ZONE}\" \"${node}\" --command 'echo test > /dev/null'; then\n      break\n    fi\n    sleep 5\n  done\n  # Then actually try the command.\n  gcloud compute ssh --ssh-flag=\"-o LogLevel=quiet\" --ssh-flag=\"-o ConnectTimeout=30\" --project \"${PROJECT}\" --zone=\"${ZONE}\" \"${node}\" --command \"${cmd}\"\n}\n\n# Perform preparations required to run e2e tests\nfunction prepare-e2e() {\n  detect-project\n}\n\n# Delete the image given by $1.\nfunction delete-image() {\n  gcloud container images delete --quiet \"$1\"\n}\n", "num_lines": 3988}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is for configuring kubernetes master and node instances. It is\n# uploaded in the manifests tar ball.\n\n# TODO: this script duplicates templating logic from cluster/saltbase/salt\n# using sed. It should use an actual template parser on the manifest\n# files.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n### Hardcoded constants\nMETADATA_SERVER_IP=\"${METADATA_SERVER_IP:-169.254.169.254}\"\n\n# Standard curl flags.\nCURL_FLAGS='--fail --silent --show-error --retry 5 --retry-delay 3 --connect-timeout 10 --retry-connrefused'\n\nfunction convert-manifest-params {\n  # A helper function to convert the manifest args from a string to a list of\n  # flag arguments.\n  # Old format:\n  #   command=[\"/bin/sh\", \"-c\", \"exec KUBE_EXEC_BINARY --param1=val1 --param2-val2\"].\n  # New format:\n  #   command=[\"KUBE_EXEC_BINARY\"]  # No shell dependencies.\n  #   args=[\"--param1=val1\", \"--param2-val2\"]\n  IFS=' ' read -ra FLAGS <<< \"$1\"\n  params=\"\"\n  for flag in \"${FLAGS[@]}\"; do\n    params+=\"\\n\\\"$flag\\\",\"\n  done\n  if [ -n \"$params\" ]; then\n    echo \"${params::-1}\"  #  drop trailing comma\n  fi\n}\n\nfunction append-param-if-not-present {\n  # A helper function to add flag to an arguments string\n  # if no such flag is present already\n  local params=\"$1\"\n  local -r flag=\"$2\"\n  local -r value=\"$3\"\n  if [[ ! \"${params}\" =~ \"--${flag}\"[=\\ ] ]]; then\n    params+=\" --${flag}=${value}\"\n  fi\n  echo \"${params}\"\n}\n\nfunction setup-os-params {\n  # Reset core_pattern. On GCI, the default core_pattern pipes the core dumps to\n  # /sbin/crash_reporter which is more restrictive in saving crash dumps. So for\n  # now, set a generic core_pattern that users can work with.\n  echo \"/core.%e.%p.%t\" > /proc/sys/kernel/core_pattern\n}\n\n# secure_random generates a secure random string of bytes. This function accepts\n# a number of secure bytes desired and returns a base64 encoded string with at\n# least the requested entropy. Rather than directly reading from /dev/urandom,\n# we use uuidgen which calls getrandom(2). getrandom(2) verifies that the\n# entropy pool has been initialized sufficiently for the desired operation\n# before reading from /dev/urandom.\n#\n# ARGS:\n#   #1: number of secure bytes to generate. We round up to the nearest factor of 32.\nfunction secure_random {\n  local infobytes=\"${1}\"\n  if ((infobytes <= 0)); then\n    echo \"Invalid argument to secure_random: infobytes='${infobytes}'\" 1>&2\n    return 1\n  fi\n\n  local out=\"\"\n  for (( i = 0; i < \"${infobytes}\"; i += 32 )); do\n    # uuids have 122 random bits, sha256 sums have 256 bits, so concatenate\n    # three uuids and take their sum. The sum is encoded in ASCII hex, hence the\n    # 64 character cut.\n    out+=\"$(\n     (\n       uuidgen --random;\n       uuidgen --random;\n       uuidgen --random;\n     ) | sha256sum \\\n       | head -c 64\n    )\";\n  done\n  # Finally, convert the ASCII hex to base64 to increase the density.\n  echo -n \"${out}\" | xxd -r -p | base64 -w 0\n}\n\n# Helper for configuring iptables rules for metadata server.\n#\n# $1 is the command flag (-I or -D).\n# $2 is the firewall action (LOG or REJECT).\n# $3 is the prefix for log output.\n# $4 is \"!\" to optionally invert the uid range.\nfunction gce-metadata-fw-helper {\n  local -r command=\"$1\"\n  local action=\"$2\"\n  local -r prefix=\"$3\"\n  local -r invert=\"${4:-}\"\n\n  # Expand rule action to include relevant option flags.\n  case \"${action}\" in\n    LOG)\n      action=\"LOG --log-prefix \"${prefix}:\" --log-uid --log-tcp-options --log-ip-option\"\n      ;;\n  esac\n\n  # Deliberately allow word split here\n  # shellcheck disable=SC2086\n  iptables -w ${command} OUTPUT -p tcp --dport 80 -d ${METADATA_SERVER_IP} -m owner ${invert:-} --uid-owner=${METADATA_SERVER_ALLOWED_UID_RANGE:-0-2999} -j ${action}\n}\n\n# WARNING: DO NOT USE THE FILTER TABLE! Some implementations of network policy\n# think they own it and will stomp all over your changes. At this time, the\n# mangle table is less contentious so use that if possible.\nfunction config-ip-firewall {\n  echo \"Configuring IP firewall rules\"\n\n  # Do not consider loopback addresses as martian source or destination while\n  # routing. This enables the use of 127/8 for local routing purposes.\n  sysctl -w net.ipv4.conf.all.route_localnet=1\n\n  # The GCI image has host firewall which drop most inbound/forwarded packets.\n  # We need to add rules to accept all TCP/UDP/ICMP/SCTP packets.\n  if iptables -w -L INPUT | grep \"Chain INPUT (policy DROP)\" > /dev/null; then\n    echo \"Add rules to accept all inbound TCP/UDP/ICMP packets\"\n    iptables -w -A INPUT -w -p TCP -j ACCEPT\n    iptables -w -A INPUT -w -p UDP -j ACCEPT\n    iptables -w -A INPUT -w -p ICMP -j ACCEPT\n    iptables -w -A INPUT -w -p SCTP -j ACCEPT\n  fi\n  if iptables -w -L FORWARD | grep \"Chain FORWARD (policy DROP)\" > /dev/null; then\n    echo \"Add rules to accept all forwarded TCP/UDP/ICMP/SCTP packets\"\n    iptables -w -A FORWARD -w -p TCP -j ACCEPT\n    iptables -w -A FORWARD -w -p UDP -j ACCEPT\n    iptables -w -A FORWARD -w -p ICMP -j ACCEPT\n    iptables -w -A FORWARD -w -p SCTP -j ACCEPT\n  fi\n\n  # Flush iptables nat table\n  iptables -w -t nat -F || true\n\n  if [[ \"${NON_MASQUERADE_CIDR:-}\" == \"0.0.0.0/0\" ]]; then\n    echo \"Add rules for ip masquerade\"\n    iptables -w -t nat -N IP-MASQ\n    iptables -w -t nat -A POSTROUTING -m comment --comment \"ip-masq: ensure nat POSTROUTING directs all non-LOCAL destination traffic to our custom IP-MASQ chain\" -m addrtype ! --dst-type LOCAL -j IP-MASQ\n    iptables -w -t nat -A IP-MASQ -d 169.254.0.0/16 -m comment --comment \"ip-masq: local traffic is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 10.0.0.0/8 -m comment --comment \"ip-masq: RFC 1918 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 172.16.0.0/12 -m comment --comment \"ip-masq: RFC 1918 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 192.168.0.0/16 -m comment --comment \"ip-masq: RFC 1918 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 240.0.0.0/4 -m comment --comment \"ip-masq: RFC 5735 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 192.0.2.0/24 -m comment --comment \"ip-masq: RFC 5737 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 198.51.100.0/24 -m comment --comment \"ip-masq: RFC 5737 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 203.0.113.0/24 -m comment --comment \"ip-masq: RFC 5737 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 100.64.0.0/10 -m comment --comment \"ip-masq: RFC 6598 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 198.18.0.0/15 -m comment --comment \"ip-masq: RFC 6815 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 192.0.0.0/24 -m comment --comment \"ip-masq: RFC 6890 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -d 192.88.99.0/24 -m comment --comment \"ip-masq: RFC 7526 reserved range is not subject to MASQUERADE\" -j RETURN\n    iptables -w -t nat -A IP-MASQ -m comment --comment \"ip-masq: outbound traffic is subject to MASQUERADE (must be last in chain)\" -j MASQUERADE\n  fi\n\n  # If METADATA_CONCEALMENT_NO_FIREWALL is set, don't create a firewall on this\n  # node because we don't expect the daemonset to run on this node.\n  if [[ \"${ENABLE_METADATA_CONCEALMENT:-}\" == \"true\" ]] && [[ ! \"${METADATA_CONCEALMENT_NO_FIREWALL:-}\" == \"true\" ]]; then\n    echo \"Add rule for metadata concealment\"\n    ip addr add dev lo 169.254.169.252/32\n    iptables -w -t nat -I PREROUTING -p tcp ! -i eth0 -d \"${METADATA_SERVER_IP}\" --dport 80 -m comment --comment \"metadata-concealment: bridge traffic to metadata server goes to metadata proxy\" -j DNAT --to-destination 169.254.169.252:988\n    iptables -w -t nat -I PREROUTING -p tcp ! -i eth0 -d \"${METADATA_SERVER_IP}\" --dport 8080 -m comment --comment \"metadata-concealment: bridge traffic to metadata server goes to metadata proxy\" -j DNAT --to-destination 169.254.169.252:987\n  fi\n  iptables -w -t mangle -I OUTPUT -s 169.254.169.254 -j DROP\n\n  # Log all metadata access not from approved processes.\n  case \"${METADATA_SERVER_FIREWALL_MODE:-off}\" in\n    log)\n      echo \"Installing metadata firewall logging rules\"\n      gce-metadata-fw-helper -I LOG \"MetadataServerFirewallReject\" !\n      gce-metadata-fw-helper -I LOG \"MetadataServerFirewallAccept\"\n      ;;\n  esac\n}\n\nfunction create-dirs {\n  echo \"Creating required directories\"\n  mkdir -p /var/lib/kubelet\n  mkdir -p /etc/kubernetes/manifests\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"false\" ]]; then\n    mkdir -p /var/lib/kube-proxy\n  fi\n}\n\n# Gets the total number of $(1) and $(2) type disks specified\n# by the user in ${NODE_LOCAL_SSDS_EXT}\nfunction get-local-disk-num() {\n  local interface=\"${1}\"\n  local format=\"${2}\"\n\n  localdisknum=0\n  if [[ -n \"${NODE_LOCAL_SSDS_EXT:-}\" ]]; then\n    IFS=\";\" read -r -a ssdgroups <<< \"${NODE_LOCAL_SSDS_EXT:-}\"\n    for ssdgroup in \"${ssdgroups[@]}\"; do\n      IFS=\",\" read -r -a ssdopts <<< \"${ssdgroup}\"\n      local opnum=\"${ssdopts[0]}\"\n      local opinterface=\"${ssdopts[1]}\"\n      local opformat=\"${ssdopts[2]}\"\n\n      if [[ \"${opformat,,}\" == \"${format,,}\" && \"${opinterface,,}\" == \"${interface,,}\" ]]; then\n        localdisknum=$((localdisknum+opnum))\n      fi\n    done\n  fi\n}\n\n# Creates a symlink for a ($1) so that it may be used as block storage\nfunction safe-block-symlink(){\n  local device=\"${1}\"\n  local symdir=\"${2}\"\n\n  mkdir -p \"${symdir}\"\n\n  get-or-generate-uuid \"${device}\"\n  local myuuid=\"${retuuid}\"\n\n  local sym=\"${symdir}/local-ssd-${myuuid}\"\n  # Do not \"mkdir -p ${sym}\" as that will cause unintended symlink behavior\n  ln -s \"${device}\" \"${sym}\"\n  echo \"Created a symlink for SSD $ssd at ${sym}\"\n  chmod a+w \"${sym}\"\n}\n\n# Gets a pregenerated UUID from ${ssdmap} if it exists, otherwise generates a new\n# UUID and places it inside ${ssdmap}\nfunction get-or-generate-uuid(){\n  local device=\"${1}\"\n\n  local ssdmap=\"/home/kubernetes/localssdmap.txt\"\n  echo \"Generating or getting UUID from ${ssdmap}\"\n\n  if [[ ! -e \"${ssdmap}\" ]]; then\n    touch \"${ssdmap}\"\n    chmod +w \"${ssdmap}\"\n  fi\n\n  # each line of the ssdmap looks like \"${device} persistent-uuid\"\n  local myuuid\n  if grep -q \"${device}\" \"${ssdmap}\"; then\n    #create symlink based on saved uuid\n    myuuid=$(grep \"${device}\" \"${ssdmap}\" | cut -d ' ' -f 2)\n  else\n    # generate new uuid and add it to the map\n    if ! myuuid=$(uuidgen); then\n      echo \"Failed to generate valid UUID with uuidgen\" >&2\n      exit 2\n    fi\n    echo \"${device} ${myuuid}\" >> \"${ssdmap}\"\n  fi\n\n  if [[ -z \"${myuuid}\" ]]; then\n    echo \"Failed to get a uuid for device ${device} when symlinking.\" >&2\n    exit 2\n  fi\n\n  retuuid=\"${myuuid}\"\n}\n\n#Formats the given device ($1) if needed and mounts it at given mount point\n# ($2).\nfunction safe-format-and-mount() {\n  local device\n  local mountpoint\n  device=\"$1\"\n  mountpoint=\"$2\"\n\n  # Format only if the disk is not already formatted.\n  if ! tune2fs -l \"${device}\" ; then\n    echo \"Formatting '${device}'\"\n    mkfs.ext4 -F \"${device}\"\n  fi\n\n  mkdir -p \"${mountpoint}\"\n  echo \"Mounting '${device}' at '${mountpoint}'\"\n  mount -o discard,defaults \"${device}\" \"${mountpoint}\"\n  chmod a+w \"${mountpoint}\"\n}\n\n# Gets a devices UUID and bind mounts the device to mount location in\n# /mnt/disks/by-id/\nfunction unique-uuid-bind-mount(){\n  local mountpoint\n  local actual_device\n  mountpoint=\"$1\"\n  actual_device=\"$2\"\n\n  # Trigger udev refresh so that newly formatted devices are propagated in by-uuid\n  udevadm control --reload-rules\n  udevadm trigger\n  udevadm settle\n\n  # find uuid for actual_device\n  local myuuid\n  myuuid=$(find -L /dev/disk/by-uuid -maxdepth 1 -samefile /dev/\"${actual_device}\" -printf '%P')\n  # myuuid should be the uuid of the device as found in /dev/disk/by-uuid/\n  if [[ -z \"${myuuid}\" ]]; then\n    echo \"Failed to get a uuid for device ${actual_device} when mounting.\" >&2\n    exit 2\n  fi\n\n  # bindpoint should be the full path of the to-be-bound device\n  local bindpoint=\"${UUID_MNT_PREFIX}-${interface}-fs/local-ssd-${myuuid}\"\n\n  safe-bind-mount \"${mountpoint}\" \"${bindpoint}\"\n}\n\n# Bind mounts device at mountpoint to bindpoint\nfunction safe-bind-mount(){\n  local mountpoint=\"${1}\"\n  local bindpoint=\"${2}\"\n\n  # Mount device to the mountpoint\n  mkdir -p \"${bindpoint}\"\n  echo \"Binding '${mountpoint}' at '${bindpoint}'\"\n  mount --bind \"${mountpoint}\" \"${bindpoint}\"\n  chmod a+w \"${bindpoint}\"\n}\n\n\n# Mounts, bindmounts, or symlinks depending on the interface and format\n# of the incoming device\nfunction mount-ext(){\n  local ssd=\"${1}\"\n  local devicenum=\"${2}\"\n  local interface=\"${3}\"\n  local format=\"${4}\"\n\n\n  if [[ -z \"${devicenum}\" ]]; then\n    echo \"Failed to get the local disk number for device ${ssd}\" >&2\n    exit 2\n  fi\n\n  # TODO: Handle partitioned disks. Right now this code just ignores partitions\n  if [[ \"${format}\" == \"fs\" ]]; then\n    if [[ \"${interface}\" == \"scsi\" ]]; then\n      local actual_device\n      actual_device=$(readlink -f \"${ssd}\" | cut -d '/' -f 3)\n      # Error checking\n      if [[ \"${actual_device}\" != sd* ]]; then\n        echo \"'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead\" >&2\n        exit 1\n      fi\n      local mountpoint=\"/mnt/disks/ssd${devicenum}\"\n    else\n      # This path is required because the existing Google images do not\n      # expose NVMe devices in /dev/disk/by-id so we are using the /dev/nvme instead\n      local actual_device\n      actual_device=$(echo \"${ssd}\" | cut -d '/' -f 3)\n      # Error checking\n      if [[ \"${actual_device}\" != nvme* ]]; then\n        echo \"'actual_device' is not of the correct format. It must be the kernel name of the device, got ${actual_device} instead\" >&2\n        exit 1\n      fi\n      local mountpoint=\"/mnt/disks/ssd-nvme${devicenum}\"\n    fi\n\n    safe-format-and-mount \"${ssd}\" \"${mountpoint}\"\n    # We only do the bindmount if users are using the new local ssd request method\n    # see https://github.com/kubernetes/kubernetes/pull/53466#discussion_r146431894\n    if [[ -n \"${NODE_LOCAL_SSDS_EXT:-}\" ]]; then\n      unique-uuid-bind-mount \"${mountpoint}\" \"${actual_device}\"\n    fi\n  elif [[ \"${format}\" == \"block\" ]]; then\n    local symdir=\"${UUID_BLOCK_PREFIX}-${interface}-block\"\n    safe-block-symlink \"${ssd}\" \"${symdir}\"\n  else\n    echo \"Disk format must be either fs or block, got ${format}\"\n  fi\n}\n\n# Local ssds, if present, are mounted or symlinked to their appropriate\n# locations\nfunction ensure-local-ssds() {\n  if [ \"${NODE_LOCAL_SSDS_EPHEMERAL:-false}\" == \"true\" ]; then\n    ensure-local-ssds-ephemeral-storage\n    return\n  fi\n  get-local-disk-num \"scsi\" \"block\"\n  local scsiblocknum=\"${localdisknum}\"\n  local i=0\n  for ssd in /dev/disk/by-id/google-local-ssd-*; do\n    if [ -e \"${ssd}\" ]; then\n      local devicenum\n      devicenum=$(echo \"${ssd}\" | sed -e 's/\\/dev\\/disk\\/by-id\\/google-local-ssd-\\([0-9]*\\)/\\1/')\n      if [[ \"${i}\" -lt \"${scsiblocknum}\" ]]; then\n        mount-ext \"${ssd}\" \"${devicenum}\" \"scsi\" \"block\"\n      else\n        # GKE does not set NODE_LOCAL_SSDS so all non-block devices\n        # are assumed to be filesystem devices\n        mount-ext \"${ssd}\" \"${devicenum}\" \"scsi\" \"fs\"\n      fi\n      i=$((i+1))\n    else\n      echo \"No local SCSI SSD disks found.\"\n    fi\n  done\n\n  # The following mounts or symlinks NVMe devices\n  get-local-disk-num \"nvme\" \"block\"\n  local nvmeblocknum=\"${localdisknum}\"\n  get-local-disk-num \"nvme\" \"fs\"\n  local nvmefsnum=\"${localdisknum}\"\n  # Check if NVMe SSD specified.\n  if [ \"${nvmeblocknum}\" -eq \"0\" ] && [ \"${nvmefsnum}\" -eq \"0\" ]; then\n    echo \"No local NVMe SSD specified.\"\n    return\n  fi\n  local i=0\n  for ssd in /dev/nvme*; do\n    if [ -e \"${ssd}\" ]; then\n      # This workaround to find if the NVMe device is a disk is required because\n      # the existing Google images does not expose NVMe devices in /dev/disk/by-id\n      if [[ $(udevadm info --query=property --name=\"${ssd}\" | grep DEVTYPE | sed \"s/DEVTYPE=//\") == \"disk\" ]]; then\n        # shellcheck disable=SC2155\n        local devicenum=$(echo \"${ssd}\" | sed -e 's/\\/dev\\/nvme0n\\([0-9]*\\)/\\1/')\n        if [[ \"${i}\" -lt \"${nvmeblocknum}\" ]]; then\n          mount-ext \"${ssd}\" \"${devicenum}\" \"nvme\" \"block\"\n        else\n          mount-ext \"${ssd}\" \"${devicenum}\" \"nvme\" \"fs\"\n        fi\n        i=$((i+1))\n      fi\n    else\n      echo \"No local NVMe SSD disks found.\"\n    fi\n  done\n}\n\n# Local SSDs, if present, are used in a single RAID 0 array and directories that\n# back ephemeral storage are mounted on them (kubelet root, container runtime\n# root and pod logs).\nfunction ensure-local-ssds-ephemeral-storage() {\n  local devices=()\n  # Get nvme devices\n  for ssd in /dev/nvme*n*; do\n    if [ -e \"${ssd}\" ]; then\n      # This workaround to find if the NVMe device is a local SSD is required\n      # because the existing Google images does not them in /dev/disk/by-id\n      if [[ \"$(lsblk -o MODEL -dn \"${ssd}\")\" == \"nvme_card\" ]]; then\n        devices+=(\"${ssd}\")\n      fi\n    fi\n  done\n  if [ \"${#devices[@]}\" -eq 0 ]; then\n    echo \"No local NVMe SSD disks found.\"\n    return\n  fi\n\n  local device=\"${devices[0]}\"\n  if [ \"${#devices[@]}\" -ne 1 ]; then\n    seen_arrays=(/dev/md/*)\n    device=${seen_arrays[0]}\n    echo \"Setting RAID array with local SSDs on device ${device}\"\n    if [ ! -e \"$device\" ]; then\n      device=\"/dev/md/0\"\n      echo \"y\" | mdadm --create \"${device}\" --level=0 --raid-devices=${#devices[@]} \"${devices[@]}\"\n    fi\n  fi\n\n  local ephemeral_mountpoint=\"/mnt/stateful_partition/kube-ephemeral-ssd\"\n  safe-format-and-mount \"${device}\" \"${ephemeral_mountpoint}\"\n\n  # mount container runtime root dir on SSD\n  local container_runtime=\"${CONTAINER_RUNTIME:-docker}\"\n  systemctl stop \"$container_runtime\"\n  # Some images remount the container runtime root dir.\n  umount \"/var/lib/${container_runtime}\" || true\n  # Move the container runtime's directory to the new location to preserve\n  # preloaded images.\n  if [ ! -d \"${ephemeral_mountpoint}/${container_runtime}\" ]; then\n    mv \"/var/lib/${container_runtime}\" \"${ephemeral_mountpoint}/${container_runtime}\"\n  fi\n  safe-bind-mount \"${ephemeral_mountpoint}/${container_runtime}\" \"/var/lib/${container_runtime}\"\n  systemctl start \"$container_runtime\"\n\n  # mount kubelet root dir on SSD\n  mkdir -p \"${ephemeral_mountpoint}/kubelet\"\n  safe-bind-mount \"${ephemeral_mountpoint}/kubelet\" \"/var/lib/kubelet\"\n\n  # mount pod logs root dir on SSD\n  mkdir -p \"${ephemeral_mountpoint}/log_pods\"\n  safe-bind-mount \"${ephemeral_mountpoint}/log_pods\" \"/var/log/pods\"\n}\n\n# Installs logrotate configuration files\nfunction setup-logrotate() {\n  mkdir -p /etc/logrotate.d/\n\n  if [[ \"${ENABLE_LOGROTATE_FILES:-true}\" = \"true\" ]]; then\n    # Configure log rotation for all logs in /var/log, which is where k8s services\n    # are configured to write their log files. Whenever logrotate is ran, this\n    # config will:\n    # * rotate the log file if its size is > 100Mb OR if one day has elapsed\n    # * save rotated logs into a gzipped timestamped backup\n    # * log file timestamp (controlled by 'dateformat') includes seconds too. This\n    #   ensures that logrotate can generate unique logfiles during each rotation\n    #   (otherwise it skips rotation if 'maxsize' is reached multiple times in a\n    #   day).\n    # * keep only 5 old (rotated) logs, and will discard older logs.\n    cat > /etc/logrotate.d/allvarlogs <<EOF\n/var/log/*.log {\n    rotate ${LOGROTATE_FILES_MAX_COUNT:-5}\n    copytruncate\n    missingok\n    notifempty\n    compress\n    maxsize ${LOGROTATE_MAX_SIZE:-100M}\n    daily\n    dateext\n    dateformat -%Y%m%d-%s\n    create 0644 root root\n}\nEOF\n  fi\n\n  if [[ \"${ENABLE_POD_LOG:-false}\" = \"true\" ]]; then\n    # Configure log rotation for pod logs in /var/log/pods/NAMESPACE_NAME_UID.\n    cat > /etc/logrotate.d/allpodlogs <<EOF\n/var/log/pods/*/*.log {\n    rotate ${POD_LOG_MAX_FILE:-5}\n    copytruncate\n    missingok\n    notifempty\n    compress\n    maxsize ${POD_LOG_MAX_SIZE:-5M}\n    daily\n    dateext\n    dateformat -%Y%m%d-%s\n    create 0644 root root\n}\nEOF\n  fi\n}\n\n# Finds the master PD device; returns it in MASTER_PD_DEVICE\nfunction find-master-pd {\n  MASTER_PD_DEVICE=\"\"\n  if [[ ! -e /dev/disk/by-id/google-master-pd ]]; then\n    return\n  fi\n  device_info=$(ls -l /dev/disk/by-id/google-master-pd)\n  relative_path=${device_info##* }\n  MASTER_PD_DEVICE=\"/dev/disk/by-id/${relative_path}\"\n}\n\n# Mounts a persistent disk (formatting if needed) to store the persistent data\n# on the master -- etcd's data, a few settings, and security certs/keys/tokens.\n# safe-format-and-mount only formats an unformatted disk, and mkdir -p will\n# leave a directory be if it already exists.\nfunction mount-master-pd {\n  find-master-pd\n  if [[ -z \"${MASTER_PD_DEVICE:-}\" ]]; then\n    return\n  fi\n\n  echo \"Mounting master-pd\"\n  local -r pd_path=\"/dev/disk/by-id/google-master-pd\"\n  local -r mount_point=\"/mnt/disks/master-pd\"\n  # Format and mount the disk, create directories on it for all of the master's\n  # persistent data, and link them to where they're used.\n  mkdir -p \"${mount_point}\"\n  safe-format-and-mount \"${pd_path}\" \"${mount_point}\"\n  echo \"Mounted master-pd '${pd_path}' at '${mount_point}'\"\n\n  # NOTE: These locations on the PD store persistent data, so to maintain\n  # upgradeability, these locations should not change.  If they do, take care\n  # to maintain a migration path from these locations to whatever new\n  # locations.\n\n  # Contains all the data stored in etcd.\n  mkdir -p \"${mount_point}/var/etcd\"\n  chmod 700 \"${mount_point}/var/etcd\"\n  ln -s -f \"${mount_point}/var/etcd\" /var/etcd\n  mkdir -p /etc/srv\n  # Contains the dynamically generated apiserver auth certs and keys.\n  mkdir -p \"${mount_point}/srv/kubernetes\"\n  ln -s -f \"${mount_point}/srv/kubernetes\" /etc/srv/kubernetes\n  # Directory for kube-apiserver to store SSH key (if necessary).\n  mkdir -p \"${mount_point}/srv/sshproxy\"\n  ln -s -f \"${mount_point}/srv/sshproxy\" /etc/srv/sshproxy\n\n  chown -R etcd \"${mount_point}/var/etcd\"\n  chgrp -R etcd \"${mount_point}/var/etcd\"\n}\n\n# append_or_replace_prefixed_line ensures:\n# 1. the specified file exists\n# 2. existing lines with the specified ${prefix} are removed\n# 3. a new line with the specified ${prefix}${suffix} is appended\nfunction append_or_replace_prefixed_line {\n  local -r file=\"${1:-}\"\n  local -r prefix=\"${2:-}\"\n  local -r suffix=\"${3:-}\"\n  local -r dirname=$(dirname \"${file}\")\n  local -r tmpfile=$(mktemp \"${dirname}/filtered.XXXX\")\n\n  touch \"${file}\"\n  awk -v pfx=\"${prefix}\" 'substr($0,1,length(pfx)) != pfx { print }' \"${file}\" > \"${tmpfile}\"\n  echo \"${prefix}${suffix}\" >> \"${tmpfile}\"\n  mv \"${tmpfile}\" \"${file}\"\n}\n\nfunction write-pki-data {\n  local data=\"${1}\"\n  local path=\"${2}\"\n  # remove the path if it exists\n  rm -f \"${path}\"\n  if [[ -n \"${KUBE_PKI_READERS_GROUP:-}\" ]]; then\n    (umask 027; echo \"${data}\" | base64 --decode > \"${path}\")\n    chgrp \"${KUBE_PKI_READERS_GROUP:-}\" \"${path}\"\n    chmod g+r \"${path}\"\n  else\n    (umask 077; echo \"${data}\" | base64 --decode > \"${path}\")\n  fi\n}\n\nfunction create-node-pki {\n  echo \"Creating node pki files\"\n\n  local -r pki_dir=\"/etc/srv/kubernetes/pki\"\n  mkdir -p \"${pki_dir}\"\n\n  if [[ -z \"${CA_CERT_BUNDLE:-}\" ]]; then\n    CA_CERT_BUNDLE=\"${CA_CERT}\"\n  fi\n\n  CA_CERT_BUNDLE_PATH=\"${pki_dir}/ca-certificates.crt\"\n  write-pki-data \"${CA_CERT_BUNDLE}\" \"${CA_CERT_BUNDLE_PATH}\"\n\n  if [[ -n \"${KUBELET_CERT:-}\" && -n \"${KUBELET_KEY:-}\" ]]; then\n    KUBELET_CERT_PATH=\"${pki_dir}/kubelet.crt\"\n    write-pki-data \"${KUBELET_CERT}\" \"${KUBELET_CERT_PATH}\"\n\n    KUBELET_KEY_PATH=\"${pki_dir}/kubelet.key\"\n    write-pki-data \"${KUBELET_KEY}\" \"${KUBELET_KEY_PATH}\"\n  fi\n}\n\nfunction create-master-pki {\n  echo \"Creating master pki files\"\n\n  local -r pki_dir=\"/etc/srv/kubernetes/pki\"\n  mkdir -p \"${pki_dir}\"\n\n  CA_CERT_PATH=\"${pki_dir}/ca.crt\"\n  write-pki-data \"${CA_CERT}\" \"${CA_CERT_PATH}\"\n\n  # this is not true on GKE\n  if [[ -n \"${CA_KEY:-}\" ]]; then\n    CA_KEY_PATH=\"${pki_dir}/ca.key\"\n    write-pki-data \"${CA_KEY}\" \"${CA_KEY_PATH}\"\n  fi\n\n  if [[ -z \"${APISERVER_SERVER_CERT:-}\" || -z \"${APISERVER_SERVER_KEY:-}\" ]]; then\n    APISERVER_SERVER_CERT=\"${MASTER_CERT}\"\n    APISERVER_SERVER_KEY=\"${MASTER_KEY}\"\n  fi\n\n  APISERVER_SERVER_CERT_PATH=\"${pki_dir}/apiserver.crt\"\n  write-pki-data \"${APISERVER_SERVER_CERT}\" \"${APISERVER_SERVER_CERT_PATH}\"\n\n  APISERVER_SERVER_KEY_PATH=\"${pki_dir}/apiserver.key\"\n  write-pki-data \"${APISERVER_SERVER_KEY}\" \"${APISERVER_SERVER_KEY_PATH}\"\n\n  if [[ -z \"${APISERVER_CLIENT_CERT:-}\" || -z \"${APISERVER_CLIENT_KEY:-}\" ]]; then\n    APISERVER_CLIENT_CERT=\"${KUBEAPISERVER_CERT}\"\n    APISERVER_CLIENT_KEY=\"${KUBEAPISERVER_KEY}\"\n  fi\n\n  APISERVER_CLIENT_CERT_PATH=\"${pki_dir}/apiserver-client.crt\"\n  write-pki-data \"${APISERVER_CLIENT_CERT}\" \"${APISERVER_CLIENT_CERT_PATH}\"\n\n  APISERVER_CLIENT_KEY_PATH=\"${pki_dir}/apiserver-client.key\"\n  write-pki-data \"${APISERVER_CLIENT_KEY}\" \"${APISERVER_CLIENT_KEY_PATH}\"\n\n  if [[ -z \"${SERVICEACCOUNT_CERT:-}\" || -z \"${SERVICEACCOUNT_KEY:-}\" ]]; then\n    SERVICEACCOUNT_CERT=\"${MASTER_CERT}\"\n    SERVICEACCOUNT_KEY=\"${MASTER_KEY}\"\n  fi\n\n  if [[ -n \"${OLD_MASTER_CERT:-}\" && -n \"${OLD_MASTER_KEY:-}\" ]]; then\n    OLD_MASTER_CERT_PATH=\"${pki_dir}/oldapiserver.crt\"\n    echo \"${OLD_MASTER_CERT}\" | base64 --decode > \"${OLD_MASTER_CERT_PATH}\"\n    OLD_MASTER_KEY_PATH=\"${pki_dir}/oldapiserver.key\"\n    echo \"${OLD_MASTER_KEY}\" | base64 --decode > \"${OLD_MASTER_KEY_PATH}\"\n  fi\n\n  SERVICEACCOUNT_CERT_PATH=\"${pki_dir}/serviceaccount.crt\"\n  write-pki-data \"${SERVICEACCOUNT_CERT}\" \"${SERVICEACCOUNT_CERT_PATH}\"\n\n  SERVICEACCOUNT_KEY_PATH=\"${pki_dir}/serviceaccount.key\"\n  write-pki-data \"${SERVICEACCOUNT_KEY}\" \"${SERVICEACCOUNT_KEY_PATH}\"\n\n  if [[ -n \"${REQUESTHEADER_CA_CERT:-}\" ]]; then\n    REQUESTHEADER_CA_CERT_PATH=\"${pki_dir}/aggr_ca.crt\"\n    write-pki-data \"${REQUESTHEADER_CA_CERT}\" \"${REQUESTHEADER_CA_CERT_PATH}\"\n\n    PROXY_CLIENT_KEY_PATH=\"${pki_dir}/proxy_client.key\"\n    write-pki-data \"${PROXY_CLIENT_KEY}\" \"${PROXY_CLIENT_KEY_PATH}\"\n\n    PROXY_CLIENT_CERT_PATH=\"${pki_dir}/proxy_client.crt\"\n    write-pki-data \"${PROXY_CLIENT_CERT}\" \"${PROXY_CLIENT_CERT_PATH}\"\n  fi\n}\n\n# After the first boot and on upgrade, these files exist on the master-pd\n# and should never be touched again (except perhaps an additional service\n# account, see NB below.) One exception is if METADATA_CLOBBERS_CONFIG is\n# enabled.\nfunction create-master-auth {\n  echo \"Creating master auth files\"\n  local -r auth_dir=\"/etc/srv/kubernetes\"\n  local -r known_tokens_csv=\"${auth_dir}/known_tokens.csv\"\n  if [[ -e \"${known_tokens_csv}\" && \"${METADATA_CLOBBERS_CONFIG:-false}\" == \"true\" ]]; then\n    rm \"${known_tokens_csv}\"\n  fi\n  if [[ -n \"${KUBE_BEARER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_BEARER_TOKEN},\"             \"admin,admin,system:masters\"\n  fi\n  if [[ -n \"${KUBE_BOOTSTRAP_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_BOOTSTRAP_TOKEN},\"          \"gcp:kube-bootstrap,uid:gcp:kube-bootstrap,system:masters\"\n  fi\n  if [[ -n \"${KUBE_CONTROLLER_MANAGER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_CONTROLLER_MANAGER_TOKEN},\" \"system:kube-controller-manager,uid:system:kube-controller-manager\"\n  fi\n  if [[ -n \"${KUBE_SCHEDULER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_SCHEDULER_TOKEN},\"          \"system:kube-scheduler,uid:system:kube-scheduler\"\n  fi\n  if [[ -n \"${KUBE_CLUSTER_AUTOSCALER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_CLUSTER_AUTOSCALER_TOKEN},\" \"cluster-autoscaler,uid:cluster-autoscaler\"\n  fi\n  if [[ -n \"${KUBE_PROXY_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KUBE_PROXY_TOKEN},\"              \"system:kube-proxy,uid:kube_proxy\"\n  fi\n  if [[ -n \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${NODE_PROBLEM_DETECTOR_TOKEN},\"   \"system:node-problem-detector,uid:node-problem-detector\"\n  fi\n  if [[ -n \"${GCE_GLBC_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${GCE_GLBC_TOKEN},\"                \"system:controller:glbc,uid:system:controller:glbc\"\n  fi\n  if [[ -n \"${ADDON_MANAGER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${ADDON_MANAGER_TOKEN},\"           \"system:addon-manager,uid:system:addon-manager,system:masters\"\n  fi\n  if [[ -n \"${KONNECTIVITY_SERVER_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${KONNECTIVITY_SERVER_TOKEN},\"     \"system:konnectivity-server,uid:system:konnectivity-server\"\n    create-kubeconfig \"konnectivity-server\" \"${KONNECTIVITY_SERVER_TOKEN}\"\n  fi\n  if [[ -n \"${MONITORING_TOKEN:-}\" ]]; then\n    append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${MONITORING_TOKEN},\"     \"system:monitoring,uid:system:monitoring,system:monitoring\"\n  fi\n\n  if [[ -n \"${EXTRA_STATIC_AUTH_COMPONENTS:-}\" ]]; then\n    # Create a static Bearer token and kubeconfig for extra, comma-separated components.\n    IFS=\",\" read -r -a extra_components <<< \"${EXTRA_STATIC_AUTH_COMPONENTS:-}\"\n    for extra_component in \"${extra_components[@]}\"; do\n      local token\n      token=\"$(secure_random 32)\"\n      append_or_replace_prefixed_line \"${known_tokens_csv}\" \"${token},\" \"system:${extra_component},uid:system:${extra_component}\"\n      create-kubeconfig \"${extra_component}\" \"${token}\"\n    done\n  fi\n  local use_cloud_config=\"false\"\n  cat <<EOF >/etc/gce.conf\n[global]\nEOF\n  if [[ -n \"${GCE_API_ENDPOINT:-}\" ]]; then\n    cat <<EOF >>/etc/gce.conf\napi-endpoint = ${GCE_API_ENDPOINT}\nEOF\n  fi\n  if [[ -n \"${TOKEN_URL:-}\" && -n \"${TOKEN_BODY:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\ntoken-url = ${TOKEN_URL}\ntoken-body = ${TOKEN_BODY}\nEOF\n  fi\n  if [[ -n \"${CONTAINER_API_ENDPOINT:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\ncontainer-api-endpoint = ${CONTAINER_API_ENDPOINT}\nEOF\n  fi\n  if [[ -n \"${PROJECT_ID:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nproject-id = ${PROJECT_ID}\nEOF\n  fi\n  if [[ -n \"${NETWORK_PROJECT_ID:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nnetwork-project-id = ${NETWORK_PROJECT_ID}\nEOF\n  fi\n  if [[ -n \"${STACK_TYPE:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nstack-type = ${STACK_TYPE}\nEOF\n  fi\n  if [[ -n \"${NODE_NETWORK:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nnetwork-name = ${NODE_NETWORK}\nEOF\n  fi\n  if [[ -n \"${NODE_SUBNETWORK:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nsubnetwork-name = ${NODE_SUBNETWORK}\nEOF\n  fi\n  if [[ -n \"${NODE_INSTANCE_PREFIX:-}\" ]]; then\n    use_cloud_config=\"true\"\n    if [[ -n \"${NODE_TAGS:-}\" ]]; then\n      # split NODE_TAGS into an array by comma.\n      IFS=',' read -r -a node_tags <<< \"${NODE_TAGS}\"\n    else\n      local -r node_tags=(\"${NODE_INSTANCE_PREFIX}\")\n    fi\n    cat <<EOF >>/etc/gce.conf\nnode-instance-prefix = ${NODE_INSTANCE_PREFIX}\nEOF\n    for tag in \"${node_tags[@]}\"; do\n      cat <<EOF >>/etc/gce.conf\nnode-tags = ${tag}\nEOF\n    done\n  fi\n  if [[ -n \"${MULTIZONE:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nmultizone = ${MULTIZONE}\nEOF\n  fi\n# Multimaster indicates that the cluster is HA.\n# Currently the only HA clusters are regional.\n# If we introduce zonal multimaster this will need to be revisited.\n  if [[ -n \"${MULTIMASTER:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >>/etc/gce.conf\nregional = ${MULTIMASTER}\nEOF\n  fi\n  if [[ -n \"${GCE_ALPHA_FEATURES:-}\" ]]; then\n    use_cloud_config=\"true\"\n    # split GCE_ALPHA_FEATURES into an array by comma.\n    IFS=',' read -r -a alpha_features <<< \"${GCE_ALPHA_FEATURES}\"\n    for feature in \"${alpha_features[@]}\"; do\n      cat <<EOF >>/etc/gce.conf\nalpha-features = ${feature}\nEOF\n    done\n  fi\n  if [[ -n \"${SECONDARY_RANGE_NAME:-}\" ]]; then\n    use_cloud_config=\"true\"\n    cat <<EOF >> /etc/gce.conf\nsecondary-range-name = ${SECONDARY_RANGE_NAME}\nEOF\n  fi\n  if [[ \"${use_cloud_config}\" != \"true\" ]]; then\n    rm -f /etc/gce.conf\n  fi\n\n  if [[ -n \"${GCP_AUTHN_URL:-}\" ]]; then\n    cat <<EOF >/etc/gcp_authn.config\nclusters:\n  - name: gcp-authentication-server\n    cluster:\n      server: ${GCP_AUTHN_URL}\nusers:\n  - name: kube-apiserver\n    user:\n      auth-provider:\n        name: gcp\ncurrent-context: webhook\ncontexts:\n- context:\n    cluster: gcp-authentication-server\n    user: kube-apiserver\n  name: webhook\nEOF\n  fi\n\n  if [[ -n \"${GCP_AUTHZ_URL:-}\" ]]; then\n    cat <<EOF >/etc/gcp_authz.config\nclusters:\n  - name: gcp-authorization-server\n    cluster:\n      server: ${GCP_AUTHZ_URL}\nusers:\n  - name: kube-apiserver\n    user:\n      auth-provider:\n        name: gcp\ncurrent-context: webhook\ncontexts:\n- context:\n    cluster: gcp-authorization-server\n    user: kube-apiserver\n  name: webhook\nEOF\n  fi\n  if [[ \"${PREPARE_KONNECTIVITY_SERVICE:-false}\" == \"true\" ]]; then\n    if [[ \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\" == 'grpc' ]]; then\n      cat <<EOF >/etc/srv/kubernetes/egress_selector_configuration.yaml\napiVersion: apiserver.k8s.io/v1beta1\nkind: EgressSelectorConfiguration\negressSelections:\n- name: cluster\n  connection:\n    proxyProtocol: GRPC\n    transport:\n      uds:\n        udsName: /etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket\n- name: master\n  connection:\n    proxyProtocol: Direct\n- name: etcd\n  connection:\n    proxyProtocol: Direct\nEOF\n    elif [[ \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\" == 'http-connect' ]]; then\n      cat <<EOF >/etc/srv/kubernetes/egress_selector_configuration.yaml\napiVersion: apiserver.k8s.io/v1beta1\nkind: EgressSelectorConfiguration\negressSelections:\n- name: cluster\n  connection:\n    proxyProtocol: HTTPConnect\n    transport:\n      uds:\n        udsName: /etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket\n- name: master\n  connection:\n    proxyProtocol: Direct\n- name: etcd\n  connection:\n    proxyProtocol: Direct\nEOF\n    else\n      echo \"KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE must be set to either grpc or http-connect\"\n      exit 1\n    fi\n  fi\n\n  if [[ -n \"${WEBHOOK_GKE_EXEC_AUTH:-}\" ]]; then\n    if [[ -z \"${EXEC_AUTH_PLUGIN_URL:-}\" ]]; then\n      1>&2 echo \"You requested GKE exec auth support for webhooks, but EXEC_AUTH_PLUGIN_URL was not specified.  This configuration depends on gke-exec-auth-plugin for authenticating to the webhook endpoint.\"\n      exit 1\n    fi\n\n    if [[ -z \"${TOKEN_URL:-}\" || -z \"${TOKEN_BODY:-}\" || -z \"${TOKEN_BODY_UNQUOTED:-}\" ]]; then\n      1>&2 echo \"You requested GKE exec auth support for webhooks, but TOKEN_URL, TOKEN_BODY, and TOKEN_BODY_UNQUOTED were not provided.  gke-exec-auth-plugin requires these values for its configuration.\"\n      exit 1\n    fi\n\n    # kubeconfig to be used by webhooks with GKE exec auth support.  Note that\n    # the path to gke-exec-auth-plugin is the path when mounted inside the\n    # kube-apiserver pod.\n    cat <<EOF >/etc/srv/kubernetes/webhook.kubeconfig\napiVersion: v1\nkind: Config\nusers:\n- name: '*.googleapis.com'\n  user:\n    exec:\n      apiVersion: \"client.authentication.k8s.io/v1alpha1\"\n      command: /usr/bin/gke-exec-auth-plugin\n      args:\n      - --mode=alt-token\n      - --alt-token-url=${TOKEN_URL}\n      - --alt-token-body=${TOKEN_BODY_UNQUOTED}\nEOF\n  fi\n\n  if [[ -n \"${ADMISSION_CONTROL:-}\" ]]; then\n    # Emit a basic admission control configuration file, with no plugins specified.\n    cat <<EOF >/etc/srv/kubernetes/admission_controller_config.yaml\napiVersion: apiserver.k8s.io/v1alpha1\nkind: AdmissionConfiguration\nplugins:\nEOF\n\n    # Add resourcequota config to limit critical pods to kube-system by default\n    cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml\n- name: \"ResourceQuota\"\n  configuration:\n    apiVersion: apiserver.config.k8s.io/v1\n    kind: ResourceQuotaConfiguration\n    limitedResources:\n    - resource: pods\n      matchScopes:\n      - scopeName: PriorityClass\n        operator: In\n        values: [\"system-node-critical\", \"system-cluster-critical\"]\nEOF\n\n    if [[ \"${ADMISSION_CONTROL:-}\" == *\"ImagePolicyWebhook\"* ]]; then\n      if [[ -z \"${GCP_IMAGE_VERIFICATION_URL:-}\" ]]; then\n        1>&2 echo \"The ImagePolicyWebhook admission control plugin was requested, but GCP_IMAGE_VERIFICATION_URL was not provided.\"\n        exit 1\n      fi\n\n      1>&2 echo \"ImagePolicyWebhook admission control plugin requested.  Configuring it to point at ${GCP_IMAGE_VERIFICATION_URL}\"\n\n      # ImagePolicyWebhook does not use gke-exec-auth-plugin for authenticating\n      # to the webhook endpoint.  Emit its special kubeconfig.\n      cat <<EOF >/etc/srv/kubernetes/gcp_image_review.kubeconfig\nclusters:\n  - name: gcp-image-review-server\n    cluster:\n      server: ${GCP_IMAGE_VERIFICATION_URL}\nusers:\n  - name: kube-apiserver\n    user:\n      auth-provider:\n        name: gcp\ncurrent-context: webhook\ncontexts:\n- context:\n    cluster: gcp-image-review-server\n    user: kube-apiserver\n  name: webhook\nEOF\n\n      # Append config for ImagePolicyWebhook to the shared admission controller\n      # configuration file.\n      cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml\n- name: ImagePolicyWebhook\n  configuration:\n    imagePolicy:\n      kubeConfigFile: /etc/srv/kubernetes/gcp_image_review.kubeconfig\n      allowTTL: 30\n      denyTTL: 30\n      retryBackoff: 500\n      defaultAllow: true\nEOF\n    fi\n\n    # If GKE exec auth for webhooks has been requested, then\n    # ValidatingAdmissionWebhook should use it.  Otherwise, run with the default\n    # config.\n    if [[ -n \"${WEBHOOK_GKE_EXEC_AUTH:-}\" ]]; then\n      1>&2 echo \"ValidatingAdmissionWebhook requested, and WEBHOOK_GKE_EXEC_AUTH specified.  Configuring ValidatingAdmissionWebhook to use gke-exec-auth-plugin.\"\n\n      # Append config for ValidatingAdmissionWebhook to the shared admission\n      # controller configuration file.\n      cat <<EOF >>/etc/srv/kubernetes/admission_controller_config.yaml\n- name: ValidatingAdmissionWebhook\n  configuration:\n    apiVersion: apiserver.config.k8s.io/v1alpha1\n    kind: WebhookAdmission\n    kubeConfigFile: /etc/srv/kubernetes/webhook.kubeconfig\nEOF\n    fi\n  fi\n}\n\n# Write the config for the audit policy.\nfunction create-master-audit-policy {\n  local -r path=\"${1}\"\n  local -r policy=\"${2:-}\"\n\n  if [[ -n \"${policy}\" ]]; then\n    echo \"${policy}\" > \"${path}\"\n    return\n  fi\n\n  # Known api groups\n  local -r known_apis='\n      - group: \"\" # core\n      - group: \"admissionregistration.k8s.io\"\n      - group: \"apiextensions.k8s.io\"\n      - group: \"apiregistration.k8s.io\"\n      - group: \"apps\"\n      - group: \"authentication.k8s.io\"\n      - group: \"authorization.k8s.io\"\n      - group: \"autoscaling\"\n      - group: \"batch\"\n      - group: \"certificates.k8s.io\"\n      - group: \"extensions\"\n      - group: \"metrics.k8s.io\"\n      - group: \"networking.k8s.io\"\n      - group: \"node.k8s.io\"\n      - group: \"policy\"\n      - group: \"rbac.authorization.k8s.io\"\n      - group: \"scheduling.k8s.io\"\n      - group: \"storage.k8s.io\"'\n\n  cat <<EOF >\"${path}\"\napiVersion: audit.k8s.io/v1\nkind: Policy\nrules:\n  # The following requests were manually identified as high-volume and low-risk,\n  # so drop them.\n  - level: None\n    users: [\"system:kube-proxy\"]\n    verbs: [\"watch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"endpoints\", \"services\", \"services/status\"]\n  - level: None\n    # Ingress controller reads 'configmaps/ingress-uid' through the unsecured port.\n    # TODO(#46983): Change this to the ingress controller service account.\n    users: [\"system:unsecured\"]\n    namespaces: [\"kube-system\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"configmaps\"]\n  - level: None\n    users: [\"kubelet\"] # legacy kubelet identity\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes\", \"nodes/status\"]\n  - level: None\n    userGroups: [\"system:nodes\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes\", \"nodes/status\"]\n  - level: None\n    users:\n      - system:kube-controller-manager\n      - system:kube-scheduler\n      - system:serviceaccount:kube-system:endpoint-controller\n    verbs: [\"get\", \"update\"]\n    namespaces: [\"kube-system\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"endpoints\"]\n  - level: None\n    users: [\"system:apiserver\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"namespaces\", \"namespaces/status\", \"namespaces/finalize\"]\n  - level: None\n    users: [\"cluster-autoscaler\"]\n    verbs: [\"get\", \"update\"]\n    namespaces: [\"kube-system\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"configmaps\", \"endpoints\"]\n  # Don't log HPA fetching metrics.\n  - level: None\n    users:\n      - system:kube-controller-manager\n    verbs: [\"get\", \"list\"]\n    resources:\n      - group: \"metrics.k8s.io\"\n\n  # Don't log these read-only URLs.\n  - level: None\n    nonResourceURLs:\n      - /healthz*\n      - /version\n      - /swagger*\n\n  # Don't log events requests because of performance impact.\n  - level: None\n    resources:\n      - group: \"\" # core\n        resources: [\"events\"]\n\n  # node and pod status calls from nodes are high-volume and can be large, don't log responses for expected updates from nodes\n  - level: Request\n    users: [\"kubelet\", \"system:node-problem-detector\", \"system:serviceaccount:kube-system:node-problem-detector\"]\n    verbs: [\"update\",\"patch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes/status\", \"pods/status\"]\n    omitStages:\n      - \"RequestReceived\"\n  - level: Request\n    userGroups: [\"system:nodes\"]\n    verbs: [\"update\",\"patch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes/status\", \"pods/status\"]\n    omitStages:\n      - \"RequestReceived\"\n\n  # deletecollection calls can be large, don't log responses for expected namespace deletions\n  - level: Request\n    users: [\"system:serviceaccount:kube-system:namespace-controller\"]\n    verbs: [\"deletecollection\"]\n    omitStages:\n      - \"RequestReceived\"\n\n  # Secrets, ConfigMaps, TokenRequest and TokenReviews can contain sensitive & binary data,\n  # so only log at the Metadata level.\n  - level: Metadata\n    resources:\n      - group: \"\" # core\n        resources: [\"secrets\", \"configmaps\", \"serviceaccounts/token\"]\n      - group: authentication.k8s.io\n        resources: [\"tokenreviews\"]\n    omitStages:\n      - \"RequestReceived\"\n  # Get responses can be large; skip them.\n  - level: Request\n    verbs: [\"get\", \"list\", \"watch\"]\n    resources: ${known_apis}\n    omitStages:\n      - \"RequestReceived\"\n  # Default level for known APIs\n  - level: RequestResponse\n    resources: ${known_apis}\n    omitStages:\n      - \"RequestReceived\"\n  # Default level for all other requests.\n  - level: Metadata\n    omitStages:\n      - \"RequestReceived\"\nEOF\n}\n\n# Writes the configuration file used by the webhook advanced auditing backend.\nfunction create-master-audit-webhook-config {\n  local -r path=\"${1}\"\n\n  if [[ -n \"${GCP_AUDIT_URL:-}\" ]]; then\n    # The webhook config file is a kubeconfig file describing the webhook endpoint.\n    cat <<EOF >\"${path}\"\nclusters:\n  - name: gcp-audit-server\n    cluster:\n      server: ${GCP_AUDIT_URL}\nusers:\n  - name: kube-apiserver\n    user:\n      auth-provider:\n        name: gcp\ncurrent-context: webhook\ncontexts:\n- context:\n    cluster: gcp-audit-server\n    user: kube-apiserver\n  name: webhook\nEOF\n  fi\n}\n\nfunction create-kubeconfig {\n  local component=$1\n  local token=$2\n  local path=\"/etc/srv/kubernetes/${component}/kubeconfig\"\n  mkdir -p \"/etc/srv/kubernetes/${component}\"\n\n  if [[ -e \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\" ]]; then\n    gke-internal-create-kubeconfig \"${component}\" \"${token}\" \"${path}\"\n  else\n    echo \"Creating kubeconfig file for component ${component}\"\n    cat <<EOF >\"${path}\"\napiVersion: v1\nkind: Config\nusers:\n- name: ${component}\n  user:\n    token: ${token}\nclusters:\n- name: local\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://localhost:443\ncontexts:\n- context:\n    cluster: local\n    user: ${component}\n  name: ${component}\ncurrent-context: ${component}\nEOF\n  fi\n}\n\n# Arg 1: the IP address of the API server\nfunction create-kubelet-kubeconfig() {\n  local apiserver_address=\"${1}\"\n  if [[ -z \"${apiserver_address}\" ]]; then\n    echo \"Must provide API server address to create Kubelet kubeconfig file!\"\n    exit 1\n  fi\n  if [[ \"${CREATE_BOOTSTRAP_KUBECONFIG:-true}\" == \"true\" ]]; then\n    echo \"Creating kubelet bootstrap-kubeconfig file\"\n    cat <<EOF >/var/lib/kubelet/bootstrap-kubeconfig\napiVersion: v1\nkind: Config\nusers:\n- name: kubelet\n  user:\n    client-certificate: ${KUBELET_CERT_PATH}\n    client-key: ${KUBELET_KEY_PATH}\nclusters:\n- name: local\n  cluster:\n    server: https://${apiserver_address}\n    certificate-authority: ${CA_CERT_BUNDLE_PATH}\ncontexts:\n- context:\n    cluster: local\n    user: kubelet\n  name: service-account-context\ncurrent-context: service-account-context\nEOF\n  elif [[ \"${FETCH_BOOTSTRAP_KUBECONFIG:-false}\" == \"true\" ]]; then\n    echo \"Fetching kubelet bootstrap-kubeconfig file from metadata\"\n    get-metadata-value \"instance/attributes/bootstrap-kubeconfig\" >/var/lib/kubelet/bootstrap-kubeconfig\n  else\n    echo \"Fetching kubelet kubeconfig file from metadata\"\n    get-metadata-value \"instance/attributes/kubeconfig\" >/var/lib/kubelet/kubeconfig\n  fi\n}\n\n# Uses KUBELET_CA_CERT (falling back to CA_CERT), KUBELET_CERT, and KUBELET_KEY\n# to generate a kubeconfig file for the kubelet to securely connect to the apiserver.\n# Set REGISTER_MASTER_KUBELET to true if kubelet on the master node\n# should register to the apiserver.\nfunction create-master-kubelet-auth {\n  # Only configure the kubelet on the master if the required variables are\n  # set in the environment.\n  if [[ -n \"${KUBELET_APISERVER:-}\" && -n \"${KUBELET_CERT:-}\" && -n \"${KUBELET_KEY:-}\" ]]; then\n    REGISTER_MASTER_KUBELET=\"true\"\n    create-kubelet-kubeconfig \"${KUBELET_APISERVER}\"\n  fi\n}\n\nfunction create-kubeproxy-user-kubeconfig {\n  echo \"Creating kube-proxy user kubeconfig file\"\n  cat <<EOF >/var/lib/kube-proxy/kubeconfig\napiVersion: v1\nkind: Config\nusers:\n- name: kube-proxy\n  user:\n    token: ${KUBE_PROXY_TOKEN}\nclusters:\n- name: local\n  cluster:\n    certificate-authority-data: ${CA_CERT_BUNDLE}\ncontexts:\n- context:\n    cluster: local\n    user: kube-proxy\n  name: service-account-context\ncurrent-context: service-account-context\nEOF\n}\n\nfunction create-kube-scheduler-config {\n  echo \"Creating kube-scheduler config file\"\n  mkdir -p /etc/srv/kubernetes/kube-scheduler\n  cat <<EOF >/etc/srv/kubernetes/kube-scheduler/config\n${KUBE_SCHEDULER_CONFIG}\nEOF\n}\n\n# TODO(#92143): Remove legacy policy config creation once kube-scheduler config is GA.\nfunction create-kubescheduler-policy-config {\n  echo \"Creating kube-scheduler policy config file\"\n  mkdir -p /etc/srv/kubernetes/kube-scheduler\n  cat <<EOF >/etc/srv/kubernetes/kube-scheduler/policy-config\n${SCHEDULER_POLICY_CONFIG}\nEOF\n}\n\nfunction create-node-problem-detector-kubeconfig {\n  local apiserver_address=\"${1}\"\n  if [[ -z \"${apiserver_address}\" ]]; then\n    echo \"Must provide API server address to create node-problem-detector kubeconfig file!\"\n    exit 1\n  fi\n  echo \"Creating node-problem-detector kubeconfig file\"\n  mkdir -p /var/lib/node-problem-detector\n  cat <<EOF >/var/lib/node-problem-detector/kubeconfig\napiVersion: v1\nkind: Config\nusers:\n- name: node-problem-detector\n  user:\n    token: ${NODE_PROBLEM_DETECTOR_TOKEN}\nclusters:\n- name: local\n  cluster:\n    server: https://${apiserver_address}\n    certificate-authority-data: ${CA_CERT}\ncontexts:\n- context:\n    cluster: local\n    user: node-problem-detector\n  name: service-account-context\ncurrent-context: service-account-context\nEOF\n}\n\nfunction create-node-problem-detector-kubeconfig-from-kubelet {\n  echo \"Creating node-problem-detector kubeconfig from /var/lib/kubelet/kubeconfig\"\n  mkdir -p /var/lib/node-problem-detector\n  cp /var/lib/kubelet/kubeconfig /var/lib/node-problem-detector/kubeconfig\n}\n\nfunction create-master-etcd-auth {\n  if [[ -n \"${ETCD_CA_CERT:-}\" && -n \"${ETCD_PEER_KEY:-}\" && -n \"${ETCD_PEER_CERT:-}\" ]]; then\n    local -r auth_dir=\"/etc/srv/kubernetes\"\n    echo \"${ETCD_CA_CERT}\" | base64 --decode | gunzip > \"${auth_dir}/etcd-ca.crt\"\n    echo \"${ETCD_PEER_KEY}\" | base64 --decode > \"${auth_dir}/etcd-peer.key\"\n    echo \"${ETCD_PEER_CERT}\" | base64 --decode | gunzip > \"${auth_dir}/etcd-peer.crt\"\n  fi\n}\n\nfunction create-master-etcd-apiserver-auth {\n   if [[ -n \"${ETCD_APISERVER_CA_CERT:-}\" && -n \"${ETCD_APISERVER_SERVER_KEY:-}\" && -n \"${ETCD_APISERVER_SERVER_CERT:-}\" && -n \"${ETCD_APISERVER_CLIENT_KEY:-}\" && -n \"${ETCD_APISERVER_CLIENT_CERT:-}\" ]]; then\n     local -r auth_dir=\"/etc/srv/kubernetes/pki\"\n\n     ETCD_APISERVER_CA_KEY_PATH=\"${auth_dir}/etcd-apiserver-ca.key\"\n     echo \"${ETCD_APISERVER_CA_KEY}\" | base64 --decode > \"${ETCD_APISERVER_CA_KEY_PATH}\"\n\n     # Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.\n     ETCD_APISERVER_CA_CERT_PATH=\"${auth_dir}/etcd-apiserver-ca.crt\"\n     echo \"${ETCD_APISERVER_CA_CERT}\" | base64 --decode | gunzip > \"${ETCD_APISERVER_CA_CERT_PATH}\"\n\n     ETCD_APISERVER_SERVER_KEY_PATH=\"${auth_dir}/etcd-apiserver-server.key\"\n     echo \"${ETCD_APISERVER_SERVER_KEY}\" | base64 --decode > \"${ETCD_APISERVER_SERVER_KEY_PATH}\"\n\n     ETCD_APISERVER_SERVER_CERT_PATH=\"${auth_dir}/etcd-apiserver-server.crt\"\n     echo \"${ETCD_APISERVER_SERVER_CERT}\" | base64 --decode | gunzip > \"${ETCD_APISERVER_SERVER_CERT_PATH}\"\n\n     # Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.\n     ETCD_APISERVER_CLIENT_KEY_PATH=\"${auth_dir}/etcd-apiserver-client.key\"\n     echo \"${ETCD_APISERVER_CLIENT_KEY}\" | base64 --decode > \"${ETCD_APISERVER_CLIENT_KEY_PATH}\"\n\n     # Keep in sync with add-replica-to-etcd/remove-replica-from-etcd in util.sh.\n     ETCD_APISERVER_CLIENT_CERT_PATH=\"${auth_dir}/etcd-apiserver-client.crt\"\n     echo \"${ETCD_APISERVER_CLIENT_CERT}\" | base64 --decode | gunzip > \"${ETCD_APISERVER_CLIENT_CERT_PATH}\"\n   fi\n}\n\n\nfunction docker-installed {\n    if systemctl cat docker.service &> /dev/null ; then\n        return 0\n    else\n        return 1\n    fi\n}\n\n# util function to add a docker option to daemon.json file only if the daemon.json file is present.\n# accepts only one argument (docker options)\nfunction addockeropt {\n\tDOCKER_OPTS_FILE=/etc/docker/daemon.json\n\tif [ \"$#\" -lt 1 ]; then\n\techo \"No arguments are passed while adding docker options. Expect one argument\"\n\texit 1\n\telif [ \"$#\" -gt 1 ]; then\n\techo \"Only one argument is accepted\"\n\texit 1\n\tfi\n\t# appends the given input to the docker opts file i.e. /etc/docker/daemon.json file\n\tif [ -f \"$DOCKER_OPTS_FILE\" ]; then\n\tcat >> \"${DOCKER_OPTS_FILE}\" <<EOF\n  $1\nEOF\n\tfi\n}\n\nfunction set_docker_options_non_ubuntu() {\n  # set docker options mtu and storage driver for non-ubuntu\n  # as it is default for ubuntu\n   if [[ -n \"$(command -v lsb_release)\" && $(lsb_release -si) == \"Ubuntu\" ]]; then\n      echo \"Not adding docker options on ubuntu, as these are default on ubuntu. Bailing out...\"\n      return\n   fi\n\n   addockeropt \"\\\"mtu\\\": 1460,\"\n   addockeropt \"\\\"storage-driver\\\": \\\"overlay2\\\",\"\n\n   echo \"setting live restore\"\n   # Disable live-restore if the environment variable is set.\n   if [[ \"${DISABLE_DOCKER_LIVE_RESTORE:-false}\" == \"true\" ]]; then\n      addockeropt \"\\\"live-restore\\\": \\\"false\\\",\"\n   fi\n}\n\nfunction assemble-docker-flags {\n  echo \"Assemble docker options\"\n\n    # log the contents of the /etc/docker/daemon.json if already exists\n  if [ -f /etc/docker/daemon.json ]; then\n    echo \"Contents of the old docker config\"\n    cat /etc/docker/daemon.json\n  fi\n\n  cat <<EOF >/etc/docker/daemon.json\n{\nEOF\n\naddockeropt \"\\\"pidfile\\\": \\\"/var/run/docker.pid\\\",\n  \\\"iptables\\\": false,\n  \\\"ip-masq\\\": false,\"\n\n  echo \"setting log-level\"\n  if [[ \"${TEST_CLUSTER:-}\" == \"true\" ]]; then\n    addockeropt \"\\\"log-level\\\": \\\"debug\\\",\"\n  else\n    addockeropt \"\\\"log-level\\\": \\\"warn\\\",\"\n  fi\n\n  echo \"setting network bridge\"\n  if [[ \"${NETWORK_PROVIDER:-}\" == \"kubenet\" || \"${NETWORK_PROVIDER:-}\" == \"cni\" ]]; then\n    # set docker0 cidr to private ip address range to avoid conflict with cbr0 cidr range\n    addockeropt \"\\\"bip\\\": \\\"169.254.123.1/24\\\",\"\n  else\n    addockeropt \"\\\"bridge\\\": \\\"cbr0\\\",\"\n  fi\n\n  echo \"setting registry mirror\"\n  # TODO (vteratipally)  move the registry-mirror completely to /etc/docker/daemon.json\n  local docker_opts=\"\"\n  # Decide whether to enable a docker registry mirror. This is taken from\n  # the \"kube-env\" metadata value.\n  if [[ -n \"${DOCKER_REGISTRY_MIRROR_URL:-}\" ]]; then\n      docker_opts+=\"--registry-mirror=${DOCKER_REGISTRY_MIRROR_URL} \"\n  fi\n\n  set_docker_options_non_ubuntu\n\n  echo \"setting docker logging options\"\n  # Configure docker logging\n  addockeropt \"\\\"log-driver\\\": \\\"${DOCKER_LOG_DRIVER:-json-file}\\\",\"\n  addockeropt \"\\\"log-opts\\\": {\n      \\\"max-size\\\": \\\"${DOCKER_LOG_MAX_SIZE:-10m}\\\",\n      \\\"max-file\\\": \\\"${DOCKER_LOG_MAX_FILE:-5}\\\"\n    }\"\n  cat <<EOF >>/etc/docker/daemon.json\n}\nEOF\n  echo \"DOCKER_OPTS=\\\"${docker_opts}${EXTRA_DOCKER_OPTS:-}\\\"\" > /etc/default/docker\n\n  # Ensure TasksMax is sufficient for docker.\n  # (https://github.com/kubernetes/kubernetes/issues/51977)\n  echo \"Extend the docker.service configuration to set a higher pids limit\"\n  mkdir -p /etc/systemd/system/docker.service.d\n  cat <<EOF >/etc/systemd/system/docker.service.d/01tasksmax.conf\n[Service]\nTasksMax=infinity\nEOF\n\n    systemctl daemon-reload\n    echo \"Docker command line is updated. Restart docker to pick it up\"\n    systemctl restart docker\n}\n\n# This function assembles the kubelet systemd service file and starts it\n# using systemctl.\nfunction start-kubelet {\n  echo \"Start kubelet\"\n\n  local kubelet_bin=\"${KUBE_HOME}/bin/kubelet\"\n  local -r version=\"$(\"${kubelet_bin}\" --version=true | cut -f2 -d \" \")\"\n  local -r builtin_kubelet=\"/usr/bin/kubelet\"\n  if [[ \"${TEST_CLUSTER:-}\" == \"true\" ]]; then\n    # Determine which binary to use on test clusters. We use the built-in\n    # version only if the downloaded version is the same as the built-in\n    # version. This allows GCI to run some of the e2e tests to qualify the\n    # built-in kubelet.\n    if [[ -x \"${builtin_kubelet}\" ]]; then\n      local -r builtin_version=\"$(\"${builtin_kubelet}\"  --version=true | cut -f2 -d \" \")\"\n      if [[ \"${builtin_version}\" == \"${version}\" ]]; then\n        kubelet_bin=\"${builtin_kubelet}\"\n      fi\n    fi\n  fi\n  echo \"Using kubelet binary at ${kubelet_bin}\"\n\n  local -r kubelet_env_file=\"/etc/default/kubelet\"\n  local kubelet_opts=\"${KUBELET_ARGS} ${KUBELET_CONFIG_FILE_ARG:-}\"\n  echo \"KUBELET_OPTS=\\\"${kubelet_opts}\\\"\" > \"${kubelet_env_file}\"\n  echo \"KUBE_COVERAGE_FILE=\\\"/var/log/kubelet.cov\\\"\" >> \"${kubelet_env_file}\"\n\n  # Write the systemd service file for kubelet.\n  cat <<EOF >/etc/systemd/system/kubelet.service\n[Unit]\nDescription=Kubernetes kubelet\nRequires=network-online.target\nAfter=network-online.target\n\n[Service]\nRestart=always\nRestartSec=10\nEnvironmentFile=${kubelet_env_file}\nExecStart=${kubelet_bin} \\$KUBELET_OPTS\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\n  systemctl daemon-reload\n  systemctl start kubelet.service\n}\n\n# This function assembles the node problem detector systemd service file and\n# starts it using systemctl.\nfunction start-node-problem-detector {\n  echo \"Start node problem detector\"\n  local -r npd_bin=\"${KUBE_HOME}/bin/node-problem-detector\"\n  echo \"Using node problem detector binary at ${npd_bin}\"\n\n  local flags=\"${NODE_PROBLEM_DETECTOR_CUSTOM_FLAGS:-}\"\n  if [[ -z \"${flags}\" ]]; then\n    local -r km_config=\"${KUBE_HOME}/node-problem-detector/config/kernel-monitor.json\"\n    # TODO(random-liu): Handle this for alternative container runtime.\n    local -r dm_config=\"${KUBE_HOME}/node-problem-detector/config/docker-monitor.json\"\n    local -r sm_config=\"${KUBE_HOME}/node-problem-detector/config/systemd-monitor.json\"\n    local -r ssm_config=\"${KUBE_HOME}/node-problem-detector/config/system-stats-monitor.json\"\n\n    local -r custom_km_config=\"${KUBE_HOME}/node-problem-detector/config/kernel-monitor-counter.json\"\n    local -r custom_sm_config=\"${KUBE_HOME}/node-problem-detector/config/systemd-monitor-counter.json\"\n\n    flags=\"${NPD_TEST_LOG_LEVEL:-\"--v=2\"} ${NPD_TEST_ARGS:-}\"\n    flags+=\" --logtostderr\"\n    flags+=\" --config.system-log-monitor=${km_config},${dm_config},${sm_config}\"\n    flags+=\" --config.system-stats-monitor=${ssm_config}\"\n    flags+=\" --config.custom-plugin-monitor=${custom_km_config},${custom_sm_config}\"\n    local -r npd_port=${NODE_PROBLEM_DETECTOR_PORT:-20256}\n    flags+=\" --port=${npd_port}\"\n    if [[ -n \"${EXTRA_NPD_ARGS:-}\" ]]; then\n      flags+=\" ${EXTRA_NPD_ARGS}\"\n    fi\n  fi\n  flags+=\" --apiserver-override=https://${KUBERNETES_MASTER_NAME}?inClusterConfig=false&auth=/var/lib/node-problem-detector/kubeconfig\"\n\n  # Write the systemd service file for node problem detector.\n  cat <<EOF >/etc/systemd/system/node-problem-detector.service\n[Unit]\nDescription=Kubernetes node problem detector\nRequires=network-online.target\nAfter=network-online.target\n\n[Service]\nRestart=always\nRestartSec=10\nExecStart=${npd_bin} ${flags}\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\n  systemctl start node-problem-detector.service\n}\n\n# Create the log file and set its properties.\n#\n# $1 is the file to create.\n# $2: the log owner uid to set for the log file.\n# $3: the log owner gid to set for the log file. If $KUBE_POD_LOG_READERS_GROUP\n# is set then this value will not be used.\nfunction prepare-log-file {\n  touch \"$1\"\n  if [[ -n \"${KUBE_POD_LOG_READERS_GROUP:-}\" ]]; then\n    chmod 640 \"$1\"\n    chown \"${2:-root}\":\"${KUBE_POD_LOG_READERS_GROUP}\" \"$1\"\n  else\n    chmod 644 \"$1\"\n    chown \"${2:-${LOG_OWNER_USER:-root}}\":\"${3:-${LOG_OWNER_GROUP:-root}}\" \"$1\"\n  fi\n}\n\n# Prepares parameters for kube-proxy manifest.\n# $1 source path of kube-proxy manifest.\n# Assumptions: HOST_PLATFORM and HOST_ARCH are specified by calling detect_host_info.\nfunction prepare-kube-proxy-manifest-variables {\n  local -r src_file=$1;\n\n  local -r kubeconfig=\"--kubeconfig=/var/lib/kube-proxy/kubeconfig\"\n  local kube_docker_registry=\"k8s.gcr.io\"\n  if [[ -n \"${KUBE_DOCKER_REGISTRY:-}\" ]]; then\n    kube_docker_registry=${KUBE_DOCKER_REGISTRY}\n  fi\n  local -r kube_proxy_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-proxy.docker_tag)\n  local api_servers=\"--master=https://${KUBERNETES_MASTER_NAME}\"\n  local params=\"${KUBEPROXY_TEST_LOG_LEVEL:-\"--v=2\"}\"\n  if [[ -n \"${FEATURE_GATES:-}\" ]]; then\n    params+=\" --feature-gates=${FEATURE_GATES}\"\n  fi\n  if [[ \"${KUBE_PROXY_MODE:-}\" == \"ipvs\" ]];then\n    # use 'nf_conntrack' instead of 'nf_conntrack_ipv4' for linux kernel >= 4.19\n    # https://github.com/kubernetes/kubernetes/pull/70398\n    local -r kernel_version=$(uname -r | cut -d\\. -f1,2)\n    local conntrack_module=\"nf_conntrack\"\n    if [[ $(printf '%s\\n4.18\\n' \"${kernel_version}\" | sort -V | tail -1) == \"4.18\" ]]; then\n      conntrack_module=\"nf_conntrack_ipv4\"\n    fi\n\n    if sudo modprobe -a ip_vs ip_vs_rr ip_vs_wrr ip_vs_sh ${conntrack_module}; then\n      params+=\" --proxy-mode=ipvs\"\n    else\n      # If IPVS modules are not present, make sure the node does not come up as\n      # healthy.\n      exit 1\n    fi\n  fi\n  params+=\" --iptables-sync-period=1m --iptables-min-sync-period=10s --ipvs-sync-period=1m --ipvs-min-sync-period=10s\"\n  if [[ -n \"${KUBEPROXY_TEST_ARGS:-}\" ]]; then\n    params+=\" ${KUBEPROXY_TEST_ARGS}\"\n  fi\n  if [[ -n \"${DETECT_LOCAL_MODE:-}\" ]]; then\n    params+=\" --detect-local-mode=${DETECT_LOCAL_MODE}\"\n  fi\n  local container_env=\"\"\n  local kube_cache_mutation_detector_env_name=\"\"\n  local kube_cache_mutation_detector_env_value=\"\"\n  if [[ -n \"${ENABLE_CACHE_MUTATION_DETECTOR:-}\" ]]; then\n    container_env=\"env:\"\n    kube_cache_mutation_detector_env_name=\"- name: KUBE_CACHE_MUTATION_DETECTOR\"\n    kube_cache_mutation_detector_env_value=\"value: \\\"${ENABLE_CACHE_MUTATION_DETECTOR}\\\"\"\n  fi\n  sed -i -e \"s@{{kubeconfig}}@${kubeconfig}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube_docker_registry'\\]}}@${kube_docker_registry}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube-proxy_docker_tag'\\]}}@${kube_proxy_docker_tag}@g\" \"${src_file}\"\n  # TODO(#99245): Use multi-arch image and get rid of this.\n  sed -i -e \"s@{{pillar\\['host_arch'\\]}}@${HOST_ARCH}@g\" \"${src_file}\"\n  sed -i -e \"s@{{params}}@${params}@g\" \"${src_file}\"\n  sed -i -e \"s@{{container_env}}@${container_env}@g\" \"${src_file}\"\n  sed -i -e \"s@{{kube_cache_mutation_detector_env_name}}@${kube_cache_mutation_detector_env_name}@g\" \"${src_file}\"\n  sed -i -e \"s@{{kube_cache_mutation_detector_env_value}}@${kube_cache_mutation_detector_env_value}@g\" \"${src_file}\"\n  sed -i -e \"s@{{ cpurequest }}@100m@g\" \"${src_file}\"\n  sed -i -e \"s@{{api_servers_with_port}}@${api_servers}@g\" \"${src_file}\"\n  sed -i -e \"s@{{kubernetes_service_host_env_value}}@${KUBERNETES_MASTER_NAME}@g\" \"${src_file}\"\n  if [[ -n \"${CLUSTER_IP_RANGE:-}\" ]]; then\n    sed -i -e \"s@{{cluster_cidr}}@--cluster-cidr=${CLUSTER_IP_RANGE}@g\" \"${src_file}\"\n  fi\n}\n\n# Starts kube-proxy static pod.\nfunction start-kube-proxy {\n  echo \"Start kube-proxy static pod\"\n  prepare-log-file /var/log/kube-proxy.log\n  local -r src_file=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-proxy.manifest\"\n  prepare-kube-proxy-manifest-variables \"${src_file}\"\n\n  cp \"${src_file}\" /etc/kubernetes/manifests\n}\n\n# Replaces the variables in the etcd manifest file with the real values, and then\n# copy the file to the manifest dir\n# $1: value for variable 'suffix'\n# $2: value for variable 'port'\n# $3: value for variable 'server_port'\n# $4: value for variable 'cpulimit'\n# $5: pod name, which should be either etcd or etcd-events\nfunction prepare-etcd-manifest {\n  local host_name=${ETCD_HOSTNAME:-$(hostname -s)}\n  local -r host_ip=$(python3 -c \"import socket;print(socket.gethostbyname(\\\"${host_name}\\\"))\")\n  local etcd_cluster=\"\"\n  local cluster_state=\"new\"\n  local etcd_protocol=\"http\"\n  local etcd_apiserver_protocol=\"http\"\n  local etcd_creds=\"\"\n  local etcd_apiserver_creds=\"${ETCD_APISERVER_CREDS:-}\"\n  local etcd_extra_args=\"${ETCD_EXTRA_ARGS:-}\"\n  local suffix=\"$1\"\n  local etcd_listen_metrics_port=\"$2\"\n  local etcdctl_certs=\"\"\n\n  if [[ -n \"${INITIAL_ETCD_CLUSTER_STATE:-}\" ]]; then\n    cluster_state=\"${INITIAL_ETCD_CLUSTER_STATE}\"\n  fi\n  if [[ -n \"${ETCD_CA_CERT:-}\" && -n \"${ETCD_PEER_KEY:-}\" && -n \"${ETCD_PEER_CERT:-}\" ]]; then\n    etcd_creds=\" --peer-trusted-ca-file /etc/srv/kubernetes/etcd-ca.crt --peer-cert-file /etc/srv/kubernetes/etcd-peer.crt --peer-key-file /etc/srv/kubernetes/etcd-peer.key -peer-client-cert-auth \"\n    etcd_protocol=\"https\"\n  fi\n\n  # mTLS should only be enabled for etcd server but not etcd-events. if $1 suffix is empty, it's etcd server.\n  if [[ -z \"${suffix}\" && -n \"${ETCD_APISERVER_CA_KEY:-}\" && -n \"${ETCD_APISERVER_CA_CERT:-}\" && -n \"${ETCD_APISERVER_SERVER_KEY:-}\" && -n \"${ETCD_APISERVER_SERVER_CERT:-}\" && -n \"${ETCD_APISERVER_CLIENT_KEY:-}\" && -n \"${ETCD_APISERVER_CLIENT_CERT:-}\" ]]; then\n    etcd_apiserver_creds=\" --client-cert-auth --trusted-ca-file ${ETCD_APISERVER_CA_CERT_PATH} --cert-file ${ETCD_APISERVER_SERVER_CERT_PATH} --key-file ${ETCD_APISERVER_SERVER_KEY_PATH} \"\n    etcdctl_certs=\"--cacert ${ETCD_APISERVER_CA_CERT_PATH} --cert ${ETCD_APISERVER_CLIENT_CERT_PATH} --key ${ETCD_APISERVER_CLIENT_KEY_PATH}\"\n    etcd_apiserver_protocol=\"https\"\n    etcd_listen_metrics_port=\"2382\"\n    etcd_extra_args+=\" --listen-metrics-urls=http://${ETCD_LISTEN_CLIENT_IP:-127.0.0.1}:${etcd_listen_metrics_port} \"\n  fi\n\n  if [[ -n \"${ETCD_PROGRESS_NOTIFY_INTERVAL:-}\" ]]; then\n    etcd_extra_args+=\" --experimental-watch-progress-notify-interval=${ETCD_PROGRESS_NOTIFY_INTERVAL}\"\n  fi\n\n  for host in $(echo \"${INITIAL_ETCD_CLUSTER:-${host_name}}\" | tr \",\" \"\\n\"); do\n    etcd_host=\"etcd-${host}=${etcd_protocol}://${host}:$3\"\n    if [[ -n \"${etcd_cluster}\" ]]; then\n      etcd_cluster+=\",\"\n    fi\n    etcd_cluster+=\"${etcd_host}\"\n  done\n\n  local -r temp_file=\"/tmp/$5\"\n  cp \"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/etcd.manifest\" \"${temp_file}\"\n  sed -i -e \"s@{{ *suffix *}}@$1@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *port *}}@$2@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *server_port *}}@$3@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *cpulimit *}}@\\\"$4\\\"@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *hostname *}}@$host_name@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *host_ip *}}@$host_ip@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcd_cluster *}}@$etcd_cluster@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *liveness_probe_initial_delay *}}@${ETCD_LIVENESS_PROBE_INITIAL_DELAY_SEC:-15}@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *listen_client_ip *}}@${ETCD_LISTEN_CLIENT_IP:-127.0.0.1}@g\" \"${temp_file}\"\n  # Get default storage backend from manifest file.\n  local -r default_storage_backend=$( \\\n    grep -o \"{{ *pillar\\.get('storage_backend', '\\(.*\\)') *}}\" \"${temp_file}\" | \\\n    sed -e \"s@{{ *pillar\\.get('storage_backend', '\\(.*\\)') *}}@\\1@g\")\n  if [[ -n \"${STORAGE_BACKEND:-}\" ]]; then\n    sed -i -e \"s@{{ *pillar\\.get('storage_backend', '\\(.*\\)') *}}@${STORAGE_BACKEND}@g\" \"${temp_file}\"\n  else\n    sed -i -e \"s@{{ *pillar\\.get('storage_backend', '\\(.*\\)') *}}@\\1@g\" \"${temp_file}\"\n  fi\n  if [[ \"${STORAGE_BACKEND:-${default_storage_backend}}\" == \"etcd3\" ]]; then\n    sed -i -e \"s@{{ *quota_bytes *}}@--quota-backend-bytes=${ETCD_QUOTA_BACKEND_BYTES:-4294967296}@g\" \"${temp_file}\"\n  else\n    sed -i -e \"s@{{ *quota_bytes *}}@@g\" \"${temp_file}\"\n  fi\n  sed -i -e \"s@{{ *cluster_state *}}@$cluster_state@g\" \"${temp_file}\"\n  if [[ -n \"${ETCD_IMAGE:-}\" ]]; then\n    sed -i -e \"s@{{ *pillar\\.get('etcd_docker_tag', '\\(.*\\)') *}}@${ETCD_IMAGE}@g\" \"${temp_file}\"\n  else\n    sed -i -e \"s@{{ *pillar\\.get('etcd_docker_tag', '\\(.*\\)') *}}@\\1@g\" \"${temp_file}\"\n  fi\n  if [[ -n \"${ETCD_DOCKER_REPOSITORY:-}\" ]]; then\n    sed -i -e \"s@{{ *pillar\\.get('etcd_docker_repository', '\\(.*\\)') *}}@${ETCD_DOCKER_REPOSITORY}@g\" \"${temp_file}\"\n  else\n    sed -i -e \"s@{{ *pillar\\.get('etcd_docker_repository', '\\(.*\\)') *}}@\\1@g\" \"${temp_file}\"\n  fi\n  sed -i -e \"s@{{ *etcd_protocol *}}@$etcd_protocol@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcd_apiserver_protocol *}}@$etcd_apiserver_protocol@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcd_creds *}}@$etcd_creds@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcdctl_certs *}}@$etcdctl_certs@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcd_apiserver_creds *}}@$etcd_apiserver_creds@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *etcd_extra_args *}}@$etcd_extra_args@g\" \"${temp_file}\"\n  if [[ -n \"${ETCD_VERSION:-}\" ]]; then\n    sed -i -e \"s@{{ *pillar\\.get('etcd_version', '\\(.*\\)') *}}@${ETCD_VERSION}@g\" \"${temp_file}\"\n  else\n    sed -i -e \"s@{{ *pillar\\.get('etcd_version', '\\(.*\\)') *}}@\\1@g\" \"${temp_file}\"\n  fi\n  # Replace the volume host path.\n  sed -i -e \"s@/mnt/master-pd/var/etcd@/mnt/disks/master-pd/var/etcd@g\" \"${temp_file}\"\n  # Replace the run as user and run as group\n  container_security_context=\"\"\n  if [[ -n \"${ETCD_RUNASUSER:-}\" && -n \"${ETCD_RUNASGROUP:-}\" ]]; then\n    container_security_context=\"\\\"securityContext\\\": {\\\"runAsUser\\\": ${ETCD_RUNASUSER}, \\\"runAsGroup\\\": ${ETCD_RUNASGROUP}, \\\"allowPrivilegeEscalation\\\": false, \\\"capabilities\\\": {\\\"drop\\\": [\\\"all\\\"]}},\"\n  fi\n  sed -i -e \"s@{{security_context}}@${container_security_context}@g\" \"${temp_file}\"\n  mv \"${temp_file}\" /etc/kubernetes/manifests\n}\n\n# Starts etcd server pod (and etcd-events pod if needed).\n# More specifically, it prepares dirs and files, sets the variable value\n# in the manifests, and copies them to /etc/kubernetes/manifests.\nfunction start-etcd-servers {\n  echo \"Start etcd pods\"\n  if [[ -d /etc/etcd ]]; then\n    rm -rf /etc/etcd\n  fi\n  if [[ -e /etc/default/etcd ]]; then\n    rm -f /etc/default/etcd\n  fi\n  if [[ -e /etc/systemd/system/etcd.service ]]; then\n    rm -f /etc/systemd/system/etcd.service\n  fi\n  if [[ -e /etc/init.d/etcd ]]; then\n    rm -f /etc/init.d/etcd\n  fi\n  if [[ -n \"${ETCD_RUNASUSER:-}\" && -n \"${ETCD_RUNASGROUP:-}\" ]]; then\n    chown -R \"${ETCD_RUNASUSER}\":\"${ETCD_RUNASGROUP}\" /mnt/disks/master-pd/var/etcd\n  fi\n  prepare-log-file /var/log/etcd.log \"${ETCD_RUNASUSER:-0}\"\n  prepare-etcd-manifest \"\" \"2379\" \"2380\" \"200m\" \"etcd.manifest\"\n\n  prepare-log-file /var/log/etcd-events.log \"${ETCD_RUNASUSER:-0}\"\n  prepare-etcd-manifest \"-events\" \"4002\" \"2381\" \"100m\" \"etcd-events.manifest\"\n}\n\n# Replaces the variables in the konnectivity-server manifest file with the real values, and then\n# copy the file to the manifest dir\n# $1: value for variable \"agent_port\"\n# $2: value for variable \"health_port\"\n# $3: value for variable \"admin_port\"\nfunction prepare-konnectivity-server-manifest {\n  local -r temp_file=\"/tmp/konnectivity-server.yaml\"\n  params=()\n  cp \"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/konnectivity-server.yaml\" \"${temp_file}\"\n  params+=(\"--log-file=/var/log/konnectivity-server.log\")\n  params+=(\"--logtostderr=false\")\n  params+=(\"--log-file-max-size=0\")\n  params+=(\"--uds-name=/etc/srv/kubernetes/konnectivity-server/konnectivity-server.socket\")\n  params+=(\"--cluster-cert=/etc/srv/kubernetes/pki/apiserver.crt\")\n  params+=(\"--cluster-key=/etc/srv/kubernetes/pki/apiserver.key\")\n  if [[ \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\" == 'grpc' ]]; then\n    params+=(\"--mode=grpc\")\n  elif [[ \"${KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE:-grpc}\" == 'http-connect' ]]; then\n    params+=(\"--mode=http-connect\")\n  else\n    echo \"KONNECTIVITY_SERVICE_PROXY_PROTOCOL_MODE must be set to either grpc or http-connect\"\n    exit 1\n  fi\n\n  params+=(\"--server-port=0\")\n  params+=(\"--agent-port=$1\")\n  params+=(\"--health-port=$2\")\n  params+=(\"--admin-port=$3\")\n  params+=(\"--agent-namespace=kube-system\")\n  params+=(\"--agent-service-account=konnectivity-agent\")\n  params+=(\"--kubeconfig=/etc/srv/kubernetes/konnectivity-server/kubeconfig\")\n  params+=(\"--authentication-audience=system:konnectivity-server\")\n  params+=(\"--kubeconfig-qps=75\")\n  params+=(\"--kubeconfig-burst=150\")\n  konnectivity_args=\"\"\n  for param in \"${params[@]}\"; do\n    konnectivity_args+=\", \\\"${param}\\\"\"\n  done\n  sed -i -e \"s@{{ *konnectivity_args *}}@${konnectivity_args}@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *agent_port *}}@$1@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *health_port *}}@$2@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *admin_port *}}@$3@g\" \"${temp_file}\"\n  sed -i -e \"s@{{ *liveness_probe_initial_delay *}}@30@g\" \"${temp_file}\"\n  if [[ -n \"${KONNECTIVITY_SERVER_RUNASUSER:-}\" && -n \"${KONNECTIVITY_SERVER_RUNASGROUP:-}\" && -n \"${KONNECTIVITY_SERVER_SOCKET_WRITER_GROUP:-}\" ]]; then\n    sed -i -e \"s@{{ *run_as_user *}}@runAsUser: ${KONNECTIVITY_SERVER_RUNASUSER}@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *run_as_group *}}@runAsGroup: ${KONNECTIVITY_SERVER_RUNASGROUP}@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *supplemental_groups *}}@supplementalGroups: [${KUBE_PKI_READERS_GROUP}]@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *container_security_context *}}@securityContext:@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *capabilities *}}@capabilities:@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *drop_capabilities *}}@drop: [ ALL ]@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *disallow_privilege_escalation *}}@allowPrivilegeEscalation: false@g\" \"${temp_file}\"\n    mkdir -p /etc/srv/kubernetes/konnectivity-server/\n    chown -R \"${KONNECTIVITY_SERVER_RUNASUSER}\":\"${KONNECTIVITY_SERVER_RUNASGROUP}\" /etc/srv/kubernetes/konnectivity-server\n    chmod g+w /etc/srv/kubernetes/konnectivity-server\n  else\n    sed -i -e \"s@{{ *run_as_user *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *run_as_group *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *supplemental_groups *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *container_security_context *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *capabilities *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *drop_capabilities *}}@@g\" \"${temp_file}\"\n    sed -i -e \"s@{{ *disallow_privilege_escalation *}}@@g\" \"${temp_file}\"\n  fi\n  mv \"${temp_file}\" /etc/kubernetes/manifests\n}\n\n# Starts konnectivity server pod.\n# More specifically, it prepares dirs and files, sets the variable value\n# in the manifests, and copies them to /etc/kubernetes/manifests.\nfunction start-konnectivity-server {\n  echo \"Start konnectivity server pods\"\n  prepare-log-file /var/log/konnectivity-server.log \"${KONNECTIVITY_SERVER_RUNASUSER:-0}\"\n  prepare-konnectivity-server-manifest \"8132\" \"8133\" \"8134\"\n}\n\n# Calculates the following variables based on env variables, which will be used\n# by the manifests of several kube-master components.\n#   CLOUD_CONFIG_OPT\n#   CLOUD_CONFIG_VOLUME\n#   CLOUD_CONFIG_MOUNT\n#   DOCKER_REGISTRY\n#   FLEXVOLUME_HOSTPATH_MOUNT\n#   FLEXVOLUME_HOSTPATH_VOLUME\n#   INSECURE_PORT_MAPPING\nfunction compute-master-manifest-variables {\n  CLOUD_CONFIG_OPT=\"\"\n  CLOUD_CONFIG_VOLUME=\"\"\n  CLOUD_CONFIG_MOUNT=\"\"\n  if [[ -f /etc/gce.conf ]]; then\n    CLOUD_CONFIG_OPT=\"--cloud-config=/etc/gce.conf\"\n    CLOUD_CONFIG_VOLUME=\"{\\\"name\\\": \\\"cloudconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"/etc/gce.conf\\\", \\\"type\\\": \\\"FileOrCreate\\\"}},\"\n    CLOUD_CONFIG_MOUNT=\"{\\\"name\\\": \\\"cloudconfigmount\\\",\\\"mountPath\\\": \\\"/etc/gce.conf\\\", \\\"readOnly\\\": true},\"\n  fi\n  DOCKER_REGISTRY=\"k8s.gcr.io\"\n  if [[ -n \"${KUBE_DOCKER_REGISTRY:-}\" ]]; then\n    DOCKER_REGISTRY=\"${KUBE_DOCKER_REGISTRY}\"\n  fi\n\n  FLEXVOLUME_HOSTPATH_MOUNT=\"\"\n  FLEXVOLUME_HOSTPATH_VOLUME=\"\"\n  if [[ -n \"${VOLUME_PLUGIN_DIR:-}\" ]]; then\n    FLEXVOLUME_HOSTPATH_MOUNT=\"{ \\\"name\\\": \\\"flexvolumedir\\\", \\\"mountPath\\\": \\\"${VOLUME_PLUGIN_DIR}\\\", \\\"readOnly\\\": true},\"\n    FLEXVOLUME_HOSTPATH_VOLUME=\"{ \\\"name\\\": \\\"flexvolumedir\\\", \\\"hostPath\\\": {\\\"path\\\": \\\"${VOLUME_PLUGIN_DIR}\\\"}},\"\n  fi\n\n  INSECURE_PORT_MAPPING=\"\"\n  if [[ \"${ENABLE_APISERVER_INSECURE_PORT:-false}\" == \"true\" ]]; then\n    # INSECURE_PORT_MAPPING is used by sed\n    # shellcheck disable=SC2089\n    INSECURE_PORT_MAPPING='{ \"name\": \"local\", \"containerPort\": 8080, \"hostPort\": 8080},'\n  fi\n  # shellcheck disable=SC2090\n  export INSECURE_PORT_MAPPING\n}\n\n# A helper function that bind mounts kubelet dirs for running mount in a chroot\nfunction prepare-mounter-rootfs {\n  echo \"Prepare containerized mounter\"\n  mount --bind \"${CONTAINERIZED_MOUNTER_HOME}\" \"${CONTAINERIZED_MOUNTER_HOME}\"\n  mount -o remount,exec \"${CONTAINERIZED_MOUNTER_HOME}\"\n  CONTAINERIZED_MOUNTER_ROOTFS=\"${CONTAINERIZED_MOUNTER_HOME}/rootfs\"\n  mount --rbind /var/lib/kubelet/ \"${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet\"\n  mount --make-rshared \"${CONTAINERIZED_MOUNTER_ROOTFS}/var/lib/kubelet\"\n  mount --bind -o ro /proc \"${CONTAINERIZED_MOUNTER_ROOTFS}/proc\"\n  mount --bind -o ro /dev \"${CONTAINERIZED_MOUNTER_ROOTFS}/dev\"\n  cp /etc/resolv.conf \"${CONTAINERIZED_MOUNTER_ROOTFS}/etc/\"\n}\n\n# Updates node labels used by addons.\nfunction update-legacy-addon-node-labels() {\n  # need kube-apiserver to be ready\n  until kubectl get nodes; do\n    sleep 5\n  done\n  update-node-label \"beta.kubernetes.io/metadata-proxy-ready=true,cloud.google.com/metadata-proxy-ready!=true\" \"cloud.google.com/metadata-proxy-ready=true\"\n  update-node-label \"beta.kubernetes.io/kube-proxy-ds-ready=true,node.kubernetes.io/kube-proxy-ds-ready!=true\" \"node.kubernetes.io/kube-proxy-ds-ready=true\"\n  update-node-label \"beta.kubernetes.io/masq-agent-ds-ready=true,node.kubernetes.io/masq-agent-ds-ready!=true\" \"node.kubernetes.io/masq-agent-ds-ready=true\"\n}\n\n# A helper function for labeling all nodes matching a given selector.\n# Runs: kubectl label --overwrite nodes -l \"${1}\" \"${2}\"\n# Retries on failure\n#\n# $1: label selector of nodes\n# $2: label to apply\nfunction update-node-label() {\n  local selector=\"$1\"\n  local label=\"$2\"\n  local retries=5\n  until (( retries == 0 )); do\n    if kubectl label --overwrite nodes -l \"${selector}\" \"${label}\"; then\n      break\n    fi\n    (( retries-- ))\n    sleep 3\n  done\n}\n\n# Starts kubernetes controller manager.\n# It prepares the log file, loads the docker image, calculates variables, sets them\n# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.\n#\n# Assumed vars (which are calculated in function compute-master-manifest-variables)\n#   CLOUD_CONFIG_OPT\n#   CLOUD_CONFIG_VOLUME\n#   CLOUD_CONFIG_MOUNT\n#   DOCKER_REGISTRY\nfunction start-kube-controller-manager {\n  if [[ -e \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\" ]]; then\n    if ! deploy-kube-controller-manager-via-kube-up; then\n      echo \"kube-controller-manager is configured to not be deployed through kube-up.\"\n      return\n    fi\n  fi\n  echo \"Start kubernetes controller-manager\"\n  create-kubeconfig \"kube-controller-manager\" \"${KUBE_CONTROLLER_MANAGER_TOKEN}\"\n  prepare-log-file /var/log/kube-controller-manager.log \"${KUBE_CONTROLLER_MANAGER_RUNASUSER:-0}\"\n  # Calculate variables and assemble the command line.\n  local params=(\"${CONTROLLER_MANAGER_TEST_LOG_LEVEL:-\"--v=2\"}\" \"${CONTROLLER_MANAGER_TEST_ARGS:-}\" \"${CLOUD_CONFIG_OPT}\")\n  local config_path='/etc/srv/kubernetes/kube-controller-manager/kubeconfig'\n  params+=(\"--use-service-account-credentials\")\n  params+=(\"--cloud-provider=gce\")\n  params+=(\"--kubeconfig=${config_path}\" \"--authentication-kubeconfig=${config_path}\" \"--authorization-kubeconfig=${config_path}\")\n  params+=(\"--root-ca-file=${CA_CERT_BUNDLE_PATH}\")\n  params+=(\"--service-account-private-key-file=${SERVICEACCOUNT_KEY_PATH}\")\n  params+=(\"--volume-host-allow-local-loopback=false\")\n  if [[ -n \"${ENABLE_GARBAGE_COLLECTOR:-}\" ]]; then\n    params+=(\"--enable-garbage-collector=${ENABLE_GARBAGE_COLLECTOR}\")\n  fi\n  if [[ -n \"${INSTANCE_PREFIX:-}\" ]]; then\n    params+=(\"--cluster-name=${INSTANCE_PREFIX}\")\n  fi\n  if [[ -n \"${CLUSTER_IP_RANGE:-}\" ]]; then\n    params+=(\"--cluster-cidr=${CLUSTER_IP_RANGE}\")\n  fi\n  if [[ -n \"${CA_KEY:-}\" ]]; then\n    params+=(\"--cluster-signing-cert-file=${CA_CERT_PATH}\")\n    params+=(\"--cluster-signing-key-file=${CA_KEY_PATH}\")\n  fi\n  if [[ -n \"${SERVICE_CLUSTER_IP_RANGE:-}\" ]]; then\n    params+=(\"--service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}\")\n  fi\n  if [[ -n \"${CONCURRENT_SERVICE_SYNCS:-}\" ]]; then\n    params+=(\"--concurrent-service-syncs=${CONCURRENT_SERVICE_SYNCS}\")\n  fi\n  if [[ \"${NETWORK_PROVIDER:-}\" == \"kubenet\" ]]; then\n    params+=(\"--allocate-node-cidrs=true\")\n  elif [[ -n \"${ALLOCATE_NODE_CIDRS:-}\" ]]; then\n    params+=(\"--allocate-node-cidrs=${ALLOCATE_NODE_CIDRS}\")\n  fi\n  if [[ -n \"${TERMINATED_POD_GC_THRESHOLD:-}\" ]]; then\n    params+=(\"--terminated-pod-gc-threshold=${TERMINATED_POD_GC_THRESHOLD}\")\n  fi\n  if [[ \"${ENABLE_IP_ALIASES:-}\" == 'true' ]]; then\n    params+=(\"--cidr-allocator-type=${NODE_IPAM_MODE}\")\n    params+=(\"--configure-cloud-routes=false\")\n  fi\n  if [[ -n \"${FEATURE_GATES:-}\" ]]; then\n    params+=(\"--feature-gates=${FEATURE_GATES}\")\n  fi\n  if [[ -n \"${VOLUME_PLUGIN_DIR:-}\" ]]; then\n    params+=(\"--flex-volume-plugin-dir=${VOLUME_PLUGIN_DIR}\")\n  fi\n  if [[ -n \"${CLUSTER_SIGNING_DURATION:-}\" ]]; then\n    params+=(\"--cluster-signing-duration=$CLUSTER_SIGNING_DURATION\")\n  fi\n  if [[ -n \"${PV_RECYCLER_OVERRIDE_TEMPLATE:-}\" ]]; then\n    params+=(\"--pv-recycler-pod-template-filepath-nfs=$PV_RECYCLER_OVERRIDE_TEMPLATE\")\n    params+=(\"--pv-recycler-pod-template-filepath-hostpath=$PV_RECYCLER_OVERRIDE_TEMPLATE\")\n  fi\n  if [[ -n \"${RUN_CONTROLLERS:-}\" ]]; then\n    params+=(\"--controllers=${RUN_CONTROLLERS}\")\n  fi\n\n  local -r kube_rc_docker_tag=$(cat /home/kubernetes/kube-docker-files/kube-controller-manager.docker_tag)\n  local container_env=\"\"\n  if [[ -n \"${ENABLE_CACHE_MUTATION_DETECTOR:-}\" ]]; then\n    container_env=\"\\\"env\\\":[{\\\"name\\\": \\\"KUBE_CACHE_MUTATION_DETECTOR\\\", \\\"value\\\": \\\"${ENABLE_CACHE_MUTATION_DETECTOR}\\\"}],\"\n  fi\n\n  local paramstring\n  paramstring=\"$(convert-manifest-params \"${params[*]}\")\"\n  local -r src_file=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-controller-manager.manifest\"\n  # Evaluate variables.\n  sed -i -e \"s@{{pillar\\['kube_docker_registry'\\]}}@${DOCKER_REGISTRY}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube-controller-manager_docker_tag'\\]}}@${kube_rc_docker_tag}@g\" \"${src_file}\"\n  sed -i -e \"s@{{params}}@${paramstring}@g\" \"${src_file}\"\n  sed -i -e \"s@{{container_env}}@${container_env}@g\" \"${src_file}\"\n  sed -i -e \"s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g\" \"${src_file}\"\n  sed -i -e \"s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g\" \"${src_file}\"\n  sed -i -e \"s@{{additional_cloud_config_mount}}@@g\" \"${src_file}\"\n  sed -i -e \"s@{{additional_cloud_config_volume}}@@g\" \"${src_file}\"\n  sed -i -e \"s@{{pv_recycler_mount}}@${PV_RECYCLER_MOUNT}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pv_recycler_volume}}@${PV_RECYCLER_VOLUME}@g\" \"${src_file}\"\n  sed -i -e \"s@{{flexvolume_hostpath_mount}}@${FLEXVOLUME_HOSTPATH_MOUNT}@g\" \"${src_file}\"\n  sed -i -e \"s@{{flexvolume_hostpath}}@${FLEXVOLUME_HOSTPATH_VOLUME}@g\" \"${src_file}\"\n  sed -i -e \"s@{{cpurequest}}@${KUBE_CONTROLLER_MANAGER_CPU_REQUEST}@g\" \"${src_file}\"\n\n  if [[ -n \"${KUBE_CONTROLLER_MANAGER_RUNASUSER:-}\" && -n \"${KUBE_CONTROLLER_MANAGER_RUNASGROUP:-}\" ]]; then\n    sed -i -e \"s@{{runAsUser}}@\\\"runAsUser\\\": ${KUBE_CONTROLLER_MANAGER_RUNASUSER},@g\" \"${src_file}\"\n    sed -i -e \"s@{{runAsGroup}}@\\\"runAsGroup\\\":${KUBE_CONTROLLER_MANAGER_RUNASGROUP},@g\" \"${src_file}\"\n    sed -i -e \"s@{{supplementalGroups}}@\\\"supplementalGroups\\\": [ ${KUBE_PKI_READERS_GROUP} ],@g\" \"${src_file}\"\n  else\n    sed -i -e \"s@{{runAsUser}}@@g\" \"${src_file}\"\n    sed -i -e \"s@{{runAsGroup}}@@g\" \"${src_file}\"\n    sed -i -e \"s@{{supplementalGroups}}@@g\" \"${src_file}\"\n  fi\n\n  cp \"${src_file}\" /etc/kubernetes/manifests\n}\n\n# Starts kubernetes scheduler.\n# It prepares the log file, loads the docker image, calculates variables, sets them\n# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.\n#\n# Assumed vars (which are calculated in compute-master-manifest-variables)\n#   DOCKER_REGISTRY\nfunction start-kube-scheduler {\n  if [[ -e \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\" ]]; then\n    if ! deploy-kube-scheduler-via-kube-up; then\n      echo \"kube-scheduler is configured to not be deployed through kube-up.\"\n      return\n    fi\n  fi\n  echo \"Start kubernetes scheduler\"\n  create-kubeconfig \"kube-scheduler\" \"${KUBE_SCHEDULER_TOKEN}\"\n  # User and group should never contain characters that need to be quoted\n  # shellcheck disable=SC2086\n  prepare-log-file /var/log/kube-scheduler.log ${KUBE_SCHEDULER_RUNASUSER:-2001}\n\n  # Calculate variables and set them in the manifest.\n  params=(\"${SCHEDULER_TEST_LOG_LEVEL:-\"--v=2\"}\" \"${SCHEDULER_TEST_ARGS:-}\")\n  if [[ -n \"${FEATURE_GATES:-}\" ]]; then\n    params+=(\"--feature-gates=${FEATURE_GATES}\")\n  fi\n\n  # Scheduler Component Config takes precedence over some flags.\n  if [[ -n \"${KUBE_SCHEDULER_CONFIG:-}\" ]]; then\n    create-kube-scheduler-config\n    params+=(\"--config=/etc/srv/kubernetes/kube-scheduler/config\")\n  else\n    params+=(\"--kubeconfig=/etc/srv/kubernetes/kube-scheduler/kubeconfig\")\n    if [[ -n \"${SCHEDULER_POLICY_CONFIG:-}\" ]]; then\n      create-kubescheduler-policy-config\n      params+=(\"--use-legacy-policy-config\")\n      params+=(\"--policy-config-file=/etc/srv/kubernetes/kube-scheduler/policy-config\")\n    fi\n  fi\n\n  local config_path\n  config_path='/etc/srv/kubernetes/kube-scheduler/kubeconfig'\n  params+=(\"--authentication-kubeconfig=${config_path}\" \"--authorization-kubeconfig=${config_path}\")\n\n  local paramstring\n  paramstring=\"$(convert-manifest-params \"${params[*]}\")\"\n  local -r kube_scheduler_docker_tag=$(cat \"${KUBE_HOME}/kube-docker-files/kube-scheduler.docker_tag\")\n\n  # Remove salt comments and replace variables with values.\n  local -r src_file=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/kube-scheduler.manifest\"\n\n  sed -i -e \"s@{{params}}@${paramstring}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube_docker_registry'\\]}}@${DOCKER_REGISTRY}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube-scheduler_docker_tag'\\]}}@${kube_scheduler_docker_tag}@g\" \"${src_file}\"\n  sed -i -e \"s@{{cpurequest}}@${KUBE_SCHEDULER_CPU_REQUEST}@g\" \"${src_file}\"\n  sed -i -e \"s@{{runAsUser}}@${KUBE_SCHEDULER_RUNASUSER:-2001}@g\" \"${src_file}\"\n  sed -i -e \"s@{{runAsGroup}}@${KUBE_SCHEDULER_RUNASGROUP:-2001}@g\" \"${src_file}\"\n  cp \"${src_file}\" /etc/kubernetes/manifests\n}\n\n# Starts cluster autoscaler.\n# Assumed vars (which are calculated in function compute-master-manifest-variables)\n#   CLOUD_CONFIG_OPT\n#   CLOUD_CONFIG_VOLUME\n#   CLOUD_CONFIG_MOUNT\nfunction start-cluster-autoscaler {\n  if [[ \"${ENABLE_CLUSTER_AUTOSCALER:-}\" == \"true\" ]]; then\n    echo \"Start kubernetes cluster autoscaler\"\n    setup-addon-manifests \"addons\" \"rbac/cluster-autoscaler\"\n    create-kubeconfig \"cluster-autoscaler\" \"${KUBE_CLUSTER_AUTOSCALER_TOKEN}\"\n    prepare-log-file /var/log/cluster-autoscaler.log\n\n    # Remove salt comments and replace variables with values\n    local -r src_file=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/cluster-autoscaler.manifest\"\n\n    local params\n    read -r -a params <<< \"${AUTOSCALER_MIG_CONFIG}\"\n    params+=(\"${CLOUD_CONFIG_OPT}\" \"${AUTOSCALER_EXPANDER_CONFIG:---expander=price}\")\n    params+=(\"--kubeconfig=/etc/srv/kubernetes/cluster-autoscaler/kubeconfig\")\n\n    # split the params into separate arguments passed to binary\n    local params_split\n    params_split=$(eval 'for param in \"${params[@]}\"; do echo -n \\\"\"$param\"\\\",; done')\n    params_split=${params_split%?}\n\n    sed -i -e \"s@{{params}}@${params_split}@g\" \"${src_file}\"\n    sed -i -e \"s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g\" \"${src_file}\"\n    sed -i -e \"s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g\" \"${src_file}\"\n    sed -i -e \"s@{%.*%}@@g\" \"${src_file}\"\n\n    cp \"${src_file}\" /etc/kubernetes/manifests\n  fi\n}\n\n# A helper function for setting up addon manifests.\n#\n# $1: addon category under /etc/kubernetes\n# $2: manifest source dir\n# $3: (optional) auxiliary manifest source dir\nfunction setup-addon-manifests {\n  local -r src_dir=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty\"\n  local -r dst_dir=\"/etc/kubernetes/$1/$2\"\n\n  copy-manifests \"${src_dir}/$2\" \"${dst_dir}\"\n\n  # If the PodSecurityPolicy admission controller is enabled,\n  # set up the corresponding addon policies.\n  if [[ \"${ENABLE_POD_SECURITY_POLICY:-}\" == \"true\" ]]; then\n    local -r psp_dir=\"${src_dir}/${3:-$2}/podsecuritypolicies\"\n    if [[ -d \"${psp_dir}\" ]]; then\n      copy-manifests \"${psp_dir}\" \"${dst_dir}\"\n    fi\n  fi\n}\n\n# A function that downloads extra addons from a URL and puts them in the GCI\n# manifests directory.\nfunction download-extra-addons {\n  local -r out_dir=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/gce-extras\"\n\n  mkdir -p \"${out_dir}\"\n\n  # shellcheck disable=SC2206\n  local curl_cmd=(\n    \"curl\"\n    ${CURL_FLAGS}\n  )\n  if [[ -n \"${EXTRA_ADDONS_HEADER:-}\" ]]; then\n    curl_cmd+=(\"-H\" \"${EXTRA_ADDONS_HEADER}\")\n  fi\n  curl_cmd+=(\"-o\" \"${out_dir}/extras.json\")\n  curl_cmd+=(\"${EXTRA_ADDONS_URL}\")\n\n  \"${curl_cmd[@]}\"\n}\n\n# A function that fetches a GCE metadata value and echoes it out.\n# Args:\n#   $1 : URL path after /computeMetadata/v1/ (without heading slash).\n#   $2 : An optional default value to echo out if the fetch fails.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction get-metadata-value {\n  local default=\"${2:-}\"\n\n  local status\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    -H 'Metadata-Flavor: Google' \\\n    \"http://metadata/computeMetadata/v1/${1}\" \\\n  || status=\"$?\"\n  status=\"${status:-0}\"\n\n  if [[ \"${status}\" -eq 0 || -z \"${default}\" ]]; then\n    return \"${status}\"\n  else\n    echo \"${default}\"\n  fi\n}\n\n# A helper function for copying manifests and setting dir/files\n# permissions.\n#\n# $1: absolute source dir\n# $2: absolute destination dir\nfunction copy-manifests {\n  local -r src_dir=\"$1\"\n  local -r dst_dir=\"$2\"\n  if [[ ! -d \"${dst_dir}\" ]]; then\n    mkdir -p \"${dst_dir}\"\n  fi\n  if [[ -n \"$(ls \"${src_dir}\"/*.yaml 2>/dev/null)\" ]]; then\n    cp \"${src_dir}/\"*.yaml \"${dst_dir}\"\n  fi\n  if [[ -n \"$(ls \"${src_dir}\"/*.json 2>/dev/null)\" ]]; then\n    cp \"${src_dir}/\"*.json \"${dst_dir}\"\n  fi\n  if [[ -n \"$(ls \"${src_dir}\"/*.yaml.in 2>/dev/null)\" ]]; then\n    cp \"${src_dir}/\"*.yaml.in \"${dst_dir}\"\n  fi\n  chown -R root:root \"${dst_dir}\"\n  chmod 755 \"${dst_dir}\"\n  chmod 644 \"${dst_dir}\"/*\n}\n\n# Fluentd resources are modified using ScalingPolicy CR, which may not be\n# available at this point. Run this as a background process.\nfunction wait-for-apiserver-and-update-fluentd {\n  local any_overrides=false\n  if [[ -n \"${FLUENTD_GCP_MEMORY_LIMIT:-}\" ]]; then\n    any_overrides=true\n  fi\n  if [[ -n \"${FLUENTD_GCP_CPU_REQUEST:-}\" ]]; then\n    any_overrides=true\n  fi\n  if [[ -n \"${FLUENTD_GCP_MEMORY_REQUEST:-}\" ]]; then\n    any_overrides=true\n  fi\n  if ! $any_overrides; then\n    # Nothing to do here.\n    exit\n  fi\n\n  # Wait until ScalingPolicy CRD is in place.\n  until kubectl get scalingpolicies.scalingpolicy.kope.io\n  do\n    sleep 10\n  done\n\n  # Single-shot, not managed by addon manager. Can be later modified or removed\n  # at will.\n  cat <<EOF | kubectl apply -f -\napiVersion: scalingpolicy.kope.io/v1alpha1\nkind: ScalingPolicy\nmetadata:\n  name: fluentd-gcp-scaling-policy\n  namespace: kube-system\nspec:\n  containers:\n  - name: fluentd-gcp\n    resources:\n      requests:\n      - resource: cpu\n        base: ${FLUENTD_GCP_CPU_REQUEST:-}\n      - resource: memory\n        base: ${FLUENTD_GCP_MEMORY_REQUEST:-}\n      limits:\n      - resource: memory\n        base: ${FLUENTD_GCP_MEMORY_LIMIT:-}\nEOF\n}\n\n# Trigger background process that will ultimately update fluentd resource\n# requirements.\nfunction start-fluentd-resource-update {\n  wait-for-apiserver-and-update-fluentd &\n}\n\n# VolumeSnapshot CRDs and controller are installed by cluster addon manager,\n# which may not be available at this point. Run this as a background process.\nfunction wait-for-volumesnapshot-crd-and-controller {\n  # Wait until volumesnapshot CRDs and controller are in place.\n  echo \"Wait until volume snapshot CRDs are installed\"\n  until kubectl get volumesnapshotclasses.snapshot.storage.k8s.io\n  do\n    sleep 10\n  done\n\n  until kubectl get volumesnapshotcontents.snapshot.storage.k8s.io\n  do\n    sleep 10\n  done\n\n  until kubectl get volumesnapshots.snapshot.storage.k8s.io\n  do\n    sleep 10\n  done\n\n  echo \"Wait until volume snapshot RBAC rules are installed\"\n  until kubectl get clusterrolebinding volume-snapshot-controller-role\n  do\n    sleep 10\n  done\n\n  echo \"Wait until volume snapshot controller is installed\"\n  until kubectl get statefulset volume-snapshot-controller | grep volume-snapshot-controller | grep \"1/1\"\n  do\n    sleep 10\n  done\n}\n\n# Trigger background process that will wait for volumesnapshot CRDs\n# and snapshot-controller to be installed\nfunction start-volumesnapshot-crd-and-controller {\n  wait-for-volumesnapshot-crd-and-controller &\n}\n\n# Update {{ fluentd_container_runtime_service }} with actual container runtime name,\n# and {{ container_runtime_endpoint }} with actual container runtime\n# endpoint.\nfunction update-container-runtime {\n  local -r file=\"$1\"\n  local -r container_runtime_endpoint=\"${CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}\"\n  sed -i \\\n    -e \"s@{{ *fluentd_container_runtime_service *}}@${FLUENTD_CONTAINER_RUNTIME_SERVICE:-${CONTAINER_RUNTIME_NAME:-docker}}@g\" \\\n    -e \"s@{{ *container_runtime_endpoint *}}@${container_runtime_endpoint#unix://}@g\" \\\n    \"${file}\"\n}\n\n# Remove configuration in yaml file if node journal is not enabled.\nfunction update-node-journal {\n  local -r configmap_yaml=\"$1\"\n  if [[ \"${ENABLE_NODE_JOURNAL:-}\" != \"true\" ]]; then\n    # Removes all lines between two patterns (throws away node-journal)\n    sed -i -e \"/# BEGIN_NODE_JOURNAL/,/# END_NODE_JOURNAL/d\" \"${configmap_yaml}\"\n  fi\n}\n\n# Updates parameters in yaml file for prometheus-to-sd configuration, or\n# removes component if it is disabled.\nfunction update-prometheus-to-sd-parameters {\n  if [[ \"${ENABLE_PROMETHEUS_TO_SD:-}\" == \"true\" ]]; then\n    sed -i -e \"s@{{ *prometheus_to_sd_prefix *}}@${PROMETHEUS_TO_SD_PREFIX}@g\" \"$1\"\n    sed -i -e \"s@{{ *prometheus_to_sd_endpoint *}}@${PROMETHEUS_TO_SD_ENDPOINT}@g\" \"$1\"\n  else\n    # Removes all lines between two patterns (throws away prometheus-to-sd)\n    sed -i -e \"/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d\" \"$1\"\n   fi\n}\n\n# Updates parameters in yaml file for prometheus-to-sd configuration in daemon sets, or\n# removes component if it is disabled.\nfunction update-daemon-set-prometheus-to-sd-parameters {\n  if [[ \"${DISABLE_PROMETHEUS_TO_SD_IN_DS:-}\" == \"true\" ]]; then\n    # Removes all lines between two patterns (throws away prometheus-to-sd)\n    sed -i -e \"/# BEGIN_PROMETHEUS_TO_SD/,/# END_PROMETHEUS_TO_SD/d\" \"$1\"\n  else\n    update-prometheus-to-sd-parameters \"$1\"\n  fi\n}\n\n# Updates parameters in yaml file for event-exporter configuration\nfunction update-event-exporter {\n    local -r stackdriver_resource_model=\"${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}\"\n    sed -i -e \"s@{{ exporter_sd_resource_model }}@${stackdriver_resource_model}@g\" \"$1\"\n    sed -i -e \"s@{{ exporter_sd_endpoint }}@${STACKDRIVER_ENDPOINT:-}@g\" \"$1\"\n}\n\nfunction update-dashboard-deployment {\n  if [ -n \"${CUSTOM_KUBE_DASHBOARD_BANNER:-}\" ]; then\n    sed -i -e \"s@\\( \\+\\)# PLATFORM-SPECIFIC ARGS HERE@\\1- --system-banner=${CUSTOM_KUBE_DASHBOARD_BANNER}\\n\\1- --system-banner-severity=WARNING@\" \"$1\"\n  fi\n}\n\n# Sets up the manifests of coreDNS for k8s addons.\nfunction setup-coredns-manifest {\n  setup-addon-manifests \"addons\" \"0-dns/coredns\"\n  local -r coredns_file=\"${dst_dir}/0-dns/coredns/coredns.yaml\"\n  mv \"${dst_dir}/0-dns/coredns/coredns.yaml.in\" \"${coredns_file}\"\n  # Replace the salt configurations with variable values.\n  sed -i -e \"s@dns_domain@${DNS_DOMAIN}@g\" \"${coredns_file}\"\n  sed -i -e \"s@dns_server@${DNS_SERVER_IP}@g\" \"${coredns_file}\"\n  sed -i -e \"s@{{ *pillar\\['service_cluster_ip_range'\\] *}}@${SERVICE_CLUSTER_IP_RANGE}@g\" \"${coredns_file}\"\n  sed -i -e \"s@dns_memory_limit@${DNS_MEMORY_LIMIT:-170Mi}@g\" \"${coredns_file}\"\n\n  if [[ \"${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"dns-horizontal-autoscaler\" \"gce\"\n    local -r dns_autoscaler_file=\"${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml\"\n    sed -i'' -e \"s@{{.Target}}@${COREDNS_AUTOSCALER}@g\" \"${dns_autoscaler_file}\"\n  fi\n}\n\n# Sets up the manifests of Fluentd configmap and yamls for k8s addons.\nfunction setup-fluentd {\n  local -r dst_dir=\"$1\"\n  local -r fluentd_gcp_yaml=\"${dst_dir}/fluentd-gcp/fluentd-gcp-ds.yaml\"\n  local -r fluentd_gcp_scaler_yaml=\"${dst_dir}/fluentd-gcp/scaler-deployment.yaml\"\n  # Ingest logs against new resources like \"k8s_container\" and \"k8s_node\" if\n  # LOGGING_STACKDRIVER_RESOURCE_TYPES is \"new\".\n  # Ingest logs against old resources like \"gke_container\" and \"gce_instance\" if\n  # LOGGING_STACKDRIVER_RESOURCE_TYPES is \"old\".\n  if [[ \"${LOGGING_STACKDRIVER_RESOURCE_TYPES:-old}\" == \"new\" ]]; then\n    local -r fluentd_gcp_configmap_yaml=\"${dst_dir}/fluentd-gcp/fluentd-gcp-configmap.yaml\"\n    fluentd_gcp_configmap_name=\"fluentd-gcp-config\"\n  else\n    local -r fluentd_gcp_configmap_yaml=\"${dst_dir}/fluentd-gcp/fluentd-gcp-configmap-old.yaml\"\n    fluentd_gcp_configmap_name=\"fluentd-gcp-config-old\"\n  fi\n  sed -i -e \"s@{{ fluentd_gcp_configmap_name }}@${fluentd_gcp_configmap_name}@g\" \"${fluentd_gcp_yaml}\"\n  fluentd_gcp_yaml_version=\"${FLUENTD_GCP_YAML_VERSION:-v3.2.0}\"\n  sed -i -e \"s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g\" \"${fluentd_gcp_yaml}\"\n  sed -i -e \"s@{{ fluentd_gcp_yaml_version }}@${fluentd_gcp_yaml_version}@g\" \"${fluentd_gcp_scaler_yaml}\"\n  fluentd_gcp_version=\"${FLUENTD_GCP_VERSION:-1.6.17}\"\n  sed -i -e \"s@{{ fluentd_gcp_version }}@${fluentd_gcp_version}@g\" \"${fluentd_gcp_yaml}\"\n  update-daemon-set-prometheus-to-sd-parameters \"${fluentd_gcp_yaml}\"\n  start-fluentd-resource-update \"${fluentd_gcp_yaml}\"\n  update-container-runtime \"${fluentd_gcp_configmap_yaml}\"\n  update-node-journal \"${fluentd_gcp_configmap_yaml}\"\n}\n\n# Sets up the manifests of kube-dns for k8s addons.\nfunction setup-kube-dns-manifest {\n  setup-addon-manifests \"addons\" \"0-dns/kube-dns\"\n  local -r kubedns_file=\"${dst_dir}/0-dns/kube-dns/kube-dns.yaml\"\n  mv \"${dst_dir}/0-dns/kube-dns/kube-dns.yaml.in\" \"${kubedns_file}\"\n  if [ -n \"${CUSTOM_KUBE_DNS_YAML:-}\" ]; then\n    # Replace with custom GKE kube-dns deployment.\n    cat > \"${kubedns_file}\" <<EOF\n$CUSTOM_KUBE_DNS_YAML\nEOF\n    update-prometheus-to-sd-parameters \"${kubedns_file}\"\n  fi\n  # Replace the salt configurations with variable values.\n  sed -i -e \"s@dns_domain@${DNS_DOMAIN}@g\" \"${kubedns_file}\"\n  sed -i -e \"s@dns_server@${DNS_SERVER_IP}@g\" \"${kubedns_file}\"\n  sed -i -e \"s@dns_memory_limit@${DNS_MEMORY_LIMIT:-170Mi}@g\" \"${kubedns_file}\"\n\n  if [[ \"${ENABLE_DNS_HORIZONTAL_AUTOSCALER:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"dns-horizontal-autoscaler\" \"gce\"\n    local -r dns_autoscaler_file=\"${dst_dir}/dns-horizontal-autoscaler/dns-horizontal-autoscaler.yaml\"\n    sed -i'' -e \"s@{{.Target}}@${KUBEDNS_AUTOSCALER}@g\" \"${dns_autoscaler_file}\"\n  fi\n}\n\n# Sets up the manifests of local dns cache agent for k8s addons.\nfunction setup-nodelocaldns-manifest {\n  setup-addon-manifests \"addons\" \"0-dns/nodelocaldns\"\n  local -r localdns_file=\"${dst_dir}/0-dns/nodelocaldns/nodelocaldns.yaml\"\n  setup-addon-custom-yaml \"addons\" \"0-dns/nodelocaldns\" \"nodelocaldns.yaml\" \"${CUSTOM_NODELOCAL_DNS_YAML:-}\"\n  # eventually all the __PILLAR__ stuff will be gone, but theyre still in nodelocaldns for backward compat.\n  sed -i -e \"s/__PILLAR__DNS__DOMAIN__/${DNS_DOMAIN}/g\" \"${localdns_file}\"\n  sed -i -e \"s/__PILLAR__DNS__SERVER__/${DNS_SERVER_IP}/g\" \"${localdns_file}\"\n  sed -i -e \"s/__PILLAR__LOCAL__DNS__/${LOCAL_DNS_IP}/g\" \"${localdns_file}\"\n}\n\n# Sets up the manifests of netd for k8s addons.\nfunction setup-netd-manifest {\n  local -r netd_file=\"${dst_dir}/netd/netd.yaml\"\n  mkdir -p \"${dst_dir}/netd\"\n  touch \"${netd_file}\"\n  if [ -n \"${CUSTOM_NETD_YAML:-}\" ]; then\n    # Replace with custom GCP netd deployment.\n    cat > \"${netd_file}\" <<EOF\n$CUSTOM_NETD_YAML\nEOF\n  fi\n}\n\n# A helper function to set up a custom yaml for a k8s addon.\n#\n# $1: addon category under /etc/kubernetes\n# $2: manifest source dir\n# $3: manifest file\n# $4: custom yaml\nfunction setup-addon-custom-yaml {\n  local -r manifest_path=\"/etc/kubernetes/$1/$2/$3\"\n  local -r custom_yaml=\"$4\"\n  if [ -n \"${custom_yaml:-}\" ]; then\n    # Replace with custom manifest.\n    cat > \"${manifest_path}\" <<EOF\n$custom_yaml\nEOF\n  fi\n}\n\n# Prepares the manifests of k8s addons, and starts the addon manager.\n# Vars assumed:\n#   CLUSTER_NAME\nfunction start-kube-addons {\n  echo \"Prepare kube-addons manifests and start kube addon manager\"\n  local -r src_dir=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty\"\n  local -r dst_dir=\"/etc/kubernetes/addons\"\n\n  create-kubeconfig \"addon-manager\" \"${ADDON_MANAGER_TOKEN}\"\n  # User and group should never contain characters that need to be quoted\n  # shellcheck disable=SC2086\n  prepare-log-file /var/log/kube-addon-manager.log ${KUBE_ADDON_MANAGER_RUNASUSER:-2002}\n\n  # prep addition kube-up specific rbac objects\n  setup-addon-manifests \"addons\" \"rbac/kubelet-api-auth\"\n  setup-addon-manifests \"addons\" \"rbac/kubelet-cert-rotation\"\n  if [[ \"${REGISTER_MASTER_KUBELET:-false}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"rbac/legacy-kubelet-user\"\n  else\n    setup-addon-manifests \"addons\" \"rbac/legacy-kubelet-user-disable\"\n  fi\n\n  if [[ \"${ENABLE_POD_SECURITY_POLICY:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"podsecuritypolicies\"\n  fi\n\n  # Set up manifests of other addons.\n  if [[ \"${KUBE_PROXY_DAEMONSET:-}\" == \"true\" ]] && [[ \"${KUBE_PROXY_DISABLE:-}\" != \"true\" ]]; then\n    if [ -n \"${CUSTOM_KUBE_PROXY_YAML:-}\" ]; then\n      # Replace with custom GKE kube proxy.\n      cat > \"$src_dir/kube-proxy/kube-proxy-ds.yaml\" <<EOF\n$CUSTOM_KUBE_PROXY_YAML\nEOF\n      update-daemon-set-prometheus-to-sd-parameters \"$src_dir/kube-proxy/kube-proxy-ds.yaml\"\n    fi\n    prepare-kube-proxy-manifest-variables \"$src_dir/kube-proxy/kube-proxy-ds.yaml\"\n    setup-addon-manifests \"addons\" \"kube-proxy\"\n  fi\n  if [[ \"${ENABLE_CLUSTER_LOGGING:-}\" == \"true\" ]] &&\n     [[ \"${LOGGING_DESTINATION:-}\" == \"gcp\" ]]; then\n    if [[ \"${ENABLE_METADATA_AGENT:-}\" == \"stackdriver\" ]]; then\n      metadata_agent_cpu_request=\"${METADATA_AGENT_CPU_REQUEST:-40m}\"\n      metadata_agent_memory_request=\"${METADATA_AGENT_MEMORY_REQUEST:-50Mi}\"\n      metadata_agent_cluster_level_cpu_request=\"${METADATA_AGENT_CLUSTER_LEVEL_CPU_REQUEST:-40m}\"\n      metadata_agent_cluster_level_memory_request=\"${METADATA_AGENT_CLUSTER_LEVEL_MEMORY_REQUEST:-50Mi}\"\n      setup-addon-manifests \"addons\" \"metadata-agent/stackdriver\"\n      metadata_agent_yaml=\"${dst_dir}/metadata-agent/stackdriver/metadata-agent.yaml\"\n      sed -i -e \"s@{{ metadata_agent_cpu_request }}@${metadata_agent_cpu_request}@g\" \"${metadata_agent_yaml}\"\n      sed -i -e \"s@{{ metadata_agent_memory_request }}@${metadata_agent_memory_request}@g\" \"${metadata_agent_yaml}\"\n      sed -i -e \"s@{{ metadata_agent_cluster_level_cpu_request }}@${metadata_agent_cluster_level_cpu_request}@g\" \"${metadata_agent_yaml}\"\n      sed -i -e \"s@{{ metadata_agent_cluster_level_memory_request }}@${metadata_agent_cluster_level_memory_request}@g\" \"${metadata_agent_yaml}\"\n    fi\n  fi\n  if [[ \"${ENABLE_METRICS_SERVER:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"metrics-server\"\n    base_metrics_server_cpu=\"40m\"\n    base_metrics_server_memory=\"40Mi\"\n    metrics_server_memory_per_node=\"4\"\n    metrics_server_min_cluster_size=\"16\"\n    if [[ \"${ENABLE_SYSTEM_ADDON_RESOURCE_OPTIMIZATIONS:-}\" == \"true\" ]]; then\n      base_metrics_server_cpu=\"40m\"\n      base_metrics_server_memory=\"35Mi\"\n      metrics_server_memory_per_node=\"4\"\n      metrics_server_min_cluster_size=\"5\"\n    fi\n    local -r metrics_server_yaml=\"${dst_dir}/metrics-server/metrics-server-deployment.yaml\"\n    sed -i -e \"s@{{ base_metrics_server_cpu }}@${base_metrics_server_cpu}@g\" \"${metrics_server_yaml}\"\n    sed -i -e \"s@{{ base_metrics_server_memory }}@${base_metrics_server_memory}@g\" \"${metrics_server_yaml}\"\n    sed -i -e \"s@{{ metrics_server_memory_per_node }}@${metrics_server_memory_per_node}@g\" \"${metrics_server_yaml}\"\n    sed -i -e \"s@{{ metrics_server_min_cluster_size }}@${metrics_server_min_cluster_size}@g\" \"${metrics_server_yaml}\"\n  fi\n  if [[ \"${ENABLE_NVIDIA_GPU_DEVICE_PLUGIN:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"device-plugins/nvidia-gpu\"\n  fi\n  # Setting up the konnectivity-agent daemonset\n  if [[ \"${RUN_KONNECTIVITY_PODS:-false}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"konnectivity-agent\"\n    setup-konnectivity-agent-manifest\n  fi\n  if [[ \"${ENABLE_CLUSTER_DNS:-}\" == \"true\" ]]; then\n    # Create a new directory for the DNS addon and prepend a \"0\" on the name.\n    # Prepending \"0\" to the directory ensures that add-on manager\n    # creates the dns service first. This ensures no other add-on\n    # can \"steal\" the designated DNS clusterIP.\n    BASE_ADDON_DIR=${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty\n    BASE_DNS_DIR=${BASE_ADDON_DIR}/dns\n    NEW_DNS_DIR=${BASE_ADDON_DIR}/0-dns\n    mkdir \"${NEW_DNS_DIR}\" && mv \"${BASE_DNS_DIR}\"/* \"${NEW_DNS_DIR}\" && rm -r \"${BASE_DNS_DIR}\"\n    if [[ \"${CLUSTER_DNS_CORE_DNS:-}\" == \"true\" ]]; then\n      setup-coredns-manifest\n    else\n      setup-kube-dns-manifest\n    fi\n    if [[ \"${ENABLE_NODELOCAL_DNS:-}\" == \"true\" ]]; then\n      setup-nodelocaldns-manifest\n    fi\n  fi\n  if [[ \"${ENABLE_NETD:-}\" == \"true\" ]]; then\n    setup-netd-manifest\n  fi\n  if [[ \"${ENABLE_NODE_LOGGING:-}\" == \"true\" ]] && \\\n     [[ \"${LOGGING_DESTINATION:-}\" == \"elasticsearch\" ]] && \\\n     [[ \"${ENABLE_CLUSTER_LOGGING:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"fluentd-elasticsearch\"\n    local -r fluentd_es_configmap_yaml=\"${dst_dir}/fluentd-elasticsearch/fluentd-es-configmap.yaml\"\n    update-container-runtime ${fluentd_es_configmap_yaml}\n  fi\n  if [[ \"${ENABLE_NODE_LOGGING:-}\" == \"true\" ]] && \\\n     [[ \"${LOGGING_DESTINATION:-}\" == \"gcp\" ]]; then\n    setup-addon-manifests \"addons\" \"fluentd-gcp\"\n    setup-fluentd ${dst_dir}\n    local -r event_exporter_yaml=\"${dst_dir}/fluentd-gcp/event-exporter.yaml\"\n    update-event-exporter ${event_exporter_yaml}\n    update-prometheus-to-sd-parameters ${event_exporter_yaml}\n  fi\n  if [[ \"${ENABLE_CLUSTER_UI:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"dashboard\"\n    local -r dashboard_deployment_yaml=\"${dst_dir}/dashboard/dashboard-deployment.yaml\"\n    update-dashboard-deployment ${dashboard_deployment_yaml}\n  fi\n  if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"daemonset\" ]]; then\n    setup-addon-manifests \"addons\" \"node-problem-detector\"\n  fi\n  if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" ]]; then\n    # Setup role binding(s) for standalone node problem detector.\n    if [[ -n \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\" ]]; then\n      setup-addon-manifests \"addons\" \"node-problem-detector/standalone\"\n    fi\n    setup-addon-manifests \"addons\" \"node-problem-detector/kubelet-user-standalone\" \"node-problem-detector\"\n  fi\n  if echo \"${ADMISSION_CONTROL:-}\" | grep -q \"LimitRanger\"; then\n    setup-addon-manifests \"admission-controls\" \"limit-range\" \"gce\"\n  fi\n  setup-addon-manifests \"addons\" \"admission-resource-quota-critical-pods\"\n  if [[ \"${NETWORK_POLICY_PROVIDER:-}\" == \"calico\" ]]; then\n    setup-addon-manifests \"addons\" \"calico-policy-controller\"\n\n    setup-addon-custom-yaml \"addons\" \"calico-policy-controller\" \"calico-node-daemonset.yaml\" \"${CUSTOM_CALICO_NODE_DAEMONSET_YAML:-}\"\n    setup-addon-custom-yaml \"addons\" \"calico-policy-controller\" \"typha-deployment.yaml\" \"${CUSTOM_TYPHA_DEPLOYMENT_YAML:-}\"\n\n    # Configure Calico CNI directory.\n    local -r ds_file=\"${dst_dir}/calico-policy-controller/calico-node-daemonset.yaml\"\n    sed -i -e \"s@__CALICO_CNI_DIR__@/home/kubernetes/bin@g\" \"${ds_file}\"\n  fi\n  if [[ \"${ENABLE_DEFAULT_STORAGE_CLASS:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"storage-class/gce\"\n  fi\n  if [[ \"${ENABLE_VOLUME_SNAPSHOTS:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"volumesnapshots/crd\"\n    setup-addon-manifests \"addons\" \"volumesnapshots/volume-snapshot-controller\"\n    start-volumesnapshot-crd-and-controller\n  fi\n  if [[ \"${ENABLE_IP_MASQ_AGENT:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"ip-masq-agent\"\n  fi\n  if [[ \"${ENABLE_METADATA_CONCEALMENT:-}\" == \"true\" ]]; then\n    setup-addon-manifests \"addons\" \"metadata-proxy/gce\"\n    local -r metadata_proxy_yaml=\"${dst_dir}/metadata-proxy/gce/metadata-proxy.yaml\"\n    update-daemon-set-prometheus-to-sd-parameters ${metadata_proxy_yaml}\n  fi\n  if [[ \"${ENABLE_ISTIO:-}\" == \"true\" ]]; then\n    if [[ \"${ISTIO_AUTH_TYPE:-}\" == \"MUTUAL_TLS\" ]]; then\n      setup-addon-manifests \"addons\" \"istio/auth\"\n    else\n      setup-addon-manifests \"addons\" \"istio/noauth\"\n    fi\n  fi\n  if [[ -n \"${EXTRA_ADDONS_URL:-}\" ]]; then\n    download-extra-addons\n    setup-addon-manifests \"addons\" \"gce-extras\"\n  fi\n\n\n  # Place addon manager pod manifest.\n  src_file=\"${src_dir}/kube-addon-manager.yaml\"\n  sed -i -e \"s@{{kubectl_prune_whitelist_override}}@${KUBECTL_PRUNE_WHITELIST_OVERRIDE:-}@g\" \"${src_file}\"\n  sed -i -e \"s@{{kubectl_extra_prune_whitelist}}@${ADDON_MANAGER_PRUNE_WHITELIST:-}@g\" \"${src_file}\"\n  sed -i -e \"s@{{runAsUser}}@${KUBE_ADDON_MANAGER_RUNASUSER:-2002}@g\" \"${src_file}\"\n  sed -i -e \"s@{{runAsGroup}}@${KUBE_ADDON_MANAGER_RUNASGROUP:-2002}@g\" \"${src_file}\"\n  cp \"${src_file}\" /etc/kubernetes/manifests\n}\n\nfunction setup-konnectivity-agent-manifest {\n    local -r manifest=\"/etc/kubernetes/addons/konnectivity-agent/konnectivity-agent-ds.yaml\"\n    sed -i \"s|__APISERVER_IP__|${KUBERNETES_MASTER_NAME}|g\" \"${manifest}\"\n}\n\n# Setups manifests for ingress controller and gce-specific policies for service controller.\nfunction start-lb-controller {\n  setup-addon-manifests \"addons\" \"loadbalancing\"\n\n  # Starts a l7 loadbalancing controller for ingress.\n  if [[ \"${ENABLE_L7_LOADBALANCING:-}\" == \"glbc\" ]]; then\n    echo \"Start GCE L7 pod\"\n    prepare-log-file /var/log/glbc.log\n    setup-addon-manifests \"addons\" \"cluster-loadbalancing/glbc\"\n    setup-addon-manifests \"addons\" \"rbac/cluster-loadbalancing/glbc\"\n    create-kubeconfig \"l7-lb-controller\" \"${GCE_GLBC_TOKEN}\"\n\n    local -r src_manifest=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty/glbc.manifest\"\n    local -r dest_manifest=\"/etc/kubernetes/manifests/glbc.manifest\"\n\n    if [[ -n \"${CUSTOM_INGRESS_YAML:-}\" ]]; then\n      echo \"${CUSTOM_INGRESS_YAML}\" > \"${dest_manifest}\"\n    else\n      cp \"${src_manifest}\" \"${dest_manifest}\"\n    fi\n\n    # Override the glbc image if GCE_GLBC_IMAGE is specified.\n    if [[ -n \"${GCE_GLBC_IMAGE:-}\" ]]; then\n      sed -i \"s|image:.*|image: ${GCE_GLBC_IMAGE}|\" \"${dest_manifest}\"\n    fi\n  fi\n}\n\n# Setup working directory for kubelet.\nfunction setup-kubelet-dir {\n    echo \"Making /var/lib/kubelet executable for kubelet\"\n    mount -B /var/lib/kubelet /var/lib/kubelet/\n    mount -B -o remount,exec,suid,dev /var/lib/kubelet\n\n    # TODO(#60123): The kubelet should create the cert-dir directory if it doesn't exist\n    mkdir -p /var/lib/kubelet/pki/\n\n    # Mount /var/lib/kubelet/pki on a tmpfs so it doesn't persist across\n    # reboots. This can help avoid some rare instances of corrupt cert files\n    # (e.g. created but not written during a shutdown). Kubelet crash-loops\n    # in these cases. Do this after above mount calls so it isn't overwritten.\n    echo \"Mounting /var/lib/kubelet/pki on tmpfs\"\n    mount -t tmpfs tmpfs /var/lib/kubelet/pki\n}\n\n# Override for GKE custom master setup scripts (no-op outside of GKE).\nfunction gke-master-start {\n  if [[ -e \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\" ]]; then\n    echo \"Running GKE internal configuration script\"\n    . \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\"\n    gke-internal-master-start\n elif [[ -n \"${KUBE_BEARER_TOKEN:-}\" ]]; then\n   echo \"setting up local admin kubeconfig\"\n   create-kubeconfig \"local-admin\" \"${KUBE_BEARER_TOKEN}\"\n   echo \"export KUBECONFIG=/etc/srv/kubernetes/local-admin/kubeconfig\" > /etc/profile.d/kubeconfig.sh\n  fi\n}\n\nfunction reset-motd {\n  # kubelet is installed both on the master and nodes, and the version is easy to parse (unlike kubectl)\n  local -r version=\"$(\"${KUBE_HOME}\"/bin/kubelet --version=true | cut -f2 -d \" \")\"\n  # This logic grabs either a release tag (v1.2.1 or v1.2.1-alpha.1),\n  # or the git hash that's in the build info.\n  local gitref\n  gitref=\"$(echo \"${version}\" | sed -r \"s/(v[0-9]+\\.[0-9]+\\.[0-9]+)(-[a-z]+\\.[0-9]+)?.*/\\1\\2/g\")\"\n  local devel=\"\"\n  if [[ \"${gitref}\" != \"${version}\" ]]; then\n    devel=\"\nNote: This looks like a development version, which might not be present on GitHub.\nIf it isn't, the closest tag is at:\n  https://github.com/kubernetes/kubernetes/tree/${gitref}\n\"\n    gitref=\"${version//*+/}\"\n  fi\n  cat > /etc/motd <<EOF\n\nWelcome to Kubernetes ${version}!\n\nYou can find documentation for Kubernetes at:\n  http://docs.kubernetes.io/\n\nThe source for this release can be found at:\n  /home/kubernetes/kubernetes-src.tar.gz\nOr you can download it at:\n  https://storage.googleapis.com/kubernetes-release/release/${version}/kubernetes-src.tar.gz\n\nIt is based on the Kubernetes source at:\n  https://github.com/kubernetes/kubernetes/tree/${gitref}\n${devel}\nFor Kubernetes copyright and licensing information, see:\n  /home/kubernetes/LICENSES\n\nEOF\n}\n\nfunction override-kubectl {\n    echo \"overriding kubectl\"\n    echo \"export PATH=${KUBE_HOME}/bin:\\$PATH\" > /etc/profile.d/kube_env.sh\n\n    # source the file explicitly otherwise we have\n    # issues on a ubuntu OS image finding the kubectl\n    # shellcheck disable=SC1091\n    source /etc/profile.d/kube_env.sh\n\n    # Add ${KUBE_HOME}/bin into sudoer secure path.\n    local sudo_path\n    sudo_path=$(sudo env | grep \"^PATH=\")\n    if [[ -n \"${sudo_path}\" ]]; then\n      sudo_path=${sudo_path#PATH=}\n      (\n        umask 027\n        echo \"Defaults secure_path=\\\"${KUBE_HOME}/bin:${sudo_path}\\\"\" > /etc/sudoers.d/kube_secure_path\n      )\n    fi\n}\n\nfunction override-pv-recycler {\n  if [[ -z \"${PV_RECYCLER_OVERRIDE_TEMPLATE:-}\" ]]; then\n    echo \"PV_RECYCLER_OVERRIDE_TEMPLATE is not set\"\n    exit 1\n  fi\n\n  PV_RECYCLER_VOLUME=\"{\\\"name\\\": \\\"pv-recycler-mount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"${PV_RECYCLER_OVERRIDE_TEMPLATE}\\\", \\\"type\\\": \\\"FileOrCreate\\\"}},\"\n  PV_RECYCLER_MOUNT=\"{\\\"name\\\": \\\"pv-recycler-mount\\\",\\\"mountPath\\\": \\\"${PV_RECYCLER_OVERRIDE_TEMPLATE}\\\", \\\"readOnly\\\": true},\"\n\n  cat > \"${PV_RECYCLER_OVERRIDE_TEMPLATE}\" <<EOF\nversion: v1\nkind: Pod\nmetadata:\n  generateName: pv-recycler-\n  namespace: default\nspec:\n  activeDeadlineSeconds: 60\n  restartPolicy: Never\n  volumes:\n  - name: vol\n  containers:\n  - name: pv-recycler\n    image: k8s.gcr.io/busybox:1.27\n    command:\n    - /bin/sh\n    args:\n    - -c\n    - test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z $(ls -A /scrub) || exit 1\n    volumeMounts:\n    - name: vol\n      mountPath: /scrub\nEOF\n}\n\nfunction wait-till-apiserver-ready() {\n  until kubectl get nodes; do\n    sleep 5\n  done\n}\n\nfunction ensure-master-bootstrap-kubectl-auth {\n  # By default, `kubectl` uses http://localhost:8080\n  # If the insecure port is disabled, kubectl will need to use an admin-authenticated kubeconfig.\n  if [[ -n \"${KUBE_BOOTSTRAP_TOKEN:-}\" ]]; then\n    create-kubeconfig \"kube-bootstrap\" \"${KUBE_BOOTSTRAP_TOKEN}\"\n    export KUBECONFIG=/etc/srv/kubernetes/kube-bootstrap/kubeconfig\n  fi\n}\n\nfunction setup-containerd {\n  echo \"Generate containerd config\"\n  local config_path=\"${CONTAINERD_CONFIG_PATH:-\"/etc/containerd/config.toml\"}\"\n  mkdir -p \"$(dirname \"${config_path}\")\"\n  local cni_template_path=\"${KUBE_HOME}/cni.template\"\n  cat > \"${cni_template_path}\" <<EOF\n{\n  \"name\": \"k8s-pod-network\",\n  \"cniVersion\": \"0.3.1\",\n  \"plugins\": [\n    {\n      \"type\": \"ptp\",\n      \"mtu\": 1460,\n      \"ipam\": {\n        \"type\": \"host-local\",\n        \"subnet\": \"{{.PodCIDR}}\",\n        \"routes\": [\n          {\n            \"dst\": \"0.0.0.0/0\"\n          }\n        ]\n      }\n    },\n    {\n      \"type\": \"portmap\",\n      \"capabilities\": {\n        \"portMappings\": true\n      }\n    }\n  ]\n}\nEOF\n  if [[ \"${KUBERNETES_MASTER:-}\" != \"true\" ]]; then\n    if [[ \"${NETWORK_POLICY_PROVIDER:-\"none\"}\" != \"none\" || \"${ENABLE_NETD:-}\" == \"true\" ]]; then\n      # Use Kubernetes cni daemonset on node if network policy provider is specified\n      # or netd is enabled.\n      cni_template_path=\"\"\n    fi\n  fi\n  cat > \"${config_path}\" <<EOF\nversion = 2\n# Kubernetes requires the cri plugin.\nrequired_plugins = [\"io.containerd.grpc.v1.cri\"]\n# Kubernetes doesn't use containerd restart manager.\ndisabled_plugins = [\"io.containerd.internal.v1.restart\"]\noom_score = -999\n\n[debug]\n  level = \"${CONTAINERD_LOG_LEVEL:-\"info\"}\"\n\n[plugins.\"io.containerd.grpc.v1.cri\"]\n  stream_server_address = \"127.0.0.1\"\n  max_container_log_line_size = ${CONTAINERD_MAX_CONTAINER_LOG_LINE:-262144}\n[plugins.\"io.containerd.grpc.v1.cri\".cni]\n  bin_dir = \"${KUBE_HOME}/bin\"\n  conf_dir = \"/etc/cni/net.d\"\n  conf_template = \"${cni_template_path}\"\n[plugins.\"io.containerd.grpc.v1.cri\".containerd]\n  default_runtime_name = \"runc\"\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.runc]\n  runtime_type = \"io.containerd.runc.v2\"\n[plugins.\"io.containerd.grpc.v1.cri\".registry.mirrors.\"docker.io\"]\n  endpoint = [\"https://mirror.gcr.io\",\"https://registry-1.docker.io\"]\nEOF\n\n  if [[ \"${CONTAINER_RUNTIME_TEST_HANDLER:-}\" == \"true\" ]]; then\n  cat >> \"${config_path}\" <<EOF\n# Setup a runtime with the magic name (\"test-handler\") used for Kubernetes\n# runtime class tests ...\n[plugins.\"io.containerd.grpc.v1.cri\".containerd.runtimes.test-handler]\n  runtime_type = \"io.containerd.runc.v2\"\nEOF\n  fi\n\n  # Reuse docker group for containerd.\n  local -r containerd_gid=\"$(grep ^docker: /etc/group | cut -d: -f 3)\"\n  if [[ -n \"${containerd_gid:-}\" ]]; then\n    cat >> \"${config_path}\" <<EOF\n# reuse id of the docker group\n[grpc]\n  gid = ${containerd_gid}\nEOF\n  fi\n  chmod 644 \"${config_path}\"\n\n  echo \"Restart containerd to load the config change\"\n  systemctl restart containerd\n}\n\n# This function detects the platform/arch of the machine where the script runs,\n# and sets the HOST_PLATFORM and HOST_ARCH environment variables accordingly.\n# Callers can specify HOST_PLATFORM_OVERRIDE and HOST_ARCH_OVERRIDE to skip the detection.\n# This function is adapted from the detect_client_info function in cluster/get-kube-binaries.sh\n# and kube::util::host_os, kube::util::host_arch functions in hack/lib/util.sh\n# This function should be synced with detect_host_info in ./configure.sh\nfunction detect_host_info() {\n  HOST_PLATFORM=${HOST_PLATFORM_OVERRIDE:-\"$(uname -s)\"}\n  case \"${HOST_PLATFORM}\" in\n    Linux|linux)\n      HOST_PLATFORM=\"linux\"\n      ;;\n    *)\n      echo \"Unknown, unsupported platform: ${HOST_PLATFORM}.\" >&2\n      echo \"Supported platform(s): linux.\" >&2\n      echo \"Bailing out.\" >&2\n      exit 2\n  esac\n\n  HOST_ARCH=${HOST_ARCH_OVERRIDE:-\"$(uname -m)\"}\n  case \"${HOST_ARCH}\" in\n    x86_64*|i?86_64*|amd64*)\n      HOST_ARCH=\"amd64\"\n      ;;\n    aHOST_arch64*|aarch64*|arm64*)\n      HOST_ARCH=\"arm64\"\n      ;;\n    *)\n      echo \"Unknown, unsupported architecture (${HOST_ARCH}).\" >&2\n      echo \"Supported architecture(s): amd64 and arm64.\" >&2\n      echo \"Bailing out.\" >&2\n      exit 2\n      ;;\n  esac\n}\n\n# Initializes variables used by the log-* functions.\n#\n# get-metadata-value must be defined before calling this function.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-init {\n  # Used by log-* functions.\n  LOG_CLUSTER_ID=$(get-metadata-value 'instance/attributes/cluster-uid' 'get-metadata-value-error')\n  LOG_INSTANCE_NAME=$(hostname)\n  LOG_BOOT_ID=$(journalctl --list-boots | grep -E '^ *0' | awk '{print $2}')\n  declare -Ag LOG_START_TIMES\n  declare -ag LOG_TRAP_STACK\n\n  LOG_STATUS_STARTED='STARTED'\n  LOG_STATUS_COMPLETED='COMPLETED'\n  LOG_STATUS_ERROR='ERROR'\n}\n\n# Sets an EXIT trap.\n# Args:\n#   $1:... : the trap command.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-trap-push {\n  local t=\"${*:1}\"\n  LOG_TRAP_STACK+=(\"${t}\")\n  # shellcheck disable=2064\n  trap \"${t}\" EXIT\n}\n\n# Removes and restores an EXIT trap.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-trap-pop {\n  # Remove current trap.\n  unset 'LOG_TRAP_STACK[-1]'\n\n  # Restore previous trap.\n  if [ ${#LOG_TRAP_STACK[@]} -ne 0 ]; then\n    local t=\"${LOG_TRAP_STACK[-1]}\"\n    # shellcheck disable=2064\n    trap \"${t}\" EXIT\n  else\n    # If no traps in stack, clear.\n    trap EXIT\n  fi\n}\n\n# Logs the end of a bootstrap step that errored.\n# Args:\n#  $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-error {\n  local bootstep=\"$1\"\n\n  log-proto \"${bootstep}\" \"${LOG_STATUS_ERROR}\" \"encountered non-zero exit code\"\n}\n\n# Wraps a command with bootstrap logging.\n# Args:\n#   $1    : bootstrap step name.\n#   $2... : the command to run.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-wrap {\n  local bootstep=\"$1\"\n  local command=\"${*:2}\"\n\n  log-trap-push \"log-error ${bootstep}\"\n  log-proto \"${bootstep}\" \"${LOG_STATUS_STARTED}\"\n  $command\n  log-proto \"${bootstep}\" \"${LOG_STATUS_COMPLETED}\"\n  log-trap-pop\n}\n\n# Logs a bootstrap step start. Prefer log-wrap.\n# Args:\n#   $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-start {\n  local bootstep=\"$1\"\n\n  log-trap-push \"log-error ${bootstep}\"\n  log-proto \"${bootstep}\" \"${LOG_STATUS_STARTED}\"\n}\n\n# Logs a bootstrap step end. Prefer log-wrap.\n# Args:\n#   $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-end {\n  local bootstep=\"$1\"\n\n  log-proto \"${bootstep}\" \"${LOG_STATUS_COMPLETED}\"\n  log-trap-pop\n}\n\n# Writes a log proto to stdout.\n# Args:\n#   $1: bootstrap step name.\n#   $2: status. Either 'STARTED', 'COMPLETED', or 'ERROR'.\n#   $3: optional status reason.\n#\n# NOTE: this function is duplicated in configure.sh, any changes here should be\n# duplicated there as well.\nfunction log-proto {\n  local bootstep=\"$1\"\n  local status=\"$2\"\n  local status_reason=\"${3:-}\"\n\n  # Get current time.\n  local current_time\n  current_time=\"$(date --utc '+%s.%N')\"\n  # ...formatted as UTC RFC 3339.\n  local timestamp\n  timestamp=\"$(date --utc --date=\"@${current_time}\" '+%FT%T.%NZ')\"\n\n  # Calculate latency.\n  local latency='null'\n  if [ \"${status}\" == \"${LOG_STATUS_STARTED}\" ]; then\n    LOG_START_TIMES[\"${bootstep}\"]=\"${current_time}\"\n  else\n    local start_time=\"${LOG_START_TIMES[\"${bootstep}\"]}\"\n    unset 'LOG_START_TIMES['\"${bootstep}\"']'\n\n    # Bash cannot do non-integer math, shell out to awk.\n    latency=\"$(echo \"${current_time} ${start_time}\" | awk '{print $1 - $2}')s\"\n\n    # The default latency is null which cannot be wrapped as a string so we must\n    # do it here instead of the printf.\n    latency=\"\\\"${latency}\\\"\"\n  fi\n\n  printf '[cloud.kubernetes.monitoring.proto.SerialportLog] {\"cluster_hash\":\"%s\",\"vm_instance_name\":\"%s\",\"boot_id\":\"%s\",\"timestamp\":\"%s\",\"bootstrap_status\":{\"step_name\":\"%s\",\"status\":\"%s\",\"status_reason\":\"%s\",\"latency\":%s}}\\n' \\\n  \"${LOG_CLUSTER_ID}\" \"${LOG_INSTANCE_NAME}\" \"${LOG_BOOT_ID}\" \"${timestamp}\" \"${bootstep}\" \"${status}\" \"${status_reason}\" \"${latency}\"\n}\n\n########### Main Function ###########\nfunction main() {\n  echo \"Start to configure instance for kubernetes\"\n  log-wrap 'DetectHostInfo' detect_host_info\n\n  readonly UUID_MNT_PREFIX=\"/mnt/disks/by-uuid/google-local-ssds\"\n  readonly UUID_BLOCK_PREFIX=\"/dev/disk/by-uuid/google-local-ssds\"\n  readonly COREDNS_AUTOSCALER=\"Deployment/coredns\"\n  readonly KUBEDNS_AUTOSCALER=\"Deployment/kube-dns\"\n\n  # Resource requests of master components.\n  KUBE_CONTROLLER_MANAGER_CPU_REQUEST=\"${KUBE_CONTROLLER_MANAGER_CPU_REQUEST:-200m}\"\n  KUBE_SCHEDULER_CPU_REQUEST=\"${KUBE_SCHEDULER_CPU_REQUEST:-75m}\"\n\n  KUBE_HOME=\"/home/kubernetes\"\n  KUBE_BIN=${KUBE_HOME}/bin\n  CONTAINERIZED_MOUNTER_HOME=\"${KUBE_HOME}/containerized_mounter\"\n  PV_RECYCLER_OVERRIDE_TEMPLATE=\"${KUBE_HOME}/kube-manifests/kubernetes/pv-recycler-template.yaml\"\n\n  log-start 'SourceKubeEnv'\n  if [[ ! -e \"${KUBE_HOME}/kube-env\" ]]; then\n    echo \"The ${KUBE_HOME}/kube-env file does not exist!! Terminate cluster initialization.\"\n    exit 1\n  fi\n  source \"${KUBE_HOME}/kube-env\"\n  log-end 'SourceKubeEnv'\n\n  if [[ -f \"${KUBE_HOME}/kubelet-config.yaml\" ]]; then\n    echo \"Found Kubelet config file at ${KUBE_HOME}/kubelet-config.yaml\"\n    KUBELET_CONFIG_FILE_ARG=\"--config ${KUBE_HOME}/kubelet-config.yaml\"\n  fi\n\n  if [[ -e \"${KUBE_HOME}/kube-master-certs\" ]]; then\n    log-wrap 'SourceKubeMasterCerts' source \"${KUBE_HOME}/kube-master-certs\"\n  fi\n\n  log-start 'VerifyKubeUser'\n  if [[ -n \"${KUBE_USER:-}\" ]]; then\n    if ! [[ \"${KUBE_USER}\" =~ ^[-._@a-zA-Z0-9]+$ ]]; then\n      echo \"Bad KUBE_USER format.\"\n      exit 1\n    fi\n  fi\n  log-end 'VerifyKubeUser'\n\n  log-start 'GenerateTokens'\n  KUBE_CONTROLLER_MANAGER_TOKEN=\"$(secure_random 32)\"\n  KUBE_SCHEDULER_TOKEN=\"$(secure_random 32)\"\n  KUBE_CLUSTER_AUTOSCALER_TOKEN=\"$(secure_random 32)\"\n  if [[ \"${ENABLE_L7_LOADBALANCING:-}\" == \"glbc\" ]]; then\n    GCE_GLBC_TOKEN=\"$(secure_random 32)\"\n  fi\n  ADDON_MANAGER_TOKEN=\"$(secure_random 32)\"\n  if [[ \"${ENABLE_APISERVER_INSECURE_PORT:-false}\" != \"true\" ]]; then\n    KUBE_BOOTSTRAP_TOKEN=\"$(secure_random 32)\"\n  fi\n  if [[ \"${PREPARE_KONNECTIVITY_SERVICE:-false}\" == \"true\" ]]; then\n    KONNECTIVITY_SERVER_TOKEN=\"$(secure_random 32)\"\n  fi\n  if [[ \"${ENABLE_MONITORING_TOKEN:-false}\" == \"true\" ]]; then\n    MONITORING_TOKEN=\"$(secure_random 32)\"\n  fi\n  log-end 'GenerateTokens'\n\n  log-wrap 'SetupOSParams' setup-os-params\n  log-wrap 'ConfigIPFirewall' config-ip-firewall\n  log-wrap 'CreateDirs' create-dirs\n  log-wrap 'EnsureLocalSSDs' ensure-local-ssds\n  log-wrap 'SetupKubeletDir' setup-kubelet-dir\n  log-wrap 'SetupLogrotate' setup-logrotate\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"true\" ]]; then\n    log-wrap 'MountMasterPD' mount-master-pd\n    log-wrap 'CreateNodePKI' create-node-pki\n    log-wrap 'CreateMasterPKI' create-master-pki\n    log-wrap 'CreateMasterAuth' create-master-auth\n    log-wrap 'EnsureMasterBootstrapKubectlAuth' ensure-master-bootstrap-kubectl-auth\n    log-wrap 'CreateMasterKubeletAuth' create-master-kubelet-auth\n    log-wrap 'CreateMasterEtcdAuth' create-master-etcd-auth\n    log-wrap 'CreateMasterEtcdApiserverAuth' create-master-etcd-apiserver-auth\n    log-wrap 'OverridePVRecycler' override-pv-recycler\n    log-wrap 'GKEMasterStart' gke-master-start\n  else\n    log-wrap 'CreateNodePKI' create-node-pki\n    log-wrap 'CreateKubeletKubeconfig' create-kubelet-kubeconfig \"${KUBERNETES_MASTER_NAME}\"\n    if [[ \"${KUBE_PROXY_DAEMONSET:-}\" != \"true\" ]] && [[ \"${KUBE_PROXY_DISABLE:-}\" != \"true\" ]]; then\n      log-wrap 'CreateKubeproxyUserKubeconfig' create-kubeproxy-user-kubeconfig\n    fi\n    if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" ]]; then\n      if [[ -n \"${NODE_PROBLEM_DETECTOR_TOKEN:-}\" ]]; then\n        log-wrap 'CreateNodeProblemDetectorKubeconfig' create-node-problem-detector-kubeconfig \"${KUBERNETES_MASTER_NAME}\"\n      elif [[ -f \"/var/lib/kubelet/kubeconfig\" ]]; then\n        log-wrap 'CreateNodeProblemDetectorKubeconfigFromKubelet' create-node-problem-detector-kubeconfig-from-kubelet\n      else\n        echo \"Either NODE_PROBLEM_DETECTOR_TOKEN or /var/lib/kubelet/kubeconfig must be set\"\n        exit 1\n      fi\n    fi\n  fi\n\n  log-wrap 'OverrideKubectl' override-kubectl\n  container_runtime=\"${CONTAINER_RUNTIME:-docker}\"\n  # Run the containerized mounter once to pre-cache the container image.\n  if [[ \"${container_runtime}\" == \"docker\" ]]; then\n    log-wrap 'AssembleDockerFlags' assemble-docker-flags\n  elif [[ \"${container_runtime}\" == \"containerd\" ]]; then\n    if docker-installed; then\n      # We still need to configure docker so it wouldn't reserver the 172.17.0/16 subnet\n      # And if somebody will start docker to build or pull something, logging will also be set up\n      log-wrap 'AssembleDockerFlags' assemble-docker-flags\n      # stop docker if it is present as we want to use just containerd\n      log-wrap 'StopDocker' systemctl stop docker || echo \"unable to stop docker\"\n    fi\n    log-wrap 'SetupContainerd' setup-containerd\n  fi\n\n  log-start 'SetupKubePodLogReadersGroupDir'\n  if [[ -n \"${KUBE_POD_LOG_READERS_GROUP:-}\" ]]; then\n     mkdir -p /var/log/pods/\n     chgrp -R \"${KUBE_POD_LOG_READERS_GROUP:-}\" /var/log/pods/\n     chmod -R g+s /var/log/pods/\n  fi\n  log-end 'SetupKubePodLogReadersGroupDir'\n\n  log-wrap 'StartKubelet' start-kubelet\n\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"true\" ]]; then\n    log-wrap 'ComputeMasterManifestVariables' compute-master-manifest-variables\n    if [[ -z \"${ETCD_SERVERS:-}\" ]]; then\n      log-wrap 'StartEtcdServers' start-etcd-servers\n    fi\n    log-wrap 'SourceConfigureKubeApiserver' source ${KUBE_BIN}/configure-kubeapiserver.sh\n    log-wrap 'StartKubeApiserver' start-kube-apiserver\n    if [[ \"${RUN_KONNECTIVITY_PODS:-false}\" == \"true\" ]]; then\n      log-wrap 'StartKonnectivityServer' start-konnectivity-server\n    fi\n    log-wrap 'StartKubeControllerManager' start-kube-controller-manager\n    log-wrap 'StartKubeScheduler' start-kube-scheduler\n    log-wrap 'WaitTillApiserverReady' wait-till-apiserver-ready\n    log-wrap 'StartKubeAddons' start-kube-addons\n    log-wrap 'StartClusterAutoscaler' start-cluster-autoscaler\n    log-wrap 'StartLBController' start-lb-controller\n    log-wrap 'UpdateLegacyAddonNodeLabels' update-legacy-addon-node-labels &\n  else\n    if [[ \"${KUBE_PROXY_DAEMONSET:-}\" != \"true\" ]] && [[ \"${KUBE_PROXY_DISABLE:-}\" != \"true\" ]]; then\n      log-wrap 'StartKubeProxy' start-kube-proxy\n    fi\n    if [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" ]]; then\n      log-wrap 'StartNodeProblemDetector' start-node-problem-detector\n    fi\n  fi\n  log-wrap 'ResetMotd' reset-motd\n  log-wrap 'PrepareMounterRootfs' prepare-mounter-rootfs\n\n  # Wait for all background jobs to finish.\n  wait\n  echo \"Done for the configuration for kubernetes\"\n}\n\nif [[ \"${BASH_SOURCE[0]}\" == \"${0}\" ]]; then\n  log-init\n  log-wrap 'ConfigureHelperMain' main \"${@}\"\n\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"true\" ]]; then\n    # Give kube-bootstrap-logs-forwarder.service some time to write all logs.\n    sleep 3\n  fi\nfi\n", "num_lines": 3411}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# Configures etcd related flags of kube-apiserver.\nfunction configure-etcd-params {\n  local -n params_ref=$1\n\n  if [[ -n \"${ETCD_APISERVER_CA_KEY:-}\" && -n \"${ETCD_APISERVER_CA_CERT:-}\" && -n \"${ETCD_APISERVER_SERVER_KEY:-}\" && -n \"${ETCD_APISERVER_SERVER_CERT:-}\" && -n \"${ETCD_APISERVER_CLIENT_KEY:-}\" && -n \"${ETCD_APISERVER_CLIENT_CERT:-}\" ]]; then\n      params_ref+=\" --etcd-servers=${ETCD_SERVERS:-https://127.0.0.1:2379}\"\n      params_ref+=\" --etcd-cafile=${ETCD_APISERVER_CA_CERT_PATH}\"\n      params_ref+=\" --etcd-certfile=${ETCD_APISERVER_CLIENT_CERT_PATH}\"\n      params_ref+=\" --etcd-keyfile=${ETCD_APISERVER_CLIENT_KEY_PATH}\"\n  elif [[ -z \"${ETCD_APISERVER_CA_KEY:-}\" && -z \"${ETCD_APISERVER_CA_CERT:-}\" && -z \"${ETCD_APISERVER_SERVER_KEY:-}\" && -z \"${ETCD_APISERVER_SERVER_CERT:-}\" && -z \"${ETCD_APISERVER_CLIENT_KEY:-}\" && -z \"${ETCD_APISERVER_CLIENT_CERT:-}\" ]]; then\n      params_ref+=\" --etcd-servers=${ETCD_SERVERS:-http://127.0.0.1:2379}\"\n      echo \"WARNING: ALL of ETCD_APISERVER_CA_KEY, ETCD_APISERVER_CA_CERT, ETCD_APISERVER_SERVER_KEY, ETCD_APISERVER_SERVER_CERT, ETCD_APISERVER_CLIENT_KEY and ETCD_APISERVER_CLIENT_CERT are missing, mTLS between etcd server and kube-apiserver is not enabled.\"\n  else\n      echo \"ERROR: Some of ETCD_APISERVER_CA_KEY, ETCD_APISERVER_CA_CERT, ETCD_APISERVER_SERVER_KEY, ETCD_APISERVER_SERVER_CERT, ETCD_APISERVER_CLIENT_KEY and ETCD_APISERVER_CLIENT_CERT are missing, mTLS between etcd server and kube-apiserver cannot be enabled. Please provide all mTLS credential.\"\n      exit 1\n  fi\n\n  if [[ -z \"${ETCD_SERVERS:-}\" ]]; then\n    params_ref+=\" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-/events#http://127.0.0.1:4002}\"\n  elif [[ -n \"${ETCD_SERVERS_OVERRIDES:-}\" ]]; then\n    params_ref+=\" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-}\"\n  fi\n\n  if [[ -n \"${STORAGE_BACKEND:-}\" ]]; then\n    params_ref+=\" --storage-backend=${STORAGE_BACKEND}\"\n  fi\n\n  if [[ -n \"${STORAGE_MEDIA_TYPE:-}\" ]]; then\n    params_ref+=\" --storage-media-type=${STORAGE_MEDIA_TYPE}\"\n  fi\n\n  if [[ -n \"${ETCD_COMPACTION_INTERVAL_SEC:-}\" ]]; then\n    params_ref+=\" --etcd-compaction-interval=${ETCD_COMPACTION_INTERVAL_SEC}s\"\n  fi\n}\n\n# Starts kubernetes apiserver.\n# It prepares the log file, loads the docker image, calculates variables, sets them\n# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.\n#\n# Assumed vars (which are calculated in function compute-master-manifest-variables)\n#   CLOUD_CONFIG_OPT\n#   CLOUD_CONFIG_VOLUME\n#   CLOUD_CONFIG_MOUNT\n#   DOCKER_REGISTRY\n#   INSECURE_PORT_MAPPING\nfunction start-kube-apiserver {\n  echo \"Start kubernetes api-server\"\n  prepare-log-file \"${KUBE_API_SERVER_LOG_PATH:-/var/log/kube-apiserver.log}\" \"${KUBE_API_SERVER_RUNASUSER:-0}\"\n  prepare-log-file \"${KUBE_API_SERVER_AUDIT_LOG_PATH:-/var/log/kube-apiserver-audit.log}\" \"${KUBE_API_SERVER_RUNASUSER:-0}\"\n\n  # Calculate variables and assemble the command line.\n  local params=\"${API_SERVER_TEST_LOG_LEVEL:-\"--v=2\"} ${APISERVER_TEST_ARGS:-} ${CLOUD_CONFIG_OPT}\"\n  params+=\" --address=127.0.0.1\"\n  params+=\" --allow-privileged=true\"\n  params+=\" --cloud-provider=gce\"\n  params+=\" --client-ca-file=${CA_CERT_BUNDLE_PATH}\"\n\n  # params is passed by reference, so no \"$\"\n  configure-etcd-params params\n\n  params+=\" --secure-port=443\"\n  if [[ \"${ENABLE_APISERVER_INSECURE_PORT:-false}\" != \"true\" ]]; then\n    # Default is :8080\n    params+=\" --insecure-port=0\"\n  fi\n  params+=\" --tls-cert-file=${APISERVER_SERVER_CERT_PATH}\"\n  params+=\" --tls-private-key-file=${APISERVER_SERVER_KEY_PATH}\"\n  if [[ -n \"${OLD_MASTER_IP:-}\" ]]; then\n    local old_ips=\"${OLD_MASTER_IP}\"\n    if [[ -n \"${OLD_LOAD_BALANCER_IP:-}\" ]]; then\n      old_ips+=\",${OLD_LOAD_BALANCER_IP}\"\n    fi\n    if [[ -n \"${OLD_PRIVATE_VIP:-}\" ]]; then\n      old_ips+=\",${OLD_PRIVATE_VIP}\"\n    fi\n    params+=\" --tls-sni-cert-key=${OLD_MASTER_CERT_PATH},${OLD_MASTER_KEY_PATH}:${old_ips}\"\n  fi\n  if [[ -n \"${TLS_CIPHER_SUITES:-}\" ]]; then\n    params+=\" --tls-cipher-suites=${TLS_CIPHER_SUITES}\"\n  fi\n  if [[ -e \"${KUBE_HOME}/bin/gke-internal-configure-helper.sh\" ]]; then\n    params+=\" $(gke-kube-apiserver-internal-sni-param)\"\n  fi\n  params+=\" --kubelet-preferred-address-types=InternalIP,ExternalIP,Hostname\"\n  if [[ -s \"${REQUESTHEADER_CA_CERT_PATH:-}\" ]]; then\n    params+=\" --requestheader-client-ca-file=${REQUESTHEADER_CA_CERT_PATH}\"\n    params+=\" --requestheader-allowed-names=aggregator\"\n    params+=\" --requestheader-extra-headers-prefix=X-Remote-Extra-\"\n    params+=\" --requestheader-group-headers=X-Remote-Group\"\n    params+=\" --requestheader-username-headers=X-Remote-User\"\n    params+=\" --proxy-client-cert-file=${PROXY_CLIENT_CERT_PATH}\"\n    params+=\" --proxy-client-key-file=${PROXY_CLIENT_KEY_PATH}\"\n  fi\n  params+=\" --enable-aggregator-routing=true\"\n  if [[ -e \"${APISERVER_CLIENT_CERT_PATH}\" ]] && [[ -e \"${APISERVER_CLIENT_KEY_PATH}\" ]]; then\n    params+=\" --kubelet-client-certificate=${APISERVER_CLIENT_CERT_PATH}\"\n    params+=\" --kubelet-client-key=${APISERVER_CLIENT_KEY_PATH}\"\n  fi\n  if [[ -n \"${SERVICEACCOUNT_CERT_PATH:-}\" ]]; then\n    params+=\" --service-account-key-file=${SERVICEACCOUNT_CERT_PATH}\"\n  fi\n  local known_tokens_file='/etc/srv/kubernetes/known_tokens.csv'\n  if [[ -f \"${known_tokens_file}\" ]]; then\n    chown \"${KUBE_API_SERVER_RUNASUSER:-0}\":\"${KUBE_API_SERVER_RUNASGROUP:-0}\" \"${known_tokens_file}\"\n  fi\n  params+=\" --token-auth-file=${known_tokens_file}\"\n\n  if [[ -n \"${KUBE_APISERVER_REQUEST_TIMEOUT_SEC:-}\" ]]; then\n    params+=\" --request-timeout=${KUBE_APISERVER_REQUEST_TIMEOUT_SEC}s\"\n  fi\n  if [[ -n \"${ENABLE_GARBAGE_COLLECTOR:-}\" ]]; then\n    params+=\" --enable-garbage-collector=${ENABLE_GARBAGE_COLLECTOR}\"\n  fi\n  if [[ -n \"${NUM_NODES:-}\" ]]; then\n    # If the cluster is large, increase max-requests-inflight limit in apiserver.\n    if [[ \"${NUM_NODES}\" -gt 3000 ]]; then\n      params=$(append-param-if-not-present \"${params}\" \"max-requests-inflight\" 3000)\n      params=$(append-param-if-not-present \"${params}\" \"max-mutating-requests-inflight\" 1000)\n    elif [[ \"${NUM_NODES}\" -gt 500 ]]; then\n      params=$(append-param-if-not-present \"${params}\" \"max-requests-inflight\" 1500)\n      params=$(append-param-if-not-present \"${params}\" \"max-mutating-requests-inflight\" 500)\n    fi\n    # Set amount of memory available for apiserver based on number of nodes.\n    # TODO: Once we start setting proper requests and limits for apiserver\n    # we should reuse the same logic here instead of current heuristic.\n    params=$(append-param-if-not-present \"${params}\" \"target-ram-mb\" $((NUM_NODES * 60)))\n  fi\n  if [[ -n \"${SERVICE_CLUSTER_IP_RANGE:-}\" ]]; then\n    params+=\" --service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}\"\n  fi\n  params+=\" --service-account-issuer=${SERVICEACCOUNT_ISSUER}\"\n  params+=\" --service-account-api-audiences=${SERVICEACCOUNT_ISSUER}\"\n  params+=\" --service-account-signing-key-file=${SERVICEACCOUNT_KEY_PATH}\"\n\n  local audit_policy_config_mount=\"\"\n  local audit_policy_config_volume=\"\"\n  local audit_webhook_config_mount=\"\"\n  local audit_webhook_config_volume=\"\"\n  if [[ \"${ENABLE_APISERVER_ADVANCED_AUDIT:-}\" == \"true\" ]]; then\n    local -r audit_policy_file=\"/etc/audit_policy.config\"\n    params+=\" --audit-policy-file=${audit_policy_file}\"\n    # Create the audit policy file, and mount it into the apiserver pod.\n    create-master-audit-policy \"${audit_policy_file}\" \"${ADVANCED_AUDIT_POLICY:-}\"\n    audit_policy_config_mount=\"{\\\"name\\\": \\\"auditpolicyconfigmount\\\",\\\"mountPath\\\": \\\"${audit_policy_file}\\\", \\\"readOnly\\\": true},\"\n    audit_policy_config_volume=\"{\\\"name\\\": \\\"auditpolicyconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"${audit_policy_file}\\\", \\\"type\\\": \\\"FileOrCreate\\\"}},\"\n\n    if [[ \"${ADVANCED_AUDIT_BACKEND:-log}\" == *\"log\"* ]]; then\n      # The advanced audit log backend config matches the basic audit log config.\n      params+=\" --audit-log-path=/var/log/kube-apiserver-audit.log\"\n      params+=\" --audit-log-maxage=0\"\n      params+=\" --audit-log-maxbackup=0\"\n      # Lumberjack doesn't offer any way to disable size-based rotation. It also\n      # has an in-memory counter that doesn't notice if you truncate the file.\n      # 2000000000 (in MiB) is a large number that fits in 31 bits. If the log\n      # grows at 10MiB/s (~30K QPS), it will rotate after ~6 years if apiserver\n      # never restarts. Please manually restart apiserver before this time.\n      params+=\" --audit-log-maxsize=2000000000\"\n\n      # Batching parameters\n      if [[ -n \"${ADVANCED_AUDIT_LOG_MODE:-}\" ]]; then\n        params+=\" --audit-log-mode=${ADVANCED_AUDIT_LOG_MODE}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_BUFFER_SIZE:-}\" ]]; then\n        params+=\" --audit-log-batch-buffer-size=${ADVANCED_AUDIT_LOG_BUFFER_SIZE}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_MAX_BATCH_SIZE:-}\" ]]; then\n        params+=\" --audit-log-batch-max-size=${ADVANCED_AUDIT_LOG_MAX_BATCH_SIZE}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_MAX_BATCH_WAIT:-}\" ]]; then\n        params+=\" --audit-log-batch-max-wait=${ADVANCED_AUDIT_LOG_MAX_BATCH_WAIT}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_THROTTLE_QPS:-}\" ]]; then\n        params+=\" --audit-log-batch-throttle-qps=${ADVANCED_AUDIT_LOG_THROTTLE_QPS}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_THROTTLE_BURST:-}\" ]]; then\n        params+=\" --audit-log-batch-throttle-burst=${ADVANCED_AUDIT_LOG_THROTTLE_BURST}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_LOG_INITIAL_BACKOFF:-}\" ]]; then\n        params+=\" --audit-log-initial-backoff=${ADVANCED_AUDIT_LOG_INITIAL_BACKOFF}\"\n      fi\n      # Truncating backend parameters\n      if [[ -n \"${ADVANCED_AUDIT_TRUNCATING_BACKEND:-}\" ]]; then\n        params+=\" --audit-log-truncate-enabled=${ADVANCED_AUDIT_TRUNCATING_BACKEND}\"\n      fi\n    fi\n    if [[ \"${ADVANCED_AUDIT_BACKEND:-}\" == *\"webhook\"* ]]; then\n      # Create the audit webhook config file, and mount it into the apiserver pod.\n      local -r audit_webhook_config_file=\"/etc/audit_webhook.config\"\n      params+=\" --audit-webhook-config-file=${audit_webhook_config_file}\"\n      create-master-audit-webhook-config \"${audit_webhook_config_file}\"\n      audit_webhook_config_mount=\"{\\\"name\\\": \\\"auditwebhookconfigmount\\\",\\\"mountPath\\\": \\\"${audit_webhook_config_file}\\\", \\\"readOnly\\\": true},\"\n      audit_webhook_config_volume=\"{\\\"name\\\": \\\"auditwebhookconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"${audit_webhook_config_file}\\\", \\\"type\\\": \\\"FileOrCreate\\\"}},\"\n\n      # Batching parameters\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_MODE:-}\" ]]; then\n        params+=\" --audit-webhook-mode=${ADVANCED_AUDIT_WEBHOOK_MODE}\"\n      else\n        params+=\" --audit-webhook-mode=batch\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE:-}\" ]]; then\n        params+=\" --audit-webhook-batch-buffer-size=${ADVANCED_AUDIT_WEBHOOK_BUFFER_SIZE}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE:-}\" ]]; then\n        params+=\" --audit-webhook-batch-max-size=${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_SIZE}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT:-}\" ]]; then\n        params+=\" --audit-webhook-batch-max-wait=${ADVANCED_AUDIT_WEBHOOK_MAX_BATCH_WAIT}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS:-}\" ]]; then\n        params+=\" --audit-webhook-batch-throttle-qps=${ADVANCED_AUDIT_WEBHOOK_THROTTLE_QPS}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST:-}\" ]]; then\n        params+=\" --audit-webhook-batch-throttle-burst=${ADVANCED_AUDIT_WEBHOOK_THROTTLE_BURST}\"\n      fi\n      if [[ -n \"${ADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF:-}\" ]]; then\n        params+=\" --audit-webhook-initial-backoff=${ADVANCED_AUDIT_WEBHOOK_INITIAL_BACKOFF}\"\n      fi\n      # Truncating backend parameters\n      if [[ -n \"${ADVANCED_AUDIT_TRUNCATING_BACKEND:-}\" ]]; then\n        params+=\" --audit-webhook-truncate-enabled=${ADVANCED_AUDIT_TRUNCATING_BACKEND}\"\n      fi\n    fi\n  fi\n\n  if [[ \"${ENABLE_APISERVER_DYNAMIC_AUDIT:-}\" == \"true\" ]]; then\n    params+=\" --audit-dynamic-configuration\"\n    RUNTIME_CONFIG=\"${RUNTIME_CONFIG},auditconfiguration.k8s.io/v1alpha1=true\"\n  fi\n\n  if [[ \"${ENABLE_APISERVER_LOGS_HANDLER:-}\" == \"false\" ]]; then\n    params+=\" --enable-logs-handler=false\"\n  fi\n  if [[ \"${APISERVER_SET_KUBELET_CA:-false}\" == \"true\" ]]; then\n    params+=\" --kubelet-certificate-authority=${CA_CERT_BUNDLE_PATH}\"\n  fi\n\n  if [[ -n \"${ADMISSION_CONTROL:-}\" ]]; then\n    params+=\" --enable-admission-plugins=${ADMISSION_CONTROL}\"\n    params+=\" --admission-control-config-file=/etc/srv/kubernetes/admission_controller_config.yaml\"\n  fi\n\n  # If GKE exec auth support is requested for webhooks, then\n  # gke-exec-auth-plugin needs to be mounted into the kube-apiserver container.\n  local webhook_exec_auth_plugin_mount=\"\"\n  local webhook_exec_auth_plugin_volume=\"\"\n  if [[ -n \"${WEBHOOK_GKE_EXEC_AUTH:-}\" ]]; then\n    webhook_exec_auth_plugin_mount='{\"name\": \"gkeauth\", \"mountPath\": \"/usr/bin/gke-exec-auth-plugin\", \"readOnly\": true},'\n    webhook_exec_auth_plugin_volume='{\"name\": \"gkeauth\", \"hostPath\": {\"path\": \"/home/kubernetes/bin/gke-exec-auth-plugin\", \"type\": \"File\"}},'\n  fi\n\n  if [[ -n \"${KUBE_APISERVER_REQUEST_TIMEOUT:-}\" ]]; then\n    params+=\" --min-request-timeout=${KUBE_APISERVER_REQUEST_TIMEOUT}\"\n  fi\n  if [[ -n \"${RUNTIME_CONFIG:-}\" ]]; then\n    params+=\" --runtime-config=${RUNTIME_CONFIG}\"\n  fi\n  if [[ -n \"${FEATURE_GATES:-}\" ]]; then\n    params+=\" --feature-gates=${FEATURE_GATES}\"\n  fi\n  if [[ -n \"${MASTER_ADVERTISE_ADDRESS:-}\" ]]; then\n    params+=\" --advertise-address=${MASTER_ADVERTISE_ADDRESS}\"\n  elif [[ -n \"${PROJECT_ID:-}\" && -n \"${TOKEN_URL:-}\" && -n \"${TOKEN_BODY:-}\" && -n \"${NODE_NETWORK:-}\" ]]; then\n    local -r vm_external_ip=$(get-metadata-value \"instance/network-interfaces/0/access-configs/0/external-ip\")\n    params+=\" --advertise-address=${vm_external_ip}\"\n    if [[ -n \"${KUBE_API_SERVER_RUNASUSER:-}\" && -n \"${KUBE_API_SERVER_RUNASGROUP:-}\" ]]; then\n      chown -R \"${KUBE_API_SERVER_RUNASUSER}\":\"${KUBE_API_SERVER_RUNASGROUP}\" /etc/srv/sshproxy/\n    fi\n  fi\n\n  local webhook_authn_config_mount=\"\"\n  local webhook_authn_config_volume=\"\"\n  if [[ -n \"${GCP_AUTHN_URL:-}\" ]]; then\n    params+=\" --authentication-token-webhook-config-file=/etc/gcp_authn.config\"\n    webhook_authn_config_mount=\"{\\\"name\\\": \\\"webhookauthnconfigmount\\\",\\\"mountPath\\\": \\\"/etc/gcp_authn.config\\\", \\\"readOnly\\\": true},\"\n    webhook_authn_config_volume=\"{\\\"name\\\": \\\"webhookauthnconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"/etc/gcp_authn.config\\\", \\\"type\\\": \\\"File\\\"}},\"\n    if [[ -n \"${GCP_AUTHN_CACHE_TTL:-}\" ]]; then\n      params+=\" --authentication-token-webhook-cache-ttl=${GCP_AUTHN_CACHE_TTL}\"\n    fi\n  fi\n\n  local authorization_mode=\"RBAC\"\n  local -r src_dir=\"${KUBE_HOME}/kube-manifests/kubernetes/gci-trusty\"\n\n  # Enable ABAC mode unless the user explicitly opts out with ENABLE_LEGACY_ABAC=false\n  if [[ \"${ENABLE_LEGACY_ABAC:-}\" != \"false\" ]]; then\n    echo \"Warning: Enabling legacy ABAC policy. All service accounts will have superuser API access. Set ENABLE_LEGACY_ABAC=false to disable this.\"\n    # Create the ABAC file if it doesn't exist yet, or if we have a KUBE_USER set (to ensure the right user is given permissions)\n    if [[ -n \"${KUBE_USER:-}\" || ! -e /etc/srv/kubernetes/abac-authz-policy.jsonl ]]; then\n      local -r abac_policy_json=\"${src_dir}/abac-authz-policy.jsonl\"\n      if [[ -n \"${KUBE_USER:-}\" ]]; then\n        sed -i -e \"s/{{kube_user}}/${KUBE_USER}/g\" \"${abac_policy_json}\"\n      else\n        sed -i -e \"/{{kube_user}}/d\" \"${abac_policy_json}\"\n      fi\n      cp \"${abac_policy_json}\" /etc/srv/kubernetes/\n    fi\n\n    params+=\" --authorization-policy-file=/etc/srv/kubernetes/abac-authz-policy.jsonl\"\n    authorization_mode+=\",ABAC\"\n  fi\n\n  local webhook_config_mount=\"\"\n  local webhook_config_volume=\"\"\n  if [[ -n \"${GCP_AUTHZ_URL:-}\" ]]; then\n    authorization_mode=\"${authorization_mode},Webhook\"\n    params+=\" --authorization-webhook-config-file=/etc/gcp_authz.config\"\n    webhook_config_mount=\"{\\\"name\\\": \\\"webhookconfigmount\\\",\\\"mountPath\\\": \\\"/etc/gcp_authz.config\\\", \\\"readOnly\\\": true},\"\n    webhook_config_volume=\"{\\\"name\\\": \\\"webhookconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"/etc/gcp_authz.config\\\", \\\"type\\\": \\\"File\\\"}},\"\n    if [[ -n \"${GCP_AUTHZ_CACHE_AUTHORIZED_TTL:-}\" ]]; then\n      params+=\" --authorization-webhook-cache-authorized-ttl=${GCP_AUTHZ_CACHE_AUTHORIZED_TTL}\"\n    fi\n    if [[ -n \"${GCP_AUTHZ_CACHE_UNAUTHORIZED_TTL:-}\" ]]; then\n      params+=\" --authorization-webhook-cache-unauthorized-ttl=${GCP_AUTHZ_CACHE_UNAUTHORIZED_TTL}\"\n    fi\n  fi\n  authorization_mode=\"Node,${authorization_mode}\"\n  params+=\" --authorization-mode=${authorization_mode}\"\n\n  local csc_config_mount=\"\"\n  local csc_config_volume=\"\"\n  local default_konnectivity_socket_vol=\"\"\n  local default_konnectivity_socket_mnt=\"\"\n  if [[ \"${PREPARE_KONNECTIVITY_SERVICE:-false}\" == \"true\" ]]; then\n    # Create the EgressSelectorConfiguration yaml file to control the Egress Selector.\n    csc_config_mount=\"{\\\"name\\\": \\\"cscconfigmount\\\",\\\"mountPath\\\": \\\"/etc/srv/kubernetes/egress_selector_configuration.yaml\\\", \\\"readOnly\\\": false},\"\n    csc_config_volume=\"{\\\"name\\\": \\\"cscconfigmount\\\",\\\"hostPath\\\": {\\\"path\\\": \\\"/etc/srv/kubernetes/egress_selector_configuration.yaml\\\", \\\"type\\\": \\\"FileOrCreate\\\"}},\"\n\n    # UDS socket for communication between apiserver and konnectivity-server\n    local default_konnectivity_socket_path=\"/etc/srv/kubernetes/konnectivity-server\"\n    default_konnectivity_socket_vol=\"{ \\\"name\\\": \\\"konnectivity-socket\\\", \\\"hostPath\\\": {\\\"path\\\": \\\"${default_konnectivity_socket_path}\\\", \\\"type\\\": \\\"DirectoryOrCreate\\\"}},\"\n    default_konnectivity_socket_mnt=\"{ \\\"name\\\": \\\"konnectivity-socket\\\", \\\"mountPath\\\": \\\"${default_konnectivity_socket_path}\\\", \\\"readOnly\\\": false},\"\n  fi\n  if [[ \"${EGRESS_VIA_KONNECTIVITY:-false}\" == \"true\" ]]; then\n    params+=\" --egress-selector-config-file=/etc/srv/kubernetes/egress_selector_configuration.yaml\"\n  fi\n\n  local container_env=\"\"\n  if [[ -n \"${ENABLE_CACHE_MUTATION_DETECTOR:-}\" ]]; then\n    container_env+=\"{\\\"name\\\": \\\"KUBE_CACHE_MUTATION_DETECTOR\\\", \\\"value\\\": \\\"${ENABLE_CACHE_MUTATION_DETECTOR}\\\"}\"\n  fi\n  if [[ -n \"${ENABLE_PATCH_CONVERSION_DETECTOR:-}\" ]]; then\n    if [[ -n \"${container_env}\" ]]; then\n      container_env=\"${container_env}, \"\n    fi\n    container_env+=\"{\\\"name\\\": \\\"KUBE_PATCH_CONVERSION_DETECTOR\\\", \\\"value\\\": \\\"${ENABLE_PATCH_CONVERSION_DETECTOR}\\\"}\"\n  fi\n  if [[ -n \"${container_env}\" ]]; then\n    container_env=\"\\\"env\\\":[${container_env}],\"\n  fi\n\n  local -r src_file=\"${src_dir}/kube-apiserver.manifest\"\n\n  # params is passed by reference, so no \"$\"\n  setup-etcd-encryption \"${src_file}\" params\n\n  local healthcheck_ip=\"127.0.0.1\"\n  if [[ ${KUBE_APISERVER_HEALTHCHECK_ON_HOST_IP:-} == \"true\" ]]; then\n    healthcheck_ip=$(hostname -i)\n  fi\n\n  params=\"$(convert-manifest-params \"${params}\")\"\n  # Evaluate variables.\n  local -r kube_apiserver_docker_tag=\"${KUBE_API_SERVER_DOCKER_TAG:-$(cat /home/kubernetes/kube-docker-files/kube-apiserver.docker_tag)}\"\n  sed -i -e \"s@{{params}}@${params}@g\" \"${src_file}\"\n  sed -i -e \"s@{{container_env}}@${container_env}@g\" \"${src_file}\"\n  sed -i -e \"s@{{srv_sshproxy_path}}@/etc/srv/sshproxy@g\" \"${src_file}\"\n  sed -i -e \"s@{{cloud_config_mount}}@${CLOUD_CONFIG_MOUNT}@g\" \"${src_file}\"\n  sed -i -e \"s@{{cloud_config_volume}}@${CLOUD_CONFIG_VOLUME}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube_docker_registry'\\]}}@${DOCKER_REGISTRY}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['kube-apiserver_docker_tag'\\]}}@${kube_apiserver_docker_tag}@g\" \"${src_file}\"\n  sed -i -e \"s@{{pillar\\['allow_privileged'\\]}}@true@g\" \"${src_file}\"\n  sed -i -e \"s@{{liveness_probe_initial_delay}}@${KUBE_APISERVER_LIVENESS_PROBE_INITIAL_DELAY_SEC:-15}@g\" \"${src_file}\"\n  sed -i -e \"s@{{secure_port}}@443@g\" \"${src_file}\"\n  sed -i -e \"s@{{insecure_port_mapping}}@${INSECURE_PORT_MAPPING}@g\" \"${src_file}\"\n  sed -i -e \"s@{{additional_cloud_config_mount}}@@g\" \"${src_file}\"\n  sed -i -e \"s@{{additional_cloud_config_volume}}@@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_authn_config_mount}}@${webhook_authn_config_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_authn_config_volume}}@${webhook_authn_config_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_config_mount}}@${webhook_config_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_config_volume}}@${webhook_config_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{csc_config_mount}}@${csc_config_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{csc_config_volume}}@${csc_config_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{audit_policy_config_mount}}@${audit_policy_config_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{audit_policy_config_volume}}@${audit_policy_config_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{audit_webhook_config_mount}}@${audit_webhook_config_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{audit_webhook_config_volume}}@${audit_webhook_config_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_exec_auth_plugin_mount}}@${webhook_exec_auth_plugin_mount}@g\" \"${src_file}\"\n  sed -i -e \"s@{{webhook_exec_auth_plugin_volume}}@${webhook_exec_auth_plugin_volume}@g\" \"${src_file}\"\n  sed -i -e \"s@{{konnectivity_socket_mount}}@${default_konnectivity_socket_mnt}@g\" \"${src_file}\"\n  sed -i -e \"s@{{konnectivity_socket_volume}}@${default_konnectivity_socket_vol}@g\" \"${src_file}\"\n  sed -i -e \"s@{{healthcheck_ip}}@${healthcheck_ip}@g\" \"${src_file}\"\n\n  if [[ -n \"${KUBE_API_SERVER_RUNASUSER:-}\" && -n \"${KUBE_API_SERVER_RUNASGROUP:-}\" && -n \"${KUBE_PKI_READERS_GROUP:-}\" ]]; then\n    sed -i -e \"s@{{runAsUser}}@\\\"runAsUser\\\": ${KUBE_API_SERVER_RUNASUSER},@g\" \"${src_file}\"\n    sed -i -e \"s@{{runAsGroup}}@\\\"runAsGroup\\\": ${KUBE_API_SERVER_RUNASGROUP},@g\" \"${src_file}\"\n    sed -i -e \"s@{{containerSecurityContext}}@\\\"securityContext\\\": { \\\"capabilities\\\": { \\\"drop\\\": [\\\"all\\\"], \\\"add\\\": [\\\"NET_BIND_SERVICE\\\"] } },@g\" \"${src_file}\"\n    local supplementalGroups=\"${KUBE_PKI_READERS_GROUP}\"\n    if [[ -n \"${KMS_PLUGIN_SOCKET_WRITER_GROUP:-}\" ]]; then\n      supplementalGroups+=\",${KMS_PLUGIN_SOCKET_WRITER_GROUP}\"\n    fi\n    if [[ -n \"${KONNECTIVITY_SERVER_SOCKET_WRITER_GROUP:-}\" ]]; then\n      supplementalGroups+=\",${KONNECTIVITY_SERVER_SOCKET_WRITER_GROUP}\"\n    fi\n    sed -i -e \"s@{{supplementalGroups}}@\\\"supplementalGroups\\\": [ ${supplementalGroups} ],@g\" \"${src_file}\"\n  else\n    sed -i -e \"s@{{runAsUser}}@@g\" \"${src_file}\"\n    sed -i -e \"s@{{runAsGroup}}@@g\" \"${src_file}\"\n    sed -i -e \"s@{{containerSecurityContext}}@@g\" \"${src_file}\"\n    sed -i -e \"s@{{supplementalGroups}}@@g\" \"${src_file}\"\n  fi\n\n  cp \"${src_file}\" \"${ETC_MANIFESTS:-/etc/kubernetes/manifests}\"\n}\n\n\n# Sets-up etcd encryption.\n# Configuration of etcd level encryption consists of the following steps:\n# 1. Writing encryption provider config to disk\n# 2. Adding encryption-provider-config flag to kube-apiserver\n# 3. Add kms-socket-vol and kms-socket-vol-mnt to enable communication with kms-plugin (if requested)\n#\n# Expects parameters:\n# $1 - path to kube-apiserver template\n# $2 - kube-apiserver startup flags (must be passed by reference)\n#\n# Assumes vars (supplied via kube-env):\n# ENCRYPTION_PROVIDER_CONFIG\n# CLOUD_KMS_INTEGRATION\n# ENCRYPTION_PROVIDER_CONFIG_PATH (will default to /etc/srv/kubernetes/encryption-provider-config.yml)\nfunction setup-etcd-encryption {\n  local kube_apiserver_template_path\n  local -n kube_api_server_params\n  local default_encryption_provider_config_vol\n  local default_encryption_provider_config_vol_mnt\n  local encryption_provider_config_vol_mnt\n  local encryption_provider_config_vol\n  local default_kms_socket_dir\n  local default_kms_socket_vol_mnt\n  local default_kms_socket_vol\n  local kms_socket_vol_mnt\n  local kms_socket_vol\n  local encryption_provider_config_path\n\n  kube_apiserver_template_path=\"$1\"\n  if [[ -z \"${ENCRYPTION_PROVIDER_CONFIG:-}\" ]]; then\n    sed -i -e \" {\n      s@{{encryption_provider_mount}}@@\n      s@{{encryption_provider_volume}}@@\n      s@{{kms_socket_mount}}@@\n      s@{{kms_socket_volume}}@@\n    } \" \"${kube_apiserver_template_path}\"\n    return\n  fi\n\n  kube_api_server_params=\"$2\"\n  encryption_provider_config_path=${ENCRYPTION_PROVIDER_CONFIG_PATH:-/etc/srv/kubernetes/encryption-provider-config.yml}\n\n  echo \"${ENCRYPTION_PROVIDER_CONFIG}\" | base64 --decode > \"${encryption_provider_config_path}\"\n  kube_api_server_params+=\" --encryption-provider-config=${encryption_provider_config_path}\"\n\n  default_encryption_provider_config_vol=$(echo \"{ \\\"name\\\": \\\"encryptionconfig\\\", \\\"hostPath\\\": {\\\"path\\\": \\\"${encryption_provider_config_path}\\\", \\\"type\\\": \\\"File\\\"}}\" | base64 | tr -d '\\r\\n')\n  default_encryption_provider_config_vol_mnt=$(echo \"{ \\\"name\\\": \\\"encryptionconfig\\\", \\\"mountPath\\\": \\\"${encryption_provider_config_path}\\\", \\\"readOnly\\\": true}\" | base64 | tr -d '\\r\\n')\n\n  encryption_provider_config_vol_mnt=$(echo \"${ENCRYPTION_PROVIDER_CONFIG_VOL_MNT:-\"${default_encryption_provider_config_vol_mnt}\"}\" | base64 --decode)\n  encryption_provider_config_vol=$(echo \"${ENCRYPTION_PROVIDER_CONFIG_VOL:-\"${default_encryption_provider_config_vol}\"}\" | base64 --decode)\n  sed -i -e \" {\n    s@{{encryption_provider_mount}}@${encryption_provider_config_vol_mnt},@\n    s@{{encryption_provider_volume}}@${encryption_provider_config_vol},@\n  } \" \"${kube_apiserver_template_path}\"\n\n  if [[ -n \"${CLOUD_KMS_INTEGRATION:-}\" ]]; then\n    default_kms_socket_dir=\"/var/run/kmsplugin\"\n    default_kms_socket_vol_mnt=$(echo \"{ \\\"name\\\": \\\"kmssocket\\\", \\\"mountPath\\\": \\\"${default_kms_socket_dir}\\\", \\\"readOnly\\\": false}\" | base64 | tr -d '\\r\\n')\n    default_kms_socket_vol=$(echo \"{ \\\"name\\\": \\\"kmssocket\\\", \\\"hostPath\\\": {\\\"path\\\": \\\"${default_kms_socket_dir}\\\", \\\"type\\\": \\\"DirectoryOrCreate\\\"}}\" | base64 | tr -d '\\r\\n')\n\n    kms_socket_vol_mnt=$(echo \"${KMS_PLUGIN_SOCKET_VOL_MNT:-\"${default_kms_socket_vol_mnt}\"}\" | base64 --decode)\n    kms_socket_vol=$(echo \"${KMS_PLUGIN_SOCKET_VOL:-\"${default_kms_socket_vol}\"}\" | base64 --decode)\n    sed -i -e \" {\n      s@{{kms_socket_mount}}@${kms_socket_vol_mnt},@\n      s@{{kms_socket_volume}}@${kms_socket_vol},@\n    } \" \"${kube_apiserver_template_path}\"\n  else\n    sed -i -e \" {\n      s@{{kms_socket_mount}}@@\n      s@{{kms_socket_volume}}@@\n    } \" \"${kube_apiserver_template_path}\"\n  fi\n}\n", "num_lines": 506}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Due to the GCE custom metadata size limit, we split the entire script into two\n# files configure.sh and configure-helper.sh. The functionality of downloading\n# kubernetes configuration, manifests, docker images, and binary files are\n# put in configure.sh, which is uploaded via GCE custom metadata.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n### Hardcoded constants\nDEFAULT_CNI_VERSION='v0.9.1'\nDEFAULT_CNI_HASH='b5a59660053a5f1a33b5dd5624d9ed61864482d9dc8e5b79c9b3afc3d6f62c9830e1c30f9ccba6ee76f5fb1ff0504e58984420cc0680b26cb643f1cb07afbd1c'\nDEFAULT_NPD_VERSION='v0.8.8'\nDEFAULT_NPD_HASH='ba8315a29368bfc33bdc602eb02d325b0b80e295c8739da35616de5b562c372bd297a2553f3ccd4daaecd67698b659b2c7068a2d2a0b9418ad29233fb75ff3f2'\nDEFAULT_CRICTL_VERSION='v1.21.0'\nDEFAULT_CRICTL_HASH='e4fb9822cb5f71ab8f85021c66170613aae972f4b32030e42868fb36a3bc3ea8642613df8542bf716fad903ed4d7528021ecb28b20c6330448cd2bd2b76bd776'\nDEFAULT_MOUNTER_TAR_SHA='7956fd42523de6b3107ddc3ce0e75233d2fcb78436ff07a1389b6eaac91fb2b1b72a08f7a219eaf96ba1ca4da8d45271002e0d60e0644e796c665f99bb356516'\n###\n\n# Standard curl flags.\nCURL_FLAGS='--fail --silent --show-error --retry 5 --retry-delay 3 --connect-timeout 10 --retry-connrefused'\n\nfunction set-broken-motd {\n  cat > /etc/motd <<EOF\nBroken (or in progress) Kubernetes node setup! Check the cluster initialization status\nusing the following commands.\n\nMaster instance:\n  - sudo systemctl status kube-master-installation\n  - sudo systemctl status kube-master-configuration\n\nNode instance:\n  - sudo systemctl status kube-node-installation\n  - sudo systemctl status kube-node-configuration\nEOF\n}\n\n# A function that fetches a GCE metadata value and echoes it out.\n# Args:\n#   $1 : URL path after /computeMetadata/v1/ (without heading slash).\n#   $2 : An optional default value to echo out if the fetch fails.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction get-metadata-value {\n  local default=\"${2:-}\"\n\n  local status\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    -H 'Metadata-Flavor: Google' \\\n    \"http://metadata/computeMetadata/v1/${1}\" \\\n  || status=\"$?\"\n  status=\"${status:-0}\"\n\n  if [[ \"${status}\" -eq 0 || -z \"${default}\" ]]; then\n    return \"${status}\"\n  else\n    echo \"${default}\"\n  fi\n}\n\nfunction download-kube-env {\n  # Fetch kube-env from GCE metadata server.\n  (\n    umask 077\n    local -r tmp_kube_env=\"/tmp/kube-env.yaml\"\n    # shellcheck disable=SC2086\n    retry-forever 10 curl ${CURL_FLAGS} \\\n      -H \"X-Google-Metadata-Request: True\" \\\n      -o \"${tmp_kube_env}\" \\\n      http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-env\n    # Convert the yaml format file into a shell-style file.\n    eval \"$(python3 -c '''\nimport pipes,sys,yaml\nitems = yaml.load(sys.stdin, Loader=yaml.BaseLoader).items()\nfor k, v in items:\n    print(\"readonly {var}={value}\".format(var=k, value=pipes.quote(str(v))))\n''' < \"${tmp_kube_env}\" > \"${KUBE_HOME}/kube-env\")\"\n    rm -f \"${tmp_kube_env}\"\n  )\n}\n\nfunction download-kubelet-config {\n  local -r dest=\"$1\"\n  echo \"Downloading Kubelet config file, if it exists\"\n  # Fetch kubelet config file from GCE metadata server.\n  (\n    umask 077\n    local -r tmp_kubelet_config=\"/tmp/kubelet-config.yaml\"\n    # shellcheck disable=SC2086\n    retry-forever 10 curl ${CURL_FLAGS} \\\n      -H \"X-Google-Metadata-Request: True\" \\\n      -o \"${tmp_kubelet_config}\" \\\n      http://metadata.google.internal/computeMetadata/v1/instance/attributes/kubelet-config\n    # only write to the final location if curl succeeds\n    mv \"${tmp_kubelet_config}\" \"${dest}\"\n  )\n}\n\nfunction download-kube-master-certs {\n  # Fetch kube-env from GCE metadata server.\n  (\n    umask 077\n    local -r tmp_kube_master_certs=\"/tmp/kube-master-certs.yaml\"\n    # shellcheck disable=SC2086\n    retry-forever 10 curl ${CURL_FLAGS} \\\n      -H \"X-Google-Metadata-Request: True\" \\\n      -o \"${tmp_kube_master_certs}\" \\\n      http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-master-certs\n    # Convert the yaml format file into a shell-style file.\n    eval \"$(python3 -c '''\nimport pipes,sys,yaml\nitems = yaml.load(sys.stdin, Loader=yaml.BaseLoader).items()\nfor k, v in items:\n    print(\"readonly {var}={value}\".format(var=k, value=pipes.quote(str(v))))\n''' < \"${tmp_kube_master_certs}\" > \"${KUBE_HOME}/kube-master-certs\")\"\n    rm -f \"${tmp_kube_master_certs}\"\n  )\n}\n\nfunction validate-hash {\n  local -r file=\"$1\"\n  local -r expected=\"$2\"\n\n  actual_sha1=$(sha1sum \"${file}\" | awk '{ print $1 }') || true\n  actual_sha512=$(sha512sum \"${file}\" | awk '{ print $1 }') || true\n  if [[ \"${actual_sha1}\" != \"${expected}\" ]] && [[ \"${actual_sha512}\" != \"${expected}\" ]]; then\n    echo \"== ${file} corrupted, sha1 ${actual_sha1}/sha512 ${actual_sha512} doesn't match expected ${expected} ==\"\n    return 1\n  fi\n}\n\n# Get default service account credentials of the VM.\nGCE_METADATA_INTERNAL=\"http://metadata.google.internal/computeMetadata/v1/instance\"\nfunction get-credentials {\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    -H \"Metadata-Flavor: Google\" \\\n    \"${GCE_METADATA_INTERNAL}/service-accounts/default/token\" \\\n  | python3 -c 'import sys; import json; print(json.loads(sys.stdin.read())[\"access_token\"])'\n}\n\nfunction valid-storage-scope {\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    -H \"Metadata-Flavor: Google\" \\\n    \"${GCE_METADATA_INTERNAL}/service-accounts/default/scopes\" \\\n  | grep -E \"auth/devstorage|auth/cloud-platform\"\n}\n\n# Retry a download until we get it. Takes a hash and a set of URLs.\n#\n# $1 is the sha512/sha1 hash of the URL. Can be \"\" if the sha512/sha1 hash is unknown.\n# $2+ are the URLs to download.\nfunction download-or-bust {\n  local -r hash=\"$1\"\n  shift 1\n\n  while true; do\n    for url in \"$@\"; do\n      local file=\"${url##*/}\"\n      rm -f \"${file}\"\n      # if the url belongs to GCS API we should use oauth2_token in the headers\n      local curl_headers=\"\"\n      if [[ \"$url\" =~ ^https://storage.googleapis.com.* ]] && valid-storage-scope ; then\n        curl_headers=\"Authorization: Bearer $(get-credentials)\"\n      fi\n      if ! curl ${curl_headers:+-H \"${curl_headers}\"} -f --ipv4 -Lo \"${file}\" --connect-timeout 20 --max-time 300 --retry 6 --retry-delay 10 --retry-connrefused \"${url}\"; then\n        echo \"== Failed to download ${url}. Retrying. ==\"\n      elif [[ -n \"${hash}\" ]] && ! validate-hash \"${file}\" \"${hash}\"; then\n        echo \"== Hash validation of ${url} failed. Retrying. ==\"\n      else\n        if [[ -n \"${hash}\" ]]; then\n          echo \"== Downloaded ${url} (HASH = ${hash}) ==\"\n        else\n          echo \"== Downloaded ${url} ==\"\n        fi\n        return\n      fi\n    done\n  done\n}\n\nfunction is-preloaded {\n  local -r key=$1\n  local -r value=$2\n  grep -qs \"${key},${value}\" \"${KUBE_HOME}/preload_info\"\n}\n\nfunction split-commas {\n  echo -e \"${1//,/'\\n'}\"\n}\n\nfunction remount-flexvolume-directory {\n  local -r flexvolume_plugin_dir=$1\n  mkdir -p \"$flexvolume_plugin_dir\"\n  mount --bind \"$flexvolume_plugin_dir\" \"$flexvolume_plugin_dir\"\n  mount -o remount,exec \"$flexvolume_plugin_dir\"\n}\n\nfunction install-gci-mounter-tools {\n  CONTAINERIZED_MOUNTER_HOME=\"${KUBE_HOME}/containerized_mounter\"\n  local -r mounter_tar_sha=\"${DEFAULT_MOUNTER_TAR_SHA}\"\n  if is-preloaded \"mounter\" \"${mounter_tar_sha}\"; then\n    echo \"mounter is preloaded.\"\n    return\n  fi\n\n  echo \"Downloading gci mounter tools.\"\n  mkdir -p \"${CONTAINERIZED_MOUNTER_HOME}\"\n  chmod a+x \"${CONTAINERIZED_MOUNTER_HOME}\"\n  mkdir -p \"${CONTAINERIZED_MOUNTER_HOME}/rootfs\"\n  download-or-bust \"${mounter_tar_sha}\" \"https://storage.googleapis.com/kubernetes-release/gci-mounter/mounter.tar\"\n  cp \"${KUBE_HOME}/kubernetes/server/bin/mounter\" \"${CONTAINERIZED_MOUNTER_HOME}/mounter\"\n  chmod a+x \"${CONTAINERIZED_MOUNTER_HOME}/mounter\"\n  mv \"${KUBE_HOME}/mounter.tar\" /tmp/mounter.tar\n  tar xf /tmp/mounter.tar -C \"${CONTAINERIZED_MOUNTER_HOME}/rootfs\"\n  rm /tmp/mounter.tar\n  mkdir -p \"${CONTAINERIZED_MOUNTER_HOME}/rootfs/var/lib/kubelet\"\n}\n\n# Install node problem detector binary.\nfunction install-node-problem-detector {\n  if [[ -n \"${NODE_PROBLEM_DETECTOR_VERSION:-}\" ]]; then\n      local -r npd_version=\"${NODE_PROBLEM_DETECTOR_VERSION}\"\n      local -r npd_hash=\"${NODE_PROBLEM_DETECTOR_TAR_HASH}\"\n  else\n      local -r npd_version=\"${DEFAULT_NPD_VERSION}\"\n      local -r npd_hash=\"${DEFAULT_NPD_HASH}\"\n  fi\n  local -r npd_tar=\"node-problem-detector-${npd_version}-${HOST_PLATFORM}_${HOST_ARCH}.tar.gz\"\n\n  if is-preloaded \"${npd_tar}\" \"${npd_hash}\"; then\n    echo \"${npd_tar} is preloaded.\"\n    return\n  fi\n\n  echo \"Downloading ${npd_tar}.\"\n  local -r npd_release_path=\"${NODE_PROBLEM_DETECTOR_RELEASE_PATH:-https://storage.googleapis.com/kubernetes-release}\"\n  download-or-bust \"${npd_hash}\" \"${npd_release_path}/node-problem-detector/${npd_tar}\"\n  local -r npd_dir=\"${KUBE_HOME}/node-problem-detector\"\n  mkdir -p \"${npd_dir}\"\n  tar xzf \"${KUBE_HOME}/${npd_tar}\" -C \"${npd_dir}\" --overwrite\n  mv \"${npd_dir}/bin\"/* \"${KUBE_BIN}\"\n  chmod a+x \"${KUBE_BIN}/node-problem-detector\"\n  rmdir \"${npd_dir}/bin\"\n  rm -f \"${KUBE_HOME}/${npd_tar}\"\n}\n\nfunction install-cni-binaries {\n  local -r cni_version=${CNI_VERSION:-$DEFAULT_CNI_VERSION}\n  if [[ -n \"${CNI_VERSION:-}\" ]]; then\n      local -r cni_hash=\"${CNI_HASH:-}\"\n  else\n      local -r cni_hash=\"${DEFAULT_CNI_HASH}\"\n  fi\n\n  local -r cni_tar=\"${CNI_TAR_PREFIX}${cni_version}.tgz\"\n  local -r cni_url=\"${CNI_STORAGE_URL_BASE}/${cni_version}/${cni_tar}\"\n\n  if is-preloaded \"${cni_tar}\" \"${cni_hash}\"; then\n    echo \"${cni_tar} is preloaded.\"\n    return\n  fi\n\n  echo \"Downloading cni binaries\"\n  download-or-bust \"${cni_hash}\" \"${cni_url}\"\n  local -r cni_dir=\"${KUBE_HOME}/cni\"\n  mkdir -p \"${cni_dir}/bin\"\n  tar xzf \"${KUBE_HOME}/${cni_tar}\" -C \"${cni_dir}/bin\" --overwrite\n  mv \"${cni_dir}/bin\"/* \"${KUBE_BIN}\"\n  rmdir \"${cni_dir}/bin\"\n  rm -f \"${KUBE_HOME}/${cni_tar}\"\n}\n\n# Install crictl binary.\n# Assumptions: HOST_PLATFORM and HOST_ARCH are specified by calling detect_host_info.\nfunction install-crictl {\n  if [[ -n \"${CRICTL_VERSION:-}\" ]]; then\n    local -r crictl_version=\"${CRICTL_VERSION}\"\n    local -r crictl_hash=\"${CRICTL_TAR_HASH}\"\n  else\n    local -r crictl_version=\"${DEFAULT_CRICTL_VERSION}\"\n    local -r crictl_hash=\"${DEFAULT_CRICTL_HASH}\"\n  fi\n  local -r crictl=\"crictl-${crictl_version}-${HOST_PLATFORM}-${HOST_ARCH}.tar.gz\"\n\n  # Create crictl config file.\n  cat > /etc/crictl.yaml <<EOF\nruntime-endpoint: ${CONTAINER_RUNTIME_ENDPOINT:-unix:///var/run/dockershim.sock}\nEOF\n\n  if is-preloaded \"${crictl}\" \"${crictl_hash}\"; then\n    echo \"crictl is preloaded\"\n    return\n  fi\n\n  echo \"Downloading crictl\"\n  local -r crictl_path=\"https://storage.googleapis.com/k8s-artifacts-cri-tools/release/${crictl_version}\"\n  download-or-bust \"${crictl_hash}\" \"${crictl_path}/${crictl}\"\n  tar xf \"${crictl}\"\n  mv crictl \"${KUBE_BIN}/crictl\"\n}\n\nfunction install-exec-auth-plugin {\n  if [[ ! \"${EXEC_AUTH_PLUGIN_URL:-}\" ]]; then\n      return\n  fi\n  local -r plugin_url=\"${EXEC_AUTH_PLUGIN_URL}\"\n  local -r plugin_hash=\"${EXEC_AUTH_PLUGIN_HASH}\"\n\n  if is-preloaded \"gke-exec-auth-plugin\" \"${plugin_hash}\"; then\n    echo \"gke-exec-auth-plugin is preloaded\"\n    return\n  fi\n\n  echo \"Downloading gke-exec-auth-plugin binary\"\n  download-or-bust \"${plugin_hash}\" \"${plugin_url}\"\n  mv \"${KUBE_HOME}/gke-exec-auth-plugin\" \"${KUBE_BIN}/gke-exec-auth-plugin\"\n  chmod a+x \"${KUBE_BIN}/gke-exec-auth-plugin\"\n\n  if [[ ! \"${EXEC_AUTH_PLUGIN_LICENSE_URL:-}\" ]]; then\n      return\n  fi\n  local -r license_url=\"${EXEC_AUTH_PLUGIN_LICENSE_URL}\"\n  echo \"Downloading gke-exec-auth-plugin license\"\n  download-or-bust \"\" \"${license_url}\"\n  mv \"${KUBE_HOME}/LICENSES/LICENSE\" \"${KUBE_BIN}/gke-exec-auth-plugin-license\"\n}\n\nfunction install-kube-manifests {\n  # Put kube-system pods manifests in ${KUBE_HOME}/kube-manifests/.\n  local dst_dir=\"${KUBE_HOME}/kube-manifests\"\n  mkdir -p \"${dst_dir}\"\n  local manifests_tar_urls\n  while IFS= read -r url; do\n    manifests_tar_urls+=(\"$url\")\n  done < <(split-commas \"${KUBE_MANIFESTS_TAR_URL}\")\n  local -r manifests_tar=\"${manifests_tar_urls[0]##*/}\"\n  if [ -n \"${KUBE_MANIFESTS_TAR_HASH:-}\" ]; then\n    local -r manifests_tar_hash=\"${KUBE_MANIFESTS_TAR_HASH}\"\n  else\n    echo \"Downloading k8s manifests hash (not found in env)\"\n    download-or-bust \"\" \"${manifests_tar_urls[@]/.tar.gz/.tar.gz.sha512}\"\n    local -r manifests_tar_hash=$(cat \"${manifests_tar}.sha512\")\n  fi\n\n  if is-preloaded \"${manifests_tar}\" \"${manifests_tar_hash}\"; then\n    echo \"${manifests_tar} is preloaded.\"\n    return\n  fi\n\n  echo \"Downloading k8s manifests tar\"\n  download-or-bust \"${manifests_tar_hash}\" \"${manifests_tar_urls[@]}\"\n  tar xzf \"${KUBE_HOME}/${manifests_tar}\" -C \"${dst_dir}\" --overwrite\n  local -r kube_addon_registry=\"${KUBE_ADDON_REGISTRY:-k8s.gcr.io}\"\n  if [[ \"${kube_addon_registry}\" != \"k8s.gcr.io\" ]]; then\n    find \"${dst_dir}\" \\(-name '*.yaml' -or -name '*.yaml.in'\\) -print0 | \\\n      xargs -0 sed -ri \"s@(image:\\s.*)k8s.gcr.io@\\1${kube_addon_registry}@\"\n    find \"${dst_dir}\" \\(-name '*.manifest' -or -name '*.json'\\) -print0 | \\\n      xargs -0 sed -ri \"s@(image\\\":\\s+\\\")k8s.gcr.io@\\1${kube_addon_registry}@\"\n  fi\n  cp \"${dst_dir}/kubernetes/gci-trusty/gci-configure-helper.sh\" \"${KUBE_BIN}/configure-helper.sh\"\n  cp \"${dst_dir}/kubernetes/gci-trusty/configure-kubeapiserver.sh\" \"${KUBE_BIN}/configure-kubeapiserver.sh\"\n  if [[ -e \"${dst_dir}/kubernetes/gci-trusty/gke-internal-configure-helper.sh\" ]]; then\n    cp \"${dst_dir}/kubernetes/gci-trusty/gke-internal-configure-helper.sh\" \"${KUBE_BIN}/\"\n  fi\n\n  cp \"${dst_dir}/kubernetes/gci-trusty/health-monitor.sh\" \"${KUBE_BIN}/health-monitor.sh\"\n\n  rm -f \"${KUBE_HOME}/${manifests_tar}\"\n  rm -f \"${KUBE_HOME}/${manifests_tar}.sha512\"\n}\n\n# A helper function for loading a docker image. It keeps trying up to 5 times.\n#\n# $1: Full path of the docker image\nfunction try-load-docker-image {\n  local -r img=$1\n  echo \"Try to load docker image file ${img}\"\n  # Temporarily turn off errexit, because we don't want to exit on first failure.\n  set +e\n  local -r max_attempts=5\n  local -i attempt_num=1\n\n  if [[ \"${CONTAINER_RUNTIME_NAME:-}\" == \"docker\" ]]; then\n    load_image_command=${LOAD_IMAGE_COMMAND:-docker load -i}\n  elif [[ \"${CONTAINER_RUNTIME_NAME:-}\" == \"containerd\" || \"${CONTAINERD_TEST:-}\"  == \"containerd\" ]]; then\n    load_image_command=${LOAD_IMAGE_COMMAND:-ctr -n=k8s.io images import}\n  else\n    load_image_command=\"${LOAD_IMAGE_COMMAND:-}\"\n  fi\n\n  # Deliberately word split load_image_command\n  # shellcheck disable=SC2086\n  until timeout 30 ${load_image_command} \"${img}\"; do\n    if [[ \"${attempt_num}\" == \"${max_attempts}\" ]]; then\n      echo \"Fail to load docker image file ${img} using ${load_image_command} after ${max_attempts} retries. Exit!!\"\n      exit 1\n    else\n      attempt_num=$((attempt_num+1))\n      sleep 5\n    fi\n  done\n  # Re-enable errexit.\n  set -e\n}\n\n# Loads kube-system docker images. It is better to do it before starting kubelet,\n# as kubelet will restart docker daemon, which may interfere with loading images.\nfunction load-docker-images {\n  echo \"Start loading kube-system docker images\"\n  local -r img_dir=\"${KUBE_HOME}/kube-docker-files\"\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"true\" ]]; then\n    try-load-docker-image \"${img_dir}/kube-apiserver.tar\"\n    try-load-docker-image \"${img_dir}/kube-controller-manager.tar\"\n    try-load-docker-image \"${img_dir}/kube-scheduler.tar\"\n  else\n    try-load-docker-image \"${img_dir}/kube-proxy.tar\"\n  fi\n}\n\n# If we are on ubuntu we can try to install docker\nfunction install-docker {\n  # bailout if we are not on ubuntu\n  if ! command -v apt-get >/dev/null 2>&1; then\n    echo \"Unable to automatically install docker. Bailing out...\"\n    return\n  fi\n  # Install Docker deps, some of these are already installed in the image but\n  # that's fine since they won't re-install and we can reuse the code below\n  # for another image someday.\n  apt-get update\n  apt-get install -y --no-install-recommends \\\n    apt-transport-https \\\n    ca-certificates \\\n    socat \\\n    curl \\\n    gnupg2 \\\n    software-properties-common \\\n    lsb-release\n\n  release=$(lsb_release -cs)\n\n  # Add the Docker apt-repository\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    --location \\\n    \"https://download.docker.com/${HOST_PLATFORM}/$(. /etc/os-release; echo \"$ID\")/gpg\" \\\n  | apt-key add -\n  add-apt-repository \\\n    \"deb [arch=${HOST_ARCH}] https://download.docker.com/${HOST_PLATFORM}/$(. /etc/os-release; echo \"$ID\") \\\n    $release stable\"\n\n  # Install Docker\n  apt-get update && \\\n    apt-get install -y --no-install-recommends \"${GCI_DOCKER_VERSION:-\"docker-ce=5:19.03.*\"}\"\n  rm -rf /var/lib/apt/lists/*\n}\n\n# If we are on ubuntu we can try to install containerd\nfunction install-containerd-ubuntu {\n  # bailout if we are not on ubuntu\n  if [[ -z \"$(command -v lsb_release)\" || $(lsb_release -si) != \"Ubuntu\" ]]; then\n    echo \"Unable to automatically install containerd in non-ubuntu image. Bailing out...\"\n    exit 2\n  fi\n\n  # Install dependencies, some of these are already installed in the image but\n  # that's fine since they won't re-install and we can reuse the code below\n  # for another image someday.\n  apt-get update\n  apt-get install -y --no-install-recommends \\\n    apt-transport-https \\\n    ca-certificates \\\n    socat \\\n    curl \\\n    gnupg2 \\\n    software-properties-common \\\n    lsb-release\n\n  release=$(lsb_release -cs)\n\n  # Add the Docker apt-repository (as we install containerd from there)\n  # shellcheck disable=SC2086\n  curl ${CURL_FLAGS} \\\n    --location \\\n    \"https://download.docker.com/${HOST_PLATFORM}/$(. /etc/os-release; echo \"$ID\")/gpg\" \\\n  | apt-key add -\n  add-apt-repository \\\n    \"deb [arch=${HOST_ARCH}] https://download.docker.com/${HOST_PLATFORM}/$(. /etc/os-release; echo \"$ID\") \\\n    $release stable\"\n\n  # Install containerd from Docker repo\n  apt-get update && \\\n    apt-get install -y --no-install-recommends containerd\n  rm -rf /var/lib/apt/lists/*\n\n  # Override to latest versions of containerd and runc\n  systemctl stop containerd\n  if [[ -n \"${UBUNTU_INSTALL_CONTAINERD_VERSION:-}\" ]]; then\n    # TODO(https://github.com/containerd/containerd/issues/2901): Remove this check once containerd has arm64 release.\n    if [[ $(dpkg --print-architecture) != \"amd64\" ]]; then\n      echo \"Unable to automatically install containerd in non-amd64 image. Bailing out...\"\n      exit 2\n    fi\n    # containerd versions have slightly different url(s), so try both\n    # shellcheck disable=SC2086\n    ( curl ${CURL_FLAGS} \\\n        --location \\\n        \"https://github.com/containerd/containerd/releases/download/${UBUNTU_INSTALL_CONTAINERD_VERSION}/containerd-${UBUNTU_INSTALL_CONTAINERD_VERSION:1}-${HOST_PLATFORM}-${HOST_ARCH}.tar.gz\" \\\n      || curl ${CURL_FLAGS} \\\n        --location \\\n        \"https://github.com/containerd/containerd/releases/download/${UBUNTU_INSTALL_CONTAINERD_VERSION}/containerd-${UBUNTU_INSTALL_CONTAINERD_VERSION:1}.${HOST_PLATFORM}-${HOST_ARCH}.tar.gz\" ) \\\n    | tar --overwrite -xzv -C /usr/\n  fi\n  if [[ -n \"${UBUNTU_INSTALL_RUNC_VERSION:-}\" ]]; then\n    # TODO: Remove this check once runc has arm64 release.\n    if [[ $(dpkg --print-architecture) != \"amd64\" ]]; then\n      echo \"Unable to automatically install runc in non-amd64. Bailing out...\"\n      exit 2\n    fi\n    # shellcheck disable=SC2086\n    curl ${CURL_FLAGS} \\\n      --location \\\n      \"https://github.com/opencontainers/runc/releases/download/${UBUNTU_INSTALL_RUNC_VERSION}/runc.${HOST_ARCH}\" --output /usr/sbin/runc \\\n    && chmod 755 /usr/sbin/runc\n  fi\n  sudo systemctl start containerd\n}\n\nfunction ensure-container-runtime {\n  container_runtime=\"${CONTAINER_RUNTIME:-docker}\"\n  if [[ \"${container_runtime}\" == \"docker\" ]]; then\n    if ! command -v docker >/dev/null 2>&1; then\n      install-docker\n      if ! command -v docker >/dev/null 2>&1; then\n        echo \"ERROR docker not found. Aborting.\"\n        exit 2\n      fi\n    fi\n    docker version\n  elif [[ \"${container_runtime}\" == \"containerd\" ]]; then\n    # Install containerd/runc if requested\n    if [[ -n \"${UBUNTU_INSTALL_CONTAINERD_VERSION:-}\" || -n \"${UBUNTU_INSTALL_RUNC_VERSION:-}\" ]]; then\n      install-containerd-ubuntu\n    fi\n    # Verify presence and print versions of ctr, containerd, runc\n    if ! command -v ctr >/dev/null 2>&1; then\n      echo \"ERROR ctr not found. Aborting.\"\n      exit 2\n    fi\n    ctr --version\n\n    if ! command -v containerd >/dev/null 2>&1; then\n      echo \"ERROR containerd not found. Aborting.\"\n      exit 2\n    fi\n    containerd --version\n\n    if ! command -v runc >/dev/null 2>&1; then\n      echo \"ERROR runc not found. Aborting.\"\n      exit 2\n    fi\n    runc --version\n  fi\n}\n\n# Downloads kubernetes binaries and kube-system manifest tarball, unpacks them,\n# and places them into suitable directories. Files are placed in /home/kubernetes.\nfunction install-kube-binary-config {\n  cd \"${KUBE_HOME}\"\n  local server_binary_tar_urls\n  while IFS= read -r url; do\n    server_binary_tar_urls+=(\"$url\")\n  done < <(split-commas \"${SERVER_BINARY_TAR_URL}\")\n  local -r server_binary_tar=\"${server_binary_tar_urls[0]##*/}\"\n  if [[ -n \"${SERVER_BINARY_TAR_HASH:-}\" ]]; then\n    local -r server_binary_tar_hash=\"${SERVER_BINARY_TAR_HASH}\"\n  else\n    echo \"Downloading binary release sha512 (not found in env)\"\n    download-or-bust \"\" \"${server_binary_tar_urls[@]/.tar.gz/.tar.gz.sha512}\"\n    local -r server_binary_tar_hash=$(cat \"${server_binary_tar}.sha512\")\n  fi\n\n  if is-preloaded \"${server_binary_tar}\" \"${server_binary_tar_hash}\"; then\n    echo \"${server_binary_tar} is preloaded.\"\n  else\n    echo \"Downloading binary release tar\"\n    download-or-bust \"${server_binary_tar_hash}\" \"${server_binary_tar_urls[@]}\"\n    tar xzf \"${KUBE_HOME}/${server_binary_tar}\" -C \"${KUBE_HOME}\" --overwrite\n    # Copy docker_tag and image files to ${KUBE_HOME}/kube-docker-files.\n    local -r src_dir=\"${KUBE_HOME}/kubernetes/server/bin\"\n    local dst_dir=\"${KUBE_HOME}/kube-docker-files\"\n    mkdir -p \"${dst_dir}\"\n    cp \"${src_dir}/\"*.docker_tag \"${dst_dir}\"\n    if [[ \"${KUBERNETES_MASTER:-}\" == \"false\" ]]; then\n      cp \"${src_dir}/kube-proxy.tar\" \"${dst_dir}\"\n    else\n      cp \"${src_dir}/kube-apiserver.tar\" \"${dst_dir}\"\n      cp \"${src_dir}/kube-controller-manager.tar\" \"${dst_dir}\"\n      cp \"${src_dir}/kube-scheduler.tar\" \"${dst_dir}\"\n      cp -r \"${KUBE_HOME}/kubernetes/addons\" \"${dst_dir}\"\n    fi\n    load-docker-images\n    mv \"${src_dir}/kubelet\" \"${KUBE_BIN}\"\n    mv \"${src_dir}/kubectl\" \"${KUBE_BIN}\"\n\n    # Some older images have LICENSES baked-in as a file. Presumably they will\n    # have the directory baked-in eventually.\n    rm -rf \"${KUBE_HOME}\"/LICENSES\n    mv \"${KUBE_HOME}/kubernetes/LICENSES\" \"${KUBE_HOME}\"\n    mv \"${KUBE_HOME}/kubernetes/kubernetes-src.tar.gz\" \"${KUBE_HOME}\"\n  fi\n\n  if [[ \"${KUBERNETES_MASTER:-}\" == \"false\" ]] && \\\n     [[ \"${ENABLE_NODE_PROBLEM_DETECTOR:-}\" == \"standalone\" ]]; then\n    install-node-problem-detector\n  fi\n\n  if [[ \"${NETWORK_PROVIDER:-}\" == \"kubenet\" ]] || \\\n     [[ \"${NETWORK_PROVIDER:-}\" == \"cni\" ]]; then\n    install-cni-binaries\n  fi\n\n  # Put kube-system pods manifests in ${KUBE_HOME}/kube-manifests/.\n  install-kube-manifests\n  chmod -R 755 \"${KUBE_BIN}\"\n\n  # Install gci mounter related artifacts to allow mounting storage volumes in GCI\n  install-gci-mounter-tools\n\n  # Remount the Flexvolume directory with the \"exec\" option, if needed.\n  if [[ \"${REMOUNT_VOLUME_PLUGIN_DIR:-}\" == \"true\" && -n \"${VOLUME_PLUGIN_DIR:-}\" ]]; then\n    remount-flexvolume-directory \"${VOLUME_PLUGIN_DIR}\"\n  fi\n\n  # Install crictl on each node.\n  install-crictl\n\n  # TODO(awly): include the binary and license in the OS image.\n  install-exec-auth-plugin\n\n  # Clean up.\n  rm -rf \"${KUBE_HOME}/kubernetes\"\n  rm -f \"${KUBE_HOME}/${server_binary_tar}\"\n  rm -f \"${KUBE_HOME}/${server_binary_tar}.sha512\"\n}\n\n\n# This function detects the platform/arch of the machine where the script runs,\n# and sets the HOST_PLATFORM and HOST_ARCH environment variables accordingly.\n# Callers can specify HOST_PLATFORM_OVERRIDE and HOST_ARCH_OVERRIDE to skip the detection.\n# This function is adapted from the detect_client_info function in cluster/get-kube-binaries.sh\n# and kube::util::host_os, kube::util::host_arch functions in hack/lib/util.sh\n# This function should be synced with detect_host_info in ./configure-helper.sh\nfunction detect_host_info() {\n  HOST_PLATFORM=${HOST_PLATFORM_OVERRIDE:-\"$(uname -s)\"}\n  case \"${HOST_PLATFORM}\" in\n    Linux|linux)\n      HOST_PLATFORM=\"linux\"\n      ;;\n    *)\n      echo \"Unknown, unsupported platform: ${HOST_PLATFORM}.\" >&2\n      echo \"Supported platform(s): linux.\" >&2\n      echo \"Bailing out.\" >&2\n      exit 2\n  esac\n\n  HOST_ARCH=${HOST_ARCH_OVERRIDE:-\"$(uname -m)\"}\n  case \"${HOST_ARCH}\" in\n    x86_64*|i?86_64*|amd64*)\n      HOST_ARCH=\"amd64\"\n      ;;\n    aHOST_arch64*|aarch64*|arm64*)\n      HOST_ARCH=\"arm64\"\n      ;;\n    *)\n      echo \"Unknown, unsupported architecture (${HOST_ARCH}).\" >&2\n      echo \"Supported architecture(s): amd64 and arm64.\" >&2\n      echo \"Bailing out.\" >&2\n      exit 2\n      ;;\n  esac\n}\n\n# Retries a command forever with a delay between retries.\n# Args:\n#  $1    : delay between retries, in seconds.\n#  $2... : the command to run.\nfunction retry-forever {\n  local -r delay=\"$1\"\n  shift 1\n\n  until \"$@\"; do\n    echo \"== $* failed, retrying after ${delay}s\"\n    sleep \"${delay}\"\n  done\n}\n\n# Initializes variables used by the log-* functions.\n#\n# get-metadata-value must be defined before calling this function.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-init {\n  # Used by log-* functions.\n  LOG_CLUSTER_ID=$(get-metadata-value 'instance/attributes/cluster-uid' 'get-metadata-value-error')\n  LOG_INSTANCE_NAME=$(hostname)\n  LOG_BOOT_ID=$(journalctl --list-boots | grep -E '^ *0' | awk '{print $2}')\n  declare -Ag LOG_START_TIMES\n  declare -ag LOG_TRAP_STACK\n\n  LOG_STATUS_STARTED='STARTED'\n  LOG_STATUS_COMPLETED='COMPLETED'\n  LOG_STATUS_ERROR='ERROR'\n}\n\n# Sets an EXIT trap.\n# Args:\n#   $1:... : the trap command.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-trap-push {\n  local t=\"${*:1}\"\n  LOG_TRAP_STACK+=(\"${t}\")\n  # shellcheck disable=2064\n  trap \"${t}\" EXIT\n}\n\n# Removes and restores an EXIT trap.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-trap-pop {\n  # Remove current trap.\n  unset 'LOG_TRAP_STACK[-1]'\n\n  # Restore previous trap.\n  if [ ${#LOG_TRAP_STACK[@]} -ne 0 ]; then\n    local t=\"${LOG_TRAP_STACK[-1]}\"\n    # shellcheck disable=2064\n    trap \"${t}\" EXIT\n  else\n    # If no traps in stack, clear.\n    trap EXIT\n  fi\n}\n\n# Logs the end of a bootstrap step that errored.\n# Args:\n#  $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-error {\n  local bootstep=\"$1\"\n\n  log-proto \"${bootstep}\" \"${LOG_STATUS_ERROR}\" \"encountered non-zero exit code\"\n}\n\n# Wraps a command with bootstrap logging.\n# Args:\n#   $1    : bootstrap step name.\n#   $2... : the command to run.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-wrap {\n  local bootstep=\"$1\"\n  local command=\"${*:2}\"\n\n  log-trap-push \"log-error ${bootstep}\"\n  log-proto \"${bootstep}\" \"${LOG_STATUS_STARTED}\"\n  $command\n  log-proto \"${bootstep}\" \"${LOG_STATUS_COMPLETED}\"\n  log-trap-pop\n}\n\n# Logs a bootstrap step start. Prefer log-wrap.\n# Args:\n#   $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-start {\n  local bootstep=\"$1\"\n\n  log-trap-push \"log-error ${bootstep}\"\n  log-proto \"${bootstep}\" \"${LOG_STATUS_STARTED}\"\n}\n\n# Logs a bootstrap step end. Prefer log-wrap.\n# Args:\n#   $1 : bootstrap step name.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-end {\n  local bootstep=\"$1\"\n\n  log-proto \"${bootstep}\" \"${LOG_STATUS_COMPLETED}\"\n  log-trap-pop\n}\n\n# Writes a log proto to stdout.\n# Args:\n#   $1: bootstrap step name.\n#   $2: status. Either 'STARTED', 'COMPLETED', or 'ERROR'.\n#   $3: optional status reason.\n#\n# NOTE: this function is duplicated in configure-helper.sh, any changes here\n# should be duplicated there as well.\nfunction log-proto {\n  local bootstep=\"$1\"\n  local status=\"$2\"\n  local status_reason=\"${3:-}\"\n\n  # Get current time.\n  local current_time\n  current_time=\"$(date --utc '+%s.%N')\"\n  # ...formatted as UTC RFC 3339.\n  local timestamp\n  timestamp=\"$(date --utc --date=\"@${current_time}\" '+%FT%T.%NZ')\"\n\n  # Calculate latency.\n  local latency='null'\n  if [ \"${status}\" == \"${LOG_STATUS_STARTED}\" ]; then\n    LOG_START_TIMES[\"${bootstep}\"]=\"${current_time}\"\n  else\n    local start_time=\"${LOG_START_TIMES[\"${bootstep}\"]}\"\n    unset 'LOG_START_TIMES['\"${bootstep}\"']'\n\n    # Bash cannot do non-integer math, shell out to awk.\n    latency=\"$(echo \"${current_time} ${start_time}\" | awk '{print $1 - $2}')s\"\n\n    # The default latency is null which cannot be wrapped as a string so we must\n    # do it here instead of the printf.\n    latency=\"\\\"${latency}\\\"\"\n  fi\n\n  printf '[cloud.kubernetes.monitoring.proto.SerialportLog] {\"cluster_hash\":\"%s\",\"vm_instance_name\":\"%s\",\"boot_id\":\"%s\",\"timestamp\":\"%s\",\"bootstrap_status\":{\"step_name\":\"%s\",\"status\":\"%s\",\"status_reason\":\"%s\",\"latency\":%s}}\\n' \\\n  \"${LOG_CLUSTER_ID}\" \"${LOG_INSTANCE_NAME}\" \"${LOG_BOOT_ID}\" \"${timestamp}\" \"${bootstep}\" \"${status}\" \"${status_reason}\" \"${latency}\"\n}\n\n######### Main Function ##########\nlog-init\nlog-start 'ConfigureMain'\necho \"Start to install kubernetes files\"\nlog-wrap 'DetectHostInfo' detect_host_info\n\n# if install fails, message-of-the-day (motd) will warn at login shell\nlog-wrap 'SetBrokenMotd' set-broken-motd\n\nKUBE_HOME=\"/home/kubernetes\"\nKUBE_BIN=\"${KUBE_HOME}/bin\"\n\n# download and source kube-env\nlog-wrap 'DownloadKubeEnv' download-kube-env\nlog-wrap 'SourceKubeEnv' source \"${KUBE_HOME}/kube-env\"\n\nlog-wrap 'DownloadKubeletConfig' download-kubelet-config \"${KUBE_HOME}/kubelet-config.yaml\"\n\n# master certs\nif [[ \"${KUBERNETES_MASTER:-}\" == \"true\" ]]; then\n  log-wrap 'DownloadKubeMasterCerts' download-kube-master-certs\nfi\n\n# ensure chosen container runtime is present\nlog-wrap 'EnsureContainerRuntime' ensure-container-runtime\n\n# binaries and kube-system manifests\nlog-wrap 'InstallKubeBinaryConfig' install-kube-binary-config\n\necho \"Done for installing kubernetes files\"\nlog-end 'ConfigureMain'\n", "num_lines": 896}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Sets up FlexVolume drivers on GCE COS instances using mounting utilities packaged in a Google\n# Container Registry image.\n# The user-provided FlexVolume driver(s) must be under /flexvolume of the image filesystem.\n# For example, the driver k8s/nfs must be located at /flexvolume/k8s~nfs/nfs .\n#\n# This script should be used on a clean instance, with no FlexVolume installed.\n# Should not be run on instances with an existing full or partial installation.\n# Upon failure, the script will clean up the partial installation automatically.\n#\n# Must be executed under /home/kubernetes/bin with sudo.\n# Warning: kubelet will be restarted upon successful execution.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMOUNTER_IMAGE=${1:-}\nMOUNTER_PATH=/home/kubernetes/flexvolume_mounter\nVOLUME_PLUGIN_DIR=/home/kubernetes/flexvolume\n\nusage() {\n  echo \"usage: $0 imagename[:tag]\"\n  echo \"    imagename  Name of a Container Registry image. By default the latest image is used.\"\n  echo \"    :tag       Container Registry image tag.\"\n  exit 1\n}\n\nif [ -z \"${MOUNTER_IMAGE}\" ]; then\n  echo \"ERROR: No Container Registry mounter image is specified.\"\n  echo\n  usage\nfi\n\n# Unmounts a mount point lazily. If a mount point does not exist, continue silently,\n# and without error.\numount_silent() {\n  umount -l \"$1\" &> /dev/null || /bin/true\n}\n\n# Waits for kubelet to restart for 1 minute.\nkubelet_wait() {\n  timeout=60\n  healthz_port=10248\n  until [[ $timeout -eq 0 ]]; do\n    printf \".\"\n    if [[ $( curl -s http://localhost:${healthz_port}/healthz ) == \"ok\" ]]; then\n      return 0\n    fi\n    sleep 1\n    timeout=$(( timeout-1 ))\n  done\n\n  # Timed out waiting for kubelet to become healthy.\n  return 1\n}\n\nflex_clean() {\n  echo\n  echo \"An error has occurred. Cleaning up...\"\n  echo\n\n  umount_silent ${VOLUME_PLUGIN_DIR}\n  rm -rf ${VOLUME_PLUGIN_DIR}\n  umount_silent ${MOUNTER_PATH}/var/lib/kubelet\n  umount_silent ${MOUNTER_PATH}\n  rm -rf ${MOUNTER_PATH}\n\n  if [[ -n ${IMAGE_URL:-} ]]; then\n    docker rmi -f \"${IMAGE_URL}\" &> /dev/null || /bin/true\n  fi\n  if [[ -n ${MOUNTER_DEFAULT_NAME:-} ]]; then\n    docker rm -f \"${MOUNTER_DEFAULT_NAME}\" &> /dev/null || /bin/true\n  fi\n}\n\ntrap flex_clean ERR\n\n# Generates a bash script that wraps all calls to the actual driver inside mount utilities\n# in the chroot environment. Kubelet sees this script as the FlexVolume driver.\ngenerate_chroot_wrapper() {\n  if [ ! -d ${MOUNTER_PATH}/flexvolume ]; then\n    echo \"Failed to set up FlexVolume driver: cannot find directory '/flexvolume' in the mount utility image.\"\n    exit 1\n  fi\n\n  for driver_dir in \"${MOUNTER_PATH}/flexvolume\"/*; do\n    if [ -d \"$driver_dir\" ]; then\n\n      filecount=$(cd \"$driver_dir\"; find . -mindepth 1 -maxdepth 1 -print0 | xargs -0 -n1 basename | wc -l)\n      if [ \"$filecount\" -gt 1 ]; then\n        echo \"ERROR: Expected 1 file in the FlexVolume directory but found $filecount.\"\n        exit 1\n      fi\n\n      driver_file=$(cd \"$driver_dir\"; find . -mindepth 1 -maxdepth 1 -print0 | xargs -0 -n1 basename | head -n 1)\n\n      # driver_path points to the actual driver inside the mount utility image,\n      # relative to image root.\n      # wrapper_path is the wrapper script location, which is known to kubelet.\n      driver_path=flexvolume/$( basename \"$driver_dir\" )/${driver_file}\n      wrapper_dir=${VOLUME_PLUGIN_DIR}/$( basename \"$driver_dir\" )\n      wrapper_path=${wrapper_dir}/${driver_file}\n\n      mkdir -p \"$wrapper_dir\"\n      cat >\"$wrapper_path\" <<EOF\n#!/usr/bin/env bash\nchroot ${MOUNTER_PATH} ${driver_path} \"\\$@\"\nEOF\n\n      chmod 755 \"$wrapper_path\"\n      echo \"FlexVolume driver installed at ${wrapper_path}\"\n    fi\n  done\n}\n\necho\necho \"Importing mount utility image from Container Registry...\"\necho\n\nMETADATA=http://metadata.google.internal/computeMetadata/v1\nSVC_ACCT_ENDPOINT=$METADATA/instance/service-accounts/default\nACCESS_TOKEN=$(curl -s -H 'Metadata-Flavor: Google' $SVC_ACCT_ENDPOINT/token | cut -d'\"' -f 4)\nPROJECT_ID=$(curl -s -H 'Metadata-Flavor: Google' $METADATA/project/project-id)\nIMAGE_URL=gcr.io/${PROJECT_ID}/${MOUNTER_IMAGE}\nMOUNTER_DEFAULT_NAME=flexvolume_mounter\nsudo -u \"${SUDO_USER}\" docker login -u _token -p \"$ACCESS_TOKEN\" https://gcr.io > /dev/null\nsudo -u \"${SUDO_USER}\" docker run --name=${MOUNTER_DEFAULT_NAME} \"${IMAGE_URL}\"\ndocker export ${MOUNTER_DEFAULT_NAME} > /tmp/${MOUNTER_DEFAULT_NAME}.tar\ndocker rm ${MOUNTER_DEFAULT_NAME} > /dev/null\ndocker rmi \"${IMAGE_URL}\" > /dev/null\n\necho\necho \"Loading mount utilities onto this instance...\"\necho\n\nmkdir -p ${MOUNTER_PATH}\ntar xf /tmp/${MOUNTER_DEFAULT_NAME}.tar -C ${MOUNTER_PATH}\n\n# Bind the kubelet directory to one under flexvolume_mounter\nmkdir -p ${MOUNTER_PATH}/var/lib/kubelet\nmount --rbind /var/lib/kubelet/ ${MOUNTER_PATH}/var/lib/kubelet\nmount --make-rshared ${MOUNTER_PATH}/var/lib/kubelet\n\n# Remount the flexvolume_mounter environment with /dev enabled.\nmount --bind ${MOUNTER_PATH} ${MOUNTER_PATH}\nmount -o remount,dev,exec ${MOUNTER_PATH}\n\necho\necho \"Setting up FlexVolume driver...\"\necho\n\nmkdir -p ${VOLUME_PLUGIN_DIR}\nmount --bind ${VOLUME_PLUGIN_DIR} ${VOLUME_PLUGIN_DIR}\nmount -o remount,exec ${VOLUME_PLUGIN_DIR}\ngenerate_chroot_wrapper\n\necho\necho \"Restarting Kubelet...\"\necho\n\nsystemctl restart kubelet.service\nif kubelet_wait; then\n  echo\n  echo \"FlexVolume is ready.\"\nelse\n  echo \"ERROR: Timed out after 1 minute waiting for kubelet restart.\"\nfi\n", "num_lines": 184}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is for master and node instance health monitoring, which is\n# packed in kube-manifest tarball. It is executed through a systemd service\n# in cluster/gce/gci/<master/node>.yaml. The env variables come from an env\n# file provided by the systemd service.\n\nset -o nounset\nset -o pipefail\n\n# We simply kill the process when there is a failure. Another systemd service will\n# automatically restart the process.\nfunction container_runtime_monitoring {\n  local -r max_attempts=5\n  local attempt=1\n  local -r crictl=\"${KUBE_HOME}/bin/crictl\"\n  local -r container_runtime_name=\"${CONTAINER_RUNTIME_NAME:-docker}\"\n  # We still need to use `docker ps` when container runtime is \"docker\". This is because\n  # dockershim is still part of kubelet today. When kubelet is down, crictl pods\n  # will also fail, and docker will be killed. This is undesirable especially when\n  # docker live restore is disabled.\n  local healthcheck_command=(docker ps)\n  if [[ \"${CONTAINER_RUNTIME:-docker}\" != \"docker\" ]]; then\n    healthcheck_command=(\"${crictl}\" pods)\n  fi\n  # Container runtime startup takes time. Make initial attempts before starting\n  # killing the container runtime.\n  until timeout 60 \"${healthcheck_command[@]}\" > /dev/null; do\n    if (( attempt == max_attempts )); then\n      echo \"Max attempt ${max_attempts} reached! Proceeding to monitor container runtime healthiness.\"\n      break\n    fi\n    echo \"$attempt initial attempt \\\"${healthcheck_command[*]}\\\"! Trying again in $attempt seconds...\"\n    sleep \"$(( 2 ** attempt++ ))\"\n  done\n  while true; do\n    if ! timeout 60 \"${healthcheck_command[@]}\" > /dev/null; then\n      echo \"Container runtime ${container_runtime_name} failed!\"\n      if [[ \"$container_runtime_name\" == \"docker\" ]]; then\n          # Dump stack of docker daemon for investigation.\n          # Log fle name looks like goroutine-stacks-TIMESTAMP and will be saved to\n          # the exec root directory, which is /var/run/docker/ on Ubuntu and COS.\n          pkill -SIGUSR1 dockerd\n      fi\n      systemctl kill --kill-who=main \"${container_runtime_name}\"\n      # Wait for a while, as we don't want to kill it again before it is really up.\n      sleep 120\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\nfunction kubelet_monitoring {\n  echo \"Wait for 2 minutes for kubelet to be functional\"\n  # TODO(andyzheng0831): replace it with a more reliable method if possible.\n  sleep 120\n  local -r max_seconds=10\n  local output=\"\"\n  while true; do\n    if ! output=$(curl -m \"${max_seconds}\" -f -s -S http://127.0.0.1:10248/healthz 2>&1); then\n      # Print the response and/or errors.\n      echo \"${output}\"\n      echo \"Kubelet is unhealthy!\"\n      systemctl kill kubelet\n      # Wait for a while, as we don't want to kill it again before it is really up.\n      sleep 60\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\n\n############## Main Function ################\nif [[ \"$#\" -ne 1 ]]; then\n  echo \"Usage: health-monitor.sh <container-runtime/kubelet>\"\n  exit 1\nfi\n\nKUBE_HOME=\"/home/kubernetes\"\nKUBE_ENV=\"${KUBE_HOME}/kube-env\"\nif [[ ! -e \"${KUBE_ENV}\" ]]; then\n  echo \"The ${KUBE_ENV} file does not exist!! Terminate health monitoring\"\n  exit 1\nfi\n\nSLEEP_SECONDS=10\ncomponent=$1\necho \"Start kubernetes health monitoring for ${component}\"\nsource \"${KUBE_ENV}\"\nif [[ \"${component}\" == \"container-runtime\" ]]; then\n  container_runtime_monitoring\nelif [[ \"${component}\" == \"kubelet\" ]]; then\n  kubelet_monitoring\nelse\n  echo \"Health monitoring for component \\\"${component}\\\" is not supported!\"\nfi\n", "num_lines": 113}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions and constant for GCI distro\n\n# Creates the GCI specific metadata files if they do not exit.\n# Assumed var\n#   KUBE_TEMP\nfunction ensure-gci-metadata-files {\n  if [[ ! -f \"${KUBE_TEMP}/gci-update.txt\" ]]; then\n    echo -n \"update_disabled\" > \"${KUBE_TEMP}/gci-update.txt\"\n  fi\n  if [[ ! -f \"${KUBE_TEMP}/gci-ensure-gke-docker.txt\" ]]; then\n    echo -n \"true\" > \"${KUBE_TEMP}/gci-ensure-gke-docker.txt\"\n  fi\n  if [[ ! -f \"${KUBE_TEMP}/gci-docker-version.txt\" ]]; then\n    echo -n \"${GCI_DOCKER_VERSION:-}\" > \"${KUBE_TEMP}/gci-docker-version.txt\"\n  fi\n}\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nMETADATA_ENDPOINT=\"http://metadata.google.internal/computeMetadata/v1/instance/attributes/kube-master-internal-ip\"\nMETADATA_HEADER=\"Metadata-Flavor: Google\"\nip=$(curl -s --fail ${METADATA_ENDPOINT} -H \"${METADATA_HEADER}\")\nif [ -n \"$ip\" ];\nthen\n    # Check if route is already set if not set it\n    if ! sudo ip route show table local | grep -q \"$(echo \"$ip\" | cut -d'/' -f 1)\";\n    then\n            sudo ip route add to local \"${ip}/32\" dev \"$(ip route | grep default | awk '{print $5}')\"\n    fi\nfi\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions and constant for GCI distro\nsource \"${KUBE_ROOT}/cluster/gce/gci/helper.sh\"\n\n# create-master-instance creates the master instance. If called with\n# an argument, the argument is used as the name to a reserved IP\n# address for the master. (In the case of upgrade/repair, we re-use\n# the same IP.)\n#\n# It requires a whole slew of assumed variables, partially due to to\n# the call to write-master-env. Listing them would be rather\n# futile. Instead, we list the required calls to ensure any additional\n#\n# variables are set:\n#   ensure-temp-dir\n#   detect-project\n#   get-bearer-token\nfunction create-master-instance {\n  local address=\"\"\n  [[ -n ${1:-} ]] && address=\"${1}\"\n  local internal_address=\"\"\n  [[ -n ${2:-} ]] && internal_address=\"${2}\"\n\n  write-master-env\n  ensure-gci-metadata-files\n  # shellcheck disable=SC2153 # 'MASTER_NAME' is assigned by upstream\n  create-master-instance-internal \"${MASTER_NAME}\" \"${address}\" \"${internal_address}\"\n}\n\nfunction replicate-master-instance() {\n  local existing_master_zone=\"${1}\"\n  local existing_master_name=\"${2}\"\n  local existing_master_replicas=\"${3}\"\n\n  local kube_env\n  kube_env=\"$(get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" kube-env)\"\n  # Substitute INITIAL_ETCD_CLUSTER to enable etcd clustering.\n  kube_env=\"$(echo \"${kube_env}\" | grep -v \"INITIAL_ETCD_CLUSTER\")\"\n  kube_env=\"$(echo -e \"${kube_env}\\nINITIAL_ETCD_CLUSTER: '${existing_master_replicas},${REPLICA_NAME}'\")\"\n\n  # Substitute INITIAL_ETCD_CLUSTER_STATE\n  kube_env=\"$(echo \"${kube_env}\" | grep -v \"INITIAL_ETCD_CLUSTER_STATE\")\"\n  kube_env=\"$(echo -e \"${kube_env}\\nINITIAL_ETCD_CLUSTER_STATE: 'existing'\")\"\n\n  ETCD_CA_KEY=\"$(echo \"${kube_env}\" | grep \"ETCD_CA_KEY\" |  sed \"s/^.*: '//\" | sed \"s/'$//\")\"\n  ETCD_CA_CERT=\"$(echo \"${kube_env}\" | grep \"ETCD_CA_CERT\" |  sed \"s/^.*: '//\" | sed \"s/'$//\")\"\n  create-etcd-certs \"${REPLICA_NAME}\" \"${ETCD_CA_CERT}\" \"${ETCD_CA_KEY}\"\n\n  kube_env=\"$(echo \"${kube_env}\" | grep -v \"ETCD_PEER_KEY\")\"\n  kube_env=\"$(echo -e \"${kube_env}\\nETCD_PEER_KEY: '${ETCD_PEER_KEY_BASE64}'\")\"\n  kube_env=\"$(echo \"${kube_env}\" | grep -v \"ETCD_PEER_CERT\")\"\n  kube_env=\"$(echo -e \"${kube_env}\\nETCD_PEER_CERT: '${ETCD_PEER_CERT_BASE64}'\")\"\n\n  local master_certs\n  master_certs=\"$(get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" kube-master-certs)\"\n\n  ETCD_APISERVER_CA_KEY=\"$(echo \"${master_certs}\" | grep \"ETCD_APISERVER_CA_KEY\" |  sed \"s/^.*: '//\" | sed \"s/'$//\")\"\n  ETCD_APISERVER_CA_CERT=\"$(echo \"${master_certs}\" | grep \"ETCD_APISERVER_CA_CERT\" |  sed \"s/^.*: '//\" | sed \"s/'$//\")\"\n  create-etcd-apiserver-certs \"etcd-${REPLICA_NAME}\" \"${REPLICA_NAME}\" \"${ETCD_APISERVER_CA_CERT}\" \"${ETCD_APISERVER_CA_KEY}\"\n\n  master_certs=\"$(echo \"${master_certs}\" | grep -v \"ETCD_APISERVER_SERVER_KEY\")\"\n  master_certs=\"$(echo -e \"${master_certs}\\nETCD_APISERVER_SERVER_KEY: '${ETCD_APISERVER_SERVER_KEY_BASE64}'\")\"\n  master_certs=\"$(echo \"${master_certs}\" | grep -v \"ETCD_APISERVER_SERVER_CERT\")\"\n  master_certs=\"$(echo -e \"${master_certs}\\nETCD_APISERVER_SERVER_CERT: '${ETCD_APISERVER_SERVER_CERT_BASE64}'\")\"\n  master_certs=\"$(echo \"${master_certs}\" | grep -v \"ETCD_APISERVER_CLIENT_KEY\")\"\n  master_certs=\"$(echo -e \"${master_certs}\\nETCD_APISERVER_CLIENT_KEY: '${ETCD_APISERVER_CLIENT_KEY_BASE64}'\")\"\n  master_certs=\"$(echo \"${master_certs}\" | grep -v \"ETCD_APISERVER_CLIENT_CERT\")\"\n  master_certs=\"$(echo -e \"${master_certs}\\nETCD_APISERVER_CLIENT_CERT: '${ETCD_APISERVER_CLIENT_CERT_BASE64}'\")\"\n\n  echo \"${kube_env}\" > \"${KUBE_TEMP}/master-kube-env.yaml\"\n  echo \"${master_certs}\" > \"${KUBE_TEMP}/kube-master-certs.yaml\"\n  get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" cluster-name > \"${KUBE_TEMP}/cluster-name.txt\"\n  get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" gci-update-strategy > \"${KUBE_TEMP}/gci-update.txt\"\n  get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" gci-ensure-gke-docker > \"${KUBE_TEMP}/gci-ensure-gke-docker.txt\"\n  get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" gci-docker-version > \"${KUBE_TEMP}/gci-docker-version.txt\"\n  get-metadata \"${existing_master_zone}\" \"${existing_master_name}\" cluster-location > \"${KUBE_TEMP}/cluster-location.txt\"\n\n  create-master-instance-internal \"${REPLICA_NAME}\"\n}\n\n\n# run-gcloud-command runs a given command over ssh with retries.\nfunction run-gcloud-command() {\n  local master_name=\"${1}\"\n  local zone=\"${2}\"\n  local command=\"${3}\"\n\n  local retries=5\n  local sleep_sec=10\n\n  local result=\"\"\n\n  for ((i=0; i<retries; i++)); do\n    if result=$(gcloud compute ssh \"${master_name}\" --project \"${PROJECT}\" --zone \"${zone}\" --command \"${command}\" -- -oConnectTimeout=60 2>&1); then\n      echo \"Successfully executed '${command}' on ${master_name}\"\n      return 0\n    fi\n\n    sleep \"${sleep_sec}\"\n  done\n  echo \"Failed to execute '${command}' on ${master_name} despite ${retries} attempts\" >&2\n  echo \"Last attempt failed with: ${result}\" >&2\n  return 1\n}\n\n\nfunction create-master-instance-internal() {\n  local gcloud=\"gcloud\"\n  local retries=5\n  local sleep_sec=10\n  if [[ \"${MASTER_SIZE##*-}\" -ge 64 ]]; then  # remove everything up to last dash (inclusive)\n    # Workaround for #55777\n    retries=30\n    sleep_sec=60\n  fi\n\n  local -r master_name=\"${1}\"\n  local -r address=\"${2:-}\"\n  local -r internal_address=\"${3:-}\"\n\n  local preemptible_master=\"\"\n  if [[ \"${PREEMPTIBLE_MASTER:-}\" == \"true\" ]]; then\n    preemptible_master=\"--preemptible --maintenance-policy TERMINATE\"\n  fi\n\n  local enable_ip_aliases\n  if [[ \"${NODE_IPAM_MODE:-}\" == \"CloudAllocator\" ]]; then\n    enable_ip_aliases=true\n  else\n    enable_ip_aliases=false\n  fi\n\n  local network\n  # shellcheck disable=SC2153 # 'NETWORK' is assigned by upstream\n  network=$(make-gcloud-network-argument \\\n    \"${NETWORK_PROJECT}\" \"${REGION}\" \"${NETWORK}\" \"${SUBNETWORK:-}\" \\\n    \"${address:-}\" \"${enable_ip_aliases:-}\" \"${IP_ALIAS_SIZE:-}\")\n\n  local metadata=\"kube-env=${KUBE_TEMP}/master-kube-env.yaml\"\n  metadata=\"${metadata},kubelet-config=${KUBE_TEMP}/master-kubelet-config.yaml\"\n  metadata=\"${metadata},user-data=${KUBE_ROOT}/cluster/gce/gci/master.yaml\"\n  metadata=\"${metadata},configure-sh=${KUBE_ROOT}/cluster/gce/gci/configure.sh\"\n  metadata=\"${metadata},cluster-location=${KUBE_TEMP}/cluster-location.txt\"\n  metadata=\"${metadata},cluster-name=${KUBE_TEMP}/cluster-name.txt\"\n  metadata=\"${metadata},gci-update-strategy=${KUBE_TEMP}/gci-update.txt\"\n  metadata=\"${metadata},gci-ensure-gke-docker=${KUBE_TEMP}/gci-ensure-gke-docker.txt\"\n  metadata=\"${metadata},gci-docker-version=${KUBE_TEMP}/gci-docker-version.txt\"\n  metadata=\"${metadata},kube-master-certs=${KUBE_TEMP}/kube-master-certs.yaml\"\n  metadata=\"${metadata},cluster-location=${KUBE_TEMP}/cluster-location.txt\"\n  metadata=\"${metadata},kube-master-internal-route=${KUBE_ROOT}/cluster/gce/gci/kube-master-internal-route.sh\"\n  metadata=\"${metadata},${MASTER_EXTRA_METADATA}\"\n\n  local disk=\"name=${master_name}-pd\"\n  disk=\"${disk},device-name=master-pd\"\n  disk=\"${disk},mode=rw\"\n  disk=\"${disk},boot=no\"\n  disk=\"${disk},auto-delete=no\"\n\n  for ((i=0; i<retries; i++)); do\n    # We expect ZONE to be set and deliberately do not quote preemptible_master\n    # and network\n    # shellcheck disable=SC2153 disable=SC2086\n    if result=$(${gcloud} compute instances create \"${master_name}\" \\\n      --project \"${PROJECT}\" \\\n      --zone \"${ZONE}\" \\\n      --machine-type \"${MASTER_SIZE}\" \\\n      --image-project=\"${MASTER_IMAGE_PROJECT}\" \\\n      --image \"${MASTER_IMAGE}\" \\\n      --tags \"${MASTER_TAG}\" \\\n      --scopes \"storage-ro,compute-rw,monitoring,logging-write\" \\\n      --metadata-from-file \"${metadata}\" \\\n      --disk \"${disk}\" \\\n      --boot-disk-size \"${MASTER_ROOT_DISK_SIZE}\" \\\n      ${MASTER_MIN_CPU_ARCHITECTURE:+\"--min-cpu-platform=${MASTER_MIN_CPU_ARCHITECTURE}\"} \\\n      ${preemptible_master} \\\n      ${network} 2>&1); then\n      echo \"${result}\" >&2\n\n      if [[ -n \"${internal_address:-}\" ]]; then\n        attach-internal-master-ip \"${master_name}\" \"${ZONE}\" \"${internal_address}\"\n      fi\n      return 0\n    else\n      echo \"${result}\" >&2\n      if [[ ! \"${result}\" =~ \"try again later\" ]]; then\n        echo \"Failed to create master instance due to non-retryable error\" >&2\n        return 1\n      fi\n      sleep $sleep_sec\n    fi\n  done\n\n  echo \"Failed to create master instance despite ${retries} attempts\" >&2\n  return 1\n}\n\nfunction get-metadata() {\n  local zone=\"${1}\"\n  local name=\"${2}\"\n  local key=\"${3}\"\n  gcloud compute ssh \"${name}\" \\\n    --project \"${PROJECT}\" \\\n    --zone \"${zone}\" \\\n    --command \"curl \\\"http://metadata.google.internal/computeMetadata/v1/instance/attributes/${key}\\\" -H \\\"Metadata-Flavor: Google\\\"\" 2>/dev/null\n}\n", "num_lines": 221}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions and constant for GCI distro\nsource \"${KUBE_ROOT}/cluster/gce/gci/helper.sh\"\n\n# shellcheck disable=SC2120\nfunction get-node-instance-metadata-from-file {\n  local kube_env=${1:-node-kube-env} # optional\n  local metadata=\"\"\n  metadata+=\"kube-env=${KUBE_TEMP}/${kube_env}.yaml,\"\n  metadata+=\"kubelet-config=${KUBE_TEMP}/node-kubelet-config.yaml,\"\n  metadata+=\"user-data=${KUBE_ROOT}/cluster/gce/gci/node.yaml,\"\n  metadata+=\"configure-sh=${KUBE_ROOT}/cluster/gce/gci/configure.sh,\"\n  metadata+=\"cluster-location=${KUBE_TEMP}/cluster-location.txt,\"\n  metadata+=\"cluster-name=${KUBE_TEMP}/cluster-name.txt,\"\n  metadata+=\"gci-update-strategy=${KUBE_TEMP}/gci-update.txt,\"\n  metadata+=\"gci-ensure-gke-docker=${KUBE_TEMP}/gci-ensure-gke-docker.txt,\"\n  metadata+=\"gci-docker-version=${KUBE_TEMP}/gci-docker-version.txt,\"\n  metadata+=\"shutdown-script=${KUBE_ROOT}/cluster/gce/gci/shutdown.sh,\"\n  metadata+=\"${NODE_EXTRA_METADATA}\"\n  echo \"${metadata}\"\n}\n\n# Assumed vars:\n#   scope_flags\n# Parameters:\n#   $1: template name (required).\nfunction create-linux-node-instance-template {\n  local template_name=\"$1\"\n  local machine_type=\"${2:-$NODE_SIZE}\"\n\n  ensure-gci-metadata-files\n  # shellcheck disable=2154 # 'scope_flags' is assigned by upstream\n  create-node-template \"${template_name}\" \"${scope_flags[*]}\" \"$(get-node-instance-metadata-from-file)\" \"\" \"linux\" \"${machine_type}\"\n}\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A script that let's gci preemptible nodes gracefully terminate in the event of a VM shutdown.\npreemptible=$(curl \"http://metadata.google.internal/computeMetadata/v1/instance/scheduling/preemptible\" -H \"Metadata-Flavor: Google\")\nif [ \"${preemptible}\" == \"TRUE\" ]; then\n    echo \"Shutting down! Sleeping for a minute to let the node gracefully terminate\"\n    # https://cloud.google.com/compute/docs/instances/stopping-or-deleting-an-instance#delete_timeout\n    sleep 30\nfi\n", "num_lines": 24}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Due to the GCE custom metadata size limit, we split the entire script into two\n# files configure.sh and configure-helper.sh. The functionality of downloading\n# kubernetes configuration, manifests, docker images, and binary files are\n# put in configure.sh, which is uploaded via GCE custom metadata.\n\nset -o errexit\nset -o pipefail\nset -o nounset\n\nDOCKER2ACI_VERSION=\"v0.13.0\"\nMOUNTER_VERSION=$1\nDOCKER_IMAGE=docker://$2\nMOUNTER_ACI_IMAGE=gci-mounter-${MOUNTER_VERSION}.aci\nMOUNTER_GCS_DIR=gs://kubernetes-release/gci-mounter/\n\nTMPDIR=/tmp\n# Setup a working directory\nDOWNLOAD_DIR=$(mktemp --tmpdir=${TMPDIR} -d gci-mounter-build.XXXXXXXXXX)\n\n# Setup a staging directory\nSTAGING_DIR=$(mktemp --tmpdir=${TMPDIR} -d gci-mounter-staging.XXXXXXXXXX)\nACI_DIR=${STAGING_DIR}/gci-mounter\nCWD=${PWD}\n\n# Cleanup the temporary directories\ncleanup() {\n    rm -rf \"${DOWNLOAD_DIR}\"\n    rm -rf \"${STAGING_DIR}\"\n    cd \"${CWD}\"\n}\n\n# Delete temporary directories on exit\ntrap cleanup EXIT\n\nmkdir \"${ACI_DIR}\"\n\n# Convert docker image to aci and stage it\necho \"Downloading docker2aci ${DOCKER2ACI_VERSION}\"\nwget \"https://github.com/appc/docker2aci/releases/download/${DOCKER2ACI_VERSION}/docker2aci-${DOCKER2ACI_VERSION}.tar.gz\" >/dev/null 2>&1\necho \"Extracting docker2aci ${DOCKER2ACI_VERSION}\"\ntar xzf docker2aci-${DOCKER2ACI_VERSION}.tar.gz\nACI_IMAGE=$(\"${DOWNLOAD_DIR}/docker2aci-${DOCKER2ACI_VERSION}/docker2aci\" \"${DOCKER_IMAGE}\" 2>/dev/null | tail -n 1)\ncp \"${ACI_IMAGE}\" \"${ACI_DIR}/${MOUNTER_ACI_IMAGE}\"\n\n# Upload the contents to gcs\necho \"Uploading gci mounter ACI in ${ACI_DIR} to ${MOUNTER_GCS_DIR}\"\ngsutil cp \"${ACI_DIR}/${MOUNTER_ACI_IMAGE}\" \"${MOUNTER_GCS_DIR}\"\n\necho \"Upload completed\"\necho \"Updated gci-mounter ACI version and SH512 in cluster/gce/gci/configure.sh\"\nACI_HASH=$(sha512sum \"${ACI_DIR}/${MOUNTER_ACI_IMAGE}\")\necho \"${MOUNTER_ACI_IMAGE} hash: ${ACI_HASH}\"\n", "num_lines": 69}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions and constants for Windows nodes.\n\nfunction get-windows-node-instance-metadata-from-file {\n  local metadata=\"\"\n  metadata+=\"cluster-name=${KUBE_TEMP}/cluster-name.txt,\"\n  metadata+=\"cluster-location=${KUBE_TEMP}/cluster-location.txt,\"\n  metadata+=\"kube-env=${KUBE_TEMP}/windows-node-kube-env.yaml,\"\n  metadata+=\"kubelet-config=${KUBE_TEMP}/windows-node-kubelet-config.yaml,\"\n  # To get startup script output run \"gcloud compute instances\n  # get-serial-port-output <instance>\" from the location where you're running\n  # kube-up.\n  metadata+=\"windows-startup-script-ps1=${KUBE_ROOT}/cluster/gce/windows/configure.ps1,\"\n  metadata+=\"common-psm1=${KUBE_ROOT}/cluster/gce/windows/common.psm1,\"\n  metadata+=\"k8s-node-setup-psm1=${KUBE_ROOT}/cluster/gce/windows/k8s-node-setup.psm1,\"\n  metadata+=\"install-ssh-psm1=${KUBE_ROOT}/cluster/gce/windows/testonly/install-ssh.psm1,\"\n  metadata+=\"user-profile-psm1=${KUBE_ROOT}/cluster/gce/windows/testonly/user-profile.psm1,\"\n  metadata+=\"${NODE_EXTRA_METADATA}\"\n  echo \"${metadata}\"\n}\n\nfunction get-windows-node-instance-metadata {\n  local metadata=\"\"\n  metadata+=\"k8s-version=${KUBE_VERSION:-v1.13.2},\"\n  # Prevent the GCE Windows agent from managing IP addresses, since kube-proxy\n  # and these cluster setup scripts should take care of everything. See\n  # https://github.com/kubernetes/kubernetes/issues/75561.\n  metadata+=\"disable-address-manager=true,\"\n  metadata+=\"serial-port-enable=1,\"\n  # This enables logging the serial port output.\n  # https://cloud.google.com/compute/docs/instances/viewing-serial-port-output\n  metadata+=\"serial-port-logging-enable=true,\"\n  metadata+=\"win-version=${WINDOWS_NODE_OS_DISTRIBUTION}\"\n  echo \"${metadata}\"\n}\n\n# $1: template name (required).\n# $2: scopes flag.\nfunction create-windows-node-instance-template {\n  local template_name=\"$1\"\n  local scopes_flag=\"$2\"\n  create-node-template \"${template_name}\" \"${scopes_flag}\" \"$(get-windows-node-instance-metadata-from-file)\" \"$(get-windows-node-instance-metadata)\" \"windows\" \"${NODE_SIZE}\"\n}\n", "num_lines": 59}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A small smoke test to run against a just-deployed kube-up cluster with Windows\n# nodes. Performs checks such as:\n#   1) Verifying that all Windows nodes have status Ready.\n#   2) Verifying that no system pods are attempting to run on Windows nodes.\n#   3) Verifying pairwise connectivity between most of the following: Linux\n#      pods, Windows pods, K8s services, and the Internet.\n#   4) Verifying that basic DNS resolution works in Windows pods.\n#\n# This script assumes that it is run from the root of the kubernetes repository.\n#\n# TODOs:\n#   - Implement the node-to-pod checks.\n#   - Capture stdout for each command to a file and only print it when the test\n#     fails.\n#   - Move copy-pasted code into reusable functions.\n#   - Continue running all checks after one fails.\n#   - Test service connectivity by running a test pod with an http server and\n#     exposing it as a service (rather than curl-ing from existing system\n#     services that don't serve http requests).\n#   - Add test retries for transient errors, such as:\n#     \"error: unable to upgrade connection: Authorization error\n#     (user=kube-apiserver, verb=create, resource=nodes, subresource=proxy)\"\n\n# Override this to use a different kubectl binary.\nkubectl=kubectl\nlinux_deployment_timeout=60\nwindows_deployment_timeout=600\noutput_file=/tmp/k8s-smoke-test.out\n\nfunction check_windows_nodes_are_ready {\n  # kubectl filtering is the worst.\n  statuses=$(${kubectl} get nodes -l kubernetes.io/os=windows \\\n    -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}')\n  for status in $statuses; do\n    if [[ $status == \"False\" ]]; then\n      echo \"ERROR: some Windows node has status != Ready\"\n      echo \"kubectl get nodes -l kubernetes.io/os=windows\"\n      ${kubectl} get nodes -l kubernetes.io/os=windows\n      exit 1\n    fi\n  done\n  echo \"Verified that all Windows nodes have status Ready\"\n}\n\nfunction untaint_windows_nodes {\n  # Untaint the windows nodes to allow test workloads without tolerations to be\n  # scheduled onto them.\n  WINDOWS_NODES=$(${kubectl} get nodes -l kubernetes.io/os=windows -o name)\n  for node in $WINDOWS_NODES; do\n    ${kubectl} taint node \"$node\" node.kubernetes.io/os:NoSchedule-\n  done\n}\n\nfunction check_no_system_pods_on_windows_nodes {\n  windows_system_pods=$(${kubectl} get pods --namespace kube-system \\\n    -o wide | grep -E \"Pending|windows\" | wc -w)\n  if [[ $windows_system_pods -ne 0 ]]; then\n    echo \"ERROR: there are kube-system pods trying to run on Windows nodes\"\n    echo \"kubectl get pods --namespace kube-system -o wide\"\n    ${kubectl} get pods --namespace kube-system -o wide\n    exit 1\n  fi\n  echo \"Verified that all system pods are running on Linux nodes\"\n}\n\nlinux_webserver_deployment=linux-nginx\nlinux_webserver_pod_label=nginx\nlinux_webserver_replicas=1\n\nfunction deploy_linux_webserver_pod {\n  echo \"Writing example deployment to $linux_webserver_deployment.yaml\"\n  cat <<EOF > $linux_webserver_deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: $linux_webserver_deployment\n  labels:\n    app: $linux_webserver_pod_label\nspec:\n  replicas: $linux_webserver_replicas\n  selector:\n    matchLabels:\n      app: $linux_webserver_pod_label\n  template:\n    metadata:\n      labels:\n        app: $linux_webserver_pod_label\n    spec:\n      containers:\n      - name: nginx\n        image: nginx:1.7.9\n      nodeSelector:\n        kubernetes.io/os: linux\nEOF\n\n  if ! ${kubectl} create -f $linux_webserver_deployment.yaml; then\n    echo \"kubectl create -f $linux_webserver_deployment.yaml failed\"\n    exit 1\n  fi\n\n  timeout=$linux_deployment_timeout\n  while [[ $timeout -gt 0 ]]; do\n    echo \"Waiting for $linux_webserver_replicas Linux $linux_webserver_pod_label pods to become Ready\"\n    statuses=$(${kubectl} get pods -l app=$linux_webserver_pod_label \\\n      -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}' \\\n      | grep \"True\" | wc -w)\n    if [[ $statuses -eq $linux_webserver_replicas ]]; then\n      break\n    else\n      sleep 10\n      (( timeout=timeout-10 ))\n    fi\n  done\n\n  if [[ $timeout -gt 0 ]]; then\n    echo \"All $linux_webserver_pod_label pods became Ready\"\n  else\n    echo \"ERROR: Not all $linux_webserver_pod_label pods became Ready\"\n    echo \"kubectl get pods -l app=$linux_webserver_pod_label\"\n    ${kubectl} get pods -l app=$linux_webserver_pod_label\n    cleanup_deployments\n    exit 1\n  fi\n}\n\n# Returns the name of an arbitrary Linux webserver pod.\nfunction get_linux_webserver_pod_name {\n  $kubectl get pods -l app=$linux_webserver_pod_label \\\n    -o jsonpath='{.items[0].metadata.name}'\n}\n\n# Returns the IP address of an arbitrary Linux webserver pod.\nfunction get_linux_webserver_pod_ip {\n  $kubectl get pods -l app=$linux_webserver_pod_label \\\n    -o jsonpath='{.items[0].status.podIP}'\n}\n\nfunction undeploy_linux_webserver_pod {\n  ${kubectl} delete deployment $linux_webserver_deployment\n}\n\nlinux_command_deployment=linux-ubuntu\nlinux_command_pod_label=ubuntu\nlinux_command_replicas=1\n\nfunction deploy_linux_command_pod {\n  echo \"Writing example deployment to $linux_command_deployment.yaml\"\n  cat <<EOF > $linux_command_deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: $linux_command_deployment\n  labels:\n    app: $linux_command_pod_label\nspec:\n  replicas: $linux_command_replicas\n  selector:\n    matchLabels:\n      app: $linux_command_pod_label\n  template:\n    metadata:\n      labels:\n        app: $linux_command_pod_label\n    spec:\n      containers:\n      - name: ubuntu\n        image: ubuntu\n        command: [\"sleep\", \"123456\"]\n      nodeSelector:\n        kubernetes.io/os: linux\nEOF\n\n  if ! ${kubectl} create -f $linux_command_deployment.yaml; then\n    echo \"kubectl create -f $linux_command_deployment.yaml failed\"\n    exit 1\n  fi\n\n  timeout=$linux_deployment_timeout\n  while [[ $timeout -gt 0 ]]; do\n    echo \"Waiting for $linux_command_replicas Linux $linux_command_pod_label pods to become Ready\"\n    statuses=$(${kubectl} get pods -l app=$linux_command_pod_label \\\n      -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}' \\\n      | grep \"True\" | wc -w)\n    if [[ $statuses -eq $linux_command_replicas ]]; then\n      break\n    else\n      sleep 10\n      (( timeout=timeout-10 ))\n    fi\n  done\n\n  if [[ $timeout -gt 0 ]]; then\n    echo \"All $linux_command_pod_label pods became Ready\"\n  else\n    echo \"ERROR: Not all $linux_command_pod_label pods became Ready\"\n    echo \"kubectl get pods -l app=$linux_command_pod_label\"\n    ${kubectl} get pods -l app=$linux_command_pod_label\n    cleanup_deployments\n    exit 1\n  fi\n}\n\n# Returns the name of an arbitrary Linux command pod.\nfunction get_linux_command_pod_name {\n  $kubectl get pods -l app=$linux_command_pod_label \\\n    -o jsonpath='{.items[0].metadata.name}'\n}\n\n# Returns the IP address of an arbitrary Linux command pod.\nfunction get_linux_command_pod_ip {\n  $kubectl get pods -l app=$linux_command_pod_label \\\n    -o jsonpath='{.items[0].status.podIP}'\n}\n\n# Installs test executables (ping, curl) in the Linux command pod.\n# NOTE: this assumes that there is only one Linux \"command pod\".\n# TODO(pjh): fix this.\nfunction prepare_linux_command_pod {\n  local linux_command_pod\n  linux_command_pod=\"$(get_linux_command_pod_name)\"\n\n  echo \"Installing test utilities in Linux command pod, may take a minute\"\n  $kubectl exec \"$linux_command_pod\" -- apt-get update > /dev/null\n  $kubectl exec \"$linux_command_pod\" -- \\\n    apt-get install -y iputils-ping curl > /dev/null\n}\n\nfunction undeploy_linux_command_pod {\n  ${kubectl} delete deployment $linux_command_deployment\n}\n\nwindows_webserver_deployment=windows-agnhost\nwindows_webserver_pod_label=agnhost\n# The default port for 'agnhost serve-hostname'. The documentation says that\n# this can be changed but the --port arg does not seem to work.\nwindows_webserver_port=9376\nwindows_webserver_replicas=1\n\nfunction deploy_windows_webserver_pod {\n  echo \"Writing example deployment to $windows_webserver_deployment.yaml\"\n  cat <<EOF > $windows_webserver_deployment.yaml\n# A multi-arch Windows container that runs an HTTP server on port\n# $windows_webserver_port that serves the container's hostname.\n#   curl -s http://<pod_ip>:$windows_webserver_port\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: $windows_webserver_deployment\n  labels:\n    app: $windows_webserver_pod_label\nspec:\n  replicas: $windows_webserver_replicas\n  selector:\n    matchLabels:\n      app: $windows_webserver_pod_label\n  template:\n    metadata:\n      labels:\n        app: $windows_webserver_pod_label\n    spec:\n      containers:\n      - name: agnhost\n        image: e2eteam/agnhost:2.26\n        args:\n        - serve-hostname\n      nodeSelector:\n        kubernetes.io/os: windows\n      tolerations:\n      - effect: NoSchedule\n        key: node.kubernetes.io/os\n        operator: Equal\n        value: windows\nEOF\n\n  if ! ${kubectl} create -f $windows_webserver_deployment.yaml; then\n    echo \"kubectl create -f $windows_webserver_deployment.yaml failed\"\n    exit 1\n  fi\n\n  timeout=$windows_deployment_timeout\n  while [[ $timeout -gt 0 ]]; do\n    echo \"Waiting for $windows_webserver_replicas Windows $windows_webserver_pod_label pods to become Ready\"\n    statuses=$(${kubectl} get pods -l app=$windows_webserver_pod_label \\\n      -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}' \\\n      | grep \"True\" | wc -w)\n    if [[ $statuses -eq $windows_webserver_replicas ]]; then\n      break\n    else\n      sleep 10\n      (( timeout=timeout-10 ))\n    fi\n  done\n\n  if [[ $timeout -gt 0 ]]; then\n    echo \"All $windows_webserver_pod_label pods became Ready\"\n  else\n    echo \"ERROR: Not all $windows_webserver_pod_label pods became Ready\"\n    echo \"kubectl get pods -l app=$windows_webserver_pod_label\"\n    ${kubectl} get pods -l app=$windows_webserver_pod_label\n    cleanup_deployments\n    exit 1\n  fi\n}\n\nfunction get_windows_webserver_pod_name {\n  $kubectl get pods -l app=$windows_webserver_pod_label \\\n    -o jsonpath='{.items[0].metadata.name}'\n}\n\nfunction get_windows_webserver_pod_ip {\n  $kubectl get pods -l app=$windows_webserver_pod_label \\\n    -o jsonpath='{.items[0].status.podIP}'\n}\n\nfunction undeploy_windows_webserver_pod {\n  ${kubectl} delete deployment $windows_webserver_deployment\n}\n\nwindows_command_deployment=windows-powershell\nwindows_command_pod_label=powershell\nwindows_command_replicas=1\n\n# Deploys a multi-arch Windows pod capable of running PowerShell.\nfunction deploy_windows_command_pod {\n  echo \"Writing example deployment to $windows_command_deployment.yaml\"\n  cat <<EOF > $windows_command_deployment.yaml\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: $windows_command_deployment\n  labels:\n    app: $windows_command_pod_label\nspec:\n  replicas: $windows_command_replicas\n  selector:\n    matchLabels:\n      app: $windows_command_pod_label\n  template:\n    metadata:\n      labels:\n        app: $windows_command_pod_label\n    spec:\n      containers:\n      - name: pause-win\n        image: k8s.gcr.io/pause:3.5\n      nodeSelector:\n        kubernetes.io/os: windows\n      tolerations:\n      - effect: NoSchedule\n        key: node.kubernetes.io/os\n        operator: Equal\n        value: windows\nEOF\n\n  if ! ${kubectl} create -f $windows_command_deployment.yaml; then\n    echo \"kubectl create -f $windows_command_deployment.yaml failed\"\n    exit 1\n  fi\n\n  timeout=$windows_deployment_timeout\n  while [[ $timeout -gt 0 ]]; do\n    echo \"Waiting for $windows_command_replicas Windows $windows_command_pod_label pods to become Ready\"\n    statuses=$(${kubectl} get pods -l app=$windows_command_pod_label \\\n      -o jsonpath='{.items[*].status.conditions[?(@.type==\"Ready\")].status}' \\\n      | grep \"True\" | wc -w)\n    if [[ $statuses -eq $windows_command_replicas ]]; then\n      break\n    else\n      sleep 10\n      (( timeout=timeout-10 ))\n    fi\n  done\n\n  if [[ $timeout -gt 0 ]]; then\n    echo \"All $windows_command_pod_label pods became Ready\"\n  else\n    echo \"ERROR: Not all $windows_command_pod_label pods became Ready\"\n    echo \"kubectl get pods -l app=$windows_command_pod_label\"\n    ${kubectl} get pods -l app=$windows_command_pod_label\n    cleanup_deployments\n    exit 1\n  fi\n}\n\nfunction get_windows_command_pod_name {\n  $kubectl get pods -l app=$windows_command_pod_label \\\n    -o jsonpath='{.items[0].metadata.name}'\n}\n\nfunction get_windows_command_pod_ip {\n  $kubectl get pods -l app=$windows_command_pod_label \\\n    -o jsonpath='{.items[0].status.podIP}'\n}\n\nfunction undeploy_windows_command_pod {\n  ${kubectl} delete deployment $windows_command_deployment\n}\n\nfunction test_linux_node_to_linux_pod {\n  echo \"TODO: ${FUNCNAME[0]}\"\n}\n\nfunction test_linux_node_to_windows_pod {\n  echo \"TODO: ${FUNCNAME[0]}\"\n}\n\nfunction test_linux_pod_to_linux_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local linux_command_pod\n  linux_command_pod=\"$(get_linux_command_pod_name)\"\n  local linux_webserver_pod_ip\n  linux_webserver_pod_ip=\"$(get_linux_webserver_pod_ip)\"\n\n  if ! $kubectl exec \"$linux_command_pod\" -- curl -s -m 20 \\\n      \"http://$linux_webserver_pod_ip\" &> $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\n# TODO(pjh): this test flakily fails on brand-new clusters, not sure why.\n# % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current\n#                                Dload  Upload   Total   Spent    Left  Speed\n# 0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0\n# curl: (6) Could not resolve host:\n# command terminated with exit code 6\nfunction test_linux_pod_to_windows_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local linux_command_pod\n  linux_command_pod=\"$(get_linux_command_pod_name)\"\n  local windows_webserver_pod_ip\n  windows_webserver_pod_ip=\"$(get_windows_webserver_pod_ip)\"\n\n  if ! $kubectl exec \"$linux_command_pod\" -- curl -s -m 20 \\\n      \"http://$windows_webserver_pod_ip:$windows_webserver_port\" &> $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    echo \"This test seems to be flaky. TODO(pjh): investigate.\"\n    exit 1\n  fi\n}\n\nfunction test_linux_pod_to_internet {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local linux_command_pod\n  linux_command_pod=\"$(get_linux_command_pod_name)\"\n  # A stable (hopefully) HTTP server provided by Cloudflare.\n  local internet_ip=\"1.1.1.1\"\n\n  if ! $kubectl exec \"$linux_command_pod\" -- curl -s -m 20 \\\n      \"http://$internet_ip\" > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_linux_pod_to_k8s_service {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local linux_command_pod\n  linux_command_pod=\"$(get_linux_command_pod_name)\"\n  local service=\"metrics-server\"\n  local service_ip\n  service_ip=$($kubectl get service --namespace kube-system $service \\\n    -o jsonpath='{.spec.clusterIP}')\n  local service_port\n  service_port=$($kubectl get service --namespace kube-system $service \\\n    -o jsonpath='{.spec.ports[?(@.protocol==\"TCP\")].port}')\n  echo \"curl-ing $service address from Linux pod: $service_ip:$service_port\"\n\n  # curl-ing the metrics-server service downloads 14 bytes of unprintable binary\n  # data and sets a return code of success (0).\n  if ! $kubectl exec \"$linux_command_pod\" -- \\\n      curl -s -m 20 --insecure \"https://$service_ip:$service_port\" &> $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_windows_node_to_linux_pod {\n  echo \"TODO: ${FUNCNAME[0]}\"\n}\n\nfunction test_windows_node_to_windows_pod {\n  echo \"TODO: ${FUNCNAME[0]}\"\n}\n\n# TODO(pjh): this test failed for me once with\n#   error: unable to upgrade connection: container not found (\"nettest\")\n# Maybe the container crashed for some reason? Investigate if it happens more.\n#\n# TODO(pjh): another one-time failure:\n#   error: unable to upgrade connection: Authorization error\n#   (user=kube-apiserver, verb=create, resource=nodes, subresource=proxy)\nfunction test_windows_pod_to_linux_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n  local linux_webserver_pod_ip\n  linux_webserver_pod_ip=\"$(get_linux_webserver_pod_ip)\"\n\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"curl -UseBasicParsing http://$linux_webserver_pod_ip\" > \\\n      $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_windows_pod_to_windows_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n  local windows_webserver_pod_ip\n  windows_webserver_pod_ip=\"$(get_windows_webserver_pod_ip)\"\n\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"curl -UseBasicParsing http://$windows_webserver_pod_ip:$windows_webserver_port\" \\\n      > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_windows_pod_to_internet {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n  # A stable (hopefully) HTTP server provided by Cloudflare. If this ever stops\n  # working, we can request from 8.8.8.8 (Google DNS) using https instead.\n  local internet_ip=\"1.1.1.1\"\n\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"curl -UseBasicParsing http://$internet_ip\" > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_windows_pod_to_k8s_service {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n  local service=\"metrics-server\"\n  local service_ip\n  service_ip=$($kubectl get service --namespace kube-system $service \\\n    -o jsonpath='{.spec.clusterIP}')\n  local service_port\n  service_port=$($kubectl get service --namespace kube-system $service \\\n    -o jsonpath='{.spec.ports[?(@.protocol==\"TCP\")].port}')\n  local service_address=\"$service_ip:$service_port\"\n\n  echo \"curl-ing $service address from Windows pod: $service_address\"\n  # curl-ing the metrics-server service results in a ServerProtocolViolation\n  # (\"The server committed a protocol violation. Section=ResponseStatusLine\")\n  # exception. Since we don't care about what the metrics-server actually gives\n  # back to us, just that we can reach it, we check that we get the expected\n  # exception code and not some other exception code.\n  # TODO: it might be less fragile to check that we don't get the \"Unable to\n  # connect to the remote server\" exception code (2) instead of specifically\n  # expecting the protocol-violation exception code (11).\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"\\$result = try { \\`\n         curl -UseBasicParsing http://$service_address -ErrorAction Stop \\`\n       } catch [System.Net.WebException] { \\`\n         \\$_ \\`\n       }; \\`\n       if ([int]\\$result.Exception.Status -eq 11) { \\`\n         Write-Host \\\"curl $service_address got expected exception\\\"\n         exit 0 \\`\n       } else { \\`\n         Write-Host \\\"curl $service_address got unexpected result/exception: \\$result\\\"\n         exit 1 \\`\n       }\" > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_kube_dns_in_windows_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n  local service=\"kube-dns\"\n  local service_ip\n  service_ip=$($kubectl get service --namespace kube-system $service \\\n    -o jsonpath='{.spec.clusterIP}')\n\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"Resolve-DnsName www.bing.com -server $service_ip\" > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction test_dns_just_works_in_windows_pod {\n  echo \"TEST: ${FUNCNAME[0]}\"\n  local windows_command_pod\n  windows_command_pod=\"$(get_windows_command_pod_name)\"\n\n  if ! $kubectl exec \"$windows_command_pod\" -- powershell.exe \\\n      \"curl -UseBasicParsing http://www.bing.com\" > $output_file; then\n    cleanup_deployments\n    echo \"Failing output: $(cat $output_file)\"\n    echo \"FAILED: ${FUNCNAME[0]}\"\n    exit 1\n  fi\n}\n\nfunction cleanup_deployments {\n  undeploy_linux_webserver_pod\n  undeploy_linux_command_pod\n  undeploy_windows_webserver_pod\n  undeploy_windows_command_pod\n}\n\ncheck_windows_nodes_are_ready\nuntaint_windows_nodes\ncheck_no_system_pods_on_windows_nodes\n\ndeploy_linux_webserver_pod\ndeploy_linux_command_pod\ndeploy_windows_webserver_pod\ndeploy_windows_command_pod\nprepare_linux_command_pod\necho \"\"\n\ntest_linux_node_to_linux_pod\ntest_linux_node_to_windows_pod\ntest_linux_pod_to_linux_pod\ntest_linux_pod_to_windows_pod\ntest_linux_pod_to_k8s_service\n\n# Note: test_windows_node_to_k8s_service is not supported at this time.\n# https://docs.microsoft.com/en-us/virtualization/windowscontainers/kubernetes/common-problems#my-windows-node-cannot-access-my-services-using-the-service-ip\ntest_windows_node_to_linux_pod\ntest_windows_node_to_windows_pod\ntest_windows_pod_to_linux_pod\ntest_windows_pod_to_windows_pod\ntest_windows_pod_to_internet\ntest_windows_pod_to_k8s_service\ntest_kube_dns_in_windows_pod\ntest_dns_just_works_in_windows_pod\necho \"\"\n\ncleanup_deployments\necho \"All tests passed!\"\nexit 0\n", "num_lines": 681}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nkubectl create -f conformance-e2e.yaml\nwhile true; do\n  STATUS=$(kubectl -n conformance get pods e2e-conformance-test -o jsonpath=\"{.status.phase}\")\n  timestamp=$(date +\"[%H:%M:%S]\")\n  echo \"$timestamp Pod status is: ${STATUS}\"\n  if [[ \"$STATUS\" == \"Succeeded\" ]]; then\n    echo \"$timestamp Done.\"\n    break\n  elif [[ \"$STATUS\" == \"Failed\" ]]; then\n    echo \"$timestamp Failed.\"\n    kubectl -n conformance describe pods e2e-conformance-test || true\n    kubectl -n conformance logs e2e-conformance-test || true\n    exit 1\n  else\n    sleep 5\n  fi\ndone\necho \"Please use 'kubectl logs -n conformance e2e-conformance-test' to view the results\"\n", "num_lines": 38}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Shutdown the tests gracefully then save the results\nshutdown () {\n    E2E_SUITE_PID=$(pgrep e2e.test)\n    echo \"sending TERM to ${E2E_SUITE_PID}\"\n    kill -s TERM \"${E2E_SUITE_PID}\"\n\n    # Kind of a hack to wait for this pid to finish.\n    # Since it's not a child of this shell we cannot use wait.\n    tail --pid \"${E2E_SUITE_PID}\" -f /dev/null\n    saveResults\n}\n\nsaveResults() {\n    cd \"${RESULTS_DIR}\" || exit\n    tar -czf e2e.tar.gz ./*\n    # mark the done file as a termination notice.\n    echo -n \"${RESULTS_DIR}/e2e.tar.gz\" > \"${RESULTS_DIR}/done\"\n}\n\n# Optional Golang runner alternative to the bash script.\n# Entry provided via env var to simplify invocation.\nif [[ -n ${E2E_USE_GO_RUNNER:-} ]]; then\n    set -x\n    /gorunner && ret=0 || ret=$?\n    exit ${ret}\nfi\n\n# We get the TERM from kubernetes and handle it gracefully\ntrap shutdown TERM\n\nginkgo_args=()\nif [[ -n ${E2E_DRYRUN:-} ]]; then\n    ginkgo_args+=(\"--dryRun=true\")\nfi\n\ncase ${E2E_PARALLEL} in\n    'y'|'Y'|'true')\n        # The flag '--p' will automatically detect the optimal number of ginkgo nodes.\n        ginkgo_args+=(\"--p\")\n        # Skip serial tests if parallel mode is enabled.\n        E2E_SKIP=\"\\\\[Serial\\\\]|${E2E_SKIP}\" ;;\nesac\n\nginkgo_args+=(\n    \"--focus=${E2E_FOCUS}\"\n    \"--skip=${E2E_SKIP}\"\n    \"--noColor=true\"\n)\n\nset -x\n/usr/local/bin/ginkgo \"${ginkgo_args[@]}\" /usr/local/bin/e2e.test -- --disable-log-dump --repo-root=/kubernetes --provider=\"${E2E_PROVIDER}\" --report-dir=\"${RESULTS_DIR}\" --kubeconfig=\"${KUBECONFIG}\" -v=\"${E2E_VERBOSITY}\" > >(tee \"${RESULTS_DIR}\"/e2e.log) && ret=0 || ret=$?\nset +x\nsaveResults\nexit ${ret}\n", "num_lines": 74}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# DEPRECATED:\n# The functionality has been moved to migrate binary and this script\n# if left for backward compatibility with previous manifests. It will be\n# removed in the future.\n\nset -o errexit\nset -o nounset\n\n/usr/local/bin/migrate\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/test/kubemark/cloud-provider-config.sh\"\nsource \"${KUBE_ROOT}/cluster/${CLOUD_PROVIDER}/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kubemark/${CLOUD_PROVIDER}/config-default.sh\"\n", "num_lines": 21}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A configuration for Kubemark cluster. It doesn't need to be kept in\n# sync with gce/config-default.sh (except the filename, because I'm reusing\n# gce/util.sh script which assumes config filename), but if some things that\n# are enabled by default should not run in hollow clusters, they should be disabled here.\n\n# shellcheck disable=SC2034 # Variables sourced in other scripts.\n\nsource \"${KUBE_ROOT}/cluster/gce/config-common.sh\"\n\nCLEANUP_KUBEMARK_IMAGE=${CLEANUP_KUBEMARK_IMAGE:-true}\nTEST_CLUSTER_LOG_LEVEL=\"${TEST_CLUSTER_LOG_LEVEL:-\"--v=4\"}\"\n\n# If you want to set up multiple kubemark clusters with different \"names\",\n# you should change this env per each start-kubemark.sh invocation.\nKUBE_GCE_INSTANCE_PREFIX=\"${KUBE_GCE_INSTANCE_PREFIX:-\"default\"}\"\n\n# NUM_NODES is used by start-kubemark.sh to determine a correct number of replicas.\nNUM_NODES=${KUBEMARK_NUM_NODES:-10}\nNUM_WINDOWS_NODES=${KUBEMARK_NUM_WINDOWS_NODES:-0}\n\nHOLLOW_KUBELET_TEST_LOG_LEVEL=\"${HOLLOW_KUBELET_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\"\nHOLLOW_PROXY_TEST_LOG_LEVEL=\"${HOLLOW_PROXY_TEST_LOG_LEVEL:-$TEST_CLUSTER_LOG_LEVEL}\"\n\n# Hollow-node components' test arguments.\nHOLLOW_KUBELET_TEST_ARGS=\"${HOLLOW_KUBELET_TEST_ARGS:-} ${HOLLOW_KUBELET_TEST_LOG_LEVEL}\"\nHOLLOW_PROXY_TEST_ARGS=\"${HOLLOW_PROXY_TEST_ARGS:-} ${HOLLOW_PROXY_TEST_LOG_LEVEL}\"\n\n# Optional: Enable cluster autoscaler.\nENABLE_KUBEMARK_CLUSTER_AUTOSCALER=\"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER:-false}\"\n# When using Cluster Autoscaler, always start with one hollow-node replica.\n# NUM_NODES should not be specified by the user. Instead we use\n# NUM_NODES=KUBEMARK_AUTOSCALER_MAX_NODES. This gives other cluster components\n# (e.g. kubemark master, Heapster) enough resources to handle maximum cluster size.\nif [[ \"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n  NUM_REPLICAS=1\n  if [[ -n \"$NUM_NODES\" ]]; then\n    echo \"WARNING: Using Cluster Autoscaler, ignoring NUM_NODES parameter. Set KUBEMARK_AUTOSCALER_MAX_NODES to specify maximum size of the cluster.\"\n  fi\nfi\n\n#Optional: Enable kube dns.\nENABLE_KUBEMARK_KUBE_DNS=\"${ENABLE_KUBEMARK_KUBE_DNS:-true}\"\nKUBE_DNS_DOMAIN=\"${KUBE_DNS_DOMAIN:-cluster.local}\"\n\nCLEANUP_KUBEMARK_IMAGE=false\n", "num_lines": 62}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Cloud information\nRANDGEN=$(dd if=/dev/urandom bs=64 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=16 count=1 2>/dev/null | sed 's/[A-Z]//g')\n# shellcheck disable=2034 # Variable sourced in other scripts.\nKUBE_NAMESPACE=\"kubemark_${RANDGEN}\"\nKUBEMARK_IMAGE_TAG=\"${KUBEMARK_IMAGE_TAG:-2}\"\nKUBEMARK_IMAGE_LOCATION=\"${KUBEMARK_IMAGE_LOCATION:-${KUBE_ROOT}/cluster/images/kubemark}\"\nKUBEMARK_INIT_TAG=\"${KUBEMARK_INIT_TAG:-${PROJECT}:${KUBEMARK_IMAGE_TAG}}\"\nCLUSTER_LOCATION=\"${CLUSTER_LOCATION:-wdc06}\"\nREGISTRY_LOGIN_URL=\"${REGISTRY_LOGIN_URL:-https://api.ng.bluemix.net}\"\n\n# User defined\n# number of real workers in spawnTester cluster\nNUM_NODES=\"${NUM_NODES:-2}\"\n# spec of real workers in spawnTester cluster\nNODE_SIZE=${NODE_SIZE:-u2c.2x4}\nDESIRED_NODES=\"${DESIRED_NODES:-10}\"\n# number of hollow nodes\n# TODO: once IKS supports `kubetest`, i.e. the base cluster provisioning implemented in `kubetest`\n# we can use NUM_NODES=${KUBEMARK_NUM_NODES:-10} to avoid usage of KUBEMARK_NUM_NODES\n# more context, see https://github.com/kubernetes/kubernetes/pull/76909#discussion_r277735942\nKUBEMARK_NUM_NODES=\"${KUBEMARK_NUM_NODES:-10}\"\nENABLE_KUBEMARK_CLUSTER_AUTOSCALER=\"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER:-true}\"\nENABLE_KUBEMARK_KUBE_DNS=\"${ENABLE_KUBEMARK_KUBE_DNS:-false}\"\nKUBELET_TEST_LOG_LEVEL=\"${KUBELET_TEST_LOG_LEVEL:-\"--v=2\"}\"\nKUBEPROXY_TEST_LOG_LEVEL=\"${KUBEPROXY_TEST_LOG_LEVEL:-\"--v=4\"}\"\nUSE_REAL_PROXIER=${USE_REAL_PROXIER:-false}\nNODE_INSTANCE_PREFIX=${NODE_INSTANCE_PREFIX:-node}\nUSE_EXISTING=${USE_EXISTING:-}\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Configuration for landing a Kubemark cluster on a pre-existing Kubernetes\n# cluster.\n\n# Pre-existing provider expects a MASTER_IP.\n# If you need to specify a port that's not the default (443), add it to MASTER_IP.\n#\n# Example: Connect to the Master on the secure port 6443\n#          MASTER_IP=192.168.122.5:6443\n#\nMASTER_IP=\"${MASTER_IP:-}\"\n\n# The container registry and project given to the kubemark container:\n#   $CONTAINER_REGISTRY/$PROJECT/kubemark\n#\nCONTAINER_REGISTRY=\"${CONTAINER_REGISTRY:-}\"\nPROJECT=\"${PROJECT:-}\"\n\nNUM_NODES=\"${NUM_NODES:-1}\"\n\nKUBELET_TEST_LOG_LEVEL=\"${KUBELET_TEST_LOG_LEVEL:-}\"\nKUBEPROXY_TEST_LOG_LEVEL=\"${KUBEPROXY_TEST_LOG_LEVEL:-}\"\nMASTER_NAME=\"${MASTER_NAME:-}\"\n", "num_lines": 38}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Call this to dump all master and node logs into the folder specified in $1\n# (defaults to _artifacts). Only works if the provider supports SSH.\n\n# TODO(shyamjvs): This script should be moved to test/e2e which is where it ideally belongs.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nreadonly report_dir=\"${1:-_artifacts}\"\nreadonly gcs_artifacts_dir=\"${2:-}\"\nreadonly logexporter_namespace=\"${3:-logexporter}\"\n\n# In order to more trivially extend log-dump for custom deployments,\n# check for a function named log_dump_custom_get_instances. If it's\n# defined, we assume the function can me called with one argument, the\n# role, which is either \"master\" or \"node\".\necho 'Checking for custom logdump instances, if any'\nif [[ $(type -t log_dump_custom_get_instances) == \"function\" ]]; then\n  readonly use_custom_instance_list=yes\nelse\n  readonly use_custom_instance_list=\nfi\n\nreadonly master_ssh_supported_providers=\"gce aws\"\nreadonly node_ssh_supported_providers=\"gce gke aws\"\nreadonly gcloud_supported_providers=\"gce gke\"\n\nreadonly master_logfiles=\"kube-apiserver.log kube-apiserver-audit.log kube-scheduler.log kube-controller-manager.log etcd.log etcd-events.log glbc.log cluster-autoscaler.log kube-addon-manager.log konnectivity-server.log fluentd.log kubelet.cov\"\nreadonly node_logfiles=\"kube-proxy.log fluentd.log node-problem-detector.log kubelet.cov\"\nreadonly node_systemd_services=\"node-problem-detector\"\nreadonly hollow_node_logfiles=\"kubelet-hollow-node-*.log kubeproxy-hollow-node-*.log npd-hollow-node-*.log\"\nreadonly aws_logfiles=\"cloud-init-output.log\"\nreadonly gce_logfiles=\"startupscript.log\"\nreadonly kern_logfile=\"kern.log\"\nreadonly initd_logfiles=\"docker/log\"\nreadonly supervisord_logfiles=\"kubelet.log supervisor/supervisord.log supervisor/kubelet-stdout.log supervisor/kubelet-stderr.log supervisor/docker-stdout.log supervisor/docker-stderr.log\"\nreadonly systemd_services=\"kubelet kubelet-monitor kube-container-runtime-monitor ${LOG_DUMP_SYSTEMD_SERVICES:-docker}\"\nreadonly extra_log_files=\"${LOG_DUMP_EXTRA_FILES:-}\"\nreadonly extra_systemd_services=\"${LOG_DUMP_SAVE_SERVICES:-}\"\nreadonly dump_systemd_journal=\"${LOG_DUMP_SYSTEMD_JOURNAL:-false}\"\n# Log files found in WINDOWS_LOGS_DIR on Windows nodes:\nreadonly windows_node_logfiles=\"kubelet.log kube-proxy.log docker.log docker_images.log csi-proxy.log\"\n# Log files found in other directories on Windows nodes:\nreadonly windows_node_otherfiles=\"C:\\\\Windows\\\\MEMORY.dmp\"\n\n# Limit the number of concurrent node connections so that we don't run out of\n# file descriptors for large clusters.\nreadonly max_dump_processes=25\n\n# Indicator variable whether we experienced a significant failure during\n# logexporter creation or execution.\nlogexporter_failed=0\n\n# Percentage of nodes that must be logexported successfully (otherwise the\n# process will exit with a non-zero exit code).\nreadonly log_dump_expected_success_percentage=\"${LOG_DUMP_EXPECTED_SUCCESS_PERCENTAGE:-0}\"\n\nfunction print-deprecation-note() {\n  local -r dashline=$(printf -- '-%.0s' {1..100})\n  echo \"${dashline}\"\n  echo \"k/k version of the log-dump.sh script is deprecated!\"\n  echo \"Please migrate your test job to use test-infra's repo version of log-dump.sh!\"\n  echo \"Migration steps can be found in the readme file.\"\n  echo \"${dashline}\"\n}\n\n# TODO: Get rid of all the sourcing of bash dependencies eventually.\nfunction setup() {\n  KUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n  if [[ -z \"${use_custom_instance_list}\" ]]; then\n    : \"${KUBE_CONFIG_FILE:=config-test.sh}\"\n    echo 'Sourcing kube-util.sh'\n    source \"${KUBE_ROOT}/cluster/kube-util.sh\"\n    echo 'Detecting project'\n    detect-project 2>&1\n  elif [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then\n    echo \"Using 'use_custom_instance_list' with gke, skipping check for LOG_DUMP_SSH_KEY and LOG_DUMP_SSH_USER\"\n    # Source the below script for the ssh-to-node utility function.\n    # Hack to save and restore the value of the ZONE env as the script overwrites it.\n    local gke_zone=\"${ZONE:-}\"\n    source \"${KUBE_ROOT}/cluster/gce/util.sh\"\n    ZONE=\"${gke_zone}\"\n  elif [[ -z \"${LOG_DUMP_SSH_KEY:-}\" ]]; then\n    echo 'LOG_DUMP_SSH_KEY not set, but required when using log_dump_custom_get_instances'\n    exit 1\n  elif [[ -z \"${LOG_DUMP_SSH_USER:-}\" ]]; then\n    echo 'LOG_DUMP_SSH_USER not set, but required when using log_dump_custom_get_instances'\n    exit 1\n  fi\n  source \"${KUBE_ROOT}/hack/lib/util.sh\"\n}\n\nfunction log-dump-ssh() {\n  if [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    ssh-to-node \"$@\"\n    return\n  fi\n\n  local host=\"$1\"\n  local cmd=\"$2\"\n\n  ssh -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${LOG_DUMP_SSH_KEY}\" \"${LOG_DUMP_SSH_USER}@${host}\" \"${cmd}\"\n}\n\n# Copy all files /var/log/{$3}.log on node $1 into local dir $2.\n# $3 should be a string array of file names.\n# This function shouldn't ever trigger errexit, but doesn't block stderr.\nfunction copy-logs-from-node() {\n    local -r node=\"${1}\"\n    local -r dir=\"${2}\"\n    shift\n    shift\n    local files=(\"$@\")\n    # Append \"*\"\n    # The * at the end is needed to also copy rotated logs (which happens\n    # in large clusters and long runs).\n    files=( \"${files[@]/%/*}\" )\n    # Prepend \"/var/log/\"\n    files=( \"${files[@]/#/\\/var\\/log\\/}\" )\n    # Comma delimit (even the singleton, or scp does the wrong thing), surround by braces.\n    local -r scp_files=\"{$(printf \"%s,\" \"${files[@]}\")}\"\n\n    if [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n      # get-serial-port-output lets you ask for ports 1-4, but currently (11/21/2016) only port 1 contains useful information\n      gcloud compute instances get-serial-port-output --project \"${PROJECT}\" --zone \"${ZONE}\" --port 1 \"${node}\" > \"${dir}/serial-1.log\" || true\n      gcloud compute scp --recurse --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}:${scp_files}\" \"${dir}\" > /dev/null || true\n    elif  [[ \"${KUBERNETES_PROVIDER}\" == \"aws\" ]]; then\n      local ip\n      ip=$(get_ssh_hostname \"${node}\")\n      scp -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${AWS_SSH_KEY}\" \"${SSH_USER}@${ip}:${scp_files}\" \"${dir}\" > /dev/null || true\n    elif  [[ -n \"${use_custom_instance_list}\" ]]; then\n      scp -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${LOG_DUMP_SSH_KEY}\" \"${LOG_DUMP_SSH_USER}@${node}:${scp_files}\" \"${dir}\" > /dev/null || true\n    else\n      echo \"Unknown cloud-provider '${KUBERNETES_PROVIDER}' and use_custom_instance_list is unset too - skipping logdump for '${node}'\"\n    fi\n}\n\n# Save logs for node $1 into directory $2. Pass in any non-common files in $3.\n# Pass in any non-common systemd services in $4.\n# $3 and $4 should be a space-separated list of files.\n# Set $5 to true to indicate it is on master. Default to false.\n# This function shouldn't ever trigger errexit\nfunction save-logs() {\n    local -r node_name=\"${1}\"\n    local -r dir=\"${2}\"\n    local files=()\n    IFS=' ' read -r -a files <<< \"$3\"\n    local opt_systemd_services=\"${4:-\"\"}\"\n    local on_master=\"${5:-\"false\"}\"\n\n    local extra=()\n    IFS=' ' read -r -a extra <<< \"$extra_log_files\"\n    files+=(\"${extra[@]}\")\n    if [[ -n \"${use_custom_instance_list}\" ]]; then\n      if [[ -n \"${LOG_DUMP_SAVE_LOGS:-}\" ]]; then\n\tlocal dump=()\n        IFS=' ' read -r -a dump <<< \"${LOG_DUMP_SAVE_LOGS:-}\"\n        files+=(\"${dump[@]}\")\n      fi\n    else\n      local providerlogs=()\n      case \"${KUBERNETES_PROVIDER}\" in\n        gce|gke)\n          IFS=' ' read -r -a providerlogs <<< \"${gce_logfiles}\"\n          ;;\n        aws)\n          IFS=' ' read -r -a providerlogs <<< \"${aws_logfiles}\"\n          ;;\n      esac\n      files+=(\"${providerlogs[@]}\")\n    fi\n    local services\n    read -r -a services <<< \"${systemd_services} ${opt_systemd_services} ${extra_systemd_services}\"\n\n    if log-dump-ssh \"${node_name}\" \"command -v journalctl\" &> /dev/null; then\n        if [[ \"${on_master}\" == \"true\" ]]; then\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-master-installation.service\" > \"${dir}/kube-master-installation.log\" || true\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-master-configuration.service\" > \"${dir}/kube-master-configuration.log\" || true\n        else\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-node-installation.service\" > \"${dir}/kube-node-installation.log\" || true\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-node-configuration.service\" > \"${dir}/kube-node-configuration.log\" || true\n        fi\n        log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -k\" > \"${dir}/kern.log\" || true\n\n        for svc in \"${services[@]}\"; do\n            log-dump-ssh \"${node_name}\" \"sudo journalctl --output=cat -u ${svc}.service\" > \"${dir}/${svc}.log\" || true\n        done\n\n        if [[ \"$dump_systemd_journal\" == \"true\" ]]; then\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise\" > \"${dir}/systemd.log\" || true\n        fi\n    else\n        local tmpfiles=()\n        for f in \"${kern_logfile}\" \"${initd_logfiles}\" \"${supervisord_logfiles}\"; do\n\t    IFS=' ' read -r -a tmpfiles <<< \"$f\"\n\t    files+=(\"${tmpfiles[@]}\")\n        done\n    fi\n\n    # Try dumping coverage profiles, if it looks like coverage is enabled in the first place.\n    if log-dump-ssh \"${node_name}\" \"stat /var/log/kubelet.cov\" &> /dev/null; then\n      if log-dump-ssh \"${node_name}\" \"command -v docker\" &> /dev/null; then\n        if [[ \"${on_master}\" == \"true\" ]]; then\n          run-in-docker-container \"${node_name}\" \"kube-apiserver\" \"cat /tmp/k8s-kube-apiserver.cov\" > \"${dir}/kube-apiserver.cov\" || true\n          run-in-docker-container \"${node_name}\" \"kube-scheduler\" \"cat /tmp/k8s-kube-scheduler.cov\" > \"${dir}/kube-scheduler.cov\" || true\n          run-in-docker-container \"${node_name}\" \"kube-controller-manager\" \"cat /tmp/k8s-kube-controller-manager.cov\" > \"${dir}/kube-controller-manager.cov\" || true\n        else\n          run-in-docker-container \"${node_name}\" \"kube-proxy\" \"cat /tmp/k8s-kube-proxy.cov\" > \"${dir}/kube-proxy.cov\" || true\n        fi\n      else\n        echo 'Coverage profiles seem to exist, but cannot be retrieved from inside containers.'\n      fi\n    fi\n\n    echo 'Changing logfiles to be world-readable for download'\n    log-dump-ssh \"${node_name}\" \"sudo chmod -R a+r /var/log\" || true\n\n    echo \"Copying '${files[*]}' from ${node_name}\"\n    copy-logs-from-node \"${node_name}\" \"${dir}\" \"${files[@]}\"\n}\n\n# Saves a copy of the Windows Docker event log to ${WINDOWS_LOGS_DIR}\\docker.log\n# on node $1.\nfunction export-windows-docker-event-log() {\n    local -r node=\"${1}\"\n\n    local -r powershell_cmd=\"powershell.exe -Command \\\"\\$logs=\\$(Get-EventLog -LogName Application -Source Docker | Format-Table -Property TimeGenerated, EntryType, Message -Wrap); \\$logs | Out-File -FilePath '${WINDOWS_LOGS_DIR}\\\\docker.log'\\\"\"\n\n    # Retry up to 3 times to allow ssh keys to be properly propagated and\n    # stored.\n    for retry in {1..3}; do\n      if gcloud compute ssh --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}\" \\\n        --command \"$powershell_cmd\"; then\n        break\n      else\n        sleep 10\n      fi\n    done\n}\n\n# Saves prepulled Windows Docker images list to ${WINDOWS_LOGS_DIR}\\docker_images.log\n# on node $1.\nfunction export-windows-docker-images-list() {\n    local -r node=\"${1}\"\n\n    local -r powershell_cmd=\"powershell.exe -Command \\\"\\$logs=\\$(docker image list); \\$logs | Out-File -FilePath '${WINDOWS_LOGS_DIR}\\\\docker_images.log'\\\"\"\n\n    # Retry up to 3 times to allow ssh keys to be properly propagated and\n    # stored.\n    for retry in {1..3}; do\n      if gcloud compute ssh --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}\" \\\n        --command \"$powershell_cmd\"; then\n        break\n      else\n        sleep 10\n      fi\n    done\n}\n\n# Saves log files from diagnostics tool.(https://github.com/GoogleCloudPlatform/compute-image-tools/tree/master/cli_tools/diagnostics)\nfunction save-windows-logs-via-diagnostics-tool() {\n    local node=\"${1}\"\n    local dest_dir=\"${2}\"\n\n    gcloud compute instances add-metadata \"${node}\" --metadata enable-diagnostics=true --project=\"${PROJECT}\" --zone=\"${ZONE}\"\n    local logs_archive_in_gcs\n    logs_archive_in_gcs=$(gcloud alpha compute diagnose export-logs \"${node}\" \"--zone=${ZONE}\" \"--project=${PROJECT}\" | tail -n 1)\n    local temp_local_path=\"${node}.zip\"\n    for retry in {1..20}; do\n      if gsutil mv \"${logs_archive_in_gcs}\" \"${temp_local_path}\"  > /dev/null 2>&1; then\n        echo \"Downloaded diagnostics log from ${logs_archive_in_gcs}\"\n        break\n      else\n        sleep 10\n      fi\n    done\n\n    if [[ -f \"${temp_local_path}\" ]]; then\n      unzip \"${temp_local_path}\" -d \"${dest_dir}\" > /dev/null\n      rm -f \"${temp_local_path}\"\n    fi\n}\n\n# Saves log files from SSH\nfunction save-windows-logs-via-ssh() {\n    local node=\"${1}\"\n    local dest_dir=\"${2}\"\n\n    export-windows-docker-event-log \"${node}\"\n    export-windows-docker-images-list \"${node}\"\n\n    local remote_files=()\n    for file in \"${windows_node_logfiles[@]}\"; do\n      remote_files+=( \"${WINDOWS_LOGS_DIR}\\\\${file}\" )\n    done\n    remote_files+=( \"${windows_node_otherfiles[@]}\" )\n\n    # TODO(pjh, yujuhong): handle rotated logs and copying multiple files at the\n    # same time.\n    for remote_file in \"${remote_files[@]}\"; do\n      # Retry up to 3 times to allow ssh keys to be properly propagated and\n      # stored.\n      for retry in {1..3}; do\n        if gcloud compute scp --recurse --project \"${PROJECT}\" \\\n          --zone \"${ZONE}\" \"${node}:${remote_file}\" \"${dest_dir}\" \\\n          > /dev/null; then\n          break\n        else\n          sleep 10\n        fi\n      done\n    done\n}\n\n# Save log files and serial console output from Windows node $1 into local\n# directory $2.\n# This function shouldn't ever trigger errexit.\nfunction save-logs-windows() {\n    local -r node=\"${1}\"\n    local -r dest_dir=\"${2}\"\n\n    if [[ ! \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n      echo \"Not saving logs for ${node}, Windows log dumping requires gcloud support\"\n      return\n    fi\n\n    if [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then\n      save-windows-logs-via-diagnostics-tool \"${node}\" \"${dest_dir}\"\n    else\n      save-windows-logs-via-ssh \"${node}\" \"${dest_dir}\"\n    fi\n\n    # Serial port 1 contains the Windows console output.\n    gcloud compute instances get-serial-port-output --project \"${PROJECT}\" \\\n      --zone \"${ZONE}\" --port 1 \"${node}\" > \"${dest_dir}/serial-1.log\" || true\n}\n\n# Execute a command in container $2 on node $1.\n# Uses docker because the container may not ordinarily permit direct execution.\nfunction run-in-docker-container() {\n  local node_name=\"$1\"\n  local container=\"$2\"\n  shift 2\n  log-dump-ssh \"${node_name}\" \"docker exec \\\"\\$(docker ps -f label=io.kubernetes.container.name=${container} --format \\\"{{.ID}}\\\")\\\" $*\"\n}\n\nfunction dump_masters() {\n  local master_names=()\n  if [[ -n \"${use_custom_instance_list}\" ]]; then\n    while IFS='' read -r line; do master_names+=(\"$line\"); done < <(log_dump_custom_get_instances master)\n  elif [[ ! \"${master_ssh_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    echo \"Master SSH not supported for ${KUBERNETES_PROVIDER}\"\n    return\n  elif [[ -n \"${KUBEMARK_MASTER_NAME:-}\" ]]; then\n    master_names=( \"${KUBEMARK_MASTER_NAME}\" )\n  else\n    if ! (detect-master); then\n      echo 'Master not detected. Is the cluster up?'\n      return\n    fi\n    master_names=( \"${MASTER_NAME}\" )\n  fi\n\n  if [[ \"${#master_names[@]}\" == 0 ]]; then\n    echo 'No masters found?'\n    return\n  fi\n\n  proc=${max_dump_processes}\n  for master_name in \"${master_names[@]}\"; do\n    master_dir=\"${report_dir}/${master_name}\"\n    mkdir -p \"${master_dir}\"\n    save-logs \"${master_name}\" \"${master_dir}\" \"${master_logfiles}\" \"\" \"true\" &\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n    fi\n  done\n  # Wait for any remaining processes.\n  if [[ proc -gt 0 && proc -lt ${max_dump_processes} ]]; then\n    wait\n  fi\n}\n\n# Dumps logs from nodes in the cluster. Linux nodes to dump logs from can be\n# specified via $1 or $use_custom_instance_list. If not specified then the nodes\n# to dump logs for will be detected using detect-node-names(); if Windows nodes\n# are present then they will be detected and their logs will be dumped too.\nfunction dump_nodes() {\n  local node_names=()\n  local windows_node_names=()\n  if [[ -n \"${1:-}\" ]]; then\n    echo 'Dumping logs for nodes provided as args to dump_nodes() function'\n    node_names=( \"$@\" )\n  elif [[ -n \"${use_custom_instance_list}\" ]]; then\n    echo 'Dumping logs for nodes provided by log_dump_custom_get_instances() function'\n    while IFS='' read -r line; do node_names+=(\"$line\"); done < <(log_dump_custom_get_instances node)\n  elif [[ ! \"${node_ssh_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    echo \"Node SSH not supported for ${KUBERNETES_PROVIDER}\"\n    return\n  else\n    echo 'Detecting nodes in the cluster'\n    detect-node-names &> /dev/null\n    if [[ -n \"${NODE_NAMES:-}\" ]]; then\n      node_names=( \"${NODE_NAMES[@]}\" )\n    fi\n    if [[ -n \"${WINDOWS_NODE_NAMES:-}\" ]]; then\n      windows_node_names=( \"${WINDOWS_NODE_NAMES[@]}\" )\n    fi\n  fi\n\n  if [[ \"${#node_names[@]}\" == 0 && \"${#windows_node_names[@]}\" == 0 ]]; then\n    echo 'No nodes found!'\n    return\n  fi\n\n  node_logfiles_all=\"${node_logfiles}\"\n  if [[ \"${ENABLE_HOLLOW_NODE_LOGS:-}\" == \"true\" ]]; then\n    node_logfiles_all=\"${node_logfiles_all} ${hollow_node_logfiles}\"\n  fi\n\n  linux_nodes_selected_for_logs=()\n  if [[ -n \"${LOGDUMP_ONLY_N_RANDOM_NODES:-}\" ]]; then\n    # We randomly choose 'LOGDUMP_ONLY_N_RANDOM_NODES' many nodes for fetching logs.\n    for index in $(shuf -i 0-$(( ${#node_names[*]} - 1 )) -n \"${LOGDUMP_ONLY_N_RANDOM_NODES}\")\n    do\n      linux_nodes_selected_for_logs+=(\"${node_names[$index]}\")\n    done\n  else\n    linux_nodes_selected_for_logs=( \"${node_names[@]}\" )\n  fi\n  all_selected_nodes=( \"${linux_nodes_selected_for_logs[@]}\" )\n  all_selected_nodes+=( \"${windows_node_names[@]}\" )\n\n  proc=${max_dump_processes}\n  start=\"$(date +%s)\"\n  # log_dump_ssh_timeout is the maximal number of seconds the log dumping over\n  # SSH operation can take. Please note that the logic enforcing the timeout\n  # is only a best effort. The actual time of the operation may be longer\n  # due to waiting for all the child processes below.\n  log_dump_ssh_timeout_seconds=\"${LOG_DUMP_SSH_TIMEOUT_SECONDS:-}\"\n  for i in \"${!all_selected_nodes[@]}\"; do\n    node_name=\"${all_selected_nodes[$i]}\"\n    node_dir=\"${report_dir}/${node_name}\"\n    mkdir -p \"${node_dir}\"\n    if [[ \"${i}\" -lt \"${#linux_nodes_selected_for_logs[@]}\" ]]; then\n      # Save logs in the background. This speeds up things when there are\n      # many nodes.\n      save-logs \"${node_name}\" \"${node_dir}\" \"${node_logfiles_all}\" \"${node_systemd_services}\" &\n    else\n      save-logs-windows \"${node_name}\" \"${node_dir}\" &\n    fi\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n      now=\"$(date +%s)\"\n      if [[ -n \"${log_dump_ssh_timeout_seconds}\" && $((now - start)) -gt ${log_dump_ssh_timeout_seconds} ]]; then\n        echo \"WARNING: Hit timeout after ${log_dump_ssh_timeout_seconds} seconds, finishing log dumping over SSH shortly\"\n        break\n      fi\n    fi\n  done\n  # Wait for any remaining processes.\n  if [[ proc -gt 0 && proc -lt ${max_dump_processes} ]]; then\n    wait\n  fi\n}\n\n# Collect names of nodes which didn't run logexporter successfully.\n# This function examines NODE_NAMES but not WINDOWS_NODE_NAMES since logexporter\n# does not run on Windows nodes.\n#\n# Note: This step is O(#nodes^2) as we check if each node is present in the list of succeeded nodes.\n# Making it linear would add code complexity without much benefit (as it just takes ~1s for 5k nodes).\n# Assumes:\n#   NODE_NAMES\n# Sets:\n#   NON_LOGEXPORTED_NODES\nfunction find_non_logexported_nodes() {\n  local file=\"${gcs_artifacts_dir}/logexported-nodes-registry\"\n  echo \"Listing marker files ($file) for successful nodes...\"\n  succeeded_nodes=$(gsutil ls \"${file}\") || return 1\n  echo 'Successfully listed marker files for successful nodes'\n  NON_LOGEXPORTED_NODES=()\n  for node in \"${NODE_NAMES[@]}\"; do\n    if [[ ! \"${succeeded_nodes}\" =~ ${node} ]]; then\n      NON_LOGEXPORTED_NODES+=(\"${node}\")\n    fi\n  done\n}\n\n# This function examines NODE_NAMES but not WINDOWS_NODE_NAMES since logexporter\n# does not run on Windows nodes.\nfunction dump_nodes_with_logexporter() {\n  if [[ -n \"${use_custom_instance_list}\" ]]; then\n    echo 'Dumping logs for nodes provided by log_dump_custom_get_instances() function'\n    NODE_NAMES=()\n    while IFS='' read -r line; do NODE_NAMES+=(\"$line\"); done < <(log_dump_custom_get_instances node)\n  else\n    echo 'Detecting nodes in the cluster'\n    detect-node-names &> /dev/null\n  fi\n\n  if [[ -z \"${NODE_NAMES:-}\" ]]; then\n    echo 'No nodes found!'\n    return\n  fi\n\n  # Obtain parameters required by logexporter.\n  local -r service_account_credentials=\"$(base64 \"${GOOGLE_APPLICATION_CREDENTIALS}\" | tr -d '\\n')\"\n  local -r cloud_provider=\"${KUBERNETES_PROVIDER}\"\n  local -r enable_hollow_node_logs=\"${ENABLE_HOLLOW_NODE_LOGS:-false}\"\n  local -r logexport_sleep_seconds=\"$(( 90 + NUM_NODES / 3 ))\"\n  if [[ -z \"${ZONE_NODE_SELECTOR_DISABLED:-}\" ]]; then\n    local -r node_selector=\"${ZONE_NODE_SELECTOR_LABEL:-topology.kubernetes.io/zone}: ${ZONE}\"\n  fi\n\n  # Fill in the parameters in the logexporter daemonset template.\n  local -r tmp=\"${KUBE_TEMP}/logexporter\"\n  local -r manifest_yaml=\"${tmp}/logexporter-daemonset.yaml\"\n  mkdir -p \"${tmp}\"\n  cp \"${KUBE_ROOT}/cluster/log-dump/logexporter-daemonset.yaml\" \"${manifest_yaml}\"\n\n  sed -i'' -e \"s@{{.NodeSelector}}@${node_selector:-}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.LogexporterNamespace}}@${logexporter_namespace}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ServiceAccountCredentials}}@${service_account_credentials}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.CloudProvider}}@${cloud_provider}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.GCSPath}}@${gcs_artifacts_dir}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.EnableHollowNodeLogs}}@${enable_hollow_node_logs}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.DumpSystemdJournal}}@${dump_systemd_journal}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ExtraLogFiles}}@${extra_log_files}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ExtraSystemdServices}}@${extra_systemd_services}@g\" \"${manifest_yaml}\"\n\n  # Create the logexporter namespace, service-account secret and the logexporter daemonset within that namespace.\n  KUBECTL=\"${KUBE_ROOT}/cluster/kubectl.sh\"\n  if ! \"${KUBECTL}\" create -f \"${manifest_yaml}\"; then\n    echo 'Failed to create logexporter daemonset.. falling back to logdump through SSH'\n    \"${KUBECTL}\" delete namespace \"${logexporter_namespace}\" || true\n    dump_nodes \"${NODE_NAMES[@]}\"\n    logexporter_failed=1\n    return\n  fi\n\n  # Periodically fetch list of already logexported nodes to verify\n  # if we aren't already done.\n  start=\"$(date +%s)\"\n  while true; do\n    now=\"$(date +%s)\"\n    if [[ $((now - start)) -gt ${logexport_sleep_seconds} ]]; then\n      echo 'Waiting for all nodes to be logexported timed out.'\n      break\n    fi\n    if find_non_logexported_nodes; then\n      if [[ -z \"${NON_LOGEXPORTED_NODES:-}\" ]]; then\n        break\n      fi\n    fi\n    sleep 15\n  done\n\n  # Store logs from logexporter pods to allow debugging log exporting process\n  # itself.\n  proc=${max_dump_processes}\n  \"${KUBECTL}\" get pods -n \"${logexporter_namespace}\" -o jsonpath='{range .items[*]}{.metadata.name}{\"\\t\"}{.spec.nodeName}{\"\\n\"}{end}' | (while read -r pod node; do\n    echo \"Fetching logs from ${pod} running on ${node}\"\n    mkdir -p \"${report_dir}/${node}\"\n    \"${KUBECTL}\" logs -n \"${logexporter_namespace}\" \"${pod}\" > \"${report_dir}/${node}/${pod}.log\" &\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n    fi\n  # Wait for any remaining processes.\n  done; wait)\n\n  # List registry of marker files (of nodes whose logexporter succeeded) from GCS.\n  for retry in {1..10}; do\n    if find_non_logexported_nodes; then\n      break\n    else\n      echo \"Attempt ${retry} failed to list marker files for successful nodes\"\n      if [[ \"${retry}\" == 10 ]]; then\n        echo 'Final attempt to list marker files failed.. falling back to logdump through SSH'\n        \"${KUBECTL}\" delete namespace \"${logexporter_namespace}\" || true\n        dump_nodes \"${NODE_NAMES[@]}\"\n        logexporter_failed=1\n        return\n      fi\n      sleep 2\n    fi\n  done\n\n  failed_nodes=()\n  # The following if is needed, because defaulting for empty arrays\n  # seems to treat them as non-empty with single empty string.\n  if [[ -n \"${NON_LOGEXPORTED_NODES:-}\" ]]; then\n    for node in \"${NON_LOGEXPORTED_NODES[@]:-}\"; do\n      echo \"Logexporter didn't succeed on node ${node}. Queuing it for logdump through SSH.\"\n      failed_nodes+=(\"${node}\")\n    done\n  fi\n\n  # If less than a certain ratio of the nodes got logexported, report an error.\n  if [[ $(((${#NODE_NAMES[@]} - ${#failed_nodes[@]}) * 100)) -lt $((${#NODE_NAMES[@]} * log_dump_expected_success_percentage )) ]]; then\n    logexporter_failed=1\n  fi\n\n  # Delete the logexporter resources and dump logs for the failed nodes (if any) through SSH.\n  \"${KUBECTL}\" get pods --namespace \"${logexporter_namespace}\" || true\n  \"${KUBECTL}\" delete namespace \"${logexporter_namespace}\" || true\n  if [[ \"${#failed_nodes[@]}\" != 0 ]]; then\n    echo -e \"Dumping logs through SSH for the following nodes:\\n${failed_nodes[*]}\"\n    dump_nodes \"${failed_nodes[@]}\"\n  fi\n}\n\nfunction detect_node_failures() {\n  if ! [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    return\n  fi\n\n  detect-node-names\n  if [[ \"${KUBERNETES_PROVIDER}\" == \"gce\" ]]; then\n    local all_instance_groups=(\"${INSTANCE_GROUPS[@]}\" \"${WINDOWS_INSTANCE_GROUPS[@]}\")\n  else\n    local all_instance_groups=(\"${INSTANCE_GROUPS[@]}\")\n  fi\n\n  if [ -z \"${all_instance_groups:-}\" ]; then\n    return\n  fi\n  for group in \"${all_instance_groups[@]}\"; do\n    local creation_timestamp\n    creation_timestamp=$(gcloud compute instance-groups managed describe \\\n                         \"${group}\" \\\n                         --project \"${PROJECT}\" \\\n                         --zone \"${ZONE}\" \\\n                         --format='value(creationTimestamp)')\n    echo \"Failures for ${group} (if any):\"\n    gcloud logging read --order=asc \\\n          --format='table(timestamp,jsonPayload.resource.name,jsonPayload.event_subtype)' \\\n          --project \"${PROJECT}\" \\\n          \"resource.type=\\\"gce_instance\\\"\n           logName=\\\"projects/${PROJECT}/logs/compute.googleapis.com%2Factivity_log\\\"\n           (jsonPayload.event_subtype=\\\"compute.instances.hostError\\\" OR jsonPayload.event_subtype=\\\"compute.instances.automaticRestart\\\")\n           jsonPayload.resource.name:\\\"${group}\\\"\n           timestamp >= \\\"${creation_timestamp}\\\"\"\n  done\n}\n\nfunction main() {\n  print-deprecation-note\n  setup\n  kube::util::ensure-temp-dir\n  # Copy master logs to artifacts dir locally (through SSH).\n  echo \"Dumping logs from master locally to '${report_dir}'\"\n  dump_masters\n  if [[ \"${DUMP_ONLY_MASTER_LOGS:-}\" == \"true\" ]]; then\n    echo 'Skipping dumping of node logs'\n    return\n  fi\n\n  # Copy logs from nodes to GCS directly or to artifacts dir locally (through SSH).\n  if [[ -n \"${gcs_artifacts_dir}\" ]]; then\n    echo \"Dumping logs from nodes to GCS directly at '${gcs_artifacts_dir}' using logexporter\"\n    dump_nodes_with_logexporter\n  else\n    echo \"Dumping logs from nodes locally to '${report_dir}'\"\n    dump_nodes\n  fi\n\n  detect_node_failures\n  if [[ ${logexporter_failed} -ne 0 && ${log_dump_expected_success_percentage} -gt 0 ]]; then\n    return 1\n  fi\n}\n\nmain\n", "num_lines": 709}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A library of helper functions for landing kubemark containers on a\n# pre-existing Kubernetes master. See test/kubemark/pre-existing/README.md\n# for me details on using a pre-existing provider.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\nsource \"${KUBE_ROOT}/cluster/common.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nfunction detect-project() {\n  if [[ -z \"${MASTER_IP:-}\" ]]; then\n    echo \"Set 'MASTER_IP' to the instance assigned to be the Kubernetes master\" 1>&2\n    exit 1\n  fi\n\n  if [[ -z \"${PROJECT:-}\" ]]; then\n    echo \"Set 'PROJECT' to the name of the container project: $CONTAINER_REGISTRY/$PROJECT/kubemark\" >&2\n    exit 1\n  fi\n\n  if [[ -z \"${SERVICE_CLUSTER_IP_RANGE:-}\" ]]; then\n    cluster_range=$(echo \"${MASTER_IP}\" | awk -F '.' '{printf(\"%d.%d.%d.0\", $1, $2, $3)}')\n    SERVICE_CLUSTER_IP_RANGE=\"${SERVICE_CLUSTER_IP_RANGE:-$cluster_range/16}\"\n  fi\n}\n\nfunction create-certs {\n  execute-cmd-on-pre-existing-master-with-retries 'sudo cat /etc/kubernetes/admin.conf' > /tmp/kubeconfig\n\n  # CA_CERT_BASE64, KUBELET_CERT_BASE64 and KUBELET_KEY_BASE64 might be used\n  # in test/kubemark/iks/util.sh\n  # If it becomes clear that the variables are not used anywhere, then we can\n  # remove them:\n  CA_CERT_BASE64=$(grep certificate-authority /tmp/kubeconfig | awk '{print $2}' | head -n 1)\n  KUBELET_CERT_BASE64=$(grep client-certificate-data /tmp/kubeconfig | awk '{print $2}' | head -n 1)\n  KUBELET_KEY_BASE64=$(grep client-key-data /tmp/kubeconfig | awk '{print $2}' | head -n 1)\n  export CA_CERT_BASE64\n  export KUBELET_CERT_BASE64\n  export KUBELET_KEY_BASE64\n}\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script contains the helper functions that each provider hosting\n# Kubernetes must implement to use cluster/kube-*.sh scripts.\n\n# Must ensure that the following ENV vars are set\nfunction detect-master {\n\techo \"KUBE_MASTER_IP: ${KUBE_MASTER_IP:-}\" 1>&2\n\techo \"KUBE_MASTER: ${KUBE_MASTER:-}\" 1>&2\n}\n\n# Get node names if they are not static.\nfunction detect-node-names {\n\techo \"NODE_NAMES: [${NODE_NAMES[*]}]\" 1>&2\n}\n\n# Get node IP addresses and store in KUBE_NODE_IP_ADDRESSES[]\nfunction detect-nodes {\n\techo \"KUBE_NODE_IP_ADDRESSES: [${KUBE_NODE_IP_ADDRESSES[*]}]\" 1>&2\n}\n\n# Verify prereqs on host machine\nfunction verify-prereqs {\n\techo \"Skeleton Provider: verify-prereqs not implemented\" 1>&2\n}\n\n# Validate a kubernetes cluster\nfunction validate-cluster {\n\t# by default call the generic validate-cluster.sh script, customizable by\n\t# any cluster provider if this does not fit.\n\t\"${KUBE_ROOT}/cluster/validate-cluster.sh\"\n}\n\n# Instantiate a kubernetes cluster\nfunction kube-up {\n\techo \"Skeleton Provider: kube-up not implemented\" 1>&2\n}\n\n# Delete a kubernetes cluster\nfunction kube-down {\n\techo \"Skeleton Provider: kube-down not implemented\" 1>&2\n}\n\n# Execute prior to running tests to build a release if required for env\nfunction test-build-release {\n\techo \"Skeleton Provider: test-build-release not implemented\" 1>&2\n}\n\n# Execute prior to running tests to initialize required structure\nfunction test-setup {\n\techo \"Skeleton Provider: test-setup not implemented\" 1>&2\n}\n\n# Execute after running tests to perform any required clean-up\nfunction test-teardown {\n\techo \"Skeleton Provider: test-teardown not implemented\" 1>&2\n}\n\nfunction prepare-e2e {\n\techo \"Skeleton Provider: prepare-e2e not implemented\" 1>&2\n}\n\nfunction detect-project {\n\techo \"Skeleton Provider: detect-project not implemented\" 1>&2\n}\n", "num_lines": 80}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs `make test` command with some args for benchmark test.\n# The \"true\" target of this makerule is `hack/make-rules/test.sh`.\n# Args:\n#   WHAT: Directory names to test.  All *_test.go files under these\n#     directories will be run.  If not specified, \"everything\" will be tested.\n# Usage: `hack/benchmark-go.sh`.\n# Example: `hack/benchmark-go.sh WHAT=./pkg/kubelet`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nmake test \\\n    WHAT=\"$*\" \\\n    KUBE_COVER=\"\" \\\n    KUBE_RACE=\" \" \\\n    KUBE_TEST_ARGS=\"-- -test.run='^X' -benchtime=1s -bench=. -benchmem\" \\\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is a vestigial redirection.  Please do not add \"real\" logic.\n# The \"true\" target of this makerule is `hack/make-rules/cross.sh`.\n\n# This script runs `make cross` command.\n# The command sets up a go workspace locally and builds all for all appropriate\n# platforms.\n# Usage: `hack/build-cross.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\necho \"NOTE: $0 has been replaced by 'make cross'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make cross\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" cross\n", "num_lines": 38}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is a vestigial redirection.  Please do not add \"real\" logic.\n\n# This script runs `make all` command.\n# The command compiles all Makefile configs.\n# Args:\n#   WHAT: Directory names to build.  If any of these directories has a 'main'\n#     package, the build will produce executable files under $(OUT_DIR)/go/bin.\n#     If not specified, \"everything\" will be built.\n# Usage: `hack/build-go.sh`.\n# Example: `hack/build-go.sh WHAT=cmd/kubelet`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# For help output\nARGHELP=\"\"\nif [[ \"$#\" -gt 0 ]]; then\n    ARGHELP=\"WHAT='$*'\"\nfi\n\necho \"NOTE: $0 has been replaced by 'make' or 'make all'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make ${ARGHELP}\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" all WHAT=\"$*\"\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage Instructions: https://git.k8s.io/community/contributors/devel/sig-release/cherry-picks.md\n\n# Checkout a PR from GitHub. (Yes, this is sitting in a Git tree. How\n# meta.) Assumes you care about pulls from remote \"upstream\" and\n# checks them out to a branch named:\n#  automated-cherry-pick-of-<pr>-<target branch>-<timestamp>\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel)\"\ndeclare -r REPO_ROOT\ncd \"${REPO_ROOT}\"\n\nSTARTINGBRANCH=$(git symbolic-ref --short HEAD)\ndeclare -r STARTINGBRANCH\ndeclare -r REBASEMAGIC=\"${REPO_ROOT}/.git/rebase-apply\"\nDRY_RUN=${DRY_RUN:-\"\"}\nREGENERATE_DOCS=${REGENERATE_DOCS:-\"\"}\nUPSTREAM_REMOTE=${UPSTREAM_REMOTE:-upstream}\nFORK_REMOTE=${FORK_REMOTE:-origin}\nMAIN_REPO_ORG=${MAIN_REPO_ORG:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $3}')}\nMAIN_REPO_NAME=${MAIN_REPO_NAME:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $4}')}\n\nif [[ -z ${GITHUB_USER:-} ]]; then\n  echo \"Please export GITHUB_USER=<your-user> (or GH organization, if that's where your fork lives)\"\n  exit 1\nfi\n\nif ! command -v gh > /dev/null; then\n  echo \"Can't find 'gh' tool in PATH, please install from https://github.com/cli/cli\"\n  exit 1\nfi\n\nif [[ \"$#\" -lt 2 ]]; then\n  echo \"${0} <remote branch> <pr-number>...: cherry pick one or more <pr> onto <remote branch> and leave instructions for proposing pull request\"\n  echo\n  echo \"  Checks out <remote branch> and handles the cherry-pick of <pr> (possibly multiple) for you.\"\n  echo \"  Examples:\"\n  echo \"    $0 upstream/release-3.14 12345        # Cherry-picks PR 12345 onto upstream/release-3.14 and proposes that as a PR.\"\n  echo \"    $0 upstream/release-3.14 12345 56789  # Cherry-picks PR 12345, then 56789 and proposes the combination as a single PR.\"\n  echo\n  echo \"  Set the DRY_RUN environment var to skip git push and creating PR.\"\n  echo \"  This is useful for creating patches to a release branch without making a PR.\"\n  echo \"  When DRY_RUN is set the script will leave you in a branch containing the commits you cherry-picked.\"\n  echo\n  echo \"  Set the REGENERATE_DOCS environment var to regenerate documentation for the target branch after picking the specified commits.\"\n  echo \"  This is useful when picking commits containing changes to API documentation.\"\n  echo\n  echo \"  Set UPSTREAM_REMOTE (default: upstream) and FORK_REMOTE (default: origin)\"\n  echo \"  to override the default remote names to what you have locally.\"\n  echo\n  echo \"  For merge process info, see https://git.k8s.io/community/contributors/devel/sig-release/cherry-picks.md\"\n  exit 2\nfi\n\n# Checks if you are logged in. Will error/bail if you are not.\ngh auth status\n\nif git_status=$(git status --porcelain --untracked=no 2>/dev/null) && [[ -n \"${git_status}\" ]]; then\n  echo \"!!! Dirty tree. Clean up and try again.\"\n  exit 1\nfi\n\nif [[ -e \"${REBASEMAGIC}\" ]]; then\n  echo \"!!! 'git rebase' or 'git am' in progress. Clean up and try again.\"\n  exit 1\nfi\n\ndeclare -r BRANCH=\"$1\"\nshift 1\ndeclare -r PULLS=( \"$@\" )\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\nPULLDASH=$(join - \"${PULLS[@]/#/#}\") # Generates something like \"#12345-#56789\"\ndeclare -r PULLDASH\nPULLSUBJ=$(join \" \" \"${PULLS[@]/#/#}\") # Generates something like \"#12345 #56789\"\ndeclare -r PULLSUBJ\n\necho \"+++ Updating remotes...\"\ngit remote update \"${UPSTREAM_REMOTE}\" \"${FORK_REMOTE}\"\n\nif ! git log -n1 --format=%H \"${BRANCH}\" >/dev/null 2>&1; then\n  echo \"!!! '${BRANCH}' not found. The second argument should be something like ${UPSTREAM_REMOTE}/release-0.21.\"\n  echo \"    (In particular, it needs to be a valid, existing remote branch that I can 'git checkout'.)\"\n  exit 1\nfi\n\nNEWBRANCHREQ=\"automated-cherry-pick-of-${PULLDASH}\" # \"Required\" portion for tools.\ndeclare -r NEWBRANCHREQ\nNEWBRANCH=\"$(echo \"${NEWBRANCHREQ}-${BRANCH}\" | sed 's/\\//-/g')\"\ndeclare -r NEWBRANCH\nNEWBRANCHUNIQ=\"${NEWBRANCH}-$(date +%s)\"\ndeclare -r NEWBRANCHUNIQ\necho \"+++ Creating local branch ${NEWBRANCHUNIQ}\"\n\ncleanbranch=\"\"\ngitamcleanup=false\nfunction return_to_kansas {\n  if [[ \"${gitamcleanup}\" == \"true\" ]]; then\n    echo\n    echo \"+++ Aborting in-progress git am.\"\n    git am --abort >/dev/null 2>&1 || true\n  fi\n\n  # return to the starting branch and delete the PR text file\n  if [[ -z \"${DRY_RUN}\" ]]; then\n    echo\n    echo \"+++ Returning you to the ${STARTINGBRANCH} branch and cleaning up.\"\n    git checkout -f \"${STARTINGBRANCH}\" >/dev/null 2>&1 || true\n    if [[ -n \"${cleanbranch}\" ]]; then\n      git branch -D \"${cleanbranch}\" >/dev/null 2>&1 || true\n    fi\n  fi\n}\ntrap return_to_kansas EXIT\n\nSUBJECTS=()\nfunction make-a-pr() {\n  local rel\n  rel=\"$(basename \"${BRANCH}\")\"\n  echo\n  echo \"+++ Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}\"\n\n  local numandtitle\n  numandtitle=$(printf '%s\\n' \"${SUBJECTS[@]}\")\n  prtext=$(cat <<EOF\nCherry pick of ${PULLSUBJ} on ${rel}.\n\n${numandtitle}\n\nFor details on the cherry pick process, see the [cherry pick requests](https://git.k8s.io/community/contributors/devel/sig-release/cherry-picks.md) page.\nEOF\n)\n\n  gh pr create --title=\"Automated cherry pick of ${numandtitle}\" --body=\"${prtext}\" --head \"${GITHUB_USER}:${NEWBRANCH}\" --base \"${rel}\" --repo=\"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}\"\n}\n\ngit checkout -b \"${NEWBRANCHUNIQ}\" \"${BRANCH}\"\ncleanbranch=\"${NEWBRANCHUNIQ}\"\n\ngitamcleanup=true\nfor pull in \"${PULLS[@]}\"; do\n  echo \"+++ Downloading patch to /tmp/${pull}.patch (in case you need to do this again)\"\n\n  curl -o \"/tmp/${pull}.patch\" -sSL \"https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch\"\n  echo\n  echo \"+++ About to attempt cherry pick of PR. To reattempt:\"\n  echo \"  $ git am -3 /tmp/${pull}.patch\"\n  echo\n  git am -3 \"/tmp/${pull}.patch\" || {\n    conflicts=false\n    while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \\\n      || [[ -e \"${REBASEMAGIC}\" ]]; do\n      conflicts=true # <-- We should have detected conflicts once\n      echo\n      echo \"+++ Conflicts detected:\"\n      echo\n      (git status --porcelain | grep ^U) || echo \"!!! None. Did you git am --continue?\"\n      echo\n      echo \"+++ Please resolve the conflicts in another window (and remember to 'git add / git am --continue')\"\n      read -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\n      echo\n      if ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n        echo \"Aborting.\" >&2\n        exit 1\n      fi\n    done\n\n    if [[ \"${conflicts}\" != \"true\" ]]; then\n      echo \"!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'\"\n      exit 1\n    fi\n  }\n\n  # set the subject\n  subject=$(grep -m 1 \"^Subject\" \"/tmp/${pull}.patch\" | sed -e 's/Subject: \\[PATCH//g' | sed 's/.*] //')\n  SUBJECTS+=(\"#${pull}: ${subject}\")\n\n  # remove the patch file from /tmp\n  rm -f \"/tmp/${pull}.patch\"\ndone\ngitamcleanup=false\n\n# Re-generate docs (if needed)\nif [[ -n \"${REGENERATE_DOCS}\" ]]; then\n  echo\n  echo \"Regenerating docs...\"\n  if ! hack/generate-docs.sh; then\n    echo\n    echo \"hack/generate-docs.sh FAILED to complete.\"\n    exit 1\n  fi\nfi\n\nif [[ -n \"${DRY_RUN}\" ]]; then\n  echo \"!!! Skipping git push and PR creation because you set DRY_RUN.\"\n  echo \"To return to the branch you were in when you invoked this script:\"\n  echo\n  echo \"  git checkout ${STARTINGBRANCH}\"\n  echo\n  echo \"To delete this branch:\"\n  echo\n  echo \"  git branch -D ${NEWBRANCHUNIQ}\"\n  exit 0\nfi\n\nif git remote -v | grep ^\"${FORK_REMOTE}\" | grep \"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"; then\n  echo \"!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"\n  echo \"This isn't normal. Leaving you with push instructions:\"\n  echo\n  echo \"+++ First manually push the branch this script created:\"\n  echo\n  echo \"  git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\n  echo\n  echo \"where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.).\"\n  echo \"OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values.\"\n  echo\n  make-a-pr\n  cleanbranch=\"\"\n  exit 0\nfi\n\necho\necho \"+++ I'm about to do the following to push to GitHub (and I'm assuming ${FORK_REMOTE} is your personal fork):\"\necho\necho \"  git push ${FORK_REMOTE} ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\necho\nread -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\nif ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n  echo \"Aborting.\" >&2\n  exit 1\nfi\n\ngit push \"${FORK_REMOTE}\" -f \"${NEWBRANCHUNIQ}:${NEWBRANCH}\"\nmake-a-pr\n", "num_lines": 254}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script will build a dev release and push it to an existing cluster.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# Build a dev release\nif ! make -f \"${KUBE_ROOT}\"/Makefile quick-release\nthen\n        echo \"Building a release failed!\"\n        exit 1\nfi\n\n# Now push this out to the cluster\n\"${KUBE_ROOT}/cluster/kube-push.sh\"\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script will build a dev release and bring up a new cluster with that\n# release.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# Build a dev release\n\n\nif ! make -f \"${KUBE_ROOT}\"/Makefile quick-release\nthen\n        echo \"Building the release failed!\"\n        exit 1\nfi\n\n# Now bring a new cluster up with that release.\n\"${KUBE_ROOT}/cluster/kube-up.sh\"\n", "num_lines": 37}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script builds some binaries and then the conformance image.\n# REGISTRY and VERSION must be set.\n# Example usage:\n#   $ export REGISTRY=gcr.io/someone\n#   $ export VERSION=v1.4.0-testfix\n#   ./hack/dev-push-conformance.sh\n# That will build and push gcr.io/someone/conformance-amd64:v1.4.0-testfix\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=\"$(dirname \"${BASH_SOURCE[0]}\")/..\"\nsource \"${KUBE_ROOT}/build/common.sh\"\n\nif [[ -z \"${REGISTRY:-}\" ]]; then\n\techo \"REGISTRY must be set\"\n\texit 1\nfi\nif [[ -z \"${VERSION:-}\" ]]; then\n\techo \"VERSION must be set\"\n\texit 1\nfi\n\nIMAGE=\"${REGISTRY}/conformance-amd64:${VERSION}\"\n\nkube::build::verify_prereqs\nkube::build::build_image\nkube::build::run_build_command make WHAT=\"vendor/github.com/onsi/ginkgo/ginkgo test/e2e/e2e.test cmd/kubectl cluster/images/conformance/go-runner\"\nkube::build::copy_output\n\nmake -C \"${KUBE_ROOT}/cluster/images/conformance\" build\ndocker push \"${IMAGE}\"\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is a vestigial redirection.  Please do not add \"real\" logic.\n# The \"true\" target of this makerule is `hack/make-rules/test-e2e-node.sh`.\n\n# This script runs `make test-e2e-node` command.\n# The command builds and runs node end-to-end tests.\n# Args:\n#  FOCUS: Regexp that matches the tests to be run.  Defaults to \"\".\n#  SKIP: Regexp that matches the tests that needs to be skipped.  Defaults\n# Usage: `hack/e2e-node-test.sh `.\n# Example: `hack/e2e-node-test.sh FOCUS=Kubelet SKIP=container`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# For help output\nARGHELP=\"\"\nif [[ -n \"${FOCUS:-}\" ]]; then\n    ARGHELP=\"FOCUS='${FOCUS}' \"\nfi\nif [[ -n \"${SKIP:-}\" ]]; then\n    ARGHELP=\"${ARGHELP}SKIP='${SKIP}'\"\nfi\n\necho \"NOTE: $0 has been replaced by 'make test-e2e-node'\"\necho\necho \"This script supports a number of parameters passed as environment variables.\"\necho \"Please see the Makefile for more details.\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make test-e2e-node ${ARGHELP}\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" test-e2e-node FOCUS=\"${FOCUS:-}\" SKIP=\"${SKIP:-}\"\n", "num_lines": 53}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o pipefail\nset -o nounset\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nexport KUBE_ROOT\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/logging.sh\"\n\nif [[ ! -d \"${KUBE_ROOT}/pkg\" ]]; then\n\techo \"${KUBE_ROOT}/pkg not detected.  This script should be run from a location where the source dirs are available.\"\n\texit 1\nfi\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install tools we need, but only from vendor/...\ngo install k8s.io/kubernetes/vendor/github.com/go-bindata/go-bindata/go-bindata\n\n# run the generation from the root directory for stable output\npushd \"${KUBE_ROOT}\" >/dev/null\n\n# These are files for e2e tests.\nBINDATA_OUTPUT=\"test/e2e/generated/bindata.go\"\ngo-bindata -nometadata -o \"${BINDATA_OUTPUT}.tmp\" -pkg generated \\\n\t-ignore .jpg -ignore .png -ignore .md \\\n\t\"test/conformance/testdata/...\" \\\n\t\"test/e2e/testing-manifests/...\" \\\n\t\"test/e2e_node/testing-manifests/...\" \\\n\t\"test/images/...\" \\\n\t\"test/fixtures/...\"\n\ngofmt -s -w \"${BINDATA_OUTPUT}.tmp\"\n\n# Here we compare and overwrite only if different to avoid updating the\n# timestamp and triggering a rebuild. The 'cat' redirect trick to preserve file\n# permissions of the target file.\nif ! cmp -s \"${BINDATA_OUTPUT}.tmp\" \"${BINDATA_OUTPUT}\" ; then\n\tcat \"${BINDATA_OUTPUT}.tmp\" > \"${BINDATA_OUTPUT}\"\n\tV=2 kube::log::info \"Generated bindata file : ${BINDATA_OUTPUT} has $(wc -l ${BINDATA_OUTPUT}) lines of lovely automated artifacts\"\nelse\n\tV=2 kube::log::info \"No changes in generated bindata file: ${BINDATA_OUTPUT}\"\nfi\n\nrm -f \"${BINDATA_OUTPUT}.tmp\"\n\n# These are files for runtime code\nBINDATA_OUTPUT=\"staging/src/k8s.io/kubectl/pkg/generated/bindata.go\"\ngo-bindata -nometadata -nocompress -o \"${BINDATA_OUTPUT}.tmp\" -pkg generated \\\n\t-ignore .jpg -ignore .png -ignore .md \\\n\t\"translations/...\"\n\ngofmt -s -w \"${BINDATA_OUTPUT}.tmp\"\n\n# Here we compare and overwrite only if different to avoid updating the\n# timestamp and triggering a rebuild. The 'cat' redirect trick to preserve file\n# permissions of the target file.\nif ! cmp -s \"${BINDATA_OUTPUT}.tmp\" \"${BINDATA_OUTPUT}\" ; then\n\tcat \"${BINDATA_OUTPUT}.tmp\" > \"${BINDATA_OUTPUT}\"\n\tV=2 kube::log::info \"Generated bindata file : ${BINDATA_OUTPUT} has $(wc -l ${BINDATA_OUTPUT}) lines of lovely automated artifacts\"\nelse\n\tV=2 kube::log::info \"No changes in generated bindata file: ${BINDATA_OUTPUT}\"\nfi\n\nrm -f \"${BINDATA_OUTPUT}.tmp\"\n\npopd >/dev/null\n", "num_lines": 86}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file is not intended to be run automatically. It is meant to be run\n# immediately before exporting docs. We do not want to check these documents in\n# by default.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_HACK_ROOT=$(dirname \"${BASH_SOURCE[0]}\")\n\necho \"WARNING: hack/generate-docs.sh is an alias for hack/update-generated-docs.sh\"\necho \"and will be removed in a future version.\"\n\n\"${KUBE_HACK_ROOT}\"/update-generated-docs.sh\n", "num_lines": 31}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs `curl` command to get the kubernetes build file.\n# Version number or publication is either a proper version number'\n# (e.g. \"v1.0.6\", \"v1.2.0-alpha.1.881+376438b69c7612\") or a version'\n#  publication of the form <bucket>/<version> (e.g. \"release/stable\",'\n# \"ci/latest-1\").'\n\n# Usage `hack/get-build.sh [Version]`.\n# Example `hack/get-build.sh v1.16.4`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nsource \"${KUBE_ROOT}/cluster/common.sh\"\n\ndeclare -r KUBE_RELEASE_BUCKET_URL=\"https://storage.googleapis.com/kubernetes-release\"\ndeclare -r KUBE_DEV_RELEASE_BUCKET_URL=\"https://storage.googleapis.com/kubernetes-release-dev\"\ndeclare -r KUBE_TAR_NAME=\"kubernetes.tar.gz\"\n\nusage() {\n  echo \"${0} [-v] <version number or publication>\"\n  echo \"  -v:  Don't get tars, just print the version number\"\n  echo \"\"\n  echo '  Version number or publication is either a proper version number'\n  echo '  (e.g. \"v1.0.6\", \"v1.2.0-alpha.1.881+376438b69c7612\") or a version'\n  echo '  publication of the form <bucket>/<version> (e.g. \"release/stable\",'\n  echo '  \"ci/latest-1\").  Some common ones are:'\n  echo '    - \"release/stable\"'\n  echo '    - \"release/latest\"'\n  echo '    - \"ci/latest\"'\n  echo '  See the docs on getting builds for more information about version'\n  echo '  publication.'\n}\n\nprint_version=false\n\nwhile getopts \":vh\" opt; do\n  case ${opt} in\n    v)\n      print_version=\"true\"\n      ;;\n    h)\n      usage\n      exit 0\n      ;;\n    \\?)\n      echo \"Invalid option: -$OPTARG\" >&2\n      usage\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [[ $# -ne 1 ]]; then\n    usage\n    exit 1\nfi\n\nset_binary_version \"${1}\"\n\nif [[ \"${print_version}\" == \"true\" ]]; then\n  echo \"${KUBE_VERSION}\"\nelse\n  echo \"Using version at ${1}: ${KUBE_VERSION}\" >&2\n  if [[ ${KUBE_VERSION} =~ ${KUBE_RELEASE_VERSION_REGEX} ]]; then\n    curl --fail -o \"kubernetes-${KUBE_VERSION}.tar.gz\" \"${KUBE_RELEASE_BUCKET_URL}/release/${KUBE_VERSION}/${KUBE_TAR_NAME}\"\n  elif [[ ${KUBE_VERSION} =~ ${KUBE_CI_VERSION_REGEX} ]]; then\n    curl --fail -o \"kubernetes-${KUBE_VERSION}.tar.gz\" \"${KUBE_DEV_RELEASE_BUCKET_URL}/ci/${KUBE_VERSION}/${KUBE_TAR_NAME}\"\n  else\n    echo \"Version doesn't match regexp\" >&2\n    exit 1\n  fi\nfi\n", "num_lines": 93}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs e2e tests on Google Cloud Platform.\n# Usage: `hack/ginkgo-e2e.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/cluster/common.sh\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Find the ginkgo binary build as part of the release.\nginkgo=$(kube::util::find-binary \"ginkgo\")\ne2e_test=$(kube::util::find-binary \"e2e.test\")\n\n# --- Setup some env vars.\n\nGINKGO_PARALLEL=${GINKGO_PARALLEL:-n} # set to 'y' to run tests in parallel\nCLOUD_CONFIG=${CLOUD_CONFIG:-\"\"}\n\n# If 'y', Ginkgo's reporter will not print out in color when tests are run\n# in parallel\nGINKGO_NO_COLOR=${GINKGO_NO_COLOR:-n}\n\n# If 'y', will rerun failed tests once to give them a second chance.\nGINKGO_TOLERATE_FLAKES=${GINKGO_TOLERATE_FLAKES:-n}\n\n# If set, the command executed will be:\n# - `dlv exec` if set to \"delve\"\n# - `gdb` if set to \"gdb\"\n# NOTE: for this to work the e2e.test binary has to be compiled with\n# make WHAT=test/e2e/e2e.test GOGCFLAGS=\"all=-N -l\" GOLDFLAGS=\"\"\nE2E_TEST_DEBUG_TOOL=${E2E_TEST_DEBUG_TOOL:-}\n\n: \"${KUBECTL:=\"${KUBE_ROOT}/cluster/kubectl.sh\"}\"\n: \"${KUBE_CONFIG_FILE:=\"config-test.sh\"}\"\n\nexport KUBECTL KUBE_CONFIG_FILE\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nfunction detect-master-from-kubeconfig() {\n    export KUBECONFIG=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\n\n    local cc\n    cc=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.current-context}\")\n    if [[ -n \"${KUBE_CONTEXT:-}\" ]]; then\n      cc=\"${KUBE_CONTEXT}\"\n    fi\n    local cluster\n    cluster=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.contexts[?(@.name == \\\"${cc}\\\")].context.cluster}\")\n    KUBE_MASTER_URL=$(\"${KUBE_ROOT}/cluster/kubectl.sh\" config view -o jsonpath=\"{.clusters[?(@.name == \\\"${cluster}\\\")].cluster.server}\")\n}\n\n# ---- Do cloud-provider-specific setup\nif [[ -n \"${KUBERNETES_CONFORMANCE_TEST:-}\" ]]; then\n    echo \"Conformance test: not doing test setup.\"\n    KUBERNETES_PROVIDER=${KUBERNETES_CONFORMANCE_PROVIDER:-\"skeleton\"}\n\n    detect-master-from-kubeconfig\n\n    auth_config=(\n      \"--kubeconfig=${KUBECONFIG}\"\n    )\nelse\n    echo \"Setting up for KUBERNETES_PROVIDER=\\\"${KUBERNETES_PROVIDER}\\\".\"\n\n    prepare-e2e\n\n    detect-master >/dev/null\n\n    KUBE_MASTER_URL=\"${KUBE_MASTER_URL:-}\"\n    if [[ -z \"${KUBE_MASTER_URL:-}\" && -n \"${KUBE_MASTER_IP:-}\" ]]; then\n      KUBE_MASTER_URL=\"https://${KUBE_MASTER_IP}\"\n    fi\n\n    auth_config=(\n      \"--kubeconfig=${KUBECONFIG:-$DEFAULT_KUBECONFIG}\"\n    )\nfi\n\nif [[ -n \"${NODE_INSTANCE_PREFIX:-}\" ]]; then\n  NODE_INSTANCE_GROUP=\"${NODE_INSTANCE_PREFIX}-group\"\nfi\n\nif [[ \"${KUBERNETES_PROVIDER}\" == \"gce\" ]]; then\n  set_num_migs\n  NODE_INSTANCE_GROUP=\"\"\n  for ((i=1; i<=NUM_MIGS; i++)); do\n    if [[ ${i} == \"${NUM_MIGS}\" ]]; then\n      # We are assigning the same mig names as create-nodes function from cluster/gce/util.sh.\n      NODE_INSTANCE_GROUP=\"${NODE_INSTANCE_GROUP}${NODE_INSTANCE_PREFIX}-group\"\n    else\n      NODE_INSTANCE_GROUP=\"${NODE_INSTANCE_GROUP}${NODE_INSTANCE_PREFIX}-group-${i},\"\n    fi\n  done\nfi\n\n# TODO(kubernetes/test-infra#3330): Allow NODE_INSTANCE_GROUP to be\n# set before we get here, which eliminates any cluster/gke use if\n# KUBERNETES_CONFORMANCE_PROVIDER is set to \"gke\".\nif [[ -z \"${NODE_INSTANCE_GROUP:-}\" ]] && [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then\n  detect-node-instance-groups\n  NODE_INSTANCE_GROUP=$(kube::util::join , \"${NODE_INSTANCE_GROUP[@]}\")\nfi\n\nif [[ \"${KUBERNETES_PROVIDER}\" == \"azure\" ]]; then\n    if [[ ${CLOUD_CONFIG} == \"\" ]]; then\n        echo \"Missing azure cloud config\"\n        exit 1\n    fi\nfi\n\nginkgo_args=()\nif [[ -n \"${CONFORMANCE_TEST_SKIP_REGEX:-}\" ]]; then\n  ginkgo_args+=(\"--skip=${CONFORMANCE_TEST_SKIP_REGEX}\")\n  ginkgo_args+=(\"--seed=1436380640\")\nfi\nif [[ -n \"${GINKGO_PARALLEL_NODES:-}\" ]]; then\n  ginkgo_args+=(\"--nodes=${GINKGO_PARALLEL_NODES}\")\nelif [[ ${GINKGO_PARALLEL} =~ ^[yY]$ ]]; then\n  ginkgo_args+=(\"--nodes=25\")\nfi\n\nif [[ \"${GINKGO_UNTIL_IT_FAILS:-}\" == true ]]; then\n  ginkgo_args+=(\"--untilItFails=true\")\nfi\n\nFLAKE_ATTEMPTS=1\nif [[ \"${GINKGO_TOLERATE_FLAKES}\" == \"y\" ]]; then\n  FLAKE_ATTEMPTS=2\nfi\n\nif [[ \"${GINKGO_NO_COLOR}\" == \"y\" ]]; then\n  ginkgo_args+=(\"--noColor\")\nfi\n\nCONTAINER_RUNTIME=${CONTAINER_RUNTIME:-${KUBE_CONTAINER_RUNTIME:-}}\n\n# The --host setting is used only when providing --auth_config\n# If --kubeconfig is used, the host to use is retrieved from the .kubeconfig\n# file and the one provided with --host is ignored.\n# Add path for things like running kubectl binary.\nPATH=$(dirname \"${e2e_test}\"):\"${PATH}\"\nexport PATH\n\n# Choose the program to execute.\nprogram=(\"${ginkgo}\")\nif [[ \"${E2E_TEST_DEBUG_TOOL}\" == \"delve\" ]]; then\n  program=(\"dlv\" \"exec\")\nelif [[ \"${E2E_TEST_DEBUG_TOOL}\" == \"gdb\" ]]; then\n  program=(\"gdb\")\nfi\n\n\"${program[@]}\" \"${ginkgo_args[@]:+${ginkgo_args[@]}}\" \"${e2e_test}\" -- \\\n  \"${auth_config[@]:+${auth_config[@]}}\" \\\n  --ginkgo.flakeAttempts=\"${FLAKE_ATTEMPTS}\" \\\n  --host=\"${KUBE_MASTER_URL}\" \\\n  --provider=\"${KUBERNETES_PROVIDER}\" \\\n  --gce-project=\"${PROJECT:-}\" \\\n  --gce-zone=\"${ZONE:-}\" \\\n  --gce-region=\"${REGION:-}\" \\\n  --gce-multizone=\"${MULTIZONE:-false}\" \\\n  --gke-cluster=\"${CLUSTER_NAME:-}\" \\\n  --kube-master=\"${KUBE_MASTER:-}\" \\\n  --cluster-tag=\"${CLUSTER_ID:-}\" \\\n  --cloud-config-file=\"${CLOUD_CONFIG:-}\" \\\n  --repo-root=\"${KUBE_ROOT}\" \\\n  --node-instance-group=\"${NODE_INSTANCE_GROUP:-}\" \\\n  --prefix=\"${KUBE_GCE_INSTANCE_PREFIX:-e2e}\" \\\n  --network=\"${KUBE_GCE_NETWORK:-${KUBE_GKE_NETWORK:-e2e}}\" \\\n  --node-tag=\"${NODE_TAG:-}\" \\\n  --master-tag=\"${MASTER_TAG:-}\" \\\n  --docker-config-file=\"${DOCKER_CONFIG_FILE:-}\" \\\n  --dns-domain=\"${KUBE_DNS_DOMAIN:-cluster.local}\" \\\n  --ginkgo.slowSpecThreshold=\"${GINKGO_SLOW_SPEC_THRESHOLD:-300}\" \\\n  ${CONTAINER_RUNTIME:+\"--container-runtime=${CONTAINER_RUNTIME}\"} \\\n  ${MASTER_OS_DISTRIBUTION:+\"--master-os-distro=${MASTER_OS_DISTRIBUTION}\"} \\\n  ${NODE_OS_DISTRIBUTION:+\"--node-os-distro=${NODE_OS_DISTRIBUTION}\"} \\\n  ${NUM_NODES:+\"--num-nodes=${NUM_NODES}\"} \\\n  ${E2E_REPORT_DIR:+\"--report-dir=${E2E_REPORT_DIR}\"} \\\n  ${E2E_REPORT_PREFIX:+\"--report-prefix=${E2E_REPORT_PREFIX}\"} \\\n  \"${@:-}\"\n", "num_lines": 200}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script grabs profiles from running components.\n# Usage: `hack/grab-profiles.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nfunction grab_profiles_from_component {\n  local requested_profiles=$1\n  local mem_pprof_flags=$2\n  local binary=$3\n  local tunnel_port=$4\n  local path=$5\n  local output_prefix=$6\n  local timestamp=$7\n\n  echo \"binary: $binary\"\n\n  for profile in ${requested_profiles}; do\n    case ${profile} in\n      cpu)\n        go tool pprof \"-pdf\" \"${binary}\" \"http://localhost:${tunnel_port}${path}/debug/pprof/profile\" > \"${output_prefix}-${profile}-profile-${timestamp}.pdf\"\n        ;;\n      mem)\n        # There are different kinds of memory profiles that are available that\n        # had to be grabbed separately: --inuse-space, --inuse-objects,\n        # --alloc-space, --alloc-objects. We need to iterate over all requested\n        # kinds.\n        for flag in ${mem_pprof_flags}; do\n          go tool pprof \"-${flag}\" \"-pdf\" \"${binary}\" \"http://localhost:${tunnel_port}${path}/debug/pprof/heap\" > \"${output_prefix}-${profile}-${flag}-profile-${timestamp}.pdf\"\n        done\n        ;;\n    esac\n  done\n}\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nserver_addr=\"\"\nkubelet_addresses=\"\"\nkubelet_binary=\"\"\nmaster_binary=\"\"\nscheduler_binary=\"\"\nscheduler_port=\"10251\"\ncontroller_manager_port=\"10252\"\ncontroller_manager_binary=\"\"\nrequested_profiles=\"\"\nmem_pprof_flags=\"\"\nprofile_components=\"\"\noutput_dir=\".\"\ntunnel_port=\"${tunnel_port:-1234}\"\n\nif ! args=$(getopt -o s:mho:k:c -l server:,master,heapster,output:,kubelet:,scheduler,controller-manager,help,inuse-space,inuse-objects,alloc-space,alloc-objects,cpu,kubelet-binary:,master-binary:,scheduler-binary:,controller-manager-binary:,scheduler-port:,controller-manager-port: -- \"$@\"); then\n  >&2 echo \"Error in getopt\"\n  exit 1\nfi\n\nHEAPSTER_VERSION=\"v0.18.2\"\nMASTER_PPROF_PATH=\"\"\nHEAPSTER_PPROF_PATH=\"/api/v1/namespaces/kube-system/services/monitoring-heapster/proxy\"\nKUBELET_PPROF_PATH_PREFIX=\"/api/v1/proxy/nodes\"\nSCHEDULER_PPROF_PATH_PREFIX=\"/api/v1/namespaces/kube-system/pods/kube-scheduler/proxy\"\nCONTROLLER_MANAGER_PPROF_PATH_PREFIX=\"/api/v1/namespaces/kube-system/pods/kube-controller-manager/proxy\"\n\neval set -- \"${args}\"\n\nwhile true; do\n  case $1 in\n    -s|--server)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --server flag\"\n        exit 1\n      fi\n      server_addr=$1\n      shift\n      ;;\n    -m|--master)\n      shift\n      profile_components=\"master ${profile_components}\"\n      ;;\n    --master-binary)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --master-binary flag\"\n        exit 1\n      fi\n      master_binary=$1\n      shift\n      ;;\n    -h|--heapster)\n      shift\n      profile_components=\"heapster ${profile_components}\"\n      ;;\n    -k|--kubelet)\n      shift\n      profile_components=\"kubelet ${profile_components}\"\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --kubelet flag\"\n        exit 1\n      fi\n      kubelet_addresses=\"$1 $kubelet_addresses\"\n      shift\n      ;;\n    --kubelet-binary)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --kubelet-binary flag\"\n        exit 1\n      fi\n      kubelet_binary=$1\n      shift\n      ;;\n    --scheduler)\n      shift\n      profile_components=\"scheduler ${profile_components}\"\n      ;;\n    --scheduler-binary)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --scheduler-binary flag\"\n        exit 1\n      fi\n      scheduler_binary=$1\n      shift\n      ;;\n    --scheduler-port)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --scheduler-port flag\"\n        exit 1\n      fi\n      scheduler_port=$1\n      shift\n      ;;\n    -c|--controller-manager)\n      shift\n      profile_components=\"controller-manager ${profile_components}\"\n      ;;\n    --controller-manager-binary)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --controller-manager-binary flag\"\n        exit 1\n      fi\n      controller_manager_binary=$1\n      shift\n      ;;\n    --controller-manager-port)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --controller-manager-port flag\"\n        exit 1\n      fi\n      controller_manager_port=$1\n      shift\n      ;;\n    -o|--output)\n      shift\n      if [ -z \"$1\" ]; then\n        >&2 echo \"empty argument to --output flag\"\n        exit 1\n      fi\n      output_dir=$1\n      shift\n      ;;\n    --inuse-space)\n      shift\n      requested_profiles=\"mem ${requested_profiles}\"\n      mem_pprof_flags=\"inuse_space ${mem_pprof_flags}\"\n      ;;\n    --inuse-objects)\n      shift\n      requested_profiles=\"mem ${requested_profiles}\"\n      mem_pprof_flags=\"inuse_objects ${mem_pprof_flags}\"\n      ;;\n    --alloc-space)\n      shift\n      requested_profiles=\"mem ${requested_profiles}\"\n      mem_pprof_flags=\"alloc_space ${mem_pprof_flags}\"\n      ;;\n    --alloc-objects)\n      shift\n      requested_profiles=\"mem ${requested_profiles}\"\n      mem_pprof_flags=\"alloc_objects ${mem_pprof_flags}\"\n      ;;\n    --cpu)\n      shift\n      requested_profiles=\"cpu ${requested_profiles}\"\n      ;;\n    --help)\n      shift\n      echo \"Recognized options:\n        -o/--output,\n        -s/--server,\n        -m/--master,\n        -h/--heapster,\n        --inuse-space,\n        --inuse-objects,\n        --alloc-space,\n        --alloc-objects,\n        --cpu,\n        --help\"\n      exit 0\n      ;;\n    --)\n      shift\n      break;\n      ;;\n  esac\ndone\n\nif [[ -z \"${server_addr}\" ]]; then\n  >&2 echo \"Server flag is required\"\n  exit 1\nfi\n\nif [[ -z \"${profile_components}\" ]]; then\n  >&2 echo \"Choose at least one component to profile\"\n  exit 1\nfi\n\nif [[ -z \"${requested_profiles}\" ]]; then\n  >&2 echo \"Choose at least one profiling option\"\n  exit 1\nfi\n\ngcloud compute ssh \"${server_addr}\" --ssh-flag=-nN --ssh-flag=-L\"${tunnel_port}\":localhost:8080 &\n\necho \"Waiting for tunnel to be created...\"\nkube::util::wait_for_url http://localhost:\"${tunnel_port}\"/healthz\n\nSSH_PID=$(pgrep -f \"/usr/bin/ssh.*${tunnel_port}:localhost:8080\")\nkube::util::trap_add \"kill $SSH_PID\" EXIT\nkube::util::trap_add \"kill $SSH_PID\" SIGTERM\n\nrequested_profiles=$(echo \"${requested_profiles}\" | xargs -n1 | LC_ALL=C sort -u | xargs)\nprofile_components=$(echo \"${profile_components}\" | xargs -n1 | LC_ALL=C sort -u | xargs)\nkubelet_addresses=$(echo \"${kubelet_addresses}\" | xargs -n1 | LC_ALL=C sort -u | xargs)\necho \"requested profiles: ${requested_profiles}\"\necho \"flags for heap profile: ${mem_pprof_flags}\"\n\ntimestamp=$(date +%Y%m%d%H%M%S)\nbinary=\"\"\n\nfor component in ${profile_components}; do\n  case ${component} in\n    master)\n      path=${MASTER_PPROF_PATH}\n      binary=${master_binary}\n      ;;\n    controller-manager)\n      path=\"${CONTROLLER_MANAGER_PPROF_PATH_PREFIX}-${server_addr}:${controller_manager_port}\"\n      binary=${controller_manager_binary}\n      ;;\n    scheduler)\n      path=\"${SCHEDULER_PPROF_PATH_PREFIX}-${server_addr}:${scheduler_port}\"\n      binary=${scheduler_binary}\n      ;;\n    heapster)\n      rm heapster\n      wget https://github.com/kubernetes/heapster/releases/download/${HEAPSTER_VERSION}/heapster\n      kube::util::trap_add 'rm -f heapster' EXIT\n      kube::util::trap_add 'rm -f heapster' SIGTERM\n      binary=heapster\n      path=${HEAPSTER_PPROF_PATH}\n      ;;\n    kubelet)\n      path=\"${KUBELET_PPROF_PATH_PREFIX}\"\n      if [[ -z \"${kubelet_binary}\" ]]; then\n        binary=\"${KUBE_ROOT}/_output/local/bin/linux/amd64/kubelet\"\n      else\n        binary=${kubelet_binary}\n      fi\n      ;;\n  esac\n\n  if [[ \"${component}\" == \"kubelet\" ]]; then\n    for node in ${kubelet_addresses//[,;]/' '}; do\n      grab_profiles_from_component \"${requested_profiles}\" \"${mem_pprof_flags}\" \"${binary}\" \"${tunnel_port}\" \"${path}/${node}/proxy\" \"${output_dir}/${component}\" \"${timestamp}\"\n    done\n  else\n    grab_profiles_from_component \"${requested_profiles}\" \"${mem_pprof_flags}\" \"${binary}\" \"${tunnel_port}\" \"${path}\" \"${output_dir}/${component}\" \"${timestamp}\"\n  fi\ndone\n", "num_lines": 303}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is convenience to download and install etcd in third_party.\n# Mostly just used by CI.\n# Usage: `hack/install-etcd.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::etcd::install\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks version dependencies of modules. It checks whether all\n# pinned versions of checked dependencies match their preferred version or not.\n# Usage: `hack/lint-dependencies.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Explicitly opt into go modules, even though we're inside a GOPATH directory\nexport GO111MODULE=on\n# Explicitly set GOFLAGS to ignore vendor, since GOFLAGS=-mod=vendor breaks dependency resolution while rebuilding vendor\nexport GOFLAGS=-mod=mod\n# Detect problematic GOPROXY settings that prevent lookup of dependencies\nif [[ \"${GOPROXY:-}\" == \"off\" ]]; then\n  kube::log::error \"Cannot run with \\$GOPROXY=off\"\n  exit 1\nfi\n\nkube::golang::verify_go_version\nkube::util::require-jq\n\n# let us log all errors before we exit\nrc=0\n\n# List of dependencies we need to avoid dragging back into kubernetes/kubernetes\nforbidden_repos=(\n  \"k8s.io/klog\"  # we have switched to klog v2, so avoid klog v1\n)\nfor forbidden_repo in \"${forbidden_repos[@]}\"; do\n  deps_on_forbidden=$(go mod graph | grep \" ${forbidden_repo}@\" || echo \"\")\n  if [ -n \"${deps_on_forbidden}\" ]; then\n    kube::log::error \"The following have transitive dependencies on ${forbidden_repo}, which is not allowed:\"\n    echo \"${deps_on_forbidden}\"\n    echo \"\"\n    rc=1\n  fi\ndone\n\noutdated=$(go list -m -json all | jq -r \"\n  select(.Replace.Version != null) |\n  select(.Version != .Replace.Version) |\n  select(.Path) |\n  \\\"\\(.Path)\n    pinned:    \\(.Replace.Version)\n    preferred: \\(.Version)\n    hack/pin-dependency.sh \\(.Path) \\(.Version)\\\"\n\")\nif [[ -n \"${outdated}\" ]]; then\n  echo \"These modules are pinned to versions different than the minimal preferred version.\"\n  echo \"That means that without replace directives, a different version would be selected,\"\n  echo \"which breaks consumers of our published modules.\"\n  echo \"1. Use hack/pin-dependency.sh to switch to the preferred version for each module\"\n  echo \"2. Run hack/update-vendor.sh to rebuild the vendor directory\"\n  echo \"3. Run hack/lint-dependencies.sh to verify no additional changes are required\"\n  echo \"\"\n  echo \"${outdated}\"\nfi\n\nunused=$(comm -23 \\\n  <(go mod edit -json | jq -r '.Replace[] | select(.New.Version != null) | .Old.Path' | sort) \\\n  <(go list -m -json all | jq -r .Path | sort))\nif [[ -n \"${unused}\" ]]; then\n  echo \"\"\n  echo \"Use the given commands to remove pinned module versions that aren't actually used:\"\n  echo \"${unused}\" | xargs -L 1 echo 'GO111MODULE=on go mod edit -dropreplace'\nfi\n\nif [[ -n \"${unused}${outdated}\" ]]; then\n  rc=1\nfi\n\necho \"All pinned versions of checked dependencies match their preferred version.\"\nexit $rc\n", "num_lines": 93}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script lists all of the [Feature:.+] tests in our e2e suite.\n# Usage: `hack/list-feature-tests.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\ngrep \"\\[Feature:\\w+\\]\" \"${KUBE_ROOT}\"/test/e2e/**/*.go -Eoh | LC_ALL=C sort -u\n", "num_lines": 26}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# This script builds and runs a local kubernetes cluster. You may need to run\n# this as root to allow kubelet to open docker's socket, and to write the test\n# CA in /var/run/kubernetes.\n# Usage: `hack/local-up-cluster.sh`.\n\nDOCKER_OPTS=${DOCKER_OPTS:-\"\"}\nexport DOCKER=(docker \"${DOCKER_OPTS[@]}\")\nDOCKER_ROOT=${DOCKER_ROOT:-\"\"}\nALLOW_PRIVILEGED=${ALLOW_PRIVILEGED:-\"\"}\nDENY_SECURITY_CONTEXT_ADMISSION=${DENY_SECURITY_CONTEXT_ADMISSION:-\"\"}\nPSP_ADMISSION=${PSP_ADMISSION:-\"\"}\nNODE_ADMISSION=${NODE_ADMISSION:-\"\"}\nRUNTIME_CONFIG=${RUNTIME_CONFIG:-\"\"}\nKUBELET_AUTHORIZATION_WEBHOOK=${KUBELET_AUTHORIZATION_WEBHOOK:-\"\"}\nKUBELET_AUTHENTICATION_WEBHOOK=${KUBELET_AUTHENTICATION_WEBHOOK:-\"\"}\nPOD_MANIFEST_PATH=${POD_MANIFEST_PATH:-\"/var/run/kubernetes/static-pods\"}\nKUBELET_FLAGS=${KUBELET_FLAGS:-\"\"}\nKUBELET_IMAGE=${KUBELET_IMAGE:-\"\"}\n# many dev environments run with swap on, so we don't fail in this env\nFAIL_SWAP_ON=${FAIL_SWAP_ON:-\"false\"}\n# Name of the network plugin, eg: \"kubenet\"\nNET_PLUGIN=${NET_PLUGIN:-\"\"}\n# Name of the dns addon, eg: \"kube-dns\" or \"coredns\"\nDNS_ADDON=${DNS_ADDON:-\"coredns\"}\n# Place the config files and binaries required by NET_PLUGIN in these directory,\n# eg: \"/etc/cni/net.d\" for config files, and \"/opt/cni/bin\" for binaries.\nCNI_CONF_DIR=${CNI_CONF_DIR:-\"\"}\nCNI_BIN_DIR=${CNI_BIN_DIR:-\"\"}\nCLUSTER_CIDR=${CLUSTER_CIDR:-10.1.0.0/16}\nSERVICE_CLUSTER_IP_RANGE=${SERVICE_CLUSTER_IP_RANGE:-10.0.0.0/24}\nFIRST_SERVICE_CLUSTER_IP=${FIRST_SERVICE_CLUSTER_IP:-10.0.0.1}\n# if enabled, must set CGROUP_ROOT\nCGROUPS_PER_QOS=${CGROUPS_PER_QOS:-true}\n# name of the cgroup driver, i.e. cgroupfs or systemd\nCGROUP_DRIVER=${CGROUP_DRIVER:-\"\"}\n# if cgroups per qos is enabled, optionally change cgroup root\nCGROUP_ROOT=${CGROUP_ROOT:-\"\"}\n# owner of client certs, default to current user if not specified\nUSER=${USER:-$(whoami)}\n\n# enables testing eviction scenarios locally.\nEVICTION_HARD=${EVICTION_HARD:-\"memory.available<100Mi,nodefs.available<10%,nodefs.inodesFree<5%\"}\nEVICTION_SOFT=${EVICTION_SOFT:-\"\"}\nEVICTION_PRESSURE_TRANSITION_PERIOD=${EVICTION_PRESSURE_TRANSITION_PERIOD:-\"1m\"}\n\n# This script uses docker0 (or whatever container bridge docker is currently using)\n# and we don't know the IP of the DNS pod to pass in as --cluster-dns.\n# To set this up by hand, set this flag and change DNS_SERVER_IP.\n# Note also that you need API_HOST (defined below) for correct DNS.\nKUBE_PROXY_MODE=${KUBE_PROXY_MODE:-\"\"}\nENABLE_CLUSTER_DNS=${KUBE_ENABLE_CLUSTER_DNS:-true}\nENABLE_NODELOCAL_DNS=${KUBE_ENABLE_NODELOCAL_DNS:-false}\nDNS_SERVER_IP=${KUBE_DNS_SERVER_IP:-10.0.0.10}\nLOCAL_DNS_IP=${KUBE_LOCAL_DNS_IP:-169.254.20.10}\nDNS_MEMORY_LIMIT=${KUBE_DNS_MEMORY_LIMIT:-170Mi}\nDNS_DOMAIN=${KUBE_DNS_NAME:-\"cluster.local\"}\nKUBECTL=${KUBECTL:-\"${KUBE_ROOT}/cluster/kubectl.sh\"}\nWAIT_FOR_URL_API_SERVER=${WAIT_FOR_URL_API_SERVER:-60}\nMAX_TIME_FOR_URL_API_SERVER=${MAX_TIME_FOR_URL_API_SERVER:-1}\nENABLE_DAEMON=${ENABLE_DAEMON:-false}\nHOSTNAME_OVERRIDE=${HOSTNAME_OVERRIDE:-\"127.0.0.1\"}\nEXTERNAL_CLOUD_PROVIDER=${EXTERNAL_CLOUD_PROVIDER:-false}\nEXTERNAL_CLOUD_PROVIDER_BINARY=${EXTERNAL_CLOUD_PROVIDER_BINARY:-\"\"}\nEXTERNAL_CLOUD_VOLUME_PLUGIN=${EXTERNAL_CLOUD_VOLUME_PLUGIN:-\"\"}\nCLOUD_PROVIDER=${CLOUD_PROVIDER:-\"\"}\nCLOUD_CONFIG=${CLOUD_CONFIG:-\"\"}\nKUBELET_PROVIDER_ID=${KUBELET_PROVIDER_ID:-\"$(hostname)\"}\nFEATURE_GATES=${FEATURE_GATES:-\"AllAlpha=false\"}\nSTORAGE_BACKEND=${STORAGE_BACKEND:-\"etcd3\"}\nSTORAGE_MEDIA_TYPE=${STORAGE_MEDIA_TYPE:-\"application/vnd.kubernetes.protobuf\"}\n# preserve etcd data. you also need to set ETCD_DIR.\nPRESERVE_ETCD=\"${PRESERVE_ETCD:-false}\"\n\n# enable kubernetes dashboard\nENABLE_CLUSTER_DASHBOARD=${KUBE_ENABLE_CLUSTER_DASHBOARD:-false}\n\n# enable Kubernetes-CSI snapshotter\nENABLE_CSI_SNAPSHOTTER=${ENABLE_CSI_SNAPSHOTTER:-false}\n\n# RBAC Mode options\nAUTHORIZATION_MODE=${AUTHORIZATION_MODE:-\"Node,RBAC\"}\nKUBECONFIG_TOKEN=${KUBECONFIG_TOKEN:-\"\"}\nAUTH_ARGS=${AUTH_ARGS:-\"\"}\n\n# WebHook Authentication and Authorization\nAUTHORIZATION_WEBHOOK_CONFIG_FILE=${AUTHORIZATION_WEBHOOK_CONFIG_FILE:-\"\"}\nAUTHENTICATION_WEBHOOK_CONFIG_FILE=${AUTHENTICATION_WEBHOOK_CONFIG_FILE:-\"\"}\n\n# Install a default storage class (enabled by default)\nDEFAULT_STORAGE_CLASS=${KUBE_DEFAULT_STORAGE_CLASS:-true}\n\n# Do not run the mutation detector by default on a local cluster.\n# It is intended for a specific type of testing and inherently leaks memory.\nKUBE_CACHE_MUTATION_DETECTOR=\"${KUBE_CACHE_MUTATION_DETECTOR:-false}\"\nexport KUBE_CACHE_MUTATION_DETECTOR\n\n# panic the server on watch decode errors since they are considered coder mistakes\nKUBE_PANIC_WATCH_DECODE_ERROR=\"${KUBE_PANIC_WATCH_DECODE_ERROR:-true}\"\nexport KUBE_PANIC_WATCH_DECODE_ERROR\n\n# Default list of admission Controllers to invoke prior to persisting objects in cluster\n# The order defined here does not matter.\nENABLE_ADMISSION_PLUGINS=${ENABLE_ADMISSION_PLUGINS:-\"NamespaceLifecycle,LimitRanger,ServiceAccount,DefaultStorageClass,DefaultTolerationSeconds,Priority,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,ResourceQuota\"}\nDISABLE_ADMISSION_PLUGINS=${DISABLE_ADMISSION_PLUGINS:-\"\"}\nADMISSION_CONTROL_CONFIG_FILE=${ADMISSION_CONTROL_CONFIG_FILE:-\"\"}\n\n# START_MODE can be 'all', 'kubeletonly', 'nokubelet', or 'nokubeproxy'\nSTART_MODE=${START_MODE:-\"all\"}\n\n# A list of controllers to enable\nKUBE_CONTROLLERS=\"${KUBE_CONTROLLERS:-\"*\"}\"\n\n# Audit policy\nAUDIT_POLICY_FILE=${AUDIT_POLICY_FILE:-\"\"}\n\n# sanity check for OpenStack provider\nif [ \"${CLOUD_PROVIDER}\" == \"openstack\" ]; then\n    if [ \"${CLOUD_CONFIG}\" == \"\" ]; then\n        echo \"Missing CLOUD_CONFIG env for OpenStack provider!\"\n        exit 1\n    fi\n    if [ ! -f \"${CLOUD_CONFIG}\" ]; then\n        echo \"Cloud config ${CLOUD_CONFIG} doesn't exist\"\n        exit 1\n    fi\nfi\n\nif [ \"$(id -u)\" != \"0\" ]; then\n    echo \"WARNING : This script MAY be run as root for docker socket / iptables functionality; if failures occur, retry as root.\" 2>&1\nfi\n\n# Stop right away if the build fails\nset -e\n\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nkube::util::ensure-gnu-sed\n\nfunction usage {\n            echo \"This script starts a local kube cluster. \"\n            echo \"Example 0: hack/local-up-cluster.sh -h  (this 'help' usage description)\"\n            echo \"Example 1: hack/local-up-cluster.sh -o _output/dockerized/bin/linux/amd64/ (run from docker output)\"\n            echo \"Example 2: hack/local-up-cluster.sh -O (auto-guess the bin path for your platform)\"\n            echo \"Example 3: hack/local-up-cluster.sh (build a local copy of the source)\"\n}\n\n# This function guesses where the existing cached binary build is for the `-O`\n# flag\nfunction guess_built_binary_path {\n  local apiserver_path\n  apiserver_path=$(kube::util::find-binary \"kube-apiserver\")\n  if [[ -z \"${apiserver_path}\" ]]; then\n    return\n  fi\n  echo -n \"$(dirname \"${apiserver_path}\")\"\n}\n\n### Allow user to supply the source directory.\nGO_OUT=${GO_OUT:-}\nwhile getopts \"ho:O\" OPTION\ndo\n    case ${OPTION} in\n        o)\n            echo \"skipping build\"\n            GO_OUT=\"${OPTARG}\"\n            echo \"using source ${GO_OUT}\"\n            ;;\n        O)\n            GO_OUT=$(guess_built_binary_path)\n            if [ \"${GO_OUT}\" == \"\" ]; then\n                echo \"Could not guess the correct output directory to use.\"\n                exit 1\n            fi\n            ;;\n        h)\n            usage\n            exit\n            ;;\n        ?)\n            usage\n            exit\n            ;;\n    esac\ndone\n\nif [ \"x${GO_OUT}\" == \"x\" ]; then\n    make -C \"${KUBE_ROOT}\" WHAT=\"cmd/kubectl cmd/kube-apiserver cmd/kube-controller-manager cmd/cloud-controller-manager cmd/kubelet cmd/kube-proxy cmd/kube-scheduler\"\nelse\n    echo \"skipped the build.\"\nfi\n\n# Shut down anyway if there's an error.\nset +e\n\nAPI_PORT=${API_PORT:-0}\nAPI_SECURE_PORT=${API_SECURE_PORT:-6443}\n\n# WARNING: For DNS to work on most setups you should export API_HOST as the docker0 ip address,\nAPI_HOST=${API_HOST:-localhost}\nAPI_HOST_IP=${API_HOST_IP:-\"127.0.0.1\"}\nADVERTISE_ADDRESS=${ADVERTISE_ADDRESS:-\"\"}\nNODE_PORT_RANGE=${NODE_PORT_RANGE:-\"\"}\nAPI_BIND_ADDR=${API_BIND_ADDR:-\"0.0.0.0\"}\nEXTERNAL_HOSTNAME=${EXTERNAL_HOSTNAME:-localhost}\n\nKUBELET_HOST=${KUBELET_HOST:-\"127.0.0.1\"}\n# By default only allow CORS for requests on localhost\nAPI_CORS_ALLOWED_ORIGINS=${API_CORS_ALLOWED_ORIGINS:-/127.0.0.1(:[0-9]+)?$,/localhost(:[0-9]+)?$}\nKUBELET_PORT=${KUBELET_PORT:-10250}\n# By default we use 0(close it) for it's insecure\nKUBELET_READ_ONLY_PORT=${KUBELET_READ_ONLY_PORT:-0}\nLOG_LEVEL=${LOG_LEVEL:-3}\n# Use to increase verbosity on particular files, e.g. LOG_SPEC=token_controller*=5,other_controller*=4\nLOG_SPEC=${LOG_SPEC:-\"\"}\nLOG_DIR=${LOG_DIR:-\"/tmp\"}\nCONTAINER_RUNTIME=${CONTAINER_RUNTIME:-\"docker\"}\nCONTAINER_RUNTIME_ENDPOINT=${CONTAINER_RUNTIME_ENDPOINT:-\"\"}\nRUNTIME_REQUEST_TIMEOUT=${RUNTIME_REQUEST_TIMEOUT:-\"2m\"}\nIMAGE_SERVICE_ENDPOINT=${IMAGE_SERVICE_ENDPOINT:-\"\"}\nCPU_CFS_QUOTA=${CPU_CFS_QUOTA:-true}\nENABLE_HOSTPATH_PROVISIONER=${ENABLE_HOSTPATH_PROVISIONER:-\"false\"}\nCLAIM_BINDER_SYNC_PERIOD=${CLAIM_BINDER_SYNC_PERIOD:-\"15s\"} # current k8s default\nENABLE_CONTROLLER_ATTACH_DETACH=${ENABLE_CONTROLLER_ATTACH_DETACH:-\"true\"} # current default\n# This is the default dir and filename where the apiserver will generate a self-signed cert\n# which should be able to be used as the CA to verify itself\nCERT_DIR=${CERT_DIR:-\"/var/run/kubernetes\"}\nROOT_CA_FILE=${CERT_DIR}/server-ca.crt\nCLUSTER_SIGNING_CERT_FILE=${CLUSTER_SIGNING_CERT_FILE:-\"${CERT_DIR}/client-ca.crt\"}\nCLUSTER_SIGNING_KEY_FILE=${CLUSTER_SIGNING_KEY_FILE:-\"${CERT_DIR}/client-ca.key\"}\n# Reuse certs will skip generate new ca/cert files under CERT_DIR\n# it's useful with PRESERVE_ETCD=true because new ca will make existed service account secrets invalided\nREUSE_CERTS=${REUSE_CERTS:-false}\n\n# name of the cgroup driver, i.e. cgroupfs or systemd\nif [[ ${CONTAINER_RUNTIME} == \"docker\" ]]; then\n  # default cgroup driver to match what is reported by docker to simplify local development\n  if [[ -z ${CGROUP_DRIVER} ]]; then\n    # match driver with docker runtime reported value (they must match)\n    CGROUP_DRIVER=$(docker info | grep \"Cgroup Driver:\" |  sed -e 's/^[[:space:]]*//'|cut -f3- -d' ')\n    echo \"Kubelet cgroup driver defaulted to use: ${CGROUP_DRIVER}\"\n  fi\n  if [[ -f /var/log/docker.log && ! -f \"${LOG_DIR}/docker.log\" ]]; then\n    ln -s /var/log/docker.log \"${LOG_DIR}/docker.log\"\n  fi\nfi\n\n\n\n# Ensure CERT_DIR is created for auto-generated crt/key and kubeconfig\nmkdir -p \"${CERT_DIR}\" &>/dev/null || sudo mkdir -p \"${CERT_DIR}\"\nCONTROLPLANE_SUDO=$(test -w \"${CERT_DIR}\" || echo \"sudo -E\")\n\nfunction test_apiserver_off {\n    # For the common local scenario, fail fast if server is already running.\n    # this can happen if you run local-up-cluster.sh twice and kill etcd in between.\n    if [[ \"${API_PORT}\" -gt \"0\" ]]; then\n        if ! curl --silent -g \"${API_HOST}:${API_PORT}\" ; then\n            echo \"API SERVER insecure port is free, proceeding...\"\n        else\n            echo \"ERROR starting API SERVER, exiting. Some process on ${API_HOST} is serving already on ${API_PORT}\"\n            exit 1\n        fi\n    fi\n\n    if ! curl --silent -k -g \"${API_HOST}:${API_SECURE_PORT}\" ; then\n        echo \"API SERVER secure port is free, proceeding...\"\n    else\n        echo \"ERROR starting API SERVER, exiting. Some process on ${API_HOST} is serving already on ${API_SECURE_PORT}\"\n        exit 1\n    fi\n}\n\nfunction detect_binary {\n    # Detect the OS name/arch so that we can find our binary\n    case \"$(uname -s)\" in\n      Darwin)\n        host_os=darwin\n        ;;\n      Linux)\n        host_os=linux\n        ;;\n      *)\n        echo \"Unsupported host OS.  Must be Linux or Mac OS X.\" >&2\n        exit 1\n        ;;\n    esac\n\n    case \"$(uname -m)\" in\n      x86_64*)\n        host_arch=amd64\n        ;;\n      i?86_64*)\n        host_arch=amd64\n        ;;\n      amd64*)\n        host_arch=amd64\n        ;;\n      aarch64*)\n        host_arch=arm64\n        ;;\n      arm64*)\n        host_arch=arm64\n        ;;\n      arm*)\n        host_arch=arm\n        ;;\n      i?86*)\n        host_arch=x86\n        ;;\n      s390x*)\n        host_arch=s390x\n        ;;\n      ppc64le*)\n        host_arch=ppc64le\n        ;;\n      *)\n        echo \"Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le.\" >&2\n        exit 1\n        ;;\n    esac\n\n   GO_OUT=\"${KUBE_ROOT}/_output/local/bin/${host_os}/${host_arch}\"\n}\n\ncleanup()\n{\n  echo \"Cleaning up...\"\n  # delete running images\n  # if [[ \"${ENABLE_CLUSTER_DNS}\" == true ]]; then\n  # Still need to figure why this commands throw an error: Error from server: client: etcd cluster is unavailable or misconfigured\n  #     ${KUBECTL} --namespace=kube-system delete service kube-dns\n  # And this one hang forever:\n  #     ${KUBECTL} --namespace=kube-system delete rc kube-dns-v10\n  # fi\n\n  # Check if the API server is still running\n  [[ -n \"${APISERVER_PID-}\" ]] && kube::util::read-array APISERVER_PIDS < <(pgrep -P \"${APISERVER_PID}\" ; ps -o pid= -p \"${APISERVER_PID}\")\n  [[ -n \"${APISERVER_PIDS-}\" ]] && sudo kill \"${APISERVER_PIDS[@]}\" 2>/dev/null\n\n  # Check if the controller-manager is still running\n  [[ -n \"${CTLRMGR_PID-}\" ]] && kube::util::read-array CTLRMGR_PIDS < <(pgrep -P \"${CTLRMGR_PID}\" ; ps -o pid= -p \"${CTLRMGR_PID}\")\n  [[ -n \"${CTLRMGR_PIDS-}\" ]] && sudo kill \"${CTLRMGR_PIDS[@]}\" 2>/dev/null\n\n  # Check if the cloud-controller-manager is still running\n  [[ -n \"${CLOUD_CTLRMGR_PID-}\" ]] && kube::util::read-array CLOUD_CTLRMGR_PIDS < <(pgrep -P \"${CLOUD_CTLRMGR_PID}\" ; ps -o pid= -p \"${CLOUD_CTLRMGR_PID}\")\n  [[ -n \"${CLOUD_CTLRMGR_PIDS-}\" ]] && sudo kill \"${CLOUD_CTLRMGR_PIDS[@]}\" 2>/dev/null\n\n  # Check if the kubelet is still running\n  [[ -n \"${KUBELET_PID-}\" ]] && kube::util::read-array KUBELET_PIDS < <(pgrep -P \"${KUBELET_PID}\" ; ps -o pid= -p \"${KUBELET_PID}\")\n  [[ -n \"${KUBELET_PIDS-}\" ]] && sudo kill \"${KUBELET_PIDS[@]}\" 2>/dev/null\n\n  # Check if the proxy is still running\n  [[ -n \"${PROXY_PID-}\" ]] && kube::util::read-array PROXY_PIDS < <(pgrep -P \"${PROXY_PID}\" ; ps -o pid= -p \"${PROXY_PID}\")\n  [[ -n \"${PROXY_PIDS-}\" ]] && sudo kill \"${PROXY_PIDS[@]}\" 2>/dev/null\n\n  # Check if the scheduler is still running\n  [[ -n \"${SCHEDULER_PID-}\" ]] && kube::util::read-array SCHEDULER_PIDS < <(pgrep -P \"${SCHEDULER_PID}\" ; ps -o pid= -p \"${SCHEDULER_PID}\")\n  [[ -n \"${SCHEDULER_PIDS-}\" ]] && sudo kill \"${SCHEDULER_PIDS[@]}\" 2>/dev/null\n\n  # Check if the etcd is still running\n  [[ -n \"${ETCD_PID-}\" ]] && kube::etcd::stop\n  if [[ \"${PRESERVE_ETCD}\" == \"false\" ]]; then\n    [[ -n \"${ETCD_DIR-}\" ]] && kube::etcd::clean_etcd_dir\n  fi\n\n  # Drop the rule we added\n  iptables -t nat -D OUTPUT -m addrtype --dst-type LOCAL -j DOCKER || true\n  exit 0\n}\n\n# Check if all processes are still running. Prints a warning once each time\n# a process dies unexpectedly.\nfunction healthcheck {\n  if [[ -n \"${APISERVER_PID-}\" ]] && ! sudo kill -0 \"${APISERVER_PID}\" 2>/dev/null; then\n    warning_log \"API server terminated unexpectedly, see ${APISERVER_LOG}\"\n    APISERVER_PID=\n  fi\n\n  if [[ -n \"${CTLRMGR_PID-}\" ]] && ! sudo kill -0 \"${CTLRMGR_PID}\" 2>/dev/null; then\n    warning_log \"kube-controller-manager terminated unexpectedly, see ${CTLRMGR_LOG}\"\n    CTLRMGR_PID=\n  fi\n\n  if [[ -n \"${KUBELET_PID-}\" ]] && ! sudo kill -0 \"${KUBELET_PID}\" 2>/dev/null; then\n    warning_log \"kubelet terminated unexpectedly, see ${KUBELET_LOG}\"\n    KUBELET_PID=\n  fi\n\n  if [[ -n \"${PROXY_PID-}\" ]] && ! sudo kill -0 \"${PROXY_PID}\" 2>/dev/null; then\n    warning_log \"kube-proxy terminated unexpectedly, see ${PROXY_LOG}\"\n    PROXY_PID=\n  fi\n\n  if [[ -n \"${SCHEDULER_PID-}\" ]] && ! sudo kill -0 \"${SCHEDULER_PID}\" 2>/dev/null; then\n    warning_log \"scheduler terminated unexpectedly, see ${SCHEDULER_LOG}\"\n    SCHEDULER_PID=\n  fi\n\n  if [[ -n \"${ETCD_PID-}\" ]] && ! sudo kill -0 \"${ETCD_PID}\" 2>/dev/null; then\n    warning_log \"etcd terminated unexpectedly\"\n    ETCD_PID=\n  fi\n}\n\nfunction print_color {\n  message=$1\n  prefix=${2:+$2: } # add colon only if defined\n  color=${3:-1}     # default is red\n  echo -n \"$(tput bold)$(tput setaf \"${color}\")\"\n  echo \"${prefix}${message}\"\n  echo -n \"$(tput sgr0)\"\n}\n\nfunction warning_log {\n  print_color \"$1\" \"W$(date \"+%m%d %H:%M:%S\")]\" 1\n}\n\nfunction start_etcd {\n    echo \"Starting etcd\"\n    export ETCD_LOGFILE=${LOG_DIR}/etcd.log\n    kube::etcd::start\n}\n\nfunction set_service_accounts {\n    SERVICE_ACCOUNT_LOOKUP=${SERVICE_ACCOUNT_LOOKUP:-true}\n    SERVICE_ACCOUNT_KEY=${SERVICE_ACCOUNT_KEY:-/tmp/kube-serviceaccount.key}\n    # Generate ServiceAccount key if needed\n    if [[ ! -f \"${SERVICE_ACCOUNT_KEY}\" ]]; then\n      mkdir -p \"$(dirname \"${SERVICE_ACCOUNT_KEY}\")\"\n      openssl genrsa -out \"${SERVICE_ACCOUNT_KEY}\" 2048 2>/dev/null\n    fi\n}\n\nfunction generate_certs {\n    # Create CA signers\n    if [[ \"${ENABLE_SINGLE_CA_SIGNER:-}\" = true ]]; then\n        kube::util::create_signing_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" server '\"client auth\",\"server auth\"'\n        sudo cp \"${CERT_DIR}/server-ca.key\" \"${CERT_DIR}/client-ca.key\"\n        sudo cp \"${CERT_DIR}/server-ca.crt\" \"${CERT_DIR}/client-ca.crt\"\n        sudo cp \"${CERT_DIR}/server-ca-config.json\" \"${CERT_DIR}/client-ca-config.json\"\n    else\n        kube::util::create_signing_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" server '\"server auth\"'\n        kube::util::create_signing_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" client '\"client auth\"'\n    fi\n\n    # Create auth proxy client ca\n    kube::util::create_signing_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" request-header '\"client auth\"'\n\n    # serving cert for kube-apiserver\n    kube::util::create_serving_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"server-ca\" kube-apiserver kubernetes.default kubernetes.default.svc \"localhost\" \"${API_HOST_IP}\" \"${API_HOST}\" \"${FIRST_SERVICE_CLUSTER_IP}\"\n\n    # Create client certs signed with client-ca, given id, given CN and a number of groups\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' controller system:kube-controller-manager\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' scheduler  system:kube-scheduler\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' admin system:admin system:masters\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' kube-apiserver kube-apiserver\n\n    # Create matching certificates for kube-aggregator\n    kube::util::create_serving_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"server-ca\" kube-aggregator api.kube-public.svc \"localhost\" \"${API_HOST_IP}\"\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" request-header-ca auth-proxy system:auth-proxy\n\n    # TODO remove masters and add rolebinding\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' kube-aggregator system:kube-aggregator system:masters\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" kube-aggregator\n}\n\nfunction generate_kubeproxy_certs {\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' kube-proxy system:kube-proxy system:nodes\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" kube-proxy\n}\n\nfunction generate_kubelet_certs {\n    kube::util::create_client_certkey \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" 'client-ca' kubelet \"system:node:${HOSTNAME_OVERRIDE}\" system:nodes\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" kubelet\n}\n\nfunction start_apiserver {\n    security_admission=\"\"\n    if [[ -n \"${DENY_SECURITY_CONTEXT_ADMISSION}\" ]]; then\n      security_admission=\",SecurityContextDeny\"\n    fi\n    if [[ -n \"${PSP_ADMISSION}\" ]]; then\n      security_admission=\",PodSecurityPolicy\"\n    fi\n    if [[ -n \"${NODE_ADMISSION}\" ]]; then\n      security_admission=\",NodeRestriction\"\n    fi\n\n    # Append security_admission plugin\n    ENABLE_ADMISSION_PLUGINS=\"${ENABLE_ADMISSION_PLUGINS}${security_admission}\"\n\n    authorizer_arg=\"\"\n    if [[ -n \"${AUTHORIZATION_MODE}\" ]]; then\n      authorizer_arg=\"--authorization-mode=${AUTHORIZATION_MODE}\"\n    fi\n    priv_arg=\"\"\n    if [[ -n \"${ALLOW_PRIVILEGED}\" ]]; then\n      priv_arg=\"--allow-privileged=${ALLOW_PRIVILEGED}\"\n    fi\n\n    runtime_config=\"\"\n    if [[ -n \"${RUNTIME_CONFIG}\" ]]; then\n      runtime_config=\"--runtime-config=${RUNTIME_CONFIG}\"\n    fi\n\n    # Let the API server pick a default address when API_HOST_IP\n    # is set to 127.0.0.1\n    advertise_address=\"\"\n    if [[ \"${API_HOST_IP}\" != \"127.0.0.1\" ]]; then\n        advertise_address=\"--advertise-address=${API_HOST_IP}\"\n    fi\n    if [[ \"${ADVERTISE_ADDRESS}\" != \"\" ]] ; then\n        advertise_address=\"--advertise-address=${ADVERTISE_ADDRESS}\"\n    fi\n    node_port_range=\"\"\n    if [[ \"${NODE_PORT_RANGE}\" != \"\" ]] ; then\n        node_port_range=\"--service-node-port-range=${NODE_PORT_RANGE}\"\n    fi\n\n    if [[ \"${REUSE_CERTS}\" != true ]]; then\n      # Create Certs\n      generate_certs\n    fi\n\n    cloud_config_arg=\"--cloud-provider=${CLOUD_PROVIDER} --cloud-config=${CLOUD_CONFIG}\"\n    if [[ \"${EXTERNAL_CLOUD_PROVIDER:-}\" == \"true\" ]]; then\n      cloud_config_arg=\"--cloud-provider=external\"\n    fi\n\n    if [[ -z \"${EGRESS_SELECTOR_CONFIG_FILE:-}\" ]]; then\n      cat <<EOF > /tmp/kube_egress_selector_configuration.yaml\napiVersion: apiserver.k8s.io/v1beta1\nkind: EgressSelectorConfiguration\negressSelections:\n- name: cluster\n  connection:\n    proxyProtocol: Direct\n- name: controlplane\n  connection:\n    proxyProtocol: Direct\n- name: etcd\n  connection:\n    proxyProtocol: Direct\nEOF\n      EGRESS_SELECTOR_CONFIG_FILE=\"/tmp/kube_egress_selector_configuration.yaml\"\n    fi\n\n    if [[ -z \"${AUDIT_POLICY_FILE}\" ]]; then\n      cat <<EOF > /tmp/kube-audit-policy-file\n# Log all requests at the Metadata level.\napiVersion: audit.k8s.io/v1\nkind: Policy\nrules:\n- level: Metadata\nEOF\n      AUDIT_POLICY_FILE=\"/tmp/kube-audit-policy-file\"\n    fi\n\n    APISERVER_LOG=${LOG_DIR}/kube-apiserver.log\n    # shellcheck disable=SC2086\n    ${CONTROLPLANE_SUDO} \"${GO_OUT}/kube-apiserver\" \"${authorizer_arg}\" \"${priv_arg}\" ${runtime_config} \\\n      ${cloud_config_arg} \\\n      \"${advertise_address}\" \\\n      \"${node_port_range}\" \\\n      --v=\"${LOG_LEVEL}\" \\\n      --vmodule=\"${LOG_SPEC}\" \\\n      --audit-policy-file=\"${AUDIT_POLICY_FILE}\" \\\n      --audit-log-path=\"${LOG_DIR}/kube-apiserver-audit.log\" \\\n      --authorization-webhook-config-file=\"${AUTHORIZATION_WEBHOOK_CONFIG_FILE}\" \\\n      --authentication-token-webhook-config-file=\"${AUTHENTICATION_WEBHOOK_CONFIG_FILE}\" \\\n      --cert-dir=\"${CERT_DIR}\" \\\n      --egress-selector-config-file=\"${EGRESS_SELECTOR_CONFIG_FILE:-}\" \\\n      --client-ca-file=\"${CERT_DIR}/client-ca.crt\" \\\n      --kubelet-client-certificate=\"${CERT_DIR}/client-kube-apiserver.crt\" \\\n      --kubelet-client-key=\"${CERT_DIR}/client-kube-apiserver.key\" \\\n      --service-account-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n      --service-account-lookup=\"${SERVICE_ACCOUNT_LOOKUP}\" \\\n      --service-account-issuer=\"https://kubernetes.default.svc\" \\\n      --service-account-jwks-uri=\"https://kubernetes.default.svc/openid/v1/jwks\" \\\n      --service-account-signing-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n      --enable-admission-plugins=\"${ENABLE_ADMISSION_PLUGINS}\" \\\n      --disable-admission-plugins=\"${DISABLE_ADMISSION_PLUGINS}\" \\\n      --admission-control-config-file=\"${ADMISSION_CONTROL_CONFIG_FILE}\" \\\n      --bind-address=\"${API_BIND_ADDR}\" \\\n      --secure-port=\"${API_SECURE_PORT}\" \\\n      --tls-cert-file=\"${CERT_DIR}/serving-kube-apiserver.crt\" \\\n      --tls-private-key-file=\"${CERT_DIR}/serving-kube-apiserver.key\" \\\n      --storage-backend=\"${STORAGE_BACKEND}\" \\\n      --storage-media-type=\"${STORAGE_MEDIA_TYPE}\" \\\n      --etcd-servers=\"http://${ETCD_HOST}:${ETCD_PORT}\" \\\n      --service-cluster-ip-range=\"${SERVICE_CLUSTER_IP_RANGE}\" \\\n      --feature-gates=\"${FEATURE_GATES}\" \\\n      --external-hostname=\"${EXTERNAL_HOSTNAME}\" \\\n      --requestheader-username-headers=X-Remote-User \\\n      --requestheader-group-headers=X-Remote-Group \\\n      --requestheader-extra-headers-prefix=X-Remote-Extra- \\\n      --requestheader-client-ca-file=\"${CERT_DIR}/request-header-ca.crt\" \\\n      --requestheader-allowed-names=system:auth-proxy \\\n      --proxy-client-cert-file=\"${CERT_DIR}/client-auth-proxy.crt\" \\\n      --proxy-client-key-file=\"${CERT_DIR}/client-auth-proxy.key\" \\\n      --cors-allowed-origins=\"${API_CORS_ALLOWED_ORIGINS}\" >\"${APISERVER_LOG}\" 2>&1 &\n    APISERVER_PID=$!\n\n    # Wait for kube-apiserver to come up before launching the rest of the components.\n    echo \"Waiting for apiserver to come up\"\n    kube::util::wait_for_url \"https://${API_HOST_IP}:${API_SECURE_PORT}/healthz\" \"apiserver: \" 1 \"${WAIT_FOR_URL_API_SERVER}\" \"${MAX_TIME_FOR_URL_API_SERVER}\" \\\n        || { echo \"check apiserver logs: ${APISERVER_LOG}\" ; exit 1 ; }\n\n    # Create kubeconfigs for all components, using client certs\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" admin\n    ${CONTROLPLANE_SUDO} chown \"${USER}\" \"${CERT_DIR}/client-admin.key\" # make readable for kubectl\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" controller\n    kube::util::write_client_kubeconfig \"${CONTROLPLANE_SUDO}\" \"${CERT_DIR}\" \"${ROOT_CA_FILE}\" \"${API_HOST}\" \"${API_SECURE_PORT}\" scheduler\n\n    if [[ -z \"${AUTH_ARGS}\" ]]; then\n        AUTH_ARGS=\"--client-key=${CERT_DIR}/client-admin.key --client-certificate=${CERT_DIR}/client-admin.crt\"\n    fi\n\n    # Grant apiserver permission to speak to the kubelet\n    ${KUBECTL} --kubeconfig \"${CERT_DIR}/admin.kubeconfig\" create clusterrolebinding kube-apiserver-kubelet-admin --clusterrole=system:kubelet-api-admin --user=kube-apiserver\n\n    # Grant kubelets permission to request client certificates\n    ${KUBECTL} --kubeconfig \"${CERT_DIR}/admin.kubeconfig\" create clusterrolebinding kubelet-csr --clusterrole=system:certificates.k8s.io:certificatesigningrequests:selfnodeclient --group=system:nodes\n\n    ${CONTROLPLANE_SUDO} cp \"${CERT_DIR}/admin.kubeconfig\" \"${CERT_DIR}/admin-kube-aggregator.kubeconfig\"\n    ${CONTROLPLANE_SUDO} chown \"$(whoami)\" \"${CERT_DIR}/admin-kube-aggregator.kubeconfig\"\n    ${KUBECTL} config set-cluster local-up-cluster --kubeconfig=\"${CERT_DIR}/admin-kube-aggregator.kubeconfig\" --server=\"https://${API_HOST_IP}:31090\"\n    echo \"use 'kubectl --kubeconfig=${CERT_DIR}/admin-kube-aggregator.kubeconfig' to use the aggregated API server\"\n\n}\n\nfunction start_controller_manager {\n    node_cidr_args=()\n    if [[ \"${NET_PLUGIN}\" == \"kubenet\" ]]; then\n      node_cidr_args=(\"--allocate-node-cidrs=true\" \"--cluster-cidr=${CLUSTER_CIDR}\")\n    fi\n\n    cloud_config_arg=(\"--cloud-provider=${CLOUD_PROVIDER}\" \"--cloud-config=${CLOUD_CONFIG}\")\n    if [[ \"${EXTERNAL_CLOUD_PROVIDER:-}\" == \"true\" ]]; then\n      cloud_config_arg=(\"--cloud-provider=external\")\n      cloud_config_arg+=(\"--external-cloud-volume-plugin=${EXTERNAL_CLOUD_VOLUME_PLUGIN}\")\n      cloud_config_arg+=(\"--cloud-config=${CLOUD_CONFIG}\")\n    fi\n\n    CTLRMGR_LOG=${LOG_DIR}/kube-controller-manager.log\n    ${CONTROLPLANE_SUDO} \"${GO_OUT}/kube-controller-manager\" \\\n      --v=\"${LOG_LEVEL}\" \\\n      --vmodule=\"${LOG_SPEC}\" \\\n      --service-account-private-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n      --service-cluster-ip-range=\"${SERVICE_CLUSTER_IP_RANGE}\" \\\n      --root-ca-file=\"${ROOT_CA_FILE}\" \\\n      --cluster-signing-cert-file=\"${CLUSTER_SIGNING_CERT_FILE}\" \\\n      --cluster-signing-key-file=\"${CLUSTER_SIGNING_KEY_FILE}\" \\\n      --enable-hostpath-provisioner=\"${ENABLE_HOSTPATH_PROVISIONER}\" \\\n      ${node_cidr_args[@]+\"${node_cidr_args[@]}\"} \\\n      --pvclaimbinder-sync-period=\"${CLAIM_BINDER_SYNC_PERIOD}\" \\\n      --feature-gates=\"${FEATURE_GATES}\" \\\n      \"${cloud_config_arg[@]}\" \\\n      --authentication-kubeconfig \"${CERT_DIR}\"/controller.kubeconfig \\\n      --authorization-kubeconfig \"${CERT_DIR}\"/controller.kubeconfig \\\n      --kubeconfig \"${CERT_DIR}\"/controller.kubeconfig \\\n      --use-service-account-credentials \\\n      --controllers=\"${KUBE_CONTROLLERS}\" \\\n      --leader-elect=false \\\n      --cert-dir=\"${CERT_DIR}\" \\\n      --master=\"https://${API_HOST}:${API_SECURE_PORT}\" >\"${CTLRMGR_LOG}\" 2>&1 &\n    CTLRMGR_PID=$!\n}\n\nfunction start_cloud_controller_manager {\n    if [ -z \"${CLOUD_CONFIG}\" ]; then\n      echo \"CLOUD_CONFIG cannot be empty!\"\n      exit 1\n    fi\n    if [ ! -f \"${CLOUD_CONFIG}\" ]; then\n      echo \"Cloud config ${CLOUD_CONFIG} doesn't exist\"\n      exit 1\n    fi\n\n    node_cidr_args=()\n    if [[ \"${NET_PLUGIN}\" == \"kubenet\" ]]; then\n      node_cidr_args=(\"--allocate-node-cidrs=true\" \"--cluster-cidr=${CLUSTER_CIDR}\")\n    fi\n\n    CLOUD_CTLRMGR_LOG=${LOG_DIR}/cloud-controller-manager.log\n    ${CONTROLPLANE_SUDO} \"${EXTERNAL_CLOUD_PROVIDER_BINARY:-\"${GO_OUT}/cloud-controller-manager\"}\" \\\n      --v=\"${LOG_LEVEL}\" \\\n      --vmodule=\"${LOG_SPEC}\" \\\n      \"${node_cidr_args[@]:-}\" \\\n      --feature-gates=\"${FEATURE_GATES}\" \\\n      --cloud-provider=\"${CLOUD_PROVIDER}\" \\\n      --cloud-config=\"${CLOUD_CONFIG}\" \\\n      --kubeconfig \"${CERT_DIR}\"/controller.kubeconfig \\\n      --use-service-account-credentials \\\n      --leader-elect=false \\\n      --master=\"https://${API_HOST}:${API_SECURE_PORT}\" >\"${CLOUD_CTLRMGR_LOG}\" 2>&1 &\n    export CLOUD_CTLRMGR_PID=$!\n}\n\nfunction wait_node_ready(){\n  # check the nodes information after kubelet daemon start\n  local nodes_stats=\"${KUBECTL} --kubeconfig '${CERT_DIR}/admin.kubeconfig' get nodes\"\n  local node_name=$HOSTNAME_OVERRIDE\n  local system_node_wait_time=60\n  local interval_time=2\n  kube::util::wait_for_success \"$system_node_wait_time\" \"$interval_time\" \"$nodes_stats | grep $node_name\"\n  if [ $? == \"1\" ]; then\n    echo \"time out on waiting $node_name info\"\n    exit 1\n  fi\n}\n\nfunction start_kubelet {\n    KUBELET_LOG=${LOG_DIR}/kubelet.log\n    mkdir -p \"${POD_MANIFEST_PATH}\" &>/dev/null || sudo mkdir -p \"${POD_MANIFEST_PATH}\"\n\n    cloud_config_arg=(\"--cloud-provider=${CLOUD_PROVIDER}\" \"--cloud-config=${CLOUD_CONFIG}\")\n    if [[ \"${EXTERNAL_CLOUD_PROVIDER:-}\" == \"true\" ]]; then\n       cloud_config_arg=(\"--cloud-provider=external\")\n       if [[ \"${CLOUD_PROVIDER:-}\" == \"aws\" ]]; then\n         cloud_config_arg+=(\"--provider-id=$(curl http://169.254.169.254/latest/meta-data/instance-id)\")\n       else\n         cloud_config_arg+=(\"--provider-id=${KUBELET_PROVIDER_ID}\")\n       fi\n    fi\n\n    mkdir -p \"/var/lib/kubelet\" &>/dev/null || sudo mkdir -p \"/var/lib/kubelet\"\n    net_plugin_args=()\n    if [[ -n \"${NET_PLUGIN}\" ]]; then\n      net_plugin_args=(\"--network-plugin=${NET_PLUGIN}\")\n    fi\n\n    cni_conf_dir_args=()\n    if [[ -n \"${CNI_CONF_DIR}\" ]]; then\n      cni_conf_dir_args=(\"--cni-conf-dir=${CNI_CONF_DIR}\")\n    fi\n\n    cni_bin_dir_args=()\n    if [[ -n \"${CNI_BIN_DIR}\" ]]; then\n      cni_bin_dir_args=(\"--cni-bin-dir=${CNI_BIN_DIR}\")\n    fi\n\n    container_runtime_endpoint_args=()\n    if [[ -n \"${CONTAINER_RUNTIME_ENDPOINT}\" ]]; then\n      container_runtime_endpoint_args=(\"--container-runtime-endpoint=${CONTAINER_RUNTIME_ENDPOINT}\")\n    fi\n\n    image_service_endpoint_args=()\n    if [[ -n \"${IMAGE_SERVICE_ENDPOINT}\" ]]; then\n      image_service_endpoint_args=(\"--image-service-endpoint=${IMAGE_SERVICE_ENDPOINT}\")\n    fi\n\n    # shellcheck disable=SC2206\n    all_kubelet_flags=(\n      \"--v=${LOG_LEVEL}\"\n      \"--vmodule=${LOG_SPEC}\"\n      \"--container-runtime=${CONTAINER_RUNTIME}\"\n      \"--hostname-override=${HOSTNAME_OVERRIDE}\"\n      \"${cloud_config_arg[@]}\"\n      \"--bootstrap-kubeconfig=${CERT_DIR}/kubelet.kubeconfig\"\n      \"--kubeconfig=${CERT_DIR}/kubelet-rotated.kubeconfig\"\n      ${cni_conf_dir_args[@]+\"${cni_conf_dir_args[@]}\"}\n      ${cni_bin_dir_args[@]+\"${cni_bin_dir_args[@]}\"}\n      ${net_plugin_args[@]+\"${net_plugin_args[@]}\"}\n      ${container_runtime_endpoint_args[@]+\"${container_runtime_endpoint_args[@]}\"}\n      ${image_service_endpoint_args[@]+\"${image_service_endpoint_args[@]}\"}\n      ${KUBELET_FLAGS}\n    )\n\n    # warn if users are running with swap allowed\n    if [ \"${FAIL_SWAP_ON}\" == \"false\" ]; then\n        echo \"WARNING : The kubelet is configured to not fail even if swap is enabled; production deployments should disable swap.\"\n    fi\n\n    if [[ \"${REUSE_CERTS}\" != true ]]; then\n        # clear previous dynamic certs\n        sudo rm -fr \"/var/lib/kubelet/pki\" \"${CERT_DIR}/kubelet-rotated.kubeconfig\"\n        # create new certs\n        generate_kubelet_certs\n    fi\n\n    cat <<EOF > /tmp/kubelet.yaml\napiVersion: kubelet.config.k8s.io/v1beta1\nkind: KubeletConfiguration\naddress: \"${KUBELET_HOST}\"\ncgroupDriver: \"${CGROUP_DRIVER}\"\ncgroupRoot: \"${CGROUP_ROOT}\"\ncgroupsPerQOS: ${CGROUPS_PER_QOS}\ncpuCFSQuota: ${CPU_CFS_QUOTA}\nenableControllerAttachDetach: ${ENABLE_CONTROLLER_ATTACH_DETACH}\nevictionPressureTransitionPeriod: \"${EVICTION_PRESSURE_TRANSITION_PERIOD}\"\nfailSwapOn: ${FAIL_SWAP_ON}\nport: ${KUBELET_PORT}\nreadOnlyPort: ${KUBELET_READ_ONLY_PORT}\nrotateCertificates: true\nruntimeRequestTimeout: \"${RUNTIME_REQUEST_TIMEOUT}\"\nstaticPodPath: \"${POD_MANIFEST_PATH}\"\nEOF\n    {\n      # authentication\n      echo \"authentication:\"\n      echo \"  webhook:\"\n      if [[ \"${KUBELET_AUTHENTICATION_WEBHOOK:-}\" != \"false\" ]]; then\n        echo \"    enabled: true\"\n      else\n        echo \"    enabled: false\"\n      fi\n      echo \"  x509:\"\n      if [[ -n \"${CLIENT_CA_FILE:-}\" ]]; then\n        echo \"    clientCAFile: \\\"${CLIENT_CA_FILE}\\\"\"\n      else\n        echo \"    clientCAFile: \\\"${CERT_DIR}/client-ca.crt\\\"\"\n      fi\n\n      # authorization\n      if [[ \"${KUBELET_AUTHORIZATION_WEBHOOK:-}\" != \"false\" ]]; then\n        echo \"authorization:\"\n        echo \"  mode: Webhook\"\n      fi\n\n      # dns\n      if [[ \"${ENABLE_CLUSTER_DNS}\" = true ]]; then\n        if [[ \"${ENABLE_NODELOCAL_DNS:-}\" == \"true\" ]]; then\n          echo \"clusterDNS: [ \\\"${LOCAL_DNS_IP}\\\" ]\"\n        else\n          echo \"clusterDNS: [ \\\"${DNS_SERVER_IP}\\\" ]\"\n        fi\n        echo \"clusterDomain: \\\"${DNS_DOMAIN}\\\"\"\n      else\n        # To start a private DNS server set ENABLE_CLUSTER_DNS and\n        # DNS_SERVER_IP/DOMAIN. This will at least provide a working\n        # DNS server for real world hostnames.\n        echo \"clusterDNS: [ \\\"8.8.8.8\\\" ]\"\n      fi\n\n      # eviction\n      if [[ -n ${EVICTION_HARD} ]]; then\n        echo \"evictionHard:\"\n        parse_eviction \"${EVICTION_HARD}\"\n      fi\n      if [[ -n ${EVICTION_SOFT} ]]; then\n        echo \"evictionSoft:\"\n        parse_eviction \"${EVICTION_SOFT}\"\n      fi\n\n      # feature gate\n      if [[ -n ${FEATURE_GATES} ]]; then\n        parse_feature_gates \"${FEATURE_GATES}\"\n      fi\n    } >>/tmp/kubelet.yaml\n\n    # shellcheck disable=SC2024\n    sudo -E \"${GO_OUT}/kubelet\" \"${all_kubelet_flags[@]}\" \\\n      --config=/tmp/kubelet.yaml >\"${KUBELET_LOG}\" 2>&1 &\n    KUBELET_PID=$!\n\n    # Quick check that kubelet is running.\n    if [ -n \"${KUBELET_PID}\" ] && ps -p ${KUBELET_PID} > /dev/null; then\n      echo \"kubelet ( ${KUBELET_PID} ) is running.\"\n    else\n      cat \"${KUBELET_LOG}\" ; exit 1\n    fi\n}\n\nfunction start_kubeproxy {\n    PROXY_LOG=${LOG_DIR}/kube-proxy.log\n\n    if [[ \"${START_MODE}\" != \"nokubelet\" ]]; then\n      # wait for kubelet collect node information\n      echo \"wait kubelet ready\"\n      wait_node_ready\n    fi\n\n    cat <<EOF > /tmp/kube-proxy.yaml\napiVersion: kubeproxy.config.k8s.io/v1alpha1\nkind: KubeProxyConfiguration\nclientConnection:\n  kubeconfig: ${CERT_DIR}/kube-proxy.kubeconfig\nhostnameOverride: ${HOSTNAME_OVERRIDE}\nmode: ${KUBE_PROXY_MODE}\nconntrack:\n# Skip setting sysctl value \"net.netfilter.nf_conntrack_max\"\n  maxPerCore: 0\n# Skip setting \"net.netfilter.nf_conntrack_tcp_timeout_established\"\n  tcpEstablishedTimeout: 0s\n# Skip setting \"net.netfilter.nf_conntrack_tcp_timeout_close\"\n  tcpCloseWaitTimeout: 0s\nEOF\n    if [[ -n ${FEATURE_GATES} ]]; then\n      parse_feature_gates \"${FEATURE_GATES}\"\n    fi >>/tmp/kube-proxy.yaml\n\n    if [[ \"${NET_PLUGIN}\" == \"kubenet\" && -n ${CLUSTER_CIDR} ]]; then\n        echo \"clusterCIDR: \\\"${CLUSTER_CIDR}\\\"\" >> /tmp/kube-proxy.yaml\n    fi\n\n    if [[ \"${REUSE_CERTS}\" != true ]]; then\n        generate_kubeproxy_certs\n    fi\n\n    # shellcheck disable=SC2024\n    sudo \"${GO_OUT}/kube-proxy\" \\\n      --v=\"${LOG_LEVEL}\" \\\n      --config=/tmp/kube-proxy.yaml \\\n      --master=\"https://${API_HOST}:${API_SECURE_PORT}\" >\"${PROXY_LOG}\" 2>&1 &\n    PROXY_PID=$!\n}\n\nfunction start_kubescheduler {\n    SCHEDULER_LOG=${LOG_DIR}/kube-scheduler.log\n\n    cat <<EOF > /tmp/kube-scheduler.yaml\napiVersion: kubescheduler.config.k8s.io/v1beta1\nkind: KubeSchedulerConfiguration\nclientConnection:\n  kubeconfig: ${CERT_DIR}/scheduler.kubeconfig\nleaderElection:\n  leaderElect: false\nEOF\n    ${CONTROLPLANE_SUDO} \"${GO_OUT}/kube-scheduler\" \\\n      --v=\"${LOG_LEVEL}\" \\\n      --config=/tmp/kube-scheduler.yaml \\\n      --feature-gates=\"${FEATURE_GATES}\" \\\n      --authentication-kubeconfig \"${CERT_DIR}\"/scheduler.kubeconfig \\\n      --authorization-kubeconfig \"${CERT_DIR}\"/scheduler.kubeconfig \\\n      --master=\"https://${API_HOST}:${API_SECURE_PORT}\" >\"${SCHEDULER_LOG}\" 2>&1 &\n    SCHEDULER_PID=$!\n}\n\nfunction start_dns_addon {\n    if [[ \"${ENABLE_CLUSTER_DNS}\" = true ]]; then\n        cp \"${KUBE_ROOT}/cluster/addons/dns/${DNS_ADDON}/${DNS_ADDON}.yaml.in\" dns.yaml\n        ${SED} -i -e \"s/dns_domain/${DNS_DOMAIN}/g\" dns.yaml\n        ${SED} -i -e \"s/dns_server/${DNS_SERVER_IP}/g\" dns.yaml\n        ${SED} -i -e \"s/dns_memory_limit/${DNS_MEMORY_LIMIT}/g\" dns.yaml\n        # TODO update to dns role once we have one.\n        # use kubectl to create dns addon\n        if ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" --namespace=kube-system create -f dns.yaml ; then\n            echo \"${DNS_ADDON} addon successfully deployed.\"\n        else\n\t\techo \"Something is wrong with your DNS input\"\n\t\tcat dns.yaml\n\t\texit 1\n        fi\n        rm dns.yaml\n    fi\n}\n\nfunction start_nodelocaldns {\n  cp \"${KUBE_ROOT}/cluster/addons/dns/nodelocaldns/nodelocaldns.yaml\" nodelocaldns.yaml\n  # eventually all the __PILLAR__ stuff will be gone, but theyre still in nodelocaldns for backward compat.\n  ${SED} -i -e \"s/__PILLAR__DNS__DOMAIN__/${DNS_DOMAIN}/g\" nodelocaldns.yaml\n  ${SED} -i -e \"s/__PILLAR__DNS__SERVER__/${DNS_SERVER_IP}/g\" nodelocaldns.yaml\n  ${SED} -i -e \"s/__PILLAR__LOCAL__DNS__/${LOCAL_DNS_IP}/g\" nodelocaldns.yaml\n\n  # use kubectl to create nodelocaldns addon\n  ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" --namespace=kube-system create -f nodelocaldns.yaml\n  echo \"NodeLocalDNS addon successfully deployed.\"\n  rm nodelocaldns.yaml\n}\n\nfunction start_kubedashboard {\n    if [[ \"${ENABLE_CLUSTER_DASHBOARD}\" = true ]]; then\n        echo \"Creating kubernetes-dashboard\"\n        # use kubectl to create the dashboard\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/dashboard/dashboard.yaml\"\n        echo \"kubernetes-dashboard deployment and service successfully deployed.\"\n    fi\n}\n\nfunction start_csi_snapshotter {\n    if [[ \"${ENABLE_CSI_SNAPSHOTTER}\" = true ]]; then\n        echo \"Creating Kubernetes-CSI snapshotter\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/volumesnapshots/crd/snapshot.storage.k8s.io_volumesnapshots.yaml\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/volumesnapshots/crd/snapshot.storage.k8s.io_volumesnapshotclasses.yaml\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/volumesnapshots/crd/snapshot.storage.k8s.io_volumesnapshotcontents.yaml\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/volumesnapshots/volume-snapshot-controller/rbac-volume-snapshot-controller.yaml\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" apply -f \"${KUBE_ROOT}/cluster/addons/volumesnapshots/volume-snapshot-controller/volume-snapshot-controller-deployment.yaml\"\n\n        echo \"Kubernetes-CSI snapshotter successfully deployed.\"\n    fi\n}\n\nfunction create_psp_policy {\n    echo \"Create podsecuritypolicy policies for RBAC.\"\n    ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" create -f \"${KUBE_ROOT}/examples/podsecuritypolicy/rbac/policies.yaml\"\n    ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" create -f \"${KUBE_ROOT}/examples/podsecuritypolicy/rbac/roles.yaml\"\n    ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" create -f \"${KUBE_ROOT}/examples/podsecuritypolicy/rbac/bindings.yaml\"\n}\n\nfunction create_storage_class {\n    if [ -z \"${CLOUD_PROVIDER}\" ]; then\n        CLASS_FILE=${KUBE_ROOT}/cluster/addons/storage-class/local/default.yaml\n    else\n        CLASS_FILE=${KUBE_ROOT}/cluster/addons/storage-class/${CLOUD_PROVIDER}/default.yaml\n    fi\n\n    if [ -e \"${CLASS_FILE}\" ]; then\n        echo \"Create default storage class for ${CLOUD_PROVIDER}\"\n        ${KUBECTL} --kubeconfig=\"${CERT_DIR}/admin.kubeconfig\" create -f \"${CLASS_FILE}\"\n    else\n        echo \"No storage class available for ${CLOUD_PROVIDER}.\"\n    fi\n}\n\nfunction print_success {\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  if [[ \"${ENABLE_DAEMON}\" = false ]]; then\n    echo \"Local Kubernetes cluster is running. Press Ctrl-C to shut it down.\"\n  else\n    echo \"Local Kubernetes cluster is running.\"\n  fi\n  cat <<EOF\n\nLogs:\n  ${APISERVER_LOG:-}\n  ${CTLRMGR_LOG:-}\n  ${CLOUD_CTLRMGR_LOG:-}\n  ${PROXY_LOG:-}\n  ${SCHEDULER_LOG:-}\nEOF\nfi\n\nif [[ \"${START_MODE}\" == \"all\" ]]; then\n  echo \"  ${KUBELET_LOG}\"\nelif [[ \"${START_MODE}\" == \"nokubelet\" ]]; then\n  echo\n  echo \"No kubelet was started because you set START_MODE=nokubelet\"\n  echo \"Run this script again with START_MODE=kubeletonly to run a kubelet\"\nfi\n\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  echo\n  if [[ \"${ENABLE_DAEMON}\" = false ]]; then\n    echo \"To start using your cluster, you can open up another terminal/tab and run:\"\n  else\n    echo \"To start using your cluster, run:\"\n  fi\n  cat <<EOF\n\n  export KUBECONFIG=${CERT_DIR}/admin.kubeconfig\n  cluster/kubectl.sh\n\nAlternatively, you can write to the default kubeconfig:\n\n  export KUBERNETES_PROVIDER=local\n\n  cluster/kubectl.sh config set-cluster local --server=https://${API_HOST}:${API_SECURE_PORT} --certificate-authority=${ROOT_CA_FILE}\n  cluster/kubectl.sh config set-credentials myself ${AUTH_ARGS}\n  cluster/kubectl.sh config set-context local --cluster=local --user=myself\n  cluster/kubectl.sh config use-context local\n  cluster/kubectl.sh\nEOF\nelse\n  cat <<EOF\nThe kubelet was started.\n\nLogs:\n  ${KUBELET_LOG}\nEOF\nfi\n}\n\nfunction parse_feature_gates {\n  echo \"featureGates:\"\n  # Convert from foo=true,bar=false to\n  #   foo: true\n  #   bar: false\n  for gate in $(echo \"$1\" | tr ',' ' '); do\n    echo \"${gate}\" | ${SED} -e 's/\\(.*\\)=\\(.*\\)/  \\1: \\2/'\n  done\n}\n\nfunction parse_eviction {\n  # Convert from memory.available<100Mi,nodefs.available<10%,nodefs.inodesFree<5% to\n  #   memory.available: \"100Mi\"\n  #   nodefs.available: \"10%\"\n  #   nodefs.inodesFree: \"5%\"\n  for eviction in $(echo \"$1\" | tr ',' ' '); do\n    echo \"${eviction}\" | ${SED} -e 's/</: \\\"/' | ${SED} -e 's/^/  /' | ${SED} -e 's/$/\\\"/'\n  done\n}\n\n# If we are running in the CI, we need a few more things before we can start\nif [[ \"${KUBETEST_IN_DOCKER:-}\" == \"true\" ]]; then\n  echo \"Preparing to test ...\"\n  \"${KUBE_ROOT}\"/hack/install-etcd.sh\n  export PATH=\"${KUBE_ROOT}/third_party/etcd:${PATH}\"\n  KUBE_FASTBUILD=true make ginkgo cross\n\n  apt-get update && apt-get install -y sudo\n  apt-get remove -y systemd\n\n  # configure shared mounts to prevent failure in DIND scenarios\n  mount --make-rshared /\n\n  # kubekins has a special directory for docker root\n  DOCKER_ROOT=\"/docker-graph\"\nfi\n\n# validate that etcd is: not running, in path, and has minimum required version.\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  kube::etcd::validate\nfi\n\nif [ \"${CONTAINER_RUNTIME}\" == \"docker\" ]; then\n  if ! kube::util::ensure_docker_daemon_connectivity; then\n    exit 1\n  else\n    # docker doesn't allow to reach exposed hostPorts from the node, however, Kubernetes does\n    # so we append a new rule on top of the docker one\n    # -A OUTPUT ! -d 127.0.0.0/8 -m addrtype --dst-type LOCAL -j DOCKER  <-- docker rule\n    if ! iptables -t nat -C OUTPUT -m addrtype --dst-type LOCAL -j DOCKER; then\n      iptables -t nat -A OUTPUT -m addrtype --dst-type LOCAL -j DOCKER\n    fi\n  fi\nfi\n\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  test_apiserver_off\nfi\n\nkube::util::test_openssl_installed\nkube::util::ensure-cfssl\n\n### IF the user didn't supply an output/ for the build... Then we detect.\nif [ \"${GO_OUT}\" == \"\" ]; then\n  detect_binary\nfi\necho \"Detected host and ready to start services.  Doing some housekeeping first...\"\necho \"Using GO_OUT ${GO_OUT}\"\nexport KUBELET_CIDFILE=/tmp/kubelet.cid\nif [[ \"${ENABLE_DAEMON}\" = false ]]; then\n  trap cleanup EXIT\nfi\n\necho \"Starting services now!\"\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  start_etcd\n  set_service_accounts\n  start_apiserver\n  start_controller_manager\n  if [[ \"${EXTERNAL_CLOUD_PROVIDER:-}\" == \"true\" ]]; then\n    start_cloud_controller_manager\n  fi\n  start_kubescheduler\n  start_dns_addon\n  if [[ \"${ENABLE_NODELOCAL_DNS:-}\" == \"true\" ]]; then\n    start_nodelocaldns\n  fi\n  start_kubedashboard\n  start_csi_snapshotter\nfi\n\nif [[ \"${START_MODE}\" != \"nokubelet\" ]]; then\n  ## TODO remove this check if/when kubelet is supported on darwin\n  # Detect the OS name/arch and display appropriate error.\n    case \"$(uname -s)\" in\n      Darwin)\n        print_color \"kubelet is not currently supported in darwin, kubelet aborted.\"\n        KUBELET_LOG=\"\"\n        ;;\n      Linux)\n        start_kubelet\n        ;;\n      *)\n        print_color \"Unsupported host OS.  Must be Linux or Mac OS X, kubelet aborted.\"\n        ;;\n    esac\nfi\n\nif [[ \"${START_MODE}\" != \"kubeletonly\" ]]; then\n  if [[ \"${START_MODE}\" != \"nokubeproxy\" ]]; then\n    start_kubeproxy\n  fi\nfi\nif [[ -n \"${PSP_ADMISSION}\" && \"${AUTHORIZATION_MODE}\" = *RBAC* ]]; then\n  create_psp_policy\nfi\n\nif [[ \"${DEFAULT_STORAGE_CLASS}\" = \"true\" ]]; then\n  create_storage_class\nfi\n\nprint_success\n\nif [[ \"${ENABLE_DAEMON}\" = false ]]; then\n  while true; do sleep 1; healthcheck; done\nfi\n\nif [[ \"${KUBETEST_IN_DOCKER:-}\" == \"true\" ]]; then\n  cluster/kubectl.sh config set-cluster local --server=https://localhost:6443 --certificate-authority=/var/run/kubernetes/server-ca.crt\n  cluster/kubectl.sh config set-credentials myself --client-key=/var/run/kubernetes/client-admin.key --client-certificate=/var/run/kubernetes/client-admin.crt\n  cluster/kubectl.sh config set-context local --cluster=local --user=myself\n  cluster/kubectl.sh config use-context local\nfi\n", "num_lines": 1214}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates a jpg image of our internal dependency graph.\n# It relies on go mod and dot to do so and should be run from K8s root.\n# TODO: Containerize the script to remove dependency issues with go mod and dot.\n\n# To generate graph with all Kubernetes modules run\n# ./hack/module-graph.sh\n# To generate graph with just staging modules run\n# ./hack/module-graph.sh staging\n\nerror_exit()\n{\n\techo \"$1\" 1>&2\n\texit 1\n}\n\nstaging_dependencies()\n{\n\trelevant_modules=\"(k8s.io/kubernetes|$(find staging/src/k8s.io -maxdepth 1 -mindepth 1 | sed -E 's|staging/src/k8s.io|k8s.io|g' | tr '\\n' '|' | sed 's#|$##' ))\"\n\t# Generating lines of the form \" k8s_io_kubernetes -> k8s_io_api\"\n\t# Use only the directories in staging\n\t# Trimming away version info\n\t# Replacing non DOT (graph description language) characters with underscores\n\t# Dedupe lines\n\t# Inserting needed arrow.\n\t# Indenting the line appropriately\n\tgo mod graph | grep -E \"^${relevant_modules}(@.*| )${relevant_modules}@.*$\" | sed -E 's|@\\S+ | |g' | sed -E 's|@\\S+$||g' | sed -E 's/[\\.\\/\\-]/_/g' | sort | uniq | sed -E 's| | -> |g' | sed -E 's|^|    |g' >> _output/module-dependencies.dot || error_exit \"Failed to generate staging dependencies in DOT file\"\n}\n\nkubernetes_dependencies()\n{\n\t# Generating lines of the form \" k8s_io_kubernetes -> k8s_io_api\"\n\t# Excluding all non Kubernetes dependencies\n\t# Trimming away version info\n\t# Replacing non DOT (graph description language) characters with underscores\n\t# Dedupe lines\n\t# Inserting needed arrow.\n\t# Indenting the line appropriately\n\tgo mod graph | grep -E \"^.*k8s.io.*k8s.io.*$\" | sed -E 's|@\\S+ | |g' | sed -E 's|@\\S+$||g' | sed -E 's/[\\.\\/\\-]/_/g' | sort | uniq | sed -E 's| | -> |g' | sed -E 's|^|    |g' >> _output/module-dependencies.dot || error_exit \"Failed to generate kubernetes dependencies in DOT file\"\n}\n\nmkdir -p _output\necho \"digraph module_dependencies {\" > _output/module-dependencies.dot || error_exit \"Failed to open DOT file\"\nif [[ -n \"$1\" && $1 == \"staging\" ]]; then\n\techo \"Generating just staging modules\"\n\tstaging_dependencies\nelse\n\techo \"Generating all Kubernetes modules\"\n\tkubernetes_dependencies\nfi\necho \"}\" >> _output/module-dependencies.dot || error_exit \"Failed to close DOT file\"\ndot -Gratio=1,1 -Nwidth=2 -Nheight=2 -Nfontsize=48 -Earrowsize=8 -Tjpg _output/module-dependencies.dot -o _output/module-dependencies.jpg || error_exit \"Failed to generate graph from DOT file\"\n", "num_lines": 68}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script switches to the preferred version for specified module.\n# Usage: `hack/pin-dependency.sh $MODULE $SHA-OR-TAG`.\n# Example: `hack/pin-dependency.sh github.com/docker/docker 501cb131a7b7`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Explicitly opt into go modules, even though we're inside a GOPATH directory\nexport GO111MODULE=on\n# Explicitly set GOFLAGS to ignore vendor, since GOFLAGS=-mod=vendor breaks dependency resolution while rebuilding vendor\nexport GOFLAGS=-mod=mod\n# Detect problematic GOPROXY settings that prevent lookup of dependencies\nif [[ \"${GOPROXY:-}\" == \"off\" ]]; then\n  kube::log::error \"Cannot run with \\$GOPROXY=off\"\n  exit 1\nfi\n\nkube::golang::verify_go_version\nkube::util::require-jq\n\ndep=\"${1:-}\"\nsha=\"${2:-}\"\nif [[ -z \"${dep}\" || -z \"${sha}\" ]]; then\n  echo \"Usage:\"\n  echo \"  hack/pin-dependency.sh \\$MODULE \\$SHA-OR-TAG\"\n  echo \"\"\n  echo \"Example:\"\n  echo \"  hack/pin-dependency.sh github.com/docker/docker 501cb131a7b7\"\n  echo \"\"\n  exit 1\nfi\n\n_tmp=\"${KUBE_ROOT}/_tmp\"\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\ncleanup\nmkdir -p \"${_tmp}\"\n\n# Add the require directive\necho \"Running: go get ${dep}@${sha}\"\ngo get -d \"${dep}@${sha}\"\n\n# Find the resolved version\nrev=$(go mod edit -json | jq -r \".Require[] | select(.Path == \\\"${dep}\\\") | .Version\")\n\n# No entry in go.mod, we must be using the natural version indirectly\nif [[ -z \"${rev}\" ]]; then\n  # backup the go.mod file, since go list modifies it\n  cp go.mod \"${_tmp}/go.mod.bak\"\n  # find the revision\n  rev=$(go list -m -json \"${dep}\" | jq -r .Version)\n  # restore the go.mod file\n  mv \"${_tmp}/go.mod.bak\" go.mod\nfi\n\n# No entry found\nif [[ -z \"${rev}\" ]]; then\n  echo \"Could not resolve ${sha}\"\n  exit 1\nfi\n\necho \"Resolved to ${dep}@${rev}\"\n\n# Add the replace directive\necho \"Running: go mod edit -replace ${dep}=${dep}@${rev}\"\ngo mod edit -replace \"${dep}=${dep}@${rev}\"\n\n# Propagate pinned version to staging repos that also have that dependency\nfor repo in $(kube::util::list_staging_repos); do\n  pushd \"staging/src/k8s.io/${repo}\" >/dev/null 2>&1\n    if go mod edit -json | jq -e -r \".Require[] | select(.Path == \\\"${dep}\\\")\" > /dev/null 2>&1; then\n      go mod edit -require \"${dep}@${rev}\"\n      go mod edit -replace \"${dep}=${dep}@${rev}\"\n    fi\n  popd >/dev/null 2>&1\ndone\n\necho \"\"\necho \"Run hack/update-vendor.sh to rebuild the vendor directory\"\n", "num_lines": 102}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script was used by bazel as the workspace_status_command to implement\n# build stamping with git information.\n#\n# It is still useful for obtaining kube::version::get_version_vars without\n# sourcing Kubernetes build internals.\n#\n# Usage: `hack/print-workspace-status.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nsource \"${KUBE_ROOT}/hack/lib/version.sh\"\nkube::version::get_version_vars\n\n# Prefix with STABLE_ so that these values are saved to stable-status.txt\n# instead of volatile-status.txt.\n# Stamped rules will be retriggered by changes to stable-status.txt, but not by\n# changes to volatile-status.txt.\n# IMPORTANT: the camelCase vars should match the lists in hack/lib/version.sh\n# and staging/src/k8s.io/kubectl/pkg/version/def.bzl.\ncat <<EOF\nSTABLE_BUILD_GIT_COMMIT ${KUBE_GIT_COMMIT-}\nSTABLE_BUILD_SCM_STATUS ${KUBE_GIT_TREE_STATE-}\nSTABLE_BUILD_SCM_REVISION ${KUBE_GIT_VERSION-}\nSTABLE_BUILD_MAJOR_VERSION ${KUBE_GIT_MAJOR-}\nSTABLE_BUILD_MINOR_VERSION ${KUBE_GIT_MINOR-}\nSTABLE_DOCKER_TAG ${KUBE_GIT_VERSION/+/_}\nSTABLE_DOCKER_REGISTRY ${KUBE_DOCKER_REGISTRY:-k8s.gcr.io}\nSTABLE_DOCKER_PUSH_REGISTRY ${KUBE_DOCKER_PUSH_REGISTRY:-${KUBE_DOCKER_REGISTRY:-staging-k8s.gcr.io}}\ngitCommit ${KUBE_GIT_COMMIT-}\ngitTreeState ${KUBE_GIT_TREE_STATE-}\ngitVersion ${KUBE_GIT_VERSION-}\ngitMajor ${KUBE_GIT_MAJOR-}\ngitMinor ${KUBE_GIT_MINOR-}\nbuildDate $(date \\\n  ${SOURCE_DATE_EPOCH:+\"--date=@${SOURCE_DATE_EPOCH}\"} \\\n -u +'%Y-%m-%dT%H:%M:%SZ')\nEOF\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script sets up a temporary Kubernetes GOPATH and runs an arbitrary\n# command under it. Go tooling requires that the current directory be under\n# GOPATH or else it fails to find some things, such as the vendor directory for\n# the project.\n# Usage: `hack/run-in-gopath.sh <command>`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# This sets up a clean GOPATH and makes sure we are currently in it.\nkube::golang::setup_env\n\n# Run the user-provided command.\n\"${@}\"\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs all *_test.go files. It is equivalent to `make test`.\n# Usage: `hack/test-go.sh` or `make test`.\n# Note: This script is a vestigial redirection. Please do not add \"real\" logic.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# For help output\nARGHELP=\"\"\nif [[ \"$#\" -gt 0 ]]; then\n    ARGHELP=\"WHAT='$*'\"\nfi\n\necho \"NOTE: $0 has been replaced by 'make test'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make test ${ARGHELP}\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" test WHAT=\"$*\"\n", "num_lines": 40}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script has been replaced by `make test-integration`.\n# `make test-integration` runs all integration tests.\n# Usage: `make test-integration`.\n# Note: This script is a vestigial redirection. Please do not add \"real\" logic.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\necho \"$0 has been replaced by 'make test-integration'\"\necho\necho \"The following invocation will run all integration tests: \"\necho '    make test-integration'\necho\necho \"The following invocation will run a specific test with the verbose flag set: \"\necho '    make test-integration WHAT=./test/integration/pods GOFLAGS=\"-v\" KUBE_TEST_ARGS=\"-run ^TestPodUpdateActiveDeadlineSeconds$\"'\necho\nexit 1\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is a vestigial redirection.  Please do not add \"real\" logic.\n# The \"true\" target of this makerule is `hack/make-rules/update.sh`.\n# We should run `hack/update-all.sh` if anything fails after\n# running `hack/verify-all.sh`. It is equivalent to `make update`.\n# Usage: `hack/update-all.sh` or `make update`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\necho \"NOTE: $0 has been replaced by 'make update'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make update\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" update\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# delete all bazel related files not in vendor/\nfind \"${KUBE_ROOT}\" \\\n  \\( \\\n    -name BUILD \\\n    -o -name BUILD.bazel \\\n    -o -name '*.bzl' \\\n  \\) \\\n  -not \\\n  \\( \\\n    -path \"${KUBE_ROOT}\"'/vendor*' \\\n  \\) \\\n  -delete\n\n# remove additional one-off bazel related files\n# NOTE: most of these will be pairs of symlinked location in \"${KUBE_ROOT}/\"\n# and the actual location in \"${KUBE_ROOT}/build/root/\"\nrm -f \\\n  \"${KUBE_ROOT}/build/root/BUILD.root\" \\\n  \"${KUBE_ROOT}/WORKSPACE\" \\\n  \"${KUBE_ROOT}/build/root/WORKSPACE\" \\\n  \"${KUBE_ROOT}/.bazelrc\" \\\n  \"${KUBE_ROOT}/build/root/.bazelrc\" \\\n  \"${KUBE_ROOT}/.bazelversion\" \\\n  \"${KUBE_ROOT}/build/root/.bazelversion\" \\\n  \"${KUBE_ROOT}/.kazelcfg.json\" \\\n  \"${KUBE_ROOT}/build/root/.kazelcfg.json\"\n\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Please do not add any logic to this shell script. Add logic to the go code\n# that generates the set-gen program.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\ngo install k8s.io/kubernetes/pkg/generated/openapi/cmd/models-schema\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/client-gen\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/lister-gen\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/informer-gen\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/applyconfiguration-gen\n\nmodelsschema=$(kube::util::find-binary \"models-schema\")\nclientgen=$(kube::util::find-binary \"client-gen\")\nlistergen=$(kube::util::find-binary \"lister-gen\")\ninformergen=$(kube::util::find-binary \"informer-gen\")\napplyconfigurationgen=$(kube::util::find-binary \"applyconfiguration-gen\")\n\nIFS=\" \" read -r -a GROUP_VERSIONS <<< \"${KUBE_AVAILABLE_GROUP_VERSIONS}\"\nGV_DIRS=()\nfor gv in \"${GROUP_VERSIONS[@]}\"; do\n  # add items, but strip off any leading apis/ you find to match command expectations\n  api_dir=$(kube::util::group-version-to-pkg-path \"${gv}\")\n  nopkg_dir=${api_dir#pkg/}\n  nopkg_dir=${nopkg_dir#vendor/k8s.io/api/}\n  pkg_dir=${nopkg_dir#apis/}\n\n\n  # skip groups that aren't being served, clients for these don't matter\n  if [[ \" ${KUBE_NONSERVER_GROUP_VERSIONS} \" == *\" ${gv} \"* ]]; then\n    continue\n  fi\n\n  GV_DIRS+=(\"${pkg_dir}\")\ndone\n# delimit by commas for the command\nGV_DIRS_CSV=$(IFS=',';echo \"${GV_DIRS[*]// /,}\";IFS=$)\n\napplyconfigurationgen_external_apis=()\n# because client-gen doesn't do policy/v1alpha1, we have to skip it too\nkube::util::read-array applyconfigurationgen_external_apis < <(\n  cd \"${KUBE_ROOT}/staging/src\"\n  find k8s.io/api -name types.go -print0 | xargs -0 -n1 dirname | sort | grep -v pkg.apis.policy.v1alpha1\n)\napplyconfigurationgen_external_apis+=(\"k8s.io/apimachinery/pkg/apis/meta/v1\")\napplyconfigurationgen_external_apis_csv=$(IFS=,; echo \"${applyconfigurationgen_external_apis[*]}\")\napplyconfigurations_package=\"k8s.io/client-go/applyconfigurations\"\n${applyconfigurationgen} \\\n  --openapi-schema <(${modelsschema}) \\\n  --output-base \"${KUBE_ROOT}/vendor\" \\\n  --output-package \"${applyconfigurations_package}\" \\\n  --input-dirs \"${applyconfigurationgen_external_apis_csv}\" \\\n  --go-header-file \"${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt\" \\\n  \"$@\"\n\n# This can be called with one flag, --verify-only, so it works for both the\n# update- and verify- scripts.\n${clientgen} --output-base \"${KUBE_ROOT}/vendor\" --output-package=\"k8s.io/client-go\" --clientset-name=\"kubernetes\" --input-base=\"k8s.io/api\" --input=\"${GV_DIRS_CSV}\" --apply-configuration-package \"${applyconfigurations_package}\" --go-header-file \"${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt\" \"$@\"\n\nlistergen_external_apis=()\nkube::util::read-array listergen_external_apis < <(\n  cd \"${KUBE_ROOT}/staging/src\"\n  find k8s.io/api -name types.go -print0 | xargs -0 -n1 dirname | sort\n)\nlistergen_external_apis_csv=$(IFS=,; echo \"${listergen_external_apis[*]}\")\n${listergen} --output-base \"${KUBE_ROOT}/vendor\" --output-package \"k8s.io/client-go/listers\" --input-dirs \"${listergen_external_apis_csv}\" --go-header-file \"${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt\" \"$@\"\n\ninformergen_external_apis=()\n# because client-gen doesn't do policy/v1alpha1, we have to skip it too\nkube::util::read-array informergen_external_apis < <(\n  cd \"${KUBE_ROOT}/staging/src\"\n  find k8s.io/api -name types.go -print0 | xargs -0 -n1 dirname | sort | grep -v pkg.apis.policy.v1alpha1\n)\ninformergen_external_apis_csv=$(IFS=,; echo \"${informergen_external_apis[*]}\")\n\n${informergen} \\\n  --output-base \"${KUBE_ROOT}/vendor\" \\\n  --output-package \"k8s.io/client-go/informers\" \\\n  --single-directory \\\n  --input-dirs \"${informergen_external_apis_csv}\" \\\n  --versioned-clientset-package k8s.io/client-go/kubernetes \\\n  --listers-package k8s.io/client-go/listers \\\n  --go-header-file \"${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt\" \\\n  \"$@\"\n\n# You may add additional calls of code generators like set-gen above.\n\n# call generation on sub-project for now\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/code-generator/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/kube-aggregator/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/sample-apiserver/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/sample-controller/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/apiextensions-apiserver/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/metrics/hack/update-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/apiextensions-apiserver/examples/client-go/hack/update-codegen.sh\n", "num_lines": 118}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\ncd \"${KUBE_ROOT}\"\n\n# generate json spec -> yaml\ntest/conformance/gen-conformance-yaml.sh\n# replace checked-in yaml\ncp _output/conformance.yaml test/conformance/testdata/conformance.yaml\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\n# run in module mode to match test command in readme.md\nexport GO111MODULE=on\n\n# UPDATE_COMPATIBILITY_FIXTURE_DATA=true regenerates fixture data if needed.\n# -run //HEAD only runs the test cases comparing against testdata for HEAD.\n# We suppress the output because we are expecting to have changes.\n# We suppress the test failure that occurs when there are changes.\nUPDATE_COMPATIBILITY_FIXTURE_DATA=true go test k8s.io/api -run //HEAD >/dev/null 2>&1 || true\n\n# Now that we have regenerated data at HEAD, run the test without suppressing output or failures\ngo test k8s.io/api -run //HEAD -count=1\n", "num_lines": 37}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates `*/api.pb.go` from the protobuf file `*/api.proto`.\n# Example:\n#   kube::protoc::generate_proto \"${DEVICE_PLUGIN_ALPHA}\"\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../\" && pwd -P)\"\nDEVICE_PLUGIN_ALPHA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/deviceplugin/v1alpha/\"\nDEVICE_PLUGIN_V1BETA1=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1/\"\n\nsource \"${KUBE_ROOT}/hack/lib/protoc.sh\"\nkube::protoc::generate_proto \"${DEVICE_PLUGIN_ALPHA}\"\nkube::protoc::generate_proto \"${DEVICE_PLUGIN_V1BETA1}\"\n", "num_lines": 32}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-device-plugin-dockerized.sh \"$@\"\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file is not intended to be run automatically. It is meant to be run\n# immediately before exporting docs. We do not want to check these documents in\n# by default.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nBINS=(\n\tcmd/gendocs\n\tcmd/genkubedocs\n\tcmd/genman\n\tcmd/genyaml\n)\nmake -C \"${KUBE_ROOT}\" WHAT=\"${BINS[*]}\"\n\nkube::util::ensure-temp-dir\n\nkube::util::gen-docs \"${KUBE_TEMP}\"\n\n# remove all of the old docs\nkube::util::remove-gen-docs\n\n# Copy fresh docs into the repo.\n# the shopt is so that we get docs/.generated_docs from the glob.\nshopt -s dotglob\ncp -af \"${KUBE_TEMP}\"/* \"${KUBE_ROOT}\"\nshopt -u dotglob\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nKUBE_KMS_GRPC_ROOT=\"${KUBE_ROOT}/staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/v1beta1/\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo\n\nif [[ -z \"$(which protoc)\" || \"$(protoc --version)\" != \"libprotoc 3.\"* ]]; then\n  echo \"Generating protobuf requires protoc 3.0.0-beta1 or newer. Please download and\"\n  echo \"install the platform appropriate Protobuf package for your OS: \"\n  echo\n  echo \"  https://github.com/google/protobuf/releases\"\n  echo\n  echo \"WARNING: Protobuf changes are not being validated\"\n  exit 1\nfi\n\nfunction cleanup {\n\trm -f \"${KUBE_KMS_GRPC_ROOT}/service.pb.go.bak\"\n\trm -f \"${KUBE_KMS_GRPC_ROOT}/service.pb.go.tmp\"\n}\n\ntrap cleanup EXIT\n\ngogopath=$(dirname \"$(kube::util::find-binary \"protoc-gen-gogo\")\")\n\nPATH=\"${gogopath}:${PATH}\" \\\n  protoc \\\n  --proto_path=\"${KUBE_KMS_GRPC_ROOT}\" \\\n  --proto_path=\"${KUBE_ROOT}/vendor\" \\\n  --gogo_out=plugins=grpc:\"${KUBE_KMS_GRPC_ROOT}\" \"${KUBE_KMS_GRPC_ROOT}/service.proto\"\n\n# Update boilerplate for the generated file.\ncat hack/boilerplate/boilerplate.generatego.txt \"${KUBE_KMS_GRPC_ROOT}/service.pb.go\" > \"${KUBE_KMS_GRPC_ROOT}/service.pb.go.tmp\" && \\\nmv \"${KUBE_KMS_GRPC_ROOT}/service.pb.go.tmp\" \"${KUBE_KMS_GRPC_ROOT}/service.pb.go\"\n\n# Run gofmt to clean up the generated code.\nkube::golang::verify_go_version\ngofmt -l -s -w \"${KUBE_KMS_GRPC_ROOT}/service.pb.go\"\n", "num_lines": 61}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-kms-dockerized.sh \"$@\"\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates `*/api.pb.go` from the protobuf file `*/api.proto`.\n# Example:\n#   kube::protoc::generate_proto \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}\"\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../\" && pwd -P)\"\nKUBELET_PLUGIN_REGISTRATION_V1ALPHA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/pluginregistration/v1alpha1/\"\nKUBELET_PLUGIN_REGISTRATION_V1BETA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/pluginregistration/v1beta1/\"\nKUBELET_EXAMPLE_PLUGIN_V1BETA1=\"${KUBE_ROOT}/pkg/kubelet/pluginmanager/pluginwatcher/example_plugin_apis/v1beta1/\"\nKUBELET_EXAMPLE_PLUGIN_V1BETA2=\"${KUBE_ROOT}/pkg/kubelet/pluginmanager/pluginwatcher/example_plugin_apis/v1beta2/\"\n\nsource \"${KUBE_ROOT}/hack/lib/protoc.sh\"\nkube::protoc::generate_proto \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}\"\nkube::protoc::generate_proto \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}\"\nkube::protoc::generate_proto \"${KUBELET_EXAMPLE_PLUGIN_V1BETA1}\"\nkube::protoc::generate_proto \"${KUBELET_EXAMPLE_PLUGIN_V1BETA2}\"\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-kubelet-plugin-registration-dockerized.sh \"$@\"\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates `*/api.pb.go` from the protobuf file `*/api.proto`.\n# Example:\n#   kube::protoc::generate_proto \"${POD_RESOURCES}\"\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../\" && pwd -P)\"\nPOD_RESOURCES=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/podresources/v1/\"\n\nsource \"${KUBE_ROOT}/hack/lib/protoc.sh\"\nkube::protoc::generate_proto \"${POD_RESOURCES}\"\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates `/staging/src/k8s.io/kubelet/pkg/apis/podresources/v1/api.pb.go`\n# from the protobuf file `/staging/src/k8s.io/kubelet/pkg/apis/podresources/v1/api.proto`\n# for pods.\n# Usage: `hack/update-generated-pod-resources.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-pod-resources-dockerized.sh \"$@\"\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script genertates `*/api.pb.go` from the protobuf file `*/api.proto`.\n# Usage: \n#     hack/update-generated-protobuf-dockerized.sh \"${APIROOTS}\"\n#     An example APIROOT is: \"k8s.io/api/admissionregistration/v1\"\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/go-to-protobuf\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo\n\nif [[ -z \"$(which protoc)\" || \"$(protoc --version)\" != \"libprotoc 3.\"* ]]; then\n  echo \"Generating protobuf requires protoc 3.0.0-beta1 or newer. Please download and\"\n  echo \"install the platform appropriate Protobuf package for your OS: \"\n  echo\n  echo \"  https://github.com/google/protobuf/releases\"\n  echo\n  echo \"WARNING: Protobuf changes are not being validated\"\n  exit 1\nfi\n\ngotoprotobuf=$(kube::util::find-binary \"go-to-protobuf\")\n\nwhile IFS=$'\\n' read -r line; do\n  APIROOTS+=( \"$line\" );\ndone <<< \"${1}\"\nshift\n\n# requires the 'proto' tag to build (will remove when ready)\n# searches for the protoc-gen-gogo extension in the output directory\n# satisfies import of github.com/gogo/protobuf/gogoproto/gogo.proto and the\n# core Google protobuf types\nPATH=\"${KUBE_ROOT}/_output/bin:${PATH}\" \\\n  \"${gotoprotobuf}\" \\\n  --proto-import=\"${KUBE_ROOT}/vendor\" \\\n  --proto-import=\"${KUBE_ROOT}/third_party/protobuf\" \\\n  --packages=\"$(IFS=, ; echo \"${APIROOTS[*]}\")\" \\\n  --go-header-file \"${KUBE_ROOT}/hack/boilerplate/boilerplate.generatego.txt\" \\\n  \"$@\"\n", "num_lines": 62}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates all go files from the corresponding protobuf files.\n# Usage: `hack/update-generated-protobuf.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\nAPIROOTS=${APIROOTS:-$(git grep --files-with-matches -e '// +k8s:protobuf-gen=package' cmd pkg staging | \\\n\txargs -n 1 dirname | \\\n\tsed 's,^,k8s.io/kubernetes/,;s,k8s.io/kubernetes/staging/src/,,' | \\\n\tsort | uniq\n)}\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-protobuf-dockerized.sh \"${APIROOTS}\" \"$@\"\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 39}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script builds protoc-gen-gogo binary in runtime and genertates \n# `*/api.pb.go` from the protobuf file `*/api.proto`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nKUBE_REMOTE_RUNTIME_ROOT=\"${KUBE_ROOT}/staging/src/k8s.io/cri-api/pkg/apis/runtime/\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nruntime_versions=(\"v1alpha2\" \"v1\")\n\nkube::golang::setup_env\n\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo\n\nif [[ -z \"$(which protoc)\" || \"$(protoc --version)\" != \"libprotoc 3.\"* ]]; then\n  echo \"Generating protobuf requires protoc 3.0.0-beta1 or newer. Please download and\"\n  echo \"install the platform appropriate Protobuf package for your OS: \"\n  echo\n  echo \"  https://github.com/google/protobuf/releases\"\n  echo\n  echo \"WARNING: Protobuf changes are not being validated\"\n  exit 1\nfi\n\nfunction cleanup {\n\tfor v in \"${runtime_versions[@]}\"; do\n\t\trm -f \"${KUBE_REMOTE_RUNTIME_ROOT}/${v}/api.pb.go.bak\"\n\t\trm -f \"${KUBE_REMOTE_RUNTIME_ROOT}/${v}/api.pb.go.tmp\"\n\tdone\n}\n\ntrap cleanup EXIT\n\ngogopath=$(dirname \"$(kube::util::find-binary \"protoc-gen-gogo\")\")\nPATH=\"${gogopath}:${PATH}\"\n\nfunction generate_code() {\n\tRUNTIME_API_VERSION=\"$1\"\n\tKUBE_REMOTE_RUNTIME_PATH=\"${KUBE_REMOTE_RUNTIME_ROOT}/${RUNTIME_API_VERSION}\"\n\tprotoc \\\n\t--proto_path=\"${KUBE_REMOTE_RUNTIME_PATH}\" \\\n\t--proto_path=\"${KUBE_ROOT}/vendor\" \\\n\t--gogo_out=plugins=grpc:\"${KUBE_REMOTE_RUNTIME_PATH}\" \"${KUBE_REMOTE_RUNTIME_PATH}/api.proto\"\n\n\t# Update boilerplate for the generated file.\n\tcat hack/boilerplate/boilerplate.generatego.txt \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go\" > \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go.tmp\"\n\tmv \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go.tmp\" \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go\"\n\n\t# Run gofmt to clean up the generated code.\n\tkube::golang::verify_go_version\n\tgofmt -l -s -w \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go\"\n}\n\nfor v in \"${runtime_versions[@]}\"; do\n\tgenerate_code \"${v}\"\ndone\n", "num_lines": 76}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script builds protoc-gen-gogo binary in runtime and genertates \n# `*/api.pb.go` from the protobuf file `*/api.proto`.\n# Usage: \n#     hack/update-generated-runtime.sh\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# NOTE: All output from this script needs to be copied back to the calling\n# source tree.  This is managed in kube::build::copy_output in build/common.sh.\n# If the output set is changed update that function.\n\n\"${KUBE_ROOT}/build/run.sh\" hack/update-generated-runtime-dockerized.sh \"$@\"\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file is not intended to be run automatically. It is meant to be run\n# immediately before exporting docs. We do not want to check these documents in\n# by default.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/test/instrumentation/stability-utils.sh\"\n\nkube::update::stablemetrics\n\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script generates `types_swagger_doc_generated.go` files for API group\n# versions. That file contains functions on API structs that return\n# the comments that should be surfaced for the corresponding API type\n# in our API docs.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/swagger.sh\"\n\nkube::golang::setup_env\n\nIFS=\" \" read -r -a GROUP_VERSIONS <<< \"meta/v1 meta/v1beta1 ${KUBE_AVAILABLE_GROUP_VERSIONS}\"\n\n# To avoid compile errors, remove the currently existing files.\nfor group_version in \"${GROUP_VERSIONS[@]}\"; do\n  rm -f \"$(kube::util::group-version-to-pkg-path \"${group_version}\")/types_swagger_doc_generated.go\"\ndone\n# ensure we have the latest genswaggertypedocs built\ngo install k8s.io/kubernetes/cmd/genswaggertypedocs\nfor group_version in \"${GROUP_VERSIONS[@]}\"; do\n  kube::swagger::gen_types_swagger_doc \"${group_version}\" \"$(kube::util::group-version-to-pkg-path \"${group_version}\")\"\ndone\n", "num_lines": 43}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# GoFmt apparently is changing @ head...\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './.git' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n      \\) -prune \\\n    \\) -name '*.go'\n}\n\nfind_files | xargs gofmt -s -w\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script fixes imports programmatically according to\n# all the imports that we have our preferred alias(es).\n# Usage: `hack/update-import-aliases.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\n\nret=0\ngo run cmd/preferredimports/preferredimports.go --confirm \"$@\" || ret=$?\nif [[ $ret -ne 0 ]]; then\n  echo \"!!! Unable to fix imports programmatically. Please see errors above.\" >&2\n  exit 1\nfi\n\n", "num_lines": 39}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# These are \"internal\" modules.  For various reasons, we want them to be\n# decoupled from their parent modules.\nMODULES=(\n    hack/tools\n    staging/src/k8s.io/code-generator/examples\n)\n\n# Explicitly opt into go modules, even though we're inside a GOPATH directory\nexport GO111MODULE=on\n\n# Detect problematic GOPROXY settings that prevent lookup of dependencies\nif [[ \"${GOPROXY:-}\" == \"off\" ]]; then\n  kube::log::error \"Cannot run hack/update-internal-modules.sh with \\$GOPROXY=off\"\n  exit 1\nfi\n\nkube::golang::verify_go_version\n\nfor mod in \"${MODULES[@]}\"; do\n  pushd \"${KUBE_ROOT}/${mod}\" >/dev/null\n    echo \"=== tidying go.mod/go.sum in ${mod}\"\n    go mod edit -fmt\n    go mod tidy\n  popd >/dev/null\ndone\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to fetch latest openapi spec.\n# Puts the updated spec at api/openapi-spec/\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nOPENAPI_ROOT_DIR=\"${KUBE_ROOT}/api/openapi-spec\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::util::require-jq\nkube::golang::setup_env\n\nmake -C \"${KUBE_ROOT}\" WHAT=cmd/kube-apiserver\n\nfunction cleanup()\n{\n    if [[ -n ${APISERVER_PID-} ]]; then\n      kill \"${APISERVER_PID}\" 1>&2 2>/dev/null\n      wait \"${APISERVER_PID}\" || true\n    fi\n    unset APISERVER_PID\n\n    kube::etcd::cleanup\n\n    kube::log::status \"Clean up complete\"\n}\n\ntrap cleanup EXIT SIGINT\n\nkube::golang::setup_env\n\nTMP_DIR=$(mktemp -d /tmp/update-openapi-spec.XXXX)\nETCD_HOST=${ETCD_HOST:-127.0.0.1}\nETCD_PORT=${ETCD_PORT:-2379}\nAPI_PORT=${API_PORT:-8050}\nAPI_HOST=${API_HOST:-127.0.0.1}\nAPI_LOGFILE=${API_LOGFILE:-/tmp/openapi-api-server.log}\n\nkube::etcd::start\n\necho \"dummy_token,admin,admin\" > \"${TMP_DIR}/tokenauth.csv\"\n\n# setup envs for TokenRequest required flags\nSERVICE_ACCOUNT_LOOKUP=${SERVICE_ACCOUNT_LOOKUP:-true}\nSERVICE_ACCOUNT_KEY=${SERVICE_ACCOUNT_KEY:-/tmp/kube-serviceaccount.key}\n# Generate ServiceAccount key if needed\nif [[ ! -f \"${SERVICE_ACCOUNT_KEY}\" ]]; then\n  mkdir -p \"$(dirname \"${SERVICE_ACCOUNT_KEY}\")\"\n  openssl genrsa -out \"${SERVICE_ACCOUNT_KEY}\" 2048 2>/dev/null\nfi\n\n# Start kube-apiserver\nkube::log::status \"Starting kube-apiserver\"\n\"${KUBE_OUTPUT_HOSTBIN}/kube-apiserver\" \\\n  --bind-address=\"${API_HOST}\" \\\n  --secure-port=\"${API_PORT}\" \\\n  --etcd-servers=\"http://${ETCD_HOST}:${ETCD_PORT}\" \\\n  --advertise-address=\"10.10.10.10\" \\\n  --cert-dir=\"${TMP_DIR}/certs\" \\\n  --feature-gates=AllAlpha=true \\\n  --runtime-config=\"api/all=true\" \\\n  --token-auth-file=\"${TMP_DIR}/tokenauth.csv\" \\\n  --authorization-mode=RBAC \\\n  --service-account-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n  --service-account-lookup=\"${SERVICE_ACCOUNT_LOOKUP}\" \\\n  --service-account-issuer=\"https://kubernetes.default.svc\" \\\n  --service-account-signing-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n  --logtostderr \\\n  --v=2 \\\n  --service-cluster-ip-range=\"10.0.0.0/24\" >\"${API_LOGFILE}\" 2>&1 &\nAPISERVER_PID=$!\n\nif ! kube::util::wait_for_url \"https://${API_HOST}:${API_PORT}/healthz\" \"apiserver: \"; then\n  kube::log::error \"Here are the last 10 lines from kube-apiserver (${API_LOGFILE})\"\n  kube::log::error \"=== BEGIN OF LOG ===\"\n  tail -10 \"${API_LOGFILE}\" >&2 || :\n  kube::log::error \"=== END OF LOG ===\"\n  exit 1\nfi\n\nkube::log::status \"Updating \" \"${OPENAPI_ROOT_DIR}\"\n\ncurl -w \"\\n\" -kfsS -H 'Authorization: Bearer dummy_token' \"https://${API_HOST}:${API_PORT}/openapi/v2\" | jq -S '.info.version=\"unversioned\"' > \"${OPENAPI_ROOT_DIR}/swagger.json\"\n\nkube::log::status \"SUCCESS\"\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 106}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script updates `translations/kubectl/template.pot` for\n# `pkg/kubectl/cmd/*.go pkg/kubectl/cmd/*/*.go`.\n# Usage: `update-translations.sh`.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nKUBECTL_FILES=\"pkg/kubectl/cmd/*.go pkg/kubectl/cmd/*/*.go\"\n\ngenerate_pot=\"false\"\ngenerate_mo=\"false\"\n\nwhile getopts \"hf:xg\" opt; do\n  case ${opt} in\n    h)\n      echo \"$0 [-f files] [-x] [-g]\"\n      echo \" -f <file-path>: Files to process\"\n      echo \" -x extract strings to a POT file\"\n      echo \" -g sort .po files and generate .mo files\"\n      exit 0\n      ;;\n    f)\n      KUBECTL_FILES=\"${OPTARG}\"\n      ;;\n    x)\n      generate_pot=\"true\"\n      ;;\n    g)\n      generate_mo=\"true\"\n      ;;\n    \\?)\n      echo \"[-f <files>] -x -g\" >&2\n      exit 1\n      ;;\n  esac\ndone\n\nif ! which go-xgettext > /dev/null; then\n  echo 'Can not find go-xgettext, install with:'\n  echo 'go get github.com/gosexy/gettext/go-xgettext'\n  exit 1\nfi\n\nif ! which msgfmt > /dev/null; then\n  echo 'Can not find msgfmt, install with:'\n  echo 'apt-get install gettext'\n  exit 1\nfi\n\nif [[ \"${generate_pot}\" == \"true\" ]]; then\n  echo \"Extracting strings to POT\"\n  go-xgettext -k=i18n.T \"${KUBECTL_FILES}\" > tmp.pot\n  perl -pi -e 's/CHARSET/UTF-8/' tmp.pot\n  perl -pi -e 's/\\\\\\(/\\\\\\\\\\(/g' tmp.pot\n  perl -pi -e 's/\\\\\\)/\\\\\\\\\\)/g' tmp.pot\n  kube::util::ensure-temp-dir\n  if msgcat -s tmp.pot > \"${KUBE_TEMP}/template.pot\"; then\n    mv \"${KUBE_TEMP}/template.pot\" translations/kubectl/template.pot\n    rm tmp.pot\n  else\n    echo \"Failed to update template.pot\"\n    exit 1\n  fi\nfi\n\nif [[ \"${generate_mo}\" == \"true\" ]]; then\n  echo \"Generating .po and .mo files\"\n  for x in translations/*/*/*/*.po; do\n    msgcat -s \"${x}\" > tmp.po\n    mv tmp.po \"${x}\"\n    echo \"generating .mo file for: ${x}\"\n    msgfmt \"${x}\" -o \"$(dirname \"${x}\")/$(basename \"${x}\" .po).mo\"\n  done\nfi\n\n./hack/generate-bindata.sh\n", "num_lines": 93}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Update the LICENSES directory.\n# Generates a table of Go dependencies and their licenses.\n#\n# Usage:\n#    $0 [--create-missing] [/path/to/licenses]\n#\n#    --create-missing will write the files that only exist upstream, locally.\n#    This option is mostly used for testing as we cannot check-in any of the\n#    additionally created files into the vendor auto-generated tree.\n#\n#    Run every time a license file is added/modified within /vendor to\n#    update /LICENSES\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nexport LANG=C\nexport LC_ALL=C\n\n###############################################################################\n# Process package content\n#\n# @param package  The incoming package name\n# @param type     The type of content (LICENSE, COPYRIGHT or COPYING)\n#\nprocess_content () {\n  local package=$1\n  local type=$2\n\n  local package_root\n  local ensure_pattern\n  local dir_root\n  local find_maxdepth\n  local find_names\n  local -a local_files=()\n\n  # Necessary to expand {}\n  case ${type} in\n      LICENSE) find_names=(-iname 'licen[sc]e*')\n               find_maxdepth=1\n               # Sadly inconsistent in the wild, but mostly license files\n               # containing copyrights, but no readme/notice files containing\n               # licenses (except to \"see license file\")\n               ensure_pattern=\"license|copyright\"\n               ;;\n    # We search READMEs for copyrights and this includes notice files as well\n    # Look in as many places as we find files matching\n    COPYRIGHT) find_names=(-iname 'notice*' -o -iname 'readme*')\n               find_maxdepth=3\n               ensure_pattern=\"copyright\"\n               ;;\n      COPYING) find_names=(-iname 'copying*')\n               find_maxdepth=1\n               ensure_pattern=\"license|copyright\"\n               ;;\n  esac\n\n  # Start search at package root\n  case ${package} in\n    github.com/*|golang.org/*|bitbucket.org/*|gonum.org/*)\n     package_root=$(echo \"${package}\" |awk -F/ '{ print $1\"/\"$2\"/\"$3 }')\n     ;;\n    go4.org/*)\n     package_root=$(echo \"${package}\" |awk -F/ '{ print $1 }')\n     ;;\n    gopkg.in/*)\n     # Root of gopkg.in package always ends with '.v(number)' and my contain\n     # more than two path elements. For example:\n     # - gopkg.in/yaml.v2\n     # - gopkg.in/inf.v0\n     # - gopkg.in/square/go-jose.v2\n     package_root=$(echo \"${package}\" |grep -oh '.*\\.v[0-9]')\n     ;;\n    */*)\n     package_root=$(echo \"${package}\" |awk -F/ '{ print $1\"/\"$2 }')\n     ;;\n    *)\n     package_root=\"${package}\"\n     ;;\n  esac\n\n  # Find files - only root and package level\n  local_files=()\n  IFS=\" \" read -r -a local_files <<< \"$(\n    for dir_root in ${package} ${package_root}; do\n      [[ -d ${DEPS_DIR}/${dir_root} ]] || continue\n\n      # One (set) of these is fine\n      find \"${DEPS_DIR}/${dir_root}\" \\\n          -xdev -follow -maxdepth ${find_maxdepth} \\\n          -type f \"${find_names[@]}\"\n    done | sort -u)\"\n\n  local index\n  local f\n  index=\"${package}-${type}\"\n  if [[ -z \"${CONTENT[${index}]-}\" ]]; then\n    for f in \"${local_files[@]-}\"; do\n      if [[ -z \"$f\" ]]; then\n        # Set the default value and then check it to prevent\n        # accessing potentially empty array\n        continue\n      fi\n      # Find some copyright info in any file and break\n      if grep -E -i -wq \"${ensure_pattern}\" \"${f}\"; then\n        CONTENT[${index}]=\"${f}\"\n        break\n      fi\n    done\n  fi\n}\n\n\n#############################################################################\n# MAIN\n#############################################################################\n\n# use modules, and use module info rather than the vendor dir for computing dependencies\nexport GO111MODULE=on\nexport GOFLAGS=-mod=mod\n\n# Check bash version\nif (( BASH_VERSINFO[0] < 4 )); then\n  echo\n  echo \"ERROR: Bash v4+ required.\"\n  # Extra help for OSX\n  if [[ \"$(uname -s)\" == \"Darwin\" ]]; then\n    echo\n    echo \"Ensure you are up to date on the following packages:\"\n    echo \"$ brew install md5sha1sum bash jq\"\n  fi\n  echo\n  exit 9\nfi\n\n# This variable can be injected, as in the verify script.\nLICENSE_ROOT=\"${LICENSE_ROOT:-${KUBE_ROOT}}\"\ncd \"${LICENSE_ROOT}\"\n\nkube::util::ensure-temp-dir\n\n# Save the genreated LICENSE file for each package temporarily\nTMP_LICENSE_FILE=\"${KUBE_TEMP}/LICENSES.$$\"\n\n# The directory to save all the LICENSE files\nLICENSES_DIR=\"${LICENSES_DIR:-${LICENSE_ROOT}/LICENSES}\"\nmkdir -p \"${LICENSES_DIR}\"\n\n# The tmp directory to save all the LICENSE files, will move to LICENSES_DIR\nTMP_LICENSES_DIR=\"${KUBE_TEMP}/LICENSES.DIR.$$\"\nmkdir -p \"${TMP_LICENSES_DIR}\"\n\nDEPS_DIR=\"vendor\"\ndeclare -Ag CONTENT\n\n# Put the K8S LICENSE on top\nif [ -f \"${LICENSE_ROOT}/LICENSE\" ]; then\n  (\n    echo \"================================================================================\"\n    echo \"= Kubernetes licensed under: =\"\n    echo\n    cat \"${LICENSE_ROOT}/LICENSE\"\n    echo\n    echo \"= LICENSE $(kube::util::md5 \"${LICENSE_ROOT}/LICENSE\")\"\n    echo \"================================================================================\"\n  ) > \"${TMP_LICENSE_FILE}\"\n  mv \"${TMP_LICENSE_FILE}\" \"${TMP_LICENSES_DIR}/LICENSE\"\nfi\n\n# Loop through every vendored package\nfor PACKAGE in $(go list -m -json all | jq -r .Path | sort -f); do\n  if [[ -e \"staging/src/${PACKAGE}\" ]]; then\n    echo \"${PACKAGE} is a staging package, skipping\" >&2\n    continue\n  fi\n  if [[ ! -e \"${DEPS_DIR}/${PACKAGE}\" ]]; then\n    echo \"${PACKAGE} doesn't exist in ${DEPS_DIR}, skipping\" >&2\n    continue\n  fi\n  # Skip a directory if 1) it has no files and 2) all the subdirectories contain a go.mod file.\n  misses_go_mod=false\n  DEPS_SUBDIR=\"${DEPS_DIR}/${PACKAGE}\"\n  search_for_mods () {\n    if [[ -z \"$(find \"${DEPS_SUBDIR}/\" -mindepth 1 -maxdepth 1 -type f)\" ]]; then\n      while read -d \"\" -r SUBDIR; do\n          if [[ ! -e \"${SUBDIR}/go.mod\" ]]; then\n              DEPS_SUBDIR=${SUBDIR}\n              search_for_mods\n          fi\n      done < <(find \"${DEPS_SUBDIR}/\" -mindepth 1 -maxdepth 1 -type d -print0)\n    else\n      misses_go_mod=true\n    fi\n  }\n  search_for_mods\n  if [[ $misses_go_mod = false ]]; then\n      echo \"${PACKAGE} has no files, skipping\" >&2\n      continue\n  fi\n  echo \"${PACKAGE}\"\n\n  process_content \"${PACKAGE}\" LICENSE\n  process_content \"${PACKAGE}\" COPYRIGHT\n  process_content \"${PACKAGE}\" COPYING\n\n  # copy content and throw error message\n  {\n    echo \"= ${DEPS_DIR}/${PACKAGE} licensed under: =\"\n    echo\n\n    file=\"\"\n    if [[ -n \"${CONTENT[${PACKAGE}-LICENSE]-}\" ]]; then\n      file=\"${CONTENT[${PACKAGE}-LICENSE]-}\"\n    elif [[ -n \"${CONTENT[${PACKAGE}-COPYRIGHT]-}\" ]]; then\n      file=\"${CONTENT[${PACKAGE}-COPYRIGHT]-}\"\n    elif [[ -n \"${CONTENT[${PACKAGE}-COPYING]-}\" ]]; then\n      file=\"${CONTENT[${PACKAGE}-COPYING]-}\"\n    fi\n    if [[ -z \"${file}\" ]]; then\n      cat >&2 << __EOF__\nNo license could be found for ${PACKAGE} - aborting.\n\nOptions:\n1. Check if the upstream repository has a newer version with LICENSE, COPYRIGHT and/or\n   COPYING files.\n2. Contact the author of the package to ensure there is a LICENSE, COPYRIGHT and/or\n   COPYING file present.\n3. Do not use this package in Kubernetes.\n__EOF__\n      exit 9\n    fi\n\n    cat \"${file}\"\n    echo\n    echo \"= ${file} $(kube::util::md5 \"${file}\")\"\n  } >> \"${TMP_LICENSE_FILE}\"\n\n  dest_dir=\"${TMP_LICENSES_DIR}/vendor/${PACKAGE}\"\n  mkdir -p \"${dest_dir}\"\n  mv \"${TMP_LICENSE_FILE}\" \"${dest_dir}/LICENSE\"\ndone\n\n# Leave things like OWNERS alone.\nrm -f \"${LICENSES_DIR}/LICENSE\"\nrm -rf \"${LICENSES_DIR}/vendor\"\nmv \"${TMP_LICENSES_DIR}\"/* \"${LICENSES_DIR}\"\n", "num_lines": 266}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Go tools really don't like it if you have a symlink in `pwd`.\ncd \"$(pwd -P)\"\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Explicitly opt into go modules, even though we're inside a GOPATH directory\nexport GO111MODULE=on\n# Explicitly set GOFLAGS to ignore vendor, since GOFLAGS=-mod=vendor breaks dependency resolution while rebuilding vendor\nexport GOFLAGS=-mod=mod\n# Ensure sort order doesn't depend on locale\nexport LANG=C\nexport LC_ALL=C\n# Detect problematic GOPROXY settings that prevent lookup of dependencies\nif [[ \"${GOPROXY:-}\" == \"off\" ]]; then\n  kube::log::error \"Cannot run hack/update-vendor.sh with \\$GOPROXY=off\"\n  exit 1\nfi\n\nkube::golang::verify_go_version\nkube::util::require-jq\n\nTMP_DIR=\"${TMP_DIR:-$(mktemp -d /tmp/update-vendor.XXXX)}\"\nLOG_FILE=\"${LOG_FILE:-${TMP_DIR}/update-vendor.log}\"\nkube::log::status \"logfile at ${LOG_FILE}\"\n\nfunction finish {\n  ret=$?\n  if [[ ${ret} != 0 ]]; then\n    echo \"An error has occurred. Please see more details in ${LOG_FILE}\"\n  fi\n  exit ${ret}\n}\ntrap finish EXIT\n\nif [ -z \"${BASH_XTRACEFD:-}\" ]; then\n  exec 19> \"${LOG_FILE}\"\n  export BASH_XTRACEFD=\"19\"\n  set -x\nfi\n\n# ensure_require_replace_directives_for_all_dependencies:\n# - ensures all existing 'require' directives have an associated 'replace' directive pinning a version\n# - adds explicit 'require' directives for all transitive dependencies\n# - adds explicit 'replace' directives for all require directives (existing 'replace' directives take precedence)\nfunction ensure_require_replace_directives_for_all_dependencies() {\n  local local_tmp_dir\n  local_tmp_dir=$(mktemp -d \"${TMP_DIR}/pin_replace.XXXX\")\n\n  # collect 'require' directives that actually specify a version\n  local require_filter='(.Version != null) and (.Version != \"v0.0.0\") and (.Version != \"v0.0.0-00010101000000-000000000000\")'\n  # collect 'replace' directives that unconditionally pin versions (old=new@version)\n  local replace_filter='(.Old.Version == null) and (.New.Version != null)'\n\n  # Capture local require/replace directives before running any go commands that can modify the go.mod file\n  local require_json=\"${local_tmp_dir}/require.json\"\n  local replace_json=\"${local_tmp_dir}/replace.json\"\n  go mod edit -json \\\n      | jq -r \".Require // [] | sort | .[] | select(${require_filter})\" \\\n      > \"${require_json}\"\n  go mod edit -json \\\n      | jq -r \".Replace // [] | sort | .[] | select(${replace_filter})\" \\\n      > \"${replace_json}\"\n\n  # 1a. Ensure replace directives have an explicit require directive\n  jq -r '\"-require \\(.Old.Path)@\\(.New.Version)\"' < \"${replace_json}\" \\\n      | xargs -L 100 go mod edit -fmt\n  # 1b. Ensure require directives have a corresponding replace directive pinning a version\n  jq -r '\"-replace \\(.Path)=\\(.Path)@\\(.Version)\"' < \"${require_json}\" \\\n      | xargs -L 100 go mod edit -fmt\n  jq -r '\"-replace \\(.Old.Path)=\\(.New.Path)@\\(.New.Version)\"' < \"${replace_json}\" \\\n      | xargs -L 100 go mod edit -fmt\n\n  # 2. Propagate root replace/require directives into staging modules, in case we are downgrading, so they don't bump the root required version back up\n  for repo in $(kube::util::list_staging_repos); do\n    pushd \"staging/src/k8s.io/${repo}\" >/dev/null 2>&1\n      jq -r '\"-require \\(.Path)@\\(.Version)\"' < \"${require_json}\" \\\n          | xargs -L 100 go mod edit -fmt\n      jq -r '\"-replace \\(.Path)=\\(.Path)@\\(.Version)\"' < \"${require_json}\" \\\n          | xargs -L 100 go mod edit -fmt\n      jq -r '\"-replace \\(.Old.Path)=\\(.New.Path)@\\(.New.Version)\"' < \"${replace_json}\" \\\n          | xargs -L 100 go mod edit -fmt\n    popd >/dev/null 2>&1\n  done\n\n  # 3. Add explicit require directives for indirect dependencies\n  go list -m -json all \\\n      | jq -r 'select(.Main != true) | select(.Indirect == true) | \"-require \\(.Path)@\\(.Version)\"' \\\n      | xargs -L 100 go mod edit -fmt\n\n  # 4. Add explicit replace directives pinning dependencies that aren't pinned yet\n  go list -m -json all \\\n      | jq -r 'select(.Main != true) | select(.Replace == null)  | \"-replace \\(.Path)=\\(.Path)@\\(.Version)\"' \\\n      | xargs -L 100 go mod edit -fmt\n}\n\nfunction group_replace_directives() {\n  local local_tmp_dir\n  local_tmp_dir=$(mktemp -d \"${TMP_DIR}/group_replace.XXXX\")\n  local go_mod_replace=\"${local_tmp_dir}/go.mod.replace.tmp\"\n  local go_mod_noreplace=\"${local_tmp_dir}/go.mod.noreplace.tmp\"\n  # separate replace and non-replace directives\n  awk \"\n     # print lines between 'replace (' ... ')' lines\n     /^replace [(]/      { inreplace=1; next                   }\n     inreplace && /^[)]/ { inreplace=0; next                   }\n     inreplace           { print > \\\"${go_mod_replace}\\\"; next }\n\n     # print ungrouped replace directives with the replace directive trimmed\n     /^replace [^(]/ { sub(/^replace /,\\\"\\\"); print > \\\"${go_mod_replace}\\\"; next }\n\n     # otherwise print to the noreplace file\n     { print > \\\"${go_mod_noreplace}\\\" }\n  \" < go.mod\n  {\n    cat \"${go_mod_noreplace}\";\n    echo \"replace (\";\n    cat \"${go_mod_replace}\";\n    echo \")\";\n  } > go.mod\n\n  go mod edit -fmt\n}\n\nfunction add_generated_comments() {\n  local local_tmp_dir\n  local_tmp_dir=$(mktemp -d \"${TMP_DIR}/add_generated_comments.XXXX\")\n  local go_mod_nocomments=\"${local_tmp_dir}/go.mod.nocomments.tmp\"\n\n  # drop comments before the module directive\n  awk \"\n     BEGIN           { dropcomments=1 }\n     /^module /      { dropcomments=0 }\n     dropcomments && /^\\/\\// { next }\n     { print }\n  \" < go.mod > \"${go_mod_nocomments}\"\n\n  # Add the specified comments\n  local comments=\"${1}\"\n  {\n    echo \"${comments}\"\n    echo \"\"\n    cat \"${go_mod_nocomments}\"\n   } > go.mod\n\n  # Format\n  go mod edit -fmt\n}\n\n\n# Phase 1: ensure go.mod files for staging modules and main module\n\nfor repo in $(kube::util::list_staging_repos); do\n  pushd \"staging/src/k8s.io/${repo}\" >/dev/null 2>&1\n    if [[ ! -f go.mod ]]; then\n      kube::log::status \"go.mod: initialize ${repo}\"\n      rm -f Godeps/Godeps.json # remove before initializing, staging Godeps are not authoritative\n      go mod init \"k8s.io/${repo}\"\n      go mod edit -fmt\n    fi\n  popd >/dev/null 2>&1\ndone\n\nif [[ ! -f go.mod ]]; then\n  kube::log::status \"go.mod: initialize k8s.io/kubernetes\"\n  go mod init \"k8s.io/kubernetes\"\n  rm -f Godeps/Godeps.json # remove after initializing\nfi\n\n\n# Phase 2: ensure staging repo require/replace directives\n\nkube::log::status \"go.mod: update staging references\"\n# Prune\ngo mod edit -json \\\n    | jq -r '.Require[]? | select(.Version == \"v0.0.0\")                 | \"-droprequire \\(.Path)\"' \\\n    | xargs -L 100 go mod edit -fmt\ngo mod edit -json \\\n    | jq -r '.Replace[]? | select(.New.Path | startswith(\"./staging/\")) | \"-dropreplace \\(.Old.Path)\"' \\\n    | xargs -L 100 go mod edit -fmt\n# Readd\nkube::util::list_staging_repos \\\n    | while read -r X; do echo \"-require k8s.io/${X}@v0.0.0\"; done \\\n    | xargs -L 100 go mod edit -fmt\nkube::util::list_staging_repos \\\n    | while read -r X; do echo \"-replace k8s.io/${X}=./staging/src/k8s.io/${X}\"; done \\\n    | xargs -L 100 go mod edit -fmt\n\n\n# Phase 3: capture required (minimum) versions from all modules, and replaced (pinned) versions from the root module\n\n# pin referenced versions\nensure_require_replace_directives_for_all_dependencies\n# resolves/expands references in the root go.mod (if needed)\ngo mod tidy >>\"${LOG_FILE}\" 2>&1\n# pin expanded versions\nensure_require_replace_directives_for_all_dependencies\n# group replace directives\ngroup_replace_directives\n\n# Phase 4: copy root go.mod to staging dirs and rewrite\n\nkube::log::status \"go.mod: propagate to staging modules\"\nfor repo in $(kube::util::list_staging_repos); do\n  pushd \"staging/src/k8s.io/${repo}\" >/dev/null 2>&1\n    echo \"=== propagating to ${repo}\" >> \"${LOG_FILE}\"\n    # copy root go.mod, changing module name\n    sed \"s#module k8s.io/kubernetes#module k8s.io/${repo}#\" \\\n        < \"${KUBE_ROOT}/go.mod\" \\\n        > \"${KUBE_ROOT}/staging/src/k8s.io/${repo}/go.mod\"\n    # remove `require` directives for staging components (will get re-added as needed by `go list`)\n    kube::util::list_staging_repos \\\n        | while read -r X; do echo \"-droprequire k8s.io/${X}\"; done \\\n        | xargs -L 100 go mod edit\n    # rewrite `replace` directives for staging components to point to peer directories\n    kube::util::list_staging_repos \\\n        | while read -r X; do echo \"-replace k8s.io/${X}=../${X}\"; done \\\n        | xargs -L 100 go mod edit\n  popd >/dev/null 2>&1\ndone\n\n\n# Phase 5: sort and tidy staging components\n\nkube::log::status \"go.mod: sorting staging modules\"\n# tidy staging repos in reverse dependency order.\n# the content of dependencies' go.mod files affects what `go mod tidy` chooses to record in a go.mod file.\ntidy_unordered=\"${TMP_DIR}/tidy_unordered.txt\"\nkube::util::list_staging_repos \\\n    | xargs -I {} echo \"k8s.io/{}\" > \"${tidy_unordered}\"\nrm -f \"${TMP_DIR}/tidy_deps.txt\"\n# SC2094 checks that you do not read and write to the same file in a pipeline.\n# We do read from ${tidy_unordered} in the pipeline and mention it within the\n# pipeline (but only ready it again) so we disable the lint to assure shellcheck\n# that :this-is-fine:\n# shellcheck disable=SC2094\nwhile IFS= read -r repo; do\n  # record existence of the repo to ensure modules with no peer relationships still get included in the order\n  echo \"${repo} ${repo}\" >> \"${TMP_DIR}/tidy_deps.txt\"\n\n  pushd \"${KUBE_ROOT}/staging/src/${repo}\" >/dev/null 2>&1\n    # save the original go.mod, since go list doesn't just add missing entries, it also removes specific required versions from it\n    tmp_go_mod=\"${TMP_DIR}/tidy_${repo/\\//_}_go.mod.original\"\n    tmp_go_deps=\"${TMP_DIR}/tidy_${repo/\\//_}_deps.txt\"\n    cp go.mod \"${tmp_go_mod}\"\n\n    {\n      echo \"=== sorting ${repo}\"\n      # 'go list' calculates direct imports and updates go.mod so that go list -m lists our module dependencies\n      echo \"=== computing imports for ${repo}\"\n      go list all\n      echo \"=== computing tools imports for ${repo}\"\n      go list -tags=tools all\n    } >> \"${LOG_FILE}\" 2>&1\n\n    # capture module dependencies\n    go list -m -f '{{if not .Main}}{{.Path}}{{end}}' all > \"${tmp_go_deps}\"\n\n    # restore the original go.mod file\n    cp \"${tmp_go_mod}\" go.mod\n\n    # list all module dependencies\n    for dep in $(join \"${tidy_unordered}\" \"${tmp_go_deps}\"); do\n      # record the relationship (put dep first, because we want to sort leaves first)\n      echo \"${dep} ${repo}\" >> \"${TMP_DIR}/tidy_deps.txt\"\n      # switch the required version to an explicit v0.0.0 (rather than an unknown v0.0.0-00010101000000-000000000000)\n      go mod edit -require \"${dep}@v0.0.0\"\n    done\n  popd >/dev/null 2>&1\ndone < \"${tidy_unordered}\"\n\nkube::log::status \"go.mod: tidying\"\nfor repo in $(tsort \"${TMP_DIR}/tidy_deps.txt\"); do\n  pushd \"${KUBE_ROOT}/staging/src/${repo}\" >/dev/null 2>&1\n    echo \"=== tidying ${repo}\" >> \"${LOG_FILE}\"\n\n    # prune replace directives that pin to the naturally selected version.\n    # do this before tidying, since tidy removes unused modules that\n    # don't provide any relevant packages, which forgets which version of the\n    # unused transitive dependency we had a require directive for,\n    # and prevents pruning the matching replace directive after tidying.\n    go list -m -json all |\n      jq -r 'select(.Replace != null) |\n             select(.Path == .Replace.Path) |\n             select(.Version == .Replace.Version) |\n             \"-dropreplace \\(.Replace.Path)\"' |\n    xargs -L 100 go mod edit -fmt\n\n    go mod tidy -v >>\"${LOG_FILE}\" 2>&1\n\n    # disallow transitive dependencies on k8s.io/kubernetes\n    loopback_deps=()\n    kube::util::read-array loopback_deps < <(go list all 2>/dev/null | grep k8s.io/kubernetes/ || true)\n    if [[ -n ${loopback_deps[*]:+\"${loopback_deps[*]}\"} ]]; then\n      kube::log::error \"Disallowed ${repo} -> k8s.io/kubernetes dependencies exist via the following imports:\n$(go mod why \"${loopback_deps[@]}\")\"\n      exit 1\n    fi\n\n    # prune unused pinned replace directives\n    comm -23 \\\n      <(go mod edit -json | jq -r '.Replace[] | .Old.Path' | sort) \\\n      <(go list -m -json all | jq -r .Path | sort) |\n    while read -r X; do echo \"-dropreplace=${X}\"; done |\n    xargs -L 100 go mod edit -fmt\n\n    # prune replace directives that pin to the naturally selected version\n    go list -m -json all |\n      jq -r 'select(.Replace != null) |\n             select(.Path == .Replace.Path) |\n             select(.Version == .Replace.Version) |\n             \"-dropreplace \\(.Replace.Path)\"' |\n    xargs -L 100 go mod edit -fmt\n\n  popd >/dev/null 2>&1\ndone\necho \"=== tidying root\" >> \"${LOG_FILE}\"\ngo mod tidy >>\"${LOG_FILE}\" 2>&1\n\n# disallow transitive dependencies on k8s.io/kubernetes\nloopback_deps=()\nkube::util::read-array loopback_deps < <(go mod graph | grep ' k8s.io/kubernetes' || true)\nif [[ -n ${loopback_deps[*]:+\"${loopback_deps[*]}\"} ]]; then\n  kube::log::error \"Disallowed transitive k8s.io/kubernetes dependencies exist via the following imports:\"\n  kube::log::error \"${loopback_deps[@]}\"\n  exit 1\nfi\n\n# Phase 6: add generated comments to go.mod files\nkube::log::status \"go.mod: adding generated comments\"\nadd_generated_comments \"\n// This is a generated file. Do not edit directly.\n// Ensure you've carefully read\n// https://git.k8s.io/community/contributors/devel/sig-architecture/vendor.md\n// Run hack/pin-dependency.sh to change pinned dependency versions.\n// Run hack/update-vendor.sh to update go.mod files and the vendor directory.\n\"\nfor repo in $(kube::util::list_staging_repos); do\n  pushd \"staging/src/k8s.io/${repo}\" >/dev/null 2>&1\n    add_generated_comments \"// This is a generated file. Do not edit directly.\"\n  popd >/dev/null 2>&1\ndone\n\n\n# Phase 7: rebuild vendor directory\nkube::log::status \"vendor: running 'go mod vendor'\"\ngo mod vendor >>\"${LOG_FILE}\" 2>&1\n\n# create a symlink in vendor directory pointing to the staging components.\n# This lets other packages and tools use the local staging components as if they were vendored.\nfor repo in $(kube::util::list_staging_repos); do\n  rm -fr \"${KUBE_ROOT}/vendor/k8s.io/${repo}\"\n  ln -s \"../../staging/src/k8s.io/${repo}\" \"${KUBE_ROOT}/vendor/k8s.io/${repo}\"\ndone\n\nkube::log::status \"vendor: updating vendor/LICENSES\"\nhack/update-vendor-licenses.sh >>\"${LOG_FILE}\" 2>&1\n\nkube::log::status \"vendor: creating OWNERS file\"\nrm -f \"vendor/OWNERS\"\ncat <<__EOF__ > \"vendor/OWNERS\"\n# See the OWNERS docs at https://go.k8s.io/owners\n\napprovers:\n- dep-approvers\nreviewers:\n- dep-reviewers\n__EOF__\n\nkube::log::status \"NOTE: don't forget to handle vendor/* files that were added or removed\"\n", "num_lines": 391}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs all the verify scripts respectively, so we should run\n# `hack/verify-all.sh` before submit a PR. It is equivalent to `make verify`.\n# Usage: `hack/verify-all.sh` or `make verify`.\n# Note: This script is a vestigial redirection. Please do not add \"real\" logic.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# For help output\nARGHELP=\"\"\nif [[ -n \"${KUBE_VERIFY_GIT_BRANCH:-}\" ]]; then\n    ARGHELP=\"BRANCH=${KUBE_VERIFY_GIT_BRANCH}\"\nfi\n\necho \"NOTE: $0 has been replaced by 'make verify'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make verify ${ARGHELP}\"\necho\necho\nmake --no-print-directory -C \"${KUBE_ROOT}\" verify BRANCH=\"${KUBE_VERIFY_GIT_BRANCH:-}\"\n", "num_lines": 41}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This scripts locates all API groups by their packages and versions\n# Usage: `hack/verify-api-groups.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nregister_files=()\nwhile read -r file ; do\n\tregister_files+=(\"${file}\")\ndone < <(find pkg/apis -name register.go | sort)\n\n# every register file should contain a GroupName.  Gather the different representations.\n# 1. group directory name for client gen\n# 2. external group versions for init.sh all APIs list\n# 3. install packages for inclusion in import_known_versions files\ngroup_dirnames=()\nexternal_group_versions=()\nexpected_install_packages=()\nfor register_file in \"${register_files[@]}\"; do\n\tpackage=\"${register_file%\"/register.go\"}\"\n\tgroup_dirname=\"${package#\"pkg/apis/\"}\"\n\tgroup_dirname=\"${group_dirname%%\"/*\"}\"\n\tgroup_name=\"\"\n\tif grep -q 'GroupName = \"' \"${register_file}\"; then\n\t\tgroup_name=$(grep 'GroupName = \"' \"${register_file}\" | cut -d\\\" -f2 -)\n\telse\n\t\techo \"${register_file} is missing \\\"const GroupName =\\\"\"\n\t\texit 1\n\tfi\n\n\t# If the dirname doesn't have a slash, then it's the internal package.\n\t# if does have one, then it's versioned (e.g. foobar/v1).\n\tif [[ \"${group_dirname#*'/'}\" == \"${group_dirname}\" ]]; then\n\t\tgroup_dirnames+=(\"${group_dirname}\")\n\t\texpected_install_packages+=(\"k8s.io/kubernetes/${package}\")\n\telse\n\t\tversion=$(echo \"${group_dirname}\" | cut -d/ -f2 -)\n\t\texternal_group_versions+=(\"${group_name}/${version}\")\n\tfi\ndone\n\n\n# check to make sure that client gen is getting\n# groups_without_codegen is the list of group we EXPECT to not have the client generated for\n# them.  This happens for types that aren't served from the API server\ngroups_without_codegen=(\n\t\"abac\"\n\t\"componentconfig\"\n\t\"imagepolicy\"\n\t\"admission\"\n)\nclient_gen_file=\"${KUBE_ROOT}/vendor/k8s.io/code-generator/cmd/client-gen/main.go\"\n\nfor group_dirname in \"${group_dirnames[@]}\"; do\n\tif ! grep -q \"${group_dirname}/\" \"${client_gen_file}\" ; then\n\t\tfound=0\n\t\tfor group_without_codegen in \"${groups_without_codegen[@]}\"; do\n\t\t\tif [[ \"${group_without_codegen}\" == \"${group_dirname}\" ]]; then\n\t\t\t\tfound=1\n\t\t\tfi\n\t\tdone\n\t\tif [[ \"${found}\" -ne \"1\" && -f \"${group_dirname}/types.go\" ]] ; then\n\t\t\techo \"need to add ${group_dirname}/ to ${client_gen_file}\"\n\t\t\texit 1\n\t\tfi\n\tfi\ndone\n\n# import_known_versions checks to be sure we'll get installed\n# groups_without_codegen is the list of group we EXPECT to not have the client generated for\n# them.  This happens for types that aren't served from the API server\npackages_without_install=(\n\t\"k8s.io/kubernetes/pkg/apis/abac\"\n\t\"k8s.io/kubernetes/pkg/apis/admission\"\n\t\"k8s.io/kubernetes/pkg/apis/componentconfig\" # TODO: Remove this package completely and from this list\n)\nknown_version_files=(\n\t\"pkg/controlplane/import_known_versions.go\"\n)\nfor expected_install_package in \"${expected_install_packages[@]}\"; do\n\tfound=0\n\tfor package_without_install in \"${packages_without_install[@]}\"; do\n\t\tif [ \"${package_without_install}\" == \"${expected_install_package}\" ]; then\n\t\t\tfound=1\n\t\tfi\n\tdone\n\tif [[ \"${found}\" -eq \"1\" ]] ; then\n\t\tcontinue\n\tfi\n\n\tfor known_version_file in \"${known_version_files[@]}\"; do\n\t\tif ! grep -q \"${expected_install_package}/install\" \"${known_version_file}\" ; then\n\t\t\techo \"missing ${expected_install_package}/install from ${known_version_file}\"\n\t\t\texit 1\n\t\tfi\n\tdone\ndone\n\n# check all groupversions to make sure they're in the init.sh file.  This isn't perfect, but its slightly\n# better than nothing\nfor external_group_version in \"${external_group_versions[@]}\"; do\n\tif ! grep -q \"${external_group_version}\" \"${KUBE_ROOT}/hack/lib/init.sh\" ; then\n\t\techo \"missing ${external_group_version} from hack/lib/init.sh:/KUBE_AVAILABLE_GROUP_VERSIONS or hack/init.sh:/KUBE_NONSERVER_GROUP_VERSIONS\"\n\t\texit 1\n\tfi\ndone\n", "num_lines": 127}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether removal of bazel related files is still needed.\n# If so: run `hack/update-bazel.sh` to actually remove them.\n#\n# Usage: `hack/verify-bazel.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nexport KUBE_ROOT\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n_tmpdir=\"$(kube::realpath \"$(mktemp -d -t verify-bazel.XXXXXX)\")\"\nkube::util::trap_add \"chmod -R u+rw ${_tmpdir} && rm -rf ${_tmpdir}\" EXIT\n\n_tmp_gopath=\"${_tmpdir}/go\"\n_tmp_kuberoot=\"${_tmp_gopath}/src/k8s.io/kubernetes\"\nmkdir -p \"${_tmp_kuberoot}/..\"\ncp -a \"${KUBE_ROOT}\" \"${_tmp_kuberoot}/..\"\n\ncd \"${_tmp_kuberoot}\"\nGOPATH=\"${_tmp_gopath}\" PATH=\"${_tmp_gopath}/bin:${PATH}\" ./hack/update-bazel.sh\n\ndiff=$(diff -Naupr -x '_output' \"${KUBE_ROOT}\" \"${_tmp_kuberoot}\" || true)\n\nif [[ -n \"${diff}\" ]]; then\n  echo \"${diff}\" >&2\n  echo >&2\n  echo \"Run ./hack/update-bazel.sh\" >&2\n  exit 1\nfi\n", "num_lines": 48}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks boilerplate header for all files.\n# Usage: `hack/verify-boilerplate.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nboilerDir=\"${KUBE_ROOT}/hack/boilerplate\"\nboiler=\"${boilerDir}/boilerplate.py\"\n\nfiles_need_boilerplate=()\nwhile IFS=$'\\n' read -r line; do\n  files_need_boilerplate+=( \"$line\" )\ndone < <(\"${boiler}\" \"$@\")\n\n# Run boilerplate check\nif [[ ${#files_need_boilerplate[@]} -gt 0 ]]; then\n  for file in \"${files_need_boilerplate[@]}\"; do\n    echo \"Boilerplate header is wrong for: ${file}\" >&2\n  done\n\n  exit 1\nfi\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks the description format of help message of kubectl command\n# is valid or not. And this checking is done for all kubectl sub-commands.\n# Usage: `hack/verify-cli-conventions.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nBINS=(\n\tcmd/clicheck\n)\nmake -C \"${KUBE_ROOT}\" WHAT=\"${BINS[*]}\"\n\nclicheck=$(kube::util::find-binary \"clicheck\")\n\nif ! output=$($clicheck 2>&1)\nthen\n\techo \"$output\"\n\techo\n\techo \"FAILURE: CLI is not following one or more required conventions.\"\n\texit 1\nelse\n\techo \"$output\"\n\techo\n  echo \"SUCCESS: CLI is following all tested conventions.\"\nfi\n", "num_lines": 48}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies whether code update is needed or not against the\n# specific sub-projects. The sub-projects are listed below this script(the\n# line that starts with `CODEGEN_PKG`).\n# Usage: `hack/verify-codegen.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\n# call verify on sub-project for now\n#\n# Note: these must be before the main script call because the later calls the sub-project's\n#       update-codegen.sh scripts. We wouldn't see any error on changes then.\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/code-generator/hack/verify-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/kube-aggregator/hack/verify-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/sample-apiserver/hack/verify-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/sample-controller/hack/verify-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/apiextensions-apiserver/hack/verify-codegen.sh\nCODEGEN_PKG=./vendor/k8s.io/code-generator vendor/k8s.io/metrics/hack/verify-codegen.sh\n\n\"${KUBE_ROOT}/hack/update-codegen.sh\" --verify-only\n", "num_lines": 43}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks conformance tests follow the requirements as\n# https://git.k8s.io/community/contributors/devel/sig-architecture/conformance-tests.md#conformance-test-requirements\n# Usage: `hack/verify-conformance-requirements.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\n\nerrors=()\n# Check conformance tests follow the requirements as https://git.k8s.io/community/contributors/devel/sig-architecture/conformance-tests.md#conformance-test-requirements\nif ! failedLint=$(go run \"${KUBE_ROOT}\"/hack/conformance/check_conformance_test_requirements.go \"${KUBE_ROOT}\"/test/e2e/)\nthen\n  errors+=( \"${failedLint}\" )\nfi\n\n# Check to be sure all the packages that should pass lint are.\nif [ ${#errors[@]} -eq 0 ]; then\n  echo 'Congratulations!  All e2e test source files have been linted for conformance requirements.'\nelse\n  {\n    echo \"Errors from lint:\"\n    for err in \"${errors[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'Please review the above warnings.'\n    echo\n  } >&2\n  exit 1\nfi\n\n", "num_lines": 56}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\ncd \"${KUBE_ROOT}\"\n\n# generate json spec -> yaml\ntest/conformance/gen-conformance-yaml.sh\n\n# diff generated and checked-in\nif diff -u test/conformance/testdata/conformance.yaml _output/conformance.yaml; then\n  echo PASS\n  exit 0\nfi\necho 'See instructions in test/conformance/README.md'\nexit 1\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks API-related files for missing descriptions and outputs a\n# list of structs and fields that are missing descriptions.\n# Usage: `hack/verify-description.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::setup_env\n\nmake -C \"${KUBE_ROOT}\" WHAT=cmd/genswaggertypedocs\n\n# Find binary\ngenswaggertypedocs=$(kube::util::find-binary \"genswaggertypedocs\")\n\nresult=0\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './pkg/*' \\\n      \\) -prune \\\n    \\) \\\n    \\( -wholename './staging/src/k8s.io/api/*/v*/types.go' \\\n       -o -wholename './staging/src/k8s.io/kube-aggregator/pkg/apis/*/v*/types.go' \\\n       -o -wholename './staging/src/k8s.io/apiextensions-apiserver/pkg/apis/*/v*/types.go' \\\n    \\)\n}\n\nif [[ $# -eq 0 ]]; then\n  versioned_api_files=$(find_files) || true\nelse\n  versioned_api_files=\"${*}\"\nfi\n\n# find_files had incorrect regexes which led to genswaggertypedocs never being invoked.\n# This led to many types.go have missing descriptions.\n# These types.go files are listed in hack/.descriptions_failures\n# Check that the file is in alphabetical order\nfailure_file=\"${KUBE_ROOT}/hack/.descriptions_failures\"\nkube::util::check-file-in-alphabetical-order \"${failure_file}\"\n\nfailing_files=()\nwhile IFS='' read -r line; do failing_files+=(\"$line\"); done < <(cat \"$failure_file\")\n\nfor file in $versioned_api_files; do\n  if ! kube::util::array_contains \"$file\" \"${failing_files[@]}\"; then\n    gen_swagger_result=0\n    $genswaggertypedocs -v -s \"${file}\" -f - || gen_swagger_result=$?\n    if [[ \"${gen_swagger_result}\" -ne 0 ]]; then\n      echo \"API file: ${file} is missing: ${gen_swagger_result} descriptions\"\n      result=1\n    fi\n  fi\n\n  if grep json: \"${file}\" | grep -v // | grep description: ; then\n    echo \"API file: ${file} should not contain descriptions in struct tags\"\n    result=1\n  fi\n  if grep json: \"${file}\" | grep -Ee \",[[:space:]]+omitempty|omitempty[[:space:]]+\" ; then\n    echo \"API file: ${file} should not contain leading or trailing spaces for omitempty directive\"\n    result=1\n  fi\ndone\n\ninternal_types_files=\"${KUBE_ROOT}/pkg/apis/core/types.go ${KUBE_ROOT}/pkg/apis/extensions/types.go\"\nfor internal_types_file in $internal_types_files; do\n  if [[ ! -e $internal_types_file ]]; then\n    echo \"Internal types file ${internal_types_file} does not exist\"\n    result=1\n    continue\n  fi\n\n  if grep json: \"${internal_types_file}\" | grep -v // | grep description: ; then\n    echo \"Internal API types should not contain descriptions\"\n    result=1\n  fi\ndone\n\nexit ${result}\n", "num_lines": 108}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies the following e2e test ownership policies\n# - tests MUST start with [sig-foo]\n# - tests MUST use top-level SIGDescribe\n# - tests SHOULD NOT have multiple [sig-foo] tags\n# - tests MUST NOT use nested SIGDescribe\n# TODO: these two can be dropped if KubeDescribe is gone from codebase\n# - tests MUST NOT have [k8s.io] in test names\n# - tests MUST NOT use KubeDescribe\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/.. && pwd -P)\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Set REUSE_BUILD_OUTPUT=y to skip rebuilding dependencies if present\nREUSE_BUILD_OUTPUT=${REUSE_BUILD_OUTPUT:-n}\n# set VERBOSE_OUTPUT=y to output .jq files and shell commands\nVERBOSE_OUTPUT=${VERBOSE_OUTPUT:-n}\n\nif [[ ${VERBOSE_OUTPUT} =~ ^[yY]$ ]]; then\n  set -x\nfi\n\npushd \"${KUBE_ROOT}\" > /dev/null\n\n# Setup a tmpdir to hold generated scripts and results\nreadonly tmpdir=$(mktemp -d -t verify-e2e-test-ownership.XXXX)\ntrap 'rm -rf ${tmpdir}' EXIT\n\n# input\nspec_summaries=\"${KUBE_ROOT}/_output/specsummaries.json\"\n# output\nresults_json=\"${tmpdir}/results.json\"\nsummary_json=\"${tmpdir}/summary.json\"\nfailures_json=\"${tmpdir}/failures.json\"\n\n# rebuild dependencies if necessary\nfunction ensure_dependencies() {\n  local -r ginkgo=\"${KUBE_ROOT}/_output/bin/ginkgo\"\n  local -r e2e_test=\"${KUBE_ROOT}/_output/bin/e2e.test\"\n  if ! { [ -f \"${ginkgo}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then\n    make ginkgo\n  fi\n  if ! { [ -f \"${e2e_test}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then\n    hack/make-rules/build.sh test/e2e/e2e.test\n  fi\n  if ! { [ -f \"${spec_summaries}\" ] && [[ \"${REUSE_BUILD_OUTPUT}\" =~ ^[yY]$ ]]; }; then\n    \"${ginkgo}\" --dryRun=true \"${e2e_test}\" -- --spec-dump \"${spec_summaries}\" > /dev/null\n  fi\n}\n\n# evaluate ginkgo spec summaries against e2e test ownership polices\n# output to ${results_json}\nfunction generate_results_json() {\n  readonly results_jq=${tmpdir}/results.jq\n  cat >\"${results_jq}\" <<EOS\n  [.[] | . as { ComponentTexts: \\$text, ComponentCodeLocations: \\$code } | {\n      calls: [ \\$text | range(1;length) as \\$i | {\n        sig: ((\\$text[\\$i] | match(\"\\\\\\[(sig-[^\\\\\\]]+)\\\\\\]\") | .captures[0].string) // \"unknown\"),\n        text: \\$text[\\$i],\n        # unused, but if we ever wanted to have policies based on other tags...\n        # tags: \\$text[\\$i] | [match(\"(\\\\\\[[^\\\\\\]]+\\\\\\])\"; \"g\").string],\n        line: \\$code[\\$i] | \"\\(.FileName):\\(.LineNumber)\",\n      } + (\\$code[\\$i] | .FullStackTrace | match(\"^(.*)\\\\\\.(.+)\\\\\\(.*\\\\n\") | .captures | {\n          package: .[0].string,\n          func: .[1].string\n      })],\n    } | {\n      owner: .calls[0].sig,\n      testname: .calls | map(.text) | join(\" \"),\n      calls,\n      policies: [(\n        .calls[0] |\n          {\n            fail: (.sig == \"unknown\"),\n            level: \"FAIL\",\n            category: \"unowned_test\",\n            reason: \"must start with [sig-foo]\",\n            found: .,\n          }, {\n            fail: (.func != \"SIGDescribe\"),\n            level: \"FAIL\",\n            category: \"no_sig_describe\",\n            reason: \"must use top-level SIGDescribe\",\n            found: .,\n          }\n        ), (\n        .calls[1:] |\n          (map(select(.sig != \"unknown\")) // [] | {\n            fail: . | any,\n            level: \"WARN\",\n            category: \"too_many_sigs\",\n            reason: \"should not have multiple [sig-foo] tags\",\n            found: .,\n          }),\n          (map(select(.func == \"SIGDescribe\")) // [] | {\n            fail: . | any,\n            level: \"FAIL\",\n            category: \"nested_sig_describe\",\n            reason: \"must not use nested SIGDescribe\",\n            found: .,\n          })\n        )\n      ]\n  }]\nEOS\n  if [[ ${VERBOSE_OUTPUT} =~ ^[yY]$ ]]; then\n    echo \"about to  ${results_jq}...\"\n    cat -n \"${results_jq}\"\n    echo\n  fi\n  <\"${spec_summaries}\" jq --slurp --from-file \"${results_jq}\" > \"${results_json}\"\n}\n\n# summarize e2e test policy results\n# output to ${summary_json}\nfunction generate_summary_json() {\n  summary_jq=${tmpdir}/summary.jq\n  cat >\"${summary_jq}\" <<EOS\n  . as \\$results |\n  # for each policy category\n  reduce \\$results[0].policies[] as \\$p ({}; . + {\n    # add a convenience .policy field containing that policy's result\n    (\\$p.category): \\$results | map(. + {policy: .policies[] | select(.category == \\$p.category)}) | {\n      level: \\$p.level,\n      reason: \\$p.reason,\n      passing: map(select(.policy.fail | not)) | length,\n      failing: map(select(.policy.fail)) | length,\n      testnames: map(select(.policy.fail) | .testname),\n    }\n  })\n  # add a meta policy based on whether any policy failed\n  + {\n    all_policies: \\$results | {\n      level: \"WARN\",\n      reason: \"should pass all policies\",\n      passing: map(select(.policies | map(.fail) | any | not)) | length,\n      failing: map(select(.policies | map(.fail) | any)) | length,\n      testnames: map(select(.policies | map(.fail) | any) | .testname),\n    }\n  }\n  # if a policy has no failing tests, change its log output to PASS\n  | with_entries(.value += { log: (if (.value.failing == 0) then \"PASS\" else .value.level end) })\n  # sort by policies with the most failing tests first\n  | to_entries | sort_by(.value.failing) | reverse | from_entries\nEOS\n  if [[ ${VERBOSE_OUTPUT} =~ ^[yY]$ ]]; then\n    echo \"about to run ${results_jq}...\"\n    cat -n \"${summary_jq}\"\n    echo\n  fi\n  <\"${results_json}\" jq --from-file \"${summary_jq}\" > \"${summary_json}\"\n}\n\n# filter e2e policy tests results to tests that failed, with the policies they failed\n# output to ${failures_json}\nfunction generate_failures_json() {\n  local -r failures_jq=\"${tmpdir}/failures.jq\"\n  cat >\"${failures_jq}\" <<EOS\n  .\n  # for each test\n  | map(\n    # filter down to failing policies; trim category, .reason is more verbose\n    .policies |= map(select(.fail) | del(.category))\n    # trim the full callstack, .found will contain the relevant call\n    | del(.calls)\n  )\n  # filter down to tests that have failed policies\n  | map(select(.policies | map (.fail) | any))\nEOS\n  if [[ ${VERBOSE_OUTPUT} =~ ^[yY]$ ]]; then\n    echo \"about to run ${failures_jq}...\"\n    cat -n \"${failures_jq}\"\n    echo\n  fi\n  <\"${results_json}\" jq --from-file \"${failures_jq}\" > \"${failures_json}\"\n}\n\nfunction output_results_and_exit_if_failed() {\n  local -r total_tests=$(<\"${spec_summaries}\" wc -l | awk '{print $1}')\n\n  # output results to console\n  (\n    echo \"run at datetime: $(date -u +%Y-%m-%dT%H:%M:%SZ)\"\n    echo \"based on commit: $(git log -n1 --date=iso-strict --pretty='%h - %cd - %s')\"\n    echo\n    <\"${failures_json}\" cat\n    printf \"%4s: e2e tests %-40s: %-4d\\n\" \"INFO\" \"in total\" \"${total_tests}\"\n    <\"${summary_json}\" jq -r 'to_entries[].value |\n      \"printf \\\"%4s: ..failing %-40s: %-4d\\\\n\\\" \\\"\\(.log)\\\" \\\"\\(.reason)\\\" \\\"\\(.failing)\\\"\"' | sh\n  ) | tee \"${tmpdir}/output.txt\"\n  # if we said \"FAIL\" in that output, we should fail\n  if <\"${tmpdir}/output.txt\" grep -q \"^FAIL\"; then\n    echo \"FAIL\"\n    exit 1\n  fi\n}\n\nensure_dependencies\ngenerate_results_json\ngenerate_failures_json\ngenerate_summary_json\noutput_results_and_exit_if_failed\necho \"PASS\"\n", "num_lines": 224}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies that dependencies are up-to-date across different files\n# Usage: `hack/verify-external-dependencies-version.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install zeitgeist\ncd \"${KUBE_ROOT}/hack/tools\"\nGO111MODULE=on go install sigs.k8s.io/zeitgeist\ncd -\n\n# Prefer full path for running zeitgeist\nZEITGEIST_BIN=\"$(which zeitgeist)\"\n\n# TODO: revert sed hack when zetigeist respects CLICOLOR/ttys\nCLICOLOR=0 \"${ZEITGEIST_BIN}\" validate \\\n  --local \\\n  --base-path \"${KUBE_ROOT}\" \\\n  --config \"${KUBE_ROOT}\"/build/dependencies.yaml \\\n  2> >(sed -e $'s/\\x1b\\[[0-9;]*m//g' >&2)\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of device plugin API is needed or not. We\n# should run `hack/update-generated-device-plugin.sh` if device plugin API is\n# out of date.\n# Usage: `hack/verify-generated-device-plugin.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nERROR=\"Device plugin api is out of date. Please run hack/update-generated-device-plugin.sh\"\nDEVICE_PLUGIN_ALPHA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/deviceplugin/v1alpha/\"\nDEVICE_PLUGIN_V1BETA1=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/deviceplugin/v1beta1/\"\n\nsource \"${KUBE_ROOT}/hack/lib/protoc.sh\"\nkube::golang::setup_env\n\nfunction cleanup {\n\trm -rf \"${DEVICE_PLUGIN_ALPHA}/_tmp/\"\n\trm -rf \"${DEVICE_PLUGIN_V1BETA1}/_tmp/\"\n}\n\ntrap cleanup EXIT\n\nmkdir -p \"${DEVICE_PLUGIN_ALPHA}/_tmp\"\ncp \"${DEVICE_PLUGIN_ALPHA}/api.pb.go\" \"${DEVICE_PLUGIN_ALPHA}/_tmp/\"\nmkdir -p \"${DEVICE_PLUGIN_V1BETA1}/_tmp\"\ncp \"${DEVICE_PLUGIN_V1BETA1}/api.pb.go\" \"${DEVICE_PLUGIN_V1BETA1}/_tmp/\"\n\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-device-plugin.sh\"\nkube::protoc::diff \"${DEVICE_PLUGIN_ALPHA}/api.pb.go\" \"${DEVICE_PLUGIN_ALPHA}/_tmp/api.pb.go\" \"${ERROR}\"\necho \"Generated device plugin alpha api is up to date.\"\nkube::protoc::diff \"${DEVICE_PLUGIN_V1BETA1}/api.pb.go\" \"${DEVICE_PLUGIN_V1BETA1}/_tmp/api.pb.go\" \"${ERROR}\"\necho \"Generated device plugin beta api is up to date.\"\n", "num_lines": 51}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks that various type of documents(* .md, * .yaml and man\n# files) are generated correctly(just verifies the generation process).\n# Usage: `hack/verify-generated-docs.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nBINS=(\n\tcmd/gendocs\n\tcmd/genkubedocs\n\tcmd/genman\n\tcmd/genyaml\n)\nmake -C \"${KUBE_ROOT}\" WHAT=\"${BINS[*]}\"\n\nkube::util::ensure-temp-dir\n\n# just verify the generation process\nkube::util::gen-docs \"${KUBE_TEMP}\"\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies that the expected results are obtained when creating each\n# type of file(e.g. codegen tool itself, a file in a package that needs codegen,\n# and etc.) for verification and then generating the code(executes\n# `make generated_files`).\n# Usage: `hack/verify-generated-files-remake.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::util::ensure_clean_working_dir\n\n_tmpdir=\"$(kube::realpath \"$(mktemp -d -t verify-generated-files.XXXXXX)\")\"\n_tmp_gopath=\"${_tmpdir}/go\"\n_tmp_kuberoot=\"${_tmp_gopath}/src/k8s.io/kubernetes\"\nmkdir -p \"${_tmp_kuberoot}/..\"\ngit worktree add \"${_tmp_kuberoot}\"\nkube::util::trap_add \"git worktree remove -f ${_tmp_kuberoot} && rm -rf ${_tmpdir}\" EXIT\ncd \"${_tmp_kuberoot}\"\n\n# clean out anything from the temp dir that's not checked in\ngit clean -ffxd\n\n# $1 = filename pattern as in \"zz_generated.$1.go\"\nfunction find_genfiles() {\n    find .                         \\\n        \\(                         \\\n          -not \\(                  \\\n            \\(                     \\\n                -path ./_\\* -o     \\\n                -path ./.\\*        \\\n            \\) -prune              \\\n          \\)                       \\\n        \\) -name \"zz_generated.$1.go\"\n}\n\n# $1 = filename pattern as in \"zz_generated.$1.go\"\n# $2 timestamp file\nfunction newer() {\n    find_genfiles \"$1\" | while read -r F; do\n        if [[ \"${F}\" -nt \"$2\" ]]; then\n            echo \"${F}\"\n        fi\n    done | LC_ALL=C sort\n}\n\n# $1 = filename pattern as in \"zz_generated.$1.go\"\n# $2 timestamp file\nfunction older() {\n    find_genfiles \"$1\" | while read -r F; do\n        if [[ \"$2\" -nt \"${F}\" ]]; then\n            echo \"${F}\"\n        fi\n    done | LC_ALL=C sort\n}\n\nfunction assert_clean() {\n    make generated_files >/dev/null\n    touch \"${STAMP}\"\n    make generated_files >/dev/null\n    X=\"$(newer deepcopy \"${STAMP}\")\"\n    if [[ -n \"${X}\" ]]; then\n        echo \"Generated files changed on back-to-back 'make' runs:\"\n        echo \"  ${X}\" | tr '\\n' ' '\n        echo \"\"\n        return 1\n    fi\n    true\n}\n\nSTAMP=/tmp/stamp.$RANDOM\n\n#\n# Test when we touch a file in a package that needs codegen.\n#\n\nassert_clean\n\nDIR=staging/src/k8s.io/sample-apiserver/pkg/apis/wardle/v1alpha1\ntouch \"${DIR}/types.go\"\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(newer deepcopy \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./${DIR}/zz_generated.deepcopy.go\" ]]; then\n    echo \"Wrong generated deepcopy files changed after touching src file:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\nX=\"$(newer defaults \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./${DIR}/zz_generated.defaults.go\" ]]; then\n    echo \"Wrong generated defaults files changed after touching src file:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\nX=\"$(newer conversion \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./${DIR}/zz_generated.conversion.go\" ]]; then\n    echo \"Wrong generated conversion files changed after touching src file:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when the codegen tool itself changes: deepcopy\n#\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/deepcopy-gen/main.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older deepcopy \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated deepcopy files did not change after touching code-generator file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/deepcopy-gen/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older deepcopy \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated deepcopy files did not change after touching code-generator dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/gengo/examples/deepcopy-gen/generators/deepcopy.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older deepcopy \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated deepcopy files did not change after touching code-generator dep file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/gengo/examples/deepcopy-gen/generators/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older deepcopy \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated deepcopy files did not change after touching code-generator dep dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when the codegen tool itself changes: defaults\n#\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/defaulter-gen/main.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older defaults \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated defaults files did not change after touching code-generator file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/defaulter-gen/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older defaults \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated defaults files did not change after touching code-generator dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/gengo/examples/defaulter-gen/generators/defaulter.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older defaults \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated defaults files did not change after touching code-generator dep file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/gengo/examples/defaulter-gen/generators/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older defaults \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated defaults files did not change after touching code-generator dep dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when the codegen tool itself changes: conversion\n#\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/conversion-gen/main.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older conversion \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated conversion files did not change after touching code-generator file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch staging/src/k8s.io/code-generator/cmd/conversion-gen/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older conversion \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated conversion files did not change after touching code-generator dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/code-generator/cmd/conversion-gen/generators/conversion.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older conversion \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated conversion files did not change after touching code-generator dep file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/code-generator/cmd/conversion-gen/generators/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older conversion \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated conversion files did not change after touching code-generator dep dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when we touch a file in a package that needs codegen for all openapi specs.\n#\n\nassert_clean\n\ntouch \"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go\"\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(newer openapi \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/apiextensions-apiserver/pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/code-generator/examples/apiserver/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/kube-aggregator/pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/sample-apiserver/pkg/generated/openapi/zz_generated.openapi.go\" ]]; then\n    echo \"Wrong generated openapi files changed after touching src file:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when we touch a file in a package that needs codegen for only the main openapi spec.\n#\n\nassert_clean\n\ntouch \"staging/src/k8s.io/api/apps/v1/types.go\"\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(newer openapi \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./pkg/generated/openapi/zz_generated.openapi.go\" ]]; then\n    echo \"Wrong generated openapi files changed after touching src file:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\n#\n# Test when we touch a file, modify the violation file it should fail, and UPDATE_API_KNOWN_VIOLATIONS=true updates it.\n#\n\nassert_clean\n\ntouch \"staging/src/k8s.io/apimachinery/pkg/apis/meta/v1/types.go\"\necho > api/api-rules/violation_exceptions.list\necho > api/api-rules/codegen_violation_exceptions.list\nif make generated_files >/dev/null 2>&1; then\n    echo \"Expected make generated_files to fail with API violations.\"\n    echo \"\"\n    exit 1\nfi\ntouch \"${STAMP}\"\nmake generated_files UPDATE_API_KNOWN_VIOLATIONS=true >/dev/null\nX=\"$(newer openapi \"${STAMP}\")\"\nif [[ -z \"${X}\" || ${X} != \"./pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/apiextensions-apiserver/pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/code-generator/examples/apiserver/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/kube-aggregator/pkg/generated/openapi/zz_generated.openapi.go\n./staging/src/k8s.io/sample-apiserver/pkg/generated/openapi/zz_generated.openapi.go\" ]]; then\n    echo \"Wrong generated openapi files changed after updating violation files:\"\n    echo \"  ${X:-(none)}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\nfor f in api/api-rules/violation_exceptions.list api/api-rules/codegen_violation_exceptions.list; do\n    if ! git diff --quiet \"$f\"; then\n        echo \"Violation file \\\"$f\\\" was not updated with UPDATE_API_KNOWN_VIOLATIONS=true.\"\n        echo \"\"\n        exit 1\n    fi\ndone\n\n#\n# Test when the codegen tool itself changes: openapi\n#\n\nassert_clean\n\ntouch vendor/k8s.io/kube-openapi/cmd/openapi-gen/openapi-gen.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older openapi \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated openapi files did not change after touching code-generator file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/kube-openapi/cmd/openapi-gen/\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older openapi \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated openapi files did not change after touching code-generator dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/kube-openapi/pkg/generators/openapi.go\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older openapi \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated openapi files did not change after touching code-generator dep file:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n\nassert_clean\n\ntouch vendor/k8s.io/kube-openapi/pkg/generators\ntouch \"${STAMP}\"\nmake generated_files >/dev/null\nX=\"$(older openapi \"${STAMP}\")\"\nif [[ -n \"${X}\" ]]; then\n    echo \"Generated openapi files did not change after touching code-generator dep dir:\"\n    echo \"  ${X}\" | tr '\\n' ' '\n    echo \"\"\n    exit 1\nfi\n", "num_lines": 420}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of generated code is needed or not. We\n# should run `make generated_files` if generated code is out of date.\n# Usage: `hack/verify-generated-files.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nexport KUBE_ROOT\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::util::ensure_clean_working_dir\n\n_tmpdir=\"$(kube::realpath \"$(mktemp -d -t verify-generated-files.XXXXXX)\")\"\nkube::util::trap_add \"rm -rf ${_tmpdir}\" EXIT\n\n_tmp_gopath=\"${_tmpdir}/go\"\n_tmp_kuberoot=\"${_tmp_gopath}/src/k8s.io/kubernetes\"\nmkdir -p \"${_tmp_kuberoot}/..\"\ncp -a \"${KUBE_ROOT}\" \"${_tmp_kuberoot}/..\"\n\ncd \"${_tmp_kuberoot}\"\n\n# clean out anything from the temp dir that's not checked in\ngit clean -ffxd\n# regenerate any generated code\nmake generated_files\n\nchanged_files=$(git status --porcelain)\n\nif [[ -n \"${changed_files}\" ]]; then\n  echo \"!!! Generated code is out of date:\" >&2\n  echo \"${changed_files}\" >&2\n  echo >&2\n  echo \"Please run make generated_files.\" >&2\n  exit 1\nfi\n", "num_lines": 55}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of KMS gRPC is needed or not. We should\n# run `hack/update-generated-kms.sh` if KMS gRPC is out of date.\n# Usage: `hack/verify-generated-kms.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nKUBE_KMS_GRPC_ROOT=\"${KUBE_ROOT}/staging/src/k8s.io/apiserver/pkg/storage/value/encrypt/envelope/v1beta1/\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nfunction cleanup {\n\trm -rf \"${KUBE_KMS_GRPC_ROOT}/_tmp/\"\n}\n\ntrap cleanup EXIT\n\nmkdir -p \"${KUBE_KMS_GRPC_ROOT}/_tmp\"\ncp \"${KUBE_KMS_GRPC_ROOT}/service.pb.go\" \"${KUBE_KMS_GRPC_ROOT}/_tmp/\"\n\nret=0\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-kms.sh\"\ndiff -I \"gzipped FileDescriptorProto\" -I \"0x\" -Naupr \"${KUBE_KMS_GRPC_ROOT}/_tmp/service.pb.go\" \"${KUBE_KMS_GRPC_ROOT}/service.pb.go\" || ret=$?\nif [[ $ret -eq 0 ]]; then\n    echo \"Generated KMS gRPC is up to date.\"\n    cp \"${KUBE_KMS_GRPC_ROOT}/_tmp/service.pb.go\" \"${KUBE_KMS_GRPC_ROOT}/\"\nelse\n    echo \"Generated KMS gRPC is out of date. Please run hack/update-generated-kms.sh\"\n    exit 1\nfi\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of kubelet plugin registration API is\n# needed or not. We should run\n# `hack/update-generated-kubelet-plugin-registration.sh` if kubelet plugin\n# registration API is out of date.\n# Usage: `hack/verify-generated-kubelet-plugin-registration.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nERROR=\"Kubelet Plugin Registration api is out of date. Please run hack/update-generated-kubelet-plugin-registration.sh\"\nKUBELET_PLUGIN_REGISTRATION_V1ALPHA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/pluginregistration/v1alpha1/\"\nKUBELET_PLUGIN_REGISTRATION_V1BETA=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/pluginregistration/v1beta1/\"\n\nsource \"${KUBE_ROOT}/hack/lib/protoc.sh\"\nkube::golang::setup_env\n\nfunction cleanup {\n\trm -rf \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/_tmp/\"\n\trm -rf \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/_tmp/\"\n}\n\ntrap cleanup EXIT\n\nmkdir -p \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/_tmp\"\nmkdir -p \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/_tmp\"\n\ncp \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/api.pb.go\" \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/_tmp/\"\ncp \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/api.pb.go\" \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/_tmp/\"\n\n# Check V1Alpha\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-kubelet-plugin-registration.sh\"\nkube::protoc::diff \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/api.pb.go\" \"${KUBELET_PLUGIN_REGISTRATION_V1ALPHA}/_tmp/api.pb.go\" \"${ERROR}\"\necho \"Generated Kubelet Plugin Registration api is up to date.\"\n\n# Check V1Beta\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-kubelet-plugin-registration.sh\"\nkube::protoc::diff \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/api.pb.go\" \"${KUBELET_PLUGIN_REGISTRATION_V1BETA}/_tmp/api.pb.go\" \"${ERROR}\"\necho \"Generated Kubelet Plugin Registration api is up to date.\"\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of Pod resources API is needed or not. We\n# should run `hack/update-generated-pod-resources.sh` if Pod resources API is\n# out of date.\n# Usage: `hack/verify-generated-pod-resources.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nPOD_RESOURCES=\"${KUBE_ROOT}/staging/src/k8s.io/kubelet/pkg/apis/podresources/v1/\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nfunction cleanup {\n\trm -rf \"${POD_RESOURCES}/_tmp/\"\n}\n\ntrap cleanup EXIT\n\nmkdir -p \"${POD_RESOURCES}/_tmp\"\ncp \"${POD_RESOURCES}/api.pb.go\" \"${POD_RESOURCES}/_tmp/\"\n\nret=0\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-pod-resources.sh\"\ndiff -I \"gzipped FileDescriptorProto\" -I \"0x\" -Naupr \"${POD_RESOURCES}/_tmp/api.pb.go\" \"${POD_RESOURCES}/api.pb.go\" || ret=$?\nif [[ $ret -eq 0 ]]; then\n    echo \"Generated pod resources api is up to date.\"\n    cp \"${POD_RESOURCES}/_tmp/api.pb.go\" \"${POD_RESOURCES}/\"\nelse\n    echo \"Generated pod resources api is out of date. Please run hack/update-generated-pod-resources.sh\"\n    exit 1\nfi\n", "num_lines": 51}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of the packages which explicitly\n# requesting generation is needed or not. We should run\n# `hack/update-generated-protobuf.sh` if those packages are out of date.\n# Usage: `hack/verify-generated-protobuf.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nAPIROOTS=$({\n  # gather the packages explicitly requesting generation\n  git grep --files-with-matches -e '// +k8s:protobuf-gen=package' cmd pkg staging | xargs -n 1 dirname\n  # add the root apimachinery pkg containing implicitly generated files (--apimachinery-packages)\n  echo staging/src/k8s.io/apimachinery/pkg\n} | sort | uniq)\n\n_tmp=\"${KUBE_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\n\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\nfor APIROOT in ${APIROOTS}; do\n  mkdir -p \"${_tmp}/${APIROOT}\"\n  cp -a \"${KUBE_ROOT}/${APIROOT}\"/* \"${_tmp}/${APIROOT}/\"\ndone\n\nKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-protobuf.sh\"\nfor APIROOT in ${APIROOTS}; do\n  TMP_APIROOT=\"${_tmp}/${APIROOT}\"\n  echo \"diffing ${APIROOT} against freshly generated protobuf\"\n  ret=0\n  diff -Naupr -I 'Auto generated by' -x 'zz_generated.*' -x '.github' -x '.import-restrictions' \"${KUBE_ROOT}/${APIROOT}\" \"${TMP_APIROOT}\" || ret=$?\n  cp -a \"${TMP_APIROOT}\"/* \"${KUBE_ROOT}/${APIROOT}/\"\n  if [[ $ret -eq 0 ]]; then\n    echo \"${APIROOT} up to date.\"\n  else\n    echo \"${APIROOT} is out of date. Please run hack/update-generated-protobuf.sh\"\n    exit 1\n  fi\ndone\n", "num_lines": 66}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of container runtime API is needed or not.\n# We should run `hack/update-generated-runtime.sh` if container runtime API is\n# out of date.\n# Usage: `hack/verify-generated-runtime.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nKUBE_REMOTE_RUNTIME_ROOT=\"${KUBE_ROOT}/staging/src/k8s.io/cri-api/pkg/apis/runtime/\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nruntime_versions=(\"v1alpha2\" \"v1\")\n\nkube::golang::setup_env\n\nfunction cleanup {\n\tfor v in \"${runtime_versions[@]}\"; do\n\t\trm -rf \"${KUBE_REMOTE_RUNTIME_ROOT}/${v}/_tmp/\"\n\tdone\n}\n\ntrap cleanup EXIT\n\nfunction verify_generated_code() {\n\tRUNTIME_API_VERSION=\"$1\"\n\tKUBE_REMOTE_RUNTIME_PATH=\"${KUBE_REMOTE_RUNTIME_ROOT}/${RUNTIME_API_VERSION}\"\n\tmkdir -p \"${KUBE_REMOTE_RUNTIME_PATH}/_tmp\"\n\tcp \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go\" \"${KUBE_REMOTE_RUNTIME_PATH}/_tmp/\"\n\n\tret=0\n\tKUBE_VERBOSE=3 \"${KUBE_ROOT}/hack/update-generated-runtime.sh\"\n\tdiff -I \"gzipped FileDescriptorProto\" -I \"0x\" -Naupr \"${KUBE_REMOTE_RUNTIME_PATH}/_tmp/api.pb.go\" \"${KUBE_REMOTE_RUNTIME_PATH}/api.pb.go\" || ret=$?\n\tif [[ $ret -eq 0 ]]; then\n\t    echo \"Generated container runtime api is up to date.\"\n\t    cp \"${KUBE_REMOTE_RUNTIME_PATH}/_tmp/api.pb.go\" \"${KUBE_REMOTE_RUNTIME_PATH}/\"\n\telse\n\t    echo \"Generated container runtime api is out of date. Please run hack/update-generated-runtime.sh\"\n\t    exit 1\n\tfi\n}\n\nfor v in \"${runtime_versions[@]}\"; do\n\tverify_generated_code \"${v}\"\ndone\n", "num_lines": 63}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script runs to ensure that we do not violate metric stability\n# policies.\n# Usage: `hack/verify-generated-stable-metrics.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/test/instrumentation/stability-utils.sh\"\n\nkube::validate::stablemetrics\n\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of swagger type documentation is needed or\n# not. We should run `hack/update-generated-swagger-docs.sh` if swagger type\n# documentation is out of date.\n# Usage: `hack/verify-generated-swagger-docs.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\n_tmpdir=\"$(kube::realpath \"$(mktemp -d -t swagger-docs.XXXXXX)\")\"\nfunction swagger_cleanup {\n  rm -rf \"${_tmpdir}\"\n}\nkube::util::trap_add swagger_cleanup EXIT\n\n# Copy the contents of the kube directory into the nice clean place\n_kubetmp=\"${_tmpdir}/src/k8s.io\"\nmkdir -p \"${_kubetmp}\"\n# should create ${_kubetmp}/kubernetes\ngit archive --format=tar --prefix=kubernetes/ \"$(git write-tree)\" | (cd \"${_kubetmp}\" && tar xf -)\n_kubetmp=\"${_kubetmp}/kubernetes\"\n# Do all our work in the new GOPATH\nexport GOPATH=\"${_tmpdir}\"\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './.git' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n      \\) -prune \\\n    \\) -name 'types_swagger_doc_generated.go'\n}\nwhile IFS=$'\\n' read -r line; do TARGET_FILES+=(\"$line\"); done < <(find_files)\n\npushd \"${_kubetmp}\" > /dev/null 2>&1\n  # Update the generated swagger docs\n  hack/update-generated-swagger-docs.sh\npopd > /dev/null 2>&1\n\nret=0\n\npushd \"${KUBE_ROOT}\" > /dev/null 2>&1\n  # Test for diffs\n  _output=\"\"\n  for file in ${TARGET_FILES[*]}; do\n    _output=\"${_output}$(diff -Naupr -I 'Auto generated by' \"${KUBE_ROOT}/${file}\" \"${_kubetmp}/${file}\")\" || ret=1\n  done\n\n  if [[ ${ret} -gt 0 ]]; then\n    echo \"Generated swagger type documentation is out of date:\" >&2\n    echo \"${_output}\" >&2\n    exit ${ret}\n  fi\npopd > /dev/null 2>&1\n\necho \"Generated swagger type documentation up to date.\"\n", "num_lines": 85}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether the source code needs to be formatted or not by\n# `gofmt`. Run `hack/update-gofmt.sh` to actually format sources.\n#\n# Note: gofmt output can change between go versions.\n#\n# Usage: `hack/verify-gofmt.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\ncd \"${KUBE_ROOT}\"\n\nkube::golang::setup_env\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './.git' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n        -o -wholename '*/bindata.go' \\\n      \\) -prune \\\n    \\) -name '*.go'\n}\n\n# gofmt exits with non-zero exit code if it finds a problem unrelated to\n# formatting (e.g., a file does not parse correctly). Without \"|| true\" this\n# would have led to no useful error message from gofmt, because the script would\n# have failed before getting to the \"echo\" in the block below.\ndiff=$(find_files | xargs gofmt -d -s 2>&1) || true\nif [[ -n \"${diff}\" ]]; then\n  echo \"${diff}\" >&2\n  echo >&2\n  echo \"Run ./hack/update-gofmt.sh\" >&2\n  exit 1\nfi\n", "num_lines": 63}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks coding style for go language files in each\n# Kubernetes package by golint.\n# Usage: `hack/verify-golangci-lint.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::verify_go_version\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Explicitly opt into go modules, even though we're inside a GOPATH directory\nexport GO111MODULE=on\n\n# Install golangci-lint\necho 'installing golangci-lint '\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  go install github.com/golangci/golangci-lint/cmd/golangci-lint\npopd >/dev/null\n\ncd \"${KUBE_ROOT}\"\n\necho 'running golangci-lint '\ngolangci-lint run \\\n  --timeout 30m \\\n  --disable-all \\\n  -E deadcode \\\n  -E unused \\\n  -E varcheck \\\n  -E ineffassign\n", "num_lines": 54}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script vets each package by `levee`.\n# Usage: `hack/verify-govet-levee.sh`.\n\nset -o errexit\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::verify_go_version\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install levee\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  GO111MODULE=on go install github.com/google/go-flow-levee/cmd/levee\npopd >/dev/null\n\n# Prefer full path for interaction with make vet\nLEVEE_BIN=\"$(which levee)\"\nCONFIG_FILE=\"${KUBE_ROOT}/hack/testdata/levee/levee-config.yaml\"\n\n\"${KUBE_ROOT}\"/hack/verify-govet.sh -vettool=\"${LEVEE_BIN}\" -config=\"${CONFIG_FILE}\"\n", "num_lines": 43}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script vets all *.go files by running `go vet`. It is equivalent to\n# `make vet`.\n# Usage: `hack/verify-govet.sh` or `make vet`.\n# Note: This script is a vestigial redirection. Please do not add \"real\" logic.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# For help output\nARGHELP=\"\"\nif [[ \"$#\" -gt 0 ]]; then\n    ARGHELP=\"WHAT='$*'\"\nfi\n\necho \"NOTE: $0 has been replaced by 'make vet'\"\necho\necho \"The equivalent of this invocation is: \"\necho \"    make vet ${ARGHELP}\"\necho\necho\n\nmake --no-print-directory -C \"${KUBE_ROOT}\" vet WHAT=\"$*\"\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies that all the imports have our preferred alias(es). The\n# preferred aliases for imports are listed in `hack/.import-aliases`.\n# Usage: `hack/verify-import-aliases.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\n\nret=0\ngo run cmd/preferredimports/preferredimports.go \"$@\" || ret=$?\nif [[ $ret -ne 0 ]]; then\n  echo \"!!! Please see hack/.import-aliases for the preferred aliases for imports.\" >&2\n  exit 1\nfi\n\n", "num_lines": 39}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks import restrictions. The script looks for a file called\n# `.import-restrictions` in each directory, then all imports of the package are\n# checked against each \"rule\" in the file.\n# Usage: `hack/verify-import-boss.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\ngo install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/import-boss\n\npackages=(\n  \"k8s.io/kubernetes/pkg/...\"\n  \"k8s.io/kubernetes/cmd/...\"\n  \"k8s.io/kubernetes/plugin/...\"\n  \"k8s.io/kubernetes/test/e2e/framework/...\"\n  \"k8s.io/kubernetes/test/integration/...\"\n)\nfor d in staging/src/k8s.io/*/; do\n  if [ -d \"$d\" ]; then\n    packages+=(\"./vendor/${d#\"staging/src/\"}...\")\n  fi\ndone\n\n$(kube::util::find-binary \"import-boss\") --include-test-files=true --verify-only --input-dirs \"$(IFS=, ; echo \"${packages[*]}\")\"\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks restricted packages are imported or not and outputs the\n# result. Target directory's path and allowed packages against checking are\n# listed in `staging/publishing/import-restrictions.yaml`.\n# Usage: `hack/verify-imports.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nmake -C \"${KUBE_ROOT}\" WHAT=cmd/importverifier\n\n# Find binary\nimportverifier=$(kube::util::find-binary \"importverifier\")\n\nif [[ ! -x \"$importverifier\" ]]; then\n  {\n    echo \"It looks as if you don't have a compiled importverifier binary\"\n    echo\n    echo \"If you are running from a clone of the git repo, please run\"\n    echo \"'make WHAT=cmd/importverifier'.\"\n  } >&2\n  exit 1\nfi\n\n\"${importverifier}\" \"k8s.io/\" \"${KUBE_ROOT}/staging/publishing/import-restrictions.yaml\"\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::util::ensure_clean_working_dir\n\n_tmpdir=\"$(kube::realpath \"$(mktemp -d -t verify-internal-modules.XXXXXX)\")\"\n#kube::util::trap_add \"rm -rf ${_tmpdir}\" EXIT\n\n_tmp_gopath=\"${_tmpdir}/go\"\n_tmp_kuberoot=\"${_tmp_gopath}/src/k8s.io/kubernetes\"\ngit worktree add -f \"${_tmp_kuberoot}\" HEAD\nkube::util::trap_add \"git worktree remove -f ${_tmp_kuberoot}\" EXIT\n\npushd \"${_tmp_kuberoot}\" >/dev/null\n./hack/update-internal-modules.sh\npopd\n\ngit -C \"${_tmp_kuberoot}\" add -N .\ndiff=$(git -C \"${_tmp_kuberoot}\" diff HEAD || true)\n\nif [[ -n \"${diff}\" ]]; then\n  echo \"${diff}\" >&2\n  echo >&2\n  echo \"Run ./hack/update-internal-modules.sh\" >&2\n  exit 1\nfi\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script extracts the links from types.go and .md files in pkg/api/,\n# pkg/apis/ and docs/ directories, checks the status code of the response, and\n# output the list of invalid links.\n# Usage: `hack/verify-linkcheck.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nmake -C \"${KUBE_ROOT}\" WHAT=cmd/linkcheck\n\nlinkcheck=$(kube::util::find-binary \"linkcheck\")\n\nkube::util::ensure-temp-dir\nOUTPUT=\"${KUBE_TEMP}\"/linkcheck-output\ncleanup() {\n\trm -rf \"${OUTPUT}\"\n}\ntrap \"cleanup\" EXIT SIGINT\nmkdir -p \"$OUTPUT\"\n\nAPIROOT=\"${KUBE_ROOT}/pkg/api/\"\nAPISROOT=\"${KUBE_ROOT}/pkg/apis/\"\nDOCROOT=\"${KUBE_ROOT}/docs/\"\nROOTS=(\"$APIROOT\" \"$APISROOT\" \"$DOCROOT\")\nfound_invalid=false\nfor root in \"${ROOTS[@]}\"; do\n  \"${linkcheck}\" \"--root-dir=${root}\" 2> >(tee -a \"${OUTPUT}/error\" >&2) && ret=0 || ret=$?\n  if [[ $ret -eq 1 ]]; then\n    echo \"Failed: found invalid links in ${root}.\"\n    found_invalid=true\n  fi\n  if [[ $ret -gt 1 ]]; then\n    echo \"Error running linkcheck\"\n    exit 1\n  fi\ndone\n\nif [ ${found_invalid} = true ]; then\n  echo \"Summary of invalid links:\"\n  cat \"${OUTPUT}/error\"\n  exit 1\nfi\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 67}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether packages under `vendor` directory have cyclic\n# dependencies on `main` or `staging` repositories.\n# Usage: `hack/verify-no-vendor-cycles.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nexport GO111MODULE=auto\n\nstaging_repos=()\nkube::util::read-array staging_repos < <(kube::util::list_staging_repos)\nstaging_repos_pattern=$(IFS=\"|\"; echo \"${staging_repos[*]}\")\n\ncd \"${KUBE_ROOT}\"\n\n# Check for any module that is not main or staging and depends on main or staging\nbad_deps=$(go mod graph | grep -vE \"^k8s.io\\/(kubernetes|${staging_repos_pattern})\" | grep -E \"\\sk8s.io\\/(kubernetes|${staging_repos_pattern})\" || true)\nif [[ -n \"${bad_deps}\" ]]; then\n  echo \"Found disallowed dependencies that transitively depend on k8s.io/kubernetes or staging modules:\"\n  echo \"${bad_deps}\"\n  exit 1\nfi\n\nkube::util::ensure-temp-dir\n\n# Get vendored packages dependencies\n# Use -deps flag to include transitive dependencies\ngo list -mod=vendor -test -deps -json ./vendor/... > \"${KUBE_TEMP}/deps.json\"\n\n# Check for any vendored package that imports main repo\n# Staging repos are explicitly excluded even though go list does not currently consider symlinks\ngo run cmd/dependencycheck/dependencycheck.go -restrict \"^k8s\\.io/kubernetes/\" -exclude \"^k8s\\.io/(${staging_repos_pattern})(/|$)\" \"${KUBE_TEMP}/deps.json\"\n\n# Check for any vendored package that imports a staging repo\n# Staging repos are explicitly excluded even though go list does not currently consider symlinks\ngo run cmd/dependencycheck/dependencycheck.go -restrict \"^k8s\\.io/(${staging_repos_pattern})(/|$)\" -exclude \"^k8s\\.io/(${staging_repos_pattern})(/|$)\" \"${KUBE_TEMP}/deps.json\"\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of OpenAPI specification is needed or not.\n# We should run `hack/update-openapi-spec.sh` if OpenAPI specification is out of\n# date.\n# Usage: `hack/verify-openapi-spec.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\nkube::etcd::install\n\nmake -C \"${KUBE_ROOT}\" WHAT=cmd/kube-apiserver\n\nSPECROOT=\"${KUBE_ROOT}/api/openapi-spec\"\nTMP_SPECROOT=\"${KUBE_ROOT}/_tmp/openapi-spec\"\n_tmp=\"${KUBE_ROOT}/_tmp\"\n\nmkdir -p \"${_tmp}\"\ncp -a \"${SPECROOT}\" \"${TMP_SPECROOT}\"\ntrap 'cp -a ${TMP_SPECROOT} ${SPECROOT}/..; rm -rf ${_tmp}' EXIT SIGINT\nrm \"${SPECROOT}\"/*\ncp \"${TMP_SPECROOT}/README.md\" \"${SPECROOT}/README.md\"\n\n\"${KUBE_ROOT}/hack/update-openapi-spec.sh\"\necho \"diffing ${SPECROOT} against freshly generated openapi spec\"\nret=0\ndiff -Naupr -I 'Auto generated by' \"${SPECROOT}\" \"${TMP_SPECROOT}\" || ret=$?\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${SPECROOT} up to date.\"\nelse\n  echo \"${SPECROOT} is out of date. Please run hack/update-openapi-spec.sh\" >&2\n  exit 1\nfi\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies whether codes follow golang convention.\n# Usage: `hack/verify-pkg-names.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\nif git --no-pager grep -E $'^(import |\\t)[a-z]+[A-Z_][a-zA-Z]* \"[^\"]+\"$' -- '**/*.go' ':(exclude)vendor/*' ':(exclude)**/*.pb.go'; then\n  echo \"!!! Some package aliases break go conventions.\"\n  echo \"To fix these errors, do not use capitalized or underlined characters\"\n  echo \"in pkg aliases. Refer to https://blog.golang.org/package-names for more info.\"\n  exit 1\nfi\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies whether codes follow golang convention.\n# Usage: `hack/verify-prerelease-lifecycle-tags.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\nif git --no-pager grep -L '// +k8s:prerelease-lifecycle-gen=true' -- 'staging/src/k8s.io/api/**/*beta*/doc.go'; then\n  echo \"!!! Some beta packages doc.go do not include prerelease-lifecycle tags.\"\n  echo \"To fix these errors, add '// +k8s:prerelease-lifecycle-gen=true' to doc.go and\"\n  echo \"add '// +k8s:prerelease-lifecycle-gen:introduced=1.<release>' to every type that embeds metav1.TypeMeta\"\n  exit 1\nfi\n\nif git --no-pager grep -L '// +k8s:prerelease-lifecycle-gen=true' -- 'staging/src/k8s.io/kube-aggregator/pkg/apis/**/*beta*/doc.go'; then\n  echo \"!!! Some beta packages doc.go do not include prerelease-lifecycle tags.\"\n  echo \"To fix these errors, add '// +k8s:prerelease-lifecycle-gen=true' to doc.go and\"\n  echo \"add '// +k8s:prerelease-lifecycle-gen:introduced=1.<release>' to every type that embeds metav1.TypeMeta\"\n  exit 1\nfi\n\nif git --no-pager grep -L '// +k8s:prerelease-lifecycle-gen=true' -- 'staging/src/k8s.io/apiextensions-apisever/pkg/apis/**/*beta*/doc.go'; then\n  echo \"!!! Some beta packages doc.go do not include prerelease-lifecycle tags.\"\n  echo \"To fix these errors, add '// +k8s:prerelease-lifecycle-gen=true' to doc.go and\"\n  echo \"add '// +k8s:prerelease-lifecycle-gen:introduced=1.<release>' to every type that embeds metav1.TypeMeta\"\n  exit 1\nfi\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script validates that only a restricted set of packages are importing\n# github.com/prometheus/*\n\n# NOTE: this is not the same as verify-imports which can only verify\n# that within a particular package the imports made are allowed.\n#\n# This is also not the same thing as verify-import-boss, which is pretty\n# powerful for specifying restricted imports but does not scale to checking\n# the entire source tree well and is only enabled for specific packages.\n#\n# See: https://github.com/kubernetes/kubernetes/issues/99876\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# See: https://github.com/kubernetes/kubernetes/issues/89267\nallowed_prometheus_importers=(\n  ./cluster/images/etcd-version-monitor/etcd-version-monitor.go\n  ./pkg/volume/util/operationexecutor/operation_generator_test.go\n  ./staging/src/k8s.io/component-base/metrics/collector.go\n  ./staging/src/k8s.io/component-base/metrics/collector_test.go\n  ./staging/src/k8s.io/component-base/metrics/counter.go\n  ./staging/src/k8s.io/component-base/metrics/counter_test.go\n  ./staging/src/k8s.io/component-base/metrics/desc.go\n  ./staging/src/k8s.io/component-base/metrics/gauge.go\n  ./staging/src/k8s.io/component-base/metrics/gauge_test.go\n  ./staging/src/k8s.io/component-base/metrics/histogram.go\n  ./staging/src/k8s.io/component-base/metrics/histogram_test.go\n  ./staging/src/k8s.io/component-base/metrics/http.go\n  ./staging/src/k8s.io/component-base/metrics/labels.go\n  ./staging/src/k8s.io/component-base/metrics/legacyregistry/registry.go\n  ./staging/src/k8s.io/component-base/metrics/metric.go\n  ./staging/src/k8s.io/component-base/metrics/opts.go\n  ./staging/src/k8s.io/component-base/metrics/processstarttime_others.go\n  ./staging/src/k8s.io/component-base/metrics/registry.go\n  ./staging/src/k8s.io/component-base/metrics/registry_test.go\n  ./staging/src/k8s.io/component-base/metrics/summary.go\n  ./staging/src/k8s.io/component-base/metrics/testutil/metrics.go\n  ./staging/src/k8s.io/component-base/metrics/testutil/metrics_test.go\n  ./staging/src/k8s.io/component-base/metrics/testutil/promlint.go\n  ./staging/src/k8s.io/component-base/metrics/testutil/testutil.go\n  ./staging/src/k8s.io/component-base/metrics/value.go\n  ./staging/src/k8s.io/component-base/metrics/wrappers.go\n  ./test/e2e/apimachinery/flowcontrol.go\n  ./test/e2e/node/pods.go\n  ./test/e2e_node/dynamic_kubelet_config_test.go\n  ./test/e2e_node/resource_metrics_test.go\n  ./test/instrumentation/main_test.go\n  ./test/integration/apiserver/flowcontrol/concurrency_test.go\n  ./test/integration/metrics/metrics_test.go\n)\n\n# Go imports always involve a double quoted string of the package path\n# https://golang.org/ref/spec#Import_declarations\n#\n# If you *really* need a string literal that looks like \"github.com/prometheus/.*\"\n# somewhere else that actually isn't an import, you can use backticks / a raw \n# string literal instead (which cannot be used in imports, only double quotes).\n#\n# NOTE: we previously had an implementation that checked for an actual import\n# as a post-processing step on the matching files, which is cheap enough and\n# accurate, except that it's difficult to guarantee we check for all supported\n# GOOS, GOARCH, and other build tags, and we want to prevent all imports.\n# So we dropped this, in favor of only the grep call.\n# See: https://github.com/kubernetes/kubernetes/pull/100552\nreally_failing_files=()\nall_failing_files=()\nwhile IFS='' read -r filepath; do\n  # convert from file to package, and only insert unique results\n  # we want to minimize the amount of `go list` calls we need to make\n  if ! kube::util::array_contains \"$filepath\" \"${allowed_prometheus_importers[@]}\"; then\n    # record a failure if not\n    really_failing_files+=(\"$filepath\")\n  fi\n  all_failing_files+=(\"$filepath\")\ndone < <(cd \"${KUBE_ROOT}\" && grep \\\n  --exclude-dir={_output,vendor} \\\n  --include='*.go' \\\n  -R . \\\n  -l \\\n  -Ee '\"github.com/prometheus/.*\"' \\\n| LC_ALL=C sort -u)\n\n# check for any files we're allowing to fail that are no longer failing, so we\n# can enforce that the list shrinks\nallowed_but_not_failing=()\nfor allowed_file in \"${allowed_prometheus_importers[@]}\"; do\n  if ! kube::util::array_contains \"$allowed_file\" \"${all_failing_files[@]}\"; then\n    allowed_but_not_failing+=(\"$allowed_file\")\n  fi\ndone\n\n# we will exit with this at the end of the script depending on the checks below\nexit_code=0\n\n# check for files we've allow-listed that no longer need to be\nif [ -n \"${allowed_but_not_failing[*]}\" ]; then\n  {\n    echo \"ERROR: Some files allow-listed to import prometheus are no longer failing and should be removed.\"\n    echo \"Please remove these files from allowed_prometheus_importers in hack/verify-prometheus-imports.sh\"\n    echo \"\"\n    echo \"Non-failing but allow-listed files:\"\n    for non_failing_file in \"${allowed_but_not_failing[@]}\"; do\n      echo \"  ${non_failing_file}\"\n    done\n  } >&2\n  exit_code=1\nfi\n# check for files that fail but are not allow-listed\nif [ -n \"${really_failing_files[*]}\" ]; then\n  {\n    echo \"ERROR: Some files are importing packages under github.com/prometheus/* but are not allow-listed to do so.\"\n    echo \"\"\n    echo \"See: https://github.com/kubernetes/kubernetes/issues/89267\"\n    echo \"\"\n    echo \"Failing files:\"\n    for failing_file in \"${really_failing_files[@]}\"; do\n      echo \"  ${failing_file}\"\n    done\n  } >&2\n  exit_code=2\nfi\n\nexit \"$exit_code\"\n", "num_lines": 146}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether between $KUBE_VERIFY_GIT_BRANCH and HEAD files in\n# readonly directories were modified. A directory is readonly if it contains a\n# .readonly file. Being readonly DOES NOT apply recursively to subdirectories.\n# Usage: `hack/verify-readonly-packages.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nreadonly branch=${1:-${KUBE_VERIFY_GIT_BRANCH:-master}}\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/pkg/*' \\\n      \\) -prune \\\n    \\) -name '.readonly'\n}\n\nconflicts=()\nwhile IFS=$'\\n' read -r dir; do\n    dir=${dir#./}\n    if kube::util::has_changes \"${branch}\" \"^${dir}/[^/]*\\$\" '/\\.readonly$|/BUILD$|/zz_generated|/\\.generated\\.|\\.proto$|\\.pb\\.go$' >/dev/null; then\n        conflicts+=(\"${dir}\")\n    fi\ndone < <(find_files | sed 's|/.readonly||')\n\nif [ ${#conflicts[@]} -gt 0 ]; then\n    exec 1>&2\n    for dir in \"${conflicts[@]}\"; do\n        echo \"Found ${dir}/.readonly, but files changed compared to \\\"${branch}\\\" branch.\"\n    done\n    exit 1\nelse\n    echo \"Readonly packages verified.\"\nfi\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 65}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script lints each shell script by `shellcheck`.\n# Usage: `hack/verify-shellcheck.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# allow overriding docker cli, which should work fine for this script\nDOCKER=\"${DOCKER:-docker}\"\n\n# required version for this script, if not installed on the host we will\n# use the official docker image instead. keep this in sync with SHELLCHECK_IMAGE\nSHELLCHECK_VERSION=\"0.7.1\"\n# upstream shellcheck latest stable image as of October 23rd, 2019\nSHELLCHECK_IMAGE=\"docker.io/koalaman/shellcheck-alpine:v0.7.1@sha256:d6147f30864ddb7c9cf983fc277d345bc315e798e309ddf70062b194843ee252\"\n\n# disabled lints\ndisabled=(\n  # this lint disallows non-constant source, which we use extensively without\n  # any known bugs\n  1090\n  # this lint prefers command -v to which, they are not the same\n  2230\n)\n# comma separate for passing to shellcheck\njoin_by() {\n  local IFS=\"$1\";\n  shift;\n  echo \"$*\";\n}\nSHELLCHECK_DISABLED=\"$(join_by , \"${disabled[@]}\")\"\nreadonly SHELLCHECK_DISABLED\n\n# ensure we're linting the k8s source tree\ncd \"${KUBE_ROOT}\"\n\n# Find all shell scripts excluding:\n# - Anything git-ignored - No need to lint untracked files.\n# - ./_* - No need to lint output directories.\n# - ./.git/* - Ignore anything in the git object store.\n# - ./vendor* - Vendored code should be fixed upstream instead.\n# - ./third_party/*, but re-include ./third_party/forked/*  - only code we\n#    forked should be linted and fixed.\nall_shell_scripts=()\nwhile IFS=$'\\n' read -r script;\n  do git check-ignore -q \"$script\" || all_shell_scripts+=(\"$script\");\ndone < <(find . -name \"*.sh\" \\\n  -not \\( \\\n    -path ./_\\*      -o \\\n    -path ./.git\\*   -o \\\n    -path ./vendor\\* -o \\\n    \\( -path ./third_party\\* -a -not -path ./third_party/forked\\* \\) \\\n  \\))\n\n# detect if the host machine has the required shellcheck version installed\n# if so, we will use that instead.\nHAVE_SHELLCHECK=false\nif which shellcheck &>/dev/null; then\n  detected_version=\"$(shellcheck --version | grep 'version: .*')\"\n  if [[ \"${detected_version}\" = \"version: ${SHELLCHECK_VERSION}\" ]]; then\n    HAVE_SHELLCHECK=true\n  fi\nfi\n\n# if KUBE_JUNIT_REPORT_DIR is set, disable colorized output.\n# Colorized output causes malformed XML in the JUNIT report.\nSHELLCHECK_COLORIZED_OUTPUT=\"auto\"\nif [[ -n \"${KUBE_JUNIT_REPORT_DIR:-}\" ]]; then\n  SHELLCHECK_COLORIZED_OUTPUT=\"never\"\nfi\n\n# common arguments we'll pass to shellcheck\nSHELLCHECK_OPTIONS=(\n  # allow following sourced files that are not specified in the command,\n  # we need this because we specify one file at a time in order to trivially\n  # detect which files are failing\n  \"--external-sources\"\n  # include our disabled lints\n  \"--exclude=${SHELLCHECK_DISABLED}\"\n  # set colorized output\n  \"--color=${SHELLCHECK_COLORIZED_OUTPUT}\"\n)\n\n# tell the user which we've selected and lint all scripts\nres=0\nif ${HAVE_SHELLCHECK}; then\n  echo \"Using host shellcheck ${SHELLCHECK_VERSION} binary.\"\n  shellcheck \"${SHELLCHECK_OPTIONS[@]}\" \"${all_shell_scripts[@]}\" || res=$?\nelse\n  echo \"Using shellcheck ${SHELLCHECK_VERSION} docker image.\"\n  \"${DOCKER}\" run \\\n    --rm -v \"${KUBE_ROOT}:${KUBE_ROOT}\" -w \"${KUBE_ROOT}\" \\\n    \"${SHELLCHECK_IMAGE}\" \\\n  shellcheck \"${SHELLCHECK_OPTIONS[@]}\" \"${all_shell_scripts[@]}\" || res=$?\nfi\n\n# print a message based on the result\nif [ $res -eq 0 ]; then\n  echo 'Congratulations! All shell files are passing lint :-)'\nelse\n  {\n    echo\n    echo 'Please review the above warnings. You can test via \"./hack/verify-shellcheck.sh\"'\n    echo 'If the above warnings do not make sense, you can exempt this warning with a comment'\n    echo ' (if your reviewer is okay with it).'\n    echo 'In general please prefer to fix the error, we have already disabled specific lints'\n    echo ' that the project chooses to ignore.'\n    echo 'See: https://github.com/koalaman/shellcheck/wiki/Ignore#ignoring-one-specific-instance-in-a-file'\n    echo\n  } >&2\n  exit 1\nfi\n\n# preserve the result\nexit $res\n", "num_lines": 136}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks commonly misspelled English words in all files in the\n# working directory by client9/misspell package.\n# Usage: `hack/verify-spelling.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nexport KUBE_ROOT\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install tools we need\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  GO111MODULE=on go install github.com/client9/misspell/cmd/misspell\npopd >/dev/null\n\n# Spell checking\n# All the skipping files are defined in hack/.spelling_failures\nskipping_file=\"${KUBE_ROOT}/hack/.spelling_failures\"\nfailing_packages=$(sed \"s| | -e |g\" \"${skipping_file}\")\ngit ls-files | grep -v -e \"${failing_packages}\" | xargs misspell -i \"Creater,creater,ect\" -error -o stderr\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether the expected metadata files (such as OWNERS and\n# LICENSE) exist under the `staging/src/k8s.io/*` directories.\n# Usage: `hack/verify-staging-meta-files.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nexpected_filenames=(\n  .github/PULL_REQUEST_TEMPLATE.md\n  code-of-conduct.md\n  LICENSE\n  OWNERS\n  README.md\n  SECURITY_CONTACTS\n)\n\nexceptions=(\n  client-go/README.md # client-go provides its own README\n)\n\nRESULT=0\nfor full_repo_path in \"${KUBE_ROOT}\"/staging/src/k8s.io/*; do\n  repo=$(basename \"${full_repo_path}\")\n  for filename in \"${expected_filenames[@]}\"; do\n    if echo \" ${exceptions[*]} \" | grep -F \" ${repo}/${filename} \" >/dev/null; then\n      continue\n    elif [ ! -f \"${KUBE_ROOT}/staging/src/k8s.io/${repo}/${filename}\" ]; then\n      echo \"staging/src/k8s.io/${repo}/${filename} does not exist and must be created\"\n      RESULT=1\n    fi\n  done\ndone\n\nexit $RESULT\n", "num_lines": 54}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script lints each package by `staticcheck`.\n# Usage: `hack/verify-staticcheck.sh`.\n# NOTE: To ignore issues detected a package, add it to the\n# `.staticcheck_failures` blacklist.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::verify_go_version\n\nFOCUS=\"${1:-}\"\nFOCUS=\"${FOCUS%/}\" # Remove the ending \"/\"\n\n# See https://staticcheck.io/docs/checks\nCHECKS=(\n  \"all\"\n  \"-S1*\"   # Omit code simplifications for now.\n  \"-ST1*\"  # Mostly stylistic, redundant w/ golint\n)\nexport IFS=','; checks=\"${CHECKS[*]}\"; unset IFS\n\n# Packages to ignore due to bugs in staticcheck\n# NOTE: To ignore issues detected a package, add it to the .staticcheck_failures blacklist\nIGNORE=(\n  \"vendor/k8s.io/kubectl/pkg/cmd/edit/testdata\"  # golang/go#24854, dominikh/go-tools#565\n)\nexport IFS='|'; ignore_pattern=\"^(${IGNORE[*]})\\$\"; unset IFS\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install staticcheck\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  GO111MODULE=on go install honnef.co/go/tools/cmd/staticcheck\npopd >/dev/null\n\ncd \"${KUBE_ROOT}\"\n\n# Check that the file is in alphabetical order\nfailure_file=\"${KUBE_ROOT}/hack/.staticcheck_failures\"\nkube::util::check-file-in-alphabetical-order \"${failure_file}\"\n\nall_packages=()\nwhile IFS='' read -r line; do\n  # Prepend './' to get staticcheck to treat these as paths, not packages.\n  all_packages+=(\"./$line\")\ndone < <( hack/make-rules/helpers/cache_go_dirs.sh \"${KUBE_ROOT}/_tmp/all_go_dirs\" |\n            grep \"^${FOCUS:-.}\" |\n            grep -vE \"(third_party|generated|clientset_generated|hack|testdata|/_)\" |\n            grep -vE \"$ignore_pattern\" )\n\nfailing_packages=()\nif [[ -z $FOCUS ]]; then # Ignore failing_packages in FOCUS mode\n  while IFS='' read -r line; do failing_packages+=(\"$line\"); done < <(cat \"$failure_file\")\nfi\nerrors=()\nnot_failing=()\n\nwhile read -r error; do\n  # Ignore compile errors caused by lack of files due to build tags.\n  # TODO: Add verification for these directories.\n  ignore_no_files=\"^-: build constraints exclude all Go files in .* \\(compile\\)\"\n  if [[ $error =~ $ignore_no_files ]]; then\n    continue\n  fi\n\n  file=\"${error%%:*}\"\n  pkg=\"$(dirname \"$file\")\"\n  kube::util::array_contains \"$pkg\" \"${failing_packages[@]}\" && in_failing=$? || in_failing=$?\n  if [[ \"${in_failing}\" -ne \"0\" ]]; then\n    errors+=( \"${error}\" )\n  elif [[ \"${in_failing}\" -eq \"0\" ]]; then\n    really_failing+=( \"$pkg\" )\n  fi\ndone < <(GOOS=linux staticcheck -checks \"${checks}\" \"${all_packages[@]}\" 2>/dev/null || true)\n\nexport IFS=$'\\n'  # Expand ${really_failing[*]} to separate lines\nkube::util::read-array really_failing < <(sort -u <<<\"${really_failing[*]}\")\nunset IFS\nfor pkg in \"${failing_packages[@]}\"; do\n  if ! kube::util::array_contains \"$pkg\" \"${really_failing[@]}\"; then\n    not_failing+=( \"$pkg\" )\n  fi\ndone\n\n# Check that all failing_packages actually still exist\ngone=()\nfor p in \"${failing_packages[@]}\"; do\n  if ! kube::util::array_contains \"./$p\" \"${all_packages[@]}\"; then\n    gone+=( \"$p\" )\n  fi\ndone\n\n# Check to be sure all the packages that should pass check are.\nif [ ${#errors[@]} -eq 0 ]; then\n  echo 'Congratulations!  All Go source files have passed staticcheck.'\nelse\n  {\n    echo \"Errors from staticcheck:\"\n    for err in \"${errors[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'Please review the above warnings. You can test via:'\n    echo '  hack/verify-staticcheck.sh <failing package>'\n    echo 'If the above warnings do not make sense, you can exempt the line or file. See:'\n    echo '  https://staticcheck.io/docs/#ignoring-problems'\n    echo\n  } >&2\n  exit 1\nfi\n\nif [[ ${#not_failing[@]} -gt 0 ]]; then\n  {\n    echo \"Some packages in hack/.staticcheck_failures are passing staticcheck. Please remove them.\"\n    echo\n    for p in \"${not_failing[@]}\"; do\n      echo \"  $p\"\n    done\n    echo\n  } >&2\n  exit 1\nfi\n\nif [[ ${#gone[@]} -gt 0 ]]; then\n  {\n    echo \"Some packages in hack/.staticcheck_failures do not exist anymore. Please remove them.\"\n    echo\n    for p in \"${gone[@]}\"; do\n      echo \"  $p\"\n    done\n    echo\n  } >&2\n  exit 1\nfi\n", "num_lines": 158}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to avoid regressions after a package is migrated\n# to structured logging. once a package is completely migrated add\n# it .structured_logging file to avoid any future regressions.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nkube::golang::verify_go_version\n\n# Ensure that we find the binaries we build before anything else.\nexport GOBIN=\"${KUBE_OUTPUT_BINPATH}\"\nPATH=\"${GOBIN}:${PATH}\"\n\n# Install logcheck\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  GO111MODULE=on go install k8s.io/klog/hack/tools/logcheck\npopd >/dev/null\n\n# We store packaged that are migrated in .structured_logging\nmigrated_packages_file=\"${KUBE_ROOT}/hack/.structured_logging\"\n\n# Ensure that file is sorted.\nkube::util::check-file-in-alphabetical-order \"${migrated_packages_file}\"\n\nmigrated_packages=()\nwhile IFS='' read -r line; do\n  migrated_packages+=(\"$KUBE_ROOT/$line\")\ndone < <(cat \"${migrated_packages_file}\")\n\n\nret=0\nGOOS=linux    logcheck \"${migrated_packages[@]}\" || ret=$?\nGOOS=windows  logcheck \"${migrated_packages[@]}\" || ret=$?\n\nif [ $ret -eq 0 ]; then\n  echo \"Structured logging static check is passed :).\"\nelse\n  echo \"Please fix above failures. You can locally test via:\"\n  echo \"hack/verify-structured-logging.sh\"\nfi\nexit $ret\n", "num_lines": 63}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether e2e test code which contains `Expect()` but not use\n# the e2e framework exists or not.\n# Usage: `hack/verify-test-code.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\ncd \"${KUBE_ROOT}\"\n\nall_e2e_files=()\n# NOTE: This checks e2e test code without the e2e framework which contains Expect().To(HaveOccurred())\nkube::util::read-array all_e2e_files < <(find test/e2e{,_node,_kubeadm} -name '*.go' | grep -v 'test/e2e/framework/')\nerrors_expect_no_error=()\nfor file in \"${all_e2e_files[@]}\"\ndo\n    if grep -E \"Expect\\(.*\\)\\.(NotTo|ToNot)\\(.*HaveOccurred\\(\\)\" \"${file}\" > /dev/null\n    then\n        errors_expect_no_error+=( \"${file}\" )\n    fi\n    if grep -E \"Expect\\(err\\)\\.To\\(gomega\\.BeNil\\(\\)\\)\" \"${file}\" > /dev/null\n    then\n        errors_expect_no_error+=( \"${file}\" )\n    fi\ndone\n\nerrors_expect_error=()\nfor file in \"${all_e2e_files[@]}\"\ndo\n    if grep \"Expect(.*)\\.To(.*HaveOccurred()\" \"${file}\" > /dev/null\n    then\n        errors_expect_error+=( \"${file}\" )\n    fi\ndone\n\nerrors_expect_no_equal=()\nfor file in \"${all_e2e_files[@]}\"\ndo\n    if grep -E \"Expect\\(.*\\)\\.(NotTo|ToNot)\\((gomega\\.Equal|Equal)\" \"${file}\" > /dev/null\n    then\n        errors_expect_no_equal+=( \"${file}\" )\n    fi\ndone\n\nerrors_expect_equal=()\nfor file in \"${all_e2e_files[@]}\"\ndo\n    if grep -E \"Expect\\(.*\\)\\.To\\((gomega\\.Equal|Equal)\" \"${file}\" > /dev/null\n    then\n        errors_expect_equal+=( \"${file}\" )\n    fi\ndone\n\nall_e2e_framework_files=()\nkube::util::read-array all_e2e_framework_files < <(find test/e2e/framework/ -name '*.go' | grep -v \"_test.go\")\nerrors_framework_contains_tests=()\nfor file in \"${all_e2e_framework_files[@]}\"\ndo\n    if grep -E \"(ConformanceIt\\(.*, func\\(\\) {|ginkgo.It\\(.*, func\\(\\) {)\" \"${file}\" > /dev/null\n    then\n        errors_framework_contains_tests+=( \"${file}\" )\n    fi\ndone\n\nif [ ${#errors_expect_no_error[@]} -ne 0 ]; then\n  {\n    echo \"Errors:\"\n    for err in \"${errors_expect_no_error[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'The above files need to use framework.ExpectNoError(err) instead of '\n    echo 'Expect(err).NotTo(HaveOccurred()) or gomega.Expect(err).NotTo(gomega.HaveOccurred())'\n    echo\n  } >&2\n  exit 1\nfi\n\nif [ ${#errors_expect_error[@]} -ne 0 ]; then\n  {\n    echo \"Errors:\"\n    for err in \"${errors_expect_error[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'The above files need to use framework.ExpectError(err) instead of '\n    echo 'Expect(err).To(HaveOccurred()) or gomega.Expect(err).To(gomega.HaveOccurred())'\n    echo\n  } >&2\n  exit 1\nfi\n\nif [ ${#errors_expect_no_equal[@]} -ne 0 ]; then\n  {\n    echo \"Errors:\"\n    for err in \"${errors_expect_no_equal[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'The above files need to use framework.ExpectNotEqual(foo, bar) instead of '\n    echo 'Expect(foo).NotTo(Equal(bar)) or gomega.Expect(foo).NotTo(gomega.Equal(bar))'\n    echo\n  } >&2\n  exit 1\nfi\n\nif [ ${#errors_expect_equal[@]} -ne 0 ]; then\n  {\n    echo \"Errors:\"\n    for err in \"${errors_expect_equal[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'The above files need to use framework.ExpectEqual(foo, bar) instead of '\n    echo 'Expect(foo).To(Equal(bar)) or gomega.Expect(foo).To(gomega.Equal(bar))'\n    echo\n  } >&2\n  exit 1\nfi\n\nif [ ${#errors_framework_contains_tests[@]} -ne 0 ]; then\n  {\n    echo \"Errors:\"\n    for err in \"${errors_framework_contains_tests[@]}\"; do\n      echo \"$err\"\n    done\n    echo\n    echo 'The above e2e framework files should not contain any e2e tests which are implemented '\n    echo 'with framework.ConformanceIt() or ginkgo.It()'\n    echo\n  } >&2\n  exit 1\nfi\n\necho 'Congratulations!  All e2e test source files are valid.'\n", "num_lines": 153}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether mutable global feature gate is invocated correctly\n# in `*_test.go` files.\n# Usage: `hack/verify-test-featuregates.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\ncd \"${KUBE_ROOT}\"\n\nrc=0\n\n# find test files accessing the mutable global feature gate or interface\ndirect_sets=$(find -L . -name '*_test.go' -exec grep -Hn 'MutableFeatureGate' {} \\; 2>/dev/null) || true\nif [[ -n \"${direct_sets}\" ]]; then\n  echo \"Test files may not access mutable global feature gates directly:\" >&2\n  echo \"${direct_sets}\" >&2\n  echo >&2\n  echo \"Use this invocation instead:\" >&2\n  echo \"  defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.<FeatureName>, <value>)()\" >&2\n  echo >&2\n  rc=1\nfi\n\n# find test files calling SetFeatureGateDuringTest and not calling the result\nmissing_defers=$(find -L . -name '*_test.go' -exec grep -Hn 'SetFeatureGateDuringTest' {} \\; 2>/dev/null | grep -E -v \"defer .*\\\\)\\\\(\\\\)$\") || true\nif [[ -n \"${missing_defers}\" ]]; then\n  echo \"Invalid invocations of featuregatetesting.SetFeatureGateDuringTest():\" >&2\n  echo \"${missing_defers}\" >&2\n  echo >&2\n  echo \"Always make a deferred call to the returned function to ensure the feature gate is reset:\" >&2\n  echo \"  defer featuregatetesting.SetFeatureGateDuringTest(t, utilfeature.DefaultFeatureGate, features.<FeatureName>, <value>)()\" >&2\n  echo >&2\n  rc=1\nfi\n\nexit $rc\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether the latest or untagged  gcr.io image is in\n# `test/e2e/*.go` files.\n# Usage: `hack/verify-test-images.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\ncd \"${KUBE_ROOT}\"\nresult=0\n\n# Find mentions of untagged gcr.io images in test/e2e/*.go\nfind_e2e_test_untagged_gcr_images() {\n    grep -o -E -e 'gcr.io/[-a-z0-9/_:.]+' test/e2e/*.go | grep -v -E \"gcr.io/.*:\" | cut -d \":\" -f 1 | LC_ALL=C sort -u\n}\n\n\n# Find mentions of latest gcr.io images in test/e2e/*.go\nfind_e2e_test_latest_gcr_images() {\n    grep -o -E -e 'gcr.io/.*:latest' test/e2e/*.go | cut -d \":\" -f 1 | LC_ALL=C sort -u\n}\n\nif find_e2e_test_latest_gcr_images; then\n  echo \"!!! Found :latest gcr.io images in the above files\"\n  result=1\nfi\n\nif find_e2e_test_untagged_gcr_images; then\n  echo \"!!! Found untagged gcr.io images in the above files\"\n  result=1\nfi\n\nexit ${result}\n", "num_lines": 52}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\ncd \"${KUBE_ROOT}\"\n# verify the dockerless build\n# https://github.com/kubernetes/enhancements/blob/master/keps/sig-node/1547-building-kubelet-without-docker/README.md\nhack/verify-typecheck.sh --skip-test --tags=dockerless --ignore-dirs=test\n\n# verify using go list\nif _out=\"$(go list -mod=readonly -tags \"dockerless\" -e -json  k8s.io/kubernetes/cmd/kubelet/... \\\n  | grep -e dockershim)\"; then\n    echo \"${_out}\" >&2\n    echo \"Verify typecheck for dockerless tag failed. Found restricted packages.\" >&2\n    exit 1\nfi\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script verifies the build without in-tree cloud providers.\n# Usage: `hack/verify-typecheck-providerless.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\ncd \"${KUBE_ROOT}\"\n# verify the providerless build\n# https://github.com/kubernetes/enhancements/blob/master/keps/sig-cloud-provider/1179-building-without-in-tree-providers/README.md\nhack/verify-typecheck.sh --skip-test --tags=providerless --ignore-dirs=test\n\n# verify using go list\nif _out=\"$(go list -mod=readonly -tags \"providerless\" -e -json  k8s.io/kubernetes/cmd/kubelet/... \\\n  | grep -e Azure/azure-sdk-for-go -e github.com/aws/aws-sdk-go -e google.golang.org/api)\"; then\n    echo \"${_out}\" >&2\n    echo \"Verify typecheck for providerless tag failed. Found restricted packages.\" >&2\n    exit 1\nfi\nif _out=\"$(go list -mod=readonly -tags \"providerless\" -e -json  k8s.io/kubernetes/cmd/kube-apiserver/... \\\n  | grep -e Azure/azure-sdk-for-go -e github.com/aws/aws-sdk-go -e google.golang.org/api \\\n         -e Azure/go-autorest -e oauth2/google)\"; then\n    echo \"${_out}\" >&2\n    echo \"Verify typecheck for providerless tag failed. Found restricted packages.\" >&2\n    exit 1\nfi\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script does a fast type check of kubernetes code for all platforms.\n# Usage: `hack/verify-typecheck.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${KUBE_ROOT}\"\n\nmake --no-print-directory -C \"${KUBE_ROOT}\" generated_files\n\n# As of June, 2020 the typecheck tool is written in terms of go/packages, but\n# that library doesn't work well with multiple modules.  Until that is done,\n# force this tooling to run in a fake GOPATH.\nret=0\nhack/run-in-gopath.sh \\\n    go run test/typecheck/main.go \"$@\" || ret=$?\nif [[ $ret -ne 0 ]]; then\n  echo \"!!! Type Check has failed. This may cause cross platform build failures.\" >&2\n  echo \"!!! Please see https://git.k8s.io/kubernetes/test/typecheck for more information.\" >&2\n  exit 1\nfi\n", "num_lines": 44}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether updating of licenses files is needed\n# or not. We should run `hack/update-vendor-licenses.sh` and commit the results,\n# if actually updates them.\n# Usage: `hack/verify-vendor-licenses.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# create a nice clean place to put our new licenses\nmkdir -p \"${KUBE_ROOT}/_tmp\"\n_tmpdir=\"$(mktemp -d \"${KUBE_ROOT}/_tmp/kube-licenses.XXXXXX\")\"\n#echo \"Created workspace: ${_tmpdir}\"\nfunction cleanup {\n  #echo \"Removing workspace: ${_tmpdir}\"\n  rm -rf \"${_tmpdir}\"\n}\nkube::util::trap_add cleanup EXIT\n\n# symlink all vendor subfolders in temp vendor\nmkdir -p \"${_tmpdir}/vendor\"\nfor child in \"${KUBE_ROOT}/vendor\"/*\ndo\n  ln -s \"${child}\" \"${_tmpdir}/vendor\"\ndone\n\nln -s \"${KUBE_ROOT}/LICENSE\" \"${_tmpdir}\"\nln -s \"${KUBE_ROOT}/staging\" \"${_tmpdir}\"\n\n# Update licenses\nLICENSE_ROOT=\"${_tmpdir}\" \"${KUBE_ROOT}/hack/update-vendor-licenses.sh\"\n\n# Compare licenses\nif ! _out=\"$(diff -Naupr -x OWNERS \"${KUBE_ROOT}/LICENSES\" \"${_tmpdir}/LICENSES\")\"; then\n  echo \"Your LICENSES tree is out of date. Run hack/update-vendor-licenses.sh and commit the results.\" >&2\n  echo \"${_out}\" >&2\n  exit 1\nfi\n", "num_lines": 58}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether fixing of vendor directory or go.mod is needed or\n# not. We should run `hack/update-vendor.sh` if actually fixes them.\n# Usage: `hack/verify-vendor.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# create a nice clean place to put our new vendor tree\nmkdir -p \"${KUBE_ROOT}/_tmp\"\n_tmpdir=\"$(mktemp -d \"${KUBE_ROOT}/_tmp/kube-vendor.XXXXXX\")\"\n\nif [[ -z ${KEEP_TMP:-} ]]; then\n    KEEP_TMP=false\nfi\n\nfunction cleanup {\n  # make go module dirs writeable\n  chmod -R +w \"${_tmpdir}\"\n  if [ \"${KEEP_TMP}\" == \"true\" ]; then\n    echo \"Leaving ${_tmpdir} for you to examine or copy. Please delete it manually when finished. (rm -rf ${_tmpdir})\"\n  else\n    echo \"Removing ${_tmpdir}\"\n    rm -rf \"${_tmpdir}\"\n  fi\n}\nkube::util::trap_add cleanup EXIT\n\n# Copy the contents of the kube directory into the nice clean place (which is NOT shaped like a GOPATH)\n_kubetmp=\"${_tmpdir}/kubernetes\"\nmkdir -p \"${_kubetmp}\"\ntar --exclude=.git --exclude=\"./_*\" -c . | (cd \"${_kubetmp}\" && tar xf -)\n\n# Do all our work in module mode\nexport GO111MODULE=on\n\npushd \"${_kubetmp}\" > /dev/null 2>&1\n  # Destroy deps in the copy of the kube tree\n  rm -rf ./vendor ./LICENSES\n\n  # Recreate the vendor tree using the nice clean set we just downloaded\n  hack/update-vendor.sh\npopd > /dev/null 2>&1\n\nret=0\n\npushd \"${KUBE_ROOT}\" > /dev/null 2>&1\n  # Test for diffs\n  if ! _out=\"$(diff -Naupr --ignore-matching-lines='^\\s*\\\"GoVersion\\\":' go.mod \"${_kubetmp}/go.mod\")\"; then\n    echo \"Your go.mod file is different:\" >&2\n    echo \"${_out}\" >&2\n    echo \"Vendor Verify failed.\" >&2\n    echo \"If you're seeing this locally, run the below command to fix your go.mod:\" >&2\n    echo \"hack/update-vendor.sh\" >&2\n    ret=1\n  fi\n\n  if ! _out=\"$(diff -Naupr -x \"BUILD\" -x \"AUTHORS*\" -x \"CONTRIBUTORS*\" vendor \"${_kubetmp}/vendor\")\"; then\n    echo \"Your vendored results are different:\" >&2\n    echo \"${_out}\" >&2\n    echo \"Vendor Verify failed.\" >&2\n    echo \"${_out}\" > vendordiff.patch\n    echo \"If you're seeing this locally, run the below command to fix your directories:\" >&2\n    echo \"hack/update-vendor.sh\" >&2\n    ret=1\n  fi\n\n  # Verify we are pinned to matching levels\n  hack/lint-dependencies.sh >&2\npopd > /dev/null 2>&1\n\nif [[ ${ret} -gt 0 ]]; then\n  exit ${ret}\nfi\n\necho \"Vendor Verified.\"\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 97}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\n: \"${KUBECTL:=${KUBE_ROOT}/cluster/kubectl.sh}\"\n: \"${KUBE_CONFIG_FILE:=\"config-test.sh\"}\"\n\nexport KUBECTL KUBE_CONFIG_FILE\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nprepare-e2e\n\n#TODO(colhom): spec and implement federated version of this\n${KUBECTL} get nodes --no-headers | wc -l\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\n: \"${KUBECTL:=${KUBE_ROOT}/cluster/kubectl.sh}\"\n: \"${KUBE_CONFIG_FILE:=\"config-test.sh\"}\"\n\nexport KUBECTL KUBE_CONFIG_FILE\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nprepare-e2e\n\ntest-teardown\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\nif [[ -n \"${1:-}\" ]]; then\n  export KUBE_GCE_ZONE=\"${1}\"\nfi\nif [[ -n \"${2:-}\" ]]; then\n  export MULTIZONE=\"${2}\"\nfi\nif [[ -n \"${3:-}\" ]]; then\n  export KUBE_REPLICATE_EXISTING_MASTER=\"${3}\"\nfi\nif [[ -n \"${4:-}\" ]]; then\n  export KUBE_USE_EXISTING_MASTER=\"${4}\"\nfi\nif [[ -z \"${NUM_NODES:-}\" ]]; then\n  export NUM_NODES=3\nfi\n\nsource \"${KUBE_ROOT}/hack/e2e-internal/e2e-up.sh\"\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\nif [[ -n \"${1:-}\" ]]; then\n  export KUBE_GCE_ZONE=\"${1}\"\nfi\nif [[ -n \"${2:-}\" ]]; then\n  export MULTIZONE=\"${2}\"\nfi\nif [[ -n \"${3:-}\" ]]; then\n  export KUBE_DELETE_NODES=\"${3}\"\nfi\nif [[ -n \"${4:-}\" ]]; then\n  export KUBE_USE_EXISTING_MASTER=\"${4}\"\nfi\n\nsource \"${KUBE_ROOT}/hack/e2e-internal/e2e-down.sh\"\n\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\n: \"${KUBECTL:=${KUBE_ROOT}/cluster/kubectl.sh}\"\n: \"${KUBE_CONFIG_FILE:=\"config-test.sh\"}\"\n\nexport KUBECTL KUBE_CONFIG_FILE\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nprepare-e2e\n\n${KUBECTL} version\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\n: \"${KUBECTL:=${KUBE_ROOT}/cluster/kubectl.sh}\"\n: \"${KUBE_CONFIG_FILE:=\"config-test.sh\"}\"\n\nexport KUBECTL KUBE_CONFIG_FILE\n\nsource \"${KUBE_ROOT}/cluster/kube-util.sh\"\n\nprepare-e2e\n\ntest-setup\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to generate docs from the latest swagger spec.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\ncd /build\n\n# gendocs takes \"input.json\" as the input swagger spec.\n# $1 is expected to be <group>_<version>\ncp /swagger-source/\"$1\".json input.json\n\n./gradle-2.5/bin/gradle gendocs --info\n\n#insert a TOC for top level API objects\nbuf=\"== Top Level API Objects\\n\\n\"\ntop_level_models=$(grep '&[A-Za-z]*{},' /register.go | sed 's/.*&//;s/{},//')\n\n# check if the top level models exist in the definitions.adoc. If they exist,\n# their name will be <version>.<model_name>\nVERSION=\"${1#*_}\"\nfor m in ${top_level_models}\ndo\n  if grep -xq \"=== ${VERSION}.${m}\" ./definitions.adoc\n  then\n    buf+=\"* <<${VERSION}.${m}>>\\n\"\n  fi\ndone\nsed -i \"1i ${buf}\" ./definitions.adoc\n\n# fix the links in .adoc, replace <<x.y>> with link:definitions.html#_x_y[x.y], and lowercase the _x_y part\nsed -i -e 's|<<\\(.*\\)\\.\\(.*\\)>>|link:#_\\L\\1_\\2\\E[\\1.\\2]|g' ./definitions.adoc\nsed -i -e 's|<<\\(.*\\)\\.\\(.*\\)>>|link:../definitions#_\\L\\1_\\2\\E[\\1.\\2]|g' ./paths.adoc\n\n# fix the link to <<any>>\nsed -i -e 's|<<any>>|link:#_any[any]|g' ./definitions.adoc\nsed -i -e 's|<<any>>|link:../definitions#_any[any]|g' ./paths.adoc\n\n# change the title of paths.adoc from \"paths\" to \"operations\"\nsed -i 's|== Paths|== Operations|g' ./paths.adoc\n\n# $$ has special meaning in asciidoc, we need to escape it\nsed -i 's|\\$\\$|+++$$+++|g' ./definitions.adoc\n\necho -e \"=== any\\nRepresents an untyped JSON map - see the description of the field for more info about the structure of this object.\" >> ./definitions.adoc\n\nasciidoctor definitions.adoc\nasciidoctor paths.adoc\n\ncp definitions.html /output/\ncp paths.html /output/operations.html\n\necho \"SUCCESS\"\n", "num_lines": 70}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\nretry() {\n  for i in {1..5}; do\n    if \"$@\"\n    then\n      return 0\n    else\n      sleep \"${i}\"\n    fi\n  done\n  \"$@\"\n}\n\n# The root of the build/dist directory\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nexport KUBE_ROOT\n\n# Runs benchmark integration tests, producing pretty-printed results\n# in ${WORKSPACE}/artifacts. This script can also be run within a\n# kubekins-test container with a kubernetes repo mounted (at the path\n# /go/src/k8s.io/kubernetes).\n\nexport PATH=${GOPATH}/bin:${PWD}/third_party/etcd:/usr/local/go/bin:${PATH}\n\n# Until all GOPATH references are removed from all build scripts as well,\n# explicitly disable module mode to avoid picking up user-set GO111MODULE preferences.\n# As individual scripts make use of go modules, they can explicitly set GO111MODULE=on\nexport GO111MODULE=off\n\n# Install tools we need\npushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n  GO111MODULE=on go install github.com/cespare/prettybench\n  GO111MODULE=on go install gotest.tools/gotestsum\npopd >/dev/null\n\n# Disable the Go race detector.\nexport KUBE_RACE=\" \"\n# Disable coverage report\nexport KUBE_COVER=\"n\"\nexport ARTIFACTS=${ARTIFACTS:-\"${WORKSPACE}/artifacts\"}\nexport FULL_LOG=\"true\"\n\nmkdir -p \"${ARTIFACTS}\"\ncd \"${GOPATH}/src/k8s.io/kubernetes\"\n\n./hack/install-etcd.sh\n\n# Run the benchmark tests and pretty-print the results into a separate file.\nmake test-integration WHAT=\"$*\" KUBE_TEST_ARGS=\"-run='XXX' -bench=${TEST_PREFIX:-.} -benchtime=${BENCHTIME:-1s} -benchmem  -alsologtostderr=false -logtostderr=false -data-items-dir=${ARTIFACTS}\" \\\n  | (go run test/integration/benchmark/extractlog/main.go) \\\n  | tee \\\n   >(prettybench -no-passthrough > \"${ARTIFACTS}/BenchmarkResults.txt\") \\\n   >(go run test/integration/benchmark/jsonify/main.go \"${ARTIFACTS}/BenchmarkResults_benchmark_$(date -u +%Y-%m-%dT%H:%M:%SZ).json\" || cat > /dev/null)\n", "num_lines": 74}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# Runs the unit and integration tests, producing JUnit-style XML test\n# reports in ${WORKSPACE}/artifacts. This script is intended to be run from\n# kubekins-test container with a kubernetes repo mapped in. See\n# k8s.io/test-infra/scenarios/kubernetes_verify.py\n\nexport PATH=${GOPATH}/bin:${PWD}/third_party/etcd:/usr/local/go/bin:${PATH}\n\n# Until all GOPATH references are removed from all build scripts as well,\n# explicitly disable module mode to avoid picking up user-set GO111MODULE preferences.\n# As individual scripts make use of go modules, they can explicitly set GO111MODULE=on\nexport GO111MODULE=off\n\n# Install tools we need\npushd \"./hack/tools\" >/dev/null\n  GO111MODULE=on go install gotest.tools/gotestsum\npopd >/dev/null\n\n# Disable coverage report\nexport KUBE_COVER=\"n\"\n# Set artifacts directory\nexport ARTIFACTS=${ARTIFACTS:-\"${WORKSPACE}/artifacts\"}\n# Save the verbose stdout as well.\nexport KUBE_KEEP_VERBOSE_TEST_OUTPUT=y\nexport KUBE_INTEGRATION_TEST_MAX_CONCURRENCY=4\nexport LOG_LEVEL=4\n\ncd \"${GOPATH}/src/k8s.io/kubernetes\"\n\nmake generated_files\ngo install ./cmd/...\n./hack/install-etcd.sh\n\nmake test-cmd\nmake test-integration\n", "num_lines": 56}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\nretry() {\n  for i in {1..5}; do\n    if \"$@\"; then\n      return 0\n    else\n      sleep \"${i}\"\n    fi\n  done\n  \"$@\"\n}\n\n# This script is intended to be run from kubekins-test container with a\n# kubernetes repo mapped in. See k8s.io/test-infra/scenarios/kubernetes_verify.py\n\nexport PATH=${GOPATH}/bin:${PWD}/third_party/etcd:/usr/local/go/bin:${PATH}\n\n# Set artifacts directory\nexport ARTIFACTS=${ARTIFACTS:-\"${WORKSPACE}/artifacts\"}\n# Produce a JUnit-style XML test report\nexport KUBE_JUNIT_REPORT_DIR=\"${ARTIFACTS}\"\n\nexport LOG_LEVEL=4\n\ncd \"${GOPATH}/src/k8s.io/kubernetes\"\n\nmake verify\n", "num_lines": 48}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A set of helpers for starting/running etcd for tests\n\nETCD_VERSION=${ETCD_VERSION:-3.5.0-rc.0}\nETCD_HOST=${ETCD_HOST:-127.0.0.1}\nETCD_PORT=${ETCD_PORT:-2379}\nexport KUBE_INTEGRATION_ETCD_URL=\"http://${ETCD_HOST}:${ETCD_PORT}\"\n\nkube::etcd::validate() {\n  # validate if in path\n  command -v etcd >/dev/null || {\n    kube::log::usage \"etcd must be in your PATH\"\n    kube::log::info \"You can use 'hack/install-etcd.sh' to install a copy in third_party/.\"\n    exit 1\n  }\n\n  # validate etcd port is free\n  local port_check_command\n  if command -v ss &> /dev/null && ss -Version | grep 'iproute2' &> /dev/null; then\n    port_check_command=\"ss\"\n  elif command -v netstat &>/dev/null; then\n    port_check_command=\"netstat\"\n  else\n    kube::log::usage \"unable to identify if etcd is bound to port ${ETCD_PORT}. unable to find ss or netstat utilities.\"\n    exit 1\n  fi\n  if ${port_check_command} -nat | grep \"LISTEN\" | grep \"[\\.:]${ETCD_PORT:?}\" >/dev/null 2>&1; then\n    kube::log::usage \"unable to start etcd as port ${ETCD_PORT} is in use. please stop the process listening on this port and retry.\"\n    kube::log::usage \"$(netstat -nat | grep \"[\\.:]${ETCD_PORT:?} .*LISTEN\")\"\n    exit 1\n  fi\n\n  # need set the env of \"ETCD_UNSUPPORTED_ARCH\" on unstable arch.\n  arch=$(uname -m)\n  if [[ $arch =~ aarch* ]]; then\n\t  export ETCD_UNSUPPORTED_ARCH=arm64\n  elif [[ $arch =~ arm* ]]; then\n\t  export ETCD_UNSUPPORTED_ARCH=arm\n  fi\n  # validate installed version is at least equal to minimum\n  version=$(etcd --version | grep Version | head -n 1 | cut -d \" \" -f 3)\n  if [[ $(kube::etcd::version \"${ETCD_VERSION}\") -gt $(kube::etcd::version \"${version}\") ]]; then\n   export PATH=${KUBE_ROOT}/third_party/etcd:${PATH}\n   hash etcd\n   echo \"${PATH}\"\n   version=$(etcd --version | grep Version | head -n 1 | cut -d \" \" -f 3)\n   if [[ $(kube::etcd::version \"${ETCD_VERSION}\") -gt $(kube::etcd::version \"${version}\") ]]; then\n    kube::log::usage \"etcd version ${ETCD_VERSION} or greater required.\"\n    kube::log::info \"You can use 'hack/install-etcd.sh' to install a copy in third_party/.\"\n    exit 1\n   fi\n  fi\n}\n\nkube::etcd::version() {\n  printf '%s\\n' \"${@}\" | awk -F . '{ printf(\"%d%03d%03d\\n\", $1, $2, $3) }'\n}\n\nkube::etcd::start() {\n  # validate before running\n  kube::etcd::validate\n\n  # Start etcd\n  ETCD_DIR=${ETCD_DIR:-$(mktemp -d 2>/dev/null || mktemp -d -t test-etcd.XXXXXX)}\n  if [[ -d \"${ARTIFACTS:-}\" ]]; then\n    ETCD_LOGFILE=\"${ARTIFACTS}/etcd.$(uname -n).$(id -un).log.DEBUG.$(date +%Y%m%d-%H%M%S).$$\"\n  else\n    ETCD_LOGFILE=${ETCD_LOGFILE:-\"/dev/null\"}\n  fi\n  kube::log::info \"etcd --advertise-client-urls ${KUBE_INTEGRATION_ETCD_URL} --data-dir ${ETCD_DIR} --listen-client-urls http://${ETCD_HOST}:${ETCD_PORT} --log-level=debug > \\\"${ETCD_LOGFILE}\\\" 2>/dev/null\"\n  etcd --advertise-client-urls \"${KUBE_INTEGRATION_ETCD_URL}\" --data-dir \"${ETCD_DIR}\" --listen-client-urls \"${KUBE_INTEGRATION_ETCD_URL}\" --log-level=debug 2> \"${ETCD_LOGFILE}\" >/dev/null &\n  ETCD_PID=$!\n\n  echo \"Waiting for etcd to come up.\"\n  kube::util::wait_for_url \"${KUBE_INTEGRATION_ETCD_URL}/health\" \"etcd: \" 0.25 80\n  curl -fs -X POST \"${KUBE_INTEGRATION_ETCD_URL}/v3/kv/put\" -d '{\"key\": \"X3Rlc3Q=\", \"value\": \"\"}'\n}\n\nkube::etcd::stop() {\n  if [[ -n \"${ETCD_PID-}\" ]]; then\n    kill \"${ETCD_PID}\" &>/dev/null || :\n    wait \"${ETCD_PID}\" &>/dev/null || :\n  fi\n}\n\nkube::etcd::clean_etcd_dir() {\n  if [[ -n \"${ETCD_DIR-}\" ]]; then\n    rm -rf \"${ETCD_DIR}\"\n  fi\n}\n\nkube::etcd::cleanup() {\n  kube::etcd::stop\n  kube::etcd::clean_etcd_dir\n}\n\nkube::etcd::install() {\n  (\n    local os\n    local arch\n\n    os=$(kube::util::host_os)\n    arch=$(kube::util::host_arch)\n\n    cd \"${KUBE_ROOT}/third_party\" || return 1\n    if [[ $(readlink etcd) == etcd-v${ETCD_VERSION}-${os}-* ]]; then\n      kube::log::info \"etcd v${ETCD_VERSION} already installed. To use:\"\n      kube::log::info \"export PATH=\\\"$(pwd)/etcd:\\${PATH}\\\"\"\n      return  #already installed\n    fi\n\n    if [[ ${os} == \"darwin\" ]]; then\n      download_file=\"etcd-v${ETCD_VERSION}-darwin-amd64.zip\"\n      url=\"https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/${download_file}\"\n      kube::util::download_file \"${url}\" \"${download_file}\"\n      unzip -o \"${download_file}\"\n      ln -fns \"etcd-v${ETCD_VERSION}-darwin-amd64\" etcd\n      rm \"${download_file}\"\n    else\n      url=\"https://github.com/coreos/etcd/releases/download/v${ETCD_VERSION}/etcd-v${ETCD_VERSION}-linux-${arch}.tar.gz\"\n      download_file=\"etcd-v${ETCD_VERSION}-linux-${arch}.tar.gz\"\n      kube::util::download_file \"${url}\" \"${download_file}\"\n      tar xzf \"${download_file}\"\n      ln -fns \"etcd-v${ETCD_VERSION}-linux-${arch}\" etcd\n      rm \"${download_file}\"\n    fi\n    kube::log::info \"etcd v${ETCD_VERSION} installed. To use:\"\n    kube::log::info \"export PATH=\\\"$(pwd)/etcd:\\${PATH}\\\"\"\n  )\n}\n", "num_lines": 146}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# shellcheck disable=SC2034 # Variables sourced in other scripts.\n\n# The golang package that we are building.\nreadonly KUBE_GO_PACKAGE=k8s.io/kubernetes\nreadonly KUBE_GOPATH=\"${KUBE_OUTPUT}/go\"\n\n# The server platform we are building on.\nreadonly KUBE_SUPPORTED_SERVER_PLATFORMS=(\n  linux/amd64\n  linux/arm\n  linux/arm64\n  linux/s390x\n  linux/ppc64le\n)\n\n# The node platforms we build for\nreadonly KUBE_SUPPORTED_NODE_PLATFORMS=(\n  linux/amd64\n  linux/arm\n  linux/arm64\n  linux/s390x\n  linux/ppc64le\n  windows/amd64\n)\n\n# If we update this we should also update the set of platforms whose standard\n# library is precompiled for in build/build-image/cross/Dockerfile\nreadonly KUBE_SUPPORTED_CLIENT_PLATFORMS=(\n  linux/amd64\n  linux/386\n  linux/arm\n  linux/arm64\n  linux/s390x\n  linux/ppc64le\n  darwin/amd64\n  darwin/arm64\n  windows/amd64\n  windows/386\n)\n\n# Which platforms we should compile test targets for.\n# Not all client platforms need these tests\nreadonly KUBE_SUPPORTED_TEST_PLATFORMS=(\n  linux/amd64\n  linux/arm\n  linux/arm64\n  linux/s390x\n  linux/ppc64le\n  darwin/amd64\n  darwin/arm64\n  windows/amd64\n)\n\n# The set of server targets that we are only building for Linux\n# If you update this list, please also update build/BUILD.\nkube::golang::server_targets() {\n  local targets=(\n    cmd/kube-proxy\n    cmd/kube-apiserver\n    cmd/kube-controller-manager\n    cmd/kubelet\n    cmd/kubeadm\n    cmd/kube-scheduler\n    vendor/k8s.io/kube-aggregator\n    vendor/k8s.io/apiextensions-apiserver\n    cluster/gce/gci/mounter\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_SERVER_TARGETS <<< \"$(kube::golang::server_targets)\"\nreadonly KUBE_SERVER_TARGETS\nreadonly KUBE_SERVER_BINARIES=(\"${KUBE_SERVER_TARGETS[@]##*/}\")\n\n# The set of server targets we build docker images for\nkube::golang::server_image_targets() {\n  # NOTE: this contains cmd targets for kube::build::get_docker_wrapped_binaries\n  local targets=(\n    cmd/kube-apiserver\n    cmd/kube-controller-manager\n    cmd/kube-scheduler\n    cmd/kube-proxy\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_SERVER_IMAGE_TARGETS <<< \"$(kube::golang::server_image_targets)\"\nreadonly KUBE_SERVER_IMAGE_TARGETS\nreadonly KUBE_SERVER_IMAGE_BINARIES=(\"${KUBE_SERVER_IMAGE_TARGETS[@]##*/}\")\n\n# The set of conformance targets we build docker image for\nkube::golang::conformance_image_targets() {\n  # NOTE: this contains cmd targets for kube::release::build_conformance_image\n  local targets=(\n    vendor/github.com/onsi/ginkgo/ginkgo\n    test/e2e/e2e.test\n    cluster/images/conformance/go-runner\n    cmd/kubectl\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_CONFORMANCE_IMAGE_TARGETS <<< \"$(kube::golang::conformance_image_targets)\"\nreadonly KUBE_CONFORMANCE_IMAGE_TARGETS\n\n# The set of server targets that we are only building for Kubernetes nodes\n# If you update this list, please also update build/BUILD.\nkube::golang::node_targets() {\n  local targets=(\n    cmd/kube-proxy\n    cmd/kubeadm\n    cmd/kubelet\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_NODE_TARGETS <<< \"$(kube::golang::node_targets)\"\nreadonly KUBE_NODE_TARGETS\nreadonly KUBE_NODE_BINARIES=(\"${KUBE_NODE_TARGETS[@]##*/}\")\nreadonly KUBE_NODE_BINARIES_WIN=(\"${KUBE_NODE_BINARIES[@]/%/.exe}\")\n\n# ------------\n# NOTE: All functions that return lists should use newlines.\n# bash functions can't return arrays, and spaces are tricky, so newline\n# separators are the preferred pattern.\n# To transform a string of newline-separated items to an array, use kube::util::read-array:\n# kube::util::read-array FOO < <(kube::golang::dups a b c a)\n#\n# ALWAYS remember to quote your subshells. Not doing so will break in\n# bash 4.3, and potentially cause other issues.\n# ------------\n\n# Returns a sorted newline-separated list containing only duplicated items.\nkube::golang::dups() {\n  # We use printf to insert newlines, which are required by sort.\n  printf \"%s\\n\" \"$@\" | sort | uniq -d\n}\n\n# Returns a sorted newline-separated list with duplicated items removed.\nkube::golang::dedup() {\n  # We use printf to insert newlines, which are required by sort.\n  printf \"%s\\n\" \"$@\" | sort -u\n}\n\n# Depends on values of user-facing KUBE_BUILD_PLATFORMS, KUBE_FASTBUILD,\n# and KUBE_BUILDER_OS.\n# Configures KUBE_SERVER_PLATFORMS, KUBE_NODE_PLATFOMRS,\n# KUBE_TEST_PLATFORMS, and KUBE_CLIENT_PLATFORMS, then sets them\n# to readonly.\n# The configured vars will only contain platforms allowed by the\n# KUBE_SUPPORTED* vars at the top of this file.\ndeclare -a KUBE_SERVER_PLATFORMS\ndeclare -a KUBE_CLIENT_PLATFORMS\ndeclare -a KUBE_NODE_PLATFORMS\ndeclare -a KUBE_TEST_PLATFORMS\nkube::golang::setup_platforms() {\n  if [[ -n \"${KUBE_BUILD_PLATFORMS:-}\" ]]; then\n    # KUBE_BUILD_PLATFORMS needs to be read into an array before the next\n    # step, or quoting treats it all as one element.\n    local -a platforms\n    IFS=\" \" read -ra platforms <<< \"${KUBE_BUILD_PLATFORMS}\"\n\n    # Deduplicate to ensure the intersection trick with kube::golang::dups\n    # is not defeated by duplicates in user input.\n    kube::util::read-array platforms < <(kube::golang::dedup \"${platforms[@]}\")\n\n    # Use kube::golang::dups to restrict the builds to the platforms in\n    # KUBE_SUPPORTED_*_PLATFORMS. Items should only appear at most once in each\n    # set, so if they appear twice after the merge they are in the intersection.\n    kube::util::read-array KUBE_SERVER_PLATFORMS < <(kube::golang::dups \\\n        \"${platforms[@]}\" \\\n        \"${KUBE_SUPPORTED_SERVER_PLATFORMS[@]}\" \\\n      )\n    readonly KUBE_SERVER_PLATFORMS\n\n    kube::util::read-array KUBE_NODE_PLATFORMS < <(kube::golang::dups \\\n        \"${platforms[@]}\" \\\n        \"${KUBE_SUPPORTED_NODE_PLATFORMS[@]}\" \\\n      )\n    readonly KUBE_NODE_PLATFORMS\n\n    kube::util::read-array KUBE_TEST_PLATFORMS < <(kube::golang::dups \\\n        \"${platforms[@]}\" \\\n        \"${KUBE_SUPPORTED_TEST_PLATFORMS[@]}\" \\\n      )\n    readonly KUBE_TEST_PLATFORMS\n\n    kube::util::read-array KUBE_CLIENT_PLATFORMS < <(kube::golang::dups \\\n        \"${platforms[@]}\" \\\n        \"${KUBE_SUPPORTED_CLIENT_PLATFORMS[@]}\" \\\n      )\n    readonly KUBE_CLIENT_PLATFORMS\n\n  elif [[ \"${KUBE_FASTBUILD:-}\" == \"true\" ]]; then\n    host_arch=$(kube::util::host_arch)\n    if [[ \"${host_arch}\" != \"amd64\" && \"${host_arch}\" != \"arm64\" ]]; then\n      # on any platform other than amd64 and arm64, we just default to amd64\n      host_arch=\"amd64\"\n    fi\n    KUBE_SERVER_PLATFORMS=(\"linux/${host_arch}\")\n    readonly KUBE_SERVER_PLATFORMS\n    KUBE_NODE_PLATFORMS=(\"linux/${host_arch}\")\n    readonly KUBE_NODE_PLATFORMS\n    if [[ \"${KUBE_BUILDER_OS:-}\" == \"darwin\"* ]]; then\n      KUBE_TEST_PLATFORMS=(\n        \"darwin/${host_arch}\"\n        \"linux/${host_arch}\"\n      )\n      readonly KUBE_TEST_PLATFORMS\n      KUBE_CLIENT_PLATFORMS=(\n        \"darwin/${host_arch}\"\n        \"linux/${host_arch}\"\n      )\n      readonly KUBE_CLIENT_PLATFORMS\n    else\n      KUBE_TEST_PLATFORMS=(\"linux/${host_arch}\")\n      readonly KUBE_TEST_PLATFORMS\n      KUBE_CLIENT_PLATFORMS=(\"linux/${host_arch}\")\n      readonly KUBE_CLIENT_PLATFORMS\n    fi\n  else\n    KUBE_SERVER_PLATFORMS=(\"${KUBE_SUPPORTED_SERVER_PLATFORMS[@]}\")\n    readonly KUBE_SERVER_PLATFORMS\n\n    KUBE_NODE_PLATFORMS=(\"${KUBE_SUPPORTED_NODE_PLATFORMS[@]}\")\n    readonly KUBE_NODE_PLATFORMS\n\n    KUBE_CLIENT_PLATFORMS=(\"${KUBE_SUPPORTED_CLIENT_PLATFORMS[@]}\")\n    readonly KUBE_CLIENT_PLATFORMS\n\n    KUBE_TEST_PLATFORMS=(\"${KUBE_SUPPORTED_TEST_PLATFORMS[@]}\")\n    readonly KUBE_TEST_PLATFORMS\n  fi\n}\n\nkube::golang::setup_platforms\n\n# The set of client targets that we are building for all platforms\n# If you update this list, please also update build/BUILD.\nreadonly KUBE_CLIENT_TARGETS=(\n  cmd/kubectl\n  cmd/kubectl-convert\n)\nreadonly KUBE_CLIENT_BINARIES=(\"${KUBE_CLIENT_TARGETS[@]##*/}\")\nreadonly KUBE_CLIENT_BINARIES_WIN=(\"${KUBE_CLIENT_BINARIES[@]/%/.exe}\")\n\n# The set of test targets that we are building for all platforms\n# If you update this list, please also update build/BUILD.\nkube::golang::test_targets() {\n  local targets=(\n    cmd/gendocs\n    cmd/genkubedocs\n    cmd/genman\n    cmd/genyaml\n    cmd/genswaggertypedocs\n    cmd/linkcheck\n    vendor/github.com/onsi/ginkgo/ginkgo\n    test/e2e/e2e.test\n    cluster/images/conformance/go-runner\n  )\n  echo \"${targets[@]}\"\n}\nIFS=\" \" read -ra KUBE_TEST_TARGETS <<< \"$(kube::golang::test_targets)\"\nreadonly KUBE_TEST_TARGETS\nreadonly KUBE_TEST_BINARIES=(\"${KUBE_TEST_TARGETS[@]##*/}\")\nreadonly KUBE_TEST_BINARIES_WIN=(\"${KUBE_TEST_BINARIES[@]/%/.exe}\")\n# If you update this list, please also update build/BUILD.\nreadonly KUBE_TEST_PORTABLE=(\n  test/e2e/testing-manifests\n  test/kubemark\n  hack/e2e-internal\n  hack/get-build.sh\n  hack/ginkgo-e2e.sh\n  hack/lib\n)\n\n# Test targets which run on the Kubernetes clusters directly, so we only\n# need to target server platforms.\n# These binaries will be distributed in the kubernetes-test tarball.\n# If you update this list, please also update build/BUILD.\nkube::golang::server_test_targets() {\n  local targets=(\n    cmd/kubemark\n    vendor/github.com/onsi/ginkgo/ginkgo\n  )\n\n  if [[ \"${OSTYPE:-}\" == \"linux\"* ]]; then\n    targets+=( test/e2e_node/e2e_node.test )\n  fi\n\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_TEST_SERVER_TARGETS <<< \"$(kube::golang::server_test_targets)\"\nreadonly KUBE_TEST_SERVER_TARGETS\nreadonly KUBE_TEST_SERVER_BINARIES=(\"${KUBE_TEST_SERVER_TARGETS[@]##*/}\")\nreadonly KUBE_TEST_SERVER_PLATFORMS=(\"${KUBE_SERVER_PLATFORMS[@]:+\"${KUBE_SERVER_PLATFORMS[@]}\"}\")\n\n# Gigabytes necessary for parallel platform builds.\n# As of March 2021 (go 1.16/amd64), the RSS usage is 2GiB by using cached\n# memory of 15GiB.\n# This variable can be overwritten at your own risk.\n# It's defaulting to 20G to provide some headroom.\nreadonly KUBE_PARALLEL_BUILD_MEMORY=${KUBE_PARALLEL_BUILD_MEMORY:-20}\n\nreadonly KUBE_ALL_TARGETS=(\n  \"${KUBE_SERVER_TARGETS[@]}\"\n  \"${KUBE_CLIENT_TARGETS[@]}\"\n  \"${KUBE_TEST_TARGETS[@]}\"\n  \"${KUBE_TEST_SERVER_TARGETS[@]}\"\n)\nreadonly KUBE_ALL_BINARIES=(\"${KUBE_ALL_TARGETS[@]##*/}\")\n\nreadonly KUBE_STATIC_LIBRARIES=(\n  kube-apiserver\n  kube-controller-manager\n  kube-scheduler\n  kube-proxy\n  kubeadm\n  kubectl\n)\n\n# Fully-qualified package names that we want to instrument for coverage information.\nreadonly KUBE_COVERAGE_INSTRUMENTED_PACKAGES=(\n  k8s.io/kubernetes/cmd/kube-apiserver\n  k8s.io/kubernetes/cmd/kube-controller-manager\n  k8s.io/kubernetes/cmd/kube-scheduler\n  k8s.io/kubernetes/cmd/kube-proxy\n  k8s.io/kubernetes/cmd/kubelet\n)\n\n# KUBE_CGO_OVERRIDES is a space-separated list of binaries which should be built\n# with CGO enabled, assuming CGO is supported on the target platform.\n# This overrides any entry in KUBE_STATIC_LIBRARIES.\nIFS=\" \" read -ra KUBE_CGO_OVERRIDES_LIST <<< \"${KUBE_CGO_OVERRIDES:-}\"\nreadonly KUBE_CGO_OVERRIDES_LIST\n# KUBE_STATIC_OVERRIDES is a space-separated list of binaries which should be\n# built with CGO disabled. This is in addition to the list in\n# KUBE_STATIC_LIBRARIES.\nIFS=\" \" read -ra KUBE_STATIC_OVERRIDES_LIST <<< \"${KUBE_STATIC_OVERRIDES:-}\"\nreadonly KUBE_STATIC_OVERRIDES_LIST\n\nkube::golang::is_statically_linked_library() {\n  local e\n  # Explicitly enable cgo when building kubectl for darwin from darwin.\n  [[ \"$(go env GOHOSTOS)\" == \"darwin\" && \"$(go env GOOS)\" == \"darwin\" &&\n    \"$1\" == *\"/kubectl\" ]] && return 1\n  if [[ -n \"${KUBE_CGO_OVERRIDES_LIST:+x}\" ]]; then\n    for e in \"${KUBE_CGO_OVERRIDES_LIST[@]}\"; do [[ \"${1}\" == *\"/${e}\" ]] && return 1; done;\n  fi\n  for e in \"${KUBE_STATIC_LIBRARIES[@]}\"; do [[ \"${1}\" == *\"/${e}\" ]] && return 0; done;\n  if [[ -n \"${KUBE_STATIC_OVERRIDES_LIST:+x}\" ]]; then\n    for e in \"${KUBE_STATIC_OVERRIDES_LIST[@]}\"; do [[ \"${1}\" == *\"/${e}\" ]] && return 0; done;\n  fi\n  return 1;\n}\n\n# kube::binaries_from_targets take a list of build targets and return the\n# full go package to be built\nkube::golang::binaries_from_targets() {\n  local target\n  for target; do\n    # If the target starts with what looks like a domain name, assume it has a\n    # fully-qualified package name rather than one that needs the Kubernetes\n    # package prepended.\n    if [[ \"${target}\" =~ ^([[:alnum:]]+\".\")+[[:alnum:]]+\"/\" ]]; then\n      echo \"${target}\"\n    else\n      echo \"${KUBE_GO_PACKAGE}/${target}\"\n    fi\n  done\n}\n\n# Asks golang what it thinks the host platform is. The go tool chain does some\n# slightly different things when the target platform matches the host platform.\nkube::golang::host_platform() {\n  echo \"$(go env GOHOSTOS)/$(go env GOHOSTARCH)\"\n}\n\n# Takes the platform name ($1) and sets the appropriate golang env variables\n# for that platform.\nkube::golang::set_platform_envs() {\n  [[ -n ${1-} ]] || {\n    kube::log::error_exit \"!!! Internal error. No platform set in kube::golang::set_platform_envs\"\n  }\n\n  export GOOS=${platform%/*}\n  export GOARCH=${platform##*/}\n\n  # Do not set CC when building natively on a platform, only if cross-compiling\n  if [[ $(kube::golang::host_platform) != \"$platform\" ]]; then\n    # Dynamic CGO linking for other server architectures than host architecture goes here\n    # If you want to include support for more server platforms than these, add arch-specific gcc names here\n    case \"${platform}\" in\n      \"linux/amd64\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_AMD64_CC:-x86_64-linux-gnu-gcc}\n        ;;\n      \"linux/386\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_386_CC:-i686-linux-gnu-gcc}\n        ;;\n      \"linux/arm\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_ARM_CC:-arm-linux-gnueabihf-gcc}\n        ;;\n      \"linux/arm64\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_ARM64_CC:-aarch64-linux-gnu-gcc}\n        ;;\n      \"linux/ppc64le\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_PPC64LE_CC:-powerpc64le-linux-gnu-gcc}\n        ;;\n      \"linux/s390x\")\n        export CGO_ENABLED=1\n        export CC=${KUBE_LINUX_S390X_CC:-s390x-linux-gnu-gcc}\n        ;;\n    esac\n  fi\n\n  # if CC is defined for platform then always enable it\n  ccenv=$(echo \"$platform\" | awk -F/ '{print \"KUBE_\" toupper($1) \"_\" toupper($2) \"_CC\"}')\n  if [ -n \"${!ccenv-}\" ]; then \n    export CGO_ENABLED=1\n    export CC=\"${!ccenv}\"\n  fi\n}\n\nkube::golang::unset_platform_envs() {\n  unset GOOS\n  unset GOARCH\n  unset GOROOT\n  unset CGO_ENABLED\n  unset CC\n}\n\n# Create the GOPATH tree under $KUBE_OUTPUT\nkube::golang::create_gopath_tree() {\n  local go_pkg_dir=\"${KUBE_GOPATH}/src/${KUBE_GO_PACKAGE}\"\n  local go_pkg_basedir\n  go_pkg_basedir=$(dirname \"${go_pkg_dir}\")\n\n  mkdir -p \"${go_pkg_basedir}\"\n\n  # TODO: This symlink should be relative.\n  if [[ ! -e \"${go_pkg_dir}\" || \"$(readlink \"${go_pkg_dir}\")\" != \"${KUBE_ROOT}\" ]]; then\n    ln -snf \"${KUBE_ROOT}\" \"${go_pkg_dir}\"\n  fi\n}\n\n# Ensure the go tool exists and is a viable version.\nkube::golang::verify_go_version() {\n  if [[ -z \"$(command -v go)\" ]]; then\n    kube::log::usage_from_stdin <<EOF\nCan't find 'go' in PATH, please fix and retry.\nSee http://golang.org/doc/install for installation instructions.\nEOF\n    return 2\n  fi\n\n  local go_version\n  IFS=\" \" read -ra go_version <<< \"$(GOFLAGS='' go version)\"\n  local minimum_go_version\n  minimum_go_version=go1.16.0\n  if [[ \"${minimum_go_version}\" != $(echo -e \"${minimum_go_version}\\n${go_version[2]}\" | sort -s -t. -k 1,1 -k 2,2n -k 3,3n | head -n1) && \"${go_version[2]}\" != \"devel\" ]]; then\n    kube::log::usage_from_stdin <<EOF\nDetected go version: ${go_version[*]}.\nKubernetes requires ${minimum_go_version} or greater.\nPlease install ${minimum_go_version} or later.\nEOF\n    return 2\n  fi\n}\n\n# kube::golang::setup_env will check that the `go` commands is available in\n# ${PATH}. It will also check that the Go version is good enough for the\n# Kubernetes build.\n#\n# Inputs:\n#   KUBE_EXTRA_GOPATH - If set, this is included in created GOPATH\n#\n# Outputs:\n#   env-var GOPATH points to our local output dir\n#   env-var GOBIN is unset (we want binaries in a predictable place)\n#   env-var GO15VENDOREXPERIMENT=1\n#   current directory is within GOPATH\nkube::golang::setup_env() {\n  kube::golang::verify_go_version\n\n  kube::golang::create_gopath_tree\n\n  export GOPATH=\"${KUBE_GOPATH}\"\n  export GOCACHE=\"${KUBE_GOPATH}/cache\"\n\n  # Append KUBE_EXTRA_GOPATH to the GOPATH if it is defined.\n  if [[ -n ${KUBE_EXTRA_GOPATH:-} ]]; then\n    GOPATH=\"${GOPATH}:${KUBE_EXTRA_GOPATH}\"\n  fi\n\n  # Make sure our own Go binaries are in PATH.\n  export PATH=\"${KUBE_GOPATH}/bin:${PATH}\"\n\n  # Change directories so that we are within the GOPATH.  Some tools get really\n  # upset if this is not true.  We use a whole fake GOPATH here to collect the\n  # resultant binaries.  Go will not let us use GOBIN with `go install` and\n  # cross-compiling, and `go install -o <file>` only works for a single pkg.\n  local subdir\n  subdir=$(kube::realpath . | sed \"s|${KUBE_ROOT}||\")\n  cd \"${KUBE_GOPATH}/src/${KUBE_GO_PACKAGE}/${subdir}\" || return 1\n\n  # Set GOROOT so binaries that parse code can work properly.\n  GOROOT=$(go env GOROOT)\n  export GOROOT\n\n  # Unset GOBIN in case it already exists in the current session.\n  unset GOBIN\n\n  # This seems to matter to some tools\n  export GO15VENDOREXPERIMENT=1\n}\n\n# This will take binaries from $GOPATH/bin and copy them to the appropriate\n# place in ${KUBE_OUTPUT_BINDIR}\n#\n# Ideally this wouldn't be necessary and we could just set GOBIN to\n# KUBE_OUTPUT_BINDIR but that won't work in the face of cross compilation.  'go\n# install' will place binaries that match the host platform directly in $GOBIN\n# while placing cross compiled binaries into `platform_arch` subdirs.  This\n# complicates pretty much everything else we do around packaging and such.\nkube::golang::place_bins() {\n  local host_platform\n  host_platform=$(kube::golang::host_platform)\n\n  V=2 kube::log::status \"Placing binaries\"\n\n  local platform\n  for platform in \"${KUBE_CLIENT_PLATFORMS[@]}\"; do\n    # The substitution on platform_src below will replace all slashes with\n    # underscores.  It'll transform darwin/amd64 -> darwin_amd64.\n    local platform_src=\"/${platform//\\//_}\"\n    if [[ \"${platform}\" == \"${host_platform}\" ]]; then\n      platform_src=\"\"\n      rm -f \"${THIS_PLATFORM_BIN}\"\n      ln -s \"${KUBE_OUTPUT_BINPATH}/${platform}\" \"${THIS_PLATFORM_BIN}\"\n    fi\n\n    local full_binpath_src=\"${KUBE_GOPATH}/bin${platform_src}\"\n    if [[ -d \"${full_binpath_src}\" ]]; then\n      mkdir -p \"${KUBE_OUTPUT_BINPATH}/${platform}\"\n      find \"${full_binpath_src}\" -maxdepth 1 -type f -exec \\\n        rsync -pc {} \"${KUBE_OUTPUT_BINPATH}/${platform}\" \\;\n    fi\n  done\n}\n\n# Try and replicate the native binary placement of go install without\n# calling go install.\nkube::golang::outfile_for_binary() {\n  local binary=$1\n  local platform=$2\n  local output_path=\"${KUBE_GOPATH}/bin\"\n  local bin\n  bin=$(basename \"${binary}\")\n  if [[ \"${platform}\" != \"${host_platform}\" ]]; then\n    output_path=\"${output_path}/${platform//\\//_}\"\n  fi\n  if [[ ${GOOS} == \"windows\" ]]; then\n    bin=\"${bin}.exe\"\n  fi\n  echo \"${output_path}/${bin}\"\n}\n\n# Argument: the name of a Kubernetes package.\n# Returns 0 if the binary can be built with coverage, 1 otherwise.\n# NB: this ignores whether coverage is globally enabled or not.\nkube::golang::is_instrumented_package() {\n  kube::util::array_contains \"$1\" \"${KUBE_COVERAGE_INSTRUMENTED_PACKAGES[@]}\"\n  return $?\n}\n\n# Argument: the name of a Kubernetes package (e.g. k8s.io/kubernetes/cmd/kube-scheduler)\n# Echos the path to a dummy test used for coverage information.\nkube::golang::path_for_coverage_dummy_test() {\n  local package=\"$1\"\n  local path=\"${KUBE_GOPATH}/src/${package}\"\n  local name\n  name=$(basename \"${package}\")\n  echo \"${path}/zz_generated_${name}_test.go\"\n}\n\n# Argument: the name of a Kubernetes package (e.g. k8s.io/kubernetes/cmd/kube-scheduler).\n# Creates a dummy unit test on disk in the source directory for the given package.\n# This unit test will invoke the package's standard entry point when run.\nkube::golang::create_coverage_dummy_test() {\n  local package=\"$1\"\n  local name\n  name=\"$(basename \"${package}\")\"\n  cat <<EOF > \"$(kube::golang::path_for_coverage_dummy_test \"${package}\")\"\npackage main\nimport (\n  \"testing\"\n  \"k8s.io/kubernetes/pkg/util/coverage\"\n)\n\nfunc TestMain(m *testing.M) {\n  // Get coverage running\n  coverage.InitCoverage(\"${name}\")\n\n  // Go!\n  main()\n\n  // Make sure we actually write the profiling information to disk, if we make it here.\n  // On long-running services, or anything that calls os.Exit(), this is insufficient,\n  // so we also flush periodically with a default period of five seconds (configurable by\n  // the KUBE_COVERAGE_FLUSH_INTERVAL environment variable).\n  coverage.FlushCoverage()\n}\nEOF\n}\n\n# Argument: the name of a Kubernetes package (e.g. k8s.io/kubernetes/cmd/kube-scheduler).\n# Deletes a test generated by kube::golang::create_coverage_dummy_test.\n# It is not an error to call this for a nonexistent test.\nkube::golang::delete_coverage_dummy_test() {\n  local package=\"$1\"\n  rm -f \"$(kube::golang::path_for_coverage_dummy_test \"${package}\")\"\n}\n\n# Arguments: a list of kubernetes packages to build.\n# Expected variables: ${build_args} should be set to an array of Go build arguments.\n# In addition, ${package} and ${platform} should have been set earlier, and if\n# ${KUBE_BUILD_WITH_COVERAGE} is set, coverage instrumentation will be enabled.\n#\n# Invokes Go to actually build some packages. If coverage is disabled, simply invokes\n# go install. If coverage is enabled, builds covered binaries using go test, temporarily\n# producing the required unit test files and then cleaning up after itself.\n# Non-covered binaries are then built using go install as usual.\nkube::golang::build_some_binaries() {\n  if [[ -n \"${KUBE_BUILD_WITH_COVERAGE:-}\" ]]; then\n    local -a uncovered=()\n    for package in \"$@\"; do\n      if kube::golang::is_instrumented_package \"${package}\"; then\n        V=2 kube::log::info \"Building ${package} with coverage...\"\n\n        kube::golang::create_coverage_dummy_test \"${package}\"\n        kube::util::trap_add \"kube::golang::delete_coverage_dummy_test \\\"${package}\\\"\" EXIT\n\n        go test -c -o \"$(kube::golang::outfile_for_binary \"${package}\" \"${platform}\")\" \\\n          -covermode count \\\n          -coverpkg k8s.io/...,k8s.io/kubernetes/vendor/k8s.io/... \\\n          \"${build_args[@]}\" \\\n          -tags coverage \\\n          \"${package}\"\n      else\n        uncovered+=(\"${package}\")\n      fi\n    done\n    if [[ \"${#uncovered[@]}\" != 0 ]]; then\n      V=2 kube::log::info \"Building ${uncovered[*]} without coverage...\"\n      go install \"${build_args[@]}\" \"${uncovered[@]}\"\n    else\n      V=2 kube::log::info \"Nothing to build without coverage.\"\n     fi\n   else\n    V=2 kube::log::info \"Coverage is disabled.\"\n    go install \"${build_args[@]}\" \"$@\"\n   fi\n}\n\nkube::golang::build_binaries_for_platform() {\n  # This is for sanity.  Without it, user umasks can leak through.\n  umask 0022\n\n  local platform=$1\n\n  local -a statics=()\n  local -a nonstatics=()\n  local -a tests=()\n\n  V=2 kube::log::info \"Env for ${platform}: GOOS=${GOOS-} GOARCH=${GOARCH-} GOROOT=${GOROOT-} CGO_ENABLED=${CGO_ENABLED-} CC=${CC-}\"\n\n  for binary in \"${binaries[@]}\"; do\n    if [[ \"${binary}\" =~ \".test\"$ ]]; then\n      tests+=(\"${binary}\")\n    elif kube::golang::is_statically_linked_library \"${binary}\"; then\n      statics+=(\"${binary}\")\n    else\n      nonstatics+=(\"${binary}\")\n    fi\n  done\n\n  local -a build_args\n  if [[ \"${#statics[@]}\" != 0 ]]; then\n    build_args=(\n      -installsuffix static\n      ${goflags:+\"${goflags[@]}\"}\n      -gcflags \"${gogcflags:-}\"\n      -asmflags \"${goasmflags:-}\"\n      -ldflags \"${goldflags:-}\"\n      -tags \"${gotags:-}\"\n    )\n    CGO_ENABLED=0 kube::golang::build_some_binaries \"${statics[@]}\"\n  fi\n\n  if [[ \"${#nonstatics[@]}\" != 0 ]]; then\n    build_args=(\n      ${goflags:+\"${goflags[@]}\"}\n      -gcflags \"${gogcflags:-}\"\n      -asmflags \"${goasmflags:-}\"\n      -ldflags \"${goldflags:-}\"\n      -buildmode pie\n      -tags \"${gotags:-}\"\n    )\n    kube::golang::build_some_binaries \"${nonstatics[@]}\"\n  fi\n\n  for test in \"${tests[@]:+${tests[@]}}\"; do\n    local outfile testpkg\n    outfile=$(kube::golang::outfile_for_binary \"${test}\" \"${platform}\")\n    testpkg=$(dirname \"${test}\")\n\n    mkdir -p \"$(dirname \"${outfile}\")\"\n    go test -c \\\n      ${goflags:+\"${goflags[@]}\"} \\\n      -gcflags \"${gogcflags:-}\" \\\n      -asmflags \"${goasmflags:-}\" \\\n      -ldflags \"${goldflags:-}\" \\\n      -tags \"${gotags:-}\" \\\n      -o \"${outfile}\" \\\n      \"${testpkg}\"\n  done\n}\n\n# Return approximate physical memory available in gigabytes.\nkube::golang::get_physmem() {\n  local mem\n\n  # Linux kernel version >=3.14, in kb\n  if mem=$(grep MemAvailable /proc/meminfo | awk '{ print $2 }'); then\n    echo $(( mem / 1048576 ))\n    return\n  fi\n\n  # Linux, in kb\n  if mem=$(grep MemTotal /proc/meminfo | awk '{ print $2 }'); then\n    echo $(( mem / 1048576 ))\n    return\n  fi\n\n  # OS X, in bytes. Note that get_physmem, as used, should only ever\n  # run in a Linux container (because it's only used in the multiple\n  # platform case, which is a Dockerized build), but this is provided\n  # for completeness.\n  if mem=$(sysctl -n hw.memsize 2>/dev/null); then\n    echo $(( mem / 1073741824 ))\n    return\n  fi\n\n  # If we can't infer it, just give up and assume a low memory system\n  echo 1\n}\n\n# Build binaries targets specified\n#\n# Input:\n#   $@ - targets and go flags.  If no targets are set then all binaries targets\n#     are built.\n#   KUBE_BUILD_PLATFORMS - Incoming variable of targets to build for.  If unset\n#     then just the host architecture is built.\nkube::golang::build_binaries() {\n  # Create a sub-shell so that we don't pollute the outer environment\n  (\n    # Check for `go` binary and set ${GOPATH}.\n    kube::golang::setup_env\n    V=2 kube::log::info \"Go version: $(GOFLAGS='' go version)\"\n\n    local host_platform\n    host_platform=$(kube::golang::host_platform)\n\n    local goflags goldflags goasmflags gogcflags gotags\n    # If GOLDFLAGS is unset, then set it to the a default of \"-s -w\".\n    # Disable SC2153 for this, as it will throw a warning that the local\n    # variable goldflags will exist, and it suggest changing it to this.\n    # shellcheck disable=SC2153\n    goldflags=\"${GOLDFLAGS=-s -w} $(kube::version::ldflags)\"\n    goasmflags=\"-trimpath=${KUBE_ROOT}\"\n    gogcflags=\"${GOGCFLAGS:-} -trimpath=${KUBE_ROOT}\"\n\n    # extract tags if any specified in GOFLAGS\n    # shellcheck disable=SC2001\n    gotags=\"selinux,notest,$(echo \"${GOFLAGS:-}\" | sed -e 's|.*-tags=\\([^-]*\\).*|\\1|')\"\n\n    local -a targets=()\n    local arg\n\n    for arg; do\n      if [[ \"${arg}\" == -* ]]; then\n        # Assume arguments starting with a dash are flags to pass to go.\n        goflags+=(\"${arg}\")\n      else\n        targets+=(\"${arg}\")\n      fi\n    done\n\n    if [[ ${#targets[@]} -eq 0 ]]; then\n      targets=(\"${KUBE_ALL_TARGETS[@]}\")\n    fi\n\n    local -a platforms\n    IFS=\" \" read -ra platforms <<< \"${KUBE_BUILD_PLATFORMS:-}\"\n    if [[ ${#platforms[@]} -eq 0 ]]; then\n      platforms=(\"${host_platform}\")\n    fi\n\n    local -a binaries\n    while IFS=\"\" read -r binary; do binaries+=(\"$binary\"); done < <(kube::golang::binaries_from_targets \"${targets[@]}\")\n\n    local parallel=false\n    if [[ ${#platforms[@]} -gt 1 ]]; then\n      local gigs\n      gigs=$(kube::golang::get_physmem)\n\n      if [[ ${gigs} -ge ${KUBE_PARALLEL_BUILD_MEMORY} ]]; then\n        kube::log::status \"Multiple platforms requested and available ${gigs}G >= threshold ${KUBE_PARALLEL_BUILD_MEMORY}G, building platforms in parallel\"\n        parallel=true\n      else\n        kube::log::status \"Multiple platforms requested, but available ${gigs}G < threshold ${KUBE_PARALLEL_BUILD_MEMORY}G, building platforms in serial\"\n        parallel=false\n      fi\n    fi\n\n    if [[ \"${parallel}\" == \"true\" ]]; then\n      kube::log::status \"Building go targets for {${platforms[*]}} in parallel (output will appear in a burst when complete):\" \"${targets[@]}\"\n      local platform\n      for platform in \"${platforms[@]}\"; do (\n          kube::golang::set_platform_envs \"${platform}\"\n          kube::log::status \"${platform}: build started\"\n          kube::golang::build_binaries_for_platform \"${platform}\"\n          kube::log::status \"${platform}: build finished\"\n        ) &> \"/tmp//${platform//\\//_}.build\" &\n      done\n\n      local fails=0\n      for job in $(jobs -p); do\n        wait \"${job}\" || (( fails+=1 ))\n      done\n\n      for platform in \"${platforms[@]}\"; do\n        cat \"/tmp//${platform//\\//_}.build\"\n      done\n\n      exit \"${fails}\"\n    else\n      for platform in \"${platforms[@]}\"; do\n        kube::log::status \"Building go targets for ${platform}:\" \"${targets[@]}\"\n        (\n          kube::golang::set_platform_envs \"${platform}\"\n          kube::golang::build_binaries_for_platform \"${platform}\"\n        )\n      done\n    fi\n  )\n}\n", "num_lines": 881}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Unset CDPATH so that path interpolation can work correctly\n# https://github.com/kubernetes/kubernetes/issues/52255\nunset CDPATH\n\n# Until all GOPATH references are removed from all build scripts as well,\n# explicitly disable module mode to avoid picking up user-set GO111MODULE preferences.\n# As individual scripts (like hack/update-vendor.sh) make use of go modules,\n# they can explicitly set GO111MODULE=on\nexport GO111MODULE=off\n\n# The root of the build/dist directory\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\nKUBE_OUTPUT_SUBPATH=\"${KUBE_OUTPUT_SUBPATH:-_output/local}\"\nKUBE_OUTPUT=\"${KUBE_ROOT}/${KUBE_OUTPUT_SUBPATH}\"\nKUBE_OUTPUT_BINPATH=\"${KUBE_OUTPUT}/bin\"\n\n# This controls rsync compression. Set to a value > 0 to enable rsync\n# compression for build container\nKUBE_RSYNC_COMPRESS=\"${KUBE_RSYNC_COMPRESS:-0}\"\n\n# Set no_proxy for localhost if behind a proxy, otherwise,\n# the connections to localhost in scripts will time out\nexport no_proxy=\"127.0.0.1,localhost${no_proxy:+,${no_proxy}}\"\n\n# This is a symlink to binaries for \"this platform\", e.g. build tools.\nexport THIS_PLATFORM_BIN=\"${KUBE_ROOT}/_output/bin\"\n\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\nsource \"${KUBE_ROOT}/hack/lib/logging.sh\"\n\nkube::log::install_errexit\nkube::util::ensure-bash-version\n\nsource \"${KUBE_ROOT}/hack/lib/version.sh\"\nsource \"${KUBE_ROOT}/hack/lib/golang.sh\"\nsource \"${KUBE_ROOT}/hack/lib/etcd.sh\"\n\nKUBE_OUTPUT_HOSTBIN=\"${KUBE_OUTPUT_BINPATH}/$(kube::util::host_platform)\"\nexport KUBE_OUTPUT_HOSTBIN\n\n# list of all available group versions.  This should be used when generated code\n# or when starting an API server that you want to have everything.\n# most preferred version for a group should appear first\nKUBE_AVAILABLE_GROUP_VERSIONS=\"${KUBE_AVAILABLE_GROUP_VERSIONS:-\\\nv1 \\\nadmissionregistration.k8s.io/v1 \\\nadmissionregistration.k8s.io/v1beta1 \\\nadmission.k8s.io/v1 \\\nadmission.k8s.io/v1beta1 \\\napps/v1 \\\napps/v1beta1 \\\napps/v1beta2 \\\nauthentication.k8s.io/v1 \\\nauthentication.k8s.io/v1beta1 \\\nauthorization.k8s.io/v1 \\\nauthorization.k8s.io/v1beta1 \\\nautoscaling/v1 \\\nautoscaling/v2beta1 \\\nautoscaling/v2beta2 \\\nbatch/v1 \\\nbatch/v1beta1 \\\ncertificates.k8s.io/v1 \\\ncertificates.k8s.io/v1beta1 \\\ncoordination.k8s.io/v1beta1 \\\ncoordination.k8s.io/v1 \\\ndiscovery.k8s.io/v1 \\\ndiscovery.k8s.io/v1beta1 \\\nextensions/v1beta1 \\\nevents.k8s.io/v1 \\\nevents.k8s.io/v1beta1 \\\nimagepolicy.k8s.io/v1alpha1 \\\nnetworking.k8s.io/v1 \\\nnetworking.k8s.io/v1beta1 \\\nnode.k8s.io/v1 \\\nnode.k8s.io/v1alpha1 \\\nnode.k8s.io/v1beta1 \\\npolicy/v1 \\\npolicy/v1beta1 \\\nrbac.authorization.k8s.io/v1 \\\nrbac.authorization.k8s.io/v1beta1 \\\nrbac.authorization.k8s.io/v1alpha1 \\\nscheduling.k8s.io/v1alpha1 \\\nscheduling.k8s.io/v1beta1 \\\nscheduling.k8s.io/v1 \\\nstorage.k8s.io/v1beta1 \\\nstorage.k8s.io/v1 \\\nstorage.k8s.io/v1alpha1 \\\nflowcontrol.apiserver.k8s.io/v1alpha1 \\\nflowcontrol.apiserver.k8s.io/v1beta1 \\\ninternal.apiserver.k8s.io/v1alpha1 \\\n}\"\n\n# not all group versions are exposed by the server.  This list contains those\n# which are not available so we don't generate clients or swagger for them\nKUBE_NONSERVER_GROUP_VERSIONS=\"\n abac.authorization.kubernetes.io/v0 \\\n abac.authorization.kubernetes.io/v1beta1 \\\n componentconfig/v1alpha1 \\\n imagepolicy.k8s.io/v1alpha1\\\n admission.k8s.io/v1\\\n admission.k8s.io/v1beta1\\\n\"\nexport KUBE_NONSERVER_GROUP_VERSIONS\n\n# This emulates \"readlink -f\" which is not available on MacOS X.\n# Test:\n# T=/tmp/$$.$RANDOM\n# mkdir $T\n# touch $T/file\n# mkdir $T/dir\n# ln -s $T/file $T/linkfile\n# ln -s $T/dir $T/linkdir\n# function testone() {\n#   X=$(readlink -f $1 2>&1)\n#   Y=$(kube::readlinkdashf $1 2>&1)\n#   if [ \"$X\" != \"$Y\" ]; then\n#     echo readlinkdashf $1: expected \"$X\", got \"$Y\"\n#   fi\n# }\n# testone /\n# testone /tmp\n# testone $T\n# testone $T/file\n# testone $T/dir\n# testone $T/linkfile\n# testone $T/linkdir\n# testone $T/nonexistant\n# testone $T/linkdir/file\n# testone $T/linkdir/dir\n# testone $T/linkdir/linkfile\n# testone $T/linkdir/linkdir\nfunction kube::readlinkdashf {\n  # run in a subshell for simpler 'cd'\n  (\n    if [[ -d \"${1}\" ]]; then # This also catch symlinks to dirs.\n      cd \"${1}\"\n      pwd -P\n    else\n      cd \"$(dirname \"${1}\")\"\n      local f\n      f=$(basename \"${1}\")\n      if [[ -L \"${f}\" ]]; then\n        readlink \"${f}\"\n      else\n        echo \"$(pwd -P)/${f}\"\n      fi\n    fi\n  )\n}\n\n# This emulates \"realpath\" which is not available on MacOS X\n# Test:\n# T=/tmp/$$.$RANDOM\n# mkdir $T\n# touch $T/file\n# mkdir $T/dir\n# ln -s $T/file $T/linkfile\n# ln -s $T/dir $T/linkdir\n# function testone() {\n#   X=$(realpath $1 2>&1)\n#   Y=$(kube::realpath $1 2>&1)\n#   if [ \"$X\" != \"$Y\" ]; then\n#     echo realpath $1: expected \"$X\", got \"$Y\"\n#   fi\n# }\n# testone /\n# testone /tmp\n# testone $T\n# testone $T/file\n# testone $T/dir\n# testone $T/linkfile\n# testone $T/linkdir\n# testone $T/nonexistant\n# testone $T/linkdir/file\n# testone $T/linkdir/dir\n# testone $T/linkdir/linkfile\n# testone $T/linkdir/linkdir\nkube::realpath() {\n  if [[ ! -e \"${1}\" ]]; then\n    echo \"${1}: No such file or directory\" >&2\n    return 1\n  fi\n  kube::readlinkdashf \"${1}\"\n}\n", "num_lines": 206}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Controls verbosity of the script output and logging.\nKUBE_VERBOSE=\"${KUBE_VERBOSE:-2}\"\n\n# Handler for when we exit automatically on an error.\n# Borrowed from https://gist.github.com/ahendrix/7030300\nkube::log::errexit() {\n  local err=\"${PIPESTATUS[*]}\"\n\n  # If the shell we are in doesn't have errexit set (common in subshells) then\n  # don't dump stacks.\n  set +o | grep -qe \"-o errexit\" || return\n\n  set +o xtrace\n  local code=\"${1:-1}\"\n  # Print out the stack trace described by $function_stack\n  if [ ${#FUNCNAME[@]} -gt 2 ]\n  then\n    kube::log::error \"Call tree:\"\n    for ((i=1;i<${#FUNCNAME[@]}-1;i++))\n    do\n      kube::log::error \" ${i}: ${BASH_SOURCE[${i}+1]}:${BASH_LINENO[${i}]} ${FUNCNAME[${i}]}(...)\"\n    done\n  fi\n  kube::log::error_exit \"Error in ${BASH_SOURCE[1]}:${BASH_LINENO[0]}. '${BASH_COMMAND}' exited with status ${err}\" \"${1:-1}\" 1\n}\n\nkube::log::install_errexit() {\n  # trap ERR to provide an error handler whenever a command exits nonzero  this\n  # is a more verbose version of set -o errexit\n  trap 'kube::log::errexit' ERR\n\n  # setting errtrace allows our ERR trap handler to be propagated to functions,\n  # expansions and subshells\n  set -o errtrace\n}\n\n# Print out the stack trace\n#\n# Args:\n#   $1 The number of stack frames to skip when printing.\nkube::log::stack() {\n  local stack_skip=${1:-0}\n  stack_skip=$((stack_skip + 1))\n  if [[ ${#FUNCNAME[@]} -gt ${stack_skip} ]]; then\n    echo \"Call stack:\" >&2\n    local i\n    for ((i=1 ; i <= ${#FUNCNAME[@]} - stack_skip ; i++))\n    do\n      local frame_no=$((i - 1 + stack_skip))\n      local source_file=${BASH_SOURCE[${frame_no}]}\n      local source_lineno=${BASH_LINENO[$((frame_no - 1))]}\n      local funcname=${FUNCNAME[${frame_no}]}\n      echo \"  ${i}: ${source_file}:${source_lineno} ${funcname}(...)\" >&2\n    done\n  fi\n}\n\n# Log an error and exit.\n# Args:\n#   $1 Message to log with the error\n#   $2 The error code to return\n#   $3 The number of stack frames to skip when printing.\nkube::log::error_exit() {\n  local message=\"${1:-}\"\n  local code=\"${2:-1}\"\n  local stack_skip=\"${3:-0}\"\n  stack_skip=$((stack_skip + 1))\n\n  if [[ ${KUBE_VERBOSE} -ge 4 ]]; then\n    local source_file=${BASH_SOURCE[${stack_skip}]}\n    local source_line=${BASH_LINENO[$((stack_skip - 1))]}\n    echo \"!!! Error in ${source_file}:${source_line}\" >&2\n    [[ -z ${1-} ]] || {\n      echo \"  ${1}\" >&2\n    }\n\n    kube::log::stack ${stack_skip}\n\n    echo \"Exiting with status ${code}\" >&2\n  fi\n\n  exit \"${code}\"\n}\n\n# Log an error but keep going.  Don't dump the stack or exit.\nkube::log::error() {\n  timestamp=$(date +\"[%m%d %H:%M:%S]\")\n  echo \"!!! ${timestamp} ${1-}\" >&2\n  shift\n  for message; do\n    echo \"    ${message}\" >&2\n  done\n}\n\n# Print an usage message to stderr.  The arguments are printed directly.\nkube::log::usage() {\n  echo >&2\n  local message\n  for message; do\n    echo \"${message}\" >&2\n  done\n  echo >&2\n}\n\nkube::log::usage_from_stdin() {\n  local messages=()\n  while read -r line; do\n    messages+=(\"${line}\")\n  done\n\n  kube::log::usage \"${messages[@]}\"\n}\n\n# Print out some info that isn't a top level status line\nkube::log::info() {\n  local V=\"${V:-0}\"\n  if [[ ${KUBE_VERBOSE} < ${V} ]]; then\n    return\n  fi\n\n  for message; do\n    echo \"${message}\"\n  done\n}\n\n# Just like kube::log::info, but no \\n, so you can make a progress bar\nkube::log::progress() {\n  for message; do\n    echo -e -n \"${message}\"\n  done\n}\n\nkube::log::info_from_stdin() {\n  local messages=()\n  while read -r line; do\n    messages+=(\"${line}\")\n  done\n\n  kube::log::info \"${messages[@]}\"\n}\n\n# Print a status line.  Formatted to show up in a stream of output.\nkube::log::status() {\n  local V=\"${V:-0}\"\n  if [[ ${KUBE_VERBOSE} < ${V} ]]; then\n    return\n  fi\n\n  timestamp=$(date +\"[%m%d %H:%M:%S]\")\n  echo \"+++ ${timestamp} ${1}\"\n  shift\n  for message; do\n    echo \"    ${message}\"\n  done\n}\n", "num_lines": 172}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# The root of the build/dist directory\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# Generates $1/api.pb.go from the protobuf file $1/api.proto\n# and formats it correctly\n# $1: Full path to the directory where the api.proto file is\nfunction kube::protoc::generate_proto() {\n  kube::golang::setup_env\n  go install k8s.io/kubernetes/vendor/k8s.io/code-generator/cmd/go-to-protobuf/protoc-gen-gogo\n\n  kube::protoc::check_protoc\n\n  local package=${1}\n  kube::protoc::protoc \"${package}\"\n  kube::protoc::format \"${package}\"\n}\n\n# Checks that the current protoc version is at least version 3.0.0-beta1\n# exit 1 if it's not the case\nfunction kube::protoc::check_protoc() {\n  if [[ -z \"$(which protoc)\" || \"$(protoc --version)\" != \"libprotoc 3.\"* ]]; then\n    echo \"Generating protobuf requires protoc 3.0.0-beta1 or newer. Please download and\"\n    echo \"install the platform appropriate Protobuf package for your OS: \"\n    echo\n    echo \"  https://github.com/google/protobuf/releases\"\n    echo\n    echo \"WARNING: Protobuf changes are not being validated\"\n    exit 1\n  fi\n}\n\n# Generates $1/api.pb.go from the protobuf file $1/api.proto\n# $1: Full path to the directory where the api.proto file is\nfunction kube::protoc::protoc() {\n  local package=${1}\n  gogopath=$(dirname \"$(kube::util::find-binary \"protoc-gen-gogo\")\")\n\n  PATH=\"${gogopath}:${PATH}\" protoc \\\n    --proto_path=\"${package}\" \\\n    --proto_path=\"${KUBE_ROOT}/vendor\" \\\n    --gogo_out=plugins=grpc:\"${package}\" \"${package}/api.proto\"\n}\n\n# Formats $1/api.pb.go, adds the boilerplate comments and run gofmt on it\n# $1: Full path to the directory where the api.proto file is\nfunction kube::protoc::format() {\n  local package=${1}\n\n  # Update boilerplate for the generated file.\n  cat hack/boilerplate/boilerplate.generatego.txt \"${package}/api.pb.go\" > tmpfile && mv tmpfile \"${package}/api.pb.go\"\n\n  # Run gofmt to clean up the generated code.\n  kube::golang::verify_go_version\n  gofmt -l -s -w \"${package}/api.pb.go\"\n}\n\n# Compares the contents of $1 and $2\n# Echo's $3 in case of error and exits 1\nfunction kube::protoc::diff() {\n  local ret=0\n  diff -I \"gzipped FileDescriptorProto\" -I \"0x\" -Naupr \"${1}\" \"${2}\" || ret=$?\n  if [[ ${ret} -ne 0 ]]; then\n    echo \"${3}\"\n    exit 1\n  fi\n}\n", "num_lines": 88}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Contains swagger related util functions.\n#\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Generates types_swagger_doc_generated file for the given group version.\n# $1: Name of the group version\n# $2: Path to the directory where types.go for that group version exists. This\n# is the directory where the file will be generated.\nkube::swagger::gen_types_swagger_doc() {\n  local group_version=$1\n  local gv_dir=$2\n  local TMPFILE\n  TMPFILE=\"${TMPDIR:-/tmp}/types_swagger_doc_generated.$(date +%s).go\"\n\n  echo \"Generating swagger type docs for ${group_version} at ${gv_dir}\"\n\n  {\n    echo -e \"$(cat hack/boilerplate/boilerplate.generatego.txt)\\n\"\n    echo \"package ${group_version##*/}\"\n    cat <<EOF\n\n// This file contains a collection of methods that can be used from go-restful to\n// generate Swagger API documentation for its models. Please read this PR for more\n// information on the implementation: https://github.com/emicklei/go-restful/pull/215\n//\n// TODOs are ignored from the parser (e.g. TODO(andronat):... || TODO:...) if and only if\n// they are on one line! For multiple line or blocks that you want to ignore use ---.\n// Any context after a --- is ignored.\n//\n// Those methods can be generated by using hack/update-generated-swagger-docs.sh\n\n// AUTO-GENERATED FUNCTIONS START HERE. DO NOT EDIT.\nEOF\n  } > \"${TMPFILE}\"\n\n  if ! which genswaggertypedocs >/dev/null; then\n    # build if needed\n    go install k8s.io/kubernetes/cmd/genswaggertypedocs\n  fi\n\n  genswaggertypedocs -s \\\n    \"${gv_dir}/types.go\" \\\n    -f - \\\n    >>  \"${TMPFILE}\"\n\n  echo \"// AUTO-GENERATED FUNCTIONS END HERE\" >> \"${TMPFILE}\"\n\n  gofmt -w -s \"${TMPFILE}\"\n  mv \"${TMPFILE}\" \"${gv_dir}/types_swagger_doc_generated.go\"\n}\n", "num_lines": 69}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# shellcheck disable=SC2034 # Variables sourced in other scripts.\n\n# A set of helpers for tests\n\nreadonly reset=$(tput sgr0)\nreadonly  bold=$(tput bold)\nreadonly black=$(tput setaf 0)\nreadonly   red=$(tput setaf 1)\nreadonly green=$(tput setaf 2)\n\nkube::test::clear_all() {\n  if kube::test::if_supports_resource \"rc\" ; then\n    # shellcheck disable=SC2154\n    # Disabling because \"kube_flags\" is set in a parent script\n    kubectl delete \"${kube_flags[@]}\" rc --all --grace-period=0 --force\n  fi\n  if kube::test::if_supports_resource \"pods\" ; then\n    kubectl delete \"${kube_flags[@]}\" pods --all --grace-period=0 --force\n  fi\n}\n\n# Prints the calling file and line number $1 levels deep\n# Defaults to 2 levels so you can call this to find your own caller\nkube::test::get_caller() {\n  local levels=${1:-2}\n  local caller_file=\"${BASH_SOURCE[${levels}]}\"\n  local caller_line=\"${BASH_LINENO[${levels}-1]}\"\n  echo \"$(basename \"${caller_file}\"):${caller_line}\"\n}\n\n# Force exact match of a returned result for a object query.  Wrap this with || to support multiple\n# valid return types.\n# This runs `kubectl get` once and asserts that the result is as expected.\n# $1: Object on which get should be run\n# $2: The go-template to run on the result\n# $3: The expected output\n# $4: Additional args to be passed to kubectl\nkube::test::get_object_assert() {\n  kube::test::object_assert 1 \"$@\"\n}\n\n# Asserts that the output of a given get query is as expected.\n# Runs the query multiple times before failing it.\n# $1: Object on which get should be run\n# $2: The go-template to run on the result\n# $3: The expected output\n# $4: Additional args to be passed to kubectl\nkube::test::wait_object_assert() {\n  kube::test::object_assert 10 \"$@\"\n}\n\n# Asserts that the output of a given get query is as expected.\n# Can run the query multiple times before failing it.\n# $1: Number of times the query should be run before failing it.\n# $2: Object on which get should be run\n# $3: The go-template to run on the result\n# $4: The expected output\n# $5: Additional args to be passed to kubectl\nkube::test::object_assert() {\n  local tries=$1\n  local object=$2\n  local request=$3\n  local expected=$4\n  local args=${5:-}\n\n  for j in $(seq 1 \"${tries}\"); do\n    # shellcheck disable=SC2086\n    # Disabling because \"args\" needs to allow for expansion here\n    res=$(eval kubectl get \"${kube_flags[@]}\" ${args} \"${object}\" -o go-template=\\\"\"${request}\"\\\")\n    if [[ \"${res}\" =~ ^$expected$ ]]; then\n        echo -n \"${green}\"\n        echo \"$(kube::test::get_caller 3): Successful get ${object} ${request}: ${res}\"\n        echo -n \"${reset}\"\n        return 0\n    fi\n    echo \"Waiting for Get ${object} ${request} ${args}: expected: ${expected}, got: ${res}\"\n    sleep $((j-1))\n  done\n\n  echo \"${bold}${red}\"\n  echo \"$(kube::test::get_caller 3): FAIL!\"\n  echo \"Get ${object} ${request}\"\n  echo \"  Expected: ${expected}\"\n  echo \"  Got:      ${res}\"\n  echo \"${reset}${red}\"\n  caller\n  echo \"${reset}\"\n  return 1\n}\n\nkube::test::get_object_jsonpath_assert() {\n  local object=$1\n  local request=$2\n  local expected=$3\n\n  res=$(eval kubectl get \"${kube_flags[@]}\" \"${object}\" -o jsonpath=\\\"\"${request}\"\\\")\n\n  if [[ \"${res}\" =~ ^$expected$ ]]; then\n      echo -n \"${green}\"\n      echo \"$(kube::test::get_caller): Successful get ${object} ${request}: ${res}\"\n      echo -n \"${reset}\"\n      return 0\n  else\n      echo \"${bold}${red}\"\n      echo \"$(kube::test::get_caller): FAIL!\"\n      echo \"Get ${object} ${request}\"\n      echo \"  Expected: ${expected}\"\n      echo \"  Got:      ${res}\"\n      echo \"${reset}${red}\"\n      caller\n      echo \"${reset}\"\n      return 1\n  fi\n}\n\nkube::test::describe_object_assert() {\n  local resource=$1\n  local object=$2\n  local matches=( \"${@:3}\" )\n\n  result=$(eval kubectl describe \"${kube_flags[@]}\" \"${resource}\" \"${object}\")\n\n  for match in \"${matches[@]}\"; do\n    if grep -q \"${match}\" <<< \"${result}\"; then\n      echo \"matched ${match}\"\n    else\n      echo \"${bold}${red}\"\n      echo \"$(kube::test::get_caller): FAIL!\"\n      echo \"Describe ${resource} ${object}\"\n      echo \"  Expected Match: ${match}\"\n      echo \"  Not found in:\"\n      echo \"${result}\"\n      echo \"${reset}${red}\"\n      caller\n      echo \"${reset}\"\n      return 1\n    fi\n  done\n\n  echo -n \"${green}\"\n  echo \"$(kube::test::get_caller): Successful describe ${resource} ${object}:\"\n  echo \"${result}\"\n  echo -n \"${reset}\"\n  return 0\n}\n\nkube::test::describe_object_events_assert() {\n    local resource=$1\n    local object=$2\n    local showevents=${3:-\"true\"}\n\n    if [[ -z \"${3:-}\" ]]; then\n        result=$(eval kubectl describe \"${kube_flags[@]}\" \"${resource}\" \"${object}\")\n    else\n        result=$(eval kubectl describe \"${kube_flags[@]}\" \"--show-events=${showevents}\" \"${resource}\" \"${object}\")\n    fi\n\n    if grep -q \"No events.\\|Events:\" <<< \"${result}\"; then\n        local has_events=\"true\"\n    else\n        local has_events=\"false\"\n    fi\n    if [[ \"${showevents}\" == \"${has_events}\" ]]; then\n        echo -n \"${green}\"\n        echo \"$(kube::test::get_caller): Successful describe\"\n        echo \"${result}\"\n        echo \"${reset}\"\n        return 0\n    else\n        echo \"${bold}${red}\"\n        echo \"$(kube::test::get_caller): FAIL\"\n        if [[ \"${showevents}\" == \"false\" ]]; then\n            echo \"  Events information should not be described in:\"\n        else\n            echo \"  Events information not found in:\"\n        fi\n        echo \"${result}\"\n        echo \"${reset}${red}\"\n        caller\n        echo \"${reset}\"\n        return 1\n    fi\n}\n\nkube::test::describe_resource_assert() {\n  local resource=$1\n  local matches=( \"${@:2}\" )\n\n  result=$(eval kubectl describe \"${kube_flags[@]}\" \"${resource}\")\n\n  for match in \"${matches[@]}\"; do\n    if grep -q \"${match}\" <<< \"${result}\"; then\n      echo \"matched ${match}\"\n    else\n      echo \"${bold}${red}\"\n      echo \"FAIL!\"\n      echo \"Describe ${resource}\"\n      echo \"  Expected Match: ${match}\"\n      echo \"  Not found in:\"\n      echo \"${result}\"\n      echo \"${reset}${red}\"\n      caller\n      echo \"${reset}\"\n      return 1\n    fi\n  done\n\n  echo -n \"${green}\"\n  echo \"Successful describe ${resource}:\"\n  echo \"${result}\"\n  echo -n \"${reset}\"\n  return 0\n}\n\nkube::test::describe_resource_events_assert() {\n    local resource=$1\n    local showevents=${2:-\"true\"}\n\n    result=$(eval kubectl describe \"${kube_flags[@]}\" \"--show-events=${showevents}\" \"${resource}\")\n\n    if grep -q \"No events.\\|Events:\" <<< \"${result}\"; then\n        local has_events=\"true\"\n    else\n        local has_events=\"false\"\n    fi\n    if [[ \"${showevents}\" == \"${has_events}\" ]]; then\n        echo -n \"${green}\"\n        echo \"Successful describe\"\n        echo \"${result}\"\n        echo -n \"${reset}\"\n        return 0\n    else\n        echo \"${bold}${red}\"\n        echo \"FAIL\"\n        if [[ \"${showevents}\" == \"false\" ]]; then\n            echo \"  Events information should not be described in:\"\n        else\n            echo \"  Events information not found in:\"\n        fi\n        echo \"${result}\"\n        caller\n        echo \"${reset}\"\n        return 1\n    fi\n}\n\nkube::test::describe_resource_chunk_size_assert() {\n  # $1: the target resource\n  local resource=$1\n  # $2: comma-separated list of additional resources that will be listed\n  local additionalResources=${2:-}\n  # Remaining args are flags to pass to kubectl\n  local args=${3:-}\n\n  # Expect list requests for the target resource and the additional resources\n  local expectLists\n  IFS=\",\" read -r -a expectLists <<< \"${resource},${additionalResources}\"\n\n  # Default chunk size\n  defaultResult=$(eval kubectl describe \"${resource}\" --show-events=true -v=6 \"${args}\" \"${kube_flags[@]}\" 2>&1 >/dev/null)\n  for r in \"${expectLists[@]}\"; do\n    if grep -q \"${r}?.*limit=500\" <<< \"${defaultResult}\"; then\n      echo \"query for ${r} had limit param\"\n    else\n      echo \"${bold}${red}\"\n      echo \"FAIL!\"\n      echo \"Describe ${resource}\"\n      echo \"  Expected limit param on request for: ${r}\"\n      echo \"  Not found in:\"\n      echo \"${defaultResult}\"\n      echo \"${reset}${red}\"\n      caller\n      echo \"${reset}\"\n      return 1\n    fi\n  done\n\n  # Try a non-default chunk size\n  customResult=$(eval kubectl describe \"${resource}\" --show-events=false --chunk-size=10 -v=6 \"${args}\" \"${kube_flags[@]}\" 2>&1 >/dev/null)\n  if grep -q \"${resource}?limit=10\" <<< \"${customResult}\"; then\n    echo \"query for ${resource} had user-specified limit param\"\n  else\n    echo \"${bold}${red}\"\n    echo \"FAIL!\"\n    echo \"Describe ${resource}\"\n    echo \"  Expected limit param on request for: ${r}\"\n    echo \"  Not found in:\"\n    echo \"${customResult}\"\n    echo \"${reset}${red}\"\n    caller\n    echo \"${reset}\"\n    return 1\n  fi\n\n  echo -n \"${green}\"\n  echo \"Successful describe ${resource} verbose logs:\"\n  echo \"${defaultResult}\"\n  echo -n \"${reset}\"\n\n  return 0\n}\n\n# Compare sort-by resource name output (first column, skipping first line) with expected order specify in the last parameter\nkube::test::if_sort_by_has_correct_order() {\n  local var\n  var=\"$(echo \"$1\" | awk '{if(NR!=1) print $1}' | tr '\\n' ':')\"\n  kube::test::if_has_string \"${var}\" \"${@:$#}\"\n}\n\nkube::test::if_has_string() {\n  local message=$1\n  local match=$2\n\n  if grep -q \"${match}\" <<< \"${message}\"; then\n    echo \"Successful\"\n    echo \"message:${message}\"\n    echo \"has:${match}\"\n    return 0\n  else\n    echo \"FAIL!\"\n    echo \"message:${message}\"\n    echo \"has not:${match}\"\n    caller\n    return 1\n  fi\n}\n\nkube::test::if_has_not_string() {\n  local message=$1\n  local match=$2\n\n  if grep -q \"${match}\" <<< \"${message}\"; then\n    echo \"FAIL!\"\n    echo \"message:${message}\"\n    echo \"has:${match}\"\n    caller\n    return 1\n  else\n    echo \"Successful\"\n    echo \"message:${message}\"\n    echo \"has not:${match}\"\n    return 0\n  fi\n}\n\nkube::test::if_empty_string() {\n  local match=$1\n  if [ -n \"${match}\" ]; then\n    echo \"${match} is not empty\"\n    caller\n    return 1\n  else\n    echo \"Successful\"\n    return 0\n  fi\n}\n\n# Returns true if the required resource is part of supported resources.\n# Expects env vars:\n#   SUPPORTED_RESOURCES: Array of all resources supported by the apiserver. \"*\"\n#   means it supports all resources. For ex: (\"*\") or (\"rc\" \"*\") both mean that\n#   all resources are supported.\n#   $1: Name of the resource to be tested.\nkube::test::if_supports_resource() {\n  SUPPORTED_RESOURCES=${SUPPORTED_RESOURCES:-\"\"}\n  REQUIRED_RESOURCE=${1:-\"\"}\n\n  for r in \"${SUPPORTED_RESOURCES[@]}\"; do\n    if [[ \"${r}\" == \"*\" || \"${r}\" == \"${REQUIRED_RESOURCE}\" ]]; then\n      return 0\n    fi\n  done\n  return 1\n}\n\n\nkube::test::version::object_to_file() {\n  name=$1\n  flags=${2:-\"\"}\n  file=$3\n  # shellcheck disable=SC2086\n  # Disabling because \"flags\" needs to allow for expansion here\n  kubectl version ${flags} | grep \"${name} Version:\" | sed -e s/\"${name} Version: version.Info{\"/'/' -e s/'}'/'/' -e s/', '/','/g -e s/':'/'=/g' -e s/'\"'/\"\"/g | tr , '\\n' > \"${file}\"\n}\n\nkube::test::version::json_object_to_file() {\n  flags=$1\n  file=$2\n  # shellcheck disable=SC2086\n  # Disabling because \"flags\" needs to allow for expansion here\n  kubectl version ${flags} --output json | sed -e s/' '/''/g -e s/'\\\"'/''/g -e s/'}'/''/g -e s/'{'/''/g -e s/'clientVersion:'/'clientVersion:,'/ -e s/'serverVersion:'/'serverVersion:,'/ | tr , '\\n' > \"${file}\"\n}\n\nkube::test::version::json_client_server_object_to_file() {\n  flags=$1\n  name=$2\n  file=$3\n  # shellcheck disable=SC2086\n  # Disabling because \"flags\" needs to allow for expansion here\n  kubectl version ${flags} --output json | jq -r \".${name}\" | sed -e s/'\\\"'/''/g -e s/'}'/''/g -e s/'{'/''/g -e /^$/d -e s/','/''/g  -e s/':'/'='/g > \"${file}\"\n}\n\nkube::test::version::yaml_object_to_file() {\n  flags=$1\n  file=$2\n  # shellcheck disable=SC2086\n  # Disabling because \"flags\" needs to allow for expansion here\n  kubectl version ${flags} --output yaml | sed -e s/' '/''/g -e s/'\\\"'/''/g -e /^$/d > \"${file}\"\n}\n\nkube::test::version::diff_assert() {\n  local original=$1\n  local comparator=${2:-\"eq\"}\n  local latest=$3\n  local diff_msg=${4:-\"\"}\n  local res=\"\"\n\n  if [ ! -f \"${original}\" ]; then\n        echo \"${bold}${red}\"\n        echo \"FAIL! ${diff_msg}\"\n        echo \"the file '${original}' does not exit\"\n        echo \"${reset}${red}\"\n        caller\n        echo \"${reset}\"\n        return 1\n  fi\n\n  if [ ! -f \"${latest}\" ]; then\n        echo \"${bold}${red}\"\n        echo \"FAIL! ${diff_msg}\"\n        echo \"the file '${latest}' does not exit\"\n        echo \"${reset}${red}\"\n        caller\n        echo \"${reset}\"\n        return 1\n  fi\n\n  sort \"${original}\" > \"${original}.sorted\"\n  sort \"${latest}\" > \"${latest}.sorted\"\n\n  if [ \"${comparator}\" == \"eq\" ]; then\n    if [ \"$(diff -iwB \"${original}\".sorted \"${latest}\".sorted)\" == \"\" ] ; then\n        echo -n \"${green}\"\n        echo \"Successful: ${diff_msg}\"\n        echo -n \"${reset}\"\n        return 0\n    else\n        echo \"${bold}${red}\"\n        echo \"FAIL! ${diff_msg}\"\n        echo \"  Expected: \"\n        cat \"${original}\"\n        echo \"  Got: \"\n        cat \"${latest}\"\n        echo \"${reset}${red}\"\n        caller\n        echo \"${reset}\"\n        return 1\n    fi\n  else\n    if [ -n \"$(diff -iwB \"${original}\".sorted \"${latest}\".sorted)\" ] ; then\n        echo -n \"${green}\"\n        echo \"Successful: ${diff_msg}\"\n        echo -n \"${reset}\"\n        return 0\n    else\n        echo \"${bold}${red}\"\n        echo \"FAIL! ${diff_msg}\"\n        echo \"  Expected: \"\n        cat \"${original}\"\n        echo \"  Got: \"\n        cat \"${latest}\"\n        echo \"${reset}${red}\"\n        caller\n        echo \"${reset}\"\n        return 1\n      fi\n  fi\n}\n\n", "num_lines": 496}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction kube::util::sourced_variable {\n  # Call this function to tell shellcheck that a variable is supposed to\n  # be used from other calling context. This helps quiet an \"unused\n  # variable\" warning from shellcheck and also document your code.\n  true\n}\n\nkube::util::sortable_date() {\n  date \"+%Y%m%d-%H%M%S\"\n}\n\n# arguments: target, item1, item2, item3, ...\n# returns 0 if target is in the given items, 1 otherwise.\nkube::util::array_contains() {\n  local search=\"$1\"\n  local element\n  shift\n  for element; do\n    if [[ \"${element}\" == \"${search}\" ]]; then\n      return 0\n     fi\n  done\n  return 1\n}\n\nkube::util::wait_for_url() {\n  local url=$1\n  local prefix=${2:-}\n  local wait=${3:-1}\n  local times=${4:-30}\n  local maxtime=${5:-1}\n\n  command -v curl >/dev/null || {\n    kube::log::usage \"curl must be installed\"\n    exit 1\n  }\n\n  local i\n  for i in $(seq 1 \"${times}\"); do\n    local out\n    if out=$(curl --max-time \"${maxtime}\" -gkfs \"${@:6}\" \"${url}\" 2>/dev/null); then\n      kube::log::status \"On try ${i}, ${prefix}: ${out}\"\n      return 0\n    fi\n    sleep \"${wait}\"\n  done\n  kube::log::error \"Timed out waiting for ${prefix} to answer at ${url}; tried ${times} waiting ${wait} between each\"\n  return 1\n}\n\nkube::util::wait_for_url_with_bearer_token() {\n  local url=$1\n  local token=$2\n  local prefix=${3:-}\n  local wait=${4:-1}\n  local times=${5:-30}\n  local maxtime=${6:-1}\n\n  kube::util::wait_for_url \"${url}\" \"${prefix}\" \"${wait}\" \"${times}\" \"${maxtime}\" -H \"Authorization: Bearer ${token}\"\n}\n\n# Example:  kube::util::wait_for_success 120 5 \"kubectl get nodes|grep localhost\"\n# arguments: wait time, sleep time, shell command\n# returns 0 if the shell command get output, 1 otherwise.\nkube::util::wait_for_success(){\n  local wait_time=\"$1\"\n  local sleep_time=\"$2\"\n  local cmd=\"$3\"\n  while [ \"$wait_time\" -gt 0 ]; do\n    if eval \"$cmd\"; then\n      return 0\n    else\n      sleep \"$sleep_time\"\n      wait_time=$((wait_time-sleep_time))\n    fi\n  done\n  return 1\n}\n\n# Example:  kube::util::trap_add 'echo \"in trap DEBUG\"' DEBUG\n# See: http://stackoverflow.com/questions/3338030/multiple-bash-traps-for-the-same-signal\nkube::util::trap_add() {\n  local trap_add_cmd\n  trap_add_cmd=$1\n  shift\n\n  for trap_add_name in \"$@\"; do\n    local existing_cmd\n    local new_cmd\n\n    # Grab the currently defined trap commands for this trap\n    existing_cmd=$(trap -p \"${trap_add_name}\" |  awk -F\"'\" '{print $2}')\n\n    if [[ -z \"${existing_cmd}\" ]]; then\n      new_cmd=\"${trap_add_cmd}\"\n    else\n      new_cmd=\"${trap_add_cmd};${existing_cmd}\"\n    fi\n\n    # Assign the test. Disable the shellcheck warning telling that trap\n    # commands should be single quoted to avoid evaluating them at this\n    # point instead evaluating them at run time. The logic of adding new\n    # commands to a single trap requires them to be evaluated right away.\n    # shellcheck disable=SC2064\n    trap \"${new_cmd}\" \"${trap_add_name}\"\n  done\n}\n\n# Opposite of kube::util::ensure-temp-dir()\nkube::util::cleanup-temp-dir() {\n  rm -rf \"${KUBE_TEMP}\"\n}\n\n# Create a temp dir that'll be deleted at the end of this bash session.\n#\n# Vars set:\n#   KUBE_TEMP\nkube::util::ensure-temp-dir() {\n  if [[ -z ${KUBE_TEMP-} ]]; then\n    KUBE_TEMP=$(mktemp -d 2>/dev/null || mktemp -d -t kubernetes.XXXXXX)\n    kube::util::trap_add kube::util::cleanup-temp-dir EXIT\n  fi\n}\n\nkube::util::host_os() {\n  local host_os\n  case \"$(uname -s)\" in\n    Darwin)\n      host_os=darwin\n      ;;\n    Linux)\n      host_os=linux\n      ;;\n    *)\n      kube::log::error \"Unsupported host OS.  Must be Linux or Mac OS X.\"\n      exit 1\n      ;;\n  esac\n  echo \"${host_os}\"\n}\n\nkube::util::host_arch() {\n  local host_arch\n  case \"$(uname -m)\" in\n    x86_64*)\n      host_arch=amd64\n      ;;\n    i?86_64*)\n      host_arch=amd64\n      ;;\n    amd64*)\n      host_arch=amd64\n      ;;\n    aarch64*)\n      host_arch=arm64\n      ;;\n    arm64*)\n      host_arch=arm64\n      ;;\n    arm*)\n      host_arch=arm\n      ;;\n    i?86*)\n      host_arch=x86\n      ;;\n    s390x*)\n      host_arch=s390x\n      ;;\n    ppc64le*)\n      host_arch=ppc64le\n      ;;\n    *)\n      kube::log::error \"Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le.\"\n      exit 1\n      ;;\n  esac\n  echo \"${host_arch}\"\n}\n\n# This figures out the host platform without relying on golang.  We need this as\n# we don't want a golang install to be a prerequisite to building yet we need\n# this info to figure out where the final binaries are placed.\nkube::util::host_platform() {\n  echo \"$(kube::util::host_os)/$(kube::util::host_arch)\"\n}\n\n# looks for $1 in well-known output locations for the platform ($2)\n# $KUBE_ROOT must be set\nkube::util::find-binary-for-platform() {\n  local -r lookfor=\"$1\"\n  local -r platform=\"$2\"\n  local locations=(\n    \"${KUBE_ROOT}/_output/bin/${lookfor}\"\n    \"${KUBE_ROOT}/_output/dockerized/bin/${platform}/${lookfor}\"\n    \"${KUBE_ROOT}/_output/local/bin/${platform}/${lookfor}\"\n    \"${KUBE_ROOT}/platforms/${platform}/${lookfor}\"\n  )\n  # if we're looking for the host platform, add local non-platform-qualified search paths\n  if [[ \"${platform}\" = \"$(kube::util::host_platform)\" ]]; then\n    locations+=(\n      \"${KUBE_ROOT}/_output/local/go/bin/${lookfor}\"\n      \"${KUBE_ROOT}/_output/dockerized/go/bin/${lookfor}\"\n    );\n  fi\n\n  # List most recently-updated location.\n  local -r bin=$( (ls -t \"${locations[@]}\" 2>/dev/null || true) | head -1 )\n\n  if [[ -z \"${bin}\" ]]; then\n    kube::log::error \"Failed to find binary ${lookfor} for platform ${platform}\"\n    return 1\n  fi\n\n  echo -n \"${bin}\"\n}\n\n# looks for $1 in well-known output locations for the host platform\n# $KUBE_ROOT must be set\nkube::util::find-binary() {\n  kube::util::find-binary-for-platform \"$1\" \"$(kube::util::host_platform)\"\n}\n\n# Run all known doc generators (today gendocs and genman for kubectl)\n# $1 is the directory to put those generated documents\nkube::util::gen-docs() {\n  local dest=\"$1\"\n\n  # Find binary\n  gendocs=$(kube::util::find-binary \"gendocs\")\n  genkubedocs=$(kube::util::find-binary \"genkubedocs\")\n  genman=$(kube::util::find-binary \"genman\")\n  genyaml=$(kube::util::find-binary \"genyaml\")\n\n  mkdir -p \"${dest}/docs/user-guide/kubectl/\"\n  \"${gendocs}\" \"${dest}/docs/user-guide/kubectl/\"\n  mkdir -p \"${dest}/docs/admin/\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kube-apiserver\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kube-controller-manager\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kube-proxy\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kube-scheduler\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kubelet\"\n  \"${genkubedocs}\" \"${dest}/docs/admin/\" \"kubeadm\"\n\n  mkdir -p \"${dest}/docs/man/man1/\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kube-apiserver\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kube-controller-manager\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kube-proxy\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kube-scheduler\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kubelet\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kubectl\"\n  \"${genman}\" \"${dest}/docs/man/man1/\" \"kubeadm\"\n\n  mkdir -p \"${dest}/docs/yaml/kubectl/\"\n  \"${genyaml}\" \"${dest}/docs/yaml/kubectl/\"\n\n  # create the list of generated files\n  pushd \"${dest}\" > /dev/null || return 1\n  touch docs/.generated_docs\n  find . -type f | cut -sd / -f 2- | LC_ALL=C sort > docs/.generated_docs\n  popd > /dev/null || return 1\n}\n\n# Removes previously generated docs-- we don't want to check them in. $KUBE_ROOT\n# must be set.\nkube::util::remove-gen-docs() {\n  if [ -e \"${KUBE_ROOT}/docs/.generated_docs\" ]; then\n    # remove all of the old docs; we don't want to check them in.\n    while read -r file; do\n      rm \"${KUBE_ROOT}/${file}\" 2>/dev/null || true\n    done <\"${KUBE_ROOT}/docs/.generated_docs\"\n    # The docs/.generated_docs file lists itself, so we don't need to explicitly\n    # delete it.\n  fi\n}\n\n# Takes a group/version and returns the path to its location on disk, sans\n# \"pkg\". E.g.:\n# * default behavior: extensions/v1beta1 -> apis/extensions/v1beta1\n# * default behavior for only a group: experimental -> apis/experimental\n# * Special handling for empty group: v1 -> api/v1, unversioned -> api/unversioned\n# * Special handling for groups suffixed with \".k8s.io\": foo.k8s.io/v1 -> apis/foo/v1\n# * Very special handling for when both group and version are \"\": / -> api\n#\n# $KUBE_ROOT must be set.\nkube::util::group-version-to-pkg-path() {\n  local group_version=\"$1\"\n\n  while IFS=$'\\n' read -r api; do\n    if [[ \"${api}\" = \"${group_version/.*k8s.io/}\" ]]; then\n      echo \"vendor/k8s.io/api/${group_version/.*k8s.io/}\"\n      return\n    fi\n  done < <(cd \"${KUBE_ROOT}/staging/src/k8s.io/api\" && find . -name types.go -exec dirname {} \\; | sed \"s|\\./||g\" | sort)\n\n  # \"v1\" is the API GroupVersion\n  if [[ \"${group_version}\" == \"v1\" ]]; then\n    echo \"vendor/k8s.io/api/core/v1\"\n    return\n  fi\n\n  # Special cases first.\n  # TODO(lavalamp): Simplify this by moving pkg/api/v1 and splitting pkg/api,\n  # moving the results to pkg/apis/api.\n  case \"${group_version}\" in\n    # both group and version are \"\", this occurs when we generate deep copies for internal objects of the legacy v1 API.\n    __internal)\n      echo \"pkg/apis/core\"\n      ;;\n    meta/v1)\n      echo \"vendor/k8s.io/apimachinery/pkg/apis/meta/v1\"\n      ;;\n    meta/v1beta1)\n      echo \"vendor/k8s.io/apimachinery/pkg/apis/meta/v1beta1\"\n      ;;\n    internal.apiserver.k8s.io/v1alpha1)\n      echo \"vendor/k8s.io/api/apiserverinternal/v1alpha1\"\n      ;;\n    *.k8s.io)\n      echo \"pkg/apis/${group_version%.*k8s.io}\"\n      ;;\n    *.k8s.io/*)\n      echo \"pkg/apis/${group_version/.*k8s.io/}\"\n      ;;\n    *)\n      echo \"pkg/apis/${group_version%__internal}\"\n      ;;\n  esac\n}\n\n# Takes a group/version and returns the swagger-spec file name.\n# default behavior: extensions/v1beta1 -> extensions_v1beta1\n# special case for v1: v1 -> v1\nkube::util::gv-to-swagger-name() {\n  local group_version=\"$1\"\n  case \"${group_version}\" in\n    v1)\n      echo \"v1\"\n      ;;\n    *)\n      echo \"${group_version%/*}_${group_version#*/}\"\n      ;;\n  esac\n}\n\n# Returns the name of the upstream remote repository name for the local git\n# repo, e.g. \"upstream\" or \"origin\".\nkube::util::git_upstream_remote_name() {\n  git remote -v | grep fetch |\\\n    grep -E 'github.com[/:]kubernetes/kubernetes|k8s.io/kubernetes' |\\\n    head -n 1 | awk '{print $1}'\n}\n\n# Exits script if working directory is dirty. If it's run interactively in the terminal\n# the user can commit changes in a second terminal. This script will wait.\nkube::util::ensure_clean_working_dir() {\n  while ! git diff HEAD --exit-code &>/dev/null; do\n    echo -e \"\\nUnexpected dirty working directory:\\n\"\n    if tty -s; then\n        git status -s\n    else\n        git diff -a # be more verbose in log files without tty\n        exit 1\n    fi | sed 's/^/  /'\n    echo -e \"\\nCommit your changes in another terminal and then continue here by pressing enter.\"\n    read -r\n  done 1>&2\n}\n\n# Find the base commit using:\n# $PULL_BASE_SHA if set (from Prow)\n# current ref from the remote upstream branch\nkube::util::base_ref() {\n  local -r git_branch=$1\n\n  if [[ -n ${PULL_BASE_SHA:-} ]]; then\n    echo \"${PULL_BASE_SHA}\"\n    return\n  fi\n\n  full_branch=\"$(kube::util::git_upstream_remote_name)/${git_branch}\"\n\n  # make sure the branch is valid, otherwise the check will pass erroneously.\n  if ! git describe \"${full_branch}\" >/dev/null; then\n    # abort!\n    exit 1\n  fi\n\n  echo \"${full_branch}\"\n}\n\n# Checks whether there are any files matching pattern $2 changed between the\n# current branch and upstream branch named by $1.\n# Returns 1 (false) if there are no changes\n#         0 (true) if there are changes detected.\nkube::util::has_changes() {\n  local -r git_branch=$1\n  local -r pattern=$2\n  local -r not_pattern=${3:-totallyimpossiblepattern}\n\n  local base_ref\n  base_ref=$(kube::util::base_ref \"${git_branch}\")\n  echo \"Checking for '${pattern}' changes against '${base_ref}'\"\n\n  # notice this uses ... to find the first shared ancestor\n  if git diff --name-only \"${base_ref}...HEAD\" | grep -v -E \"${not_pattern}\" | grep \"${pattern}\" > /dev/null; then\n    return 0\n  fi\n  # also check for pending changes\n  if git status --porcelain | grep -v -E \"${not_pattern}\" | grep \"${pattern}\" > /dev/null; then\n    echo \"Detected '${pattern}' uncommitted changes.\"\n    return 0\n  fi\n  echo \"No '${pattern}' changes detected.\"\n  return 1\n}\n\nkube::util::download_file() {\n  local -r url=$1\n  local -r destination_file=$2\n\n  rm \"${destination_file}\" 2&> /dev/null || true\n\n  for i in $(seq 5)\n  do\n    if ! curl -fsSL --retry 3 --keepalive-time 2 \"${url}\" -o \"${destination_file}\"; then\n      echo \"Downloading ${url} failed. $((5-i)) retries left.\"\n      sleep 1\n    else\n      echo \"Downloading ${url} succeed\"\n      return 0\n    fi\n  done\n  return 1\n}\n\n# Test whether openssl is installed.\n# Sets:\n#  OPENSSL_BIN: The path to the openssl binary to use\nfunction kube::util::test_openssl_installed {\n    if ! openssl version >& /dev/null; then\n      echo \"Failed to run openssl. Please ensure openssl is installed\"\n      exit 1\n    fi\n\n    OPENSSL_BIN=$(command -v openssl)\n}\n\n# Query the API server for client certificate authentication capabilities\nfunction kube::util::test_client_certificate_authentication_enabled {\n  local output\n  kube::util::test_openssl_installed\n\n  output=$(echo \\\n    | \"${OPENSSL_BIN}\" s_client -connect \"127.0.0.1:${SECURE_API_PORT}\" 2> /dev/null \\\n    | grep -A3 'Acceptable client certificate CA names')\n\n  if [[ \"${output}\" != *\"/CN=127.0.0.1\"* ]] && [[ \"${output}\" != *\"CN = 127.0.0.1\"* ]]; then\n    echo \"API server not configured for client certificate authentication\"\n    echo \"Output of from acceptable client certificate check: ${output}\"\n    exit 1\n  fi\n}\n\n# creates a client CA, args are sudo, dest-dir, ca-id, purpose\n# purpose is dropped in after \"key encipherment\", you usually want\n# '\"client auth\"'\n# '\"server auth\"'\n# '\"client auth\",\"server auth\"'\nfunction kube::util::create_signing_certkey {\n    local sudo=$1\n    local dest_dir=$2\n    local id=$3\n    local purpose=$4\n    # Create client ca\n    ${sudo} /usr/bin/env bash -e <<EOF\n    rm -f \"${dest_dir}/${id}-ca.crt\" \"${dest_dir}/${id}-ca.key\"\n    ${OPENSSL_BIN} req -x509 -sha256 -new -nodes -days 365 -newkey rsa:2048 -keyout \"${dest_dir}/${id}-ca.key\" -out \"${dest_dir}/${id}-ca.crt\" -subj \"/C=xx/ST=x/L=x/O=x/OU=x/CN=ca/emailAddress=x/\"\n    echo '{\"signing\":{\"default\":{\"expiry\":\"43800h\",\"usages\":[\"signing\",\"key encipherment\",${purpose}]}}}' > \"${dest_dir}/${id}-ca-config.json\"\nEOF\n}\n\n# signs a client certificate: args are sudo, dest-dir, CA, filename (roughly), username, groups...\nfunction kube::util::create_client_certkey {\n    local sudo=$1\n    local dest_dir=$2\n    local ca=$3\n    local id=$4\n    local cn=${5:-$4}\n    local groups=\"\"\n    local SEP=\"\"\n    shift 5\n    while [ -n \"${1:-}\" ]; do\n        groups+=\"${SEP}{\\\"O\\\":\\\"$1\\\"}\"\n        SEP=\",\"\n        shift 1\n    done\n    ${sudo} /usr/bin/env bash -e <<EOF\n    cd ${dest_dir}\n    echo '{\"CN\":\"${cn}\",\"names\":[${groups}],\"hosts\":[\"\"],\"key\":{\"algo\":\"rsa\",\"size\":2048}}' | ${CFSSL_BIN} gencert -ca=${ca}.crt -ca-key=${ca}.key -config=${ca}-config.json - | ${CFSSLJSON_BIN} -bare client-${id}\n    mv \"client-${id}-key.pem\" \"client-${id}.key\"\n    mv \"client-${id}.pem\" \"client-${id}.crt\"\n    rm -f \"client-${id}.csr\"\nEOF\n}\n\n# signs a serving certificate: args are sudo, dest-dir, ca, filename (roughly), subject, hosts...\nfunction kube::util::create_serving_certkey {\n    local sudo=$1\n    local dest_dir=$2\n    local ca=$3\n    local id=$4\n    local cn=${5:-$4}\n    local hosts=\"\"\n    local SEP=\"\"\n    shift 5\n    while [ -n \"${1:-}\" ]; do\n        hosts+=\"${SEP}\\\"$1\\\"\"\n        SEP=\",\"\n        shift 1\n    done\n    ${sudo} /usr/bin/env bash -e <<EOF\n    cd ${dest_dir}\n    echo '{\"CN\":\"${cn}\",\"hosts\":[${hosts}],\"key\":{\"algo\":\"rsa\",\"size\":2048}}' | ${CFSSL_BIN} gencert -ca=${ca}.crt -ca-key=${ca}.key -config=${ca}-config.json - | ${CFSSLJSON_BIN} -bare serving-${id}\n    mv \"serving-${id}-key.pem\" \"serving-${id}.key\"\n    mv \"serving-${id}.pem\" \"serving-${id}.crt\"\n    rm -f \"serving-${id}.csr\"\nEOF\n}\n\n# creates a self-contained kubeconfig: args are sudo, dest-dir, ca file, host, port, client id, token(optional)\nfunction kube::util::write_client_kubeconfig {\n    local sudo=$1\n    local dest_dir=$2\n    local ca_file=$3\n    local api_host=$4\n    local api_port=$5\n    local client_id=$6\n    local token=${7:-}\n    cat <<EOF | ${sudo} tee \"${dest_dir}\"/\"${client_id}\".kubeconfig > /dev/null\napiVersion: v1\nkind: Config\nclusters:\n  - cluster:\n      certificate-authority: ${ca_file}\n      server: https://${api_host}:${api_port}/\n    name: local-up-cluster\nusers:\n  - user:\n      token: ${token}\n      client-certificate: ${dest_dir}/client-${client_id}.crt\n      client-key: ${dest_dir}/client-${client_id}.key\n    name: local-up-cluster\ncontexts:\n  - context:\n      cluster: local-up-cluster\n      user: local-up-cluster\n    name: local-up-cluster\ncurrent-context: local-up-cluster\nEOF\n\n    # flatten the kubeconfig files to make them self contained\n    username=$(whoami)\n    ${sudo} /usr/bin/env bash -e <<EOF\n    $(kube::util::find-binary kubectl) --kubeconfig=\"${dest_dir}/${client_id}.kubeconfig\" config view --minify --flatten > \"/tmp/${client_id}.kubeconfig\"\n    mv -f \"/tmp/${client_id}.kubeconfig\" \"${dest_dir}/${client_id}.kubeconfig\"\n    chown ${username} \"${dest_dir}/${client_id}.kubeconfig\"\nEOF\n}\n\n# list_staging_repos outputs a sorted list of repos in staging/src/k8s.io\n# each entry will just be the $repo portion of staging/src/k8s.io/$repo/...\n# $KUBE_ROOT must be set.\nfunction kube::util::list_staging_repos() {\n  (\n    cd \"${KUBE_ROOT}/staging/src/k8s.io\" && \\\n    find . -mindepth 1 -maxdepth 1 -type d | cut -c 3- | sort\n  )\n}\n\n\n# Determines if docker can be run, failures may simply require that the user be added to the docker group.\nfunction kube::util::ensure_docker_daemon_connectivity {\n  IFS=\" \" read -ra DOCKER <<< \"${DOCKER_OPTS}\"\n  # Expand ${DOCKER[@]} only if it's not unset. This is to work around\n  # Bash 3 issue with unbound variable.\n  DOCKER=(docker ${DOCKER[@]:+\"${DOCKER[@]}\"})\n  if ! \"${DOCKER[@]}\" info > /dev/null 2>&1 ; then\n    cat <<'EOF' >&2\nCan't connect to 'docker' daemon.  please fix and retry.\n\nPossible causes:\n  - Docker Daemon not started\n    - Linux: confirm via your init system\n    - macOS w/ Docker for Mac: Check the menu bar and start the Docker application\n  - DOCKER_HOST hasn't been set or is set incorrectly\n    - Linux: domain socket is used, DOCKER_* should be unset. In Bash run `unset ${!DOCKER_*}`\n    - macOS w/ Docker for Mac: domain socket is used, DOCKER_* should be unset. In Bash run `unset ${!DOCKER_*}`\n  - Other things to check:\n    - Linux: User isn't in 'docker' group.  Add and relogin.\n      - Something like 'sudo usermod -a -G docker ${USER}'\n      - RHEL7 bug and workaround: https://bugzilla.redhat.com/show_bug.cgi?id=1119282#c8\nEOF\n    return 1\n  fi\n}\n\n# Wait for background jobs to finish. Return with\n# an error status if any of the jobs failed.\nkube::util::wait-for-jobs() {\n  local fail=0\n  local job\n  for job in $(jobs -p); do\n    wait \"${job}\" || fail=$((fail + 1))\n  done\n  return ${fail}\n}\n\n# kube::util::join <delim> <list...>\n# Concatenates the list elements with the delimiter passed as first parameter\n#\n# Ex: kube::util::join , a b c\n#  -> a,b,c\nfunction kube::util::join {\n  local IFS=\"$1\"\n  shift\n  echo \"$*\"\n}\n\n# Downloads cfssl/cfssljson into $1 directory if they do not already exist in PATH\n#\n# Assumed vars:\n#   $1 (cfssl directory) (optional)\n#\n# Sets:\n#  CFSSL_BIN: The path of the installed cfssl binary\n#  CFSSLJSON_BIN: The path of the installed cfssljson binary\n#\nfunction kube::util::ensure-cfssl {\n  if command -v cfssl &>/dev/null && command -v cfssljson &>/dev/null; then\n    CFSSL_BIN=$(command -v cfssl)\n    CFSSLJSON_BIN=$(command -v cfssljson)\n    return 0\n  fi\n\n  host_arch=$(kube::util::host_arch)\n\n  if [[ \"${host_arch}\" != \"amd64\" ]]; then\n    echo \"Cannot download cfssl on non-amd64 hosts and cfssl does not appear to be installed.\"\n    echo \"Please install cfssl and cfssljson and verify they are in \\$PATH.\"\n    echo \"Hint: export PATH=\\$PATH:\\$GOPATH/bin; go get -u github.com/cloudflare/cfssl/cmd/...\"\n    exit 1\n  fi\n\n  # Create a temp dir for cfssl if no directory was given\n  local cfssldir=${1:-}\n  if [[ -z \"${cfssldir}\" ]]; then\n    kube::util::ensure-temp-dir\n    cfssldir=\"${KUBE_TEMP}/cfssl\"\n  fi\n\n  mkdir -p \"${cfssldir}\"\n  pushd \"${cfssldir}\" > /dev/null || return 1\n\n    echo \"Unable to successfully run 'cfssl' from ${PATH}; downloading instead...\"\n    kernel=$(uname -s)\n    case \"${kernel}\" in\n      Linux)\n        curl --retry 10 -L -o cfssl https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssl_1.5.0_linux_amd64\n        curl --retry 10 -L -o cfssljson https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssljson_1.5.0_linux_amd64\n        ;;\n      Darwin)\n        curl --retry 10 -L -o cfssl https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssl_1.5.0_darwin_amd64\n        curl --retry 10 -L -o cfssljson https://github.com/cloudflare/cfssl/releases/download/v1.5.0/cfssljson_1.5.0_darwin_amd64\n        ;;\n      *)\n        echo \"Unknown, unsupported platform: ${kernel}.\" >&2\n        echo \"Supported platforms: Linux, Darwin.\" >&2\n        exit 2\n    esac\n\n    chmod +x cfssl || true\n    chmod +x cfssljson || true\n\n    CFSSL_BIN=\"${cfssldir}/cfssl\"\n    CFSSLJSON_BIN=\"${cfssldir}/cfssljson\"\n    if [[ ! -x ${CFSSL_BIN} || ! -x ${CFSSLJSON_BIN} ]]; then\n      echo \"Failed to download 'cfssl'. Please install cfssl and cfssljson and verify they are in \\$PATH.\"\n      echo \"Hint: export PATH=\\$PATH:\\$GOPATH/bin; go get -u github.com/cloudflare/cfssl/cmd/...\"\n      exit 1\n    fi\n  popd > /dev/null || return 1\n}\n\n# kube::util::ensure_dockerized\n# Confirms that the script is being run inside a kube-build image\n#\nfunction kube::util::ensure_dockerized {\n  if [[ -f /kube-build-image ]]; then\n    return 0\n  else\n    echo \"ERROR: This script is designed to be run inside a kube-build container\"\n    exit 1\n  fi\n}\n\n# kube::util::ensure-bash-version\n# Check if we are using a supported bash version\n#\nfunction kube::util::ensure-bash-version {\n  # shellcheck disable=SC2004\n  if ((${BASH_VERSINFO[0]}<4)) || ( ((${BASH_VERSINFO[0]}==4)) && ((${BASH_VERSINFO[1]}<2)) ); then\n    echo \"ERROR: This script requires a minimum bash version of 4.2, but got version of ${BASH_VERSINFO[0]}.${BASH_VERSINFO[1]}\"\n    if [ \"$(uname)\" = 'Darwin' ]; then\n      echo \"On macOS with homebrew 'brew install bash' is sufficient.\"\n    fi\n    exit 1\n  fi\n}\n\n# kube::util::ensure-gnu-sed\n# Determines which sed binary is gnu-sed on linux/darwin\n#\n# Sets:\n#  SED: The name of the gnu-sed binary\n#\nfunction kube::util::ensure-gnu-sed {\n  # NOTE: the echo below is a workaround to ensure sed is executed before the grep.\n  # see: https://github.com/kubernetes/kubernetes/issues/87251\n  sed_help=\"$(LANG=C sed --help 2>&1 || true)\"\n  if echo \"${sed_help}\" | grep -q \"GNU\\|BusyBox\"; then\n    SED=\"sed\"\n  elif command -v gsed &>/dev/null; then\n    SED=\"gsed\"\n  else\n    kube::log::error \"Failed to find GNU sed as sed or gsed. If you are on Mac: brew install gnu-sed.\" >&2\n    return 1\n  fi\n  kube::util::sourced_variable \"${SED}\"\n}\n\n# kube::util::check-file-in-alphabetical-order <file>\n# Check that the file is in alphabetical order\n#\nfunction kube::util::check-file-in-alphabetical-order {\n  local failure_file=\"$1\"\n  if ! diff -u \"${failure_file}\" <(LC_ALL=C sort \"${failure_file}\"); then\n    {\n      echo\n      echo \"${failure_file} is not in alphabetical order. Please sort it:\"\n      echo\n      echo \"  LC_ALL=C sort -o ${failure_file} ${failure_file}\"\n      echo\n    } >&2\n    false\n  fi\n}\n\n# kube::util::require-jq\n# Checks whether jq is installed.\nfunction kube::util::require-jq {\n  if ! command -v jq &>/dev/null; then\n    kube::log::error  \"jq not found. Please install.\"\n    return 1\n  fi\n}\n\n# outputs md5 hash of $1, works on macOS and Linux\nfunction kube::util::md5() {\n  if which md5 >/dev/null 2>&1; then\n    md5 -q \"$1\"\n  else\n    md5sum \"$1\" | awk '{ print $1 }'\n  fi\n}\n\n# kube::util::read-array\n# Reads in stdin and adds it line by line to the array provided. This can be\n# used instead of \"mapfile -t\", and is bash 3 compatible.\n#\n# Assumed vars:\n#   $1 (name of array to create/modify)\n#\n# Example usage:\n# kube::util::read-array files < <(ls -1)\n#\nfunction kube::util::read-array {\n  local i=0\n  unset -v \"$1\"\n  while IFS= read -r \"$1[i++]\"; do :; done\n  eval \"[[ \\${$1[--i]} ]]\" || unset \"$1[i]\" # ensures last element isn't empty\n}\n\n# Some useful colors.\nif [[ -z \"${color_start-}\" ]]; then\n  declare -r color_start=\"\\033[\"\n  declare -r color_red=\"${color_start}0;31m\"\n  declare -r color_yellow=\"${color_start}0;33m\"\n  declare -r color_green=\"${color_start}0;32m\"\n  declare -r color_blue=\"${color_start}1;34m\"\n  declare -r color_cyan=\"${color_start}1;36m\"\n  declare -r color_norm=\"${color_start}0m\"\n\n  kube::util::sourced_variable \"${color_start}\"\n  kube::util::sourced_variable \"${color_red}\"\n  kube::util::sourced_variable \"${color_yellow}\"\n  kube::util::sourced_variable \"${color_green}\"\n  kube::util::sourced_variable \"${color_blue}\"\n  kube::util::sourced_variable \"${color_cyan}\"\n  kube::util::sourced_variable \"${color_norm}\"\nfi\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 829}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# -----------------------------------------------------------------------------\n# Version management helpers.  These functions help to set, save and load the\n# following variables:\n#\n#    KUBE_GIT_COMMIT - The git commit id corresponding to this\n#          source code.\n#    KUBE_GIT_TREE_STATE - \"clean\" indicates no changes since the git commit id\n#        \"dirty\" indicates source code changes after the git commit id\n#        \"archive\" indicates the tree was produced by 'git archive'\n#    KUBE_GIT_VERSION - \"vX.Y\" used to indicate the last release version.\n#    KUBE_GIT_MAJOR - The major part of the version\n#    KUBE_GIT_MINOR - The minor component of the version\n\n# Grovels through git to set a set of env variables.\n#\n# If KUBE_GIT_VERSION_FILE, this function will load from that file instead of\n# querying git.\nkube::version::get_version_vars() {\n  if [[ -n ${KUBE_GIT_VERSION_FILE-} ]]; then\n    kube::version::load_version_vars \"${KUBE_GIT_VERSION_FILE}\"\n    return\n  fi\n\n  # If the kubernetes source was exported through git archive, then\n  # we likely don't have a git tree, but these magic values may be filled in.\n  # shellcheck disable=SC2016,SC2050\n  # Disabled as we're not expanding these at runtime, but rather expecting\n  # that another tool may have expanded these and rewritten the source (!)\n  if [[ '$Format:%%$' == \"%\" ]]; then\n    KUBE_GIT_COMMIT='$Format:%H$'\n    KUBE_GIT_TREE_STATE=\"archive\"\n    # When a 'git archive' is exported, the '$Format:%D$' below will look\n    # something like 'HEAD -> release-1.8, tag: v1.8.3' where then 'tag: '\n    # can be extracted from it.\n    if [[ '$Format:%D$' =~ tag:\\ (v[^ ,]+) ]]; then\n     KUBE_GIT_VERSION=\"${BASH_REMATCH[1]}\"\n    fi\n  fi\n\n  local git=(git --work-tree \"${KUBE_ROOT}\")\n\n  if [[ -n ${KUBE_GIT_COMMIT-} ]] || KUBE_GIT_COMMIT=$(\"${git[@]}\" rev-parse \"HEAD^{commit}\" 2>/dev/null); then\n    if [[ -z ${KUBE_GIT_TREE_STATE-} ]]; then\n      # Check if the tree is dirty.  default to dirty\n      if git_status=$(\"${git[@]}\" status --porcelain 2>/dev/null) && [[ -z ${git_status} ]]; then\n        KUBE_GIT_TREE_STATE=\"clean\"\n      else\n        KUBE_GIT_TREE_STATE=\"dirty\"\n      fi\n    fi\n\n    # Use git describe to find the version based on tags.\n    if [[ -n ${KUBE_GIT_VERSION-} ]] || KUBE_GIT_VERSION=$(\"${git[@]}\" describe --tags --match='v*' --abbrev=14 \"${KUBE_GIT_COMMIT}^{commit}\" 2>/dev/null); then\n      # This translates the \"git describe\" to an actual semver.org\n      # compatible semantic version that looks something like this:\n      #   v1.1.0-alpha.0.6+84c76d1142ea4d\n      #\n      # TODO: We continue calling this \"git version\" because so many\n      # downstream consumers are expecting it there.\n      #\n      # These regexes are painful enough in sed...\n      # We don't want to do them in pure shell, so disable SC2001\n      # shellcheck disable=SC2001\n      DASHES_IN_VERSION=$(echo \"${KUBE_GIT_VERSION}\" | sed \"s/[^-]//g\")\n      if [[ \"${DASHES_IN_VERSION}\" == \"---\" ]] ; then\n        # shellcheck disable=SC2001\n        # We have distance to subversion (v1.1.0-subversion-1-gCommitHash)\n        KUBE_GIT_VERSION=$(echo \"${KUBE_GIT_VERSION}\" | sed \"s/-\\([0-9]\\{1,\\}\\)-g\\([0-9a-f]\\{14\\}\\)$/.\\1\\+\\2/\")\n      elif [[ \"${DASHES_IN_VERSION}\" == \"--\" ]] ; then\n        # shellcheck disable=SC2001\n        # We have distance to base tag (v1.1.0-1-gCommitHash)\n        KUBE_GIT_VERSION=$(echo \"${KUBE_GIT_VERSION}\" | sed \"s/-g\\([0-9a-f]\\{14\\}\\)$/+\\1/\")\n      fi\n      if [[ \"${KUBE_GIT_TREE_STATE}\" == \"dirty\" ]]; then\n        # git describe --dirty only considers changes to existing files, but\n        # that is problematic since new untracked .go files affect the build,\n        # so use our idea of \"dirty\" from git status instead.\n        KUBE_GIT_VERSION+=\"-dirty\"\n      fi\n\n\n      # Try to match the \"git describe\" output to a regex to try to extract\n      # the \"major\" and \"minor\" versions and whether this is the exact tagged\n      # version or whether the tree is between two tagged versions.\n      if [[ \"${KUBE_GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?([-].*)?([+].*)?$ ]]; then\n        KUBE_GIT_MAJOR=${BASH_REMATCH[1]}\n        KUBE_GIT_MINOR=${BASH_REMATCH[2]}\n        if [[ -n \"${BASH_REMATCH[4]}\" ]]; then\n          KUBE_GIT_MINOR+=\"+\"\n        fi\n      fi\n\n      # If KUBE_GIT_VERSION is not a valid Semantic Version, then refuse to build.\n      if ! [[ \"${KUBE_GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$ ]]; then\n          kube::log::error \"KUBE_GIT_VERSION should be a valid Semantic Version. Current value: ${KUBE_GIT_VERSION}\"\n          kube::log::error \"Please see more details here: https://semver.org\"\n          exit 1\n      fi\n    fi\n  fi\n}\n\n# Saves the environment flags to $1\nkube::version::save_version_vars() {\n  local version_file=${1-}\n  [[ -n ${version_file} ]] || {\n    echo \"!!! Internal error.  No file specified in kube::version::save_version_vars\"\n    return 1\n  }\n\n  cat <<EOF >\"${version_file}\"\nKUBE_GIT_COMMIT='${KUBE_GIT_COMMIT-}'\nKUBE_GIT_TREE_STATE='${KUBE_GIT_TREE_STATE-}'\nKUBE_GIT_VERSION='${KUBE_GIT_VERSION-}'\nKUBE_GIT_MAJOR='${KUBE_GIT_MAJOR-}'\nKUBE_GIT_MINOR='${KUBE_GIT_MINOR-}'\nEOF\n}\n\n# Loads up the version variables from file $1\nkube::version::load_version_vars() {\n  local version_file=${1-}\n  [[ -n ${version_file} ]] || {\n    echo \"!!! Internal error.  No file specified in kube::version::load_version_vars\"\n    return 1\n  }\n\n  source \"${version_file}\"\n}\n\n# Prints the value that needs to be passed to the -ldflags parameter of go build\n# in order to set the Kubernetes based on the git tree status.\n# IMPORTANT: if you update any of these, also update the lists in\n# pkg/version/def.bzl and hack/print-workspace-status.sh.\nkube::version::ldflags() {\n  kube::version::get_version_vars\n\n  local -a ldflags\n  function add_ldflag() {\n    local key=${1}\n    local val=${2}\n    # If you update these, also update the list component-base/version/def.bzl.\n    ldflags+=(\n      \"-X '${KUBE_GO_PACKAGE}/vendor/k8s.io/client-go/pkg/version.${key}=${val}'\"\n      \"-X '${KUBE_GO_PACKAGE}/vendor/k8s.io/component-base/version.${key}=${val}'\"\n    )\n  }\n\n  add_ldflag \"buildDate\" \"$(date ${SOURCE_DATE_EPOCH:+\"--date=@${SOURCE_DATE_EPOCH}\"} -u +'%Y-%m-%dT%H:%M:%SZ')\"\n  if [[ -n ${KUBE_GIT_COMMIT-} ]]; then\n    add_ldflag \"gitCommit\" \"${KUBE_GIT_COMMIT}\"\n    add_ldflag \"gitTreeState\" \"${KUBE_GIT_TREE_STATE}\"\n  fi\n\n  if [[ -n ${KUBE_GIT_VERSION-} ]]; then\n    add_ldflag \"gitVersion\" \"${KUBE_GIT_VERSION}\"\n  fi\n\n  if [[ -n ${KUBE_GIT_MAJOR-} && -n ${KUBE_GIT_MINOR-} ]]; then\n    add_ldflag \"gitMajor\" \"${KUBE_GIT_MAJOR}\"\n    add_ldflag \"gitMinor\" \"${KUBE_GIT_MINOR}\"\n  fi\n\n  # The -ldflags parameter takes a single string, so join the output.\n  echo \"${ldflags[*]-}\"\n}\n", "num_lines": 183}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script sets up a go workspace locally and builds all go components.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nKUBE_VERBOSE=\"${KUBE_VERBOSE:-1}\"\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::build_binaries \"$@\"\nkube::golang::place_bins\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nCLEAN_PATTERNS=(\n  \"_tmp\"\n  \"doc_tmp\"\n  \"((?!staging\\/src\\/k8s\\.io\\/apiextensions-apiserver\\/pkg\\/generated\\/openapi).)*/zz_generated.openapi.go\"\n  \"test/e2e/generated/bindata.go\"\n  # TODO(bentheelder): remove this pattern after bazel is not in any supported releases\n  # see: https://github.com/kubernetes/enhancements/issues/2420\n  \"bazel-.*\"\n)\n\nfor pattern in \"${CLEAN_PATTERNS[@]}\"; do\n  while IFS=$'\\n' read -r match; do\n    echo \"Removing ${match#${KUBE_ROOT}\\/} ..\"\n    rm -rf \"${match#${KUBE_ROOT}\\/}\"\n  done <   <(find \"${KUBE_ROOT}\" -iregex \"^${KUBE_ROOT}/${pattern}$\")\ndone\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script sets up a go workspace locally and builds all for all appropriate\n# platforms.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# NOTE: Using \"${array[*]}\" here is correct.  [@] becomes distinct words (in\n# bash parlance).\n\nmake all WHAT=\"${KUBE_SERVER_TARGETS[*]}\" KUBE_BUILD_PLATFORMS=\"${KUBE_SERVER_PLATFORMS[*]}\"\n\nmake all WHAT=\"${KUBE_NODE_TARGETS[*]}\" KUBE_BUILD_PLATFORMS=\"${KUBE_NODE_PLATFORMS[*]}\"\n\nmake all WHAT=\"${KUBE_CLIENT_TARGETS[*]}\" KUBE_BUILD_PLATFORMS=\"${KUBE_CLIENT_PLATFORMS[*]}\"\n\nmake all WHAT=\"${KUBE_TEST_TARGETS[*]}\" KUBE_BUILD_PLATFORMS=\"${KUBE_TEST_PLATFORMS[*]}\"\n\nmake all WHAT=\"${KUBE_TEST_SERVER_TARGETS[*]}\" KUBE_BUILD_PLATFORMS=\"${KUBE_TEST_SERVER_PLATFORMS[*]}\"\n", "num_lines": 39}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nreadonly red=$(tput setaf 1)\nreadonly reset=$(tput sgr0)\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nALL_TARGETS=$(make -C \"${KUBE_ROOT}\" PRINT_HELP=y -rpn | sed -n -e '/^$/ { n ; /^[^ .#][^ ]*:/ { s/:.*$// ; p ; } ; }' | sort)\nCMD_TARGETS=$(cd \"${KUBE_ROOT}/cmd\"; find . -mindepth 1 -maxdepth 1 -type d | cut -c 3-)\nCMD_FLAG=false\n\necho \"--------------------------------------------------------------------------------\"\nfor tar in ${ALL_TARGETS}; do\n\tfor cmdtar in ${CMD_TARGETS}; do\n\t\tif [ \"${tar}\" = \"${cmdtar}\" ]; then\n\t\t\tif [ ${CMD_FLAG} = true ]; then\n\t\t\t\tcontinue 2;\n\t\t\tfi\n\n\t\t\techo -e \"${red}${CMD_TARGETS}${reset}\"\n\t\t\tmake -C \"${KUBE_ROOT}\" \"${tar}\" PRINT_HELP=y\n\t\t\techo \"---------------------------------------------------------------------------------\"\n\n\t\t\tCMD_FLAG=true\n\t\t\tcontinue 2\n\t\tfi\n\tdone\n\n\techo -e \"${red}${tar}${reset}\"\n\tmake -C \"${KUBE_ROOT}\" \"${tar}\" PRINT_HELP=y\n\techo \"---------------------------------------------------------------------------------\"\ndone\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This command checks that the built commands can function together for\n# simple scenarios.  It does not require Docker.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# start the cache mutation detector by default so that cache mutators will be found\nKUBE_CACHE_MUTATION_DETECTOR=\"${KUBE_CACHE_MUTATION_DETECTOR:-true}\"\nexport KUBE_CACHE_MUTATION_DETECTOR\n\n# panic the server on watch decode errors since they are considered coder mistakes\nKUBE_PANIC_WATCH_DECODE_ERROR=\"${KUBE_PANIC_WATCH_DECODE_ERROR:-true}\"\nexport KUBE_PANIC_WATCH_DECODE_ERROR\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/test.sh\"\nsource \"${KUBE_ROOT}/test/cmd/legacy-script.sh\"\n\n# setup envs for TokenRequest required flags\nSERVICE_ACCOUNT_LOOKUP=${SERVICE_ACCOUNT_LOOKUP:-true}\nSERVICE_ACCOUNT_KEY=${SERVICE_ACCOUNT_KEY:-/tmp/kube-serviceaccount.key}\n# Generate ServiceAccount key if needed\nif [[ ! -f \"${SERVICE_ACCOUNT_KEY}\" ]]; then\n  mkdir -p \"$(dirname \"${SERVICE_ACCOUNT_KEY}\")\"\n  openssl genrsa -out \"${SERVICE_ACCOUNT_KEY}\" 2048 2>/dev/null\nfi\n\n# Runs kube-apiserver\n#\n# Exports:\n#   APISERVER_PID\nfunction run_kube_apiserver() {\n  kube::log::status \"Building kube-apiserver\"\n  make -C \"${KUBE_ROOT}\" WHAT=\"cmd/kube-apiserver\"\n\n  # Start kube-apiserver\n  kube::log::status \"Starting kube-apiserver\"\n\n  # Admission Controllers to invoke prior to persisting objects in cluster\n  ENABLE_ADMISSION_PLUGINS=\"LimitRanger,ResourceQuota\"\n  DISABLE_ADMISSION_PLUGINS=\"ServiceAccount,PersistentVolumeLabel,DefaultStorageClass,DefaultTolerationSeconds,MutatingAdmissionWebhook,ValidatingAdmissionWebhook,StorageObjectInUseProtection\"\n\n  # Include RBAC (to exercise bootstrapping), and AlwaysAllow to allow all actions\n  AUTHORIZATION_MODE=\"RBAC,AlwaysAllow\"\n\n  # Enable features\n  ENABLE_FEATURE_GATES=\"ServerSideApply=true\"\n\n  \"${KUBE_OUTPUT_HOSTBIN}/kube-apiserver\" \\\n    --bind-address=\"127.0.0.1\" \\\n    --authorization-mode=\"${AUTHORIZATION_MODE}\" \\\n    --secure-port=\"${SECURE_API_PORT}\" \\\n    --feature-gates=\"${ENABLE_FEATURE_GATES}\" \\\n    --enable-admission-plugins=\"${ENABLE_ADMISSION_PLUGINS}\" \\\n    --disable-admission-plugins=\"${DISABLE_ADMISSION_PLUGINS}\" \\\n    --etcd-servers=\"http://${ETCD_HOST}:${ETCD_PORT}\" \\\n    --runtime-config=api/v1 \\\n    --service-account-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n    --service-account-lookup=\"${SERVICE_ACCOUNT_LOOKUP}\" \\\n    --service-account-issuer=\"https://kubernetes.default.svc\" \\\n    --service-account-signing-key-file=\"${SERVICE_ACCOUNT_KEY}\" \\\n    --storage-media-type=\"${KUBE_TEST_API_STORAGE_TYPE-}\" \\\n    --cert-dir=\"${TMPDIR:-/tmp/}\" \\\n    --service-cluster-ip-range=\"10.0.0.0/24\" \\\n    --client-ca-file=hack/testdata/ca.crt \\\n    --token-auth-file=hack/testdata/auth-tokens.csv 1>&2 &\n  export APISERVER_PID=$!\n\n  kube::util::wait_for_url_with_bearer_token \"https://127.0.0.1:${SECURE_API_PORT}/healthz\" \"admin-token\" \"apiserver\"\n}\n\n# Runs run_kube_controller_manager\n#\n# Exports:\n#   CTLRMGR_PID\nfunction run_kube_controller_manager() {\n  kube::log::status \"Building kube-controller-manager\"\n  make -C \"${KUBE_ROOT}\" WHAT=\"cmd/kube-controller-manager\"\n\n  # Start controller manager\n  kube::log::status 'Generate kubeconfig for controller-manager'\n  local config\n  config=\"$(mktemp controller-manager.kubeconfig.XXXXX)\"\n  cat <<EOF > \"$config\"\nkind: Config\nusers:\n- name: controller-manager\n  user:\n    token: admin-token\nclusters:\n- cluster:\n    server: https://127.0.0.1:${SECURE_API_PORT}\n    insecure-skip-tls-verify: true\n  name: local\ncontexts:\n- context:\n    cluster: local\n    user: controller-manager\n  name: local-context\ncurrent-context: local-context\nEOF\n\n  kube::log::status \"Starting controller-manager\"\n  \"${KUBE_OUTPUT_HOSTBIN}/kube-controller-manager\" \\\n    --kube-api-content-type=\"${KUBE_TEST_API_TYPE-}\" \\\n    --kubeconfig=\"${config}\" 1>&2 &\n  export CTLRMGR_PID=$!\n\n  kube::util::wait_for_url \"https://127.0.0.1:${SECURE_CTLRMGR_PORT}/healthz\" \"controller-manager\"\n}\n\n# Creates a node object with name 127.0.0.1. This is required because we do not\n# run kubelet.\n#\n# An arbitrary annotation is needed to ensure field managers are saved on the\n# object. Without it, we would be creating an empty object and because status\n# and name get wiped, there were be no field managers tracking any fields.\n#\n# Exports:\n#   SUPPORTED_RESOURCES(Array of all resources supported by the apiserver).\nfunction create_node() {\n  kubectl create -f - << __EOF__\n{\n  \"kind\": \"Node\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"127.0.0.1\",\n    \"annotations\": {\n      \"save-managers\": \"true\"\n    }\n  },\n  \"status\": {\n    \"capacity\": {\n      \"memory\": \"1Gi\"\n    }\n  }\n}\n__EOF__\n}\n\n# Run it if:\n# 1) $WHAT is empty\n# 2) $WHAT is not empty and kubeadm is part of $WHAT\nWHAT=${WHAT:-}\nif [[ ${WHAT} == \"\" || ${WHAT} =~ .*kubeadm.* ]] ; then\n  kube::log::status \"Running kubeadm tests\"\n\n  # build kubeadm\n  make all -C \"${KUBE_ROOT}\" WHAT=cmd/kubeadm\n  # unless the user sets KUBEADM_PATH, assume that \"make all...\" just built it\n  export KUBEADM_PATH=\"${KUBEADM_PATH:=$(kube::realpath \"${KUBE_ROOT}\")/_output/local/go/bin/kubeadm}\"\n  # invoke the tests\n  make -C \"${KUBE_ROOT}\" test \\\n    WHAT=k8s.io/kubernetes/cmd/kubeadm/test/cmd \\\n    KUBE_TIMEOUT=--timeout=240s \\\n    KUBE_RACE=\"\"\n\n  # if we ONLY want to run kubeadm, then exit here.\n  if [[ ${WHAT} == \"kubeadm\" ]]; then\n    kube::log::status \"TESTS PASSED\"\n    exit 0\n  fi\nfi\n\nkube::log::status \"Running kubectl tests for kube-apiserver\"\n\nsetup\nrun_kube_apiserver\nrun_kube_controller_manager\ncreate_node\nexport SUPPORTED_RESOURCES=(\"*\")\n# WARNING: Do not wrap this call in a subshell to capture output, e.g. output=$(runTests)\n# Doing so will suppress errexit behavior inside runTests\nrunTests\n\nkube::log::status \"TESTS PASSED\"\n", "num_lines": 195}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nfocus=${FOCUS:-\"\"}\nskip=${SKIP:-\"\"}\nparallelism=${PARALLELISM:-\"\"}\nartifacts=${ARTIFACTS:-\"/tmp/_artifacts/$(date +%y%m%dT%H%M%S)\"}\nrun_until_failure=${RUN_UNTIL_FAILURE:-\"false\"}\nbuild=${BUILD:-\"true\"}\n\n# Parse the flags to pass to ginkgo\nginkgoflags=\"\"\nif [[ ${parallelism} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -nodes=${parallelism} \"\nelse\n  ginkgoflags=\"${ginkgoflags} -p \"\nfi\n\nif [[ ${focus} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -focus=\\\"${focus}\\\" \"\nfi\n\nif [[ ${skip} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -skip=\\\"${skip}\\\" \"\nfi\n\nif [[ ${run_until_failure} != \"false\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -untilItFails=${run_until_failure} \"\nfi\n\n# Setup the directory to copy test artifacts (logs, junit.xml, etc) from remote host to local host\nif [[ ! -d \"${artifacts}\" ]]; then\n  echo \"Creating artifacts directory at ${artifacts}\"\n  mkdir -p \"${artifacts}\"\nfi\necho \"Test artifacts will be written to ${artifacts}\"\n\n# Test\nkube::golang::verify_go_version\n\ngo run test/e2e_kubeadm/runner/local/run_local.go \\\n  --ginkgo-flags=\"${ginkgoflags}\" \\\n  --test-flags=\"--provider=skeleton --report-dir=${artifacts}\" \\\n  --build=\"${build}\" 2>&1 | tee -i \"${artifacts}/build-log.txt\"\n", "num_lines": 65}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\n# start the cache mutation detector by default so that cache mutators will be found\nKUBE_CACHE_MUTATION_DETECTOR=\"${KUBE_CACHE_MUTATION_DETECTOR:-true}\"\nexport KUBE_CACHE_MUTATION_DETECTOR\n\n# panic the server on watch decode errors since they are considered coder mistakes\nKUBE_PANIC_WATCH_DECODE_ERROR=\"${KUBE_PANIC_WATCH_DECODE_ERROR:-true}\"\nexport KUBE_PANIC_WATCH_DECODE_ERROR\n\nfocus=${FOCUS:-\"\"}\nskip=${SKIP-\"\\[Flaky\\]|\\[Slow\\]|\\[Serial\\]\"}\n# The number of tests that can run in parallel depends on what tests\n# are running and on the size of the node. Too many, and tests will\n# fail due to resource contention. 8 is a reasonable default for a\n# n1-standard-1 node.\n# Currently, parallelism only affects when REMOTE=true. For local test,\n# ginkgo default parallelism (cores - 1) is used.\nparallelism=${PARALLELISM:-8}\nartifacts=\"${ARTIFACTS:-\"/tmp/_artifacts/$(date +%y%m%dT%H%M%S)\"}\"\nremote=${REMOTE:-\"false\"}\nruntime=${RUNTIME:-\"docker\"}\ncontainer_runtime_endpoint=${CONTAINER_RUNTIME_ENDPOINT:-\"\"}\nimage_service_endpoint=${IMAGE_SERVICE_ENDPOINT:-\"\"}\nrun_until_failure=${RUN_UNTIL_FAILURE:-\"false\"}\ntest_args=${TEST_ARGS:-\"\"}\ntimeout_arg=\"\"\nsystem_spec_name=${SYSTEM_SPEC_NAME:-}\nextra_envs=${EXTRA_ENVS:-}\nruntime_config=${RUNTIME_CONFIG:-}\n\n# Parse the flags to pass to ginkgo\nginkgoflags=\"\"\nif [[ ${parallelism} -gt 1 ]]; then\n  ginkgoflags=\"${ginkgoflags} -nodes=${parallelism} \"\nfi\n\nif [[ ${focus} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -focus=\\\"${focus}\\\" \"\nfi\n\nif [[ ${skip} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -skip=\\\"${skip}\\\" \"\nfi\n\nif [[ ${run_until_failure} != \"\" ]]; then\n  ginkgoflags=\"${ginkgoflags} -untilItFails=${run_until_failure} \"\nfi\n\n# Setup the directory to copy test artifacts (logs, junit.xml, etc) from remote host to local host\nif [ ! -d \"${artifacts}\" ]; then\n  echo \"Creating artifacts directory at ${artifacts}\"\n  mkdir -p \"${artifacts}\"\nfi\necho \"Test artifacts will be written to ${artifacts}\"\n\nif [[ ${runtime} == \"remote\" ]] ; then\n  if [[ -n ${container_runtime_endpoint} ]] ; then\n    test_args=\"--container-runtime-endpoint=${container_runtime_endpoint} ${test_args}\"\n  fi\n  if [[ -n ${image_service_endpoint} ]] ; then\n    test_args=\"--image-service-endpoint=${image_service_endpoint} ${test_args}\"\n  fi\nfi\n\n\nif [ \"${remote}\" = true ] ; then\n  # The following options are only valid in remote run.\n  images=${IMAGES:-\"\"}\n  hosts=${HOSTS:-\"\"}\n  image_project=${IMAGE_PROJECT:-\"kubernetes-node-e2e-images\"}\n  metadata=${INSTANCE_METADATA:-\"\"}\n  list_images=${LIST_IMAGES:-false}\n  if  [[ ${list_images} == \"true\" ]]; then\n    gcloud compute images list --project=\"${image_project}\" | grep \"e2e-node\"\n    exit 0\n  fi\n  gubernator=${GUBERNATOR:-\"false\"}\n  image_config_file=${IMAGE_CONFIG_FILE:-\"\"}\n  if [[ ${hosts} == \"\" && ${images} == \"\" && ${image_config_file} == \"\" ]]; then\n    image_project=\"${IMAGE_PROJECT:-\"cos-cloud\"}\"\n    gci_image=$(gcloud compute images list --project \"${image_project}\" \\\n    --no-standard-images --filter=\"name ~ 'cos-beta.*'\" --format=\"table[no-heading](name)\")\n    images=${gci_image}\n    metadata=\"user-data<${KUBE_ROOT}/test/e2e_node/jenkins/gci-init.yaml,gci-update-strategy=update_disabled\"\n  fi\n  instance_prefix=${INSTANCE_PREFIX:-\"test\"}\n  cleanup=${CLEANUP:-\"true\"}\n  delete_instances=${DELETE_INSTANCES:-\"false\"}\n  preemptible_instances=${PREEMPTIBLE_INSTANCES:-\"false\"}\n  test_suite=${TEST_SUITE:-\"default\"}\n  if [[ -n \"${TIMEOUT:-}\" ]] ; then\n    timeout_arg=\"--test-timeout=${TIMEOUT}\"\n  fi\n\n  # Get the compute zone\n  zone=${ZONE:-\"$(gcloud info --format='value(config.properties.compute.zone)')\"}\n  if [[ ${zone} == \"\" ]]; then\n    echo \"Could not find gcloud compute/zone when running: \\`gcloud info --format='value(config.properties.compute.zone)'\\`\"\n    exit 1\n  fi\n\n  # Get the compute project\n  project=$(gcloud info --format='value(config.project)')\n  if [[ ${project} == \"\" ]]; then\n    echo \"Could not find gcloud project when running: \\`gcloud info --format='value(config.project)'\\`\"\n    exit 1\n  fi\n\n  # Check if any of the images specified already have running instances.  If so reuse those instances\n  # by moving the IMAGE to a HOST\n  if [[ ${images} != \"\" ]]; then\n  IFS=',' read -ra IM <<< \"${images}\"\n       images=\"\"\n       for i in \"${IM[@]}\"; do\n         if gcloud compute instances list --project=\"${project}\" --filter=\"name:'${instance_prefix}-${i}' AND zone:'${zone}'\" | grep \"${i}\"; then\n           if [[ \"${hosts}\" != \"\" ]]; then\n             hosts=\"${hosts},\"\n           fi\n           echo \"Reusing host ${instance_prefix}-${i}\"\n           hosts=\"${hosts}${instance_prefix}-${i}\"\n         else\n           if [[ \"${images}\" != \"\" ]]; then\n             images=\"${images},\"\n           fi\n           images=\"${images}${i}\"\n         fi\n       done\n  fi\n\n  # Use cluster.local as default dns-domain\n  test_args='--dns-domain=\"'${KUBE_DNS_DOMAIN:-cluster.local}'\" '${test_args}\n  test_args='--kubelet-flags=\"--cluster-domain='${KUBE_DNS_DOMAIN:-cluster.local}'\" '${test_args}\n\n  # Output the configuration we will try to run\n  echo \"Running tests remotely using\"\n  echo \"Project: ${project}\"\n  echo \"Image Project: ${image_project}\"\n  echo \"Compute/Zone: ${zone}\"\n  echo \"Images: ${images}\"\n  echo \"Hosts: ${hosts}\"\n  echo \"Ginkgo Flags: ${ginkgoflags}\"\n  echo \"Instance Metadata: ${metadata}\"\n  echo \"Image Config File: ${image_config_file}\"\n  # Invoke the runner\n  go run test/e2e_node/runner/remote/run_remote.go  --logtostderr --vmodule=*=4 --ssh-env=\"gce\" \\\n    --zone=\"${zone}\" --project=\"${project}\" --gubernator=\"${gubernator}\" \\\n    --hosts=\"${hosts}\" --images=\"${images}\" --cleanup=\"${cleanup}\" \\\n    --results-dir=\"${artifacts}\" --ginkgo-flags=\"${ginkgoflags}\" \\\n    --image-project=\"${image_project}\" --instance-name-prefix=\"${instance_prefix}\" \\\n    --delete-instances=\"${delete_instances}\" --test_args=\"${test_args}\" --instance-metadata=\"${metadata}\" \\\n    --image-config-file=\"${image_config_file}\" --system-spec-name=\"${system_spec_name}\" \\\n    --runtime-config=\"${runtime_config}\" --preemptible-instances=\"${preemptible_instances}\" \\\n    --extra-envs=\"${extra_envs}\" --test-suite=\"${test_suite}\" \\\n    \"${timeout_arg}\" \\\n    2>&1 | tee -i \"${artifacts}/build-log.txt\"\n  exit $?\n\nelse\n  # Refresh sudo credentials if needed\n  if ping -c 1 -q metadata.google.internal &> /dev/null; then\n    echo 'Running on GCE, not asking for sudo credentials'\n  elif sudo --non-interactive \"$(which bash)\" -c true 2> /dev/null; then\n    # if we can run bash without a password, it's a pretty safe bet that either\n    # we can run any command without a password, or that sudo credentials\n    # are already cached - and they've just been re-cached\n    echo 'No need to refresh sudo credentials'\n  else\n    echo 'Updating sudo credentials'\n    sudo -v || exit 1\n  fi\n\n  # Do not use any network plugin by default. User could override the flags with\n  # test_args.\n  test_args='--kubelet-flags=\"--network-plugin= --cni-bin-dir=\" '${test_args}\n\n  # Runtime flags\n  test_args='--kubelet-flags=\"--container-runtime='${runtime}'\" '${test_args}\n\n  # Use cluster.local as default dns-domain\n  test_args='--dns-domain=\"'${KUBE_DNS_DOMAIN:-cluster.local}'\" '${test_args}\n  test_args='--kubelet-flags=\"--cluster-domain='${KUBE_DNS_DOMAIN:-cluster.local}'\" '${test_args}\n  # Test using the host the script was run on\n  # Provided for backwards compatibility\n  go run test/e2e_node/runner/local/run_local.go \\\n    --system-spec-name=\"${system_spec_name}\" --extra-envs=\"${extra_envs}\" \\\n    --ginkgo-flags=\"${ginkgoflags}\" --test-flags=\"--container-runtime=${runtime} \\\n    --alsologtostderr --v 4 --report-dir=${artifacts} --node-name $(hostname) \\\n    ${test_args}\" --runtime-config=\"${runtime_config}\" \\\n    --build-dependencies=true 2>&1 | tee -i \"${artifacts}/build-log.txt\"\n  exit $?\nfi\n", "num_lines": 212}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# start the cache mutation detector by default so that cache mutators will be found\nKUBE_CACHE_MUTATION_DETECTOR=\"${KUBE_CACHE_MUTATION_DETECTOR:-true}\"\nexport KUBE_CACHE_MUTATION_DETECTOR\n\n# panic the server on watch decode errors since they are considered coder mistakes\nKUBE_PANIC_WATCH_DECODE_ERROR=\"${KUBE_PANIC_WATCH_DECODE_ERROR:-true}\"\nexport KUBE_PANIC_WATCH_DECODE_ERROR\n\n# Give integration tests longer to run by default.\nKUBE_TIMEOUT=${KUBE_TIMEOUT:--timeout=600s}\nKUBE_INTEGRATION_TEST_MAX_CONCURRENCY=${KUBE_INTEGRATION_TEST_MAX_CONCURRENCY:-\"-1\"}\nLOG_LEVEL=${LOG_LEVEL:-2}\nKUBE_TEST_ARGS=${KUBE_TEST_ARGS:-}\n# Default glog module settings.\nKUBE_TEST_VMODULE=${KUBE_TEST_VMODULE:-\"garbagecollector*=6,graph_builder*=6\"}\n\nkube::test::find_integration_test_dirs() {\n  (\n    cd \"${KUBE_ROOT}\"\n    find test/integration/ -name '*_test.go' -print0 \\\n      | xargs -0n1 dirname | sed \"s|^|${KUBE_GO_PACKAGE}/|\" \\\n      | LC_ALL=C sort -u\n    find vendor/k8s.io/apiextensions-apiserver/test/integration/ -name '*_test.go' -print0 \\\n      | xargs -0n1 dirname | sed \"s|^|${KUBE_GO_PACKAGE}/|\" \\\n      | LC_ALL=C sort -u\n  )\n}\n\nCLEANUP_REQUIRED=\ncleanup() {\n  if [[ -z \"${CLEANUP_REQUIRED}\" ]]; then\n    return\n  fi\n  kube::log::status \"Cleaning up etcd\"\n  kube::etcd::cleanup\n  CLEANUP_REQUIRED=\n  kube::log::status \"Integration test cleanup complete\"\n}\n\nrunTests() {\n  kube::log::status \"Starting etcd instance\"\n  CLEANUP_REQUIRED=1\n  kube::etcd::start\n  kube::log::status \"Running integration test cases\"\n\n  make -C \"${KUBE_ROOT}\" test \\\n      WHAT=\"${WHAT:-$(kube::test::find_integration_test_dirs | paste -sd' ' -)}\" \\\n      GOFLAGS=\"${GOFLAGS:-}\" \\\n      KUBE_TEST_ARGS=\"--alsologtostderr=true ${KUBE_TEST_ARGS:-} ${SHORT:--short=true} --vmodule=${KUBE_TEST_VMODULE}\" \\\n      KUBE_TIMEOUT=\"${KUBE_TIMEOUT}\" \\\n      KUBE_RACE=\"\"\n\n  cleanup\n}\n\ncheckEtcdOnPath() {\n  kube::log::status \"Checking etcd is on PATH\"\n  which etcd && return\n  kube::log::status \"Cannot find etcd, cannot run integration tests.\"\n  kube::log::status \"Please see https://git.k8s.io/community/contributors/devel/sig-testing/integration-tests.md#install-etcd-dependency for instructions.\"\n  kube::log::usage \"You can use 'hack/install-etcd.sh' to install a copy in third_party/.\"\n  return 1\n}\n\ncheckEtcdOnPath\n\n# Run cleanup to stop etcd on interrupt or other kill signal.\ntrap cleanup EXIT\n\nrunTests\n", "num_lines": 94}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\n# start the cache mutation detector by default so that cache mutators will be found\nKUBE_CACHE_MUTATION_DETECTOR=\"${KUBE_CACHE_MUTATION_DETECTOR:-true}\"\nexport KUBE_CACHE_MUTATION_DETECTOR\n\n# panic the server on watch decode errors since they are considered coder mistakes\nKUBE_PANIC_WATCH_DECODE_ERROR=\"${KUBE_PANIC_WATCH_DECODE_ERROR:-true}\"\nexport KUBE_PANIC_WATCH_DECODE_ERROR\n\nkube::test::find_dirs() {\n  (\n    cd \"${KUBE_ROOT}\"\n    find -L . -not \\( \\\n        \\( \\\n          -path './_artifacts/*' \\\n          -o -path './bazel-*/*' \\\n          -o -path './_output/*' \\\n          -o -path './_gopath/*' \\\n          -o -path './cmd/kubeadm/test/*' \\\n          -o -path './contrib/podex/*' \\\n          -o -path './output/*' \\\n          -o -path './release/*' \\\n          -o -path './target/*' \\\n          -o -path './test/e2e/*' \\\n          -o -path './test/e2e_node/*' \\\n          -o -path './test/e2e_kubeadm/*' \\\n          -o -path './test/integration/*' \\\n          -o -path './third_party/*' \\\n          -o -path './staging/*' \\\n          -o -path './vendor/*' \\\n        \\) -prune \\\n      \\) -name '*_test.go' -print0 | xargs -0n1 dirname | sed \"s|^\\./|${KUBE_GO_PACKAGE}/|\" | LC_ALL=C sort -u\n\n    find ./staging -name '*_test.go' -not -path '*/test/integration/*' -prune -print0 | xargs -0n1 dirname | sed 's|^\\./staging/src/|./vendor/|' | LC_ALL=C sort -u\n  )\n}\n\n# TODO: This timeout should really be lower, this is a *long* time to test one\n# package, however pkg/api/testing in particular will fail with a lower timeout\n# currently. We should attempt to lower this over time.\nKUBE_TIMEOUT=${KUBE_TIMEOUT:--timeout=180s}\nKUBE_COVER=${KUBE_COVER:-n} # set to 'y' to enable coverage collection\nKUBE_COVERMODE=${KUBE_COVERMODE:-atomic}\n# The directory to save test coverage reports to, if generating them. If unset,\n# a semi-predictable temporary directory will be used.\nKUBE_COVER_REPORT_DIR=\"${KUBE_COVER_REPORT_DIR:-}\"\n# How many 'go test' instances to run simultaneously when running tests in\n# coverage mode.\nKUBE_COVERPROCS=${KUBE_COVERPROCS:-4}\n# use KUBE_RACE=\"\" to disable the race detector\n# this is defaulted to \"-race\" in make test as well\n# NOTE: DO NOT ADD A COLON HERE. KUBE_RACE=\"\" is meaningful!\nKUBE_RACE=${KUBE_RACE-\"-race\"}\n# Set to the goveralls binary path to report coverage results to Coveralls.io.\nKUBE_GOVERALLS_BIN=${KUBE_GOVERALLS_BIN:-}\n# once we have multiple group supports\n# Create a junit-style XML test report in this directory if set.\nKUBE_JUNIT_REPORT_DIR=${KUBE_JUNIT_REPORT_DIR:-}\n# If KUBE_JUNIT_REPORT_DIR is unset, and ARTIFACTS is set, then have them match.\nif [[ -z \"${KUBE_JUNIT_REPORT_DIR:-}\" && -n \"${ARTIFACTS:-}\" ]]; then\n    export KUBE_JUNIT_REPORT_DIR=\"${ARTIFACTS}\"\nfi\n# Set to 'y' to keep the verbose stdout from tests when KUBE_JUNIT_REPORT_DIR is\n# set.\nKUBE_KEEP_VERBOSE_TEST_OUTPUT=${KUBE_KEEP_VERBOSE_TEST_OUTPUT:-n}\n\nkube::test::usage() {\n  kube::log::usage_from_stdin <<EOF\nusage: $0 [OPTIONS] [TARGETS]\n\nOPTIONS:\n  -p <number>   : number of parallel workers, must be >= 1\nEOF\n}\n\nisnum() {\n  [[ \"$1\" =~ ^[0-9]+$ ]]\n}\n\nPARALLEL=\"${PARALLEL:-1}\"\nwhile getopts \"hp:i:\" opt ; do\n  case ${opt} in\n    h)\n      kube::test::usage\n      exit 0\n      ;;\n    p)\n      PARALLEL=\"${OPTARG}\"\n      if ! isnum \"${PARALLEL}\" || [[ \"${PARALLEL}\" -le 0 ]]; then\n        kube::log::usage \"'$0': argument to -p must be numeric and greater than 0\"\n        kube::test::usage\n        exit 1\n      fi\n      ;;\n    i)\n      kube::log::usage \"'$0': use GOFLAGS='-count <num-iterations>'\"\n      kube::test::usage\n      exit 1\n      ;;\n    :)\n      kube::log::usage \"Option -${OPTARG} <value>\"\n      kube::test::usage\n      exit 1\n      ;;\n    ?)\n      kube::test::usage\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND - 1))\n\n# Use eval to preserve embedded quoted strings.\ntestargs=()\neval \"testargs=(${KUBE_TEST_ARGS:-})\"\n\n# Used to filter verbose test output.\ngo_test_grep_pattern=\".*\"\n\n# The junit report tool needs full test case information to produce a\n# meaningful report.\nif [[ -n \"${KUBE_JUNIT_REPORT_DIR}\" ]] ; then\n  goflags+=(-v)\n  goflags+=(-json)\n  # Show only summary lines by matching lines like \"status package/test\"\n  go_test_grep_pattern=\"^[^[:space:]]\\+[[:space:]]\\+[^[:space:]]\\+/[^[[:space:]]\\+\"\nfi\n\nif [[ -n \"${FULL_LOG:-}\" ]] ; then\n  go_test_grep_pattern=\".*\"\nfi\n\n# Filter out arguments that start with \"-\" and move them to goflags.\ntestcases=()\nfor arg; do\n  if [[ \"${arg}\" == -* ]]; then\n    goflags+=(\"${arg}\")\n  else\n    testcases+=(\"${arg}\")\n  fi\ndone\nif [[ ${#testcases[@]} -eq 0 ]]; then\n  while IFS='' read -r line; do testcases+=(\"$line\"); done < <(kube::test::find_dirs)\nfi\nset -- \"${testcases[@]+${testcases[@]}}\"\n\nif [[ -n \"${KUBE_RACE}\" ]] ; then\n  goflags+=(\"${KUBE_RACE}\")\nfi\n\njunitFilenamePrefix() {\n  if [[ -z \"${KUBE_JUNIT_REPORT_DIR}\" ]]; then\n    echo \"\"\n    return\n  fi\n  mkdir -p \"${KUBE_JUNIT_REPORT_DIR}\"\n  echo \"${KUBE_JUNIT_REPORT_DIR}/junit_$(kube::util::sortable_date)\"\n}\n\nverifyAndSuggestPackagePath() {\n  local specified_package_path=\"$1\"\n  local alternative_package_path=\"$2\"\n  local original_package_path=\"$3\"\n  local suggestion_package_path=\"$4\"\n\n  if [[ \"${specified_package_path}\" =~ '/...'$ ]]; then\n    specified_package_path=${specified_package_path::-4}\n  fi\n\n  if ! [ -d \"${specified_package_path}\" ]; then\n    # Because k8s sets a localized $GOPATH for testing, seeing the actual\n    # directory can be confusing. Instead, just show $GOPATH if it exists in the\n    # $specified_package_path.\n    local printable_package_path\n    printable_package_path=${specified_package_path//${GOPATH}/\\$\\{GOPATH\\}}\n    kube::log::error \"specified test path '${printable_package_path}' does not exist\"\n\n    if [ -d \"${alternative_package_path}\" ]; then\n      kube::log::info \"try changing \\\"${original_package_path}\\\" to \\\"${suggestion_package_path}\\\"\"\n    fi\n    exit 1\n  fi\n}\n\nverifyPathsToPackagesUnderTest() {\n  local packages_under_test=(\"$@\")\n\n  for package_path in \"${packages_under_test[@]}\"; do\n    local local_package_path=\"${package_path}\"\n    local go_package_path=\"${GOPATH}/src/${package_path}\"\n\n    if [[ \"${package_path:0:2}\" == \"./\" ]] ; then\n      verifyAndSuggestPackagePath \"${local_package_path}\" \"${go_package_path}\" \"${package_path}\" \"${package_path:2}\"\n    else\n      verifyAndSuggestPackagePath \"${go_package_path}\" \"${local_package_path}\" \"${package_path}\" \"./${package_path}\"\n    fi\n  done\n}\n\nproduceJUnitXMLReport() {\n  local -r junit_filename_prefix=$1\n  if [[ -z \"${junit_filename_prefix}\" ]]; then\n    return\n  fi\n\n  local junit_xml_filename\n  junit_xml_filename=\"${junit_filename_prefix}.xml\"\n\n  if ! command -v gotestsum >/dev/null 2>&1; then\n    kube::log::status \"gotestsum not found; installing from hack/tools\"\n    pushd \"${KUBE_ROOT}/hack/tools\" >/dev/null\n      GO111MODULE=on go install gotest.tools/gotestsum\n    popd >/dev/null\n  fi\n  gotestsum --junitfile \"${junit_xml_filename}\" --raw-command cat \"${junit_filename_prefix}\"*.stdout\n  if [[ ! ${KUBE_KEEP_VERBOSE_TEST_OUTPUT} =~ ^[yY]$ ]]; then\n    rm \"${junit_filename_prefix}\"*.stdout\n  fi\n\n  kube::log::status \"Saved JUnit XML test report to ${junit_xml_filename}\"\n}\n\nrunTests() {\n  local junit_filename_prefix\n  junit_filename_prefix=$(junitFilenamePrefix)\n\n  verifyPathsToPackagesUnderTest \"$@\"\n\n  # If we're not collecting coverage, run all requested tests with one 'go test'\n  # command, which is much faster.\n  if [[ ! ${KUBE_COVER} =~ ^[yY]$ ]]; then\n    kube::log::status \"Running tests without code coverage ${KUBE_RACE:+\"and with ${KUBE_RACE}\"}\"\n    go test \"${goflags[@]:+${goflags[@]}}\" \\\n     \"${KUBE_TIMEOUT}\" \"${@}\" \\\n     \"${testargs[@]:+${testargs[@]}}\" \\\n     | tee ${junit_filename_prefix:+\"${junit_filename_prefix}.stdout\"} \\\n     | grep --binary-files=text \"${go_test_grep_pattern}\" && rc=$? || rc=$?\n    produceJUnitXMLReport \"${junit_filename_prefix}\"\n    return ${rc}\n  fi\n\n  kube::log::status \"Running tests with code coverage ${KUBE_RACE:+\"and with ${KUBE_RACE}\"}\"\n\n  # Create coverage report directories.\n  if [[ -z \"${KUBE_COVER_REPORT_DIR}\" ]]; then\n    cover_report_dir=\"/tmp/k8s_coverage/$(kube::util::sortable_date)\"\n  else\n    cover_report_dir=\"${KUBE_COVER_REPORT_DIR}\"\n  fi\n  cover_profile=\"coverage.out\"  # Name for each individual coverage profile\n  kube::log::status \"Saving coverage output in '${cover_report_dir}'\"\n  mkdir -p \"${@+${@/#/${cover_report_dir}/}}\"\n\n  # Run all specified tests, collecting coverage results. Go currently doesn't\n  # support collecting coverage across multiple packages at once, so we must issue\n  # separate 'go test' commands for each package and then combine at the end.\n  # To speed things up considerably, we can at least use xargs -P to run multiple\n  # 'go test' commands at once.\n  # To properly parse the test results if generating a JUnit test report, we\n  # must make sure the output from PARALLEL runs is not mixed. To achieve this,\n  # we spawn a subshell for each PARALLEL process, redirecting the output to\n  # separate files.\n\n  # ignore paths:\n  # vendor/k8s.io/code-generator/cmd/generator: is fragile when run under coverage, so ignore it for now.\n  #                            https://github.com/kubernetes/kubernetes/issues/24967\n  # vendor/k8s.io/client-go/1.4/rest: causes cover internal errors\n  #                            https://github.com/golang/go/issues/16540\n  cover_ignore_dirs=\"vendor/k8s.io/code-generator/cmd/generator|vendor/k8s.io/client-go/1.4/rest\"\n  for path in ${cover_ignore_dirs//|/ }; do\n      echo -e \"skipped\\tk8s.io/kubernetes/${path}\"\n  done\n\n  printf \"%s\\n\" \"${@}\" \\\n    | grep -Ev ${cover_ignore_dirs} \\\n    | xargs -I{} -n 1 -P \"${KUBE_COVERPROCS}\" \\\n    bash -c \"set -o pipefail; _pkg=\\\"\\$0\\\"; _pkg_out=\\${_pkg//\\//_}; \\\n      go test ${goflags[*]:+${goflags[*]}} \\\n        ${KUBE_TIMEOUT} \\\n        -cover -covermode=\\\"${KUBE_COVERMODE}\\\" \\\n        -coverprofile=\\\"${cover_report_dir}/\\${_pkg}/${cover_profile}\\\" \\\n        \\\"\\${_pkg}\\\" \\\n        ${testargs[*]:+${testargs[*]}} \\\n      | tee ${junit_filename_prefix:+\\\"${junit_filename_prefix}-\\$_pkg_out.stdout\\\"} \\\n      | grep \\\"${go_test_grep_pattern}\\\"\" \\\n    {} \\\n    && test_result=$? || test_result=$?\n\n  produceJUnitXMLReport \"${junit_filename_prefix}\"\n\n  COMBINED_COVER_PROFILE=\"${cover_report_dir}/combined-coverage.out\"\n  {\n    # The combined coverage profile needs to start with a line indicating which\n    # coverage mode was used (set, count, or atomic). This line is included in\n    # each of the coverage profiles generated when running 'go test -cover', but\n    # we strip these lines out when combining so that there's only one.\n    echo \"mode: ${KUBE_COVERMODE}\"\n\n    # Include all coverage reach data in the combined profile, but exclude the\n    # 'mode' lines, as there should be only one.\n    while IFS='' read -r x; do\n      grep -h -v \"^mode:\" < \"${x}\" || true\n    done < <(find \"${cover_report_dir}\" -name \"${cover_profile}\")\n  } >\"${COMBINED_COVER_PROFILE}\"\n\n  coverage_html_file=\"${cover_report_dir}/combined-coverage.html\"\n  go tool cover -html=\"${COMBINED_COVER_PROFILE}\" -o=\"${coverage_html_file}\"\n  kube::log::status \"Combined coverage report: ${coverage_html_file}\"\n\n  return ${test_result}\n}\n\nreportCoverageToCoveralls() {\n  if [[ ${KUBE_COVER} =~ ^[yY]$ ]] && [[ -x \"${KUBE_GOVERALLS_BIN}\" ]]; then\n    kube::log::status \"Reporting coverage results to Coveralls for service ${CI_NAME:-}\"\n    ${KUBE_GOVERALLS_BIN} -coverprofile=\"${COMBINED_COVER_PROFILE}\" \\\n    ${CI_NAME:+\"-service=${CI_NAME}\"} \\\n    ${COVERALLS_REPO_TOKEN:+\"-repotoken=${COVERALLS_REPO_TOKEN}\"} \\\n      || true\n  fi\n}\n\ncheckFDs() {\n  # several unittests panic when httptest cannot open more sockets\n  # due to the low default files limit on OS X.  Warn about low limit.\n  local fileslimit\n  fileslimit=\"$(ulimit -n)\"\n  if [[ ${fileslimit} -lt 1000 ]]; then\n    echo \"WARNING: ulimit -n (files) should be at least 1000, is ${fileslimit}, may cause test failure\";\n  fi\n}\n\ncheckFDs\n\nrunTests \"$@\"\n\n# We might run the tests for multiple versions, but we want to report only\n# one of them to coveralls. Here we report coverage from the last run.\nreportCoverageToCoveralls\n", "num_lines": 364}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A single script that runs a predefined set of update-* scripts, as they often go together.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\n# If called directly, exit.\nif [[ \"${CALLED_FROM_MAIN_MAKEFILE:-\"\"}\" == \"\" ]]; then\n    echo \"ERROR: $0 should not be run directly.\" >&2\n    echo >&2\n    echo \"Please run this command using \\\"make update\\\"\"\n    exit 1\nfi\n\nSILENT=${SILENT:-true}\nALL=${FORCE_ALL:-false}\n\ntrap 'exit 1' SIGINT\n\nif ${SILENT} ; then\n\techo \"Running in silent mode, run with SILENT=false if you want to see script logs.\"\nfi\n\nif ! ${ALL} ; then\n\techo \"Running in short-circuit mode; run with FORCE_ALL=true to force all scripts to run.\"\nfi\n\nBASH_TARGETS=\"\n\tupdate-generated-protobuf\n\tupdate-codegen\n\tupdate-generated-runtime\n\tupdate-generated-device-plugin\n\tupdate-generated-api-compatibility-data\n\tupdate-generated-docs\n\tupdate-generated-swagger-docs\n\tupdate-openapi-spec\n\tupdate-bazel\n\tupdate-gofmt\"\n\nfor t in ${BASH_TARGETS}; do\n\techo -e \"${color_yellow:?}Running ${t}${color_norm:?}\"\n\tif ${SILENT} ; then\n\t\tif ! bash \"${KUBE_ROOT}/hack/${t}.sh\" 1> /dev/null; then\n\t\t\techo -e \"${color_red:?}Running ${t} FAILED${color_norm}\"\n\t\t\tif ! ${ALL}; then\n\t\t\t\texit 1\n\t\t\tfi\n\t\tfi\n\telse\n\t\tif ! bash \"${KUBE_ROOT}/hack/${t}.sh\"; then\n\t\t\techo -e \"${color_red}Running ${t} FAILED${color_norm}\"\n\t\t\tif ! ${ALL}; then\n\t\t\t\texit 1\n\t\t\tfi\n\t\tfi\n\tfi\ndone\n\necho -e \"${color_green:?}Update scripts completed successfully${color_norm}\"\n", "num_lines": 78}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# If KUBE_JUNIT_REPORT_DIR is unset, and ARTIFACTS is set, then have them match.\nif [[ -z \"${KUBE_JUNIT_REPORT_DIR:-}\" && -n \"${ARTIFACTS:-}\" ]]; then\n    export KUBE_JUNIT_REPORT_DIR=\"${ARTIFACTS}\"\nfi\n\n# include shell2junit library\nsource \"${KUBE_ROOT}/third_party/forked/shell2junit/sh2ju.sh\"\n\n# Excluded check patterns are always skipped.\nEXCLUDED_PATTERNS=(\n  \"verify-all.sh\"                # this script calls the make rule and would cause a loop\n  \"verify-linkcheck.sh\"          # runs in separate Jenkins job once per day due to high network usage\n  \"verify-*-dockerized.sh\"       # Don't run any scripts that intended to be run dockerized\n  \"verify-govet-levee.sh\"        # Do not run levee analysis by default while KEP-1933 implementation is in alpha.\n  \"verify-golangci-lint.sh\"      # Experimental - intended to be run by hand periodically\n  )\n\n# Exclude generated-files-remake in certain cases, if they're running in a separate job.\nif [[ ${EXCLUDE_FILES_REMAKE:-} =~ ^[yY]$ ]]; then\n  EXCLUDED_PATTERNS+=(\n    \"verify-generated-files-remake.sh\" # run in a separate job\n    )\nfi\n\n# Exclude typecheck in certain cases, if they're running in a separate job.\nif [[ ${EXCLUDE_TYPECHECK:-} =~ ^[yY]$ ]]; then\n  EXCLUDED_PATTERNS+=(\n    \"verify-typecheck.sh\"              # runs in separate typecheck job\n    \"verify-typecheck-providerless.sh\" # runs in separate typecheck job\n    \"verify-typecheck-dockerless.sh\" # runs in separate typecheck job\n    )\nfi\n\n# Exclude dependency checks in certain cases, if they're running in a separate job.\n# From @cblecker: We can't change the variable name here, unless we update it throughout\n#                 test-infra (and we would need to pick it backwards).\nif [[ ${EXCLUDE_GODEP:-} =~ ^[yY]$ ]]; then\n  EXCLUDED_PATTERNS+=(\n    \"verify-external-dependencies-version.sh\" # runs in separate dependencies job\n    \"verify-vendor.sh\"                        # runs in separate dependencies job\n    \"verify-vendor-licenses.sh\"               # runs in separate dependencies job\n    )\nfi\n\n# Exclude readonly package check in certain cases, aka, in periodic jobs we don't care and a readonly package won't be touched\nif [[ ${EXCLUDE_READONLY_PACKAGE:-} =~ ^[yY]$ ]]; then\n  EXCLUDED_PATTERNS+=(\n    \"verify-readonly-packages.sh\"  # skip in CI, if env is set\n    )\nfi\n\n# Only run known fast checks in quick mode.\n# These ideally run in less than 10s.\nQUICK_PATTERNS+=(\n  \"verify-api-groups.sh\"\n  \"verify-boilerplate.sh\"\n  \"verify-external-dependencies-version.sh\"\n  \"verify-vendor-licenses.sh\"\n  \"verify-gofmt.sh\"\n  \"verify-imports.sh\"\n  \"verify-pkg-names.sh\"\n  \"verify-readonly-packages.sh\"\n  \"verify-spelling.sh\"\n  \"verify-staging-client-go.sh\"\n  \"verify-staging-meta-files.sh\"\n  \"verify-test-featuregates.sh\"\n  \"verify-test-images.sh\"\n)\n\nwhile IFS='' read -r line; do EXCLUDED_CHECKS+=(\"$line\"); done < <(ls \"${EXCLUDED_PATTERNS[@]/#/${KUBE_ROOT}/hack/}\" 2>/dev/null || true)\nwhile IFS='' read -r line; do QUICK_CHECKS+=(\"$line\"); done < <(ls \"${QUICK_PATTERNS[@]/#/${KUBE_ROOT}/hack/}\" 2>/dev/null || true)\nTARGET_LIST=()\nIFS=\" \" read -r -a TARGET_LIST <<< \"${WHAT:-}\"\n\nfunction is-excluded {\n  for e in \"${EXCLUDED_CHECKS[@]}\"; do\n    if [[ $1 -ef \"${e}\" ]]; then\n      return\n    fi\n  done\n  return 1\n}\n\nfunction is-quick {\n  for e in \"${QUICK_CHECKS[@]}\"; do\n    if [[ $1 -ef \"${e}\" ]]; then\n      return\n    fi\n  done\n  return 1\n}\n\nfunction is-explicitly-chosen {\n  local name=\"${1#verify-}\"\n  name=\"${name%.*}\"\n  index=0\n  for e in \"${TARGET_LIST[@]}\"; do\n    if [[ \"${e}\" == \"${name}\" ]]; then\n      TARGET_LIST[${index}]=\"\"\n      return\n    fi\n    index=$((index + 1))\n  done\n  return 1\n}\n\nfunction run-cmd {\n  local filename=\"${2##*/verify-}\"\n  local testname=\"${filename%%.*}\"\n  local output=\"${KUBE_JUNIT_REPORT_DIR:-/tmp/junit-results}\"\n  local tr\n\n  if ${SILENT}; then\n    juLog -output=\"${output}\" -class=\"verify\" -name=\"${testname}\" \"$@\" &> /dev/null\n    tr=$?\n  else\n    juLog -output=\"${output}\" -class=\"verify\" -name=\"${testname}\" \"$@\"\n    tr=$?\n  fi\n  return ${tr}\n}\n\n# Collect Failed tests in this Array , initialize it to nil\nFAILED_TESTS=()\n\nfunction print-failed-tests {\n  echo -e \"========================\"\n  echo -e \"${color_red:?}FAILED TESTS${color_norm:?}\"\n  echo -e \"========================\"\n  for t in \"${FAILED_TESTS[@]}\"; do\n      echo -e \"${color_red}${t}${color_norm}\"\n  done\n}\n\nfunction run-checks {\n  local -r pattern=$1\n  local -r runner=$2\n\n  local t\n  for t in ${pattern}\n  do\n    local check_name\n    check_name=\"$(basename \"${t}\")\"\n    if [[ -n ${WHAT:-} ]]; then\n      if ! is-explicitly-chosen \"${check_name}\"; then\n        continue\n      fi\n    else\n      if is-excluded \"${t}\" ; then\n        echo \"Skipping ${check_name}\"\n        continue\n      fi\n      if ${QUICK} && ! is-quick \"${t}\" ; then\n        echo \"Skipping ${check_name} in quick mode\"\n        continue\n      fi\n    fi\n    echo -e \"Verifying ${check_name}\"\n    local start\n    start=$(date +%s)\n    run-cmd \"${runner}\" \"${t}\" && tr=$? || tr=$?\n    local elapsed=$(($(date +%s) - start))\n    if [[ ${tr} -eq 0 ]]; then\n      echo -e \"${color_green:?}SUCCESS${color_norm}  ${check_name}\\t${elapsed}s\"\n    else\n      echo -e \"${color_red}FAILED${color_norm}   ${check_name}\\t${elapsed}s\"\n      ret=1\n      FAILED_TESTS+=(\"${t}\")\n    fi\n  done\n}\n\n# Check invalid targets specified in \"WHAT\" and mark them as failure cases\nfunction missing-target-checks {\n  # In case WHAT is not specified\n  [[ ${#TARGET_LIST[@]} -eq 0 ]] && return\n\n  for v in \"${TARGET_LIST[@]}\"\n  do\n    [[ -z \"${v}\" ]] && continue\n\n    FAILED_TESTS+=(\"${v}\")\n    ret=1\n  done\n}\n\nSILENT=${SILENT:-false}\nQUICK=${QUICK:-false}\n\nif ${SILENT} ; then\n  echo \"Running in silent mode, run with SILENT=false if you want to see script logs.\"\nfi\n\nif ${QUICK} ; then\n  echo \"Running in quick mode (QUICK=true). Only fast checks will run.\"\nfi\n\nret=0\nrun-checks \"${KUBE_ROOT}/hack/verify-*.sh\" bash\nrun-checks \"${KUBE_ROOT}/hack/verify-*.py\" python3\nmissing-target-checks\n\nif [[ ${ret} -eq 1 ]]; then\n    print-failed-tests\nfi\nexit ${ret}\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 232}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\ncd \"${KUBE_ROOT}\"\n\n# If called directly, exit.\nif [[ \"${CALLED_FROM_MAIN_MAKEFILE:-\"\"}\" == \"\" ]]; then\n    echo \"ERROR: $0 should not be run directly.\" >&2\n    echo >&2\n    echo \"Please run this command using \\\"make vet\\\"\"\n    exit 1\nfi\n\n# Filter out arguments that start with \"-\" and move them to goflags.\ntargets=()\nfor arg; do\n  if [[ \"${arg}\" == -* ]]; then\n    goflags+=(\"${arg}\")\n  else\n    targets+=(\"${arg}\")\n  fi\ndone\n\nif [[ ${#targets[@]} -eq 0 ]]; then\n  # Do not run on third_party directories or generated client code or build tools.\n  while IFS='' read -r line; do\n    targets+=(\"${line}\")\n  done < <(go list -e ./... | grep -E -v \"/(build|third_party|vendor|staging|clientset_generated|hack)/\")\nfi\n\ngo vet \"${goflags[@]:+${goflags[@]}}\" \"${targets[@]}\"\n", "num_lines": 52}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script finds, caches, and prints a list of all directories that hold\n# *.go files.  If any directory is newer than the cache, re-find everything and\n# update the cache.  Otherwise use the cached file.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ -z \"${1:-}\" ]]; then\n    echo \"usage: $0 <cache-file>\"\n    exit 1\nfi\nCACHE=\"$1\"; shift\n\ntrap 'rm -f \"${CACHE}\"' HUP INT TERM ERR\n\n# This is a partial 'find' command.  The caller is expected to pass the\n# remaining arguments.\n#\n# Example:\n#   kfind -type f -name foobar.go\nfunction kfind() {\n    # We want to include the \"special\" vendor directories which are actually\n    # part of the Kubernetes source tree (./staging/*) but we need them to be\n    # named as their ./vendor/* equivalents.  Also, we  do not want all of\n    # ./vendor or even all of ./vendor/k8s.io.\n    find -H .                      \\\n        \\(                         \\\n        -not \\(                    \\\n            \\(                     \\\n                -name '_*' -o      \\\n                -name '.[^.]*' -o  \\\n                -path './vendor'   \\\n            \\) -prune              \\\n        \\)                         \\\n        \\)                         \\\n        \"$@\"                       \\\n        | sed 's|^./staging/src|vendor|'\n}\n\n# It's *significantly* faster to check whether any directories are newer than\n# the cache than to blindly rebuild it.\nif [[ -f \"${CACHE}\" && -n \"${CACHE}\" ]]; then\n    N=$(kfind -type d -newer \"${CACHE}\" -print -quit | wc -l)\n    if [[ \"${N}\" == 0 ]]; then\n        cat \"${CACHE}\"\n        exit\n    fi\nfi\n\nmkdir -p \"$(dirname \"${CACHE}\")\"\nkfind -type f -name \\*.go  \\\n    | sed 's|/[^/]*$||'    \\\n    | sed 's|^./||'        \\\n    | LC_ALL=C sort -u     \\\n    | tee \"${CACHE}\"\n", "num_lines": 73}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ncfssl gencert -initca root.csr.json | cfssljson -bare root\n\ncfssl gencert -initca intermediate.csr.json | cfssljson -bare intermediate\ncfssl sign -ca root.pem -ca-key root-key.pem -config intermediate.config.json intermediate.csr | cfssljson -bare intermediate\n\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=valid   client.csr.json | cfssljson -bare client-valid\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=expired client.csr.json | cfssljson -bare client-expired\n\n", "num_lines": 25}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook authz plugin tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=webhook_imagepolicy_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=webhook_imagepolicy_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=webhook_imagepolicy_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=webhook_imagepolicy_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the imagepolicy webhook tests.\n\n//lint:file-ignore U1000 Ignore all unused code, it's generated\n\npackage imagepolicy\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 105}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\n# generate the code with:\n# --output-base    because this script should also be able to run inside the vendor dir of\n#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#                  instead of the $GOPATH directly. For normal projects this can be dropped.\nbash \"${CODEGEN_PKG}/generate-groups.sh\" all \\\n  k8s.io/apiextensions-apiserver/examples/client-go/pkg/client k8s.io/apiextensions-apiserver/examples/client-go/pkg/apis \\\n  cr:v1 \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../../../..\"\n\n# To use your own boilerplate text append:\n#   --go-header-file ${SCRIPT_ROOT}/hack/custom-boilerplate.go.txt\n", "num_lines": 35}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../../../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# Register function to be called on EXIT to remove generated binary.\nfunction cleanup {\n  rm \"${KUBE_ROOT}/vendor/k8s.io/apiextensions-apiserver/artifacts/simple-image/apiextensions-apiserver\"\n}\ntrap cleanup EXIT\n\npushd \"${KUBE_ROOT}/vendor/k8s.io/apiextensions-apiserver\"\ncp -v ../../../../_output/local/bin/linux/amd64/apiextensions-apiserver ./artifacts/simple-image/apiextensions-apiserver\ndocker build -t apiextensions-apiserver:latest ./artifacts/simple-image\npopd\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\nCLIENTSET_NAME_VERSIONED=clientset \\\nCLIENTSET_PKG_NAME=clientset \\\nbash \"${CODEGEN_PKG}/generate-groups.sh\" deepcopy,client,lister,informer \\\n  k8s.io/apiextensions-apiserver/pkg/client k8s.io/apiextensions-apiserver/pkg/apis \\\n  \"apiextensions:v1beta1,v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\nCLIENTSET_NAME_VERSIONED=clientset \\\nCLIENTSET_PKG_NAME=clientset \\\nCLIENTSET_NAME_INTERNAL=internalclientset \\\nbash \"${CODEGEN_PKG}/generate-internal-groups.sh\" deepcopy,conversion \\\n  k8s.io/apiextensions-apiserver/pkg/client k8s.io/apiextensions-apiserver/pkg/apis k8s.io/apiextensions-apiserver/pkg/apis \\\n  \"apiextensions:v1beta1,v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n", "num_lines": 40}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the generic webhook admission plugin tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\nCN_BASE=\"generic_webhook_admission_plugin_tests\"\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nDNS.1 = webhook-test.default.svc\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nDNS.1 = webhook-test.default.svc\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out CAKey.pem 2048\nopenssl req -x509 -new -nodes -key CAKey.pem -days 100000 -out CACert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out BadCAKey.pem 2048\nopenssl req -x509 -new -nodes -key BadCAKey.pem -days 100000 -out BadCACert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out ServerKey.pem 2048\nopenssl req -new -key ServerKey.pem -out server.csr -subj \"/CN=webhook-test.default.svc\" -config server.conf\nopenssl x509 -req -in server.csr -CA CACert.pem -CAkey CAKey.pem -CAcreateserial -out ServerCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out ClientKey.pem 2048\nopenssl req -new -key ClientKey.pem -out client.csr -subj \"/CN=${CN_BASE}_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA CACert.pem -CAkey CAKey.pem -CAcreateserial -out ClientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs.go\n\ncat > $outfile << EOF\n/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage testcerts\nEOF\n\nfor file in CAKey CACert BadCAKey BadCACert ServerKey ServerCert ClientKey ClientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 110}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ncfssl gencert -initca root.csr.json | cfssljson -bare root\n\ncfssl gencert -initca intermediate.csr.json | cfssljson -bare intermediate\ncfssl sign -ca root.pem -ca-key root-key.pem -config intermediate.config.json intermediate.csr | cfssljson -bare intermediate\n\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=valid   client.csr.json | cfssljson -bare client-valid\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=expired client.csr.json | cfssljson -bare client-expired\n\n", "num_lines": 25}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ncfssl gencert -initca root.csr.json | cfssljson -bare root\n\ncfssl gencert -initca intermediate.csr.json | cfssljson -bare intermediate\ncfssl sign -ca root.pem -ca-key root-key.pem -config intermediate.config.json intermediate.csr | cfssljson -bare intermediate\n\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=valid   client.csr.json | cfssljson -bare client-valid\ncfssl gencert -ca intermediate.pem -ca-key intermediate-key.pem -config client.config.json --profile=expired client.csr.json | cfssljson -bare client-expired\n\n", "num_lines": 25}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\nCN_BASE=\"webhook_tests\"\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nDNS.1 = localhost\nEOF\n\ncat > server_no_san.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=${CN_BASE}_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a server certiticate w/o SAN\nopenssl req -new -key serverKey.pem -out serverNoSAN.csr -subj \"/CN=localhost\" -config server_no_san.conf\nopenssl x509 -req -in serverNoSAN.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCertNoSAN.pem -days 100000 -extensions v3_req -extfile server_no_san.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=${CN_BASE}_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert serverCertNoSAN clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 124}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nrm ./*.pem\n\nfor N in $(seq 1 3); do\n    ssh-keygen -t rsa -b 2048 -f rsa_\"$N\".pem -N ''\ndone\n\nfor N in $(seq 1 3); do\n    ssh-keygen -t ecdsa -b 521 -f ecdsa_\"$N\".pem -N ''\ndone\n\nrm ./*.pub\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook authz plugin tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=webhook_authz_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=webhook_authz_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 103}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n>&2 echo \"$KUBERNETES_EXEC_INFO\"\necho \"$TEST_OUTPUT\"\nexit \"${TEST_EXIT_CODE:-0}\"\n", "num_lines": 20}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# generate-groups generates everything for a project with external types only, e.g. a project based\n# on CustomResourceDefinitions.\n\nif [ \"$#\" -lt 4 ] || [ \"${1}\" == \"--help\" ]; then\n  cat <<EOF\nUsage: $(basename \"$0\") <generators> <output-package> <apis-package> <groups-versions> ...\n\n  <generators>        the generators comma separated to run (deepcopy,defaulter,client,lister,informer) or \"all\".\n  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).\n  <apis-package>      the external types dir (e.g. github.com/example/api or github.com/example/project/pkg/apis).\n  <groups-versions>   the groups and their versions in the format \"groupA:v1,v2 groupB:v1 groupC:v2\", relative\n                      to <api-package>.\n  ...                 arbitrary flags passed to all generator binaries.\n\n\nExamples:\n  $(basename \"$0\") all             github.com/example/project/pkg/client github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\n  $(basename \"$0\") deepcopy,client github.com/example/project/pkg/client github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\nEOF\n  exit 0\nfi\n\nGENS=\"$1\"\nOUTPUT_PKG=\"$2\"\nAPIS_PKG=\"$3\"\nGROUPS_WITH_VERSIONS=\"$4\"\nshift 4\n\n(\n  # To support running this script from anywhere, we have to first cd into this directory\n  # so we can install the tools.\n  cd \"$(dirname \"${0}\")\"\n  go install ./cmd/{defaulter-gen,client-gen,lister-gen,informer-gen,deepcopy-gen}\n)\n# Go installs the above commands to get installed in $GOBIN if defined, and $GOPATH/bin otherwise:\nGOBIN=\"$(go env GOBIN)\"\ngobin=\"${GOBIN:-$(go env GOPATH)/bin}\"\n\nfunction codegen::join() { local IFS=\"$1\"; shift; echo \"$*\"; }\n\n# enumerate group versions\nFQ_APIS=() # e.g. k8s.io/api/apps/v1\nfor GVs in ${GROUPS_WITH_VERSIONS}; do\n  IFS=: read -r G Vs <<<\"${GVs}\"\n\n  # enumerate versions\n  for V in ${Vs//,/ }; do\n    FQ_APIS+=(\"${APIS_PKG}/${G}/${V}\")\n  done\ndone\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"deepcopy\" <<<\"${GENS}\"; then\n  echo \"Generating deepcopy funcs\"\n  \"${gobin}/deepcopy-gen\" --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" -O zz_generated.deepcopy --bounding-dirs \"${APIS_PKG}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"client\" <<<\"${GENS}\"; then\n  echo \"Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\"\n  \"${gobin}/client-gen\" --clientset-name \"${CLIENTSET_NAME_VERSIONED:-versioned}\" --input-base \"\" --input \"$(codegen::join , \"${FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"lister\" <<<\"${GENS}\"; then\n  echo \"Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers\"\n  \"${gobin}/lister-gen\" --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/listers\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"informer\" <<<\"${GENS}\"; then\n  echo \"Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers\"\n  \"${gobin}/informer-gen\" \\\n           --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" \\\n           --versioned-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}\" \\\n           --listers-package \"${OUTPUT_PKG}/listers\" \\\n           --output-package \"${OUTPUT_PKG}/informers\" \\\n           \"$@\"\nfi\n", "num_lines": 96}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# generate-internal-groups generates everything for a project with internal types, e.g. an\n# user-provided API server based on k8s.io/apiserver.\n\nif [ \"$#\" -lt 5 ] || [ \"${1}\" == \"--help\" ]; then\n  cat <<EOF\nUsage: $(basename \"$0\") <generators> <output-package> <internal-apis-package> <extensiona-apis-package> <groups-versions> ...\n\n  <generators>        the generators comma separated to run (deepcopy,defaulter,conversion,client,lister,informer,openapi) or \"all\".\n  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).\n  <int-apis-package>  the internal types dir (e.g. github.com/example/project/pkg/apis).\n  <ext-apis-package>  the external types dir (e.g. github.com/example/project/pkg/apis or githubcom/example/apis).\n  <groups-versions>   the groups and their versions in the format \"groupA:v1,v2 groupB:v1 groupC:v2\", relative\n                      to <api-package>.\n  ...                 arbitrary flags passed to all generator binaries.\n\nExamples:\n  $(basename \"$0\") all                           github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\n  $(basename \"$0\") deepcopy,defaulter,conversion github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/apis     \"foo:v1 bar:v1alpha1,v1beta1\"\nEOF\n  exit 0\nfi\n\nGENS=\"$1\"\nOUTPUT_PKG=\"$2\"\nINT_APIS_PKG=\"$3\"\nEXT_APIS_PKG=\"$4\"\nGROUPS_WITH_VERSIONS=\"$5\"\nshift 5\n\ngo install ./\"$(dirname \"${0}\")\"/cmd/{defaulter-gen,conversion-gen,client-gen,lister-gen,informer-gen,deepcopy-gen,openapi-gen}\n\nfunction codegen::join() { local IFS=\"$1\"; shift; echo \"$*\"; }\n\n# enumerate group versions\nALL_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps k8s.io/api/apps/v1\nINT_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps\nEXT_FQ_APIS=() # e.g. k8s.io/api/apps/v1\nfor GVs in ${GROUPS_WITH_VERSIONS}; do\n  IFS=: read -r G Vs <<<\"${GVs}\"\n\n  if [ -n \"${INT_APIS_PKG}\" ]; then\n    ALL_FQ_APIS+=(\"${INT_APIS_PKG}/${G}\")\n    INT_FQ_APIS+=(\"${INT_APIS_PKG}/${G}\")\n  fi\n\n  # enumerate versions\n  for V in ${Vs//,/ }; do\n    ALL_FQ_APIS+=(\"${EXT_APIS_PKG}/${G}/${V}\")\n    EXT_FQ_APIS+=(\"${EXT_APIS_PKG}/${G}/${V}\")\n  done\ndone\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"deepcopy\" <<<\"${GENS}\"; then\n  echo \"Generating deepcopy funcs\"\n  \"${GOPATH}/bin/deepcopy-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" -O zz_generated.deepcopy --bounding-dirs \"${INT_APIS_PKG},${EXT_APIS_PKG}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"defaulter\" <<<\"${GENS}\"; then\n  echo \"Generating defaulters\"\n  \"${GOPATH}/bin/defaulter-gen\"  --input-dirs \"$(codegen::join , \"${EXT_FQ_APIS[@]}\")\" -O zz_generated.defaults \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"conversion\" <<<\"${GENS}\"; then\n  echo \"Generating conversions\"\n  \"${GOPATH}/bin/conversion-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" -O zz_generated.conversion \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"client\" <<<\"${GENS}\"; then\n  echo \"Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\"\n  if [ -n \"${INT_APIS_PKG}\" ]; then\n    IFS=\" \" read -r -a APIS <<< \"$(printf '%s/ ' \"${INT_FQ_APIS[@]}\")\"\n    \"${GOPATH}/bin/client-gen\" --clientset-name \"${CLIENTSET_NAME_INTERNAL:-internalversion}\" --input-base \"\" --input \"$(codegen::join , \"${APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\n  fi\n  \"${GOPATH}/bin/client-gen\" --clientset-name \"${CLIENTSET_NAME_VERSIONED:-versioned}\" --input-base \"\" --input \"$(codegen::join , \"${EXT_FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"lister\" <<<\"${GENS}\"; then\n  echo \"Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers\"\n  \"${GOPATH}/bin/lister-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/listers\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"informer\" <<<\"${GENS}\"; then\n  echo \"Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers\"\n  \"${GOPATH}/bin/informer-gen\" \\\n           --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" \\\n           --versioned-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}\" \\\n           --internal-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_INTERNAL:-internalversion}\" \\\n           --listers-package \"${OUTPUT_PKG}/listers\" \\\n           --output-package \"${OUTPUT_PKG}/informers\" \\\n           \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"openapi\" <<<\"${GENS}\"; then\n  echo \"Generating OpenAPI definitions for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/openapi\"\n  declare -a OPENAPI_EXTRA_PACKAGES\n  \"${GOPATH}/bin/openapi-gen\" \\\n           --input-dirs \"$(codegen::join , \"${EXT_FQ_APIS[@]}\" \"${OPENAPI_EXTRA_PACKAGES[@]+\"${OPENAPI_EXTRA_PACKAGES[@]}\"}\")\" \\\n           --input-dirs \"k8s.io/apimachinery/pkg/apis/meta/v1,k8s.io/apimachinery/pkg/runtime,k8s.io/apimachinery/pkg/version\" \\\n           --output-package \"${OUTPUT_PKG}/openapi\" \\\n           -O zz_generated.openapi \\\n           \"$@\"\nfi\n", "num_lines": 123}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\n# generate the code with:\n# - --output-base because this script should also be able to run inside the vendor dir of\n#   k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#   instead of the $GOPATH directly. For normal projects this can be dropped.\n\"$(dirname \"${BASH_SOURCE[0]}\")\"/../generate-internal-groups.sh all \\\n  k8s.io/code-generator/examples/apiserver k8s.io/code-generator/examples/apiserver/apis k8s.io/code-generator/examples/apiserver/apis \\\n  \"example:v1 example2:v1 example3.io:v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\"$(dirname \"${BASH_SOURCE[0]}\")\"/../generate-groups.sh all \\\n  k8s.io/code-generator/examples/crd k8s.io/code-generator/examples/crd/apis \\\n  \"example:v1 example2:v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\"$(dirname \"${BASH_SOURCE[0]}\")\"/../generate-groups.sh all \\\n  k8s.io/code-generator/examples/MixedCase k8s.io/code-generator/examples/MixedCase/apis \\\n  \"example:v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\"$(dirname \"${BASH_SOURCE[0]}\")\"/../generate-groups.sh all \\\n  k8s.io/code-generator/examples/HyphenGroup k8s.io/code-generator/examples/HyphenGroup/apis \\\n  \"example:v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\n", "num_lines": 48}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/examples\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/examples\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n\n# smoke test\necho \"Smoke testing examples by compiling...\"\ngo build \"./${SCRIPT_ROOT}/examples/crd/...\"\ngo build \"./${SCRIPT_ROOT}/examples/apiserver/...\"\ngo build \"./${SCRIPT_ROOT}/examples/MixedCase/...\"\ngo build \"./${SCRIPT_ROOT}/examples/HyphenGroup/...\"\n", "num_lines": 56}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../../../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# Register function to be called on EXIT to remove generated binary.\nfunction cleanup {\n  rm \"${KUBE_ROOT}/vendor/k8s.io/kube-aggregator/artifacts/simple-image/kube-aggregator\"\n}\ntrap cleanup EXIT\n\npushd \"${KUBE_ROOT}/vendor/k8s.io/kube-aggregator\"\ncp -v ../../../../_output/local/bin/linux/amd64/kube-aggregator ./artifacts/simple-image/kube-aggregator\ndocker build -t kube-aggregator:latest ./artifacts/simple-image\npopd", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# starts kube-aggregator as a pod after you've run `local-up-cluster.sh`\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nAGG_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nKUBE_ROOT=${AGG_ROOT}/../../../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nAGGREGATOR_SECURE_PORT=${AGGREGATOR_SECURE_PORT:-31090}\nAPI_HOST=${API_HOST:-localhost}\nAPI_HOST_IP=${API_HOST_IP:-\"127.0.0.1\"}\nAGGREGATOR_CERT_DIR=${AGGREGATOR_CERT_DIR:-\"/var/run/kubernetes/aggregator\"}\n\nKUBE_CERT_DIR=${KUBE_CERT_DIR:-\"/var/run/kubernetes\"}\nSERVING_CERT_CA_CERT=${SERVING_CERT_CA_CERT:-\"${KUBE_CERT_DIR}/server-ca.crt\"}\nCLIENT_CERT_CA_CERT=${CLIENT_CERT_CA_CERT:-\"${KUBE_CERT_DIR}/client-ca.crt\"}\nFRONT_PROXY_CLIENT_CERT_CA_CERT=${FRONT_PROXY_CLIENT_CERT_CA_CERT:-\"${KUBE_CERT_DIR}/request-header-ca.crt\"}\nSERVING_CERT=${SERVING_CERT:-\"${KUBE_CERT_DIR}/serving-kube-aggregator.crt\"}\nSERVING_KEY=${SERVING_KEY:-\"${KUBE_CERT_DIR}/serving-kube-aggregator.key\"}\nFRONT_PROXY_CLIENT_CERT=${FRONT_PROXY_CLIENT_CERT:-\"${KUBE_CERT_DIR}/client-auth-proxy.crt\"}\nFRONT_PROXY_CLIENT_KEY=${FRONT_PROXY_CLIENT_KEY:-\"${KUBE_CERT_DIR}/client-auth-proxy.key\"}\n\n\n# Ensure AGGREGATOR_CERT_DIR is created for auto-generated crt/key and kubeconfig\nmkdir -p \"${AGGREGATOR_CERT_DIR}\" &>/dev/null || sudo mkdir -p \"${AGGREGATOR_CERT_DIR}\"\nsudo=$(test -w \"${AGGREGATOR_CERT_DIR}\" || echo \"sudo -E\")\n\n# start_kube-aggregator relies on certificates created by start_apiserver\nfunction start_kube-aggregator {\n\t # Create serving and client CA.  etcd only takes one arg\n\tkube::util::create_signing_certkey \"${sudo}\" \"${AGGREGATOR_CERT_DIR}\" \"etcd\" '\"client auth\",\"server auth\"'\n\tkube::util::create_serving_certkey \"${sudo}\" \"${AGGREGATOR_CERT_DIR}\" \"etcd-ca\" etcd etcd.kube-public.svc\n\t# etcd doesn't seem to have separate signers for serving and client trust\n\tkube::util::create_client_certkey \"${sudo}\" \"${AGGREGATOR_CERT_DIR}\" \"etcd-ca\" kube-aggregator-etcd kube-aggregator-etcd\n\n\t# don't fail if the namespace already exists or something\n\t# If this fails for some reason, the script will fail during creation of other resources\n\tkubectl create namespace kube-public || true\n\n\t# grant permission to run delegated authentication and authorization checks\n\tkubectl delete clusterrolebinding kube-aggregator:system:auth-delegator > /dev/null 2>&1 || true\n\tkubectl delete clusterrolebinding kube-aggregator:system:kube-aggregator > /dev/null 2>&1 || true\n\tkubectl create clusterrolebinding kube-aggregator:system:auth-delegator --clusterrole=system:auth-delegator --serviceaccount=kube-public:kube-aggregator\n\tkubectl create clusterrolebinding kube-aggregator:system:kube-aggregator --clusterrole=system:kube-aggregator --serviceaccount=kube-public:kube-aggregator\n\tkubectl delete rolebinding -n kube-system kube-aggregator:authentication-reader > /dev/null 2>&1 || true\n\tkubectl create rolebinding -n kube-system kube-aggregator:authentication-reader --role=extension-apiserver-authentication-reader --serviceaccount=kube-public:kube-aggregator\n\n\t# make sure the resources we're about to create don't exist\n\tkubectl -n kube-public delete secret auth-proxy-client serving-etcd serving-kube-aggregator kube-aggregator-etcd > /dev/null 2>&1 || true\n\tkubectl -n kube-public delete configmap etcd-ca kube-aggregator-ca client-ca request-header-ca > /dev/null 2>&1 || true\n\tkubectl -n kube-public delete -f \"${AGG_ROOT}/artifacts/self-contained\" > /dev/null 2>&1 || true\n\n\t${sudo} \"$(which kubectl)\" -n kube-public create secret tls auth-proxy-client --cert=\"${FRONT_PROXY_CLIENT_CERT}\" --key=\"${FRONT_PROXY_CLIENT_KEY}\"\n\t${sudo} \"$(which kubectl)\"  -n kube-public create secret tls serving-etcd --cert=\"${AGGREGATOR_CERT_DIR}/serving-etcd.crt\" --key=\"${AGGREGATOR_CERT_DIR}/serving-etcd.key\"\n\t${sudo} \"$(which kubectl)\"  -n kube-public create secret tls serving-kube-aggregator --cert=\"${SERVING_CERT}\" --key=\"${SERVING_KEY}\"\n\t${sudo} \"$(which kubectl)\"  -n kube-public create secret tls kube-aggregator-etcd --cert=\"${AGGREGATOR_CERT_DIR}/client-kube-aggregator-etcd.crt\" --key=\"${AGGREGATOR_CERT_DIR}/client-kube-aggregator-etcd.key\"\n\tkubectl -n kube-public create configmap etcd-ca --from-file=\"ca.crt=${AGGREGATOR_CERT_DIR}/etcd-ca.crt\" || true\n\tkubectl -n kube-public create configmap kube-aggregator-ca --from-file=\"ca.crt=${SERVING_CERT_CA_CERT}\" || true\n\tkubectl -n kube-public create configmap client-ca --from-file=\"ca.crt=${CLIENT_CERT_CA_CERT}\" || true\n\tkubectl -n kube-public create configmap request-header-ca --from-file=\"ca.crt=${FRONT_PROXY_CLIENT_CERT_CA_CERT}\" || true\n\n\tkubectl -n kube-public create -f \"${AGG_ROOT}/artifacts/self-contained\"\n\n\t# Wait for kube-aggregator to come up before launching the rest of the components.\n\t# This should work since we're creating a node port service.\n\techo \"Waiting for kube-aggregator to come up: https://${API_HOST_IP}:${AGGREGATOR_SECURE_PORT}/version\"\n\tkube::util::wait_for_url \"https://${API_HOST_IP}:${AGGREGATOR_SECURE_PORT}/version\" \"kube-aggregator: \" 1 60 || exit 1\n}\n\nkube::util::test_openssl_installed\nkube::util::ensure-cfssl\n\nstart_kube-aggregator\n\necho \"kube-aggregator available at https://${API_HOST_IP}:${AGGREGATOR_SECURE_PORT} from 'api.kube-public.svc'\"\n", "num_lines": 94}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\nif LANG=C sed --help 2>&1 | grep -q GNU; then\n  SED=\"sed\"\nelif which gsed &>/dev/null; then\n  SED=\"gsed\"\nelse\n  echo \"Failed to find GNU sed as sed or gsed. If you are on Mac: brew install gnu-sed.\" >&2\n  exit 1\nfi\n\ndir=$(mktemp -d \"${TMPDIR:-/tmp/}$(basename 0).XXXXXXXXXXXX\")\n# Register function to be called on EXIT to remove generated binary.\nfunction cleanup {\n  rm -rf \"${dir}\"\n}\ntrap cleanup EXIT\n\n\nscriptDir=$(dirname \"${BASH_SOURCE[0]}\")\n\n# this uses discovery from a kube-like API server to register ALL the API versions that server provides\n# first argument is reference to kube-config file that points the API server you're adding from\n# second argument is the service namespace\n# third argument is the service name\n# fourth argument is reference to kube-config file that points to the aggregator you're using\n\nFROM_KUBECONFIG=${1}\nSERVICE_NAMESPACE=${2}\nSERVICE_NAME=${3}\nAGG_KUBECONFIG=${4}\n\n\ncaBundle=$(base64 /var/run/kubernetes/server-ca.crt | awk 'BEGIN{ORS=\"\";} {print}')\n\n# if we have a /api endpoint, then we need to register that\nif kubectl --kubeconfig=\"${FROM_KUBECONFIG}\" get --raw / | grep -q /api/v1; then\n\tgroup=\"\"\n\tversion=\"v1\"\n\tresourceName=${version}.${group}\n\tresourceFileName=\"${dir}/${resourceName}.yaml\"\n\tcp \"${scriptDir}/apiservice-template.yaml\" \"${resourceFileName}\"\n\t${SED} -i \"s/RESOURCE_NAME/${resourceName}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/API_GROUP/${group}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/API_VERSION/${version}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/SERVICE_NAMESPACE/${SERVICE_NAMESPACE}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/SERVICE_NAME/${SERVICE_NAME}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/CA_BUNDLE/${caBundle}/\" \"${resourceFileName}\"\n\techo \"registering ${resourceName} using ${resourceFileName}\"\n\n\tkubectl --kubeconfig=\"${AGG_KUBECONFIG}\" create -f \"${resourceFileName}\"\nfi\n\nwhile IFS=$'\\n' read -r groupVersion;\n  do groupVersions+=(\"$groupVersion\");\ndone < <(kubectl get --raw / | grep /apis/ | sed 's/\",.*//' | sed 's|.*\"/apis/||' | grep '/')\n\nfor groupVersion in \"${groupVersions[@]}\"; do\n\tgroup=$(echo \"$groupVersion\" | awk -F/ '{print $1}')\n\tversion=$(echo \"$groupVersion\" | awk -F/ '{print $2}')\n\tresourceName=${version}.${group}\n\tresourceFileName=${dir}/${resourceName}.yaml\n\tcp \"${scriptDir}/apiservice-template.yaml\" \"${resourceFileName}\"\n\t${SED} -i \"s/RESOURCE_NAME/${resourceName}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/API_GROUP/${group}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/API_VERSION/${version}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/SERVICE_NAMESPACE/${SERVICE_NAMESPACE}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/SERVICE_NAME/${SERVICE_NAME}/\" \"${resourceFileName}\"\n\t${SED} -i \"s/CA_BUNDLE/${caBundle}/\" \"${resourceFileName}\"\n\techo \"registering ${resourceName} using ${resourceFileName}\"\n\n\tkubectl --kubeconfig=\"${AGG_KUBECONFIG}\" create -f \"${resourceFileName}\"\ndone\n", "num_lines": 93}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\nCLIENTSET_NAME_VERSIONED=clientset \\\nCLIENTSET_PKG_NAME=clientset_generated \\\nbash \"${CODEGEN_PKG}/generate-groups.sh\" deepcopy,client,lister,informer \\\n  k8s.io/kube-aggregator/pkg/client k8s.io/kube-aggregator/pkg/apis \\\n  \"apiregistration:v1beta1,v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\nCLIENTSET_NAME_VERSIONED=clientset \\\nCLIENTSET_PKG_NAME=clientset_generated \\\nCLIENTSET_NAME_INTERNAL=internalclientset \\\nbash \"${CODEGEN_PKG}/generate-internal-groups.sh\" deepcopy,conversion \\\n  k8s.io/kube-aggregator/pkg/client k8s.io/kube-aggregator/pkg/apis k8s.io/kube-aggregator/pkg/apis \\\n  \"apiregistration:v1beta1,v1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n", "num_lines": 40}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ncfssl gencert -initca generate.client-ca.json | cfssljson -bare client-ca\ncfssl gencert -initca generate.server-ca.json | cfssljson -bare server-ca\n\ncfssl gencert -ca client-ca.pem -ca-key client-ca-key.pem -config generate.profiles.json --profile=client generate.client.json | cfssljson -bare client\ncfssl gencert -ca server-ca.pem -ca-key server-ca-key.pem -config generate.profiles.json --profile=server generate.server.json | cfssljson -bare server\n\nrm ./*.csr\n", "num_lines": 24}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# send the original content to the server\ncurl -s -k -XPOST \"http://localhost:8081/callback/in\" --data-binary \"@${1}\"\n# allow the user to edit the file\nvi \"${1}\"\n# send the resulting content to the server\ncurl -s -k -XPOST \"http://localhost:8081/callback/out\" --data-binary \"@${1}\"\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ -z \"${1-}\" ]]; then\n    echo \"Usage: record_testcase.sh testcase-name\"\n    exit 1\nfi\n\n# Clean up the test server\nfunction cleanup {\n    if [[ -n \"${pid-}\" ]]; then\n        echo \"Stopping recording server (${pid})\"\n        # kill the process `go run` launched\n        pkill -P \"${pid}\"\n        # kill the `go run` process itself\n        kill -9 \"${pid}\"\n    fi\n}\n\ntestcase=\"${1}\"\n\ntest_root=\"$(dirname \"${BASH_SOURCE[0]}\")\"\ntestcase_dir=\"${test_root}/testcase-${testcase}\"\nmkdir -p \"${testcase_dir}\"\n\npushd \"${testcase_dir}\"\n    export EDITOR=\"../record_editor.sh\"\n    go run \"../record.go\" &\n    pid=$!\n    trap cleanup EXIT\n    echo \"Started recording server (${pid})\"\n\n    # Make a kubeconfig that makes kubectl talk to our test server\n    edit_kubeconfig=\"${TMP:-/tmp}/edit_test.kubeconfig\"\n    echo \"apiVersion: v1\nclusters:\n- cluster:\n    server: http://localhost:8081\n  name: test\ncontexts:\n- context:\n    cluster: test\n    user: test\n  name: test\ncurrent-context: test\nkind: Config\nusers: []\n\" > \"${edit_kubeconfig}\"\n    export KUBECONFIG=\"${edit_kubeconfig}\"\n\n    echo \"Starting subshell. Type exit when finished.\"\n    bash\npopd\n", "num_lines": 71}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Send the file content to the server\nif command -v curl &>/dev/null; then\n    curl -s -k -XPOST --data-binary \"@${1}\" -o \"${1}.result\" \"${KUBE_EDITOR_CALLBACK}\"\nelif command -v wget &>/dev/null; then\n    wget --post-file=\"${1}\" -O \"${1}.result\" \"${KUBE_EDITOR_CALLBACK}\"\nelse\n    echo \"curl and wget are unavailable\" >&2\n    exit 1\nfi\n\n# Use the response as the edited version\nmv \"${1}.result\" \"${1}\"\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu\n\nreadonly VALID_DAYS='73000'\nreadonly RSA_KEY_SIZE='4096'\n\ncreateKey() {\n  openssl genrsa \\\n    -out \"$1\" \\\n    \"$RSA_KEY_SIZE\"\n}\n\ncreateCaCert() {\n  openssl req \\\n    -x509 \\\n    -subj \"$( getSubj 'someCA' )\" \\\n    -new \\\n    -nodes \\\n    -key \"$2\" \\\n    -sha256 \\\n    -days \"$VALID_DAYS\" \\\n    -out \"$1\"\n}\n\ncreateCSR() {\n  openssl req \\\n    -new \\\n    -sha256 \\\n    -key \"$2\" \\\n    -subj \"$( getSubj 'localhost' )\" \\\n    -reqexts SAN \\\n    -config <( getSANConfig ) \\\n    -out \"$1\"\n}\n\nsignCSR() {\n  openssl x509 \\\n    -req \\\n    -in \"$2\" \\\n    -CA \"$3\" \\\n    -CAkey \"$4\" \\\n    -CAcreateserial \\\n    -days \"$VALID_DAYS\" \\\n    -sha256 \\\n    -extfile <( getSAN ) \\\n    -out \"$1\"\n}\n\ngetSubj() {\n  local cn=\"${1:-someRandomCN}\"\n  echo \"/C=US/ST=CA/O=Acme, Inc./CN=${cn}\"\n}\n\ngetSAN() {\n  printf \"subjectAltName=DNS:localhost,IP:127.0.0.1\"\n}\n\ngetSANConfig() {\n  cat /etc/ssl/openssl.cnf\n  printf '\\n[SAN]\\n'\n  getSAN\n}\n\nmain() {\n  local caCertPath=\"./ca.pem\"\n  local caKeyPath=\"./ca.key\"\n  local serverCsrPath=\"./server.csr\"\n  local serverCertPath=\"./server.pem\"\n  local serverKeyPath=\"./server.key\"\n\n  createKey \"$caKeyPath\"\n  createCaCert \"$caCertPath\" \"$caKeyPath\"\n  createKey \"$serverKeyPath\"\n  createCSR \"$serverCsrPath\" \"$serverKeyPath\"\n  signCSR \"$serverCertPath\" \"$serverCsrPath\" \"$caCertPath\" \"$caKeyPath\"\n}\n\nmain \"$@\"\n", "num_lines": 94}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\n# generate the code with:\n# --output-base    because this script should also be able to run inside the vendor dir of\n#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#                  instead of the $GOPATH directly. For normal projects this can be dropped.\n#\n# we skip informers and listers for metrics, because we don't quite support the requisite operations yet\n# we skip generating the internal clientset as it's not really needed\nbash \"${CODEGEN_PKG}/generate-internal-groups.sh\" deepcopy,conversion \\\n  k8s.io/metrics/pkg/client k8s.io/metrics/pkg/apis k8s.io/metrics/pkg/apis \\\n  \"metrics:v1alpha1,v1beta1 custom_metrics:v1beta1 external_metrics:v1beta1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\nbash \"${CODEGEN_PKG}/generate-groups.sh\" client \\\n  k8s.io/metrics/pkg/client k8s.io/metrics/pkg/apis \\\n  \"metrics:v1alpha1,v1beta1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"", "num_lines": 40}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../../../..\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# Register function to be called on EXIT to remove generated binary.\nfunction cleanup {\n  rm \"${KUBE_ROOT}/vendor/k8s.io/sample-apiserver/artifacts/simple-image/kube-sample-apiserver\"\n}\ntrap cleanup EXIT\n\npushd \"${KUBE_ROOT}/vendor/k8s.io/sample-apiserver\"\ncp -v ../../../../_output/local/bin/linux/amd64/sample-apiserver ./artifacts/simple-image/kube-sample-apiserver\ndocker build -t kube-sample-apiserver:latest ./artifacts/simple-image\npopd\n", "num_lines": 34}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\n# generate the code with:\n# --output-base    because this script should also be able to run inside the vendor dir of\n#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#                  instead of the $GOPATH directly. For normal projects this can be dropped.\nbash \"${CODEGEN_PKG}/generate-groups.sh\" all \\\n  k8s.io/sample-apiserver/pkg/generated k8s.io/sample-apiserver/pkg/apis \\\n  \"wardle:v1alpha1,v1beta1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}\"/hack/boilerplate.go.txt\n\nbash \"${CODEGEN_PKG}/generate-internal-groups.sh\" \"deepcopy,defaulter,conversion,openapi\" \\\n  k8s.io/sample-apiserver/pkg/generated k8s.io/sample-apiserver/pkg/apis k8s.io/sample-apiserver/pkg/apis \\\n  \"wardle:v1alpha1,v1beta1\" \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}/hack/boilerplate.go.txt\"\n\n# To use your own boilerplate text append:\n#   --go-header-file \"${SCRIPT_ROOT}/hack/custom-boilerplate.go.txt\"\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\n# generate the code with:\n# --output-base    because this script should also be able to run inside the vendor dir of\n#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#                  instead of the $GOPATH directly. For normal projects this can be dropped.\nbash \"${CODEGEN_PKG}\"/generate-groups.sh \"deepcopy,client,informer,lister\" \\\n  k8s.io/sample-controller/pkg/generated k8s.io/sample-controller/pkg/apis \\\n  samplecontroller:v1alpha1 \\\n  --output-base \"$(dirname \"${BASH_SOURCE[0]}\")/../../..\" \\\n  --go-header-file \"${SCRIPT_ROOT}\"/hack/boilerplate.go.txt\n\n# To use your own boilerplate text append:\n#   --go-header-file \"${SCRIPT_ROOT}\"/hack/custom-boilerplate.go.txt\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Runs tests related to kubectl apply.\nrun_kubectl_apply_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl apply\"\n  ## kubectl apply should create the resource that doesn't exist yet\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: apply a pod \"test-pod\" (doesn't exist) should create this pod\n  kubectl apply -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" is created\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field:?}.name}}\" 'test-pod-label'\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\"\n  # pod has field manager for kubectl client-side apply\n  output_message=$(kubectl get --show-managed-fields -f hack/testdata/pod.yaml -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-client-side-apply'\n  # Clean up\n  kubectl delete pods test-pod \"${kube_flags[@]:?}\"\n\n  ### set-last-applied\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: create \"test-pod\" (doesn't exist) should create this pod without last-applied annotation\n  kubectl create -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" is created\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field:?}.name}}\" 'test-pod-label'\n  # Pre-Condition: pod \"test-pod\" does not have configuration annotation\n  ! grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\" || exit 1\n  # Dry-run set-last-applied\n  kubectl apply set-last-applied --dry-run=client -f hack/testdata/pod.yaml --create-annotation=true \"${kube_flags[@]:?}\"\n  kubectl apply set-last-applied --dry-run=server -f hack/testdata/pod.yaml --create-annotation=true \"${kube_flags[@]:?}\"\n  ! grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\" || exit 1\n  # Command\n  kubectl apply set-last-applied -f hack/testdata/pod.yaml --create-annotation=true \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\"\n  # Clean up\n  kubectl delete pods test-pod \"${kube_flags[@]:?}\"\n\n  ## kubectl apply should be able to clear defaulted fields.\n  # Pre-Condition: no deployment exists\n  kube::test::get_object_assert deployments \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: apply a deployment \"test-deployment-retainkeys\" (doesn't exist) should create this deployment\n  kubectl apply -f hack/testdata/retainKeys/deployment/deployment-before.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: deployment \"test-deployment-retainkeys\" created\n  kube::test::get_object_assert deployments \"{{range.items}}{{${id_field:?}}}{{end}}\" 'test-deployment-retainkeys'\n  # Post-Condition: deployment \"test-deployment-retainkeys\" has defaulted fields\n  grep -q RollingUpdate <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  grep -q maxSurge <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  grep -q maxUnavailable <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  grep -q emptyDir <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  # Command: apply a deployment \"test-deployment-retainkeys\" should clear\n  # defaulted fields and successfully update the deployment\n  [[ \"$(kubectl apply -f hack/testdata/retainKeys/deployment/deployment-after.yaml \"${kube_flags[@]:?}\")\" ]]\n  # Post-Condition: deployment \"test-deployment-retainkeys\" has updated fields\n  grep -q Recreate <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  ! grep -q RollingUpdate <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\" || exit 1\n  grep -q hostPath <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\"\n  ! grep -q emptyDir <<< \"$(kubectl get deployments test-deployment-retainkeys -o yaml \"${kube_flags[@]:?}\")\" || exit 1\n  # Clean up\n  kubectl delete deployments test-deployment-retainkeys \"${kube_flags[@]:?}\"\n\n  ## kubectl apply -f with label selector should only apply matching objects\n  # Pre-Condition: no POD exists\n  kube::test::wait_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply\n  kubectl apply -l unique-label=bingbang -f hack/testdata/filter \"${kube_flags[@]:?}\"\n  # check right pod exists\n  kube::test::get_object_assert 'pods selector-test-pod' \"{{${labels_field:?}.name}}\" 'selector-test-pod'\n  # check wrong pod doesn't exist\n  output_message=$(! kubectl get pods selector-test-pod-dont-apply 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'pods \"selector-test-pod-dont-apply\" not found'\n  # cleanup\n  kubectl delete pods selector-test-pod\n\n  ## kubectl apply --dry-run=server\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # apply dry-run\n  kubectl apply --dry-run=true -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  kubectl apply --dry-run=client -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  kubectl apply --dry-run=server -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # No pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply non dry-run creates the pod\n  kubectl apply -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  initialResourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n  # apply changes\n  kubectl apply --dry-run=client -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\"\n  kubectl apply --dry-run=server -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: label still has initial value\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field:?}.name}}\" 'test-pod-label'\n  # Ensure dry-run doesn't persist change\n  resourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n  kube::test::if_has_string \"${resourceVersion}\" \"${initialResourceVersion}\"\n\n  # clean-up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n\n  ## kubectl apply dry-run on CR\n  # Create CRD\n  kubectl \"${kube_flags_with_token[@]:?}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"resources.mygroup.example.com\"\n  },\n  \"spec\": {\n    \"group\": \"mygroup.example.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"resources\",\n      \"singular\": \"resource\",\n      \"kind\": \"Kind\",\n      \"listKind\": \"KindList\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1alpha1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"x-kubernetes-preserve-unknown-fields\": true,\n            \"type\": \"object\"\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Ensure the API server has recognized and started serving the associated CR API\n  local tries=5\n  for i in $(seq 1 $tries); do\n      local output\n      output=$(kubectl \"${kube_flags[@]:?}\" api-resources --api-group mygroup.example.com -oname)\n      if kube::test::if_has_string \"$output\" resources.mygroup.example.com; then\n          break\n      fi\n      echo \"${i}: Waiting for CR API to be available\"\n      sleep \"$i\"\n  done\n\n  # Dry-run create the CR\n  kubectl \"${kube_flags[@]:?}\" apply --dry-run=server -f hack/testdata/CRD/resource.yaml \"${kube_flags[@]:?}\"\n  # Make sure that the CR doesn't exist\n  ! kubectl \"${kube_flags[@]:?}\" get resource/myobj 2>/dev/null || exit 1\n\n  # clean-up\n  kubectl \"${kube_flags[@]:?}\" delete customresourcedefinition resources.mygroup.example.com\n\n  ## kubectl apply --prune\n  # Pre-Condition: namespace nsb exists; no POD exists\n  kubectl create ns nsb\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply a into namespace nsb\n  kubectl apply --namespace nsb -l prune-group=true -f hack/testdata/prune/a.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pods a -n nsb' \"{{${id_field:?}}}\" 'a'\n  # apply b with namespace\n  kubectl apply --namespace nsb --prune -l prune-group=true -f hack/testdata/prune/b.yaml \"${kube_flags[@]:?}\"\n  # check right pod exists and wrong pod doesn't exist\n  kube::test::wait_object_assert 'pods -n nsb' \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'b:'\n\n  # cleanup\n  kubectl delete pods b -n nsb\n\n  # same thing without prune for a sanity check\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # apply a\n  kubectl apply -l prune-group=true -f hack/testdata/prune/a.yaml \"${kube_flags[@]:?}\"\n  # check right pod exists\n  kube::test::get_object_assert 'pods a' \"{{${id_field:?}}}\" 'a'\n  # check wrong pod doesn't exist\n  kube::test::wait_object_assert 'pods -n nsb' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # apply b\n  kubectl apply -l prune-group=true -f hack/testdata/prune/b.yaml \"${kube_flags[@]:?}\"\n  # check both pods exist\n  kube::test::get_object_assert 'pods a' \"{{${id_field:?}}}\" 'a'\n  kube::test::get_object_assert 'pods b -n nsb' \"{{${id_field:?}}}\" 'b'\n\n  # cleanup\n  kubectl delete pod/a\n  kubectl delete pod/b -n nsb\n\n  ## kubectl apply --prune requires a --all flag to select everything\n  output_message=$(! kubectl apply --prune -f hack/testdata/prune 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" \\\n    'all resources selected for prune without explicitly passing --all'\n  # should apply everything\n  kubectl apply --all --prune -f hack/testdata/prune\n  kube::test::get_object_assert 'pods a' \"{{${id_field:?}}}\" 'a'\n  kube::test::get_object_assert 'pods b -n nsb' \"{{${id_field:?}}}\" 'b'\n  kubectl delete pod/a\n  kubectl delete pod/b -n nsb\n  kubectl delete ns nsb\n\n  ## kubectl apply --prune should fallback to delete for non reapable types\n  kubectl apply --all --prune -f hack/testdata/prune-reap/a.yml 2>&1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pvc a-pvc' \"{{${id_field:?}}}\" 'a-pvc'\n  kubectl apply --all --prune -f hack/testdata/prune-reap/b.yml 2>&1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pvc b-pvc' \"{{${id_field:?}}}\" 'b-pvc'\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kubectl delete pvc b-pvc 2>&1 \"${kube_flags[@]:?}\"\n\n  ## kubectl apply --prune --prune-whitelist\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply pod a\n  kubectl apply --prune -l prune-group=true -f hack/testdata/prune/a.yaml \"${kube_flags[@]:?}\"\n  # check right pod exists\n  kube::test::get_object_assert 'pods a' \"{{${id_field:?}}}\" 'a'\n  # apply svc and don't prune pod a by overwriting whitelist\n  kubectl apply --prune -l prune-group=true -f hack/testdata/prune/svc.yaml --prune-whitelist core/v1/Service 2>&1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'service prune-svc' \"{{${id_field:?}}}\" 'prune-svc'\n  kube::test::get_object_assert 'pods a' \"{{${id_field:?}}}\" 'a'\n  # apply svc and prune pod a with default whitelist\n  kubectl apply --prune -l prune-group=true -f hack/testdata/prune/svc.yaml 2>&1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'service prune-svc' \"{{${id_field:?}}}\" 'prune-svc'\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # cleanup\n  kubectl delete svc prune-svc 2>&1 \"${kube_flags[@]:?}\"\n\n  ## kubectl apply --prune can prune resources not in the defaulted namespace\n  # Pre-Condition: namespace nsb exists; no POD exists\n  kubectl create ns nsb\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply a into namespace nsb\n  kubectl apply --namespace nsb -f hack/testdata/prune/a.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pods a -n nsb' \"{{${id_field:?}}}\" 'a'\n  # apply b with namespace\n  kubectl apply --namespace nsb -f hack/testdata/prune/b.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pods b -n nsb' \"{{${id_field:?}}}\" 'b'\n  # apply --prune must prune a\n  kubectl apply --prune --all -f hack/testdata/prune/b.yaml\n  # check wrong pod doesn't exist and right pod exists\n  kube::test::wait_object_assert 'pods -n nsb' \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'b:'\n\n  # cleanup\n  kubectl delete ns nsb\n\n  ## kubectl apply -n must fail if input file contains namespace other than the one given in -n\n  output_message=$(! kubectl apply -n foo -f hack/testdata/prune/b.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'the namespace from the provided object \"nsb\" does not match the namespace \"foo\".'\n\n  ## kubectl apply -f some.yml --force\n  # Pre-condition: no service exists\n  kube::test::get_object_assert services \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply service a\n  kubectl apply -f hack/testdata/service-revision1.yaml \"${kube_flags[@]:?}\"\n  # check right service exists\n  kube::test::get_object_assert 'services a' \"{{${id_field:?}}}\" 'a'\n  # change immutable field and apply service a\n  output_message=$(! kubectl apply -f hack/testdata/service-revision2.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'may not change once set'\n  # apply --force to recreate resources for immutable fields\n  kubectl apply -f hack/testdata/service-revision2.yaml --force \"${kube_flags[@]:?}\"\n  # check immutable field exists\n  kube::test::get_object_assert 'services a' \"{{.spec.clusterIP}}\" '10.0.0.12'\n  # cleanup\n  kubectl delete -f hack/testdata/service-revision2.yaml \"${kube_flags[@]:?}\"\n\n  ## kubectl apply -k somedir\n  kubectl apply -k hack/testdata/kustomize\n  kube::test::get_object_assert 'configmap test-the-map' \"{{${id_field}}}\" 'test-the-map'\n  kube::test::get_object_assert 'deployment test-the-deployment' \"{{${id_field}}}\" 'test-the-deployment'\n  kube::test::get_object_assert 'service test-the-service' \"{{${id_field}}}\" 'test-the-service'\n  # cleanup\n  kubectl delete -k hack/testdata/kustomize\n\n  ## kubectl apply --kustomize somedir\n  kubectl apply --kustomize hack/testdata/kustomize\n  kube::test::get_object_assert 'configmap test-the-map' \"{{${id_field}}}\" 'test-the-map'\n  kube::test::get_object_assert 'deployment test-the-deployment' \"{{${id_field}}}\" 'test-the-deployment'\n  kube::test::get_object_assert 'service test-the-service' \"{{${id_field}}}\" 'test-the-service'\n  # cleanup\n  kubectl delete --kustomize hack/testdata/kustomize\n\n  ## kubectl apply multiple resources with one failure during apply phase.\n  # Pre-Condition: namepace does not exist and no POD exists\n  output_message=$(! kubectl get namespace multi-resource-ns 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'namespaces \"multi-resource-ns\" not found'\n  kube::test::wait_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # First pass, namespace is created, but pod is not (since namespace does not exist yet).\n  output_message=$(! kubectl apply -f hack/testdata/multi-resource-1.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'namespaces \"multi-resource-ns\" not found'\n  output_message=$(! kubectl get pods test-pod -n multi-resource-ns 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'pods \"test-pod\" not found'\n  # Second pass, pod is created (now that namespace exists).\n  kubectl apply -f hack/testdata/multi-resource-1.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'pods test-pod -n multi-resource-ns' \"{{${id_field}}}\" 'test-pod'\n  # cleanup\n  kubectl delete -f hack/testdata/multi-resource-1.yaml \"${kube_flags[@]:?}\"\n\n  ## kubectl apply multiple resources with one failure during builder phase.\n  # Pre-Condition: No configmaps with name=foo\n  kube::test::get_object_assert 'configmaps --field-selector=metadata.name=foo' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Apply a configmap and a bogus custom resource.\n  output_message=$(! kubectl apply -f hack/testdata/multi-resource-2.yaml 2>&1 \"${kube_flags[@]:?}\")\n  # Should be error message from bogus custom resource.\n  kube::test::if_has_string \"${output_message}\" 'no matches for kind \"Bogus\" in version \"example.com/v1\"'\n  # ConfigMap should have been created even with custom resource error.\n  kube::test::get_object_assert 'configmaps foo' \"{{${id_field}}}\" 'foo'\n  # cleanup\n  kubectl delete configmaps foo \"${kube_flags[@]:?}\"\n\n  ## kubectl apply multiple resources with one failure during builder phase.\n  # Pre-Condition: No pods exist.\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Applies three pods, one of which is invalid (POD-B), two succeed (pod-a, pod-c).\n  output_message=$(! kubectl apply -f hack/testdata/multi-resource-3.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'The Pod \"POD-B\" is invalid'\n  kube::test::get_object_assert 'pods pod-a' \"{{${id_field}}}\" 'pod-a'\n  kube::test::get_object_assert 'pods pod-c' \"{{${id_field}}}\" 'pod-c'\n  # cleanup\n  kubectl delete pod pod-a pod-c \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  ## kubectl apply multiple resources with one failure during apply phase.\n  # Pre-Condition: crd does not exist, and custom resource does not exist.\n  kube::test::get_object_assert crds \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # First pass, custom resource fails, but crd apply succeeds.\n  output_message=$(! kubectl apply -f hack/testdata/multi-resource-4.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'no matches for kind \"Widget\" in version \"example.com/v1\"'\n  output_message=$(! kubectl get widgets foo 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'widgets.example.com \"foo\" not found'\n  kube::test::get_object_assert 'crds widgets.example.com' \"{{${id_field}}}\" 'widgets.example.com'\n  # Second pass, custom resource is created (now that crd exists).\n  kubectl apply -f hack/testdata/multi-resource-4.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'widget foo' \"{{${id_field}}}\" 'foo'\n  # cleanup\n  kubectl delete -f hack/testdata/multi-resource-4.yaml \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n\n# Runs tests related to kubectl apply (server-side)\nrun_kubectl_server_side_apply_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl apply --server-side\"\n  ## kubectl apply should create the resource that doesn't exist yet\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: apply a pod \"test-pod\" (doesn't exist) should create this pod\n  kubectl apply --server-side -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" is created\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field:?}.name}}\" 'test-pod-label'\n  # pod has field manager for kubectl server-side apply\n  output_message=$(kubectl get --show-managed-fields -f hack/testdata/pod.yaml -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl'\n  # pod has custom field manager\n  kubectl apply --server-side --field-manager=my-field-manager --force-conflicts -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  output_message=$(kubectl get -f hack/testdata/pod.yaml -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'my-field-manager'\n  # Clean up\n  kubectl delete pods test-pod \"${kube_flags[@]:?}\"\n\n  ## kubectl apply --dry-run=server\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # apply dry-run\n  kubectl apply --server-side --dry-run=server -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # No pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply non dry-run creates the pod\n  kubectl apply --server-side -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  initialResourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n  # apply changes\n  kubectl apply --server-side --dry-run=server -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: label still has initial value\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field:?}.name}}\" 'test-pod-label'\n  # Ensure dry-run doesn't persist change\n  resourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n  kube::test::if_has_string \"${resourceVersion}\" \"${initialResourceVersion}\"\n\n  # clean-up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n\n  ## kubectl apply upgrade\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  kube::log::status \"Testing upgrade kubectl client-side apply to server-side apply\"\n  # run client-side apply\n  kubectl apply -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # test upgrade does not work with non-standard server-side apply field manager\n  ! kubectl apply --server-side --field-manager=\"not-kubectl\" -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\" || exit 1\n  # test upgrade from client-side apply to server-side apply\n  kubectl apply --server-side -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\"\n  output_message=$(kubectl apply view-last-applied pod/test-pod -o json 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" '\"name\": \"test-pod-applied\"'\n\n  kube::log::status \"Testing downgrade kubectl server-side apply to client-side apply\"\n  # test downgrade from server-side apply to client-side apply\n  kubectl apply --server-side -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]:?}\")\"\n  output_message=$(kubectl apply view-last-applied pod/test-pod -o json 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" '\"name\": \"test-pod-label\"'\n  kubectl apply -f hack/testdata/pod-apply.yaml \"${kube_flags[@]:?}\"\n\n  # clean-up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n\n  ## kubectl apply dry-run on CR\n  # Create CRD\n  kubectl \"${kube_flags_with_token[@]}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"resources.mygroup.example.com\"\n  },\n  \"spec\": {\n    \"group\": \"mygroup.example.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"resources\",\n      \"singular\": \"resource\",\n      \"kind\": \"Kind\",\n      \"listKind\": \"KindList\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1alpha1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"x-kubernetes-preserve-unknown-fields\": true,\n            \"type\": \"object\"\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Ensure the API server has recognized and started serving the associated CR API\n  local tries=5\n  for i in $(seq 1 $tries); do\n      local output\n      output=$(kubectl \"${kube_flags[@]:?}\" api-resources --api-group mygroup.example.com -oname)\n      if kube::test::if_has_string \"$output\" resources.mygroup.example.com; then\n          break\n      fi\n      echo \"${i}: Waiting for CR API to be available\"\n      sleep \"$i\"\n  done\n\n  # Dry-run create the CR\n  kubectl \"${kube_flags[@]:?}\" apply --server-side --dry-run=server -f hack/testdata/CRD/resource.yaml \"${kube_flags[@]:?}\"\n  # Make sure that the CR doesn't exist\n  ! kubectl \"${kube_flags[@]:?}\" get resource/myobj 2>/dev/null || exit 1\n\n  # clean-up\n  kubectl \"${kube_flags[@]:?}\" delete customresourcedefinition resources.mygroup.example.com\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 499}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_daemonset_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:daemonsets)\"\n\n  ### Create a rolling update DaemonSet\n  # Pre-condition: no DaemonSet exists\n  kube::test::get_object_assert daemonsets \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl apply -f hack/testdata/rollingupdate-daemonset.yaml \"${kube_flags[@]:?}\"\n  # Template Generation should be 1\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '1'\n  kubectl apply -f hack/testdata/rollingupdate-daemonset.yaml \"${kube_flags[@]:?}\"\n  # Template Generation should stay 1\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '1'\n  # Test set commands\n  kubectl set image daemonsets/bind \"${kube_flags[@]:?}\" \"*=k8s.gcr.io/pause:test-cmd\"\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '2'\n  kubectl set env daemonsets/bind \"${kube_flags[@]:?}\" foo=bar\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '3'\n  kubectl set resources daemonsets/bind \"${kube_flags[@]:?}\" --limits=cpu=200m,memory=512Mi\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '4'\n  # pod has field for kubectl set field manager\n  output_message=$(kubectl get daemonsets bind --show-managed-fields -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-set'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert daemonsets pods,events\n\n  # Rollout restart should change generation\n  kubectl rollout restart daemonset/bind \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'daemonsets bind' \"{{${generation_field:?}}}\" '5'\n\n  # Clean up\n  kubectl delete -f hack/testdata/rollingupdate-daemonset.yaml \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_daemonset_history_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:daemonsets, v1:controllerrevisions)\"\n\n  ### Test rolling back a DaemonSet\n  # Pre-condition: no DaemonSet or its pods exists\n  kube::test::get_object_assert daemonsets \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  # Create a DaemonSet (revision 1)\n  kubectl apply -f hack/testdata/rollingupdate-daemonset.yaml --record \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert controllerrevisions \"{{range.items}}{{${annotations_field:?}}}:{{end}}\" \".*rollingupdate-daemonset.yaml --record.*\"\n  # Rollback to revision 1 - should be no-op\n  kubectl rollout undo daemonset --to-revision=1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Update the DaemonSet (revision 2)\n  kubectl apply -f hack/testdata/rollingupdate-daemonset-rv2.yaml --record \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2}:\"\n  kube::test::wait_object_assert daemonset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2_2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  kube::test::wait_object_assert controllerrevisions \"{{range.items}}{{${annotations_field:?}}}:{{end}}\" \".*rollingupdate-daemonset-rv2.yaml --record.*\"\n  # Rollback to revision 1 with dry-run - should be no-op\n  kubectl rollout undo daemonset --dry-run=client \"${kube_flags[@]:?}\"\n  kubectl rollout undo daemonset --dry-run=server \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2_2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  # Rollback to revision 1\n  kubectl rollout undo daemonset --to-revision=1 \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Rollback to revision 1000000 - should fail\n  output_message=$(! kubectl rollout undo daemonset --to-revision=1000000 \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"unable to find specified revision\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Rollback to last revision\n  kubectl rollout undo daemonset \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert daemonset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2}:\"\n  kube::test::wait_object_assert daemonset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_DAEMONSET_R2_2}:\"\n  kube::test::get_object_assert daemonset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  # Clean up\n  kubectl delete -f hack/testdata/rollingupdate-daemonset.yaml \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_apply_deployments_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl apply deployments\"\n  ## kubectl apply should propagate user defined null values\n  # Pre-Condition: no Deployments, ReplicaSets, Pods exist\n  kube::test::get_object_assert deployments \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert replicasets \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply base deployment\n  kubectl apply -f hack/testdata/null-propagation/deployment-l1.yaml \"${kube_flags[@]:?}\"\n  # check right deployment exists\n  kube::test::get_object_assert 'deployments my-depl' \"{{${id_field:?}}}\" 'my-depl'\n  # check right labels exists\n  kube::test::get_object_assert 'deployments my-depl' \"{{.spec.template.metadata.labels.l1}}\" 'l1'\n  kube::test::get_object_assert 'deployments my-depl' \"{{.spec.selector.matchLabels.l1}}\" 'l1'\n  kube::test::get_object_assert 'deployments my-depl' \"{{.metadata.labels.l1}}\" 'l1'\n\n  # apply new deployment with new template labels\n  kubectl apply -f hack/testdata/null-propagation/deployment-l2.yaml \"${kube_flags[@]:?}\"\n  # check right labels exists\n  kube::test::get_object_assert 'deployments my-depl' \"{{.spec.template.metadata.labels.l1}}\" 'l1'\n  kube::test::get_object_assert 'deployments my-depl' \"{{.spec.selector.matchLabels.l1}}\" 'l1'\n  kube::test::get_object_assert 'deployments my-depl' \"{{.metadata.labels.l1}}\" '<no value>'\n\n  # cleanup\n  # need to explicitly remove replicasets and pods because we changed the deployment selector and orphaned things\n  kubectl delete deployments,rs,pods --all --cascade=orphan --grace-period=0\n  # Post-Condition: no Deployments, ReplicaSets, Pods exist\n  kube::test::wait_object_assert deployments \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::wait_object_assert replicasets \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # kubectl apply deployment --overwrite=true --force=true\n  # Pre-Condition: no deployment exists\n  kube::test::get_object_assert deployments \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # apply deployment nginx\n  kubectl apply -f hack/testdata/deployment-label-change1.yaml \"${kube_flags[@]:?}\"\n  # check right deployment exists\n  kube::test::get_object_assert 'deployment nginx' \"{{${id_field:?}}}\" 'nginx'\n  # apply deployment with new labels and a conflicting resourceVersion\n  output_message=$(! kubectl apply -f hack/testdata/deployment-label-change2.yaml 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'Error from server (Conflict)'\n  # apply deployment with --force and --overwrite will succeed\n  kubectl apply -f hack/testdata/deployment-label-change2.yaml --overwrite=true  --force=true --grace-period=10\n  # check the changed deployment\n  output_message=$(kubectl apply view-last-applied deploy/nginx -o json 2>&1 \"${kube_flags[@]:?}\" |grep nginx2)\n  kube::test::if_has_string \"${output_message}\" '\"name\": \"nginx2\"'\n  # applying a resource (with --force) that is both conflicting and invalid will\n  # cause the server to only return a \"Conflict\" error when we attempt to patch.\n  # This means that we will delete the existing resource after receiving 5 conflict\n  # errors in a row from the server, and will attempt to create the modified\n  # resource that we are passing to \"apply\". Since the modified resource is also\n  # invalid, we will receive an invalid error when we attempt to create it, after\n  # having deleted the old resource. Ensure that when this case is reached, the\n  # old resource is restored once again, and the validation error is printed.\n  output_message=$(! kubectl apply -f hack/testdata/deployment-label-change3.yaml --force 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'Invalid value'\n  # Ensure that the old object has been restored\n  kube::test::get_object_assert 'deployment nginx' \"{{${template_labels:?}}}\" 'nginx2'\n  # cleanup\n  kubectl delete deployments --all --grace-period=10\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_deployment_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing deployments\"\n  # Test kubectl create deployment (using default - old generator)\n  kubectl create deployment test-nginx-extensions --image=k8s.gcr.io/nginx:test-cmd\n  # Post-Condition: Deployment \"nginx\" is created.\n  kube::test::get_object_assert 'deploy test-nginx-extensions' \"{{${container_name_field:?}}}\" 'nginx'\n  # and old generator was used, iow. old defaults are applied\n  output_message=$(kubectl get deployment.apps/test-nginx-extensions -o jsonpath='{.spec.revisionHistoryLimit}')\n  kube::test::if_has_not_string \"${output_message}\" '2'\n  # Ensure we can interact with deployments through apps endpoints\n  output_message=$(kubectl get deployment.apps -o=jsonpath='{.items[0].apiVersion}' 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'apps/v1'\n  # Clean up\n  kubectl delete deployment test-nginx-extensions \"${kube_flags[@]:?}\"\n\n  # Test kubectl create deployment\n  kubectl create deployment test-nginx-apps --image=k8s.gcr.io/nginx:test-cmd\n  # Post-Condition: Deployment \"nginx\" is created.\n  kube::test::get_object_assert 'deploy test-nginx-apps' \"{{${container_name_field:?}}}\" 'nginx'\n  # and new generator was used, iow. new defaults are applied\n  output_message=$(kubectl get deployment/test-nginx-apps -o jsonpath='{.spec.revisionHistoryLimit}')\n  kube::test::if_has_string \"${output_message}\" '10'\n  # Ensure we can interact with deployments through apps endpoints\n  output_message=$(kubectl get deployment.apps -o=jsonpath='{.items[0].apiVersion}' 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'apps/v1'\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert rs \"Name:\" \"Pod Template:\" \"Labels:\" \"Selector:\" \"Controlled By\" \"Replicas:\" \"Pods Status:\" \"Volumes:\"\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert pods \"Name:\" \"Image:\" \"Node:\" \"Labels:\" \"Status:\" \"Controlled By\"\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert deployments replicasets,events\n  # Clean up\n  kubectl delete deployment test-nginx-apps \"${kube_flags[@]:?}\"\n\n  ### Test kubectl create deployment with image and command\n  # Pre-Condition: No deployment exists.\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Dry-run command\n  kubectl create deployment nginx-with-command --dry-run=client --image=k8s.gcr.io/nginx:test-cmd -- /bin/sleep infinity\n  kubectl create deployment nginx-with-command --dry-run=server --image=k8s.gcr.io/nginx:test-cmd -- /bin/sleep infinity\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create deployment nginx-with-command --image=k8s.gcr.io/nginx:test-cmd -- /bin/sleep infinity\n  # Post-Condition: Deployment \"nginx\" is created.\n  kube::test::get_object_assert 'deploy nginx-with-command' \"{{${container_name_field:?}}}\" 'nginx'\n  # Clean up\n  kubectl delete deployment nginx-with-command \"${kube_flags[@]:?}\"\n\n  ### Test kubectl create deployment should not fail validation\n  # Pre-Condition: No deployment exists.\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/deployment-with-UnixUserID.yaml \"${kube_flags[@]:?}\"\n  # Post-Condition: Deployment \"deployment-with-unixuserid\" is created.\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'deployment-with-unixuserid:'\n  # Clean up\n  kubectl delete deployment deployment-with-unixuserid \"${kube_flags[@]:?}\"\n\n  ### Test cascading deletion\n  ## Test that rs is deleted when deployment is deleted.\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Create deployment\n  kubectl create -f test/fixtures/doc-yaml/user-guide/deployment.yaml \"${kube_flags[@]:?}\"\n  # Wait for rs to come up.\n  kube::test::wait_object_assert rs \"{{range.items}}{{${rs_replicas_field:?}}}{{end}}\" '3'\n  # Deleting the deployment should delete the rs.\n  # using empty value in cascade flag to make sure the backward compatibility.\n  kubectl delete deployment nginx-deployment \"${kube_flags[@]:?}\" --cascade\n  kube::test::wait_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  ## Test that rs is not deleted when deployment is deleted with cascading strategy set to orphan.\n  # Pre-condition: no deployment and rs exist\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Create deployment\n  kubectl create deployment nginx-deployment --image=k8s.gcr.io/nginx:test-cmd\n  # Wait for rs to come up.\n  kube::test::wait_object_assert rs \"{{range.items}}{{${rs_replicas_field:?}}}{{end}}\" '1'\n  # Delete the deployment with cascading strategy set to orphan.\n  kubectl delete deployment nginx-deployment \"${kube_flags[@]:?}\" --cascade=orphan\n  # Wait for the deployment to be deleted and then verify that rs is not\n  # deleted.\n  kube::test::wait_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert rs \"{{range.items}}{{${rs_replicas_field:?}}}{{end}}\" '1'\n  # Cleanup\n  # Find the name of the rs to be deleted.\n  output_message=$(kubectl get rs \"${kube_flags[@]:?}\" -o template --template=\"{{range.items}}{{${id_field:?}}}{{end}}\")\n  kubectl delete rs \"${output_message}\" \"${kube_flags[@]:?}\"\n\n  ### Auto scale deployment\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Pre-condition: no hpa exists\n  kube::test::get_object_assert 'hpa' \"{{range.items}}{{ if eq $id_field \\\\\\\"nginx-deployment\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/deployment.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'nginx-deployment:'\n  # Dry-run autoscale\n  kubectl-with-retry autoscale deployment nginx-deployment --dry-run=client \"${kube_flags[@]:?}\" --min=2 --max=3\n  kubectl-with-retry autoscale deployment nginx-deployment --dry-run=server \"${kube_flags[@]:?}\" --min=2 --max=3\n  kube::test::get_object_assert 'hpa' \"{{range.items}}{{ if eq $id_field \\\\\\\"nginx-deployment\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # autoscale 2~3 pods, no CPU utilization specified\n  kubectl-with-retry autoscale deployment nginx-deployment \"${kube_flags[@]:?}\" --min=2 --max=3\n  kube::test::get_object_assert 'hpa nginx-deployment' \"{{${hpa_min_field:?}}} {{${hpa_max_field:?}}} {{${hpa_cpu_field:?}}}\" '2 3 80'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert horizontalpodautoscalers events\n  # Clean up\n  # Note that we should delete hpa first, otherwise it may fight with the deployment reaper.\n  kubectl delete hpa nginx-deployment \"${kube_flags[@]:?}\"\n  kubectl delete deployment.apps nginx-deployment \"${kube_flags[@]:?}\"\n\n  ### Rollback a deployment\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  # Create a deployment (revision 1)\n  kubectl create -f hack/testdata/deployment-revision1.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'nginx:'\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Rollback to revision 1 - should be no-op\n  kubectl rollout undo deployment nginx --to-revision=1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Update the deployment (revision 2)\n  kubectl apply -f hack/testdata/deployment-revision2.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment.apps \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  # Rollback to revision 1 with dry-run - should be no-op\n  kubectl rollout undo deployment nginx --dry-run=client \"${kube_flags[@]:?}\" | grep \"test-cmd\"\n  kubectl rollout undo deployment nginx --dry-run=server \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment.apps \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  # Rollback to revision 1\n  kubectl rollout undo deployment nginx --to-revision=1 \"${kube_flags[@]:?}\"\n  sleep 1\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Rollback to revision 1000000 - should be no-op\n  ! kubectl rollout undo deployment nginx --to-revision=1000000 \"${kube_flags[@]:?}\" || exit 1\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Rollback to last revision\n  kubectl rollout undo deployment nginx \"${kube_flags[@]:?}\"\n  sleep 1\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  # Pause the deployment\n  kubectl-with-retry rollout pause deployment nginx \"${kube_flags[@]:?}\"\n  # A paused deployment cannot be rolled back\n  ! kubectl rollout undo deployment nginx \"${kube_flags[@]:?}\" || exit 1\n  # A paused deployment cannot be restarted\n  ! kubectl rollout restart deployment nginx \"${kube_flags[@]:?}\" || exit 1\n  # Resume the deployment\n  kubectl-with-retry rollout resume deployment nginx \"${kube_flags[@]:?}\"\n  # The resumed deployment can now be rolled back\n  kubectl rollout undo deployment nginx \"${kube_flags[@]:?}\"\n  # Check that the new replica set has all old revisions stored in an annotation\n  newrs=\"$(kubectl describe deployment nginx | grep NewReplicaSet | awk '{print $2}')\"\n  kubectl get rs \"${newrs}\" -o yaml | grep \"deployment.kubernetes.io/revision-history: 1,3\"\n  # Check that trying to watch the status of a superseded revision returns an error\n  ! kubectl rollout status deployment/nginx --revision=3 || exit 1\n  # Restarting the deployment creates a new replicaset\n  kubectl rollout restart deployment/nginx\n  sleep 1\n  newrs=\"$(kubectl describe deployment nginx | grep NewReplicaSet | awk '{print $2}')\"\n  rs=\"$(kubectl get rs \"${newrs}\" -o yaml)\"\n  kube::test::if_has_string \"${rs}\" \"deployment.kubernetes.io/revision: \\\"6\\\"\"\n  # Deployment has field for kubectl rollout field manager\n  output_message=$(kubectl get deployment nginx --show-managed-fields -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-rollout'\n  # Create second deployment\n  ${SED} \"s/name: nginx$/name: nginx2/\" hack/testdata/deployment-revision1.yaml | kubectl create -f - \"${kube_flags[@]:?}\"\n  # Deletion of both deployments should not be blocked\n  kubectl delete deployment nginx2 \"${kube_flags[@]:?}\"\n  # Clean up\n  kubectl delete deployment nginx \"${kube_flags[@]:?}\"\n\n  ### Set image of a deployment\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Create a deployment\n  kubectl create -f hack/testdata/deployment-multicontainer.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'nginx-deployment:'\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Dry-run set the deployment's image\n  kubectl set image deployment nginx-deployment nginx=\"${IMAGE_DEPLOYMENT_R2}\" --dry-run=client \"${kube_flags[@]:?}\"\n  kubectl set image deployment nginx-deployment nginx=\"${IMAGE_DEPLOYMENT_R2}\" --dry-run=server \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set the deployment's image\n  kubectl set image deployment nginx-deployment nginx=\"${IMAGE_DEPLOYMENT_R2}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set non-existing container should fail\n  ! kubectl set image deployment nginx-deployment redis=redis \"${kube_flags[@]:?}\" || exit 1\n  # Set image of deployments without specifying name\n  kubectl set image deployments --all nginx=\"${IMAGE_DEPLOYMENT_R1}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set image of a deployment specified by file\n  kubectl set image -f hack/testdata/deployment-multicontainer.yaml nginx=\"${IMAGE_DEPLOYMENT_R2}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set image of a local file without talking to the server\n  kubectl set image -f hack/testdata/deployment-multicontainer.yaml nginx=\"${IMAGE_DEPLOYMENT_R1}\" \"${kube_flags[@]:?}\" --local -o yaml\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R2}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set image of all containers of the deployment\n  kubectl set image deployment nginx-deployment \"*=${IMAGE_DEPLOYMENT_R1}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Set image of all containers of the deployment again when image not change\n  kubectl set image deployment nginx-deployment \"*=${IMAGE_DEPLOYMENT_R1}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Clean up\n  kubectl delete deployment nginx-deployment \"${kube_flags[@]:?}\"\n\n  ### Set env of a deployment\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Create a deployment\n  kubectl create -f hack/testdata/deployment-multicontainer.yaml \"${kube_flags[@]:?}\"\n  kubectl create -f hack/testdata/configmap.yaml \"${kube_flags[@]:?}\"\n  kubectl create -f hack/testdata/secret.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'nginx-deployment:'\n  #configmap is special here due to controller will create kube-root-ca.crt for each namespace automatically\n  kube::test::get_object_assert 'configmaps/test-set-env-config' \"{{${id_field:?}}}\" 'test-set-env-config'\n  kube::test::get_object_assert secret \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'test-set-env-secret:'\n  # Set env of deployments by configmap from keys\n  kubectl set env deployment nginx-deployment --keys=key-2 --from=configmap/test-set-env-config \"${kube_flags[@]:?}\"\n  # Assert correct value in deployment env\n  kube::test::get_object_assert 'deploy nginx-deployment' \"{{ (index (index .spec.template.spec.containers 0).env 0).name}}\" 'KEY_2'\n  # Assert single value in deployment env\n  kube::test::get_object_assert 'deploy nginx-deployment' \"{{ len (index .spec.template.spec.containers 0).env }}\" '1'\n  # Dry-run set env\n  kubectl set env deployment nginx-deployment --dry-run=client --from=configmap/test-set-env-config \"${kube_flags[@]:?}\"\n  kubectl set env deployment nginx-deployment --dry-run=server --from=configmap/test-set-env-config \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'deploy nginx-deployment' \"{{ len (index .spec.template.spec.containers 0).env }}\" '1'\n  # Set env of deployments by configmap\n  kubectl set env deployment nginx-deployment --from=configmap/test-set-env-config \"${kube_flags[@]:?}\"\n  # Assert all values in deployment env\n  kube::test::get_object_assert 'deploy nginx-deployment' \"{{ len (index .spec.template.spec.containers 0).env }}\" '2'\n  # Set env of deployments for all container\n  kubectl set env deployment nginx-deployment env=prod \"${kube_flags[@]:?}\"\n  # Set env of deployments for specific container\n  kubectl set env deployment nginx-deployment superenv=superprod -c=nginx \"${kube_flags[@]:?}\"\n  # Set env of deployments by secret from keys\n  kubectl set env deployment nginx-deployment --keys=username --from=secret/test-set-env-secret \"${kube_flags[@]:?}\"\n  # Set env of deployments by secret\n  kubectl set env deployment nginx-deployment --from=secret/test-set-env-secret \"${kube_flags[@]:?}\"\n  # Remove specific env of deployment\n  kubectl set env deployment nginx-deployment env-\n  # Assert that we cannot use standard input for both resource and environment variable\n  output_message=\"$(echo SOME_ENV_VAR_KEY=SOME_ENV_VAR_VAL | kubectl set env -f - - \"${kube_flags[@]:?}\" 2>&1 || true)\"\n  kube::test::if_has_string \"${output_message}\" 'standard input cannot be used for multiple arguments'\n  # Clean up\n  kubectl delete deployment nginx-deployment \"${kube_flags[@]:?}\"\n  kubectl delete configmap test-set-env-config \"${kube_flags[@]:?}\"\n  kubectl delete secret test-set-env-secret \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_statefulset_history_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:statefulsets, v1:controllerrevisions)\"\n\n  ### Test rolling back a StatefulSet\n  # Pre-condition: no statefulset or its pods exists\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  # Create a StatefulSet (revision 1)\n  kubectl apply -f hack/testdata/rollingupdate-statefulset.yaml --record \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert controllerrevisions \"{{range.items}}{{${annotations_field:?}}}:{{end}}\" \".*rollingupdate-statefulset.yaml --record.*\"\n  # Rollback to revision 1 - should be no-op\n  kubectl rollout undo statefulset --to-revision=1 \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R1}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Update the statefulset (revision 2)\n  kubectl apply -f hack/testdata/rollingupdate-statefulset-rv2.yaml --record \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R2}:\"\n  kube::test::wait_object_assert statefulset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  kube::test::wait_object_assert controllerrevisions \"{{range.items}}{{${annotations_field:?}}}:{{end}}\" \".*rollingupdate-statefulset-rv2.yaml --record.*\"\n  # Rollback to revision 1 with dry-run - should be no-op\n  kubectl rollout undo statefulset --dry-run=client \"${kube_flags[@]:?}\"\n  kubectl rollout undo statefulset --dry-run=server \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R2}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  # Rollback to revision 1\n  kubectl rollout undo statefulset --to-revision=1 \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R1}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Rollback to revision 1000000 - should fail\n  output_message=$(! kubectl rollout undo statefulset --to-revision=1000000 \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"unable to find specified revision\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R1}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"1\"\n  # Rollback to last revision\n  kubectl rollout undo statefulset \"${kube_flags[@]:?}\"\n  kube::test::wait_object_assert statefulset \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_STATEFULSET_R2}:\"\n  kube::test::wait_object_assert statefulset \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PAUSE_V2}:\"\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${container_len:?}}}{{end}}\" \"2\"\n  # Clean up - delete newest configuration\n  kubectl delete -f hack/testdata/rollingupdate-statefulset-rv2.yaml \"${kube_flags[@]:?}\"\n  # Post-condition: no pods from statefulset controller\n  wait-for-pods-with-label \"app=nginx-statefulset\" \"\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_stateful_set_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:statefulsets)\"\n\n  ### Create and stop statefulset, make sure it doesn't leak pods\n  # Pre-condition: no statefulset exists\n  kube::test::get_object_assert statefulset \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: create statefulset\n  kubectl create -f hack/testdata/rollingupdate-statefulset.yaml \"${kube_flags[@]:?}\"\n\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert statefulsets pods,events\n\n  ### Scale statefulset test with current-replicas and replicas\n  # Pre-condition: 0 replicas\n  kube::test::get_object_assert 'statefulset nginx' \"{{${statefulset_replicas_field:?}}}\" '0'\n  kube::test::wait_object_assert 'statefulset nginx' \"{{${statefulset_observed_generation:?}}}\" '1'\n  # Command: Scale up\n  kubectl scale --current-replicas=0 --replicas=1 statefulset nginx \"${kube_flags[@]:?}\"\n  # Post-condition: 1 replica, named nginx-0\n  kube::test::get_object_assert 'statefulset nginx' \"{{${statefulset_replicas_field:?}}}\" '1'\n  kube::test::wait_object_assert 'statefulset nginx' \"{{${statefulset_observed_generation:?}}}\" '2'\n  # Typically we'd wait and confirm that N>1 replicas are up, but this framework\n  # doesn't start  the scheduler, so pet-0 will block all others.\n  # TODO: test robust scaling in an e2e.\n  wait-for-pods-with-label \"app=nginx-statefulset\" \"nginx-0\"\n\n  # Rollout restart should change generation\n  kubectl rollout restart statefulset nginx \"${kube_flags[@]}\"\n  kube::test::get_object_assert 'statefulset nginx' \"{{$statefulset_observed_generation}}\" '3'\n\n  ### Clean up\n  kubectl delete -f hack/testdata/rollingupdate-statefulset.yaml \"${kube_flags[@]:?}\"\n  # Post-condition: no pods from statefulset controller\n  wait-for-pods-with-label \"app=nginx-statefulset\" \"\"\n\n  set +o nounset\n  set +o errexit\n\n}\n\nrun_rs_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:replicasets)\"\n\n  ### Create and stop a replica set, make sure it doesn't leak pods\n  # Pre-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\"\n  kube::log::status \"Deleting rs\"\n  kubectl delete rs frontend \"${kube_flags[@]:?}\"\n  # Post-condition: no pods from frontend replica set\n  kube::test::wait_object_assert 'pods -l \"tier=frontend\"' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  ### Create and then delete a replica set with cascading strategy set to orphan, make sure it doesn't delete pods.\n  # Pre-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]}\"\n  # wait for all 3 pods to be set up\n  kube::test::wait_object_assert 'pods -l \"tier=frontend\"' \"{{range.items}}{{${pod_container_name_field:?}}}:{{end}}\" 'php-redis:php-redis:php-redis:'\n  kube::log::status \"Deleting rs\"\n  kubectl delete rs frontend \"${kube_flags[@]:?}\" --cascade=orphan\n  # Wait for the rs to be deleted.\n  kube::test::wait_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Post-condition: All 3 pods still remain from frontend replica set\n  kube::test::get_object_assert 'pods -l \"tier=frontend\"' \"{{range.items}}{{$pod_container_name_field}}:{{end}}\" 'php-redis:php-redis:php-redis:'\n  # Cleanup\n  kubectl delete pods -l \"tier=frontend\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  ### Create replica set frontend from YAML\n  # Pre-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\"\n  # Post-condition: frontend replica set is created\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'frontend:'\n  # Describe command should print detailed information\n  kube::test::describe_object_assert rs 'frontend' \"Name:\" \"Pod Template:\" \"Labels:\" \"Selector:\" \"Replicas:\" \"Pods Status:\" \"Volumes:\"\n  # Describe command should print events information by default\n  kube::test::describe_object_events_assert rs 'frontend'\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_object_events_assert rs 'frontend' false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_object_events_assert rs 'frontend' true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert rs \"Name:\" \"Pod Template:\" \"Labels:\" \"Selector:\" \"Replicas:\" \"Pods Status:\" \"Volumes:\"\n  # Describe command should print events information by default\n  kube::test::describe_resource_events_assert rs\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_resource_events_assert rs false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_resource_events_assert rs true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert pods \"Name:\" \"Image:\" \"Node:\" \"Labels:\" \"Status:\" \"Controlled By\"\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert replicasets pods,events\n\n  ### Scale replica set frontend with current-replicas and replicas\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'rs frontend' \"{{${rs_replicas_field:?}}}\" '3'\n  # Dry-run Command\n  kubectl scale --dry-run=client --current-replicas=3 --replicas=2 replicasets frontend \"${kube_flags[@]:?}\"\n  kubectl scale --dry-run=server --current-replicas=3 --replicas=2 replicasets frontend \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'rs frontend' \"{{${rs_replicas_field:?}}}\" '3'\n  # Command\n  kubectl scale --current-replicas=3 --replicas=2 replicasets frontend \"${kube_flags[@]:?}\"\n  # Post-condition: 2 replicas\n  kube::test::get_object_assert 'rs frontend' \"{{${rs_replicas_field:?}}}\" '2'\n\n  # Set up three deploy, two deploy have same label\n  kubectl create -f hack/testdata/scale-deploy-1.yaml \"${kube_flags[@]:?}\"\n  kubectl create -f hack/testdata/scale-deploy-2.yaml \"${kube_flags[@]:?}\"\n  kubectl create -f hack/testdata/scale-deploy-3.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'deploy scale-1' \"{{.spec.replicas}}\" '1'\n  kube::test::get_object_assert 'deploy scale-2' \"{{.spec.replicas}}\" '1'\n  kube::test::get_object_assert 'deploy scale-3' \"{{.spec.replicas}}\" '1'\n  # Test kubectl scale --all with dry run\n  kubectl scale deploy --replicas=3 --all --dry-run=client\n  kubectl scale deploy --replicas=3 --all --dry-run=server\n  kube::test::get_object_assert 'deploy scale-1' \"{{.spec.replicas}}\" '1'\n  kube::test::get_object_assert 'deploy scale-2' \"{{.spec.replicas}}\" '1'\n  kube::test::get_object_assert 'deploy scale-3' \"{{.spec.replicas}}\" '1'\n  # Test kubectl scale --selector\n  kubectl scale deploy --replicas=2 -l run=hello\n  kube::test::get_object_assert 'deploy scale-1' \"{{.spec.replicas}}\" '2'\n  kube::test::get_object_assert 'deploy scale-2' \"{{.spec.replicas}}\" '2'\n  kube::test::get_object_assert 'deploy scale-3' \"{{.spec.replicas}}\" '1'\n  # Test kubectl scale --all\n  kubectl scale deploy --replicas=3 --all\n  kube::test::get_object_assert 'deploy scale-1' \"{{.spec.replicas}}\" '3'\n  kube::test::get_object_assert 'deploy scale-2' \"{{.spec.replicas}}\" '3'\n  kube::test::get_object_assert 'deploy scale-3' \"{{.spec.replicas}}\" '3'\n  # Clean-up\n  kubectl delete rs frontend \"${kube_flags[@]:?}\"\n  kubectl delete deploy scale-1 scale-2 scale-3 \"${kube_flags[@]:?}\"\n\n  ### Expose replica set as service\n  kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\"\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'rs frontend' \"{{${rs_replicas_field:?}}}\" '3'\n  # Command\n  kubectl expose rs frontend --port=80 \"${kube_flags[@]:?}\"\n  # Post-condition: service exists and the port is unnamed\n  kube::test::get_object_assert 'service frontend' \"{{${port_name:?}}} {{${port_field:?}}}\" '<no value> 80'\n  # Cleanup services\n  kubectl delete service frontend \"${kube_flags[@]:?}\"\n\n  # Test set commands\n  # Pre-condition: frontend replica set exists at generation 1\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '1'\n  kubectl set image rs/frontend \"${kube_flags[@]:?}\" \"*=k8s.gcr.io/pause:test-cmd\"\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '2'\n  kubectl set env rs/frontend \"${kube_flags[@]:?}\" foo=bar\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '3'\n  kubectl set resources rs/frontend --dry-run=client \"${kube_flags[@]:?}\" --limits=cpu=200m,memory=512Mi\n  kubectl set resources rs/frontend --dry-run=server \"${kube_flags[@]:?}\" --limits=cpu=200m,memory=512Mi\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '3'\n  kubectl set resources rs/frontend \"${kube_flags[@]:?}\" --limits=cpu=200m,memory=512Mi\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '4'\n  kubectl set serviceaccount rs/frontend --dry-run=client \"${kube_flags[@]:?}\" serviceaccount1\n  kubectl set serviceaccount rs/frontend --dry-run=server \"${kube_flags[@]:?}\" serviceaccount1\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '4'\n  kubectl set serviceaccount rs/frontend \"${kube_flags[@]:?}\" serviceaccount1\n  kube::test::get_object_assert 'rs frontend' \"{{${generation_field:?}}}\" '5'\n\n  # RS has field for kubectl set field manager\n  output_message=$(kubectl get rs frontend --show-managed-fields -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-set'\n\n  ### Delete replica set with id\n  # Pre-condition: frontend replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'frontend:'\n  # Command\n  kubectl delete rs frontend \"${kube_flags[@]:?}\"\n  # Post-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  ### Create two replica sets\n  # Pre-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\"\n  kubectl create -f hack/testdata/redis-slave-replicaset.yaml \"${kube_flags[@]:?}\"\n  # Post-condition: frontend and redis-slave\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'frontend:redis-slave:'\n\n  ### Delete multiple replica sets at once\n  # Pre-condition: frontend and redis-slave\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'frontend:redis-slave:'\n  # Command\n  kubectl delete rs frontend redis-slave \"${kube_flags[@]:?}\" # delete multiple replica sets at once\n  # Post-condition: no replica set exists\n  kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  if kube::test::if_supports_resource \"horizontalpodautoscalers\" ; then\n    ### Auto scale replica set\n    # Pre-condition: no replica set exists\n    kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n    # Command\n    kubectl create -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\"\n    kube::test::get_object_assert rs \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'frontend:'\n    # autoscale 1~2 pods, CPU utilization 70%, replica set specified by file\n    kubectl autoscale -f hack/testdata/frontend-replicaset.yaml \"${kube_flags[@]:?}\" --max=2 --cpu-percent=70\n    kube::test::get_object_assert 'hpa frontend' \"{{${hpa_min_field:?}}} {{${hpa_max_field:?}}} {{${hpa_cpu_field:?}}}\" '1 2 70'\n    kubectl delete hpa frontend \"${kube_flags[@]:?}\"\n    # autoscale 2~3 pods, no CPU utilization specified, replica set specified by name\n    kubectl autoscale rs frontend \"${kube_flags[@]:?}\" --min=2 --max=3\n    kube::test::get_object_assert 'hpa frontend' \"{{${hpa_min_field:?}}} {{${hpa_max_field:?}}} {{${hpa_cpu_field:?}}}\" '2 3 80'\n    # HorizontalPodAutoscaler has field for kubectl autoscale field manager\n    output_message=$(kubectl get hpa frontend -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n    kube::test::if_has_string \"${output_message}\" 'kubectl-autoscale'\n    # Clean up\n    kubectl delete hpa frontend \"${kube_flags[@]:?}\"\n    # autoscale without specifying --max should fail\n    ! kubectl autoscale rs frontend \"${kube_flags[@]:?}\" || exit 1\n    # Clean up\n    kubectl delete rs frontend \"${kube_flags[@]:?}\"\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 731}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_exec_credentials_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl with configured exec credentials plugin\"\n\n  cat > \"${TMPDIR:-/tmp}\"/invalid_exec_plugin.yaml << EOF\napiVersion: v1\nclusters:\n- cluster:\n  name: test\ncontexts:\n- context:\n    cluster: test\n    user: invalid_token_user\n  name: test\ncurrent-context: test\nkind: Config\npreferences: {}\nusers:\n- name: invalid_token_user\n  user:\n    exec:\n      apiVersion: client.authentication.k8s.io/v1beta1\n      # Any invalid exec credential plugin will do to demonstrate\n      command: ls\nEOF\n\n  ### Provided --token should take precedence, thus not triggering the (invalid) exec credential plugin\n  # Pre-condition: Client certificate authentication enabled on the API server\n  kube::util::test_client_certificate_authentication_enabled\n  # Command\n  output=$(kubectl \"${kube_flags_with_token[@]:?}\" --kubeconfig=\"${TMPDIR:-/tmp}\"/invalid_exec_plugin.yaml get namespace kube-system -o name || true)\n\n  if [[ \"${output}\" == \"namespace/kube-system\" ]]; then\n    kube::log::status \"exec credential plugin not triggered since kubectl was called with provided --token\"\n  else\n    kube::log::status \"Unexpected output when providing --token for authentication - exec credential plugin likely triggered. Output: ${output}\"\n    exit 1    \n  fi\n  # Post-condition: None\n\n  ### Without provided --token, the exec credential plugin should be triggered\n  # Pre-condition: Client certificate authentication enabled on the API server - already checked by positive test above\n\n  # Command\n  output2=$(kubectl \"${kube_flags_without_token[@]:?}\" --kubeconfig=\"${TMPDIR:-/tmp}\"/invalid_exec_plugin.yaml get namespace kube-system -o name 2>&1 || true)\n\n  if [[ \"${output2}\" =~ \"json parse error\" ]]; then\n    kube::log::status \"exec credential plugin triggered since kubectl was called without provided --token\"\n  else\n    kube::log::status \"Unexpected output when not providing --token for authentication - exec credential plugin not triggered. Output: ${output2}\"\n    exit 1\n  fi\n  # Post-condition: None\n\n  cat > \"${TMPDIR:-/tmp}\"/valid_exec_plugin.yaml << EOF\napiVersion: v1\nclusters:\n- cluster:\n  name: test\ncontexts:\n- context:\n    cluster: test\n    user: valid_token_user\n  name: test\ncurrent-context: test\nkind: Config\npreferences: {}\nusers:\n- name: valid_token_user\n  user:\n    exec:\n      apiVersion: client.authentication.k8s.io/v1beta1\n      command: echo\n      args:\n        - '{\"apiVersion\":\"client.authentication.k8s.io/v1beta1\",\"status\":{\"token\":\"admin-token\"}}'\nEOF\n\n  ### Valid exec plugin should authenticate user properly\n  # Pre-condition: Client certificate authentication enabled on the API server - already checked by positive test above\n\n  # Command\n  output3=$(kubectl \"${kube_flags_without_token[@]:?}\" --kubeconfig=\"${TMPDIR:-/tmp}\"/valid_exec_plugin.yaml get namespace kube-system -o name 2>&1 || true)\n\n  if [[ \"${output3}\" == \"namespace/kube-system\" ]]; then\n    kube::log::status \"exec credential plugin triggered and provided valid credentials\"\n  else\n    kube::log::status \"Unexpected output when using valid exec credential plugin for authentication. Output: ${output3}\"\n    exit 1\n  fi\n  # Post-condition: None\n\n  ### Provided --username/--password should take precedence, thus not triggering the (valid) exec credential plugin\n  # Pre-condition: Client certificate authentication enabled on the API server - already checked by positive test above\n\n  # Command\n  output4=$(kubectl \"${kube_flags_without_token[@]:?}\" --username bad --password wrong --kubeconfig=\"${TMPDIR:-/tmp}\"/valid_exec_plugin.yaml get namespace kube-system -o name 2>&1 || true)\n\n  if [[ \"${output4}\" =~ \"Unauthorized\" ]]; then\n    kube::log::status \"exec credential plugin not triggered since kubectl was called with provided --username/--password\"\n  else\n    kube::log::status \"Unexpected output when providing --username/--password for authentication - exec credential plugin likely triggered. Output: ${output4}\"\n    exit 1\n  fi\n  # Post-condition: None\n\n  rm \"${TMPDIR:-/tmp}\"/invalid_exec_plugin.yaml\n  rm \"${TMPDIR:-/tmp}\"/valid_exec_plugin.yaml\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_exec_credentials_interactive_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl with configured interactive exec credentials plugin\"\n\n  cat > \"${TMPDIR:-/tmp}\"/always_interactive_exec_plugin.yaml << EOF\napiVersion: v1\nclusters:\n- cluster:\n  name: test\ncontexts:\n- context:\n    cluster: test\n    user: always_interactive_token_user\n  name: test\ncurrent-context: test\nkind: Config\npreferences: {}\nusers:\n- name: always_interactive_token_user\n  user:\n    exec:\n      apiVersion: client.authentication.k8s.io/v1beta1\n      command: echo\n      args:\n        - '{\"apiVersion\":\"client.authentication.k8s.io/v1beta1\",\"status\":{\"token\":\"admin-token\"}}'\n      interactiveMode: Always\nEOF\n\n  ### The exec credential plugin should not be run if it kubectl already uses standard input\n  # Pre-condition: The kubectl command requires standard input\n\n  some_resource='{\"apiVersion\":\"v1\",\"kind\":\"ConfigMap\",\"metadata\":{\"name\":\"some-resource\"}}'\n\n  # Declare map from kubectl command to standard input data\n  declare -A kubectl_commands\n  kubectl_commands[\"apply -f -\"]=\"$some_resource\"\n  kubectl_commands[\"set env deployment/some-deployment -\"]=\"SOME_ENV_VAR_KEY=SOME_ENV_VAR_VAL\"\n  kubectl_commands[\"replace -f - --force\"]=\"$some_resource\"\n\n  failure=\n  for kubectl_command in \"${!kubectl_commands[@]}\"; do\n    # Use a separate bash script for the command here so that script(1) will not get confused with kubectl flags\n    script_file=\"${TMPDIR:-/tmp}/test-cmd-exec-credentials-script-file.sh\"\n    cat <<EOF >\"$script_file\"\n#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nkubectl ${kube_flags_without_token[*]:?} --kubeconfig=${TMPDIR:-/tmp}/always_interactive_exec_plugin.yaml ${kubectl_command} 2>&1 || true\nEOF\n    chmod +x \"$script_file\"\n\n    # Run kubectl as child of script(1) so kubectl will always run with a PTY\n    # Dynamically build script(1) command so that we can conditionally add flags on Linux\n    script_command=\"script -q /dev/null\"\n    if [[ \"$(uname)\" == \"Linux\" ]]; then script_command=\"${script_command} -c\"; fi\n    script_command=\"${script_command} ${script_file}\"\n\n    # Specify SHELL env var when we call script(1) since it is picky about the format of the env var\n    shell=\"$(which bash)\"\n\n    kube::log::status \"Running command '$script_command' (kubectl command: '$kubectl_command') with input '${kubectl_commands[$kubectl_command]}'\"\n    output=$(echo \"${kubectl_commands[$kubectl_command]}\" | SHELL=\"$shell\" $script_command)\n\n    if [[ \"${output}\" =~ \"used by stdin resource manifest reader\" ]]; then\n      kube::log::status \"exec credential plugin not run because kubectl already uses standard input\"\n    else\n      kube::log::status \"Unexpected output when running kubectl command that uses standard input. Output: ${output}\"\n      failure=yup\n    fi\n  done\n\n  if [[ -n \"$failure\" ]]; then\n    exit 1\n  fi\n\n  # Post-condition: None\n\n  rm \"${TMPDIR:-/tmp}\"/always_interactive_exec_plugin.yaml\n\n  set +o nounset\n  set +o errexit\n}", "num_lines": 219}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_authorization_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing authorization\"\n\n  # check remote authorization endpoint, kubectl doesn't actually display the returned object so this isn't super useful\n  # but it proves that works\n  kubectl create -f test/fixtures/pkg/kubectl/cmd/create/sar-v1.json --validate=false\n\n  SAR_RESULT_FILE=\"${KUBE_TEMP}/sar-result.json\"\n  curl -kfsS -H \"Content-Type:\" -H 'Authorization: Bearer admin-token' \"https://localhost:${SECURE_API_PORT}/apis/authorization.k8s.io/v1/subjectaccessreviews\" -XPOST -d @test/fixtures/pkg/kubectl/cmd/create/sar-v1.json > \"${SAR_RESULT_FILE}\"\n  if grep -q '\"allowed\": true' \"${SAR_RESULT_FILE}\"; then\n    kube::log::status \"\\\"authorization.k8s.io/subjectaccessreviews\\\" returns as expected: $(cat \"${SAR_RESULT_FILE}\")\"\n  else\n    kube::log::status \"\\\"authorization.k8s.io/subjectaccessreviews\\\" does not return as expected: $(cat \"${SAR_RESULT_FILE}\")\"\n    exit 1\n  fi\n  rm \"${SAR_RESULT_FILE}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_impersonation_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing impersonation\"\n\n  output_message=$(! kubectl get pods \"${kube_flags_with_token[@]:?}\" --as-group=foo 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'without impersonating a user'\n\n  if kube::test::if_supports_resource \"${csr:?}\" ; then\n    # --as\n    kubectl create -f hack/testdata/csr.yml \"${kube_flags_with_token[@]:?}\" --as=user1\n    kube::test::get_object_assert 'csr/foo' '{{.spec.username}}' 'user1'\n    kube::test::get_object_assert 'csr/foo' '{{range .spec.groups}}{{.}}{{end}}' 'system:authenticated'\n    kubectl delete -f hack/testdata/csr.yml \"${kube_flags_with_token[@]:?}\"\n\n    # --as-group\n    kubectl create -f hack/testdata/csr.yml \"${kube_flags_with_token[@]:?}\" --as=user1 --as-group=group2 --as-group=group1 --as-group=,,,chameleon\n    kube::test::get_object_assert 'csr/foo' '{{len .spec.groups}}' '4'\n    kube::test::get_object_assert 'csr/foo' '{{range .spec.groups}}{{.}} {{end}}' 'group2 group1 ,,,chameleon system:authenticated '\n    kubectl delete -f hack/testdata/csr.yml \"${kube_flags_with_token[@]:?}\"\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 71}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_job_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing job\"\n\n  ### Create a new namespace\n  # Pre-condition: the test-jobs namespace does not exist\n  kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq ${id_field:?} \\\\\\\"test-jobs\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create namespace test-jobs\n  # Post-condition: namespace 'test-jobs' is created.\n  kube::test::get_object_assert 'namespaces/test-jobs' \"{{$id_field}}\" 'test-jobs'\n\n  # Pre-condition: cronjob does not exist\n  kube::test::get_object_assert 'cronjob --namespace=test-jobs' \"{{range.items}}{{ if eq $id_field \\\\\\\"pi\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run create CronJob\n  kubectl create cronjob pi --dry-run=client --schedule=\"59 23 31 2 *\" --namespace=test-jobs \"--image=$IMAGE_PERL\" -- perl -Mbignum=bpi -wle 'print bpi(20)' \"${kube_flags[@]:?}\"\n  kubectl create cronjob pi --dry-run=server --schedule=\"59 23 31 2 *\" --namespace=test-jobs \"--image=$IMAGE_PERL\" -- perl -Mbignum=bpi -wle 'print bpi(20)' \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'cronjob' \"{{range.items}}{{ if eq $id_field \\\\\\\"pi\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  ### Create a cronjob in a specific namespace\n  kubectl create cronjob pi --schedule=\"59 23 31 2 *\" --namespace=test-jobs \"--image=$IMAGE_PERL\" -- perl -Mbignum=bpi -wle 'print bpi(20)' \"${kube_flags[@]:?}\"\n  # Post-Condition: assertion object exists\n  kube::test::get_object_assert 'cronjob/pi --namespace=test-jobs' \"{{$id_field}}\" 'pi'\n  kubectl get cronjob/pi --namespace=test-jobs\n  kubectl describe cronjob/pi --namespace=test-jobs\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert cronjobs events \"--namespace=test-jobs\"\n\n  ### Create a job in dry-run mode\n  output_message=$(kubectl create job test-job --from=cronjob/pi --dry-run=true --namespace=test-jobs -o name)\n  # Post-condition: The text 'job.batch/test-job' should be part of the output\n  kube::test::if_has_string \"${output_message}\" 'job.batch/test-job'\n  # Post-condition: The test-job wasn't created actually\n  kube::test::get_object_assert jobs \"{{range.items}}{{$id_field}}{{end}}\" ''\n\n  # Pre-condition: job does not exist\n  kube::test::get_object_assert 'job --namespace=test-jobs' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-jobs\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  ### Dry-run create a job in a specific namespace\n  kubectl create job test-job --from=cronjob/pi --namespace=test-jobs --dry-run=client\n  kubectl create job test-job --from=cronjob/pi --namespace=test-jobs --dry-run=server\n  kube::test::get_object_assert 'job --namespace=test-jobs' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-jobs\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  ### Create a job in a specific namespace\n  kubectl create job test-job --from=cronjob/pi --namespace=test-jobs\n  # Post-Condition: assertion object exists\n  kube::test::get_object_assert 'job/test-job --namespace=test-jobs' \"{{$id_field}}\" 'test-job'\n  kubectl get job/test-job --namespace=test-jobs\n  kubectl describe job/test-job --namespace=test-jobs\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert jobs events \"--namespace=test-jobs\"\n  #Clean up\n  kubectl delete job test-job --namespace=test-jobs\n  kubectl delete cronjob pi --namespace=test-jobs\n  kubectl delete namespace test-jobs\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 80}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_certificates_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing certificates\"\n\n  # approve\n  kubectl create -f hack/testdata/csr.yml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' ''\n  kubectl certificate approve foo \"${kube_flags[@]}\"\n  kubectl get csr \"${kube_flags[@]}\" -o json\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' 'Approved'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert certificatesigningrequests events\n  kubectl delete -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert csr \"{{range.items}}{{${id_field:?}}}{{end}}\" ''\n\n  kubectl create -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' ''\n  kubectl certificate approve -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kubectl get csr \"${kube_flags[@]}\" -o json\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' 'Approved'\n  kubectl delete -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert csr \"{{range.items}}{{$id_field}}{{end}}\" ''\n\n  # deny\n  kubectl create -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' ''\n  kubectl certificate deny foo \"${kube_flags[@]}\"\n  kubectl get csr \"${kube_flags[@]}\" -o json\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' 'Denied'\n  kubectl delete -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert csr \"{{range.items}}{{$id_field}}{{end}}\" ''\n\n  kubectl create -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' ''\n  kubectl certificate deny -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kubectl get csr \"${kube_flags[@]}\" -o json\n  kube::test::get_object_assert 'csr/foo' '{{range.status.conditions}}{{.type}}{{end}}' 'Denied'\n  kubectl delete -f hack/testdata/csr.yml \"${kube_flags[@]}\"\n  kube::test::get_object_assert csr \"{{range.items}}{{$id_field}}{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 66}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_convert_tests() {\n  set -o nounset\n  set -o errexit\n\n  ### Convert deployment YAML file locally without affecting the live deployment\n  # Pre-condition: no deployments exist\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  # Create a deployment (revision 1)\n  kubectl create -f hack/testdata/deployment-revision1.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'nginx:'\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  # Command\n  output_message=$(kubectl convert --local -f hack/testdata/deployment-revision1.yaml --output-version=apps/v1beta1 -o yaml \"${kube_flags[@]:?}\")\n  # Post-condition: apiVersion is still apps/v1 in the live deployment, but command output is the new value\n  kube::test::get_object_assert 'deployment nginx' \"{{ .apiVersion }}\" 'apps/v1'\n  kube::test::if_has_string \"${output_message}\" \"apps/v1beta1\"\n  # Clean up\n  kubectl delete deployment nginx \"${kube_flags[@]:?}\"\n\n  ## Convert multiple busybox PODs recursively from directory of YAML files\n  # Command\n  output_message=$(! kubectl-convert -f hack/testdata/recursive/pod --recursive 2>&1 \"${kube_flags[@]:?}\")\n  # Post-condition: busybox0 & busybox1 PODs are converted, and since busybox2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  # check that convert command supports --template output\n  output_message=$(kubectl-convert \"${kube_flags[@]:?}\" -f hack/testdata/deployment-revision1.yaml --output-version=apps/v1beta2 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'nginx:'\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 54}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_configmap_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing configmaps\"\n  kubectl create -f test/fixtures/doc-yaml/user-guide/configmap/configmap.yaml\n  kube::test::get_object_assert 'configmap/test-configmap' \"{{${id_field:?}}}\" 'test-configmap'\n  kubectl delete configmap test-configmap \"${kube_flags[@]:?}\"\n\n  ### Create a new namespace\n  # Pre-condition: the test-configmaps namespace does not exist\n  kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-configmaps\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create namespace test-configmaps\n  # Post-condition: namespace 'test-configmaps' is created.\n  kube::test::get_object_assert 'namespaces/test-configmaps' \"{{$id_field}}\" 'test-configmaps'\n\n  ### Create a generic configmap in a specific namespace\n  # Pre-condition: configmap test-configmap and test-binary-configmap does not exist\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-configmap\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-binary-configmap\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run command\n  kubectl create configmap test-configmap --dry-run=client --from-literal=key1=value1 --namespace=test-configmaps\n  kubectl create configmap test-configmap --dry-run=server --from-literal=key1=value1 --namespace=test-configmaps\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-configmap\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create configmap test-configmap --from-literal=key1=value1 --namespace=test-configmaps\n  kubectl create configmap test-binary-configmap --from-file <( head -c 256 /dev/urandom ) --namespace=test-configmaps\n  # Post-condition: configmap exists and has expected values\n  kube::test::get_object_assert 'configmap/test-configmap --namespace=test-configmaps' \"{{$id_field}}\" 'test-configmap'\n  kube::test::get_object_assert 'configmap/test-binary-configmap --namespace=test-configmaps' \"{{$id_field}}\" 'test-binary-configmap'\n  grep -q \"key1: value1\" <<< \"$(kubectl get configmap/test-configmap --namespace=test-configmaps -o yaml \"${kube_flags[@]}\")\"\n  grep -q \"binaryData\" <<< \"$(kubectl get configmap/test-binary-configmap --namespace=test-configmaps -o yaml \"${kube_flags[@]}\")\"\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert configmaps events \"--namespace=test-configmaps\"\n  # Clean-up\n  kubectl delete configmap test-configmap --namespace=test-configmaps\n  kubectl delete configmap test-binary-configmap --namespace=test-configmaps\n  kubectl delete namespace test-configmaps\n\n  set +o nounset\n  set +o errexit\n}\n\n# Runs all pod related tests.\nrun_pod_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl(v1:pods)\"\n\n  ### Create POD valid-pod from JSON\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  # Post-condition: valid-pod POD is created\n  kubectl get \"${kube_flags[@]}\" pods -o json\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  kube::test::get_object_assert 'pod valid-pod' \"{{$id_field}}\" 'valid-pod'\n  kube::test::get_object_assert 'pod/valid-pod' \"{{$id_field}}\" 'valid-pod'\n  kube::test::get_object_assert 'pods/valid-pod' \"{{$id_field}}\" 'valid-pod'\n  # pod has field manager for kubectl create\n  output_message=$(kubectl get --show-managed-fields -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-create'\n  # Repeat above test using jsonpath template\n  kube::test::get_object_jsonpath_assert pods \"{.items[*]$id_field}\" 'valid-pod'\n  kube::test::get_object_jsonpath_assert 'pod valid-pod' \"{$id_field}\" 'valid-pod'\n  kube::test::get_object_jsonpath_assert 'pod/valid-pod' \"{$id_field}\" 'valid-pod'\n  kube::test::get_object_jsonpath_assert 'pods/valid-pod' \"{$id_field}\" 'valid-pod'\n  # Describe command should print detailed information\n  kube::test::describe_object_assert pods 'valid-pod' \"Name:\" \"Image:\" \"Node:\" \"Labels:\" \"Status:\"\n  # Describe command should print events information by default\n  kube::test::describe_object_events_assert pods 'valid-pod'\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_object_events_assert pods 'valid-pod' false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_object_events_assert pods 'valid-pod' true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert pods \"Name:\" \"Image:\" \"Node:\" \"Labels:\" \"Status:\"\n\n  # Describe command should print events information by default\n  kube::test::describe_resource_events_assert pods\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_resource_events_assert pods false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_resource_events_assert pods true\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert pods events\n\n  ### Dump current valid-pod POD\n  output_pod=$(kubectl get pod valid-pod -o yaml \"${kube_flags[@]}\")\n\n  ### Delete POD valid-pod by id\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete pod valid-pod \"${kube_flags[@]}\" --grace-period=0 --force\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Delete POD valid-pod by id with --now\n  # Pre-condition: valid-pod POD exists\n  kubectl create \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete pod valid-pod \"${kube_flags[@]}\" --now\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Delete POD valid-pod by id with --grace-period=0\n  # Pre-condition: valid-pod POD exists\n  kubectl create \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command succeeds without --force by waiting\n  kubectl delete pod valid-pod \"${kube_flags[@]}\" --grace-period=0\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create POD valid-pod from dumped YAML\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  echo \"${output_pod}\" | ${SED} '/namespace:/d' | kubectl create -f - \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Delete POD valid-pod from JSON\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\" --grace-period=0 --force\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create POD valid-pod from JSON\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Delete POD valid-pod with label\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert \"pods -l'name in (valid-pod)'\" \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete pods -l'name in (valid-pod)' \"${kube_flags[@]}\" --grace-period=0 --force\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert \"pods -l'name in (valid-pod)'\" \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create POD valid-pod from YAML\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  output_message=$(kubectl get pods --field-selector metadata.name=valid-pod \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"valid-pod\"\n  # Command\n  phase=$(kubectl get \"${kube_flags[@]}\" pod valid-pod -o go-template='{{ .status.phase }}')\n  output_message=$(kubectl get pods --field-selector status.phase=\"${phase}\" \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"valid-pod\"\n\n  ### Delete PODs with no parameter mustn't kill everything\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  ! kubectl delete pods \"${kube_flags[@]}\" || exit 1\n  # Post-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Delete PODs with --all and a label selector is not permitted\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  ! kubectl delete --all pods -l'name in (valid-pod)' \"${kube_flags[@]}\" || exit 1\n  # Post-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Delete all PODs\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete --all pods \"${kube_flags[@]}\" --grace-period=0 --force # --all remove all the pods\n  # Post-condition: no POD exists\n  kube::test::get_object_assert \"pods -l'name in (valid-pod)'\" \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Detailed tests for describe pod output\n    ### Create a new namespace\n  # Pre-condition: the test-secrets namespace does not exist\n  kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-kubectl-describe-pod\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create namespace test-kubectl-describe-pod\n  # Post-condition: namespace 'test-secrets' is created.\n  kube::test::get_object_assert 'namespaces/test-kubectl-describe-pod' \"{{$id_field}}\" 'test-kubectl-describe-pod'\n\n  ### Create a generic secret\n  # Pre-condition: no SECRET exists\n  kube::test::get_object_assert 'secrets --namespace=test-kubectl-describe-pod' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Dry-run command\n  kubectl create secret generic test-secret --dry-run=client --from-literal=key-1=value1 --type=test-type --namespace=test-kubectl-describe-pod\n  kubectl create secret generic test-secret --dry-run=server --from-literal=key-1=value1 --type=test-type --namespace=test-kubectl-describe-pod\n  kube::test::get_object_assert 'secrets --namespace=test-kubectl-describe-pod' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create secret generic test-secret --from-literal=key-1=value1 --type=test-type --namespace=test-kubectl-describe-pod\n  # Post-condition: secret exists and has expected values\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-kubectl-describe-pod' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-kubectl-describe-pod' \"{{${secret_type:?}}}\" 'test-type'\n\n  ### Create a generic configmap\n  # Pre-condition: CONFIGMAP test-configmap does not exist\n  #kube::test::get_object_assert 'configmap/test-configmap --namespace=test-kubectl-describe-pod' \"{{$id_field}}\" ''\n  kube::test::get_object_assert 'configmaps --namespace=test-kubectl-describe-pod' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-configmap\\\\\\\" }}found{{end}}{{end}}:\" ':'\n\n  #kube::test::get_object_assert 'configmaps --namespace=test-kubectl-describe-pod' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create configmap test-configmap --from-literal=key-2=value2 --namespace=test-kubectl-describe-pod\n  # Post-condition: configmap exists and has expected values\n  kube::test::get_object_assert 'configmap/test-configmap --namespace=test-kubectl-describe-pod' \"{{$id_field}}\" 'test-configmap'\n\n  ### Create a pod disruption budget with minAvailable\n  # Pre-condition: pdb does not exist\n  kube::test::get_object_assert 'pdb --namespace=test-kubectl-describe-pod' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-pdb-1\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run command\n  kubectl create pdb test-pdb-1 --dry-run=client --selector=app=rails --min-available=2 --namespace=test-kubectl-describe-pod\n  kubectl create pdb test-pdb-1 --dry-run=server --selector=app=rails --min-available=2 --namespace=test-kubectl-describe-pod\n  kube::test::get_object_assert 'pdb --namespace=test-kubectl-describe-pod' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-pdb-1\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create pdb test-pdb-1 --selector=app=rails --min-available=2 --namespace=test-kubectl-describe-pod\n  # Post-condition: pdb exists and has expected values\n  kube::test::get_object_assert 'pdb/test-pdb-1 --namespace=test-kubectl-describe-pod' \"{{${pdb_min_available:?}}}\" '2'\n  # Command\n  kubectl create pdb test-pdb-2 --selector=app=rails --min-available=50% --namespace=test-kubectl-describe-pod\n  # Post-condition: pdb exists and has expected values\n  kube::test::get_object_assert 'pdb/test-pdb-2 --namespace=test-kubectl-describe-pod' \"{{$pdb_min_available}}\" '50%'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert poddisruptionbudgets events \"--namespace=test-kubectl-describe-pod\"\n\n  ### Create a pod disruption budget with maxUnavailable\n  # Command\n  kubectl create pdb test-pdb-3 --selector=app=rails --max-unavailable=2 --namespace=test-kubectl-describe-pod\n  # Post-condition: pdb exists and has expected values\n  kube::test::get_object_assert 'pdb/test-pdb-3 --namespace=test-kubectl-describe-pod' \"{{${pdb_max_unavailable:?}}}\" '2'\n  # Command\n  kubectl create pdb test-pdb-4 --selector=app=rails --max-unavailable=50% --namespace=test-kubectl-describe-pod\n  # Post-condition: pdb exists and has expected values\n  kube::test::get_object_assert 'pdb/test-pdb-4 --namespace=test-kubectl-describe-pod' \"{{$pdb_max_unavailable}}\" '50%'\n\n  ### Fail creating a pod disruption budget if both maxUnavailable and minAvailable specified\n  ! kubectl create pdb test-pdb --selector=app=rails --min-available=2 --max-unavailable=3 --namespace=test-kubectl-describe-pod || exit 1\n\n  # Create a pod that consumes secret, configmap, and downward API keys as envs\n  kube::test::get_object_assert 'pods --namespace=test-kubectl-describe-pod' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kubectl create -f hack/testdata/pod-with-api-env.yaml --namespace=test-kubectl-describe-pod\n\n  kube::test::describe_object_assert 'pods --namespace=test-kubectl-describe-pod' 'env-test-pod' \"TEST_CMD_1\" \"<set to the key 'key-1' in secret 'test-secret'>\" \"TEST_CMD_2\" \"<set to the key 'key-2' of config map 'test-configmap'>\" \"TEST_CMD_3\" \"env-test-pod (v1:metadata.name)\"\n  # Describe command (resource only) should print detailed information about environment variables\n  kube::test::describe_resource_assert 'pods --namespace=test-kubectl-describe-pod' \"TEST_CMD_1\" \"<set to the key 'key-1' in secret 'test-secret'>\" \"TEST_CMD_2\" \"<set to the key 'key-2' of config map 'test-configmap'>\" \"TEST_CMD_3\" \"env-test-pod (v1:metadata.name)\"\n\n  # Clean-up\n  kubectl delete pod env-test-pod --namespace=test-kubectl-describe-pod\n  kubectl delete secret test-secret --namespace=test-kubectl-describe-pod\n  kubectl delete configmap test-configmap --namespace=test-kubectl-describe-pod\n  kubectl delete pdb/test-pdb-1 pdb/test-pdb-2 pdb/test-pdb-3 pdb/test-pdb-4 --namespace=test-kubectl-describe-pod\n  kubectl delete namespace test-kubectl-describe-pod\n\n  ### Priority Class\n  kube::test::get_object_assert 'priorityclasses' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-priorityclass\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run command\n  kubectl create priorityclass test-priorityclass --dry-run=client\n  kubectl create priorityclass test-priorityclass --dry-run=server\n  kube::test::get_object_assert 'priorityclasses' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-priorityclass\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create priorityclass test-priorityclass\n  kube::test::get_object_assert 'priorityclasses' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-priorityclass\\\\\\\" }}found{{end}}{{end}}:\" 'found:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert priorityclasses events\n  kubectl delete priorityclass test-priorityclass\n\n  ### Create two PODs\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  kubectl create -f test/e2e/testing-manifests/kubectl/agnhost-primary-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod and agnhost-primary PODs are created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'agnhost-primary:valid-pod:'\n\n  ### Delete multiple PODs at once\n  # Pre-condition: valid-pod and agnhost-primary PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'agnhost-primary:valid-pod:'\n  # Command\n  kubectl delete pods valid-pod agnhost-primary \"${kube_flags[@]}\" --grace-period=0 --force # delete multiple pods at once\n  # Post-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create valid-pod POD\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Dry-run label the valid-pod POD\n  # Pre-condition: valid-pod is not labelled\n  kube::test::get_object_assert 'pod valid-pod' \"{{range${labels_field:?}}}{{.}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl label pods valid-pod new-name=new-valid-pod --dry-run=client \"${kube_flags[@]}\"\n  kubectl label pods valid-pod new-name=new-valid-pod --dry-run=server \"${kube_flags[@]}\"\n  # Post-condition: valid-pod is not labelled\n  kube::test::get_object_assert 'pod valid-pod' \"{{range${labels_field:?}}}{{.}}:{{end}}\" 'valid-pod:'\n\n  ### Label the valid-pod POD\n  # Pre-condition: valid-pod is not labelled\n  kube::test::get_object_assert 'pod valid-pod' \"{{range${labels_field:?}}}{{.}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl label pods valid-pod new-name=new-valid-pod \"${kube_flags[@]}\"\n  # Post-condition: valid-pod is labelled\n  kube::test::get_object_assert 'pod valid-pod' \"{{range$labels_field}}{{.}}:{{end}}\" 'valid-pod:new-valid-pod:'\n\n  ### Label the valid-pod POD with empty label value\n  # Pre-condition: valid-pod does not have label \"emptylabel\"\n  kube::test::get_object_assert 'pod valid-pod' \"{{range$labels_field}}{{.}}:{{end}}\" 'valid-pod:new-valid-pod:'\n  # Command\n  kubectl label pods valid-pod emptylabel=\"\" \"${kube_flags[@]}\"\n  # Post-condition: valid pod contains \"emptylabel\" with no value\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.emptylabel}}\" ''\n\n  ### Dry-run annotate the valid-pod POD with empty annotation value\n  # Pre-condition: valid-pod does not have annotation \"emptyannotation\"\n  kube::test::get_object_assert 'pod valid-pod' \"{{${annotations_field:?}.emptyannotation}}\" '<no value>'\n  # Command\n  kubectl annotate pods valid-pod emptyannotation=\"\" --dry-run=client \"${kube_flags[@]}\"\n  kubectl annotate pods valid-pod emptyannotation=\"\" --dry-run=server \"${kube_flags[@]}\"\n  # Post-condition: valid-pod does not have annotation \"emptyannotation\"\n  kube::test::get_object_assert 'pod valid-pod' \"{{${annotations_field:?}.emptyannotation}}\" '<no value>'\n\n  ### Annotate the valid-pod POD with empty annotation value\n  # Pre-condition: valid-pod does not have annotation \"emptyannotation\"\n  kube::test::get_object_assert 'pod valid-pod' \"{{${annotations_field:?}.emptyannotation}}\" '<no value>'\n  # Command\n  kubectl annotate pods valid-pod emptyannotation=\"\" \"${kube_flags[@]}\"\n  # Post-condition: valid pod contains \"emptyannotation\" with no value\n  kube::test::get_object_assert 'pod valid-pod' \"{{${annotations_field}.emptyannotation}}\" ''\n  # pod has field for kubectl annotate field manager\n  output_message=$(kubectl get pod valid-pod -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-annotate'\n\n  ### Record label change\n  # Pre-condition: valid-pod does not have record annotation\n  kube::test::get_object_assert 'pod valid-pod' \"{{range.items}}{{$annotations_field}}:{{end}}\" ''\n  # Command\n  kubectl label pods valid-pod record-change=true --record=true \"${kube_flags[@]}\"\n  # Post-condition: valid-pod has record annotation\n  kube::test::get_object_assert 'pod valid-pod' \"{{range$annotations_field}}{{.}}:{{end}}\" \".*--record=true.*\"\n  # pod has field for kubectl label field manager\n  output_message=$(kubectl get pod valid-pod -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-label'\n\n  ### Do not record label change\n  # Command\n  kubectl label pods valid-pod no-record-change=true --record=false \"${kube_flags[@]}\"\n  # Post-condition: valid-pod's record annotation still contains command with --record=true\n  kube::test::get_object_assert 'pod valid-pod' \"{{range$annotations_field}}{{.}}:{{end}}\" \".*--record=true.*\"\n\n  ### Record label change with specified flag and previous change already recorded\n  ### we are no longer tricked by data from another user into revealing more information about our client\n  # Command\n  kubectl label pods valid-pod new-record-change=true --record=true \"${kube_flags[@]}\"\n  # Post-condition: valid-pod's record annotation contains new change\n  kube::test::get_object_assert 'pod valid-pod' \"{{range$annotations_field}}{{.}}:{{end}}\" \".*new-record-change=true.*\"\n\n\n  ### Delete POD by label\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete pods -lnew-name=new-valid-pod --grace-period=0 --force \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create pod-with-precision POD\n  # Pre-condition: no POD is running\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/pod-with-precision.json \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is running\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'pod-with-precision:'\n\n  ## Patch preserves precision\n  # Command\n  kubectl patch \"${kube_flags[@]}\" pod pod-with-precision -p='{\"metadata\":{\"annotations\":{\"patchkey\": \"patchvalue\"}}}'\n  # Post-condition: pod-with-precision POD has patched annotation\n  kube::test::get_object_assert 'pod pod-with-precision' \"{{${annotations_field}.patchkey}}\" 'patchvalue'\n  # Command\n  kubectl label pods pod-with-precision labelkey=labelvalue \"${kube_flags[@]}\"\n  # Post-condition: pod-with-precision POD has label\n  kube::test::get_object_assert 'pod pod-with-precision' \"{{${labels_field}.labelkey}}\" 'labelvalue'\n  # Command\n  kubectl annotate pods pod-with-precision annotatekey=annotatevalue \"${kube_flags[@]}\"\n  # Post-condition: pod-with-precision POD has annotation\n  kube::test::get_object_assert 'pod pod-with-precision' \"{{${annotations_field}.annotatekey}}\" 'annotatevalue'\n  # Cleanup\n  kubectl delete pod pod-with-precision \"${kube_flags[@]}\"\n\n  ### Annotate POD YAML file locally without effecting the live pod.\n  kubectl create -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  # Command\n  kubectl annotate -f hack/testdata/pod.yaml annotatekey=annotatevalue \"${kube_flags[@]}\"\n\n  # Pre-condition: annotationkey is annotationvalue\n  kube::test::get_object_assert 'pod test-pod' \"{{${annotations_field}.annotatekey}}\" 'annotatevalue'\n\n  # Command\n  output_message=$(kubectl annotate --local -f hack/testdata/pod.yaml annotatekey=localvalue -o yaml \"${kube_flags[@]}\")\n  echo \"$output_message\"\n\n  # Post-condition: annotationkey is still annotationvalue in the live pod, but command output is the new value\n  kube::test::get_object_assert 'pod test-pod' \"{{${annotations_field}.annotatekey}}\" 'annotatevalue'\n  kube::test::if_has_string \"${output_message}\" \"localvalue\"\n\n  # Cleanup\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n\n  ### Create valid-pod POD\n  # Pre-condition: no services and no rcs exist\n  kube::test::get_object_assert service \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  ## kubectl create --edit can update the label filed of multiple resources. tmp-editor.sh is a fake editor\n  TEMP=$(mktemp /tmp/tmp-editor-XXXXXXXX.sh)\n  echo -e \"#!/usr/bin/env bash\\n${SED} -i \\\"s/mock/modified/g\\\" \\$1\" > \"${TEMP}\"\n  chmod +x \"${TEMP}\"\n  # Command\n  EDITOR=${TEMP} kubectl create --edit -f hack/testdata/multi-resource-json.json \"${kube_flags[@]}\"\n  # Post-condition: service named modified and rc named modified are created\n  kube::test::get_object_assert service \"{{range.items}}{{$id_field}}:{{end}}\" 'modified:'\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'modified:'\n  # resources have field manager for kubectl create\n  output_message=$(kubectl get service/modified -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-create'\n  output_message=$(kubectl get rc/modified -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-create'\n  # Clean up\n  kubectl delete service/modified \"${kube_flags[@]}\"\n  kubectl delete rc/modified \"${kube_flags[@]}\"\n\n  # Pre-condition: no services and no rcs exist\n  kube::test::get_object_assert service \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  EDITOR=${TEMP} kubectl create --edit -f hack/testdata/multi-resource-list.json \"${kube_flags[@]}\"\n  # Post-condition: service named modified and rc named modified are created\n  kube::test::get_object_assert service \"{{range.items}}{{$id_field}}:{{end}}\" 'modified:'\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'modified:'\n  # Clean up\n  rm \"${TEMP}\"\n  kubectl delete service/modified \"${kube_flags[@]}\"\n  kubectl delete rc/modified \"${kube_flags[@]}\"\n\n  ## kubectl create --edit won't create anything if user makes no changes\n  grep -q 'Edit cancelled' <<< \"$(EDITOR=\"cat\" kubectl create --edit -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml -o json 2>&1)\"\n\n  ## Create valid-pod POD\n  # Pre-condition: no POD exists\n  kube::test::wait_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ## Patch can modify a local object\n  kubectl patch --local -f test/fixtures/pkg/kubectl/cmd/patch/validPod.yaml --patch='{\"spec\": {\"restartPolicy\":\"Never\"}}' -o yaml | grep -q \"Never\"\n\n  ## Patch fails with type restore error and exit code 1\n  output_message=$(! kubectl patch \"${kube_flags[@]}\" pod valid-pod -p='{\"metadata\":{\"labels\":\"invalid\"}}' 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'cannot restore map from string'\n\n  ## Patch exits with error message \"patched (no change)\" and exit code 0 when no-op occurs\n  output_message=$(kubectl patch \"${kube_flags[@]}\" pod valid-pod -p='{\"metadata\":{\"labels\":{\"name\":\"valid-pod\"}}}' 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'patched (no change)'\n\n  ## Patch pod can change image\n  # Command\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod --record -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"nginx\"}]}}'\n  # Post-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{${image_field:?}}}:{{end}}\" 'nginx:'\n  # Post-condition: valid-pod has the record annotation\n  kube::test::get_object_assert pods \"{{range.items}}{{$annotations_field}}:{{end}}\" \"${change_cause_annotation:?}\"\n  # prove that patch can use different types\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod --type=\"json\" -p='[{\"op\": \"replace\", \"path\": \"/spec/containers/0/image\", \"value\":\"nginx2\"}]'\n  # Post-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'nginx2:'\n  # prove that patch can use different types\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod --type=\"json\" -p='[{\"op\": \"replace\", \"path\": \"/spec/containers/0/image\", \"value\":\"nginx\"}]'\n  # Post-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'nginx:'\n  # Dry-run change image\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod --record --dry-run=client -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"not-nginx\"}]}}'\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod --record --dry-run=server -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"not-nginx\"}]}}'\n  # Post-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'nginx:'\n  # prove that yaml input works too\n  YAML_PATCH=$'spec:\\n  containers:\\n  - name: kubernetes-serve-hostname\\n    image: changed-with-yaml\\n'\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod -p=\"${YAML_PATCH}\"\n  # Post-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'changed-with-yaml:'\n  ## Patch pod from JSON can change image\n  # Command\n  kubectl patch \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"k8s.gcr.io/pause:3.5\"}]}}'\n  # Post-condition: valid-pod POD has expected image\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'k8s.gcr.io/pause:3.5:'\n\n  # pod has field for kubectl patch field manager\n  output_message=$(kubectl get pod valid-pod -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-patch'\n\n  ## If resourceVersion is specified in the patch, it will be treated as a precondition, i.e., if the resourceVersion is different from that is stored in the server, the Patch should be rejected\n  ERROR_FILE=\"${KUBE_TEMP}/conflict-error\"\n  ## If the resourceVersion is the same as the one stored in the server, the patch will be applied.\n  # Command\n  # Needs to retry because other party may change the resource.\n  for count in {0..3}; do\n    resourceVersion=$(kubectl get \"${kube_flags[@]}\" pod valid-pod -o go-template='{{ .metadata.resourceVersion }}')\n    kubectl patch \"${kube_flags[@]}\" pod valid-pod -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"nginx\"}]},\"metadata\":{\"resourceVersion\":\"'\"${resourceVersion}\"'\"}}' 2> \"${ERROR_FILE}\" || true\n    if grep -q \"the object has been modified\" \"${ERROR_FILE}\"; then\n      kube::log::status \"retry $1, error: $(cat \"${ERROR_FILE}\")\"\n      rm \"${ERROR_FILE}\"\n      sleep $((2**count))\n    else\n      rm \"${ERROR_FILE}\"\n      kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'nginx:'\n      break\n    fi\n  done\n\n  ## If the resourceVersion is the different from the one stored in the server, the patch will be rejected.\n  resourceVersion=$(kubectl get \"${kube_flags[@]}\" pod valid-pod -o go-template='{{ .metadata.resourceVersion }}')\n  ((resourceVersion+=100))\n  # Command\n  kubectl patch \"${kube_flags[@]}\" pod valid-pod -p='{\"spec\":{\"containers\":[{\"name\": \"kubernetes-serve-hostname\", \"image\": \"nginx\"}]},\"metadata\":{\"resourceVersion\":\"'\"$resourceVersion\"'\"}}' 2> \"${ERROR_FILE}\" || true\n  # Post-condition: should get an error reporting the conflict\n  if grep -q \"please apply your changes to the latest version and try again\" \"${ERROR_FILE}\"; then\n    kube::log::status \"\\\"kubectl patch with resourceVersion $resourceVersion\\\" returns error as expected: $(cat \"${ERROR_FILE}\")\"\n  else\n    kube::log::status \"\\\"kubectl patch with resourceVersion $resourceVersion\\\" returns unexpected error or non-error: $(cat \"${ERROR_FILE}\")\"\n    exit 1\n  fi\n  rm \"${ERROR_FILE}\"\n\n  ## --force replace pod can change other field, e.g., spec.container.name\n  # Command\n  kubectl get \"${kube_flags[@]}\" pod valid-pod -o json | ${SED} 's/\"kubernetes-serve-hostname\"/\"replaced-k8s-serve-hostname\"/g' > /tmp/tmp-valid-pod.json\n  kubectl replace \"${kube_flags[@]}\" --force -f /tmp/tmp-valid-pod.json\n  # Post-condition: spec.container.name = \"replaced-k8s-serve-hostname\"\n  kube::test::get_object_assert 'pod valid-pod' \"{{(index .spec.containers 0).name}}\" 'replaced-k8s-serve-hostname'\n\n  # Pod has field manager for kubectl replace\n  output_message=$(kubectl get pod valid-pod -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-replace'\n\n  ## check replace --grace-period requires --force\n  output_message=$(! kubectl replace \"${kube_flags[@]}\" --grace-period=1 -f /tmp/tmp-valid-pod.json 2>&1)\n  kube::test::if_has_string \"${output_message}\" '\\-\\-grace-period must have \\-\\-force specified'\n\n  ## check replace --timeout requires --force\n  output_message=$(! kubectl replace \"${kube_flags[@]}\" --timeout=1s -f /tmp/tmp-valid-pod.json 2>&1)\n  kube::test::if_has_string \"${output_message}\" '\\-\\-timeout must have \\-\\-force specified'\n\n  #cleaning\n  rm /tmp/tmp-valid-pod.json\n\n  ## replace of a cluster scoped resource can succeed\n  # Pre-condition: a node exists\n  kubectl create -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Node\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"node-v1-test\"\n  }\n}\n__EOF__\n  kube::test::get_object_assert \"node node-v1-test\" \"{{range.items}}{{if .metadata.annotations.a}}found{{end}}{{end}}:\" ':'\n\n  # Dry-run command\n  kubectl replace --dry-run=server -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Node\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"node-v1-test\",\n    \"annotations\": {\"a\":\"b\"},\n    \"resourceVersion\": \"0\"\n  }\n}\n__EOF__\n  kubectl replace --dry-run=client -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Node\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"node-v1-test\",\n    \"annotations\": {\"a\":\"b\"},\n    \"resourceVersion\": \"0\"\n  }\n}\n__EOF__\n  kube::test::get_object_assert \"node node-v1-test\" \"{{range.items}}{{if .metadata.annotations.a}}found{{end}}{{end}}:\" ':'\n\n  # Command\n  kubectl replace -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Node\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"node-v1-test\",\n    \"annotations\": {\"a\":\"b\"},\n    \"resourceVersion\": \"0\"\n  }\n}\n__EOF__\n\n  # Post-condition: the node command succeeds\n  kube::test::get_object_assert \"node node-v1-test\" \"{{.metadata.annotations.a}}\" 'b'\n  kubectl delete node node-v1-test \"${kube_flags[@]}\"\n\n  ## kubectl edit can update the image field of a POD. tmp-editor.sh is a fake editor\n  echo -e \"#!/usr/bin/env bash\\n${SED} -i \\\"s/nginx/k8s.gcr.io\\/serve_hostname/g\\\" \\$1\" > /tmp/tmp-editor.sh\n  chmod +x /tmp/tmp-editor.sh\n  # Pre-condition: valid-pod POD has image nginx\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'nginx:'\n  grep -q 'Patch:' <<< \"$(EDITOR=/tmp/tmp-editor.sh kubectl edit \"${kube_flags[@]}\" pods/valid-pod --output-patch=true)\"\n  # Post-condition: valid-pod POD has image k8s.gcr.io/serve_hostname\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'k8s.gcr.io/serve_hostname:'\n  # pod has field for kubectl edit field manager\n  output_message=$(kubectl get pod valid-pod -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-edit'\n  # cleaning\n  rm /tmp/tmp-editor.sh\n\n  ## kubectl edit should work on Windows\n  grep -q 'Edit cancelled' <<< \"$(EDITOR=\"cat\" kubectl edit pod/valid-pod 2>&1)\"\n  grep -q 'name: valid-pod' <<< \"$(EDITOR=\"cat\" kubectl edit pod/valid-pod)\"\n  grep -q CRLF <<< \"$(EDITOR=\"cat\" kubectl edit --windows-line-endings pod/valid-pod | file - )\"\n  ! grep -q CRLF <<< \"$(EDITOR=\"cat\" kubectl edit --windows-line-endings=false pod/valid-pod | file - )\" || exit 1\n  grep -q 'kind: List' <<< \"$(EDITOR=\"cat\" kubectl edit ns)\"\n\n  ### Label POD YAML file locally without effecting the live pod.\n  # Pre-condition: name is valid-pod\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod'\n  # Command\n  output_message=$(kubectl label --local --overwrite -f hack/testdata/pod.yaml name=localonlyvalue -o yaml \"${kube_flags[@]}\")\n  echo \"$output_message\"\n  # Post-condition: name is still valid-pod in the live pod, but command output is the new value\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod'\n  kube::test::if_has_string \"${output_message}\" \"localonlyvalue\"\n\n  ### Overwriting an existing label is not permitted\n  # Pre-condition: name is valid-pod\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod'\n  # Command\n  ! kubectl label pods valid-pod name=valid-pod-super-sayan \"${kube_flags[@]}\" || exit 1\n  # Post-condition: name is still valid-pod\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod'\n\n  ### --overwrite must be used to overwrite existing label, can be applied to all resources\n  # Pre-condition: name is valid-pod\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod'\n  # Command\n  kubectl label --overwrite pods --all name=valid-pod-super-sayan \"${kube_flags[@]}\"\n  # Post-condition: name is valid-pod-super-sayan\n  kube::test::get_object_assert 'pod valid-pod' \"{{${labels_field}.name}}\" 'valid-pod-super-sayan'\n\n  ### Delete POD by label\n  # Pre-condition: valid-pod POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete pods -l'name in (valid-pod-super-sayan)' --grace-period=0 --force \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create two PODs from 1 yaml file\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: redis-master and valid-pod PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'redis-master:valid-pod:'\n\n  ### Delete two PODs from 1 yaml file\n  # Pre-condition: redis-master and valid-pod PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'redis-master:valid-pod:'\n  # Command\n  kubectl delete -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: no PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ## kubectl apply should update configuration annotations only if apply is already called\n  ## 1. kubectl create doesn't set the annotation\n  # Pre-Condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command: create a pod \"test-pod\"\n  kubectl create -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" is created\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field}.name}}\" 'test-pod-label'\n  # Post-Condition: pod \"test-pod\" doesn't have configuration annotation\n  ! grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" )\" || exit 1\n  ## 2. kubectl replace doesn't set the annotation\n  kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" | ${SED} 's/test-pod-label/test-pod-replaced/g' > \"${KUBE_TEMP}\"/test-pod-replace.yaml\n  # Command: replace the pod \"test-pod\"\n  kubectl replace -f \"${KUBE_TEMP}\"/test-pod-replace.yaml \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" is replaced\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field}.name}}\" 'test-pod-replaced'\n  # Post-Condition: pod \"test-pod\" doesn't have configuration annotation\n  ! grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\" || exit 1\n  ## 3. kubectl apply does set the annotation\n  # Command: apply the pod \"test-pod\"\n  kubectl apply -f hack/testdata/pod-apply.yaml \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" is applied\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field}.name}}\" 'test-pod-applied'\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\"\n  kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" | grep kubectl.kubernetes.io/last-applied-configuration > \"${KUBE_TEMP}\"/annotation-configuration\n  ## 4. kubectl replace updates an existing annotation\n  kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" | ${SED} 's/test-pod-applied/test-pod-replaced/g' > \"${KUBE_TEMP}\"/test-pod-replace.yaml\n  # Command: replace the pod \"test-pod\"\n  kubectl replace -f \"${KUBE_TEMP}\"/test-pod-replace.yaml \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" is replaced\n  kube::test::get_object_assert 'pods test-pod' \"{{${labels_field}.name}}\" 'test-pod-replaced'\n  # Post-Condition: pod \"test-pod\" has configuration annotation, and it's updated (different from the annotation when it's applied)\n  grep -q kubectl.kubernetes.io/last-applied-configuration <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" )\"\n  kubectl get pods test-pod -o yaml \"${kube_flags[@]}\" | grep kubectl.kubernetes.io/last-applied-configuration > \"${KUBE_TEMP}\"/annotation-configuration-replaced\n  ! [[ $(diff -q \"${KUBE_TEMP}\"/annotation-configuration \"${KUBE_TEMP}\"/annotation-configuration-replaced > /dev/null) ]] || exit 1\n  # Clean up\n  rm \"${KUBE_TEMP}\"/test-pod-replace.yaml \"${KUBE_TEMP}\"/annotation-configuration \"${KUBE_TEMP}\"/annotation-configuration-replaced\n  kubectl delete pods test-pod \"${kube_flags[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n\n# runs specific kubectl create tests\nrun_create_secret_tests() {\n    set -o nounset\n    set -o errexit\n\n    ### Create generic secret with explicit namespace\n    # Pre-condition: secret 'mysecret' does not exist\n    output_message=$(! kubectl get secrets mysecret 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" 'secrets \"mysecret\" not found'\n    # Command\n    output_message=$(kubectl create \"${kube_flags[@]}\" secret generic mysecret --dry-run=client --from-literal=foo=bar -o jsonpath='{.metadata.namespace}' --namespace=user-specified)\n    kube::test::if_has_string \"${output_message}\" 'user-specified'\n    # Post-condition: mysecret still not created since --dry-run was used\n    # Output from 'create' command should contain the specified --namespace value\n    failure_message=$(! kubectl get secrets mysecret 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${failure_message}\" 'secrets \"mysecret\" not found'\n    # Command\n    output_message=$(kubectl create \"${kube_flags[@]}\" secret generic mysecret --dry-run=client --from-literal=foo=bar -o jsonpath='{.metadata.namespace}')\n    # Post-condition: jsonpath for .metadata.namespace should be empty for object since --namespace was not explicitly specified\n    kube::test::if_empty_string \"${output_message}\"\n\n\n    # check to make sure that replace correctly PUTs to a URL\n    kubectl create configmap tester-update-cm -o json --dry-run=client | kubectl create \"${kube_flags[@]}\" --raw /api/v1/namespaces/default/configmaps -f -\n    output_message=$(kubectl create configmap tester-update-cm --from-literal=key1=config1 -o json --dry-run=client | kubectl replace \"${kube_flags[@]}\" --raw /api/v1/namespaces/default/configmaps/tester-update-cm -f -)\n    # the message should show the body returned which will include a UID not present in the input\n    kube::test::if_has_string \"${output_message}\" 'uid'\n    # if the PUT was well-formed, the server will now have a key and value we can retrieve on GET\n    output_message=$(kubectl get \"${kube_flags[@]}\" --raw /api/v1/namespaces/default/configmaps/tester-update-cm 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" 'config1'\n\n    # if DELETE raw works correctly, this will delete the configmap\n    kubectl delete \"${kube_flags[@]}\" --raw /api/v1/namespaces/default/configmaps/tester-update-cm\n    output_message=$(! kubectl get \"${kube_flags[@]}\" configmap tester-update-cm 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" 'configmaps \"tester-update-cm\" not found'\n\n    set +o nounset\n    set +o errexit\n}\n\nrun_secrets_test() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing secrets\"\n\n  # Ensure dry run succeeds and includes kind, apiVersion and data, and doesn't require a server connection\n  output_message=$(kubectl create secret generic test --from-literal=key1=value1 --dry-run=client -o yaml --server=example.com --v=6)\n  kube::test::if_has_string \"${output_message}\" 'kind: Secret'\n  kube::test::if_has_string \"${output_message}\" 'apiVersion: v1'\n  kube::test::if_has_string \"${output_message}\" 'key1: dmFsdWUx'\n  kube::test::if_has_not_string \"${output_message}\" 'example.com'\n\n  ### Create a new namespace\n  # Pre-condition: the test-secrets namespace does not exist\n  kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-secrets\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create namespace test-secrets\n  # Post-condition: namespace 'test-secrets' is created.\n  kube::test::get_object_assert 'namespaces/test-secrets' \"{{$id_field}}\" 'test-secrets'\n\n  ### Create a generic secret in a specific namespace\n  # Pre-condition: no SECRET exists\n  kube::test::get_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create secret generic test-secret --from-literal=key1=value1 --type=test-type --namespace=test-secrets\n  # Post-condition: secret exists and has expected values\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$secret_type}}\" 'test-type'\n  grep -q 'key1: dmFsdWUx' <<< \"$(kubectl get secret/test-secret --namespace=test-secrets -o yaml \"${kube_flags[@]}\")\"\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert secrets \"\"  \"--namespace=test-secrets\"\n  # Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n\n  ### Create a docker-registry secret in a specific namespace\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  fi\n  # Pre-condition: no SECRET exists\n  kube::test::get_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create secret docker-registry test-secret --docker-username=test-user --docker-password=test-password --docker-email='test-user@test.com' --namespace=test-secrets\n  # Post-condition: secret exists and has expected values\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$secret_type}}\" 'kubernetes.io/dockerconfigjson'\n  grep -q '.dockerconfigjson: eyJhdXRocyI6eyJodHRwczovL2luZGV4LmRvY2tlci5pby92MS8iOnsidXNlcm5hbWUiOiJ0ZXN0LXVzZXIiLCJwYXNzd29yZCI6InRlc3QtcGFzc3dvcmQiLCJlbWFpbCI6InRlc3QtdXNlckB0ZXN0LmNvbSIsImF1dGgiOiJkR1Z6ZEMxMWMyVnlPblJsYzNRdGNHRnpjM2R2Y21RPSJ9fX0=' <<< \"$(kubectl get secret/test-secret --namespace=test-secrets -o yaml \"${kube_flags[@]}\")\"\n  # Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n\n  ### Create a docker-registry secret in a specific namespace with docker config file\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  fi\n  # Pre-condition: no SECRET exists\n  kube::test::get_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create secret docker-registry test-secret --from-file=.dockerconfigjson=hack/testdata/dockerconfig.json --namespace=test-secrets\n  # Post-condition: secret exists and has expected values\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$secret_type}}\" 'kubernetes.io/dockerconfigjson'\n  grep -q '.dockerconfigjson: ewogICAgImF1dGhzIjp7CiAgICAgICAgImh0dHA6Ly9mb28uZXhhbXBsZS5jb20iOnsKICAgICAgICAgICAgInVzZXJuYW1lIjoiZm9vIiwKICAgICAgICAgICAgInBhc3N3b3JkIjoiYmFyIiwKICAgICAgICAgICAgImVtYWlsIjoiZm9vQGV4YW1wbGUuY29tIgogICAgICAgIH0sCiAgICAgICAgImh0dHA6Ly9iYXIuZXhhbXBsZS5jb20iOnsKICAgICAgICAgICAgInVzZXJuYW1lIjoiYmFyIiwKICAgICAgICAgICAgInBhc3N3b3JkIjoiYmF6IiwKICAgICAgICAgICAgImVtYWlsIjoiYmFyQGV4YW1wbGUuY29tIgogICAgICAgIH0KICAgIH0KfQo=' <<< \"$(kubectl get secret/test-secret --namespace=test-secrets -o yaml \"${kube_flags[@]}\")\"\n  # Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n\n  ### Create a tls secret\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  fi\n  # Pre-condition: no SECRET exists\n  kube::test::get_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create secret tls test-secret --namespace=test-secrets --key=hack/testdata/tls.key --cert=hack/testdata/tls.crt\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$secret_type}}\" 'kubernetes.io/tls'\n  # Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n\n  # Command with process substitution\n  kubectl create secret tls test-secret --namespace=test-secrets --key <(cat hack/testdata/tls.key) --cert <(cat hack/testdata/tls.crt)\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$id_field}}\" 'test-secret'\n  kube::test::get_object_assert 'secret/test-secret --namespace=test-secrets' \"{{$secret_type}}\" 'kubernetes.io/tls'\n    # Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n\n  # Create a secret using stringData\n  kubectl create --namespace=test-secrets -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Secret\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"secret-string-data\"\n  },\n  \"data\": {\n    \"k1\":\"djE=\",\n    \"k2\":\"\"\n  },\n  \"stringData\": {\n    \"k2\":\"v2\"\n  }\n}\n__EOF__\n  # Post-condition: secret-string-data secret is created with expected data, merged/overridden data from stringData, and a cleared stringData field\n  kube::test::get_object_assert 'secret/secret-string-data --namespace=test-secrets ' '{{.data}}' '.*k1:djE=.*'\n  kube::test::get_object_assert 'secret/secret-string-data --namespace=test-secrets ' '{{.data}}' '.*k2:djI=.*'\n  kube::test::get_object_assert 'secret/secret-string-data --namespace=test-secrets ' '{{.stringData}}' '<no value>'\n  # Clean up\n  kubectl delete secret secret-string-data --namespace=test-secrets\n\n  ### Create a secret using output flags\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  fi\n  # Pre-condition: no secret exists\n  kube::test::get_object_assert 'secrets --namespace=test-secrets' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  grep -q 'test-secret:' <<< \"$(kubectl create secret generic test-secret --namespace=test-secrets --from-literal=key1=value1 --output=go-template --template=\"{{.metadata.name}}:\")\"\n  ## Clean-up\n  kubectl delete secret test-secret --namespace=test-secrets\n  # Clean up\n  kubectl delete namespace test-secrets\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_service_accounts_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing service accounts\"\n\n  ### Create a new namespace\n  # Pre-condition: the test-service-accounts namespace does not exist\n  kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-service-accounts\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create namespace test-service-accounts\n  # Post-condition: namespace 'test-service-accounts' is created.\n  kube::test::get_object_assert 'namespaces/test-service-accounts' \"{{$id_field}}\" 'test-service-accounts'\n\n  ### Create a service account in a specific namespace\n  # Pre-condition: service account does not exist\n  kube::test::get_object_assert 'serviceaccount --namespace=test-service-accounts' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-service-account\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run command\n  kubectl create serviceaccount test-service-account --dry-run=client --namespace=test-service-accounts\n  kubectl create serviceaccount test-service-account --dry-run=server --namespace=test-service-accounts\n  kube::test::get_object_assert 'serviceaccount --namespace=test-service-accounts' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-service-account\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create serviceaccount test-service-account --namespace=test-service-accounts\n  # Post-condition: secret exists and has expected values\n  kube::test::get_object_assert 'serviceaccount/test-service-account --namespace=test-service-accounts' \"{{$id_field}}\" 'test-service-account'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert serviceaccounts secrets,events \"--namespace=test-service-accounts\"\n  # Clean-up\n  kubectl delete serviceaccount test-service-account --namespace=test-service-accounts\n  # Clean up\n  kubectl delete namespace test-service-accounts\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_service_tests() {\n  set -o nounset\n  set -o errexit\n\n  # switch back to the default namespace\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"\"\n  kube::log::status \"Testing kubectl(v1:services)\"\n\n  ### Create redis-master service from JSON\n  # Pre-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Command\n  kubectl create -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml \"${kube_flags[@]}\"\n  # Post-condition: redis-master service exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:'\n  # Describe command should print detailed information\n  kube::test::describe_object_assert services 'redis-master' \"Name:\" \"Labels:\" \"Selector:\" \"IP:\" \"Port:\" \"Endpoints:\" \"Session Affinity:\"\n  # Describe command should print events information by default\n  kube::test::describe_object_events_assert services 'redis-master'\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_object_events_assert services 'redis-master' false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_object_events_assert services 'redis-master' true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert services \"Name:\" \"Labels:\" \"Selector:\" \"IP:\" \"Port:\" \"Endpoints:\" \"Session Affinity:\"\n  # Describe command should print events information by default\n  kube::test::describe_resource_events_assert services\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_resource_events_assert services false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_resource_events_assert services true\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert services events\n\n  ### set selector\n  # prove role=master\n  kube::test::get_object_assert 'services redis-master' \"{{range${service_selector_field:?}}}{{.}}:{{end}}\" \"redis:master:backend:\"\n\n  # Set selector of a local file without talking to the server\n  kubectl set selector -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml role=padawan --local -o yaml \"${kube_flags[@]}\"\n  kubectl set selector -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml role=padawan --dry-run=client -o yaml \"${kube_flags[@]}\"\n  # Set command to change the selector.\n  kubectl set selector -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml role=padawan\n  # prove role=padawan\n  kube::test::get_object_assert 'services redis-master' \"{{range$service_selector_field}}{{.}}:{{end}}\" \"padawan:\"\n  # Set command to reset the selector back to the original one.\n  kubectl set selector -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml app=redis,role=master,tier=backend\n  # prove role=master\n  kube::test::get_object_assert 'services redis-master' \"{{range$service_selector_field}}{{.}}:{{end}}\" \"redis:master:backend:\"\n  # Show dry-run works on running selector\n  kubectl set selector services redis-master role=padawan --dry-run=client -o yaml \"${kube_flags[@]}\"\n  kubectl set selector services redis-master role=padawan --dry-run=server -o yaml \"${kube_flags[@]}\"\n  output_message=$(kubectl get services redis-master --show-managed-fields -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-set'\n  ! kubectl set selector services redis-master role=padawan --local -o yaml \"${kube_flags[@]}\" || exit 1\n  kube::test::get_object_assert 'services redis-master' \"{{range$service_selector_field}}{{.}}:{{end}}\" \"redis:master:backend:\"\n  # --resource-version=<current-resource-version> succeeds\n  rv=$(kubectl get services redis-master -o jsonpath='{.metadata.resourceVersion}' \"${kube_flags[@]}\")\n  kubectl set selector services redis-master rvtest1=true \"--resource-version=${rv}\" \"${kube_flags[@]}\"\n  # --resource-version=<non-current-resource-version> fails\n  output_message=$(! kubectl set selector services redis-master rvtest1=true --resource-version=1 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'Conflict'\n\n  ### Dump current redis-master service\n  output_service=$(kubectl get service redis-master -o json \"${kube_flags[@]}\")\n\n  ### Delete redis-master-service by id\n  # Pre-condition: redis-master service exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:'\n  # Command\n  kubectl delete service redis-master \"${kube_flags[@]}\"\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  fi\n  # Post-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n\n  ### Create redis-master-service from dumped JSON\n  # Pre-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Command\n  echo \"${output_service}\" | kubectl create -f - \"${kube_flags[@]}\"\n  # Post-condition: redis-master service is created\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:'\n\n  ### Create redis-master-v1-test service\n  # Pre-condition: redis-master-service service exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:'\n  # Command\n  kubectl create -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Service\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"service-v1-test\"\n  },\n  \"spec\": {\n    \"ports\": [\n      {\n        \"protocol\": \"TCP\",\n        \"port\": 80,\n        \"targetPort\": 80\n      }\n    ]\n  }\n}\n__EOF__\n  # Post-condition: service-v1-test service is created\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:service-.*-test:'\n\n  ### Identity\n  kubectl get service \"${kube_flags[@]}\" service-v1-test -o json | kubectl replace \"${kube_flags[@]}\" -f -\n\n  ### Delete services by id\n  # Pre-condition: service-v1-test exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:service-.*-test:'\n  # Command\n  kubectl delete service redis-master \"${kube_flags[@]}\"\n  kubectl delete service \"service-v1-test\" \"${kube_flags[@]}\"\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  fi\n  # Post-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n\n  ### Create two services\n  # Pre-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Command\n  kubectl create -f test/e2e/testing-manifests/guestbook/redis-master-service.yaml \"${kube_flags[@]}\"\n  kubectl create -f test/e2e/testing-manifests/guestbook/redis-slave-service.yaml \"${kube_flags[@]}\"\n  # Post-condition: redis-master and redis-slave services are created\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:redis-slave:'\n\n  ### Custom columns can be specified\n  # Pre-condition: generate output using custom columns\n  output_message=$(kubectl get services -o=custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: should contain name column\n  kube::test::if_has_string \"${output_message}\" 'redis-master'\n\n  ### Delete multiple services at once\n  # Pre-condition: redis-master and redis-slave services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:redis-master:redis-slave:'\n  # Command\n  kubectl delete services redis-master redis-slave \"${kube_flags[@]}\" # delete multiple services at once\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  fi\n  # Post-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n\n  ### Create an ExternalName service\n  # Pre-condition: Only the default kubernetes service exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Dry-run command\n  kubectl create service externalname beep-boop --dry-run=client --external-name bar.com\n  kubectl create service externalname beep-boop --dry-run=server --external-name bar.com\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Command\n  kubectl create service externalname beep-boop --external-name bar.com\n  # Post-condition: beep-boop service is created\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'beep-boop:kubernetes:'\n\n  ### Delete beep-boop service by id\n  # Pre-condition: beep-boop service exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'beep-boop:kubernetes:'\n  # Command\n  kubectl delete service beep-boop \"${kube_flags[@]}\"\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  fi\n  # Post-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n\n  ### Create pod and service\n  # Pre-condition: no pod exists\n  kube::test::wait_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Pre-condition: Only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Dry-run command\n  kubectl run testmetadata --image=nginx --port=80 --expose --dry-run=client\n  kubectl run testmetadata --image=nginx --port=80 --expose --dry-run=server\n  # Check only the default kubernetes services exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  # Command\n  kubectl run testmetadata --image=nginx --port=80 --expose\n  # Check result\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'testmetadata:'\n  kube::test::get_object_assert 'service testmetadata' \"{{${port_field:?}}}\" '80'\n  # pod has field for kubectl run field manager\n  output_message=$(kubectl get pod testmetadata -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-run'\n\n  ### Expose pod as a new service\n  # Command\n  kubectl expose pod testmetadata  --port=1000 --target-port=80 --type=NodePort --name=exposemetadata --overrides='{ \"metadata\": { \"annotations\": { \"zone-context\": \"work\" } } } '\n  # Check result\n  kube::test::get_object_assert 'service exposemetadata' \"{{.metadata.annotations}}\" \"map\\[zone-context:work\\]\"\n  # Service has field manager for kubectl expose\n  output_message=$(kubectl get service exposemetadata -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-expose'\n\n  # Clean-Up\n  # Command\n  kubectl delete service exposemetadata testmetadata \"${kube_flags[@]}\"\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'kubernetes:'\n  fi\n  kubectl delete pod testmetadata \"${kube_flags[@]}\"\n  if [[ \"${WAIT_FOR_DELETION:-}\" == \"true\" ]]; then\n    kube::test::wait_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_rc_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:replicationcontrollers)\"\n\n  ### Create and stop controller, make sure it doesn't leak pods\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  kubectl delete rc frontend \"${kube_flags[@]}\"\n  # Post-condition: no pods from frontend controller\n  kube::test::wait_object_assert 'pods -l \"name=frontend\"' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create replication controller frontend from JSON\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  # Post-condition: frontend replication controller is created\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'frontend:'\n  # Describe command should print detailed information\n  kube::test::describe_object_assert rc 'frontend' \"Name:\" \"Pod Template:\" \"Labels:\" \"Selector:\" \"Replicas:\" \"Pods Status:\" \"Volumes:\" \"GET_HOSTS_FROM:\"\n  # Describe command should print events information by default\n  kube::test::describe_object_events_assert rc 'frontend'\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_object_events_assert rc 'frontend' false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_object_events_assert rc 'frontend' true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert rc \"Name:\" \"Name:\" \"Pod Template:\" \"Labels:\" \"Selector:\" \"Replicas:\" \"Pods Status:\" \"Volumes:\" \"GET_HOSTS_FROM:\"\n  # Describe command should print events information by default\n  kube::test::describe_resource_events_assert rc\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_resource_events_assert rc false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_resource_events_assert rc true\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert replicationcontrollers events\n\n  ### Scale replication controller frontend with current-replicas and replicas\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{${rc_replicas_field:?}}}\" '3'\n  # Command\n  kubectl scale --current-replicas=3 --replicas=2 replicationcontrollers frontend \"${kube_flags[@]}\"\n  # Post-condition: 2 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '2'\n\n  ### Scale replication controller frontend with (wrong) current-replicas and replicas\n  # Pre-condition: 2 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '2'\n  # Command\n  ! kubectl scale --current-replicas=3 --replicas=2 replicationcontrollers frontend \"${kube_flags[@]}\" || exit 1\n  # Post-condition: nothing changed\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '2'\n\n  ### Scale replication controller frontend with replicas only\n  # Pre-condition: 2 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '2'\n  # Command\n  kubectl scale  --replicas=3 replicationcontrollers frontend \"${kube_flags[@]}\"\n  # Post-condition: 3 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '3'\n\n  ### Scale replication controller from JSON with replicas only\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '3'\n  # Command\n  kubectl scale  --replicas=2 -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  # Post-condition: 2 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '2'\n  # Clean-up\n  kubectl delete rc frontend \"${kube_flags[@]}\"\n\n  ### Scale multiple replication controllers\n  kubectl create -f test/e2e/testing-manifests/guestbook/legacy/redis-master-controller.yaml \"${kube_flags[@]}\"\n  kubectl create -f test/e2e/testing-manifests/guestbook/legacy/redis-slave-controller.yaml \"${kube_flags[@]}\"\n  # Command\n  kubectl scale rc/redis-master rc/redis-slave --replicas=4 \"${kube_flags[@]}\"\n  # Post-condition: 4 replicas each\n  kube::test::get_object_assert 'rc redis-master' \"{{$rc_replicas_field}}\" '4'\n  kube::test::get_object_assert 'rc redis-slave' \"{{$rc_replicas_field}}\" '4'\n  # Clean-up\n  kubectl delete rc redis-{master,slave} \"${kube_flags[@]}\"\n\n  ### Scale a deployment\n  kubectl create -f test/fixtures/doc-yaml/user-guide/deployment.yaml \"${kube_flags[@]}\"\n  # Command\n  kubectl scale --current-replicas=3 --replicas=1 deployment/nginx-deployment\n  # Post-condition: 1 replica for nginx-deployment\n  kube::test::get_object_assert 'deployment nginx-deployment' \"{{${deployment_replicas:?}}}\" '1'\n  # Clean-up\n  kubectl delete deployment/nginx-deployment \"${kube_flags[@]}\"\n\n  ### Expose deployments by creating a service\n  # Uses deployment selectors for created service\n  output_message=$(kubectl expose -f test/fixtures/pkg/kubectl/cmd/expose/appsv1deployment.yaml --port 80 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: service created for deployment.\n  kube::test::if_has_string \"${output_message}\" 'service/expose-test-deployment exposed'\n  # Clean-up\n  kubectl delete service/expose-test-deployment \"${kube_flags[@]}\"\n  # Contains no selectors, should fail.\n  output_message=$(! kubectl expose -f test/fixtures/pkg/kubectl/cmd/expose/appsv1deployment-no-selectors.yaml --port 80 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: service created for deployment.\n  kube::test::if_has_string \"${output_message}\" 'invalid deployment: no selectors'\n\n  ### Expose a deployment as a service\n  kubectl create -f test/fixtures/doc-yaml/user-guide/deployment.yaml \"${kube_flags[@]}\"\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'deployment nginx-deployment' \"{{$deployment_replicas}}\" '3'\n  # Command\n  kubectl expose deployment/nginx-deployment\n  # Post-condition: service exists and exposes deployment port (80)\n  kube::test::get_object_assert 'service nginx-deployment' \"{{${port_field:?}}}\" '80'\n  # Clean-up\n  kubectl delete deployment/nginx-deployment service/nginx-deployment \"${kube_flags[@]}\"\n\n  ### Expose replication controller as service\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  # Pre-condition: 3 replicas\n  kube::test::get_object_assert 'rc frontend' \"{{$rc_replicas_field}}\" '3'\n  # Command\n  kubectl expose rc frontend --port=80 \"${kube_flags[@]}\"\n  # Post-condition: service exists and the port is unnamed\n  kube::test::get_object_assert 'service frontend' \"{{${port_name:?}}} {{$port_field}}\" '<no value> 80'\n  # Command\n  kubectl expose service frontend --port=443 --name=frontend-2 \"${kube_flags[@]}\"\n  # Post-condition: service exists and the port is unnamed\n  kube::test::get_object_assert 'service frontend-2' \"{{$port_name}} {{$port_field}}\" '<no value> 443'\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  kubectl expose pod valid-pod --port=444 --name=frontend-3 \"${kube_flags[@]}\"\n  # Post-condition: service exists and the port is unnamed\n  kube::test::get_object_assert 'service frontend-3' \"{{$port_name}} {{$port_field}}\" '<no value> 444'\n  # Verify that expose service works without specifying a port.\n  kubectl expose service frontend --name=frontend-4 \"${kube_flags[@]}\"\n  # Post-condition: service exists with the same port as the original service.\n  kube::test::get_object_assert 'service frontend-4' \"{{$port_field}}\" '80'\n  # Cleanup services\n  kubectl delete pod valid-pod \"${kube_flags[@]}\"\n  kubectl delete service frontend{,-2,-3,-4} \"${kube_flags[@]}\"\n\n  ### Expose negative invalid resource test\n  # Pre-condition: don't need\n  # Command\n  output_message=$(! kubectl expose nodes 127.0.0.1 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: the error message has \"cannot expose\" string\n  kube::test::if_has_string \"${output_message}\" 'cannot expose'\n\n  ### Try to generate a service with invalid name (exceeding maximum valid size)\n  # Pre-condition: use --name flag\n  output_message=$(! kubectl expose -f hack/testdata/pod-with-large-name.yaml --name=invalid-large-service-name-that-has-more-than-sixty-three-characters --port=8081 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: should fail due to invalid name\n  kube::test::if_has_string \"${output_message}\" 'metadata.name: Invalid value'\n  # Pre-condition: default run without --name flag; should succeed by truncating the inherited name\n  output_message=$(kubectl expose -f hack/testdata/pod-with-large-name.yaml --port=8081 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: inherited name from pod has been truncated\n  kube::test::if_has_string \"${output_message}\" 'kubernetes-serve-hostname-testing-sixty-three-characters-in-len exposed'\n  # Clean-up\n  kubectl delete svc kubernetes-serve-hostname-testing-sixty-three-characters-in-len \"${kube_flags[@]}\"\n\n  ### Expose multiport object as a new service\n  # Pre-condition: don't use --port flag\n  output_message=$(kubectl expose -f test/fixtures/doc-yaml/admin/high-availability/etcd.yaml --selector=test=etcd 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: expose succeeded\n  kube::test::if_has_string \"${output_message}\" 'etcd-server exposed'\n  # Post-condition: generated service has both ports from the exposed pod\n  kube::test::get_object_assert 'service etcd-server' \"{{$port_name}} {{$port_field}}\" 'port-1 2380'\n  kube::test::get_object_assert 'service etcd-server' \"{{${second_port_name:?}}} {{${second_port_field:?}}}\" 'port-2 2379'\n  # Clean-up\n  kubectl delete svc etcd-server \"${kube_flags[@]}\"\n\n  ### Delete replication controller with id\n  # Pre-condition: frontend replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'frontend:'\n  # Command\n  kubectl delete rc frontend \"${kube_flags[@]}\"\n  # Post-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Create two replication controllers\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  kubectl create -f test/e2e/testing-manifests/guestbook/legacy/redis-slave-controller.yaml \"${kube_flags[@]}\"\n  # Post-condition: frontend and redis-slave\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'frontend:redis-slave:'\n\n  ### Delete multiple controllers at once\n  # Pre-condition: frontend and redis-slave\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'frontend:redis-slave:'\n  # Command\n  kubectl delete rc frontend redis-slave \"${kube_flags[@]}\" # delete multiple controllers at once\n  # Post-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Auto scale replication controller\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'frontend:'\n  # autoscale 1~2 pods, CPU utilization 70%, rc specified by file\n  kubectl autoscale -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\" --max=2 --cpu-percent=70\n  kube::test::get_object_assert 'hpa frontend' \"{{${hpa_min_field:?}}} {{${hpa_max_field:?}}} {{${hpa_cpu_field:?}}}\" '1 2 70'\n  kubectl delete hpa frontend \"${kube_flags[@]}\"\n  # autoscale 2~3 pods, no CPU utilization specified, rc specified by name\n  kubectl autoscale rc frontend \"${kube_flags[@]}\" --min=2 --max=3\n  kube::test::get_object_assert 'hpa frontend' \"{{$hpa_min_field}} {{$hpa_max_field}} {{$hpa_cpu_field}}\" '2 3 80'\n  kubectl delete hpa frontend \"${kube_flags[@]}\"\n  # autoscale without specifying --max should fail\n  ! kubectl autoscale rc frontend \"${kube_flags[@]}\" || exit 1\n  # Clean up\n  kubectl delete rc frontend \"${kube_flags[@]}\"\n\n  ## Set resource limits/request of a deployment\n  # Pre-condition: no deployment exists\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Set resources of a local file without talking to the server\n  kubectl set resources -f hack/testdata/deployment-multicontainer-resources.yaml -c=perl --limits=cpu=300m --requests=cpu=300m --local -o yaml \"${kube_flags[@]}\"\n  ! kubectl set resources -f hack/testdata/deployment-multicontainer-resources.yaml -c=perl --limits=cpu=300m --requests=cpu=300m --dry-run=client -o yaml \"${kube_flags[@]}\" || exit 1\n  # Create a deployment\n  kubectl create -f hack/testdata/deployment-multicontainer-resources.yaml \"${kube_flags[@]}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" 'nginx-deployment-resources:'\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_DEPLOYMENT_R1}:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field1:?}}}:{{end}}\" \"${IMAGE_PERL}:\"\n  # Set the deployment's cpu limits\n  kubectl set resources deployment nginx-deployment-resources --limits=cpu=100m \"${kube_flags[@]}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 0).resources.limits.cpu}}:{{end}}\" \"100m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.limits.cpu}}:{{end}}\" \"100m:\"\n  # Set a non-existing container should fail\n  ! kubectl set resources deployment nginx-deployment-resources -c=redis --limits=cpu=100m || exit 1\n  # Set the limit of a specific container in deployment\n  kubectl set resources deployment nginx-deployment-resources -c=nginx --limits=cpu=200m \"${kube_flags[@]}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 0).resources.limits.cpu}}:{{end}}\" \"200m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.limits.cpu}}:{{end}}\" \"100m:\"\n  # Set limits/requests of a deployment specified by a file\n  kubectl set resources -f hack/testdata/deployment-multicontainer-resources.yaml -c=perl --limits=cpu=300m --requests=cpu=300m \"${kube_flags[@]}\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 0).resources.limits.cpu}}:{{end}}\" \"200m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.limits.cpu}}:{{end}}\" \"300m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.requests.cpu}}:{{end}}\" \"300m:\"\n  # Show dry-run works on running deployments\n  kubectl set resources deployment nginx-deployment-resources -c=perl --limits=cpu=400m --requests=cpu=400m --dry-run=client -o yaml \"${kube_flags[@]}\"\n  kubectl set resources deployment nginx-deployment-resources -c=perl --limits=cpu=400m --requests=cpu=400m --dry-run=server -o yaml \"${kube_flags[@]}\"\n  ! kubectl set resources deployment nginx-deployment-resources -c=perl --limits=cpu=400m --requests=cpu=400m --local -o yaml \"${kube_flags[@]}\" || exit 1\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 0).resources.limits.cpu}}:{{end}}\" \"200m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.limits.cpu}}:{{end}}\" \"300m:\"\n  kube::test::get_object_assert deployment \"{{range.items}}{{(index .spec.template.spec.containers 1).resources.requests.cpu}}:{{end}}\" \"300m:\"\n  # Clean up\n  kubectl delete deployment nginx-deployment-resources \"${kube_flags[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_namespace_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl(v1:namespaces)\"\n  ### Create a new namespace\n  # Pre-condition: test namespace does not exist\n  output_message=$(! kubectl get ns/my-namespace 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" ' not found'\n  # Dry-run command\n  kubectl create namespace my-namespace --dry-run=client\n  kubectl create namespace my-namespace --dry-run=server\n  output_message=$(! kubectl get ns/my-namespace 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" ' not found'\n  # Command\n  kubectl create namespace my-namespace\n  # Post-condition: namespace 'my-namespace' is created.\n  kube::test::get_object_assert 'namespaces/my-namespace' \"{{$id_field}}\" 'my-namespace'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert namespaces resourcequotas,limitranges\n  # Clean up\n  kubectl delete namespace my-namespace --wait=false\n  # make sure that wait properly waits for finalization\n  kubectl wait --for=delete ns/my-namespace\n  output_message=$(! kubectl get ns/my-namespace 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" ' not found'\n\n  kubectl create namespace my-namespace\n  kube::test::get_object_assert 'namespaces/my-namespace' \"{{$id_field}}\" 'my-namespace'\n  output_message=$(! kubectl delete namespace -n my-namespace --all 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'warning: deleting cluster-scoped resources'\n  kube::test::if_has_string \"${output_message}\" 'namespace \"my-namespace\" deleted'\n\n  ### Quota\n  kubectl create namespace quotas\n  kube::test::get_object_assert 'namespaces/quotas' \"{{$id_field}}\" 'quotas'\n  kube::test::get_object_assert 'quota --namespace=quotas' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-quota\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Dry-run command\n  kubectl create quota test-quota --dry-run=client --namespace=quotas\n  kubectl create quota test-quota --dry-run=server --namespace=quotas\n  kube::test::get_object_assert 'quota --namespace=quotas' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-quota\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  # Command\n  kubectl create quota test-quota --namespace=quotas\n  kube::test::get_object_assert 'quota --namespace=quotas' \"{{range.items}}{{ if eq $id_field \\\\\\\"test-quota\\\\\\\" }}found{{end}}{{end}}:\" 'found:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert resourcequotas \"\" \"--namespace=quotas\"\n  # Clean up\n  kubectl delete quota test-quota --namespace=quotas\n  kubectl delete namespace quotas\n\n  ######################\n  # Pods in Namespaces #\n  ######################\n\n  if kube::test::if_supports_resource \"${pods:?}\" ; then\n    ### Create a new namespace\n    # Pre-condition: the other namespace does not exist\n    kube::test::get_object_assert 'namespaces' \"{{range.items}}{{ if eq $id_field \\\\\\\"other\\\\\\\" }}found{{end}}{{end}}:\" ':'\n    # Command\n    kubectl create namespace other\n    # Post-condition: namespace 'other' is created.\n    kube::test::get_object_assert 'namespaces/other' \"{{$id_field}}\" 'other'\n\n    ### Create POD valid-pod in specific namespace\n    # Pre-condition: no POD exists\n    kube::test::get_object_assert 'pods --namespace=other' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    # Command\n    kubectl create \"${kube_flags[@]}\" --namespace=other -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n    # Post-condition: valid-pod POD is created\n    kube::test::get_object_assert 'pods --namespace=other' \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n    # Post-condition: verify shorthand `-n other` has the same results as `--namespace=other`\n    kube::test::get_object_assert 'pods -n other' \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n    # Post-condition: a resource cannot be retrieved by name across all namespaces\n    output_message=$(! kubectl get \"${kube_flags[@]}\" pod valid-pod --all-namespaces 2>&1)\n    kube::test::if_has_string \"${output_message}\" \"a resource cannot be retrieved by name across all namespaces\"\n\n    ### Delete POD valid-pod in specific namespace\n    # Pre-condition: valid-pod POD exists\n    kube::test::get_object_assert 'pods --namespace=other' \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n    # Command\n    kubectl delete \"${kube_flags[@]}\" pod --namespace=other valid-pod --grace-period=0 --force\n    # Post-condition: valid-pod POD doesn't exist\n    kube::test::get_object_assert 'pods --namespace=other' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    # Clean up\n    kubectl delete namespace other\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_nodes_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl(v1:nodes)\"\n\n  kube::test::get_object_assert nodes \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:'\n\n  kube::test::describe_object_assert nodes \"127.0.0.1\" \"Name:\" \"Labels:\" \"CreationTimestamp:\" \"Conditions:\" \"Addresses:\" \"Capacity:\" \"Pods:\"\n  # Describe command should print events information by default\n  kube::test::describe_object_events_assert nodes \"127.0.0.1\"\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_object_events_assert nodes \"127.0.0.1\" false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_object_events_assert nodes \"127.0.0.1\" true\n  # Describe command (resource only) should print detailed information\n  kube::test::describe_resource_assert nodes \"Name:\" \"Labels:\" \"CreationTimestamp:\" \"Conditions:\" \"Addresses:\" \"Capacity:\" \"Pods:\"\n  # Describe command should print events information by default\n  kube::test::describe_resource_events_assert nodes\n  # Describe command should not print events information when show-events=false\n  kube::test::describe_resource_events_assert nodes false\n  # Describe command should print events information when show-events=true\n  kube::test::describe_resource_events_assert nodes true\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert nodes pods,events\n\n  ### kubectl patch update can mark node unschedulable\n  # Pre-condition: node is schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n  kubectl patch \"${kube_flags[@]}\" nodes \"127.0.0.1\" -p='{\"spec\":{\"unschedulable\":true}}'\n  # Post-condition: node is unschedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" 'true'\n  kubectl patch \"${kube_flags[@]}\" nodes \"127.0.0.1\" -p='{\"spec\":{\"unschedulable\":null}}'\n  # Post-condition: node is schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n  # check webhook token authentication endpoint, kubectl doesn't actually display the returned object so this isn't super useful\n  # but it proves that works\n  kubectl create -f test/fixtures/pkg/kubectl/cmd/create/tokenreview-v1.json --validate=false\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_pod_templates_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing pod templates\"\n\n  ### Create PODTEMPLATE\n  # Pre-condition: no PODTEMPLATE\n  kube::test::get_object_assert podtemplates \"{{range.items}}{{.metadata.name}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/walkthrough/podtemplate.json \"${kube_flags[@]}\"\n  # Post-condition: nginx PODTEMPLATE is available\n  kube::test::get_object_assert podtemplates \"{{range.items}}{{.metadata.name}}:{{end}}\" 'nginx:'\n\n  ### Printing pod templates works\n  kubectl get podtemplates \"${kube_flags[@]}\"\n  grep -q nginx <<< \"$(kubectl get podtemplates -o yaml \"${kube_flags[@]}\")\"\n\n  ### Delete nginx pod template by name\n  # Pre-condition: nginx pod template is available\n  kube::test::get_object_assert podtemplates \"{{range.items}}{{.metadata.name}}:{{end}}\" 'nginx:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert podtemplates events\n  # Command\n  kubectl delete podtemplate nginx \"${kube_flags[@]}\"\n  # Post-condition: No templates exist\n  kube::test::get_object_assert podtemplate \"{{range.items}}{{.metadata.name}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 1621}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_crd_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl crd\"\n  kubectl \"${kube_flags_with_token[@]:?}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"foos.company.com\"\n  },\n  \"spec\": {\n    \"group\": \"company.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"foos\",\n      \"kind\": \"Foo\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"x-kubernetes-preserve-unknown-fields\": true,\n            \"type\": \"object\"\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Post-Condition: assertion object exist\n  kube::test::get_object_assert customresourcedefinitions \"{{range.items}}{{if eq ${id_field:?} \\\\\\\"foos.company.com\\\\\\\"}}{{$id_field}}:{{end}}{{end}}\" 'foos.company.com:'\n\n  kubectl \"${kube_flags_with_token[@]}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"bars.company.com\"\n  },\n  \"spec\": {\n    \"group\": \"company.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"bars\",\n      \"kind\": \"Bar\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"x-kubernetes-preserve-unknown-fields\": true,\n            \"type\": \"object\"\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Post-Condition: assertion object exist\n  kube::test::get_object_assert customresourcedefinitions \"{{range.items}}{{if eq $id_field \\\\\\\"foos.company.com\\\\\\\" \\\\\\\"bars.company.com\\\\\\\"}}{{$id_field}}:{{end}}{{end}}\" 'bars.company.com:foos.company.com:'\n\n  # This test ensures that the name printer is able to output a resource\n  # in the proper \"kind.group/resource_name\" format, and that the\n  # resource builder is able to resolve a GVK when a kind.group pair is given.\n  kubectl \"${kube_flags_with_token[@]}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"resources.mygroup.example.com\"\n  },\n  \"spec\": {\n    \"group\": \"mygroup.example.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"resources\",\n      \"singular\": \"resource\",\n      \"kind\": \"Kind\",\n      \"listKind\": \"KindList\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1alpha1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"x-kubernetes-preserve-unknown-fields\": true,\n            \"type\": \"object\"\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Post-Condition: assertion crd with non-matching kind and resource exists\n  kube::test::get_object_assert customresourcedefinitions \"{{range.items}}{{if eq $id_field \\\\\\\"foos.company.com\\\\\\\" \\\\\\\"bars.company.com\\\\\\\" \\\\\\\"resources.mygroup.example.com\\\\\\\"}}{{$id_field}}:{{end}}{{end}}\" 'bars.company.com:foos.company.com:resources.mygroup.example.com:'\n\n  # This test ensures that we can create complex validation without client-side validation complaining\n  kubectl \"${kube_flags_with_token[@]}\" create -f - << __EOF__\n{\n  \"kind\": \"CustomResourceDefinition\",\n  \"apiVersion\": \"apiextensions.k8s.io/v1\",\n  \"metadata\": {\n    \"name\": \"validfoos.company.com\"\n  },\n  \"spec\": {\n    \"group\": \"company.com\",\n    \"scope\": \"Namespaced\",\n    \"names\": {\n      \"plural\": \"validfoos\",\n      \"kind\": \"ValidFoo\"\n    },\n    \"versions\": [\n      {\n        \"name\": \"v1\",\n        \"served\": true,\n        \"storage\": true,\n        \"schema\": {\n          \"openAPIV3Schema\": {\n            \"type\": \"object\",\n            \"properties\": {\n              \"spec\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"type\": \"number\"\n                }\n              }\n            }\n          }\n        }\n      }\n    ]\n  }\n}\n__EOF__\n\n  # Post-Condition: assertion crd with non-matching kind and resource exists\n  kube::test::get_object_assert customresourcedefinitions \"{{range.items}}{{if eq $id_field \\\\\\\"foos.company.com\\\\\\\" \\\\\\\"bars.company.com\\\\\\\" \\\\\\\"resources.mygroup.example.com\\\\\\\" \\\\\\\"validfoos.company.com\\\\\\\"}}{{$id_field}}:{{end}}{{end}}\" 'bars.company.com:foos.company.com:resources.mygroup.example.com:validfoos.company.com:'\n\n  run_non_native_resource_tests\n\n  # teardown\n  kubectl delete customresourcedefinitions/foos.company.com \"${kube_flags_with_token[@]}\"\n  kubectl delete customresourcedefinitions/bars.company.com \"${kube_flags_with_token[@]}\"\n  kubectl delete customresourcedefinitions/resources.mygroup.example.com \"${kube_flags_with_token[@]}\"\n  kubectl delete customresourcedefinitions/validfoos.company.com \"${kube_flags_with_token[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nkube::util::non_native_resources() {\n  local times\n  local wait\n  local failed\n  times=30\n  wait=10\n  for _ in $(seq 1 $times); do\n    failed=\"\"\n    kubectl \"${kube_flags[@]:?}\" get --raw '/apis/company.com/v1' || failed=true\n    kubectl \"${kube_flags[@]}\" get --raw '/apis/company.com/v1/foos' || failed=true\n    kubectl \"${kube_flags[@]}\" get --raw '/apis/company.com/v1/bars' || failed=true\n\n    if [ -z \"${failed}\" ]; then\n      return 0\n    fi\n    sleep ${wait}\n  done\n\n  kube::log::error \"Timed out waiting for non-native-resources; tried ${times} waiting ${wait}s between each\"\n  return 1\n}\n\nrun_non_native_resource_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl non-native resources\"\n  kube::util::non_native_resources\n\n  # Test that we can list this new CustomResource (foos)\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can list this new CustomResource (bars)\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can list this new CustomResource (resources)\n  kube::test::get_object_assert resources \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can create a new resource of type Kind\n  kubectl \"${kube_flags[@]}\" create -f hack/testdata/CRD/resource.yaml \"${kube_flags[@]}\"\n\n  # Test that -o name returns kind.group/resourcename\n  output_message=$(kubectl \"${kube_flags[@]}\" get resource/myobj -o name)\n  kube::test::if_has_string \"${output_message}\" 'kind.mygroup.example.com/myobj'\n\n  output_message=$(kubectl \"${kube_flags[@]}\" get resources/myobj -o name)\n  kube::test::if_has_string \"${output_message}\" 'kind.mygroup.example.com/myobj'\n\n  output_message=$(kubectl \"${kube_flags[@]}\" get kind.mygroup.example.com/myobj -o name)\n  kube::test::if_has_string \"${output_message}\" 'kind.mygroup.example.com/myobj'\n\n  # Delete the resource with cascading strategy background.\n  kubectl \"${kube_flags[@]}\" delete resources myobj --cascade=background\n\n  # Make sure it's gone\n  kube::test::wait_object_assert resources \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can create a new resource of type Foo\n  kubectl \"${kube_flags[@]}\" create -f hack/testdata/CRD/foo.yaml \"${kube_flags[@]}\"\n  kubectl \"${kube_flags[@]}\" create -f hack/testdata/CRD/foo-2.yaml \"${kube_flags[@]}\"\n\n  # Test that we can list this new custom resource\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n\n  # Test alternate forms\n  kube::test::get_object_assert foo                 \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n  kube::test::get_object_assert foos.company.com    \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n  kube::test::get_object_assert foos.v1.company.com \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n\n  # Test all printers, with lists and individual items\n  kube::log::status \"Testing CustomResource printing\"\n  kubectl \"${kube_flags[@]}\" get foos\n  kubectl \"${kube_flags[@]}\" get foos/test\n  kubectl \"${kube_flags[@]}\" get foos      -o name\n  kubectl \"${kube_flags[@]}\" get foos/test -o name\n  kubectl \"${kube_flags[@]}\" get foos      -o wide\n  kubectl \"${kube_flags[@]}\" get foos/test -o wide\n  kubectl \"${kube_flags[@]}\" get foos      -o json\n  kubectl \"${kube_flags[@]}\" get foos/test -o json\n  kubectl \"${kube_flags[@]}\" get foos      -o yaml\n  kubectl \"${kube_flags[@]}\" get foos/test -o yaml\n  kubectl \"${kube_flags[@]}\" get foos      -o \"jsonpath={.items[*].someField}\" --allow-missing-template-keys=false\n  kubectl \"${kube_flags[@]}\" get foos/test -o \"jsonpath={.someField}\"          --allow-missing-template-keys=false\n  kubectl \"${kube_flags[@]}\" get foos      -o \"go-template={{range .items}}{{.someField}}{{end}}\" --allow-missing-template-keys=false\n  kubectl \"${kube_flags[@]}\" get foos/test -o \"go-template={{.someField}}\"                        --allow-missing-template-keys=false\n  output_message=$(kubectl \"${kube_flags[@]}\" get foos/test -o name)\n  kube::test::if_has_string \"${output_message}\" 'foo.company.com/test'\n\n  # Test patching\n  kube::log::status \"Testing CustomResource patching\"\n  kubectl \"${kube_flags[@]}\" patch foos/test -p '{\"patched\":\"value1\"}' --type=merge\n  kube::test::get_object_assert foos/test \"{{.patched}}\" 'value1'\n  kubectl \"${kube_flags[@]}\" patch foos/test -p '{\"patched\":\"value2\"}' --type=merge --record\n  kube::test::get_object_assert foos/test \"{{.patched}}\" 'value2'\n  kubectl \"${kube_flags[@]}\" patch foos/test -p '{\"patched\":null}' --type=merge --record\n  kube::test::get_object_assert foos/test \"{{.patched}}\" '<no value>'\n  # Get local version\n  CRD_RESOURCE_FILE=\"${KUBE_TEMP}/crd-foos-test.json\"\n  kubectl \"${kube_flags[@]}\" get foos/test -o json > \"${CRD_RESOURCE_FILE}\"\n  # cannot apply strategic patch locally\n  CRD_PATCH_ERROR_FILE=\"${KUBE_TEMP}/crd-foos-test-error\"\n  ! kubectl \"${kube_flags[@]}\" patch --local -f \"${CRD_RESOURCE_FILE}\" -p '{\"patched\":\"value3\"}' 2> \"${CRD_PATCH_ERROR_FILE}\" || exit 1\n  if grep -q \"try --type merge\" \"${CRD_PATCH_ERROR_FILE}\"; then\n    kube::log::status \"\\\"kubectl patch --local\\\" returns error as expected for CustomResource: $(cat \"${CRD_PATCH_ERROR_FILE}\")\"\n  else\n    kube::log::status \"\\\"kubectl patch --local\\\" returns unexpected error or non-error: $(cat \"${CRD_PATCH_ERROR_FILE}\")\"\n    exit 1\n  fi\n  # can apply merge patch locally\n  kubectl \"${kube_flags[@]}\" patch --local -f \"${CRD_RESOURCE_FILE}\" -p '{\"patched\":\"value3\"}' --type=merge -o json\n  # can apply merge patch remotely\n  kubectl \"${kube_flags[@]}\" patch --record -f \"${CRD_RESOURCE_FILE}\" -p '{\"patched\":\"value3\"}' --type=merge -o json\n  kube::test::get_object_assert foos/test \"{{.patched}}\" 'value3'\n  rm \"${CRD_RESOURCE_FILE}\"\n  rm \"${CRD_PATCH_ERROR_FILE}\"\n\n  # Test labeling\n  kube::log::status \"Testing CustomResource labeling\"\n  kubectl \"${kube_flags[@]}\" label foos --all listlabel=true\n  kubectl \"${kube_flags[@]}\" label foo/test itemlabel=true\n  kubectl \"${kube_flags[@]}\" label --all --all-namespaces foo allnsLabel=true\n  # make sure all instances in different namespaces got the annotation\n  kubectl \"${kube_flags[@]}\" get foo/test -oyaml | grep allnsLabel\n  kubectl \"${kube_flags[@]}\" get -n default foo -oyaml | grep allnsLabel\n\n  # Test annotating\n  kube::log::status \"Testing CustomResource annotating\"\n  kubectl \"${kube_flags[@]}\" annotate foos --all listannotation=true\n  kubectl \"${kube_flags[@]}\" annotate foo/test itemannotation=true\n  kubectl \"${kube_flags[@]}\" annotate --all --all-namespaces foo allnsannotation=true\n  # make sure all instances in different namespaces got the annotation\n  kubectl \"${kube_flags[@]}\" get foo/test -oyaml | grep allnsannotation\n  kubectl \"${kube_flags[@]}\" get -n default foo -oyaml | grep allnsannotation\n\n  # Test describing\n  kube::log::status \"Testing CustomResource describing\"\n  kubectl \"${kube_flags[@]}\" describe foos\n  kubectl \"${kube_flags[@]}\" describe foos/test\n  kubectl \"${kube_flags[@]}\" describe foos | grep listlabel=true\n  kubectl \"${kube_flags[@]}\" describe foos | grep itemlabel=true\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert customresourcedefinitions events\n  kube::test::describe_resource_chunk_size_assert foos events\n\n  # Delete the resource with cascading strategy background.\n  kubectl \"${kube_flags[@]}\" delete foos test --cascade=background\n\n  # Make sure it's gone\n  kube::test::wait_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can create a new resource of type Bar\n  kubectl \"${kube_flags[@]}\" create -f hack/testdata/CRD/bar.yaml \"${kube_flags[@]}\"\n\n  # Test that we can list this new custom resource\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n\n  # Test that we can watch the resource.\n  # Start watcher in background with process substitution,\n  # so we can read from stdout asynchronously.\n  kube::log::status \"Testing CustomResource watching\"\n  exec 3< <(kubectl \"${kube_flags[@]}\" get bars --request-timeout=1m --watch-only -o name & echo $! ; wait)\n  local watch_pid\n  read -r <&3 watch_pid\n\n  # We can't be sure when the watch gets established,\n  # so keep triggering events (in the background) until something comes through.\n  local tries=0\n  while [ ${tries} -lt 10 ]; do\n    tries=$((tries+1))\n    kubectl \"${kube_flags[@]}\" patch bars/test -p \"{\\\"patched\\\":\\\"${tries}\\\"}\" --type=merge\n    sleep 1\n  done &\n  local patch_pid=$!\n\n  # Wait up to 30s for a complete line of output.\n  local watch_output\n  read -r <&3 -t 30 watch_output\n  # Stop the watcher and the patch loop.\n  kill -9 \"${watch_pid}\"\n  kill -9 \"${patch_pid}\"\n  kube::test::if_has_string \"${watch_output}\" 'bar.company.com/test'\n\n  # Delete the resource with cascading strategy orphan.\n  kubectl \"${kube_flags[@]}\" delete bars test --cascade=orphan\n\n  # Make sure it's gone\n  kube::test::wait_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can create single item via apply\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/foo.yaml\n\n  # Test that we have create a foo named test\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n\n  # Test that the field has the expected value\n  kube::test::get_object_assert foos/test '{{.someField}}' 'field1'\n\n  # Test that apply an empty patch doesn't change fields\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/foo.yaml\n\n  # Test that the field has the same value after re-apply\n  kube::test::get_object_assert foos/test '{{.someField}}' 'field1'\n\n  # Test that apply has updated the subfield\n  kube::test::get_object_assert foos/test '{{.nestedField.someSubfield}}' 'subfield1'\n\n  # Update a subfield and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/foo-updated-subfield.yaml\n\n  # Test that apply has updated the subfield\n  kube::test::get_object_assert foos/test '{{.nestedField.someSubfield}}' 'modifiedSubfield'\n\n  # Test that the field has the expected value\n  kube::test::get_object_assert foos/test '{{.nestedField.otherSubfield}}' 'subfield2'\n\n  # Delete a subfield and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/foo-deleted-subfield.yaml\n\n  # Test that apply has deleted the field\n  kube::test::get_object_assert foos/test '{{.nestedField.otherSubfield}}' '<no value>'\n\n  # Test that the field does not exist\n  kube::test::get_object_assert foos/test '{{.nestedField.newSubfield}}' '<no value>'\n\n  # Add a field and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/foo-added-subfield.yaml\n\n  # Test that apply has added the field\n  kube::test::get_object_assert foos/test '{{.nestedField.newSubfield}}' 'subfield3'\n\n  # Delete the resource\n  kubectl \"${kube_flags[@]}\" delete -f hack/testdata/CRD/foo.yaml\n\n  # Make sure it's gone\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test that we can create list via apply\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/multi-crd-list.yaml\n\n  # Test that we have create a foo and a bar from a list\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" 'test-list:'\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" 'test-list:'\n\n  # Test that the field has the expected value\n  kube::test::get_object_assert foos/test-list '{{.someField}}' 'field1'\n  kube::test::get_object_assert bars/test-list '{{.someField}}' 'field1'\n\n  # Test that re-apply an list doesn't change anything\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/multi-crd-list.yaml\n\n  # Test that the field has the same value after re-apply\n  kube::test::get_object_assert foos/test-list '{{.someField}}' 'field1'\n  kube::test::get_object_assert bars/test-list '{{.someField}}' 'field1'\n\n  # Test that the fields have the expected value\n  kube::test::get_object_assert foos/test-list '{{.someField}}' 'field1'\n  kube::test::get_object_assert bars/test-list '{{.someField}}' 'field1'\n\n  # Update fields and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/multi-crd-list-updated-field.yaml\n\n  # Test that apply has updated the fields\n  kube::test::get_object_assert foos/test-list '{{.someField}}' 'modifiedField'\n  kube::test::get_object_assert bars/test-list '{{.someField}}' 'modifiedField'\n\n  # Test that the field has the expected value\n  kube::test::get_object_assert foos/test-list '{{.otherField}}' 'field2'\n  kube::test::get_object_assert bars/test-list '{{.otherField}}' 'field2'\n\n  # Delete fields and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/multi-crd-list-deleted-field.yaml\n\n  # Test that apply has deleted the fields\n  kube::test::get_object_assert foos/test-list '{{.otherField}}' '<no value>'\n  kube::test::get_object_assert bars/test-list '{{.otherField}}' '<no value>'\n\n  # Test that the fields does not exist\n  kube::test::get_object_assert foos/test-list '{{.newField}}' '<no value>'\n  kube::test::get_object_assert bars/test-list '{{.newField}}' '<no value>'\n\n  # Add a field and then apply the change\n  kubectl \"${kube_flags[@]}\" apply -f hack/testdata/CRD/multi-crd-list-added-field.yaml\n\n  # Test that apply has added the field\n  kube::test::get_object_assert foos/test-list '{{.newField}}' 'field3'\n  kube::test::get_object_assert bars/test-list '{{.newField}}' 'field3'\n\n  # Delete the resource\n  kubectl \"${kube_flags[@]}\" delete -f hack/testdata/CRD/multi-crd-list.yaml\n\n  # Make sure it's gone\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ## kubectl apply --prune\n  # Test that no foo or bar exist\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # apply --prune on foo.yaml that has foo/test\n  kubectl apply --prune -l pruneGroup=true -f hack/testdata/CRD/foo.yaml \"${kube_flags[@]}\" --prune-whitelist=company.com/v1/Foo --prune-whitelist=company.com/v1/Bar\n  # check right crds exist\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # apply --prune on bar.yaml that has bar/test\n  kubectl apply --prune -l pruneGroup=true -f hack/testdata/CRD/bar.yaml \"${kube_flags[@]}\" --prune-whitelist=company.com/v1/Foo --prune-whitelist=company.com/v1/Bar\n  # check right crds exist\n  kube::test::wait_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" 'test:'\n\n  # Delete the resource\n  kubectl \"${kube_flags[@]}\" delete -f hack/testdata/CRD/bar.yaml\n\n  # Make sure it's gone\n  kube::test::get_object_assert foos \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert bars \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Test 'kubectl create' with namespace, and namespace cleanup.\n  kubectl \"${kube_flags[@]}\" create namespace non-native-resources\n  kubectl \"${kube_flags[@]}\" create -f hack/testdata/CRD/bar.yaml --namespace=non-native-resources\n  kube::test::get_object_assert bars '{{len .items}}' '1' --namespace=non-native-resources\n  kubectl \"${kube_flags[@]}\" delete namespace non-native-resources\n  # Make sure objects go away.\n  kube::test::wait_object_assert bars '{{len .items}}' '0' --namespace=non-native-resources\n  # Make sure namespace goes away.\n  local tries=0\n  while kubectl \"${kube_flags[@]}\" get namespace non-native-resources && [ ${tries} -lt 10 ]; do\n    tries=$((tries+1))\n    sleep ${tries}\n  done\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 524}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Runs tests related to kubectl create --dry-run.\nrun_kubectl_create_dry_run_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl create dry-run\"\n\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # dry-run create\n  kubectl create --dry-run=client -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  kubectl create --dry-run=server -f hack/testdata/pod.yaml \"${kube_flags[@]:?}\"\n  # check no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\n# Runs tests related to kubectl create --filename(-f) --selector(-l).\nrun_kubectl_create_filter_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl create filter\"\n  ## kubectl create -f with label selector should only create matching objects\n  # Pre-Condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # create\n  kubectl create -l unique-label=bingbang -f hack/testdata/filter \"${kube_flags[@]:?}\"\n  # check right pod exists\n  kube::test::get_object_assert 'pods selector-test-pod' \"{{${labels_field:?}.name}}\" 'selector-test-pod'\n  # check wrong pod doesn't exist\n  output_message=$(! kubectl get pods selector-test-pod-dont-apply 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'pods \"selector-test-pod-dont-apply\" not found'\n  # cleanup\n  kubectl delete pods selector-test-pod\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_create_error_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl create with error\"\n\n  # Passing no arguments to create is an error\n  ! kubectl create || exit 1\n\n  ## kubectl create should not panic on empty string lists in a template\n  ERROR_FILE=\"${KUBE_TEMP}/validation-error\"\n  kubectl create -f hack/testdata/invalid-rc-with-empty-args.yaml \"${kube_flags[@]}\" 2> \"${ERROR_FILE}\" || true\n  # Post-condition: should get an error reporting the empty string\n  if grep -q \"unknown object type \\\"nil\\\" in ReplicationController\" \"${ERROR_FILE}\"; then\n    kube::log::status \"\\\"kubectl create with empty string list returns error as expected: $(cat \"${ERROR_FILE}\")\"\n  else\n    kube::log::status \"\\\"kubectl create with empty string list returns unexpected error or non-error: $(cat \"${ERROR_FILE}\")\"\n    exit 1\n  fi\n  rm \"${ERROR_FILE}\"\n\n  # Posting a pod to namespaces should fail.  Also tests --raw forcing the post location\n  grep -q 'the object provided is unrecognized (must be of type Namespace)' <<< \"$( kubectl create \"${kube_flags[@]}\" --raw /api/v1/namespaces -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml --v=8 2>&1 )\"\n\n  grep -q \"raw and --edit are mutually exclusive\" <<< \"$( kubectl create \"${kube_flags[@]}\" --raw /api/v1/namespaces -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml --edit 2>&1 )\"\n\n  set +o nounset\n  set +o errexit\n}\n\n# Runs kubectl create job tests\nrun_create_job_tests() {\n    set -o nounset\n    set -o errexit\n\n    create_and_use_new_namespace\n\n    # Test kubectl create job\n    kubectl create job test-job --image=k8s.gcr.io/nginx:test-cmd\n    # Post-Condition: job nginx is created\n    kube::test::get_object_assert 'job test-job' \"{{${image_field0:?}}}\" 'k8s.gcr.io/nginx:test-cmd'\n    # Clean up\n    kubectl delete job test-job \"${kube_flags[@]}\"\n\n    # Test kubectl create job with command\n    kubectl create job test-job-pi \"--image=$IMAGE_PERL\" -- perl -Mbignum=bpi -wle 'print bpi(20)'\n    kube::test::get_object_assert 'job test-job-pi' \"{{$image_field0}}\" \"$IMAGE_PERL\"\n    # Clean up\n    kubectl delete job test-job-pi\n\n    # Test kubectl create job from cronjob\n    # Pre-Condition: create a cronjob\n    kubectl create cronjob test-pi --schedule=\"* */5 * * *\" \"--image=$IMAGE_PERL\" -- perl -Mbignum=bpi -wle 'print bpi(10)'\n    kubectl create job my-pi --from=cronjob/test-pi\n    # Post-condition: container args contain expected command\n    output_message=$(kubectl get job my-pi -o go-template='{{(index .spec.template.spec.containers 0).command}}' \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"perl -Mbignum=bpi -wle print bpi(10)\"\n\n    # Clean up\n    kubectl delete job my-pi\n    kubectl delete cronjob test-pi\n\n    set +o nounset\n    set +o errexit\n}\n\nrun_kubectl_create_kustomization_directory_tests() {\n  set -o nounset\n  set -o errexit\n\n  ## kubectl create -k <dir> for kustomization directory\n  # Pre-Condition: No configmaps with name=test-the-map, no Deployment, Service exist\n  kube::test::get_object_assert 'configmaps --field-selector=metadata.name=test-the-map' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -k hack/testdata/kustomize\n  # Post-condition: test-the-map, test-the-deployment, test-the-service exist\n\n  # Check that all items in the list are printed\n  kube::test::get_object_assert 'configmap test-the-map' \"{{${id_field}}}\" 'test-the-map'\n  kube::test::get_object_assert 'deployment test-the-deployment' \"{{${id_field}}}\" 'test-the-deployment'\n  kube::test::get_object_assert 'service test-the-service' \"{{${id_field}}}\" 'test-the-service'\n\n  # cleanup\n  kubectl delete -k hack/testdata/kustomize\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 156}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_debug_pod_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl debug (pod tests)\"\n\n  ### Pod Troubleshooting by Copy\n\n  # Pre-Condition: Pod \"nginx\" is created\n  kubectl run target \"--image=${IMAGE_NGINX:?}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target:'\n  # Command: create a copy of target with a new debug container\n  kubectl debug target -it --copy-to=target-copy --image=busybox --container=debug-container --attach=false \"${kube_flags[@]:?}\"\n  # Post-Conditions\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target:target-copy:'\n  kube::test::get_object_assert pod/target-copy '{{range.spec.containers}}{{.name}}:{{end}}' 'target:debug-container:'\n  kube::test::get_object_assert pod/target-copy '{{range.spec.containers}}{{.image}}:{{end}}' \"${IMAGE_NGINX:?}:busybox:\"\n  # Clean up\n  kubectl delete pod target target-copy \"${kube_flags[@]:?}\"\n \n  # Pre-Condition: Pod \"nginx\" is created\n  kubectl run target \"--image=${IMAGE_NGINX:?}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target:'\n  # Command: create a copy of target with a new debug container replacing the previous pod\n  kubectl debug target -it --copy-to=target-copy --image=busybox --container=debug-container --attach=false --replace \"${kube_flags[@]:?}\"\n  # Post-Conditions\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target-copy:'\n  kube::test::get_object_assert pod/target-copy '{{range.spec.containers}}{{.name}}:{{end}}' 'target:debug-container:'\n  kube::test::get_object_assert pod/target-copy '{{range.spec.containers}}{{.image}}:{{end}}' \"${IMAGE_NGINX:?}:busybox:\"\n  # Clean up\n  kubectl delete pod target-copy \"${kube_flags[@]:?}\"\n\n  # Pre-Condition: Pod \"nginx\" is created\n  kubectl run target \"--image=${IMAGE_NGINX:?}\" \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target:'\n  kube::test::get_object_assert pod/target '{{(index .spec.containers 0).name}}' 'target'\n  # Command: copy the pod and replace the image of an existing container\n  kubectl debug target --image=busybox --container=target --copy-to=target-copy \"${kube_flags[@]:?}\" -- sleep 1m\n  # Post-Conditions\n  kube::test::get_object_assert pod \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'target:target-copy:'\n  kube::test::get_object_assert pod/target-copy \"{{(len .spec.containers)}}:{{${image_field:?}}}\" '1:busybox'\n  # Clean up\n  kubectl delete pod target target-copy \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_debug_node_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl debug (pod tests)\"\n\n  ### Node Troubleshooting by Privileged Container\n\n  # Pre-Condition: Pod \"nginx\" is created\n  kube::test::get_object_assert nodes \"{{range.items}}{{${id_field:?}}}:{{end}}\" '127.0.0.1:'\n  # Command: create a new node debugger pod\n  output_message=$(kubectl debug node/127.0.0.1 --image=busybox --attach=false \"${kube_flags[@]:?}\" -- true)\n  # Post-Conditions\n  kube::test::get_object_assert pod \"{{(len .items)}}\" '1'\n  debugger=$(kubectl get pod -o go-template=\"{{(index .items 0)${id_field:?}}}\")\n  kube::test::if_has_string \"${output_message:?}\" \"${debugger:?}\"\n  kube::test::get_object_assert \"pod/${debugger:?}\" \"{{${image_field:?}}}\" 'busybox'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{.spec.nodeName}}' '127.0.0.1'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{.spec.hostIPC}}' 'true'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{.spec.hostNetwork}}' 'true'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{.spec.hostPID}}' 'true'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{(index (index .spec.containers 0).volumeMounts 0).mountPath}}' '/host'\n  kube::test::get_object_assert \"pod/${debugger:?}\" '{{(index .spec.volumes 0).hostPath.path}}' '/'\n  # Clean up\n  # pod.spec.nodeName is set by kubectl debug node which causes the delete to hang,\n  # presumably waiting for a kubelet that's not present. Force the delete.\n  kubectl delete --force pod \"${debugger:?}\" \"${kube_flags[@]:?}\"\n \n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 102}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Runs tests related to kubectl delete --all-namespaces.\nrun_kubectl_delete_allnamespaces_tests() {\n  set -o nounset\n  set -o errexit\n\n  ns_one=\"namespace-$(date +%s)-${RANDOM}\"\n  ns_two=\"namespace-$(date +%s)-${RANDOM}\"\n  kubectl create namespace \"${ns_one}\"\n  kubectl create namespace \"${ns_two}\"\n\n  kubectl create configmap \"one\" --namespace=\"${ns_one}\"\n  kubectl create configmap \"two\" --namespace=\"${ns_two}\"\n  kubectl label configmap \"one\" --namespace=\"${ns_one}\" deletetest=true\n  kubectl label configmap \"two\" --namespace=\"${ns_two}\" deletetest=true\n\n  # dry-run\n  kubectl delete configmap --dry-run=client -l deletetest=true --all-namespaces\n  kubectl delete configmap --dry-run=server -l deletetest=true --all-namespaces\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"${ns_one}\"\n  kube::test::get_object_assert 'configmap -l deletetest' \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'one:'\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"${ns_two}\"\n  kube::test::get_object_assert 'configmap -l deletetest' \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'two:'\n\n  kubectl delete configmap -l deletetest=true --all-namespaces\n\n  # no configmaps should be in either of those namespaces with label deletetest\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"${ns_one}\"\n  kube::test::get_object_assert 'configmap -l deletetest' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"${ns_two}\"\n  kube::test::get_object_assert 'configmap -l deletetest' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 55}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Runs tests for kubectl diff\nrun_kubectl_diff_tests() {\n    set -o nounset\n    set -o errexit\n\n    create_and_use_new_namespace\n    kube::log::status \"Testing kubectl diff\"\n\n    # Test that it works when the live object doesn't exist\n    output_message=$(! kubectl diff -f hack/testdata/pod.yaml)\n    kube::test::if_has_string \"${output_message}\" 'test-pod'\n    # Ensure diff only dry-runs and doesn't persist change\n    kube::test::get_object_assert 'pod' \"{{range.items}}{{ if eq ${id_field:?} \\\\\\\"test-pod\\\\\\\" }}found{{end}}{{end}}:\" ':'\n\n    kubectl apply -f hack/testdata/pod.yaml\n    kube::test::get_object_assert 'pod' \"{{range.items}}{{ if eq ${id_field:?} \\\\\\\"test-pod\\\\\\\" }}found{{end}}{{end}}:\" 'found:'\n    initialResourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n\n    # Make sure that diffing the resource right after returns nothing (0 exit code).\n    kubectl diff -f hack/testdata/pod.yaml\n\n    # Ensure diff only dry-runs and doesn't persist change\n    resourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n    kube::test::if_has_string \"${resourceVersion}\" \"${initialResourceVersion}\"\n\n    # Make sure that:\n    # 1. the exit code for diff is 1 because it found a difference\n    # 2. the difference contains the changed image\n    output_message=$(kubectl diff -f hack/testdata/pod-changed.yaml || test $? -eq 1)\n    kube::test::if_has_string \"${output_message}\" 'k8s.gcr.io/pause:3.4'\n\n    # Ensure diff only dry-runs and doesn't persist change\n    resourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n    kube::test::if_has_string \"${resourceVersion}\" \"${initialResourceVersion}\"\n\n    # Test found diff with server-side apply\n    output_message=$(kubectl diff -f hack/testdata/pod-changed.yaml --server-side || test $? -eq 1)\n    kube::test::if_has_string \"${output_message}\" 'k8s.gcr.io/pause:3.4'\n\n    # Ensure diff --server-side only dry-runs and doesn't persist change\n    resourceVersion=$(kubectl get \"${kube_flags[@]:?}\" -f hack/testdata/pod.yaml -o go-template='{{ .metadata.resourceVersion }}')\n    kube::test::if_has_string \"${resourceVersion}\" \"${initialResourceVersion}\"\n\n    # Test that we have a return code bigger than 1 if there is an error when diffing\n    kubectl diff -f hack/testdata/invalid-pod.yaml || test $? -gt 1\n\n    # Cleanup\n    kubectl delete -f hack/testdata/pod.yaml\n\n    kube::log::status \"Testing kubectl diff with server-side apply\"\n\n    # Test that kubectl diff --server-side works when the live object doesn't exist\n    output_message=$(! kubectl diff --server-side -f hack/testdata/pod.yaml)\n    kube::test::if_has_string \"${output_message}\" 'test-pod'\n    # Ensure diff --server-side only dry-runs and doesn't persist change\n    kube::test::get_object_assert 'pod' \"{{range.items}}{{ if eq ${id_field:?} \\\\\\\"test-pod\\\\\\\" }}found{{end}}{{end}}:\" ':'\n\n    # Server-side apply the Pod\n    kubectl apply --server-side -f hack/testdata/pod.yaml\n    kube::test::get_object_assert 'pod' \"{{range.items}}{{ if eq ${id_field:?} \\\\\\\"test-pod\\\\\\\" }}found{{end}}{{end}}:\" 'found:'\n\n    # Make sure that --server-side diffing the resource right after returns nothing (0 exit code).\n    kubectl diff --server-side -f hack/testdata/pod.yaml\n\n    # Make sure that for kubectl diff --server-side:\n    # 1. the exit code for diff is 1 because it found a difference\n    # 2. the difference contains the changed image\n    output_message=$(kubectl diff --server-side -f hack/testdata/pod-changed.yaml || test $? -eq 1)\n    kube::test::if_has_string \"${output_message}\" 'k8s.gcr.io/pause:3.4'\n\n    # Cleanup\n    kubectl delete -f hack/testdata/pod.yaml\n\n    set +o nounset\n    set +o errexit\n}\n\nrun_kubectl_diff_same_names() {\n    set -o nounset\n    set -o errexit\n\n    create_and_use_new_namespace\n    kube::log::status \"Test kubectl diff with multiple resources with the same name\"\n\n    output_message=$(KUBECTL_EXTERNAL_DIFF=\"find\" kubectl diff -Rf hack/testdata/diff/)\n    kube::test::if_has_string \"${output_message}\" 'v1\\.Pod\\..*\\.test'\n    kube::test::if_has_string \"${output_message}\" 'apps\\.v1\\.Deployment\\..*\\.test'\n    kube::test::if_has_string \"${output_message}\" 'v1\\.ConfigMap\\..*\\.test'\n    kube::test::if_has_string \"${output_message}\" 'v1\\.Secret\\..*\\.test'\n\n    set +o nounset\n    set +o errexit\n}\n", "num_lines": 114}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_RESTMapper_evaluation_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing RESTMapper\"\n\n  RESTMAPPER_ERROR_FILE=\"${KUBE_TEMP}/restmapper-error\"\n\n  ### Non-existent resource type should give a recognizeable error\n  # Pre-condition: None\n  # Command\n  kubectl get \"${kube_flags[@]:?}\" unknownresourcetype 2>\"${RESTMAPPER_ERROR_FILE}\" || true\n  if grep -q \"the server doesn't have a resource type\" \"${RESTMAPPER_ERROR_FILE}\"; then\n    kube::log::status \"\\\"kubectl get unknownresourcetype\\\" returns error as expected: $(cat \"${RESTMAPPER_ERROR_FILE}\")\"\n  else\n    kube::log::status \"\\\"kubectl get unknownresourcetype\\\" returns unexpected error or non-error: $(cat \"${RESTMAPPER_ERROR_FILE}\")\"\n    exit 1\n  fi\n  rm \"${RESTMAPPER_ERROR_FILE}\"\n  # Post-condition: None\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_assert_short_name_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing assert short name\"\n\n  kube::log::status \"Testing propagation of short names for resources\"\n  output_message=$(kubectl get --raw=/api/v1)\n\n  ## test if a short name is exported during discovery\n  kube::test::if_has_string \"${output_message}\" '{\"name\":\"configmaps\",\"singularName\":\"\",\"namespaced\":true,\"kind\":\"ConfigMap\",\"verbs\":\\[\"create\",\"delete\",\"deletecollection\",\"get\",\"list\",\"patch\",\"update\",\"watch\"\\],\"shortNames\":\\[\"cm\"\\],\"storageVersionHash\":'\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_assert_categories_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing propagation of categories for resources\"\n  output_message=$(kubectl get --raw=/api/v1 | grep -o '\"name\":\"pods\"[^}]*}')\n  kube::test::if_has_string \"${output_message}\" '\"categories\":\\[\"all\"\\]'\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_resource_aliasing_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing resource aliasing\"\n  kubectl create -f test/e2e/testing-manifests/statefulset/cassandra/controller.yaml \"${kube_flags[@]}\"\n  kubectl create -f test/e2e/testing-manifests/statefulset/cassandra/service.yaml \"${kube_flags[@]}\"\n\n  object=\"all -l'app=cassandra'\"\n  request=\"{{range.items}}{{range .metadata.labels}}{{.}}:{{end}}{{end}}\"\n\n  # all 4 cassandra's might not be in the request immediately...\n  # :? suffix is for possible service.kubernetes.io/headless\n  # label with \"\" value\n  kube::test::get_object_assert \"$object\" \"$request\" '(cassandra:){2}(cassandra:(cassandra::?)?)?'\n\n  kubectl delete all -l app=cassandra \"${kube_flags[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_explain_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl(v1:explain)\"\n  kubectl explain pods\n  # shortcuts work\n  kubectl explain po\n  kubectl explain po.status.message\n  # cronjob work\n  kubectl explain cronjob\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_swagger_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing swagger\"\n\n  # Verify schema\n  file=\"${KUBE_TEMP}/schema.json\"\n  curl -kfsS -H 'Authorization: Bearer admin-token' \"https://127.0.0.1:${SECURE_API_PORT}/openapi/v2\" > \"${file}\"\n  grep -q \"list of returned\" \"${file}\"\n  grep -q \"List of services\" \"${file}\"\n  grep -q \"Watch for changes to the described resources\" \"${file}\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 131}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2019 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_exec_pod_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl exec POD COMMAND\"\n\n  ### Test execute non-existing POD\n  output_message=$(! kubectl exec abc date 2>&1)\n  # POD abc should error since it doesn't exist\n  kube::test::if_has_string \"${output_message}\" 'pods \"abc\" not found'\n\n  ### Test execute existing POD\n  # Create test-pod\n  kubectl create -f hack/testdata/pod.yaml\n  # Execute existing POD\n  output_message=$(! kubectl exec test-pod date 2>&1)\n  # POD test-pod is exists this is shouldn't have output not found\n  kube::test::if_has_not_string \"${output_message}\" 'pods \"test-pod\" not found'\n  # These must be pass the validate\n  kube::test::if_has_not_string \"${output_message}\" 'pod or type/name must be specified'\n\n  # Clean up\n  kubectl delete pods test-pod\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_exec_resource_name_tests() {\n  set +o nounset\n  set +o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl exec TYPE/NAME COMMAND\"\n\n  ### Test execute invalid resource type\n  output_message=$(! kubectl exec foo/bar date 2>&1)\n  # resource type foo should error since it's invalid\n  kube::test::if_has_string \"${output_message}\" 'error:'\n\n  ### Test execute non-existing resources\n  output_message=$(! kubectl exec deployments/bar date 2>&1)\n  # resource type foo should error since it doesn't exist\n  kube::test::if_has_string \"${output_message}\" '\"bar\" not found'\n\n  kubectl create -f hack/testdata/pod.yaml\n  kubectl create -f hack/testdata/frontend-replicaset.yaml\n  kubectl create -f hack/testdata/configmap.yaml\n\n  ### Test execute non-implemented resources\n  output_message=$(! kubectl exec configmap/test-set-env-config date 2>&1)\n  # resource type configmap should error since configmap not implemented to be attached\n  kube::test::if_has_string \"${output_message}\" 'not implemented'\n\n  ### Test execute exists and valid resource type.\n  # Just check the output, since test-cmd not run kubelet, pod never be assigned.\n  # and not really can run `kubectl exec` command\n\n  output_message=$(! kubectl exec pods/test-pod date 2>&1)\n  # POD test-pod is exists this is shouldn't have output not found\n  kube::test::if_has_not_string \"${output_message}\" 'not found'\n  # These must be pass the validate\n  kube::test::if_has_not_string \"${output_message}\" 'pod, type/name or --filename must be specified'\n\n  output_message=$(! kubectl exec replicaset/frontend date 2>&1)\n  # Replicaset frontend is valid and exists will select the first pod.\n  # and Shouldn't have output not found\n  kube::test::if_has_not_string \"${output_message}\" 'not found'\n  # These must be pass the validate\n  kube::test::if_has_not_string \"${output_message}\" 'pod, type/name or --filename must be specified'\n\n  # Clean up\n  kubectl delete pods/test-pod\n  kubectl delete replicaset/frontend\n  kubectl delete configmap/test-set-env-config\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 101}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_multi_resources_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:multiple resources)\"\n\n  FILES=\"hack/testdata/multi-resource-yaml\n  hack/testdata/multi-resource-list\n  hack/testdata/multi-resource-json\n  hack/testdata/multi-resource-rclist\n  hack/testdata/multi-resource-svclist\"\n  YAML=\".yaml\"\n  JSON=\".json\"\n  for file in $FILES; do\n    if [ -f \"${file}${YAML}\" ]\n    then\n      file=${file}${YAML}\n      replace_file=\"${file%.yaml}-modify.yaml\"\n    else\n      file=${file}${JSON}\n      replace_file=\"${file%.json}-modify.json\"\n    fi\n\n    has_svc=true\n    has_rc=true\n    two_rcs=false\n    two_svcs=false\n    if [[ \"${file}\" == *rclist* ]]; then\n      has_svc=false\n      two_rcs=true\n    fi\n    if [[ \"${file}\" == *svclist* ]]; then\n      has_rc=false\n      two_svcs=true\n    fi\n\n    ### Create, get, describe, replace, label, annotate, and then delete service nginxsvc and replication controller my-nginx from 5 types of files:\n    ### 1) YAML, separated by ---; 2) JSON, with a List type; 3) JSON, with JSON object concatenation\n    ### 4) JSON, with a ReplicationControllerList type; 5) JSON, with a ServiceList type\n    echo \"Testing with file ${file} and replace with file ${replace_file}\"\n    # Pre-condition: no service (other than default kubernetes services) or replication controller exists\n    kube::test::get_object_assert services \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n    kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    # Command\n    kubectl create -f \"${file}\" \"${kube_flags[@]:?}\"\n    # Post-condition: mock service (and mock2) exists\n    if [ \"$has_svc\" = true ]; then\n      if [ \"$two_svcs\" = true ]; then\n        kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:mock2:'\n      else\n        kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:'\n      fi\n    fi\n    # Post-condition: mock rc (and mock2) exists\n    if [ \"$has_rc\" = true ]; then\n      if [ \"$two_rcs\" = true ]; then\n        kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:mock2:'\n      else\n        kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:'\n      fi\n    fi\n    # Command\n    kubectl get -f \"${file}\" \"${kube_flags[@]}\"\n    # Command: watching multiple resources should return \"not supported\" error\n    WATCH_ERROR_FILE=\"${KUBE_TEMP}/kubectl-watch-error\"\n    kubectl get -f \"${file}\" \"${kube_flags[@]}\" \"--watch\" 2> \"${WATCH_ERROR_FILE}\" || true\n    if ! grep -q \"watch is only supported on individual resources and resource collections\" \"${WATCH_ERROR_FILE}\"; then\n      kube::log::error_exit \"kubectl watch multiple resource returns unexpected error or non-error: $(cat \"${WATCH_ERROR_FILE}\")\" \"1\"\n    fi\n    kubectl describe -f \"${file}\" \"${kube_flags[@]}\"\n    # Command\n    kubectl replace -f \"${replace_file}\" --force --cascade=background \"${kube_flags[@]}\"\n    # Post-condition: mock service (and mock2) and mock rc (and mock2) are replaced\n    if [ \"$has_svc\" = true ]; then\n      kube::test::get_object_assert 'services mock' \"{{${labels_field:?}.status}}\" 'replaced'\n      if [ \"$two_svcs\" = true ]; then\n        kube::test::get_object_assert 'services mock2' \"{{${labels_field}.status}}\" 'replaced'\n      fi\n    fi\n    if [ \"$has_rc\" = true ]; then\n      kube::test::get_object_assert 'rc mock' \"{{${labels_field}.status}}\" 'replaced'\n      if [ \"$two_rcs\" = true ]; then\n        kube::test::get_object_assert 'rc mock2' \"{{${labels_field}.status}}\" 'replaced'\n      fi\n    fi\n    # Command: kubectl edit multiple resources\n    temp_editor=\"${KUBE_TEMP}/tmp-editor.sh\"\n    echo -e \"#!/usr/bin/env bash\\n${SED} -i \\\"s/status\\:\\ replaced/status\\:\\ edited/g\\\" \\$@\" > \"${temp_editor}\"\n    chmod +x \"${temp_editor}\"\n    EDITOR=\"${temp_editor}\" kubectl edit \"${kube_flags[@]}\" -f \"${file}\"\n    # Post-condition: mock service (and mock2) and mock rc (and mock2) are edited\n    if [ \"$has_svc\" = true ]; then\n      kube::test::get_object_assert 'services mock' \"{{${labels_field}.status}}\" 'edited'\n      if [ \"$two_svcs\" = true ]; then\n        kube::test::get_object_assert 'services mock2' \"{{${labels_field}.status}}\" 'edited'\n      fi\n    fi\n    if [ \"$has_rc\" = true ]; then\n      kube::test::get_object_assert 'rc mock' \"{{${labels_field}.status}}\" 'edited'\n      if [ \"$two_rcs\" = true ]; then\n        kube::test::get_object_assert 'rc mock2' \"{{${labels_field}.status}}\" 'edited'\n      fi\n    fi\n    # cleaning\n    rm \"${temp_editor}\"\n    # Command\n    # We need to set --overwrite, because otherwise, if the first attempt to run \"kubectl label\"\n    # fails on some, but not all, of the resources, retries will fail because it tries to modify\n    # existing labels.\n    kubectl-with-retry label -f \"${file}\" labeled=true --overwrite \"${kube_flags[@]}\"\n    # Post-condition: mock service and mock rc (and mock2) are labeled\n    if [ \"$has_svc\" = true ]; then\n      kube::test::get_object_assert 'services mock' \"{{${labels_field}.labeled}}\" 'true'\n      if [ \"$two_svcs\" = true ]; then\n        kube::test::get_object_assert 'services mock2' \"{{${labels_field}.labeled}}\" 'true'\n      fi\n    fi\n    if [ \"$has_rc\" = true ]; then\n      kube::test::get_object_assert 'rc mock' \"{{${labels_field}.labeled}}\" 'true'\n      if [ \"$two_rcs\" = true ]; then\n        kube::test::get_object_assert 'rc mock2' \"{{${labels_field}.labeled}}\" 'true'\n      fi\n    fi\n    # Command\n    # Command\n    # We need to set --overwrite, because otherwise, if the first attempt to run \"kubectl annotate\"\n    # fails on some, but not all, of the resources, retries will fail because it tries to modify\n    # existing annotations.\n    kubectl-with-retry annotate -f \"${file}\" annotated=true --overwrite \"${kube_flags[@]}\"\n    # Post-condition: mock service (and mock2) and mock rc (and mock2) are annotated\n    if [ \"$has_svc\" = true ]; then\n      kube::test::get_object_assert 'services mock' \"{{${annotations_field:?}.annotated}}\" 'true'\n      if [ \"$two_svcs\" = true ]; then\n        kube::test::get_object_assert 'services mock2' \"{{${annotations_field}.annotated}}\" 'true'\n      fi\n    fi\n    if [ \"$has_rc\" = true ]; then\n      kube::test::get_object_assert 'rc mock' \"{{${annotations_field}.annotated}}\" 'true'\n      if [ \"$two_rcs\" = true ]; then\n        kube::test::get_object_assert 'rc mock2' \"{{${annotations_field}.annotated}}\" 'true'\n      fi\n    fi\n    # Cleanup resources created\n    kubectl delete -f \"${file}\" \"${kube_flags[@]}\"\n  done\n\n  #############################\n  # Multiple Resources via URL#\n  #############################\n\n  # Pre-condition: no service (other than default kubernetes services) or replication controller exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  # Command\n  kubectl create -f https://raw.githubusercontent.com/kubernetes/kubernetes/master/hack/testdata/multi-resource-yaml.yaml \"${kube_flags[@]}\"\n\n  # Post-condition: service(mock) and rc(mock) exist\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:'\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'mock:'\n\n  # Clean up\n  kubectl delete -f https://raw.githubusercontent.com/kubernetes/kubernetes/master/hack/testdata/multi-resource-yaml.yaml \"${kube_flags[@]}\"\n\n  # Post-condition: no service (other than default kubernetes services) or replication controller exists\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_recursive_resources_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing recursive resources\"\n  ### Create multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  output_message=$(! kubectl create -f hack/testdata/recursive/pod --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are created, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  kube::test::if_has_string \"${output_message}\" 'error validating data: kind not set'\n\n  ## Edit multiple busybox PODs by updating the image field of multiple PODs recursively from a directory. tmp-editor.sh is a fake editor\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  # shellcheck disable=SC2016  # $1 here is not a Expressions\n  echo -e '#!/usr/bin/env bash\\nsed -i \"s/image: busybox/image: prom\\/busybox/g\" $1' > /tmp/tmp-editor.sh\n  chmod +x /tmp/tmp-editor.sh\n  output_message=$(! EDITOR=/tmp/tmp-editor.sh kubectl edit -f hack/testdata/recursive/pod --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are not edited, and since busybox2 is malformed, it should error\n  # The reason why busybox0 & busybox1 PODs are not edited is because the editor tries to load all objects in\n  # a list but since it contains invalid objects, it will never open.\n  kube::test::get_object_assert pods \"{{range.items}}{{${image_field:?}}}:{{end}}\" 'busybox:busybox:'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  # cleaning\n  rm /tmp/tmp-editor.sh\n\n  ## Replace multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl replace -f hack/testdata/recursive/pod-modify --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are replaced, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert pods \"{{range.items}}{{${labels_field}.status}}:{{end}}\" 'replaced:replaced:'\n  kube::test::if_has_string \"${output_message}\" 'error validating data: kind not set'\n\n  ## Describe multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl describe -f hack/testdata/recursive/pod --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are described, and since busybox2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" \"app=busybox0\"\n  kube::test::if_has_string \"${output_message}\" \"app=busybox1\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ## Annotate multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl annotate -f hack/testdata/recursive/pod annotatekey='annotatevalue' --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are annotated, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert pods \"{{range.items}}{{${annotations_field}.annotatekey}}:{{end}}\" 'annotatevalue:annotatevalue:'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ## Apply multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl apply -f hack/testdata/recursive/pod-modify --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are updated, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert pods \"{{range.items}}{{${labels_field}.status}}:{{end}}\" 'replaced:replaced:'\n  kube::test::if_has_string \"${output_message}\" 'error validating data: kind not set'\n\n  ## Get multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl get -f hack/testdata/recursive/pod --recursive 2>&1 \"${kube_flags[@]}\" -o go-template=\"{{range.items}}{{$id_field}}:{{end}}\")\n  # Post-condition: busybox0 & busybox1 PODs are retrieved, but because busybox2 is malformed, it should not show up\n  kube::test::if_has_string \"${output_message}\" \"busybox0:busybox1:\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ## Label multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl label -f hack/testdata/recursive/pod mylabel='myvalue' --recursive 2>&1 \"${kube_flags[@]}\")\n  echo \"${output_message}\"\n  # Post-condition: busybox0 & busybox1 PODs are labeled, but because busybox2 is malformed, it should not show up\n  kube::test::get_object_assert pods \"{{range.items}}{{${labels_field}.mylabel}}:{{end}}\" 'myvalue:myvalue:'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ## Patch multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl patch -f hack/testdata/recursive/pod -p='{\"spec\":{\"containers\":[{\"name\":\"busybox\",\"image\":\"prom/busybox\"}]}}' --recursive 2>&1 \"${kube_flags[@]}\")\n  echo \"${output_message}\"\n  # Post-condition: busybox0 & busybox1 PODs are patched, but because busybox2 is malformed, it should not show up\n  kube::test::get_object_assert pods \"{{range.items}}{{$image_field}}:{{end}}\" 'prom/busybox:prom/busybox:'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ### Delete multiple busybox PODs recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl delete -f hack/testdata/recursive/pod --recursive --grace-period=0 --force 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 PODs are deleted, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ### Create replication controller recursively from directory of YAML files\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  ! kubectl create -f hack/testdata/recursive/rc --recursive \"${kube_flags[@]}\" || exit 1\n  # Post-condition: frontend replication controller is created\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n\n  ### Autoscale multiple replication controllers recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 replication controllers exist & 1\n  # replica each\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  kube::test::get_object_assert 'rc busybox0' \"{{${rc_replicas_field:?}}}\" '1'\n  kube::test::get_object_assert 'rc busybox1' \"{{$rc_replicas_field}}\" '1'\n  # Command\n  output_message=$(! kubectl autoscale --min=1 --max=2 -f hack/testdata/recursive/rc --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox replication controllers are autoscaled\n  # with min. of 1 replica & max of 2 replicas, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert 'hpa busybox0' \"{{${hpa_min_field:?}}} {{${hpa_max_field:?}}} {{${hpa_cpu_field:?}}}\" '1 2 80'\n  kube::test::get_object_assert 'hpa busybox1' \"{{$hpa_min_field}} {{$hpa_max_field}} {{$hpa_cpu_field}}\" '1 2 80'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  kubectl delete hpa busybox0 \"${kube_flags[@]}\"\n  kubectl delete hpa busybox1 \"${kube_flags[@]}\"\n\n  ### Expose multiple replication controllers as service recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 replication controllers exist & 1\n  # replica each\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  kube::test::get_object_assert 'rc busybox0' \"{{$rc_replicas_field}}\" '1'\n  kube::test::get_object_assert 'rc busybox1' \"{{$rc_replicas_field}}\" '1'\n  # Command\n  output_message=$(! kubectl expose -f hack/testdata/recursive/rc --recursive --port=80 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: service exists and the port is unnamed\n  kube::test::get_object_assert 'service busybox0' \"{{${port_name:?}}} {{${port_field:?}}}\" '<no value> 80'\n  kube::test::get_object_assert 'service busybox1' \"{{$port_name}} {{$port_field}}\" '<no value> 80'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ### Scale multiple replication controllers recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 replication controllers exist & 1\n  # replica each\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  kube::test::get_object_assert 'rc busybox0' \"{{$rc_replicas_field}}\" '1'\n  kube::test::get_object_assert 'rc busybox1' \"{{$rc_replicas_field}}\" '1'\n  # Command\n  output_message=$(! kubectl scale --current-replicas=1 --replicas=2 -f hack/testdata/recursive/rc --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 replication controllers are scaled to 2 replicas, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert 'rc busybox0' \"{{$rc_replicas_field}}\" '2'\n  kube::test::get_object_assert 'rc busybox1' \"{{$rc_replicas_field}}\" '2'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ### Delete multiple busybox replication controllers recursively from directory of YAML files\n  # Pre-condition: busybox0 & busybox1 PODs exist\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  output_message=$(! kubectl delete -f hack/testdata/recursive/rc --recursive --grace-period=0 --force 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 replication controllers are deleted, and since busybox2 is malformed, it should error\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n\n  ### Rollout on multiple deployments recursively\n  # Pre-condition: no deployments exist\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  # Create deployments (revision 1) recursively from directory of YAML files\n  ! kubectl create -f hack/testdata/recursive/deployment --recursive \"${kube_flags[@]}\" || exit 1\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" 'nginx0-deployment:nginx1-deployment:'\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_NGINX}:${IMAGE_NGINX}:\"\n  ## Rollback the deployments to revision 1 recursively\n  output_message=$(! kubectl rollout undo -f hack/testdata/recursive/deployment --recursive --to-revision=1 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: nginx0 & nginx1 should be a no-op, and since nginx2 is malformed, it should error\n  kube::test::get_object_assert deployment \"{{range.items}}{{${image_field0:?}}}:{{end}}\" \"${IMAGE_NGINX}:${IMAGE_NGINX}:\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  ## Pause the deployments recursively\n  # shellcheck disable=SC2034  # PRESERVE_ERR_FILE is used in kubectl-with-retry\n  PRESERVE_ERR_FILE=true\n  kubectl-with-retry rollout pause -f hack/testdata/recursive/deployment --recursive \"${kube_flags[@]}\"\n  output_message=$(cat \"${ERROR_FILE}\")\n  # Post-condition: nginx0 & nginx1 should both have paused set to true, and since nginx2 is malformed, it should error\n  kube::test::get_object_assert deployment \"{{range.items}}{{.spec.paused}}:{{end}}\" \"true:true:\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  ## Resume the deployments recursively\n  kubectl-with-retry rollout resume -f hack/testdata/recursive/deployment --recursive \"${kube_flags[@]}\"\n  output_message=$(cat \"${ERROR_FILE}\")\n  # Post-condition: nginx0 & nginx1 should both have paused set to nothing, and since nginx2 is malformed, it should error\n  kube::test::get_object_assert deployment \"{{range.items}}{{.spec.paused}}:{{end}}\" \"<no value>:<no value>:\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  ## Retrieve the rollout history of the deployments recursively\n  output_message=$(! kubectl rollout history -f hack/testdata/recursive/deployment --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: nginx0 & nginx1 should both have a history, and since nginx2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" \"nginx0-deployment\"\n  kube::test::if_has_string \"${output_message}\" \"nginx1-deployment\"\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  # Clean up\n  unset PRESERVE_ERR_FILE\n  rm \"${ERROR_FILE}\"\n  ! kubectl delete -f hack/testdata/recursive/deployment --recursive \"${kube_flags[@]}\" --grace-period=0 --force || exit 1\n  sleep 1\n\n  ### Rollout on multiple replication controllers recursively - these tests ensure that rollouts cannot be performed on resources that don't support it\n  # Pre-condition: no replication controller exists\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  # Create replication controllers recursively from directory of YAML files\n  ! kubectl create -f hack/testdata/recursive/rc --recursive \"${kube_flags[@]}\" || exit 1\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" 'busybox0:busybox1:'\n  # Command\n  ## Attempt to rollback the replication controllers to revision 1 recursively\n  output_message=$(! kubectl rollout undo -f hack/testdata/recursive/rc --recursive --to-revision=1 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 should error as they are RC's, and since busybox2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" 'no rollbacker has been implemented for \"ReplicationController\"'\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  ## Attempt to pause the replication controllers recursively\n  output_message=$(! kubectl rollout pause -f hack/testdata/recursive/rc --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 should error as they are RC's, and since busybox2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  kube::test::if_has_string \"${output_message}\" 'replicationcontrollers \"busybox0\" pausing is not supported'\n  kube::test::if_has_string \"${output_message}\" 'replicationcontrollers \"busybox1\" pausing is not supported'\n  ## Attempt to resume the replication controllers recursively\n  output_message=$(! kubectl rollout resume -f hack/testdata/recursive/rc --recursive 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: busybox0 & busybox1 should error as they are RC's, and since busybox2 is malformed, it should error\n  kube::test::if_has_string \"${output_message}\" \"Object 'Kind' is missing\"\n  kube::test::if_has_string \"${output_message}\" 'replicationcontrollers \"busybox0\" resuming is not supported'\n  kube::test::if_has_string \"${output_message}\" 'replicationcontrollers \"busybox1\" resuming is not supported'\n  # Clean up\n  ! kubectl delete -f hack/testdata/recursive/rc --recursive \"${kube_flags[@]}\" --grace-period=0 --force || exit 1\n  sleep 1\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_lists_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:lists)\"\n\n  ### Create a List with objects from multiple versions\n  # Command\n  kubectl create -f hack/testdata/list.yaml \"${kube_flags[@]}\"\n\n  ### Delete the List with objects from multiple versions\n  # Command\n  kubectl delete service/list-service-test deployment/list-deployment-test\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 449}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_get_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl get\"\n  ### Test retrieval of non-existing pods\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  output_message=$(! kubectl get pods abc 2>&1 \"${kube_flags[@]:?}\")\n  # Post-condition: POD abc should error since it doesn't exist\n  kube::test::if_has_string \"${output_message}\" 'pods \"abc\" not found'\n\n  ### Test retrieval of non-existing POD with output flag specified\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  output_message=$(! kubectl get pods abc 2>&1 \"${kube_flags[@]}\" -o name)\n  # Post-condition: POD abc should error since it doesn't exist\n  kube::test::if_has_string \"${output_message}\" 'pods \"abc\" not found'\n\n  ### Test retrieval of pods when none exist with non-human readable output format flag specified\n  # Pre-condition: no pods exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o json)\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o yaml)\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o name)\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o jsonpath='{.items}')\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o go-template='{{.items}}')\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o custom-columns=NAME:.metadata.name)\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n\n  ### Test retrieval of pods when none exist, with human-readable output format flag specified\n  # Pre-condition: no pods exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  output_message=$(! kubectl get foobar 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: The text \"No resources found\" should not be part of the output when an error occurs\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: The text \"No resources found\" should be part of the output\n  kube::test::if_has_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods --ignore-not-found 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: The text \"No resources found\" should not be part of the output\n  kube::test::if_has_not_string \"${output_message}\" 'No resources found'\n  # Command\n  output_message=$(kubectl get pods 2>&1 \"${kube_flags[@]}\" -o wide)\n  # Post-condition: The text \"No resources found\" should be part of the output\n  kube::test::if_has_string \"${output_message}\" 'No resources found'\n\n  ### Test retrieval of non-existing POD with json output flag specified\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  output_message=$(! kubectl get pods abc 2>&1 \"${kube_flags[@]}\" -o json)\n  # Post-condition: POD abc should error since it doesn't exist\n  kube::test::if_has_string \"${output_message}\" 'pods \"abc\" not found'\n  # Post-condition: make sure we don't display an empty List\n  kube::test::if_has_not_string \"${output_message}\" 'List'\n\n  ### Test kubectl get all\n  output_message=$(kubectl --v=6 --namespace default get all --chunk-size=0 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: Check if we get 200 OK from all the url(s)\n  kube::test::if_has_string \"${output_message}\" \"/api/v1/namespaces/default/pods 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/api/v1/namespaces/default/replicationcontrollers 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/api/v1/namespaces/default/services 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/apps/v1/namespaces/default/daemonsets 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/apps/v1/namespaces/default/deployments 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/apps/v1/namespaces/default/replicasets 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/apps/v1/namespaces/default/statefulsets 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/autoscaling/v1/namespaces/default/horizontalpodautoscalers 200\"\n  kube::test::if_has_string \"${output_message}\" \"/apis/batch/v1/namespaces/default/jobs 200 OK\"\n  kube::test::if_has_not_string \"${output_message}\" \"/apis/extensions/v1beta1/namespaces/default/daemonsets 200 OK\"\n  kube::test::if_has_not_string \"${output_message}\" \"/apis/extensions/v1beta1/namespaces/default/deployments 200 OK\"\n  kube::test::if_has_not_string \"${output_message}\" \"/apis/extensions/v1beta1/namespaces/default/replicasets 200 OK\"\n\n  ### Test kubectl get chunk size\n  output_message=$(kubectl --v=6 get clusterrole --chunk-size=10 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: Check if we get a limit and continue\n  kube::test::if_has_string \"${output_message}\" \"/clusterroles?limit=10 200 OK\"\n  kube::test::if_has_string \"${output_message}\" \"/v1/clusterroles?continue=\"\n\n  ### Test kubectl get chunk size defaults to 500\n  output_message=$(kubectl --v=6 get clusterrole 2>&1 \"${kube_flags[@]}\")\n  # Post-condition: Check if we get a limit and continue\n  kube::test::if_has_string \"${output_message}\" \"/clusterroles?limit=500 200 OK\"\n\n  ### Test kubectl get accumulates pages\n  output_message=$(kubectl get namespaces --chunk-size=1 --no-headers \"${kube_flags[@]}\")\n  # Post-condition: Check we got multiple pages worth of namespaces\n  kube::test::if_has_string \"${output_message}\" \"default\"\n  kube::test::if_has_string \"${output_message}\" \"kube-public\"\n  kube::test::if_has_string \"${output_message}\" \"kube-system\"\n\n  ### Test kubectl get chunk size does not result in a --watch error when resource list is served in multiple chunks\n  # Pre-condition: ConfigMap one two tree does not exist\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"one\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"two\\\\\\\" }}found{{end}}{{end}}:\" ':'\n  kube::test::get_object_assert 'configmaps' \"{{range.items}}{{ if eq $id_field \\\\\\\"three\\\\\\\" }}found{{end}}{{end}}:\" ':'\n\n  # Post-condition: Create three configmaps and ensure that we can --watch them with a --chunk-size of 1\n  kubectl create cm one \"${kube_flags[@]}\"\n  kubectl create cm two \"${kube_flags[@]}\"\n  kubectl create cm three \"${kube_flags[@]}\"\n  output_message=$(kubectl get configmap --chunk-size=1 --watch --request-timeout=1s 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_not_string \"${output_message}\" \"watch is only supported on individual resources\"\n  output_message=$(kubectl get configmap --chunk-size=1 --watch-only --request-timeout=1s 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_not_string \"${output_message}\" \"watch is only supported on individual resources\"\n\n  ### Test --allow-missing-template-keys\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: valid-pod POD is created\n  kubectl get \"${kube_flags[@]}\" pods -o json\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ## check --allow-missing-template-keys defaults to true for jsonpath templates\n  kubectl get \"${kube_flags[@]}\" pod valid-pod -o jsonpath='{.missing}'\n\n  ## check --allow-missing-template-keys defaults to true for go templates\n  kubectl get \"${kube_flags[@]}\" pod valid-pod -o go-template='{{.missing}}'\n\n  ## check --template flag causes go-template to be printed, even when no --output value is provided\n  output_message=$(kubectl get \"${kube_flags[@]}\" pod valid-pod --template=\"{{$id_field}}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  ## check --allow-missing-template-keys=false results in an error for a missing key with jsonpath\n  output_message=$(! kubectl get pod valid-pod --allow-missing-template-keys=false -o jsonpath='{.missing}' 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'missing is not found'\n\n  ## check --allow-missing-template-keys=false results in an error for a missing key with go\n  output_message=$(! kubectl get pod valid-pod --allow-missing-template-keys=false -o go-template='{{.missing}}' \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'map has no entry for key \"missing\"'\n\n  ### Test kubectl get watch\n  output_message=$(kubectl get pods -w --request-timeout=1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'STATUS'    # headers\n  kube::test::if_has_string \"${output_message}\" 'valid-pod' # pod details\n  output_message=$(kubectl get pods/valid-pod -o name -w --request-timeout=1 \"${kube_flags[@]}\")\n  kube::test::if_has_not_string \"${output_message}\" 'STATUS' # no headers\n  kube::test::if_has_string     \"${output_message}\" 'pod/valid-pod' # resource name\n  output_message=$(kubectl get pods/valid-pod -o yaml -w --request-timeout=1 \"${kube_flags[@]}\")\n  kube::test::if_has_not_string \"${output_message}\" 'STATUS'          # no headers\n  kube::test::if_has_string     \"${output_message}\" 'name: valid-pod' # yaml\n  output_message=$(! kubectl get pods/invalid-pod -w --request-timeout=1 \"${kube_flags[@]}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" '\"invalid-pod\" not found'\n\n  # cleanup\n  kubectl delete pods valid-pod \"${kube_flags[@]}\"\n\n  ### Test 'kubectl get -f <file> -o <non default printer>' prints all the items in the file's list\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml \"${kube_flags[@]}\"\n  # Post-condition: PODs redis-master and valid-pod exist\n\n  # Check that all items in the list are printed\n  output_message=$(kubectl get -f test/fixtures/doc-yaml/user-guide/multi-pod.yaml -o jsonpath=\"{..metadata.name}\" \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"redis-master valid-pod\"\n\n  # cleanup\n  kubectl delete pods redis-master valid-pod \"${kube_flags[@]}\"\n\n  ### Test 'kubectl get -k <dir>' prints all the items built from a kustomization directory\n  # Pre-Condition: No configmaps with name=test-the-map, no Deployment, Service exist\n  kube::test::get_object_assert 'configmaps --field-selector=metadata.name=test-the-map' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl apply -k hack/testdata/kustomize\n  # Post-condition: test-the-map, test-the-deployment, test-the-service exist\n\n  # Check that all items in the list are printed\n  output_message=$(kubectl get -k hack/testdata/kustomize -o jsonpath=\"{..metadata.name}\" \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"test-the-map\"\n  kube::test::if_has_string \"${output_message}\" \"test-the-deployment\"\n  kube::test::if_has_string \"${output_message}\" \"test-the-service\"\n\n  # cleanup\n  kubectl delete -k hack/testdata/kustomize\n\n  # Check that all items in the list are deleted\n  kube::test::get_object_assert 'configmaps --field-selector=metadata.name=test-the-map' \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  kube::test::get_object_assert deployment \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kube::test::get_object_assert services \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_retrieve_multiple_tests() {\n  set -o nounset\n  set -o errexit\n\n  # switch back to the default namespace\n  kubectl config set-context \"${CONTEXT}\" --namespace=\"\"\n  kube::log::status \"Testing kubectl(v1:multiget)\"\n  kube::test::get_object_assert 'nodes/127.0.0.1 service/kubernetes' \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:kubernetes:'\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_sort_by_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl --sort-by\"\n\n  ### sort-by should not panic if no pod exists\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl get pods --sort-by=\"{metadata.name}\"\n  kubectl get pods --sort-by=\"{metadata.creationTimestamp}\"\n\n  ### sort-by should works if pod exists\n  # Create POD\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  # Post-condition: valid-pod is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Check output of sort-by\n  output_message=$(kubectl get pods --sort-by=\"{metadata.name}\")\n  kube::test::if_has_string \"${output_message}\" \"valid-pod\"\n  # ensure sort-by receivers objects as Table\n  output_message=$(kubectl get pods --v=8 --sort-by=\"{metadata.name}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"as=Table\"\n  # ensure sort-by requests the full object\n  kube::test::if_has_string \"${output_message}\" \"includeObject=Object\"\n  ### Clean up\n  # Pre-condition: valid-pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete \"${kube_flags[@]}\" pod valid-pod --grace-period=0 --force\n  # Post-condition: valid-pod doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### sort-by should works by sorting by name\n  # Create three PODs\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f hack/testdata/sorted-pods/sorted-pod1.yaml\n  # Post-condition: sorted-pod1 is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'sorted-pod1:'\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f hack/testdata/sorted-pods/sorted-pod2.yaml\n  # Post-condition: sorted-pod1 is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'sorted-pod1:sorted-pod2:'\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f hack/testdata/sorted-pods/sorted-pod3.yaml\n  # Post-condition: sorted-pod1 is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'sorted-pod1:sorted-pod2:sorted-pod3:'\n\n  # Check output of sort-by '{metadata.name}'\n  output_message=$(kubectl get pods --sort-by=\"{metadata.name}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod1:sorted-pod2:sorted-pod3:\"\n\n  # Check output of sort-by '{metadata.labels.name}'\n  output_message=$(kubectl get pods --sort-by=\"{metadata.labels.name}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod3:sorted-pod2:sorted-pod1:\"\n\n  # if sorting, we should be able to use any field in our objects\n  output_message=$(kubectl get pods --sort-by=\"{spec.containers[0].name}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod2:sorted-pod1:sorted-pod3:\"\n\n  # ensure sorting by creation timestamps works\n  output_message=$(kubectl get pods --sort-by=\"{metadata.creationTimestamp}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod1:sorted-pod2:sorted-pod3:\"\n\n  # ensure sorting by resource memory request works\n  output_message=$(kubectl get pods --sort-by=\"{.spec.containers[0].resources.requests.memory}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod3:sorted-pod1:sorted-pod2:\"\n\n  # ensure sorting by resource cpu request works\n  output_message=$(kubectl get pods --sort-by=\"{.spec.containers[0].resources.requests.cpu}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod3:sorted-pod1:sorted-pod2:\"\n\n  # ensure sorting by resource memory limit works\n  output_message=$(kubectl get pods --sort-by=\"{.spec.containers[0].resources.limits.memory}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod3:sorted-pod1:sorted-pod2:\"\n\n  # ensure sorting by resource cpu limit works\n   output_message=$(kubectl get pods --sort-by=\"{.spec.containers[0].resources.limits.cpu}\")\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod3:sorted-pod1:sorted-pod2:\"\n\n  # ensure sorting using fallback codepath still works\n  output_message=$(kubectl get pods --sort-by=\"{spec.containers[0].name}\" --server-print=false --v=8 2>&1)\n  kube::test::if_sort_by_has_correct_order \"${output_message}\" \"sorted-pod2:sorted-pod1:sorted-pod3:\"\n  kube::test::if_has_not_string \"${output_message}\" \"Table\"\n\n  ### Clean up\n  # Pre-condition: valid-pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'sorted-pod1:sorted-pod2:sorted-pod3:'\n  # Command\n  kubectl delete \"${kube_flags[@]}\" pod --grace-period=0 --force --all\n  # Post-condition: valid-pod doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_all_namespace_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl --all-namespace\"\n\n  # Pre-condition: the \"default\" namespace exists\n  kube::test::get_object_assert namespaces \"{{range.items}}{{if eq $id_field \\\\\\\"default\\\\\\\"}}{{$id_field}}:{{end}}{{end}}\" 'default:'\n\n  ### Create POD\n  # Pre-condition: no POD exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command\n  kubectl create \"${kube_flags[@]}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  # Post-condition: valid-pod is created\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ### Verify a specific namespace is ignored when all-namespaces is provided\n  # Command\n  kubectl get pods --all-namespaces --namespace=default\n\n  ### Check --all-namespaces option shows namespaces\n  # Create objects in multiple namespaces\n  kubectl create \"${kube_flags[@]}\" namespace all-ns-test-1\n  kubectl create \"${kube_flags[@]}\" serviceaccount test -n all-ns-test-1\n  kubectl create \"${kube_flags[@]}\" namespace all-ns-test-2\n  kubectl create \"${kube_flags[@]}\" serviceaccount test -n all-ns-test-2\n  # Ensure listing across namespaces displays the namespace (--all-namespaces)\n  output_message=$(kubectl get serviceaccounts --all-namespaces \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"all-ns-test-1\"\n  kube::test::if_has_string \"${output_message}\" \"all-ns-test-2\"\n  # Ensure listing across namespaces displays the namespace (-A)\n  output_message=$(kubectl get serviceaccounts -A \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" \"all-ns-test-1\"\n  kube::test::if_has_string \"${output_message}\" \"all-ns-test-2\"\n  # Clean up\n  kubectl delete \"${kube_flags[@]}\" namespace all-ns-test-1\n  kubectl delete \"${kube_flags[@]}\" namespace all-ns-test-2\n\n  ### Clean up\n  # Pre-condition: valid-pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n  # Command\n  kubectl delete \"${kube_flags[@]}\" pod valid-pod --grace-period=0 --force\n  # Post-condition: valid-pod doesn't exist\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  ### Verify flag all-namespaces is ignored for rootScoped resources\n  # Pre-condition: node exists\n  kube::test::get_object_assert nodes \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:'\n  # Command\n  output_message=$(kubectl get nodes --all-namespaces 2>&1)\n  # Post-condition: output with no NAMESPACE field\n  kube::test::if_has_not_string \"${output_message}\" \"NAMESPACE\"\n\n  set +o nounset\n  set +o errexit\n}\n\n\nrun_deprecated_api_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing deprecated APIs\"\n\n  # Test deprecated API request output\n  # TODO(liggitt): switch this to a custom deprecated resource once CRDs support marking versions as deprecated\n  output_message=$(kubectl get podsecuritypolicies.v1beta1.policy 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'PodSecurityPolicy is deprecated'\n  output_message=$(! kubectl get podsecuritypolicies.v1beta1.policy --warnings-as-errors 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'PodSecurityPolicy is deprecated'\n  kube::test::if_has_string \"${output_message}\" 'Error: 1 warning received'\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 429}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_config_set_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl(v1:config set)\"\n\n  kubectl config set-cluster test-cluster --server=\"https://does-not-work\"\n\n  # Get the api cert and add a comment to avoid flag parsing problems\n  cert_data=$(echo \"#Comment\" && cat \"${TMPDIR:-/tmp}/apiserver.crt\")\n\n  kubectl config set clusters.test-cluster.certificate-authority-data \"$cert_data\" --set-raw-bytes\n  r_written=$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name == \"test-cluster\")].cluster.certificate-authority-data}')\n\n  encoded=$(echo -n \"$cert_data\" | base64)\n  kubectl config set clusters.test-cluster.certificate-authority-data \"$encoded\"\n  e_written=$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name == \"test-cluster\")].cluster.certificate-authority-data}')\n\n  test \"$e_written\" == \"$r_written\"\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_config_set_cluster_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl config set-cluster\"\n\n  ca_file=\"${TMPDIR:-/tmp}/apiserver.crt\"\n  ca_data=$(base64 -w0 \"$ca_file\")\n\n  # Set cert file\n  kubectl config set-cluster test-cluster-1 --certificate-authority \"$ca_file\"\n  expected=\"$ca_file\"\n  actual=$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name == \"test-cluster-1\")].cluster.certificate-authority}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Certificate authority did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  # Embed cert from file\n  kubectl config set-cluster test-cluster-2 --embed-certs --certificate-authority \"$ca_file\"\n  expected=\"$ca_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name == \"test-cluster-2\")].cluster.certificate-authority-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Certificate authority embedded from file did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  # Embed cert using process substitution\n  kubectl config set-cluster test-cluster-3 --embed-certs --certificate-authority <(cat \"$ca_file\")\n  expected=\"$ca_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.clusters[?(@.name == \"test-cluster-3\")].cluster.certificate-authority-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Certificate authority embedded using process substitution did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_kubectl_config_set_credentials_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl config set-credentials\"\n\n  cert_file=\"${TMPDIR:-/tmp}/test-client-certificate.crt\"\n  key_file=\"${TMPDIR:-/tmp}/test-client-key.crt\"\n\n  cat << EOF > \"$cert_file\"\n-----BEGIN CERTIFICATE-----\nMIIDazCCAlOgAwIBAgIUdSrvuXs0Bft9Ao/AFnC7fNBqD+owDQYJKoZIhvcNAQEL\nBQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM\nGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yMDA1MTExODMyNDJaFw0yMTA1\nMTExODMyNDJaMEUxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw\nHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB\nAQUAA4IBDwAwggEKAoIBAQCrS5/kYM3TjdFw4OYMdSOys0+4aHPgtXqePWrn1pBP\nW9D1yhjI/JS1/uPAWLi+1nnn0PBMCbqo+ZEsRIlSAABJE4fVbRPg+AuBPDdlCex5\nQfKNi3vwp0Gy756SKTNZmIx42I9in0WeocCDliTEM2KsawCrVzuE3gwcHHkOnmLX\nDEc4bajkQxcaJITG3hsJ2Cm5OBMLPwrsq/77VzOdC12r9j8+w0f7lCJfOm2ui7rm\nVl76V2Nits6U0ZrF1yzYtVQ1iWqCnOudPPf3jyc7KcSetGwozgoydkcqfUS9iMs9\n2OV3v17GX6+sd8zY8tA95d/Vj6yU/l03GI9V6X9LXHSTAgMBAAGjUzBRMB0GA1Ud\nDgQWBBQo2BKDxo4XI5FJDj9ZUuDst9ck7DAfBgNVHSMEGDAWgBQo2BKDxo4XI5FJ\nDj9ZUuDst9ck7DAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQAL\nLjJ5k5kNdOUXFL2XhKO8w25tpkjd71vD3vKvPIN0Q5BgVmu5Bg476/WPBnSMvTVU\nQYLQR5aGMLPdWuiSJnwO0BChKjOHaoCnP6D3cs2xP9hLBGoENaXMJRM4ZvFBRbES\nQ6iTfq4OBPh5yCDDrjlppjhSnqaZuksmFnPFHLB/km003w8fgCD3VhmC2UFscl2K\nnHaxK6uzIxisyE84ZDZYhjnPPib1wXGL8yu1dq0cbktE5+xJ2FHQkBJ6qaujkgV0\njpuWE9zk3CImFRkzPEwTF+3s5eP2XTIyWbtJGvJMmO0kHFx2PqCiAkdFldPKfrRh\nM007Wf15dtkqyLNkzOxv\n-----END CERTIFICATE-----\nEOF\n\n  cat << EOF > \"$key_file\"\n-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCrS5/kYM3TjdFw\n4OYMdSOys0+4aHPgtXqePWrn1pBPW9D1yhjI/JS1/uPAWLi+1nnn0PBMCbqo+ZEs\nRIlSAABJE4fVbRPg+AuBPDdlCex5QfKNi3vwp0Gy756SKTNZmIx42I9in0WeocCD\nliTEM2KsawCrVzuE3gwcHHkOnmLXDEc4bajkQxcaJITG3hsJ2Cm5OBMLPwrsq/77\nVzOdC12r9j8+w0f7lCJfOm2ui7rmVl76V2Nits6U0ZrF1yzYtVQ1iWqCnOudPPf3\njyc7KcSetGwozgoydkcqfUS9iMs92OV3v17GX6+sd8zY8tA95d/Vj6yU/l03GI9V\n6X9LXHSTAgMBAAECggEASKlTsfS+WrcV2OQNscse0XbuojLstK1GzkkPSDjkDkXM\nZfbMfLVn/6uXwMfh1lH0dDlVNWwLGhKDWlvYREhr1pPKUuZqQEv31WJNvTZwcR9g\nXFqGwJayb8zlXurLNX5YWArFB/i394p1t1vBTNjfSnQ5XHUscjgeuu35DBJzqvSA\nmh1nDUBFIMC4ruPzD7OMI7rXBN02PbfTBpoL8MGoesW0S/BFQciMS07rELL2hFih\nzZPJE+E6h3GMoSPAzqx+ubSkhMbxb/xQQSw4gfp8zii2SMuq8Ith9xaGhdj1TuaX\nNqZahgSRe7bbgYyHWHXYbd7gQa4fxxoT7Qyh0cSKwQKBgQDZP0yYcFfNADFfnw62\neWgNHnfPsOTYa/gAXdKgueUekT+linGvAUQtdXxnLoVMiLXSVxaJbW1rAP0avJt8\nEJiTdtTXkKqTqwtfbUP/bmxjYNExvGfIOpJbDsCX+kwpCoWzHupXeQlZn7UDEmKR\nl0DWUVzqNnhO0WWaM9J4MD4BjwKBgQDJ2elu8h7V/U/0dr2e4GG1/Xoa1nIcct8C\nrn0cG2GJ6UxN9Rr/brrLZuBewlhul9VjGtcmD7ZvEEsR4EUHUguvheAg90rpAqSE\nc6LOYdGAsUa21iuVLPKPMFwd4MhtrP2JcwHO+oqlUK4939TlZEtyiMWsMJGuugh1\nnrudZ9LSvQKBgBFG83R8Gr928HZGVAk3BotkjOq7irebfpGo5INbxVj0/DbSF9Bv\nLVjgKxCZpog7pxofSu+LAFSuM3LY5RSszTWNEchC/Q3ZYIIqUmoSAhS1Mm3eKfLG\nlbUgKzjq8vuglpl0L/bc7V1vUhn4cFZbzRA+UEFgK5k5Ffd5f5eHXqcJAoGBAJmA\nhVwg9sBHfnlrn3JmMwiCdkxYjrkBxoS0i2JHlFqbt7KFVn2wCI/McY6+fx/Dibxv\nWfSQ+Gzn2B8FDZmulEJsLfED/szKfLBZfBM1Imya5CsBHm24m9G2tibmnaWCa+EO\nO+7aa3uiqo9VXAMCzbmRN7plyTQ2N16zUvw2S4aFAoGARoPL2cJ+7HHcnc4SzKm4\nSu5nLwVPj+IJUwI5SRsRdnUKqo4gaX54p/u/TlA6fm7esRqPu5LK0oIyItVP7wmT\nnUCUFtnE53Rm2QT+BlYg7CewkaRiUHgQR31RDsQP8XtQouy0Si2jG53QLtBm+b7D\nzpqQAUELuiSK67vTd+D96ss=\n-----END PRIVATE KEY-----\nEOF\n\n  cert_data=$(base64 -w0 \"$cert_file\")\n  key_data=$(base64 -w0 \"$key_file\")\n\n  # Set client certificate and client key files\n  kubectl config set-credentials user1 --client-certificate=\"$cert_file\" --client-key=\"$key_file\"\n  expected=\"$cert_file\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user1\")].user.client-certificate}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client certificate did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n  expected=\"$key_file\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user1\")].user.client-key}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client key did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  # Embed client certificate and client key from files\n  kubectl config set-credentials user2 --client-certificate=\"$cert_file\" --client-key=\"$key_file\" --embed-certs=true\n  expected=\"$cert_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user2\")].user.client-certificate-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client certificate data embedded from file did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n  expected=\"$key_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user2\")].user.client-key-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client key data embedded from file did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  # Embed client certificate and client key using process substitution\n  kubectl config set-credentials user3 --client-certificate=<(cat \"$cert_file\") --client-key=<(cat \"$key_file\") --embed-certs=true\n  expected=\"$cert_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user3\")].user.client-certificate-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client certificate data embedded using process substitution did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n  expected=\"$key_data\"\n  actual=$(kubectl config view --raw -o jsonpath='{.users[?(@.name == \"user3\")].user.client-key-data}')\n  if [ \"$expected\" != \"$actual\" ]; then\n    kube::log::error \"Client key data embedded using process substitution did not match the expected value (expected=$expected, actual=$actual)\"\n    exit 1\n  fi\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_client_config_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing client config\"\n\n  # Command\n  # Pre-condition: kubeconfig \"missing\" is not a file or directory\n  output_message=$(! kubectl get pod --context=\"\" --kubeconfig=missing 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"missing: no such file or directory\"\n\n  # Pre-condition: kubeconfig \"missing\" is not a file or directory\n  # Command\n  output_message=$(! kubectl get pod --user=\"\" --kubeconfig=missing 2>&1)\n  # Post-condition: --user contains a valid / empty value, missing config file returns error\n  kube::test::if_has_string \"${output_message}\" \"missing: no such file or directory\"\n  # Command\n  output_message=$(! kubectl get pod --cluster=\"\" --kubeconfig=missing 2>&1)\n  # Post-condition: --cluster contains a \"valid\" value, missing config file returns error\n  kube::test::if_has_string \"${output_message}\" \"missing: no such file or directory\"\n\n  # Pre-condition: context \"missing-context\" does not exist\n  # Command\n  output_message=$(! kubectl get pod --context=\"missing-context\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'context was not found for specified context: missing-context'\n  # Post-condition: invalid or missing context returns error\n\n  # Pre-condition: cluster \"missing-cluster\" does not exist\n  # Command\n  output_message=$(! kubectl get pod --cluster=\"missing-cluster\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'no server found for cluster \"missing-cluster\"'\n  # Post-condition: invalid or missing cluster returns error\n\n  # Pre-condition: user \"missing-user\" does not exist\n  # Command\n  output_message=$(! kubectl get pod --user=\"missing-user\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'auth info \"missing-user\" does not exist'\n  # Post-condition: invalid or missing user returns error\n\n  # test invalid config\n  kubectl config view | sed -E \"s/apiVersion: .*/apiVersion: v-1/g\" > \"${TMPDIR:-/tmp}\"/newconfig.yaml\n  output_message=$(! \"${KUBE_OUTPUT_HOSTBIN}/kubectl\" get pods --context=\"\" --user=\"\" --kubeconfig=\"${TMPDIR:-/tmp}\"/newconfig.yaml 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"error loading config file\"\n\n  output_message=$(! kubectl get pod --kubeconfig=missing-config 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'no such file or directory'\n\n  set +o nounset\n  set +o errexit\n}", "num_lines": 254}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This contains util code for testing kubectl.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Set locale to ensure english responses from kubectl commands\nexport LANG=C\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n# Expects the following has already been done by whatever sources this script\n# source \"${KUBE_ROOT}/hack/lib/init.sh\"\n# source \"${KUBE_ROOT}/hack/lib/test.sh\"\nsource \"${KUBE_ROOT}/test/cmd/apply.sh\"\nsource \"${KUBE_ROOT}/test/cmd/apps.sh\"\nsource \"${KUBE_ROOT}/test/cmd/authentication.sh\"\nsource \"${KUBE_ROOT}/test/cmd/authorization.sh\"\nsource \"${KUBE_ROOT}/test/cmd/batch.sh\"\nsource \"${KUBE_ROOT}/test/cmd/certificate.sh\"\nsource \"${KUBE_ROOT}/test/cmd/convert.sh\"\nsource \"${KUBE_ROOT}/test/cmd/core.sh\"\nsource \"${KUBE_ROOT}/test/cmd/crd.sh\"\nsource \"${KUBE_ROOT}/test/cmd/create.sh\"\nsource \"${KUBE_ROOT}/test/cmd/debug.sh\"\nsource \"${KUBE_ROOT}/test/cmd/delete.sh\"\nsource \"${KUBE_ROOT}/test/cmd/diff.sh\"\nsource \"${KUBE_ROOT}/test/cmd/discovery.sh\"\nsource \"${KUBE_ROOT}/test/cmd/exec.sh\"\nsource \"${KUBE_ROOT}/test/cmd/generic-resources.sh\"\nsource \"${KUBE_ROOT}/test/cmd/get.sh\"\nsource \"${KUBE_ROOT}/test/cmd/kubeconfig.sh\"\nsource \"${KUBE_ROOT}/test/cmd/node-management.sh\"\nsource \"${KUBE_ROOT}/test/cmd/plugins.sh\"\nsource \"${KUBE_ROOT}/test/cmd/proxy.sh\"\nsource \"${KUBE_ROOT}/test/cmd/rbac.sh\"\nsource \"${KUBE_ROOT}/test/cmd/request-timeout.sh\"\nsource \"${KUBE_ROOT}/test/cmd/run.sh\"\nsource \"${KUBE_ROOT}/test/cmd/save-config.sh\"\nsource \"${KUBE_ROOT}/test/cmd/storage.sh\"\nsource \"${KUBE_ROOT}/test/cmd/template-output.sh\"\nsource \"${KUBE_ROOT}/test/cmd/version.sh\"\nsource \"${KUBE_ROOT}/test/cmd/wait.sh\"\n\n\nETCD_HOST=${ETCD_HOST:-127.0.0.1}\nETCD_PORT=${ETCD_PORT:-2379}\nSECURE_API_PORT=${SECURE_API_PORT:-6443}\nAPI_HOST=${API_HOST:-127.0.0.1}\nKUBELET_HEALTHZ_PORT=${KUBELET_HEALTHZ_PORT:-10248}\nSECURE_CTLRMGR_PORT=${SECURE_CTLRMGR_PORT:-10257}\nPROXY_HOST=127.0.0.1 # kubectl only serves on localhost.\n\nIMAGE_NGINX=\"k8s.gcr.io/nginx:1.7.9\"\nexport IMAGE_DEPLOYMENT_R1=\"k8s.gcr.io/nginx:test-cmd\"  # deployment-revision1.yaml\nexport IMAGE_DEPLOYMENT_R2=\"$IMAGE_NGINX\"  # deployment-revision2.yaml\nexport IMAGE_PERL=\"k8s.gcr.io/perl\"\nexport IMAGE_PAUSE_V2=\"k8s.gcr.io/pause:2.0\"\nexport IMAGE_DAEMONSET_R2=\"k8s.gcr.io/pause:latest\"\nexport IMAGE_DAEMONSET_R2_2=\"k8s.gcr.io/nginx:test-cmd\"  # rollingupdate-daemonset-rv2.yaml\nexport IMAGE_STATEFULSET_R1=\"k8s.gcr.io/nginx-slim:0.7\"\nexport IMAGE_STATEFULSET_R2=\"k8s.gcr.io/nginx-slim:0.8\"\n\n# Expose kubectl directly for readability\nPATH=\"${KUBE_OUTPUT_HOSTBIN}\":$PATH\n\n# Define variables for resource types to prevent typos.\nclusterroles=\"clusterroles\"\nconfigmaps=\"configmaps\"\ncsr=\"csr\"\ndeployments=\"deployments\"\nnamespaces=\"namespaces\"\nnodes=\"nodes\"\npersistentvolumeclaims=\"persistentvolumeclaims\"\npersistentvolumes=\"persistentvolumes\"\npods=\"pods\"\npodsecuritypolicies=\"podsecuritypolicies\"\npodtemplates=\"podtemplates\"\nreplicasets=\"replicasets\"\nreplicationcontrollers=\"replicationcontrollers\"\nroles=\"roles\"\nsecrets=\"secrets\"\nserviceaccounts=\"serviceaccounts\"\nservices=\"services\"\nstatefulsets=\"statefulsets\"\nstorageclass=\"storageclass\"\nsubjectaccessreviews=\"subjectaccessreviews\"\ncustomresourcedefinitions=\"customresourcedefinitions\"\ndaemonsets=\"daemonsets\"\ncontrollerrevisions=\"controllerrevisions\"\njob=\"jobs\"\n\n\n# include shell2junit library\nsh2ju=\"${KUBE_ROOT}/third_party/forked/shell2junit/sh2ju.sh\"\nif [[ -f \"${sh2ju}\" ]]; then\n  source \"${sh2ju}\"\nelse\n  echo \"failed to find third_party/forked/shell2junit/sh2ju.sh\"\n  exit 1\nfi\n\n# record_command runs the command and records its output/error messages in junit format\n# it expects the first to be the name of the command\n# Example:\n# record_command run_kubectl_tests\n#\n# WARNING: Variable changes in the command will NOT be effective after record_command returns.\n#          This is because the command runs in subshell.\nfunction record_command() {\n    set +o nounset\n    set +o errexit\n\n    local name=\"$1\"\n    local output=\"${KUBE_JUNIT_REPORT_DIR:-/tmp/junit-results}\"\n    echo \"Recording: ${name}\"\n    echo \"Running command: $*\"\n    juLog -output=\"${output}\" -class=\"test-cmd\" -name=\"${name}\" \"$@\"\n    local exitCode=$?\n    if [[ ${exitCode} -ne 0 ]]; then\n      # Record failures for any non-canary commands\n      if [ \"${name}\" != \"record_command_canary\" ]; then\n        echo \"Error when running ${name}\"\n        foundError=\"${foundError}\"\"${name}\"\", \"\n      fi\n    elif [ \"${name}\" == \"record_command_canary\" ]; then\n      # If the canary command passed, fail\n      echo \"record_command_canary succeeded unexpectedly\"\n      foundError=\"${foundError}\"\"${name}\"\", \"\n    fi\n\n    set -o nounset\n    set -o errexit\n}\n\n# Ensure our record_command stack correctly propagates and detects errexit failures in invoked commands - see https://issue.k8s.io/84871\nfoundError=\"\"\nfunction record_command_canary()\n{\n  set -o nounset\n  set -o errexit\n  bogus-expected-to-fail\n  set +o nounset\n  set +o errexit\n}\nKUBE_JUNIT_REPORT_DIR=$(mktemp -d /tmp/record_command_canary.XXXXX) record_command record_command_canary\nif [[ -n \"${foundError}\" ]]; then\n  echo \"FAILED TESTS: record_command_canary\"\n  exit 1\nfi\n\n# Stops the running kubectl proxy, if there is one.\nfunction stop-proxy()\n{\n  [[ -n \"${PROXY_PORT-}\" ]] && kube::log::status \"Stopping proxy on port ${PROXY_PORT}\"\n  [[ -n \"${PROXY_PID-}\" ]] && kill \"${PROXY_PID}\" 1>&2 2>/dev/null\n  [[ -n \"${PROXY_PORT_FILE-}\" ]] && rm -f \"${PROXY_PORT_FILE}\"\n  PROXY_PID=\n  PROXY_PORT=\n  PROXY_PORT_FILE=\n}\n\n# Starts \"kubect proxy\" to test the client proxy. $1: api_prefix\nfunction start-proxy()\n{\n  stop-proxy\n\n  PROXY_PORT_FILE=$(mktemp proxy-port.out.XXXXX)\n  kube::log::status \"Starting kubectl proxy on random port; output file in ${PROXY_PORT_FILE}; args: ${1-}\"\n\n\n  if [ $# -eq 0 ]; then\n    kubectl proxy --port=0 --www=. 1>\"${PROXY_PORT_FILE}\" 2>&1 &\n  else\n    kubectl proxy --port=0 --www=. --api-prefix=\"$1\" 1>\"${PROXY_PORT_FILE}\" 2>&1 &\n  fi\n  PROXY_PID=$!\n  PROXY_PORT=\n\n  local attempts=0\n  while [[ -z ${PROXY_PORT} ]]; do\n    if (( attempts > 9 )); then\n      kill \"${PROXY_PID}\"\n      kube::log::error_exit \"Couldn't start proxy. Failed to read port after ${attempts} tries. Got: $(cat \"${PROXY_PORT_FILE}\")\"\n    fi\n    sleep .5\n    kube::log::status \"Attempt ${attempts} to read ${PROXY_PORT_FILE}...\"\n    PROXY_PORT=$(sed 's/.*Starting to serve on 127.0.0.1:\\([0-9]*\\)$/\\1/'< \"${PROXY_PORT_FILE}\")\n    attempts=$((attempts+1))\n  done\n\n  kube::log::status \"kubectl proxy running on port ${PROXY_PORT}\"\n\n  # We try checking kubectl proxy 30 times with 1s delays to avoid occasional\n  # failures.\n  if [ $# -eq 0 ]; then\n    kube::util::wait_for_url \"http://127.0.0.1:${PROXY_PORT}/healthz\" \"kubectl proxy\"\n  else\n    kube::util::wait_for_url \"http://127.0.0.1:${PROXY_PORT}/$1/healthz\" \"kubectl proxy --api-prefix=$1\"\n  fi\n}\n\nfunction cleanup()\n{\n  [[ -n \"${APISERVER_PID-}\" ]] && kill \"${APISERVER_PID}\" 1>&2 2>/dev/null\n  [[ -n \"${CTLRMGR_PID-}\" ]] && kill \"${CTLRMGR_PID}\" 1>&2 2>/dev/null\n  [[ -n \"${KUBELET_PID-}\" ]] && kill \"${KUBELET_PID}\" 1>&2 2>/dev/null\n  stop-proxy\n\n  kube::etcd::cleanup\n  rm -rf \"${KUBE_TEMP}\"\n\n  local junit_dir=\"${KUBE_JUNIT_REPORT_DIR:-/tmp/junit-results}\"\n  echo \"junit report dir:\" \"${junit_dir}\"\n\n  kube::log::status \"Clean up complete\"\n}\n\n# Executes curl against the proxy. $1 is the path to use, $2 is the desired\n# return code. Prints a helpful message on failure.\nfunction check-curl-proxy-code()\n{\n  local status\n  local -r address=$1\n  local -r desired=$2\n  local -r full_address=\"${PROXY_HOST}:${PROXY_PORT}${address}\"\n  status=$(curl -w \"%{http_code}\" --silent --output /dev/null \"${full_address}\")\n  if [ \"${status}\" == \"${desired}\" ]; then\n    return 0\n  fi\n  echo \"For address ${full_address}, got ${status} but wanted ${desired}\"\n  return 1\n}\n\n# TODO: Remove this function when we do the retry inside the kubectl commands. See #15333.\nfunction kubectl-with-retry()\n{\n  ERROR_FILE=\"${KUBE_TEMP}/kubectl-error\"\n  preserve_err_file=${PRESERVE_ERR_FILE:-false}\n  for count in {0..3}; do\n    kubectl \"$@\" 2> \"${ERROR_FILE}\" || true\n    if grep -q \"the object has been modified\" \"${ERROR_FILE}\"; then\n      kube::log::status \"retry $1, error: $(cat \"${ERROR_FILE}\")\"\n      rm \"${ERROR_FILE}\"\n      sleep $((2**count))\n    else\n      if [ \"$preserve_err_file\" != true ] ; then\n        rm \"${ERROR_FILE}\"\n      fi\n      break\n    fi\n  done\n}\n\n# Waits for the pods with the given label to match the list of names. Don't call\n# this function unless you know the exact pod names, or expect no pods.\n# $1: label to match\n# $2: list of pod names sorted by name\n# Example invocation:\n# wait-for-pods-with-label \"app=foo\" \"nginx-0nginx-1\"\nfunction wait-for-pods-with-label()\n{\n  local i\n  for i in $(seq 1 10); do\n    kubeout=$(kubectl get po -l \"$1\" --output=go-template --template='{{range.items}}{{.metadata.name}}{{end}}' --sort-by metadata.name \"${kube_flags[@]}\")\n    if [[ $kubeout = \"$2\" ]]; then\n        return\n    fi\n    echo Waiting for pods: \"$2\", found \"$kubeout\"\n    sleep \"$i\"\n  done\n  kube::log::error_exit \"Timeout waiting for pods with label $1\"\n}\n\n# Code to be run before running the tests.\nsetup() {\n  kube::util::trap_add cleanup EXIT SIGINT\n  kube::util::ensure-temp-dir\n  # ensure ~/.kube/config isn't loaded by tests\n  HOME=\"${KUBE_TEMP}\"\n\n  kube::etcd::start\n\n  # Find a standard sed instance for use with edit scripts\n  kube::util::ensure-gnu-sed\n\n  kube::log::status \"Building kubectl\"\n  make -C \"${KUBE_ROOT}\" WHAT=\"cmd/kubectl cmd/kubectl-convert\"\n\n  # Check kubectl\n  kube::log::status \"Running kubectl with no options\"\n  \"${KUBE_OUTPUT_HOSTBIN}/kubectl\"\n\n  # TODO: we need to note down the current default namespace and set back to this\n  # namespace after the tests are done.\n  CONTEXT=\"test\"\n  kubectl config set-credentials test-admin --token admin-token\n  kubectl config set-cluster local --insecure-skip-tls-verify --server \"https://127.0.0.1:${SECURE_API_PORT}\"\n  kubectl config set-context \"${CONTEXT}\" --user test-admin --cluster local\n  kubectl config use-context \"${CONTEXT}\"\n  kubectl config view\n\n  kube::log::status \"Setup complete\"\n}\n\n# Runs all kubectl tests.\n# Requires an env var SUPPORTED_RESOURCES which is a comma separated list of\n# resources for which tests should be run.\nrunTests() {\n  foundError=\"\"\n\n  if [ -z \"${SUPPORTED_RESOURCES:-}\" ]; then\n    echo \"Need to set SUPPORTED_RESOURCES env var. It is a list of resources that are supported and hence should be tested. Set it to (*) to test all resources\"\n    exit 1\n  fi\n  kube::log::status \"Checking kubectl version\"\n  kubectl version\n\n  # Generate a random namespace name, based on the current time (to make\n  # debugging slightly easier) and a random number. Don't use `date +%N`\n  # because that doesn't work on OSX.\n  create_and_use_new_namespace() {\n    local ns_name\n    ns_name=\"namespace-$(date +%s)-${RANDOM}\"\n    kube::log::status \"Creating namespace ${ns_name}\"\n    kubectl create namespace \"${ns_name}\"\n    kubectl config set-context \"${CONTEXT}\" --namespace=\"${ns_name}\"\n  }\n\n  kube_flags=( '-s' \"https://127.0.0.1:${SECURE_API_PORT}\" '--insecure-skip-tls-verify' )\n\n  kube_flags_without_token=( \"${kube_flags[@]}\" )\n\n  # token defined in hack/testdata/auth-tokens.csv\n  kube_flags_with_token=( \"${kube_flags_without_token[@]}\" '--token=admin-token' )\n\n  if [[ -z \"${ALLOW_SKEW:-}\" ]]; then\n    kube_flags+=('--match-server-version')\n    kube_flags_with_token+=('--match-server-version')\n  fi\n  if kube::test::if_supports_resource \"${nodes}\" ; then\n    [ \"$(kubectl get nodes -o go-template='{{ .apiVersion }}' \"${kube_flags[@]}\")\" == \"v1\" ]\n  fi\n\n  # Define helper variables for fields to prevent typos.\n  # They will be used in some other files under test/cmd,\n  # Let's export them as https://github.com/koalaman/shellcheck/wiki/SC2034 suggested.\n  export id_field=\".metadata.name\"\n  export labels_field=\".metadata.labels\"\n  export annotations_field=\".metadata.annotations\"\n  export service_selector_field=\".spec.selector\"\n  export rc_replicas_field=\".spec.replicas\"\n  export rc_status_replicas_field=\".status.replicas\"\n  export rc_container_image_field=\".spec.template.spec.containers\"\n  export rs_replicas_field=\".spec.replicas\"\n  export port_field=\"(index .spec.ports 0).port\"\n  export port_name=\"(index .spec.ports 0).name\"\n  export second_port_field=\"(index .spec.ports 1).port\"\n  export second_port_name=\"(index .spec.ports 1).name\"\n  export image_field=\"(index .spec.containers 0).image\"\n  export pod_container_name_field=\"(index .spec.containers 0).name\"\n  export container_name_field=\"(index .spec.template.spec.containers 0).name\"\n  export hpa_min_field=\".spec.minReplicas\"\n  export hpa_max_field=\".spec.maxReplicas\"\n  export hpa_cpu_field=\".spec.targetCPUUtilizationPercentage\"\n  export template_labels=\".spec.template.metadata.labels.name\"\n  export statefulset_replicas_field=\".spec.replicas\"\n  export statefulset_observed_generation=\".status.observedGeneration\"\n  export job_parallelism_field=\".spec.parallelism\"\n  export deployment_replicas=\".spec.replicas\"\n  export secret_data=\".data\"\n  export secret_type=\".type\"\n  export change_cause_annotation='.*kubernetes.io/change-cause.*'\n  export pdb_min_available=\".spec.minAvailable\"\n  export pdb_max_unavailable=\".spec.maxUnavailable\"\n  export generation_field=\".metadata.generation\"\n  export container_len=\"(len .spec.template.spec.containers)\"\n  export image_field0=\"(index .spec.template.spec.containers 0).image\"\n  export image_field1=\"(index .spec.template.spec.containers 1).image\"\n\n  # Make sure \"default\" namespace exists.\n  if kube::test::if_supports_resource \"${namespaces}\" ; then\n    output_message=$(kubectl get \"${kube_flags[@]}\" namespaces)\n    if ! grep -q \"default\" <<< \"${output_message}\"; then\n      # Create default namespace\n      kubectl create \"${kube_flags[@]}\" ns default\n    fi\n  fi\n\n  # Make sure \"kubernetes\" service exists.\n  if kube::test::if_supports_resource \"${services}\" ; then\n    # Attempt to create the kubernetes service, tolerating failure (since it might already exist)\n    kubectl create \"${kube_flags[@]}\" -f hack/testdata/kubernetes-service.yaml || true\n    # Require the service to exist (either we created it or the API server did)\n    kubectl get \"${kube_flags[@]}\" -f hack/testdata/kubernetes-service.yaml\n  fi\n\n  cleanup_tests(){\n    kube::test::clear_all\n    if [[ -n \"${foundError}\" ]]; then\n      echo \"FAILED TESTS: \"\"${foundError}\"\n      exit 1\n    fi\n  }\n\n  if [[ -n \"${WHAT-}\" ]]; then\n    for pkg in ${WHAT}\n    do\n      # running of kubeadm is captured in hack/make-targets/test-cmd.sh\n      if [[ \"${pkg}\" != \"kubeadm\" ]]; then\n        record_command \"run_${pkg}_tests\"\n      fi\n    done\n    cleanup_tests\n    return\n  fi\n\n  #########################\n  # Kubectl version #\n  #########################\n\n  record_command run_kubectl_version_tests\n\n  #######################\n  # kubectl config set #\n  #######################\n\n  record_command run_kubectl_config_set_tests\n\n  ##############################\n  # kubectl config set-cluster #\n  ##############################\n\n  record_command run_kubectl_config_set_cluster_tests\n\n  ##################################\n  # kubectl config set-credentials #\n  ##################################\n\n  record_command run_kubectl_config_set_credentials_tests\n\n  #######################\n  # kubectl local proxy #\n  #######################\n\n  record_command run_kubectl_local_proxy_tests\n\n  #########################\n  # RESTMapper evaluation #\n  #########################\n\n  record_command run_RESTMapper_evaluation_tests\n\n  # find all resources\n  kubectl \"${kube_flags[@]}\" api-resources\n  # find all namespaced resources that support list by name and get them\n  kubectl \"${kube_flags[@]}\" api-resources --verbs=list --namespaced -o name | xargs -n 1 kubectl \"${kube_flags[@]}\" get -o name\n\n  ################\n  # Cluster Role #\n  ################\n\n  if kube::test::if_supports_resource \"${clusterroles}\" ; then\n    record_command run_clusterroles_tests\n  fi\n\n  ########\n  # Role #\n  ########\n  if kube::test::if_supports_resource \"${roles}\" ; then\n      record_command run_role_tests\n  fi\n\n  #########################\n  # Assert short name     #\n  #########################\n\n  record_command run_assert_short_name_tests\n\n  #########################\n  # Assert categories     #\n  #########################\n\n  ## test if a category is exported during discovery\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_assert_categories_tests\n  fi\n\n  ###########################\n  # POD creation / deletion #\n  ###########################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_pod_tests\n  fi\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_save_config_tests\n  fi\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_create_error_tests\n  fi\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_apply_tests\n    record_command run_kubectl_server_side_apply_tests\n    record_command run_kubectl_run_tests\n    record_command run_kubectl_create_filter_tests\n  fi\n\n  if kube::test::if_supports_resource \"${deployments}\" ; then\n    record_command run_kubectl_apply_deployments_tests\n  fi\n\n  ################\n  # Kubectl diff #\n  ################\n  record_command run_kubectl_diff_tests\n  record_command run_kubectl_diff_same_names\n\n  ###############\n  # Kubectl get #\n  ###############\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_get_tests\n  fi\n\n  ################\n  # Kubectl exec #\n  ################\n\n  if kube::test::if_supports_resource \"${pods}\"; then\n    record_command run_kubectl_exec_pod_tests\n    if kube::test::if_supports_resource \"${replicasets}\" && kube::test::if_supports_resource \"${configmaps}\"; then\n      record_command run_kubectl_exec_resource_name_tests\n    fi\n  fi\n\n  ######################\n  # Create             #\n  ######################\n  if kube::test::if_supports_resource \"${secrets}\" ; then\n    record_command run_create_secret_tests\n  fi\n  if kube::test::if_supports_resource \"${deployments}\"; then\n    record_command run_kubectl_create_kustomization_directory_tests\n  fi\n\n  ######################\n  # Convert            #\n  ######################\n  if kube::test::if_supports_resource \"${deployments}\"; then\n    record_command run_convert_tests\n  fi\n\n  ######################\n  # Delete             #\n  ######################\n  if kube::test::if_supports_resource \"${configmaps}\" ; then\n    record_command run_kubectl_delete_allnamespaces_tests\n  fi\n\n  ##################\n  # Global timeout #\n  ##################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_request_timeout_tests\n  fi\n\n  #####################################\n  # CustomResourceDefinitions         #\n  #####################################\n\n  # customresourcedefinitions cleanup after themselves.\n  if kube::test::if_supports_resource \"${customresourcedefinitions}\" ; then\n    record_command run_crd_tests\n  fi\n\n  #####################################\n  # Recursive Resources via directory #\n  #####################################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    run_recursive_resources_tests\n  fi\n\n\n  ##############\n  # Namespaces #\n  ##############\n  if kube::test::if_supports_resource \"${namespaces}\" ; then\n    record_command run_namespace_tests\n  fi\n\n\n  ###########\n  # Secrets #\n  ###########\n  if kube::test::if_supports_resource \"${namespaces}\" ; then\n    if kube::test::if_supports_resource \"${secrets}\" ; then\n      record_command run_secrets_test\n    fi\n  fi\n\n\n  ######################\n  # ConfigMap          #\n  ######################\n\n  if kube::test::if_supports_resource \"${namespaces}\"; then\n    if kube::test::if_supports_resource \"${configmaps}\" ; then\n      record_command run_configmap_tests\n    fi\n  fi\n\n  ####################\n  # Client Config    #\n  ####################\n\n  record_command run_client_config_tests\n\n  ####################\n  # Service Accounts #\n  ####################\n\n  if kube::test::if_supports_resource \"${namespaces}\" && kube::test::if_supports_resource \"${serviceaccounts}\" ; then\n    record_command run_service_accounts_tests\n  fi\n\n  ####################\n  # Job              #\n  ####################\n\n  if kube::test::if_supports_resource \"${job}\" ; then\n    record_command run_job_tests\n    record_command run_create_job_tests\n  fi\n\n  #################\n  # Pod templates #\n  #################\n\n  if kube::test::if_supports_resource \"${podtemplates}\" ; then\n    record_command run_pod_templates_tests\n  fi\n\n  ############\n  # Services #\n  ############\n\n  if kube::test::if_supports_resource \"${services}\" ; then\n    record_command run_service_tests\n  fi\n\n  ##################\n  # DaemonSets     #\n  ##################\n\n  if kube::test::if_supports_resource \"${daemonsets}\" ; then\n    record_command run_daemonset_tests\n    if kube::test::if_supports_resource \"${controllerrevisions}\"; then\n      record_command run_daemonset_history_tests\n    fi\n  fi\n\n  ###########################\n  # Replication controllers #\n  ###########################\n\n  if kube::test::if_supports_resource \"${namespaces}\" ; then\n    if kube::test::if_supports_resource \"${replicationcontrollers}\" ; then\n      record_command run_rc_tests\n    fi\n  fi\n\n  ######################\n  # Deployments       #\n  ######################\n\n  if kube::test::if_supports_resource \"${deployments}\" ; then\n    record_command run_deployment_tests\n  fi\n\n  ######################\n  # Replica Sets       #\n  ######################\n\n  if kube::test::if_supports_resource \"${replicasets}\" ; then\n    record_command run_rs_tests\n  fi\n\n  #################\n  # Stateful Sets #\n  #################\n\n  if kube::test::if_supports_resource \"${statefulsets}\" ; then\n    record_command run_stateful_set_tests\n    if kube::test::if_supports_resource \"${controllerrevisions}\"; then\n      record_command run_statefulset_history_tests\n    fi\n  fi\n\n  ######################\n  # Lists              #\n  ######################\n\n  if kube::test::if_supports_resource \"${services}\" ; then\n    if kube::test::if_supports_resource \"${deployments}\" ; then\n      record_command run_lists_tests\n    fi\n  fi\n\n\n  ######################\n  # Multiple Resources #\n  ######################\n  if kube::test::if_supports_resource \"${services}\" ; then\n    if kube::test::if_supports_resource \"${replicationcontrollers}\" ; then\n      record_command run_multi_resources_tests\n    fi\n  fi\n\n  ######################\n  # Persistent Volumes #\n  ######################\n\n  if kube::test::if_supports_resource \"${persistentvolumes}\" ; then\n    record_command run_persistent_volumes_tests\n  fi\n\n  ############################\n  # Persistent Volume Claims #\n  ############################\n\n  if kube::test::if_supports_resource \"${persistentvolumeclaims}\" ; then\n    record_command run_persistent_volume_claims_tests\n  fi\n\n  ############################\n  # Storage Classes #\n  ############################\n\n  if kube::test::if_supports_resource \"${storageclass}\" ; then\n    record_command run_storage_class_tests\n  fi\n\n  #########\n  # Nodes #\n  #########\n\n  if kube::test::if_supports_resource \"${nodes}\" ; then\n    record_command run_nodes_tests\n  fi\n\n  ########################\n  # Authentication\n  ########################\n\n  record_command run_exec_credentials_tests\n  record_command run_exec_credentials_interactive_tests\n\n  ########################\n  # authorization.k8s.io #\n  ########################\n\n  if kube::test::if_supports_resource \"${subjectaccessreviews}\" ; then\n    record_command run_authorization_tests\n  fi\n\n  # kubectl auth can-i\n  # kube-apiserver is started with authorization mode AlwaysAllow, so kubectl can-i always returns yes\n  if kube::test::if_supports_resource \"${subjectaccessreviews}\" ; then\n    output_message=$(kubectl auth can-i '*' '*' 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"yes\"\n\n    output_message=$(kubectl auth can-i get pods --subresource=log 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"yes\"\n\n    output_message=$(kubectl auth can-i get invalid_resource 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"the server doesn't have a resource type\"\n\n    output_message=$(kubectl auth can-i get /logs/ 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"yes\"\n\n    output_message=$(! kubectl auth can-i get /logs/ --subresource=log 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"subresource can not be used with NonResourceURL\"\n\n    output_message=$(kubectl auth can-i list jobs.batch/bar -n foo --quiet 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_empty_string \"${output_message}\"\n\n    output_message=$(kubectl auth can-i get pods --subresource=log 2>&1 \"${kube_flags[@]}\"; echo $?)\n    kube::test::if_has_string \"${output_message}\" '0'\n\n    output_message=$(kubectl auth can-i get pods --subresource=log --quiet 2>&1 \"${kube_flags[@]}\"; echo $?)\n    kube::test::if_has_string \"${output_message}\" '0'\n\n    # kubectl auth can-i get '*' does not warn about namespaced scope or print an error\n    output_message=$(kubectl auth can-i get '*' 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_not_string \"${output_message}\" \"Warning\"\n\n    # kubectl auth can-i get foo does not print a namespaced warning message, and only prints a single lookup error\n    output_message=$(kubectl auth can-i get foo 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"Warning: the server doesn't have a resource type 'foo'\"\n    kube::test::if_has_not_string \"${output_message}\" \"Warning: resource 'foo' is not namespace scoped\"\n\n    # kubectl auth can-i get pods does not print a namespaced warning message or a lookup error\n    output_message=$(kubectl auth can-i get pods 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_not_string \"${output_message}\" \"Warning\"\n\n    # kubectl auth can-i get nodes prints a namespaced warning message\n    output_message=$(kubectl auth can-i get nodes 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_string \"${output_message}\" \"Warning: resource 'nodes' is not namespace scoped\"\n\n    # kubectl auth can-i get nodes --all-namespaces does not print a namespaced warning message\n    output_message=$(kubectl auth can-i get nodes --all-namespaces 2>&1 \"${kube_flags[@]}\")\n    kube::test::if_has_not_string \"${output_message}\" \"Warning: resource 'nodes' is not namespace scoped\"\n  fi\n\n  # kubectl auth reconcile\n  if kube::test::if_supports_resource \"${clusterroles}\" ; then\n    # dry-run command\n    kubectl auth reconcile --dry-run=client \"${kube_flags[@]}\" -f test/fixtures/pkg/kubectl/cmd/auth/rbac-resource-plus.yaml\n    kube::test::get_object_assert 'rolebindings -n some-other-random -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    kube::test::get_object_assert 'roles -n some-other-random -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    kube::test::get_object_assert 'clusterrolebindings -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n    kube::test::get_object_assert 'clusterroles -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n    # command\n    kubectl auth reconcile \"${kube_flags[@]}\" -f test/fixtures/pkg/kubectl/cmd/auth/rbac-resource-plus.yaml\n    kube::test::get_object_assert 'rolebindings -n some-other-random -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" 'testing-RB:'\n    kube::test::get_object_assert 'roles -n some-other-random -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" 'testing-R:'\n    kube::test::get_object_assert 'clusterrolebindings -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" 'testing-CRB:'\n    kube::test::get_object_assert 'clusterroles -l test-cmd=auth' \"{{range.items}}{{$id_field}}:{{end}}\" 'testing-CR:'\n\n    failure_message=$(! kubectl auth reconcile \"${kube_flags[@]}\" -f test/fixtures/pkg/kubectl/cmd/auth/rbac-v1beta1.yaml 2>&1 )\n    kube::test::if_has_string \"${failure_message}\" 'only rbac.authorization.k8s.io/v1 is supported'\n\n    kubectl delete \"${kube_flags[@]}\" rolebindings,role,clusterroles,clusterrolebindings -n some-other-random -l test-cmd=auth\n  fi\n\n  #####################\n  # Retrieve multiple #\n  #####################\n\n  if kube::test::if_supports_resource \"${nodes}\" ; then\n    if kube::test::if_supports_resource \"${services}\" ; then\n      record_command run_retrieve_multiple_tests\n    fi\n  fi\n\n\n  #####################\n  # Resource aliasing #\n  #####################\n\n  if kube::test::if_supports_resource \"${services}\" ; then\n    if kube::test::if_supports_resource \"${replicationcontrollers}\" ; then\n      record_command run_resource_aliasing_tests\n    fi\n  fi\n\n  ###########\n  # Explain #\n  ###########\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_explain_tests\n  fi\n\n\n  ###########\n  # Swagger #\n  ###########\n\n  record_command run_swagger_tests\n\n  #####################\n  # Kubectl --sort-by #\n  #####################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_sort_by_tests\n  fi\n\n  ############################\n  # Kubectl --all-namespaces #\n  ############################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    if kube::test::if_supports_resource \"${nodes}\" ; then\n      record_command run_kubectl_all_namespace_tests\n    fi\n  fi\n\n  ############################\n  # Kubectl deprecated APIs  #\n  ############################\n\n  if kube::test::if_supports_resource \"${podsecuritypolicies}\" ; then\n    run_deprecated_api_tests\n  fi\n\n\n  ######################\n  # kubectl --template #\n  ######################\n\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_template_output_tests\n  fi\n\n  ################\n  # Certificates #\n  ################\n\n  if kube::test::if_supports_resource \"${csr}\" ; then\n    record_command run_certificates_tests\n  fi\n\n  ######################\n  # Cluster Management #\n  ######################\n  if kube::test::if_supports_resource \"${nodes}\" ; then\n    record_command run_cluster_management_tests\n  fi\n\n  ###########\n  # Plugins #\n  ###########\n\n  record_command run_plugins_tests\n\n\n  #################\n  # Impersonation #\n  #################\n  record_command run_impersonation_tests\n\n  ####################\n  # kubectl wait     #\n  ####################\n\n  record_command run_wait_tests\n\n  ####################\n  # kubectl debug    #\n  ####################\n  if kube::test::if_supports_resource \"${pods}\" ; then\n    record_command run_kubectl_debug_pod_tests\n  fi\n  if kube::test::if_supports_resource \"${nodes}\" ; then\n    record_command run_kubectl_debug_node_tests\n  fi\n\n  cleanup_tests\n}\n", "num_lines": 975}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\ncreate_test_pods(){\n  # create test pods we can work with\n  kubectl create -f - \"${kube_flags[@]:?}\" << __EOF__\n{\n  \"kind\": \"Pod\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"test-pod-1\",\n    \"labels\": {\n      \"e\": \"f\",\n      \"type\": \"test-pod\"\n    }\n  },\n  \"spec\": {\n    \"nodeName\": \"127.0.0.1\",\n    \"containers\": [\n      {\n        \"name\": \"container-1\",\n        \"resources\": {},\n        \"image\": \"test-image\"\n      }\n    ]\n  }\n}\n__EOF__\n\n  kubectl create -f - \"${kube_flags[@]}\" << __EOF__\n{\n  \"kind\": \"Pod\",\n  \"apiVersion\": \"v1\",\n  \"metadata\": {\n    \"name\": \"test-pod-2\",\n    \"labels\": {\n      \"c\": \"d\",\n      \"type\": \"test-pod\"\n    }\n  },\n  \"spec\": {\n    \"nodeName\": \"127.0.0.1\",\n    \"containers\": [\n      {\n        \"name\": \"container-1\",\n        \"resources\": {},\n        \"image\": \"test-image\"\n      }\n    ]\n  }\n}\n__EOF__\n}\n\ndelete_test_pods() {\n  # need to use --force because node is unready\n  kubectl delete pod/test-pod-1 --force --ignore-not-found\n  kubectl delete pod/test-pod-2 --force --ignore-not-found\n}\n\nrun_cluster_management_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing cluster-management commands\"\n\n  kube::test::get_object_assert nodes \"{{range.items}}{{${id_field:?}}}:{{end}}\" '127.0.0.1:'\n\n  create_test_pods\n\n  # taint/untaint\n  # Pre-condition: node doesn't have dedicated=foo:PreferNoSchedule taint\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"\" # expect no output\n  # Dry-run\n  kubectl taint node 127.0.0.1 --dry-run=client dedicated=foo:PreferNoSchedule\n  kubectl taint node 127.0.0.1 --dry-run=server dedicated=foo:PreferNoSchedule\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"\" # expect no output\n  # taint can add a taint (<key>=<value>:<effect>)\n  kubectl taint node 127.0.0.1 dedicated=foo:PreferNoSchedule\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"dedicated=foo:PreferNoSchedule\"\n  # taint can remove a taint\n  kubectl taint node 127.0.0.1 dedicated-\n  # taint can add a taint (<key>:<effect>)\n  kubectl taint node 127.0.0.1 dedicated:PreferNoSchedule\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"dedicated=<no value>:PreferNoSchedule\"\n  # Node has field manager for kubectl taint\n  output_message=$(kubectl get node 127.0.0.1 --show-managed-fields -o=jsonpath='{.metadata.managedFields[*].manager}' \"${kube_flags[@]:?}\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-taint'\n  # Dry-run remove a taint\n  kubectl taint node 127.0.0.1 --dry-run=client dedicated-\n  kubectl taint node 127.0.0.1 --dry-run=server dedicated-\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"dedicated=<no value>:PreferNoSchedule\"\n  # taint can remove a taint\n  kubectl taint node 127.0.0.1 dedicated-\n  # Post-condition: node doesn't have dedicated=foo:PreferNoSchedule taint\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{range .spec.taints}}{{if eq .key \\\"dedicated\\\"}}{{.key}}={{.value}}:{{.effect}}{{end}}{{end}}' \"\" # expect no output\n\n  ### kubectl cordon update with --dry-run does not mark node unschedulable\n  # Pre-condition: node is schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n  kubectl cordon \"127.0.0.1\" --dry-run=client\n  kubectl cordon \"127.0.0.1\" --dry-run=server\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n  ### kubectl drain update with --dry-run does not mark node unschedulable\n  # Pre-condition: node is schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n  kubectl drain \"127.0.0.1\" --dry-run=client --force\n  kubectl drain \"127.0.0.1\" --dry-run=server --force\n  # Post-condition: node still exists, node is still schedulable\n  kube::test::get_object_assert nodes \"{{range.items}}{{$id_field}}:{{end}}\" '127.0.0.1:'\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n  ### kubectl drain with --pod-selector only evicts pods that match the given selector\n  # Pre-condition: node is schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n  # Pre-condition: test-pod-1 and test-pod-2 exist\n  kube::test::get_object_assert \"pods\" \"{{range .items}}{{.metadata.name}},{{end}}\" 'test-pod-1,test-pod-2,'\n  # dry-run command\n  kubectl drain \"127.0.0.1\" --pod-selector 'e in (f)' --dry-run=client --force\n  kubectl drain \"127.0.0.1\" --pod-selector 'e in (f)' --dry-run=server --force\n  kube::test::get_object_assert \"pods\" \"{{range .items}}{{.metadata.name}},{{end}}\" 'test-pod-1,test-pod-2,'\n  # command - need --force because pod is unmanaged and --skip-wait-for-delete-timeout because node is unready\n  response=$(kubectl drain \"127.0.0.1\" --force --pod-selector 'e in (f)' --skip-wait-for-delete-timeout=1)\n  kube::test::if_has_string \"${response}\" \"evicting pod .*/test-pod-1\"\n  # only \"test-pod-1\" should have been matched and deleted - test-pod-2 should not have a deletion timestamp\n  kube::test::get_object_assert \"pods/test-pod-2\" \"{{.metadata.deletionTimestamp}}\" '<no value>'\n  # Post-condition: recreate test pods -- they have deletionTimestamp set but will not go away because node is unready\n  delete_test_pods\n  create_test_pods\n  # Post-condition: node is schedulable\n  kubectl uncordon \"127.0.0.1\"\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n  ### kubectl uncordon update with --dry-run is a no-op\n  # Pre-condition: node is already schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n  response=$(kubectl uncordon \"127.0.0.1\" --dry-run=client)\n  kube::test::if_has_string \"${response}\" 'already uncordoned'\n  response=$(kubectl uncordon \"127.0.0.1\" --dry-run=server)\n  kube::test::if_has_string \"${response}\" 'already uncordoned'\n  # Post-condition: node is still schedulable\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n  ### kubectl drain command fails when both --selector and a node argument are given\n  # Pre-condition: node exists and contains label test=label\n  kubectl label node \"127.0.0.1\" \"test=label\"\n  kube::test::get_object_assert \"nodes 127.0.0.1\" '{{.metadata.labels.test}}' 'label'\n  response=$(! kubectl drain \"127.0.0.1\" --selector test=label 2>&1)\n  kube::test::if_has_string \"${response}\" 'cannot specify both a node name'\n\n   ### Test kubectl drain chunk size\n   # Pre-condition: node exists and contains label test=label\n   kube::test::get_object_assert \"nodes 127.0.0.1\" '{{.metadata.labels.test}}' 'label'\n   # Pre-condition: node is schedulable\n   kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n   # Pre-condition: test-pod-1 and test-pod-2 exist\n   kube::test::get_object_assert \"pods\" \"{{range .items}}{{.metadata.name}},{{end}}\" 'test-pod-1,test-pod-2,'\n   # command - need to use force because pods are unmanaged, dry run (or skip-wait) because node is unready\n   output_message=$(kubectl --v=6 drain --force --pod-selector type=test-pod --selector test=label --chunk-size=1 --dry-run=client 2>&1 \"${kube_flags[@]}\")\n   # Post-condition: Check if we get a limit on node, and both limit and continue on pods\n   kube::test::if_has_string \"${output_message}\" \"/v1/nodes?labelSelector=test%3Dlabel&limit=1 200 OK\"\n   kube::test::if_has_string \"${output_message}\" \"/v1/pods?fieldSelector=spec.nodeName%3D127.0.0.1&labelSelector=type%3Dtest-pod&limit=1 200 OK\"\n   kube::test::if_has_string \"${output_message}\" \"/v1/pods?continue=.*&fieldSelector=spec.nodeName%3D127.0.0.1&labelSelector=type%3Dtest-pod&limit=1 200 OK\"\n   # Post-condition: Check we evict multiple pages worth of pods\n   kube::test::if_has_string \"${output_message}\" \"evicting pod .*/test-pod-1\"\n   kube::test::if_has_string \"${output_message}\" \"evicting pod .*/test-pod-2\"\n   # Post-condition: node is schedulable\n   kubectl uncordon \"127.0.0.1\"\n   kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" '<no value>'\n\n   ### Test kubectl drain chunk size defaults to 500\n   output_message=$(kubectl --v=6 drain --force --selector test=label --dry-run=client 2>&1 \"${kube_flags[@]}\")\n   # Post-condition: Check if we get a limit\n   kube::test::if_has_string \"${output_message}\" \"/v1/nodes?labelSelector=test%3Dlabel&limit=500 200 OK\"\n   kube::test::if_has_string \"${output_message}\" \"/v1/pods?fieldSelector=spec.nodeName%3D127.0.0.1&limit=500 200 OK\"\n\n  ### kubectl cordon command fails when no arguments are passed\n  # Pre-condition: node exists\n  response=$(! kubectl cordon 2>&1)\n  kube::test::if_has_string \"${response}\" 'error\\: USAGE\\: cordon NODE'\n\n  ### kubectl cordon selects no nodes with an empty --selector=\n  # Pre-condition: node \"127.0.0.1\" is uncordoned\n  kubectl uncordon \"127.0.0.1\"\n  response=$(! kubectl cordon --selector= 2>&1)\n  kube::test::if_has_string \"${response}\" 'must provide one or more resources'\n  # test=label matches our node\n  response=$(kubectl cordon --selector test=label)\n  kube::test::if_has_string \"${response}\" 'node/127.0.0.1 cordoned'\n  # invalid=label does not match any nodes\n  response=$(kubectl cordon --selector invalid=label)\n  kube::test::if_has_not_string \"${response}\" 'cordoned'\n  # Post-condition: node \"127.0.0.1\" is cordoned\n  kube::test::get_object_assert \"nodes 127.0.0.1\" \"{{.spec.unschedulable}}\" 'true'\n\n  # Clean up test pods\n  delete_test_pods\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 221}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_plugins_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl plugins\"\n\n  # Create a folder which only contains our kubectl executable\n  TEMP_PATH=$(mktemp -d /tmp/tmp-kubectl-path-XXXXX)\n  ln -s \"$(which kubectl)\" \"${TEMP_PATH}/kubectl\"\n\n  # test plugins that overwrite existing kubectl commands\n  output_message=$(! PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins/version\" kubectl plugin list 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'kubectl-version overwrites existing command: \"kubectl version\"'\n\n  # test plugins that overwrite similarly-named plugins\n  output_message=$(! PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins:test/fixtures/pkg/kubectl/plugins/foo\" kubectl plugin list 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'test/fixtures/pkg/kubectl/plugins/foo/kubectl-foo is overshadowed by a similarly named plugin'\n\n  # test plugins with no warnings\n  output_message=$(PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins\" kubectl plugin list 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'plugins are available'\n\n  # no plugins\n  output_message=$(! PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins/empty\" kubectl plugin list 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'unable to find any kubectl plugins in your PATH'\n\n  # attempt to run a plugin in the user's PATH\n  output_message=$(PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins\" kubectl foo)\n  kube::test::if_has_string \"${output_message}\" 'plugin foo'\n\n  # check arguments passed to the plugin\n  output_message=$(PATH=${PATH}:\"test/fixtures/pkg/kubectl/plugins/bar\" kubectl bar arg1)\n  kube::test::if_has_string \"${output_message}\" 'test/fixtures/pkg/kubectl/plugins/bar/kubectl-bar arg1'\n\n  # ensure that a kubectl command supersedes a plugin that overshadows it\n  output_message=$(PATH=${TEMP_PATH}:\"test/fixtures/pkg/kubectl/plugins/version\" kubectl version --client)\n  kube::test::if_has_string \"${output_message}\" 'Client Version'\n  kube::test::if_has_not_string \"${output_message}\" 'overshadows an existing plugin'\n\n  rm -fr \"${TEMP_PATH}\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 65}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_local_proxy_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl local proxy\"\n\n  start-proxy\n  check-curl-proxy-code /api/kubernetes 404\n  check-curl-proxy-code /api/v1/namespaces 200\n  if kube::test::if_supports_resource \"metrics\" ; then\n    check-curl-proxy-code /metrics 200\n  fi\n  if kube::test::if_supports_resource \"static\" ; then\n    check-curl-proxy-code /static/ 200\n  fi\n  stop-proxy\n\n  # Make sure the in-development api is accessible by default\n  start-proxy\n  check-curl-proxy-code /apis 200\n  check-curl-proxy-code /apis/apps/ 200\n  stop-proxy\n\n  # Custom paths let you see everything.\n  start-proxy /custom\n  check-curl-proxy-code /custom/api/kubernetes 404\n  check-curl-proxy-code /custom/api/v1/namespaces 200\n  if kube::test::if_supports_resource \"metrics\" ; then\n    check-curl-proxy-code /custom/metrics 200\n  fi\n  check-curl-proxy-code /custom/api/v1/namespaces 200\n  stop-proxy\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_clusterroles_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing clusterroles\"\n\n  # make sure the server was properly bootstrapped with clusterroles and bindings\n  kube::test::get_object_assert clusterroles/cluster-admin \"{{.metadata.name}}\" 'cluster-admin'\n  kube::test::get_object_assert clusterrolebindings/cluster-admin \"{{.metadata.name}}\" 'cluster-admin'\n\n  # Pre-condition: no ClusterRole pod-admin exists\n  output_message=$(! kubectl get clusterrole pod-admin 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'clusterroles.rbac.authorization.k8s.io \"pod-admin\" not found'\n  # Dry-run test `kubectl create clusterrole`\n  kubectl create \"${kube_flags[@]:?}\" clusterrole pod-admin --dry-run=client --verb=* --resource=pods\n  kubectl create \"${kube_flags[@]:?}\" clusterrole pod-admin --dry-run=server --verb=* --resource=pods\n  output_message=$(! kubectl get clusterrole pod-admin 2>&1 \"${kube_flags[@]:?}\")\n  kube::test::if_has_string \"${output_message}\" 'clusterroles.rbac.authorization.k8s.io \"pod-admin\" not found'\n  # test `kubectl create clusterrole`\n  kubectl create \"${kube_flags[@]:?}\" clusterrole pod-admin --verb=* --resource=pods\n  kube::test::get_object_assert clusterrole/pod-admin \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" '\\*:'\n  output_message=$(kubectl delete clusterrole pod-admin -n test 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'warning: deleting cluster-scoped resources'\n  kube::test::if_has_string \"${output_message}\" 'clusterrole.rbac.authorization.k8s.io \"pod-admin\" deleted'\n\n  kubectl create \"${kube_flags[@]}\" clusterrole pod-admin --verb=* --resource=pods\n  kube::test::get_object_assert clusterrole/pod-admin \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" '\\*:'\n  kube::test::get_object_assert clusterrole/pod-admin \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods:'\n  kube::test::get_object_assert clusterrole/pod-admin \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':'\n  kubectl create \"${kube_flags[@]}\" clusterrole resource-reader --verb=get,list --resource=pods,deployments.apps\n  kube::test::get_object_assert clusterrole/resource-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:get:list:'\n  kube::test::get_object_assert clusterrole/resource-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods:deployments:'\n  kube::test::get_object_assert clusterrole/resource-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':apps:'\n  kubectl create \"${kube_flags[@]}\" clusterrole resourcename-reader --verb=get,list --resource=pods --resource-name=foo\n  kube::test::get_object_assert clusterrole/resourcename-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:'\n  kube::test::get_object_assert clusterrole/resourcename-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods:'\n  kube::test::get_object_assert clusterrole/resourcename-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':'\n  kube::test::get_object_assert clusterrole/resourcename-reader \"{{range.rules}}{{range.resourceNames}}{{.}}:{{end}}{{end}}\" 'foo:'\n  kubectl create \"${kube_flags[@]}\" clusterrole url-reader --verb=get --non-resource-url=/logs/* --non-resource-url=/healthz/*\n  kube::test::get_object_assert clusterrole/url-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:'\n  kube::test::get_object_assert clusterrole/url-reader \"{{range.rules}}{{range.nonResourceURLs}}{{.}}:{{end}}{{end}}\" '/logs/\\*:/healthz/\\*:'\n  kubectl create \"${kube_flags[@]}\" clusterrole aggregation-reader --aggregation-rule=\"foo1=foo2\"\n  kube::test::get_object_assert clusterrole/aggregation-reader \"{{${id_field:?}}}\" 'aggregation-reader'\n\n  # Pre-condition: no ClusterRoleBinding super-admin exists\n  output_message=$(! kubectl get clusterrolebinding super-admin 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'clusterrolebindings.rbac.authorization.k8s.io \"super-admin\" not found'\n  # Dry-run test `kubectl create clusterrolebinding`\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding super-admin --dry-run=client --clusterrole=admin --user=super-admin\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding super-admin --dry-run=server --clusterrole=admin --user=super-admin\n  output_message=$(! kubectl get clusterrolebinding super-admin 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'clusterrolebindings.rbac.authorization.k8s.io \"super-admin\" not found'\n  # test `kubectl create clusterrolebinding`\n  # test `kubectl set subject clusterrolebinding`\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding super-admin --clusterrole=admin --user=super-admin\n  kube::test::get_object_assert clusterrolebinding/super-admin \"{{range.subjects}}{{.name}}:{{end}}\" 'super-admin:'\n  kubectl set subject --dry-run=client \"${kube_flags[@]}\" clusterrolebinding super-admin --user=foo\n  kubectl set subject --dry-run=server \"${kube_flags[@]}\" clusterrolebinding super-admin --user=foo\n  kube::test::get_object_assert clusterrolebinding/super-admin \"{{range.subjects}}{{.name}}:{{end}}\" 'super-admin:'\n  kubectl set subject \"${kube_flags[@]}\" clusterrolebinding super-admin --user=foo\n  kube::test::get_object_assert clusterrolebinding/super-admin \"{{range.subjects}}{{.name}}:{{end}}\" 'super-admin:foo:'\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding multi-users --clusterrole=admin --user=user-1 --user=user-2\n  kube::test::get_object_assert clusterrolebinding/multi-users \"{{range.subjects}}{{.name}}:{{end}}\" 'user-1:user-2:'\n\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding super-group --clusterrole=admin --group=the-group\n  kube::test::get_object_assert clusterrolebinding/super-group \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:'\n  kubectl set subject \"${kube_flags[@]}\" clusterrolebinding super-group --group=foo\n  kube::test::get_object_assert clusterrolebinding/super-group \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:foo:'\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding multi-groups --clusterrole=admin --group=group-1 --group=group-2\n  kube::test::get_object_assert clusterrolebinding/multi-groups \"{{range.subjects}}{{.name}}:{{end}}\" 'group-1:group-2:'\n\n  kubectl create \"${kube_flags[@]}\" clusterrolebinding super-sa --clusterrole=admin --serviceaccount=otherns:sa-name\n  kube::test::get_object_assert clusterrolebinding/super-sa \"{{range.subjects}}{{.namespace}}:{{end}}\" 'otherns:'\n  kube::test::get_object_assert clusterrolebinding/super-sa \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:'\n  kubectl set subject \"${kube_flags[@]}\" clusterrolebinding super-sa --serviceaccount=otherfoo:foo\n  kube::test::get_object_assert clusterrolebinding/super-sa \"{{range.subjects}}{{.namespace}}:{{end}}\" 'otherns:otherfoo:'\n  kube::test::get_object_assert clusterrolebinding/super-sa \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:foo:'\n\n  # test `kubectl set subject clusterrolebinding --all`\n  kubectl set subject \"${kube_flags[@]}\" clusterrolebinding --all --user=test-all-user\n  kube::test::get_object_assert clusterrolebinding/super-admin \"{{range.subjects}}{{.name}}:{{end}}\" 'super-admin:foo:test-all-user:'\n  kube::test::get_object_assert clusterrolebinding/super-group \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:foo:test-all-user:'\n  kube::test::get_object_assert clusterrolebinding/super-sa \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:foo:test-all-user:'\n\n  # test `kubectl create rolebinding`\n  # test `kubectl set subject rolebinding`\n  kubectl create \"${kube_flags[@]}\" rolebinding admin --dry-run=client --clusterrole=admin --user=default-admin\n  kubectl create \"${kube_flags[@]}\" rolebinding admin --dry-run=server --clusterrole=admin --user=default-admin\n  output_message=$(! kubectl get rolebinding/admin 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" ' not found'\n  kubectl create \"${kube_flags[@]}\" rolebinding admin --clusterrole=admin --user=default-admin\n  kube::test::get_object_assert rolebinding/admin \"{{.roleRef.kind}}\" 'ClusterRole'\n  kube::test::get_object_assert rolebinding/admin \"{{range.subjects}}{{.name}}:{{end}}\" 'default-admin:'\n  kubectl set subject \"${kube_flags[@]}\" rolebinding admin --user=foo\n  kube::test::get_object_assert rolebinding/admin \"{{range.subjects}}{{.name}}:{{end}}\" 'default-admin:foo:'\n\n  kubectl create \"${kube_flags[@]}\" rolebinding localrole --role=localrole --group=the-group\n  kube::test::get_object_assert rolebinding/localrole \"{{.roleRef.kind}}\" 'Role'\n  kube::test::get_object_assert rolebinding/localrole \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:'\n  kubectl set subject \"${kube_flags[@]}\" rolebinding localrole --group=foo\n  kube::test::get_object_assert rolebinding/localrole \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:foo:'\n\n  kubectl create \"${kube_flags[@]}\" rolebinding sarole --role=localrole --serviceaccount=otherns:sa-name\n  kube::test::get_object_assert rolebinding/sarole \"{{range.subjects}}{{.namespace}}:{{end}}\" 'otherns:'\n  kube::test::get_object_assert rolebinding/sarole \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:'\n  kubectl set subject \"${kube_flags[@]}\" rolebinding sarole --serviceaccount=otherfoo:foo\n  kube::test::get_object_assert rolebinding/sarole \"{{range.subjects}}{{.namespace}}:{{end}}\" 'otherns:otherfoo:'\n  kube::test::get_object_assert rolebinding/sarole \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:foo:'\n\n  # test `kubectl set subject rolebinding --all`\n  kubectl set subject \"${kube_flags[@]}\" rolebinding --all --user=test-all-user\n  kube::test::get_object_assert rolebinding/admin \"{{range.subjects}}{{.name}}:{{end}}\" 'default-admin:foo:test-all-user:'\n  kube::test::get_object_assert rolebinding/localrole \"{{range.subjects}}{{.name}}:{{end}}\" 'the-group:foo:test-all-user:'\n  kube::test::get_object_assert rolebinding/sarole \"{{range.subjects}}{{.name}}:{{end}}\" 'sa-name:foo:test-all-user:'\n\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert clusterrolebindings\n  kube::test::describe_resource_chunk_size_assert clusterroles\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_role_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing role\"\n\n  # Dry-run create\n  kubectl create \"${kube_flags[@]}\" role pod-admin --dry-run=client --verb=* --resource=pods\n  kubectl create \"${kube_flags[@]}\" role pod-admin --dry-run=server --verb=* --resource=pods\n  output_message=$(! kubectl get role/pod-admin 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" ' not found'\n  # Create Role from command (only resource)\n  kubectl create \"${kube_flags[@]}\" role pod-admin --verb=* --resource=pods\n  kube::test::get_object_assert role/pod-admin \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" '\\*:'\n  kube::test::get_object_assert role/pod-admin \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods:'\n  kube::test::get_object_assert role/pod-admin \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':'\n  output_message=$(! kubectl create \"${kube_flags[@]}\" role invalid-pod-admin --verb=* --resource=invalid-resource 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"the server doesn't have a resource type \\\"invalid-resource\\\"\"\n  # Create Role from command (resource + group)\n  kubectl create \"${kube_flags[@]}\" role group-reader --verb=get,list --resource=deployments.apps\n  kube::test::get_object_assert role/group-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:'\n  kube::test::get_object_assert role/group-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'deployments:'\n  kube::test::get_object_assert role/group-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" 'apps:'\n  output_message=$(! kubectl create \"${kube_flags[@]}\" role invalid-group --verb=get,list --resource=deployments.invalid-group 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"the server doesn't have a resource type \\\"deployments\\\" in group \\\"invalid-group\\\"\"\n  # Create Role from command (resource / subresource)\n  kubectl create \"${kube_flags[@]}\" role subresource-reader --verb=get,list --resource=pods/status\n  kube::test::get_object_assert role/subresource-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:'\n  kube::test::get_object_assert role/subresource-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods/status:'\n  kube::test::get_object_assert role/subresource-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':'\n  # Create Role from command (resource + group / subresource)\n  kubectl create \"${kube_flags[@]}\" role group-subresource-reader --verb=get,list --resource=replicasets.apps/scale\n  kube::test::get_object_assert role/group-subresource-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:'\n  kube::test::get_object_assert role/group-subresource-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'replicasets/scale:'\n  kube::test::get_object_assert role/group-subresource-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" 'apps:'\n  output_message=$(! kubectl create \"${kube_flags[@]}\" role invalid-group --verb=get,list --resource=rs.invalid-group/scale 2>&1)\n  kube::test::if_has_string \"${output_message}\" \"the server doesn't have a resource type \\\"rs\\\" in group \\\"invalid-group\\\"\"\n  # Create Role from command (resource + resourcename)\n  kubectl create \"${kube_flags[@]}\" role resourcename-reader --verb=get,list --resource=pods --resource-name=foo\n  kube::test::get_object_assert role/resourcename-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:'\n  kube::test::get_object_assert role/resourcename-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods:'\n  kube::test::get_object_assert role/resourcename-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':'\n  kube::test::get_object_assert role/resourcename-reader \"{{range.rules}}{{range.resourceNames}}{{.}}:{{end}}{{end}}\" 'foo:'\n  # Create Role from command (multi-resources)\n  kubectl create \"${kube_flags[@]}\" role resource-reader --verb=get,list --resource=pods/status,deployments.apps\n  kube::test::get_object_assert role/resource-reader \"{{range.rules}}{{range.verbs}}{{.}}:{{end}}{{end}}\" 'get:list:get:list:'\n  kube::test::get_object_assert role/resource-reader \"{{range.rules}}{{range.resources}}{{.}}:{{end}}{{end}}\" 'pods/status:deployments:'\n  kube::test::get_object_assert role/resource-reader \"{{range.rules}}{{range.apiGroups}}{{.}}:{{end}}{{end}}\" ':apps:'\n\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert roles\n  kube::test::describe_resource_chunk_size_assert rolebindings\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 202}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_request_timeout_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl request timeout\"\n  ### Test global request timeout option\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create \"${kube_flags[@]:?}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  # Post-condition: valid-pod POD is created\n  kubectl get \"${kube_flags[@]}\" pods -o json\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" 'valid-pod:'\n\n  ## check --request-timeout on 'get pod'\n  output_message=$(kubectl get pod valid-pod --request-timeout=1)\n  kube::test::if_has_string \"${output_message}\" 'valid-pod'\n\n  ## check --request-timeout on 'get pod' with --watch\n  output_message=$(kubectl get pod valid-pod --request-timeout=1 --watch --v=5 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'Timeout'\n\n  ## check --request-timeout value with no time unit\n  output_message=$(kubectl get pod valid-pod --request-timeout=1 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'valid-pod'\n\n  ## check --request-timeout value with invalid time unit\n  output_message=$(! kubectl get pod valid-pod --request-timeout=\"1p\" 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'Invalid timeout value'\n\n  # cleanup\n  kubectl delete pods valid-pod \"${kube_flags[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 58}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_kubectl_run_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing kubectl run\"\n\n  # Command with dry-run\n  kubectl run --dry-run=client nginx-extensions \"--image=${IMAGE_NGINX}\" \"${kube_flags[@]:?}\"\n  kubectl run --dry-run=server nginx-extensions \"--image=${IMAGE_NGINX}\" \"${kube_flags[@]:?}\"\n  # Post-Condition: no Pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  # Pre-Condition: no Pod exists\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl run nginx-extensions \"--image=${IMAGE_NGINX}\" \"${kube_flags[@]:?}\"\n  # Post-Condition: Pod \"nginx\" is created\n  kube::test::get_object_assert pod \"{{range.items}}{{$id_field}}:{{end}}\" 'nginx-extensions:'\n  # Clean up\n  kubectl delete pod nginx-extensions \"${kube_flags[@]}\"\n\n  # Test that a valid image reference value is provided as the value of --image in `kubectl run <name> --image`\n  output_message=$(kubectl run test1 --image=validname)\n  kube::test::if_has_string \"${output_message}\" 'pod/test1 created'\n  kubectl delete pods test1\n  # test invalid image name\n  output_message=$(! kubectl run test2 --image=InvalidImageName 2>&1)\n  kube::test::if_has_string \"${output_message}\" 'error: Invalid image name \"InvalidImageName\": invalid reference format'\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 54}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Runs tests for --save-config tests.\nrun_save_config_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl --save-config\"\n  ## Configuration annotations should be set when --save-config is enabled\n  ## 1. kubectl create --save-config should generate configuration annotation\n  # Pre-Condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command: create a pod \"test-pod\"\n  kubectl create -f hack/testdata/pod.yaml --save-config \"${kube_flags[@]:?}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\"\n  # Clean up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  ## 2. kubectl edit --save-config should generate configuration annotation\n  # Pre-Condition: no POD exists, then create pod \"test-pod\", which shouldn't have configuration annotation\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kubectl create -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  ! grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\" || exit 1\n  # Command: edit the pod \"test-pod\"\n  temp_editor=\"${KUBE_TEMP}/tmp-editor.sh\"\n  echo -e \"#!/usr/bin/env bash\\n${SED} -i \\\"s/test-pod-label/test-pod-label-edited/g\\\" \\$@\" > \"${temp_editor}\"\n  chmod +x \"${temp_editor}\"\n  EDITOR=${temp_editor} kubectl edit pod test-pod --save-config \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\"\n  # Clean up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  ## 3. kubectl replace --save-config should generate configuration annotation\n  # Pre-Condition: no POD exists, then create pod \"test-pod\", which shouldn't have configuration annotation\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kubectl create -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  ! grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\" || exit 1\n  # Command: replace the pod \"test-pod\"\n  kubectl replace -f hack/testdata/pod.yaml --save-config \"${kube_flags[@]}\"\n  # Post-Condition: pod \"test-pod\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pods test-pod -o yaml \"${kube_flags[@]}\")\"\n  # Clean up\n  kubectl delete -f hack/testdata/pod.yaml \"${kube_flags[@]}\"\n  ## 4. kubectl run --save-config should generate configuration annotation\n  # Pre-Condition: no pods exists\n  kube::test::get_object_assert pods \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command: create the pod \"nginx\" with image nginx\n  kubectl run nginx \"--image=$IMAGE_NGINX\" --save-config \"${kube_flags[@]}\"\n  # Post-Condition: pod \"nginx\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get pod nginx -o yaml \"${kube_flags[@]}\")\"\n  ## 5. kubectl expose --save-config should generate configuration annotation\n  # Pre-Condition: no service exists\n  kube::test::get_object_assert svc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  # Command: expose the rc \"nginx\"\n  kubectl expose pod nginx --save-config --port=80 --target-port=8000 \"${kube_flags[@]}\"\n  # Post-Condition: service \"nginx\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get svc nginx -o yaml \"${kube_flags[@]}\")\"\n  # Clean up\n  kubectl delete pod,svc nginx\n  ## 6. kubectl autoscale --save-config should generate configuration annotation\n  # Pre-Condition: no RC exists, then create the rc \"frontend\", which shouldn't have configuration annotation\n  kube::test::get_object_assert rc \"{{range.items}}{{$id_field}}:{{end}}\" ''\n  kubectl create -f hack/testdata/frontend-controller.yaml \"${kube_flags[@]}\"\n  ! grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get rc frontend -o yaml \"${kube_flags[@]}\")\" || exit 1\n  # Command: autoscale rc \"frontend\"\n  kubectl autoscale -f hack/testdata/frontend-controller.yaml --save-config \"${kube_flags[@]}\" --max=2\n  # Post-Condition: hpa \"frontend\" has configuration annotation\n  grep -q \"kubectl.kubernetes.io/last-applied-configuration\" <<< \"$(kubectl get hpa frontend -o yaml \"${kube_flags[@]}\")\"\n  # Ensure we can interact with HPA objects in lists through autoscaling/v1 APIs\n  output_message=$(kubectl get hpa -o=jsonpath='{.items[0].apiVersion}' 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'autoscaling/v1'\n  output_message=$(kubectl get hpa.autoscaling -o=jsonpath='{.items[0].apiVersion}' 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'autoscaling/v1'\n  # tests kubectl group prefix matching\n  output_message=$(kubectl get hpa.autoscal -o=jsonpath='{.items[0].apiVersion}' 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'autoscaling/v1'\n  # Clean up\n  # Note that we should delete hpa first, otherwise it may fight with the rc reaper.\n  kubectl delete hpa frontend \"${kube_flags[@]}\"\n  kubectl delete rc  frontend \"${kube_flags[@]}\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 106}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_persistent_volumes_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing persistent volumes\"\n\n  ### Create and delete persistent volume examples\n  # Pre-condition: no persistent volumes currently exist\n  kube::test::get_object_assert pv \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/volumes/local-01.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pv \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'pv0001:'\n  kubectl delete pv pv0001 \"${kube_flags[@]:?}\"\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/volumes/local-02.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pv \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'pv0002:'\n  kubectl delete pv pv0002 \"${kube_flags[@]:?}\"\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/volumes/gce.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pv \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'pv0003:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert persistentvolumes events\n  kubectl delete pv pv0003 \"${kube_flags[@]:?}\"\n  # Post-condition: no PVs\n  kube::test::get_object_assert pv \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/volumes/local-01.yaml \"${kube_flags[@]}\"\n  kube::test::get_object_assert pv \"{{range.items}}{{$id_field}}:{{end}}\" 'pv0001:'\n  output_message=$(kubectl delete pv -n test --all 2>&1 \"${kube_flags[@]}\")\n  kube::test::if_has_string \"${output_message}\" 'warning: deleting cluster-scoped resources'\n  kube::test::if_has_string \"${output_message}\" 'persistentvolume \"pv0001\" deleted'\n  kube::test::get_object_assert pv \"{{range.items}}{{$id_field}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_persistent_volume_claims_tests() {\n  set -o nounset\n  set -o errexit\n\n  create_and_use_new_namespace\n  kube::log::status \"Testing persistent volumes claims\"\n\n  ### Create and delete persistent volume claim examples\n  # Pre-condition: no persistent volume claims currently exist\n  kube::test::get_object_assert pvc \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/claims/claim-01.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pvc \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'myclaim-1:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert persistentvolumeclaims pods,events\n  kubectl delete pvc myclaim-1 \"${kube_flags[@]:?}\"\n\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/claims/claim-02.yaml \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pvc \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'myclaim-2:'\n  kubectl delete pvc myclaim-2 \"${kube_flags[@]:?}\"\n\n  kubectl create -f test/fixtures/doc-yaml/user-guide/persistent-volumes/claims/claim-03.json \"${kube_flags[@]:?}\"\n  kube::test::get_object_assert pvc \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'myclaim-3:'\n  kubectl delete pvc myclaim-3 \"${kube_flags[@]:?}\"\n  # Post-condition: no PVCs\n  kube::test::get_object_assert pvc \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n}\n\nrun_storage_class_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing storage class\"\n\n  ### Create and delete storage class\n  # Pre-condition: no storage classes currently exist\n  kube::test::get_object_assert storageclass \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  kubectl create -f - \"${kube_flags[@]:?}\" << __EOF__\n{\n  \"kind\": \"StorageClass\",\n  \"apiVersion\": \"storage.k8s.io/v1\",\n  \"metadata\": {\n  \"name\": \"storage-class-name\"\n  },\n  \"provisioner\": \"kubernetes.io/fake-provisioner-type\",\n  \"parameters\": {\n  \"zone\":\"us-east-1b\",\n  \"type\":\"ssd\"\n  }\n}\n__EOF__\n  kube::test::get_object_assert storageclass \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'storage-class-name:'\n  kube::test::get_object_assert sc \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'storage-class-name:'\n  # Describe command should respect the chunk size parameter\n  kube::test::describe_resource_chunk_size_assert storageclasses events\n  kubectl delete storageclass storage-class-name \"${kube_flags[@]:?}\"\n  # Post-condition: no storage classes\n  kube::test::get_object_assert storageclass \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n\n  set +o nounset\n  set +o errexit\n\n}\n", "num_lines": 124}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_template_output_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing --template support on commands\"\n  ### Test global request timeout option\n  # Pre-condition: no POD exists\n  create_and_use_new_namespace\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" ''\n  # Command\n  # check that create supports --template output\n  kubectl create \"${kube_flags[@]:?}\" -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml\n  # Post-condition: valid-pod POD is created\n  kubectl get \"${kube_flags[@]:?}\" pods -o json\n  kube::test::get_object_assert pods \"{{range.items}}{{${id_field:?}}}:{{end}}\" 'valid-pod:'\n\n  # check that patch command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" patch --dry-run=client pods/valid-pod -p '{\"patched\":\"value3\"}' --type=merge --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that label command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" label --dry-run=client pods/valid-pod label=value --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that annotate command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" annotate --dry-run=client pods/valid-pod annotation=value --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that apply command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" apply --dry-run=client -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that create command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create -f test/fixtures/doc-yaml/admin/limitrange/valid-pod.yaml --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that autoscale command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" autoscale --max=2 -f hack/testdata/scale-deploy-1.yaml --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'scale-1:'\n\n  # check that expose command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" expose -f hack/testdata/redis-slave-replicaset.yaml --save-config --port=80 --target-port=8000 --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'redis-slave:'\n\n  # check that run command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" run --dry-run=client --template=\"{{ .metadata.name }}:\" pi --image=perl --restart=OnFailure -- perl -Mbignum=bpi -wle 'print bpi(2000)')\n  kube::test::if_has_string \"${output_message}\" 'pi:'\n\n  # check that taint command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" taint node 127.0.0.1 dedicated=foo:PreferNoSchedule --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" '127.0.0.1:'\n  # untaint node\n  kubectl taint node 127.0.0.1 dedicated-\n\n  # check that \"apply set-last-applied\" command supports --template output\n  kubectl \"${kube_flags[@]:?}\" create -f test/e2e/testing-manifests/statefulset/cassandra/controller.yaml\n  output_message=$(kubectl \"${kube_flags[@]:?}\" apply set-last-applied -f test/e2e/testing-manifests/statefulset/cassandra/controller.yaml --dry-run=client --create-annotation --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'cassandra:'\n\n  # check that \"auth reconcile\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" auth reconcile --dry-run=client -f test/fixtures/pkg/kubectl/cmd/auth/rbac-resource-plus.yaml --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'testing-CR:testing-CRB:testing-RB:testing-R:'\n\n  # check that \"create clusterrole\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create clusterrole --template=\"{{ .metadata.name }}:\" --verb get myclusterrole  --non-resource-url /logs/ --resource pods)\n  kube::test::if_has_string \"${output_message}\" 'myclusterrole:'\n\n  # check that \"create clusterrolebinding\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create clusterrolebinding foo --clusterrole=myclusterrole --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create configmap\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create configmap cm --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'cm:'\n\n  # check that \"create deployment\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create deployment deploy --image=nginx --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'deploy:'\n\n  # check that \"create job\" command supports --template output\n  kubectl create \"${kube_flags[@]:?}\" -f - <<EOF\napiVersion: batch/v1\nkind: CronJob\nmetadata:\n  name: pi\nspec:\n  schedule: \"*/10 * * * *\"\n  jobTemplate:\n    spec:\n      template:\n        metadata:\n          labels:\n            parent: \"pi\"\n        spec:\n          containers:\n          - name: pi\n            image: perl\n            command: [\"perl\",  \"-Mbignum=bpi\", \"-wle\", \"print bpi(2000)\"]\n          restartPolicy: OnFailure\nEOF\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create job foo --from=cronjob/pi --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create namespace\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create ns bar --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'bar:'\n\n  # check that \"create namespace\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create rolebinding foo --clusterrole=myclusterrole --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create role\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create role --dry-run=client --template=\"{{ .metadata.name }}:\" --verb get myrole --resource pods)\n  kube::test::if_has_string \"${output_message}\" 'myrole:'\n\n  # check that \"create quota\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create quota foo --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create priorityclass\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create priorityclass foo --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create poddisruptionbudget\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create poddisruptionbudget foo --dry-run=client --selector=foo --min-available=1 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create serviceaccount\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create serviceaccount foo --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"set env\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set env pod/valid-pod --dry-run=client A=B --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that \"set image\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set image pod/valid-pod --dry-run=client kubernetes-serve-hostname=nginx --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that \"set resources\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set resources pod/valid-pod --limits=memory=256Mi --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that \"set selector\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set selector -f hack/testdata/kubernetes-service.yaml A=B --local --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'kubernetes:'\n\n  # check that \"set serviceaccount\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set serviceaccount pod/valid-pod deployer --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'valid-pod:'\n\n  # check that \"set subject\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" set subject clusterrolebinding/foo --user=foo --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create secret docker-registry\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create secret docker-registry foo --docker-username user --docker-password pass --docker-email foo@bar.baz --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create secret generic\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create secret generic foo --from-literal=key1=value1 --dry-run=client --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create secret tls\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create secret tls --dry-run=client foo --key=hack/testdata/tls.key --cert=hack/testdata/tls.crt --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create service clusterip\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create service clusterip foo --dry-run=client --tcp=8080 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create service externalname\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create service externalname foo --dry-run=client --external-name=bar --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create service loadbalancer\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create service loadbalancer foo --dry-run=client --tcp=8080 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"create service nodeport\" command supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create service nodeport foo --dry-run=client --tcp=8080 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'foo:'\n\n  # check that \"config view\" ouputs \"yaml\" as its default output format\n  output_message=$(kubectl \"${kube_flags[@]:?}\" config view)\n  kube::test::if_has_string \"${output_message}\" 'kind: Config'\n\n  # check that \"rollout pause\" supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" rollout pause deploy/deploy --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'deploy:'\n\n   # check that \"rollout history\" supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" rollout history deploy/deploy --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'deploy:'\n\n  # check that \"rollout resume\" supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" rollout resume deploy/deploy --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'deploy:'\n\n  # check that \"rollout undo\" supports --template output\n  output_message=$(kubectl \"${kube_flags[@]:?}\" rollout undo deploy/deploy --to-revision=1 --template=\"{{ .metadata.name }}:\")\n  kube::test::if_has_string \"${output_message}\" 'deploy:'\n\n  # check that \"config view\" command supports --template output\n  # and that commands that set a default output (yaml in this case),\n  # default to \"go-template\" as their output format when a --template\n  # value is provided, but no explicit --output format is given.\n  output_message=$(kubectl \"${kube_flags[@]:?}\" config view --template=\"{{ .kind }}:\")\n  kube::test::if_has_string \"${output_message}\" 'Config'\n\n  # check that running a command with both a --template flag and a\n  # non-template --output prefers the non-template output value\n  output_message=$(kubectl \"${kube_flags[@]:?}\" create configmap cm --dry-run=client --template=\"{{ .metadata.name }}:\" --output yaml)\n  kube::test::if_has_string \"${output_message}\" 'kind: ConfigMap'\n\n  # cleanup\n  kubectl delete cronjob pi \"${kube_flags[@]:?}\"\n  kubectl delete pods --all \"${kube_flags[@]:?}\"\n  kubectl delete rc cassandra \"${kube_flags[@]:?}\"\n  kubectl delete clusterrole myclusterrole \"${kube_flags[@]:?}\"\n  kubectl delete clusterrolebinding foo \"${kube_flags[@]:?}\"\n  kubectl delete deployment deploy \"${kube_flags[@]:?}\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 247}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n########################################################\n# Kubectl version (--short, --client, --output) #\n########################################################\nrun_kubectl_version_tests() {\n  set -o nounset\n  set -o errexit\n\n  kube::log::status \"Testing kubectl version\"\n  TEMP=\"${KUBE_TEMP}\"\n\n  kubectl get \"${kube_flags[@]:?}\" --raw /version\n\n  # create version files, one for the client, one for the server.\n  # these are the files we will use to ensure that the remainder output is correct\n  kube::test::version::object_to_file \"Client\" \"\" \"${TEMP}/client_version_test\"\n  kube::test::version::object_to_file \"Server\" \"\" \"${TEMP}/server_version_test\"\n\n  kube::log::status \"Testing kubectl version: check client only output matches expected output\"\n  kube::test::version::object_to_file \"Client\" \"--client\" \"${TEMP}/client_only_version_test\"\n  set +e pipefail   # Turn off bash options, since this command pipes empty text.\n  kube::test::version::object_to_file \"Server\" \"--client\" \"${TEMP}/server_client_only_version_test\"\n  set -e pipefail   # Reset bash options\n  kube::test::version::diff_assert \"${TEMP}/client_version_test\" \"eq\" \"${TEMP}/client_only_version_test\" \"the flag '--client' shows correct client info\"\n  kube::test::version::diff_assert \"${TEMP}/server_version_test\" \"ne\" \"${TEMP}/server_client_only_version_test\" \"the flag '--client' correctly has no server version info\"\n\n  kube::log::status \"Testing kubectl version: verify json output\"\n  kube::test::version::json_client_server_object_to_file \"\" \"clientVersion\" \"${TEMP}/client_json_version_test\"\n  kube::test::version::json_client_server_object_to_file \"\" \"serverVersion\" \"${TEMP}/server_json_version_test\"\n  kube::test::version::diff_assert \"${TEMP}/client_version_test\" \"eq\" \"${TEMP}/client_json_version_test\" \"--output json has correct client info\"\n  kube::test::version::diff_assert \"${TEMP}/server_version_test\" \"eq\" \"${TEMP}/server_json_version_test\" \"--output json has correct server info\"\n\n  kube::log::status \"Testing kubectl version: verify json output using additional --client flag does not contain serverVersion\"\n  kube::test::version::json_client_server_object_to_file \"--client\" \"clientVersion\" \"${TEMP}/client_only_json_version_test\"\n  kube::test::version::json_client_server_object_to_file \"--client\" \"serverVersion\" \"${TEMP}/server_client_only_json_version_test\"\n  kube::test::version::diff_assert \"${TEMP}/client_version_test\" \"eq\" \"${TEMP}/client_only_json_version_test\" \"--client --output json has correct client info\"\n  kube::test::version::diff_assert \"${TEMP}/server_version_test\" \"ne\" \"${TEMP}/server_client_only_json_version_test\" \"--client --output json has no server info\"\n\n  kube::log::status \"Testing kubectl version: compare json output using additional --short flag\"\n  kube::test::version::json_client_server_object_to_file \"--short\" \"clientVersion\" \"${TEMP}/client_short_json_version_test\"\n  kube::test::version::json_client_server_object_to_file \"--short\" \"serverVersion\" \"${TEMP}/server_short_json_version_test\"\n  kube::test::version::diff_assert \"${TEMP}/client_version_test\" \"eq\" \"${TEMP}/client_short_json_version_test\" \"--short --output client json info is equal to non short result\"\n  kube::test::version::diff_assert \"${TEMP}/server_version_test\" \"eq\" \"${TEMP}/server_short_json_version_test\" \"--short --output server json info is equal to non short result\"\n\n  kube::log::status \"Testing kubectl version: compare json output with yaml output\"\n  kube::test::version::json_object_to_file \"\" \"${TEMP}/client_server_json_version_test\"\n  kube::test::version::yaml_object_to_file \"\" \"${TEMP}/client_server_yaml_version_test\"\n  kube::test::version::diff_assert \"${TEMP}/client_server_json_version_test\" \"eq\" \"${TEMP}/client_server_yaml_version_test\" \"--output json/yaml has identical information\"\n\n  set +o nounset\n  set +o errexit\n}\n", "num_lines": 72}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrun_wait_tests() {\n    set -o nounset\n    set -o errexit\n\n    kube::log::status \"Testing kubectl wait\"\n\n    create_and_use_new_namespace\n\n    ### Wait for deletion using --all flag\n\n    # create test data\n    kubectl create deployment test-1 --image=busybox\n    kubectl create deployment test-2 --image=busybox\n\n    # Post-Condition: deployments exists\n    kube::test::get_object_assert \"deployments\" \"{{range .items}}{{.metadata.name}},{{end}}\" 'test-1,test-2,'\n\n    # Delete all deployments async to kubectl wait\n    ( sleep 2 && kubectl delete deployment --all ) &\n\n    # Command: Wait for all deployments to be deleted\n    output_message=$(kubectl wait deployment --for=delete --all)\n\n    # Post-Condition: Wait was successful\n    kube::test::if_has_string \"${output_message}\" 'test-1 condition met'\n    kube::test::if_has_string \"${output_message}\" 'test-2 condition met'\n\n    set +o nounset\n    set +o errexit\n}", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# echo ${TEST_SRCDIR}\n# pwd\n# env | grep --color=always test/conformance\n# find ${TEST_SRCDIR} -ls | grep --color=always test/conformance\n\nset -o errexit\n\nif diff -u test/conformance/testdata/conformance.yaml test/conformance/conformance.yaml; then\n  echo PASS\n  exit 0\nfi\necho 'See instructions in test/conformance/README.md'\nexit 1\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/../.. && pwd -P)\ncd \"${KUBE_ROOT}\"\n\n# test sources -> json spec _output/specsummaries.json\ntest/conformance/gen-specsummaries.sh\n# specsummaries.json -> conformance.md\ntest/conformance/spec-to-docs.sh\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/../.. && pwd -P)\ncd \"${KUBE_ROOT}\"\n\n# test sources -> json spec _output/specsummaries.json\ntest/conformance/gen-specsummaries.sh\n# specsummaries.json -> conformance.yaml\ntest/conformance/spec-to-yaml.sh\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/../.. && pwd -P)\ncd \"${KUBE_ROOT}\"\n\n# build ginkgo and e2e.test\n# NOTE: we do *not* use `make WHAT=...` because we do *not* want to be running\n# make generated_files when diffing things (see: hack/verify-conformance-yaml.sh)\n# other update/verify already handle the generated files\nhack/make-rules/build.sh vendor/github.com/onsi/ginkgo/ginkgo test/e2e/e2e.test\n\n# dump spec\n./_output/bin/ginkgo --dryRun=true --focus='[Conformance]' ./_output/bin/e2e.test -- --spec-dump \"${KUBE_ROOT}/_output/specsummaries.json\" > /dev/null\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/../.. && pwd -P)\ncd \"${KUBE_ROOT}\"\n\n# convert dumped spec (see dump-spec.sh) to conformance.md\ngo run ./test/conformance/walk.go --source=\"${KUBE_ROOT}\" --docs ./_output/specsummaries.json > ./_output/conformance.md\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# This will canonicalize the path\nKUBE_ROOT=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"/../.. && pwd -P)\ncd \"${KUBE_ROOT}\"\n\n# convert dumped spec (see dump-spec.sh) to conformance.yaml\ngo run ./test/conformance/walk.go --source=\"${KUBE_ROOT}\" ./_output/specsummaries.json > ./_output/conformance.yaml\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script will update all sidecar RBAC files and the CSI hostpath\n# deployment files such that they match what is in a hostpath driver\n# release.\n#\n# Beware that this will wipe out all local modifications!\n\n# Can be a tag or a branch.\nscript=\"$0\"\nhostpath_version=\"$1\"\n\nif ! [ \"$hostpath_version\" ]; then\n    cat >&2 <<EOF\nUsage: $0 <hostpath tag or branch name>\n\nRequired parameter is missing.\nEOF\n    exit 1\nfi\n\nset -xe\ncd \"$(dirname \"$0\")\"\n\n# Remove stale files.\nrm -rf external-attacher external-provisioner external-resizer external-snapshotter external-health-monitor hostpath csi-driver-host-path\n\n# Check out desired release.\ngit clone https://github.com/kubernetes-csi/csi-driver-host-path.git\n(cd csi-driver-host-path && git checkout \"$hostpath_version\")\ntrap \"rm -rf csi-driver-host-path\" EXIT\n\n# Main YAML files.\nmkdir hostpath\ncat >hostpath/README.md <<EOF\nThe files in this directory are exact copys of \"kubernetes-latest\" in\nhttps://github.com/kubernetes-csi/csi-driver-host-path/tree/$hostpath_version/deploy/\n\nDo not edit manually. Run $script to refresh the content.\nEOF\ncp -r csi-driver-host-path/deploy/kubernetes-latest/hostpath hostpath/\ncat >hostpath/hostpath/e2e-test-rbac.yaml <<EOF\n# priviledged Pod Security Policy, previously defined just for gcePD via PrivilegedTestPSPClusterRoleBinding()\nkind: ClusterRoleBinding\napiVersion: rbac.authorization.k8s.io/v1\nmetadata:\n  name: psp-csi-hostpath-role\nsubjects:\n  # This list of ServiceAccount intentionally covers everything that might\n  # be needed. In practice, only some of these accounts are actually\n  # used.\n  - kind: ServiceAccount\n    name: csi-attacher\n    namespace: default\n  - kind: ServiceAccount\n    name: csi-provisioner\n    namespace: default\n  - kind: ServiceAccount\n    name: csi-snapshotter\n    namespace: default\n  - kind: ServiceAccount\n    name: csi-resizer\n    namespace: default\n  - kind: ServiceAccount\n    name: csi-external-health-monitor-controller\n    namespace: default\n  - kind: ServiceAccount\n    name: csi-hostpathplugin-sa\n    namespace: default\nroleRef:\n  kind: ClusterRole\n  name: e2e-test-privileged-psp\n  apiGroup: rbac.authorization.k8s.io\nEOF\n\ndownload () {\n    project=\"$1\"\n    path=\"$2\"\n    tag=\"$3\"\n    rbac=\"$4\"\n\n    mkdir -p \"$project/$path\"\n    url=\"https://github.com/kubernetes-csi/$project/raw/$tag/deploy/kubernetes/$path/$rbac\"\n    cat >\"$project/$path/$rbac\" <<EOF\n# Do not edit, downloaded from $url\n# for csi-driver-host-path $hostpath_version\n# by $script\n#\nEOF\n    curl --fail --location \"$url\" >>\"$project/$path/$rbac\"\n}\n\n# RBAC files for each sidecar.\n# This relies on the convention that \"external-something\" has \"csi-something\" as image name.\n# external-health-monitor is special, it has two images.\n# The repository for each image is ignored.\nimages=$(grep -r '^ *image:.*csi' hostpath/hostpath | sed -e 's;.*image:.*/;;' | grep -v 'node-driver-registrar' | sort -u)\nfor image in $images; do\n    tag=$(echo \"$image\" | sed -e 's/.*://')\n    path=\n    rbac=\"rbac.yaml\"\n    case $image in\n        csi-external-*)\n            # csi-external-health-monitor-agent:v0.2.0\n            project=$(echo \"$image\" | sed -e 's/csi-\\(.*\\)-[^:]*:.*/\\1/')\n            path=$(echo \"$image\" | sed -e 's/csi-\\([^:]*\\):.*/\\1/')\n            ;;\n        *)\n            project=$(echo \"$image\" | sed -e 's/:.*//' -e 's/^csi/external/')\n            case $project in\n                external-snapshotter)\n                    # Another special case...\n                    path=\"csi-snapshotter\"\n                    rbac=\"rbac-csi-snapshotter.yaml\"\n                    ;;\n            esac\n            ;;\n    esac\n    download \"$project\" \"$path\" \"$tag\" \"$rbac\"\ndone\n", "num_lines": 135}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Make bucket and a folder for e2e-node test logs.\n# Populate the folder from the logs stored in /tmp/_artifacts/ in the same way as a\n# jenkins build would, and then print the URL to view the test results on Gubernator\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/logging.sh\"\n\n\nif [[ $# -eq 0 || ! $1 =~ ^[Yy]$ ]]; then\n  read -r -p \"Do you want to run gubernator.sh and upload logs publicly to GCS? [y/n]\" yn\n  echo\n  if [[ ! $yn =~ ^[Yy]$ ]]; then\n      exit 1\n  fi\nfi\n\n# Check that user has gsutil\nif [[ $(which gsutil) == \"\" ]]; then\n  echo \"Could not find gsutil when running \\`which gsutil\\`\"\n  exit 1\nfi\n\n# Check that user has gcloud\nif [[ $(which gcloud) == \"\" ]]; then\n  echo \"Could not find gcloud when running: \\`which gcloud\\`\"\n  exit 1\nfi\n\n# Check that user has Credentialed Active account\nif ! gcloud auth list | grep -q \"ACTIVE\"; then\n  echo \"Could not find active account when running: \\`gcloud auth list\\`\"\n  exit 1\nfi\n\nreadonly gcs_acl=\"public-read\"\nbucket_name=\"${USER}-g8r-logs\"\necho \"\"\nV=2 kube::log::status \"Using bucket ${bucket_name}\"\n\n# Check if the bucket exists\nif ! gsutil ls gs:// | grep -q \"gs://${bucket_name}/\"; then\n  V=2 kube::log::status \"Creating public bucket ${bucket_name}\"\n  gsutil mb \"gs://${bucket_name}/\"\n  # Make all files in the bucket publicly readable\n  gsutil acl ch -u AllUsers:R \"gs://${bucket_name}\"\nelse\n  V=2 kube::log::status \"Bucket already exists\"\nfi\n\n# Path for e2e-node test results\nGCS_JOBS_PATH=\"gs://${bucket_name}/logs/e2e-node\"\n\nARTIFACTS=${ARTIFACTS:-\"/tmp/_artifacts\"}\nBUILD_LOG_PATH=\"${ARTIFACTS}/build-log.txt\"\n\nif [[ ! -e $BUILD_LOG_PATH ]]; then\n  echo \"Could not find build-log.txt at ${BUILD_LOG_PATH}\"\n  exit 1\nfi\n\n# Get start and end timestamps based on build-log.txt file contents\n# Line where the actual tests start\nstart_line=$(grep -n -m 1 \"^=\" \"${BUILD_LOG_PATH}\" | sed 's/\\([0-9]*\\).*/\\1/')\n# Create text file starting where the tests start\nafter_start=$(tail -n \"+${start_line}\" \"${BUILD_LOG_PATH}\")\necho \"${after_start}\" >> build-log-cut.txt\n# Match the first timestamp\nstart_time_raw=$(grep -m 1 -o '[0-9][0-9][0-9][0-9][[:blank:]][0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*' build-log-cut.txt)\nrm build-log-cut.txt\n# Make the date readable by date command (ex: 0101 00:00:00.000 -> 01/01 00:00:00.000)\nstart_time=$(echo \"${start_time_raw}\" | sed 's/^.\\{2\\}/&\\//')\nV=2 kube::log::status \"Started at ${start_time}\"\n# Match the last timestamp in the build-log file\nend_time=$(grep -o '[0-9][0-9][0-9][0-9][[:blank:]][0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9]*' \"${BUILD_LOG_PATH}\" | tail -1 | sed 's/^.\\{2\\}/&\\//')\n# Convert to epoch time for Gubernator\nstart_time_epoch=$(date -d \"${start_time}\" +%s)\nend_time_epoch=$(date -d \"${end_time}\" +%s)\n\n# Make folder name for build from timestamp\nBUILD_STAMP=$(echo \"${start_time}\" | sed 's/\\///' | sed 's/ /_/')\n\nGCS_LOGS_PATH=\"${GCS_JOBS_PATH}/${BUILD_STAMP}\"\n\n# Check if folder for same logs already exists\nif gsutil ls \"${GCS_JOBS_PATH}\" | grep -q \"${BUILD_STAMP}\"; then\n  V=2 kube::log::status \"Log files already uploaded\"\n  echo \"Gubernator linked below:\"\n  echo \"k8s-gubernator.appspot.com/build/${GCS_LOGS_PATH}?local=on\"\n  exit\nfi\n\nwhile IFS= read -r result; do\n  if [[ $result != \"\" && $result != \"${ARTIFACTS}/results\" && $result != \"${ARTIFACTS}\" ]]; then\n    mv \"${result}/\"* \"${ARTIFACTS}\"\n  fi\ndone < <(find \"${ARTIFACTS}\" -type d -name \"results\")\n\n# Upload log files\nfor upload_attempt in $(seq 3); do\n  if [[ -d \"${ARTIFACTS}\" && -n $(ls -A \"${ARTIFACTS}\") ]]; then\n    V=2 kube::log::status \"Uploading artifacts\"\n    gsutil -m -q -o \"GSUtil:use_magicfile=True\" cp -a \"${gcs_acl}\" -r -c \\\n      -z log,xml,json \"${ARTIFACTS}\" \"${GCS_LOGS_PATH}/artifacts\" || continue\n  fi\n  break\ndone\nfor upload_attempt in $(seq 3); do\n  if [[ -e \"${BUILD_LOG_PATH}\" ]]; then\n    V=2 kube::log::status \"Uploading build log\"\n    gsutil -q cp -Z -a \"${gcs_acl}\" \"${BUILD_LOG_PATH}\" \"${GCS_LOGS_PATH}\" || continue\n  fi\n  break\ndone\n\n\n# Find the k8s version for started.json\nversion=\"\"\nif [[ -e \"version\" ]]; then\n  version=$(cat \"version\")\nelif [[ -e \"hack/lib/version.sh\" ]]; then\n  source \"hack/lib/version.sh\"\n  kube::version::get_version_vars\n  version=\"${KUBE_GIT_VERSION-}\"\nfi\nif [[ -n \"${version}\" ]]; then\n  V=2 kube::log::status \"Found Kubernetes version: ${version}\"\nelse\n  V=2 kube::log::status \"Could not find Kubernetes version\"\nfi\n\n#Find build result from build-log.txt\nif grep -Fxq \"Test Suite Passed\" \"${BUILD_LOG_PATH}\"\n  then\n    build_result=\"SUCCESS\"\nelse\n    build_result=\"FAILURE\"\nfi\n\nV=4 kube::log::status \"Build result is ${build_result}\"\n\nif [[ -e \"${ARTIFACTS}/started.json\" ]]; then\n  rm \"${ARTIFACTS}/started.json\"\nfi\n\nif [[ -e \"${ARTIFACTS}/finished.json\" ]]; then\n  rm \"${ARTIFACTS}/finished.json\"\nfi\n\nV=2 kube::log::status \"Constructing started.json and finished.json files\"\ncat <<EOF >\"${ARTIFACTS}/started.json\"\n{\n    \"version\": \"${version}\",\n    \"timestamp\": ${start_time_epoch},\n    \"jenkins-node\": \"${NODE_NAME:-}\"\n}\nEOF\n\n\ncat <<EOF >\"${ARTIFACTS}/finished.json\"\n{\n    \"result\": \"${build_result}\",\n    \"timestamp\": ${end_time_epoch}\n}\nEOF\n\n\n# Upload started.json\nV=2 kube::log::status \"Uploading started.json and finished.json\"\nV=2 kube::log::status \"Run started at ${start_time}\"\njson_file=\"${GCS_LOGS_PATH}/started.json\"\n\nfor upload_attempt in $(seq 3); do\n  V=2 kube::log::status \"Uploading started.json to ${json_file} (attempt ${upload_attempt})\"\n  gsutil -q -h \"Content-Type:application/json\" cp -a \"${gcs_acl}\" \"${ARTIFACTS}/started.json\" \\\n    \"${json_file}\" || continue\n  break\ndone\n\n# Upload finished.json\nfor upload_attempt in $(seq 3); do\n  V=2 kube::log::status \"Uploading finished.json to ${GCS_LOGS_PATH} (attempt ${upload_attempt})\"\n  gsutil -q -h \"Content-Type:application/json\" cp -a \"${gcs_acl}\" \"${ARTIFACTS}/finished.json\" \\\n    \"${GCS_LOGS_PATH}/finished.json\" || continue\n  break\ndone\n\n\necho \"Gubernator linked below:\"\necho \"k8s-gubernator.appspot.com/build/${bucket_name}/logs/e2e-node/${BUILD_STAMP}\"\n", "num_lines": 210}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is only for demonstrating how to use the node test container. In\n# production environment, kubelet bootstrap will be more complicated, user\n# should configure the node test container accordingly.\n# In addition, this script will also be used in the node e2e test to let it use\n# the containerized test suite.\n\n# TODO(random-liu): Use standard installer to install kubelet.\n# TODO(random-liu): Use standard tool to start kubelet in production way (such\n# as systemd, supervisord etc.)\n\n# Refresh sudo credentials if needed\nif ping -c 1 -q metadata.google.internal &> /dev/null; then\n  echo 'Running on GCE, not asking for sudo credentials'\nelif sudo --non-interactive \"$(which bash)\" -c true 2> /dev/null; then\n  # if we can run bash without a password, it's a pretty safe bet that either\n  # we can run any command without a password, or that sudo credentials\n  # are already cached - and they've just been re-cached\n  echo 'No need to refresh sudo credentials'\nelse\n  echo 'Updating sudo credentials'\n  sudo -v || exit 1\nfi\n\n# FOCUS is ginkgo focus to select which tests to run. By default, FOCUS is\n# initialized as \"\\[Conformance\\]\" in the test container to run all conformance\n# test.\nFOCUS=${FOCUS:-\"\"}\n\n# SKIP is ginkgo skip to select which tests to skip. By default, SKIP is\n# initialized as \"\\[Flaky\\]|\\[Serial\\]\" in the test container skipping all\n# flaky and serial test.\nSKIP=${SKIP:-\"\"}\n\n# TEST_ARGS is the test arguments. It could be used to override default test\n# arguments in the container.\nTEST_ARGS=${TEST_ARGS:-\"\"}\n\n# REGISTRY is the image registry for node test image.\nREGISTRY=${REGISTRY:-\"k8s.gcr.io\"}\n\n# ARCH is the architecture of current machine, the script will use this to\n# select corresponding test container image.\nARCH=${ARCH:-\"amd64\"}\n\n# VERSION is the version of the test container image.\nVERSION=${VERSION:-\"0.2\"}\n\n# KUBELET_BIN is the kubelet binary name. If it is not specified, use the\n# default binary name \"kubelet\".\nKUBELET_BIN=${KUBELET_BIN:-\"kubelet\"}\n\n# KUBELET is the kubelet binary path. If it is not specified, assume kubelet is\n# in PATH.\nKUBELET=${KUBELET:-\"$(which \"$KUBELET_BIN\")\"}\n\n# LOG_DIR is the absolute path of the directory where the test will collect all\n# logs to. By default, use the current directory.\nLOG_DIR=${LOG_DIR:-$(pwd)}\nmkdir -p \"$LOG_DIR\"\n\n# NETWORK_PLUGIN is the network plugin used by kubelet. Do not use network\n# plugin by default.\nNETWORK_PLUGIN=${NETWORK_PLUGIN:-\"\"}\n\n# CNI_CONF_DIR is the path to network plugin binaries.\nCNI_CONF_DIR=${CNI_CONF_DIR:-\"\"}\n\n# CNI_BIN_DIR is the path to network plugin config files.\nCNI_BIN_DIR=${CNI_BIN_DIR:-\"\"}\n\n# KUBELET_KUBECONFIG is the path to a kubeconfig file, specifying how to connect to the API server.\nKUBELET_KUBECONFIG=${KUBELET_KUBECONFIG:-\"/var/lib/kubelet/kubeconfig\"}\n\n# Creates a kubeconfig file for the kubelet.\n# Args: address (e.g. \"http://localhost:8080\"), destination file path\nfunction create-kubelet-kubeconfig() {\n  local api_addr=\"${1}\"\n  local dest=\"${2}\"\n  local dest_dir\n  dest_dir=\"$(dirname \"${dest}\")\"\n  mkdir -p \"${dest_dir}\" &>/dev/null || sudo mkdir -p \"${dest_dir}\"\n  sudo=$(test -w \"${dest_dir}\" || echo \"sudo -E\")\n  cat <<EOF | ${sudo} tee \"${dest}\" > /dev/null\napiVersion: v1\nkind: Config\nclusters:\n  - cluster:\n      server: ${api_addr}\n    name: local\ncontexts:\n  - context:\n      cluster: local\n    name: local\ncurrent-context: local\nEOF\n}\n\n# start_kubelet starts kubelet and redirect kubelet log to $LOG_DIR/kubelet.log.\nkubelet_log=kubelet.log\nstart_kubelet() {\n  echo \"Creating kubelet.kubeconfig\"\n  create-kubelet-kubeconfig \"http://localhost:8080\" \"${KUBELET_KUBECONFIG}\"\n  echo \"Starting kubelet...\"\n  # we want to run this command as root but log the file to a normal user file\n  # (so disable SC2024)\n  # shellcheck disable=SC2024\n  if ! sudo -b \"${KUBELET}\" \"$@\" &>\"${LOG_DIR}/${kubelet_log}\"; then\n    echo \"Failed to start kubelet\"\n    exit 1\n  fi\n}\n\n# wait_kubelet retries for 10 times for kubelet to be ready by checking http://127.0.0.1:10255/healthz.\nwait_kubelet() {\n  echo \"Health checking kubelet...\"\n  healthCheckURL=http://127.0.0.1:10255/healthz\n  local maxRetry=10\n  local cur=1\n  while [ $cur -le $maxRetry ]; do\n    if curl -s $healthCheckURL > /dev/null; then\n      echo \"Kubelet is ready\"\n      break\n    fi\n    if [ $cur -eq $maxRetry ]; then\n      echo \"Health check exceeds max retry\"\n      exit 1\n    fi\n    echo \"Kubelet is not ready\"\n    sleep 1\n    ((cur++))\n  done\n}\n\n# kill_kubelet kills kubelet.\nkill_kubelet() {\n  echo \"Stopping kubelet...\"\n  if ! sudo pkill \"${KUBELET_BIN}\"; then\n    echo \"Failed to stop kubelet.\"\n    exit 1\n  fi\n}\n\n# run_test runs the node test container.\nrun_test() {\n  env=\"\"\n  if [ -n \"$FOCUS\" ]; then\n    env=\"$env -e FOCUS=\\\"$FOCUS\\\"\"\n  fi\n  if [ -n \"$SKIP\" ]; then\n    env=\"$env -e SKIP=\\\"$SKIP\\\"\"\n  fi\n  if [ -n \"$TEST_ARGS\" ]; then\n    env=\"$env -e TEST_ARGS=\\\"$TEST_ARGS\\\"\"\n  fi\n  # The test assumes that inside the container:\n  # * kubelet manifest path is mounted to the same path;\n  # * log collect directory is mounted to /var/result;\n  # * root file system is mounted to /rootfs.\n  sudo sh -c \"docker run -it --rm --privileged=true --net=host -v /:/rootfs \\\n    -v $config_dir:$config_dir -v $LOG_DIR:/var/result ${env} $REGISTRY/node-test-$ARCH:$VERSION\"\n}\n\n# Check whether kubelet is running. If kubelet is running, tell the user to stop\n# it before running the test.\npid=$(pidof \"${KUBELET_BIN}\")\nif [ -n \"$pid\" ]; then\n  echo \"Kubelet is running (pid=$pid), please stop it before running the test.\"\n  exit 1\nfi\n\nvolume_stats_agg_period=10s\nserialize_image_pulls=false\nconfig_dir=$(mktemp -d)\nfile_check_frequency=10s\npod_cidr=10.100.0.0/24\nlog_level=4\nstart_kubelet --kubeconfig \"${KUBELET_KUBECONFIG}\" \\\n  --volume-stats-agg-period $volume_stats_agg_period \\\n  --serialize-image-pulls=$serialize_image_pulls \\\n  --pod-manifest-path \"${config_dir}\" \\\n  --file-check-frequency $file_check_frequency \\\n  --pod-cidr=$pod_cidr \\\n  --runtime-cgroups=/docker-daemon \\\n  --kubelet-cgroups=/kubelet \\\n  --system-cgroups=/system \\\n  --cgroup-root=/ \\\n  \"--network-plugin=${NETWORK_PLUGIN}\" \\\n  \"--cni-conf-dir=${CNI_CONF_DIR}\" \\\n  \"--cni-bin-dir=${CNI_BIN_DIR}\" \\\n  --v=$log_level \\\n  --logtostderr\n\nwait_kubelet\n\nrun_test\n\nkill_kubelet\n\n# Clean up the kubelet config directory\nsudo rm -rf \"${config_dir}\"\n", "num_lines": 217}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script used to configure node e2e test hosts from gce base images.\n# DISCLAIMER: This script is not actively tested or maintained.  No guarantees that this will work\n# on any host environment.  Contributions encouraged!  Send PRs to pwittrock (github.com).\n#\n# At some point has successfully configured the following distros:\n# - ubuntu trusty\n# - containervm (no-op)\n# - rhel 7\n# - centos 7\n# - debian jessie\n\n# RHEL os detection\ncat /etc/*-release | grep \"ID=\\\"rhel\\\"\"\nOS_RHEL=$?\n\n# On a systemd environment, enable cpu and memory accounting for all processes by default.\nif [ -d /etc/systemd ]; then\n  cat <<EOF >kubernetes-accounting.conf\n[Manager]\nDefaultCPUAccounting=yes\nDefaultMemoryAccounting=yes\nEOF\n  sudo mkdir -p /etc/systemd/system.conf.d/\n  sudo cp kubernetes-accounting.conf /etc/systemd/system.conf.d\n  sudo systemctl daemon-reload\nfi\n\n# For coreos, disable updates\nif sudo systemctl status update-engine &>/dev/null; then\n  sudo systemctl mask update-engine locksmithd\nfi\n\n# Fixup sudoers require tty\nif ! sudo grep -q \"# Defaults    requiretty\" /etc/sudoers; then\n  sudo sed -i 's/Defaults    requiretty/# Defaults    requiretty/' /etc/sudoers\nfi\n\n# Install nsenter for ubuntu images\nif cat /etc/*-release | grep \"ID=ubuntu\"; then\n  if ! which nsenter > /dev/null; then\n     echo \"Do not find nsenter. Install it.\"\n     NSENTER_BUILD_DIR=$(mktemp -d /tmp/nsenter-build-XXXXXX)\n     cd \"$NSENTER_BUILD_DIR\" || exit 1\n     curl https://www.kernel.org/pub/linux/utils/util-linux/v2.31/util-linux-2.31.tar.gz | tar -zxf-\n     sudo apt-get update\n     sudo apt-get --yes install make\n     sudo apt-get --yes install gcc\n     cd util-linux-2.31 || exit 1\n     ./configure --without-ncurses\n     make nsenter\n     sudo cp nsenter /usr/local/bin\n     rm -rf \"$NSENTER_BUILD_DIR\"\n   fi\nfi\n\n# Install docker\nif ! hash docker 2>/dev/null; then\n  # RHEL platforms should always install from RHEL repository\n  # This will install the latest supported stable docker platform on RHEL\n  if [ $OS_RHEL -eq 0 ]; then\n    sudo yum install -y docker-latest\n    sudo groupadd docker\n    sudo systemctl enable docker-latest.service\n    sudo systemctl start docker-latest.service\n  else\n    curl -fsSL https://get.docker.com/ | sh\n    sudo service docker start\n    sudo systemctl enable docker.service\n  fi\nfi\n\n# Allow jenkins access to docker\nid jenkins || sudo useradd jenkins -m\nsudo usermod -a -G docker jenkins\n\n# install lxc\nif ! cat /etc/*-release | grep \"ID=debian\"; then\n  hash apt-get 2>/dev/null\n  if [ $? -ne 1 ]; then\n    sudo apt-get install lxc -y\n    lxc-checkconfig\n    sudo sed -i 's/GRUB_CMDLINE_LINUX=\"\\(.*\\)\"/GRUB_CMDLINE_LINUX=\"\\1 cgroup_enable=memory\"/' /etc/default/grub\n    sudo update-grub\n  fi\nfi\n\n# delete init kubelet from containervm so that is doesn't startup\nif [ -f /etc/init.d/kubelet ]; then\n  sudo rm /etc/init.d/kubelet\nfi\n", "num_lines": 107}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage: copy-e2e-image.sh <image-name> <from-project-name> <to-project-name>\n\n# See *.properties for list of images to copy,\n# typically from kubernetes-node-e2e-images\n\nset -e\n\nprint_usage() {\n    echo \"This script helps copy a GCE image from a source to a target project\"\n    echo -e \"\\nUsage:\\n$0 <from-image-name> <from-project-name> <to-project-name> <to-image-name>\\n\"\n}\n\nif [  $# -ne 4 ]; then\n    print_usage\n    exit 1\nfi\n\nFROM_IMAGE=$1\nFROM_PROJECT=$2\nTO_PROJECT=$3\nTO_IMAGE=$4\n\necho \"Copying image $FROM_IMAGE from project $FROM_PROJECT to project $TO_PROJECT as image $TO_IMAGE...\"\ngcloud compute --project \"${TO_PROJECT}\" disks create \"${TO_IMAGE}\" --image=https://www.googleapis.com/compute/v1/projects/\"${FROM_PROJECT}/global/images/\"\"${FROM_IMAGE}\"\ngcloud compute --project \"${TO_PROJECT}\" images create \"${TO_IMAGE}\" \\\n  --source-disk=\"${TO_IMAGE}\" \\\n  --description=\"Cloned from projects/$2/global/images/$1 by $USER on $(date)\"\ngcloud -q compute --project \"${TO_PROJECT}\" disks delete \"${TO_IMAGE}\"\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script executed by jenkins to run node e2e tests against gce\n# Usage: test/e2e_node/jenkins/e2e-node-jenkins.sh <path to properties>\n# Properties files:\n# - test/e2e_node/jenkins/jenkins-ci.properties : for running jenkins ci\n# - test/e2e_node/jenkins/jenkins-pull.properties : for running jenkins pull request builder\n# - test/e2e_node/jenkins/template.properties : template for creating a properties file to run locally\n\nset -e\nset -x\n\n: \"${1:?Usage test/e2e_node/jenkins/e2e-node-jenkins.sh <path to properties>}\"\n\n. \"${1}\"\n\n# Until all GOPATH references are removed from all build scripts as well,\n# explicitly disable module mode to avoid picking up user-set GO111MODULE preferences.\n# As individual scripts make use of go modules, they can explicitly set GO111MODULE=on\nexport GO111MODULE=off\n\n# indirectly generates test/e2e/generated/bindata.go too\nmake generated_files\n\n# TODO converge build steps with hack/build-go some day if possible.\ngo build test/e2e_node/environment/conformance.go\n\nPARALLELISM=${PARALLELISM:-8}\nWORKSPACE=${WORKSPACE:-\"/tmp/\"}\nARTIFACTS=${WORKSPACE}/_artifacts\nTIMEOUT=${TIMEOUT:-\"45m\"}\n\nmkdir -p \"${ARTIFACTS}\"\n\ngo run test/e2e_node/runner/remote/run_remote.go  --logtostderr --vmodule=*=4 \\\n  --ssh-env=\"gce\" --ssh-user=\"$GCE_USER\" --zone=\"$GCE_ZONE\" --project=\"$GCE_PROJECT\" \\\n  --hosts=\"$GCE_HOSTS\" --images=\"$GCE_IMAGES\" --image-project=\"$GCE_IMAGE_PROJECT\" \\\n  --image-config-file=\"$GCE_IMAGE_CONFIG_PATH\" --cleanup=\"$CLEANUP\" \\\n  --results-dir=\"$ARTIFACTS\" --ginkgo-flags=\"--nodes=$PARALLELISM $GINKGO_FLAGS\" \\\n  --test-timeout=\"$TIMEOUT\" --test_args=\"$TEST_ARGS --kubelet-flags=\\\"$KUBELET_ARGS\\\"\" \\\n  --instance-metadata=\"$GCE_INSTANCE_METADATA\" --system-spec-name=\"$SYSTEM_SPEC_NAME\" \\\n  --extra-envs=\"$EXTRA_ENVS\"\n", "num_lines": 57}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is meant to install Nvidia drivers on Ubuntu 14.04 GCE VMs.\n# This script is meant to facilitate testing of Nvidia GPU support in Kubernetes.\necho \"Checking for CUDA and installing.\"\n# Check for CUDA and try to install.\nif ! dpkg-query -W cuda; then\n  curl -O http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1404/x86_64/cuda-repo-ubuntu1404_8.0.61-1_amd64.deb\n  dpkg -i ./cuda-repo-ubuntu1404_8.0.61-1_amd64.deb\n  apt-get update\n  apt-get install cuda -y\n  apt-get install \"linux-headers-$(uname -r)\" -y\nfi\n## Pre-loads kernel modules\nnvidia-smi\n", "num_lines": 30}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script executed by jenkins to run node conformance test against gce\n# Usage: test/e2e_node/jenkins/conformance-node-jenkins.sh <path to properties>\n\nset -e\nset -x\n\n: \"${1:?Usage test/e2e_node/jenkins/conformance-node-jenkins.sh <path to properties>}\"\n\n. \"${1}\"\n\nmake generated_files\n\nWORKSPACE=${WORKSPACE:-\"/tmp/\"}\nARTIFACTS=${WORKSPACE}/_artifacts\nTIMEOUT=${TIMEOUT:-\"45m\"}\n\nmkdir -p \"${ARTIFACTS}\"\n\ngo run test/e2e_node/runner/remote/run_remote.go  --test-suite=conformance \\\n  --logtostderr --vmodule=*=4 --ssh-env=\"gce\" --ssh-user=\"$GCE_USER\" \\\n  --zone=\"$GCE_ZONE\" --project=\"$GCE_PROJECT\" --hosts=\"$GCE_HOSTS\" \\\n  --images=\"$GCE_IMAGES\" --image-project=\"$GCE_IMAGE_PROJECT\" \\\n  --image-config-file=\"$GCE_IMAGE_CONFIG_PATH\" --cleanup=\"$CLEANUP\" \\\n  --results-dir=\"$ARTIFACTS\" --test-timeout=\"$TIMEOUT\" \\\n  --test_args=\"--kubelet-flags=\\\"$KUBELET_ARGS\\\"\" \\\n  --instance-metadata=\"$GCE_INSTANCE_METADATA\" \\\n  --system-spec-name=\"$SYSTEM_SPEC_NAME\" \\\n  --extra-envs=\"$EXTRA_ENVS\"\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTASK=${1}\nWHAT=${2}\n\n# docker buildx command is still experimental as of Docker 19.03.0\nexport DOCKER_CLI_EXPERIMENTAL=\"enabled\"\n\n# Connecting to a Remote Docker requires certificates for authentication, which can be found\n# at this path. By default, they can be found in the ${HOME} folder. We're expecting to find\n# here \".docker-${os_version}\" folders which contains the necessary certificates.\nDOCKER_CERT_BASE_PATH=\"${DOCKER_CERT_BASE_PATH:-${HOME}}\"\n\nKUBE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nsource \"${KUBE_ROOT}/hack/lib/logging.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\n# Mapping of go ARCH to actual architectures shipped part of multiarch/qemu-user-static project\ndeclare -A QEMUARCHS=( [\"amd64\"]=\"x86_64\" [\"arm\"]=\"arm\" [\"arm64\"]=\"aarch64\" [\"ppc64le\"]=\"ppc64le\" [\"s390x\"]=\"s390x\" )\n\nwindows_os_versions=(1809 1903 1909 2004 20H2)\ndeclare -A WINDOWS_OS_VERSIONS_MAP\n\ninitWindowsOsVersions() {\n  for os_version in \"${windows_os_versions[@]}\"; do\n    img_base=\"mcr.microsoft.com/windows/nanoserver:${os_version}\"\n    full_version=$(docker manifest inspect \"${img_base}\" | grep \"os.version\" | head -n 1 | awk '{print $2}') || true\n    WINDOWS_OS_VERSIONS_MAP[\"${os_version}\"]=\"${full_version}\"\n  done\n}\n\ninitWindowsOsVersions\n\n# Returns list of all supported architectures from BASEIMAGE file\nlistOsArchs() {\n  local image=${1}\n  cut -d \"=\" -f 1 \"${image}\"/BASEIMAGE\n}\n\nsplitOsArch() {\n  local image=${1}\n  local os_arch=${2}\n\n  if [[ $os_arch =~ .*/.*/.* ]]; then\n    # for Windows, we have to support both LTS and SAC channels, so we're building multiple Windows images.\n    # the format for this case is: OS/ARCH/OS_VERSION.\n    os_name=$(echo \"$os_arch\" | cut -d \"/\" -f 1)\n    arch=$(echo \"$os_arch\" | cut -d \"/\" -f 2)\n    os_version=$(echo \"$os_arch\" | cut -d \"/\" -f 3)\n    suffix=\"$os_name-$arch-$os_version\"\n  elif [[ $os_arch =~ .*/.* ]]; then\n    os_name=$(echo \"$os_arch\" | cut -d \"/\" -f 1)\n    arch=$(echo \"$os_arch\" | cut -d \"/\" -f 2)\n    os_version=\"\"\n    suffix=\"$os_name-$arch\"\n  else\n    echo \"The BASEIMAGE file for the ${image} image is not properly formatted. Expected entries to start with 'os/arch', found '${os_arch}' instead.\"\n    exit 1\n  fi\n}\n\n# Returns baseimage need to used in Dockerfile for any given architecture\ngetBaseImage() {\n  os_arch=$1\n  grep \"${os_arch}=\" BASEIMAGE | cut -d= -f2\n}\n\n# This function will build test image for all the architectures\n# mentioned in BASEIMAGE file. In the absence of BASEIMAGE file,\n# it will build for all the supported arch list - amd64, arm,\n# arm64, ppc64le, s390x\nbuild() {\n  local image=${1}\n  local img_folder=${1}\n  local output_type=${2}\n  docker_version_check\n\n  if [[ -f \"${img_folder}/BASEIMAGE\" ]]; then\n    os_archs=$(listOsArchs \"$image\")\n  else\n    # prepend linux/ to the QEMUARCHS items.\n    os_archs=$(printf 'linux/%s\\n' \"${!QEMUARCHS[@]}\")\n  fi\n\n  # image tag\n  TAG=$(<\"${img_folder}/VERSION\")\n\n  alias_name=\"$(cat \"${img_folder}/ALIAS\" 2>/dev/null || true)\"\n  if [[ -n \"${alias_name}\" ]]; then\n    echo \"Found an alias for '${image}'. Building / tagging image as '${alias_name}.'\"\n    image=\"${alias_name}\"\n  fi\n\n  kube::util::ensure-gnu-sed\n\n  for os_arch in ${os_archs}; do\n    splitOsArch \"${image}\" \"${os_arch}\"\n    if [[ \"${os_name}\" == \"windows\" && \"${output_type}\" == \"docker\" ]]; then\n      echo \"Cannot build the image '${image}' for ${os_arch}. Built Windows container images need to be pushed to a registry.\"\n      continue\n    fi\n\n    echo \"Building image for ${image} OS/ARCH: ${os_arch}...\"\n\n    # Create a temporary directory for every architecture and copy the image content\n    # and build the image from temporary directory\n    mkdir -p \"${KUBE_ROOT}\"/_tmp\n    temp_dir=$(mktemp -d \"${KUBE_ROOT}\"/_tmp/test-images-build.XXXXXX)\n    kube::util::trap_add \"rm -rf ${temp_dir}\" EXIT\n\n    cp -r \"${img_folder}\"/* \"${temp_dir}\"\n    if [[ -f ${img_folder}/Makefile ]]; then\n      # make bin will take care of all the prerequisites needed\n      # for building the docker image\n      make -C \"${img_folder}\" bin OS=\"${os_name}\" ARCH=\"${arch}\" TARGET=\"${temp_dir}\"\n    fi\n    pushd \"${temp_dir}\"\n\n    # NOTE(claudiub): Some Windows images might require their own Dockerfile\n    # while simpler ones will not. If we're building for Windows, check if\n    # \"Dockerfile_windows\" exists or not.\n    dockerfile_name=\"Dockerfile\"\n    if [[ \"$os_name\" = \"windows\" && -f \"Dockerfile_windows\" ]]; then\n      dockerfile_name=\"Dockerfile_windows\"\n    fi\n\n    base_image=\"\"\n    if [[ -f BASEIMAGE ]]; then\n      base_image=$(getBaseImage \"${os_arch}\" | \"${SED}\" \"s|REGISTRY|${REGISTRY}|g\")\n      \"${SED}\" -i \"s|BASEARCH|${arch}|g\" $dockerfile_name\n    fi\n\n    # Only the cross-build on x86 is guaranteed by far, other arches like aarch64 doesn't support cross-build\n    # thus, there is no need to tackle a disability feature on those platforms, and also help to prevent from\n    # ending up a wrong image tag on non-amd64 platforms.\n    build_arch=$(uname -m)\n    if [[ ${build_arch} = 'x86_64' ]]; then\n        # copy the qemu-*-static binary to docker image to build the multi architecture image on x86 platform\n        if grep -q 'CROSS_BUILD_' Dockerfile; then\n          if [[ \"${arch}\" = 'amd64' ]]; then\n            \"${SED}\" -i '/CROSS_BUILD_/d' Dockerfile\n          else\n            \"${SED}\" -i \"s|QEMUARCH|${QEMUARCHS[$arch]}|g\" Dockerfile\n            # Register qemu-*-static for all supported processors except the current one\n            echo 'Registering qemu-*-static binaries in the kernel'\n            local sudo=\"\"\n            if [[ $(id -u) -ne 0 ]]; then\n\t            sudo=\"sudo\"\n            fi\n            ${sudo} docker run --rm --privileged tonistiigi/binfmt:latest --install all\n            curl -sSL https://github.com/multiarch/qemu-user-static/releases/download/\"${QEMUVERSION}\"/x86_64_qemu-\"${QEMUARCHS[$arch]}\"-static.tar.gz | tar -xz -C \"${temp_dir}\"\n            # Ensure we don't get surprised by umask settings\n            chmod 0755 \"${temp_dir}/qemu-${QEMUARCHS[$arch]}-static\"\n            \"${SED}\" -i 's/CROSS_BUILD_//g' Dockerfile\n          fi\n        fi\n    elif [[ \"${QEMUARCHS[$arch]}\" != \"${build_arch}\" ]]; then\n\t\techo \"skip cross-build $arch on non-supported platform ${build_arch}.\"\n\t\tpopd\n        continue\n    else\n        \"${SED}\" -i '/CROSS_BUILD_/d' Dockerfile\n    fi\n\n    docker buildx build --progress=plain --no-cache --pull --output=type=\"${output_type}\" --platform \"${os_name}/${arch}\" \\\n        --build-arg BASEIMAGE=\"${base_image}\" --build-arg REGISTRY=\"${REGISTRY}\" --build-arg OS_VERSION=\"${os_version}\" \\\n        -t \"${REGISTRY}/${image}:${TAG}-${suffix}\" -f \"${dockerfile_name}\" .\n\n    popd\n  done\n}\n\ndocker_version_check() {\n  # docker buildx has been introduced in 19.03, so we need to make sure we have it.\n  docker_version=$(docker version --format '{{.Client.Version}}' | cut -d\"-\" -f1)\n  if [[ ${docker_version} != 19.03.0 && ${docker_version} < 19.03.0 ]]; then\n    echo \"Minimum docker version 19.03.0 is required for using docker buildx: ${docker_version}]\"\n    exit 1\n  fi\n}\n\n# This function will push the docker images\npush() {\n  local image=${1}\n  docker_version_check\n\n  TAG=$(<\"${image}\"/VERSION)\n  if [[ -f ${image}/BASEIMAGE ]]; then\n    os_archs=$(listOsArchs \"$image\")\n  else\n    # prepend linux/ to the QEMUARCHS items.\n    os_archs=$(printf 'linux/%s\\n' \"${!QEMUARCHS[@]}\")\n  fi\n\n  pushd \"${image}\"\n  alias_name=\"$(cat ALIAS 2>/dev/null || true)\"\n  if [[ -n \"${alias_name}\" ]]; then\n    echo \"Found an alias for '${image}'. Pushing image as '${alias_name}.'\"\n    image=\"${alias_name}\"\n  fi\n\n  kube::util::ensure-gnu-sed\n\n  # reset manifest list; needed in case multiple images are being built / pushed.\n  manifest=()\n  # Make os_archs list into image manifest. Eg: 'linux/amd64 linux/ppc64le' to '${REGISTRY}/${image}:${TAG}-linux-amd64 ${REGISTRY}/${image}:${TAG}-linux-ppc64le'\n  while IFS='' read -r line; do manifest+=(\"$line\"); done < <(echo \"$os_archs\" | \"${SED}\" \"s~\\/~-~g\" | \"${SED}\" -e \"s~[^ ]*~$REGISTRY\\/$image:$TAG\\-&~g\")\n  docker manifest create --amend \"${REGISTRY}/${image}:${TAG}\" \"${manifest[@]}\"\n\n  # We will need the full registry name in order to set the \"os.version\" for Windows images.\n  # If the ${REGISTRY} dcesn't have any slashes, it means that it's on dockerhub.\n  registry_prefix=\"\"\n  if [[ ! $REGISTRY =~ .*/.* ]]; then\n    registry_prefix=\"docker.io/\"\n  fi\n  # The images in the manifest list are stored locally. The folder / file name is almost the same,\n  # with a few changes.\n  manifest_image_folder=$(echo \"${registry_prefix}${REGISTRY}/${image}:${TAG}\" | sed \"s|/|_|g\" | sed \"s/:/-/\")\n\n  for os_arch in ${os_archs}; do\n    splitOsArch \"${image}\" \"${os_arch}\"\n    docker manifest annotate --os \"${os_name}\" --arch \"${arch}\" \"${REGISTRY}/${image}:${TAG}\" \"${REGISTRY}/${image}:${TAG}-${suffix}\"\n\n    # For Windows images, we also need to include the \"os.version\" in the manifest list, so the Windows node\n    # can pull the proper image it needs.\n    if [[ \"$os_name\" = \"windows\" ]]; then\n      full_version=\"${WINDOWS_OS_VERSIONS_MAP[$os_version]}\"\n\n      # At the moment, docker manifest annotate doesn't allow us to set the os.version, so we'll have to\n      # it ourselves. The manifest list can be found locally as JSONs.\n      sed -i -r \"s/(\\\"os\\\"\\:\\\"windows\\\")/\\0,\\\"os.version\\\":$full_version/\" \\\n        \"${HOME}/.docker/manifests/${manifest_image_folder}/${manifest_image_folder}-${suffix}\"\n    fi\n  done\n  popd\n  docker manifest push --purge \"${REGISTRY}/${image}:${TAG}\"\n}\n\n# This function is for building AND pushing images. Useful if ${WHAT} is \"all-conformance\".\n# This will allow images to be pushed immediately after they've been built.\nbuild_and_push() {\n  local image=${1}\n  build \"${image}\" \"registry\"\n  push \"${image}\"\n}\n\n# This function is for building the go code\nbin() {\n  local arch_prefix=\"\"\n  if [[ \"${ARCH:-}\" == \"arm\" ]]; then\n    arch_prefix=\"GOARM=${GOARM:-7}\"\n  fi\n  for SRC in \"$@\";\n  do\n  docker run --rm -v \"${TARGET}:${TARGET}:Z\" -v \"${KUBE_ROOT}\":/go/src/k8s.io/kubernetes:Z \\\n        golang:\"${GOLANG_VERSION}\" \\\n        /bin/bash -c \"\\\n                cd /go/src/k8s.io/kubernetes/test/images/${SRC_DIR} && \\\n                CGO_ENABLED=0 ${arch_prefix} GOOS=${OS} GOARCH=${ARCH} go build -a -installsuffix cgo --ldflags '-w' -o ${TARGET}/${SRC} ./$(dirname \"${SRC}\")\"\n  done\n}\n\nshift\n\nif [[ \"${WHAT}\" == \"all-conformance\" ]]; then\n  # NOTE(claudiub): Building *ALL* the images under the kubernetes/test/images folder takes an extremely\n  # long time (especially some images), and some images are rarely used and rarely updated, so there's\n  # no point in rebuilding all of them every time. This will only build the Conformance-related images.\n  # Discussed during Conformance Office Hours Meeting (2019.12.17):\n  # https://docs.google.com/document/d/1W31nXh9RYAb_VaYkwuPLd1hFxuRX3iU0DmaQ4lkCsX8/edit#heading=h.l87lu17xm9bh\n  shift\n  conformance_images=(\"busybox\" \"agnhost\" \"echoserver\" \"jessie-dnsutils\" \"kitten\" \"nautilus\" \"nonewprivs\" \"resource-consumer\" \"sample-apiserver\")\n  for image in \"${conformance_images[@]}\"; do\n    eval \"${TASK}\" \"${image}\" \"$@\"\n  done\nelse\n  eval \"${TASK}\" \"$@\"\nfi\n", "num_lines": 297}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nARCH=$(uname -m)\n\nif [ \"${ARCH}\" = \"s390x\" ]; then\n    echo \"http://dl-cdn.alpinelinux.org/alpine/v3.8/main\" > /etc/apk/repositories\n    echo \"http://dl-cdn.alpinelinux.org/alpine/v3.8/community\" >> /etc/apk/repositories\nfi\n\napk add --no-cache openssl nginx-mod-http-lua nginx-mod-http-lua-upstream\n\nexit 0\n", "num_lines": 27}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\necho \"Generating self-signed cert\"\nmkdir -p /certs\nopenssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 \\\n-keyout /certs/privateKey.key \\\n-out /certs/certificate.crt \\\n-subj \"/C=UK/ST=Warwickshire/L=Leamington/O=OrgName/OU=IT Department/CN=example.com\"\n\n# If we're running on Windows, skip loading the Linux .so modules.\nif [ \"$(uname)\" = \"Windows_NT\" ]; then\n\tsed -i -E \"s/^(load_module modules\\/ndk_http_module.so;)$/#\\1/\" conf/nginx.conf\n\tsed -i -E \"s/^(load_module modules\\/ngx_http_lua_module.so;)$/#\\1/\" conf/nginx.conf\n\tsed -i -E \"s/^(load_module modules\\/ngx_http_lua_upstream_module.so;)$/#\\1/\" conf/nginx.conf\n\n\t# NOTE(claudiub): on Windows, nginx will take the paths in the nginx.conf file as relative paths.\n\tcmd /S /C \"mklink /D C:\\\\openresty\\\\certs C:\\\\certs\"\nfi\n\necho \"Starting nginx\"\nnginx -g \"daemon off;\"\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nDEB_ARCH=$(dpkg --print-architecture)\n\n# http://security.debian.org/debian-security/dists/jessie/updates/InRelease is missing\n# entries for some platforms, so we just remove the last line in sources.list in\n# /etc/apt/sources.list which is \"deb http://deb.debian.org/debian jessie-updates main\"\n\ncase ${DEB_ARCH} in\n    s390x|arm64|ppc64el)\n        # we have to use the archive mirrors.\n        # See: https://lists.debian.org/debian-devel-announce/2019/03/msg00006.html\n        echo \"deb http://archive.debian.org/debian/ jessie main contrib non-free\" | tee /etc/apt/sources.list\n        echo \"deb-src http://archive.debian.org/debian/ jessie main contrib non-free\" | tee -a /etc/apt/sources.list\n       ;;\nesac\n\nexit 0\n", "num_lines": 33}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This volume is assumed to exist and is shared with parent of the init\n# container. It contains the redis installation.\nINSTALL_VOLUME=\"/opt\"\n\n# This volume is assumed to exist and is shared with the peer-finder\n# init container. It contains on-start/change configuration scripts.\nWORK_DIR=\"/work-dir\"\n\nVERSION=\"3.2.0\"\n\nfor i in \"$@\"\ndo\ncase $i in\n    -i=*|--install-into=*)\n    INSTALL_VOLUME=\"${i#*=}\"\n    shift\n    ;;\n    -w=*|--work-dir=*)\n    WORK_DIR=\"${i#*=}\"\n    shift\n    ;;\n    *)\n    # unknown option\n    ;;\nesac\ndone\n\necho installing config scripts into \"${WORK_DIR}\"\nmkdir -p \"${WORK_DIR}\"\ncp /on-start.sh \"${WORK_DIR}\"/\ncp /peer-finder \"${WORK_DIR}\"/\n\necho installing redis-\"${VERSION}\" into \"${INSTALL_VOLUME}\"\nmkdir -p \"${INSTALL_VOLUME}\"\nmv /redis \"${INSTALL_VOLUME}\"/redis\n", "num_lines": 52}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nCFG=/opt/redis/redis.conf\nHOSTNAME=$(hostname)\nDATADIR=\"/data\"\n# Port on which redis listens for connections.\nPORT=6379\n\n# Ping everyone but ourself to see if there's a master. Only one pet starts at\n# a time, so if we don't see a master we can assume the position is ours.\nwhile read -ra LINE; do\n    if [[ \"${LINE[0]}\" == *\"${HOSTNAME}\"* ]]; then\n        sed -i -e \"s|^bind.*$|bind ${LINE[0]}|\" ${CFG}\n    elif [ \"$(/opt/redis/redis-cli -h \"${LINE[0]}\" info | grep role | sed 's,\\r$,,')\" = \"role:master\" ]; then\n        # TODO: More restrictive regex?\n        sed -i -e \"s|^# slaveof.*$|slaveof ${LINE[0]} ${PORT}|\" ${CFG}\n    fi\ndone\n\n# Set the data directory for append only log and snapshot files. This should\n# be a persistent volume for consistency.\nsed -i -e \"s|^.*dir .*$|dir ${DATADIR}|\" ${CFG}\n\n# The append only log is written for every SET operation. Without this setting,\n# redis just snapshots periodically which is only safe for a cache. This will\n# produce an appendonly.aof file in the configured data dir.\nsed -i -e \"s|^appendonly .*$|appendonly yes|\" ${CFG}\n\n# Every write triggers an fsync. Recommended default is \"everysec\", which\n# is only safe for AP applications.\nsed -i -e \"s|^appendfsync .*$|appendfsync always|\" ${CFG}\n\n\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This volume is assumed to exist and is shared with parent of the init\n# container. It contains the zookeeper installation.\nINSTALL_VOLUME=\"/opt\"\n\n# This volume is assumed to exist and is shared with the peer-finder\n# init container. It contains on-start/change configuration scripts.\nWORKDIR_VOLUME=\"/work-dir\"\n\n# As of April-2016 is 3.4.8 is the latest stable, but versions 3.5.0 onward\n# allow dynamic reconfiguration.\nVERSION=\"3.5.0-alpha\"\n\nfor i in \"$@\"\ndo\ncase $i in\n    -i=*|--install-into=*)\n    INSTALL_VOLUME=\"${i#*=}\"\n    shift\n    ;;\n    -w=*|--work-dir=*)\n    WORKDIR_VOLUME=\"${i#*=}\"\n    shift\n    ;;\n    *)\n    # unknown option\n    ;;\nesac\ndone\n\necho installing config scripts into \"${WORKDIR_VOLUME}\"\nmkdir -p \"${WORKDIR_VOLUME}\"\ncp /on-start.sh \"${WORKDIR_VOLUME}\"/\ncp /peer-finder \"${WORKDIR_VOLUME}\"/\n\necho installing zookeeper-\"${VERSION}\" into \"${INSTALL_VOLUME}\"\nmkdir -p \"${INSTALL_VOLUME}\"\nmv /zookeeper \"${INSTALL_VOLUME}\"/zookeeper\ncp \"${INSTALL_VOLUME}\"/zookeeper/conf/zoo_sample.cfg \"${INSTALL_VOLUME}\"/zookeeper/conf/zoo.cfg\n\n# TODO: Should dynamic config be tied to the version?\nIFS=\".\" read -ra RELEASE <<< \"${VERSION}\"\nif [ \"$((\"${RELEASE[1]}\"))\" -gt 4 ]; then\n    echo zookeeper-\"${VERSION}\" supports dynamic reconfiguration, enabling it\n    echo \"standaloneEnabled=false\" >> \"${INSTALL_VOLUME}\"/zookeeper/conf/zoo.cfg\n    echo \"dynamicConfigFile=${INSTALL_VOLUME}/zookeeper/conf/zoo.cfg.dynamic\" >> \"${INSTALL_VOLUME}\"/zookeeper/conf/zoo.cfg\nfi\n\n# TODO: This is a hack, netcat is convenient to have in the zookeeper container\n# I want to avoid using a custom zookeeper image just for this. So copy it.\nNC=$(which nc)\nif [ \"${NC}\" != \"\" ]; then\n    echo copying nc into \"${INSTALL_VOLUME}\"\n    cp \"${NC}\" \"${INSTALL_VOLUME}\"\nfi\n", "num_lines": 71}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\n# This script configures zookeeper cluster member ship for version of zookeeper\n# >= 3.5.0. It should not be used with the on-change.sh script in this example.\n# As of April-2016 is 3.4.8 is the latest stable.\n\n# Both /opt and /tmp/zookeeper are assumed to be volumes shared with the parent.\n# The format of each line in the dynamic config file is:\n# server.<1 based index>=<server-dns-name>:<peer port>:<election port>[:role];[<client port address>:]<client port>\n# <1 based index> is the server index that matches the id in datadir/myid\n# <peer port> is the port on which peers communicate to agree on updates\n# <election port> is the port used for leader election\n# [:role] can be set to observer, participant by default\n# <client port address> is optional and defaults to 0.0.0.0\n# <client port> is the port on which the server accepts client connections\n\nCFG=/opt/zookeeper/conf/zoo.cfg.dynamic\nCFG_BAK=/opt/zookeeper/conf/zoo.cfg.bak\nMY_ID_FILE=/tmp/zookeeper/myid\nHOSTNAME=$(hostname)\n\nwhile read -ra LINE; do\n    PEERS=(\"${PEERS[@]}\" \"${LINE[0]}\")\ndone\n\n# Don't add the first member as an observer\nif [ ${#PEERS[@]} -eq 1 ]; then\n    # We need to write our index in this list of servers into MY_ID_FILE.\n    # Note that this may not always coincide with the hostname id.\n    echo 1 > \"${MY_ID_FILE}\"\n    echo \"server.1=${PEERS[0]}:2888:3888;2181\" > \"${CFG}\"\n    # TODO: zkServer-initialize is the safe way to handle changes to datadir\n    # because simply starting will create a new datadir, BUT if the user changed\n    # pod template they might end up with 2 datadirs and brief split brain.\n    exit\nfi\n\n# Every subsequent member is added as an observer and promoted to a participant\necho \"\" > \"${CFG_BAK}\"\ni=0\nLEADER=$HOSTNAME\nfor peer in \"${PEERS[@]}\"; do\n    (( i=i+1 ))\n    if [[ \"${peer}\" == *\"${HOSTNAME}\"* ]]; then\n      MY_ID=$i\n      MY_NAME=${peer}\n      echo \"$i\" > \"${MY_ID_FILE}\"\n      echo \"server.${i}=${peer}:2888:3888:observer;2181\" >> \"${CFG_BAK}\"\n    else\n      if [[ $(echo srvr | /opt/nc \"${peer}\" 2181 | grep Mode) = \"Mode: leader\" ]]; then\n        LEADER=\"${peer}\"\n      fi\n      echo \"server.${i}=${peer}:2888:3888:participant;2181\" >> \"${CFG_BAK}\"\n    fi\ndone\n\n# zookeeper won't start without myid anyway.\n# This means our hostname wasn't in the peer list.\nif [ ! -f \"${MY_ID_FILE}\" ]; then\n  exit 1\nfi\n\n# Once the dynamic config file is written it shouldn't be modified, so the final\n# reconfigure needs to happen through the \"reconfig\" command.\ncp ${CFG_BAK} ${CFG}\n\n# TODO: zkServer-initialize is the safe way to handle changes to datadir\n# because simply starting will create a new datadir, BUT if the user changed\n# pod template they might end up with 2 datadirs and brief split brain.\n/opt/zookeeper/bin/zkServer.sh start\n\n# TODO: We shouldn't need to specify the address of the master as long as\n# there's quorum. According to the docs the new server is just not allowed to\n# vote, it's still allowed to propose config changes, and it knows the\n# existing members of the ensemble from *its* config.\nADD_SERVER=\"server.$MY_ID=$MY_NAME:2888:3888:participant;0.0.0.0:2181\"\n/opt/zookeeper/bin/zkCli.sh reconfig -s \"${LEADER}\":2181 -add \"${ADD_SERVER}\"\n\n# Prove that we've actually joined the running cluster\nITERATION=0\nuntil echo config | /opt/nc localhost 2181 | grep \"${ADD_SERVER}\" > /dev/null; do\n  echo \"$ITERATION\"] waiting for updated config to sync back to localhost\n  sleep 1\n  (( ITERATION=ITERATION+1 ))\n  if [ \"$ITERATION\" -eq 20 ]; then\n    exit 1\n  fi\ndone\n\n/opt/zookeeper/bin/zkServer.sh stop\n", "num_lines": 107}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nDIR=\"$(mktemp -d)\"\n\nfunction start()\n{\n    mount -t tmpfs test \"$DIR\"\n    chmod 755 \"$DIR\"\n    cp /vol/* \"$DIR/\"\n    /usr/sbin/glusterd -p /run/glusterd.pid\n    gluster volume create test_vol \"$(hostname -i):$DIR\" force\n    gluster volume start test_vol\n}\n\nfunction stop()\n{\n    gluster --mode=script volume stop test_vol force\n    kill \"$(cat /run/glusterd.pid)\"\n    umount \"$DIR\"\n    rm -rf \"$DIR\"\n    exit 0\n}\n\n\ntrap stop TERM\n\nstart \"$@\"\n\nwhile true; do\n    sleep 5\ndone\n\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Exit on the first error.\nset -e\n\nMNTDIR=\"$(mktemp -d)\"\n\ncleanup()\n{\n    # Make sure we return the right exit code\n    RET=$?\n    # Silently remove everything and ignore errors\n    set +e\n    /bin/umount \"$MNTDIR\" 2>/dev/null\n    /bin/rmdir \"$MNTDIR\" 2>/dev/null\n    /bin/rm block 2>/dev/null\n    exit $RET\n}\n\ntrap cleanup TERM EXIT\n\n# Create 120MB device with ext2\n# (volume_io tests need at least 100MB)\ndd if=/dev/zero of=block seek=120 count=1 bs=1M\nmkfs.ext2 block\n\n# Add index.html to it\nmount -o loop block \"$MNTDIR\"\necho \"Hello from iscsi\" > \"$MNTDIR/index.html\"\numount \"$MNTDIR\"\n\nrm block.tar.gz 2>/dev/null || :\ntar cfz block.tar.gz block\n", "num_lines": 48}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script does not run any daemon, it only configures iSCSI target (=server)\n# in kernel. It is possible to run this script multiple times on a single\n# node, each run will create its own IQN and LUN.\n\n# Kubernetes must provide unique name.\nIQN=$1\n\n# targetcli synchronizes over dbus, however it does not work in\n# containers. Use flock instead\nLOCK=/srv/iscsi/targetcli.lock\n\nfunction start()\n{\n    # targetcli need dbus. It may not run on the host, so start a private one\n    mkdir /run/dbus\n    dbus-daemon  --system\n\n    # Create new IQN (iSCSI Qualified Name)\n    flock $LOCK targetcli /iscsi create \"$IQN\"\n    # Run it in demo mode, i.e. no authentication\n    flock $LOCK targetcli /iscsi/\"$IQN\"/tpg1 set attribute authentication=0 demo_mode_write_protect=0 generate_node_acls=1 cache_dynamic_acls=1\n\n    # Create unique \"block volume\" (i.e. flat file) on the *host*.\n    # Having it in the container confuses kernel from some reason\n    # and it's not able to server multiple LUNs from different\n    # containers.\n    # /srv/iscsi must be bind-mount from the host.\n    cp /block /srv/iscsi/\"$IQN\"\n\n    # Make the block volume available through our IQN as LUN 0\n    flock $LOCK targetcli /backstores/fileio create block-\"$IQN\" /srv/iscsi/\"$IQN\"\n    flock $LOCK targetcli /iscsi/\"$IQN\"/tpg1/luns create /backstores/fileio/block-\"$IQN\"\n\n    echo \"iscsi target started\"\n}\n\nfunction stop()\n{\n    echo \"stopping iscsi target\"\n    # Remove IQN\n    flock $LOCK targetcli /iscsi/\"$IQN\"/tpg1/luns/ delete 0\n    flock $LOCK targetcli /iscsi delete \"$IQN\"\n    # Remove block device mapping\n    flock $LOCK targetcli /backstores/fileio delete block-\"$IQN\"\n    /bin/rm -f /srv/iscsi/\"$IQN\"\n    echo \"iscsi target stopped\"\n    exit 0\n}\n\n\ntrap stop TERM\nstart\n\nwhile true; do\n    sleep 1\ndone\n", "num_lines": 73}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction start()\n{\n\n    unset gid\n    # accept \"-G gid\" option\n    while getopts \"G:\" opt; do\n        case ${opt} in\n            G) gid=${OPTARG};;\n            *):;;\n        esac\n    done\n    shift $((OPTIND - 1))\n\n    # prepare /etc/exports\n    for i in \"$@\"; do\n        # fsid=0: needed for NFSv4\n        echo \"$i *(rw,fsid=0,insecure,no_root_squash)\" >> /etc/exports\n        if [ -v gid ] ; then\n            chmod 070 \"$i\"\n            chgrp \"$gid\" \"$i\"\n        fi\n        # move index.html to here\n        /bin/cp /tmp/index.html \"$i/\"\n        chmod 644 \"$i/index.html\"\n        echo \"Serving $i\"\n    done\n\n    # start rpcbind if it is not started yet\n    /usr/sbin/rpcinfo 127.0.0.1 > /dev/null; s=$?\n    if [ $s -ne 0 ]; then\n       echo \"Starting rpcbind\"\n       /usr/sbin/rpcbind -w\n    fi\n\n    mount -t nfsd nfsd /proc/fs/nfsd\n\n    # -V 3: enable NFSv3\n    /usr/sbin/rpc.mountd -N 2 -V 3\n\n    /usr/sbin/exportfs -r\n    # -G 10 to reduce grace time to 10 seconds (the lowest allowed)\n    /usr/sbin/rpc.nfsd -G 10 -N 2 -V 3\n    /usr/sbin/rpc.statd --no-notify\n    echo \"NFS started\"\n}\n\nfunction stop()\n{\n    echo \"Stopping NFS\"\n\n    /usr/sbin/rpc.nfsd 0\n    /usr/sbin/exportfs -au\n    /usr/sbin/exportfs -f\n\n    kill \"$( pidof rpc.mountd )\"\n    umount /proc/fs/nfsd\n    echo > /etc/exports\n    exit 0\n}\n\n\ntrap stop TERM\n\nstart \"$@\"\n\n# Ugly hack to do nothing and wait for SIGTERM\nwhile true; do\n    sleep 5\ndone\n", "num_lines": 86}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Bootstraps a CEPH server.\n# It creates two OSDs on local machine, creates RBD pool there\n# and imports 'block' device there.\n#\n# We must create fresh OSDs and filesystem here, because shipping it\n# in a container would increase the image by ~300MB.\n#\n\n\n# Create /etc/ceph/ceph.conf\nsh ./ceph.conf.sh \"$(hostname -i)\"\n\n# Configure and start ceph-mon\nsh ./mon.sh \"$(hostname -i)\"\n\n# Configure and start 2x ceph-osd\nmkdir -p /var/lib/ceph/osd/ceph-0 /var/lib/ceph/osd/ceph-1\nsh ./osd.sh 0\nsh ./osd.sh 1\n\n# Configure and start cephfs metadata server\nsh ./mds.sh\n\n# Prepare a RBD volume \"foo\" (only with layering feature, the others may\n# require newer clients).\n# NOTE: we need Ceph kernel modules on the host that runs the client!\n# As the default pool `rbd` might not be created on arm64 platform for ceph deployment,\n# should create it if it does not exist.\narch=$(uname -m)\nif [[ ${arch} = 'aarch64' || ${arch} = 'arm64' ]]; then\n    if [[ $(ceph osd lspools) = \"\" ]]; then\n        ceph osd pool create rbd 8\n        rbd pool init rbd\n    fi\nfi\nrbd import --image-feature layering block foo\n\n# Prepare a cephfs volume\nceph osd pool create cephfs_data 4\nceph osd pool create cephfs_metadata 4\nceph fs new cephfs cephfs_metadata cephfs_data\n# Put index.html into the volume\n# It takes a while until the volume created above is mountable,\n# 1 second is usually enough, but try indefinetily.\nsleep 1\nwhile ! ceph-fuse -m \"$(hostname -i):6789\" /mnt; do\n    echo \"Waiting for cephfs to be up\"\n    sleep 1\ndone\necho \"Hello Ceph!\" > /mnt/index.html\nchmod 644 /mnt/index.html\numount /mnt\n\necho \"Ceph is ready\"\n\n# Wait forever\nwhile true; do\n    sleep 10\ndone\n", "num_lines": 77}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Configures /etc/ceph.conf from a template.\n#\n\necho \"\n[global]\nauth cluster required = none\nauth service required = none\nauth client required = none\n\n[mon.a]\nhost = cephbox\nmon addr = $1\n\n[osd]\nosd journal size = 128\njournal dio = false\n\n# allow running on ext4\nosd max object name len = 256\nosd max object namespace len = 64\n\n[osd.0]\nosd host = cephbox\n\" > /etc/ceph/ceph.conf\n\n", "num_lines": 43}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Create block.tar.gz with a small ext2 filesystem.\n# It must be run as root (to mount with '-o loop')!\n\n# Exit on the first error.\nset -e\n\nMNTDIR=\"$(mktemp -d)\"\n\ncleanup()\n{\n    # Make sure we return the right exit code\n    RET=$?\n    # Silently remove everything and ignore errors\n    set +e\n    /bin/umount \"$MNTDIR\" 2>/dev/null\n    /bin/rmdir \"$MNTDIR\" 2>/dev/null\n    /bin/rm block 2>/dev/null\n    exit $RET\n}\n\ntrap cleanup TERM EXIT\n\n# Create 120MB device with ext2\n# (volume_io tests need at least 100MB)\ndd if=/dev/zero of=block seek=120 count=1 bs=1M\nmkfs.ext2 block\n\n# Add index.html to it\nmount -o loop block \"$MNTDIR\"\necho \"Hello from RBD\" > \"$MNTDIR/index.html\"\numount \"$MNTDIR\"\n\nrm block.tar.gz 2>/dev/null || :\ntar cfz block.tar.gz block\n", "num_lines": 51}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Configures Ceph Metadata Service (mds), needed by CephFS\n#\nceph-mds -i cephfs -c /etc/ceph/ceph.conf\n", "num_lines": 21}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Configures and launches a new MON.\n#\n\n# monitor setup\nmonmaptool --create --clobber --fsid \"$(uuidgen)\" --add a \"${1}\":6789 /etc/ceph/monmap\nmkdir /var/lib/ceph/mon/ceph-a\nceph-mon -i a --mkfs --monmap /etc/ceph/monmap -k /var/lib/ceph/mon/keyring\ncp /var/lib/ceph/mon/keyring /var/lib/ceph/mon/ceph-a\nceph-mon -i a --monmap /etc/ceph/monmap -k /var/lib/ceph/mon/ceph-a/keyring\n\n# client setup (handy)\ncp /var/lib/ceph/mon/keyring /etc/ceph\n\n# for this test we want to\nceph osd getcrushmap -o /tmp/crushc\ncrushtool -d /tmp/crushc -o /tmp/crushd\nsed -i 's/step chooseleaf firstn 0 type host/step chooseleaf firstn 0 type osd/' /tmp/crushd\ncrushtool -c /tmp/crushd -o /tmp/crushc\nceph osd setcrushmap -i /tmp/crushc\n", "num_lines": 37}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# Configures and launches a new OSD.\n#\n\nceph osd create\nceph-osd -i \"${1}\" --mkfs --mkkey\nceph auth add \"osd.${1}\" osd 'allow *' mon 'allow rwx' -i \"/var/lib/ceph/osd/ceph-${1}/keyring\"\nceph osd crush add \"${1}\" 1 root=default host=cephbox\nceph-osd -i \"${1}\" -k \"/var/lib/ceph/osd/ceph-${1}/keyring\"\n", "num_lines": 26}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\nsource \"${KUBE_ROOT}/hack/lib/util.sh\"\n\nstability_check_setup() {\n  kube::golang::verify_go_version\n  kube::util::ensure-temp-dir\n  cd \"${KUBE_ROOT}\"\n  export KUBE_EXTRA_GOPATH=$KUBE_TEMP\n  kube::golang::setup_env\n  pushd \"${KUBE_EXTRA_GOPATH}\" >/dev/null\n    GO111MODULE=on go get \"gopkg.in/yaml.v2\"\n  popd >/dev/null\n}\n\nfind_files_to_check() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './_output' \\\n        -o -wholename './_gopath' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename '*/hack/*' \\\n        -o -wholename '*_test.go' \\\n        \\) -prune \\\n    \\) \\\n    \\( -wholename '**/*.go' \\\n  \\)\n}\n\nred=$(tput setaf 1)\ngreen=$(tput setaf 2)\nreset=$(tput sgr0)\n\nkube::validate::stablemetrics() {\n  stability_check_setup\n  temp_file=$(mktemp)\n  doValidate=$(find_files_to_check | grep -E \".*.go\" | grep -v \".*_test.go\" | sort | xargs -L 200 go run \"test/instrumentation/main.go\" \"test/instrumentation/decode_metric.go\" \"test/instrumentation/find_stable_metric.go\" \"test/instrumentation/error.go\" \"test/instrumentation/metric.go\" -- 1>\"${temp_file}\")\n\n  if $doValidate; then\n    echo -e \"${green}Diffing test/instrumentation/testdata/stable-metrics-list.yaml\\n${reset}\"\n    if diff -u \"$KUBE_ROOT/test/instrumentation/testdata/stable-metrics-list.yaml\" \"$temp_file\"; then\n      echo -e \"${green}\\nPASS metrics stability verification ${reset}\"\n      return 0\n    fi\n  fi\n  \n  echo \"${red}!!! Metrics Stability static analysis has failed!${reset}\" >&2\n  echo \"${red}!!! Please run ./hack/update-generated-stable-metrics.sh to update the golden list.${reset}\" >&2\n  exit 1\n}\n\nkube::update::stablemetrics() {\n  stability_check_setup\n  temp_file=$(mktemp)\n  doCheckStability=$(find_files_to_check | grep -E \".*.go\" | grep -v \".*_test.go\" | sort | xargs -L 200 go run \"test/instrumentation/main.go\" \"test/instrumentation/decode_metric.go\" \"test/instrumentation/find_stable_metric.go\" \"test/instrumentation/error.go\" \"test/instrumentation/metric.go\" -- 1>\"${temp_file}\")\n\n  if ! $doCheckStability; then\n    echo \"${red}!!! updating golden list of metrics has failed! ${reset}\" >&2\n    exit 1\n  fi\n  mv -f \"$temp_file\" \"${KUBE_ROOT}/test/instrumentation/testdata/stable-metrics-list.yaml\"\n  echo \"${green}Updated golden list of stable metrics.${reset}\"\n}\n\n", "num_lines": 89}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This file is not executable, and therefore it will not be run.\nexit 1\n", "num_lines": 19}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ -n \"${EXEC_PLUGIN_OUTPUT_FILE-\"\"}\" ]]; then\n  cat \"$EXEC_PLUGIN_OUTPUT_FILE\"\n  exit\nfi\n\necho \"${EXEC_PLUGIN_OUTPUT-\"\"}\"\n\nexit \"${EXEC_PLUGIN_EXEC_CODE-0}\"\n", "num_lines": 29}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTEST_ARGS=\"\"\nRUN_PATTERN=\".*\"\nPROFILE_OPTS=\"\"\n\nfunction usage() {\n  echo \"usage: $0 <options>\"\n  echo \" -h display this help message\"\n  echo \" -d enable debug logs in tests\"\n  echo \" -r <pattern> regex pattern to match for tests\"\n  echo \" -o <filename> file to write JSON formatted results to\"\n  echo \" -p <id> enable cpu and memory profiles, output written to mem-<id>.out and cpu-<id>.out\"\n  echo \" -c enable custom test configuration\"\n  echo \" -a <name> allocator name, one of RangeAllocator, CloudAllocator, IPAMFromCluster, IPAMFromCloud\"\n  echo \" -k <num> api server qps for allocator\"\n  echo \" -n <num> number of nodes to simulate\"\n  echo \" -m <num> api server qps for node creation\"\n  echo \" -l <num> gce cloud endpoint qps\"\n  exit 1\n}\n\nwhile getopts \":hdr:o:p:ca:k:n:m:l:\" opt; do\n  case ${opt} in\n    d) TEST_ARGS=\"${TEST_ARGS} -v=6\"\n      ;;\n    r) RUN_PATTERN=\"${OPTARG}\"\n      ;;\n    o) TEST_ARGS=\"${TEST_ARGS} -log ${OPTARG}\"\n      ;;\n    p) PROFILE_OPTS=\"-memprofile mem-${OPTARG}.out -cpuprofile cpu-${OPTARG}.out\"\n      ;;\n    c) TEST_ARGS=\"${TEST_ARGS} -custom\"\n      ;;\n    a) TEST_ARGS=\"${TEST_ARGS} -allocator ${OPTARG}\"\n      ;;\n    k) TEST_ARGS=\"${TEST_ARGS} -kube-qps ${OPTARG}\"\n      ;;\n    n) TEST_ARGS=\"${TEST_ARGS} -num-nodes ${OPTARG}\"\n      ;;\n    m) TEST_ARGS=\"${TEST_ARGS} -create-qps ${OPTARG}\"\n      ;;\n    l) TEST_ARGS=\"${TEST_ARGS} -cloud-qps ${OPTARG}\"\n      ;;\n    h) usage\n      ;;\n    \\?) usage\n      ;;\n  esac\ndone\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../../\nsource \"${KUBE_ROOT}/hack/lib/init.sh\"\n\nkube::golang::setup_env\n\nDIR_BASENAME=$(dirname \"${BASH_SOURCE[0]}\")\npushd \"${DIR_BASENAME}\"\n\ncleanup() {\n  popd 2> /dev/null\n  kube::etcd::cleanup\n  kube::log::status \"performance test cleanup complete\"\n}\n\ntrap cleanup EXIT\n\nkube::etcd::start\n\n# Running IPAM tests. It might take a long time.\nkube::log::status \"performance test (IPAM) start\"\ngo test \"${PROFILE_OPTS}\" -test.run=\"${RUN_PATTERN}\" -test.timeout=60m -test.short=false -v -args \"${TEST_ARGS}\"\nkube::log::status \"... IPAM tests finished.\"\n", "num_lines": 92}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nCLOUD_PROVIDER=\"${CLOUD_PROVIDER:-gce}\"\nCONTAINER_REGISTRY=\"${CONTAINER_REGISTRY:-gcr.io}\"\nPROJECT=\"${PROJECT:-}\"\nKUBEMARK_IMAGE_REGISTRY=\"${KUBEMARK_IMAGE_REGISTRY:-}\"\nKUBEMARK_IMAGE_MAKE_TARGET=\"${KUBEMARK_IMAGE_MAKE_TARGET:-gcloudpush}\"\n", "num_lines": 22}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script assumes that kubectl binary is present in PATH.\nkubectl config set-cluster hollow-cluster --server=http://localhost:8080 --insecure-skip-tls-verify=true\nkubectl config set-credentials \"$(whoami)\"\nkubectl config set-context hollow-context --cluster=hollow-cluster --user=\"$(whoami)\"\n", "num_lines": 21}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nexport KUBERNETES_PROVIDER=\"kubemark\"\nexport KUBE_CONFIG_FILE=\"config-default.sh\"\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\n# We need an absolute path to KUBE_ROOT\nABSOLUTE_ROOT=$(readlink -f \"${KUBE_ROOT}\")\n\nsource \"${KUBE_ROOT}/cluster/kubemark/util.sh\"\n\necho \"Kubemark master name: ${MASTER_NAME}\"\necho \"Kubemark master ip: ${KUBE_MASTER_IP}\"\n\nexport KUBE_MASTER_URL=\"https://${KUBE_MASTER_IP}\"\nexport KUBECONFIG=\"${ABSOLUTE_ROOT}/test/kubemark/resources/kubeconfig.kubemark\"\nexport E2E_MIN_STARTUP_PODS=0\n\nif [[ -z \"$*\" ]]; then\n\tARGS=('--ginkgo.focus=[Feature:Performance]')\nelse\n\tARGS=(\"$@\")\nfi\n\nif [[ \"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER}\" == \"true\" ]]; then\n  ARGS+=(\"--kubemark-external-kubeconfig=${DEFAULT_KUBECONFIG}\")\nfi\n\n# Running locally.\nfor ((i=0; i < ${#ARGS[@]}; i++)); do\n  ARGS[$i]=\"$(echo \"${ARGS[$i]}\" | sed -e 's/\\[/\\\\\\[/g' -e 's/\\]/\\\\\\]/g' )\"\ndone\n\"${KUBE_ROOT}/hack/ginkgo-e2e.sh\" \"--e2e-verify-service-account=false\" \"--dump-logs-on-failure=false\" \"${ARGS[@]}\"\n", "num_lines": 49}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script that creates a Kubemark cluster for any given cloud provider.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTMP_ROOT=\"$(dirname \"${BASH_SOURCE[@]}\")/../..\"\nKUBE_ROOT=$(readlink -e \"${TMP_ROOT}\" 2> /dev/null || perl -MCwd -e 'print Cwd::abs_path shift' \"${TMP_ROOT}\")\n\nsource \"${KUBE_ROOT}/test/kubemark/skeleton/util.sh\"\nsource \"${KUBE_ROOT}/test/kubemark/cloud-provider-config.sh\"\nsource \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kubemark/${CLOUD_PROVIDER}/config-default.sh\"\n\nif [[ -f \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/startup.sh\" ]] ; then\n  source \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/startup.sh\"\nfi\n\nsource \"${KUBE_ROOT}/cluster/kubemark/util.sh\"\n\nKUBECTL=\"${KUBE_ROOT}/cluster/kubectl.sh\"\nKUBEMARK_DIRECTORY=\"${KUBE_ROOT}/test/kubemark\"\nRESOURCE_DIRECTORY=\"${KUBEMARK_DIRECTORY}/resources\"\nLOCAL_KUBECONFIG=\"${RESOURCE_DIRECTORY}/kubeconfig.kubemark\"\nINTERNAL_KUBECONFIG=\"${RESOURCE_DIRECTORY}/kubeconfig-internal.kubemark\"\n\n# Generate a random 6-digit alphanumeric tag for the kubemark image.\n# Used to uniquify image builds across different invocations of this script.\nKUBEMARK_IMAGE_TAG=$(head /dev/urandom | tr -dc 'a-z0-9' | fold -w 6 | head -n 1)\n\n# Create a docker image for hollow-node and upload it to the appropriate docker registry.\nfunction create-and-upload-hollow-node-image {\n  authenticate-docker\n  KUBEMARK_IMAGE_REGISTRY=\"${KUBEMARK_IMAGE_REGISTRY:-${CONTAINER_REGISTRY}/${PROJECT}}\"\n  # Build+push the image through makefile.\n  build_cmd=(\"make\" \"${KUBEMARK_IMAGE_MAKE_TARGET}\")\n  MAKE_DIR=\"${KUBE_ROOT}/cluster/images/kubemark\"\n  KUBEMARK_BIN=\"$(kube::util::find-binary-for-platform kubemark linux/amd64)\"\n  if [[ -z \"${KUBEMARK_BIN}\" ]]; then\n    echo 'Cannot find cmd/kubemark binary'\n    exit 1\n  fi\n  echo \"Copying kubemark binary to ${MAKE_DIR}\"\n  cp \"${KUBEMARK_BIN}\" \"${MAKE_DIR}\"\n  CURR_DIR=$(pwd)\n  cd \"${MAKE_DIR}\"\n  REGISTRY=${KUBEMARK_IMAGE_REGISTRY} IMAGE_TAG=${KUBEMARK_IMAGE_TAG} run-cmd-with-retries \"${build_cmd[@]}\"\n  rm kubemark\n  cd \"$CURR_DIR\"\n  echo \"Created and uploaded the kubemark hollow-node image to docker registry.\"\n  # Cleanup the kubemark image after the script exits.\n  if [[ \"${CLEANUP_KUBEMARK_IMAGE:-}\" == \"true\" ]]; then\n    trap delete-kubemark-image EXIT\n  fi\n}\n\nfunction delete-kubemark-image {\n  delete-image \"${KUBEMARK_IMAGE_REGISTRY}/kubemark:${KUBEMARK_IMAGE_TAG}\"\n}\n\n# Generate secret and configMap for the hollow-node pods to work, prepare\n# manifests of the hollow-node and heapster replication controllers from\n# templates, and finally create these resources through kubectl.\nfunction create-kube-hollow-node-resources {\n  # Create kubemark namespace.\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/kubemark-ns.json\"\n\n  # Create configmap for configuring hollow- kubelet, proxy and npd.\n  \"${KUBECTL}\" create configmap \"node-configmap\" --namespace=\"kubemark\" \\\n    --from-file=kernel.monitor=\"${RESOURCE_DIRECTORY}/kernel-monitor.json\"\n\n  # Create secret for passing kubeconfigs to kubelet, kubeproxy and npd.\n  # It's bad that all component shares the same kubeconfig.\n  # TODO(https://github.com/kubernetes/kubernetes/issues/79883): Migrate all components to separate credentials.\n  \"${KUBECTL}\" create secret generic \"kubeconfig\" --type=Opaque --namespace=\"kubemark\" \\\n    --from-file=kubelet.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\" \\\n    --from-file=kubeproxy.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\" \\\n    --from-file=npd.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\" \\\n    --from-file=heapster.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\" \\\n    --from-file=cluster_autoscaler.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\" \\\n    --from-file=dns.kubeconfig=\"${HOLLOWNODE_KUBECONFIG}\"\n\n  # Create addon pods.\n  # Heapster.\n  mkdir -p \"${RESOURCE_DIRECTORY}/addons\"\n  sed \"s@{{MASTER_IP}}@${MASTER_IP}@g\" \"${RESOURCE_DIRECTORY}/heapster_template.json\" > \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  metrics_mem_per_node=4\n  metrics_mem=$((200 + metrics_mem_per_node*NUM_NODES))\n  sed -i'' -e \"s@{{METRICS_MEM}}@${metrics_mem}@g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  metrics_cpu_per_node_numerator=${NUM_NODES}\n  metrics_cpu_per_node_denominator=2\n  metrics_cpu=$((80 + metrics_cpu_per_node_numerator / metrics_cpu_per_node_denominator))\n  sed -i'' -e \"s@{{METRICS_CPU}}@${metrics_cpu}@g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  eventer_mem_per_node=500\n  eventer_mem=$((200 * 1024 + eventer_mem_per_node*NUM_NODES))\n  sed -i'' -e \"s@{{EVENTER_MEM}}@${eventer_mem}@g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n\n  # Cluster Autoscaler.\n  if [[ \"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER:-}\" == \"true\" ]]; then\n    echo \"Setting up Cluster Autoscaler\"\n    KUBEMARK_AUTOSCALER_MIG_NAME=\"${KUBEMARK_AUTOSCALER_MIG_NAME:-${NODE_INSTANCE_PREFIX}-group}\"\n    KUBEMARK_AUTOSCALER_MIN_NODES=\"${KUBEMARK_AUTOSCALER_MIN_NODES:-0}\"\n    KUBEMARK_AUTOSCALER_MAX_NODES=\"${KUBEMARK_AUTOSCALER_MAX_NODES:-10}\"\n    NUM_NODES=${KUBEMARK_AUTOSCALER_MAX_NODES}\n    echo \"Setting maximum cluster size to ${NUM_NODES}.\"\n    KUBEMARK_MIG_CONFIG=\"autoscaling.k8s.io/nodegroup: ${KUBEMARK_AUTOSCALER_MIG_NAME}\"\n    sed \"s/{{master_ip}}/${MASTER_IP}/g\" \"${RESOURCE_DIRECTORY}/cluster-autoscaler_template.json\" > \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s@{{kubemark_autoscaler_mig_name}}@${KUBEMARK_AUTOSCALER_MIG_NAME}@g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s@{{kubemark_autoscaler_min_nodes}}@${KUBEMARK_AUTOSCALER_MIN_NODES}@g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s@{{kubemark_autoscaler_max_nodes}}@${KUBEMARK_AUTOSCALER_MAX_NODES}@g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n  fi\n\n  # Kube DNS.\n  if [[ \"${ENABLE_KUBEMARK_KUBE_DNS:-}\" == \"true\" ]]; then\n    echo \"Setting up kube-dns\"\n    sed \"s@{{dns_domain}}@${KUBE_DNS_DOMAIN}@g\" \"${RESOURCE_DIRECTORY}/kube_dns_template.yaml\" > \"${RESOURCE_DIRECTORY}/addons/kube_dns.yaml\"\n  fi\n\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/addons\" --namespace=\"kubemark\"\n\n  # Create the replication controller for hollow-nodes.\n  # We allow to override the NUM_REPLICAS when running Cluster Autoscaler.\n  NUM_REPLICAS=${NUM_REPLICAS:-${NUM_NODES}}\n  sed \"s@{{numreplicas}}@${NUM_REPLICAS}@g\" \"${RESOURCE_DIRECTORY}/hollow-node_template.yaml\" > \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  proxy_cpu=20\n  if [ \"${NUM_NODES}\" -gt 1000 ]; then\n    proxy_cpu=50\n  fi\n  proxy_cpu=${KUBEMARK_HOLLOW_PROXY_MILLICPU:-$proxy_cpu}\n  proxy_mem_per_node=${KUBEMARK_HOLLOW_PROXY_MEM_PER_NODE_KB:-50}\n  proxy_mem=$((100 * 1024 + proxy_mem_per_node*NUM_NODES))\n  hollow_node_labels=${HOLLOW_NODE_LABELS:-$(calculate-node-labels)}\n  hollow_kubelet_params=$(eval \"for param in ${HOLLOW_KUBELET_TEST_ARGS:-}; do echo -n \\\\\\\"\\$param\\\\\\\",; done\")\n  hollow_kubelet_params=${hollow_kubelet_params%?}\n  hollow_proxy_params=$(eval \"for param in ${HOLLOW_PROXY_TEST_ARGS:-}; do echo -n \\\\\\\"\\$param\\\\\\\",; done\")\n  hollow_proxy_params=${hollow_proxy_params%?}\n\n  sed -i'' -e \"s@{{hollow_kubelet_millicpu}}@${KUBEMARK_HOLLOW_KUBELET_MILLICPU:-40}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_kubelet_mem_Ki}}@${KUBEMARK_HOLLOW_KUBELET_MEM_KB:-$((100*1024))}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_proxy_millicpu}}@${proxy_cpu}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_proxy_mem_Ki}}@${proxy_mem}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{npd_millicpu}}@${KUBEMARK_NPD_MILLICPU:-20}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{npd_mem_Ki}}@${KUBEMARK_NPD_MEM_KB:-$((20*1024))}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{kubemark_image_registry}}@${KUBEMARK_IMAGE_REGISTRY}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{kubemark_image_tag}}@${KUBEMARK_IMAGE_TAG}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{master_ip}}@${MASTER_IP}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_node_labels}}@${hollow_node_labels}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_kubelet_params}}@${hollow_kubelet_params}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{hollow_proxy_params}}@${hollow_proxy_params}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s@{{kubemark_mig_config}}@${KUBEMARK_MIG_CONFIG:-}@g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/hollow-node.yaml\" --namespace=\"kubemark\"\n\n  echo \"Created secrets, configMaps, replication-controllers required for hollow-nodes.\"\n}\n\n# Wait until all hollow-nodes are running or there is a timeout.\nfunction wait-for-hollow-nodes-to-run-or-timeout {\n  echo -n \"Waiting for all hollow-nodes to become Running\"\n  start=$(date +%s)\n  nodes=$(\"${KUBECTL}\" --kubeconfig=\"${LOCAL_KUBECONFIG}\" get node 2> /dev/null) || true\n  ready=$(($(echo \"${nodes}\" | grep -vc \"NotReady\") - 1))\n\n  until [[ \"${ready}\" -ge \"${NUM_REPLICAS}\" ]]; do\n    echo -n \".\"\n    sleep 1\n    now=$(date +%s)\n    # Fail it if it already took more than 30 minutes.\n    if [ $((now - start)) -gt 1800 ]; then\n      echo \"\"\n      # shellcheck disable=SC2154 # Color defined in sourced script\n      echo -e \"${color_red} Timeout waiting for all hollow-nodes to become Running. ${color_norm}\"\n      # Try listing nodes again - if it fails it means that API server is not responding\n      if \"${KUBECTL}\" --kubeconfig=\"${LOCAL_KUBECONFIG}\" get node &> /dev/null; then\n        echo \"Found only ${ready} ready hollow-nodes while waiting for ${NUM_NODES}.\"\n      else\n        echo \"Got error while trying to list hollow-nodes. Probably API server is down.\"\n      fi\n      pods=$(\"${KUBECTL}\" get pods -l name=hollow-node --namespace=kubemark) || true\n      running=$(($(echo \"${pods}\" | grep -c \"Running\")))\n      echo \"${running} hollow-nodes are reported as 'Running'\"\n      not_running=$(($(echo \"${pods}\" | grep -vc \"Running\") - 1))\n      echo \"${not_running} hollow-nodes are reported as NOT 'Running'\"\n      echo \"${pods}\" | grep -v Running\n      exit 1\n    fi\n    nodes=$(\"${KUBECTL}\" --kubeconfig=\"${LOCAL_KUBECONFIG}\" get node 2> /dev/null) || true\n    ready=$(($(echo \"${nodes}\" | grep -vc \"NotReady\") - 1))\n  done\n  # shellcheck disable=SC2154 # Color defined in sourced script\n  echo -e \"${color_green} Done!${color_norm}\"\n}\n\n############################### Main Function ########################################\n\n# Setup for hollow-nodes.\nfunction start-hollow-nodes {\n  # shellcheck disable=SC2154 # Color defined in sourced script\n  echo -e \"${color_yellow}STARTING SETUP FOR HOLLOW-NODES${color_norm}\"\n  create-and-upload-hollow-node-image\n  create-kube-hollow-node-resources\n  wait-for-hollow-nodes-to-run-or-timeout\n}\n\n# Annotates the node objects in the kubemark cluster to make their size\n# similar to regular nodes.\n# TODO(#90833): Replace this with image preloading from ClusterLoader to better\n# reflect the reality in kubemark tests.\nfunction resize-node-objects {\n  if [[ -z \"$KUBEMARK_NODE_OBJECT_SIZE_BYTES\" ]]; then\n    return 0\n  fi\n\n  annotation_size_bytes=\"${KUBEMARK_NODE_OBJECT_SIZE_BYTES}\"\n  echo \"Annotating node objects with ${annotation_size_bytes} byte label\"\n  label=$( (< /dev/urandom tr -dc 'a-zA-Z0-9' | fold -w \"$annotation_size_bytes\"; true) | head -n 1)\n  \"${KUBECTL}\" --kubeconfig=\"${LOCAL_KUBECONFIG}\" get nodes -o name \\\n    | xargs -n10 -P100 -r -I% \"${KUBECTL}\" --kubeconfig=\"${LOCAL_KUBECONFIG}\" annotate --overwrite % label=\"$label\" > /dev/null\n  echo \"Annotating node objects completed\"\n}\n\n\ndetect-project &> /dev/null\ncreate-kubemark-master\n\nif [ -f \"${INTERNAL_KUBECONFIG}\" ]; then\n    HOLLOWNODE_KUBECONFIG=\"${INTERNAL_KUBECONFIG}\"\nelse\n    HOLLOWNODE_KUBECONFIG=\"${LOCAL_KUBECONFIG}\"\nfi\n\nMASTER_IP=$(grep server \"${HOLLOWNODE_KUBECONFIG}\" | awk -F \"/\" '{print $3}')\n\nstart-hollow-nodes\nresize-node-objects\n\necho \"\"\necho \"Master IP: ${MASTER_IP}\"\necho \"Kubeconfig for kubemark master is written in ${LOCAL_KUBECONFIG}\"\n", "num_lines": 255}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script that destroys Kubemark cluster and deletes all master resources.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../..\n\nsource \"${KUBE_ROOT}/test/kubemark/skeleton/util.sh\"\nsource \"${KUBE_ROOT}/test/kubemark/cloud-provider-config.sh\"\nsource \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/util.sh\"\nsource \"${KUBE_ROOT}/cluster/kubemark/${CLOUD_PROVIDER}/config-default.sh\"\n\nif [[ -f \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/shutdown.sh\" ]] ; then\n  source \"${KUBE_ROOT}/test/kubemark/${CLOUD_PROVIDER}/shutdown.sh\"\nfi\n\nsource \"${KUBE_ROOT}/cluster/kubemark/util.sh\"\n\nKUBECTL=\"${KUBE_ROOT}/cluster/kubectl.sh\"\nKUBEMARK_DIRECTORY=\"${KUBE_ROOT}/test/kubemark\"\nRESOURCE_DIRECTORY=\"${KUBEMARK_DIRECTORY}/resources\"\n\ndetect-project &> /dev/null\n\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/addons\" --namespace=\"kubemark\" &> /dev/null || true\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/hollow-node.yaml\" --namespace=\"kubemark\" &> /dev/null || true\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/kubemark-ns.json\" &> /dev/null || true\n\nrm -rf \"${RESOURCE_DIRECTORY}/addons\" \\\n\t\"${RESOURCE_DIRECTORY}/kubeconfig.kubemark\" \\\n\t\"${RESOURCE_DIRECTORY}/hollow-node.yaml\"  &> /dev/null || true\n\ndelete-kubemark-master\n", "num_lines": 47}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Running cmd $RETRIES times in case of failures.\nfunction run-cmd-with-retries {\n  RETRIES=\"${RETRIES:-3}\"\n  for attempt in $(seq 1 \"${RETRIES}\"); do\n    local ret_val=0\n    exec 5>&1 # Duplicate &1 to &5 for use below.\n    # We don't use 'local' to declare result as then ret_val always gets value 0.\n    # We use tee to output to &5 (redirected to stdout) while also storing it in the variable.\n    result=$(\"$@\" 2>&1 | tee >(cat - >&5)) || ret_val=\"$?\"\n    if [[ \"${ret_val:-0}\" -ne \"0\" ]]; then\n      if [[ $(echo \"${result}\" | grep -c \"already exists\") -gt 0 ]]; then\n        if [[ \"${attempt}\" == 1 ]]; then\n          # shellcheck disable=SC2154 # Color defined in sourced script\n          echo -e \"${color_red}Failed to $1 $2 ${3:-} as the resource hasn't been deleted from a previous run.${color_norm}\" >& 2\n          exit 1\n        fi\n        # shellcheck disable=SC2154 # Color defined in sourced script\n        echo -e \"${color_yellow}Succeeded to $1 $2 ${3:-} in the previous attempt, but status response wasn't received.${color_norm}\"\n        return 0\n      fi\n      # shellcheck disable=SC2154 # Color defined in sourced script\n      echo -e \"${color_yellow}Attempt $attempt failed to $1 $2 ${3:-}. Retrying.${color_norm}\" >& 2\n      sleep $((attempt * 5))\n    else\n      # shellcheck disable=SC2154 # Color defined in sourced script\n      echo -e \"${color_green}Succeeded to $1 $2 ${3:-}.${color_norm}\"\n      return 0\n    fi\n  done\n  # shellcheck disable=SC2154 # Color defined in sourced script\n  echo -e \"${color_red}Failed to $1 $2 ${3:-}.${color_norm}\" >& 2\n  exit 1\n}\n", "num_lines": 50}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../..\n\nsource \"${KUBE_ROOT}/test/kubemark/common/util.sh\"\n\n# Wrapper for gcloud compute, running it $RETRIES times in case of failures.\n# Args:\n# $@: all stuff that goes after 'gcloud compute'\nfunction run-gcloud-compute-with-retries {\n  run-cmd-with-retries gcloud compute \"$@\"\n}\n\nfunction authenticate-docker {\n  echo \"Configuring registry authentication\"\n  mkdir -p \"${HOME}/.docker\"\n  gcloud beta auth configure-docker -q\n}\n\nfunction create-kubemark-master {\n  # We intentionally override env vars in subshell to preserve original values.\n  # shellcheck disable=SC2030,SC2031\n  (\n    # All calls to e2e-grow-cluster must share temp dir with initial e2e-up.sh.\n    kube::util::ensure-temp-dir\n    export KUBE_TEMP=\"${KUBE_TEMP}\"\n\n    export KUBECONFIG=\"${RESOURCE_DIRECTORY}/kubeconfig.kubemark\"\n    export KUBECONFIG_INTERNAL=\"${RESOURCE_DIRECTORY}/kubeconfig-internal.kubemark\"\n    export CLUSTER_NAME=\"${CLUSTER_NAME}-kubemark\"\n    export KUBE_CREATE_NODES=false\n    export KUBE_GCE_INSTANCE_PREFIX=\"${KUBE_GCE_INSTANCE_PREFIX}-kubemark\"\n\n    # Quite tricky cidr setup: we set KUBE_GCE_ENABLE_IP_ALIASES=true to avoid creating\n    # cloud routes and RangeAllocator to assign cidrs by kube-controller-manager.\n    export KUBE_GCE_ENABLE_IP_ALIASES=true\n    export KUBE_GCE_NODE_IPAM_MODE=RangeAllocator\n\n    # Disable all addons. They are running outside of the kubemark cluster.\n    export KUBE_ENABLE_CLUSTER_AUTOSCALER=false\n    export KUBE_ENABLE_CLUSTER_DNS=false\n    export KUBE_ENABLE_NODE_LOGGING=false\n    export KUBE_ENABLE_METRICS_SERVER=false\n    export KUBE_ENABLE_L7_LOADBALANCING=\"none\"\n\n    # Unset env variables set by kubetest for 'root cluster'. We need recompute them\n    # for kubemark master.\n    # TODO(mborsz): Figure out some better way to filter out such env variables than\n    # listing them here.\n    unset MASTER_SIZE MASTER_DISK_SIZE MASTER_ROOT_DISK_SIZE\n\n    # Set kubemark-specific overrides:\n    # for each defined env KUBEMARK_X=Y call export X=Y.\n    for var in ${!KUBEMARK_*}; do\n      dst_var=${var#KUBEMARK_}\n      val=${!var}\n      echo \"Setting ${dst_var} to '${val}'\"\n      export \"${dst_var}\"=\"${val}\"\n    done\n\n    \"${KUBE_ROOT}/hack/e2e-internal/e2e-up.sh\"\n\n    if [[ \"${KUBEMARK_HA_MASTER:-}\" == \"true\" && -n \"${KUBEMARK_MASTER_ADDITIONAL_ZONES:-}\" ]]; then\n        for KUBE_GCE_ZONE in ${KUBEMARK_MASTER_ADDITIONAL_ZONES}; do\n          KUBE_GCE_ZONE=\"${KUBE_GCE_ZONE}\" KUBE_REPLICATE_EXISTING_MASTER=true \\\n            \"${KUBE_ROOT}/hack/e2e-internal/e2e-grow-cluster.sh\"\n        done\n    fi\n\n    # The e2e-up.sh script is not sourced, so we don't have access to variables that\n    # it sets. Instead, we read data which was written to the KUBE_TEMP directory.\n    # The cluster-location is either ZONE (say us-east1-a) or REGION (say us-east1).\n    # To get REGION from location, only first two parts are matched.\n    REGION=$(grep -o \"^[a-z]*-[a-z0-9]*\" \"${KUBE_TEMP}\"/cluster-location.txt)\n    MASTER_NAME=\"${KUBE_GCE_INSTANCE_PREFIX}\"-master\n\n    if [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      MASTER_INTERNAL_IP=$(gcloud compute addresses describe \"${MASTER_NAME}-internal-ip\" \\\n          --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)')\n    fi\n    MASTER_IP=$(gcloud compute addresses describe \"${MASTER_NAME}-ip\" \\\n        --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)')\n\n    # If cluster uses private master IP, two kubeconfigs are created:\n    # - kubeconfig with public IP, which will be used to connect to the cluster\n    #     from outside of the cluster network\n    # - kubeconfig with private IP (called internal kubeconfig), which will be\n    #      used to create hollow nodes.\n    #\n    # Note that hollow nodes might use either of these kubeconfigs, but\n    # using internal one is better from performance and cost perspective, since\n    # traffic does not need to go through Cloud NAT.\n    if [[ -n \"${MASTER_INTERNAL_IP:-}\" ]]; then\n      echo \"Writing internal kubeconfig to '${KUBECONFIG_INTERNAL}'\"\n      ip_regexp=${MASTER_IP//./\\\\.} # escape \".\", so that sed won't treat it as \"any char\"\n      sed \"s/${ip_regexp}/${MASTER_INTERNAL_IP}/g\" \"${KUBECONFIG}\" > \"${KUBECONFIG_INTERNAL}\"\n    fi\n    )\n}\n\nfunction delete-kubemark-master {\n  # We intentionally override env vars in subshell to preserve original values.\n  # shellcheck disable=SC2030,SC2031\n  (\n    export CLUSTER_NAME=\"${CLUSTER_NAME}-kubemark\"\n    export KUBE_GCE_INSTANCE_PREFIX=\"${KUBE_GCE_INSTANCE_PREFIX}-kubemark\"\n\n    export KUBE_DELETE_NETWORK=false\n\n    if [[ \"${KUBEMARK_HA_MASTER:-}\" == \"true\" && -n \"${KUBEMARK_MASTER_ADDITIONAL_ZONES:-}\" ]]; then\n      for KUBE_GCE_ZONE in ${KUBEMARK_MASTER_ADDITIONAL_ZONES}; do\n        KUBE_GCE_ZONE=\"${KUBE_GCE_ZONE}\" KUBE_REPLICATE_EXISTING_MASTER=true \\\n          \"${KUBE_ROOT}/hack/e2e-internal/e2e-shrink-cluster.sh\"\n      done\n    fi\n\n    \"${KUBE_ROOT}/hack/e2e-internal/e2e-down.sh\"\n  )\n}\n\nfunction calculate-node-labels {\n  echo \"cloud.google.com/metadata-proxy-ready=true\"\n}\n", "num_lines": 138}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script that destroys the clusters used, namespace, and deployment.\n\nKUBECTL=kubectl\nKUBEMARK_DIRECTORY=\"${KUBE_ROOT}/test/kubemark\"\nRESOURCE_DIRECTORY=\"${KUBEMARK_DIRECTORY}/resources\"\n\n# Login to cloud services\ncomplete-login\n\n# Remove resources created for kubemark\n# shellcheck disable=SC2154 # Color defined in sourced script\necho -e \"${color_yellow}REMOVING RESOURCES${color_norm}\"\nspawn-config\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/addons\" &> /dev/null || true\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/hollow-node.yaml\" &> /dev/null || true\n\"${KUBECTL}\" delete -f \"${RESOURCE_DIRECTORY}/kubemark-ns.json\" &> /dev/null || true\nrm -rf \"${RESOURCE_DIRECTORY}/addons\"\n\t\"${RESOURCE_DIRECTORY}/hollow-node.yaml\" &> /dev/null || true\n\n# Remove clusters, namespaces, and deployments\ndelete-clusters\nif [[ -f \"${RESOURCE_DIRECTORY}/iks-namespacelist.sh\" ]] ; then\n  bash \"${RESOURCE_DIRECTORY}/iks-namespacelist.sh\"\n  rm -f \"${RESOURCE_DIRECTORY}/iks-namespacelist.sh\"\nfi\n# shellcheck disable=SC2154 # Color defined in sourced script\necho -e \"${color_blue}EXECUTION COMPLETE${color_norm}\"\nexit 0\n", "num_lines": 45}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script that creates a Kubemark cluster for IBM cloud.\n\nKUBECTL=\"${KUBE_ROOT}/cluster/kubectl.sh\"\nKUBEMARK_DIRECTORY=\"${KUBE_ROOT}/test/kubemark\"\nRESOURCE_DIRECTORY=\"${KUBEMARK_DIRECTORY}/resources\"\n\n# Generate secret and configMap for the hollow-node pods to work, prepare\n# manifests of the hollow-node and heapster replication controllers from\n# templates, and finally create these resources through kubectl.\nfunction create-kube-hollow-node-resources {\n  # Create kubeconfig for Kubelet.\n  KUBELET_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: kubelet\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    certificate-authority-data: \"${CA_CERT_BASE64}\"\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: kubelet\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n)\"\n\n  # Create kubeconfig for Kubeproxy.\n  KUBEPROXY_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: kube-proxy\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: kube-proxy\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n  )\"\n\n  # Create kubeconfig for Heapster.\n  HEAPSTER_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: heapster\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: heapster\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n)\"\n\n  # Create kubeconfig for Cluster Autoscaler.\n  CLUSTER_AUTOSCALER_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: cluster-autoscaler\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: cluster-autoscaler\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n)\"\n\n  # Create kubeconfig for NodeProblemDetector.\n  NPD_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: node-problem-detector\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: node-problem-detector\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n)\"\n\n  # Create kubeconfig for Kube DNS.\n  KUBE_DNS_KUBECONFIG_CONTENTS=\"$(cat <<EOF\napiVersion: v1\nkind: Config\nusers:\n- name: kube-dns\n  user:\n    client-certificate-data: \"${KUBELET_CERT_BASE64}\"\n    client-key-data: \"${KUBELET_KEY_BASE64}\"\nclusters:\n- name: kubemark\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://${MASTER_IP}\ncontexts:\n- context:\n    cluster: kubemark\n    user: kube-dns\n  name: kubemark-context\ncurrent-context: kubemark-context\nEOF\n)\"\n\n  # Create kubemark namespace.\n  spawn-config\n  if kubectl get ns | grep -Fq \"kubemark\"; then\n  \t kubectl delete ns kubemark\n  \t while kubectl get ns | grep -Fq \"kubemark\"\n  \t do\n  \t \tsleep 10\n  \t done\n  fi\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/kubemark-ns.json\"\n  # Create configmap for configuring hollow- kubelet, proxy and npd.\n  \"${KUBECTL}\" create configmap \"node-configmap\" --namespace=\"kubemark\" \\\n    --from-file=kernel.monitor=\"${RESOURCE_DIRECTORY}/kernel-monitor.json\"\n\n  # Create secret for passing kubeconfigs to kubelet, kubeproxy and npd.\n  \"${KUBECTL}\" create secret generic \"kubeconfig\" --type=Opaque --namespace=\"kubemark\" \\\n    --from-literal=kubelet.kubeconfig=\"${KUBELET_KUBECONFIG_CONTENTS}\" \\\n    --from-literal=kubeproxy.kubeconfig=\"${KUBEPROXY_KUBECONFIG_CONTENTS}\" \\\n    --from-literal=heapster.kubeconfig=\"${HEAPSTER_KUBECONFIG_CONTENTS}\" \\\n    --from-literal=cluster_autoscaler.kubeconfig=\"${CLUSTER_AUTOSCALER_KUBECONFIG_CONTENTS}\" \\\n    --from-literal=npd.kubeconfig=\"${NPD_KUBECONFIG_CONTENTS}\" \\\n    --from-literal=dns.kubeconfig=\"${KUBE_DNS_KUBECONFIG_CONTENTS}\"\n\n  # Create addon pods.\n  # Heapster.\n  mkdir -p \"${RESOURCE_DIRECTORY}/addons\"\n  sed \"s/{{MASTER_IP}}/${MASTER_IP}/g\" \"${RESOURCE_DIRECTORY}/heapster_template.json\" > \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  metrics_mem_per_node=4\n  metrics_mem=$((200 + metrics_mem_per_node*NUM_NODES))\n  sed -i'' -e \"s/{{METRICS_MEM}}/${metrics_mem}/g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  metrics_cpu_per_node_numerator=${NUM_NODES}\n  metrics_cpu_per_node_denominator=2\n  metrics_cpu=$((80 + metrics_cpu_per_node_numerator / metrics_cpu_per_node_denominator))\n  sed -i'' -e \"s/{{METRICS_CPU}}/${metrics_cpu}/g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n  eventer_mem_per_node=500\n  eventer_mem=$((200 * 1024 + eventer_mem_per_node*NUM_NODES))\n  sed -i'' -e \"s/{{EVENTER_MEM}}/${eventer_mem}/g\" \"${RESOURCE_DIRECTORY}/addons/heapster.json\"\n\n  # Cluster Autoscaler.\n  if [[ \"${ENABLE_KUBEMARK_CLUSTER_AUTOSCALER:-}\" == \"true\" ]]; then\n    echo \"Setting up Cluster Autoscaler\"\n    KUBEMARK_AUTOSCALER_MIG_NAME=\"${KUBEMARK_AUTOSCALER_MIG_NAME:-${NODE_INSTANCE_PREFIX}-group}\"\n    KUBEMARK_AUTOSCALER_MIN_NODES=\"${KUBEMARK_AUTOSCALER_MIN_NODES:-0}\"\n    KUBEMARK_AUTOSCALER_MAX_NODES=\"${KUBEMARK_AUTOSCALER_MAX_NODES:-${DESIRED_NODES}}\"\n    NUM_NODES=${KUBEMARK_AUTOSCALER_MAX_NODES}\n    echo \"Setting maximum cluster size to ${NUM_NODES}.\"\n    KUBEMARK_MIG_CONFIG=\"autoscaling.k8s.io/nodegroup: ${KUBEMARK_AUTOSCALER_MIG_NAME}\"\n    sed \"s/{{master_ip}}/${MASTER_IP}/g\" \"${RESOURCE_DIRECTORY}/cluster-autoscaler_template.json\" > \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s/{{kubemark_autoscaler_mig_name}}/${KUBEMARK_AUTOSCALER_MIG_NAME}/g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s/{{kubemark_autoscaler_min_nodes}}/${KUBEMARK_AUTOSCALER_MIN_NODES}/g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n    sed -i'' -e \"s/{{kubemark_autoscaler_max_nodes}}/${KUBEMARK_AUTOSCALER_MAX_NODES}/g\" \"${RESOURCE_DIRECTORY}/addons/cluster-autoscaler.json\"\n  fi\n\n  # Kube DNS.\n  if [[ \"${ENABLE_KUBEMARK_KUBE_DNS:-}\" == \"true\" ]]; then\n    echo \"Setting up kube-dns\"\n    sed \"s/{{dns_domain}}/${KUBE_DNS_DOMAIN}/g\" \"${RESOURCE_DIRECTORY}/kube_dns_template.yaml\" > \"${RESOURCE_DIRECTORY}/addons/kube_dns.yaml\"\n  fi\n\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/addons\" --namespace=\"kubemark\"\n  set-registry-secrets\n\n  # Create the replication controller for hollow-nodes.\n  # We allow to override the NUM_REPLICAS when running Cluster Autoscaler.\n  NUM_REPLICAS=${NUM_REPLICAS:-${KUBEMARK_NUM_NODES}}\n  sed \"s/{{numreplicas}}/${NUM_REPLICAS}/g\" \"${RESOURCE_DIRECTORY}/hollow-node_template.yaml\" > \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  proxy_cpu=20\n  if [ \"${NUM_NODES}\" -gt 1000 ]; then\n    proxy_cpu=50\n  fi\n  proxy_mem_per_node=50\n  proxy_mem=$((100 * 1024 + proxy_mem_per_node*NUM_NODES))\n  hollow_kubelet_params=$(eval \"for param in ${HOLLOW_KUBELET_TEST_ARGS:-}; do echo -n \\\\\\\"\\$param\\\\\\\",; done\")\n  hollow_kubelet_params=${hollow_kubelet_params%?}\n  hollow_proxy_params=$(eval \"for param in ${HOLLOW_PROXY_TEST_ARGS:-}; do echo -n \\\\\\\"\\$param\\\\\\\",; done\")\n  hollow_proxy_params=${hollow_proxy_params%?}\n\n  sed -i'' -e \"s/{{HOLLOW_PROXY_CPU}}/${proxy_cpu}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s/{{HOLLOW_PROXY_MEM}}/${proxy_mem}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s'{{kubemark_image_registry}}'${KUBEMARK_IMAGE_REGISTRY}${KUBE_NAMESPACE}'g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s/{{kubemark_image_tag}}/${KUBEMARK_IMAGE_TAG}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s/{{master_ip}}/${MASTER_IP}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s/{{hollow_kubelet_params}}/${hollow_kubelet_params}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s/{{hollow_proxy_params}}/${hollow_proxy_params}/g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  sed -i'' -e \"s'{{kubemark_mig_config}}'${KUBEMARK_MIG_CONFIG:-}'g\" \"${RESOURCE_DIRECTORY}/hollow-node.yaml\"\n  \"${KUBECTL}\" create -f \"${RESOURCE_DIRECTORY}/hollow-node.yaml\" --namespace=\"kubemark\"\n\n  echo \"Created secrets, configMaps, replication-controllers required for hollow-nodes.\"\n}\n\n# Wait until all hollow-nodes are running or there is a timeout.\nfunction wait-for-hollow-nodes-to-run-or-timeout {\n  echo -n \"Waiting for all hollow-nodes to become Running\"\n  start=$(date +%s)\n  # IKS uses a real cluster for hollow master, so need to exclude the real worker nodes\n  nodes=$(\"${KUBECTL}\" --kubeconfig=\"${KUBECONFIG}\" get node | grep hollow-node 2> /dev/null) || true\n  ready=$(($(echo \"${nodes}\" | grep -vc \"NotReady\") - 1))\n  until [[ \"${ready}\" -ge \"${NUM_REPLICAS}\" ]]; do\n    echo -n \".\"\n    sleep 1\n    now=$(date +%s)\n    # Fail it if it already took more than 30 minutes.\n    if [ $((now - start)) -gt 1800 ]; then\n      echo \"\"\n      # shellcheck disable=SC2154 # Color defined in sourced script\n      echo -e \"${color_red} Timeout waiting for all hollow-nodes to become Running. ${color_norm}\"\n      # Try listing nodes again - if it fails it means that API server is not responding\n      if \"${KUBECTL}\" --kubeconfig=\"${KUBECONFIG}\" get node &> /dev/null; then\n        echo \"Found only ${ready} ready hollow-nodes while waiting for ${NUM_NODES}.\"\n      else\n        echo \"Got error while trying to list hollow-nodes. Probably API server is down.\"\n      fi\n      spawn-config\n      pods=$(\"${KUBECTL}\" get pods -l name=hollow-node --namespace=kubemark) || true\n      running=$(($(echo \"${pods}\" | grep -c \"Running\")))\n      echo \"${running} hollow-nodes are reported as 'Running'\"\n      not_running=$(($(echo \"${pods}\" | grep -vc \"Running\") - 1))\n      echo \"${not_running} hollow-nodes are reported as NOT 'Running'\"\n      echo \"${pods}\" | grep -v \"Running\"\n      exit 1\n    fi\n    nodes=$(\"${KUBECTL}\" --kubeconfig=\"${KUBECONFIG}\" get node 2> /dev/null) || true\n    ready=$(($(echo \"${nodes}\" | grep -vc \"NotReady\") - 1))\n  done\n  # shellcheck disable=SC2154 # Color defined in sourced script\n  echo -e \"${color_green} Done!${color_norm}\"\n}\n\n############################### Main Function ########################################\n# In order for the cluster autoscalar to function, the template file must be changed so that the \":443\"\n# is removed. This is because the port is already given with the MASTER_IP.\n\n\n# Create clusters and populate with hollow nodes\ncomplete-login\nbuild-kubemark-image\nchoose-clusters\ngenerate-values\nset-hollow-master\necho \"Creating kube hollow node resources\"\ncreate-kube-hollow-node-resources\nmaster-config\n# shellcheck disable=SC2154 # Color defined in sourced script\necho -e \"${color_blue}EXECUTION COMPLETE${color_norm}\"\n\n# Check status of Kubemark\n# shellcheck disable=SC2154 # Color defined in sourced script\necho -e \"${color_yellow}CHECKING STATUS${color_norm}\"\nwait-for-hollow-nodes-to-run-or-timeout\n\n# Celebrate\necho \"\"\n# shellcheck disable=SC2154 # Color defined in sourced script\necho -e \"${color_blue}SUCCESS${color_norm}\"\nclean-repo\nexit 0", "num_lines": 320}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../..\n\n# Creates a new kube-spawn cluster\nfunction create-clusters {\n\t# shellcheck disable=SC2154\t# Color defined in sourced script\n\techo -e \"${color_yellow}CHECKING CLUSTERS${color_norm}\"\n\tif ibmcloud ks clusters | grep -Fq 'deleting'; then\n\t\techo -n \"Deleting old clusters\"\n\tfi\n\twhile ibmcloud ks clusters | grep -Fq 'deleting'\n\tdo\n\t\techo -n \".\"\n\t\tsleep 10\n\tdone\n\techo \"\"\n\tibmcloud ks region-set us-east >/dev/null\n\tibmcloud ks vlans wdc06 >/dev/null\n\tPRIVLAN=$(ibmcloud ks vlans wdc06 --json | jq '. | .[] | select(.type == \"private\") | .id' | sed -e \"s/\\\"//g\")\n\tPUBVLAN=$(ibmcloud ks vlans wdc06 --json | jq '. | .[] | select(.type == \"public\") | .id' | sed -e \"s/\\\"//g\")\n\tif ! ibmcloud ks clusters | grep -Fq 'kubeSpawnTester'; then\n\t\techo \"Creating spawning cluster\"\n\t\t# make number and spec of node workers configurable\n\t\t# otherwise it can't afford tests like kubemark-5000\n\t\t# TODO: dynamically adjust the number and spec\n\t\tibmcloud ks cluster-create --location \"${CLUSTER_LOCATION}\" --public-vlan \"${PUBVLAN}\" --private-vlan \"${PRIVLAN}\" --workers \"${NUM_NODES:-2}\" --machine-type \"${NODE_SIZE}\" --name kubeSpawnTester\n\tfi\n\tif ! ibmcloud ks clusters | grep -Fq 'kubeMasterTester'; then\n\t\techo \"Creating master cluster\"\n\t\t# if we can't make it a bare master (workers = 0)\n\t\t# then make workers = 1 with the smallest machine spec\n\t\tibmcloud ks cluster-create --location \"${CLUSTER_LOCATION}\" --public-vlan \"${PUBVLAN}\" --private-vlan \"${PRIVLAN}\" --workers 1 --machine-type u2c.2x4 --name kubeMasterTester\n\tfi\n\tpush-image\n\tif ! ibmcloud ks clusters | grep 'kubeSpawnTester' | grep -Fq 'normal'; then\n\t\t# shellcheck disable=SC2154 # Color defined in sourced script\n\t\techo -e \"${color_cyan}Warning: new clusters may take up to 60 minutes to be ready${color_norm}\"\n\t\techo -n \"Clusters loading\"\n\tfi\n\twhile ! ibmcloud ks clusters | grep 'kubeSpawnTester' | grep -Fq 'normal'\n\tdo\n\t\techo -n \".\"\n\t\tsleep 5\n\tdone\n\twhile ! ibmcloud ks clusters | grep 'kubeMasterTester' | grep -Fq 'normal'\n\tdo\n\t\techo -n \".\"\n\t\tsleep 5\n\tdone\n\techo -e \"${color_yellow}CLUSTER CREATION COMPLETE${color_norm}\"\n}\n\n# Builds and pushes image to registry\nfunction push-image {\n\tif [[ \"${ISBUILD}\" = \"y\" ]]; then\n\t\tif ! ibmcloud cr namespaces | grep -Fq \"${KUBE_NAMESPACE}\"; then\n\t\t\techo \"Creating registry namespace\"\n\t\t\tibmcloud cr namespace-add \"${KUBE_NAMESPACE}\"\n\t\t\techo \"ibmcloud cr namespace-rm ${KUBE_NAMESPACE}\" >> \"${RESOURCE_DIRECTORY}/iks-namespacelist.sh\"\n\t\tfi\n\t\tdocker build -t \"${KUBEMARK_INIT_TAG}\" \"${KUBEMARK_IMAGE_LOCATION}\"\n\t\tdocker tag \"${KUBEMARK_INIT_TAG}\" \"${KUBEMARK_IMAGE_REGISTRY}${KUBE_NAMESPACE}/${PROJECT}:${KUBEMARK_IMAGE_TAG}\"\n\t\tdocker push \"${KUBEMARK_IMAGE_REGISTRY}${KUBE_NAMESPACE}/${PROJECT}:${KUBEMARK_IMAGE_TAG}\"\n\t\techo \"Image pushed\"\n\telse\n\t\tKUBEMARK_IMAGE_REGISTRY=\"${KUBEMARK_IMAGE_REGISTRY:-brandondr96}\"\n\t\tKUBE_NAMESPACE=\"\"\n\tfi\n}\n\n# Allow user to use existing clusters if desired\nfunction choose-clusters {\n\techo -n -e \"Do you want to use custom clusters? [y/N]${color_cyan}>${color_norm} \"\n\tread -r USE_EXISTING\n\tif [[ \"${USE_EXISTING}\" = \"y\" ]]; then\n\t\techo -e \"${color_yellow}Enter path for desired hollow-node spawning cluster kubeconfig file:${color_norm}\"\n\t\tread -r CUSTOM_SPAWN_CONFIG\n\t\techo -e \"${color_yellow}Enter path for desired hollow-node hosting cluster kubeconfig file:${color_norm}\"\n\t\tread -r CUSTOM_MASTER_CONFIG\n\t\tpush-image\n\telif [[ \"${USE_EXISTING}\" = \"N\" ]]; then\n\t\tcreate-clusters\n\telse\n\t\t# shellcheck disable=SC2154 # Color defined in sourced script\n\t\techo -e \"${color_red}Invalid response, please try again:${color_norm}\"\n\t\tchoose-clusters\n\tfi\n}\n\n# Ensure secrets are correctly set\nfunction set-registry-secrets {\n\tspawn-config\n\tkubectl get secret bluemix-default-secret-regional -o yaml | sed 's/default/kubemark/g' | kubectl -n kubemark create -f -\n\tkubectl patch serviceaccount -n kubemark default -p '{\"imagePullSecrets\": [{\"name\": \"bluemix-kubemark-secret\"}]}'\n\tkubectl -n kubemark get serviceaccounts default -o json | jq 'del(.metadata.resourceVersion)' | jq 'setpath([\"imagePullSecrets\"];[{\"name\":\"bluemix-kubemark-secret-regional\"}])' | kubectl -n kubemark replace serviceaccount default -f -\n}\n\n# Sets the hollow-node master\n# Exported variables:\n#   MASTER_IP - IP Address of the Kubemark master\nfunction set-hollow-master {\n\techo -e \"${color_yellow}CONFIGURING MASTER${color_norm}\"\n\tmaster-config\n\tMASTER_IP=$(grep server \"$KUBECONFIG\" | awk -F \"/\" '{print $3}')\n\texport MASTER_IP\n}\n\n# Set up master cluster environment\n# Exported variables:\n#   KUBECONFIG - Overrides default kube config for the purpose of setting up the Kubemark master components.\nfunction master-config {\n\tif [[ \"${USE_EXISTING}\" = \"y\" ]]; then\n\t\texport KUBECONFIG=${CUSTOM_MASTER_CONFIG}\n\telse\n\t\teval \"$(ibmcloud ks cluster-config kubeMasterTester --admin | grep export)\"\n\tfi\n}\n\n# Set up spawn cluster environment\n# Exported variables:\n#    KUBECONFIG - Overrides default kube config for the purpose of setting up the hollow-node cluster.\nfunction spawn-config {\n\tif [[ \"${USE_EXISTING}\" = \"y\" ]]; then\n\t\texport KUBECONFIG=${CUSTOM_SPAWN_CONFIG}\n\telse\n\t\teval \"$(ibmcloud ks cluster-config kubeSpawnTester --admin | grep export)\"\n\tfi\n}\n\n# Deletes existing clusters\nfunction delete-clusters {\n\techo \"DELETING CLUSTERS\"\n\tibmcloud ks cluster-rm kubeSpawnTester\n\tibmcloud ks cluster-rm kubeMasterTester\n\twhile ! ibmcloud ks clusters | grep 'kubeSpawnTester' | grep -Fq 'deleting'\n\tdo\n\t\tsleep 5\n\tdone\n\twhile ! ibmcloud ks clusters | grep 'kubeMasterTester' | grep -Fq 'deleting'\n\tdo\n\t\tsleep 5\n\tdone\n\tkubectl delete ns kubemark\n}\n\n# Login to cloud services\nfunction complete-login {\n\techo -e \"${color_yellow}LOGGING INTO CLOUD SERVICES${color_norm}\"\n\techo -n -e \"Do you have a federated IBM cloud login? [y/N]${color_cyan}>${color_norm} \"\n\tread -r ISFED\n\tif [[ \"${ISFED}\" = \"y\" ]]; then\n\t\tibmcloud login --sso -a \"${REGISTRY_LOGIN_URL}\"\n\telif [[ \"${ISFED}\" = \"N\" ]]; then\n\t\tibmcloud login -a \"${REGISTRY_LOGIN_URL}\"\n\telse\n\t\techo -e \"${color_red}Invalid response, please try again:${color_norm}\"\n\t\tcomplete-login\n\tfi\n\tibmcloud cr login\n}\n\n# Generate values to fill the hollow-node configuration templates.\n# Exported variables:\n#   KUBECTL - The name or path to the kubernetes client binary.\nfunction generate-values {\n\techo \"Generating values\"\n\tmaster-config\n\tKUBECTL=kubectl\n\texport KUBECTL\n\tKUBEMARK_DIRECTORY=\"${KUBE_ROOT}/test/kubemark\"\n\tRESOURCE_DIRECTORY=\"${KUBEMARK_DIRECTORY}/resources\"\n\tCONFIGPATH=${KUBECONFIG%/*}\n\tKUBELET_CERT_BASE64=\"${KUBELET_CERT_BASE64:-$(base64 \"${CONFIGPATH}/admin.pem\" | tr -d '\\r\\n')}\"\n\tKUBELET_KEY_BASE64=\"${KUBELET_KEY_BASE64:-$(base64 \"${CONFIGPATH}/admin-key.pem\" | tr -d '\\r\\n')}\"\n\tCA_CERT_BASE64=\"${CA_CERT_BASE64:-$( base64 \"$(find \"${CONFIGPATH}\" -name \"*ca*\" | head -n 1)\" | tr -d '\\r\\n')}\"\n\n}\n\n# Build image for kubemark\nfunction build-kubemark-image {\n\techo -n -e \"Do you want to build the kubemark image? [y/N]${color_cyan}>${color_norm} \"\n\tread -r ISBUILD\n\tif [[ \"${ISBUILD}\" = \"y\" ]]; then\n\t\techo -e \"${color_yellow}BUILDING IMAGE${color_norm}\"\n\t\t\"${KUBE_ROOT}/build/run.sh\" make kubemark\n\t\tcp \"${KUBE_ROOT}/_output/dockerized/bin/linux/amd64/kubemark\" \"${KUBEMARK_IMAGE_LOCATION}\"\n\telif [[ \"${ISBUILD}\" = \"N\" ]]; then\n\t\techo -n \"\"\n\telse\n\t\techo -e \"${color_red}Invalid response, please try again:${color_norm}\"\n\t\tbuild-kubemark-image\n\tfi\n}\n\n# Clean up repository\nfunction clean-repo {\n\techo -n -e \"Do you want to remove build output and binary? [y/N]${color_cyan}>${color_norm} \"\n\tread -r ISCLEAN\n\tif [[ \"${ISCLEAN}\" = \"y\" ]]; then\n\t\techo -e \"${color_yellow}CLEANING REPO${color_norm}\"\n\t\trm -rf \"${KUBE_ROOT}/_output\"\n\t\trm -f \"${KUBEMARK_IMAGE_LOCATION}/kubemark\"\n\telif [[ \"${ISCLEAN}\" = \"N\" ]]; then\n\t\techo -n \"\"\n\telse\n\t\techo -e \"${color_red}Invalid response, please try again:${color_norm}\"\n\t\tclean-repo\n\tfi\n}\n", "num_lines": 225}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/../../..\n\nsource \"${KUBE_ROOT}/test/kubemark/common/util.sh\"\n\n# Leave the skeleton definition of execute-cmd-on-master-with-retries\n# so only the pre-existing provider functions will target this.\nfunction execute-cmd-on-pre-existing-master-with-retries() {\n  IP_WITHOUT_PORT=$(echo \"${MASTER_IP}\" | cut -f 1 -d ':') || \"${MASTER_IP}\"\n\n  RETRIES=\"${2:-1}\" run-cmd-with-retries ssh kubernetes@\"${IP_WITHOUT_PORT}\" \"${1}\"\n}\n", "num_lines": 28}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script that starts kubelet on kubemark-master as a supervisord process\n# and then runs the master components as pods using kubelet.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Define key path variables.\nKUBE_ROOT=\"/home/kubernetes\"\nKUBE_BINDIR=\"${KUBE_ROOT}/kubernetes/server/bin\"\n\nfunction config-ip-firewall {\n  echo \"Configuring IP firewall rules\"\n  # The GCI image has host firewall which drop most inbound/forwarded packets.\n  # We need to add rules to accept all TCP/UDP/ICMP packets.\n  if iptables -L INPUT | grep \"Chain INPUT (policy DROP)\" > /dev/null; then\n    echo \"Add rules to accept all inbound TCP/UDP/ICMP packets\"\n    iptables -A INPUT -w -p TCP -j ACCEPT\n    iptables -A INPUT -w -p UDP -j ACCEPT\n    iptables -A INPUT -w -p ICMP -j ACCEPT\n  fi\n  if iptables -L FORWARD | grep \"Chain FORWARD (policy DROP)\" > /dev/null; then\n    echo \"Add rules to accept all forwarded TCP/UDP/ICMP packets\"\n    iptables -A FORWARD -w -p TCP -j ACCEPT\n    iptables -A FORWARD -w -p UDP -j ACCEPT\n    iptables -A FORWARD -w -p ICMP -j ACCEPT\n  fi\n}\n\nfunction create-dirs {\n\techo \"Creating required directories\"\n\tmkdir -p /var/lib/kubelet\n\tmkdir -p /etc/kubernetes/manifests\n\tmkdir -p /etc/kubernetes/addons\n}\n\n# Setup working directory for kubelet.\nfunction setup-kubelet-dir {\n\techo \"Making /var/lib/kubelet executable for kubelet\"\n\tmount -B /var/lib/kubelet /var/lib/kubelet/\n\tmount -B -o remount,exec,suid,dev /var/lib/kubelet\n}\n\n# Remove any default etcd config dirs/files.\nfunction delete-default-etcd-configs {\n\tif [[ -d /etc/etcd ]]; then\n\t\trm -rf /etc/etcd\n\tfi\n\tif [[ -e /etc/default/etcd ]]; then\n\t\trm -f /etc/default/etcd\n\tfi\n\tif [[ -e /etc/systemd/system/etcd.service ]]; then\n\t\trm -f /etc/systemd/system/etcd.service\n\tfi\n\tif [[ -e /etc/init.d/etcd ]]; then\n\t\trm -f /etc/init.d/etcd\n\tfi\n}\n\n# Compute etcd related variables.\nfunction compute-etcd-variables {\n\tETCD_IMAGE=\"${ETCD_IMAGE:-}\"\n\tETCD_QUOTA_BYTES=\"\"\n\tif [ \"${ETCD_VERSION:0:2}\" == \"3.\" ]; then\n\t\t# TODO: Set larger quota to see if that helps with\n\t\t# 'mvcc: database space exceeded' errors. If so, pipe\n\t\t# though our setup scripts.\n\t\tETCD_QUOTA_BYTES=\" --quota-backend-bytes=4294967296 \"\n\tfi\n}\n\n# Formats the given device ($1) if needed and mounts it at given mount point\n# ($2).\nfunction safe-format-and-mount() {\n\tdevice=$1\n\tmountpoint=$2\n\n\t# Format only if the disk is not already formatted.\n\tif ! tune2fs -l \"${device}\" ; then\n\t\techo \"Formatting '${device}'\"\n\t\tmkfs.ext4 -F \"${device}\"\n\tfi\n\n\techo \"Mounting '${device}' at '${mountpoint}'\"\n\tmount -o discard,defaults \"${device}\" \"${mountpoint}\"\n}\n\n# Finds a PD device with name '$1' attached to the master.\nfunction find-attached-pd() {\n\tlocal -r pd_name=$1\n\tif [[ ! -e /dev/disk/by-id/${pd_name} ]]; then\n\t\techo \"\"\n\tfi\n\tdevice_info=$(ls -l \"/dev/disk/by-id/${pd_name}\")\n\trelative_path=${device_info##* }\n\techo \"/dev/disk/by-id/${relative_path}\"\n}\n\n# Mounts a persistent disk (formatting if needed) to store the persistent data\n# on the master. safe-format-and-mount only formats an unformatted disk, and\n# mkdir -p will leave a directory be if it already exists.\nfunction mount-pd() {\n\tlocal -r pd_name=$1\n\tlocal -r mount_point=$2\n\n\tif [[ -z \"${find-attached-pd ${pd_name}}\" ]]; then\n\t\techo \"Can't find ${pd_name}. Skipping mount.\"\n\t\treturn\n\tfi\n\n\tlocal -r pd_path=\"/dev/disk/by-id/${pd_name}\"\n\techo \"Mounting PD '${pd_path}' at '${mount_point}'\"\n\t# Format and mount the disk, create directories on it for all of the master's\n\t# persistent data, and link them to where they're used.\n\tmkdir -p \"${mount_point}\"\n\tsafe-format-and-mount \"${pd_path}\" \"${mount_point}\"\n\techo \"Mounted PD '${pd_path}' at '${mount_point}'\"\n\n\t# NOTE: These locations on the PD store persistent data, so to maintain\n\t# upgradeability, these locations should not change.  If they do, take care\n\t# to maintain a migration path from these locations to whatever new\n\t# locations.\n}\n\n# Create kubeconfig for controller-manager's service account authentication.\nfunction create-kubecontrollermanager-kubeconfig {\n\techo \"Creating kube-controller-manager kubeconfig file\"\n\tmkdir -p \"${KUBE_ROOT}/k8s_auth_data/kube-controller-manager\"\n\tcat <<EOF >\"${KUBE_ROOT}/k8s_auth_data/kube-controller-manager/kubeconfig\"\napiVersion: v1\nkind: Config\nusers:\n- name: kube-controller-manager\n  user:\n    token: ${KUBE_CONTROLLER_MANAGER_TOKEN}\nclusters:\n- name: local\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://localhost:443\ncontexts:\n- context:\n    cluster: local\n    user: kube-controller-manager\n  name: service-account-context\ncurrent-context: service-account-context\nEOF\n}\n\nfunction create-kubescheduler-kubeconfig {\n  echo \"Creating kube-scheduler kubeconfig file\"\n  mkdir -p \"${KUBE_ROOT}/k8s_auth_data/kube-scheduler\"\n  cat <<EOF >\"${KUBE_ROOT}/k8s_auth_data/kube-scheduler/kubeconfig\"\napiVersion: v1\nkind: Config\nusers:\n- name: kube-scheduler\n  user:\n    token: ${KUBE_SCHEDULER_TOKEN}\nclusters:\n- name: local\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://localhost:443\ncontexts:\n- context:\n    cluster: local\n    user: kube-scheduler\n  name: kube-scheduler\ncurrent-context: kube-scheduler\nEOF\n}\n\nfunction create-addonmanager-kubeconfig {\n  echo \"Creating addonmanager kubeconfig file\"\n  mkdir -p \"${KUBE_ROOT}/k8s_auth_data/addon-manager\"\n  cat <<EOF >\"${KUBE_ROOT}/k8s_auth_data/addon-manager/kubeconfig\"\napiVersion: v1\nkind: Config\nusers:\n- name: addon-manager\n  user:\n    token: ${ADDON_MANAGER_TOKEN}\nclusters:\n- name: local\n  cluster:\n    insecure-skip-tls-verify: true\n    server: https://localhost:443\ncontexts:\n- context:\n    cluster: local\n    user: addon-manager\n  name: addon-manager\ncurrent-context: addon-manager\nEOF\n}\n\nfunction assemble-docker-flags {\n\techo \"Assemble docker command line flags\"\n\tlocal docker_opts=\"-p /var/run/docker.pid --iptables=false --ip-masq=false\"\n\tdocker_opts+=\" --log-level=debug\"  # Since it's a test cluster\n\t# TODO(shyamjvs): Incorporate network plugin options, etc later.\n\techo \"DOCKER_OPTS=\\\"${docker_opts}\\\"\" > /etc/default/docker\n\techo \"DOCKER_NOFILE=65536\" >> /etc/default/docker  # For setting ulimit -n\n\tsystemctl restart docker\n}\n\n# A helper function for loading a docker image. It keeps trying up to 5 times.\n#\n# $1: Full path of the docker image\nfunction try-load-docker-image {\n\tlocal -r img=$1\n\techo \"Try to load docker image file ${img}\"\n\t# Temporarily turn off errexit, because we don't want to exit on first failure.\n\tset +e\n\tlocal -r max_attempts=5\n\tlocal -i attempt_num=1\n\tuntil timeout 30 docker load -i \"${img}\"; do\n\t\tif [[ \"${attempt_num}\" == \"${max_attempts}\" ]]; then\n\t\t\techo \"Fail to load docker image file ${img} after ${max_attempts} retries. Exit!!\"\n\t\t\texit 1\n\t\telse\n\t\t\tattempt_num=$((attempt_num+1))\n\t\t\tsleep 5\n\t\tfi\n\tdone\n\t# Re-enable errexit.\n\tset -e\n}\n\n# Loads kube-system docker images. It is better to do it before starting kubelet,\n# as kubelet will restart docker daemon, which may interfere with loading images.\nfunction load-docker-images {\n\techo \"Start loading kube-system docker images\"\n\tlocal -r img_dir=\"${KUBE_BINDIR}\"\n\ttry-load-docker-image \"${img_dir}/kube-apiserver.tar\"\n\ttry-load-docker-image \"${img_dir}/kube-controller-manager.tar\"\n\ttry-load-docker-image \"${img_dir}/kube-scheduler.tar\"\n}\n\n# Computes command line arguments to be passed to kubelet.\nfunction compute-kubelet-params {\n\tlocal params=\"${KUBELET_TEST_ARGS:-}\"\n\tparams+=\" --cgroup-root=/\"\n\tparams+=\" --cloud-provider=gce\"\n\tparams+=\" --pod-manifest-path=/etc/kubernetes/manifests\"\n\tif [[ -n \"${KUBELET_PORT:-}\" ]]; then\n\t\tparams+=\" --port=${KUBELET_PORT}\"\n\tfi\n\tparams+=\" --enable-debugging-handlers=false\"\n\tparams+=\" --hairpin-mode=none\"\n\techo \"${params}\"\n}\n\n# Creates the systemd config file for kubelet.service.\nfunction create-kubelet-conf() {\n\tlocal -r kubelet_bin=\"$1\"\n\tlocal -r kubelet_env_file=\"/etc/default/kubelet\"\n\tlocal -r flags=$(compute-kubelet-params)\n\techo \"KUBELET_OPTS=\\\"${flags}\\\"\" > \"${kubelet_env_file}\"\n\n\t# Write the systemd service file for kubelet.\n\tcat <<EOF >/etc/systemd/system/kubelet.service\n[Unit]\nDescription=Kubermark kubelet\nRequires=network-online.target\nAfter=network-online.target\n\n[Service]\nRestart=always\nRestartSec=10\nEnvironmentFile=${kubelet_env_file}\nExecStart=${kubelet_bin} \\$KUBELET_OPTS\n\n[Install]\nWantedBy=multi-user.target\nEOF\n}\n\n# This function assembles the kubelet systemd service file and starts it using\n# systemctl, on the kubemark master.\nfunction start-kubelet {\n\t# Create systemd config.\n\tlocal -r kubelet_bin=\"/usr/bin/kubelet\"\n\tcreate-kubelet-conf \"${kubelet_bin}\"\n\n\t# Flush iptables nat table\n  \tiptables -t nat -F || true\n\n\t# Start the kubelet service.\n\tsystemctl start kubelet.service\n}\n\n# Create the log file and set its properties.\n#\n# $1 is the file to create.\nfunction prepare-log-file {\n\ttouch \"$1\"\n\tchmod 644 \"$1\"\n\tchown root:root \"$1\"\n}\n\n# A helper function for copying addon manifests and set dir/files\n# permissions.\n#\n# $1: addon category under /etc/kubernetes\n# $2: manifest source dir\nfunction setup-addon-manifests {\n  local -r src_dir=\"${KUBE_ROOT}/$2\"\n  local -r dst_dir=\"/etc/kubernetes/$1/$2\"\n\n  if [[ ! -d \"${dst_dir}\" ]]; then\n    mkdir -p \"${dst_dir}\"\n  fi\n\n  local files\n  files=$(find \"${src_dir}\" -maxdepth 1 -name \"*.yaml\")\n  if [[ -n \"${files}\" ]]; then\n    cp \"${src_dir}/\"*.yaml \"${dst_dir}\"\n  fi\n  chown -R root:root \"${dst_dir}\"\n  chmod 755 \"${dst_dir}\"\n  chmod 644 \"${dst_dir}\"/*\n}\n\n# Write the config for the audit policy.\n# Note: This duplicates the function in cluster/gce/gci/configure-helper.sh.\n# TODO: Get rid of this function when #53321 is fixed.\nfunction create-master-audit-policy {\n  local -r path=\"${1}\"\n  local -r policy=\"${2:-}\"\n\n  if [[ -n \"${policy}\" ]]; then\n    echo \"${policy}\" > \"${path}\"\n    return\n  fi\n\n  # Known api groups\n  local -r known_apis='\n      - group: \"\" # core\n      - group: \"admissionregistration.k8s.io\"\n      - group: \"apiextensions.k8s.io\"\n      - group: \"apiregistration.k8s.io\"\n      - group: \"apps\"\n      - group: \"authentication.k8s.io\"\n      - group: \"authorization.k8s.io\"\n      - group: \"autoscaling\"\n      - group: \"batch\"\n      - group: \"certificates.k8s.io\"\n      - group: \"extensions\"\n      - group: \"metrics\"\n      - group: \"networking.k8s.io\"\n      - group: \"policy\"\n      - group: \"rbac.authorization.k8s.io\"\n      - group: \"storage.k8s.io\"'\n\n  cat <<EOF >\"${path}\"\napiVersion: audit.k8s.io/v1\nkind: Policy\nrules:\n  # The following requests were manually identified as high-volume and low-risk,\n  # so drop them.\n  - level: None\n    users: [\"system:kube-proxy\"]\n    verbs: [\"watch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"endpoints\", \"services\", \"services/status\"]\n  - level: None\n    # Ingress controller reads 'configmaps/ingress-uid' through the unsecured port.\n    # TODO(#46983): Change this to the ingress controller service account.\n    users: [\"system:unsecured\"]\n    namespaces: [\"kube-system\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"configmaps\"]\n  - level: None\n    users: [\"kubelet\"] # legacy kubelet identity\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes\", \"nodes/status\"]\n  - level: None\n    userGroups: [\"system:nodes\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes\", \"nodes/status\"]\n  - level: None\n    users:\n      - system:kube-controller-manager\n      - system:kube-scheduler\n      - system:serviceaccount:kube-system:endpoint-controller\n    verbs: [\"get\", \"update\"]\n    namespaces: [\"kube-system\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"endpoints\"]\n  - level: None\n    users: [\"system:apiserver\"]\n    verbs: [\"get\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"namespaces\", \"namespaces/status\", \"namespaces/finalize\"]\n  # Don't log HPA fetching metrics.\n  - level: None\n    users:\n      - system:kube-controller-manager\n    verbs: [\"get\", \"list\"]\n    resources:\n      - group: \"metrics\"\n  # Don't log these read-only URLs.\n  - level: None\n    nonResourceURLs:\n      - /healthz*\n      - /version\n      - /swagger*\n  # Don't log events requests.\n  - level: None\n    resources:\n      - group: \"\" # core\n        resources: [\"events\"]\n  # node and pod status calls from nodes are high-volume and can be large, don't log responses for expected updates from nodes\n  - level: Request\n    users: [\"kubelet\", \"system:node-problem-detector\", \"system:serviceaccount:kube-system:node-problem-detector\"]\n    verbs: [\"update\",\"patch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes/status\", \"pods/status\"]\n    omitStages:\n      - \"RequestReceived\"\n  - level: Request\n    userGroups: [\"system:nodes\"]\n    verbs: [\"update\",\"patch\"]\n    resources:\n      - group: \"\" # core\n        resources: [\"nodes/status\", \"pods/status\"]\n    omitStages:\n      - \"RequestReceived\"\n  # deletecollection calls can be large, don't log responses for expected namespace deletions\n  - level: Request\n    users: [\"system:serviceaccount:kube-system:namespace-controller\"]\n    verbs: [\"deletecollection\"]\n    omitStages:\n      - \"RequestReceived\"\n  # Secrets, ConfigMaps, TokenRequest and TokenReviews can contain sensitive & binary data,\n  # so only log at the Metadata level.\n  - level: Metadata\n    resources:\n      - group: \"\" # core\n        resources: [\"secrets\", \"configmaps\", \"serviceaccounts/token\"]\n      - group: authentication.k8s.io\n        resources: [\"tokenreviews\"]\n    omitStages:\n      - \"RequestReceived\"\n  # Get responses can be large; skip them.\n  - level: Request\n    verbs: [\"get\", \"list\", \"watch\"]\n    resources: ${known_apis}\n    omitStages:\n      - \"RequestReceived\"\n  # Default level for known APIs\n  - level: RequestResponse\n    resources: ${known_apis}\n    omitStages:\n      - \"RequestReceived\"\n  # Default level for all other requests.\n  - level: Metadata\n    omitStages:\n      - \"RequestReceived\"\nEOF\n}\n\n# Computes command line arguments to be passed to etcd.\nfunction compute-etcd-params {\n\tlocal params=\"${ETCD_TEST_ARGS:-}\"\n\tparams+=\" --name=etcd-$(hostname -s)\"\n\tparams+=\" --listen-peer-urls=http://127.0.0.1:2380\"\n\tparams+=\" --advertise-client-urls=http://127.0.0.1:2379\"\n\tparams+=\" --listen-client-urls=http://0.0.0.0:2379\"\n\n\t# Enable apiserver->etcd auth.\n\tparams+=\" --client-cert-auth\"\n\tparams+=\" --trusted-ca-file /etc/srv/kubernetes/etcd-apiserver-ca.crt\"\n\tparams+=\" --cert-file /etc/srv/kubernetes/etcd-apiserver-server.crt\"\n\tparams+=\" --key-file /etc/srv/kubernetes/etcd-apiserver-server.key\"\n\n\tparams+=\" --data-dir=/var/etcd/data\"\n\tparams+=\" ${ETCD_QUOTA_BYTES}\"\n\techo \"${params}\"\n}\n\n# Computes command line arguments to be passed to etcd-events.\nfunction compute-etcd-events-params {\n\tlocal params=\"${ETCD_TEST_ARGS:-}\"\n\tparams+=\" --name=etcd-$(hostname -s)\"\n\tparams+=\" --listen-peer-urls=http://127.0.0.1:2381\"\n\tparams+=\" --advertise-client-urls=http://127.0.0.1:4002\"\n\tparams+=\" --listen-client-urls=http://0.0.0.0:4002\"\n\tparams+=\" --data-dir=/var/etcd/data-events\"\n\tparams+=\" ${ETCD_QUOTA_BYTES}\"\n\techo \"${params}\"\n}\n\n# Computes command line arguments to be passed to apiserver.\nfunction compute-kube-apiserver-params {\n\tlocal params=\"--insecure-bind-address=0.0.0.0\"\n\tparams+=\" --etcd-servers=${ETCD_SERVERS:-http://127.0.0.1:2379}\"\n\tif [[ -z \"${ETCD_SERVERS:-}\" ]]; then\n\t\tparams+=\" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-/events#${EVENT_STORE_URL}}\"\n\telif [[ -n \"${ETCD_SERVERS_OVERRIDES:-}\" ]]; then\n\t\tparams+=\" --etcd-servers-overrides=${ETCD_SERVERS_OVERRIDES:-}\"\n\tfi\n\t# Enable apiserver->etcd auth.\n\tparams+=\" --etcd-cafile=/etc/srv/kubernetes/etcd-apiserver-ca.crt\"\n\tparams+=\" --etcd-certfile=/etc/srv/kubernetes/etcd-apiserver-client.crt\"\n\tparams+=\" --etcd-keyfile=/etc/srv/kubernetes/etcd-apiserver-client.key\"\n\n\tparams+=\" --tls-cert-file=/etc/srv/kubernetes/server.cert\"\n\tparams+=\" --tls-private-key-file=/etc/srv/kubernetes/server.key\"\n\tparams+=\" --requestheader-client-ca-file=/etc/srv/kubernetes/aggr_ca.crt\"\n\tparams+=\" --requestheader-allowed-names=aggregator\"\n\tparams+=\" --requestheader-extra-headers-prefix=X-Remote-Extra-\"\n\tparams+=\" --requestheader-group-headers=X-Remote-Group\"\n\tparams+=\" --requestheader-username-headers=X-Remote-User\"\n\tparams+=\" --proxy-client-cert-file=/etc/srv/kubernetes/proxy_client.crt\"\n\tparams+=\" --proxy-client-key-file=/etc/srv/kubernetes/proxy_client.key\"\n\tparams+=\" --enable-aggregator-routing=true\"\n\tparams+=\" --client-ca-file=/etc/srv/kubernetes/ca.crt\"\n\tparams+=\" --token-auth-file=/etc/srv/kubernetes/known_tokens.csv\"\n\tparams+=\" --secure-port=443\"\n\tparams+=\" --target-ram-mb=$((NUM_NODES * 60))\"\n\tparams+=\" --service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}\"\n\tparams+=\" --admission-control=${CUSTOM_ADMISSION_PLUGINS}\"\n\tparams+=\" --authorization-mode=Node,RBAC\"\n\tparams+=\" --allow-privileged=true\"\n\tif [[ -n \"${STORAGE_BACKEND:-}\" ]]; then\n\t\tparams+=\" --storage-backend=${STORAGE_BACKEND}\"\n\tfi\n\tif [[ -n \"${STORAGE_MEDIA_TYPE:-}\" ]]; then\n\t\tparams+=\" --storage-media-type=${STORAGE_MEDIA_TYPE}\"\n\tfi\n  if [[ -n \"${ETCD_COMPACTION_INTERVAL_SEC:-}\" ]]; then\n    params+=\" --etcd-compaction-interval=${ETCD_COMPACTION_INTERVAL_SEC}s\"\n  fi\n\tif [[ -n \"${KUBE_APISERVER_REQUEST_TIMEOUT:-}\" ]]; then\n\t\tparams+=\" --min-request-timeout=${KUBE_APISERVER_REQUEST_TIMEOUT}\"\n\tfi\n\tif [[ \"${NUM_NODES}\" -ge 3000 ]]; then\n\t\tparams+=\" --max-requests-inflight=3000 --max-mutating-requests-inflight=1000\"\n\telif [[ \"${NUM_NODES}\" -ge 1000 ]]; then\n\t\tparams+=\" --max-requests-inflight=1500 --max-mutating-requests-inflight=500\"\n\tfi\n\tif [[ -n \"${RUNTIME_CONFIG:-}\" ]]; then\n\t\tparams+=\" --runtime-config=${RUNTIME_CONFIG}\"\n\tfi\n\tif [[ -n \"${FEATURE_GATES:-}\" ]]; then\n\t\tparams+=\" --feature-gates=${FEATURE_GATES}\"\n\tfi\n\tif [[ \"${ENABLE_APISERVER_ADVANCED_AUDIT:-}\" == \"true\" ]]; then\n\t\t# Create the audit policy file, and mount it into the apiserver pod.\n\t\tcreate-master-audit-policy \"${audit_policy_file}\" \"${ADVANCED_AUDIT_POLICY:-}\"\n\n\t\t# The config below matches the one in cluster/gce/gci/configure-helper.sh.\n\t\t# TODO: Currently supporting just log backend. Support webhook if needed.\n\t\tparams+=\" --audit-policy-file=${audit_policy_file}\"\n\t\tparams+=\" --audit-log-path=/var/log/kube-apiserver-audit.log\"\n\t\tparams+=\" --audit-log-maxage=0\"\n\t\tparams+=\" --audit-log-maxbackup=0\"\n\t\tparams+=\" --audit-log-maxsize=2000000000\"\n\tfi\n        # Append APISERVER_TEST_ARGS to the end, which will allow for\n        # the above defaults to be overridden.\n\tparams+=\" ${APISERVER_TEST_ARGS:-}\"\n\techo \"${params}\"\n}\n\n# Computes command line arguments to be passed to controller-manager.\nfunction compute-kube-controller-manager-params {\n\tlocal params=\"${CONTROLLER_MANAGER_TEST_ARGS:-}\"\n\tparams+=\" --use-service-account-credentials\"\n\tparams+=\" --kubeconfig=/etc/srv/kubernetes/kube-controller-manager/kubeconfig\"\n\tparams+=\" --service-account-private-key-file=/etc/srv/kubernetes/server.key\"\n\tparams+=\" --root-ca-file=/etc/srv/kubernetes/ca.crt\"\n\tparams+=\" --allocate-node-cidrs=${ALLOCATE_NODE_CIDRS}\"\n\tparams+=\" --cluster-cidr=${CLUSTER_IP_RANGE}\"\n\tparams+=\" --service-cluster-ip-range=${SERVICE_CLUSTER_IP_RANGE}\"\n\tparams+=\" --terminated-pod-gc-threshold=${TERMINATED_POD_GC_THRESHOLD}\"\n\techo \"${params}\"\n}\n\n# Computes command line arguments to be passed to scheduler.\nfunction compute-kube-scheduler-params {\n\tlocal params=\"${SCHEDULER_TEST_ARGS:-}\"\n\tparams+=\" --kubeconfig=/etc/srv/kubernetes/kube-scheduler/kubeconfig\"\n\techo \"${params}\"\n}\n\n# Computes command line arguments to be passed to addon-manager.\nfunction compute-kube-addon-manager-params {\n\techo \"\"\n}\n\n# Start a kubernetes master component '$1' which can be any of the following:\n# 1. etcd\n# 2. etcd-events\n# 3. kube-apiserver\n# 4. kube-controller-manager\n# 5. kube-scheduler\n# 6. kube-addon-manager\n#\n# It prepares the log file, loads the docker tag, calculates variables, sets them\n# in the manifest file, and then copies the manifest file to /etc/kubernetes/manifests.\n#\n# Assumed vars:\n#   DOCKER_REGISTRY\nfunction start-kubemaster-component() {\n\techo \"Start master component $1\"\n\tlocal -r component=$1\n\tprepare-log-file /var/log/\"${component}\".log\n\tlocal -r src_file=\"${KUBE_ROOT}/${component}.yaml\"\n\tlocal -r params=$(\"compute-${component}-params\")\n\n\t# Evaluate variables.\n\tsed -i -e \"s@{{params}}@${params}@g\" \"${src_file}\"\n\tsed -i -e \"s@{{kube_docker_registry}}@${DOCKER_REGISTRY}@g\" \"${src_file}\"\n\tsed -i -e \"s@{{instance_prefix}}@${INSTANCE_PREFIX}@g\" \"${src_file}\"\n\tif [ \"${component:0:4}\" == \"etcd\" ]; then\n\t\tsed -i -e \"s@{{etcd_image}}@${ETCD_IMAGE}@g\" \"${src_file}\"\n\telif [ \"${component}\" == \"kube-addon-manager\" ]; then\n\t\tsetup-addon-manifests \"addons\" \"kubemark-rbac-bindings\"\n\telse\n\t\tlocal -r component_docker_tag=$(cat \"${KUBE_BINDIR}/${component}.docker_tag\")\n\t\tsed -i -e \"s@{{${component}_docker_tag}}@${component_docker_tag}@g\" \"${src_file}\"\n\t\tif [ \"${component}\" == \"kube-apiserver\" ]; then\n\t\t\tlocal audit_policy_config_mount=\"\"\n\t\t\tlocal audit_policy_config_volume=\"\"\n\t\t\tif [[ \"${ENABLE_APISERVER_ADVANCED_AUDIT:-}\" == \"true\" ]]; then\n\t\t\t\tread -r -d '' audit_policy_config_mount << EOF\n- name: auditpolicyconfigmount\n  mountPath: ${audit_policy_file}\n  readOnly: true\nEOF\n\t\t\t\tread -r -d '' audit_policy_config_volume << EOF\n- name: auditpolicyconfigmount\n  hostPath:\n    path: ${audit_policy_file}\n    type: FileOrCreate\nEOF\n\t\t\tfi\n\t\t\tsed -i -e \"s@{{audit_policy_config_mount}}@${audit_policy_config_mount}@g\" \"${src_file}\"\n\t\t\tsed -i -e \"s@{{audit_policy_config_volume}}@${audit_policy_config_volume}@g\" \"${src_file}\"\n\t\tfi\n\tfi\n\tcp \"${src_file}\" /etc/kubernetes/manifests\n}\n\n############################### Main Function ########################################\necho \"Start to configure master instance for kubemark\"\n\n# Extract files from the server tar and setup master env variables.\ncd \"${KUBE_ROOT}\"\nif [[ ! -d \"${KUBE_ROOT}/kubernetes\" ]]; then\n\ttar xzf kubernetes-server-linux-amd64.tar.gz\nfi\nsource \"${KUBE_ROOT}/kubemark-master-env.sh\"\n\n# Setup IP firewall rules, required directory structure and etcd config.\nconfig-ip-firewall\ncreate-dirs\nsetup-kubelet-dir\ndelete-default-etcd-configs\ncompute-etcd-variables\n\n# Setup authentication tokens and kubeconfigs for kube-controller-manager and kube-scheduler,\n# only if their kubeconfigs don't already exist as this script could be running on reboot.\nif [[ ! -f \"${KUBE_ROOT}/k8s_auth_data/kube-controller-manager/kubeconfig\" ]]; then\n\tKUBE_CONTROLLER_MANAGER_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n\techo \"${KUBE_CONTROLLER_MANAGER_TOKEN},system:kube-controller-manager,uid:system:kube-controller-manager\" >> \"${KUBE_ROOT}/k8s_auth_data/known_tokens.csv\"\n\tcreate-kubecontrollermanager-kubeconfig\nfi\nif [[ ! -f \"${KUBE_ROOT}/k8s_auth_data/kube-scheduler/kubeconfig\" ]]; then\n\tKUBE_SCHEDULER_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\n\techo \"${KUBE_SCHEDULER_TOKEN},system:kube-scheduler,uid:system:kube-scheduler\" >> \"${KUBE_ROOT}/k8s_auth_data/known_tokens.csv\"\n\tcreate-kubescheduler-kubeconfig\nfi\n\nADDON_MANAGER_TOKEN=$(dd if=/dev/urandom bs=128 count=1 2>/dev/null | base64 | tr -d \"=+/\" | dd bs=32 count=1 2>/dev/null)\necho \"${ADDON_MANAGER_TOKEN},system:addon-manager,admin,system:masters\" >> \"${KUBE_ROOT}/k8s_auth_data/known_tokens.csv\"\ncreate-addonmanager-kubeconfig\n\n# Mount master PD for etcd and create symbolic links to it.\n{\n\tmain_etcd_mount_point=\"/mnt/disks/master-pd\"\n\tmount-pd \"google-master-pd\" \"${main_etcd_mount_point}\"\n\t# Contains all the data stored in etcd.\n\tmkdir -p \"${main_etcd_mount_point}/var/etcd\"\n\tchmod 700 \"${main_etcd_mount_point}/var/etcd\"\n\tln -s -f \"${main_etcd_mount_point}/var/etcd\" /var/etcd\n\tmkdir -p /etc/srv\n\t# Setup the dynamically generated apiserver auth certs and keys to pd.\n\tmkdir -p \"${main_etcd_mount_point}/srv/kubernetes\"\n\tln -s -f \"${main_etcd_mount_point}/srv/kubernetes\" /etc/srv/kubernetes\n\t# Copy the files to the PD only if they don't exist (so we do it only the first time).\n\tif [[ \"$(ls -A ${main_etcd_mount_point}/srv/kubernetes/)\" == \"\" ]]; then\n\t\tcp -r \"${KUBE_ROOT}\"/k8s_auth_data/* \"${main_etcd_mount_point}/srv/kubernetes/\"\n\tfi\n\t# Directory for kube-apiserver to store SSH key (if necessary).\n\tmkdir -p \"${main_etcd_mount_point}/srv/sshproxy\"\n\tln -s -f \"${main_etcd_mount_point}/srv/sshproxy\" /etc/srv/sshproxy\n}\n\n# Mount master PD for event-etcd (if required) and create symbolic links to it.\n{\n\tEVENT_STORE_IP=\"${EVENT_STORE_IP:-127.0.0.1}\"\n\tEVENT_STORE_URL=\"${EVENT_STORE_URL:-http://${EVENT_STORE_IP}:4002}\"\n\tif [ \"${EVENT_PD:-}\" == \"true\" ]; then\n\t\tevent_etcd_mount_point=\"/mnt/disks/master-event-pd\"\n\t\tmount-pd \"google-master-event-pd\" \"${event_etcd_mount_point}\"\n\t\t# Contains all the data stored in event etcd.\n\t\tmkdir -p \"${event_etcd_mount_point}/var/etcd/events\"\n\t\tchmod 700 \"${event_etcd_mount_point}/var/etcd/events\"\n\t\tln -s -f \"${event_etcd_mount_point}/var/etcd/events\" /var/etcd/events\n\tfi\n}\n\n# Setup docker flags and load images of the master components.\nassemble-docker-flags\nDOCKER_REGISTRY=\"k8s.gcr.io\"\nload-docker-images\n\nreadonly audit_policy_file=\"/etc/audit_policy.config\"\n\n# Start kubelet as a supervisord process and master components as pods.\nstart-kubelet\nif [[ -z \"${ETCD_SERVERS:-}\" ]]; then\n\tstart-kubemaster-component \"etcd\"\n\tif [ \"${EVENT_STORE_IP:-}\" == \"127.0.0.1\" ]; then\n\t\tstart-kubemaster-component \"etcd-events\"\n\tfi\nfi\nstart-kubemaster-component \"kube-apiserver\"\nstart-kubemaster-component \"kube-controller-manager\"\nstart-kubemaster-component \"kube-scheduler\"\nstart-kubemaster-component \"kube-addon-manager\"\n\n# Wait till apiserver is working fine or timeout.\necho -n \"Waiting for apiserver to be healthy\"\nstart=$(date +%s)\nuntil [ \"$(curl 127.0.0.1:8080/healthz 2> /dev/null)\" == \"ok\" ]; do\n\techo -n \".\"\n\tsleep 1\n\tnow=$(date +%s)\n\tif [ $((now - start)) -gt 300 ]; then\n\t\techo \"Timeout!\"\n\t\texit 1\n\tfi\ndone\n\necho \"Done for the configuration for kubemark master\"\n", "num_lines": 778}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script contains the helper functions that each provider hosting\n# Kubermark must implement to use test/kubemark/start-kubemark.sh and\n# test/kubemark/stop-kubemark.sh scripts.\n\n# This function should authenticate docker to be able to read/write to\n# the right container registry (needed for pushing kubemark image).\nfunction authenticate-docker {\n\techo \"Configuring registry authentication\" 1>&2\n}\n\n# This function should create kubemark master and write kubeconfig to\n# \"${RESOURCE_DIRECTORY}/kubeconfig.kubemark\".\n# If a cluster uses private master IP, create-kubemark-master might also write\n# a second kubeconfig to \"${RESOURCE_DIRECTORY}/kubeconfig-internal.kubemark\".\n# The difference between these two kubeconfigs is that the internal one uses\n# private master IP, which might be better suited for setting up hollow nodes.\nfunction create-kubemark-master {\n  echo \"Creating cluster...\"\n}\n\n# This function should delete kubemark master.\nfunction delete-kubemark-master {\n  echo \"Deleting cluster...\"\n}\n\n# This function should return node labels.\nfunction calculate-node-labels {\n  echo \"\"\n}\n\n# Common colors used throughout the kubemark scripts\nif [[ -z \"${color_start-}\" ]]; then\n  declare -r color_start=\"\\033[\"\n  # shellcheck disable=SC2034\n  declare -r color_red=\"${color_start}0;31m\"\n  # shellcheck disable=SC2034\n  declare -r color_yellow=\"${color_start}0;33m\"\n  # shellcheck disable=SC2034\n  declare -r color_green=\"${color_start}0;32m\"\n  # shellcheck disable=SC2034\n  declare -r color_blue=\"${color_start}1;34m\"\n  # shellcheck disable=SC2034\n  declare -r color_cyan=\"${color_start}1;36m\"\n  # shellcheck disable=SC2034\n  declare -r color_norm=\"${color_start}0m\"\nfi\n", "num_lines": 63}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n### Copyright 2010 Manuel Carrasco Mo\u00c3\u00b1ino. (manolo at apache.org)\n###\n### Licensed under the Apache License, Version 2.0.\n### You may obtain a copy of it at\n### http://www.apache.org/licenses/LICENSE-2.0\n\n###\n### A library for shell scripts which creates reports in jUnit format.\n### These reports can be used in Jenkins, or any other CI.\n###\n### Usage:\n###     - Include this file in your shell script\n###     - Use juLog to call your command any time you want to produce a new report\n###        Usage:   juLog <options> command arguments\n###           options:\n###             -class=\"MyClass\" : a class name which will be shown in the junit report\n###             -name=\"TestName\" : the test name which will be shown in the junit report\n###             -error=\"RegExp\"  : a regexp which sets the test as failure when the output matches it\n###             -ierror=\"RegExp\" : same as -error but case insensitive\n###             -output=\"Path\"   : path to output directory, defaults to \"./results\"\n###     - Junit reports are left in the folder 'result' under the directory where the script is executed.\n###     - Configure Jenkins to parse junit files from the generated folder\n###\n\nasserts=00; errors=0; total=0; content=\"\"\ndate=\"$(which gdate 2>/dev/null || which date)\"\n\n# default output folder\njuDIR=\"$(pwd)/results\"\n\n# The name of the suite is calculated based in your script name\nsuite=\"\"\n\nif LANG=C sed --help 2>&1 | grep -q GNU; then\n  SED=\"sed\"\nelif which gsed &>/dev/null; then\n  SED=\"gsed\"\nelse\n  echo \"Failed to find GNU sed as sed or gsed. If you are on Mac: brew install gnu-sed.\" >&2\n  exit 1\nfi\n\n# A wrapper for the eval method witch allows catching seg-faults and use tee\nerrfile=/tmp/evErr.$$.log\nfunction eVal() {\n  (eval \"$1\")\n  # stdout and stderr may currently be inverted (see below) so echo may write to stderr\n  echo \"$?\" 2>&1 | tr -d \"\\n\" > \"${errfile}\"\n}\n\n# Method to clean old tests\nfunction juLogClean() {\n  echo \"+++ Removing old junit reports from: ${juDIR} \"\n  rm -f \"${juDIR}\"/junit-*\n}\n\n# Execute a command and record its results\nfunction juLog() {\n  suite=\"\";\n  errfile=/tmp/evErr.$$.log\n  date=\"$(which gdate 2>/dev/null || which date)\"\n  asserts=00; errors=0; total=0; content=\"\"\n\n  # parse arguments\n  ya=\"\"; icase=\"\"\n  while [[ -z \"$ya\" ]]; do\n    case \"$1\" in\n      -name=*)   name=\"$(echo \"$1\" | ${SED} -e 's/-name=//')\";   shift;;\n      -class=*)  class=\"$(echo \"$1\" | ${SED} -e 's/-class=//')\";   shift;;\n      -ierror=*) ereg=\"$(echo \"$1\" | ${SED} -e 's/-ierror=//')\"; icase=\"-i\"; shift;;\n      -error=*)  ereg=\"$(echo \"$1\" | ${SED} -e 's/-error=//')\";  shift;;\n      -output=*) juDIR=\"$(echo \"$1\" | ${SED} -e 's/-output=//')\";  shift;;\n      *)         ya=1;;\n    esac\n  done\n\n  # create output directory\n  mkdir -p \"${juDIR}\" || exit\n  # use first arg as name if it was not given\n  if [[ -z \"${name}\" ]]; then\n    name=\"${asserts}-$1\"\n    shift\n  fi\n\n  if [[ \"${class}\" = \"\" ]]; then\n    class=\"default\"\n  fi\n\n  suite=${class}\n\n  # calculate command to eval\n  [[ -z \"$1\" ]] && return\n  cmd=\"$1\"; shift\n  while [[ -n \"${1:-}\" ]]\n  do\n     cmd=\"${cmd} \\\"$1\\\"\"\n     shift\n  done\n\n  # eval the command sending output to a file\n  outf=/var/tmp/ju$$.txt\n  errf=/var/tmp/ju$$-err.txt\n  :>${outf}\n  echo \"\"                         | tee -a ${outf}\n  echo \"+++ Running case: ${class}.${name} \" | tee -a ${outf}\n  echo \"+++ working dir: $(pwd)\"           | tee -a ${outf}\n  echo \"+++ command: ${cmd}\"            | tee -a ${outf}\n  ini=\"$(${date} +%s.%N)\"\n  # execute the command, temporarily swapping stderr and stdout so they can be tee'd to separate files,\n  # then swapping them back again so that the streams are written correctly for the invoking process\n  ( (eVal \"${cmd}\" | tee -a ${outf}) 3>&1 1>&2 2>&3 | tee ${errf}) 3>&1 1>&2 2>&3\n  evErr=\"$(cat ${errfile})\"\n  rm -f ${errfile}\n  end=\"$(${date} +%s.%N)\"\n  echo \"+++ exit code: ${evErr}\"        | tee -a ${outf}\n\n  # set the appropriate error, based in the exit code and the regex\n  [[ ${evErr} != 0 ]] && err=1 || err=0\n  out=\"$(${SED} -e 's/^\\([^+]\\)/| \\1/g' \"$outf\")\"\n  if [ ${err} = 0 ] && [ -n \"${ereg:-}\" ]; then\n      H=$(echo \"${out}\" | grep -E ${icase} \"${ereg}\")\n      [[ -n \"${H}\" ]] && err=1\n  fi\n  [[ ${err} != 0 ]] && echo \"+++ error: ${err}\"         | tee -a ${outf}\n  rm -f ${outf}\n\n  errMsg=$(cat ${errf})\n  rm -f ${errf}\n  # calculate vars\n  asserts=$((asserts+1))\n  errors=$((errors+err))\n  time=$(echo \"${end} ${ini}\" | awk '{print $1 - $2}')\n  total=$(echo \"${total} ${time}\" | awk '{print $1 + $2}')\n\n  # write the junit xml report\n  ## failure tag\n  [[ ${err} = 0 ]] && failure=\"\" || failure=\"\n      <failure type=\\\"ScriptError\\\" message=\\\"Script Error\\\"><![CDATA[${errMsg}]]></failure>\n  \"\n  ## testcase tag\n  content=\"${content}\n    <testcase assertions=\\\"1\\\" name=\\\"${name}\\\" time=\\\"${time}\\\" classname=\\\"${class}\\\">\n    ${failure}\n    <system-err><![CDATA[${errMsg}]]></system-err>\n    </testcase>\n  \"\n  ## testsuite block\n\n  if [[ -e \"${juDIR}/junit_${suite}.xml\" ]]; then\n    # file exists. first update the failures count\n    failCount=$(${SED} -n \"s/.*testsuite.*failures=\\\"\\([0-9]*\\)\\\".*/\\1/p\" \"${juDIR}/junit_${suite}.xml\")\n    errors=$((failCount+errors))\n    ${SED} -i \"0,/failures=\\\"${failCount}\\\"/ s/failures=\\\"${failCount}\\\"/failures=\\\"${errors}\\\"/\" \"${juDIR}/junit_${suite}.xml\"\n    ${SED} -i \"0,/errors=\\\"${failCount}\\\"/ s/errors=\\\"${failCount}\\\"/errors=\\\"${errors}\\\"/\" \"${juDIR}/junit_${suite}.xml\"\n\n    # file exists. Need to append to it. If we remove the testsuite end tag, we can just add it in after.\n    ${SED} -i \"s^</testsuite>^^g\" \"${juDIR}/junit_${suite}.xml\" ## remove testSuite so we can add it later\n    ${SED} -i \"s^</testsuites>^^g\" \"${juDIR}/junit_${suite}.xml\"\n    cat <<EOF >> \"$juDIR/junit_$suite.xml\"\n     ${content:-}\n    </testsuite>\n</testsuites>\nEOF\n\n  else\n    # no file exists. Adding a new file\n    cat <<EOF > \"${juDIR}/junit_${suite}.xml\"\n<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites>\n    <testsuite failures=\"${errors}\" assertions=\"${assertions:-}\" name=\"${suite}\" tests=\"1\" errors=\"${errors}\" time=\"${total}\">\n    ${content:-}\n    </testsuite>\n</testsuites>\nEOF\n  fi\n\n  return ${err}\n}\n", "num_lines": 180}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# enable automatic i386/ARM/M68K/MIPS/SPARC/PPC/s390/HPPA/Xtensa/microblaze\n# program execution by the kernel\n#\n# downloaded from https://raw.githubusercontent.com/qemu/qemu/master/scripts/qemu-binfmt-conf.sh\n\n# Enable automatic program execution by the kernel.\n\nqemu_target_list=\"i386 i486 alpha arm armeb sparc sparc32plus sparc64 \\\nppc ppc64 ppc64le m68k mips mipsel mipsn32 mipsn32el mips64 mips64el \\\nsh4 sh4eb s390x aarch64 aarch64_be hppa riscv32 riscv64 xtensa xtensaeb \\\nmicroblaze microblazeel or1k x86_64\"\n\ni386_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x03\\x00'\ni386_mask='\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\ni386_family=i386\n\ni486_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x06\\x00'\ni486_mask='\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\ni486_family=i386\n\nx86_64_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x3e\\x00'\nx86_64_mask='\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nx86_64_family=i386\n\nalpha_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x26\\x90'\nalpha_mask='\\xff\\xff\\xff\\xff\\xff\\xfe\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nalpha_family=alpha\n\narm_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28\\x00'\narm_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\narm_family=arm\n\narmeb_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x28'\narmeb_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\narmeb_family=armeb\n\nsparc_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x02'\nsparc_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nsparc_family=sparc\n\nsparc32plus_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x12'\nsparc32plus_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nsparc32plus_family=sparc\n\nsparc64_magic='\\x7fELF\\x02\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x2b'\nsparc64_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nsparc64_family=sparc\n\nppc_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x14'\nppc_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nppc_family=ppc\n\nppc64_magic='\\x7fELF\\x02\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x15'\nppc64_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nppc64_family=ppc\n\nppc64le_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x15\\x00'\nppc64le_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\x00'\nppc64le_family=ppcle\n\nm68k_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x04'\nm68k_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nm68k_family=m68k\n\n# FIXME: We could use the other endianness on a MIPS host.\n\nmips_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08'\nmips_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nmips_family=mips\n\nmipsel_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08\\x00'\nmipsel_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nmipsel_family=mips\n\nmipsn32_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08'\nmipsn32_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nmipsn32_family=mips\n\nmipsn32el_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08\\x00'\nmipsn32el_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nmipsn32el_family=mips\n\nmips64_magic='\\x7fELF\\x02\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08'\nmips64_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nmips64_family=mips\n\nmips64el_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x08\\x00'\nmips64el_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nmips64el_family=mips\n\nsh4_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x2a\\x00'\nsh4_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nsh4_family=sh4\n\nsh4eb_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x2a'\nsh4eb_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nsh4eb_family=sh4\n\ns390x_magic='\\x7fELF\\x02\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x16'\ns390x_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\ns390x_family=s390x\n\naarch64_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xb7\\x00'\naarch64_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\naarch64_family=arm\n\naarch64_be_magic='\\x7fELF\\x02\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xb7'\naarch64_be_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\naarch64_be_family=armeb\n\nhppa_magic='\\x7f\\x45\\x4c\\x46\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x0f'\nhppa_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nhppa_family=hppa\n\nriscv32_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xf3\\x00'\nriscv32_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nriscv32_family=riscv\n\nriscv64_magic='\\x7fELF\\x02\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xf3\\x00'\nriscv64_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nriscv64_family=riscv\n\nxtensa_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x5e\\x00'\nxtensa_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nxtensa_family=xtensa\n\nxtensaeb_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x5e'\nxtensaeb_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nxtensaeb_family=xtensaeb\n\nmicroblaze_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xba\\xab'\nmicroblaze_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nmicroblaze_family=microblaze\n\nmicroblazeel_magic='\\x7fELF\\x01\\x01\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\xab\\xba'\nmicroblazeel_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff\\xff'\nmicroblazeel_family=microblazeel\n\nor1k_magic='\\x7fELF\\x01\\x02\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x02\\x00\\x5c'\nor1k_mask='\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\x00\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xff\\xfe\\xff\\xff'\nor1k_family=or1k\n\nqemu_get_family() {\n    cpu=${HOST_ARCH:-$(uname -m)}\n    case \"$cpu\" in\n    amd64|i386|i486|i586|i686|i86pc|BePC|x86_64)\n        echo \"i386\"\n        ;;\n    mips*)\n        echo \"mips\"\n        ;;\n    \"Power Macintosh\"|ppc64|powerpc|ppc)\n        echo \"ppc\"\n        ;;\n    ppc64el|ppc64le)\n        echo \"ppcle\"\n        ;;\n    arm|armel|armhf|arm64|armv[4-9]*l|aarch64)\n        echo \"arm\"\n        ;;\n    armeb|armv[4-9]*b|aarch64_be)\n        echo \"armeb\"\n        ;;\n    sparc*)\n        echo \"sparc\"\n        ;;\n    riscv*)\n        echo \"riscv\"\n        ;;\n    *)\n        echo \"$cpu\"\n        ;;\n    esac\n}\n\nusage() {\n    cat <<EOF\nUsage: qemu-binfmt-conf.sh [--qemu-path PATH][--debian][--systemd CPU]\n                           [--help][--credential yes|no][--exportdir PATH]\n                           [--persistent yes|no][--qemu-suffix SUFFIX]\n\n       Configure binfmt_misc to use qemu interpreter\n\n       --help:        display this usage\n       --qemu-path:   set path to qemu interpreter ($QEMU_PATH)\n       --qemu-suffix: add a suffix to the default interpreter name\n       --debian:      don't write into /proc,\n                      instead generate update-binfmts templates\n       --systemd:     don't write into /proc,\n                      instead generate file for systemd-binfmt.service\n                      for the given CPU. If CPU is \"ALL\", generate a\n                      file for all known cpus\n       --exportdir:   define where to write configuration files\n                      (default: $SYSTEMDDIR or $DEBIANDIR)\n       --credential:  if yes, credential and security tokens are\n                      calculated according to the binary to interpret\n       --persistent:  if yes, the interpreter is loaded when binfmt is\n                      configured and remains in memory. All future uses\n                      are cloned from the open file.\n\n    To import templates with update-binfmts, use :\n\n        sudo update-binfmts --importdir ${EXPORTDIR:-$DEBIANDIR} --import qemu-CPU\n\n    To remove interpreter, use :\n\n        sudo update-binfmts --package qemu-CPU --remove qemu-CPU $QEMU_PATH\n\n    With systemd, binfmt files are loaded by systemd-binfmt.service\n\n    The environment variable HOST_ARCH allows to override 'uname' to generate\n    configuration files for a different architecture than the current one.\n\n    where CPU is one of:\n\n        $qemu_target_list\n\nEOF\n}\n\nqemu_check_access() {\n    if [ ! -w \"$1\" ] ; then\n        echo \"ERROR: cannot write to $1\" 1>&2\n        exit 1\n    fi\n}\n\nqemu_check_bintfmt_misc() {\n    # load the binfmt_misc module\n    if [ ! -d /proc/sys/fs/binfmt_misc ]; then\n      if ! /sbin/modprobe binfmt_misc ; then\n          exit 1\n      fi\n    fi\n    if [ ! -f /proc/sys/fs/binfmt_misc/register ]; then\n      if ! mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc ; then\n          exit 1\n      fi\n    fi\n\n    qemu_check_access /proc/sys/fs/binfmt_misc/register\n}\n\ninstalled_dpkg() {\n    dpkg --status \"$1\" > /dev/null 2>&1\n}\n\nqemu_check_debian() {\n    if [ ! -e /etc/debian_version ] ; then\n        echo \"WARNING: your system is not a Debian based distro\" 1>&2\n    elif ! installed_dpkg binfmt-support ; then\n        echo \"WARNING: package binfmt-support is needed\" 1>&2\n    fi\n    qemu_check_access \"$EXPORTDIR\"\n}\n\nqemu_check_systemd() {\n    if ! systemctl -q is-enabled systemd-binfmt.service ; then\n        echo \"WARNING: systemd-binfmt.service is missing or disabled\" 1>&2\n    fi\n    qemu_check_access \"$EXPORTDIR\"\n}\n\nqemu_generate_register() {\n    flags=\"\"\n    if [ \"$CREDENTIAL\" = \"yes\" ] ; then\n        flags=\"OC\"\n    fi\n    if [ \"$PERSISTENT\" = \"yes\" ] ; then\n        flags=\"${flags}F\"\n    fi\n\n    echo \":qemu-$cpu:M::$magic:$mask:$qemu:$flags\"\n}\n\nqemu_register_interpreter() {\n    echo \"Setting $qemu as binfmt interpreter for $cpu\"\n    qemu_generate_register > /proc/sys/fs/binfmt_misc/register\n}\n\nqemu_generate_systemd() {\n    echo \"Setting $qemu as binfmt interpreter for $cpu for systemd-binfmt.service\"\n    qemu_generate_register > \"$EXPORTDIR/qemu-$cpu.conf\"\n}\n\nqemu_generate_debian() {\n    cat > \"$EXPORTDIR/qemu-$cpu\" <<EOF\npackage qemu-$cpu\ninterpreter $qemu\nmagic $magic\nmask $mask\ncredential $CREDENTIAL\nEOF\n}\n\nqemu_set_binfmts() {\n    # probe cpu type\n    host_family=$(qemu_get_family)\n\n    # register the interpreter for each cpu except for the native one\n\n    for cpu in ${qemu_target_list} ; do\n        magic=$(eval echo \\$${cpu}_magic)\n        mask=$(eval echo \\$${cpu}_mask)\n        family=$(eval echo \\$${cpu}_family)\n\n        if [ \"$magic\" = \"\" ] || [ \"$mask\" = \"\" ] || [ \"$family\" = \"\" ] ; then\n            echo \"INTERNAL ERROR: unknown cpu $cpu\" 1>&2\n            continue\n        fi\n\n        qemu=\"$QEMU_PATH/qemu-$cpu\"\n        if [ \"$cpu\" = \"i486\" ] ; then\n            qemu=\"$QEMU_PATH/qemu-i386\"\n        fi\n\n        qemu=\"$qemu$QEMU_SUFFIX\"\n        if [ \"$host_family\" != \"$family\" ] ; then\n            $BINFMT_SET\n        fi\n    done\n}\n\nCHECK=qemu_check_bintfmt_misc\nBINFMT_SET=qemu_register_interpreter\n\nSYSTEMDDIR=\"/etc/binfmt.d\"\nDEBIANDIR=\"/usr/share/binfmts\"\n\nQEMU_PATH=/usr/local/bin\nCREDENTIAL=no\nPERSISTENT=no\nQEMU_SUFFIX=\"\"\n\noptions=$(getopt -o ds:Q:S:e:hc:p: -l debian,systemd:,qemu-path:,qemu-suffix:,exportdir:,help,credential:,persistent: -- \"$@\")\neval set -- \"$options\"\n\nwhile true ; do\n    case \"$1\" in\n    -d|--debian)\n        CHECK=qemu_check_debian\n        BINFMT_SET=qemu_generate_debian\n        EXPORTDIR=${EXPORTDIR:-$DEBIANDIR}\n        ;;\n    -s|--systemd)\n        CHECK=qemu_check_systemd\n        BINFMT_SET=qemu_generate_systemd\n        EXPORTDIR=${EXPORTDIR:-$SYSTEMDDIR}\n        shift\n        # check given cpu is in the supported CPU list\n        if [ \"$1\" != \"ALL\" ] ; then\n            for cpu in ${qemu_target_list} ; do\n                if [ \"$cpu\" = \"$1\" ] ; then\n                    break\n                fi\n            done\n\n            if [ \"$cpu\" = \"$1\" ] ; then\n                qemu_target_list=\"$1\"\n            else\n                echo \"ERROR: unknown CPU \\\"$1\\\"\" 1>&2\n                usage\n                exit 1\n            fi\n        fi\n        ;;\n    -Q|--qemu-path)\n        shift\n        QEMU_PATH=\"$1\"\n        ;;\n    -F|--qemu-suffix)\n        shift\n        QEMU_SUFFIX=\"$1\"\n        ;;\n    -e|--exportdir)\n        shift\n        EXPORTDIR=\"$1\"\n        ;;\n    -h|--help)\n        usage\n        exit 1\n        ;;\n    -c|--credential)\n        shift\n        CREDENTIAL=\"$1\"\n        ;;\n    -p|--persistent)\n        shift\n        PERSISTENT=\"$1\"\n        ;;\n    *)\n        break\n        ;;\n    esac\n    shift\ndone\n\n$CHECK\nqemu_set_binfmts\n", "num_lines": 401}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nQEMU_BIN_DIR=${QEMU_BIN_DIR:-/usr/bin}\n\n\nif [ ! -d /proc/sys/fs/binfmt_misc ]; then\n    echo \"No binfmt support in the kernel.\"\n    echo \"  Try: '/sbin/modprobe binfmt_misc' from the host\"\n    exit 1\nfi\n\n\nif [ ! -f /proc/sys/fs/binfmt_misc/register ]; then\n    mount binfmt_misc -t binfmt_misc /proc/sys/fs/binfmt_misc\nfi\n\n\nif [ \"${1}\" = \"--reset\" ]; then\n    shift\n    find /proc/sys/fs/binfmt_misc -type f -name 'qemu-*' -exec sh -c 'echo -1 > {}' \\;\nfi\n\nexec $(dirname \"${BASH_SOURCE[0]}\")/qemu-binfmt-conf.sh --qemu-suffix \"-static\" --qemu-path=\"${QEMU_BIN_DIR}\" \"$@\"\n", "num_lines": 24}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Test the current package under a different kernel.\n# Requires virtme and qemu to be installed.\n\nset -eu\nset -o pipefail\n\nif [[ \"${1:-}\" = \"--in-vm\" ]]; then\n  shift\n\n  mount -t bpf bpf /sys/fs/bpf\n  mount -t tracefs tracefs /sys/kernel/debug/tracing\n  export CGO_ENABLED=0\n  export GOFLAGS=-mod=readonly\n  export GOPATH=/run/go-path\n  export GOPROXY=file:///run/go-path/pkg/mod/cache/download\n  export GOSUMDB=off\n  export GOCACHE=/run/go-cache\n\n  if [[ -d \"/run/input/bpf\" ]]; then\n    export KERNEL_SELFTESTS=\"/run/input/bpf\"\n  fi\n\n  readonly output=\"${1}\"\n  shift\n\n  echo Running tests...\n  go test -v -coverpkg=./... -coverprofile=\"$output/coverage.txt\" -count 1 ./...\n  touch \"$output/success\"\n  exit 0\nfi\n\n# Pull all dependencies, so that we can run tests without the\n# vm having network access.\ngo mod download\n\n# Use sudo if /dev/kvm isn't accessible by the current user.\nsudo=\"\"\nif [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then\n  sudo=\"sudo\"\nfi\nreadonly sudo\n\nreadonly kernel_version=\"${1:-}\"\nif [[ -z \"${kernel_version}\" ]]; then\n  echo \"Expecting kernel version as first argument\"\n  exit 1\nfi\n\nreadonly kernel=\"linux-${kernel_version}.bz\"\nreadonly selftests=\"linux-${kernel_version}-selftests-bpf.bz\"\nreadonly input=\"$(mktemp -d)\"\nreadonly output=\"$(mktemp -d)\"\nreadonly tmp_dir=\"${TMPDIR:-/tmp}\"\nreadonly branch=\"${BRANCH:-master}\"\n\nfetch() {\n    echo Fetching \"${1}\"\n    wget -nv -N -P \"${tmp_dir}\" \"https://github.com/cilium/ci-kernels/raw/${branch}/${1}\"\n}\n\nfetch \"${kernel}\"\n\nif fetch \"${selftests}\"; then\n  mkdir \"${input}/bpf\"\n  tar --strip-components=4 -xjf \"${tmp_dir}/${selftests}\" -C \"${input}/bpf\"\nelse\n  echo \"No selftests found, disabling\"\nfi\n\necho Testing on \"${kernel_version}\"\n$sudo virtme-run --kimg \"${tmp_dir}/${kernel}\" --memory 512M --pwd \\\n  --rw \\\n  --rwdir=/run/input=\"${input}\" \\\n  --rwdir=/run/output=\"${output}\" \\\n  --rodir=/run/go-path=\"$(go env GOPATH)\" \\\n  --rwdir=/run/go-cache=\"$(go env GOCACHE)\" \\\n  --script-sh \"PATH=\\\"$PATH\\\" $(realpath \"$0\") --in-vm /run/output\" \\\n  --qemu-opts -smp 2 # need at least two CPUs for some tests\n\nif [[ ! -e \"${output}/success\" ]]; then\n  echo \"Test failed on ${kernel_version}\"\n  exit 1\nelse\n  echo \"Test successful on ${kernel_version}\"\n  if [[ -v COVERALLS_TOKEN ]]; then\n    goveralls -coverprofile=\"${output}/coverage.txt\" -service=semaphore -repotoken \"$COVERALLS_TOKEN\"\n  fi\nfi\n\n$sudo rm -r \"${input}\"\n$sudo rm -r \"${output}\"\n", "num_lines": 93}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# for version in v1.9.1 v1.10.0 v1.10.3 v1.10.12 v1.11.2 v1.11.3 v1.12.0 v1.13.1 v1.14.0 v1.14.1 ; do\nfor version in v1.10.12 v1.14.1 v1.15.2 ; do\n    echo \"### $version\" > $version.txt\n    git checkout -- go.mod && git checkout $version && go test -run=NONE -bench=Benchmark2 >> $version.txt || exit 1\ndone\n", "num_lines": 8}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n\npushd \"$(dirname \"$0\")\" >/dev/null\n\n{\n  cat <<EOF\n/*\nCopyright (c) 2017 VMware, Inc. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\npackage simulator\n\n// GuestID is the list of valid types.VirtualMachineGuestOsIdentifier\nvar GuestID = []types.VirtualMachineGuestOsIdentifier{\nEOF\n\n  ids=($(grep 'VirtualMachineGuestOsIdentifier(' ../vim25/types/enum.go | grep = | awk '{print $1}'))\n  printf \"types.%s,\\n\" \"${ids[@]}\"\n\n  echo \"}\"\n} > guest_id.go\n\ngoimports -w guest_id.go\n", "num_lines": 36}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#\n# This script is used for\n# a) creating a new tagged release of go.opentelemetry.io/contrib\n# b) bumping the referenced version of go.opentelemetry.io/otel\n#\n# The options can be used together or individually.\n#\nset -e\n\ndeclare CONTRIB_TAG\ndeclare OTEL_TAG\n\nhelp() {\n   printf \"\\n\"\n   printf \"Usage: %s [-o otel_tag] [-t tag]\\n\" \"$0\"\n   printf \"\\t-o Otel release tag. Update all go.mod to reference go.opentelemetry.io/otel <otel_tag>.\\n\"\n   printf \"\\t-t New Contrib unreleased tag. Update all go.mod files with this tag.\\n\"\n   exit 1 # Exit script after printing help\n}\n\nwhile getopts \"t:o:\" opt\ndo\n   case \"$opt\" in\n      t ) CONTRIB_TAG=\"$OPTARG\" ;;\n      o ) OTEL_TAG=\"$OPTARG\" ;;\n      ? ) help ;; # Print help\n   esac\ndone\n\ndeclare -r SEMVER_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(\\\\-[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?(\\\\+[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?$\"\n\nvalidate_tag() {\n    local tag_=$1\n    if [[ \"${tag_}\" =~ ${SEMVER_REGEX} ]]; then\n\t    printf \"%s is valid semver tag.\\n\" \"${tag_}\"\n    else\n\t    printf \"%s is not a valid semver tag.\\n\" \"${tag_}\"\n\t    return 1\n    fi\n}\n\n# Print help in case parameters are empty\nif [[ -z \"$CONTRIB_TAG\" && -z \"$OTEL_TAG\" ]]\nthen\n    printf \"At least one of '-o' or '-t' must be specified.\\n\"\n    help\nfi\n\n\n## Validate tags first\nif [ -n \"${OTEL_TAG}\" ]; then\n    validate_tag \"${OTEL_TAG}\" || exit $?\n\n    # check that OTEL_TAG is a currently released tag for go.opentelemetry.io/otel\n    TMPDIR=$(mktemp -d \"/tmp/otel-contrib.XXXXXX\") || exit 1\n    trap \"rm -fr ${TMPDIR}\" EXIT\n    (cd \"${TMPDIR}\" && go mod init tagtest)\n    # requires go 1.14 for support of '-modfile'\n    if ! go get -modfile=\"${TMPDIR}/go.mod\" -d -v \"go.opentelemetry.io/otel@${OTEL_TAG}\"; then\n        printf \"go.opentelemetry.io/otel %s does not exist. Please supply a valid tag\\n\" \"${OTEL_TAG}\"\n        exit 1\n    fi\nfi\nif [ -n \"${CONTRIB_TAG}\" ]; then\n    validate_tag \"${CONTRIB_TAG}\" || exit $?\n    TAG_FOUND=$(git tag --list \"${CONTRIB_TAG}\")\n    if [[ ${TAG_FOUND} = \"${CONTRIB_TAG}\" ]] ; then\n        printf \"Tag %s already exists in this repo\\n\" \"${CONTRIB_TAG}\"\n        exit 1\n    fi\nelse\n    CONTRIB_TAG=${OTEL_TAG}  # if contrib_tag not specified, but OTEL_TAG is, then set it to OTEL_TAG\nfi\n\n# Get version for contrib.go\nOTEL_CONTRIB_VERSION=$(echo \"${CONTRIB_TAG}\" | egrep -o \"${SEMVER_REGEX}\")\n# Strip leading v\nOTEL_CONTRIB_VERSION=\"${OTEL_CONTRIB_VERSION#v}\"\n\ncd \"$(dirname \"$0\")\"\n\nif ! git diff --quiet; then \\\n    printf \"Working tree is not clean, can't proceed\\n\"\n    git status\n    git diff\n    exit 1\nfi\n\n# Update contrib.go version definition\ncp contrib.go contrib.go.bak\nsed \"s/\\(return \\\"\\)[0-9]*\\.[0-9]*\\.[0-9]*\\\"/\\1${OTEL_CONTRIB_VERSION}\\\"/\" ./contrib.go.bak > ./contrib.go\nrm -f ./contrib.go.bak\n\ndeclare -r BRANCH_NAME=pre_release_${CONTRIB_TAG}\n\npatch_gomods() {\n    local pkg_=$1\n    local tag_=$2\n    # now do the same for all the directories underneath\n    PACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; | egrep -v 'tools' | sed 's|^\\.\\/||' | sort)\n    # quote any '.' characters in the pkg name\n    local quoted_pkg_=${pkg_//./\\\\.}\n    for dir in $PACKAGE_DIRS; do\n\t    cp \"${dir}/go.mod\" \"${dir}/go.mod.bak\"\n\t    sed \"s|${quoted_pkg_}\\([^ ]*\\) v[0-9][0-9]*\\.[0-9][0-9]*\\.[0-9][0-9]*[^0-9]*.*$|${pkg_}\\1 ${tag_}|\" \"${dir}/go.mod.bak\" >\"${dir}/go.mod\"\n\t    rm -f \"${dir}/go.mod.bak\"\n    done\n}\n\n# branch off from existing main\ngit checkout -b \"${BRANCH_NAME}\" main\n\n# Update go.mods\nif [ -n \"${OTEL_TAG}\" ]; then\n    # first update the top most module\n    go get \"go.opentelemetry.io/otel@${OTEL_TAG}\"\n    patch_gomods go.opentelemetry.io/otel \"${OTEL_TAG}\"\nfi\n\nif [ -n \"${CONTRIB_TAG}\" ]; then\n    patch_gomods go.opentelemetry.io/contrib \"${CONTRIB_TAG}\"\nfi\n\ngit diff\n# Run lint to update go.sum\nmake lint\n\n# Add changes and commit.\ngit add .\nmake ci\n# Check whether registry links are up to date\nmake registry-links-check\n\ndeclare COMMIT_MSG=\"\"\nif [ -n \"${OTEL_TAG}\" ]; then\n    COMMIT_MSG+=\"Bumping otel version to ${OTEL_TAG}\"\nfi\nCOMMIT_MSG+=\".  Prepare for releasing ${CONTRIB_TAG}\"\ngit commit -m \"${COMMIT_MSG}\"\n\nprintf \"Now run following to verify the changes.\\ngit diff main\\n\"\nprintf \"\\nThen push the changes to upstream\\n\"\n", "num_lines": 159}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nreadonly PROGNAME=$(basename \"$0\")\nreadonly PROGDIR=$(readlink -m \"$(dirname \"$0\")\")\n\nreadonly EXCLUDE_PACKAGES=\"tools\"\nreadonly SEMVER_REGEX=\"v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(\\\\-[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?(\\\\+[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?\"\n\nusage() {\n    cat <<- EOF\nUsage: $PROGNAME [OPTIONS] SEMVER_TAG COMMIT_HASH\n\nCreates git tag for all Go packages in project.\n\nOPTIONS:\n  -h --help        Show this help.\n\nARGUMENTS:\n  SEMVER_TAG       Semantic version to tag with.\n  COMMIT_HASH      Git commit hash to tag.\nEOF\n}\n\ncmdline() {\n    local arg commit\n\n    for arg\n    do\n        local delim=\"\"\n        case \"$arg\" in\n            # Translate long form options to short form.\n            --help)           args=\"${args}-h \";;\n            # Pass through for everything else.\n            *) [[ \"${arg:0:1}\" == \"-\" ]] || delim=\"\\\"\"\n                args=\"${args}${delim}${arg}${delim} \";;\n        esac\n    done\n\n    # Reset and process short form options.\n    eval set -- \"$args\"\n\n    while getopts \"h\" OPTION\n    do\n         case $OPTION in\n         h)\n             usage\n             exit 0\n             ;;\n         *)\n             echo \"unknown option: $OPTION\"\n             usage\n             exit 1\n             ;;\n        esac\n    done\n\n    # Positional arguments.\n    shift $((OPTIND-1))\n    readonly TAG=\"$1\"\n    if [ -z \"$TAG\" ]\n    then\n        echo \"missing SEMVER_TAG\"\n        usage\n        exit 1\n    fi\n    if [[ ! \"$TAG\" =~ $SEMVER_REGEX ]]\n    then\n        printf \"invalid semantic version: %s\\n\" \"$TAG\"\n        exit 2\n    fi\n    if [[ \"$( git tag --list \"$TAG\" )\" ]]\n    then\n        printf \"tag already exists: %s\\n\" \"$TAG\"\n        exit 2\n    fi\n\n    shift\n    commit=\"$1\"\n    if [ -z \"$commit\" ]\n    then\n        echo \"missing COMMIT_HASH\"\n        usage\n        exit 1\n    fi\n    # Verify rev is for a commit and unify hashes into a complete SHA1.\n    readonly SHA=\"$( git rev-parse --quiet --verify \"${commit}^{commit}\" )\"\n    if [ -z \"$SHA\" ]\n    then\n        printf \"invalid commit hash: %s\\n\" \"$commit\"\n        exit 2\n    fi\n    if [ \"$( git merge-base \"$SHA\" HEAD )\" != \"$SHA\" ]\n    then\n        printf \"commit '%s' not found on this branch\\n\" \"$commit\"\n        exit 2\n    fi\n}\n\npackage_dirs() {\n    # Return a list of package directories in the form:\n    #\n    #  package/directory/a\n    #  package/directory/b\n    #  deeper/package/directory/a\n    #  ...\n    #\n    # Making sure to exclude any packages in the EXCLUDE_PACKAGES regexp.\n    find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; \\\n        | grep -E -v \"$EXCLUDE_PACKAGES\" \\\n        | sed 's/^\\.\\///' \\\n        | sort\n}\n\ngit_tag() {\n    local tag=\"$1\"\n    local commit=\"$2\"\n\n    git tag -a \"$tag\" -s -m \"Version $tag\" \"$commit\"\n}\n\nprevious_version() {\n    local current=\"$1\"\n\n    # Requires git > 2.0\n    git tag -l --sort=v:refname \\\n        | grep -E \"^${SEMVER_REGEX}$\" \\\n        | grep -v \"$current\" \\\n        | tail -1\n}\n\nprint_changes() {\n    local tag=\"$1\"\n    local previous\n\n    previous=\"$( previous_version \"$tag\" )\"\n    if [ -n \"$previous\" ]\n    then\n        printf \"\\nRaw changes made between %s and %s\\n\" \"$previous\" \"$tag\"\n        printf \"======================================\\n\"\n        git --no-pager log --pretty=oneline \"${previous}..$tag\"\n    fi\n}\n\nmain() {\n    local dir\n\n    cmdline \"$@\"\n\n    cd \"$PROGDIR\" || exit 3\n\n    # Create tag for root package.\n    git_tag \"$TAG\" \"$SHA\"\n    printf \"created tag: %s\\n\" \"$TAG\"\n\n    # Create tag for all sub-packages.\n    for dir in $( package_dirs )\n    do\n        git_tag \"${dir}/$TAG\" \"$SHA\"\n        printf \"created tag: %s\\n\" \"${dir}/$TAG\"\n    done\n\n    print_changes \"$TAG\"\n}\nmain \"$@\"\n", "num_lines": 179}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ntop_dir='.'\nif [[ $# -gt 0 ]]; then\n    top_dir=\"${1}\"\nfi\n\np=$(pwd)\nmod_dirs=()\n\n# Note `mapfile` does not exist in older bash versions:\n# https://stackoverflow.com/questions/41475261/need-alternative-to-readarray-mapfile-for-script-on-older-version-of-bash\n\nwhile IFS= read -r line; do\n    mod_dirs+=(\"$line\")\ndone < <(find \"${top_dir}\" -type f -name 'go.mod' -exec dirname {} \\; | sort)\n\nfor mod_dir in \"${mod_dirs[@]}\"; do\n    cd \"${mod_dir}\"\n\n    while IFS= read -r line; do\n        echo \".${line#${p}}\"\n    done < <(go list --find -f '{{.Name}}|{{.Dir}}' ./... | grep '^main|' | cut -f 2- -d '|')\n    cd \"${p}\"\ndone\n", "num_lines": 42}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nhelp()\n{\n   printf \"\\n\"\n   printf \"Usage: $0 -t tag\\n\"\n   printf \"\\t-t Unreleased tag. Update all go.mod with this tag.\\n\"\n   exit 1 # Exit script after printing help\n}\n\nwhile getopts \"t:\" opt\ndo\n   case \"$opt\" in\n      t ) TAG=\"$OPTARG\" ;;\n      ? ) help ;; # Print help\n   esac\ndone\n\n# Print help in case parameters are empty\nif [ -z \"$TAG\" ]\nthen\n   printf \"Tag is missing\\n\";\n   help\nfi\n\n# Validate semver\nSEMVER_REGEX=\"^v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(\\\\-[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?(\\\\+[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?$\"\nif [[ \"${TAG}\" =~ ${SEMVER_REGEX} ]]; then\n\tprintf \"${TAG} is valid semver tag.\\n\"\nelse\n\tprintf \"${TAG} is not a valid semver tag.\\n\"\n\texit -1\nfi\n\nTAG_FOUND=`git tag --list ${TAG}`\nif [[ ${TAG_FOUND} = ${TAG} ]] ; then\n        printf \"Tag ${TAG} already exists\\n\"\n        exit -1\nfi\n\n# Get version for version.go\nOTEL_VERSION=$(echo \"${TAG}\" | grep -o '^v[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+')\n# Strip leading v\nOTEL_VERSION=\"${OTEL_VERSION#v}\"\n\ncd $(dirname $0)\n\nif ! git diff --quiet; then \\\n\tprintf \"Working tree is not clean, can't proceed with the release process\\n\"\n\tgit status\n\tgit diff\n\texit 1\nfi\n\n# Update version.go\ncp ./version.go ./version.go.bak\nsed \"s/\\(return \\\"\\)[0-9]*\\.[0-9]*\\.[0-9]*\\\"/\\1${OTEL_VERSION}\\\"/\" ./version.go.bak >./version.go\nrm -f ./version.go.bak\n\n# Update go.mod\ngit checkout -b pre_release_${TAG} main\nPACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; | egrep -v 'tools' | sed 's/^\\.\\///' | sort)\n\nfor dir in $PACKAGE_DIRS; do\n\tcp \"${dir}/go.mod\" \"${dir}/go.mod.bak\"\n\tsed \"s/opentelemetry.io\\/otel\\([^ ]*\\) v[0-9]*\\.[0-9]*\\.[0-9]/opentelemetry.io\\/otel\\1 ${TAG}/\" \"${dir}/go.mod.bak\" >\"${dir}/go.mod\"\n\trm -f \"${dir}/go.mod.bak\"\ndone\n\n# Run lint to update go.sum\nmake lint\n\n# Add changes and commit.\ngit add .\nmake ci\ngit commit -m \"Prepare for releasing $TAG\"\n\nprintf \"Now run following to verify the changes.\\ngit diff main\\n\"\nprintf \"\\nThen push the changes to upstream\\n\"\n", "num_lines": 96}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nreadonly PROGNAME=$(basename \"$0\")\nreadonly PROGDIR=$(readlink -m \"$(dirname \"$0\")\")\n\nreadonly EXCLUDE_PACKAGES=\"internal/tools\"\nreadonly SEMVER_REGEX=\"v(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)\\\\.(0|[1-9][0-9]*)(\\\\-[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?(\\\\+[0-9A-Za-z-]+(\\\\.[0-9A-Za-z-]+)*)?\"\n\nusage() {\n    cat <<- EOF\nUsage: $PROGNAME [OPTIONS] SEMVER_TAG COMMIT_HASH\n\nCreates git tag for all Go packages in project.\n\nOPTIONS:\n  -h --help        Show this help.\n\nARGUMENTS:\n  SEMVER_TAG       Semantic version to tag with.\n  COMMIT_HASH      Git commit hash to tag.\nEOF\n}\n\ncmdline() {\n    local arg commit\n\n    for arg\n    do\n        local delim=\"\"\n        case \"$arg\" in\n            # Translate long form options to short form.\n            --help)           args=\"${args}-h \";;\n            # Pass through for everything else.\n            *) [[ \"${arg:0:1}\" == \"-\" ]] || delim=\"\\\"\"\n                args=\"${args}${delim}${arg}${delim} \";;\n        esac\n    done\n\n    # Reset and process short form options.\n    eval set -- \"$args\"\n\n    while getopts \"h\" OPTION\n    do\n         case $OPTION in\n         h)\n             usage\n             exit 0\n             ;;\n         *)\n             echo \"unknown option: $OPTION\"\n             usage\n             exit 1\n             ;;\n        esac\n    done\n\n    # Positional arguments.\n    shift $((OPTIND-1))\n    readonly TAG=\"$1\"\n    if [ -z \"$TAG\" ]\n    then\n        echo \"missing SEMVER_TAG\"\n        usage\n        exit 1\n    fi\n    if [[ ! \"$TAG\" =~ $SEMVER_REGEX ]]\n    then\n        printf \"invalid semantic version: %s\\n\" \"$TAG\"\n        exit 2\n    fi\n    if [[ \"$( git tag --list \"$TAG\" )\" ]]\n    then\n        printf \"tag already exists: %s\\n\" \"$TAG\"\n        exit 2\n    fi\n\n    shift\n    commit=\"$1\"\n    if [ -z \"$commit\" ]\n    then\n        echo \"missing COMMIT_HASH\"\n        usage\n        exit 1\n    fi\n    # Verify rev is for a commit and unify hashes into a complete SHA1.\n    readonly SHA=\"$( git rev-parse --quiet --verify \"${commit}^{commit}\" )\"\n    if [ -z \"$SHA\" ]\n    then\n        printf \"invalid commit hash: %s\\n\" \"$commit\"\n        exit 2\n    fi\n    if [ \"$( git merge-base \"$SHA\" HEAD )\" != \"$SHA\" ]\n    then\n        printf \"commit '%s' not found on this branch\\n\" \"$commit\"\n        exit 2\n    fi\n}\n\npackage_dirs() {\n    # Return a list of package directories in the form:\n    #\n    #  package/directory/a\n    #  package/directory/b\n    #  deeper/package/directory/a\n    #  ...\n    #\n    # Making sure to exclude any packages in the EXCLUDE_PACKAGES regexp.\n    find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; \\\n        | grep -E -v \"$EXCLUDE_PACKAGES\" \\\n        | sed 's/^\\.\\///' \\\n        | sort\n}\n\ngit_tag() {\n    local tag=\"$1\"\n    local commit=\"$2\"\n\n    git tag -a \"$tag\" -s -m \"Version $tag\" \"$commit\"\n}\n\nprevious_version() {\n    local current=\"$1\"\n\n    # Requires git > 2.0\n    git tag -l --sort=v:refname \\\n        | grep -E \"^${SEMVER_REGEX}$\" \\\n        | grep -v \"$current\" \\\n        | tail -1\n}\n\nprint_changes() {\n    local tag=\"$1\"\n    local previous\n\n    previous=\"$( previous_version \"$tag\" )\"\n    if [ -n \"$previous\" ]\n    then\n        printf \"\\nRaw changes made between %s and %s\\n\" \"$previous\" \"$tag\"\n        printf \"======================================\\n\"\n        git --no-pager log --pretty=oneline \"${previous}..$tag\"\n    fi\n}\n\nmain() {\n    local dir\n\n    cmdline \"$@\"\n\n    cd \"$PROGDIR\" || exit 3\n\n    # Create tag for root package.\n    git_tag \"$TAG\" \"$SHA\"\n    printf \"created tag: %s\\n\" \"$TAG\"\n\n    # Create tag for all sub-packages.\n    for dir in $( package_dirs )\n    do\n        git_tag \"${dir}/$TAG\" \"$SHA\"\n        printf \"created tag: %s\\n\" \"${dir}/$TAG\"\n    done\n\n    print_changes \"$TAG\"\n}\nmain \"$@\"\n", "num_lines": 179}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ncd $(dirname $0)\nTOOLS_DIR=$(pwd)/.tools\n\nif [ -z \"${GOPATH}\" ] ; then\n\tprintf \"GOPATH is not defined.\\n\"\n\texit -1\nfi\n\nif [ ! -d \"${GOPATH}\" ] ; then\n\tprintf \"GOPATH ${GOPATH} is invalid \\n\"\n\texit -1\nfi\n\n# Pre-requisites\nif ! git diff --quiet; then \\\n\tgit status\n\tprintf \"\\n\\nError: working tree is not clean\\n\"\n\texit -1\nfi\n\nif [ \"$(git tag --contains $(git log -1 --pretty=format:\"%H\"))\" = \"\" ] ; then\n\tprintf \"$(git log -1)\"\n\tprintf \"\\n\\nError: HEAD is not pointing to a tagged version\"\nfi\n\nmake ${TOOLS_DIR}/gojq\n\nDIR_TMP=\"${GOPATH}/src/oteltmp/\"\nrm -rf $DIR_TMP\nmkdir -p $DIR_TMP\n\nprintf \"Copy examples to ${DIR_TMP}\\n\"\ncp -a ./example ${DIR_TMP}\n\n# Update go.mod files\nprintf \"Update go.mod: rename module and remove replace\\n\"\n\nPACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; | egrep 'example' | sed 's/^\\.\\///' | sort)\n\nfor dir in $PACKAGE_DIRS; do\n\tprintf \"  Update go.mod for $dir\\n\"\n\t(cd \"${DIR_TMP}/${dir}\" && \\\n\t # replaces is (\"mod1\" \"mod2\" \u00e2\u20ac\u00a6)\n\t replaces=($(go mod edit -json | ${TOOLS_DIR}/gojq '.Replace[].Old.Path')) && \\\n\t # strip double quotes\n\t replaces=(\"${replaces[@]%\\\"}\") && \\\n\t replaces=(\"${replaces[@]#\\\"}\") && \\\n\t # make an array (-dropreplace=mod1 -dropreplace=mod2 \u00e2\u20ac\u00a6)\n\t dropreplaces=(\"${replaces[@]/#/-dropreplace=}\") && \\\n\t go mod edit -module \"oteltmp/${dir}\" \"${dropreplaces[@]}\" && \\\n\t go mod tidy)\ndone\nprintf \"Update done:\\n\\n\"\n\n# Build directories that contain main package. These directories are different than\n# directories that contain go.mod files.\nprintf \"Build examples:\\n\"\nEXAMPLES=$(./get_main_pkgs.sh ./example)\nfor ex in $EXAMPLES; do\n\tprintf \"  Build $ex in ${DIR_TMP}/${ex}\\n\"\n\t(cd \"${DIR_TMP}/${ex}\" && \\\n\t go build .)\ndone\n\n# Cleanup\nprintf \"Remove copied files.\\n\"\nrm -rf $DIR_TMP\n", "num_lines": 86}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nERROR_COUNT=0\nwhile read -r file\ndo\n\tcase \"$(head -1 \"${file}\")\" in\n\t\t*\"Copyright (c) \"*\" Uber Technologies, Inc.\")\n\t\t\t# everything's cool\n\t\t\t;;\n\t\t*)\n\t\t\techo \"$file is missing license header.\"\n\t\t\t(( ERROR_COUNT++ ))\n\t\t\t;;\n\tesac\ndone < <(git ls-files \"*\\.go\")\n\nexit $ERROR_COUNT\n", "num_lines": 18}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"darwin\" ]; then\n\t\t\t        # 1.12 and later, syscalls via libSystem\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\t\t# 1.13 and later, syscalls via libSystem (including syscallPtr)\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go\";\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOARCH\"; fi\n) | $run\n", "num_lines": 232}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/icmp.h>\n#include <linux/icmpv6.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 !~ /^EV_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 760}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=$(mktemp -d /tmp/sdk.XXX) \\\n&& curl -o $TMP.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\" \\\n&& unzip -q $TMP.zip -d $TMP \\\n&& export PATH=\"$PATH:$TMP/go_appengine\"", "num_lines": 6}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu -o pipefail\n\nWORKDIR=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$WORKDIR\"\n}\ntrap finish EXIT\n\nexport GOBIN=${WORKDIR}/bin\nexport PATH=${GOBIN}:${PATH}\nmkdir -p ${GOBIN}\n\necho \"remove existing generated files\"\n# grpc_testingv3/testv3.pb.go is not re-generated because it was\n# intentionally generated by an older version of protoc-gen-go.\nrm -f $(find . -name '*.pb.go' | grep -v 'grpc_testingv3/testv3.pb.go')\n\necho \"go install google.golang.org/protobuf/cmd/protoc-gen-go\"\n(cd test/tools && go install google.golang.org/protobuf/cmd/protoc-gen-go)\n\necho \"go install cmd/protoc-gen-go-grpc\"\n(cd cmd/protoc-gen-go-grpc && go install .)\n\necho \"git clone https://github.com/grpc/grpc-proto\"\ngit clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto\n\necho \"git clone https://github.com/protocolbuffers/protobuf\"\ngit clone --quiet https://github.com/protocolbuffers/protobuf ${WORKDIR}/protobuf\n\n# Pull in code.proto as a proto dependency\nmkdir -p ${WORKDIR}/googleapis/google/rpc\necho \"curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto\"\ncurl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto\n\nmkdir -p ${WORKDIR}/out\n\n# Generates sources without the embed requirement\nLEGACY_SOURCES=(\n  ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto\n  ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto\n  ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto\n  ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto\n  profiling/proto/service.proto\n  reflection/grpc_reflection_v1alpha/reflection.proto\n)\n\n# Generates only the new gRPC Service symbols\nSOURCES=(\n  $(git ls-files --exclude-standard --cached --others \"*.proto\" | grep -v '^\\(profiling/proto/service.proto\\|reflection/grpc_reflection_v1alpha/reflection.proto\\)$')\n  ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto\n  ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto\n  ${WORKDIR}/grpc-proto/grpc/testing/*.proto\n  ${WORKDIR}/grpc-proto/grpc/core/*.proto\n)\n\n# These options of the form 'Mfoo.proto=bar' instruct the codegen to use an\n# import path of 'bar' in the generated code when 'foo.proto' is imported in\n# one of the sources.\nOPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config,Mgrpc/core/stats.proto=google.golang.org/grpc/interop/grpc_testing/core\n\nfor src in ${SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    -I${WORKDIR}/istio \\\n    ${src}\ndone\n\nfor src in ${LEGACY_SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},require_unimplemented_servers=false:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    -I${WORKDIR}/istio \\\n    ${src}\ndone\n\n# The go_package option in grpc/lookup/v1/rls.proto doesn't match the\n# current location. Move it into the right place.\nmkdir -p ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\nmv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\n\n# grpc_testingv3/testv3.pb.go is not re-generated because it was\n# intentionally generated by an older version of protoc-gen-go.\nrm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testingv3/*.pb.go\n\n# grpc/service_config/service_config.proto does not have a go_package option.\nmv ${WORKDIR}/out/grpc/service_config/service_config.pb.go internal/proto/grpc_service_config\n\n# grpc/testing does not have a go_package option.\nmv ${WORKDIR}/out/grpc/testing/*.pb.go interop/grpc_testing/\nmv ${WORKDIR}/out/grpc/core/*.pb.go interop/grpc_testing/core/\n\ncp -R ${WORKDIR}/out/google.golang.org/grpc/* .\n", "num_lines": 120}
{"repo_name": "kubernetes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\n# not makes sure the command passed to it does not exit with a return code of 0.\nnot() {\n  # This is required instead of the earlier (! $COMMAND) because subshells and\n  # pipefail don't work the same on Darwin as in Linux.\n  ! \"$@\"\n}\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | not read\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${HOME}/go/bin:${GOROOT}/bin:${PATH}\"\ngo version\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Check for module support\n  if go help mod >& /dev/null; then\n    # Install the pinned versions as defined in module tools.\n    pushd ./test/tools\n    go install \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell\n    popd\n  else\n    # Ye olde `go get` incantation.\n    # Note: this gets the latest version of all tools (vs. the pinned versions\n    # with Go modules).\n    go get -u \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell\n  fi\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif [[ \"${GITHUB_ACTIONS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/runner/go\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif not which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\nnot git grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" -- '*.go'\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\nnot grep 'func Test[^(]' *_test.go\nnot grep 'func Test[^(]' test/*.go\n\n# - Do not import x/net/context.\nnot git grep -l 'x/net/context' -- \"*.go\"\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit grep -l '\"math/rand\"' -- \"*.go\" 2>&1 | not grep -v '^examples\\|^stress\\|grpcrand\\|^benchmark\\|wrr_test'\n\n# - Do not call grpclog directly. Use grpclog.Component instead.\ngit grep -l 'grpclog.I\\|grpclog.W\\|grpclog.E\\|grpclog.F\\|grpclog.V' -- \"*.go\" | not grep -v '^grpclog/component.go\\|^internal/grpctest/tlogger_test.go'\n\n# - Ensure all ptypes proto packages are renamed when importing.\nnot git grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\" -- \"*.go\"\n\n# - Ensure all xds proto imports are renamed to *pb or *grpc.\ngit grep '\"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*.pb.go' | not grep -v 'pb \"\\|grpc \"'\n\n# - Check imports that are illegal in appengine (until Go 1.11).\n# TODO: Remove when we drop Go 1.10 support\ngo list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go\n\nmisspell -error .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet,\n# go mod tidy.\n# Perform these checks on each module inside gRPC.\nfor MOD_FILE in $(find . -name 'go.mod'); do\n  MOD_DIR=$(dirname ${MOD_FILE})\n  pushd ${MOD_DIR}\n  go vet -all ./... | fail_on_output\n  gofmt -s -d -l . 2>&1 | fail_on_output\n  goimports -l . 2>&1 | not grep -vE \"\\.pb\\.go\"\n  golint ./... 2>&1 | not grep -vE \"/testv3\\.pb\\.go:\"\n\n  go mod tidy\n  git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\n  popd\ndone\n\n# - Collection of static analysis checks\n#\n# TODO(dfawley): don't use deprecated functions in examples or first-party\n# plugins.\nSC_OUT=\"$(mktemp)\"\nstaticcheck -go 1.9 -checks 'inherit,-ST1015' ./... > \"${SC_OUT}\" || true\n# Error if anything other than deprecation warnings are printed.\nnot grep -v \"is deprecated:.*SA1019\" \"${SC_OUT}\"\n# Only ignore the following deprecated types/fields/functions.\nnot grep -Fv '.CredsBundle\n.HeaderMap\n.Metadata is deprecated: use Attributes\n.NewAddress\n.NewServiceConfig\n.Type is deprecated: use Attributes\nBuildVersion is deprecated\nbalancer.ErrTransientFailure\nbalancer.Picker\nextDesc.Filename is deprecated\ngithub.com/golang/protobuf/jsonpb is deprecated\ngrpc.CallCustomCodec\ngrpc.Code\ngrpc.Compressor\ngrpc.CustomCodec\ngrpc.Decompressor\ngrpc.MaxMsgSize\ngrpc.MethodConfig\ngrpc.NewGZIPCompressor\ngrpc.NewGZIPDecompressor\ngrpc.RPCCompressor\ngrpc.RPCDecompressor\ngrpc.ServiceConfig\ngrpc.WithBalancerName\ngrpc.WithCompressor\ngrpc.WithDecompressor\ngrpc.WithDialer\ngrpc.WithMaxMsgSize\ngrpc.WithServiceConfig\ngrpc.WithTimeout\nhttp.CloseNotifier\ninfo.SecurityVersion\nproto is deprecated\nproto.InternalMessageInfo is deprecated\nproto.EnumName is deprecated\nproto.ErrInternalBadWireType is deprecated\nproto.FileDescriptor is deprecated\nproto.Marshaler is deprecated\nproto.MessageType is deprecated\nproto.RegisterEnum is deprecated\nproto.RegisterFile is deprecated\nproto.RegisterType is deprecated\nproto.RegisterExtension is deprecated\nproto.RegisteredExtension is deprecated\nproto.RegisteredExtensions is deprecated\nproto.RegisterMapType is deprecated\nproto.Unmarshaler is deprecated\nresolver.Backend\nresolver.GRPCLB\nTarget is deprecated: Use the Target field in the BuildOptions instead.\nxxx_messageInfo_\n' \"${SC_OUT}\"\n\n# - special golint on package comments.\nlint_package_comment_per_package() {\n  # Number of files in this go package.\n  fileCount=$(go list -f '{{len .GoFiles}}' $1)\n  if [ ${fileCount} -eq 0 ]; then\n    return 0\n  fi\n  # Number of package errors generated by golint.\n  lintPackageCommentErrorsCount=$(golint --min_confidence 0 $1 | grep -c \"should have a package comment\")\n  # golint complains about every file that's missing the package comment. If the\n  # number of files for this package is greater than the number of errors, there's\n  # at least one file with package comment, good. Otherwise, fail.\n  if [ ${fileCount} -le ${lintPackageCommentErrorsCount} ]; then\n    echo \"Package $1 (with ${fileCount} files) is missing package comment\"\n    return 1\n  fi\n}\nlint_package_comment() {\n  set +ex\n\n  count=0\n  for i in $(go list ./...); do\n    lint_package_comment_per_package \"$i\"\n    ((count += $?))\n  done\n\n  set -ex\n  return $count\n}\nlint_package_comment\n\necho SUCCESS\n", "num_lines": 228}
{"repo_name": "lean-gym", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# run from project root\n\nleanpkg configure\nbash ./_target/deps/mathlib/scripts/mk_all.sh\nleanproject get-mathlib-cache\nleanpkg build\n", "num_lines": 9}
{"repo_name": "lean-gym", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# run from project root\n\nrm -rf leanpkg.path\nrm -rf _target\n\ncp leanpkg_mathlib.toml leanpkg.toml\nleanpkg configure\nbash ./_target/deps/mathlib/scripts/mk_all.sh\nleanproject get-mathlib-cache\nleanpkg build\n", "num_lines": 13}
{"repo_name": "lean-gym", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# run from project root\n\nrm -rf leanpkg.path\nrm -rf _target\n\ncp leanpkg_miniF2F.toml leanpkg.toml\nleanpkg configure\nbash ./_target/deps/mathlib/scripts/mk_all.sh\n\nmv ./_target/deps/mathlib/src/all.lean ./_target/deps/minif2f/lean/src/all.lean\necho \"import test\" >> ./_target/deps/minif2f/lean/src/all.lean\necho \"import valid\" >> ./_target/deps/minif2f/lean/src/all.lean\n\nleanproject get-mathlib-cache\nleanpkg build\n", "num_lines": 18}
{"repo_name": "lucid", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Config\nMODEL_NAME=\"VGG_ILSVRC_16_layers\"\nPROTO_URL=\"https://gist.githubusercontent.com/ksimonyan/211839e770f7b538e2d8/raw/ded9363bd93ec0c770134f4e387d8aaaaa2407ce/VGG_ILSVRC_16_layers_deploy.prototxt\"\nCAFFE_URL=\"http://www.robots.ox.ac.uk/~vgg/software/very_deep/caffe/VGG_ILSVRC_16_layers.caffemodel\"\n\n# Enter virtualenv (for old TF version, etc)\ncd workspace/\n. bin/activate\n\n# Fetch caffe model files\necho \"\"\necho \"----------------------------------------\"\necho \"Fetching models\"\necho \"----------------------------------------\"\ncurl -sS ${PROTO_URL} --output ${MODEL_NAME}.prototxt\ncurl -sS ${CAFFE_URL} --output ${MODEL_NAME}.caffemodel\n  \n# Upgrade prototxt, in case it's for an old unsupported version of caffe.\necho \"\"\necho \"----------------------------------------\"\necho \"Attempting to upgrade proto file format\"\necho \"----------------------------------------\"\nupgrade_net_proto_text ${MODEL_NAME}.prototxt ${MODEL_NAME}_upgraded.prototxt\n\n# caffe-tensorflow will fail if .tmp/ already exists\nrm -rf .tmp/\n\n# Run caffe-tensorflow conversion script\necho \"\"\necho \"----------------------------------------\"\necho \"Attempting to convert to tensorflow\"\necho \"----------------------------------------\"\npython caffe-tensorflow/convert.py           \\\n  --caffemodel ${MODEL_NAME}.caffemodel      \\\n  --standalone-output-path ${MODEL_NAME}.pb  \\\n  ${MODEL_NAME}_upgraded.prototxt\n\necho \"Frozen tensflow graph:\"\necho \"  workspace/${MODEL_NAME}.pb\"\n", "num_lines": 42}
{"repo_name": "lucid", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# Run this script once to create the workspace for us to export models\n# from caffe. This is necessary because caffe-tensorflow needs old tf versions.\n\n# Create and enter virtualenv\nvirtualenv workspace\ncd workspace\n. bin/activate\n\n# Install virtualenv dependencies\npip install tensorflow==1.2\ngit clone https://github.com/linkfluence/caffe-tensorflow\n", "num_lines": 13}
{"repo_name": "lucid", "repo_creator": "openai", "programming_language": "Shell", "code": "\n# Extract list of urls for checkpoints\ncat slim_readme_table.md          \\\n  | sed \"s/[|\\\\(\\\\)]/\\n/g\"        \\\n  | grep download.tensorflow.org  \\\n  > url_list.txt\n\n# Create proposed list of model names (will need to be modified)\ncat url_list.txt                                      \\\n  | sed \"s/\\\\//\\n/g\"                                  \\\n  | grep \"gz$\"                                        \\\n  | sed \"s/_201[0-9]_[0-9][0-9]_[0-9][0-9].tar.gz//g\" \\\n  | sed \"s/_[0-9][0-9]_[0-9][0-9]_201[0-9].tar.gz//g\" \\\n  > names.txt\n\n# TODO - make sure to sanity check the output of this script before\n# running the next one.\n", "num_lines": 18}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# NOTE: Please avoid bashisms (bash specific syntax) in this script\n\nset -e\npw=\"$PWD\"\nfor dir in libcfs lnet lustre snmp ; do\n\tACLOCAL_FLAGS=\"$ACLOCAL_FLAGS -I $pw/$dir/autoconf\"\ndone\n\nlibtoolize -q\naclocal -I $pw/config $ACLOCAL_FLAGS\nautoheader\nautomake -a -c\nautoconf\n", "num_lines": 16}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# $1 : $module\n# $2 : $module_version\n# $3 : $kernelver\n# $4 : $kernel_source_dir\n# $5 : $arch\n# $6 : $source_tree\n# $7 : $dkms_tree\n#\n# This script ensure that ALL Lustre kernel modules that have been built\n# during DKMS build step of lustre[-client]-dkms module will be moved in\n# DKMS vault/repository, and this before the build directory content will be\n# trashed.\n# This is required because dkms.conf file is only sourced at the very\n# beginning of the DKMS build step when its content has to be on-target\n# customized during pre_build script. This can lead to incomplete list\n# of built Lustre kernel modules then to be saved for next DKMS install step.\n\n# Use this place to also save config.log that has been generated during\n# pre_build.\n# $7/$1/$2/$3/$5/log repository should have already been created to save\n# make.log and $kernel_config\nmkdir -p \"$7/$1/$2/$3/$5/log\"\ncp -f \"$7/$1/$2/build/config.log\" \"$7/$1/$2/$3/$5/log/config.log\" 2>/dev/null\ncp -f \"$7/$1/$2/build/config.h\" \\\n    \"$7/$1/$2/build/Module.symvers\" \\\n    \"$7/$1/$2/$3/$5/\" 2> /dev/null\n", "num_lines": 28}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# $1 : $module\n# $2 : $module_version\n# $3 : $kernelver\n# $4 : $kernel_source_dir\n# $5 : $arch\n# $6 : $source_tree\n# $7 : $dkms_tree\n\ncase $1 in\n    lustre-client)\n\tSERVER=\"--disable-server\"\n\tKERNEL_STUFF=\"\"\n\t;;\n\n    lustre-zfs|lustre-all)\n\tLDISKFS=\"\"\n\tif [ \"$1\" == \"lustre-zfs\" ]; then\n\t    LDISKFS=\"--disable-ldiskfs\"\n\tfi\n\n\t# ZFS and SPL are version locked\n\tZFS_VERSION=$(dkms status -m zfs -k $3 -a $5 | awk -F', ' '{print $2; exit 0}' | grep -v ': added$')\n\tif [ -z $ZFS_VERSION ] ; then\n\t\techo \"zfs-dkms package must already be installed and built under DKMS control\"\n\t\texit 1\n\tfi\n\n\tSERVER=\"--enable-server $LDISKFS \\\n\t\t--with-linux=$4 --with-linux-obj=$4 \\\n\t\t--with-spl=$6/spl-${ZFS_VERSION} \\\n\t\t--with-spl-obj=$7/spl/${ZFS_VERSION}/$3/$5 \\\n\t\t--with-zfs=$6/zfs-${ZFS_VERSION} \\\n\t\t--with-zfs-obj=$7/zfs/${ZFS_VERSION}/$3/$5\"\n\n\tKERNEL_STUFF=\"--with-linux=$4 --with-linux-obj=$4\"\n\t;;\n\n    lustre-ldiskfs)\n\tSERVER=\"--enable-server --without-zfs --without-spl \\\n\t\t--with-linux=$4 --with-linux-obj=$4\"\n\n\tKERNEL_STUFF=\"--with-linux=$4 --with-linux-obj=$4\"\n\t;;\nesac\n\nPACKAGE_CONFIG=\"/etc/sysconfig/lustre\"\nDKMS_CONFIG_OPTS=$(\n    [[ -r ${PACKAGE_CONFIG} ]] \\\n    && source ${PACKAGE_CONFIG} \\\n    && shopt -q -s extglob \\\n    && \\\n    {\n      if [[ ${LUSTRE_DKMS_DISABLE_CDEBUG,,} == @(y|yes) ]]\n      then\n\techo --disable-libcfs-cdebug\n      fi\n      if [[ ${LUSTRE_DKMS_DISABLE_TRACE,,} == @(y|yes) ]]\n      then\n\techo --disable-libcfs-trace\n      fi\n      if [[ ${LUSTRE_DKMS_DISABLE_ASSERT,,} == @(y|yes) ]]\n      then\n\techo --disable-libcfs-assert\n      fi\n    }\n  )\n\nrpm -qa | grep krb5-devel >/dev/null\nif [ $? == 0 ] ; then\n\tGSS=\"--enable-gss\"\nelse\n\tGSS=\"--disable-gss\"\nfi\n\n# run a configure pass to clean \"--enable-dist\" only effect and also to\n# ensure local/on-target environment to be taken into account for\n# dkms.mkconf script customizations and before next build/MAKE step\n./configure --prefix=/usr --enable-modules --disable-iokit --disable-snmp \\\n\t--disable-doc --disable-utils --disable-tests --disable-maintainer-mode \\\n\t$KERNEL_STUFF $GSS $SERVER $DKMS_CONFIG_OPTS \\\n\t--disable-manpages --disable-mpitests\n\nif [ $? != 0 ] ; then\n\techo \"configure error, check $7/$1/$2/build/config.log\"\n\texit 1\nfi\n", "num_lines": 88}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nprogram=$0\nprogdir=$(\\cd $(dirname $0) >/dev/null && pwd)\n\ndie() {\n\techo \"$program fatal error:  $*\"\n\texit 1\n} 1>&2\n\nTEMPFILE=$(mktemp ${TMPDIR:-.}/commit-XXXXXX)\ntest -f \"$TEMPFILE\" || die \"mktemp fails\"\ntrap \"rm -f $TEMPFILE COMMIT*\" EXIT\n\n# Pass through xtrace setting to commit-msg script\n#\nSHELL=${SHELL:-sh}\nshopt -qo xtrace && SHELL+=' -x'\n\ntest $# -eq 0 && set -- ${progdir}/commit.*\n\nexport FAIL=\"\"\nreadonly report_fmt='%-20s %s\\n'\nfor f; do\n\tcase \"$f\" in\n\t( *.orig | *.rej ) continue ;;\n\tesac\n\n\tcp $f $TEMPFILE\n\tresults=$(exec 2>&1 ${SHELL} $progdir/../commit-msg $TEMPFILE)\n\tcase $'\\n'\"$results\" in\n\t( *$'\\nerror:'* ) OK=0 ;;\n\t( * ) OK=1 ;;\n\tesac\n\n\tf=$(basename $f)\n\tcase $OK${f#*commit.} in\n\t1ok*)\tprintf \"$report_fmt\" $f: \"PASS (was allowed)\" ;;\n\t0ok*)\tprintf \"$report_fmt\" $f: \"FAIL (not allowed)\"; FAIL=\"$FAIL $f\";;\n\t0*)\tprintf \"$report_fmt\" $f: \"PASS (found error)\" ;;\n\t*)\tprintf \"$report_fmt\" $f: \"FAIL (no error)\"   ; FAIL=\"$FAIL $f\";;\n\tesac\ndone\n\nif [ -n \"$FAIL\" ]; then\n\techo -e \"\\nerror: commit-msg test(s) failed!\" 1>&2\n\techo \"\t $FAIL\"\nfi\n\nrm -f $TEMPFILE $TEMPFILE.*\n\n## Local Variables:\n## Mode: shell-script\n## sh-basic-offset:          8\n## sh-indent-after-do:       8\n## sh-indentation:           8\n## sh-indent-for-case-label: 0\n## sh-indent-for-case-alt:   8\n## indent-tabs-mode:         t\n## End:\n", "num_lines": 61}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# a framework for stacking EXIT traps\n# this could, should be further enhanced to allow stacks of traps for various\n# exits.  but right now it's hard-coded for EXIT traps\n\nexit_actions=()\n\npush_exit_trap() {\n    local action=\"$1\"\n    local trap_handle=\"$2\"\n\n    local var=\"exit_trap_handle_$trap_handle\"\n\n    if [ -n \"${!var}\" ]; then\n        echo \"fail!  trap handle $trap_handle is already in use\"\n        return 1\n    fi\n\n    local num_items=${#exit_actions[@]}\n    exit_actions[$num_items]=\"$action\"\n    eval $var=\"$num_items\"\n\n    return 0\n\n}\n\ndelete_exit_trap() {\n    local trap_handles=\"$@\"\n\n    local handle\n    for handle in $trap_handles; do\n        local var=\"exit_trap_handle_$handle\"\n        local trap_num=${!var}\n        exit_actions[$trap_num]=\"\"\n        eval unset $var\n    done\n}\n\nprint_exit_traps() {\n\n    local i num_items=${#exit_actions[@]}\n    for i in $(seq 0 $((num_items-1))); do\n        if [ -z \"${exit_actions[$i]}\" ]; then\n            continue\n        fi\n        echo \"${exit_actions[$i]}\"\n    done\n\n}\n\nrun_exit_traps() {\n\n    local i num_items=${#exit_actions[@]}\n    for i in $(seq $((num_items-1)) -1 0); do\n        if [ -z \"${exit_actions[$i]}\" ]; then\n            continue\n        fi\n        eval ${exit_actions[$i]}\n    done\n\n}\n\ntrap run_exit_traps EXIT\n\nif [ \"$1\" = \"unit_test\" ]; then\n    if ! push_exit_trap \"echo \\\"this is the first trap\\\"\" \"a\"; then\n        echo \"failed to install trap 1\"\n        exit 1\n    fi\n    if ! push_exit_trap \"echo \\\"this is the second trap\\\"\" \"b\"; then\n        echo \"failed to install trap 2\"\n        exit 2\n    fi\n    delete_exit_trap \"b\"\n    if ! push_exit_trap \"echo \\\"this is the third trap\\\"\" \"b\"; then\n        echo \"failed to install trap 3\"\n        exit 3\n    fi\n    \n    # to see the traps\n    print_exit_traps\n    echo \"------------\"\n\n    delete_exit_trap \"a\" \"b\"\n    print_exit_traps\n    echo \"------------\"\n   \n    if ! push_exit_trap \"echo \\\"this is the first trap\\\"\" \"a\"; then\n        echo \"failed to install trap 1\"\n        exit 1\n    fi\n    if ! push_exit_trap \"echo \\\"this is the second trap\\\"\" \"b\"; then\n        echo \"failed to install trap 2\"\n        exit 2\n    fi\n    if ! push_exit_trap \"echo \\\"this is the third trap\\\"\" \"c\"; then\n        echo \"failed to install trap 3\"\n        exit 3\n    fi\n    delete_exit_trap \"a\" \"c\"\n\n    print_exit_traps\n    echo \"------------\"\nfi\n", "num_lines": 106}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "cleanup() {\n\n    true\n}\n\nerror() {\n    local msg=\"$1\"\n\n    if [ -n \"$msg\" ]; then\n        echo -e \"\\n${0##*/}: $msg\" >&$STDOUT\n    fi\n}\n\nfatal() {\n    cleanup\n    error \"$2\"\n    exit $1\n}\n\n#\n# in a given directory, find the first rpm matching given requirements\n#\nfind_rpm() {\n    local dir=\"$1\"\n    local match_type=\"$2\"\n    local match=\"$3\"\n\n    pushd \"$dir\" > /dev/null || \\\n        fatal 1 \"Unable to chdir to directory \\\"$dir\\\" in find_rpm()\"\n\n    local file\n    for file in $(ls *.rpm); do\n        if [ ! -f \"$file\" ]; then\n            continue\n        fi\n        case \"$match_type\" in\n            provides)\n                # match is any valid ERE (i.e. given to egrep) match\n                if rpm -q --provides -p \"$file\" 2>&$STDOUT | egrep \"$match\" >&$STDOUT; then\n                    echo \"$file\"\n                    popd >/dev/null\n                    return 0\n                fi\n                ;;\n            *)\n                popd >/dev/null\n                fatal 1 \"Unknown match type \\\"$match_type\\\" given to find_rpm()\"\n                ;;\n        esac\n    done\n\n    popd >/dev/null\n    return 1\n}\n\nfind_linux_rpms() {\n    local prefix=\"$1\"\n    local pathtorpms=${2:-\"$KERNELRPMSBASE/$lnxmaj/$DISTROMAJ/$TARGET_ARCH\"}\n\n    local wanted_kernel=\"${lnxmaj}${lnxmin}-${lnxrel}${rpmfix}\"\n    local kernel_rpms=$(find_linux_rpm \"$prefix\" \"$pathtorpms\")\n    # call a distro specific hook, if available\n    if type -p find_linux_rpms-$DISTROMAJ; then\n        local rpm\n        if rpm=$(find_linux_rpms-$DISTROMAJ \"$prefix\" \"$wanted_kernel\" \"$pathtorpms\"); then\n            kernel_rpms=\"$kernel_rpms $rpm\"\n        else\n            return 255\n        fi\n    fi\n\n    echo \"$kernel_rpms\"\n    return 0\n\n}\n\n# a noop function which can be overridden by a distro method implementation\nresolve_arch() {\n    local arch=\"$1\"\n\n    echo \"$arch\"\n}\n\n# XXX this needs to be re-written as a wrapper around find_rpm\n#     or just gotten rid of.  :-)\nfind_linux_rpm() {\n    local prefix=\"$1\"\n    local pathtorpms=${2:-\"$KERNELRPMSBASE/$lnxmaj/$DISTROMAJ/$TARGET_ARCH\"}\n\n    local found_rpm=\"\"\n    local wanted_kernel=\"${lnxmaj}${lnxmin}-${lnxrel}${rpmfix}\"\n    local ret=1\n    if [ -d \"$pathtorpms\" ]; then\n        local rpm\n        for rpm in $(ls ${pathtorpms}/*.$(resolve_arch $TARGET_ARCH $PATCHLESS).rpm); do\n            if rpm -q --provides -p \"$rpm\" 2>&$STDOUT | grep -q \"kernel${prefix} = $wanted_kernel\" 2>&$STDOUT; then\n                found_rpm=\"$rpm\"\n                ret=0\n                break\n            fi\n        done\n    else\n        mkdir -p \"$pathtorpms\"\n    fi\n    # see above \"XXX\"\n    #     [ -f \"$found_rpm\" ] && break\n    # done\n    if [ -z \"$found_rpm\" ]; then\n        # see if there is a distro specific way of getting the RPM\n        if type -p find_linux_rpm-$DISTROMAJ; then\n            if found_rpm=$(find_linux_rpm-$DISTROMAJ \"$prefix\" \"$wanted_kernel\" \"$pathtorpms\"); then\n                found_rpm=\"${pathtorpms}/$found_rpm\"\n                ret=0\n            else\n                ret=${PIPESTATUS[0]}\n            fi\n        fi\n    fi\n\n    echo \"$found_rpm\"\n    return $ret\n\n}\n\n# autodetect used Distro\nautodetect_distro() {\n\n    local name\n    local version\n\n    if which lsb_release >/dev/null 2>&1; then\n        name=\"$(lsb_release -s -i)\"\n        version=\"$(lsb_release -s -r)\"\n        case \"$name\" in\n            \"EnterpriseEnterpriseServer\")\n                name=\"oel\"\n                ;;\n            \"RedHatEnterpriseServer\" | \"ScientificSL\" | \"CentOS\")\n                name=\"rhel\"\n                ;;\n\t    \"SUSE LINUX\" | \"SUSE\")\n\t\tname=\"sles\"\n\t\tcase \"$version\" in\n\t\t*.*)\t# $version already has patchlevel\n\t\t\t;;\n\t\t*)\t# add patchlevel\n\t\t\tPATCHLEVEL=$(sed -n -e 's/^PATCHLEVEL = //p' /etc/SuSE-release)\n\t\t\tif [ \"$PATCHLEVEL\" -ne \"0\" ]; then\n\t\t\t\tversion=\"${version}.$PATCHLEVEL\"\n\t\t\tfi\n\t\t\t;;\n\t\tesac\n\t\t;;\n            \"Fedora\")\n                name=\"fc\"\n                ;;\n            *)\n                fatal 1 \"I don't know what distro name $name and version $version is.\\nEither update autodetect_distro() or use the --distro argument.\"\n                ;;\n        esac\n    else\n        error \"You really ought to install lsb_release for accurate distro identification\"\n        # try some heuristics\n        if [ -f /etc/SuSE-release ]; then\n            name=sles\n            version=$(sed -n -e 's/^VERSION = //p' /etc/SuSE-release)\n\t    PATCHLEVEL=$(sed -n -e 's/^PATCHLEVEL = //p' /etc/SuSE-release)\n\t    if [ \"$PATCHLEVEL\" -ne \"0\" ]; then\n\t\t    version=\"${version}.$PATCHLEVEL\"\n\t    fi\n        elif [ -f /etc/redhat-release ]; then\n            #name=$(head -1 /etc/redhat-release)\n            name=rhel\n            version=$(echo \"$distroname\" |\n                      sed -e 's/^[^0-9.]*//g' | sed -e 's/[ ].*//')\n        fi\n        if [ -z \"$name\" -o -z \"$version\" ]; then\n            fatal 1 \"I don't know how to determine distro type/version.\\nEither update autodetect_distro() or use the --distro argument.\"\n        fi\n    fi\n\n    echo ${name}-${version}\n    return 0\n\n}\n\n# autodetect target\nautodetect_target() {\n    local distro=\"$1\"\n\n    local target=\"\"\n    case ${distro} in\n         rhel7*)  target=\"3.10-rhel7\";;\n         rhel8*)  target=\"4.18-rhel8\";;\n        sles11.4) target=\"$(uname -r | cut -d . -f 1,2)-sles11sp4\";;\n        sles11.3) target=\"$(uname -r | cut -d . -f 1,2)-sles11sp3\";;\n        sles11*)  target=\"$(uname -r | cut -d . -f 1,2)-sles11\";;\n        sles12.5) target=\"$(uname -r | cut -d . -f 1,2)-sles12sp5\";;\n        sles12.4) target=\"$(uname -r | cut -d . -f 1,2)-sles12sp4\";;\n        sles12.3) target=\"$(uname -r | cut -d . -f 1,2)-sles12sp3\";;\n        sles12*)  target=\"$(uname -r | cut -d . -f 1,2)-sles12\";;\n        sles15.1) target=\"$(uname -r | cut -d . -f 1,2)-sles15sp1\";;\n          fc18)   target=\"3.x-fc18\";;\n             *)   fatal 1 \"I don't know what distro $distro is.\\nEither update autodetect_target() or use the --target argument.\";;\n    esac\n\n    echo ${target}\n    return 0\n\n}\n", "num_lines": 211}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nPROG=$(basename $0)\n[ \"$1\" = \"-h\" -o \"$1\" = \"--help\" ] && echo \"usage: $PROG [patch dir]\" && exit 0\n[ \"$1\" = \"-d\" ] && shift && DELETE=\"git rm\" || DELETE=\"echo Unused\"\n[ \"$1\" = \"-v\" ] && shift && VERBOSE=\"echo Checking\" || VERBOSE=\":\"\n\n[ \"$1\" ] && BASEDIR=\"$1\"\nBASEDIR=${BASEDIR:-lustre/kernel_patches}\nSERIESPATH=${SERIESPATH:-$BASEDIR/series}\nPATCHPATH=${PATCHPATH:-$BASEDIR/patches}\n\n[ ! -d \"$BASEDIR\" ] && echo \"$PROG: missing base directory '$BASEDIR'\" && exit 1\n[ ! -d \"$SERIESPATH\" ] && echo \"$PROG: missing series '$SERIESPATH'\" && exit 2\n[ ! -d \"$PATCHPATH\" ] && echo \"$PROG: missing patches '$PATCHPATH'\" && exit 3\n\nCANONICAL_SERIESPATH=$(readlink -f ${SERIESPATH})\npushd $PATCHPATH > /dev/null\nfor PATCH in $(find -name \"*.patch\"); do\n\t# Remove the leading \"./\"\n\tPATCH=${PATCH##./}\n\t$VERBOSE $PATCH\n\tif ! grep -q -e \"^$PATCH\" $CANONICAL_SERIESPATH/*.series ; then\n\t\t$DELETE $PATCH\n\tfi\ndone\npopd > /dev/null\n", "num_lines": 27}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nPROG=$(basename $0)\n[ \"$1\" = \"-h\" -o \"$1\" = \"--help\" ] && echo \"usage: $PROG [patch dir]\" && exit 0\n[ \"$1\" = \"-v\" ] && shift && VERBOSE=\"echo\" || VERBOSE=\":\"\n\n[ \"$1\" ] && BASEDIR=\"$1\"\nBASEDIR=${BASEDIR:-lustre/kernel_patches}\nSERIESPATH=${SERIESPATH:-$BASEDIR/series}\nPATCHPATH=${PATCHPATH:-$BASEDIR/patches}\n\n[ ! -d \"$BASEDIR\" ] && echo \"$PROG: missing base directory '$BASEDIR'\" && exit 1\n[ ! -d \"$SERIESPATH\" ] && echo \"$PROG: missing series '$SERIESPATH'\" && exit 2\n[ ! -d \"$PATCHPATH\" ] && echo \"$PROG: missing patches '$PATCHPATH'\" && exit 3\n\nfor SERIES in $(ls $SERIESPATH | egrep -v \"~$|.orig|.rej\") ; do\n\t$VERBOSE \"series: $SERIES\"\n\tfor PATCH in $(grep -v \"^#\" $SERIESPATH/$SERIES); do\n\t\t$VERBOSE $PATCH\n\t\tif [ ! -e $PATCHPATH/$PATCH ]; then\n\t\t\techo \"$SERIESPATH/$SERIES: patch '$PATCH' not found!\"\n\t\tfi\n\tdone\ndone\n", "num_lines": 24}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Purpose of this script is to show the method used to integrate fscrypt\n# sources from the Linux kernel, and the transformations required.\n#\n# All C files from $LINUX/fs/crypto/ are put under libcfs/libcfs/crypto/.\n# File $LINUX/include/linux/fscrypt.h is put in libcfs/include/libcfs/crypto/.\n# File $LINUX/include/uapi/linux/fscrypt.h is placed under\n# libcfs/include/uapi/linux/.\n#\n\nmv libcfs/libcfs/crypto/fscrypt_private.h libcfs/libcfs/crypto/llcrypt_private.h\nmv libcfs/include/libcfs/crypto/fscrypt.h libcfs/include/libcfs/crypto/llcrypt.h\nmv libcfs/include/uapi/linux/fscrypt.h libcfs/include/uapi/linux/llcrypt.h\n\nfile_list=$(find libcfs/libcfs/crypto/ -type f)\nfile_list+=\" libcfs/include/libcfs/crypto/Makefile.am\"\nfile_list+=\" libcfs/include/libcfs/crypto/llcrypt.h\"\nfile_list+=\" libcfs/include/libcfs/crypto/Makefile.in\"\nfile_list+=\" libcfs/include/uapi/linux/llcrypt.h\"\n\nudef_list=$(grep -n \"#define FS_\" libcfs/include/uapi/linux/llcrypt.h | awk '{print $2}')\n\nfor file in $file_list; do\n\tcp $file ${file}.bkp\n\tsed -i s+fscrypt+llcrypt+g $file\n\tsed -i s+FSCRYPT+LLCRYPT+g $file\n\tsed -i s+FS_CRYPTO_BLOCK_SIZE+LL_CRYPTO_BLOCK_SIZE+g $file\n\tsed -i s+FSTR_INIT+LLTR_INIT+g $file\n\tsed -i s+FSTR_TO_QSTR+LLTR_TO_QSTR+g $file\n\tsed -i s+CONFIG_FS_ENCRYPTION+CONFIG_LL_ENCRYPTION+g $file\n\tsed -i s+FS_CFLG_OWN_PAGES+LL_CFLG_OWN_PAGES+g $file\n\tsed -i s+fname_name+lname_name+g $file\n\tsed -i s+fname_len+lname_len+g $file\n\tfor def in $udef_list; do\n\t\tnewdef=$(echo $def | sed s+^FS_+LL_+)\n\t\tsed -i s+$def+$newdef+g $file\n\tdone\ndone\n\nfor patch in $(cat contrib/scripts/crypto_patches/series); do\n\tpatch -p1 < $patch\ndone\n\nexit 0\n", "num_lines": 47}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Adds Intel copyright notices to files modified by Intel.\n# Does not add copyright notices to files that are missing them.\n#\n# Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.\n# Copyright (c) 2012, 2014, Intel Corporation.\n#\nTMP=${TMP:-/tmp}\nTMPFILE=$(mktemp $TMP/updatecopy.XXXXXX)\nEXCFILE=$(mktemp $TMP/excludecopy.XXXXXX)\nTHISYEAR=$(date +%Y)\nDIRS=${*:-\"build ldiskfs libcfs lnet lustre lustre-iokit snmp\"}\n\n#Old copyright messages we might need to find\nOLDCOPY1=\"Copyright.*\"\nOLDCOPY2=\"Use is subject to license terms.\"\n#The current copyright\nINTCOPY=${INTCOPY:-\"Copyright.*Intel Corporation\"}\n\n#Emails we assume ownership of\nAUTH_WHAM=${AUTH_WHAM:-\".*@whamcloud.com\"}\nAUTH_INT=${AUTH_INT:-\".*@intel.com\"}\nAUTHOR=${AUTHOR:-$AUTH_INT|$AUTH_WHAM}\n\nSTART=${START:-\"2010-06-01\"}\t# Post Oracle date\nECHOE=${ECHOE:-\"echo -e\"}\n[ \"$($ECHOE foo)\" = \"-e foo\" ] && ECHOE=echo\n\n#Commits to exclude (whitespace, copyright, prefix, revert, delete only, etc)\ncat << EXCLUDE_END > $EXCFILE\n003df3c38fe74a092f75569793edd6ec5a387d5c\n01def2b635ff0b7bacde158d9124334c42cd5d2b\n08aa217ce49aba1ded52e0f7adb8a607035123fd\n11db1a551172f596d1d284e8496530f9ce24ac81\n14d162c5438de959d0ea01fb1b40a7c5dfa764d1\na9ab51fcbd1b4dbe4c23ff774782d598f6f91ffa\n1f1d3a376d488d715dd1b0c94d5b66ea05c1e6ca\n27bc60aa7cb3c567fd3150cc55a133d60cec2405\n2841be335687840cf98961e6c6cde6ee9312e4d7\n317ebf88af58e9d9235c90f84b112e931ae69b43\n320e014a2c93cb905637d178269b80847cb8d277\n3f90f344ae059b30e7d23e4fe554a985eb827b02\n4df63615669a69b51c752cc4e416f705f8a56197\n5d37670e8507563db556879041c7992936aefa56\n60e07b972114df24105a3a1bfa7365892f72a4a7\n65701b4a30efdb695776bcf690a2b3cabc928da1\n98060d83459ba10409f295898f0ec917f938b4d3\nb1e595c09e1b07a6840142b3ae015b8a5a8affeb\nb529a917a48cb0873f2898348b25a1074d7e9429\nb5a7260ae8f96c3ff9a9948dacc4f17a46943d00\nc2c14f31da5f69770d3a46627c81335f5b8d7821\ncd8c65642f1c36b56ae74a0414a1f1f27337a662\ne3a7c58aebafce40323db54bf6056029e5af4a70\ne5f552b70dccbd2fdf21ec7b7053a01bcbe062c2\ne64d9101cc8ebc61924d6e9db6d7ab3cfa94767c\nf2a9374170e4522b9d2ac3b7096cf2912339d480\nfc1475ebdd64cd8eccc603d629ac6b4dcd222445\nb6332b5c0dfe28d6b574e206ae651262337a8309\n5acebd778f7427e8221e2cd6e463c76649f83ad3\n2b294992edce5af7b79d4300ed3aa1ea6a8db850\n21d716e6c16424d9deb646456758ebbaa9c70fec\n3c1f519956598b0106bd639f0ccae30ce745eb54\nfaeb94fe81e4646b3121c263521d30e0e83fa71f\n3b84a1ee5213563945225854a50e9037bb9646db\nc6aab2ca77831852db22b7dc39baed4d06405b7e\n26b8238659974959780cd49de92595b4b0bdf89f\n7817e4c785d075aae76b635dcf799064590833b0\n930dca7253bc2531bffa15dc763db1081cdf32d8\nd843591c30d63bf54024e21b48dec92eb0ec9f68\n1738e70fe6aaf1e07b78a6b89eb11ea115135e69\n353ef58b1d2394c4721a340e2463b07d4069d99c\nb0638b322b8c8adb2cf5f6189efd17ad70f3af2c\n83ae3e2e5b9713822ea4889d832915e791801d90\n315f6e0237b676a7512a4d2fa5765ad57483676e\n7b63a5dab65cde131627bf22d16d6e13cf259686\n6eda93c7b5f65324bdc831100a17c0bef1a3c078\n355a283fce6998f5b5621adc9697d98d0fb72dfe\ne2d2fbc07bf8f45e19d8f3127c3a7088351126d6\n89e685e154daba096c8388e39e279c6e6b342940\n4c3858b3c88d2a2f443d348945229f5995f3e1dd\nd5d5b349f23e769ae4c6307a295c532856af9c21\nbe4372fddbada6d026f4188a7e88c6a11d0a83d4\n9b8eb394ab9164066115596d26786bce80f07bd8\nbb6dbca9c2c9bdcd33663d6449b27a671fcaf902\n65e067d5d90270d4237a7271008561a4b432b94d\n3151aa574e2c9bd3343dad11577cba3c55c16dca\nbca975c7fa261ffb926e8a18d5869b886c65f447\n8fdb46e476f0f54025fd9ff85c274f2ed86315f0\n8f1c8dbe2389e1ef1e1d3387e343fb9a1bb84198\n8daba6a7381a2fb8cc933f7e9486f60e659465d4\n2bac2cd8f7bf7f31b92e976d500d89b958ab1788\n95f85ba9ed5df66a0385755be62254322fc447e1\n8f27184b14a192848429e52ac234805c324e1f7a\n3dc94d835dc3adf871c3603fc91c08bdd36701ff\n25670bb8c21deb64cfbb277bdeeab6e7ee39aa0e\nf4b93dff9a8f4a59976ea864c4e3c2c42faa5770\naab1d832130ee5c181cf7e0e5aa555244d150b00\n32bd5051a518c57e35f51b7f3c7f739b5ef91b25\n9fdef0896b78d85312269e97962d9818b395f57a\nfdd5596593050d22feef05ecba6ba53c65cb3397\n4817574ad5a31d6dbafc2bd0dfc2b6a33851ea11\n55f2a237320f23cb59df23518f5a72698d4f251c\n06c83e0109b2e934ac8cbcdcb2a22f184fe546f5\n315f6e0237b676a7512a4d2fa5765ad57483676e\n63a296c31a51cf8ac29f6e339e5686192da14769\n6c0fa97869b568a7af2d21e7e4ed2b440b7dfa27\n97da796bd3d9b98f6b65ecce493044a3e7404607\n9bf46408b3c2c8b7f939d7000a9e8df38c3fd6ed\neebeee9afa368d62b9a0813652a4c14430bd8e35\nff4357229efe87781e65382c20d3d718ecc3114d\nbeca050380b592477153fe16b79b7b6bb3aacbf2\n6c47e7f99f5fa8884751ac549a45dd3c0b81e7f1\n9d06de39731ae16d030cda672ae771496d4f0952\n0b1ad400c8f64575292a7ff54a8ce872a124b19e\nb1ff338ede34421acfc2cdbfe0dbe7b293ebd3b2\nf28cc25929c4e8a111e96b2205a0433542b35e84\n2112bc0e8b54832c303008cfe53957b8a0019407\nbbee5d1ae941a208d7a07d0348e835ab58ca90ce\ndd6623e657032bf34e70446a6d72851c70d605d9\nf470f3a166b3d471e2a3282864af35fa9d83c859\nc09317f0ba07bc7c9af229b9bfb166be56792bbf\n0754bc8f2623bea184111af216f7567608db35b6\n587a25e227024c89eb0802d1b311b5521fd5793c\n7e58fd07723483517dbe712ee671db416b6d3ac4\n60c9a2d351d40b5306b586d08847b6c7727b73cf\n5eef95fee06f712694daba942f8e90a7df96e5e1\n3af10d510078ddf050fbda2ef80bdc6920d89f8d\n0568e93539ebc1bbec601182f9faba4d43ed106b\n1d6d594d1043425a237585d2d5ad33599127dc3d\n6e27028b08eace5fc9a141d33499940ef00c9761\n2b90c15b72c25711793cc4ea46b964098131c736\nd10200a80770f0029d1d665af954187b9ad883df\ndad40c1980cbe67ec60055258f435cc3369745db\n990890eacf757d73fc87a83bfa703a51b739a05c\n9999d2d959e74f79be00e1708d0e53c5e600c47a\nfc55dd29cfaccbe925839ff665591c85313e3359\n8633aaba2da245bc62b876e535e7ac26385e1385\n9c5fad36aac2086b38f91e28db90da01efc9126a\n7524da20e134f6bbafb2a10aadc89852c6cd236d\n590881dcd2256844d45b5ea325d85057cfcd473b\nf4e95a4429e9f6a8aa8170984bc6f8cd14cd5db0\n0760baa19438f882edb94e8e86512b9751bc4432\n5a8f63b80f705756e0d530706c20793924a975a1\na67628b9e49547b75ec92fed05f770da05d14f9d\nb2c88463370dbed1539e6d7a232f8096ac735c30\n8c867d1bcd5e7b09a9cfc063ae82324f9780c0ef\n7a946907a09654c80e6d3e514920028512036bcf\n56ca45bc5a514f415c9c13ae00e2c276a6b82a52\n9afa14529b35de066b395abba448e4d2e9c2999f\na1d62378ed98e2663c1f95f955433e2a5b13d68c\n4bf65a2f6b215644b17ed20beaae1b7ff1a73bc5\nc87553ac891f092f5e9bb4eef9cf06b6516e5e48\nbbac283b4488cd34245347e59631e3f0bb3bc792\ndb46268d3be602f04ff9beb00e15f945dcd44434\nc26a4d72445c7ce02e370cc84932d7cc89416966\n73c2c103f4f43f9bb37119a2e90d6c0fc1870711\n8f66e833b9042c8015bf7a5ce0dbe2fd8fb91af1\n0ff91d6ad8c71498e29f442119327e166f527281\n59ed16fa7591513691a812ada1c9b1ebb2b426f7\nfcb2dfa7a20fec396b6b5dfd23a791e13115bbed\nb5a93d1595c5d47599ab97f93882703d30074aed\nb96b6f20764a806902898890046b31dcfa2f8dae\n107b2cba7e4a05e2aa7318c20ad7142f88083c35\nce7bb5449ab15bb9c6e8a1b2dc22be7c8efe74be\nf905bc45f49a183d8953001bd5da2741ab8c6d62\n3c60d60188e129f1cad3ed79153626fa118376ae\nd61792d0f5fa1e313ec216a5dcb833381cbec92b\n37cef588d339191f4ed0b8f1f11822f0231dcd78\n70e9d4ecc9130aeed1260d78cd8b33a5cde6edd7\n80d5a0ed4faab5bb21bcbf856765fd804002d145\nb1ff338ede34421acfc2cdbfe0dbe7b293ebd3b2\n587a25e227024c89eb0802d1b311b5521fd5793c\n6815c3c849e25c060f44db7f730831bcbcbc9091\n874690977923f9fa984f608e7bf1d6effda04e6b\n5419eabdfedd80d3f30aa456ad7dd35c3198729b\ncc311c0c9f884234a3458f471640a40d24c011b5\n226fdfbd8d177587787f473f4fb48714e1ffad91\nee41ed7803c860cb79782b3d7df8ac2b8e0ab31a\n20c748658000f5454f38576af506643e370bb1bc\ne439ba810daaebd7a51a112100a182caca72ac35\n4ddad88d15d8f9e36c5cbb9fd5611a3d8e16ea8c\nf13b2a4cea69d8c4c079d03d58f55d32a54a9679\nc7558380b8e6dc6ac23879959731938bd5d32709\nef6bb2cd842d18e6fbe4f6160467a9318c1862e0\n650b7450b612943e7ade76434c3be70b06f58f58\ne5eaaff6e378b8c95d0a809f4dd3b4817d9fd492\n4ed67efd13cddd7ec41d29e853601ce862aaae9e\n434eeba4d33d9ddd871cff080d51534081bb3d30\n558c93dc56dc603be0b4e065a5ffe8b448f33bd5\n53d3890f16e4c6e5717c4d020ef213897a36c2b7\nbcb737a19433e3e32df6a826f29d15a3666f54d8\n40fe3cd7283dfd1cee5f989483c517601ac773f8\ne5eaaff6e378b8c95d0a809f4dd3b4817d9fd492\nEXCLUDE_END\n[ -n \"$EXCLUDE\" ] && echo \"$EXCLUDE\" >> $EXCFILE\n\nHASHFILE=$TMP/hash_list\n> $TMP/hash_list\ngit ls-files $DIRS | while read FILE; do\n\tFILE=$FILE # just so FILE shows up in \"sh -vx\" output\n\tcase \"$FILE\" in\n\t*/list.h)\n\t\t# file is copied from upstream kernel\n\t\tcontinue ;;\n\t*/liblustreapi.h)\n\t\t# file just includes lustreapi.h, copyrights are in there\n\t\tcontinue ;;\n\t*/*.patch|*/*.series)\n\t\t# patches can't add copyrights easily\n\t\tcontinue ;;\n\t*/lustre_dlm_flags.h)\n\t\t# file is automatically generated\n\t\tcontinue ;;\n\t*/.gitignore)\n\t\tcontinue ;;\n\t*/LCOPYING)\n\t\t# just a copy of the LGPL, don't claim copyright\n\t\tcontinue ;;\n\tesac\n\n\tOLDCOPY=$(egrep \"$INTCOPY\" $FILE | tail -n1)\n\t# Skip files that already have a copyright for this year\n\t[ -n \"$(egrep -e $THISYEAR <<<\"$OLDCOPY\")\" ] && continue\n\n\tADDCOPY=false\n\t# Pick only files that have changed since $START\n\t# %ai author dates holds has bad data, use %ci instead\n\t# Exclude revert commits and the patch being reverted.\n\tgit log --follow --since=$START --pretty=format:\"%ci %ae %H\" $FILE |\n\t\tgrep -v -f $EXCFILE | egrep -e \"$AUTHOR\" |\n\t\twhile read YYYY TTTT TZZZ AUTHOR HASH; do\n\t\t\tREVERT=$(git show -s $HASH |\n\t\t\t\t awk '/This reverts commit/ { print $4 }')\n\t\t\tif [ -n \"$REVERT\" ]; then\n\t\t\t\techo $HASH >> $EXCFILE\n\t\t\t\ttr -d . <<<$REVERT >> $EXCFILE\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\techo \"$YYYY $TTTT $TZZZ $AUTHOR $HASH\"\n\t\tdone > $TMPFILE.2\n\tgrep -v -f $EXCFILE $TMPFILE.2 > $TMPFILE\n\n\t# Skip files not modified by $AUTHOR\n\t[ -s \"$TMPFILE\" ] || continue\n\n\tif [ -z \"$(egrep -e \"$OLDCOPY1\" $FILE)\" ]; then\n\t\tcase $FILE in\n\t\t*.[ch])\n\t\t\techo \"$FILE: ** NO COPYRIGHT. INSPECT  **\"\n\t\t\tcontinue ;;\n\t\t*)\n\t\t\tcontinue ;;\n\t\tesac\n\tfi\n\n\tif [ -z \"$(grep \"$INTCOPY\" <<<\"$OLDCOPY\")\" ]; then\n\t\tADDCOPY=true\n\t\tOLDCOPY=\"$(egrep \"$OLDCOPY1|$OLDCOPY2\" $FILE| tail -n1| tr / .)\"\n\tfi\n\n\t# Get commit dates\n\tNEWYEAR=$(head -1 $TMPFILE | cut -d- -f 1)\n\tOLDYEAR=$(tail -1 $TMPFILE | cut -d- -f 1)\n\n\tif [ \"$NEWYEAR\" -lt \"$OLDYEAR\" ]; then\n\t\techo \"$FILE: ** YEAR INVERSION: INSPECT  **\"\n\t\tcontinue;\n\tfi\n\n\t[ $NEWYEAR == $OLDYEAR ] && YEAR=\"$NEWYEAR\" || YEAR=\"$OLDYEAR, $NEWYEAR\"\n\t# The man page comment .\\\" needs to be escaped, and the '\\' reinforced\n\tCOMMENT=$(sed -e 's/^\\( *[\\*#\\.\\\"\\\\]*\\) *[A-Z(].*/\\1/' -e 's/\\\\/\\\\\\\\/' \\\n\t\t  <<<\"$OLDCOPY\")\n\tNEWCOPY=$(sed -e\"s/^/$COMMENT /\" -e\"s/\\.\\*/ (c) $YEAR, /\" -e's/\\.*$//' \\\n\t\t  <<<\"$INTCOPY\").\n\n\t# '.\\\"' as a COMMENT in a man page isn't escaped correctly\n\t#case \"$FILE\" in\n\t#*/*.[1-9])\n\t#\techo \"$FILE: *** EDIT MANUALLY ***\"\n\t#\tcontinue ;;\n\t#esac\n\n\t# If copyright is unchanged (excluding whitespace), we're done\n\t[ \"$OLDCOPY\" == \"$NEWCOPY\" ] && continue\n\n\t# Log all changes this year, to help find \"noisy\" patches\n\tawk '/'$THISYEAR'-/ { print $5 }' $TMPFILE | cut -c1-12 >> $HASHFILE\n\n\t[ ! -w $FILE ] && echo \"$FILE: *** can't write, EDIT MANUALLY ***\" &&\n\t\tcontinue\n\n\tif $ADDCOPY; then\n\t\techo \"$FILE: $NEWCOPY (newly added) ** INSPECT **\"\n\t\t# Add a new copyright line after the existing copyright.\n\t\t# Using a temporary file is ugly, but I couldn't get\n\t\t# newlines into the substitution pattern for some reason,\n\t\t# and this is not a performance-critical process.\n\t\t$ECHOE \"${COMMENT}\\n${NEWCOPY}\" > $TMPFILE\n\t\t# The man page comment .\\\" (currently .\") needs '\\' added back\n\t\tsed -e \"/$OLDCOPY/r $TMPFILE\" \\\n\t\t    -e 's/^\\.\"/.\\\\\"/' $FILE > $FILE.tmp\n\telse\n\t\tif grep -q \"Commissariat\" <<<\"$OLDCOPY\"; then\n\t\t\tINSPECT=\"** INSPECT **\"\n\t\telse\n\t\t\tINSPECT=\"\"\n\t\tfi\n\t\techo \"$FILE: $NEWCOPY $INSPECT\"\n\t\t# Replace the old copyright line with a new copyright\n\t\t# The man page comment .\\\" (currently .\") needs '\\' added back\n\t\tsed -e \"s/.*$INTCOPY.*/$NEWCOPY/\" \\\n\t\t    -e 's/^\\.\"/.\\\\\"/' $FILE > $FILE.tmp\n\tfi\n\t[ -s $FILE.tmp ] && cp $FILE.tmp $FILE && rm -f $FILE.tmp\n#exit\ndone\nif [ -s $HASHFILE ]; then\n\techo \"commits causing the most changes\"\n\tsort $HASHFILE | uniq -c | sort -nr | head -30 | while read CNT HASH; do\n\t\techo $CNT $(git show --oneline --no-patch $HASH)\n\tdone\n\nfi\nrm -f $TMPFILE $TMPFILE.2\n", "num_lines": 326}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This file is provided under a dual BSD/GPLv2 license.  When using or\n# redistributing this file, you may do so under either license.\n#\n# GPL LICENSE SUMMARY\n#\n# Copyright(c) 2016 Intel Corporation.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of version 2 of the GNU General Public License as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# Contact Information:\n# Cong Xu, cong.xu@intel.com\n#\n# BSD LICENSE\n#\n# Copyright(c) 2016 Intel Corporation.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Intel Corporation nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n\nfunction usage() {\n\tcat << EOF\nUsage: $0 [-a] [-d] [-l] [-h] [-m] [-n] [-o] [-u]\n\t-a  command to launch application\n\t-d  shared nfs directory to store LIOProf logs\n\t-l  lowest Lustre OSS node [Hostname]\n\t-h  highest Lustre OSS node [Hostname]\n\t-m  lowest Lustre Client [Hostname]\n\t-n  highest Lustre Client [Hostname]\n\t-o  use Obdfilter-survey to measure Lustre bandwidth\n\t-u  user name\nEOF\n\texit 0\n}\n\n\nwhile getopts \":a:d:l:h:m:n:ou:\" arg; do\n\tcase \"${arg}\" in\n\t\ta)\n\t\t\ta=${OPTARG};;\n\t\td)\n\t\t\td=${OPTARG};;\n\t\tl)\n\t\t\tl=${OPTARG};;\n\t\th)\n\t\t\th=${OPTARG};;\n\t\tm)\n\t\t\tm=${OPTARG};;\n\t\tn)\n\t\t\tn=${OPTARG};;\n\t\to)\n\t\t\to=\"Obdfilter-survey\";;\n\t\tu)\n\t\t\tu=${OPTARG};;\n\t\t*)\n\t\t\tusage;;\n\tesac\ndone\nshift $((OPTIND-1))\n\nif [ -n \"${o}\" ]; then\n\t# Launch OBDfilter-survey to measure Lustre bandwidth\n\tif [ -n \"${a}\" ] || [ -z \"${d}\" ] || [ -z \"${l}\" ] || [ -z \"${h}\" ] \\\n\t\t|| [ -z \"${u}\" ]; then\n\t\tusage\n\tfi\nelse\n\t# Launch application\n\tif [ -z \"${a}\" ] || [ -z \"${d}\" ] || [ -z \"${l}\" ] || [ -z \"${h}\" ] \\\n\t\t|| [ -z \"${m}\" ] || [ -z \"${n}\" ] || [ -z \"${u}\" ]; then\n\t\tusage\n\tfi\nfi\n\n\n# Cluster Name\ncluster_name=$(cut -d- -f1 <<<\"${l}\")\n\n# Lustre OSS Nodes\nOSS_MIN=$(cut -d- -f2 <<<\"${l}\")\nOSS_MAX=$(cut -d- -f2 <<<\"${h}\")\n\n# Lustre Clients\nCLIENT_MIN=$(cut -d- -f2 <<<\"${m}\")\nCLIENT_MAX=$(cut -d- -f2 <<<\"${n}\")\n\n# Input user name\nUSER_NAME=${u}\n\n# Commands information\nmpi_cmd=mpirun\npdsh_cmd=/usr/bin/pdsh\n\n# Job ID (Based on job time)\njob_id=job-`date +%s`\necho \"Launch\" ${job_id}\n\n\nif [ -n \"${o}\" ]; then\n\t# OBDfilter-survey (Obtain maximum available bandwidth of Lustre)\n\techo \"Running OBDfilter-survey in the background\"\n\n\tHOMEOBDFILTER=${d}/${job_id}/obdfilter\n\tsudo -u ${USER_NAME} mkdir -p $HOMEOBDFILTER\n\tsudo -u ${USER_NAME} chmod 777 -R ${d}/${job_id}\n\t${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\t\tsize=65536 nobjlo=1 nobjhi=2 thrlo=32 thrhi=64 \\\n\t\tobdfilter-survey > ${HOMEOBDFILTER}/\\`hostname -s\\` & \\\n\t\"\n\texit 0\nfi\n\n\n# rpc and brw logs directories\nLOCALRPC=/lioprof_loc/${job_id}/rpc\nLOCALBRW=/lioprof_loc/${job_id}/brw\nLOCALIOSTAT=/lioprof_loc/${job_id}/iostat\n\nHOMERPC=${d}/${job_id}/rpc\nHOMEBRW=${d}/${job_id}/brw\nHOMEIOSTAT=${d}/${job_id}/iostat\n\n# Create logs directories\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\tmkdir -p ${LOCALRPC} ${LOCALBRW} ${LOCALIOSTAT}; \\\n\t\"\n\n# Change log directories permissions\nsudo -u ${USER_NAME} mkdir -p ${HOMERPC} ${HOMEBRW} ${HOMEIOSTAT}\nsudo -u ${USER_NAME} chmod 777 -R ${d}/${job_id}\n\n# Enable RPC Tracing\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \\\n\t\"lctl set_param debug=rpctrace\"\n\n# Evaluate Performance\n\n# Clear Lustre cache\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$CLIENT_MAX] \" \\\n\techo 3 > /proc/sys/vm/drop_caches; echo 0 > /proc/sys/vm/drop_caches;\n\"\n\n# Start RPC log service and brw_stats\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\techo > /proc/fs/lustre/obdfilter/*/brw_stats; \\\n\tlctl clear; lctl debug_daemon start ${LOCALRPC}/rpc.log 1024; \\\n\t\"\n\n# Start iostat\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\tiostat 1 > ${LOCALIOSTAT}/iostat.log&\n\t\"\nsleep 2\n\n######################## Launch Application ########################\n${a} > ${d}/${job_id}/job-output\nsleep 2\n####################################################################\n\n# Collect Lustre RPC and btw_stats logs\n${pdsh_cmd} -R ssh -w $cluster_name-[$CLIENT_MIN-$CLIENT_MAX] \" \\\n\tlctl set_param ldlm.namespaces.*.lru_size=clear\n\t\"\nsleep 5\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\tlctl debug_daemon stop; \\\n\tcat /proc/fs/lustre/obdfilter/*/brw_stats > \\\n\t\t\t${HOMEBRW}/brw-\\`hostname -s\\`; \\\n\tlctl debug_file ${LOCALRPC}/rpc.log ${HOMERPC}/rpc-\\`hostname -s\\`; \\\n\"\n\n# Stop iostat and collect data\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\tpkill iostat; cp -r ${LOCALIOSTAT}/iostat.log \\\n\t${HOMEIOSTAT}/iostat-\\`hostname -s\\` \\\n\"\n\n# Change log file mode\nsleep 1\nsudo -u root chmod 755 -R ${HOMERPC}/* ${HOMEBRW}/* ${HOMEIOSTAT}/*\n\n###################################################################\n#### Warning! Pay much more attention to rm commands with root ####\n###################################################################\n# Clear local history logs\nsleep 2\nLOCAL_LIOPROF=/lioprof_loc\n${pdsh_cmd} -R ssh -w $cluster_name-[$OSS_MIN-$OSS_MAX] \" \\\n\tpkill iostat; \\\n\trm -rf ${LOCAL_LIOPROF}; \\\n\"\n", "num_lines": 226}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This file is provided under a dual BSD/GPLv2 license.  When using or\n# redistributing this file, you may do so under either license.\n#\n# GPL LICENSE SUMMARY\n#\n# Copyright(c) 2016 Intel Corporation.\n#\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of version 2 of the GNU General Public License as\n# published by the Free Software Foundation.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# Contact Information:\n# Cong Xu, cong.xu@intel.com\n#\n# BSD LICENSE\n#\n# Copyright(c) 2016 Intel Corporation.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions\n# are met:\n#\n# * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n# * Redistributions in binary form must reproduce the above copyright\n# notice, this list of conditions and the following disclaimer in\n# the documentation and/or other materials provided with the\n# distribution.\n# * Neither the name of Intel Corporation nor the names of its\n# contributors may be used to endorse or promote products derived\n# from this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\n\n\nfunction usage() {\n\tcat << EOF\nUsage: $0 [-i] [-x] [-y] [-t]\n\t-i  path to LIOProf rpc tracing logs\n\t-x  lowest Lustre Client [IB IP Address]\n\t-y  highest Lustre Client [IB IP Address]\n\t-t  Type of Operation Code (OPC) (OST_READ 3, OST_WRITE 4)\nEOF\n\texit 0\n}\n\n\nwhile getopts \":i:x:y:t:\" o; do\n\tcase \"${o}\" in\n\t\ti)\n\t\t\ti=${OPTARG};;\n\t\tx)\n\t\t\tx=${OPTARG};;\n\t\ty)\n\t\t\ty=${OPTARG};;\n\t\tt)\n\t\t\tt=${OPTARG};;\n\t\t*)\n\t\t\tusage;;\n\tesac\ndone\nshift $((OPTIND-1))\n\nif [ -z \"${i}\" ] || [ -z \"${x}\" ] || [ -z \"${y}\" ] || [ -z \"${t}\" ]; then\n\tusage\nfi\n\n\n# Cluster Name\ncluster_name=$(cut -d- -f1 <<<\"${x}\")\n\n# Lustre Clients\nCLIENT_PRE=$(cut -d. -f 1-3 <<<\"${x}\")\nCLIENT_MIN=$(cut -d. -f4 <<<\"${x}\")\nCLIENT_MAX=$(cut -d. -f4 <<<\"${y}\")\n\n# Type of Operation Code (OPC) (Defined in lustre/include/lustre/lustre_idl.h)\nOPC_TYPE=${t}\n\n# Input directory\nIN_PUT=${i}\n\n# Output directory\nOUT_PUT=${i}-out\nrm -rf $OUT_PUT\nmkdir -p $OUT_PUT\n\nfor f in ${IN_PUT}/*\ndo\n\techo \"Processing ${f}\"\n\tfor ((c = $CLIENT_MIN; c <= $CLIENT_MAX; c = c + 1))\n\tdo\n\t\tip=${CLIENT_PRE}.$c\n\t\tCUR_OST=$(echo \"${f}\" | rev | cut -d'/' -f1 | rev)\n\n\t\tcat ${f} | grep \"Handling RPC pname\" | grep \"ll_ost_io\" | \\\n\t\tgrep o2ib:${OPC_TYPE} | grep ${ip} | \\\n\t\tawk 'BEGIN{FS=\":\"}{print $4}' | sort -n | \\\n\t\tawk 'BEGIN {count = 0; line = 0; FS=\".\"} {\n\t\t\tif (NR == 1) {curval = $1};\n\t\t\tif($1 <= curval) {\n\t\t\t\tcount = count + 1;\n\t\t\t} else {\n\t\t\t\tprint line \"\\t\" count;\n\t\t\t\tcurval = curval + 1;\n\t\t\t\tline = line + 1;\n\t\t\t\tcount = 1;\n\t\t\t\twhile(curval < $1) {\n\t\t\t\t\tprint line \"\\t\" 0;\n\t\t\t\t\tcurval = curval + 1;\n\t\t\t\t\tline = line + 1;\n\t\t\t\t}\n\t\t\t}\n\t\t} END {\n\t\t\tprint line \"\\t\" count;\n\t\t}' \\\n\t\t> ${OUT_PUT}/$CUR_OST-Client-$c &\n\tdone\ndone\n\n# Wait for completion\nwait\n\n\n# If the lines of the files are different, fill the end of files with zeros to\n# guarantee all the files have the same number of lines.\n\n# Get max line\nMAX_LINE=-1\nfor f in ${OUT_PUT}/*\ndo\n\tLINE=$(wc -l < ${f})\n\tif [ \"$MAX_LINE\" -lt \"$LINE\" ]\n\tthen\n\t\tMAX_LINE=${LINE}\n\tfi\ndone\n\n# Append zeros\nfor f in  ${OUT_PUT}/*\ndo\n\tLINE=$(wc -l < ${f})\n\tfor ((i = $LINE; i < $MAX_LINE; i = i + 1))\n\tdo\n\t\tprintf  \"0\\t0\\n\" >> ${f} &\n\tdone\ndone\n", "num_lines": 167}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# License:      GNU General Public License (GPL)\n# \n# lustre_server\n#      Description: Manages a lustre_server on a shared storage medium.\n#  Original Author: Eric Z. Ayers (eric.ayers@compgen.com)\n# Original Release: 25 Oct 2000\n#\n# Rewritten Filesystem agent to lustre_server agent by bschubert@ddn.com\n#\n# usage: ./lustre_server {start|stop|status|monitor|validate-all|meta-data}\n#\n#         OCF parameters are as below:\n#               OCF_RESKEY_device\n#               OCF_RESKEY_directory\n#               OCF_RESKEY_options\n#\n#OCF_RESKEY_device    : name of block device for the filesystem. e.g. /dev/sda1, /dev/md0\n#                       Or a -U or -L option for mount, or an NFS mount specification\n#OCF_RESKEY_directory : the mount point for the filesystem\n#OCF_RESKEY_options   : options to be given to the mount command via -o\n#\n#\n# NOTE: There is no locking (such as a SCSI reservation) being done here.\n#       I would if the SCSI driver could properly maintain the reservation,\n#       which it cannot, even with the 'scsi reservation' patch submitted\n#       earlier this year by James Bottomley.  The patch minimizes the\n#       bus resets caused by a RESERVATION_CONFLICT return, and helps the\n#       reservation stay when 2 nodes contend for a reservation,\n#       but it does not attempt to recover the reservation in the\n#       case of a bus reset.\n#\n#       What all this means is that if 2 nodes mount the same file system\n#       read-write, the filesystem is going to become corrupted. However\n#       Lustre provides the Multi-Mount-Protection feature (MMP).\n#\n#       As a result, you should use this together with the stonith option\n#       and redundant, independent communications paths.\n#\n#       If you don't do this, don't blame us when you scramble your disk.\n#\n#       Note:  the ServeRAID controller does prohibit concurrent acess\n#       In this case, you don't actually need STONITH, but redundant comm is\n#       still an excellent idea.\n#\n\n#######################################################################\n# Initialization:\n\n. ${OCF_ROOT}/resource.d/heartbeat/.ocf-shellfuncs\n\n#######################################################################\nHOSTOS=`uname`\nFSTYPE=\"lustre\"\n\n# FIXME: OCF_DEBUG officially supported in the the mean time?\n#OCF_DEBUG=yes\n\nusage() {\n        cat <<-EOT\n        usage: $0 {start|stop|status|monitor|validate-all|meta-data}\n        EOT\n}\n\nmeta_data() {\n        cat <<END\n<?xml version=\"1.0\"?>\n<!DOCTYPE resource-agent SYSTEM \"ra-api-1.dtd\">\n<resource-agent name=\"lustre_server\">\n<version>1.0</version>\n\n\n<longdesc lang=\"en\">\n  Resource script for lustre_server. It manages a lustre_server on a shared storage medium. \n</longdesc>\n<shortdesc lang=\"en\">lustre_server resource agent</shortdesc>\n\n<parameters>\n  <parameter name=\"device\" required=\"1\">\n    <longdesc lang=\"en\">\n       The name of block device for the filesystem\n  </longdesc>\n  <shortdesc lang=\"en\">block device</shortdesc>\n  <content type=\"string\" default=\"\" />\n</parameter>\n\n<parameter name=\"directory\" required=\"1\">\n <longdesc lang=\"en\">\n   The mount point for the filesystem.\n </longdesc>\n <shortdesc lang=\"en\">mount point</shortdesc>\n <content type=\"string\" default=\"\" />\n</parameter>\n\n<parameter name=\"options\">\n <longdesc lang=\"en\">\n  Any extra options to be given as -o options to mount.\n </longdesc>\n <shortdesc lang=\"en\">options</shortdesc>\n <content type=\"string\" default=\"\" />\n</parameter>\n</parameters>\n\n<actions>\n <action name=\"start\" timeout=\"300\" />\n <action name=\"stop\" timeout=\"300\" />\n <action name=\"monitor\" depth=\"0\" timeout=\"300\" interval=\"120\" start-delay=\"10\" />\n <action name=\"validate-all\" timeout=\"5\" />\n <action name=\"meta-data\" timeout=\"5\" />\n </actions>\n</resource-agent>\nEND\n}\n\n#\n#       Make sure the kernel does the right thing with the FS buffers\n#       This function should be called after unmounting and before mounting\n#       It may not be necessary in 2.4 and later kernels, but it shouldn't hurt\n#       anything either...\n#\n#       It's really a bug that you have to do this at all...\n#\nflushbufs() {\n    if have_binary $BLOCKDEV ; then\n       $BLOCKDEV --flushbufs $1\n    fi\n    return 0\n}\n\n# Figure out the real device number of external journals\n# we need to provide as mount options, since the block\n# device only know major/minor of the the journal device and it\n# might/will change dynamically on reboots and between servers\n# It would be MUCH better if 'mount' would do it on its own\n# and in fact mount is already linked against libblkid to do\n# this job\nget_external_journal_device()\n{\n        UUID=`dumpe2fs -h $DEVICE 2>/dev/null | awk '/^Journal UUID/{print $3}'`\n        if [ -z \"$UUID\" ]; then\n                # device has internal journal, not need to proceed\n                return\n        fi\n\n        # prefer /dev/mapper/\n        JDEV=\"`blkid -t UUID=$UUID /dev/mapper/* | awk -F: '{print $1}'`\"\n        if [ -z \"$JDEV\" ]; then\n                JDEV=\"`blkid -t UUID=$UUID | awk -F: '{print $1}'`\"\n        fi\n\n        if [ -z \"$JDEV\" ]; then\n                # know the journal is on an external device, but we can't find it\n                ocf_log err \"Cannot find device with journal UUID $UUID\"\n                return $OCF_ERR_GENERIC\n        fi\n\n        DEVNUM=\"`stat -c %02t%02T $JDEV`\"\n        if [ -z \"$DEVNUM\" ]; then\n                ocf_log err \"Failed to retrieve device number of Journal device\"\n                return $OCF_ERR_GENERIC\n        fi\n\n        # add 0x only here, because we couldn't check for an empty string otherwise\n        DEVNUM=\"0x$DEVNUM\"\n\n        echo $DEVNUM\n        return 0\n}\n\n# Take advantage of /proc/mounts if present, use portable mount command\n# otherwise. Normalize format to \"dev mountpoint fstype\".\nlist_mounts() {\n        mtab=/proc/mounts\n        if [ ! -f $mtab ]; then\n                ocf_log err \"$mtab is missing!\"\n                exit $OCF_ERR_GENERIC\n        fi\n        cat $mtab | cut -d' ' -f1,2,3\n}\n\nlustre_health_check()\n{\n\tcheck=$(lctl get_param -n health_check 2>&1)\n        # on first check the lustre modules are not loaded yet\n        if [ $? != 0 ]; then\n                return 0\n        fi\n\n        if [ \"$check\" = \"healthy\" ]; then\n                return 0\n        else\n                ocf_log err \"health_check is $check\"\n                return 1\n        fi\n}\n\n#\n# START: Start up the filesystem\n#\nlustre_server_start()\n{\n        lustre_health_check\n        if [ $? -ne 0 ]; then\n                return ${OCF_ERR_GENERIC}\n        fi\n\n        # See if the device is currently mounted\n        lustre_server_status >/dev/null 2>&1\n        rc=$?\n        if [ $rc -ne $OCF_NOT_RUNNING -a $rc -ne $OCF_SUCCESS ]; then\n                ocf_log err \"Unexpected status ($c) before mounting $DEVICE to $MOUNTPOINT\"\n        elif [ $rc -eq $OCF_SUCCESS ]; then\n                return $OCF_SUCCESS\n        fi\n\n        if [ ! -d \"$MOUNTPOINT\" ] ; then\n                ocf_log err \"Couldn't find directory  [$MOUNTPOINT] to use as a mount point\"\n                exit $OCF_ERR_ARGS\n        fi\n\n        flushbufs $DEVICE\n\n        jdev=`get_external_journal_device`\n        rc=$?\n        if [ $rc -ne 0 ]; then\n                ocf_log err \"Failure to get journal device\"\n                return $rc\n        fi\n\n        if [ -n \"$jdev\" ]; then\n                if [ -n \"$options\" ]; then\n                        options=\"$options,journal_dev=$jdev\"\n                else\n                        options=\"-ojournal_dev=$jdev\"\n                fi\n        fi\n\n        # Mount the filesystem.\n        cmd=\"$MOUNT -t $FSTYPE $options $DEVICE $MOUNTPOINT\"\n        ocf_log info \"Running $cmd\"\n        res=`eval $cmd 2>&1`\n        if [ $? -ne 0 ]; then\n                ocf_log err \"cmd \\\"$cmd\\\" failed: $res\"\n                return $OCF_ERR_GENERIC\n        fi\n\n        return 0\n}\n# end of lustre_server_start\n\n#\n# STOP: Unmount the filesystem\n#\nlustre_server_stop()\n{\n        # See if the device is currently mounted\n        lustre_server_mounted >/dev/null 2>&1\n        if [ $? -eq $OCF_NOT_RUNNING ]; then\n                # Already unmounted, wonderful.\n                rc=$OCF_SUCCESS\n        else\n                # Umount $MOUNTPOINT.\n                ocf_log info \"Trying to unmount $MOUNTPOINT\"\n                cmd=\"$UMOUNT $MOUNTPOINT\"\n                ocf_log info \"Running $cmd\"\n                res=`eval $cmd 2>&1`\n                rc=$?\n                if [ $rc -eq 0 ] ; then\n                        rc=$OCF_SUCCESS\n                        ocf_log info \"unmounted $MOUNTPOINT successfully\"\n                else\n                        rc=$OCF_ERR_GENERIC\n                        ocf_log err \"\\\"$cmd\\\" failed ($rc): $res\"\n                fi\n        fi\n\n        flushbufs $DEVICE\n\n        return $rc\n}\n# end of lustre_server_stop\n\n#\n# MOUNTED: is the filesystem mounted or not?\n#\nlustre_server_mounted()\n{\n        if list_mounts | grep -q \" $MOUNTPOINT \" >/dev/null 2>&1; then\n                rc=$OCF_SUCCESS\n                msg=\"$MOUNTPOINT is mounted (running)\"\n        else\n                rc=$OCF_NOT_RUNNING\n                msg=\"$MOUNTPOINT is unmounted (stopped)\"\n        fi\n\n        # check in all mntdevs if really not mounted\n        # lustre bug 21359 (https://bugzilla.lustre.org/show_bug.cgi?id=21359)\n        if [ $rc -eq $OCF_NOT_RUNNING ]; then\n\t\tdev=$(lctl get_param -n mds.*.mntdev 2>&1)\n\t\tif [ $? = 0 ]; then\n\t\t\tMNTDEVS=$dev\n\t\tfi\n\t\tdev=$(lctl get_param -n obdfilter.*.mntdev 2>&1)\n\t\tif [ $? = 0 ]; then\n\t\t\tMNTDEVS=\"$MNTDEVS $dev\"\n\t\tfi\n\t\tdev=$(lctl get_param -n mgs.MGS.mntdev 2>&1)\n\t\tif [ $? = 0 ]; then\n\t\t\tMNTDEVS=\"$MNTDEVS $dev\"\n\t\tfi\n\t\tfor i in $MNTDEVS; do\n\t\t\tif [ \"$i\" = \"$DEVICE\" ]; then\n                                ocf_log err \"Bug21359, /proc/mounts claims device is not mounted, but $i proves this is wrong\"\n                                rc=$OCF_ERR_GENERIC\n                        fi\n                done\n\n        fi\n\n        if [ \"$OCF_DEBUG\" = \"yes\" ]; then\n                ocf_log info \"$msg\"\n        fi\n\n        case \"$OP\" in\n        status) ocf_log info \"$msg\"\n                ;;\n        monitor)\n                if [ $rc -ne $OCF_SUCCESS ]; then\n                        ocf_log err \"$msg\"\n                fi\n        esac\n\n        return $rc\n}\n# end of lustre_server_mounted\n\n#\n# STATUS: is the filesystem mounted and healthy or not?\n#\nlustre_server_status()\n{\n        lustre_health_check\n        if [ $? -ne 0 ]; then\n                return ${OCF_ERR_GENERIC}\n        fi\n\n        lustre_server_mounted\n        rc=$?\n\n        return $rc\n}\n# end of lustre_server_status\n\n#\n#       Check if Lustre is available at all\n#\nlustre_server_validate_all()\n{\n\tvar=$(lctl get_param -n version 2>&1)\n\tif [ $? != 0 ]; then\n\t\tmodprobe lustre\n\n\t\tfor i in `seq 1 10`; do\n\t\t\tvar=$(lctl get_param -n version 2>&1)\n\t\t\tif [ $? != 0 ]; then\n\t\t\t\tsleep 1\n\t\t\telse\n\t\t\t\tbreak\n\t\t\tfi\n\t\tdone\n\n\t\tvar=$(lctl get_param -n version 2>&1)\n\t\tif [ $? != 0 ]; then\n\t\t\tocf_log err \"Failed to load the lustre module\"\n\t\t\treturn $OCF_ERR_GENERIC\n\t\tfi\n\tfi\n\n        return $OCF_SUCCESS\n}\n\n# Check the arguments passed to this script\nif [ $# -ne 1 ]; then\n        usage\n        exit $OCF_ERR_ARGS\nfi\n\n# Check the OCF_RESKEY_ environment variables...\nDEVICE=$OCF_RESKEY_device\nif [ ! -z \"$OCF_RESKEY_options\" ]; then\n        options=\"-o $OCF_RESKEY_options\"\nfi\n\nOP=$1\n\nif [ \"$OCF_DEBUG\" = \"yes\" ]; then\n        ocf_log info \"OP = $OP\"\nfi\n\n# These operations do not require instance parameters\ncase $OP in\nmeta-data)      meta_data\n                exit $OCF_SUCCESS\n                ;;\nusage)          usage\n                exit $OCF_SUCCESS\n                ;;\nesac\n\n# Normalize instance parameters:\n\n# It is possible that OCF_RESKEY_directory has one or even multiple trailing \"/\".\n# But the output of `mount` and /proc/mounts do not.\nif [ -z \"$OCF_RESKEY_directory\" ]; then\n        ocf_log err \"Please specify the directory\"\n        exit $OCF_ERR_ARGS\nelse\n        MOUNTPOINT=$(echo $OCF_RESKEY_directory | sed 's/\\/*$//')\n        : ${MOUNTPOINT:=/}\n        # At this stage, $MOUNTPOINT does not contain trailing \"/\" unless it is \"/\"\n        # TODO: / mounted via lustre_server sounds dangerous. On stop, we'll\n        # kill the whole system. Is that a good idea?\nfi\n\nMOUNTPOINT=`echo $MOUNTPOINT | sed -e 's/\\s*//'`\nif [ -z \"$MOUNTPOINT\" ]; then\n        ocf_log err \"Empty mount point!\"\n        ocf_log err \"Please specify the directory\"\n        exit $OCF_ERR_ARGS\nfi\n\n# Check to make sure the utilites are found\ncheck_binary $MODPROBE\ncheck_binary $FSCK\ncheck_binary $MOUNT\ncheck_binary $UMOUNT\n\nif [ \"$OP\" != \"monitor\" ]; then\n        ocf_log info \"Running $OP for $DEVICE on $MOUNTPOINT\"\nfi\n\n# These operations do not require the clone checking + OCFS2\n# initialization.\ncase $OP in\nstatus|monitor) lustre_server_status\n                exit $?\n                ;;\nvalidate-all)   lustre_server_validate_all\n                exit $?\n                ;;\nstop)           lustre_server_stop\n                exit $?\n                ;;\nesac\n\nif [ -n \"$OCF_RESKEY_CRM_meta_clone\" ]; then\n        ocf_log err \"DANGER! $FSTYPE on $DEVICE is NOT cluster-aware!\"\n        ocf_log err \"DO NOT RUN IT AS A CLONE!\"\n        ocf_log err \"Politely refusing to proceed to avoid data corruption.\"\n        exit $OCF_ERR_GENERIC\nfi\n\ncase $OP in\nstart)  lustre_server_start\n        ;;\n*)      usage\n        exit $OCF_ERR_UNIMPLEMENTED\n        ;;\nesac\nexit $?\n\n\n\n", "num_lines": 475}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ndie() {\n\techo -e $* >&2\n\techo aborting.. >&2\n\texit 1\n}\n\ncanon() {\n\tcd $1\n\tCANON=$PWD\n\tcd -\n}\n\ncanon $(dirname $0)\nMYDIR=$CANON\n\nwhile [ ${#*} -gt 1 ]; do\n        case \"$1\" in\n                -t)\n                        shift;\n                        TREE=$1\n                        ;;\n                -s)\n                        shift;\n                        SERIES=$1\n                        ;;\n                *)\n\t\t\tdie \"unknown argument $1\"\n                        break;\n                        ;;\n        esac\n        shift;\ndone\n\n[ -z \"$TREE\" -o -z \"$SERIES\" ] && die \"I need a tree and series:\\n\\t$0 -t kernel_dir -s series_name\"\n[ ! -d $TREE ] && die \"kernel tree '$TREE' isn't a directory\"\nSERIES=$(basename $SERIES)\n[ ! -f $MYDIR/series/$SERIES ] && die \"no series file '$SERIES'\"\n\ncanon $TREE\nTREE=$CANON\n\n# patch scripts wants a relative path from the linux tree to\n# its patch pile :(\n\nMY=$(echo $MYDIR | sed -e 's_^/__')\nTR=$(echo $TREE | sed -e 's_^/__')\n\nwhile true ; do\n\tM=$(echo $MY | cut -d/ -f 1)\n\tT=$(echo $TR | cut -d/ -f 1)\n\n\tif [ $M != $T ]; then\n\t\tbreak;\n\tfi\n\n\tMY=$(echo $MY | cut -d/ -f 2-)\n\tTR=$(echo $TR | cut -d/ -f 2-)\ndone\n\n[ $MY == $MYDIR ] && die \"bad! $MY == $MYDIR\" \n\nREVERSE=$(revpath $TR)${MY}\nABSINO=$(stat $MYDIR | awk '($3 == \"Inode:\") {print $4}')\nREVINO=`(cd $TREE ; stat $REVERSE | awk '($3 == \"Inode:\") {print $4}')`\n\n[ $ABSINO != $REVINO ] && die \"inodes differ, my reverse path is bad?\"\n\necho export PATCHSCRIPTS_LIBDIR=$REVERSE\n\ncd $TREE\nln -sf $REVERSE/series/$SERIES series\n\nPATH_ELEMENTS=$(echo $PATH | sed -e 's/:/ /g')\n\nNEW_PATH=$MYDIR/scripts\n\nfor p in $PATH_ELEMENTS; do\n\tif echo $p | grep kernel_patches/scripts > /dev/null 2>&1 ; then\n\t\tcontinue;\n\tfi\n\tNEW_PATH=\"$NEW_PATH:$p\"\ndone\n\necho export PATH=$NEW_PATH\n\necho \"'$TREE' successfully setup\" >&2\n", "num_lines": 89}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# CDDL HEADER START\n#\n# The contents of this file are subject to the terms of the\n# Common Development and Distribution License Version 1.0 (CDDL-1.0).\n# You can obtain a copy of the license from the top-level file\n# \"OPENSOLARIS.LICENSE\" or at <http://opensource.org/licenses/CDDL-1.0>.\n# You may not use this file except in compliance with the license.\n#\n# CDDL HEADER END\n#\n\n#\n# Copyright (c) 2018, Intel Corporation.\n#\n\n#\n# Adjust lustre service degrade state in response to a statechange\n#\n# ZEVENT_SUBCLASS: 'statechange'\n# POOL HEALTH: status from \"zpool list health\" (either ONLINE or DEGRADED)\n#\n# depends on lctl(1)\n#\n# Exit codes:\n#   0: normal exit\n#   1: lctl missing\n#   2: zpool missing\n#   3: zfs missing\n#   4: Pool status neither \"ONLINE\" nor \"DEGRADED\n\n[ -f \"${ZED_ZEDLET_DIR}/zed.rc\" ] && . \"${ZED_ZEDLET_DIR}/zed.rc\"\n. \"${ZED_ZEDLET_DIR}/zed-functions.sh\"\n\nLCTL=${LCTL:-/usr/sbin/lctl}\nZPOOL=${ZPOOL:-/usr/sbin/zpool}\nZFS=${ZFS:-/usr/sbin/zfs}\n\nzed_check_cmd \"$LCTL\" || exit 1\nzed_check_cmd \"$ZPOOL\" || exit 2\nzed_check_cmd \"$ZFS\" || exit 3\n\n#\n# sync_degrade_state (dataset, state)\n#\nsync_degrade_state()\n{\n\tlocal dataset=\"$1\"\n\tlocal state=\"$2\"\n\tlocal service=$($ZFS list -H -o lustre:svname ${dataset})\n\n\tzed_log_msg \"Lustre:sync_degrade_state pool:${dataset} degraded:${state}\"\n\n\tif [ -n \"${service}\" ] && [ \"${service}\" != \"-\" ] ; then\n\t\tlocal current=$($LCTL get_param -n obdfilter.${service}.degraded)\n\n\t\tif [ \"${current}\" != \"${state}\" ] ; then\n\t\t\t$LCTL set_param obdfilter.${service}.degraded=${state}\n\t\tfi\n\tfi\n}\n\n#\n# use pool state as deciding factor\n#\nPOOL_STATE=$($ZPOOL list -H -o health ${ZEVENT_POOL})\n\nif [ \"${POOL_STATE}\" == \"ONLINE\" ] ; then\n\tMODE=\"0\"\nelif [ \"${POOL_STATE}\" == \"DEGRADED\" ] ; then\n\tMODE=\"1\"\nelse\n\texit 4\nfi\n\n#\n# visit target pool's datasets and adjust lustre service degrade mode\n#\nread -r -a DATASETS <<< \\\n\t$($ZFS get -rH -s local -t filesystem -o name lustre:svname ${ZEVENT_POOL})\n\nfor dataset in \"${DATASETS[@]}\" ; do\n\tsync_degrade_state \"${dataset}\" \"${MODE}\"\ndone\n\nexit 0\n", "num_lines": 88}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# System Profiling Script\n\nTESTS=\"oprofile iostat vmstat proc_dump\"\n\n# common parameters\nexport OUTPUTDIR=/home/op\nexport KERNELDIR=/usr/src/linux\nexport LUSTREDIR=/usr/src/lustre\nexport PORTALSDIR=/usr/src/portals\nNAL=socknal\n\n# Params for OPROFILE\n#CTR0_EVENT=CPU_CLK_UNHALTED\nCTR0_COUNT=10000\n\n# for intel Petium 4 onwards... Also requires Unit Mask\nCTR0_EVENT=GLOBAL_POWER_EVENTS\nCTR0_UNIT_MASK=0x01\n\n# Params for VMSTAT\nVM_SAMPLING=1\n\n# Params for IOSTAT\nIO_SAMPLING=1\n\n# Params for PROC DUMP\nexport PROC_SAMPLING=2\n\noprofile_start() {\n\techo \"$(date +%T): oprofile started....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\top_start --ctr0-event=$CTR0_EVENT --ctr0-count=$CTR0_COUNT --ctr0-unit-mask=$CTR0_UNIT_MASK --vmlinux=${KERNELDIR}/vmlinux\n\tmkdir -p ${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/{obdclass,obdecho,osc,ptlrpc,extN,obdfilter,ost,mdc,mds4mds,mds4mds_extN,llite,portals,$NAL}\n\tmkdir -p ${OUTPUTDIR}/${HOSTNAME}/oprofile/profiling\n}\n\niostat_start() {\n\techo \"$(date +%T): iostat started....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\tmkdir ${OUTPUTDIR}/${HOSTNAME}/iostat\n\tiostat $IO_SAMPLING > $OUTPUTDIR/$HOSTNAME/iostat/iostat.op &\n\tPID=$!\n\techo $PID > $OUTPUTDIR/$HOSTNAME/tmp/iostat.pid\n}\n\nvmstat_start() {\n\techo $OUTPUTDIR;\n\techo \"$(date +%T): vmstat started....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\tmkdir ${OUTPUTDIR}/${HOSTNAME}/vmstat\n\tvmstat $VM_SAMPLING > $OUTPUTDIR/$HOSTNAME/vmstat/vmstat.op &\n\tPID=$!\n\techo $PID > $OUTPUTDIR/$HOSTNAME/tmp/vmstat.pid\n}\n\nproc_dump_start() {\n\techo \"$(date +%T): proc dump started....\" >> $OUTPUTDIR/$HOSTNAME/summary\n\tsh -c '\n\t\tCTRFILE=/$OUTPUTDIR/$HOSTNAME/tmp/running.$$.pid;\n\t\techo $$ > ${CTRFILE};\n\t\twhile [ -f $CTRFILE ]; do\n\t\t\tcat /proc/meminfo >> $OUTPUTDIR/$HOSTNAME/meminfo;\n\t\t\tcat /proc/interrupts >> $OUTPUTDIR/$HOSTNAME/interrupts;\n\t\t\tcat /proc/net/dev >> $OUTPUTDIR/$HOSTNAME/net-dev;\n\t\t\tsleep ${PROC_SAMPLING};\n\t\tdone;\n\t\t' &\n\tCTRFILE=/tmp/running.$!.pid\n\techo \"proc_dump_ctrl $CTRFILE\" >> /tmp/prof-ctrl\n}\n\noprofile_stop() {\n\top_dump\n\top_stop\n\n\techo \"$(date +%T): oprofile stopped....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\n\tfor i in obdclass obdecho osc ptlrpc extN obdfilter mds ost mdc llite\n\tdo\n\t\toprofpp -l ${LUSTREDIR}/${i}/${i}.o >  ${OUTPUTDIR}/${HOSTNAME}/oprofile/profiling/${i}.prof 2>/dev/null\n\tdone\n\n\toprofpp -l ${LUSTREDIR}/mds/mds_extN.o > ${OUTPUTDIR}/${HOSTNAME}/oprofile/profiling/mds_extN.prof 2>/dev/null\n\toprofpp -l ${PORTALSDIR}/linux/oslib/portals.o > ${OUTPUTDIR}/${HOSTNAME}/oprofile/profiling/portals.prof 2>/dev/null\n\toprofpp -l ${PORTALSDIR}/linux/${NAL}/k${NAL}.o > ${OUTPUTDIR}/${HOSTNAME}/oprofile/profiling/k${NAL}.prof 2>/dev/null\n\n\tfor i in obdclass obdecho osc ptlrpc extN obdfilter ost mdc llite\n\tdo\n\t\top_to_source --source-dir=${LUSTREDIR}/${i}/ --output-dir=${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/${i}/ ${LUSTREDIR}/${i}/${i}.o 2>/dev/null\n\tdone\n\n\top_to_source --source-dir=${LUSTREDIR}/mds/ --output-dir=${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/mds4mds/ ${LUSTREDIR}/mds/mds.o 2>/dev/null\n\top_to_source --source-dir=${LUSTREDIR}/mds/ --output-dir=${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/mds4mds_extN/  ${LUSTREDIR}/mds/mds_extN.o 2>/dev/null\n\n\top_to_source --source-dir=${PORTALSDIR}/linux/oslib/ --output-dir=${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/portals ${PORTALSDIR}/linux/oslib/portals.o 2>/dev/null\n\top_to_source --source-dir=${PORTALSDIR}/linux/${NAL}/ --output-dir=${OUTPUTDIR}/${HOSTNAME}/oprofile/prof_source/${NAL} ${PORTALSDIR}/linux/${NAL}/k${NAL}.o 2>/dev/null\n\top_time -l > ${OUTPUTDIR}/${HOSTNAME}/oprofile/globalprofile 2>/dev/null\n}\n\niostat_stop() {\n\techo \"$(date +%T): iostat stopped....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\tPID=$(cat $OUTPUTDIR/$HOSTNAME/tmp/iostat.pid)\n\tkill $PID\n}\n\nvmstat_stop() {\n\techo \"$(date +%T): vmstat stopped....\" >>  $OUTPUTDIR/$HOSTNAME/summary\n\tPID=$(cat $OUTPUTDIR/$HOSTNAME/tmp/vmstat.pid)\n\tkill $PID\n}\n\noprofile_dump() {\n\top_dump;\n}\n\nproc_dump_stop() {\n\techo \"$(date +%T): proc dump stopped....\" >> $OUTPUTDIR/$HOSTNAME/summary\n\tCTRFILE=$(cat /tmp/prof-ctrl | awk '$1 == \"prof_dump_ctrl\" {print $2}')\n\trm -f $CTRFILE\n}\n\ncase \"$1\" in\n\tstart)\n\t\tshift;\n\t\twhile [ ${#*} -gt 1 ]; do\n\t\t\tcase \"$1\" in\n\t\t\t\t-k)\n\t\t\t\t\tshift;\n\t\t\t\t\tKERNELDIR=$1;\n\t\t\t\t\t;;\n\t\t\t\t-l)\n\t\t\t\t\tshift;\n\t\t\t\t\tLUSTREDIR=$1;\n\t\t\t\t\t;;\n\t\t\t\t-p)\n\t\t\t\t\tshift;\n\t\t\t\t\tPORTALSDIR=$1;\n\t\t\t\t\t;;\n\t\t\t\t-o)\n\t\t\t\t\tshift;\n\t\t\t\t\tOUTPUTDIR=$1;\n\t\t\t\t\t;;\n\t\t\t\t*)\n\t\t\t\t\techo unrecognized option $1\n\t\t\t\t\tbreak;\n\t\t\t\t\t;;\n\t\t\tesac\n\t\t\tshift;\n\t\tdone\n\n\t\techo \"kerneldir $KERNELDIR\" > /tmp/prof-ctrl\n\t\techo -e \"\\nlustredir $LUSTREDIR\" >> /tmp/prof-ctrl\n\t\techo -e \"\\nportalsdir $PORTALSDIR\" >> /tmp/prof-ctrl\n\t\techo -e \"\\noutputdir $OUTPUTDIR\" >> /tmp/prof-ctrl\n\n\t\tif [ -d ${OUTPUTDIR}/${HOSTNAME} ]; then\n\t\t\techo \"Output already exists\"\n\t\t\techo \"Please take backup and remove it\"\n\t\t\texit 1\n\t\tfi\n\n\t\tmkdir -p ${OUTPUTDIR}/${HOSTNAME}\n\t\techo -e \"Profiling started on $HOSTNAME\" >  ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\techo -e \"\\n\\nModules Listing on $HOSTNAME\" >> ${OUTPUTDIR}/${HOSTNAME}/summary \n\t\t/sbin/lsmod >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\techo -e \"\\n\\nKernel : \" >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\tuname -a  >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\techo -e \"\\n\\nPCI Devices : \"  >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\tlspci -t -v  >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\techo -e \"\\n\\nTests carried out \" >> ${OUTPUTDIR}/${HOSTNAME}/summary\n\t\tmkdir $OUTPUTDIR/$HOSTNAME/tmp\n\n\t\tfor test in $TESTS; do\n\t\t\t${test}_start;\n\t\tdone\n\t;;\n\tstop)\n\t\tKERNELDIR=$(cat /tmp/prof-ctrl | awk '$1 == \"kerneldir\" {print $2}')\n\t\tLUSTREDIR=$(cat /tmp/prof-ctrl | awk '$1 == \"lustredir\" {print $2}')\n\t\tPORTALSDIR=$(cat /tmp/prof-ctrl | awk '$1 == \"portalsdir\" {print $2}')\n\t\tOUTPUTDIR=$(cat /tmp/prof-ctrl | awk '$1 == \"outputdir\" {print $2}')\n\n\t\tfor test in $TESTS; do\n\t\t\t${test}_stop;\n\t\tdone\n\n\t\trm -rf ${OUTPUTDIR}/$HOSTNAME/tmp\n\t\ttar -cf ${OUTPUTDIR}/${HOSTNAME}.tar  ${OUTPUTDIR}/${HOSTNAME}\n\t\techo \"Dumped results in ${OUTPUTDIR}/${HOSTNAME}.tar\"\n\t;;\n\tdump)\n\t\tif \"oprofile\" in $TESTS; then\n\t\t\toprofile_dump;\n\t\tfi\n\t;;\n\tclean)\n\t\tOUTPUTDIR=$(cat /tmp/prof-ctrl | awk '$1 == \"outputdir\" {print $2}')\n\n\t\techo Deleting directory $OUTPUTDIR/$HOSTNAME ...\n\t\trm -rf $OUTPUTDIR/$HOSTNAME\n\t\techo Deleting file $OUTPUTDIR/${HOSTNAME}.tar ...\n\t\trm -rf $OUTPUTDIR/${HOSTNAME}.tar\n\t\techo Deleting oprofile samples ...\n\t\trm -f /var/lib/oprofile/samples/*\n\t\trm -f /tmp/prof-ctrl\n\t;;\n\t*)\n\t\techo $\"Usage : $0 {start|stop|dump|clean} [OPTIONS]\";\n\t\techo $\"OPTIONS :\"\n\t\techo $\" -l lustre_dir\"\t\n\t\techo $\" -p portals_dir\"\t\n\t\techo $\" -k kernel_dir\"\t\n\t\techo $\" -o output_dir\"\t\n\t\texit 1\nesac\n\nexit 0\n", "num_lines": 217}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# usage: acceptance-small.sh [test list]\n#\tif no tests are specified, they are taken from test-groups/regression\n#\tif {TEST_NAME}=no is set, that test script is skipped\nDEFAULT_SUITES=\"${@:-$ACC_SM_ONLY}\"\nDEFAULT_SUITES=\"${DEFAULT_SUITES:-$(cat $LUSTRE/tests/test-groups/regression)}\"\nfor SUB in $DEFAULT_SUITES; do\n\tENV=$(echo $SUB | tr \"[:lower:]-\" \"[:upper:]_\")\n\t[ \"$(eval echo \\$$ENV)\" = \"no\" ] && continue\n\tSUITES=\"$SUITES $SUB\"\ndone\nsh auster -r -R -v -f ${NAME:-lustre} $SUITES\n", "num_lines": 14}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nset -evx\n\nMOUNT=${MOUNT:-/mnt/lustre}\nDIR=${DIR:-$MOUNT}\nSRC=${SRC:-`dirname $0`/../..}\nexport CC=${CC:-gcc}\nwhile date; do\n\tfor i in lustre; do\n\t\tTGT=$DIR/$i\n\t\t[ -d $TGT ] || cp -av $SRC/$i/ $TGT\n\t\tmake -C $TGT clean\n\t\tmake -C $TGT -j2\n\t\tmake -C $TGT clean\n\tdone\ndone\n", "num_lines": 17}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# run tests on different directories at the same time\n#\n\nset -e\n\nSRCDIR=$(cd $(dirname $0); echo $PWD)\nPATH=$PWD/$SRCDIR:$SRCDIR:$SRCDIR/../utils:$PATH\n\nSAVE_PWD=$PWD\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nPARALLEL_RUNS=${PARALLEL_RUNS:-2}\nFAIL_ON_ERROR=false\n\ncheck_and_setup_lustre\n\nbuild_test_filter\n\nDIR=${DIR:-$MOUNT}\n\nORIGIN_DIR=$DIR\n\nprepare_running_directories()\n{\n\tlocal mdtidx\n\tlocal rc=0\n\tlocal i\n\n\tfor i in $(seq $PARALLEL_RUNS); do\n\t\trm -rf $ORIGIN_DIR/dir$i\n\t\tif [ $MDSCOUNT -gt 1 ]; then\n\t\t\tmdtidx=$((i % MDSCOUNT))\n\t\t\t$LFS mkdir -i $mdtidx $ORIGIN_DIR/dir$i || rc=$?\n\t\telse\n\t\t\tmkdir -p $ORIGIN_DIR/dir$i\n\t\tfi\n\n\t\tif [ $rc != 0 ]; then\n\t\t\techo \"can not create dir$i\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\treturn $rc\n}\n\nprepare_running_directories || error \"Can not create running directories\"\n\ncleanup_running_directories()\n{\n\tlocal i\n\tlocal rc=0\n\n\tfor i in $(seq $PARALLEL_RUNS); do\n\t\trm -rf $ORIGIN_DIR/dir$i || rc=$?\n\tdone\n\n\treturn $rc\n}\n\ntest_sanity()\n{\n\t[ ! -f sanity.sh ] && skip_env \"No sanity.sh skipping\"\n\n\tlocal index\n\tlocal pid\n\tlocal rpids\n\tlocal rc=0\n\tlocal rrc=0\n\n\tfor index in $(seq $PARALLEL_RUNS); do\n\t\tDIR=$ORIGIN_DIR/dir${index} PARALLEL=yes \\\n\t\tEXT2_DEV=\"$TMP/SANITY.LOOP_${index}\" \\\n\t\tLOGDIR=\"${LOGDIR}_${index}\" YAML_LOG=\"\" sh sanity.sh &\n\t\tpid=$!\n\t\techo start sanity: $pid\n\t\trpids=\"$rpids $pid\"\n\tdone\n\n\techo sanity pids: $rpids\n\tfor pid in $rpids; do\n\t\twait $pid\n\t\trc=$?\n\t\techo \"pid=$pid rc=$rc\"\n\t\tif [ $rc != 0 ]; then\n\t\t\trrc=$((rrc + 1))\n\t\tfi\n\tdone\n\treturn $rrc\n}\n\nrun_test sanity \"Run sanity parallel on different directories at the same time\"\n\ncleanup_running_directories || error \"unlink running directories\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 106}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\nALWAYS_EXCEPT=${ALWAYS_EXCEPT:-\"$DOM_PERFORMANCE_EXCEPT\"}\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n\n. $LUSTRE/tests/test-framework.sh\n\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nSAVED_FAIL_ON_ERROR=$FAIL_ON_ERROR\nFAIL_ON_ERROR=false\n\nSAVED_DEBUG=$($LCTL get_param -n debug 2> /dev/null)\n\n\n. $LUSTRE/tests/functions.sh\nbuild_test_filter\ncheck_and_setup_lustre\n\n# if MACHINEFILE set and exists -- use it\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh)-$(hostname).machines}\nclients=${CLIENTS:-$HOSTNAME}\ngenerate_machine_file $clients $MACHINEFILE ||\n\terror \"Failed to generate machine file\"\n\nDP_DIO=${DP_DIO:-\"no\"}\n\nDOM_SIZE=${DOM_SIZE:-\"1M\"}\nDP_OSC=\"mdc\"\n\nDP_NORM=$DIR/dp_norm\nDP_DOM=$DIR/dp_dom\nDP_DOM_DNE=$DIR/dp_dne\nDP_STATS=${DP_STATS:-\"no\"}\n\nif $DO_CLEANUP; then\n\trm -rf $DIR/*\nelse\n\trm -rf $DP_NORM $DP_DOM $DP_DOM_DNE\nfi\n\n# total number of files\nDP_FNUM=${DP_FNUM:-16384}\n# number of threads\nDP_NUM=${DP_NUM:-4}\n\n# 1 stripe for normal files\nmkdir -p $DP_NORM\n$LFS setstripe -c 2 $DP_NORM ||\n\terror \"Cannot create test directory for ordinary files\"\n\nif [[ $MDSCOUNT -gt 1 ]] ; then\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DP_DOM_DNE ||\n\t\terror_noexit \"Cannot create striped directory\"\n\t$LFS setstripe -E ${DOM_SIZE} -L mdt -E EOF $DP_DOM_DNE ||\n\t\terror_noexit \"Cannot create test directory for dom files\"\nfi\n\nmkdir -p $DP_DOM\n$LFS setstripe -E ${DOM_SIZE} -L mdt -E EOF $DP_DOM ||\n\terror \"Cannot create test directory for dom files\"\n\ndp_clear_stats() {\n\tlocal cli=$1\n\n\t$LCTL set_param -n osc.*.stats=0\n\t$LCTL set_param -n mdc.*.stats=0\n\t$LCTL set_param -n ${cli}.*.${cli}_stats=0\n\t$LCTL set_param -n ${cli}.*.rpc_stats=0\n\t$LCTL set_param -n llite.*.read_ahead_stats=0\n\t$LCTL set_param -n llite.*.unstable_stats=0\n}\n\ndp_collect_stats() {\n\tlocal cli=$1\n\n\tsync;sync\n\techo ----- MDC RPCs: $(calc_stats mdc.*.stats req_active)\n\techo ----- OSC RPCs: $(calc_stats osc.*.stats req_active)\n\n\tif [ \"x$DP_STATS\" != \"xyes\" ] ; then\n\t\treturn 0\n\tfi\n\n\t$LCTL get_param ${cli}.*.${cli}_stats\n\t$LCTL get_param ${cli}.*.rpc_stats\n\t# for OSC get both OSC and MDC stats\n\tif [ $cli == \"osc\" ] ; then\n\t\t$LCTL get_param mdc.*.stats\n\tfi\n\t$LCTL get_param ${cli}.*.stats\n\t$LCTL get_param ${cli}.*.unstable_stats\n\t$LCTL get_param ${cli}.*.${cli}_cached_mb\n\t$LCTL get_param llite.*.read_ahead_stats\n}\n\ndp_setup_test() {\n\tlocal cli=$1\n\n\tcancel_lru_locks $cli\n\t### drop all debug except critical\n\t$LCTL set_param -n debug=\"error warning console emerg\"\n\tdp_clear_stats $cli\n}\n\ndp_run_cmd() {\n\tlocal cmd=$1\n\tlocal cmdlog=$TMP/dp_cmd.log\n\tlocal rc\n\n\tdp_setup_test $DP_OSC\n\tif ! grep -qw \"$MOUNT\" /proc/mounts ; then\n\t\techo \"!!!!! Lustre is not mounted !!!!!, aborting\"\n\t\treturn 0\n\tfi\n\n\techo \"## $cmd\" | awk '{ if (NR==1) {gsub(/[ \\t\\r\\n]+/, \" \"); \\\n\t\t\t\tgsub(/\\|.*$/, \"\"); print }}'\n\techo \"## $(date +'%F %H:%M:%S'): START\"\n\teval $cmd 2>&1 | tee $cmdlog || true\n\n\trc=${PIPESTATUS[0]}\n\tif [ $rc -eq 0 ] && grep -q \"p4_error:\" $cmdlog ; then\n\t\trc=1\n\tfi\n\n\tdp_collect_stats $DP_OSC\n\tremount_client $DIR > /dev/null\n\treturn $rc\n}\n\nrun_MDtest() {\n\tif ! which mdtest > /dev/null 2>&1 ; then\n\t\tskip_env \"Mdtest is not installed, skipping\"\n\tfi\n\n\tlocal mdtest=$(which mdtest)\n\n\tlocal TDIR=${1:-$MOUNT}\n\tlocal th_num=$((DP_FNUM * 2 / DP_NUM))\n\tlocal bsizes=\"8192\"\n\n\tchmod 0777 $TDIR\n\n\t[ \"$SLOW\" = \"yes\" ] && bsizes=\"4096 32768\"\n\n\tfor bsize in $bsizes ; do\n\t\tdp_run_cmd \"mpi_run -np $DP_NUM $mdtest -i 3 -I $th_num -F \\\n\t\t\t-z 1 -b 1 -L -u -w $bsize -R -d $TDIR\"\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"MDtest failed, aborting\"\n\t\tfi\n\tdone\n\n\trm -rf $TDIR/*\n\treturn 0\n}\n\nrun_SmallIO() {\n\tlocal TDIR=${1:-$DIR}\n\tlocal count=$DP_FNUM\n\n\tlocal MIN=$((count * 16))\n\tlocal mdssize=$(mdssize_from_index $TDIR 0)\n\t[ $mdssize -le $MIN ] && count=$((mdssize / 16))\n\n\tdp_run_cmd \"createmany -o $TDIR/file- $count | grep 'total:'\"\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"File creation failed, aborting\"\n\tfi\n\n\tdp_run_cmd \"statmany -s $TDIR/file- $count $((count * 5)) |\n\t\tgrep 'total:'\"\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"File stat failed, aborting\"\n\tfi\n\n\tfor opc in w a r ; do\n\t\tdp_run_cmd \"smalliomany -${opc} $TDIR/file- $count 300 |\n\t\t\tgrep 'total:'\"\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"SmallIO -${opc} failed, aborting\"\n\t\tfi\n\n\tdone\n\n\tdp_run_cmd \"unlinkmany $TDIR/file- $count | grep 'total:'\"\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"SmallIO failed, aborting\"\n\tfi\n\n\treturn 0\n}\n\nrun_IOR() {\n\tif ! which IOR > /dev/null 2>&1 ; then\n\t\tskip_env \"IOR is not installed, skipping\"\n\tfi\n\n\tlocal IOR=$(which IOR)\n\tlocal iter=$((DP_FNUM / DP_NUM))\n\tlocal direct=\"\"\n\n\tif [ \"x$DP_DIO\" == \"xyes\" ] ; then\n\t\tdirect=\"-B\"\n\tfi\n\n\tlocal TDIR=${1:-$MOUNT}\n\n\tchmod 0777 $TDIR\n\n\t# for DoM large files (beyond the DoM size) use\n\t# DOM_SIZE=1M :\n\t#     bsize=\"4096 \" - 4Mb\n\t#     nsegments=$((128 * 1024))\n\t# DOM_SIZE=64k :\n\t#     bsize=\"1024 \" - 1Mb\n\t#     nsegments=$((32 * 1024))\n\tlocal bsizes=${BSIZES:-\"4 32\"}\n\tlocal nsegments=${NSEGMENTS:-128}\n\t[ \"$SLOW\" = \"no\" ] && bsizes=\"8\"\n\n\tfor bsize in $bsizes ; do\n\t\tsegments=$((nsegments / bsize))\n\n\t\tdp_run_cmd \"mpi_run -np $DP_NUM $IOR \\\n\t\t\t-a POSIX -b ${bsize}K -t ${bsize}K -o $TDIR/ -k \\\n\t\t\t-s $segments -w -r -i $iter -F -E -z -m -Z $direct\" |\n\t\t\tawk '($1 !~ /^(write|read|access)$/) || NF>12 {print}'\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"IOR write test for ${bsize}K failed, aborting\"\n\t\tfi\n\n\t\t# check READ performance only (no cache)\n\t\tdp_run_cmd \"mpi_run -np $DP_NUM $IOR \\\n\t\t\t-a POSIX -b ${bsize}K -t ${bsize}K -o $TDIR/ -X 42\\\n\t\t\t-s $segments -r -i $iter -F -E -z -m -Z $direct\" |\n\t\t\tawk '($1 !~ /^(read|access|remove)$/) || NF>12 {print}'\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"IOR read test for ${bsize}K failed, aborting\"\n\t\tfi\n\n\tdone\n\trm -rf $TDIR/*\n\treturn 0\n}\n\nrun_Dbench() {\n\tif ! which dbench > /dev/null 2>&1 ; then\n\t\tskip_env \"Dbench is not installed, skipping\"\n\tfi\n\n\tlocal TDIR=${1:-$MOUNT}\n\n\tif [ \"x$DP_DOM_DNE\" == \"x$TDIR\" ] ; then\n\t\techo \"dbench uses subdirs, skipping for DNE dir\"\n\t\treturn 0\n\tfi\n\n\tdp_run_cmd \"dbench -D $TDIR $DP_NUM | egrep -v 'warmup|execute'\"\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"Dbench failed, aborting\"\n\tfi\n\n\trm -rf $TDIR/*\n\treturn 0\n}\n\nrun_FIO() {\n\t# https://github.com/axboe/fio/archive/fio-2.8.zip\n\tif ! which fio > /dev/null 2>&1 ; then\n\t\tskip_env \"No FIO installed, skipping\"\n\tfi\n\n\tlocal fnum=128 # per thread\n\tlocal total=$((fnum * DP_NUM)) # files in all threads\n\tlocal loops=$((DP_FNUM / total)) # number of loops\n\tlocal direct=\"\"\n\tlocal output=\"\"\n\n\tif [ $loops -eq 0 ] ; then\n\t\tloops=1\n\tfi\n\n\tif [ \"x$DP_DIO\" == \"xyes\" ] ; then\n\t\tdirect=\"--direct=1\"\n\telse\n\t\tdirect=\"--buffered=1 --bs_unaligned=1\"\n\tfi\n\n\tif [ \"x$DP_STATS\" != \"xyes\" ] ; then\n\t\toutput=\"--minimal\"\n\tfi\n\n\tlocal TDIR=${1:-$MOUNT}\n\tbase_cmd=\"fio --name=smallio --ioengine=posixaio $output \\\n\t\t  --iodepth=$((DP_NUM * 4)) --directory=$TDIR \\\n\t\t  --nrfiles=$fnum --openfiles=10000 \\\n\t\t  --numjobs=$DP_NUM --filesize=64k --lockfile=readwrite\"\n\n\tdp_run_cmd \"$base_cmd --create_only=1\" > /dev/null\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"FIO file creation failed, aborting\"\n\tfi\n\n\tlocal bsizes=\"8\"\n\t[ \"$SLOW\" = \"yes\" ] && bsizes=\"4 32\"\n\n\tfor bsize in $bsizes ; do\n\t\tlocal write_cmd=\"$base_cmd --bs=${bsize}k --rw=randwrite \\\n\t\t\t$direct --file_service_type=random --randrepeat=1 \\\n\t\t\t --norandommap --group_reporting=1 --loops=$loops\"\n\t\tif [ \"x$DP_STATS\" != \"xyes\" ] ; then\n\t\t\tdp_run_cmd \"$write_cmd | awk -F\\; '{printf \\\"WRITE: \\\n\t\t\t\tBW %dKiB/sec, IOPS %d, lat (%d/%d/%d)usec\\n\\\", \\\n\t\t\t\t\\$48, \\$49, \\$53, \\$57, \\$81}'\"\n\t\telse\n\t\t\tdp_run_cmd \"$write_cmd\"\n\t\tfi\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"FIO write test with ${bsize}k failed, aborting\"\n\t\tfi\n\n\t\tlocal read_cmd=\"$base_cmd --bs=${bsize}k --rw=randread \\\n\t\t\t$direct --file_service_type=random --randrepeat=1 \\\n\t\t\t --norandommap --group_reporting=1 --loops=$loops\"\n\t\tif [ \"x$DP_STATS\" != \"xyes\" ] ; then\n\t\t\tdp_run_cmd \"$read_cmd | awk -F\\; '{printf \\\"READ : \\\n\t\t\t\tBW %dKiB/sec, IOPS %d, lat (%d/%d/%d)usec\\n\\\", \\\n\t\t\t\t\\$7, \\$8, \\$12, \\$16, \\$40}'\"\n\t\telse\n\t\t\tdp_run_cmd \"$read_cmd\"\n\t\tfi\n\t\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t\terror \"FIO read test with ${bsize}k failed, aborting\"\n\t\tfi\n\tdone\n\trm -rf $TDIR/*\n\treturn 0\n}\n\nrun_compbench() {\n\tlocal compilebench\n\tif [ x$cbench_DIR = x ]; then\n\t\tcompilebench=$(which compilebench 2> /dev/null)\n\telse\n\t\tcd $cbench_DIR\n\t\t[ -x compilebench ] ||\n\t\t\tskip_env \"compilebench is missing in $cbench_DIR\"\n\t\tcompilebench=compilebench\n\tfi\n\n\t[ x$compilebench != x ] ||\n\t\tskip_env \"Compilebench is not installed, skipping\"\n\n\tlocal TDIR=${1:-$MOUNT}\n\n\tdp_run_cmd \"$compilebench -D $TDIR -i 2 -r 2 --makej\"\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"Compilebench failed, aborting\"\n\tfi\n\n\trm -rf $TDIR/*\n}\n\ndp_test_run() {\n\tlocal test=$1\n\tlocal facets=$(get_facets MDS)\n\tlocal nodes=$(comma_list $(mdts_nodes))\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params $facets \"mdt.*.dom_lock\" >> $p\n\n\tprintf \"\\n##### $test: DoM files\\n\"\n\tdo_nodes $nodes \"lctl set_param -n mdt.*.dom_lock=1\"\n\tDP_OSC=\"mdc\"\n\trun_${test} $DP_DOM\n\n\tif [ -d $DP_DOM_DNE ] ; then\n\t\tprintf \"\\n##### $test: DoM files + DNE\\n\"\n\t\tDP_OSC=\"mdc\"\n\t\trun_${test} $DP_DOM_DNE\n\tfi\n\n\tprintf \"\\n##### $test: OST files\\n\"\n\tDP_OSC=\"osc\"\n\trun_${test} $DP_NORM\n\n\trestore_lustre_params < $p\n\trm -f $p\n}\n\ntest_smallio() {\n\tdp_test_run SmallIO\n}\nrun_test smallio \"Performance comparision: smallio\"\n\ntest_mdtest() {\n\tdp_test_run MDtest\n}\nrun_test mdtest \"Performance comparision: mdtest\"\n\ntest_IOR() {\n\tdp_test_run IOR\n}\nrun_test IOR \"Performance comparision: IOR\"\n\ntest_dbench() {\n\tdp_test_run Dbench\n}\nrun_test dbench \"Performance comparision: dbench\"\n\ntest_fio() {\n\tdp_test_run FIO\n}\nrun_test fio \"Performance comparision: FIO\"\n\ntest_compbench() {\n\tdp_test_run compbench\n}\nrun_test compbench \"Performance comparision: compilebench\"\n\nFAIL_ON_ERROR=$SAVED_FAIL_ON_ERROR\n$LCTL set_param -n debug=\"$SAVED_DEBUG\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 442}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Simple function used by run_*.sh scripts\n\nassert_env() {\n    local failed=\"\"\n    for name in $@; do\n        if [ -z \"${!name}\" ]; then\n            echo \"$0: $name must be set\"\n            failed=1\n        fi\n    done\n    [ $failed ] && exit 1 || true\n}\n\n# lrepl - Lustre test Read-Eval-Print Loop.\n#\n# This function implements a REPL for the Lustre test framework.  It\n# doesn't exec an actual shell because the user may want to inspect\n# variables and use functions from the test framework.\nlrepl() {\n    local line\n    local rawline\n    local prompt\n\n    cat <<EOF\n        This is an interactive read-eval-print loop interactive shell\n        simulation that you can use to debug failing tests.  You can\n        enter most bash command lines (see notes below).\n\n        Use this REPL to inspect variables, set them, call test\n        framework shell functions, etcetera.\n\n        'exit' or EOF to exit this shell.\n\n        set \\$retcode to 0 to cause the assertion failure that\n        triggered this REPL to be ignored.\n\n        Examples:\n            do_facet ost1 lctl get_param ost.*.ost.threads_*\n            do_rpc_nodes \\$OSTNODES unload_modules\n\n        NOTES:\n            All but the last line of multi-line statements or blocks\n            must end in a backslash.\n\n            \"Here documents\" are not supported.\n\n            History is not supported, but command-line editing is.\n\nEOF\n\n    # Prompt escapes don't work in read -p, sadly.\n    prompt=\":${TESTNAME:-UNKNOWN}:$(uname -n):$(basename $PWD)% \"\n\n    # We use read -r to get close to a shell experience\n    while read -e -r -p \"$prompt\" rawline; do\n        line=\n        case \"$rawline\" in\n        # Don't want to exit-exit, just exit the REPL\n        exit) break;;\n        # We need to handle continuations, and read -r doesn't do\n        # that for us.  Yet we need read -r.\n        #\n        # We also use case/esac to compare lines read to \"*\\\\\"\n        # because [ \"$line\" = *\\\\ ] and variants of that don't work.\n        *\\\\) line=\"$rawline\"\n            while read -e -r -p '> ' rawline\n            do\n                line=\"$line\"$'\\n'\"$rawline\"\n                case \"$rawline\" in\n                # We could check for here documents by matching\n                # against *<<*, but who cares.\n                *\\\\) continue;;\n                *) break;;\n                esac\n            done\n            ;;\n        *) line=$rawline\n        esac\n\n        case \"$line\" in\n        *\\\\) break;;\n        esac\n\n        # Finally!  Time to eval.\n        eval \"$line\"\n    done\n\n    echo $'\\n\\tExiting interactive shell...\\n'\n    return 0\n}\n\n# lassert - Lustre test framework assert\n#\n# Arguments: failure code, failure message, expression/statement\n#\n# lassert evaluates the expression given, and, if false, calls\n# error() to trigger test failure.  If REPL_ON_LASSERT is true then\n# lassert will call lrepl() to give the user an interactive shell.\n# If the REPL sets retcode=0 then the assertion failure will be\n# ignored.\nlassert() {\n    local retcode=$1\n    local msg=$2\n    shift 2\n\n    echo \"checking $* ($(eval echo \\\"\"$*\"\\\"))...\"\n    eval \"$@\" && return 0;\n\n    if ${REPL_ON_LASSERT:-false}; then\n        echo \"Assertion $retcode failed: $* (expanded: $(eval echo \\\"\"$*\"\\\"))\n$msg\"\n        lrepl\n    fi\n\n    error \"Assertion $retcode failed: $* (expanded: $(eval echo \\\"\"$*\"\\\"))\n$msg\"\n    return $retcode\n}\n\n# setmodopts- set module options for subsequent calls to load_modules\n#\n# Usage: setmodopts module_name new_value [var_in_which_to_save_old_value]\n#        setmodopts -a module_name new_value [var_in_which_to_save_old_value]\n#\n# In the second usage the new value is appended to the old.\nsetmodopts() {\n        local _append=false\n\n        if [ \"$1\" = -a ]; then\n            _append=true\n            shift\n        fi\n\n        local _var=MODOPTS_$1\n        local _newvalue=$2\n        local _savevar=$3\n        local _oldvalue\n\n        # Dynamic naming of variables is a pain in bash.  In ksh93 we could\n        # write \"nameref opts_var=${modname}_MODOPTS\" then assign directly\n        # to opts_var.  Associative arrays would also help, alternatively.\n        # Alas, we're stuck with eval until all distros move to a more recent\n        # version of bash.  Fortunately we don't need to eval unset and export.\n\n        if [ -z \"$_newvalue\" ]; then\n            unset $_var\n            return 0\n        fi\n\n        _oldvalue=${!var}\n        $_append && _newvalue=\"$_oldvalue $_newvalue\"\n        export $_var=\"$_newvalue\"\n        echo setmodopts: ${_var}=${_newvalue}\n\n        [ -n \"$_savevar\" ] && eval $_savevar=\\\"\"$_oldvalue\"\\\"\n}\n\nechoerr () { echo \"$@\" 1>&2 ; }\n\nsignaled() {\n    echoerr \"$(date +'%F %H:%M:%S'): client load was signaled to terminate\"\n\n    local PGID=$(ps -eo \"%c %p %r\" | awk \"/ $PPID / {print \\$3}\")\n    kill -TERM -$PGID\n    sleep 5\n    kill -KILL -$PGID\n}\n\nmpi_run () {\n    local mpirun=\"$MPIRUN $MPIRUN_OPTIONS --oversubscribe\"\n    local command=\"$mpirun $@\"\n    local mpilog=$TMP/mpi.log\n    local rc\n\n    if [ -n \"$MPI_USER\" -a \"$MPI_USER\" != root -a -n \"$mpirun\" ]; then\n        echo \"+ chmod 0777 $MOUNT\"\n        chmod 0777 $MOUNT\n        command=\"su $MPI_USER sh -c \\\"$command \\\"\"\n    fi\n\n    ls -ald $MOUNT\n    echo \"+ $command\"\n    eval $command 2>&1 | tee $mpilog || true\n\n    rc=${PIPESTATUS[0]}\n    if [ $rc -eq 0 ] && grep -q \"p4_error:\" $mpilog ; then\n       rc=1\n    fi\n    return $rc\n}\n\nnids_list () {\n\tlocal list\n\tlocal escape=\"$2\"\n\tfor i in ${1//,/ }; do\n\t\tif [ \"$list\" = \"\" ]; then\n\t\t\tlist=\"$i@$NETTYPE\"\n\t\telse\n\t\t\tlist=\"$list$escape $i@$NETTYPE\"\n\t\tfi\n\tdone\n\techo $list\n}\n\n# FIXME: all setup/cleanup can be done without rpc.sh\nlst_end_session () {\n    local verbose=false\n    [ x$1 = x--verbose ] && verbose=true\n\n    export LST_SESSION=`$LST show_session 2>/dev/null | awk -F \" \" '{print $5}'`\n    [ \"$LST_SESSION\" == \"\" ] && return\n\n\t$LST stop b\n    if $verbose; then\n        $LST show_error c s\n    fi\n    $LST end_session\n}\n\nlst_session_cleanup_all () {\n    local list=$(comma_list $(nodes_list))\n    do_rpc_nodes $list lst_end_session\n}\n\nlst_cleanup () {\n    lsmod | grep -q lnet_selftest && \\\n        rmmod lnet_selftest > /dev/null 2>&1 || true\n}\n\nlst_cleanup_all () {\n   local list=$(comma_list $(nodes_list))\n\n   # lst end_session needs to be executed only locally\n   # i.e. on node where lst new_session was called\n   lst_end_session --verbose\n   do_rpc_nodes $list lst_cleanup\n}\n\nlst_setup () {\n    load_module lnet_selftest\n}\n\nlst_setup_all () {\n    local list=$(comma_list $(nodes_list))\n    do_rpc_nodes $list lst_setup\n}\n\n###\n# short_hostname\n#\n# Passed a single argument, strips everything off following\n# and includes the first period.\n# client-20.lab.whamcloud.com becomes client-20\nshort_hostname() {\n  echo $(sed 's/\\..*//' <<< $1)\n}\n\n###\n# short_nodename\n#\n# Find remote nodename, stripped of any domain, etc.\n# 'hostname -s' is easy, but not implemented on all systems\nshort_nodename() {\n\tlocal rname=$(do_node $1 \"uname -n\" || echo -1)\n\tif [[ \"$rname\" = \"-1\" ]]; then\n\t\trname=$1\n\tfi\n\techo $(short_hostname $rname)\n}\n\nprint_opts () {\n    local var\n\n    echo OPTIONS:\n\n    for i in $@; do\n        var=$i\n        echo \"${var}=${!var}\"\n    done\n    [ -e $MACHINEFILE ] && cat $MACHINEFILE\n}\n\nis_lustre () {\n\t[ \"$(stat -f -c %T $1)\" = \"lustre\" ]\n}\n\nsetstripe_getstripe () {\n\tlocal file=$1\n\tshift\n\tlocal params=$@\n\n\tis_lustre $file || return 0\n\n\tif [ -n \"$params\" ]; then\n\t\t$LFS setstripe $params $file ||\n\t\t\terror \"setstripe $params failed\"\n\tfi\n\t$LFS getstripe $file ||\n\t\terror \"getstripe $file failed\"\n}\n\nrun_compilebench() {\n\tlocal dir=${1:-$DIR}\n\tlocal cbench_DIR=${cbench_DIR:-\"\"}\n\tlocal cbench_IDIRS=${cbench_IDIRS:-2}\n\tlocal cbench_RUNS=${cbench_RUNS:-2}\n\n\tprint_opts cbench_DIR cbench_IDIRS cbench_RUNS\n\n\t[ x$cbench_DIR = x ] &&\n\t\tskip_env \"compilebench not found\"\n\n\t[ -e $cbench_DIR/compilebench ] ||\n\t\tskip_env \"No compilebench build\"\n\n\t# Space estimation:\n\t# compile dir kernel-0\t~1GB\n\t# required space\t~1GB * cbench_IDIRS\n\tlocal space=$(df -P $dir | tail -n 1 | awk '{ print $4 }')\n\tif [[ $space -le $((1024 * 1024 * cbench_IDIRS)) ]]; then\n\t\tcbench_IDIRS=$((space / 1024 / 1024))\n\t\t[[ $cbench_IDIRS -eq 0 ]] &&\n\t\t\tskip_env \"Need free space at least 1GB, have $space\"\n\n\t\techo \"reducing initial dirs to $cbench_IDIRS\"\n\tfi\n\techo \"free space = $space KB\"\n\n\t# FIXME:\n\t# t-f _base needs to be modifyed to set properly tdir\n\t# for new \"test_foo\" functions names\n\t# local testdir=$DIR/$tdir\n\tlocal testdir=$dir/d0.compilebench.$$\n\ttest_mkdir -p $testdir\n\tsetstripe_getstripe $testdir $cbench_STRIPEPARAMS\n\n    local savePWD=$PWD\n    cd $cbench_DIR\n    local cmd=\"./compilebench -D $testdir -i $cbench_IDIRS \\\n        -r $cbench_RUNS --makej\"\n\n    log \"$cmd\"\n\n    local rc=0\n    eval $cmd\n    rc=$?\n\n    cd $savePWD\n    [ $rc = 0 ] || error \"compilebench failed: $rc\"\n    rm -rf $testdir\n}\n\nrun_metabench() {\n\tlocal dir=${1:-$DIR}\n\tlocal mntpt=${2:-$MOUNT}\n\tMETABENCH=${METABENCH:-$(which metabench 2> /dev/null || true)}\n\tmbench_NFILES=${mbench_NFILES:-30400}\n\t# threads per client\n\tmbench_THREADS=${mbench_THREADS:-4}\n\tmbench_OPTIONS=${mbench_OPTIONS:-}\n\tmbench_CLEANUP=${mbench_CLEANUP:-true}\n\n\t[ x$METABENCH = x ] && skip_env \"metabench not found\"\n\n\tprint_opts METABENCH clients mbench_NFILES mbench_THREADS\n\n\tlocal testdir=$dir/d0.metabench\n\ttest_mkdir -p $testdir\n\tsetstripe_getstripe $testdir $mbench_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\t# -C             Run the file creation tests. Creates zero byte files.\n\t# -S             Run the file stat tests.\n\t# -c nfile       Number of files to be used in each test.\n\t# -k             Cleanup files when finished.\n\tlocal cmd=\"$METABENCH -w $testdir -c $mbench_NFILES -C -S $mbench_OPTIONS\"\n\techo \"+ $cmd\"\n\n\t# find out if we need to use srun by checking $SRUN_PARTITION\n\tif [ \"$SRUN_PARTITION\" ]; then\n\t\t$SRUN $SRUN_OPTIONS -D $testdir -w $clients -N $num_clients \\\n\t\t\t-n $((num_clients * mbench_THREADS)) \\\n\t\t\t-p $SRUN_PARTITION -- $cmd\n\telse\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $((num_clients * $mbench_THREADS)) $cmd\n\tfi\n\n\tlocal rc=$?\n\tif [ $rc != 0 ] ; then\n\t\terror \"metabench failed! $rc\"\n\tfi\n\n\tif $mbench_CLEANUP; then\n\t\trm -rf $testdir\n\telse\n\t\tmv $dir/d0.metabench $mntpt/_xxx.$(date +%s).d0.metabench\n\tfi\n}\n\nrun_simul() {\n\tSIMUL=${SIMUL:=$(which simul 2> /dev/null || true)}\n\t[ x$SIMUL = x ] && skip_env \"simul not found\"\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\n\t# threads per client\n\tsimul_THREADS=${simul_THREADS:-2}\n\tsimul_REP=${simul_REP:-20}\n\n\t# FIXME\n\t# Need space estimation here.\n\n\tprint_opts SIMUL clients simul_REP simul_THREADS\n\n\tlocal testdir=$DIR/d0.simul\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $simul_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\t# -n # : repeat each test # times\n\t# -N # : repeat the entire set of tests # times\n\n\tlocal cmd=\"$SIMUL -d $testdir -n $simul_REP -N $simul_REP\"\n\n\techo \"+ $cmd\"\n\t# find out if we need to use srun by checking $SRUN_PARTITION\n\tif [ \"$SRUN_PARTITION\" ]; then\n\t\t$SRUN $SRUN_OPTIONS -D $testdir -w $clients -N $num_clients \\\n\t\t\t-n $((num_clients * simul_THREADS)) -p $SRUN_PARTITION \\\n\t\t\t-- $cmd\n\telse\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $((num_clients * simul_THREADS)) $cmd\n\tfi\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"simul failed! $rc\"\n    fi\n    rm -rf $testdir\n}\n\nrun_mdtest() {\n\tMDTEST=${MDTEST:=$(which mdtest 2> /dev/null || true)}\n\t[ x$MDTEST = x ] && skip_env \"mdtest not found\"\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\n\t# threads per client\n\tmdtest_THREADS=${mdtest_THREADS:-2}\n\tmdtest_nFiles=${mdtest_nFiles:-\"100000\"}\n\t# We devide the files by number of core\n\tmdtest_nFiles=$((mdtest_nFiles/mdtest_THREADS/num_clients))\n\tmdtest_iteration=${mdtest_iteration:-1}\n\tlocal mdtest_custom_params=${mdtest_custom_params:-\"\"}\n\tlocal type=${1:-\"ssf\"}\n\n\tlocal mdtest_Nmntp=${mdtest_Nmntp:-1}\n\n\tif [ $type = \"ssf\" ] && [ $mdtest_Nmntp -ne 1 ]; then\n\t\tskip \"shared directory mode is not compatible\" \\\n\t\t\t\"with multiple directory paths\"\n\tfi\n\n\t# FIXME\n\t# Need space estimation here.\n\n\tprint_opts MDTEST mdtest_iteration mdtest_THREADS mdtest_nFiles\n\n\tlocal testdir=$DIR/d0.mdtest\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $mdtest_STRIPEPARAMS\n\tchmod 0777 $testdir\n\n\tfor ((i=1; i<mdtest_Nmntp; i++)); do\n\t\tzconf_mount_clients $clients $MOUNT$i \"$mntopts\" ||\n\t\t\terror_exit \"Failed $clients on $MOUNT$i\"\n\t\tlocal dir=$DIR$i/d0.mdtest$i\n\t\ttest_mkdir $dir\n\t\tsetstripe_getstripe $dir $mdtest_SETSTRIPEPARAMS\n\t\tchmod 0777 $dir\n\t\ttestdir=\"$testdir@$dir\"\n\tdone\n\t# mpi_run uses mpiuser\n\n\t# -i # : repeat each test # times\n\t# -d   : test dir\n\t# -n # : number of file/dir to create/stat/remove\n\t# -u   : each process create/stat/remove individually\n\n\tlocal cmd=\"$MDTEST -d $testdir -i $mdtest_iteration \\\n\t\t-n $mdtest_nFiles $mdtest_custom_params\"\n\n\t[ $type = \"fpp\" ] && cmd=\"$cmd -u\"\n\n\techo \"+ $cmd\"\n\t# find out if we need to use srun by checking $SRUN_PARTITION\n\tif [ \"$SRUN_PARTITION\" ]; then\n\t\t$SRUN $SRUN_OPTIONS -D $testdir -w $clients -N $num_clients \\\n\t\t\t-n $((num_clients * mdtest_THREADS)) \\\n\t\t\t-p $SRUN_PARTITION -- $cmd\n\telse\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $((num_clients * mdtest_THREADS)) $cmd\n\tfi\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"mdtest failed! $rc\"\n    fi\n\trm -rf $testdir\n\tfor ((i=1; i<mdtest_Nmntp; i++)); do\n\t\tlocal dir=$DIR$i/d0.mdtest$i\n\t\trm -rf $dir\n\t\tzconf_umount_clients $clients $MOUNT$i ||\n\t\t\terror_exit \"Failed umount $MOUNT$i on $clients\"\n\tdone\n}\n\nrun_connectathon() {\n\tlocal dir=${1:-$DIR}\n\tcnt_DIR=${cnt_DIR:-\"\"}\n\tcnt_NRUN=${cnt_NRUN:-10}\n\n\tprint_opts cnt_DIR cnt_NRUN\n\n\t[ x$cnt_DIR = x ] && skip_env \"connectathon dir not found\"\n\t[ -e $cnt_DIR/runtests ] || skip_env \"No connectathon runtests found\"\n\n\t# Space estimation:\n\t# \"special\" tests create a 30 MB file + misc. small files\n\t# required space ~40 MB\n\tlocal space=$(df -P $dir | tail -n 1 | awk '{ print $4 }')\n\tif [[ $space -le $((1024 * 40)) ]]; then\n\t\tskip_env \"Need free space at least 40MB, have $space KB\"\n\tfi\n\techo \"free space = $space KB\"\n\n\tlocal testdir=$dir/d0.connectathon\n\ttest_mkdir -p $testdir\n\tsetstripe_getstripe $testdir $cnt_STRIPEPARAMS\n\n\tlocal savePWD=$PWD\n\tcd $cnt_DIR\n\n\t#\n\t# To run connectathon:\n\t# runtests [-a|-b|-g|-s|-l] [-f|-n|-t] [-N numpasses] [test-directory]\n\t#\n\t# One of the following test types\n\t#    -b  basic\n\t#    -g  general\n\t#    -s  special\n\t#    -l  lock\n\t#    -a  all of the above\n\t#\n\t# -f  a quick functional test\n\t# -n  suppress directory operations (mkdir and rmdir)\n\t# -t  run with time statistics (default for basic tests)\n\t#\n\t# -N numpasses - specifies the number of times to run\n\t#                the tests. Optional.\n\n\ttests=\"-b -g -s\"\n\t# Include lock tests unless we're running on nfsv4\n\tlocal fstype=$(df -TP $testdir | awk 'NR==2  {print $2}')\n\techo \"$testdir: $fstype\"\n\tif [[ $fstype != \"nfs4\" ]]; then\n\t\ttests=\"$tests -l\"\n\tfi\n\techo \"tests: $tests\"\n\tfor test in $tests; do\n\t\tlocal cmd=\"sh ./runtests -N $cnt_NRUN $test -f $testdir\"\n\t\tlocal rc=0\n\n\t\tlog \"$cmd\"\n\t\teval $cmd\n\t\trc=$?\n\t\t[ $rc = 0 ] || error \"connectathon failed: $rc\"\n\tdone\n\n\tcd $savePWD\n\trm -rf $testdir\n}\n\nrun_ior() {\n\tlocal type=${1:=\"ssf\"}\n\tlocal dir=${2:-$DIR}\n\tlocal testdir=$dir/d0.ior.$type\n\tlocal nfs_srvmntpt=$3\n\n\tif [ \"$NFSCLIENT\" ]; then\n\t\t[[ -n $nfs_srvmntpt ]] ||\n\t\t\t{ error \"NFSCLIENT mode, but nfs exported dir\"\\\n\t\t\t\t\"is not set!\" && return 1; }\n\tfi\n\n\tIOR=${IOR:-$(which IOR 2> /dev/null || true)}\n\t[ x$IOR = x ] && skip_env \"IOR not found\"\n\n\t# threads per client\n\tior_THREADS=${ior_THREADS:-2}\n\tior_iteration=${ior_iteration:-1}\n\tior_blockSize=${ior_blockSize:-6}\n\tior_blockUnit=${ior_blockUnit:-M}   # K, M, G\n\tior_xferSize=${ior_xferSize:-1M}\n\tior_type=${ior_type:-POSIX}\n\tior_DURATION=${ior_DURATION:-30}        # minutes\n\tlocal multiplier=1\n\tcase ${ior_blockUnit} in\n\t\t[G])\n\t\t\tmultiplier=$((1024 * 1024 * 1024))\n\t\t\t;;\n\t\t[M])\n\t\t\tmultiplier=$((1024 * 1024))\n\t\t\t;;\n\t\t[K])\n\t\t\tmultiplier=1024\n\t\t\t;;\n\t\t*)      error \"Incorrect block unit should be one of [KMG]\"\n\t\t\t;;\n\tesac\n\n\t# calculate the space in bytes\n\tlocal space=$(df -B 1 -P $dir | tail -n 1 | awk '{ print $4 }')\n\tlocal total_threads=$((num_clients * ior_THREADS))\n\techo \"+ $ior_blockSize * $multiplier * $total_threads \"\n\tif [ $((space / 2)) -le \\\n\t     $((ior_blockSize * multiplier * total_threads)) ]; then\n\t\tior_blockSize=$((space / 2 / multiplier / total_threads))\n\t\t[ $ior_blockSize -eq 0 ] &&\n\t\tskip_env \"Need free space more than $((2 * total_threads)) \\\n\t\t\t ${ior_blockUnit}: have $((space / multiplier))\"\n\n\t\techo \"(reduced blockSize to $ior_blockSize \\\n\t\t     ${ior_blockUnit} bytes)\"\n\tfi\n\n\tprint_opts IOR ior_THREADS ior_DURATION MACHINEFILE\n\n\ttest_mkdir -p $testdir\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\t[[ \"$ior_stripe_params\" && -z \"$ior_STRIPEPARAMS\" ]] &&\n\t\tior_STRIPEPARAMS=\"$ior_stripe_params\" &&\n\t\techo \"got deprecated ior_stripe_params,\"\\\n\t\t\t\"use ior_STRIPEPARAMS instead\"\n\tsetstripe_getstripe $testdir $ior_STRIPEPARAMS\n\n\t#\n\t# -b N  blockSize --\n\t#       contiguous bytes to write per task (e.g.: 8, 4K, 2M, 1G)\"\n\t# -o S  testFileName\n\t# -t N  transferSize -- size of transfer in bytes (e.g.: 8, 4K, 2M, 1G)\"\n\t# -w    writeFile -- write file\"\n\t# -r    readFile -- read existing file\"\n\t# -W    checkWrite -- check read after write\"\n\t# -C    reorderTasks -- changes task ordering to n+1 ordering for readback\n\t# -T    maxTimeDuration -- max time in minutes to run tests\"\n\t# -k    keepFile -- keep testFile(s) on program exit\n\n\tlocal cmd\n\tif [ -n \"$ior_custom_params\" ]; then\n\t\tcmd=\"$IOR -o $testdir/iorData $ior_custom_params\"\n\telse\n\t\tcmd=\"$IOR -a $ior_type -b ${ior_blockSize}${ior_blockUnit} \\\n\t\t-o $testdir/iorData -t $ior_xferSize -v -C -w -r -W \\\n\t\t-i $ior_iteration -T $ior_DURATION -k\"\n\tfi\n\n\t[ $type = \"fpp\" ] && cmd=\"$cmd -F\"\n\n\techo \"+ $cmd\"\n\t# find out if we need to use srun by checking $SRUN_PARTITION\n\tif [ \"$SRUN_PARTITION\" ]; then\n\t\t$SRUN $SRUN_OPTIONS -D $testdir -w $clients -N $num_clients \\\n\t\t\t-n $((num_clients * ior_THREADS)) -p $SRUN_PARTITION \\\n\t\t\t-- $cmd\n\telse\n\t\tmpi_ior_custom_threads=${mpi_ior_custom_threads:-\"$((num_clients * ior_THREADS))\"}\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $mpi_ior_custom_threads $cmd\n\tfi\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"ior failed! $rc\"\n    fi\n    rm -rf $testdir\n}\n\nrun_mib() {\n\tMIB=${MIB:=$(which mib 2> /dev/null || true)}\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\t[ x$MIB = x ] && skip_env \"MIB not found\"\n\n\t# threads per client\n\tmib_THREADS=${mib_THREADS:-2}\n\tmib_xferSize=${mib_xferSize:-1m}\n\tmib_xferLimit=${mib_xferLimit:-5000}\n\tmib_timeLimit=${mib_timeLimit:-300}\n\tmib_STRIPEPARAMS=${mib_STRIPEPARAMS:-\"-c -1\"}\n\n\tprint_opts MIB mib_THREADS mib_xferSize mib_xferLimit mib_timeLimit \\\n\t\tMACHINEFILE\n\n\tlocal testdir=$DIR/d0.mib\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $mib_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\t#\n\t# -I    Show intermediate values in output\n\t# -H    Show headers in output\n\t# -L    Do not issue new system calls after this many seconds\n\t# -s    Use system calls of this size\n\t# -t    test dir\n\t# -l    Issue no more than this many system calls\n\tlocal cmd=\"$MIB -t $testdir -s $mib_xferSize -l $mib_xferLimit \\\n\t\t-L $mib_timeLimit -HI -p mib.$(date +%Y%m%d%H%M%S)\"\n\n\techo \"+ $cmd\"\n\t# find out if we need to use srun by checking $SRUN_PARTITION\n\tif [ \"$SRUN_PARTITION\" ]; then\n\t\t$SRUN $SRUN_OPTIONS -D $testdir -w $clients -N $num_clients \\\n\t\t\t-n $((num_clients * mib_THREADS)) -p $SRUN_PARTITION \\\n\t\t\t-- $cmd\n\telse\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $((num_clients * mib_THREADS)) $cmd\n\tfi\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"mib failed! $rc\"\n    fi\n    rm -rf $testdir\n}\n\nrun_cascading_rw() {\n\tCASC_RW=${CASC_RW:-$(which cascading_rw 2> /dev/null || true)}\n\t[ x$CASC_RW = x ] && skip_env \"cascading_rw not found\"\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\n\t# threads per client\n\tcasc_THREADS=${casc_THREADS:-2}\n\tcasc_REP=${casc_REP:-300}\n\n\t# FIXME\n\t# Need space estimation here.\n\n\tprint_opts CASC_RW clients casc_THREADS casc_REP MACHINEFILE\n\n\tlocal testdir=$DIR/d0.cascading_rw\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $casc_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\t# -g: debug mode\n\t# -n: repeat test # times\n\n\tlocal cmd=\"$CASC_RW -g -d $testdir -n $casc_REP\"\n\n\techo \"+ $cmd\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((num_clients * $casc_THREADS)) $cmd\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"cascading_rw failed! $rc\"\n    fi\n    rm -rf $testdir\n}\n\nrun_write_append_truncate() {\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\t# location is lustre/tests dir\n\tif ! which write_append_truncate > /dev/null 2>&1 ; then\n\t\tskip_env \"write_append_truncate not found\"\n\tfi\n\n\t# threads per client\n\twrite_THREADS=${write_THREADS:-8}\n\twrite_REP=${write_REP:-10000}\n\n\t# FIXME\n\t# Need space estimation here.\n\n\tlocal testdir=$DIR/d0.write_append_truncate\n\tlocal file=$testdir/f0.wat\n\n\tprint_opts clients write_REP write_THREADS MACHINEFILE\n\n\ttest_mkdir $testdir\n\t# mpi_run uses mpiuser\n\tsetstripe_getstripe $testdir $write_STRIPEPARAMS\n\n\tchmod 0777 $testdir\n\n\tlocal cmd=\"write_append_truncate -n $write_REP $file\"\n\n\techo \"+ $cmd\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((num_clients * $write_THREADS)) $cmd\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"write_append_truncate failed! $rc\"\n        return $rc\n    fi\n    rm -rf $testdir\n}\n\nrun_write_disjoint() {\n\tWRITE_DISJOINT=${WRITE_DISJOINT:-$(which write_disjoint 2> /dev/null ||\n\t\t\t\t\t   true)}\n\t[ x$WRITE_DISJOINT = x ] && skip_env \"write_disjoint not found\"\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\n\t# threads per client\n\twdisjoint_THREADS=${wdisjoint_THREADS:-4}\n\twdisjoint_REP=${wdisjoint_REP:-10000}\n\tchunk_size_limit=$1\n\n\t# FIXME\n\t# Need space estimation here.\n\n\tprint_opts WRITE_DISJOINT clients wdisjoint_THREADS wdisjoint_REP \\\n\t\tMACHINEFILE\n\tlocal testdir=$DIR/d0.write_disjoint\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $wdisjoint_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\tlocal cmd=\"$WRITE_DISJOINT -f $testdir/file -n $wdisjoint_REP -m \\\n\t\t\t$chunk_size_limit\"\n\n\techo \"+ $cmd\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((num_clients * $wdisjoint_THREADS)) $cmd\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"write_disjoint failed! $rc\"\n    fi\n    rm -rf $testdir\n}\n\nrun_parallel_grouplock() {\n\tPARALLEL_GROUPLOCK=${PARALLEL_GROUPLOCK:-$(which parallel_grouplock \\\n\t    2> /dev/null || true)}\n\n\t[ x$PARALLEL_GROUPLOCK = x ] && skip \"PARALLEL_GROUPLOCK not found\"\n\t[ \"$NFSCLIENT\" ] && skip \"skipped for NFSCLIENT mode\"\n\n\tparallel_grouplock_MINTASKS=${parallel_grouplock_MINTASKS:-5}\n\n\tprint_opts clients parallel_grouplock_MINTASKS MACHINEFILE\n\n\tlocal testdir=$DIR/d0.parallel_grouplock\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $parallel_grouplock_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\tlocal cmd\n\tlocal status=0\n\tlocal subtest\n\tfor i in $(seq 12); do\n\t\tsubtest=\"-t $i\"\n\t\tlocal cmd=\"$PARALLEL_GROUPLOCK -g -v -d $testdir $subtest\"\n\t\techo \"+ $cmd\"\n\n\t\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t\t-np $parallel_grouplock_MINTASKS $cmd\n\t\tlocal rc=$?\n\t\tif [ $rc != 0 ] ; then\n\t\t\terror_noexit \"parallel_grouplock subtests $subtest \" \\\n\t\t\t\t     \"failed! $rc\"\n\t\telse\n\t\t\techo \"parallel_grouplock subtests $subtest PASS\"\n\t\tfi\n\t\tlet status=$((status + rc))\n\t\t# clear debug to collect one log per one test\n\t\tdo_nodes $(comma_list $(nodes_list)) lctl clear\n\tdone\n\t[ $status -eq 0 ] || error \"parallel_grouplock status: $status\"\n\trm -rf $testdir\n}\n\ncleanup_statahead () {\n    trap 0\n\n    local clients=$1\n    local mntpt_root=$2\n    local num_mntpts=$3\n\n    for i in $(seq 0 $num_mntpts);do\n        zconf_umount_clients $clients ${mntpt_root}$i ||\n            error_exit \"Failed to umount lustre on ${mntpt_root}$i\"\n    done\n}\n\nrun_statahead () {\n\tif [[ -n $NFSCLIENT ]]; then\n\t\tskip \"Statahead testing is not supported on NFS clients.\"\n\tfi\n\t[ x$MDSRATE = x ] && skip_env \"mdsrate not found\"\n\n\tstatahead_NUMMNTPTS=${statahead_NUMMNTPTS:-5}\n\tstatahead_NUMFILES=${statahead_NUMFILES:-500000}\n\n\tprint_opts MDSRATE clients statahead_NUMMNTPTS statahead_NUMFILES\n\n\t# create large dir\n\n\t# do not use default \"d[0-9]*\" dir name\n\t# to avoid of rm $statahead_NUMFILES (500k) files in t-f cleanup\n\tlocal dir=dstatahead\n\tlocal testdir=$DIR/$dir\n\n\t# cleanup only if dir exists\n\t# cleanup only $statahead_NUMFILES number of files\n\t# ignore the other files created by someone else\n\t[ -d $testdir ] &&\n\tmdsrate_cleanup $((num_clients * 32)) $MACHINEFILE \\\n\t\t$statahead_NUMFILES $testdir 'f%%d' --ignore\n\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $statahead_STRIPEPARAMS\n\n    # mpi_run uses mpiuser\n    chmod 0777 $testdir\n\n    local num_files=$statahead_NUMFILES\n\n    local IFree=$(inodes_available)\n    if [ $IFree -lt $num_files ]; then\n      num_files=$IFree\n    fi\n\n    cancel_lru_locks mdc\n\n    local cmd1=\"${MDSRATE} ${MDSRATE_DEBUG} --mknod --dir $testdir\"\n    local cmd2=\"--nfiles $num_files --filefmt 'f%%d'\"\n    local cmd=\"$cmd1 $cmd2\"\n    echo \"+ $cmd\"\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((num_clients * 32)) $cmd\n\n    local rc=$?\n    if [ $rc != 0 ] ; then\n        error \"mdsrate failed to create $rc\"\n        return $rc\n    fi\n\n    local num_mntpts=$statahead_NUMMNTPTS\n    local mntpt_root=$TMP/mntpt/lustre\n    local mntopts=$MNTOPTSTATAHEAD\n\n    echo \"Mounting $num_mntpts lustre clients starts on $clients\"\n    trap \"cleanup_statahead $clients $mntpt_root $num_mntpts\" EXIT ERR\n    for i in $(seq 0 $num_mntpts); do\n        zconf_mount_clients $clients ${mntpt_root}$i \"$mntopts\" ||\n            error_exit \"Failed to mount lustre on ${mntpt_root}$i on $clients\"\n    done\n\n    do_rpc_nodes $clients cancel_lru_locks mdc\n\n    do_rpc_nodes $clients do_ls $mntpt_root $num_mntpts $dir\n\n    mdsrate_cleanup $((num_clients * 32)) $MACHINEFILE \\\n        $num_files $testdir 'f%%d' --ignore\n\n    # use rm instead of rmdir because of\n    # testdir could contain the files created by someone else,\n    # or by previous run where is num_files prev > num_files current\n    rm -rf $testdir\n    cleanup_statahead $clients $mntpt_root $num_mntpts\n}\n\ncleanup_rr_alloc () {\n\ttrap 0\n\tlocal clients=\"$1\"\n\tlocal mntpt_root=\"$2\"\n\tlocal rr_alloc_MNTPTS=\"$3\"\n\tlocal mntpt_dir=$(dirname ${mntpt_root})\n\n\tfor i in $(seq 0 $((rr_alloc_MNTPTS - 1))); do\n\t\tzconf_umount_clients $clients ${mntpt_root}$i ||\n\t\terror_exit \"Failed to umount lustre on ${mntpt_root}$i\"\n\tdone\n\tdo_nodes $clients \"rm -rf $mntpt_dir\"\n}\n\nrun_rr_alloc() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\techo \"===Test gives more reproduction percentage if number of \"\\\n\t\t\"client and ost are more. Test with 44 or more clients \"\\\n\t\t\"and 73 or more OSTs gives 100% reproduction rate==\"\n\n\tRR_ALLOC=${RR_ALLOC:-$(which rr_alloc 2> /dev/null || true)}\n\t[ x$RR_ALLOC = x ] && skip_env \"rr_alloc not found\"\n\tdeclare -a diff_max_min_arr\n\t# foeo = file on each ost. calc = calculated.\n\tlocal ost_idx\n\tlocal foeo_calc\n\tlocal qos_prec_objs=\"${TMP}/qos_and_precreated_objects\"\n\tlocal rr_alloc_NFILES=${rr_alloc_NFILES:-555}\n\tlocal rr_alloc_MNTPTS=${rr_alloc_MNTPTS:-11}\n\tlocal total_MNTPTS=$((rr_alloc_MNTPTS * num_clients))\n\tlocal mntpt_root=\"${TMP}/rr_alloc_mntpt/lustre\"\n\ttest_mkdir $DIR/$tdir\n\tsetstripe_getstripe $DIR/$tdir $rr_alloc_STRIPEPARAMS\n\n\tchmod 0777 $DIR/$tdir\n\n\ttrap \"cleanup_rr_alloc $clients $mntpt_root $rr_alloc_MNTPTS\" EXIT ERR\n\tfor i in $(seq 0 $((rr_alloc_MNTPTS - 1))); do\n\t\tzconf_mount_clients $clients ${mntpt_root}$i $MOUNT_OPTS ||\n\t\terror_exit \"Failed to mount lustre on ${mntpt_root}$i $clients\"\n\tdone\n\n\tlocal cmd=\"$RR_ALLOC $mntpt_root/$tdir/ash $rr_alloc_NFILES \\\n\t\t$num_clients\"\n\n\t# Save mdt values, set threshold to 100% i.e always Round Robin,\n\t# restore the saved values again after creating files...\n\tsave_lustre_params mds1 \\\n\t\t\"lov.$FSNAME-MDT0000*.qos_threshold_rr\" > $qos_prec_objs\n\tsave_lustre_params mds1 \\\n\t\t\"osp.$FSNAME-OST*-osc-MDT0000.create_count\" >> $qos_prec_objs\n\n\tlocal old_create_count=$(grep -e \"create_count\" $qos_prec_objs |\n\t\tcut -d'=' -f 2 | sort -nr | head -n1)\n\n\t# Make sure that every osp has enough precreated objects for the file\n\t# creation app\n\n\t# create_count is always set to the power of 2 only, so if the files\n\t# per OST are not multiple of that then it will be set to nearest\n\t# lower power of 2. So set 'create_count' to the upper power of 2.\n\n\tfoeo_calc=$((rr_alloc_NFILES * total_MNTPTS / OSTCOUNT))\n\tlocal create_count=$((2 * foeo_calc))\n\tdo_facet mds1 \"$LCTL set_param -n \\\n\t\tlov.$FSNAME-MDT0000*.qos_threshold_rr 100 \\\n\t\tosp.$FSNAME-OST*-osc-MDT0000.create_count $create_count\" ||\n\t\terror \"failed while setting qos_threshold_rr & creat_count\"\n\n\t# Create few temporary files in order to increase the precreated objects\n\t# to a desired value, before starting 'rr_alloc' app. Due to default\n\t# value 32 of precreation count (OST_MIN_PRECREATE=32), precreated\n\t# objects available are 32 initially, these gets exhausted very soon,\n\t# which causes skip of some osps when very large number of files\n\t# is created per OSTs.\n\tcreatemany -o $DIR/$tdir/foo- $(((old_create_count + 1) * OSTCOUNT)) \\\n\t\t> /dev/null\n\trm -f /$DIR/$tdir/foo*\n\n\t# Check for enough precreated objects... We should not\n\t# fail here because code(osp_precreate.c) also takes care of it.\n\t# So we have good chances of passing test even if this check fails.\n\tlocal mdt_idx=0\n\tfor ost_idx in $(seq 0 $((OSTCOUNT - 1))); do\n\t\t[[ $(precreated_ost_obj_count $mdt_idx $ost_idx) -ge \\\n\t\t\t$foeo_calc ]] || echo \"Warning: test may fail because\" \\\n\t\t\t\"of lack of precreated objects on OST${ost_idx}\"\n\tdone\n\n\tif [[ $total_MNTPTS -ne 0 ]]; then\n\t\t# Now start the actual file creation app.\n\t\tmpi_run \"-np $total_MNTPTS\" $cmd || return\n\telse\n\t\terror \"No mount point\"\n\tfi\n\n\trestore_lustre_params < $qos_prec_objs\n\trm -f $qos_prec_objs\n\n\tdiff_max_min_arr=($($LFS getstripe -r $DIR/$tdir/ |\n\t\tgrep \"lmm_stripe_offset:\" | awk '{print $2}' | sort -n |\n\t\tuniq -c | awk 'NR==1 {min=max=$1} \\\n\t\t{ $1<min ? min=$1 : min; $1>max ? max=$1 : max} \\\n\t\tEND {print max-min, max, min}'))\n\n\trm -rf $DIR/$tdir\n\n\t# In-case of fairly large number of file creation using RR (round-robin)\n\t# there can be two cases in which deviation will occur than the regular\n\t# RR algo behaviour-\n\t# 1- When rr_alloc does not start right with 'lqr_start_count' reseeded,\n\t# 2- When rr_alloc does not finish with 'lqr_start_count == 0'.\n\t# So the difference of files b/w any 2 OST should not be more than 2.\n\t[[ ${diff_max_min_arr[0]} -le 2 ]] ||\n\t\terror \"Uneven distribution detected: difference between\" \\\n\t\t\"maximum files per OST (${diff_max_min_arr[1]}) and\" \\\n\t\t\"minimum files per OST (${diff_max_min_arr[2]}) must not be\" \\\n\t\t\"greater than 2\"\n}\n\nrun_fs_test() {\n\t# fs_test.x is the default name for exe\n\tFS_TEST=${FS_TEST:=$(which fs_test.x 2> /dev/null || true)}\n\n\tlocal clients=${CLIENTS:-$(hostname)}\n\tlocal testdir=$DIR/d0.fs_test\n\tlocal file=${testdir}/fs_test\n\tfs_test_threads=${fs_test_threads:-2}\n\tfs_test_type=${fs_test_type:-1}\n\tfs_test_nobj=${fs_test_nobj:-10}\n\tfs_test_check=${fs_test_check:-3}\n\tfs_test_strided=${fs_test_strided:-1}\n\tfs_test_touch=${fs_test_touch:-3}\n\tfs_test_supersize=${fs_test_supersize:-1}\n\tfs_test_op=${fs_test_op:-write}\n\tfs_test_barriers=${fs_test_barriers:-bopen,bwrite,bclose}\n\tfs_test_io=${fs_test_io:-mpi}\n\tfs_test_objsize=${fs_test_objsize:-100}\n\tfs_test_objunit=${fs_test_objunit:-1048576} # 1 mb\n\tfs_test_ndirs=${fs_test_ndirs:-80000}\n\n\t[ x$FS_TEST = x ] && skip \"FS_TEST not found\"\n\n\t# Space estimation  in bytes\n\tlocal space=$(df -B 1 -P $dir | tail -n 1 | awk '{ print $4 }')\n\tlocal total_threads=$((num_clients * fs_test_threads))\n\techo \"+ $fs_test_objsize * $fs_test_objunit * $total_threads \"\n\tif [ $((space / 2)) -le \\\n\t\t$((fs_test_objsize * fs_test_objunit * total_threads)) ]; then\n\t\t\tfs_test_objsize=$((space / 2 / fs_test_objunit / \\\n\t\t\t\ttotal_threads))\n\t\t\t[ $fs_test_objsize -eq 0 ] &&\n\t\t\tskip_env \"Need free space more than \\\n\t\t\t\t$((2 * total_threads * fs_test_objunit)) \\\n\t\t\t\t: have $((space / fs_test_objunit))\"\n\n\t\t\techo \"(reduced objsize to \\\n\t\t\t\t$((fs_test_objsize * fs_test_objunit)) bytes)\"\n\tfi\n\n\tprint_opts FS_TEST clients fs_test_threads fs_test_objsize MACHINEFILE\n\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $fs_test_STRIPEPARAMS\n\n\t# mpi_run uses mpiuser\n\tchmod 0777 $testdir\n\n\t# --nodb          Turn off the database code at runtime\n\t# -g --target     The path to the data file\n\t# -t --type       Whether to do N-N (1) or N-1 (2)\n\t# -n --nobj       The number of objects written/read by each proc\n\t# -z --size       The size of each object\n\t# -d ---num_nn_dirs Number of subdirectories for files\n\t# -C --check      Check every byte using argument 3.\n\t# --collective    Whether to use collective I/O (for N-1, mpi-io only)\n\t# -s --strided    Whether to use a strided pattern (for N-1 only)\n\t# -T --touch      Touch every byte using argument 3\n\t# -o --op         Whether to read only (read) or write only (write)\n\t# -b --barriers   When to barrier.\n\t# -i --io         Use POSIX, MPI, or PLFS IO routines (mpi|posix|plfs)\n\t# -S --supersize  Specify how many objects per superblock\n\n\tlocal cmd=\"$FS_TEST -nodb -g $file -t $fs_test_type -n $fs_test_nobj \\\n\t\t-z $((fs_test_objsize * fs_test_objunit)) -d $fs_test_ndirs \\\n\t\t-C $fs_test_check -collective -s $fs_test_strided \\\n\t\t-T $fs_test_touch -o $fs_test_op -b $fs_test_barriers \\\n\t\t-i $fs_test_io -S $fs_test_supersize\"\n\n\techo \"+ $cmd\"\n\tmpi_run \"-np $((num_clients * fs_test_threads))\" $cmd\n\n\tlocal rc=$?\n\tif [ $rc != 0 ] ; then\n\t\terror \"fs_test failed! $rc\"\n\tfi\n\n\trm -rf $testdir\n}\n\nior_mdtest_parallel() {\n\tlocal rc1=0\n\tlocal rc2=0\n\tlocal type=$1\n\n\trun_ior $type &\n\tlocal pids=$!\n\n\trun_mdtest $type || rc2=$?\n\t[[ $rc2 -ne 0 ]] && echo \"mdtest failed with error $rc2\"\n\n\twait $pids || rc1=$?\n\t[[ $rc1 -ne 0 ]] && echo \"ior failed with error $rc1\"\n\n\t[[ $rc1 -ne 0 || $rc2 -ne 0 ]] && return 1\n\treturn 0\n}\n\nrun_fio() {\n\tFIO=${FIO:=$(which fio 2> /dev/null || true)}\n\n\tlocal clients=${CLIENTS:-$(hostname)}\n\tlocal fio_jobNum=${fio_jobNum:-4}\n\tlocal fio_jobFile=${fio_jobFile:-$TMP/fiojobfile.$(date +%s)}\n\tlocal fio_bs=${fio_bs:-1}\n\tlocal testdir=$DIR/d0.fio\n\tlocal file=${testdir}/fio\n\tlocal runtime=60\n\tlocal propagate=false\n\n\t[ \"$SLOW\" = \"no\" ] || runtime=600\n\n\t[ x$FIO = x ] && skip_env \"FIO not found\"\n\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $fio_STRIPEPARAMS\n\n\t# use fio job file if exists,\n\t# create a simple one if missing\n\tif ! [ -f $fio_jobFile ]; then\n\t\tcat >> $fio_jobFile <<EOF\n[global]\nrw=randwrite\nsize=128m\ntime_based=1\nruntime=$runtime\nfilename=${file}_\\$(hostname)\nEOF\n\t\t# bs size increased by $i for each job\n\t\tfor ((i=1; i<=fio_jobNum; i++)); do\n\t\t\tcat >> $fio_jobFile <<EOF\n\n[job$i]\nbs=$(( fio_bs * i ))m\nEOF\n\t\tdone\n\t\t# job file is created, should be propagated to all clients\n\t\tpropagate=true\n\tfi\n\n\n\t# propagate the job file if not all clients have it yet or\n\t# if the job file was created during the test run\n\tif ! do_nodesv $clients \" [ -f $fio_jobFile ] \" ||\n\t   $propagate; then\n\t\tlocal cfg=$(cat $fio_jobFile)\n\t\tdo_nodes $clients \"echo \\\\\\\"$cfg\\\\\\\" > ${fio_jobFile}\" ||\n\t\t\terror \"job file $fio_jobFile is not propagated\"\n\t\tdo_nodesv $clients \"cat ${fio_jobFile}\"\n\tfi\n\n\tcmd=\"$FIO $fio_jobFile\"\n\techo \"+ $cmd\"\n\n\tlog \"clients: $clients $cmd\"\n\n\tlocal rc=0\n\tdo_nodesv $clients \"$cmd \"\n\trc=$?\n\n\t[ $rc = 0 ] || error \"fio failed: $rc\"\n\trm -rf $testdir\n}\n\nrun_xdd() {\n\tXDD=${XDD:=$(which xdd 2> /dev/null || true)}\n\n\tlocal clients=${CLIENTS:-$(hostname)}\n\tlocal testdir=$DIR/d0.xdd\n\txdd_queuedepth=${xdd_queuedepth:-4}\n\txdd_blocksize=${xdd_blocksize:-512}\n\txdd_reqsize=${xdd_reqsize:-128}\n\txdd_mbytes=${xdd_mbytes:-100}\n\txdd_passes=${xdd_passes:-40}\n\txdd_rwratio=${xdd_rwratio:-0}\n\txdd_ntargets=${xdd_ntargets:-6}\n\tlocal xdd_custom_params=${xdd_custom_params:-\"-dio -stoponerror \\\n\t\t-maxpri -minall -noproclock -nomemlock\"}\n\n\t[ x$XDD = x ] && skip \"XDD not found\"\n\n\tprint_opts XDD clients xdd_queuedepth xdd_blocksize xdd_reqsize \\\n\t\txdd_mbytes xdd_passes xdd_rwratio\n\n\ttest_mkdir $testdir\n\tsetstripe_getstripe $testdir $xdd_STRIPEPARAMS\n\n\tlocal files=\"\"\n\t# Target files creates based on the given number of targets\n\tfor (( i=0; i < $xdd_ntargets; i++ ))\n\tdo\n\t\tfiles+=\"${testdir}/xdd\"$i\" \"\n\tdone\n\n\t# -targets      specifies the devices or files to perform operation\n\t# -reqsize      number of 'blocks' per operation\n\t# -mbytes       number of 1024*1024-byte blocks to transfer\n\t# -blocksize    size of a single 'block'\n\t# -passes       number of times to read mbytes\n\t# -queuedepth   number of commands to queue on the target\n\t# -rwratio      percentage of read to write operations\n\t# -verbose      will print out statistics on each pass\n\n\tlocal cmd=\"$XDD -targets $xdd_ntargets $files -reqsize $xdd_reqsize \\\n\t\t-mbytes $xdd_mbytes -blocksize $xdd_blocksize \\\n\t\t-passes $xdd_passes -queuedepth $xdd_queuedepth \\\n\t\t-rwratio $xdd_rwratio -verbose $xdd_custom_params\"\n\techo \"+ $cmd\"\n\n\tlocal rc=0\n\tdo_nodesv $clients \"$cmd \"\n\trc=$?\n\n\t[ $rc = 0 ] || error \"xdd failed: $rc\"\n\n\trm -rf $testdir\n}\n", "num_lines": 1333}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# -*- mode: Bash; tab-width: 4; indent-tabs-mode: t; -*-\n# vim:shiftwidth=4:softtabstop=4:tabstop=4:\n#\n# NAME\n#\n#   ha.sh - test Lustre HA (aka failover) configurations\n#\n# SYNOPSIS\n#\n#   ha.sh [OPTIONS]\n#\n# DESCRIPTION\n#\n#   ha.sh tests Lustre HA (aka failover) configurations with a CRM.\n#\n# OPTIONS\n#\n#   -h\n#       Help.\n#\n#   -c HOST[,...]\n#       Specify client nodes.\n#\n#   -s HOST[,...]\n#       Specify server nodes.\n#\n#   -v HOST[,...]\n#       Specify victim nodes to be rebooted.\n#\n#   -d DIRECTORY\n#       Choose a parent of the test directory.  \"/mnt/lustre\" if not specified.\n#\n#   -u SECONDS\n#       Define a duration for the test. 86400 seconds if not specified.\n#\n#   -p SECONDS\n#       Define a max failover period. 10 minutes if not set.\n#\n#   -w\n#       Only run the workloads; no failure will be introduced.\n#       -v, -s are ignored in this case.\n#   -r\n#       Workloads dry run for several seconds; no failures will be introduced.\n#       This option is useful to verify the loads.\n#       -u is ignored in this case\n#   -m\n#       Reboot victim nodes simultaneously.\n#\n#\n# ASSUMPTIONS\n#\n#   A Lustre file system is up and mounted on all client nodes.  This script\n#   does not mount or unmount any Lustre targets or clients, let alone format\n#   anything.\n#\n#   Each target has a failnode, so that workloads can continue after a power\n#   failure.\n#\n#   CRM could be configured by 2 ways:\n#   1.\n#   Targets are automatically failed back when their primary node is back.  This\n#   assumption avoids calling CRM-specific commands to trigger failbacks, making\n#   this script more CRM-neural.\n#   2.\n#   Targets are not automatically failed back when their primary node is back.\n#   CRM-specific command is executed to trigger failbacks.\n#\n#   A crash dump mechanism is configured to catch LBUGs, panics, etc.\n#\n# WORKLOADS\n#\n#   Each client runs set of MPI and non-MPI workloads. These\n#   applications are run in short loops so that their exit status can be waited\n#   for and checked within reasonable time by ha_wait_loads.\n#   The set of MPI and non-MPI workloads are configurable by parameters:\n#\tha_nonmpi_loads\n#\t\tdefault set: dd, tar, iozone\n#\tha_mpi_loads\n#\t\tdefault set: ior, simul, mdtest\n#\n#   The number of clients run MPI loads is configured by parameter\n#   ha_mpi_instances. Only one client runs MPI workloads by default.\n#\n#   MPI workloads can be run from several users. The list of users to use is\n#   configured by parameter ha_mpi_users, default is \"mpiuser\".\n#\n# PROCESS STRUCTURE AND IPC\n#\n#   On the node where this script is run, the processes look like this:\n#\n#       ~ ha.sh (ha_killer)\n#\n#           ~ ha.sh (ha_repeat_mpi_load ior)\n#               ~ mpirun IOR\n#           ~ ha.sh (ha_repeat_mpi_load simul)\n#               ~ mpirun simul\n#           ~ ha.sh (ha_repeat_mpi_load mdtest)\n#               ~ mpirun mdtest\n#           ~ ... (one for each MPI load)\n#\n#           ~ ha.sh (ha_repeat_nonmpi_load client2 dbench)\n#               ~ pdsh client2 dbench\n#           ~ ha.sh (ha_repeat_nonmpi_load client2 iozone)\n#               ~ pdsh client2 iozone\n#           ~ ha.sh (ha_repeat_nonmpi_load client5 iozone)\n#               ~ pdsh client5 iozone\n#           ~ ... (one for each non-MPI load on each client)\n#\n#   Each tilde represents a process.  Indentations imply parent-children\n#   relation.\n#\n#   IPC is done by files in the temporary directory.\n#\n\n#set -x\n\nSIMUL=${SIMUL:-$(which simul 2> /dev/null || true)}\nIOR=${IOR:-$(which IOR 2> /dev/null || true)}\nMDTEST=${MDTEST:-$(which mdtest 2> /dev/null || true)}\n\nior_blockSize=${ior_blockSize:-6g}\nmpi_threads_per_client=${mpi_threads_per_client:-2}\n\niozone_SIZE=${iozone_SIZE:-262144} # 256m\n\nmpirun=${MPIRUN:-$(which mpirun)}\nLFS=${LFS:-$(which lfs)}\n\nha_check_env()\n{\n\tfor ((load = 0; load < ${#ha_mpi_load_tags[@]}; load++)); do\n\t\tlocal tag=${ha_mpi_load_tags[$load]}\n\t\tlocal bin=$(echo $tag | tr '[:lower:]' '[:upper:]')\n\t\tif [ x${!bin} = x ]; then\n\t\t\tha_error ha_mpi_loads: ${ha_mpi_loads}, $bin is not set\n\t\t\texit 1\n\t\tfi\n\tdone\n}\n\nha_info()\n{\n\techo \"$0: $(date +%H:%M:%S' '%s):\" \"$@\"\n}\n\nha_log()\n{\n\tlocal nodes=${1// /,}\n\tshift\n\tha_on $nodes \"lctl mark $*\"\n}\n\nha_error()\n{\n    ha_info \"$@\" >&2\n}\n\nha_trap_err()\n{\n    local i\n\n    ha_error \"Trap ERR triggered by:\"\n    ha_error \"    $BASH_COMMAND\"\n    ha_error \"Call trace:\"\n    for ((i = 0; i < ${#FUNCNAME[@]}; i++)); do\n        ha_error \"    ${FUNCNAME[$i]} [${BASH_SOURCE[$i]}:${BASH_LINENO[$i]}]\"\n    done\n}\n\ntrap ha_trap_err ERR\nset -eE\n\ndeclare     ha_tmp_dir=/tmp/$(basename $0)-$$\ndeclare     ha_stop_file=$ha_tmp_dir/stop\ndeclare     ha_fail_file=$ha_tmp_dir/fail\ndeclare     ha_status_file_prefix=$ha_tmp_dir/status\ndeclare -a  ha_status_files\ndeclare     ha_machine_file=$ha_tmp_dir/machine_file\ndeclare     ha_lfsck_log=$ha_tmp_dir/lfsck.log\ndeclare     ha_lfsck_lock=$ha_tmp_dir/lfsck.lock\ndeclare     ha_lfsck_stop=$ha_tmp_dir/lfsck.stop\ndeclare     ha_lfsck_bg=${LFSCK_BG:-false}\ndeclare     ha_lfsck_after=${LFSCK_AFTER:-false}\ndeclare     ha_lfsck_node=${LFSCK_NODE:-\"\"}\ndeclare     ha_lfsck_device=${LFSCK_DEV:-\"\"}\ndeclare     ha_lfsck_types=${LFSCK_TYPES:-\"namespace layout\"}\ndeclare     ha_lfsck_custom_params=${LFSCK_CUSTOM_PARAMS:-\"\"}\ndeclare     ha_lfsck_wait=${LFSCK_WAIT:-1200}\ndeclare     ha_lfsck_fail_on_repaired=${LFSCK_FAIL_ON_REPAIRED:-false}\ndeclare     ha_power_down_cmd=${POWER_DOWN:-\"pm -0\"}\ndeclare     ha_power_up_cmd=${POWER_UP:-\"pm -1\"}\ndeclare     ha_power_delay=${POWER_DELAY:-60}\ndeclare     ha_failback_delay=${DELAY:-5}\ndeclare     ha_failback_cmd=${FAILBACK:-\"\"}\ndeclare     ha_stripe_params=${STRIPEPARAMS:-\"-c 0\"}\ndeclare     ha_dir_stripe_count=${DSTRIPECOUNT:-\"1\"}\ndeclare     ha_mdt_index=${MDTINDEX:-\"0\"}\ndeclare     ha_mdt_index_random=${MDTINDEXRAND:-false}\ndeclare -a  ha_clients\ndeclare -a  ha_servers\ndeclare -a  ha_victims\ndeclare     ha_test_dir=/mnt/lustre/$(basename $0)-$$\ndeclare     ha_start_time=$(date +%s)\ndeclare     ha_expected_duration=$((60 * 60 * 24))\ndeclare     ha_max_failover_period=10\ndeclare     ha_nr_loops=0\ndeclare     ha_stop_signals=\"SIGINT SIGTERM SIGHUP\"\ndeclare     ha_load_timeout=$((60 * 10))\ndeclare     ha_workloads_only=false\ndeclare     ha_workloads_dry_run=false\ndeclare     ha_simultaneous=false\n\ndeclare     ha_mpi_instances=${ha_mpi_instances:-1}\n\ndeclare     ha_mpi_loads=${ha_mpi_loads=\"ior simul mdtest\"}\ndeclare -a  ha_mpi_load_tags=($ha_mpi_loads)\ndeclare -a  ha_mpiusers=(${ha_mpi_users=\"mpiuser\"})\n\ndeclare     ha_ior_params=${IORP:-'\" -b $ior_blockSize -t 2m -w -W -T 1\"'}\ndeclare     ha_simul_params=${SIMULP:-'\" -n 10\"'}\ndeclare     ha_mdtest_params=${MDTESTP:-'\" -i 1 -n 1000\"'}\ndeclare     ha_mpirun_options=${MPIRUN_OPTIONS:-\"\"}\ndeclare     ha_clients_stripe=${CLIENTSSTRIPE:-'\"$STRIPEPARAMS\"'}\ndeclare     ha_nclientsset=${NCLIENTSSET:-1}\ndeclare     ha_ninstmustfail=${NINSTMUSTFAIL:-0}\n\ndeclare     ha_racer_params=${RACERP:-\"MDSCOUNT=1\"}\n\neval ha_params_ior=($ha_ior_params)\neval ha_params_simul=($ha_simul_params)\neval ha_params_mdtest=($ha_mdtest_params)\neval ha_stripe_clients=($ha_clients_stripe)\n\ndeclare ha_nparams_ior=${#ha_params_ior[@]}\ndeclare ha_nparams_simul=${#ha_params_simul[@]}\ndeclare ha_nparams_mdtest=${#ha_params_mdtest[@]}\ndeclare ha_nstripe_clients=${#ha_stripe_clients[@]}\n\ndeclare -A  ha_mpi_load_cmds=(\n\t[ior]=\"$IOR -o {}/f.ior {params}\"\n\t[simul]=\"$SIMUL {params} -d {}\"\n\t[mdtest]=\"$MDTEST {params} -d {}\"\n)\n\ndeclare racer=${RACER:-\"$(dirname $0)/racer/racer.sh\"}\n\ndeclare     ha_nonmpi_loads=${ha_nonmpi_loads=\"dd tar iozone\"}\ndeclare -a  ha_nonmpi_load_tags=($ha_nonmpi_loads)\ndeclare -A  ha_nonmpi_load_cmds=(\n\t[dd]=\"dd if=/dev/zero of={}/f.dd bs=1M count=256\"\n\t[tar]=\"tar cf - /etc | tar xf - -C {}\"\n\t[iozone]=\"iozone -a -e -+d -s $iozone_SIZE {}/f.iozone\"\n\t[racer]=\"$ha_racer_params $racer {}\"\n)\n\nha_usage()\n{\n    ha_info \"Usage: $0 -c HOST[,...] -s HOST[,...]\"                         \\\n            \"-v HOST[,...] [-d DIRECTORY] [-u SECONDS]\"\n}\n\nha_process_arguments()\n{\n    local opt\n\n\twhile getopts hc:s:v:d:p:u:wrm opt; do\n        case $opt in\n        h)\n            ha_usage\n            exit 0\n            ;;\n        c)\n            ha_clients=(${OPTARG//,/ })\n            ;;\n        s)\n            ha_servers=(${OPTARG//,/ })\n            ;;\n        v)\n            ha_victims=(${OPTARG//,/ })\n            ;;\n        d)\n            ha_test_dir=$OPTARG/$(basename $0)-$$\n            ;;\n        u)\n            ha_expected_duration=$OPTARG\n            ;;\n\tp)\n\t\tha_max_failover_period=$OPTARG\n\t\t;;\n        w)\n\t\tha_workloads_only=true\n\t\t;;\n\tr)\n\t\tha_workloads_dry_run=true\n\t\t;;\n\tm)\n\t\tha_simultaneous=true\n\t\t;;\n        \\?)\n            ha_usage\n            exit 1\n            ;;\n        esac\n    done\n\n\tif [ -z \"${ha_clients[*]}\" ]; then\n\t\tha_error \"-c is mandatory\"\n\t\tha_usage\n\t\texit 1\n\tfi\n\tif ! ($ha_workloads_dry_run ||\n\t\t\t$ha_workloads_only) &&\n\t\t\t([ -z \"${ha_servers[*]}\" ] ||\n\t\t\t[ -z \"${ha_victims[*]}\" ]); then\n\t\tha_error \"-s, and -v are all mandatory\"\n\t\tha_usage\n\t\texit 1\n\tfi\n}\n\nha_on()\n{\n\tlocal nodes=$1\n\tlocal rc=0\n\n\tshift\n\n\t#\n\t# -S is to be used here to track the\n\t# remote command return values\n\t#\n\tpdsh -S -w $nodes PATH=/usr/local/sbin:/usr/local/bin:/sbin:\\\n/bin:/usr/sbin:/usr/bin \"$@\" ||\n\t\trc=$?\n\treturn $rc\n}\n\nha_trap_exit()\n{\n\ttouch \"$ha_stop_file\"\n\ttrap 0\n\tif [ -e \"$ha_fail_file\" ]; then\n\t\tha_info \"Test directory $ha_test_dir not removed\"\n\t\tha_info \"Temporary directory $ha_tmp_dir not removed\"\n\telse\n\t\tha_on ${ha_clients[0]} rm -rf \"$ha_test_dir\"\n\t\tha_info \"Please find the results in the directory $ha_tmp_dir\"\n\tfi\n}\n\nha_trap_stop_signals()\n{\n    ha_info \"${ha_stop_signals// /,} received\"\n    touch \"$ha_stop_file\"\n}\n\nha_sleep()\n{\n    local n=$1\n\n    ha_info \"Sleeping for ${n}s\"\n    #\n    # sleep(1) could interrupted.\n    #\n    sleep $n || true\n}\n\nha_wait_unlock()\n{\n\tlocal lock=$1\n\n\twhile [ -e $lock ]; do\n\t\tsleep 1\n\tdone\n}\n\nha_lock()\n{\n    local lock=$1\n\n    until mkdir \"$lock\" >/dev/null 2>&1; do\n        ha_sleep 1 >/dev/null\n    done\n}\n\nha_unlock()\n{\n    local lock=$1\n\n    rm -r \"$lock\"\n}\n\nha_dump_logs()\n{\n\tlocal nodes=${1// /,}\n\tlocal file=/tmp/$(basename $0)-$$-$(date +%s).dk\n\tlocal lock=$ha_tmp_dir/lock-dump-logs\n\tlocal rc=0\n\n\tha_lock \"$lock\"\n\tha_info \"Dumping lctl log to $file\"\n\n\t#\n\t# some nodes could crash, so\n\t# do not exit with error if not all logs are dumped\n\t#\n\tha_on $nodes \"lctl dk >>$file\" || rc=$?\n\n\t[ $rc -eq 0 ] ||\n\t\tha_error \"not all logs are dumped! Some nodes are unreachable.\"\n\tha_unlock \"$lock\"\n}\n\nha_repeat_mpi_load()\n{\n\tlocal client=$1\n\tlocal load=$2\n\tlocal status=$3\n\tlocal parameter=$4\n\tlocal machines=$5\n\tlocal stripeparams=$6\n\tlocal mpiuser=$7\n\tlocal mustpass=$8\n\tlocal tag=${ha_mpi_load_tags[$load]}\n\tlocal cmd=${ha_mpi_load_cmds[$tag]}\n\tlocal dir=$ha_test_dir/$client-$tag\n\tlocal log=$ha_tmp_dir/$client-$tag\n\tlocal rc=0\n\tlocal nr_loops=0\n\tlocal avg_loop_time=0\n\tlocal start_time=$(date +%s)\n\n\tcmd=${cmd//\"{}\"/$dir}\n\tcmd=${cmd//\"{params}\"/$parameter}\n\n\t[[ -n \"$ha_postcmd\" ]] && ha_postcmd=${ha_postcmd//\"{}\"/$dir}\n\tha_info \"Starting $tag\"\n\n\tmachines=\"-machinefile $machines\"\n\twhile [ ! -e \"$ha_stop_file\" ] && ((rc == 0)); do\n\t\tha_info \"$client Starts: $cmd\" 2>&1 |  tee -a $log\n\t\t{\n\t\tlocal mdt_index\n\t\tif $ha_mdt_index_random && [ $ha_mdt_index -ne 0 ]; then\n\t\t\tmdt_index=$(ha_rand $ha_mdt_index)\n\t\telse\n\t\t\tmdt_index=$ha_mdt_index\n\t\tfi\n\t\tha_on $client $LFS mkdir -i$mdt_index -c$ha_dir_stripe_count \"$dir\" &&\n\t\tha_on $client $LFS getdirstripe \"$dir\" &&\n\t\tha_on $client $LFS setstripe $stripeparams $dir &&\n\t\tha_on $client $LFS getstripe $dir &&\n\t\tha_on $client chmod a+xwr $dir &&\n\t\tha_on $client \"su $mpiuser sh -c \\\" $mpirun $ha_mpirun_options \\\n\t\t\t-np $((${#ha_clients[@]} * mpi_threads_per_client )) \\\n\t\t\t$machines $cmd \\\" \" || rc=$?\n\t\t[[ -n \"$ha_postcmd\" ]] && ha_info \"$ha_postcmd\" &&\n\t\t\tha_on $client $ha_postcmd >>\"$log\" 2>&1\n\t\t(( ((rc == 0)) && (( mustpass != 0 )) )) ||\n\t\t(( ((rc != 0)) && (( mustpass == 0 )) )) &&\n\t\t\tha_on $client rm -rf \"$dir\";\n\t\t} >>\"$log\" 2>&1 || rc=$?\n\n\t\tha_info rc=$rc mustpass=$mustpass\n\n\t\t# mustpass=0 means that failure is expected\n\t\tif (( rc !=0 )); then\n\t\t\tif (( mustpass != 0 )); then\n\t\t\t\ttouch \"$ha_fail_file\"\n\t\t\t\ttouch \"$ha_stop_file\"\n\t\t\t\tha_dump_logs \"${ha_clients[*]} ${ha_servers[*]}\"\n\t\t\telse\n\t\t\t\t# Ok to fail\n\t\t\t\trc=0\n\t\t\tfi\n\t\telif (( mustpass == 0 )); then\n\t\t\ttouch \"$ha_fail_file\"\n\t\t\ttouch \"$ha_stop_file\"\n\t\t\tha_dump_logs \"${ha_clients[*]} ${ha_servers[*]}\"\n\t\tfi\n\t\techo rc=$rc mustpass=$mustpass >\"$status\"\n\n\t\tnr_loops=$((nr_loops + 1))\n\tdone\n\n\t[ $nr_loops -ne 0 ] &&\n\t\tavg_loop_time=$((($(date +%s) - start_time) / nr_loops))\n\n\tha_info \"$tag stopped: rc=$rc mustpass=$mustpass \\\n\t\tavg loop time $avg_loop_time\"\n}\n\nha_start_mpi_loads()\n{\n\tlocal client\n\tlocal load\n\tlocal tag\n\tlocal status\n\tlocal n\n\tlocal nparam\n\tlocal machines\n\tlocal m\n\tlocal -a mach\n\tlocal mpiuser\n\n\t# ha_mpi_instances defines the number of\n\t# clients start mpi loads; should be <= ${#ha_clients[@]}\n\t# do nothing if\n\t#    ha_mpi_instances = 0\n\t# or\n\t#    ${#ha_mpi_load_tags[@]} =0\n\tlocal inst=$ha_mpi_instances\n\t(( inst == 0 )) || (( ${#ha_mpi_load_tags[@]} == 0 )) &&\n\t\tha_info \"no mpi load to start\" &&\n\t\treturn 0\n\n\t(( inst <= ${#ha_clients[@]} )) || inst=${#ha_clients[@]}\n\n\t# Define names for machinefiles for each client set\n\tfor (( n=0; n < $ha_nclientsset; n++ )); do\n\t\tmach[$n]=$ha_machine_file$n\n\tdone\n\n\tfor ((n = 0; n < ${#ha_clients[@]}; n++)); do\n\t\tm=$(( n % ha_nclientsset))\n\t\tmachines=${mach[m]}\n\t\tha_info machine_file=$machines\n\t\techo ${ha_clients[n]} >> $machines\n\tdone\n\tlocal dirname=$(dirname $ha_machine_file)\n\tfor client in ${ha_clients[@]}; do\n\t\tha_on $client mkdir -p $dirname\n\t\tscp $ha_machine_file* $client:$dirname\n\tdone\n\n\tfor ((n = 0; n < $inst; n++)); do\n\t\tclient=${ha_clients[n]}\n\t\tmpiuser=${ha_mpiusers[$((n % ${#ha_mpiusers[@]}))]}\n\t\tfor ((load = 0; load < ${#ha_mpi_load_tags[@]}; load++)); do\n\t\t\ttag=${ha_mpi_load_tags[$load]}\n\t\t\tstatus=$ha_status_file_prefix-$tag-$client\n\t\t\t# ha_nparams_ior\n\t\t\t# ha_nparams_simul\n\t\t\tlocal num=ha_nparams_$tag\n\t\t\tnparam=$((n % num))\n\t\t\tlocal aref=ha_params_$tag[nparam]\n\t\t\tlocal parameter=${!aref}\n\t\t\tlocal nstripe=$((n % ha_nstripe_clients))\n\t\t\taref=ha_stripe_clients[nstripe]\n\t\t\tlocal stripe=${!aref}\n\t\t\tlocal m=$(( n % ha_nclientsset))\n\t\t\tmachines=${mach[m]}\n\t\t\tlocal mustpass=1\n\t\t\t[[ $ha_ninstmustfail == 0 ]] ||\n\t\t\t\tmustpass=$(( n % ha_ninstmustfail ))\n\t\t\tha_repeat_mpi_load $client $load $status \"$parameter\" \\\n\t\t\t\t$machines \"$stripe\" \"$mpiuser\" \"$mustpass\" &\n\t\t\t\tha_status_files+=(\"$status\")\n\t\tdone\n\tdone\n}\n\nha_repeat_nonmpi_load()\n{\n\tlocal client=$1\n\tlocal load=$2\n\tlocal status=$3\n\tlocal tag=${ha_nonmpi_load_tags[$load]}\n\tlocal cmd=${ha_nonmpi_load_cmds[$tag]}\n\tlocal dir=$ha_test_dir/$client-$tag\n\tlocal log=$ha_tmp_dir/$client-$tag\n\tlocal rc=0\n\tlocal nr_loops=0\n\tlocal avg_loop_time=0\n\tlocal start_time=$(date +%s)\n\n\tcmd=${cmd//\"{}\"/$dir}\n\n\tha_info \"Starting $tag on $client\"\n\n\twhile [ ! -e \"$ha_stop_file\" ] && ((rc == 0)); do\n\t\tha_info \"$client Starts: $cmd\" 2>&1 |  tee -a $log\n\t\tha_on $client \"mkdir -p $dir &&                              \\\n\t\t\t$cmd &&                                              \\\n\t\t\trm -rf $dir\" >>\"$log\" 2>&1 || rc=$?\n\n\t\tif ((rc != 0)); then\n\t\t\tha_dump_logs \"${ha_clients[*]} ${ha_servers[*]}\"\n\t\t\ttouch \"$ha_fail_file\"\n\t\t\ttouch \"$ha_stop_file\"\n\t\tfi\n\t\techo $rc >\"$status\"\n\n\t\tnr_loops=$((nr_loops + 1))\n\tdone\n\n\t[ $nr_loops -ne 0 ] &&\n\t\tavg_loop_time=$((($(date +%s) - start_time) / nr_loops))\n\n\tha_info \"$tag on $client stopped: rc $rc avg loop time ${avg_loop_time}s\"\n}\n\nha_start_nonmpi_loads()\n{\n    local client\n    local load\n    local tag\n    local status\n\n    for client in ${ha_clients[@]}; do\n        for ((load = 0; load < ${#ha_nonmpi_load_tags[@]}; load++)); do\n            tag=${ha_nonmpi_load_tags[$load]}\n            status=$ha_status_file_prefix-$tag-$client\n            ha_repeat_nonmpi_load $client $load $status &\n            ha_status_files+=(\"$status\")\n        done\n    done\n}\n\nha_lfsck_bg () {\n\trm -f $ha_lfsck_log\n\trm -f $ha_lfsck_stop\n\n\tha_info \"LFSCK BG\"\n\twhile [ true ]; do\n\t\t[ -f $ha_lfsck_stop ] && ha_info \"LFSCK stopped\" && break\n\t\t[ -f $ha_stop_file ] &&\n\t\t\tha_info \"$ha_stop_file found! LFSCK not started\" &&\n\t\t\tbreak\n\t\tha_start_lfsck 2>&1 | tee -a $ha_lfsck_log\n\t\tsleep 1\n\tdone &\n\tLFSCK_BG_PID=$!\n\tha_info LFSCK BG PID: $LFSCK_BG_PID\n}\n\nha_wait_lfsck_completed () {\n\tlocal -a status\n\tlocal -a types=($ha_lfsck_types)\n\tlocal type\n\tlocal s\n\n\tlocal nodes=\"${ha_servers[@]}\"\n\tnodes=${nodes// /,}\n\n\t# -A start LFSCK on all nodes\n\t# -t default all\n\t[ ${#types[@]} -eq 0 ] && types=(namespace layout)\n\tha_info \"Waiting LFSCK completed in $ha_lfsck_wait sec: types ${types[@]}\"\n\tfor type in ${types[@]}; do\n\t\teval var_$type=0\n\t\tfor (( i=0; i<=ha_lfsck_wait; i++)); do\n\t\t\tstatus=($(ha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null | \\\n\t\t\t\tawk '/status/ { print $3 }'))\n\t\t\tfor (( s=0; s<${#status[@]}; s++ )); do\n\t\t\t\t# \"partial\" is expected after HARD failover\n\t\t\t\t[[ \"${status[s]}\" = \"completed\" ]] ||\n\t\t\t\t[[ \"${status[s]}\" = \"partial\" ]] ||  break\n\t\t\tdone\n\t\t\t[[ $s -eq ${#status[@]} ]] && eval var_$type=1 && break\n\t\t\tsleep 1\n\t\tdone\n\t\tha_info \"LFSCK $type status in $i sec:\"\n\t\tha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null | grep status\n\n\tdone\n\n\tfor type in ${types[@]}; do\n\t\tlocal var=var_$type\n\t\tha_on $nodes lctl get_param -n *.*.lfsck_$type 2>/dev/null\n\t\t[[ ${!var} -eq 1 ]] ||\n\t\t\t{ ha_info \"lfsck not completed in $ha_lfsck_wait sec\";\n\t\t\treturn 1; }\n\tdone\n\treturn 0\n}\n\nha_start_lfsck()\n{\n\tlocal -a types=($ha_lfsck_types)\n\tlocal rc=0\n\n\t# -A: start LFSCK on all nodes via the specified MDT device\n\t# (see \"-M\" option) by single LFSCK command\n\tlocal params=\" -A -r $ha_lfsck_custom_params\"\n\n\t# use specified device if set\n\t[ -n \"$ha_lfsck_device\" ] && params=\"-M $ha_lfsck_device $params\"\n\n\t# -t: check type(s) to be performed (default all)\n\t# check only specified types if set\n\tif [ ${#types[@]} -ne 0 ]; then\n\t\tlocal type=\"${types[@]}\"\n\t\tparams=\"$params -t ${type// /,}\"\n\tfi\n\n\tha_info \"LFSCK start $params\"\n\tha_on $ha_lfsck_node \"lctl lfsck_start $params\" || rc=1\n\tif [ $rc -ne 0 ]; then\n\t\tif [ -e $ha_lfsck_lock ]; then\n\t\t\trc=0\n\t\t\tha_wait_unlock $ha_lfsck_lock\n\t\t\tha_sleep 120\n\t\t\tha_on $ha_lfsck_node \"lctl lfsck_start $params\" || rc=1\n\t\tfi\n\tfi\n\n\t[ $rc -eq 0 ] ||\n\t\t{ touch \"$ha_fail_file\"; touch \"$ha_stop_file\";\n\t\ttouch $ha_lfsck_stop; return 1; }\n\n\tha_wait_lfsck_completed ||\n\t\t{ touch \"$ha_fail_file\"; touch \"$ha_stop_file\";\n\t\ttouch $ha_lfsck_stop; return 1; }\n\n\treturn 0\n}\n\nha_lfsck_repaired()\n{\n\tlocal n=0\n\n\tn=$(cat $ha_lfsck_log | awk '/repaired/ {print $3}' |\\\n\t\tawk '{sum += $1} END { print sum }')\n\t[ $n -eq 0] ||\n\t\t{ ha_info \"Total repaired: $n\";\n\t\ttouch \"$ha_fail_file\"; return 1; }\n\treturn 0\n}\n\nha_start_loads()\n{\n\t$ha_lfsck_bg && ha_lfsck_bg\n\ttrap ha_trap_stop_signals $ha_stop_signals\n\tha_start_nonmpi_loads\n\tha_start_mpi_loads\n}\n\nha_stop_loads()\n{\n\ttouch $ha_stop_file\n\t# true because of lfsck_bg could be stopped already\n\t$ha_lfsck_bg && wait $LFSCK_BG_PID || true\n\ttrap - $ha_stop_signals\n\tha_info \"Waiting for workloads to stop\"\n\twait\n}\n\nha_wait_loads()\n{\n    local file\n    local end=$(($(date +%s) + ha_load_timeout))\n\n    ha_info \"Waiting for workload status\"\n    rm -f \"${ha_status_files[@]}\"\n\n\t#\n\t# return immediately if ha_stop_file exists,\n\t# all status_files not needed to be checked\n\t#\n\tfor file in \"${ha_status_files[@]}\"; do\n\t\tif [ -e \"$ha_stop_file\" ]; then\n\t\t\tha_info \"$ha_stop_file found! Stop.\"\n\t\t\tbreak\n\t\tfi\n\t\t#\n\t\t# Wait status file created during ha_load_timeout.\n\t\t# Existing file guarantees that some application\n\t\t# is completed. If no status file was created\n\t\t# this function guarantees that we allow\n\t\t# applications to continue after/before\n\t\t# failover/failback during ha_load_timeout time.\n\t\t#\n\t\tuntil [ -e \"$file\" ] || (($(date +%s) >= end)); do\n\t\t\t#\n\t\t\t# check ha_stop_file again, it could appear\n\t\t\t# during ha_load_timeout\n\t\t\t#\n\t\t\tif [ -e \"$ha_stop_file\" ]; then\n\t\t\t\tha_info \"$ha_stop_file found! Stop.\"\n\t\t\t\tbreak\n\t\t\tfi\n\t\t\tha_sleep 1 >/dev/null\n\t\tdone\n\tdone\n}\n\nha_power_down()\n{\n\tlocal nodes=$1\n\tlocal rc=1\n\tlocal i\n\n\tif $ha_lfsck_bg && [[ ${nodes//,/ /} =~ $ha_lfsck_node ]]; then\n\t\tha_info \"$ha_lfsck_node down, delay start LFSCK\"\n\t\tha_lock $ha_lfsck_lock\n\tfi\n\n\tha_info \"Powering down $nodes\"\n\tfor i in $(seq 1 5); do\n\t\t$ha_power_down_cmd $nodes && rc=0 && break\n\t\tsleep $ha_power_delay\n\tdone\n\n\t[ $rc -eq 0 ] || ha_info \"Failed Powering down in $i attempts\"\n}\n\nha_power_up()\n{\n\tlocal nodes=$1\n\tlocal rc=1\n\tlocal i\n\n\tha_info \"Powering up $nodes\"\n\tfor i in $(seq 1 5); do\n\t\t$ha_power_up_cmd $nodes && rc=0 && break\n\t\tsleep $ha_power_delay\n\tdone\n\n\t[ $rc -eq 0 ] || ha_info \"Failed Powering up in $i attempts\"\n}\n\n#\n# rand MAX\n#\n# Print a random integer within [0, MAX).\n#\nha_rand()\n{\n    local max=$1\n\n    #\n    # See \"5.2 Bash Variables\" from \"info bash\".\n    #\n    echo -n $((RANDOM * max / 32768))\n}\n\nha_aim()\n{\n\tlocal i\n\tlocal nodes\n\n\tif $ha_simultaneous ; then\n\t\tnodes=$(echo ${ha_victims[@]})\n\t\tnodes=${nodes// /,}\n\telse\n\t\ti=$(ha_rand ${#ha_victims[@]})\n\t\tnodes=${ha_victims[$i]}\n\tfi\n\n\techo -n $nodes\n}\n\nha_wait_nodes()\n{\n\tlocal nodes=$1\n\tlocal end=$(($(date +%s) + 10 * 60))\n\n\tha_info \"Waiting for $nodes to boot up\"\n\tuntil ha_on $nodes hostname >/dev/null 2>&1 ||\n\t\t[ -e \"$ha_stop_file\" ] ||\n\t\t\t(($(date +%s) >= end)); do\n\t\tha_sleep 1 >/dev/null\n\tdone\n}\n\nha_failback()\n{\n\tlocal nodes=$1\n\tha_info \"Failback resources on $nodes in $ha_failback_delay sec\"\n\n\tha_sleep $ha_failback_delay\n\t[ \"$ha_failback_cmd\" ] ||\n\t{\n\t\tha_info \"No failback command set, skiping\"\n\t\treturn 0\n\t}\n\n\t$ha_failback_cmd $nodes\n\t[ -e $ha_lfsck_lock ] && ha_unlock $ha_lfsck_lock || true\n}\n\nha_summarize()\n{\n    ha_info \"---------------8<---------------\"\n    ha_info \"Summary:\"\n    ha_info \"    Duration: $(($(date +%s) - $ha_start_time))s\"\n    ha_info \"    Loops: $ha_nr_loops\"\n}\n\nha_killer()\n{\n\tlocal nodes\n\n\twhile (($(date +%s) < ha_start_time + ha_expected_duration)) &&\n\t\t\t[ ! -e \"$ha_stop_file\" ]; do\n\t\tha_info \"---------------8<---------------\"\n\n\t\t$ha_workloads_only || nodes=$(ha_aim)\n\n\t\tha_info \"Failing $nodes\"\n\t\t$ha_workloads_only && ha_info \"    is skipped: workload only...\"\n\n\t\tha_sleep $(ha_rand $ha_max_failover_period)\n\t\t$ha_workloads_only || ha_power_down $nodes\n\t\tha_sleep 10\n\t\tha_wait_loads || return\n\n\t\tif [ -e $ha_stop_file ]; then\n\t\t\t$ha_workloads_only || ha_power_up $nodes\n\t\t\tbreak\n\t\tfi\n\n\t\tha_info \"Bringing $nodes back\"\n\t\tha_sleep $(ha_rand 10)\n\t\t$ha_workloads_only ||\n\t\t{\n\t\t\tha_power_up $nodes\n\t\t\tha_wait_nodes $nodes\n\t\t\tha_failback $nodes\n\t\t}\n\n\t\t#\n\t\t# Wait for the failback to start.\n\t\t#\n\t\tha_sleep 60\n\t\tha_wait_loads || return\n\n\t\tha_sleep $(ha_rand 20)\n\n\t\tha_nr_loops=$((ha_nr_loops + 1))\n\t\tha_info \"Loop $ha_nr_loops done\"\n\tdone\n\tha_summarize\n}\n\nha_main()\n{\n\tha_process_arguments \"$@\"\n\tha_check_env\n\n\tha_log \"${ha_clients[*]} ${ha_servers[*]}\" \\\n\t\t\"START: $0: $(date +%H:%M:%S' '%s)\"\n\ttrap ha_trap_exit EXIT\n\tmkdir \"$ha_tmp_dir\"\n\tha_on ${ha_clients[0]} mkdir \"$ha_test_dir\"\n\tha_on ${ha_clients[0]} \" \\\n\t\t$LFS setstripe $ha_stripe_params $ha_test_dir\"\n\n\tha_start_loads\n\tha_wait_loads\n\n\tif $ha_workloads_dry_run; then\n\t\tha_sleep 5\n\telse\n\t\tha_killer\n\t\tha_dump_logs \"${ha_clients[*]} ${ha_servers[*]}\"\n\tfi\n\n\tha_stop_loads\n\n\t$ha_lfsck_after && ha_start_lfsck | tee -a $ha_lfsck_log\n\n\t$ha_lfsck_fail_on_repaired && ha_lfsck_repaired\n\n\tif [ -e \"$ha_fail_file\" ]; then\n\t\texit 1\n\telse\n\t\tha_log \"${ha_clients[*]} ${ha_servers[*]}\" \\\n\t\t\t\"END: $0: $(date +%H:%M:%S' '%s)\"\n\t\texit 0\n\tfi\n}\n\nha_main \"$@\"\n", "num_lines": 977}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Test different failure modes combinations\n\nset -e\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$INSANITY_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nif [ \"$FAILURE_MODE\" = \"HARD\" ]; then\n\tskip_env \"$TESTSUITE: is not functional with FAILURE_MODE = HARD, \" \\\n\t\t\"please use recovery-double-scale, bz20407\"\nfi\n\nSINGLECLIENT=${SINGLECLIENT:-$HOSTNAME}\nLIVE_CLIENT=${LIVE_CLIENT:-$SINGLECLIENT}\nFAIL_CLIENTS=${FAIL_CLIENTS:-$RCLIENTS}\n\nassert_env mds_HOST MDSCOUNT\nassert_env ost_HOST OSTCOUNT\nassert_env LIVE_CLIENT FSNAME\n\nrequire_dsh_mds || exit 0\nrequire_dsh_ost || exit 0\n\n# FAIL_CLIENTS list should not contain the LIVE_CLIENT\nFAIL_CLIENTS=$(echo \" $FAIL_CLIENTS \" | sed -re \"s/\\s+$LIVE_CLIENT\\s+/ /g\")\n\nDIR=${DIR:-$MOUNT}\nTESTDIR=$DIR/d0.$TESTSUITE\n\n#####\n# fail clients round robin\n\n# list of failable clients\nFAIL_LIST=($FAIL_CLIENTS)\nFAIL_NUM=${#FAIL_LIST[*]}\nFAIL_NEXT=0\ntypeset -i  FAIL_NEXT\nDOWN_NUM=0   # number of nodes currently down\n\n# set next client to fail\nset_fail_client() {\n\tFAIL_CLIENT=${FAIL_LIST[$FAIL_NEXT]}\n\tFAIL_NEXT=$(( (FAIL_NEXT+1) % FAIL_NUM ))\n\techo \"fail $FAIL_CLIENT, next is $FAIL_NEXT\"\n}\n\nfail_clients() {\n\tnum=$1\n\n\tlog \"Request fail clients: $num, to fail: $FAIL_NUM, failed: $DOWN_NUM\"\n\tif [ -z \"$num\"  ] || [ \"$num\" -gt $((FAIL_NUM - DOWN_NUM)) ]; then\n\t\tnum=$((FAIL_NUM - DOWN_NUM))\n\tfi\n\n\tif [ -z \"$num\" ] || [ \"$num\" -le 0 ]; then\n\t\tlog \"No clients failed!\"\n\t\treturn\n\tfi\n\n\tclient_mkdirs\n\n\tfor i in `seq $num`; do\n\t\tset_fail_client\n\t\tclient=$FAIL_CLIENT\n\t\tDOWN_CLIENTS=\"$DOWN_CLIENTS $client\"\n\t\tshutdown_client $client\n\tdone\n\n\techo \"down clients: $DOWN_CLIENTS\"\n\n\tfor client in $DOWN_CLIENTS; do\n\t\tboot_node $client\n\tdone\n\tDOWN_NUM=`echo $DOWN_CLIENTS | wc -w`\n\tclient_rmdirs\n}\n\nreintegrate_clients() {\n\tfor client in $DOWN_CLIENTS; do\n\t\twait_for_host $client\n\t\techo \"Restarting $client\"\n\t\tzconf_mount $client $MOUNT || return 1\n\tdone\n\n\tDOWN_CLIENTS=\"\"\n\tDOWN_NUM=0\n}\n\nstart_ost() {\n\tstart ost$1 `ostdevname $1` $OST_MOUNT_OPTS\n}\n\nstart_mdt() {\n\tstart mds$1 $(mdsdevname $1) $MDS_MOUNT_OPTS\n}\n\ntrap exit INT\n\nclient_touch() {\n\tfile=$1\n\tfor c in $LIVE_CLIENT $FAIL_CLIENTS; do\n\t\techo $DOWN_CLIENTS | grep -q $c && continue\n\t\t$PDSH $c touch $TESTDIR/${c}_$file || return 1\n\tdone\n}\n\nclient_rm() {\n\tfile=$1\n\tfor c in $LIVE_CLIENT $FAIL_CLIENTS; do\n\t\t$PDSH $c rm $TESTDIR/${c}_$file\n\tdone\n}\n\nclient_mkdirs() {\n\tfor c in $LIVE_CLIENT $FAIL_CLIENTS; do\n\t\techo \"$c mkdir $TESTDIR/$c\"\n\t\t$PDSH $c \"mkdir $TESTDIR/$c && ls -l $TESTDIR/$c\"\n\tdone\n}\n\nclient_rmdirs() {\n\tfor c in $LIVE_CLIENT $FAIL_CLIENTS; do\n\t\techo \"rmdir $TESTDIR/$c\"\n\t\t$PDSH $LIVE_CLIENT \"rmdir $TESTDIR/$c\"\n\tdone\n}\n\nclients_recover_osts() {\n    facet=$1\n#    do_node $CLIENTS \"$LCTL \"'--device %OSC_`hostname`_'\"${facet}_svc_MNT_client_facet recover\"\n}\n\ncheck_and_setup_lustre\n\nrm -rf $TESTDIR\nmkdir -p $TESTDIR\n\ntest_0() {\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\tfail mds$i\n\tdone\n\n\tfor i in $(seq $OSTCOUNT) ; do\n\t\tfail ost$i\n\tdone\n\treturn 0\n}\nrun_test 0 \"Fail all nodes, independently\"\n\n############### First Failure Mode ###############\ntest_1() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\n\tclients_up\n\n\tshutdown_facet mds1\n\treboot_facet mds1\n\n\t# prepare for MDS failover\n\tchange_active mds1\n\treboot_facet mds1\n\n\tclients_up &\n\tDFPID=$!\n\tsleep 5\n\n\tshutdown_facet mds2\n\n\techo \"Reintegrating MDS2\"\n\treboot_facet mds2\n\twait_for_facet mds2\n\tstart_mdt 2 || return 2\n\n\twait_for_facet mds1\n\tstart_mdt 1 || return $?\n\n\t#Check FS\n\twait $DFPID\n\techo \"Verify reintegration\"\n\tclients_up || return 1\n}\nrun_test 1 \"MDS/MDS failure\"\n###################################################\n\n############### Second Failure Mode ###############\ntest_2() {\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\tshutdown_facet mds$i\n\t\treboot_facet mds$i\n\n\t\t# prepare for MDS failover\n\t\tchange_active mds$i\n\t\treboot_facet mds$i\n\tdone\n\n\tclients_up &\n\tDFPID=$!\n\tsleep 5\n\n\tshutdown_facet ost1\n\n\techo \"Reintegrating OST\"\n\treboot_facet ost1\n\twait_for_facet ost1\n\tstart_ost 1 || return 2\n\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\twait_for_facet mds$i\n\t\tstart_mdt $i || return $?\n\tdone\n\n\t#Check FS\n\twait $DFPID\n\tclients_recover_osts ost1\n\techo \"Verify reintegration\"\n\tclients_up || return 1\n\n}\nrun_test 2 \"Second Failure Mode: MDS/OST `date`\"\n###################################################\n\n############### Third Failure Mode ###############\ntest_3() {\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\t#MDS Portion\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\tfail mds$i\n\tdone\n\n\t#Check FS\n\techo \"Test Lustre stability after MDS failover\"\n\tclients_up\n\n\t#CLIENT Portion\n\techo \"Failing 2 CLIENTS\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENT failure\"\n\tclients_up\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTS\"\n\treintegrate_clients || return 1\n\n\tclients_up || return 3\n\tsleep 2 # give it a little time for fully recovered before next test\n}\nrun_test 3  \"Third Failure Mode: MDS/CLIENT `date`\"\n###################################################\n\n############### Fourth Failure Mode ###############\ntest_4() {\n\techo \"Fourth Failure Mode: OST/MDS `date`\"\n\n\t#OST Portion\n\tshutdown_facet ost1\n\n\t#Check FS\n\techo \"Test Lustre stability after OST failure\"\n\tclients_up &\n\tDFPIDA=$!\n\tsleep 5\n\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\tshutdown_facet mds$i\n\t\treboot_facet mds$i\n\n\t\t# prepare for MDS failover\n\t\tchange_active mds$i\n\t\treboot_facet mds$i\n\tdone\n\n\tclients_up &\n\tDFPIDB=$!\n\tsleep 5\n\n\t#Reintegration\n\techo \"Reintegrating OST\"\n\treboot_facet ost1\n\twait_for_facet ost1\n\tstart_ost 1\n\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\twait_for_facet mds$i\n\t\tstart_mdt $i || return $?\n\tdone\n\n\t#Check FS\n\twait $DFPIDA\n\twait $DFPIDB\n\tclients_recover_osts ost1\n\techo \"Test Lustre stability after MDS failover\"\n\tclients_up || return 1\n}\nrun_test 4 \"Fourth Failure Mode: OST/MDS `date`\"\n###################################################\n\n############### Fifth Failure Mode ###############\ntest_5() {\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\n\techo \"Fifth Failure Mode: OST/OST `date`\"\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\t#OST Portion\n\tshutdown_facet ost1\n\treboot_facet ost1\n\n\t#Check FS\n\techo \"Test Lustre stability after OST failure\"\n\tclients_up &\n\tDFPIDA=$!\n\tsleep 5\n\n\t#OST Portion\n\tshutdown_facet ost2\n\treboot_facet ost2\n\n\t#Check FS\n\techo \"Test Lustre stability after OST failure\"\n\tclients_up &\n\tDFPIDB=$!\n\tsleep 5\n\n\t#Reintegration\n\techo \"Reintegrating OSTs\"\n\twait_for_facet ost1\n\tstart_ost 1\n\twait_for_facet ost2\n\tstart_ost 2\n\n\tclients_recover_osts ost1\n\tclients_recover_osts ost2\n\tsleep $TIMEOUT\n\n\twait $DFPIDA\n\twait $DFPIDB\n\tclients_up || return 2\n}\nrun_test 5 \"Fifth Failure Mode: OST/OST `date`\"\n###################################################\n\n############### Sixth Failure Mode ###############\ntest_6() {\n\techo \"Sixth Failure Mode: OST/CLIENT `date`\"\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\tclient_touch testfile || return 2\n\n\t#OST Portion\n\tshutdown_facet ost1\n\treboot_facet ost1\n\n\t#Check FS\n\techo \"Test Lustre stability after OST failure\"\n\tclients_up &\n\tDFPIDA=$!\n\techo DFPIDA=$DFPIDA\n\tsleep 5\n\n\t#CLIENT Portion\n\techo \"Failing CLIENTs\"\n\tfail_clients\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENTs failure\"\n\tclients_up &\n\tDFPIDB=$!\n\techo DFPIDB=$DFPIDB\n\tsleep 5\n\n\t#Reintegration\n\techo \"Reintegrating OST/CLIENTs\"\n\twait_for_facet ost1\n\tstart_ost 1\n\treintegrate_clients || return 1\n\tsleep 5\n\n\twait_remote_prog \"stat -f\" $((TIMEOUT * 3 + 20))\n\twait $DFPIDA\n\twait $DFPIDB\n\n\techo \"Verifying mount\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && return 3\n\tclients_up\n}\nrun_test 6 \"Sixth Failure Mode: OST/CLIENT `date`\"\n###################################################\n\n############### Seventh Failure Mode ###############\ntest_7() {\n\techo \"Seventh Failure Mode: CLIENT/MDS `date`\"\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\tclient_touch testfile  || return 1\n\n\t#CLIENT Portion\n\techo \"Part 1: Failing CLIENT\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENTs failure\"\n\tclients_up\n\t$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\"\n\t$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\"\n\n\t#Sleep\n\techo \"Wait 1 minutes\"\n\tsleep 60\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && return 2\n\n\tclients_up\n\tclient_rm testfile\n\n\t#MDS Portion\n\tfor i in $(seq $MDSCOUNT) ; do\n\t\tfail mds$i\n\tdone\n\n\t$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\"\n\t$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\"\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTs\"\n\treintegrate_clients || return 2\n\tclients_up\n\n\t#Sleep\n\techo \"wait 1 minutes\"\n\tsleep 60\n}\nrun_test 7 \"Seventh Failure Mode: CLIENT/MDS `date`\"\n###################################################\n\n############### Eighth Failure Mode ###############\ntest_8() {\n\techo \"Eighth Failure Mode: CLIENT/OST `date`\"\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\tclient_touch testfile\n\n\t#CLIENT Portion\n\techo \"Failing CLIENTs\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENTs failure\"\n\tclients_up\n\t$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\"\n\t$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\"\n\n\t#Sleep\n\techo \"Wait 1 minutes\"\n\tsleep 60\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\tclient_touch testfile\n\n\t#OST Portion\n\tshutdown_facet ost1\n\treboot_facet ost1\n\n\t#Check FS\n\techo \"Test Lustre stability after OST failure\"\n\tclients_up &\n\tDFPID=$!\n\tsleep 5\n\t#non-failout hangs forever here\n\t#$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\"\n\t#$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\"\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTs/OST\"\n\treintegrate_clients || return 3\n\twait_for_facet ost1\n\tstart_ost 1\n\twait $DFPID\n\tclients_up || return 1\n\tclient_touch testfile2 || return 2\n\n\t#Sleep\n\techo \"Wait 1 minutes\"\n\tsleep 60\n}\nrun_test 8 \"Eighth Failure Mode: CLIENT/OST `date`\"\n###################################################\n\n############### Ninth Failure Mode ###############\ntest_9() {\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\tclients_up\n\tclient_touch testfile || return 1\n\n\t#CLIENT Portion\n\techo \"Failing CLIENTs\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENTs failure\"\n\tclients_up\n\t$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\" || return 1\n\t$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\" || return 2\n\n\t#Sleep\n\techo \"Wait 1 minutes\"\n\tsleep 60\n\n\t#Create files\n\techo \"Verify Lustre filesystem is up and running\"\n\tclient_up $LIVE_CLIENT || return 3\n\tclient_touch testfile || return 4\n\n\t#CLIENT Portion\n\techo \"Failing CLIENTs\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENTs failure\"\n\tclients_up\n\t$PDSH $LIVE_CLIENT \"ls -l $TESTDIR\" || return 5\n\t$PDSH $LIVE_CLIENT \"rm -f $TESTDIR/*_testfile\" || return 6\n\n\t#Reintegration\n\techo \"Reintegrating  CLIENTs/CLIENTs\"\n\treintegrate_clients || return 7\n\tclients_up\n\n\t#Sleep\n\techo \"Wait 1 minutes\"\n\tsleep 60\n}\nrun_test 9 \"Ninth Failure Mode: CLIENT/CLIENT `date`\"\n###################################################\n\n############### Tenth Failure Mode ###############\ntest_10() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\n\tshutdown_facet mds1\n\treboot_facet mds1\n\n\t# prepare for MDS failover\n\tchange_active mds1\n\treboot_facet mds1\n\n\tclients_up &\n\tDFPID=$!\n\tsleep 5\n\n\tshutdown_facet ost1\n\n\techo \"Reintegrating OST\"\n\treboot_facet ost1\n\twait_for_facet ost1\n\tstart_ost 1 || return 2\n\n\tshutdown_facet mds2\n\treboot_facet mds2\n\n\t# prepare for MDS failover\n\tchange_active mds2\n\treboot_facet mds2\n\n\twait_for_facet mds1\n\tstart_mdt 1 || return $?\n\n\twait_for_facet mds2\n\tstart_mdt 2 || return $?\n\n\t#Check FS\n\twait $DFPID\n\tclients_recover_osts ost1\n\techo \"Verify reintegration\"\n\tclients_up || return 1\n}\nrun_test 10 \"Tenth Failure Mode: MDT0/OST/MDT1 `date`\"\n###################################################\n\n############### Seventh Failure Mode ###############\ntest_11() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\t#MDS Portion\n\tfail mds1\n\t#Check FS\n\n\techo \"Test Lustre stability after MDS failover\"\n\tclients_up\n\n\t#CLIENT Portion\n\techo \"Failing 2 CLIENTS\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENT failure\"\n\tclients_up\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTS\"\n\treintegrate_clients || return 1\n\n\tfail mds2\n\n\tclients_up || return 3\n\tsleep 2 # give it a little time for fully recovered before next test\n}\nrun_test 11 \"Eleventh Failure Mode: MDS0/CLIENT/MDS1 `date`\"\n###################################################\n\ntest_12() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\t#MDS Portion\n\tfail mds1,mds2\n\tclients_up\n\n\t#OSS Portion\n\tfail ost1,ost2\n\tclients_up\n\n\t#CLIENT Portion\n\techo \"Failing 2 CLIENTS\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENT failure\"\n\tclients_up\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTS\"\n\treintegrate_clients || return 1\n\n\tclients_up || return 3\n\tsleep 2 # give it a little time for fully recovered before next test\n}\nrun_test 12 \"Twelve Failure Mode: MDS0,MDS1/OST0, OST1/CLIENTS `date`\"\n###################################################\n\ntest_13() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\t#MDS Portion\n\tfail mds1,mds2\n\tclients_up\n\n\t#CLIENT Portion\n\techo \"Failing 2 CLIENTS\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENT failure\"\n\tclients_up\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTS\"\n\treintegrate_clients || return 1\n\n\tclients_up || return 3\n\tsleep 2 # give it a little time for fully recovered before next test\n\n\t#OSS Portion\n\tfail ost1,ost2\n\tclients_up || return 4\n}\nrun_test 13 \"Thirteen Failure Mode: MDS0,MDS1/CLIENTS/OST0,OST1 `date`\"\n###################################################\n\ntest_14() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\techo \"Verify Lustre filesystem is up and running\"\n\t[ -z \"$(mounted_lustre_filesystems)\" ] && error \"Lustre is not running\"\n\n\t#OST Portion\n\tfail ost1,ost2\n\tclients_up\n\n\t#CLIENT Portion\n\techo \"Failing 2 CLIENTS\"\n\tfail_clients 2\n\n\t#Check FS\n\techo \"Test Lustre stability after CLIENT failure\"\n\tclients_up\n\n\t#Reintegration\n\techo \"Reintegrating CLIENTS\"\n\treintegrate_clients || return 1\n\n\tclients_up || return 3\n\tsleep 2 # give it a little time for fully recovered before next test\n\n\t#OSS Portion\n\tfail mds1,mds2\n\tclients_up || return 4\n}\nrun_test 14 \"Fourteen Failure Mode: OST0,OST1/CLIENTS/MDS0,MDS1 `date`\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 752}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# krb5_login.sh - obtain and cache Kerberos ticket-granting ticket\n#\n###############################################################################\n\n#\n# nothing need for root\n#\n[ $UID -eq 0 ] && exit 0\n\n#\n# list Kerberos 5 credentials silently\n# exit status:\n# 0 - klist finds a credentials cache\n# 1 - klist does not find a credentials cache or the tickets are expired\n#\nklist -5 -s && exit 0\n\n# get the user name for uid $UID\nGSS_USER=$(getent passwd $UID | cut -d: -f1)\n\nGSS_PASS=${GSS_PASS:-\"$GSS_USER\"}\n\necho \"***** refresh Kerberos V5 TGT for uid $UID *****\"\nif [ -z \"$GSS_PASS\" ]; then\n    kinit\nelse\n    expect <<EOF\nset timeout 30 \n\nlog_user 1 \n\nset spawnid [spawn /bin/bash]\nsend \"export PS1=\\\"user@host $ \\\" \\r\"\nexpect {\n    timeout {puts \"timeout\" ;exit 1}\n    \"user@host $ \"\n}\n\nsend \"kinit\\r\"\nexpect {\n    timeout {puts \"timeout\" ;exit 1}\n    \"Password for \"\n}\n\nsend \"$GSS_PASS\\r\"\nexpect {\n    timeout {puts \"timeout\" ;exit 1}\n    \"user@host $ \"\n}\n\nexit 0\nEOF\nfi\nret=$?\nexit $ret\n", "num_lines": 58}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to test large size LUN support in Lustre.\n#\n################################################################################\nset -e\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nif [ \"$REFORMAT\" != \"yes\" ]; then\n\tskip_env \"$0 reformats all devices,\\\n\t\tplease set REFORMAT to run this test\"\nfi\n\n# Variable to run mdsrate\nTHREADS_PER_CLIENT=${THREADS_PER_CLIENT:-5}    # thread(s) per client node\nMACHINEFILE=${MACHINEFILE:-$TMP/$TESTSUITE.machines}\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\n# bug number:\nALWAYS_EXCEPT=\"$LARGE_LUN_EXCEPT\"\n\nbuild_test_filter\nLARGE_LUN_RESTORE_MOUNT=false\nif is_mounted $MOUNT || is_mounted $MOUNT2; then\n\tLARGE_LUN_RESTORE_MOUNT=true\nfi\n# Unmount and cleanup the Lustre filesystem\ncleanupall\nload_modules\n\nFULL_MODE=${FULL_MODE:-false}\nRUN_FSCK=${RUN_FSCK:-true}\n# if SLOW=yes, enable the FULL_MODE\n[[ $SLOW = yes ]] && FULL_MODE=true\n#########################################################################\n# Dump the super block information for the filesystem present on device.\nrun_dumpfs() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal cmd\n\n\tlog \"dump the super block information on $facet device $dev\"\n\tlocal fstype=$(facet_fstype $facet)\n\n\tcase $fstype in\n\t\tldiskfs )\n\t\t\tcmd=\"$DUMPE2FS -h $dev\" ;;\n\t\tzfs )\n\t\t\tcmd=\"$ZDB -l $(zpool_name $facet)\" ;;\n\t\t* )\n\t\t\terror \"unknown fstype!\" ;;\n\tesac\n\n\tdo_facet $facet \"$cmd\"\n}\n\n# Report Lustre filesystem disk space usage and inodes usage of each MDT/OST.\nclient_df() {\n\tlocal mnt_pnt=$1\n\tlocal cmd\n\n\tcmd=\"df -h\"\n\techo -e \"\\n# $cmd\"\n\teval $cmd\n\n\tcmd=\"lfs df -h $mnt_pnt\"\n\techo -e \"\\n# $cmd\"\n\teval $cmd\n\n\tcmd=\"lfs df -i $mnt_pnt\"\n\techo -e \"\\n# $cmd\"\n\teval $cmd\n}\n\n# Cleanup the directories and files created by llverfs utility.\ncleanup_dirs() {\n\tlocal target=$1\n\tlocal mnt=${2:-$MOUNT}\n\tlocal cmd=\"rm -rf $mnt/{llverfs,dir}*\"\n\tdo_facet $target \"$cmd\"\n}\n\n# Run mdsrate.\nrun_mdsrate() {\n\tgenerate_machine_file $NODES_TO_USE $MACHINEFILE ||\n\t\terror \"can not generate machinefile\"\n\n\t# set the default stripe count for files in this test to one\n\tlocal testdir=$MOUNT/mdsrate\n\tmkdir -p $testdir\n\tchmod 0777 $testdir\n\t$LFS setstripe $testdir -i 0 -c 1\n\tget_stripe $testdir\n\n\tlocal num_dirs=$THREADS_PER_CLIENT\n\t[[ $num_dirs -eq 0 ]] && num_dirs=1\n\tlocal free_inodes=$(lfs df -i $MOUNT | grep \"OST:0\" | awk '{print $4}')\n\tlocal num_files\n\tnum_files=$((free_inodes / num_dirs))\n\n\tlocal command=\"$MDSRATE $MDSRATE_DEBUG --create --verbose \\\n\t\t--ndirs $num_dirs --dirfmt '$testdir/dir%d' \\\n\t\t--nfiles $num_files --filefmt 'file%%d'\"\n\n\techo \"# $command\"\n\tmpi_run -machinefile $MACHINEFILE \\\n\t\t-np $((NUM_CLIENTS * THREADS_PER_CLIENT)) $command\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror \"mdsrate create failed\"\n\tfi\n}\n\ncheck_fsfacet() {\n\tlocal facet=$1\n\tlocal fstype=$(facet_fstype $facet)\n\n\tcase $fstype in\n\t    ldiskfs)\n\t\trun_e2fsck $(facet_active_host $facet) $(facet_device $facet) \\\n\t\t    \"-y\" || error \"run e2fsck error\"\n\t\t;;\n\t    zfs)\n\t\t# Could call fsck.zfs, but currently it does nothing,\n\t\t# Could also call zpool scrub, but that could take a LONG time\n\t\t# do_facet $facet \"fsck.zfs $(facet_device $facet)\"\n\t\t;;\n\tesac\n}\n\n# Run e2fsck on MDS and OST\ndo_fsck() {\n\t$RUN_FSCK || return\n\n\tcheck_fsfacet $SINGLEMDS\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tcheck_fsfacet ost${num}\n\tdone\n}\n################################## Main Flow ###################################\ntrap cleanupall EXIT\n\ntest_1 () {\n\t[ \"$mds1_FSTYPE\" != ldiskfs ] && skip_env \"ldiskfs only test\"\n\n\tlocal dev\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tdev=$(ostdevname $num)\n\t\tlog \"run llverdev on the OST $dev\"\n\t\tdo_rpc_nodes $(facet_host ost${num}) run_llverdev $dev -vpf ||\n\t\t\terror \"llverdev on $dev failed!\"\n\tdone\n\t# restore format overwritten by llverdev\n\tformatall\n}\nrun_test 1 \"run llverdev on raw LUN\"\n\ntest_2 () {\n\tlocal dev\n\tlocal ostmnt\n\tlocal fstype\n\tlocal zostsize_restore=${OSTSIZE}\n\tlocal zmin=$((30 << 30)) # 30GiB in bytes\n\tlocal skipped=1\n\n\tstack_trap \"export OSTSIZE=$zostsize_restore\" EXIT\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tdev=$(ostdevname $num)\n\t\tostmnt=$(facet_mntpt ost${num})\n\t\tfstype=$(facet_fstype ost${num})\n\n\t\tif [[ $fstype == \"zfs\" ]] && [[ ${OSTSIZE} -lt ${zmin} ]]; then\n\t\t\tlocal real_dev=$(ostvdevname $num)\n\t\t\tlocal num_sectors=$(get_num_sectors $facet $real_dev)\n\t\t\tlocal phy_bytes=$((num_sectors * 512))\n\n\t\t\tif [ ${phy_bytes} -lt ${zmin} ] ; then\n\t\t\t\tlog \"ost${num}: OSTSIZE ${OSTSIZE} less than 30GiB\"\n\t\t\t\tlog \"ost${num}: Block device ${phy_bytes} too small\"\n\t\t\t\tlog \" .. skipping this ost\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t# Backing block device is big enough\n\t\t\tskipped=0\n\t\t\tlog \"ost${num}: OSTSIZE ${OSTSIZE} too small, increasing to 30GiB [temporarily]\"\n\t\t\tformat_ost ${num}\n\t\t\t# NOTE: OSTSIZE is in KB\n\t\t\texport OSTSIZE=$((zmin >> 10))\n\t\tfi\n\n\t\t# Mount the OST as an ldiskfs or zfs filesystem.\n\t\tlog \"mount the OST $dev as a $fstype filesystem\"\n\t\tadd ost${num} $(mkfs_opts ost${num} $dev) $FSTYPE_OPT \\\n\t\t\t--reformat $(ostdevname $num) \\\n\t\t\t$(ostvdevname $num) > /dev/null ||\n\t\t\terror \"format ost${num} error\"\n\t\tif [ $fstype == zfs ]; then\n\t\t\timport_zpool ost${num}\n\t\t\tdo_facet ost${num} \\\n\t\t\t    \"$ZFS set canmount=on $dev; \" \\\n\t\t\t    \"$ZFS set mountpoint=legacy $dev; \" \\\n\t\t\t    \"$ZFS list $dev\"\n\t\tfi\n\t\trun_dumpfs ost${num} $dev\n\t\tdo_facet ost${num} mount -t $fstype $dev \\\n\t\t\t$ostmnt \"$OST_MOUNT_OPTS\"\n\n\t\t# Run llverfs on the mounted filesystem in partial mode\n\t\t# to ensure that the kernel can perform filesystem operations\n\t\t# on the complete device without any errors.\n\t\tlog \"run llverfs in partial mode on the OST $fstype $ostmnt\"\n\t\tdo_rpc_nodes $(facet_host ost${num}) run_llverfs $ostmnt -vpl \\\n\t\t\t\"no\" || error \"run_llverfs error on $fstype\"\n\n\t\t# Unmount the OST.\n\t\tlog \"unmount the OST $dev\"\n\t\tstop ost${num}\n\n\t\t# After llverfs is run on the filesystem in partial\n\t\t# mode, a full e2fsck should be run to catch any errors early.\n\t\t$RUN_FSCK && check_fsfacet ost${num}\n\n\t\tif $FULL_MODE; then\n\t\t\tlog \"full mode, mount the OST $dev as a $fstype again\"\n\t\t\tif [ $fstype == zfs ]; then\n\t\t\t\timport_zpool ost${num}\n\t\t\tfi\n\t\t\tdo_facet ost${num} mount -t $(facet_fstype ost${num}) \\\n\t\t\t\t$dev $ostmnt \"$OST_MOUNT_OPTS\"\n\t\t\tcleanup_dirs ost${num} $ostmnt\n\t\t\tdo_facet ost${num} \"sync\"\n\n\t\t\trun_dumpfs ost${num} $dev\n\n\t\t\t# Run llverfs on the mounted ldiskfs filesystem in full\n\t\t\t# mode to ensure that the kernel can perform filesystem\n\t\t\t# operations on the complete device without any errors.\n\t\t\tlog \"run llverfs in full mode on OST $fstype $ostmnt\"\n\t\t\tdo_rpc_nodes $(facet_host ost${num}) run_llverfs \\\n\t\t\t\t$ostmnt -vl \"no\" ||\n\t\t\t\terror \"run_llverfs error on $fstype\"\n\n\t\t\t# Unmount the OST.\n\t\t\tlog \"unmount the OST $dev\"\n\t\t\tstop ost${num}\n\n\t\t\t# After llverfs is run on the ldiskfs filesystem in\n\t\t\t# full mode, a full e2fsck should be run to catch any\n\t\t\t#  errors early.\n\t\t\t$RUN_FSCK && check_fsfacet ost${num}\n\t\tfi\n\t\texport OSTSIZE=${zostsize_restore}\n\tdone\n\t[[ $skipped -ne 0 ]] && skip_env \"No OST with enough space is available.\"\n\t# there is no reason to continue using ost devices\n\t# filled by llverfs as ldiskfs\n\tformatall\n}\nrun_test 2 \"run llverfs on OST ldiskfs/zfs filesystem\"\n\ntest_3 () {\n\t[ -z \"$CLIENTS\" ] && skip_env \"CLIENTS not defined, skipping\"\n\t[ -z \"$MPIRUN\" ] && skip_env \"MIPRUN not defined, skipping\"\n\t[ -z \"$MDSRATE\" ] && skip_env \"MDSRATE not defined, skipping\"\n\t[ ! -x $MDSRATE ] && skip_env \"$MDSRATE not built, skipping\"\n\t# Setup the Lustre filesystem.\n\tlog \"setup the lustre filesystem\"\n\tREFORMAT=\"yes\" check_and_setup_lustre\n\n\tlog \"run mdsrate to use up the free inodes.\"\n\t# Run the mdsrate test suite.\n\trun_mdsrate\n\tclient_df $MOUNT\n\n\tsync; sleep 5; sync\n\tstopall\n\tdo_fsck\n}\nrun_test 3 \"use up free inodes on the OST with mdsrate\"\n\ntest_4 () {\n\t# Setup the Lustre filesystem.\n\tlog \"setup the lustre filesystem\"\n\tREFORMAT=\"yes\" check_and_setup_lustre\n\tlocal dev\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tdev=$(ostdevname $num)\n\t\trun_dumpfs ost${num} $dev\n\tdone\n\n\t# Run llverfs on the mounted Lustre filesystem both in partial and\n\t# full mode to to fill the filesystem and verify the file contents.\n\tlog \"run llverfs in partial mode on the Lustre filesystem $MOUNT\"\n\trun_llverfs $MOUNT -vp \"no\" || error \"run_llverfs error on lustre\"\n\tclient_df $MOUNT\n\n\tsync; sleep 5; sync\n\tstopall\n\tdo_fsck\n\n\tif $FULL_MODE; then\n\t\t# Setup the Lustre filesystem again.\n\t\tlog \"setup the lustre filesystem again\"\n\t\tsetupall\n\n\t\tcleanup_dirs client $MOUNT\n\t\tsync\n\t\tclient_df $MOUNT\n\n\t\tfor num in $(seq $OSTCOUNT); do\n\t\t\tdev=$(ostdevname $num)\n\t\t\trun_dumpfs ost${num} $dev\n\t\tdone\n\n\t\tlog \"run llverfs in full mode on the Lustre filesystem $MOUNT\"\n\t\trun_llverfs $MOUNT -vl \"no\" ||\n\t\t\terror \"run_llverfs error on lustre\"\n\t\tclient_df $MOUNT\n\n\t\tsync; sleep 5; sync\n\t\tstopall\n\t\tdo_fsck\n\tfi\n}\nrun_test 4 \"run llverfs on lustre filesystem\"\n\ncomplete $SECONDS\n$LARGE_LUN_RESTORE_MOUNT && setupall\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 341}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nPTLDEBUG=${PTLDEBUG:--1}\nSETUP=${SETUP:-\"\"}\nCLEANUP=${CLEANUP:-\"\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$LARGE_SCALE_EXCEPT \"\n\nbuild_test_filter\n\nremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n[ -z \"$CLIENTS\" ] && skip_env \"$TESTSUITE: Need two or more clients\"\n[ $CLIENTCOUNT -lt 2 ] &&\n\tskip_env \"$TESTSUITE: Need 2+ clients, have only $CLIENTCOUNT\"\n\nMOUNT_2=\"\"\n\ncheck_and_setup_lustre\nrm -rf $DIR/[df][0-9]*\n\nget_mpiuser_id $MPI_USER\nMPI_RUNAS=${MPI_RUNAS:-\"runas -u $MPI_USER_UID -g $MPI_USER_GID\"}\n$GSS_KRB5 && refresh_krb5_tgt $MPI_USER_UID $MPI_USER_GID $MPI_RUNAS\n\n[ \"$DAEMONFILE\" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE\n\ntest_3a() {\n\tassert_env CLIENTS MDSRATE MPIRUN\n\n\tlocal -a nodes=(${CLIENTS//,/ })\n\t# INCREMENT is a number of clients a half of clients by default\n\tlocal increment=${INCREMENT:-$(( CLIENTCOUNT / 2 ))}\n\tlocal num=$increment\n\tlocal LOG=$TMP/${TESTSUITE}_$tfile\n\tlocal var=${SINGLEMDS}_svc\n\tlocal procfile=\"*.${!var}.recovery_status\"\n\tlocal iters=${ITERS:-3}\n\tlocal nfiles=${NFILES:-50000}\n\tlocal nthreads=${THREADS_PER_CLIENT:-3}\n\tlocal IFree=$(inodes_available)\n\tlocal pid\n\tlocal list\n\tlocal -a res\n\tlocal dir=$DIR/d0.$TESTNAME\n\n\t[ $IFree -gt $nfiles ] || nfiles=$IFree\n\n\tmkdir -p $dir\n\tchmod 0777 $dir\n\n\twhile [ $num -le $CLIENTCOUNT ]; do\n\t\tlist=$(comma_list ${nodes[@]:0:$num})\n\n\t\tgenerate_machine_file $list $MACHINEFILE ||\n\t\t\terror \"can not generate machinefile\"\n\n\t\tfor i in $(seq $iters); do\n\t\t\tmdsrate_cleanup $num $MACHINEFILE $nfiles $dir 'f%%d' \\\n\t\t\t\t--ignore\n\n\t\t\tCOMMAND=\"${MDSRATE} --create --nfiles $nfiles --dir\n\t\t\t\t $dir --filefmt 'f%%d'\"\n\t\t\tmpi_run ${MACHINEFILE_OPTION} $MACHINEFILE \\\n\t\t\t\t-np $((num * nthreads)) ${COMMAND} | tee ${LOG}&\n\n\t\t\tpid=$!\n\t\t\techo \"pid=$pid\"\n\n\t\t\t# 2 threads 100000 creates 117 secs\n\t\t\tsleep 20\n\n\t\t\tlog \"$i : Starting failover on $SINGLEMDS\"\n\t\t\tfacet_failover $SINGLEMDS\n\t\t\tif ! wait_recovery_complete $SINGLEMDS \\\n\t\t\t     $((TIMEOUT * 10)); then\n\t\t\t\techo \"$SINGLEMDS recovery is not completed!\"\n\t\t\t\tkill -9 $pid\n\t\t\t\texit 7\n\t\t\tfi\n\n\t\t\tduration=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\t\t$procfile | grep recovery_duration)\n\n\t\t\tres=( \"${res[@]}\" \"$num\" )\n\t\t\tres=( \"${res[@]}\" \"$duration\" )\n\t\t\techo \"RECOVERY TIME: NFILES=$nfiles number of clients: $num $duration\"\n\t\t\twait $pid\n\t\tdone\n\t\tnum=$((num + increment))\n\tdone\n\n\tmdsrate_cleanup $num $MACHINEFILE $nfiles $dir 'f%%d' --ignore\n\n\ti=0\n\twhile [ $i -lt ${#res[@]} ]; do\n\t\techo \"RECOVERY TIME: NFILES=$nfiles number of clients: ${res[i]}  ${res[i+1]}\"\n\t\ti=$((i+2))\n\tdone\n}\n\nrun_test 3a \"recovery time, $CLIENTCOUNT clients\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 114}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\nALWAYS_EXCEPT=\"$LFSCK_PERFORMANCE_EXCEPT\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nrequire_dsh_mds || exit 0\nrequire_dsh_ost || exit 0\n\n[ \"$SLOW\" = \"no\" ] &&\n\tskip \"skip lfsck performance test under non-SLOW mode\"\n\nNTHREADS=${NTHREADS:-0}\nUNIT=${UNIT:-8192}\nMINCOUNT=${MINCOUNT:-4096}\nMAXCOUNT=${MAXCOUNT:-8192}\nMINCOUNT_REPAIR=${MINCOUNT_REPAIR:-4096}\nMAXCOUNT_REPAIR=${MAXCOUNT_REPAIR:-8192}\nBASE_COUNT=${BASE_COUNT:-8192}\nFACTOR=${FACTOR:-2}\nINCFACTOR=${INCFACTOR:-25} #percent\nMINSUBDIR=${MINSUBDIR:-1}\nMAXSUBDIR=${MAXSUBDIR:-2}\nTOTSUBDIR=${TOTSUBDIR:-2}\nWTIME=${WTIME:-86400}\n\nRCMD=\"do_facet ${SINGLEMDS}\"\nRLCTL=\"${RCMD} ${LCTL}\"\nMDT_DEV=\"${FSNAME}-MDT0000\"\nMDT_DEVNAME=$(mdsdevname ${SINGLEMDS//mds/})\nSTART_NAMESPACE=\"${RLCTL} lfsck_start -M ${MDT_DEV} -t namespace\"\nSTOP_LFSCK=\"${RLCTL} lfsck_stop -M ${MDT_DEV} -A\"\nSHOW_NAMESPACE=\"${RLCTL} get_param -n mdd.${MDT_DEV}.lfsck_namespace\"\nMNTOPTS_NOSCRUB=\"-o user_xattr,noscrub\"\nremote_mds && ECHOCMD=${RCMD} || ECHOCMD=\"eval\"\n\nif [ ${NTHREADS} -eq 0 ]; then\n\tCPUCORE=$(${RCMD} cat /proc/cpuinfo | grep \"processor.*:\" | wc -l)\n\tNTHREADS=$((CPUCORE * 2))\nfi\n\nlfsck_attach() {\n\t${RCMD} \"modprobe obdecho\"\n\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tattach echo_client lfsck-MDT0000 lfsck-MDT0000_UUID\n\t\tsetup ${MDT_DEV} mdd\n\tEOF\"\n}\n\nlfsck_detach() {\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tdevice lfsck-MDT0000\n\t\tcleanup\n\t\tdetach\n\tEOF\"\n}\n\nlfsck_create() {\n\tlocal echodev=$(${RLCTL} dl | grep echo_client|awk '{print $1}')\n\tlocal j\n\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tcfg_device ${echodev}\n\t\ttest_mkdir ${tdir}\n\tEOF\"\n\n\tfor ((j = 1; j < ${threads}; j++)); do\n\t\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\t\tcfg_device ${echodev}\n\t\t\ttest_mkdir ${tdir}${j}\n\t\tEOF\"\n\tdone\n\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tcfg_device ${echodev}\n\t\t--threads ${threads} 0 ${echodev} test_create \\\n\t\t-d ${tdir} -D ${threads} -b ${lbase} -c 0 -n ${usize}\n\tEOF\"\n}\n\nlfsck_cleanup() {\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) unload_modules\n\tREFORMAT=\"yes\" cleanup_and_setup_lustre\n}\n\nlfsck_create_nfiles() {\n\tlocal total=$1\n\tlocal lbase=$2\n\tlocal threads=$3\n\tlocal linkea=$4\n\tlocal ldir=\"/test-${lbase}\"\n\tlocal cycle=0\n\tlocal count=${UNIT}\n\n\twhile true; do\n\t\t[ ${count} -eq 0 -o  ${count} -gt ${total} ] && count=${total}\n\t\tlocal usize=$((count / NTHREADS))\n\t\t[ ${usize} -eq 0 ] && break\n\t\tlocal tdir=${ldir}-${cycle}-\n\n\t\techo \"[cycle: ${cycle}] [threads: ${threads}]\"\\\n\t\t     \"[files: ${count}] [basedir: ${tdir}]\"\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB ||\n\t\t\terror \"Fail to start MDS!\"\n\t\t#define OBD_FAIL_FID_IGIF\t0x1504\n\t\t[ ! -z $linkea ] && ${RLCTL} set_param fail_loc=0x1504\n\n\t\tlfsck_attach\n\t\tlfsck_create\n\t\tlfsck_detach\n\n\t\t[ ! -z $linkea ] && ${RLCTL} set_param fail_loc=0x0\n\t\tstop ${SINGLEMDS} || error \"Fail to stop MDS!\"\n\n\t\ttotal=$((total - usize * NTHREADS))\n\t\t[ ${total} -eq 0 ] && break\n\t\tlbase=$((lbase + usize))\n\t\tcycle=$((cycle + 1))\n\tdone\n}\n\nbuild_test_filter\n\nformat_start_mgs () {\n\tdo_rpc_nodes $(facet_active_host mgs) load_modules_local\n\tformat_mgs\n\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS\n}\n\ntest_0() {\n\tlocal BCOUNT=0\n\tlocal i\n\n\tstopall\n\tcombined_mgs_mds || format_start_mgs\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) load_modules_local\n\tformat_mdt $(facet_number $SINGLEMDS)\n\n\tfor ((i = $MINCOUNT; i <= $MAXCOUNT; i = $((i * FACTOR)))); do\n\t\tlocal nfiles=$((i - BCOUNT))\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tlfsck_create_nfiles ${nfiles} ${BCOUNT} ${NTHREADS} ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\n\t\tBCOUNT=${i}\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\t\terror \"Fail to start MDS!\"\n\n\t\techo \"start lfsck_namespace for ${i} files set at: $(date)\"\n\t\t$START_NAMESPACE || error \"Fail to start lfsck_namespace!\"\n\n\t\twhile true; do\n\t\t\tlocal STATUS=$($SHOW_NAMESPACE |\n\t\t\t\t\tawk '/^status/ { print $2 }')\n\t\t\t[ \"$STATUS\" == \"completed\" ] && break\n\t\t\tsleep 3 # check status every 3 seconds\n\t\tdone\n\n\t\techo \"end lfsck_namespace for ${i} files set at: $(date)\"\n\t\tSPEED=$($SHOW_NAMESPACE |\n\t\t\tawk '/^average_speed_phase1/ { print $2 }')\n\t\techo \"lfsck_namespace speed is ${SPEED}/sec\"\n\t\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\tdone\n\tcombined_mgs_mds || stop mgs\n}\nrun_test 0 \"lfsck namespace performance (routine case) without load\"\n\ntest_1() {\n\t[ \"$mds1_FSTYPE\" != ldiskfs ] &&\n\t\tskip_env \"not implemented for ZFS\"\n\n\tlocal BCOUNT=0\n\tlocal i\n\n\tstopall\n\tcombined_mgs_mds || format_start_mgs\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) load_modules_local\n\tformat_mdt $(facet_number $SINGLEMDS)\n\n\tfor ((i = $MINCOUNT_REPAIR; i <= $MAXCOUNT_REPAIR;\n\t      i = $((i * FACTOR)))); do\n\t\tlocal nfiles=$((i - BCOUNT))\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tlfsck_create_nfiles ${nfiles} ${BCOUNT} ${NTHREADS} ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\n\t\tBCOUNT=${i}\n\t\tlocal stime=$(date +%s)\n\t\techo \"backup/restore ${i} files start at: $(date)\"\n\t\tmds_backup_restore $SINGLEMDS || error \"Fail to backup/restore!\"\n\t\techo \"backup/restore ${i} files end at: $(date)\"\n\t\tlocal etime=$(date +%s)\n\t\tlocal delta=$((etime - stime))\n\t\t[ $delta -gt 0 ] || delta=1\n\t\techo \"backup/restore ${i} files used ${delta} seconds\"\n\t\techo \"backup/restore speed is $((i / delta))/sec\"\n\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\t\terror \"Fail to start MDS!\"\n\n\t\techo \"start lfsck_namespace for ${i} files set at: $(date)\"\n\t\t$START_NAMESPACE || error \"Fail to start lfsck_namespace!\"\n\n\t\twhile true; do\n\t\t\tlocal STATUS=$($SHOW_NAMESPACE |\n\t\t\t\t\tawk '/^status/ { print $2 }')\n\t\t\t[ \"$STATUS\" == \"completed\" ] && break\n\t\t\tsleep 3 # check status every 3 seconds\n\t\tdone\n\n\t\techo \"end lfsck_namespace for ${i} files set at: $(date)\"\n\t\tlocal SPEED=$($SHOW_NAMESPACE |\n\t\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\t\techo \"lfsck_namespace speed is ${SPEED}/sec\"\n\t\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\tdone\n\tcombined_mgs_mds || stop mgs\n}\nrun_test 1 \"lfsck namespace performance (backup/restore) without load\"\n\ntest_2() {\n\tlocal i\n\n\tfor ((i = $MINCOUNT_REPAIR; i <= $MAXCOUNT_REPAIR;\n\t      i = $((i * FACTOR)))); do\n\t\tstopall\n\t\tcombined_mgs_mds || format_start_mgs\n\t\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) load_modules_local\n\t\tformat_mdt $(facet_number $SINGLEMDS)\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tlfsck_create_nfiles ${i} 0 ${NTHREADS} 1 ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\t\terror \"Fail to start MDS!\"\n\n\t\techo \"start lfsck_namespace for ${i} files set at: $(date)\"\n\t\t$START_NAMESPACE || error \"Fail to start lfsck_namespace!\"\n\n\t\twhile true; do\n\t\t\tlocal STATUS=$($SHOW_NAMESPACE |\n\t\t\t\t\tawk '/^status/ { print $2 }')\n\t\t\t[ \"$STATUS\" == \"completed\" ] && break\n\t\t\tsleep 3 # check status every 3 seconds\n\t\tdone\n\n\t\techo \"end lfsck_namespace for ${i} files set at: $(date)\"\n\t\tlocal SPEED=$($SHOW_NAMESPACE |\n\t\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\t\techo \"lfsck_namespace speed is ${SPEED}/sec\"\n\t\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\tdone\n\tcombined_mgs_mds || stop mgs\n}\nrun_test 2 \"lfsck namespace performance (upgrade from 1.8) without load\"\n\ntest_3() {\n\t[ $INCFACTOR -gt 25 ] && INCFACTOR=25\n\n\tlocal inc_count=$((BASE_COUNT * INCFACTOR / 100))\n\tlocal BCOUNT=0\n\tlocal i\n\n\tstopall\n\tcombined_mgs_mds || format_start_mgs\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) load_modules_local\n\tformat_mdt $(facet_number $SINGLEMDS)\n\n\tfor ((i = $inc_count; i <= $BASE_COUNT; i = $((i + inc_count)))); do\n\t\tlocal nfiles=$((i - BCOUNT))\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tlfsck_create_nfiles ${nfiles} ${BCOUNT} ${NTHREADS} ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\t\tBCOUNT=${i}\n\tdone\n\n\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\terror \"Fail to start MDS!\"\n\n\techo \"start lfsck_namespace for ${BASE_COUNT} files set at: $(date)\"\n\t$START_NAMESPACE || error \"Fail to start lfsck_namespace!\"\n\n\twhile true; do\n\t\tlocal STATUS=$($SHOW_NAMESPACE |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$STATUS\" == \"completed\" ] && break\n\t\tsleep 3 # check status every 3 seconds\n\tdone\n\n\techo \"end lfsck_namespace for ${BASE_COUNT} files set at: $(date)\"\n\tlocal FULL_SPEED=$($SHOW_NAMESPACE |\n\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\techo \"lfsck_namespace full_speed is ${FULL_SPEED}/sec\"\n\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\tlocal inc_speed=$((FULL_SPEED * INCFACTOR / 100))\n\tlocal j\n\n\tfor ((j = $inc_speed; j < $FULL_SPEED; j = $((j + inc_speed)))); do\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\t\terror \"Fail to start MDS!\"\n\n\t\t$STOP_LFSCK > /dev/null 2>&1\n\t\techo \"start lfsck_namespace with speed ${j} at: $(date)\"\n\t\t$START_NAMESPACE --reset -s ${j} ||\n\t\t\terror \"Fail to start lfsck_namespace with speed ${j}!\"\n\t\t# lfsck_namespace will be paused when MDS stop,\n\t\t# and will be restarted automatically when mount up again.\n\t\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\n\t\tlocal nfiles=$(((i - BCOUNT) / 2))\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tlfsck_create_nfiles ${nfiles} ${BCOUNT} ${NTHREADS} ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\t\tBCOUNT=${i}\n\t\ti=$((i + inc_count))\n\tdone\n\n\tstart ${SINGLEMDS} $MDT_DEVNAME $MNTOPTS_NOSCRUB > /dev/null ||\n\t\terror \"Fail to start MDS!\"\n\n\t$STOP_LFSCK /dev/null 2>&1\n\techo \"start lfsck_namespace with full speed at: $(date)\"\n\t$START_NAMESPACE --reset -s 0 ||\n\t\terror \"Fail to start lfsck_namespace with full speed!\"\n\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\n\tlocal nfiles=$(((i - BCOUNT) / 2))\n\n\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\tlfsck_create_nfiles ${nfiles} ${BCOUNT} ${NTHREADS} ||\n\t\terror \"Fail to create files!\"\n\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\tcombined_mgs_mds || stop mgs\n}\nrun_test 3 \"lfsck namespace impact on create performance\"\n\nshow_layout() {\n\tlocal idx=$1\n\n\tdo_facet mds${idx} \\\n\t\t\"$LCTL get_param -n mdd.$(facet_svc mds${idx}).lfsck_layout\"\n}\n\nlayout_test_one() {\n\techo \"***** Start layout LFSCK on all devices at: $(date) *****\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t layout -A -r || return 21\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $WTIME || {\n\t\tshow_layout 1\n\t\treturn 22\n\t}\n\techo \"***** End layout LFSCK on all devices at: $(date) *****\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tshow_layout ${n}\n\n\t\tlocal SPEED=$(show_layout ${n} |\n\t\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\t\techo\n\t\techo \"lfsck_layout speed on MDS_${n} is $SPEED objs/sec\"\n\t\techo\n\tdone\n}\n\nlayout_gen_one() {\n\tlocal idx1=$1\n\tlocal idx2=$2\n\tlocal mntpt=\"/mnt/lustre_lfsck_${idx1}_${idx2}\"\n\tlocal basedir=\"$mntpt/$tdir/$idx1/$idx2\"\n\n\tmkdir -p $mntpt || {\n\t\terror_noexit \"(11) Fail to mkdir $mntpt\"\n\t\treturn 11\n\t}\n\n\tmount_client $mntpt || {\n\t\terror_noexit \"(12) Fail to mount $mntpt\"\n\t\treturn 12\n\t}\n\n\tmkdir $basedir || {\n\t\tumount_client $mntpt\n\t\terror_noexit \"(13) Fail to mkdir $basedir\"\n\t\treturn 13\n\t}\n\n\techo \"&&&&& Start create $UNIT files under $basedir at: $(date) &&&&&\"\n\tcreatemany -o ${basedir}/f $UNIT || {\n\t\tumount_client $mntpt\n\t\terror_noexit \"(14) Fail to gen $UNIT files under $basedir\"\n\t\treturn 14\n\t}\n\techo \"&&&&& End create $UNIT files under $basedir at: $(date) &&&&&\"\n\n\tumount_client $mntpt\n}\n\nlayout_gen_set() {\n\tlocal cnt=$1\n\n\techo \"##### Start generate test set for subdirs=$cnt at: $(date) #####\"\n\tfor ((k = 0; k < $MDSCOUNT; k++)); do\n\t\t$LFS mkdir -i ${k} $LFSCKDIR/${k} || return 10\n\n\t\tfor ((l = 1; l <= $cnt; l++)); do\n\t\t\tlayout_gen_one ${k} ${l} &\n\t\tdone\n\tdone\n\n\twait\n\techo \"##### End generate test set for subdirs=$cnt at: $(date) #####\"\n}\n\nt4_test() {\n\tlocal saved_mdscount=$MDSCOUNT\n\tlocal saved_ostcount=$OSTCOUNT\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(1) Fail to stopall\"\n\n\tLFSCKDIR=\"$DIR/$tdir\"\n\tMDSCOUNT=1\n\tfor ((i = 1; i <= $saved_ostcount; i = $((i * 2)))); do\n\t\tOSTCOUNT=${i}\n\n\t\techo \"+++++ Start cycle ostcount=$OSTCOUNT at: $(date) +++++\"\n\t\techo\n\n\t\tfor ((j = $MINSUBDIR; j <= $MAXSUBDIR; j = $((j * FACTOR)))); do\n\t\t\techo \"formatall\"\n\t\t\tformatall > /dev/null ||\n\t\t\t\terror \"(2) Fail to formatall, subdirs=${j}\"\n\n\t\t\techo \"setupall\"\n\t\t\tsetupall > /dev/null ||\n\t\t\t\terror \"(3) Fail to setupall, subdirs=${j}\"\n\n\t\t\tmkdir $LFSCKDIR ||\n\t\t\t\terror \"(4) mkdir $LFSCKDIR, subdirs=${j}\"\n\n\t\t\t$LFS setstripe -c ${OSTCOUNT} -i 0 $LFSCKDIR ||\n\t\t\t\terror \"(5) setstripe on $LFSCKDIR, subdirs=${j}\"\n\n\t\t\tlocal RC=0\n\t\t\tlayout_gen_set ${j} || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(6) generate set $RC, subdirs=${j}\"\n\n\t\t\tRC=0\n\t\t\tlayout_test_one || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(7) LFSCK failed with $RC, subdirs=${j}\"\n\t\tdone\n\n\t\techo \"stopall\"\n\t\tstopall > /dev/null || error \"(8) Fail to stopall, subdirs=${j}\"\n\n\t\techo\n\t\techo \"----- Stop cycle ostcount=$OSTCOUNT at: $(date) -----\"\n\tdone\n\n\tMDSCOUNT=$saved_mdscount\n\tOSTCOUNT=$saved_ostcount\n}\n\ntest_4a() {\n\tt4_test\n}\nrun_test 4a \"Single MDS lfsck layout performance (routine case) without load\"\n\ntest_4b() {\n\techo \"Inject failure stub to simulate dangling reference\"\n\t#define OBD_FAIL_LFSCK_DANGLING 0x1610\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1610\n\n\tt4_test\n}\nrun_test 4b \"Single MDS lfsck layout performance (repairing case) without load\"\n\nt5_test() {\n\tlocal saved_mdscount=$MDSCOUNT\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(1) Fail to stopall\"\n\n\tLFSCKDIR=\"$DIR/$tdir\"\n\tfor ((i = 1; i <= $saved_mdscount; i++)); do\n\t\tMDSCOUNT=${i}\n\n\t\techo \"+++++ Start cycle mdscount=$MDSCOUNT at: $(date) +++++\"\n\t\techo\n\n\t\tfor ((j = $MINSUBDIR; j <= $MAXSUBDIR; j = $((j * FACTOR)))); do\n\t\t\techo \"formatall\"\n\t\t\tformatall > /dev/null ||\n\t\t\t\terror \"(2) Fail to formatall, subdirs=${j}\"\n\n\t\t\techo \"setupall\"\n\t\t\tsetupall > /dev/null ||\n\t\t\t\terror \"(3) Fail to setupall, subdirs=${j}\"\n\n\t\t\tmkdir $LFSCKDIR ||\n\t\t\t\terror \"(4) mkdir $LFSCKDIR, subdirs=${j}\"\n\n\t\t\t$LFS setstripe -c ${OSTCOUNT} -i 0 $LFSCKDIR ||\n\t\t\t\terror \"(5) setstripe on $LFSCKDIR, subdirs=${j}\"\n\n\t\t\tlocal RC=0\n\t\t\tlayout_gen_set ${j} || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(6) generate set $RC, subdirs=${j}\"\n\n\t\t\tRC=0\n\t\t\tlayout_test_one || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(7) LFSCK failed with $RC, subdirs=${j}\"\n\t\tdone\n\n\t\techo \"stopall\"\n\t\tstopall > /dev/null || error \"(8) Fail to stopall\"\n\n\t\techo\n\t\techo \"----- Stop cycle mdscount=$MDSCOUNT at: $(date) -----\"\n\tdone\n\n\tMDSCOUNT=$saved_mdscount\n}\n\ntest_5a() {\n\tt5_test\n}\nrun_test 5a \"lfsck layout performance (routine case) without load for DNE\"\n\ntest_5b() {\n\techo \"Inject failure stub to simulate dangling reference\"\n\t#define OBD_FAIL_LFSCK_DANGLING 0x1610\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1610\n\n\tt5_test\n}\nrun_test 5b \"lfsck layout performance (repairing case) without load for DNE\"\n\nlfsck_fast_create() {\n\tlocal total=$1\n\tlocal lbase=$2\n\tlocal threads=$3\n\tlocal ldir=\"/test-${lbase}\"\n\tlocal cycle=0\n\tlocal count=$UNIT\n\n\twhile true; do\n\t\t[ $count -eq 0 -o  $count -gt ${total} ] && count=$total\n\t\tlocal usize=$((count / NTHREADS))\n\t\t[ ${usize} -eq 0 ] && break\n\t\tlocal tdir=${ldir}-${cycle}-\n\n\t\techo \"[cycle: $cycle] [threads: $threads]\"\\\n\t\t     \"[files: $count] [basedir: $tdir]\"\n\n\t\tlfsck_create\n\n\t\ttotal=$((total - usize * NTHREADS))\n\t\t[ $total -eq 0 ] && break\n\t\tlbase=$((lbase + usize))\n\t\tcycle=$((cycle + 1))\n\tdone\n}\n\nlfsck_detach_error() {\n\tlfsck_detach\n\terror \"$@\"\n}\n\ntest_6() {\n\t[ $INCFACTOR -gt 25 ] && INCFACTOR=25\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(1) Fail to stopall\"\n\n\tlocal saved_mdscount=$MDSCOUNT\n\n\tLFSCKDIR=\"$DIR/$tdir\"\n\tMDSCOUNT=1\n\techo \"formatall\"\n\tformatall > /dev/null || error \"(2) Fail to formatall\"\n\n\techo \"setupall\"\n\tsetupall > /dev/null || error \"(3) Fail to setupall\"\n\n\tmkdir $LFSCKDIR || error \"(4) Fail to mkdir $LFSCKDIR\"\n\n\t$LFS setstripe -c ${OSTCOUNT} -i 0 $LFSCKDIR ||\n\t\terror \"(5) Fail to setstripe on $LFSCKDIR\"\n\n\tlocal RC=0\n\tlayout_gen_set $TOTSUBDIR || RC=$?\n\t[ $RC -eq 0 ] ||\n\t\terror \"(6) Fail to generate set $RC, subdirs=$TOTSUBDIR\"\n\n\techo\n\techo \"***** Start layout LFSCK on single MDS at: $(date) *****\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t layout -r ||\n\t\terror \"(7) Fail to start layout LFSCK\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $WTIME || {\n\t\tshow_layout 1\n\t\terror \"(8) layout LFSCK cannot finished in time\"\n\t}\n\techo \"***** End layout LFSCK on single MDS at: $(date) *****\"\n\n\tlocal SPEED=$(show_layout 1 |\n\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\techo \"lfsck_layout full_speed is $SPEED objs/sec\"\n\n\tlocal inc_count=$((BASE_COUNT * INCFACTOR / 100))\n\tlocal nfiles=$((inc_count / 2))\n\n\tlfsck_attach\n\tfor ((m = 0, n = $INCFACTOR; n < 100;\n\t      m = $((m + inc_count)), n = $((n + INCFACTOR)))); do\n\t\tlocal sl=$((SPEED * n / 100))\n\n\t\t$STOP_LFSCK > /dev/null 2>&1\n\t\techo\n\t\techo \"start lfsck_layout with speed ${sl} at: $(date)\"\n\t\t$RLCTL lfsck_start -M ${MDT_DEV} -t layout -r -s ${sl} ||\n\t\t\tlfsck_detach_error \\\n\t\t\t\"(9) Fail to start lfsck_layout with speed ${sl}\"\n\n\t\techo \"&&&&& Start create files set from ${m} at: $(date) &&&&&\"\n\t\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\t\tlfsck_detach_error \"(10) Fail to create files\"\n\t\techo \"&&&&& End create files set from ${m} at: $(date) &&&&&\"\n\tdone\n\n\t$STOP_LFSCK > /dev/null 2>&1\n\techo\n\techo \"start lfsck_layout with full speed at: $(date)\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t layout -r -s 0 ||\n\t\tlfsck_detach_error \\\n\t\t\"(11) Fail to start lfsck_layout with full speed\"\n\n\techo \"&&&&& start to create files set from ${m} at: $(date) &&&&&\"\n\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\tlfsck_detach_error \"(12) Fail to create files\"\n\techo \"&&&&& end to create files set from ${m} at: $(date) &&&&&\"\n\n\tm=$((m + inc_count))\n\t$STOP_LFSCK > /dev/null 2>&1\n\techo\n\techo \"create without lfsck_layout run back-ground\"\n\techo \"&&&&& start to create files set from ${m} at: $(date) &&&&&\"\n\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\tlfsck_detach_error \"(13) Fail to create files\"\n\techo \"&&&&& end to create files set from ${m} at: $(date) &&&&&\"\n\n\tlfsck_detach\n\techo\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(14) Fail to stopall\"\n\n\tMDSCOUNT=$saved_mdscount\n}\nrun_test 6 \"lfsck layout impact on create performance\"\n\nshow_namespace() {\n\tlocal idx=$1\n\n\tdo_facet mds${idx} \\\n\t\t\"$LCTL get_param -n mdd.$(facet_svc mds${idx}).lfsck_namespace\"\n}\n\nnamespace_test_one() {\n\techo \"***** Start namespace LFSCK on all devices at: $(date) *****\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t namespace -A -r || return 21\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\twait_update_facet mds${n} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${n}).lfsck_namespace |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $WTIME || {\n\t\t\tshow_namespace ${n}\n\t\t\treturn 22\n\t\t}\n\tdone\n\techo \"***** End namespace LFSCK on all devices at: $(date) *****\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tshow_namespace ${n}\n\n\t\tlocal SPEED=$(show_namespace ${n} |\n\t\t\t      awk '/^average_speed_total/ { print $2 }')\n\t\techo\n\t\techo \"lfsck_namespace speed on MDS_${n} is $SPEED objs/sec\"\n\t\techo\n\tdone\n}\n\nnamespace_gen_one() {\n\tlocal idx1=$1\n\tlocal idx2=$2\n\tlocal idx3=$(((idx1 + 1) % MDSCOUNT))\n\tlocal base_mntpt=\"/mnt/lustre_lfsck_${idx1}\"\n\tlocal show_dir=\"$LFSCKDIR/${idx1}/${idx2}\"\n\tlocal work_dir=\"${base_mntpt}_0/$tdir/${idx1}/${idx2}\"\n\n\tmkdir $show_dir || return 20\n\n\tlocal count=$((UNIT * 78 / 100)) # 78% regular files\n\tlocal sub_count=$((count / NTHREADS))\n\techo \"Creating $count regular files under $show_dir at: $(date)\"\n\tfor ((m = 0; m < $NTHREADS; m++)); do\n\t\tlocal sub_dir=\"${base_mntpt}_${m}/$tdir/${idx1}/${idx2}\"\n\n\t\tcreatemany -o ${sub_dir}/f_${m}_ $sub_count > /dev/null &\n\tdone\n\n\twait || {\n\t\terror_noexit \"(21) Fail to gen regular files under $show_dir\"\n\t\treturn 21\n\t}\n\n\tcount=$((UNIT * 3 / 100)) # 3% local sub-dirs\n\techo \"Creating $count local sub-dirs under $show_dir at: $(date)\"\n\tcreatemany -d $work_dir/d_l_ $count > /dev/null || {\n\t\terror_noexit \"(22) Fail to gen local sub-dir under $show_dir\"\n\t\treturn 22\n\t}\n\n\t# 3% * 5 = 15% regular files under local sub-dirs\n\techo \"Creating 5 regular files under each local sub-dir at: $(date)\"\n\tfor ((m = 0; m < $count; m++)); do\n\t\tcreatemany -o $work_dir/d_l_${m}/f_l_ 5 > /dev/null || {\n\t\t\terror_noexit \\\n\t\t\t\"(23) Fail to gen regular under $work_dir/d_l_${m}\"\n\t\t\treturn 23\n\t\t}\n\tdone\n\n\tcount=$((UNIT * 4 / 1000)) # 0.4% multiple hard-links\n\techo \"Creating $count multiple hard-links under $show_dir at: $(date)\"\n\tfor ((m = 0; m < $count; m++)); do\n\t\tln $work_dir/f_0_${m} $work_dir/f_m_${m} || {\n\t\t\terror_noexit \\\n\t\t\t\"(24) Fail to hardlink to $work_dir/f_0_${m}\"\n\t\t\treturn 24\n\t\t}\n\tdone\n\n\tcount=$((UNIT * 3 / 1000)) # 0.3% remote sub-dirs\n\techo \"Creating $count remote sub-dirs under $show_dir, and 4 regular\" \\\n\t\t\"files under each remote sub-dir at: $(date)\"\n\tfor ((m = 0; m < $count; m++)); do\n\t\t$LFS mkdir -i ${idx3} $work_dir/d_r_${m} || {\n\t\t\terror_noexit \\\n\t\t\t\"(25) Fail to remote mkdir $work_dir/d_r_${m}\"\n\t\t\treturn 25\n\t\t}\n\n\t\t# 0.3% * 4 = 1.2% regular files under remote sub-dirs\n\t\tcreatemany -o $work_dir/d_r_${m}/f_r_ 4 > /dev/null || {\n\t\t\terror_noexit \\\n\t\t\t\"(26) Fail to gen regular under $work_dir/d_r_${m}\"\n\t\t\treturn 26\n\t\t}\n\tdone\n\n\t# 0.3% 2-striped sub-dirs + 0.6% shards of the 2-striped sub-dirs\n\tcount=$((UNIT * 3 / 1000))\n\techo \"Creating $count 2-striped sub-dirs under $show_dir,\" \\\n\t\t\"and 4 regular files under each striped sub-dir at: $(date)\"\n\tfor ((m = 0; m < $count; m++)); do\n\t\t$LFS setdirstripe -i ${idx1} -c 2 -H all_char \\\n\t\t\t$work_dir/d_s_${m} || {\n\t\t\terror_noexit \\\n\t\t\t\"(27) Fail to make striped-dir $work_dir/d_s_${m}\"\n\t\t\treturn 27\n\t\t}\n\n\t\t# 0.3% * 4 = 1.2% regular files under striped sub-dirs\n\t\tcreatemany -o $work_dir/d_s_${m}/f_s_ 4 > /dev/null || {\n\t\t\terror_noexit \\\n\t\t\t\"(28) Fail to gen regular under $work_dir/d_s_${m}\"\n\t\t\treturn 28\n\t\t}\n\tdone\n}\n\nnamespace_gen_mdt() {\n\tlocal mdt_idx=$1\n\tlocal dir_cnt=$2\n\tlocal base_mntpt=\"/mnt/lustre_lfsck_${mdt_idx}\"\n\n\t$LFS mkdir -i ${mdt_idx} $LFSCKDIR/${mdt_idx} || return 10\n\n\tfor ((m = 0; m < $NTHREADS; m++)); do\n\t\tlocal mntpt=\"${base_mntpt}_${m}\"\n\n\t\tmkdir -p $mntpt || {\n\t\t\tumount ${base_mntpt}_*\n\t\t\terror_noexit \"(11) Fail to mkdir $mntpt\"\n\t\t\treturn 11\n\t\t}\n\n\t\tmount_client $mntpt || {\n\t\t\tumount ${base_mntpt}_*\n\t\t\terror_noexit \"(12) Fail to mount $mntpt\"\n\t\t\treturn 12\n\t\t}\n\tdone\n\n\tfor ((l = 0; l < $dir_cnt; l++)); do\n\t\tnamespace_gen_one ${mdt_idx} ${l}\n\tdone\n\n\tumount ${base_mntpt}_*\n}\n\nnamespace_gen_set() {\n\n\tlocal cnt=$1\n\n\techo \"##### Start generate test set for subdirs=$cnt at: $(date) #####\"\n\tfor ((k = 0; k < $MDSCOUNT; k++)); do\n\t\tnamespace_gen_mdt ${k} ${cnt} &\n\tdone\n\twait\n\techo \"##### End generate test set for subdirs=$cnt at: $(date) #####\"\n}\n\nt7_test() {\n\tlocal local_loc=$1\n\tlocal saved_mdscount=$MDSCOUNT\n\n\t[ $MDSCOUNT -le 8 ] ||\n\t\terror \"Too much MDT, test data set on each MDT may be unbalance\"\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(1) Fail to stopall\"\n\n\tLFSCKDIR=\"$DIR/$tdir\"\n\tfor ((i = 2; i <= $saved_mdscount; i = $((i + 2)))); do\n\t\tMDSCOUNT=${i}\n\n\t\techo \"+++++ Start cycle mdscount=$MDSCOUNT at: $(date) +++++\"\n\t\techo\n\n\t\tfor ((j = $MINSUBDIR; j <= $MAXSUBDIR;\n\t\t      j = $((j + MINSUBDIR)))); do\n\t\t\techo \"formatall\"\n\t\t\tformatall > /dev/null ||\n\t\t\t\terror \"(2) Fail to formatall, subdirs=${j}\"\n\n\t\t\techo \"setupall\"\n\t\t\tsetupall > /dev/null ||\n\t\t\t\terror \"(3) Fail to setupall, subdirs=${j}\"\n\n\t\t\tmkdir $LFSCKDIR ||\n\t\t\t\terror \"(4) mkdir $LFSCKDIR, subdirs=${j}\"\n\n\t\t\t$LFS setstripe -c 1 -i -1 $LFSCKDIR ||\n\t\t\t\terror \"(5) Fail to setstripe on $LFSCKDIR\"\n\n\t\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\t$LCTL set_param fail_loc=$local_loc\n\n\t\t\tlocal RC=0\n\t\t\tnamespace_gen_set ${j} || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(6) generate set $RC, subdirs=${j}\"\n\n\t\t\tRC=0\n\t\t\tnamespace_test_one || RC=$?\n\t\t\t[ $RC -eq 0 ] ||\n\t\t\t\terror \"(7) LFSCK failed with $RC, subdirs=${j}\"\n\n\t\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\t$LCTL set_param fail_loc=0\n\t\tdone\n\n\t\techo \"stopall\"\n\t\tstopall > /dev/null || error \"(8) Fail to stopall\"\n\n\t\techo\n\t\techo \"----- Stop cycle mdscount=$MDSCOUNT at: $(date) -----\"\n\tdone\n\n\tMDSCOUNT=$saved_mdscount\n}\n\ntest_7a() {\n\tt7_test 0\n}\nrun_test 7a \"namespace LFSCK performance (routine check) without load for DNE\"\n\ntest_7b() {\n\techo \"Inject failure stub to simulate the case of lost linkEA\"\n\t#define OBD_FAIL_LFSCK_NO_LINKEA\t0x161d\n\tt7_test 0x161d\n}\nrun_test 7b \"namespace LFSCK performance (repairing lost linkEA) for DNE\"\n\ntest_7c() {\n\techo \"Inject failure stub to simulate the case of bad FID-in-dirent\"\n\t#define OBD_FAIL_FID_INDIR      0x1501\n\tt7_test 0x1501\n}\nrun_test 7c \"namespace LFSCK performance (repairing bad FID-in-dirent) for DNE\"\n\ntest_8() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\t[ $INCFACTOR -gt 25 ] && INCFACTOR=25\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(1) Fail to stopall\"\n\n\tlocal saved_mdscount=$MDSCOUNT\n\n\tLFSCKDIR=\"$DIR/$tdir\"\n\tMDSCOUNT=2\n\techo \"formatall\"\n\tformatall > /dev/null || error \"(2) Fail to formatall\"\n\n\techo \"setupall\"\n\tsetupall > /dev/null || error \"(3) Fail to setupall\"\n\n\tmkdir $LFSCKDIR || error \"(4) Fail to mkdir $LFSCKDIR\"\n\n\t$LFS setstripe -c 1 -i 0 $LFSCKDIR ||\n\t\terror \"(5) Fail to setstripe on $LFSCKDIR\"\n\n\tlocal RC=0\n\tnamespace_gen_set $TOTSUBDIR || RC=$?\n\t[ $RC -eq 0 ] ||\n\t\terror \"(6) Fail to generate set $RC, subdirs=$TOTSUBDIR\"\n\n\techo\n\techo \"***** Start namespace LFSCK at: $(date) *****\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t namespace -A -r ||\n\t\terror \"(7) Fail to start namespace LFSCK\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\twait_update_facet mds${n} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${n}).lfsck_namespace |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $WTIME || {\n\t\t\tshow_namespace ${n}\n\t\t\terror \"(8) namespace LFSCK cannot finished in time\"\n\t\t}\n\tdone\n\techo \"***** End namespace LFSCK at: $(date) *****\"\n\n\tlocal SPEED=$(show_namespace 1 |\n\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\techo \"lfsck_namespace full_speed is $SPEED objs/sec\"\n\techo\n\n\tlocal inc_count=$((BASE_COUNT * INCFACTOR / 100))\n\tlocal nfiles=$((inc_count / 2))\n\tlocal m=0\n\n\tlfsck_attach\n\n\tlocal stime=$(date +%s)\n\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\tlfsck_detach_error \"(9) Fail to create files\"\n\tlocal etime=$(date +%s)\n\techo \"created $nfiles without lfsck_namespace run back-ground used\" \\\n\t\t\"$((etime - stime)) seconds\"\n\techo\n\n\tfor ((m = nfiles, n = $INCFACTOR; n < 100;\n\t      m = $((m + inc_count)), n = $((n + INCFACTOR)))); do\n\t\tlocal sl=$((SPEED * n / 100))\n\n\t\t$STOP_LFSCK > /dev/null 2>&1\n\t\techo \"start lfsck_namespace with speed ${sl} at: $(date)\"\n\t\t$RLCTL lfsck_start -M ${MDT_DEV} -t namespace -A -r -s ${sl} ||\n\t\t\tlfsck_detach_error \\\n\t\t\t\"(10) Fail to start lfsck_namespace with speed ${sl}\"\n\n\t\tstime=$(date +%s)\n\t\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\t\tlfsck_detach_error \"(11) Fail to create files\"\n\t\tetime=$(date +%s)\n\t\techo \"created $nfiles with namespace LFSCK run with the\" \\\n\t\t\t\"speed limit of ${n}% of full speed used\" \\\n\t\t\t\"$((etime - stime)) seconds\"\n\t\techo\n\tdone\n\n\t$STOP_LFSCK > /dev/null 2>&1\n\techo \"start lfsck_namespace with full speed at: $(date)\"\n\t$RLCTL lfsck_start -M ${MDT_DEV} -t namespace -A -r -s 0 ||\n\t\tlfsck_detach_error \\\n\t\t\"(12) Fail to start lfsck_namespace with full speed\"\n\n\tstime=$(date +%s)\n\tlfsck_fast_create $nfiles ${m} $NTHREADS ||\n\t\tlfsck_detach_error \"(13) Fail to create files\"\n\tetime=$(date +%s)\n\techo \"created $nfiles with namespace LFSCK run with full speed used\" \\\n\t\t\"$((etime - stime)) seconds\"\n\techo\n\n\t$STOP_LFSCK > /dev/null 2>&1\n\n\tlfsck_detach\n\n\techo \"stopall\"\n\tstopall > /dev/null || error \"(14) Fail to stopall\"\n\n\tMDSCOUNT=$saved_mdscount\n}\nrun_test 8 \"lfsck namespace impact on create performance\"\n\n# cleanup the system at last\nlfsck_cleanup\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1046}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\n[ -n \"$LOAD\" ] && load_modules && exit 0\n[ -z \"$NOFORMAT\" ] && formatall\n[ -z \"$NOSETUP\" ] && setupall\n", "num_lines": 10}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\ncleanupall -f\n", "num_lines": 8}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$LNET_SELFTEST_EXCEPT\"\nif (( $LINUX_VERSION_CODE >= $(version_code 4.4.0) )); then\n\t# bug number for skipped test: LU-10073\n\tALWAYS_EXCEPT+=\"               smoke \"\nfi\n\nif [[ $(uname -m) = ppc64 ]]; then\n\t# bug number for skipped test: LU-10073\n\tALWAYS_EXCEPT+=\"               smoke \"\nfi\n\nbuild_test_filter\n\n[ x$LST = x ] && skip_env \"lst not found LST=$LST\"\n\n# FIXME: what is the reasonable value here?\nlst_LOOP=${lst_LOOP:-100000}\nlst_CONCR=${lst_CONCR:-\"1 2 4 8\"}\nlst_SIZES=${lst_SIZES:-\"4k 8k 256k 1M\"}\nif [ \"$SLOW\" = no ]; then\n    lst_CONCR=\"1 8\"\n    lst_SIZES=\"4k 1M\"\n    lst_LOOP=1000\nfi\n\nsmoke_DURATION=${smoke_DURATION:-1800}\nif [ \"$SLOW\" = no ]; then\n    [ $smoke_DURATION -le 300 ] || smoke_DURATION=300\nfi\n\nlst_TESTS=${lst_TESTS:-\"write read ping\"}\n\n# \"none\" -> LST_BRW_CHECK_NONE\n# \"full\" -> LST_BRW_CHECK_FULL\n# \"simple\" -> LST_BRW_CHECK_SIMPLE\nlst_CHECK=${lst_CHECK:-\"full\"}\n\nlst_FROM=${lst_FROM:-\"cs\"}\n\ncase $lst_CHECK in\n\tfull|simple) check=\"check=$lst_CHECK\";;\n\tnone) check=\"\";;\n\t*) error Unknown flag $lst_CHECK;;\nesac\nnodes=$(comma_list \"$(osts_nodes) $(mdts_nodes)\")\nlst_SERVERS=${lst_SERVERS:-$(comma_list \"$(host_nids_address $nodes $NETTYPE)\")}\nlst_CLIENTS=${lst_CLIENTS:-$(comma_list \"$(host_nids_address $CLIENTS $NETTYPE)\")}\ninterim_umount=false\ninterim_umount1=false\n\n#\n# _restore_mount(): This function calls restore_mount function for \"MOUNT\" and\n# \"MOUNT2\" paths to mount clients if they were not mounted and were umounted\n# in this file earlier.\n# Parameter: None\n# Returns: None. Exit with error if client mount fails.\n#\n_restore_mount () {\n\tif $interim_umount && ! is_mounted $MOUNT; then\n\t\trestore_mount $MOUNT || error \"Restore $MOUNT failed\"\n\tfi\n\n\tif $interim_umount1 && ! is_mounted $MOUNT2; then\n\t\trestore_mount $MOUNT2 || error \"Restore $MOUNT2 failed\"\n\tfi\n}\n\nif local_mode; then\n   lst_SERVERS=`hostname`\n   lst_CLIENTS=`hostname`\nfi\n\n# FIXME: do we really need to unload lustre modules on all nodes?\n# bug 19387, comment 9\n# unloading lustre modules is not strictly necessary but unmounting\n# /mnt/lustre before running lst would be useful:\n# 1) because lustre messages clutter logs - we needn't them for testing LNET\n# 2) it's theoretically possible that lst tests congest comm paths so tightly\n# that mounted lustre wouldn't able to perform some of its background activities\nif is_mounted $MOUNT; then\n\tcleanup_mount $MOUNT || error \"Fail to unmount client $MOUNT\"\n\tinterim_umount=true\nfi\n\nif is_mounted $MOUNT2; then\n\tcleanup_mount $MOUNT2 || error \"Fail to unmount client $MOUNT2\"\n\tinterim_umount1=true\nfi\n\nlst_prepare () {\n    # Workaround for bug 15619\n    lst_cleanup_all\n    lst_setup_all\n}\n\n# make batch\ntest_smoke_sub () {\n    local servers=$1\n    local clients=$2\n\n    local nc=$(echo ${clients//,/ } | wc -w)\n    local ns=$(echo ${servers//,/ } | wc -w)\n    echo '#!/bin/bash'\n    echo 'set -e'\n\n    echo 'cleanup () { trap 0; echo killing $1 ... ; kill -9 $1 || true; }'\n\n    echo \"$LST new_session --timeo 100000 hh\"\n    echo \"$LST add_group c $(nids_list $clients)\"\n    echo \"$LST add_group s $(nids_list $servers)\"\n    echo \"$LST add_batch b\"\n\n\tdeclare -a tests\n\n\tcase $lst_FROM in\n\t\tc) tests[0]=\"${nc}:${ns} --from c --to s\";;\n\t\ts) tests[0]=\"${ns}:${nc} --from s --to c\";;\n\t\tcs)tests[0]=\"${nc}:${ns} --from c --to s\"\n\t\t   tests[1]=\"${ns}:${nc} --from s --to c\";;\n\t\t*) error Unknown flag $lst_FROM;;\n\tesac\n\n\tpre=\"$LST add_test --batch b --loop $lst_LOOP \"\n\tfor t in $lst_TESTS; do\n\t\tfor s in $lst_SIZES; do\n\t\t\tfor c in $lst_CONCR; do\n\t\t\t\tfor ((i=0; i<${#tests[@]}; i++)); do\n\t\t\t\t\techo -n \"$pre --concurrency $c\"\\\n\t\t\t\t\t\t\" --distribute ${tests[i]} \"\n\t\t\t\t\tcase $t in\n\t\t\t\t\t\tread|write)\n\t\t\t\t\t\t\techo -n \"brw $t\" \\\n\t\t\t\t\t\t\t\" $check size=$s\";;\n\t\t\t\t\t\tping)\n\t\t\t\t\t\t\techo -n $t;;\n\t\t\t\t\t\t*) error Unknonwn LST test;;\n\t\t\t\t\tesac\n\t\t\t\t\techo\n\t\t\t\tdone\n\t\t\tdone\n\t\tdone\n\tdone\n\n    echo $LST run b\n    echo sleep 1\n    echo \"$LST stat --delay 10 --timeout 10 c s &\"\n    echo 'pid=$!'\n    echo 'trap \"cleanup $pid\" INT TERM'\n    echo sleep $smoke_DURATION\n    echo 'cleanup $pid'\n    \n}\n\nrun_lst () {\n   local file=$1\n\n   export LST_SESSION=$$\n\n   # start lst\n   sh $file\n}\n\ncheck_lst_err () {\n\tlocal log=$1\n\n\tgrep ^Total $log\n\n\tif awk '/^Total.*nodes/ {print $2}' $log | grep -vq '^0$'; then\n\t\t_restore_mount\n\t\terror 'lst Error found'\n\tfi\n}\n\ntest_smoke () {\n\tlst_prepare\n\n\tlocal servers=$lst_SERVERS\n\tlocal clients=$lst_CLIENTS\n\n\tlocal runlst=$TMP/smoke.sh\n\n\tlocal log=$TMP/$tfile.log\n\tlocal rc=0\n\n\ttest_smoke_sub $servers $clients 2>&1 > $runlst\n\n\tcat $runlst\n\n\trun_lst $runlst | tee $log\n\trc=${PIPESTATUS[0]}\n\t[ $rc = 0 ] || { _restore_mount; error \"$runlst failed: $rc\"; }\n\n\tlst_end_session --verbose | tee -a $log\n\n\t# error counters in \"lst show_error\" should be checked\n\tcheck_lst_err $log\n\tlst_cleanup_all\n}\nrun_test smoke \"lst regression test\"\n\ncomplete $SECONDS\n_restore_mount\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 212}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\nexport PATH=`dirname $0`:`dirname $0`/../utils:$PATH\nCREATEMANY=${CREATEMANY:-createmany}\nSTATMANY=${STATMANY:-statmany}\nUNLINKMANY=${UNLINKMANY:-unlinkmany}\nLCTL=${LCTL:-lctl}\n\nMOUNT=${MOUNT:-/mnt/lustre}\nMOUNT2=${MOUNT2:-/mnt/lustre2}\nDIR=${DIR:-$MOUNT}\nDIR2=${DIR2:-$MOUNT2}\nCOUNT=${COUNT:-100}\n\ncleanup() {\n\t[ $CR_PID ] && kill -9 $CR_PID\n\t[ $ST_PID ] && kill -9 $ST_PID\n}\n\ntrap cleanup EXIT\n\nLOCKDIR=$DIR/lockdir\nLOCKFILE=$LOCKDIR/lockfile\nrm -rf $LOCKDIR\n\nNUM=0\n\nMINDIR=$DIR\nMAXDIR=$DIR\nMINRES=4294967295\nMAXRES=0\nmkdir -p $MINDIR\nwhile [ $MINRES -gt $MAXRES ]; do\n\tFILETMP=$MINDIR/f$$${NUM}\n\tDIRTMP=$DIR/d$$/d${NUM}\n\ttouch $FILETMP\n\tmkdir -p $DIRTMP\n\tFILERES=`ls -id $FILETMP | awk '{ print $1 }'`\n\tDIRRES=`ls -id $DIRTMP | awk '{ print $1 }'`\n\tif [ $DIRRES -gt $MAXRES ]; then\n\t\tMAXDIR=$DIRTMP\n\t\tMAXRES=$DIRRES\n\tfi\n\tif [ $FILERES -lt $MINRES -o -z \"$MINFILE\" ]; then\n\t\t[ -f \"$MINFILE\" ] && rm $MINFILE\n\t\tMINFILE=$FILETMP\n\t\tMINRES=$FILERES\n\telse\n\t\trm $FILETMP\n\tfi\n\tNUM=$(($NUM + 1))\ndone\n\nmv $MAXDIR $LOCKDIR\nmv $MINFILE $LOCKFILE\nrm -rf $DIR/d$$\n\n$LCTL mark \"start dir: $LOCKDIR=$MAXRES file: $LOCKFILE=$MINRES\"\n# link will lock $LOCKFILE and $DIR as it creates ${LOCKFILE}{0,1,...}\n$CREATEMANY -l$LOCKFILE $LOCKFILE -$COUNT &\nCR_PID=$!\n\nwhile ! test -f ${LOCKFILE}1 ; do\n\tsleep 1\ndone\n\n# this will lock $DIR and ${LOCKFILE}0\n$STATMANY -s $DIR2/lockdir/lockfile 1 -$COUNT &\nST_PID=$!\n\nsleep $(($COUNT / 2))\n\n$UNLINKMANY $DIR2/lockdir/lockfile 1 $(($COUNT * 1000)) || true\n\ntrap 0\nkill $CR_PID || true\nkill $ST_PID || true\n\nrm -rf $LOCKDIR\n", "num_lines": 81}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nKILL=/bin/kill\nLREPL_LOG=$TMP/lustre_rsync.log\nORIG_PWD=${PWD}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$LRSYNC_EXCEPT \"\n# bug number for skipped test: LU-4256\nALWAYS_EXCEPT+=\"               2b\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\n[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\ncheck_and_setup_lustre\n\nDIR=${DIR:-$MOUNT}\nassert_DIR\n\nif getent group nobody; then\n\tGROUP=nobody\nelif getent group nogroup; then\n\tGROUP=nogroup\nelse\n\terror \"No generic nobody group\"\nfi\n\nexport LRSYNC=${LRSYNC:-\"$LUSTRE/utils/lustre_rsync\"}\n[ ! -f \"$LRSYNC\" ] && export LRSYNC=$(which lustre_rsync)\nexport LRSYNC=\"$LRSYNC -v -c no -d 2\"\n\n# Number of seconds to run dbench\nDBENCH_TIME=${DBENCH_TIME:-60}\nTGT=$TMP/target\nTGT2=$TMP/target2\nMDT0=$($LCTL get_param -n mdc.*.mds_server_uuid |\n\tawk '{ gsub(/_UUID/,\"\"); print $1 }' | head -n1)\n\ninit_changelog() {\n\tchangelog_register || error \"changelog_register failed\"\n\tCL_USER=(${CL_USERS[$SINGLEMDS]})\n\techo $MDT0: Registered changelog user $CL_USER\n\t[ -z $CL_USER ] &&\n\t\techo \"No changelog users present on $SINGLEMDS\"\n}\n\nfini_changelog() {\n\tchangelog_clear\n\tchangelog_deregister\n}\n\ninit_src() {\n\trm -rf $TGT/$tdir $TGT/d*.lustre_rsync-test 2> /dev/null\n\trm -rf $TGT2/$tdir $TGT2/d*.lustre_rsync-test 2> /dev/null\n\trm -rf ${DIR}/$tdir $DIR/d*.lustre_rsync-test ${DIR}/tgt 2> /dev/null\n\trm -f $LREPL_LOG\n\tmkdir -p ${DIR}/$tdir || error \"Failed to create target: \" $DIR/$tdir\n\tmkdir -p ${TGT}/$tdir || error \"Failed to create target: \" $TGT/$tdir\n\tmkdir -p ${TGT2}/$tdir || error \"Failed to create target: \" $TGT2/$tdir\n}\n\ncleanup_src_tgt() {\n\trm -rf $TGT/$tdir\n\trm -rf $DIR/$tdir\n\trm -rf $DIR/tgt\n}\n\n# Check whether the filesystem supports xattr or not.\n# Return value:\n# \"large\" - large xattr is supported\n# \"small\" - large xattr is unsupported but small xattr is supported\n# \"no\"    - xattr is unsupported\ncheck_xattr() {\n    local tgt=$1\n    local xattr=\"no\"\n\n    touch $tgt\n\n    local val=\"$(generate_string $(max_xattr_size))\"\n    if large_xattr_enabled &&\n       setfattr -n user.foo -v $val $tgt 2>/dev/null; then\n            xattr=\"large\"\n    else\n        setfattr -n user.foo -v bar $tgt 2>/dev/null && xattr=\"small\"\n    fi\n\n    rm -f $tgt\n    echo $xattr\n}\n\ncheck_diff() {\n\tlocal changelog_file=$(generate_logname \"changelog\")\n\n\tif [ -e $1 -o -e $2 ]; then\n\t\tdiff -rq -x \"dev1\" $1 $2\n\t\tlocal RC=$?\n\t\tif [ $RC -ne 0 ]; then\n\t\t\t$LFS changelog $MDT0 > $changelog_file\n\t\t\terror \"Failure in replication; differences found.\"\n\t\tfi\n\tfi\n}\n\nprocs_are_stopped() {\n\tlocal pids=\"$*\"\n\tlocal state\n\n\tfor state in $(ps -p \"$pids\" -o state=); do\n\t\tif [[ \"$state\" != T ]]; then\n\t\t\treturn 1\n\t\tfi\n\tdone\n\n\treturn 0\n}\n\n# Send SIGSTOP to PIDs and wait up to 60 seconds for them to show a\n# stopped process state.\nstop_procs() {\n\tlocal pids=\"$*\"\n\tlocal end\n\n\t$KILL -SIGSTOP $pids\n\tend=$((SECONDS + 60))\n\twhile ((SECONDS < end)); do\n\t\tif procs_are_stopped $pids; then\n\t\t\treturn 0\n\t\tfi\n\n\t\tsleep 1\n\tdone\n\n\treturn 1\n}\n\n# Test 1A - test basic operations\ntest_1A() { # was test_1\n    init_src\n    init_changelog\n    local xattr=$(check_xattr $TGT/foo)\n\n    # Directory create\n    mkdir $DIR/$tdir/d1\n    mkdir $DIR/$tdir/d2\n\n    # File create\n    touch $DIR/$tdir/file1\n    cp /etc/hosts  $DIR/$tdir/d1/\n    touch  $DIR/$tdir/d1/\"space in filename\"\n    touch  $DIR/$tdir/d1/file2\n\n    # File rename\n    mv $DIR/$tdir/d1/file2 $DIR/$tdir/d2/file3\n\n    # File and directory delete\n    touch $DIR/$tdir/d1/file4\n    mkdir $DIR/$tdir/d1/del\n    touch  $DIR/$tdir/d1/del/del1\n    touch  $DIR/$tdir/d1/del/del2\n    rm -rf $DIR/$tdir/d1/del\n    rm $DIR/$tdir/d1/file4\n\n    #hard and soft links\n    cat /etc/hosts > $DIR/$tdir/d1/link1\n    ln  $DIR/$tdir/d1/link1  $DIR/$tdir/d1/link2\n    ln -s $DIR/$tdir/d1/link1  $DIR/$tdir/d1/link3\n\n    # Device files\n    #mknod $DIR/$tdir/dev1 b 8 1\n\n\t# Replicate\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\techo \"Replication #1\"\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n    # Set attributes\n    chmod 000 $DIR/$tdir/d2/file3\n    chown nobody:$GROUP $DIR/$tdir/d2/file3\n\n    # Set xattrs\n    if [[ \"$xattr\" != \"no\" ]]; then\n        local value\n        touch $DIR/$tdir/file5\n        [[ \"$xattr\" = \"large\" ]] &&\n            value=\"$(generate_string $(max_xattr_size))\" || value=\"bar\"\n        setfattr -n user.foo -v $value $DIR/$tdir/file5\n    fi\n\n\techo \"Replication #2\"\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\n\tif [[ \"$xattr\" != \"no\" ]]; then\n\t\tlocal xval1=$(get_xattr_value user.foo $TGT/$tdir/file5)\n\t\tlocal xval2=$(get_xattr_value user.foo $TGT2/$tdir/file5)\n\n\t\tif [[ \"$xval1\" != \"$value\" || \"$xval2\" != \"$value\" ]]; then\n\t\t\terror \"Error in replicating xattrs.\"\n\t\tfi\n\tfi\n\n\t# Use diff to compare the source and the destination\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n}\nrun_test 1A \"Simple Replication\"\n\n# Test 1a - test create/delete operations in ROOT directory\ntest_1a() { # LU-5005\n\trm -rf $TGT/root-* 2> /dev/null\n\trm -rf $DIR/root-* 2> /dev/null\n\tinit_src\n\tinit_changelog\n\n\t# Directory create\n\tmkdir $DIR/root-dir\n\n\t# File create\n\ttouch $DIR/root-file\n\ttouch $DIR/root-file2\n\n\t# File rename\n\tmv $DIR/root-file2 $DIR/root-file3\n\n\t# File and directory delete\n\ttouch $DIR/root-file4\n\tmkdir $DIR/root-dir1\n\trm $DIR/root-file4\n\trm -rf $DIR/root-dir1\n\n\t# Replicate\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\techo \"Replication\"\n\t$LRSYNC -s $DIR -t $TGT -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\t# Verify\n\tstat $TGT/root-dir || error \"Dir create not replicated\"\n\tstat $TGT/root-file || error \"File create not replicated\"\n\tstat $TGT/root-file2 && error \"Rename not replicated (src)\"\n\tstat $TGT/root-file3 || error \"Rename not replicated (tgt)\"\n\tstat $TGT/root-dir1 && error \"Dir delete not replicated\"\n\tstat $TGT/root-file4 && error \"File delete not replicated\"\n\n\tcleanup_src_tgt\n\tfini_changelog\n\trm -fr $TGT/root-*\n\trm -fr $DIR/root-*\n\treturn 0\n}\nrun_test 1a \"Replicate create/delete operations in ROOT directory\"\n\n# Test 2a - Replicate files created by dbench\ntest_2a() {\n\tinit_src\n\tinit_changelog\n\n\t# Run dbench\n\tsh rundbench -C -D $DIR/$tdir 2 -t $DBENCH_TIME || error \"dbench failed\"\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\t# Use diff to compare the source and the destination\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 2a \"Replicate files created by dbench.\"\n\n# Test 2b - Replicate files changed by dbench.\ntest_2b() {\n\tlocal child_pid\n\tinit_src\n\tinit_changelog\n\n\t# Run dbench\n\tsh rundbench -C -D $DIR/$tdir 2 -t $DBENCH_TIME &\n\t# wait for dbench to start\n\twait_for_function 'child_pid=$(pgrep dbench)' 360\n\t# let dbench run for a bit\n\tsleep 10\n\n\techo PIDs: $child_pid\n\techo Stopping dbench\n\tstop_procs $child_pid\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\techo Starting replication\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\n    echo Resuming dbench\n    $KILL -SIGCONT $child_pid\n    sleep 10\n\n    echo Stopping dbench\n\tstop_procs $child_pid\n\n\techo Starting replication\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\n    echo \"Wait for dbench to finish\"\n    $KILL -SIGCONT $child_pid\n    wait\n\n\t# Replicate the changes to $TGT\n\techo Starting replication\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n    fini_changelog\n    cleanup_src_tgt\n    return 0\n}\nrun_test 2b \"Replicate files changed by dbench.\"\n\n# Test 2c - Replicate files while dbench is running\ntest_2c() {\n\tinit_src\n\tinit_changelog\n\n\t# Run dbench\n\tsh rundbench -C -D $DIR/$tdir 2 -t $DBENCH_TIME &\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\tsleep 10 # give dbench a headstart\n\tlocal quit=0\n\twhile [ $quit -le 1 ];\n\tdo\n\t\techo \"Running lustre_rsync\"\n\t\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m ${mds1_svc} -u $CL_USER \\\n\t\t\t-l $LREPL_LOG -D $LRSYNC_LOG\n\t\tsleep 5\n\t\tpgrep dbench\n\t\tif [ $? -ne 0 ]; then\n\t\t\tquit=$(expr $quit + 1)\n\t\tfi\n\tdone\n\n\t# Use diff to compare the source and the destination\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 2c \"Replicate files while dbench is running.\"\n\n# Test 3a - Replicate files created by createmany\ntest_3a() {\n\tinit_src\n\tinit_changelog\n\n\tlocal numfiles=1000\n\tcreatemany -o $DIR/$tdir/$tfile $numfiles || error \"createmany failed\"\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 3a \"Replicate files created by createmany\"\n\n# Test 3b - Replicate files created by writemany\ntest_3b() {\n\tinit_src\n\tinit_changelog\n\n\tlocal time=60\n\tlocal threads=5\n\twritemany -q -a $DIR/$tdir/$tfile $time $threads ||\n\t\terror \"writemany failed\"\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 3b \"Replicate files created by writemany\"\n\n# Test 3c - Replicate files created by createmany/unlinkmany\ntest_3c() {\n\tinit_src\n\tinit_changelog\n\n\tlocal numfiles=1000\n\tcreatemany -o $DIR/$tdir/$tfile $numfiles || error \"createmany failed\"\n\tunlinkmany $DIR/$tdir/$tfile $numfiles || error \"unlinkmany failed\"\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0  -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 3c \"Replicate files created by createmany/unlinkmany\"\n\n# Test 4 - Replicate files created by iozone\ntest_4() {\n\twhich iozone > /dev/null 2>&1\n\t[ $? -ne 0 ] && skip \"iozone not found\"\n\n\tinit_src\n\tinit_changelog\n\n\tEND_RUN_FILE=${DIR}/$tdir/run LOAD_PID_FILE=${DIR}/$tdir/pid \\\n\t\tMOUNT=${DIR}/$tdir run_iozone.sh &\n\tsleep 30\n\tchild_pid=$(pgrep iozone)\n\tstop_procs $child_pid\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0  -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n    $KILL -SIGCONT $child_pid\n    sleep 60\n    $KILL -SIGKILL $(pgrep run_iozone.sh)\n    $KILL -SIGKILL $(pgrep iozone)\n\n    # After killing 'run_iozone.sh', process 'iozone' becomes the\n    # child of PID 1. Hence 'wait' does not wait for it. Killing\n    # iozone first, means more iozone processes are spawned off which\n    # is not desirable. So, after sending a sigkill, the test goes\n    # into a wait loop for iozone to cleanup and exit.\n    wait\n    while [ \"$(pgrep \"iozone\")\" != \"\" ];\n    do\n      ps -ef | grep iozone | grep -v grep\n      sleep 1;\n    done\n\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n    fini_changelog\n    cleanup_src_tgt\n    return 0\n}\nrun_test 4 \"Replicate files created by iozone\"\n\n# Test 5a - Stop / start lustre_rsync\ntest_5a() {\n\tinit_src\n\tinit_changelog\n\n\tNUMTEST=2000\n\tcreatemany -o $DIR/$tdir/$tfile $NUMTEST\n\n\t# Replicate the changes to $TGT\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG &\n\tlocal child_pid=$!\n\tsleep 30\n\t$KILL -SIGHUP $child_pid\n\twait\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 5a \"Stop / start lustre_rsync\"\n\n# Test 5b - Kill / restart lustre_rsync\ntest_5b() {\n\tinit_src\n\tinit_changelog\n\n\tNUMTEST=2000\n\tcreatemany -o $DIR/$tdir/$tfile $NUMTEST\n\n\t# Replicate the changes to $TGT\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG &\n\tlocal child_pid=$!\n\tsleep 30\n\t$KILL -SIGKILL $child_pid\n\twait\n\t$LRSYNC -l $LREPL_LOG -D $LRSYNC_LOG\n\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 5b \"Kill / restart lustre_rsync\"\n\n# Test 6 - lustre_rsync large no of hard links\ntest_6() {\n\tinit_src\n\tinit_changelog\n\n\tlocal num_links=128\n\tlocal i\n\n\ttouch $DIR/$tdir/link0\n\tfor ((i = 1; i < num_links - 1; i++)); do\n\t\tln $DIR/$tdir/link0 $DIR/$tdir/link$i\n\tdone\n\t# create an extra hard link of src name ending with dest name\n\tln $DIR/$tdir/link0 $DIR/$tdir/ink0\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t# Replicate the changes to $TGT\n\t$LRSYNC -s $DIR -t $TGT -t $TGT2 -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff $DIR/$tdir $TGT/$tdir\n\tcheck_diff $DIR/$tdir $TGT2/$tdir\n\n\tlocal count1=$(stat --format=%h $TGT/$tdir/link0)\n\tlocal count2=$(stat --format=%h $TGT2/$tdir/link0)\n\tif ((count1 != num_links || count2 != num_links)); then\n\t\tls -l $TGT/$tdir/link0 $TGT2/$tdir/link0\n\t\terror \"Incorrect no of hard links found $count1, $count2\"\n\tfi\n\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 6 \"lustre_rsync large no of hard links\"\n\n# Test 7 - lustre_rsync stripesize\ntest_7() {\n\tlocal numfiles=100\n\n\tinit_src\n\tmkdir -p ${DIR}/tgt/$tdir\n\tinit_changelog\n\n\t$LFS setstripe -c $OSTCOUNT $DIR/$tdir ||\n\t\terror \"$LFS setstripe failed\"\n\tcreatemany -o $DIR/$tdir/$tfile $numfiles\n\n\t# To simulate replication to another lustre filesystem, replicate\n\t# the changes to $DIR/tgt. We can't turn off the changelogs\n\t# while we are registered, so lustre_rsync better not try to\n\t# replicate the replication steps.  It seems ok :)\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t$LRSYNC -s $DIR -t $DIR/tgt -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\tcheck_diff ${DIR}/$tdir $DIR/tgt/$tdir\n\n\tlocal i=0\n\twhile [ $i -lt $numfiles ];\n\tdo\n\t\tlocal count=$($LFS getstripe $DIR/tgt/$tdir/${tfile}$i |\n\t\t\t      awk '/stripe_count/ {print $2}')\n\t\tif [ $count -ne $OSTCOUNT ]; then\n\t\t\terror \"Stripe size not replicated\"\n\t\tfi\n\t\ti=$(expr $i + 1)\n\tdone\n\tfini_changelog\n\tcleanup_src_tgt\n\treturn 0\n}\nrun_test 7 \"lustre_rsync stripesize\"\n\n# Test 8 - Replicate multiple file/directory moves\ntest_8() {\n    init_src\n    init_changelog\n\n    for i in 1 2 3 4 5 6 7 8 9; do\n\tmkdir $DIR/$tdir/d$i\n\t    for j in 1 2 3 4 5 6 7 8 9; do\n\t\tmkdir $DIR/$tdir/d$i/d$i$j\n\t\tcreatemany -o $DIR/$tdir/d$i/d$i$j/a 10 \\\n\t\t    > /dev/null\n\t\tmv $DIR/$tdir/d$i/d$i$j $DIR/$tdir/d$i/d0$i$j\n\t\tcreatemany -o $DIR/$tdir/d$i/d0$i$j/b 10 \\\n\t            > /dev/null\n\t\tmv $DIR/$tdir/d$i/d0$i$j/a0 $DIR/$tdir/d$i/d0$i$j/c0\n\t    done\n\t    mv $DIR/$tdir/d$i $DIR/$tdir/d0$i\n    done\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t$LRSYNC -s $DIR -t $TGT -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\tcheck_diff ${DIR}/$tdir $TGT/$tdir\n\n    fini_changelog\n    cleanup_src_tgt\n    return 0\n}\nrun_test 8 \"Replicate multiple file/directory moves\"\n\ntest_9() {\n    init_src\n    init_changelog\n\n    mkdir $DIR/$tdir/foo\n    touch $DIR/$tdir/foo/a1\n\n\tlocal LRSYNC_LOG=$(generate_logname \"lrsync_log\")\n\t$LRSYNC -s $DIR -t $TGT -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\tcheck_diff ${DIR}/$tdir $TGT/$tdir\n\n\trm -rf $DIR/$tdir/foo\n\n\t$LRSYNC -s $DIR -t $TGT -m $MDT0 -u $CL_USER -l $LREPL_LOG \\\n\t\t-D $LRSYNC_LOG\n\n\tcheck_diff ${DIR}/$tdir $TGT/$tdir\n\n    fini_changelog\n    cleanup_src_tgt\n    return 0\n}\nrun_test 9 \"Replicate recursive directory removal\"\n\ncd $ORIG_PWD\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 680}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nFILENAME=$1\n\nif [ -r ~/.maloorc ] ; then\n\tsource ~/.maloorc\nelse\n\techo \"Error: ~/.maloorc not found.\" \\\n\t     \"Please obtain this file from the maloo web interface,\" \\\n\t     \"under 'Upload results'\"\n\texit 1\nfi\n\nif [ -z $FILENAME ] ; then\n\techo \"Usage: ${0} <tarball or directory>\"\n\texit 2\nfi\n\nif [ ! -r $FILENAME ] ; then\n\techo \"Input file '$FILENAME' not found\"\n\texit 3\nfi\n\necho Uploading $FILENAME to $MALOO_URL\nif [ -d $FILENAME ] ; then\n\tpushd $FILENAME\n\ttar czf upload.tar.gz * |\n\t\tcurl -F \"user_id=${MALOO_USER_ID}\" -F \"upload=@upload.tar.gz\" \\\n\t\t     -F \"user_upload_token=${MALOO_UPLOAD_TOKEN}\" ${MALOO_URL} \\\n\t\t     > /dev/null\n\tpopd\nelse\n\tcurl -F \"user_id=${MALOO_USER_ID}\" -F \"upload=@${FILENAME}\" \\\n\t     -F \"user_upload_token=${MALOO_UPLOAD_TOKEN}\" ${MALOO_URL} \\\n\t     > /dev/null\nfi\necho Complete.\n", "num_lines": 40}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$MDS_SURVEY_EXCEPT \"\n\nbuild_test_filter\n\nMDSSURVEY=${MDSSURVEY:-$(which mds-survey 2>/dev/null || true)}\n[ -z ${MDSSURVEY} ] && skip_env \"mds-survey not found\"\n\nif [ \"$MDS1_VERSION\" -lt $(version_code 2.3.51) ]; then\n\tskip \"Need MDS version at least 2.3.51\"\nfi\n\nfile_count=${file_count:-150000}\ndir_count=${dir_count:-4}\nthrhi=${thrhi:-8}\nthrlo=${thrlo:-1}\n\n[ \"$SLOW\" = no ] && { file_count=50000; dir_count=2; thrhi=4; }\n\ncheck_and_setup_lustre\n\nadjust_inode() {\n    local require_inode=0\n    local avail_mdt_inode=0\n    local avail_ost_inode=0\n\n    require_inode=$((file_count * thrhi))\n    # get available inode for mdt\n    avail_mdt_inode=$(mdt_free_inodes 0)\n    avail_mdt_inode=$((avail_mdt_inode * 9 / 10))\n\n    # get available inode for ost\n    for i in $($LFS df -i | grep ${FSNAME}-OST | awk '{print $4}'); do\n        avail_ost_inode=$((avail_ost_inode + i))\n    done\n    avail_ost_inode=$((avail_ost_inode * 9 / 10))\n\n    ((require_inode > avail_mdt_inode)) && require_inode=$avail_mdt_inode\n    ((require_inode > avail_ost_inode)) && require_inode=$avail_ost_inode\n\n    if ((require_inode == 0)); then\n        error \"Fail to get the inode count\"\n    fi\n    # convert it back to per thread inode\n    require_inode=$((require_inode / thrhi))\n\n    echo $require_inode\n}\n\n\nfile_count=$(adjust_inode)\nost_count=$($LCTL dl | grep -c osc)\n\n# first unmount all the lustre clients\ncleanup_mount $MOUNT\ncleanup_mount $MOUNT2\n\nget_target() {\n\tlocal node=$1\n\tlocal mdt\n\tlocal mdts\n\tlocal target\n\n\tmdts=$(do_node $node \"$LCTL dl\" |\n\t       awk \"{if (\\$2 == \\\"UP\\\" && \\$3 == \\\"mdt\\\") {print \\$4}}\")\n\n\tfor mdt in $mdts; do\n\t\ttarget+=\"${target:+ }$node:$mdt\"\n\tdone\n\n\techo -n $target\n}\n\nget_targets() {\n\tlocal targets\n\tlocal node\n\n\tfor node in $(mdts_nodes); do\n\t\ttargets+=\"${targets:+ }$(get_target $node)\"\n\tdone\n\n\techo -n $targets\n}\n\nmds_survey_run() {\n\tlocal layer=${1:-mdd}\n\tlocal stripe_count=${2:-0}\n\tlocal rc=0\n\n\trm -f ${TMP}/mds_survey*\n\n\tlocal cmd=\"file_count=$file_count thrlo=$thrlo thrhi=$thrhi\"\n\tcmd+=\" dir_count=$dir_count layer=$layer stripe_count=$stripe_count\"\n\tcmd+=\" rslt_loc=${TMP} targets=\\\"$(get_targets)\\\" $MDSSURVEY\"\n\n\ttrap cleanup_echo_devs EXIT ERR\n\n\techo + $cmd\n\teval $cmd || rc=$?\n\tcat ${TMP}/mds_survey*\n\trm -f ${TMP}/mds_survey*\n\t((rc == 0)) || error \"mds-survey failed\"\n}\n\ntest_1() {\n\tmds_survey_run \"mdd\" \"0\"\n}\nrun_test 1 \"Metadata survey with zero-stripe\"\n\ntest_2() {\n\tlocal mdscount=$(get_node_count \"$(mdts_nodes)\")\n\n\t[ $mdscount -gt 1 ] && skip_env \"Only run this test on single MDS\"\n\t[ $ost_count -eq 0 ] && skip_env \"Need to mount OST to test\"\n\n\tmds_survey_run \"mdd\" \"1\"\n}\nrun_test 2 \"Metadata survey with stripe_count = 1\"\n\n# remount the clients\nrestore_mount $MOUNT\n\ncomplete $SECONDS\ncleanup_echo_devs\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 134}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-4 test).\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\nBASEDIR=$MOUNT/mdsrate\n\n# Requirements\n# set NUM_FILES=0 to force TIME_PERIOD work\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\n# Local test variables\nTESTDIR_SINGLE=\"${BASEDIR}/single\"\nTESTDIR_MULTI=\"${BASEDIR}/multi\"\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-c -1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\n# Make sure we start with a clean slate\nrm -f ${LOG}\n\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Test for creates for a single client.\"\nelse\n    # We can use np = $NUM_CLIENTS to speed up the cleanup\n    mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR_SINGLE 'f%%d' --ignore\n\n    log \"===== $0 ### 1 NODE CREATE ###\"\n\n\tCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --create --time ${TIME_PERIOD}\n\t\t--nfiles ${NUM_FILES} --dir ${TESTDIR_SINGLE} --filefmt 'f%%d'\"\n\techo \"+ ${COMMAND}\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate create on single client failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR_SINGLE 'f%%d' --ignore\n\t\texit 1\n\tfi\n\n    log \"===== $0 ### 1 NODE UNLINK ###\"\n\n    COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --unlink\n                --nfiles ${NUM_FILES} --dir ${TESTDIR_SINGLE} --filefmt 'f%%d'\"\n    echo \"+ ${COMMAND}\"\n    mpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} | tee ${LOG}\n\n    if [ ${PIPESTATUS[0]} != 0 ]; then\n\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\terror \"mdsrate unlink on a single client failed, aborting\"\n    fi\n\n    rmdir $TESTDIR_SINGLE\nfi\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\n[ $NUM_CLIENTS -eq 1 ] && NOMULTI=yes\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO test for create on multiple nodes.\"\nelse\n    mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR_MULTI 'f%%d' --ignore\n\n    log \"===== $0 ### $NUM_CLIENTS NODES CREATE ###\"\n\n\tCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --create --time ${TIME_PERIOD}\n\t\t--nfiles $NUM_FILES --dir ${TESTDIR_MULTI} --filefmt 'f%%d'\"\n\techo \"+ ${COMMAND}\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate create on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR_MULTI 'f%%d' --ignore\n\t\texit 1\n\tfi\n\n    log \"===== $0 ### $NUM_CLIENTS NODES UNLINK ###\"\n\n\tCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --unlink\n\t\t--nfiles ${NUM_FILES} --dir ${TESTDIR_MULTI} --filefmt 'f%%d'\"\n\techo \"+ ${COMMAND}\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n    if [ ${PIPESTATUS[0]} != 0 ]; then\n\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\terror \"mdsrate unlink on multiple nodes failed, aborting\"\n    fi\n\n    rmdir $TESTDIR_MULTI\nfi\n\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 136}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": " #!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-3 test).\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\nBASEDIR=$MOUNT/mdsrate\n\n# Requirements\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\n# Local test variables\nTESTDIR_SINGLE=\"${BASEDIR}/single\"\nTESTDIR_MULTI=\"${BASEDIR}/multi\"\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n# XXX - this needs to be determined given the number of MDTs and the number\n#       of clients.\nTHREADS_PER_CLIENT=3                   # threads/client for multi client test\nif [ $NUM_CLIENTS -gt 50 ]; then\n    THREADS_PER_CLIENT=1\nfi\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\n# Make sure we start with a clean slate\nrm -f ${LOG}\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-i 0 -c 1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Tests on single client.\"\nelse\n    if [ -n \"$NOCREATE\" ]; then\n        echo \"NO Test for creates for a single client.\"\n    else\n        # We can use np = $NUM_CLIENTS to speed up the cleanup\n        mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR_SINGLE 'f%%d' --ignore\n\n        log \"===== $0 ### 1 NODE CREATE ###\"\n\n\tCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --create --time ${TIME_PERIOD}\n\t\t--nfiles $NUM_FILES --dir ${TESTDIR_SINGLE} --filefmt 'f%%d'\"\n\techo \"+ ${COMMAND}\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate create on single client failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR_SINGLE 'f%%d' --ignore\n\t\texit 1\n\tfi\n    fi\n\n    if [ -n \"$NOUNLINK\" ]; then\n        echo \"NO Test for unlinks for a single client.\"\n    else\n        log \"===== $0 ### 1 NODE UNLINK ###\"\n\n        COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --unlink\n                     --nfiles ${NUM_FILES} --dir ${TESTDIR_SINGLE} --filefmt 'f%%d'\"\n        echo \"+ ${COMMAND}\"\n        mpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n        if [ ${PIPESTATUS[0]} != 0 ]; then\n            [ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n            error \"mdsrate unlinks for a single client failed, aborting\"\n        fi\n\n        rmdir $TESTDIR_SINGLE\n    fi\nfi\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO tests on multiple nodes.\"\nelse\n    if [ -n \"$NOCREATE\" ]; then\n        echo \"NO test for create on multiple nodes.\"\n    else\n        mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR_MULTI 'f%%d' --ignore\n\n        log \"===== $0 ### $NUM_CLIENTS NODES CREATE with $THREADS_PER_CLIENT threads per client ###\"\n\n\tCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --create --time ${TIME_PERIOD}\n\t\t--nfiles $NUM_FILES --dir ${TESTDIR_MULTI} --filefmt 'f%%d'\"\n\techo \"+ ${COMMAND}\"\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((NUM_CLIENTS * THREADS_PER_CLIENT)) ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate create on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup $((NUM_CLIENTS * THREADS_PER_CLIENT)) \\\n\t\t\t\t$MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR_MULTI 'f%%d' --ignore\n\t\texit 1\n\tfi\n    fi\n\n    if [ -n \"$NOUNLINK\" ]; then\n        echo \"NO Test for unlinks multiple nodes.\"\n    else\n        log \"===== $0 ### $NUM_CLIENTS NODES UNLINK with $THREADS_PER_CLIENT threads per client ###\"\n\n        COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --unlink\n                      --nfiles ${NUM_FILES} --dir ${TESTDIR_MULTI} --filefmt 'f%%d'\"\n        echo \"+ ${COMMAND}\"\n        mpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} \\\n\t\t-np $((NUM_CLIENTS * THREADS_PER_CLIENT)) ${COMMAND} |\n\t\ttee ${LOG}\n        if [ ${PIPESTATUS[0]} != 0 ]; then\n            [ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n            error \"mdsrate unlinks multiple nodes failed, aborting\"\n        fi\n\n        rmdir $TESTDIR_MULTI\n    fi\nfi\n\ncomplete $SECONDS\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 160}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-5 test).\n\n# Directory lookup retrieval rate 10 directories 1 million files each\n# 6000 random lookups/sec per client node 62,000 random lookups/sec aggregate\n#\n# In 10 dirs containing 1 million files each the mdsrate Test Program will\n# perform lookups for 10 minutes. This test is run from a single node for\n# #1 and from all nodes for #2 aggregate test to measure lookup performance.\n# TEst performs lookups across all 10 directories.\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n# Do not use name [df][0-9]* to avoid cleanup by rm, bug 18045\nBASEDIR=$MOUNT/mdsrate\n\n# Requirements\nNUM_DIRS=${NUM_DIRS:-10}\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\nrm -f $LOG\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-c 1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(($(mdsrate_inodes_available) - NUM_DIRS))\nif [ $IFree -lt $((NUM_FILES * NUM_DIRS)) ]; then\n    NUM_FILES=$((IFree / NUM_DIRS))\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\nDIRfmt=\"${BASEDIR}/lookup-%d\"\n\n#\n# Unlink the files created in the directories under $BASEDIR.\n# FIXME: does it make sense to add the possibility to unlink dirfmt to mdsrate?\n#\nmdsrate_cleanup_all() {\n\tlocal i\n\tfor i in $(seq 0 $NUM_DIRS); do\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$BASEDIR/lookup-$i 'f%%d' --ignore\n\tdone\n}\n\nif [ -n \"$NOCREATE\" ]; then\n    echo \"NOCREATE=$NOCREATE  => no file creation.\"\nelse\n\tmdsrate_cleanup_all\n\n    log \"===== $0 Test preparation: creating ${NUM_DIRS} dirs with ${NUM_FILES} files.\"\n\n    COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --mknod\n                        --ndirs ${NUM_DIRS} --dirfmt '${DIRfmt}'\n                        --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\n\techo \"+\" ${COMMAND}\n\t# For files creation we can use -np equal to NUM_DIRS\n\t# This is just a test preparation, does not matter how many threads we\n\t# use for files creation; we just should be aware that NUM_DIRS is less\n\t# than or equal to the number of threads np\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_DIRS} \\\n\t\t${COMMAND} 2>&1\n\n\t# No lookup if error occurs on file creation, abort.\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror_noexit \"mdsrate file creation failed, aborting\"\n\t\tmdsrate_cleanup_all\n\t\texit 1\n\tfi\nfi\n\nCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --lookup --time ${TIME_PERIOD} ${SEED_OPTION}\n        --ndirs ${NUM_DIRS} --dirfmt '${DIRfmt}'\n        --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\n# 1\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Test for lookups on a single client.\"\nelse\n\tlog \"===== $0 ### 1 NODE LOOKUPS ###\"\n\techo \"+\" ${COMMAND}\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate lookup on single client failed, aborting\"\n\t\tmdsrate_cleanup_all\n\t\texit 1\n\tfi\nfi\n\n# 2\n[ $NUM_CLIENTS -eq 1 ] && NOMULTI=yes\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO test for lookups on multiple nodes.\"\nelse\n\tlog \"===== $0 ### ${NUM_CLIENTS} NODES LOOKUPS ###\"\n\techo \"+\" ${COMMAND}\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate lookup on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup_all\n\t\texit 1\n\tfi\nfi\n\ncomplete $SECONDS\nmdsrate_cleanup_all\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 141}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-5 test).\n\n# Directory lookup retrieval rate single directory 10 million files\n# 5900 random lookups/sec per client node 62,000 random lookups/sec aggregate\n#\n# In a dir containing 10 million non-striped files the mdsrate Test Program will\n# perform lookups for 10 minutes. This test can be run from a single node for\n# #1 and from all nodes for #2 aggregate test to measure lookup performance.\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n# Do not use name [df][0-9]* to avoid cleanup by rm, bug 18045\nBASEDIR=$MOUNT/mdsrate\nTESTDIR=$BASEDIR/lookup\n\n# Requirements\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\nrm -f $LOG\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-c 1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\nif [ -n \"$NOCREATE\" ]; then\n    echo \"NOCREATE=$NOCREATE  => no file creation.\"\nelse\n    mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d' --ignore\n\n    log \"===== $0 Test preparation: creating ${NUM_FILES} files.\"\n\n    NUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n    NUM_THREADS=$((NUM_CLIENTS * MDSCOUNT))\n    if [ $NUM_CLIENTS -gt 50 ]; then\n        NUM_THREADS=$NUM_CLIENTS\n    fi\n    COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --mknod --dir ${TESTDIR}\n                        --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\techo \"+\" ${COMMAND}\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_THREADS} \\\n\t\t${COMMAND} 2>&1\n\n\t# No lockup if error occurs on file creation, abort.\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror_noexit \"mdsrate file creation failed, aborting\"\n\t\tmdsrate_cleanup $NUM_THREADS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\nCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --lookup --time ${TIME_PERIOD} ${SEED_OPTION}\n        --dir ${TESTDIR} --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\n# 1\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Test for lookups on a single client.\"\nelse\n\tlog \"===== $0 ### 1 NODE LOOKUPS ###\"\n\techo \"+\" ${COMMAND}\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate lookup on single client failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\n# 2\n[ $NUM_CLIENTS -eq 1 ] && NOMULTI=yes\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO test for lookups on multiple nodes.\"\nelse\n\tlog \"===== $0 ### ${NUM_CLIENTS} NODES LOOKUPS ###\"\n\techo \"+\" ${COMMAND}\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate lookup on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\ncomplete $SECONDS\nmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d'\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 127}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-8 test).\n\n# File attribute retrieval rate for large file creation\n# 3300 ops/sec/OST for single node 28500 ops/sec/OST aggregate\n\n# In a dir containing 10 million striped files, the mdsrate Test Program will\n# perform directory ordered stat's (readdir) for 10 minutes. This test will be\n# run from a single node for #1 and from all nodes for #2 aggregate test to\n# measure stat performance.\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n# Do not use name [df][0-9]* to avoid cleanup by rm, bug 18045\nBASEDIR=$MOUNT/mdsrate\nTESTDIR=$MOUNT/stat\n\n# Requirements\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\nrm -f $LOG\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-c -1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\nif [ -n \"$NOCREATE\" ]; then\n    echo \"NOCREATE=$NOCREATE  => no file creation.\"\nelse\n    mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d' --ignore\n\n    log \"===== $0 Test preparation: creating ${NUM_FILES} files.\"\n\n    COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --create --dir ${TESTDIR}\n                        --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n    echo \"+\" ${COMMAND}\n\n    NUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n    NUM_THREADS=$((NUM_CLIENTS * MDSCOUNT))\n    if [ $NUM_CLIENTS -gt 50 ]; then\n        NUM_THREADS=$NUM_CLIENTS\n    fi\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_THREADS} \\\n\t\t${COMMAND} 2>&1\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror_noexit \"mdsrate file creation failed, aborting\"\n\t\tmdsrate_cleanup $NUM_THREADS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\nCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --stat --time ${TIME_PERIOD}\n        --dir ${TESTDIR} --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\n# 1\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Test for stats on a single client.\"\nelse\n    log \"===== $0 ### 1 NODE STAT ###\"\n    echo \"+\" ${COMMAND}\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate stat on single client failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\n# 2\n[ $NUM_CLIENTS -eq 1 ] && NOMULTI=yes\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO test for stats on multiple nodes.\"\nelse\n    log \"===== $0 ### ${NUM_CLIENTS} NODES STAT ###\"\n    echo \"+\" ${COMMAND}\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate stat on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\n\ncomplete $SECONDS\nmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d'\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 133}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This test was used in a set of CMD3 tests (cmd3-7 test).\n\n# File attribute retrieval rate for small file creation\n# 3200 ops/sec for single node 29,000 ops/sec aggregate\n\n# In a dir containing 10 million non-striped files, the mdsrate Test Program\n# will perform directory ordered stat's (readdir) for 10 minutes. This test\n# will be run from a single node for #1 and from all nodes for #2\n# aggregate test to measure stat performance.\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nassert_env CLIENTS MDSRATE SINGLECLIENT MPIRUN\n\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n# Do not use name [df][0-9]* to avoid cleanup by rm, bug 18045\nBASEDIR=$MOUNT/mdsrate\nTESTDIR=$BASEDIR/stat\n\n# Requirements\nNUM_FILES=${NUM_FILES:-1000000}\nTIME_PERIOD=${TIME_PERIOD:-600}                        # seconds\n\nLOG=${TESTSUITELOG:-$TMP/$(basename $0 .sh).log}\nCLIENT=$SINGLECLIENT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n\nrm -f $LOG\n\n[ ! -x ${MDSRATE} ] && error \"${MDSRATE} not built.\"\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\n\nmkdir -p $BASEDIR\nchmod 0777 $BASEDIR\nmdsrate_STRIPEPARAMS=${mdsrate_STRIPEPARAMS:-${fs_STRIPEPARAMS:-\"-i 0 -c 1\"}}\nsetstripe_getstripe $BASEDIR $mdsrate_STRIPEPARAMS\n\nIFree=$(mdsrate_inodes_available)\nif [ $IFree -lt $NUM_FILES ]; then\n    NUM_FILES=$IFree\nfi\n\ngenerate_machine_file $NODES_TO_USE $MACHINEFILE || error \"can not generate machinefile\"\n\nif [ -n \"$NOCREATE\" ]; then\n    echo \"NOCREATE=$NOCREATE  => no file creation.\"\nelse\n    mdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d' --ignore\n\n    log \"===== $0 Test preparation: creating ${NUM_FILES} files.\"\n\n    COMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --mknod --dir ${TESTDIR}\n                        --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n    echo \"+\" ${COMMAND}\n\n    NUM_CLIENTS=$(get_node_count ${NODES_TO_USE//,/ })\n    NUM_THREADS=$((NUM_CLIENTS * MDSCOUNT))\n    if [ $NUM_CLIENTS -gt 50 ]; then\n        NUM_THREADS=$NUM_CLIENTS\n    fi\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_THREADS} \\\n\t\t${COMMAND} 2>&1\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\terror_noexit \"mdsrate file creation failed, aborting\"\n\t\tmdsrate_cleanup $NUM_THREADS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\nCOMMAND=\"${MDSRATE} ${MDSRATE_DEBUG} --stat --time ${TIME_PERIOD}\n        --dir ${TESTDIR} --nfiles ${NUM_FILES} --filefmt 'f%%d'\"\n\n# 1\nif [ -n \"$NOSINGLE\" ]; then\n    echo \"NO Test for stats on a single client.\"\nelse\n    log \"===== $0 ### 1 NODE STAT ###\"\n    echo \"+\" ${COMMAND}\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np 1 ${COMMAND} |\n\t\ttee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate stat on single client failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\n# 2\n[ $NUM_CLIENTS -eq 1 ] && NOMULTI=yes\nif [ -n \"$NOMULTI\" ]; then\n    echo \"NO test for stats on multiple nodes.\"\nelse\n    log \"===== $0 ### ${NUM_CLIENTS} NODES STAT ###\"\n    echo \"+\" ${COMMAND}\n\n\tmpi_run ${MACHINEFILE_OPTION} ${MACHINEFILE} -np ${NUM_CLIENTS} \\\n\t\t${COMMAND} | tee ${LOG}\n\n\tif [ ${PIPESTATUS[0]} != 0 ]; then\n\t\t[ -f $LOG ] && sed -e \"s/^/log: /\" $LOG\n\t\terror_noexit \"mdsrate stat on multiple nodes failed, aborting\"\n\t\tmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES \\\n\t\t\t\t$TESTDIR 'f%%d' --ignore\n\t\texit 1\n\tfi\nfi\n\ncomplete $SECONDS\nmdsrate_cleanup $NUM_CLIENTS $MACHINEFILE $NUM_FILES $TESTDIR 'f%%d'\nrmdir $BASEDIR || true\nrm -f $MACHINEFILE\ncheck_and_cleanup_lustre\n#rm -f $LOG\n\nexit 0\n", "num_lines": 132}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# A Metadata Update Test tests that\n# metadata updates are properly completed when\n# multiple clients create/delete files and modify the attributes of files.\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\n#Bug number for excepting test\nALWAYS_EXCEPT=\"$METADATA_UPDATES_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT LIST\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nTRACE=${TRACE:-\"+x\"}\n\nTESTDIR=${TESTDIR:-$DIR/d0.$(basename $0 .sh)}\n\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\n\n[ -z $CLIENTS ] && NODES_TO_USE=$(hostname)\n\n# hostname could differ from a network interface\n# configured for NODES_TO_USE, bug 23961\n# the test dir on each host is created based on `hostname` of this host\nHOSTS=$(comma_list $(do_nodes $NODES_TO_USE \"echo \\\\\\$(hostname)\"))\n\nFILE=testfile\nFILE_SIZE=1024\nCURRENT_MODE=0644\nNEW_MODE=0222\nNEW_ATIME=\"2001-01-01 GMT\"\nNEW_MTIME=\"2005-05-05 GMT\"\n\ntest_USER=$(id -u -n)\ntest_GROUP=$(id -g -n)\n\nSUMFILE=$TESTDIR/mdsum\n\nNUM_FILES=1000\n\nlog \"===== $0 ====== \"\n\ncheck_and_setup_lustre\nbuild_test_filter\n\ncleanup_prepare () {\n\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tDIR=$TESTDIR/\\\\\\$(hostname);\n\tTESTFILE=\\\\\\$DIR/$FILE;\n\trm -f \\\\\\$TESTFILE;\n\trm -f $SUMFILE;\n\trmdir \\\\\\$DIR 2>/dev/null;\n\tmkdir -p \\\\\\$DIR\" || return ${PIPESTATUS[0]}\n\treturn 0;\n}\n\ndo_mknod () {\n\tlog \"Creating file(s) by mknod (2) ... \"\n\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\tmcreate \\\\\\$TESTFILE; \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_write () {\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\tdd if=/dev/zero of=\\\\\\$TESTFILE bs=$FILE_SIZE count=1 2>/dev/null ||\n\t\texit 54;\n\techo \\\\\\$(hostname) | dd of=\\\\\\$TESTFILE conv=notrunc 2>/dev/null ||\n\t\texit 55;\n\tmd5sum \\\\\\$TESTFILE >> $SUMFILE; \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_check_data () {\n\tlog \"Checking file(s) data ... md5sum : \"\n\tcat $SUMFILE\n\n\tdo_nodesv $NODES_TO_USE \"md5sum --check $SUMFILE\" ||\n\t\treturn ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_truncate () {\n\tlog \"Truncating file(s) ... \"\n\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\t$TRUNCATE \\\\\\$TESTFILE 0\" || return ${PIPESTATUS[0]}\n\n\tFILE_SIZE=0\n\treturn 0\n}\n\n# check st_uid, st_gid, st_size, st_mode\nget_stat () {\n\tlocal attr=\"$test_USER $test_GROUP $FILE_SIZE $CURRENT_MODE\"\n\n\tlog \"Checking file(s) attributes ... \"\n\n\tdo_nodesv $NODES_TO_USE \"set $TRACE;\nfor HOST in ${HOSTS//,/ } ; do\n    TESTFILE=$TESTDIR/\\\\\\$HOST/$FILE;\n    tmp=\\\\\\$(stat -c \\\\\\\"%U %G %s 0%a\\\\\\\" \\\\\\$TESTFILE);\n    echo \\\\\\\"\\\\\\$TESTFILE [ uid gid size mode ] expected : $attr ;  got : \\\\\\$tmp \\\\\\\";\n    if [ x\\\\\\\"\\\\\\$tmp\\\\\\\" != x\\\\\\\"$attr\\\\\\\" ] ; then\n        echo \\\\\\\"Wrong file attributes\\\\\\\";\n        exit 56;\n    fi;\ndone \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_chmod () {\n\tlog \"Performing chmod 0$NEW_MODE ...\"\n\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\tchmod $NEW_MODE \\\\\\$TESTFILE\" || return ${PIPESTATUS[0]}\n\n\tCURRENT_MODE=$NEW_MODE\n\treturn 0\n}\n\ndo_change_timestamps () {\n\tlog \"Changing atime, mtime ...\"\n\n\tdo_nodes $NODES_TO_USE \" set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\ttouch -c --date=\\\\\\\"$NEW_ATIME\\\\\\\" -a \\\\\\$TESTFILE;\n\ttouch -c --date=\\\\\\\"$NEW_MTIME\\\\\\\" -m \\\\\\$TESTFILE \" ||\n\t\treturn ${PIPESTATUS[0]}\n\treturn 0\n}\n\n# check st_atime, st_mtime\ndo_check_timestamps () {\n\tlocal atime=$(date --date=\"$NEW_ATIME\" +%s)\n\tlocal mtime=$(date --date=\"$NEW_MTIME\" +%s)\n\n\tlocal times=\"$atime $mtime\"\n\n\tlog \"Checking atime, mtime ... \"\n\n\tdo_nodesv $NODES_TO_USE \"set $TRACE;\nfor HOST in ${HOSTS//,/ } ; do\n    TESTFILE=$TESTDIR/\\\\\\$HOST/$FILE;\n    tmp=\\\\\\$(stat -c \\\\\\\"%X %Y\\\\\\\" \\\\\\$TESTFILE);\n    if [ x\\\\\\\"\\\\\\$tmp\\\\\\\" != x\\\\\\\"$times\\\\\\\" ] ; then\n       echo \\\\\\\"\\\\\\$TESTFILE [ atime mtime ] expected : $times ;  got : \\\\\\$tmp \\\\\\\";\n       RC=57;\n    fi;\ndone;\nexit \\\\\\$RC\" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_fill_dir () {\n\tlog \"Filling up directories ... files : f1 ... f$NUM_FILES) ... \"\n\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\n\tTESTFILE=$TESTDIR/\\\\\\$(hostname)/$FILE;\n\trm -f \\\\\\$TESTFILE;\n\tDIR=$TESTDIR/\\\\\\$(hostname);\n\tfor i in \\\\\\$(seq $NUM_FILES) ; do\n\t\ttouch \\\\\\$DIR/f\\\\\\$i;\n\tdone \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ncheck_dir_contents () {\n\tlocal num_files=${1:-1}\n\n\tlog \"Directory contents should exist: f$num_files ... f$NUM_FILES)\"\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\nfor HOST in ${HOSTS//,/ } ; do\n    DIR=$TESTDIR/\\\\\\$HOST;\n    for i in \\\\\\$(seq $NUM_FILES -1 $num_files) ; do\n        if ! [ -f \\\\\\$DIR/f\\\\\\$i ] ; then\n            echo \\\\\\\"ERROR: file \\\\\\$DIR/f\\\\\\$i should exist\\\\\\\";\n            RC=1;\n        fi;\n    done;\n    for i in \\\\\\$(seq $(($num_files - 1 ))) ; do\n        if [ -f \\\\\\$DIR/f\\\\\\$i ] ; then\n            echo \\\\\\\"ERROR: deleted file \\\\\\$DIR/f\\\\\\$i exists\\\\\\\";\n            RC=1;\n        fi;\n    done;\ndone;\nexit \\\\\\$RC \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\ndo_partial_delete () {\n\tlocal num_files=$1\n\n\tlog \"Deleting files ... f1 ... f$num_files ... \"\n\tdo_nodes $NODES_TO_USE \"set $TRACE;\nDIR=$TESTDIR/\\\\\\$(hostname);\nfor i in \\\\\\$(seq $num_files) ; do\n    if ! rm -f \\\\\\$DIR/f\\\\\\$i ; then\n        exit 1;\n    fi;\ndone \" || return ${PIPESTATUS[0]}\n\treturn 0\n}\n\nchmod 0777 $MOUNT   || exit 1\nmkdir -p $TESTDIR   || exit 1\nchmod 0777 $TESTDIR || exit 1\n\ncleanup_prepare     || error_exit \"cleanup failed\"\n\ntest_1(){\n\tlog \"Create files (mknod (2)) and write data\"\n\tdo_mknod || error \"mknod failed\"\n\tdo_write || error \"write data failed\"\n\tlog \"Check data and file attributes.\"\n\tdo_check_data || error \"md5sum verification failed\"\n\tget_stat || error \"attributes check failed\"\n\n\t# file attributes modification\n\tlog \"File attributes modification.\"\n\tdo_chmod || error \"chmod failed\"\n\tget_stat || error \"wrong attributes after chmod\"\n\n\tdo_change_timestamps || error \"timestamps change failed\"\n\tdo_check_timestamps || error \"wrong timestamps\"\n\n\t# truncate file(s) to 0 size, check new file size\n\tlog \"Truncate file(s) to 0 size, check new file size.\"\n\tdo_truncate || error \"truncate failed\"\n\tget_stat || error \"wrong attributes after truncate\"\n}\nrun_test 1 \"create files (mknod), write and check data, truncate files\"\n\ntest_2() {\n\tdo_fill_dir || error \"dir creation failed\"\n\tcheck_dir_contents || error \"dir contents check failed\"\n\n\tdo_partial_delete $(($NUM_FILES / 2)) || error \"delete failed\"\n\tcheck_dir_contents $(($NUM_FILES / 2 + 1)) ||\n\t\terror \"dir contents check after delete failed\"\n}\nrun_test 2 \"directory content create, check, delete files , check\"\n\ntest_3() {\n\tWRITE_DISJOINT=${WRITE_DISJOINT:-$(which write_disjoint 2> /dev/null)} || true\n\tdisjoint_file=$TESTDIR/$tfile\n\tmachine_file=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n\tnumloops=1000\n\n\t[ ! -f \"$WRITE_DISJOINT\" ] && skip_env \"write_disjoint not found\"\n\n\tset $TRACE\n\tgenerate_machine_file $NODES_TO_USE $machine_file\n\tmpi_run ${MACHINEFILE_OPTION} $machine_file \\\n\t\t-np $(get_node_count ${NODES_TO_USE//,/ }) \\\n\t\t$WRITE_DISJOINT -f $disjoint_file -n $numloops ||\n\t\t\terror \"mpi_run failed\"\n\n\trm -f $machine_file\n}\nrun_test 3 \"write_disjoint test\"\n\ncomplete $SECONDS\nrm -rf $TESTDIR\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 283}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Tests for multiple mount protection (MMP) feature.\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# e.g. ONLY=\"5 6\" or ONLY=\"`seq 8 11`\" or EXCEPT=\"7\"\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=$MMP_EXCEPT\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nremote_mds_nodsh && skip \"remote MDS with nodsh\"\nremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n# unmount and cleanup the Lustre filesystem\nMMP_RESTORE_MOUNT=false\nif is_mounted $MOUNT || is_mounted $MOUNT2; then\n\tcleanupall\n\tMMP_RESTORE_MOUNT=true\nfi\n\nSAVED_FAIL_ON_ERROR=$FAIL_ON_ERROR\nFAIL_ON_ERROR=false\n\n# Get the failover facet.\nget_failover_facet() {\n    local facet=$1\n    local failover_facet=${facet}failover\n\n    local host=$(facet_host $facet)\n    local failover_host=$(facet_host $failover_facet)\n\n    [ -z \"$failover_host\" -o \"$host\" = \"$failover_host\" ] && \\\n        failover_facet=$facet\n\n    echo $failover_facet\n}\n\n# Initiate the variables for Lustre servers and targets.\ninit_vars() {\n    MMP_MDS=${MMP_MDS:-$SINGLEMDS}\n    MMP_MDS_FAILOVER=$(get_failover_facet $MMP_MDS)\n\n    local mds_num=$(echo $MMP_MDS | tr -d \"mds\")\n    MMP_MDSDEV=$(mdsdevname $mds_num)\n\n    MMP_OSS=${MMP_OSS:-ost1}\n    MMP_OSS_FAILOVER=$(get_failover_facet $MMP_OSS)\n\n    local oss_num=$(echo $MMP_OSS | tr -d \"ost\")\n    MMP_OSTDEV=$(ostdevname $oss_num)\n}\n\n# Stop the MDS and OSS services on the primary or failover servers.\nstop_services() {\n    local flavor=$1\n    shift\n    local opts=\"$@\"\n    local mds_facet\n    local oss_facet\n\n    if [ \"$flavor\" = \"failover\" ]; then\n        mds_facet=$MMP_MDS_FAILOVER\n        oss_facet=$MMP_OSS_FAILOVER\n    else\n        mds_facet=$MMP_MDS\n        oss_facet=$MMP_OSS\n    fi\n\n    stop $mds_facet $opts || return ${PIPESTATUS[0]}\n    stop $oss_facet $opts || return ${PIPESTATUS[0]}\n}\n\n# Enable the MMP feature.\nenable_mmp() {\n    local facet=$1\n    local device=$2\n\n    do_facet $facet \"$TUNE2FS -O mmp $device\"\n    return ${PIPESTATUS[0]}\n}\n\n# Disable the MMP feature.\ndisable_mmp() {\n    local facet=$1\n    local device=$2\n\n    do_facet $facet \"$TUNE2FS -O ^mmp $device\"\n    return ${PIPESTATUS[0]}\n}\n\n# Set the MMP block to 'fsck' state\nmark_mmp_block() {\n    local facet=$1\n    local device=$2\n\n    do_facet $facet \"$LUSTRE/tests/mmp_mark.sh $device\"\n    return ${PIPESTATUS[0]}\n}\n\n# Reset the MMP block (if any) back to the clean state.\nreset_mmp_block() {\n    local facet=$1\n    local device=$2\n\n    do_facet $facet \"$TUNE2FS -f -E clear-mmp $device\"\n    return ${PIPESTATUS[0]}\n}\n\n# Check whether the MMP feature is enabled or not.\nmmp_is_enabled() {\n    local facet=$1\n    local device=$2\n\n    do_facet $facet \"$DUMPE2FS -h $device | grep mmp\"\n    return ${PIPESTATUS[0]}\n}\n\n# Get MMP update interval (in seconds) from the Lustre server target.\nget_mmp_update_interval() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal interval\n\n\tinterval=$(do_facet $facet \\\n\t\t   \"$DEBUGFS -c -R dump_mmp $device 2>$TMP/mmp.debugfs.msg\" |\n\t\t   awk 'tolower($0) ~ /update.interval/ { print $NF }')\n\t[ -z \"$interval\" ] && interval=5 &&\n\t\tdo_facet $facet cat $TMP/mmp.debugfs.msg &&\n\t\techo \"$facet:$device: assume update interval=$interval\" 1>&2 ||\n\t\techo \"$facet:$device: got actual update interval=$interval\" 1>&2\n\n\techo $interval\n}\n\n# Get MMP check interval (in seconds) from the Lustre server target.\nget_mmp_check_interval() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal interval\n\n\tinterval=$(do_facet $facet \\\n\t\t   \"$DEBUGFS -c -R dump_mmp $device 2>$TMP/mmp.debugfs.msg\" |\n\t\t   awk 'tolower($0) ~ /check.interval/ { print $NF }')\n\t[ -z \"$interval\" ] && interval=5 &&\n\t\tdo_facet $facet cat $TMP/mmp.debugfs.msg &&\n\t\techo \"$facet:$device: assume check interval=$interval\" 1>&2 ||\n\t\techo \"$facet:$device: got actual check interval=$interval\" 1>&2\n\n\techo $interval\n}\n\n# Adjust the MMP update interval (in seconds) on the Lustre server target.\n# Specifying an interval of 0 means to use the default interval.\nset_mmp_update_interval() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal interval=${3:-0}\n\n\tdo_facet $facet \"$TUNE2FS -E mmp_update_interval=$interval $device\"\n\treturn ${PIPESTATUS[0]}\n}\n\nI_ENABLED_MDS=0\nI_ENABLED_OSS=0\n\n# Enable the MMP feature on the Lustre server targets.\nmmp_init() {\n\tinit_vars\n\n\tif [ $(facet_fstype $MMP_MDS) != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\tif [ $(facet_fstype $MMP_OSS) != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\tmmp_is_enabled $MMP_MDS $MMP_MDSDEV ||\n\t{\n\t\tlog \"MMP is not enabled on MDS, enabling it manually...\"\n\t\tenable_mmp $MMP_MDS $MMP_MDSDEV ||\n\t\t\terror \"failed to enable MMP on $MMP_MDSDEV on $MMP_MDS\"\n\t\tI_ENABLED_MDS=1\n\t}\n\n\tmmp_is_enabled $MMP_OSS $MMP_OSTDEV ||\n\t{\n\t\tlog \"MMP is not enabled on OSS, enabling it manually...\"\n\t\tenable_mmp $MMP_OSS $MMP_OSTDEV ||\n\t\t\terror \"failed to enable MMP on $MMP_OSTDEV on $MMP_OSS\"\n\t\tI_ENABLED_OSS=1\n\t}\n\n\t# check whether the MMP feature is enabled or not\n\tmmp_is_enabled $MMP_MDS $MMP_MDSDEV ||\n\t\terror \"MMP was not enabled on $MMP_MDSDEV on $MMP_MDS\"\n\n\tmmp_is_enabled $MMP_OSS $MMP_OSTDEV ||\n\t\terror \"MMP was not enabled on $MMP_OSTDEV on $MMP_OSS\"\n}\n\n# Disable the MMP feature on the Lustre server targets\nmmp_fini() {\n\n\tif [ $I_ENABLED_MDS -eq 1 ]; then\n\t\tlog \"Disabling MMP on $MMP_MDSDEV on $MMP_MDS manually...\"\n\t\tdisable_mmp $MMP_MDS $MMP_MDSDEV ||\n\t\t\terror \"failed to disable MMP on $MMP_MDSDEV on $MMP_MDS\"\n\t\tmmp_is_enabled $MMP_MDS $MMP_MDSDEV &&\n\t\t\terror \"MMP was not disabled on $MMP_MDSDEV on $MMP_MDS\"\n\tfi\n\n\tif [ $I_ENABLED_OSS -eq 1 ]; then\n\t\tlog \"Disabling MMP on $MMP_OSTDEV on $MMP_OSS manually...\"\n\t\tdisable_mmp $MMP_OSS $MMP_OSTDEV ||\n\t\t\terror \"failed to disable MMP on $MMP_OSTDEV on $MMP_OSS\"\n\t\tmmp_is_enabled $MMP_OSS $MMP_OSTDEV &&\n\t\t\terror \"MMP was not disabled on $MMP_OSTDEV on $MMP_OSS\"\n\tfi\n\n\treturn 0\n}\n\n# Mount the shared target on the failover server after some interval it's\n# mounted on the primary server.\nmount_after_interval_sub() {\n    local interval=$1\n    shift\n    local device=$1\n    shift\n    local facet=$1\n    shift\n    local opts=\"$@\"\n    local failover_facet=$(get_failover_facet $facet)\n\n    local mount_pid\n    local first_mount_rc=0\n    local second_mount_rc=0\n\n    log \"Mounting $device on $facet...\"\n    start $facet $device $opts &\n    mount_pid=$!\n\n    if [ $interval -ne 0 ]; then\n        log \"sleep $interval...\"\n        sleep $interval\n    fi\n\n    log \"Mounting $device on $failover_facet...\"\n    start $failover_facet $device $opts\n    second_mount_rc=${PIPESTATUS[0]}\n\n    wait $mount_pid\n    first_mount_rc=${PIPESTATUS[0]}\n\n    if [ $second_mount_rc -eq 0 -a $first_mount_rc -eq 0 ]; then\n        error_noexit \"one mount delayed by mmp interval $interval should fail\"\n        stop $facet || return ${PIPESTATUS[0]}\n        [ \"$failover_facet\" != \"$facet\" ] && stop $failover_facet || \\\n            return ${PIPESTATUS[0]}\n        return 1\n    elif [ $second_mount_rc -ne 0 -a $first_mount_rc -ne 0 ]; then\n\terror_noexit \"mount failure on failover pair $facet,$failover_facet\"\n        return $first_mount_rc\n    fi\n\n    return 0\n}\n\nmount_after_interval() {\n    local mdt_interval=$1\n    local ost_interval=$2\n    local rc=0\n\n    mount_after_interval_sub $mdt_interval $MMP_MDSDEV $MMP_MDS \\\n        $MDS_MOUNT_OPTS || return ${PIPESTATUS[0]}\n\n    echo\n    mount_after_interval_sub $ost_interval $MMP_OSTDEV $MMP_OSS $OST_MOUNT_OPTS\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        stop $MMP_MDS\n        return $rc\n    fi\n\n    return 0\n}\n\n# Mount the shared target on the failover server\n# during unmounting it on the primary server.\nmount_during_unmount() {\n\tlocal device=$1\n\tshift\n\tlocal facet=$1\n\tshift\n\tlocal mnt_opts=\"$@\"\n\tlocal failover_facet=$(get_failover_facet $facet)\n\n\tlocal unmount_pid\n\tlocal unmount_rc=0\n\tlocal mount_rc=0\n\n\tlog \"Mounting $device on $facet...\"\n\tstart $facet $device $mnt_opts || return ${PIPESTATUS[0]}\n\n\tlog \"Unmounting $device on $facet...\"\n\tstop $facet &\n\tunmount_pid=$!\n\n\tlog \"Mounting $device on $failover_facet...\"\n\tstart $failover_facet $device $mnt_opts\n\tmount_rc=${PIPESTATUS[0]}\n\n\t# check whether the first filesystem is still mounted\n\tlocal mntpt=$(facet_mntpt $facet)\n\tlocal mounted=$(do_facet $facet \"grep -w $mntpt /proc/mounts\")\n\n\twait $unmount_pid\n\tunmount_rc=${PIPESTATUS[0]}\n\n\tif [ $mount_rc -eq 0 ]; then\n\t\tstop $failover_facet || return ${PIPESTATUS[0]}\n\n\t\tif [ -n \"$mounted\" ]; then\n\t\t\terror_noexit \"mount during unmount of first filesystem worked\"\n\t\t\treturn 1\n\t\tfi\n\tfi\n\n\tif [ $unmount_rc -ne 0 ]; then\n\t\terror_noexit \"unmount the $device on $facet should succeed\"\n\t\treturn $unmount_rc\n\tfi\n\n\treturn 0\n}\n\n# Mount the shared target on the failover server\n# after clean unmounting it on the primary server.\nmount_after_unmount() {\n    local device=$1\n    shift\n    local facet=$1\n    shift\n    local mnt_opts=\"$@\"\n    local failover_facet=$(get_failover_facet $facet)\n\n    log \"Mounting $device on $facet...\"\n    start $facet $device $mnt_opts || return ${PIPESTATUS[0]}\n\n    log \"Unmounting $device on $facet...\"\n    stop $facet || return ${PIPESTATUS[0]}\n\n    log \"Mounting $device on $failover_facet...\"\n    start $failover_facet $device $mnt_opts || return ${PIPESTATUS[0]}\n\n    return 0\n}\n\n# Mount the shared target on the failover server after rebooting\n# the primary server.\nmount_after_reboot() {\n    local device=$1\n    shift\n    local facet=$1\n    shift\n    local mnt_opts=\"$@\"\n    local failover_facet=$(get_failover_facet $facet)\n    local rc=0\n\n    log \"Mounting $device on $facet...\"\n    start $facet $device $mnt_opts || return ${PIPESTATUS[0]}\n\n    if [ \"$FAILURE_MODE\" = \"HARD\" ]; then\n        shutdown_facet $facet\n        reboot_facet $facet\n        wait_for_facet $facet\n    else\n        replay_barrier_nodf $facet\n    fi\n\n    log \"Mounting $device on $failover_facet...\"\n    start $failover_facet $device $mnt_opts\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        error_noexit \"mount $device on $failover_facet should succeed\"\n        stop $facet || return ${PIPESTATUS[0]}\n        return $rc\n    fi\n\n    return 0\n}\n\n# Run e2fsck on the Lustre server target.\nrun_e2fsck() {\n\tlocal facet=$1\n\tshift\n\tlocal device=$1\n\tshift\n\tlocal opts=\"$@\"\n\n\techo \"Running e2fsck on the device $device on $facet...\"\n\tdo_facet $facet \"$E2FSCK $opts $device\"\n\treturn ${PIPESTATUS[0]}\n}\n\n# Check whether there are failover pairs for MDS and OSS servers.\ncheck_failover_pair() {\n\t[ \"$MMP_MDS\" = \"$MMP_MDS_FAILOVER\" -o \"$MMP_OSS\" = \"$MMP_OSS_FAILOVER\" ] &&\n\t\tskip_env \"failover pair is needed\"\n\treturn 0\n}\n\nmmp_init\n\n# Test 1 - two mounts at the same time.\ntest_1() {\n\tcheck_failover_pair\n\n\tmount_after_interval 0 0 || return ${PIPESTATUS[0]}\n\tstop_services primary || return ${PIPESTATUS[0]}\n\tstop_services failover || return ${PIPESTATUS[0]}\n}\nrun_test 1 \"two mounts at the same time\"\n\n# Test 2 - one mount delayed by mmp update interval.\ntest_2() {\n\tcheck_failover_pair\n\n\tlocal mdt_interval=$(get_mmp_update_interval $MMP_MDS $MMP_MDSDEV)\n\tlocal ost_interval=$(get_mmp_update_interval $MMP_OSS $MMP_OSTDEV)\n\n\tmount_after_interval $mdt_interval $ost_interval ||\n\t\treturn ${PIPESTATUS[0]}\n\tstop_services primary || return ${PIPESTATUS[0]}\n}\nrun_test 2 \"one mount delayed by mmp update interval\"\n\n# Test 3 - one mount delayed by 2x mmp check interval.\ntest_3() {\n\tcheck_failover_pair\n\n\tlocal mdt_interval=$(get_mmp_check_interval $MMP_MDS $MMP_MDSDEV)\n\tlocal ost_interval=$(get_mmp_check_interval $MMP_OSS $MMP_OSTDEV)\n\n\tmdt_interval=$((2 * $mdt_interval + 1))\n\tost_interval=$((2 * $ost_interval + 1))\n\n\tmount_after_interval $mdt_interval $ost_interval ||\n\t\treturn ${PIPESTATUS[0]}\n\tstop_services primary || return ${PIPESTATUS[0]}\n}\nrun_test 3 \"one mount delayed by 2x mmp check interval\"\n\n# Test 4 - one mount delayed by > 2x mmp check interval.\ntest_4() {\n\tcheck_failover_pair\n\n\tlocal mdt_interval=$(get_mmp_check_interval $MMP_MDS $MMP_MDSDEV)\n\tlocal ost_interval=$(get_mmp_check_interval $MMP_OSS $MMP_OSTDEV)\n\n\tmdt_interval=$((4 * $mdt_interval))\n\tost_interval=$((4 * $ost_interval))\n\n\tmount_after_interval $mdt_interval $ost_interval ||\n\t\treturn ${PIPESTATUS[0]}\n\tstop_services primary || return ${PIPESTATUS[0]}\n}\nrun_test 4 \"one mount delayed by > 2x mmp check interval\"\n\n# Test 5 - mount during unmount of the first filesystem.\ntest_5() {\n\tlocal rc=0\n\tcheck_failover_pair\n\n\tmount_during_unmount $MMP_MDSDEV $MMP_MDS $MDS_MOUNT_OPTS ||\n\t\treturn ${PIPESTATUS[0]}\n\n\techo\n\tstart $MMP_MDS $MMP_MDSDEV $MDS_MOUNT_OPTS || return ${PIPESTATUS[0]}\n\tmount_during_unmount $MMP_OSTDEV $MMP_OSS $OST_MOUNT_OPTS\n\trc=${PIPESTATUS[0]}\n\tstop $MMP_MDS || return ${PIPESTATUS[0]}\n\treturn $rc\n}\nrun_test 5 \"mount during unmount of the first filesystem\"\n\n# Test 6 - mount after clean unmount.\ntest_6() {\n\tlocal rc=0\n\tcheck_failover_pair\n\n\tmount_after_unmount $MMP_MDSDEV $MMP_MDS $MDS_MOUNT_OPTS ||\n\t\treturn ${PIPESTATUS[0]}\n\n\techo\n\tmount_after_unmount $MMP_OSTDEV $MMP_OSS $OST_MOUNT_OPTS\n\trc=${PIPESTATUS[0]}\n\tif [ $rc -ne 0 ]; then\n\t\tstop $MMP_MDS_FAILOVER || return ${PIPESTATUS[0]}\n\t\treturn $rc\n\tfi\n\n\tstop_services failover || return ${PIPESTATUS[0]}\n}\nrun_test 6 \"mount after clean unmount\"\n\n# Test 7 - mount after reboot.\ntest_7() {\n\tlocal rc=0\n\tcheck_failover_pair\n\n\tmount_after_reboot $MMP_MDSDEV $MMP_MDS $MDS_MOUNT_OPTS ||\n\t\treturn ${PIPESTATUS[0]}\n\n\techo\n\tmount_after_reboot $MMP_OSTDEV $MMP_OSS $OST_MOUNT_OPTS\n\trc=${PIPESTATUS[0]}\n\tif [ $rc -ne 0 ]; then\n\t\tstop $MMP_MDS || return ${PIPESTATUS[0]}\n\t\tstop $MMP_MDS_FAILOVER || return ${PIPESTATUS[0]}\n\t\treturn $rc\n\tfi\n\n\tstop_services failover || return ${PIPESTATUS[0]}\n\tstop_services primary || return ${PIPESTATUS[0]}\n}\nrun_test 7 \"mount after reboot\"\n\n# Test 8 - mount during e2fsck (should never succeed).\ntest_8() {\n\tlocal e2fsck_pid\n\tlocal saved_interval\n\tlocal new_interval\n\n\t# After writing a new sequence number into the MMP block, e2fsck will\n\t# sleep at least (2 * new_interval + 1) seconds before it goes into\n\t# e2fsck passes.\n\tnew_interval=30\n\n\t# MDT\n\tsaved_interval=$(get_mmp_update_interval $MMP_MDS $MMP_MDSDEV)\n\tset_mmp_update_interval $MMP_MDS $MMP_MDSDEV $new_interval\n\n\trun_e2fsck $MMP_MDS $MMP_MDSDEV \"-fy\" &\n\te2fsck_pid=$!\n\tsleep 5\n\n\tif start $MMP_MDS_FAILOVER $MMP_MDSDEV $MDS_MOUNT_OPTS; then\n\t\terror_noexit \\\n\t\t\t\"mount $MMP_MDSDEV on $MMP_MDS_FAILOVER should fail\"\n\t\tstop $MMP_MDS_FAILOVER || return ${PIPESTATUS[0]}\n\t\tset_mmp_update_interval $MMP_MDS $MMP_MDSDEV $saved_interval\n\t\treturn 1\n\tfi\n\n\twait $e2fsck_pid\n\tset_mmp_update_interval $MMP_MDS $MMP_MDSDEV $saved_interval\n\n\t# OST\n\techo\n\tsaved_interval=$(get_mmp_update_interval $MMP_OSS $MMP_OSTDEV)\n\tset_mmp_update_interval $MMP_OSS $MMP_OSTDEV $new_interval\n\n\trun_e2fsck $MMP_OSS $MMP_OSTDEV \"-fy\" &\n\te2fsck_pid=$!\n\tsleep 5\n\n\tif start $MMP_OSS_FAILOVER $MMP_OSTDEV $OST_MOUNT_OPTS; then\n\t\terror_noexit \\\n\t\t\t\"mount $MMP_OSTDEV on $MMP_OSS_FAILOVER should fail\"\n\t\tstop $MMP_OSS_FAILOVER || return ${PIPESTATUS[0]}\n\t\tset_mmp_update_interval $MMP_OSS $MMP_OSTDEV $saved_interval\n\t\treturn 2\n\tfi\n\n\twait $e2fsck_pid\n\tset_mmp_update_interval $MMP_OSS $MMP_OSTDEV $saved_interval\n\treturn 0\n}\nrun_test 8 \"mount during e2fsck\"\n\n# Test 9 - mount after aborted e2fsck (should never succeed).\ntest_9() {\n    start $MMP_MDS $MMP_MDSDEV $MDS_MOUNT_OPTS || return ${PIPESTATUS[0]}\n    if ! start $MMP_OSS $MMP_OSTDEV $OST_MOUNT_OPTS; then\n        local rc=${PIPESTATUS[0]}\n        stop $MMP_MDS || return ${PIPESTATUS[0]}\n        return $rc\n    fi\n    stop_services primary || return ${PIPESTATUS[0]}\n\n    mark_mmp_block $MMP_MDS $MMP_MDSDEV || return ${PIPESTATUS[0]}\n\n    log \"Mounting $MMP_MDSDEV on $MMP_MDS...\"\n    if start $MMP_MDS $MMP_MDSDEV $MDS_MOUNT_OPTS; then\n        error_noexit \"mount $MMP_MDSDEV on $MMP_MDS should fail\"\n        stop $MMP_MDS || return ${PIPESTATUS[0]}\n        return 1\n    fi\n\n    reset_mmp_block $MMP_MDS $MMP_MDSDEV || return ${PIPESTATUS[0]}\n\n    mark_mmp_block $MMP_OSS $MMP_OSTDEV || return ${PIPESTATUS[0]}\n\n    log \"Mounting $MMP_OSTDEV on $MMP_OSS...\"\n    if start $MMP_OSS $MMP_OSTDEV $OST_MOUNT_OPTS; then\n        error_noexit \"mount $MMP_OSTDEV on $MMP_OSS should fail\"\n        stop $MMP_OSS || return ${PIPESTATUS[0]}\n        return 2\n    fi\n\n    reset_mmp_block $MMP_OSS $MMP_OSTDEV || return ${PIPESTATUS[0]}\n    return 0\n}\nrun_test 9 \"mount after aborted e2fsck\"\n\n# Test 10 - e2fsck with mounted filesystem.\ntest_10() {\n    local rc=0\n\n    log \"Mounting $MMP_MDSDEV on $MMP_MDS...\"\n    start $MMP_MDS $MMP_MDSDEV $MDS_MOUNT_OPTS || return ${PIPESTATUS[0]}\n\n    run_e2fsck $MMP_MDS_FAILOVER $MMP_MDSDEV \"-fn\"\n    rc=${PIPESTATUS[0]}\n\n    # e2fsck is called with -n option (Open the filesystem read-only), so\n    # 0 (No errors) and 4 (File system errors left uncorrected) are the only\n    # acceptable exit codes in this case\n    if [ $rc -ne 0 ] && [ $rc -ne 4 ]; then\n        error_noexit \"e2fsck $MMP_MDSDEV on $MMP_MDS_FAILOVER returned $rc\"\n        stop $MMP_MDS || return ${PIPESTATUS[0]}\n        return $rc\n    fi\n\n    log \"Mounting $MMP_OSTDEV on $MMP_OSS...\"\n    start $MMP_OSS $MMP_OSTDEV $OST_MOUNT_OPTS\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        stop $MMP_MDS || return ${PIPESTATUS[0]}\n        return $rc\n    fi\n\n    run_e2fsck $MMP_OSS_FAILOVER $MMP_OSTDEV \"-fn\"\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ] && [ $rc -ne 4 ]; then\n        error_noexit \"e2fsck $MMP_OSTDEV on $MMP_OSS_FAILOVER returned $rc\"\n    fi\n\n    CLEANUP_DM_DEV=true stop_services primary || return ${PIPESTATUS[0]}\n    return 0\n}\nrun_test 10 \"e2fsck with mounted filesystem\"\n\nmmp_fini\nFAIL_ON_ERROR=$SAVED_FAIL_ON_ERROR\n\ncomplete $SECONDS\n$MMP_RESTORE_MOUNT && setupall\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 676}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# this will cause debugfs to create the /tmp/debugfs.mark file once it has\n# passed the MMP startup, then continue reading input until it is killed\nMARKFILE=$(mktemp)\nDEBUGFS=${DEBUGFS:-debugfs}\nDEVICE=$1\n\nrm -f $MARKFILE\necho \"$DEBUGFS -w $DEVICE\"\n{ echo \"dump_inode <2> $MARKFILE\"; cat /dev/zero; } | $DEBUGFS -w $DEVICE &\ndebugfspid=$!\nwhile [ ! -e $MARKFILE ]; do\n        sleep 1\ndone\nrm -f $MARKFILE\nkill -9 $debugfspid\n", "num_lines": 17}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\nset -e\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\nnobjhi=${nobjhi:-1}\nthrhi=${thrhi:-16}\nsize=${size:-1024}\n\n# the summary file a bit smaller than OSTSIZE\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n[ \"$SLOW\" = no ] && { nobjhi=1; thrhi=4; }\nthrlo=${thrlo:-$(( thrhi / 2))}\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$OBDFILTER_SURVEY_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nOBDSURVEY=${OBDSURVEY:-$(which obdfilter-survey)}\n\nbuild_test_filter\ncheck_and_setup_lustre\n\n# FIXME: the summary file a bit smaller than OSTSIZE, add estimation\nminsize=$(min_ost_size)\nif [ $(( size * 1024 )) -ge $minsize  ]; then\n    size=$((minsize * 10 / 1024 / 12 ))\n    echo min kbytesavail: $minsize using size=${size} MBytes per obd instance\nfi\n\nget_targets () {\n\tlocal targets\n\tlocal target\n\tlocal dev\n\tlocal nid\n\tlocal osc\n\n\tfor osc in $($LCTL get_param -N osc.${FSNAME}-*osc-*); do\n\t\tnid=$($LCTL get_param $osc.import |\n\t\t\tawk '/current_connection:/ {sub(/@.*/,\"\"); print $2}')\n\t\tdev=$(echo $osc | sed -e 's/^osc\\.//' -e 's/-osc.*//')\n\t\ttarget=$dev\n\n\t\t# For local disk obdfilter-survey requires target devs w/o nid.\n\t\t# obdfilter-survey :\n\t\t# case 1 (local disk):\n\t\t#    $ nobjhi=2 thrhi=2 size=1024\n\t\t#      targets=\"$nid:$FSNAME-OST0000 $nid:$FSNAME-OST0001 ...\"\n\t\t#                 sh obdfilter-survey\n\t\tlocal_node && [ \"$1\" == \"disk\" ] || target=$nid:$target\n\t\ttargets=\"$targets $target\"\n\tdone\n\techo $targets\n}\n\nobdflter_survey_targets () {\n\tlocal case=$1\n\tlocal targets\n\n\tcase $case in\n\t\tdisk)    targets=$(get_targets $case);;\n\t\tnetdisk) targets=$(get_targets $case);;\n\t\tnetwork) targets=$(host_nids_address $(comma_list $(osts_nodes)) $NETTYPE);;\n\t\t*) error \"unknown obdflter-survey case!\" ;;\n\tesac\n\techo $targets\n}\n\nobdflter_survey_run () {\n\tlocal case=$1\n\n\trm -f ${TMP}/obdfilter_survey*\n\n\tlocal targets=$(obdflter_survey_targets $case)\n\tlocal cmd=\"NETTYPE=$NETTYPE thrlo=$thrlo nobjhi=$nobjhi thrhi=$thrhi size=$size case=$case rslt_loc=${TMP} targets=\\\"$targets\\\" $OBDSURVEY\"\n\techo + $cmd\n\teval $cmd\n\tlocal rc=$?\n\n\tcat ${TMP}/obdfilter_survey*\n\t[ $rc = 0 ] || error \"$OBDSURVEY failed: $rc\"\n}\n\ntest_1a () {\n\tobdflter_survey_run disk\n}\nrun_test 1a \"Object Storage Targets survey\"\n\ntest_1b () {\n\tlocal param_file=$TMP/$tfile-params\n\n\tdo_nodesv $(comma_list $(osts_nodes)) \\\n\t\t$LCTL get_param obdfilter.${FSNAME}-*.sync_journal\n\tsave_lustre_params $(get_facets OST) \\\n\t\t\"obdfilter.${FSNAME}-*.sync_journal\" > $param_file\n\tdo_nodesv $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param obdfilter.${FSNAME}-*.sync_journal=0\n\n\tlocal stime=$(date +%s)\n\tthrlo=4 nobjhi=1 thrhi=4 obdflter_survey_run disk\n\tlocal etime=$(date +%s)\n\t# run time of obd survey\n\tlocal rtime=$((etime - stime))\n\n\techo \"obd survey finished in $rtime seconds\"\n\trestore_lustre_params < $param_file\n\n\trm -f $param_file\n}\nrun_test 1b \"Object Storage Targets survey, async journal\"\n\ntest_1c () {\n\tnobjlo=1 nobjhi=1 thrlo=32 thrhi=32 rszlo=1024 rszhi=1024 size=8192\\\n\tobdflter_survey_run disk\n}\nrun_test 1c \"Object Storage Targets survey, big batch\"\n\ntest_2a () {\n\tobdflter_survey_run netdisk\n}\nrun_test 2a \"Stripe F/S over the Network\"\n\ntest_2b () {\n\tlocal param_file=$TMP/$tfile-params\n\n\tdo_nodesv $(comma_list $(osts_nodes)) \\\n\t\t$LCTL get_param obdfilter.${FSNAME}-*.sync_journal\n\tsave_lustre_params $(get_facets OST) \\\n\t\t\"obdfilter.${FSNAME}-*.sync_journal\" > $param_file\n\tdo_nodesv $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param obdfilter.${FSNAME}-*.sync_journal=0\n\n\tlocal stime=$(date +%s)\n\tthrlo=4 nobjhi=1 thrhi=4 obdflter_survey_run netdisk\n\tlocal etime=$(date +%s)\n\tlocal rtime=$((etime - stime))\n\n\techo \"obd survey finished in $rtime seconds\"\n\trestore_lustre_params < $param_file\n\n\trm -f $param_file\n}\nrun_test 2b \"Stripe F/S over the Network, async journal\"\n\n\n# README.obdfilter-survey: In network test only automated run is supported.\ntest_3a () {\n\t# obdfilter-survey Prerequisite:\n\t#    For \"network\" case  you need to have all\n\t#    modules (those llmount.sh loads) loaded in kernel. And the\n\t#    'lctl dl' output must be blank.\n\t# Skipping test for CLIENTONLY mode because of\n\t# cleanupall()->stopall() does not cleanup the servers on this mode.\n\t[ \"$CLIENTONLY\" ] && skip \"CLIENTONLY mode\"\n\n\tremote_servers || skip \"Local servers\"\n\n\tcleanupall\n\n\tobdflter_survey_run network\n\n\tsetupall\n}\nrun_test 3a \"Network survey\"\n\ncomplete $SECONDS\ncleanup_echo_devs\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 175}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n#set -vx\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\n. ${CONFIG:=$LUSTRE/tests/cfg/${NAME}.sh}\n\nexport PATH=`dirname $0`/../utils:$PATH\nLFS=${LFS:-lfs}\nLCTL=${LCTL:-lctl}\nMOUNT=${MOUNT:-$1}\nMOUNT=${MOUNT:-/mnt/lustre}\nOOS=$MOUNT/oosfile\nTMP=${TMP:-/tmp}\nLOG=$TMP/$(basename $0 .sh).log\n\nSUCCESS=1\n\nrm -f $OOS $LOG\n\nsync; sleep 1; sync\t# to ensure we get up-to-date statfs info\n\n#$LCTL set_param -n debug=-1\n#$LCTL set_param -n subsystem_debug=0x40a8\n\n#$LCTL clear\n#$LCTL debug_daemon start /r/tmp/debug 1024\n\nSTRIPECOUNT=`$LCTL get_param -n lov.*.activeobd | head -n 1`\nORIGFREE=`$LCTL get_param -n llite.*.kbytesavail | head -n 1`\nMAXFREE=${MAXFREE:-$((400000 * $STRIPECOUNT))}\necho STRIPECOUNT=$STRIPECOUNT ORIGFREE=$ORIGFREE MAXFREE=$MAXFREE\nif [ $ORIGFREE -gt $MAXFREE ]; then\n\tskip \"$0: ${ORIGFREE}kB free gt MAXFREE ${MAXFREE}kB, increase $MAXFREE (or reduce test fs size) to proceed\"\n\texit 0\nfi\n\nexport LANG=C LC_LANG=C # for \"No space left on device\" message\n\n[ -f $LOG ] && error \"log file wasn't removed?\"\n\necho BEFORE dd started\noos_full || true\n\n# make sure we stripe over all OSTs to avoid OOS on only a subset of OSTs\n$LFS setstripe $OOS -c $STRIPECOUNT\n# add 20% of margin since the metadata overhead estimated in bavail might be\n# too aggressive and we might be able to write more than reported initially\n#\u00c2\u00a0by statfs.\necho dd size $((ORIGFREE * 120 / 100))kB\nif dd if=/dev/zero of=$OOS count=$((ORIGFREE * 120 / 100)) bs=1k 2> $LOG; then\n\techo \"ERROR: dd did not fail\"\n\tSUCCESS=0\nfi\n\n[ ! -s \"$LOG\" ] && error \"LOG file is empty!\"\n\nif [ \"`grep -c 'No space left on device' $LOG`\" -ne 1 ]; then\n\techo \"ERROR: dd not return ENOSPC\"\n\tsed \"s/^/LOG: /\" $LOG\n\tSUCCESS=0\nfi\n\n# flush cache to OST(s) so avail numbers are correct\nsync; sleep 1 ; sync\n\necho AFTER dd\nif ! oos_full; then\n\techo \"no OSTs are close to full\"\n\tSUCCESS=0\nfi\n\nRECORDSOUT=`grep \"records out\" $LOG | cut -d + -f1`\nFILESIZE=`ls -l $OOS | awk '{ print $5 }'`\nif [ -z \"$RECORDSOUT\" ]; then\n\techo \"ERROR: no blocks written by dd?\"\n\tsed \"s/^/LOG: /\" $LOG\n\tSUCCESS=0\nelif [ \"$RECORDSOUT\" -ne $((FILESIZE / 1024)) ]; then\n\techo \"ERROR: blocks written by dd not equal to the size of file\"\n\tSUCCESS=0\nfi\n\n#$LCTL debug_daemon stop\n\n[ $SUCCESS != 0 ] && echo LOG file && sed \"s/^/LOG: /\" $LOG\nrm -f $OOS\n\nsync; sleep 3; sync\n\nwait_delete_completed 300\n\nif [ $SUCCESS -eq 1 ]; then\n\techo \"Success!\"\n\trm -f $LOG\nelse\n\texit 1\nfi\n", "num_lines": 101}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\n. ${CONFIG:=$LUSTRE/tests/cfg/${NAME}.sh}\n\nexport PATH=$LUSTRE/utils:$PATH\nLFS=${LFS:-lfs}\nLCTL=${LCTL:-lctl}\nMOUNT=${MOUNT:-$1}\nMOUNT=${MOUNT:-/mnt/lustre}\nMOUNT2=${MOUNT2:-$2}\nMOUNT2=${MOUNT2:-${MOUNT}2}\nOOS=$MOUNT/oosfile\nOOS2=$MOUNT2/oosfile2\nTMP=${TMP:-/tmp}\nLOG=$TMP/$(basename $0 .sh).log\nLOG2=${LOG}2\n\nSUCCESS=1\n\nrm -f $OOS $OOS2 $LOG $LOG2\n\nsync; sleep 1; sync\t# to ensure we get up-to-date statfs info\n\nSTRIPECOUNT=`$LCTL get_param -n lov.*.activeobd | head -n 1`\nORIGFREE=`$LCTL get_param -n llite.*.kbytesavail | head -n 1`\nMAXFREE=${MAXFREE:-$((400000 * $STRIPECOUNT))}\necho STRIPECOUNT=$STRIPECOUNT ORIGFREE=$ORIGFREE MAXFREE=$MAXFREE\nif [ $ORIGFREE -gt $MAXFREE ]; then\n\tskip \"$0: ${ORIGFREE}kB free gt MAXFREE ${MAXFREE}kB, increase $MAXFREE (or reduce test fs size) to proceed\"\n\texit 0\nfi\n\nexport LANG=C LC_LANG=C # for \"No space left on device\" message\n\n# make sure we stripe over all OSTs to avoid OOS on only a subset of OSTs\n$LFS setstripe $OOS -c $STRIPECOUNT\n$LFS setstripe $OOS2 -c $STRIPECOUNT\ndd if=/dev/zero of=$OOS count=$((3 * $ORIGFREE / 4 + 100)) bs=1k 2>> $LOG &\nDDPID=$!\nif dd if=/dev/zero of=$OOS2 count=$((3*$ORIGFREE/4 + 100)) bs=1k 2>> $LOG2; then\n\techo \"ERROR: dd2 did not fail\"\n\tSUCCESS=0\nfi\nif wait $DDPID; then\n\techo \"ERROR: dd did not fail\"\n\tSUCCESS=0\nfi\n\n[ ! -s \"$LOG\" ] && error \"LOG file is empty!\"\n[ ! -s \"$LOG2\" ] && error \"LOG2 file is empty!\"\n\nif [ \"`cat $LOG $LOG2 | grep -c 'No space left on device'`\" -ne 2 ]; then\n\techo \"ERROR: dd not return ENOSPC\"\n\tSUCCESS=0\nfi\n\n# flush cache to OST(s) so avail numbers are correct\nsync; sleep 1 ; sync\n\nif ! oos_full; then\n\techo \"no OSTs are close to full\"\n\tSUCCESS=0\nfi\n\nRECORDSOUT=$((`grep \"records out\" $LOG | cut -d+ -f 1` + \\\n              `grep \"records out\" $LOG2 | cut -d+ -f 1`))\n\nFILESIZE=$((`ls -l $OOS | awk '{print $5}'` + `ls -l $OOS2 | awk '{print $5}'`))\nif [ \"$RECORDSOUT\" -ne $(($FILESIZE / 1024)) ]; then\n        echo \"ERROR: blocks written by dd not equal to the size of file\"\n        SUCCESS=0\nfi\n\necho LOG LOG2 file\ncat $LOG $LOG2\n\nrm -f $OOS $OOS2\nsync; sleep 1; sync\n\nif [ $SUCCESS -eq 1 ]; then\n\techo \"Success!\"\n\trm -f $LOG $LOG2\nelse\n\texit 1\nfi\n", "num_lines": 90}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nONLY=${ONLY:-\"$*\"}\nORIG_PWD=${PWD}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$OST_POOLS_EXCEPT\"\n# bug number for skipped test: -\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\ncheck_and_setup_lustre\n\nif ! combined_mgs_mds; then\n\tdo_facet mgs \"mkdir -p $MOUNT\"\n\tzconf_mount $mgs_HOST $MOUNT $MOUNT_OPTS ||\n\t\terror \"unable to mount $MOUNT on the MGS\"\nfi\n\nDIR=${DIR:-$MOUNT}\nassert_DIR\n\nMAXFREE=${MAXFREE:-$((2000000 * OSTCOUNT))}\n\n# OST pools tests\nPOOL=testpool\nPOOL2=${POOL2:-${POOL}2}\nPOOL3=${POOL3:-${POOL}3}\nNON_EXISTANT_POOL=nonexistantpool\nNON_EXISTANT_FS=nonexistantfs\nINVALID_POOL=some_invalid_pool_name\nTGT_COUNT=$OSTCOUNT\nTGT_FIRST=$(printf %04x 0)\nTGT_MAX=$(printf %04x $((TGT_COUNT-1)))\nTGT_STEP=1\nTGT_LIST=$(seq 0x$TGT_FIRST $TGT_STEP 0x$TGT_MAX)\nTGT_LIST2=$(seq 0x$TGT_FIRST 2 0x$TGT_MAX)\n\nTGT_ALL=\"$FSNAME-OST[$TGT_FIRST-$TGT_MAX/1]\"\nTGT_HALF=\"$FSNAME-OST[$TGT_FIRST-$TGT_MAX/2]\"\n\nTGT_UUID=$(for i in $TGT_LIST; do printf \"$FSNAME-OST%04x_UUID \" $i; done)\nTGT_UUID2=$(for i in $TGT_LIST2; do printf \"$FSNAME-OST%04x_UUID \" $i; done)\n\ncreate_dir() {\n\tlocal dir=$1\n\tlocal pool=$2\n\tlocal count=${3:-\"-1\"}\n\tlocal idx=$4\n\n\tmkdir -p $dir\n\tif [[ -n $idx ]]; then\n\t\t$LFS setstripe -c $count -p $pool -i $idx $dir\n\telse\n\t\t$LFS setstripe -c $count -p $pool $dir\n\tfi\n\t[[ $? -eq 0 ]] || error \"$LFS setstripe -p $pool $dir failed\"\n\t[[ \"$($LFS getstripe --pool $dir)\" == \"$pool\" ]] ||\n\t\terror \"$dir not created in expected pool '$pool'\"\n}\n\ncreate_file() {\n\tlocal file=$1\n\tlocal pool=$2\n\tlocal count=${3:-\"-1\"}\n\tlocal index=${4:-\"-1\"}\n\trm -f $file\n\t$LFS setstripe -i $index -c $count -p $pool $file\n\t[[ $? -eq 0 ]] || error \"$LFS setstripe -p $pool $file failed\"\n\t[[ \"$($LFS getstripe --pool $file)\" == \"$pool\" ]] ||\n\t\terror \"$file not created in '$pool'\"\n}\n\nosts_in_pool() {\n\tlocal pool=$1\n\tlocal res\n\tfor i in $(list_pool $FSNAME.$pool |\n\t\tsed -e 's/_UUID$//;s/^.*-OST//'); do\n\t\tres=\"$res $(printf \"%d\" 0x$i)\"\n\tdone\n\techo $res\n}\n\ncheck_dir_in_pool() {\n\tlocal dir=$1\n\tlocal pool=$2\n\tlocal res=$($LFS getstripe --pool $dir)\n\n\t[ -n \"$res\" ] || error \"dir '$dir' not in any pool\"\n\n\t[ \"$res\" == \"$pool\" ] ||\n\t\terror \"dir '$dir' in pool '$res' instead of '$pool'\"\n}\n\ncheck_file_in_pool() {\n\tlocal file=\"$1\"\n\tlocal pool=$2\n\tlocal count=$3\n\tlocal osts=$(osts_in_pool $pool)\n\tlocal res=$($LFS getstripe --pool $file)\n\n\t[ -n \"$res\" ] || error \"file '$file' not in any pool\"\n\n\t[ \"$res\" == \"$pool\" ] ||\n\t\terror \"file '$file' in pool '$res' instead of '$pool'\"\n\n\tlocal osts=$(osts_in_pool $2)\n\tcheck_file_in_osts \"$file\" \"$osts\" $count\n}\n\ncheck_file_in_osts() {\n\tlocal file=$1\n\tlocal ost_list=${2:-$TGT_LIST}\n\tlocal count=$3\n\tlocal res=$($LFS getstripe $file | awk '/0x/ { print $1 }')\n\tlocal i\n\n\tfor i in $res; do\n\t\tfound=$(echo :$ost_list: | tr \" \" \":\" | grep :$i:)\n\t\tif [[ \"$found\" == \"\" ]]; then\n\t\t\techo \"ost list: $ost_list\"\n\t\t\techo \"striping: $res\"\n\t\t\t$LFS getstripe -v $file\n\t\t\terror \"$file not allocated from OSTs $ost_list.\"\n\t\tfi\n\tdone\n\n\tlocal ost_count=$($LFS getstripe -c $file)\n\t[[ -n \"$count\" ]] && [[ $ost_count -ne $count ]] &&\n\t\terror \"$file stripe count $count expected; got $ost_count\" &&\n\t\treturn 1\n\n}\n\ncheck_file_not_in_pool() {\n\tlocal file=$1\n\tlocal pool=$2\n\tlocal res=$($LFS getstripe --pool $file)\n\n\t[ \"$res\" != \"$pool\" ] || error \"File '$file' is in pool: $res\"\n}\n\ncheck_dir_not_in_pool() {\n\tlocal dir=$1\n\tlocal pool=$2\n\tlocal res=$($LFS getstripe --pool $dir)\n\n\t[ \"$res\" != \"$pool\" ] || error \"Dir '$dir' is in pool: $res\"\n}\n\ndrain_pool() {\n    pool=$1\n    wait_update $HOSTNAME \"lctl get_param -n lov.$FSNAME-*.pools.$pool\" \"\" ||\n        error \"Failed to remove targets from pool: $pool\"\n}\n\nadd_pool() {\n\tlocal pool=$1\n\tlocal osts=$2\n\tlocal tgt=\"${3}$(lctl get_param -n lov.$FSNAME-*.pools.$pool |\n\t\tsort -u | tr '\\n' ' ')\"\n\n\tdo_facet mgs lctl pool_add $FSNAME.$pool $osts\n\tlocal RC=$?\n\t[[ $RC -ne 0 ]] && return $RC\n\n\t# wait for OSTs to be added to the pool\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$FSNAME-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \\\n\t\t\t\"lctl get_param -n lod.$lodname.pools.$pool |\n\t\t\t\tsort -u | tr '\\n' ' ' \" \"$tgt\" >/dev/null ||\n\t\t\terror \"mds$mds_id:pool add failed $1; $2\"\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n lov.$FSNAME-*.pools.$pool |\n\t\tsort -u | tr '\\n' ' ' \" \"$tgt\" >/dev/null ||\n\t\terror \"pool_add failed: $1; $2\"\n\treturn $RC\n}\n\ncreate_pool_nofail() {\n\tcreate_pool $FSNAME.$1\n\t[[ $? -ne 0 ]] && error \"Pool creation of $1 failed\"\n\treturn 0\n}\n\ncreate_pool_fail() {\n\tcreate_pool $FSNAME.$1\n\t[[ $? -ne 0 ]] ||\n\t\terror \"Pool creation of $1 succeeded; should have failed\"\n\treturn 0\n}\n\nost_pools_init() {\n\tdestroy_test_pools\n}\n\n# Initialization\nremote_mds_nodsh && skip \"remote MDS with nodsh\"\nremote_ost_nodsh && skip \"remote OST with nodsh\"\nost_pools_init\n\n# Tests for new commands added\ntest_1a() {\n\tcreate_pool_nofail p\n\tdestroy_pool p\n}\nrun_test 1a \"Create a pool with a 1 character pool name\"\n\ntest_1b() {\n\tcreate_pool_nofail ${POOL}12\n\tdestroy_pool ${POOL}12\n}\nrun_test 1b \"Create a pool with a 10 char pool name\"\n\ntest_1c() {\n\tcreate_pool_nofail ${POOL}1234567\n\tdestroy_pool ${POOL}1234567\n}\nrun_test 1c \"Create a pool with a 15 char pool name\"\n\ntest_1d() {\n\tcreate_pool_fail ${POOL}12345678\n}\nrun_test 1d \"Create a pool with a 16 char pool name; should fail\"\n\ntest_1e() {\n\tlocal pool_name=\"$POOL\"\n\tfor ((i = 1; i <= 991; i++)); do pool_name=${pool_name}\"o\"; done\n\tcreate_pool_fail $pool_name\n}\nrun_test 1e \"Create a pool with a 1000 char pool name; should fail\"\n\ntest_1f() {\n\tcreate_pool .$POOL\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even though fs-name was missing\"\n}\nrun_test 1f \"pool_new should fail if fs-name is missing\"\n\ntest_1g() {\n\tcreate_pool $POOL\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even though fs-name was missing\"\n}\nrun_test 1g \"pool_new should fail if fs-name is missing\"\n\ntest_1h() {\n\tcreate_pool ${FSNAME}.\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even though pool name was missing\"\n}\nrun_test 1h \"pool_new should fail if poolname is missing\"\n\ntest_1i() {\n\tcreate_pool .\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even if pool/fs-name was missing\"\n}\nrun_test 1i \"pool_new should fail if poolname and fs-name are missing\"\n\ntest_1j() {\n\tdo_facet mgs lctl pool_new ${FSNAME},$POOL\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even if poolname format was wrong\"\n}\nrun_test 1j \"pool_new should fail if poolname format is wrong\"\n\ntest_1k() {\n\tdo_facet mgs lctl pool_new ${FSNAME}/$POOL\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even if poolname format was wrong\"\n}\nrun_test 1k \"pool_new should fail if poolname format is wrong\"\n\ntest_1m() {\n\tcreate_pool_nofail $POOL2\n\tcreate_pool ${FSNAME}.$POOL2\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_new did not fail even though $POOL2 existed\"\n\tdestroy_pool $POOL2\n}\nrun_test 1m \"pool_new did not fail even though $POOL2 existed\"\n\ntest_1n() {\n\tcreate_pool_nofail ${POOL}1234567\n\n\tadd_pool ${POOL}1234567 \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tcreate_dir $POOL_ROOT ${POOL}1234567\n\tdd if=/dev/zero of=$POOL_ROOT/file bs=1M count=100\n\tRC=$?; [[ $RC -eq 0 ]] ||\n\t\terror \"failed to write to $POOL_ROOT/file: $RC\"\n\tdo_facet mgs lctl pool_remove $FSNAME.${POOL}1234567 OST0000\n\tdrain_pool ${POOL}1234567\n\n\tdestroy_pool ${POOL}1234567\n}\nrun_test 1n \"Pool with a 15 char pool name works well\"\n\ntest_2a() {\n\tdestroy_pool $POOL\n\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $FSNAME-OST0000 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_add did not fail even though $POOL did not exist\"\n}\nrun_test 2a \"pool_add: non-existant pool $POOL\"\n\ntest_2b() {\n\tdo_facet mgs lctl pool_add $FSNAME.${POOL}1234567890 \\\n\t\t$FSNAME-OST0000 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_add did not fail even though pool name was invalid.\"\n}\nrun_test 2b \"pool_add: Invalid pool name\"\n\n# Testing various combinations of OST name list\ntest_2c() {\n\tlocal TGT\n\tlocal RC\n\n\tlctl get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tcreate_pool_nofail $POOL\n\n\t# 1. OST0000\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL OST0000\n\tRC=$?; [[ $RC -eq 0 ]] ||\n\t\terror \"pool_add failed. $FSNAME $POOL OST0000: $RC\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL OST0000\n\tdrain_pool $POOL\n\n\t# 2. $FSNAME-OST0000\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $FSNAME-OST0000\n\tRC=$?; [[ $RC -eq 0 ]] ||\n\t\terror \"pool_add failed. $FSNAME $POOL $FSNAME-OST0000: $RC\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $FSNAME-OST0000\n\tdrain_pool $POOL\n\n\t# 3. $FSNAME-OST0000_UUID\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $FSNAME-OST0000_UUID\n\tRC=$?; [[ $RC -eq 0 ]] ||\n\t\terror \"pool_add failed. $FSNAME $POOL $FSNAME-OST0000_UUID: $RC\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $FSNAME-OST0000_UUID\n\tdrain_pool $POOL\n\n\t# 4. $FSNAME-OST[0,1,2,3,]\n\tTGT=\"$FSNAME-OST[\"\n\tfor i in $TGT_LIST; do TGT=${TGT}$(printf \"%04x,\" $i); done\n\tTGT=\"${TGT}]\"\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT\n\t[[ $? -eq 0 ]] || error \"pool_add failed. $FSNAME.$POOL $TGT. $RC\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $TGT\n\tdrain_pool $POOL\n\n\t# 5. $FSNAME-OST[0-5/1]\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT_ALL\n\tRC=$?; [[ $RC -eq 0 ]] ||\n\t\terror \"pool_add failed. $FSNAME $POOL\" \"$TGT_ALL $RC\"\n\twait_update $HOSTNAME \"lctl get_param -n lov.$FSNAME-*.pools.$POOL |\n\t\tsort -u | tr '\\n' ' ' \" \"$TGT_UUID\" ||\n\t\t\terror \"Add to pool failed\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $TGT_ALL\n\tdrain_pool $POOL\n\n\tdestroy_pool $POOL\n}\nrun_test 2c \"pool_add: OST index combinations\"\n\ntest_2d() {\n\tlocal TGT\n\tlocal RC\n\n\tlctl get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tcreate_pool_nofail $POOL\n\n\tTGT=$(printf \"$FSNAME-OST%04x_UUID \" $OSTCOUNT)\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT\n\tRC=$?; [[ $RC -ne 0 ]] ||\n\t\terror \"pool_add succeeded for an OST ($TGT) that does not exist.\"\n\n\tdestroy_pool $POOL\n}\nrun_test 2d \"pool_add: OSTs that don't exist should be rejected\"\n\ntest_2e() {\n\tlocal TGT\n\tlocal RC\n\tlocal RESULT\n\n\t$LCTL get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tcreate_pool_nofail $POOL\n\n\tTGT=\"$FSNAME-OST0000_UUID\"\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT\n\twait_update_facet $SINGLEMDS \\\n\t\t\"lctl pool_list $FSNAME.$POOL | sed '1d'\" \"$TGT\" ||\n\t\terror \"Add $TGT to $FSNAME.$POOL failed\"\n\tRESULT=$(do_facet mgs \\\n\t\t\"LOCALE=C $LCTL pool_add $FSNAME.$POOL $TGT 2>&1\")\n\tRC=$?\n\techo $RESULT\n\n\t[[ $RC -ne 0 ]] ||\n\t\terror \"pool_add succeeded for an OST that was already in the pool.\"\n\n\t[[ $(grep \"already in pool\" <<< $RESULT) ]] ||\n\t\terror \"pool_add failed as expected but error message not as expected.\"\n\n\tdestroy_pool $POOL\n}\nrun_test 2e \"pool_add: OST already in a pool should be rejected\"\n\ntest_3a() {\n\tlctl get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tdo_facet mgs \\\n\t\tlctl pool_remove $FSNAME.$POOL $FSNAME-OST0000 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_remove did not fail even though pool did not exist.\"\n}\nrun_test 3a \"pool_remove: non-existant pool\"\n\ntest_3b() {\n\tdo_facet mgs \\\n\t\tlctl pool_remove ${NON_EXISTANT_FS}.$POOL OST0000 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_remove did not fail even though fsname did not exist.\"\n}\nrun_test 3b \"pool_remove: non-existant fsname\"\n\ntest_3c() {\n\tdo_facet mgs lctl pool_remove $FSNAME.p1234567891234567890 \\\n\t\t$FSNAME-OST0000 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_remove did not fail even though pool name was invalid.\"\n}\nrun_test 3c \"pool_remove: Invalid pool name\"\n\n# Testing various combinations of OST name list\ntest_3d() {\n\tlctl get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tcreate_pool_nofail $POOL\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL OST0000\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL OST0000\n\t[[ $? -eq 0 ]] || error \"pool_remove failed. $FSNAME $POOL OST0000\"\n\tdrain_pool $POOL\n\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $FSNAME-OST0000\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $FSNAME-OST0000\n\t[[ $? -eq 0 ]] || error \"pool_remove failed. $FSNAME $POOL $FSNAME-OST0000\"\n\tdrain_pool $POOL\n\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $FSNAME-OST0000_UUID\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $FSNAME-OST0000_UUID\n\t[[ $? -eq 0 ]] ||\n\t\terror \"pool_remove failed. $FSNAME $POOL $FSNAME-OST0000_UUID\"\n\tdrain_pool $POOL\n\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $TGT_ALL\n\t[[ $? -eq 0 ]] || error \"pool_remove failed. $FSNAME $POOL\" $TGT_ALL\n\tdrain_pool $POOL\n\n\tdestroy_pool $POOL\n}\nrun_test 3d \"pool_remove: OST index combinations\"\n\ntest_4a() {\n\tlctl get_param -n lov.$FSNAME-*.pools.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] || destroy_pool $POOL\n\n\tdo_facet mgs lctl pool_destroy $FSNAME.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_destroy did not fail even though pool did not exist.\"\n}\nrun_test 4a \"pool_destroy: non-existant pool\"\n\ntest_4b() {\n\tdo_facet mgs lctl pool_destroy ${NON_EXISTANT_FS}.$POOL 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_destroy did not fail even though filesystem did not exist.\"\n}\nrun_test 4b \"pool_destroy: non-existant fs-name\"\n\ntest_4c() {\n\tcreate_pool_nofail $POOL\n\tadd_pool $POOL \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\n\tdo_facet mgs lctl pool_destroy ${FSNAME}.$POOL\n\t[[ $? -ne 0 ]] || error \"pool_destroy succeeded with a non-empty pool.\"\n\tdestroy_pool $POOL\n}\nrun_test 4c \"pool_destroy: non-empty pool\"\n\nsub_test_5() {\n\tlocal LCMD=$1\n\n\t$LCMD pool_list 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_list did not fail even though fsname missing.\"\n\n\tdestroy_pool $POOL 2>/dev/null\n\tdestroy_pool $POOL2 2>/dev/null\n\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\t$LCMD pool_list $FSNAME\n\t[[ $? -eq 0 ]] || error \"pool_list $FSNAME failed.\"\n\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT_ALL\n\n\t$LCMD pool_list $FSNAME.$POOL\n\t[[ $? -eq 0 ]] || error \"pool_list $FSNAME.$POOL failed.\"\n\n\t$LCMD pool_list ${NON_EXISTANT_FS} 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_list did not fail for fsname $NON_EXISTANT_FS\"\n\n\t$LCMD pool_list ${FSNAME}.$NON_EXISTANT_POOL 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_list did not fail for pool $NON_EXISTANT_POOL\"\n\n\tif [[ ! $(grep $SINGLEMDS <<< $LCMD) ]]; then\n\t\techo $LCMD pool_list $DIR\n\t\t$LCMD pool_list $DIR\n\t\t[[ $? -eq 0 ]] || error \"pool_list failed for $DIR\"\n\n\t\tmkdir -p ${DIR}/d1\n\t\t$LCMD pool_list ${DIR}/d1\n\t\t[[ $? -eq 0 ]] || error \"pool_list failed for ${DIR}/d1\"\n\tfi\n\n\trm -rf ${DIR}nonexistant\n\t$LCMD pool_list ${DIR}nonexistant 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\t\terror \"pool_list did not fail for invalid mountpoint ${DIR}nonexistant\"\n\n\tdestroy_pool $POOL\n\tdestroy_pool $POOL2\n}\n\ntest_5a() {\n\t# Issue commands from client\n\tsub_test_5 $LFS\n}\nrun_test 5a \"lfs pool_list from client\"\n\ntest_5b() {\n\tsub_test_5 \"do_facet $SINGLEMDS lctl\"\n}\nrun_test 5b \"lctl pool_list from MDS\"\n\ntest_6() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal POOL_DIR=$POOL_ROOT/dir_tst\n\tlocal POOL_FILE=$POOL_ROOT/file_tst\n\n\tcreate_pool_nofail $POOL\n\n\tdo_facet $SINGLEMDS lctl pool_list $FSNAME\n\t[[ $? -eq 0 ]] || error \"pool_list $FSNAME failed.\"\n\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\n\tmkdir -p $POOL_DIR\n\t$LFS setstripe -c -1 -p $POOL $POOL_DIR\n\t[[ $? -eq 0 ]] || error \"$LFS setstripe -p $POOL failed.\"\n\tcheck_dir_in_pool $POOL_DIR $POOL\n\n\t# If an invalid pool name is specified, the command should fail\n\t$LFS setstripe -c 2 -p $INVALID_POOL $POOL_DIR 2>/dev/null\n\t[[ $? -ne 0 ]] || error \"setstripe to invalid pool did not fail.\"\n\n\t# If the pool name does not exist, the command should fail\n\t$LFS setstripe -c 2 -p $NON_EXISTANT_POOL $POOL_DIR 2>/dev/null\n\t[[ $? -ne 0 ]] || error \"setstripe to non-existant pool did not fail.\"\n\n\t# lfs setstripe should work as before if a pool name is not specified.\n\t$LFS setstripe -c -1 $POOL_DIR\n\t[[ $? -eq 0 ]] || error \"$LFS setstripe -c -1 $POOL_DIR failed.\"\n\t$LFS setstripe -c -1 $POOL_FILE\n\t[[ $? -eq 0 ]] || error \"$LFS setstripe -c -1 $POOL_FILE failed.\"\n\n\t# lfs setstripe should fail if a start index that is outside the\n\t# pool is specified.\n\tcreate_pool_nofail $POOL2\n\tadd_pool $POOL2 \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\t$LFS setstripe -i 1 -p $POOL2 $ROOT_POOL/$tfile 2>/dev/null\n\t[[ $? -ne 0 ]] ||\n\terror \"$LFS setstripe with start index outside the pool did not fail.\"\n}\nrun_test 6 \"getstripe/setstripe\"\n\nhelper_test_7a()\n{\n\t# Create a pool, stripe a directory and file with it\n\tlocal pool=$1\n\n\tpool_add $pool || error \"pool_add failed\"\n\tpool_add_targets $pool 0 1 || error \"pool_add_targets failed\"\n\n\t$LFS setstripe -c 1 $DIR/$tdir/testfile1 --pool \"$pool\" ||\n\t\terror \"setstripe failed\"\n\t$LFS setstripe -c 1 $DIR/$tdir/testfile2 --pool \"$FSNAME.$pool\" ||\n\t\terror \"setstripe failed\"\n\n\tmkdir $DIR/$tdir/testdir\n\t$LFS setstripe -c 1 $DIR/$tdir/testdir  -p \"$pool\" ||\n\t\terror \"setstripe failed\"\n\t$LFS setstripe -c 1 $DIR/$tdir/testdir  -p \"$FSNAME.$pool\" ||\n\t\terror \"setstripe failed\"\n\n\trm -f $DIR/$tdir/testfile1\n\trm -f $DIR/$tdir/testfile2\n\trmdir $DIR/$tdir/testdir\n\n\tdestroy_pool_int $FSNAME.$pool\n}\n\ntest_7a()\n{\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\n\tmkdir -p $DIR/$tdir\n\n\t# Generate pool with random name from 1 to 15 characters\n\tfor i in 1 9 15 ; do\n\t\tPOOLNAME=$(echo $$$RANDOM$RANDOM |\n\t\t\t   tr -dc 'a-zA-Z0-9' | fold -w $i |\n\t\t\t   head -n 1)\n\t\techo set poolname to $POOLNAME\n\t\thelper_test_7a $POOLNAME\n\tdone\n}\nrun_test 7a \"create various pool name\"\n\ntest_7b()\n{\n\t# No fsname\n\tcreate_pool qwerty\n\t[ $? -ne 22 ] && error \"can create a pool with no fsname\"\n\n\t# No pool name\n\tcreate_pool $FSNAME.\n\t[ $? -ne 22 ] && error \"can create a pool with no name\"\n\n\t# Invalid character\n\tcreate_pool $FSNAME.0123456789^bdef\n\t[ $? -ne 22 ] && error \"can create a pool with an invalid name\"\n\n\t# Too long\n\tcreate_pool $FSNAME.0123456789abdefg\n\t[ $? -ne 36 ] && error \"can create a pool with a name too long\"\n\n\treturn 0\n}\nrun_test 7b \"try to create pool name with invalid lengths or names\"\n\ntest_7c()\n{\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\n\tmkdir -p $DIR/$tdir\n\n\t# Create a pool with 15 letters\n\tlocal pool=0123456789abcde\n\tpool_add $pool || error \"pool_add failed\"\n\tpool_add_targets $pool 0 1 || error \"pool_add_targets failed\"\n\n\t# setstripe with the same pool name plus 1 letter\n\t$LFS setstripe -c 1 $DIR/$tdir/testfile1 --pool \"${pool}X\" &&\n\t\terror \"setstripe succedeed\"\n\n\t# setstripe with the same pool name minus 1 letter\n\t$LFS setstripe -c 1 $DIR/$tdir/testfile1 --pool \"${pool%?}\" &&\n\t\terror \"setstripe succedeed\"\n\n\trm -f $DIR/$tdir/testfile1\n\n\tdestroy_pool_int $FSNAME.$pool\n}\nrun_test 7c \"create a valid pool name and setstripe with a bad one\"\n\ntest_11() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\n\tlocal start=$(printf %04x $((TGT_FIRST + 1)))\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL2 \\\n\t\t$FSNAME-OST[$start-$TGT_MAX/2]\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\tcreate_dir $POOL_ROOT/dir1  $POOL\n\tcreate_dir $POOL_ROOT/dir2  $POOL2\n\n\tlocal numfiles=100\n\tcreatemany -o $POOL_ROOT/dir1/$tfile $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir1/$tfile failed!\"\n\n\tfor file in $POOL_ROOT/dir1/*; do\n\t\tcheck_file_in_pool $file $POOL\n\tdone\n\n\tcreatemany -o $POOL_ROOT/dir2/$tfile $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir2/$tfile failed!\"\n\tfor file in $POOL_ROOT/dir2/*; do\n\t\tcheck_file_in_pool $file $POOL2\n\tdone\n\n\trm -rf $POOL_ROOT/dir?\n\n\treturn 0\n}\nrun_test 11 \"OSTs in overlapping/multiple pools\"\n\ntest_12() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\n\t[[ $OSTCOUNT -le 2 ]] && skip_env \"needs >=3 OSTs\"\n\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\n\tlocal start=$(printf %04x $((TGT_FIRST + 1)))\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL2 \\\n\t\t$FSNAME-OST[$start-$TGT_MAX/2]\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\techo creating some files in $POOL and $POOL2\n\n\tcreate_dir $POOL_ROOT/dir1  $POOL\n\tcreate_dir $POOL_ROOT/dir2  $POOL2\n\tcreate_file $POOL_ROOT/file1 $POOL\n\tcreate_file $POOL_ROOT/file2 $POOL2\n\n\techo Checking the files created\n\tcheck_file_in_pool $POOL_ROOT/file1 $POOL\n\tcheck_file_in_pool $POOL_ROOT/file2 $POOL2\n\n\techo Changing the pool membership\n\tdo_facet mgs lctl pool_remove $FSNAME.$POOL $FSNAME-OST[$TGT_FIRST]\n\tdo_facet mgs lctl pool_list $FSNAME.$POOL\n\tFIRST_UUID=$(echo $TGT_UUID | awk '{print $1}')\n\tadd_pool $POOL2 $FSNAME-OST[$TGT_FIRST] \"$FIRST_UUID \"\n\tdo_facet mgs lctl pool_list $FSNAME.$POOL2\n\n\techo Checking the files again\n\tcheck_dir_in_pool $POOL_ROOT/dir1 $POOL\n\tcheck_dir_in_pool $POOL_ROOT/dir2 $POOL2\n\tcheck_file_in_osts $POOL_ROOT/file1 \"$TGT_LIST2\"\n\tcheck_file_in_osts $POOL_ROOT/file2 \"$(seq 0x$start 2 0x$TGT_MAX)\"\n\n\techo Creating some more files\n\tcreate_dir $POOL_ROOT/dir3 $POOL\n\tcreate_dir $POOL_ROOT/dir4 $POOL2\n\tcreate_file $POOL_ROOT/file3 $POOL\n\tcreate_file $POOL_ROOT/file4 $POOL2\n\n\techo Checking the new files\n\tcheck_file_in_pool $POOL_ROOT/file3 $POOL\n\tcheck_file_in_pool $POOL_ROOT/file4 $POOL2\n\n\treturn 0\n}\nrun_test 12 \"OST Pool Membership\"\n\ntest_13() {\n\t[[ $OSTCOUNT -le 2 ]] && skip_env \"needs >= 3 OSTs\"\n\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=10\n\tlocal count=3\n\n\tcreate_pool_nofail $POOL\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\n\tcreate_dir $POOL_ROOT/dir1 $POOL -1\n\tcreatemany -o $POOL_ROOT/dir1/$tfile $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir1/$tfile failed!\"\n\tfor file in $POOL_ROOT/dir1/*; do\n\t\tcheck_file_in_pool $file $POOL $OSTCOUNT\n\tdone\n\n\tcreate_file $POOL_ROOT/dir1/file1 $POOL 1 $TGT_FIRST\n\tcreate_file $POOL_ROOT/dir1/file2 $POOL 1 $((TGT_FIRST + 1))\n\tcreate_file $POOL_ROOT/dir1/file3 $POOL 1 $((TGT_FIRST + 2))\n\tcheck_file_in_osts $POOL_ROOT/dir1/file1 $((16#$TGT_FIRST))\n\tcheck_file_in_osts $POOL_ROOT/dir1/file2 \"$((TGT_FIRST + 1))\"\n\tcheck_file_in_osts $POOL_ROOT/dir1/file3 \"$((TGT_FIRST + 2))\"\n\n\tcreate_dir $POOL_ROOT/dir2 $POOL $count\n\tcreatemany -o $POOL_ROOT/dir2/$tfile- $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir2/$tfile- failed!\"\n\tfor file in $POOL_ROOT/dir2/*; do\n\t\tcheck_file_in_pool $file $POOL $count\n\tdone\n\n\tcreate_dir $POOL_ROOT/dir3 $POOL $count $((TGT_FIRST + 1))\n\tcreatemany -o $POOL_ROOT/dir3/$tfile- $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir3/$tfile- failed!\"\n\tfor file in $POOL_ROOT/dir3/*; do\n\t\tcheck_file_in_pool $file $POOL $count\n\tdone\n\n\tcreate_dir $POOL_ROOT/dir4 $POOL 1\n\tcreatemany -o $POOL_ROOT/dir4/$tfile- $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir4/$tfile- failed!\"\n\tfor file in $POOL_ROOT/dir4/*; do\n\t\tcheck_file_in_pool $file $POOL 1\n\tdone\n\n\tcreate_dir $POOL_ROOT/dir5 $POOL 1 $((TGT_FIRST + 2))\n\tcreatemany -o $POOL_ROOT/dir5/$tfile- $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir5/$tfile- failed!\"\n\tfor file in $POOL_ROOT/dir5/*; do\n\t\tcheck_file_in_pool $file $POOL 1\n\tdone\n\n\trm -rf $POOL_ROOT/dir[1-5]/\n\n\treturn 0\n}\nrun_test 13 \"Striping characteristics in a pool\"\n\ntest_14() {\n\t[[ $OSTCOUNT -le 2 ]] && skip_env \"needs >= 3 OSTs\"\n\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=100\n\tlocal i\n\n\t[ $OSTSIZE -gt $((MAXFREE / OSTCOUNT)) ] &&\n\tskip_env \"OST size $OSTSIZE is larger than $((MAXFREE / OSTCOUNT))\"\n\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\tadd_pool $POOL2 \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\n\tcreate_dir $POOL_ROOT/dir1 $POOL 1\n\tcreate_file $POOL_ROOT/dir1/file $POOL 1\n\tlocal ost=$($LFS getstripe -i $POOL_ROOT/dir1/file)\n\ti=0\n\twhile [[ $i -lt $numfiles ]]; do\n\t\tost=$((ost + 2))\n\t\t[[ $ost -gt $((16#$TGT_MAX)) ]] && ost=$TGT_FIRST\n\n\t\t# echo \"Iteration: $i OST: $ost\"\n\t\tcreate_file $POOL_ROOT/dir1/file${i} $POOL 1\n\t\tcheck_file_in_pool $POOL_ROOT/dir1/file${i} $POOL\n\t\ti=$((i + 1))\n\tdone\n\n\t# Fill up OST0 until it is nearly full.\n\t# Create 9 files of size OST0_SIZE/10 each.\n\tcreate_dir $POOL_ROOT/dir2 $POOL2 1\n\t$LFS df $POOL_ROOT/dir2\n\tOST0_SIZE=$($LFS df $POOL_ROOT/dir2 | awk '/\\[OST:0\\]/ { print $4 }')\n\tFILE_SIZE=$((OST0_SIZE/1024/10))\n\techo \"Filling OST0 with 9 files of ${FILE_SIZE}MB in $POOL_ROOT/dir2\"\n\ti=1\n\twhile [[ $i -lt 10 ]]; do\n\t\tdd if=/dev/zero of=$POOL_ROOT/dir2/f${i} bs=1M count=$FILE_SIZE\n\t\ti=$((i + 1))\n\tdone\n\tsleep 1 # get new statfs info\n\t$LFS df $POOL_ROOT/dir2\n\n\t# OST $TGT_FIRST is no longer favored; but it may still be used.\n\tcreate_dir $POOL_ROOT/dir3 $POOL 1\n\tcreate_file $POOL_ROOT/dir3/file $POOL 1\n\tcreatemany -o $POOL_ROOT/dir3/$tfile- $numfiles ||\n\t\terror \"createmany $POOL_ROOT/dir3/$tfile- failed!\"\n\tfor file in $POOL_ROOT/dir3/*; do\n\t\tcheck_file_in_pool $file $POOL\n\tdone\n\n\trm -rf $POOL_ROOT\n\n\treturn 0\n}\nrun_test 14 \"Round robin and QOS striping within a pool\"\n\ntest_15() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=100\n\tlocal i=0\n\n\twhile [[ $i -lt $OSTCOUNT ]]; do\n\t\tcreate_pool_nofail $POOL${i}\n\n\t\tlocal tgt=$(printf \"$FSNAME-OST%04x_UUID \" $i)\n\t\tadd_pool $POOL${i} \"$FSNAME-OST[$(printf %04x $i)]\" \"$tgt\"\n\t\tcreate_dir $POOL_ROOT/dir${i} $POOL${i}\n\t\tcreatemany -o $POOL_ROOT/dir$i/$tfile $numfiles ||\n\t\t\terror \"createmany $POOL_ROOT/dir$i/$tfile failed!\"\n\n\t\tfor file in $POOL_ROOT/dir$i/*; do\n\t\t\tcheck_file_in_osts $file $i\n\t\tdone\n\n\t\ti=$((i + 1))\n\tdone\n\n\treturn 0\n}\nrun_test 15 \"One directory per OST/pool\"\n\ntest_16() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=10\n\tlocal i=0\n\n\tcreate_pool_nofail $POOL\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\tlocal dir=$POOL_ROOT/$tdir\n\tcreate_dir $dir $POOL\n\n\tfor i in $(seq 1 10); do\n\t\tdir=${dir}/dir${i}\n\tdone\n\tmkdir -p $dir\n\n\tcreatemany -o $dir/$tfile $numfiles ||\n\t\terror \"createmany $dir/$tfile failed!\"\n\n\tfor file in $dir/*; do\n\t\tcheck_file_in_pool $file $POOL\n\tdone\n\n\trm -rf $POOL_ROOT/$tdir\n\n\treturn 0\n}\nrun_test 16 \"Inheritance of pool properties\"\n\ntest_17() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=10\n\tlocal i=0\n\n\tcreate_pool_nofail $POOL\n\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\n\tlocal dir=$POOL_ROOT/dir\n\tcreate_dir $dir $POOL\n\n\tcreatemany -o $dir/${tfile}1_ $numfiles ||\n\t\terror \"createmany $dir/${tfile}1_ failed!\"\n\n\tfor file in $dir/*; do\n\t\tcheck_file_in_pool $file $POOL\n\tdone\n\n\tdestroy_pool $POOL\n\n\tcreatemany -o $dir/${tfile}2_ $numfiles ||\n\t\terror \"createmany $dir/${tfile}2_ failed!\"\n\n\trm -rf $dir\n\treturn 0\n}\nrun_test 17 \"Referencing an empty pool\"\n\ncreate_perf() {\n    local cdir=$1/d\n    local numsec=$2\n    local time\n\n    mkdir -p $cdir\n    sync\n    wait_delete_completed >/dev/null # give pending IO a chance to go to disk\n    stat=$(createmany -o $cdir/${tfile} -$numsec | tail -1)\n    files=$(echo $stat | cut -f 2 -d ' ')\n    echo $stat 1>&2\n    unlinkmany $cdir/${tfile} $files > /dev/null\n    sync\n\n    echo $files\n}\n\ntest_18() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numsec=15\n\tlocal iter=3\n\tlocal plaindir=$POOL_ROOT/plaindir\n\tlocal pooldir=$POOL_ROOT/pooldir\n\tlocal f1=0\n\tlocal f2=0\n\tlocal f3=0\n\tlocal diff\n\n\tfor i in $(seq 1 $iter); do\n\t\techo \"Create performance, iteration $i, $numsec seconds x 3\"\n\n\t\tlocal files1=$(create_perf $plaindir $numsec)\n\t\t[[ $files1 -eq 0 ]] && error \"Zero files created without pool\"\n\t\tf1=$((f1 + files1))\n\t\techo \"iter $i: $files1 creates without pool\"\n\n\t\tcreate_pool_nofail $POOL > /dev/null\n\t\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\" > /dev/null\n\t\tcreate_dir $pooldir $POOL\n\t\tlocal files2=$(create_perf $pooldir $numsec)\n\t\t[[ $files2 -eq 0 ]] && error \"Zero files created with pool\"\n\t\tf2=$((f2 + files2))\n\t\techo \"iter $i: $files2 creates with pool\"\n\n\t\tdestroy_pool $POOL > /dev/null\n\t\tlocal files3=$(create_perf $pooldir $numsec)\n\t\t[[ $files3 -eq 0 ]] &&\n\t\t\terror \"Zero files created with missing pool\"\n\t\tf3=$((f3 + files3))\n\t\techo \"iter $i: $files3 creates with missing pool\"\n\n\t\techo\n\tdone\n\n\techo Avg files created in $numsec seconds without pool: $((f1 / iter))\n\techo Avg files created in $numsec seconds with pool: $((f2 / iter))\n\techo Avg files created in $numsec seconds missing pool: $((f3 / iter))\n\n\t# Set this high until we establish a baseline for what the degradation\n\t# is / should be\n\tmax=30\n\n\tdiff=$((($f1 - $f2) * 100 / $f1))\n\techo  \"No pool / wide pool: $diff %.\"\n\t[ $diff -gt $max ] &&\n\t\terror_ignore bz23408 \"Degradation with wide pool is $diff% > $max%\"\n\n\tmax=30\n\tdiff=$((($f1 - $f3) * 100 / $f1))\n\techo  \"No pool / missing pool: $diff %.\"\n\t[ $diff -gt $max ] &&\n\t\terror_ignore bz23408 \"Degradation with wide pool is $diff% > $max%\"\n\n\treturn 0\n}\nrun_test 18 \"File create in a directory which references a deleted pool\"\n\ntest_19() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=12\n\tlocal dir1=$POOL_ROOT/dir1\n\tlocal dir2=$POOL_ROOT/dir2\n\tlocal i=0\n\n\tcreate_pool_nofail $POOL\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\tcreate_dir $dir1 $POOL\n\tcreatemany -o $dir1/${tfile} $numfiles ||\n\t\terror \"createmany $dir1/${tfile} failed!\"\n\tfor file in $dir1/*; do\n\t\tcheck_file_in_pool $file $POOL\n\tdone\n\n\tmkdir -p $dir2\n\tcreatemany -o $dir2/${tfile} $numfiles ||\n\t\terror \"createmany $dir2/${tfile} failed!\"\n\tfor file in $dir2/*; do\n\t\tcheck_file_not_in_pool $file $POOL\n\tdone\n\n\trm -rf $dir1 $dir2\n\n\treturn 0\n}\nrun_test 19 \"Pools should not come into play when not specified\"\n\ntest_20() {\n\t[[ $OSTCOUNT -ge 2 ]] || skip_env \"needs >= 2 OSTs\"\n\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=12\n\tlocal dir1=$POOL_ROOT/dir1\n\tlocal dir2=$dir1/dir2\n\tlocal dir3=$dir1/dir3\n\tlocal i=0\n\tlocal TGT\n\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\tlocal start=$(printf %04x $((TGT_FIRST + 1)))\n\tTGT=$(for i in $(seq 0x$start 2 0x$TGT_MAX); do \\\n\t\tprintf \"$FSNAME-OST%04x_UUID \" $i; done)\n\tadd_pool $POOL2 \"$FSNAME-OST[$start-$TGT_MAX/2]\" \"$TGT\"\n\n\tcreate_dir $dir1 $POOL\n\tcreate_file $dir1/file1 $POOL2\t# Should replace $dir1 pool with $POOL2\n\tcreate_dir $dir2 $POOL2\n\ttouch $dir2/file2\t\t# Should inherit $POOL2 from $dir2\n\tmkdir $dir3\t\t\t# Should inherit $POOL from $dir1\n\t$LFS setstripe -c 1 $dir3\t# Should remain existing $POOL\n\ttouch $dir3/file3\t\t# Should inherit $POOL from $dir3\n\t$LFS setstripe -c 1 $dir2/file4 # Should inherit $POOL2 from dir2\n\t$LFS setstripe -S 64K $dir1/file5 # Should inderit $POOL from $dir1\n\n\tcheck_file_in_pool $dir1/file1 $POOL2\n\tcheck_file_in_pool $dir2/file2 $POOL2\n\tcheck_dir_not_in_pool $dir3 $POOL2\n\tcheck_file_not_in_pool $dir3/file3 $POOL2\n\tcheck_file_not_in_pool $dir2/file4 $POOL\n\tcheck_file_not_in_pool $dir1/file5 $POOL2\n\n\tif [ \"$MDS1_VERSION\" -ge $(version_code 2.10.54) ]; then\n\t\tcheck_dir_in_pool $dir3 $POOL\n\t\tcheck_file_in_pool $dir3/file3 $POOL\n\t\tcheck_file_in_pool $dir2/file4 $POOL2\n\t\tcheck_file_in_pool $dir1/file5 $POOL\n\tfi\n\n\trm -rf $dir1\n\n\treturn 0\n}\nrun_test 20 \"Different pools in a directory hierarchy.\"\n\ntest_21() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal numfiles=12\n\tlocal i=0\n\tlocal dir=$POOL_ROOT/dir\n\n\tcreate_pool_nofail $POOL\n\n\tadd_pool $POOL $TGT_HALF \"$TGT_UUID2\"\n\n\tcreate_dir $dir $POOL $OSTCOUNT\n\tcreate_file $dir/file1 $POOL $OSTCOUNT\n\t$LFS getstripe -v $dir/file1\n\tcheck_file_in_pool $dir/file1 $POOL\n\n\trm -rf $dir\n\n\treturn 0\n}\nrun_test 21 \"OST pool with fewer OSTs than stripe count\"\n\nadd_loop() {\n\tlocal pool=$1\n\tlocal step=$2\n\n\techo loop for $pool\n\n\tfor c in $(seq 1 10); do\n\t\techo \"Pool $pool, iteration $c\"\n\t\tdo_facet mgs lctl pool_add $FSNAME.$pool \\\n\t\t\tOST[$TGT_FIRST-$TGT_MAX/$step] 2>/dev/null\n\t\tlocal TGT_SECOND=$(printf %04x $((TGT_FIRST + $step)))\n\t\tif [ $((16#$TGT_SECOND)) -le $((16#$TGT_MAX)) ]; then\n\t\tdo_facet mgs lctl pool_remove $FSNAME.$pool \\\n\t\t\tOST[$TGT_SECOND-$TGT_MAX/$step]\n\t\tfi\n\tdone\n\techo loop for $pool complete\n}\n\ntest_22() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal numfiles=100\n\n\tcreate_pool_nofail $POOL\n\tadd_pool $POOL \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\tcreate_pool_nofail $POOL2\n\tadd_pool $POOL2 \"OST0000\" \"$FSNAME-OST0000_UUID \"\n\n\tadd_loop $POOL 1 &\n\tadd_loop $POOL2 2 &\n\tsleep 5\n\tcreate_dir $POOL_ROOT $POOL\n\tcreatemany -o $POOL_ROOT/${tfile} $numfiles ||\n\t\terror \"createmany $POOL_ROOT/${tfile} failed!\"\n\twait\n\n\treturn 0\n}\nrun_test 22 \"Simultaneous manipulation of a pool\"\n\ntest_23a() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tmkdir -p $POOL_ROOT\n\tcheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS ||\n\t\tskip_env \"User $RUNAS_ID does not exist - skipping\"\n\n\tlocal i=0\n\tlocal TGT\n\tlocal BUNIT_SZ=1024  # min block quota unit(kB)\n\tlocal LIMIT=$((BUNIT_SZ * (OSTCOUNT + 1)))\n\tlocal dir=$POOL_ROOT/dir\n\tlocal file=\"$dir/$tfile-quota\"\n\n\tcreate_pool_nofail $POOL\n\n\tlocal TGT=$(for i in $(seq 0x$TGT_FIRST 3 0x$TGT_MAX); do \\\n\t\tprintf \"$FSNAME-OST%04x_UUID \" $i; done)\n\tadd_pool $POOL \"$FSNAME-OST[$TGT_FIRST-$TGT_MAX/3]\" \"$TGT\"\n\tcreate_dir $dir $POOL\n\n\t# XXX remove the interoperability code once we drop the old server\n\t#     ( < 2.3.50) support.\n\tif [ \"$MDS1_VERSION\" -lt $(version_code 2.3.50) ]; then\n\t\t$LFS quotaoff -ug $MOUNT\n\t\t$LFS quotacheck -ug $MOUNT\n\telse\n\t\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\t\tdo_facet mgs $PERM_CMD \\\n\t\t\t\tosd-*.$FSNAME-OST*.quota_slave.enable=ug\n\t\telse\n\t\t\tdo_facet mgs $PERM_CMD $FSNAME.quota.ost=ug\n\t\tfi\n\t\tsleep 5\n\tfi\n\n\t$LFS setquota -u $RUNAS_ID -b $LIMIT -B $LIMIT $dir\n\tsleep 3\n\t$LFS quota -v -u $RUNAS_ID $dir\n\n\t$LFS setstripe -c 1 -p $POOL $file\n\tchown $RUNAS_ID.$RUNAS_GID $file\n\tls -l $file\n\n\t# This does two \"dd\" runs to ensure that the quota failure is returned\n\t# to userspace when we check.  The first \"dd\" might otherwise complete\n\t# without error if it is only writing into cache.\n\tstat=$(LOCALE=C $RUNAS dd if=/dev/zero of=$file bs=$BUNIT_SZ \\\n\t\tcount=$((BUNIT_SZ*2)) 2>&1)\n\techo $stat | grep \"Disk quota exceeded\" > /dev/null\n\tif [ $? -eq 0 ]; then\n\t\t$LFS quota -v -u $RUNAS_ID $dir\n\t\tcancel_lru_locks osc\n\t\tstat=$(LOCALE=C $RUNAS dd if=/dev/zero of=$file bs=$BUNIT_SZ \\\n\t\t\tcount=$BUNIT_SZ seek=$((BUNIT_SZ*2)) 2>&1)\n\t\tRC=$?\n\t\techo $stat\n\t\t[[ $RC -eq 0 ]] && error \"second dd did not fail.\"\n\t\techo $stat | grep \"Disk quota exceeded\" > /dev/null\n\t\t[[ $? -eq 1 ]] && error \"second dd did not fail with EDQUOT.\"\n\telse\n\t\tlog \"first dd failed with EDQUOT.\"\n\tfi\n\t$LFS quota -v -u $RUNAS_ID $dir\n}\nrun_test 23a \"OST pools and quota\"\n\ntest_23b() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tmkdir -p $POOL_ROOT\n\tcheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS || {\n\t\tskip_env \"User $RUNAS_ID does not exist - skipping\"\n\t}\n\n\tlocal i=0\n\tlocal TGT\n\tlocal dir=$POOL_ROOT/dir\n\tlocal file=\"$dir/$tfile-quota\"\n\n\tcreate_pool_nofail $POOL\n\n\tlocal TGT=$(for i in $(seq 0x$TGT_FIRST 3 0x$TGT_MAX); do \\\n\t\tprintf \"$FSNAME-OST%04x_UUID \" $i; done)\n\tadd_pool $POOL \"$FSNAME-OST[$TGT_FIRST-$TGT_MAX/3]\" \"$TGT\"\n\tcreate_dir $dir $POOL\n\n\tlocal maxfree=$((1024 * 1024 * 30)) # 30G\n\tlocal AVAIL=$(lfs_df -p $POOL $dir | awk '/summary/ { print $4 }')\n\t[ $AVAIL -gt $maxfree ] &&\n\t\tskip_env \"Filesystem space $AVAIL is larger than \" \\\n\t\t\t\"$maxfree limit\"\n\n\techo \"OSTCOUNT=$OSTCOUNT, OSTSIZE=$OSTSIZE, AVAIL=$AVAIL\"\n\techo \"MAXFREE=$maxfree, SLOW=$SLOW\"\n\n\t# XXX remove the interoperability code once we drop the old server\n\t#     ( < 2.3.50) support.\n\tif [ \"$MDS1_VERSION\" -lt $(version_code 2.3.50) ]; then\n\t\t$LFS quotaoff -ug $MOUNT\n\telse\n\t\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\t\tdo_facet mgs $PERM_CMD \\\n\t\t\t\tosd-*.$FSNAME-OST*.quota_slave.enable=none\n\t\telse\n\t\t\tdo_facet mgs $PERM_CMD $FSNAME.quota.ost=none\n\t\tfi\n\t\tsleep 5\n\tfi\n\n\tchown $RUNAS_ID.$RUNAS_ID $dir\n\ti=0\n\tlocal RC=0\n\tlocal TOTAL=0 # KB\n\tlocal stime=$(date +%s)\n\tlocal stat\n\tlocal etime\n\tlocal elapsed\n\tlocal maxtime=300 # minimum speed: 5GB / 300sec ~= 17MB/s\n\twhile [ $RC -eq 0 ]; do\n\t\ti=$((i + 1))\n\t\tstat=$(LOCALE=C $RUNAS2 dd if=/dev/zero of=${file}$i bs=1M \\\n\t\t\tcount=$((5 * 1024)) 2>&1)\n\t\tRC=$?\n\t\tTOTAL=$((TOTAL + 1024 * 1024 * 5))\n\t\techo \"[$i iteration] $stat\"\n\t\techo \"total written: $TOTAL\"\n\n\t\tetime=$(date +%s)\n\t\telapsed=$((etime - stime))\n\t\techo \"stime=$stime, etime=$etime, elapsed=$elapsed\"\n\n\t\tif [ $RC -eq 1 ]; then\n\t\t\techo $stat | grep -q \"Disk quota exceeded\"\n\t\t\t[[ $? -eq 0 ]] &&\n\t\t\t\terror \"dd failed with EDQUOT with quota off\"\n\n\t\t\techo $stat | grep -q \"No space left on device\"\n\t\t\t[[ $? -ne 0 ]] &&\n\t\t\t\terror \"dd did not fail with ENOSPC\"\n\t\telif [ $TOTAL -gt $AVAIL ]; then\n\t\t\terror \"dd didn't fail with ENOSPC ($TOTAL > $AVAIL)\"\n\t\telif [ $i -eq 1 -a $elapsed -gt $maxtime ]; then\n\t\t\tlog \"The first 5G write used $elapsed (> $maxtime) \" \\\n\t\t\t\t\"seconds, terminated\"\n\t\t\tRC=1\n\t\tfi\n\tdone\n\n\tdf -h\n\trm -rf $POOL_ROOT\n}\nrun_test 23b \"OST pools and OOS\"\n\ntest_24() {\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"needs >= 2 OSTs\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.8.56) ]] ||\n\t\tskip \"Need server version newer than 2.8.55\"\n\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\tlocal numfiles=10\n\tlocal i=0\n\tlocal TGT\n\tlocal dir\n\tlocal res\n\n\tcreate_pool_nofail $POOL\n\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\n\tcreate_dir $POOL_ROOT/dir1 $POOL $OSTCOUNT\n\n\tmkdir $POOL_ROOT/dir2\n\t$LFS setstripe -p $POOL -S 65536 -i 0 -c 1 $POOL_ROOT/dir2 ||\n\t\terror \"$LFS setstripe $POOL_ROOT/dir2 failed\"\n\n\tmkdir $POOL_ROOT/dir3\n\t$LFS setstripe -S 65536 -i 0 -c 1 $POOL_ROOT/dir3 ||\n\t\terror \"$LFS setstripe $POOL_ROOT/dir3 failed\"\n\n\tmkdir $POOL_ROOT/dir4\n\n\tfor i in 1 2 3 4; do\n\t\tdir=${POOL_ROOT}/dir${i}\n\t\tlocal pool\n\t\tlocal pool1\n\t\tlocal count\n\t\tlocal count1\n\t\tlocal index\n\t\tlocal size\n\t\tlocal size1\n\n\t\tcreatemany -o $dir/${tfile} $numfiles ||\n\t\t\terror \"createmany $dir/${tfile} failed!\"\n\t\tpool=$($LFS getstripe --pool $dir)\n\t\tindex=$($LFS getstripe -i $dir)\n\t\tsize=$($LFS getstripe -S $dir)\n\t\tcount=$($LFS getstripe -c $dir)\n\n\t\tfor file in $dir/*; do\n\t\t\tif [ \"$pool\" != \"\" ]; then\n\t\t\t\tcheck_file_in_pool $file $pool\n\t\t\tfi\n\t\t\tpool1=$($LFS getstripe --pool $file)\n\t\t\tcount1=$($LFS getstripe -c $file)\n\t\t\tsize1=$($LFS getstripe -S $file)\n\t\t\t[[ \"$pool\" != \"$pool1\" ]] &&\n\t\t\t\terror \"Pool '$pool' not on $file:$pool1\"\n\t\t\t[[ \"$count\" != \"$count1\" ]] &&\n\t\t\t\t[[ \"$count\" != \"-1\" ]] &&\n\t\t\t\t\terror \"Stripe count $count not on\"\\\n\t\t\t\t\t\t\"$file:$count1\"\n\t\t\t[[ \"$count1\" != \"$OSTCOUNT\" ]] &&\n\t\t\t\t[[ \"$count\" = \"-1\" ]] &&\n\t\t\t\t\terror \"Stripe count $count1 not on\"\\\n\t\t\t\t\t\t\"$file:$OSTCOUNT\"\n\t\t\t[[ \"$size\" != \"$size1\" ]] && [[ \"$size\" != \"0\" ]] &&\n\t\t\t\terror \"Stripe size $size not on $file:$size1\"\n\t\tdone\n\tdone\n\n\trm -rf $POOL_ROOT\n\n\treturn 0\n}\nrun_test 24 \"Independence of pool from other setstripe parameters\"\n\ntest_25() {\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\n\tmkdir -p $POOL_ROOT\n\n\tfor i in $(seq 10); do\n\t\tcreate_pool_nofail $POOL$i\n\t\tdo_facet mgs \"lctl pool_add $FSNAME.$POOL$i OST0000; sync\"\n\t\twait_update $HOSTNAME \"lctl get_param -n \\\n\t\t\tlov.$FSNAME-*.pools.$POOL$i | sort -u |\n\t\t\ttr '\\n' ' ' \" \"$FSNAME-OST0000_UUID \" >/dev/null ||\n\t\t\t\terror \"pool_add failed: $1; $2\"\n\n\t\tfacet_failover $SINGLEMDS ||\n\t\t\terror \"failed to failover $SINGLEMDS\"\n\t\twait_osc_import_state $SINGLEMDS ost FULL\n\t\tclients_up\n\n\t\twait_mds_ost_sync\n\t\t# Veriy that the pool got created and is usable\n\t\tdf $POOL_ROOT > /dev/null\n\t\tsleep 5\n\n\t\t# Make sure OST0 can be striped on\n\t\t$LFS setstripe -i 0 -c 1 $POOL_ROOT/$tfile\n\t\tlocal STR=$($LFS getstripe -i $POOL_ROOT/$tfile)\n\t\trm $POOL_ROOT/$tfile\n\t\tif [[ \"$STR\" == \"0\" ]]; then\n\t\t\techo \"Creating a file in pool$i\"\n\t\t\tcreate_file $POOL_ROOT/file$i $POOL$i || break\n\t\t\tcheck_file_in_pool $POOL_ROOT/file$i $POOL$i || break\n\t\telse\n\t\t\techo \"OST 0 seems to be unavailable.  Try later.\"\n\t\tfi\n\tdone\n\n\trm -rf $POOL_ROOT\n}\nrun_test 25 \"Create new pool and restart MDS\"\n\ntest_26() {\n\t[[ $OSTCOUNT -le 2 ]] && skip_env \"needs >= 3 OSTs\"\n\tlocal dev=$(mdsdevname ${SINGLEMDS//mds/})\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/$tdir}\n\n\tmkdir -p $POOL_ROOT\n\n\tcreate_pool_nofail $POOL2\n\n\tdo_facet mgs \"lctl pool_add $FSNAME.$POOL2 OST0000; sync\"\n\twait_update $HOSTNAME \"lctl get_param -n \\\n\t\tlov.$FSNAME-*.pools.$POOL2 | sort -u |\n\t\tgrep $FSNAME-OST0000_UUID \" \"$FSNAME-OST0000_UUID\" ||\n\t\t\terror \"pool_add failed: $1; $2\"\n\n\tdo_facet mgs \"lctl pool_add $FSNAME.$POOL2 OST0002; sync\"\n\twait_update $HOSTNAME \"lctl get_param -n \\\n\t\tlov.$FSNAME-*.pools.$POOL2 | sort -u |\n\t\tgrep $FSNAME-OST0002_UUID\" \"$FSNAME-OST0002_UUID\" ||\n\t\t\terror \"pool_add failed: $1; $2\"\n\n\t# Veriy that the pool got created and is usable\n\tdf $POOL_ROOT\n\techo \"Creating files in $POOL2\"\n\n\tfor ((i = 0; i < 10; i++)); do\n\t\t#OBD_FAIL_MDS_OSC_CREATE_FAIL     0x147\n\t\t#Fail OST0000 to ensure objects create on\n\t\t#the other OST in the pool\n\t\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x147\n\t\tdo_facet $SINGLEMDS lctl set_param fail_val=0\n\t\tcreate_file $POOL_ROOT/file$i $POOL2 1 -1 || break\n\t\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\t\tcheck_file_in_pool $POOL_ROOT/file$i $POOL2 || break\n\tdone\n\trm -rf $POOL_ROOT\n}\nrun_test 26 \"Choose other OSTs in the pool first in the creation remedy\"\n\ntest_27() {\n\t[[ $OSTCOUNT -le 1 ]] && skip_env \"Need at least 2 OSTs\"\n\n\tlocal osts\n\tlocal pid\n\tlocal count=$OSTCOUNT\n\n\tcreate_pool_nofail $POOL\n\tdo_facet mgs lctl pool_add $FSNAME.$POOL $TGT_ALL\n\twait_update_facet $SINGLEMDS \\\n\t\t\"lctl pool_list $FSNAME.$POOL | wc -l\" \"$((OSTCOUNT + 1))\" ||\n\t\terror \"MDS: pool_list $FSNAME.$POOL failed\"\n\tosts=$(list_pool $FSNAME.$POOL)\n\tfor ost in ${osts}; do\n\t\t((count--))\n\t\tif [[ $count -eq 0 ]]; then\n\t\t\t#define OBD_FAIL_OST_LIST_ASSERT    0x239\n\t\t\tdo_facet $SINGLEMDS \\\n\t\t\t\t$LCTL set_param fail_loc=0x239 fail_val=10\n\t\t\tlist_pool $FSNAME.$POOL &\n\t\t\tpid=$!\n\t\t\tsleep 5\n\t\t\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\t\t\tdo_facet mgs $LCTL pool_remove $FSNAME.$POOL $ost\n\t\t\twait $pid\n\t\t\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0\n\t\telse\n\t\t\tdo_facet mgs $LCTL pool_remove $FSNAME.$POOL $ost\n\t\tfi\n\tdone\n\tdestroy_pool $POOL\n}\nrun_test 27 \"Race pool_list and pool_remove\"\n\ntest_28() {\n\tcreate_pool_nofail $POOL\n\tcreate_pool_nofail $POOL2\n\tadd_pool $POOL $TGT_ALL \"$TGT_UUID\"\n\tadd_pool $POOL2 $TGT_ALL \"$TGT_UUID\"\n\n\tstart_full_debug_logging\n\t#$LFS setstripe -E 4M -c 1 -p $POOL -E 16M -c 2 $DIR/$tfile\n\t$LFS setstripe -c 1 -p $POOL $DIR/$tfile\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1M count=1 seek=16\n\tlocal csum=$(cksum $DIR/$tfile)\n\t$LFS getstripe $DIR/$tfile\n\tlocal pool=\"$($LFS getstripe -p $DIR/$tfile)\"\n\t[[ \"$pool\" == \"$POOL\" ]] ||\n\t\terror \"$tfile is in '$pool', not created on $POOL\"\n\t$LFS_MIGRATE -y -p $POOL2 $DIR/$tfile ||\n\t\terror \"migrate $tfile to $POOL2 failed\"\n\t$LFS getstripe $DIR/$tfile\n\tpool=\"$($LFS getstripe -p $DIR/$tfile)\"\n\t[[ \"$pool\" == \"$POOL2\" ]] ||\n\t\terror \"$tfile is in '$pool', not migrated to $POOL2\"\n\tlocal csum2=$(cksum $DIR/$tfile)\n\t[[ \"$csum\" == \"$csum2\" ]] || error \"checksum error after migration\"\n\tstop_full_debug_logging\n}\nrun_test 28 \"lfs_migrate with pool name\"\n\ncd $ORIG_PWD\n\ncomplete $SECONDS\ndestroy_test_pools $FSNAME\nif ! combined_mgs_mds; then\n\tzconf_umount $mgs_HOST $MOUNT\n\tdo_facet mgs \"rm -rf $MOUNT\"\nfi\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1598}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport NAME=${NAME:-local}\nexport OSTSIZE=10000\n\nMOUNT=${MOUNT:-/mnt/lustre}\n\necho \"mnt..\"\nsh llmount.sh\necho \"done\"\necho \"\"\n\nSUCCESS=1\n\nFREESPACE=`df |grep $MOUNT|tr -s ' '|cut -d ' ' -f4`\n\nrm -f /tmp/oosfile\ndd if=/dev/zero of=$MOUNT/oosfile count=$[$FREESPACE + 1] bs=1k 2>/tmp/oosfile\n\nRECORDSOUT=`grep \"records out\" /tmp/oosfile|cut -d + -f1`\n\n[ -z \"`grep \"No space left on device\" /tmp/oosfile`\" ] && \\\n        echo \"failed:dd not return ENOSPC\" && SUCCESS=0\n\n[ $FREESPACE -lt $RECORDSOUT ] && \\\n        echo \"failed:the space written by dd larger than available space\" && \\\n        SUCCESS=0\n\nFILESIZE=`ls -l $MOUNT/oosfile|tr -s ' '|cut -d ' ' -f5`\n[ $RECORDSOUT -ne $[$FILESIZE/1024] ] && \\\n        echo \"failed:the space written by dd not equal to the size of file\" && \\\n        SUCCESS=0\n\n[ $SUCCESS -eq 1 ] && echo \"Success!\"\n\nrm -f $MOUNT/oosfile*\nrm -f /tmp/oosfile\n\necho \"\"\necho \"cln..\"\nsh llmountcleanup.sh\n", "num_lines": 42}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Requires the pre-configured samba machine\n# RPMS required are :\n# server:\n#      samba\n#      samba-common\n#      cifs-utils\n# clients:\n#      samba-client\n#      samba-common\n#      cifs-utils\n\n#set -vx\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n. $LUSTRE/tests/setup-cifs.sh\n\ncheck_and_setup_lustre\n\n# first unmount all the lustre clients\ncleanup_mount $MOUNT\n# lustre client used as samba server (default is mds node)\nLUSTRE_CLIENT_SMBSRV=${LUSTRE_CLIENT_SMBSRV:-$(facet_active_host $SINGLEMDS)}\nSMBSHARE=${SMBSHARE:-lustretest}\nSMBUSER=${SMBUSER:-root}\nSMBPASSWD=${SMBPASSWD:-lustre}\nSMBSRVMNTPT=${SMBSRVMNTPT:-$MOUNT}\nSMBCLIMNTPT=${SMBCLIMNTPT:-$MOUNT}\nSMBCLIENTS=${SMBCLIENTS:-$CLIENTS}\nSMBCLIENTS=$(exclude_items_from_list $SMBCLIENTS $LUSTRE_CLIENT_SMBSRV)\n\n[ -z \"$SMBCLIENTS\" ] &&\n\tskip_env \"need at least two nodes: samba server and samba client\"\n\n# set CONFIGURE_SMB=false to skip smb config\nCONFIGURE_SMB=${CONFIGURE_SMB:-true}\n\n# store smb status to restart smb service if it was running initially\nSMBSTATUS=0\nsmb_status $LUSTRE_CLIENT_SMBSRV || SMBSTATUS=$?\nSMBCONFTMP=$(do_node $LUSTRE_CLIENT_SMBSRV \"mktemp -t smb.conf.XXX\")\n\ncleanup_exit() {\n\ttrap 0\n\tcleanup\n\tcheck_and_cleanup_lustre\n\texit\n}\n\ncleanup() {\n\tcleanup_cifs $LUSTRE_CLIENT_SMBSRV $SMBCLIMNTPT $SMBCLIENTS ||\n\t\terror_noexit false \"failed to cleanup cifs\"\n\tzconf_umount $LUSTRE_CLIENT_SMBSRV $SMBSRVMNTPT force ||\n\t\terror_noexit false \"failed to umount lustre on $LUSTRE_CLIENT_SMBSRV\"\n\t# restore lustre mount\n\trestore_mount $MOUNT ||\n\t\terror_noexit false \"failed to mount lustre\"\n\n\t$CONFIGURE_SMB && restore_config_smb $LUSTRE_CLIENT_SMBSRV $SMBCONFTMP\n\t[[ $SMBSTATUS -eq 0 ]] &&\n\t\tdo_node $LUSTRE_CLIENT_SMBSRV \"service smb start\"\n\tunset CIFSCLIENT\n}\n\n$CONFIGURE_SMB && configure_smb $LUSTRE_CLIENT_SMBSRV $SMBSHARE $SMBUSER \\\n\t\t$SMBPASSWD $SMBSRVMNTPT $SMBCONFTMP ||\n\techo -e \"\\nSkipping smb config ...\"\n\ntrap cleanup_exit EXIT SIGHUP SIGINT\n\n# mount lustre client on smb server\nzconf_mount $LUSTRE_CLIENT_SMBSRV $SMBSRVMNTPT ||\n\terror \"mount lustre on $LUSTRE_CLIENT_SMBSRV failed\"\n\n# setup the cifs\nsetup_cifs $LUSTRE_CLIENT_SMBSRV $SMBSHARE $SMBCLIMNTPT $SMBUSER \\\n\t\t$SMBPASSWD $SMBCLIENTS ||\n\terror false \"setup cifs failed\"\n\nCIFSCLIENT=yes\nFAIL_ON_ERROR=false\n\n# compilbench\n# Run short iteration in cifs mode\ncbench_IDIRS=${cbench_IDIRS:-2}\ncbench_RUNS=${cbench_RUNS:-2}\n\n# source the common file after all parameters are set to take effect\n. $LUSTRE/tests/functions.sh\n\nbuild_test_filter\n\ncheck_prog_output() {\n\tlocal clients=$1\n\tlocal file=$2\n\tlocal str=$3\n\n\tdo_nodes $clients grep -q \\\\\\\"$str\\\\\\\" $file 2>/dev/null\n}\n\nwait_prog_output() {\n\tlocal clients=$1\n\tlocal file=$2\n\tlocal str=$3\n\tlocal time=$4\n\tlocal start_ts=$(date +%s)\n\tlocal elapsed\n\n\twhile ! check_prog_output $clients $file \"$str\"; do\n\t\telapsed=$(($(date +%s) - start_ts))\n\t\tif [ $elapsed -gt $time ]; then\n\t\t\treturn 1\n\t\tfi\n\t\tsleep 1\n\tdone\n}\n\ntest_compilebench() {\n\trun_compilebench $SMBCLIMNTPT\n}\nrun_test compilebench \"compilebench on cifs clients\"\n\ntest_dbench() {\n\tlocal clients=$SMBCLIENTS\n\tlocal duration=${DBENCH_DURATION:-300}\n\tlocal nproc=${DBENCH_NPROC:-1}\n\tlocal delay=${dbench_STARTDELAY:-120}\n\tlocal log=$TMP/dbench.log\n\tlocal pid=\"\"\n\n\tlocal cmd=\"rundbench $nproc -t $duration\"\n\n\techo \"Using: $cmd\"\n\n\tdo_nodesv $clients \"set -x; MISSING_DBENCH_OK=$MISSING_DBENCH_OK \\\n\t\tPATH=\\$PATH DBENCH_LIB=$DBENCH_LIB \\\n\t\tTESTSUITE=$TESTSUITE TESTNAME=$TESTNAME \\\n\t\tDIR=$SMBCLIMNTPT/$tdir/\\\\\\$(hostname) \\\n\t\tLCTL=$LCTL $cmd 2>&1 | tee $log; \\\n\t\texit \\\\\\${PIPESTATUS[0]}\" &\n\tpid=$!\n\n\t# check that dbench is started on all clients after\n\t# $dbench_STARTDELAY: the dbench log on each client\n\t# is to be started for this moment and contain \"dbench PID\";\n\tif ! wait_prog_output $clients $log \"dbench PID\" $delay; then\n\t\tkill -s TERM $pid\n\t\tkillall_process $clients dbench\n\t\terror \"dbench failed to start on $clients!\"\n\tfi\n\n\tlog \"Started rundbench load pid=$pid ...\"\n\twait $pid || error \"rundbench load on $clients failed!\"\n}\nrun_test dbench \"dbench on cifs clients\"\n\ntest_fsx() {\n\tlocal clients=$SMBCLIENTS\n\tlocal seed=${fsx_SEED:-$RANDOM}\n\tlocal size=${fsx_SIZE:-1024}\n\tlocal numop=${fsx_NUMOP:-100000}\n\tlocal delay=${fsx_STARTDELAY:-120}\n\tlocal log=$TMP/fsx.log\n\tlocal pid=\"\"\n\n\tlocal nclients=$(get_node_count ${clients//,/ })\n\tlocal space=$(df -P $SMBCLIMNTPT | tail -n 1 | awk '{ print $4 }')\n\t[ $space -lt $((size * nclients)) ] && size=$((space * 3 / 4 / nclients))\n\n\tlocal cmd=\"$FSX -c 50 -p 500 -S $seed -P $TMP -l $size -N $numop \"\n\n\techo \"Using: $cmd\"\n\n\tdo_nodesv $clients \"set -x; \\\n\t\tPATH=\\$PATH \\\n\t\t$cmd $SMBCLIMNTPT/f0.fsx_\\\\\\$(hostname) 2>&1 | tee $log; \\\n\t\texit \\\\\\${PIPESTATUS[0]}\" &\n\tpid=$!\n\n\t# check that fsx is started on all clients after\n\t# $fsx_STARTDELAY: the fsx log on each client\n\t# is to be started for this moment and contain \"Seed set\";\n\tif ! wait_prog_output $clients $log \"Seed set\" $delay; then\n\t\tkill -s TERM $pid\n\t\tkillall_process $clients fsx\n\t\terror \"fsx failed to start on $clients!\"\n\tfi\n\n\tlog \"Started fsx load pid=$pid ...\"\n\twait $pid || error \"fsx load on $clients failed!\"\n}\nrun_test fsx \"fsx on cifs clients\"\n\ntest_iozone() {\n\tlocal clients=$SMBCLIENTS\n\tlocal size=${iozone_SIZE:-262144} # 256m\n\tlocal delay=${iozone_STARTDELAY:-120}\n\tlocal log=$TMP/iozone.log\n\tlocal pid=\"\"\n\n\tlocal nclients=$(get_node_count ${clients//,/ })\n\n\tlocal space=$(df -P $SMBCLIMNTPT | tail -n 1 | awk '{ print $4 }')\n\n\t[[ $((size * nclients)) -gt $((space * 3 / 4)) ]] &&\n\t\tsize=$((space * 3 / 4 / nclients))\n\n\tdo_node $LUSTRE_CLIENT_SMBSRV \"mkdir $SMBSRVMNTPT/$tdir\n\t\tlfs setstripe -c -1 $SMBSRVMNTPT/$tdir\"\n\n\tlog \"free space: $space Kb, using $size size, $nclients number of clients\"\n\n\tlocal cmd=\"iozone -a -e -+d -s $size \"\n\n\techo \"Using: $cmd\"\n\n\tdo_nodesv $clients \"set -x; \\\n\t\tPATH=\\$PATH \\\n\t\t$cmd -f $SMBCLIMNTPT/$tdir/f0.iozone_\\\\\\$(hostname) \\\n\t\t2>&1 | tee $log; exit \\\\\\${PIPESTATUS[0]}\" &\n\tpid=$!\n\n\t# check that iozone is started on all clients after\n\t# $iozone_STARTDELAY: the iozone log on each client\n\t# is to be started for this moment and contain \"Command line used\";\n\tif ! wait_prog_output $clients $log \"Command line used\" $delay; then\n\t\tkill -s TERM $pid\n\t\tkillall_process $clients iozone\n\t\terror \"iozone failed to start on $clients!\"\n\tfi\n\n\tlog \"Started iozone load pid=$pid ...\"\n\twait $pid\n\trc=$?\n\tlog \"Processing iozone log\"\n\tdo_nodesv $clients \"tail -1 $log | grep -q complete\" || rc=2\n\tdo_node $LUSTRE_CLIENT_SMBSRV \"rm -rf $SMBSRVMNTPT/$tdir\"\n\t[ $rc -eq 0 ] || error \"iozone load on $clients failed! rc=$rc\"\n}\nrun_test iozone \"iozone on cifs clients\"\n\ncomplete $SECONDS\nexit_status\n", "num_lines": 249}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#set -vx\n\nNFSVERSION=${1:-\"3\"}\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\n# only call init_test_env if this script is called directly\nif [[ -z \"$TESTSUITE\" || \"$TESTSUITE\" = \"$(basename $0 .sh)\" ]]; then\n\tinit_test_env $@\nfi\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nracer=$LUSTRE/tests/racer/racer.sh\n. $LUSTRE/tests/setup-nfs.sh\n\n# lustre client used as nfs server (default is mds node)\nLUSTRE_CLIENT_NFSSRV=${LUSTRE_CLIENT_NFSSRV:-$(facet_active_host $SINGLEMDS)}\nNFS_SRVMNTPT=${NFS_SRVMNTPT:-$MOUNT}\nNFS_CLIENTS=${NFS_CLIENTS:-$CLIENTS}\nNFS_CLIENTS=$(exclude_items_from_list $NFS_CLIENTS $LUSTRE_CLIENT_NFSSRV)\nNFS_CLIMNTPT=${NFS_CLIMNTPT:-$MOUNT}\n\n[ -z \"$NFS_CLIENTS\" ] &&\n\tskip_env \"need at least two nodes: nfs server and nfs client\"\n\n[ \"$NFSVERSION\" = \"4\" ] && cl_mnt_opt=\"${MOUNT_OPTS:+$MOUNT_OPTS,}32bitapi\" ||\n\tcl_mnt_opt=\"\"\n\ncheck_and_setup_lustre\n$LFS df\nTESTDIR=$NFS_CLIMNTPT/d0.$(basename $0 .sh)\nmkdir -p $TESTDIR\n$LFS setstripe -c -1 $TESTDIR\n\n# first unmount all the lustre clients\ncleanup_mount $MOUNT\n\ncleanup_exit () {\n\ttrap 0\n\tcleanup\n\tcheck_and_cleanup_lustre\n\texit\n}\n\ncleanup () {\n\tcleanup_nfs \"$NFS_CLIMNTPT\" \"$LUSTRE_CLIENT_NFSSRV\" \"$NFS_CLIENTS\" ||\n\t\terror_noexit false \"failed to cleanup nfs\"\n\tzconf_umount $LUSTRE_CLIENT_NFSSRV $NFS_SRVMNTPT force ||\n\t\terror_noexit false \"failed to umount lustre on\"\\\n\t\t\t\"$LUSTRE_CLIENT_NFSSRV\"\n\t# restore lustre mount\n\trestore_mount $MOUNT ||\n\t\terror_noexit false \"failed to mount lustre\"\n}\n\ntrap cleanup_exit EXIT SIGHUP SIGINT\n\nzconf_mount $LUSTRE_CLIENT_NFSSRV $NFS_SRVMNTPT \"$cl_mnt_opt\" ||\n\terror \"mount lustre on $LUSTRE_CLIENT_NFSSRV failed\"\n\n# setup the nfs\nsetup_nfs \"$NFSVERSION\" \"$NFS_SRVMNTPT\" \"$LUSTRE_CLIENT_NFSSRV\" \\\n\t\t\"$NFS_CLIENTS\" \"$NFS_CLIMNTPT\" ||\n\terror false \"setup nfs failed!\"\n\nNFSCLIENT=true\nFAIL_ON_ERROR=false\n\n# common setup\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\nclients=${NFS_CLIENTS:-$HOSTNAME}\ngenerate_machine_file $clients $MACHINEFILE ||\n\terror \"Failed to generate machine file\"\nnum_clients=$(get_node_count ${clients//,/ })\n\n# compilbench\n# Run short iteration in nfs mode\ncbench_IDIRS=${cbench_IDIRS:-2}\ncbench_RUNS=${cbench_RUNS:-2}\n\n# metabench\n# Run quick in nfs mode\nmbench_NFILES=${mbench_NFILES:-10000}\n\n# connectathon\n[ \"$SLOW\" = \"no\" ] && cnt_NRUN=2\n\n# IOR\nior_DURATION=${ior_DURATION:-30}\n\n# source the common file after all parameters are set to take affect\n. $LUSTRE/tests/functions.sh\n\nbuild_test_filter\n\nget_mpiuser_id $MPI_USER\nMPI_RUNAS=${MPI_RUNAS:-\"runas -u $MPI_USER_UID -g $MPI_USER_GID\"}\n$GSS_KRB5 && refresh_krb5_tgt $MPI_USER_UID $MPI_USER_GID $MPI_RUNAS\n\ntest_compilebench() {\n\trun_compilebench $TESTDIR\n}\nrun_test compilebench \"compilebench\"\n\ntest_metabench() {\n\trun_metabench $TESTDIR $NFS_CLIMNTPT\n}\nrun_test metabench \"metabench\"\n\ntest_connectathon() {\n\trun_connectathon $TESTDIR\n}\nrun_test connectathon \"connectathon\"\n\ntest_iorssf() {\n\trun_ior \"ssf\" $TESTDIR $NFS_SRVMNTPT\n}\nrun_test iorssf \"iorssf\"\n\ntest_iorfpp() {\n\trun_ior \"fpp\" $TESTDIR $NFS_SRVMNTPT\n}\nrun_test iorfpp \"iorfpp\"\n\ntest_racer_on_nfs() {\n\tlocal racer_params=\"MDSCOUNT=$MDSCOUNT OSTCOUNT=$OSTCOUNT LFS=$LFS\"\n\n\tdo_nodes $CLIENTS \"$racer_params $racer $TESTDIR\"\n}\nrun_test racer_on_nfs \"racer on NFS client\"\n\ncomplete $SECONDS\nexit_status\n", "num_lines": 136}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#set -vx\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\nsh $LUSTRE/tests/parallel-scale-nfs.sh 3\n", "num_lines": 10}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#set -vx\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\nsh $LUSTRE/tests/parallel-scale-nfs.sh 4\n", "num_lines": 10}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#set -vx\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n# bug number for skipped test:  LU-9429\n     ALWAYS_EXCEPT=\"            parallel_grouplock  $PARALLEL_SCALE_EXCEPT \"\n\nif [ \"$mds1_FSTYPE\" = zfs -o \"$ost1_FSTYPE\" = zfs ]; then\n\tZFSSLOW=$SLOW\n\tSLOW=no\n\n\tcbench_IDIRS=${cbench_IDIRS:-1}\n\tcbench_RUNS=${cbench_RUNS:-1}\n\n\tmdtest_nFiles=${mdtest_nFiles:-\"10000\"}\n\tstatahead_NUMFILES=${statahead_NUMFILES:-100000}\nfi\n\n# common setup\nMACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\nclients=${CLIENTS:-$HOSTNAME}\ngenerate_machine_file $clients $MACHINEFILE ||\n    error \"Failed to generate machine file\"\nnum_clients=$(get_node_count ${clients//,/ })\n\n# compilbench\nif [ \"$SLOW\" = \"no\" ]; then\n\tcbench_IDIRS=${cbench_IDIRS:-2}\n\tcbench_RUNS=${cbench_RUNS:-2}\nfi\n\n# metabench\n[ \"$SLOW\" = \"no\" ] && mbench_NFILES=${mbench_NFILES:-10000}\n\n# simul\n[ \"$SLOW\" = \"no\" ] && simul_REP=${simul_REP:-2}\n\n# connectathon\n[ \"$SLOW\" = \"no\" ] && cnt_NRUN=${cnt_NRUN:-2}\n\n# cascading rw\n[ \"$SLOW\" = \"no\" ] && casc_REP=${casc_REP:-10}\n\n# IOR\n[ \"$SLOW\" = \"no\" ] && ior_DURATION=${ior_DURATION:-5}\n\n# write_append_truncate\n[ \"$SLOW\" = \"no\" ] && write_REP=${write_REP:-100}\n\n# write_disjoint\n[ \"$SLOW\" = \"no\" ] && wdisjoint_REP=${wdisjoint_REP:-100}\n\n# fs_test\nif [ \"$SLOW\" = \"no\" ]; then\n\tfs_test_ndirs=${fs_test_ndirs:-10000}\n\tfs_test_nobj=${fs_test_nobj:-2}\nfi\n\n# xdd\n[ \"$SLOW\" = \"no\" ] && xdd_passes=${xdd_passes:-15}\n\n. $LUSTRE/tests/functions.sh\n\nbuild_test_filter\ncheck_and_setup_lustre\n\nget_mpiuser_id $MPI_USER\nMPI_RUNAS=${MPI_RUNAS:-\"runas -u $MPI_USER_UID -g $MPI_USER_GID\"}\n$GSS_KRB5 && refresh_krb5_tgt $MPI_USER_UID $MPI_USER_GID $MPI_RUNAS\n\ntest_compilebench() {\n    run_compilebench\n}\nrun_test compilebench \"compilebench\"\n\ntest_metabench() {\n    run_metabench\n}\nrun_test metabench \"metabench\"\n\ntest_simul() {\n    run_simul\n}\nrun_test simul \"simul\"\n\ntest_mdtestssf() {\n    run_mdtest \"ssf\"\n}\nrun_test mdtestssf \"mdtestssf\"\n\ntest_mdtestfpp() {\n    run_mdtest \"fpp\"\n}\nrun_test mdtestfpp \"mdtestfpp\"\n\ntest_connectathon() {\n    run_connectathon\n}\nrun_test connectathon \"connectathon\"\n\ntest_iorssf() {\n    run_ior \"ssf\"\n}\nrun_test iorssf \"iorssf\"\n\ntest_iorfpp() {\n    run_ior \"fpp\"\n}\nrun_test iorfpp \"iorfpp\"\n\ntest_ior_mdtest_parallel_ssf() {\n\tior_mdtest_parallel \"ssf\"\n}\nrun_test ior_mdtest_parallel_ssf \"iormdtestssf\"\n\ntest_ior_mdtest_parallel_fpp() {\n\tior_mdtest_parallel \"fpp\"\n}\nrun_test ior_mdtest_parallel_fpp \"iormdtestfpp\"\n\ntest_mib() {\n    run_mib\n}\nrun_test mib \"mib\"\n\ntest_cascading_rw() {\n    run_cascading_rw\n}\nrun_test cascading_rw \"cascading_rw\"\n\ntest_write_append_truncate() {\n    run_write_append_truncate\n}\nrun_test write_append_truncate \"write_append_truncate\"\n\n# Argument is chunk size limit, the upper bound on write size\ntest_write_disjoint() {\n    run_write_disjoint 123456\n}\nrun_test write_disjoint \"write_disjoint\"\n\n# Make sure to exercise the tiny write code\ntest_write_disjoint_tiny() {\n\trun_write_disjoint 16384\n}\nrun_test write_disjoint_tiny \"write_disjoint_tiny\"\n\ntest_parallel_grouplock() {\n    run_parallel_grouplock\n}\nrun_test parallel_grouplock \"parallel_grouplock\"\n\ntest_statahead () {\n    run_statahead\n}\nrun_test statahead \"statahead test, multiple clients\"\n\ntest_rr_alloc () {\n\trun_rr_alloc\n}\nrun_test rr_alloc \"Checking even file distribution over OSTs in RR policy\"\n\ntest_fs_test () {\n\trun_fs_test\n}\nrun_test fs_test \"fs_test\"\n\ntest_fio () {\n\trun_fio\n}\nrun_test fio \"fio\"\n\ntest_xdd () {\n\trun_xdd\n}\nrun_test xdd \"xdd\"\n\n# If necessary, return SLOW to its original value\n[ \"$mds1_FSTYPE\" = zfs -o \"$ost1_FSTYPE\" = zfs ] &&\n\tSLOW=$ZFSSLOW\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 191}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -vx\nset -e\n\nTESTNAME=`basename $0 .sh`\nTMP=${TMP:-/tmp}\nLOG=${LOG:-\"$TMP/${TESTNAME}.log\"}\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n[ -x \"$MDSRATE\" ] || FAIL_ON_ERROR=true error \"No mdsrate program. Aborting.\"\nwhich mpirun > /dev/null 2>&1 ||\n\tFAIL_ON_ERROR=true error \"No mpirun program. Aborting.\"\n\n# Skip these tests\n# bug number:\nALWAYS_EXCEPT=\"  $PERFORMANCE_SANITY_EXCEPT\"\n\nbuild_test_filter\n\nget_mpiuser_id $MPI_USER\nMPI_RUNAS=${MPI_RUNAS:-\"runas -u $MPI_USER_UID -g $MPI_USER_GID\"}\n$GSS_KRB5 && refresh_krb5_tgt $MPI_USER_UID $MPI_USER_GID $MPI_RUNAS\n\n# mdsrate-create-small\ntest_3() {\n    echo \"File creation performance tests for file objects\"\n    bash mdsrate-create-small.sh\n}\nrun_test 3 \"small file create/open/delete ======\"\n\n# mdsrate-create-large\ntest_4() {\n\t# LU-2600/LU-4108 - Decrease load on zfs\n\t[ \"$SLOW\" = no -a \"$mds1_FSTYPE\" = zfs ] &&\n\t\tNUM_FILES=10000\n\techo \"Large file creation performance\"\n\tbash mdsrate-create-large.sh\n}\nrun_test 4 \"large file create/open/delete\"\n\n# mdsrate-lookup-1dir\ntest_5() {\n    echo \"Single directory lookup retrieval rate\"\n    bash mdsrate-lookup-1dir.sh\n}\nrun_test 5 \"lookup rate 10M file dir ======\"\n\n# mdsrate-lookup-10dir\ntest_6() {\n    echo \"Directory lookup retrieval rate 10 directories, 1 million files each\"\n    bash mdsrate-lookup-10dirs.sh\n}\nrun_test 6 \"lookup rate 10M file 10 dir ======\"\n\n# mdsrate-stat-small\ntest_7() {\n    echo \"File attribute retrieval rate for small file creation\"\n    bash mdsrate-stat-small.sh\n}\nrun_test 7 \"getattr small file ======\"\n\n# mdsrate-stat-large\ntest_8() {\n    echo \"File attribute retrieval rate for large file creation\"\n    bash mdsrate-stat-large.sh\n}\nrun_test 8 \"getattr large files ======\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\n[ -f \"$LOG\" ] && cat $LOG || true\nexit_status\n", "num_lines": 79}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n{\ncat << 'HEADER'\n#!/bin/bash\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$PJDFSTEST_EXCEPT \"\n# bug number for skipped test: LU-12922\t\tLU-1158\nALWAYS_EXCEPT+=\"               chown_00\tutimensat_08\"\nbuild_test_filter\n\nPJDFSTEST_DIR=${PJDFSTEST_DIR:-\"/usr/share/pjdfstest\"}\nPJDFSTEST_BIN=${PJDFSTEST_BIN:-\"/bin/pjdfstest\"}\nEXT4_LOG=${EXT4_LOG:-\"$TMP/pjdfstest-ext4\"}\nLUSTRE_LOG=${LUSTRE_LOG:-\"$TMP/pjdfstest-lustre\"}\n\ncheck_and_setup_lustre\n\nif [[ ! -f $PJDFSTEST_DIR/pjdfstest ]]; then\n\t# copy the bin to the suite dir\n\tif ! cp -af $PJDFSTEST_BIN $PJDFSTEST_DIR; then\n\t\terror \"Copy pjdfstest binary failed\"\n\tfi\nfi\n\nrun_pjdfstest() {\n\tlocal mntpnt=$1\n\tlocal pjdfstest=$2\n\tlocal report=$3\n\tlocal rc=0\n\tlocal cmd\n\n\twhich prove > /dev/null || skip_env \"must have prove installed\"\n\n\tcmd=\"prove -f $pjdfstest &> $report\"\n\n\tpushd $mntpnt > /dev/null\n\techo $cmd\n\tif ! eval $cmd; then\n\t\trc=${PIPESTATUS[0]}\n\tfi\n\tpopd > /dev/null\n\n\treturn $rc\n}\n\nrun_lustre_ext4() {\n\tlocal pjdfstest=$1\n\n\tlog \"Run $pjdfstest against ext4 filesystem\"\n\trun_pjdfstest $EXT4_MNTPT $pjdfstest $EXT4_LOG\n\n\tlog \"Run $pjdfstest against lustre filesystem\"\n\trun_pjdfstest $MOUNT $pjdfstest $LUSTRE_LOG\n\n}\n\nsetup_ext4() {\n\tlocal loop_file=$1\n\tlocal mntpt=$2\n\tlocal size=${3:-50}\n\n\tmkdir -p $mntpt || error \"mkdir -p $mntpt failed\"\n\tstack_trap \"rm -rf $mntpt\"\n\tdd if=/dev/zero of=$loop_file bs=1M count=$size\n\tstack_trap \"rm -f $loop_file\"\n\tmkfs.ext4 $loop_file > /dev/null ||\n\t\terror \"mkfs.ext4 $loop_file failed\"\n\tfile $loop_file\n\tmount -t ext4 -o loop,usrquota,grpquota $loop_file $mntpt ||\n\t\terror \"mount -o loop,usrquota,grpquota $loop_file $mntpt failed\"\n\tstack_trap \"$UMOUNT $mntpt\"\n}\n\ncompare_report() {\n\tlocal ext4_summary=$TMP/pjdfstest-ext4-summary\n\tlocal lustre_summary=$TMP/pjdfstest-lustre-summary\n\tlocal summary=\"Test Summary Report\"\n\tlocal summary_end=\"Files\"\n\tlocal diff=$TMP/pjdfstest-diff\n\tlocal rc=0\n\n\t# filter out the summary and delete the duration part to compare\n\tsed -n '/'\"$summary\"'/,/'\"$summary_end\"'/p' \"$EXT4_LOG\" |\n\t\tsed '$d'> $ext4_summary\n\tsed -n '/'\"$summary\"'/,/'\"$summary_end\"'/p' \"$LUSTRE_LOG\" |\n\t\tsed '$d' > $lustre_summary\n\tgrep -vf $ext4_summary $lustre_summary > $diff\n\n\t[ -s $diff ] && rc=1\n\tlog \"ext4 report\"\n\tcat $EXT4_LOG || error_noexit \"Cannot open file\"\n\tlog \"lustre report\"\n\tcat $LUSTRE_LOG || error_noexit \"Cannot open file\"\n\n\trm -f $TMP/pjdfstest-* ||\n\t\terror_noexit \"Cannot remove pjdfstest tmp files\"\n\treturn $rc\n}\n\n# All tests will be run on Lustre and an ext4 file system. Set up\n# an ext4 file system\nEXT4_MNTPT=/mnt/pjdfstest.ext4\nLOOP_FILE=$TMP/loop_file\nsetup_ext4 $LOOP_FILE $EXT4_MNTPT\n\n# Create users and groups required by the tests\nmds=$(facet_host mds1)\n\nUSR=(pjd_usr1 pjd_usr2 pjd_usr3)\nUSRID=(65535 65533 65532)\nGRP=(pjd_grp1 pjd_grp2 pjd_grp3)\nGRPID=(65535 65533 65531)\n\nidx=0\nfor grp_id in ${GRPID[@]}; do\n\techo \"setup up GRPID $grp_id for group ${GRP[$idx]} on $mds\"\n\tdo_rpc_nodes $mds add_group $grp_id ${GRP[$idx]}\n\tstack_trap \"do_rpc_nodes $mds groupdel ${GRP[$idx]}\"\n\tidx=$((idx+1))\ndone\n\nidx=0\nfor user_id in ${USRID[@]}; do\n\techo \"setup up USRID $user_id for user ${USR[$idx]}\"\n\tdo_rpc_nodes $mds add_user $user_id ${USR[$idx]} \\\n\t\t${GRPID[$idx]} $DIR/${USR[$idx]}\n\tstack_trap \"do_rpc_nodes $mds userdel ${USR[$idx]}\"\n\tidx=$((idx+1))\ndone\nHEADER\n\nPJDFSTEST_DIR=${PJDFSTEST_DIR:-\"/usr/share/pjdfstest\"}\n# enable globstar so ** can get all dir recursively\nshopt -s globstar\nfor testname in $PJDFSTEST_DIR/**/*.t; do\n\ttest_dir=$(dirname $testname)\n\ttest_grp=$(basename $test_dir)\n\tsub_t=\"${test_grp}_$(basename $testname .t)\"\n\t# execute the \"desc=\" line and set it the environment for our use\n\teval $(grep \"^desc=\" $testname)\n\n\tcat - <<SUBTEST\ntest_$sub_t() {\n\trun_lustre_ext4 $testname\n\tcompare_report || error \"$testname against lustre failed\"\n}\nrun_test $sub_t \"$desc\"\nSUBTEST\ndone\n\ncat << 'TAIL'\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\nTAIL\n} > $TMP/run_pjdfstest.sh\nbash $TMP/run_pjdfstest.sh\n\n", "num_lines": 170}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -vx\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$POSIX_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n[ \"$ALWAYS_EXCEPT$EXCEPT\" ] &&\n\techo \"Skipping tests: $ALWAYS_EXCEPT $EXCEPT\"\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nPOSIX_DIR=${POSIX_DIR:-\"$LUSTRE/tests/posix\"}\nPOSIX_SRC=${POSIX_SRC:-\"/usr/src/posix\"}\nBASELINE_FS=${BASELINE_FS:-\"ext4\"}\n\n# SLES does not support read-write access to an ext4 file system by default\n[[ -e /etc/SuSE-release ]] && BASELINE_FS=ext3\n\nif [[ \"$mds1_FSTYPE\" = zfs ]]; then\n\tBASELINE_FS=zfs\n\t! which $ZFS $ZPOOL >/dev/null 2>&1 &&\n\t\tskip_env \"need $ZFS and $ZPOOL commands\"\n\n\tPOSIX_ZPOOL=$FSNAME-posix\n\tPOSIX_ZFS=$POSIX_ZPOOL/${POSIX_ZPOOL##$FSNAME-}\nfi\n\ncheck_and_setup_lustre\nbuild_test_filter\n\ncleanup_loop_dev() {\n    local mnt=$1\n    local dev=$2\n    local file=$3\n\n    # if we only have 1 arg, we will search for dev\n    if [[ $# = 1 ]]; then\n        dev=$(losetup -a | grep \"$mnt\" | cut -d: -f1)\n        [[ -n $dev ]] && losetup -d $dev\n    else # we need all args\n        [[ -z $mnt ]] || [[ -z $dev ]] || [[ -z $file ]] &&\n            error \"Can't cleanup loop device\"\n        umount -f $mnt\n        losetup -d $dev && rm -rf $mnt\n        rm -f $file\n    fi\n\n\t[[ $BASELINE_FS != zfs ]] || destroy_zpool client $POSIX_ZPOOL\n}\n\nsetup_loop_dev() {\n\tlocal mnt=$1\n\tlocal dev=$2\n\tlocal file=$3\n\tlocal rc=0\n\n\techo \"Make a loop file system with $file on $dev\"\n\tdd if=/dev/zero of=$file bs=1024k count=500 > /dev/null\n\tif ! losetup $dev $file; then\n\t\trc=$?\n\t\techo \"can't set up $dev for $file\"\n\t\treturn $rc\n\tfi\n\n\tif [[ $BASELINE_FS = zfs ]]; then\n\t\tcreate_zpool client $POSIX_ZPOOL $dev || return ${PIPESTATUS[0]}\n\t\tcreate_zfs client $POSIX_ZFS || return ${PIPESTATUS[0]}\n\t\tdev=$POSIX_ZFS\n\n\telif ! eval mkfs.$BASELINE_FS $dev; then\n\t\trc=$?\n\t\techo \"mkfs.$BASELINE_FS on $dev failed\"\n\t\treturn $rc\n\tfi\n\tmkdir -p $mnt\n\tif ! mount -t $BASELINE_FS $dev $mnt; then\n\t\trc=$?\n\t\techo \"mount $BASELINE_FS failed\"\n\t\treturn $rc\n\tfi\n\techo\n\treturn $rc\n}\n\ntest_1() {\n\tlocal allnodes=\"$(comma_list $(nodes_list))\"\n\tlocal tfile=\"$TMP/$BASELINE_FS-file\"\n\tlocal mntpnt=$POSIX_SRC/$BASELINE_FS\n\tlocal loopbase\n\tlocal loopdev\n\tlocal rc=0\n\n\t# We start at loop1 because posix build uses loop0\n\t[ -b /dev/loop/1 ] && loopbase=/dev/loop/\n\t[ -b /dev/loop1 ] && loopbase=/dev/loop\n\tif [ -z \"$loopbase\" ]; then\n\t\t# there is no /dev/loop by default on EL7, LU-6707.\n\t\tload_module loop max_loop=8 || error \"load loop module failed\"\n\t\tloopbase=/dev/loop\n\tfi\n\n\tfor i in $(seq 1 7); do\n\t\tlosetup $loopbase$i > /dev/null 2>&1 && continue || true\n\t\tloopdev=$loopbase$i\n\t\tbreak\n\tdone\n\n\t[ -z \"$loopdev\" ] && error \"Can not find loop device\"\n\n\tif ! setup_loop_dev $mntpnt $loopdev $tfile; then\n\t\tcleanup_loop_dev \"$mntpnt\" \"$loopdev\" \"$tfile\"\n\t\terror \"Setup loop device failed\"\n\tfi\n\n\t# copy the source over to ext mount point\n\tif ! cp -af ${POSIX_SRC}/*.* $mntpnt; then\n\t\tcleanup_loop_dev \"$mntpnt\" \"$loopdev\" \"$tfile\"\n\t\terror \"Copy POSIX test suite failed\"\n\tfi\n\texport POSIX_SRC=$mntpnt\n\t. $POSIX_DIR/posix.cfg\n\n\tsetup_posix_users $allnodes\n\tif ! setup_posix; then\n\t\tdelete_posix_users $allnodes\n\t\tcleanup_loop_dev \"$POSIX_SRC\"\n\t\tcleanup_loop_dev \"$mntpnt\" \"$loopdev\" \"$tfile\"\n\t\terror \"Setup POSIX test suite failed\"\n\tfi\n\n\tlog \"Run POSIX test against lustre filesystem\"\n\trun_posix $MOUNT $MGSNID $FSNAME compare ||\n\t\terror_noexit \"Run POSIX testsuite on $MOUNT failed\"\n\n\t[[ -d \"$MOUNT/TESTROOT\" ]] && rm -fr $MOUNT/TESTROOT\n\tdelete_posix_users $allnodes\n\tcleanup_loop_dev \"$POSIX_SRC\"\n\tcleanup_loop_dev \"$mntpnt\" \"$loopdev\" \"$tfile\"\n}\nrun_test 1 \"install, build, run posix on $BASELINE_FS and lustre, then compare\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 153}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -vx\nset -e\n\nONLY=${ONLY:-\"$*\"}\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nracer=$LUSTRE/tests/racer/racer.sh\necho racer: $racer with $MDSCOUNT MDTs\n\nif [ \"$SLOW\" = \"no\" ]; then\n    DURATION=${DURATION:-300}\nelse\n    DURATION=${DURATION:-900}\nfi\nMOUNT_2=${MOUNT_2:-\"yes\"}\n\nbuild_test_filter\ncheck_and_setup_lustre\n\nCLIENTS=${CLIENTS:-$HOSTNAME}\nRACERDIRS=${RACERDIRS:-\"$DIR $DIR2\"}\necho RACERDIRS=$RACERDIRS\n\nRACER_FAILOVER=${RACER_FAILOVER:-false}\nFAIL_TARGETS=${FAIL_TARGETS:-\"MDS OST\"}\nRACER_FAILOVER_PERIOD=${RACER_FAILOVER_PERIOD:-60}\n\nif $RACER_FAILOVER; then\n\tdeclare -a  victims\n\tfor target in $FAIL_TARGETS; do\n\t\tvictims=(${victims[@]} $(get_facets $target))\n\tdone\n\techo Victim facets ${victims[@]}\nfi\n\n#LU-4684\nRACER_ENABLE_MIGRATION=false\n\nif ((MDSCOUNT > 1 && \"$MDS1_VERSION\" >= $(version_code 2.8.0))); then\n\tRACER_ENABLE_REMOTE_DIRS=${RACER_ENABLE_REMOTE_DIRS:-true}\n\tRACER_ENABLE_STRIPED_DIRS=${RACER_ENABLE_STRIPED_DIRS:-true}\n\tRACER_ENABLE_MIGRATION=${RACER_ENABLE_MIGRATION:-true}\nelif ((MDSCOUNT > 1 && \"$MDS1_VERSION\" >= $(version_code 2.5.0))); then\n\tRACER_ENABLE_REMOTE_DIRS=${RACER_ENABLE_REMOTE_DIRS:-true}\nfi\n\n[[ \"$MDS1_VERSION\" -lt $(version_code 2.9.54) ||\n   $(facet_fstype mgs) != zfs ]] && RACER_ENABLE_SNAPSHOT=false\n\n[[ \"$MDS1_VERSION\" -le $(version_code 2.9.55) ]] &&\n\tRACER_ENABLE_PFL=false\n\n[[ \"$MDS1_VERSION\" -le $(version_code 2.10.53) ]] &&\n\tRACER_ENABLE_DOM=false\n\n[[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ]] &&\n\tRACER_ENABLE_FLR=false\n\n[[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.12.0) ]] &&\n\tRACER_ENABLE_SEL=false\n\nRACER_ENABLE_REMOTE_DIRS=${RACER_ENABLE_REMOTE_DIRS:-false}\nRACER_ENABLE_STRIPED_DIRS=${RACER_ENABLE_STRIPED_DIRS:-false}\nRACER_ENABLE_MIGRATION=${RACER_ENABLE_MIGRATION:-false}\nRACER_ENABLE_SNAPSHOT=${RACER_ENABLE_SNAPSHOT:-true}\nRACER_ENABLE_PFL=${RACER_ENABLE_PFL:-true}\nRACER_ENABLE_DOM=${RACER_ENABLE_DOM:-true}\nRACER_ENABLE_FLR=${RACER_ENABLE_FLR:-true}\nRACER_ENABLE_SEL=${RACER_ENABLE_SEL:-true}\n\nfail_random_facet () {\n\tlocal facets=${victims[@]}\n\tfacets=${facets// /,}\n\n\tsleep $RACER_FAILOVER_PERIOD\n\twhile [ ! -f $racer_done ]; do\n\t\tlocal facet=$(get_random_entry $facets)\n\t\tfacet_failover $facet\n\t\tsleep $RACER_FAILOVER_PERIOD\n\tdone\n}\n\n# run racer\ntest_1() {\n\tlocal rrc=0\n\tlocal rc=0\n\tlocal clients=$CLIENTS\n\tlocal RDIRS\n\tlocal i\n\tlocal racer_done=$TMP/racer_done\n\n\trm -f $racer_done\n\n\tfor d in ${RACERDIRS}; do\n\t\tis_mounted $d || continue\n\n\t\tRDIRS=\"$RDIRS $d/racer\"\n\t\tmkdir -p $d/racer\n\t#\tlfs setstripe $d/racer -c -1\n\t\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t\tfor i in $(seq $((MDSCOUNT - 1))); do\n\t\t\t\tRDIRS=\"$RDIRS $d/racer$i\"\n\t\t\t\tif [ ! -e $d/racer$i ]; then\n\t\t\t\t\t$LFS mkdir -i $i $d/racer$i ||\n\t\t\t\t\t\terror \"lfs mkdir $i failed\"\n\t\t\t\tfi\n\t\t\tdone\n\t\tfi\n\tdone\n\n\tlocal rpids=\"\"\n\tfor rdir in $RDIRS; do\n\t\tdo_nodes $clients \"DURATION=$DURATION \\\n\t\t\tMDSCOUNT=$MDSCOUNT OSTCOUNT=$OSTCOUNT\\\n\t\t\tRACER_ENABLE_REMOTE_DIRS=$RACER_ENABLE_REMOTE_DIRS \\\n\t\t\tRACER_ENABLE_STRIPED_DIRS=$RACER_ENABLE_STRIPED_DIRS \\\n\t\t\tRACER_ENABLE_MIGRATION=$RACER_ENABLE_MIGRATION \\\n\t\t\tRACER_ENABLE_PFL=$RACER_ENABLE_PFL \\\n\t\t\tRACER_ENABLE_DOM=$RACER_ENABLE_DOM \\\n\t\t\tRACER_ENABLE_FLR=$RACER_ENABLE_FLR \\\n\t\t\tRACER_MAX_CLEANUP_WAIT=$RACER_MAX_CLEANUP_WAIT \\\n\t\t\tRACER_ENABLE_SEL=$RACER_ENABLE_SEL \\\n\t\t\tLFS=$LFS \\\n\t\t\tLCTL=$LCTL \\\n\t\t\t$racer $rdir $NUM_RACER_THREADS\" &\n\t\tpid=$!\n\t\trpids=\"$rpids $pid\"\n\tdone\n\n\tlocal failpid=\"\"\n\tif $RACER_FAILOVER; then\n\t\tfail_random_facet &\n\t\tfailpid=$!\n\t\techo racers failpid: $failpid\n\tfi\n\n\tlocal lss_pids=\"\"\n\tif $RACER_ENABLE_SNAPSHOT; then\n\t\tlss_gen_conf\n\n\t\t$LUSTRE/tests/racer/lss_create.sh &\n\t\tpid=$!\n\t\tlss_pids=\"$lss_pids $pid\"\n\n\t\t$LUSTRE/tests/racer/lss_destroy.sh &\n\t\tpid=$!\n\t\tlss_pids=\"$lss_pids $pid\"\n\tfi\n\n\techo racers pids: $rpids\n\tfor pid in $rpids; do\n\t\twait $pid\n\t\trc=$?\n\t\techo \"pid=$pid rc=$rc\"\n\t\tif [ $rc != 0 ]; then\n\t\t    rrc=$((rrc + 1))\n\t\tfi\n\tdone\n\n\tif $RACER_FAILOVER; then\n\t\ttouch $racer_done\n\t\twait $failpid\n\t\trrc=$((rrc + $?))\n\tfi\n\n\tif $RACER_ENABLE_SNAPSHOT; then\n\t\tkillall -q lss_create.sh\n\t\tkillall -q lss_destroy.sh\n\n\t\tfor pid in $lss_pids; do\n\t\t\twait $pid\n\t\tdone\n\n\t\tlss_cleanup\n\tfi\n\n\treturn $rrc\n}\nrun_test 1 \"racer on clients: ${CLIENTS:-$(hostname)} DURATION=$DURATION\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 189}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# All pairwise combinations of node failures.\n# Was cmd3-17\n#\n# Author: Chris Cooper <ccooper@clusterfs.com>\n#\n# Script fails pair of nodes:\n# --  in parallel by default\n# --  in series if SERIAL is set\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$RECOVERY_DOUBLE_SCALE_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nremote_mds_nodsh && skip_env \"remote MDS with nodsh\" && exit 0\nremote_ost_nodsh && skip_env \"remote OST with nodsh\" && exit 0\n\n[ -z \"$CLIENTS\" -o $CLIENTCOUNT -lt 3 ] &&\n    skip_env \"need three or more clients\" && exit 0\n\nif [ -z \"$SHARED_DIRECTORY\" ] || ! check_shared_dir $SHARED_DIRECTORY; then\n    skip_env \"SHARED_DIRECTORY should be specified with a shared directory \\\nwhich is accessable on all of the nodes\"\n    exit 0\nfi\n\n[[ $FAILURE_MODE = SOFT ]] && \\\n    log \"WARNING: $0 is not functional with FAILURE_MODE = SOFT, bz22797\"\n\n# Set SERIAL to serialize the failure through a recovery of the first failure.\nSERIAL=${SERIAL:-\"\"}\nERRORS_OK=\"yes\"\n\n[ \"$SERIAL\" ] && ERRORS_OK=\"\"\n\nFAILOVER_PERIOD=${FAILOVER_PERIOD:-$((60 * 5))} # 5 minutes\n\nEND_RUN_FILE=${END_RUN_FILE:-$SHARED_DIRECTORY/end_run_file}\nLOAD_PID_FILE=${LOAD_PID_FILE:-$TMP/client-load.pid}\n\nreboot_recover_node () {\n    # item var contains a pair of clients if nodetype=clients\n    # I would prefer to have a list here\n    local item=$1\n    local nodetype=$2\n    local c\n\n    # MDS, OST item contains the facet\n    case $nodetype in\n        MDS|OST )   facet_failover $item\n                    [ \"$SERIAL\" ] && wait_recovery_complete $item || true\n                    ;;\n        clients)    for c in ${item//,/ }; do\n                        # make sure the client loads die\n                        stop_process $c $LOAD_PID_FILE\n                        shutdown_client $c\n                        boot_node $c\n                        echo \"Reintegrating $c\"\n                        zconf_mount $c $MOUNT ||\n                            error \"mount $MOUNT on $c failed\"\n                        client_up $c || error \"start client on $c failed\"\n                    done\n                    start_client_loads $item\n                    ;;\n        * )         echo \"ERROR: invalid nodetype=$nodetype.\" \\\n                         \"Must be one of 'MDS', 'OST', or 'clients'.\"\n                    exit 1;;\n    esac\n}\n\nget_item_type () {\n    local type=$1\n    local excluded=${2:-\"\"}\n\n    local list\n    case $type in\n       MDS )    list=$MDTS;;\n       OST )    list=$OSTS;;\n       clients) list=$NODES_TO_USE;;\n       * )      echo \"ERROR: invalid type=$type.\" \\\n                     \"Must be one of 'MDS', 'OST', or 'clients'.\"\n                exit 1;;\n    esac\n\n    [ \"$excluded\" ] && list=$(exclude_items_from_list $list $excluded)\n    # empty list\n    if [ ! \"$(echo $list)\" ]; then\n        echo\n        return\n    fi\n\n    local item=$(get_random_entry $list)\n    if [ \"$type\" = \"clients\" ]; then\n        item=\"$item $(get_random_entry $(exclude_items_from_list $list $item))\"\n        item=$(comma_list $item)\n    fi\n    echo $item\n}\n\n# failover_pair\n#\n# for the two nodetypes specified, chooses a random node(s) from each\n# class, reboots the nodes sequentially, and then restarts lustre on\n# the nodes.\nfailover_pair() {\n    local type1=$1\n    local type2=$2\n    local title=$3\n\n    local client_nodes=\"\"\n    local item1=\n    local item2=\n    local client1=\n    local client2=\n\n    log \"\n==== START === $title\"\n\n    item1=$(get_item_type $type1)\n    [ \"$item1\" ] || \\\n        { echo \"type1=$type1 item1 is empty\" && return 0; }\n    item2=$(get_item_type $type2 $item1)\n    [ \"$item2\" ] || \\\n        { echo \"type1=$type1 item1=$item1 type2=$type2 item2=$item2 is empty\" \\\n          && return 0; }\n\n    # Check that our client loads are still running. If any have died,\n    # that means they have died outside of recovery, which is unacceptable.\n    log \"==== Checking the clients loads BEFORE failover -- failure NOT OK\"\n    # FIXME. need print summary on exit\n    check_client_loads $NODES_TO_USE || exit $?\n\n    log \"Done checking client loads. Failing type1=$type1 item1=$item1 ... \"\n    reboot_recover_node $item1 $type1 || exit $?\n\n    # Hendrix test17 description:\n    # Introduce a failure, wait at\n    # least 5 minutes (for recovery),\n    # introduce a 2nd\n    # failure, and wait another 5\n    # minutes\n\n    # reboot_recover_node waits recovery in according to\n    # SERIAL value.\n    # We have a \"double failures\" if SERIAL is not set,\n    # do not need a sleep between failures for \"double failures\"\n\n    log \"                            Failing type2=$type2 item2=$item2 ... \"\n    reboot_recover_node $item2 $type2 || exit $?\n\n    # Client loads are allowed to die while in recovery, so we just\n    # restart them.\n    log \"==== Checking the clients loads AFTER failovers -- ERRORS_OK=$ERRORS_OK\"\n    restart_client_loads $NODES_TO_USE $ERRORS_OK || exit $?\n    log \"Done checking / re-starting client loads. PASS\"\n    return 0\n}\n\nsummary_and_cleanup () {\n    local rc=$?\n    trap 0\n\n    CURRENT_TS=$(date +%s)\n    ELAPSED=$((CURRENT_TS - START_TS))\n\n    # Having not empty END_RUN_FILE means the failed loads only\n    if [ -s $END_RUN_FILE ]; then\n        print_end_run_file $END_RUN_FILE\n        rc=1\n    fi\n\n    echo $(date +'%F %H:%M:%S') Terminating clients loads ...\n    echo \"$0\" >> $END_RUN_FILE\n    local result=PASS\n    [ $rc -eq 0 ] || result=FAIL\n\n    log \"\nServer failover period: $FAILOVER_PERIOD seconds\nExited after:           $ELAPSED seconds\nStatus: $result: rc=$rc\"\n\n    # stop the client loads\n    stop_client_loads $NODES_TO_USE $LOAD_PID_FILE\n\n\tif [ $rc -ne 0 ]; then\n\t\t# we are interested in only on failed clients and servers\n\t\tlocal failedclients=$(cat $END_RUN_FILE | grep -v $0)\n\t\tgather_logs $(comma_list $(all_server_nodes) $failedclients)\n\tfi\n\n    exit $rc\n}\n\n################################## Main Flow ###################################\ncheck_and_setup_lustre\nrm -rf $DIR/[Rdfs][0-9]*\n\ncheck_timeout || exit 1\n\n# The test node needs to be insulated from a lustre failure as much as possible,\n# so not even loading the lustre modules is ideal.\n# -- umount lustre\n# -- remove hostname from clients list\nzconf_umount $HOSTNAME $MOUNT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNODES_TO_USE=$(exclude_items_from_list $NODES_TO_USE $HOSTNAME)\n\ncheck_progs_installed $NODES_TO_USE ${CLIENT_LOADS[@]}\n\nMDTS=$(get_facets MDS)\nOSTS=$(get_facets OST)\n\nELAPSED=0\nSTART_TS=$(date +%s)\nCURRENT_TS=$START_TS\n\n# Every pairwise combination of client failures (2 clients),\n# MDS failure, and OST failure will be tested.\ntest_pairwise_fail() {\n    trap summary_and_cleanup EXIT TERM INT\n\n    # Start client loads.\n    rm -f $END_RUN_FILE\n    start_client_loads $NODES_TO_USE\n\n    echo clients load pids:\n    do_nodesv $NODES_TO_USE \"cat $LOAD_PID_FILE\" || exit 3\n\n    # FIXME: Do we want to have an initial sleep period where the clients\n    # just run before introducing a failure?\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.1\n    failover_pair MDS OST \"test 1: failover MDS, then OST ==========\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.2\n    failover_pair MDS clients \"test 2: failover MDS, then 2 clients ====\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.3\n    if [ $MDSCOUNT -gt 1 ]; then\n        failover_pair MDS MDS \"test 3: failover MDS, then another MDS ==\"\n        sleep $FAILOVER_PERIOD\n    else\n        skip_env \"has less than 2 MDTs, test 3 skipped\"\n    fi\n\n    # CMD_TEST_NUM=17.4\n    if [ $OSTCOUNT -gt 1 ]; then\n        failover_pair OST OST \"test 4: failover OST, then another OST ==\"\n        sleep $FAILOVER_PERIOD\n    else\n        skip_env \"has less than 2 OSTs, test 4 skipped\"\n    fi\n\n    # CMD_TEST_NUM=17.5\n    failover_pair OST clients \"test 5: failover OST, then 2 clients ====\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.6\n    failover_pair OST MDS \"test 6: failover OST, then MDS ==========\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.7\n    failover_pair clients MDS \"test 7: failover 2 clients, then MDS ====\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.8\n    failover_pair clients OST \"test 8: failover 2 clients, then OST ====\"\n    sleep $FAILOVER_PERIOD\n\n    # CMD_TEST_NUM=17.9\n    if [ $CLIENTCOUNT -gt 4 ]; then\n        failover_pair clients clients \\\n            \"test 9: failover 2 clients, then 2 different clients ==\"\n        sleep $FAILOVER_PERIOD\n    else\n        skip_env \"has less than 5 Clients, test 9 skipped\"\n    fi\n\n    log \"==== Checking the clients loads AFTER all failovers -- failure NOT OK\"\n    if ! check_client_loads $NODES_TO_USE; then\n        log \"Client load failed after failover. Exiting...\"\n        exit 5\n    fi\n\n    exit 0\n}\nrun_test pairwise_fail \"pairwise combination of clients, MDS, and OST failures\"\n\nzconf_mount $HOSTNAME $MOUNT || error \"mount $MOUNT on $HOSTNAME failed\"\nclient_up || error \"start client on $HOSTNAME failed\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 309}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Was Test 11 in cmd3.\n# For duration of 24 hours repeatedly failover a random MDS at\n# 10 minute intervals and verify that no application errors occur.\n\n# Test runs one of CLIENT_LOAD progs on remote clients.\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$RECOVERY_MDS_SCALE_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nremote_mds_nodsh && skip_env \"remote MDS with nodsh\" && exit 0\nremote_ost_nodsh && skip_env \"remote OST with nodsh\" && exit 0\n\n[ -z \"$CLIENTS\" -o $CLIENTCOUNT -lt 3 ] &&\n    skip_env \"need three or more clients\" && exit 0\n\nif [ -z \"$SHARED_DIRECTORY\" ] || ! check_shared_dir $SHARED_DIRECTORY; then\n    skip_env \"SHARED_DIRECTORY should be specified with a shared directory \\\nwhich is accessable on all of the nodes\"\n    exit 0\nfi\n\nERRORS_OK=\"\"    # No application failures should occur during this test.\n\nif [ \"$SLOW\" = \"no\" ]; then\n    DURATION=${DURATION:-$((60 * 30))}\nelse\n    DURATION=${DURATION:-$((60 * 60 * 24))}\nfi\nSERVER_FAILOVER_PERIOD=${SERVER_FAILOVER_PERIOD:-$((60 * 10))} # 10 minutes\n\nMINSLEEP=${MINSLEEP:-120}\nREQFAIL_PERCENT=${REQFAIL_PERCENT:-3}    # bug17839 comment 62\n# round up the result of integer division: C=(A + (B - 1)) / B\nREQFAIL=${REQFAIL:-$(((DURATION * REQFAIL_PERCENT + (SERVER_FAILOVER_PERIOD *\n\t100 - 1 )) / SERVER_FAILOVER_PERIOD / 100))}\n\nEND_RUN_FILE=${END_RUN_FILE:-$SHARED_DIRECTORY/end_run_file}\nLOAD_PID_FILE=${LOAD_PID_FILE:-$TMP/client-load.pid}\nVMSTAT_PID_FILE=${VMSTAT_PID_FILE:-$TMP/vmstat.pid}\n\nserver_numfailovers () {\n    local facet=$1\n    local var=${facet}_numfailovers\n    local val=0\n\n    [[ ${!var} ]] && val=${!var}\n    echo $val\n}\n\nservers_numfailovers () {\n    local facet\n    local var\n\n    for facet in ${MDTS//,/ } ${OSTS//,/ }; do\n        echo \"$facet: $(server_numfailovers $facet) times\"\n    done\n}\n\nsummary_and_cleanup () {\n    local rc=$?\n    trap 0\n\n    # Having not empty END_RUN_FILE means the failed loads only\n    if [ -s $END_RUN_FILE ]; then\n        print_end_run_file $END_RUN_FILE\n        rc=1\n    fi\n\n    echo $(date +'%F %H:%M:%S') Terminating clients loads ...\n    echo \"$0\" >> $END_RUN_FILE\n    local result=PASS\n    [ $rc -eq 0 ] || result=FAIL\n\n    log \"Duration:               $DURATION\nServer failover period: $SERVER_FAILOVER_PERIOD seconds\nExited after:           $ELAPSED seconds\nNumber of failovers before exit:\n$(servers_numfailovers)\nStatus: $result: rc=$rc\"\n\n    # stop vmstat on OSS nodes\n    [ \"$VMSTAT\" ] && stop_process $(comma_list $(osts_nodes)) $VMSTAT_PID_FILE\n\n    # stop the client loads\n    stop_client_loads $NODES_TO_USE $LOAD_PID_FILE\n\n\tif [ $rc -ne 0 ]; then\n\t\t# we are interested in only on failed clients and servers\n\t\tlocal failedclients=$(cat $END_RUN_FILE | grep -v $0)\n\t\tgather_logs $(comma_list $(all_server_nodes) $failedclients)\n\tfi\n\n    exit $rc\n}\n\nfailover_target() {\n    local flavor=${1:-\"MDS\"}\n    local servers\n    local serverfacet\n    local var\n\n    [ \"$flavor\" = \"MDS\" ] && servers=$MDTS || servers=$OSTS\n\n    trap summary_and_cleanup EXIT INT\n\n    # start vmstat on OSS nodes\n    [ \"$VMSTAT\" ] && start_vmstat $(comma_list $(osts_nodes)) $VMSTAT_PID_FILE\n\n    # start client loads\n    rm -f $END_RUN_FILE\n    start_client_loads $NODES_TO_USE\n\n    echo client loads pids:\n    do_nodesv $NODES_TO_USE \"cat $LOAD_PID_FILE\" || exit 3\n\n    ELAPSED=0\n    local sleep=0\n    local reqfail=0\n    local it_time_start\n    local start_ts=$(date +%s)\n    local current_ts=$start_ts\n\n    while [ $ELAPSED -lt $DURATION -a ! -e $END_RUN_FILE ]; do\n        # In order to perform the\n        # expected number of failovers, we need to account the following:\n        # 1) the time that has elapsed during the client load checking\n        # 2) time takes for failover\n        it_time_start=$(date +%s)\n\n        serverfacet=$(get_random_entry $servers)\n        var=${serverfacet}_numfailovers\n\n        # Check that our client loads are still running. If any have died,\n        # that means they have died outside of recovery, which is unacceptable.\n        log \"==== Checking the clients loads BEFORE failover -- failure NOT OK \\\n             ELAPSED=$ELAPSED DURATION=$DURATION PERIOD=$SERVER_FAILOVER_PERIOD\"\n        check_client_loads $NODES_TO_USE || exit 4\n\n        log \"Wait $serverfacet recovery complete before doing next failover...\"\n        if ! wait_recovery_complete $serverfacet; then\n            echo \"$serverfacet recovery is not completed!\"\n            exit 7\n        fi\n\n        log \"Checking clients are in FULL state before doing next failover...\"\n        if ! wait_clients_import_state $NODES_TO_USE $serverfacet FULL; then\n            echo \"Clients import not FULL, please consider to increase \\\nSERVER_FAILOVER_PERIOD=$SERVER_FAILOVER_PERIOD!\"\n        fi\n\n        log \"Starting failover on $serverfacet\"\n        facet_failover \"$serverfacet\" || exit 1\n\n        # Check that our client loads are still running during failover.\n        # No application failures should occur.\n        log \"==== Checking the clients loads AFTER failover -- failure NOT OK\"\n        if ! check_client_loads $NODES_TO_USE; then\n            log \"Client load failed during failover. Exiting...\"\n            exit 5\n        fi\n\n        # Increment the number of failovers.\n        val=$((${!var} + 1))\n        eval $var=$val\n\n        current_ts=$(date +%s)\n        ELAPSED=$((current_ts - start_ts))\n\n        sleep=$((SERVER_FAILOVER_PERIOD - (current_ts - it_time_start)))\n\n        # Keep counting the number of iterations when\n        # time spent to failover and two client loads check exceeded\n        # the value ( SERVER_FAILOVER_PERIOD - MINSLEEP ).\n        if [ $sleep -lt $MINSLEEP ]; then\n            reqfail=$((reqfail + 1))\n            log \"WARNING: failover and two check_client_loads time exceeded \\\nSERVER_FAILOVER_PERIOD - MINSLEEP!\nFailed to load the filesystem with I/O for a minimum period of \\\n$MINSLEEP $reqfail times ( REQFAIL=$REQFAIL ).\nThis iteration, the load was only applied for sleep=$sleep seconds.\nEstimated max recovery time: $MAX_RECOV_TIME\nProbably the hardware is taking excessively long time to boot.\nTry to increase SERVER_FAILOVER_PERIOD (current is $SERVER_FAILOVER_PERIOD), \\\nbug 20918\"\n            [ $reqfail -gt $REQFAIL ] && exit 6\n        fi\n\n        log \"$serverfacet has failed over ${!var} times, and counting...\"\n\n        [ $((ELAPSED + sleep)) -ge $DURATION ] && break\n\n        if [ $sleep -gt 0 ]; then\n            echo \"sleeping $sleep seconds... \"\n            sleep $sleep\n        fi\n    done\n    exit 0\n}\n\n################################## Main Flow ###################################\ncheck_and_setup_lustre\nrm -rf $DIR/[Rdfs][0-9]*\n\nMAX_RECOV_TIME=$(max_recovery_time)\n\n# The test node needs to be insulated from a lustre failure as much as possible,\n# so not even loading the lustre modules is ideal.\n# -- umount lustre\n# -- remove hostname from clients list\nzconf_umount $HOSTNAME $MOUNT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNODES_TO_USE=$(exclude_items_from_list $NODES_TO_USE $HOSTNAME)\n\ncheck_progs_installed $NODES_TO_USE ${CLIENT_LOADS[@]}\n\nMDTS=$(get_facets MDS)\nOSTS=$(get_facets OST)\n\ntest_failover_mds() {\n    # failover a random MDS\n    failover_target MDS\n}\nrun_test failover_mds \"failover MDS\"\n\ntest_failover_ost() {\n    # failover a random OST\n    failover_target OST\n}\nrun_test failover_ost \"failover OST\"\n\nzconf_mount $HOSTNAME $MOUNT || error \"mount $MOUNT on $HOSTNAME failed\"\nclient_up || error \"start client on $HOSTNAME failed\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 250}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# client failure does not affect other clients\n\n# Start load on clients (each client works on it's own directory).\n# At defined (5-10 minutes) interval fail one random client and then fail mds.\n# Reintegrate failed client after recovery completed,\n# application errors are allowed for that client but not on other clients.\n# 10 minute intervals and verify that no application errors occur.\n\n# Test runs one of CLIENT_LOAD progs on remote clients.\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$RECOVERY_RANDOM_SCALE_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nremote_mds_nodsh && skip_env \"remote MDS with nodsh\" && exit 0\nremote_ost_nodsh && skip_env \"remote OST with nodsh\" && exit 0\n\n[ -z \"$CLIENTS\" -o $CLIENTCOUNT -lt 3 ] &&\n    skip_env \"need three or more clients\" && exit 0\n\nif [ -z \"$SHARED_DIRECTORY\" ] || ! check_shared_dir $SHARED_DIRECTORY; then\n    skip_env \"SHARED_DIRECTORY should be specified with a shared directory \\\nwhich is accessable on all of the nodes\"\n    exit 0\nfi\n\n[[ $FAILURE_MODE = SOFT ]] && \\\n    log \"WARNING: $0 is not functional with FAILURE_MODE = SOFT, bz22797\"\n\n# Application failures are allowed for the failed client\n# but not for other clients.\nERRORS_OK=\"yes\"\n\nif [ \"$SLOW\" = \"no\" ]; then\n    DURATION=${DURATION:-$((60 * 30))}\nelse\n    DURATION=${DURATION:-$((60 * 60 * 24))}\nfi\nSERVER_FAILOVER_PERIOD=${SERVER_FAILOVER_PERIOD:-$((60 * 10))} # 10 minutes\n\nMINSLEEP=${MINSLEEP:-120}\nREQFAIL_PERCENT=${REQFAIL_PERCENT:-3}    # bug17839 comment 62\n# round up the result of integer division: C=(A + (B - 1)) / B\nREQFAIL=${REQFAIL:-$(((DURATION * REQFAIL_PERCENT + (SERVER_FAILOVER_PERIOD *\n\t100 - 1 )) / SERVER_FAILOVER_PERIOD / 100))}\n\nEND_RUN_FILE=${END_RUN_FILE:-$SHARED_DIRECTORY/end_run_file}\nLOAD_PID_FILE=${LOAD_PID_FILE:-$TMP/client-load.pid}\nVMSTAT_PID_FILE=${VMSTAT_PID_FILE:-$TMP/vmstat.pid}\n\nnumfailovers () {\n    local facet\n    local var\n\n    for facet in $MDTS ${FAILED_CLIENTS//,/ }; do\n        var=${facet}_nums\n        val=${!var}\n        if [ \"$val\" ] ; then\n            echo \"$facet failed over $val times\"\n        fi\n    done\n}\n\nsummary_and_cleanup () {\n    local rc=$?\n    trap 0\n\n    # Having not empty END_RUN_FILE means the failed loads only\n    if [ -s $END_RUN_FILE ]; then\n        print_end_run_file $END_RUN_FILE\n        rc=1\n    fi\n\n    echo $(date +'%F %H:%M:%S') Terminating clients loads ...\n    echo \"$0\" >> $END_RUN_FILE\n    local result=PASS\n    [ $rc -eq 0 ] || result=FAIL\n\n    log \"Duration:               $DURATION\nServer failover period: $SERVER_FAILOVER_PERIOD seconds\nExited after:           $ELAPSED seconds\nNumber of failovers before exit:\n$(numfailovers)\nStatus: $result: rc=$rc\"\n\n    # stop vmstat on OSS nodes\n    [ \"$VMSTAT\" ] && stop_process $(comma_list $(osts_nodes)) $VMSTAT_PID_FILE\n\n    # stop the client loads\n    stop_client_loads $NODES_TO_USE $LOAD_PID_FILE\n\n\tif [ $rc -ne 0 ]; then\n\t\t# we are interested in only on failed clients and servers\n\t\tlocal failedclients=$(cat $END_RUN_FILE | grep -v $0)\n\t\tgather_logs $(comma_list $(all_server_nodes) $failedclients)\n\tfi\n\n    exit $rc\n}\n\n################################## Main Flow ###################################\ncheck_and_setup_lustre\nrm -rf $DIR/[Rdfs][0-9]*\n\nMAX_RECOV_TIME=$(max_recovery_time)\n\n# The test node needs to be insulated from a lustre failure as much as possible,\n# so not even loading the lustre modules is ideal.\n# -- umount lustre\n# -- remove hostname from clients list\nzconf_umount $HOSTNAME $MOUNT\nNODES_TO_USE=${NODES_TO_USE:-$CLIENTS}\nNODES_TO_USE=$(exclude_items_from_list $NODES_TO_USE $HOSTNAME)\n\ncheck_progs_installed $NODES_TO_USE ${CLIENT_LOADS[@]}\n\nMDTS=$(get_facets MDS)\n\n# Fail a random client and then failover a random MDS.\ntest_fail_client_mds() {\n    local fail_client\n    local serverfacet\n    local client_var\n    local var\n\n    trap summary_and_cleanup EXIT INT\n\n    # start vmstat on OSS nodes\n    [ \"$VMSTAT\" ] && start_vmstat $(comma_list $(osts_nodes)) $VMSTAT_PID_FILE\n\n    # start client loads\n    rm -f $END_RUN_FILE\n    start_client_loads $NODES_TO_USE\n\n    echo client loads pids:\n    do_nodesv $NODES_TO_USE \"cat $LOAD_PID_FILE\" || exit 3\n\n    ELAPSED=0\n    local sleep=0\n    local reqfail=0\n    local it_time_start\n    local start_ts=$(date +%s)\n    local current_ts=$start_ts\n\n    while [ $ELAPSED -lt $DURATION -a ! -e $END_RUN_FILE ]; do\n        # In order to perform the\n        # expected number of failovers, we need to account the following:\n        # 1) the time that has elapsed during the client load checking\n        # 2) time takes for failover\n        it_time_start=$(date +%s)\n\n        fail_client=$(get_random_entry $NODES_TO_USE)\n        client_var=$(node_var_name $fail_client)_nums\n\n        # store the list of failed clients\n        # lists are comma separated\n        FAILED_CLIENTS=$(expand_list $FAILED_CLIENTS $fail_client)\n\n        serverfacet=$(get_random_entry $MDTS)\n        var=${serverfacet}_nums\n\n        # Check that our client loads are still running. If any have died,\n        # that means they have died outside of recovery, which is unacceptable.\n        log \"==== Checking the clients loads BEFORE failover -- failure NOT OK \\\n             ELAPSED=$ELAPSED DURATION=$DURATION PERIOD=$SERVER_FAILOVER_PERIOD\"\n        check_client_loads $NODES_TO_USE || exit 4\n\n        log \"FAIL CLIENT $fail_client...\"\n        shutdown_client $fail_client\n\n        log \"Starting failover on $serverfacet\"\n        facet_failover \"$serverfacet\" || exit 1\n\n        if ! wait_recovery_complete $serverfacet; then\n            echo \"$serverfacet recovery is not completed!\"\n            exit 7\n        fi\n\n        boot_node $fail_client\n        echo \"Reintegrating $fail_client\"\n        zconf_mount $fail_client $MOUNT || exit $?\n        client_up $fail_client || exit $?\n\n        # Increment the number of failovers\n        val=$((${!var} + 1))\n        eval $var=$val\n        val=$((${!client_var} + 1))\n        eval $client_var=$val\n\n        # load script on failed clients could create END_RUN_FILE\n        # We shuold remove it and ignore the failure if this\n        # file contains the failed client only.\n        # We can not use ERRORS_OK when start all loads at the start of\n        # this script because the application errors allowed for random\n        # failed client only, but not for all clients.\n        if [ -e $END_RUN_FILE ]; then\n            local end_run_node\n            read end_run_node < $END_RUN_FILE\n            [[ $end_run_node = $fail_client ]] &&\n                rm -f $END_RUN_FILE || exit 13\n        fi\n\n        restart_client_loads $fail_client $ERRORS_OK || exit $?\n\n        # Check that not failed clients loads are still running.\n        # No application failures should occur on clients that were not failed.\n        log \"==== Checking the clients loads AFTER failed client reintegrated \\\n-- failure NOT OK\"\n        if ! ERRORS_OK= check_client_loads \\\n            $(exclude_items_from_list $NODES_TO_USE $fail_client); then\n            log \"Client load failed. Exiting...\"\n            exit 5\n        fi\n\n        current_ts=$(date +%s)\n        ELAPSED=$((current_ts - start_ts))\n        sleep=$((SERVER_FAILOVER_PERIOD - (current_ts - it_time_start)))\n\n        # Keep counting the number of iterations when\n        # time spent to failover and two client loads check exceeded\n        # the value ( SERVER_FAILOVER_PERIOD - MINSLEEP ).\n        if [ $sleep -lt $MINSLEEP ]; then\n            reqfail=$((reqfail + 1))\n            log \"WARNING: failover, client reintegration and \\\ncheck_client_loads time exceeded SERVER_FAILOVER_PERIOD - MINSLEEP!\nFailed to load the filesystem with I/O for a minimum period of \\\n$MINSLEEP $reqfail times ( REQFAIL=$REQFAIL ).\nThis iteration, the load was only applied for sleep=$sleep seconds.\nEstimated max recovery time : $MAX_RECOV_TIME\nProbably the hardware is taking excessively long time to boot.\nTry to increase SERVER_FAILOVER_PERIOD (current is $SERVER_FAILOVER_PERIOD), \\\nbug 20918\"\n            [ $reqfail -gt $REQFAIL ] && exit 6\n        fi\n\n        log \"Number of failovers:\n$(numfailovers)                and counting...\"\n\n        [ $((ELAPSED + sleep)) -ge $DURATION ] && break\n\n        if [ $sleep -gt 0 ]; then\n            echo \"sleeping $sleep seconds... \"\n            sleep $sleep\n        fi\n    done\n    exit 0\n}\nrun_test fail_client_mds \"fail client, then failover MDS\"\n\nzconf_mount $HOSTNAME $MOUNT || error \"mount $MOUNT on $HOSTNAME failed\"\nclient_up || error \"start client on $HOSTNAME failed\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 268}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nPTLDEBUG=${PTLDEBUG:--1}\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$RECOVERY_SMALL_EXCEPT \"\nif $SHARED_KEY; then\n\t# bug number for skipped test: LU-12896\n\tALWAYS_EXCEPT+=\"               110k\"\n\t# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\nfi\n\nbuild_test_filter\n\nrequire_dsh_mds || exit 0\n\n# Allow us to override the setup if we already have a mounted system by\n# setting SETUP=\" \" and CLEANUP=\" \"\nSETUP=${SETUP:-\"\"}\nCLEANUP=${CLEANUP:-\"\"}\n\ncheck_and_setup_lustre\n\nassert_DIR\nrm -rf $DIR/d[0-9]* $DIR/f.${TESTSUITE}*\n\ntest_1() {\n\tlocal f1=\"$DIR/$tfile\"\n\tlocal f2=\"$DIR/$tfile.2\"\n\n\tdrop_request \"mcreate $f1\" ||\n\t\terror_noexit \"create '$f1': drop req\"\n\n\tdrop_reint_reply \"mcreate $f2\" ||\n\t\terror_noexit \"create '$f2': drop rep\"\n\n\tdrop_request \"tchmod 111 $f2\" ||\n\t\terror_noexit \"chmod '$f2': drop req\"\n\n\tdrop_reint_reply \"tchmod 666 $f2\" ||\n\t\terror_noexit \"chmod '$f2': drop rep\"\n\n\tdrop_request \"statone $f2\" ||\n\t\terror_noexit \"stat '$f2': drop req\"\n\n\tdrop_reply  \"statone $f2\" ||\n\t\terror_noexit \"stat '$f2': drop rep\"\n}\nrun_test 1 \"create, chmod, stat: drop req, drop rep\"\n\ntest_4() {\n\tlocal t=$DIR/$tfile\n\tdo_facet_create_file client $t 10K ||\n\t\terror_noexit \"Create file $t\"\n\n\tdrop_request \"cat $t > /dev/null\" ||\n\t\terror_noexit \"Open request for $t file\"\n\n\tdrop_reply \"cat $t > /dev/null\" ||\n\t\terror_noexit \"Open replay for $t file\"\n}\nrun_test 4 \"open: drop req, drop rep\"\n\ntest_5() {\n\tlocal T=$DIR/$tfile\n\tlocal R=\"$T-renamed\"\n\tlocal RR=\"$T-renamed-again\"\n\tdo_facet_create_file client $T 10K ||\n\t\terror_noexit \"Create file $T\"\n\n\tdrop_request \"mv $T $R\" ||\n\t\terror_noexit \"Rename $T\"\n\n\tdrop_reint_reply \"mv $R $RR\" ||\n\t\terror_noexit \"Failed rename replay on $R\"\n\n\tdo_facet client \"checkstat -v $RR\" ||\n\t\terror_noexit \"checkstat error on $RR\"\n\n\tdo_facet client \"rm $RR\" ||\n\t\terror_noexit \"Can't remove file $RR\"\n}\nrun_test 5 \"rename: drop req, drop rep\"\n\ntest_6() {\n\tlocal T=$DIR/$tfile\n\tlocal LINK1=$DIR/$tfile.link1\n\tlocal LINK2=$DIR/$tfile.link2\n\n\tdo_facet_create_file client $T 10K ||\n\t\terror_noexit \"Create file $T\"\n\n\tdrop_request \"mlink $T $LINK1\" ||\n\t\terror_noexit \"mlink request for $T\"\n\n\tdrop_reint_reply \"mlink $T $LINK2\" ||\n\t\terror_noexit \"mlink reply for $T\"\n\n\tdrop_request \"munlink $LINK1\" ||\n\t\terror_noexit \"munlink request for $T\"\n\n\tdrop_reint_reply \"munlink $LINK2\" ||\n\t\terror_noexit \"munlink reply for $T\"\n\n\tdo_facet client \"rm $T\" ||\n\t\terror_noexit \"Can't remove file $T\"\n}\nrun_test 6 \"link, unlink: drop req, drop rep\"\n\n#bug 1423\ntest_8() {\n    drop_reint_reply \"touch $DIR/$tfile\"    || return 1\n}\nrun_test 8 \"touch: drop rep (bug 1423)\"\n\n#bug 1420\ntest_9() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tlocal t1=${tfile}.1\n\tlocal t2=${tfile}.2\n\tdo_facet_random_file client $TMP/$tfile 1K ||\n\t\terror_noexit \"Create random file $TMP/$tfile\"\n\t# make this big, else test 9 doesn't wait for bulk -- bz 5595\n\tdo_facet_create_file client $TMP/$t1 4M ||\n\t\terror_noexit \"Create file $TMP/$t1\"\n\tdo_facet client \"cp $TMP/$t1 $DIR/$t1\" ||\n\t\terror_noexit \"Can't copy to $DIR/$t1 file\"\n\tpause_bulk \"cp $TMP/$tfile $DIR/$tfile\" ||\n\t\terror_noexit \"Can't pause_bulk copy\"\n\tdo_facet client \"cp $TMP/$t1 $DIR/$t2\" ||\n\t\terror_noexit \"Can't copy file\"\n\tdo_facet client \"sync\"\n\tdo_facet client \"rm $DIR/$tfile $DIR/$t2 $DIR/$t1\" ||\n\t\terror_noexit \"Can't remove files\"\n\tdo_facet client \"rm $TMP/$t1 $TMP/$tfile\"\n}\nrun_test 9 \"pause bulk on OST (bug 1420)\"\n\n#bug 1521\ntest_10a() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\tdo_facet client \"stat $DIR > /dev/null\"  ||\n\t\terror \"failed to stat $DIR: $?\"\n\tdrop_bl_callback \"chmod 0777 $DIR\" ||\n\t\terror \"failed to chmod $DIR: $?\"\n\n\t# let the client reconnect\n\tclient_reconnect\n\tevict=$(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\t[ ! -z \"$evict\" ] && [[ $evict -gt $before ]] ||\n\t\t(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state;\n\t\t    error \"no eviction: $evict before:$before\")\n\n\tdo_facet client checkstat -v -p 0777 $DIR ||\n\t\terror \"client checkstat failed: $?\"\n}\nrun_test 10a \"finish request on server after client eviction (bug 1521)\"\n\ntest_10b() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.6.53) ]] &&\n\t\tskip \"Need MDS version at least 2.6.53\"\n\tdo_facet client \"stat $DIR > /dev/null\"  ||\n\t\terror \"failed to stat $DIR: $?\"\n\tdrop_bl_callback_once \"chmod 0777 $DIR\" ||\n\t\terror \"failed to chmod $DIR: $?\"\n\n\t# let the client reconnect\n\tclient_reconnect\n\tevict=$(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] ||\n\t\t(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state;\n\t\t    error \"eviction happened: $evict before:$before\")\n\n\tdo_facet client checkstat -v -p 0777 $DIR ||\n \t\terror \"client checkstat failed: $?\"\n}\nrun_test 10b \"re-send BL AST\"\n\ntest_10c() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\tlocal mdccli\n\tlocal mdcpath\n\tlocal conn_uuid\n\tlocal workdir\n\tlocal pid\n\tlocal rc\n\n\tworkdir=\"${DIR}/${tdir}\"\n\tmkdir -p ${workdir} || error \"can't create workdir $?\"\n\tstat ${workdir} > /dev/null ||\n\t\terror \"failed to stat ${workdir}: $?\"\n\tmdtidx=$($LFS getdirstripe -i ${workdir})\n\tmdtname=$($LFS mdts ${workdir} | grep -e \"^$mdtidx:\" |\n\t\t  awk '{sub(\"_UUID\", \"\", $2); print $2;}')\n\t#assume one client\n\tmdccli=$($LCTL dl | grep \"${mdtname}-mdc\" | awk '{print $4;}')\n\tconn_uuid=$($LCTL get_param -n mdc.${mdccli}.conn_uuid)\n\tmdcpath=\"mdc.${mdccli}.import=connection=${conn_uuid}\"\n\n\tdrop_bl_callback_once \"chmod 0777 ${workdir}\" &\n\tpid=$!\n\n\t# let chmod blocked\n\tsleep 1\n\t# force client reconnect\n\t$LCTL set_param \"${mdcpath}\"\n\n\t# wait client reconnect\n\tclient_reconnect\n\twait $pid\n\trc=$?\n\tevict=$($LCTL get_param mdc.${mdccli}.state |\n\t   awk -F\"[ [,]\" '/EVICTED]$/ { if (t<$4) {t=$4;} } END { print t }')\n\n\t[[ $evict -le $before ]] ||\n\t\t( $LCTL get_param mdc.$FSNAME-MDT*.state;\n\t\t    error \"eviction happened: $EVICT before:$BEFORE\" )\n\n\t[ $rc -eq 0 ] || error \"chmod must finished OK\"\n\tcheckstat -v -p 0777 \"${workdir}\" ||\n\t\terror \"client checkstat failed: $?\"\n}\nrun_test 10c \"re-send BL AST vs reconnect race (LU-5569)\"\n\ntest_10d() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.6.90) ]] &&\n\t\tskip \"Need MDS version at least 2.6.90\"\n\n\t# sleep 1 is to make sure that BEFORE is not equal to EVICTED below\n\tsleep 1\n\trm -f $TMP/$tfile\n\techo -n \", world\" | dd of=$TMP/$tfile bs=1c seek=5\n\n\tremount_client $MOUNT\n\tmount_client $MOUNT2\n\n\tcancel_lru_locks osc\n\t$LFS setstripe -i 0 -c 1 $DIR1/$tfile\n\techo -n hello | dd of=$DIR1/$tfile bs=5\n\n\tstat $DIR2/$tfile >& /dev/null\n\t$LCTL set_param fail_err=71\n\tdrop_bl_callback \"echo -n \\\\\\\", world\\\\\\\" >> $DIR2/$tfile\"\n\n\tclient_reconnect\n\n\tcancel_lru_locks osc\n\tcmp -l $DIR1/$tfile $DIR2/$tfile || error \"file contents differ\"\n\tcmp -l $DIR1/$tfile $TMP/$tfile || error \"wrong content found\"\n\n\tevict=$(do_facet client $LCTL get_param osc.$FSNAME-OST0000*.state | \\\n\t\ttr -d '\\-\\[\\] ' | \\\n\t  awk -F\"[ [,]\" '/EVICTED$/ { if (mx<$1) {mx=$1;} } END { print mx }')\n\n\t[[ $evict -gt $before ]] ||\n\t\t(do_facet client $LCTL get_param osc.$FSNAME-OST0000*.state;\n\t\t    error \"no eviction: $evict before:$before\")\n\n\t$LCTL set_param fail_err=0\n\trm $TMP/$tfile\n\tumount_client $MOUNT2\n}\nrun_test 10d \"test failed blocking ast\"\n\ntest_10e()\n{\n\t[[ \"$OST1_VERSION\" -le $(version_code 2.8.58) ]] &&\n\t\tskip \"Need OST version at least 2.8.59\"\n\t[ $CLIENTCOUNT -lt 2 ] && skip \"need two clients\"\n\t[ $(facet_host client) == $(facet_host ost1) ] &&\n\t\tskip \"need ost1 and client on different nodes\"\n\tlocal -a clients=(${CLIENTS//,/ })\n\tlocal client1=${clients[0]}\n\tlocal client2=${clients[1]}\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile-1 $DIR/$tfile-2\n\t$MULTIOP $DIR/$tfile-1 Ow1048576c\n\n#define OBD_FAIL_LDLM_BL_CALLBACK_NET                   0x305\n\t$LCTL set_param fail_loc=0x80000305\n\n#define OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT 0x30e\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x1000030e\"\n\t# hit OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT twice:\n\t# 1. to return ENOTCONN from ldlm_handle_enqueue0\n\t# 2. to pause reconnect handling between resend and setting\n\t# import to LUSTRE_IMP_FULL state\n\tdo_facet ost1 \"$LCTL set_param fail_val=3\"\n\n\t# client1 fails ro respond to bl ast\n\tdo_node $client2 \"$MULTIOP $DIR/$tfile-1 Ow1048576c\" &\n\tMULTIPID=$!\n\n\t# ost1 returns error on enqueue, which causes client1 to reconnect\n\tdo_node $client1 \"$MULTIOP $DIR/$tfile-2 Ow1048576c\" ||\n\t\terror \"multiop failed\"\n\twait $MULTIPID\n\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0\"\n\tdo_facet ost1 \"$LCTL set_param fail_val=0\"\n}\nrun_test 10e \"re-send BL AST vs reconnect race 2\"\n\n#bug 2460\n# wake up a thread waiting for completion after eviction\ntest_11(){\n\tdo_facet client $MULTIOP $DIR/$tfile Ow  ||\n\t\t{ error \"multiop write failed: $?\"; return 1; }\n\tdo_facet client $MULTIOP $DIR/$tfile or  ||\n\t\t{ error \"multiop read failed: $?\"; return 2; }\n\n\tcancel_lru_locks osc\n\n\tdo_facet client $MULTIOP $DIR/$tfile or  ||\n\t\t{ error \"multiop read failed: $?\"; return 3; }\n\tdrop_bl_callback_once $MULTIOP $DIR/$tfile Ow ||\n\t\techo \"evicted as expected\"\n\n\tdo_facet client munlink $DIR/$tfile ||\n\t\t{ error \"munlink failed: $?\"; return 4; }\n\t# allow recovery to complete\n\tclient_up || client_up || sleep $TIMEOUT\n}\nrun_test 11 \"wake up a thread waiting for completion after eviction (b=2460)\"\n\n#b=2494\ntest_12(){\n\t$LCTL mark $MULTIOP $DIR/$tfile OS_c\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x115\"\n\tclear_failloc $SINGLEMDS $((TIMEOUT * 2)) &\n\tmultiop_bg_pause $DIR/$tfile OS_c ||\n\t\t{ error \"multiop failed: $?\"; return 1; }\n\tPID=$!\n#define OBD_FAIL_MDS_CLOSE_NET           0x115\n\tkill -USR1 $PID\n\techo \"waiting for multiop $PID\"\n\twait $PID || { error \"wait for multiop faile: $?\"; return 2; }\n\tdo_facet client munlink $DIR/$tfile ||\n\t\t{ error \"client munlink failed: $?\"; return 3; }\n\t# allow recovery to complete\n\tclient_up || client_up || sleep $TIMEOUT\n}\nrun_test 12 \"recover from timed out resend in ptlrpcd (b=2494)\"\n\n# Bug 113, check that readdir lost recv timeout works.\ntest_13() {\n\tmkdir -p $DIR/$tdir || { error \"mkdir failed: $?\"; return 1; }\n\ttouch $DIR/$tdir/newentry || { error \"touch failed: $?\"; return 2; }\n# OBD_FAIL_MDS_READPAGE_NET|OBD_FAIL_ONCE\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000104\"\n\tls $DIR/$tdir || { error \"ls failed: $?\"; return 3; }\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\trm -rf $DIR/$tdir || { error \"remove test dir failed: $?\"; return 4; }\n}\nrun_test 13 \"mdc_readpage restart test (bug 1138)\"\n\n# Bug 113, check that readdir lost send timeout works.\ntest_14() {\n    mkdir -p $DIR/$tdir\n    touch $DIR/$tdir/newentry\n# OBD_FAIL_MDS_SENDPAGE|OBD_FAIL_ONCE\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000106\"\n    ls $DIR/$tdir || return 1\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n}\nrun_test 14 \"mdc_readpage resend test (bug 1138)\"\n\ntest_15() {\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000128\"\n    touch $DIR/$tfile && return 1\n    return 0\n}\nrun_test 15 \"failed open (-ENOMEM)\"\n\nREAD_AHEAD=`lctl get_param -n llite.*.max_read_ahead_mb | head -n 1`\nstop_read_ahead() {\n   lctl set_param -n llite.*.max_read_ahead_mb 0\n}\n\nstart_read_ahead() {\n   lctl set_param -n llite.*.max_read_ahead_mb $READ_AHEAD\n}\n\ntest_16() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tdo_facet_random_file client $TMP/$tfile 100K ||\n\t\t{ error_noexit \"Create random file $TMP/$T\" ; return 0; }\n\tdo_facet client \"cp $TMP/$tfile $DIR/$tfile\" ||\n\t\t{ error_noexit \"Copy to $DIR/$tfile file\" ; return 0; }\n\tsync\n\tstop_read_ahead\n\n#define OBD_FAIL_PTLRPC_BULK_PUT_NET 0x504 | OBD_FAIL_ONCE\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000504\"\n\tcancel_lru_locks osc\n\t# OST bulk will time out here, client resends\n\tdo_facet client \"cmp $TMP/$tfile $DIR/$tfile\" || return 1\n\tdo_facet ost1 lctl set_param fail_loc=0\n\t# give recovery a chance to finish (shouldn't take long)\n\tsleep $TIMEOUT\n\tdo_facet client \"cmp $TMP/$tfile $DIR/$tfile\" || return 2\n\tstart_read_ahead\n\trm -f $TMP/$tfile\n}\nrun_test 16 \"timeout bulk put, don't evict client (2732)\"\n\ntest_17a() {\n    local at_max_saved=0\n\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tlocal SAMPLE_FILE=$TMP/$tfile\n\tdo_facet_random_file client $SAMPLE_FILE 20K ||\n\t\t{ error_noexit \"Create random file $SAMPLE_FILE\" ; return 0; }\n\n    # With adaptive timeouts, bulk_get won't expire until adaptive_timeout_max\n    if at_is_enabled; then\n        at_max_saved=$(at_max_get ost1)\n        at_max_set $TIMEOUT ost1\n    fi\n\n    # OBD_FAIL_PTLRPC_BULK_GET_NET 0x0503 | OBD_FAIL_ONCE\n    # OST bulk will time out here, client retries\n    do_facet ost1 lctl set_param fail_loc=0x80000503\n    # need to ensure we send an RPC\n    do_facet client cp $SAMPLE_FILE $DIR/$tfile\n    sync\n\n    # with AT, client will wait adaptive_max*factor+net_latency before\n    # expiring the req, hopefully timeout*2 is enough\n    sleep $(($TIMEOUT*2))\n\n    do_facet ost1 lctl set_param fail_loc=0\n    do_facet client \"df $DIR\"\n    # expect cmp to succeed, client resent bulk\n    do_facet client \"cmp $SAMPLE_FILE $DIR/$tfile\" || return 3\n    do_facet client \"rm $DIR/$tfile\" || return 4\n    [ $at_max_saved -ne 0 ] && at_max_set $at_max_saved ost1\n    return 0\n}\nrun_test 17a \"timeout bulk get, don't evict client (2732)\"\n\ntest_17b() {\n\t[ -z \"$RCLIENTS\" ] && skip \"Needs multiple clients\" && return 0\n\n\t# get one of the clients from client list\n\tlocal rcli=$(echo $RCLIENTS | cut -d ' ' -f 1)\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tlocal ldlm_enqueue_min=$(do_facet ost1 find /sys -name ldlm_enqueue_min)\n\t[ -z \"$ldlm_enqueue_min\" ] &&\n\t\tskip \"missing /sys/.../ldlm_enqueue_min\" && return 0\n\n\t$LFS setstripe -i 0 -c 1 -S 1048576 $DIR/$tfile ||\n\t\terror \"setstripe failed\"\n\t$LFS setstripe -i 0 -c 1 -S 1048576 $DIR/${tfile}2 ||\n\t\terror \"setstripe 2 failed\"\n\n\tsave_lustre_params ost1 \"at_history\" > $p\n\tsave_lustre_params ost1 \"bulk_timeout\" >> $p\n\tlocal dev=\"${FSNAME}-OST0000\"\n\tsave_lustre_params ost1 \"obdfilter.$dev.brw_size\" >> $p\n\tlocal ldlm_enqueue_min_save=$(do_facet ost1 cat $ldlm_enqueue_min)\n\n\tlocal new_at_history=15\n\n\tdo_facet ost1 \"$LCTL set_param at_history=$new_at_history\"\n\tdo_facet ost1 \"$LCTL set_param bulk_timeout=30\"\n\tdo_facet ost1 \"echo 30 > /sys/module/ptlrpc/parameters/ldlm_enqueue_min\"\n\n\t# brw_size is required to be 4m so that bulk transfer timeout\n\t# could be simulated with OBD_FAIL_PTLRPC_CLIENT_BULK_CB3\n\tlocal brw_size=$($LCTL get_param -n \\\n\t    osc.$FSNAME-OST0000-osc-[^M]*.import |\n\t    awk '/max_brw_size/{print $2}')\n\tif [ $brw_size -ne 4194304 ]\n\tthen\n\t\tsave_lustre_params ost1 \"obdfilter.$dev.brw_size\" >> $p\n\t\tdo_facet ost1 \"$LCTL set_param obdfilter.$dev.brw_size=4\"\n\t\tremount_client $MOUNT\n\tfi\n\n\t# get service estimate expanded\n\t#define OBD_FAIL_OST_BRW_PAUSE_PACK\t\t 0x224\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x80000224 fail_val=35\"\n\techo \"delay rpc servicing by 35 seconds\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 conv=fdatasync\n\n\tlocal estimate\n\testimate=$($LCTL get_param -n osc.$dev-osc-*.timeouts |\n\t    awk '/portal 6/ {print $5}')\n\techo \"service estimates increased to $estimate\"\n\n\t# let current worst service estimate to get closer to obliteration\n\tsleep $((new_at_history / 3))\n\n\t# start i/o and simulate bulk transfer loss\n\t#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB3     0x520\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0xa0000520 fail_val=1\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=2M count=1 conv=fdatasync,notrunc &\n\tlocal writedd=$!\n\n\t# start lock conflict handling\n\tsleep $((new_at_history / 3))\n\tdo_node $rcli \"dd if=$DIR/$tfile of=/dev/null bs=1M count=1\" &\n\tlocal readdd=$!\n\n\t# obliterate the worst service estimate\n\tsleep $((new_at_history / 3 + 1))\n\tdd if=/dev/zero of=$DIR/${tfile}2 bs=1M count=1\n\n\testimate=$($LCTL get_param -n osc.$dev-osc-*.timeouts |\n\t    awk '/portal 6/ {print $5}')\n\techo \"service estimate dropped to $estimate\"\n\n\twait $writedd\n\t[[ $? == 0 ]] || error \"write failed\"\n\twait $readdd\n\t[[ $? == 0 ]] || error \"read failed\"\n\n\trestore_lustre_params <$p\n\tif [ $brw_size -ne 4194304 ]\n\tthen\n\t\tremount_client $MOUNT || error \"remount_client failed\"\n\tfi\n\tdo_facet ost1 \"echo $ldlm_enqueue_min_save > $ldlm_enqueue_min\"\n}\nrun_test 17b \"timeout bulk get, dont evict client (3582)\"\n\ntest_18a() {\n    [ -z ${ost2_svc} ] && skip_env \"needs 2 osts\" && return 0\n\n\tdo_facet_create_file client $TMP/$tfile 20K ||\n\t\t{ error_noexit \"Create file $TMP/$tfile\" ; return 0; }\n\n    do_facet client mkdir -p $DIR/$tdir\n    f=$DIR/$tdir/$tfile\n\n    cancel_lru_locks osc\n    pgcache_empty || return 1\n\n    # 1 stripe on ost2\n    $LFS setstripe -i 1 -c 1 $f\n    stripe_index=$($LFS getstripe -i $f)\n    if [ $stripe_index -ne 1 ]; then\n        $LFS getstripe $f\n        error \"$f: stripe_index $stripe_index != 1\" && return\n    fi\n\n    do_facet client cp $TMP/$tfile $f\n    sync\n    local osc2dev=`lctl get_param -n devices | grep ${ost2_svc}-osc- | egrep -v 'MDT' | awk '{print $1}'`\n    $LCTL --device $osc2dev deactivate || return 3\n    # my understanding is that there should be nothing in the page\n    # cache after the client reconnects?     \n    rc=0\n    pgcache_empty || rc=2\n    $LCTL --device $osc2dev activate\n    rm -f $f $TMP/$tfile\n    return $rc\n}\nrun_test 18a \"manual ost invalidate clears page cache immediately\"\n\ntest_18b() {\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tdo_facet_create_file client $TMP/$tfile 20K ||\n\t\t{ error_noexit \"Create file $TMP/$tfile\" ; return 0; }\n\n    do_facet client mkdir -p $DIR/$tdir\n    f=$DIR/$tdir/$tfile\n\n    cancel_lru_locks osc\n    pgcache_empty || return 1\n\n    $LFS setstripe -i 0 -c 1 $f\n    stripe_index=$($LFS getstripe -i $f)\n    if [ $stripe_index -ne 0 ]; then\n        $LFS getstripe $f\n        error \"$f: stripe_index $stripe_index != 0\" && return\n    fi\n\n    do_facet client cp $TMP/$tfile $f\n    sync\n    ost_evict_client\n    # allow recovery to complete\n    sleep $((TIMEOUT + 2))\n    # my understanding is that there should be nothing in the page\n    # cache after the client reconnects?     \n    rc=0\n    pgcache_empty || rc=2\n    rm -f $f $TMP/$tfile\n    return $rc\n}\nrun_test 18b \"eviction and reconnect clears page cache (2766)\"\n\ntest_18c() {\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tdo_facet_create_file client $TMP/$tfile 20K ||\n\t\t{ error_noexit \"Create file $TMP/$tfile\" ; return 0; }\n\n    do_facet client mkdir -p $DIR/$tdir\n    f=$DIR/$tdir/$tfile\n\n    cancel_lru_locks osc\n    pgcache_empty || return 1\n\n    $LFS setstripe -i 0 -c 1 $f\n    stripe_index=$($LFS getstripe -i $f)\n    if [ $stripe_index -ne 0 ]; then\n        $LFS getstripe $f\n        error \"$f: stripe_index $stripe_index != 0\" && return\n    fi\n\n    do_facet client cp $TMP/$tfile $f\n    sync\n    ost_evict_client\n\n    # OBD_FAIL_OST_CONNECT_NET2\n    # lost reply to connect request\n    do_facet ost1 lctl set_param fail_loc=0x80000225\n    # force reconnect\n    sleep 1\n    $LFS df $MOUNT > /dev/null 2>&1\n    sleep 2\n    # my understanding is that there should be nothing in the page\n    # cache after the client reconnects?\n    rc=0\n    pgcache_empty || rc=2\n    rm -f $f $TMP/$tfile\n    return $rc\n}\nrun_test 18c \"Dropped connect reply after eviction handing (14755)\"\n\ntest_19a() {\n\tlocal BEFORE=`date +%s`\n\tlocal EVICT\n\n\tmount_client $DIR2 || error \"failed to mount $DIR2\"\n\n\t# cancel cached locks from OST to avoid eviction from it\n\tcancel_lru_locks osc\n\n\tdo_facet client \"stat $DIR > /dev/null\"  ||\n\t\terror \"failed to stat $DIR: $?\"\n\tdrop_ldlm_cancel \"chmod 0777 $DIR2\" ||\n\t\terror \"failed to chmod $DIR2\"\n\n\tumount_client $DIR2\n\n\t# let the client reconnect\n\tclient_reconnect\n\tEVICT=$(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state |\n\t\tawk -F\"[ [,]\" '/EVICTED ]$/ \\\n\t\t\t{ if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ ! -z \"$EVICT\" ] && [[ $EVICT -gt $BEFORE ]] ||\n\t\t(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state;\n\t\t    error \"no eviction: $EVICT before:$BEFORE\")\n}\nrun_test 19a \"test expired_lock_main on mds (2867)\"\n\ntest_19b() {\n\tlocal BEFORE=`date +%s`\n\tlocal EVICT\n\n\tmount_client $DIR2 || error \"failed to mount $DIR2: $?\"\n\n\t# cancel cached locks from MDT to avoid eviction from it\n\tcancel_lru_locks mdc\n\n\tdo_facet client $MULTIOP $DIR/$tfile Ow ||\n\t\terror \"failed to run multiop: $?\"\n\tdrop_ldlm_cancel $MULTIOP $DIR2/$tfile Ow ||\n\t\terror \"failed to ldlm_cancel: $?\"\n\n\tumount_client $DIR2 || error \"failed to unmount $DIR2: $?\"\n\tdo_facet client munlink $DIR/$tfile ||\n\t\terror \"failed to unlink $DIR/$tfile: $?\"\n\n\t# let the client reconnect\n\tclient_reconnect\n\tEVICT=$(do_facet client $LCTL get_param osc.$FSNAME-OST*.state |\n\t\tawk -F\"[ [,]\" '/EVICTED ]$/ \\\n\t\t\t{ if (mx < $5) {mx = $5;} } END { print mx }')\n\n\t[ ! -z \"$EVICT\" ] && [[ $EVICT -gt $BEFORE ]] ||\n\t\t(do_facet client $LCTL get_param osc.$FSNAME-OST*.state;\n\t\t    error \"no eviction: $EVICT before:$BEFORE\")\n}\nrun_test 19b \"test expired_lock_main on ost (2867)\"\n\ntest_19c() {\n\tlocal BEFORE=`date +%s`\n\n\tmount_client $DIR2\n\t$LCTL set_param ldlm.namespaces.*.early_lock_cancel=0\n\n\tmkdir -p $DIR1/$tfile\n\tstat $DIR1/$tfile\n\n#define OBD_FAIL_PTLRPC_CANCEL_RESEND 0x516\n\tdo_facet mds $LCTL set_param fail_loc=0x80000516\n\n\ttouch $DIR2/$tfile/file1 &\n\tPID1=$!\n\t# let touch to get blocked on the server\n\tsleep 2\n\n\twait $PID1\n\t$LCTL set_param ldlm.namespaces.*.early_lock_cancel=1\n\tumount_client $DIR2\n\n\t# let the client reconnect\n\tsleep 5\n\tEVICT=$(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$EVICT\" ] || [[ $EVICT -le $BEFORE ]] || error \"eviction happened\"\n}\nrun_test 19c \"check reconnect and lock resend do not trigger expired_lock_main\"\n\ntest_20a() {\t# bug 2983 - ldlm_handle_enqueue cleanup\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir/${tfile}\n\tmultiop_bg_pause $DIR/$tdir/${tfile} O_wc || return 1\n\tMULTI_PID=$!\n\tcancel_lru_locks osc\n#define OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR 0x308\n\tdo_facet ost1 lctl set_param fail_loc=0x80000308\n\tkill -USR1 $MULTI_PID\n\twait $MULTI_PID\n\trc=$?\n\t[ $rc -eq 0 ] && error \"multiop didn't fail enqueue: rc $rc\" || true\n}\nrun_test 20a \"ldlm_handle_enqueue error (should return error)\" \n\ntest_20b() {\t# bug 2986 - ldlm_handle_enqueue error during open\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir/${tfile}\n\tcancel_lru_locks osc\n#define OBD_FAIL_LDLM_ENQUEUE_EXTENT_ERR 0x308\n\tdo_facet ost1 lctl set_param fail_loc=0x80000308\n\tdd if=/etc/hosts of=$DIR/$tdir/$tfile && \\\n\t\terror \"didn't fail open enqueue\" || true\n}\nrun_test 20b \"ldlm_handle_enqueue error (should return error)\"\n\ntest_21a() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       close_pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000129\"\n       $MULTIOP $DIR/$tdir-2/f Oc &\n       open_pid=$!\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n       kill -USR1 $close_pid\n       cancel_lru_locks mdc\n       wait $close_pid || return 1\n       wait $open_pid || return 2\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 3\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 4\n\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21a \"drop close request while close and open are both in flight\"\n\ntest_21b() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       close_pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n       mcreate $DIR/$tdir-2/f &\n       open_pid=$!\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       kill -USR1 $close_pid\n       cancel_lru_locks mdc\n       wait $close_pid || return 1\n       wait $open_pid || return 3\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 4\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 5\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21b \"drop open request while close and open are both in flight\"\n\ntest_21c() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       close_pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n       mcreate $DIR/$tdir-2/f &\n       open_pid=$!\n       sleep 3\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n       kill -USR1 $close_pid\n       cancel_lru_locks mdc\n       wait $close_pid || return 1\n       wait $open_pid || return 2\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 2\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 3\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21c \"drop both request while close and open are both in flight\"\n\ntest_21d() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000129\"\n       $MULTIOP $DIR/$tdir-2/f Oc &\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000122\"\n       kill -USR1 $pid\n       cancel_lru_locks mdc\n       wait $pid || return 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 2\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 3\n\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21d \"drop close reply while close and open are both in flight\"\n\ntest_21e() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000119\"\n       touch $DIR/$tdir-2/f &\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       kill -USR1 $pid\n       cancel_lru_locks mdc\n       wait $pid || return 1\n\n       sleep $TIMEOUT\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 2\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 3\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21e \"drop open reply while close and open are both in flight\"\n\ntest_21f() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000119\"\n       touch $DIR/$tdir-2/f &\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000122\"\n       kill -USR1 $pid\n       cancel_lru_locks mdc\n       wait $pid || return 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 2\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 3\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21f \"drop both reply while close and open are both in flight\"\n\ntest_21g() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000119\"\n       touch $DIR/$tdir-2/f &\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n       kill -USR1 $pid\n       cancel_lru_locks mdc\n       wait $pid || return 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 2\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 3\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21g \"drop open reply and close request while close and open are both in flight\"\n\ntest_21h() {\n       mkdir -p $DIR/$tdir-1\n       mkdir -p $DIR/$tdir-2\n       multiop_bg_pause $DIR/$tdir-1/f O_c || return 1\n       pid=$!\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n       touch $DIR/$tdir-2/f &\n       touch_pid=$!\n       sleep 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000122\"\n       cancel_lru_locks mdc\n       kill -USR1 $pid\n       wait $pid || return 1\n       do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n       wait $touch_pid || return 2\n\n       $CHECKSTAT -t file $DIR/$tdir-1/f || return 3\n       $CHECKSTAT -t file $DIR/$tdir-2/f || return 4\n       rm -rf $DIR/$tdir-*\n}\nrun_test 21h \"drop open request and close reply while close and open are both in flight\"\n\n# bug 3462 - multiple MDC requests\ntest_22() {\n    f1=$DIR/${tfile}-1\n    f2=$DIR/${tfile}-2\n    \n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n    $MULTIOP $f2 Oc &\n    close_pid=$!\n\n    sleep 1\n    $MULTIOP $f1 msu || return 1\n\n    cancel_lru_locks mdc\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n    wait $close_pid || return 2\n    rm -rf $f2 || return 4\n}\nrun_test 22 \"drop close request and do mknod\"\n\ntest_23() { #b=4561\n    multiop_bg_pause $DIR/$tfile O_c || return 1\n    pid=$!\n    # give a chance for open\n    sleep 5\n\n    # try the close\n    drop_request \"kill -USR1 $pid\"\n\n    fail $SINGLEMDS\n    wait $pid || return 1\n    return 0\n}\nrun_test 23 \"client hang when close a file after mds crash\"\n\ntest_24a() { # bug 11710 details correct fsync() behavior\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir\n\tcancel_lru_locks osc\n\tmultiop_bg_pause $DIR/$tdir/$tfile Owy_wyc || return 1\n\tMULTI_PID=$!\n\tost_evict_client\n\tkill -USR1 $MULTI_PID\n\twait $MULTI_PID\n\trc=$?\n\tlctl set_param fail_loc=0x0\n\tclient_reconnect\n\t[ $rc -eq 0 ] &&\n\t\terror_ignore bz5494 \"multiop didn't fail fsync: rc $rc\" || true\n}\nrun_test 24a \"fsync error (should return error)\"\n\nwait_client_evicted () {\n\tlocal facet=$1\n\tlocal exports=$2\n\tlocal varsvc=${facet}_svc\n\n\twait_update $(facet_active_host $facet) \\\n\t\t\"lctl get_param -n *.${!varsvc}.num_exports | cut -d' ' -f2\" \\\n\t\t$((exports - 1)) $3\n}\n\ntest_24b() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tdmesg -c > /dev/null\n\tmkdir -p $DIR/$tdir\n\tlfs setstripe $DIR/$tdir -S 0 -i 0 -c 1 ||\n\t\terror \"$LFS setstripe failed\"\n\tcancel_lru_locks osc\n\tmultiop_bg_pause $DIR/$tdir/$tfile-1 Ow8192_yc ||\n\t\terror \"mulitop Ow8192_yc failed\"\n\n\tMULTI_PID1=$!\n\tmultiop_bg_pause $DIR/$tdir/$tfile-2 Ow8192_c ||\n\t\terror \"mulitop Ow8192_c failed\"\n\n\tMULTI_PID2=$!\n\tost_evict_client\n\n\tkill -USR1 $MULTI_PID1\n\twait $MULTI_PID1\n\trc1=$?\n\tkill -USR1 $MULTI_PID2\n\twait $MULTI_PID2\n\trc2=$?\n\tlctl set_param fail_loc=0x0\n\tclient_reconnect\n\t[ $rc1 -eq 0 -o $rc2 -eq 0 ] &&\n\terror_ignore bz5494 \"multiop didn't fail fsync: $rc1 or close: $rc2\" ||\n\t\ttrue\n\n\tdmesg | grep \"dirty page discard:\" ||\n\t\terror \"no discarded dirty page found!\"\n}\nrun_test 24b \"test dirty page discard due to client eviction\"\n\ntest_26a() {      # was test_26 bug 5921 - evict dead exports by pinger\n# this test can only run from a client on a separate node.\n\tremote_ost || { skip \"local OST\" && return 0; }\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\tremote_mds || { skip \"local MDS\" && return 0; }\n\n        if [ $(facet_host mgs) = $(facet_host ost1) ]; then\n                skip \"msg and ost1 are at the same node\"\n                return 0\n        fi\n\n\tcheck_timeout || return 1\n\n# OBD_FAIL_PTLRPC_DROP_RPC 0x505\n\tdo_facet client lctl set_param fail_loc=0x505\n\tlocal before=$(date +%s)\n\tlocal rc=0\n\n\t# evictor takes PING_EVICT_TIMEOUT + 3 * PING_INTERVAL to evict.\n\t# But if there's a race to start the evictor from various obds,\n\t# the loser might have to wait for the next ping.\n\tsleep $((TIMEOUT * 2 + TIMEOUT * 3 / 4))\n\tdo_facet client lctl set_param fail_loc=0x0\n\tdo_facet client df > /dev/null\n\n\tlocal oscs=$(lctl dl | awk '/-osc-/ {print $4}')\n\tcheck_clients_evicted $before ${oscs[@]}\n\tcheck_clients_full 10 ${oscs[@]}\n}\nrun_test 26a \"evict dead exports\"\n\ntest_26b() {      # bug 10140 - evict dead exports by pinger\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n        if [ $(facet_host mgs) = $(facet_host ost1) ]; then\n                skip \"msg and ost1 are at the same node\"\n                return 0\n        fi\n\n\tcheck_timeout || return 1\n\tclients_up\n\tzconf_mount `hostname` $MOUNT2 ||\n                { error \"Failed to mount $MOUNT2\"; return 2; }\n\tsleep 1 # wait connections being established\n\n\tlocal MDS_NEXP=$(do_facet $SINGLEMDS lctl get_param -n mdt.${mds1_svc}.num_exports | cut -d' ' -f2)\n\tlocal OST_NEXP=$(do_facet ost1 lctl get_param -n obdfilter.${ost1_svc}.num_exports | cut -d' ' -f2)\n\n\techo starting with $OST_NEXP OST and $MDS_NEXP MDS exports\n\n\tzconf_umount `hostname` $MOUNT2 -f\n\n\t# PING_INTERVAL max(obd_timeout / 4, 1U)\n\t# PING_EVICT_TIMEOUT (PING_INTERVAL * 6)\n\n\t# evictor takes PING_EVICT_TIMEOUT + 3 * PING_INTERVAL to evict.  \n\t# But if there's a race to start the evictor from various obds, \n\t# the loser might have to wait for the next ping.\n\t# = 9 * PING_INTERVAL + PING_INTERVAL\n\t# = 10 PING_INTERVAL = 10 obd_timeout / 4 = 2.5 obd_timeout\n\t# let's wait $((TIMEOUT * 3)) # bug 19887\n\tlocal rc=0\n\twait_client_evicted ost1 $OST_NEXP $((TIMEOUT * 3)) || \\\n\t\terror \"Client was not evicted by ost\" rc=1\n\twait_client_evicted $SINGLEMDS $MDS_NEXP $((TIMEOUT * 3)) || \\\n\t\terror \"Client was not evicted by mds\"\n}\nrun_test 26b \"evict dead exports\"\n\ntest_27() {\n\tmkdir -p $DIR/$tdir\n\twritemany -q -a $DIR/$tdir/$tfile 0 5 &\n\tCLIENT_PID=$!\n\tsleep 1\n\tlocal save_FAILURE_MODE=$FAILURE_MODE\n\tFAILURE_MODE=\"SOFT\"\n\tfacet_failover $SINGLEMDS\n#define OBD_FAIL_OSC_SHUTDOWN            0x407\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x80000407\n\t# need to wait for reconnect\n\techo waiting for fail_loc\n\twait_update_facet $SINGLEMDS \"lctl get_param -n fail_loc\" \"-2147482617\"\n\tfacet_failover $SINGLEMDS\n\t#no crashes allowed!\n        kill -USR1 $CLIENT_PID\n\twait $CLIENT_PID \n\ttrue\n\tFAILURE_MODE=$save_FAILURE_MODE\n}\nrun_test 27 \"fail LOV while using OSC's\"\n\ntest_28() {      # bug 6086 - error adding new clients\n\tdo_facet client mcreate $DIR/$tfile       || return 1\n\tdrop_bl_callback_once \"chmod 0777 $DIR/$tfile\" ||\n\t\techo \"evicted as expected\"\n\t#define OBD_FAIL_MDS_CLIENT_ADD 0x12f\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000012f\"\n\t# fail once (evicted), reconnect fail (fail_loc), ok\n\tclient_up || (sleep 10; client_up) || (sleep 10; client_up) || error \"reconnect failed\"\n\trm -f $DIR/$tfile\n\tfail $SINGLEMDS\t\t# verify MDS last_rcvd can be loaded\n}\nrun_test 28 \"handle error adding new clients (bug 6086)\"\n\ntest_29a() { # bug 22273 - error adding new clients\n\t#define OBD_FAIL_TGT_CLIENT_ADD 0x711\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000711\"\n\t# fail abort so client will be new again\n\tfail_abort $SINGLEMDS\n\tclient_up || error \"reconnect failed\"\n\twait_osc_import_state $SINGLEMDS ost FULL\n\treturn 0\n}\nrun_test 29a \"error adding new clients doesn't cause LBUG (bug 22273)\"\n\ntest_29b() { # bug 22273 - error adding new clients\n\t#define OBD_FAIL_TGT_CLIENT_ADD 0x711\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000711\"\n\t# fail abort so client will be new again\n\tfail_abort ost1\n\tclient_up || error \"reconnect failed\"\n\treturn 0\n}\nrun_test 29b \"error adding new clients doesn't cause LBUG (bug 22273)\"\n\ntest_50() {\n\tmkdir -p $DIR/$tdir\n\t# put a load of file creates/writes/deletes\n\twritemany -q $DIR/$tdir/$tfile 0 5 &\n\tCLIENT_PID=$!\n\techo writemany pid $CLIENT_PID\n\tsleep 10\n\tFAILURE_MODE=\"SOFT\"\n\tfail $SINGLEMDS\n\t# wait for client to reconnect to MDS\n\tsleep 60\n\tfail $SINGLEMDS\n\tsleep 60\n\tfail $SINGLEMDS\n\t# client process should see no problems even though MDS went down\n\tsleep $TIMEOUT\n        kill -USR1 $CLIENT_PID\n\twait $CLIENT_PID \n\trc=$?\n\techo writemany returned $rc\n\t#these may fail because of eviction due to slow AST response.\n\t[ $rc -eq 0 ] ||\n\t\terror_ignore bz13652 \"writemany returned rc $rc\" || true\n}\nrun_test 50 \"failover MDS under load\"\n\ntest_51() {\n\t#define OBD_FAIL_MDS_SYNC_CAPA_SL                    0x1310\n\tdo_facet ost1 lctl set_param fail_loc=0x00001310\n\n\tmkdir -p $DIR/$tdir\n\t# put a load of file creates/writes/deletes\n\twritemany -q $DIR/$tdir/$tfile 0 5 &\n\tCLIENT_PID=$!\n\tsleep 1\n\tFAILURE_MODE=\"SOFT\"\n\tfacet_failover $SINGLEMDS\n\t# failover at various points during recovery\n\tSEQ=\"1 5 10 $(seq $TIMEOUT 5 $(($TIMEOUT+10)))\"\n        echo will failover at $SEQ\n        for i in $SEQ\n        do\n\t\t#echo failover in $i sec\n\t\tlog \"$TESTNAME: failover in $i sec\"\n\t\tsleep $i\n\t\tfacet_failover $SINGLEMDS\n        done\n\t# client process should see no problems even though MDS went down\n\t# and recovery was interrupted\n\tsleep $TIMEOUT\n        kill -USR1 $CLIENT_PID\n\twait $CLIENT_PID\n\trc=$?\n\techo writemany returned $rc\n\t[ $rc -eq 0 ] ||\n\t\terror_ignore bz13652 \"writemany returned rc $rc\" || true\n}\nrun_test 51 \"failover MDS during recovery\"\n\ntest_52_guts() {\n\tdo_facet client \"mkdir -p $DIR/$tdir\"\n\tdo_facet client \"writemany -q -a $DIR/$tdir/$tfile 300 5\" &\n\tCLIENT_PID=$!\n\techo writemany pid $CLIENT_PID\n\tsleep 10\n\tFAILURE_MODE=\"SOFT\"\n\tfail ost1\n\trc=0\n\twait $CLIENT_PID || rc=$?\n\t# active client process should see an EIO for down OST\n\t[ $rc -eq 5 ] && { echo \"writemany correctly failed $rc\" && return 0; }\n\t# but timing or failover setup may allow success\n\t[ $rc -eq 0 ] && { echo \"writemany succeeded\" && return 0; }\n\techo \"writemany returned $rc\"\n\treturn $rc\n}\n\ntest_52() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\ttest_52_guts\n\trc=$?\n\t[ $rc -ne 0 ] && { return $rc; }\n\t# wait for client to reconnect to OST\n\tsleep 30\n\ttest_52_guts\n\trc=$?\n\t[ $rc -ne 0 ] && { return $rc; }\n\tsleep 30\n\ttest_52_guts\n\trc=$?\n\tclient_reconnect\n\t#return $rc\n}\nrun_test 52 \"failover OST under load\"\n\n# test of open reconstruct\ntest_53() {\n\ttouch $DIR/$tfile\n\tdrop_mdt_ldlm_reply \"openfile -f O_RDWR:O_CREAT -m 0755 $DIR/$tfile\" ||\\\n\t\treturn 2\n}\nrun_test 53 \"touch: drop rep\"\n\ntest_54() {\n\tzconf_mount $(hostname) $MOUNT2\n\ttouch $DIR/$tfile\n\ttouch $DIR2/$tfile.1\n\tsleep 10\n\tcat $DIR2/$tfile.missing # save transno = 0, rc != 0 into last_rcvd\n\tfail $SINGLEMDS\n\tumount $MOUNT2\n\tERROR=$(dmesg | egrep \"(test 54|went back in time)\" | tail -n1 |\n\t\tgrep \"went back in time\")\n\t[ x\"$ERROR\" == x ] || error \"back in time occured\"\n}\nrun_test 54 \"back in time\"\n\n# bug 11330 - liblustre application death during I/O locks up OST\ntest_55() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\n\t# This test assumes relatively small max_dirty_mb setting\n\t# which we want to walk away from, so just for it we will\n\t# temporarily lower the value\n\tlocal max_dirty_mb=$(lctl get_param -n osc.*.max_dirty_mb | head -n 1)\n\tlctl set_param -n osc.*.max_dirty_mb=32\n\tstack_trap \"lctl set_param osc.*.max_dirty_mb=$max_dirty_mb\" EXIT\n\n\t# Minimum pass speed is 2MBps\n\tlocal ddtimeout=64\n\t# LU-2887/LU-3089 - set min pass speed to 500KBps\n\t[ \"$ost1_FSTYPE\" = zfs ] && ddtimeout=256\n\n\t# first dd should be finished quickly\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/$tfile-1\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile-1 bs=32M count=4 &\n\tDDPID=$!\n\tcount=0\n\techo  \"step1: testing ......\"\n\twhile kill -0 $DDPID 2> /dev/null; do\n\t\tlet count++\n\t\tif [ $count -gt $ddtimeout ]; then\n\t\t\terror \"dd should be finished!\"\n\t\tfi\n\t\tsleep 1\n\tdone\n\techo \"(dd_pid=$DDPID, time=$count)successful\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/$tfile-2\n\t#define OBD_FAIL_OST_DROP_REQ            0x21d\n\tdo_facet ost1 lctl set_param fail_loc=0x0000021d\n\t# second dd will be never finished\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile-2 bs=32M count=4 &\n\tDDPID=$!\n\tcount=0\n\techo  \"step2: testing ......\"\n\twhile [ $count -le $ddtimeout ]; do\n\t\tif ! kill -0 $DDPID 2> /dev/null; then\n\t\t\tls -l $DIR/$tdir\n\t\t\terror \"dd shouldn't be finished! (time=$count)\"\n\t\tfi\n\t\tlet count++\n\t\tsleep 1\n\tdone\n\techo \"(dd_pid=$DDPID, time=$count)successful\"\n\n\t#Recover fail_loc and dd will finish soon\n\tdo_facet ost1 lctl set_param fail_loc=0\n\tcount=0\n\techo  \"step3: testing ......\"\n\twhile kill -0 $DDPID 2> /dev/null; do\n\t\tlet count++\n\t\tif [ $count -gt $((ddtimeout + 440)) ]; then\n\t\t\terror \"dd should be finished!\"\n\t\tfi\n\t\tsleep 1\n\tdone\n\techo \"(dd_pid=$DDPID, time=$count)successful\"\n\n\trm -rf $DIR/$tdir\n}\nrun_test 55 \"ost_brw_read/write drops timed-out read/write request\"\n\ntest_56() { # b=11277\n#define OBD_FAIL_MDS_RESEND      0x136\n        touch $DIR/$tfile\n        do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000136\"\n        stat $DIR/$tfile || error \"stat failed\"\n        do_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n        rm -f $DIR/$tfile\n}\nrun_test 56 \"do not fail on getattr resend\"\n\ntest_57_helper() {\n        # no oscs means no client or mdt \n        while lctl get_param osc.*.* > /dev/null 2>&1; do\n                : # loop until proc file is removed\n        done\n}\n\ntest_57() { # bug 10866\n        test_57_helper &\n        pid=$!\n        sleep 1\n#define OBD_FAIL_LPROC_REMOVE            0xB00\n        lctl set_param fail_loc=0x80000B00\n        zconf_umount `hostname` $DIR\n        lctl set_param fail_loc=0x80000B00\n        fail_abort $SINGLEMDS\n        kill -9 $pid\n        lctl set_param fail_loc=0\n        mount_client $DIR\n        do_facet client \"df $DIR\"\n}\nrun_test 57 \"read procfs entries causes kernel crash\"\n\ntest_58() { # bug 11546\n#define OBD_FAIL_MDC_ENQUEUE_PAUSE        0x801\n        touch $DIR/$tfile\n        ls -la $DIR/$tfile\n        lctl set_param fail_loc=0x80000801\n        cp $DIR/$tfile /dev/null &\n        pid=$!\n        sleep 1\n        lctl set_param fail_loc=0\n        drop_bl_callback_once rm -f $DIR/$tfile\n        wait $pid\n        # the first 'df' could tigger the eviction caused by\n        # 'drop_bl_callback_once', and it's normal case.\n        # but the next 'df' should return successfully.\n        do_facet client \"df $DIR\" || do_facet client \"df $DIR\"\n}\nrun_test 58 \"Eviction in the middle of open RPC reply processing\"\n\ntest_59() { # bug 10589\n\tzconf_mount `hostname` $MOUNT2 || error \"Failed to mount $MOUNT2\"\n\techo $DIR2 | grep -q $MOUNT2 || error \"DIR2 is not set properly: $DIR2\"\n#define OBD_FAIL_LDLM_CANCEL_EVICT_RACE  0x311\n\tlctl set_param fail_loc=0x311\n\twrites=$(LANG=C dd if=/dev/zero of=$DIR2/$tfile count=1 2>&1)\n\t[ $? = 0 ] || error \"dd write failed\"\n\twrites=$(echo $writes | awk  -F '+' '/out/ {print $1}')\n\tlctl set_param fail_loc=0\n\tsync\n\tzconf_umount `hostname` $MOUNT2 -f\n\treads=$(LANG=C dd if=$DIR/$tfile of=/dev/null 2>&1)\n\t[ $? = 0 ] || error \"dd read failed\"\n\treads=$(echo $reads | awk -F '+' '/in/ {print $1}')\n\t[ \"$reads\" -eq \"$writes\" ] || error \"read\" $reads \"blocks, must be\" $writes\n}\nrun_test 59 \"Read cancel race on client eviction\"\n\ntest_60() {\n\tlocal num_files=${COUNT:-5000}\n\ttest_mkdir $DIR/$tdir\n\n\t# Register (and start) changelog\n\tchangelog_register || error \"changelog_register failed\"\n\n\t# Generate a large number of changelog entries\n\tcreatemany -o $DIR/$tdir/$tfile $num_files\n\tsync\n\tsleep 5\n\n\t# Unlink files in the background\n\tunlinkmany $DIR/$tdir/$tfile $num_files &\n\tlocal client_pid=$!\n\tsleep 1\n\n\t# Failover the MDS while unlinks are happening\n\tfacet_failover $SINGLEMDS\n\n\t# Wait for unlinkmany to finish\n\twait $client_pid\n\n\t# Check if all the create/unlink events were recorded\n\t# in the changelog\n\tlocal cl_count=$(changelog_dump | grep -c UNLNK)\n\techo \"$cl_count unlinks in changelog\"\n\n\tchangelog_deregister || error \"changelog_deregister failed\"\n\tif ! changelog_users $SINGLEMDS | grep -q \"^cl\"; then\n\t\t[ $cl_count -eq $num_files ] ||\n\t\t\terror \"Recorded $cl_count of $num_files unlinks\"\n\t\t# Also make sure we can clear large changelogs\n\t\tcl_count=$(changelog_dump | wc -l)\n\t\t[ $cl_count -le 2 ] ||\n\t\t\terror \"Changelog not empty: $cl_count entries\"\n\telse # If other users, there may be other unlinks in the log\n\t\t[ $cl_count -ge $num_files ] ||\n\t\t\terror \"Recorded $cl_count of $num_files unlinks\"\n\t\tchangelog_users $SINGLEMDS\n\t\techo \"other changelog users; can't verify clear\"\n\tfi\n}\nrun_test 60 \"Add Changelog entries during MDS failover\"\n\ntest_61()\n{\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $FSNAME-OST0000)\n\tmdtosc=${mdtosc/-MDT*/-MDT\\*}\n\tlocal cflags=\"osc.$mdtosc.connect_flags\"\n\tdo_facet $SINGLEMDS \"lctl get_param -n $cflags\" |grep -q skip_orphan\n\t[ $? -ne 0 ] && skip \"don't have skip orphan feature\" && return\n\n\tmkdir -p $DIR/$tdir || error \"mkdir dir $DIR/$tdir failed\"\n\t# Set the default stripe of $DIR/$tdir to put the files to ost1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\treplay_barrier $SINGLEMDS\n\tcreatemany -o $DIR/$tdir/$tfile-%d 10 \n\tlocal oid=$(do_facet ost1 \"lctl get_param -n \\\n\t\tobdfilter.${ost1_svc}.last_id\" | sed -e 's/.*://')\n\n\tfail_abort $SINGLEMDS\n\n\ttouch $DIR/$tdir/$tfile\n\tlocal id=$($LFS getstripe $DIR/$tdir/$tfile |\n\t\tawk '$1 == 0 { print $2 }')\n\t[ $id -le $oid ] && error \"the orphan objid was reused, failed\"\n\n\t# Cleanup\n\trm -rf $DIR/$tdir\n}\nrun_test 61 \"Verify to not reuse orphan objects - bug 17025\"\n\n# test_62 as seen it b2_1 please do not reuse test_62\n#test_62()\n#{\n#\tzconf_umount `hostname` $DIR\n#\t#define OBD_FAIL_PTLRPC_DELAY_IMP_FULL   0x516\n#\tlctl set_param fail_loc=0x516\n#\tmount_client $DIR\n#}\n#run_test 62 \"Verify connection flags race - bug LU-1716\"\n\ntest_65() {\n\tmount_client $DIR2\n\n\t#grant lock1, export2\n\t$LFS setstripe -i -0 $DIR2/$tfile || error \"setstripe failed\"\n\t$MULTIOP $DIR2/$tfile Ow  || error \"multiop failed\"\n\n#define OBD_FAIL_LDLM_BL_EVICT            0x31e\n\tdo_facet ost $LCTL set_param fail_loc=0x31e\n\t#get waiting lock2, export1\n\t$MULTIOP $DIR/$tfile Ow &\n\tPID1=$!\n\t# let enqueue to get asleep\n\tsleep 2\n\n\t#get lock2 blocked\n\t$MULTIOP $DIR2/$tfile Ow &\n\tPID2=$!\n\tsleep 2\n\n\t#evict export1\n\tost_evict_client\n\n\tsleep 2\n\tdo_facet ost $LCTL set_param fail_loc=0\n\n\twait $PID1\n\twait $PID2\n\n\tumount_client $DIR2\n}\nrun_test 65 \"lock enqueue for destroyed export\"\n\ntest_66()\n{\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.51) ]] ||\n\t\tskip \"Need MDS version at least 2.7.51\"\n\n\tlocal list=$(comma_list $(osts_nodes))\n\n\t# modify dir so that next revalidate would not obtain UPDATE lock\n\ttouch $DIR\n\n\t# drop 1 reply with UPDATE lock\n\tmcreate $DIR/$tfile || error \"mcreate failed: $?\"\n\tdrop_mdt_ldlm_reply_once \"stat $DIR/$tfile\" &\n\tsleep 2\n\n\t# make the re-sent lock to sleep\n#define OBD_FAIL_MDS_RESEND              0x136\n\tdo_nodes $list $LCTL set_param fail_loc=0x80000136\n\n\t#initiate the re-connect & re-send\n\tlocal mdtname=\"MDT0000\"\n\tlocal mdccli=$($LCTL dl | grep \"${mdtname}-mdc\" | awk '{print $4;}')\n\tlocal conn_uuid=$($LCTL get_param -n mdc.${mdccli}.conn_uuid)\n\t$LCTL set_param \"mdc.${mdccli}.import=connection=${conn_uuid}\"\n\tsleep 2\n\n\t#initiate the client eviction while enqueue re-send is in progress\n\tmds_evict_client\n\n\tclient_reconnect\n\twait\n}\nrun_test 66 \"lock enqueue re-send vs client eviction\"\n\ntest_67()\n{\n#define OBD_FAIL_PTLRPC_CONNECT_RACE\t 0x531\n\t$LCTL set_param fail_loc=0x80000531\n\n\tlocal mdtname=\"MDT0000\"\n\tlocal mdccli=$($LCTL dl | grep \"${mdtname}-mdc\" | awk '{print $4;}')\n\tlocal conn_uuid=$($LCTL get_param -n mdc.${mdccli}.mds_conn_uuid)\n\t$LCTL set_param \"mdc.${mdccli}.import=connection=${conn_uuid}\" &\n\tsleep 2\n\n\tmds_evict_client\n\tsleep 1\n\n\tclient_reconnect\n\twait\n}\nrun_test 67 \"connect vs import invalidate race\"\n\ncheck_cli_ir_state()\n{\n        local NODE=${1:-$HOSTNAME}\n        local st\n        st=$(do_node $NODE \"lctl get_param mgc.*.ir_state |\n                            awk '/imperative_recovery:/ { print \\\\\\$2}'\")\n\t[ $st != ON -o $st != OFF -o $st != ENABLED -o $st != DISABLED ] ||\n\t\terror \"Error state $st, must be ENABLED or DISABLED\"\n        echo -n $st\n}\n\ncheck_target_ir_state()\n{\n        local target=${1}\n        local name=${target}_svc\n        local recovery_proc=obdfilter.${!name}.recovery_status\n        local st\n\n\twhile : ; do\n\t\tst=$(do_facet $target \"$LCTL get_param -n $recovery_proc |\n\t\t\tawk '/status:/{ print \\\\\\$2}'\")\n\t\t[ x$st = xRECOVERING ] || break\n\tdone\n        st=$(do_facet $target \"lctl get_param -n $recovery_proc |\n                               awk '/IR:/{ print \\\\\\$2}'\")\n\t[ $st != ON -o $st != OFF -o $st != ENABLED -o $st != DISABLED ] ||\n\t\terror \"Error state $st, must be ENABLED or DISABLED\"\n        echo -n $st\n}\n\nset_ir_status()\n{\n        do_facet mgs lctl set_param -n mgs.MGS.live.$FSNAME=\"state=$1\"\n}\n\nget_ir_status()\n{\n        local state=$(do_facet mgs \"lctl get_param -n mgs.MGS.live.$FSNAME |\n                                    awk '/state:/{ print \\\\\\$2 }'\")\n        echo -n ${state/,/}\n}\n\nnidtbl_version_mgs()\n{\n        local ver=$(do_facet mgs \"lctl get_param -n mgs.MGS.live.$FSNAME |\n                                  awk '/nidtbl_version:/{ print \\\\\\$2 }'\")\n        echo -n $ver\n}\n\n# nidtbl_version_client <mds1|client> [node]\nnidtbl_version_client()\n{\n        local cli=$1\n        local node=${2:-$HOSTNAME}\n\n        if [ X$cli = Xclient ]; then\n                cli=$FSNAME-client\n        else\n                local obdtype=${cli/%[0-9]*/}\n                [ $obdtype != mds ] && error \"wrong parameters $cli\"\n\n                node=$(facet_active_host $cli)\n                local t=${cli}_svc\n                cli=${!t}\n        fi\n\n        local vers=$(do_node $node \"lctl get_param -n mgc.*.ir_state\" |\n                     awk \"/$cli/{print \\$6}\" |sort -u)\n\n        # in case there are multiple mounts on the client node\n        local arr=($vers)\n        [ ${#arr[@]} -ne 1 ] && error \"versions on client node mismatch\"\n        echo -n $vers\n}\n\nnidtbl_versions_match()\n{\n        [ $(nidtbl_version_mgs) -eq $(nidtbl_version_client ${1:-client}) ]\n}\n\ntarget_instance_match()\n{\n        local srv=$1\n        local obdtype\n        local cliname\n\n        obdtype=${srv/%[0-9]*/}\n        case $obdtype in\n        mds)\n                obdname=\"mdt\"\n                cliname=\"mdc\"\n                ;;\n        ost)\n                obdname=\"obdfilter\"\n                cliname=\"osc\"\n                ;;\n        *)\n                error \"invalid target type\" $srv\n                return 1\n                ;;\n        esac\n\n        local target=${srv}_svc\n        local si=$(do_facet $srv lctl get_param -n $obdname.${!target}.instance)\n\tlocal ci=$(lctl get_param -n $cliname.${!target}-${cliname}-*.import |\n\t\tawk '/instance/{ print $2 }' | head -n1)\n\n        return $([ $si -eq $ci ])\n}\n\ntest_100()\n{\n\tdo_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n\t\t{ skip \"MGS without IR support\"; return 0; }\n\n\t# MDT was just restarted in the previous test, make sure everything\n\t# is all set.\n\tlocal cnt=30\n\twhile [ $cnt -gt 0 ]; do\n\t\tnidtbl_versions_match && break\n\t\tsleep 1\n\t\tcnt=$((cnt - 1))\n\tdone\n\n\t# disable IR\n\tset_ir_status disabled\n\n\tlocal prev_ver=$(nidtbl_version_client client)\n\n        local saved_FAILURE_MODE=$FAILURE_MODE\n        [ $(facet_host mgs) = $(facet_host ost1) ] && FAILURE_MODE=\"SOFT\"\n        fail ost1\n\n        # valid check\n\t[ $(nidtbl_version_client client) -eq $prev_ver ] ||\n\t\terror \"version must not change due to IR disabled\"\n        target_instance_match ost1 || error \"instance mismatch\"\n\n        # restore env\n        set_ir_status full\n        FAILURE_MODE=$saved_FAILURE_MODE\n}\nrun_test 100 \"IR: Make sure normal recovery still works w/o IR\"\n\ntest_101a()\n{\n\tdo_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n\t\tskip \"MGS without IR support\"\n\n\tset_ir_status full\n\n\tlocal ost1_imp=$(get_osc_import_name client ost1)\n\n\t# disable pinger recovery\n\tlctl set_param -n osc.$ost1_imp.pinger_recov=0\n\tstack_trap \"$LCTL set_param -n osc.$ost1_imp.pinger_recov=1\" EXIT\n\n\tfail ost1\n\n\ttarget_instance_match ost1 || error \"instance mismatch\"\n\tnidtbl_versions_match || error \"version must match\"\n}\nrun_test 101a \"IR: Make sure IR works w/o normal recovery\"\n\ntest_101b()\n{\n\tdo_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n\t\tskip \"MGS without IR support\"\n\n\tset_ir_status full\n\n\tlocal ost1_imp=$(get_osc_import_name client ost1)\n\n#define OBD_FAIL_OST_PREPARE_DELAY\t 0x247\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x247\"\n\t# disable pinger recovery\n\t$LCTL set_param -n osc.$ost1_imp.pinger_recov=0\n\tstack_trap \"$LCTL set_param -n osc.$ost1_imp.pinger_recov=1\" EXIT\n\n#OST may return EAGAIN if it is not configured yet\n\tfail ost1\n}\nrun_test 101b \"IR: Make sure IR works w/o normal recovery and proceed EAGAIN\"\n\ntest_102()\n{\n        do_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n                { skip \"MGS without IR support\"; return 0; }\n\n        local clients=${CLIENTS:-$HOSTNAME}\n        local old_version\n        local new_version\n        local mgsdev=mgs\n\n        set_ir_status full\n\n        # let's have a new nidtbl version\n        fail ost1\n\n        # sleep for a while so that clients can see the failure of ost\n        # it must be MGC_TIMEOUT_MIN_SECONDS + MGC_TIMEOUT_RAND_CENTISEC.\n        # int mgc_request.c:\n        # define MGC_TIMEOUT_MIN_SECONDS   5\n        # define MGC_TIMEOUT_RAND_CENTISEC 0x1ff /* ~500 *\n        local count=30  # 20 seconds at most\n        while [ $count -gt 0 ]; do\n                nidtbl_versions_match && break\n                sleep 1\n                count=$((count-1))\n        done\n\n        nidtbl_versions_match || error \"nidtbl mismatch\"\n\n        # get the version #\n        old_version=$(nidtbl_version_client client)\n\n        zconf_umount_clients $clients $MOUNT || error \"Cannot umount client\"\n\n        # restart mgs\n        combined_mgs_mds && mgsdev=mds1\n        remount_facet $mgsdev\n        fail ost1\n\n        zconf_mount_clients $clients $MOUNT || error \"Cannot mount client\"\n\n        # check new version\n        new_version=$(nidtbl_version_client client)\n        [ $new_version -lt $old_version ] &&\n                error \"nidtbl version wrong after mgs restarts\"\n        return 0\n}\nrun_test 102 \"IR: New client gets updated nidtbl after MGS restart\"\n\ntest_103()\n{\n        do_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n                { skip \"MGS without IR support\"; return 0; }\n\n\tcombined_mgs_mds && skip \"needs separate mgs and mds\" && return 0\n\n        # workaround solution to generate config log on the mds\n        remount_facet mds1\n\n        stop mgs\n        stop mds1\n\n        # We need this test because mds is like a client in IR context.\n        start mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS ||\n\t\terror \"MDS should start w/o mgs\"\n\n        # start mgs and remount mds w/ ir\n        start mgs $(mgsdevname) $MGS_MOUNT_OPTS\n        clients_up\n\n        # remount client so that fsdb will be created on the MGS\n        umount_client $MOUNT || error \"umount failed\"\n        mount_client $MOUNT || error \"mount failed\"\n\n        # sleep 30 seconds so the MDS has a chance to detect MGS restarting\n        local count=30\n        while [ $count -gt 0 ]; do\n                [ $(nidtbl_version_client mds1) -ne 0 ] && break\n                sleep 1\n                count=$((count-1))\n        done\n\n        # after a while, mds should be able to reconnect to mgs and fetch\n        # up-to-date nidtbl version\n        nidtbl_versions_match mds1 || error \"mds nidtbl mismatch\"\n\n        # reset everything\n        set_ir_status full\n}\nrun_test 103 \"IR: MDS can start w/o MGS and get updated nidtbl later\"\n\ntest_104()\n{\n        do_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n                { skip \"MGS without IR support\"; return 0; }\n\n        set_ir_status full\n\n        stop ost1\n        start ost1 $(ostdevname 1) \"$OST_MOUNT_OPTS -onoir\" ||\n                error \"OST1 cannot start\"\n        clients_up\n\n        local ir_state=$(check_target_ir_state ost1)\n\t[ $ir_state = \"DISABLED\" -o $ir_state = \"OFF\" ] ||\n\t\terror \"ir status on ost1 should be DISABLED\"\n}\nrun_test 104 \"IR: ost can disable IR voluntarily\"\n\ntest_105()\n{\n        [ -z \"$RCLIENTS\" ] && skip \"Needs multiple clients\" && return 0\n        do_facet mgs $LCTL list_param mgs.*.ir_timeout ||\n                { skip \"MGS without IR support\"; return 0; }\n\n        set_ir_status full\n\n        # get one of the clients from client list\n        local rcli=$(echo $RCLIENTS |cut -d' ' -f 1)\n\n        local mount_opts=${MOUNT_OPTS:+$MOUNT_OPTS,}noir\n        zconf_umount $rcli $MOUNT || error \"umount failed\"\n        zconf_mount $rcli $MOUNT $mount_opts || error \"mount failed\"\n\n        # make sure lustre mount at $rcli disabling IR\n        local ir_state=$(check_cli_ir_state $rcli)\n\t[ $ir_state = \"DISABLED\" -o $ir_state = \"OFF\" ] ||\n\t\terror \"IR state must be DISABLED at $rcli\"\n\n\t# Since the client just mounted, its last_rcvd entry is not on disk.\n\t# Send an RPC so exp_need_sync forces last_rcvd to commit this export\n\t# so the client can reconnect during OST recovery (LU-924, LU-1582)\n\t$LFS setstripe -i 0 $DIR/$tfile\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 conv=sync\n\n        # make sure MGS's state is Partial\n        [ $(get_ir_status) = \"partial\" ] || error \"MGS IR state must be partial\"\n\n        fail ost1\n\t# make sure IR on ost1 is DISABLED\n        local ir_state=$(check_target_ir_state ost1)\n\t[ $ir_state = \"DISABLED\" -o $ir_state = \"OFF\" ] ||\n\t\terror \"IR status on ost1 should be DISABLED\"\n\n        # remount with the default MOUNT_OPTS\n        zconf_umount $rcli $MOUNT || error \"umount failed\"\n        zconf_mount $rcli $MOUNT || error \"mount failed\"\n\n        # make sure MGS's state is full\n        [ $(get_ir_status) = \"full\" ] || error \"MGS IR status must be full\"\n\n        fail ost1\n\t# make sure IR on ost1 is ENABLED\n        local ir_state=$(check_target_ir_state ost1)\n\t[ $ir_state = \"ENABLED\" -o $ir_state = \"ON\" ] ||\n\t\terror \"IR status on ost1 should be ENABLED\"\n\n        return 0\n}\nrun_test 105 \"IR: NON IR clients support\"\n\ncleanup_106() {\n\ttrap 0\n\tumount_client $DIR2\n\tdebugrestore\n}\n\ntest_106() { # LU-1789\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.50) ]] ||\n\t\tskip \"Need MDS version at least 2.3.50\"\n\n#define OBD_FAIL_MDC_LIGHTWEIGHT         0x805\n\t$LCTL set_param fail_loc=0x805\n\n\tdebugsave\n\ttrap cleanup_106 EXIT\n\n\t# enable lightweight flag on mdc connection\n\tmount_client $DIR2\n\n\tlocal MDS_NEXP=$(do_facet $SINGLEMDS \\\n\t\t\t lctl get_param -n mdt.${mds1_svc}.num_exports |\n\t\t\t cut -d' ' -f2)\n\t$LCTL set_param fail_loc=0\n\n\ttouch $DIR2/$tfile || error \"failed to create empty file\"\n\treplay_barrier $SINGLEMDS\n\n\t$LCTL set_param debug=ha\n\t$LCTL clear\n\tfacet_failover $SINGLEMDS\n\n\t# lightweight goes through LUSTRE_IMP_RECOVER during failover\n\ttouch -c $DIR2/$tfile || true\n\t$LCTL dk $TMP/lustre-log-$TESTNAME.log\n\trecovered=$(awk '/MDT0000-mdc-[0-9a-f]*. lwp recover/ { print }' \\\n\t\t    $TMP/lustre-log-$TESTNAME.log)\n\t[ -z \"$recovered\" ] && error \"lightweight client was not recovered\"\n\n\t# and all operations performed by lightweight client should be\n\t# synchronous, so the file created before mds restart should be there\n\t$CHECKSTAT -t file $DIR/$tfile || error \"file not present\"\n\trm -f $DIR/$tfile\n\n\tcleanup_106\n}\nrun_test 106 \"lightweight connection support\"\n\ntest_107 () {\n\tlocal CLIENT_PID\n\tlocal close_pid\n\n\tmkdir -p $DIR/$tdir\n\t# OBD_FAIL_MDS_REINT_NET_REP   0x119\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x119\n\tmultiop $DIR/$tdir D_c &\n\tclose_pid=$!\n\tmkdir $DIR/$tdir/dir_106 &\n\tCLIENT_PID=$!\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\tfail $SINGLEMDS\n\n\twait $CLIENT_PID || rc=$?\n\tcheckstat -t dir $DIR/$tdir/dir_106 || return 1\n\n\tkill -USR1 $close_pid\n\twait $close_pid || return 2\n\n\treturn $rc\n}\nrun_test 107 \"drop reint reply, then restart MDT\"\n\ntest_108() {\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=256 &\n\tlocal dd_pid=$!\n\tsleep 0.1\n\n\tost_evict_client\n\n\twait $dd_pid\n\n\tclient_up || error \"reconnect failed\"\n\trm -f $DIR/$tdir/$tfile\n}\nrun_test 108 \"client eviction don't crash\"\n\ntest_110a () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal mdtidx=1\n\tlocal num\n\n\t#prepare for 110 test, which need set striped dir on remote MDT.\n\tfor num in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$num \\\n\t\t\tlctl set_param -n mdt.$FSNAME*.enable_remote_dir=1 \\\n\t\t\t\t2>/dev/null\n\tdone\n\n\tmkdir -p $DIR/$tdir\n\tdrop_request \"$LFS mkdir -i $mdtidx -c2 $remote_dir\" ||\n\t\terror \"lfs mkdir failed\"\n\tlocal diridx=$($LFS getstripe -m $remote_dir)\n\t[ $diridx -eq $mdtidx ] || error \"$diridx != $mdtidx\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 110a \"create remote directory: drop client req\"\n\ntest_110b () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal mdtidx=1\n\n\tmkdir -p $DIR/$tdir\n\tdrop_reint_reply \"$LFS mkdir -i $mdtidx -c2 $remote_dir\" ||\n\t\terror \"lfs mkdir failed\"\n\n\tdiridx=$($LFS getstripe -m $remote_dir)\n\t[ $diridx -eq $mdtidx ] || error \"$diridx != $mdtidx\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 110b \"create remote directory: drop Master rep\"\n\ntest_110c () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal mdtidx=1\n\n\tmkdir -p $DIR/$tdir\n\tdrop_update_reply $mdtidx \"$LFS mkdir -i $mdtidx -c2 $remote_dir\" ||\n\t\terror \"lfs mkdir failed\"\n\n\tdiridx=$($LFS getstripe -m $remote_dir)\n\t[ $diridx -eq $mdtidx ] || error \"$diridx != $mdtidx\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 110c \"create remote directory: drop update rep on slave MDT\"\n\ntest_110d () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX -c2 $remote_dir || error \"lfs mkdir failed\"\n\n\tdrop_request \"rm -rf $remote_dir\" || error \"rm remote dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110d \"remove remote directory: drop client req\"\n\ntest_110e () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX -c2 $remote_dir  || error \"lfs mkdir failed\"\n\tdrop_reint_reply \"rm -rf $remote_dir\" || error \"rm remote dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110e \"remove remote directory: drop master rep\"\n\ntest_110f () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX -c2 $remote_dir || error \"lfs mkdir failed\"\n\tdrop_update_reply $MDTIDX \"rm -rf $remote_dir\" ||\n\t\t\t\t\terror \"rm remote dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 110f \"remove remote directory: drop slave rep\"\n\ntest_110g () {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.11.0) ]] ||\n\t\tskip \"Need MDS version at least 2.11.0\"\n\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\n\tmkdir -p $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\n\t# OBD_FAIL_MDS_REINT_NET_REP\t0x119\n\tdo_facet mds1 $LCTL set_param fail_loc=0x119\n\t$LFS migrate -m 1 $DIR/$tdir &\n\tmigrate_pid=$!\n\tsleep 5\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\twait $migrate_pid\n\n\tlocal mdt_index\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir)\n\t[ $mdt_index == 1 ] || error \"$tdir is not on MDT1\"\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/$tfile)\n\t[ $mdt_index == 1 ] || error \"$tfile is not on MDT1\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 110g \"drop reply during migration\"\n\ntest_110h () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\tlocal src_dir=$DIR/$tdir/source_dir\n\tlocal tgt_dir=$DIR/$tdir/target_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $src_dir\n\t$LFS mkdir -i $MDTIDX $tgt_dir\n\n\tdd if=/etc/hosts of=$src_dir/src_file\n\ttouch $tgt_dir/tgt_file\n\tdrop_update_reply $MDTIDX \\\n\t\t\"mrename $src_dir/src_file $tgt_dir/tgt_file\" ||\n\t\terror \"mrename failed\"\n\n\t$CHECKSTAT -t file $src_dir/src_file &&\n\t\t\t\terror \"src_file present after rename\"\n\n\tdiff /etc/hosts $tgt_dir/tgt_file ||\n\t\t\terror \"file changed after rename\"\n\n}\nrun_test 110h \"drop update reply during cross-MDT file rename\"\n\ntest_110i () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\tlocal src_dir=$DIR/$tdir/source_dir\n\tlocal tgt_dir=$DIR/$tdir/target_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $src_dir\n\t$LFS mkdir -i $MDTIDX $tgt_dir\n\n\tmkdir $src_dir/src_dir\n\ttouch $src_dir/src_dir/a\n\tmkdir $tgt_dir/tgt_dir\n\tdrop_update_reply $MDTIDX \\\n\t\t\"mrename $src_dir/src_dir $tgt_dir/tgt_dir\" ||\n\t\terror \"mrename failed\"\n\n\t$CHECKSTAT -t dir $src_dir/src_dir &&\n\t\t\terror \"src_dir present after rename\"\n\n\t$CHECKSTAT -t dir $tgt_dir/tgt_dir ||\n\t\t\t\terror \"tgt_dir not present after rename\"\n\n\t$CHECKSTAT -t file $tgt_dir/tgt_dir/a ||\n\t\t\t\terror \"a not present after rename\"\n}\nrun_test 110i \"drop update reply during cross-MDT dir rename\"\n\ntest_110j () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal local_dir=$DIR/$tdir/local_dir\n\tlocal MDTIDX=1\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $DIR/$tdir/local_dir\n\t$LFS mkdir -i $MDTIDX $remote_dir\n\n\ttouch $local_dir/local_file\n\tdrop_update_reply $MDTIDX \\\n\t\t\"ln $local_dir/local_file $remote_dir/remote_file\" ||\n\t\terror \"ln failed\"\n\n\t$CHECKSTAT -t file $remote_dir/remote_file ||\n\t\t\t\terror \"remote not present after ln\"\n}\nrun_test 110j \"drop update reply during cross-MDT ln\"\n\ntest_110k() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTS\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.12.55) ]] ||\n\t\tskip \"Need MDS version at least 2.12.55\"\n\n\tstop mds2 || error \"stop mds2 failed\"\n\tumount $MOUNT\n\n#define OBD_FAIL_FLD_QUERY_REQ 0x1103\n\tdo_facet mds2 lctl set_param fail_loc=0x1103\n\tlocal OPTS=\"$MDS_MOUNT_OPTS -o abort_recovery\"\n\tstart mds2 $(mdsdevname 2) $OPTS ||\n\t\terror \"start MDS with abort_recovery should succeed\"\n\tdo_facet mds2 lctl set_param fail_loc=0\n\n\t# cleanup\n\tstop mds2 || error \"cleanup: stop mds2 failed\"\n\tstart mds2 $(mdsdevname 2) $MDS_MOUNT_OPTS ||\n\t\terror \"cleanup: start mds2 failed\"\n\tzconf_mount $(hostname) $MOUNT || error \"cleanup: mount failed\"\n\tclient_up || error \"post-failover df failed\"\n}\nrun_test 110k \"FID_QUERY failed during recovery\"\n\n# LU-2844 mdt prepare fail should not cause umount oops\ntest_111 ()\n{\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.62) ]] ||\n\t\tskip \"Need MDS version at least 2.3.62\"\n\n#define OBD_FAIL_MDS_CHANGELOG_INIT 0x151\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x151\n\tstop $SINGLEMDS || error \"stop MDS failed\"\n\tstart $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS &&\n\t\terror \"start MDS should fail\"\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\tstart $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS ||\n\t\terror \"start MDS failed\"\n}\nrun_test 111 \"mdd setup fail should not cause umount oops\"\n\n# LU-793\ntest_112a() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tdo_facet_random_file client $TMP/$tfile 100K ||\n\t\terror_noexit \"Create random file $TMP/$tfile\"\n\n\tpause_bulk \"cp $TMP/$tfile $DIR/$tfile\" $TIMEOUT ||\n\t\terror_noexit \"Can't pause_bulk copy\"\n\n\tdf $DIR\n\t# expect cmp to succeed, client resent bulk\n\tcmp $TMP/$tfile $DIR/$tfile ||\n\t\terror_noexit \"Wrong data has been written\"\n\trm $DIR/$tfile ||\n\t\terror_noexit \"Can't remove file\"\n\trm $TMP/$tfile\n}\nrun_test 112a \"bulk resend while orignal request is in progress\"\n\ntest_115_read() {\n\tlocal fail1=$1\n\tlocal fail2=$2\n\n\tdf $DIR\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1\n\tcancel_lru_locks osc\n\n\t# OST_READ       =  3,\n\t$LCTL set_param fail_loc=$fail1 fail_val=3\n\tdd of=/dev/null if=$DIR/$tfile bs=4096 count=1 &\n\tpid=$!\n\tsleep 1\n\n\tset_nodes_failloc \"$(osts_nodes)\" $fail2\n\n\twait $pid || error \"dd failed\"\n\treturn 0\n}\n\ntest_115_write() {\n\tlocal fail1=$1\n\tlocal fail2=$2\n\tlocal error=$3\n\tlocal fail_val2=${4:-0}\n\n\tdf $DIR\n\ttouch $DIR/$tfile\n\n\t# OST_WRITE      =  4,\n\t$LCTL set_param fail_loc=$fail1 fail_val=4\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 oflag=dsync &\n\tpid=$!\n\tsleep 1\n\n\tdf $MOUNT\n\tset_nodes_failloc \"$(osts_nodes)\" $fail2 $fail_val2\n\n\twait $pid\n\trc=$?\n\t[ $error -eq 0 ] && [ $rc -ne 0 ] && error \"dd error ($rc)\"\n\t[ $error -ne 0 ] && [ $rc -eq 0 ] && error \"dd success\"\n\treturn 0\n}\n\ntest_115a() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_REQ_UNLINK  0x51b\n\t#define OBD_FAIL_PTLRPC_DROP_BULK\t 0x51a\n\ttest_115_read 0x8000051b 0x8000051a\n}\nrun_test 115a \"read: late REQ MDunlink and no bulk\"\n\ntest_115b() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_REQ_UNLINK  0x51b\n\t#define OBD_FAIL_OST_ENOSPC              0x215\n\n\t# pass $OSTCOUNT for the fail_loc to be caught\n\t# appropriately by the IO thread\n\ttest_115_write 0x8000051b 0x80000215 1 $OSTCOUNT\n}\nrun_test 115b \"write: late REQ MDunlink and no bulk\"\n\ntest_115c() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_REPL_UNLINK 0x50f\n\t#define OBD_FAIL_PTLRPC_DROP_BULK\t 0x51a\n\ttest_115_read 0x8000050f 0x8000051a\n}\nrun_test 115c \"read: late Reply MDunlink and no bulk\"\n\ntest_115d() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_REPL_UNLINK 0x50f\n\t#define OBD_FAIL_OST_ENOSPC              0x215\n\ttest_115_write 0x8000050f 0x80000215 0\n}\nrun_test 115d \"write: late Reply MDunlink and no bulk\"\n\ntest_115e() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_BULK_UNLINK 0x510\n\t#define OBD_FAIL_OST_ALL_REPLY_NET       0x211\n\ttest_115_read 0x80000510 0x80000211\n}\nrun_test 115e \"read: late Bulk MDunlink and no reply\"\n\ntest_115f() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_REQ_UNLINK  0x51b\n\t#define OBD_FAIL_OST_ALL_REPLY_NET       0x211\n\ttest_115_read 0x8000051b 0x80000211\n}\nrun_test 115f \"read: late REQ MDunlink and no reply\"\n\ntest_115g() {\n\t[ \"$OST1_VERSION\" -lt $(version_code 2.8.50) ] &&\n\t\tskip \"need at least 2.8.50 on OST\"\n\n\t#define OBD_FAIL_PTLRPC_LONG_BOTH_UNLINK 0x51c\n\ttest_115_read 0x8000051c 0\n}\nrun_test 115g \"read: late REQ MDunlink and Reply MDunlink\"\n\n# parameters: fail_loc CMD RC\ntest_120_reply() {\n\tlocal PID\n\tlocal PID2\n\tlocal rc=5\n\tlocal fail\n\n\t#define OBD_FAIL_LDLM_CP_CB_WAIT2\t0x320\n\t#define OBD_FAIL_LDLM_CP_CB_WAIT3\t0x321\n\t#define OBD_FAIL_LDLM_CP_CB_WAIT4\t0x322\n\t#define OBD_FAIL_LDLM_CP_CB_WAIT5\t0x323\n\n\techo\n\techo -n \"** FLOCK REPLY vs. EVICTION race, lock $2\"\n\t[ \"$1\" = \"CLEANUP\" ] &&\n\t\tfail=0x80000320 && echo \", $1 cp first\"\n\t[ \"$1\" = \"REPLY\" ] &&\n\t\tfail=0x80000321 && echo \", $1 cp first\"\n\t[ \"$1\" = \"DEADLOCK CLEANUP\" ] &&\n\t\tfail=0x80000322 && echo \" DEADLOCK, CLEANUP cp first\"\n\t[ \"$1\" = \"DEADLOCK REPLY\" ] &&\n\t\tfail=0x80000323 && echo \" DEADLOCK, REPLY cp first\"\n\n\tif [ x\"$2\" = x\"get\" ]; then\n\t\t#for TEST lock, take a conflict in advance\n\t\t# sleep longer than evictor to not confuse fail_loc: 2+2+4\n\t\techo \"** Taking conflict **\"\n\t\tflocks_test 5 set read sleep 10 $DIR/$tfile &\n\t\tPID2=$!\n\n\t\tsleep 2\n\tfi\n\n\t$LCTL set_param fail_loc=$fail\n\n\tflocks_test 5 $2 write $DIR/$tfile &\n\tPID=$!\n\n\tsleep 2\n\techo \"** Evicting and re-connecting client **\"\n\tmds_evict_client\n\n\tclient_reconnect\n\n\tif [ x\"$2\" = x\"get\" ]; then\n\t\twait $PID2\n\tfi\n\n\twait $PID\n\trc=$?\n\n\t# check if the return value is allowed\n\t[ $rc -eq $3 ] && rc=0\n\n\t$LCTL set_param fail_loc=0\n\treturn $rc\n}\n\n# a lock is taken, unlock vs. cleanup_resource() race for destroying\n# the ORIGINAL lock.\ntest_120_destroy()\n{\n\tlocal PID\n\n\tflocks_test 5 set write sleep 4 $DIR/$tfile &\n\tPID=$!\n\tsleep 2\n\n\t# let unlock to sleep in CP CB\n\t$LCTL set_param fail_loc=$1\n\tsleep 4\n\n\t# let cleanup to cleep in CP CB\n\tmds_evict_client\n\n\tclient_reconnect\n\n\twait $PID\n\trc=$?\n\n\t$LCTL set_param fail_loc=0\n\treturn $rc\n}\n\ntest_120() {\n\tflock_is_enabled || { skip \"mount w/o flock enabled\" && return; }\n\ttouch $DIR/$tfile\n\n\ttest_120_reply \"CLEANUP\" set 5 || error \"SET race failed\"\n\ttest_120_reply \"CLEANUP\" get 5 || error \"GET race failed\"\n\ttest_120_reply \"CLEANUP\" unlock 5 || error \"UNLOCK race failed\"\n\n\ttest_120_reply \"REPLY\" set 5 || error \"SET race failed\"\n\ttest_120_reply \"REPLY\" get 5 || error \"GET race failed\"\n\ttest_120_reply \"REPLY\" unlock 5 || error \"UNLOCK race failed\"\n\n\t# DEADLOCK tests\n\ttest_120_reply \"DEADLOCK CLEANUP\" set 5 || error \"DEADLOCK race failed\"\n\ttest_120_reply \"DEADLOCK REPLY\" set 35 || error \"DEADLOCK race failed\"\n\n\ttest_120_destroy 0x320 || error \"unlock-cleanup race failed\"\n}\nrun_test 120 \"flock race: completion vs. evict\"\n\ntest_113() {\n\tlocal BEFORE=$(date +%s)\n\tlocal EVICT\n\n\t# modify dir so that next revalidate would not obtain UPDATE lock\n\ttouch $DIR\n\n\t# drop 1 reply with UPDATE lock,\n\t# resend should not create 2nd lock on server\n\tmcreate $DIR/$tfile || error \"mcreate failed: $?\"\n\tdrop_mdt_ldlm_reply_once \"stat $DIR/$tfile\" || error \"stat failed: $?\"\n\n\t# 2 BL AST will be sent to client, both must find the same lock,\n\t# race them to not get EINVAL for 2nd BL AST\n\t#define OBD_FAIL_LDLM_PAUSE_CANCEL2      0x31f\n\t$LCTL set_param fail_loc=0x8000031f\n\n\t$LCTL set_param ldlm.namespaces.*.early_lock_cancel=0 > /dev/null\n\tchmod 0777 $DIR/$tfile || error \"chmod failed: $?\"\n\t$LCTL set_param ldlm.namespaces.*.early_lock_cancel=1 > /dev/null\n\n\t# let the client reconnect\n\tclient_reconnect\n\tEVICT=$($LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$EVICT\" ] || [[ $EVICT -le $BEFORE ]] || error \"eviction happened\"\n}\nrun_test 113 \"ldlm enqueue dropped reply should not cause deadlocks\"\n\nT130_PID=0\ntest_130_base() {\n\ttest_mkdir -p $DIR/$tdir\n\n\t# Prevent interference from layout intent RPCs due to\n\t# asynchronous writeback. These will be tested in 130c below.\n\tdo_nodes ${CLIENTS:-$HOSTNAME} sync\n\n\t# get only LOOKUP lock on $tdir\n\tcancel_lru_locks mdc\n\tls $DIR/$tdir/$tfile 2>/dev/null\n\n\t# get getattr by fid on $tdir\n\t#\n\t# we need to race with unlink, unlink must complete before we will\n\t# take a DLM lock, otherwise unlink will wait until getattr will\n\t# complete; but later than getattr starts so that getattr found\n\t# the object\n#define OBD_FAIL_MDS_INTENT_DELAY\t\t0x160\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000160\n\tstat $DIR/$tdir &\n\tT130_PID=$!\n\tsleep 2\n\n\trm -rf $DIR/$tdir\n\n\t# drop the reply so that resend happens on an unlinked file.\n#define OBD_FAIL_MDS_LDLM_REPLY_NET\t 0x157\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000157\n}\n\ntest_130a() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.2) ]] ||\n\t\tskip \"Need server version newer than 2.7.1\"\n\n\ttest_130_base\n\n\twait $T130_PID || [ $? -eq 0 ] && error \"stat should fail\"\n\treturn 0\n}\nrun_test 130a \"enqueue resend on not existing file\"\n\ntest_130b() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.2) ]] ||\n\t\tskip \"Need server version newer than 2.7.1\"\n\n\ttest_130_base\n\t# let the reply to be dropped\n\tsleep 10\n\n#define OBD_FAIL_SRV_ENOENT              0x217\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000217\n\n\twait $T130_PID || [ $? -eq 0 ] && error \"stat should fail\"\n\treturn 0\n}\nrun_test 130b \"enqueue resend on a stale inode\"\n\ntest_130c() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\n\tdo_nodes ${CLIENTS:-$HOSTNAME} sync\n\techo XXX > $DIR/$tfile\n\n\tcancel_lru_locks mdc\n\n\t# Trigger writeback on $tfile.\n\t#\n\t# we need to race with unlink, unlink must complete before we will\n\t# take a DLM lock, otherwise unlink will wait until intent will\n\t# complete; but later than intent starts so that intent found\n\t# the object\n#define OBD_FAIL_MDS_INTENT_DELAY\t\t0x160\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000160\n\tsync &\n\tT130_PID=$!\n\tsleep 2\n\n\trm $DIR/$tfile\n\n\t# drop the reply so that resend happens on an unlinked file.\n#define OBD_FAIL_MDS_LDLM_REPLY_NET\t 0x157\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000157\n\n\t# let the reply to be dropped\n\tsleep 10\n\n#define OBD_FAIL_SRV_ENOENT              0x217\n\tset_nodes_failloc \"$(mdts_nodes)\" 0x80000217\n\n\twait $T130_PID\n\n\treturn 0\n}\nrun_test 130c \"layout intent resend on a stale inode\"\n\ntest_132() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\tmount_client $MOUNT2 || error \"mount filed\"\n\n\trm -f $DIR/$tfile\n\t# get a lock on client so that export would reach the stale list\n\t$LFS setstripe -i 0 $DIR/$tfile || error \"setstripe failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 conv=fsync ||\n\t\terror \"dd failed\"\n\n\t#define OBD_FAIL_OST_PAUSE_PUNCH         0x236\n\tdo_facet ost1 $LCTL set_param fail_val=120 fail_loc=0x80000236\n\n\t$TRUNCATE $DIR/$tfile 100 &\n\n\tsleep 1\n\tdd if=/dev/zero of=$DIR2/$tfile bs=4096 count=1 conv=notrunc ||\n\t\terror \"dd failed\"\n\n\twait\n\tumount_client $MOUNT2\n\n\tevict=$(do_facet client $LCTL get_param \\\n\t\tosc.$FSNAME-OST0000-osc-*/state |\n\t    awk -F\"[ [,]\" '/EVICTED ]$/ { if (t<$5) {t=$5;} } END { print t }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] ||\n\t\t(do_facet client $LCTL get_param \\\n\t\t\tosc.$FSNAME-OST0000-osc-*/state;\n\t\t    error \"eviction happened: $evict before:$before\")\n}\nrun_test 132 \"long punch\"\n\ntest_131() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\trm -f $DIR/$tfile\n\t# get a lock on client so that export would reach the stale list\n\t$LFS setstripe -i 0 $DIR/$tfile || error \"setstripe failed\"\n\tdd if=/dev/zero of=$DIR/$tfile count=1 || error \"dd failed\"\n\n\t# another IO under the same lock\n\t#define OBD_FAIL_OSC_DELAY_IO            0x414\n\t$LCTL set_param fail_loc=0x80000414\n\t$LCTL set_param fail_val=4 fail_loc=0x80000414\n\tdd if=/dev/zero of=$DIR/$tfile count=1 conv=notrunc oflag=dsync &\n\tlocal pid=$!\n\tsleep 1\n\n\t#define OBD_FAIL_LDLM_BL_EVICT           0x31e\n\tset_nodes_failloc \"$(osts_nodes)\" 0x8000031e\n\tost_evict_client\n\tclient_reconnect\n\n\twait $pid && error \"dd succeeded\"\n\treturn 0\n}\nrun_test 131 \"IO vs evict results to IO under staled lock\"\n\ntest_133() {\n\tlocal list=$(comma_list $(mdts_nodes))\n\n\tlocal t=$((TIMEOUT * 2))\n\ttouch $DIR/$tfile\n\n\tflock $DIR/$tfile -c \"echo bl lock;sleep $t;echo bl flock unlocked\" &\n\tsleep 1\n\tmultiop_bg_pause $DIR/$tfile O_jc || return 1\n\tPID=$!\n\n\t#define OBD_FAIL_MDS_LDLM_REPLY_NET 0x157\n\tdo_nodes $list $LCTL set_param fail_loc=0x80000157\n\tkill -USR1 $PID\n\techo \"waiting for multiop $PID\"\n\twait $PID || return 2\n\n\trm -f $DIR/$tfile\n\n\treturn 0\n}\nrun_test 133 \"don't fail on flock resend\"\n\ntest_134() {\n\t[ -z \"$CLIENTS\" ] && skip \"Need two or more clients\" && return\n\t[ $CLIENTCOUNT -lt 2 ] &&\n\t\t{ skip \"Need 2+ clients, have $CLIENTCOUNT\" && return; }\n\n\tmkdir -p $MOUNT/$tdir/1 $MOUNT/$tdir/2 || error \"mkdir failed\"\n\ttouch $MOUNT/$tdir/1/$tfile $MOUNT/$tdir/2/$tfile ||\n\t\terror \"touch failed\"\n\tzconf_umount_clients $CLIENTS $MOUNT\n\tzconf_mount_clients $CLIENTS $MOUNT\n\n#define OBD_FAIL_TGT_REPLY_DATA_RACE    0x722\n\t# assume commit interval is 5\n\tdo_facet mds1 \"$LCTL set_param fail_loc=0x722 fail_val=5\"\n\n\tlocal -a clients=(${CLIENTS//,/ })\n\tlocal client1=${clients[0]}\n\tlocal client2=${clients[1]}\n\n\tdo_node $client1 rm $MOUNT/$tdir/1/$tfile &\n\trmpid=$!\n\tdo_node $client2 mv $MOUNT/$tdir/2/$tfile $MOUNT/$tdir/2/${tfile}_2 &\n\tmvpid=$!\n\tfail mds1\n\twait $rmpid || error \"rm failed\"\n\twait $mvpid || error \"mv failed\"\n\treturn 0\n}\nrun_test 134 \"race between failover and search for reply data free slot\"\n\ntest_135() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.12.51) ] &&\n\t\tskip \"Need MDS version at least 2.12.51\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt $DIR/$tdir\n\t# to have parent dir write lock before open/resend\n\ttouch $DIR/$tdir/$tfile\n\t#define OBD_FAIL_MDS_LDLM_REPLY_NET 0x157\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x80000157\n\topenfile -f O_RDWR:O_CREAT -m 0755 $DIR/$tdir/$tfile ||\n\t\terror \"Failed to open DOM file\"\n}\nrun_test 135 \"DOM: open/create resend to return size\"\n\ntest_136() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.12.52) ]] ||\n\t\tskip \"Need MDS version at least 2.12.52\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\n\tlocal clog=$(do_facet mds1 $LCTL --device $MDT0 changelog_register -n)\n\t[ -n \"$clog\" ] || error \"changelog_register failed\"\n\tcl_mask=$(do_facet mds1 $LCTL get_param \\\n\t\t\t\tmdd.$MDT0.changelog_mask -n)\n\tchangelog_chmask \"ALL\"\n\n\t# generate some changelog records to accumulate\n\ttest_mkdir -i 0 -c 0 $DIR/$tdir || error \"mkdir $tdir failed\"\n\tcreatemany -m $DIR/$tdir/$tfile 10000 ||\n\t\terror \"create $DIR/$tdir/$tfile failed\"\n\n\tlocal size1=$(do_facet $SINGLEMDS \\\n\t\t      $LCTL get_param -n mdd.$MDT0.changelog_size)\n\techo \"Changelog size $size1\"\n\n\t#define OBD_FAIL_LLOG_PURGE_DELAY\t\t    0x1318\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x1318 fail_val=30\n\n\t# launch changelog_deregister in background on MDS\n\tdo_facet mds1 \"nohup $LCTL --device $MDT0 changelog_deregister $clog \\\n\t\t\t> foo.out 2> foo.err < /dev/null &\"\n\t# give time to reach fail_loc\n\tsleep 15\n\n\t# fail_loc will make MDS sleep in the middle of changelog_deregister\n\t# take this opportunity to abruptly kill MDS\n\tFAILURE_MODE_save=$FAILURE_MODE\n\tFAILURE_MODE=HARD\n\tfail mds1\n\tFAILURE_MODE=$FAILURE_MODE_save\n\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x0 fail_val=0\n\n\tlocal size2=$(do_facet $SINGLEMDS \\\n\t\t      $LCTL get_param -n mdd.$MDT0.changelog_size)\n\techo \"Changelog size $size2\"\n\tlocal clog2=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\tmdd.$MDT0.changelog_users | grep $clog\")\n\techo \"After crash, changelog user $clog2\"\n\n\t[ -n \"$clog2\" -o $size2 -lt $size1 ] ||\n\t\terror \"changelog record count unchanged\"\n\n\tdo_facet mds1 $LCTL set_param mdd.$MDT0.changelog_mask=\\'$cl_mask\\' -n\n}\nrun_test 136 \"changelog_deregister leaving pending records\"\n\ntest_137() {\n\tdf $DIR\n\tmkdir -p $DIR/d1\n\tmkdir -p $DIR/d2\n\tdd if=/dev/zero of=$DIR/d1/$tfile bs=4096 count=1\n\tdd if=/dev/zero of=$DIR/d2/$tfile bs=4096 count=1\n\tcancel_lru_locks osc\n\n\t#define OBD_FAIL_PTLRPC_RESEND_RACE\t 0x525\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000525\"\n\n\t# RPC1: any reply is to be delayed to disable last_xid logic\n\tln $DIR/d1/$tfile $DIR/d1/f2 &\n\tsleep 1\n\n\t# RPC2: setattr1 reply is delayed & resent\n\t# original reply comes to client; the resend get asleep\n\tchmod 666 $DIR/d2/$tfile\n\n\t# RPC3: setattr2 on the same file; run ahead of RPC2 resend\n\tchmod 777 $DIR/d2/$tfile\n\n\t# RPC2 resend wakes up\n\tsleep 5\n\t[ $(stat -c \"%a\" $DIR/d2/$tfile) == 777 ] || error \"resend got applied\"\n}\nrun_test 137 \"late resend must be skipped if already applied\"\n\ntest_138() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.12.59) ]] ||\n\t\tskip \"Need server version newer than 2.12.59\"\n\n\tzconf_umount_clients $CLIENTS $MOUNT\n\n#define OBD_FAIL_TGT_RECOVERY_CONNECT 0x724\n\t#delay a first step of recovey when MDS waiting clients\n\t#and failing to get osp logs\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x724 fail_val=5\n\n\tfacet_failover $SINGLEMDS\n\n\t#waiting failover and recovery timer\n\t#the valuse is based on target_recovery_overseer() wait_event timeout\n\tsleep 55\n\tstop $SINGLEMDS || error \"stop MDS failed\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tstart $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) ||\n\t\terror \"start MDS failed\"\n\tzconf_mount_clients $CLIENTS $MOUNT\n}\nrun_test 138 \"Umount MDT during recovery\"\n\ntest_139() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ $MDS1_VERSION -lt $(version_code 2.13.50) ] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\n\tmdt_dev=$(mdsdevname 1)\n\n\tstop $SINGLEMDS || error \"stop $SINGLEMDS failed\"\n\n#define OBD_FAIL_OSP_INVALID_LOGID\t\t0x2106\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0x68 fail_loc=0x80002106\n\tstart $SINGLEMDS $mdt_dev $MDS_MOUNT_OPTS || error \"Fail to start MDT\"\n}\nrun_test 139 \"corrupted catid won't cause crash\"\n\ntest_140a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.58) ] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\n\t[ \"$SHARED_KEY\" = true ] &&\n\t\tskip \"server local client incompatible with SSK keys installed\"\n\n\tslr=$(do_facet mds1 \\\n\t\t$LCTL get_param -n mdt.$FSNAME-MDT0000.local_recovery)\n\tstack_trap \"do_facet mds1 $LCTL set_param \\\n\t\tmdt.*.local_recovery=$slr\" EXIT\n\n\t# disable recovery for local clients\n\t# so local clients should be marked with no_recovery flag\n\tdo_facet mds1 $LCTL set_param mdt.*.local_recovery=0\n\tmount_mds_client\n\n\tlocal cnt\n\tcnt=$(do_facet mds1 $LCTL get_param \"mdt.*.exports.*.export\" |\n\t\tgrep export_flags.*no_recovery | wc -l)\n\techo \"$cnt clients with recovery disabled\"\n\tumount_mds_client\n\t[ $cnt -eq 0 ] && error \"no clients with recovery disabled\"\n\n\t# enable recovery for local clients\n\t# so no local clients should be marked with no_recovery flag\n\tdo_facet mds1 $LCTL set_param mdt.*.local_recovery=1\n\tmount_mds_client\n\n\tcnt=$(do_facet mds1 $LCTL get_param \"mdt.*.exports.*.export\" |\n\t\tgrep export_flags.*no_recovery | wc -l)\n\techo \"$cnt clients with recovery disabled\"\n\tumount_mds_client\n\t[ $cnt -eq 0 ] || error \"$cnt clients with recovery disabled\"\n}\nrun_test 140a \"local mount is flagged properly\"\n\ntest_140b() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.58) ] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\n\t[ \"$SHARED_KEY\" = true ] &&\n\t\tskip \"server local client incompatible with SSK keys installed\"\n\n\tslr=$(do_facet mds1 \\\n\t\t$LCTL get_param -n mdt.$FSNAME-MDT0000.local_recovery)\n\tstack_trap \"do_facet mds1 $LCTL set_param \\\n\t\tmdt.*.local_recovery=$slr\" EXIT\n\n\t# disable recovery for local clients\n\tdo_facet mds1 $LCTL set_param mdt.*.local_recovery=0\n\n\tmount_mds_client\n\treplay_barrier mds1\n\tumount_mds_client\n\tfail mds1\n\tlocal recovery=$(do_facet mds1 dmesg |\n\t\t\t awk -F: '/Recovery over after/ { print $4 }' |\n\t\t\t cut -d, -f1 | tail -1)\n\t(( $recovery < $TIMEOUT*2 )) ||\n\t\terror \"recovery took too long $recovery > $((TIMEOUT * 2))\"\n}\nrun_test 140b \"local mount is excluded from recovery\"\n\ntest_141() {\n\tlocal oldc\n\tlocal newc\n\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tcombined_mgs_mds || skip \"needs combined MGS/MDT\"\n\t( local_mode || from_build_tree ) &&\n\t\tskip \"cannot run in local mode or from build tree\"\n\n\t# some get_param have a bug to handle dot in param name\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) cancel_lru_locks MGC\n\toldc=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t'ldlm.namespaces.MGC*.lock_count')\n\tfail $SINGLEMDS\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) cancel_lru_locks MGC\n\tnewc=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t'ldlm.namespaces.MGC*.lock_count')\n\n\t[ $oldc -eq $newc ] || error \"mgc lost locks ($oldc != $newc)\"\n\treturn 0\n}\nrun_test 141 \"do not lose locks on MGS restart\"\n\ntest_142() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\t#define OBD_FAIL_MDS_ORPHAN_DELETE\t0x165\n\tdo_facet mds1 $LCTL set_param fail_loc=0x165\n\t$MULTIOP $DIR/$tfile Ouc || error \"multiop failed\"\n\n\tstop mds1\n\tstart mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS\n\n\twait_update_facet mds1 \"pgrep orph_.*-MDD | wc -l\" \"0\" ||\n\t\terror \"MDD orphan cleanup thread not quit\"\n}\nrun_test 142 \"orphan name stub can be cleaned up in startup\"\n\ntest_143() {\n\t[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.13.00) ] &&\n\t\tskip \"Need MDS version at least 2.13.00\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal mntpt=$(facet_mntpt $SINGLEMDS)\n\tstop mds1\n\tmount_fstype $SINGLEMDS || error \"mount as fstype $SINGLEMDS failed\"\n\tdo_facet $SINGLEMDS touch $mntpt/PENDING/$tfile\n\tunmount_fstype $SINGLEMDS\n\tstart mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS || error \"mds1 start fail\"\n\n\twait_recovery_complete $SINGLEMDS || error \"MDS recovery not done\"\n\twait_update_facet mds1 \"pgrep orph_.*-MDD | wc -l\" \"0\" ||\n\t\terror \"MDD orphan cleanup thread not quit\"\n}\nrun_test 143 \"orphan cleanup thread shouldn't be blocked even delete failed\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 3042}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nPTLDEBUG=${PTLDEBUG:--1}\nMOUNT_2=${MOUNT_2:-\"yes\"}\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nremote_mds_nodsh && skip \"remote MDS with nodsh\" && exit 0\n\nALWAYS_EXCEPT=\"$REPLAY_DUAL_EXCEPT \"\n# bug number for skipped test:  LU-2012 LU-8333 LU-7372\nALWAYS_EXCEPT+=\"                14b     21b     26 \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n[[ \"$mds1_FSTYPE\" == zfs ]] &&\n# bug number for skipped test:        LU-2230\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT 21b\"\n\nif $SHARED_KEY; then\n# bug number for skipped tests:  LU-9795 LU-9795\n\tALWAYS_EXCEPT+=\"         0a      0b \"\nfi\n\n#                                   7  (min)\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"21b \"\n\nbuild_test_filter\ncheck_and_setup_lustre\n\nMOUNTED=$(mounted_lustre_filesystems)\nif ! $(echo $MOUNTED' ' | grep -w -q $MOUNT2' '); then\n\tzconf_mount $HOSTNAME $MOUNT2\n\tMOUNTED2=yes\nfi\n\nassert_DIR\nrm -rf $DIR/[df][0-9]*\n\n[ \"$DAEMONFILE\" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE\n\n# if there is no CLIENT1 defined, some tests can be ran on localhost\nCLIENT1=${CLIENT1:-$HOSTNAME}\n# if CLIENT2 doesn't exist then use CLIENT1 instead\n# All tests should use CLIENT2 with MOUNT2 only therefore it will work if\n# $CLIENT2 == CLIENT1\n# Exception is the test which need two separate nodes\nCLIENT2=${CLIENT2:-$CLIENT1}\n\n# LU-482 Avert LVM and VM inability to flush caches in pre .33 kernels\nif [ $LINUX_VERSION_CODE -lt $(version_code 2.6.33) ]; then\n\tsync\n\tdo_facet $SINGLEMDS \"sync; sleep 10; sync; sleep 10; sync\"\nfi\n\nLU482_FAILED=$(mktemp -u $TMP/$TESTSUITE.lu482.XXXXXX)\ntest_0a() {\n\techo \"Check file is LU482_FAILED=$LU482_FAILED\"\n\ttouch $MOUNT2/$tfile-A # force sync FLD/SEQ update before barrier\n\treplay_barrier $SINGLEMDS\n#define OBD_FAIL_PTLRPC_FINISH_REPLAY | OBD_FAIL_ONCE\n\ttouch $MOUNT2/$tfile\n\tcreatemany -o $MOUNT1/$tfile- 50\n\t$LCTL set_param fail_loc=0x80000514\n\tfacet_failover $SINGLEMDS\n\t[ -f \"$LU482_FAILED\" ] && skip \"LU-482 failure\" && return 0\n\tclient_up || return 1\n\tumount -f $MOUNT2\n\tclient_up || return 1\n\tzconf_mount `hostname` $MOUNT2 || error \"mount2 fais\"\n\tunlinkmany $MOUNT1/$tfile- 50 || return 2\n\trm $MOUNT2/$tfile || return 3\n\trm $MOUNT2/$tfile-A || return 4\n}\nrun_test 0a \"expired recovery with lost client\"\n\nif [ -f \"$LU482_FAILED\" ]; then\n\tlog \"Found check file $LU482_FAILED, aborting test script\"\n\trm -vf \"$LU482_FAILED\"\n\tcomplete $SECONDS\n\tdo_nodes $CLIENTS umount -f $MOUNT2 || true\n\tdo_nodes $CLIENTS umount -f $MOUNT || true\n\t# copied from stopall, but avoid the MDS recovery\n    for num in `seq $OSTCOUNT`; do\n        stop ost$num -f\n        rm -f $TMP/ost${num}active\n    done\n    if ! combined_mgs_mds ; then\n        stop mgs\n    fi\n\n\texit_status\nfi\n\ntest_0b() {\n    replay_barrier $SINGLEMDS\n    touch $MOUNT2/$tfile\n    touch $MOUNT1/$tfile-2\n    umount $MOUNT2\n    facet_failover $SINGLEMDS\n    umount -f $MOUNT1\n    zconf_mount `hostname` $MOUNT1 || error \"mount1 fais\"\n    zconf_mount `hostname` $MOUNT2 || error \"mount2 fais\"\n    # it is uncertain if file-2 exists or not, remove it if it does\n    checkstat $MOUNT1/$tfile-2 && rm $MOUNT1/$tfile-2\n    checkstat $MOUNT2/$tfile && return 2\n    return 0\n}\nrun_test 0b \"lost client during waiting for next transno\"\n\ntest_1() {\n    touch $MOUNT1/a\n    replay_barrier $SINGLEMDS\n    touch $MOUNT2/b\n\n    fail $SINGLEMDS\n    checkstat $MOUNT2/a || return 1\n    checkstat $MOUNT1/b || return 2\n    rm $MOUNT2/a $MOUNT1/b\n    checkstat $MOUNT1/a && return 3\n    checkstat $MOUNT2/b && return 4\n    return 0\n}\n\nrun_test 1 \"|X| simple create\"\n\n\ntest_2() {\n    replay_barrier $SINGLEMDS\n    mkdir $MOUNT1/adir\n\n    fail $SINGLEMDS\n    checkstat $MOUNT2/adir || return 1\n    rmdir $MOUNT2/adir\n    checkstat $MOUNT2/adir && return 2\n    return 0\n}\nrun_test 2 \"|X| mkdir adir\"\n\ntest_3() {\n    replay_barrier $SINGLEMDS\n    mkdir $MOUNT1/adir\n    mkdir $MOUNT2/adir/bdir\n\n    fail $SINGLEMDS\n    checkstat $MOUNT2/adir      || return 1\n    checkstat $MOUNT1/adir/bdir || return 2\n    rmdir $MOUNT2/adir/bdir $MOUNT1/adir\n    checkstat $MOUNT1/adir      && return 3\n    checkstat $MOUNT2/adir/bdir && return 4\n    return 0\n}\nrun_test 3 \"|X| mkdir adir, mkdir adir/bdir \"\n\ntest_4() {\n    mkdir $MOUNT1/adir\n    replay_barrier $SINGLEMDS\n    mkdir $MOUNT1/adir  && return 1\n    mkdir $MOUNT2/adir/bdir\n\n    fail $SINGLEMDS\n    checkstat $MOUNT2/adir      || return 2\n    checkstat $MOUNT1/adir/bdir || return 3\n\n    rmdir $MOUNT2/adir/bdir $MOUNT1/adir\n    checkstat $MOUNT1/adir      && return 4\n    checkstat $MOUNT2/adir/bdir && return 5\n    return 0\n}\nrun_test 4 \"|X| mkdir adir (-EEXIST), mkdir adir/bdir \"\n\n\ntest_5() {\n    # multiclient version of replay_single.sh/test_8\n    mcreate $MOUNT1/a\n    multiop_bg_pause $MOUNT2/a o_tSc || return  1\n    pid=$!\n    rm -f $MOUNT1/a\n    replay_barrier $SINGLEMDS\n    kill -USR1 $pid\n    wait $pid || return 1\n\n    fail $SINGLEMDS\n    [ -e $MOUNT2/a ] && return 2\n    return 0\n}\nrun_test 5 \"open, unlink |X| close\"\n\n\ntest_6() {\n    mcreate $MOUNT1/a\n    multiop_bg_pause $MOUNT2/a o_c || return 1\n    pid1=$!\n    multiop_bg_pause $MOUNT1/a o_c || return 1\n    pid2=$!\n    rm -f $MOUNT1/a\n    replay_barrier $SINGLEMDS\n    kill -USR1 $pid1\n    wait $pid1 || return 1\n\n    fail $SINGLEMDS\n    kill -USR1 $pid2\n    wait $pid2 || return 1\n    [ -e $MOUNT2/a ] && return 2\n    return 0\n}\nrun_test 6 \"open1, open2, unlink |X| close1 [fail $SINGLEMDS] close2\"\n\ntest_8() {\n    replay_barrier $SINGLEMDS\n    drop_reint_reply \"mcreate $MOUNT1/$tfile\"    || return 1\n    fail $SINGLEMDS\n    checkstat $MOUNT2/$tfile || return 2\n    rm $MOUNT1/$tfile || return 3\n\n    return 0\n}\nrun_test 8 \"replay of resent request\"\n\ntest_9() {\n    replay_barrier $SINGLEMDS\n    mcreate $MOUNT1/$tfile-1\n    mcreate $MOUNT2/$tfile-2\n    # drop first reint reply\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x80000119\n    fail $SINGLEMDS\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n\n    rm $MOUNT1/$tfile-[1,2] || return 1\n\n    return 0\n}\nrun_test 9 \"resending a replayed create\"\n\ntest_10() {\n    mcreate $MOUNT1/$tfile-1\n    replay_barrier $SINGLEMDS\n    munlink $MOUNT1/$tfile-1\n    mcreate $MOUNT2/$tfile-2\n    # drop first reint reply\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x80000119\n    fail $SINGLEMDS\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n\n    checkstat $MOUNT1/$tfile-1 && return 1\n    checkstat $MOUNT1/$tfile-2 || return 2\n    rm $MOUNT1/$tfile-2\n\n    return 0\n}\nrun_test 10 \"resending a replayed unlink\"\n\ntest_11() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR1/$tfile-1\n\tmcreate $DIR2/$tfile-2\n\tmcreate $DIR1/$tfile-3\n\tmcreate $DIR2/$tfile-4\n\tmcreate $DIR1/$tfile-5\n\t# drop all reint replies for a while\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0119\n\t# note that with this fail_loc set, facet_failover df will fail\n\tfacet_failover $SINGLEMDS\n\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\twait_clients_import_state \"$clients\" $SINGLEMDS FULL\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\trm $DIR1/$tfile-[1-5] || return 1\n\n\treturn 0\n}\nrun_test 11 \"both clients timeout during replay\"\n\ntest_12() {\n    replay_barrier $SINGLEMDS\n\n    multiop_bg_pause $DIR/$tfile mo_c || return 1\n    MULTIPID=$!\n\n#define OBD_FAIL_LDLM_ENQUEUE_NET\t\t\t0x302\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x80000302\n    facet_failover $SINGLEMDS\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n    clients_up || return 1\n\n    ls $DIR/$tfile\n    kill -USR1 $MULTIPID || return 3\n    wait $MULTIPID || return 4\n    $CHECKSTAT -t file $DIR/$tfile || return 2\n    rm $DIR/$tfile\n\n    return 0\n}\nrun_test 12 \"open resend timeout\"\n\ntest_13() {\n    multiop_bg_pause $DIR/$tfile mo_c || return 1\n    MULTIPID=$!\n\n    replay_barrier $SINGLEMDS\n\n    kill -USR1 $MULTIPID || return 3\n    wait $MULTIPID || return 4\n\n    # drop close\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x80000115\n    facet_failover $SINGLEMDS\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n    clients_up || return 1\n\n    ls $DIR/$tfile\n    $CHECKSTAT -t file $DIR/$tfile || return 2\n    rm $DIR/$tfile\n\n    return 0\n}\nrun_test 13 \"close resend timeout\"\n\n# test 14a removed after 18143 because it shouldn't fail anymore and do the same\n# as test_15a\n\ntest_14b() {\n\twait_mds_ost_sync\n\twait_delete_completed\n\n\tlocal beforeused=$(df -P $DIR | tail -1 | awk '{ print $3 }')\n\n\tmkdir -p $MOUNT1/$tdir\n\t$LFS setstripe -i 0 $MOUNT1/$tdir\n\treplay_barrier $SINGLEMDS\n\tcreatemany -o $MOUNT1/$tdir/$tfile- 5\n\n\t$LFS setstripe -i 0 $MOUNT2/$tfile-2\n\tdd if=/dev/zero of=$MOUNT2/$tfile-2 bs=1M count=5\n\tcreatemany -o $MOUNT1/$tdir/$tfile-3- 5\n\tumount $MOUNT2\n\n\tfail $SINGLEMDS\n\twait_recovery_complete $SINGLEMDS || error \"MDS recovery not done\"\n\n\t# first set of files should have been replayed\n\tunlinkmany $MOUNT1/$tdir/$tfile- 5 || error \"first unlinks failed\"\n\tunlinkmany $MOUNT1/$tdir/$tfile-3- 5 || error \"second unlinks failed\"\n\n\tzconf_mount $HOSTNAME $MOUNT2 || error \"mount $MOUNT2 failed\"\n\t[ -f $MOUNT2/$tfile-2 ] && error \"$MOUNT2/$tfile-2 exists!\"\n\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\twait_delete_completed || error \"wait_delete_complete failed\"\n\n\tlocal afterused=$(df -P $DIR | tail -1 | awk '{ print $3 }')\n\tlog \"before $beforeused, after $afterused\"\n\t# leave some margin for some files/dirs to be modified (OI, llog, etc)\n\t[ $afterused -le $((beforeused + $(fs_log_size))) ] ||\n\t\terror \"after $afterused > before $beforeused\"\n}\nrun_test 14b \"delete ost orphans if gap occured in objids due to VBR\"\n\ntest_15a() { # was test_15\n    replay_barrier $SINGLEMDS\n    createmany -o $MOUNT1/$tfile- 25\n    createmany -o $MOUNT2/$tfile-2- 1\n    umount $MOUNT2\n\n    fail $SINGLEMDS\n\n    unlinkmany $MOUNT1/$tfile- 25 || return 2\n    [ -e $MOUNT1/$tfile-2-0 ] && error \"$tfile-2-0 exists\"\n\n    zconf_mount `hostname` $MOUNT2 || error \"mount $MOUNT2 fail\"\n    return 0\n}\nrun_test 15a \"timeout waiting for lost client during replay, 1 client completes\"\n\ntest_15c() {\n    replay_barrier $SINGLEMDS\n    for ((i = 0; i < 2000; i++)); do\n        echo \"data\" > \"$MOUNT2/${tfile}-$i\" || error \"create ${tfile}-$i failed\"\n    done\n    umount $MOUNT2\n\n    fail $SINGLEMDS\n\n    zconf_mount `hostname` $MOUNT2 || error \"mount $MOUNT2 fail\"\n    return 0\n}\nrun_test 15c \"remove multiple OST orphans\"\n\ntest_16() {\n    replay_barrier $SINGLEMDS\n    createmany -o $MOUNT1/$tfile- 25\n    createmany -o $MOUNT2/$tfile-2- 1\n    umount $MOUNT2\n\n    facet_failover $SINGLEMDS\n    sleep $TIMEOUT\n    fail $SINGLEMDS\n\n    unlinkmany $MOUNT1/$tfile- 25 || return 2\n\n    zconf_mount `hostname` $MOUNT2 || error \"mount $MOUNT2 fail\"\n    return 0\n\n}\nrun_test 16 \"fail MDS during recovery (3571)\"\n\ntest_17() {\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    createmany -o $MOUNT1/$tfile- 25\n    createmany -o $MOUNT2/$tfile-2- 1\n\n    # Make sure the disconnect is lost\n    replay_barrier ost1\n    umount $MOUNT2\n\n    facet_failover ost1\n    sleep $TIMEOUT\n    fail ost1\n\n    unlinkmany $MOUNT1/$tfile- 25 || return 2\n\n    zconf_mount `hostname` $MOUNT2 || error \"mount $MOUNT2 fail\"\n    return 0\n\n}\nrun_test 17 \"fail OST during recovery (3571)\"\n\n# cleanup with blocked enqueue fails until timer elapses (MDS busy), wait for it\nexport NOW=0\n\ntest_18() { # bug 3822 - evicting client with enqueued lock\n\t#set -vx\n\tlocal DLMTRACE=$(do_facet $SINGLEMDS lctl get_param debug)\n\tdo_facet $SINGLEMDS lctl set_param debug=+dlmtrace\n\tmkdir -p $MOUNT1/$tdir || error \"mkdir $MOUNT1/$tdir failed\"\n\ttouch $MOUNT1/$tdir/${tfile}0 || error \"touch file failed\"\n\tstatmany -s $MOUNT1/$tdir/$tfile 1 500 &\n\tOPENPID=$!\n\tNOW=$SECONDS\n\t#define OBD_FAIL_LDLM_ENQUEUE_BLOCKED    0x30b\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x8000030b  # hold enqueue\n\tsleep 1\n\t#define OBD_FAIL_LDLM_BL_CALLBACK_NET\t\t\t0x305\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0\n\tdo_facet client lctl set_param fail_loc=0x80000305  # drop cb, evict\n\tcancel_lru_locks mdc\n\tusleep 500 # wait to ensure first client is one that will be evicted\n\topenfile -f O_RDONLY $MOUNT2/$tdir/$tfile\n\twait $OPENPID\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1\n\tdo_facet $SINGLEMDS lctl debug_kernel |\n\t\tgrep \"not entering recovery\" && error \"client not evicted\"\n\tdo_facet client \"lctl set_param fail_loc=0\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n}\nrun_test 18 \"ldlm_handle_enqueue succeeds on evicted export (3822)\"\n\ntest_19() { # Bug 10991 - resend of open request does not fail assertion.\n    replay_barrier $SINGLEMDS\n    drop_mdt_ldlm_reply \"createmany -o $DIR/$tfile 1\" || return 1\n    fail $SINGLEMDS\n    checkstat $DIR2/${tfile}0 || return 2\n    rm $DIR/${tfile}0 || return 3\n\n    return 0\n}\nrun_test 19 \"resend of open request\"\n\ntest_20() { #16389\n\tlocal before=$SECONDS\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR1/$tfile.a\n\ttouch $DIR2/$tfile.b\n\tumount $DIR2\n\tfail $SINGLEMDS\n\trm $DIR1/$tfile.a\n\tzconf_mount $HOSTNAME $DIR2 || error \"mount $DIR2 fail\"\n\tlocal tier1=$((SECONDS - before))\n\n\tbefore=$SECONDS\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR1/$tfile.a\n\ttouch $DIR2/$tfile.b\n\tumount $DIR2\n\tfail $SINGLEMDS\n\trm $DIR1/$tfile.a\n\tzconf_mount $HOSTNAME $DIR2 || error \"mount $DIR2 fail\"\n\tlocal tier2=$((SECONDS - before))\n\n\t# timeout is more than 1.5x original timeout\n\t((tier2 < tier1 * 6 / 4)) ||\n\t\terror \"recovery time $tier2 >= 1.5x original time $tier1\"\n}\nrun_test 20 \"recovery time is not increasing\"\n\n# commit on sharing tests\ntest_21a() {\n    local param_file=$TMP/$tfile-params\n\n\tsave_lustre_params $SINGLEMDS \"mdt.*.commit_on_sharing\" > $param_file\n    do_facet $SINGLEMDS lctl set_param mdt.*.commit_on_sharing=1\n    touch  $MOUNT1/$tfile-1\n    mv  $MOUNT2/$tfile-1 $MOUNT2/$tfile-2\n    mv  $MOUNT1/$tfile-2 $MOUNT1/$tfile-3\n    replay_barrier_nosync $SINGLEMDS\n    umount $MOUNT2\n\n    facet_failover $SINGLEMDS\n\n    # all renames are replayed\n    unlink  $MOUNT1/$tfile-3 || return 2\n\n    zconf_mount `hostname` $MOUNT2 || error \"mount $MOUNT2 fail\"\n\n    do_facet $SINGLEMDS lctl set_param mdt.*.commit_on_sharing=0\n    rm -rf $MOUNT1/$tfile-*\n    restore_lustre_params < $param_file\n    rm -f $param_file\n    return 0\n}\nrun_test 21a \"commit on sharing\"\n\ntest_21b_sub () {\n\tlocal mds=$1\n\tdo_node $CLIENT1 rm -f $MOUNT1/$tfile-*\n\n\tdo_facet $mds sync\n\tdo_node $CLIENT1 touch $MOUNT1/$tfile-1\n\tdo_node $CLIENT2 mv $MOUNT1/$tfile-1 $MOUNT1/$tfile-2\n\tdo_node $CLIENT1 mv $MOUNT1/$tfile-2 $MOUNT1/$tfile-3\n\n\treplay_barrier_nosync $mds\n\tshutdown_client $CLIENT2 $MOUNT1\n\n\tfacet_failover $mds\n\n\t# were renames replayed?\n\tlocal rc=0\n\techo UNLINK $MOUNT1/$tfile-3\n\tdo_node $CLIENT1 unlink  $MOUNT1/$tfile-3 ||\n\t\t{ echo \"unlink $tfile-3 fail!\" && rc=1; }\n\n\tboot_node $CLIENT2\n\tzconf_mount_clients $CLIENT2 $MOUNT1 ||\n\t\terror \"mount $CLIENT2 $MOUNT1 fail\"\n\n\treturn $rc\n}\n\ntest_21b() {\n\t[ -z \"$CLIENTS\" ] && skip \"Need two or more clients\" && return\n\t[ $CLIENTCOUNT -lt 2 ] &&\n\t\t{ skip \"Need 2+ clients, have $CLIENTCOUNT\" && return; }\n\n\tif [ \"$FAILURE_MODE\" = \"HARD\" ] && mixed_mdt_devs; then\n\t\tskip \"Several MDTs on one MDS with FAILURE_MODE=$FAILURE_MODE\"\n\t\treturn 0\n\tfi\n\n\tzconf_umount_clients $CLIENTS $MOUNT2\n\tzconf_mount_clients $CLIENTS $MOUNT1\n\n\tlocal param_file=$TMP/$tfile-params\n\n\tlocal mdtidx=$($LFS getstripe -m $MOUNT1)\n\tlocal facet=mds$((mdtidx + 1))\n\n\tsave_lustre_params $facet \"mdt.*.commit_on_sharing\" > $param_file\n\n\t# COS enabled\n\tlocal COS=1\n\tdo_facet $facet lctl set_param mdt.*.commit_on_sharing=$COS\n\n\ttest_21b_sub $facet || error \"Not all renames are replayed. COS=$COS\"\n\n\t# there is still a window when transactions may be written to disk\n\t# before the mds device is set R/O. To avoid such a rare test failure,\n\t# the check is repeated several times.\n\tCOS=0\n\tlocal n_attempts=1\n\twhile true; do\n\t\t# COS disabled (should fail)\n\t\tdo_facet $facet lctl set_param mdt.*.commit_on_sharing=$COS\n\n\t\ttest_21b_sub $facet || break\n\t\tn_attempts=$((n_attempts + 1))\n\t\t[ $n_attempts -gt 3 ] &&\n\t\t\terror \"can't check if COS works: rename replied w/o COS\"\n\tdone\n\tzconf_mount_clients $CLIENTS $MOUNT2\n\trestore_lustre_params < $param_file\n\trm -f $param_file\n\treturn 0\n}\nrun_test 21b \"commit on sharing, two clients\"\n\ncheckstat_22() {\n\tcheckstat $MOUNT1/$remote_dir || return 1\n\tcheckstat $MOUNT1/$remote_dir/dir || return 2\n\tcheckstat $MOUNT1/$remote_dir/$tfile-1 || return 3\n\tcheckstat $MOUNT1/$remote_dir/dir/$tfile-1 || return 4\n\treturn 0\n}\n\ncreate_remote_dir_files_22() {\n\tdo_node $CLIENT2 mkdir ${MOUNT2}/$remote_dir/dir || return 1\n\tdo_node $CLIENT1 createmany -o $MOUNT1/$remote_dir/dir/$tfile- 2 ||\n\t\t\t\t\t\t\t    return 2\n\tdo_node $CLIENT2 createmany -o $MOUNT2/$remote_dir/$tfile- 2 ||\n\t\t\t\t\t\t\t    return 3\n\treturn 0\n}\n\ntest_22a () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=${tdir}/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\n\tfail mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"lfs mkdir failed\"\n\n\treplay_barrier mds$MDTIDX\n\tcreate_remote_dir_files_22 || error \"Remote creation failed $?\"\n\tfail mds$MDTIDX\n\n\tcheckstat_22 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 22a \"c1 lfs mkdir -i 1 dir1, M1 drop reply & fail, c2 mkdir dir1/dir\"\n\ntest_22b () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"lfs mkdir failed\"\n\n\treplay_barrier mds$MDTIDX\n\tcreate_remote_dir_files_22 || error \"Remote creation failed $?\"\n\tfail mds${MDTIDX}\n\n\tcheckstat_22 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 22b \"c1 lfs mkdir -i 1 d1, M1 drop reply & fail M0/M1, c2 mkdir d1/dir\"\n\ntest_22c () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=${tdir}/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP    0x1701\n\tdo_facet mds$MDTIDX lctl set_param fail_loc=0x1701\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds$MDTIDX lctl set_param fail_loc=0\n\n\tfail mds$MDTIDX\n\twait $CLIENT_PID || error \"lfs mkdir failed\"\n\n\treplay_barrier mds$MDTIDX\n\tcreate_remote_dir_files_22 || error \"Remote creation failed $?\"\n\tfail mds$MDTIDX\n\n\tcheckstat_22 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 22c \"c1 lfs mkdir -i 1 d1, M1 drop update & fail M1, c2 mkdir d1/dir\"\n\ntest_22d () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=${tdir}/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP    0x1701\n\tdo_facet mds$MDTIDX lctl set_param fail_loc=0x1701\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds$MDTIDX lctl set_param fail_loc=0\n\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"lfs mkdir failed\"\n\n\treplay_barrier mds$MDTIDX\n\tcreate_remote_dir_files_22 || error \"Remote creation failed $?\"\n\tfail mds$MDTIDX\n\n\tcheckstat_22 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 22d \"c1 lfs mkdir -i 1 d1, M1 drop update & fail M0/M1,c2 mkdir d1/dir\"\n\ncheckstat_23() {\n\tcheckstat $MOUNT1/$remote_dir || return 1\n\tcheckstat $MOUNT1/$remote_dir/$tfile-1 || return 2\n\treturn 0\n}\n\ncreate_remote_dir_files_23() {\n\tdo_node $CLIENT2 mkdir ${MOUNT2}/$remote_dir || return 1\n\tdo_node $CLIENT2 createmany -o $MOUNT2/$remote_dir/$tfile- 2 || return 2\n\treturn 0\n}\n\ntest_23a () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir ||\n\t\t\terror \"lfs mkdir failed\"\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\tdo_node $CLIENT1 rmdir $MOUNT1/$remote_dir &\n\tlocal CLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0\n\n\tfail mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"rmdir remote dir failed\"\n\n\treplay_barrier mds${MDTIDX}\n\tcreate_remote_dir_files_23 || error \"Remote creation failed $?\"\n\tfail mds${MDTIDX}\n\n\tcheckstat_23 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 23a \"c1 rmdir d1, M1 drop reply and fail, client2 mkdir d1\"\n\ntest_23b () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir ||\n\t\t\terror \"lfs mkdir failed\"\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\tdo_node $CLIENT1 rmdir $MOUNT1/$remote_dir &\n\tlocal CLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0\n\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"rmdir remote dir failed\"\n\n\treplay_barrier mds${MDTIDX}\n\tcreate_remote_dir_files_23 || error \"Remote creation failed $?\"\n\tfail mds${MDTIDX}\n\n\tcheckstat_23 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || error \"rmdir remote_dir failed\"\n\treturn 0\n}\nrun_test 23b \"c1 rmdir d1, M1 drop reply and fail M0/M1, c2 mkdir d1\"\n\ntest_23c () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir ||\n\t\t\terror \"lfs mkdir failed\"\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP    0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\tdo_node $CLIENT1 rmdir $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0\n\n\tfail mds${MDTIDX}\n\twait $CLIENT_PID || error \"rmdir remote dir failed\"\n\n\treplay_barrier mds${MDTIDX}\n\tcreate_remote_dir_files_23 || error \"Remote creation failed $?\"\n\tfail mds${MDTIDX}\n\n\tcheckstat_23 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || return 6\n\treturn 0\n}\nrun_test 23c \"c1 rmdir d1, M0 drop update reply and fail M0, c2 mkdir d1\"\n\ntest_23d () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\tdo_node $CLIENT1 mkdir -p $MOUNT1/${tdir}\n\tdo_node $CLIENT1 $LFS mkdir -i $MDTIDX $MOUNT1/$remote_dir ||\n\t\t\terror \"lfs mkdir failed\"\n\n\t# OBD_FAIL_UPDATE_OBJ_NET    0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\tdo_node $CLIENT1 rmdir $MOUNT1/$remote_dir &\n\tCLIENT_PID=$!\n\tsleep 1\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0\n\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\twait $CLIENT_PID || error \"rmdir remote dir failed\"\n\n\treplay_barrier mds${MDTIDX}\n\tcreate_remote_dir_files_23 || error \"Remote creation failed $?\"\n\tfail mds${MDTIDX}\n\n\tcheckstat_23 || error \"check stat failed $?\"\n\n\trm -rf $MOUNT1/$tdir || return 6\n\treturn 0\n}\nrun_test 23d \"c1 rmdir d1, M0 drop update reply and fail M0/M1, c2 mkdir d1\"\n\ntest_24 () {\n\t[[ \"$MDS1_VERSION\" -gt $(version_code 2.5.2) ]] ||\n\t\tskip \"Need MDS version newer than 2.5.2\"\n\n\ttouch $MOUNT/$tfile\n\tstat $MOUNT/$tfile >&/dev/null\n# OBD_FAIL_MDS_REINT_NET_REP\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x119\n\t$TRUNCATE $MOUNT/$tfile 100 &\n\tPID=$!\n\tsleep 1\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\t# sync to release rep-ack lock quickly\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t    \"lctl set_param -n osd*.*MDT*.force_sync 1\"\n\trm $MOUNT2/$tfile\n\twait\n}\nrun_test 24 \"reconstruct on non-existing object\"\n\n# end commit on sharing tests \n\ntest_25() {\n\tcancel_lru_locks osc\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\n\t# get lock for the 1st client\n\tdd if=/dev/zero of=$DIR/$tfile count=1 >/dev/null ||\n\t\terror \"failed to write data\"\n\n\t# get waiting locks for the 2nd client\n\tdrop_ldlm_cancel \"multiop $DIR2/$tfile Ow512\" &\n\tsleep 1\n\n\t# failover, replay and resend replayed waiting locks\n\tif [ \"$OST1_VERSION\" -ge $(version_code 2.6.90) ]; then\n\t\t#define OBD_FAIL_LDLM_SRV_CP_AST      0x325\n\t\tdo_facet ost1 lctl set_param fail_loc=0x80000325\n\telse\n\t\t#define OBD_FAIL_OST_LDLM_REPLY_NET\t0x213\n\t\tdo_facet ost1 lctl set_param fail_loc=0x80000213\n\tfi\n\n\tfail ost1\n\n\t# multiop does not finish because CP AST is skipped;\n\t# it is ok to kill it in the test, because CP AST is already re-sent\n\t# and it does not hung forever in real life\n\tkillall multiop\n\twait\n}\nrun_test 25 \"replay|resend\"\n\ncleanup_26() {\n\ttrap 0\n\tkill -9 $tar_26_pid\n\tkill -9 $dbench_26_pid\n\tkillall -9 dbench\n}\n\ntest_26() {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=600\n\t[ \"$SLOW\" = \"no\" ] && duration=200\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tlocal start_ts=$SECONDS\n\tlocal rc=0\n\n\ttrap cleanup_26\tEXIT\n\t(\n\t\tlocal tar_dir=$DIR/$tdir/run_tar\n\t\twhile true; do\n\t\t\ttest_mkdir -p -c$MDSCOUNT $tar_dir || break\n\t\t\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t\t\t$LFS setdirstripe -D -c$MDSCOUNT $tar_dir ||\n\t\t\t\t\terror \"set default dirstripe failed\"\n\t\t\tfi\n\t\t\tcd $tar_dir || break\n\t\t\ttar cf - /etc | tar xf - || error \"tar failed\"\n\t\t\tcd $DIR/$tdir || break\n\t\t\trm -rf $tar_dir || break\n\t\tdone\n\t)&\n\ttar_26_pid=$!\n\techo \"Started tar $tar_26_pid\"\n\n\t(\n\t\tlocal dbench_dir=$DIR2/$tdir/run_dbench\n\t\twhile true; do\n\t\t\ttest_mkdir -p -c$MDSCOUNT $dbench_dir || break\n\t\t\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t\t\t$LFS setdirstripe -D -c$MDSCOUNT $dbench_dir ||\n\t\t\t\t\terror \"set default dirstripe failed\"\n\t\t\tfi\n\t\t\tcd $dbench_dir || break\n\t\t\trundbench 1 -D $dbench_dir -t 100 &>/dev/null || break\n\t\t\tcd $DIR/$tdir || break\n\t\t\trm -rf $dbench_dir || break\n\t\tdone\n\t)&\n\tdbench_26_pid=$!\n\techo \"Started dbench $dbench_26_pid\"\n\n\tlocal num_failovers=0\n\tlocal fail_index=1\n\twhile [ $((SECONDS - start_ts)) -lt $duration ]; do\n\t\tkill -0 $tar_26_pid || error \"tar $tar_26_pid missing\"\n\t\tkill -0 $dbench_26_pid || error \"dbench $dbench_26_pid missing\"\n\t\tsleep 2\n\t\treplay_barrier mds$fail_index\n\t\tsleep 2 # give clients a time to do operations\n\t\t# Increment the number of failovers\n\t\tnum_failovers=$((num_failovers + 1))\n\t\tlog \"$TESTNAME fail mds$fail_index $num_failovers times\"\n\t\tfail mds$fail_index\n\t\tif [ $fail_index -ge $MDSCOUNT ]; then\n\t\t\tfail_index=1\n\t\telse\n\t\t\tfail_index=$((fail_index + 1))\n\t\tfi\n\tdone\n\t# stop the client loads\n\tkill -0 $tar_26_pid || error \"tar $tar_26_pid stopped\"\n\tkill -0 $dbench_26_pid || error \"dbench $dbench_26_pid stopped\"\n\tcleanup_26 || true\n}\nrun_test 26 \"dbench and tar with mds failover\"\n\ntest_28() {\n\t$LFS setstripe -i 0 -c 1 $DIR2/$tfile\n\tdd if=/dev/zero of=$DIR2/$tfile bs=4096 count=1\n\n\t#define OBD_FAIL_LDLM_SRV_BL_AST\t 0x324\n\tdo_facet ost1 $LCTL set_param fail_loc=0x80000324\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 &\n\tlocal pid=$!\n\tsleep 2\n\n\t#define OBD_FAIL_LDLM_GRANT_CHECK        0x32a\n\tdo_facet ost1 $LCTL set_param fail_loc=0x32a\n\n\tfail ost1\n\n\tsleep 2\n\tcancel_lru_locks OST0000-osc\n\twait $pid || error \"dd failed\"\n}\nrun_test 28 \"lock replay should be ordered: waiting after granted\"\n\ntest_29() {\n\tlocal dir0=$DIR/$tdir/d0\n\tlocal dir1=$DIR/$tdir/d1\n\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ $CLIENTCOUNT -lt 2 ] && skip \"needs >= 2 clients\" && return 0\n\t[ \"$CLIENT1\" == \"$CLIENT2\" ] &&\n\t\tskip \"clients must be on different nodes\" && return 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i0 $dir0\n\t$LFS mkdir -i1 $dir1\n\tsync\n\n\treplay_barrier mds2\n\t# create a remote dir, drop reply\n\t#define OBD_FAIL_PTLRPC_ROUND_XID 0x530\n\t$LCTL set_param fail_loc=0x530 fail_val=36\n\t#define OBD_FAIL_MDS_REINT_MULTI_NET_REP 0x15a\n\tdo_facet mds2 $LCTL set_param fail_loc=0x8000015a\n\techo make remote dir d0 for $dir0\n\t$LFS mkdir -i1 -c1 $dir0/d3 &\n\tsleep 1\n\n\techo make local dir d1 for $dir1\n\tdo_node $CLIENT2 $LCTL set_param fail_loc=0x530 fail_val=36\n\tdo_node $CLIENT2 mkdir $dir1/d4\n\n\tfail mds2\n}\nrun_test 29 \"replay vs update with the same xid\"\n\ncomplete $SECONDS\nSLEEP=$((SECONDS - $NOW))\n[ $SLEEP -lt $TIMEOUT ] && sleep $SLEEP\n[ \"$MOUNTED2\" = yes ] && zconf_umount $HOSTNAME $MOUNT2 || true\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1074}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$REPLAY_OST_SINGLE_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n# bug number for SLOW test:\n# time in minutes:                 40 min\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"5\"\n\nbuild_test_filter\n\n# While we do not use OSTCOUNT=1 setup anymore,\n# ost1failover_HOST is used\n#ostfailover_HOST=${ostfailover_HOST:-$ost_HOST}\n#failover= must be defined in OST_MKFS_OPTIONS if ostfailover_HOST != ost_HOST\n\nrequire_dsh_ost || exit 0\n\ncheck_and_setup_lustre\nassert_DIR\nrm -rf $DIR/[df][0-9]*\n\nTDIR=$DIR/d0.${TESTSUITE}\nmkdir -p $TDIR\n$LFS setstripe $TDIR -i 0 -c 1\n$LFS getstripe $TDIR\n\ntest_0a() {\n\tzconf_umount $(hostname) $MOUNT -f\n\t# needs to run during initial client->OST connection\n\t#define OBD_FAIL_OST_ALL_REPLY_NET       0x211\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000211\"\n\tzconf_mount $(hostname) $MOUNT && $LFS df $MOUNT || error \"mount fail\"\n}\nrun_test 0a \"target handle mismatch (bug 5317)\"\n\ntest_0b() {\n\tfail ost1\n\tcp /etc/profile  $TDIR/$tfile\n\tsync\n\tdiff /etc/profile $TDIR/$tfile\n\trm -f $TDIR/$tfile\n}\nrun_test 0b \"empty replay\"\n\ntest_1() {\n\tdate > $TDIR/$tfile || error \"error creating $TDIR/$tfile\"\n\tfail ost1\n\t$CHECKSTAT -t file $TDIR/$tfile || error \"check for file failed\"\n\trm -f $TDIR/$tfile\n}\nrun_test 1 \"touch\"\n\ntest_2() {\n\tfor i in $(seq 10); do\n\t\techo \"tag-$i\" > $TDIR/$tfile-$i ||\n\t\t\terror \"create $TDIR/$tfile-$i failed\"\n\tdone\n\tfail ost1\n\tfor i in $(seq 10); do\n\t\tgrep -q \"tag-$i\" $TDIR/$tfile-$i ||\n\t\t\terror \"grep $TDIR/$tfile-$i failed\"\n\tdone\n\trm -f $TDIR/$tfile-*\n}\nrun_test 2 \"|x| 10 open(O_CREAT)s\"\n\ntest_3() {\n\tverify=$ROOT/tmp/verify-$$\n\tdd if=/dev/urandom bs=4096 count=1280 | tee $verify > $TDIR/$tfile &\n\tddpid=$!\n\tsync &\n\tfail ost1\n\twait $ddpid || error \"wait for dd failed\"\n\tcmp $verify $TDIR/$tfile || error \"compare $verify $TDIR/$tfile failed\"\n\trm -f $verify $TDIR/$tfile\n}\nrun_test 3 \"Fail OST during write, with verification\"\n\ntest_4() {\n\tverify=$ROOT/tmp/verify-$$\n\tdd if=/dev/urandom bs=4096 count=1280 | tee $verify > $TDIR/$tfile\n\t# invalidate cache, so that we're reading over the wire\n\tcancel_lru_locks osc\n\tcmp $verify $TDIR/$tfile &\n\tcmppid=$!\n\tfail ost1\n\twait $cmppid || error \"wait on cmp failed\"\n\trm -f $verify $TDIR/$tfile\n}\nrun_test 4 \"Fail OST during read, with verification\"\n\niozone_bg () {\n    local args=$@\n\n    local tmppipe=$TMP/${TESTSUITE}.${TESTNAME}.pipe\n    mkfifo $tmppipe\n\n    echo \"+ iozone $args\"\n    iozone $args > $tmppipe &\n\n    local pid=$!\n\n    echo \"tmppipe=$tmppipe\"\n    echo iozone pid=$pid\n\n    # iozone exit code is 0 even if iozone is not completed\n    # need to check iozone output  on \"complete\"\n    local iozonelog=$TMP/${TESTSUITE}.iozone.log\n    rm -f $iozonelog\n    cat $tmppipe | while read line ; do\n        echo \"$line\"\n        echo \"$line\" >>$iozonelog\n    done;\n\n    local rc=0\n    wait $pid\n    rc=$?\n    if ! $(tail -1 $iozonelog | grep -q complete); then\n        echo iozone failed!\n        rc=1\n    fi\n    rm -f $tmppipe\n    rm -f $iozonelog\n    return $rc\n}\n\ntest_5() {\n\tif [ -z \"$(which iozone 2> /dev/null)\" ]; then\n\t\tskip_env \"iozone missing\"\n\t\treturn 0\n\tfi\n\n\t# striping is -c 1, get min of available\n\tlocal minavail=$(lctl get_param -n osc.*[oO][sS][cC][-_]*.kbytesavail |\n\t\tsort -n | head -n1)\n\tlocal size=$(( minavail * 3/4 ))\n\tlocal GB=1048576  # 1048576KB == 1GB\n\n\tif (( size > GB )); then\n\t\tsize=$GB\n\tfi\n\t# no random I/O (-i 2) as it's very slow with ZFS\n\tlocal iozone_opts=\"-i 0 -i 1 -+d -r 4 -s $size -f $TDIR/$tfile\"\n\n\tiozone_bg $iozone_opts &\n\tlocal pid=$!\n\n\techo iozone bg pid=$pid\n\n\tsleep 8\n\tfail ost1\n\tlocal rc=0\n\twait $pid || error \"wait on iozone failed\"\n\trc=$?\n\tlog \"iozone rc=$rc\"\n\trm -f $TDIR/$tfile\n\twait_delete_completed_mds\n\t[ $rc -eq 0 ] || error \"iozone failed\"\n\treturn $rc\n}\nrun_test 5 \"Fail OST during iozone\"\n\nkbytesfree() {\n   calc_osc_kbytes kbytesfree\n}\n\ntest_6() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return 0\n\n\tlocal f=$TDIR/$tfile\n\tsync && sleep 5 && sync  # wait for delete thread\n\n\t# wait till space is returned, following\n\t# (( $before > $after_dd)) test counting on that\n\twait_mds_ost_sync || error \"first wait_mds_ost_sync failed\"\n\twait_destroy_complete || error \"first wait_destroy_complete failed\"\n\tsync_all_data\n\n\tlocal before=$(kbytesfree)\n\tdd if=/dev/urandom bs=4096 count=1280 of=$f || error \"dd failed\"\n\t$LFS getstripe $f || error \"$LFS getstripe $f failed\"\n\tlocal stripe_index=$(lfs getstripe -i $f)\n\n\tsync\n\tsleep 2 # ensure we have a fresh statfs\n\tsync\n\n\t#define OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000119\"\n\n\t# retry till statfs returns useful results\n\tlocal after_dd=$(kbytesfree)\n\tlocal i=0\n\twhile (( $before <= $after_dd && $i < 20 )); do\n\t\tsync\n\t\tsleep 1\n\t\tlet ++i\n\t\tafter_dd=$(kbytesfree)\n\tdone\n\n\tlog \"before_free: $before after_dd_free: $after_dd took $i seconds\"\n\t(( $before > $after_dd )) ||\n\t\terror \"free grew after dd: before:$before after_dd:$after_dd\"\n\n\trm -f $f\n\tfail ost$((stripe_index + 1))\n\twait_recovery_complete ost$((stripe_index + 1)) ||\n\t\terror \"OST$((stripe_index + 1)) recovery not completed\"\n\t$CHECKSTAT -t file $f && return 2 || true\n\tsync\n\t# let the delete happen\n\twait_mds_ost_sync || error \"second wait_mds_ost_sync failed\"\n\twait_delete_completed || error \"second wait_delete_completed failed\"\n\tlocal after=$(kbytesfree)\n\tlog \"free_before: $before free_after: $after\"\n\t(( $before <= $after + $(fs_log_size) )) ||\n\t\terror \"$before > $after + logsize $(fs_log_size)\"\n}\nrun_test 6 \"Fail OST before obd_destroy\"\n\ntest_7() {\n\tlocal f=$TDIR/$tfile\n\tsync && sleep 5 && sync\t# wait for delete thread\n\n\t# wait till space is returned, following\n\t# (( $before > $after_dd)) test counting on that\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\twait_destroy_complete || error \"wait_destroy_complete failed\"\n\n\tlocal before=$(kbytesfree)\n\tdd if=/dev/urandom bs=4096 count=1280 of=$f ||\n\t\terror \"dd to file failed: $?\"\n\n\tsync\n\tlocal after_dd=$(kbytesfree)\n\tlocal i=0\n\twhile (( $before <= $after_dd && $i < 10 )); do\n\t\tsync\n\t\tsleep 1\n\t\tlet ++i\n\t\tafter_dd=$(kbytesfree)\n\tdone\n\n\tlog \"before: $before after_dd: $after_dd took $i seconds\"\n\t(( $before > $after_dd )) ||\n\t\terror \"space grew after dd: before:$before after_dd:$after_dd\"\n\treplay_barrier ost1\n\trm -f $f\n\tfail ost1\n\twait_recovery_complete ost1 || error \"OST recovery not done\"\n\t$CHECKSTAT -t file $f && return 2 || true\n\tsync\n\t# let the delete happen\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\twait_delete_completed || error \"wait_delete_completed failed\"\n\tlocal after=$(kbytesfree)\n\tlog \"before: $before after: $after\"\n\t(( $before <= $after + $(fs_log_size) )) ||\n\t\t error \"$before > $after + logsize $(fs_log_size)\"\n}\nrun_test 7 \"Fail OST before obd_destroy\"\n\ntest_8a() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.0) ]] ||\n\t\tskip \"Need MDS version at least 2.3.0\"\n\tverify=$ROOT/tmp/verify-$$\n\tdd if=/dev/urandom of=$verify bs=4096 count=1280 ||\n\t\terror \"Create verify file failed\"\n\t#define OBD_FAIL_OST_DQACQ_NET 0x230\n\tdo_facet ost1 \"lctl set_param fail_loc=0x230\"\n\tdd if=$verify of=$TDIR/$tfile bs=4096 count=1280 oflag=sync &\n\tddpid=$!\n\tsleep $TIMEOUT  # wait for the io to become redo io\n\tif ! ps -p $ddpid  > /dev/null 2>&1; then\n\t\terror \"redo io finished incorrectly\"\n\tfi\n\tdo_facet ost1 \"lctl set_param fail_loc=0\"\n\twait $ddpid || true\n\tcancel_lru_locks osc\n\tcmp $verify $TDIR/$tfile || error \"compare $verify $TDIR/$tfile failed\"\n\trm -f $verify $TDIR/$tfile\n\tmessage=$(dmesg | grep \"redo for recoverable error -115\")\n\t[ -z \"$message\" ] || error \"redo error messages found in dmesg\"\n}\nrun_test 8a \"Verify redo io: redo io when get -EINPROGRESS error\"\n\ntest_8b() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.0) ]] ||\n\t\tskip \"Need MDS version at least 2.3.0\"\n\tverify=$ROOT/tmp/verify-$$\n\tdd if=/dev/urandom of=$verify bs=4096 count=1280 ||\n\t\terror \"Create verify file failed\"\n\t#define OBD_FAIL_OST_DQACQ_NET 0x230\n\tdo_facet ost1 \"lctl set_param fail_loc=0x230\"\n\tdd if=$verify of=$TDIR/$tfile bs=4096 count=1280 oflag=sync &\n\tddpid=$!\n\tsleep $TIMEOUT  # wait for the io to become redo io\n\tfail ost1\n\tdo_facet ost1 \"lctl set_param fail_loc=0\"\n\twait $ddpid || error \"dd did not complete\"\n\tcancel_lru_locks osc\n\tcmp $verify $TDIR/$tfile || error \"compare $verify $TDIR/$tfile failed\"\n\trm -f $verify $TDIR/$tfile\n}\nrun_test 8b \"Verify redo io: redo io should success after recovery\"\n\ntest_8c() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.0) ]] ||\n\t\tskip \"Need MDS version at least 2.3.0\"\n\tverify=$ROOT/tmp/verify-$$\n\tdd if=/dev/urandom of=$verify bs=4096 count=1280 ||\n\t\terror \"Create verify file failed\"\n\t#define OBD_FAIL_OST_DQACQ_NET 0x230\n\tdo_facet ost1 \"lctl set_param fail_loc=0x230\"\n\tdd if=$verify of=$TDIR/$tfile bs=4096 count=1280 oflag=sync &\n\tddpid=$!\n\tsleep $TIMEOUT  # wait for the io to become redo io\n\tost_evict_client\n\t# allow recovery to complete\n\tsleep $((TIMEOUT + 2))\n\tdo_facet ost1 \"lctl set_param fail_loc=0\"\n\twait $ddpid\n\tcancel_lru_locks osc\n\tcmp $verify $TDIR/$tfile && error \"compare files should fail\"\n\trm -f $verify $TDIR/$tfile\n}\nrun_test 8c \"Verify redo io: redo io should fail after eviction\"\n\ntest_8d() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.0) ]] ||\n\t\tskip \"Need MDS version at least 2.3.0\"\n\t#define OBD_FAIL_MDS_DQACQ_NET 0x187\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x187\"\n\t# test the non-intent create path\n\tmcreate $TDIR/$tfile &\n\tcpid=$!\n\tsleep $TIMEOUT\n\tif ! ps -p $cpid  > /dev/null 2>&1; then\n\t\terror \"mknod finished incorrectly\"\n\tfi\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\twait $cpid || error \"mcreate did not complete\"\n\tstat $TDIR/$tfile || error \"mknod failed\"\n\n\trm $TDIR/$tfile\n\n\t#define OBD_FAIL_MDS_DQACQ_NET 0x187\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x187\"\n\t# test the intent create path\n\topenfile -f O_RDWR:O_CREAT $TDIR/$tfile &\n\tcpid=$!\n\tsleep $TIMEOUT\n\tif ! ps -p $cpid > /dev/null 2>&1; then\n\t\terror \"open finished incorrectly\"\n\tfi\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\twait $cpid || error \"openfile failed\"\n\tstat $TDIR/$tfile || error \"open failed\"\n}\nrun_test 8d \"Verify redo creation on -EINPROGRESS\"\n\ntest_8e() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.0) ]] ||\n\t\tskip \"Need MDS version at least 2.3.0\"\n\tsleep 1 # ensure we have a fresh statfs\n\t#define OBD_FAIL_OST_STATFS_EINPROGRESS 0x231\n\tdo_facet ost1 \"lctl set_param fail_loc=0x231\"\n\t$LFS df $MOUNT &\n\tdfpid=$!\n\tsleep $TIMEOUT\n\tif ! ps -p $dfpid  > /dev/null 2>&1; then\n\t\tdo_facet ost1 \"lctl set_param fail_loc=0\"\n\t\terror \"df shouldn't have completed!\"\n\tfi\n}\nrun_test 8e \"Verify that ptlrpc resends request on -EINPROGRESS\"\n\ntest_9() {\n\t[ \"$OST1_VERSION\" -ge $(version_code 2.6.54) ] ||\n\t\tskip \"Need OST version at least 2.6.54\"\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile || error \"setstripe failed\"\n\n\t# LU-1573 - Add duplicate write to generate grants\n\tdd if=/dev/zero of=$DIR/$tfile count=1 bs=1M > /dev/null ||\n\t\terror \"First write failed\"\n\treplay_barrier ost1\n\t# do IO\n\tdd if=/dev/zero of=$DIR/$tfile count=1 bs=1M > /dev/null ||\n\t\terror \"failed to write\"\n\t# failover, replay and resend replayed waiting request\n\t#define OBD_FAIL_TGT_REPLAY_DELAY2       0x714\n\tdo_facet ost1 $LCTL set_param fail_loc=0x00000714\n\tdo_facet ost1 $LCTL set_param fail_val=$TIMEOUT\n\tfail ost1\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\tdo_facet ost1 \"dmesg | tail -n 100\" |\n\t\tsed -n '/no req deadline/,$ p' | grep -qi 'Already past' &&\n\t\treturn 1\n\treturn 0\n}\nrun_test 9 \"Verify that no req deadline happened during recovery\"\n\ntest_10() {\n\trm -f $TDIR/$tfile\n\n\tdd if=/dev/zero of=$TDIR/$tfile count=10 || error \"dd failed\"\n\n\t#define OBD_FAIL_OSC_DELAY_IO            0x414\n\t$LCTL set_param fail_val=60 fail_loc=0x414\n\tcancel_lru_locks OST0000-osc &\n\tsleep 2\n\tfacet_failover ost1 || error \"failover: $?\"\n\n\t#define OBD_FAIL_LDLM_GRANT_CHECK        0x32a\n\t$LCTL set_param fail_loc=0x32a\n\tstat $TDIR/$tfile\n\n\twait\n}\nrun_test 10 \"conflicting PW & PR locks on a client\"\n\ntest_12() {\n\t[ $FAILURE_MODE != \"HARD\" ] &&\n\t\tskip \"Test needs FAILURE_MODE HARD\" && return 0\n\tremote_ost || { skip \"need remote OST\" && return 0; }\n\n\tlocal tmp=$TMP/$tdir\n\tlocal dir=$DIR/$tdir\n\tdeclare -a pids\n\n\n\tmkdir -p $tmp || error \"can't create $tmp\"\n\tmkdir -p $dir || error \"can't create $dir\"\n\n\t$LFS setstripe -c 1 -i 0 $dir\n\n\tfor i in `seq 1 10`; do mkdir $dir/d$i; done\n\n\t#define OBD_FAIL_OST_DELAY_TRANS        0x245\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x245\" ||\n\t\terror \"can't set fail_loc\"\n\n\tfor i in `seq 1 10`;\n\tdo\n\t\tcreatemany -o $dir/d$i/$(openssl rand -base64 12) 500 &\n\t\tpids+=($!)\n\tdone\n\techo \"Waiting createmany pids\"\n\twait ${pids[@]}\n\n\tls -lR $dir > $tmp/ls_r_out 2>&1&\n\tlocal ls_pid=$!\n\n\tfacet_failover ost1\n\n\techo \"starting wait for ls -l\"\n\twait $ls_pid\n\tgrep \"?\\|No such file or directory\" $tmp/ls_r_out &&\n\t\terror \"Found file without object on OST\"\n\trm -rf $tmp\n\trm -rf $dir\n}\nrun_test 12 \"check stat after OST failover\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 477}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"REPLAY_SINGLE_LMV_EXCEPT \"\nbuild_test_filter\n\nSETUP=${SETUP:-\"setup\"}\nCLEANUP=${CLEANUP:-\"stopall\"}\n\nif [ \"$ONLY\" == \"cleanup\" ]; then\n\tlctl set_param debug=0 || true\n\t$CLEANUP\n\texit 0\nfi\n\nsetup() {\n\tformatall\n\tsetupall\n}\n\n$SETUP\n\nif [ \"$ONLY\" == \"setup\" ]; then\n    exit 0\nfi\n\nmkdir -p $DIR\n\n# LU-482 Avert LVM and VM inability to flush caches in pre .33 kernels\nif [ $LINUX_VERSION_CODE -lt $(version_code 2.6.33) ]; then\n    sync\n    do_facet $SINGLEMDS sync\nfi\n\ntest_0() {\n    replay_barrier mds1\n    fail mds1\n}\nrun_test 0 \"empty replay\"\n\ntest_0b() {\n    # this test attempts to trigger a race in the precreation code, \n    # and must run before any other objects are created on the filesystem\n    fail ost1\n    createmany -o $DIR/$tfile 20 || return 1\n    unlinkmany $DIR/$tfile 20 || return 2\n}\nrun_test 0b \"ensure object created after recover exists. (3284)\"\n\ntest_1a() {\n    mkdir $DIR/dir01\n    replay_barrier mds2\n    $CHECKSTAT -t dir $DIR/dir01 || return 1\n    rmdir $DIR/dir01\n    fail mds2\n    stat $DIR/dir01\n}\nrun_test 1a \"unlink cross-node dir (fail mds with inode)\"\n\ntest_1b() {\n    mkdir $DIR/dir11\n    replay_barrier mds1\n    $CHECKSTAT -t dir $DIR/dir11 || return 1\n    rmdir $DIR/dir11\n    fail mds1\n    stat $DIR/dir11\n}\nrun_test 1b \"unlink cross-node dir (fail mds with name)\"\n\ntest_2a() {\n    mkdir $DIR/dir21\n    createmany -o $DIR/dir21/f 3000\n    sleep 10\n    $CHECKSTAT -t dir $DIR/dir21 || return 1\n    $CHECKSTAT -t file $DIR/dir21/f1002 || return 1\n    replay_barrier mds1\n    rm $DIR/dir21/f1002\n    fail mds1\n    stat $DIR/dir21/f1002\n}\nrun_test 2a \"unlink cross-node file (fail mds with name)\"\n\ntest_3a() {\n    replay_barrier mds2\n    mkdir $DIR/dir3a1\n    $LCTL mark \"FAILOVER mds2\"\n    fail mds2\n    stat $DIR\n    $CHECKSTAT -t dir $DIR/dir3a1 || return 1\n}\nrun_test 3a \"mkdir cross-node dir (fail mds with inode)\"\n\ntest_3b() {\n    replay_barrier mds1\n    mkdir $DIR/dir3b1\n    $LCTL mark \"FAILOVER mds1\"\n    fail mds1\n    stat $DIR\n    $CHECKSTAT -t dir $DIR/dir3b1 || return 1\n}\nrun_test 3b \"mkdir cross-node dir (fail mds with inode)\"\n\ncomplete $SECONDS\n$CLEANUP\n\n", "num_lines": 112}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$REPLAY_SINGLE_EXCEPT \"\n\nif [ \"$mds1_FSTYPE\" = zfs ]; then\n\t# bug number for skipped test: LU-11388\n\tALWAYS_EXCEPT+=\"               131b\"\n\t# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\nfi\nif $SHARED_KEY; then\n\t# bug number for skipped tests: LU-9795 (all below)\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT\t0b\t0c\t0d\t34\t45\"\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT\t47\t58b\t58c\t71a\t85a\"\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT\t85b\t86\t88\t89\t90\"\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT\t93a\t100a\t100b\t120\"\nfi\n\nbuild_test_filter\n\nCHECK_GRANT=${CHECK_GRANT:-\"yes\"}\nGRANT_CHECK_LIST=${GRANT_CHECK_LIST:-\"\"}\n\nrequire_dsh_mds || exit 0\ncheck_and_setup_lustre\n\nmkdir -p $DIR\n\nassert_DIR\nrm -rf $DIR/[df][0-9]* $DIR/f.$TESTSUITE.*\n\n# LU-482 Avert LVM and VM inability to flush caches in pre .33 kernels\nif [ $LINUX_VERSION_CODE -lt $(version_code 2.6.33) ]; then\n    sync\n    do_facet $SINGLEMDS sync\nfi\n\ntest_0a() {\t# was test_0\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\trmdir $DIR/$tdir\n}\nrun_test 0a \"empty replay\"\n\ntest_0b() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\t# this test attempts to trigger a race in the precreation code,\n\t# and must run before any other objects are created on the filesystem\n\tfail ost1\n\tcreatemany -o $DIR/$tfile 20 || error \"createmany -o $DIR/$tfile failed\"\n\tunlinkmany $DIR/$tfile 20 || error \"unlinkmany $DIR/$tfile failed\"\n}\nrun_test 0b \"ensure object created after recover exists. (3284)\"\n\ntest_0c() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tfile\n\tumount $MOUNT\n\tfacet_failover $SINGLEMDS\n\tzconf_mount $(hostname) $MOUNT || error \"mount fails\"\n\tclient_up || error \"post-failover df failed\"\n\t# file shouldn't exist if replay-barrier works as expected\n\trm $DIR/$tfile && error \"File exists and it shouldn't\"\n\treturn 0\n}\nrun_test 0c \"check replay-barrier\"\n\ntest_0d() {\n\treplay_barrier $SINGLEMDS\n\tumount $MOUNT\n\tfacet_failover $SINGLEMDS\n\tzconf_mount $(hostname) $MOUNT || error \"mount fails\"\n\tclient_up || error \"post-failover df failed\"\n}\nrun_test 0d \"expired recovery with no clients\"\n\ntest_1() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\trm $DIR/$tfile\n}\nrun_test 1 \"simple create\"\n\ntest_2a() {\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\trm $DIR/$tfile\n}\nrun_test 2a \"touch\"\n\ntest_2b() {\n\tmcreate $DIR/$tfile || error \"mcreate $DIR/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\trm $DIR/$tfile\n}\nrun_test 2b \"touch\"\n\ntest_2c() {\n\treplay_barrier $SINGLEMDS\n\t$LFS setstripe -c $OSTCOUNT $DIR/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile check failed\"\n}\nrun_test 2c \"setstripe replay\"\n\ntest_2d() {\n\t[[ \"$mds1_FSTYPE\" = zfs ]] &&\n\t\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.12.51) ]] &&\n\t\tskip \"requires LU-10143 fix on MDS\"\n\treplay_barrier $SINGLEMDS\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t dir $DIR/$tdir ||\n\t\terror \"$CHECKSTAT $DIR/$tdir check failed\"\n}\nrun_test 2d \"setdirstripe replay\"\n\ntest_3a() {\n\tlocal file=$DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\tmcreate $file\n\topenfile -f O_DIRECTORY $file\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $file ||\n\t\terror \"$CHECKSTAT $file attribute check failed\"\n\trm $file\n}\nrun_test 3a \"replay failed open(O_DIRECTORY)\"\n\ntest_3b() {\n\treplay_barrier $SINGLEMDS\n\t#define OBD_FAIL_MDS_OPEN_PACK | OBD_FAIL_ONCE\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000114\"\n\ttouch $DIR/$tfile\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile &&\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check should fail\"\n\treturn 0\n}\nrun_test 3b \"replay failed open -ENOMEM\"\n\ntest_3c() {\n\treplay_barrier $SINGLEMDS\n\t#define OBD_FAIL_MDS_ALLOC_OBDO | OBD_FAIL_ONCE\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000128\"\n\ttouch $DIR/$tfile\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tfail $SINGLEMDS\n\n\t$CHECKSTAT -t file $DIR/$tfile &&\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check should fail\"\n\treturn 0\n}\nrun_test 3c \"replay failed open -ENOMEM\"\n\ntest_4a() {\t# was test_4\n\treplay_barrier $SINGLEMDS\n\tfor i in $(seq 10); do\n\t\techo \"tag-$i\" > $DIR/$tfile-$i\n\tdone\n\tfail $SINGLEMDS\n\tfor i in $(seq 10); do\n\t\tgrep -q \"tag-$i\" $DIR/$tfile-$i || error \"$tfile-$i\"\n\tdone\n}\nrun_test 4a \"|x| 10 open(O_CREAT)s\"\n\ntest_4b() {\n\tfor i in $(seq 10); do\n\t\techo \"tag-$i\" > $DIR/$tfile-$i\n\tdone\n\treplay_barrier $SINGLEMDS\n\trm -rf $DIR/$tfile-*\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile-* &&\n\t\terror \"$CHECKSTAT $DIR/$tfile-* attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 4b \"|x| rm 10 files\"\n\n# The idea is to get past the first block of precreated files on both\n# osts, and then replay.\ntest_5() {\n\treplay_barrier $SINGLEMDS\n\tfor i in $(seq 220); do\n\t\techo \"tag-$i\" > $DIR/$tfile-$i\n\tdone\n\tfail $SINGLEMDS\n\tfor i in $(seq 220); do\n\t\tgrep -q \"tag-$i\" $DIR/$tfile-$i || error \"$tfile-$i\"\n\tdone\n\trm -rf $DIR/$tfile-*\n\tsleep 3\n\t# waiting for commitment of removal\n}\nrun_test 5 \"|x| 220 open(O_CREAT)\"\n\ntest_6a() {\t# was test_6\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tdir/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t dir $DIR/$tdir ||\n\t\terror \"$CHECKSTAT $DIR/$tdir attribute check failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tdir/$tfile attribute check failed\"\n\tsleep 2\n\t# waiting for log process thread\n}\nrun_test 6a \"mkdir + contained create\"\n\ntest_6b() {\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\treplay_barrier $SINGLEMDS\n\trm -rf $DIR/$tdir\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t dir $DIR/$tdir &&\n\t\terror \"$CHECKSTAT $DIR/$tdir attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 6b \"|X| rmdir\"\n\ntest_7() {\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tdir/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT -t dir $DIR/$tdir ||\n\t\terror \"$CHECKSTAT $DIR/$tdir attribute check failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tdir/$tfile attribute check failed\"\n\trm -fr $DIR/$tdir\n}\nrun_test 7 \"mkdir |X| contained create\"\n\ntest_8() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile mo_c ||\n\t\terror \"multiop mknod $DIR/$tfile failed\"\n\tMULTIPID=$!\n\tfail $SINGLEMDS\n\tls $DIR/$tfile\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\tkill -USR1 $MULTIPID || error \"multiop mknod $MULTIPID not running\"\n\twait $MULTIPID || error \"multiop mknod $MULTIPID failed\"\n\trm $DIR/$tfile\n}\nrun_test 8 \"creat open |X| close\"\n\ntest_9() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tfile\n\tlocal old_inum=$(ls -i $DIR/$tfile | awk '{print $1}')\n\tfail $SINGLEMDS\n\tlocal new_inum=$(ls -i $DIR/$tfile | awk '{print $1}')\n\n\techo \" old_inum == $old_inum, new_inum == $new_inum\"\n\tif [ $old_inum -eq $new_inum  ] ;\n\tthen\n\t\techo \"old_inum and new_inum match\"\n\telse\n\t\techo \" old_inum and new_inum do not match\"\n\t\terror \"old index($old_inum) does not match new index($new_inum)\"\n\tfi\n\trm $DIR/$tfile\n}\nrun_test 9 \"|X| create (same inum/gen)\"\n\ntest_10() {\n\tmcreate $DIR/$tfile || error \"mcreate $DIR/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\tmv $DIR/$tfile $DIR/$tfile-2\n\trm -f $DIR/$tfile\n\tfail $SINGLEMDS\n\t$CHECKSTAT $DIR/$tfile &&\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check should fail\"\n\t$CHECKSTAT $DIR/$tfile-2 ||\n\t\terror \"$CHECKSTAT $DIR/$tfile-2 attribute check failed\"\n\trm $DIR/$tfile-2\n\treturn 0\n}\nrun_test 10 \"create |X| rename unlink\"\n\ntest_11() {\n\tmcreate $DIR/$tfile || error \"mcreate $DIR/$tfile failed\"\n\techo \"old\" > $DIR/$tfile\n\tmv $DIR/$tfile $DIR/$tfile-2\n\treplay_barrier $SINGLEMDS\n\techo \"new\" > $DIR/$tfile\n\tgrep new $DIR/$tfile\n\tgrep old $DIR/$tfile-2\n\tfail $SINGLEMDS\n\tgrep new $DIR/$tfile || error \"grep $DIR/$tfile failed\"\n\tgrep old $DIR/$tfile-2 || error \"grep $DIR/$tfile-2 failed\"\n}\nrun_test 11 \"create open write rename |X| create-old-name read\"\n\ntest_12() {\n\tmcreate $DIR/$tfile || error \"mcreate $DIR/$tfile failed\"\n\tmultiop_bg_pause $DIR/$tfile o_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\tfail $SINGLEMDS\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 12 \"open, unlink |X| close\"\n\n# 1777 - replay open after committed chmod that would make\n#        a regular open a failure\ntest_13() {\n\tmcreate $DIR/$tfile || error \"mcreate $DIR/$tfile failed\"\n\tmultiop_bg_pause $DIR/$tfile O_wc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\tchmod 0 $DIR/$tfile\n\t$CHECKSTAT -p 0 $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\t$CHECKSTAT -s 1 -p 0 $DIR/$tfile ||\n\t\terror \"second $CHECKSTAT $DIR/$tfile attribute check failed\"\n\trm $DIR/$tfile || error \"rm $DIR/$tfile failed\"\n\treturn 0\n}\nrun_test 13 \"open chmod 0 |x| write close\"\n\ntest_14() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\tfail $SINGLEMDS\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 14 \"open(O_CREAT), unlink |X| close\"\n\ntest_15() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR/$tfile-1 || error \"touch $DIR/$tfile-1 failed\"\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\tfail $SINGLEMDS\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\ttouch $DIR/$tfile-2 || error \"touch $DIR/$tfile-2 failed\"\n\treturn 0\n}\nrun_test 15 \"open(O_CREAT), unlink |X|  touch new, close\"\n\ntest_16() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tfile\n\tmunlink $DIR/$tfile\n\tmcreate $DIR/$tfile-2\n\tfail $SINGLEMDS\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\t[ -e $DIR/$tfile-2 ] || error \"file $DIR/$tfile-2 does not exist\"\n\tmunlink $DIR/$tfile-2 || error \"munlink $DIR/$tfile-2 failed\"\n}\nrun_test 16 \"|X| open(O_CREAT), unlink, touch new,  unlink new\"\n\ntest_17() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile O_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\trm $DIR/$tfile\n}\nrun_test 17 \"|X| open(O_CREAT), |replay| close\"\n\ntest_18() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\ttouch $DIR/$tfile-2 || error \"touch $DIR/$tfile-2 failed\"\n\techo \"pid: $pid will close\"\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\tfail $SINGLEMDS\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\t[ -e $DIR/$tfile-2 ] || error \"file $DIR/$tfile-2 does not exist\"\n\t# this touch frequently fails\n\ttouch $DIR/$tfile-3 || error \"touch $DIR/$tfile-3 failed\"\n\tmunlink $DIR/$tfile-2 || error \"munlink $DIR/$tfile-2 failed\"\n\tmunlink $DIR/$tfile-3 || error \"munlink $DIR/$tfile-3 failed\"\n\treturn 0\n}\nrun_test 18 \"open(O_CREAT), unlink, touch new, close, touch, unlink\"\n\n# bug 1855 (a simpler form of test_11 above)\ntest_19() {\n\treplay_barrier $SINGLEMDS\n\tmcreate $DIR/$tfile\n\techo \"old\" > $DIR/$tfile\n\tmv $DIR/$tfile $DIR/$tfile-2\n\tgrep old $DIR/$tfile-2\n\tfail $SINGLEMDS\n\tgrep old $DIR/$tfile-2 || error \"grep $DIR/$tfile-2 failed\"\n}\nrun_test 19 \"mcreate, open, write, rename \"\n\ntest_20a() {\t# was test_20\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 20a \"|X| open(O_CREAT), unlink, replay, close (test mds_cleanup_orphans)\"\n\ntest_20b() { # bug 10480\n\tlocal wait_timeout=$((TIMEOUT * 4))\n\tlocal extra=$(fs_log_size)\n\tlocal n_attempts=1\n\n\tsync_all_data\n\t$LFS setstripe -i 0 -c 1 $DIR\n\n\tlocal beforeused=$(df -P $DIR | tail -1 | awk '{ print $3 }')\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=10000 &\n\twhile [ ! -e $DIR/$tfile ] ; do\n\t\tusleep 60\t\t\t# give dd a chance to start\n\tdone\n\n\t$LFS getstripe $DIR/$tfile || error \"$LFS getstripe $DIR/$tfile failed\"\n\t# make it an orphan\n\trm -f $DIR/$tfile || error \"rm -f $DIR/$tfile failed\"\n\tmds_evict_client\n\tclient_up || client_up || true\t\t# reconnect\n\n\tdo_facet $SINGLEMDS \"lctl set_param -n osd*.*MDT*.force_sync=1\"\n\n\tfail $SINGLEMDS\t\t\t\t# start orphan recovery\n\twait_recovery_complete $SINGLEMDS || error \"MDS recovery not done\"\n\twait_delete_completed $wait_timeout || error \"delete did not finish\"\n\tsync_all_data\n\n\twhile true; do\n\t\tlocal afterused=$(df -P $DIR | tail -1 | awk '{ print $3 }')\n\t\tlog \"before $beforeused, after $afterused\"\n\n\t\t(( $beforeused + $extra >= $afterused )) && break\n\t\tn_attempts=$((n_attempts + 1))\n\t\t[ $n_attempts -gt 3 ] &&\n\t\t\terror \"after $afterused > before $beforeused + $extra\"\n\n\t\twait_zfs_commit $SINGLEMDS 5\n\t\tsync_all_data\n\tdone\n}\n\nrun_test 20b \"write, unlink, eviction, replay (test mds_cleanup_orphans)\"\n\ntest_20c() { # bug 10480\n\tmultiop_bg_pause $DIR/$tfile Ow_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\n\tls -la $DIR/$tfile\n\n\tmds_evict_client\n\tclient_up || client_up || true    # reconnect\n\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -s $DIR/$tfile ] || error \"File was truncated\"\n\n\treturn 0\n}\nrun_test 20c \"check that client eviction does not affect file content\"\n\ntest_21() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\ttouch $DIR/$tfile-1 || error \"touch $DIR/$tfile-1 failed\"\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\ttouch $DIR/$tfile-2 || error \"touch $DIR/$tfile-2 failed\"\n\treturn 0\n}\nrun_test 21 \"|X| open(O_CREAT), unlink touch new, replay, close (test mds_cleanup_orphans)\"\n\ntest_22() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\n\treplay_barrier $SINGLEMDS\n\trm -f $DIR/$tfile\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 22 \"open(O_CREAT), |X| unlink, replay, close (test mds_cleanup_orphans)\"\n\ntest_23() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\n\treplay_barrier $SINGLEMDS\n\trm -f $DIR/$tfile\n\ttouch $DIR/$tfile-1 || error \"touch $DIR/$tfile-1 failed\"\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\ttouch $DIR/$tfile-2 || error \"touch $DIR/$tfile-2 failed\"\n\treturn 0\n}\nrun_test 23 \"open(O_CREAT), |X| unlink touch new, replay, close (test mds_cleanup_orphans)\"\n\ntest_24() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\trm -f $DIR/$tfile\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 24 \"open(O_CREAT), replay, unlink, close (test mds_cleanup_orphans)\"\n\ntest_25() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 25 \"open(O_CREAT), unlink, replay, close (test mds_cleanup_orphans)\"\n\ntest_26() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\trm -f $DIR/$tfile-1\n\trm -f $DIR/$tfile-2\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 26 \"|X| open(O_CREAT), unlink two, close one, replay, close one (test mds_cleanup_orphans)\"\n\ntest_27() {\n\treplay_barrier $SINGLEMDS\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\trm -f $DIR/$tfile-1\n\trm -f $DIR/$tfile-2\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 27 \"|X| open(O_CREAT), unlink two, replay, close two (test mds_cleanup_orphans)\"\n\ntest_28() {\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\treplay_barrier $SINGLEMDS\n\trm -f $DIR/$tfile-1\n\trm -f $DIR/$tfile-2\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 28 \"open(O_CREAT), |X| unlink two, close one, replay, close one (test mds_cleanup_orphans)\"\n\ntest_29() {\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\treplay_barrier $SINGLEMDS\n\trm -f $DIR/$tfile-1\n\trm -f $DIR/$tfile-2\n\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 29 \"open(O_CREAT), |X| unlink two, replay, close two (test mds_cleanup_orphans)\"\n\ntest_30() {\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\trm -f $DIR/$tfile-1\n\trm -f $DIR/$tfile-2\n\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 30 \"open(O_CREAT) two, unlink two, replay, close two (test mds_cleanup_orphans)\"\n\ntest_31() {\n\tmultiop_bg_pause $DIR/$tfile-1 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-1 failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile-2 O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile-2 failed\"\n\tpid2=$!\n\trm -f $DIR/$tfile-1\n\n\treplay_barrier $SINGLEMDS\n\trm -f $DIR/$tfile-2\n\tfail $SINGLEMDS\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\t[ -e $DIR/$tfile-1 ] && error \"file $DIR/$tfile-1 should not exist\"\n\t[ -e $DIR/$tfile-2 ] && error \"file $DIR/$tfile-2 should not exist\"\n\treturn 0\n}\nrun_test 31 \"open(O_CREAT) two, unlink one, |X| unlink one, close two (test mds_cleanup_orphans)\"\n\n# tests for bug 2104; completion without crashing is success.  The close is\n# stale, but we always return 0 for close, so the app never sees it.\ntest_32() {\n\tmultiop_bg_pause $DIR/$tfile O_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid1=$!\n\tmultiop_bg_pause $DIR/$tfile O_c ||\n\t\terror \"second multiop_bg_pause $DIR/$tfile failed\"\n\tpid2=$!\n\tmds_evict_client\n\tclient_up || client_up || error \"client_up failed\"\n\tkill -USR1 $pid1 || error \"multiop $pid1 not running\"\n\tkill -USR1 $pid2 || error \"second multiop $pid2 not running\"\n\twait $pid1 || error \"multiop $pid1 failed\"\n\twait $pid2 || error \"second multiop $pid2 failed\"\n\treturn 0\n}\nrun_test 32 \"close() notices client eviction; close() after client eviction\"\n\ntest_33a() {\n\tcreatemany -o $DIR/$tfile-%d 10 ||\n\t\terror \"createmany create $DIR/$tfile failed\"\n\treplay_barrier_nosync $SINGLEMDS\n\tfail_abort $SINGLEMDS\n\t# recreate shouldn't fail\n\tcreatemany -o $DIR/$tfile--%d 10 ||\n\t\terror \"createmany recreate $DIR/$tfile failed\"\n\trm $DIR/$tfile-* -f\n\treturn 0\n}\nrun_test 33a \"fid seq shouldn't be reused after abort recovery\"\n\ntest_33b() {\n\t#define OBD_FAIL_SEQ_ALLOC                          0x1311\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x1311\"\n\n\tcreatemany -o $DIR/$tfile-%d 10\n\treplay_barrier_nosync $SINGLEMDS\n\tfail_abort $SINGLEMDS\n\t# recreate shouldn't fail\n\tcreatemany -o $DIR/$tfile--%d 10 ||\n\t\terror \"createmany recreate $DIR/$tfile failed\"\n\trm $DIR/$tfile-* -f\n\treturn 0\n}\nrun_test 33b \"test fid seq allocation\"\n\ntest_34() {\n\tmultiop_bg_pause $DIR/$tfile O_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\n\treplay_barrier $SINGLEMDS\n\tfail_abort $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\tsync\n\treturn 0\n}\nrun_test 34 \"abort recovery before client does replay (test mds_cleanup_orphans)\"\n\n# bug 2278 - generate one orphan on OST, then destroy it during recovery from llog\ntest_35() {\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\n\t#define OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000119\"\n\trm -f $DIR/$tfile &\n\tsleep 1\n\tsync\n\tsleep 1\n\t# give a chance to remove from MDS\n\tfail_abort $SINGLEMDS\n\t$CHECKSTAT -t file $DIR/$tfile &&\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 35 \"test recovery from llog for unlink op\"\n\n# b=2432 resent cancel after replay uses wrong cookie,\n# so don't resend cancels\ntest_36() {\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR/$tfile\n\tcheckstat $DIR/$tfile\n\tfacet_failover $SINGLEMDS\n\tcancel_lru_locks mdc\n\tif $LCTL dk | grep \"stale lock .*cookie\"; then\n\t\terror \"cancel after replay failed\"\n\tfi\n}\nrun_test 36 \"don't resend cancel\"\n\n# b=2368\n# directory orphans can't be unlinked from PENDING directory\ntest_37() {\n\trmdir $DIR/$tfile 2>/dev/null\n\tmultiop_bg_pause $DIR/$tfile dD_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trmdir $DIR/$tfile\n\n\treplay_barrier $SINGLEMDS\n\t# clear the dmesg buffer so we only see errors from this recovery\n\tdo_facet $SINGLEMDS dmesg -c >/dev/null\n\tfail_abort $SINGLEMDS\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\tdo_facet $SINGLEMDS dmesg | grep \"error unlinking orphan\" &&\n\t\terror \"error unlinking files\"\n\twait $pid || error \"multiop $pid failed\"\n\tsync\n\treturn 0\n}\nrun_test 37 \"abort recovery before client does replay (test mds_cleanup_orphans for directories)\"\n\ntest_38() {\n\tcreatemany -o $DIR/$tfile-%d 800 ||\n\t\terror \"createmany -o $DIR/$tfile failed\"\n\tunlinkmany $DIR/$tfile-%d 0 400 || error \"unlinkmany $DIR/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\tunlinkmany $DIR/$tfile-%d 400 400 ||\n\t\terror \"unlinkmany $DIR/$tfile 400 failed\"\n\tsleep 2\n\t$CHECKSTAT -t file $DIR/$tfile-* &&\n\t\terror \"$CHECKSTAT $DIR/$tfile-* attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 38 \"test recovery from unlink llog (test llog_gen_rec) \"\n\ntest_39() { # bug 4176\n\tcreatemany -o $DIR/$tfile-%d 800 ||\n\t\terror \"createmany -o $DIR/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\tunlinkmany $DIR/$tfile-%d 0 400\n\tfail $SINGLEMDS\n\tunlinkmany $DIR/$tfile-%d 400 400 ||\n\t\terror \"unlinkmany $DIR/$tfile 400 failed\"\n\tsleep 2\n\t$CHECKSTAT -t file $DIR/$tfile-* &&\n\t\terror \"$CHECKSTAT $DIR/$tfile-* attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 39 \"test recovery from unlink llog (test llog_gen_rec) \"\n\ncount_ost_writes() {\n    lctl get_param -n osc.*.stats | awk -vwrites=0 '/ost_write/ { writes += $2 } END { print writes; }'\n}\n\n#b=2477,2532\ntest_40(){\n\t# always need connection to MDS to verify layout during IO. LU-2628.\n\tlctl get_param mdc.*.connect_flags | grep -q layout_lock &&\n\t\tskip \"layout_lock needs MDS connection for IO\" && return 0\n\n\t$LCTL mark multiop $MOUNT/$tfile OS_c\n\tmultiop $MOUNT/$tfile OS_c  &\n\tPID=$!\n\twriteme -s $MOUNT/${tfile}-2 &\n\tWRITE_PID=$!\n\tsleep 1\n\tfacet_failover $SINGLEMDS\n\t#define OBD_FAIL_MDS_CONNECT_NET         0x117\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000117\"\n\tkill -USR1 $PID\n\tstat1=$(count_ost_writes)\n\tsleep $TIMEOUT\n\tstat2=$(count_ost_writes)\n\techo \"$stat1, $stat2\"\n\tif [ $stat1 -lt $stat2 ]; then\n\t\techo \"writes continuing during recovery\"\n\t\tRC=0\n\telse\n\t\techo \"writes not continuing during recovery, bug 2477\"\n\t\tRC=4\n\tfi\n\techo \"waiting for writeme $WRITE_PID\"\n\tkill $WRITE_PID\n\twait $WRITE_PID\n\n\techo \"waiting for multiop $PID\"\n\twait $PID || error \"multiop $PID failed\"\n\tdo_facet client munlink $MOUNT/$tfile  ||\n\t\terror \"munlink $MOUNT/$tfile failed\"\n\tdo_facet client munlink $MOUNT/${tfile}-2  ||\n\t\terror \"munlink $MOUNT/$tfile-2 failed\"\n\treturn $RC\n}\nrun_test 40 \"cause recovery in ptlrpc, ensure IO continues\"\n\n#b=2814\n# make sure that a read to one osc doesn't try to double-unlock its page just\n# because another osc is invalid.  trigger_group_io used to mistakenly return\n# an error if any oscs were invalid even after having successfully put rpcs\n# on valid oscs.  This was fatal if the caller was ll_readpage who unlocked\n# the page, guarnateeing that the unlock from the RPC completion would\n# assert on trying to unlock the unlocked page.\ntest_41() {\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\" && return\n\n\tlocal f=$MOUNT/$tfile\n\t# make sure the start of the file is ost1\n\t$LFS setstripe -S $((128 * 1024)) -i 0 $f\n\tdo_facet client dd if=/dev/zero of=$f bs=4k count=1 ||\n\t\terror \"dd on client failed\"\n\tcancel_lru_locks osc\n\t# fail ost2 and read from ost1\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $ost2_svc)\n\tlocal osc2dev=$(do_facet $SINGLEMDS \"lctl get_param -n devices\" |\n\t\tgrep $mdtosc | awk '{print $1}')\n\t[ -z \"$osc2dev\" ] && echo \"OST: $ost2_svc\" &&\n\t\tlctl get_param -n devices &&\n\t\terror \"OST 2 $osc2dev does not exist\"\n\tdo_facet $SINGLEMDS $LCTL --device $osc2dev deactivate ||\n\t\terror \"deactive device on $SINGLEMDS failed\"\n\tdo_facet client dd if=$f of=/dev/null bs=4k count=1 ||\n\t\terror \"second dd on client failed\"\n\tdo_facet $SINGLEMDS $LCTL --device $osc2dev activate ||\n\t\terror \"active device on $SINGLEMDS failed\"\n\treturn 0\n}\nrun_test 41 \"read from a valid osc while other oscs are invalid\"\n\n# test MDS recovery after ost failure\ntest_42() {\n\tblocks=$(df -P $MOUNT | tail -n 1 | awk '{ print $2 }')\n\tcreatemany -o $DIR/$tfile-%d 800 ||\n\t\terror \"createmany -o $DIR/$tfile failed\"\n\treplay_barrier ost1\n\tunlinkmany $DIR/$tfile-%d 0 400\n\tdebugsave\n\tlctl set_param debug=-1\n\tfacet_failover ost1\n\n\t# osc is evicted, fs is smaller (but only with failout OSTs (bug 7287)\n\t#blocks_after=`df -P $MOUNT | tail -n 1 | awk '{ print $2 }'`\n\t#[ $blocks_after -lt $blocks ] || return 1\n\techo \"wait for MDS to timeout and recover\"\n\tsleep $((TIMEOUT * 2))\n\tdebugrestore\n\tunlinkmany $DIR/$tfile-%d 400 400 ||\n\t\terror \"unlinkmany $DIR/$tfile 400 failed\"\n\t$CHECKSTAT -t file $DIR/$tfile-* &&\n\t\terror \"$CHECKSTAT $DIR/$tfile-* attribute check should fail\" ||\n\t\ttrue\n}\nrun_test 42 \"recovery after ost failure\"\n\n# timeout in MDS/OST recovery RPC will LBUG MDS\ntest_43() { # bug 2530\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\treplay_barrier $SINGLEMDS\n\n\t# OBD_FAIL_OST_CREATE_NET 0x204\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000204\"\n\tfail $SINGLEMDS\n\tsleep 10\n\n\treturn 0\n}\nrun_test 43 \"mds osc import failure during recovery; don't LBUG\"\n\ntest_44a() { # was test_44\n\tlocal at_max_saved=0\n\n\tlocal mdcdev=$($LCTL dl |\n\t\tawk \"/${FSNAME}-MDT0000-mdc-/ {if (\\$2 == \\\"UP\\\") {print \\$1}}\")\n\t[ \"$mdcdev\" ] || error \"${FSNAME}-MDT0000-mdc- not UP\"\n\t[ $(echo $mdcdev | wc -w) -eq 1 ] ||\n\t\t{ $LCTL dl; error \"looking for mdcdev=$mdcdev\"; }\n\n\t# adaptive timeouts slow this way down\n\tif at_is_enabled; then\n\t\tat_max_saved=$(at_max_get mds)\n\t\tat_max_set 40 mds\n\tfi\n\n\tfor i in $(seq 1 10); do\n\t\techo \"$i of 10 ($(date +%s))\"\n\t\tdo_facet $SINGLEMDS \\\n\t\t\t\"lctl get_param -n md[ts].*.mdt.timeouts | grep service\"\n\t\t#define OBD_FAIL_TGT_CONN_RACE     0x701\n\t\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000701\"\n\t\t# lctl below may fail, it is valid case\n\t\t$LCTL --device $mdcdev recover\n\t\t$LFS df $MOUNT\n\tdone\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\t[ $at_max_saved -ne 0 ] && at_max_set $at_max_saved mds\n\treturn 0\n}\nrun_test 44a \"race in target handle connect\"\n\ntest_44b() {\n\tlocal mdcdev=$($LCTL dl |\n\t\tawk \"/${FSNAME}-MDT0000-mdc-/ {if (\\$2 == \\\"UP\\\") {print \\$1}}\")\n\t[ \"$mdcdev\" ] || error \"${FSNAME}-MDT0000-mdc not up\"\n\t[ $(echo $mdcdev | wc -w) -eq 1 ] ||\n\t\t{ echo mdcdev=$mdcdev; $LCTL dl;\n\t\t  error \"more than one ${FSNAME}-MDT0000-mdc\"; }\n\n\tfor i in $(seq 1 10); do\n\t\techo \"$i of 10 ($(date +%s))\"\n\t\tdo_facet $SINGLEMDS \\\n\t\t\t\"lctl get_param -n md[ts].*.mdt.timeouts | grep service\"\n\t\t#define OBD_FAIL_TGT_DELAY_RECONNECT 0x704\n\t\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000704\"\n\t\t# lctl below may fail, it is valid case\n\t\t$LCTL --device $mdcdev recover\n\t\tdf $MOUNT\n\tdone\n\treturn 0\n}\nrun_test 44b \"race in target handle connect\"\n\ntest_44c() {\n\treplay_barrier $SINGLEMDS\n\tcreatemany -m $DIR/$tfile-%d 100 || error \"failed to create directories\"\n\t#define OBD_FAIL_TGT_RCVG_FLAG 0x712\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000712\"\n\tfail_abort $SINGLEMDS\n\tunlinkmany $DIR/$tfile-%d 100 && error \"unliked after fail abort\"\n\tfail $SINGLEMDS\n\tunlinkmany $DIR/$tfile-%d 100 && error \"unliked after fail\"\n\treturn 0\n}\nrun_test 44c \"race in target handle connect\"\n\n# Handle failed close\ntest_45() {\n\tlocal mdcdev=$($LCTL get_param -n devices |\n\t\tawk \"/ ${FSNAME}-MDT0000-mdc-/ {print \\$1}\")\n\t[ \"$mdcdev\" ] || error \"${FSNAME}-MDT0000-mdc not up\"\n\t[ $(echo $mdcdev | wc -w) -eq 1 ] ||\n\t\t{ echo mdcdev=$mdcdev; $LCTL dl;\n\t\t  error \"more than one ${FSNAME}-MDT0000-mdc\"; }\n\n\t$LCTL --device $mdcdev recover ||\n\t\terror \"$LCTL --device $mdcdev recover failed\"\n\n\tmultiop_bg_pause $DIR/$tfile O_c ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\n\t# This will cause the CLOSE to fail before even\n\t# allocating a reply buffer\n\t$LCTL --device $mdcdev deactivate ||\n\t\terror \"$LCTL --device $mdcdev deactivate failed\"\n\n\t# try the close\n\tkill -USR1 $pid || error \"multiop $pid not running\"\n\twait $pid || error \"multiop $pid failed\"\n\n\t$LCTL --device $mdcdev activate ||\n\t\terror \"$LCTL --device $mdcdev activate failed\"\n\tsleep 1\n\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\treturn 0\n}\nrun_test 45 \"Handle failed close\"\n\ntest_46() {\n\tdrop_reply \"touch $DIR/$tfile\"\n\tfail $SINGLEMDS\n\t# ironically, the previous test, 45, will cause a real forced close,\n\t# so just look for one for this test\n\tlocal FID=$($LFS path2fid $tfile)\n\t$LCTL dk | grep -i \"force closing file handle $FID\" &&\n\t\terror \"found force closing in dmesg\"\n\treturn 0\n}\nrun_test 46 \"Don't leak file handle after open resend (3325)\"\n\ntest_47() { # bug 2824\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\t# create some files to make sure precreate has been done on all\n\t# OSTs. (just in case this test is run independently)\n\tcreatemany -o $DIR/$tfile 20  ||\n\t\terror \"createmany create $DIR/$tfile failed\"\n\n\t# OBD_FAIL_OST_CREATE_NET 0x204\n\tfail ost1\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000204\"\n\tclient_up || error \"client_up failed\"\n\n\t# let the MDS discover the OST failure, attempt to recover, fail\n\t# and recover again.\n\tsleep $((3 * TIMEOUT))\n\n\t# Without 2824, this createmany would hang\n\tcreatemany -o $DIR/$tfile 20 ||\n\t\terror \"createmany recraete $DIR/$tfile failed\"\n\tunlinkmany $DIR/$tfile 20 || error \"unlinkmany $DIR/$tfile failed\"\n\n\treturn 0\n}\nrun_test 47 \"MDS->OSC failure during precreate cleanup (2824)\"\n\ntest_48() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\t[ \"$OSTCOUNT\" -lt \"2\" ] && skip_env \"needs >= 2 OSTs\" && return\n\n\treplay_barrier $SINGLEMDS\n\tcreatemany -o $DIR/$tfile 20  ||\n\t\terror \"createmany -o $DIR/$tfile failed\"\n\t# OBD_FAIL_OST_EROFS 0x216\n\tfacet_failover $SINGLEMDS\n\tdo_facet ost1 \"lctl set_param fail_loc=0x80000216\"\n\tclient_up || error \"client_up failed\"\n\n\t# let the MDS discover the OST failure, attempt to recover, fail\n\t# and recover again.\n\tsleep $((3 * TIMEOUT))\n\n\tcreatemany -o $DIR/$tfile 20 20 ||\n\t\terror \"createmany recraete $DIR/$tfile failed\"\n\tunlinkmany $DIR/$tfile 40 || error \"unlinkmany $DIR/$tfile failed\"\n\treturn 0\n}\nrun_test 48 \"MDS->OSC failure during precreate cleanup (2824)\"\n\ntest_50() {\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $ost1_svc)\n\tlocal oscdev=$(do_facet $SINGLEMDS \"lctl get_param -n devices\" |\n\t\tgrep $mdtosc | awk '{print $1}')\n\t[ \"$oscdev\" ] || error \"could not find OSC device on MDS\"\n\tdo_facet $SINGLEMDS $LCTL --device $oscdev recover ||\n\t\terror \"OSC device $oscdev recovery failed\"\n\tdo_facet $SINGLEMDS $LCTL --device $oscdev recover ||\n\t\terror \"second OSC device $oscdev recovery failed\"\n\t# give the mds_lov_sync threads a chance to run\n\tsleep 5\n}\nrun_test 50 \"Double OSC recovery, don't LASSERT (3812)\"\n\n# b3764 timed out lock replay\ntest_52() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.6.90) ] &&\n\t\tskip \"MDS prior to 2.6.90 handle LDLM_REPLY_NET incorrectly\"\n\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\tcancel_lru_locks mdc\n\n\tmultiop_bg_pause $DIR/$tfile s_s || error \"multiop $DIR/$tfile failed\"\n\tmpid=$!\n\n\t#define OBD_FAIL_MDS_LDLM_REPLY_NET\t0x157\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"0\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000157\"\n\n\tfail $SINGLEMDS || error \"fail $SINGLEMDS failed\"\n\tkill -USR1 $mpid\n\twait $mpid || error \"multiop_bg_pause pid failed\"\n\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x0\"\n\tlctl set_param fail_loc=0x0\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"1\"\n\trm -f $DIR/$tfile\n}\nrun_test 52 \"time out lock replay (3764)\"\n\n# bug 3462 - simultaneous MDC requests\ntest_53a() {\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\t# give multiop a change to open\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET 0x115\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n\tmcreate $DIR/${tdir}-2/f || error \"mcreate $DIR/${tdir}-2/f failed\"\n\n\t# close should still be here\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\n\treplay_barrier_nodf $SINGLEMDS\n\tfail $SINGLEMDS\n\twait $close_pid || error \"close_pid $close_pid failed\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53a \"|X| close request while two MDC requests in flight\"\n\ntest_53b() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop_bg_pause $DIR/${tdir}-1/f O_c ||\n\t\terror \"multiop_bg_pause $DIR/${tdir}-1/f failed\"\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET 0x107\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\twait $close_pid || error \"close_pid $close_pid failed\"\n\t# open should still be here\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exist\"\n\n\treplay_barrier_nodf $SINGLEMDS\n\tfail $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53b \"|X| open request while two MDC requests in flight\"\n\ntest_53c() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET 0x107\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET 0x115\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\n\t#bz20647: make sure all pids exist before failover\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exists\"\n\treplay_barrier_nodf $SINGLEMDS\n\tfail_nodf $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\tsleep 2\n\t# close should be gone\n\t[ -d /proc/$close_pid ] && error \"close_pid should not exist\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53c \"|X| open request and close request while two MDC requests in flight\"\n\ntest_53d() {\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\t# give multiop a chance to open\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET_REP 0x13b\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000013b\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tmcreate $DIR/${tdir}-2/f || error \"mcreate $DIR/${tdir}-2/f failed\"\n\n\t# close should still be here\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\tfail $SINGLEMDS\n\twait $close_pid || error \"close_pid failed\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53d \"close reply while two MDC requests in flight\"\n\ntest_53e() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET_REP 0x119\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x119\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\twait $close_pid || error \"close_pid failed\"\n\t# open should still be here\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exists\"\n\n\treplay_barrier_nodf $SINGLEMDS\n\tfail $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53e \"|X| open reply while two MDC requests in flight\"\n\ntest_53f() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET_REP 0x119\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x119\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET_REP 0x13b\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000013b\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\n\t#bz20647: make sure all pids are exists before failover\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exists\"\n\treplay_barrier_nodf $SINGLEMDS\n\tfail_nodf $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\tsleep 2\n\t# close should be gone\n\t[ -d /proc/$close_pid ] && error \"close_pid should not exist\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53f \"|X| open reply and close reply while two MDC requests in flight\"\n\ntest_53g() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET_REP 0x119\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x119\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET 0x115\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000115\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n\t#bz20647: make sure all pids are exists before failover\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exists\"\n\treplay_barrier_nodf $SINGLEMDS\n\tfail_nodf $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\tsleep 2\n\t# close should be gone\n\t[ -d /proc/$close_pid ] && error \"close_pid should not exist\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53g \"|X| drop open reply and close request while close and open are both in flight\"\n\ntest_53h() {\n\tcancel_lru_locks mdc    # cleanup locks from former test cases\n\n\tmkdir $DIR/${tdir}-1 || error \"mkdir $DIR/${tdir}-1 failed\"\n\tmkdir $DIR/${tdir}-2 || error \"mkdir $DIR/${tdir}-2 failed\"\n\tmultiop $DIR/${tdir}-1/f O_c &\n\tclose_pid=$!\n\n\t#define OBD_FAIL_MDS_REINT_NET 0x107\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000107\"\n\tmcreate $DIR/${tdir}-2/f &\n\topen_pid=$!\n\tsleep 1\n\n\t#define OBD_FAIL_MDS_CLOSE_NET_REP 0x13b\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000013b\"\n\tkill -USR1 $close_pid\n\tcancel_lru_locks mdc    # force the close\n\tsleep 1\n\n\t#bz20647: make sure all pids are exists before failover\n\t[ -d /proc/$close_pid ] || error \"close_pid doesn't exist\"\n\t[ -d /proc/$open_pid ] || error \"open_pid doesn't exists\"\n\treplay_barrier_nodf $SINGLEMDS\n\tfail_nodf $SINGLEMDS\n\twait $open_pid || error \"open_pid failed\"\n\tsleep 2\n\t# close should be gone\n\t[ -d /proc/$close_pid ] && error \"close_pid should not exist\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\n\t$CHECKSTAT -t file $DIR/${tdir}-1/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-1/f attribute check failed\"\n\t$CHECKSTAT -t file $DIR/${tdir}-2/f ||\n\t\terror \"$CHECKSTAT $DIR/${tdir}-2/f attribute check failed\"\n\trm -rf $DIR/${tdir}-*\n}\nrun_test 53h \"open request and close reply while two MDC requests in flight\"\n\n#b3761 ASSERTION(hash != 0) failed\ntest_55() {\n# OBD_FAIL_MDS_OPEN_CREATE | OBD_FAIL_ONCE\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000012b\"\n    touch $DIR/$tfile &\n    # give touch a chance to run\n    sleep 5\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x0\"\n    rm $DIR/$tfile\n    return 0\n}\nrun_test 55 \"let MDS_CHECK_RESENT return the original return code instead of 0\"\n\n#b3440 ASSERTION(rec->ur_fid2->id) failed\ntest_56() {\n    ln -s foo $DIR/$tfile\n    replay_barrier $SINGLEMDS\n    #drop_reply \"cat $DIR/$tfile\"\n    fail $SINGLEMDS\n    sleep 10\n}\nrun_test 56 \"don't replay a symlink open request (3440)\"\n\n#recovery one mds-ost setattr from llog\ntest_57() {\n\t#define OBD_FAIL_MDS_OST_SETATTR       0x12c\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000012c\"\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\twait_recovery_complete $SINGLEMDS || error \"MDS recovery is not done\"\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\t$CHECKSTAT -t file $DIR/$tfile ||\n\t\terror \"$CHECKSTAT $DIR/$tfile attribute check failed\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x0\"\n\trm $DIR/$tfile\n}\nrun_test 57 \"test recovery from llog for setattr op\"\n\ncleanup_58() {\n\tzconf_umount $(hostname) $MOUNT2\n\ttrap - EXIT\n}\n\n#recovery many mds-ost setattr from llog\ntest_58a() {\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t#define OBD_FAIL_MDS_OST_SETATTR       0x12c\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000012c\"\n\tcreatemany -o $DIR/$tdir/$tfile-%d 2500\n\treplay_barrier $SINGLEMDS\n\tfail $SINGLEMDS\n\tsleep 2\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile-* >/dev/null ||\n\t\terror \"$CHECKSTAT $DIR/$tfile-* attribute check failed\"\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x0\"\n\tunlinkmany $DIR/$tdir/$tfile-%d 2500 ||\n\t\terror \"unlinkmany $DIR/$tfile failed\"\n\trmdir $DIR/$tdir\n}\nrun_test 58a \"test recovery from llog for setattr op (test llog_gen_rec)\"\n\ntest_58b() {\n\tlocal orig\n\tlocal new\n\n\ttrap cleanup_58 EXIT\n\n\tlarge_xattr_enabled &&\n\t\torig=\"$(generate_string $(max_xattr_size))\" || orig=\"bar\"\n\t# Original extended attribute can be long. Print a small version of\n\t# attribute if an error occurs\n\tlocal sm_msg=$(printf \"%.9s\" $orig)\n\n\tmount_client $MOUNT2 || error \"mount_client on $MOUNT2 failed\"\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch $DIR/$tdir/$tfile failed\"\n\treplay_barrier $SINGLEMDS\n\tsetfattr -n trusted.foo -v $orig $DIR/$tdir/$tfile\n\tfail $SINGLEMDS\n\tnew=$(get_xattr_value trusted.foo $MOUNT2/$tdir/$tfile)\n\t[[ \"$new\" = \"$orig\" ]] ||\n\t\terror \"xattr set ($sm_msg...) differs from xattr get ($new)\"\n\trm -f $DIR/$tdir/$tfile\n\trmdir $DIR/$tdir\n\tcleanup_58\n\twait_clients_import_state ${CLIENTS:-$HOSTNAME} \"mgs\" FULL\n}\nrun_test 58b \"test replay of setxattr op\"\n\ntest_58c() { # bug 16570\n\tlocal orig\n\tlocal orig1\n\tlocal new\n\n\ttrap cleanup_58 EXIT\n\n\tif large_xattr_enabled; then\n\t\tlocal xattr_size=$(max_xattr_size)\n\t\torig=\"$(generate_string $((xattr_size / 2)))\"\n\t\torig1=\"$(generate_string $xattr_size)\"\n\telse\n\t\torig=\"bar\"\n\t\torig1=\"bar1\"\n\tfi\n\n\t# PING_INTERVAL max(obd_timeout / 4, 1U)\n\tsleep $((TIMEOUT / 4))\n\n\t# Original extended attribute can be long. Print a small version of\n\t# attribute if an error occurs\n\tlocal sm_msg=$(printf \"%.9s\" $orig)\n\tlocal sm_msg1=$(printf \"%.9s\" $orig1)\n\n\tmount_client $MOUNT2 || error \"mount_client on $MOUNT2 failed\"\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch $DIR/$tdir/$tfile failed\"\n\tdrop_request \"setfattr -n trusted.foo -v $orig $DIR/$tdir/$tfile\" ||\n\t\terror \"drop_request for setfattr failed\"\n\tnew=$(get_xattr_value trusted.foo $MOUNT2/$tdir/$tfile)\n\t[[ \"$new\" = \"$orig\" ]] ||\n\t\terror \"xattr set ($sm_msg...) differs from xattr get ($new)\"\n\tdrop_reint_reply \"setfattr -n trusted.foo1 \\\n\t\t\t  -v $orig1 $DIR/$tdir/$tfile\" ||\n\t\terror \"drop_reint_reply for setfattr failed\"\n\tnew=$(get_xattr_value trusted.foo1 $MOUNT2/$tdir/$tfile)\n\t[[ \"$new\" = \"$orig1\" ]] ||\n\t\terror \"second xattr set ($sm_msg1...) differs xattr get ($new)\"\n\trm -f $DIR/$tdir/$tfile\n\trmdir $DIR/$tdir\n\tcleanup_58\n}\nrun_test 58c \"resend/reconstruct setxattr op\"\n\n# log_commit_thread vs filter_destroy race used to lead to import use after free\n# bug 11658\ntest_59() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tcreatemany -o $DIR/$tdir/$tfile-%d 200 ||\n\t\terror \"createmany create files failed\"\n\tsync\n\tunlinkmany $DIR/$tdir/$tfile-%d 200 ||\n\t\terror \"unlinkmany $DIR/$tdir/$tfile failed\"\n\t#define OBD_FAIL_PTLRPC_DELAY_RECOV       0x507\n\tdo_facet ost1 \"lctl set_param fail_loc=0x507\"\n\tfail ost1\n\tfail $SINGLEMDS\n\tdo_facet ost1 \"lctl set_param fail_loc=0x0\"\n\tsleep 20\n\trmdir $DIR/$tdir\n}\nrun_test 59 \"test log_commit_thread vs filter_destroy race\"\n\n# race between add unlink llog vs cat log init in post_recovery (only for b1_6)\n# bug 12086: should no oops and No ctxt error for this test\ntest_60() {\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tcreatemany -o $DIR/$tdir/$tfile-%d 200 ||\n\t\terror \"createmany create files failed\"\n\treplay_barrier $SINGLEMDS\n\tunlinkmany $DIR/$tdir/$tfile-%d 0 100\n\tfail $SINGLEMDS\n\tunlinkmany $DIR/$tdir/$tfile-%d 100 100\n\tlocal no_ctxt=$(dmesg | grep \"No ctxt\")\n\t[ -z \"$no_ctxt\" ] || error \"ctxt is not initialized in recovery\"\n}\nrun_test 60 \"test llog post recovery init vs llog unlink\"\n\n#test race  llog recovery thread vs llog cleanup\ntest_61a() {\t# was test_61\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tcreatemany -o $DIR/$tdir/$tfile-%d 800 ||\n\t\terror \"createmany create files failed\"\n\treplay_barrier ost1\n\tunlinkmany $DIR/$tdir/$tfile-%d 800\n\t#   OBD_FAIL_OST_LLOG_RECOVERY_TIMEOUT 0x221\n\tset_nodes_failloc \"$(osts_nodes)\" 0x80000221\n\tfacet_failover ost1\n\tsleep 10\n\tfail ost1\n\tsleep 30\n\tset_nodes_failloc \"$(osts_nodes)\" 0x0\n\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile-* &&\n\t\terror \"$CHECKSTAT $DIR/$tdir/$tfile attribute check should fail\"\n\trmdir $DIR/$tdir\n}\nrun_test 61a \"test race llog recovery vs llog cleanup\"\n\n#test race  mds llog sync vs llog cleanup\ntest_61b() {\n\t#   OBD_FAIL_MDS_LLOG_SYNC_TIMEOUT 0x13a\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x8000013a\"\n\tfacet_failover $SINGLEMDS\n\tsleep 10\n\tfail $SINGLEMDS\n\tdo_facet client dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 ||\n\t\terror \"dd failed\"\n}\nrun_test 61b \"test race mds llog sync vs llog cleanup\"\n\n#test race  cancel cookie cb vs llog cleanup\ntest_61c() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\t#   OBD_FAIL_OST_CANCEL_COOKIE_TIMEOUT 0x222\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\tset_nodes_failloc \"$(osts_nodes)\" 0x80000222\n\trm $DIR/$tfile\n\tsleep 10\n\tfail ost1\n\tset_nodes_failloc \"$(osts_nodes)\" 0x0\n}\nrun_test 61c \"test race mds llog sync vs llog cleanup\"\n\ntest_61d() { # bug 16002 # bug 17466 # bug 22137\n#   OBD_FAIL_OBD_LLOG_SETUP        0x605\n    stop mgs\n    do_facet mgs \"lctl set_param fail_loc=0x80000605\"\n    start mgs $(mgsdevname) $MGS_MOUNT_OPTS &&\n\terror \"mgs start should have failed\"\n    do_facet mgs \"lctl set_param fail_loc=0\"\n    start mgs $(mgsdevname) $MGS_MOUNT_OPTS || error \"cannot restart mgs\"\n}\nrun_test 61d \"error in llog_setup should cleanup the llog context correctly\"\n\ntest_62() { # Bug 15756 - don't mis-drop resent replay\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\treplay_barrier $SINGLEMDS\n\tcreatemany -o $DIR/$tdir/$tfile- 25 ||\n\t\terror \"createmany create files failed\"\n\t#define OBD_FAIL_TGT_REPLAY_DROP         0x707\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000707\"\n\tfail $SINGLEMDS\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0\"\n\tunlinkmany $DIR/$tdir/$tfile- 25 ||\n\t\terror \"unlinkmany $DIR/$tdir/$tfile failed\"\n\treturn 0\n}\nrun_test 62 \"don't mis-drop resent replay\"\n\n#Adaptive Timeouts (bug 3055)\nAT_MAX_SET=0\n\nat_cleanup () {\n    local var\n    local facet\n    local at_new\n\n    echo \"Cleaning up AT ...\"\n    if [ -n \"$ATOLDBASE\" ]; then\n        local at_history=$($LCTL get_param -n at_history)\n        do_facet $SINGLEMDS \"lctl set_param at_history=$at_history\" || true\n        do_facet ost1 \"lctl set_param at_history=$at_history\" || true\n    fi\n\n\tif [ $AT_MAX_SET -ne 0 ]; then\n\t\tfor facet in mds client ost; do\n\t\t\tvar=AT_MAX_SAVE_${facet}\n\t\t\techo restore AT on $facet to saved value ${!var}\n\t\t\tat_max_set ${!var} $facet\n\t\t\tat_new=$(at_max_get $facet)\n\t\t\techo Restored AT value on $facet $at_new\n\t\t\t[ $at_new -eq ${!var} ] ||\n\t\t\terror \"AT value not restored SAVED ${!var} NEW $at_new\"\n\t\tdone\n\tfi\n}\n\nat_start()\n{\n    local at_max_new=600\n\n    # Save at_max original values\n    local facet\n    if [ $AT_MAX_SET -eq 0 ]; then\n        # Suppose that all osts have the same at_max\n        for facet in mds client ost; do\n            eval AT_MAX_SAVE_${facet}=$(at_max_get $facet)\n        done\n    fi\n    local at_max\n    for facet in mds client ost; do\n        at_max=$(at_max_get $facet)\n        if [ $at_max -ne $at_max_new ]; then\n            echo \"AT value on $facet is $at_max, set it by force temporarily to $at_max_new\"\n            at_max_set $at_max_new $facet\n            AT_MAX_SET=1\n        fi\n    done\n\n    if [ -z \"$ATOLDBASE\" ]; then\n\tATOLDBASE=$(do_facet $SINGLEMDS \"lctl get_param -n at_history\")\n        # speed up the timebase so we can check decreasing AT\n        do_facet $SINGLEMDS \"lctl set_param at_history=8\" || true\n        do_facet ost1 \"lctl set_param at_history=8\" || true\n\n\t# sleep for a while to cool down, should be > 8s and also allow\n\t# at least one ping to be sent. simply use TIMEOUT to be safe.\n\tsleep $TIMEOUT\n    fi\n}\n\ntest_65a() #bug 3055\n{\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    at_start || return 0\n    $LCTL dk > /dev/null\n    debugsave\n    $LCTL set_param debug=\"other\"\n    # Slow down a request to the current service time, this is critical\n    # because previous tests may have caused this value to increase.\n    REQ_DELAY=`lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts |\n               awk '/portal 12/ {print $5}'`\n    REQ_DELAY=$((${REQ_DELAY} + ${REQ_DELAY} / 4 + 5))\n\n    do_facet $SINGLEMDS lctl set_param fail_val=$((${REQ_DELAY} * 1000))\n#define OBD_FAIL_PTLRPC_PAUSE_REQ        0x50a\n    do_facet $SINGLEMDS $LCTL set_param fail_loc=0x8000050a\n    createmany -o $DIR/$tfile 10 > /dev/null\n    unlinkmany $DIR/$tfile 10 > /dev/null\n    # check for log message\n    $LCTL dk | grep -i \"Early reply #\" || error \"No early reply\"\n    debugrestore\n    # client should show REQ_DELAY estimates\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep portal\n    sleep 9\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep portal\n}\nrun_test 65a \"AT: verify early replies\"\n\ntest_65b() #bug 3055\n{\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tat_start || return 0\n\t# turn on D_ADAPTTO\n\tdebugsave\n\t$LCTL set_param debug=\"other trace\"\n\t$LCTL dk > /dev/null\n\t# Slow down a request to the current service time, this is critical\n\t# because previous tests may have caused this value to increase.\n\t$LFS setstripe --stripe-index=0 --stripe-count=1 $DIR/$tfile ||\n\t\terror \"$LFS setstripe failed for $DIR/$tfile\"\n\n\tmultiop $DIR/$tfile Ow1yc\n\tREQ_DELAY=`lctl get_param -n osc.${FSNAME}-OST0000-osc-*.timeouts |\n\t\t   awk '/portal 6/ {print $5}'`\n\tREQ_DELAY=$((${REQ_DELAY} + ${REQ_DELAY} / 4 + 5))\n\n\tdo_facet ost1 lctl set_param fail_val=${REQ_DELAY}\n\t#define OBD_FAIL_OST_BRW_PAUSE_PACK      0x224\n\tdo_facet ost1 $LCTL set_param fail_loc=0x224\n\n\trm -f $DIR/$tfile\n\t$LFS setstripe --stripe-index=0 --stripe-count=1 $DIR/$tfile ||\n\t\terror \"$LFS setstripe failed\"\n\t# force some real bulk transfer\n\tmultiop $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\t# check for log message\n\t$LCTL dk | grep -i \"Early reply #\" || error \"No early reply\"\n\tdebugrestore\n\t# client should show REQ_DELAY estimates\n\tlctl get_param -n osc.${FSNAME}-OST0000-osc-*.timeouts | grep portal\n}\nrun_test 65b \"AT: verify early replies on packed reply / bulk\"\n\ntest_66a() #bug 3055\n{\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    at_start || return 0\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep \"portal 12\"\n    # adjust 5s at a time so no early reply is sent (within deadline)\n    do_facet $SINGLEMDS \"$LCTL set_param fail_val=5000\"\n#define OBD_FAIL_PTLRPC_PAUSE_REQ        0x50a\n    do_facet $SINGLEMDS \"$LCTL set_param fail_loc=0x8000050a\"\n    createmany -o $DIR/$tfile 20 > /dev/null\n    unlinkmany $DIR/$tfile 20 > /dev/null\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep \"portal 12\"\n    do_facet $SINGLEMDS \"$LCTL set_param fail_val=10000\"\n    do_facet $SINGLEMDS \"$LCTL set_param fail_loc=0x8000050a\"\n    createmany -o $DIR/$tfile 20 > /dev/null\n    unlinkmany $DIR/$tfile 20 > /dev/null\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep \"portal 12\"\n    do_facet $SINGLEMDS \"$LCTL set_param fail_loc=0\"\n    sleep 9\n    createmany -o $DIR/$tfile 20 > /dev/null\n    unlinkmany $DIR/$tfile 20 > /dev/null\n    lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | grep \"portal 12\"\n    CUR=$(lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | awk '/portal 12/ {print $5}')\n    WORST=$(lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts | awk '/portal 12/ {print $7}')\n    echo \"Current MDT timeout $CUR, worst $WORST\"\n    [ $CUR -lt $WORST ] || error \"Current $CUR should be less than worst $WORST\"\n}\nrun_test 66a \"AT: verify MDT service time adjusts with no early replies\"\n\ntest_66b() #bug 3055\n{\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n\tat_start || return 0\n\tORIG=$(lctl get_param -n mdc.${FSNAME}-MDT0000*.timeouts |\n\t\tawk '/network/ {print $4}')\n\t$LCTL set_param fail_val=$(($ORIG + 5))\n\t#define OBD_FAIL_PTLRPC_PAUSE_REP      0x50c\n\t$LCTL set_param fail_loc=0x50c\n\ttouch $DIR/$tfile > /dev/null 2>&1\n\t$LCTL set_param fail_loc=0\n\tCUR=$(lctl get_param -n mdc.${FSNAME}-MDT0000*.timeouts |\n\t\tawk '/network/ {print $4}')\n\tWORST=$(lctl get_param -n mdc.${FSNAME}-MDT0000*.timeouts |\n\t\tawk '/network/ {print $6}')\n\techo \"network timeout orig $ORIG, cur $CUR, worst $WORST\"\n\t[ $WORST -gt $ORIG ] ||\n\t\terror \"Worst $WORST should be worse than orig $ORIG\"\n}\nrun_test 66b \"AT: verify net latency adjusts\"\n\ntest_67a() #bug 3055\n{\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    at_start || return 0\n    CONN1=$(lctl get_param -n osc.*.stats | awk '/_connect/ {total+=$2} END {print total}')\n    # sleeping threads may drive values above this\n    do_facet ost1 \"$LCTL set_param fail_val=400\"\n#define OBD_FAIL_PTLRPC_PAUSE_REQ    0x50a\n    do_facet ost1 \"$LCTL set_param fail_loc=0x50a\"\n    createmany -o $DIR/$tfile 20 > /dev/null\n    unlinkmany $DIR/$tfile 20 > /dev/null\n    do_facet ost1 \"$LCTL set_param fail_loc=0\"\n    CONN2=$(lctl get_param -n osc.*.stats | awk '/_connect/ {total+=$2} END {print total}')\n    ATTEMPTS=$(($CONN2 - $CONN1))\n    echo \"$ATTEMPTS osc reconnect attempts on gradual slow\"\n\t[ $ATTEMPTS -gt 0 ] &&\n\t\terror_ignore bz13721 \"AT should have prevented reconnect\"\n\treturn 0\n}\nrun_test 67a \"AT: verify slow request processing doesn't induce reconnects\"\n\ntest_67b() #bug 3055\n{\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    at_start || return 0\n    CONN1=$(lctl get_param -n osc.*.stats | awk '/_connect/ {total+=$2} END {print total}')\n\n\t# exhaust precreations on ost1\n\tlocal OST=$(ostname_from_index 0)\n\tlocal mdtosc=$(get_mdtosc_proc_path mds $OST)\n\tlocal last_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\tosp.$mdtosc.prealloc_last_id)\n\tlocal next_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\tosp.$mdtosc.prealloc_next_id)\n\n\tmkdir -p $DIR/$tdir/${OST} || error \"mkdir $DIR/$tdir/${OST} failed\"\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir/${OST} ||\n\t\terror \"$LFS setstripe failed\"\n\techo \"Creating to objid $last_id on ost $OST...\"\n#define OBD_FAIL_OST_PAUSE_CREATE        0x223\n    do_facet ost1 \"$LCTL set_param fail_val=20000\"\n    do_facet ost1 \"$LCTL set_param fail_loc=0x80000223\"\n    createmany -o $DIR/$tdir/${OST}/f $next_id $((last_id - next_id + 2))\n\n    client_reconnect\n    do_facet ost1 \"lctl get_param -n ost.OSS.ost_create.timeouts\"\n    log \"phase 2\"\n    CONN2=$(lctl get_param -n osc.*.stats | awk '/_connect/ {total+=$2} END {print total}')\n    ATTEMPTS=$(($CONN2 - $CONN1))\n    echo \"$ATTEMPTS osc reconnect attempts on instant slow\"\n    # do it again; should not timeout\n    do_facet ost1 \"$LCTL set_param fail_loc=0x80000223\"\n    cp /etc/profile $DIR/$tfile || error \"cp failed\"\n    do_facet ost1 \"$LCTL set_param fail_loc=0\"\n    client_reconnect\n    do_facet ost1 \"lctl get_param -n ost.OSS.ost_create.timeouts\"\n    CONN3=$(lctl get_param -n osc.*.stats | awk '/_connect/ {total+=$2} END {print total}')\n    ATTEMPTS=$(($CONN3 - $CONN2))\n    echo \"$ATTEMPTS osc reconnect attempts on 2nd slow\"\n    [ $ATTEMPTS -gt 0 ] && error \"AT should have prevented reconnect\"\n    return 0\n}\nrun_test 67b \"AT: verify instant slowdown doesn't induce reconnects\"\n\ntest_68 () #bug 13813\n{\n    remote_ost_nodsh && skip \"remote OST with nodsh\" && return 0\n\n    at_start || return 0\n    local ldlm_enqueue_min=$(find /sys -name ldlm_enqueue_min)\n    [ -z \"$ldlm_enqueue_min\" ] && skip \"missing /sys/.../ldlm_enqueue_min\" && return 0\n    local ldlm_enqueue_min_r=$(do_facet ost1 \"find /sys -name ldlm_enqueue_min\")\n    [ -z \"$ldlm_enqueue_min_r\" ] && skip \"missing /sys/.../ldlm_enqueue_min in the ost1\" && return 0\n    local ENQ_MIN=$(cat $ldlm_enqueue_min)\n    local ENQ_MIN_R=$(do_facet ost1 \"cat $ldlm_enqueue_min_r\")\n\techo $TIMEOUT >> $ldlm_enqueue_min\n\tdo_facet ost1 \"echo $TIMEOUT >> $ldlm_enqueue_min_r\"\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS setstripe --stripe-index=0 -c 1 $DIR/$tdir ||\n\t\terror \"$LFS setstripe failed for $DIR/$tdir\"\n\t#define OBD_FAIL_LDLM_PAUSE_CANCEL       0x312\n\t$LCTL set_param fail_val=$(($TIMEOUT - 1))\n\t$LCTL set_param fail_loc=0x80000312\n\tcp /etc/profile $DIR/$tdir/${tfile}_1 || error \"1st cp failed $?\"\n\t$LCTL set_param fail_val=$((TIMEOUT * 5 / 4))\n\t$LCTL set_param fail_loc=0x80000312\n\tcp /etc/profile $DIR/$tdir/${tfile}_2 || error \"2nd cp failed $?\"\n\t$LCTL set_param fail_loc=0\n\n\techo $ENQ_MIN >> $ldlm_enqueue_min\n\tdo_facet ost1 \"echo $ENQ_MIN_R >> $ldlm_enqueue_min_r\"\n\trm -rf $DIR/$tdir\n\treturn 0\n}\nrun_test 68 \"AT: verify slowing locks\"\n\nat_cleanup\n# end of AT tests includes above lines\n\n# start multi-client tests\ntest_70a () {\n\t[ -z \"$CLIENTS\" ] &&\n\t\t{ skip \"Need two or more clients.\" && return; }\n\t[ $CLIENTCOUNT -lt 2 ] &&\n\t\t{ skip \"Need two or more clients, have $CLIENTCOUNT\" && return; }\n\n\techo \"mount clients $CLIENTS ...\"\n\tzconf_mount_clients $CLIENTS $MOUNT\n\n\tlocal clients=${CLIENTS//,/ }\n\techo \"Write/read files on $DIR ; clients $CLIENTS ... \"\n\tfor CLIENT in $clients; do\n\t\tdo_node $CLIENT dd bs=1M count=10 if=/dev/zero \\\n\t\t\tof=$DIR/${tfile}_${CLIENT} 2>/dev/null ||\n\t\t\t\terror \"dd failed on $CLIENT\"\n\tdone\n\n\tlocal prev_client=$(echo $clients | sed 's/^.* \\(.\\+\\)$/\\1/')\n\tfor C in ${CLIENTS//,/ }; do\n\t\tdo_node $prev_client dd if=$DIR/${tfile}_${C} \\\n\t\t\tof=/dev/null 2>/dev/null ||\n\t\t\terror \"dd if=$DIR/${tfile}_${C} failed on $prev_client\"\n\t\tprev_client=$C\n\tdone\n\n\tls $DIR\n}\nrun_test 70a \"check multi client t-f\"\n\ncheck_for_process () {\n\tlocal clients=$1\n\tshift\n\tlocal prog=$@\n\n\tkillall_process $clients \"$prog\" -0\n}\n\ntest_70b () {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=300\n\t[ \"$SLOW\" = \"no\" ] && duration=120\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\tlocal cmd=\"rundbench 1 -t $duration\"\n\tlocal pid=\"\"\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\ttest_mkdir -p -c$MDSCOUNT $DIR/$tdir\n\t\t$LFS setdirstripe -D -c$MDSCOUNT $DIR/$tdir\n\tfi\n\tdo_nodesv $clients \"set -x; MISSING_DBENCH_OK=$MISSING_DBENCH_OK \\\n\t\tPATH=\\$PATH:$LUSTRE/utils:$LUSTRE/tests/:$DBENCH_LIB \\\n\t\tDBENCH_LIB=$DBENCH_LIB TESTSUITE=$TESTSUITE TESTNAME=$TESTNAME \\\n\t\tMOUNT=$MOUNT DIR=$DIR/$tdir/\\\\\\$(hostname) LCTL=$LCTL $cmd\" &\n\tpid=$!\n\n\t#LU-1897 wait for all dbench copies to start\n\twhile ! check_for_process $clients dbench; do\n\t\telapsed=$(($(date +%s) - start_ts))\n\t\tif [ $elapsed -gt $duration ]; then\n\t\t\tkillall_process $clients dbench\n\t\t\terror \"dbench failed to start on $clients!\"\n\t\tfi\n\t\tsleep 1\n\tdone\n\n\tlog \"Started rundbench load pid=$pid ...\"\n\n\telapsed=$(($(date +%s) - start_ts))\n\tlocal num_failovers=0\n\tlocal fail_index=1\n\twhile [ $elapsed -lt $duration ]; do\n\t\tif ! check_for_process $clients dbench; then\n\t\t\terror_noexit \"dbench stopped on some of $clients!\"\n\t\t\tkillall_process $clients dbench\n\t\t\tbreak\n\t\tfi\n\t\tsleep 1\n\t\treplay_barrier mds$fail_index\n\t\tsleep 1 # give clients a time to do operations\n\t\t# Increment the number of failovers\n\t\tnum_failovers=$((num_failovers+1))\n\t\tlog \"$TESTNAME fail mds$fail_index $num_failovers times\"\n\t\tfail mds$fail_index\n\t\telapsed=$(($(date +%s) - start_ts))\n\t\tif [ $fail_index -ge $MDSCOUNT ]; then\n\t\t\tfail_index=1\n\t\telse\n\t\t\tfail_index=$((fail_index+1))\n\t\tfi\n\tdone\n\n\twait $pid || error \"rundbench load on $clients failed!\"\n}\nrun_test 70b \"dbench ${MDSCOUNT}mdts recovery; $CLIENTCOUNT clients\"\n# end multi-client tests\n\nrandom_fail_mdt() {\n\tlocal max_index=$1\n\tlocal duration=$2\n\tlocal monitor_pid=$3\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\tlocal num_failovers=0\n\tlocal fail_index\n\n\telapsed=$(($(date +%s) - start_ts))\n\twhile [ $elapsed -lt $duration ]; do\n\t\tfail_index=$((RANDOM%max_index+1))\n\t\tkill -0 $monitor_pid ||\n\t\t\terror \"$monitor_pid stopped\"\n\t\tsleep 120\n\t\treplay_barrier mds$fail_index\n\t\tsleep 10\n\t\t# Increment the number of failovers\n\t\tnum_failovers=$((num_failovers+1))\n\t\tlog \"$TESTNAME fail mds$fail_index $num_failovers times\"\n\t\tfail mds$fail_index\n\t\telapsed=$(($(date +%s) - start_ts))\n\tdone\n}\n\ncleanup_70c() {\n\ttrap 0\n\trm -f $DIR/replay-single.70c.lck\n\trm -rf /$DIR/$tdir\n}\n\ntest_70c () {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal rc=0\n\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=300\n\t[ \"$SLOW\" = \"no\" ] && duration=180\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=600\n\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\n\ttrap cleanup_70c EXIT\n\t(\n\t\twhile [ ! -e $DIR/replay-single.70c.lck ]; do\n\t\t\ttest_mkdir -p -c$MDSCOUNT $DIR/$tdir || break\n\t\t\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t\t\t$LFS setdirstripe -D -c$MDSCOUNT $DIR/$tdir ||\n\t\t\t\terror \"set default dirstripe failed\"\n\t\t\tfi\n\t\t\tcd $DIR/$tdir || break\n\t\t\ttar cf - /etc | tar xf - || error \"tar failed in loop\"\n\t\tdone\n\t)&\n\ttar_70c_pid=$!\n\techo \"Started tar $tar_70c_pid\"\n\n\trandom_fail_mdt $MDSCOUNT $duration $tar_70c_pid\n\tkill -0 $tar_70c_pid || error \"tar $tar_70c_pid stopped\"\n\n\ttouch $DIR/replay-single.70c.lck\n\twait $tar_70c_pid || error \"$?: tar failed\"\n\n\tcleanup_70c\n\ttrue\n}\nrun_test 70c \"tar ${MDSCOUNT}mdts recovery\"\n\ncleanup_70d() {\n\ttrap 0\n\tkill -9 $mkdir_70d_pid\n}\n\ntest_70d () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal rc=0\n\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=300\n\t[ \"$SLOW\" = \"no\" ] && duration=180\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\n\ttrap cleanup_70d EXIT\n\t(\n\t\twhile true; do\n\t\t\t$LFS mkdir -i0 -c2 $DIR/$tdir/test || {\n\t\t\t\techo \"mkdir fails\"\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t$LFS mkdir -i1 -c2 $DIR/$tdir/test1 || {\n\t\t\t\techo \"mkdir fails\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttouch $DIR/$tdir/test/a || {\n\t\t\t\techo \"touch fails\"\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmkdir $DIR/$tdir/test/b || {\n\t\t\t\techo \"mkdir fails\"\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\trm -rf $DIR/$tdir/test || {\n\t\t\t\techo \"rmdir fails\"\n\t\t\t\tls -lR $DIR/$tdir\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\ttouch $DIR/$tdir/test1/a || {\n\t\t\t\techo \"touch fails\"\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tmkdir $DIR/$tdir/test1/b || {\n\t\t\t\techo \"mkdir fails\"\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\trm -rf $DIR/$tdir/test1 || {\n\t\t\t\techo \"rmdir fails\"\n\t\t\t\tls -lR $DIR/$tdir/test1\n\t\t\t\tbreak\n\t\t\t}\n\t\tdone\n\t)&\n\tmkdir_70d_pid=$!\n\techo \"Started  $mkdir_70d_pid\"\n\n\trandom_fail_mdt $MDSCOUNT $duration $mkdir_70d_pid\n\tkill -0 $mkdir_70d_pid || error \"mkdir/rmdir $mkdir_70d_pid stopped\"\n\n\tcleanup_70d\n\ttrue\n}\nrun_test 70d \"mkdir/rmdir striped dir ${MDSCOUNT}mdts recovery\"\n\ntest_70e () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal rc=0\n\n\tlctl set_param debug=+ha\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=300\n\t[ \"$SLOW\" = \"no\" ] && duration=180\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i0 $DIR/$tdir/test_0\n\t$LFS mkdir -i0 $DIR/$tdir/test_1\n\ttouch $DIR/$tdir/test_0/a\n\ttouch $DIR/$tdir/test_1/b\n\t(\n\twhile true; do\n\t\tmrename $DIR/$tdir/test_0/a $DIR/$tdir/test_1/b > /dev/null || {\n\t\t\techo \"a->b fails\"\n\t\t\tbreak;\n\t\t}\n\n\t\tcheckstat $DIR/$tdir/test_0/a && {\n\t\t\techo \"a still exists\"\n\t\t\tbreak\n\t\t}\n\n\t\tcheckstat $DIR/$tdir/test_1/b || {\n\t\t\techo \"b still  exists\"\n\t\t\tbreak\n\t\t}\n\n\t\ttouch $DIR/$tdir/test_0/a || {\n\t\t\techo \"touch a fails\"\n\t\t\tbreak\n\t\t}\n\n\t\tmrename $DIR/$tdir/test_1/b $DIR/$tdir/test_0/a > /dev/null || {\n\t\t\techo \"a->a fails\"\n\t\t\tbreak;\n\t\t}\n\tdone\n\t)&\n\trename_70e_pid=$!\n\tstack_trap \"kill -9 $rename_70e_pid\" EXIT\n\techo \"Started PID=$rename_70e_pid\"\n\n\trandom_fail_mdt 2 $duration $rename_70e_pid\n\tkill -0 $rename_70e_pid || error \"rename $rename_70e_pid stopped\"\n}\nrun_test 70e \"rename cross-MDT with random fails\"\n\ntest_70f_write_and_read(){\n\tlocal srcfile=$1\n\tlocal stopflag=$2\n\tlocal client\n\n\techo \"Write/read files in: '$DIR/$tdir', clients: '$CLIENTS' ...\"\n\tfor client in ${CLIENTS//,/ }; do\n\t\t[ -f $stopflag ] || return\n\n\t\tlocal tgtfile=$DIR/$tdir/$tfile.$client\n\t\tdo_node $client dd $DD_OPTS bs=1M count=10 if=$srcfile \\\n\t\t\tof=$tgtfile 2>/dev/null ||\n\t\t\terror \"dd $DD_OPTS bs=1M count=10 if=$srcfile \" \\\n\t\t\t      \"of=$tgtfile failed on $client, rc=$?\"\n\tdone\n\n\tlocal prev_client=$(echo ${CLIENTS//,/ } | awk '{ print $NF }')\n\tlocal index=0\n\n\tfor client in ${CLIENTS//,/ }; do\n\t\t[ -f $stopflag ] || return\n\n\t\t# flush client cache in case test is running on only one client\n\t\t# do_node $client cancel_lru_locks osc\n\t\tdo_node $client $LCTL set_param ldlm.namespaces.*.lru_size=clear\n\n\t\ttgtfile=$DIR/$tdir/$tfile.$client\n\t\tlocal md5=$(do_node $prev_client \"md5sum $tgtfile\")\n\t\t[ ${checksum[$index]// */} = ${md5// */} ] ||\n\t\t\terror \"$tgtfile: checksum doesn't match on $prev_client\"\n\t\tindex=$((index + 1))\n\t\tprev_client=$client\n\tdone\n}\n\ntest_70f_loop(){\n\tlocal srcfile=$1\n\tlocal stopflag=$2\n\tDD_OPTS=\n\n\tmkdir -p $DIR/$tdir || error \"cannot create $DIR/$tdir directory\"\n\t$LFS setstripe -c -1 $DIR/$tdir ||\n\t\terror \"cannot $LFS setstripe $DIR/$tdir\"\n\n\ttouch $stopflag\n\twhile [ -f $stopflag ]; do\n\t\ttest_70f_write_and_read $srcfile $stopflag\n\t\t# use direct IO and buffer cache in turns if loop\n\t\t[ -n \"$DD_OPTS\" ] && DD_OPTS=\"\" || DD_OPTS=\"oflag=direct\"\n\tdone\n}\n\ntest_70f_cleanup() {\n\ttrap 0\n\trm -f $TMP/$tfile.stop\n\tdo_nodes $CLIENTS rm -f $TMP/$tfile\n\trm -f $DIR/$tdir/$tfile.*\n}\n\ntest_70f() {\n#\t[ x$ost1failover_HOST = x$ost_HOST ] &&\n#\t\t{ skip \"Failover host not defined\" && return; }\n#\t[ -z \"$CLIENTS\" ] &&\n#\t\t{ skip \"CLIENTS are not specified.\" && return; }\n#\t[ $CLIENTCOUNT -lt 2 ] &&\n#\t\t{ skip \"Need 2 or more clients, have $CLIENTCOUNT\" && return; }\n\n\t[[ \"$OST1_VERSION\" -lt $(version_code 2.9.53) ]] &&\n\t\tskip \"Need server version at least 2.9.53\"\n\n\techo \"mount clients $CLIENTS ...\"\n\tzconf_mount_clients $CLIENTS $MOUNT\n\n\tlocal srcfile=$TMP/$tfile\n\tlocal client\n\tlocal index=0\n\n\ttrap test_70f_cleanup EXIT\n\t# create a different source file local to each client node so we can\n\t# detect if the file wasn't written out properly after failover\n\tdo_nodes $CLIENTS dd bs=1M count=10 if=/dev/urandom of=$srcfile \\\n\t\t2>/dev/null || error \"can't create $srcfile on $CLIENTS\"\n\tfor client in ${CLIENTS//,/ }; do\n\t\tchecksum[$index]=$(do_node $client \"md5sum $srcfile\")\n\t\tindex=$((index + 1))\n\tdone\n\n\tlocal duration=120\n\t[ \"$SLOW\" = \"no\" ] && duration=60\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tlocal stopflag=$TMP/$tfile.stop\n\ttest_70f_loop $srcfile $stopflag &\n\tlocal pid=$!\n\n\tlocal elapsed=0\n\tlocal num_failovers=0\n\tlocal start_ts=$SECONDS\n\twhile [ $elapsed -lt $duration ]; do\n\t\tsleep 3\n\t\treplay_barrier ost1\n\t\tsleep 1\n\t\tnum_failovers=$((num_failovers + 1))\n\t\tlog \"$TESTNAME failing OST $num_failovers times\"\n\t\tfail ost1\n\t\tsleep 2\n\t\telapsed=$((SECONDS - start_ts))\n\tdone\n\n\trm -f $stopflag\n\twait $pid\n\ttest_70f_cleanup\n}\nrun_test 70f \"OSS O_DIRECT recovery with $CLIENTCOUNT clients\"\n\ncleanup_71a() {\n\ttrap 0\n\tkill -9 $mkdir_71a_pid\n}\n\nrandom_double_fail_mdt() {\n\tlocal max_index=$1\n\tlocal duration=$2\n\tlocal monitor_pid=$3\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\tlocal num_failovers=0\n\tlocal fail_index\n\tlocal second_index\n\n\telapsed=$(($(date +%s) - start_ts))\n\twhile [ $elapsed -lt $duration ]; do\n\t\tfail_index=$((RANDOM%max_index + 1))\n\t\tif [ $fail_index -eq $max_index ]; then\n\t\t\tsecond_index=1\n\t\telse\n\t\t\tsecond_index=$((fail_index + 1))\n\t\tfi\n\t\tkill -0 $monitor_pid ||\n\t\t\terror \"$monitor_pid stopped\"\n\t\tsleep 120\n\t\treplay_barrier mds$fail_index\n\t\treplay_barrier mds$second_index\n\t\tsleep 10\n\t\t# Increment the number of failovers\n\t\tnum_failovers=$((num_failovers+1))\n\t\tlog \"fail mds$fail_index mds$second_index $num_failovers times\"\n\t\tfail mds${fail_index},mds${second_index}\n\t\telapsed=$(($(date +%s) - start_ts))\n\tdone\n}\n\ntest_71a () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal rc=0\n\n\tzconf_mount_clients $clients $MOUNT\n\n\tlocal duration=300\n\t[ \"$SLOW\" = \"no\" ] && duration=180\n\t# set duration to 900 because it takes some time to boot node\n\t[ \"$FAILURE_MODE\" = HARD ] && duration=900\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal elapsed\n\tlocal start_ts=$(date +%s)\n\n\ttrap cleanup_71a EXIT\n\t(\n\t\twhile true; do\n\t\t\t$LFS mkdir -i0 -c2 $DIR/$tdir/test\n\t\t\trmdir $DIR/$tdir/test\n\t\tdone\n\t)&\n\tmkdir_71a_pid=$!\n\techo \"Started  $mkdir_71a_pid\"\n\n\trandom_double_fail_mdt 2 $duration $mkdir_71a_pid\n\tkill -0 $mkdir_71a_pid || error \"mkdir/rmdir $mkdir_71a_pid stopped\"\n\n\tcleanup_71a\n\ttrue\n}\nrun_test 71a \"mkdir/rmdir striped dir with 2 mdts recovery\"\n\ntest_73a() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\n\treplay_barrier $SINGLEMDS\n\t#define OBD_FAIL_LDLM_ENQUEUE_NET\t\t\t0x302\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000302\"\n\tfail $SINGLEMDS\n\tkill -USR1 $pid\n\twait $pid || error \"multiop pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 73a \"open(O_CREAT), unlink, replay, reconnect before open replay, close\"\n\ntest_73b() {\n\tmultiop_bg_pause $DIR/$tfile O_tSc ||\n\t\terror \"multiop_bg_pause $DIR/$tfile failed\"\n\tpid=$!\n\trm -f $DIR/$tfile\n\n\treplay_barrier $SINGLEMDS\n\t#define OBD_FAIL_MDS_LDLM_REPLY_NET       0x157\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000157\"\n\tfail $SINGLEMDS\n\tkill -USR1 $pid\n\twait $pid || error \"multiop pid failed\"\n\t[ -e $DIR/$tfile ] && error \"file $DIR/$tfile should not exist\"\n\treturn 0\n}\nrun_test 73b \"open(O_CREAT), unlink, replay, reconnect at open_replay reply, close\"\n\n# bug 18554\ntest_74() {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\tzconf_umount_clients $clients $MOUNT\n\tstop ost1\n\tfacet_failover $SINGLEMDS\n\tzconf_mount_clients $clients $MOUNT\n\tmount_facet ost1\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\trm $DIR/$tfile || error \"rm $DIR/$tfile failed\"\n\tclients_up || error \"client evicted: $?\"\n\treturn 0\n}\nrun_test 74 \"Ensure applications don't fail waiting for OST recovery\"\n\nremote_dir_check_80() {\n\tlocal mdtidx=1\n\tlocal diridx\n\tlocal fileidx\n\n\tdiridx=$($LFS getstripe -m $remote_dir) ||\n\t\terror \"$LFS getstripe -m $remote_dir failed\"\n\t[ $diridx -eq $mdtidx ] || error \"$diridx != $mdtidx\"\n\n\tcreatemany -o $remote_dir/f-%d 20 || error \"creation failed\"\n\tfileidx=$($LFS getstripe -m $remote_dir/f-1) ||\n\t\terror \"$LFS getstripe -m $remote_dir/f-1 failed\"\n\t[ $fileidx -eq $mdtidx ] || error \"$fileidx != $mdtidx\"\n\n\treturn 0\n}\n\ntest_80a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t#define OBD_FAIL_OUT_UPDATE_NET_REP\t0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\tfail mds${MDTIDX}\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80a \"DNE: create remote dir, drop update rep from MDT0, fail MDT0\"\n\ntest_80b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t#define OBD_FAIL_OUT_UPDATE_NET_REP\t0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80b \"DNE: create remote dir, drop update rep from MDT0, fail MDT1\"\n\ntest_80c() {\n\t[[ \"$mds1_FSTYPE\" = zfs ]] &&\n\t\t[[ $MDS1_VERSION -lt $(version_code 2.12.51) ]] &&\n\t\tskip \"requires LU-10143 fix on MDS\"\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\"\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t#define OBD_FAIL_OUT_UPDATE_NET_REP\t0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX}\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80c \"DNE: create remote dir, drop update rep from MDT1, fail MDT[0,1]\"\n\ntest_80d() {\n\t[[ \"$mds1_FSTYPE\" = zfs ]] &&\n\t\t[[ $MDS1_VERSION -lt $(version_code 2.12.51) ]] &&\n\t\tskip \"requires LU-10143 fix on MDS\"\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t#define OBD_FAIL_OUT_UPDATE_NET_REP\t0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\t# sleep 3 seconds to make sure MDTs are failed after\n\t# lfs mkdir -i has finished on all of MDTs.\n\tsleep 3\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80d \"DNE: create remote dir, drop update rep from MDT1, fail 2 MDTs\"\n\ntest_80e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\t# sleep 3 seconds to make sure MDTs are failed after\n\t# lfs mkdir -i has finished on all of MDTs.\n\tsleep 3\n\n\treplay_barrier mds1\n\tfail mds${MDTIDX}\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80e \"DNE: create remote dir, drop MDT1 rep, fail MDT0\"\n\ntest_80f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds2\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80f \"DNE: create remote dir, drop MDT1 rep, fail MDT1\"\n\ntest_80g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\t# sleep 3 seconds to make sure MDTs are failed after\n\t# lfs mkdir -i has finished on all of MDTs.\n\tsleep 3\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX}\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80g \"DNE: create remote dir, drop MDT1 rep, fail MDT0, then MDT1\"\n\ntest_80h() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\t$LFS mkdir -i $MDTIDX $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\t# sleep 3 seconds to make sure MDTs are failed after\n\t# lfs mkdir -i has finished on all of MDTs.\n\tsleep 3\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"remote dir creation failed\"\n\n\tremote_dir_check_80 || error \"remote dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 80h \"DNE: create remote dir, drop MDT1 rep, fail 2 MDTs\"\n\ntest_81a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\ttouch $remote_dir || error \"touch $remote_dir failed\"\n\t# OBD_FAIL_OUT_UPDATE_NET_REP       0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds2\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81a \"DNE: unlink remote dir, drop MDT0 update rep,  fail MDT1\"\n\ntest_81b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP       0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\tfail mds${MDTIDX}\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81b \"DNE: unlink remote dir, drop MDT0 update reply,  fail MDT0\"\n\ntest_81c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP       0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX}\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81c \"DNE: unlink remote dir, drop MDT0 update reply, fail MDT0,MDT1\"\n\ntest_81d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_OUT_UPDATE_NET_REP       0x1701\n\tdo_facet mds${MDTIDX} lctl set_param fail_loc=0x1701\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81d \"DNE: unlink remote dir, drop MDT0 update reply,  fail 2 MDTs\"\n\ntest_81e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0\n\n\treplay_barrier mds1\n\tfail mds${MDTIDX}\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81e \"DNE: unlink remote dir, drop MDT1 req reply, fail MDT0\"\n\ntest_81f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds2\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81f \"DNE: unlink remote dir, drop MDT1 req reply, fail MDT1\"\n\ntest_81g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX}\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81g \"DNE: unlink remote dir, drop req reply, fail M0, then M1\"\n\ntest_81h() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i $MDTIDX $remote_dir || error \"lfs mkdir failed\"\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$((MDTIDX + 1)) lctl set_param fail_loc=0x119\n\trmdir $remote_dir &\n\tlocal CLIENT_PID=$!\n\n\treplay_barrier mds1\n\treplay_barrier mds2\n\tfail mds${MDTIDX},mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"rm remote dir failed\"\n\n\tstat $remote_dir &>/dev/null && error \"$remote_dir still exist!\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 81h \"DNE: unlink remote dir, drop request reply, fail 2 MDTs\"\n\ntest_84a() {\n#define OBD_FAIL_MDS_OPEN_WAIT_CREATE  0x144\n    do_facet $SINGLEMDS \"lctl set_param fail_loc=0x80000144\"\n    createmany -o $DIR/$tfile- 1 &\n    PID=$!\n    mds_evict_client\n    wait $PID\n    client_up || client_up || true    # reconnect\n}\nrun_test 84a \"stale open during export disconnect\"\n\ntest_85a() { #bug 16774\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"1\"\n\n\tfor i in $(seq 100); do\n\t\techo \"tag-$i\" > $DIR/$tfile-$i\n\t\tgrep -q \"tag-$i\" $DIR/$tfile-$i || error \"f2-$i\"\n\tdone\n\n\tlov_id=$(lctl dl | grep \"clilov\")\n\taddr=$(echo $lov_id | awk '{print $4}' | awk -F '-' '{print $NF}')\n\tcount=$(lctl get_param -n \\\n\t\tldlm.namespaces.*MDT0000*$addr.lock_unused_count)\n\techo \"before recovery: unused locks count = $count\"\n\n\tfail $SINGLEMDS\n\n\tcount2=$(lctl get_param -n \\\n\t\t ldlm.namespaces.*MDT0000*$addr.lock_unused_count)\n\techo \"after recovery: unused locks count = $count2\"\n\n\tif [ $count2 -ge $count ]; then\n\t\terror \"unused locks are not canceled\"\n\tfi\n}\nrun_test 85a \"check the cancellation of unused locks during recovery(IBITS)\"\n\ntest_85b() { #bug 16774\n\trm -rf $DIR/$tdir\n\tmkdir $DIR/$tdir\n\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"1\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\tfor i in $(seq 100); do\n\t\tdd if=/dev/urandom of=$DIR/$tdir/$tfile-$i bs=4096 \\\n\t\t\tcount=32 >/dev/null 2>&1\n\tdone\n\n\tcancel_lru_locks osc\n\n\tfor i in $(seq 100); do\n\t\tdd if=$DIR/$tdir/$tfile-$i of=/dev/null bs=4096 \\\n\t\t\tcount=32 >/dev/null 2>&1\n\tdone\n\n\tlov_id=$(lctl dl | grep \"clilov\")\n\taddr=$(echo $lov_id | awk '{print $4}' | awk -F '-' '{print $NF}')\n\tcount=$(lctl get_param -n \\\n\t\t\t  ldlm.namespaces.*OST0000*$addr.lock_unused_count)\n\techo \"before recovery: unused locks count = $count\"\n\t[ $count -ne 0 ] || error \"unused locks ($count) should be zero\"\n\n\tfail ost1\n\n\tcount2=$(lctl get_param \\\n\t\t -n ldlm.namespaces.*OST0000*$addr.lock_unused_count)\n\techo \"after recovery: unused locks count = $count2\"\n\n\tif [ $count2 -ge $count ]; then\n\t\terror \"unused locks are not canceled\"\n\tfi\n\n\trm -rf $DIR/$tdir\n}\nrun_test 85b \"check the cancellation of unused locks during recovery(EXTENT)\"\n\ntest_86() {\n        local clients=${CLIENTS:-$HOSTNAME}\n\n        zconf_umount_clients $clients $MOUNT\n        do_facet $SINGLEMDS lctl set_param mdt.${FSNAME}-MDT*.exports.clear=0\n        remount_facet $SINGLEMDS\n        zconf_mount_clients $clients $MOUNT\n}\nrun_test 86 \"umount server after clear nid_stats should not hit LBUG\"\n\ntest_87a() {\n\tdo_facet ost1 \"lctl set_param -n obdfilter.${ost1_svc}.sync_journal 0\"\n\n\treplay_barrier ost1\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1024k count=8 ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\tcksum=$(md5sum $DIR/$tfile | awk '{print $1}')\n\tcancel_lru_locks osc\n\tfail ost1\n\tdd if=$DIR/$tfile of=/dev/null bs=1024k count=8 || error \"Cannot read\"\n\tcksum2=$(md5sum $DIR/$tfile | awk '{print $1}')\n\tif [ $cksum != $cksum2 ] ; then\n\t\terror \"New checksum $cksum2 does not match original $cksum\"\n\tfi\n}\nrun_test 87a \"write replay\"\n\ntest_87b() {\n\tdo_facet ost1 \"lctl set_param -n obdfilter.${ost1_svc}.sync_journal 0\"\n\n\treplay_barrier ost1\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1024k count=8 ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\tsleep 1 # Give it a chance to flush dirty data\n\techo TESTTEST | dd of=$DIR/$tfile bs=1 count=8 seek=64\n\tcksum=$(md5sum $DIR/$tfile | awk '{print $1}')\n\tcancel_lru_locks osc\n\tfail ost1\n\tdd if=$DIR/$tfile of=/dev/null bs=1024k count=8 || error \"Cannot read\"\n\tcksum2=$(md5sum $DIR/$tfile | awk '{print $1}')\n\tif [ $cksum != $cksum2 ] ; then\n\t\terror \"New checksum $cksum2 does not match original $cksum\"\n\tfi\n}\nrun_test 87b \"write replay with changed data (checksum resend)\"\n\ntest_88() { #bug 17485\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tmkdir -p $TMP/$tdir || error \"mkdir $TMP/$tdir failed\"\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir || error \"$LFS setstripe failed\"\n\n\treplay_barrier ost1\n\treplay_barrier $SINGLEMDS\n\n\t# exhaust precreations on ost1\n\tlocal OST=$(ostname_from_index 0)\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $OST)\n\tlocal last_id=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_last_id)\n\tlocal next_id=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_next_id)\n\techo \"before test: last_id = $last_id, next_id = $next_id\"\n\n\techo \"Creating to objid $last_id on ost $OST...\"\n\tcreatemany -o $DIR/$tdir/f-%d $next_id $((last_id - next_id + 2)) ||\n\t\terror \"createmany create files to last_id failed\"\n\n\t#create some files to use some uncommitted objids\n\tlast_id=$(($last_id + 1))\n\tcreatemany -o $DIR/$tdir/f-%d $last_id 8 ||\n\t\terror \"createmany create files with uncommitted objids failed\"\n\n    last_id2=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_last_id)\n    next_id2=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_next_id)\n    echo \"before recovery: last_id = $last_id2, next_id = $next_id2\" \n\n    # if test uses shutdown_facet && reboot_facet instead of facet_failover ()\n    # it has to take care about the affected facets, bug20407\n    local affected_mds1=$(affected_facets mds1)\n    local affected_ost1=$(affected_facets ost1)\n\n    shutdown_facet $SINGLEMDS\n    shutdown_facet ost1\n\n    reboot_facet $SINGLEMDS\n    change_active $affected_mds1\n    wait_for_facet $affected_mds1\n    mount_facets $affected_mds1 || error \"Restart of mds failed\"\n\n    reboot_facet ost1\n    change_active $affected_ost1\n    wait_for_facet $affected_ost1\n    mount_facets $affected_ost1 || error \"Restart of ost1 failed\"\n\n    clients_up\n\n    last_id2=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_last_id)\n    next_id2=$(do_facet $SINGLEMDS lctl get_param -n osp.$mdtosc.prealloc_next_id)\n\techo \"after recovery: last_id = $last_id2, next_id = $next_id2\"\n\n\t# create new files, which should use new objids, and ensure the orphan\n\t# cleanup phase for ost1 is completed at the same time\n\tfor i in $(seq 8); do\n\t\tfile_id=$(($last_id + 10 + $i))\n\t\tdd if=/dev/urandom of=$DIR/$tdir/f-$file_id bs=4096 count=128\n\tdone\n\n\t# if the objids were not recreated, then \"ls\" will fail with -ENOENT\n\tls -l $DIR/$tdir/* || error \"can't get the status of precreated files\"\n\n\tlocal file_id\n\t# write into previously created files\n\tfor i in $(seq 8); do\n\t\tfile_id=$(($last_id + $i))\n\t\tdd if=/dev/urandom of=$DIR/$tdir/f-$file_id bs=4096 count=128\n\t\tcp -f $DIR/$tdir/f-$file_id $TMP/$tdir/\n\tdone\n\n\t# compare the content\n\tfor i in $(seq 8); do\n\t\tfile_id=$(($last_id + $i))\n\t\tcmp $TMP/$tdir/f-$file_id $DIR/$tdir/f-$file_id ||\n\t\t\terror \"the content of file is modified!\"\n\tdone\n\n\trm -fr $TMP/$tdir\n}\nrun_test 88 \"MDS should not assign same objid to different files \"\n\nfunction calc_osc_kbytes_used() {\n\tlocal kbtotal=$(calc_osc_kbytes kbytestotal)\n\tlocal kbfree=$(calc_osc_kbytes kbytesfree)\n\techo $((kbtotal-kbfree))\n}\n\ntest_89() {\n\tcancel_lru_locks osc\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\trm -f $DIR/$tdir/$tfile\n\twait_mds_ost_sync || error \"initial MDS-OST sync timed out\"\n\twait_delete_completed || error \"initial wait delete timed out\"\n\tlocal blocks1=$(calc_osc_kbytes_used)\n\tlocal write_size=$(fs_log_size)\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir/$tfile\n\t[ $write_size -lt 1024 ] && write_size=1024\n\tdd if=/dev/zero bs=${write_size}k count=10 of=$DIR/$tdir/$tfile\n\tsync\n\tstop ost1\n\tfacet_failover $SINGLEMDS\n\trm $DIR/$tdir/$tfile\n\tumount $MOUNT\n\tmount_facet ost1\n\tzconf_mount $(hostname) $MOUNT || error \"mount fails\"\n\tclient_up || error \"client_up failed\"\n\n\t# wait for the remounted client to connect to ost1\n\tlocal target=$(get_osc_import_name client ost1)\n\twait_import_state \"FULL\" \"osc.${target}.ost_server_uuid\" \\\n\t\t$(max_recovery_time)\n\n\twait_mds_ost_sync || error \"MDS-OST sync timed out\"\n\twait_delete_completed || error \"wait delete timed out\"\n\tlocal blocks2=$(calc_osc_kbytes_used)\n\n\t[ $((blocks2 - blocks1)) -le $(fs_log_size)  ] ||\n\t\terror $((blocks2 - blocks1)) blocks leaked\n}\nrun_test 89 \"no disk space leak on late ost connection\"\n\ncleanup_90 () {\n\tlocal facet=$1\n\n\ttrap 0\n\treboot_facet $facet\n\tchange_active $facet\n\twait_for_facet $facet\n\tmount_facet $facet || error \"Restart of $facet failed\"\n\tclients_up\n}\n\ntest_90() { # bug 19494\n    local dir=$DIR/$tdir\n    local ostfail=$(get_random_entry $(get_facets OST))\n\n    if [[ $FAILURE_MODE = HARD ]]; then\n        local affected=$(affected_facets $ostfail);\n        if [[ \"$affected\" != $ostfail ]]; then\n            skip not functional with FAILURE_MODE=$FAILURE_MODE, affected: $affected\n            return 0\n        fi\n    fi\n\t# ensure all OSTs are active to allow allocations\n\twait_osts_up\n\n\tmkdir $dir || error \"mkdir $dir failed\"\n\n\techo \"Create the files\"\n\n\t# file \"f${index}\" striped over 1 OST\n\t# file \"all\" striped over all OSTs\n\n\t$LFS setstripe -c $OSTCOUNT $dir/all ||\n\t\terror \"setstripe failed to create $dir/all\"\n\n\tfor ((i = 0; i < $OSTCOUNT; i++)); do\n\t\tlocal f=$dir/f$i\n\n\t\t$LFS setstripe -i $i -c 1 $f ||\n\t\t\terror \"$LFS setstripe failed to create $f\"\n\n\t\t# confirm setstripe actually created stripe on requested OST\n\t\tlocal uuid=$(ostuuid_from_index $i)\n\n\t\tfor file in f$i all; do\n\t\t\tlocal found=$($LFS find --obd $uuid --name $file $dir)\n\n\t\t\tif [[ $dir/$file != $found ]]; then\n\t\t\t\t$LFS getstripe $dir/$file\n\t\t\t\terror \"wrong stripe: $file, uuid: $uuid\"\n\t\t\tfi\n\t\tdone\n\tdone\n\n\t# Before failing an OST, get its obd name and index\n\tlocal varsvc=${ostfail}_svc\n\tlocal obd=$(do_facet $ostfail lctl get_param \\\n\t\t    -n obdfilter.${!varsvc}.uuid)\n\tlocal index=$(($(facet_number $ostfail) - 1))\n\n\techo \"Fail $ostfail $obd, display the list of affected files\"\n\tshutdown_facet $ostfail || error \"shutdown_facet $ostfail failed\"\n\n\ttrap \"cleanup_90 $ostfail\" EXIT INT\n\techo \"General Query: lfs find $dir\"\n\tlocal list=$($LFS find $dir)\n\techo \"$list\"\n\tfor (( i=0; i<$OSTCOUNT; i++ )); do\n\t\tlist_member \"$list\" $dir/f$i ||\n\t\t\terror_noexit \"lfs find $dir: no file f$i\"\n\tdone\n\tlist_member \"$list\" $dir/all ||\n\t\terror_noexit \"lfs find $dir: no file all\"\n\n\t# focus on the missing OST,\n\t# we expect to see only two files affected: \"f$(index)\" and \"all\"\n\n\techo \"Querying files on shutdown $ostfail: lfs find --obd $obd\"\n    list=$($LFS find --obd $obd $dir)\n    echo \"$list\"\n    for file in all f$index; do\n        list_member \"$list\" $dir/$file ||\n            error_noexit \"lfs find does not report the affected $obd for $file\"\n    done\n\n    [[ $(echo $list | wc -w) -eq 2 ]] ||\n        error_noexit \"lfs find reports the wrong list of affected files ${#list[@]}\"\n\n\techo \"Check getstripe: $LFS getstripe -r --obd $obd\"\n\tlist=$($LFS getstripe -r --obd $obd $dir)\n\techo \"$list\"\n    for file in all f$index; do\n        echo \"$list\" | grep $dir/$file ||\n            error_noexit \"lfs getsripe does not report the affected $obd for $file\"\n    done\n\n    cleanup_90 $ostfail\n}\nrun_test 90 \"lfs find identifies the missing striped file segments\"\n\ntest_93a() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.6.90) ]] ||\n\t\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.5.4) &&\n\t\t   \"$MDS1_VERSION\" -lt $(version_code 2.5.50) ]] ||\n\t\tskip \"Need MDS version 2.5.4+ or 2.6.90+\"\n\n\tcancel_lru_locks osc\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile ||\n\t\terror \"$LFS setstripe  $DIR/$tfile failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=1024 count=1 ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\t#define OBD_FAIL_TGT_REPLAY_RECONNECT     0x715\n\t# We need to emulate a state that OST is waiting for other clients\n\t# not completing the recovery. Final ping is queued, but reply will be\n\t# sent on the recovery completion. It is done by sleep before\n\t# processing final pings\n\tdo_facet ost1 \"$LCTL set_param fail_val=40\"\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x715\"\n\tfail ost1\n}\nrun_test 93a \"replay + reconnect\"\n\ntest_93b() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.90) ]] ||\n\t\tskip \"Need MDS version 2.7.90+\"\n\n\tcancel_lru_locks mdc\n\n\tcreatemany -o $DIR/$tfile 20 ||\n\t\t\terror \"createmany -o $DIR/$tfile failed\"\n\n\t#define OBD_FAIL_TGT_REPLAY_RECONNECT     0x715\n\t# We need to emulate a state that MDT is waiting for other clients\n\t# not completing the recovery. Final ping is queued, but reply will be\n\t# sent on the recovery completion. It is done by sleep before\n\t# processing final pings\n\tdo_facet mds1 \"$LCTL set_param fail_val=80\"\n\tdo_facet mds1 \"$LCTL set_param fail_loc=0x715\"\n\tfail mds1\n}\nrun_test 93b \"replay + reconnect on mds\"\n\nstriped_dir_check_100() {\n\tlocal striped_dir=$DIR/$tdir/striped_dir\n\tlocal stripe_count=$($LFS getdirstripe -c $striped_dir)\n\n\t$LFS getdirstripe $striped_dir\n\t[ $stripe_count -eq 2 ] || error \"$stripe_count != 2\"\n\n\tcreatemany -o $striped_dir/f-%d 20 ||\n\t\terror \"creation failed under striped dir\"\n}\n\ntest_100a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal striped_dir=$DIR/$tdir/striped_dir\n\tlocal MDTIDX=1\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\n\t#To make sure MDT1 and MDT0 are connected\n\t#otherwise it may create single stripe dir here\n\t$LFS setdirstripe -i1 $DIR/$tdir/remote_dir\n\n\t#define OBD_FAIL_OUT_UPDATE_NET_REP\t0x1701\n\tdo_facet mds$((MDTIDX+1)) lctl set_param fail_loc=0x1701\n\t$LFS setdirstripe -i0 -c2 $striped_dir &\n\tlocal CLIENT_PID=$!\n\n\tfail mds$((MDTIDX + 1))\n\n\twait $CLIENT_PID || error \"striped dir creation failed\"\n\n\tstriped_dir_check_100 || error \"striped dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 100a \"DNE: create striped dir, drop update rep from MDT1, fail MDT1\"\n\ntest_100b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal striped_dir=$DIR/$tdir/striped_dir\n\tlocal MDTIDX=1\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\n\t#To make sure MDT1 and MDT0 are connected\n\t#otherwise it may create single stripe dir here\n\t$LFS setdirstripe -i1 $DIR/$tdir/remote_dir\n\n\t# OBD_FAIL_MDS_REINT_NET_REP       0x119\n\tdo_facet mds$MDTIDX lctl set_param fail_loc=0x119\n\t$LFS mkdir -i0 -c2 $striped_dir &\n\n\tlocal CLIENT_PID=$!\n\tfail mds$MDTIDX\n\n\twait $CLIENT_PID || error \"striped dir creation failed\"\n\n\tstriped_dir_check_100 || error \"striped dir check failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 100b \"DNE: create striped dir, fail MDT0\"\n\ntest_101() { #LU-5648\n\tmkdir -p $DIR/$tdir/d1\n\tmkdir -p $DIR/$tdir/d2\n\ttouch $DIR/$tdir/file0\n\tnum=1000\n\n\treplay_barrier $SINGLEMDS\n\tfor i in $(seq $num) ; do\n\t\techo test$i > $DIR/$tdir/d1/file$i\n\tdone\n\n\tfail_abort $SINGLEMDS\n\tfor i in $(seq $num) ; do\n\t\ttouch $DIR/$tdir/d2/file$i\n\t\ttest -s $DIR/$tdir/d2/file$i &&\n\t\t\tls -al $DIR/$tdir/d2/file$i && error \"file$i's size > 0\"\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 101 \"Shouldn't reassign precreated objs to other files after recovery\"\n\ntest_102a() {\n\tlocal idx\n\tlocal facet\n\tlocal num\n\tlocal i\n\tlocal pids pid\n\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\t$LFS mkdir -c1 $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tidx=$(printf \"%04x\" $($LFS getdirstripe -i $DIR/$tdir))\n\tfacet=\"mds$((0x$idx + 1))\"\n\n\t# get current value of max_mod_rcps_in_flight\n\tnum=$($LCTL get_param -n \\\n\t\tmdc.$FSNAME-MDT$idx-mdc-*.max_mod_rpcs_in_flight)\n\t# set default value if client does not support multi mod RPCs\n\t[ -z \"$num\" ] && num=1\n\n\techo \"creating $num files ...\"\n\tumask 0022\n\tfor i in $(seq $num); do\n\t\ttouch $DIR/$tdir/file-$i\n\tdone\n\n\t# drop request on MDT to force resend\n\t#define OBD_FAIL_MDS_REINT_MULTI_NET 0x159\n\tdo_facet $facet \"$LCTL set_param fail_loc=0x159\"\n\techo \"launch $num chmod in parallel ($(date +%H:%M:%S)) ...\"\n\tfor i in $(seq $num); do\n\t\tchmod 0600 $DIR/$tdir/file-$i &\n\t\tpids=\"$pids $!\"\n\tdone\n\tsleep 1\n\tdo_facet $facet \"$LCTL set_param fail_loc=0\"\n\tfor pid in $pids; do\n\t\twait $pid || error \"chmod failed\"\n\tdone\n\techo \"done ($(date +%H:%M:%S))\"\n\n\t# check chmod succeed\n\tfor i in $(seq $num); do\n\t\tcheckstat -vp 0600 $DIR/$tdir/file-$i\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 102a \"check resend (request lost) with multiple modify RPCs in flight\"\n\ntest_102b() {\n\tlocal idx\n\tlocal facet\n\tlocal num\n\tlocal i\n\tlocal pids pid\n\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\t$LFS mkdir -c1 $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tidx=$(printf \"%04x\" $($LFS getdirstripe -i $DIR/$tdir))\n\tfacet=\"mds$((0x$idx + 1))\"\n\n\t# get current value of max_mod_rcps_in_flight\n\tnum=$($LCTL get_param -n \\\n\t\tmdc.$FSNAME-MDT$idx-mdc-*.max_mod_rpcs_in_flight)\n\t# set default value if client does not support multi mod RPCs\n\t[ -z \"$num\" ] && num=1\n\n\techo \"creating $num files ...\"\n\tumask 0022\n\tfor i in $(seq $num); do\n\t\ttouch $DIR/$tdir/file-$i\n\tdone\n\n\t# drop reply on MDT to force reconstruction\n\t#define OBD_FAIL_MDS_REINT_MULTI_NET_REP 0x15a\n\tdo_facet $facet \"$LCTL set_param fail_loc=0x15a\"\n\techo \"launch $num chmod in parallel ($(date +%H:%M:%S)) ...\"\n\tfor i in $(seq $num); do\n\t\tchmod 0600 $DIR/$tdir/file-$i &\n\t\tpids=\"$pids $!\"\n\tdone\n\tsleep 1\n\tdo_facet $facet \"$LCTL set_param fail_loc=0\"\n\tfor pid in $pids; do\n\t\twait $pid || error \"chmod failed\"\n\tdone\n\techo \"done ($(date +%H:%M:%S))\"\n\n\t# check chmod succeed\n\tfor i in $(seq $num); do\n\t\tcheckstat -vp 0600 $DIR/$tdir/file-$i\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 102b \"check resend (reply lost) with multiple modify RPCs in flight\"\n\ntest_102c() {\n\tlocal idx\n\tlocal facet\n\tlocal num\n\tlocal i\n\tlocal pids pid\n\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\t$LFS mkdir -c1 $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tidx=$(printf \"%04x\" $($LFS getdirstripe -i $DIR/$tdir))\n\tfacet=\"mds$((0x$idx + 1))\"\n\n\t# get current value of max_mod_rcps_in_flight\n\tnum=$($LCTL get_param -n \\\n\t\tmdc.$FSNAME-MDT$idx-mdc-*.max_mod_rpcs_in_flight)\n\t# set default value if client does not support multi mod RPCs\n\t[ -z \"$num\" ] && num=1\n\n\techo \"creating $num files ...\"\n\tumask 0022\n\tfor i in $(seq $num); do\n\t\ttouch $DIR/$tdir/file-$i\n\tdone\n\n\treplay_barrier $facet\n\n\t# drop reply on MDT\n\t#define OBD_FAIL_MDS_REINT_MULTI_NET_REP 0x15a\n\tdo_facet $facet \"$LCTL set_param fail_loc=0x15a\"\n\techo \"launch $num chmod in parallel ($(date +%H:%M:%S)) ...\"\n\tfor i in $(seq $num); do\n\t\tchmod 0600 $DIR/$tdir/file-$i &\n\t\tpids=\"$pids $!\"\n\tdone\n\tsleep 1\n\tdo_facet $facet \"$LCTL set_param fail_loc=0\"\n\n\t# fail MDT\n\tfail $facet\n\n\tfor pid in $pids; do\n\t\twait $pid || error \"chmod failed\"\n\tdone\n\techo \"done ($(date +%H:%M:%S))\"\n\n\t# check chmod succeed\n\tfor i in $(seq $num); do\n\t\tcheckstat -vp 0600 $DIR/$tdir/file-$i\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 102c \"check replay w/o reconstruction with multiple mod RPCs in flight\"\n\ntest_102d() {\n\tlocal idx\n\tlocal facet\n\tlocal num\n\tlocal i\n\tlocal pids pid\n\n\t[[ $(lctl get_param mdc.*.import |\n\t     grep \"connect_flags:.*multi_mod_rpc\") ]] ||\n\t\t{ skip \"Need MDC with 'multi_mod_rpcs' feature\"; return 0; }\n\n\t$LFS mkdir -c1 $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tidx=$(printf \"%04x\" $($LFS getdirstripe -i $DIR/$tdir))\n\tfacet=\"mds$((0x$idx + 1))\"\n\n\t# get current value of max_mod_rcps_in_flight\n\tnum=$($LCTL get_param -n \\\n\t\tmdc.$FSNAME-MDT$idx-mdc-*.max_mod_rpcs_in_flight)\n\t# set default value if client does not support multi mod RPCs\n\t[ -z \"$num\" ] && num=1\n\n\techo \"creating $num files ...\"\n\tumask 0022\n\tfor i in $(seq $num); do\n\t\ttouch $DIR/$tdir/file-$i\n\tdone\n\n\t# drop reply on MDT\n\t#define OBD_FAIL_MDS_REINT_MULTI_NET_REP 0x15a\n\tdo_facet $facet \"$LCTL set_param fail_loc=0x15a\"\n\techo \"launch $num chmod in parallel ($(date +%H:%M:%S)) ...\"\n\tfor i in $(seq $num); do\n\t\tchmod 0600 $DIR/$tdir/file-$i &\n\t\tpids=\"$pids $!\"\n\tdone\n\tsleep 1\n\n\t# write MDT transactions to disk\n\tdo_facet $facet \"sync; sync; sync\"\n\n\tdo_facet $facet \"$LCTL set_param fail_loc=0\"\n\n\t# fail MDT\n\tfail $facet\n\n\tfor pid in $pids; do\n\t\twait $pid || error \"chmod failed\"\n\tdone\n\techo \"done ($(date +%H:%M:%S))\"\n\n\t# check chmod succeed\n\tfor i in $(seq $num); do\n\t\tcheckstat -vp 0600 $DIR/$tdir/file-$i\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 102d \"check replay & reconstruction with multiple mod RPCs in flight\"\n\ntest_103() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ \"$MDS1_VERSION\" -gt $(version_code 2.8.54) ]] ||\n\t\tskip \"Need MDS version 2.8.54+\"\n\n#define OBD_FAIL_MDS_TRACK_OVERFLOW 0x162\n\tdo_facet mds1 $LCTL set_param fail_loc=0x80000162\n\n\tmkdir -p $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/t- 30 ||\n\t\terror \"create files on remote directory failed\"\n\tsync\n\trm -rf $DIR/$tdir/t-*\n\tsync\n#MDS should crash with tr->otr_next_id overflow\n\tfail mds1\n}\nrun_test 103 \"Check otr_next_id overflow\"\n\n\ncheck_striped_dir_110()\n{\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir ||\n\t\t\terror \"create striped dir failed\"\n\tlocal stripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir)\n\t[ $stripe_count -eq $MDSCOUNT ] ||\n\t\terror \"$stripe_count != 2 after recovery\"\n}\n\ntest_110a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds1\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tfail mds1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110a \"DNE: create striped dir, fail MDT1\"\n\ntest_110b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds1\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\tfail mds1\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110b \"DNE: create striped dir, fail MDT1 and client\"\n\ntest_110c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds2\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tfail mds2\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110c \"DNE: create striped dir, fail MDT2\"\n\ntest_110d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds2\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\tfail mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110d \"DNE: create striped dir, fail MDT2 and client\"\n\ntest_110e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds2\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\treplay_barrier mds1\n\tfail mds1,mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110e \"DNE: create striped dir, uncommit on MDT2, fail client/MDT1/MDT2\"\n\ntest_110f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds1\n\treplay_barrier mds2\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tfail mds2,mds1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110f \"DNE: create striped dir, fail MDT1/MDT2\"\n\ntest_110g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds1\n\t$LFS mkdir -i1 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\treplay_barrier mds2\n\tfail mds1,mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\tcheck_striped_dir_110 || error \"check striped_dir failed\"\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 110g \"DNE: create striped dir, uncommit on MDT1, fail client/MDT1/MDT2\"\n\ntest_111a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds1\n\trm -rf $DIR/$tdir/striped_dir\n\tfail mds1\n\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111a \"DNE: unlink striped dir, fail MDT1\"\n\ntest_111b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds2\n\trm -rf $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\tfail mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111b \"DNE: unlink striped dir, fail MDT2\"\n\ntest_111c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds1\n\trm -rf $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\treplay_barrier mds2\n\tfail mds1,mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111c \"DNE: unlink striped dir, uncommit on MDT1, fail client/MDT1/MDT2\"\n\ntest_111d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds2\n\trm -rf $DIR/$tdir/striped_dir\n\tumount $MOUNT\n\treplay_barrier mds1\n\tfail mds1,mds2\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\n\treturn 0\n}\nrun_test 111d \"DNE: unlink striped dir, uncommit on MDT2, fail client/MDT1/MDT2\"\n\ntest_111e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds2\n\trm -rf $DIR/$tdir/striped_dir\n\treplay_barrier mds1\n\tfail mds1,mds2\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111e \"DNE: unlink striped dir, uncommit on MDT2, fail MDT1/MDT2\"\n\ntest_111f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds1\n\trm -rf $DIR/$tdir/striped_dir\n\treplay_barrier mds2\n\tfail mds1,mds2\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111f \"DNE: unlink striped dir, uncommit on MDT1, fail MDT1/MDT2\"\n\ntest_111g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i1 -c2 $DIR/$tdir/striped_dir\n\treplay_barrier mds1\n\treplay_barrier mds2\n\trm -rf $DIR/$tdir/striped_dir\n\tfail mds1,mds2\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir &&\n\t\t\terror \"striped dir still exists\"\n\treturn 0\n}\nrun_test 111g \"DNE: unlink striped dir, fail MDT1/MDT2\"\n\ntest_112_rename_prepare() {\n\tmkdir -p $DIR/$tdir/src_dir\n\t$LFS mkdir -i 1 $DIR/$tdir/src_dir/src_child ||\n\t\terror \"create remote source failed\"\n\n\ttouch $DIR/$tdir/src_dir/src_child/a\n\n\t$LFS mkdir -i 2 $DIR/$tdir/tgt_dir ||\n\t\terror \"create remote target dir failed\"\n\n\t$LFS mkdir -i 3 $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"create remote target child failed\"\n}\n\ntest_112_check() {\n\tfind $DIR/$tdir/\n\t$CHECKSTAT -t dir $DIR/$tdir/src_dir/src_child &&\n\t\terror \"src_child still exists after rename\"\n\n\t$CHECKSTAT -t file $DIR/$tdir/tgt_dir/tgt_child/a ||\n\t\terror \"missing file(a) after rename\"\n}\n\ntest_112a() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\tfail mds1\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112a \"DNE: cross MDT rename, fail MDT1\"\n\ntest_112b() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds2\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds2\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112b \"DNE: cross MDT rename, fail MDT2\"\n\ntest_112c() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds3\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds3\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112c \"DNE: cross MDT rename, fail MDT3\"\n\ntest_112d() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112d \"DNE: cross MDT rename, fail MDT4\"\n\ntest_112e() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds2\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds2\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112e \"DNE: cross MDT rename, fail MDT1 and MDT2\"\n\ntest_112f() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds3\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds3\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112f \"DNE: cross MDT rename, fail MDT1 and MDT3\"\n\ntest_112g() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112g \"DNE: cross MDT rename, fail MDT1 and MDT4\"\n\ntest_112h() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds2\n\treplay_barrier mds3\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds2,mds3\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112h \"DNE: cross MDT rename, fail MDT2 and MDT3\"\n\ntest_112i() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds2\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds2,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112i \"DNE: cross MDT rename, fail MDT2 and MDT4\"\n\ntest_112j() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds3\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds3,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112j \"DNE: cross MDT rename, fail MDT3 and MDT4\"\n\ntest_112k() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds2\n\treplay_barrier mds3\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds2,mds3\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112k \"DNE: cross MDT rename, fail MDT1,MDT2,MDT3\"\n\ntest_112l() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds2\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds2,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112l \"DNE: cross MDT rename, fail MDT1,MDT2,MDT4\"\n\ntest_112m() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds1\n\treplay_barrier mds3\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds1,mds3,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112m \"DNE: cross MDT rename, fail MDT1,MDT3,MDT4\"\n\ntest_112n() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\ttest_112_rename_prepare\n\treplay_barrier mds2\n\treplay_barrier mds3\n\treplay_barrier mds4\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfail mds2,mds3,mds4\n\n\ttest_112_check\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 112n \"DNE: cross MDT rename, fail MDT2,MDT3,MDT4\"\n\ntest_115() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.7.56) ]] ||\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal fail_index=0\n\tlocal index\n\tlocal i\n\tlocal j\n\n\tmkdir -p $DIR/$tdir\n\tfor ((j=0;j<$((MDSCOUNT));j++)); do\n\t\tfail_index=$((fail_index+1))\n\t\tindex=$((fail_index % MDSCOUNT))\n\t\treplay_barrier mds$((index + 1))\n\t\tfor ((i=0;i<5;i++)); do\n\t\t\ttest_mkdir -i$index -c$MDSCOUNT $DIR/$tdir/test_$i ||\n\t\t\t\terror \"create striped dir $DIR/$tdir/test_$i\"\n\t\tdone\n\n\t\tfail mds$((index + 1))\n\t\tfor ((i=0;i<5;i++)); do\n\t\t\tcheckstat -t dir $DIR/$tdir/test_$i ||\n\t\t\t\terror \"$DIR/$tdir/test_$i does not exist!\"\n\t\tdone\n\t\trm -rf $DIR/$tdir/test_* ||\n\t\t\t\terror \"rmdir fails\"\n\tdone\n}\nrun_test 115 \"failover for create/unlink striped directory\"\n\ntest_116a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Do not support large update log before 2.7.55\" &&\n\t\treturn 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal fail_index=0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds1\n\n\t# OBD_FAIL_SPLIT_UPDATE_REC       0x1702\n\tdo_facet mds1 \"lctl set_param fail_loc=0x80001702\"\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\n\tfail mds1\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir ||\n\t\terror \"stried_dir does not exists\"\n}\nrun_test 116a \"large update log master MDT recovery\"\n\ntest_116b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Do not support large update log before 2.7.55\" &&\n\t\treturn 0\n\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal fail_index=0\n\n\tmkdir -p $DIR/$tdir\n\treplay_barrier mds2\n\n\t# OBD_FAIL_SPLIT_UPDATE_REC       0x1702\n\tdo_facet mds2 \"lctl set_param fail_loc=0x80001702\"\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\n\tfail mds2\n\t$CHECKSTAT -t dir $DIR/$tdir/striped_dir ||\n\t\terror \"stried_dir does not exists\"\n}\nrun_test 116b \"large update log slave MDT recovery\"\n\ntest_117() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\tlocal index\n\tlocal mds_indexs\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/remote_dir\n\t$LFS setdirstripe -i1 -c$MDSCOUNT $DIR/$tdir/remote_dir_1\n\tsleep 2\n\n\t# Let's set rdonly on all MDTs, so client will send\n\t# replay requests on all MDTs and replay these requests\n\t# at the same time. This test will verify the recovery\n\t# will not be deadlock in this case, LU-7531.\n\tfor ((index = 0; index < $((MDSCOUNT)); index++)); do\n\t\treplay_barrier mds$((index + 1))\n\t\tif [ -z $mds_indexs ]; then\n\t\t\tmds_indexs=\"${mds_indexs}mds$((index+1))\"\n\t\telse\n\t\t\tmds_indexs=\"${mds_indexs},mds$((index+1))\"\n\t\tfi\n\tdone\n\n\trm -rf $DIR/$tdir/remote_dir\n\trm -rf $DIR/$tdir/remote_dir_1\n\n\tfail $mds_indexs\n\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 117 \"DNE: cross MDT unlink, fail MDT1 and MDT2\"\n\ntest_118() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.64) ] &&\n\t\tskip \"Do not support large update log before 2.7.64\" &&\n\t\treturn 0\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir ||\n\t\terror \"setdirstripe fails\"\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir1 ||\n\t\terror \"setdirstripe fails 1\"\n\trm -rf $DIR/$tdir/striped_dir* || error \"rmdir fails\"\n\n\t# OBD_FAIL_INVALIDATE_UPDATE       0x1705\n\tdo_facet mds1 \"lctl set_param fail_loc=0x1705\"\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir1\n\tdo_facet mds1 \"lctl set_param fail_loc=0x0\"\n\n\treplay_barrier mds1\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir1\n\tfail mds1\n\n\ttrue\n}\nrun_test 118 \"invalidate osp update will not cause update log corruption\"\n\ntest_119() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.64) ] &&\n\t\tskip \"Do not support large update log before 2.7.64\" &&\n\t\treturn 0\n\tlocal stripe_count\n\tlocal hard_timeout=$(do_facet mds1 \\\n\t\t\"lctl get_param -n mdt.$FSNAME-MDT0000.recovery_time_hard\")\n\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal time_min=$(recovery_time_min)\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $DIR/$tdir/tmp\n\trmdir $DIR/$tdir/tmp\n\n\treplay_barrier mds1\n\tmkdir $DIR/$tdir/dir_1\n\tfor ((i = 0; i < 20; i++)); do\n\t\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/stripe_dir-$i\n\tdone\n\n\tstop mds1\n\tchange_active mds1\n\twait_for_facet mds1\n\n\t#define OBD_FAIL_TGT_REPLAY_DELAY  0x714\n\tdo_facet mds1 $LCTL set_param fail_loc=0x80000714\n\t#sleep (timeout + 5), so mds will evict the client exports,\n\t#but DNE update recovery will keep going.\n\tdo_facet mds1 $LCTL set_param fail_val=$((time_min + 5))\n\n\tmount_facet mds1 \"-o recovery_time_hard=$time_min\"\n\n\twait_clients_import_state \"$clients\" mds1 FULL\n\n\tclients_up || clients_up || error \"failover df: $?\"\n\n\t#revert back the hard timeout\n\tdo_facet mds1 $LCTL set_param \\\n\t\tmdt.$FSNAME-MDT0000.recovery_time_hard=$hard_timeout\n\n\tfor ((i = 0; i < 20; i++)); do\n\t\tstripe_count=$($LFS getdirstripe -c $DIR/$tdir/stripe_dir-$i)\n\t\t[ $stripe_count == 2 ] || {\n\t\t\terror \"stripe_dir-$i creation replay fails\"\n\t\t\tbreak\n\t\t}\n\tdone\n}\nrun_test 119 \"timeout of normal replay does not cause DNE replay fails  \"\n\ntest_120() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.64) ] &&\n\t\tskip \"Do not support large update log before 2.7.64\" &&\n\t\treturn 0\n\n\tmkdir $DIR/$tdir\n\treplay_barrier_nosync mds1\n\tfor ((i = 0; i < 20; i++)); do\n\t\tmkdir $DIR/$tdir/dir-$i || {\n\t\t\terror \"create dir-$i fails\"\n\t\t\tbreak\n\t\t}\n\t\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/stripe_dir-$i || {\n\t\t\terror \"create stripe_dir-$i fails\"\n\t\t\tbreak\n\t\t}\n\tdone\n\n\tfail_abort mds1\n\n\tfor ((i = 0; i < 20; i++)); do\n\t\t[ ! -e \"$DIR/$tdir/dir-$i\" ] || {\n\t\t\terror \"dir-$i still exists\"\n\t\t\tbreak\n\t\t}\n\t\t[ ! -e \"$DIR/$tdir/stripe_dir-$i\" ] || {\n\t\t\terror \"stripe_dir-$i still exists\"\n\t\t\tbreak\n\t\t}\n\tdone\n}\nrun_test 120 \"DNE fail abort should stop both normal and DNE replay\"\n\ntest_121() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.90) ] &&\n\t\tskip \"Don't support it before 2.11\" &&\n\t\treturn 0\n\n\tlocal at_max_saved=$(at_max_get mds)\n\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\tcancel_lru_locks mdc\n\n\tmultiop_bg_pause $DIR/$tfile s_s || error \"multiop $DIR/$tfile failed\"\n\tmpid=$!\n\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"0\"\n\n\tstop mds1\n\tchange_active mds1\n\twait_for_facet mds1\n\n\t#define OBD_FAIL_TGT_RECOVERY_REQ_RACE\t0x721\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x721 fail_val=0\"\n\tat_max_set 0 mds\n\n\tmount_facet mds1\n\twait_clients_import_state \"$clients\" mds1 FULL\n\tclients_up || clients_up || error \"failover df: $?\"\n\n\tkill -USR1 $mpid\n\twait $mpid || error \"multiop_bg_pause pid failed\"\n\n\tdo_facet $SINGLEMDS \"lctl set_param fail_loc=0x0\"\n\tlctl set_param -n ldlm.cancel_unused_locks_before_replay \"1\"\n\tat_max_set $at_max_saved mds\n\trm -f $DIR/$tfile\n}\nrun_test 121 \"lock replay timed out and race\"\n\ntest_130a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.90) ] &&\n\t\tskip \"Do not support Data-on-MDT before 2.11\"\n\n\treplay_barrier $SINGLEMDS\n\t$LFS setstripe -E 1M -L mdt -E EOF -c 2 $DIR/$tfile\n\tfail $SINGLEMDS\n\n\t[ $($LFS getstripe -L $DIR/$tfile) == \"mdt\" ] ||\n\t\terror \"Fail to replay DoM file creation\"\n}\nrun_test 130a \"DoM file create (setstripe) replay\"\n\ntest_130b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.90) ] &&\n\t\tskip \"Do not support Data-on-MDT before 2.11\"\n\n\tmkdir $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt -E EOF -c 2 $DIR/$tdir\n\treplay_barrier $SINGLEMDS\n\ttouch $DIR/$tdir/$tfile\n\tfail $SINGLEMDS\n\n\t[ $($LFS getstripe -L $DIR/$tdir/$tfile) == \"mdt\" ] ||\n\t\terror \"Fail to replay DoM file creation\"\n}\nrun_test 130b \"DoM file create (inherited) replay\"\n\ntest_131a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.90) ] &&\n\t\tskip \"Do not support Data-on-MDT before 2.11\"\n\n\t$LFS setstripe -E 1M -L mdt -E EOF -c 2 $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\techo \"dom_data\" | dd of=$DIR/$tfile bs=8 count=1\n\t# lock is not canceled and will be replayed\n\tfail $SINGLEMDS\n\n\t[ $(cat $DIR/$tfile) == \"dom_data\" ] ||\n\t\terror \"Wrong file content after failover\"\n}\nrun_test 131a \"DoM file write lock replay\"\n\ntest_131b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.90) ] &&\n\t\tskip \"Do not support Data-on-MDT before 2.11\"\n\n\t$LFS setstripe -E 1M -L mdt -E EOF -c 2 $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\techo \"dom_data\" | dd of=$DIR/$tfile bs=8 count=1\n\tcancel_lru_locks mdc\n\n\tfail $SINGLEMDS\n\n\t[ $(cat $DIR/$tfile) == \"dom_data\" ] ||\n\t\terror \"Wrong file content after failover\"\n}\nrun_test 131b \"DoM file write replay\"\n\ntest_132a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.12.0) ] &&\n\t\tskip \"Need MDS version 2.12.0 or later\"\n\n\t$LFS setstripe -E 1M -c 1 -E EOF -c 2 $DIR/$tfile\n\treplay_barrier $SINGLEMDS\n\t# write over the first component size cause next component instantiation\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1M count=1 seek=1 ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\tlfs getstripe $DIR/$tfile\n\n\tcksum=$(md5sum $DIR/$tfile | awk '{print $1}')\n\t$LFS getstripe -I2 $DIR/$tfile | grep -q lmm_objects ||\n\t\terror \"Component #1 was not instantiated\"\n\n\tfail $SINGLEMDS\n\n\tlfs getstripe $DIR/$tfile\n\t$LFS getstripe -I2 $DIR/$tfile | grep -q lmm_objects ||\n\t\terror \"Component #1 instantiation was not replayed\"\n\tcksum2=$(md5sum $DIR/$tfile | awk '{print $1}')\n\tif [ $cksum != $cksum2 ] ; then\n\t\terror_noexit \"New cksum $cksum2 does not match original $cksum\"\n\tfi\n}\nrun_test 132a \"PFL new component instantiate replay\"\n\ntest_133() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\t([ $FAILURE_MODE == \"HARD\" ] &&\n\t\t[ \"$(facet_host mds1)\" == \"$(facet_host mds2)\" ]) &&\n\t\tskip \"MDTs needs to be on diff hosts for HARD fail mode\" &&\n\t\treturn 0\n\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\t$LFS mkdir -i 1 $remote_dir\n\n\tumount $MOUNT\n\tdo_facet mds2 $LCTL set_param seq.srv*MDT0001.space=clear\n\n\tzconf_mount $(hostname) $MOUNT\n\tclient_up || return 1\n\n\t#define OBD_FAIL_MDS_ALL_REQUEST_NET     0x123\n\t# SEQ_QUERY                       = 700\n\tdo_facet mds1 $LCTL set_param fail_val=700 fail_loc=0x80000123\n\tcp /etc/hosts $remote_dir/file &\n\tlocal pid=$!\n\tsleep 1\n\n\tfail_nodf mds1\n\n\twait $pid || error \"cp failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n\n\treturn 0\n}\nrun_test 133 \"check resend of ongoing requests for lwp during failover\"\n\ntest_134() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return 0\n\n\tpool_add pool_134\n\tpool_add_targets pool_134 1 1\n\n\tmkdir -p $DIR/$tdir/{A,B}\n\t$LFS setstripe -p pool_134 $DIR/$tdir/A\n\t$LFS setstripe -E EOF -p pool_134 $DIR/$tdir/B\n\n\treplay_barrier mds1\n\n\ttouch $DIR/$tdir/A/$tfile || error \"touch non-pfl file failed\"\n\ttouch $DIR/$tdir/B/$tfile || error \"touch pfl failed\"\n\n\tfail mds1\n\n\t[ -f $DIR/$tdir/A/$tfile ] || error \"non-pfl file does not exist\"\n\t[ -f $DIR/$tdir/B/$tfile ] || error \"pfl file does not exist\"\n}\nrun_test 134 \"replay creation of a file created in a pool\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 4916}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nMOUNT_2=${MOUNT_2:-\"yes\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nremote_mds_nodsh && log \"SKIP: remote MDS with nodsh\" && exit 0\n\nALWAYS_EXCEPT=\" $REPLAY_VBR_EXCEPT\"\n\n#                                  ~6  (min)\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"7 \"\n\nbuild_test_filter\n\ncheck_and_setup_lustre\n\nassert_DIR\nrm -rf $DIR/[df][0-9]*\n\n[ \"$DAEMONFILE\" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE\n\n# if there is no CLIENT1 defined, some tests can be ran on localhost\nCLIENT1=${CLIENT1:-$HOSTNAME}\n# if CLIENT2 doesn't exist then use CLIENT1 instead\n# All tests should use CLIENT2 with MOUNT2 only therefore it will work if\n# $CLIENT2 == CLIENT1\n# Exception is the test which need two separate nodes\nCLIENT2=${CLIENT2:-$CLIENT1}\n\nis_mounted $MOUNT2 || error \"MOUNT2 is not mounted\"\n\n#\n# get_version(): Gets the version of an object on servers\n# Parameter1: Client/Machine Name\n# Parameter2: File Path\n# Returns: Objectversion Or -1 if getobjversion fails.\n#\nget_version() {\n\tlocal var=${SINGLEMDS}_svc\n\tlocal client=$1\n\tlocal file=$2\n\tlocal fid=$(do_node $client $LFS path2fid $file)\n\tlocal objver=$(do_facet $SINGLEMDS $LCTL --device ${!var} \\\n\t\tgetobjversion \\\\\\\"$fid\\\\\\\")\n\n\t[[ -z $objver ]] && objver=-1\n\techo $objver\n}\n\n#\n# chk_get_version(): Wrapper to get_version().\n# Parameter1: Client/Machine Name\n# Parameter2: File Path\n# Returns: Objectversion Or Exit with error in case objver is -1.\n#\nchk_get_version() {\n\tlocal objver=$(get_version $1 $2)\n\n\t[[ \"$objver\" == \"-1\" ]] && error \"object version is empty.\"\n\techo $objver\n}\n\n\n#save COS setting\ncos_param_file=$TMP/rvbr-cos-params\nsave_lustre_params $(get_facets MDS) \"mdt.*.commit_on_sharing\" > $cos_param_file\n\ntest_0a() {\n\tlocal ver=$(get_version $CLIENT1 $DIR/$tdir/1a)\n\n\t[[ \"$ver\" == \"-1\" ]] && return 0\n\treturn 1\n}\nrun_test 0a \"getversion for non existent file shouldn't cause kernel panic\"\n\ntest_0b() {\n        local var=${SINGLEMDS}_svc\n        local fid\n        local file=$DIR/$tdir/f\n\n        do_node $CLIENT1 mkdir -p $DIR/$tdir/\n        do_node $CLIENT1 touch $file\n        fid=$(do_node $CLIENT1 $LFS path2fid $file)\n        do_node $CLIENT1 rm -rf $file\n        do_facet $SINGLEMDS $LCTL --device ${!var} getobjversion \\\\\\\"$fid\\\\\\\" || true\n}\nrun_test 0b \"getversion for non existent fid shouldn't cause kernel panic\"\n\n# test set #1: OPEN\ntest_1a() { # former test_0a\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 openfile -f O_RDWR $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tif (($pre != $post)); then\n\t\terror \"version changed unexpectedly: pre $pre, post $post\"\n\tfi\n}\nrun_test 1a \"open and close do not change versions\"\n\ntest_1b() { # former test_0b\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n    do_node $CLIENT1 mkdir -p -m 755 $MOUNT/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2/$tdir\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT $MOUNT/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -a $DIR/$tdir/$tfile; then\n\t\terror_and_remount \"open succeeded unexpectedly\"\n    fi\n}\nrun_test 1b \"open (O_CREAT) checks version of parent\"\n\ntest_1c() { # former test_0c\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $DIR/$tdir/$tfile\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 0777 $MOUNT2/$tdir\n    do_node $CLIENT2 chmod 0666 $MOUNT2/$tdir/$tfile\n    rmultiop_start $CLIENT1 $DIR/$tdir/$tfile o_c\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_up $CLIENT1 || error \"$CLIENT1 evicted\"\n    rmultiop_stop $CLIENT1 || error \"close failed\"\n}\nrun_test 1c \"open (non O_CREAT) does not checks versions\"\n\n# test set #2: CREAT (not open)\n# - version of parent is not changed but checked\n# - pre-version should be -1\n# - post-version should be valid\ntest_2a() {  # extended former test_0d\n\tlocal pre\n\tlocal post\n\n\t# fifo\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 mkfifo $DIR/$tfile-fifo\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version was changed: pre $pre, post $post\"\n\tfi\n\t# mkdir\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 mkdir $DIR/$tfile-dir\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version was changed: pre $pre, post $post\"\n\tfi\n\tdo_node $CLIENT1 rmdir $DIR/$tfile-dir\n\n\t# mknod\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 mkfifo $DIR/$tfile-nod\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version was changed: pre $pre, post $post\"\n\tfi\n\t# symlink\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 mkfifo $DIR/$tfile-symlink\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version was changed: pre $pre, post $post\"\n\tfi\n\t# remote directory\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t#create remote dir\n\t\tlocal MDT_IDX=1\n\t\tpre=$(chk_get_version $CLIENT1 $DIR)\n\t\tdo_node $CLIENT1 $LFS mkdir -i $MDT_IDX $DIR/$tfile-remote_dir\n\t\tpost=$(chk_get_version $CLIENT1 $DIR)\n\t\tif (($pre != $post)); then\n\t\t\terror \"version was changed: pre $pre, post $post\"\n\t\tfi\n\tfi\n\tdo_node $CLIENT1 rm -rf $DIR/$tfile-*\n\n}\nrun_test 2a \"create operations doesn't change version of parent\"\n\ntest_2b() { # former test_0e\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2/$tdir\n    do_node $CLIENT1 mkfifo $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -a $DIR/$tdir/$tfile; then\n\t\terror_and_remount \"create succeeded unexpectedly\"\n    fi\n}\nrun_test 2b \"create checks version of parent\"\n\ntest_3a() { # former test_0f\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $DIR/$tfile\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 rm $DIR/$tfile\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version was changed: pre $pre, post $post\"\n\tfi\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t#create remote dir\n\t\tlocal MDT_IDX=1\n\t\tdo_node $CLIENT1 $LFS mkdir -i $MDT_IDX $DIR/$tfile-remote_dir\n\t\tpre=$(chk_get_version $CLIENT1 $DIR)\n\t\tdo_node $CLIENT1 rmdir $DIR/$tfile-remote_dir\n\t\tpost=$(chk_get_version $CLIENT1 $DIR)\n\t\tif (($pre != $post)); then\n\t\t\terror \"version was changed: pre $pre, post $post\"\n\t\tfi\n\tfi\n}\nrun_test 3a \"unlink doesn't change version of parent\"\n\ntest_3b() { # former test_0g\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n    do_node $CLIENT1 mcreate $DIR/$tdir/$tfile\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2/$tdir\n    do_node $CLIENT1 rm $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if do_node $CLIENT1 $CHECKSTAT -a $DIR/$tdir/$tfile; then\n\t\terror_and_remount \"unlink succeeded unexpectedly\"\n    fi\n}\nrun_test 3b \"unlink checks version of parent\"\n\ntest_4a() { # former test_0h\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 chown $RUNAS_ID:$RUNAS_GID $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tif (($pre == $post)); then\n\t\terror \"version not changed: pre $pre, post $post\"\n\tfi\n}\nrun_test 4a \"setattr of UID changes versions\"\n\ntest_4b() { # former test_0i\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 chgrp $RUNAS_GID $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tif (($pre == $post)); then\n\t\terror \"version not changed: pre $pre, post $post\"\n\tfi\n}\nrun_test 4b \"setattr of GID changes versions\"\n\ntest_4c() { # former test_0j\n    local file=$DIR/$tfile\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $file\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chgrp $RUNAS_GID $MOUNT2/$tfile\n    do_node $CLIENT1 chown $RUNAS_ID:$RUNAS_GID $file\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -u \\\\\\#$UID $file; then\n\t\terror_and_remount \"setattr of UID succeeded unexpectedly\"\n    fi\n}\nrun_test 4c \"setattr of UID checks versions\"\n\ntest_4d() { # former test_0k\n    local file=$DIR/$tfile\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $file\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chown $RUNAS_ID:$RUNAS_GID $MOUNT2/$tfile\n    do_node $CLIENT1 chgrp $RUNAS_GID $file\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -g \\\\\\#$UID $file; then\n\t\terror_and_remount \"setattr of GID succeeded unexpectedly\"\n    fi\n}\nrun_test 4d \"setattr of GID checks versions\"\n\ntest_4e() { # former test_0l\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 chmod 666 $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tif (($pre == $post)); then\n\t\terror \"version not changed: pre $pre, post $post\"\n\tfi\n}\nrun_test 4e \"setattr of permission changes versions\"\n\ntest_4f() { # former test_0m\n    local file=$DIR/$tfile\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $file\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chgrp $RUNAS_GID $MOUNT2/$tfile\n    do_node $CLIENT1 chmod 666 $file\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -p 0644 $file; then\n\t\terror_and_remount \"setattr of permission succeeded unexpectedly\"\n    fi\n}\nrun_test 4f \"setattr of permission checks versions\"\n\ntest_4g() { # former test_0n\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 chattr +i $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 chattr -i $file\n\tif (($pre == $post)); then\n\t\terror \"version not changed: pre $pre, post $post\"\n\tfi\n}\nrun_test 4g \"setattr of flags changes versions\"\n\ncheckattr() {\n    local client=$1\n    local attr=$2\n    local file=$3\n    local rc\n\n    if ((${#attr} != 1)); then\n        error \"checking multiple attributes not implemented yet\"\n    fi\n    do_node $client lsattr $file | cut -d ' ' -f 1 | grep -q $attr\n}\n\ntest_4h() { # former test_0o\n    local file=$DIR/$tfile\n    local rc\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $file\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 666 $MOUNT2/$tfile\n    do_node $CLIENT1 chattr +i $file\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    checkattr $CLIENT1 i $file\n    rc=$?\n    do_node $CLIENT1 chattr -i $file\n    if [ $rc -eq 0 ]; then\n        error \"setattr of flags succeeded unexpectedly\"\n    fi\n}\nrun_test 4h \"setattr of flags checks versions\"\n\ntest_4i() { # former test_0p\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\tlocal ad_orig\n\tlocal var=${SINGLEMDS}_svc\n\n\tad_orig=$(do_facet $SINGLEMDS \"$LCTL get_param mdd.${!var}.atime_diff\")\n\tdo_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.atime_diff=0\"\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 touch $file\n\tpost=$(chk_get_version $CLIENT1 $file)\n\t#\n\t# We don't fail MDS in this test.  atime_diff shall be\n\t# restored to its original value.\n\t#\n\tdo_facet $SINGLEMDS \"$LCTL set_param $ad_orig\"\n\tif (($pre != $post)); then\n\t\terror \"version changed unexpectedly: pre $pre, post $post\"\n\tfi\n}\nrun_test 4i \"setattr of times does not change versions\"\n\ntest_4j() { # former test_0q\n\tlocal file=$DIR/$tfile\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $file\n\tpre=$(chk_get_version $CLIENT1 $file)\n\tdo_node $CLIENT1 $TRUNCATE $file 1\n\tpost=$(chk_get_version $CLIENT1 $file)\n\tif (($pre != $post)); then\n\t\terror \"version changed unexpectedly: pre $pre, post $post\"\n\tfi\n}\nrun_test 4j \"setattr of size does not change versions\"\n\ntest_4k() { # former test_0r\n    local file=$DIR/$tfile\n    local mtime_pre\n    local mtime_post\n    local mtime\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.atime_diff=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $file\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 666 $MOUNT2/$tfile\n    do_node $CLIENT1 $TRUNCATE $file 1\n    sleep 1\n    mtime_pre=$(do_node $CLIENT1 stat --format=%Y $file)\n    do_node $CLIENT1 touch $file\n    sleep 1 # avoid stat caching\n    mtime_post=$(do_node $CLIENT1 stat --format=%Y $file)\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_up $CLIENT1 || error \"$CLIENT1 evicted\"\n    if (($mtime_pre >= $mtime_post)); then\n        error \"time not changed: pre $mtime_pre, post $mtime_post\"\n    fi\n    if ! do_node $CLIENT1 $CHECKSTAT -s 1 $file; then\n\t\terror_and_remount \"setattr of size failed\"\n    fi\n    mtime=$(do_node $CLIENT1 stat --format=%Y $file)\n    if (($mtime != $mtime_post)); then\n        error \"setattr of times failed: expected $mtime_post, got $mtime\"\n    fi\n}\nrun_test 4k \"setattr of times and size does not check versions\"\n\ntest_5a() { # former test_0s\n\tlocal pre\n\tlocal post\n\tlocal tp_pre\n\tlocal tp_post\n\n\tdo_node $CLIENT1 mcreate $DIR/$tfile\n\tdo_node $CLIENT1 mkdir -p $DIR/$tdir\n\tpre=$(chk_get_version $CLIENT1 $DIR/$tfile)\n\ttp_pre=$(chk_get_version $CLIENT1 $DIR/$tdir)\n\tdo_node $CLIENT1 link $DIR/$tfile $DIR/$tdir/$tfile\n\tpost=$(chk_get_version $CLIENT1 $DIR/$tfile)\n\ttp_post=$(chk_get_version $CLIENT1 $DIR/$tdir)\n\tif (($pre == $post)); then\n\t\terror \"version of source not changed: pre $pre, post $post\"\n\tfi\n\tif (($tp_pre != $tp_post)); then\n\t\terror \"version of target parent was changed:\"\\\n\t\t\t\"pre $tp_pre, post $tp_post\"\n\tfi\n}\nrun_test 5a \"link changes versions of source but not target parent\"\n\ntest_5b() { # former test_0t\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $DIR/$tfile\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2/$tdir\n    do_node $CLIENT1 link $DIR/$tfile $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -a $DIR/$tdir/$tfile; then\n\t\terror_and_remount \"link should fail\"\n    fi\n}\nrun_test 5b \"link checks version of target parent\"\n\ntest_5c() { # former test_0u\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $DIR/$tfile\n    do_node $CLIENT1 mkdir -p $DIR/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 666 $MOUNT2/$tfile\n    do_node $CLIENT1 link $DIR/$tfile $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if ! do_node $CLIENT1 $CHECKSTAT -a $DIR/$tdir/$tfile; then\n\t\terror_and_remount \"link should fail\"\n    fi\n}\nrun_test 5c \"link checks version of source\"\n\ntest_6a() { # former test_0v\n\tlocal sp_pre\n\tlocal tp_pre\n\tlocal sp_post\n\tlocal tp_post\n\n\tdo_node $CLIENT1 mcreate $DIR/$tfile\n\tdo_node $CLIENT1 mkdir -p $DIR/$tdir\n\tsp_pre=$(chk_get_version $CLIENT1 $DIR)\n\ttp_pre=$(chk_get_version $CLIENT1 $DIR/$tdir)\n\tdo_node $CLIENT1 mv $DIR/$tfile $DIR/$tdir/$tfile\n\tsp_post=$(chk_get_version $CLIENT1 $DIR)\n\ttp_post=$(chk_get_version $CLIENT1 $DIR/$tdir)\n\tif (($sp_pre != $sp_post)); then\n\t\terror \"version of source parent was changed:\" \\\n\t\t\t\"pre $sp_pre, post $sp_post\"\n\tfi\n\tif (($tp_pre != $tp_post)); then\n\t\terror \"version of target parent was changed:\" \\\n\t\t\t\"pre $tp_pre, post $tp_post\"\n\tfi\n}\nrun_test 6a \"rename doesn't change versions of source parent and target parent\"\n\ntest_6b() { # former test_0w\n\tlocal pre\n\tlocal post\n\n\tdo_node $CLIENT1 mcreate $DIR/$tfile\n\tpre=$(chk_get_version $CLIENT1 $DIR)\n\tdo_node $CLIENT1 mv $DIR/$tfile $DIR/$tfile-new\n\tpost=$(chk_get_version $CLIENT1 $DIR)\n\tif (($pre != $post)); then\n\t\terror \"version of parent was changed: pre $pre, post $post\"\n\tfi\n}\nrun_test 6b \"rename within same dir doesn't change version of parent\"\n\ntest_6c() { # former test_0x\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $DIR/$tfile\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2\n    do_node $CLIENT1 mv $DIR/$tfile $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if do_node $CLIENT1 $CHECKSTAT -a $DIR/$tfile; then\n\t\terror_and_remount \"rename should fail\"\n    fi\n}\nrun_test 6c \"rename checks version of source parent\"\n\ntest_6d() { # former test_0y\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $DIR/$tfile\n    do_node $CLIENT1 mkdir -p -m 755 $DIR/$tdir\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 chmod 777 $MOUNT2/$tdir\n    do_node $CLIENT1 mv $DIR/$tfile $DIR/$tdir/$tfile\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n\n    client_evicted $CLIENT1 || error \"$CLIENT1 not evicted\"\n    if do_node $CLIENT1 $CHECKSTAT -a $DIR/$tfile; then\n\t\terror_and_remount \"rename should fail\"\n    fi\n}\nrun_test 6d \"rename checks version of target parent\"\n\n# pdirops tests, bug 18143\ncycle=0\ntest_7_cycle() {\n    local first=$1\n    local lost=$2\n    local last=$3\n    local rc=0\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n    cycle=$((cycle + 1))\n    local cname=$TESTNAME.$cycle\n\n    echo \"start cycle: $cname\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mkdir -p $DIR/$tdir\n    replay_barrier $SINGLEMDS\n    # first operation\n    echo \"$cname first: $first\"\n    do_node $CLIENT1 $first || error \"$cname: Cannot do first operation\"\n    # client2 operations that will be lost\n    echo \"$cname lost: $lost\"\n    do_node $CLIENT2 $lost || error \"$cname: Cannot do 'lost' operations\"\n    # second operation\n    echo \"$cname last: $last\"\n    do_node $CLIENT1 $last || error \"$cname: Cannot do last operation\"\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n    # should fail as conflict expected\n    client_evicted $CLIENT1 || rc=1\n\n\twait_recovery_complete $SINGLEMDS\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\n\trm -rf $DIR/$tdir\n\treturn $rc\n}\n\ntest_7a() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0\"\n    last=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7a.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0\"\n    last=\"mkdir $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7a.2 failed\"\n\n    first=\"mkdir $DIR/$tdir/$tfile-0\"\n    lost=\"mv $MOUNT2/$tdir/$tfile-0 $MOUNT2/$tdir/$tfile-1\"\n    last=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7a.3 failed\"\n    return 0\n}\nrun_test 7a \"create, {lost}, create\"\n\ntest_7b() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0; createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7b.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"touch $MOUNT2/$tdir/$tfile; mv $MOUNT2/$tdir/$tfile $MOUNT2/$tdir/$tfile-0\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7b.2 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0; mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"rmdir $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7b.3 failed\"\n    return 0\n}\nrun_test 7b \"create, {lost}, unlink\"\n\ntest_7c() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0; createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7c.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0; mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7c.2 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; mkdir $DIR/$tdir/$tfile-1-0\"\n    lost=\"rmdir $MOUNT2/$tdir/$tfile-1-0; createmany -o $MOUNT2/$tdir/$tfile-1- 1\"\n    last=\"mv $DIR/$tdir/$tfile-1-0 $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7c.3 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    lost=\"mv $MOUNT2/$tdir/$tfile-0 $MOUNT2/$tdir/$tfile\"\n    last=\"mv $DIR/$tdir/$tfile $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7c.4 failed\"\n    return 0\n}\nrun_test 7c \"create, {lost}, rename\"\n\ntest_7d() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; rm $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1; rm $MOUNT2/$tdir/$tfile-0\"\n    last=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" && error \"Test 7d.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; rm $DIR/$tdir/$tfile-0\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile-0; rmdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"mkdir $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" && error \"Test 7d.2 failed\"\n\n    first=\"mkdir $DIR/$tdir/$tfile-0; rmdir $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1; mv $MOUNT2/$tdir/$tfile-0 $MOUNT2/$tdir/$tfile-1\"\n    last=\"createmany -o $DIR/$tdir/$tfile- 1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" && error \"Test 7d.3 failed\"\n    return 0\n}\nrun_test 7d \"unlink, {lost}, create\"\n\ntest_7e() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; rm $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1; rm $MOUNT2/$tdir/$tfile-0;createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7e.1 failed\"\n\n    first=\"mkdir $DIR/$tdir/$tfile-0; rmdir $DIR/$tdir/$tfile-0\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile-0; rmdir $MOUNT2/$tdir/$tfile-0; mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"rmdir $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7e.2 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; rm $DIR/$tdir/$tfile-0\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"rmdir $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7e.3 failed\"\n\n    first=\"mkdir $DIR/$tdir/$tfile-0; rmdir $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7e.4 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; rm $DIR/$tdir/$tfile-0\"\n    lost=\"mv $MOUNT2/$tdir/$tfile-1 $MOUNT2/$tdir/$tfile-0\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7e.5 failed\"\n    return 0\n}\nrun_test 7e \"unlink, {lost}, unlink\"\n\ntest_7f() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; rm $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7f.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; rm $DIR/$tdir/$tfile-0\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7f.2 failed\"\n\n    first=\"mkdir $DIR/$tdir/$tfile; createmany -o $DIR/$tdir/$tfile- 1; rmdir $DIR/$tdir/$tfile\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7f.3 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; rm $DIR/$tdir/$tfile-0\"\n    lost=\"mv $MOUNT2/$tdir/$tfile-1 $MOUNT2/$tdir/$tfile-0\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7f.4 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; rm $DIR/$tdir/$tfile-0\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7f.5 failed\"\n    return 0\n}\nrun_test 7f \"unlink, {lost}, rename\"\n\ntest_7g() {\n\tfirst=\"createmany -o $DIR/$tdir/$tfile- 1; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n\tlost=\"mkdir $MOUNT2/$tdir/$tfile-0;rmdir $MOUNT2/$tdir/$tfile-0\"\n\tlast=\"createmany -o $DIR/$tdir/$tfile- 1\"\n\ttest_7_cycle \"$first\" \"$lost\" \"$last\" && error \"Test 7g.1 failed\"\n\n\tfirst=\"createmany -o $DIR/$tdir/$tfile- 2; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n\tlost=\"createmany -o $MOUNT2/$tdir/$tfile- 1; rm $MOUNT2/$tdir/$tfile-0\"\n\tlast=\"mkdir $DIR/$tdir/$tfile-0\"\n\ttest_7_cycle \"$first\" \"$lost\" \"$last\" && error \"Test 7g.2 failed\"\n\n\tfirst=\"createmany -o $DIR/$tdir/$tfile- 1; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile\"\n\tlost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n\tlast=\"link $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n\tif [ \"$MDS1_VERSION\" -lt $(version_code 2.5.1) ]; then\n\t\ttest_7_cycle \"$first\" \"$lost\" \"$last\" ||\n\t\t\terror \"Test 7g.3 failed\"\n\telse #LU-4442 LU-3528\n\t\ttest_7_cycle \"$first\" \"$lost\" \"$last\" &&\n\t\t\terror \"Test 7g.3 failed\"\n\tfi\n    return 0\n}\nrun_test 7g \"rename, {lost}, create\"\n\ntest_7h() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7h.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-0; createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"rm $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7h.2 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; mkdir  $DIR/$tdir/$tfile; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile\"\n    lost=\"rm $MOUNT2/$tdir/$tfile/$tfile-0\"\n    last=\"rmdir $DIR/$tdir/$tfile\"\n    #test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7h.3 failed\"\n    return 0\n}\nrun_test 7h \"rename, {lost}, unlink\"\n\ntest_7i() {\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    lost=\"createmany -o $MOUNT2/$tdir/$tfile- 1\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7i.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 1; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-1\"\n    lost=\"mkdir $MOUNT2/$tdir/$tfile-0\"\n    last=\"mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7i.1 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 3; mv $DIR/$tdir/$tfile-1 $DIR/$tdir/$tfile-0\"\n    lost=\"mv $MOUNT2/$tdir/$tfile-2 $MOUNT2/$tdir/$tfile-0\"\n    last=\"mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile-2\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7i.3 failed\"\n\n    first=\"createmany -o $DIR/$tdir/$tfile- 2; mv $DIR/$tdir/$tfile-0 $DIR/$tdir/$tfile\"\n    lost=\"rm $MOUNT2/$tdir/$tfile-1\"\n    last=\"mv $DIR/$tdir/$tfile $DIR/$tdir/$tfile-1\"\n    test_7_cycle \"$first\" \"$lost\" \"$last\" || error \"Test 7i.4 failed\"\n    return 0\n}\nrun_test 7i \"rename, {lost}, rename\"\n\n# test set #8: orphan handling bug 15392.\n# Unlink during recovery creates orphan always just in case some late open may\n# arrive. These orphans will be removed after recovery anyway.\n# Tests check that valid create,unlink,create sequence will work in this case\n# too but not fail on second create due to orphan found.\n\ntest_8a() {\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 mcreate $DIR/$tfile\n    do_node $CLIENT1 mkdir $DIR/$tfile-2\n    replay_barrier $SINGLEMDS\n    # missed replay from client2 will lead to recovery by versions\n    do_node $CLIENT2 touch $MOUNT2/$tfile-2/$tfile\n    do_node $CLIENT1 rm $DIR/$tfile || return 1\n    do_node $CLIENT1 touch $DIR/$tfile || return 2\n\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n    client_up $CLIENT1 || return 6\n\n    do_node $CLIENT1 rm $DIR/$tfile || error \"$tfile doesn't exists\"\n    return 0\n}\nrun_test 8a \"create | unlink, create shouldn't fail\"\n\ntest_8b() {\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 touch $DIR/$tfile\n    do_node $CLIENT1 mkdir $DIR/$tfile-2\n    replay_barrier $SINGLEMDS\n    # missed replay from client2 will lead to recovery by versions\n    do_node $CLIENT2 touch $MOUNT2/$tfile-2/$tfile\n    do_node $CLIENT1 rm -f $MOUNT1/$tfile || return 1\n    do_node $CLIENT1 mcreate $MOUNT1/$tfile || return 2\n\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n    client_up $CLIENT1 || return 6\n\n    do_node $CLIENT1 rm $MOUNT1/$tfile || error \"$tfile doesn't exists\"\n    return 0\n}\nrun_test 8b \"create | unlink, create shouldn't fail\"\n\ntest_8c() {\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT1 touch $DIR/$tfile\n    do_node $CLIENT1 mkdir $DIR/$tfile-2\n    replay_barrier $SINGLEMDS\n    # missed replay from client2 will lead to recovery by versions\n    do_node $CLIENT2 touch $MOUNT2/$tfile-2/$tfile\n    do_node $CLIENT1 rm -f $MOUNT1/$tfile || return 1\n    do_node $CLIENT1 mkdir $MOUNT1/$tfile || return 2\n\n    zconf_umount $CLIENT2 $MOUNT2\n    facet_failover $SINGLEMDS\n    client_up $CLIENT1 || return 6\n\n    do_node $CLIENT1 rmdir $MOUNT1/$tfile || error \"$tfile doesn't exists\"\n    return 0\n}\nrun_test 8c \"create | unlink, create shouldn't fail\"\n\n#\n# This test uses three Lustre clients on two hosts.\n#\n#   Lustre Client 1:    $CLIENT1:$MOUNT     ($DIR)\n#   Lustre Client 2:    $CLIENT2:$MOUNT2    ($DIR2)\n#   Lustre Client 3:    $CLIENT2:$MOUNT1    ($DIR1)\n#\ntest_10b() { # former test_2b\n\tlocal pre\n\tlocal post\n\tlocal var=${SINGLEMDS}_svc\n\n\t[ -n \"$CLIENTS\" ] || { skip \"Need two or more clients\" && exit 0; }\n\t[ $CLIENTCOUNT -ge 2 ] || \\\n\t\t{ skip \"Need two or more clients, have $CLIENTCOUNT\" && \\\n\t\t\texit 0; }\n\n\tdo_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n\tdo_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n\tzconf_mount $CLIENT1 $MOUNT\n\tzconf_mount $CLIENT2 $MOUNT1\n\tzconf_mount $CLIENT2 $MOUNT2\n\tdo_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $DIR/$tfile-a\n\tdo_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $DIR/$tfile-b\n\n\t#\n\t# Save an MDT transaction number before recovery.\n\t#\n\tdo_node $CLIENT1 touch $DIR1/$tfile\n\tpre=$(chk_get_version $CLIENT1 $DIR/$tfile)\n\n\t#\n\t# Comments on the replay sequence state the expected result\n\t# of each request.\n\t#\n\t#   \"R\"     Replayed.\n\t#   \"U\"     Unable to replay.\n\t#   \"J\"     Rejected.\n\t#\n\treplay_barrier $SINGLEMDS\n\tdo_node $CLIENT1 chmod 666 $DIR/$tfile-a            # R\n\tdo_node $CLIENT2 chmod 666 $DIR1/$tfile-b           # R\n\tdo_node $CLIENT2 chgrp $RUNAS_GID $DIR2/$tfile-a    # U\n\tdo_node $CLIENT1 chown $RUNAS_ID:$RUNAS_GID $DIR/$tfile-a      # J\n\tdo_node $CLIENT2 $TRUNCATE $DIR2/$tfile-b 1          # U\n\tdo_node $CLIENT2 chgrp $RUNAS_GID $DIR1/$tfile-b    # R\n\tdo_node $CLIENT1 chown $RUNAS_ID:$RUNAS_GID $DIR/$tfile-b      # R\n\tzconf_umount $CLIENT2 $MOUNT2\n\tfacet_failover $SINGLEMDS\n\n\tclient_evicted $CLIENT1 || error \"$CLIENT1:$MOUNT not evicted\"\n\tclient_up $CLIENT2 || error \"$CLIENT2:$MOUNT1 evicted\"\n\n\t#\n\t# Check the MDT epoch.  $post must be the first transaction\n\t# number assigned after recovery.\n\t#\n\tdo_node $CLIENT2 chmod 666 $DIR1/$tfile\n\tpost=$(chk_get_version $CLIENT2 $DIR1/$tfile)\n\tif (($(($pre >> 32)) == $((post >> 32)))); then\n\t\terror \"epoch not changed: pre $pre, post $post\"\n\tfi\n\n\tif (($(($post & 0x00000000ffffffff)) != 1)); then\n\t\terror \"transno should restart from one: got $post\"\n\tfi\n\n\tdo_node $CLIENT2 stat $DIR1/$tfile-a\n\tdo_node $CLIENT2 stat $DIR1/$tfile-b\n\n\tdo_node $CLIENT2 $CHECKSTAT -p 0666 -u \\\\\\#$UID -g \\\\\\#$UID \\\n\t\t$DIR1/$tfile-a || error \"$DIR/$tfile-a: unexpected state\"\n\tdo_node $CLIENT2 $CHECKSTAT -p 0666 -u \\\\\\#$RUNAS_ID -g \\\\\\#$RUNAS_GID \\\n\t\t$DIR1/$tfile-b || error \"$DIR/$tfile-b: unexpected state\"\n\n\tzconf_umount $CLIENT2 $MOUNT1\n}\nrun_test 10b \"3 clients: some, none, and all reqs replayed\"\n\n# test set #11: operations in single directory\ntest_11a() {\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    replay_barrier $SINGLEMDS\n\n    do_node $CLIENT1 createmany -o $DIR/$tfile-1- 100 &\n    PID=$!\n    do_node $CLIENT2 createmany -o $MOUNT2/$tfile-2- 100\n    zconf_umount $CLIENT2 $MOUNT2\n    wait $PID\n\n    facet_failover $SINGLEMDS\n    # recovery shouldn't fail due to missing client 2\n    client_up $CLIENT1 || return 1\n    # All files from client1 should have been replayed\n    do_node $CLIENT1 unlinkmany $DIR/$tfile-1- 100 || return 2\n\n    [ -e $DIR/$tdir/$tfile-2-0 ] && error \"$tfile-2-0 exists\"\n    return 0\n}\nrun_test 11a \"concurrent creates don't affect each other\"\n\ntest_11b() {\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT2 createmany -o $MOUNT2/$tfile-2- 100\n\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT1 createmany -o $DIR/$tfile-1- 100 &\n    PID=$!\n    do_node $CLIENT2 unlinkmany -o $MOUNT2/$tfile-2- 100\n    zconf_umount $CLIENT2 $MOUNT2\n    wait $PID\n\n    facet_failover $SINGLEMDS\n    # recovery shouldn't fail due to missing client 2\n    client_up $CLIENT1 || return 1\n    # All files from client1 should have been replayed\n    do_node $CLIENT1 unlinkmany $DIR/$tfile-1- 100 || return 2\n\n    [ -e $DIR/$tdir/$tfile-2-0 ] && error \"$tfile-2-0 exists\"\n    return 0\n}\nrun_test 11b \"concurrent creates and unlinks don't affect each other\"\n\n# test set #12: lock replay with VBR, bug 16356\ntest_12a() { # former test_2a\n    local var=${SINGLEMDS}_svc\n    zconf_mount $CLIENT2 $MOUNT2\n\n    do_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n    do_node $CLIENT2 mkdir -p $MOUNT2/$tdir\n    replay_barrier $SINGLEMDS\n    do_node $CLIENT2 mcreate $MOUNT2/$tdir/$tfile\n    do_node $CLIENT1 createmany -o $DIR/$tfile- 25\n    #client1 read data from client2 which will be lost\n    do_node $CLIENT1 $CHECKSTAT $DIR/$tdir/$tfile\n    do_node $CLIENT1 createmany -o $DIR/$tfile-3- 25\n    zconf_umount $CLIENT2 $MOUNT2\n\n    facet_failover $SINGLEMDS\n    # recovery shouldn't fail due to missing client 2\n    client_up $CLIENT1 || return 1\n\n    # All 50 files should have been replayed\n    do_node $CLIENT1 unlinkmany $DIR/$tfile- 25 || return 2\n    do_node $CLIENT1 unlinkmany $DIR/$tfile-3- 25 || return 3\n    do_node $CLIENT1 $CHECKSTAT $DIR/$tdir/$tfile && return 4\n\n    return 0\n}\nrun_test 12a \"lost data due to missed REMOTE client during replay\"\n\ntest_13() { # LU-8826\n\tlocal var=${SINGLEMDS}_svc\n\n\tif combined_mgs_mds ; then\n\t\tskip \"Needs separate MGS to enable IR\"\n\t\treturn 0\n\tfi\n\n\tdo_facet $SINGLEMDS \"$LCTL set_param mdd.${!var}.sync_permission=0\"\n\tdo_facet $SINGLEMDS \"$LCTL set_param mdt.${!var}.commit_on_sharing=0\"\n\n\tzconf_mount $CLIENT2 $MOUNT2\n\tdo_node $CLIENT1 openfile -f O_RDWR:O_CREAT -m 0644 $DIR/$tfile\n\n\t# set ir_timeout to a reasonable small value\n\tlocal ir_timeout=$(do_facet mgs $LCTL get_param -n mgs.*.ir_timeout)\n\tdo_facet mgs $LCTL set_param mgs.*.ir_timeout=5\n\t# make sure IR functional\n\tsleep 5\n\n\treplay_barrier $SINGLEMDS\n\tdo_node $CLIENT1 chmod 666 $DIR/$tfile\n\tdo_node $CLIENT2 chmod 777 $DIR2/$tfile\n\n\t# make sure client data of $CLIENT2:$MOUNT2 is remained\n\t# define OBD_FAIL_TGT_CLIENT_DEL\t0x718\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x718\n\tzconf_umount $CLIENT2 $MOUNT2\n\t# define OBD_FAIL_TGT_SLUGGISH_NET\t0x719\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x719\n\tfacet_failover $SINGLEMDS\n\n\tclient_up $CLIENT1 || error \"$CLIENT1 evicted\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tdo_facet mgs $LCTL set_param mgs.*.ir_timeout=$ir_timeout\n\n\tdo_node $CLIENT1 $CHECKSTAT -p 0666 $DIR/$tfile ||\n\t\terror \"$DIR/$tfile-a: unexpected state\"\n}\nrun_test 13 \"Shouldn't give up VBR easily on sluggish network\"\n\n#restore COS setting\nrestore_lustre_params < $cos_param_file\nrm -f $cos_param_file\n\n[ \"$CLIENTS\" ] && zconf_mount_clients $CLIENTS $DIR\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1212}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n\nif [ ! -f $LUSTRE/tests/rpc.sh ]; then\n\tLUSTRE=$(cd $(dirname $(which $0))/..; echo $PWD)\nfi\n\n. $LUSTRE/tests/test-framework.sh\nRPC_MODE=true init_test_env\n\n# Reset the trap on ERR set by the framework.  Noticing this failure is the\n# framework's job.\ntrap - ERR\n\nlog \"$HOSTNAME: executing $@\"\n# Execute the command\n\"$@\"\n", "num_lines": 19}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nPATH=$(dirname $0):$LUSTRE/utils:$PATH\nTMP=${TMP:-/tmp}\n\nset -x\nMGS=$($LCTL dl | awk '/mgs/ { print $4 }')\n[ -z \"$MGS\" ] && echo \"$0: SKIP: no MGS available, skipping llog test\" && exit 0\n\nload_module obdclass/llog_test || exit 1\n$LCTL modules > $TMP/ogdb-$(hostname)\necho \"NOW reload debugging syms..\"\n\nRC=0\n# Using ignore_errors will allow lctl to cleanup even if the test fails.\neval \"$LCTL <<-EOF || RC=2\n\tattach llog_test llt_name llt_uuid\n\tignore_errors\n\tsetup $MGS\n\tdevice llt_name\n\tcleanup\n\tdetach\nEOF\"\nrmmod -v llog_test || RC2=3\n[ $RC -eq 0 -a \"$RC2\" ] && RC=$RC2\n\nexit $RC\n", "num_lines": 33}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=${TMP:-/tmp}\n\nTESTLOG_PREFIX=${TESTLOG_PREFIX:-$TMP/recovery-mds-scale}\nTESTNAME=${TESTNAME:-\"\"}\n[ -n \"$TESTNAME\" ] && TESTLOG_PREFIX=$TESTLOG_PREFIX.$TESTNAME\n\nLOG=$TESTLOG_PREFIX.$(basename $0 .sh)_stdout.$(hostname -s).log\nDEBUGLOG=$(echo $LOG | sed 's/\\(.*\\)stdout/\\1debug/')\n\nmkdir -p ${LOG%/*}\n\nrm -f $LOG $DEBUGLOG\nexec 2>$DEBUGLOG\nset -x\n\n. $(dirname $0)/functions.sh\n\nassert_env MOUNT END_RUN_FILE LOAD_PID_FILE\n\ntrap signaled TERM\n\n# recovery-*-scale scripts use this to signal the client loads to die\necho $$ >$LOAD_PID_FILE\n\nTESTDIR=$MOUNT/d0.dbench-$(hostname)\n\nCONTINUE=true\n\nwhile [ ! -e \"$END_RUN_FILE\" ] && $CONTINUE; do\n\techoerr \"$(date +'%F %H:%M:%S'): dbench run starting\"\n\n\tmkdir -p $TESTDIR\n\n\tsync\n\trundbench -D $TESTDIR 2 1>$LOG &\n\tload_pid=$!\n\n\twait $load_pid\n\tif [ ${PIPESTATUS[0]} -eq 0 ]; then\n\t\techoerr \"$(date +'%F %H:%M:%S'): dbench succeeded\"\n\t\tcd $TMP\n\t\trm -rf $TESTDIR\n\t\techoerr \"$(date +'%F %H:%M:%S'): dbench run finished\"\n\telse\n\t\techoerr \"$(date +'%F %H:%M:%S'): dbench failed\"\n\t\tif [ -z \"$ERRORS_OK\" ]; then\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\tfi\n\n\t\tif [ $BREAK_ON_ERROR ]; then\n\t\t\t# break\n\t\t\tCONTINUE=false\n\t\tfi\n\tfi\ndone\n\nechoerr \"$(date +'%F %H:%M:%S'): dbench run exiting\"\n", "num_lines": 60}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=${TMP:-/tmp}\n\nTESTLOG_PREFIX=${TESTLOG_PREFIX:-$TMP/recovery-mds-scale}\nTESTNAME=${TESTNAME:-\"\"}\n[ -n \"$TESTNAME\" ] && TESTLOG_PREFIX=$TESTLOG_PREFIX.$TESTNAME\n\nLOG=$TESTLOG_PREFIX.$(basename $0 .sh)_stdout.$(hostname -s).log\nDEBUGLOG=$(echo $LOG | sed 's/\\(.*\\)stdout/\\1debug/')\n\nmkdir -p ${LOG%/*}\n\nrm -f $LOG $DEBUGLOG\nexec 2>$DEBUGLOG\nset -x\n\n. $(dirname $0)/functions.sh\n\nassert_env MOUNT END_RUN_FILE LOAD_PID_FILE LFS CLIENT_COUNT\n\ntrap signaled TERM\n\n# recovery-*-scale scripts use this to signal the client loads to die\necho $$ >$LOAD_PID_FILE\n\nTESTDIR=$MOUNT/d0.dd-$(hostname)\n\nCONTINUE=true\nwhile [ ! -e \"$END_RUN_FILE\" ] && $CONTINUE; do\n\techoerr \"$(date +'%F %H:%M:%S'): dd run starting\"\n\tmkdir -p $TESTDIR\n\t$LFS setstripe -c -1 $TESTDIR\n\tcd $TESTDIR\n\tsync\n\n\t# suppress dd xfer stat to workaround buggy coreutils/gettext\n\t# combination in RHEL5 and OEL5, see BZ 21264\n\tFREE_SPACE=$(df -P $TESTDIR | awk '/:/ { print $4 }')\n\tBLKS=$((FREE_SPACE * 9 / 40 / CLIENT_COUNT))\n\techoerr \"Total free disk space is $FREE_SPACE, 4k blocks to dd is $BLKS\"\n\n\tdf $TESTDIR || true\n\tdd bs=4k count=$BLKS status=noxfer if=/dev/zero of=$TESTDIR/dd-file \\\n\t\t\t\t\t\t\t\t1>$LOG\n\tif [ $? -eq 0 ]; then\n\t\techoerr \"$(date +'%F %H:%M:%S'): dd succeeded\"\n\t\tcd $TMP\n\t\trm -rf $TESTDIR\n\t\techoerr \"$(date +'%F %H:%M:%S'): dd run finished\"\n\telse\n\t\techoerr \"$(date +'%F %H:%M:%S'): dd failed\"\n\t\tif [ -z \"$ERRORS_OK\" ]; then\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\tfi\n\t\tif [ $BREAK_ON_ERROR ]; then\n\t\t\t# break\n\t\t\tCONTINUE=false\n\t\tfi\n\tfi\ndone\n\nechoerr \"$(date +'%F %H:%M:%S'): dd run exiting\"\n", "num_lines": 64}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=${TMP:-/tmp}\n\nTESTLOG_PREFIX=${TESTLOG_PREFIX:-$TMP/recovery-mds-scale}\nTESTNAME=${TESTNAME:-\"\"}\n[ -n \"$TESTNAME\" ] && TESTLOG_PREFIX=$TESTLOG_PREFIX.$TESTNAME\n\nLOG=$TESTLOG_PREFIX.$(basename $0 .sh)_stdout.$(hostname -s).log\nDEBUGLOG=$(echo $LOG | sed 's/\\(.*\\)stdout/\\1debug/')\n\nmkdir -p ${LOG%/*}\n\nrm -f $LOG $DEBUGLOG\nexec 2>$DEBUGLOG\nset -x\n\n. $(dirname $0)/functions.sh\n\nIOR=${IOR:-\"$(which IOR)\"}\n\nassert_env MOUNT END_RUN_FILE LOAD_PID_FILE IOR\n\ntrap signaled TERM\n\n# if MACHINEFILE set and exists -- use it\nif [ -z $MACHINEFILE ] || [ ! -e $MACHINEFILE ]; then\n    MACHINEFILE=$TMP/$(basename $0)-$(hostname).machines\n    echo $(hostname) >$MACHINEFILE\nfi\n\nTHREADS_PER_CLIENT=${THREADS_PER_CLIENT:-3}\nNUM_CLIENTS=$(cat $MACHINEFILE | wc -l)\n\n# recovery-*-scale scripts use this to signal the client loads to die\necho $$ >$LOAD_PID_FILE\n\nTESTDIR=${TESTDIR:-$MOUNT/d0.ior-$(hostname)}\n\nCONTINUE=true\nwhile [ ! -e \"$END_RUN_FILE\" ] && $CONTINUE; do\n\techoerr \"$(date +'%F %H:%M:%S'): IOR run starting\"\n\tmkdir -p $TESTDIR\n\t# need this only if TESTDIR is not default\n\tchmod -R 777 $TESTDIR\n\n\tsync\n\n\trun_ior fpp $TESTDIR  1>$LOG &\n\n\tload_pid=$!\n\twait $load_pid\n\tif [ ${PIPESTATUS[0]} -eq 0 ]; then\n        \techoerr \"$(date +'%F %H:%M:%S'): IOR succeeded\"\n        \tcd $TMP\n        \trm -rf $TESTDIR\n\t\techoerr \"$(date +'%F %H:%M:%S'): IOR run finished\"\n\telse\n\t\techoerr \"$(date +'%F %H:%M:%S'): IOR failed\"\n\t\tif [ -z \"$ERRORS_OK\" ]; then\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\tfi\n\t\tif [ $BREAK_ON_ERROR ]; then\n\t\t\t# break\n\t\t\tCONTINUE=false\n\t\tfi\n\tfi\ndone\n\nechoerr \"$(date +'%F %H:%M:%S'): IOR run exiting\"\n", "num_lines": 71}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=${TMP:-/tmp}\n\nTESTLOG_PREFIX=${TESTLOG_PREFIX:-$TMP/recovery-mds-scale}\nTESTNAME=${TESTNAME:-\"\"}\n[ -n \"$TESTNAME\" ] && TESTLOG_PREFIX=$TESTLOG_PREFIX.$TESTNAME\n\nLOG=$TESTLOG_PREFIX.$(basename $0 .sh)_stdout.$(hostname -s).log\nDEBUGLOG=$(echo $LOG | sed 's/\\(.*\\)stdout/\\1debug/')\n\nmkdir -p ${LOG%/*}\n\nrm -f $LOG $DEBUGLOG\nexec 2>$DEBUGLOG\nset -x\n\n. $(dirname $0)/functions.sh\n\nassert_env MOUNT END_RUN_FILE LOAD_PID_FILE\n\ntrap signaled TERM\n\n# recovery-*-scale scripts use this to signal the client loads to die\necho $$ >$LOAD_PID_FILE\n\nTESTDIR=$MOUNT/d0.iozone-$(hostname)\n\nCONTINUE=true\nwhile [ ! -e \"$END_RUN_FILE\" ] && $CONTINUE; do\n\techoerr \"$(date +'%F %H:%M:%S'): iozone run starting\"\n\tmkdir -p $TESTDIR\n\tcd $TESTDIR\n\n\tsync\n\tiozone -a -M -R -V 0xab -g 100M -q 512k -i0 -i1 \\\n\t\t\t\t\t-f $TESTDIR/iozone-file 1>$LOG &\n\tload_pid=$!\n\twait $load_pid\n\tif [ ${PIPESTATUS[0]} -eq 0 ]; then\n\t\techoerr \"$(date +'%F %H:%M:%S'): iozone succeeded\"\n\t\tcd $TMP\n\t\trm -rf $TESTDIR\n\t\tif [ -d $TESTDIR ]; then\n\t\t\techoerr \"$(date +'%F %H:%M:%S'): failed to remove \\\n\t\t\t\t\t\t\t\t $TESTDIR\"\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\t\tCONTINUE=false\n\t\tfi\n\t\techoerr \"$(date +'%F %H:%M:%S'): iozone run finished\"\n\telse\n\t\techoerr \"$(date +'%F %H:%M:%S'): iozone failed\"\n\t\tif [ -z \"$ERRORS_OK\" ]; then\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\tfi\n\t\tif [ $BREAK_ON_ERROR ]; then\n\t\t\t# break\n\t\t\tCONTINUE=false\n\t\tfi\n\tfi\ndone\n\nechoerr \"$(date +'%F %H:%M:%S'): iozone run exiting\"\n", "num_lines": 64}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=${TMP:-/tmp}\n\nTESTLOG_PREFIX=${TESTLOG_PREFIX:-$TMP/recovery-mds-scale}\nTESTNAME=${TESTNAME:-\"\"}\n[ -n \"$TESTNAME\" ] && TESTLOG_PREFIX=$TESTLOG_PREFIX.$TESTNAME\n\nLOG=$TESTLOG_PREFIX.$(basename $0 .sh)_stdout.$(hostname -s).log\nDEBUGLOG=$(echo $LOG | sed 's/\\(.*\\)stdout/\\1debug/')\n\nmkdir -p ${LOG%/*}\n\nrm -f $LOG $DEBUGLOG\nexec 2>$DEBUGLOG\nset -x\n\n. $(dirname $0)/functions.sh\n\nassert_env MOUNT END_RUN_FILE LOAD_PID_FILE LFS CLIENT_COUNT LCTL\n\ntrap signaled TERM\n\n# recovery-*-scale scripts use this to signal the client loads to die\necho $$ >$LOAD_PID_FILE\n\nTESTDIR=$MOUNT/d0.tar-$(hostname)\n\ndo_tar() {\n    tar cf - /etc | tar xf - >$LOG 2>&1\n    return ${PIPESTATUS[1]}\n}\n\nCONTINUE=true\nwhile [ ! -e \"$END_RUN_FILE\" ] && $CONTINUE; do\n\techoerr \"$(date +'%F %H:%M:%S'): tar run starting\"\n\tmkdir -p $TESTDIR\n\tcd $TESTDIR\n\tsync\n\n\tUSAGE=$(du -s /etc | awk '{print $1}')\n\t$LCTL set_param llite.*.lazystatfs=0\n\tdf $TESTDIR || true\n\tsleep 2\n\tFREE_SPACE=$(df $TESTDIR | awk '/:/ { print $4 }')\n\tAVAIL=$((FREE_SPACE * 9 / 10 / CLIENT_COUNT))\n\tif [ $AVAIL -lt $USAGE ]; then\n\t\techoerr \"no enough free disk space: need $USAGE, avail $AVAIL\"\n\t\techo $(hostname) >> $END_RUN_FILE\n\t\tbreak\n\tfi\n\n\tdo_tar\n\tRC=$?\n\tPREV_ERRORS=$(grep \"exit delayed from previous errors\" $LOG) || true\n\tif [ $RC -ne 0 -a \"$ERRORS_OK\" -a \"$PREV_ERRORS\" ]; then\n\t\techoerr \"$(date +'%F %H:%M:%S'): tar errors earlier, ignoring\"\n\t\tRC=0\n\tfi\n\tif [ $RC -eq 0 ]; then\n\t\techoerr \"$(date +'%F %H:%M:%S'): tar succeeded\"\n\t\tcd $TMP\n\t\trm -rf $TESTDIR\n\t\techoerr \"$(date +'%F %H:%M:%S'): tar run finished\"\n\telse\n\t\techoerr \"$(date +'%F %H:%M:%S'): tar failed\"\n\t\tif [ -z \"$ERRORS_OK\" ]; then\n\t\t\techo $(hostname) >> $END_RUN_FILE\n\t\tfi\n\t\tif [ $BREAK_ON_ERROR ]; then\n\t\t\t# break\n\t\t\tCONTINUE=false\n\t\tfi\n\tfi\ndone\n\nechoerr \"$(date +'%F %H:%M:%S'): tar run exiting\"\n", "num_lines": 78}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Test basic functionality of the filesystem using simple\n# benchmarks.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n# bug number:\nALWAYS_EXCEPT=\"$SANITY_BENCHMARK_EXCEPT\"\n\nMAX_THREADS=${MAX_THREADS:-20}\nRAMKB=`awk '/MemTotal:/ { print $2 }' /proc/meminfo`\nif [ -z \"$THREADS\" ]; then\n\tTHREADS=$((RAMKB / 16384))\n\t[ $THREADS -gt $MAX_THREADS ] && THREADS=$MAX_THREADS\nfi\nSIZE=${SIZE:-$((RAMKB * 2))}\nRSIZE=${RSIZE:-512}\n\nDEBUG_LVL=${DEBUG_LVL:-0}\nDEBUG_OFF=${DEBUG_OFF:-\"eval lctl set_param debug=\\\"$DEBUG_LVL\\\"\"}\nDEBUG_ON=${DEBUG_ON:-\"eval lctl set_param debug=0x33f0484\"}\nDIRECTIO=${DIRECTIO:-directio}\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"iozone\"\n\nbuild_test_filter\ncheck_and_setup_lustre\n\nassert_DIR\nrm -rf $DIR/[df][0-9]*\n\ntest_dbench() {\n    if ! which dbench > /dev/null 2>&1 ; then\n\tskip_env \"No dbench installed\"\n\treturn\n    fi\n\n    local DBENCHDIR=$DIR/d0.$HOSTNAME\n    mkdir -p $DBENCHDIR\n    local SPACE=`df -P $MOUNT | tail -n 1 | awk '{ print $4 }'`\n    DB_THREADS=$((SPACE / 50000))\n    [ $THREADS -lt $DB_THREADS ] && DB_THREADS=$THREADS\n    \n    $DEBUG_OFF\n    myUID=$RUNAS_ID\n    myGID=$RUNAS_GID\n    myRUNAS=$RUNAS\n    FAIL_ON_ERROR=false check_runas_id_ret $myUID $myGID $myRUNAS || \\\n      { myRUNAS=\"\" && myUID=$UID && myGID=`id -g $USER`; }\n    chown $myUID:$myGID $DBENCHDIR\n    local duration=\"\"\n    [ \"$SLOW\" = \"no\" ] && duration=\" -t 120\"\n    if [ \"$SLOW\" != \"no\" -o $DB_THREADS -eq 1 ]; then\n\t$myRUNAS bash rundbench -D $DBENCHDIR 1 $duration || error \"dbench failed!\"\n\t$DEBUG_ON\n    fi\n    if [ $DB_THREADS -gt 1 ]; then\n\t$DEBUG_OFF\n\t$myRUNAS bash rundbench -D $DBENCHDIR $DB_THREADS $duration\n\t$DEBUG_ON\n    fi\n    rm -rf $DBENCHDIR\n}\nrun_test dbench \"dbench\"\n\ntest_bonnie() {\n    if ! which bonnie++ > /dev/null 2>&1; then\n\tskip_env \"No bonnie++ installed\"\n\treturn 0\n    fi\n    local BONDIR=$DIR/d0.bonnie\n    mkdir -p $BONDIR\n    $LFS setstripe -c -1 $BONDIR\n    sync\n    local MIN=`lctl get_param -n osc.*.kbytesavail | sort -n | head -n1`\n    local SPACE=$(( OSTCOUNT * MIN ))\n    [ $SPACE -lt $SIZE ] && SIZE=$((SPACE * 3 / 4))\n    log \"min OST has ${MIN}kB available, using ${SIZE}kB file size\"\n    $DEBUG_OFF\n    myUID=$RUNAS_ID\n    myGID=$RUNAS_GID\n    myRUNAS=$RUNAS\n    FAIL_ON_ERROR=false check_runas_id_ret $myUID $myGID $myRUNAS || \\\n      { myRUNAS=\"\" && myUID=$UID && myGID=`id -$USER`; }\n    chown $myUID:$myGID $BONDIR\t\t\n    $myRUNAS bonnie++ -f -r 0 -s$((SIZE / 1024)) -n 10 -u$myUID:$myGID -d$BONDIR\n    $DEBUG_ON\n}\nrun_test bonnie \"bonnie++\"\n\ntest_iozone() {\n    if ! which iozone > /dev/null 2>&1; then\n\tskip_env \"No iozone installed\"\n\treturn 0\n    fi\n\n    export O_DIRECT\n    \n    local IOZDIR=$DIR/d0.iozone\n    wait_delete_completed || true\n    mkdir -p $IOZDIR\n    $LFS setstripe -c -1 $IOZDIR\n    sync\n    local MIN=`lctl get_param -n osc.*.kbytesavail | sort -n | head -n1`\n    local SPACE=$(( OSTCOUNT * MIN ))\n    [ $SPACE -lt $SIZE ] && SIZE=$((SPACE * 3 / 4))\n    log \"min OST has ${MIN}kB available, using ${SIZE}kB file size\"\n    IOZONE_OPTS=\"-i 0 -i 1 -i 2 -e -+d -r $RSIZE\"\n    IOZFILE=\"$IOZDIR/iozone\"\n    IOZLOG=$TMP/iozone.log\n\t\t# $SPACE was calculated with all OSTs\n    $DEBUG_OFF\n    myUID=$RUNAS_ID\n    myGID=$RUNAS_GID\n    myRUNAS=$RUNAS\n    FAIL_ON_ERROR=false check_runas_id_ret $myUID $myGID $myRUNAS || \\\n        { myRUNAS=\"\" && myUID=$UID && myGID=`id -g $USER`; }\n    chown $myUID:$myGID $IOZDIR\n    $myRUNAS iozone $IOZONE_OPTS -s $SIZE -f $IOZFILE 2>&1 | tee $IOZLOG\n    tail -1 $IOZLOG | grep -q complete || \\\n\t{ error \"iozone (1) failed\" && return 1; }\n    rm -f $IOZLOG\n    wait_delete_completed || true\n    $DEBUG_ON\n    \n    # check if O_DIRECT support is implemented in kernel\n    if [ -z \"$O_DIRECT\" ]; then\n\ttouch $DIR/f.iozone\n\tif ! $DIRECTIO write $DIR/f.iozone 0 1; then\n\t    log \"SKIP iozone DIRECT IO test\"\n\t    O_DIRECT=no\n\tfi\n\trm -f $DIR/f.iozone\n\twait_delete_completed || true\n    fi\n    if [ \"$O_DIRECT\" != \"no\" -a \"$IOZONE_DIR\" != \"no\" ]; then\n\t$DEBUG_OFF\n\t$myRUNAS iozone -I $IOZONE_OPTS -s $SIZE -f $IOZFILE.odir 2>&1 | tee $IOZLOG\n\ttail -1 $IOZLOG | grep -q complete || \\\n\t    { error \"iozone (2) failed\" && return 1; }\n\trm -f $IOZLOG\n\twait_delete_completed || true\n\t$DEBUG_ON\n    fi\n\n    SPACE=`df -P $MOUNT | tail -n 1 | awk '{ print $4 }'`\n    IOZ_THREADS=$((SPACE / SIZE * 2 / 3 ))\n    [ $THREADS -lt $IOZ_THREADS ] && IOZ_THREADS=$THREADS\n    IOZVER=`iozone -v | awk '/Revision:/ {print $3}' | tr -d .`\n    if [ \"$IOZ_THREADS\" -gt 1 -a \"$IOZVER\" -ge 3145 ]; then\n\t$LFS setstripe -c -1 $IOZDIR\n\t$DEBUG_OFF\n\tTHREAD=1\n\tIOZFILE=\" \"\n\twhile [ $THREAD -le $IOZ_THREADS ]; do\n\t    IOZFILE=\"$IOZFILE $IOZDIR/iozone.$THREAD\"\n\t    THREAD=$((THREAD + 1))\n\tdone\n\t$myRUNAS iozone $IOZONE_OPTS -s $((SIZE / IOZ_THREADS)) -t $IOZ_THREADS -F $IOZFILE 2>&1 | tee $IOZLOG\n\ttail -1 $IOZLOG | grep -q complete || \\\n\t    { error \"iozone (3) failed\" && return 1; }\n\trm -f $IOZLOG\n\twait_delete_completed || true\n\t$DEBUG_ON\n    elif [ $IOZVER -lt 3145 ]; then\n\tVER=`iozone -v | awk '/Revision:/ { print $3 }'`\n\techo \"iozone $VER too old for multi-thread test\"\n    fi\n}\nrun_test iozone \"iozone\"\n\ntest_fsx() {\n\tlocal testfile=$DIR/f0.fsxfile\n\tFSX_SIZE=$SIZE\n\tFSX_COUNT=1000\n\tlocal SPACE=`df -P $MOUNT | tail -n 1 | awk '{ print $4 }'`\n\n\t[ $SPACE -lt $FSX_SIZE ] && FSX_SIZE=$((SPACE * 3 / 4))\n\t$DEBUG_OFF\n\tFSX_SEED=${FSX_SEED:-$RANDOM}\n\trm -f $testfile\n\t$LFS setstripe -c -1 $testfile\n\tCMD=\"fsx -c 50 -p 1000 -S $FSX_SEED -P $TMP -l $FSX_SIZE \\\n\t-N $((FSX_COUNT * 100)) $FSXOPT $testfile\"\n\techo \"Using: $CMD\"\n\t$CMD || error \"fsx failed\"\n\trm -f $testfile\n\t$DEBUG_ON\n}\nrun_test fsx \"fsx\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 205}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$SANITY_DOM_EXCEPT\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\n[[ \"$MDS1_VERSION\" -ge $(version_code 2.10.56) ]] ||\n\tskip \"Need MDS version at least 2.10.56\"\n\nOPENFILE=${OPENFILE:-openfile}\nMOUNT_2=${MOUNT_2:-\"yes\"}\nFAIL_ON_ERROR=false\n\ncheck_and_setup_lustre\n\n# $RUNAS_ID may get set incorrectly somewhere else\nif [[ $UID -eq 0 && $RUNAS_ID -eq 0 ]]; then\n\tskip_env \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\" && exit\nfi\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\n\nDOM=\"yes\"\nDOM_SIZE=${DOM_SIZE:-\"$((1024*1024))\"}\nOSC=\"mdc\"\n\nsave_layout_restore_at_exit $DIR1\n$LFS setstripe -E $DOM_SIZE -L mdt -E EOF $DIR1\n\nmkdir -p $MOUNT2\nmount_client $MOUNT2\n\ntest_1() {\n\tdd if=/dev/zero of=$DIR1/$tfile bs=7k count=1 || error \"write 1\"\n\t$TRUNCATE $DIR2/$tfile 1000 || error \"truncate\"\n\tdd if=/dev/zero of=$DIR1/$tfile bs=3k count=1 seek=1 || error \"write 2\"\n\t$CHECKSTAT -t file -s 6144 $DIR2/$tfile || error \"stat\"\n\trm $DIR1/$tfile\n}\nrun_test 1 \"write a file on one mount, truncate on the other, write again\"\n\ntest_2() {\n\tSZ1=234852\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=4 || return 1\n\tdd if=/dev/zero bs=$SZ1 count=1 >> $DIR/$tfile || return 2\n\tdd if=$DIR/$tfile of=$DIR/${tfile}_left bs=1M skip=5 || return 3\n\t$CHECKSTAT -t file -s $SZ1 $DIR/${tfile}_left ||\n\t\terror \"Error reading at the end of the file $tfile\"\n}\nrun_test 2 \"Write with a seek, append, read from a single mountpoint\"\n\ntest_3() {\n\t# Write on one node to the DoM stripe and then truncate to over DoM size\n\tdd if=/dev/zero of=$DIR1/$tfile bs=$((DOM_SIZE-100)) count=1 ||\n\t\treturn 1\n\ttruncate $DIR1/$tfile $((DOM_SIZE+700)) || return 2\n\t# read on the second node inside DoM stripe to take a lock data from\n\t# the first client\n\tdd if=$DIR2/$tfile of=/dev/null bs=4096 count=1 seek=1 || return 3\n\t$CHECKSTAT -t file -s $((DOM_SIZE+700)) $DIR2/$tfile ||\n\t\terror \"Wrong size after first truncate $tfile on first node\"\n\t# now do local truncate over DoM size and check size is correct\n\ttruncate $DIR2/$tfile $((DOM_SIZE+500)) || return 4\n\t$CHECKSTAT -t file -s $((DOM_SIZE+500)) $DIR2/$tfile ||\n\t\terror \"Wrong size after second truncate on the same node\"\n\t$CHECKSTAT -t file -s $((DOM_SIZE+500)) $DIR1/$tfile ||\n\t\terror \"Wrong size after second truncate on other node\"\n}\nrun_test 3 \"Truncate over DoM size on different nodes\"\n\ntest_4() {\n\tlocal before=0\n\tlocal after=0\n\n\tdd if=/dev/zero of=$DIR1/$tfile bs=2M count=1\n\tcancel_lru_locks mdc\n\n\t#define OBD_FAIL_MDC_GLIMPSE_DDOS 0x808\n\t$LCTL set_param fail_loc=0x80000808\n\tbefore=$(lctl get_param -n ldlm.namespaces.*mdc*.lock_count |\n\t\tgawk '{cnt=cnt+$1}  END{print cnt}')\n\tfor ((i=1; i < 100; i++))\n\tdo\n\t\ttail -n100 $DIR1/$tfile > /dev/null\n\t\tstat -f $DIR2/$tfile > /dev/null\n\tdone\n\tafter=$(lctl get_param -n ldlm.namespaces.*mdc*.lock_count |\n\t\tgawk '{cnt=cnt+$1}  END{print cnt}')\n\t[[ $((after - before)) -ge 20 ]] &&\n\t\terror \"Too many locks found $((after - before))\"\n\treturn 0\n}\nrun_test 4 \"DoM: glimpse doesn't produce duplicated locks\"\n\ntest_5() {\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 || return 1\n\n\tmultiop_bg_pause $DIR/$tfile O_Ac || return 1\n\tsetxattr=$!\n\n\tmultiop_bg_pause $DIR/$tfile O_Tc || return 1\n\ttruncate=$!\n\n\tmultiop $DIR2/$tfile Ow10 || return 1\n\n\tgetfattr -d $DIR2/$tfile\n\n#define OBD_FAIL_LLITE_TRUNCATE_INODE_PAUSE        0x1415\n\t$LCTL set_param fail_loc=0x80001415 fail_val=5\n\tkill -USR1 $truncate\n\tsleep 1\n\tmultiop $DIR2/$tfile Ow10 &\n\tsleep 1\n\tkill -USR1 $setxattr\n\n\twait\n\n\tevict=$(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] ||\n\t\t(do_facet client $LCTL get_param mdc.$FSNAME-MDT*.state;\n\t\t\terror \"eviction happened: $evict before:$before\")\n}\nrun_test 5 \"DoM truncate deadlock\"\n\ntest_6() {\n\t$MULTIOP $DIR1/$tfile Oz40960w100_z200w100c &\n\tMULTIPID=$!\n\n\t# let MULTIPID to create the file\n\tsleep 1\n\t$MULTIOP $DIR2/$tfile oO_RDWR:Tw100c\n\tkill -USR1 $MULTIPID\n\twait\n\t$MULTIOP $DIR2/$tfile oO_RDWR:z400w100c\n\t$CHECKSTAT -s 500 $DIR2/$tfile || error \"wrong size\"\n}\nrun_test 6 \"Race two writes, check file size\"\n\ntest_7() {\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1000 count=1\n\tcancel_lru_locks\n\n\t$MULTIOP $DIR1/$tfile or1000c\n\tdd if=/dev/urandom of=$DIR2/$tfile bs=1000 count=1\n\tlocal md5_1=$(md5sum $DIR/$tfile | awk '{ print $1 }')\n\tlocal md5_2=$(md5sum $DIR2/$tfile | awk '{ print $1 }')\n\t[[ $md5_1 == $md5_2 ]] ||\n\t\terror \"Client reads stale page\"\n}\nrun_test 7 \"Stale pages after read-on-open\"\n\ntest_fsx() {\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\n\ttouch $file1\n\tfsx -c 50 -p 100 -N 1000 -l $((DOM_SIZE*2)) -S 0 -d -d $file1 $file2\n}\nrun_test fsx \"Dual-mount fsx with DoM files\"\n\ntest_sanity()\n{\n\tSANITY_ONLY=${SANITY_ONLY:-\"36 39 40 41 42d 42e 43 46 56r 101e 119a \\\n\t\t\t\t    131 150 155a 155b 155c 155d 207 241 251\"}\n\tSANITY_REPEAT=${SANITY_REPEAT:-1}\n\t# XXX: to fix 45. Add 42a, c when LU-9693 fixed.\n\t# Add 42b when LU-6493 fixed\n\tONLY=$SANITY_ONLY ONLY_REPEAT=$SANITY_REPEAT OSC=\"mdc\" DOM=\"yes\" \\\n\t\tbash sanity.sh\n\n\treturn 0\n}\nrun_test sanity \"Run sanity with Data-on-MDT files\"\n\ntest_sanityn()\n{\n\tSANITYN_ONLY=${SANITYN_ONLY:-\"1 2 4 5 6 7 8 9 10 11 12 14 17 19 20 \\\n\t\t\t\t      23 27 39 51a 51c 51d\"}\n\tSANITYN_REPEAT=${SANITYN_REPEAT:-1}\n\t# XXX: to fix 60\n\tONLY=$SANITYN_ONLY ONLY_REPEAT=$SANITYN_REPEAT OSC=\"mdc\" DOM=\"yes\" \\\n\t\tbash sanityn.sh\n\n\treturn 0\n}\nrun_test sanityn \"Run sanityn with Data-on-MDT files\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status \"${TMP}/sanity.log ${TMP}/sanityn.log\"\n", "num_lines": 210}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\nset -e\nset +o posix\n\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_FLR_EXCEPT \"\n# Bug number for skipped test:    LU-11381\nALWAYS_EXCEPT+=\"                  201 \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n# skip all tests for PPC until we can get sanity-pfl to pass\nif [[ $(uname -m) = ppc64 ]]; then\n\tskip \"Skip FLR testing for PPC clients\"\nfi\n\nbuild_test_filter\n\n[[ \"$MDS1_VERSION\" -ge $(version_code 2.10.56) ]] ||\n\tskip \"Need MDS version at least 2.10.56\"\n\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&\n\terror \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\n\ncheck_and_setup_lustre\nDIR=${DIR:-$MOUNT}\nassert_DIR\n\nassert_DIR\nrm -rf $DIR/[Rdfs][0-9]*\n\n# global array to store mirror IDs\ndeclare -a mirror_array\nget_mirror_ids() {\n\tlocal tf=$1\n\tlocal id\n\tlocal array\n\n\tarray=()\n\tfor id in $($LFS getstripe $tf | awk '/lcme_id/{print $2}'); do\n\t\tarray[${#array[@]}]=$((id >> 16))\n\tdone\n\n\tmirror_array=($(printf \"%s\\n\" \"${array[@]}\" | sort -u))\n\n\techo ${#mirror_array[@]}\n}\n\ndrop_client_cache() {\n\techo 3 > /proc/sys/vm/drop_caches\n}\n\nstop_osts() {\n\tlocal idx\n\n\tfor idx in \"$@\"; do\n\t\tstop ost$idx\n\tdone\n\n\tfor idx in \"$@\"; do\n\t\twait_osc_import_state client ost$idx \"\\(DISCONN\\|IDLE\\)\"\n\tdone\n}\n\nstart_osts() {\n\tlocal idx\n\n\tfor idx in \"$@\"; do\n\t\tstart ost$idx $(ostdevname $idx) $OST_MOUNT_OPTS ||\n\t\t\terror \"start ost$idx failed\"\n\tdone\n\n\tfor idx in \"$@\"; do\n\t\twait_recovery_complete ost$idx\n\tdone\n}\n\n#\n# Verify mirror count with an expected value for a given file.\n#\nverify_mirror_count() {\n\tlocal tf=$1\n\tlocal expected=$2\n\tlocal mirror_count=$($LFS getstripe -N $tf)\n\n\t[[ $mirror_count = $expected ]] || {\n\t\t$LFS getstripe -v $tf\n\t\terror \"verify mirror count failed on $tf:\" \\\n\t\t      \"$mirror_count != $expected\"\n\t}\n}\n\n#\n# Verify component count with an expected value for a given file.\n#\t$1 coposited layout file\n#\t$2 expected component number\n#\nverify_comp_count() {\n\tlocal tf=$1\n\tlocal expected=$2\n\tlocal comp_count=$($LFS getstripe --component-count $tf)\n\n\t[[ $comp_count = $expected ]] || {\n\t\t$LFS getstripe -v $tf\n\t\terror \"verify component count failed on $tf:\" \\\n\t\t      \"$comp_count != $expected\"\n\t}\n}\n\n#\n# Verify component attribute with an expected value for a given file\n# and component ID.\n#\nverify_comp_attr() {\n\tlocal attr=$1\n\tlocal tf=$2\n\tlocal comp_id=$3\n\tlocal expected=$4\n\tlocal cmd=\"$LFS getstripe -I$comp_id\"\n\tlocal getstripe_cmd=\"$cmd -v\"\n\tlocal value\n\n\tcase $attr in\n\t\tstripe-size) cmd+=\" -S $tf\" ;;\n\t\tstripe-count) cmd+=\" -c $tf\" ;;\n\t\tstripe-index) cmd+=\" -i $tf\" ;;\n\t\tpool) cmd+=\" -p $tf\" ;;\n\t\tcomp-start) cmd+=\" --component-start $tf\" ;;\n\t\tcomp-end) cmd+=\" --component-end $tf\" ;;\n\t\tlcme_flags) cmd+=\" $tf | awk '/lcme_flags:/ { print \\$2 }'\" ;;\n\t\t*) error \"invalid attribute $attr\";;\n\tesac\n\n\tvalue=$(eval $cmd)\n\n\t[ $attr = lcme_flags ] && {\n\t\tlocal fl\n\t\tlocal expected_list=$(comma_list $expected)\n\t\tfor fl in ${expected_list//,/ }; do\n\t\t\tlocal neg=0\n\n\t\t\t[[ ${fl:0:1} = \"^\" ]] && neg=1\n\t\t\t[[ $neg = 1 ]] && fl=${fl:1}\n\n\t\t\t$(echo $value | grep -q $fl)\n\t\t\tlocal match=$?\n\t\t\t# 0: matched; 1: not matched\n\n\t\t\tif  [[ $neg = 0 && $match != 0 ||\n\t\t\t       $neg = 1 && $match = 0 ]]; then\n\t\t\t\t$getstripe_cmd $tf\n\t\t\t\t[[ $neg = 0 ]] && # expect the flag\n\t\t\t\t    error \"expected flag '$fl' not in $comp_id\"\n\t\t\t\t[[ $neg = 1 ]] && # not expect the flag\n\t\t\t\t    error \"not expected flag '$fl' in $comp_id\"\n\t\t\tfi\n\t\tdone\n\t\treturn\n\t}\n\n\t[[ $value = $expected ]] || {\n\t\t$getstripe_cmd $tf\n\t\terror \"verify $attr failed on $tf: $value != $expected\"\n\t}\n}\n\n#\n# Verify component extent with expected start and end extent values\n# for a given file and component ID.\n#\nverify_comp_extent() {\n\tlocal tf=$1\n\tlocal comp_id=$2\n\tlocal expected_start=$3\n\tlocal expected_end=$4\n\n\tverify_comp_attr comp-start $tf $comp_id $expected_start\n\tverify_comp_attr comp-end $tf $comp_id $expected_end\n}\n\n#\n# Verify component attribute with parent directory for a given file\n# and component ID.\n#\nverify_comp_attr_with_parent() {\n\tlocal attr=$1\n\tlocal tf=$2\n\tlocal comp_id=$3\n\tlocal td=$(cd $(dirname $tf); echo $PWD)\n\tlocal tf_cmd=\"$LFS getstripe -I$comp_id\"\n\tlocal td_cmd=\"$LFS getstripe\"\n\tlocal opt\n\tlocal expected\n\tlocal value\n\n\tcase $attr in\n\t\tstripe-size) opt=\"-S\" ;;\n\t\tstripe-count) opt=\"-c\" ;;\n\t\tpool) opt=\"-p\" ;;\n\t\t*) error \"invalid attribute $attr\";;\n\tesac\n\n\texpected=$($td_cmd $opt $td)\n\t[[ $expected = -1 ]] && expected=$OSTCOUNT\n\n\tvalue=$($tf_cmd $opt $tf)\n\t[[ $value = -1 ]] && value=$OSTCOUNT\n\n\t[[ $value = $expected ]] || {\n\t\t$td_cmd -d $td\n\t\t$tf_cmd -v $tf\n\t\terror \"verify $attr failed with parent on $tf:\" \\\n\t\t      \"$value != $expected\"\n\t}\n}\n\n#\n# Verify component attribute with filesystem-wide default value for a given file\n# and component ID.\n#\nverify_comp_attr_with_default() {\n\tlocal attr=$1\n\tlocal tf=$2\n\tlocal comp_id=$3\n\tlocal tf_cmd=\"$LFS getstripe -I$comp_id\"\n\tlocal opt\n\tlocal expected\n\tlocal value\n\n\tcase $attr in\n\t\tstripe-size)\n\t\t\topt=\"-S\"\n\t\t\texpected=$($LCTL get_param -n \\\n\t\t\t\t   lov.$FSNAME-clilov-*.stripesize)\n\t\t\t;;\n\t\tstripe-count)\n\t\t\topt=\"-c\"\n\t\t\texpected=$($LCTL get_param -n \\\n\t\t\t\t   lov.$FSNAME-clilov-*.stripecount)\n\t\t\t[[ $expected = -1 ]] && expected=$OSTCOUNT\n\t\t\t;;\n\t\t*) error \"invalid attribute $attr\";;\n\tesac\n\n\tvalue=$($tf_cmd $opt $tf)\n\t[[ $value = -1 ]] && value=$OSTCOUNT\n\n\t[[ $value = $expected ]] || {\n\t\t$tf_cmd -v $tf\n\t\terror \"verify $attr failed with default value on $tf:\" \\\n\t\t      \"$value != $expected\"\n\t}\n}\n\n#\n# Verify unspecified component attributes for a given file\n# and component ID.\n#\n# This will only verify the inherited attributes:\n# stripe size, stripe count and OST pool name\n#\nverify_comp_attrs() {\n\tlocal tf=$1\n\tlocal comp_id=$2\n\n\tverify_comp_attr_with_default stripe-size $tf $comp_id\n\tverify_comp_attr_with_default stripe-count $tf $comp_id\n\tverify_comp_attr_with_parent pool $tf $comp_id\n}\n\nverify_flr_state()\n{\n\tlocal tf=$1\n\tlocal expected_state=$2\n\n\tlocal state=$($LFS getstripe -v $tf | awk '/lcm_flags/{ print $2 }')\n\t[ $expected_state = $state ] ||\n\t\terror \"expected: $expected_state, actual $state\"\n}\n\n# command line test cases\ntest_0a() {\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_count=16 # LUSTRE_MIRROR_COUNT_MAX\n\tlocal mirror_cmd=\"$LFS mirror create\"\n\tlocal id\n\tlocal ids\n\tlocal i\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\n\t$mirror_cmd $tf &> /dev/null && error \"miss -N option\"\n\n\t$mirror_cmd -N $tf || error \"create mirrored file $tf failed\"\n\tverify_mirror_count $tf 1\n\tid=$($LFS getstripe -I $tf)\n\tverify_comp_attrs $tf $id\n\tverify_comp_extent $tf $id 0 EOF\n\n\t$mirror_cmd -N0 $tf-1 &> /dev/null && error \"invalid mirror count 0\"\n\t$mirror_cmd -N$((mirror_count + 1)) $tf-1 &> /dev/null &&\n\t\terror \"invalid mirror count $((mirror_count + 1))\"\n\n\t$mirror_cmd -N$mirror_count $tf-1 ||\n\t\terror \"create mirrored file $tf-1 failed\"\n\tverify_mirror_count $tf-1 $mirror_count\n\tids=($($LFS getstripe $tf-1 | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < $mirror_count; i++)); do\n\t\tverify_comp_attrs $tf-1 ${ids[$i]}\n\t\tverify_comp_extent $tf-1 ${ids[$i]} 0 EOF\n\tdone\n\n\t$mirror_cmd -N -N2 -N3 -N4 $tf-2 ||\n\t\terror \"create mirrored file $tf-2 failed\"\n\tverify_mirror_count $tf-2 10\n\tids=($($LFS getstripe $tf-2 | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < 10; i++)); do\n\t\tverify_comp_attrs $tf-2 ${ids[$i]}\n\t\tverify_comp_extent $tf-2 ${ids[$i]} 0 EOF\n\tdone\n}\nrun_test 0a \"lfs mirror create with -N option\"\n\ntest_0b() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_cmd=\"$LFS mirror create\"\n\tlocal ids\n\tlocal i\n\n\t# create a new OST pool\n\tlocal pool_name=$TESTNAME\n\tcreate_pool $FSNAME.$pool_name ||\n\t\terror \"create OST pool $pool_name failed\"\n\n\t# add OSTs into the pool\n\tpool_add_targets $pool_name 0 $((OSTCOUNT - 1)) ||\n\t\terror \"add OSTs into pool $pool_name failed\"\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\t$LFS setstripe -S 8M -c -1 -p $pool_name $td ||\n\t\terror \"$LFS setstripe $td failed\"\n\n\t# create a mirrored file with plain layout mirrors\n\t$mirror_cmd -N -N -S 4M -c 2 -p flash -i 2 -o 2,3 \\\n\t\t    -N -S 16M -N -c -1 -N -p archive -N -p none $tf ||\n\t\terror \"create mirrored file $tf failed\"\n\tverify_mirror_count $tf 6\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < 6; i++)); do\n\t\tverify_comp_extent $tf ${ids[$i]} 0 EOF\n\tdone\n\n\t# verify component ${ids[0]}\n\tverify_comp_attrs $tf ${ids[0]}\n\n\t# verify component ${ids[1]}\n\tverify_comp_attr stripe-size $tf ${ids[1]} 4194304\n\tverify_comp_attr stripe-count $tf ${ids[1]} 2\n\tverify_comp_attr stripe-index $tf ${ids[1]} 2\n\tverify_comp_attr pool $tf ${ids[1]} flash\n\n\t# verify component ${ids[2]}\n\tverify_comp_attr stripe-size $tf ${ids[2]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[2]} 2\n\tverify_comp_attr pool $tf ${ids[2]} flash\n\n\t# verify component ${ids[3]}\n\tverify_comp_attr stripe-size $tf ${ids[3]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[3]} $OSTCOUNT\n\tverify_comp_attr pool $tf ${ids[3]} flash\n\n\t# verify component ${ids[4]}\n\tverify_comp_attr stripe-size $tf ${ids[4]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[4]} $OSTCOUNT\n\tverify_comp_attr pool $tf ${ids[4]} archive\n\n\t# verify component ${ids[5]}\n\tverify_comp_attr stripe-size $tf ${ids[5]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[5]} $OSTCOUNT\n\tverify_comp_attr_with_parent pool $tf ${ids[5]}\n\n\tif [ $MDS1_VERSION -ge $(version_code 2.12.55) ]; then\n\t\t# LU-11022 - remove mirror by pool name\n\t\tlocal=cnt cnt=$($LFS getstripe $tf | grep archive | wc -l)\n\t\t[ \"$cnt\" != \"1\" ] && error \"unexpected mirror count $cnt\"\n\t\t$LFS mirror delete --pool archive $tf || error \"delete mirror\"\n\t\tcnt=$($LFS getstripe $tf | grep archive | wc -l)\n\t\t[ \"$cnt\" != \"0\" ] && error \"mirror count after removal: $cnt\"\n\tfi\n\n\t# destroy OST pool\n\tdestroy_test_pools\n}\nrun_test 0b \"lfs mirror create plain layout mirrors\"\n\ntest_0c() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_cmd=\"$LFS mirror create\"\n\tlocal ids\n\tlocal i\n\n\t# create a new OST pool\n\tlocal pool_name=$TESTNAME\n\tcreate_pool $FSNAME.$pool_name ||\n\t\terror \"create OST pool $pool_name failed\"\n\n\t# add OSTs into the pool\n\tpool_add_targets $pool_name 0 $((OSTCOUNT - 1)) ||\n\t\terror \"add OSTs into pool $pool_name failed\"\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\t$LFS setstripe -E 32M -S 8M -c -1 -p $pool_name -E eof -S 16M $td ||\n\t\terror \"$LFS setstripe $td failed\"\n\n\t# create a mirrored file with composite layout mirrors\n\t$mirror_cmd -N2 -E 4M -c 2 -p flash -i 1 -o 1,3 -E eof -S 4M \\\n\t\t    -N -c 4 -p none \\\n\t\t    -N3 -E 512M -S 16M -p archive -E -1 -i -1 -c -1 $tf ||\n\t\terror \"create mirrored file $tf failed\"\n\tverify_mirror_count $tf 6\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\n\t# verify components ${ids[0]} and ${ids[2]}\n\tfor i in 0 2; do\n\t\tverify_comp_attr_with_default stripe-size $tf ${ids[$i]}\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} 2\n\t\tverify_comp_attr stripe-index $tf ${ids[$i]} 1\n\t\tverify_comp_attr pool $tf ${ids[$i]} flash\n\t\tverify_comp_extent $tf ${ids[$i]} 0 4194304\n\tdone\n\n\t# verify components ${ids[1]} and ${ids[3]}\n\tfor i in 1 3; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 4194304\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} 2\n\t\tverify_comp_attr pool $tf ${ids[$i]} flash\n\t\tverify_comp_extent $tf ${ids[$i]} 4194304 EOF\n\tdone\n\n\t# verify component ${ids[4]}\n\tverify_comp_attr stripe-size $tf ${ids[4]} 4194304\n\tverify_comp_attr stripe-count $tf ${ids[4]} 4\n\tverify_comp_attr_with_parent pool $tf ${ids[4]}\n\tverify_comp_extent $tf ${ids[4]} 0 EOF\n\n\t# verify components ${ids[5]}, ${ids[7]} and ${ids[9]}\n\tfor i in 5 7 9; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 16777216\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} 4\n\t\tverify_comp_attr pool $tf ${ids[$i]} archive\n\t\tverify_comp_extent $tf ${ids[$i]} 0 536870912\n\tdone\n\n\t# verify components ${ids[6]}, ${ids[8]} and ${ids[10]}\n\tfor i in 6 8 10; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 16777216\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} -1\n\t\tverify_comp_attr pool $tf ${ids[$i]} archive\n\t\tverify_comp_extent $tf ${ids[$i]} 536870912 EOF\n\tdone\n\n\t# destroy OST pool\n\tdestroy_test_pools\n}\nrun_test 0c \"lfs mirror create composite layout mirrors\"\n\ntest_0d() {\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_count=16 # LUSTRE_MIRROR_COUNT_MAX\n\tlocal mirror_cmd=\"$LFS mirror extend\"\n\tlocal ids\n\tlocal i\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\n\t$mirror_cmd $tf &> /dev/null && error \"miss -N option\"\n\t$mirror_cmd -N $tf &> /dev/null && error \"$tf does not exist\"\n\n\t# create a non-mirrored file, convert it to a mirrored file and extend\n\ttouch $tf || error \"touch $tf failed\"\n\t$mirror_cmd -N $tf || error \"convert and extend $tf failed\"\n\tverify_mirror_count $tf 2\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < 2; i++)); do\n\t\tverify_comp_attrs $tf ${ids[$i]}\n\t\tverify_comp_extent $tf ${ids[$i]} 0 EOF\n\tdone\n\n\tlfsck_verify_pfid $tf || error \"PFID is not set\"\n\n\t# create a mirrored file and extend it\n\t$LFS mirror create -N $tf-1 || error \"create mirrored file $tf-1 failed\"\n\t$LFS mirror create -N $tf-2 || error \"create mirrored file $tf-2 failed\"\n\n\t$mirror_cmd -N -S 4M -N -f $tf-2 $tf-1 &> /dev/null &&\n\t\terror \"setstripe options should not be specified with -f option\"\n\n\t$mirror_cmd -N$((mirror_count - 1)) $tf-1 ||\n\t\terror \"extend mirrored file $tf-1 failed\"\n\tverify_mirror_count $tf-1 $mirror_count\n\tids=($($LFS getstripe $tf-1 | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < $mirror_count; i++)); do\n\t\tverify_comp_attrs $tf-1 ${ids[$i]}\n\t\tverify_comp_extent $tf-1 ${ids[$i]} 0 EOF\n\tdone\n\n\t$mirror_cmd -N $tf-1 &> /dev/null &&\n\t\terror \"exceeded maximum mirror count $mirror_count\" || true\n}\nrun_test 0d \"lfs mirror extend with -N option\"\n\ntest_0e() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_cmd=\"$LFS mirror extend\"\n\tlocal ids\n\tlocal i\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\n\t# create a mirrored file with plain layout mirrors\n\t$LFS mirror create -N -S 32M -c 3 -p ssd -i 1 -o 1,2,3 $tf ||\n\t\terror \"create mirrored file $tf failed\"\n\n\t# extend the mirrored file with plain layout mirrors\n\t$mirror_cmd -N -S 4M -c 2 -p flash -i 2 -o 2,3 \\\n\t\t    -N -S 16M -N -c -1 -N -p archive -N -p none $tf ||\n\t\terror \"extend mirrored file $tf failed\"\n\tverify_mirror_count $tf 6\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tfor ((i = 0; i < 6; i++)); do\n\t\tverify_comp_extent $tf ${ids[$i]} 0 EOF\n\tdone\n\n\t# verify component ${ids[0]}\n\tverify_comp_attr stripe-size $tf ${ids[0]} 33554432\n\tverify_comp_attr stripe-count $tf ${ids[0]} 3\n\tverify_comp_attr stripe-index $tf ${ids[0]} 1\n\tverify_comp_attr pool $tf ${ids[0]} ssd\n\n\t# verify component ${ids[1]}\n\tverify_comp_attr stripe-size $tf ${ids[1]} 4194304\n\tverify_comp_attr stripe-count $tf ${ids[1]} 2\n\tverify_comp_attr stripe-index $tf ${ids[1]} 2\n\tverify_comp_attr pool $tf ${ids[1]} flash\n\n\t# verify component ${ids[2]}\n\tverify_comp_attr stripe-size $tf ${ids[2]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[2]} 2\n\tverify_comp_attr pool $tf ${ids[2]} flash\n\n\t# verify component ${ids[3]}\n\tverify_comp_attr stripe-size $tf ${ids[3]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[3]} $OSTCOUNT\n\tverify_comp_attr pool $tf ${ids[3]} flash\n\n\t# verify component ${ids[4]}\n\tverify_comp_attr stripe-size $tf ${ids[4]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[4]} $OSTCOUNT\n\tverify_comp_attr pool $tf ${ids[4]} archive\n\n\t# verify component ${ids[5]}\n\tverify_comp_attr stripe-size $tf ${ids[5]} 16777216\n\tverify_comp_attr stripe-count $tf ${ids[5]} $OSTCOUNT\n\tverify_comp_attr_with_parent pool $tf ${ids[5]}\n}\nrun_test 0e \"lfs mirror extend plain layout mirrors\"\n\ntest_0f() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_cmd=\"$LFS mirror extend\"\n\tlocal ids\n\tlocal i\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\n\t# create a mirrored file with composite layout mirror\n\t$LFS mirror create -N -E 32M -S 16M -p ssd -E eof -S 32M $tf ||\n\t\terror \"create mirrored file $tf failed\"\n\n\t# extend the mirrored file with composite layout mirrors\n\t$mirror_cmd -N -p archive \\\n\t\t    -N2 -E 4M -c 2 -p flash -i 1 -o 1,3 -E eof -S 4M \\\n\t\t    -N -c -1 -p none \\\n\t\t    -N3 -E 512M -S 16M -p archive -E -1 -i -1 -c -1 $tf ||\n\t\terror \"extend mirrored file $tf failed\"\n\tverify_mirror_count $tf 8\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\n\t# verify component ${ids[0]}\n\tverify_comp_attr stripe-size $tf ${ids[0]} 16777216\n\tverify_comp_attr_with_default stripe-count $tf ${ids[0]}\n\tverify_comp_attr pool $tf ${ids[0]} ssd\n\tverify_comp_extent $tf ${ids[0]} 0 33554432\n\n\t# verify component ${ids[1]}\n\tverify_comp_attr stripe-size $tf ${ids[1]} 33554432\n\tverify_comp_attr_with_default stripe-count $tf ${ids[1]}\n\tverify_comp_attr pool $tf ${ids[1]} ssd\n\tverify_comp_extent $tf ${ids[1]} 33554432 EOF\n\n\t# verify component ${ids[2]}\n\tverify_comp_attr stripe-size $tf ${ids[0]} 16777216\n\tverify_comp_attr_with_default stripe-count $tf ${ids[2]}\n\tverify_comp_attr pool $tf ${ids[2]} archive\n\tverify_comp_extent $tf ${ids[2]} 0 EOF\n\n\t# verify components ${ids[3]} and ${ids[5]}\n\tfor i in 3 5; do\n\t\tverify_comp_attr_with_default stripe-size $tf ${ids[$i]}\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} 2\n\t\tverify_comp_attr stripe-index $tf ${ids[$i]} 1\n\t\tverify_comp_attr pool $tf ${ids[$i]} flash\n\t\tverify_comp_extent $tf ${ids[$i]} 0 4194304\n\tdone\n\n\t# verify components ${ids[4]} and ${ids[6]}\n\tfor i in 4 6; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 4194304\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} 2\n\t\tverify_comp_attr pool $tf ${ids[$i]} flash\n\t\tverify_comp_extent $tf ${ids[$i]} 4194304 EOF\n\tdone\n\n\t# verify component ${ids[7]}\n\tverify_comp_attr stripe-size $tf ${ids[7]} 4194304\n\tverify_comp_attr stripe-count $tf ${ids[7]} $OSTCOUNT\n\tverify_comp_attr_with_parent pool $tf ${ids[7]}\n\tverify_comp_extent $tf ${ids[7]} 0 EOF\n\n\t# verify components ${ids[8]}, ${ids[10]} and ${ids[12]}\n\tfor i in 8 10 12; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 16777216\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} $OSTCOUNT\n\t\tverify_comp_attr pool $tf ${ids[$i]} archive\n\t\tverify_comp_extent $tf ${ids[$i]} 0 536870912\n\tdone\n\n\t# verify components ${ids[9]}, ${ids[11]} and ${ids[13]}\n\tfor i in 9 11 13; do\n\t\tverify_comp_attr stripe-size $tf ${ids[$i]} 16777216\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} -1\n\t\tverify_comp_attr pool $tf ${ids[$i]} archive\n\t\tverify_comp_extent $tf ${ids[$i]} 536870912 EOF\n\tdone\n}\nrun_test 0f \"lfs mirror extend composite layout mirrors\"\n\ntest_0g() {\n\tlocal tf=$DIR/$tfile\n\n\t$LFS mirror create -N -E 1M -S 1M -o0 --flags=prefer -E eof -o1 \\\n\t\t\t   -N -o1 $tf || error \"create mirrored file $tf failed\"\n\n\tverify_comp_attr lcme_flags $tf 0x10001 prefer\n\tverify_comp_attr lcme_flags $tf 0x10002 prefer\n\n\t# write to the mirrored file and check primary\n\tcp /etc/hosts $tf || error \"error writing file '$tf'\"\n\n\tverify_comp_attr lcme_flags $tf 0x20003 stale\n\n\t# resync file and check prefer flag\n\t$LFS mirror resync $tf || error \"error resync-ing file '$tf'\"\n\n\tcancel_lru_locks osc\n\t$LCTL set_param osc.*.stats=clear\n\tcat $tf &> /dev/null || error \"error reading file '$tf'\"\n\n\t# verify that the data was provided by OST1 where mirror 1 resides\n\tlocal nr_read=$($LCTL get_param -n osc.$FSNAME-OST0000-osc-[-0-9a-f]*.stats |\n\t\t\tawk '/ost_read/{print $2}')\n\t[ -n \"$nr_read\" ] || error \"read was not provided by OST1\"\n}\nrun_test 0g \"lfs mirror create flags support\"\n\ntest_0h() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.57) ] &&\n\t\tskip \"Need MDS version at least 2.11.57\"\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal ids\n\tlocal i\n\n\t# create parent directory\n\ttest_mkdir $td || error \"mkdir $td failed\"\n\n\t$LFS setstripe -N -E 1M -S 1M --flags=prefer -E eof -N2 $td ||\n\t\terror \"set default mirrored layout on directory $td failed\"\n\n\t# verify flags are inherited from the directory\n\ttouch $tf\n\n\tverify_comp_attr lcme_flags $tf 0x10001 prefer\n\tverify_comp_attr lcme_flags $tf 0x10002 prefer\n\n\t# set flags to the first component\n\t$LFS setstripe --comp-set -I 0x10001 --comp-flags=^prefer,stale $tf\n\n\tverify_comp_attr lcme_flags $tf 0x10001 stale\n\tverify_comp_attr lcme_flags $tf 0x10002 prefer\n\n\t$LFS setstripe --comp-set -I0x10001 --comp-flags=^stale $tf &&\n\t\terror \"clearing 'stale' should fail\"\n\n\t# write and resync file. It can't resync the file directly because the\n\t# file state is still 'ro'\n\tcp /etc/hosts $tf || error \"error writing file '$tf'\"\n\t$LFS mirror resync $tf || error \"error resync-ing file '$tf'\"\n\n\t$LFS setstripe --comp-set -I 0x20003 --comp-flags=prefer $tf ||\n\t\terror \"error setting flag prefer\"\n\n\tverify_comp_attr lcme_flags $tf 0x20003 prefer\n\n\t$LFS setstripe --comp-set -I 0x20003 --comp-flags=^prefer $tf ||\n\t\terror \"error clearing prefer flag from component 0x20003\"\n\n\t# MDS disallows setting stale flag on the last non-stale mirror\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.12.57) ]] || return 0\n\n\tcp /etc/hosts $tf || error \"error writing file '$tf'\"\n\n\tverify_comp_attr lcme_flags $tf 0x10002 prefer\n\tverify_comp_attr lcme_flags $tf 0x20003 stale\n\tverify_comp_attr lcme_flags $tf 0x30004 stale\n\n\t! $LFS setstripe --comp-set -I 0x10002 --comp-flags=^prefer,stale $tf \\\n\t\t> /dev/null 2>&1 ||\n\t\terror \"setting stale flag on component 0x10002 should fail\"\n\n\t$LFS mirror resync $tf || error \"error resync-ing file '$tf'\"\n\n\t$LFS setstripe --comp-set -I 0x10001 --comp-flags=stale $tf ||\n\t\terror \"error setting stale flag on component 0x10001\"\n\t$LFS setstripe --comp-set -I 0x20003 --comp-flags=stale $tf ||\n\t\terror \"error setting stale flag on component 0x20003\"\n\n\t! $LFS setstripe --comp-set -I 0x30004 --comp-flags=stale $tf \\\n\t\t> /dev/null 2>&1 ||\n\t\terror \"setting stale flag on component 0x30004 should fail\"\n\n\t$LFS mirror resync $tf || error \"error resync-ing file '$tf'\"\n}\nrun_test 0h \"set, clear and test flags for FLR files\"\n\ntest_0j() {\n\t$LFS mirror create -N2 $DIR/$tfile || error \"create $DIR/$tfile failed\"\n\n\tcp /etc/hosts $DIR/$tfile || error \"write to $DIR/$tfile failed\"\n\t$LFS mirror resync $DIR/$tfile || error \"resync $DIR/$tfile failed\"\n\tcmp /etc/hosts $DIR/$tfile || error \"cmp with /etc/hosts failed\"\n\n\t$LFS mirror read -N2 -o $TMP/$tfile $DIR/$tfile || \"read mirror failed\"\n\tstack_trap \"rm -f $TMP/$tfile\"\n\tcmp $TMP/$tfile $DIR/$tfile || error \"cmp with $TMP/$tfile failed\"\n\t$LFS mirror write -N2 -i /etc/passwd $DIR/$tfile || \"write failed\"\n\t$LFS setstripe --comp-set -I 65537 --comp-flags=stale $DIR/$tfile ||\n\t\terror \"set component 1 stale failed\"\n\t$LFS mirror resync $DIR/$tfile || error \"resync $DIR/$tfile failed\"\n\tcmp /etc/passwd $DIR/$tfile || error \"cmp with /etc/passwd failed\"\n}\nrun_test 0j \"test lfs mirror read/write commands\"\n\ntest_1() {\n\tlocal tf=$DIR/$tfile\n\tlocal mirror_count=16 # LUSTRE_MIRROR_COUNT_MAX\n\tlocal mirror_create_cmd=\"$LFS mirror create\"\n\tlocal stripes[0]=$OSTCOUNT\n\n\tmirror_create_cmd+=\" -N -c ${stripes[0]}\"\n\tfor ((i = 1; i < $mirror_count; i++)); do\n\t\t# add mirrors with different stripes to the file\n\t\tstripes[$i]=$((RANDOM % OSTCOUNT))\n\t\t[ ${stripes[$i]} -eq 0 ] && stripes[$i]=1\n\n\t\tmirror_create_cmd+=\" -N -c ${stripes[$i]}\"\n\tdone\n\n\t$mirror_create_cmd $tf || error \"create mirrored file $tf failed\"\n\tverify_mirror_count $tf $mirror_count\n\n\t# can't create mirrors exceeding LUSTRE_MIRROR_COUNT_MAX\n\t$LFS mirror extend -N $tf &&\n\t\terror \"Creating the $((mirror_count+1))th mirror succeeded\"\n\n\tlocal ids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' |\n\t\t\ttr '\\n' ' '))\n\n\t# verify the range of components and stripe counts\n\tfor ((i = 0; i < $mirror_count; i++)); do\n\t\tverify_comp_attr stripe-count $tf ${ids[$i]} ${stripes[$i]}\n\t\tverify_comp_extent $tf ${ids[$i]} 0 EOF\n\tdone\n}\nrun_test 1 \"create components with setstripe options\"\n\ntest_2() {\n\tlocal tf=$DIR/$tfile\n\tlocal tf2=$DIR/$tfile-2\n\n\t$LFS setstripe -E 1M -S 1M -E EOF -c 1 $tf\n\t$LFS setstripe -E 2M -S 1M -E EOF -c -1 $tf2\n\n\t$LFS mirror extend -N -f $tf2 $tf ||\n\t\terror \"merging $tf2 into $tf failed\"\n\n\tverify_mirror_count $tf 2\n\t[[ ! -e $tf2 ]] || error \"$tf2 was not unlinked\"\n}\nrun_test 2 \"create components from existing files\"\n\ntest_3() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip \"need >= 2 MDTs\" && return\n\n\tfor ((i = 0; i < 2; i++)); do\n\t\t$LFS mkdir -i $i $DIR/$tdir-$i\n\t\t$LFS setstripe -E -1 $DIR/$tdir-$i/$tfile\n\tdone\n\n\t$LFS mirror extend -N -f $DIR/$tdir-1/$tfile \\\n\t\t$DIR/$tdir-0/$tfile || error \"creating mirrors\"\n\n\t# mdt doesn't support to cancel layout lock for remote objects, do\n\t# it here manually.\n\tcancel_lru_locks mdc\n\n\t# make sure the mirrorted file was created successfully\n\t[[ $($LFS getstripe --component-count $DIR/$tdir-0/$tfile) -eq 2 ]] ||\n\t\t{ $LFS getstripe $DIR/$tdir-0/$tfile;\n\t\t\terror \"expected 2 components\"; }\n\n\t# cleanup\n\trm -rf $DIR/$tdir-*\n}\nrun_test 3 \"create components from files located on different MDTs\"\n\ntest_4() {\n\tlocal tf=$DIR/$tdir/$tfile\n\tlocal ids=()\n\n\ttest_mkdir $DIR/$tdir\n\n\t# set mirror with setstripe options to directory\n\t$LFS mirror create -N2 -E 1M -S 1M -E eof $DIR/$tdir ||\n\t\terror \"set mirror to directory error\"\n\n\t[ x$($LFS getstripe -v $DIR/$tdir | awk '/lcm_flags/{print $2}') = \\\n\t\tx\"mirrored\" ] || error \"failed to create mirrored dir\"\n\n\ttouch $tf\n\tverify_mirror_count $tf 2\n\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tverify_comp_extent $tf ${ids[0]} 0 1048576\n\tverify_comp_extent $tf ${ids[1]} 1048576 EOF\n\n\t# sub directory should inherit mirror setting from parent\n\ttest_mkdir $DIR/$tdir/td\n\t[ x$($LFS getstripe -v $DIR/$tdir/td | awk '/lcm_flags/{print $2}') = \\\n\t\tx\"mirrored\" ] || error \"failed to inherit mirror from parent\"\n\n\t# mirror extend won't be applied to directory\n\t$LFS mirror extend -N2 $DIR/$tdir &&\n\t\terror \"expecting mirror extend failure\"\n\ttrue\n}\nrun_test 4 \"Make sure mirror attributes can be inhertied from directory\"\n\ntest_5() {\n\tlocal tf=$DIR/$tfile\n\tlocal ids=()\n\n\t$MULTIOP $tf oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:T12345c ||\n\t\terror \"failed to create file with non-empty layout\"\n\t$CHECKSTAT -t file -s 12345 $tf || error \"size error: expecting 12345\"\n\n\t$LFS mirror create -N3 $tf || error \"failed to attach mirror layout\"\n\tverify_mirror_count $tf 3\n\n\t$CHECKSTAT -t file -s 12345 $tf ||\n\t\terror \"size error after attaching layout \"\n}\nrun_test 5 \"Make sure init size work for mirrored layout\"\n\n# LU=10112: disable dom+flr for phase 1\ntest_6() {\n\tlocal tf=$DIR/$tfile\n\n\t$LFS mirror create -N -E 1M -S 1M -L mdt -E eof -N -E eof $tf &&\n\t\terror \"expect failure to create mirrored file with DoM\"\n\n\t$LFS mirror create -N -E 1M -S 1M -E eof -N -E 1M -L mdt -E eof $tf &&\n\t\terror \"expect failure to create mirrored file with DoM\"\n\n\t$LFS setstripe -E 1M -S 1M -L mdt -E eof $tf\n\t$LFS mirror extend -N2 $tf &&\n\t\terror \"expect failure to extend mirror with DoM\"\n\n\t$LFS mirror create -N2 -E 1M -S 1M -E eof $tf-2\n\t$LFS mirror extend -N -f $tf $tf-2 &&\n\t\terror \"expect failure to extend mirrored file with DoM extent\"\n\n\ttrue\n}\nrun_test 6 \"DoM and FLR won't co-exist for phase 1\"\n\ntest_21() {\n\tlocal tf=$DIR/$tfile\n\tlocal tf2=$DIR/$tfile-2\n\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\" && return\n\n\t$LFS setstripe -E EOF -o 0 $tf\n\t$LFS setstripe -E EOF -o 1 $tf2\n\n\tlocal dd_count=$((RANDOM % 20 + 1))\n\tdd if=/dev/zero of=$tf bs=1M count=$dd_count oflag=sync\n\tdd if=/dev/zero of=$tf2 bs=1M count=1 seek=$((dd_count - 1)) oflag=sync\n\n\t# for zfs - sync OST dataset so that du below will return\n\t# accurate results\n\t[ \"$FSTYPE\" = \"zfs\" ] &&\n\t\tdo_nodes $(comma_list $(osts_nodes)) \"$ZPOOL sync\"\n\n\tlocal blocks=$(du -kc $tf $tf2 | awk '/total/{print $1}')\n\n\t# add component\n\t$LFS mirror extend -N -f $tf2 $tf ||\n\t\terror \"merging $tf2 into $tf failed\"\n\n\t# cancel layout lock\n\tcancel_lru_locks mdc\n\n\tlocal new_blocks=$(du -k $tf | awk '{print $1}')\n\t[ $new_blocks -eq $blocks ] ||\n\terror \"i_blocks error expected: $blocks, actual: $new_blocks\"\n}\nrun_test 21 \"glimpse should report accurate i_blocks\"\n\nget_osc_lock_count() {\n\tlocal lock_count=0\n\n\tfor idx in \"$@\"; do\n\t\tlocal osc_name\n\t\tlocal count\n\n\t\tosc_name=${FSNAME}-OST$(printf \"%04x\" $((idx-1)))-osc-'[-0-9a-f]*'\n\t\tcount=$($LCTL get_param -n ldlm.namespaces.$osc_name.lock_count)\n\t\tlock_count=$((lock_count + count))\n\tdone\n\techo $lock_count\n}\n\ntest_22() {\n\tlocal tf=$DIR/$tfile\n\n\t$LFS setstripe -E EOF -o 0 $tf\n\tdd if=/dev/zero of=$tf bs=1M count=$((RANDOM % 20 + 1))\n\n\t# add component, two mirrors located on the same OST ;-)\n\t$LFS mirror extend -N -o 0 $tf ||\n\t\terror \"extending mirrored file $tf failed\"\n\n\tsize_blocks=$(stat --format=\"%b %s\" $tf)\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\tlocal new_size_blocks=$(stat --format=\"%b %s\" $tf)\n\n\t# make sure there is no lock cached\n\t[ $(get_osc_lock_count 1) -eq 0 ] || error \"glimpse requests were sent\"\n\n\t[ \"$new_size_blocks\" = \"$size_blocks\" ] ||\n\t\techo \"size expected: $size_blocks, actual: $new_size_blocks\"\n\n\trm -f $tmpfile\n}\nrun_test 22 \"no glimpse to OSTs for READ_ONLY files\"\n\ntest_31() {\n\tlocal tf=$DIR/$tfile\n\n\t$LFS mirror create -N -o 0 -N -o 1 $tf ||\n\t\terror \"creating mirrored file $tf failed\"\n\n\t#define OBD_FAIL_GLIMPSE_IMMUTABLE 0x1A00\n\t$LCTL set_param fail_loc=0x1A00\n\n\tlocal ost_idx\n\tfor ((ost_idx = 1; ost_idx <= 2; ost_idx++)); do\n\t\tcancel_lru_locks osc\n\t\tstop_osts $ost_idx\n\n\t\tlocal tmpfile=$(mktemp)\n\t\tstat --format=\"%b %s\" $tf > $tmpfile  &\n\t\tlocal pid=$!\n\n\t\tlocal cnt=0\n\t\twhile [ $cnt -le 5 ]; do\n\t\t\tkill -0 $pid > /dev/null 2>&1 || break\n\t\t\tsleep 1\n\t\t\t((cnt += 1))\n\t\tdone\n\t\tkill -0 $pid > /dev/null 2>&1 &&\n\t\t\terror \"stat process stuck due to unavailable OSTs\"\n\n\t\t# make sure glimpse request has been sent\n\t\t[ $(get_osc_lock_count 1 2) -ne 0 ] ||\n\t\t\terror \"OST $ost_idx: no glimpse request was sent\"\n\n\t\tstart_osts $ost_idx\n\tdone\n}\nrun_test 31 \"make sure glimpse request can be retried\"\n\ntest_32() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\" && return\n\trm -f $DIR/$tfile $DIR/$tfile-2\n\n\t$LFS setstripe -E EOF -o 0 $DIR/$tfile\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1M count=$((RANDOM % 10 + 2))\n\n\tlocal fsize=$(stat -c %s $DIR/$tfile)\n\t[[ $fsize -ne 0 ]] || error \"file size is (wrongly) zero\"\n\n\tlocal cksum=$(md5sum $DIR/$tfile)\n\n\t# create a new mirror in sync mode\n\t$LFS mirror extend -N -o 1 $DIR/$tfile ||\n\t\terror \"extending mirrored file $DIR/$tfile failed\"\n\n\t# make sure the mirrored file was created successfully\n\t[ $($LFS getstripe -N $DIR/$tfile) -eq 2 ] ||\n\t\t{ $LFS getstripe $DIR/$tfile; error \"expected 2 mirrors\"; }\n\n\tdrop_client_cache\n\tstop_osts 1\n\n\t# check size is correct, glimpse request should go to the 2nd mirror\n\t$CHECKSTAT -t file -s $fsize $DIR/$tfile ||\n\t\terror \"file size error $fsize vs. $(stat -c %s $DIR/$tfile)\"\n\n\techo \"reading file from the 2nd mirror and verify checksum\"\n\t[[ \"$cksum\" == \"$(md5sum $DIR/$tfile)\" ]] ||\n\t\terror \"checksum error: expected $cksum\"\n\n\tstart_osts 1\n}\nrun_test 32 \"data should be mirrored to newly created mirror\"\n\ntest_33a() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\" && return\n\n\trm -f $DIR/$tfile $DIR/$tfile-2\n\n\t# create a file with two mirrors\n\t$LFS setstripe -E EOF -o 0 $DIR/$tfile\n\tlocal max_count=100\n\tlocal count=0\n\twhile [ $count -lt $max_count ]; do\n\t\techo \"ost1\" >> $DIR/$tfile\n\t\tcount=$((count + 1));\n\tdone\n\n\t# tmp file that will be used as mirror\n\t$LFS setstripe -E EOF -o 1 $DIR/$tfile-2\n\tcount=0\n\twhile [ $count -lt $max_count ]; do\n\t\techo \"ost2\" >> $DIR/$tfile-2\n\t\tcount=$((count + 1));\n\tdone\n\n\t# create a mirrored file\n\t$LFS mirror extend -N -f $DIR/$tfile-2 $DIR/$tfile &&\n\t\terror \"merging $DIR/$tfile-2 into $DIR/$tfile\" \\\n\t\t      \"with verification should fail\"\n\t$LFS mirror extend --no-verify -N -f $DIR/$tfile-2 $DIR/$tfile ||\n\t\terror \"merging $DIR/$tfile-2 into $DIR/$tfile\" \\\n\t\t      \"without verification failed\"\n\n\t# make sure that $tfile has two mirrors and $tfile-2 does not exist\n\t[ $($LFS getstripe -N $DIR/$tfile) -eq 2 ] ||\n\t\t{ $LFS getstripe $DIR/$tfile; error \"expected count 2\"; }\n\n\t[[ ! -e $DIR/$tfile-2 ]] || error \"$DIR/$tfile-2 was not unlinked\"\n\n\t# execpted file size\n\tlocal fsize=$((5 * max_count))\n\t$CHECKSTAT -t file -s $fsize $DIR/$tfile ||\n\t\terror \"mirrored file size is not $fsize\"\n\n\t# read file - all OSTs are available\n\techo \"reading file (data can be provided by any ost)... \"\n\tlocal rs=$(cat $DIR/$tfile | head -1)\n\t[[ \"$rs\" == \"ost1\" || \"$rs\" == \"ost2\" ]] ||\n\t\terror \"file content error: expected: \\\"ost1\\\" or \\\"ost2\\\"\"\n\n\t# read file again with ost1 failed\n\tstop_osts 1\n\tdrop_client_cache\n\n\techo \"reading file (data should be provided by ost2)...\"\n\tlocal rs=$(cat $DIR/$tfile | head -1)\n\t[[ \"$rs\" == \"ost2\" ]] ||\n\t\terror \"file content error: expected: \\\"ost2\\\", actual: \\\"$rs\\\"\"\n\n\t# remount ost1\n\tstart_osts 1\n\n\t# read file again with ost2 failed\n\tstop_osts 2\n\tdrop_client_cache\n\n\t# check size, glimpse should work\n\t$CHECKSTAT -t file -s $fsize $DIR/$tfile ||\n\t\terror \"mirrored file size is not $fsize\"\n\n\techo \"reading file (data should be provided by ost1)...\"\n\tlocal rs=$(cat $DIR/$tfile | head -1)\n\t[[ \"$rs\" == \"ost1\" ]] ||\n\t\terror \"file content error: expected: \\\"ost1\\\", actual: \\\"$rs\\\"\"\n\n\tstart_osts 2\n}\nrun_test 33a \"read can choose available mirror to read\"\n\ntest_33b() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\" && return\n\n\trm -f $DIR/$tfile\n\n\tstack_trap \"rm -f $DIR/$tfile\" EXIT\n\n\t# create a file with two mirrors on OST0000 and OST0001\n\t$LFS setstripe -N -Eeof -o0 -N -Eeof -o1 $DIR/$tfile\n\n\t# make sure that $tfile has two mirrors\n\t[ $($LFS getstripe -N $DIR/$tfile) -eq 2 ] ||\n\t\t{ $LFS getstripe $DIR/$tfile; error \"expected count 2\"; }\n\n\t# write 50M\n\tdd if=/dev/urandom of=$DIR/$tfile bs=2M count=25 ||\n\t\terror \"write failed for $DIR/$tfile\"\n\t$LFS mirror resync $DIR/$tfile || error \"resync failed for $DIR/$tfile\"\n\tverify_flr_state $DIR/$tfile \"ro\"\n\tdrop_client_cache\n\n\tls -l $DIR/$tfile\n\n\t# read file - all OSTs are available\n\techo \"reading file (data can be provided by any ost)... \"\n\tlocal t1=$SECONDS\n\ttime cat $DIR/$tfile > /dev/null || error \"read all\"\n\tlocal t2=$SECONDS\n\tra=$((t2 - t1))\n\n\t# read file again with ost1 {OST0000} failed\n\tstop_osts 1\n\tdrop_client_cache\n\techo \"reading file (data should be provided by ost2)...\"\n\tt1=$SECONDS\n\ttime cat $DIR/$tfile > /dev/null || error \"read ost2\"\n\tt2=$SECONDS\n\tr1=$((t2 - t1))\n\n\t# remount ost1\n\tstart_osts 1\n\n\t# read file again with ost2 {OST0001} failed\n\tstop_osts 2\n\tdrop_client_cache\n\n\techo \"reading file (data should be provided by ost1)...\"\n\tt1=$SECONDS\n\ttime cat $DIR/$tfile > /dev/null || error \"read ost1\"\n\tt2=$SECONDS\n\tr2=$((t2 - t1))\n\n\t# remount ost2\n\tstart_osts 2\n\n\t[ $((r1 * 100)) -gt $((ra * 105)) -a $r1 -gt $((ra + 2)) ] &&\n\t\terror \"read mirror too slow without ost1, from $ra to $r1\"\n\t[ $((r2 * 100)) -gt $((ra * 105)) -a $r2 -gt $((ra + 2)) ] &&\n\t\terror \"read mirror too slow without ost2, from $ra to $r2\"\n\n\twait_osc_import_ready client ost2\n}\nrun_test 33b \"avoid reading from unhealthy mirror\"\n\ntest_33c() {\n\t[[ $OSTCOUNT -lt 3 ]] && skip \"need >= 3 OSTs\" && return\n\n\trm -f $DIR/$tfile\n\n\tstack_trap \"rm -f $DIR/$tfile\" EXIT\n\n\t# create a file with two mirrors\n\t# mirror1: {OST0000, OST0001}\n\t# mirror2: {OST0001, OST0002}\n\t$LFS setstripe -N -Eeof -c2 -o0,1 -N -Eeof -c2 -o1,2 $DIR/$tfile\n\n\t# make sure that $tfile has two mirrors\n\t[ $($LFS getstripe -N $DIR/$tfile) -eq 2 ] ||\n\t\t{ $LFS getstripe $DIR/$tfile; error \"expected count 2\"; }\n\n\t# write 50M\n\tdd if=/dev/urandom of=$DIR/$tfile bs=2M count=25 ||\n\t\terror \"write failed for $DIR/$tfile\"\n\t$LFS mirror resync $DIR/$tfile || error \"resync failed for $DIR/$tfile\"\n\tverify_flr_state $DIR/$tfile \"ro\"\n\tdrop_client_cache\n\n\tls -l $DIR/$tfile\n\n\t# read file - all OSTs are available\n\techo \"reading file (data can be provided by any ost)... \"\n\ttime cat $DIR/$tfile > /dev/null || error \"read all\"\n\n\t# read file again with ost2 (OST0001) failed\n\tstop_osts 2\n\tdrop_client_cache\n\n\techo \"reading file (data should be provided by ost1 and ost3)...\"\n\ttime cat $DIR/$tfile > /dev/null || error \"read ost1 & ost3\"\n\n\t# remount ost2\n\tstart_osts 2\n\n\twait_osc_import_ready client ost2\n}\nrun_test 33c \"keep reading among unhealthy mirrors\"\n\ntest_34a() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\trm -f $DIR/$tfile $DIR/$tfile-2 $DIR/$tfile-ref\n\n\t# reference file\n\t$LFS setstripe -o 0 $DIR/$tfile-ref\n\tdd if=/dev/urandom of=$DIR/$tfile-ref bs=1M count=3\n\n\t# create a file with two mirrors\n\t$LFS setstripe -E -1 -o 0,1 -S 1M $DIR/$tfile\n\tdd if=$DIR/$tfile-ref of=$DIR/$tfile bs=1M\n\n\t$LFS setstripe -E -1 -o 2,3 -S 1M $DIR/$tfile-2\n\tdd if=$DIR/$tfile-ref of=$DIR/$tfile-2 bs=1M\n\n\t$CHECKSTAT -t file -s $((3 * 1024 * 1024)) $DIR/$tfile ||\n\t\terror \"mirrored file size is not 3M\"\n\n\t# merge a mirrored file\n\t$LFS mirror extend -N -f $DIR/$tfile-2 $DIR/$tfile ||\n\t\terror \"merging $DIR/$tfile-2 into $DIR/$tfile failed\"\n\n\tcancel_lru_locks osc\n\n\t# stop two OSTs, so the 2nd stripe of the 1st mirror and\n\t# the 1st stripe of the 2nd mirror will be inaccessible, ...\n\tstop_osts 2 3\n\n\techo \"comparing files ... \"\n\n\t# however, read can still return the correct data. It should return\n\t# the 1st stripe from mirror 1 and 2st stripe from mirror 2.\n\tcmp -n 2097152 <(rwv -f $DIR/$tfile -r -o -n 1 2097152) \\\n\t\t$DIR/$tfile-ref || error \"file reading error\"\n\n\tstart_osts 2 3\n}\nrun_test 34a \"read mirrored file with multiple stripes\"\n\ntest_34b() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\trm -f $DIR/$tfile $DIR/$tfile-2 $DIR/$tfile-ref\n\n\t# reference file\n\t$LFS setstripe -o 0 $DIR/$tfile-ref\n\tdd if=/dev/urandom of=$DIR/$tfile-ref bs=1M count=3\n\n\t$LFS setstripe -E 1M -S 1M -o 0 -E eof -o 1 $DIR/$tfile\n\tdd if=$DIR/$tfile-ref of=$DIR/$tfile bs=1M\n\n\t$LFS setstripe -E 1M -S 1M -o 2 -E eof -o 3 $DIR/$tfile-2\n\tdd if=$DIR/$tfile-ref of=$DIR/$tfile-2 bs=1M\n\n\t$CHECKSTAT -t file -s $((3 * 1024 * 1024)) $DIR/$tfile ||\n\t\terror \"mirrored file size is not 3M\"\n\n\t# merge a mirrored file\n\t$LFS mirror extend -N -f $DIR/$tfile-2 $DIR/$tfile ||\n\t\terror \"merging $DIR/$tfile-2 into $DIR/$tfile failed\"\n\n\tcancel_lru_locks osc\n\n\t# stop two OSTs, so the 2nd component of the 1st mirror and\n\t# the 1st component of the 2nd mirror will be inaccessible, ...\n\tstop_osts 2 3\n\n\techo \"comparing files ... \"\n\n\t# however, read can still return the correct data. It should return\n\t# the 1st stripe from mirror 1 and 2st stripe from mirror 2.\n\tcmp -n 2097152 <(rwv -f $DIR/$tfile -r -o -n 1 2097152) \\\n\t\t$DIR/$tfile-ref || error \"file reading error\"\n\n\tstart_osts 2 3\n}\nrun_test 34b \"read mirrored file with multiple components\"\n\ntest_35() {\n\tlocal tf=$DIR/$tfile\n\n\t$LFS setstripe -E eof $tf\n\n\t# add an out-of-sync mirror to the file\n\t$LFS mirror extend -N -c 2 $tf ||\n\t\terror \"extending mirrored file $tf failed\"\n\n\t$MULTIOP $tf oO_WRONLY:c ||\n\t\terror \"write open a mirrored file failed\"\n\n\t# truncate file should return error\n\t$TRUNCATE $tf 100 || error \"error truncating a mirrored file\"\n}\nrun_test 35 \"allow to write to mirrored files\"\n\nverify_ost_layout_version() {\n\tlocal tf=$1\n\n\t# get file layout version\n\tlocal flv=$($LFS getstripe $tf | awk '/lcm_layout_gen/{print $2}')\n\n\t# layout version from OST objects\n\tlocal olv=$($MULTIOP $tf oXc | awk '/ostlayoutversion/{print $2}')\n\n\t[ $flv -eq $olv ] || error \"layout version mismatch: $flv vs. $olv\"\n}\n\ncreate_file_36() {\n\tlocal tf\n\n\tfor tf in \"$@\"; do\n\t\t$LFS setstripe -E 1M -S 1M -E 2M -E 4M -E eof -c -1 $tf\n\t\t$LFS setstripe -E 3M -S 1M -E 6M -E eof -c -1 $tf-tmp\n\n\t\t$LFS mirror extend -N -f $tf-tmp $tf ||\n\t\t\terror \"merging $tf-tmp into $tf failed\"\n\tdone\n}\n\ntest_36() {\n\tlocal tf=$DIR/$tfile\n\n\tcreate_file_36 $tf $tf-2 $tf-3\n\n\t[ $($LFS getstripe -N $tf) -gt 1 ] || error \"wrong mirror count\"\n\n\t# test case 1 - check file write and verify layout version\n\t$MULTIOP $tf oO_WRONLY:c ||\n\t\terror \"write open a mirrored file failed\"\n\n\t# write open file should not return error\n\t$MULTIOP $tf oO_WRONLY:w1024Yc || error \"write mirrored file error\"\n\n\t# instantiate components should work\n\tdd if=/dev/zero of=$tf bs=1M count=12 || error \"write file error\"\n\n\t# verify OST layout version\n\tverify_ost_layout_version $tf\n\n\t# test case 2\n\tlocal mds_facet=mds$(($($LFS getstripe -m $tf-2) + 1))\n\n\tlocal delay_sec=10\n\tdo_facet $mds_facet $LCTL set_param fail_val=$delay_sec\n\n\t#define OBD_FAIL_FLR_LV_DELAY 0x1A01\n\tdo_facet $mds_facet $LCTL set_param fail_loc=0x1A01\n\n\t# write should take at least $fail_loc seconds and succeed\n\tlocal st=$(date +%s)\n\t$MULTIOP $tf-2 oO_WRONLY:w1024Yc || error \"write mirrored file error\"\n\n\t[ $(date +%s) -ge $((st+delay_sec)) ] ||\n\t\terror \"write finished before layout version is transmitted\"\n\n\t# verify OST layout version\n\tverify_ost_layout_version $tf\n\n\tdo_facet $mds_facet $LCTL set_param fail_loc=0\n\n\t# test case 3\n\tmds_idx=mds$(($($LFS getstripe -m $tf-3) + 1))\n\n\t#define OBD_FAIL_FLR_LV_INC 0x1A02\n\tdo_facet $mds_facet $LCTL set_param fail_loc=0x1A02\n\n\t# write open file should return error\n\t$MULTIOP $tf-3 oO_WRONLY:O_SYNC:w1024c &&\n\t\terror \"write a mirrored file succeeded\" || true\n\n\tdo_facet $mds_facet $LCTL set_param fail_loc=0\n}\nrun_test 36 \"write to mirrored files\"\n\ncreate_files_37() {\n\tlocal tf\n\tlocal fsize=$1\n\n\techo \"create test files with size $fsize ..\"\n\n\tshift\n\tfor tf in \"$@\"; do\n\t\t$LFS setstripe -E 1M -S 1M -c 1 -E eof -c -1 $tf\n\n\t\tdd if=/dev/urandom of=$tf bs=1M count=16 &> /dev/null\n\t\t$TRUNCATE $tf $fsize\n\tdone\n}\n\ntest_37()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.11.57) ] &&\n\t\tskip \"Need MDS version at least 2.11.57\"\n\n\tlocal tf=$DIR/$tfile\n\tlocal tf2=$DIR/$tfile-2\n\tlocal tf3=$DIR/$tfile-3\n\tlocal tf4=$DIR/$tfile-4\n\n\tcreate_files_37 $((RANDOM + 15 * 1048576)) $tf $tf2 $tf3\n\trm -f $tf4\n\tcp $tf $tf4\n\n\t# assume the mirror id will be 1, 2, and 3\n\tdeclare -A checksums\n\tchecksums[1]=$(cat $tf | md5sum)\n\tchecksums[2]=$(cat $tf2 | md5sum)\n\tchecksums[3]=$(cat $tf3 | md5sum)\n\n\tprintf '%s\\n' \"${checksums[@]}\"\n\n\t# merge these files into a mirrored file\n\t$LFS mirror extend --no-verify -N -f $tf2 $tf ||\n\t\terror \"merging $tf2 into $tf failed\"\n\t$LFS mirror extend --no-verify -N -f $tf3 $tf ||\n\t\terror \"merging $tf3 into $tf failed\"\n\n\tget_mirror_ids $tf\n\n\t# verify mirror read, checksums should equal to the original files'\n\techo \"Verifying mirror read ..\"\n\n\tlocal sum\n\tfor i in ${mirror_array[@]}; do\n\t\t$LCTL set_param ldlm.namespaces.*.lru_size=clear > /dev/null\n\t\tsum=$($LFS mirror read -N $i $tf | md5sum)\n\t\t[ \"$sum\" = \"${checksums[$i]}\" ] ||\n\t\t\terror \"$i: mismatch: \\'${checksums[$i]}\\' vs. \\'$sum\\'\"\n\tdone\n\n\t# verify mirror write\n\techo \"Verifying mirror write ..\"\n\t$LFS mirror write -N2 $tf < $tf4\n\n\tsum=$($LFS mirror read -N2 $tf | md5sum)\n\t[[ \"$sum\" = \"${checksums[1]}\" ]] ||\n\t\terror \"2: mismatch \\'${checksums[1]}\\' vs. \\'$sum\\'\"\n\n\t# verify mirror copy, write to this mirrored file will invalidate\n\t# the other two mirrors\n\techo \"Verifying mirror copy ..\"\n\n\tlocal osts=$(comma_list $(osts_nodes))\n\n\t$LFS mirror copy -i ${mirror_array[0]} -o-1 $tf ||\n\t\terror \"mirror copy error\"\n\n\t# verify copying is successful by checking checksums\n\tremount_client $MOUNT\n\tfor i in ${mirror_array[@]}; do\n\t\tsum=$($LFS mirror read -N $i $tf | md5sum)\n\t\t[ \"$sum\" = \"${checksums[1]}\" ] ||\n\t\t\terror \"$i: mismatch checksum after copy \\'$sum\\'\"\n\tdone\n\n\trm -f $tf\n}\nrun_test 37 \"mirror I/O API verification\"\n\ntest_38() {\n\tlocal tf=$DIR/$tfile\n\tlocal ref=$DIR/${tfile}-ref\n\n\t$LFS setstripe -E 1M -S 1M -c 1 -E 4M -c 2 -E eof -c -1 $tf ||\n\t\terror \"creating $tf failed\"\n\t$LFS setstripe -E 2M -S 1M -c 1 -E 6M -c 2 -E 8M -c -1 -E eof -c -1 \\\n\t\t$tf-2 || error \"creating $tf-2 failed\"\n\t$LFS setstripe -E 4M -c 1 -E 8M -c 2 -E eof -c -1 $tf-3 ||\n\t\terror \"creating $tf-3 failed\"\n\n\t# instantiate all components\n\t$LFS mirror extend -N -f $tf-2 $tf ||\n\t\terror \"merging $tf-2 into $tf failed\"\n\t$LFS mirror extend -N -f $tf-3 $tf ||\n\t\terror \"merging $tf-3 into $tf failed\"\n\t$LFS mirror extend -N -c 1 $tf ||\n\t\terror \"extending mirrored file $tf failed\"\n\n\tverify_flr_state $tf \"ro\"\n\n\tdd if=/dev/urandom of=$ref  bs=1M count=16 &> /dev/null\n\n\tlocal fsize=$((RANDOM << 8 + 1048576))\n\t$TRUNCATE $ref $fsize\n\n\tlocal ref_cksum=$(cat $ref | md5sum)\n\n\t# case 1: verify write to mirrored file & resync work\n\tcp $ref $tf || error \"copy from $ref to $f error\"\n\tverify_flr_state $tf \"wp\"\n\n\tlocal file_cksum=$(cat $tf | md5sum)\n\t[ \"$file_cksum\" = \"$ref_cksum\" ] || error \"write failed, cksum mismatch\"\n\n\tget_mirror_ids $tf\n\techo \"mirror IDs: ${mirror_array[@]}\"\n\n\tlocal valid_mirror stale_mirror id mirror_cksum\n\tfor id in \"${mirror_array[@]}\"; do\n\t\tmirror_cksum=$($LFS mirror read -N $id $tf | md5sum)\n\t\t[ \"$ref_cksum\" == \"$mirror_cksum\" ] &&\n\t\t\t{ valid_mirror=$id; continue; }\n\n\t\tstale_mirror=$id\n\tdone\n\n\t[ -z \"$stale_mirror\" ] && error \"stale mirror doesn't exist\"\n\t[ -z \"$valid_mirror\" ] && error \"valid mirror doesn't exist\"\n\n\tmirror_io resync $tf || error \"resync failed\"\n\tverify_flr_state $tf \"ro\"\n\n\tmirror_cksum=$($LFS mirror read -N $stale_mirror $tf | md5sum)\n\t[ \"$file_cksum\" = \"$ref_cksum\" ] || error \"resync failed\"\n\n\t# case 2: inject an error to make mirror_io exit after changing\n\t# the file state to sync_pending so that we can start a concurrent\n\t# write.\n\t$MULTIOP $tf oO_WRONLY:w$((RANDOM % 1048576 + 1024))c\n\tverify_flr_state $tf \"wp\"\n\n\tmirror_io resync -e resync_start $tf && error \"resync succeeded\"\n\tverify_flr_state $tf \"sp\"\n\n\t# from sync_pending to write_pending\n\t$MULTIOP $tf oO_WRONLY:w$((RANDOM % 1048576 + 1024))c\n\tverify_flr_state $tf \"wp\"\n\n\tmirror_io resync -e resync_start $tf && error \"resync succeeded\"\n\tverify_flr_state $tf \"sp\"\n\n\t# from sync_pending to read_only\n\tmirror_io resync $tf || error \"resync failed\"\n\tverify_flr_state $tf \"ro\"\n}\nrun_test 38 \"resync\"\n\ntest_39() {\n\tlocal tf=$DIR/$tfile\n\n\trm -f $tf\n\t$LFS mirror create -N2 -E1m -c1 -S1M -E-1 $tf ||\n\terror \"create PFL file $tf failed\"\n\n\tverify_mirror_count $tf 2\n\tverify_comp_count $tf 4\n\n\trm -f $tf || error \"delete $tf failed\"\n}\nrun_test 39 \"check FLR+PFL (a.k.a. PFLR) creation\"\n\ntest_40() {\n\tlocal tf=$DIR/$tfile\n\tlocal ops\n\n\tfor ops in \"conv=notrunc\" \"\"; do\n\t\trm -f $tf\n\n\t\t$LFS mirror create -N -E 2M -S 1M -E 4M -E -1 --flags=prefer \\\n\t\t\t\t   -N -E 1M -E 2M -E 4M -E -1 $tf ||\n\t\t\terror \"create PFLR file $tf failed\"\n\t\tdd if=/dev/zero of=$tf $ops bs=1M seek=2 count=1 ||\n\t\t\terror \"write PFLR file $tf failed\"\n\n\t\tlfs getstripe -vy $tf\n\n\t\tlocal flags\n\n\t\t# file mirror state should be write_pending\n\t\tflags=$($LFS getstripe -v $tf | awk '/lcm_flags:/ { print $2 }')\n\t\t[ $flags = wp ] ||\n\t\terror \"file mirror state $flags\"\n\t\t# the 1st component (in mirror 1) should be inited\n\t\tverify_comp_attr lcme_flags $tf 0x10001 init\n\t\t# the 2nd component (in mirror 1) should be inited\n\t\tverify_comp_attr lcme_flags $tf 0x10002 init\n\t\t# the 3rd component (in mirror 1) should be uninited\n\t\tverify_comp_attr lcme_flags $tf 0x10003 prefer\n\t\t# the 4th component (in mirror 2) should be inited\n\t\tverify_comp_attr lcme_flags $tf 0x20004 init\n\t\t# the 5th component (in mirror 2) should be uninited\n\t\tverify_comp_attr lcme_flags $tf 0x20005 0\n\t\t# the 6th component (in mirror 2) should be stale\n\t\tverify_comp_attr lcme_flags $tf 0x20006 stale\n\t\t# the 7th component (in mirror 2) should be uninited\n\t\tif [[ x$ops = \"xconv=notrunc\" ]]; then\n\t\t\tverify_comp_attr lcme_flags $tf 0x20007 0\n\t\telif [[ x$ops = \"x\" ]]; then\n\t\t\tverify_comp_attr lcme_flags $tf 0x20007 stale\n\t\tfi\n\tdone\n\n\trm -f $tf || error \"delete $tf failed\"\n}\nrun_test 40 \"PFLR rdonly state instantiation check\"\n\ntest_41() {\n\tlocal tf=$DIR/$tfile\n\n\trm -f $tf $tf-1\n\techo \" **create two FLR files $tf $tf-1\"\n\t$LFS mirror create -N -E 2M -S 1M -E 4M -E -1 \\\n\t\t\t   -N -E 1M -E 2M -E 3M -E -1 $tf ||\n\t\terror \"create PFLR file $tf failed\"\n\t$LFS mirror create -N -E 2M -S 1M -E eof \\\n\t\t\t   -N -E 1M -E eof --flags prefer \\\n\t\t\t   -N -E 4m -E eof $tf-1 ||\n\t\terror \"create PFLR file $tf-1 failed\"\n\n\t# file should be in ro status\n\techo \" **verify files be RDONLY\"\n\tverify_flr_state $tf \"ro\"\n\tverify_flr_state $tf-1 \"ro\"\n\n\t# write data in [0, 2M)\n\tdd if=/dev/zero of=$tf bs=1M count=2 conv=notrunc ||\n\t\terror \"writing $tf failed\"\n\tdd if=/dev/urandom of=$tf-1 bs=1M count=4 conv=notrunc ||\n\t\terror \"writing $tf-1 failed\"\n\n\tlocal sum0=$(cat $tf-1 | md5sum)\n\n\techo \" **verify files be WRITE_PENDING\"\n\tverify_flr_state $tf \"wp\"\n\tverify_flr_state $tf-1 \"wp\"\n\n\t# file should have stale component\n\techo \" **verify files have stale component\"\n\t$LFS getstripe $tf | grep lcme_flags | grep stale > /dev/null ||\n\t\terror \"after writing $tf, it does not contain stale component\"\n\t$LFS getstripe $tf-1 | grep lcme_flags | grep stale > /dev/null ||\n\t\terror \"after writing $tf-1, it does not contain stale component\"\n\n\techo \" **full resync\"\n\t$LFS mirror resync $tf $tf-1 || error \"mirror resync $tf $tf-1 failed\"\n\n\techo \" **verify $tf-1 data consistency in all mirrors\"\n\tfor i in 1 2 3; do\n\t\tlocal sum=$($LFS mirror read -N$i $tf-1 | md5sum)\n\t\t[[ \"$sum\" = \"$sum0\" ]] ||\n\t\t\terror \"$tf-1.$i: checksum mismatch: $sum != $sum0\"\n\tdone\n\n\techo \" **verify files be RDONLY\"\n\tverify_flr_state $tf \"ro\"\n\tverify_flr_state $tf-1 \"ro\"\n\n\t# file should not have stale component\n\techo \" **verify files do not contain stale component\"\n\t$LFS getstripe $tf | grep lcme_flags | grep stale &&\n\t\terror \"after resyncing $tf, it contains stale component\"\n\t$LFS getstripe $tf-1 | grep lcme_flags | grep stale &&\n\t\terror \"after resyncing $tf, it contains stale component\"\n\n\t# verify partial resync\n\techo \" **write $tf-1 for partial resync test\"\n\tdd if=/dev/zero of=$tf-1 bs=1M count=2 conv=notrunc ||\n\t\terror \"writing $tf-1 failed\"\n\n\techo \" **only resync mirror 2\"\n\tverify_flr_state $tf-1 \"wp\"\n\t$LFS mirror resync --only 2 $tf-1 ||\n\t\terror \"resync mirror 2 of $tf-1 failed\"\n\tverify_flr_state $tf \"ro\"\n\n\t# resync synced mirror\n\techo \" **resync mirror 2 again\"\n\t$LFS mirror resync --only 2 $tf-1 ||\n\t\terror \"resync mirror 2 of $tf-1 failed\"\n\tverify_flr_state $tf \"ro\"\n\techo \" **verify $tf-1 contains stale component\"\n\t$LFS getstripe $tf-1 | grep lcme_flags | grep stale > /dev/null ||\n\t\terror \"after writing $tf-1, it does not contain stale component\"\n\n\techo \" **full resync $tf-1\"\n\t$LFS mirror resync $tf-1 || error \"resync of $tf-1 failed\"\n\tverify_flr_state $tf \"ro\"\n\techo \" **full resync $tf-1 again\"\n\t$LFS mirror resync $tf-1 || error \"resync of $tf-1 failed\"\n\techo \" **verify $tf-1 does not contain stale component\"\n\t$LFS getstripe $tf | grep lcme_flags | grep stale &&\n\t\terror \"after resyncing $tf, it contains stale component\"\n\n\treturn 0\n}\nrun_test 41 \"lfs mirror resync check\"\n\ntest_42() {\n\t[[ $OSTCOUNT -lt 4 ]] && skip \"need >= 4 OSTs\" && return\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal mirror_cmd=\"$LFS mirror verify\"\n\tlocal i\n\n\t# create parent directory\n\tmkdir $td || error \"mkdir $td failed\"\n\n\t$mirror_cmd &> /dev/null && error \"no file name given\"\n\t$mirror_cmd $tf &> /dev/null && error \"cannot stat file $tf\"\n\t$mirror_cmd $td &> /dev/null && error \"$td is not a regular file\"\n\n\t# create mirrored files\n\t$LFS mirror create -N -E 4M -S 1M -E 10M -E EOF $tf ||\n\t\terror \"create mirrored file $tf failed\"\n\t$LFS mirror create -N -E 2M -S 1M -E EOF \\\n\t\t\t   -N -E 6M -E 8M -E EOF \\\n\t\t\t   -N -E 16M -E EOF $tf-1 ||\n\t\terror \"create mirrored file $tf-1 failed\"\n\t$LFS mirror create -N -c 2 -o 1,3 -N -S 2M -c -1 $tf-2 ||\n\t\terror \"create mirrored file $tf-2 failed\"\n\n\t# write data in [0, 10M)\n\tfor i in $tf $tf-1 $tf-2; do\n\t\tyes | dd of=$i bs=1M count=10 iflag=fullblock conv=notrunc ||\n\t\t\terror \"write $i failed\"\n\tdone\n\n\t# resync the mirrored files\n\t$LFS mirror resync $tf-1 $tf-2 ||\n\t\terror \"resync $tf-1 $tf-2 failed\"\n\n\t# verify the mirrored files\n\t$mirror_cmd $tf-1 $tf-2 ||\n\t\terror \"verify $tf-1 $tf-2 failed\"\n\n\tget_mirror_ids $tf-1\n\t$mirror_cmd --only ${mirror_array[0]} $tf-1 &> /dev/null &&\n\t\terror \"at least 2 mirror ids needed with '--only' option\"\n\t$mirror_cmd --only ${mirror_array[0]},${mirror_array[1]} $tf-1 $tf-2 \\\n\t\t&> /dev/null &&\n\t\terror \"'--only' option cannot be used upon multiple files\"\n\t$mirror_cmd --only 65534,${mirror_array[0]},65535 $tf-1 &&\n\t\terror \"invalid specified mirror ids\"\n\n\t# change the content of $tf and merge it into $tf-1\n\tfor i in 6 10; do\n\t\techo a | dd of=$tf bs=1M seek=$i conv=notrunc ||\n\t\t\terror \"change $tf with seek=$i failed\"\n\t\techo b | dd of=$tf-1 bs=1M seek=$i conv=notrunc ||\n\t\t\terror \"change $tf-1 with seek=$i failed\"\n\tdone\n\n\t$LFS mirror resync $tf-1 || error \"resync $tf-1 failed\"\n\t$LFS mirror extend --no-verify -N -f $tf $tf-1 ||\n\t\terror \"merge $tf into $tf-1 failed\"\n\n\t# verify the mirrored files\n\techo \"Verify $tf-1 without -v option:\"\n\t$mirror_cmd $tf-1 &&\n\t\terror \"verify $tf-1 should fail\" || echo \"PASS\"\n\n\techo \"Verify $tf-1 with -v option:\"\n\t$mirror_cmd -v $tf-1 &&\n\t\terror \"verify $tf-1 should fail\"\n\n\tget_mirror_ids $tf-1\n\techo \"Verify $tf-1 with --only option:\"\n\t$mirror_cmd -v --only ${mirror_array[1]},${mirror_array[-1]} $tf-1 &&\n\t\terror \"verify $tf-1 with mirror ${mirror_array[1]} and\" \\\n\t\t      \"${mirror_array[-1]} should fail\"\n\n\t$mirror_cmd --only ${mirror_array[0]},${mirror_array[1]} $tf-1 ||\n\t\terror \"verify $tf-1 with mirror ${mirror_array[0]} and\" \\\n\t\t      \"${mirror_array[1]} should succeed\"\n\n\t# set stale components in $tf-1\n\tfor i in 0x40002 0x40003; do\n\t\t$LFS setstripe --comp-set -I$i --comp-flags=stale $tf-1 ||\n\t\t\terror \"set stale flag on component $i failed\"\n\tdone\n\n\t# verify the mirrored file\n\techo \"Verify $tf-1 with stale components:\"\n\t$mirror_cmd -vvv $tf-1 ||\n\t\terror \"verify $tf-1 with stale components should succeed\"\n\n\techo \"Verify $tf-1 with stale components and --only option:\"\n\t$mirror_cmd -vvv --only ${mirror_array[1]},${mirror_array[-1]} $tf-1 ||\n\t\terror \"verify $tf-1 with mirror ${mirror_array[1]} and\" \\\n\t\t      \"${mirror_array[-1]} should succeed\"\n}\nrun_test 42 \"lfs mirror verify\"\n\n# inactivate one OST && write && restore the OST\nwrite_file_43() {\n\tlocal file=$1\n\tlocal ost=$2\n\tlocal PARAM=\"osp.${FSNAME}-OST000${ost}-osc-M*.active\"\n\tlocal wait\n\n\twait=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.*MDT0000-*.qos_maxage\")\n\twait=${wait%%[^0-9]*}\n\n\techo \"  **deactivate OST$ost, waiting for $((wait*2+2)) seconds\"\n\t$(do_facet $SINGLEMDS \"$LCTL set_param -n $PARAM 0\")\n\t# lod_qos_statfs_update needs 2*$wait seconds to refresh targets statfs\n\tsleep $(($wait * 2 + 2))\n\techo \"  **write $file\"\n\tdd if=/dev/zero of=$file bs=1M count=1 || error \"write $file failed\"\n\techo \"  **restore activating OST$ost, waiting for $((wait*2+2)) seconds\"\n\t$(do_facet $SINGLEMDS \"$LCTL set_param -n $PARAM 1\")\n\tsleep $((wait * 2 + 2))\n\n\tlocal flags=$($LFS getstripe -v $file | awk '/lcm_flags:/ { print $2 }')\n\t[ $flags = wp ] || error \"file mirror state $flags != wp\"\n}\n\ntest_43() {\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\" && return\n\n\tlocal tf=$DIR/$tfile\n\tlocal flags\n\n\trm -f $tf\n\t##   mirror 0  ost (0, 1)\n\t##   mirror 1  ost (1, 2)\n\t##   mirror 2  ost (2, 0)\n\t$LFS mirror create -N -Eeof -c2 -o0,1 -N -Eeof -c2 -o1,2 \\\n\t\t-N -Eeof -c2 -o2,0 $tf ||\n\t\terror \"create 3 mirrors file $tf failed\"\n\n\t################## OST0 ###########################################\n\twrite_file_43 $tf 0\n\techo \"  **verify components\"\n\tverify_comp_attr lcme_flags $tf 0x10001 init,stale\n\tverify_comp_attr lcme_flags $tf 0x20002 init\n\tverify_comp_attr lcme_flags $tf 0x30003 init,stale\n\n\t# resync\n\techo \"  **resync $tf\"\n\t$LFS mirror resync $tf\n\tflags=$($LFS getstripe -v $tf | awk '/lcm_flags:/ { print $2 }')\n\t[ $flags = ro ] || error \"file mirror state $flags != ro\"\n\n\t################## OST1 ###########################################\n\twrite_file_43 $tf 1\n\techo \"  **verify components\"\n\tverify_comp_attr lcme_flags $tf 0x10001 init,stale\n\tverify_comp_attr lcme_flags $tf 0x20002 init,stale\n\tverify_comp_attr lcme_flags $tf 0x30003 init\n\n\t# resync\n\techo \"  **resync $tf\"\n\t$LFS mirror resync $tf\n\tflags=$($LFS getstripe -v $tf | awk '/lcm_flags:/ { print $2 }')\n\t[ $flags = ro ] || error \"file mirror state $flags != ro\"\n\n\t################## OST2 ###########################################\n\twrite_file_43 $tf 2\n\techo \"  **verify components\"\n\tverify_comp_attr lcme_flags $tf 0x10001 init\n\tverify_comp_attr lcme_flags $tf 0x20002 init,stale\n\tverify_comp_attr lcme_flags $tf 0x30003 init,stale\n}\nrun_test 43 \"mirror pick on write\"\n\ntest_44() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\trm -rf $DIR/$tdir\n\trm -rf $DIR/$tdir-1\n\tlocal tf=$DIR/$tdir/$tfile\n\tlocal tf1=$DIR/$tdir-1/$tfile-1\n\n\t$LFS setdirstripe -i 0 -c 1 $DIR/$tdir ||\n\t\terror \"create directory failed\"\n\t$LFS setdirstripe -i 1 -c 1 $DIR/$tdir-1 ||\n\t\terror \"create remote directory failed\"\n\trm -f $tf $tf1 $tf.mirror~2\n\t# create file with 4 mirrors\n\t$LFS mirror create -N -E 2M -S 1M -E 4M -E -1 \\\n\t\t\t   -N -E 1M -E 2M -E 3M -E -1 -N2 $tf ||\n\t\terror \"create PFLR file $tf failed\"\n\n\t# file should be in ro status\n\tverify_flr_state $tf \"ro\"\n\n\t# write data in [0, 3M)\n\tdd if=/dev/urandom of=$tf bs=1M count=3 conv=notrunc ||\n\t\terror \"writing $tf failed\"\n\n\tverify_flr_state $tf \"wp\"\n\n\t# disallow destroying the last non-stale mirror\n\t! $LFS mirror delete --mirror-id 1 $tf > /dev/null 2>&1 ||\n\t\terror \"destroying mirror 1 should fail\"\n\n\t# synchronize all mirrors of the file\n\t$LFS mirror resync $tf || error \"mirror resync $tf failed\"\n\n\tverify_flr_state $tf \"ro\"\n\n\t# split mirror 1\n\t$LFS mirror split --mirror-id 1 -f $tf1 $tf ||\n\t\terror \"split to $tf1 failed\"\n\n\tlocal idx0=$($LFS getstripe -m $tf)\n\tlocal idx1=$($LFS getstripe -m $tf1)\n\n\t[[ x$idx0 == x0 ]] || error \"$tf is not on MDT0\"\n\t[[ x$idx1 == x1 ]] || error \"$tf1 is not on MDT1\"\n\n\t# verify mirror count\n\tverify_mirror_count $tf 3\n\tverify_mirror_count $tf1 1\n\n\t$LFS mirror split --mirror-id 2 $tf ||\n\t\terror \"split mirror 2 failed\"\n\n\tverify_mirror_count $tf 2\n\tverify_mirror_count $tf.mirror~2 1\n\n\t$LFS setstripe --comp-set -I 0x30008 --comp-flags=stale $tf ||\n\t\terror \"setting stale flag on component 0x30008 failed\"\n\n\t# disallow destroying the last non-stale mirror\n\t! $LFS mirror split --mirror-id 4 -d $tf > /dev/null 2>&1 ||\n\t\terror \"destroying mirror 4 should fail\"\n\n\t$LFS mirror resync $tf || error \"resynchronizing $tf failed\"\n\n\t$LFS mirror split --mirror-id 3 -d $tf ||\n\t\terror \"destroying mirror 3 failed\"\n\tverify_mirror_count $tf 1\n\n\t# verify splitted file contains the same content as the orig file does\n\tdiff $tf $tf1 || error \"splited file $tf1 diffs from $tf\"\n\tdiff $tf $tf.mirror~2 ||\n\t\terror \"splited file $tf.mirror~2 diffs from $tf\"\n}\nrun_test 44 \"lfs mirror split check\"\n\ntest_45() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal dir=$DIR/$tdir/$dir\n\tlocal temp=$DIR/$tdir/template\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\n\t$LFS setstripe -N -E1m -S1m -c2 -o0,1 -E2m -Eeof -N -E4m -Eeof \\\n\t\t-N -E3m -S1m -Eeof -N -E8m -Eeof $file ||\n\t\t\terror \"Create $file failed\"\n\n\tverify_yaml_layout $file $file.copy $temp \"1. FLR file\"\n\trm -f $file $file.copy\n\n\t$LFS setstripe -N -E1m -S1m -c2 -o0,1 -E2m -Eeof -N -E4m -Eeof \\\n\t\t-N -E3m -S1m -Eeof -N -E8m --flags=prefer -Eeof $file ||\n\t\t\terror \"Create $file failed\"\n\n\tverify_yaml_layout $file $file.copy $temp \"2. FLR file with flags\"\n}\nrun_test 45 \"Verify setstripe/getstripe with YAML with FLR file\"\n\nverify_46() {\n\tlocal src=$1\n\tlocal dst=$2\n\tlocal msg_prefix=$3\n\n\t$LFS setstripe --copy=$src $dst || error \"setstripe $dst failed\"\n\n\tlocal layout1=$(get_layout_param $src)\n\tlocal layout2=$(get_layout_param $dst)\n\t# compare their layout info\n\t[ \"$layout1\" == \"$layout2\" ] ||\n\t\terror \"$msg_prefix $src <=> $dst layouts are not equal\"\n}\n\ntest_46() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return\n\n\tlocal file=$DIR/$tdir/$tfile\n\ttest_mkdir $DIR/$tdir\n\n\t########################### 1. PFL file #############################\n\techo \"  ** 1. PFL file\"\n\trm -f $file\n\t$LFS setstripe -E1m -S 1M -c2 -o0,1 -E2m -c2 -E3m -o1,0 -E4m -c1 -E-1 \\\n\t\t$file || error \"1. Create PFL $file failed\"\n\n\trm -f $file.copy\n\tverify_46 $file $file.copy \"1. PFL file\"\n\n\t########################### 2. plain file ###########################\n\techo \"  ** 2. plain file\"\n\trm -f $file\n\t$LFS setstripe -c2 -o0,1 -i1 $file ||\n\t\terror \"2. Create plain $file failed\"\n\n\trm -f $file.copy\n\tverify_46 $file $file.copy \"2. plain file\"\n\n\t########################### 3. FLR file #############################\n\techo \"  ** 3. FLR file\"\n\trm -f $file\n\t$LFS setstripe -N -E1m -S 1M -c2 -o0,1 -E4m -c1 -Eeof -N -E16m -Eeof \\\n\t\t$file || error \"3. Create FLR $file failed\"\n\n\trm -f $file.copy\n\tverify_46 $file $file.copy \"3. FLR file\"\n\n\tlocal dir=$DIR/$tdir/dir\n\t########################### 4. PFL dir ##############################\n\techo \"  ** 4. PFL dir\"\n\ttest_mkdir $dir\n\t$LFS setstripe -E1m -S 1M -c2 -E2m -c1 -E-1 $dir ||\n\t\terror \"4. setstripe PFL $dir failed\"\n\n\ttest_mkdir $dir.copy\n\tverify_46 $dir $dir.copy \"4. PFL dir\"\n\n\t########################### 5. plain dir ############################\n\techo \"  ** 5. plain dir\"\n\t$LFS setstripe -c2 -i-1 $dir || error \"5. setstripe plain $dir failed\"\n\n\tverify_46 $dir $dir.copy \"5. plain dir\"\n\n\t########################### 6. FLR dir ##############################\n\techo \"  ** 6. FLR dir\"\n\t$LFS setstripe -N -E1m -S 1M -c2 -E2m -c1 -Eeof -N -E4m -Eeof $dir ||\n\t\terror \"6. setstripe FLR $dir failed\"\n\n\tverify_46 $dir $dir.copy \"6. FLR dir\"\n\n\t########################### 7. SEL file ##############################\n\techo \"  ** 7. SEL file\"\n\trm -f $file\n\t$LFS setstripe -E256M -S 1M -c2 -o0,1 -z 64M -E-1 -o1,0 -z 128M \\\n\t\t$file || error \"Create $file failed\"\n\n\trm -f $file.copy\n\tverify_46 $file $file.copy \"7. SEL file\"\n\n\t########################### 8. SEL dir ##############################\n\techo \"  ** 8. SEL dir\"\n\t$LFS setstripe -E256M -S 1M -c2 -z 64M -E-1 -z 128M \\\n\t\t$dir || error \"setstripe $dir failed\"\n\n\tverify_46 $dir $dir.copy \"8. SEL dir\"\n\n\t########################### 9. FLR SEL file ##########################\n\techo \"  ** 9. FLR SEL file\"\n\trm -f $file\n\t$LFS setstripe -N -E256M -c2 -z 64M -E-1 -z 128M \\\n\t\t-N -E1G -c4 -z128M -E-1 -z256M $file || error \"Create $file failed\"\n\n\trm -f $file.copy\n\tverify_46 $file $file.copy \"9. SEL file\"\n\n\t########################### 10. FLR SEL dir #########################\n\techo \"  ** 10. FLR SEL dir\"\n\t$LFS setstripe -N -E256M -c2 -z 64M -E-1 -z 128M \\\n\t\t-N -E1G -c4 -z128M -E-1 -z256M $dir || error \"Create $file failed\"\n\n\tverify_46 $dir $dir.copy \"10. SEL dir\"\n}\nrun_test 46 \"Verify setstripe --copy option\"\n\ntest_47() {\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\" && return\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal ids\n\tlocal ost\n\tlocal osts\n\n\ttest_mkdir $DIR/$tdir\n\n\t# test case 1:\n\trm -f $file\n\t# mirror1: [comp0]ost0,    [comp1]ost1 and ost2\n\t# mirror2: [comp2]    ,    [comp3] should not use ost1 or ost2\n\t$LFS mirror create -N -E2m -c1 -o0 --flags=prefer -Eeof -c2 -o1,2 \\\n\t\t-N -E2m -c1 -Eeof -c1 $file || error \"create FLR $file failed\"\n\tids=($($LFS getstripe $file | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\n\tdd if=/dev/zero of=$file bs=1M count=3 || error \"dd $file failed\"\n\t$LFS mirror resync $file || error \"resync $file failed\"\n\n\tost=$($LFS getstripe -I${ids[2]} $file | awk '/l_ost_idx/{print $5}')\n\tif [[ x$ost == \"x0,\" ]]; then\n\t\t$LFS getstripe $file\n\t\terror \"component ${ids[2]} objects allocated on $ost \" \\\n\t\t      \"shouldn't on OST0\"\n\tfi\n\n\tost=$($LFS getstripe -I${ids[3]} $file | awk '/l_ost_idx/{print $5}')\n\tif [[ x$ost == \"x1,\" || x$ost == \"x2,\" ]]; then\n\t\t$LFS getstripe $file\n\t\terror \"component ${ids[3]} objects allocated on $ost \" \\\n\t\t      \"shouldn't on OST1 or on OST2\"\n\tfi\n\n\t## test case 2:\n\trm -f $file\n\t# mirror1: [comp0]    [comp1]\n\t# mirror2: [comp2]    [comp3]\n\t# mirror3: [comp4]    [comp5]\n\t# mirror4: [comp6]    [comp7]\n\t$LFS mirror create -N4 -E1m -c1 -Eeof -c1 $file ||\n\t\terror \"create FLR $file failed\"\n\tids=($($LFS getstripe $file | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\n\tdd if=/dev/zero of=$file bs=1M count=3 || error \"dd $file failed\"\n\t$LFS mirror resync $file || error \"resync $file failed\"\n\n\tfor ((i = 0; i < 6; i++)); do\n\t\tosts[$i]=$($LFS getstripe -I${ids[$i]} $file |\n\t\t\tawk '/l_ost_idx/{print $5}')\n\tdone\n\t# comp[0],comp[2],comp[4] should use different osts\n\tif [[ ${osts[0]} == ${osts[2]} || ${osts[0]} == ${osts[4]} ||\n\t      ${osts[2]} == ${osts[4]} ]]; then\n\t\t$LFS getstripe $file\n\t\terror \"component ${ids[0]}, ${ids[2]}, ${ids[4]} have objects \"\\\n\t\t      \"allocated on duplicated OSTs\"\n\tfi\n\t# comp[1],comp[3],comp[5] should use different osts\n\tif [[ ${osts[1]} == ${osts[3]} || ${osts[1]} == ${osts[5]} ||\n\t      ${osts[3]} == ${osts[5]} ]]; then\n\t\t$LFS getstripe $file\n\t\terror \"component ${ids[1]}, ${ids[3]}, ${ids[5]} have objects \"\\\n\t\t      \"allocated on duplicated OSTs\"\n\tfi\n\n\treturn 0\n}\nrun_test 47 \"Verify mirror obj alloc\"\n\ntest_48() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&\n\t\tskip \"Need MDS version at least 2.11.55\"\n\n\tlocal tf=$DIR/$tfile\n\n\trm -f $tf\n\techo \" ** create 2 mirrors FLR file $tf\"\n\t$LFS mirror create -N -E2M -Eeof --flags prefer \\\n\t\t\t   -N -E1M -Eeof $tf ||\n\t\terror \"create FLR file $tf failed\"\n\n\techo \" ** write it\"\n\tdd if=/dev/urandom of=$tf bs=1M count=3 || error \"write $tf failed\"\n\tverify_flr_state $tf \"wp\"\n\n\tlocal sum0=$(md5sum < $tf)\n\n\techo \" ** resync the file\"\n\t$LFS mirror resync $tf\n\n\techo \" ** snapshot mirror 2\"\n\t$LFS setstripe --comp-set -I 0x20003 --comp-flags=nosync $tf\n\n\techo \" ** write it again\"\n\tdd if=/dev/urandom of=$tf bs=1M count=3 || error \"write $tf failed\"\n\techo \" ** resync it again\"\n\t$LFS mirror resync $tf\n\n\tverify_flr_state $tf \"wp\"\n\tverify_comp_attr lcme_flags $tf 0x20003 nosync,stale\n\n\tlocal sum1=$($LFS mirror read -N1 $tf | md5sum)\n\tlocal sum2=$($LFS mirror read -N2 $tf | md5sum)\n\n\techo \" ** verify mirror 2 doesn't change\"\n\techo \"original checksum: $sum0\"\n\techo \"mirror 1 checksum: $sum1\"\n\techo \"mirror 2 checksum: $sum2\"\n\t[[ $sum0 = $sum2 ]] ||\n\t\terror \"original checksum: $sum0, mirror 2 checksum: $sum2\"\n\techo \" ** mirror 2 stripe info\"\n\t$LFS getstripe -v --mirror-index=2 $tf\n\n\techo \" ** resync mirror 2\"\n\t$LFS mirror resync --only 2 $tf\n\n\tverify_flr_state $tf \"ro\"\n\tverify_comp_attr lcme_flags $tf 0x20003 nosync,^stale\n\n\tsum1=$($LFS mirror read -N1 $tf | md5sum)\n\tsum2=$($LFS mirror read -N2 $tf | md5sum)\n\n\techo \" ** verify mirror 2 resync-ed\"\n\techo \"original checksum: $sum0\"\n\techo \"mirror 1 checksum: $sum1\"\n\techo \"mirror 2 checksum: $sum2\"\n\t[[ $sum1 = $sum2 ]] ||\n\t\terror \"mirror 1 checksum: $sum1, mirror 2 checksum: $sum2\"\n\techo \" ** mirror 2 stripe info\"\n\t$LFS getstripe -v --mirror-index=2 $tf\n}\nrun_test 48 \"Verify snapshot mirror\"\n\nctrl_file=$(mktemp /tmp/CTRL.XXXXXX)\nlock_file=$(mktemp /var/lock/FLR.XXXXXX)\n\nwrite_file_200() {\n\tlocal tf=$1\n\n\tlocal fsize=$(stat --printf=%s $tf)\n\n\twhile [ -f $ctrl_file ]; do\n\t\tlocal off=$((RANDOM << 8))\n\t\tlocal len=$((RANDOM << 5 + 131072))\n\n\t\t[ $((off + len)) -gt $fsize ] && {\n\t\t\tfsize=$((off + len))\n\t\t\techo \"Extending file size to $fsize ..\"\n\t\t}\n\n\t\tflock -s $lock_file -c \\\n\t\t\t\"$MULTIOP $tf oO_WRONLY:z${off}w${len}c\" ||\n\t\t\t\t{ rm -f $ctrl_file;\n\t\t\t\t  error \"failed writing to $off:$len\"; }\n\t\tsleep 0.$((RANDOM % 2 + 1))\n\tdone\n}\n\nread_file_200() {\n\tlocal tf=$1\n\n\twhile [ -f $ctrl_file ]; do\n\t\tflock -s $lock_file -c \"cat $tf &> /dev/null\" ||\n\t\t\t{ rm -f $ctrl_file; error \"read failed\"; }\n\t\tsleep 0.$((RANDOM % 2 + 1))\n\tdone\n}\n\nresync_file_200() {\n\tlocal tf=$1\n\n\toptions=(\"\" \"-e resync_start\" \"-e delay_before_copy -d 1\" \"\" \"\")\n\n\texec 200<>$lock_file\n\twhile [ -f $ctrl_file ]; do\n\t\tlocal lock_taken=false\n\t\tlocal index=$((RANDOM % ${#options[@]}))\n\t\tlocal cmd=\"mirror_io resync ${options[$index]}\"\n\n\t\t[ \"${options[$index]}\" = \"\" ] && cmd=\"$LFS mirror resync\"\n\n\t\t[ $((RANDOM % 4)) -eq 0 ] && {\n\t\t\tindex=0\n\t\t\tlock_taken=true\n\t\t\techo -n \"lock to \"\n\t\t}\n\n\t\techo -n \"resync file $tf with '$cmd' ..\"\n\n\t\tif [[ $lock_taken = \"true\" ]]; then\n\t\t\tflock -x 200 -c \"$cmd $tf &> /dev/null\" &&\n\t\t\t\techo \"done\" || echo \"failed\"\n\t\t\tflock -u 200\n\t\telse\n\t\t\t$cmd $tf &> /dev/null && echo \"done\" || echo \"failed\"\n\t\tfi\n\n\t\tsleep 0.$((RANDOM % 8 + 1))\n\tdone\n}\n\ntest_200() {\n\tlocal tf=$DIR/$tfile\n\tlocal tf2=$DIR2/$tfile\n\tlocal tf3=$DIR3/$tfile\n\n\t$LFS setstripe -E 1M -S 1M -E 2M -c 2 -E 4M -E 16M -E eof $tf\n\t$LFS setstripe -E 2M -S 1M -E 6M -c 2 -E 8M -E 32M -E eof $tf-2\n\t$LFS setstripe -E 4M -c 2 -E 8M -E 64M -E eof $tf-3\n\n\t$LFS mirror extend -N -f $tf-2 $tf ||\n\t\terror \"merging $tf-2 into $tf failed\"\n\t$LFS mirror extend -N -f $tf-3 $tf ||\n\t\terror \"merging $tf-3 into $tf failed\"\n\n\tmkdir -p $MOUNT2 && mount_client $MOUNT2\n\n\tmkdir -p $MOUNT3 && mount_client $MOUNT3\n\n\tverify_flr_state $tf3 \"ro\"\n\n\t#define OBD_FAIL_FLR_RANDOM_PICK_MIRROR\t0x1A03\n\t$LCTL set_param fail_loc=0x1A03\n\n\tlocal mds_idx=mds$(($($LFS getstripe -m $tf) + 1))\n\tdo_facet $mds_idx $LCTL set_param fail_loc=0x1A03\n\n\tdeclare -a pids\n\n\twrite_file_200 $tf &\n\tpids+=($!)\n\n\tread_file_200 $tf &\n\tpids+=($!)\n\n\twrite_file_200 $tf2 &\n\tpids+=($!)\n\n\tread_file_200 $tf2 &\n\tpids+=($!)\n\n\tresync_file_200 $tf3 &\n\tpids+=($!)\n\n\tlocal sleep_time=60\n\t[ \"$SLOW\" = \"yes\" ] && sleep_time=360\n\twhile [ $sleep_time -gt 0 -a -f $ctrl_file ]; do\n\t\tsleep 1\n\t\t((--sleep_time))\n\tdone\n\n\trm -f $ctrl_file\n\n\techo \"Waiting ${pids[@]}\"\n\twait ${pids[@]}\n\n\tumount_client $MOUNT2\n\tumount_client $MOUNT3\n\n\trm -f $lock_file\n\n\t# resync and verify mirrors\n\tmirror_io resync $tf\n\tget_mirror_ids $tf\n\n\tlocal csum=$($LFS mirror read -N ${mirror_array[0]} $tf | md5sum)\n\tfor id in ${mirror_array[@]:1}; do\n\t\t[ \"$($LFS mirror read -N $id $tf | md5sum)\" = \"$csum\" ] ||\n\t\t\terror \"checksum error for mirror $id\"\n\tdone\n\n\ttrue\n}\nrun_test 200 \"stress test\"\n\ncleanup_test_201() {\n\ttrap 0\n\tdo_facet $SINGLEMDS $LCTL --device $MDT0 changelog_deregister $CL_USER\n\n\tumount_client $MOUNT2\n}\n\ntest_201() {\n\tlocal delay=${RESYNC_DELAY:-5}\n\n\tMDT0=$($LCTL get_param -n mdc.*.mds_server_uuid |\n\t       awk '{ gsub(/_UUID/,\"\"); print $1 }' | head -n1)\n\n\ttrap cleanup_test_201 EXIT\n\n\tCL_USER=$(do_facet $SINGLEMDS $LCTL --device $MDT0 \\\n\t\t\tchangelog_register -n)\n\n\tmkdir -p $MOUNT2 && mount_client $MOUNT2\n\n\tlocal index=0\n\twhile :; do\n\t\tlocal log=$($LFS changelog $MDT0 $index | grep FLRW)\n\t\t[ -z \"$log\" ] && { sleep 1; continue; }\n\n\t\tindex=$(echo $log | awk '{print $1}')\n\t\tlocal ts=$(date -d \"$(echo $log | awk '{print $3}')\" \"+%s\" -u)\n\t\tlocal fid=$(echo $log | awk '{print $6}' | sed -e 's/t=//')\n\t\tlocal file=$($LFS fid2path $MOUNT2 $fid 2> /dev/null)\n\n\t\t((++index))\n\t\t[ -z \"$file\" ] && continue\n\n\t\tlocal now=$(date +%s)\n\n\t\techo \"file: $file $fid was modified at $ts, now: $now, \" \\\n\t\t     \"will be resynced at $((ts+delay))\"\n\n\t\t[ $now -lt $((ts + delay)) ] && sleep $((ts + delay - now))\n\n\t\tmirror_io resync $file\n\t\techo \"$file resync done\"\n\tdone\n\n\tcleanup_test_201\n}\nrun_test 201 \"FLR data mover\"\n\ntest_202() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\" && return\n\n\tlocal tf=$DIR/$tfile\n\tlocal ids\n\n\t$LFS setstripe -E 1M -S 1M -c 1 $tf\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tverify_comp_attr stripe-count $tf ${ids[0]} 1\n\n\t$LFS setstripe --component-add -E 2M -c -1 $tf\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tverify_comp_attr stripe-count $tf ${ids[0]} 1\n\tverify_comp_attr stripe-count $tf ${ids[1]} -1\n\n\tdd if=/dev/zero of=$tf bs=1M count=2\n\tids=($($LFS getstripe $tf | awk '/lcme_id/{print $2}' | tr '\\n' ' '))\n\tverify_comp_attr stripe-count $tf ${ids[0]} 1\n\tverify_comp_attr stripe-count $tf ${ids[1]} $OSTCOUNT\n}\nrun_test 202 \"lfs setstripe --add-component wide striping\"\n\ntest_203() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&\n\t\tskip \"Need MDS version at least 2.11.55\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"need >= 2 OSTs\"\n\n\tlocal tf=$DIR/$tfile\n\n\t#create 2 mirrors\n\t$LFS mirror create -N2 -c1 $tf || error \"create FLR file $tf\"\n\t#delete first mirror\n\t$LFS mirror delete --mirror-id=1 $tf || error \"delete first mirror\"\n\n\t$LFS getstripe $tf\n\tlocal old_id=$($LFS getstripe --mirror-id=2 -I $tf)\n\tlocal count=$($LFS getstripe --mirror-id=2 -c $tf) ||\n\t\terror \"getstripe count of mirror 2\"\n\t[[ x$count = x1 ]] || error \"mirror 2 stripe count $count is not 1\"\n\n\t#extend a mirror with 2 OSTs\n\t$LFS mirror extend -N -c2 $tf || error \"extend mirror\"\n\t$LFS getstripe $tf\n\n\tlocal new_id=$($LFS getstripe --mirror-id=2 -I $tf)\n\tcount=$($LFS getstripe --mirror-id=2 -c $tf) ||\n\t\terror \"getstripe count of mirror 2\"\n\t[[ x$oldid = x$newid ]] ||\n\t\terror \"mirror 2 changed ID from $old_id to $new_id\"\n\t[[ x$count = x1 ]] || error \"mirror 2 stripe count $count is not 1\"\n\n\tcount=$($LFS getstripe --mirror-id=3 -c $tf) ||\n\t\terror \"getstripe count of mirror 3\"\n\t[[ x$count = x2 ]] || error \"mirror 3 stripe count $count is not 2\"\n}\nrun_test 203 \"mirror file preserve mirror ID\"\n\n# Simple test of FLR + self-extending layout, SEL in non-primary mirror\ntest_204a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir $DIR/$tdir\n\n\t# first mirror is 0-10M, then 10M-(-1), second mirror is 1M followed\n\t# by extension space to -1\n\t$LFS setstripe -N -E 10M -E-1 -N -E 1M -E-1 -z64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# Write to first component, extending & staling second mirror\n\tdd if=/dev/zero bs=2M count=1 of=$comp_file conv=notrunc ||\n\t\terror \"dd to extend + stale failed\"\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--component-flags init,stale\"\n\tfound=$($LFS find --component-end 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Second comp end incorrect\"\n\n\tflg_opts=\"--component-flags extension\"\n\tfound=$($LFS find --component-start 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Third comp start incorrect\"\n\n\t# mirror resync should not change the extents\n\t$LFS mirror resync $comp_file\n\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-end 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: Second comp end incorrect\"\n\n\tflg_opts=\"--component-flags extension\"\n\tfound=$($LFS find --component-start 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: Third comp start incorrect\"\n\n\tsel_layout_sanity $comp_file 5\n\n\trm -f $comp_file\n}\nrun_test 204a \"FLR write/stale/resync tests with self-extending mirror\"\n\n# Simple test of FLR + self-extending layout, SEL in primary mirror\ntest_204b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir $DIR/$tdir\n\n\t# first mirror is 1M followed by extension space to -1, second mirror\n\t# is 0-10M, then 10M-(-1),\n\t$LFS setstripe -N -E 1M -E-1 -z64M -N -E 10M -E-1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# Write to first component, extending first component & staling\n\t# other mirror\n\tdd if=/dev/zero bs=2M count=1 of=$comp_file conv=notrunc ||\n\t\terror \"dd to extend + stale failed\"\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-end 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: First comp end incorrect\"\n\n\tflg_opts=\"--component-flags extension\"\n\tfound=$($LFS find --component-start 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Second comp start incorrect\"\n\n\tflg_opts=\"--component-flags init,stale\"\n\tfound=$($LFS find --component-end 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: First mirror comp flags incorrect\"\n\n\t# This component is staled because it overlaps the extended first\n\t# component of the primary mirror, even though it doesn't overlap\n\t# the actual write - thus not inited.\n\tflg_opts=\"--component-flags stale\"\n\tfound=$($LFS find --component-start 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Second mirror comp flags incorrect\"\n\n\t# mirror resync should not change the extents\n\t$LFS mirror resync $comp_file\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-end 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: First comp end incorrect\"\n\n\tflg_opts=\"--component-flags extension\"\n\tfound=$($LFS find --component-start 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: Second comp start incorrect\"\n\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-end 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: First mirror comp flags incorrect\"\n\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-start 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: Second mirror comp flags incorrect\"\n\n\tsel_layout_sanity $comp_file 5\n\n\trm -f $comp_file\n}\nrun_test 204b \"FLR write/stale/resync tests with self-extending primary\"\n\n# FLR + SEL failed extension & component removal\n# extension space in second mirror\ntest_204c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal found=\"\"\n\tlocal ost_idx1=0\n\tlocal ost_name=$(ostname_from_index $ost_idx1)\n\n\ttest_mkdir $DIR/$tdir\n\n\t# first mirror is is 0-10M, then 10M-(-1), second mirror is 0-1M, then\n\t# extension space from 1M to 1G, then normal space to -1\n\t$LFS setstripe -N -E 10M -E-1 -N -E 1M -E 1G -i $ost_idx1 -z 64M \\\n\t\t-E -1 $comp_file || error \"Create $comp_file failed\"\n\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name.degraded=1\n\tsleep_maxage\n\n\t# write to first comp (0 - 10M) of mirror 1, extending + staling\n\t# first + second comp of mirror 2\n\tdd if=/dev/zero bs=2M count=1 of=$comp_file conv=notrunc\n\tRC=$?\n\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name.degraded=0\n\tsleep_maxage\n\n\t[ $RC -eq 0 ] || error \"dd to extend + stale failed\"\n\n\t$LFS getstripe $comp_file\n\n\tfound=$($LFS find --component-start 0m --component-end 1m \\\n\t\t--comp-flags init,stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: First mirror comp incorrect\"\n\n\tfound=$($LFS find --component-start 1m --component-end EOF \\\n\t\t--comp-flags stale,^init $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Second mirror comp incorrect\"\n\n\tlocal mirror_id=$($LFS getstripe --component-start=1m\t\\\n\t\t\t --component-end=EOF $comp_file |\t\\\n\t\t\t grep lcme_mirror_id | awk '{ print $2 }')\n\n\t[[ $mirror_id -eq 2 ]] ||\n\t\terror \"component not in correct mirror? $mirror_id\"\n\n\t$LFS mirror resync $comp_file\n\n\t$LFS getstripe $comp_file\n\n\t# component dimensions should not change from resync\n\tfound=$($LFS find --component-start 1m --component-end EOF \\\n\t\t--component-flags init $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: Second mirror comp incorrect\"\n\n\tsel_layout_sanity $comp_file 4\n\n\trm -f $comp_file\n}\nrun_test 204c \"FLR write/stale/resync test with component removal\"\n\n# Successful repeated component in primary mirror\ntest_204d() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal found=\"\"\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\ttest_mkdir $DIR/$tdir\n\n\t# first mirror is 64M followed by extension space to -1, second mirror\n\t# is 0-10M, then 10M-(-1)\n\t$LFS setstripe -N -E-1 -z64M -N -E 10M -E-1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal ost_idx1=$($LFS getstripe -I65537 -i $comp_file)\n\tlocal ost_name=$(ostname_from_index $ost_idx1)\n\t# degrade OST for first comp so we won't extend there\n\tdo_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=1\n\tsleep_maxage\n\n\t# Write beyond first component, causing repeat & stale second mirror\n\tdd if=/dev/zero bs=1M count=1 seek=66 of=$comp_file conv=notrunc\n\tRC=$?\n\n\tdo_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=0\n\tsleep_maxage\n\n\t[ $RC -eq 0 ] || error \"dd to repeat & stale failed\"\n\n\t$LFS getstripe $comp_file\n\n\tfound=$($LFS find --component-start 64m --component-end 128m \\\n\t\t--component-flags init $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: Repeat comp incorrect\"\n\n\tlocal ost_idx2=$($LFS getstripe --component-start=64m\t\t\\\n\t\t\t --component-end=128m --component-flags=init\t\\\n\t\t\t -i $comp_file)\n\t[[ $ost_idx1 -eq $ost_idx2 ]] && error \"$ost_idx1 == $ost_idx2\"\n\tlocal mirror_id=$($LFS getstripe --component-start=64m\t\t\\\n\t\t\t --component-end=128m --component-flags=init\t\\\n\t\t\t $comp_file | grep lcme_mirror_id | awk '{ print $2 }')\n\t[[ $mirror_id -eq 1 ]] ||\n\t\terror \"component not in correct mirror: $mirror_id, not 1\"\n\n\t$LFS mirror resync $comp_file\n\n\t$LFS getstripe $comp_file\n\n\t# component dimensions should not change from resync\n\tfound=$($LFS find --component-start 0m --component-end 64m \\\n\t\t--component-flags init $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: first comp incorrect\"\n\tfound=$($LFS find --component-start 64m --component-end 128m \\\n\t\t--component-flags init $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: repeat comp incorrect\"\n\n\tsel_layout_sanity $comp_file 5\n\n\trm -f $comp_file\n}\nrun_test 204d \"FLR write/stale/resync sel test with repeated comp\"\n\n# Successful repeated component, SEL in non-primary mirror\ntest_204e() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal found=\"\"\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\ttest_mkdir $DIR/$tdir\n\n\t# first mirror is is 0-100M, then 100M-(-1), second mirror is extension\n\t# space to -1 (-z 64M, so first comp is 0-64M)\n\t# Note: we have to place both 1st components on OST0, otherwise 2 OSTs\n\t# will be not enough - one will be degraded, the other is used on\n\t# an overlapping mirror.\n\t$LFS setstripe -N -E 100M -i 0 -E-1 -N -E-1 -i 0 -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal ost_idx1=$($LFS getstripe --component-start=0 \\\n\t\t\t --component-end=64m -i $comp_file)\n\tlocal ost_name=$(ostname_from_index $ost_idx1)\n\t# degrade OST for first comp of 2nd mirror so we won't extend there\n\tdo_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=1\n\tsleep_maxage\n\n\t$LFS getstripe $comp_file\n\n\t# Write to first component, stale & instantiate second mirror components\n\t# overlapping with the written component (0-100M);\n\tdd if=/dev/zero bs=2M count=1 of=$comp_file conv=notrunc\n\tRC=$?\n\n\tdo_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=0\n\tsleep_maxage\n\t$LFS getstripe $comp_file\n\n\t[ $RC -eq 0 ] || error \"dd to repeat & stale failed\"\n\n\tfound=$($LFS find --component-start 0m --component-end 64m \\\n\t\t--component-flags init,stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: first comp incorrect\"\n\n\t# was repeated due to degraded ost\n\tfound=$($LFS find --component-start 64m --component-end 128m \\\n\t\t--component-flags init,stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: repeated comp incorrect\"\n\n\tlocal ost_idx2=$($LFS getstripe --component-start=64m\t\t\\\n\t\t\t --component-end=128m --component-flags=init\t\\\n\t\t\t -i $comp_file)\n\t[[ $ost_idx1 -eq $ost_idx2 ]] && error \"$ost_idx1 == $ost_idx2\"\n\tlocal mirror_id=$($LFS getstripe --component-start=0m\t\t\\\n\t\t\t --component-end=64m --component-flags=init\t\\\n\t\t\t $comp_file | grep lcme_mirror_id | awk '{ print $2 }')\n\t[[ $mirror_id -eq 2 ]] ||\n\t\terror \"component not in correct mirror? $mirror_id\"\n\n\t$LFS mirror resync $comp_file\n\n\t$LFS getstripe $comp_file\n\n\t# component dimensions should not change from resync\n\tfound=$($LFS find --component-start 0m --component-end 64m \\\n\t\t--component-flags init,^stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: first comp incorrect\"\n\tfound=$($LFS find --component-start 64m --component-end 128m \\\n\t\t--component-flags init,^stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: repeated comp incorrect\"\n\n\tsel_layout_sanity $comp_file 5\n\n\trm -f $comp_file\n}\nrun_test 204e \"FLR write/stale/resync sel test with repeated comp\"\n\n# FLR + SEL: failed repeated component, SEL in non-primary mirror\ntest_204f() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal found=\"\"\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\ttest_mkdir $DIR/$tdir\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 1 || error \"Pool add targets failed\"\n\n\t# first mirror is is 0-100M, then 100M-(-1), second mirror is extension\n\t# space to -1 (-z 64M, so first comp is 0-64M)\n\t$LFS setstripe -N -E 100M -E-1 -N --pool=\"$TESTNAME\" \\\n\t\t-E-1 -c 1 -z 64M $comp_file || error \"Create $comp_file failed\"\n\n\tlocal ost_name0=$(ostname_from_index 0)\n\tlocal ost_name1=$(ostname_from_index 1)\n\n\t# degrade both OSTs in pool, so we'll try to repeat, then fail and\n\t# extend original comp\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name0.degraded=1\n\tdo_facet ost2 $LCTL set_param -n obdfilter.$ost_name1.degraded=1\n\tsleep_maxage\n\n\t# a write to the 1st component, 100M length, which will try to stale\n\t# the first 100M of mirror 2, attempting to extend its 0-64M component\n\tdd if=/dev/zero bs=2M count=1 of=$comp_file conv=notrunc\n\tRC=$?\n\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name0.degraded=0\n\tdo_facet ost2 $LCTL set_param -n obdfilter.$ost_name1.degraded=0\n\tsleep_maxage\n\n\t[ $RC -eq 0 ] || error \"dd to extend mirror comp failed\"\n\n\t$LFS getstripe $comp_file\n\n\tfound=$($LFS find --component-start 0m --component-end 128m \\\n\t\t--component-flags init,stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"write: First mirror comp incorrect\"\n\n\tlocal mirror_id=$($LFS getstripe --component-start=0m\t\t\\\n\t\t\t --component-end=128m --component-flags=init\t\\\n\t\t\t $comp_file | grep lcme_mirror_id | awk '{ print $2 }')\n\n\t[[ $mirror_id -eq 2 ]] ||\n\t\terror \"component not in correct mirror? $mirror_id, not 2\"\n\n\t$LFS mirror resync $comp_file\n\n\t$LFS getstripe $comp_file\n\n\t# component dimensions should not change from resync\n\tfound=$($LFS find --component-start 0m --component-end 128m \\\n\t\t--component-flags init,^stale $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"resync: First mirror comp incorrect\"\n\n\tsel_layout_sanity $comp_file 4\n\n\trm -f $comp_file\n}\nrun_test 204f \"FLR write/stale/resync sel w/forced extension\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 2912}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# e.g. ONLY=\"22 23\" or ONLY=\"`seq 32 39`\" or EXCEPT=\"31\"\nset -e\n\nONLY=${ONLY:-\"$*\"}\n# bug number for skipped test:\nALWAYS_EXCEPT=${ALWAYS_EXCEPT:-\"$SANITY_GSS_EXCEPT\"}\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\nif $SHARED_KEY; then\n# bug number for skipped tests:\tLU-9795\tLU-9795\n\tALWAYS_EXCEPT=\"\t\t8\t90\t$ALWAYS_EXCEPT\"\nfi\n\nSRCDIR=`dirname $0`\n\nexport MULTIOP=${MULTIOP:-multiop}\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nrequire_dsh_mds || exit 0\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"100 101\"\n\n# $RUNAS_ID may get set incorrectly somewhere else\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] && error \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\n\n# remove $SEC, we'd like to control everything by ourselves\nunset SEC\n\n#\n# global variables of this sanity\n#\nDBENCH_PID=0\n\n# set manually\nGSS=true\n\n# we want double mount\nMOUNT_2=${MOUNT_2:-\"yes\"}\ncheck_and_setup_lustre\n\nrm -rf $DIR/[df][0-9]*\n\ncheck_runas_id $RUNAS_ID $RUNAS_ID $RUNAS\n\nbuild_test_filter\n\nstart_dbench()\n{\n    NPROC=`cat /proc/cpuinfo 2>/dev/null | grep ^processor | wc -l`\n    [ $NPROC -gt 2 ] && NPROC=2\n    sh rundbench $NPROC 1>/dev/null &\n    DBENCH_PID=$!\n    sleep 2\n\n    num=`ps --no-headers -p $DBENCH_PID 2>/dev/null | wc -l`\n    if [ $num -ne 1 ]; then\n        error \"failed to start dbench $NPROC\"\n    else\n        echo \"started dbench with $NPROC processes at background\"\n    fi\n\n    return 0\n}\n\ncheck_dbench()\n{\n    num=`ps --no-headers -p $DBENCH_PID 2>/dev/null | wc -l`\n    if [ $num -eq 0 ]; then\n        echo \"dbench $DBENCH_PID already finished\"\n        wait $DBENCH_PID || error \"dbench $PID exit with error\"\n        start_dbench\n    elif [ $num -ne 1 ]; then\n        killall -9 dbench\n        error \"found $num instance of pid $DBENCH_PID ???\"\n    fi\n\n    return 0\n}\n\nstop_dbench()\n{\n    for ((;;)); do\n        killall dbench 2>/dev/null\n        num=`ps --no-headers -p $DBENCH_PID | wc -l`\n        if [ $num -eq 0 ]; then\n            echo \"dbench finished\"\n            break\n        fi\n        echo \"dbench $DBENCH_PID is still running, waiting 2s...\"\n        sleep 2\n    done\n\n    wait $DBENCH_PID || true\n    sync || true\n}\n\ncalc_connection_cnt\numask 077\n\n# Stop previously existing gss daemons\nstop_gss_daemons\n\necho \"bring up gss daemons...\"\n# start gss daemon with -z flag for gssnull\nstart_gss_daemons $(comma_list $(mdts_nodes)) \"$LSVCGSSD -z -vv\" ||\n    error \"can't start gss daemons on MDTs\"\nstart_gss_daemons $(comma_list $(osts_nodes)) \"$LSVCGSSD -z -vv\" ||\n    error \"can't start gss daemons on OSTs\"\n\nlctl set_param sptlrpc.gss.lgss_keyring.debug_level=4\n\necho \"cat /etc/request-key.d/lgssc.conf\"\ncat /etc/request-key.d/lgssc.conf ||\n    error_noexit \"/etc/request-key.d/lgssc.conf does not exist\"\necho \"cat /etc/request-key.conf\"\ncat /etc/request-key.conf ||\n    error_noexit \"/etc/request-key.conf does not exist\"\n\nset_flavor_all gssnull\n\ntest_1() {\n\tlocal file=$DIR/$tfile\n\n\tchmod 0777 $DIR || error \"chmod $DIR failed\"\n\t# access w/o context\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $DIR\n\t$RUNAS touch $file || error \"should not fail\"\n\t[ -f $file ] || error \"$file not found\"\n}\nrun_test 1 \"create file\"\n\ntest_2() {\n    local file1=$DIR/$tfile-1\n    local file2=$DIR/$tfile-2\n\n    chmod 0777 $DIR || error \"chmod $DIR failed\"\n    # current access should be ok\n    $RUNAS touch $file1 || error \"can't touch $file1\"\n    [ -f $file1 ] || error \"$file1 not found\"\n\n\t# cleanup all cred/ctx and touch\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $file2 && error \"unexpected success\"\n}\nrun_test 2 \"lfs flushctx\"\n\ntest_3() {\n    local file=$DIR/$tfile\n\n    # create file\n    echo \"aaaaaaaaaaaaaaaaa\" > $file\n    chmod 0666 $file\n    $CHECKSTAT -p 0666 $file || error \"$UID checkstat error\"\n    $RUNAS $CHECKSTAT -p 0666 $file || error \"$RUNAS_ID checkstat error\"\n    $RUNAS cat $file > /dev/null || error \"$RUNAS_ID cat error\"\n\n    # start multiop\n    $RUNAS $MULTIOP $file o_r &\n    OPPID=$!\n    # wait multiop finish its open()\n    sleep 1\n\n    # cleanup all cred/ctx and check\n    # metadata check should fail, but file data check should success\n    # because we always use root credential to OSTs\n    $RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n    echo \"destroied credentials/contexs for $RUNAS_ID\"\n    $RUNAS $CHECKSTAT -p 0666 $file && error \"checkstat succeed\"\n    kill -s 10 $OPPID\n    wait $OPPID || error \"read file data failed\"\n    echo \"read file data OK\"\n}\nrun_test 3 \"local cache under DLM lock\"\n\ntest_6() {\n    local nfile=10\n\n    mkdir $DIR/d6 || error \"mkdir $DIR/d6 failed\"\n    for ((i=0; i<$nfile; i++)); do\n        dd if=/dev/zero of=$DIR/d6/file$i bs=8k count=1 || error \"dd file$i failed\"\n    done\n    ls -l $DIR/d6/* > /dev/null || error \"ls failed\"\n    rm -rf $DIR2/d6/* || error \"rm failed\"\n    rmdir $DIR2/d6/ || error \"rmdir failed\"\n}\nrun_test 6 \"test basic DLM callback works\"\n\ntest_7() {\n\tlocal tdir=$DIR/d7\n\tlocal num_osts\n\n\t# for open(), client only reserve space for default stripe count lovea,\n\t# and server may return larger lovea in reply (because of larger stripe\n\t# count), client need call enlarge_reqbuf() and save the replied lovea\n\t# in request for future possible replay.\n\t#\n\t# Note: current script does NOT guarantee enlarge_reqbuf() will be in\n\t# the path, however it does work in local test which has 2 OSTs and\n\t# default stripe count is 1.\n\tnum_osts=$($LFS getstripe $MOUNT | egrep \"^[0-9]*:.*ACTIVE\" | wc -l)\n\techo \"found $num_osts active OSTs\"\n\t[ $num_osts -lt 2 ] &&\n\t\techo \"skipping $TESTNAME (must have >= 2 OSTs)\" && return\n\n\tmkdir $tdir || error \"mkdir $tdir failed\"\n\t$LFS setstripe -c $num_osts $tdir || error \"setstripe -c $num_osts\"\n\n\techo \"creating...\"\n\tfor ((i = 0; i < 20; i++)); do\n\t\tdd if=/dev/zero of=$tdir/f$i bs=4k count=16 2>/dev/null\n\tdone\n\techo \"reading...\"\n\tfor ((i = 0; i < 20; i++)); do\n\t\tdd if=$tdir/f$i of=/dev/null bs=4k count=16 2>/dev/null\n\tdone\n\trm -rf $tdir\n}\nrun_test 7 \"exercise enlarge_reqbuf()\"\n\ntest_8()\n{\n    local ATHISTORY=$(do_facet $SINGLEMDS \"find /sys/ -name at_history\")\n    local ATOLDBASE=$(do_facet $SINGLEMDS \"cat $ATHISTORY\")\n    local REQ_DELAY\n    do_facet $SINGLEMDS \"echo 8 >> $ATHISTORY\"\n\n    mkdir -p $DIR/d8\n    chmod a+w $DIR/d8\n\n    $LCTL dk > /dev/null\n    debugsave\n    sysctl -w lnet.debug=\"+other\"\n\n    # wait for the at estimation come down, this is faster\n    while [ true ]; do\n        REQ_DELAY=`lctl get_param -n mdc.${FSNAME}-MDT0000-mdc-*.timeouts |\n                   awk '/portal 12/ {print $5}' | tail -1`\n        [ $REQ_DELAY -le 5 ] && break\n        echo \"current AT estimation is $REQ_DELAY, wait a little bit\"\n        sleep 8\n    done\n    REQ_DELAY=$((${REQ_DELAY} + ${REQ_DELAY} / 4 + 5))\n\n    # sleep sometime in ctx handle\n    do_facet $SINGLEMDS lctl set_param fail_val=$REQ_DELAY\n#define OBD_FAIL_SEC_CTX_HDL_PAUSE       0x1204\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x1204\n\n    $RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\n    $RUNAS touch $DIR/d8/f &\n    TOUCHPID=$!\n    echo \"waiting for touch (pid $TOUCHPID) to finish...\"\n    sleep 2 # give it a chance to really trigger context init rpc\n    do_facet $SINGLEMDS $LCTL set_param fail_loc=0\n    wait $TOUCHPID || error \"touch should have succeeded\"\n\n    $LCTL dk | grep -i \"Early reply #\" || error \"No early reply\"\n\n    debugrestore\n    do_facet $SINGLEMDS \"echo $ATOLDBASE >> $ATHISTORY\" || true\n}\nrun_test 8 \"Early reply sent for slow gss context negotiation\"\n\n#\n# following tests will manipulate flavors and may end with any flavor set,\n# so each test should not assume any start flavor.\n#\n\ntest_90() {\n    if [ \"$SLOW\" = \"no\" ]; then\n        total=10\n    else\n        total=60\n    fi\n\n    restore_to_default_flavor\n\tset_rule $FSNAME any any gssnull\n\twait_flavor all2all gssnull\n\n    start_dbench\n\n    for ((n=0;n<$total;n++)); do\n        sleep 2\n        check_dbench\n        echo \"flush ctx ($n/$total) ...\"\n        $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n    done\n    check_dbench\n    #sleep to let ctxs be re-established\n    sleep 10\n    stop_dbench\n}\nrun_test 90 \"recoverable from losing contexts under load\"\n\ntest_99() {\n    local nrule_old=0\n    local nrule_new=0\n    local max=64\n\n    #\n    # general rules\n    #\n    nrule_old=`do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME 2>/dev/null \\\n               | grep \"$FSNAME.srpc.flavor.\" | wc -l`\n    echo \"original general rules: $nrule_old\"\n\n    for ((i = $nrule_old; i < $max; i++)); do\n        set_rule $FSNAME elan$i any gssnull || error \"set rule $i\"\n    done\n    for ((i = $nrule_old; i < $max; i++)); do\n        set_rule $FSNAME elan$i any || error \"remove rule $i\"\n    done\n\n    nrule_new=`do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME 2>/dev/null \\\n               | grep \"$FSNAME.srpc.flavor.\" | wc -l`\n    if [ $nrule_new != $nrule_old ]; then\n        error \"general rule: $nrule_new != $nrule_old\"\n    fi\n}\nrun_test 99 \"set large number of sptlrpc rules\"\n\nerror_dbench()\n{\n    local err_str=$1\n\n    killall -9 dbench\n    sleep 1\n\n    error $err_str\n}\n\ntest_100() {\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\t# running dbench background\n\tstart_dbench\n\n\t#\n\t# all: null -> gssnull -> plain\n\t#\n\tset_rule $FSNAME any any gssnull\n\twait_flavor all2all gssnull || error_dbench \"1\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any any plain\n\twait_flavor all2all plain || error_dbench \"2\"\n\tcheck_dbench\n\n\t#\n\t# M - M: gssnull\n\t# C - M: gssnull\n\t# M - O: gssnull\n\t# C - O: gssnull\n\t#\n\tset_rule $FSNAME any mdt2mdt gssnull\n\twait_flavor mdt2mdt gssnull || error_dbench \"3\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any cli2mdt gssnull\n\twait_flavor cli2mdt gssnull || error_dbench \"4\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any mdt2ost gssnull\n\twait_flavor mdt2ost gssnull || error_dbench \"5\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any cli2ost gssnull\n\twait_flavor cli2ost gssnull || error_dbench \"6\"\n\tcheck_dbench\n\n\t#\n\t# * - MDT0: plain\n\t# * - OST0: plain\n\t#\n\t# nothing should be changed because they are override by above dir rules\n\t#\n\tset_rule $FSNAME-MDT0000 any any plain\n\tset_rule $FSNAME-OST0000 any any plain\n\twait_flavor mdt2mdt gssnull || error_dbench \"7\"\n\twait_flavor cli2mdt gssnull || error_dbench \"8\"\n\tcheck_dbench\n\twait_flavor mdt2ost gssnull || error_dbench \"9\"\n\twait_flavor cli2ost gssnull || error_dbench \"10\"\n\n\t#\n\t# delete all dir-specific rules\n\t#\n\tset_rule $FSNAME any mdt2mdt\n\tset_rule $FSNAME any cli2mdt\n\tset_rule $FSNAME any mdt2ost\n\tset_rule $FSNAME any cli2ost\n\twait_flavor mdt2mdt gssnull $((MDSCOUNT - 1)) || error_dbench \"11\"\n\twait_flavor cli2mdt gssnull $(get_clients_mount_count) ||\n\t\terror_dbench \"12\"\n\tcheck_dbench\n\twait_flavor mdt2ost gssnull $MDSCOUNT || error_dbench \"13\"\n\twait_flavor cli2ost gssnull $(get_clients_mount_count) ||\n\t\terror_dbench \"14\"\n\tcheck_dbench\n\n\t#\n\t# remove:\n\t#  * - MDT0: gssnull\n\t#  * - OST0: gssnull\n\t#\n\tset_rule $FSNAME-MDT0000 any any\n\tset_rule $FSNAME-OST0000 any any || error_dbench \"15\"\n\twait_flavor all2all plain || error_dbench \"16\"\n\tcheck_dbench\n\n\tstop_dbench\n}\nrun_test 100 \"change security flavor on the fly under load\"\n\nswitch_sec_test()\n{\n    local flavor0=$1\n    local flavor1=$2\n    local filename=$DIR/$tfile\n    local multiop_pid\n    local num\n\n    #\n    # after set to flavor0, start multop which use flavor0 rpc, and let\n    # server drop the reply; then switch to flavor1, the resend should be\n    # completed using flavor1. To exercise the code of switching ctx/sec\n    # for a resend request.\n    #\n    log \">>>>>>>>>>>>>>> Testing $flavor0 -> $flavor1 <<<<<<<<<<<<<<<<<<<\"\n\n    set_rule $FSNAME any cli2mdt $flavor0\n    wait_flavor cli2mdt $flavor0\n    rm -f $filename || error \"remove old $filename failed\"\n\n#MDS_REINT = 36\n#define OBD_FAIL_PTLRPC_DROP_REQ_OPC     0x513\n    do_facet $SINGLEMDS lctl set_param fail_val=36\n    do_facet $SINGLEMDS lctl set_param fail_loc=0x513\n    log \"starting multiop\"\n    $MULTIOP $filename m &\n    multiop_pid=$!\n    echo \"multiop pid=$multiop_pid\"\n    sleep 1\n\n    set_rule $FSNAME any cli2mdt $flavor1\n    wait_flavor cli2mdt $flavor1\n\n    num=`ps --no-headers -p $multiop_pid 2>/dev/null | wc -l`\n    [ $num -eq 1 ] || error \"multiop($multiop_pid) already ended ($num)\"\n    echo \"process $multiop_pid is still hanging there... OK\"\n\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n    log \"waiting for multiop ($multiop_pid) to finish\"\n    wait $multiop_pid || error \"multiop returned error\"\n}\n\ntest_101()\n{\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\tswitch_sec_test null    plain\n\tswitch_sec_test plain   gssnull\n\tswitch_sec_test gssnull null\n\tswitch_sec_test null    gssnull\n\tswitch_sec_test gssnull plain\n\tswitch_sec_test plain   gssnull\n}\nrun_test 101 \"switch ctx/sec for resending request\"\n\nerror_102()\n{\n    local err_str=$1\n\n    killall -9 dbench\n    sleep 1\n\n    error $err_str\n}\n\ntest_102() {\n    # started from default flavors\n    restore_to_default_flavor\n\n    # run dbench background\n    start_dbench\n\n\techo \"Testing null->gssnull->plain->null\"\n\tset_rule $FSNAME any any gssnull\n\tset_rule $FSNAME any any plain\n\tset_rule $FSNAME any any null\n\n    check_dbench\n    wait_flavor all2all null || error_dbench \"1\"\n    check_dbench\n\n    echo \"waiting for 15s and check again\"\n    sleep 15\n    check_dbench\n\n\techo \"Testing null->gssnull->null->gssnull->null...\"\n\tfor ((i=0; i<10; i++)); do\n\t\tset_rule $FSNAME any any gssnull\n\t\tset_rule $FSNAME any any null\n\tdone\n\tset_rule $FSNAME any any gssnull\n\n\tcheck_dbench\n\twait_flavor all2all gssnull || error_dbench \"2\"\n\tcheck_dbench\n\n    echo \"waiting for 15s and check again\"\n    sleep 15\n    check_dbench\n\n    stop_dbench\n}\nrun_test 102 \"survive from insanely fast flavor switch\"\n\ntest_150() {\n    local mount_opts\n    local count\n    local clients=$CLIENTS\n\n    [ -z $clients ] && clients=$HOSTNAME\n\n    # started from default flavors\n    restore_to_default_flavor\n\n    # at this time no rules has been set on mgs; mgc use null\n    # flavor connect to mgs.\n    count=`flvr_cnt_mgc2mgs null`\n    [ $count -eq 1 ] || error \"$count mgc connection use null flavor\"\n\n    zconf_umount_clients $clients $MOUNT || return 1\n\n    # mount client with conflict flavor - should fail\n    mount_opts=\"${MOUNT_OPTS:+$MOUNT_OPTS,}mgssec=gssnull\"\n    zconf_mount_clients $clients $MOUNT $mount_opts &&\n        error \"mount with conflict flavor should have failed\"\n\n    # mount client with same flavor - should succeed\n    mount_opts=\"${MOUNT_OPTS:+$MOUNT_OPTS,}mgssec=null\"\n    zconf_mount_clients $clients $MOUNT $mount_opts ||\n        error \"mount with same flavor should have succeeded\"\n    zconf_umount_clients $clients $MOUNT || return 2\n\n    # mount client with default flavor - should succeed\n    zconf_mount_clients $clients $MOUNT || \\\n        error \"mount with default flavor should have succeeded\"\n}\nrun_test 150 \"secure mgs connection: client flavor setting\"\n\ntest_151() {\n\tlocal save_opts\n\n\t# set mgs only accept gssnull\n\tset_rule _mgs any any gssnull\n\n    # umount everything, modules still loaded\n    stopall\n\n    # mount mgs with default flavor, in current framework it means mgs+mdt1.\n    # the connection of mgc of mdt1 to mgs is expected fail.\n    DEVNAME=$(mdsdevname 1)\n    start mds1 $DEVNAME $MDS_MOUNT_OPTS && error \"mount with default flavor should have failed\"\n\n    # mount with unauthorized flavor should fail\n    save_opts=$MDS_MOUNT_OPTS\n    MDS_MOUNT_OPTS=\"$MDS_MOUNT_OPTS,mgssec=null\"\n    start mds1 $DEVNAME $MDS_MOUNT_OPTS && error \"mount with unauthorized flavor should have failed\"\n    MDS_MOUNT_OPTS=$save_opts\n\n    # mount with designated flavor should succeed\n    save_opts=$MDS_MOUNT_OPTS\n\tMDS_MOUNT_OPTS=\"$MDS_MOUNT_OPTS,mgssec=gssnull\"\n\tstart mds1 $DEVNAME $MDS_MOUNT_OPTS ||\n\t\terror \"mount with designated flavor should have succeeded\"\n\tMDS_MOUNT_OPTS=$save_opts\n\n\tstop mds1 -f\n}\nrun_test 151 \"secure mgs connection: server flavor control\"\n\nstop_gss_daemons\nif $GSS_KRB5 || $GSS_SK; then\n\tstart_gss_daemons\nfi\n\nrestore_to_default_flavor\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 607}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# exit on error\nset -e\nset +o monitor\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_HSM_EXCEPT \"\nif $SHARED_KEY; then\n# bug number for skipped tests: LU-9795 LU-9795\n\tALWAYS_EXCEPT+=\"\t13      402b \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\nfi\n\n# Skip tests for PPC that fail frequently\nif [[ $(uname -m) = ppc64 ]]; then\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 1a       1b       1d       1e       12c      12f \"\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 12g      12h      12m      12n      12o      12p \"\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 12q      21       22       23       24a      24b \"\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 24d      24e      24f      25b      30c      37 \"\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 57       58       90       110b     111b     113 \"\n\t# bug number:    LU-12251 LU-12251 LU-12251 LU-12251 LU-12251 LU-12251\n\tALWAYS_EXCEPT+=\" 222b     222d     228      260a     260b     260c \"\n\t# bug number:    LU-12252 LU-12252 LU-12252 LU-12252 LU-12252 LU-12252\n\tALWAYS_EXCEPT+=\" 220A     220a     221      222a     222c     223a \"\n\t# bug number:    LU-12252 LU-12252 LU-12252 LU-12252 LU-12252 LU-12252\n\tALWAYS_EXCEPT+=\" 223b     224A     224a     226      227      600\"\n\t# bug number:    LU-12252 LU-12252 LU-12252 LU-12252 LU-12252 LU-12252\n\tALWAYS_EXCEPT+=\" 601      602      603      604      605 \"\nfi\n\nbuild_test_filter\n\n[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\nOPENFILE=${OPENFILE:-openfile}\nMOUNT_2=${MOUNT_2:-\"yes\"}\nFAIL_ON_ERROR=false\n\n# script only handles up to 10 MDTs (because of MDT_PREFIX)\n[ $MDSCOUNT -gt 9 ] &&\n\terror \"script cannot handle more than 9 MDTs, please fix\"\n\ncheck_and_setup_lustre\n\nif [[ $MDS1_VERSION -lt $(version_code 2.4.53) ]]; then\n\tskip_env \"Need MDS version at least 2.4.53\"\nfi\n\n# $RUNAS_ID may get set incorrectly somewhere else\nif [[ $UID -eq 0 && $RUNAS_ID -eq 0 ]]; then\n\tskip_env \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\nfi\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\nif getent group nobody; then\n\tGROUP=nobody\nelif getent group nogroup; then\n\tGROUP=nogroup\nelse\n\terror \"No generic nobody group\"\nfi\n\n# if there is no CLIENT1 defined, some tests can be ran on localhost\nCLIENT1=${CLIENT1:-$HOSTNAME}\n# if CLIENT2 doesn't exist then use CLIENT1 instead\n# All tests should use CLIENT2 with MOUNT2 only therefore it will work if\n# $CLIENT2 == CLIENT1\n# Exception is the test which need two separate nodes\nCLIENT2=${CLIENT2:-$CLIENT1}\n\nsearch_copytools() {\n\tlocal hosts=${1:-$(facet_active_host $SINGLEAGT)}\n\tdo_nodesv $hosts \"libtool execute pgrep -x $HSMTOOL\"\n}\n\nwait_copytools() {\n\tlocal hosts=${1:-$(facet_active_host $SINGLEAGT)}\n\tlocal wait_timeout=200\n\tlocal wait_start=$SECONDS\n\tlocal wait_end=$((wait_start + wait_timeout))\n\tlocal sleep_time=100000 # 0.1 second\n\n\twhile ((SECONDS < wait_end)); do\n\t\tif ! search_copytools $hosts; then\n\t\t\techo \"copytools stopped in $((SECONDS - wait_start))s\"\n\t\t\treturn 0\n\t\tfi\n\n\t\techo \"copytools still running on $hosts\"\n\t\tusleep $sleep_time\n\t\t[ $sleep_time -lt 32000000 ] && # 3.2 seconds\n\t\t\tsleep_time=$(bc <<< \"$sleep_time * 2\")\n\tdone\n\n\t# try to dump Copytool's stack\n\tdo_nodesv $hosts \"echo 1 >/proc/sys/kernel/sysrq ; \" \\\n\t\t\t \"echo t >/proc/sysrq-trigger\"\n\n\techo \"copytools failed to stop in ${wait_timeout}s\"\n\n\treturn 1\n}\n\ncopytool_monitor_setup() {\n\tlocal facet=${1:-$SINGLEAGT}\n\tlocal agent=$(facet_active_host $facet)\n\n\tlocal cmd=\"mktemp --tmpdir=/tmp -d ${TESTSUITE}.${TESTNAME}.XXXX\"\n\tlocal test_dir=$(do_node $agent \"$cmd\") ||\n\t\terror \"Failed to create tempdir on $agent\"\n\texport HSMTOOL_MONITOR_DIR=$test_dir\n\n\t# Create the fifo and a monitor (cat dies when copytool dies)\n\tdo_node $agent \"mkfifo -m 0644 $test_dir/fifo\" ||\n\t\terror \"failed to create copytool fifo on $agent\"\n\tcmd=\"cat $test_dir/fifo > $test_dir/events &\"\n\tcmd+=\" echo \\\\\\$! > $test_dir/monitor_pid\"\n\n\t# This background subshell nonsense is required when pdsh/ssh decides\n\t# to wait for the cat process to exit on the remote client\n\t(do_node $agent \"$cmd\") &\n\texport HSMTOOL_MONITOR_PDSH=$!\n\n\t# Slightly racy, but just making a best-effort to catch obvious\n\t# problems.\n\tsleep 1\n\tdo_node $agent \"stat $HSMTOOL_MONITOR_DIR/monitor_pid 2>&1 > /dev/null\"\n\tif [ $? != 0 ]; then\n\t\terror \"Failed to start copytool monitor on $agent\"\n\tfi\n}\n\nfid2archive()\n{\n\tlocal fid=\"$1\"\n\n\tcase \"$HSMTOOL\" in\n\tlhsmtool_posix)\n\t\tprintf \"%s\" \"$(hsm_root)/*/*/*/*/*/*/$fid\"\n\t\t;;\n\tesac\n}\n\nget_copytool_event_log() {\n\tlocal facet=${1:-$SINGLEAGT}\n\tlocal agent=$(facet_active_host $facet)\n\n\t[ -z \"$HSMTOOL_MONITOR_DIR\" ] &&\n\t\terror \"Can't get event log: No monitor directory!\"\n\n\tdo_node $agent \"cat $HSMTOOL_MONITOR_DIR/events\" ||\n\t\terror \"Could not collect event log from $agent\"\n}\n\ncopytool_suspend() {\n\tlocal agents=${1:-$(facet_active_host $SINGLEAGT)}\n\n\tstack_trap \\\n\t\t\"do_nodesv $agents libtool execute pkill -CONT -x '$HSMTOOL' || true\" EXIT\n\tdo_nodesv $agents \"libtool execute pkill -STOP -x $HSMTOOL\" || return 0\n\techo \"Copytool is suspended on $agents\"\n}\n\ncopytool_remove_backend() {\n\tlocal fid=$1\n\tlocal be=$(do_facet $SINGLEAGT find \"$(hsm_root)\" -name $fid)\n\techo \"Remove from backend: $fid = $be\"\n\tdo_facet $SINGLEAGT rm -f $be\n}\n\nfile_creation_failure() {\n\tlocal cmd=$1\n\tlocal file=$2\n\tlocal err=$3\n\n\tcase $err in\n\t28)\n\t\tdf $MOUNT $MOUNT2 >&2\n\t\terror \"Not enough space to create $file with $cmd\"\n\t\t;;\n\t*)\n\t\terror \"cannot create $file with $cmd, status=$err\"\n\t\t;;\n\tesac\n}\n\n# Creates a file using dd\ncreate_file() {\n\tlocal file=$1\n\tlocal bs=$2\n\tlocal count=$3\n\tlocal conv=$4\n\tlocal source=${5:-/dev/zero}\n\tlocal args=\"\"\n\tlocal err\n\n\tif [ -n \"$conv\" ]; then\n\t\targs+=\" conv=$conv\"\n\tfi\n\n\t# Create the directory in case it does not exist\n\tmkdir -p \"$(dirname \"$file\")\"\n\t# Delete the file in case it already exist\n\trm -f \"$file\"\n\n\tif dd if=\"$source\" of=\"$file\" count=\"$count\" bs=\"$bs\" $args; then\n\t\tpath2fid \"$file\" || error \"cannot get FID of '$file'\"\n\telse\n\t\terr=$?\n\t\techo \"cannot create file '$file'\" >&2;\n\t\t# Let the caller decide what to do on error\n\t\treturn $err;\n\tfi\n}\n\ncreate_empty_file() {\n\tcreate_file \"${1/$DIR/$DIR2}\" 1M 0 ||\n\t\tfile_creation_failure dd \"${1/$DIR/$DIR2}\" $?\n}\n\ncreate_small_file() {\n\tlocal source_file=/dev/urandom\n\tlocal count=1\n\tlocal bs=1M\n\tlocal conv=${2:-fsync}\n\n\tcreate_file \"${1/$DIR/$DIR2}\" $bs $count $conv $source_file ||\n\t\tfile_creation_failure dd \"${1/$DIR/$DIR2}\" $?\n}\n\ncreate_small_sync_file() {\n\tcreate_small_file \"$1\" sync\n}\n\ncreate_archive_file() {\n\tlocal file=\"$(hsm_root)/$1\"\n\tlocal count=${2:-39}\n\tlocal source=/dev/urandom\n\n\t# Create the counterpart directory of the archive\n\tdo_facet \"$SINGLEAGT\" mkdir -p \"$(dirname \"$file\")\" ||\n\t\terror \"cannot create archive directory '$(dirname \"$file\")'\"\n\n\tdo_facet \"$SINGLEAGT\" dd if=$source of=\"$file\" bs=1M count=$count ||\n\t\terror \"cannot create archive file '$file'\"\n}\n\ncopy2archive() {\n\tlocal hsm_root=\"$(hsm_root)\"\n\tlocal file=\"$hsm_root/$2\"\n\n\tstack_trap \"do_facet $SINGLEAGT rm -rf '$hsm_root'\" EXIT\n\tdo_facet $SINGLEAGT mkdir -p \"$(dirname \"$file\")\" ||\n\t    error \"mkdir '$(dirname \"$file\")' failed\"\n\tdo_facet $SINGLEAGT cp -p \"$1\" \"$file\" ||\n\t\terror \"cannot copy '$1' to '$file'\"\n}\n\nget_hsm_param() {\n\tlocal param=$1\n\tlocal val=$(do_facet $SINGLEMDS $LCTL get_param -n $HSM_PARAM.$param)\n\techo $val\n}\n\nset_test_state() {\n\tlocal cmd=$1\n\tlocal target=$2\n\tmdts_set_param \"\" hsm_control \"$cmd\"\n\tmdts_check_param hsm_control \"$target\" 10\n}\n\n\ncdt_set_no_retry() {\n\tmdts_set_param \"\" hsm.policy \"+NRA\"\n\tCDT_POLICY_HAD_CHANGED=true\n}\n\ncdt_clear_no_retry() {\n\tmdts_set_param \"\" hsm.policy \"-NRA\"\n\tCDT_POLICY_HAD_CHANGED=true\n}\n\ncdt_set_non_blocking_restore() {\n\tmdts_set_param \"\" hsm.policy \"+NBR\"\n\tCDT_POLICY_HAD_CHANGED=true\n}\n\ncdt_clear_non_blocking_restore() {\n\tmdts_set_param \"\" hsm.policy \"-NBR\"\n\tCDT_POLICY_HAD_CHANGED=true\n}\n\ncdt_clear_mount_state() {\n\tmdts_set_param \"-P -d\" hsm_control \"\"\n}\n\ncdt_disable() {\n\tset_test_state disabled disabled\n}\n\ncdt_enable() {\n\tset_test_state enabled enabled\n}\n\ncdt_shutdown() {\n\tset_test_state shutdown stopped\n}\n\ncdt_purge() {\n\tset_test_state purge enabled\n}\n\ncdt_restart() {\n\tcdt_shutdown\n\tcdt_enable\n\tcdt_set_sanity_policy\n}\n\n\nget_hsm_archive_id() {\n\tlocal f=$1\n\tlocal st\n\tst=$($LFS hsm_state $f)\n\t[[ $? == 0 ]] || error \"$LFS hsm_state $f failed\"\n\n\tlocal ar=$(echo $st | grep -oP '(?<=archive_id:).*')\n\techo $ar\n}\n\ncheck_hsm_flags_user() {\n\tlocal f=$1\n\tlocal fl=$2\n\n\tlocal st=$(get_hsm_flags $f user)\n\t[[ $st == $fl ]] || error \"hsm flags on $f are $st != $fl\"\n}\n\ncopy_file() {\n\tlocal f=\n\n\tif [[ -d $2 ]]; then\n\t\tf=$2/$(basename $1)\n\telse\n\t\tf=$2\n\tfi\n\n\tif [[ \"$3\" != 1 ]]; then\n\t\tf=${f/$DIR/$DIR2}\n\tfi\n\trm -f $f\n\tcp $1 $f || file_creation_failure cp $f $?\n\n\tpath2fid $f || error \"cannot get fid on $f\"\n}\n\n# Delete any file bigger than 10M under $MOUNT and wait for deletes to complete\n#\n# Note that this might lead to surprising behaviours such as deleting an\n# important file for the currently running test\ndelete_large_files() {\n\tprintf \"Deleting large files...\\n\" >&2\n\tfind $MOUNT -size +10M -delete\n\twait_delete_completed\n}\n\nget_request_state() {\n\tlocal fid=$1\n\tlocal request=$2\n\n\tdo_facet $SINGLEMDS \"$LCTL get_param -n $HSM_PARAM.actions |\"\\\n\t\t\"awk '/'$fid'.*action='$request'/ {print \\\\\\$13}' | cut -f2 -d=\"\n}\n\nget_request_count() {\n\tlocal fid=$1\n\tlocal request=$2\n\n\tdo_facet $SINGLEMDS \"$LCTL get_param -n $HSM_PARAM.actions |\"\\\n\t\t\"awk -vn=0 '/'$fid'.*action='$request'/ {n++}; END {print n}'\"\n}\n\n# Ensure the number of HSM request for a given FID is correct\n# assert_request_count FID REQUEST_TYPE COUNT [ERROR_MSG]\nassert_request_count() {\n\tlocal request_count=$(get_request_count $1 $2)\n\tlocal default_error_msg=(\"expected $3 '$2' request(s) for '$1', found \"\n\t\t\t\t\"'$request_count'\")\n\t[ $request_count -eq $3 ] || error \"${4:-\"${default_error_msg[@]}\"}\"\n}\n\nwait_all_done() {\n\tlocal timeout=$1\n\tlocal fid=$2\n\n\tlocal cmd=\"$LCTL get_param -n $HSM_PARAM.actions\"\n\t[[ -n $fid ]] && cmd+=\" | grep '$fid'\"\n\tcmd+=\" | egrep 'WAITING|STARTED'\"\n\n\twait_update_facet --verbose mds1 \"$cmd\" \"\" $timeout ||\n\t\terror \"requests did not complete\"\n}\n\nwait_for_grace_delay() {\n\tlocal val=$(get_hsm_param grace_delay)\n\tsleep $val\n}\n\nwait_for_loop_period() {\n\tlocal val=$(get_hsm_param loop_period)\n\tsleep $val\n}\n\nparse_json_event() {\n\tlocal raw_event=$1\n\n\t# python2.6 in EL6 includes an internal json module\n\tlocal json_parser='import json; import fileinput;'\n\tjson_parser+=' print \"\\n\".join([\"local %s=\\\"%s\\\"\" % tuple for tuple in '\n\tjson_parser+='json.loads([line for line in '\n\tjson_parser+='fileinput.input()][0]).items()])'\n\n\techo $raw_event | python -c \"$json_parser\"\n}\n\nget_agent_by_uuid_mdt() {\n\tlocal uuid=$1\n\tlocal mdtidx=$2\n\tlocal mds=mds$(($mdtidx + 1))\n\tdo_facet $mds \"$LCTL get_param -n ${MDT_PREFIX}${mdtidx}.hsm.agents |\\\n\t\t grep $uuid\"\n}\n\ncheck_agent_registered_by_mdt() {\n\tlocal uuid=$1\n\tlocal mdtidx=$2\n\tlocal mds=mds$(($mdtidx + 1))\n\tlocal agent=$(get_agent_by_uuid_mdt $uuid $mdtidx)\n\tif [[ ! -z \"$agent\" ]]; then\n\t\techo \"found agent $agent on $mds\"\n\telse\n\t\terror \"uuid $uuid not found in agent list on $mds\"\n\tfi\n}\n\ncheck_agent_unregistered_by_mdt() {\n\tlocal uuid=$1\n\tlocal mdtidx=$2\n\tlocal mds=mds$(($mdtidx + 1))\n\tlocal agent=$(get_agent_by_uuid_mdt $uuid $mdtidx)\n\tif [[ -z \"$agent\" ]]; then\n\t\techo \"uuid not found in agent list on $mds\"\n\telse\n\t\terror \"uuid found in agent list on $mds: $agent\"\n\tfi\n}\n\ncheck_agent_registered() {\n\tlocal uuid=$1\n\tlocal mdsno\n\tfor mdsno in $(seq 1 $MDSCOUNT); do\n\t\tcheck_agent_registered_by_mdt $uuid $((mdsno - 1))\n\tdone\n}\n\ncheck_agent_unregistered() {\n\tlocal uuid=$1\n\tlocal mdsno\n\tfor mdsno in $(seq 1 $MDSCOUNT); do\n\t\tcheck_agent_unregistered_by_mdt $uuid $((mdsno - 1))\n\tdone\n}\n\nget_agent_uuid() {\n\tlocal agent=${1:-$(facet_active_host $SINGLEAGT)}\n\n\t# Lustre mount-point is mandatory and last parameter on\n\t# copytool cmd-line.\n\tlocal mntpnt=$(do_rpc_nodes $agent libtool execute ps -C $HSMTOOL -o args= |\n\t\t       awk '{print $NF}')\n\t[ -n \"$mntpnt\" ] || error \"Found no Agent or with no mount-point \"\\\n\t\t\t\t  \"parameter\"\n\tdo_rpc_nodes $agent get_client_uuid $mntpnt | cut -d' ' -f2\n}\n\n# initiate variables\ninit_agt_vars\n\n# populate MDT device array\nget_mdt_devices\n\n# cleanup from previous bad setup\nkill_copytools\n\n# for recovery tests, coordinator needs to be started at mount\n# so force it\n# the lustre conf must be without hsm on (like for sanity.sh)\necho \"Set HSM on and start\"\ncdt_set_mount_state enabled\ncdt_check_state enabled\n\necho \"Set sanity-hsm HSM policy\"\ncdt_set_sanity_policy\n\n# finished requests are quickly removed from list\nset_hsm_param grace_delay 10\n\nCLIENT_NIDS=( $($LCTL list_nids all) )\n\ntest_1A() { # was test_1\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\t$RUNAS touch $f\n\n\t# User flags\n\tcheck_hsm_flags_user $f \"0x00000000\"\n\n\t$RUNAS $LFS hsm_set --norelease $f ||\n\t\terror \"user could not change hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000010\"\n\n\t$RUNAS $LFS hsm_clear --norelease $f ||\n\t\terror \"user could not clear hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000000\"\n\n\t# User could not change those flags...\n\t$RUNAS $LFS hsm_set --exists $f &&\n\t\terror \"user should not set this flag\"\n\tcheck_hsm_flags_user $f \"0x00000000\"\n\n\t# ...but root can\n\t$LFS hsm_set --exists $f ||\n\t\terror \"root could not change hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000001\"\n\n\t$LFS hsm_clear --exists $f ||\n\t\terror \"root could not clear hsm state\"\n\tcheck_hsm_flags_user $f \"0x00000000\"\n\n}\nrun_test 1A \"lfs hsm flags root/non-root access\"\n\ntest_1a() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\tcopytool setup\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Release and check states\n\t$LFS hsm_release $f || error \"could not release file\"\n\techo -n \"Verifying released state: \"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\t$MMAP_CAT $f > /dev/null || error \"failed mmap & cat release file\"\n}\nrun_test 1a \"mmap & cat a HSM released file\"\n\ntest_1bde_base() {\n\tlocal f=$1\n\trm -f $f\n\n\tdd if=/dev/urandom of=$f bs=1M count=1 conv=sync ||\n\t\terror \"failed to create file\"\n\tlocal fid=$(path2fid $f)\n\n\tcopytool setup\n\n\techo \"archive $f\"\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\techo \"release $f\"\n\t$LFS hsm_release $f || error \"could not release file\"\n\techo \"verify released state: \"\n\tcheck_hsm_flags $f \"0x0000000d\" && echo \"pass\"\n\n\techo \"restore $f\"\n\t$LFS hsm_restore $f || error \"could not restore file\"\n\twait_request_state $fid RESTORE SUCCEED\n\techo \"verify restored state: \"\n\tcheck_hsm_flags $f \"0x00000009\" && echo \"pass\"\n}\n\ntest_1b() {\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -S 1M -E 64M -c 2 -E -1 -c 4 $DIR/$tdir ||\n\t\terror \"failed to set default stripe\"\n\tlocal f=$DIR/$tdir/$tfile\n\n\ttest_1bde_base $f\n}\nrun_test 1b \"Archive, Release and Restore composite file\"\n\ntest_1c() {\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\t$RUNAS touch $f\n\n\t# Test whether we can set the maximum archive number.\n\tlocal LOCAL_HSM_ARCHIVE_NUMBER=32\n\t$LFS hsm_set --exists --archive-id $LOCAL_HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"root could not change hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000001\"\n\techo \"verifying archive number is $LOCAL_HSM_ARCHIVE_NUMBER\"\n\tlocal st=$(get_hsm_archive_id $f)\n\t[[ $st == $LOCAL_HSM_ARCHIVE_NUMBER ]] ||\n\t\terror \"wrong archive number, $st != $LOCAL_HSM_ARCHIVE_NUMBER\"\n\n\t# Test whether setting archive number 0 results in no change.\n\t$LFS hsm_set --exists --archive-id 0 $f ||\n\t\terror \"root could not change hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000001\"\n\techo \"verifying archive number is still $LOCAL_HSM_ARCHIVE_NUMBER\"\n\tst=$(get_hsm_archive_id $f)\n\t[[ $st == $LOCAL_HSM_ARCHIVE_NUMBER ]] ||\n\t\terror \"wrong archive number, $st != $LOCAL_HSM_ARCHIVE_NUMBER\"\n\n\tLOCAL_HSM_ARCHIVE_NUMBER=33\n\tif [ $(lustre_version_code client) -ge $(version_code 2.11.56) ] &&\n\t   [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.11.56) ]; then\n\t\t# lustre in the new version supports unlimited archiveID.\n\t\t# Test whether setting archive number > 32 is supported\n\t\t$LFS hsm_set --exists --archive-id $LOCAL_HSM_ARCHIVE_NUMBER $f ||\n\t\t\terror \"archive ID $LOCAL_HSM_ARCHIVE_NUMBER too large?\"\n\t\tcheck_hsm_flags_user $f \"0x00000001\"\n\n\t\techo \"verifying archive number is $LOCAL_HSM_ARCHIVE_NUMBER\"\n\t\tst=$(get_hsm_archive_id $f)\n\t\t[[ $st == $LOCAL_HSM_ARCHIVE_NUMBER ]] ||\n\t\t\terror \"wrong archive number, $st != $LOCAL_HSM_ARCHIVE_NUMBER\"\n\telse\n\t\t# old client or old mds can only support at most 32 archiveID\n\t\t# test whether setting archive number > 32 results in error.\n\t\t$LFS hsm_set --exists --archive-id $LOCAL_HSM_ARCHIVE_NUMBER $f &&\n\t\t\terror \"bitmap archive number is larger than 32\"\n\t\tcheck_hsm_flags_user $f \"0x00000001\"\n\tfi\n\n\t# Test whether setting archive number 16 and archived flag.\n\tLOCAL_HSM_ARCHIVE_NUMBER=16\n\t$LFS hsm_set --exists --archived \\\n\t     --archive-id $LOCAL_HSM_ARCHIVE_NUMBER $f ||\n\t    error \"root could not change hsm flags\"\n\tcheck_hsm_flags_user $f \"0x00000009\"\n\techo \"verifying archive number is $LOCAL_HSM_ARCHIVE_NUMBER\"\n\tst=$(get_hsm_archive_id $f)\n\t[[ $st == $LOCAL_HSM_ARCHIVE_NUMBER ]] ||\n\t\terror \"wrong archive number, $st != $LOCAL_HSM_ARCHIVE_NUMBER\"\n}\nrun_test 1c \"Check setting archive-id in lfs hsm_set\"\n\ntest_1d() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.59) ] &&\n\t\tskip \"need MDS version at least 2.10.59\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt -E -1 -c 2 $DIR/$tdir ||\n\t\terror \"failed to set default stripe\"\n\tlocal f=$DIR/$tdir/$tfile\n\n\ttest_1bde_base $f\n}\nrun_test 1d \"Archive, Release and Restore DoM file\"\n\ntest_1e() {\n\t[ $(lustre_version_code $SINGLEMDS) -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1G -z 64M -E 10G -z 512M -E -1 -z 1G $DIR/$tdir ||\n\t\terror \"failed to set default stripe\"\n\tlocal comp_file=$DIR/$tdir/$tfile\n\n\ttest_1bde_base $comp_file\n\n\tlocal flg_opts=\"--comp-start 0 -E 64M --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"1st component not found\"\n\n\tflg_opts=\"--comp-start 64M -E 1G --comp-flags extension\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"2nd component not found\"\n\n\tflg_opts=\"--comp-start 1G -E 1G --comp-flags ^init\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"3rd component not found\"\n\n\tflg_opts=\"--comp-start 1G -E 10G --comp-flags extension\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"4th component not found\"\n\n\tflg_opts=\"--comp-start 10G -E 10G --comp-flags ^init\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"5th component not found\"\n\n\tflg_opts=\"--comp-start 10G -E EOF --comp-flags extension\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"6th component not found\"\n\n\tsel_layout_sanity $comp_file 6\n}\nrun_test 1e \"Archive, Release and Restore SEL file\"\n\ntest_2() {\n\tlocal f=$DIR/$tdir/$tfile\n\n\tcreate_empty_file \"$f\"\n\t# New files are not dirty\n\tcheck_hsm_flags $f \"0x00000000\"\n\n\t# For test, we simulate an archived file.\n\t$LFS hsm_set --exists $f || error \"user could not change hsm flags\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# chmod do not put the file dirty\n\tchmod 600 $f || error \"could not chmod test file\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# chown do not put the file dirty\n\tchown $RUNAS_ID $f || error \"could not chown test file\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# truncate put the file dirty\n\t$TRUNCATE $f 1 || error \"could not truncate test file\"\n\tcheck_hsm_flags $f \"0x00000003\"\n\n\t$LFS hsm_clear --dirty $f || error \"could not clear hsm flags\"\n\tcheck_hsm_flags $f \"0x00000001\"\n}\nrun_test 2 \"Check file dirtyness when doing setattr\"\n\ntest_3() {\n\tmkdir -p $DIR/$tdir\n\tf=$DIR/$tdir/$tfile\n\n\t# New files are not dirty\n\tcp -p /etc/passwd $f\n\tcheck_hsm_flags $f \"0x00000000\"\n\n\t# For test, we simulate an archived file.\n\t$LFS hsm_set --exists $f ||\n\t\terror \"user could not change hsm flags\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# Reading a file, does not set dirty\n\tcat $f > /dev/null || error \"could not read file\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# Open for write without modifying data, does not set dirty\n\topenfile -f O_WRONLY $f || error \"could not open test file\"\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# Append to a file sets it dirty\n\tcp -p /etc/passwd $f.append || error \"could not create file\"\n\t$LFS hsm_set --exists $f.append ||\n\t\terror \"user could not change hsm flags\"\n\tdd if=/etc/passwd of=$f.append bs=1 count=3\\\n\t   conv=notrunc oflag=append status=noxfer ||\n\t\tfile_creation_failure dd $f.append $?\n\tcheck_hsm_flags $f.append \"0x00000003\"\n\n\t# Modify a file sets it dirty\n\tcp -p /etc/passwd $f.modify || error \"could not create file\"\n\t$LFS hsm_set --exists $f.modify ||\n\t\terror \"user could not change hsm flags\"\n\tdd if=/dev/zero of=$f.modify bs=1 count=3\\\n\t   conv=notrunc status=noxfer ||\n\t\tfile_creation_failure dd $f.modify $?\n\tcheck_hsm_flags $f.modify \"0x00000003\"\n\n\t# Open O_TRUNC sets dirty\n\tcp -p /etc/passwd $f.trunc || error \"could not create file\"\n\t$LFS hsm_set --exists $f.trunc ||\n\t\terror \"user could not change hsm flags\"\n\tcp /etc/group $f.trunc || error \"could not override a file\"\n\tcheck_hsm_flags $f.trunc \"0x00000003\"\n\n\t# Mmapped a file sets dirty\n\tcp -p /etc/passwd $f.mmap || error \"could not create file\"\n\t$LFS hsm_set --exists $f.mmap ||\n\t\terror \"user could not change hsm flags\"\n\tmultiop $f.mmap OSMWUc || error \"could not mmap a file\"\n\tcheck_hsm_flags $f.mmap \"0x00000003\"\n}\nrun_test 3 \"Check file dirtyness when opening for write\"\n\ntest_4() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\t$LFS hsm_cancel $f\n\tlocal st=$(get_request_state $fid CANCEL)\n\t[[ -z \"$st\" ]] || error \"hsm_cancel must not be registered (state=$st)\"\n}\nrun_test 4 \"Useless cancel must not be registered\"\n\ntest_8() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\t$LFS hsm_archive $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcheck_hsm_flags $f \"0x00000009\"\n}\nrun_test 8 \"Test default archive number\"\n\ntest_9A() { # was test_9\n\t# we do not use the default one to be sure\n\tlocal archive_id=$((HSM_ARCHIVE_NUMBER + 1))\n\tcopytool setup --archive-id $archive_id\n\n\t# give time for CT to register with MDTs\n\tsleep $(($MDSCOUNT*2))\n\tlocal uuid=$(get_agent_uuid $(facet_active_host $SINGLEAGT))\n\tcheck_agent_registered $uuid\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\t$LFS hsm_archive --archive $archive_id $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcheck_hsm_flags $f \"0x00000009\"\n}\nrun_test 9A \"Use of explicit archive number, with dedicated copytool\"\n\ntest_9a() {\n\tneedclients 3 || return 0\n\n\tlocal n\n\tlocal file\n\tlocal fid\n\n\t# start all of the copytools\n\tfor n in $(seq $AGTCOUNT); do\n\t\tcopytool setup --facet agt$n\n\tdone\n\n\t# archive files\n\tfor n in $(seq $AGTCOUNT); do\n\t\tfile=$DIR/$tdir/$tfile.$n\n\t\tfid=$(create_small_file $file)\n\n\t\t$LFS hsm_archive $file || error \"could not archive file $file\"\n\t\twait_request_state $fid ARCHIVE SUCCEED\n\t\tcheck_hsm_flags $file \"0x00000009\"\n\tdone\n}\nrun_test 9a \"Multiple remote agents\"\n\ntest_10a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir/d1\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_archive -a $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"hsm_archive failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal hsm_root=\"$(copytool_device $SINGLEAGT)\"\n\tlocal archive=\"$(do_facet $SINGLEAGT \\\n\t\t\t find \"$hsm_root\" -name \"$fid\" -print0)\"\n\t[ -n \"$archive\" ] || error \"fid '$fid' not in archive '$hsm_root'\"\n\n\techo \"Verifying content\"\n\tdo_facet $SINGLEAGT diff $f $archive || error \"archived file differs\"\n\techo \"Verifying hsm state \"\n\tcheck_hsm_flags $f \"0x00000009\"\n\n\techo \"Verifying archive number is $HSM_ARCHIVE_NUMBER\"\n\tlocal st=$(get_hsm_archive_id $f)\n\t[[ $st == $HSM_ARCHIVE_NUMBER ]] ||\n\t\terror \"Wrong archive number, $st != $HSM_ARCHIVE_NUMBER\"\n}\nrun_test 10a \"Archive a file\"\n\ntest_10b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_archive $f || error \"archive request failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_archive $f || error \"archive of non dirty file failed\"\n\tlocal cnt=$(get_request_count $fid ARCHIVE)\n\t[[ \"$cnt\" == \"1\" ]] ||\n\t\terror \"archive of non dirty file must not make a request\"\n}\nrun_test 10b \"Archive of non dirty file must work without doing request\"\n\ntest_10c() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_set --noarchive $f\n\t$LFS hsm_archive $f && error \"archive a noarchive file must fail\"\n\treturn 0\n}\nrun_test 10c \"Check forbidden archive\"\n\ntest_10d() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_archive $f || error \"cannot archive $f\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal ar=$(get_hsm_archive_id $f)\n\tlocal dflt=$(get_hsm_param default_archive_id)\n\t[[ $ar == $dflt ]] ||\n\t\terror \"archived file is not on default archive: $ar != $dflt\"\n}\nrun_test 10d \"Archive a file on the default archive id\"\n\ntest_11a() {\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/hosts $tdir/$tfile\n\tlocal f=$DIR/$tdir/$tfile\n\n\tcopytool import $tdir/$tfile $f\n\techo -n \"Verifying released state: \"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tlocal LSZ=$(stat -c \"%s\" $f)\n\tlocal ASZ=$(do_facet $SINGLEAGT stat -c \"%s\" \"$(hsm_root)/$tdir/$tfile\")\n\n\techo \"Verifying imported size $LSZ=$ASZ\"\n\t[[ $LSZ -eq $ASZ ]] || error \"Incorrect size $LSZ != $ASZ\"\n\techo -n \"Verifying released pattern: \"\n\tlocal PTRN=$($LFS getstripe -L $f)\n\techo $PTRN\n\t[[ $PTRN == released ]] || error \"Is not released\"\n\tlocal fid=$(path2fid $f)\n\techo \"Verifying new fid $fid in archive\"\n\n\tdo_facet $SINGLEAGT \"[ -f \\\"$(fid2archive \"$fid\")\\\" ]\" ||\n\t\terror \"No archive for fid $fid\"\n}\nrun_test 11a \"Import a file\"\n\ntest_11b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_archive -a $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"hsm_archive failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal FILE_HASH=$(md5sum $f)\n\trm -f $f\n\n\tcopytool import $fid $f\n\n\techo \"$FILE_HASH\" | md5sum -c\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 11b \"Import a deleted file using its FID\"\n\ntest_12a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/hosts $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal f2=$DIR2/$tdir/$tfile\n\techo \"Verifying released state: \"\n\tcheck_hsm_flags $f2 \"0x0000000d\"\n\n\tlocal fid=$(path2fid $f2)\n\t$LFS hsm_restore $f2\n\twait_request_state $fid RESTORE SUCCEED\n\n\techo \"Verifying file state: \"\n\tcheck_hsm_flags $f2 \"0x00000009\"\n\n\tdo_facet $SINGLEAGT diff -q $(hsm_root)/$tdir/$tfile $f\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12a \"Restore an imported file explicitly\"\n\ntest_12b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/hosts $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\techo \"Verifying released state: \"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tcat $f > /dev/null || error \"File read failed\"\n\n\techo \"Verifying file state after restore: \"\n\tcheck_hsm_flags $f \"0x00000009\"\n\n\tdo_facet $SINGLEAGT diff -q $(hsm_root)/$tdir/$tfile $f\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12b \"Restore an imported file implicitly\"\n\ntest_12c() {\n\t[ \"$OSTCOUNT\" -lt \"2\" ] && skip_env \"needs >= 2 OSTs\" && return\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c 2 \"$f\"\n\tlocal fid=$(create_file \"$f\" 1M 5)\n\n\tlocal FILE_CRC=$(md5sum $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"release $f failed\"\n\n\techo \"$FILE_CRC\" | md5sum -c\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12c \"Restore a file with stripe of 2\"\n\ntest_12d() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_restore $f || error \"restore of non archived file failed\"\n\tlocal cnt=$(get_request_count $fid RESTORE)\n\t[[ \"$cnt\" == \"0\" ]] ||\n\t\terror \"restore non archived must not make a request\"\n\t$LFS hsm_archive $f ||\n\t\terror \"archive request failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_restore $f ||\n\t\terror \"restore of non released file failed\"\n\tlocal cnt=$(get_request_count $fid RESTORE)\n\t[[ \"$cnt\" == \"0\" ]] ||\n\t\terror \"restore a non dirty file must not make a request\"\n}\nrun_test 12d \"Restore of a non archived, non released file must work\"\\\n\t\t\" without doing request\"\n\ntest_12e() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\t$LFS hsm_archive $f || error \"archive request failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# make file dirty\n\tcat /etc/hosts >> $f\n\tsync\n\t$LFS hsm_state $f\n\n\t$LFS hsm_restore $f && error \"restore a dirty file must fail\"\n\treturn 0\n}\nrun_test 12e \"Check forbidden restore\"\n\ntest_12f() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"release of $f failed\"\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE SUCCEED\n\n\techo -n \"Verifying file state: \"\n\tcheck_hsm_flags $f \"0x00000009\"\n\n\tdiff -q /etc/hosts $f\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12f \"Restore a released file explicitly\"\n\ntest_12g() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"release of $f failed\"\n\n\tdiff -q /etc/hosts $f\n\tlocal st=$?\n\n\t# we check we had a restore done\n\twait_request_state $fid RESTORE SUCCEED\n\n\t[[ $st -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12g \"Restore a released file implicitly\"\n\ntest_12h() {\n\tneedclients 2 || return 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"release of $f failed\"\n\n\tdo_node $CLIENT2 diff -q /etc/hosts $f\n\tlocal st=$?\n\n\t# we check we had a restore done\n\twait_request_state $fid RESTORE SUCCEED\n\n\t[[ $st -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12h \"Restore a released file implicitly from a second node\"\n\ntest_12m() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\t$LFS hsm_archive $f || error \"archive of $f failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $f || error \"release of $f failed\"\n\n\tcmp /etc/passwd $f\n\n\t[[ $? -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12m \"Archive/release/implicit restore\"\n\ntest_12n() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/hosts $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\n\tdo_facet $SINGLEAGT cmp /etc/hosts $f ||\n\t\terror \"Restored file differs\"\n\n\t$LFS hsm_release $f || error \"release of $f failed\"\n}\nrun_test 12n \"Import/implicit restore/release\"\n\ntest_12o() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"release of $f failed\"\n\n#define OBD_FAIL_MDS_HSM_SWAP_LAYOUTS\t\t0x152\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x152\n\n\t# set no retry action mode\n\tcdt_set_no_retry\n\n\tdiff -q /etc/hosts $f\n\tlocal st=$?\n\n\t# we check we had a restore failure\n\twait_request_state $fid RESTORE FAILED\n\n\t[[ $st -eq 0 ]] && error \"Restore must fail\"\n\n\t# remove no retry action mode\n\tcdt_clear_no_retry\n\n\t# check file is still released\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\t# retry w/o failure injection\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\n\t# to be sure previous RESTORE result is gone\n\tcdt_purge\n\twait_for_grace_delay\n\n\tdiff -q /etc/hosts $f\n\tst=$?\n\n\t# we check we had a restore done\n\twait_request_state $fid RESTORE SUCCEED\n\n\t[[ $st -eq 0 ]] || error \"Restored file differs\"\n}\nrun_test 12o \"Layout-swap failure during Restore leaves file released\"\n\ntest_12p() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\tdo_facet $SINGLEAGT cat $f > /dev/null || error \"cannot cat $f\"\n\t$LFS hsm_release $f || error \"cannot release $f\"\n\tdo_facet $SINGLEAGT cat $f > /dev/null || error \"cannot cat $f\"\n\t$LFS hsm_release $f || error \"cannot release $f\"\n\tdo_facet $SINGLEAGT cat $f > /dev/null || error \"cannot cat $f\"\n}\nrun_test 12p \"implicit restore of a file on copytool mount point\"\n\ntest_12q() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.58) ] &&\n\t\tskip \"need MDS version at least 2.7.58\"\n\n\tstack_trap \"zconf_umount \\\"$(facet_host $SINGLEAGT)\\\" \\\"$MOUNT3\\\"\" EXIT\n\tzconf_mount $(facet_host $SINGLEAGT) $MOUNT3 ||\n\t\terror \"cannot mount $MOUNT3 on $SINGLEAGT\"\n\n\t# test needs a running copytool\n\tcopytool setup -m \"$MOUNT3\"\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal f2=$DIR2/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\tlocal orig_size=$(stat -c \"%s\" $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $f || error \"could not release file\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tkill_copytools\n\twait_copytools || error \"copytool failed to stop\"\n\n\tcat $f > /dev/null &\n\n\t# wait a bit to allow implicit restore request to be handled.\n\t# if not, next stat would also block on layout-lock.\n\tsleep 5\n\n\tlocal size=$(stat -c \"%s\" $f2)\n\t[ $size -eq $orig_size ] ||\n\t\terror \"$f2: wrong size after archive: $size != $orig_size\"\n\n\tcopytool setup -m \"$MOUNT3\"\n\n\twait\n\n\tsize=$(stat -c \"%s\" $f)\n\t[ $size -eq $orig_size ] ||\n\t\terror \"$f: wrong size after restore: $size != $orig_size\"\n\n\tsize=$(stat -c \"%s\" $f2)\n\t[ $size -eq $orig_size ] ||\n\t\terror \"$f2: wrong size after restore: $size != $orig_size\"\n\n\t:>$f\n\n\tsize=$(stat -c \"%s\" $f)\n\t[ $size -eq 0 ] ||\n\t\terror \"$f: wrong size after overwrite: $size != 0\"\n\n\tsize=$(stat -c \"%s\" $f2)\n\t[ $size -eq 0 ] ||\n\t\terror \"$f2: wrong size after overwrite: $size != 0\"\n}\nrun_test 12q \"file attributes are refreshed after restore\"\n\ntest_13() {\n\tlocal -i i j k=0\n\tfor i in {1..10}; do\n\t\tlocal archive_dir=\"$(hsm_root)\"/subdir/dir.$i\n\n\t\tdo_facet $SINGLEAGT mkdir -p \"$archive_dir\"\n\t\tfor j in {1..10}; do\n\t\t\tlocal archive_file=\"$archive_dir\"/file.$j\n\n\t\t\tdo_facet $SINGLEAGT \"echo $k > \\\"$archive_dir\\\"/file.$j\"\n\t\t\tk+=1\n\t\tdone\n\tdone\n\n\t# import to Lustre\n\tcopytool import \"subdir\" \"$DIR/$tdir\"\n\n\t# To check the import, the test uses diff with the -r flag\n\t# This is nice, but diff only checks files one by one, and triggering\n\t# an implicit restore for one file at a time will consume as many\n\t# seconds as there are files to compare. To speed this up, a restore\n\t# operation is triggered manually first.\n\tcopytool setup\n\tfind \"$DIR/$tdir\"/subdir -type f -exec $LFS hsm_restore {} \\;\n\n\t# Compare the imported data\n\tdo_facet $SINGLEAGT \\\n\t\tdiff -r \"$(hsm_root)\"/subdir \"$DIR/$tdir\"/subdir ||\n\t\terror \"imported files differ from archived data\"\n}\nrun_test 13 \"Recursively import and restore a directory\"\n\ntest_14() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\t# archive a file\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\tlocal sum=$(md5sum $f | awk '{print $1}')\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# create released file (simulate llapi_hsm_import call)\n\tlocal fid2=$(create_empty_file \"$f\")\n\t$LFS hsm_set --archived --exists $f || error \"could not force hsm flags\"\n\t$LFS hsm_release $f || error \"could not release file\"\n\n\t# rebind the archive to the newly created file\n\techo \"rebind $fid to $fid2\"\n\n\tcopytool rebind $fid $fid2\n\n\t# restore file and compare md5sum\n\tlocal sum2=$(md5sum $f | awk '{print $1}')\n\n\t[[ $sum == $sum2 ]] || error \"md5sum mismatch after restore\"\n}\nrun_test 14 \"Rebind archived file to a new fid\"\n\ntest_15() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\t# archive files\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal count=5\n\tlocal tmpfile=$SHARED_DIRECTORY/tmp.$$\n\n\tlocal fids=()\n\tlocal sums=()\n\tfor i in $(seq 1 $count); do\n\t\tfids[$i]=$(create_small_file $f.$i)\n\t\tsums[$i]=$(md5sum $f.$i | awk '{print $1}')\n\t\t$LFS hsm_archive $f.$i || error \"could not archive file\"\n\tdone\n\twait_all_done $(($count*60))\n\n\tstack_trap \"rm -f $tmpfile\" EXIT\n\t:>$tmpfile\n\t# delete the files\n\tfor i in $(seq 1 $count); do\n\t\tlocal fid2=$(create_empty_file \"${f}.${i}\")\n\t\t# add the rebind operation to the list\n\t\techo ${fids[$i]} $fid2 >> $tmpfile\n\n\t\t# set it released (simulate llapi_hsm_import call)\n\t\t$LFS hsm_set --archived --exists $f.$i ||\n\t\t\terror \"could not force hsm flags\"\n\t\t$LFS hsm_release $f.$i || error \"could not release file\"\n\tdone\n\tnl=$(wc -l < $tmpfile)\n\t[[ $nl == $count ]] || error \"$nl files in list, $count expected\"\n\n\techo \"rebind list of files\"\n\tcopytool rebind \"$tmpfile\"\n\n\t# restore files and compare md5sum\n\tfor i in $(seq 1 $count); do\n\t\tlocal sum2=$(md5sum $f.$i | awk '{print $1}')\n\t\t[[ $sum2 == ${sums[$i]} ]] ||\n\t\t    error \"md5sum mismatch after restore ($sum2 != ${sums[$i]})\"\n\tdone\n}\nrun_test 15 \"Rebind a list of files\"\n\ntest_16() {\n\t# test needs a running copytool\n\tcopytool setup -b 1\n\n\tlocal ref=/tmp/ref\n\t# create a known size file so we can verify transfer speed\n\t# 20 MB <-> 20s\n\tlocal goal=20\n\tdd if=/dev/zero of=$ref bs=1M count=20\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file $ref $f)\n\trm $ref\n\tlocal start=$(date +%s)\n\t$LFS hsm_archive $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\tlocal end=$(date +%s)\n\t# Add 1 to account for rounding errors between start and end (LU-8155)\n\tlocal duration=$((end - start + 1))\n\n\t[[ $duration -ge $((goal - 1)) ]] ||\n\t\terror \"Transfer is too fast $duration < $goal\"\n}\nrun_test 16 \"Test CT bandwith control option\"\n\ntest_20() {\n\tlocal f=$DIR/$tdir/$tfile\n\tcreate_empty_file \"$f\"\n\n\t# Could not release a non-archived file\n\t$LFS hsm_release $f && error \"release should not succeed\"\n\n\t# For following tests, we must test them with HS_ARCHIVED set\n\t$LFS hsm_set --exists --archived $f || error \"could not add flag\"\n\n\t# Could not release a file if no-release is set\n\t$LFS hsm_set --norelease $f || error \"could not add flag\"\n\t$LFS hsm_release $f && error \"release should not succeed\"\n\t$LFS hsm_clear --norelease $f || error \"could not remove flag\"\n\n\t# Could not release a file if lost\n\t$LFS hsm_set --lost $f || error \"could not add flag\"\n\t$LFS hsm_release $f && error \"release should not succeed\"\n\t$LFS hsm_clear --lost $f || error \"could not remove flag\"\n\n\t# Could not release a file if dirty\n\t$LFS hsm_set --dirty $f || error \"could not add flag\"\n\t$LFS hsm_release $f && error \"release should not succeed\"\n\t$LFS hsm_clear --dirty $f || error \"could not remove flag\"\n}\nrun_test 20 \"Release is not permitted\"\n\ntest_21() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/test_release\n\n\t# Create a file and check its states\n\tlocal fid=$(create_small_file $f)\n\tcheck_hsm_flags $f \"0x00000000\"\n\n\t# LU-4388/LU-4389 - ZFS does not report full number of blocks\n\t# used until file is flushed to disk\n\tif [  $(facet_fstype ost1) == \"zfs\" ]; then\n\t    # this causes an OST_SYNC rpc to be sent\n\t    dd if=/dev/zero of=$f bs=512 count=1 oflag=sync conv=notrunc,fsync\n\t    # clear locks to reread file data\n\t    cancel_lru_locks osc\n\tfi\n\n\tlocal orig_size=$(stat -c \"%s\" $f)\n\tlocal orig_blocks=$(stat -c \"%b\" $f)\n\n\tstart_full_debug_logging\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal blocks=$(stat -c \"%b\" $f)\n\t[ $blocks -eq $orig_blocks ] ||\n\t\terror \"$f: wrong block number after archive: \" \\\n\t\t      \"$blocks != $orig_blocks\"\n\tlocal size=$(stat -c \"%s\" $f)\n\t[ $size -eq $orig_size ] ||\n\t\terror \"$f: wrong size after archive: $size != $orig_size\"\n\n\t# Release and check states\n\t$LFS hsm_release $f || error \"could not release file\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tblocks=$(stat -c \"%b\" $f)\n\t[ $blocks -gt 5 ] &&\n\t\terror \"$f: too many blocks after release: $blocks > 5\"\n\tsize=$(stat -c \"%s\" $f)\n\t[ $size -ne $orig_size ] &&\n\t\terror \"$f: wrong size after release: $size != $orig_size\"\n\n\t# Check we can release an file without stripe info\n\tf=$f.nolov\n\t$MCREATE $f\n\tfid=$(path2fid $f)\n\tcheck_hsm_flags $f \"0x00000000\"\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Release and check states\n\t$LFS hsm_release $f || error \"could not release file\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\t# Release again a file that is already released is OK\n\t$LFS hsm_release $f || fail \"second release should succeed\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tstop_full_debug_logging\n}\nrun_test 21 \"Simple release tests\"\n\ntest_22() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/test_release\n\tlocal swap=$DIR/$tdir/test_swap\n\n\t# Create a file and check its states\n\tlocal fid=$(create_small_file $f)\n\tcheck_hsm_flags $f \"0x00000000\"\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Release and check states\n\t$LFS hsm_release $f || error \"could not release file\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tcreate_small_file $swap\n\t$LFS swap_layouts $swap $f && error \"swap_layouts should failed\"\n\n\treturn 0\n}\nrun_test 22 \"Could not swap a release file\"\n\ntest_23() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/test_mtime\n\n\t# Create a file and check its states\n\tlocal fid=$(create_small_file $f)\n\tcheck_hsm_flags $f \"0x00000000\"\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Set modification time in the past\n\ttouch -m -a -d @978261179 $f\n\n\t# Release and check states\n\t$LFS hsm_release $f || error \"could not release file\"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tlocal MTIME=$(stat -c \"%Y\" $f)\n\tlocal ATIME=$(stat -c \"%X\" $f)\n\t[ $MTIME -eq \"978261179\" ] || fail \"bad mtime: $MTIME\"\n\t[ $ATIME -eq \"978261179\" ] || fail \"bad atime: $ATIME\"\n}\nrun_test 23 \"Release does not change a/mtime (utime)\"\n\ntest_24a() {\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal fid\n\tlocal atime0\n\tlocal atime1\n\tlocal mtime0\n\tlocal mtime1\n\tlocal ctime0\n\tlocal ctime1\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tfid=$(create_small_file $file)\n\n\t# Create a file and check its states\n\tcheck_hsm_flags $file \"0x00000000\"\n\n\t# Ensure atime is less than mtime and ctime.\n\tsleep 1\n\techo >> $file\n\n\tatime0=$(stat -c \"%X\" $file)\n\tmtime0=$(stat -c \"%Y\" $file)\n\tctime0=$(stat -c \"%Z\" $file)\n\n\t[ $atime0 -lt $mtime0 ] ||\n\t\terror \"atime $atime0 is not less than mtime $mtime0\"\n\n\t[ $atime0 -lt $ctime0 ] ||\n\t\terror \"atime $atime0 is not less than ctime $ctime0\"\n\n\t# Archive should not change any timestamps.\n\t$LFS hsm_archive $file || error \"cannot archive '$file'\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tatime1=$(stat -c \"%X\" $file)\n\tmtime1=$(stat -c \"%Y\" $file)\n\tctime1=$(stat -c \"%Z\" $file)\n\n\t[ $atime0 -eq $atime1 ] ||\n\t\terror \"archive changed atime from $atime0 to $atime1\"\n\n\t[ $mtime0 -eq $mtime1 ] ||\n\t\terror \"archive changed mtime from $mtime0 to $mtime1\"\n\n\t[ $ctime0 -eq $ctime1 ] ||\n\t\terror \"archive changed ctime from $ctime0 to $ctime1\"\n\n\t# Release should not change any timestamps.\n\t$LFS hsm_release $file || error \"cannot release '$file'\"\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\tatime1=$(stat -c \"%X\" $file)\n\tmtime1=$(stat -c \"%Y\" $file)\n\tctime1=$(stat -c \"%Z\" $file)\n\n\t[ $atime0 -eq $atime1 ] ||\n\t\terror \"release changed atime from $atime0 to $atime1\"\n\n\t[ $mtime0 -eq $mtime1 ] ||\n\t\terror \"release changed mtime from $mtime0 to $mtime1\"\n\n\t[ $ctime0 -eq $ctime1 ] ||\n\t\terror \"release changed ctime from $ctime0 to $ctime1\"\n\n\t# Restore should not change any timestamps.\n\t$LFS hsm_restore $file\n\twait_request_state $fid RESTORE SUCCEED\n\n\tatime1=$(stat -c \"%X\" $file)\n\tmtime1=$(stat -c \"%Y\" $file)\n\tctime1=$(stat -c \"%Z\" $file)\n\n\t[ $atime0 -eq $atime1 ] ||\n\t\terror \"restore changed atime from $atime0 to $atime1\"\n\n\t[ $mtime0 -eq $mtime1 ] ||\n\t\terror \"restore changed mtime from $mtime0 to $mtime1\"\n\n\t[ $ctime0 -eq $ctime1 ] ||\n\t\terror \"restore changed ctime from $ctime0 to $ctime1\"\n\n\tkill_copytools\n\twait_copytools || error \"Copytools failed to stop\"\n\n\t# Once more, after unmount and mount.\n\tumount_client $MOUNT || error \"cannot unmount '$MOUNT'\"\n\tmount_client $MOUNT || error \"cannot mount '$MOUNT'\"\n\n\tatime1=$(stat -c \"%X\" $file)\n\tmtime1=$(stat -c \"%Y\" $file)\n\tctime1=$(stat -c \"%Z\" $file)\n\n\t[ $atime0 -eq $atime1 ] ||\n\t\terror \"remount changed atime from $atime0 to $atime1\"\n\n\t[ $mtime0 -eq $mtime1 ] ||\n\t\terror \"remount changed mtime from $mtime0 to $mtime1\"\n\n\t[ $ctime0 -eq $ctime1 ] ||\n\t\terror \"remount changed ctime from $ctime0 to $ctime1\"\n}\nrun_test 24a \"Archive, release, and restore does not change a/mtime (i/o)\"\n\ntest_24b() {\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal fid\n\tlocal sum0\n\tlocal sum1\n\t# LU-3811\n\n\t# Test needs a running copytool.\n\tcopytool setup\n\n\t# Check that root can do HSM actions on a regular user's file.\n\tfid=$(create_small_file $file)\n\tsum0=$(md5sum $file)\n\n\tchown $RUNAS_ID:$RUNAS_GID $file ||\n\t\terror \"cannot chown '$file' to '$RUNAS_ID'\"\n\n\tchmod ugo-w $DIR/$tdir ||\n\t\terror \"cannot chmod '$DIR/$tdir'\"\n\n\t$LFS hsm_archive $file\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $file\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\t$LFS hsm_restore $file\n\twait_request_state $fid RESTORE SUCCEED\n\n\t# Check that ordinary user can get HSM state.\n\t$RUNAS $LFS hsm_state $file ||\n\t\terror \"user '$RUNAS_ID' cannot get HSM state of '$file'\"\n\n\t$LFS hsm_release $file\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\t# Check that ordinary user can accessed released file.\n\tsum1=$($RUNAS md5sum $file) ||\n\t\terror \"user '$RUNAS_ID' cannot read '$file'\"\n\n\t[ \"$sum0\" == \"$sum1\" ] ||\n\t\terror \"md5sum mismatch for '$file'\"\n}\nrun_test 24b \"root can archive, release, and restore user files\"\n\ntest_24c() {\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal action=archive\n\tlocal user_save\n\tlocal group_save\n\tlocal other_save\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\t# Save the default masks and check that cleanup_24c will\n\t# restore the request masks correctly.\n\tuser_save=$(get_hsm_param user_request_mask)\n\tstack_trap \"set_hsm_param user_request_mask $user_save\" EXIT\n\tgroup_save=$(get_hsm_param group_request_mask)\n\tstack_trap \"set_hsm_param user_request_mask $group_save\" EXIT\n\tother_save=$(get_hsm_param other_request_mask)\n\tstack_trap \"set_hsm_param user_request_mask $other_save\" EXIT\n\n\t[ \"$user_save\" == RESTORE ] ||\n\t\terror \"user_request_mask is '$user_save' expected 'RESTORE'\"\n\t[ \"$group_save\" == RESTORE ] ||\n\t\terror \"group_request_mask is '$group_save' expected 'RESTORE'\"\n\t[ \"$other_save\" == RESTORE ] ||\n\t\terror \"other_request_mask is '$other_save' expected 'RESTORE'\"\n\n\t# User.\n\tcreate_small_file $file\n\tchown $RUNAS_ID:$GROUP $file ||\n\t\terror \"cannot chown '$file' to '$RUNAS_ID:$GROUP'\"\n\n\t$RUNAS $LFS hsm_$action $file &&\n\t\terror \"$action by user should fail\"\n\n\tset_hsm_param user_request_mask $action\n\t$RUNAS $LFS hsm_$action $file ||\n\t\terror \"$action by user should succeed\"\n\n\t# Group.\n\tcreate_small_file $file\n\tchown nobody:$RUNAS_GID $file ||\n\t\terror \"cannot chown '$file' to 'nobody:$RUNAS_GID'\"\n\n\t$RUNAS $LFS hsm_$action $file &&\n\t\terror \"$action by group should fail\"\n\n\tset_hsm_param group_request_mask $action\n\t$RUNAS $LFS hsm_$action $file ||\n\t\terror \"$action by group should succeed\"\n\n\t# Other.\n\tcreate_small_file $file\n\tchown nobody:$GROUP $file ||\n\t\terror \"cannot chown '$file' to 'nobody:$GROUP'\"\n\n\t$RUNAS $LFS hsm_$action $file &&\n\t\terror \"$action by other should fail\"\n\n\tset_hsm_param other_request_mask $action\n\t$RUNAS $LFS hsm_$action $file ||\n\t\terror \"$action by other should succeed\"\n}\nrun_test 24c \"check that user,group,other request masks work\"\n\ntest_24d() {\n\tlocal file1=$DIR/$tdir/$tfile\n\tlocal file2=$DIR2/$tdir/$tfile\n\tlocal fid1\n\tlocal fid2\n\n\tfid1=$(create_small_file $file1)\n\n\techo $fid1\n\t$LFS getstripe $file1\n\n\tstack_trap \"zconf_umount \\\"$(facet_host $SINGLEAGT)\\\" \\\"$MOUNT3\\\"\" EXIT\n\tzconf_mount \"$(facet_host $SINGLEAGT)\" \"$MOUNT3\" ||\n\t\terror \"cannot mount '$MOUNT3' on '$SINGLEAGT'\"\n\n\tcopytool setup -m  \"$MOUNT3\"\n\n\tstack_trap \"mount -o remount,rw \\\"$MOUNT2\\\"\" EXIT\n\tmount -o remount,ro $MOUNT2\n\n\tdo_nodes $(comma_list $(nodes_list)) $LCTL clear\n\n\tfid2=$(path2fid $file2)\n\t[ \"$fid1\" == \"$fid2\" ] ||\n\t\terror \"FID mismatch '$fid1' != '$fid2'\"\n\n\t$LFS hsm_archive $file2 &&\n\t\terror \"archive should fail on read-only mount\"\n\tcheck_hsm_flags $file1 \"0x00000000\"\n\n\t$LFS hsm_archive $file1 || error \"Fail to archive $file1\"\n\twait_request_state $fid1 ARCHIVE SUCCEED\n\n\t$LFS hsm_release $file1\n\t$LFS hsm_restore $file2\n\twait_request_state $fid1 RESTORE SUCCEED\n\n\t$LFS hsm_release $file1 || error \"cannot release '$file1'\"\n\tdd if=$file2 of=/dev/null bs=1M || error \"cannot read '$file2'\"\n\n\t$LFS hsm_release $file2 &&\n\t\terror \"release should fail on read-only mount\"\n\n\treturn 0\n}\nrun_test 24d \"check that read-only mounts are respected\"\n\ntest_24e() {\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid\n\n\tfid=$(create_small_file $f) || error \"cannot create $f\"\n\t$LFS hsm_archive $f || error \"cannot archive $f\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"cannot release $f\"\n\twhile ! $LFS hsm_state $f | grep released; do\n\t\tsleep 1\n\tdone\n\n\ttar -cf $TMP/$tfile.tar $DIR/$tdir || error \"cannot tar $DIR/$tdir\"\n}\nrun_test 24e \"tar succeeds on HSM released files\" # LU-6213\n\ntest_24f() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir/d1\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/hosts $f)\n\tsum0=$(md5sum $f)\n\techo $sum0\n\t$LFS hsm_archive $f ||\n\t\terror \"hsm_archive failed\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"cannot release $f\"\n\ttar --xattrs -cvf $f.tar -C $DIR/$tdir $tfile\n\trm -f $f\n\tsync\n\ttar --xattrs -xvf $f.tar -C $DIR/$tdir ||\n\t\terror \"Can not recover the tar contents\"\n\tsum1=$(md5sum $f)\n\techo \"Sum0 = $sum0, sum1 = $sum1\"\n\t[ \"$sum0\" == \"$sum1\" ] || error \"md5sum mismatch for '$tfile'\"\n}\nrun_test 24f \"root can archive, release, and restore tar files\"\n\ntest_24g() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"need MDS version 2.11.56 or later\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal fid\n\n\techo \"RUNAS = '$RUNAS'\"\n\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tchmod ugo+rwx $DIR/$tdir\n\n\techo \"Please listen carefully as our options have changed.\" | tee $file\n\tfid=$(path2fid $file)\n\tchmod ugo+rw $file\n\n\t$LFS hsm_archive $file\n\twait_request_state $fid ARCHIVE SUCCEED\n\tcheck_hsm_flags $file 0x00000009 # exists archived\n\n\techo \"To be electrocuted by your telephone, press #.\" | $RUNAS tee $file\n\tcheck_hsm_flags $file 0x0000000b # exists dirty archived\n}\nrun_test 24g \"write by non-owner still sets dirty\" # LU-11369\n\ntest_25a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/hosts $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tcopytool import $tdir/$tfile $f\n\n\t$LFS hsm_set --lost $f\n\n\tmd5sum $f\n\tlocal st=$?\n\n\t[[ $st == 1 ]] || error \"lost file access should failed (returns $st)\"\n}\nrun_test 25a \"Restore lost file (HS_LOST flag) from import\"\\\n\t     \" (Operation not permitted)\"\n\ntest_25b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $f\n\t$LFS hsm_set --lost $f\n\tmd5sum $f\n\tst=$?\n\n\t[[ $st == 1 ]] || error \"lost file access should failed (returns $st)\"\n}\nrun_test 25b \"Restore lost file (HS_LOST flag) after release\"\\\n\t     \" (Operation not permitted)\"\n\ntest_26A() { # was test_26\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_remove $f\n\twait_request_state $fid REMOVE SUCCEED\n\n\tcheck_hsm_flags $f \"0x00000000\"\n}\nrun_test 26A \"Remove the archive of a valid file\"\n\ntest_26a() {\n\tlocal raolu=$(get_hsm_param remove_archive_on_last_unlink)\n\t[[ $raolu -eq 0 ]] || error \"RAoLU policy should be off\"\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal f2=$DIR/$tdir/${tfile}_2\n\tlocal fid2=$(copy_file /etc/passwd $f2)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f2\n\twait_request_state $fid2 ARCHIVE SUCCEED\n\n\tlocal f3=$DIR/$tdir/${tfile}_3\n\tlocal fid3=$(copy_file /etc/passwd $f3)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f3\n\twait_request_state $fid3 ARCHIVE SUCCEED\n\n\t# set a long grace_delay vs short loop_period\n\tlocal orig_loop_period=$(get_hsm_param loop_period)\n\tlocal orig_grace_delay=$(get_hsm_param grace_delay)\n\tstack_trap \"set_hsm_param loop_period $orig_loop_period\" EXIT\n\tset_hsm_param loop_period 10\n\tstack_trap \"set_hsm_param grace_delay $orig_grace_delay\" EXIT\n\tset_hsm_param grace_delay 100\n\n\trm -f $f\n\n\tstack_trap \"set_hsm_param remove_archive_on_last_unlink 0\" EXIT\n\tset_hsm_param remove_archive_on_last_unlink 1\n\n\tln \"$f3\" \"$f3\"_bis || error \"Unable to create hard-link\"\n\trm -f $f3\n\n\trm -f $f2\n\n\twait_request_state $fid2 REMOVE SUCCEED\n\n\tassert_request_count $fid REMOVE 0 \\\n\t\t\"Unexpected archived data remove request for $f\"\n\tassert_request_count $fid3 REMOVE 0 \\\n\t\t\"Unexpected archived data remove request for $f3\"\n}\nrun_test 26a \"Remove Archive On Last Unlink (RAoLU) policy\"\n\ntest_26b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tstack_trap \"set_hsm_param remove_archive_on_last_unlink 0\" EXIT\n\tset_hsm_param remove_archive_on_last_unlink 1\n\n\tcdt_shutdown\n\tcdt_check_state stopped\n\n\trm -f $f\n\n\twait_request_state $fid REMOVE WAITING\n\n\tcdt_enable\n\n\t# copytool must re-register\n\tkill_copytools\n\twait_copytools || error \"copytool failed to stop\"\n\tcopytool setup\n\n\twait_request_state $fid REMOVE SUCCEED\n}\nrun_test 26b \"RAoLU policy when CDT off\"\n\ntest_26c() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal f2=$DIR/$tdir/${tfile}_2\n\tlocal fid2=$(copy_file /etc/passwd $f2)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f2\n\twait_request_state $fid2 ARCHIVE SUCCEED\n\n\t# set a long grace_delay vs short loop_period\n\tlocal orig_loop_period=$(get_hsm_param loop_period)\n\tlocal orig_grace_delay=$(get_hsm_param grace_delay)\n\tstack_trap \"set_hsm_param loop_period $orig_loop_period\" EXIT\n\tset_hsm_param loop_period 10\n\tstack_trap \"set_hsm_param grace_delay $orig_grace_delay\" EXIT\n\tset_hsm_param grace_delay 100\n\n\tstack_trap \"set_hsm_param remove_archive_on_last_unlink 0\" EXIT\n\tset_hsm_param remove_archive_on_last_unlink 1\n\n\tmultiop_bg_pause $f O_c || error \"open $f failed\"\n\tlocal pid=$!\n\n\trm -f $f\n\trm -f $f2\n\n\twait_request_state $fid2 REMOVE SUCCEED\n\tassert_request_count $fid REMOVE 0 \\\n\t\t\"Unexpected archived data remove request for $f\"\n\n\tkill -USR1 $pid || error \"multiop early exit\"\n\t# should reach autotest timeout if multiop fails to trap\n\t# signal, close file, and exit ...\n\twait $pid || error \"wait PID $PID failed\"\n\n\twait_request_state $fid REMOVE SUCCEED\n}\nrun_test 26c \"RAoLU effective when file closed\"\n\ntest_26d() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# set a long grace_delay vs short loop_period\n\tlocal orig_loop_period=$(get_hsm_param loop_period)\n\tlocal orig_grace_delay=$(get_hsm_param grace_delay)\n\tstack_trap \"set_hsm_param loop_period $orig_loop_period\" EXIT\n\tset_hsm_param loop_period 10\n\tstack_trap \"set_hsm_param grace_delay $orig_grace_delay\" EXIT\n\tset_hsm_param grace_delay 100\n\n\tstack_trap \"set_hsm_param remove_archive_on_last_unlink 0\" EXIT\n\tset_hsm_param remove_archive_on_last_unlink 1\n\n\tmultiop_bg_pause $f O_c || error \"multiop failed\"\n\tlocal MULTIPID=$!\n\n\trm -f $f\n\n\tmds_evict_client\n\n\twait_request_state $fid REMOVE SUCCEED\n\n\tclient_up || client_up || true\n\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID || error \"multiop close failed\"\n}\nrun_test 26d \"RAoLU when Client eviction\"\n\ntest_27a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tcreate_archive_file $tdir/$tfile\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\t$LFS hsm_remove $f\n\n\t[[ $? != 0 ]] || error \"Remove of a released file should fail\"\n}\nrun_test 27a \"Remove the archive of an imported file (Operation not permitted)\"\n\ntest_27b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t$LFS hsm_remove $f\n\n\t[[ $? != 0 ]] || error \"Remove of a released file should fail\"\n}\nrun_test 27b \"Remove the archive of a relased file (Operation not permitted)\"\n\ntest_28() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcdt_disable\n\t$LFS hsm_remove $f\n\n\trm -f $f\n\n\tcdt_enable\n\n\twait_request_state $fid REMOVE SUCCEED\n}\nrun_test 28 \"Concurrent archive/file remove\"\n\ntest_29a() {\n\t# Tests --mntpath and --archive options\n\n\tlocal archive_id=7\n\tcopytool setup -m \"$MOUNT\" -a $archive_id\n\n\t# Bad archive number\n\t$LFS hsm_remove -m \"$MOUNT\" -a 33 0x857765760:0x8:0x2 2>&1 |\n\t\tgrep \"Invalid argument\" ||\n\t\terror \"unexpected hsm_remove failure (1)\"\n\n\t# mntpath is present but file is given\n\t$LFS hsm_remove --mntpath \"$MOUNT\" --archive 30 /qwerty/uyt 2>&1 |\n\t\tgrep \"hsm: '/qwerty/uyt' is not a valid FID\" ||\n\t\terror \"unexpected hsm_remove failure (2)\"\n}\nrun_test 29a \"Tests --mntpath and --archive options\"\n\ntest_29b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\trm -f $f\n\n\t$LFS hsm_remove -m $MOUNT -a $HSM_ARCHIVE_NUMBER $fid\n\twait_request_state $fid REMOVE SUCCEED\n}\nrun_test 29b \"Archive/delete/remove by FID from the archive.\"\n\ntest_29c() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal fid1=$(create_small_file $DIR/$tdir/$tfile-1)\n\tlocal fid2=$(create_small_file $DIR/$tdir/$tfile-2)\n\tlocal fid3=$(create_small_file $DIR/$tdir/$tfile-3)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $DIR/$tdir/$tfile-[1-3]\n\twait_request_state $fid1 ARCHIVE SUCCEED\n\twait_request_state $fid2 ARCHIVE SUCCEED\n\twait_request_state $fid3 ARCHIVE SUCCEED\n\n\trm -f $DIR/$tdir/$tfile-[1-3]\n\n\techo $fid1 > $DIR/$tdir/list\n\techo $fid2 >> $DIR/$tdir/list\n\techo $fid3 >> $DIR/$tdir/list\n\n\t$LFS hsm_remove -m $MOUNT -a $HSM_ARCHIVE_NUMBER \\\n\t\t--filelist $DIR/$tdir/list\n\twait_request_state $fid1 REMOVE SUCCEED\n\twait_request_state $fid2 REMOVE SUCCEED\n\twait_request_state $fid3 REMOVE SUCCEED\n}\nrun_test 29c \"Archive/delete/remove by FID, using a file list.\"\n\ntest_29d() {\n\t# test needs more than one CT\n\tneedclients 3 || return 0\n\n\tlocal n\n\tlocal file\n\tlocal fid\n\n\t# start all of the copytools\n\tfor n in $(seq $AGTCOUNT); do\n\t\tcopytool setup -f agt$n -a $n\n\tdone\n\n\t# archive files\n\tfile=$DIR/$tdir/$tfile\n\tfid=$(create_small_file $file)\n\n\t$LFS hsm_archive $file\n\twait_request_state $fid ARCHIVE SUCCEED\n\tcheck_hsm_flags $file \"0x00000009\"\n\n\trm -f $file\n\n\t$LFS hsm_remove --mntpath \"$MOUNT\" -a 0 $fid ||\n\t\terror \"cannot hsm_remove '$fid'\"\n\n\t# give time for CDT to handle remove request and create broadcasted\n\tsleep 2\n\n\t# remove request has been broadcasted ?\n\tlocal cnt=$(get_request_count $fid REMOVE)\n\t# broadcasted requests + original\n\t[[ $cnt -eq $((AGTCOUNT + 1)) ]] ||\n\t\terror \"remove not broadcasted to all CTs\"\n\n\t# give time for CDT and CTs to handle broadcasted\n\twait_for_loop_period\n\n\t# each agent serves one different archive_id, so broadcasted\n\t# hsm_remove request should only succeed once and fail at all others\n\tlocal res\n\tlocal scnt=0\n\tlocal fcnt=0\n\tfor n in $(seq $AGTCOUNT); do\n\t\tres=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\t       $HSM_PARAM.actions | awk \\\n\t\t\t       '/'$fid'.*action=REMOVE archive#='$n'/ \\\n\t\t\t       {print \\\\\\$13}' | cut -f2 -d=\")\n\t\tif [[ \"$res\" == \"SUCCEED\" ]]; then\n\t\t\tscnt=$((scnt + 1))\n\t\telif [[ \"$res\" == \"FAILED\" ]]; then\n\t\t\tfcnt=$((fcnt + 1))\n\t\tfi\n\tdone\n\n\t[[ $scnt -eq 1 ]] ||\n\t\terror \"one and only CT should have removed successfully\"\n\n\t[[ $AGTCOUNT -eq $((scnt + fcnt)) ]] ||\n\t\terror \"all but one CT should have failed to remove\"\n}\nrun_test 29d \"hsm_remove by FID with archive_id 0 for unlinked file cause \"\\\n\t     \"request to be sent once for each registered archive_id\"\n\ntest_30a() {\n\t# restore at exec cannot work on agent node (because of Linux kernel\n\t# protection of executables)\n\tneedclients 2 || return 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /bin/true $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/true\n\tcopytool import $tdir/$tfile $f\n\n\tlocal fid=$(path2fid $f)\n\n\tstack_trap \"cdt_clear_no_retry\" EXIT\n\t# set no retry action mode\n\tcdt_set_no_retry\n\tdo_node $CLIENT2 $f\n\tlocal st=$?\n\n\t$LFS hsm_state $f\n\n\t[[ $st == 0 ]] || error \"Failed to exec a released file\"\n}\nrun_test 30a \"Restore at exec (import case)\"\n\ntest_30b() {\n\t# restore at exec cannot work on agent node (because of Linux kernel\n\t# protection of executables)\n\tneedclients 2 || return 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/true\n\tlocal fid=$(copy_file /bin/true $f)\n\tchmod 755 $f\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\t$LFS hsm_state $f\n\n\tstack_trap cdt_clear_no_retry EXIT\n\t# set no retry action mode\n\tcdt_set_no_retry\n\n\tdo_node $CLIENT2 $f\n\tlocal st=$?\n\n\t$LFS hsm_state $f\n\n\t[[ $st == 0 ]] || error \"Failed to exec a released file\"\n}\nrun_test 30b \"Restore at exec (release case)\"\n\ntest_30c() {\n\tneedclients 2 || return 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/SLEEP\n\tlocal slp_sum1=$(md5sum /bin/sleep)\n\tlocal fid=$(copy_file /bin/sleep $f)\n\tchmod 755 $f\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tstack_trap cdt_clear_no_retry EXIT\n\t# set no retry action mode\n\tcdt_set_no_retry\n\n\tdo_node $CLIENT2 \"$f 10\" &\n\tlocal pid=$!\n\tsleep 3\n\techo 'Hi!' > $f\n\t[[ $? == 0 ]] && error \"Update during exec of released file must fail\"\n\twait $pid\n\t[[ $? == 0 ]] || error \"Execution failed during run\"\n\tcmp /bin/sleep $f\n\tif [[ $? != 0 ]]; then\n\t\tlocal slp_sum2=$(md5sum /bin/sleep)\n\t\t# in case sleep file is modified during the test\n\t\t[[ $slp_sum1 == $slp_sum2 ]] &&\n\t\t\terror \"Binary overwritten during exec\"\n\tfi\n\n\tcheck_hsm_flags $f \"0x00000009\"\n}\nrun_test 30c \"Update during exec of released file must fail\"\n\nrestore_and_check_size() {\n\tlocal f=$1\n\tlocal fid=$2\n\tlocal s=$(stat -c \"%s\" $f)\n\tlocal n=$s\n\tlocal st=$(get_hsm_flags $f)\n\tlocal err=0\n\tlocal cpt=0\n\t$LFS hsm_restore $f\n\twhile [[ \"$st\" != \"0x00000009\" && $cpt -le 10 ]]\n\tdo\n\t\tn=$(stat -c \"%s\" $f)\n\t\t# we echo in both cases to show stat is not hang\n\t\tif [[ $n != $s ]]; then\n\t\t\techo \"size seen is $n != $s\"\n\t\t\terr=1\n\t\telse\n\t\t\techo \"size seen is right: $n == $s\"\n\t\tfi\n\t\tsleep 10\n\t\tcpt=$((cpt + 1))\n\t\tst=$(get_hsm_flags $f)\n\tdone\n\tif [[ \"$st\" = \"0x00000009\" ]]; then\n\t\techo \" \"done\n\telse\n\t\techo \" restore is too long\"\n\t\twait_request_state $fid RESTORE SUCCEED\n\tfi\n\treturn $err\n}\n\ntest_31a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tcreate_archive_file $tdir/$tfile\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$($LFS path2fid $f)\n\tcopytool setup\n\n\trestore_and_check_size $f $fid\n\tlocal err=$?\n\n\t[[ $err -eq 0 ]] || error \"File size changed during restore\"\n}\nrun_test 31a \"Import a large file and check size during restore\"\n\n\ntest_31b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1MB 39)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\trestore_and_check_size $f $fid\n\tlocal err=$?\n\n\t[[ $err -eq 0 ]] || error \"File size changed during restore\"\n}\nrun_test 31b \"Restore a large unaligned file and check size during restore\"\n\ntest_31c() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1M 39)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\trestore_and_check_size $f $fid\n\tlocal err=$?\n\n\t[[ $err -eq 0 ]] || error \"File size changed during restore\"\n}\nrun_test 31c \"Restore a large aligned file and check size during restore\"\n\ntest_33() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcopytool setup\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\n\t# Implicit restore\n\tmd5sum $f >/dev/null &\n\tlocal pid=$!\n\n\twait_request_state $fid RESTORE STARTED\n\tkill -15 $pid\n\n\tcopytool_continue\n\n\t# Check restore trigger process was killed\n\twait $pid\n\t[ $? -eq 143 ] || error \"md5sum was not 'Terminated'\"\n}\nrun_test 33 \"Kill a restore waiting process\"\n\ntest_34() {\n\t# test needs a running copytool\n\tcopytool setup -b 1\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\n\tmd5sum $f >/dev/null &\n\tlocal pid=$!\n\n\twait_request_state $fid RESTORE STARTED\n\n\t# rm must not block during restore\n\ttimeout --signal=KILL 1 rm \"$f\" || error \"rm $f failed\"\n\n\tcopytool_continue\n\twait_request_state $fid RESTORE SUCCEED\n\n\t# Check md5sum pgm finished\n\tkill -0 $pid && error \"Restore initiatior still running\"\n\twait $pid || error \"Restore initiator failed with $?\"\n\n\t# Check the file was actually deleted\n\t[ ! -f \"$f\" ] || error \"$f was not deleted\"\n}\nrun_test 34 \"Remove file during restore\"\n\ntest_35() {\n\t# test needs a running copytool\n\tcopytool setup -b 1\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal f1=$DIR/$tdir/$tfile-1\n\tlocal fid=$(create_empty_file \"$f\")\n\tlocal fid1=$(copy_file /etc/passwd $f1)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\n\tmd5sum $f >/dev/null &\n\tlocal pid=$!\n\n\twait_request_state $fid RESTORE STARTED\n\n\t# mv must not block during restore\n\ttimeout --signal=KILL 1 mv \"$f1\" \"$f\" || error \"mv $f1 $f failed\"\n\n\tcopytool_continue\n\twait_request_state $fid RESTORE SUCCEED\n\n\t# Check md5sum pgm finished\n\tkill -0 $pid && error \"Restore initiatior still running\"\n\twait $pid || error \"Restore initiator failed with $?\"\n\n\tlocal fid2=$(path2fid $f)\n\t[[ $fid2 == $fid1 ]] || error \"Wrong fid after mv $fid2 != $fid1\"\n}\nrun_test 35 \"Overwrite file during restore\"\n\ntest_36() {\n\t# test needs a running copytool\n\tcopytool setup -b 1\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\n\tmd5sum $f >/dev/null &\n\tlocal pid=$!\n\n\twait_request_state $fid RESTORE STARTED\n\n\t# mv must not block during restore\n\ttimeout --signal=KILL 10 mv \"$f\" \"$f.new\" ||\n\t\terror \"mv '$f' '$f.new' failed with rc=$?\"\n\n\tcopytool_continue\n\twait_request_state $fid RESTORE SUCCEED\n\n\t# Check md5sum pgm finished\n\tkill -0 $pid && error \"Restore initiator is still running\"\n\twait $pid || error \"Restore initiator failed with $?\"\n}\nrun_test 36 \"Move file during restore\"\n\ntest_37() {\n\t# LU-5683: check that an archived dirty file can be rearchived.\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid\n\n\tfid=$(create_small_file $f) || error \"cannot create small file\"\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f || error \"cannot release $f\"\n\n\t# Allow previous archive request to expire from the actions log.\n\twait_for_grace_delay\n\n\t# Dirty file.\n\tdd if=/dev/urandom of=$f bs=1M count=1 || error \"cannot dirty file\"\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n}\nrun_test 37 \"re-archive a dirty file\"\n\nmulti_archive() {\n\tlocal prefix=$1\n\tlocal count=$2\n\tlocal n=\"\"\n\n\tfor n in $(seq 1 $count); do\n\t\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $prefix.$n\n\tdone\n\techo \"$count archive requests submitted\"\n}\n\ntest_40() {\n\tlocal stream_count=4\n\tlocal file_count=100\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal i=\"\"\n\tlocal p=\"\"\n\tlocal fid=\"\"\n\tlocal max_requests=$(get_hsm_param max_requests)\n\n\tstack_trap \"set_hsm_param max_requests $max_requests\" EXIT\n\t# Increase the number of HSM request that can be performed in\n\t# parallel. With the coordinator running once per second, this\n\t# also limits the number of requests per seconds that can be\n\t# performed, so we pick a decent number. But we also need to keep\n\t# that number low because the copytool has no rate limit and will\n\t# fail some requests if if gets too many at once.\n\tset_hsm_param max_requests 300\n\n\tfor i in $(seq 1 $file_count); do\n\t\tfor p in $(seq 1 $stream_count); do\n\t\t\tfid=$(copy_file /etc/hosts $f.$p.$i)\n\t\tdone\n\tdone\n\n\tcopytool setup\n\n\t# to be sure wait_all_done will not be mislead by previous tests\n\tcdt_purge\n\twait_for_grace_delay\n\ttypeset -a pids\n\t# start archive streams in background (archive files in parallel)\n\tfor p in $(seq 1 $stream_count); do\n\t\tmulti_archive $f.$p $file_count &\n\t\tpids[$p]=$!\n\tdone\n\techo -n  \"Wait for all requests being enqueued...\"\n\twait ${pids[*]}\n\techo OK\n\twait_all_done 100\n}\nrun_test 40 \"Parallel archive requests\"\n\ntest_52() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\tcheck_hsm_flags $f \"0x00000009\"\n\n\tmultiop_bg_pause $f O_c || error \"multiop failed\"\n\tlocal MULTIPID=$!\n\n\tmds_evict_client\n\tclient_up || client_up || true\n\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID || error \"multiop close failed\"\n\n\tcheck_hsm_flags $f \"0x0000000b\"\n}\nrun_test 52 \"Opened for write file on an evicted client should be set dirty\"\n\ntest_53() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file $f)\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\tcheck_hsm_flags $f \"0x00000009\"\n\n\tmultiop_bg_pause $f o_c || error \"multiop failed\"\n\tMULTIPID=$!\n\n\tmds_evict_client\n\tclient_up || client_up || true\n\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID || error \"multiop close failed\"\n\n\tcheck_hsm_flags $f \"0x00000009\"\n}\nrun_test 53 \"Opened for read file on an evicted client should not be set dirty\"\n\ntest_54() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1MB 39)\n\n\tcopytool setup -b 1\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE STARTED\n\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\tstack_trap \"cdt_clear_no_retry\" EXIT\n\t# Avoid coordinator resending this request as soon it has failed.\n\tcdt_set_no_retry\n\n\techo \"foo\" >> $f\n\tsync\n\twait_request_state $fid ARCHIVE FAILED\n\n\tcheck_hsm_flags $f \"0x00000003\"\n}\nrun_test 54 \"Write during an archive cancels it\"\n\ntest_55() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1MB 39)\n\n\tcopytool setup -b 1\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE STARTED\n\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\tstack_trap \"cdt_clear_no_retry\" EXIT\n\t# Avoid coordinator resending this request as soon it has failed.\n\tcdt_set_no_retry\n\n\t$TRUNCATE $f 1024 || error \"truncate failed\"\n\tsync\n\twait_request_state $fid ARCHIVE FAILED\n\n\tcheck_hsm_flags $f \"0x00000003\"\n}\nrun_test 55 \"Truncate during an archive cancels it\"\n\ntest_56() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1MB 39)\n\n\tcopytool setup -b 1\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE STARTED\n\n\tcheck_hsm_flags $f \"0x00000001\"\n\n\t# Change metadata and sync to be sure we are not changing only\n\t# in memory.\n\tchmod 644 $f\n\tchgrp sys $f\n\tsync\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcheck_hsm_flags $f \"0x00000009\"\n}\nrun_test 56 \"Setattr during an archive is ok\"\n\ntest_57() {\n\t# Need one client for I/O, one for request\n\tneedclients 2 || return 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/test_archive_remote\n\t# Create a file on a remote node\n\tdo_node $CLIENT2 \"dd if=/dev/urandom of=$f bs=1M \"\\\n\t\t\"count=2 conv=fsync\"\n\n\t# And archive it\n\tdo_node $CLIENT2 \"$LFS hsm_archive -a $HSM_ARCHIVE_NUMBER $f\" ||\n\t\terror \"hsm_archive failed\"\n\tlocal fid=$(path2fid $f)\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Release and implicit restore it\n\tdo_node $CLIENT2 \"$LFS hsm_release $f\" ||\n\t\terror \"hsm_release failed\"\n\tdo_node $CLIENT2 \"md5sum $f\" ||\n\t\terror \"hsm_restore failed\"\n\n\twait_request_state $fid RESTORE SUCCEED\n}\nrun_test 57 \"Archive a file with dirty cache on another node\"\n\ntruncate_released_file() {\n\tlocal src_file=$1\n\tlocal trunc_to=$2\n\n\tlocal sz=$(stat -c %s $src_file)\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file $1 $f)\n\tlocal ref=$f-ref\n\tcp $f $f-ref\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $f || error \"could not release file\"\n\n\t$TRUNCATE $f $trunc_to || error \"truncate failed\"\n\tsync\n\n\tlocal sz1=$(stat -c %s $f)\n\t[[ $sz1 == $trunc_to ]] ||\n\t\terror \"size after trunc: $sz1 expect $trunc_to, original $sz\"\n\n\t$LFS hsm_state $f\n\tcheck_hsm_flags $f \"0x0000000b\"\n\n\tlocal state=$(get_request_state $fid RESTORE)\n\t[[ \"$state\" == \"SUCCEED\" ]] ||\n\t\terror \"truncate $sz does not trig restore, state = $state\"\n\n\t$TRUNCATE $ref $trunc_to\n\tcmp $ref $f || error \"file data wrong after truncate\"\n\n\trm -f $f $f-ref\n}\n\ntest_58() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal sz=$(stat -c %s /etc/passwd)\n\n\techo \"truncate up from $sz to $((sz*2))\"\n\ttruncate_released_file /etc/passwd $((sz*2))\n\n\techo \"truncate down from $sz to $((sz/2))\"\n\ttruncate_released_file /etc/passwd $((sz/2))\n\n\techo \"truncate to 0\"\n\ttruncate_released_file /etc/passwd 0\n}\nrun_test 58 \"Truncate a released file will trigger restore\"\n\ntest_59() {\n\tlocal fid\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.63) ]] &&\n\t\tskip \"Need MDS version at least 2.7.63\"\n\n\tcopytool setup\n\t$MCREATE $DIR/$tfile || error \"mcreate failed\"\n\t$TRUNCATE $DIR/$tfile 42 || error \"truncate failed\"\n\t$LFS hsm_archive $DIR/$tfile || error \"archive request failed\"\n\tfid=$(path2fid $DIR/$tfile)\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $DIR/$tfile || error \"release failed\"\n}\nrun_test 59 \"Release stripeless file with non-zero size\"\n\ntest_60() {\n\t# This test validates the fix for LU-4512. Ensure that the -u\n\t# option changes the progress reporting interval from the\n\t# default (30 seconds) to the user-specified interval.\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_file \"$f\" 1M 10)\n\n\tlocal interval=5\n\tlocal progress_timeout=$((interval * 4))\n\tcopytool setup -b 1 --update-interval $interval\n\n\tlocal mdtidx=0\n\tlocal mdt=${MDT_PREFIX}${mdtidx}\n\tlocal mds=mds$((mdtidx + 1))\n\n\t# Wait for copytool to register\n\twait_update_facet $mds \\\n\t\t\"$LCTL get_param -n ${mdt}.hsm.agents | grep -o ^uuid\" \\\n\t\tuuid 100 || error \"coyptool failed to register with $mdt\"\n\n\tlocal start_at=$(date +%s)\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\n\tlocal agent=$(facet_active_host $SINGLEAGT)\n\tlocal logfile=$(copytool_logfile $SINGLEAGT)\n\n\twait_update $agent \\\n\t    \"grep -o start.copy \\\"$logfile\\\"\" \"start copy\" 100 ||\n\t\terror \"copytool failed to start\"\n\n\tlocal cmd=\"$LCTL get_param -n ${mdt}.hsm.active_requests\"\n\tcmd+=\" | awk '/'$fid'.*action=ARCHIVE/ {print \\\\\\$12}' | cut -f2 -d=\"\n\n\tlocal RESULT\n\tlocal WAIT=0\n\tlocal sleep=1\n\n\techo -n \"Expecting a progress update within $progress_timeout seconds... \"\n\twhile [ true ]; do\n\t\tRESULT=$(do_node $(facet_active_host $mds) \"$cmd\")\n\t\tif [ -n \"$RESULT\" ] && [ \"$RESULT\" -gt 0 ]; then\n\t\t\techo \"$RESULT bytes copied in $WAIT seconds.\"\n\t\t\tbreak\n\t\telif [ $WAIT -ge $progress_timeout ]; then\n\t\t\terror \"Timed out waiting for progress update!\"\n\t\t\tbreak\n\t\tfi\n\t\tWAIT=$((WAIT + sleep))\n\t\tsleep $sleep\n\tdone\n\n\tlocal finish_at=$(date +%s)\n\tlocal elapsed=$((finish_at - start_at))\n\n\t# Ensure that the progress update occurred within the expected window.\n\tif [ $elapsed -lt $((interval - 1)) ]; then\n\t\terror \"Expected progress update after at least $interval seconds\"\n\tfi\n\n\techo \"Wait for on going archive hsm action to complete\"\n\twait_update $agent \"grep -o copied \\\"$logfile\\\"\" \"copied\" 10 ||\n\t\techo \"File archiving not completed even after 10 secs\"\n}\nrun_test 60 \"Changing progress update interval from default\"\n\ntest_61() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\tcdt_disable\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\trm -f $f\n\tcdt_enable\n\twait_request_state $fid ARCHIVE FAILED\n}\nrun_test 61 \"Waiting archive of a removed file should fail\"\n\ntest_70() {\n\t# test needs a new running copytool\n\tstack_trap copytool_monitor_cleanup EXIT\n\tcopytool_monitor_setup\n\tcopytool setup --event-fifo \"$HSMTOOL_MONITOR_DIR/fifo\"\n\n\t# Wait for the copytool to register.\n\twait_update --verbose $(facet_active_host mds1) \\\n\t\t\"$LCTL get_param -n ${MDT_PREFIX}0.hsm.agents | grep -o ^uuid\" \\\n\t\tuuid 100 ||\n\t\terror \"copytool failed to register with MDT0000\"\n\n\tkill_copytools\n\twait_copytools || error \"Copytools failed to stop\"\n\n\tlocal REGISTER_EVENT\n\tlocal UNREGISTER_EVENT\n\twhile read event; do\n\t\tlocal parsed=$(parse_json_event \"$event\")\n\t\tif [ -z \"$parsed\" ]; then\n\t\t\terror \"Copytool sent malformed event: $event\"\n\t\tfi\n\t\teval $parsed\n\n\t\tif [ $event_type == \"REGISTER\" ]; then\n\t\t\tREGISTER_EVENT=$event\n\t\telif [ $event_type == \"UNREGISTER\" ]; then\n\t\t\tUNREGISTER_EVENT=$event\n\t\tfi\n\tdone < <(echo $\"$(get_copytool_event_log)\")\n\n\tif [ -z \"$REGISTER_EVENT\" ]; then\n\t\terror \"Copytool failed to send register event to FIFO\"\n\tfi\n\n\tif [ -z \"$UNREGISTER_EVENT\" ]; then\n\t\terror \"Copytool failed to send unregister event to FIFO\"\n\tfi\n\n\techo \"Register/Unregister events look OK.\"\n}\nrun_test 70 \"Copytool logs JSON register/unregister events to FIFO\"\n\ntest_71() {\n\t# Bump progress interval for livelier events.\n\tlocal interval=5\n\n\t# test needs a new running copytool\n\tstack_trap copytool_monitor_cleanup EXIT\n\tcopytool_monitor_setup\n\tcopytool setup --update-interval $interval --event-fifo \\\n\t\t\"$HSMTOOL_MONITOR_DIR/fifo\"\n\n\tstack_trap \"cdt_clear_no_retry\" EXIT\n\t# Just start and stop the copytool to generate events.\n\tcdt_clear_no_retry\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_small_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f ||\n\t\terror \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tlocal expected_fields=\"event_time data_fid source_fid\"\n\texpected_fields+=\" total_bytes current_bytes\"\n\n\tlocal -A events=(\n\t\t[ARCHIVE_START]=false\n\t\t[ARCHIVE_FINISH]=false\n\t\t[ARCHIVE_RUNNING]=false\n\t\t)\n\twhile read event; do\n\t\t# Make sure we're not getting anything from previous events.\n\t\tfor field in $expected_fields; do\n\t\t\tunset $field\n\t\tdone\n\n\t\tlocal parsed=$(parse_json_event \"$event\")\n\t\tif [ -z \"$parsed\" ]; then\n\t\t\terror \"Copytool sent malformed event: $event\"\n\t\tfi\n\t\teval $parsed\n\n\t\tevents[\"$event_type\"]=true\n\n\t\t[ \"$event_type\" != ARCHIVE_RUNNING ] && continue\n\n\t\t# Do some simple checking of the progress update events.\n\t\tfor expected_field in $expected_fields; do\n\t\t\tif [ -z ${!expected_field+x} ]; then\n\t\t\t\terror \"Missing $expected_field field in event\"\n\t\t\tfi\n\t\tdone\n\n\t\t[ $total_bytes -gt 0 ] || error \"Expected total_bytes to be > 0\"\n\n\t\t# These should be identical throughout an archive operation\n\t\t[ $source_fid == $data_fid ] ||\n\t\t\terror \"Expected source_fid to equal data_fid\"\n\tdone < <(echo $\"$(get_copytool_event_log)\")\n\n\t# Check we received every type of events we were expecting\n\tfor event in \"${!events[@]}\"; do\n\t\t${events[\"$event\"]} ||\n\t\t\terror \"Copytool failed to send '$event' event to FIFO\"\n\tdone\n\n\techo \"Archive events look OK.\"\n}\nrun_test 71 \"Copytool logs JSON archive events to FIFO\"\n\ntest_72() {\n\t# Bump progress interval for livelier events.\n\tlocal interval=5\n\n\t# test needs a new running copytool\n\tstack_trap copytool_monitor_cleanup EXIT\n\tcopytool_monitor_setup\n\tcopytool setup --update-interval $interval --event-fifo \\\n\t\t\"$HSMTOOL_MONITOR_DIR/fifo\"\n\tlocal test_file=$HSMTOOL_MONITOR_DIR/file\n\n\tlocal cmd=\"dd if=/dev/urandom of=$test_file count=16 bs=1000000 \"\n\tcmd+=\"conv=fsync\"\n\tdo_facet $SINGLEAGT \"$cmd\" ||\n\t\terror \"cannot create $test_file on $SINGLEAGT\"\n\tcopy2archive $test_file $tdir/$tfile\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tf=$DIR2/$tdir/$tfile\n\techo \"Verifying released state: \"\n\tcheck_hsm_flags $f \"0x0000000d\"\n\n\tlocal fid=$(path2fid $f)\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE SUCCEED\n\n\tlocal expected_fields=\"event_time data_fid source_fid\"\n\texpected_fields+=\" total_bytes current_bytes\"\n\n\tlocal START_EVENT\n\tlocal FINISH_EVENT\n\twhile read event; do\n\t\t# Make sure we're not getting anything from previous events.\n\t\tfor field in $expected_fields; do\n\t\t\tunset $field\n\t\tdone\n\n\t\tlocal parsed=$(parse_json_event \"$event\")\n\t\tif [ -z \"$parsed\" ]; then\n\t\t\terror \"Copytool sent malformed event: $event\"\n\t\tfi\n\t\teval $parsed\n\n\t\tif [ $event_type == \"RESTORE_START\" ]; then\n\t\t\tSTART_EVENT=$event\n\t\t\tif [ $source_fid != $data_fid ]; then\n\t\t\t\terror \"source_fid should == data_fid at start\"\n\t\t\tfi\n\t\t\tcontinue\n\t\telif [ $event_type == \"RESTORE_FINISH\" ]; then\n\t\t\tFINISH_EVENT=$event\n\t\t\tif [ $source_fid != $data_fid ]; then\n\t\t\t\terror \"source_fid should == data_fid at finish\"\n\t\t\tfi\n\t\t\tcontinue\n\t\telif [ $event_type != \"RESTORE_RUNNING\" ]; then\n\t\t\tcontinue\n\t\tfi\n\n\t\t# Do some simple checking of the progress update events.\n\t\tfor expected_field in $expected_fields; do\n\t\t\tif [ -z ${!expected_field+x} ]; then\n\t\t\t\terror \"Missing $expected_field field in event\"\n\t\t\tfi\n\t\tdone\n\n\t\tif [ $total_bytes -eq 0 ]; then\n\t\t\terror \"Expected total_bytes to be > 0\"\n\t\tfi\n\n\t\t# When a restore starts out, the data fid is the same as the\n\t\t# source fid. After the restore has gotten going, we learn\n\t\t# the new data fid. Once the restore has finished, the source\n\t\t# fid is set to the new data fid.\n\t\t#\n\t\t# We test this because some monitoring software may depend on\n\t\t# this behavior. If it changes, then the consumers of these\n\t\t# events may need to be modified.\n\t\tif [ $source_fid == $data_fid ]; then\n\t\t\terror \"source_fid should != data_fid during restore\"\n\t\tfi\n\tdone < <(echo $\"$(get_copytool_event_log)\")\n\n\tif [ -z \"$START_EVENT\" ]; then\n\t\terror \"Copytool failed to send restore start event to FIFO\"\n\tfi\n\n\tif [ -z \"$FINISH_EVENT\" ]; then\n\t\terror \"Copytool failed to send restore finish event to FIFO\"\n\tfi\n\n\techo \"Restore events look OK.\"\n}\nrun_test 72 \"Copytool logs JSON restore events to FIFO\"\n\ntest_90() {\n\tfile_count=51 # Max number of files constrained by LNET message size\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal FILELIST=/tmp/filelist.txt\n\tlocal i=\"\"\n\n\trm -f $FILELIST\n\tfor i in $(seq 1 $file_count); do\n\t\tfid=$(copy_file /etc/hosts $f.$i)\n\t\techo $f.$i >> $FILELIST\n\tdone\n\n\tcopytool setup\n\t# to be sure wait_all_done will not be mislead by previous tests\n\tcdt_purge\n\twait_for_grace_delay\n\t$LFS hsm_archive --filelist $FILELIST ||\n\t\terror \"cannot archive a file list\"\n\twait_all_done 100\n\t$LFS hsm_release --filelist $FILELIST ||\n\t\terror \"cannot release a file list\"\n\t$LFS hsm_restore --filelist $FILELIST ||\n\t\terror \"cannot restore a file list\"\n\twait_all_done 100\n}\nrun_test 90 \"Archive/restore a file list\"\n\ndouble_verify_reset_hsm_param() {\n\tlocal p=$1\n\techo \"Testing $HSM_PARAM.$p\"\n\tlocal val=$(get_hsm_param $p)\n\tlocal save=$val\n\tlocal val2=$(($val * 2))\n\tset_hsm_param $p $val2\n\tval=$(get_hsm_param $p)\n\t[[ $val == $val2 ]] ||\n\t\terror \"$HSM_PARAM.$p: $val != $val2 should be (2 * $save)\"\n\techo \"Set $p to 0 must failed\"\n\tset_hsm_param $p 0\n\tlocal rc=$?\n\t# restore value\n\tset_hsm_param $p $save\n\n\tif [[ $rc == 0 ]]; then\n\t\terror \"we must not be able to set $HSM_PARAM.$p to 0\"\n\tfi\n}\n\ntest_100() {\n\tdouble_verify_reset_hsm_param loop_period\n\tdouble_verify_reset_hsm_param grace_delay\n\tdouble_verify_reset_hsm_param active_request_timeout\n\tdouble_verify_reset_hsm_param max_requests\n\tdouble_verify_reset_hsm_param default_archive_id\n}\nrun_test 100 \"Set coordinator /proc tunables\"\n\ntest_102() {\n\tcdt_disable\n\tcdt_enable\n\tcdt_restart\n}\nrun_test 102 \"Verify coordinator control\"\n\ntest_103() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal i=\"\"\n\tlocal fid=\"\"\n\n\tmkdir -p $DIR/$tdir\n\tfor i in $(seq 1 20); do\n\t\tfid=$(copy_file /etc/passwd $DIR/$tdir/$i)\n\tdone\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $DIR/$tdir/*\n\n\tcdt_purge\n\n\techo \"Current requests\"\n\tlocal res=$(do_facet $SINGLEMDS \"$LCTL get_param -n\\\n\t\t\t$HSM_PARAM.actions |\\\n\t\t\tgrep -v CANCELED | grep -v SUCCEED | grep -v FAILED\")\n\n\t[[ -z \"$res\" ]] || error \"Some request have not been canceled\"\n}\nrun_test 103 \"Purge all requests\"\n\nDATA=CEA\nDATAHEX='[434541]'\ntest_104() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER --data $DATA $f\n\tlocal data1=$(do_facet $SINGLEMDS \"$LCTL get_param -n\\\n\t\t\t$HSM_PARAM.actions |\\\n\t\t\tgrep $fid | cut -f16 -d=\")\n\n\t[[ \"$data1\" == \"$DATAHEX\" ]] ||\n\t\terror \"Data field in records is ($data1) and not ($DATAHEX)\"\n\n\tcdt_purge\n}\nrun_test 104 \"Copy tool data field\"\n\ntest_105() {\n\tlocal max_requests=$(get_hsm_param max_requests)\n\tmkdir -p $DIR/$tdir\n\tlocal i=\"\"\n\n\tstack_trap \"set_hsm_param max_requests $max_requests\" EXIT\n\tset_hsm_param max_requests 300\n\n\tcdt_disable\n\tfor i in $(seq -w 1 10); do\n\t\tcp /etc/passwd $DIR/$tdir/$i\n\t\t$LFS hsm_archive $DIR/$tdir/$i\n\tdone\n\tlocal reqcnt1=$(do_facet $SINGLEMDS \"$LCTL get_param -n\\\n\t\t\t$HSM_PARAM.actions |\\\n\t\t\tgrep WAITING | wc -l\")\n\tcdt_restart\n\n\tcdt_disable\n\tlocal reqcnt2=$(do_facet $SINGLEMDS \"$LCTL get_param -n\\\n\t\t\t$HSM_PARAM.actions |\\\n\t\t\tgrep WAITING | wc -l\")\n\tcdt_enable\n\tcdt_purge\n\t[[ \"$reqcnt1\" == \"$reqcnt2\" ]] ||\n\t\terror \"Requests count after shutdown $reqcnt2 != \"\\\n\t\t      \"before shutdown $reqcnt1\"\n}\nrun_test 105 \"Restart of coordinator\"\n\ntest_106() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal uuid=$(get_agent_uuid $(facet_active_host $SINGLEAGT))\n\n\tcheck_agent_registered $uuid\n\n\tsearch_copytools || error \"No copytool found\"\n\n\tkill_copytools\n\twait_copytools || error \"Copytool failed to stop\"\n\n\tcheck_agent_unregistered $uuid\n\n\tcopytool setup\n\tuuid=$(get_agent_uuid $(facet_active_host $SINGLEAGT))\n\tcheck_agent_registered $uuid\n}\nrun_test 106 \"Copytool register/unregister\"\n\ntest_107() {\n\t[ \"$CLIENTONLY\" ] && skip \"CLIENTONLY mode\" && return\n\n\t# test needs a running copytool\n\tcopytool setup\n\t# create and archive file\n\tmkdir -p $DIR/$tdir\n\tlocal f1=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f1)\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f1\n\twait_request_state $fid ARCHIVE SUCCEED\n\t# shutdown and restart MDS\n\tfail $SINGLEMDS\n\t# check the copytool still gets messages from MDT\n\tlocal f2=$DIR/$tdir/2\n\tlocal fid=$(copy_file /etc/passwd $f2)\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f2\n\t# main check of this sanity: this request MUST succeed\n\twait_request_state $fid ARCHIVE SUCCEED\n}\nrun_test 107 \"Copytool re-register after MDS restart\"\n\npolicy_set_and_test()\n{\n\tlocal change=\"$1\"\n\tlocal target=\"$2\"\n\tdo_facet $SINGLEMDS $LCTL set_param \"$HSM_PARAM.policy=\\\\\\\"$change\\\\\\\"\"\n\tlocal policy=$(do_facet $SINGLEMDS $LCTL get_param -n $HSM_PARAM.policy)\n\t[[ \"$policy\" == \"$target\" ]] ||\n\t\terror \"Wrong policy after '$change': '$policy' != '$target'\"\n}\n\ntest_109() {\n\t# to force default policy setting if error\n\tCDT_POLICY_HAD_CHANGED=true\n\n\tlocal policy=$(do_facet $SINGLEMDS $LCTL get_param -n $HSM_PARAM.policy)\n\tlocal default=\"NonBlockingRestore [NoRetryAction]\"\n\t[[ \"$policy\" == \"$default\" ]] ||\n\t\terror \"default policy has changed,\"\\\n\t\t      \" '$policy' != '$default' update the test\"\n\tpolicy_set_and_test \"+NBR\" \"[NonBlockingRestore] [NoRetryAction]\"\n\tpolicy_set_and_test \"+NRA\" \"[NonBlockingRestore] [NoRetryAction]\"\n\tpolicy_set_and_test \"-NBR\" \"NonBlockingRestore [NoRetryAction]\"\n\tpolicy_set_and_test \"-NRA\" \"NonBlockingRestore NoRetryAction\"\n\tpolicy_set_and_test \"NRA NBR\" \"[NonBlockingRestore] [NoRetryAction]\"\n\t# useless bacause we know but safer for futur changes to use real value\n\tlocal policy=$(do_facet $SINGLEMDS $LCTL get_param -n $HSM_PARAM.policy)\n\techo \"Next set_param must failed\"\n\tpolicy_set_and_test \"wrong\" \"$policy\"\n\n\t# return to default\n\techo \"Back to default policy\"\n\tcdt_set_sanity_policy\n}\nrun_test 109 \"Policy display/change\"\n\ntest_110a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tcopy2archive /etc/passwd $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\tcdt_set_non_blocking_restore\n\tmd5sum $f\n\tlocal st=$?\n\n\t# cleanup\n\twait_request_state $fid RESTORE SUCCEED\n\tcdt_clear_non_blocking_restore\n\n\t# Test result\n\t[[ $st == 1 ]] ||\n\t\terror \"md5sum returns $st != 1, \"\\\n\t\t\t\"should also perror ENODATA (No data available)\"\n}\nrun_test 110a \"Non blocking restore policy (import case)\"\n\ntest_110b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\tcdt_set_non_blocking_restore\n\tmd5sum $f\n\tlocal st=$?\n\n\t# cleanup\n\twait_request_state $fid RESTORE SUCCEED\n\tcdt_clear_non_blocking_restore\n\n\t# Test result\n\t[[ $st == 1 ]] ||\n\t\terror \"md5sum returns $st != 1, \"\\\n\t\t\t\"should also perror ENODATA (No data available)\"\n}\nrun_test 110b \"Non blocking restore policy (release case)\"\n\ntest_111a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/passwd $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\tcdt_set_no_retry\n\n\tcopytool_remove_backend $fid\n\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE FAILED\n\tlocal st=$?\n\n\t# cleanup\n\tcdt_clear_no_retry\n\n\t# Test result\n\t[[ $st == 0 ]] || error \"Restore does not failed\"\n}\nrun_test 111a \"No retry policy (import case), restore will error\"\\\n\t      \" (No such file or directory)\"\n\ntest_111b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\tstack_trap cdt_clear_no_retry EXIT\n\tcdt_set_no_retry\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\tcopytool_remove_backend $fid\n\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE FAILED\n\tlocal st=$?\n\n\t# Test result\n\t[[ $st == 0 ]] || error \"Restore does not failed\"\n}\nrun_test 111b \"No retry policy (release case), restore will error\"\\\n\t      \" (No such file or directory)\"\n\ntest_112() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\tcdt_disable\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\tlocal l=$($LFS hsm_action $f)\n\techo $l\n\tlocal res=$(echo $l | cut -f 2- -d\" \" | grep ARCHIVE)\n\n\tcdt_enable\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Test result\n\t[[ ! -z \"$res\" ]] || error \"action is $l which is not an ARCHIVE\"\n}\nrun_test 112 \"State of recorded request\"\n\ntest_113() {\n\tlocal file1=$DIR/$tdir/$tfile\n\tlocal file2=$DIR2/$tdir/$tfile\n\n\tlocal fid=$(create_small_sync_file $file1)\n\n\tstack_trap \"zconf_umount \\\"$(facet_host $SINGLEAGT)\\\" \\\"$MOUNT3\\\"\" EXIT\n\tzconf_mount \"$(facet_host $SINGLEAGT)\" \"$MOUNT3\" ||\n\t\terror \"cannot mount '$MOUNT3' on '$SINGLEAGT'\"\n\n\tcopytool setup -m  \"$MOUNT3\"\n\n\tdo_nodes $(comma_list $(nodes_list)) $LCTL clear\n\n\t$LFS hsm_archive $file1 || error \"Fail to archive $file1\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $file1\n\techo \"Verifying released state: \"\n\tcheck_hsm_flags $file1 \"0x0000000d\"\n\n\tmultiop_bg_pause $file1 oO_WRONLY:O_APPEND:_w4c || error \"multiop failed\"\n\tMULTIPID=$!\n\tstat $file2 &\n\tkill -USR1 $MULTIPID\n\n\twait\n\tsync\n\n\tlocal size1=$(stat -c \"%s\" $file1)\n\tlocal size2=$(stat -c \"%s\" $file2)\n\n\t[ $size1 -eq $size2 ] || error \"sizes are different $size1 $size2\"\n}\nrun_test 113 \"wrong stat after restore\"\n\ntest_200() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcopytool setup\n\n\t# Prevent archive from completing\n\tcopytool_suspend\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\t# wait archive to register at CDT\n\twait_request_state $fid ARCHIVE STARTED\n\n\t# Cancel the archive\n\t$LFS hsm_cancel \"$f\"\n\n\twait_request_state $fid ARCHIVE CANCELED\n\n\tcopytool_continue\n\twait_request_state $fid CANCEL SUCCEED\n}\nrun_test 200 \"Register/Cancel archive\"\n\ntest_201() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcreate_archive_file $tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\t# test with cdt on is made in test_222\n\tcdt_disable\n\t$LFS hsm_restore $f\n\t# wait restore to register at CDT\n\twait_request_state $fid RESTORE WAITING\n\t$LFS hsm_cancel $f\n\tcdt_enable\n\twait_request_state $fid RESTORE CANCELED\n\twait_request_state $fid CANCEL SUCCEED\n}\nrun_test 201 \"Register/Cancel restore\"\n\ntest_202() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcopytool_suspend\n\t$LFS hsm_remove $f\n\t# wait remove to register at CDT\n\twait_request_state $fid REMOVE STARTED\n\t$LFS hsm_cancel $f\n\n\twait_request_state $fid REMOVE CANCELED\n}\nrun_test 202 \"Register/Cancel remove\"\n\ntest_220A() { # was test_220\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x0 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 220A \"Changelog for archive\"\n\ntest_220a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\n\t# block copytool operations to allow for HSM request to be\n\t# submitted and file be unlinked (CDT will find object removed)\n\tcopytool_suspend\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\n\t# wait request to reach CT\n\twait_request_state $fid ARCHIVE STARTED\n\n\trm -f $f\n\n\tcopytool_continue\n\n\twait_request_state $fid ARCHIVE FAILED\n\n\t# HE_ARCHIVE|ENOENT\n\tchangelog_find -type HSM -target-fid $fid -flags 0x2 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 220a \"Changelog for failed archive\"\n\ntest_221() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcopytool setup -b 1\n\tchangelog_register\n\n\t# Prevent archive from completing\n\tcopytool_suspend\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE STARTED\n\n\t$LFS hsm_cancel $f\n\twait_request_state $fid ARCHIVE CANCELED\n\n\tcopytool_continue\n\twait_request_state $fid CANCEL SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x7d ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 221 \"Changelog for archive canceled\"\n\ntest_222a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/passwd $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\tchangelog_register\n\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x80 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 222a \"Changelog for explicit restore\"\n\ntest_222b() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\tmd5sum $f\n\n\twait_request_state $fid RESTORE SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x80 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 222b \"Changelog for implicit restore\"\n\ntest_222c() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tcopy2archive /etc/passwd $tdir/$tfile\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\tchangelog_register\n\n\t# block copytool operations to allow for HSM request to be\n\t# submitted and file be unlinked (CDT will find object removed)\n\tcopytool_suspend\n\n\t$LFS hsm_restore $f\n\n\t# wait request to reach CT\n\twait_request_state $fid RESTORE STARTED\n\n\trm -f $f\n\n\tcopytool_continue\n\n\twait_request_state $fid RESTORE FAILED\n\n\t# HE_RESTORE|ENOENT\n\tchangelog_find -type HSM -target-fid $fid -flags 0x82 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 222c \"Changelog for failed explicit restore\"\n\ntest_222d() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\tcopytool_remove_backend $fid\n\tmd5sum $f\n\n\twait_request_state $fid RESTORE FAILED\n\n\t# HE_RESTORE|ENOENT\n\tchangelog_find -type HSM -target-fid $fid -flags 0x82 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 222d \"Changelog for failed implicit restore\"\n\ntest_223a() {\n\t# test needs a running copytool\n\tcopytool setup -b 1\n\n\tlocal f=$DIR/$tdir/$tfile\n\tcreate_archive_file $tdir/$tfile\n\n\tchangelog_register\n\n\tcopytool import $tdir/$tfile $f\n\tlocal fid=$(path2fid $f)\n\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE STARTED\n\t$LFS hsm_cancel $f\n\twait_request_state $fid RESTORE CANCELED\n\twait_request_state $fid CANCEL SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0xfd ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 223a \"Changelog for restore canceled (import case)\"\n\ntest_223b() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcopytool setup -b 1\n\tchangelog_register\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\t$LFS hsm_restore $f\n\twait_request_state $fid RESTORE STARTED\n\n\t$LFS hsm_cancel $f\n\twait_request_state $fid RESTORE CANCELED\n\n\tcopytool_continue\n\twait_request_state $fid CANCEL SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0xfd ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 223b \"Changelog for restore canceled (release case)\"\n\ntest_224A() { # was test_224\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_remove $f\n\twait_request_state $fid REMOVE SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x200 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 224A \"Changelog for remove\"\n\ntest_224a() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(copy_file /etc/passwd $f)\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tcopytool_remove_backend $fid\n\n\t# block copytool operations to allow for HSM request to be\n\t# submitted and file be unlinked (CDT will find object removed)\n\tcopytool_suspend\n\n\t$LFS hsm_remove $f\n\n\t# wait for request to reach CT\n\twait_request_state $fid REMOVE STARTED\n\n\trm -f $f\n\n\tcopytool_continue\n\n\twait_request_state $fid REMOVE FAILED\n\n\t# HE_REMOVE|ENOENT=0x202\n\tchangelog_find -type HSM -target-fid $fid -flags 0x202 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 224a \"Changelog for failed remove\"\n\ntest_225() {\n\t# test is not usable because remove request is too fast\n\t# so it is always finished before cancel can be done ...\n\techo \"Test disabled\"\n\treturn 0\n\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\t$LFS hsm_remove $f\n\n\t$LFS hsm_cancel $f\n\twait_request_state $fid REMOVE CANCELED\n\n\tcopytool_continue\n\twait_request_state $fid CANCEL SUCCEED\n\n\tchangelog_find -type HSM -target-fid $fid -flags 0x27d\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 225 \"Changelog for remove canceled\"\n\ntest_226() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f1=$DIR/$tdir/$tfile-1\n\tlocal f2=$DIR/$tdir/$tfile-2\n\tlocal f3=$DIR/$tdir/$tfile-3\n\tlocal fid1=$(copy_file /etc/passwd $f1)\n\tlocal fid2=$(copy_file /etc/passwd $f2)\n\tcopy_file /etc/passwd $f3\n\n\tchangelog_register\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f1\n\twait_request_state $fid1 ARCHIVE SUCCEED\n\n\t$LFS hsm_archive $f2\n\twait_request_state $fid2 ARCHIVE SUCCEED\n\n\trm $f1 || error \"rm $f1 failed\"\n\n\tchangelog_dump\n\tchangelog_find -type UNLNK -target-fid $fid1 -flags 0x3 ||\n\t\terror \"The expected changelog was not emitted\"\n\n\tmv $f3 $f2 || error \"mv $f3 $f2 failed\"\n\n\tchangelog_find -type RENME -target-fid $fid2 -flags 0x3 ||\n\t\terror \"The expected changelog was not emitted\"\n}\nrun_test 226 \"changelog for last rm/mv with exiting archive\"\n\n# This is just a utility function to clarify what test_227 does\n__test_227()\n{\n\tlocal target=0x280\n\n\t\"$LFS\" \"$action\" --$flag \"$file\" ||\n\t\terror \"Cannot ${action#hsm_} $flag on '$file'\"\n\n\t# Only one changelog should be produced\n\tlocal entries=\"$(changelog_find -type HSM -target-fid $fid)\"\n\t[ $(wc -l <<< \"$entries\") -eq $((++count)) ] ||\n\t\terror \"lfs $action --$flag '$file' produced more than one\" \\\n\t\t      \"changelog record\"\n\n\t# Parse the last changelog record\n\tlocal entry=\"$(tail -n 1 <<< \"$entries\")\"\n\teval local -A changelog=$(changelog2array $entry)\n\n\t# Also check the flags match what is expected\n\t[[ ${changelog[flags]} == $target ]] ||\n\t\terror \"Changelog flag is '${changelog[flags]}', not $target\"\n}\n\ntest_227() {\n\tlocal file=\"$DIR/$tdir/$tfile\"\n\tlocal fid=$(create_empty_file \"$file\")\n\tlocal count=0\n\n\tchangelog_register\n\n\tfor flag in norelease noarchive exists archived lost; do\n\t\tif [ \"$flag\" == lost ]; then\n\t\t\t# The flag \"lost\" only works on an archived file\n\t\t\t\"$LFS\" hsm_set --archived \"$file\"\n\t\t\t((count++))\n\t\tfi\n\n\t\taction=\"hsm_set\" __test_227\n\t\taction=\"hsm_clear\" __test_227\n\tdone\n}\nrun_test 227 \"changelog when explicit setting of HSM flags\"\n\ntest_228() {\n\t# test needs a running copytool\n\tcopytool setup\n\n\tlocal fid=$(create_small_sync_file $DIR/$tfile)\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $DIR/$tfile\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t$LFS hsm_release $DIR/$tfile\n\tcheck_hsm_flags $DIR/$tfile \"0x0000000d\"\n\n\tfilefrag $DIR/$tfile | grep \" 1 extent found\" ||\n\t\terror \"filefrag on released file must return only one extent\"\n\n\t# only newer versions of cp detect sparse files by stat/FIEMAP\n\t# (LU-2580)\n\tcp --sparse=auto $DIR/$tfile $DIR/$tfile.2 ||\n\t\terror \"copying $DIR/$tfile\"\n\tcmp $DIR/$tfile $DIR/$tfile.2 || error \"comparing copied $DIR/$tfile\"\n\n\t$LFS hsm_release $DIR/$tfile\n\tcheck_hsm_flags $DIR/$tfile \"0x0000000d\"\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $tdir failed\"\n\n\ttar cf - --sparse $DIR/$tfile | tar xvf - -C $DIR/$tdir ||\n\t\terror \"tar failed\"\n\tcmp $DIR/$tfile $DIR/$tdir/$DIR/$tfile ||\n\t\terror \"comparing untarred $DIR/$tfile\"\n\n\trm -f $DIR/$tfile $DIR/$tfile.2 ||\n\t\terror \"rm $DIR/$tfile or $DIR/$tfile.2 failed\"\n}\nrun_test 228 \"On released file, return extend to FIEMAP. For [cp,tar] --sparse\"\n\ntest_250() {\n\tlocal file=\"$DIR/$tdir/$tfile\"\n\n\t# set max_requests to allow one request of each type to be started (3)\n\tstack_trap \\\n\t\t\"set_hsm_param max_requests $(get_hsm_param max_requests)\" EXIT\n\tset_hsm_param max_requests 3\n\t# speed up test\n\tstack_trap \\\n\t\t\"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1\n\n\t# send 1 requests of each kind twice\n\tcopytool setup\n\t# setup the files\n\tfor action in archive restore remove; do\n\t\tlocal filepath=\"$file\"-to-$action\n\t\tlocal fid=$(create_empty_file \"$filepath\")\n\t\tlocal fid2=$(create_empty_file \"$filepath\".bis)\n\n\t\tif [ \"$action\" != archive ]; then\n\t\t\t\"$LFS\" hsm_archive \"$filepath\"\n\t\t\twait_request_state $fid ARCHIVE SUCCEED\n\t\t\t\"$LFS\" hsm_archive \"$filepath\".bis\n\t\t\twait_request_state $fid2 ARCHIVE SUCCEED\n\t\tfi\n\t\tif [ \"$action\" == restore ]; then\n\t\t\t\"$LFS\" hsm_release \"$filepath\"\n\t\t\t\"$LFS\" hsm_release \"$filepath\".bis\n\t\tfi\n\tdone\n\n\t# suspend the copytool to prevent requests from completing\n\tstack_trap \"copytool_continue\" EXIT\n\tcopytool_suspend\n\n\t# send `max_requests' requests (one of each kind)\n\tfor action in archive restore remove; do\n\t\tfilepath=\"$file\"-to-$action\n\t\t\"$LFS\" hsm_${action} \"$filepath\"\n\t\twait_request_state $(path2fid \"$filepath\") \"${action^^}\" STARTED\n\tdone\n\n\t# send another batch of requests\n\tfor action in archive restore remove; do\n\t\t\"$LFS\" hsm_${action} \"$file-to-$action\".bis\n\tdone\n\t# wait for `loop_period' seconds to make sure the coordinator has time\n\t# to register those, even though it should not\n\tsleep 1\n\n\t# only the first batch of request should be started\n\tlocal -i count\n\tcount=$(do_facet $SINGLEMDS \"$LCTL\" get_param -n $HSM_PARAM.actions |\n\t\tgrep -c STARTED)\n\n\t((count == 3)) ||\n\t\terror \"expected 3 STARTED requests, found $count\"\n}\nrun_test 250 \"Coordinator max request\"\n\ntest_251() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcdt_disable\n\t# to have a short test\n\tlocal old_to=$(get_hsm_param active_request_timeout)\n\tset_hsm_param active_request_timeout 1\n\t# to be sure the cdt will wake up frequently so\n\t# it will be able to cancel the \"old\" request\n\tlocal old_loop=$(get_hsm_param loop_period)\n\tset_hsm_param loop_period 1\n\tcdt_enable\n\n\tcopytool setup\n\n\t# Prevent archive from completing\n\tcopytool_suspend\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE STARTED\n\n\t# Let the request timeout\n\twait_request_state $fid ARCHIVE CANCELED\n\n\tset_hsm_param active_request_timeout $old_to\n\tset_hsm_param loop_period $old_loop\n}\nrun_test 251 \"Coordinator request timeout\"\n\ntest_252() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\t# to have a short test\n\tstack_trap \"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1\n\n\tcopytool setup\n\n\t# Prevent archive from completing\n\tcopytool_suspend\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE STARTED\n\trm -f \"$f\"\n\n\tstack_trap \"set_hsm_param active_request_timeout \\\n\t\t    $(get_hsm_param active_request_timeout)\" EXIT\n\tset_hsm_param active_request_timeout 1\n\n\twait_request_state $fid ARCHIVE CANCELED\n\tcopytool_continue\n}\nrun_test 252 \"Timeout'ed running archive of a removed file should be canceled\"\n\ntest_253() {\n\tlocal rc\n\t# test needs a running copytool\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\tlocal f=$DIR/$tdir/$tfile\n\n\tdd if=/dev/zero of=$f bs=1MB count=10\n\tlocal fid=$(path2fid $f)\n\n\t$LFS hsm_archive $f || error \"could not archive file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\t# clear locks to discard inode data\n\tcancel_lru_locks osc\n\n\t#define OBD_FAIL_MDC_MERGE              0x807\n\t$LCTL set_param fail_loc=0x807\n\n\t#expect error here, instead of release with wrong size\n\t$LFS hsm_release $f\n\trc=$?\n\tif ((rc == 0)); then\n\t\tfile_size=$(stat -c '%s' $f)\n\t\tif ((file_size != 10485760)); then\n\t\t\terror \"Wrong file size after hsm_release\"\n\t\tfi\n\telse\n\t\techo \"could not release file\"\n\tfi\n}\nrun_test 253 \"Check for wrong file size after release\"\n\ntest_254a()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.10.56) ] &&\n\t\tskip \"need MDS version at least 2.10.56\"\n\n\t# Check that the counters are initialized to 0\n\tlocal count\n\tfor request_type in archive restore remove; do\n\t\tcount=\"$(get_hsm_param ${request_type}_count)\" ||\n\t\t\terror \"Reading ${request_type}_count failed with $?\"\n\n\t\t[ \"$count\" -eq 0 ] ||\n\t\t\terror \"Expected ${request_type}_count to be \" \\\n\t\t\t      \"0 != '$count'\"\n\tdone\n}\nrun_test 254a \"Request counters are initialized to zero\"\n\ntest_254b()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.10.56) ] &&\n\t\tskip \"need MDS version at least 2.10.56\"\n\n\t# The number of request to launch (at least 32)\n\tlocal request_count=$((RANDOM % 32 + 32))\n\tprintf \"Will launch %i requests of each type\\n\" \"$request_count\"\n\n\t# Launch a copytool to process requests\n\tcopytool setup\n\n\t# Set hsm.max_requests to allow starting all requests at the same time\n\tstack_trap \\\n\t\t\"set_hsm_param max_requests $(get_hsm_param max_requests)\" EXIT\n\tset_hsm_param max_requests \"$request_count\"\n\n\tlocal timeout\n\tlocal count\n\tfor request_type in archive restore remove; do\n\t\tprintf \"Checking %s requests\\n\" \"${request_type}\"\n\t\t# Suspend the copytool to give us time to read the proc files\n\t\tcopytool_suspend\n\n\t\tfor ((i = 0; i < $request_count; i++)); do\n\t\t\tcase $request_type in\n\t\t\tarchive)\n\t\t\t\tcreate_empty_file \"$DIR/$tdir/$tfile-$i\" \\\n\t\t\t\t\t>/dev/null 2>&1\n\t\t\t\t;;\n\t\t\trestore)\n\t\t\t\tlfs hsm_release \"$DIR/$tdir/$tfile-$i\"\n\t\t\t\t;;\n\t\t\tesac\n\t\t\t$LFS hsm_${request_type} \"$DIR/$tdir/$tfile-$i\"\n\t\tdone\n\n\t\t# Give the coordinator 10 seconds to start every request\n\t\ttimeout=10\n\t\twhile get_hsm_param actions | grep -q WAITING; do\n\t\t\tsleep 1\n\t\t\tlet timeout-=1\n\t\t\t[ $timeout -gt 0 ] ||\n\t\t\t\terror \"${request_type^} requests took too \" \\\n\t\t\t\t      \"long to start\"\n\t\tdone\n\n\t\tcount=\"$(get_hsm_param ${request_type}_count)\"\n\t\t[ \"$count\" -eq \"$request_count\" ] ||\n\t\t\terror \"Expected '$request_count' (!= '$count') \" \\\n\t\t\t      \"active $request_type requests\"\n\n\t\t# Let the copytool process the requests\n\t\tcopytool_continue\n\t\t# Give it 10 seconds maximum\n\t\ttimeout=10\n\t\twhile get_hsm_param actions | grep -q STARTED; do\n\t\t\tsleep 1\n\t\t\tlet timeout-=1\n\t\t\t[ $timeout -gt 0 ] ||\n\t\t\t\terror \"${request_type^} requests took too \" \\\n\t\t\t\t      \"long to complete\"\n\t\tdone\n\n\t\tcount=\"$(get_hsm_param ${request_type}_count)\"\n\t\t[ \"$count\" -eq 0 ] ||\n\t\t\terror \"Expected 0 (!= '$count') \" \\\n\t\t\t      \"active $request_type requests\"\n\tdone\n}\nrun_test 254b \"Request counters are correctly incremented and decremented\"\n\ntest_255()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.12.0) ] &&\n\t\tskip \"Need MDS version at least 2.12.0\"\n\n\tlocal file=\"$DIR/$tdir/$tfile\"\n\tlocal fid=$(create_empty_file \"$file\")\n\n\t# How do you make sure the coordinator has consumed any outstanding\n\t# event, without triggering an event yourself?\n\t#\n\t# You wait for a request to disappear from the coordinator's llog.\n\n\t# Warning: the setup represents 90% of this test\n\n\t# Create and process an HSM request\n\tcopytool setup\n\t\"$LFS\" hsm_archive \"$file\"\n\twait_request_state $fid ARCHIVE SUCCEED\n\n\tkill_copytools\n\twait_copytools || error \"failed to stop copytools\"\n\n\t# Launch a new HSM request\n\trm \"$file\"\n\tcreate_empty_file \"$file\"\n\t\"$LFS\" hsm_archive \"$file\"\n\n\tcdt_shutdown\n\n\t# Have the completed request be removed as soon as the cdt wakes up\n\tstack_trap \"set_hsm_param grace_delay $(get_hsm_param grace_delay)\" EXIT\n\tset_hsm_param grace_delay 1\n\t# (Hopefully, time on the MDS will behave nicely)\n\tdo_facet $SINGLEMDS sleep 2 &\n\n\t# Increase `loop_period' as a mean to prevent the coordinator from\n\t# waking itself up to do some housekeeping.\n\tstack_trap \"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1000\n\n\twait $! || error \"waiting failed\"\n\tcdt_enable\n\twait_request_state $fid ARCHIVE \"\"\n\t# The coordinator will not wake up on its own for ~`loop_period' secs...\n\n\t# ... Unless a copytool registers. Now the real test begins\n\tcopytool setup\n\twait_request_state $(path2fid \"$file\") ARCHIVE SUCCEED\n}\nrun_test 255 \"Copytool registration wakes the coordinator up\"\n\n# tests 260[a-c] rely on the parsing of the copytool's log file, they might\n# break in the future because of that.\ntest_260a()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"need MDS version 2.11.56 or later\"\n\n\tlocal -a files=(\"$DIR/$tdir/$tfile\".{0..15})\n\tlocal file\n\n\tfor file in \"${files[@]}\"; do\n\t\tcreate_small_file \"$file\"\n\tdone\n\n\t# Set a few hsm parameters\n\tstack_trap \\\n\t\t\"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1\n\tstack_trap \\\n\t\t\"set_hsm_param max_requests $(get_hsm_param max_requests)\" EXIT\n\tset_hsm_param max_requests 3\n\n\t# Release one file\n\tcopytool setup\n\t\"$LFS\" hsm_archive \"${files[0]}\"\n\twait_request_state \"$(path2fid \"${files[0]}\")\" ARCHIVE SUCCEED\n\t\"$LFS\" hsm_release \"${files[0]}\"\n\n\t# Stop the copytool\n\tkill_copytools\n\twait_copytools || error \"copytools failed to stop\"\n\n\t# Send several archive requests\n\tfor file in \"${files[@]:1}\"; do\n\t\t\"$LFS\" hsm_archive \"$file\"\n\tdone\n\n\t# Send one restore request\n\t\"$LFS\" hsm_restore \"${files[0]}\"\n\n\t# Launch a copytool\n\tcopytool setup\n\n\t# Wait for all the requests to complete\n\twait_request_state \"$(path2fid \"${files[0]}\")\" RESTORE SUCCEED\n\tfor file in \"${files[@]:1}\"; do\n\t\twait_request_state \"$(path2fid \"$file\")\" ARCHIVE SUCCEED\n\tdone\n\n\t# Collect the actions in the order in which the copytool processed them\n\tlocal -a actions=(\n\t\t$(do_facet \"$SINGLEAGT\" grep -o '\\\"RESTORE\\\\|ARCHIVE\\\"' \\\n\t\t\t\"$(copytool_logfile \"$SINGLEAGT\")\")\n\t\t)\n\n\tprintf '%s\\n' \"${actions[@]}\"\n\n\tlocal action\n\tfor action in \"${actions[@]:0:3}\"; do\n\t\t[ \"$action\" == RESTORE ] && return\n\tdone\n\n\terror \"Too many ARCHIVE requests were run before the RESTORE request\"\n}\nrun_test 260a \"Restore request have priority over other requests\"\n\n# This test is very much tied to the implementation of the current priorisation\n# mechanism in the coordinator. It might not make sense to keep it in the future\ntest_260b()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"need MDS version 2.11.56 or later\"\n\n\tlocal -a files=(\"$DIR/$tdir/$tfile\".{0..15})\n\tlocal file\n\n\tfor file in \"${files[@]}\"; do\n\t\tcreate_small_file \"$file\"\n\tdone\n\n\t# Set a few hsm parameters\n\tstack_trap \\\n\t\t\"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1\n\tstack_trap \\\n\t\t\"set_hsm_param max_requests $(get_hsm_param max_requests)\" EXIT\n\tset_hsm_param max_requests 3\n\n\t# Release one file\n\tcopytool setup --archive-id 2\n\t\"$LFS\" hsm_archive --archive 2 \"${files[0]}\"\n\twait_request_state \"$(path2fid \"${files[0]}\")\" ARCHIVE SUCCEED\n\t\"$LFS\" hsm_release \"${files[0]}\"\n\n\t# Stop the copytool\n\tkill_copytools\n\twait_copytools || error \"copytools failed to stop\"\n\n\t# Send several archive requests\n\tfor file in \"${files[@]:1}\"; do\n\t\t\"$LFS\" hsm_archive \"$file\"\n\tdone\n\n\t# Send one restore request\n\t\"$LFS\" hsm_restore \"${files[0]}\"\n\n\t# Launch a copytool\n\tcopytool setup\n\tcopytool setup --archive-id 2\n\n\t# Wait for all the requests to complete\n\twait_request_state \"$(path2fid \"${files[0]}\")\" RESTORE SUCCEED\n\tfor file in \"${files[@]:1}\"; do\n\t\twait_request_state \"$(path2fid \"$file\")\" ARCHIVE SUCCEED\n\tdone\n\n\t# Collect the actions in the order in which the copytool processed them\n\tlocal -a actions=(\n\t\t$(do_facet \"$SINGLEAGT\" grep -o '\\\"RESTORE\\\\|ARCHIVE\\\"' \\\n\t\t\t\"$(copytool_logfile \"$SINGLEAGT\")\")\n\t\t)\n\n\tprintf '%s\\n' \"${actions[@]}\"\n\n\tlocal action\n\tfor action in \"${actions[@]:0:3}\"; do\n\t\t[ \"$action\" == RESTORE ] && return\n\tdone\n\n\terror \"Too many ARCHIVE requests were run before the RESTORE request\"\n}\nrun_test 260b \"Restore request have priority over other requests\"\n\n# This test is very much tied to the implementation of the current priorisation\n# mechanism in the coordinator. It might not make sense to keep it in the future\ntest_260c()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.12.0) ] &&\n\t\tskip \"Need MDS version at least 2.12.0\"\n\n\tlocal -a files=(\"$DIR/$tdir/$tfile\".{0..15})\n\tlocal file\n\n\tfor file in \"${files[@]}\"; do\n\t\tcreate_small_file \"$file\"\n\tdone\n\n\t# Set a few hsm parameters\n\tstack_trap \\\n\t\t\"set_hsm_param loop_period $(get_hsm_param loop_period)\" EXIT\n\tset_hsm_param loop_period 1000\n\tstack_trap \\\n\t\t\"set_hsm_param max_requests $(get_hsm_param max_requests)\" EXIT\n\tset_hsm_param max_requests 3\n\n\t# Release one file\n\tcopytool setup --archive-id 2\n\t\"$LFS\" hsm_archive --archive 2 \"${files[0]}\"\n\twait_request_state \"$(path2fid \"${files[0]}\")\" ARCHIVE SUCCEED\n\t\"$LFS\" hsm_release \"${files[0]}\"\n\n\t# Stop the copytool\n\tkill_copytools\n\twait_copytools || error \"copytools failed to stop\"\n\n\t# Force the next coordinator run to do housekeeping\n\tcdt_shutdown\n\tcdt_enable\n\n\t\"$LFS\" hsm_archive \"${files[1]}\"\n\n\t# Launch a copytool\n\tcopytool setup\n\tcopytool setup --archive-id 2\n\n\twait_request_state \"$(path2fid \"${files[1]}\")\" ARCHIVE SUCCEED\n\t# The coordinator just did a housekeeping run it won't do another one\n\t# for around `loop_period' seconds => requests will not be reordered\n\t# if it costs too much (ie. when the coordinator has to discard a whole\n\t# hal)\n\n\t# Send several archive requests\n\tfor file in \"${files[@]:2}\"; do\n\t\t\"$LFS\" hsm_archive \"$file\"\n\tdone\n\n\t# Send one restore request\n\t\"$LFS\" hsm_restore \"${files[0]}\"\n\n\t# Wait for all the requests to complete\n\twait_request_state \"$(path2fid \"${files[0]}\")\" RESTORE SUCCEED\n\tfor file in \"${files[@]:2}\"; do\n\t\twait_request_state \"$(path2fid \"$file\")\" ARCHIVE SUCCEED\n\tdone\n\n\t# Collect the actions in the order in which the copytool processed them\n\tlocal -a actions=(\n\t\t$(do_facet \"$SINGLEAGT\" grep -o '\\\"RESTORE\\\\|ARCHIVE\\\"' \\\n\t\t\t\"$(copytool_logfile \"$SINGLEAGT\")\")\n\t\t)\n\n\tprintf '%s\\n' \"${actions[@]}\"\n\n\tlocal action\n\tfor action in \"${actions[@]:0:3}\"; do\n\t\t[ \"$action\" == RESTORE ] &&\n\t\t\terror \"Restore requests should not be prioritised\" \\\n\t\t\t      \"unless the coordinator is doing housekeeping\"\n\tdone\n\treturn 0\n}\nrun_test 260c \"Requests are not reordered on the 'hot' path of the coordinator\"\n\ntest_300() {\n\t[ \"$CLIENTONLY\" ] && skip \"CLIENTONLY mode\" && return\n\n\t# the only way to test ondisk conf is to restart MDS ...\n\techo \"Stop coordinator and remove coordinator state at mount\"\n\t# stop coordinator\n\tcdt_shutdown\n\t# clean on disk conf set by default\n\tcdt_clear_mount_state\n\tcdt_check_state stopped\n\n\t# check cdt still off after umount/remount\n\tfail $SINGLEMDS\n\tcdt_check_state stopped\n\n\techo \"Set coordinator start at mount, and start coordinator\"\n\tcdt_set_mount_state enabled\n\n\t# check cdt is on\n\tcdt_check_state enabled\n\n\t# check cdt still on after umount/remount\n\tfail $SINGLEMDS\n\tcdt_check_state enabled\n\n\t# we are back to original state (cdt started at mount)\n}\nrun_test 300 \"On disk coordinator state kept between MDT umount/mount\"\n\ntest_301() {\n\t[ \"$CLIENTONLY\" ] && skip \"CLIENTONLY mode\" && return\n\n\tlocal ai=$(get_hsm_param default_archive_id)\n\tlocal new=$((ai + 1))\n\n\tset_hsm_param default_archive_id $new -P\n\tfail $SINGLEMDS\n\tlocal res=$(get_hsm_param default_archive_id)\n\n\t# clear value\n\tset_hsm_param default_archive_id \"\" \"-P -d\"\n\n\t[[ $new == $res ]] || error \"Value after MDS restart is $res != $new\"\n}\nrun_test 301 \"HSM tunnable are persistent\"\n\ntest_302() {\n\t[ \"$CLIENTONLY\" ] && skip \"CLIENTONLY mode\" && return\n\n\tlocal ai=$(get_hsm_param default_archive_id)\n\tlocal new=$((ai + 1))\n\n\t# stop coordinator\n\tcdt_shutdown\n\n\tset_hsm_param default_archive_id $new -P\n\n\tlocal mdtno\n\tfor mdtno in $(seq 1 $MDSCOUNT); do\n\t\tfail mds${mdtno}\n\tdone\n\n\t# check cdt is on\n\tcdt_check_state enabled\n\n\tlocal res=$(get_hsm_param default_archive_id)\n\n\t# clear value\n\tset_hsm_param default_archive_id \"\" \"-P -d\"\n\n\t[[ $new == $res ]] || error \"Value after MDS restart is $res != $new\"\n}\nrun_test 302 \"HSM tunnable are persistent when CDT is off\"\n\ntest_400() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal dir_mdt0=$DIR/$tdir/mdt0\n\tlocal dir_mdt1=$DIR/$tdir/mdt1\n\n\t# create 1 dir per MDT\n\tstack_trap \"rm -rf $dir_mdt0\" EXIT\n\t$LFS mkdir -i 0 $dir_mdt0 || error \"lfs mkdir\"\n\tstack_trap \"rm -rf $dir_mdt1\" EXIT\n\t$LFS mkdir -i 1 $dir_mdt1 || error \"lfs mkdir\"\n\n\t# create 1 file in each MDT\n\tlocal fid1=$(create_small_file $dir_mdt0/$tfile)\n\tlocal fid2=$(create_small_file $dir_mdt1/$tfile)\n\n\t# check that hsm request on mdt0 is sent to the right MDS\n\t$LFS hsm_archive $dir_mdt0/$tfile || error \"lfs hsm_archive\"\n\twait_request_state $fid1 ARCHIVE SUCCEED 0 &&\n\t\techo \"archive successful on mdt0\"\n\n\t# check that hsm request on mdt1 is sent to the right MDS\n\t$LFS hsm_archive $dir_mdt1/$tfile || error \"lfs hsm_archive\"\n\twait_request_state $fid2 ARCHIVE SUCCEED 1 &&\n\t\techo \"archive successful on mdt1\"\n}\nrun_test 400 \"Single request is sent to the right MDT\"\n\ntest_401() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal dir_mdt0=$DIR/$tdir/mdt0\n\tlocal dir_mdt1=$DIR/$tdir/mdt1\n\n\t# create 1 dir per MDT\n\tstack_trap \"rm -rf $dir_mdt0\" EXIT\n\t$LFS mkdir -i 0 $dir_mdt0 || error \"lfs mkdir\"\n\tstack_trap \"rm -rf $dir_mdt1\" EXIT\n\t$LFS mkdir -i 1 $dir_mdt1 || error \"lfs mkdir\"\n\n\t# create 1 file in each MDT\n\tlocal fid1=$(create_small_file $dir_mdt0/$tfile)\n\tlocal fid2=$(create_small_file $dir_mdt1/$tfile)\n\n\t# check that compound requests are shunt to the rights MDTs\n\t$LFS hsm_archive $dir_mdt0/$tfile $dir_mdt1/$tfile ||\n\t\terror \"lfs hsm_archive\"\n\twait_request_state $fid1 ARCHIVE SUCCEED 0 &&\n\t\techo \"archive successful on mdt0\"\n\twait_request_state $fid2 ARCHIVE SUCCEED 1 &&\n\t\techo \"archive successful on mdt1\"\n}\nrun_test 401 \"Compound requests split and sent to their respective MDTs\"\n\nmdc_change_state() # facet, MDT_pattern, activate|deactivate\n{\n\tlocal facet=$1\n\tlocal pattern=\"$2\"\n\tlocal state=$3\n\tlocal node=$(facet_active_host $facet)\n\tlocal mdc\n\tfor mdc in $(do_facet $facet \"$LCTL dl | grep -E ${pattern}-mdc\" |\n\t\t\tawk '{print $4}'); do\n\t\techo \"$3 $mdc on $node\"\n\t\tdo_facet $facet \"$LCTL --device $mdc $state\" || return 1\n\tdone\n}\n\ntest_402a() {\n\t# deactivate all mdc on agent1\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT000.\" \"deactivate\"\n\n\tcopytool setup --no-fail\n\n\tcheck_agent_unregistered \"uuid\" # match any agent\n\n\t# no expected running copytool\n\tsearch_copytools $agent && error \"Copytool start should have failed\"\n\n\t# reactivate MDCs\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT000.\" \"activate\"\n}\nrun_test 402a \"Copytool start fails if all MDTs are inactive\"\n\ntest_402b() {\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n#define OBD_FAIL_MDS_HSM_CT_REGISTER_NET\t0x14d\n\tdo_facet $SINGLEAGT lctl set_param fail_loc=0x14d\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\n\t# give time for CDT to send request and to keep it for retry\n\twait_for_loop_period\n\n\twait_request_state $fid ARCHIVE WAITING\n\n\tdo_facet $SINGLEAGT lctl set_param fail_loc=0\n\n\t# request should succeed now\n\twait_request_state $fid ARCHIVE SUCCEED\n}\nrun_test 402b \"CDT must retry request upon slow start of CT\"\n\ntest_403() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n        local agent=$(facet_active_host $SINGLEAGT)\n\n\t# deactivate all mdc for MDT0001\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT0001\" \"deactivate\"\n\n\tcopytool setup\n\tlocal uuid=$(get_agent_uuid $agent)\n\t# check the agent is registered on MDT0000, and not on MDT0001\n\tcheck_agent_registered_by_mdt $uuid 0\n\tcheck_agent_unregistered_by_mdt $uuid 1\n\n\t# check running copytool process\n\tsearch_copytools $agent || error \"No running copytools on $agent\"\n\n\t# reactivate all mdc for MDT0001\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT0001\" \"activate\"\n\n\t# make sure the copytool is now registered to all MDTs\n\tcheck_agent_registered $uuid\n}\nrun_test 403 \"Copytool starts with inactive MDT and register on reconnect\"\n\ntest_404() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcopytool setup\n\n\t# create files on both MDT0000 and MDT0001\n\tmkdir -p $DIR/$tdir\n\n\tlocal dir_mdt0=$DIR/$tdir/mdt0\n\tstack_trap \"rm -rf $dir_mdt0\" EXIT\n\t$LFS mkdir -i 0 $dir_mdt0 || error \"lfs mkdir\"\n\n\t# create 1 file on mdt0\n\tlocal fid1=$(create_small_file $dir_mdt0/$tfile)\n\n\t# deactivate all mdc for MDT0001\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT0001\" \"deactivate\"\n\n\t# send an HSM request for files in MDT0000\n\t$LFS hsm_archive $dir_mdt0/$tfile || error \"lfs hsm_archive\"\n\n\t# check for completion of files in MDT0000\n\twait_request_state $fid1 ARCHIVE SUCCEED 0 &&\n\t\techo \"archive successful on mdt0\"\n\n\t# reactivate all mdc for MDT0001\n\tmdc_change_state $SINGLEAGT \"$FSNAME-MDT0001\" \"activate\"\n}\nrun_test 404 \"Inactive MDT does not block requests for active MDTs\"\n\ntest_405() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcopytool setup\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal striped_dir=$DIR/$tdir/striped_dir\n\n\t# create striped dir on all of MDTs\n\t$LFS mkdir -i 0 -c $MDSCOUNT $striped_dir || error \"lfs mkdir\"\n\n\tlocal fid1=$(create_small_sync_file $striped_dir/${tfile}_0)\n\tlocal fid2=$(create_small_sync_file $striped_dir/${tfile}_1)\n\tlocal fid3=$(create_small_sync_file $striped_dir/${tfile}_2)\n\tlocal fid4=$(create_small_sync_file $striped_dir/${tfile}_3)\n\n\tlocal idx1=$($LFS getstripe -m $striped_dir/${tfile}_0)\n\tlocal idx2=$($LFS getstripe -m $striped_dir/${tfile}_1)\n\tlocal idx3=$($LFS getstripe -m $striped_dir/${tfile}_2)\n\tlocal idx4=$($LFS getstripe -m $striped_dir/${tfile}_3)\n\n\t# check that compound requests are shunt to the rights MDTs\n\t$LFS hsm_archive $striped_dir/${tfile}_0 $striped_dir/${tfile}_1  \\\n\t\t\t $striped_dir/${tfile}_2 $striped_dir/${tfile}_3 ||\n\t\terror \"lfs hsm_archive\"\n\n\twait_request_state $fid1 ARCHIVE SUCCEED $idx1 &&\n\t\techo \"archive successful on $fid1\"\n\twait_request_state $fid2 ARCHIVE SUCCEED $idx2 &&\n\t\techo \"archive successful on $fid2\"\n\twait_request_state $fid3 ARCHIVE SUCCEED $idx3 &&\n\t\techo \"archive successful on $fid3\"\n\twait_request_state $fid4 ARCHIVE SUCCEED $idx4 &&\n\t\techo \"archive successful on $fid4\"\n\n\t$LFS hsm_release $striped_dir/${tfile}_0 || error \"lfs hsm_release 1\"\n\t$LFS hsm_release $striped_dir/${tfile}_1 || error \"lfs hsm_release 2\"\n\t$LFS hsm_release $striped_dir/${tfile}_2 || error \"lfs hsm_release 3\"\n\t$LFS hsm_release $striped_dir/${tfile}_3 || error \"lfs hsm_release 4\"\n\n\tcat $striped_dir/${tfile}_0 > /dev/null || error \"cat ${tfile}_0 failed\"\n\tcat $striped_dir/${tfile}_1 > /dev/null || error \"cat ${tfile}_1 failed\"\n\tcat $striped_dir/${tfile}_2 > /dev/null || error \"cat ${tfile}_2 failed\"\n\tcat $striped_dir/${tfile}_3 > /dev/null || error \"cat ${tfile}_3 failed\"\n}\nrun_test 405 \"archive and release under striped directory\"\n\ntest_406() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\n\t[ $MDS1_VERSION -lt $(version_code 2.7.64) ] &&\n\t\tskip \"need MDS version at least 2.7.64\"\n\n\tlocal fid\n\tlocal mdt_index\n\n\tfid=$(create_small_file $DIR/$tdir/$tfile)\n\techo \"old fid $fid\"\n\n\tcopytool setup\n\n\t$LFS hsm_archive $DIR/$tdir/$tfile\n\twait_request_state \"$fid\" ARCHIVE SUCCEED\n\t$LFS hsm_release $DIR/$tdir/$tfile\n\n\t# Should migrate $tdir but not $tfile.\n\t$LFS migrate -m1 $DIR/$tdir &&\n\t\terror \"migrating HSM an archived file should fail\"\n\n\t$LFS hsm_restore $DIR/$tdir/$tfile\n\twait_request_state \"$fid\" RESTORE SUCCEED\n\n\t$LFS hsm_remove $DIR/$tdir/$tfile\n\twait_request_state \"$fid\" REMOVE SUCCEED\n\n\tcat $DIR/$tdir/$tfile > /dev/null ||\n\t\terror \"cannot read $DIR/$tdir/$tfile\"\n\n\t$LFS migrate -m1 $DIR/$tdir ||\n\t\terror \"cannot complete migration after HSM remove\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir)\n\tif ((mdt_index != 1)); then\n\t\terror \"expected MDT index 1, got $mdt_index\"\n\tfi\n\n\t# Refresh fid after migration.\n\tfid=$(path2fid $DIR/$tdir/$tfile)\n\techo \"new fid $fid\"\n\n\t$LFS hsm_archive $DIR/$tdir/$tfile\n\twait_request_state \"$fid\" ARCHIVE SUCCEED 1\n\n\tlctl set_param debug=+trace\n\t$LFS hsm_release $DIR/$tdir/$tfile ||\n\t\terror \"cannot release $DIR/$tdir/$tfile\"\n\n\t$LFS hsm_restore $DIR/$tdir/$tfile\n\twait_request_state \"$fid\" RESTORE SUCCEED 1\n\n\tcat $DIR/$tdir/$tfile > /dev/null ||\n\t\terror \"cannot read $DIR/$tdir/$tfile\"\n}\nrun_test 406 \"attempting to migrate HSM archived files is safe\"\n\ntest_407() {\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal f2=$DIR2/$tdir/$tfile\n\tlocal fid=$(create_empty_file \"$f\")\n\n\tcopytool setup\n\n\t$LFS hsm_archive --archive $HSM_ARCHIVE_NUMBER $f\n\twait_request_state $fid ARCHIVE SUCCEED\n\t$LFS hsm_release $f\n\n#define OBD_FAIL_MDS_HSM_CDT_DELAY      0x164\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=5 fail_loc=0x164\n\n\t# Prevent restore from completing\n\tcopytool_suspend\n\n\tmd5sum $f &\n\t# 1st request holds layout lock while appropriate\n\t# RESTORE record is still not added to llog\n\tmd5sum $f2 &\n\tsleep 2\n\n\t# after umount hsm_actions->O/x/x log shouldn't have\n\t# double RESTORE records like below\n\t#[0x200000401:0x1:0x0]...0x58d03a0d/0x58d03a0c action=RESTORE...WAITING\n\t#[0x200000401:0x1:0x0]...0x58d03a0c/0x58d03a0d action=RESTORE...WAITING\n\tsleep 30 &&\n\t\tdo_facet $SINGLEMDS \"$LCTL get_param $HSM_PARAM.actions\"&\n\tfail $SINGLEMDS\n\n\tcopytool_continue\n\twait_request_state $fid RESTORE SUCCEED\n}\nrun_test 407 \"Check for double RESTORE records in llog\"\n\ntest_500()\n{\n\t[ $MDS1_VERSION -lt $(version_code 2.6.92) ] &&\n\t\tskip \"HSM migrate is not supported\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\tif [ $(lustre_version_code client) -lt $(version_code 2.11.56) ] ||\n\t     [ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.11.56) ];\n\tthen\n\t\tllapi_hsm_test -d $DIR/$tdir -b ||\n\t\t\terror \"One llapi HSM test failed\"\n\telse\n\t\tllapi_hsm_test -d $DIR/$tdir ||\n\t\t\terror \"One llapi HSM test failed\"\n\tfi\n}\nrun_test 500 \"various LLAPI HSM tests\"\n\ntest_600() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\tchmod 777 $DIR/$tdir\n\t$RUNAS touch $f || error \"touch $f failed as $RUNAS_ID\"\n\tlocal fid=$(path2fid $f)\n\n\tlocal entry\n\tentry=$(changelog_find -type CREAT -target-fid $fid -uid \"$RUNAS_ID\" \\\n\t\t\t       -gid \"$RUNAS_GID\") ||\n\t\terror \"No matching CREAT entry\"\n\n\t# Parse the changelog\n\teval local -A changelog=$(changelog2array $entry)\n\tlocal nid=\"${changelog[nid]}\"\n\n\t# Check its NID\n\techo \"Got NID '$nid'\"\n\t[ -n \"$nid\" ] && [[ \"${CLIENT_NIDS[*]}\" =~ $nid ]] ||\n\t\terror \"nid '$nid' does not match any client NID:\" \\\n\t\t      \"${CLIENT_NIDS[@]}\"\n}\nrun_test 600 \"Changelog fields 'u=' and 'nid='\"\n\ntest_601() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n\tchangelog_clear\n\tcat $f || error \"cat $f failed\"\n\n\tchangelog_find -type OPEN -target-fid $fid -mode \"r--\" ||\n\t\terror \"No matching OPEN entry\"\n}\nrun_test 601 \"OPEN Changelog entry\"\n\ntest_602() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n\tchangelog_clear\n\tcat $f || error \"cat $f failed\"\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\techo f > $f || error \"write $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n\n\t# remove OPEN from changelog_mask\n\tchangelog_chmask \"-OPEN\"\n\n\tchangelog_clear\n\tchangelog_dump\n\tcat $f || error \"cat $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid &&\n\t\terror \"There should be no CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\techo f > $f || error \"write $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n}\nrun_test 602 \"Changelog record CLOSE only if open+write or OPEN recorded\"\n\ntest_603() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n\tsetfattr -n user.xattr1 -v \"value1\" $f || error \"setfattr $f failed\"\n\n\tchangelog_clear\n\tgetfattr -n user.xattr1 $f || error \"getfattr $f failed\"\n\n\tchangelog_find -type GXATR -target-fid $fid -xattr \"user.xattr1\" ||\n\t\terror \"No matching GXATR entry\"\n}\nrun_test 603 \"GETXATTR Changelog entry\"\n\ntest_604() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal f2=$DIR2/$tdir/$tfile\n\tlocal procname=\"mdd.$FSNAME-MDT0000.changelog_deniednext\"\n\tlocal timeout\n\ttimeout=\"$(do_facet mds1 \"$LCTL\" get_param -n \"$procname\")\"\n\tstack_trap \"do_facet mds1 '$LCTL' set_param '$procname=$timeout'\" EXIT\n\tdo_facet mds1 lctl set_param \"$procname=20\"\n\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n\tchmod 600 $f\n\n\tchangelog_clear\n\tchangelog_dump\n\t$RUNAS cat $f2 && error \"cat $f2 by user $RUNAS_ID should have failed\"\n\tchangelog_dump\n\n\tlocal entry\n\tentry=$(changelog_find -type NOPEN -target-fid $fid -uid \"$RUNAS_ID\" \\\n\t\t\t       -gid \"$RUNAS_GID\" -mode \"r--\") ||\n\t\terror \"No matching NOPEN entry\"\n\n\t# Parse the changelog\n\teval local -A changelog=$(changelog2array $entry)\n\tlocal nid=\"${changelog[nid]}\"\n\n\t# Check its NID\n\techo \"Got NID '$nid'\"\n\t[ -n \"$nid\" ] && [[ \"${CLIENT_NIDS[*]}\" =~ $nid ]] ||\n\t\terror \"nid '$nid' does not match any client NID:\" \\\n\t\t      \"${CLIENT_NIDS[@]}\"\n\n\tchangelog_clear\n\tchangelog_dump\n\t$RUNAS cat $f2 && error \"cat $f2 by user $RUNAS_ID should have failed\"\n\tchangelog_dump\n\n\tchangelog_find -type NOPEN -target-fid $fid &&\n\t\terror \"There should be no NOPEN entry\"\n\n\t# Sleep for `changelog_deniednext` seconds\n\tsleep 20\n\n\tchangelog_clear\n\tchangelog_dump\n\t$RUNAS cat $f2 && error \"cat $f by user $RUNAS_ID should have failed\"\n\tchangelog_dump\n\n\tentry=$(changelog_find -type NOPEN -target-fid $fid -uid \"$RUNAS_ID\" \\\n\t\t\t       -gid \"$RUNAS_GID\" -mode \"r--\") ||\n\t\terror \"No matching NOPEN entry\"\n\n\t# Parse the changelog\n\teval local -A changelog=$(changelog2array $entry)\n\tlocal nid=\"${changelog[nid]}\"\n\n\t# Check the NID\n\techo \"Got NID '$nid'\"\n\t[ -n \"$nid\" ] && [[ \"${CLIENT_NIDS[*]}\" =~ $nid ]] ||\n\t\terror \"nid '$nid' does not match any client NID:\" \\\n\t\t      \"${CLIENT_NIDS[@]}\"\n}\nrun_test 604 \"NOPEN Changelog entry\"\n\ntest_605() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\tlocal f2=$DIR2/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\ttouch $f || error \"touch $f failed\"\n\tlocal fid=$(path2fid $f)\n\n\tchangelog_clear\n\tchangelog_dump\n\texec 3<> $f || error \"open $f failed\"\n\tchangelog_dump\n\n\tlocal entry\n\tchangelog_find -type OPEN -target-fid $fid || error \"No OPEN entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\texec 4<> $f || error \"open $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type OPEN -target-fid $fid &&\n\t\terror \"There should be no OPEN entry\"\n\n\texec 4>&- || error \"close $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid &&\n\t\terror \"There should be no CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\t# access in rw, so different access mode should generate entries\n\tcat $f || error \"cat $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type OPEN -target-fid $fid || error \"No OPEN entry\"\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\t# same access as first one, should not generate new entries\n\texec 4<> $f || error \"open $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type OPEN -target-fid $fid &&\n\t\terror \"There should be no OPEN entry\"\n\n\texec 4>&- || error \"close $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid &&\n\t\terror \"There should be no CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\t# access by different user should generate new entries\n\t$RUNAS cat $f || error \"cat $f by user $RUNAS_ID failed\"\n\tchangelog_dump\n\n\tchangelog_find -type OPEN -target-fid $fid || error \"No OPEN entry\"\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n\n\tchangelog_clear\n\tchangelog_dump\n\texec 3>&- || error \"close $f failed\"\n\tchangelog_dump\n\n\tchangelog_find -type CLOSE -target-fid $fid || error \"No CLOSE entry\"\n}\nrun_test 605 \"Test OPEN and CLOSE rate limit in Changelogs\"\n\ntest_606() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.58) ] &&\n\t\tskip \"need MDS version at least 2.10.58\"\n\n\tlocal llog_reader=$(do_facet mgs \"which llog_reader 2> /dev/null\")\n\tllog_reader=${llog_reader:-$LUSTRE/utils/llog_reader}\n\t[ -z $(do_facet mgs ls -d $llog_reader 2> /dev/null) ] &&\n\t\t\tskip_env \"missing llog_reader\" && return\n\tlocal fstype=$(facet_fstype mds1)\n\n\tmkdir -p $DIR/$tdir\n\n\tlocal f=$DIR/$tdir/$tfile\n\n\tchangelog_register\n\t# set changelog_mask to ALL\n\tchangelog_chmask \"ALL\"\n\n\tchmod 777 $DIR/$tdir\n\t$RUNAS touch $f || error \"touch $f failed as $RUNAS_ID\"\n\tlocal fid=$(path2fid $f)\n\trm $f || error \"rm $f failed\"\n\n\tlocal mntpt=$(facet_mntpt mds1)\n\tlocal pass=true\n\tlocal entry\n\n\t#remount mds1 as ldiskfs or zfs type\n\tstack_trap \"stop mds1; start mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS\" EXIT\n\tstop mds1 || error \"stop mds1 failed\"\n\tmount_fstype mds1 || error \"remount mds1 failed\"\n\n\tfor ((i = 0; i < 1; i++)); do\n\t\tdo_facet mds1 $llog_reader $mntpt/changelog_catalog\n\t\tlocal cat_file=$(do_facet mds1 $llog_reader \\\n\t\t\t\t$mntpt/changelog_catalog | awk \\\n\t\t\t\t'{match($0,\"path=([^ ]+)\",a)}END{print a[1]}')\n\t\t[ -n \"$cat_file\" ] || error \"no catalog file\"\n\n\t\tentry=$(do_facet mds1 $llog_reader $mntpt/$cat_file |\n\t\t\tawk \"/CREAT/ && /target:\\[$fid\\]/ {print}\")\n\t\t[ -n \"$entry\" ] || error \"no CREAT entry\"\n\tdone\n\n\tlocal uidgid=$(echo $entry |\n\t\tsed 's+.*\\ user:\\([0-9][0-9]*:[0-9][0-9]*\\)\\ .*+\\1+')\n\t[ -n \"$uidgid\" ] || error \"uidgid is empty\"\n\techo \"Got UID/GID $uidgid\"\n\t[ \"$uidgid\" = \"$RUNAS_ID:$RUNAS_GID\" ] ||\n\t\terror \"uidgid '$uidgid' != '$RUNAS_ID:$RUNAS_GID'\"\n\tlocal nid=$(echo $entry |\n\t\tsed 's+.*\\ nid:\\(\\S\\S*@\\S\\S*\\)\\ .*+\\1+')\n\t[ -n \"$nid\" ] || error \"nid is empty\"\n\techo \"Got NID $nid\"\n\t[ -n \"$nid\" ] && [[ \"${CLIENT_NIDS[*]}\" =~ $nid ]] ||\n\t\terror \"nid '$nid' does not match any NID ${CLIENT_NIDS[@]}\"\n}\nrun_test 606 \"llog_reader groks changelog fields\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 5390}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# e.g. ONLY=\"22 23\" or ONLY=\"`seq 32 39`\" or EXCEPT=\"31\"\nset -e\n\nONLY=${ONLY:-\"$*\"}\n# bug number for skipped test:\nALWAYS_EXCEPT=${ALWAYS_EXCEPT:-\"$SANITY_GSS_EXCEPT\"}\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nSRCDIR=$(dirname $0)\nSAVE_PWD=$PWD\n\nexport MULTIOP=${MULTIOP:-multiop}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nrequire_dsh_mds || exit 0\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"100 101\"\n\n# $RUNAS_ID may get set incorrectly somewhere else\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&\n    error \"RUNAS_ID set to 0, but UID is also 0!\"\n\n# remove $SEC, we'd like to control everything by ourselves\nunset SEC\n\n#\n# global variables of this sanity\n#\nKRB5_CCACHE_DIR=/tmp\nKRB5_CRED=$KRB5_CCACHE_DIR/krb5cc_$RUNAS_ID\nKRB5_CRED_SAVE=$KRB5_CCACHE_DIR/krb5cc.sanity.save\nDBENCH_PID=0\n\n# set manually\nGSS=true\nGSS_KRB5=true\n\nprepare_krb5_creds() {\n\techo prepare krb5 cred\n\trm -f $KRB5_CRED_SAVE\n\techo RUNAS=$RUNAS\n\t$RUNAS krb5_login.sh || exit 1\n\t[ -f $KRB5_CRED ] || exit 2\n\techo CRED=$KRB5_CRED\n\tcp $KRB5_CRED $KRB5_CRED_SAVE\n}\n\nprepare_krb5_creds\n\n# we want double mount\nMOUNT_2=${MOUNT_2:-\"yes\"}\ncheck_and_setup_lustre\n\nrm -rf $DIR/[df][0-9]*\n\ncheck_runas_id $RUNAS_ID $RUNAS_ID $RUNAS\n\nbuild_test_filter\n\nstart_dbench()\n{\n\tlocal NPROC=$(grep -c ^processor /proc/cpuinfo)\n\t[ $NPROC -gt 2 ] && NPROC=2\n\tsh rundbench $NPROC 1>/dev/null &\n\tDBENCH_PID=$!\n\tsleep 2\n\n\tnum=$(ps --no-headers -p $DBENCH_PID 2>/dev/null | wc -l)\n\tif [ $num -ne 1 ]; then\n\t\terror \"failed to start dbench $NPROC\"\n\telse\n\t\techo \"started dbench with $NPROC processes at background\"\n\tfi\n\n\treturn 0\n}\n\ncheck_dbench()\n{\n\tnum=$(ps --no-headers -p $DBENCH_PID 2>/dev/null | wc -l)\n\tif [ $num -eq 0 ]; then\n\t\techo \"dbench $DBENCH_PID already finished\"\n\t\twait $DBENCH_PID || error \"dbench $PID exit with error\"\n\t\tstart_dbench\n\telif [ $num -ne 1 ]; then\n\t\tkillall -9 dbench\n\t\terror \"found $num instance of pid $DBENCH_PID ???\"\n\tfi\n\n\treturn 0\n}\n\nstop_dbench()\n{\n\tfor ((;;)); do\n\t\tkillall dbench 2>/dev/null\n\t\tlocal num=$(ps --no-headers -p $DBENCH_PID | wc -l)\n\t\tif [ $num -eq 0 ]; then\n\t\t\techo \"dbench finished\"\n\t\t\tbreak\n\t\tfi\n\t\techo \"dbench $DBENCH_PID is still running, waiting 2s...\"\n\t\tsleep 2\n\tdone\n\n\twait $DBENCH_PID || true\n\tsync || true\n}\n\nrestore_krb5_cred() {\n\tkeyctl reap\n\tcp $KRB5_CRED_SAVE $KRB5_CRED\n\tchown $RUNAS_ID:$RUNAS_ID $KRB5_CRED\n\tchmod 0600 $KRB5_CRED\n}\n\ncheck_multiple_gss_daemons() {\n\tlocal facet=$1\n\tlocal gssd=$2\n\tlocal gssd_name=$(basename $gssd)\n\n\tfor ((i = 0; i < 10; i++)); do\n\t\tdo_facet $facet \"$gssd -v\"\n\tdone\n\n\t# wait daemons entering \"stable\" status\n\tsleep 5\n\n\tlocal num=$(do_facet $facet ps -o cmd -C $gssd_name |\n\t\tgrep -c $gssd_name)\n\techo \"$num instance(s) of $gssd_name are running\"\n\n\tif [ $num -ne 1 ]; then\n\t\terror \"$gssd_name not unique\"\n\tfi\n}\n\ncalc_connection_cnt\numask 077\n\ntest_0() {\n\tlocal my_facet=mds\n\n\techo \"bring up gss daemons...\"\n\tstart_gss_daemons\n\n\techo \"check with someone already running...\"\n\tcheck_multiple_gss_daemons $my_facet $LSVCGSSD\n\tif $GSS_PIPEFS; then\n\t\tcheck_multiple_gss_daemons $my_facet $LGSSD\n\tfi\n\n\techo \"check with someone run & finished...\"\n\tdo_facet $my_facet killall -q -2 lgssd lsvcgssd || true\n\tsleep 5 # wait fully exit\n\tcheck_multiple_gss_daemons $my_facet $LSVCGSSD\n\tif $GSS_PIPEFS; then\n\t\tcheck_multiple_gss_daemons $my_facet $LGSSD\n\tfi\n\n\techo \"check refresh...\"\n\tdo_facet $my_facet killall -q -2 lgssd lsvcgssd || true\n\tsleep 5 # wait fully exit\n\tdo_facet $my_facet ipcrm -S 0x3b92d473\n\tcheck_multiple_gss_daemons $my_facet $LSVCGSSD\n\tif $GSS_PIPEFS; then\n\t\tdo_facet $my_facet ipcrm -S 0x3a92d473\n\t\tcheck_multiple_gss_daemons $my_facet $LGSSD\n\tfi\n}\nrun_test 0 \"start multiple gss daemons\"\n\nset_flavor_all krb5p\n\ntest_1() {\n\tlocal file=$DIR/$tfile\n\n\tchmod 0777 $DIR || error \"chmod $DIR failed\"\n\t$RUNAS touch $DIR\n\t# access w/o cred\n\t$RUNAS kdestroy\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $file && error \"unexpected success\"\n\n\t# access w/ cred\n\trestore_krb5_cred\n\t$RUNAS touch $file || error \"should not fail\"\n\t[ -f $file ] || error \"$file not found\"\n}\nrun_test 1 \"access with or without krb5 credential\"\n\ntest_2() {\n\tlocal file1=$DIR/$tfile-1\n\tlocal file2=$DIR/$tfile-2\n\n\tchmod 0777 $DIR || error \"chmod $DIR failed\"\n\t# current access should be ok\n\t$RUNAS touch $file1 || error \"can't touch $file1\"\n\t[ -f $file1 ] || error \"$file1 not found\"\n\n\t# cleanup all cred/ctx and touch\n\t$RUNAS kdestroy\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $file2 && error \"unexpected success\"\n\n\t# restore and touch\n\trestore_krb5_cred\n\t$RUNAS touch $file2 || error \"should not fail\"\n\t[ -f $file2 ] || error \"$file2 not found\"\n}\nrun_test 2 \"lfs flushctx\"\n\ntest_3() {\n\tlocal file=$DIR/$tfile\n\n\t# create file\n\techo \"aaaaaaaaaaaaaaaaa\" > $file\n\tchmod 0666 $file\n\t$CHECKSTAT -p 0666 $file || error \"$UID checkstat error\"\n\t$RUNAS $CHECKSTAT -p 0666 $file || error \"$RUNAS_ID checkstat error\"\n\t$RUNAS cat $file > /dev/null || error \"$RUNAS_ID cat error\"\n\n\t# start multiop\n\t$RUNAS $MULTIOP $file o_r &\n\tOPPID=$!\n\t# wait multiop finish its open()\n\tsleep 1\n\n\t# cleanup all cred/ctx and check\n\t# metadata check should fail, but file data check should success\n\t# because we always use root credential to OSTs\n\t$RUNAS kdestroy\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\techo \"destroyed credentials/contexs for $RUNAS_ID\"\n\t$RUNAS $CHECKSTAT -p 0666 $file && error \"checkstat succeed\"\n\tkill -s 10 $OPPID\n\twait $OPPID || error \"read file data failed\"\n\techo \"read file data OK\"\n\n\t# restore and check again\n\trestore_krb5_cred\n\techo \"restored credentials for $RUNAS_ID\"\n\t$RUNAS $CHECKSTAT -p 0666 $file || error \"$RUNAS_ID checkstat (2) error\"\n\techo \"$RUNAS_ID checkstat OK\"\n\t$CHECKSTAT -p 0666 $file || error \"$UID checkstat (2) error\"\n\techo \"$UID checkstat OK\"\n\t$RUNAS cat $file > /dev/null || error \"$RUNAS_ID cat (2) error\"\n\techo \"$RUNAS_ID read file data OK\"\n}\nrun_test 3 \"local cache under DLM lock\"\n\ntest_4() {\n\tlocal file1=$DIR/$tfile-1\n\tlocal file2=$DIR/$tfile-2\n\n\t! $GSS_PIPEFS && skip \"pipefs not used\" && return\n\n\tchmod 0777 $DIR || error \"chmod $DIR failed\"\n\t# current access should be ok\n\t$RUNAS touch $file1 || error \"can't touch $file1\"\n\t[ -f $file1 ] || error \"$file1 not found\"\n\n\t# stop lgssd\n\tsend_sigint client lgssd\n\tsleep 5\n\tcheck_gss_daemon_facet client lgssd && error \"lgssd still running\"\n\n\t# flush context, and touch\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $file2 &\n\tTOUCHPID=$!\n\techo \"waiting touch pid $TOUCHPID\"\n\twait $TOUCHPID && error \"touch should fail\"\n\n\t# restart lgssd\n\tdo_facet client \"$LGSSD -v\"\n\tsleep 5\n\tcheck_gss_daemon_facet client lgssd\n\n\t# touch new should succeed\n\t$RUNAS touch $file2 || error \"can't touch $file2\"\n\t[ -f $file2 ] || error \"$file2 not found\"\n}\nrun_test 4 \"lgssd dead, operations should wait timeout and fail\"\n\ntest_5() {\n\tlocal file1=$DIR/$tfile-1\n\tlocal file2=$DIR/$tfile-2\n\tlocal wait_time=$((TIMEOUT + TIMEOUT / 2))\n\n\tchmod 0777 $DIR || error \"chmod $DIR failed\"\n\t# current access should be ok\n\t$RUNAS touch $file1 || error \"can't touch $file1\"\n\t[ -f $file1 ] || error \"$file1 not found\"\n\n\t# stop lsvcgssd\n\tsend_sigint $(comma_list $(mdts_nodes)) lsvcgssd\n\tsleep 5\n\tcheck_gss_daemon_nodes $(comma_list $(mdts_nodes)) lsvcgssd &&\n\t\terror \"lsvcgssd still running\"\n\n\t# flush context, and touch\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\t$RUNAS touch $file2 && error 'should fail without lsvcgssd'\n\n\t# restart lsvcgssd, expect touch suceed\n\techo \"restart lsvcgssd and recovering\"\n\tstart_gss_daemons $(comma_list $(mdts_nodes)) \"$LSVCGSSD -v\"\n\tsleep 5\n\tcheck_gss_daemon_nodes $(comma_list $(mdts_nodes)) lsvcgssd\n\t$RUNAS keyctl reap\n\t$RUNAS touch $file2 || error 'should not fail now'\n\t[ -f $file2 ] || error \"$file2 not found\"\n}\nrun_test 5 \"lsvcgssd dead, operations fail\"\n\ntest_6() {\n\tlocal nfile=10\n\n\tmkdir $DIR/d6 || error \"mkdir $DIR/d6 failed\"\n\tfor ((i=0; i<$nfile; i++)); do\n\t\tdd if=/dev/zero of=$DIR/d6/file$i bs=8k count=1 ||\n\t\t    error \"dd file$i failed\"\n\tdone\n\tls -l $DIR/d6/* > /dev/null || error \"ls failed\"\n\trm -rf $DIR2/d6/* || error \"rm failed\"\n\trmdir $DIR2/d6/ || error \"rmdir failed\"\n}\nrun_test 6 \"test basic DLM callback works\"\n\ntest_7() {\n\tlocal tdir=$DIR/d7\n\tlocal num_osts\n\n\t# for open(), client only reserve space for default stripe count lovea,\n\t# and server may return larger lovea in reply (because of larger stripe\n\t# count), client need call enlarge_reqbuf() and save the replied lovea\n\t# in request for future possible replay.\n\t#\n\t# Note: current script does NOT guarantee enlarge_reqbuf() will be in\n\t# the path, however it does work in local test which has 2 OSTs and\n\t# default stripe count is 1.\n\tnum_osts=$($LFS getstripe $MOUNT | egrep -c \"^[0-9]*:.*ACTIVE\")\n\techo \"found $num_osts active OSTs\"\n\t[ $num_osts -lt 2 ] &&\n\t\techo \"skipping $TESTNAME (must have >= 2 OSTs)\" && return\n\n\tmkdir $tdir || error \"mkdir $tdir failed\"\n\t$LFS setstripe -c $num_osts $tdir || error \"setstripe -c $num_osts\"\n\n\techo \"creating...\"\n\tfor ((i = 0; i < 20; i++)); do\n\t\tdd if=/dev/zero of=$tdir/f$i bs=4k count=16 2>/dev/null\n\tdone\n\techo \"reading...\"\n\tfor ((i = 0; i < 20; i++)); do\n\t\tdd if=$tdir/f$i of=/dev/null bs=4k count=16 2>/dev/null\n\tdone\n\trm -rf $tdir\n}\nrun_test 7 \"exercise enlarge_reqbuf()\"\n\ntest_8()\n{\n\tlocal ATHISTORY=$(do_facet $SINGLEMDS \"find /sys/ -name at_history\")\n\tlocal ATOLDBASE=$(do_facet $SINGLEMDS \"cat $ATHISTORY\")\n\tlocal REQ_DELAY\n\tdo_facet $SINGLEMDS \"echo 8 >> $ATHISTORY\"\n\n\tmkdir -p $DIR/d8\n\tchmod a+w $DIR/d8\n\n\t$LCTL dk > /dev/null\n\tdebugsave\n\tsysctl -w lnet.debug=\"+other\"\n\n\t# wait for the at estimation come down, this is faster\n\twhile [ true ]; do\n\t\tREQ_DELAY=$(lctl get_param -n \\\n\t\t\tmdc.${FSNAME}-MDT0000-mdc-*.timeouts |\n\t\t\tawk '/portal 12/ {print $5}' | tail -1)\n\t\t[ $REQ_DELAY -le 5 ] && break\n\t\techo \"current AT estimation is $REQ_DELAY, wait a little bit\"\n\t\tsleep 8\n\tdone\n\tREQ_DELAY=$((${REQ_DELAY} + ${REQ_DELAY} / 4 + 5))\n\n\t# sleep sometime in ctx handle\n\tdo_facet $SINGLEMDS lctl set_param fail_val=$REQ_DELAY\n\t#define OBD_FAIL_SEC_CTX_HDL_PAUSE\t 0x1204\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x1204\n\n\t$RUNAS $LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\n\t$RUNAS touch $DIR/d8/f &\n\tTOUCHPID=$!\n\techo \"waiting for touch (pid $TOUCHPID) to finish...\"\n\tsleep 2 # give it a chance to really trigger context init rpc\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\twait $TOUCHPID || error \"touch should have succeeded\"\n\n\t$LCTL dk | grep -i \"Early reply #\" || error \"No early reply\"\n\n\tdebugrestore\n\tdo_facet $SINGLEMDS \"echo $ATOLDBASE >> $ATHISTORY\" || true\n}\nrun_test 8 \"Early reply sent for slow gss context negotiation\"\n\n#\n# following tests will manipulate flavors and may end with any flavor set,\n# so each test should not assume any start flavor.\n#\n\ntest_90() {\n\tif [ \"$SLOW\" = \"no\" ]; then\n\t\ttotal=10\n\telse\n\t\ttotal=60\n\tfi\n\n\trestore_to_default_flavor\n\tset_rule $FSNAME any any krb5p\n\twait_flavor all2all krb5p\n\n\tstart_dbench\n\n\tfor ((n=0;n<$total;n++)); do\n\t\tsleep 2\n\t\tcheck_dbench\n\t\techo \"flush ctx ($n/$total) ...\"\n\t\t$LFS flushctx $MOUNT || error \"can't flush context on $MOUNT\"\n\tdone\n\tcheck_dbench\n\t#sleep to let ctxs be re-established\n\tsleep 10\n\tstop_dbench\n}\nrun_test 90 \"recoverable from losing contexts under load\"\n\ntest_99() {\n\tlocal nrule_old\n\tlocal nrule_new=0\n\tlocal max=64\n\n\t#\n\t# general rules\n\t#\n\tnrule_old=$(do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME \\\n\t    2>/dev/null | grep -c \"$FSNAME.srpc.flavor.\")\n\techo \"original general rules: $nrule_old\"\n\n\tfor ((i = $nrule_old; i < $max; i++)); do\n\t\tset_rule $FSNAME ${NETTYPE}$i any krb5n || error \"set rule $i\"\n\tdone\n\tfor ((i = $nrule_old; i < $max; i++)); do\n\t\tset_rule $FSNAME ${NETTYPE}$i any || error \"remove rule $i\"\n\tdone\n\n\tnrule_new=$(do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME \\\n\t    2>/dev/null | grep -c \"$FSNAME.srpc.flavor.\")\n\tif [ $nrule_new != $nrule_old ]; then\n\t\terror \"general rule: $nrule_new != $nrule_old\"\n\tfi\n\n\t#\n\t# target-specific rules\n\t#\n\tnrule_old=$(do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME \\\n\t    2>/dev/null | grep -c \"$FSNAME-MDT0000.srpc.flavor.\")\n\techo \"original target rules: $nrule_old\"\n\n\tfor ((i = $nrule_old; i < $max; i++)); do\n\t\tset_rule $FSNAME-MDT0000 ${NETTYPE}$i any krb5i || error \"set rule $i\"\n\tdone\n\tfor ((i = $nrule_old; i < $max; i++)); do\n\t\tset_rule $FSNAME-MDT0000 ${NETTYPE}$i any || error \"remove rule $i\"\n\tdone\n\n\tnrule_new=$(do_facet mgs lctl get_param -n mgs.MGS.live.$FSNAME \\\n\t    2>/dev/null \\ | grep -c \"$FSNAME-MDT0000.srpc.flavor.\")\n\tif [ $nrule_new != $nrule_old ]; then\n\t\terror \"general rule: $nrule_new != $nrule_old\"\n\tfi\n}\nrun_test 99 \"set large number of sptlrpc rules\"\n\nerror_dbench()\n{\n\tlocal err_str=$1\n\n\tkillall -9 dbench\n\tsleep 1\n\n\terror $err_str\n}\n\ntest_100() {\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\t# running dbench background\n\tstart_dbench\n\n\t#\n\t# all: null -> krb5n -> krb5a -> krb5i -> krb5p -> plain\n\t#\n\tset_rule $FSNAME any any krb5n\n\twait_flavor all2all krb5n || error_dbench \"1\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any any krb5a\n\twait_flavor all2all krb5a || error_dbench \"2\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any any krb5i\n\twait_flavor all2all krb5i || error_dbench \"3\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any any krb5p\n\twait_flavor all2all krb5p || error_dbench \"4\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any any plain\n\twait_flavor all2all plain || error_dbench \"5\"\n\tcheck_dbench\n\n\t#\n\t# M - M: krb5a\n\t# C - M: krb5i\n\t# M - O: krb5p\n\t# C - O: krb5n\n\t#\n\tset_rule $FSNAME any mdt2mdt krb5a\n\twait_flavor mdt2mdt krb5a || error_dbench \"6\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any cli2mdt krb5i\n\twait_flavor cli2mdt krb5i || error_dbench \"7\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any mdt2ost krb5p\n\twait_flavor mdt2ost krb5p || error_dbench \"8\"\n\tcheck_dbench\n\n\tset_rule $FSNAME any cli2ost krb5n\n\twait_flavor cli2ost krb5n || error_dbench \"9\"\n\tcheck_dbench\n\n\t#\n\t# * - MDT0: krb5p\n\t# * - OST0: krb5i\n\t#\n\t# nothing should be changed because they are override by above dir rules\n\t#\n\tset_rule $FSNAME-MDT0000 any any krb5p\n\tset_rule $FSNAME-OST0000 any any krb5i\n\twait_flavor mdt2mdt krb5a || error_dbench \"10\"\n\twait_flavor cli2mdt krb5i || error_dbench \"11\"\n\tcheck_dbench\n\twait_flavor mdt2ost krb5p || error_dbench \"12\"\n\twait_flavor cli2ost krb5n || error_dbench \"13\"\n\n\t#\n\t# delete all dir-specific rules\n\t#\n\tset_rule $FSNAME any mdt2mdt\n\tset_rule $FSNAME any cli2mdt\n\tset_rule $FSNAME any mdt2ost\n\tset_rule $FSNAME any cli2ost\n\twait_flavor mdt2mdt krb5p $((MDSCOUNT - 1)) || error_dbench \"14\"\n\twait_flavor cli2mdt krb5p $(get_clients_mount_count) ||\n\t\terror_dbench \"15\"\n\tcheck_dbench\n\twait_flavor mdt2ost krb5i $MDSCOUNT || error_dbench \"16\"\n\twait_flavor cli2ost krb5i $(get_clients_mount_count) ||\n\t\terror_dbench \"17\"\n\tcheck_dbench\n\n\t#\n\t# remove:\n\t#  * - MDT0: krb5p\n\t#  * - OST0: krb5i\n\t#\n\tset_rule $FSNAME-MDT0000 any any\n\tset_rule $FSNAME-OST0000 any any || error_dbench \"18\"\n\twait_flavor all2all plain || error_dbench \"19\"\n\tcheck_dbench\n\n\tstop_dbench\n}\nrun_test 100 \"change security flavor on the fly under load\"\n\nswitch_sec_test()\n{\n\tlocal flavor0=$1\n\tlocal flavor1=$2\n\tlocal filename=$DIR/$tfile\n\tlocal multiop_pid\n\tlocal num\n\n\t#\n\t# after set to flavor0, start multop which use flavor0 rpc, and let\n\t# server drop the reply; then switch to flavor1, the resend should be\n\t# completed using flavor1. To exercise the code of switching ctx/sec\n\t# for a resend request.\n\t#\n\tlog \">>>>>>>>>>>>>>> Testing $flavor0 -> $flavor1 <<<<<<<<<<<<<<<<<<<\"\n\n\tset_rule $FSNAME any cli2mdt $flavor0\n\twait_flavor cli2mdt $flavor0\n\trm -f $filename || error \"remove old $filename failed\"\n\n\t#MDS_REINT = 36\n\t#define OBD_FAIL_PTLRPC_DROP_REQ_OPC\t 0x513\n\tdo_facet $SINGLEMDS lctl set_param fail_val=36\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x513\n\tlog \"starting multiop\"\n\t$MULTIOP $filename m &\n\tmultiop_pid=$!\n\techo \"multiop pid=$multiop_pid\"\n\tsleep 1\n\n\tset_rule $FSNAME any cli2mdt $flavor1\n\twait_flavor cli2mdt $flavor1\n\n\tnum=$(ps --no-headers -p $multiop_pid 2>/dev/null | wc -l)\n\t[ $num -eq 1 ] || error \"multiop($multiop_pid) already ended ($num)\"\n\techo \"process $multiop_pid is still hanging there... OK\"\n\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\tlog \"waiting for multiop ($multiop_pid) to finish\"\n\twait $multiop_pid || error \"multiop returned error\"\n}\n\ntest_101()\n{\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\tswitch_sec_test null  plain\n\tswitch_sec_test plain krb5n\n\tswitch_sec_test krb5n krb5a\n\tswitch_sec_test krb5a krb5i\n\tswitch_sec_test krb5i krb5p\n\tswitch_sec_test krb5p null\n\tswitch_sec_test null  krb5p\n\tswitch_sec_test krb5p krb5i\n\tswitch_sec_test krb5i plain\n\tswitch_sec_test plain krb5p\n}\nrun_test 101 \"switch ctx/sec for resending request\"\n\nerror_102()\n{\n\tlocal err_str=$1\n\n\tkillall -9 dbench\n\tsleep 1\n\n\terror $err_str\n}\n\ntest_102() {\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\t# run dbench background\n\tstart_dbench\n\n\techo \"Testing null->krb5n->krb5a->krb5i->krb5p->plain->null\"\n\tset_rule $FSNAME any any krb5n\n\tset_rule $FSNAME any any krb5a\n\tset_rule $FSNAME any any krb5i\n\tset_rule $FSNAME any any krb5p\n\tset_rule $FSNAME any any plain\n\tset_rule $FSNAME any any null\n\n\tcheck_dbench\n\twait_flavor all2all null || error_dbench \"1\"\n\tcheck_dbench\n\n\techo \"waiting for 15s and check again\"\n\tsleep 15\n\tcheck_dbench\n\n\techo \"Testing null->krb5i->null->krb5i->null...\"\n\tfor ((i=0; i<10; i++)); do\n\t\tset_rule $FSNAME any any krb5i\n\t\tset_rule $FSNAME any any null\n\tdone\n\tset_rule $FSNAME any any krb5i\n\n\tcheck_dbench\n\twait_flavor all2all krb5i || error_dbench \"2\"\n\tcheck_dbench\n\n\techo \"waiting for 15s and check again\"\n\tsleep 15\n\tcheck_dbench\n\n\tstop_dbench\n}\nrun_test 102 \"survive from insanely fast flavor switch\"\n\ntest_150() {\n\tlocal mount_opts\n\tlocal count\n\tlocal clients=$CLIENTS\n\n\t[ -z $clients ] && clients=$HOSTNAME\n\n\t# started from default flavors\n\trestore_to_default_flavor\n\n\t# at this time no rules has been set on mgs; mgc use null\n\t# flavor connect to mgs.\n\tcount=$(flvr_cnt_mgc2mgs null)\n\t[ $count -eq 1 ] || error \"$count mgc connection use null flavor\"\n\n\tzconf_umount_clients $clients $MOUNT || return 1\n\n\t# mount client with conflict flavor - should fail\n\tmount_opts=\"${MOUNT_OPTS:+$MOUNT_OPTS,}mgssec=krb5p\"\n\tzconf_mount_clients $clients $MOUNT $mount_opts &&\n\t    error \"mount with conflict flavor should have failed\"\n\n\t# mount client with same flavor - should succeed\n\tmount_opts=\"${MOUNT_OPTS:+$MOUNT_OPTS,}mgssec=null\"\n\tzconf_mount_clients $clients $MOUNT $mount_opts ||\n\t    error \"mount with same flavor should have succeeded\"\n\tzconf_umount_clients $clients $MOUNT || return 2\n\n\t# mount client with default flavor - should succeed\n\tzconf_mount_clients $clients $MOUNT ||\n\t    error \"mount with default flavor should have succeeded\"\n}\nrun_test 150 \"secure mgs connection: client flavor setting\"\n\ntest_151() {\n\tlocal save_opts\n\n\t# set mgs only accept krb5p\n\tset_rule _mgs any any krb5p\n\n\t# umount everything, modules still loaded\n\tstopall\n\n\t# start gss daemon on mgs node\n\tcombined_mgs_mds || start_gss_daemons $mgs_HOST \"$LSVCGSSD -v\"\n\n\t# start mgs\n\tstart mgs $(mgsdevname 1) $MDS_MOUNT_OPTS\n\n\t# mount mgs with default flavor, in current framework it means mgs+mdt1.\n\t# the connection of mgc of mdt1 to mgs is expected fail.\n\tDEVNAME=$(mdsdevname 1)\n\tstart mds1 $DEVNAME $MDS_MOUNT_OPTS\n\twait_mgc_import_state mds FULL 0 &&\n\t    error \"mount with default flavor should have failed\"\n\tstop mds1\n\n\t# mount with unauthorized flavor should fail\n\tsave_opts=$MDS_MOUNT_OPTS\n\tif [ -z \"$MDS_MOUNT_OPTS\" ]; then\n\t    MDS_MOUNT_OPTS=\"-o mgssec=null\"\n\telse\n\tMDS_MOUNT_OPTS=\"$MDS_MOUNT_OPTS,mgssec=null\"\n\tfi\n\tstart mds1 $DEVNAME $MDS_MOUNT_OPTS\n\twait_mgc_import_state mds FULL 0 &&\n\t    error \"mount with unauthorized flavor should have failed\"\n\tMDS_MOUNT_OPTS=$save_opts\n\tstop mds1\n\n\t# mount with designated flavor should succeed\n\tsave_opts=$MDS_MOUNT_OPTS\n\tif [ -z \"$MDS_MOUNT_OPTS\" ]; then\n\t    MDS_MOUNT_OPTS=\"-o mgssec=krb5p\"\n\telse\n\tMDS_MOUNT_OPTS=\"$MDS_MOUNT_OPTS,mgssec=krb5p\"\n\tfi\n\tstart mds1 $DEVNAME $MDS_MOUNT_OPTS\n\twait_mgc_import_state mds FULL 0 ||\n\t    error \"mount with designated flavor should have succeeded\"\n\tMDS_MOUNT_OPTS=$save_opts\n\n\tstop mds1 -f\n}\nrun_test 151 \"secure mgs connection: server flavor control\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 804}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_LFSCK_EXCEPT \"\n\n# DNE does not support striped directory on zfs-based backend yet.\n[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\n# bug number for skipped test:\tLU-5855\tLU-5855\tLU-5855\tLU-5855\n\tALWAYS_EXCEPT+=\"\t31a\t31b\t31c\t31d\"\n# bug number for skipped test:\tLU-5855\tLU-5855\tLU-5855\tLU-5855\n\tALWAYS_EXCEPT+=\"\t31e\t31f\t31g\t31h\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n[[ $(lustre_version_code $SINGLEMDS) -le $(version_code 2.4.90) ]] &&\n# bug number for skipped test:\tLU-4165\n\tALWAYS_EXCEPT+=\"\t2c\"\n\n[[ $(lustre_version_code ost1) -lt $(version_code 2.5.55) ]] &&\n# bug number for skipped test:\tLU-1267\n\tALWAYS_EXCEPT+=\"\t11\"\n# bug number for skipped test:\tLU-3950\n\tALWAYS_EXCEPT+=\"\t12\"\n# bug number for skipped test:\tLU-3593\n\tALWAYS_EXCEPT+=\"\t13\"\n# bug number for skipped test:\tLU-3590\n\tALWAYS_EXCEPT+=\"\t14\"\n# bug number for skipped test:\tLU-3591\n\tALWAYS_EXCEPT+=\"\t15\"\n# bug number for skipped test:\tLU-3594\tLU-3594\n\tALWAYS_EXCEPT+=\"\t16\t17\"\n# bug number for skipped test:\tLU-3336\tLU-3336\tLU-3336\tLU-3336\tLU-3336\n\tALWAYS_EXCEPT+=\"\t18a\t18b\t18c\t18d\t18e\"\n# bug number for skipped test:\tLU-3951\tLU-3951\n\tALWAYS_EXCEPT+=\"\t19a\t19b\"\n# bug number for skipped test:\tLU-4887\tLU-4887\n\tALWAYS_EXCEPT+=\"\t20\t21\"\n\n[[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.6.50) ]] &&\n# bug number for skipped test:\tLU-4788\n\tALWAYS_EXCEPT+=\"\t2d\"\n# bug number for skipped test:\tLU-5511\tLU-5511\tLU-5511\n\tALWAYS_EXCEPT+=\"\t2e\t22a\t22b\"\n# bug number for skipped test:\tLU-4788\n\tALWAYS_EXCEPT+=\"\t3\"\n# bug number for skipped test:\tLU-5512\tLU-5512\tLU-5512\n\tALWAYS_EXCEPT+=\"\t23a\t23b\t23c\"\n# bug number for skipped test:\tLU-5513\n\tALWAYS_EXCEPT+=\"\t24\"\n# bug number for skipped test:\tLU-5515\n\tALWAYS_EXCEPT+=\"\t25\"\n# bug number for skipped test:\tLU-5516\tLU-5516\n\tALWAYS_EXCEPT+=\"\t26a\t26b\"\n# bug number for skipped test:\tLU-5516\tLU-5516\n\tALWAYS_EXCEPT+=\"\t27a\t27b\"\n# bug number for skipped test:\tLU-5506\n\tALWAYS_EXCEPT+=\"\t28\"\n# bug number for skipped test:\tLU-5517\tLU-5517\tLU-5517\n\tALWAYS_EXCEPT+=\"\t29a\t29b\t29c\"\n# bug number for skipped test:\tLU-5518\n\tALWAYS_EXCEPT+=\"\t30\"\n# bug number for skipped test:\tLU-5519\tLU-5519\tLU-5519\tLU-5519\n\tALWAYS_EXCEPT+=\"\t31a\t31b\t31c\t31d\"\n# bug number for skipped test:\tLU-5519\tLU-5519\tLU-5519\tLU-5519\n\tALWAYS_EXCEPT+=\"\t31e\t31f\t31g\t31h\"\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\nbuild_test_filter\n\nrequire_dsh_mds || exit 0\n\nload_modules\n\nif ! check_versions; then\n\tskip \"It is NOT necessary to test lfsck under interoperation mode\"\n\texit 0\nfi\n\n[[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.3.60) ]] &&\n\tskip \"Need MDS version at least 2.3.60\" && exit 0\n\nLTIME=${LTIME:-120}\n\nSAVED_MDSSIZE=${MDSSIZE}\nSAVED_OSTSIZE=${OSTSIZE}\nSAVED_OSTCOUNT=${OSTCOUNT}\n# use small MDS + OST size to speed formatting time\n# do not use too small MDSSIZE/OSTSIZE, which affect the default journal size\nMDSSIZE=100000\n[ $(facet_fstype $SINGLEMDS) == zfs ] && MDSSIZE=300000\nOSTSIZE=100000\n[ $(facet_fstype ost1) == zfs ] && OSTSIZE=300000\n\n# no need too many OSTs, to reduce the format/start/stop overhead\ncleanupall\n[ $OSTCOUNT -gt 4 ] && OSTCOUNT=4\n\n# build up a clean test environment.\nREFORMAT=\"yes\" check_and_setup_lustre\n\nMDT_DEV=\"${FSNAME}-MDT0000\"\nOST_DEV=\"${FSNAME}-OST0000\"\nMDT_DEVNAME=$(mdsdevname ${SINGLEMDS//mds/})\nSTART_NAMESPACE=\"do_facet $SINGLEMDS \\\n\t\t$LCTL lfsck_start -M ${MDT_DEV} -t namespace\"\nSTART_LAYOUT=\"do_facet $SINGLEMDS \\\n\t\t$LCTL lfsck_start -M ${MDT_DEV} -t layout\"\nSTART_LAYOUT_ON_OST=\"do_facet ost1 $LCTL lfsck_start -M ${OST_DEV} -t layout\"\nSTOP_LFSCK=\"do_facet $SINGLEMDS $LCTL lfsck_stop -M ${MDT_DEV}\"\nSHOW_NAMESPACE=\"do_facet $SINGLEMDS \\\n\t\t$LCTL get_param -n mdd.${MDT_DEV}.lfsck_namespace\"\nSHOW_LAYOUT=\"do_facet $SINGLEMDS \\\n\t\t$LCTL get_param -n mdd.${MDT_DEV}.lfsck_layout\"\nSHOW_LAYOUT_ON_OST=\"do_facet ost1 \\\n\t\t$LCTL get_param -n obdfilter.${OST_DEV}.lfsck_layout\"\nMOUNT_OPTS_SCRUB=\"$MDS_MOUNT_OPTS -o user_xattr\"\nMOUNT_OPTS_NOSCRUB=\"$MDS_MOUNT_OPTS -o user_xattr,noscrub\"\nMOUNT_OPTS_SKIP_LFSCK=\"-o user_xattr,skip_lfsck\"\n\nlfsck_prep() {\n\tlocal ndirs=$1\n\tlocal nfiles=$2\n\tlocal igif=$3\n\n\tcheck_mount_and_prep\n\n\techo \"preparing... $nfiles * $ndirs files will be created $(date).\"\n\tif [ ! -z $igif ]; then\n\t\t#define OBD_FAIL_FID_IGIF\t0x1504\n\t\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1504\n\tfi\n\n\tcp $LUSTRE/tests/*.sh $DIR/$tdir/\n\tif [ $ndirs -gt 0 ]; then\n\t\tcreatemany -d $DIR/$tdir/d $ndirs\n\t\tcreatemany -m $DIR/$tdir/f $ndirs\n\t\tif [ $nfiles -gt 0 ]; then\n\t\t\tfor ((i = 0; i < $ndirs; i++)); do\n\t\t\t\tcreatemany -m $DIR/$tdir/d${i}/f $nfiles > \\\n\t\t\t\t\t/dev/null || error \"createmany $nfiles\"\n\t\t\tdone\n\t\tfi\n\t\tcreatemany -d $DIR/$tdir/e $ndirs\n\tfi\n\n\tif [ ! -z $igif ]; then\n\t\ttouch $DIR/$tdir/dummy\n\t\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tfi\n\n\techo \"prepared $(date).\"\n}\n\nrun_e2fsck_on_mdt0() {\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] && return\n\n\tstop $SINGLEMDS > /dev/null || error \"(0) Fail to the stop MDT0\"\n\trun_e2fsck $(facet_active_host $SINGLEMDS) $(mdsdevname 1) \"-n\" |\n\t\tgrep \"Fix? no\" && {\n\t\trun_e2fsck $(facet_active_host $SINGLEMDS) $(mdsdevname 1) \"-n\"\n\t\terror \"(2) Detected inconsistency on MDT0\"\n\t}\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(3) Fail to start MDT0\"\n}\n\nwait_all_targets_blocked() {\n\tlocal com=$1\n\tlocal status=$2\n\tlocal err=$3\n\n\tlocal count=$(do_facet mds1 \\\n\t\t     \"$LCTL lfsck_query -t $com -M ${FSNAME}-MDT0000 -w |\n\t\t      awk '/^${com}_mdts_${status}/ { print \\\\\\$2 }'\")\n\t[[ $count -eq $MDSCOUNT ]] || {\n\t\tdo_facet mds1 \"$LCTL lfsck_query -t $com -M ${FSNAME}-MDT0000\"\n\t\terror \"($err) only $count of $MDSCOUNT MDTs are in ${status}\"\n\t}\n}\n\nwait_all_targets() {\n\tlocal com=$1\n\tlocal status=$2\n\tlocal err=$3\n\n\twait_update_facet mds1 \"$LCTL lfsck_query -t $com -M ${FSNAME}-MDT0000 |\n\t\tawk '/^${com}_mdts_${status}/ { print \\\\\\$2 }'\" \\\n\t\t\"$MDSCOUNT\" $LTIME || {\n\t\tdo_facet mds1 \"$LCTL lfsck_query -t $com -M ${FSNAME}-MDT0000\"\n\t\terror \"($err) some MDTs are not in ${status}\"\n\t}\n}\n\ntest_0() {\n\tlfsck_prep 3 3\n\n\t#define OBD_FAIL_LFSCK_DELAY1\t\t0x1600\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=3 fail_loc=0x1600\n\t$START_NAMESPACE -r || error \"(2) Fail to start LFSCK for namespace!\"\n\n\t$SHOW_NAMESPACE || error \"Fail to monitor LFSCK (3)\"\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(4) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t$STOP_LFSCK || error \"(5) Fail to stop LFSCK!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"stopped\" ] ||\n\t\terror \"(6) Expect 'stopped', but got '$STATUS'\"\n\n\t$START_NAMESPACE || error \"(7) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(8) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(9) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(10) Expect nothing to be repaired, but got: $repaired\"\n\n\tlocal scanned1=$($SHOW_NAMESPACE | awk '/^success_count/ { print $2 }')\n\t$START_NAMESPACE -r || error \"(11) Fail to reset LFSCK!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(12) unexpected status\"\n\t}\n\n\tlocal scanned2=$($SHOW_NAMESPACE | awk '/^success_count/ { print $2 }')\n\t[ $((scanned1 + 1)) -eq $scanned2 ] ||\n\t\terror \"(13) Expect success $((scanned1 + 1)), but got $scanned2\"\n\n\techo \"stopall, should NOT crash LU-3649\"\n\tstopall || error \"(14) Fail to stopall\"\n}\nrun_test 0 \"Control LFSCK manually\"\n\ntest_1a() {\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_FID_INDIR\t0x1501\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1501\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed FID-in-dirent: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\t#define OBD_FAIL_FID_LOOKUP\t0x1505\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1505\n\tls $DIR/$tdir/ > /dev/null || error \"(7) no FID-in-dirent.\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n}\nrun_test 1a \"LFSCK can find out and repair crashed FID-in-dirent\"\n\ntest_1b()\n{\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"OI Scrub not implemented for ZFS\" && return\n\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_FID_INLMA\t0x1502\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1502\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t#define OBD_FAIL_FID_NOLMA\t0x1506\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1506\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair the missing FID-in-LMA: $repaired\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\t#define OBD_FAIL_FID_LOOKUP\t0x1505\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1505\n\tstat $DIR/$tdir/dummy > /dev/null || error \"(7) no FID-in-LMA.\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n}\nrun_test 1b \"LFSCK can find out and repair the missing FID-in-LMA\"\n\ntest_1c() {\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_FID_IGIF\t0x1504\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1504\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair lost FID-in-dirent: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\t#define OBD_FAIL_FID_LOOKUP\t0x1505\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1505\n\tls $DIR/$tdir/ > /dev/null || error \"(7) no FID-in-dirent.\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n}\nrun_test 1c \"LFSCK can find out and repair lost FID-in-dirent\"\n\ntest_2a() {\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_LINKEA_CRASH\t0x1603\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1603\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^linkea_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase2/ { print $2 }')\n\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed linkEA: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\tstat $DIR/$tdir/dummy | grep \"Links: 1\" > /dev/null ||\n\t\terror \"(7) Fail to stat $DIR/$tdir/dummy\"\n\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/dummy)\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/dummy\" ] ||\n\t\terror \"(8) Fail to repair linkEA: $dummyfid $dummyname\"\n}\nrun_test 2a \"LFSCK can find out and repair crashed linkEA entry\"\n\ntest_2b()\n{\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase2/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed linkEA: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\tstat $DIR/$tdir/dummy | grep \"Links: 1\" > /dev/null ||\n\t\terror \"(7) Fail to stat $DIR/$tdir/dummy\"\n\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/dummy)\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/dummy\" ] ||\n\t\terror \"(8) Fail to repair linkEA: $dummyfid $dummyname\"\n}\nrun_test 2b \"LFSCK can find out and remove invalid linkEA entry\"\n\ntest_2c()\n{\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE2\t0x1605\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1605\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase2/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed linkEA: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\tstat $DIR/$tdir/dummy | grep \"Links: 1\" > /dev/null ||\n\t\terror \"(7) Fail to stat $DIR/$tdir/dummy\"\n\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/dummy)\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/dummy\" ] ||\n\t\terror \"(8) Fail to repair linkEA: $dummyfid $dummyname\"\n}\nrun_test 2c \"LFSCK can find out and remove repeated linkEA entry\"\n\ntest_2d()\n{\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_NO_LINKEA\t0x161d\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x161d\n\ttouch $DIR/$tdir/dummy\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^linkea_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed linkEA: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(6) Fail to start client!\"\n\n\tstat $DIR/$tdir/dummy | grep \"Links: 1\" > /dev/null ||\n\t\terror \"(7) Fail to stat $DIR/$tdir/dummy\"\n\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/dummy)\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/dummy\" ] ||\n\t\terror \"(8) Fail to repair linkEA: $dummyfid $dummyname\"\n}\nrun_test 2d \"LFSCK can recover the missing linkEA entry\"\n\ntest_2e()\n{\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0 on MDT1\"\n\n\t#define OBD_FAIL_LFSCK_LINKEA_CRASH\t0x1603\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1603\n\t$LFS mkdir -i 0 $DIR/$tdir/d0/d1 || error \"(2) Fail to mkdir d1 on MDT0\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\t$START_NAMESPACE -r -A || error \"(3) Fail to start LFSCK for namespace!\"\n\n\twait_all_targets_blocked namespace completed 4\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^linkea_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Fail to repair crashed linkEA: $repaired\"\n\n\tlocal fid=$($LFS path2fid $DIR/$tdir/d0/d1)\n\tlocal name=$($LFS fid2path $DIR $fid)\n\t[ \"$name\" == \"$DIR/$tdir/d0/d1\" ] ||\n\t\terror \"(6) Fail to repair linkEA: $fid $name\"\n}\nrun_test 2e \"namespace LFSCK can verify remote object linkEA\"\n\ntest_3()\n{\n\tlfsck_prep 4 4\n\n\tmkdir $DIR/$tdir/dummy || error \"(1) Fail to mkdir\"\n\tln $DIR/$tdir/d0/f0 $DIR/$tdir/dummy/f0 || error \"(2) Fail to hardlink\"\n\tln $DIR/$tdir/d0/f1 $DIR/$tdir/dummy/f1 || error \"(3) Fail to hardlink\"\n\n\t$LFS mkdir -i 0 $DIR/$tdir/edir || error \"(4) Fail to mkdir\"\n\ttouch $DIR/$tdir/edir/f0 || error \"(5) Fail to touch\"\n\ttouch $DIR/$tdir/edir/f1 || error \"(6) Fail to touch\"\n\n\t#define OBD_FAIL_LFSCK_LINKEA_CRASH\t0x1603\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1603\n\tln $DIR/$tdir/edir/f0 $DIR/$tdir/edir/w0 || error \"(7) Fail to hardlink\"\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\tln $DIR/$tdir/edir/f1 $DIR/$tdir/edir/w1 || error \"(8) Fail to hardlink\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\t$START_NAMESPACE -r || error \"(9) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(10) unexpected status\"\n\t}\n\n\tlocal checked=$($SHOW_NAMESPACE |\n\t\t\tawk '/^checked_phase2/ { print $2 }')\n\t[ $checked -ge 4 ] ||\n\t\terror \"(11) Fail to check multiple-linked object: $checked\"\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^multiple_linked_repaired/ { print $2 }')\n\t[ $repaired -ge 2 ] ||\n\t\terror \"(12) Fail to repair multiple-linked object: $repaired\"\n}\nrun_test 3 \"LFSCK can verify multiple-linked objects\"\n\ntest_4()\n{\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"OI Scrub not implemented for ZFS\" && return\n\n\tlfsck_prep 3 3\n\tcleanup_mount $MOUNT || error \"(0.1) Fail to stop client!\"\n\tstop $SINGLEMDS > /dev/null || error \"(0.2) Fail to stop MDS!\"\n\n\tmds_backup_restore $SINGLEMDS || error \"(1) Fail to backup/restore!\"\n\techo \"start $SINGLEMDS with disabling OI scrub\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(2) Fail to start MDS!\"\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1601\n\t$START_NAMESPACE -r || error \"(4) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^flags/ { print \\\\\\$2 }'\" \"inconsistent\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(5) unexpected status\"\n\t}\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(6) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(7) unexpected status\"\n\t}\n\n\tFLAGS=$($SHOW_NAMESPACE | awk '/^flags/ { print $2 }')\n\t[ -z \"$FLAGS\" ] || error \"(8) Expect empty flags, but got '$FLAGS'\"\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\n\t[ $repaired -ge 9 ] ||\n\t\terror \"(9) Fail to re-generate FID-in-dirent: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(10) Fail to start client!\"\n\n\t#define OBD_FAIL_FID_LOOKUP\t0x1505\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1505\n\tls $DIR/$tdir/ > /dev/null || error \"(11) no FID-in-dirent.\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n}\nrun_test 4 \"FID-in-dirent can be rebuilt after MDT file-level backup/restore\"\n\ntest_5()\n{\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"OI Scrub not implemented for ZFS\" && return\n\n\tlfsck_prep 1 1 1\n\tcleanup_mount $MOUNT || error \"(0.1) Fail to stop client!\"\n\tstop $SINGLEMDS > /dev/null || error \"(0.2) Fail to stop MDS!\"\n\n\tmds_backup_restore $SINGLEMDS 1 || error \"(1) Fail to backup/restore!\"\n\techo \"start $SINGLEMDS with disabling OI scrub\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(2) Fail to start MDS!\"\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1601\n\t$START_NAMESPACE -r || error \"(4) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^flags/ { print \\\\\\$2 }'\" \"inconsistent,upgrade\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(5) unexpected status\"\n\t}\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(6) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(7) unexpected status\"\n\t}\n\n\tFLAGS=$($SHOW_NAMESPACE | awk '/^flags/ { print $2 }')\n\t[ -z \"$FLAGS\" ] || error \"(8) Expect empty flags, but got '$FLAGS'\"\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t# for interop with old server\n\t[ -z \"$repaired\" ] &&\n\t\trepaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^updated_phase1/ { print $2 }')\n\n\t[ $repaired -ge 2 ] ||\n\t\terror \"(9) Fail to generate FID-in-dirent for IGIF: $repaired\"\n\n\trun_e2fsck_on_mdt0\n\n\tmount_client $MOUNT || error \"(10) Fail to start client!\"\n\n\t#define OBD_FAIL_FID_LOOKUP\t0x1505\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1505\n\tstat $DIR/$tdir/dummy > /dev/null || error \"(11) no FID-in-LMA.\"\n\n\tls $DIR/$tdir/ > /dev/null || error \"(12) no FID-in-dirent.\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/dummy)\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/dummy\" ] ||\n\t\terror \"(13) Fail to generate linkEA: $dummyfid $dummyname\"\n}\nrun_test 5 \"LFSCK can handle IGIF object upgrading\"\n\ntest_6a() {\n\tlfsck_prep 5 5\n\n\t#define OBD_FAIL_LFSCK_DELAY1\t\t0x1600\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1600\n\t$START_NAMESPACE -r || error \"(2) Fail to start LFSCK for namespace!\"\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(3) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t# Sleep 3 sec to guarantee at least one object processed by LFSCK\n\tsleep 3\n\t# Fail the LFSCK to guarantee there is at least one checkpoint\n\t#define OBD_FAIL_LFSCK_FATAL1\t\t0x1608\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x80001608\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"failed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal POS0=$($SHOW_NAMESPACE |\n\t\t     awk '/^last_checkpoint_position/ { print $2 }' |\n\t\t     tr -d ',')\n\n\t#define OBD_FAIL_LFSCK_DELAY1\t\t0x1600\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1600\n\t$START_NAMESPACE || error \"(5) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(6) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tlocal POS1=$($SHOW_NAMESPACE |\n\t\t     awk '/^latest_start_position/ { print $2 }' |\n\t\t     tr -d ',')\n\t[[ $POS0 -lt $POS1 ]] ||\n\t\terror \"(7) Expect larger than: $POS0, but got $POS1\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(8) unexpected status\"\n\t}\n}\nrun_test 6a \"LFSCK resumes from last checkpoint (1)\"\n\ntest_6b() {\n\tlfsck_prep 5 5\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1601\n\t$START_NAMESPACE -r || error \"(2) Fail to start LFSCK for namespace!\"\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(3) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t# Sleep 5 sec to guarantee that we are in the directory scanning\n\tsleep 5\n\t# Fail the LFSCK to guarantee there is at least one checkpoint\n\t#define OBD_FAIL_LFSCK_FATAL2\t\t0x1609\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x80001609\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"failed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal O_POS0=$($SHOW_NAMESPACE |\n\t\t       awk '/^last_checkpoint_position/ { print $2 }' |\n\t\t       tr -d ',')\n\n\tlocal D_POS0=$($SHOW_NAMESPACE |\n\t\t       awk '/^last_checkpoint_position/ { print $4 }')\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1601\n\t$START_NAMESPACE || error \"(5) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(6) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tlocal O_POS1=$($SHOW_NAMESPACE |\n\t\t       awk '/^latest_start_position/ { print $2 }' |\n\t\t       tr -d ',')\n\tlocal D_POS1=$($SHOW_NAMESPACE |\n\t\t       awk '/^latest_start_position/ { print $4 }')\n\n\techo \"Additional debug for 6b\"\n\t$SHOW_NAMESPACE\n\tif [ \"$D_POS0\" == \"N/A\" -o \"$D_POS0\" == \"0x0\" \\\n\t     -o \"$D_POS1\" == \"0x0\" -o \"$D_POS1\" == \"N/A\" ]; then\n\t\t[[ $O_POS0 -lt $O_POS1 ]] ||\n\t\t\terror \"(7.1) $O_POS1 is not larger than $O_POS0\"\n\telse\n\t\t[[ $D_POS0 -lt $D_POS1 ]] ||\n\t\t\terror \"(7.2) $D_POS1 is not larger than $D_POS0\"\n\tfi\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(8) unexpected status\"\n\t}\n}\nrun_test 6b \"LFSCK resumes from last checkpoint (2)\"\n\ntest_7a()\n{\n\tlfsck_prep 5 5\n\tumount_client $MOUNT\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1601\n\t$START_NAMESPACE -r || error \"(2) Fail to start LFSCK for namespace!\"\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(3) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t# Sleep 3 sec to guarantee at least one object processed by LFSCK\n\tsleep 3\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(4) Fail to stop MDS!\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\techo \"start $SINGLEMDS\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_SCRUB > /dev/null ||\n\t\terror \"(5) Fail to start MDS!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 30 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(6) unexpected status\"\n\t}\n}\nrun_test 7a \"non-stopped LFSCK should auto restarts after MDS remount (1)\"\n\ntest_7b()\n{\n\tlfsck_prep 2 2\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\tfor ((i = 0; i < 20; i++)); do\n\t\ttouch $DIR/$tdir/dummy${i}\n\tdone\n\n\t#define OBD_FAIL_LFSCK_DELAY3\t\t0x1602\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1 fail_loc=0x1602\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"scanning-phase2\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tumount_client $MOUNT\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(5) Fail to stop MDS!\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\techo \"start $SINGLEMDS\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_SCRUB > /dev/null ||\n\t\terror \"(6) Fail to start MDS!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 30 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(7) unexpected status\"\n\t}\n}\nrun_test 7b \"non-stopped LFSCK should auto restarts after MDS remount (2)\"\n\ntest_8()\n{\n\techo \"formatall\"\n\tformatall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n\n\tlfsck_prep 20 20\n\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"init\" ] ||\n\t\terror \"(2) Expect 'init', but got '$STATUS'\"\n\n\t#define OBD_FAIL_LFSCK_LINKEA_CRASH\t0x1603\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1603\n\tmkdir $DIR/$tdir/crashed\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\tfor ((i = 0; i < 5; i++)); do\n\t\ttouch $DIR/$tdir/dummy${i}\n\tdone\n\n\tumount_client $MOUNT || error \"(3) Fail to stop client!\"\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=2 fail_loc=0x1601\n\t$START_NAMESPACE || error \"(4) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(5) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t$STOP_LFSCK || error \"(6) Fail to stop LFSCK!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"stopped\" ] ||\n\t\terror \"(7) Expect 'stopped', but got '$STATUS'\"\n\n\t$START_NAMESPACE || error \"(8) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(9) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t#define OBD_FAIL_LFSCK_FATAL2\t\t0x1609\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x80001609\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"failed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(10) unexpected status\"\n\t}\n\n\t#define OBD_FAIL_LFSCK_DELAY1\t\t0x1600\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1600\n\t$START_NAMESPACE || error \"(11) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(12) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\t#define OBD_FAIL_LFSCK_CRASH\t\t0x160a\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x160a\n\tsleep 5\n\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(13) Fail to stop MDS!\"\n\n\t#define OBD_FAIL_LFSCK_NO_AUTO\t\t0x160b\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x160b\n\n\techo \"start $SINGLEMDS\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_SCRUB > /dev/null ||\n\t\terror \"(14) Fail to start MDS!\"\n\n\tlocal timeout=$(max_recovery_time)\n\tlocal timer=0\n\n\twhile [ $timer -lt $timeout ]; do\n\t\tSTATUS=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\tmdt.${MDT_DEV}.recovery_status |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\")\n\t\t[ \"$STATUS\" != \"RECOVERING\" ] && break;\n\t\tsleep 1\n\t\ttimer=$((timer + 1))\n\tdone\n\n\t[ $timer != $timeout ] ||\n\t\terror \"(14.1) recovery timeout\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"crashed\" ] ||\n\t\terror \"(15) Expect 'crashed', but got '$STATUS'\"\n\n\t#define OBD_FAIL_LFSCK_DELAY2\t\t0x1601\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1601\n\t$START_NAMESPACE || error \"(16) Fail to start LFSCK for namespace!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(17) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(18) Fail to stop MDS!\"\n\n\t#define OBD_FAIL_LFSCK_NO_AUTO\t\t0x160b\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x160b\n\n\techo \"start $SINGLEMDS\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_SCRUB > /dev/null ||\n\t\terror \"(19) Fail to start MDS!\"\n\n\ttimer=0\n\twhile [ $timer -lt $timeout ]; do\n\t\tSTATUS=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\tmdt.${MDT_DEV}.recovery_status |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\")\n\t\t[ \"$STATUS\" != \"RECOVERING\" ] && break;\n\t\tsleep 1\n\t\ttimer=$((timer + 1))\n\tdone\n\n\t[ $timer != $timeout ] ||\n\t\terror \"(19.1) recovery timeout\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"paused\" ] ||\n\t\terror \"(20) Expect 'paused', but got '$STATUS'\"\n\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(20.1) Fail to stop MDS!\"\n\n\techo \"start $SINGLEMDS without resume LFSCK\"\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_SKIP_LFSCK > /dev/null ||\n\t\terror \"(20.2) Fail to start MDS!\"\n\n\ttimer=0\n\twhile [ $timer -lt $timeout ]; do\n\t\tSTATUS=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\tmdt.${MDT_DEV}.recovery_status |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\")\n\t\t[ \"$STATUS\" != \"RECOVERING\" ] && break;\n\t\tsleep 1\n\t\ttimer=$((timer + 1))\n\tdone\n\n\t[ $timer != $timeout ] ||\n\t\terror \"(20.3) recovery timeout\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"paused\" ] ||\n\t\terror \"(20.4) Expect 'paused', but got '$STATUS'\"\n\n\t#define OBD_FAIL_LFSCK_DELAY3\t\t0x1602\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=2 fail_loc=0x1602\n\n\t$START_NAMESPACE || error \"(21) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"scanning-phase2\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(22) unexpected status\"\n\t}\n\n\tlocal FLAGS=$($SHOW_NAMESPACE | awk '/^flags/ { print $2 }')\n\t[ \"$FLAGS\" == \"scanned-once,inconsistent\" ] ||\n\t\terror \"(23) Expect 'scanned-once,inconsistent',but got '$FLAGS'\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(24) unexpected status\"\n\t}\n\n\tFLAGS=$($SHOW_NAMESPACE | awk '/^flags/ { print $2 }')\n\t[ -z \"$FLAGS\" ] || error \"(25) Expect empty flags, but got '$FLAGS'\"\n}\nrun_test 8 \"LFSCK state machine\"\n\ntest_9a() {\n\tif [ -z \"$(grep \"processor.*: 1\" /proc/cpuinfo)\" ]; then\n\t\tskip \"Testing on UP system, the speed may be inaccurate.\"\n\t\treturn 0\n\tfi\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/lfsck || error \"(1) Fail to mkdir lfsck\"\n\t$LFS setstripe -c 1 -i -1 $DIR/$tdir/lfsck\n\tcreatemany -o $DIR/$tdir/lfsck/f 5000\n\n\tlocal BASE_SPEED1=100\n\tlocal RUN_TIME1=10\n\t$START_LAYOUT -r -s $BASE_SPEED1 || error \"(2) Fail to start LFSCK!\"\n\n\tsleep $RUN_TIME1\n\tSTATUS=$($SHOW_LAYOUT | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(3) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tlocal SPEED=$($SHOW_LAYOUT |\n\t\t      awk '/^average_speed_phase1/ { print $2 }')\n\n\t# There may be time error, normally it should be less than 2 seconds.\n\t# We allow another 20% schedule error.\n\tlocal TIME_DIFF=2\n\t# MAX_MARGIN = 1.3 = 13 / 10\n\tlocal MAX_SPEED=$((BASE_SPEED1 * (RUN_TIME1 + TIME_DIFF) / \\\n\t\t\t   RUN_TIME1 * 13 / 10))\n\t[ $SPEED -lt $MAX_SPEED ] || {\n\t\t$SHOW_LAYOUT\n\t\tlog \"speed1: $BASE_SPEED1 time1: $RUN_TIME1\"\n\t\terror \"(4) Speed $SPEED, expected < $MAX_SPEED\"\n\t}\n\n\t# adjust speed limit\n\tlocal BASE_SPEED2=300\n\tlocal RUN_TIME2=10\n\tdo_facet $SINGLEMDS \\\n\t\t$LCTL set_param -n mdd.${MDT_DEV}.lfsck_speed_limit $BASE_SPEED2\n\tsleep $RUN_TIME2\n\n\tSPEED=$($SHOW_LAYOUT | awk '/^average_speed_phase1/ { print $2 }')\n\t# MIN_MARGIN = 0.7 = 7 / 10\n\tlocal MIN_SPEED=$(((BASE_SPEED1 * (RUN_TIME1 - TIME_DIFF) + \\\n\t\t\t    BASE_SPEED2 * (RUN_TIME2 - TIME_DIFF)) / \\\n\t\t\t   (RUN_TIME1 + RUN_TIME2) * 7 / 10))\n\t[ $SPEED -gt $MIN_SPEED ] || {\n\t\tif [ $(facet_fstype $SINGLEMDS) != ldiskfs ]; then\n\t\t\terror_ignore LU-5624 \\\n\t\t\t\"(5.1) Got speed $SPEED, expected more than $MIN_SPEED\"\n\t\telse\n\t\t\terror \\\n\t\t\t\"(5.2) Got speed $SPEED, expected more than $MIN_SPEED\"\n\t\tfi\n\t}\n\n\t# MAX_MARGIN = 1.3 = 13 / 10\n\tMAX_SPEED=$(((BASE_SPEED1 * (RUN_TIME1 + TIME_DIFF) + \\\n\t\t      BASE_SPEED2 * (RUN_TIME2 + TIME_DIFF)) / \\\n\t\t     (RUN_TIME1 + RUN_TIME2) * 13 / 10))\n\t[ $SPEED -lt $MAX_SPEED ] || {\n\t\t$SHOW_LAYOUT\n\t\tlog \"speed1: $BASE_SPEED1 time1: $RUN_TIME1\"\n\t\tlog \"speed2: $BASE_SPEED2 time2: $RUN_TIME2\"\n\t\terror \"(6) Speed $SPEED, expected < $MAX_SPEED\"\n\t}\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param -n mdd.*.lfsck_speed_limit 0\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param -n obdfilter.*.lfsck_speed_limit 0\n\n\twait_update_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n mdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 30 ||\n\t\terror \"(7) Failed to get expected 'completed'\"\n}\nrun_test 9a \"LFSCK speed control (1)\"\n\ntest_9b() {\n\tif [ -z \"$(grep \"processor.*: 1\" /proc/cpuinfo)\" ]; then\n\t\tskip \"Testing on UP system, the speed may be inaccurate.\"\n\t\treturn 0\n\tfi\n\n\tlfsck_prep 0 0\n\n\techo \"Preparing another 50 * 50 files (with error) at $(date).\"\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\tcreatemany -d $DIR/$tdir/d 50\n\tcreatemany -m $DIR/$tdir/f 50\n\tfor ((i = 0; i < 50; i++)); do\n\t\tcreatemany -m $DIR/$tdir/d${i}/f 50 > /dev/null\n\tdone\n\n\t#define OBD_FAIL_LFSCK_NO_DOUBLESCAN\t0x160c\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x160c\n\t$START_NAMESPACE -r || error \"(4) Fail to start LFSCK!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"stopped\" 10 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(5) unexpected status\"\n\t}\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\techo \"Prepared at $(date).\"\n\n\tlocal BASE_SPEED1=50\n\tlocal RUN_TIME1=10\n\t$START_NAMESPACE -s $BASE_SPEED1 || error \"(6) Fail to start LFSCK!\"\n\n\tsleep $RUN_TIME1\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase2\" ] ||\n\t\terror \"(7) Expect 'scanning-phase2', but got '$STATUS'\"\n\n\tlocal SPEED=$($SHOW_NAMESPACE |\n\t\t      awk '/^average_speed_phase2/ { print $2 }')\n\t# There may be time error, normally it should be less than 2 seconds.\n\t# We allow another 20% schedule error.\n\tlocal TIME_DIFF=2\n\t# MAX_MARGIN = 1.3 = 13 / 10\n\tlocal MAX_SPEED=$((BASE_SPEED1 * (RUN_TIME1 + TIME_DIFF) / \\\n\t\t\t  RUN_TIME1 * 13 / 10))\n\t[ $SPEED -lt $MAX_SPEED ] || {\n\t\t$SHOW_NAMESPACE\n\t\tlog \"speed1: $BASE_SPEED1 time1: $RUN_TIME1\"\n\t\terror \"(8) Speed $SPEED, expected < $MAX_SPEED\"\n\t}\n\n\t# adjust speed limit\n\tlocal BASE_SPEED2=150\n\tlocal RUN_TIME2=10\n\tdo_facet $SINGLEMDS \\\n\t\t$LCTL set_param -n mdd.${MDT_DEV}.lfsck_speed_limit $BASE_SPEED2\n\tsleep $RUN_TIME2\n\n\tSPEED=$($SHOW_NAMESPACE | awk '/^average_speed_phase2/ { print $2 }')\n\t# MIN_MARGIN = 0.7 = 7 / 10\n\tlocal MIN_SPEED=$(((BASE_SPEED1 * (RUN_TIME1 - TIME_DIFF) + \\\n\t\t\t    BASE_SPEED2 * (RUN_TIME2 - TIME_DIFF)) / \\\n\t\t\t   (RUN_TIME1 + RUN_TIME2) * 7 / 10))\n\t[ $SPEED -gt $MIN_SPEED ] || {\n\t\tif [ $(facet_fstype $SINGLEMDS) != ldiskfs ]; then\n\t\t\terror_ignore LU-5624 \\\n\t\t\t\"(9.1) Got speed $SPEED, expected more than $MIN_SPEED\"\n\t\telse\n\t\t\terror \\\n\t\t\t\"(9.2) Got speed $SPEED, expected more than $MIN_SPEED\"\n\t\tfi\n\t}\n\n\t# MAX_MARGIN = 1.3 = 13 / 10\n\tMAX_SPEED=$(((BASE_SPEED1 * (RUN_TIME1 + TIME_DIFF) + \\\n\t\t      BASE_SPEED2 * (RUN_TIME2 + TIME_DIFF)) / \\\n\t\t     (RUN_TIME1 + RUN_TIME2) * 13 / 10))\n\t[ $SPEED -lt $MAX_SPEED ] || {\n\t\t$SHOW_NAMESPACE\n\t\tlog \"speed1: $BASE_SPEED1 time1: $RUN_TIME1\"\n\t\tlog \"speed2: $BASE_SPEED2 time2: $RUN_TIME2\"\n\t\terror \"(10) Speed $SPEED, expected < $MAX_SPEED\"\n\t}\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param -n mdd.*.lfsck_speed_limit 0\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param -n obdfilter.*.lfsck_speed_limit 0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(11) unexpected status\"\n\t}\n}\nrun_test 9b \"LFSCK speed control (2)\"\n\ntest_10()\n{\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"lookup(..)/linkea on ZFS issue\" && return\n\n\tlfsck_prep 1 1\n\n\techo \"Preparing more files with error at $(date).\"\n\t#define OBD_FAIL_LFSCK_LINKEA_CRASH\t0x1603\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1603\n\n\tfor ((i = 0; i < 1000; i = $((i+2)))); do\n\t\tmkdir -p $DIR/$tdir/d${i}\n\t\ttouch $DIR/$tdir/f${i}\n\t\tcreatemany -m $DIR/$tdir/d${i}/f 5 > /dev/null\n\tdone\n\n\t#define OBD_FAIL_LFSCK_LINKEA_MORE\t0x1604\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1604\n\n\tfor ((i = 1; i < 1000; i = $((i+2)))); do\n\t\tmkdir -p $DIR/$tdir/d${i}\n\t\ttouch $DIR/$tdir/f${i}\n\t\tcreatemany -m $DIR/$tdir/d${i}/f 5 > /dev/null\n\tdone\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\techo \"Prepared at $(date).\"\n\n\tln $DIR/$tdir/f200 $DIR/$tdir/d200/dummy\n\n\tumount_client $MOUNT\n\tmount_client $MOUNT || error \"(3) Fail to start client!\"\n\n\t$START_NAMESPACE -r -s 100 || error \"(5) Fail to start LFSCK!\"\n\n\tsleep 10\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(6) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tls -ailR $MOUNT > /dev/null || error \"(7) Fail to ls!\"\n\n\ttouch $DIR/$tdir/d198/a0 || error \"(8) Fail to touch!\"\n\n\tmkdir $DIR/$tdir/d199/a1 || error \"(9) Fail to mkdir!\"\n\n\tunlink $DIR/$tdir/f200 || error \"(10) Fail to unlink!\"\n\n\trm -rf $DIR/$tdir/d201 || error \"(11) Fail to rmdir!\"\n\n\tmv $DIR/$tdir/f202 $DIR/$tdir/d203/ || error \"(12) Fail to rename!\"\n\n\tln $DIR/$tdir/f204 $DIR/$tdir/d205/a3 || error \"(13) Fail to hardlink!\"\n\n\tln -s $DIR/$tdir/d206 $DIR/$tdir/d207/a4 ||\n\t\terror \"(14) Fail to softlink!\"\n\n\tSTATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(15) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param -n mdd.*.lfsck_speed_limit 0\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param -n obdfilter.*.lfsck_speed_limit 0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(16) unexpected status\"\n\t}\n}\nrun_test 10 \"System is available during LFSCK scanning\"\n\n# remove LAST_ID\nost_remove_lastid() {\n\tlocal ost=$1\n\tlocal idx=$2\n\tlocal rcmd=\"do_facet ost${ost}\"\n\n\techo \"remove LAST_ID on ost${ost}: idx=${idx}\"\n\n\t# step 1: local mount\n\tmount_fstype ost${ost} || return 1\n\t# step 2: remove the specified LAST_ID\n\t${rcmd} rm -fv $(facet_mntpt ost${ost})/O/${idx}/{LAST_ID,d0/0}\n\t# step 3: umount\n\tunmount_fstype ost${ost} || return 2\n}\n\ntest_11a() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f 64 || error \"(0) Fail to create 64 files.\"\n\n\techo \"stopall\"\n\tstopall > /dev/null\n\n\tost_remove_lastid 1 0 || error \"(1) Fail to remove LAST_ID\"\n\n\tstart ost1 $(ostdevname 1) $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(2) Fail to start ost1\"\n\n\t#define OBD_FAIL_LFSCK_DELAY4\t\t0x160e\n\tdo_facet ost1 $LCTL set_param fail_val=3 fail_loc=0x160e\n\n\techo \"trigger LFSCK for layout on ost1 to rebuild the LAST_ID(s)\"\n\t$START_LAYOUT_ON_OST -r || error \"(4) Fail to start LFSCK on OST!\"\n\n\twait_update_facet ost1 \"$LCTL get_param -n \\\n\t\tobdfilter.${OST_DEV}.lfsck_layout |\n\t\tawk '/^flags/ { print \\\\\\$2 }'\" \"crashed_lastid\" 60 || {\n\t\t$SHOW_LAYOUT_ON_OST\n\t\terror \"(5) unexpected status\"\n\t}\n\n\tdo_facet ost1 $LCTL set_param fail_val=0 fail_loc=0\n\n\twait_update_facet ost1 \"$LCTL get_param -n \\\n\t\tobdfilter.${OST_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT_ON_OST\n\t\terror \"(6) unexpected status\"\n\t}\n\n\techo \"the LAST_ID(s) should have been rebuilt\"\n\tFLAGS=$($SHOW_LAYOUT_ON_OST | awk '/^flags/ { print $2 }')\n\t[ -z \"$FLAGS\" ] || error \"(7) Expect empty flags, but got '$FLAGS'\"\n}\nrun_test 11a \"LFSCK can rebuild lost last_id\"\n\ntest_11b() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"set fail_loc=0x160d to skip the updating LAST_ID on-disk\"\n\t#define OBD_FAIL_LFSCK_SKIP_LASTID\t0x160d\n\tdo_facet ost1 $LCTL set_param fail_loc=0x160d\n\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 32))\n\n\tlocal proc_path=\"${FSNAME}-OST0000-osc-MDT0000\"\n\tlocal seq=$(do_facet mds1 $LCTL get_param -n \\\n\t\t    osp.${proc_path}.prealloc_last_seq)\n\tlocal id_used=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\tosp.${proc_path}.prealloc_last_id)\n\n\tumount_client $MOUNT\n\tstop ost1 || error \"(1) Fail to stop ost1\"\n\n\t#define OBD_FAIL_OST_ENOSPC              0x215\n\tdo_facet ost1 $LCTL set_param fail_loc=0x215\n\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS ||\n\t\terror \"(2) Fail to start ost1\"\n\n\tfor ((i = 0; i < 60; i++)); do\n\t\tid_ost1=$(do_facet ost1 \\\n\t\t\t  \"$LCTL get_param -n obdfilter.$ost1_svc.last_id\" |\n\t\t\t  awk -F: \"/$seq/ { print \\$2 }\")\n\t\t[ -n \"$id_ost1\" ] && break\n\t\tsleep 1\n\tdone\n\n\techo \"the on-disk LAST_ID should be smaller than the expected one\"\n\t[ $id_used -gt $id_ost1 ] ||\n\t\terror \"(4) expect id_used '$id_used' > id_ost1 '$id_ost1'\"\n\n\techo \"trigger LFSCK for layout on ost1 to rebuild the on-disk LAST_ID\"\n\t$START_LAYOUT_ON_OST -r || error \"(5) Fail to start LFSCK on OST!\"\n\n\twait_update_facet ost1 \\\n\t\t\"$LCTL get_param -n obdfilter.$ost1_svc.lfsck_layout |\n\t\t awk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT_ON_OST\n\t\terror \"(6) unexpected status\"\n\t}\n\n\tstop ost1 || error \"(7) Fail to stop ost1\"\n\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS ||\n\t\terror \"(8) Fail to start ost1\"\n\n\techo \"the on-disk LAST_ID should have been rebuilt\"\n\t# last_id may be larger than $id_used if objects were created/skipped\n\twait_update_facet_cond ost1 \\\n\t\t\"$LCTL get_param -n obdfilter.$ost1_svc.last_id |\n\t\t awk -F: '/$seq/ { print \\\\\\$2 }'\" \"-ge\" \"$id_used\" 60 || {\n\t\tdo_facet ost1 $LCTL get_param obdfilter.$ost1_svc.last_id\n\t\terror \"(9) expect last_id >= id_used $seq:$id_used\"\n\t}\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\tstopall || error \"(10) Fail to stopall\"\n}\nrun_test 11b \"LFSCK can rebuild crashed last_id\"\n\ntest_12a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tcheck_mount_and_prep\n\tfor k in $(seq $MDSCOUNT); do\n\t\t$LFS mkdir -i $((k - 1)) $DIR/$tdir/${k}\n\t\tcreatemany -o $DIR/$tdir/${k}/f 100 ||\n\t\t\terror \"(0) Fail to create 100 files.\"\n\tdone\n\n\techo \"Start namespace LFSCK on all targets by single command (-s 1).\"\n\tdo_facet mds1 $LCTL lfsck_start -M ${FSNAME}-MDT0000 -t namespace -A \\\n\t\t-s 1 -r || error \"(2) Fail to start LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'scanning-phase1' status.\"\n\twait_all_targets namespace scanning-phase1 3\n\n\techo \"Stop namespace LFSCK on all targets by single lctl command.\"\n\tdo_facet mds1 $LCTL lfsck_stop -M ${FSNAME}-MDT0000 -A ||\n\t\terror \"(4) Fail to stop LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'stopped' status.\"\n\twait_all_targets_blocked namespace stopped 5\n\n\techo \"Re-start namespace LFSCK on all targets by single command (-s 0).\"\n\tdo_facet mds1 $LCTL lfsck_start -M ${FSNAME}-MDT0000 -t namespace -A \\\n\t\t-s 0 -r || error \"(6) Fail to start LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'completed' status.\"\n\twait_all_targets_blocked namespace completed 7\n\n\tstart_full_debug_logging\n\n\techo \"Start layout LFSCK on all targets by single command (-s 1).\"\n\tdo_facet mds1 $LCTL lfsck_start -M ${FSNAME}-MDT0000 -t layout -A \\\n\t\t-s 1 -r || error \"(8) Fail to start LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'scanning-phase1' status.\"\n\twait_all_targets layout scanning-phase1 9\n\n\techo \"Stop layout LFSCK on all targets by single lctl command.\"\n\tdo_facet mds1 $LCTL lfsck_stop -M ${FSNAME}-MDT0000 -A ||\n\t\terror \"(10) Fail to stop LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'stopped' status.\"\n\twait_all_targets_blocked layout stopped 11\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal STATUS=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$STATUS\" == \"stopped\" ] ||\n\t\t\terror \"(12) OST${k} Expect 'stopped', but got '$STATUS'\"\n\tdone\n\n\techo \"Re-start layout LFSCK on all targets by single command (-s 0).\"\n\tdo_facet mds1 $LCTL lfsck_start -M ${FSNAME}-MDT0000 -t layout -A \\\n\t\t-s 0 -r || error \"(13) Fail to start LFSCK on all devices!\"\n\n\techo \"All the LFSCK targets should be in 'completed' status.\"\n\twait_all_targets_blocked layout completed 14\n\n\tstop_full_debug_logging\n}\nrun_test 12a \"single command to trigger LFSCK on all devices\"\n\ntest_12b() {\n\tcheck_mount_and_prep\n\n\techo \"Start LFSCK without '-M' specified.\"\n\tdo_facet mds1 $LCTL lfsck_start -A -r ||\n\t\terror \"(0) Fail to start LFSCK without '-M'\"\n\n\twait_all_targets_blocked namespace completed 1\n\twait_all_targets_blocked layout completed 2\n\n\tlocal count=$(do_facet mds1 $LCTL dl |\n\t\t      awk '{ print $3 }' | grep mdt | wc -l)\n\tif [ $count -gt 1 ]; then\n\t\techo\n\t\techo \"Start layout LFSCK on the node with multipe targets,\"\n\t\techo \"but not specify '-M'/'-A' option. Should get failure.\"\n\t\techo\n\t\tdo_facet mds1 $LCTL lfsck_start -t layout -r &&\n\t\t\terror \"(3) Start layout LFSCK should fail\" || true\n\tfi\n}\nrun_test 12b \"auto detect Lustre device\"\n\ntest_13() {\n\techo \"#####\"\n\techo \"The lmm_oi in layout EA should be consistent with the MDT-object\"\n\techo \"FID; otherwise, the LFSCK should re-generate the lmm_oi from the\"\n\techo \"MDT-object FID.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub to simulate bad lmm_oi\"\n\t#define OBD_FAIL_LFSCK_BAD_LMMOI\t0x160f\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x160f\n\tcreatemany -o $DIR/$tdir/f 1\n\t$LFS setstripe -E 1M -S 1M -E -1 $DIR/$tdir/f1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f1\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK to find out the bad lmm_oi and fix them\"\n\t$START_LAYOUT -r || error \"(1) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(2) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_others/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(3) Fail to repair crashed lmm_oi: $repaired\"\n}\nrun_test 13 \"LFSCK can repair crashed lmm_oi\"\n\ntest_14a() {\n\techo \"#####\"\n\techo \"The OST-object referenced by the MDT-object should be there;\"\n\techo \"otherwise, the LFSCK should re-create the missing OST-object.\"\n\techo \"without '--delay-create-ostobj' option.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"Inject failure stub to simulate dangling referenced MDT-object\"\n\t#define OBD_FAIL_LFSCK_DANGLING\t0x1610\n\tdo_facet ost1 $LCTL set_param fail_loc=0x1610\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 16)) ||\n\t\terror \"(0.1) Fail to create $DIR/$tdir/fx\"\n\ttouch $DIR/$tdir/guard0\n\n\tfor ((i = 0; i < 16; i++)); do\n\t\t$LFS setstripe -E 512K -S 256K -o 0 -E 2M \\\n\t\t\t$DIR/$tdir/f_comp${i} ||\n\t\t\terror \"(0.2) Fail to create $DIR/$tdir/f_comp${i}\"\n\tdone\n\ttouch $DIR/$tdir/guard1\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tstart_full_debug_logging\n\n\t# exhaust other pre-created dangling cases\n\tcount=$(precreated_ost_obj_count 0 0)\n\tcreatemany -o $DIR/$tdir/a $count ||\n\t\terror \"(0.5) Fail to create $count files.\"\n\n\techo \"'ls' should fail because of dangling referenced MDT-object\"\n\tls -ail $DIR/$tdir > /dev/null 2>&1 && error \"(1) ls should fail.\"\n\n\techo \"Trigger layout LFSCK to find out dangling reference\"\n\t$START_LAYOUT -r || error \"(2) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(3) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_dangling/ { print $2 }')\n\t[ $repaired -ge 32 ] ||\n\t\terror \"(4) Fail to repair dangling reference: $repaired\"\n\n\techo \"'stat' should fail because of not repair dangling by default\"\n\tstat $DIR/$tdir/guard0 > /dev/null 2>&1 &&\n\t\terror \"(5.1) stat should fail\"\n\tstat $DIR/$tdir/guard1 > /dev/null 2>&1 &&\n\t\terror \"(5.2) stat should fail\"\n\n\techo \"Trigger layout LFSCK to repair dangling reference\"\n\t$START_LAYOUT -r -c || error \"(6) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(7) unexpected status\"\n\t}\n\n\t# There may be some async LFSCK updates in processing, wait for\n\t# a while until the target reparation has been done. LU-4970.\n\n\techo \"'stat' should success after layout LFSCK repairing\"\n\twait_update_facet client \"stat $DIR/$tdir/guard0 |\n\t\tawk '/Size/ { print \\\\\\$2 }'\" \"0\" 32 || {\n\t\tstat $DIR/$tdir/guard0\n\t\t$SHOW_LAYOUT\n\t\terror \"(8.1) unexpected size\"\n\t}\n\n\twait_update_facet client \"stat $DIR/$tdir/guard1 |\n\t\tawk '/Size/ { print \\\\\\$2 }'\" \"0\" 32 || {\n\t\tstat $DIR/$tdir/guard1\n\t\t$SHOW_LAYOUT\n\t\terror \"(8.2) unexpected size\"\n\t}\n\n\trepaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_dangling/ { print $2 }')\n\t[ $repaired -ge 32 ] ||\n\t\terror \"(9) Fail to repair dangling reference: $repaired\"\n\n\tstop_full_debug_logging\n\n\techo \"stopall to cleanup object cache\"\n\tstopall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n}\nrun_test 14a \"LFSCK can repair MDT-object with dangling LOV EA reference (1)\"\n\ntest_14b() {\n\techo \"#####\"\n\techo \"The OST-object referenced by the MDT-object should be there;\"\n\techo \"otherwise, the LFSCK should re-create the missing OST-object.\"\n\techo \"with '--delay-create-ostobj' option.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"Inject failure stub to simulate dangling referenced MDT-object\"\n\t#define OBD_FAIL_LFSCK_DANGLING\t0x1610\n\tdo_facet ost1 $LCTL set_param fail_loc=0x1610\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 31))\n\ttouch $DIR/$tdir/guard\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tstart_full_debug_logging\n\n\t# exhaust other pre-created dangling cases\n\tcount=$(precreated_ost_obj_count 0 0)\n\tcreatemany -o $DIR/$tdir/a $count ||\n\t\terror \"(0) Fail to create $count files.\"\n\n\techo \"'ls' should fail because of dangling referenced MDT-object\"\n\tls -ail $DIR/$tdir > /dev/null 2>&1 && error \"(1) ls should fail.\"\n\n\techo \"Trigger layout LFSCK to find out dangling reference\"\n\t$START_LAYOUT -r -o -d || error \"(2) Fail to start LFSCK for layout!\"\n\n\twait_all_targets_blocked layout completed 3\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_dangling/ { print $2 }')\n\t[ $repaired -ge 32 ] ||\n\t\terror \"(4) Fail to repair dangling reference: $repaired\"\n\n\techo \"'stat' should fail because of not repair dangling by default\"\n\tstat $DIR/$tdir/guard > /dev/null 2>&1 && error \"(5) stat should fail\"\n\n\techo \"Trigger layout LFSCK to repair dangling reference\"\n\t$START_LAYOUT -r -o -c -d || error \"(6) Fail to start LFSCK for layout!\"\n\n\twait_all_targets_blocked layout completed 7\n\n\t# There may be some async LFSCK updates in processing, wait for\n\t# a while until the target reparation has been done. LU-4970.\n\n\techo \"'stat' should success after layout LFSCK repairing\"\n\twait_update_facet client \"stat $DIR/$tdir/guard |\n\t\tawk '/Size/ { print \\\\\\$2 }'\" \"0\" 32 || {\n\t\tstat $DIR/$tdir/guard\n\t\t$SHOW_LAYOUT\n\t\terror \"(8) unexpected size\"\n\t}\n\n\trepaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_dangling/ { print $2 }')\n\t[ $repaired -ge 32 ] ||\n\t\terror \"(9) Fail to repair dangling reference: $repaired\"\n\n\tstop_full_debug_logging\n\n\techo \"stopall to cleanup object cache\"\n\tstopall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n}\nrun_test 14b \"LFSCK can repair MDT-object with dangling LOV EA reference (2)\"\n\ntest_15a() {\n\techo \"#####\"\n\techo \"If the OST-object referenced by the MDT-object back points\"\n\techo \"to some non-exist MDT-object, then the LFSCK should repair\"\n\techo \"the OST-object to back point to the right MDT-object.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"Inject failure stub to make the OST-object to back point to\"\n\techo \"non-exist MDT-object.\"\n\t#define OBD_FAIL_LFSCK_UNMATCHED_PAIR1\t0x1611\n\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1611\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=1\n\t$LFS setstripe -E 1M -S 256K -c 1 -E -1 -S 512K -c $OSTCOUNT \\\n\t\t$DIR/$tdir/f1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f1\"\n\t# 'dd' will trigger punch RPC firstly on every OST-objects.\n\t# So even though some OST-object will not be write by 'dd',\n\t# as long as it is allocated (may be NOT allocated in pfl_3b)\n\t# its layout information will be set also.\n\tdd if=/dev/zero of=$DIR/$tdir/f1 bs=4K count=257\n\tcancel_lru_locks osc\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK to find out unmatched pairs and fix them\"\n\t$START_LAYOUT -r || error \"(1) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(2) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_unmatched_pair/ { print $2 }')\n\t[ $repaired -ge 3 ] ||\n\t\terror \"(3) Fail to repair unmatched pair: $repaired\"\n}\nrun_test 15a \"LFSCK can repair unmatched MDT-object/OST-object pairs (1)\"\n\ntest_15b() {\n\techo \"#####\"\n\techo \"If the OST-object referenced by the MDT-object back points\"\n\techo \"to other MDT-object that doesn't recognize the OST-object,\"\n\techo \"then the LFSCK should repair it to back point to the right\"\n\techo \"MDT-object (the first one).\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\tmkdir -p $DIR/$tdir/0\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/0\n\tdd if=/dev/zero of=$DIR/$tdir/0/guard bs=1M count=1\n\tcancel_lru_locks osc\n\n\techo \"Inject failure stub to make the OST-object to back point to\"\n\techo \"other MDT-object\"\n\n\tlocal stripes=1\n\t[ $OSTCOUNT -ge 2 ] && stripes=2\n\n\t#define OBD_FAIL_LFSCK_UNMATCHED_PAIR2\t0x1612\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1612\n\tdd if=/dev/zero of=$DIR/$tdir/0/f0 bs=1M count=1\n\t$LFS setstripe -E 1M -S 256K -c $stripes -E 2M -S 512K -c 1 \\\n\t\t$DIR/$tdir/f1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f1\"\n\tdd if=/dev/zero of=$DIR/$tdir/f1 bs=1M count=2\n\tcancel_lru_locks osc\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK to find out unmatched pairs and fix them\"\n\t$START_LAYOUT -r || error \"(1) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(2) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_unmatched_pair/ { print $2 }')\n\t[ $repaired -eq 4 ] ||\n\t\terror \"(3) Fail to repair unmatched pair: $repaired\"\n}\nrun_test 15b \"LFSCK can repair unmatched MDT-object/OST-object pairs (2)\"\n\ntest_15c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\t[ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.7.55) ] &&\n\t\tskip \"Skip the test after 2.7.55 see LU-6437\" && return\n\n\techo \"#####\"\n\techo \"According to current metadata migration implementation,\"\n\techo \"before the old MDT-object is removed, both the new MDT-object\"\n\techo \"and old MDT-object will reference the same LOV layout. Then if\"\n\techo \"the layout LFSCK finds the new MDT-object by race, it will\"\n\techo \"regard related OST-object(s) as multiple referenced case, and\"\n\techo \"will try to create new OST-object(s) for the new MDT-object.\"\n\techo \"To avoid such trouble, the layout LFSCK needs to lock the old\"\n\techo \"MDT-object before confirm the multiple referenced case.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 1 $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=1\n\tcancel_lru_locks osc\n\n\techo \"Inject failure stub on MDT1 to delay the migration\"\n\n\t#define OBD_FAIL_MIGRATE_DELAY\t\t\t0x1803\n\tdo_facet mds2 $LCTL set_param fail_val=5 fail_loc=0x1803\n\techo \"Migrate $DIR/$tdir/a1 from MDT1 to MDT0 with delay\"\n\t$LFS migrate -m 0 $DIR/$tdir/a1 &\n\n\tsleep 1\n\techo \"Trigger layout LFSCK to race with the migration\"\n\t$START_LAYOUT -A -r || error \"(1) Fail to start layout LFSCK!\"\n\n\twait_all_targets_blocked layout completed 2\n\n\tdo_facet mds2 $LCTL set_param fail_loc=0 fail_val=0\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_unmatched_pair/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(3) Fail to repair unmatched pair: $repaired\"\n\n\trepaired=$($SHOW_LAYOUT |\n\t\t   awk '/^repaired_multiple_referenced/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(4) Unexpectedly repaird multiple references: $repaired\"\n}\nrun_test 15c \"LFSCK can repair unmatched MDT-object/OST-object pairs (3)\"\n\ntest_16() {\n\techo \"#####\"\n\techo \"If the OST-object's owner information does not match the owner\"\n\techo \"information stored in the MDT-object, then the LFSCK trust the\"\n\techo \"MDT-object and update the OST-object's owner information.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=1\n\tcancel_lru_locks osc\n\n\t# created but no setattr or write to the file.\n\tmkdir $DIR/$tdir/d1\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/d1\n\t$RUNAS createmany -o $DIR/$tdir/d1/o 100 || error \"create failed\"\n\n\techo \"Inject failure stub to skip OST-object owner changing\"\n\t#define OBD_FAIL_LFSCK_BAD_OWNER\t0x1613\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1613\n\tchown 1.1 $DIR/$tdir/f0\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK to find out inconsistent OST-object owner\"\n\techo \"and fix them\"\n\n\t$START_LAYOUT -r || error \"(1) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(2) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_inconsistent_owner/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(3) Fail to repair inconsistent owner: $repaired\"\n}\nrun_test 16 \"LFSCK can repair inconsistent MDT-object/OST-object owner\"\n\ntest_17() {\n\techo \"#####\"\n\techo \"If more than one MDT-objects reference the same OST-object,\"\n\techo \"and the OST-object only recognizes one MDT-object, then the\"\n\techo \"LFSCK should create new OST-objects for such non-recognized\"\n\techo \"MDT-objects.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"Inject failure stub to make two MDT-objects to refernce\"\n\techo \"the OST-object\"\n\n\t#define OBD_FAIL_LFSCK_MULTIPLE_REF\t0x1614\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0 fail_loc=0x1614\n\tdd if=/dev/zero of=$DIR/$tdir/guard bs=1M count=1\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\tcreatemany -o $DIR/$tdir/f 1\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t$LFS setstripe -E 2M -S 256K -o 0 -E 4M -S 512K -o 0 \\\n\t\t$DIR/$tdir/f1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f1\"\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"$DIR/$tdir/f0 and $DIR/$tdir/guard use the same OST-objects\"\n\techo \"$DIR/$tdir/f1 and $DIR/$tdir/guard use the same OST-objects\"\n\tlocal size=$(ls -l $DIR/$tdir/f0 | awk '{ print $5 }')\n\t[ $size -eq 1048576 ] ||\n\t\terror \"(1.1) f0 (wrong) size should be 1048576, but got $size\"\n\n\tsize=$(ls -l $DIR/$tdir/f1 | awk '{ print $5 }')\n\t[ $size -eq 1048576 ] ||\n\t\terror \"(1.2) f1 (wrong) size should be 1048576, but got $size\"\n\n\techo \"Trigger layout LFSCK to find out multiple refenced MDT-objects\"\n\techo \"and fix them\"\n\n\t$START_LAYOUT -r || error \"(2) Fail to start LFSCK for layout!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(3) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_multiple_referenced/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(4) Fail to repair multiple references: $repaired\"\n\n\techo \"$DIR/$tdir/f0 and $DIR/$tdir/guard should use diff OST-objects\"\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=2 ||\n\t\terror \"(5) Fail to write f0.\"\n\tsize=$(ls -l $DIR/$tdir/guard | awk '{ print $5 }')\n\t[ $size -eq 1048576 ] ||\n\t\terror \"(6) guard size should be 1048576, but got $size\"\n\n\techo \"$DIR/$tdir/f1 and $DIR/$tdir/guard should use diff OST-objects\"\n\tdd if=/dev/zero of=$DIR/$tdir/f1 bs=1M count=2 ||\n\t\terror \"(7) Fail to write f1.\"\n\tsize=$(ls -l $DIR/$tdir/guard | awk '{ print $5 }')\n\t[ $size -eq 1048576 ] ||\n\t\terror \"(8) guard size should be 1048576, but got $size\"\n}\nrun_test 17 \"LFSCK can repair multiple references\"\n\n$LCTL set_param debug=+cache > /dev/null\n\ntest_18a() {\n\techo \"#####\"\n\techo \"The target MDT-object is there, but related stripe information\"\n\techo \"is lost or partly lost. The LFSCK should regenerate the missing\"\n\techo \"layout EA entries.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=2\n\n\tlocal saved_size1=$(ls -il $DIR/$tdir/a1/f1 | awk '{ print $6 }')\n\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS mkdir -i 1 $DIR/$tdir/a2\n\t\t$LFS setstripe -c 2 -i 1 -S 1M $DIR/$tdir/a2\n\t\tdd if=/dev/zero of=$DIR/$tdir/a2/f2 bs=1M count=2\n\t\t$LFS path2fid $DIR/$tdir/a2/f2\n\t\t$LFS getstripe $DIR/$tdir/a2/f2\n\tfi\n\n\t$LFS setstripe -E 1M -S 1M -o 0 -E -1 -S 1M $DIR/$tdir/f3 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f3\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/f3 bs=1M count=2\n\n\tlocal saved_size2=$(ls -il $DIR/$tdir/f3 | awk '{ print $6 }')\n\n\t$LFS path2fid $DIR/$tdir/f3\n\t$LFS getstripe $DIR/$tdir/f3\n\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, to make the MDT-object lost its layout EA\"\n\t#define OBD_FAIL_LFSCK_LOST_STRIPE 0x1615\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1615\n\tchown 1.1 $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0x1615\n\t\tchown 1.1 $DIR/$tdir/a2/f2\n\tfi\n\n\tchown 1.1 $DIR/$tdir/f3\n\n\tsync\n\tsleep 2\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0\n\tfi\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"The file size should be incorrect since layout EA is lost\"\n\tlocal cur_size=$(ls -il $DIR/$tdir/a1/f1 | awk '{ print $6 }')\n\t[ \"$cur_size\" != \"$saved_size1\" ] ||\n\t\terror \"(1) Expect incorrect file1 size\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tcur_size=$(ls -il $DIR/$tdir/a2/f2 | awk '{ print $6 }')\n\t\t[ \"$cur_size\" != \"$saved_size1\" ] ||\n\t\t\terror \"(2) Expect incorrect file2 size\"\n\tfi\n\n\tcur_size=$(ls -il $DIR/$tdir/f3 | awk '{ print $6 }')\n\t[ \"$cur_size\" != \"$saved_size2\" ] ||\n\t\terror \"(1.2) Expect incorrect file3 size\"\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(3) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(4) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(5) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 3 ] ||\n\terror \"(6.1) Expect 3 fixed on mds1, but got: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_layout |\n\t\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t\t[ $repaired -eq 2 ] ||\n\t\terror \"(6.2) Expect 2 fixed on mds2, but got: $repaired\"\n\tfi\n\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS path2fid $DIR/$tdir/a2/f2\n\t\t$LFS getstripe $DIR/$tdir/a2/f2\n\tfi\n\n\t$LFS path2fid $DIR/$tdir/f3\n\t$LFS getstripe $DIR/$tdir/f3\n\n\techo \"The file size should be correct after layout LFSCK scanning\"\n\tcur_size=$(ls -il $DIR/$tdir/a1/f1 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size1\" ] ||\n\t\terror \"(7) Expect file1 size $saved_size1, but got $cur_size\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tcur_size=$(ls -il $DIR/$tdir/a2/f2 | awk '{ print $6 }')\n\t\t[ \"$cur_size\" == \"$saved_size1\" ] ||\n\t\terror \"(8) Expect file2 size $saved_size1, but got $cur_size\"\n\tfi\n\n\tcur_size=$(ls -il $DIR/$tdir/f3 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size2\" ] ||\n\t\terror \"(9) Expect file1 size $saved_size2, but got $cur_size\"\n}\nrun_test 18a \"Find out orphan OST-object and repair it (1)\"\n\ntest_18b() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object is lost. The LFSCK should re-create the\"\n\techo \"MDT-object under .lustre/lost+found/MDTxxxx. The admin should\"\n\techo \"can move it back to normal namespace manually.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=2\n\tlocal saved_size1=$(ls -il $DIR/$tdir/a1/f1 | awk '{ print $6 }')\n\tlocal fid1=$($LFS path2fid $DIR/$tdir/a1/f1)\n\techo ${fid1}\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS mkdir -i 1 $DIR/$tdir/a2\n\t\t$LFS setstripe -c 2 -i 1 -S 1M $DIR/$tdir/a2\n\t\tdd if=/dev/zero of=$DIR/$tdir/a2/f2 bs=1M count=2\n\t\tfid2=$($LFS path2fid $DIR/$tdir/a2/f2)\n\t\techo ${fid2}\n\t\t$LFS getstripe $DIR/$tdir/a2/f2\n\tfi\n\n\t$LFS setstripe -E 1M -S 1M -o 0 -E -1 -S 1M $DIR/$tdir/f3 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f3\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/f3 bs=1M count=2\n\n\tlocal saved_size2=$(ls -il $DIR/$tdir/f3 | awk '{ print $6 }')\n\tlocal fid3=$($LFS path2fid $DIR/$tdir/f3)\n\techo ${fid3}\n\t$LFS getstripe $DIR/$tdir/f3\n\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, to simulate the case of missing the MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0x1616\n\t\trm -f $DIR/$tdir/a2/f2\n\tfi\n\n\trm -f $DIR/$tdir/f3\n\n\tsync\n\tsleep 2\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0\n\tfi\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t# dryrun mode only check orphans, not repaie\n\techo \"Trigger layout LFSCK --dryrun to find out orphan OST-object\"\n\t$START_LAYOUT --dryrun -o -r ||\n\t\terror \"Fail to start layout LFSCK in dryrun mode\"\n\twait_all_targets_blocked layout completed 2\n\n\tlocal PARAMS=$($SHOW_LAYOUT | awk '/^param/ { print $2 }')\n\t[ \"$PARAMS\" == \"dryrun,all_targets,orphan\" ] ||\n\t\terror \"Expect 'dryrun,all_targets,orphan', got '$PARAMS'\"\n\n\tlocal orphans=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds1).lfsck_layout |\n\t\t\tawk '/^inconsistent_orphan/ { print $2 }')\n\t[ $orphans -eq 3 ] ||\n\t\terror \"Expect 3 found on mds1, but got: $orphans\"\n\n\t# orphan parents should not be created\n\tlocal subdir\n\tfor subdir in $MOUNT/.lustre/lost+found/*; do\n\t\t[ ! \"$(ls -A $subdir)\" ] || error \"$subdir not empty\"\n\tdone\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(1) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(2) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(3) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 3 ] ||\n\terror \"(4.1) Expect 3 fixed on mds1, but got: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t\t[ $repaired -eq 2 ] ||\n\t\terror \"(4.2) Expect 2 fixed on mds2, but got: $repaired\"\n\tfi\n\n\techo \"Move the files from ./lustre/lost+found/MDTxxxx to namespace\"\n\tmv $MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0 $DIR/$tdir/a1/f1 ||\n\terror \"(5) Fail to move $MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tlocal name=$MOUNT/.lustre/lost+found/MDT0001/${fid2}-R-0\n\t\tmv $name $DIR/$tdir/a2/f2 || error \"(6) Fail to move $name\"\n\tfi\n\n\tmv $MOUNT/.lustre/lost+found/MDT0000/${fid3}-R-0 $DIR/$tdir/f3 ||\n\terror \"(5) Fail to move $MOUNT/.lustre/lost+found/MDT0000/${fid3}-R-0\"\n\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS path2fid $DIR/$tdir/a2/f2\n\t\t$LFS getstripe $DIR/$tdir/a2/f2\n\tfi\n\n\t$LFS path2fid $DIR/$tdir/f3\n\t$LFS getstripe $DIR/$tdir/f3\n\n\techo \"The file size should be correct after layout LFSCK scanning\"\n\tlocal cur_size=$(ls -il $DIR/$tdir/a1/f1 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size1\" ] ||\n\t\terror \"(7) Expect file1 size $saved_size1, but got $cur_size\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tcur_size=$(ls -il $DIR/$tdir/a2/f2 | awk '{ print $6 }')\n\t\t[ \"$cur_size\" == \"$saved_size1\" ] ||\n\t\terror \"(8) Expect file2 size $saved_size1, but got $cur_size\"\n\tfi\n\n\tcur_size=$(ls -il $DIR/$tdir/f3 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size2\" ] ||\n\t\terror \"(9) Expect file1 size $saved_size2, but got $cur_size\"\n}\nrun_test 18b \"Find out orphan OST-object and repair it (2)\"\n\ntest_18c() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object is lost, and the OST-object FID is missing.\"\n\techo \"The LFSCK should re-create the MDT-object with new FID under the \"\n\techo \"directory .lustre/lost+found/MDTxxxx.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\n\techo \"Inject failure, to simulate the case of missing parent FID\"\n\t#define OBD_FAIL_LFSCK_NOPFID\t\t0x1617\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1617\n\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=2\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS mkdir -i 1 $DIR/$tdir/a2\n\t\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a2\n\t\tdd if=/dev/zero of=$DIR/$tdir/a2/f2 bs=1M count=2\n\t\t$LFS getstripe $DIR/$tdir/a2/f2\n\tfi\n\n\t$LFS setstripe -E 1M -S 1M -o 0 -E -1 -S 1M $DIR/$tdir/f3 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f3\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/f3 bs=1M count=2\n\t$LFS getstripe $DIR/$tdir/f3\n\n\tcancel_lru_locks osc\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\n\techo \"Inject failure, to simulate the case of missing the MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/a1/f1\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0x1616\n\t\trm -f $DIR/$tdir/a2/f2\n\tfi\n\n\trm -f $DIR/$tdir/f3\n\n\tsync\n\tsleep 2\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0\n\tfi\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(1) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(2) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(3) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\texpected=4\n\telse\n\t\texpected=3\n\tfi\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq $expected ] ||\n\t\terror \"(4) Expect $expected fixed on mds1, but got: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t   mdd.$(facet_svc mds2).lfsck_layout |\n\t\t\t   awk '/^repaired_orphan/ { print $2 }')\n\t\t[ $repaired -eq 0 ] ||\n\t\t\terror \"(5) Expect 0 fixed on mds2, but got: $repaired\"\n\tfi\n\n\tls -ail $MOUNT/.lustre/lost+found/\n\n\techo \"There should NOT be some stub under .lustre/lost+found/MDT0001/\"\n\tif [ -d $MOUNT/.lustre/lost+found/MDT0001 ]; then\n\t\tcname=$(find $MOUNT/.lustre/lost+found/MDT0001/ -name *-N-*)\n\t\t[ -z \"$cname\" ] ||\n\t\t\terror \"(6) .lustre/lost+found/MDT0001/ should be empty\"\n\tfi\n\n\techo \"There should be some stub under .lustre/lost+found/MDT0000/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0000 ] ||\n\t\terror \"(7) $MOUNT/.lustre/lost+found/MDT0000/ should be there\"\n\n\tcname=$(find $MOUNT/.lustre/lost+found/MDT0000/ -name *-N-*)\n\t[ ! -z \"$cname\" ] ||\n\t\terror \"(8) .lustre/lost+found/MDT0000/ should not be empty\"\n}\nrun_test 18c \"Find out orphan OST-object and repair it (3)\"\n\ntest_18d() {\n\techo \"#####\"\n\techo \"The target MDT-object layout EA is corrupted, but the right\"\n\techo \"OST-object is still alive as orphan. The layout LFSCK will\"\n\techo \"not create new OST-object to occupy such slot.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\tmkdir $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\techo \"guard\" > $DIR/$tdir/a1/f1\n\techo \"foo\" > $DIR/$tdir/a1/f2\n\n\techo \"guard\" > $DIR/$tdir/a1/f3\n\t$LFS setstripe -E 1M -S 1M -o 0 -E -1 -S 1M $DIR/$tdir/a1/f4 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/a1/f4\"\n\techo \"foo\" > $DIR/$tdir/a1/f4\n\n\tlocal saved_size1=$(ls -il $DIR/$tdir/a1/f2 | awk '{ print $6 }')\n\tlocal saved_size2=$(ls -il $DIR/$tdir/a1/f4 | awk '{ print $6 }')\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\t$LFS path2fid $DIR/$tdir/a1/f2\n\t$LFS getstripe $DIR/$tdir/a1/f2\n\t$LFS path2fid $DIR/$tdir/a1/f3\n\t$LFS getstripe $DIR/$tdir/a1/f3\n\t$LFS path2fid $DIR/$tdir/a1/f4\n\t$LFS getstripe $DIR/$tdir/a1/f4\n\tcancel_lru_locks osc\n\n\techo \"Inject failure to make $DIR/$tdir/a1/f1 and $DIR/$tdir/a1/f2\"\n\techo \"to reference the same OST-object (which is f1's OST-obejct).\"\n\techo \"Then drop $DIR/$tdir/a1/f1 and its OST-object, so f2 becomes\"\n\techo \"dangling reference case, but f2's old OST-object is there.\"\n\n\techo \"The failure also makes $DIR/$tdir/a1/f3 and $DIR/$tdir/a1/f4\"\n\techo \"to reference the same OST-object (which is f3's OST-obejct).\"\n\techo \"Then drop $DIR/$tdir/a1/f3 and its OST-object, so f4 becomes\"\n\techo \"dangling reference case, but f4's old OST-object is there.\"\n\techo\n\n\t#define OBD_FAIL_LFSCK_CHANGE_STRIPE\t0x1618\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1618\n\tchown 1.1 $DIR/$tdir/a1/f2\n\tchown 1.1 $DIR/$tdir/a1/f4\n\trm -f $DIR/$tdir/a1/f1\n\trm -f $DIR/$tdir/a1/f3\n\tsync\n\tsleep 2\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"stopall to cleanup object cache\"\n\tstopall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o -c -d || error \"(2) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(3) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(4) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc $SINGLEMDS).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(5) Expect 2 orphans have been fixed, but got: $repaired\"\n\n\trepaired=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t   mdd.$(facet_svc $SINGLEMDS).lfsck_layout |\n\t\t   awk '/^repaired_dangling/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(6) Expect 0 dangling has been fixed, but got: $repaired\"\n\n\techo \"The file size should be correct after layout LFSCK scanning\"\n\tlocal cur_size=$(ls -il $DIR/$tdir/a1/f2 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size1\" ] ||\n\t\terror \"(7) Expect file2 size $saved_size1, but got $cur_size\"\n\n\tcur_size=$(ls -il $DIR/$tdir/a1/f4 | awk '{ print $6 }')\n\t[ \"$cur_size\" == \"$saved_size2\" ] ||\n\t\terror \"(8) Expect file4 size $saved_size2, but got $cur_size\"\n\n\techo \"The LFSCK should find back the original data.\"\n\tcat $DIR/$tdir/a1/f2\n\t$LFS path2fid $DIR/$tdir/a1/f2\n\t$LFS getstripe $DIR/$tdir/a1/f2\n\tcat $DIR/$tdir/a1/f4\n\t$LFS path2fid $DIR/$tdir/a1/f4\n\t$LFS getstripe $DIR/$tdir/a1/f4\n}\nrun_test 18d \"Find out orphan OST-object and repair it (4)\"\n\ntest_18e() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object layout EA slot is occpuied by some new\"\n\techo \"created OST-object when repair dangling reference case. Such\"\n\techo \"conflict OST-object has been modified by others. To keep the\"\n\techo \"new data, the LFSCK will create a new file to refernece this\"\n\techo \"old orphan OST-object.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\tmkdir $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\techo \"guard\" > $DIR/$tdir/a1/f1\n\techo \"foo\" > $DIR/$tdir/a1/f2\n\n\techo \"guard\" > $DIR/$tdir/a1/f3\n\t$LFS setstripe -E 1M -S 1M -o 0 -E -1 -S 1M $DIR/$tdir/a1/f4 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/a1/f4\"\n\techo \"foo\" > $DIR/$tdir/a1/f4\n\n\tlocal saved_size1=$(ls -il $DIR/$tdir/a1/f2 | awk '{ print $6 }')\n\tlocal saved_size2=$(ls -il $DIR/$tdir/a1/f4 | awk '{ print $6 }')\n\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\t$LFS path2fid $DIR/$tdir/a1/f2\n\t$LFS getstripe $DIR/$tdir/a1/f2\n\t$LFS path2fid $DIR/$tdir/a1/f3\n\t$LFS getstripe $DIR/$tdir/a1/f3\n\t$LFS path2fid $DIR/$tdir/a1/f4\n\t$LFS getstripe $DIR/$tdir/a1/f4\n\tcancel_lru_locks osc\n\n\techo \"Inject failure to make $DIR/$tdir/a1/f1 and $DIR/$tdir/a1/f2\"\n\techo \"to reference the same OST-object (which is f1's OST-obejct).\"\n\techo \"Then drop $DIR/$tdir/a1/f1 and its OST-object, so f2 becomes\"\n\techo \"dangling reference case, but f2's old OST-object is there.\"\n\n\techo \"Also the failure makes $DIR/$tdir/a1/f3 and $DIR/$tdir/a1/f4\"\n\techo \"to reference the same OST-object (which is f3's OST-obejct).\"\n\techo \"Then drop $DIR/$tdir/a1/f3 and its OST-object, so f4 becomes\"\n\techo \"dangling reference case, but f4's old OST-object is there.\"\n\techo\n\n\t#define OBD_FAIL_LFSCK_CHANGE_STRIPE\t0x1618\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1618\n\tchown 1.1 $DIR/$tdir/a1/f2\n\tchown 1.1 $DIR/$tdir/a1/f4\n\trm -f $DIR/$tdir/a1/f1\n\trm -f $DIR/$tdir/a1/f3\n\tsync\n\tsleep 2\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"stopall to cleanup object cache\"\n\tstopall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n\n\t#define OBD_FAIL_LFSCK_DELAY3\t\t0x1602\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=10 fail_loc=0x1602\n\n\tstart_full_debug_logging\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o -c || error \"(2) Fail to start LFSCK for layout!\"\n\n\twait_update_facet mds1 \"$LCTL get_param -n \\\n\t\tmdd.$(facet_svc mds1).lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"scanning-phase2\" $LTIME ||\n\t\terror \"(3) MDS1 is not the expected 'scanning-phase2'\"\n\n\t# to guarantee all updates are synced.\n\tsync\n\tsleep 2\n\n\techo \"Write new data to f2/f4 to modify the new created OST-object.\"\n\techo \"dummy\" >> $DIR/$tdir/a1/f2 || error \"write a1/f2 failed\"\n\techo \"dummy\" >> $DIR/$tdir/a1/f4 || error \"write a1/f4 failed\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0 fail_loc=0\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(4) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(5) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tstop_full_debug_logging\n\n\tlocal repaired=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc $SINGLEMDS).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(6) Expect 2 orphans have been fixed, but got: $repaired\"\n\n\techo \"There should be stub file under .lustre/lost+found/MDT0000/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0000 ] ||\n\t\terror \"(7) $MOUNT/.lustre/lost+found/MDT0000/ should be there\"\n\n\tlocal count=$(ls -l $MOUNT/.lustre/lost+found/MDT0000/*-C-* | wc -l)\n\tif [ $count -ne 2 ]; then\n\t\tls -l $MOUNT/.lustre/lost+found/MDT0000/*-C-*\n\t\terror \"(8) Expect 2 stubs under lost+found, but got $count\"\n\tfi\n\n\techo \"The stub file should keep the original f2 or f4 data\"\n\tcname=$(find $MOUNT/.lustre/lost+found/MDT0000/ -name *-C-* | head -n 1)\n\tlocal cur_size=$(ls -il $cname | awk '{ print $6 }')\n\t[ \"$cur_size\" != \"$saved_size1\" -a \"$cur_size\" != \"$saved_size2\" ] &&\n\t\terror \"(9) Got unexpected $cur_size\"\n\n\tcat $cname\n\t$LFS path2fid $cname\n\t$LFS getstripe $cname\n\n\tcname=$(find $MOUNT/.lustre/lost+found/MDT0000/ -name *-C-* | tail -n 1)\n\tcur_size=$(ls -il $cname | awk '{ print $6 }')\n\t[ \"$cur_size\" != \"$saved_size1\" -a \"$cur_size\" != \"$saved_size2\" ] &&\n\t\terror \"(10) Got unexpected $cur_size\"\n\n\tcat $cname\n\t$LFS path2fid $cname\n\t$LFS getstripe $cname\n\n\techo \"The f2/f4 should contains new data.\"\n\tcat $DIR/$tdir/a1/f2\n\t$LFS path2fid $DIR/$tdir/a1/f2\n\t$LFS getstripe $DIR/$tdir/a1/f2\n\tcat $DIR/$tdir/a1/f4\n\t$LFS path2fid $DIR/$tdir/a1/f4\n\t$LFS getstripe $DIR/$tdir/a1/f4\n}\nrun_test 18e \"Find out orphan OST-object and repair it (5)\"\n\ntest_18f() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return\n\n\techo \"#####\"\n\techo \"The target MDT-object is lost. The LFSCK should re-create the\"\n\techo \"MDT-object under .lustre/lost+found/MDTxxxx. If some OST fail\"\n\techo \"to verify some OST-object(s) during the first stage-scanning,\"\n\techo \"the LFSCK should skip orphan OST-objects for such OST. Others\"\n\techo \"should not be affected.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a1\n\tdd if=/dev/zero of=$DIR/$tdir/a1/guard bs=1M count=2\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=2\n\t$LFS mkdir -i 0 $DIR/$tdir/a2\n\t$LFS setstripe -c 2 -i 0 -S 1M $DIR/$tdir/a2\n\tdd if=/dev/zero of=$DIR/$tdir/a2/f2 bs=1M count=2\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a2/f2\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS mkdir -i 1 $DIR/$tdir/a3\n\t\t$LFS setstripe -c 1 -i 0 $DIR/$tdir/a3\n\t\tdd if=/dev/zero of=$DIR/$tdir/a3/guard bs=1M count=2\n\t\tdd if=/dev/zero of=$DIR/$tdir/a3/f3 bs=1M count=2\n\t\t$LFS mkdir -i 1 $DIR/$tdir/a4\n\t\t$LFS setstripe -c 2 -i 0 -S 1M $DIR/$tdir/a4\n\t\tdd if=/dev/zero of=$DIR/$tdir/a4/f4 bs=1M count=2\n\t\t$LFS getstripe $DIR/$tdir/a3/f3\n\t\t$LFS getstripe $DIR/$tdir/a4/f4\n\tfi\n\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, to simulate the case of missing the MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/a1/f1\n\trm -f $DIR/$tdir/a2/f2\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0x1616\n\t\trm -f $DIR/$tdir/a3/f3\n\t\trm -f $DIR/$tdir/a4/f4\n\tfi\n\n\tsync\n\tsleep 2\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tdo_facet mds2 $LCTL set_param fail_loc=0\n\tfi\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, to simulate the OST0 fail to handle\"\n\techo \"MDT0 LFSCK request during the first-stage scanning.\"\n\t#define OBD_FAIL_LFSCK_BAD_NETWORK\t0x161c\n\tdo_facet mds1 $LCTL set_param fail_loc=0x161c fail_val=0\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(1) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"partial\" $LTIME ||\n\t\t\terror \"(2) MDS${k} is not the expected 'partial'\"\n\tdone\n\n\twait_update_facet ost1 \"$LCTL get_param -n \\\n\t\tobdfilter.$(facet_svc ost1).lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"partial\" $LTIME || {\n\t\terror \"(3) OST1 is not the expected 'partial'\"\n\t}\n\n\twait_update_facet ost2 \"$LCTL get_param -n \\\n\t\tobdfilter.$(facet_svc ost2).lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME || {\n\t\terror \"(4) OST2 is not the expected 'completed'\"\n\t}\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0 fail_val=0\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(5) Expect 1 fixed on mds{1}, but got: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t\t[ $repaired -eq 1 ] ||\n\t\terror \"(6) Expect 1 fixed on mds{2}, but got: $repaired\"\n\tfi\n\n\techo \"Trigger layout LFSCK on all devices again to cleanup\"\n\t$START_LAYOUT -r -o || error \"(7) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(8) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tcur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t     obdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t     awk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(9) OST${k} Expect 'completed', but got '$cur_status'\"\n\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(10) Expect 2 fixed on mds{1}, but got: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t\t[ $repaired -eq 2 ] ||\n\t\terror \"(11) Expect 2 fixed on mds{2}, but got: $repaired\"\n\tfi\n}\nrun_test 18f \"Skip the failed OST(s) when handle orphan OST-objects\"\n\ntest_18g() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object is lost, but related OI mapping is there\"\n\techo \"The LFSCK should recreate the lost MDT-object without affected\"\n\techo \"by the stale OI mapping.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\t$LFS setstripe -c -1 -i 0 -S 1M $DIR/$tdir/a1\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=1M count=$OSTCOUNT\n\tlocal fid1=$($LFS path2fid $DIR/$tdir/a1/f1)\n\techo ${fid1}\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\tcancel_lru_locks osc\n\n\techo \"Inject failure to simulate lost MDT-object but keep OI mapping\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ2\t0x162e\n\tdo_facet mds1 $LCTL set_param fail_loc=0x162e\n\trm -f $DIR/$tdir/a1/f1\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(1) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(2) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(3) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq $OSTCOUNT ] ||\n\t\terror \"(4) Expect $OSTCOUNT fixed, but got: $repaired\"\n\n\techo \"Move the files from ./lustre/lost+found/MDTxxxx to namespace\"\n\tmv $MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0 $DIR/$tdir/a1/f1 ||\n\terror \"(5) Fail to move $MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0\"\n\n\t$LFS path2fid $DIR/$tdir/a1/f1\n\t$LFS getstripe $DIR/$tdir/a1/f1\n}\nrun_test 18g \"Find out orphan OST-object and repair it (7)\"\n\ntest_18h() {\n\techo \"#####\"\n\techo \"The PFL extent crashed. During the first cycle LFSCK scanning,\"\n\techo \"the layout LFSCK will keep the bad PFL file(s) there without\"\n\techo \"scanning its OST-object(s). Then in the second stage scanning,\"\n\techo \"the OST will return related OST-object(s) to the MDT as orphan.\"\n\techo \"And then the LFSCK on the MDT can rebuild the PFL extent with\"\n\techo \"the 'orphan(s)' stripe information.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setstripe -E 2M -S 1M -c 1 -E -1 $DIR/$tdir/f0 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f0\"\n\n\tcat $LUSTRE/tests/test-framework.sh > $DIR/$tdir/f0 ||\n\t\terror \"(1.1) Fail to write $DIR/$tdir/f0\"\n\n\tdd if=$LUSTRE/tests/test-framework.sh of=$DIR/$tdir/f0 bs=1M seek=2 ||\n\t\terror \"(1.2) Fail to write $DIR/$tdir/f0\"\n\n\tcp $DIR/$tdir/f0 $DIR/$tdir/guard\n\n\techo \"Inject failure stub to simulate bad PFL extent range\"\n\t#define OBD_FAIL_LFSCK_BAD_PFL_RANGE\t0x162f\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x162f\n\n\tchown 1.1 $DIR/$tdir/f0\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=1 &&\n\t\terror \"(2) Write to bad PFL file should fail\"\n\n\techo \"Trigger layout LFSCK to find out the bad lmm_oi and fix them\"\n\t$START_LAYOUT -r -o || error \"(3) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\t\terror \"(4.1) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tcur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t     obdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t     awk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(4.2) OST${k} Expect 'completed', but got '$cur_status'\"\n\n\tdone\n\n\tlocal repaired=$($SHOW_LAYOUT |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(5) Fail to repair crashed PFL range: $repaired\"\n\n\techo \"Data in $DIR/$tdir/f0 should not be broken\"\n\tdiff $DIR/$tdir/f0 $DIR/$tdir/guard ||\n\t\terror \"(6) Data in $DIR/$tdir/f0 is broken\"\n\n\techo \"Write should succeed after LFSCK repairing the bad PFL range\"\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=1 ||\n\t\terror \"(7) Write should succeed after LFSCK\"\n}\nrun_test 18h \"LFSCK can repair crashed PFL extent range\"\n\n$LCTL set_param debug=-cache > /dev/null\n\ntest_19a() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid 0\n\n\techo \"foo1\" > $DIR/$tdir/a0\n\t$LFS setstripe -E 512K -S 512K -o 0 -E -1 -S 1M $DIR/$tdir/a1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/a1\"\n\techo \"foo2\" > $DIR/$tdir/a1\n\techo \"guard\" > $DIR/$tdir/a2\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, then client will offer wrong parent FID when read\"\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid 1\n\n\t#define OBD_FAIL_LFSCK_INVALID_PFID\t0x1619\n\t$LCTL set_param fail_loc=0x1619\n\n\techo \"Read RPC with wrong parent FID should be denied\"\n\tcat $DIR/$tdir/a0 && error \"(3.1) Read a0 should be denied!\"\n\tcat $DIR/$tdir/a1 && error \"(3.2) Read a1 should be denied!\"\n\t$LCTL set_param fail_loc=0\n}\nrun_test 19a \"OST-object inconsistency self detect\"\n\ntest_19b() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\techo \"Inject failure stub to make the OST-object to back point to\"\n\techo \"non-exist MDT-object\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid 0\n\n\t#define OBD_FAIL_LFSCK_UNMATCHED_PAIR1\t0x1611\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x1611\n\techo \"foo1\" > $DIR/$tdir/f0\n\t$LFS setstripe -E 1M -S 1M -o 0 -E 4M -S 256K $DIR/$tdir/f1 ||\n\t\terror \"(0) Fail to create PFL $DIR/$tdir/f1\"\n\techo \"foo2\" > $DIR/$tdir/f1\n\tcancel_lru_locks osc\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\n\tdo_facet ost1 $LCTL set_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid 0\n\techo \"Nothing should be fixed since self detect and repair is disabled\"\n\tlocal repaired=$(do_facet ost1 $LCTL get_param -n \\\n\t\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid |\n\t\t\tawk '/^repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(1) Expected 0 repaired, but got $repaired\"\n\n\techo \"Read RPC with right parent FID should be accepted,\"\n\techo \"and cause parent FID on OST to be fixed\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid 1\n\n\tcat $DIR/$tdir/f0 || error \"(2.1) Read f0 should not be denied!\"\n\tcat $DIR/$tdir/f1 || error \"(2.2) Read f1 should not be denied!\"\n\n\trepaired=$(do_facet ost1 $LCTL get_param -n \\\n\t\tobdfilter.${FSNAME}-OST0000.lfsck_verify_pfid |\n\t\tawk '/^repaired/ { print $2 }')\n\t[ $repaired -eq 2 ] ||\n\t\terror \"(3) Expected 1 repaired, but got $repaired\"\n}\nrun_test 19b \"OST-object inconsistency self repair\"\n\nPATTERN_WITH_HOLE=\"40000001\"\nPATTERN_WITHOUT_HOLE=\"raid0\"\n\ntest_20a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object and some of its OST-object are lost.\"\n\techo \"The LFSCK should find out the left OST-objects and re-create\"\n\techo \"the MDT-object under the direcotry .lustre/lost+found/MDTxxxx/\"\n\techo \"with the partial OST-objects (LOV EA hole).\"\n\n\techo \"New client can access the file with LOV EA hole via normal\"\n\techo \"system tools or commands without crash the system.\"\n\n\techo \"For old client, even though it cannot access the file with\"\n\techo \"LOV EA hole, it should not cause the system crash.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/a1\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\t$LFS setstripe -c 3 -i 0 -S 1M $DIR/$tdir/a1\n\t\tbcount=513\n\telse\n\t\t$LFS setstripe -c 2 -i 0 -S 1M $DIR/$tdir/a1\n\t\tbcount=257\n\tfi\n\n\t# 256 blocks on the stripe0.\n\t# 1 block on the stripe1 for 2 OSTs case.\n\t# 256 blocks on the stripe1 for other cases.\n\t# 1 block on the stripe2 if OSTs > 2\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f0 bs=4096 count=$bcount\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f1 bs=4096 count=$bcount\n\tdd if=/dev/zero of=$DIR/$tdir/a1/f2 bs=4096 count=$bcount\n\n\tlocal fid0=$($LFS path2fid $DIR/$tdir/a1/f0)\n\tlocal fid1=$($LFS path2fid $DIR/$tdir/a1/f1)\n\tlocal fid2=$($LFS path2fid $DIR/$tdir/a1/f2)\n\n\techo ${fid0}\n\t$LFS getstripe $DIR/$tdir/a1/f0\n\techo ${fid1}\n\t$LFS getstripe $DIR/$tdir/a1/f1\n\techo ${fid2}\n\t$LFS getstripe $DIR/$tdir/a1/f2\n\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\tdd if=/dev/zero of=$DIR/$tdir/a1/f3 bs=4096 count=$bcount\n\t\tfid3=$($LFS path2fid $DIR/$tdir/a1/f3)\n\t\techo ${fid3}\n\t\t$LFS getstripe $DIR/$tdir/a1/f3\n\tfi\n\n\tcancel_lru_locks osc\n\n\techo \"Inject failure...\"\n\techo \"To simulate f0 lost MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/a1/f0\n\n\techo \"To simulate f1 lost MDT-object and OST-object0\"\n\t#define OBD_FAIL_LFSCK_LOST_SPEOBJ\t0x161a\n\tdo_facet mds1 $LCTL set_param fail_loc=0x161a\n\trm -f $DIR/$tdir/a1/f1\n\n\techo \"To simulate f2 lost MDT-object and OST-object1\"\n\tdo_facet mds1 $LCTL set_param fail_val=1\n\trm -f $DIR/$tdir/a1/f2\n\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\techo \"To simulate f3 lost MDT-object and OST-object2\"\n\t\tdo_facet mds1 $LCTL set_param fail_val=2\n\t\trm -f $DIR/$tdir/a1/f3\n\tfi\n\n\tumount_client $MOUNT\n\tsync\n\tsleep 2\n\tdo_facet mds1 $LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(1) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 ||\n\t\t\terror \"(2) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(3) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\t[ $repaired -eq 9 ] ||\n\t\t\terror \"(4.1) Expect 9 fixed on mds1, but got: $repaired\"\n\telse\n\t\t[ $repaired -eq 4 ] ||\n\t\t\terror \"(4.2) Expect 4 fixed on mds1, but got: $repaired\"\n\tfi\n\n\tmount_client $MOUNT || error \"(5.0) Fail to start client!\"\n\n\tLOV_PATTERN_F_HOLE=0x40000000\n\n\t#\n\t# ${fid0}-R-0 is the old f0\n\t#\n\tlocal name=\"$MOUNT/.lustre/lost+found/MDT0000/${fid0}-R-0\"\n\techo \"Check $name, which is the old f0\"\n\n\t$LFS getstripe -v $name || error \"(5.1) cannot getstripe on $name\"\n\n\tlocal pattern=$($LFS getstripe -L $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITHOUT_HOLE\" ]] ||\n\t\terror \"(5.2) NOT expect pattern flag hole, but got $pattern\"\n\n\tlocal stripes=$($LFS getstripe -c $name)\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\t[ $stripes -eq 3 ] ||\n\t\terror \"(5.3.1) expect the stripe count is 3, but got $stripes\"\n\telse\n\t\t[ $stripes -eq 2 ] ||\n\t\terror \"(5.3.2) expect the stripe count is 2, but got $stripes\"\n\tfi\n\n\tlocal size=$(stat $name | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(5.4) expect the size $((4096 * $bcount)), but got $size\"\n\n\tcat $name > /dev/null || error \"(5.5) cannot read $name\"\n\n\techo \"dummy\" >> $name || error \"(5.6) cannot write $name\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name || error \"(5.7) cannot chown on $name\"\n\n\ttouch $name || error \"(5.8) cannot touch $name\"\n\n\trm -f $name || error \"(5.9) cannot unlink $name\"\n\n\t#\n\t# ${fid1}-R-0 contains the old f1's stripe1 (and stripe2 if OSTs > 2)\n\t#\n\tname=\"$MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0\"\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\techo \"Check $name, it contains the old f1's stripe1 and stripe2\"\n\telse\n\t\techo \"Check $name, it contains the old f1's stripe1\"\n\tfi\n\n\t$LFS getstripe -v $name || error \"(6.1) cannot getstripe on $name\"\n\n\tpattern=$($LFS getstripe -L $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(6.2) expect pattern flag hole, but got $pattern\"\n\n\tstripes=$($LFS getstripe -c $name)\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\t[ $stripes -eq 3 ] ||\n\t\terror \"(6.3.1) expect the stripe count is 3, but got $stripes\"\n\telse\n\t\t[ $stripes -eq 2 ] ||\n\t\terror \"(6.3.2) expect the stripe count is 2, but got $stripes\"\n\tfi\n\n\tsize=$(stat $name | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(6.4) expect the size $((4096 * $bcount)), but got $size\"\n\n\tcat $name > /dev/null && error \"(6.5) normal read $name should fail\"\n\n\tlocal failures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t\t bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\n\t# stripe0 is dummy\n\t[ $failures -eq 256 ] ||\n\t\terror \"(6.6) expect 256 IO failures, but get $failures\"\n\n\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(6.7) expect the size $((4096 * $bcount)), but got $size\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 &&\n\t\terror \"(6.8) write to the LOV EA hole should fail\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 seek=300 ||\n\t\terror \"(6.9) write to normal stripe should NOT fail\"\n\n\techo \"foo\" >> $name && error \"(6.10) append write $name should fail\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name || error \"(6.11) cannot chown on $name\"\n\n\ttouch $name || error \"(6.12) cannot touch $name\"\n\n\trm -f $name || error \"(6.13) cannot unlink $name\"\n\n\t#\n\t# ${fid2}-R-0 it contains the old f2's stripe0 (and stripe2 if OSTs > 2)\n\t#\n\tname=\"$MOUNT/.lustre/lost+found/MDT0000/${fid2}-R-0\"\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\techo \"Check $name, it contains the old f2's stripe0 and stripe2\"\n\telse\n\t\techo \"Check $name, it contains the old f2's stripe0\"\n\tfi\n\n\t$LFS getstripe -v $name || error \"(7.1) cannot getstripe on $name\"\n\n\tpattern=$($LFS getstripe -L $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(7.2) expect pattern flag hole, but got $pattern\"\n\n\tstripes=$($LFS getstripe -c $name)\n\tsize=$(stat $name | awk '/Size:/ { print $2 }')\n\tif [ $OSTCOUNT -gt 2 ]; then\n\t\t[ $stripes -eq 3 ] ||\n\t\terror \"(7.3.1) expect the stripe count is 3, but got $stripes\"\n\n\t\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(7.4.1) expect size $((4096 * $bcount)), but got $size\"\n\n\t\tcat $name > /dev/null &&\n\t\t\terror \"(7.5.1) normal read $name should fail\"\n\n\t\tfailures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t\t   bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\t\t# stripe1 is dummy\n\t\t[ $failures -eq 256 ] ||\n\t\t\terror \"(7.6) expect 256 IO failures, but get $failures\"\n\n\t\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(7.7) expect the size $((4096 * $bcount)), but got $size\"\n\n\t\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 \\\n\t\tseek=300 && error \"(7.8.0) write to the LOV EA hole should fail\"\n\n\t\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 ||\n\t\terror \"(7.8.1) write to normal stripe should NOT fail\"\n\n\t\techo \"foo\" >> $name &&\n\t\t\terror \"(7.8.3) append write $name should fail\"\n\n\t\tchown $RUNAS_ID:$RUNAS_GID $name ||\n\t\t\terror \"(7.9.1) cannot chown on $name\"\n\n\t\ttouch $name || error \"(7.10.1) cannot touch $name\"\n\telse\n\t\t[ $stripes -eq 2 ] ||\n\t\terror \"(7.3.2) expect the stripe count is 2, but got $stripes\"\n\n\t\t# stripe1 is dummy\n\t\t[ $size -eq $((4096 * (256 + 0))) ] ||\n\t\terror \"(7.4.2) expect the size $((4096 * 256)), but got $size\"\n\n\t\tcat $name > /dev/null &&\n\t\t\terror \"(7.5.2) normal read $name should fail\"\n\n\t\tfailures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t\t   bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\t\t[ $failures -eq 256 ] ||\n\t\terror \"(7.6.2) expect 256 IO failures, but get $failures\"\n\n\t\tbcount=$((256 * 2))\n\t\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(7.7.2) expect the size $((4096 * $bcount)), got $size\"\n\n\t\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 \\\n\t\tseek=256 && error \"(7.8.2) write to the LOV EA hole should fail\"\n\n\t\tchown $RUNAS_ID:$RUNAS_GID $name ||\n\t\t\terror \"(7.9.2) cannot chown on $name\"\n\n\t\ttouch $name || error \"(7.10.2) cannot touch $name\"\n\tfi\n\n\trm -f $name || error \"(7.11) cannot unlink $name\"\n\n\t[ $OSTCOUNT -le 2 ] && return\n\n\t#\n\t# ${fid3}-R-0 should contains the old f3's stripe0 and stripe1\n\t#\n\tname=\"$MOUNT/.lustre/lost+found/MDT0000/${fid3}-R-0\"\n\techo \"Check $name, which contains the old f3's stripe0 and stripe1\"\n\n\t$LFS getstripe -v $name || error \"(8.1) cannot getstripe on $name\"\n\n\tpattern=$($LFS getstripe -L $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(8.2) expect pattern flag hole, but got $pattern\"\n\n\tstripes=$($LFS getstripe -c $name)\n\t[ $stripes -eq 3 ] ||\n\t\terror \"(8.3) expect the stripe count is 3, but got $stripes\"\n\n\tsize=$(stat $name | awk '/Size:/ { print $2 }')\n\t# stripe2 is lost\n\t[ $size -eq $((4096 * (256 + 256 + 0))) ] ||\n\t\terror \"(8.4) expect the size $((4096 * 512)), but got $size\"\n\n\tcat $name > /dev/null &&\n\t\terror \"(8.5) normal read $name should fail\"\n\n\tfailures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t   bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\t# stripe2 is dummy\n\t[ $failures -eq 256 ] ||\n\t\terror \"(8.6) expect 256 IO failures, but get $failures\"\n\n\tbcount=$((256 * 3))\n\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(8.7) expect the size $((4096 * $bcount)), but got $size\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 \\\n\t\tseek=512 && error \"(8.8) write to the LOV EA hole should fail\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name ||\n\t\terror \"(8.9) cannot chown on $name\"\n\n\ttouch $name || error \"(8.10) cannot touch $name\"\n\n\trm -f $name || error \"(8.11) cannot unlink $name\"\n}\nrun_test 20a \"Handle the orphan with dummy LOV EA slot properly\"\n\ntest_20b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The target MDT-object and some of its OST-object are lost.\"\n\techo \"The LFSCK should find out the left OST-objects and re-create\"\n\techo \"the MDT-object under the direcotry .lustre/lost+found/MDTxxxx/\"\n\techo \"with the partial OST-objects (LOV EA hole).\"\n\n\techo \"New client can access the file with LOV EA hole via normal\"\n\techo \"system tools or commands without crash the system - PFL case.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setstripe -E 2M -S 1M -c 2 -E -1 -S 1M -c 2 $DIR/$tdir/f0 ||\n\t\terror \"(0) Fail to create PFL file $DIR/$tdir/f0\"\n\t$LFS setstripe -E 2M -S 1M -c 2 -E -1 -S 1M -c 2 $DIR/$tdir/f1 ||\n\t\terror \"(1) Fail to create PFL file $DIR/$tdir/f1\"\n\t$LFS setstripe -E 2M -S 1M -c 2 -E -1 -S 1M -c 2 $DIR/$tdir/f2 ||\n\t\terror \"(2) Fail to create PFL file $DIR/$tdir/f2\"\n\n\tlocal bcount=$((256 * 3 + 1))\n\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=4096 count=$bcount\n\tdd if=/dev/zero of=$DIR/$tdir/f1 bs=4096 count=$bcount\n\tdd if=/dev/zero of=$DIR/$tdir/f2 bs=4096 count=$bcount\n\n\tlocal fid0=$($LFS path2fid $DIR/$tdir/f0)\n\tlocal fid1=$($LFS path2fid $DIR/$tdir/f1)\n\tlocal fid2=$($LFS path2fid $DIR/$tdir/f2)\n\n\techo ${fid0}\n\t$LFS getstripe $DIR/$tdir/f0\n\techo ${fid1}\n\t$LFS getstripe $DIR/$tdir/f1\n\techo ${fid2}\n\t$LFS getstripe $DIR/$tdir/f2\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Inject failure...\"\n\techo \"To simulate f0 lost MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/f0\n\n\techo \"To simulate the case of f1 lost MDT-object and \"\n\techo \"the first OST-object in each PFL component\"\n\t#define OBD_FAIL_LFSCK_LOST_SPEOBJ\t0x161a\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x161a\n\trm -f $DIR/$tdir/f1\n\n\techo \"To simulate the case of f2 lost MDT-object and \"\n\techo \"the second OST-object in each PFL component\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=1\n\trm -f $DIR/$tdir/f2\n\n\tsync\n\tsleep 2\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(3) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 ||\n\t\t\terror \"(4) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(5) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 8 ] ||\n\t\terror \"(6) Expect 8 fixed on mds1, but got: $repaired\"\n\n\t#\n\t# ${fid0}-R-0 is the old f0\n\t#\n\tlocal name=\"$MOUNT/.lustre/lost+found/MDT0000/${fid0}-R-0\"\n\techo \"Check $name, which is the old f0\"\n\n\t$LFS getstripe -v $name || error \"(7.1) cannot getstripe on $name\"\n\n\tlocal pattern=$($LFS getstripe -L -I1 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITHOUT_HOLE\" ]] ||\n\t\terror \"(7.2.1) NOT expect pattern flag hole, but got $pattern\"\n\n\tpattern=$($LFS getstripe -L -I2 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITHOUT_HOLE\" ]] ||\n\t\terror \"(7.2.2) NOT expect pattern flag hole, but got $pattern\"\n\n\tlocal stripes=$($LFS getstripe -c -I1 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(7.3.1) expect 2 stripes, but got $stripes\"\n\n\tstripes=$($LFS getstripe -c -I2 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(7.3.2) expect 2 stripes, but got $stripes\"\n\n\tlocal e_start=$($LFS getstripe -I1 $name |\n\t\t\tawk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 0 ] ||\n\t\terror \"(7.4.1) expect the COMP1 start at 0, got $e_start\"\n\n\tlocal e_end=$($LFS getstripe -I1 $name |\n\t\t      awk '/lcme_extent.e_end:/ { print $2 }')\n\t[ $e_end -eq 2097152 ] ||\n\t\terror \"(7.4.2) expect the COMP1 end at 2097152, got $e_end\"\n\n\te_start=$($LFS getstripe -I2 $name |\n\t\t  awk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 2097152 ] ||\n\t\terror \"(7.5.1) expect the COMP2 start at 2097152, got $e_start\"\n\n\te_end=$($LFS getstripe -I2 $name |\n\t\tawk '/lcme_extent.e_end:/ { print $2 }')\n\t[ \"$e_end\" = \"EOF\" ] ||\n\t\terror \"(7.5.2) expect the COMP2 end at (EOF), got $e_end\"\n\n\tlocal size=$(stat $name | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(7.6) expect the size $((4096 * $bcount)), but got $size\"\n\n\tcat $name > /dev/null || error \"(7.7) cannot read $name\"\n\n\techo \"dummy\" >> $name || error \"(7.8) cannot write $name\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name || error \"(7.9) cannot chown on $name\"\n\n\ttouch $name || error \"(7.10) cannot touch $name\"\n\n\trm -f $name || error \"(7.11) cannot unlink $name\"\n\n\t#\n\t# ${fid1}-R-0 contains the old f1's second stripe in each COMP\n\t#\n\tname=\"$MOUNT/.lustre/lost+found/MDT0000/${fid1}-R-0\"\n\techo \"Check $name, it contains f1's second OST-object in each COMP\"\n\n\t$LFS getstripe -v $name || error \"(8.1) cannot getstripe on $name\"\n\n\tpattern=$($LFS getstripe -L -I1 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(8.2.1) expect pattern flag hole, but got $pattern\"\n\n\tpattern=$($LFS getstripe -L -I2 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(8.2.2) expect pattern flag hole, but got $pattern\"\n\n\tstripes=$($LFS getstripe -c -I1 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(8.3.2) expect 2 stripes, but got $stripes\"\n\n\tstripes=$($LFS getstripe -c -I2 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(8.3.2) expect 2 stripes, but got $stripes\"\n\n\te_start=$($LFS getstripe -I1 $name |\n\t\t  awk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 0 ] ||\n\t\terror \"(8.4.1) expect the COMP1 start at 0, got $e_start\"\n\n\te_end=$($LFS getstripe -I1 $name |\n\t\tawk '/lcme_extent.e_end:/ { print $2 }')\n\t[ $e_end -eq 2097152 ] ||\n\t\terror \"(8.4.2) expect the COMP1 end at 2097152, got $e_end\"\n\n\te_start=$($LFS getstripe -I2 $name |\n\t\t  awk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 2097152 ] ||\n\t\terror \"(8.5.1) expect the COMP2 start at 2097152, got $e_start\"\n\n\te_end=$($LFS getstripe -I2 $name |\n\t\tawk '/lcme_extent.e_end:/ { print $2 }')\n\t[ \"$e_end\" = \"EOF\" ] ||\n\t\terror \"(8.5.2) expect the COMP2 end at (EOF), got $e_end\"\n\n\tsize=$(stat $name | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(8.6) expect the size $((4096 * $bcount)), but got $size\"\n\n\tcat $name > /dev/null && error \"(8.7) normal read $name should fail\"\n\n\tlocal failures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t\t bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\n\t# The first stripe in each COMP was lost\n\t[ $failures -eq 512 ] ||\n\t\terror \"(8.8) expect 512 IO failures, but get $failures\"\n\n\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(8.9) expect the size $((4096 * $bcount)), but got $size\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 &&\n\t\terror \"(8.10) write to the LOV EA hole should fail\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 seek=300 ||\n\t\terror \"(8.11) write to normal stripe should NOT fail\"\n\n\techo \"foo\" >> $name && error \"(8.12) append write $name should fail\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name || error \"(8.13) cannot chown on $name\"\n\n\ttouch $name || error \"(8.14) cannot touch $name\"\n\n\trm -f $name || error \"(8.15) cannot unlink $name\"\n\n\t#\n\t# ${fid2}-R-0 contains the old f2's first stripe in each COMP\n\t#\n\tname=\"$MOUNT/.lustre/lost+found/MDT0000/${fid2}-R-0\"\n\techo \"Check $name, it contains f2's first stripe in each COMP\"\n\n\t$LFS getstripe -v $name || error \"(9.1) cannot getstripe on $name\"\n\n\tpattern=$($LFS getstripe -L -I1 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(9.2.1) expect pattern flag hole, but got $pattern\"\n\n\tpattern=$($LFS getstripe -L -I2 $name)\n\t[[ \"$pattern\" = \"$PATTERN_WITH_HOLE\" ]] ||\n\t\terror \"(9.2.2) expect pattern flag hole, but got $pattern\"\n\n\tstripes=$($LFS getstripe -c -I1 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(9.3.2) expect 2 stripes, but got $stripes\"\n\n\tstripes=$($LFS getstripe -c -I2 $name)\n\t[ $stripes -eq 2 ] ||\n\t\terror \"(9.3.2) expect 2 stripes, but got $stripes\"\n\n\te_start=$($LFS getstripe -I1 $name |\n\t\t  awk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 0 ] ||\n\t\terror \"(9.4.1) expect the COMP1 start at 0, got $e_start\"\n\n\te_end=$($LFS getstripe -I1 $name |\n\t\tawk '/lcme_extent.e_end:/ { print $2 }')\n\t[ $e_end -eq 2097152 ] ||\n\t\terror \"(9.4.2) expect the COMP1 end at 2097152, got $e_end\"\n\n\te_start=$($LFS getstripe -I2 $name |\n\t\t  awk '/lcme_extent.e_start:/ { print $2 }')\n\t[ $e_start -eq 2097152 ] ||\n\t\terror \"(9.5.1) expect the COMP2 start at 2097152, got $e_start\"\n\n\te_end=$($LFS getstripe -I2 $name |\n\t\tawk '/lcme_extent.e_end:/ { print $2 }')\n\t[ \"$e_end\" = \"EOF\" ] ||\n\t\terror \"(9.5.2) expect the COMP2 end at (EOF), got $e_end\"\n\n\tsize=$(stat $name | awk '/Size:/ { print $2 }')\n\t# The second stripe in COMP was lost, so we do not know there\n\t# have ever been some data before. 'stat' will regard it as\n\t# no data on the lost stripe.\n\tbcount=$((256 * 3))\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(9.6) expect size $((4096 * $bcount)), but got $size\"\n\n\tcat $name > /dev/null &&\n\t\terror \"(9.7) normal read $name should fail\"\n\n\tfailures=$(dd if=$name of=$DIR/$tdir/dump conv=sync,noerror \\\n\t\t   bs=4096 2>&1 | grep \"Input/output error\" | wc -l)\n\t[ $failures -eq 512 ] ||\n\t\terror \"(9.8) expect 256 IO failures, but get $failures\"\n\n\tsize=$(stat $DIR/$tdir/dump | awk '/Size:/ { print $2 }')\n\t# The second stripe in COMP was lost, so we do not know there\n\t# have ever been some data before. Since 'dd' skip failure,\n\t# it will regard the lost stripe contains data.\n\tbcount=$((256 * 4))\n\t[ $size -eq $((4096 * $bcount)) ] ||\n\t\terror \"(9.9) expect the size $((4096 * $bcount)), but got $size\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 \\\n\t\tseek=300 && error \"(9.10) write to the LOV EA hole should fail\"\n\n\tdd if=/dev/zero of=$name conv=sync,notrunc bs=4096 count=1 ||\n\t\terror \"(9.11) write to normal stripe should NOT fail\"\n\n\techo \"foo\" >> $name &&\n\t\terror \"(9.12) append write $name should fail\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $name ||\n\t\terror \"(9.13) cannot chown on $name\"\n\n\ttouch $name || error \"(9.14) cannot touch $name\"\n\n\trm -f $name || error \"(7.15) cannot unlink $name\"\n}\nrun_test 20b \"Handle the orphan with dummy LOV EA slot properly - PFL case\"\n\ntest_21() {\n\t[[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.5.59) ]] &&\n\t\tskip \"ignore the test if MDS is older than 2.5.59\" && return\n\n\tcheck_mount_and_prep\n\tcreatemany -o $DIR/$tdir/f 100 || error \"(0) Fail to create 100 files\"\n\n\techo \"Start all LFSCK components by default (-s 1)\"\n\tdo_facet mds1 $LCTL lfsck_start -M ${FSNAME}-MDT0000 -s 1 -r ||\n\t\terror \"Fail to start LFSCK\"\n\n\techo \"namespace LFSCK should be in 'scanning-phase1' status\"\n\tlocal STATUS=$($SHOW_NAMESPACE | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"Expect namespace 'scanning-phase1', but got '$STATUS'\"\n\n\techo \"layout LFSCK should be in 'scanning-phase1' status\"\n\tSTATUS=$($SHOW_LAYOUT | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"Expect layout 'scanning-phase1', but got '$STATUS'\"\n\n\techo \"Stop all LFSCK components by default\"\n\tdo_facet mds1 $LCTL lfsck_stop -M ${FSNAME}-MDT0000 ||\n\t\terror \"Fail to stop LFSCK\"\n}\nrun_test 21 \"run all LFSCK components by default\"\n\ntest_22a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"The parent_A references the child directory via some name entry,\"\n\techo \"but the child directory back references another parent_B via its\"\n\techo \"\"..\" name entry. The parent_B does not exist. Then the namespace\"\n\techo \"LFSCK will repair the child directory's \"..\" name entry.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/guard || error \"(1) Fail to mkdir on MDT1\"\n\t$LFS mkdir -i 1 $DIR/$tdir/foo || error \"(2) Fail to mkdir on MDT1\"\n\n\techo \"Inject failure stub on MDT0 to simulate bad dotdot name entry\"\n\techo \"The dummy's dotdot name entry references the guard.\"\n\t#define OBD_FAIL_LFSCK_BAD_PARENT\t0x161e\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x161e\n\t$LFS mkdir -i 0 $DIR/$tdir/foo/dummy ||\n\t\terror \"(3) Fail to mkdir on MDT0\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\trmdir $DIR/$tdir/guard || error \"(4) Fail to rmdir $DIR/$tdir/guard\"\n\n\techo \"Trigger namespace LFSCK to repair unmatched pairs\"\n\t$START_NAMESPACE -A -r ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^unmatched_pairs_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair unmatched pairs: $repaired\"\n\n\techo \"'ls' should success after namespace LFSCK repairing\"\n\tls -ail $DIR/$tdir/foo/dummy > /dev/null ||\n\t\terror \"(8) ls should success.\"\n}\nrun_test 22a \"LFSCK can repair unmatched pairs (1)\"\n\ntest_22b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"The parent_A references the child directory via the name entry_B,\"\n\techo \"but the child directory back references another parent_C via its\"\n\techo \"\"..\" name entry. The parent_C exists, but there is no the name\"\n\techo \"entry_B under the parent_C. Then the namespace LFSCK will repair\"\n\techo \"the child directory's \"..\" name entry and its linkEA.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/guard || error \"(1) Fail to mkdir on MDT1\"\n\t$LFS mkdir -i 1 $DIR/$tdir/foo || error \"(2) Fail to mkdir on MDT1\"\n\n\techo \"Inject failure stub on MDT0 to simulate bad dotdot name entry\"\n\techo \"and bad linkEA. The dummy's dotdot name entry references the\"\n\techo \"guard. The dummy's linkEA references n non-exist name entry.\"\n\t#define OBD_FAIL_LFSCK_BAD_PARENT\t0x161e\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x161e\n\t$LFS mkdir -i 0 $DIR/$tdir/foo/dummy ||\n\t\terror \"(3) Fail to mkdir on MDT0\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tlocal dummyfid=$($LFS path2fid $DIR/$tdir/foo/dummy)\n\techo \"fid2path should NOT work on the dummy's FID $dummyfid\"\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" != \"$DIR/$tdir/foo/dummy\" ] ||\n\t\terror \"(4) fid2path works unexpectedly.\"\n\n\techo \"Trigger namespace LFSCK to repair unmatched pairs\"\n\t$START_NAMESPACE -A -r ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^unmatched_pairs_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair unmatched pairs: $repaired\"\n\n\techo \"fid2path should work on the dummy's FID $dummyfid after LFSCK\"\n\tlocal dummyname=$($LFS fid2path $DIR $dummyfid)\n\t[ \"$dummyname\" == \"$DIR/$tdir/foo/dummy\" ] ||\n\t\terror \"(8) fid2path does not work\"\n}\nrun_test 22b \"LFSCK can repair unmatched pairs (2)\"\n\ntest_23a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"The name entry is there, but the MDT-object for such name \"\n\techo \"entry does not exist. The namespace LFSCK should find out \"\n\techo \"and repair the inconsistency as required.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0 on MDT0\"\n\t$LFS mkdir -i 1 $DIR/$tdir/d0/d1 || error \"(2) Fail to mkdir d1 on MDT1\"\n\n\techo \"Inject failure stub on MDT1 to simulate dangling name entry\"\n\t#define OBD_FAIL_LFSCK_DANGLING2\t0x1620\n\tdo_facet mds2 $LCTL set_param fail_loc=0x1620\n\trmdir $DIR/$tdir/d0/d1 || error \"(3) Fail to rmdir d1\"\n\tdo_facet mds2 $LCTL set_param fail_loc=0\n\n\techo \"'ls' should fail because of dangling name entry\"\n\tls -ail $DIR/$tdir/d0/d1 > /dev/null 2>&1 && error \"(4) ls should fail.\"\n\n\techo \"Trigger namespace LFSCK to find out dangling name entry\"\n\t$START_NAMESPACE -A -r ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dangling_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair dangling name entry: $repaired\"\n\n\techo \"'ls' should fail because not re-create MDT-object by default\"\n\tls -ail $DIR/$tdir/d0/d1 > /dev/null 2>&1 && error \"(8) ls should fail.\"\n\n\techo \"Trigger namespace LFSCK again to repair dangling name entry\"\n\t$START_NAMESPACE -A -r -C ||\n\t\terror \"(9) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 10\n\n\trepaired=$($SHOW_NAMESPACE |\n\t\t   awk '/^dangling_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(11) Fail to repair dangling name entry: $repaired\"\n\n\techo \"'ls' should success after namespace LFSCK repairing\"\n\tls -ail $DIR/$tdir/d0/d1 > /dev/null || error \"(12) ls should success.\"\n}\nrun_test 23a \"LFSCK can repair dangling name entry (1)\"\n\ntest_23b() {\n\techo \"#####\"\n\techo \"The objectA has multiple hard links, one of them corresponding\"\n\techo \"to the name entry_B. But there is something wrong for the name\"\n\techo \"entry_B and cause entry_B to references non-exist object_C.\"\n\techo \"In the first-stage scanning, the LFSCK will think the entry_B\"\n\techo \"as dangling, and re-create the lost object_C. When the LFSCK\"\n\techo \"comes to the second-stage scanning, it will find that the\"\n\techo \"former re-creating object_C is not proper, and will try to\"\n\techo \"replace the object_C with the real object_A.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0 on MDT0\"\n\t$LFS path2fid $DIR/$tdir/d0\n\n\tcreatemany -o $DIR/$tdir/d0/t 10 || error \"(1.5) Fail to creatmany\"\n\n\techo \"dummy\" > $DIR/$tdir/d0/f0 || error \"(2) Fail to touch on MDT0\"\n\t$LFS path2fid $DIR/$tdir/d0/f0\n\n\techo \"dead\" > $DIR/$tdir/d0/f1 || error \"(3) Fail to touch on MDT0\"\n\t$LFS path2fid $DIR/$tdir/d0/f1\n\n\tlocal SEQ0=$($LFS path2fid $DIR/$tdir/d0/f0 | awk -F':' '{print $1}')\n\tlocal SEQ1=$($LFS path2fid $DIR/$tdir/d0/f1 | awk -F':' '{print $1}')\n\n\tif [ \"$SEQ0\" != \"$SEQ1\" ]; then\n\t\t# To guarantee that the f0 and f1 are in the same FID seq\n\t\trm -f $DIR/$tdir/d0/f0 ||\n\t\t\terror \"(3.1) Fail to unlink $DIR/$tdir/d0/f0\"\n\t\techo \"dummy\" > $DIR/$tdir/d0/f0 ||\n\t\t\terror \"(3.2) Fail to touch on MDT0\"\n\t\t$LFS path2fid $DIR/$tdir/d0/f0\n\tfi\n\n\tlocal OID=$($LFS path2fid $DIR/$tdir/d0/f1 | awk -F':' '{print $2}')\n\tOID=$(printf %d $OID)\n\n\techo \"Inject failure stub on MDT0 to simulate dangling name entry\"\n\t#define OBD_FAIL_LFSCK_DANGLING3\t0x1621\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=$OID fail_loc=0x1621\n\tln $DIR/$tdir/d0/f0 $DIR/$tdir/d0/foo || error \"(4) Fail to hard link\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0 fail_loc=0\n\n\t# If there is creation after the dangling injection, it may re-use\n\t# the just released local object (inode) that is referenced by the\n\t# dangling name entry. It will fail the dangling injection.\n\t# So before deleting the target object for the dangling name entry,\n\t# remove some other objects to avoid the target object being reused\n\t# by some potential creations. LU-7429\n\tunlinkmany $DIR/$tdir/d0/t 10 || error \"(5.0) Fail to unlinkmany\"\n\n\trm -f $DIR/$tdir/d0/f1 || error \"(5) Fail to unlink $DIR/$tdir/d0/f1\"\n\n\techo \"'ls' should fail because of dangling name entry\"\n\tls -ail $DIR/$tdir/d0/foo > /dev/null 2>&1 &&\n\t\terror \"(6) ls should fail.\"\n\n\techo \"Trigger namespace LFSCK to find out dangling name entry\"\n\t$START_NAMESPACE -r -C ||\n\t\terror \"(7) Fail to start LFSCK for namespace\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(8) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dangling_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(9) Fail to repair dangling name entry: $repaired\"\n\n\trepaired=$($SHOW_NAMESPACE |\n\t\t   awk '/^multiple_linked_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(10) Fail to drop the former created object: $repaired\"\n\n\tlocal data=$(cat $DIR/$tdir/d0/foo)\n\t[ \"$data\" == \"dummy\" ] ||\n\t\terror \"(11) The $DIR/$tdir/d0/foo is not recovered: $data\"\n}\nrun_test 23b \"LFSCK can repair dangling name entry (2)\"\n\ncleanup_23c() {\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0 fail_loc=0\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(10) unexpected status\"\n\t}\n\n\tstop_full_debug_logging\n}\n\ntest_23c() {\n\techo \"#####\"\n\techo \"The objectA has multiple hard links, one of them corresponding\"\n\techo \"to the name entry_B. But there is something wrong for the name\"\n\techo \"entry_B and cause entry_B to references non-exist object_C.\"\n\techo \"In the first-stage scanning, the LFSCK will think the entry_B\"\n\techo \"as dangling, and re-create the lost object_C. And then others\"\n\techo \"modified the re-created object_C. When the LFSCK comes to the\"\n\techo \"second-stage scanning, it will find that the former re-creating\"\n\techo \"object_C maybe wrong and try to replace the object_C with the\"\n\techo \"real object_A. But because object_C has been modified, so the\"\n\techo \"LFSCK cannot replace it.\"\n\techo \"#####\"\n\n\tstart_full_debug_logging\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0 on MDT0\"\n\tparent_fid=\"$($LFS path2fid $DIR/$tdir/d0)\"\n\techo \"parent_fid=$parent_fid\"\n\n\tcreatemany -o $DIR/$tdir/d0/t 10 || error \"(1.5) Fail to creatmany\"\n\n\techo \"dummy\" > $DIR/$tdir/d0/f0 || error \"(2) Fail to touch on MDT0\"\n\tf0_fid=\"$($LFS path2fid $DIR/$tdir/d0/f0)\"\n\techo \"f0_fid=$f0_fid\"\n\n\techo \"dead\" > $DIR/$tdir/d0/f1 || error \"(3) Fail to touch on MDT0\"\n\tf1_fid=\"$($LFS path2fid $DIR/$tdir/d0/f1)\"\n\techo \"f1_fid=$f1_fid\"\n\n\tif [ \"${fid_f0/:.*/}\" != \"${fid_f1/:.*/}\" ]; then\n\t\t# To guarantee that the f0 and f1 are in the same FID seq\n\t\trm -f $DIR/$tdir/d0/f0 ||\n\t\t\terror \"(3.1) Fail to unlink $DIR/$tdir/d0/f0\"\n\t\techo \"dummy\" > $DIR/$tdir/d0/f0 ||\n\t\t\terror \"(3.2) Fail to touch on MDT0\"\n\t\tf0_fid=\"$($LFS path2fid $DIR/$tdir/d0/f0)\"\n\t\techo \"f0_fid=$f0_fid (replaced)\"\n\tfi\n\n\tlocal oid=$(awk -F':' '{ printf $2 }' <<< $f1_fid)\n\n\techo \"Inject failure stub on MDT0 to simulate dangling name entry\"\n\t#define OBD_FAIL_LFSCK_DANGLING3\t0x1621\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=$oid fail_loc=0x1621\n\tln $DIR/$tdir/d0/f0 $DIR/$tdir/d0/foo || error \"(4) Fail to hard link\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=0 fail_loc=0\n\n\t# If there is creation after the dangling injection, it may re-use\n\t# the just released local object (inode) that is referenced by the\n\t# dangling name entry. It will fail the dangling injection.\n\t# So before deleting the target object for the dangling name entry,\n\t# remove some other objects to avoid the target object being reused\n\t# by some potential creations. LU-7429\n\tunlinkmany $DIR/$tdir/d0/t 10 || error \"(5.0) Fail to unlinkmany\"\n\n\trm -f $DIR/$tdir/d0/f1 || error \"(5) Fail to unlink $DIR/$tdir/d0/f1\"\n\n\techo \"'ls' should fail because of dangling name entry\"\n\tls -ail $DIR/$tdir/d0/foo > /dev/null 2>&1 &&\n\t\terror \"(6) ls should fail.\"\n\n\t#define OBD_FAIL_LFSCK_DELAY3\t\t0x1602\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=10 fail_loc=0x1602\n\n\techo \"Trigger namespace LFSCK to find out dangling name entry\"\n\t$START_NAMESPACE -r -C ||\n\t\terror \"(7) Fail to start LFSCK for namespace\"\n\n\twait_update_facet client \"stat -c%s $DIR/$tdir/d0/foo\" \"0\" $LTIME || {\n\t\t# While unexpected by the test, it is valid for LFSCK to repair\n\t\t# the link to the original object before any data is written.\n\t\tlocal size=$(stat -c %s $DIR/$tdir/d0/foo)\n\n\t\tif [ \"$size\" = \"6\" -a \"$(<$DIR/$tdir/d0/foo)\" = \"dummy\" ]; then\n\t\t\tlog \"LFSCK repaired file prematurely\"\n\t\t\tcleanup_23c\n\t\t\treturn 0\n\t\tfi\n\n\t\tstat $DIR/$tdir/d0/foo\n\t\t$SHOW_NAMESPACE\n\t\terror \"(8) unexpected size\"\n\t}\n\n\techo \"data\" >> $DIR/$tdir/d0/foo || error \"(9) Fail to write\"\n\tcancel_lru_locks osc\n\n\tcleanup_23c\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dangling_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(11) Fail to repair dangling name entry: $repaired\"\n\n\tlocal data=$(cat $DIR/$tdir/d0/foo)\n\t[ \"$data\" != \"dummy\" ] ||\n\t\terror \"(12) The $DIR/$tdir/d0/foo should not be recovered\"\n}\nrun_test 23c \"LFSCK can repair dangling name entry (3)\"\n\ntest_24() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"Two MDT-objects back reference the same name entry via their\"\n\techo \"each own linkEA entry, but the name entry only references one\"\n\techo \"MDT-object. The namespace LFSCK will remove the linkEA entry\"\n\techo \"for the MDT-object that is not recognized. If such MDT-object\"\n\techo \"has no other linkEA entry after the removing, then the LFSCK\"\n\techo \"will add it as orphan under the .lustre/lost+found/MDTxxxx/.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\n\tmkdir $DIR/$tdir/d0/guard || error \"(1) Fail to mkdir guard\"\n\t$LFS path2fid $DIR/$tdir/d0/guard\n\n\tmkdir $DIR/$tdir/d0/dummy || error \"(2) Fail to mkdir dummy\"\n\t$LFS path2fid $DIR/$tdir/d0/dummy\n\n\tlocal pfid\n\tif [ $(facet_fstype $SINGLEMDS) != ldiskfs ]; then\n\t\tpfid=$($LFS path2fid $DIR/$tdir/d0/guard)\n\telse\n\t\tpfid=$($LFS path2fid $DIR/$tdir/d0/dummy)\n\tfi\n\n\ttouch $DIR/$tdir/d0/guard/foo ||\n\t\terror \"(3) Fail to touch $DIR/$tdir/d0/guard/foo\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"the $DIR/$tdir/d0/dummy/foo has the 'bad' linkEA entry\"\n\techo \"that references $DIR/$tdir/d0/guard/foo.\"\n\techo \"Then remove the name entry $DIR/$tdir/d0/dummy/foo.\"\n\techo \"So the MDT-object $DIR/$tdir/d0/dummy/foo will be left\"\n\techo \"there with the same linkEA entry as another MDT-object\"\n\techo \"$DIR/$tdir/d0/guard/foo has\"\n\n\t#define OBD_FAIL_LFSCK_MUL_REF\t\t0x1622\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1622\n\t$LFS mkdir -i 0 $DIR/$tdir/d0/dummy/foo ||\n\t\terror \"(4) Fail to mkdir $DIR/$tdir/d0/dummy/foo\"\n\t$LFS path2fid $DIR/$tdir/d0/dummy/foo\n\tlocal cfid=$($LFS path2fid $DIR/$tdir/d0/dummy/foo)\n\trmdir $DIR/$tdir/d0/dummy/foo ||\n\t\terror \"(5) Fail to remove $DIR/$tdir/d0/dummy/foo name entry\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"stat $DIR/$tdir/d0/dummy/foo should fail\"\n\tstat $DIR/$tdir/d0/dummy/foo > /dev/null 2>&1 &&\n\t\terror \"(6) stat successfully unexpectedly\"\n\n\techo \"Trigger namespace LFSCK to repair multiple-referenced name entry\"\n\t$START_NAMESPACE -A -r ||\n\t\terror \"(7) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 8\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^multiple_referenced_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\terror \"(9) Fail to repair multiple referenced name entry: $repaired\"\n\n\techo \"There should be an orphan under .lustre/lost+found/MDT0000/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0000 ] ||\n\t\terror \"(10) $MOUNT/.lustre/lost+found/MDT0000/ should be there\"\n\n\tlocal cname=\"$cfid-$pfid-D-0\"\n\tls -ail $MOUNT/.lustre/lost+found/MDT0000/$cname ||\n\t\terror \"(11) .lustre/lost+found/MDT0000/ should not be empty\"\n}\nrun_test 24 \"LFSCK can repair multiple-referenced name entry\"\n\ntest_25() {\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"ldiskfs only test\" && return\n\n\techo \"#####\"\n\techo \"The file type in the name entry does not match the file type\"\n\techo \"claimed by the referenced object. Then the LFSCK will update\"\n\techo \"the file type in the name entry.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"the file type stored in the name entry is wrong.\"\n\n\t#define OBD_FAIL_LFSCK_BAD_TYPE\t\t0x1623\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1623\n\ttouch $DIR/$tdir/d0/foo || error \"(2) Fail to touch $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"Trigger namespace LFSCK to repair bad file type in the name entry\"\n\t$START_NAMESPACE -r || error \"(3) Fail to start LFSCK for namespace\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(4) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^bad_file_type_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\terror \"(5) Fail to repair bad file type in name entry: $repaired\"\n\n\tls -ail $DIR/$tdir/d0 || error \"(6) Fail to 'ls' the $DIR/$tdir/d0\"\n}\nrun_test 25 \"LFSCK can repair bad file type in the name entry\"\n\ntest_26a() {\n\techo \"#####\"\n\techo \"The local name entry back referenced by the MDT-object is lost.\"\n\techo \"The namespace LFSCK will add the missing local name entry back\"\n\techo \"to the normal namespace.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\ttouch $DIR/$tdir/d0/foo || error \"(2) Fail to create foo\"\n\tlocal foofid=$($LFS path2fid $DIR/$tdir/d0/foo)\n\n\tln $DIR/$tdir/d0/foo $DIR/$tdir/d0/dummy ||\n\t\terror \"(3) Fail to hard link to $DIR/$tdir/d0/foo\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"foo's name entry will be removed, but the foo's object\"\n\techo \"and its linkEA are kept in the system.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1624\n\trm -f $DIR/$tdir/d0/foo || error \"(4) Fail to unlink $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tls -ail $DIR/$tdir/d0/foo > /dev/null 2>&1 &&\n\t\terror \"(5) 'ls' should fail\"\n\n\techo \"Trigger namespace LFSCK to repair the missing remote name entry\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(6) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 7\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(8) Fail to repair lost dirent: $repaired\"\n\n\tls -ail $DIR/$tdir/d0/foo ||\n\t\terror \"(9) Fail to 'ls' $DIR/$tdir/d0/foo\"\n\n\tlocal foofid2=$($LFS path2fid $DIR/$tdir/d0/foo)\n\t[ \"$foofid\" == \"$foofid2\" ] ||\n\t\terror \"(10) foo's FID changed: $foofid, $foofid2\"\n}\nrun_test 26a \"LFSCK can add the missing local name entry back to the namespace\"\n\ntest_26b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"The remote name entry back referenced by the MDT-object is lost.\"\n\techo \"The namespace LFSCK will add the missing remote name entry back\"\n\techo \"to the normal namespace.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\t$LFS mkdir -i 0 $DIR/$tdir/d0/foo || error \"(2) Fail to mkdir foo\"\n\tlocal foofid=$($LFS path2fid $DIR/$tdir/d0/foo)\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"foo's name entry will be removed, but the foo's object\"\n\techo \"and its linkEA are kept in the system.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1624\n\trmdir $DIR/$tdir/d0/foo || error \"(3) Fail to rmdir $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tls -ail $DIR/$tdir/d0/foo > /dev/null 2>&1 &&\n\t\terror \"(4) 'ls' should fail\"\n\n\techo \"Trigger namespace LFSCK to repair the missing remote name entry\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair lost dirent: $repaired\"\n\n\tls -ail $DIR/$tdir/d0/foo ||\n\t\terror \"(8) Fail to 'ls' $DIR/$tdir/d0/foo\"\n\n\tlocal foofid2=$($LFS path2fid $DIR/$tdir/d0/foo)\n\t[ \"$foofid\" == \"$foofid2\" ] ||\n\t\terror \"(9) foo's FID changed: $foofid, $foofid2\"\n}\nrun_test 26b \"LFSCK can add the missing remote name entry back to the namespace\"\n\ntest_27a() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The local parent referenced by the MDT-object linkEA is lost.\"\n\techo \"The namespace LFSCK will re-create the lost parent as orphan.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\ttouch $DIR/$tdir/d0/foo || error \"(2) Fail to create foo\"\n\tln $DIR/$tdir/d0/foo $DIR/$tdir/d0/dummy ||\n\t\terror \"(3) Fail to hard link to $DIR/$tdir/d0/foo\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"foo's name entry will be removed, but the foo's object\"\n\techo \"and its linkEA are kept in the system. And then remove\"\n\techo \"another hard link and the parent directory.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1624\n\trm -f $DIR/$tdir/d0/foo ||\n\t\terror \"(4) Fail to unlink $DIR/$tdir/d0/foo\"\n\trm -f $DIR/$tdir/d0/dummy ||\n\t\terror \"(5) Fail to unlink $DIR/$tdir/d0/dummy\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\trm -rf $DIR/$tdir/d0 || error \"(5) Fail to unlink the dir d0\"\n\tls -ail $DIR/$tdir/d0 > /dev/null 2>&1 && error \"(6) 'ls' should fail\"\n\n\techo \"Trigger namespace LFSCK to repair the lost parent\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(6) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 7\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(8) Fail to repair lost dirent: $repaired\"\n\n\techo \"There should be an orphan under .lustre/lost+found/MDT0000/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0000 ] ||\n\t\terror \"(9) $MOUNT/.lustre/lost+found/MDT0000/ should be there\"\n\n\tls -ail $MOUNT/.lustre/lost+found/MDT0000/\n\n\tcname=$(find $MOUNT/.lustre/lost+found/MDT0000/ -name *-P-*)\n\t[ ! -z \"$cname\" ] ||\n\t\terror \"(10) .lustre/lost+found/MDT0000/ should not be empty\"\n}\nrun_test 27a \"LFSCK can recreate the lost local parent directory as orphan\"\n\ntest_27b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The remote parent referenced by the MDT-object linkEA is lost.\"\n\techo \"The namespace LFSCK will re-create the lost parent as orphan.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 1 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\t$LFS mkdir -i 0 $DIR/$tdir/d0/foo || error \"(2) Fail to mkdir foo\"\n\n\t$LFS path2fid $DIR/$tdir/d0\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"foo's name entry will be removed, but the foo's object\"\n\techo \"and its linkEA are kept in the system. And then remove\"\n\techo \"the parent directory.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1624\n\trmdir $DIR/$tdir/d0/foo || error \"(3) Fail to rmdir $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\trmdir $DIR/$tdir/d0 || error \"(4) Fail to unlink the dir d0\"\n\tls -ail $DIR/$tdir/d0 > /dev/null 2>&1 && error \"(5) 'ls' should fail\"\n\n\techo \"Trigger namespace LFSCK to repair the missing remote name entry\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(6) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 7\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(8) Fail to repair lost dirent: $repaired\"\n\n\tls -ail $MOUNT/.lustre/lost+found/\n\n\techo \"There should be an orphan under .lustre/lost+found/MDT0001/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0001 ] ||\n\t\terror \"(9) $MOUNT/.lustre/lost+found/MDT0001/ should be there\"\n\n\tls -ail $MOUNT/.lustre/lost+found/MDT0001/\n\n\tcname=$(find $MOUNT/.lustre/lost+found/MDT0001/ -name *-P-*)\n\t[ ! -z \"$cname\" ] ||\n\t\terror \"(10) .lustre/lost+found/MDT0001/ should not be empty\"\n}\nrun_test 27b \"LFSCK can recreate the lost remote parent directory as orphan\"\n\ntest_28() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"The target name entry is lost. The LFSCK should insert the\"\n\techo \"orphan MDT-object under .lustre/lost+found/MDTxxxx. But if\"\n\techo \"the MDT (on which the orphan MDT-object resides) has ever\"\n\techo \"failed to respond some name entry verification during the\"\n\techo \"first stage-scanning, then the LFSCK should skip to handle\"\n\techo \"orphan MDT-object on this MDT. But other MDTs should not\"\n\techo \"be affected.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 0 $DIR/$tdir/d1\n\t$LFS mkdir -i 1 $DIR/$tdir/d1/a1\n\t$LFS mkdir -i 1 $DIR/$tdir/d1/a2\n\n\t$LFS mkdir -i 1 $DIR/$tdir/d2\n\t$LFS mkdir -i 0 $DIR/$tdir/d2/a1\n\t$LFS mkdir -i 0 $DIR/$tdir/d2/a2\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"d1/a1's name entry will be removed, but the d1/a1's object\"\n\techo \"and its linkEA are kept in the system. And the case that\"\n\techo \"d2/a2's name entry will be removed, but the d2/a2's object\"\n\techo \"and its linkEA are kept in the system.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1624\n\tdo_facet mds2 $LCTL set_param fail_loc=0x1624\n\trmdir $DIR/$tdir/d1/a1 || error \"(1) Fail to rmdir $DIR/$tdir/d1/a1\"\n\trmdir $DIR/$tdir/d2/a2 || error \"(2) Fail to rmdir $DIR/$tdir/d2/a2\"\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tdo_facet mds2 $LCTL set_param fail_loc=0\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Inject failure, to simulate the MDT0 fail to handle\"\n\techo \"MDT1 LFSCK request during the first-stage scanning.\"\n\t#define OBD_FAIL_LFSCK_BAD_NETWORK\t0x161c\n\tdo_facet mds2 $LCTL set_param fail_loc=0x161c fail_val=0\n\n\techo \"Trigger namespace LFSCK on all devices to find out orphan object\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(3) Fail to start LFSCK for namespace\"\n\n\twait_update_facet mds1 \"$LCTL get_param -n \\\n\t\tmdd.$(facet_svc mds1).lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"partial\" 32 || {\n\t\terror \"(4) mds1 is not the expected 'partial'\"\n\t}\n\n\twait_update_facet mds2 \"$LCTL get_param -n \\\n\t\tmdd.$(facet_svc mds2).lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\terror \"(5) mds2 is not the expected 'completed'\"\n\t}\n\n\tdo_facet mds2 $LCTL set_param fail_loc=0 fail_val=0\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_namespace |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(6) Expect 0 fixed on mds1, but got: $repaired\"\n\n\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t   mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t   awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Expect 1 fixed on mds2, but got: $repaired\"\n\n\techo \"Trigger namespace LFSCK on all devices again to cleanup\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(8) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 9\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_namespace |\n\t\t\t awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(10) Expect 1 fixed on mds1, but got: $repaired\"\n\n\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t   mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t   awk '/^lost_dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(11) Expect 0 fixed on mds2, but got: $repaired\"\n}\nrun_test 28 \"Skip the failed MDT(s) when handle orphan MDT-objects\"\n\ntest_29a() {\n\techo \"#####\"\n\techo \"The object's nlink attribute is larger than the object's known\"\n\techo \"name entries count. The LFSCK will repair the object's nlink\"\n\techo \"attribute to match the known name entries count\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\ttouch $DIR/$tdir/d0/foo || error \"(2) Fail to create foo\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that foo's\"\n\techo \"nlink attribute is larger than its name entries count.\"\n\n\t#define OBD_FAIL_LFSCK_MORE_NLINK\t0x1625\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1625\n\tln $DIR/$tdir/d0/foo $DIR/$tdir/d0/h1 ||\n\t\terror \"(3) Fail to hard link to $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tcancel_lru_locks mdc\n\tlocal count=$(stat --format=%h $DIR/$tdir/d0/foo)\n\t[ $count -eq 3 ] || error \"(4) Cannot inject error: $count\"\n\n\techo \"Trigger namespace LFSCK to repair the nlink count\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^nlinks_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair nlink count: $repaired\"\n\n\tcancel_lru_locks mdc\n\tcount=$(stat --format=%h $DIR/$tdir/d0/foo)\n\t[ $count -eq 2 ] || error \"(8) Fail to repair nlink count: $count\"\n}\n# Disable 29a, we only allow nlink to be updated if the known linkEA\n# entries is larger than nlink count.\n#\n#run_test 29a \"LFSCK can repair bad nlink count (1)\"\n\ntest_29b() {\n\techo \"#####\"\n\techo \"The object's nlink attribute is smaller than the object's known\"\n\techo \"name entries count. The LFSCK will repair the object's nlink\"\n\techo \"attribute to match the known name entries count\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 || error \"(1) Fail to mkdir d0\"\n\ttouch $DIR/$tdir/d0/foo || error \"(2) Fail to create foo\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that foo's\"\n\techo \"nlink attribute is smaller than its name entries count.\"\n\n\t#define OBD_FAIL_LFSCK_LESS_NLINK\t0x1626\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1626\n\tln $DIR/$tdir/d0/foo $DIR/$tdir/d0/h1 ||\n\t\terror \"(3) Fail to hard link to $DIR/$tdir/d0/foo\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tcancel_lru_locks mdc\n\tlocal count=$(stat --format=%h $DIR/$tdir/d0/foo)\n\t[ $count -eq 1 ] || error \"(4) Cannot inject error: $count\"\n\n\techo \"Trigger namespace LFSCK to repair the nlink count\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^nlinks_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(7) Fail to repair nlink count: $repaired\"\n\n\tcancel_lru_locks mdc\n\tcount=$(stat --format=%h $DIR/$tdir/d0/foo)\n\t[ $count -eq 2 ] || error \"(8) Fail to repair nlink count: $count\"\n}\nrun_test 29b \"LFSCK can repair bad nlink count (2)\"\n\ntest_29c()\n{\n\techo \"#####\"\n\techo \"The namespace LFSCK will create many hard links to the target\"\n\techo \"file as to exceed the linkEA size limitation. Under such case\"\n\techo \"the linkEA will be marked as overflow that will prevent the\"\n\techo \"target file to be migrated. Then remove some hard links to\"\n\techo \"make the left hard links to be held within the linkEA size\"\n\techo \"limitation. But before the namespace LFSCK adding all the\"\n\techo \"missed linkEA entries back, the overflow mark (timestamp)\"\n\techo \"will not be cleared.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\tmkdir -p $DIR/$tdir/guard || error \"(0.1) Fail to mkdir\"\n\t$LFS mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir/foo ||\n\t\terror \"(0.2) Fail to mkdir\"\n\ttouch $DIR/$tdir/guard/f0 || error \"(1) Fail to create\"\n\tlocal oldfid=$($LFS path2fid $DIR/$tdir/guard/f0)\n\n\t# define MAX_LINKEA_SIZE        4096\n\t# sizeof(link_ea_header) = 24\n\t# sizeof(link_ea_entry) = 18\n\t# nlink_min=$(((MAX_LINKEA_SIZE - sizeof(link_ea_header)) /\n\t#\t      (sizeof(link_ea_entry) + name_length))\n\t# If the average name length is 12 bytes, then 150 hard links\n\t# is totally enough to overflow the linkEA\n\techo \"Create 150 hard links should succeed although the linkEA overflow\"\n\tcreatemany -l $DIR/$tdir/guard/f0 $DIR/$tdir/foo/ttttttttttt 150 ||\n\t\terror \"(2) Fail to hard link\"\n\n\tcancel_lru_locks mdc\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS migrate -m 1 $DIR/$tdir/guard 2>/dev/null &&\n\t\t\terror \"(3.1) Migrate should fail\"\n\n\t\techo \"The object with linkEA overflow should NOT be migrated\"\n\t\tlocal newfid=$($LFS path2fid $DIR/$tdir/guard/f0)\n\t\t[ \"$newfid\" == \"$oldfid\" ] ||\n\t\t\terror \"(3.2) Migrate should fail: $newfid != $oldfid\"\n\tfi\n\n\t# Remove 100 hard links, then the linkEA should have space\n\t# to hold the missed linkEA entries.\n\techo \"Remove 100 hard links to save space for the missed linkEA entries\"\n\tunlinkmany $DIR/$tdir/foo/ttttttttttt 100 || error \"(4) Fail to unlink\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS migrate -m 1 $DIR/$tdir/guard 2>/dev/null &&\n\t\t\terror \"(5.1) Migrate should fail\"\n\n\t\t# The overflow timestamp is still there, so migration will fail.\n\t\tlocal newfid=$($LFS path2fid $DIR/$tdir/guard/f0)\n\t\t[ \"$newfid\" == \"$oldfid\" ] ||\n\t\t\terror \"(5.2) Migrate should fail: $newfid != $oldfid\"\n\tfi\n\n\t# sleep 3 seconds to guarantee that the overflow is recognized\n\tsleep 3\n\n\techo \"Trigger namespace LFSCK to clear the overflow timestamp\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(6) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 7\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^linkea_overflow_cleared/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(8) Fail to clear linkea overflow: $repaired\"\n\n\trepaired=$($SHOW_NAMESPACE |\n\t\t   awk '/^nlinks_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(9) Unexpected nlink repaired: $repaired\"\n\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\t$LFS migrate -m 1 $DIR/$tdir/guard 2>/dev/null ||\n\t\t\terror \"(10.1) Migrate failure\"\n\n\t\t# Migration should succeed after clear the overflow timestamp.\n\t\tlocal newfid=$($LFS path2fid $DIR/$tdir/guard/f0)\n\t\t[ \"$newfid\" != \"$oldfid\" ] ||\n\t\t\terror \"(10.2) Migrate should succeed\"\n\n\t\tls -l $DIR/$tdir/foo > /dev/null ||\n\t\t\terror \"(11) 'ls' failed after migration\"\n\tfi\n\n\trm -f $DIR/$tdir/guard/f0 || error \"(12) Fail to unlink f0\"\n\trm -rf $DIR/$tdir/foo || error \"(13) Fail to rmdir foo\"\n}\nrun_test 29c \"verify linkEA size limitation\"\n\ntest_30() {\n\t[ $(facet_fstype $SINGLEMDS) != ldiskfs ] &&\n\t\tskip \"ldiskfs only test\" && return\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\techo \"#####\"\n\techo \"The namespace LFSCK will move the orphans from backend\"\n\techo \"/lost+found directory to normal client visible namespace\"\n\techo \"or to global visible ./lustre/lost+found/MDTxxxx/ directory\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $DIR/$tdir/foo || error \"(1) Fail to mkdir foo\"\n\ttouch $DIR/$tdir/foo/f0 || error \"(2) Fail to touch f1\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that\"\n\techo \"directory d0 has no linkEA entry, then the LFSCK will\"\n\techo \"move it into .lustre/lost+found/MDTxxxx/ later.\"\n\n\t#define OBD_FAIL_LFSCK_NO_LINKEA\t0x161d\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x161d\n\tmkdir $DIR/$tdir/foo/d0 || error \"(3) Fail to mkdir d0\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tlocal pfid=$($LFS path2fid $DIR/$tdir/foo)\n\tlocal cfid=$($LFS path2fid $DIR/$tdir/foo/d0)\n\n\ttouch $DIR/$tdir/foo/d0/f1 || error \"(4) Fail to touch f1\"\n\tmkdir $DIR/$tdir/foo/d0/d1 || error \"(5) Fail to mkdir d1\"\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"object's name entry will be removed, but not destroy the\"\n\techo \"object. Then backend e2fsck will handle it as orphan and\"\n\techo \"add them into the backend /lost+found directory.\"\n\n\t#define OBD_FAIL_LFSCK_NO_NAMEENTRY\t0x1624\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1624\n\trmdir $DIR/$tdir/foo/d0/d1 || error \"(6) Fail to rmdir d1\"\n\trm -f $DIR/$tdir/foo/d0/f1 || error \"(7) Fail to unlink f1\"\n\trmdir $DIR/$tdir/foo/d0 || error \"(8) Fail to rmdir d0\"\n\trm -f $DIR/$tdir/foo/f0 || error \"(9) Fail to unlink f0\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\tumount_client $MOUNT || error \"(10) Fail to stop client!\"\n\n\tstop $SINGLEMDS || error \"(11) Fail to stop MDT0\"\n\n\techo \"run e2fsck\"\n\trun_e2fsck $(facet_host $SINGLEMDS) $MDT_DEVNAME \"-y\" ||\n\t\terror \"(12) Fail to run e2fsck\"\n\n\tstart $SINGLEMDS $MDT_DEVNAME $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(13) Fail to start MDT0\"\n\n\techo \"Trigger namespace LFSCK to recover backend orphans\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(14) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 15\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^local_lost_found_moved/ { print $2 }')\n\t[ $repaired -ge 4 ] ||\n\t\terror \"(16) Fail to recover backend orphans: $repaired\"\n\n\tmount_client $MOUNT || error \"(17) Fail to start client!\"\n\n\tstat $DIR/$tdir/foo/f0 || error \"(18) f0 is not recovered\"\n\n\tls -ail $MOUNT/.lustre/lost+found/\n\n\techo \"d0 should become orphan under .lustre/lost+found/MDT0000/\"\n\t[ -d $MOUNT/.lustre/lost+found/MDT0000 ] ||\n\t\terror \"(19) $MOUNT/.lustre/lost+found/MDT0000/ should be there\"\n\n\tls -ail $MOUNT/.lustre/lost+found/MDT0000/\n\n\tlocal cname=$MOUNT/.lustre/lost+found/MDT0000/${cfid}-${pfid}-D-0\n\t[ ! -z \"$cname\" ] || error \"(20) d0 is not recovered\"\n\n\tstat ${cname}/d1 || error \"(21) d1 is not recovered\"\n\tstat ${cname}/f1 || error \"(22) f1 is not recovered\"\n}\nrun_test 30 \"LFSCK can recover the orphans from backend /lost+found\"\n\ntest_31a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For the name entry under a striped directory, if the name\"\n\techo \"hash does not match the shard, then the LFSCK will repair\"\n\techo \"the bad name entry\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\n\techo \"Inject failure stub on client to simulate the case that\"\n\techo \"some name entry should be inserted into other non-first\"\n\techo \"shard, but inserted into the first shard by wrong\"\n\n\t#define OBD_FAIL_LFSCK_BAD_NAME_HASH\t0x1628\n\t$LCTL set_param fail_loc=0x1628 fail_val=0\n\tcreatemany -d $DIR/$tdir/striped_dir/d $MDSCOUNT ||\n\t\terror \"(2) Fail to create file under striped directory\"\n\t$LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to repair bad name hash\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(3) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 4\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^name_hash_repaired/ { print $2 }')\n\t[ $repaired -ge 1 ] ||\n\t\terror \"(5) Fail to repair bad name hash: $repaired\"\n\n\tumount_client $MOUNT || error \"(6) umount failed\"\n\tmount_client $MOUNT || error \"(7) mount failed\"\n\n\tfor ((i = 0; i < $MDSCOUNT; i++)); do\n\t\tstat $DIR/$tdir/striped_dir/d$i ||\n\t\t\terror \"(8) Fail to stat d$i after LFSCK\"\n\t\trmdir $DIR/$tdir/striped_dir/d$i ||\n\t\t\terror \"(9) Fail to unlink d$i after LFSCK\"\n\tdone\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(10) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31a \"The LFSCK can find/repair the name entry with bad name hash (1)\"\n\ntest_31b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For the name entry under a striped directory, if the name\"\n\techo \"hash does not match the shard, then the LFSCK will repair\"\n\techo \"the bad name entry\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\n\techo \"Inject failure stub on client to simulate the case that\"\n\techo \"some name entry should be inserted into other non-second\"\n\techo \"shard, but inserted into the secod shard by wrong\"\n\n\t#define OBD_FAIL_LFSCK_BAD_NAME_HASH\t0x1628\n\t$LCTL set_param fail_loc=0x1628 fail_val=1\n\tcreatemany -d $DIR/$tdir/striped_dir/d $((MDSCOUNT * 5)) ||\n\t\terror \"(2) Fail to create file under striped directory\"\n\t$LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to repair bad name hash\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(3) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 4\n\n\tlocal repaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t\t awk '/^name_hash_repaired/ { print $2 }')\n\techo \"repaired $repaired name entries with bad hash\"\n\t[ $repaired -ge 1 ] ||\n\t\terror \"(5) Fail to repair bad name hash: $repaired\"\n\n\tumount_client $MOUNT || error \"(6) umount failed\"\n\tmount_client $MOUNT || error \"(7) mount failed\"\n\n\tfor ((i = 0; i < $((MDSCOUNT * 5)); i++)); do\n\t\tstat $DIR/$tdir/striped_dir/d$i ||\n\t\t\terror \"(8) Fail to stat d$i after LFSCK\"\n\t\trmdir $DIR/$tdir/striped_dir/d$i ||\n\t\t\terror \"(9) Fail to unlink d$i after LFSCK\"\n\tdone\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(10) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31b \"The LFSCK can find/repair the name entry with bad name hash (2)\"\n\ntest_31c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the master MDT-object of the striped directory\"\n\techo \"may lost its master LMV EA. If nobody created files under the\"\n\techo \"master directly after the master LMV EA lost, then the LFSCK\"\n\techo \"should re-generate the master LMV EA.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"master MDT-object of the striped directory lost the LMV EA.\"\n\n\t#define OBD_FAIL_LFSCK_LOST_MASTER_LMV\t0x1629\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1629\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\techo \"Trigger namespace LFSCK to re-generate master LMV EA\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(2) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 3\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^striped_dirs_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to re-generate master LMV EA: $repaired\"\n\n\tumount_client $MOUNT || error \"(5) umount failed\"\n\tmount_client $MOUNT || error \"(6) mount failed\"\n\n\tlocal empty=$(ls $DIR/$tdir/striped_dir/)\n\t[ -z \"$empty\" ] || error \"(7) The master LMV EA is not repaired: $empty\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(8) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31c \"Re-generate the lost master LMV EA for striped directory\"\n\ntest_31d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the master MDT-object of the striped directory\"\n\techo \"may lost its master LMV EA. If somebody created files under the\"\n\techo \"master directly after the master LMV EA lost, then the LFSCK\"\n\techo \"should NOT re-generate the master LMV EA, instead, it should\"\n\techo \"change the broken striped dirctory as read-only to prevent\"\n\techo \"further damage\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"master MDT-object of the striped directory lost the LMV EA.\"\n\n\t#define OBD_FAIL_LFSCK_LOST_MASTER_LMV\t0x1629\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1629\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0\n\n\tumount_client $MOUNT || error \"(2) umount failed\"\n\tmount_client $MOUNT || error \"(3) mount failed\"\n\n\ttouch $DIR/$tdir/striped_dir/dummy ||\n\t\terror \"(4) Fail to touch under broken striped directory\"\n\n\techo \"Trigger namespace LFSCK to find out the inconsistency\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(5) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 6\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^striped_dirs_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(7) Re-generate master LMV EA unexpected: $repaired\"\n\n\tstat $DIR/$tdir/striped_dir/dummy ||\n\t\terror \"(8) Fail to stat $DIR/$tdir/striped_dir/dummy\"\n\n\ttouch $DIR/$tdir/striped_dir/foo &&\n\t\terror \"(9) The broken striped directory should be read-only\"\n\n\tchattr -i $DIR/$tdir/striped_dir ||\n\t\terror \"(10) Fail to chattr on the broken striped directory\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(11) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31d \"Set broken striped directory (modified after broken) as read-only\"\n\ntest_31e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the slave MDT-object of the striped directory\"\n\techo \"may lost its slave LMV EA. The LFSCK should re-generate the\"\n\techo \"slave LMV EA.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"slave MDT-object (that resides on the same MDT as the master\"\n\techo \"MDT-object resides on) lost the LMV EA.\"\n\n\t#define OBD_FAIL_LFSCK_LOST_SLAVE_LMV\t0x162a\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x162a fail_val=0\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to re-generate slave LMV EA\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(2) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 3\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^striped_shards_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to re-generate slave LMV EA: $repaired\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(5) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31e \"Re-generate the lost slave LMV EA for striped directory (1)\"\n\ntest_31f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the slave MDT-object of the striped directory\"\n\techo \"may lost its slave LMV EA. The LFSCK should re-generate the\"\n\techo \"slave LMV EA.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"slave MDT-object (that resides on different MDT as the master\"\n\techo \"MDT-object resides on) lost the LMV EA.\"\n\n\t#define OBD_FAIL_LFSCK_LOST_SLAVE_LMV\t0x162a\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x162a fail_val=1\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to re-generate slave LMV EA\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(2) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 3\n\n\tlocal repaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t\t awk '/^striped_shards_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to re-generate slave LMV EA: $repaired\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(5) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31f \"Re-generate the lost slave LMV EA for striped directory (2)\"\n\ntest_31g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the stripe index in the slave LMV EA is\"\n\techo \"corrupted. The LFSCK should repair the slave LMV EA.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"slave LMV EA on the first shard of the striped directory\"\n\techo \"claims the same index as the second shard claims\"\n\n\t#define OBD_FAIL_LFSCK_BAD_SLAVE_LMV\t0x162b\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x162b fail_val=0\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to repair the slave LMV EA\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(2) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 3\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^striped_shards_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to repair slave LMV EA: $repaired\"\n\n\tumount_client $MOUNT || error \"(5) umount failed\"\n\tmount_client $MOUNT || error \"(6) mount failed\"\n\n\ttouch $DIR/$tdir/striped_dir/foo ||\n\t\terror \"(7) Fail to touch file after the LFSCK\"\n\n\trm -f $DIR/$tdir/striped_dir/foo ||\n\t\terror \"(8) Fail to unlink file after the LFSCK\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(9) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31g \"Repair the corrupted slave LMV EA\"\n\ntest_31h() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\techo \"#####\"\n\techo \"For some reason, the shard's name entry in the striped\"\n\techo \"directory may be corrupted. The LFSCK should repair the\"\n\techo \"bad shard's name entry.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\techo \"Inject failure stub on MDT0 to simulate the case that the\"\n\techo \"first shard's name entry in the striped directory claims\"\n\techo \"the same index as the second shard's name entry claims.\"\n\n\t#define OBD_FAIL_LFSCK_BAD_SLAVE_NAME\t0x162c\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x162c fail_val=0\n\t$LFS setdirstripe -i 0 -c $MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"(1) Fail to create striped directory\"\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x0 fail_val=0\n\n\techo \"Trigger namespace LFSCK to repair the shard's name entry\"\n\t$START_NAMESPACE -r -A ||\n\t\terror \"(2) Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 3\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to repair shard's name entry: $repaired\"\n\n\tumount_client $MOUNT || error \"(5) umount failed\"\n\tmount_client $MOUNT || error \"(6) mount failed\"\n\n\ttouch $DIR/$tdir/striped_dir/foo ||\n\t\terror \"(7) Fail to touch file after the LFSCK\"\n\n\trm -f $DIR/$tdir/striped_dir/foo ||\n\t\terror \"(8) Fail to unlink file after the LFSCK\"\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"(9) Fail to remove the striped directory after LFSCK\"\n}\nrun_test 31h \"Repair the corrupted shard's name entry\"\n\ntest_32a()\n{\n\tlfsck_prep 5 5\n\tumount_client $MOUNT\n\n\t#define OBD_FAIL_LFSCK_ENGINE_DELAY\t0x162d\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=3 fail_loc=0x162d\n\t$START_LAYOUT -r || error \"(1) Fail to start LFSCK for layout!\"\n\n\tlocal STATUS=$($SHOW_LAYOUT | awk '/^status/ { print $2 }')\n\t[ \"$STATUS\" == \"scanning-phase1\" ] ||\n\t\terror \"(2) Expect 'scanning-phase1', but got '$STATUS'\"\n\n\techo \"stop ost1\"\n\tstop ost1 > /dev/null || error \"(3) Fail to stop OST1!\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\tsleep 4\n\n\techo \"stop LFSCK\"\n\t$STOP_LFSCK || error \"(4) Fail to stop LFSCK!\"\n\n\tstart ost1 $(ostdevname 1) $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(5) Fail to start ost1\"\n}\nrun_test 32a \"stop LFSCK when some OST failed\"\n\ntest_32b()\n{\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tlfsck_prep 5 5\n\t$LFS mkdir -i 1 $DIR/$tdir/dp ||\n\t\terror \"(1) Fail to create $DIR/$tdir/dp\"\n\t$LFS mkdir -i 0 -c $MDSCOUNT $DIR/$tdir/dp/dc1 ||\n\t\terror \"(2) Fail to create $DIR/$tdir/dp/dc1\"\n\t$LFS mkdir -i 0 -c $MDSCOUNT $DIR/$tdir/dp/dc2 ||\n\t\terror \"(3) Fail to create $DIR/$tdir/dp/dc2\"\n\tumount_client $MOUNT\n\n\t#define OBD_FAIL_LFSCK_ENGINE_DELAY\t0x162d\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=3 fail_loc=0x162d\n\t$START_NAMESPACE -r -A || error \"(4) Fail to start LFSCK for namespace!\"\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"scanning-phase1\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(5) unexpected status\"\n\t}\n\n\techo \"stop mds2\"\n\tstop mds2 > /dev/null || error \"(6) Fail to stop MDT2!\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0 fail_val=0\n\tsleep 4\n\n\techo \"stop LFSCK\"\n\t$STOP_LFSCK || error \"(7) Fail to stop LFSCK!\"\n\n\tstart mds2 $(mdsdevname 2) $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(8) Fail to start MDT2\"\n}\nrun_test 32b \"stop LFSCK when some MDT failed\"\n\ntest_33()\n{\n\tlfsck_prep 5 5\n\n\t$START_LAYOUT --dryrun -o -r ||\n\t\terror \"(1) Fail to start layout LFSCK\"\n\twait_all_targets_blocked layout completed 2\n\n\tlocal PARAMS=$($SHOW_LAYOUT | awk '/^param/ { print $2 }')\n\t[ \"$PARAMS\" == \"dryrun,all_targets,orphan\" ] ||\n\t\terror \"(3) Expect 'dryrun,all_targets,orphan', got '$PARAMS'\"\n\n\t$START_NAMESPACE -e abort -A -r ||\n\t\terror \"(4) Fail to start namespace LFSCK\"\n\twait_all_targets_blocked namespace completed 5\n\n\tPARAMS=$($SHOW_NAMESPACE | awk '/^param/ { print $2 }')\n\t[ \"$PARAMS\" == \"failout,all_targets\" ] ||\n\t\terror \"(6) Expect 'failout,all_targets', got '$PARAMS'\"\n}\nrun_test 33 \"check LFSCK paramters\"\n\ntest_34()\n{\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\t[ $(facet_fstype $SINGLEMDS) != zfs ] &&\n\t\tskip \"Only valid for ZFS backend\" && return\n\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_NO_AGENTOBJ\t0x1630\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1630\n\t$LFS mkdir -i 1 $DIR/$tdir/dummy ||\n\t\terror \"(1) Fail to create $DIR/$tdir/dummy\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\t$START_NAMESPACE -r || error \"(2) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(3) unexpected status\"\n\t}\n\n\tlocal repaired=$($SHOW_NAMESPACE |\n\t\t\t awk '/^dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to repair the lost agent object: $repaired\"\n\n\t$START_NAMESPACE -r || error \"(5) Fail to start LFSCK for namespace!\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_NAMESPACE\n\t\terror \"(6) unexpected status\"\n\t}\n\n\trepaired=$($SHOW_NAMESPACE | awk '/^dirent_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(7) Unexpected repairing: $repaired\"\n}\nrun_test 34 \"LFSCK can rebuild the lost agent object\"\n\ntest_35()\n{\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tlfsck_prep 1 1\n\n\t#define OBD_FAIL_LFSCK_NO_AGENTENT\t0x1631\n\tdo_facet mds2 $LCTL set_param fail_loc=0x1631\n\t$LFS mkdir -i 1 $DIR/$tdir/dummy ||\n\t\terror \"(1) Fail to create $DIR/$tdir/dummy\"\n\n\tsync; sleep 3\n\tdo_facet mds2 $LCTL set_param fail_loc=0\n\t$START_NAMESPACE -A -r || error \"(2) Fail to start LFSCK for namespace!\"\n\twait_update_facet mds2 \"$LCTL get_param -n \\\n\t\tmdd.$(facet_svc mds2).lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\terror \"(3) MDS${k} is not the expected 'completed'\"\n\n\tlocal repaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t\t awk '/^agent_entries_repaired/ { print $2 }')\n\t[ $repaired -eq 1 ] ||\n\t\terror \"(4) Fail to repair the lost agent entry: $repaired\"\n\n\techo \"stopall to cleanup object cache\"\n\tstopall > /dev/null\n\techo \"setupall\"\n\tsetupall > /dev/null\n\n\t$START_NAMESPACE -A -r || error \"(5) Fail to start LFSCK for namespace!\"\n\twait_update_facet mds2 \"$LCTL get_param -n \\\n\t\tmdd.$(facet_svc mds2).lfsck_namespace |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" $LTIME ||\n\t\terror \"(6) MDS${k} is not the expected 'completed'\"\n\n\trepaired=$(do_facet mds2 $LCTL get_param -n \\\n\t\t   mdd.$(facet_svc mds2).lfsck_namespace |\n\t\t   awk '/^agent_entries_repaired/ { print $2 }')\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(7) Unexpected repairing: $repaired\"\n}\nrun_test 35 \"LFSCK can rebuild the lost agent entry\"\n\ntest_36a() {\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\" && return\n\n\techo \"#####\"\n\techo \"The target MDT-object's LOV EA corrupted as to lose one of the \"\n\techo \"mirrors information. The layout LFSCK should rebuild the LOV EA \"\n\techo \"with the PFID EA of related OST-object(s) belong to the mirror.\"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\tlfs df $DIR\n\tlfs df -i $DIR\n\tlctl get_param osc.*.*grant*\n\tstack_trap \"lfs df $DIR; lfs df -i $DIR; lctl get_param osc.*.*grant*\"\n\n\t$LFS setstripe -N -E 1M -o 0,1 -E -1 -o 2 -N -E 2M -o 1,2 -E -1 -o 0 \\\n\t\t-N -E 3M -o 2,0 -E -1 -o 1 $DIR/$tdir/f0 ||\n\t\terror \"(0) Fail to create mirror file $DIR/$tdir/f0\"\n\t$LFS setstripe -N -E 1M -o 0,1 -E -1 -o 2 -N -E 2M -o 1,2 -E -1 -o 0 \\\n\t\t-N -E 3M -o 2,0 -E -1 -o 1 $DIR/$tdir/f1 ||\n\t\terror \"(1) Fail to create mirror file $DIR/$tdir/f1\"\n\t$LFS setstripe -N -E 1M -o 0,1 -E -1 -o 2 -N -E 2M -o 1,2 -E -1 -o 0 \\\n\t\t-N -E 3M -o 2,0 -E -1 -o 1 $DIR/$tdir/f2 ||\n\t\terror \"(2) Fail to create mirror file $DIR/$tdir/f2\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=4 ||\n\t\terror \"(3) Fail to write $DIR/$tdir/f0\"\n\tdd if=/dev/zero of=$DIR/$tdir/f1 bs=1M count=4 ||\n\t\terror \"(4) Fail to write $DIR/$tdir/f1\"\n\tdd if=/dev/zero of=$DIR/$tdir/f2 bs=1M count=4 ||\n\t\terror \"(5) Fail to write $DIR/$tdir/f2\"\n\n\t$LFS mirror resync $DIR/$tdir/f0 ||\n\t\terror \"(6) Fail to resync $DIR/$tdir/f0\"\n\t$LFS mirror resync $DIR/$tdir/f1 ||\n\t\terror \"(7) Fail to resync $DIR/$tdir/f1\"\n\t$LFS mirror resync $DIR/$tdir/f2 ||\n\t\terror \"(8) Fail to resync $DIR/$tdir/f2\"\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t$LFS getstripe $DIR/$tdir/f0 ||\n\t\terror \"(9) Fail to getstripe for $DIR/$tdir/f0\"\n\t$LFS getstripe $DIR/$tdir/f1 ||\n\t\terror \"(10) Fail to getstripe for $DIR/$tdir/f1\"\n\t$LFS getstripe $DIR/$tdir/f2 ||\n\t\terror \"(11) Fail to getstripe for $DIR/$tdir/f2\"\n\n\techo \"Inject failure, to simulate the case of missing one mirror in LOV\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\n\t$LFS mirror split --mirror-id 1 -d $DIR/$tdir/f0 ||\n\t\terror \"(12) Fail to split 1st mirror from $DIR/$tdir/f0\"\n\t$LFS mirror split --mirror-id 2 -d $DIR/$tdir/f1 ||\n\t\terror \"(13) Fail to split 2nd mirror from $DIR/$tdir/f1\"\n\t$LFS mirror split --mirror-id 3 -d $DIR/$tdir/f2 ||\n\t\terror \"(14) Fail to split 3rd mirror from $DIR/$tdir/f2\"\n\n\tsync\n\tsleep 2\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\n\t$LFS getstripe $DIR/$tdir/f0 | grep \"lcme_mirror_id:.*1\" &&\n\t\terror \"(15) The 1st of mirror is not destroyed\"\n\t$LFS getstripe $DIR/$tdir/f1 | grep \"lcme_mirror_id:.*2\" &&\n\t\terror \"(16) The 2nd of mirror is not destroyed\"\n\t$LFS getstripe $DIR/$tdir/f2 | grep \"lcme_mirror_id:.*3\" &&\n\t\terror \"(17) The 3rd of mirror is not destroyed\"\n\n\tlocal mirrors\n\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f0)\n\t[ $mirrors -eq 2 ] || error \"(18) $DIR/$tdir/f0 has $mirrors mirrors\"\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f1)\n\t[ $mirrors -eq 2 ] || error \"(19) $DIR/$tdir/f1 has $mirrors mirrors\"\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f2)\n\t[ $mirrors -eq 2 ] || error \"(20) $DIR/$tdir/f2 has $mirrors mirrors\"\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(21) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 ||\n\t\t\terror \"(22) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(23) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal repaired=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t mdd.$(facet_svc mds1).lfsck_layout |\n\t\t\t awk '/^repaired_orphan/ { print $2 }')\n\t[ $repaired -eq 9 ] ||\n\t\terror \"(24) Expect 9 fixed on mds1, but got: $repaired\"\n\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f0)\n\t[ $mirrors -eq 3 ] || error \"(25) $DIR/$tdir/f0 has $mirrors mirrors\"\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f1)\n\t[ $mirrors -eq 3 ] || error \"(26) $DIR/$tdir/f1 has $mirrors mirrors\"\n\tmirrors=$($LFS getstripe -N $DIR/$tdir/f2)\n\t[ $mirrors -eq 3 ] || error \"(27) $DIR/$tdir/f2 has $mirrors mirrors\"\n\n\t$LFS getstripe $DIR/$tdir/f0 | grep \"lcme_mirror_id:.*1\" || {\n\t\t$LFS getstripe $DIR/$tdir/f0\n\t\terror \"(28) The 1st of mirror is not recovered\"\n\t}\n\n\t$LFS getstripe $DIR/$tdir/f1 | grep \"lcme_mirror_id:.*2\" || {\n\t\t$LFS getstripe $DIR/$tdir/f1\n\t\terror \"(29) The 2nd of mirror is not recovered\"\n\t}\n\n\t$LFS getstripe $DIR/$tdir/f2 | grep \"lcme_mirror_id:.*3\" || {\n\t\t$LFS getstripe $DIR/$tdir/f2\n\t\terror \"(30) The 3rd of mirror is not recovered\"\n\t}\n}\nrun_test 36a \"rebuild LOV EA for mirrored file (1)\"\n\ntest_36b() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\" && return\n\n\techo \"#####\"\n\techo \"The mirrored file lost its MDT-object, but relatd OST-objects \"\n\techo \"are still there. The layout LFSCK should rebuild the LOV EA \"\n\techo \"with the PFID EA of related OST-object(s) belong to the file. \"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setstripe -N -E 1M -o 0,1 -E -1 -o 2 -N -E 2M -o 1,2 -E -1 -o 0 \\\n\t\t-N -E 3M -o 2,0 -E -1 -o 1 $DIR/$tdir/f0 ||\n\t\terror \"(0) Fail to create mirror file $DIR/$tdir/f0\"\n\n\tlocal fid=$($LFS path2fid $DIR/$tdir/f0)\n\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=4 ||\n\t\terror \"(1) Fail to write $DIR/$tdir/f0\"\n\t$LFS mirror resync $DIR/$tdir/f0 ||\n\t\terror \"(2) Fail to resync $DIR/$tdir/f0\"\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t$LFS getstripe $DIR/$tdir/f0 ||\n\t\terror \"(3) Fail to getstripe for $DIR/$tdir/f0\"\n\n\techo \"Inject failure, to simulate the case of missing the MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/f0 || error \"(4) Fail to remove $DIR/$tdir/f0\"\n\n\tsync\n\tsleep 2\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(5) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 ||\n\t\t\terror \"(6) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(7) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal count=$(do_facet mds1 $LCTL get_param -n \\\n\t\t      mdd.$(facet_svc mds1).lfsck_layout |\n\t\t      awk '/^repaired_orphan/ { print $2 }')\n\t[ $count -eq 9 ] || error \"(8) Expect 9 fixed on mds1, but got: $count\"\n\n\tlocal name=$MOUNT/.lustre/lost+found/MDT0000/${fid}-R-0\n\tcount=$($LFS getstripe --mirror-count $name)\n\t[ $count -eq 3 ] || error \"(9) $DIR/$tdir/f0 has $count mirrors\"\n\n\tcount=$($LFS getstripe --component-count $name)\n\t[ $count -eq 6 ] || error \"(10) $DIR/$tdir/f0 has $count components\"\n\n\t$LFS getstripe $name | grep \"lcme_mirror_id:.*1\" || {\n\t\t$LFS getstripe $name\n\t\terror \"(11) The 1st of mirror is not recovered\"\n\t}\n\n\t$LFS getstripe $name | grep \"lcme_mirror_id:.*2\" || {\n\t\t$LFS getstripe $name\n\t\terror \"(12) The 2nd of mirror is not recovered\"\n\t}\n\n\t$LFS getstripe $name | grep \"lcme_mirror_id:.*3\" || {\n\t\t$LFS getstripe $name\n\t\terror \"(13) The 3rd of mirror is not recovered\"\n\t}\n}\nrun_test 36b \"rebuild LOV EA for mirrored file (2)\"\n\ntest_36c() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\" && return\n\n\techo \"#####\"\n\techo \"The mirrored file has been modified, not resynced yet, then \"\n\techo \"lost its MDT-object, but relatd OST-objects are still there. \"\n\techo \"The layout LFSCK should rebuild the LOV EA and relatd status \"\n\techo \"with the PFID EA of related OST-object(s) belong to the file. \"\n\techo \"#####\"\n\n\tcheck_mount_and_prep\n\n\t$LFS setstripe -N -E 1M -o 0,1 -E -1 -o 2 -N -E 2M -o 1,2 -E -1 -o 0 \\\n\t\t$DIR/$tdir/f0 ||\n\t\terror \"(0) Fail to create mirror file $DIR/$tdir/f0\"\n\n\tlocal fid=$($LFS path2fid $DIR/$tdir/f0)\n\n\t# The 1st dd && resync makes all related OST-objects have been written\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=4 ||\n\t\terror \"(1.1) Fail to write $DIR/$tdir/f0\"\n\t$LFS mirror resync $DIR/$tdir/f0 ||\n\t\terror \"(1.2) Fail to resync $DIR/$tdir/f0\"\n\t# The 2nd dd makes one mirror to be stale\n\tdd if=/dev/zero of=$DIR/$tdir/f0 bs=1M count=4 ||\n\t\terror \"(1.3) Fail to write $DIR/$tdir/f0\"\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t$LFS getstripe $DIR/$tdir/f0 ||\n\t\terror \"(2) Fail to getstripe for $DIR/$tdir/f0\"\n\n\tlocal saved_flags1=$($LFS getstripe $DIR/$tdir/f0 | head -n 10 |\n\t\t\t     awk '/lcme_flags/ { print $2 }')\n\tlocal saved_flags2=$($LFS getstripe $DIR/$tdir/f0 | tail -n 10 |\n\t\t\t     awk '/lcme_flags/ { print $2 }')\n\n\techo \"Inject failure, to simulate the case of missing the MDT-object\"\n\t#define OBD_FAIL_LFSCK_LOST_MDTOBJ\t0x1616\n\tdo_facet mds1 $LCTL set_param fail_loc=0x1616\n\trm -f $DIR/$tdir/f0 || error \"(3) Fail to remove $DIR/$tdir/f0\"\n\n\tsync\n\tsleep 2\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\n\techo \"Trigger layout LFSCK on all devices to find out orphan OST-object\"\n\t$START_LAYOUT -r -o || error \"(4) Fail to start LFSCK for layout!\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# The LFSCK status query internal is 30 seconds. For the case\n\t\t# of some LFSCK_NOTIFY RPCs failure/lost, we will wait enough\n\t\t# time to guarantee the status sync up.\n\t\twait_update_facet mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 ||\n\t\t\terror \"(5) MDS${k} is not the expected 'completed'\"\n\tdone\n\n\tfor k in $(seq $OSTCOUNT); do\n\t\tlocal cur_status=$(do_facet ost${k} $LCTL get_param -n \\\n\t\t\t\tobdfilter.$(facet_svc ost${k}).lfsck_layout |\n\t\t\t\tawk '/^status/ { print $2 }')\n\t\t[ \"$cur_status\" == \"completed\" ] ||\n\t\terror \"(6) OST${k} Expect 'completed', but got '$cur_status'\"\n\tdone\n\n\tlocal count=$(do_facet mds1 $LCTL get_param -n \\\n\t\t      mdd.$(facet_svc mds1).lfsck_layout |\n\t\t      awk '/^repaired_orphan/ { print $2 }')\n\t[ $count -eq 6 ] || error \"(7) Expect 9 fixed on mds1, but got: $count\"\n\n\tlocal name=$MOUNT/.lustre/lost+found/MDT0000/${fid}-R-0\n\tcount=$($LFS getstripe --mirror-count $name)\n\t[ $count -eq 2 ] || error \"(8) $DIR/$tdir/f0 has $count mirrors\"\n\n\tcount=$($LFS getstripe --component-count $name)\n\t[ $count -eq 4 ] || error \"(9) $DIR/$tdir/f0 has $count components\"\n\n\tlocal flags=$($LFS getstripe $name | head -n 10 |\n\t\tawk '/lcme_flags/ { print $2 }')\n\t[ \"$flags\" == \"$saved_flags1\" ] || {\n\t\t$LFS getstripe $name\n\t\terror \"(10) expect flags $saved_flags1, got $flags\"\n\t}\n\n\tflags=$($LFS getstripe $name | tail -n 10 |\n\t\tawk '/lcme_flags/ { print $2 }')\n\t[ \"$flags\" == \"$saved_flags2\" ] || {\n\t\t$LFS getstripe $name\n\t\terror \"(11) expect flags $saved_flags2, got $flags\"\n\t}\n}\nrun_test 36c \"rebuild LOV EA for mirrored file (3)\"\n\ntest_37()\n{\n\tlocal PID\n\tlocal rc\n\tlocal t_dir=\"$DIR/$tdir/d0\"\n\tcheck_mount_and_prep\n\n\t$LFS mkdir -i 0 $t_dir || error \"(2) Fail to mkdir $t_dir on MDT0\"\n\tmultiop_bg_pause $t_dir D_c || { error \"multiop failed: $?\"; return 1; }\n\tPID=$!\n\trmdir $t_dir\n\n\t$START_NAMESPACE -r -A || {\n\t    error \"(3) Fail to start LFSCK for namespace!\"; kill -USR1 $PID; }\n\n\twait_all_targets_blocked namespace completed 4\n\tstat $t_dir && rc=1\n\tkill -USR1 $PID\n\treturn $rc\n}\nrun_test 37 \"LFSCK must skip a ORPHAN\"\n\ntest_38()\n{\n\t[[ $MDS1_VERSION -le $(version_code 2.12.51) ]] &&\n\t\tskip \"Need MDS version newer than 2.12.51\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal uuid1=$(cat /proc/sys/kernel/random/uuid)\n\tlocal uuid2=$(cat /proc/sys/kernel/random/uuid)\n\n\t# create foreign file\n\t$LFS setstripe --foreign=daos --flags 0xda05 \\\n\t\t-x \"${uuid1}@${uuid2}\" $DIR/$tdir/$tfile ||\n\t\terror \"$DIR/$tdir/$tfile: create failed\"\n\n\t$LFS getstripe -v $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_magic:.*0x0BD70BD0\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign magic\"\n\t# lfm_length is LOV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t$LFS getstripe -v $DIR/$tdir/$tfile | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign size\"\n\t$LFS getstripe -v $DIR/$tdir/$tfile | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign type\"\n\t$LFS getstripe -v $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_flags:.*0x0000DA05\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign flags\"\n\t$LFS getstripe $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_value:.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign value\"\n\n\t# modify striping should fail\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile &&\n\t\terror \"$DIR/$tdir/$tfile: setstripe should fail\"\n\n\t$START_NAMESPACE -r -A || error \"Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 1\n\n\t# check that \"global\" namespace_repaired == 0 !!!\n\tlocal repaired=$(do_facet mds1 \\\n\t\t\t \"$LCTL lfsck_query -t all -M ${FSNAME}-MDT0000 |\n\t\t\t awk '/^namespace_repaired/ { print \\\\\\$2 }'\")\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(2) Expect no namespace repair, but got: $repaired\"\n\n\t$START_LAYOUT -A -r || error \"Fail to start LFSCK for layout\"\n\n\twait_all_targets_blocked layout completed 2\n\n\t# check that \"global\" layout_repaired == 0 !!!\n\tlocal repaired=$(do_facet mds1 \\\n\t\t\t \"$LCTL lfsck_query -t all -M ${FSNAME}-MDT0000 |\n\t\t\t awk '/^layout_repaired/ { print \\\\\\$2 }'\")\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(2) Expect no layout repair, but got: $repaired\"\n\n\techo \"post-lfsck checks of foreign file\"\n\n\t$LFS getstripe -v $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_magic:.*0x0BD70BD0\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign magic\"\n\t# lfm_length is LOV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t$LFS getstripe -v $DIR/$tdir/$tfile | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign size\"\n\t$LFS getstripe -v $DIR/$tdir/$tfile | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign type\"\n\t$LFS getstripe -v $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_flags:.*0x0000DA05\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign flags\"\n\t$LFS getstripe $DIR/$tdir/$tfile |\n\t\tgrep \"lfm_value:.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign value\"\n\n\t# modify striping should fail\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile &&\n\t\terror \"$DIR/$tdir/$tfile: setstripe should fail\"\n\n\t# R/W should fail\n\tcat $DIR/$tdir/$tfile && \"$DIR/$tdir/$tfile: read should fail\"\n\tcat /etc/passwd > $DIR/$tdir/$tfile &&\n\t\terror \"$DIR/$tdir/$tfile: write should fail\"\n\n\t#remove foreign file\n\trm $DIR/$tdir/$tfile ||\n\t\terror \"$DIR/$tdir/$tfile: remove of foreign file has failed\"\n}\nrun_test 38 \"LFSCK does not break foreign file and reverse is also true\"\n\ntest_39()\n{\n\t[[ $(lustre_version_code $SINGLEMDS) -le $(version_code 2.12.51) ]] &&\n\t\tskip \"Need MDS version newer than 2.12.51\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal uuid1=$(cat /proc/sys/kernel/random/uuid)\n\tlocal uuid2=$(cat /proc/sys/kernel/random/uuid)\n\n\t# create foreign dir\n\t$LFS mkdir --foreign=daos --xattr=\"${uuid1}@${uuid2}\" --flags=0xda05 \\\n\t\t$DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/$tdir/${tdir}2: create failed\"\n\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_magic:.*0x0CD50CD0\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA magic\"\n\t# lfm_length is LMV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t# - sizeof(lfm_type) - sizeof(lfm_flags)\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA size\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA type\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_flags:.*0x0000DA05\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA flags\"\n\t$LFS getdirstripe $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_value.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA value\"\n\n\t# file create in dir should fail\n\ttouch $DIR/$tdir/${tdir}2/$tfile &&\n\t\t\"$DIR/${tdir}2: file create should fail\"\n\n\t# chmod should work\n\tchmod 777 $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chmod failed\"\n\n\t# chown should work\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chown failed\"\n\n\t$START_NAMESPACE -r -A || error \"Fail to start LFSCK for namespace\"\n\n\twait_all_targets_blocked namespace completed 1\n\n\t# check that \"global\" namespace_repaired == 0 !!!\n\tlocal repaired=$(do_facet mds1 \\\n\t\t\t \"$LCTL lfsck_query -t all -M ${FSNAME}-MDT0000 |\n\t\t\t awk '/^namespace_repaired/ { print \\\\\\$2 }'\")\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(2) Expect nothing to be repaired, but got: $repaired\"\n\n\t$START_LAYOUT -A -r || error \"Fail to start LFSCK for layout\"\n\n\twait_all_targets_blocked layout completed 2\n\n\t# check that \"global\" layout_repaired == 0 !!!\n\tlocal repaired=$(do_facet mds1 \\\n\t\t\t \"$LCTL lfsck_query -t all -M ${FSNAME}-MDT0000 |\n\t\t\t awk '/^layout_repaired/ { print \\\\\\$2 }'\")\n\t[ $repaired -eq 0 ] ||\n\t\terror \"(2) Expect no layout repair, but got: $repaired\"\n\n\techo \"post-lfsck checks of foreign dir\"\n\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_magic:.*0x0CD50CD0\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA magic\"\n\t# lfm_length is LMV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t# - sizeof(lfm_type) - sizeof(lfm_flags)\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA size\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA type\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_flags:.*0x0000DA05\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA flags\"\n\t$LFS getdirstripe $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_value.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA value\"\n\n\t# file create in dir should fail\n\ttouch $DIR/$tdir/${tdir}2/$tfile &&\n\t\t\"$DIR/${tdir}2: file create should fail\"\n\n\t# chmod should work\n\tchmod 777 $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chmod failed\"\n\n\t# chown should work\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chown failed\"\n\n\t#remove foreign dir\n\trmdir $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/$tdir/${tdir}2: remove of foreign dir has failed\"\n}\nrun_test 39 \"LFSCK does not break foreign dir and reverse is also true\"\n\ntest_40a() {\n\t[[ $MDSCOUNT -ge 2 ]] || skip \"needs >= 2 MDTs\"\n\n\tcheck_mount_and_prep\n\t$LFS mkdir -i 1 $DIR/$tdir/dir1\n\t$LFS setstripe -E 1M -c1 -S 1M -E 128M -c2 -S 4M -E eof $DIR/$tdir/dir1\n\n\ttouch $DIR/$tdir/dir1/f1\n\tlocal layout1=$(get_layout_param $DIR/$tdir/dir1/f1)\n\n\techo \"Migrate $DIR/$tdir/dir1 from MDT1 to MDT0\"\n\t$LFS migrate -m 0 $DIR/$tdir/dir1\n\n\techo \"trigger LFSCK for layout\"\n\tdo_facet $SINGLEMDS $LCTL lfsck_start -M ${MDT_DEV} -t layout -r\n\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tmdd.${MDT_DEV}.lfsck_layout |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 32 || {\n\t\t$SHOW_LAYOUT\n\t\terror \"(2) unexpected status\"\n\t}\n\n\tlocal layout2=$(get_layout_param $DIR/$tdir/dir1/f1)\n\n\t[[ \"$layout1\" == \"$layout2\" ]] || error \"layout lost after lfsck\"\n}\nrun_test 40a \"LFSCK correctly fixes lmm_oi in composite layout\"\n\n# restore MDS/OST size\nMDSSIZE=${SAVED_MDSSIZE}\nOSTSIZE=${SAVED_OSTSIZE}\nOSTCOUNT=${SAVED_OSTCOUNT}\n\n# cleanup the system at last\nREFORMAT=\"yes\" cleanup_and_setup_lustre\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 5875}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$SANITY_LNET_EXCEPT \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n# skip test ARM testing until they are fixed\nif [[ $(uname -m) = aarch64 ]]; then\n\t# bug number for skipped test: LU-13704 LU-13701 LU-13701 LU-13701\n\tALWAYS_EXCEPT+=\"               204      205      206      207 \"\nfi\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n\n. $LUSTRE/tests/test-framework.sh\nCLEANUP=${CLEANUP:-:}\nSETUP=${SETUP:-:}\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nbuild_test_filter\n\nexport LNETCTL=${LNETCTL:-\"$LUSTRE/../lnet/utils/lnetctl\"}\n[ ! -f \"$LNETCTL\" ] &&\n\texport LNETCTL=$(which lnetctl 2> /dev/null)\n[[ -z $LNETCTL ]] && skip \"Need lnetctl\"\n\nrestore_mounts=false\n\nif is_mounted $MOUNT || is_mounted $MOUNT2; then\n\tcleanupall || error \"Failed cleanup prior to test execution\"\n\trestore_mounts=true\nfi\n\ncleanup_lnet() {\n\techo \"Cleaning up LNet\"\n\tlsmod | grep -q lnet &&\n\t\t$LNETCTL lnet unconfigure 2>/dev/null\n\tunload_modules\n}\n\nrestore_modules=false\nif module_loaded lnet ; then\n\tcleanup_lnet || error \"Failed to unload modules before test execution\"\n\trestore_modules=true\nfi\n\ncleanup_testsuite() {\n\ttrap \"\" EXIT\n\trm -f $TMP/sanity-dlc*\n\tcleanup_netns\n\tcleanup_lnet\n\tif $restore_mounts; then\n\t\tsetupall || error \"Failed to setup Lustre after test execution\"\n\telif $restore_modules; then\n\t\tload_modules ||\n\t\t\terror \"Couldn't load modules after test execution\"\n\tfi\n\treturn 0\n}\n\nload_lnet() {\n\tload_module ../libcfs/libcfs/libcfs\n\t# Prevent local MODOPTS_LIBCFS being passed as part of environment\n\t# variable to remote nodes\n\tunset MODOPTS_LIBCFS\n\n\tset_default_debug \"neterror net nettrace malloc\"\n\tload_module ../lnet/lnet/lnet \"$@\"\n\n\tLNDPATH=${LNDPATH:-\"../lnet/klnds\"}\n\tif [ -z \"$LNETLND\" ]; then\n\t\tcase $NETTYPE in\n\t\to2ib*)  LNETLND=\"o2iblnd/ko2iblnd\" ;;\n\t\ttcp*)   LNETLND=\"socklnd/ksocklnd\" ;;\n\t\t*)      local lnd=\"${NETTYPE%%[0-9]}lnd\"\n\t\t\t[ -f \"$LNDPATH/$lnd/k$lnd.ko\" ] &&\n\t\t\t\tLNETLND=\"$lnd/k$lnd\" ||\n\t\t\t\tLNETLND=\"socklnd/ksocklnd\"\n\t\tesac\n\tfi\n\tload_module ../lnet/klnds/$LNETLND\n}\n\ndo_lnetctl() {\n\techo \"$LNETCTL $@\"\n\t$LNETCTL \"$@\"\n}\n\nTESTNS='test_ns'\nFAKE_IF=\"test1pg\"\nFAKE_IP=\"10.1.2.3\"\ndo_ns() {\n\techo \"ip netns exec $TESTNS $@\"\n\tip netns exec $TESTNS \"$@\"\n}\n\nsetup_fakeif() {\n\tlocal netns=\"$1\"\n\n\tlocal netns_arg=\"\"\n\t[[ -n $netns ]] &&\n\t\tnetns_arg=\"netns $netns\"\n\n\tip link add 'test1pl' type veth peer name $FAKE_IF $netns_arg\n\tip link set 'test1pl' up\n\tif [[ -n $netns ]]; then\n\t\tdo_ns ip addr add \"${FAKE_IP}/31\" dev $FAKE_IF\n\t\tdo_ns ip link set $FAKE_IF up\n\telse\n\t\tip addr add \"${FAKE_IP}/31\" dev $FAKE_IF\n\t\tip link set $FAKE_IF up\n\tfi\n}\n\ncleanup_fakeif() {\n\tip link show test1pl >& /dev/null && ip link del test1pl || return 0\n}\n\nsetup_netns() {\n\tcleanup_netns\n\n\tip netns add $TESTNS\n\tsetup_fakeif $TESTNS\n}\n\ncleanup_netns() {\n\t(ip netns list | grep -q $TESTNS) && ip netns del $TESTNS\n\tcleanup_fakeif\n}\n\nconfigure_dlc() {\n\techo \"Loading LNet and configuring DLC\"\n\tload_lnet\n\tdo_lnetctl lnet configure\n}\n\nGLOBAL_YAML_FILE=$TMP/sanity-lnet-global.yaml\ndefine_global_yaml() {\n\t$LNETCTL export --backup >${GLOBAL_YAML_FILE} ||\n\t\terror \"Failed to export global yaml $?\"\n}\n\nreinit_dlc() {\n\tif lsmod | grep -q lnet; then\n\t\tdo_lnetctl lnet unconfigure ||\n\t\t\terror \"lnetctl lnet unconfigure failed $?\"\n\t\tdo_lnetctl lnet configure ||\n\t\t\terror \"lnetctl lnet configure failed $?\"\n\telse\n\t\tconfigure_dlc || error \"configure_dlc failed $?\"\n\tfi\n\tdefine_global_yaml\n}\n\nappend_global_yaml() {\n\t[[ ! -e ${GLOBAL_YAML_FILE} ]] &&\n\t\terror \"Missing global yaml at ${GLOBAL_YAML_FILE}\"\n\n\tcat ${GLOBAL_YAML_FILE} >> $TMP/sanity-lnet-$testnum-expected.yaml\n}\n\ncreate_base_yaml_file() {\n\tappend_global_yaml\n}\n\ncompare_yaml_files() {\n\tlocal expected=\"$TMP/sanity-lnet-$testnum-expected.yaml\"\n\tlocal actual=\"$TMP/sanity-lnet-$testnum-actual.yaml\"\n\tlocal rc=0\n\t! [[ -e $expected ]] && echo \"$expected not found\" && return 1\n\t! [[ -e $actual ]] && echo \"$actual not found\" && return 1\n\tdiff -upN ${actual} ${expected} || rc=$?\n\techo \"Expected:\"\n\tcat $expected\n\techo \"Actual:\"\n\tcat $actual\n\treturn $rc\n}\n\nvalidate_nid() {\n\tlocal nid=\"$1\"\n\tlocal net=\"${nid//*@/}\"\n\tlocal addr=\"${nid//@*/}\"\n\n\tlocal num_re='[0-9]\\+'\n\tlocal ip_re=\"[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\"\n\n\tif [[ $net =~ gni[0-9]* ]]; then\n\t\t[[ $addr =~ ${num_re} ]] && return 0\n\telse\n\t\t[[ $addr =~ ${ip_re} ]] && return 0\n\tfi\n}\n\nvalidate_nids() {\n\tlocal yfile=$TMP/sanity-lnet-$testnum-actual.yaml\n\tlocal primary_nids=$(awk '/- primary nid:/{print $NF}' $yfile | xargs echo)\n\tlocal secondary_nids=$(awk '/- nid:/{print $NF}' $yfile | xargs echo)\n\tlocal gateway_nids=$(awk '/gateway:/{print $NF}' $yfile | xargs echo)\n\n\tlocal nid\n\tfor nid in $primary_nids $secondary_nids; do\n\t\tvalidate_nid \"$nid\" || error \"Bad NID \\\"${nid}\\\"\"\n\tdone\n\treturn 0\n}\n\nvalidate_peer_nids() {\n\tlocal num_peers=\"$1\"\n\tlocal nids_per_peer=\"$2\"\n\n\tlocal expect_p=\"$num_peers\"\n\t# The primary nid also shows up in the list of secondary nids\n\tlocal expect_s=\"$(($num_peers + $(($nids_per_peer*$num_peers))))\"\n\n\tlocal actual_p=$(grep -c -- '- primary nid:' $TMP/sanity-lnet-$testnum-actual.yaml)\n\tlocal actual_s=$(grep -c -- '- nid:' $TMP/sanity-lnet-$testnum-actual.yaml)\n\tif [[ $expect_p -ne $actual_p ]]; then\n\t\tcompare_yaml_files\n\t\terror \"Expected $expect_p but found $actual_p primary nids\"\n\telif [[ $expect_s -ne $actual_s ]]; then\n\t\tcompare_yaml_files\n\t\terror \"Expected $expect_s but found $actual_s secondary nids\"\n\tfi\n\tvalidate_nids\n}\n\nvalidate_gateway_nids() {\n\tlocal expect_gw=$(grep -c -- 'gateway:' $TMP/sanity-lnet-$testnum-expected.yaml)\n\tlocal actual_gw=$(grep -c -- 'gateway:' $TMP/sanity-lnet-$testnum-actual.yaml)\n\tif [[ $expect_gw -ne $actual_gw ]]; then\n\t\tcompare_yaml_files\n\t\terror \"Expected $expect_gw gateways but found $actual_gw gateways\"\n\tfi\n\tvalidate_nids\n}\n\ncleanupall -f\nsetup_netns || error \"setup_netns failed with $?\"\n\nstack_trap 'cleanup_testsuite' EXIT\n\ntest_0() {\n\tload_module ../lnet/lnet/lnet || error \"Failed to load module rc = $?\"\n\tdo_lnetctl lnet configure || error \"lnet configure failed rc = $?\"\n\tdefine_global_yaml\n\treinit_dlc || return $?\n\tdo_lnetctl import <  ${GLOBAL_YAML_FILE} || error \"Import failed $?\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcreate_base_yaml_file\n\tcompare_yaml_files || error \"Configuration changed after import\"\n}\nrun_test 0 \"Export empty config, import the config, compare\"\n\ncompare_peer_add() {\n\tlocal prim_nid=\"${1:+--prim_nid $1}\"\n\tlocal nid=\"${2:+--nid $2}\"\n\n\tlocal actual=\"$TMP/sanity-lnet-$testnum-actual.yaml\"\n\n\tdo_lnetctl peer add ${prim_nid} ${nid} || error \"peer add failed $?\"\n\t$LNETCTL export --backup > $actual || error \"export failed $?\"\n\tcompare_yaml_files\n\treturn $?\n}\n\ntest_1() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 1.1.1.1@tcp\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"1.1.1.1@tcp\"\n}\nrun_test 1 \"Add peer with single nid (tcp)\"\n\ntest_2() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 2.2.2.2@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 2.2.2.2@o2ib\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"2.2.2.2@o2ib\"\n}\nrun_test 2 \"Add peer with single nid (o2ib)\"\n\ntest_3() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 3.3.3.3@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 3.3.3.3@tcp\n        - nid: 3.3.3.3@o2ib\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"3.3.3.3@tcp\" \"3.3.3.3@o2ib\"\n}\nrun_test 3 \"Add peer with tcp primary o2ib secondary\"\n\ntest_4() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 4.4.4.4@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 4.4.4.4@tcp\n        - nid: 4.4.4.1@tcp\n        - nid: 4.4.4.2@tcp\n        - nid: 4.4.4.3@tcp\nEOF\n\tappend_global_yaml\n\techo \"Add peer with nidrange (tcp)\"\n\tcompare_peer_add \"4.4.4.4@tcp\" \"4.4.4.[1-3]@tcp\"\n\n\techo \"Add peer with nidrange that overlaps primary nid (tcp)\"\n\tcompare_peer_add \"4.4.4.4@tcp\" \"4.4.4.[1-4]@tcp\"\n}\nrun_test 4 \"Add peer with nidrange (tcp)\"\n\ntest_5() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 5.5.5.5@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 5.5.5.5@o2ib\n        - nid: 5.5.5.1@o2ib\n        - nid: 5.5.5.2@o2ib\n        - nid: 5.5.5.3@o2ib\n        - nid: 5.5.5.4@o2ib\nEOF\n\tappend_global_yaml\n\techo \"Add peer with nidrange (o2ib)\"\n\tcompare_peer_add \"5.5.5.5@o2ib\" \"5.5.5.[1-4]@o2ib\"\n\n\techo \"Add peer with nidranage that overlaps primary nid (o2ib)\"\n\tcompare_peer_add \"5.5.5.5@o2ib\" \"5.5.5.[1-4]@o2ib\"\n}\nrun_test 5 \"Add peer with nidrange (o2ib)\"\n\ntest_6() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 6.6.6.6@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 6.6.6.6@tcp\n        - nid: 6.6.6.0@tcp\n        - nid: 6.6.6.2@tcp\n        - nid: 6.6.6.4@tcp\n        - nid: 6.6.7.0@tcp\n        - nid: 6.6.7.2@tcp\n        - nid: 6.6.7.4@tcp\n        - nid: 6.6.1.0@o2ib\n        - nid: 6.6.1.3@o2ib\n        - nid: 6.6.1.6@o2ib\n        - nid: 6.6.3.0@o2ib\n        - nid: 6.6.3.3@o2ib\n        - nid: 6.6.3.6@o2ib\n        - nid: 6@gni\n        - nid: 10@gni\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"6.6.6.6@tcp\" \\\n\t\t\"6.6.[6-7].[0-4/2]@tcp,6.6.[1-4/2].[0-6/3]@o2ib,[6-12/4]@gni\"\n}\nrun_test 6 \"Add peer with multiple nidranges\"\n\ncompare_peer_del() {\n\tlocal prim_nid=\"${1:+--prim_nid $1}\"\n\tlocal nid=\"${2:+--nid $2}\"\n\n\tlocal actual=\"$TMP/sanity-lnet-$testnum-actual.yaml\"\n\n\tdo_lnetctl peer del ${prim_nid} ${nid} || error \"peer del failed $?\"\n\t$LNETCTL export --backup > $actual || error \"export failed $?\"\n\tcompare_yaml_files\n\treturn $?\n}\n\ntest_7() {\n\treinit_dlc || return $?\n\tcreate_base_yaml_file\n\n\techo \"Delete peer with single nid (tcp)\"\n\tdo_lnetctl peer add --prim_nid 7.7.7.7@tcp || error \"Peer add failed $?\"\n\tcompare_peer_del \"7.7.7.7@tcp\"\n\n\techo \"Delete peer with single nid (o2ib)\"\n\tdo_lnetctl peer add --prim_nid 7.7.7.7@o2ib || error \"Peer add failed $?\"\n\tcompare_peer_del \"7.7.7.7@o2ib\"\n\n\techo \"Delete peer that has multiple nids (tcp)\"\n\tdo_lnetctl peer add --prim_nid 7.7.7.7@tcp --nid 7.7.7.[8-12]@tcp ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"7.7.7.7@tcp\"\n\n\techo \"Delete peer that has multiple nids (o2ib)\"\n\tdo_lnetctl peer add --prim_nid 7.7.7.7@o2ib --nid 7.7.7.[8-12]@o2ib ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"7.7.7.7@o2ib\"\n\n\techo \"Delete peer that has both tcp and o2ib nids\"\n\tdo_lnetctl peer add --prim_nid 7.7.7.7@tcp \\\n\t\t--nid 7.7.7.[9-12]@tcp,7.7.7.[13-15]@o2ib ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"7.7.7.7@tcp\"\n\n\techo \"Delete peer with single nid (gni)\"\n\tdo_lnetctl peer add --prim_nid 7@gni || error \"Peer add failed $?\"\n\tcompare_peer_del \"7@gni\"\n\n\techo \"Delete peer that has multiple nids (gni)\"\n\tdo_lnetctl peer add --prim_nid 7@gni --nid [8-12]@gni ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"7@gni\"\n\n\techo \"Delete peer that has tcp, o2ib and gni nids\"\n\tdo_lnetctl peer add --prim_nid 7@gni \\\n\t\t--nid [8-12]@gni,7.7.7.[9-12]@tcp,7.7.7.[13-15]@o2ib ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"7@gni\"\n}\nrun_test 7 \"Various peer delete tests\"\n\ntest_8() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 8.8.8.8@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 8.8.8.8@tcp\n        - nid: 8.8.8.10@tcp\n        - nid: 8.8.8.11@tcp\n        - nid: 8.8.8.12@tcp\n        - nid: 8.8.8.14@tcp\n        - nid: 8.8.8.15@tcp\nEOF\n\tappend_global_yaml\n\n\tdo_lnetctl peer add --prim_nid 8.8.8.8@tcp --nid 8.8.8.[10-15]@tcp ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"8.8.8.8@tcp\" \"8.8.8.13@tcp\"\n}\nrun_test 8 \"Delete single secondary nid from peer (tcp)\"\n\ntest_9() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 9.9.9.9@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 9.9.9.9@tcp\nEOF\n\tappend_global_yaml\n\n\tdo_lnetctl peer add --prim_nid 9.9.9.9@tcp \\\n\t\t--nid 9.9.9.[11-16]@tcp || error \"Peer add failed $?\"\n\tcompare_peer_del \"9.9.9.9@tcp\" \"9.9.9.[11-16]@tcp\"\n}\nrun_test 9 \"Delete all secondary nids from peer (tcp)\"\n\ntest_10() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 10.10.10.10@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 10.10.10.10@tcp\n        - nid: 10.10.10.12@tcp\n        - nid: 10.10.10.13@tcp\n        - nid: 10.10.10.15@tcp\n        - nid: 10.10.10.16@tcp\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 10.10.10.10@tcp \\\n\t\t--nid 10.10.10.[12-16]@tcp || error \"Peer add failed $?\"\n\tcompare_peer_del \"10.10.10.10@tcp\" \"10.10.10.14@tcp\"\n}\nrun_test 10 \"Delete single secondary nid from peer (o2ib)\"\n\ntest_11() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 11.11.11.11@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 11.11.11.11@tcp\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 11.11.11.11@tcp \\\n\t\t--nid 11.11.11.[13-17]@tcp || error \"Peer add failed $?\"\n\tcompare_peer_del \"11.11.11.11@tcp\" \"11.11.11.[13-17]@tcp\"\n}\nrun_test 11 \"Delete all secondary nids from peer (o2ib)\"\n\ntest_12() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 12.12.12.12@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 12.12.12.12@o2ib\n        - nid: 13.13.13.13@o2ib\n        - nid: 14.13.13.13@o2ib\n        - nid: 14.15.13.13@o2ib\n        - nid: 15.17.1.5@tcp\n        - nid: 15.17.1.10@tcp\n        - nid: 15.17.1.20@tcp\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 12.12.12.12@o2ib \\\n\t\t--nid [13-14/1].[13-15/2].13.13@o2ib,[15-16/3].[17-19/4].[1].[5-20/5]@tcp ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"12.12.12.12@o2ib\" \"13.15.13.13@o2ib,15.17.1.15@tcp\"\n}\nrun_test 12 \"Delete a secondary nid from peer (tcp and o2ib)\"\n\ntest_13() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 13.13.13.13@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 13.13.13.13@o2ib\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 13.13.13.13@o2ib \\\n\t\t--nid [14-15].[1-2/1].[1].[100-254/10]@tcp,14.14.[254].14@o2ib ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"13.13.13.13@o2ib\" \\\n\t\t\"[14-15].[1-2/1].[1].[100-254/10]@tcp,14.14.[254].14@o2ib\"\n}\nrun_test 13 \"Delete all secondary nids from peer (tcp and o2ib)\"\n\ncreate_nid() {\n\tlocal num=\"$1\"\n\tlocal net=\"$2\"\n\n\tif [[ $net =~ gni* ]]; then\n\t\techo \"${num}@${net}\"\n\telse\n\t\techo \"${num}.${num}.${num}.${num}@${net}\"\n\tfi\n}\n\ncreate_mr_peer_yaml() {\n\tlocal num_peers=\"$1\"\n\tlocal secondary_nids=\"$2\"\n\tlocal net=\"$3\"\n\n\techo \"Generating peer yaml for $num_peers peers with $secondary_nids secondary nids\"\n\techo \"peer:\" >> $TMP/sanity-lnet-$testnum-expected.yaml\n\tlocal i\n\tlocal total_nids=$((num_peers + $((num_peers * secondary_nids))))\n\tlocal created=0\n\tlocal nidnum=1\n\twhile [[ $created -lt $num_peers ]]; do\n\t\tlocal primary=$(create_nid ${nidnum} ${net})\n\tcat <<EOF >> $TMP/sanity-lnet-$testnum-expected.yaml\n    - primary nid: $primary\n      Multi-Rail: True\n      peer ni:\n        - nid: $primary\nEOF\n\t\tlocal j\n\t\tlocal start=$((nidnum + 1))\n\t\tlocal end=$((nidnum + $secondary_nids))\n\t\tfor j in $(seq ${start} ${end}); do\n\t\t\tlocal nid=$(create_nid $j ${net})\n\t\t\techo \"        - nid: $nid\" >> $TMP/sanity-lnet-$testnum-expected.yaml\n\t\tdone\n\t\tnidnum=$((end + 1))\n\t\t((created++))\n\tdone\n}\n\ntest_14() {\n\treinit_dlc || return $?\n\n\techo \"Create single peer, single nid, using import\"\n\tcreate_mr_peer_yaml 1 0 tcp\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\tappend_global_yaml\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n\n\techo \"Delete single peer using import --del\"\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\trm -f $TMP/sanity-lnet-$testnum-expected.yaml\n\tcreate_base_yaml_file\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n}\nrun_test 14 \"import peer create/delete with single nid\"\n\ntest_15() {\n\treinit_dlc || return $?\n\n\techo \"Create multiple peers, single nid per peer, using import\"\n\tcreate_mr_peer_yaml 5 0 o2ib\n\t# The ordering of nids for this use-case is non-deterministic, so we\n\t# we can't just diff the expected/actual output.\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tvalidate_peer_nids 5 0\n\n\techo \"Delete multiple peers, single nid per peer, using import --del\"\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\trm -f $TMP/sanity-lnet-$testnum-expected.yaml\n\tcreate_base_yaml_file\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n}\nrun_test 15 \"import multi peer create/delete with single nid per peer\"\n\ntest_16() {\n\treinit_dlc || return $?\n\n\techo \"Create single peer, multiple nids, using import\"\n\tcreate_mr_peer_yaml 1 5 tcp\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tvalidate_peer_nids 1 5\n\n\techo \"Delete single peer, multiple nids, using import --del\"\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\trm -f $TMP/sanity-lnet-$testnum-expected.yaml\n\tcreate_base_yaml_file\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n}\nrun_test 16 \"import peer create/delete with multiple nids\"\n\ntest_17() {\n\treinit_dlc || return $?\n\n\techo \"Create multiple peers, multiple nids per peer, using import\"\n\tcreate_mr_peer_yaml 5 7 o2ib\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tvalidate_peer_nids 5 7\n\n\techo \"Delete multiple peers, multiple nids per peer, using import --del\"\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\trm -f $TMP/sanity-lnet-$testnum-expected.yaml\n\tcreate_base_yaml_file\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n}\nrun_test 17 \"import multi peer create/delete with multiple nids\"\n\ntest_18a() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 1.1.1.1@tcp\n        - nid: 2.2.2.2@tcp\n        - nid: 4.4.4.4@tcp\n        - nid: 3.3.3.3@o2ib\n        - nid: 5@gni\nEOF\n\techo \"Import peer with 5 nids\"\n\tcat $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 2.2.2.2@tcp\n        - nid: 3.3.3.3@o2ib\n        - nid: 5@gni\nEOF\n\techo \"Delete three of the nids\"\n\tcat $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 1.1.1.1@tcp\n        - nid: 4.4.4.4@tcp\nEOF\n\techo \"Check peer has expected nids remaining\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tappend_global_yaml\n\tcompare_yaml_files\n}\nrun_test 18a \"Delete a subset of nids from a single peer using import --del\"\n\ntest_18b() {\n\treinit_dlc || return $?\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 1.1.1.1@tcp\n        - nid: 2.2.2.2@tcp\n        - nid: 4.4.4.4@tcp\n        - nid: 3.3.3.3@o2ib\n        - nid: 5@gni\n    - primary nid: 6.6.6.6@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 6.6.6.6@o2ib\n        - nid: 7.7.7.7@tcp\n        - nid: 8.8.8.8@tcp\n        - nid: 9.9.9.9@tcp\n        - nid: 10@gni\nEOF\n\techo \"Import two peers with 5 nids each\"\n\tcat $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-expected.yaml ||\n\t\terror \"Import failed $?\"\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 2.2.2.2@tcp\n        - nid: 3.3.3.3@o2ib\n        - nid: 5@gni\n    - primary nid: 6.6.6.6@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 7.7.7.7@tcp\n        - nid: 8.8.8.8@tcp\n        - nid: 10@gni\nEOF\n\techo \"Delete three of the nids from each peer\"\n\tcat $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl import --del < $TMP/sanity-lnet-$testnum-expected.yaml\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 6.6.6.6@o2ib\n      Multi-Rail: True\n      peer ni:\n        - nid: 6.6.6.6@o2ib\n        - nid: 7.7.7.7@tcp\n    - primary nid: 1.1.1.1@tcp\n      Multi-Rail: True\n      peer ni:\n        - nid: 1.1.1.1@tcp\n        - nid: 4.4.4.4@tcp\nEOF\n\tappend_global_yaml\n\techo \"Check peers have expected nids remaining\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n\tvalidate_peer_nids 2 1\n}\nrun_test 18b \"Delete multiple nids from multiple peers using import --del\"\n\ntest_19() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 19@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 19@gni\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"19@gni\"\n}\nrun_test 19 \"Add peer with single nid (gni)\"\n\ntest_20() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 20@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 20@gni\n        - nid: 20.20.20.20@tcp\n        - nid: 20.20.20.20@o2ib\nEOF\n\tappend_global_yaml\n\tcompare_peer_add \"20@gni\" \"20.20.20.20@tcp,20.20.20.20@o2ib\"\n}\nrun_test 20 \"Add peer with gni primary and tcp, o2ib secondary\"\n\ntest_21() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 21@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 21@gni\n        - nid: 22@gni\n        - nid: 23@gni\n        - nid: 24@gni\n        - nid: 25@gni\nEOF\n\tappend_global_yaml\n\techo\"Add peer with nidrange (gni)\"\n\tcompare_peer_add \"21@gni\" \"[22-25]@gni\" || error\n\techo \"Add peer with nidrange that overlaps primary nid (gni)\"\n\tcompare_peer_add \"21@gni\" \"[21-25]@gni\"\n}\nrun_test 21 \"Add peer with nidrange (gni)\"\n\ntest_22() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 22@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 22@gni\n        - nid: 24@gni\n        - nid: 25@gni\n        - nid: 27@gni\n        - nid: 28@gni\n        - nid: 29@gni\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 22@gni --nid [24-29]@gni ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"22@gni\" \"26@gni\"\n}\nrun_test 22 \"Delete single secondary nid from peer (gni)\"\n\ntest_23() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 23@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 23@gni\nEOF\n\tappend_global_yaml\n\n\tdo_lnetctl peer add --prim_nid 23@gni --nid [25-29]@gni ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"23@gni\" \"[25-29]@gni\"\n}\nrun_test 23 \"Delete all secondary nids from peer (gni)\"\n\ntest_24() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 24@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 24@gni\n        - nid: 11@gni\n        - nid: 13.13.13.13@o2ib\n        - nid: 14.13.13.13@o2ib\n        - nid: 14.15.13.13@o2ib\n        - nid: 15.17.1.5@tcp\n        - nid: 15.17.1.10@tcp\n        - nid: 15.17.1.20@tcp\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 24@gni \\\n\t\t--nid [13-14/1].[13-15/2].13.13@o2ib,[15-16/3].[17-19/4].[1].[5-20/5]@tcp,[5-12/6]@gni ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"24@gni\" \"5@gni,13.15.13.13@o2ib,15.17.1.15@tcp\"\n}\nrun_test 24 \"Delete a secondary nid from peer (tcp, o2ib and gni)\"\n\ntest_25() {\n\treinit_dlc || return $?\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\npeer:\n    - primary nid: 25@gni\n      Multi-Rail: True\n      peer ni:\n        - nid: 25@gni\nEOF\n\tappend_global_yaml\n\tdo_lnetctl peer add --prim_nid 25@gni \\\n\t\t--nid [26-27].[4-10/3].26.26@tcp,26.26.26.26@o2ib,[30-35]@gni ||\n\t\terror \"Peer add failed $?\"\n\tcompare_peer_del \"25@gni\" \\\n\t\t\"[26-27].[4-10/3].26.26@tcp,26.26.26.26@o2ib,[30-35]@gni\"\n}\nrun_test 25 \"Delete all secondary nids from peer (tcp, gni and o2ib)\"\n\ntest_99a() {\n\treinit_dlc || return $?\n\n\techo \"Invalid prim_nid - peer add\"\n\tdo_lnetctl peer add --prim_nid foobar &&\n\t\terror \"Command should have failed\"\n\n\techo \"Invalid prim_nid - peer del\"\n\tdo_lnetctl peer del --prim_nid foobar &&\n\t\terror \"Command should have failed\"\n\n\techo \"Delete non-existing peer\"\n\tdo_lnetctl peer del --prim_nid 1.1.1.1@o2ib &&\n\t\terror \"Command should have failed\"\n\n\techo \"Don't provide mandatory argument for peer del\"\n\tdo_lnetctl peer del --nid 1.1.1.1@tcp &&\n\t\terror \"Command should have failed\"\n\n\techo \"Don't provide mandatory argument for peer add\"\n\tdo_lnetctl peer add --nid 1.1.1.1@tcp &&\n\t\terror \"Command should have failed\"\n\n\techo \"Don't provide mandatory arguments peer add\"\n\tdo_lnetctl peer add &&\n\t\terror \"Command should have failed\"\n\n\techo \"Invalid secondary nids\"\n\tdo_lnetctl peer add --prim_nid 1.1.1.1@tcp --nid foobar &&\n\t\terror \"Command should have failed\"\n\n\techo \"Exceed max nids per peer\"\n\tdo_lnetctl peer add --prim_nid 1.1.1.1@tcp --nid 1.1.1.[2-255]@tcp &&\n\t\terror \"Command should have failed\"\n\n\techo \"Invalid net type\"\n\tdo_lnetctl peer add --prim_nid 1@foo &&\n\t\terror \"Command should have failed\"\n\n\techo \"Invalid nid format\"\n\tlocal invalid_nids=\"1@tcp 1@o2ib 1.1.1.1@gni\"\n\n\tlocal nid\n\tfor nid in ${invalid_nids}; do\n\t\techo \"Check invalid primary nid - '$nid'\"\n\t\tdo_lnetctl peer add --prim_nid $nid &&\n\t\t\terror \"Command should have failed\"\n\tdone\n\n\tlocal invalid_strs=\"[2-1]@gni [a-f/x]@gni 256.256.256.256@tcp\"\n\tinvalid_strs+=\" 1.1.1.1.[2-5/f]@tcp 1.]2[.3.4@o2ib\"\n\tinvalid_strs+=\"1.[2-4,[5-6],7-8].1.1@tcp foobar\"\n\n\tlocal nidstr\n\tfor nidstr in ${invalid_strs}; do\n\t\techo \"Check invalid nidstring - '$nidstr'\"\n\t\tdo_lnetctl peer add --prim_nid 1.1.1.1@tcp --nid $nidstr &&\n\t\t\terror \"Command should have failed\"\n\tdone\n\n\techo \"Add non-local gateway\"\n\tdo_lnetctl route add --net tcp --gateway 1@gni &&\n\t\terror \"Command should have failed\"\n\n\treturn 0\n}\nrun_test 99a \"Check various invalid inputs to lnetctl peer\"\n\ntest_99b() {\n\treinit_dlc || return $?\n\n\tcreate_base_yaml_file\n\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-invalid.yaml\npeer:\n    - primary nid: 99.99.99.99@tcp\n      Multi-Rail: Foobar\n      peer ni:\n        - nid: 99.99.99.99@tcp\nEOF\n\tdo_lnetctl import < $TMP/sanity-lnet-$testnum-invalid.yaml &&\n\t\terror \"import should have failed\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-actual.yaml\n\tcompare_yaml_files\n}\nrun_test 99b \"Invalid value for Multi-Rail in yaml import\"\n\nhave_interface() {\n\tlocal if=\"$1\"\n\tlocal ip=$(ip addr show dev $if | awk '/ inet /{print $2}')\n\t[[ -n $ip ]]\n}\n\nadd_net() {\n\tlocal net=\"$1\"\n\tlocal if=\"$2\"\n\n\tif ! lsmod | grep -q ksocklnd ; then\n\t\tload_module ../lnet/klnds/socklnd/ksocklnd ||\n\t\t\terror \"Can't load ksocklnd.ko\"\n\tfi\n\n\tdo_lnetctl net add --net ${net} --if ${if} ||\n\t\terror \"Failed to add net ${net} on if ${if}\"\n}\n\ncompare_route_add() {\n\tlocal rnet=\"$1\"\n\tlocal gw=\"$2\"\n\n\tlocal actual=\"$TMP/sanity-lnet-$testnum-actual.yaml\"\n\n\tdo_lnetctl route add --net ${rnet} --gateway ${gw} ||\n\t\terror \"route add failed $?\"\n\t# CPT configuration is pruned from the exported yaml, since the default\n\t# can vary across test systems (unlike default values for things like\n\t# peer_credits, peer_timeout, etc.)\n\t$LNETCTL export --backup | grep -v CPT > $actual ||\n\t\terror \"export failed $?\"\n\tvalidate_gateway_nids\n\treturn $?\n}\n\ntest_100() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\"\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\nnet:\n    - net type: tcp\n      local NI(s):\n        - interfaces:\n              0: eth0\n          tunables:\n              peer_timeout: 180\n              peer_credits: 8\n              peer_buffer_credits: 0\n              credits: 256\nroute:\n    - net: tcp7\n      gateway: 7.7.7.7@tcp\n      hop: -1\n      priority: 0\n      health_sensitivity: 1\npeer:\n    - primary nid: 7.7.7.7@tcp\n      Multi-Rail: False\n      peer ni:\n        - nid: 7.7.7.7@tcp\nEOF\n\tappend_global_yaml\n\tcompare_route_add \"tcp7\" \"7.7.7.7@tcp\" || return $?\n\tcompare_yaml_files\n}\nrun_test 100 \"Add route with single gw (tcp)\"\n\ntest_101() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\"\n\tcat <<EOF > $TMP/sanity-lnet-$testnum-expected.yaml\nnet:\n    - net type: tcp\n      local NI(s):\n        - interfaces:\n              0: eth0\n          tunables:\n              peer_timeout: 180\n              peer_credits: 8\n              peer_buffer_credits: 0\n              credits: 256\nroute:\n    - net: tcp8\n      gateway: 8.8.8.10@tcp\n      hop: -1\n      priority: 0\n      health_sensitivity: 1\n    - net: tcp8\n      gateway: 8.8.8.9@tcp\n      hop: -1\n      priority: 0\n      health_sensitivity: 1\n    - net: tcp8\n      gateway: 8.8.8.8@tcp\n      hop: -1\n      priority: 0\n      health_sensitivity: 1\npeer:\n    - primary nid: 8.8.8.9@tcp\n      Multi-Rail: False\n      peer ni:\n        - nid: 8.8.8.9@tcp\n    - primary nid: 8.8.8.10@tcp\n      Multi-Rail: False\n      peer ni:\n        - nid: 8.8.8.10@tcp\n    - primary nid: 8.8.8.8@tcp\n      Multi-Rail: False\n      peer ni:\n        - nid: 8.8.8.8@tcp\nEOF\n\tappend_global_yaml\n\tcompare_route_add \"tcp8\" \"8.8.8.[8-10]@tcp\"\n}\nrun_test 101 \"Add route with multiple gw (tcp)\"\n\ncompare_route_del() {\n\tlocal rnet=\"$1\"\n\tlocal gw=\"$2\"\n\n\tlocal actual=\"$TMP/sanity-lnet-$testnum-actual.yaml\"\n\n\tdo_lnetctl route del --net ${rnet} --gateway ${gw} ||\n\t\terror \"route del failed $?\"\n\t$LNETCTL export --backup > $actual ||\n\t\terror \"export failed $?\"\n\tvalidate_gateway_nids\n}\n\ntest_102() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl route add --net tcp102 --gateway 102.102.102.102@tcp ||\n\t\terror \"route add failed $?\"\n\tcompare_route_del \"tcp102\" \"102.102.102.102@tcp\"\n}\nrun_test 102 \"Delete route with single gw (tcp)\"\n\ntest_103() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\"\n\t$LNETCTL export --backup > $TMP/sanity-lnet-$testnum-expected.yaml\n\tdo_lnetctl route add --net tcp103 \\\n\t\t--gateway 103.103.103.[103-120/4]@tcp ||\n\t\terror \"route add failed $?\"\n\tcompare_route_del \"tcp103\" \"103.103.103.[103-120/4]@tcp\"\n}\nrun_test 103 \"Delete route with multiple gw (tcp)\"\n\n### load lnet in default namespace, configure in target namespace\n\ntest_200() {\n\tcleanup_lnet || exit 1\n\tload_lnet \"networks=\\\"\\\"\"\n\tdo_ns $LNETCTL lnet configure --all || exit 1\n\t$LNETCTL net show --net tcp | grep -q \"nid: ${FAKE_IP}@tcp$\"\n}\nrun_test 200 \"load lnet w/o module option, configure in a non-default namespace\"\n\ntest_201() {\n\tcleanup_lnet || exit 1\n\tload_lnet \"networks=tcp($FAKE_IF)\"\n\tdo_ns $LNETCTL lnet configure --all || exit 1\n\t$LNETCTL net show --net tcp | grep -q \"nid: ${FAKE_IP}@tcp$\"\n}\nrun_test 201 \"load lnet using networks module options in a non-default namespace\"\n\ntest_202() {\n\tcleanup_lnet || exit 1\n\tload_lnet \"networks=\\\"\\\" ip2nets=\\\"tcp0($FAKE_IF) ${FAKE_IP}\\\"\"\n\tdo_ns $LNETCTL lnet configure --all || exit 1\n\t$LNETCTL net show | grep -q \"nid: ${FAKE_IP}@tcp$\"\n}\nrun_test 202 \"load lnet using ip2nets in a non-default namespace\"\n\n\n### Add the interfaces in the target namespace\n\ntest_203() {\n\tcleanup_lnet || exit 1\n\tload_lnet\n\tdo_lnetctl lnet configure || exit 1\n\tdo_ns $LNETCTL net add --net tcp0 --if $FAKE_IF\n}\nrun_test 203 \"add a network using an interface in the non-default namespace\"\n\nLNET_PARAMS_FILE=\"$TMP/$TESTSUITE.parameters\"\nfunction save_lnet_params() {\n\t$LNETCTL global show | egrep -v '^global:$' |\n\t\t\t       sed 's/://' > $LNET_PARAMS_FILE\n}\n\nfunction restore_lnet_params() {\n\tlocal param value\n\twhile read param value; do\n\t\t[[ $param == max_intf ]] && continue\n\t\t[[ $param == lnd_timeout ]] && continue\n\t\t$LNETCTL set ${param} ${value} ||\n\t\t\terror \"Failed to restore ${param} to ${value}\"\n\tdone < $LNET_PARAMS_FILE\n}\n\nfunction lnet_health_pre() {\n\tsave_lnet_params\n\n\t# Lower transaction timeout to speed up test execution\n\t$LNETCTL set transaction_timeout 10 ||\n\t\terror \"Failed to set transaction_timeout $?\"\n\n\t# Increase recovery interval so we have time to capture health values\n\t$LNETCTL set recovery_interval 20 ||\n\t\terror \"Failed to set recovery_interval $?\"\n\n\tRETRY_PARAM=$($LNETCTL global show | awk '/retry_count/{print $NF}')\n\tRSND_PRE=$($LNETCTL stats show | awk '/resend_count/{print $NF}')\n\tLO_HVAL_PRE=$($LNETCTL net show -v 2 | awk '/health value/{print $NF}' |\n\t\t      xargs echo | sed 's/ /+/g' | bc -l)\n\n\tlocal my_nid=$($LCTL list_nids | head -n 1)\n\n\tRMT_HVAL_PRE=$($LNETCTL peer show --nid $my_nid -v 2 2>/dev/null |\n\t\t       awk '/health value/{print $NF}' | xargs echo |\n\t\t       sed 's/ /+/g' | bc -l)\n\n\t# Might not have any peers so initialize to zero.\n\tRMT_HVAL_PRE=${RMT_HVAL_PRE:-0}\n\n\treturn 0\n}\n\nfunction lnet_health_post() {\n\tRSND_POST=$($LNETCTL stats show | awk '/resend_count/{print $NF}')\n\tLO_HVAL_POST=$($LNETCTL net show -v 2 |\n\t\t       awk '/health value/{print $NF}' |\n\t\t       xargs echo | sed 's/ /+/g' | bc -l)\n\n\tlocal my_nid=$($LCTL list_nids | head -n 1)\n\n\tRMT_HVAL_POST=$($LNETCTL peer show --nid $my_nid -v 2 2>/dev/null |\n\t\t\tawk '/health value/{print $NF}' | xargs echo |\n\t\t\tsed 's/ /+/g' | bc -l)\n\n\t# Might not have any peers so initialize to zero.\n\tRMT_HVAL_POST=${RMT_HVAL_POST:-0}\n\n\t${VERBOSE} &&\n\techo \"Pre resends: $RSND_PRE\" &&\n\techo \"Post resends: $RSND_POST\" &&\n\techo \"Resends delta: $((RSND_POST - RSND_PRE))\" &&\n\techo \"Pre local health: $LO_HVAL_PRE\" &&\n\techo \"Post local health: $LO_HVAL_POST\" &&\n\techo \"Pre remote health: $RMT_HVAL_PRE\" &&\n\techo \"Post remote health: $RMT_HVAL_POST\"\n\n\trestore_lnet_params\n\n\treturn 0\n}\n\nfunction check_no_resends() {\n\techo \"Check that no resends took place\"\n\t[[ $RSND_POST -ne $RSND_PRE ]] &&\n\t\terror \"Found resends: $RSND_POST != $RSND_PRE\"\n\n\treturn 0\n}\n\nfunction check_resends() {\n\tlocal delta=$((RSND_POST - RSND_PRE))\n\n\techo \"Check that $RETRY_PARAM resends took place\"\n\t[[ $delta -ne $RETRY_PARAM ]] &&\n\t\terror \"Expected $RETRY_PARAM resends found $delta\"\n\n\treturn 0\n}\n\nfunction check_no_local_health() {\n\techo \"Check that local NI health is unchanged\"\n\t[[ $LO_HVAL_POST -ne $LO_HVAL_PRE ]] &&\n\t\terror \"Local health changed: $LO_HVAL_POST != $LO_HVAL_PRE\"\n\n\treturn 0\n}\n\nfunction check_local_health() {\n\techo \"Check that local NI health has been changed\"\n\t[[ $LO_HVAL_POST -eq $LO_HVAL_PRE ]] &&\n\t\terror \"Local health unchanged: $LO_HVAL_POST == $LO_HVAL_PRE\"\n\n\treturn 0\n}\n\nfunction check_no_remote_health() {\n\techo \"Check that remote NI health is unchanged\"\n\t[[ $RMT_HVAL_POST -ne $RMT_HVAL_PRE ]] &&\n\t\terror \"Remote health changed: $RMT_HVAL_POST != $RMT_HVAL_PRE\"\n\n\treturn 0\n}\n\nfunction check_remote_health() {\n\techo \"Check that remote NI health has been changed\"\n\t[[ $RMT_HVAL_POST -eq $RMT_HVAL_PRE ]] &&\n\t\terror \"Remote health unchanged: $RMT_HVAL_POST == $RMT_HVAL_PRE\"\n\n\treturn 0\n}\n\n# See lnet/lnet/lib-msg.c:lnet_health_check()\nLNET_LOCAL_RESEND_STATUSES=\"local_interrupt local_dropped local_aborted\"\nLNET_LOCAL_RESEND_STATUSES+=\" local_no_route local_timeout\"\nLNET_LOCAL_NO_RESEND_STATUSES=\"local_error\"\ntest_204() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\" || return $?\n\n\tlnet_health_pre || return $?\n\n\tlocal hstatus\n\tfor hstatus in ${LNET_LOCAL_RESEND_STATUSES} \\\n\t\t       ${LNET_LOCAL_NO_RESEND_STATUSES}; do\n\t\techo \"Simulate $hstatus\"\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\tdone\n\n\tlnet_health_post\n\n\tcheck_no_resends || return $?\n\tcheck_no_local_health || return $?\n\n\treturn 0\n}\nrun_test 204 \"Check no health or resends for single-rail local failures\"\n\ntest_205() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\n\tlocal hstatus\n\tfor hstatus in ${LNET_LOCAL_RESEND_STATUSES}; do\n\t\treinit_dlc || return $?\n\t\tadd_net \"tcp\" \"eth0\" || return $?\n\t\tadd_net \"tcp1\" \"eth0\" || return $?\n\n\t\techo \"Simulate $hstatus\"\n\t\tlnet_health_pre\n\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\t$LCTL net_drop_add -s *@tcp1 -d *@tcp1 -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\n\t\tlnet_health_post\n\n\t\tcheck_resends || return $?\n\t\tcheck_local_health || return $?\n\tdone\n\n\tfor hstatus in ${LNET_LOCAL_NO_RESEND_STATUSES}; do\n\t\treinit_dlc || return $?\n\t\tadd_net \"tcp\" \"eth0\" || return $?\n\t\tadd_net \"tcp1\" \"eth0\" || return $?\n\n\t\techo \"Simulate $hstatus\"\n\t\tlnet_health_pre || return $?\n\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\t$LCTL net_drop_add -s *@tcp1 -d *@tcp1 -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\n\t\tlnet_health_post\n\n\t\tcheck_no_resends || return $?\n\t\tcheck_local_health || return $?\n\tdone\n\n\treturn 0\n}\nrun_test 205 \"Check health and resends for multi-rail local failures\"\n\n# See lnet/lnet/lib-msg.c:lnet_health_check()\nLNET_REMOTE_RESEND_STATUSES=\"remote_dropped\"\nLNET_REMOTE_NO_RESEND_STATUSES=\"remote_error remote_timeout network_timeout\"\ntest_206() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\treinit_dlc || return $?\n\tadd_net \"tcp\" \"eth0\" || return $?\n\n\tdo_lnetctl discover $($LCTL list_nids | head -n 1) ||\n\t\terror \"failed to discover myself\"\n\n\tlnet_health_pre || return $?\n\n\tlocal hstatus\n\tfor hstatus in ${LNET_REMOTE_RESEND_STATUSES} \\\n\t\t       ${LNET_REMOTE_NO_RESEND_STATUSES}; do\n\t\techo \"Simulate $hstatus\"\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\tdone\n\n\tlnet_health_post\n\n\tcheck_no_resends || return $?\n\tcheck_no_local_health || return $?\n\tcheck_no_remote_health || return $?\n\n\treturn 0\n}\nrun_test 206 \"Check no health or resends for single-rail remote failures\"\n\ntest_207() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\n\tlocal hstatus\n\tfor hstatus in ${LNET_REMOTE_RESEND_STATUSES}; do\n\t\treinit_dlc || return $?\n\t\tadd_net \"tcp\" \"eth0\" || return $?\n\t\tadd_net \"tcp1\" \"eth0\" || return $?\n\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) ||\n\t\t\terror \"failed to discover myself\"\n\n\t\techo \"Simulate $hstatus\"\n\t\tlnet_health_pre || return $?\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\t$LCTL net_drop_add -s *@tcp1 -d *@tcp1 -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\n\t\tlnet_health_post\n\n\t\tcheck_resends || return $?\n\t\tcheck_no_local_health || return $?\n\t\tcheck_remote_health || return $?\n\tdone\n\tfor hstatus in ${LNET_REMOTE_NO_RESEND_STATUSES}; do\n\t\treinit_dlc || return $?\n\t\tadd_net \"tcp\" \"eth0\" || return $?\n\t\tadd_net \"tcp1\" \"eth0\" || return $?\n\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) ||\n\t\t\terror \"failed to discover myself\"\n\n\t\techo \"Simulate $hstatus\"\n\t\tlnet_health_pre || return $?\n\t\t$LCTL net_drop_add -s *@tcp -d *@tcp -m GET -r 1 -e ${hstatus}\n\t\t$LCTL net_drop_add -s *@tcp1 -d *@tcp1 -m GET -r 1 -e ${hstatus}\n\t\tdo_lnetctl discover $($LCTL list_nids | head -n 1) &&\n\t\t\terror \"Should have failed\"\n\t\t$LCTL net_drop_del *\n\n\t\tlnet_health_post\n\n\t\tcheck_no_resends || return $?\n\t\tcheck_no_local_health || return $?\n\t\tcheck_remote_health || return $?\n\tdone\n\n\treturn 0\n}\nrun_test 207 \"Check health and resends for multi-rail remote errors\"\n\ntest_208_load_and_check_lnet() {\n\tlocal ip2nets=\"$1\"\n\tlocal p_nid=\"$2\"\n\tlocal s_nid=\"$3\"\n\tlocal num_expected=1\n\n\tload_lnet \"networks=\\\"\\\" ip2nets=\\\"${ip2nets_str}\\\"\"\n\n\t$LCTL net up ||\n\t\terror \"Failed to load LNet with ip2nets \\\"${ip2nets_str}\\\"\"\n\n\t[[ -n $s_nid ]] &&\n\t\tnum_expected=2\n\n\tdeclare -a nids\n\tnids=( $($LCTL list_nids) )\n\n\t[[ ${#nids[@]} -ne ${num_expected} ]] &&\n\t\terror \"Expect ${num_expected} NIDs found ${#nids[@]}\"\n\n\t[[ ${nids[0]} == ${p_nid} ]] ||\n\t\terror \"Expect NID \\\"${p_nid}\\\" found \\\"${nids[0]}\\\"\"\n\n\t[[ -n $s_nid ]] && [[ ${nids[1]} != ${s_nid} ]] &&\n\t\terror \"Expect second NID \\\"${s_nid}\\\" found \\\"${nids[1]}\\\"\"\n\n\t$LCTL net down &>/dev/null\n\tcleanup_lnet\n}\n\ntest_208() {\n\thave_interface \"eth0\" || skip \"Need eth0 interface with ipv4 configured\"\n\n\tcleanup_netns || error \"Failed to cleanup netns before test execution\"\n\tcleanup_lnet || error \"Failed to unload modules before test execution\"\n\tsetup_fakeif || error \"Failed to add fake IF\"\n\n\thave_interface \"$FAKE_IF\" ||\n\t\terror \"Expect $FAKE_IF configured but not found\"\n\n\tlocal eth0_ip=$(ip --oneline addr show dev eth0 |\n\t\t\tawk '/inet /{print $4}' |\n\t\t\tsed 's:/.*::')\n\tlocal ip2nets_str=\"tcp(eth0) $eth0_ip\"\n\n\techo \"Configure single NID \\\"$ip2nets_str\\\"\"\n\ttest_208_load_and_check_lnet \"${ip2nets_str}\" \"${eth0_ip}@tcp\"\n\n\tip2nets_str=\"tcp(eth0) $eth0_ip; tcp1($FAKE_IF) $FAKE_IP\"\n\techo \"Configure two NIDs; two NETs \\\"$ip2nets_str\\\"\"\n\ttest_208_load_and_check_lnet \"${ip2nets_str}\" \"${eth0_ip}@tcp\" \\\n\t\t\t\t     \"${FAKE_IP}@tcp1\"\n\n\tip2nets_str=\"tcp(eth0) $eth0_ip; tcp($FAKE_IF) $FAKE_IP\"\n\techo \"Configure two NIDs; one NET \\\"$ip2nets_str\\\"\"\n\ttest_208_load_and_check_lnet \"${ip2nets_str}\" \"${eth0_ip}@tcp\" \\\n\t\t\t\t     \"${FAKE_IP}@tcp\"\n\tlocal addr1=( ${eth0_ip//./ } )\n\tlocal addr2=( ${FAKE_IP//./ } )\n\tlocal range=\"[${addr1[0]},${addr2[0]}]\"\n\n\tlocal i\n\tfor i in $(seq 1 3); do\n\t\trange+=\".[${addr1[$i]},${addr2[$i]}]\"\n\tdone\n\tip2nets_str=\"tcp(eth0,${FAKE_IF}) ${range}\"\n\n\techo \"Configured two NIDs; one NET alt syntax \\\"$ip2nets_str\\\"\"\n\ttest_208_load_and_check_lnet \"${ip2nets_str}\" \"${eth0_ip}@tcp\" \\\n\t\t\t\t     \"${FAKE_IP}@tcp\"\n\n\tcleanup_fakeif\n\n\techo \"alt syntax with missing IF \\\"$ip2nets_str\\\"\"\n\tload_lnet \"networks=\\\"\\\" ip2nets=\\\"${ip2nets_str}\\\"\"\n\n\techo \"$LCTL net up should fail\"\n\t$LCTL net up &&\n\t\terror \"LNet bringup should have failed\"\n\n\tcleanup_lnet\n}\nrun_test 208 \"Test various kernel ip2nets configurations\"\n\ntest_300() {\n\t# LU-13274\n\tlocal header\n\tlocal out=$TMP/$tfile\n\tlocal prefix=/usr/include/linux/lnet\n\n\t# We use a hard coded prefix so that this test will not fail\n\t# when run in tree.\n\tCC=${CC:-cc}\n\tif ! which $CC > /dev/null 2>&1; then\n\t\tskip_env \"$CC is not installed\"\n\tfi\n\n\tcleanup_lnet || exit 1\n\tload_lnet\n\n\tif ! [[ -d $prefix ]]; then\n\t\t# Assume we're running in tree and fixup the include path.\n\t\tprefix=$LUSTRE/../lnet/include/uapi/linux/lnet\n\tfi\n\n\tfor header in $prefix/*.h; do\n\t\tif ! [[ -f \"$header\" ]]; then\n\t\t\tcontinue\n\t\tfi\n\n\t\t$CC -Wall -Werror -std=c99 -include $header -c -x c /dev/null -o $out ||\n\t\t\terror \"cannot compile '$header'\"\n\tdone\n\trm -f $out\n}\nrun_test 300 \"packaged LNet UAPI headers can be compiled\"\n\ncomplete $SECONDS\n\ncleanup_testsuite\nexit_status\n", "num_lines": 1626}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\nALWAYS_EXCEPT=\"$SANITY_LSNAPSHOT_EXCEPT\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n[[ \"$MDS1_VERSION\" -lt $(version_code 2.9.55) ]] ||\n[[ \"$OST1_VERSION\" -lt $(version_code 2.9.55) ]] &&\n\tskip \"Need server version at least 2.9.55\"\n[[ \"$mds1_FSTYPE\" = \"ldiskfs\" ]] || [[ \"$ost1_FSTYPE\" = \"ldiskfs\" ]] &&\n\tskip \"ZFS only test\"\n\nrequire_dsh_mds || exit 0\nrequire_dsh_ost || exit 0\n\ncheck_and_setup_lustre\n\ndo_facet mgs $LCTL set_param debug=+snapshot\ndo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param debug=+snapshot\n\nlss_gen_conf\nlss_cleanup\nbuild_test_filter\n\ntest_0() {\n\techo \"Create lss_0_0 with default\"\n\tlsnapshot_create -n lss_0_0 ||\n\t\tlss_err \"(1) Fail to create lss_0_0 with default\"\n\n\techo \"List lss_0_0\"\n\tlsnapshot_list -n lss_0_0 ||\n\t\tlss_err \"(2) Fail to list lss_0_0\"\n\n\techo \"Create lss_0_1 with barrier off\"\n\tlsnapshot_create -n lss_0_1 --barrier=off ||\n\t\tlss_err \"(3) Fail to create lss_0_1 with barrier off\"\n\n\techo \"List lss_0_1\"\n\tlsnapshot_list -n lss_0_1 ||\n\t\tlss_err \"(4) Fail to list lss_0_1\"\n\n\techo \"Create lss_0_2 with comment\"\n\tlsnapshot_create -n lss_0_2 -c \"'This is test_0'\" ||\n\t\tlss_err \"(5) Fail to create lss_0_2 with comment\"\n\n\techo \"List lss_0_2\"\n\tlsnapshot_list -n lss_0_2 | grep \"This is test_0\" ||\n\t\tlss_err \"(6) Fail to list lss_0_2\"\n\n\techo \"Create lss_0_2 with barrier on and comment\"\n\tlsnapshot_create -n lss_0_3 --barrier=on -c \"'Another one'\" ||\n\t\tlss_err \"(7) Fail to create lss_0_3 with barrier and comment\"\n\n\techo \"List lss_0_3\"\n\tlsnapshot_list -n lss_0_3 | grep \"Another one\" ||\n\t\tlss_err \"(8) Fail to list lss_0_3\"\n\n\techo \"Try to create lss_0_0 that exist already\"\n\tlsnapshot_create -n lss_0_0 &&\n\t\tlss_err \"(9) Create snapshot with exist name should fail\" ||\n\t\ttrue\n}\nrun_test 0 \"create lustre snapshot\"\n\ntest_1a() {\n\tmkdir -p $DIR/$tdir || lss_err \"(1) Fail to mkdir $DIR/$tdir\"\n\trm -f $DIR/$tdir/test-framework.sh\n\tcp $LUSTRE/tests/test-framework.sh $DIR/$tdir/ ||\n\t\tlss_err \"(2) Fail to copy\"\n\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\techo \"Create lss_1a_0\"\n\tlsnapshot_create -n lss_1a_0 ||\n\t\tlss_err \"(3) Fail to create lss_1a_0\"\n\n\techo \"Check whether mounted (1)\"\n\tlsnapshot_list -n lss_1a_0 -d | grep \"mounted\" && {\n\t\tlsnapshot_list -n lss_1a_0 -d\n\t\tlss_err \"(4) Expect 'not mount', got 'mounted' for lss_1a_0\"\n\t}\n\n\techo \"Mount lss_1a_0\"\n\tlsnapshot_mount -n lss_1a_0 ||\n\t\tlss_err \"(5) Fail to mount lss_1a_0\"\n\n\techo \"Check whether mounted (2)\"\n\tlocal mcount=$(lsnapshot_list -n lss_1a_0 -d | grep \"not mount\" | wc -l)\n\t[[ $mcount -ne 0 ]] && {\n\t\tif combined_mgs_mds ; then\n\t\t\tlsnapshot_list -n lss_1a_0 -d\n\t\t\tlss_err \"(6.1) Got unexpected 'not mount' for lss_1a_0\"\n\t\tfi\n\n\t\t[[ $mcount -gt 1 ]] && {\n\t\t\tlsnapshot_list -n lss_1a_0 -d\n\t\t\tlss_err \"(6.2) Got unexpected 'not mount' for lss_1a_0\"\n\t\t}\n\n\t\t# The first 10 lines contains and only contains MGS mount status\n\t\tlsnapshot_list -n lss_1a_0 -d | head -n 10 |\n\t\t\tgrep \"not mount\" || {\n\t\t\tlsnapshot_list -n lss_1a_0 -d\n\t\t\tlss_err \"(6.3) Got unexpected 'not mount' for lss_1a_0\"\n\t\t}\n\t}\n\n\tlocal ss_fsname=$(lsnapshot_list -n lss_1a_0 |\n\t\t\tawk '/^snapshot_fsname/ { print $2 }')\n\tlocal mntpt=\"/mnt/$ss_fsname\"\n\tlocal saved_fsname=$FSNAME\n\n\tmkdir -p $mntpt ||\n\t\tlss_err \"(7) Fail to create mount point $mntpt\"\n\tFSNAME=$ss_fsname\n\techo \"Mount client\"\n\tmount_client $mntpt ro || {\n\t\tFSNAME=$saved_fsname\n\t\tlss_err \"(8) Fail to mount client for lss_1a_0\"\n\t}\n\n\tFSNAME=$saved_fsname\n\techo \"Check whether the file in snapshot is the same as original one\"\n\tdiff $DIR/$tdir/test-framework.sh $mntpt/$tdir/test-framework.sh ||\n\t\tlss_err \"(9) files should be the same\"\n\n\techo \"Modify the original file, and check again\"\n\techo dummy >> $DIR/$tdir/test-framework.sh\n\tdiff $DIR/$tdir/test-framework.sh $mntpt/$tdir/test-framework.sh &&\n\t\tlss_err \"(10) files should be different\"\n\n\tumount $mntpt ||\n\t\tlss_err \"(11) Fail to umount client for lss_1a_0\"\n\n\techo \"Umount lss_1a_0\"\n\tlsnapshot_umount -n lss_1a_0 ||\n\t\tlss_err \"(12) Fail to umount lss_1a_0\"\n\n\techo \"Check whether mounted (3)\"\n\tlsnapshot_list -n lss_1a_0 -d | grep \"mounted\" && {\n\t\tlsnapshot_list -n lss_1a_0 -d\n\t\tlss_err \"(13) Expect 'not mount', got 'mounted' for lss_1a_0\"\n\t} || true\n}\nrun_test 1a \"mount/umount lustre snapshot\"\n\ntest_1b() {\n\techo \"Create lss_1b_0\"\n\tlsnapshot_create -n lss_1b_0 ||\n\t\tlss_err \"(1) Fail to create lss_1b_0\"\n\n\techo \"Check whether mounted (1)\"\n\tlsnapshot_list -n lss_1b_0 -d | grep \"mounted\" && {\n\t\tlsnapshot_list -n lss_1b_0 -d\n\t\tlss_err \"(2) Expect 'not mount', got 'mounted' for lss_1b_0\"\n\t}\n\n\tstopall || lss_err \"(3) Fail to stopall\"\n\n\techo \"Mount lss_1b_0\"\n\tlsnapshot_mount -n lss_1b_0 ||\n\t\tlss_err \"(4) Fail to mount lss_1b_0\"\n\n\techo \"Check whether mounted (2)\"\n\tlsnapshot_list -n lss_1b_0 -d | grep \"not mount\" && {\n\t\tlsnapshot_list -n lss_1b_0 -d\n\t\tlss_err \"(5) Expect 'mounted', got 'not mount' for lss_1b_0\"\n\t}\n\n\techo \"umount lss_1b_0\"\n\tlsnapshot_umount -n lss_1b_0 ||\n\t\tlss_err \"(6) Fail to umount lss_1b_0\"\n\n\techo \"Check whether mounted (3)\"\n\tlsnapshot_list -n lss_1b_0 -d | grep \"mounted\" && {\n\t\tlsnapshot_list -n lss_1b_0 -d\n\t\tlss_err \"(7) Expect 'not mount', got 'mounted' for lss_1b_0\"\n\t}\n\n\tsetupall || lss_err \"(8) Fail to setupall\"\n}\nrun_test 1b \"mount snapshot without original filesystem mounted\"\n\ntest_2() {\n\techo \"Create lss_2_0\"\n\tlsnapshot_create -n lss_2_0 --barrier=off ||\n\t\tlss_err \"(1) Fail to create lss_2_0\"\n\n\techo \"List lss_2_0\"\n\tlsnapshot_list -n lss_2_0 ||\n\t\tlss_err \"(2) Fail to list lss_2_0\"\n\n\techo \"Destroy lss_2_0\"\n\tlsnapshot_destroy -n lss_2_0 ||\n\t\tlss_err \"(3) Fail to destroy lss_2_0\"\n\n\techo \"Try to list lss_2_0 after destroy\"\n\tlsnapshot_list -n lss_2_0 &&\n\t\tlss_err \"(4) List lss_2_0 should fail after destroy\"\n\n\techo \"Create lss_2_1\"\n\tlsnapshot_create -n lss_2_1 --barrier=off ||\n\t\tlss_err \"(5) Fail to create lss_2_1\"\n\n\techo \"List lss_2_1\"\n\tlsnapshot_list -n lss_2_1 ||\n\t\tlss_err \"(6) Fail to list lss_2_1\"\n\n\techo \"Mount lss_2_1\"\n\tlsnapshot_mount -n lss_2_1 ||\n\t\tlss_err \"(7) Fail to mount lss_2_1\"\n\n\techo \"Try to destroy lss_2_1 with mounted\"\n\tlsnapshot_destroy -n lss_2_1 &&\n\t\tlss_err \"(8) Destroy mounted snapshot without -f should fail\"\n\n\techo \"Destroy lss_2_1 by force with mounted\"\n\tlsnapshot_destroy -n lss_2_1 -f ||\n\t\tlss_err \"(9) Destroy mounted snapshot with -f should succeed\"\n\n\techo \"Try to list lss_2_1 after destroy\"\n\tlsnapshot_list -n lss_2_1 &&\n\t\tlss_err \"(10) List lss_2_1 should fail after destroy\" || true\n}\nrun_test 2 \"destroy lustre snapshot\"\n\ntest_3a() {\n\techo \"Create lss_3a_0\"\n\tlsnapshot_create -n lss_3a_0 --barrier=off -c \"'It is test_3a'\" ||\n\t\tlss_err \"(1) Fail to create lss_3a_0\"\n\n\techo \"List lss_3a_0\"\n\tlsnapshot_list -n lss_3a_0 ||\n\t\tlss_err \"(2) Fail to list lss_3a_0\"\n\n\tlocal old_mtime=$(lsnapshot_list -n lss_3a_0 |\n\t\t\tawk '/^modify_time/ { $1=\"\"; print $0 }')\n\n\techo \"Rename lss_3a_0 to lss_3a_1\"\n\tlsnapshot_modify -n lss_3a_0 -N \"lss_3a_1\" ||\n\t\tlss_err \"(3) Fail to rename lss_3a_0 to lss_3a_1\"\n\n\techo \"Try to list lss_3a_0 after rename\"\n\tlsnapshot_list -n lss_3a_0 &&\n\t\tlss_err \"(4) List lss_3a_0 should fail after rename\"\n\n\techo \"List lss_3a_1\"\n\tlsnapshot_list -n lss_3a_1 ||\n\t\tlss_err \"(5) Fail to list lss_3a_1\"\n\n\tlocal new_mtime=$(lsnapshot_list -n lss_3a_1 |\n\t\t\tawk '/^modify_time/ { $1=\"\"; print $0 }')\n\techo \"Check whether mtime has been changed\"\n\t[ \"$old_mtime\" != \"$new_mtime\" ] ||\n\t\tlss_err \"(6) mtime should be changed because of rename\"\n\n\techo \"Modify lss_3a_1's comment\"\n\tlsnapshot_modify -n lss_3a_1 -c \"'Renamed from lss_3a_0'\" ||\n\t\tlss_err \"(7) Fail to change lss_3a_1's comment\"\n\n\techo \"Check whether comment has been changed\"\n\tlsnapshot_list -n lss_3a_1 -d | grep \"It is test_3a\" && {\n\t\tlsnapshot_list -n lss_3a_1 -d\n\t\tlss_err \"(8) The comment should have been changed\"\n\t}\n\n\techo \"Modify lss_3a_1's name and comment together\"\n\tlsnapshot_modify -n lss_3a_1 -N \"lss_3a_2\" -c \"'Change again'\" ||\n\t\tlss_err \"(9) Fail to modify lss_3a_1\"\n\n\techo \"Mount lss_3a_2\"\n\tlsnapshot_mount -n lss_3a_2 ||\n\t\tlss_err \"(10) Fail to mount lss_3a_2\"\n\n\techo \"Try to rename lss_3a_2 to lss_3a_3 with mounted\"\n\tlsnapshot_modify -n lss_3a_2 -N \"lss_3a_3\" &&\n\t\tlss_err \"(11) Rename mounted snapshot lss_3a_2 should fail\"\n\n\techo \"Modify lss_3a_2's comment with mounted\"\n\tlsnapshot_modify -n lss_3a_2 -c \"'Change comment with mounted'\" ||\n\t\tlss_err \"(12) Change comment with mount should succeed\"\n\n\techo \"Umount lss_3a_2\"\n\tlsnapshot_umount -n lss_3a_2 ||\n\t\tlss_err \"(13) Fail to umount lss_3a_2\"\n}\nrun_test 3a \"modify lustre snapshot\"\n\ntest_3b() {\n\techo \"Create lss_3b_0\"\n\tlsnapshot_create -n lss_3b_0 --barrier=off -c \"'It is test_3b'\" ||\n\t\tlss_err \"(1) Fail to create lss_3b_0\"\n\n\techo \"List lss_3b_0\"\n\tlsnapshot_list -n lss_3b_0 ||\n\t\tlss_err \"(2) Fail to list lss_3b_0\"\n\n\tstopall || lss_err \"(3) Fail to stopall\"\n\n\techo \"Modify lss_3b_0's name and comment together\"\n\tlsnapshot_modify -n lss_3b_0 -N \"lss_3b_1\" -c \"'Change again'\" ||\n\t\tlss_err \"(4) Fail to modify lss_3b_0\"\n\n\techo \"Try to list lss_3b_0 after rename\"\n\tlsnapshot_list -n lss_3b_0 &&\n\t\tlss_err \"(5) List lss_3b_0 should fail after rename\"\n\n\techo \"Check whether comment has been changed\"\n\tlsnapshot_list -n lss_3b_1 -d | grep \"It is test_3b\" && {\n\t\tlsnapshot_list -n lss_3b_1 -d\n\t\tlss_err \"(6) The comment should have been changed\"\n\t}\n\n\tsetupall || lss_err \"(7) Fail to setupall\"\n}\nrun_test 3b \"modify snapshot without original filesystem mounted\"\n\ntest_4() { # LU-10843\n\tcombined_mgs_mds && skip \"Combined MGS/MDS\" && return\n\n\tlocal rcmd=\"$LCTL get_param ldlm.namespaces.MGS.resource_count\"\n\n\tlocal exports=$(do_facet mgs \"$LCTL get_param -n mgs.MGS.num_exports\")\n\tlocal rcount=$(do_facet mgs $rcmd)\n\n\techo \"Remount MGT\"\n\tstop mgs || error \"stop mgs failed\"\n\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS || error \"start mgs failed\"\n\n\techo \"Wait for all reconnects\"\n\tlocal CMD=\"$LCTL get_param -n mgs.MGS.num_exports\"\n\twait_update_facet mgs \"$CMD\" $exports ||\n\t\tlss_err \"(1) failed to export from mgs\"\n\n\twait_update_facet mgs \"$rcmd\" $rcount ||\n\t\tlss_err \"(2) failed to reconnect mds\"\n\n\techo \"Create lss_4_0\"\n\tlsnapshot_create -n lss_4_0 -c \"'It is test_4'\" ||\n\t\tlss_err \"(3) Fail to create lss_4_0\"\n\n\techo \"List lss_4_0\"\n\tlsnapshot_list -n lss_4_0 ||\n\t\tlss_err \"(4) Fail to list lss_4_0\"\n\n\techo \"Destroy lss_4_0\"\n\tlsnapshot_destroy -n lss_4_0 ||\n\t\tlss_err \"(5) Fail to destroy lss_4_0\"\n\n}\nrun_test 4 \"create/delete snapshot after MGS remount\"\n\nlss_cleanup\ndo_facet mgs $LCTL set_param debug=-snapshot\ndo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param debug=-snapshot\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 373}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# exit on error\nset -e\nset +o monitor\n\nSRCDIR=$(dirname $0)\nexport PATH=$PWD/$SRCDIR:$SRCDIR:$PWD/$SRCDIR/utils:$PATH:/sbin:/usr/sbin\n\nONLY=${ONLY:-\"$*\"}\nALWAYS_EXCEPT=\"$SANITY_PCC_EXCEPT \"\n# bug number for skipped test:\nALWAYS_EXCEPT+=\"\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nENABLE_PROJECT_QUOTAS=${ENABLE_PROJECT_QUOTAS:-true}\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nMULTIOP=${MULTIOP:-multiop}\nOPENFILE=${OPENFILE:-openfile}\nMOUNT_2=${MOUNT_2:-\"yes\"}\nFAIL_ON_ERROR=false\n\n# script only handles up to 10 MDTs (because of MDT_PREFIX)\n[ $MDSCOUNT -gt 9 ] &&\n\terror \"script cannot handle more than 9 MDTs, please fix\" && exit\n\ncheck_and_setup_lustre\n\nif [[ \"$MDS1_VERSION\" -lt $(version_code 2.12.52) ]]; then\n\tskip \"Need MDS version at least 2.12.52\"\nfi\n\n# $RUNAS_ID may get set incorrectly somewhere else\nif [[ $UID -eq 0 && $RUNAS_ID -eq 0 ]]; then\n\tskip_env \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\" && exit\nfi\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\nif getent group nobody; then\n\tGROUP=nobody\nelif getent group nogroup; then\n\tGROUP=nogroup\nelse\n\terror \"No generic nobody group\"\nfi\n\nbuild_test_filter\n\n# if there is no CLIENT1 defined, some tests can be ran on localhost\nCLIENT1=${CLIENT1:-$HOSTNAME}\n# if CLIENT2 doesn't exist then use CLIENT1 instead\n# All tests should use CLIENT2 with MOUNT2 only therefore it will work if\n# $CLIENT2 == CLIENT1\n# Exception is the test which need two separate nodes\nCLIENT2=${CLIENT2:-$CLIENT1}\n\ncheck_file_size()\n{\n\tlocal client=\"$1\"\n\tlocal fpath=\"$2\"\n\tlocal expected_size=\"$3\"\n\n\tsize=$(do_facet $client stat \"--printf=%s\" $fpath)\n\t[[ $size == \"$expected_size\" ]] || error \\\n\t\t\"expected $fpath size: $expected_size got: $size\"\n}\n\ncheck_lpcc_sizes()\n{\n\tlocal client=\"$1\"\n\tlocal lpcc_fpath=\"$2\"\n\tlocal lustre_fpath=\"$3\"\n\tlocal expected_size=\"$4\"\n\n\tcheck_file_size $client $lpcc_fpath $expected_size\n\tcheck_file_size $client $lustre_fpath $expected_size\n}\n\ncheck_file_data()\n{\n\tlocal client=\"$1\"\n\tlocal path=\"$2\"\n\tlocal expected_data=\"$3\"\n\n\tpath_data=$(do_facet $client cat $path)\n\t[[ \"x$path_data\" == \"x$expected_data\" ]] || error \\\n\t\t\"expected $path: $expected_data, got: $path_data\"\n}\n\ncheck_lpcc_data()\n{\n\tlocal client=\"$1\"\n\tlocal lpcc_fpath=\"$2\"\n\tlocal lustre_fpath=\"$3\"\n\tlocal expected_data=\"$4\"\n\n\tcheck_file_data  \"$client\" \"$lpcc_fpath\" \"$expected_data\"\n\tcheck_file_data  \"$client\" \"$lustre_fpath\" \"$expected_data\"\n}\n\nlpcc_fid2path()\n{\n\tlocal hsm_root=\"$1\"\n\tlocal lustre_path=\"$2\"\n\tlocal fid=$(path2fid $lustre_path)\n\n\tlocal -a f_seq\n\tlocal -a f_oid\n\tlocal -a f_ver\n\n\tf_seq=$(echo $fid | awk -F ':' '{print $1}')\n\tf_oid=$(echo $fid | awk -F ':' '{print $2}')\n\tf_ver=$(echo $fid | awk -F ':' '{print $3}')\n\n\tprintf \"%s/%04x/%04x/%04x/%04x/%04x/%04x/%s\" \\\n\t\t$hsm_root $(($f_oid & 0xFFFF)) \\\n\t\t$(($f_oid >> 16 & 0xFFFF)) \\\n\t\t$(($f_seq & 0xFFFF)) \\\n\t\t$(($f_seq >> 16 & 0xFFFF)) \\\n\t\t$(($f_seq >> 32 & 0xFFFF)) \\\n\t\t$(($f_seq >> 48 & 0xFFFF)) $fid\n}\n\ncheck_lpcc_state()\n{\n\tlocal lustre_path=\"$1\"\n\tlocal expected_state=\"$2\"\n\tlocal facet=${3:-$SINGLEAGT}\n\tlocal myRUNAS=\"$4\"\n\tlocal state=$(do_facet $facet $myRUNAS $LFS pcc state $lustre_path |\n\t\t\tawk -F 'type: ' '{print $2}' | awk -F ',' '{print $1}')\n\n\t[[ \"x$state\" == \"x$expected_state\" ]] || error \\\n\t\t\"$lustre_path expected pcc state: $expected_state, but got: $state\"\n}\n\n# initiate variables\ninit_agt_vars\n\n# populate MDT device array\nget_mdt_devices\n\n# cleanup from previous bad setup\nkill_copytools\n\n# for recovery tests, coordinator needs to be started at mount\n# so force it\n# the lustre conf must be without hsm on (like for sanity.sh)\necho \"Set HSM on and start\"\ncdt_set_mount_state enabled\ncdt_check_state enabled\n\necho \"Set sanity-hsm HSM policy\"\ncdt_set_sanity_policy\n\n# finished requests are quickly removed from list\nset_hsm_param grace_delay 10\n\ncleanup_pcc_mapping() {\n\tlocal facet=${1:-$SINGLEAGT}\n\n\tdo_facet $facet $LCTL pcc clear $MOUNT\n}\n\nsetup_pcc_mapping() {\n\tlocal facet=${1:-$SINGLEAGT}\n\tlocal hsm_root=${hsm_root:-$(hsm_root \"$facet\")}\n\tlocal param=\"$2\"\n\n\t[ -z \"$param\" ] && param=\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\"\n\tstack_trap \"cleanup_pcc_mapping $facet\" EXIT\n\tdo_facet $facet $LCTL pcc add $MOUNT $hsm_root -p $param\n}\n\nsetup_loopdev() {\n\tlocal facet=$1\n\tlocal file=$2\n\tlocal mntpt=$3\n\tlocal size=${4:-50}\n\n\tdo_facet $facet mkdir -p $mntpt || error \"mkdir -p $hsm_root failed\"\n\tstack_trap \"do_facet $facet rm -rf $mntpt\" EXIT\n\tdo_facet $facet dd if=/dev/zero of=$file bs=1M count=$size\n\tstack_trap \"do_facet $facet rm -f $file\" EXIT\n\tdo_facet $facet mkfs.ext4 $file ||\n\t\terror \"mkfs.ext4 $file failed\"\n\tdo_facet $facet file $file\n\tdo_facet $facet mount -t ext4 -o loop,usrquota,grpquota $file $mntpt ||\n\t\terror \"mount -o loop,usrquota,grpquota $file $mntpt failed\"\n\tstack_trap \"do_facet $facet $UMOUNT $mntpt\" EXIT\n}\n\nlpcc_rw_test() {\n\tlocal restore=\"$1\"\n\tlocal project=\"$2\"\n\tlocal project_id=100\n\tlocal agt_facet=$SINGLEAGT\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal -a state\n\tlocal -a lpcc_path\n\tlocal -a size\n\n\t$project && enable_project_quota\n\n\tdo_facet $SINGLEAGT rm -rf $hsm_root\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\n\tis_project_quota_supported || project=false\n\n\tdo_facet $SINGLEAGT mkdir -p $DIR/$tdir\n\tsetup_pcc_mapping\n\t$project && lfs project -sp $project_id $DIR/$tdir\n\n\tdo_facet $SINGLEAGT \"echo -n attach_origin > $file\"\n\tif ! $project; then\n\t\tcheck_lpcc_state $file \"none\"\n\t\tdo_facet $SINGLEAGT $LFS pcc attach -i \\\n\t\t\t$HSM_ARCHIVE_NUMBER $file ||\n\t\t\terror \"pcc attach $file failed\"\n\tfi\n\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tcheck_lpcc_data $SINGLEAGT $lpcc_path $file \"attach_origin\"\n\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=7654321 count=1\n\tcheck_lpcc_sizes $SINGLEAGT $lpcc_path $file 7654321\n\n\tdo_facet $SINGLEAGT $TRUNCATE $file 1234567 ||\n\t\terror \"truncate failed\"\n\tcheck_lpcc_sizes $SINGLEAGT $lpcc_path $file 1234567\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT \"echo -n file_data > $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\tcheck_lpcc_data $SINGLEAGT $lpcc_path $file \"file_data\"\n\n\techo \"Restore testing...\"\n\tif [ $CLIENTCOUNT -lt 2 -o $restore ]; then\n\t\t$LFS hsm_restore $file || error \\\n\t\t\t\"failed to restore $file\"\n\t\twait_request_state $(path2fid $file) RESTORE SUCCEED\n\telse\n\t\tpath_data=$(do_node $CLIENT2 cat $file)\n\t\t[[ \"x$path_data\" == \"xfile_data\" ]] || error \\\n\t\t\t\"expected file_data, got: $path_data\"\n\tfi\n\n\tcheck_lpcc_state $file \"none\"\n\t# HSM exists archived status\n\tcheck_hsm_flags $file \"0x00000009\"\n\n\techo -n \"new_data\" > $file\n\tcheck_lpcc_state $file \"none\"\n\t# HSM exists dirty archived status\n\tcheck_hsm_flags $file \"0x0000000b\"\n\tcheck_file_data $SINGLEAGT $file \"new_data\"\n\n\techo \"Attach and detach testing\"\n\trm -f $file\n\tdo_facet $SINGLEAGT \"echo -n new_data2 > $file\"\n\tif ! $project; then\n\t\tcheck_lpcc_state $file \"none\"\n\t\tdo_facet $SINGLEAGT $LFS pcc attach -i \\\n\t\t\t$HSM_ARCHIVE_NUMBER $file ||\n\t\t\terror \"PCC attach $file failed\"\n\tfi\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\tdo_facet $SINGLEAGT \"echo -n attach_detach > $file\"\n\techo \"Start to detach the $file\"\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"PCC detach $file failed\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\n\tcheck_lpcc_state $file \"none\"\n\t# The file is removed from PCC\n\tcheck_hsm_flags $file \"0x00000000\"\n\tcheck_file_data $SINGLEAGT $file \"attach_detach\"\n}\n\ntest_1a() {\n\tlpcc_rw_test true false\n}\nrun_test 1a \"Test manual lfs pcc attach with manual HSM restore\"\n\ntest_1b() {\n\tlpcc_rw_test false false\n}\nrun_test 1b \"Test manual lfs pcc attach with restore on remote access\"\n\ntest_1c() {\n\tlpcc_rw_test true true\n}\nrun_test 1c \"Test automated attach using Project ID with manual HSM restore\"\n\ntest_1d() {\n\tlpcc_rw_test false true\n}\nrun_test 1d \"Test Project ID with remote access\"\n\ntest_1e() {\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal hsm_root=$(hsm_root)\n\tlocal -a lpcc_path\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\t$LCTL pcc list $MOUNT\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tchmod 777 $DIR/$tdir || error \"chmod 777 $DIR/$tdir failed\"\n\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=$file of=/dev/null bs=1024 count=1 ||\n\t\terror \"failed to dd read from $file\"\n\tdo_facet $SINGLEAGT $RUNAS $TRUNCATE $file 256 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $RUNAS $TRUNCATE $file 2048 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\n\t# non-root user is forbidden to access PCC file directly\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT $RUNAS touch $lpcc_path &&\n\t\terror \"non-root user can touch access PCC file $lpcc_path\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=$lpcc_path of=/dev/null bs=1024 \\\n\t\tcount=1 && error \"non-root user can read PCC file $lpcc_path\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$lpcc_path bs=1024 \\\n\t\tcount=1 && error \"non-root user can write PCC file $lpcc_path\"\n\n\tlocal perm=$(do_facet $SINGLEAGT stat -c %a $lpcc_path)\n\n\t[[ $perm == \"0\" ]] || error \"PCC file permission ($perm) is not zero\"\n\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n}\nrun_test 1e \"Test RW-PCC with non-root user\"\n\ntest_1f() {\n\tlocal project_id=100\n\tlocal agt_facet=$SINGLEAGT\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tdir/$tfile\n\n\t! is_project_quota_supported &&\n\t\tskip \"project quota is not supported\"\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ open_attach=0\\ stat_attach=0\"\n\n\tdo_facet $SINGLEAGT mkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir || error \"chmod 0777 $DIR/$tdir failed\"\n\t$LFS project -sp $project_id $DIR/$tdir ||\n\t\terror \"failed to set project for $DIR/$tdir\"\n\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=$file of=/dev/null bs=1024 count=1 ||\n\t\terror \"failed to dd read from $file\"\n\tdo_facet $SINGLEAGT $RUNAS $TRUNCATE $file 256 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $RUNAS $TRUNCATE $file 2048 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=256 count=1 ||\n\t\terror \"failed to dd write from $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\t# non-root user is forbidden to access PCC file directly\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT $RUNAS touch $lpcc_path &&\n\t\terror \"non-root user can touch access PCC file $lpcc_path\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=$lpcc_path of=/dev/null bs=1024 \\\n\t\tcount=1 && error \"non-root user can read PCC file $lpcc_path\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$lpcc_path bs=1024 \\\n\t\tcount=1 && error \"non-root user can write PCC file $lpcc_path\"\n\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach $file ||\n\t\terror \"failed to detach file $file\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\tcheck_lpcc_state $file \"none\"\n}\nrun_test 1f \"Test auto RW-PCC cache with non-root user\"\n\ntest_1g() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tdd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 &&\n\t\terror \"non-root user can dd write to $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 &&\n\t\terror \"non-root user can dd write to $file\"\n\tchmod 777 $file || error \"chmod 777 $file failed\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"non-root user cannot write $file with permission (777)\"\n\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach $file &&\n\t\terror \"non-root user or non owner can detach $file\"\n\tchown $RUNAS_ID $file || error \"chown $RUNAS_ID $file failed\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\tdo_facet $SINGLEAGT $RUNAS dd if=$file of=/dev/null bs=1024 count=1 ||\n\t\terror \"non-root user cannot read to $file with permisson (777)\"\n}\nrun_test 1g \"General permission test for RW-PCC\"\n\n#\n# When a process created a LPCC file and holding the open,\n# another process on the same client should be able to open the file.\n#\ntest_2a() {\n\tlocal project_id=100\n\tlocal agt_facet=$SINGLEAGT\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\n\t! is_project_quota_supported &&\n\t\tskip \"project quota is not supported\" && return\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\tfile=$DIR/$tdir/multiop\n\tmkdir -p $DIR/$tdir\n\trm -f $file\n\n\tdo_facet $SINGLEAGT $LFS project -sp $project_id $DIR/$tdir ||\n\t\terror \"failed to set project quota\"\n\trmultiop_start $agt_host $file O_c || error \"open $file failed\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\tdo_facet $SINGLEAGT \"echo -n multiopen_data > $file\" ||\n\t\terror \"failed to echo multiopen_data to $file\"\n\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT ls -l $lpcc_path ||\n\t\terror \"failed to ls $lpcc_path\"\n\tcheck_lpcc_data $SINGLEAGT $lpcc_path $file \"multiopen_data\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"failed to detach $file\"\n\trmultiop_stop $agt_host || error \"close $file failed\"\n}\nrun_test 2a \"Test multi open when creating\"\n\nget_remote_client() {\n\tcurrent_id=$(do_facet $SINGLEAGT hostname)\n\tfor client in ${CLIENTS//,/ }\n\tdo\n\t\tr_id=$(do_node $client hostname)\n\t\tif [ $r_id != $current_id ]; then\n\t\t\techo $client\n\t\t\treturn\n\t\tfi\n\tdone\n}\n\n#\n# When a process created a LPCC file and holding the open, another\n# process on the different client should be able to open the file\n# and perform IO on the file.\n#\ntest_2b() {\n\tlocal agt_facet=$SINGLEAGT\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\n\tneedclients 2 || return 0\n\n\tremote_client=$(get_remote_client)\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\tfile=$DIR/$tdir/multiop\n\tmkdir -p $DIR/$tdir\n\trm -f $file\n\n\tdo_facet $SINGLEAGT \"echo -n file_data > $file\"\n\tdo_facet $SINGLEAGT lfs pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\trmultiop_start $agt_host $file O_c || error \"open $file failed\"\n\n\tdo_node $remote_client \"echo -n multiopen_data > $file\"\n\n\t# PCC cached file should be automatically detached\n\tcheck_lpcc_state $file \"none\"\n\n\tcheck_file_data $SINGLEAGT $file \"multiopen_data\"\n\trmultiop_stop $agt_host || error \"close $file failed\"\n\tcheck_file_data $SINGLEAGT $file \"multiopen_data\"\n\n\tdo_node $remote_client cat $file || error \\\n\t\t\"cat $file on remote client failed\"\n\tdo_node $remote_client echo -n \"multiopen_data\" > $file \\\n\t\t|| error \"write $file on remote client failed\"\n}\nrun_test 2b \"Test multi remote open when creating\"\n\ntest_2c() {\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal file2=$DIR2/$tdir/$tfile\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\tmkdir -p $DIR/$tdir\n\trm -f $file\n\n\tdo_facet $SINGLEAGT \"echo -n file_data > $file\"\n\tdo_facet $SINGLEAGT lfs pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\trmultiop_start $agt_host $file O_c || error \"open $file failed\"\n\n\techo -n multiopen_data > $file2\n\n\t# PCC cached file should be automatically detached\n\tcheck_lpcc_state $file \"none\"\n\n\tcheck_file_data $SINGLEAGT $file \"multiopen_data\"\n\trmultiop_stop $agt_host || error \"close $file failed\"\n\tcheck_file_data $SINGLEAGT $file \"multiopen_data\"\n\n\tcat $file2 || error \"cat $file on mount $MOUNT2 failed\"\n\techo -n \"multiopen_data\" > $file2 ||\n\t\terror \"write $file on mount $MOUNT2 failed\"\n}\nrun_test 2c \"Test multi open on different mount points when creating\"\n\ntest_3a() {\n\tlocal file=$DIR/$tdir/$tfile\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tdd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\n\techo \"Start to attach/detach the file: $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\n\techo \"Repeat to attach/detach the same file: $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n}\nrun_test 3a \"Repeat attach/detach operations\"\n\ntest_3b() {\n\tlocal n\n\tlocal file=$DIR/$tdir/$tfile\n\n\tneedclients 3 || return 0\n\n\t# Start all of the copytools and setup PCC\n\tfor n in $(seq $AGTCOUNT); do\n\t\tcopytool setup -f agt$n -a $n -m $MOUNT\n\t\tsetup_pcc_mapping agt$n \"projid={100}\\ rwid=$n\\ auto_attach=0\"\n\tdone\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tdd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\n\techo \"Start to attach/detach $file on $agt1_HOST\"\n\tdo_facet agt1 $LFS pcc attach -i 1 $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\" agt1\n\tdo_facet agt1 $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\" agt1\n\n\techo \"Repeat to attach/detach $file on $agt2_HOST\"\n\tdo_facet agt2 $LFS pcc attach -i 2 $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\" agt2\n\tdo_facet agt2 $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\" agt2\n\n\techo \"Try attach on two agents\"\n\tdo_facet agt1 $LFS pcc attach -i 1 $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\" agt1\n\tdo_facet agt2 $LFS pcc attach -i 2 $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\" agt2\n\t# The later attach PCC agent should succeed,\n\t# the former agent should be detached automatically.\n\tcheck_lpcc_state $file \"none\" agt1\n\tdo_facet agt2 $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\" agt2\n}\nrun_test 3b \"Repeat attach/detach operations on multiple clients\"\n\ntest_4() {\n\tlocal project_id=100\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal excepts=\"-e 6 -e 7 -e 8 -e 9\"\n\n\t! is_project_quota_supported &&\n\t\tskip \"project quota is not supported\" && return\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tlfs project -sp $project_id $DIR/$tdir ||\n\t\terror \"lfs project -sp $project_id $DIR/$tdir failed\"\n\n\t# 1. mmap_sanity tst7 failed on the local ext4 filesystem.\n\t#    It seems that Lustre filesystem does special process for tst 7.\n\t# 2. There is a mmap problem for PCC when multiple clients read/write\n\t#    on a shared mmapped file for mmap_sanity tst 6.\n\t# 3. Current CentOS8 kernel does not strictly obey POSIX syntax for\n\t#    mmap() within the maping but beyond current end of the underlying\n\t#    files: It does not send SIGBUS signals to the process.\n\t# 4. For negative file offset, sanity_mmap also failed on 48 bits\n\t#    ldiksfs backend due to too large offset: \"Value too large for\n\t#    defined data type\".\n\t# mmap_sanity tst7/tst8/tst9 all failed on Lustre and local ext4.\n\t# Thus, we exclude sanity tst6/tst7/tst8/tst9 from the PCC testing.\n\t$LUSTRE/tests/mmap_sanity -d $DIR/$tdir -m $DIR2/$tdir $excepts ||\n\t\terror \"mmap_sanity test failed\"\n\tsync; sleep 1; sync\n\n\t# Revoke the layout lock, the PCC-cached file will be\n\t# detached automatically.\n\tdo_facet $SINGLEAGT $LCTL \\\n\t\tset_param ldlm.namespaces.*mdc*.lru_size=clear\n\trm -rf $DIR/$tdir || error \"failed to remove $DIR/$tdir\"\n}\nrun_test 4 \"Auto cache test for mmap\"\n\ntest_5() {\n\tlocal file=$DIR/$tfile\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tdo_facet $SINGLEAGT \"echo -n attach_mmap_data > $file\" ||\n\t\terror \"echo $file failed\"\n\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tlocal content=$($MMAP_CAT $file)\n\n\t[[ $content == \"attach_mmap_data\" ]] ||\n\t\terror \"mmap cat data mismatch: $content\"\n\n\t$LFS hsm_restore $file || error \"failed to restore $file\"\n\twait_request_state $(path2fid $file) RESTORE SUCCEED\n\tcheck_lpcc_state $file \"none\"\n\n\tcontent=$($MMAP_CAT $file)\n\t[[ $content == \"attach_mmap_data\" ]] ||\n\t\terror \"mmap cat data mismatch: $content\"\n}\nrun_test 5 \"Mmap & cat a RW-PCC cached file\"\n\ntest_6() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal content\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\techo -n mmap_write_data > $file || error \"echo write $file failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $MULTIOP $file OSMWUc ||\n\t\terror \"could not mmap $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcontent=$(do_facet $SINGLEAGT $MMAP_CAT $file)\n\t# After mmap write via multiop, the first character of each page\n\t# increases with 1.\n\t[[ $content == \"nmap_write_data\" ]] ||\n\t\terror \"mmap write data mismatch: $content\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"failed to detach file $file\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\n\tcontent=$(do_facet $SINGLEAGT $MMAP_CAT $file)\n\t[[ $content == \"nmap_write_data\" ]] ||\n\t\terror \"mmap write data mismatch: $content\"\n}\nrun_test 6 \"Test mmap write on RW-PCC \"\n\ntest_7a() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal content\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\techo \"QQQQQ\" > $file\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcheck_file_data $SINGLEAGT $file \"QQQQQ\"\n\t# define OBD_FAIL_LLITE_PCC_DETACH_MKWRITE\t0x1412\n\tdo_facet $SINGLEAGT $LCTL set_param fail_loc=0x1412\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\t# multiop mmap write increase the first character of each page with 1\n\tdo_facet $SINGLEAGT $MULTIOP $file OSMWUc ||\n\t\terror \"mmap write $file failed\"\n\tcheck_lpcc_state $file \"none\"\n\tcontent=$(do_facet $SINGLEAGT $MMAP_CAT $file)\n\t[[ $content == \"RQQQQ\" ]] || error \"data mismatch: $content\"\n}\nrun_test 7a \"Fake file detached between fault() and page_mkwrite() for RW-PCC\"\n\ntest_7b() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal content\n\tlocal pid\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\n\techo \"QQQQQ\" > $file\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcheck_file_data $SINGLEAGT $file \"QQQQQ\"\n\t# define OBD_FAIL_LLITE_PCC_MKWRITE_PAUSE\t0x1413\n\tdo_facet $SINGLEAGT $LCTL set_param fail_loc=0x1413 fail_val=20\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\t# multiop mmap write increases the first character of each page with 1\n\tdo_facet $SINGLEAGT $MULTIOP $file OSMWUc &\n\tpid=$!\n\n\tsleep 3\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\n\twait $pid || error \"multiop mmap write failed\"\n\tcheck_lpcc_state $file \"none\"\n\tcontent=$(do_facet $SINGLEAGT $MMAP_CAT $file)\n\t[[ $content == \"RQQQQ\" ]] || error \"data mismatch: $content\"\n}\nrun_test 7b \"Test the race with concurrent mkwrite and detach\"\n\ntest_8() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\techo \"QQQQQ\" > $file\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach file $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcheck_file_data $SINGLEAGT $file \"QQQQQ\"\n\n\t# define OBD_FAIL_LLITE_PCC_FAKE_ERROR\t0x1411\n\tdo_facet $SINGLEAGT $LCTL set_param fail_loc=0x1411\n\tdo_facet $SINGLEAGT \"echo -n ENOSPC_write > $file\"\n\t# Above write will return -ENOSPC failure and retry the IO on normal\n\t# IO path. It will restore the HSM released file.\n\tcheck_lpcc_state $file \"none\"\n\tcheck_file_data $SINGLEAGT $file \"ENOSPC_write\"\n}\nrun_test 8 \"Test fake -ENOSPC tolerance for RW-PCC\"\n\ntest_9() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.9a\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMVER\" -h \"$hsm_root\"\n\tsetup_pcc_mapping\n\tdo_facet $SINGLEAGT $LCTL pcc list $MOUNT\n\n\ttouch $file || error \"touch $file failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"fail to attach $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\t# write 60M data, it is larger than the capacity of PCC backend\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1M count=60 ||\n\t\terror \"fail to dd write $file\"\n\tcheck_lpcc_state $file \"none\"\n\tcheck_file_size $SINGLEAGT $file 62914560\n}\nrun_test 9 \"Test -ENOSPC tolerance on loop PCC device for RW-PCC\"\n\ntest_usrgrp_quota() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal ug=$1\n\tlocal id=$RUNAS_ID\n\n\t[[ $ug == \"g\" ]] && id=$RUNAS_GID\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tdo_facet $SINGLEAGT quotacheck -c$ug $mntpt ||\n\t\terror \"quotacheck -c$ug $mntpt failed\"\n\tdo_facet $SINGLEAGT quotaon -$ug $mntpt ||\n\t\terror \"quotaon -$ug $mntpt failed\"\n\tdo_facet $SINGLEAGT setquota -$ug $id 0 20480 0 0 $mntpt ||\n\t\terror \"setquota -$ug $id on $mntpt failed\"\n\tdo_facet $SINGLEAGT repquota -${ug}vs $mntpt\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMVER\" -h \"$hsm_root\"\n\tsetup_pcc_mapping\n\tdo_facet $SINGLEAGT $LCTL pcc list $MOUNT\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\n\tlocal file1=$DIR/$tdir/${ug}quotaA\n\tlocal file2=$DIR/$tdir/${ug}quotaB\n\n\tdd if=/dev/zero of=$file1 bs=1M count=15 ||\n\t\terror \"dd write $file1 failed\"\n\tdd if=/dev/zero of=$file2 bs=1M count=15 ||\n\t\terror \"dd write $file2 failed\"\n\tchown $RUNAS_ID:$RUNAS_GID $file1 ||\n\t\terror \"chown $RUNAS_ID:$RUNAS_GID $file1 failed\"\n\tchown $RUNAS_ID:$RUNAS_GID $file2 ||\n\t\terror \"chown $RUNAS_ID:$RUNAS_GID $file2 failed\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file1 || error \"attach $file1 failed\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file2 && error \"attach $file2 should fail due to quota limit\"\n\tcheck_lpcc_state $file1 \"readwrite\"\n\tcheck_lpcc_state $file2 \"none\"\n\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file1 bs=1M count=30 ||\n\t\terror \"dd write $file1 failed\"\n\t# -EDQUOT error should be tolerated via fallback to normal Lustre path.\n\tcheck_lpcc_state $file1 \"none\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file1 ||\n\t\terror \"failed to detach file $file\"\n\trm $file1 $file2\n}\n\ntest_10a() {\n\ttest_usrgrp_quota \"u\"\n}\nrun_test 10a \"Test RW-PCC with user quota on loop PCC device\"\n\ntest_10b() {\n\ttest_usrgrp_quota \"g\"\n}\nrun_test 10b \"Test RW-PCC with group quota on loop PCC device\"\n\ntest_11() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal -a lpcc_path\n\tlocal lpcc_dir\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tdo_facet $SINGLEAGT \"echo -n QQQQQ > $file\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tlpcc_dir=$(dirname $lpcc_path)\n\techo \"Lustre file: $file LPCC dir: $lpcc_dir\"\n\tdo_facet $SINGLEAGT mkdir -p $lpcc_dir ||\n\t\terror \"mkdir -p $lpcc_dir failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcheck_file_data $SINGLEAGT $file \"QQQQQ\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach $file\"\n\trm $file || error \"rm $file failed\"\n\n\t# The parent directory of the PCC file is immutable\n\tdo_facet $SINGLEAGT \"echo -n immutable_dir > $file\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tlpcc_dir=$(dirname $lpcc_path)\n\techo \"Lustre file: $file LPCC dir: $lpcc_dir\"\n\tdo_facet $SINGLEAGT mkdir -p $lpcc_dir ||\n\t\terror \"mkdir -p $lpcc_dir failed\"\n\tdo_facet $SINGLEAGT chattr +i $lpcc_dir ||\n\t\terror \"chattr +i $lpcc_dir failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file &&\n\t\terror \"attach $file with immutable directory should be failed\"\n\tdo_facet $SINGLEAGT chattr -i $lpcc_dir ||\n\t\terror \"chattr -i $lpcc_dir failed\"\n\trm $file || error \"rm $file failed\"\n\n\t# The PCC file path is set to a directory\n\tdo_facet $SINGLEAGT \"echo -n pcc_file_path_is_dir > $file\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT mkdir -p $lpcc_path ||\n\t\terror \"mkdir -p $lpcc_path failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file &&\n\t\terror \"attach $file should fail as PCC path is a directory\"\n\trm $file || error \"rm $file failed\"\n}\nrun_test 11 \"Test attach fault injection with simulated PCC file path\"\n\ntest_12() {\n\tlocal file=$DIR/$tfile\n\tlocal hsm_root=$(hsm_root)\n\tlocal -a lpcc_path\n\tlocal pid\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\n\techo  -n race_rw_attach_hsmremove > $file\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"attach $file failed\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"detach $file failed\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\t# define OBD_FAIL_LLITE_PCC_ATTACH_PAUSE\t0x1414\n\tdo_facet $SINGLEAGT $LCTL set_param fail_loc=0x1414 fail_val=20\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file &\n\tpid=$!\n\t$LFS hsm_state $file\n\tsleep 3\n\twait_request_state $(path2fid $file) RESTORE SUCCEED\n\t$LFS hsm_remove $file || error \"hsm remove $file failed\"\n\twait $pid && error \"RW-PCC attach $file should fail\"\n\tdo_facet $SINGLEAGT \"[ -f $lpcc_path ]\"\t&&\n\t\terror \"RW-PCC cached file '$lpcc_path' should be removed\"\n\n\treturn 0\n}\nrun_test 12 \"RW-PCC attach races with concurrent HSM remove\"\n\ntest_rule_id() {\n\tlocal idstr=\"${1}id\"\n\tlocal rule=\"${idstr}={$2}\"\n\tlocal myRUNAS=\"$3\"\n\tlocal file=$DIR/$tdir/$tfile\n\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"$rule\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\t$LCTL pcc list $MOUNT\n\n\tdo_facet $SINGLEAGT mkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir || error \"chmod 0777 $DIR/$tdir failed\"\n\n\trm -f $file || error \"rm $file failed\"\n\tdo_facet $SINGLEAGT $myRUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $myRUNAS dd if=$file of=/dev/null bs=1024 count=1 ||\n\t\terror \"failed to dd read from $file\"\n\tdo_facet $SINGLEAGT $myRUNAS $TRUNCATE $file 256 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $myRUNAS $TRUNCATE $file 2048 ||\n\t\terror \"failed to truncate $file\"\n\tdo_facet $SINGLEAGT $myRUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write from $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $myRUNAS $LFS pcc detach $file ||\n\t\terror \"failed to detach file $file\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\tcheck_lpcc_state $file \"none\"\n\n\tcleanup_pcc_mapping\n}\n\ntest_13a() {\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\ttest_rule_id \"u\" \"500\" \"runas -u 500\"\n\ttest_rule_id \"g\" \"500\" \"runas -u 500 -g 500\"\n}\nrun_test 13a \"Test auto RW-PCC create caching for UID/GID rule\"\n\ntest_13b() {\n\tlocal file\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"fname={*.h5\\ suffix.*\\ Mid*dle}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\t$LCTL pcc list $MOUNT\n\n\tdo_facet $SINGLEAGT mkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir || error \"chmod 0777 $DIR/$tdir failed\"\n\n\tfile=$DIR/$tdir/prefix.h5\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $myRUNAS $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/suffix.doc\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $myRUNAS $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/MidPADdle\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $myRUNAS $LFS pcc detach -k $file ||\n\t\terror \"failed to detach file $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/Midpad\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n}\nrun_test 13b \"Test auto RW-PCC create caching for file name with wildcard\"\n\ntest_13c() {\n\tlocal file\n\tlocal myRUNAS\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\n\t! is_project_quota_supported &&\n\t\techo \"Skip project quota is not supported\" && return 0\n\n\tenable_project_quota\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100\\ 200}\\&fname={*.h5},uid={500}\\&gid={1000}\\ rwid=$HSM_ARCHIVE_NUMBER\"\n\t$LCTL pcc list $MOUNT\n\tdo_facet $SINGLEAGT mkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir || error \"chmod 0777 $DIR/$tdir failed\"\n\n\tmkdir -p $DIR/$tdir/proj || error \"mkdir $DIR/$tdir/proj failed\"\n\tmkdir -p $DIR/$tdir/proj2 || error \"mkdir $DIR/$tdir/proj2 failed\"\n\t$LFS project -sp 100 $DIR/$tdir/proj ||\n\t\terror \"failed to set project for $DIR/$tdir/proj\"\n\t$LFS project -sp 200 $DIR/$tdir/proj2 ||\n\t\terror \"failed to set project for $DIR/$tdir/proj2\"\n\n\tfile=$DIR/$tdir/proj/notcache\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/proj/autocache.h5\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach $file\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/proj2/notcache\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"none\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/proj2/autocache.h5\n\tdo_facet $SINGLEAGT dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach $file\"\n\trm $file || error \"rm $file failed\"\n\n\tfile=$DIR/$tdir/ugidcache\n\tmyRUNAS=\"runas -u 500 -g 1000\"\n\tdo_facet $SINGLEAGT $myRUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"failed to detach $file\"\n\trm $file || error \"rm $file failed\"\n}\nrun_test 13c \"Check auto RW-PCC create caching for UID/GID/ProjID/fname rule\"\n\ntest_14() {\n\tlocal file=$DIR/$tdir/$tfile\n\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\n\tmkdir -p $DIR/$tdir || error \"mkdir -p $DIR/$tdir failed\"\n\tdo_facet $SINGLEAGT \"echo -n autodetach_data > $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\t# Revoke the layout lock, the PCC-cached file will be\n\t# detached automatically.\n\tdo_facet $SINGLEAGT $LCTL \\\n\t\tset_param ldlm.namespaces.*mdc*.lru_size=clear\n\tcheck_file_data $SINGLEAGT $file \"autodetach_data\"\n\tcheck_lpcc_state $file \"none\"\n}\nrun_test 14 \"Revocation of the layout lock should detach the file automatically\"\n\ntest_15() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tdir/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tmkdir $DIR/$tdir || error \"mkdir $DIR/$tdir failed\"\n\tchmod 777 $DIR/$tdir || error \"chmod 777 $DIR/$tdir failed\"\n\n\techo \"Check open attach for non-root user\"\n\tdo_facet $SINGLEAGT $RUNAS dd if=/dev/zero of=$file bs=1024 count=1 ||\n\t\terror \"failed to dd write to $file\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"failed to attach file $file\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc state $file\n\tcheck_lpcc_state $file \"readwrite\" $SINGLEAGT \"$RUNAS\"\n\t# Revoke the layout lock, the PCC-cached file will be\n\t# detached automatically.\n\tdo_facet $SINGLEAGT $LCTL \\\n\t\tset_param ldlm.namespaces.*mdc*.lru_size=clear\n\tcheck_lpcc_state $file \"readwrite\" $SINGLEAGT \"$RUNAS\"\n\t# Detach the file but keep the cache , as the file layout generation\n\t# is not changed, so the file is still valid cached in PCC, and can\n\t# be reused from PCC cache directly.\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach -k $file ||\n\t\terror \"PCC detach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\" $SINGLEAGT \"$RUNAS\"\n\tdo_facet $SINGLEAGT $RUNAS $LFS pcc detach $file ||\n\t\terror \"PCC detach $file failed\"\n\trm $file || error \"rm $file failed\"\n\n\techo \"check open attach for root user\"\n\tdo_facet $SINGLEAGT \"echo -n autoattach_data > $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\t# Revoke the layout lock, the PCC-cached file will be\n\t# detached automatically.\n\tdo_facet $SINGLEAGT $LCTL \\\n\t\tset_param ldlm.namespaces.*mdc*.lru_size=clear\n\tcheck_file_data $SINGLEAGT $file \"autoattach_data\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\t# Detach the file with -k option, as the file layout generation\n\t# is not changed, so the file is still valid cached in PCC,\n\t# and can be reused from PCC cache directly.\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"PCC detach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\tcheck_file_data $SINGLEAGT $file \"autoattach_data\"\n\n\t# HSM restore the PCC cached file, the layout generation\n\t# was changed, so the file can not be auto attached.\n\t$LFS hsm_restore $file || error \"failed to restore $file\"\n\twait_request_state $(path2fid $file) RESTORE SUCCEED\n\tcheck_lpcc_state $file \"none\"\n\t# HSM exists archived status\n\tcheck_hsm_flags $file \"0x00000009\"\n\n}\nrun_test 15 \"Test auto attach at open when file is still valid cached\"\n\ntest_16() {\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal -a lpcc_path\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping\n\n\tdo_facet $SINGLEAGT \"echo -n detach_data > $file\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER \\\n\t\t$file || error \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\techo \"Test for reusing valid PCC cache\"\n\t# Valid PCC cache can be reused\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"PCC detach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\t# HSM released exists archived status\n\tcheck_hsm_flags $file \"0x0000000d\"\n\n\techo \"Test for the default detach\"\n\t# Permanent detach by default, it will remove the PCC copy\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"PCC detach $file failed\"\n\twait_request_state $(path2fid $file) REMOVE SUCCEED\n\tcheck_lpcc_state $file \"none\"\n\t# File is removed from PCC backend\n\tcheck_hsm_flags $file \"0x00000000\"\n\tdo_facet $SINGLEAGT \"[ -f $lpcc_path ]\"\t&&\n\t\terror \"RW-PCC cached file '$lpcc_path' should be removed\"\n\n\treturn 0\n}\nrun_test 16 \"Test detach with different options\"\n\ntest_17() {\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ open_attach=0\\ stat_attach=0\"\n\n\tdo_facet $SINGLEAGT $LCTL pcc list $MOUNT\n\n\tdo_facet $SINGLEAGT \"echo -n layout_refresh_data > $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"PCC attach $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"PCC detach $file failed\"\n\tcheck_lpcc_state $file \"none\"\n\n\t# Truncate should attach the file into PCC automatically\n\t# as the PCC copy is still valid.\n\techo \"Verify auto attach during IO for truncate\"\n\tdo_facet $SINGLEAGT $TRUNCATE $file 4 || error \"truncate $file failed\"\n\tcheck_lpcc_state $file \"readwrite\"\n\n\techo \"Verify auto attach during IO for read/write\"\n\trmultiop_start $agt_host $file O_r || error \"open $file failed\"\n\tsleep 3\n\n\t# Revoke the layout lock, the PCC-cached file will be\n\t# detached automatically.\n\tdo_facet $SINGLEAGT $LCTL \\\n\t\tset_param ldlm.namespaces.*mdc*.lru_size=clear\n\n\tcheck_lpcc_state $file \"none\"\n\trmultiop_stop $agt_host || error \"close $file failed\"\n\tsleep 3\n\tcheck_lpcc_state $file \"readwrite\"\n\n\tdo_facet $SINGLEAGT $LFS pcc detach -k $file ||\n\t\terror \"PCC detach $file failed\"\n\tcheck_lpcc_state $file \"none\"\n}\nrun_test 17 \"Test auto attach for layout refresh\"\n\ntest_18() {\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\tlocal oldmd5\n\tlocal newmd5\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\"\n\n\tdo_facet $SINGLEAGT $LCTL pcc list $MOUNT\n\tdo_facet $SINGLEAGT dd if=/dev/urandom of=$file bs=1M count=4 ||\n\t\terror \"failed to write $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach $file\"\n\tdo_facet $SINGLEAGT $LFS pcc state $file\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach --keep $file ||\n\t\terror \"failed to detach $file\"\n\tdo_facet $SINGLEAGT $LFS pcc state $file\n\t$CHECKSTAT -s 4194304 $file\n\tdd if=/dev/zero of=$DIR2/$tfile seek=1k bs=1k count=1 ||\n\t\terror \"failed to write $DIR2/$tfile\"\n\toldmd5=$(md5sum $DIR2/$tfile | awk '{print $1}')\n\t$CHECKSTAT -s 1049600 $DIR2/$tfile || error \"$DIR2/$tfile size wrong\"\n\n\tlocal lpcc_path=$(lpcc_fid2path $hsm_root $file)\n\n\tdo_facet $SINGLEAGT $LFS pcc state $file\n\tcheck_file_size $SINGLEAGT $lpcc_path 4194304\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"failed to attach $file\"\n\tcheck_lpcc_sizes $SINGLEAGT $lpcc_path $file 1049600\n\tnewmd5=$(do_facet $SINGLEAGT md5sum $file | awk '{print $1}')\n\t[ \"$oldmd5\" == \"$newmd5\" ] || error \"md5sum differ: $oldmd5 != $newmd5\"\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"failed to detach $file\"\n}\nrun_test 18 \"Verify size correctness after re-attach the file\"\n\ntest_19() {\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\\ auto_attach=0\"\n\n\tdo_facet $SINGLEAGT \"echo -n QQQQQ > $file\" || error \"echo $file failed\"\n\tlpcc_path=$(lpcc_fid2path $hsm_root $file)\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"Failed to attach $file\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tcheck_lpcc_sizes $SINGLEAGT $file $lpcc_path 5\n\tdo_facet $SINGLEAGT $LFS pcc detach --keep $file ||\n\t\terror \"Failed to detach $file\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"Failed to attach $file\"\n\tcheck_lpcc_sizes $SINGLEAGT $file $lpcc_path 5\n\tdo_facet $SINGLEAGT $LFS pcc detach --keep $file ||\n\t\terror \"Failed to detach $file\"\n}\nrun_test 19 \"Verify the file re-attach works as expected\"\n\ntest_20() {\n\tlocal agt_host=$(facet_active_host $SINGLEAGT)\n\tlocal loopfile=\"$TMP/$tfile\"\n\tlocal mntpt=\"/mnt/pcc.$tdir\"\n\tlocal hsm_root=\"$mntpt/$tdir\"\n\tlocal file=$DIR/$tfile\n\n\tsetup_loopdev $SINGLEAGT $loopfile $mntpt 50\n\tcopytool setup -m \"$MOUNT\" -a \"$HSM_ARCHIVE_NUMBER\"\n\tsetup_pcc_mapping $SINGLEAGT \\\n\t\t\"projid={100}\\ rwid=$HSM_ARCHIVE_NUMBER\"\n\n\tdo_facet $SINGLEAGT \"echo -n QQQQQ > $file\" ||\n\t\terror \"echo $file failed\"\n\tdo_facet $SINGLEAGT $LFS pcc attach -i $HSM_ARCHIVE_NUMBER $file ||\n\t\terror \"Failed to attach $file\"\n\tdo_facet $SINGLEAGT \"echo 3 > /proc/sys/vm/drop_caches\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT \"echo 3 > /proc/sys/vm/drop_caches\"\n\tdo_facet $SINGLEAGT \"echo 3 > /proc/sys/vm/drop_caches\"\n\tcheck_lpcc_state $file \"readwrite\"\n\tdo_facet $SINGLEAGT $LFS pcc detach $file ||\n\t\terror \"Failed to detach $file\"\n}\nrun_test 20 \"Auto attach works after the inode was once evicted from cache\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1491}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\n# bug number for skipped test:\nALWAYS_EXCEPT=\"$SANITY_PFL_EXCEPT \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n# Skip tests for PPC that fail frequently\nif [[ $(uname -m) = ppc64 ]]; then\n\t# bug number:    LU-13186 LU-13205 LU-13207 LU-13186\n\tALWAYS_EXCEPT+=\" 14       16a      16b      17\"\nfi\n\nbuild_test_filter\n\ncheck_and_setup_lustre\n\nif [[ \"$MDS1_VERSION\" -lt $(version_code 2.9.51) ]]; then\n\tskip_env \"Need MDS version at least 2.9.51\"\nfi\n\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&\n\terror \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\n\nassert_DIR\nrm -rf $DIR/[Rdfs][0-9]*\n\ntest_0a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((3 * 1024 * 1024))\t# 3M\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t$LFS setstripe -E 1m -S 1M -c 1 -E -1 -c 1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t#instantiate all components, so that objs are allocted\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=2k\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"$ost_idx1 == $ost_idx2\"\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 0a \"Create full components file, no reused OSTs\"\n\ntest_0b() {\n\t[[ $($LCTL get_param mdc.*.import |\n\t\tgrep \"connect_flags:.*overstriping\") ]] ||\n\t\tskip \"server does not support overstriping\"\n\tlarge_xattr_enabled || skip_env \"no large xattr support\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\n\ttest_mkdir $DIR/$tdir\n\n\t# Create file with 1.1*LOV_MAX_STRIPE_COUNT stripes should succeed\n\t$LFS setstripe -E 1m -C $((LOV_MAX_STRIPE_COUNT / 10)) -E -1 \\\n\t\t-C $LOV_MAX_STRIPE_COUNT $comp_file ||\n\terror \"Create $comp_file failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n\n\t# Create file with 2*LOV_MAX_STRIPE_COUNT stripes should fail\n\t$LFS setstripe -E 1m -C $LOV_MAX_STRIPE_COUNT -E -1 -C $LOV_MAX_STRIPE_COUNT \\\n\t\t$comp_file && error \"Create $comp_file succeeded\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 0b \"Verify comp stripe count limits\"\n\ntest_1a() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((3 * 1024 * 1024))\t# 3M\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t$LFS setstripe -E 1m -S 1m -o 0 -E -1 -o 0 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t#instantiate all components, so that objs are allocted\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=2k\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\n\t[ $ost_idx1 -ne $ost_idx2 ] && error \"$ost_idx1 != $ost_idx2\"\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 1a \"Create full components file, reused OSTs\"\n\n# test overstriping (>1 stripe/OST within a component)\ntest_1b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\" && return\n\t[[ $($LCTL get_param mdc.*.import |\n\t\tgrep \"connect_flags:.*overstriping\") ]] ||\n\t\tskip \"server does not support overstriping\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((3 * 1024 * 1024))\t# 3M\n\n\ttest_mkdir $DIR/$tdir\n\n\t$LFS setstripe -E 1m -S 1m -o 0,0 -E -1 -o 1,1,0,0 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t#instantiate all components, so that objs are allocted\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=1M\n\n\t$LFS getstripe $comp_file\n\tlocal OSTS_1=$($LFS getstripe -I1 $comp_file | grep -o 'l_ost_idx.*' |\n\t\t      awk -e '{print $2}' | tr \"\\n\" \"\\0\")\n\tlocal OSTS_2=$($LFS getstripe -I2 $comp_file | grep -o 'l_ost_idx.*' |\n\t\t      awk -e '{print $2}' | tr \"\\n\" \"\\0\")\n\n\techo \":\"$OSTS_1\":\"\n\techo \":\"$OSTS_2\":\"\n\t[ \"$OSTS_1\" = \"0,0,\" ] || error \"incorrect OSTs($OSTS_1) in component 1\"\n\t[ \"$OSTS_2\" = \"1,1,0,0,\" ] ||\n\t\terror \"incorrect OSTs($OSTS_2) in component 2\"\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 1b \"Create full components file, overstriping in components\"\n\n# test overstriping with max stripe count\ntest_1c() {\n\t[[ $($LCTL get_param mdc.*.import |\n\t\tgrep \"connect_flags:.*overstriping\") ]] ||\n\t\tskip \"server does not support overstriping\"\n\tlarge_xattr_enabled || skip_env \"no large xattr support\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((3 * 1024 * 1024))\t# 3M\n\n\ttest_mkdir $DIR/$tdir\n\n\t$LFS setstripe -E 1m -C 10 -E 10M -C 100 -E -1 \\\n\t    -C $LOV_MAX_STRIPE_COUNT $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# Seek & write in to last component so all objects are allocated\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=20000\n\n\tlocal count=$($LFS getstripe -c -I1 $DIR/$tdir/$tfile)\n\t[ $count -eq 10 ] || error \"comp1 stripe count $count, should be 10\"\n\tcount=$($LFS getstripe -c -I2 $DIR/$tdir/$tfile)\n\t[ $count -eq 100 ] || error \"comp2 stripe count $count, should be 100\"\n\tcount=$($LFS getstripe -c -I3 $DIR/$tdir/$tfile)\n\t[ $count -eq $LOV_MAX_STRIPE_COUNT ] ||\n\t\terror \"comp4 stripe count $count != $LOV_MAX_STRIPE_COUNT\"\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 1c \"Test overstriping w/max stripe count\"\n\ntest_2() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((5 * 1024 * 1024))\t# 5M\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t$LFS setstripe -E 1m -S 1m $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tcheck_component_count $comp_file 1\n\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 > /dev/null 2>&1 ||\n\t\terror \"Write first component failed\"\n\tdd if=$comp_file of=/dev/null bs=1M count=1 > /dev/null 2>&1 ||\n\t\terror \"Read first component failed\"\n\n\tdd if=/dev/zero of=$comp_file bs=1M count=2 > /dev/null 2>&1 &&\n\t\terror \"Write beyond component should fail\"\n\tdd if=$comp_file of=/dev/null bs=1M count=2 > /dev/null 2>&1 ||\n\t\terror \"Read beyond component should short read, not fail\"\n\n\t$LFS setstripe --component-add -E 2M -S 1M -c 1 $comp_file ||\n\t\terror \"Add component to $comp_file failed\"\n\n\tcheck_component_count $comp_file 2\n\n\t$LFS setstripe --component-add -E -1 -c 3 $comp_file ||\n\t\terror \"Add last component to $comp_file failed\"\n\n\tcheck_component_count $comp_file 3\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 2 \"Add component to existing file\"\n\ndel_comp_and_verify() {\n\tlocal comp_file=$1\n\tlocal id=$2\n\tlocal left=$3\n\tlocal size=$4\n\n\tlocal opt=\"-I \"\n\tif [ $id == \"init\" -o $id == \"^init\" ]; then\n\t\topt=\"--component-flags=\"\n\tfi\n\n\t$LFS setstripe --component-del $opt$id $comp_file ||\n\t\terror \"Delete component $id from $comp_file failed\"\n\n\tlocal comp_cnt=$($LFS getstripe --component-count $comp_file)\n\tif grep -q \"has no stripe info\" <<< \"$comp_cnt\" ; then\n\t\tcomp_cnt=0\n\tfi\n\t[ $comp_cnt -ne $left ] && error \"$comp_cnt != $left\"\n\n\t$CHECKSTAT -s $size $comp_file || error \"size != $size\"\n}\n\ntest_3() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t$LFS setstripe -E 1M -S 1M -E 64M -c 2 -E -1 -c 3 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tcheck_component_count $comp_file 3\n\n\tdd if=/dev/zero of=$comp_file bs=1M count=2\n\n\t$LFS setstripe --component-del -I 2 $comp_file &&\n\t\terror \"Component deletion makes hole\"\n\n\tdel_comp_and_verify $comp_file 3 2 $((2 * 1024 * 1024))\n\tdel_comp_and_verify $comp_file 2 1 $((1 * 1024 * 1024))\n\tdel_comp_and_verify $comp_file 1 0 0\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n\n\t$LFS setstripe -E 1M -S 1M -E 16M -E -1 $comp_file ||\n\t\terror \"Create second $comp_file failed\"\n\n\tdel_comp_and_verify $comp_file \"^init\" 1 0\n\tdel_comp_and_verify $comp_file \"init\" 0 0\n\trm -f $comp_file || error \"Delete second $comp_file failed\"\n\n}\nrun_test 3 \"Delete component from existing file\"\n\ntest_4() {\n\tskip \"Not supported in PFL\"\n\t# In PFL project, only LCME_FL_INIT is supported, and it can't\n\t# be altered by application.\n}\nrun_test 4 \"Modify component flags in existing file\"\n\ntest_5() {\n\tlocal parent=$DIR/$tdir\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal subdir=$parent/subdir\n\n\trm -fr $parent\n\ttest_mkdir $parent\n\n\t# set default layout to parent directory\n\t$LFS setstripe -E 64M -c 2 -i 0 -E -1 -c 4 -i 0 $parent ||\n\t\terror \"Set default layout to $parent failed\"\n\n\t# create file under parent\n\ttouch $comp_file || error \"Create $comp_file failed\"\n\tcheck_component_count $comp_file 2\n\n\t#instantiate all components, so that objs are allocted\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=65k\n\n\tlocal ost_idx=$($LFS getstripe -I1 -i $comp_file)\n\t[ $ost_idx -ne 0 ] &&\n\t\terror \"component 1 ost_idx $ost_idx != 0\"\n\n\tost_idx=$($LFS getstripe -I2 -i $comp_file)\n\t[ $ost_idx -ne 0 ] &&\n\t\terror \"component 2 ost_idx $ost_idx != 0\"\n\n\t# create subdir under parent\n\tmkdir -p $subdir || error \"Create subdir $subdir failed\"\n\n\tcomp_cnt=$($LFS getstripe -d --component-count $subdir)\n\t[ $comp_cnt -ne 2 ] && error \"subdir $comp_cnt != 2\"\n\n\t# create file under subdir\n\ttouch $subdir/$tfile || error \"Create $subdir/$tfile failed\"\n\n\tcheck_component_count $subdir/$tfile 2\n\n\t# delete default layout setting from parent\n\t$LFS setstripe -d $parent ||\n\t\terror \"Delete default layout from $parent failed\"\n\n\tcomp_cnt=$($LFS getstripe -d --component-count $parent)\n\t[ $comp_cnt -ne 0 ] && error \"$comp_cnt isn't 0\"\n\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n\trm -f $subdir/$tfile || error \"Delete $subdir/$tfile failed\"\n\trm -r $subdir || error \"Delete subdir $subdir failed\"\n\trmdir $parent || error \"Delete dir $parent failed\"\n}\nrun_test 5 \"Inherit composite layout from parent directory\"\n\ntest_6() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $DIR/$tfile\n\n\t$LFS setstripe -c 1 -S 128K $comp_file ||\n\t\terror \"Create v1 $comp_file failed\"\n\n\tcheck_component_count $comp_file 0\n\n\tdd if=/dev/urandom of=$comp_file bs=1M count=5 oflag=sync ||\n\t\terror \"Write to v1 $comp_file failed\"\n\n\tlocal old_chksum=$(md5sum $comp_file)\n\n\t# Migrate v1 to composite\n\t$LFS migrate -E 1M -S 512K -c 1 -E -1 -S 1M -c 2 $comp_file ||\n\t\terror \"Migrate(v1 -> composite) $comp_file failed\"\n\n\tcheck_component_count $comp_file 2\n\n\tlocal chksum=$(md5sum $comp_file)\n\t[ \"$old_chksum\" != \"$chksum\" ] &&\n\t\terror \"(v1 -> compsoite) $old_chksum != $chksum\"\n\n\t# Migrate composite to composite\n\t$LFS migrate -E 1M -S 1M -c 2 -E 4M -S 1M -c 2 \\\n\t\t-E -1 -S 3M -c 3 $comp_file ||\n\t\terror \"Migrate(compsoite -> composite) $comp_file failed\"\n\n\tcheck_component_count $comp_file 3\n\n\tchksum=$(md5sum $comp_file)\n\t[ \"$old_chksum\" != \"$chksum\" ] &&\n\t\terror \"(composite -> compsoite) $old_chksum != $chksum\"\n\n\t# Migrate composite to v1\n\t$LFS migrate -c 2 -S 2M $comp_file ||\n\t\terror \"Migrate(composite -> v1) $comp_file failed\"\n\n\tcheck_component_count $comp_file 0\n\n\tchksum=$(md5sum $comp_file)\n\t[ \"$old_chksum\" != \"$chksum\" ] &&\n\t\terror \"(composite -> v1) $old_chksum != $chksum\"\n\n\trm -f $comp_file || \"Delete $comp_file failed\"\n}\nrun_test 6 \"Migrate composite file\"\n\ntest_7() {\n\ttest_mkdir $DIR/$tdir\n\tchmod 0777 $DIR/$tdir || error \"chmod $tdir failed\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\t$RUNAS $LFS setstripe -E 1M -S 1M -c 1 $comp_file ||\n\t\terror \"Create composite file $comp_file failed\"\n\n\t$RUNAS $LFS setstripe --component-add -E 64M -c 4 $comp_file ||\n\t\terror \"Add component to $comp_file failed\"\n\n\t$RUNAS $LFS setstripe --component-del -I 2 $comp_file ||\n\t\terror \"Delete component from $comp_file failed\"\n\n\t$RUNAS $LFS setstripe --component-add -E -1 -c 5 $comp_file ||\n\t\terror \"Add last component to $comp_file failed\"\n\n\trm $comp_file || \"Delete composite failed\"\n}\nrun_test 7 \"Add/Delete/Create composite file by non-privileged user\"\n\ntest_8() {\n\tlocal parent=$DIR/$tdir\n\n\trm -fr $parent\n\ttest_mkdir $parent\n\n\t$LFS setstripe -E 2M -c 1 -S 1M -E 16M -c 2 -S 2M \\\n\t\t-E -1 -c 4 -S 4M $parent ||\n\t\terror \"Set default layout to $parent failed\"\n\n\tsh rundbench -C -D $parent 2 || error \"dbench failed\"\n\n\trm -fr $parent || error \"Delete dir $parent failed\"\n}\nrun_test 8 \"Run dbench over composite files\"\n\ntest_9() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t$LFS setstripe -E 1M -S 1M -E -1 -c 1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tcheck_component_count $comp_file 2\n\n\treplay_barrier $SINGLEMDS\n\n\t# instantiate the 2nd component\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=2k\n\n\tlocal f1=$($LFS getstripe -I2 $comp_file |\n\t\t\tawk '/l_fid:/ {print $7}')\n\techo \"before MDS recovery, the ost fid of 2nd component is $f1\"\n\tfail $SINGLEMDS\n\n\tlocal f2=$($LFS getstripe -I2 $comp_file |\n\t\t\tawk '/l_fid:/ {print $7}')\n\techo \"after MDS recovery, the ost fid of 2nd component is $f2\"\n\t[ \"x$f1\" == \"x$f2\" ] || error \"$f1 != $f2\"\n}\nrun_test 9 \"Replay layout extend object instantiation\"\n\ncomponent_dump() {\n\techo $($LFS getstripe $1 |\n\t\tawk '$1 == \"lcm_entry_count:\" { printf(\"%d\", $2) }\n\t\t     $1 == \"lcme_extent.e_start:\" { printf(\"[%#lx\", $2) }\n\t\t     $1 == \"lcme_extent.e_end:\" { printf(\",%s]\", $2) }')\n}\n\ntest_10() {\n\tlocal parent=$DIR/$tdir\n\tlocal root=$MOUNT\n\n\tsave_layout_restore_at_exit $MOUNT\n\n\trm -rf $parent\n\n\t# mount root on $MOUNT2 if FILESET is set\n\tif [ -n \"$FILESET\" ]; then\n\t\tFILESET=\"\" mount_client $MOUNT2 ||\n\t\t\terror \"mount $MOUNT2 fail\"\n\t\troot=$MOUNT2\n\tfi\n\n\t$LFS setstripe -d $root || error \"clear root layout\"\n\n\t# set root composite layout\n\t$LFS setstripe -E 2M -c 1 -S 1M -E 16M -c2 -S 2M \\\n\t\t-E -1 -c 4 -S 4M $root ||\n\t\terror \"Set root layout failed\"\n\n\tif [ \"$root\" == \"$MOUNT2\" ]; then\n\t\tumount_client $MOUNT2 ||\n\t\t\terror \"umount $MOUNT2 fail\"\n\tfi\n\n\ttest_mkdir $parent\n\t# set a different layout for parent\n\t$LFS setstripe -E -1 -c 1 -S 1M $parent ||\n\t\terror \"set $parent layout failed\"\n\ttouch $parent/file1\n\n\tlocal f1_entry=$(component_dump $parent/file1)\n\n\t# delete parent's layout\n\t$LFS setstripe -d $parent || error \"Clear $parent layout failed\"\n\ttouch $parent/file2\n\n\tlocal f2_entry=$(component_dump $parent/file2)\n\n\t# verify layout inheritance\n\tlocal eof=\"EOF\"\n\tlocal f1_expect=\"1[0,EOF]\"\n\tlocal f2_expect=\"3[0,2097152][0x200000,16777216][0x1000000,EOF]\"\n\n\techo \"f1 expect=$f1_expect\"\n\techo \"f1 get   =$f1_entry\"\n\techo \"f2 expect=$f2_expect\"\n\techo \"f2 get   =$f2_entry\"\n\n\t[  x$f1_expect != x$f1_entry ] &&\n\t\terror \"$parent/file1 does not inherite parent layout\"\n\t[  x$f2_expect != x$f2_entry ] &&\n\t\terror \"$parent/file2 does not inherite root layout\"\n\n\treturn 0\n}\nrun_test 10 \"Inherit composite template from root\"\n\ntest_11() {\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir $DIR/$tdir\n\trm -f $comp_file\n\n\t# only 1st component instantiated\n\t$LFS setstripe -E 1M -S 1M -E 2M -E 3M -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal f1=$($LFS getstripe -I1 $comp_file | grep \"l_fid\")\n\t[[ -z $f1 ]] && error \"1: 1st component uninstantiated\"\n\tlocal f2=$($LFS getstripe -I2 $comp_file | grep \"l_fid\")\n\t[[ -n $f2 ]] && error \"1: 2nd component instantiated\"\n\tlocal f3=$($LFS getstripe -I3 $comp_file | grep \"l_fid\")\n\t[[ -n $f3 ]] && error \"1: 3rd component instantiated\"\n\tlocal f4=$($LFS getstripe -I4 $comp_file | grep \"l_fid\")\n\t[[ -n $f4 ]] && error \"1: 4th component instantiated\"\n\n\t# the first 2 components instantiated\n\t# Truncate to exact start of new component - LU-12586\n\t$TRUNCATE $comp_file $((1024*1024*1))\n\n\tf2=$($LFS getstripe -I2 $comp_file | grep \"l_fid\")\n\t[[ -z $f2 ]] && error \"2: 2nd component uninstantiated\"\n\tf3=$($LFS getstripe -I3 $comp_file | grep \"l_fid\")\n\t[[ -n $f3 ]] && error \"2: 3rd component instantiated\"\n\tf4=$($LFS getstripe -I4 $comp_file | grep \"l_fid\")\n\t[[ -n $f4 ]] && error \"2: 4th component instantiated\"\n\n\t# the first 3 components instantiated\n\t$TRUNCATE $comp_file $((1024*1024*3 - 1))\n\t$TRUNCATE $comp_file $((1024*1024*1+1))\n\n\tf2=$($LFS getstripe -I2 $comp_file | grep \"l_fid\")\n\t[[ -z $f2 ]] && error \"3: 2nd component uninstantiated\"\n\tf3=$($LFS getstripe -I3 $comp_file | grep \"l_fid\")\n\t[[ -z $f3 ]] && error \"3: 3rd component uninstantiated\"\n\tf4=$($LFS getstripe -I4 $comp_file | grep \"l_fid\")\n\t[[ -n $f4 ]] && error \"3: 4th component instantiated\"\n\n\t# all 4 components instantiated, using append write\n\tdd if=/dev/zero of=$comp_file bs=1k count=1 seek=2k\n\tls -l $comp_file\n\trwv -f $comp_file -w -a -n 2 $((1024*1023)) 1\n\tls -l $comp_file\n\n\tf4=$($LFS getstripe -I4 $comp_file | grep \"l_fid\")\n\t[[ -z $f4 ]] && error \"4: 4th component uninstantiated\"\n\n\treturn 0\n}\nrun_test 11 \"Verify component instantiation with write/truncate\"\n\ntest_12() {\n\t[ $OSTCOUNT -lt 3 ] && skip \"needs >= 3 OSTs\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\ttest_mkdir $DIR/$tdir\n\trm -f $file\n\n\t# specify ost list for component\n\t$LFS setstripe -E 1M -S 1M -c 2 -o 0,1 -E 2M -c 2 -o 1,2 \\\n\t\t-E 3M -c 2 -o 2,1 -E 4M -c 1 -i 2 -E -1 $file ||\n\t\terror \"Create $file failed\"\n\n\t# clear lod component cache\n\tstop $SINGLEMDS || error \"stop MDS\"\n\tlocal MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})\n\tstart $SINGLEMDS $MDT_DEV $MDS_MOUNT_OPTS || error \"start MDS\"\n\n\t# instantiate all components\n\t$TRUNCATE $file $((1024*1024*4+1))\n\n\t#verify object alloc order\n\tlocal o1=$($LFS getstripe -I1 $file |\n\t\t\tawk '/l_ost_idx:/ {printf(\"%d\",$5)}')\n\t[[ $o1 != \"01\" ]] && error \"$o1 is not 01\"\n\n\tlocal o2=$($LFS getstripe -I2 $file |\n\t\t\tawk '/l_ost_idx:/ {printf(\"%d\",$5)}')\n\t[[ $o2 != \"12\" ]] && error \"$o2 is not 12\"\n\n\tlocal o3=$($LFS getstripe -I3 $file |\n\t\t\tawk '/l_ost_idx:/ {printf(\"%d\",$5)}')\n\t[[ $o3 != \"21\" ]] && error \"$o3 is not 21\"\n\n\tlocal o4=$($LFS getstripe -I4 $file |\n\t\t\tawk '/l_ost_idx:/ {printf(\"%d\",$5)}')\n\t[[ $o4 != \"2\" ]] && error \"$o4 is not 2\"\n\n\treturn 0\n}\nrun_test 12 \"Verify ost list specification\"\n\ntest_13() { # LU-9311\n\t[ $OSTCOUNT -lt 8 ] && skip \"needs >= 8 OSTs\"\n\n\tlocal file=$DIR/$tfile\n\tlocal dd_count=4\n\tlocal dd_size=$(($dd_count * 1024 * 1024))\n\tlocal real_size\n\n\trm -f $file\n\t$LFS setstripe -E 1M -S 1M -c 1 -E 2M -c 2 -E -1 -c -1 -i 1 $file ||\n\t\terror \"Create $file failed\"\n\tdd if=/dev/zero of=$file bs=1M count=$dd_count\n\treal_size=$(stat -c %s $file)\n\t[ $real_size -eq $dd_size ] ||\n\t\terror \"dd actually wrote $real_size != $dd_size bytes\"\n\n\trm -f $file\n}\nrun_test 13 \"shouldn't reprocess granted resent request\"\n\ntest_14() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\tlocal file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\trm -f $file\n\n\t$LFS setstripe -E1m -c1 -S1m --pool=\"pool1\" -E2m \\\n\t\t\t-E4m -c2 -S2m --pool=\"pool2\" -E-1 $file ||\n\t\terror \"Create $file failed\"\n\n\t# check --pool inheritance\n\tlocal pool\n\tpool=\"$($LFS getstripe -I2 --pool $file)\"\n\t[ x\"$pool\" != \"xpool1\" ] && $LFS getstripe -I2 $file &&\n\t\terror \"$file: component 2 doesn't have poolname pool1\"\n\tpool=\"$($LFS getstripe -I4 --pool $file)\"\n\t[ x\"$pool\" != \"xpool2\" ] && $LFS getstripe -I4 $file &&\n\t\terror \"$file: component 4 doesn't have poolname pool2\"\n\n\t#check --stripe-count inheritance\n\tlocal count\n\tcount=\"$($LFS getstripe -I2 -c $file)\"\n\t[ $count -ne 1 ] && $LFS getstripe -I2 $file &&\n\t\terror \"$file: component 2 doesn't have 1 stripe_count\"\n\tcount=\"$($LFS getstripe -I4 -c $file)\"\n\t[ $count -ne 2 ] && $LFS getstripe -I4 $file &&\n\t\terror \"$file: component 4 doesn't have 2 stripe_count\"\n\n\t#check --stripe-size inheritance\n\tlocal size\n\tsize=\"$($LFS getstripe -I2 -S $file)\"\n\t[ $size -ne $((1024*1024)) ] && $LFS getstripe -I2 $file &&\n\t\terror \"$file: component 2 doesn't have 1M stripe_size\"\n\tsize=\"$($LFS getstripe -I4 -S $file)\"\n\t[ $size -ne $((1024*1024*2)) ] && $LFS getstripe -I4 $file &&\n\t\terror \"$file: component 4 doesn't have 2M stripe_size\"\n\n\treturn 0\n}\nrun_test 14 \"Verify setstripe poolname/stripe_count/stripe_size inheritance\"\n\ntest_15() {\n\tlocal parent=$DIR/$tdir\n\n\trm -fr $parent\n\ttest_mkdir $parent\n\n\t$LFS setstripe -d $parent || error \"delete default layout\"\n\n\t$LFS setstripe -E 1M -S 1M -E 10M -E eof $parent/f1 || error \"create f1\"\n\t$LFS setstripe -E 4M -E 20M -E eof $parent/f2 || error \"create f2\"\n\ttest_mkdir $parent/subdir\n\t$LFS setstripe -E 6M -S 1M -c1 -E 30M -c4 -E eof -c -1 $parent/subdir ||\n\t\terror \"setstripe to subdir\"\n\t$LFS setstripe -E 8M -E eof $parent/subdir/f3 || error \"create f3\"\n\t$LFS setstripe -c 1 $parent/subdir/f4 || error \"create f4\"\n\n\t# none\n\tlocal found=$($LFS find --component-start +2M -E -15M $parent | wc -l)\n\t[ $found -eq 0 ] || error \"start+2M, end-15M, $found != 0\"\n\n\t# f2, f3\n\tfound=$($LFS find --component-start +2M -E -35M $parent | wc -l)\n\t[ $found -eq 2 ] || error \"start+2M, end-35M, $found != 2\"\n\n\t# subdir\n\tfound=$($LFS find --component-start +4M -E -eof $parent | wc -l)\n\t[ $found -eq 1 ] || error \"start+4M, end-eof, $found != 1\"\n\n\tlocal flg_opts=\"--component-flags init\"\n\t# none\n\tfound=$($LFS find --component-start 1M -E 10M $flg_opts $parent | wc -l)\n\t[ $found -eq 0 ] ||\n\t\terror \"before write: start=1M, end=10M, flag=init, $found != 0\"\n\n\tdd if=/dev/zero of=$parent/f1 bs=1M count=2 ||\n\t\terror \"dd $parent/f1 failed\"\n\n\t# f1\n\tfound=$($LFS find --component-start 1M -E 10M $flg_opts $parent | wc -l)\n\t[ $found -eq 1 ] ||\n\t\terror \"after write: start=1M, end=10M, flag=init, $found != 1\"\n\n\tlocal ext_opts=\"--component-start -1M -E +5M\"\n\t# parent, subdir, f3, f4\n\tfound=$($LFS find $ext_opts $parent | wc -l)\n\t[ $found -eq 4 ] || error \"start-1M, end+5M, $found != 4\"\n\n\tlocal cnt_opts=\"--component-count +2\"\n\t# subdir\n\tfound=$($LFS find $ext_opts $cnt_opts $parent | wc -l)\n\t[ $found -eq 1 ] || error \"start-1M, end+5M, count+2, $found != 1\"\n\n\t# none\n\tfound=$($LFS find $ext_opts $cnt_opts $flg_opts $parent | wc -l)\n\t[ $found -eq 0 ] ||\n\t\terror \"start-1M, end+5M, count+2, flag=init, $found != 0\"\n\n\t# f3, f4\n\tfound=$($LFS find $ext_opts ! $cnt_opts $flg_opts $parent | wc -l)\n\t[ $found -eq 2 ] ||\n\t\terror \"start-1M, end+5M, !count+2, flag=init, $found != 2\"\n\n\t# check last component stripe count\n\tif [ $OSTCOUNT -gt 1 ]; then\n\t\ttouch $parent/subdir/f5\n\t\t$TRUNCATE $parent/subdir/f5 $((32*1024*1024))\n\t\tfound=$($LFS find $parent/subdir -c $OSTCOUNT)\n\t\t[[ \"$found\" == \"$parent/subdir/f5\" ]] ||\n\t\t\terror \"got '$found' with stripe_count=$OSTCOUNT, not f5\"\n\tfi\n}\nrun_test 15 \"Verify component options for lfs find\"\n\ntest_16a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\tlarge_xattr_enabled || skip_env \"ea_inode feature disabled\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal dir=$DIR/$tdir/dir\n\tlocal temp=$DIR/$tdir/template\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\n\t#####################################################################\n\t#\t                    1. PFL file\n\t# set stripe for source file\n\t$LFS setstripe -E1m -S 1M -c2 -o0,1 -E2m -c2 -E3m -o1,0 -E4m -c1 -E-1 \\\n\t\t$file || error \"Create $file failed\"\n\n\techo \"1. PFL file\"\n\tverify_yaml_layout $file $file.copy $temp \"1. PFL file\"\n\n\t#####################################################################\n\t#\t                    2. plain file\n\t# set stripe for source file\n\trm -f $file\n\t$LFS setstripe -c2 -o0,1 -i1 $file || error \"Create $file failed\"\n\n\trm -f $file.copy\n\techo \"2. plain file\"\n\tverify_yaml_layout $file $file.copy $temp \"2. plain file\"\n\n\t#####################################################################\n\t#\t                    3. PFL dir\n\t# set stripe for source dir\n\ttest_mkdir $dir\n\t$LFS setstripe -E1m -S 1M -c2 -E2m -c1 -E-1 $dir ||\n\t\terror \"setstripe $dir failed\"\n\n\ttest_mkdir $dir.copy\n\techo \"3. PFL dir\"\n\tverify_yaml_layout $dir $dir.copy $temp.dir \"3. PFL dir\"\n\n\t#####################################################################\n\t#\t                    4. plain dir\n\t# set stripe for source dir\n\t$LFS setstripe -c2 -i-1 $dir || error \"setstripe $dir failed\"\n\n\techo \"4. plain dir\"\n\tverify_yaml_layout $dir $dir.copy $temp.dir \"4. plain dir\"\n}\nrun_test 16a \"Verify setstripe/getstripe with YAML config file\"\n\ntest_16b() {\n\t[[ $($LCTL get_param mdc.*.import |\n\t\tgrep \"connect_flags:.*overstriping\") ]] ||\n\t\tskip \"server does not support overstriping\"\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&\n\t\tskip_env \"too many osts, skipping\"\n\tlarge_xattr_enabled || skip_env \"ea_inode feature disabled\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal dir=$DIR/$tdir/dir\n\tlocal temp=$DIR/$tdir/template\n\t# We know OSTCOUNT < (LOV_MAX_STRIPE_COUNT / 2), so this is overstriping\n\tlocal large_count=$((LOV_MAX_STRIPE_COUNT / 2 + 10))\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\n\t#####################################################################\n\t#\t                    1. PFL file, overstriping in first comps\n\t# set stripe for source file\n\t$LFS setstripe -E1m -S 1M -o0,0 -E2m -o1,1 -E3m -C $large_count -E-1 \\\n\t\t$file || error \"Create $file failed\"\n\n\techo \"1. PFL file\"\n\tverify_yaml_layout $file $file.copy $temp \"1. PFL file\"\n\n\t#####################################################################\n\t#\t                    2. plain file + overstriping\n\t# set stripe for source file\n\trm -f $file\n\t$LFS setstripe -C $large_count -i1 $file || error \"Create $file failed\"\n\n\trm -f $file.copy\n\techo \"2. plain file\"\n\tverify_yaml_layout $file $file.copy $temp \"2. plain file\"\n\n\t#####################################################################\n\t#\t                    3. PFL dir + overstriping\n\t# set stripe for source dir\n\ttest_mkdir $dir\n\t$LFS setstripe -E1m -S 1M -o 0,0 -E2m -C $large_count -E-1 $dir ||\n\t\terror \"setstripe $dir failed\"\n\n\ttest_mkdir $dir.copy\n\techo \"3. PFL dir\"\n\tverify_yaml_layout $dir $dir.copy $temp.dir \"3. PFL dir\"\n\n\t#####################################################################\n\t#\t                    4. plain dir + overstriping\n\t# set stripe for source dir\n\t$LFS setstripe -C $large_count $dir || error \"setstripe $dir failed\"\n\n\techo \"4. plain dir\"\n\tverify_yaml_layout $dir $dir.copy $temp.dir \"4. plain dir\"\n}\nrun_test 16b \"Verify setstripe/getstripe with YAML config file + overstriping\"\n\ntest_16c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal dir=$DIR/$tdir/dir\n\tlocal temp=$DIR/$tdir/template\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\n\t#####################################################################\n\t#\t                    1. SEL file\n\t# set stripe for source file\n\t$LFS setstripe -E256M -S 1M -c2 -o0,1 -z 64M -E-1 -o1,0 -z 128M \\\n\t\t$file || error \"Create $file failed\"\n\n\techo \"1. SEL file\"\n\tverify_yaml_layout $file $file.copy $temp \"1. PFL file\"\n\n\t#####################################################################\n\t#\t                    2. SEL dir\n\t# set stripe for source dir\n\ttest_mkdir $dir\n\t$LFS setstripe -E256M -S 1M -c2 -z 64M -E-1 -z 128M \\\n\t\t$dir || error \"setstripe $dir failed\"\n\n\ttest_mkdir $dir.copy\n\techo \"2. SEL template on dir\"\n\tverify_yaml_layout $dir $dir.copy $temp.dir \"2. PFL dir\"\n}\nrun_test 16c \"Verify setstripe/getstripe for SEL layout with YAML config file\"\n\ntest_17() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\tlocal file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\trm -f $file\n\n\t$LFS setstripe -E 1M -S 1M -E 2M -c 2 -E -1 -c -1 $file ||\n\t\terror \"Create $file failed\"\n\n\tlocal s1=$($LFS getstripe -I1 -v $file | awk '/lcme_size:/{print $2}')\n\tlocal s2=$($LFS getstripe -I2 -v $file | awk '/lcme_size:/{print $2}')\n\tlocal s3=$($LFS getstripe -I3 -v $file | awk '/lcme_size:/{print $2}')\n\techo \"1st init: comp size 1:$s1 2:$s2 3:$s3\"\n\n\t# init 2nd component\n\t$TRUNCATE $file $((1024*1024+1))\n\tlocal s1n=$($LFS getstripe -I1 -v $file | awk '/lcme_size:/{print $2}')\n\tlocal s2n=$($LFS getstripe -I2 -v $file | awk '/lcme_size:/{print $2}')\n\techo \"2nd init: comp size 1:$s1n 2:$s2n 3:$s3\"\n\n\t[ $s1 -eq $s1n ] || error \"1st comp size $s1 should == $s1n\"\n\t[ $s2 -lt $s2n ] || error \"2nd comp size $s2 should < $s2n\"\n\n\t# init 3rd component\n\t$TRUNCATE $file $((1024*1024*2+1))\n\ts1n=$($LFS getstripe -I1 -v $file | awk '/lcme_size:/{print $2}')\n\ts2n=$($LFS getstripe -I2 -v $file | awk '/lcme_size:/{print $2}')\n\tlocal s3n=$($LFS getstripe -I3 -v $file | awk '/lcme_size:/{print $2}')\n\techo \"3rd init: comp size 1:$s1n 2:$s2n 3:$s3n\"\n\n\t[ $s1 -eq $s1n ] || error \"1st comp size $s1 should == $s1n\"\n\t[ $s2 -lt $s2n ] || error \"2nd comp size $s2 should < $s2n\"\n\t[ $s3 -lt $s3n ] || error \"3rd comp size $s3 should < $s3n\"\n}\nrun_test 17 \"Verify LOVEA grows with more component inited\"\n\ncheck_distribution() {\n\tlocal file=$1\n\tlocal objs\n\tlocal ave\n\tlocal obj_min_one=$((OSTCOUNT - 1))\n\n\tobjs=$($LFS getstripe $file |\n\t\tawk '/l_ost_idx:/ { print $5 }' | wc -l)\n\tlet ave=$((objs / OSTCOUNT))\n\n\t# collect objects per OST distribution\n\t$LFS getstripe $file | awk '/l_ost_idx:/ { print $5 }' | tr -d \",\" |\n\t\t(inuse=( $(for i in $(seq 0 $obj_min_one); do echo 0; done) )\n\t\twhile read O; do\n\t\t\tlet inuse[$O]=$((1 + ${inuse[$O]}))\n\t\tdone;\n\n\t\t# verify object distribution varies no more than +-1\n\t\tfor idx in $(seq 0 $obj_min_one); do\n\t\t\tlet dif=$((${inuse[$idx]} - ave))\n\t\t\tlet dif=${dif#-}\n\t\t\tif [ \"$dif\" -gt 1 ]; then\n\t\t\t\techo \"OST${idx}: ${inuse[$idx]} objects\"\n\t\t\t\terror \"bad distribution on OST${idx}\"\n\t\t\tfi\n\t\tdone)\n}\n\ntest_18() {\n\tlocal file1=$DIR/${tfile}-1\n\tlocal file2=$DIR/${tfile}-2\n\tlocal file3=$DIR/${tfile}-3\n\n\trm -f $file1 $file2 $file3\n\n\t$LFS setstripe -E 1m -S 1m $file1 ||\n\t\terror \"Create $file1 failed\"\n\t$LFS setstripe -E 1m -S 1m $file2 ||\n\t\terror \"Create $file2 failed\"\n\t$LFS setstripe -E 1m -S 1m $file3 ||\n\t\terror \"Create $file3 failed\"\n\n\tlocal objs=$((OSTCOUNT+1))\n\tfor comp in $(seq 1 $OSTCOUNT); do\n\t\t$LFS setstripe --component-add -E $((comp+1))M -c 1 $file1 ||\n\t\t\terror \"Add component to $file1 failed 2\"\n\t\t$LFS setstripe --component-add -E $((comp+1))M -c 1 $file2 ||\n\t\t\terror \"Add component to $file2 failed 2\"\n\t\t$LFS setstripe --component-add -E $((comp+1))M -c 1 $file3 ||\n\t\t\terror \"Add component to $file3 failed 2\"\n\tdone\n\n\t$LFS setstripe --component-add -E -1 -c -1 $file1 ||\n\t\terror \"Add component to $file1 failed 3\"\n\t$LFS setstripe --component-add -E -1 -c -1 $file2 ||\n\t\terror \"Add component to $file2 failed 3\"\n\t$LFS setstripe --component-add -E -1 -c -1 $file3 ||\n\t\terror \"Add component to $file3 failed 3\"\n\n\t# Instantiate all components\n\tdd if=/dev/urandom of=$file1 bs=1M count=$((objs+1)) ||\n\t\terror \"dd failed for $file1\"\n\tdd if=/dev/urandom of=$file2 bs=1M count=$((objs+1)) ||\n\t\terror \"dd failed for $file2\"\n\tdd if=/dev/urandom of=$file3 bs=1M count=$((objs+1)) ||\n\t\terror \"dd failed for $file3\"\n\n\tcheck_distribution $file1\n\tcheck_distribution $file2\n\tcheck_distribution $file3\n\n}\nrun_test 18 \"check component distribution\"\n\ntest19_io_base() {\n\tlocal comp_file=$1\n\tlocal already_created=${2:-0}\n\tlocal rw_len=$((3 * 1024 * 1024))       # 3M\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\tif [ $already_created != 1 ]; then\n\t\ttest_mkdir -p $DIR/$tdir\n\t\t$LFS setstripe --extension-size 64M -c 1 -E -1 $comp_file ||\n\t\t\terror \"Create $comp_file failed\"\n\tfi\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=127 conv=notrunc ||\n\t\terror \"dd to extend failed\"\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"$ost_idx1 == $ost_idx2\"\n\t[ $ost_idx2 -ne \"-1\" ] && error \"second component init $ost_idx2\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0 -E 128M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: Extended first component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 128M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\tfound=$($LFS find -z 64M $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"component not found by ext size\"\n\n\tfound=$($LFS find --extension-size +63M $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"component not found by +ext size\"\n\n\tfound=$($LFS find --ext-size -65M $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"component not found by -ext size\"\n\n\tfound=$($LFS find -z 65M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by wrong ext size\"\n\n\tfound=$($LFS find -z +65M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by wrong +ext size\"\n\n\tfound=$($LFS find -z -63M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by wrong -ext size\"\n\n\tfound=$($LFS find ! -z 64M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by negation of ext size\"\n\n\tfound=$($LFS find ! -z +63M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by negation of +ext size\"\n\n\tfound=$($LFS find ! -z -65M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by negation of -ext size\"\n\n\tfound=$($LFS find ! -z 65M $comp_file | wc -l)\n\t[ $found -eq 1 ] ||\n\t\terror \"component not found by negation of wrong ext size\"\n\n\tfound=$($LFS find ! -z +65M $comp_file | wc -l)\n\t[ $found -eq 1 ] ||\n\t\terror \"component not found by negation of wrong +ext size\"\n\n\tfound=$($LFS find ! -z -63M $comp_file | wc -l)\n\t[ $found -eq 1 ] ||\n\t\terror \"component not found by negation of wrong -ext size\"\n\n\tfound=$($LFS find -S +1M $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"component found by wrong +stripe size\"\n\n\tfound=$($LFS find -c 1 $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"component not found by stripe count\"\n\n\tsmall_write $comp_file $rw_len || error \"Verify RW failed\"\n\n\tsel_layout_sanity $comp_file 2\n}\n\n# Self-extending PFL tests\ntest_19a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\ttest19_io_base $DIR/$tdir/$tfile\n}\nrun_test 19a \"Simple test of extension behavior\"\n\n# Same as 19a, but with default layout set on directory rather than on file\ntest_19b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal comp_dir=$DIR/$tdir/$tdir\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\t$LFS setstripe --ext-size 64M -c 1 -E -1 $DIR/$tdir ||\n\t\terror \"Setstripe on $DIR/$tdir failed\"\n\n\t# check inheritance for a sub-dir and a file\n\ttest_mkdir $comp_dir\n\tfound=$($LFS find --comp-start 0 -E 64M $comp_dir | wc -l)\n\t[ $found -eq 1 ] || error \"Dir Inheritance: wrong first component size\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 64M -E EOF $flg_opts $comp_dir | wc -l)\n\t[ $found -eq 1 ] || error \"Dir Inheritance: Second component not found\"\n\n\ttouch $comp_file\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0 -E 64M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"File Inheritance: wrong first component size\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 64M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"File Inheritance: Second component not found\"\n\n\ttest19_io_base $comp_file 1\n}\nrun_test 19b \"Simple test of SEL as default layout\"\n\n# Test behavior when seeking deep in a file\ntest_19c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -z 128M -E 1G -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=130 conv=notrunc ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0M -E 256M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: first extension component not found\"\n\n\tflg_opts=\"--comp-flags extension,^init\"\n\tfound=$($LFS find --comp-start 256M -E 1024M $flg_opts $comp_file |\\\n\t\twc -l)\n\t[ $found -eq 1 ] || error \"Write: second extension component not found\"\n\n\tlocal end_1=$($LFS getstripe -I1 -E $comp_file)\n\n\t# 256 MiB\n\t[ $end_1 -eq 268435456 ] ||\n\t\terror \"end of first component $end_1 != 268435456\"\n\n\t# Write past end of extension space component, in to normal component\n\t# should exhaust & remove extension component\n\tdd if=/dev/zero bs=1M count=1 seek=1100 of=$comp_file conv=notrunc ||\n\t\terror \"dd distant seek failed\"\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\t# the last component index is 3\n\tlocal ost_idx2=$($LFS getstripe -I3 -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"$ost_idx1 == $ost_idx2\"\n\n\tlocal start1=$($LFS getstripe -I1 --comp-start $comp_file)\n\tlocal end1=$($LFS getstripe -I1 -E $comp_file)\n\tlocal start2=$($LFS getstripe -I3 --comp-start $comp_file)\n\tlocal end2=$($LFS getstripe -I3 -E $comp_file)\n\n\t[ $start1 -eq 0 ] || error \"start of first component incorrect\"\n\t[ $end1 -eq 1073741824 ] || error \"end of first component incorrect\"\n\t[ $start2 -eq 1073741824  ] ||\n\t\terror \"start of second component incorrect\"\n\t[ \"$end2\" = \"EOF\" ] || error \"end of second component incorrect\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"Seek Write: extension component exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 19c \"Test self-extending layout seeking behavior\"\n\ntest_19d() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 128M -c 1 -z 64M -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# This will cause component 1 to be extended to 128M, then the\n\t# extension space component will be removed\n\tdd if=/dev/zero of=$comp_file bs=130M count=1 ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0M -E 128M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: first component not found\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 128M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\tsel_layout_sanity $comp_file 2\n\n\t# always remove large files in case of DO_CLEANUP=false\n\trm -f $comp_file || error \"Delete $comp_file failed\"\n}\nrun_test 19d \"Test write which completely spans extension space component\"\n\ntest_19e_check() {\n\tcomp_file=$1\n\n\tlocal comp2_flags=$($LFS getstripe -I2 --comp-flags $comp_file)\n\tlocal comp3_flags=$($LFS getstripe -I3 --comp-flags $comp_file)\n\n\t[ \"$comp2_flags\" != \"init\" ] && error \"$comp2_flags != init\"\n\t[ \"$comp3_flags\" != \"extension\" ] && error \"$comp3_flags != extension\"\n\n\tlocal flg_opts=\" --comp-start 2M -E 66M --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extended second component not found\"\n\n\tflg_opts=\"--comp-start 66M -E EOF --comp-flags extension\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: third component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\n\ntest_19e() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal rw_len=$((3 * 1024 * 1024))       # 3M\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 2m -E -1 -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\treplay_barrier $SINGLEMDS\n\n\t#instantiate & extend second component\n\tdd if=/dev/zero of=$comp_file bs=4M count=1 ||\n\t\terror \"dd to extend failed\"\n\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\tlocal ost_idx3=$($LFS getstripe -I3 -i $comp_file)\n\n\t[ $ost_idx2 -eq $ost_idx3 ] && error \"$ost_idx2 == $ost_idx3\"\n\t[ $ost_idx3 -ne \"-1\" ] && error \"third component init $ost_idx3\"\n\n\ttest_19e_check $comp_file\n\n\tlocal f1=$($LFS getstripe -I2 $comp_file | awk '/l_fid:/ {print $7}')\n\techo \"before MDS recovery, the ost fid of 2nd component is $f1\"\n\n\tfail $SINGLEMDS\n\n\tlocal f2=$($LFS getstripe -I2 $comp_file | awk '/l_fid:/ {print $7}')\n\techo \"after MDS recovery, the ost fid of 2nd component is $f2\"\n\t[ \"x$f1\" == \"x$f2\" ] || error \"$f1 != $f2\"\n\n\t# simply repeat all previous checks, but also verify components are on\n\t# the same OST as before\n\n\tlocal ost_idx2_2=$($LFS getstripe -I2 -i $comp_file)\n\tlocal ost_idx3_2=$($LFS getstripe -I3 -i $comp_file)\n\n\t[ $ost_idx2_2 -eq $ost_idx3_2 ] && error \"$ost_idx2_2 == $ost_idx3_2\"\n\t[ $ost_idx3_2 -ne \"-1\" ] && error \"second component init $ost_idx3_2\"\n\n\t# verify OST id is the same after failover\n\t[ $ost_idx2 -ne $ost_idx2_2 ] &&\n\t\terror \"$ost_idx2 != $ost_idx2_2, changed after failover\"\n\n\ttest_19e_check $comp_file\n}\nrun_test 19e \"Replay of layout instantiation & extension\"\n\ntest_19f() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 256M --comp-flags extension -E -1 $comp_file\n\n\t[ $? != 0 ] || error \"should not be able to manually set extension flag\"\n\n}\nrun_test 19f \"Rejection of invalid layouts\"\n\ntest_19g() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal file1=$DIR/${tfile}-1\n\tlocal file2=$DIR/${tfile}-2\n\n\ttest_mkdir -p $DIR/$tdir\n\tmultiop $file1 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:c ||\n\t\terror \"create failed $file1\"\n\tmultiop $file2 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:c ||\n\t\terror \"create failed $file2\"\n\n\t$LFS setstripe --component-add -E 1G -c 1 $file1 ||\n\t\terror \"comp-add [0,1G] failed $file1\"\n\t$LFS setstripe --component-add -E 512M -z 128M $file1 &&\n\t\terror \"comp-add [1G,1G],SEL[1G,512M] succeded $file1\"\n\t$LFS setstripe --component-add -E 10G -z 128M $file1 ||\n\t\terror \"comp-add [1G,1G],SEL[1G,10G] failed $file1\"\n\t$LFS setstripe --component-add -E -1 $file1 ||\n\t\terror \"comp-add [10G,-1] failed $file1\"\n\n\t$LFS setstripe --component-add -E 1G -z 32M -c 1 $file2 &&\n\t\terror \"comp-add with smal ext size succeeded $file1\"\n\t$LFS setstripe --component-add -E 1G -z 100M -c 1 $file2 &&\n\t\terror \"comp-add with not aligned ext size succeeded $file1\"\n\t$LFS setstripe --component-add -E 1G -z 128M -c 1 $file2 ||\n\t\terror \"comp-add [0,128M],SEL[128M,1G] failed $file1\"\n\t$LFS setstripe --component-add -E 10G $file2 ||\n\t\terror \"comp-add [1G,10G] failed $file1\"\n\t$LFS setstripe --component-add -E -1 -z 128M -c 1 $file2 ||\n\t\terror \"comp-add [10G,10G],SEL[10G,-1] failed $file1\"\n\t$LFS setstripe --component-add -E -1 -z 128M -c 1 $file2 &&\n\t\terror \"repeated comp-add [10G,10G],SEL[10G,-1] succeeded $file1\"\n\n\t$LFS getstripe $file1\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0 -E 1G $flg_opts $file1 | wc -l)\n\t[ $found -eq 1 ] || error \"First component not found $file1\"\n\n\tflg_opts=\"--comp-flags ^init\"\n\tfound=$($LFS find --comp-start 1G -E 1G $flg_opts $file1 | wc -l)\n\t[ $found -eq 1 ] || error \"Second component not found $file1\"\n\n\tflg_opts=\"--comp-flags ^init,extension\"\n\tfound=$($LFS find --comp-start 1G -E 10G $flg_opts $file1 | wc -l)\n\t[ $found -eq 1 ] || error \"Third component not found $file1\"\n\n\tflg_opts=\"--comp-flags ^init\"\n\tfound=$($LFS find --comp-start 10G -E EOF $flg_opts $file1 | wc -l)\n\t[ $found -eq 1 ] || error \"Fourth component not found $file1\"\n\n\t$LFS getstripe $file2\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0 -E 128M $flg_opts $file2 | wc -l)\n\t[ $found -eq 1 ] || error \"First component not found $file2\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 128M -E 1G $flg_opts $file2 | wc -l)\n\t[ $found -eq 1 ] || error \"Second component not found $file2\"\n\n\tflg_opts=\"--comp-flags ^init\"\n\tfound=$($LFS find --comp-start 1G -E 10G $flg_opts $file2 | wc -l)\n\t[ $found -eq 1 ] || error \"Third component not found $file2\"\n\n\tflg_opts=\"--comp-flags ^init\"\n\tfound=$($LFS find --comp-start 10G -E 10G $flg_opts $file2 | wc -l)\n\t[ $found -eq 1 ] || error \"Fourth component not found $file2\"\n\n\tflg_opts=\"--comp-flags ^init,extension\"\n\tfound=$($LFS find --comp-start 10G -E EOF $flg_opts $file2 | wc -l)\n\t[ $found -eq 1 ] || error \"Fifth component not found $file2\"\n}\nrun_test 19g \"component-add behaviour\"\n\n# Test out of space behavior\ntest_20a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# without this, a previous delete can finish after we check free space\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\t# First component is on OST0\n\t$LFS setstripe -E 256M -i 0 -z 64M -E -1 -z 128M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=66 ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 128M -E 256M $flg_opts $comp_file |wc -l)\n\t[ $found -eq 1 ] || error \"Write: Second component not found\"\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal wms=$(ost_watermarks_set_enospc $tfile $ost_idx1 |\n\t\t    grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx1 $wms\" EXIT\n\n\tflg_opts=\"--comp-flags extension\"\n\t# Write past current init comp, but we won't extend (because no space)\n\tdd if=/dev/zero of=$comp_file bs=1M count=10 seek=200 ||\n\t\terror \"dd write past current comp failed\"\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 128M -E 256M $flg_opts $comp_file | \\\n\t\twc -l)\n\t[ $found -eq 1 ] || error \"Write: third component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 256M -E EOF $flg_opts $comp_file |wc -l)\n\t[ $found -eq 1 ] || error \"Write: fourth extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 20a \"Test out of space, spillover to defined component\"\n\ntest_20b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# Pool allows us to force use of only certain OSTs\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\n\t# normal component to 10M, extendable component to 1G\n\t# further extendable to EOF\n\t$LFS setstripe -E 10M -E 1G -p $TESTNAME -z 64M -E -1 -p \"\" -z 128M \\\n\t\t$comp_file || error \"Create $comp_file failed\"\n\n\treplay_barrier $SINGLEMDS\n\n\tfound=$($LFS find --comp-start 10M -E 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Zero length component not found\"\n\n\tlocal ost_idx1=0\n\tlocal wms=$(ost_watermarks_set_enospc $tfile $ost_idx1 |\n\t\t    grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx1 $wms\" EXIT\n\n\t# write past end of first component\n\t# This should remove the next component, since OST0 is out of space\n\t# and it is striped there (pool contains only OST0)\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=14 ||\n\t\terror \"dd to extend/remove failed\"\n\n\t$LFS getstripe $comp_file\n\n\tfound=$($LFS find --comp-start 10M -E 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"Write: zero length component still present\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 10M -E 138M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 138M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: third component not found\"\n\n\tfail $SINGLEMDS\n\n\tfound=$($LFS find --comp-start 10M -E 10M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"Failover: 0-length component still present\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 10M -E 138M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Failover: second component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 138M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Failover: third component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 20b \"Remove component without instantiation when there is no space\"\n\ntest_20c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# pool is used to limit available OSTs to 0 and 1, so we can set all\n\t# available OSTs out of space\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 1 || error \"Pool add targets failed\"\n\n\t# without this, a previous delete can finish after we check free space\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\t$LFS setstripe -E 100M -E -1 -p $TESTNAME -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal ost_idx1=0\n\tlocal ost_idx2=1\n\tlocal wms=$(ost_watermarks_set_enospc $tfile $ost_idx1 |\n\t\t    grep \"watermarks\")\n\tlocal wms2=$(ost_watermarks_set_enospc $tfile $ost_idx2 |\n\t\t     grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx1 $wms\" EXIT\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx2 $wms2\" EXIT\n\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=120 &&\n\t\terror \"dd should fail with ENOSPC\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 0M -E 100M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: First component not found\"\n\n\tflg_opts=\"--comp-flags ^init\"\n\tfound=$($LFS find --comp-start 100M -E 100M $flg_opts $comp_file |wc -l)\n\t[ $found -eq 1 ] || error \"Write: 0-length component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 100M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: third extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 20c \"Test inability to stripe new extension component\"\n\ntest_20d() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\t$LFS setstripe -E 64m -E -1 -p $TESTNAME -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\treplay_barrier $SINGLEMDS\n\n\tlocal wms=$(ost_watermarks_set_low_space 0 | grep \"watermarks\")\n\tdd if=/dev/zero bs=1M count=1 seek=100 of=$comp_file\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile 0 $wms\n\t[ $RC -eq 0 ] || error \"dd failed: $RC\"\n\n\t$LFS getstripe $comp_file\n\tlocal flg_opts=\"--comp-start 64M -E 128M --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: component (64M-128M) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"-1\" ] && error \"Write: EXT component disappeared\"\n\n\tfail $SINGLEMDS\n\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Failover: component (64M-128M) not found\"\n\n\tost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"-1\" ] && error \"Failover: EXT component disappeared\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 20d \"Low on space + 0-length comp: force extension\"\n\ntest_20e() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\n\t$LFS setstripe -E 64m -E 640M -z 64M -p $TESTNAME -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal wms=$(ost_watermarks_set_low_space 0 | grep \"watermarks\")\n\n\tdd if=/dev/zero bs=1M count=1 seek=100 of=$comp_file\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile 0 $wms\n\t[ $RC -eq 0 ] || error \"dd failed $RC\"\n\n\t$LFS getstripe $comp_file\n\tlocal flg_opts=\"--comp-start 64M -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: component (64M-EOF) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I2 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Write: 0-length component still exists\"\n\tost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Write: extension component still exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 20e \"ENOSPC with next real comp: spillover and backward extension\"\n\n# Simple DoM interaction test\ntest_21a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# simple, correct self-extending layout after DoM component\n\t$LFS setstripe -E 1M -L mdt -E -1 -z 64m $comp_file || \\\n\t\terror \"Create $comp_file failed\"\n\n\t# Write to DoM component & to self-extending comp after it\n\tdd if=/dev/zero bs=1M count=12 of=$comp_file ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 1M -E 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extended component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 65M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 21a \"Simple DoM interaction tests\"\n\n# DoM + extension + removal\ntest_21b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal ost_name=$(ostname_from_index 0)\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# DoM, extendable component, further extendable component\n\t$LFS setstripe -E 1M -L mdt -E 256M -i 0 -z 64M -E -1 -z 128M \\\n\t\t$comp_file || error \"Create $comp_file failed\"\n\n\tfound=$($LFS find --comp-start 1M -E 1M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: Zero length component not found\"\n\n\t# This also demonstrates that we will avoid degraded OSTs\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name.degraded=1\n\t# sleep to guarantee we see the degradation\n\tsleep_maxage\n\n\t# un-degrade on exit\n\tstack_trap \"do_facet ost1 $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=0; sleep_maxage\" EXIT\n\n\t# This should remove the first component after DoM and spill over to\n\t# the next one\n\tdd if=/dev/zero bs=1M count=2 of=$comp_file ||\n\t\terror \"dd to remove+spill over failed\"\n\n\tfound=$($LFS find --comp-start 1M -E 1M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 0 ] || error \"Write: Zero length component still present\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 1M -E 129M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extended component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 129M -E EOF $flg_opts $comp_file |wc -l)\n\t[ $found -eq 1 ] || error \"Write: extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 21b \"DoM followed by extendable component with removal\"\n\n# Test of repeat component behavior with OOS/degraded OST\ntest_22a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E -1 -c 1 -z 128M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal ost_name=$(ostname_from_index $ost_idx1)\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=130 ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 256M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\t# degrade OST for component 1\n\tdo_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=1\n\t# sleep to guarantee we see the degradation\n\tsleep_maxage\n\n\t# un-degrade on exit\n\tstack_trap \"do_facet ost$((ost_idx1+1)) $LCTL set_param -n \\\n\t\tobdfilter.$ost_name.degraded=0; sleep_maxage\" EXIT\n\n\treplay_barrier $SINGLEMDS\n\n\t# seek past the end of current comp & write, should cause a new comp\n\t# to be created (ie repeat previous comp)\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=300 ||\n\t\terror \"dd to repeat failed\"\n\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"$ost_idx1 == $ost_idx2\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 256M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 384M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extension component not found\"\n\n\tfail $SINGLEMDS\n\n\tlocal ost_idx2_2=$($LFS getstripe -I2 -i $comp_file)\n\t[ $ost_idx2_2 -ne $ost_idx2 ] && error \"$ost_idx2_2 != $ost_idx2\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 256M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Failover: second component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 384M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Failover: extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 22a \"Test repeat component behavior with degraded OST\"\n\n# Test repeat behavior with low space\ntest_22b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# without this, a previous delete can finish after we check free space\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\t$LFS setstripe -E -1 -c 1 -z 128M \\\n\t\t$comp_file || error \"Create $comp_file failed\"\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=130 ||\n\t\terror \"dd to extend failed\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 256M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: Second component not found\"\n\n\t# set our OST low on space\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal wms=$(ost_watermarks_set_low_space $ost_idx1 | grep \"watermarks\")\n\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx1 $wms\" EXIT\n\n\t# Write past end of current space, fail to extend, causing repeat\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=300 ||\n\t\terror \"dd to repeat failed\"\n\n\t$LFS getstripe $comp_file\n\n\tlocal ost_idx2=$($LFS getstripe -I2 -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"$ost_idx1 == $ost_idx2\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 256M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: Second component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 384M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: Extension component not found\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 22b \"Test simple 'out of space' condition with repeat\"\n\n# This tests both \"repeat\" and \"extend in place when repeat fails\" aspects\n# of repeating components\ntest_22c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# pool is used to limit available OSTs to 0 and 1, so we can set all\n\t# available OSTs out of space\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 1 || error \"Pool add targets failed\"\n\n\t# without this, a previous delete can finish after we check free space\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\t$LFS setstripe -E -1 -z 64M -c 1 -p \"$TESTNAME\" $comp_file || \\\n\t\terror \"Create $comp_file failed\"\n\n\t# write past end of first component, so it is extended\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=80 conv=notrunc ||\n\t\terror \"dd to extend failed\"\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 128M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\t# set our OST out of space\n\tlocal ost_idx1=$($LFS getstripe -I1 -i $comp_file)\n\tlocal wms=$(ost_watermarks_set_enospc $tfile $ost_idx1 |\n\t\t    grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx1 $wms\" EXIT\n\n\t# This should create a repeat component on a new OST\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=180 conv=notrunc ||\n\t\terror \"dd to repeat failed\"\n\n\t$LFS getstripe $comp_file\n\n\tlocal comp_cnt=$($LFS getstripe --component-count $comp_file)\n\t[ $comp_cnt -ne 3 ] && error \"component count: $comp_cnt, should be 3\"\n\n\t# New second component should be on a different OST\n\tlocal ost_idx2=$($LFS getstripe --comp-start=128m \\\n\t\t\t --comp-end=192m --comp-flags=init -i $comp_file)\n\n\t[ $ost_idx1 -eq $ost_idx2 ] && error \"2nd comp: same OST $ost_idx1\"\n\n\tlocal wms2=$(ost_watermarks_set_enospc $tfile $ost_idx2 |\n\t\t     grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ost_idx2 $wms2\" EXIT\n\n\t# now that the second OST is out of space (as is the first OST), we\n\t# attempt to extend.  This should result in an extension of the\n\t# existing component, rather than a new component.\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=240 conv=notrunc ||\n\t\terror \"dd for forced extension failed\"\n\n\t$LFS getstripe $comp_file\n\n\t# clear out of space on first OST\n\tost_watermarks_clear_enospc $tfile $ost_idx1 $wms\n\n\t# finally, now that the first OST has space again, we attempt to\n\t# extend one last time.  This should create a new component on the\n\t# first OST\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=300 conv=notrunc ||\n\t\terror \"dd for repeat on first OST failed\"\n\n\t$LFS getstripe $comp_file\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 128M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: second component not found\"\n\n\tflg_opts=\"--comp-flags init\"\n\tfound=$($LFS find --comp-start 256M $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: third component not found\"\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 320M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Write: extension component not found\"\n\n\tsel_layout_sanity $comp_file 4\n}\nrun_test 22c \"Test repeat with out of space on > 1 OST\"\n\ntest_22d_post_check() {\n\tlocal comp_file=$1\n\tlocal name=$2\n\tlocal flg_opts=\"--comp-flags init\"\n\tlocal found=$($LFS find --comp-start 0M -E 128M $flg_opts $comp_file |\n\t\t      wc -l)\n\t[ $found -eq 1 ] || {\n\t\t$LFS getstripe $comp_file\n\t\terror \"$name: second component not found\"\n\t}\n\n\tflg_opts=\"--comp-flags extension\"\n\tfound=$($LFS find --comp-start 128M -E EOF $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"$name: third extension component not found\"\n\n\tsel_layout_sanity $comp_file 2\n}\n\ntest_22d_pre() {\n\tlocal comp_file=$1\n\tlocal wms=\"$2\"\n\tlocal RC\n\n\t# write past end of first component\n\tdd if=/dev/zero of=$comp_file bs=1M count=1 seek=70\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile 0 $wms\n\t[ $RC -eq 0 ] || error \"dd to force extend failed\"\n\n\ttest_22d_post_check $comp_file \"Write\"\n}\n\ntest_22d() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\tlocal flg_opts=\"\"\n\tlocal found=\"\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# without this, a previous delete can finish after we check free space\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\t# Pool allows us to force use of only certain OSTs\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\n\t# 1. Fail to extend due to OOS, try to repeat within the same pool,\n\t# fail to stripe (again OOS) the 0-length component, remove the\n\t# repeated one, force the extension on the original one.\n\t$LFS setstripe -E -1 -p $TESTNAME -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\treplay_barrier $SINGLEMDS\n\n\t# set our OST out of space\n\tlocal wms=$(ost_watermarks_set_enospc $tfile 0 | grep \"watermarks\")\n\n\ttest_22d_pre $comp_file \"$wms\"\n\tfail $SINGLEMDS\n\ttest_22d_post_check $comp_file \"Failover\"\n\n\t# 2. repeat with low on space: 0-length repeated component will be\n\t# striped, but still fails to be extended; otherwise the same as (1).\n\trm -f $comp_file\n\t$LFS setstripe -E -1 -p $TESTNAME -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\treplay_barrier $SINGLEMDS\n\n\t# set our OST low on space\n\tlocal wms=$(ost_watermarks_set_low_space 0 | grep \"watermarks\")\n\n\ttest_22d_pre $comp_file \"$wms\"\n\tfail $SINGLEMDS\n\ttest_22d_post_check $comp_file \"Failover\"\n}\nrun_test 22d \"out of/low on space + failed to repeat + forced extension\"\n\ntest_23a() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -z 64M -c 1 -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file ||\n\t\terror \"dd append failed\"\n\n\tlocal flg_opts=\"--comp-start 0 -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: first component (0-EOF) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I2 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: second component still exists\"\n\n\tsel_layout_sanity $comp_file 1\n}\nrun_test 23a \"Append: remove EXT comp\"\n\ntest_23b() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 64m -E -1 -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file ||\n\t\terror \"dd append failed\"\n\n\tlocal flg_opts=\"--comp-start 64M -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: component (64M-EOF) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: third component still exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 23b \"Append with 0-length comp: remove EXT comp\"\n\ntest_23c() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\t$LFS setstripe -E 64m -E -1 -p $TESTNAME -z 64M $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal wms=$(ost_watermarks_set_low_space 0 | grep \"watermarks\")\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile 0 $wms\n\t[ $RC -eq 0 ] || error \"dd append failed: $RC\"\n\n\tlocal flg_opts=\"--comp-start 64M -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: component (64M-EOF) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: EXT component still exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 23c \"Append with low on space + 0-length comp: force extension\"\n\ntest_23d() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 64m -E 640M -z 64M -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file ||\n\t\terror \"dd append failed\"\n\n\tflg_opts=\"--comp-start 64M -E 640M --comp-flags init\"\n\tfound=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: component (64M-640M) not found\"\n\n\tost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: third component still exists\"\n\n\tsel_layout_sanity $comp_file 3\n}\nrun_test 23d \"Append with 0-length comp + next real comp: remove EXT comp\"\n\ntest_23e() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\twait_delete_completed\n\twait_mds_ost_sync\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\n\t$LFS setstripe -E 64m -E 640M -z 64M -p $TESTNAME -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal wms=$(ost_watermarks_set_low_space 0 | grep \"watermarks\")\n\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile 0 $wms\n\t[ $RC -eq 0 ] || error \"dd append failed $RC\"\n\n\tlocal flg_opts=\"--comp-start 64M -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: component (64M-EOF) not found\"\n\n\tlocal ost_idx=$($LFS getstripe -I2 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: 0-length component still exists\"\n\tost_idx=$($LFS getstripe -I3 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: extension component still exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 23e \"Append with next real comp: spillover and backward extension\"\n\ntest_23f() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code $SEL_VER) ] &&\n\t\tskip \"skipped for lustre < $SEL_VER\"\n\n\tlocal comp_file=$DIR/$tdir/$tfile\n\ttest_mkdir -p $DIR/$tdir\n\n\t$LFS setstripe -z 64M -c 1 -E -1 $comp_file ||\n\t\terror \"Create $comp_file failed\"\n\n\tlocal ost_idx=$($LFS getstripe -I1 -i $comp_file)\n\tlocal wms=$(ost_watermarks_set_low_space $ost_idx | grep \"watermarks\")\n\n\tdd if=/dev/zero bs=1M oflag=append count=1 of=$comp_file\n\tRC=$?\n\n\tost_watermarks_clear_enospc $tfile $ost_idx $wms\n\t[ $RC -eq 0 ] || error \"dd append failed\"\n\n\tlocal flg_opts=\"--comp-start 64M -E EOF --comp-flags init\"\n\tlocal found=$($LFS find $flg_opts $comp_file | wc -l)\n\t[ $found -eq 1 ] || error \"Append: component (64M-EOF) not found\"\n\n\tost_idx=$($LFS getstripe -I2 -i $comp_file)\n\t[ \"$ost_idx\" != \"\" ] && error \"Append: extension component still exists\"\n\n\tsel_layout_sanity $comp_file 2\n}\nrun_test 23f \"Append with low on space: repeat and remove EXT comp\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 2212}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_SCRUB_EXCEPT\"\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nbuild_test_filter\n\nrequire_dsh_mds || exit 0\n\nload_modules\n\nif ! check_versions; then\n\tskip \"It is NOT necessary to test scrub under interoperation mode\"\n\texit 0\nfi\n\ncleanupall\n\nSAVED_MDSSIZE=${MDSSIZE}\nSAVED_OSTSIZE=${OSTSIZE}\nSAVED_OSTCOUNT=${OSTCOUNT}\n\n# use small MDS + OST size to speed formatting time\n# do not use too small MDSSIZE/OSTSIZE, which affect the default journal size\n# 400M MDT device can guarantee uninitialized groups during the OI scrub\n[[ $MDSSIZE < 400000 || \"$mds1_FSTYPE\" == ldiskfs ]] && MDSSIZE=400000\n[[ $OSTSIZE < 400000 || \"$ost1_FSTYPE\" == ldiskfs ]] && OSTSIZE=400000\n\n# no need too many OSTs, to reduce the format/start/stop overhead\n[ $OSTCOUNT -gt 4 ] && OSTCOUNT=4\n\n# build up a clean test environment.\nREFORMAT=\"yes\" check_and_setup_lustre\n\nMDT_DEV=\"${FSNAME}-MDT0000\"\nOST_DEV=\"${FSNAME}-OST0000\"\n\nscrub_start() {\n\tlocal error_id=$1\n\tlocal n\n\n\t# use \"lfsck_start -A\" when we no longer need testing interop\n\tfor n in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$n $LCTL lfsck_start -M $(facet_svc mds$n) \\\n\t\t\t-t scrub \"$@\" ||\n\t\t\terror \"($error_id) Failed to start OI scrub on mds$n\"\n\tdone\n}\n\nscrub_stop() {\n\tlocal error_id=$1\n\tlocal n\n\n\t# use \"lfsck_stop -A\" when we no longer need testing interop\n\tfor n in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$n $LCTL lfsck_stop -M $(facet_svc mds$n) ||\n\t\t\terror \"($error_id) Failed to stop OI scrub on mds$n\"\n\tdone\n}\n\nscrub_status() {\n\tlocal n=$1\n\n\tdo_facet mds$n $LCTL get_param -n osd-*.$(facet_svc mds$n).oi_scrub\n}\n\nSTART_SCRUB=\"do_facet $SINGLEMDS $LCTL lfsck_start -M ${MDT_DEV} -t scrub\"\nSTART_SCRUB_ON_OST=\"do_facet ost1 $LCTL lfsck_start -M ${OST_DEV} -t scrub\"\nSTOP_SCRUB=\"do_facet $SINGLEMDS $LCTL lfsck_stop -M ${MDT_DEV}\"\nSHOW_SCRUB=\"do_facet $SINGLEMDS \\\n\t\t$LCTL get_param -n osd-*.${MDT_DEV}.oi_scrub\"\nSHOW_SCRUB_ON_OST=\"do_facet ost1 \\\n\t\t$LCTL get_param -n osd-*.${OST_DEV}.oi_scrub\"\nMOUNT_OPTS_SCRUB=\"-o user_xattr\"\nMOUNT_OPTS_NOSCRUB=\"-o user_xattr,noscrub\"\n\nscrub_prep() {\n\tlocal nfiles=$1\n\tlocal inject=$2\n\tlocal n\n\n\tcheck_mount_and_prep\n\n\techo \"preparing... $(date)\"\n\tfor n in $(seq $MDSCOUNT); do\n\t\techo \"creating $nfiles files on mds$n\"\n\t\ttest_mkdir -i $((n - 1)) -c1 $DIR/$tdir/mds$n ||\n\t\t\terror \"Failed to create directory mds$n\"\n\t\tcp $LUSTRE/tests/*.sh $DIR/$tdir/mds$n ||\n\t\t\terror \"Failed to copy files to mds$n\"\n\t\tmkdir -p $DIR/$tdir/mds$n/d_$tfile ||\n\t\t\terror \"mkdir failed on mds$n\"\n\t\ttouch $DIR/$tdir/mds$n/d_$tfile/f1 > \\\n\t\t\t/dev/null || error \"create failed on mds$n\"\n\t\tdd if=/dev/zero of=$DIR/$tdir/mds$n/d_$tfile/f2 bs=1M count=1 ||\n\t\t       \terror \"write failed on mds$n\"\n\t\tif [[ $nfiles -gt 0 ]]; then\n\t\t\tcreatemany -m $DIR/$tdir/mds$n/$tfile $nfiles > \\\n\t\t\t\t/dev/null || error \"createmany failed on mds$n\"\n\t\tfi\n\tdone\n\techo \"prepared $(date).\"\n\n\t[ ! -z $inject ] && [ $inject -eq 2 ] && {\n\t\t#define OBD_FAIL_OSD_NO_OI_ENTRY\t0x198\n\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\t$LCTL set_param fail_loc=0x198\n\n\t\tfor n in $(seq $MDSCOUNT); do\n\t\t\tcp $LUSTRE/tests/runas $DIR/$tdir/mds$n ||\n\t\t\t\terror \"Fail to copy runas to MDS$n\"\n\t\tdone\n\n\t\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0\n\t}\n\n\t[ ! -z $inject ] && [ $inject -eq 1 ] &&\n\t\t[ $(facet_fstype $SINGLEMDS) = \"zfs\" ] && {\n\t\t#define OBD_FAIL_OSD_FID_MAPPING\t0x193\n\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t$LCTL set_param fail_loc=0x193\n\n\t\tfor n in $(seq $MDSCOUNT); do\n\t\t\tchmod 0400 $DIR/$tdir/mds$n/test-framework.sh\n\t\t\tchmod 0400 $DIR/$tdir/mds$n/sanity-scrub.sh\n\t\tdone\n\n\t\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0\n\t}\n\n\tcleanup_mount $MOUNT > /dev/null || error \"Fail to stop client!\"\n\n\t# sync local transactions on every MDT\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n osd*.*MDT*.force_sync=1\"\n\n\t# wait for a while to cancel update logs after transactions committed.\n\tsleep 3\n\n\t# sync again to guarantee all things done.\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n osd*.*MDT*.force_sync=1\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\techo \"stop mds$n\"\n\t\tstop mds$n > /dev/null || error \"Fail to stop MDS$n!\"\n\tdone\n\n\t[ ! -z $inject ] && [ $(facet_fstype $SINGLEMDS) = \"ldiskfs\" ] && {\n\t\tif [ $inject -eq 1 ]; then\n\t\t\tfor n in $(seq $MDSCOUNT); do\n\t\t\t\tmds_backup_restore mds$n ||\n\t\t\t\t\terror \"Backup/restore on mds$n failed\"\n\t\t\tdone\n\t\telif [ $inject -eq 2 ]; then\n\t\t\tscrub_remove_ois 1\n\t\tfi\n\t}\n}\n\nscrub_start_mds() {\n\tlocal error_id=$1\n\tlocal opts=$2\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tstart mds$n $(mdsdevname $n) $opts >/dev/null ||\n\t\t\terror \"($error_id) Failed to start mds$n\"\n\tdone\n}\n\nscrub_stop_mds() {\n\tlocal error_id=$1\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\techo \"stopping mds$n\"\n\t\tstop mds$n >/dev/null ||\n\t\t\terror \"($error_id) Failed to stop mds$n\"\n\tdone\n}\n\nscrub_check_status() {\n\tlocal error_id=$1\n\tlocal expected=$2\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\twait_update_facet mds$n \"$LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"$expected\" 6 ||\n\t\t\terror \"($error_id) Expected '$expected' on mds$n\"\n\tdone\n}\n\nscrub_check_flags() {\n\tlocal error_id=$1\n\tlocal expected=$2\n\tlocal actual\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tactual=$(do_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub |\n\t\t\tawk '/^flags/ { print $2 }')\n\t\tif [ \"$actual\" != \"$expected\" ]; then\n\t\t\terror \"($error_id) Expected '$expected' on mds$n, but\" \\\n\t\t\t       \"got '$actual'\"\n\t\tfi\n\tdone\n}\n\nscrub_check_params() {\n\tlocal error_id=$1\n\tlocal expected=$2\n\tlocal actual\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tactual=$(do_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub |\n\t\t\tawk '/^param/ { print $2 }')\n\t\tif [ \"$actual\" != \"$expected\" ]; then\n\t\t\terror \"($error_id) Expected '$expected' on mds$n, but\" \\\n\t\t\t       \"got '$actual'\"\n\t\tfi\n\tdone\n}\n\nscrub_check_repaired() {\n\tlocal error_id=$1\n\tlocal expected=$2\n\tlocal dryrun=$3\n\tlocal actual\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tif [ $dryrun -eq 1 ]; then\n\t\t\tactual=$(do_facet mds$n $LCTL get_param -n \\\n\t\t\t\tosd-*.$(facet_svc mds$n).oi_scrub |\n\t\t\t\tawk '/^inconsistent:/ { print $2 }')\n\t\telse\n\t\t\tactual=$(do_facet mds$n $LCTL get_param -n \\\n\t\t\t\tosd-*.$(facet_svc mds$n).oi_scrub |\n\t\t\t\tawk '/^updated:/ { print $2 }')\n\t\tfi\n\n\t\tif [ $expected -eq 0 -a $actual -ne 0 ]; then\n\t\t\terror \"($error_id) Expected no repaired on mds$n, but\" \\\n\t\t\t       \"got '$actual'\"\n\t\tfi\n\n\t\tif [ $expected -ne 0 -a $actual -lt $expected ]; then\n\t\t\terror \"($error_id) Expected '$expected' on mds$n, but\" \\\n\t\t\t       \"got '$actual'\"\n\t\tfi\n\tdone\n}\n\nscrub_check_data() {\n\tlocal error_id=$1\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tdiff -q $LUSTRE/tests/test-framework.sh \\\n\t\t\t$DIR/$tdir/mds$n/test-framework.sh ||\n\t\t\terror \"($error_id) File data check failed\"\n\tdone\n}\n\nscrub_check_data2() {\n\tlocal filename=$1\n\tlocal error_id=$2\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tdiff -q $LUSTRE/tests/$filename \\\n\t\t\t$DIR/$tdir/mds$n/$filename ||\n\t\t\terror \"($error_id) File data check failed\"\n\tdone\n}\n\nscrub_remove_ois() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] && return\n\n\tlocal error_id=$1\n\tlocal index=$2\n\tlocal n\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tmds_remove_ois mds$n $index ||\n\t\t\terror \"($error_id) Failed to remove OI .$index on mds$n\"\n\tdone\n}\n\nscrub_enable_auto() {\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \\\n\t\tosd-*.*.auto_scrub=1\n}\n\nfull_scrub_ratio() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] && return\n\n\tlocal ratio=$1\n\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \\\n\t\tosd-*.*.full_scrub_ratio=$ratio\n}\n\nfull_scrub_threshold_rate() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] && return\n\n\tlocal rate=$1\n\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \\\n\t\tosd-*.*.full_scrub_threshold_rate=$rate\n}\n\nscrub_enable_index_backup() {\n\tdo_nodes $(comma_list $(all_server_nodes)) $LCTL set_param -n \\\n\t\tosd-*.*.index_backup=1\n}\n\nscrub_disable_index_backup() {\n\tdo_nodes $(comma_list $(all_server_nodes)) $LCTL set_param -n \\\n\t\tosd-*.*.index_backup=0\n}\n\ntest_0() {\n\tscrub_prep 0\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 1 \"$MOUNT_OPTS_SCRUB\"\n\tscrub_check_status 2 init\n\tscrub_check_flags 3 \"\"\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\tscrub_check_data 5\n}\nrun_test 0 \"Do not auto trigger OI scrub for non-backup/restore case\"\n\ntest_1a() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\tscrub_prep 0\n\techo \"start $SINGLEMDS without disabling OI scrub\"\n\tscrub_start_mds 1 \"$MOUNT_OPTS_SCRUB\"\n\n\tlocal FLAGS=$($SHOW_SCRUB | awk '/^flags/ { print $2 }')\n\t[ -z \"$FLAGS\" ] || error \"(3) Expect empty flags, but got '$FLAGS'\"\n\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\t#define OBD_FAIL_OSD_FID_MAPPING\t\t\t0x193\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x193\n\t# update .lustre OI mapping\n\ttouch $MOUNT/.lustre\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tumount_client $MOUNT || error \"(5) Fail to stop client!\"\n\n\techo \"stop $SINGLEMDS\"\n\tstop $SINGLEMDS > /dev/null || error \"(6) Fail to stop MDS!\"\n\n\techo \"start $SINGLEMDS with disabling OI scrub\"\n\tstart $SINGLEMDS $(mdsdevname 1) $MOUNT_OPTS_NOSCRUB > /dev/null ||\n\t\terror \"(7) Fail to start MDS!\"\n\n\tlocal FLAGS=$($SHOW_SCRUB | awk '/^flags/ { print $2 }')\n\t[ \"$FLAGS\" == \"inconsistent\" ] ||\n\t\terror \"(9) Expect 'inconsistent', but got '$FLAGS'\"\n}\nrun_test 1a \"Auto trigger initial OI scrub when server mounts\"\n\ntest_1b() {\n\tscrub_prep 0 2\n\techo \"start MDTs without disabling OI scrub\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_SCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_status 3 completed\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\tscrub_check_data2 runas 5\n\tscrub_check_status 6 completed\n}\nrun_test 1b \"Trigger OI scrub when MDT mounts for OI files remove/recreate case\"\n\ntest_1c() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\" && return\n\n\tlocal index\n\n\t# OI files to be removed:\n\t# idx 0: oi.16.0\n\t# idx 2: oi.16.{2,4,8,16,32}\n\t# idx 3: oi.16.{3,9,27}\n\tfor index in 0 2 3; do\n\t\tscrub_prep 0\n\t\tscrub_remove_ois 1 $index\n\t\techo \"start MDTs with OI scrub disabled\"\n\t\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t\tscrub_check_flags 3 recreated\n\t\tscrub_start 4\n\t\tscrub_check_status 5 completed\n\t\tscrub_check_flags 6 \"\"\n\tdone\n}\nrun_test 1c \"Auto detect kinds of OI file(s) removed/recreated cases\"\n\ntest_2() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\" && return\n\n\tscrub_prep 0 1\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_SCRUB\"\n\tscrub_check_status 3 completed\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\tscrub_check_data 5\n}\nrun_test 2 \"Trigger OI scrub when MDT mounts for backup/restore case\"\n\n# test_3 is obsolete, it will be covered by test_5.\ntest_3() {\n\tformatall > /dev/null\n\tsetupall > /dev/null\n\n\tscrub_prep 0 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 3 init\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n}\n#run_test 3 \"Do not trigger OI scrub when MDT mounts if 'noscrub' specified\"\n\ntest_4a() {\n\tscrub_prep 0 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 0\n\tscrub_check_data 6\n\tsleep 3\n\n\tscrub_check_status 7 completed\n\tscrub_check_flags 8 \"\"\n\n\tlocal -a updated0\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated0[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\tdone\n\n\tscrub_check_data2 sanity-scrub.sh 9\n\tsleep 3\n\n\tlocal -a updated1\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated1[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\t\t[ ${updated0[$n]} -eq ${updated1[$n]} ] ||\n\t\t\terror \"(10) NOT auto trigger full scrub as expected\"\n\tdone\n}\nrun_test 4a \"Auto trigger OI scrub if bad OI mapping was found (1)\"\n\ntest_4b() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\" && return\n\n\tscrub_prep 5 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 10\n\tfull_scrub_threshold_rate 10000\n\tscrub_check_data 6\n\tsleep 3\n\n\tscrub_check_status 7 completed\n\tscrub_check_flags 8 \"\"\n\n\tlocal -a updated0\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated0[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 1st time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\tdone\n\n\tscrub_check_data2 sanity-scrub.sh 9\n\tsleep 3\n\n\tscrub_check_status 10 completed\n\tscrub_check_flags 11 \"\"\n\n\tlocal -a updated1\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated1[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 2nd time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t[ ${updated0[$n]} -lt ${updated1[$n]} ] ||\n\t\t\terror \"(12) Auto trigger full scrub unexpectedly\"\n\tdone\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tls -l $DIR/$tdir/mds$n/*.sh > /dev/null ||\n\t\t\terror \"(13) fail to ls\"\n\tdone\n\tsleep 3\n\n\tscrub_check_status 14 completed\n\tscrub_check_flags 15 \"\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated0[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 3rd time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t[ ${updated0[$n]} -gt ${updated1[$n]} ] ||\n\t\t\terror \"(16) Auto trigger full scrub unexpectedly\"\n\tdone\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tls -l $DIR/$tdir/mds$n/d_${tfile}/ || error \"(17) fail to ls\"\n\tdone\n\tsleep 3\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated1[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\t\t[ ${updated0[$n]} -eq ${updated1[$n]} ] || {\n\t\t\techo \"OI scrub on MDS$n status for the 4th time:\"\n\t\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t\terror \"(18) NOT auto trigger full scrub as expected\"\n\t\t}\n\tdone\n}\nrun_test 4b \"Auto trigger OI scrub if bad OI mapping was found (2)\"\n\ntest_4c() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\" && return\n\n\tscrub_prep 500 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 2\n\tfull_scrub_threshold_rate 20\n\tscrub_check_data 6\n\tsleep 3\n\n\tscrub_check_status 7 completed\n\tscrub_check_flags 8 \"\"\n\n\tlocal -a updated0\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated0[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 1st time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\tdone\n\n\tscrub_check_data2 sanity-scrub.sh 9\n\tsleep 3\n\n\tscrub_check_status 10 completed\n\tscrub_check_flags 11 \"\"\n\n\tlocal -a updated1\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated1[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 2nd time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t[ ${updated0[$n]} -lt ${updated1[$n]} ] ||\n\t\t\terror \"(12) Auto trigger full scrub unexpectedly\"\n\tdone\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tls -l $DIR/$tdir/mds$n/*.sh > /dev/null ||\n\t\t\terror \"(13) fail to ls\"\n\tdone\n\tsleep 3\n\n\tscrub_check_status 14 completed\n\tscrub_check_flags 15 \"\"\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated0[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\n\t\techo \"OI scrub on MDS$n status for the 3rd time:\"\n\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t[ ${updated0[$n]} -gt ${updated1[$n]} ] ||\n\t\t\terror \"(16) Auto trigger full scrub unexpectedly\"\n\tdone\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tls -l $DIR/$tdir/mds$n/${tfile}1 || error \"(17) fail to ls\"\n\tdone\n\tsleep 3\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tupdated1[$n]=$(scrub_status $n |\n\t\t\t       awk '/^prior_updated/ { print $2 }')\n\t\t[ ${updated0[$n]} -eq ${updated1[$n]} ] || {\n\t\t\techo \"OI scrub on MDS$n status for the 4th time:\"\n\t\t\tdo_facet mds$n $LCTL get_param -n \\\n\t\t\t\tosd-*.$(facet_svc mds$n).oi_scrub\n\n\t\t\terror \"(18) NOT auto trigger full scrub as expected\"\n\t\t}\n\tdone\n}\nrun_test 4c \"Auto trigger OI scrub if bad OI mapping was found (3)\"\n\ntest_4d() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] && skip \"ldiskfs only test\"\n\n\tcheck_mount_and_prep\n\n\t#define OBD_FAIL_OSD_DUPLICATE_MAP\t0x19b\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0x19b\n\tfor i in {1..100}; do\n\t\techo $i > $DIR/$tdir/f_$i || error \"write f_$i failed\"\n\tdone\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\n\tfor i in {101..200}; do\n\t\techo $i > $DIR/$tdir/f_$i || error \"write f_$i failed\"\n\tdone\n\n\tfor i in {1..200}; do\n\t\techo $i | cmp $DIR/$tdir/f_$i - || error \"f_$i data corrupt\"\n\tdone\n}\nrun_test 4d \"FID in LMA mismatch with object FID won't block create\"\n\ntest_5() {\n\tformatall > /dev/null\n\tsetupall > /dev/null\n\n\tscrub_prep 100 1\n\techo \"starting MDTs with OI scrub disabled (1)\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 3 init\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 0\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\tscrub_check_data 6\n\tumount_client $MOUNT || error \"(7) Fail to stop client!\"\n\tscrub_check_status 8 scanning\n\n\t#define OBD_FAIL_OSD_SCRUB_CRASH\t 0x191\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x191\n\n\tsleep 4\n\tscrub_stop_mds 9\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\techo \"starting MDTs with OI scrub disabled (2)\"\n\tscrub_start_mds 10 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 11 crashed\n\tscrub_stop_mds 12\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 13 \"$MOUNT_OPTS_SCRUB\"\n\tscrub_check_status 14 scanning\n\n\t#define OBD_FAIL_OSD_SCRUB_FATAL\t 0x192\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x192\n\n\tscrub_check_status 15 failed\n\tmount_client $MOUNT || error \"(16) Fail to start client!\"\n\n\tfull_scrub_ratio 0\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tlocal n\n\tdeclare -a pids\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tstat $DIR/$tdir/mds$n/sanity-scrub.sh &\n\t\tpids[$n]=$!\n\tdone\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\twait ${pids[$n]} ||\n\t\t\terror \"(18) Fail to stat mds$n/sanity-scrub.sh\"\n\tdone\n\n\tscrub_check_status 19 completed\n\tscrub_check_flags 20 \"\"\n}\nrun_test 5 \"OI scrub state machine\"\n\ntest_6() {\n\tscrub_prep 100 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 0\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=2 fail_loc=0x190\n\n\tscrub_check_data 6\n\n\t# Sleep 5 sec to guarantee at least one object processed by OI scrub\n\tsleep 5\n\t# Fail the OI scrub to guarantee there is at least one checkpoint\n\t#define OBD_FAIL_OSD_SCRUB_FATAL\t 0x192\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x192\n\n\tscrub_check_status 7 failed\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\tlocal n\n\tfor n in $(seq $MDSCOUNT); do\n\t\t# stat will re-trigger OI scrub\n\t\tstat $DIR/$tdir/mds$n/sanity-scrub.sh ||\n\t\t\terror \"(8) Failed to stat mds$n/sanity-scrub.sh\"\n\tdone\n\n\tumount_client $MOUNT || error \"(9) Fail to stop client!\"\n\tscrub_check_status 10 scanning\n\n\t#define OBD_FAIL_OSD_SCRUB_CRASH\t 0x191\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x191\n\n\tsleep 4\n\tlocal -a position0\n\tfor n in $(seq $MDSCOUNT); do\n\t\tposition0[$n]=$(scrub_status $n |\n\t\t\tawk '/^last_checkpoint_position/ {print $2}')\n\t\tposition0[$n]=$((${position0[$n]} + 1))\n\tdone\n\n\tscrub_stop_mds 11\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 12 \"$MOUNT_OPTS_SCRUB\"\n\n\tscrub_check_status 13 scanning\n\n\tlocal -a position1\n\tfor n in $(seq $MDSCOUNT); do\n\t\tposition1[$n]=$(scrub_status $n |\n\t\t\tawk '/^latest_start_position/ {print $2}')\n\t\tif [ ${position0[$n]} -ne ${position1[$n]} ]; then\n\t\t\terror \"(14) Expected position ${position0[$n]}, but\" \\\n\t\t\t\t\"got ${position1[$n]}\"\n\t\tfi\n\tdone\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tscrub_check_status 15 completed\n\tscrub_check_flags 16 \"\"\n}\nrun_test 6 \"OI scrub resumes from last checkpoint\"\n\ntest_7() {\n\tscrub_prep 500 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 0\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\tscrub_check_data 6\n\n\tlocal n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tstat $DIR/$tdir/mds$n/${tfile}300 ||\n\t\t\terror \"(7) Failed to stat mds$n/${tfile}300!\"\n\tdone\n\n\tscrub_check_status 8 scanning\n\tif [ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ]; then\n\t\tscrub_check_flags 9 inconsistent,auto\n\telse\n\t\tscrub_check_flags 9 recreated,inconsistent,auto\n\tfi\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tscrub_check_status 10 completed\n\tscrub_check_flags \"\"\n}\nrun_test 7 \"System is available during OI scrub scanning\"\n\ntest_8() {\n\tscrub_prep 128 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=1 fail_loc=0x190\n\n\tscrub_start 5\n\tscrub_check_status 6 scanning\n\tscrub_stop 7\n\tscrub_check_status 8 stopped\n\tscrub_start 9\n\tscrub_check_status 10 scanning\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tscrub_check_status 11 completed\n\tscrub_check_flags 12 \"\"\n}\nrun_test 8 \"Control OI scrub manually\"\n\ntest_9() {\n\t# Skip scrub speed test for ZFS because of performance unstable\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"test scrub speed only on ldiskfs\" && return\n\n\tif [ -z \"$(grep \"processor.*: 1\" /proc/cpuinfo)\" ]; then\n\t\tskip \"Testing on UP system, the speed may be inaccurate.\"\n\t\treturn 0\n\tfi\n\n\tscrub_prep 6000 1\n\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_flags 4 recreated,inconsistent\n\n\tlocal BASE_SPEED1=100\n\tlocal RUN_TIME1=10\n\t# OI scrub should run with full speed under inconsistent case\n\tscrub_start 5 -s $BASE_SPEED1\n\n\tsleep $RUN_TIME1\n\tscrub_check_status 6 completed\n\tscrub_check_flags 7 \"\"\n\t# OI scrub should run with limited speed under non-inconsistent case\n\tscrub_start 8 -s $BASE_SPEED1 -r\n\n\tsleep $RUN_TIME1\n\tscrub_check_status 9 scanning\n\n\t# Do NOT ignore that there are 1024 pre-fetched items. And there\n\t# may be time error, normally it should be less than 2 seconds.\n\t# We allow another 20% schedule error.\n\tlocal PRE_FETCHED=1024\n\tlocal TIME_DIFF=2\n\t# MAX_MARGIN = 1.2 = 12 / 10\n\tlocal MAX_SPEED=$(((PRE_FETCHED + BASE_SPEED1 * \\\n\t\t(RUN_TIME1 + TIME_DIFF)) / RUN_TIME1 * 12 / 10))\n\tlocal n\n\tfor n in $(seq $MDSCOUNT); do\n\t\tlocal SPEED=$(scrub_status $n | \\\n\t\t\tawk '/^average_speed/ { print $2 }')\n\t\t[ $SPEED -lt $MAX_SPEED ] ||\n\t\t\terror \"(10) Got speed $SPEED, expected less than\" \\\n\t\t\t\t\"$MAX_SPEED\"\n\tdone\n\n\t# adjust speed limit\n\tlocal BASE_SPEED2=300\n\tlocal RUN_TIME2=10\n\tfor n in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$n $LCTL set_param -n \\\n\t\t\tmdd.$(facet_svc mds$n).lfsck_speed_limit $BASE_SPEED2\n\tdone\n\tsleep $RUN_TIME2\n\n\t# MIN_MARGIN = 0.8 = 8 / 10\n\tlocal MIN_SPEED=$(((PRE_FETCHED + \\\n\t\t\t    BASE_SPEED1 * (RUN_TIME1 - TIME_DIFF) + \\\n\t\t\t    BASE_SPEED2 * (RUN_TIME2 - TIME_DIFF)) / \\\n\t\t\t   (RUN_TIME1 + RUN_TIME2) * 8 / 10))\n\t# MAX_MARGIN = 1.2 = 12 / 10\n\tMAX_SPEED=$(((PRE_FETCHED + \\\n\t\t      BASE_SPEED1 * (RUN_TIME1 + TIME_DIFF) + \\\n\t\t      BASE_SPEED2 * (RUN_TIME2 + TIME_DIFF)) / \\\n\t\t     (RUN_TIME1 + RUN_TIME2) * 12 / 10))\n\tfor n in $(seq $MDSCOUNT); do\n\t\tSPEED=$(scrub_status $n | awk '/^average_speed/ { print $2 }')\n\t\t[ $SPEED -gt $MIN_SPEED ] ||\n\t\t\terror \"(11) Got speed $SPEED, expected more than\" \\\n\t\t\t\t\"$MIN_SPEED\"\n\t\t[ $SPEED -lt $MAX_SPEED ] ||\n\t\t\terror \"(12) Got speed $SPEED, expected less than\" \\\n\t\t\t\t\"$MAX_SPEED\"\n\n\t\tdo_facet mds$n $LCTL set_param -n \\\n\t\t\t\tmdd.$(facet_svc mds$n).lfsck_speed_limit 0\n\tdone\n\n\tscrub_check_status 13 completed\n}\nrun_test 9 \"OI scrub speed control\"\n\ntest_10a() {\n\tscrub_prep 0 1\n\techo \"starting mds$n with OI scrub disabled (1)\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\tscrub_enable_auto\n\tfull_scrub_ratio 0\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=1 fail_loc=0x190\n\n\tscrub_check_data 6\n\tscrub_check_status 7 scanning\n\tumount_client $MOUNT || error \"(8) Fail to stop client!\"\n\tscrub_stop_mds 9\n\techo \"starting MDTs with OI scrub disabled (2)\"\n\tscrub_start_mds 10 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 11 paused\n\tscrub_stop_mds 12\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 13 \"$MOUNT_OPTS_SCRUB\"\n\tscrub_check_status 14 scanning\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tscrub_check_status 15 completed\n\tscrub_check_flags 16 \"\"\n}\nrun_test 10a \"non-stopped OI scrub should auto restarts after MDS remount (1)\"\n\n# test_10b is obsolete, it will be coverded by related sanity-lfsck tests.\ntest_10b() {\n\tscrub_prep 0 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\n\t#define OBD_FAIL_OSD_SCRUB_DELAY\t 0x190\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_val=3 fail_loc=0x190\n\n\tscrub_start 5\n\tscrub_check_status 6 scanning\n\tscrub_stop_mds 7\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 8 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 9 paused\n\tscrub_stop_mds 10\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 11 \"$MOUNT_OPTS_SCRUB\"\n\tscrub_check_status 12 scanning\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param fail_loc=0 fail_val=0\n\n\tscrub_check_status 13 completed\n\tscrub_check_flags 14 \"\"\n}\n#run_test 10b \"non-stopped OI scrub should auto restarts after MDS remount (2)\"\n\ntest_11() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\" && return\n\n\tlocal CREATED=100\n\tlocal n\n\n\tcheck_mount_and_prep\n\n\tfor n in $(seq $MDSCOUNT); do\n\t\ttest_mkdir -i $((n - 1)) -c1 $DIR/$tdir/mds$n ||\n\t\t\terror \"(1) Fail to mkdir $DIR/$tdir/mds$n\"\n\n\t\tcreatemany -o $DIR/$tdir/mds$n/f $CREATED ||\n\t\t\terror \"(2) Fail to create under $tdir/mds$n\"\n\tdone\n\n\t# reset OI scrub start point by force\n\tscrub_start 3 -r\n\tscrub_check_status 4 completed\n\n\tdeclare -a checked0\n\tdeclare -a checked1\n\n\t# OI scrub should skip the new created objects for the first accessing\n\t# notice we're creating a new llog for every OST on every startup\n\t# new features can make this even less stable, so we only check that\n\t# the number of skipped files is more than the number or known created\n\tlocal MINIMUM=$((CREATED + 1)) # files + directory\n\tfor n in $(seq $MDSCOUNT); do\n\t\tlocal SKIPPED=$(scrub_status $n | awk '/^noscrub/ { print $2 }')\n\t\t[ $SKIPPED -lt $MINIMUM ] &&\n\t\t\terror \"(5) Expect at least $MINIMUM objects\" \\\n\t\t\t\t\"skipped on mds$n, but got $SKIPPED\"\n\n\t\tchecked0[$n]=$(scrub_status $n | awk '/^checked/ { print $2 }')\n\tdone\n\n\t# reset OI scrub start point by force\n\tscrub_start 6 -r\n\tscrub_check_status 7 completed\n\n\t# OI scrub should skip the new created object only once\n\tfor n in $(seq $MDSCOUNT); do\n\t\tSKIPPED=$(scrub_status $n | awk '/^noscrub/ { print $2 }')\n\t\tchecked1[$n]=$(scrub_status $n | awk '/^checked/ { print $2 }')\n\n\t\t[ ${checked0[$n]} -ne ${checked1[$n]} -o $SKIPPED -eq 0 ] ||\n\t\t\terror \"(8) Expect 0 objects skipped on mds$n, but\" \\\n\t\t\t\t\"got $SKIPPED\"\n\tdone\n}\nrun_test 11 \"OI scrub skips the new created objects only once\"\n\ntest_12() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\t#define OBD_FAIL_OSD_COMPAT_INVALID_ENTRY\t\t0x195\n\tdo_facet ost1 $LCTL set_param fail_loc=0x195\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 32))\n\tumount_client $MOUNT || error \"(1) Fail to stop client!\"\n\n\tstop ost1 || error \"(2) Fail to stop ost1\"\n\n\t#define OBD_FAIL_OST_NODESTROY\t\t 0x233\n\tdo_facet ost1 $LCTL set_param fail_loc=0x233\n\n\tstart ost1 $(ostdevname 1) $MOUNT_OPTS_NOSCRUB ||\n\t\terror \"(3) Fail to start ost1\"\n\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\n\tls -ail $DIR/$tdir > /dev/null 2>&1 && error \"(5) ls should fail\"\n\n\t$START_SCRUB_ON_OST -r || error \"(6) Fail to start OI scrub on OST!\"\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\twait_update_facet ost1 \"$LCTL get_param -n \\\n\t\tosd-*.$(facet_svc ost1).oi_scrub |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 6 ||\n\t\terror \"(7) Expected '$expected' on ost1\"\n\n\tls -ail $DIR/$tdir > /dev/null || {\n\t\t$SHOW_SCRUB_ON_OST\n\t\terror \"(8) ls should succeed\"\n\t}\n}\nrun_test 12 \"OI scrub can rebuild invalid /O entries\"\n\ntest_13() {\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\t#define OBD_FAIL_OSD_COMPAT_NO_ENTRY\t\t0x196\n\tdo_facet ost1 $LCTL set_param fail_loc=0x196\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 32))\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tumount_client $MOUNT || error \"(1) Fail to stop client!\"\n\n\tstop ost1 || error \"(2) Fail to stop ost1\"\n\n\tstart ost1 $(ostdevname 1) $MOUNT_OPTS_NOSCRUB ||\n\t\terror \"(3) Fail to start ost1\"\n\n\tmount_client $MOUNT || error \"(4) Fail to start client!\"\n\n\tls -ail $DIR/$tdir > /dev/null 2>&1 && error \"(5) ls should fail\"\n\n\t$START_SCRUB_ON_OST -r || error \"(6) Fail to start OI scrub on OST!\"\n\n\twait_update_facet ost1 \"$LCTL get_param -n \\\n\t\tosd-*.$(facet_svc ost1).oi_scrub |\n\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 6 ||\n\t\terror \"(7) Expected '$expected' on ost1\"\n\n\tls -ail $DIR/$tdir > /dev/null || error \"(8) ls should succeed\"\n}\nrun_test 13 \"OI scrub can rebuild missed /O entries\"\n\ntest_14() {\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] &&\n\t\tskip \"ldiskfs special test\"\n\n\tcheck_mount_and_prep\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\t#define OBD_FAIL_OSD_COMPAT_NO_ENTRY\t\t0x196\n\tdo_facet ost1 $LCTL set_param fail_loc=0x196\n\tlocal count=$(precreated_ost_obj_count 0 0)\n\n\tcreatemany -o $DIR/$tdir/f $((count + 1000))\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tumount_client $MOUNT || error \"(1) Fail to stop client!\"\n\n\tstop ost1 || error \"(2) Fail to stop ost1\"\n\n\techo \"run e2fsck\"\n\trun_e2fsck $(facet_host ost1) $(ostdevname 1) \"-y\" ||\n\t\terror \"(3) Fail to run e2fsck error\"\n\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS ||\n\t\terror \"(4) Fail to start ost1\"\n\n\tmount_client $MOUNT || error \"(5) Fail to start client!\"\n\n\tlocal LF_REPAIRED=$($SHOW_SCRUB_ON_OST |\n\t\t\t    awk '/^lf_repa[ir]*ed/ { print $2 }')\n\t[ $LF_REPAIRED -ge 1000 ] ||\n\t\terror \"(6) Some entry under /lost+found should be repaired\"\n\n\tls -ail $DIR/$tdir > /dev/null || error \"(7) ls should succeed\"\n\n\tstopall\n\n\techo \"run e2fsck again after LFSCK\"\n\trun_e2fsck $(facet_host ost1) $(ostdevname 1) \"-y\" ||\n\t\terror \"(8) Fail to run e2fsck error\"\n}\nrun_test 14 \"OI scrub can repair OST objects under lost+found\"\n\ntest_15() {\n\tlocal repaired\n\n\tformatall > /dev/null\n\tsetupall > /dev/null\n\n\tscrub_prep 20 1\n\techo \"starting MDTs with OI scrub disabled\"\n\tscrub_start_mds 2 \"$MOUNT_OPTS_NOSCRUB\"\n\tscrub_check_status 3 init\n\t[ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ] ||\n\t\tscrub_check_flags 4 recreated,inconsistent\n\n\t# run under dryrun mode\n\tscrub_start 5 --dryrun\n\tscrub_check_status 6 completed\n\tif [ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ]; then\n\t\tscrub_check_flags 7 inconsistent\n\t\trepaired=2\n\telse\n\t\tscrub_check_flags 7 recreated,inconsistent\n\t\trepaired=20\n\tfi\n\tscrub_check_params 8 dryrun\n\tscrub_check_repaired 9 $repaired 1\n\n\t# run under dryrun mode again\n\tscrub_start 10 --dryrun\n\tscrub_check_status 11 completed\n\tif [ $(facet_fstype $SINGLEMDS) != \"ldiskfs\" ]; then\n\t\tscrub_check_flags 12 inconsistent\n\telse\n\t\tscrub_check_flags 12 recreated,inconsistent\n\tfi\n\tscrub_check_params 13 dryrun\n\tscrub_check_repaired 14 $repaired 1\n\n\t# run under normal mode\n\tscrub_start 15\n\tscrub_check_status 16 completed\n\tscrub_check_flags 17 \"\"\n\tscrub_check_params 18 \"\"\n\tscrub_check_repaired 19 $repaired 0\n\n\t# run under normal mode again\n\tscrub_start 20\n\tscrub_check_status 21 completed\n\tscrub_check_flags 22 \"\"\n\tscrub_check_params 23 \"\"\n\tscrub_check_repaired 24 0 0\n}\nrun_test 15 \"Dryrun mode OI scrub\"\n\ntest_16() {\n\tcheck_mount_and_prep\n\tscrub_enable_index_backup\n\n\t#define OBD_FAIL_OSD_INDEX_CRASH\t0x199\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0x199\n\tscrub_prep 0\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param fail_loc=0\n\n\techo \"starting MDTs without disabling OI scrub\"\n\tscrub_start_mds 1 \"$MOUNT_OPTS_SCRUB\"\n\tmount_client $MOUNT || error \"(2) Fail to start client!\"\n\tscrub_check_data 3\n\tscrub_disable_index_backup\n}\nrun_test 16 \"Initial OI scrub can rebuild crashed index objects\"\n\n# restore MDS/OST size\nMDSSIZE=${SAVED_MDSSIZE}\nOSTSIZE=${SAVED_OSTSIZE}\nOSTCOUNT=${SAVED_OSTCOUNT}\n\n# cleanup the system at last\nREFORMAT=\"yes\" cleanup_and_setup_lustre\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 1287}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_SEC_EXCEPT \"\n# bug number for skipped test:\nALWAYS_EXCEPT+=\" \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"26\"\n\nNODEMAP_TESTS=$(seq 7 26)\n\nif ! check_versions; then\n\techo \"It is NOT necessary to test nodemap under interoperation mode\"\n\tEXCEPT=\"$EXCEPT $NODEMAP_TESTS\"\nfi\n\nbuild_test_filter\n\nRUNAS_CMD=${RUNAS_CMD:-runas}\n\nWTL=${WTL:-\"$LUSTRE/tests/write_time_limit\"}\n\nCONFDIR=/etc/lustre\nPERM_CONF=$CONFDIR/perm.conf\nFAIL_ON_ERROR=false\nHOSTNAME_CHECKSUM=$(hostname | sum | awk '{ print $1 }')\nSUBNET_CHECKSUM=$(expr $HOSTNAME_CHECKSUM % 250 + 1)\n\nrequire_dsh_mds || exit 0\nrequire_dsh_ost || exit 0\n\nclients=${CLIENTS//,/ }\nnum_clients=$(get_node_count ${clients})\nclients_arr=($clients)\n\nID0=${ID0:-500}\nID1=${ID1:-501}\nUSER0=$(getent passwd | grep :$ID0:$ID0: | cut -d: -f1)\nUSER1=$(getent passwd | grep :$ID1:$ID1: | cut -d: -f1)\n\nNODEMAP_COUNT=16\nNODEMAP_RANGE_COUNT=3\nNODEMAP_IPADDR_LIST=\"1 10 64 128 200 250\"\nNODEMAP_ID_COUNT=10\nNODEMAP_MAX_ID=$((ID0 + NODEMAP_ID_COUNT))\n\n[ -z \"$USER0\" ] &&\n\tskip \"need to add user0 ($ID0:$ID0)\" && exit 0\n\n[ -z \"$USER1\" ] &&\n\tskip \"need to add user1 ($ID1:$ID1)\" && exit 0\n\nIDBASE=${IDBASE:-60000}\n\n# changes to mappings must be reflected in test 23\nFOPS_IDMAPS=(\n\t[0]=\"$((IDBASE+3)):$((IDBASE+0)) $((IDBASE+4)):$((IDBASE+2))\"\n\t[1]=\"$((IDBASE+5)):$((IDBASE+1)) $((IDBASE+6)):$((IDBASE+2))\"\n\t)\n\ncheck_and_setup_lustre\n\nassert_DIR\n\n# for GSS_SUP\nGSS_REF=$(lsmod | grep ^ptlrpc_gss | awk '{print $3}')\nif [ ! -z \"$GSS_REF\" -a \"$GSS_REF\" != \"0\" ]; then\n\tGSS_SUP=1\n\techo \"with GSS support\"\nelse\n\tGSS_SUP=0\n\techo \"without GSS support\"\nfi\n\nMDT=$(do_facet $SINGLEMDS lctl get_param -N \"mdt.\\*MDT0000\" |\n\tcut -d. -f2 || true)\n[ -z \"$MDT\" ] && error \"fail to get MDT device\" && exit 1\ndo_facet $SINGLEMDS \"mkdir -p $CONFDIR\"\nIDENTITY_FLUSH=mdt.$MDT.identity_flush\nIDENTITY_UPCALL=mdt.$MDT.identity_upcall\n\nSAVE_PWD=$PWD\n\nsec_login() {\n\tlocal user=$1\n\tlocal group=$2\n\n\t$GSS_KRB5 || return\n\tif ! $RUNAS_CMD -u $user krb5_login.sh; then\n\t\terror \"$user login kerberos failed.\"\n\t\texit 1\n\tfi\n\n\tif ! $RUNAS_CMD -u $user -g $group ls $DIR > /dev/null 2>&1; then\n\t\t$RUNAS_CMD -u $user lfs flushctx -k\n\t\t$RUNAS_CMD -u $user krb5_login.sh\n\t\tif ! $RUNAS_CMD -u$user -g$group ls $DIR > /dev/null 2>&1; then\n\t\t\terror \"init $user $group failed.\"\n\t\t\texit 2\n\t\tfi\n\tfi\n}\n\ndeclare -a identity_old\n\nsec_setup() {\n\tfor num in $(seq $MDSCOUNT); do\n\t\tswitch_identity $num true || identity_old[$num]=$?\n\tdone\n\n\tif ! $RUNAS_CMD -u $ID0 ls $DIR > /dev/null 2>&1; then\n\t\tsec_login $USER0 $USER0\n\tfi\n\n\tif ! $RUNAS_CMD -u $ID1 ls $DIR > /dev/null 2>&1; then\n\t\tsec_login $USER1 $USER1\n\tfi\n}\nsec_setup\n\n# run as different user\ntest_0() {\n\tumask 0022\n\n\tchmod 0755 $DIR || error \"chmod (1)\"\n\trm -rf $DIR/$tdir || error \"rm (1)\"\n\tmkdir -p $DIR/$tdir || error \"mkdir (1)\"\n\tchown $USER0 $DIR/$tdir || error \"chown (2)\"\n\t$RUNAS_CMD -u $ID0 ls $DIR || error \"ls (1)\"\n\trm -f $DIR/f0 || error \"rm (2)\"\n\t$RUNAS_CMD -u $ID0 touch $DIR/f0 && error \"touch (1)\"\n\t$RUNAS_CMD -u $ID0 touch $DIR/$tdir/f1 || error \"touch (2)\"\n\t$RUNAS_CMD -u $ID1 touch $DIR/$tdir/f2 && error \"touch (3)\"\n\ttouch $DIR/$tdir/f3 || error \"touch (4)\"\n\tchown root $DIR/$tdir || error \"chown (3)\"\n\tchgrp $USER0 $DIR/$tdir || error \"chgrp (1)\"\n\tchmod 0775 $DIR/$tdir || error \"chmod (2)\"\n\t$RUNAS_CMD -u $ID0 touch $DIR/$tdir/f4 || error \"touch (5)\"\n\t$RUNAS_CMD -u $ID1 touch $DIR/$tdir/f5 && error \"touch (6)\"\n\ttouch $DIR/$tdir/f6 || error \"touch (7)\"\n\trm -rf $DIR/$tdir || error \"rm (3)\"\n}\nrun_test 0 \"uid permission =============================\"\n\n# setuid/gid\ntest_1() {\n\t[ $GSS_SUP = 0 ] && skip \"without GSS support.\" && return\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\tchown $USER0 $DIR/$tdir || error \"chown (1)\"\n\t$RUNAS_CMD -u $ID1 -v $ID0 touch $DIR/$tdir/f0 && error \"touch (2)\"\n\techo \"enable uid $ID1 setuid\"\n\tdo_facet $SINGLEMDS \"echo '* $ID1 setuid' >> $PERM_CONF\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n $IDENTITY_FLUSH=-1\"\n\t$RUNAS_CMD -u $ID1 -v $ID0 touch $DIR/$tdir/f1 || error \"touch (3)\"\n\n\tchown root $DIR/$tdir || error \"chown (4)\"\n\tchgrp $USER0 $DIR/$tdir || error \"chgrp (5)\"\n\tchmod 0770 $DIR/$tdir || error \"chmod (6)\"\n\t$RUNAS_CMD -u $ID1 -g $ID1 touch $DIR/$tdir/f2 && error \"touch (7)\"\n\t$RUNAS_CMD -u$ID1 -g$ID1 -j$ID0 touch $DIR/$tdir/f3 && error \"touch (8)\"\n\techo \"enable uid $ID1 setuid,setgid\"\n\tdo_facet $SINGLEMDS \"echo '* $ID1 setuid,setgid' > $PERM_CONF\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n $IDENTITY_FLUSH=-1\"\n\t$RUNAS_CMD -u $ID1 -g $ID1 -j $ID0 touch $DIR/$tdir/f4 ||\n\t\terror \"touch (9)\"\n\t$RUNAS_CMD -u $ID1 -v $ID0 -g $ID1 -j $ID0 touch $DIR/$tdir/f5 ||\n\t\terror \"touch (10)\"\n\n\trm -rf $DIR/$tdir\n\n\tdo_facet $SINGLEMDS \"rm -f $PERM_CONF\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n $IDENTITY_FLUSH=-1\"\n}\nrun_test 1 \"setuid/gid =============================\"\n\n# bug 3285 - supplementary group should always succeed.\n# NB: the supplementary groups are set for local client only,\n# as for remote client, the groups of the specified uid on MDT\n# will be obtained by upcall /sbin/l_getidentity and used.\ntest_4() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.6.93) ]] ||\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.5.35) &&\n\t   \"$MDS1_VERSION\" -lt $(version_code 2.5.50) ]] ||\n\t\tskip \"Need MDS version at least 2.6.93 or 2.5.35\"\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\tchmod 0771 $DIR/$tdir\n\tchgrp $ID0 $DIR/$tdir\n\t$RUNAS_CMD -u $ID0 ls $DIR/$tdir || error \"setgroups (1)\"\n\tdo_facet $SINGLEMDS \"echo '* $ID1 setgrp' > $PERM_CONF\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n $IDENTITY_FLUSH=-1\"\n\t$RUNAS_CMD -u $ID1 -G1,2,$ID0 ls $DIR/$tdir ||\n\t\terror \"setgroups (2)\"\n\t$RUNAS_CMD -u $ID1 -G1,2 ls $DIR/$tdir && error \"setgroups (3)\"\n\trm -rf $DIR/$tdir\n\n\tdo_facet $SINGLEMDS \"rm -f $PERM_CONF\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n $IDENTITY_FLUSH=-1\"\n}\nrun_test 4 \"set supplementary group ===============\"\n\ncreate_nodemaps() {\n\tlocal i\n\tlocal rc\n\n\tsquash_id default 99 0\n\twait_nm_sync default squash_uid '' inactive\n\tsquash_id default 99 1\n\twait_nm_sync default squash_gid '' inactive\n\tfor (( i = 0; i < NODEMAP_COUNT; i++ )); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\tdo_facet mgs $LCTL nodemap_add $csum\n\t\trc=$?\n\t\tif [ $rc -ne 0 ]; then\n\t\t\techo \"nodemap_add $csum failed with $rc\"\n\t\t\treturn $rc\n\t\tfi\n\n\t\twait_update_facet --verbose mgs \\\n\t\t\t\"$LCTL get_param nodemap.$csum.id 2>/dev/null | \\\n\t\t\tgrep -c $csum || true\" 1 30 ||\n\t\t    return 1\n\tdone\n\tfor (( i = 0; i < NODEMAP_COUNT; i++ )); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\twait_nm_sync $csum id '' inactive\n\tdone\n\treturn 0\n}\n\ndelete_nodemaps() {\n\tlocal i\n\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\tif ! do_facet mgs $LCTL nodemap_del $csum; then\n\t\t\terror \"nodemap_del $csum failed with $?\"\n\t\t\treturn 3\n\t\tfi\n\n\t\twait_update_facet --verbose mgs \\\n\t\t\t\"$LCTL get_param nodemap.$csum.id 2>/dev/null | \\\n\t\t\tgrep -c $csum || true\" 0 30 ||\n\t\t    return 1\n\tdone\n\tfor (( i = 0; i < NODEMAP_COUNT; i++ )); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\twait_nm_sync $csum id '' inactive\n\tdone\n\treturn 0\n}\n\nadd_range() {\n\tlocal j\n\tlocal cmd=\"$LCTL nodemap_add_range\"\n\tlocal range\n\tlocal rc=0\n\n\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\trange=\"$SUBNET_CHECKSUM.${2}.${j}.[1-253]@tcp\"\n\t\tif ! do_facet mgs $cmd --name $1 --range $range; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\treturn $rc\n}\n\ndelete_range() {\n\tlocal j\n\tlocal cmd=\"$LCTL nodemap_del_range\"\n\tlocal range\n\tlocal rc=0\n\n\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\trange=\"$SUBNET_CHECKSUM.${2}.${j}.[1-253]@tcp\"\n\t\tif ! do_facet mgs $cmd --name $1 --range $range; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\n\treturn $rc\n}\n\nadd_idmaps() {\n\tlocal i\n\tlocal cmd=\"$LCTL nodemap_add_idmap\"\n\tlocal rc=0\n\n\techo \"Start to add idmaps ...\"\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal j\n\n\t\tfor ((j = $ID0; j < NODEMAP_MAX_ID; j++)); do\n\t\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\t\t\tlocal client_id=$j\n\t\t\tlocal fs_id=$((j + 1))\n\n\t\t\tif ! do_facet mgs $cmd --name $csum --idtype uid \\\n\t\t\t     --idmap $client_id:$fs_id; then\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\t\tif ! do_facet mgs $cmd --name $csum --idtype gid \\\n\t\t\t     --idmap $client_id:$fs_id; then\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\tdone\n\tdone\n\n\treturn $rc\n}\n\nupdate_idmaps() { #LU-10040\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MGS >= 2.10.55\"\n\n\tlocal csum=${HOSTNAME_CHECKSUM}_0\n\tlocal old_id_client=$ID0\n\tlocal old_id_fs=$((ID0 + 1))\n\tlocal new_id=$((ID0 + 100))\n\tlocal tmp_id\n\tlocal cmd\n\tlocal run\n\tlocal idtype\n\tlocal rc=0\n\n\techo \"Start to update idmaps ...\"\n\n\t#Inserting an existed idmap should return error\n\tcmd=\"$LCTL nodemap_add_idmap --name $csum --idtype uid\"\n\tif do_facet mgs \\\n\t\t$cmd --idmap $old_id_client:$old_id_fs 2>/dev/null; then\n\t\terror \"insert idmap {$old_id_client:$old_id_fs} \" \\\n\t\t\t\"should return error\"\n\t\trc=$((rc + 1))\n\t\treturn rc\n\tfi\n\n\t#Update id_fs and check it\n\tif ! do_facet mgs $cmd --idmap $old_id_client:$new_id; then\n\t\terror \"$cmd --idmap $old_id_client:$new_id failed\"\n\t\trc=$((rc + 1))\n\t\treturn $rc\n\tfi\n\ttmp_id=$(do_facet mgs $LCTL get_param -n nodemap.$csum.idmap |\n\t\tawk '{ print $7 }' | sed -n '2p')\n\t[ $tmp_id != $new_id ] && { error \"new id_fs $tmp_id != $new_id\"; \\\n\t\trc=$((rc + 1)); return $rc; }\n\n\t#Update id_client and check it\n\tif ! do_facet mgs $cmd --idmap $new_id:$new_id; then\n\t\terror \"$cmd --idmap $new_id:$new_id failed\"\n\t\trc=$((rc + 1))\n\t\treturn $rc\n\tfi\n\ttmp_id=$(do_facet mgs $LCTL get_param -n nodemap.$csum.idmap |\n\t\tawk '{ print $5 }' | sed -n \"$((NODEMAP_ID_COUNT + 1)) p\")\n\ttmp_id=$(echo ${tmp_id%,*}) #e.g. \"501,\"->\"501\"\n\t[ $tmp_id != $new_id ] && { error \"new id_client $tmp_id != $new_id\"; \\\n\t\trc=$((rc + 1)); return $rc; }\n\n\t#Delete above updated idmap\n\tcmd=\"$LCTL nodemap_del_idmap --name $csum --idtype uid\"\n\tif ! do_facet mgs $cmd --idmap $new_id:$new_id; then\n\t\terror \"$cmd --idmap $new_id:$new_id failed\"\n\t\trc=$((rc + 1))\n\t\treturn $rc\n\tfi\n\n\t#restore the idmaps to make delete_idmaps work well\n\tcmd=\"$LCTL nodemap_add_idmap --name $csum --idtype uid\"\n\tif ! do_facet mgs $cmd --idmap $old_id_client:$old_id_fs; then\n\t\terror \"$cmd --idmap $old_id_client:$old_id_fs failed\"\n\t\trc=$((rc + 1))\n\t\treturn $rc\n\tfi\n\n\treturn $rc\n}\n\ndelete_idmaps() {\n\tlocal i\n\tlocal cmd=\"$LCTL nodemap_del_idmap\"\n\tlocal rc=0\n\n\techo \"Start to delete idmaps ...\"\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal j\n\n\t\tfor ((j = $ID0; j < NODEMAP_MAX_ID; j++)); do\n\t\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\t\t\tlocal client_id=$j\n\t\t\tlocal fs_id=$((j + 1))\n\n\t\t\tif ! do_facet mgs $cmd --name $csum --idtype uid \\\n\t\t\t     --idmap $client_id:$fs_id; then\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\t\tif ! do_facet mgs $cmd --name $csum --idtype gid \\\n\t\t\t     --idmap $client_id:$fs_id; then\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\tdone\n\tdone\n\n\treturn $rc\n}\n\nmodify_flags() {\n\tlocal i\n\tlocal proc\n\tlocal option\n\tlocal cmd=\"$LCTL nodemap_modify\"\n\tlocal rc=0\n\n\tproc[0]=\"admin_nodemap\"\n\tproc[1]=\"trusted_nodemap\"\n\toption[0]=\"admin\"\n\toption[1]=\"trusted\"\n\n\tfor ((idx = 0; idx < 2; idx++)); do\n\t\tif ! do_facet mgs $cmd --name $1 --property ${option[$idx]} \\\n\t\t     --value 1; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\n\t\tif ! do_facet mgs $cmd --name $1 --property ${option[$idx]} \\\n\t\t     --value 0; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\n\treturn $rc\n}\n\nsquash_id() {\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\tlocal cmd\n\n\tcmd[0]=\"$LCTL nodemap_modify --property squash_uid\"\n\tcmd[1]=\"$LCTL nodemap_modify --property squash_gid\"\n\n\tif ! do_facet mgs ${cmd[$3]} --name $1 --value $2; then\n\t\treturn 1\n\tfi\n}\n\nwait_nm_sync() {\n\tlocal nodemap_name=$1\n\tlocal key=$2\n\tlocal value=$3\n\tlocal opt=$4\n\tlocal proc_param\n\tlocal is_active=$(do_facet mgs $LCTL get_param -n nodemap.active)\n\tlocal max_retries=20\n\tlocal is_sync\n\tlocal out1=\"\"\n\tlocal out2\n\tlocal mgs_ip=$(host_nids_address $mgs_HOST $NETTYPE | cut -d' ' -f1)\n\tlocal i\n\n\tif [ \"$nodemap_name\" == \"active\" ]; then\n\t\tproc_param=\"active\"\n\telif [ -z \"$key\" ]; then\n\t\tproc_param=${nodemap_name}\n\telse\n\t\tproc_param=\"${nodemap_name}.${key}\"\n\tfi\n\tif [ \"$opt\" == \"inactive\" ]; then\n\t\t# check nm sync even if nodemap is not activated\n\t\tis_active=1\n\t\topt=\"\"\n\tfi\n\t(( is_active == 0 )) && [ \"$proc_param\" != \"active\" ] && return\n\n\tif [ -z \"$value\" ]; then\n\t\tout1=$(do_facet mgs $LCTL get_param $opt \\\n\t\t\tnodemap.${proc_param} 2>/dev/null)\n\t\techo \"On MGS ${mgs_ip}, ${proc_param} = $out1\"\n\telse\n\t\tout1=$value;\n\tfi\n\n\t# wait up to 10 seconds for other servers to sync with mgs\n\tfor i in $(seq 1 10); do\n\t\tfor node in $(all_server_nodes); do\n\t\t    local node_ip=$(host_nids_address $node $NETTYPE |\n\t\t\t\t    cut -d' ' -f1)\n\n\t\t    is_sync=true\n\t\t    if [ -z \"$value\" ]; then\n\t\t\t[ $node_ip == $mgs_ip ] && continue\n\t\t    fi\n\n\t\t    out2=$(do_node $node_ip $LCTL get_param $opt \\\n\t\t\t\t   nodemap.$proc_param 2>/dev/null)\n\t\t    echo \"On $node ${node_ip}, ${proc_param} = $out2\"\n\t\t    [ \"$out1\" != \"$out2\" ] && is_sync=false && break\n\t\tdone\n\t\t$is_sync && break\n\t\tsleep 1\n\tdone\n\tif ! $is_sync; then\n\t\techo MGS\n\t\techo $out1\n\t\techo OTHER - IP: $node_ip\n\t\techo $out2\n\t\terror \"mgs and $nodemap_name ${key} mismatch, $i attempts\"\n\tfi\n\techo \"waited $((i - 1)) seconds for sync\"\n}\n\n# ensure that the squash defaults are the expected defaults\nsquash_id default 99 0\nwait_nm_sync default squash_uid '' inactive\nsquash_id default 99 1\nwait_nm_sync default squash_gid '' inactive\n\ntest_nid() {\n\tlocal cmd\n\n\tcmd=\"$LCTL nodemap_test_nid\"\n\n\tnid=$(do_facet mgs $cmd $1)\n\n\tif [ $nid == $2 ]; then\n\t\treturn 0\n\tfi\n\n\treturn 1\n}\n\ncleanup_active() {\n\t# restore activation state\n\tdo_facet mgs $LCTL nodemap_activate 0\n\twait_nm_sync active\n}\n\ntest_idmap() {\n\tlocal i\n\tlocal cmd=\"$LCTL nodemap_test_id\"\n\tlocal rc=0\n\n\techo \"Start to test idmaps ...\"\n\t## nodemap deactivated\n\tif ! do_facet mgs $LCTL nodemap_activate 0; then\n\t\treturn 1\n\tfi\n\tfor ((id = $ID0; id < NODEMAP_MAX_ID; id++)); do\n\t\tlocal j\n\n\t\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\t\tlocal nid=\"$SUBNET_CHECKSUM.0.${j}.100@tcp\"\n\t\t\tlocal fs_id=$(do_facet mgs $cmd --nid $nid\t\\\n\t\t\t\t      --idtype uid --id $id)\n\t\t\tif [ $fs_id != $id ]; then\n\t\t\t\techo \"expected $id, got $fs_id\"\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\tdone\n\tdone\n\n\t## nodemap activated\n\tif ! do_facet mgs $LCTL nodemap_activate 1; then\n\t\treturn 2\n\tfi\n\n\tfor ((id = $ID0; id < NODEMAP_MAX_ID; id++)); do\n\t\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\t\tnid=\"$SUBNET_CHECKSUM.0.${j}.100@tcp\"\n\t\t\tfs_id=$(do_facet mgs $cmd --nid $nid\t\\\n\t\t\t\t--idtype uid --id $id)\n\t\t\texpected_id=$((id + 1))\n\t\t\tif [ $fs_id != $expected_id ]; then\n\t\t\t\techo \"expected $expected_id, got $fs_id\"\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\tdone\n\tdone\n\n\t## trust client ids\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\tif ! do_facet mgs $LCTL nodemap_modify --name $csum \\\n\t\t     --property trusted --value 1; then\n\t\t\terror \"nodemap_modify $csum failed with $?\"\n\t\t\treturn 3\n\t\tfi\n\tdone\n\n\tfor ((id = $ID0; id < NODEMAP_MAX_ID; id++)); do\n\t\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\t\tnid=\"$SUBNET_CHECKSUM.0.${j}.100@tcp\"\n\t\t\tfs_id=$(do_facet mgs $cmd --nid $nid\t\\\n\t\t\t\t--idtype uid --id $id)\n\t\t\tif [ $fs_id != $id ]; then\n\t\t\t\techo \"expected $id, got $fs_id\"\n\t\t\t\trc=$((rc + 1))\n\t\t\tfi\n\t\tdone\n\tdone\n\n\t## ensure allow_root_access is enabled\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\tif ! do_facet mgs $LCTL nodemap_modify --name $csum\t\\\n\t\t     --property admin --value 1; then\n\t\t\terror \"nodemap_modify $csum failed with $?\"\n\t\t\treturn 3\n\t\tfi\n\tdone\n\n\t## check that root allowed\n\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\tnid=\"$SUBNET_CHECKSUM.0.${j}.100@tcp\"\n\t\tfs_id=$(do_facet mgs $cmd --nid $nid --idtype uid --id 0)\n\t\tif [ $fs_id != 0 ]; then\n\t\t\techo \"root allowed expected 0, got $fs_id\"\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\n\t## ensure allow_root_access is disabled\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tlocal csum=${HOSTNAME_CHECKSUM}_${i}\n\n\t\tif ! do_facet mgs $LCTL nodemap_modify --name $csum\t\\\n\t\t\t\t--property admin --value 0; then\n\t\t\terror \"nodemap_modify ${HOSTNAME_CHECKSUM}_${i} \"\n\t\t\t\t\"failed with $rc\"\n\t\t\treturn 3\n\t\tfi\n\tdone\n\n\t## check that root is mapped to 99\n\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\tnid=\"$SUBNET_CHECKSUM.0.${j}.100@tcp\"\n\t\tfs_id=$(do_facet mgs $cmd --nid $nid --idtype uid --id 0)\n\t\tif [ $fs_id != 99 ]; then\n\t\t\terror \"root squash expected 99, got $fs_id\"\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\n\t## reset client trust to 0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! do_facet mgs $LCTL nodemap_modify\t\t\\\n\t\t\t--name ${HOSTNAME_CHECKSUM}_${i}\t\\\n\t\t\t--property trusted --value 0; then\n\t\t\terror \"nodemap_modify ${HOSTNAME_CHECKSUM}_${i} \"\n\t\t\t\t\"failed with $rc\"\n\t\t\treturn 3\n\t\tfi\n\tdone\n\n\treturn $rc\n}\n\ntest_7() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\"\n\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\"\n\n\treturn 0\n}\nrun_test 7 \"nodemap create and delete\"\n\ntest_8() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\t# Set up nodemaps\n\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\t# Try duplicates\n\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc == 0 ]] && error \"duplicate nodemap_add allowed with $rc\" &&\n\treturn 2\n\n\t# Clean up\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 3\n\n\treturn 0\n}\nrun_test 8 \"nodemap reject duplicates\"\n\ntest_9() {\n\tlocal i\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! add_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_add_range failed with $rc\" && return 2\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! delete_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_del_range failed with $rc\" && return 4\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 4\n\n\treturn 0\n}\nrun_test 9 \"nodemap range add\"\n\ntest_10a() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! add_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_add_range failed with $rc\" && return 2\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! add_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc == 0 ]] && error \"nodemap_add_range duplicate add with $rc\" &&\n\t\treturn 2\n\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! delete_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_del_range failed with $rc\" && return 4\n\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 5\n\n\treturn 0\n}\nrun_test 10a \"nodemap reject duplicate ranges\"\n\ntest_10b() {\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.10.53) ] &&\n\t\tskip \"Need MGS >= 2.10.53\"\n\n\tlocal nm1=\"nodemap1\"\n\tlocal nm2=\"nodemap2\"\n\tlocal nids=\"192.168.19.[0-255]@o2ib20\"\n\n\tdo_facet mgs $LCTL nodemap_del $nm1 2>/dev/null\n\tdo_facet mgs $LCTL nodemap_del $nm2 2>/dev/null\n\n\tdo_facet mgs $LCTL nodemap_add $nm1 || error \"Add $nm1 failed\"\n\tdo_facet mgs $LCTL nodemap_add $nm2 || error \"Add $nm2 failed\"\n\tdo_facet mgs $LCTL nodemap_add_range --name $nm1 --range $nids ||\n\t\terror \"Add range $nids to $nm1 failed\"\n\t[ -n \"$(do_facet mgs $LCTL get_param nodemap.$nm1.* |\n\t\tgrep start_nid)\" ] || error \"No range was found\"\n\tdo_facet mgs $LCTL nodemap_del_range --name $nm2 --range $nids &&\n\t\terror \"Deleting range $nids from $nm2 should fail\"\n\t[ -n \"$(do_facet mgs $LCTL get_param nodemap.$nm1.* |\n\t\tgrep start_nid)\" ] || error \"Range $nids should be there\"\n\n\tdo_facet mgs $LCTL nodemap_del $nm1 || error \"Delete $nm1 failed\"\n\tdo_facet mgs $LCTL nodemap_del $nm2 || error \"Delete $nm2 failed\"\n\treturn 0\n}\nrun_test 10b \"delete range from the correct nodemap\"\n\ntest_10c() { #LU-8912\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.10.57) ] &&\n\t\tskip \"Need MGS >= 2.10.57\"\n\n\tlocal nm=\"nodemap_lu8912\"\n\tlocal nid_range=\"10.210.[32-47].[0-255]@o2ib3\"\n\tlocal start_nid=\"10.210.32.0@o2ib3\"\n\tlocal end_nid=\"10.210.47.255@o2ib3\"\n\tlocal start_nid_found\n\tlocal end_nid_found\n\n\tdo_facet mgs $LCTL nodemap_del $nm 2>/dev/null\n\tdo_facet mgs $LCTL nodemap_add $nm || error \"Add $nm failed\"\n\tdo_facet mgs $LCTL nodemap_add_range --name $nm --range $nid_range ||\n\t\terror \"Add range $nid_range to $nm failed\"\n\n\tstart_nid_found=$(do_facet mgs $LCTL get_param nodemap.$nm.* |\n\t\tawk -F '[,: ]' /start_nid/'{ print $9 }')\n\t[ \"$start_nid\" == \"$start_nid_found\" ] ||\n\t\terror \"start_nid: $start_nid_found != $start_nid\"\n\tend_nid_found=$(do_facet mgs $LCTL get_param nodemap.$nm.* |\n\t\tawk -F '[,: ]' /end_nid/'{ print $13 }')\n\t[ \"$end_nid\" == \"$end_nid_found\" ] ||\n\t\terror \"end_nid: $end_nid_found != $end_nid\"\n\n\tdo_facet mgs $LCTL nodemap_del $nm || error \"Delete $nm failed\"\n\treturn 0\n}\nrun_test 10c \"verfify contiguous range support\"\n\ntest_10d() { #LU-8913\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.10.59) ] &&\n\t\tskip \"Need MGS >= 2.10.59\"\n\n\tlocal nm=\"nodemap_lu8913\"\n\tlocal nid_range=\"*@o2ib3\"\n\tlocal start_nid=\"0.0.0.0@o2ib3\"\n\tlocal end_nid=\"255.255.255.255@o2ib3\"\n\tlocal start_nid_found\n\tlocal end_nid_found\n\n\tdo_facet mgs $LCTL nodemap_del $nm 2>/dev/null\n\tdo_facet mgs $LCTL nodemap_add $nm || error \"Add $nm failed\"\n\tdo_facet mgs $LCTL nodemap_add_range --name $nm --range $nid_range ||\n\t\terror \"Add range $nid_range to $nm failed\"\n\n\tstart_nid_found=$(do_facet mgs $LCTL get_param nodemap.$nm.* |\n\t\tawk -F '[,: ]' /start_nid/'{ print $9 }')\n\t[ \"$start_nid\" == \"$start_nid_found\" ] ||\n\t\terror \"start_nid: $start_nid_found != $start_nid\"\n\tend_nid_found=$(do_facet mgs $LCTL get_param nodemap.$nm.* |\n\t\tawk -F '[,: ]' /end_nid/'{ print $13 }')\n\t[ \"$end_nid\" == \"$end_nid_found\" ] ||\n\t\terror \"end_nid: $end_nid_found != $end_nid\"\n\n\tdo_facet mgs $LCTL nodemap_del $nm || error \"Delete $nm failed\"\n\treturn 0\n}\nrun_test 10d \"verfify nodemap range format '*@<net>' support\"\n\ntest_11() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! modify_flags ${HOSTNAME_CHECKSUM}_${i}; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_modify with $rc\" && return 2\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 3\n\n\treturn 0\n}\nrun_test 11 \"nodemap modify\"\n\ntest_12() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! squash_id ${HOSTNAME_CHECKSUM}_${i} 88 0; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap squash_uid with $rc\" && return 2\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! squash_id ${HOSTNAME_CHECKSUM}_${i} 88 1; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap squash_gid with $rc\" && return 3\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 4\n\n\treturn 0\n}\nrun_test 12 \"nodemap set squash ids\"\n\ntest_13() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! add_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_add_range failed with $rc\" && return 2\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\t\tfor k in $NODEMAP_IPADDR_LIST; do\n\t\t\t\tif ! test_nid $SUBNET_CHECKSUM.$i.$j.$k\t\\\n\t\t\t\t       ${HOSTNAME_CHECKSUM}_${i}; then\n\t\t\t\t\trc=$((rc + 1))\n\t\t\t\tfi\n\t\t\tdone\n\t\tdone\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_test_nid failed with $rc\" && return 3\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 4\n\n\treturn 0\n}\nrun_test 13 \"test nids\"\n\ntest_14() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tfor ((j = 0; j < NODEMAP_RANGE_COUNT; j++)); do\n\t\t\tfor k in $NODEMAP_IPADDR_LIST; do\n\t\t\t\tif ! test_nid $SUBNET_CHECKSUM.$i.$j.$k \\\n\t\t\t\t\tdefault; then\n\t\t\t\t\trc=$((rc + 1))\n\t\t\t\tfi\n\t\t\tdone\n\t\tdone\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_test_nid failed with $rc\" && return 3\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del failed with $rc\" && return 4\n\n\treturn 0\n}\nrun_test 14 \"test default nodemap nid lookup\"\n\ntest_15() {\n\tlocal rc\n\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\"\n\n\trc=0\n\tcreate_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add failed with $rc\" && return 1\n\n\trc=0\n\tfor ((i = 0; i < NODEMAP_COUNT; i++)); do\n\t\tif ! add_range ${HOSTNAME_CHECKSUM}_${i} $i; then\n\t\t\trc=$((rc + 1))\n\t\tfi\n\tdone\n\t[[ $rc != 0 ]] && error \"nodemap_add_range failed with $rc\" && return 2\n\n\trc=0\n\tadd_idmaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_add_idmap failed with $rc\" && return 3\n\n\tactivedefault=$(do_facet mgs $LCTL get_param -n nodemap.active)\n\tif [[ \"$activedefault\" != \"1\" ]]; then\n\t\tstack_trap cleanup_active EXIT\n\tfi\n\n\trc=0\n\ttest_idmap\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_test_id failed with $rc\" && return 4\n\n\trc=0\n\tupdate_idmaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"update_idmaps failed with $rc\" && return 5\n\n\trc=0\n\tdelete_idmaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_del_idmap failed with $rc\" && return 6\n\n\trc=0\n\tdelete_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"nodemap_delete failed with $rc\" && return 7\n\n\treturn 0\n}\nrun_test 15 \"test id mapping\"\n\ncreate_fops_nodemaps() {\n\tlocal i=0\n\tlocal client\n\tfor client in $clients; do\n\t\tlocal client_ip=$(host_nids_address $client $NETTYPE)\n\t\tlocal client_nid=$(h2nettype $client_ip)\n\t\tdo_facet mgs $LCTL nodemap_add c${i} || return 1\n\t\tdo_facet mgs $LCTL nodemap_add_range \t\\\n\t\t\t--name c${i} --range $client_nid || return 1\n\t\tfor map in ${FOPS_IDMAPS[i]}; do\n\t\t\tdo_facet mgs $LCTL nodemap_add_idmap --name c${i} \\\n\t\t\t\t--idtype uid --idmap ${map} || return 1\n\t\t\tdo_facet mgs $LCTL nodemap_add_idmap --name c${i} \\\n\t\t\t\t--idtype gid --idmap ${map} || return 1\n\t\tdone\n\n\t\twait_nm_sync c$i idmap\n\n\t\ti=$((i + 1))\n\tdone\n\treturn 0\n}\n\ndelete_fops_nodemaps() {\n\tlocal i=0\n\tlocal client\n\tfor client in $clients; do\n\t\tdo_facet mgs $LCTL nodemap_del c${i} || return 1\n\t\ti=$((i + 1))\n\tdone\n\treturn 0\n}\n\nfops_mds_index=0\nnm_test_mkdir() {\n\tif [ $MDSCOUNT -le 1 ]; then\n\t\tdo_node ${clients_arr[0]} mkdir -p $DIR/$tdir\n\telse\n\t\t# round-robin MDTs to test DNE nodemap support\n\t\t[ ! -d $DIR ] && do_node ${clients_arr[0]} mkdir -p $DIR\n\t\tdo_node ${clients_arr[0]} $LFS setdirstripe -c 1 -i \\\n\t\t\t$((fops_mds_index % MDSCOUNT)) $DIR/$tdir\n\t\t((fops_mds_index++))\n\tfi\n}\n\n# acl test directory needs to be initialized on a privileged client\nfops_test_setup() {\n\tlocal admin=$(do_facet mgs $LCTL get_param -n nodemap.c0.admin_nodemap)\n\tlocal trust=$(do_facet mgs $LCTL get_param -n \\\n\t\tnodemap.c0.trusted_nodemap)\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property trusted --value 1\n\n\twait_nm_sync c0 admin_nodemap\n\twait_nm_sync c0 trusted_nodemap\n\n\tdo_node ${clients_arr[0]} rm -rf $DIR/$tdir\n\tnm_test_mkdir\n\tdo_node ${clients_arr[0]} chown $user $DIR/$tdir\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t--property admin --value $admin\n\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t--property trusted --value $trust\n\n\t# flush MDT locks to make sure they are reacquired before test\n\tdo_node ${clients_arr[0]} $LCTL set_param \\\n\t\tldlm.namespaces.$FSNAME-MDT*.lru_size=clear\n\n\twait_nm_sync c0 admin_nodemap\n\twait_nm_sync c0 trusted_nodemap\n}\n\n# fileset test directory needs to be initialized on a privileged client\nfileset_test_setup() {\n\tlocal nm=$1\n\n\tif [ -n \"$FILESET\" -a -z \"$SKIP_FILESET\" ]; then\n\t\tcleanup_mount $MOUNT\n\t\tFILESET=\"\" zconf_mount_clients $CLIENTS $MOUNT\n\tfi\n\n\tlocal admin=$(do_facet mgs $LCTL get_param -n \\\n\t\tnodemap.${nm}.admin_nodemap)\n\tlocal trust=$(do_facet mgs $LCTL get_param -n \\\n\t\tnodemap.${nm}.trusted_nodemap)\n\n\tdo_facet mgs $LCTL nodemap_modify --name $nm --property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name $nm --property trusted \\\n\t\t--value 1\n\n\twait_nm_sync $nm admin_nodemap\n\twait_nm_sync $nm trusted_nodemap\n\n\t# create directory and populate it for subdir mount\n\tdo_node ${clients_arr[0]} mkdir $MOUNT/$subdir ||\n\t\terror \"unable to create dir $MOUNT/$subdir\"\n\tdo_node ${clients_arr[0]} touch $MOUNT/$subdir/this_is_$subdir ||\n\t\terror \"unable to create file $MOUNT/$subdir/this_is_$subdir\"\n\tdo_node ${clients_arr[0]} mkdir $MOUNT/$subdir/$subsubdir ||\n\t\terror \"unable to create dir $MOUNT/$subdir/$subsubdir\"\n\tdo_node ${clients_arr[0]} touch \\\n\t\t\t$MOUNT/$subdir/$subsubdir/this_is_$subsubdir ||\n\t\terror \"unable to create file \\\n\t\t\t$MOUNT/$subdir/$subsubdir/this_is_$subsubdir\"\n\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t--property admin --value $admin\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t--property trusted --value $trust\n\n\t# flush MDT locks to make sure they are reacquired before test\n\tdo_node ${clients_arr[0]} $LCTL set_param \\\n\t\tldlm.namespaces.$FSNAME-MDT*.lru_size=clear\n\n\twait_nm_sync $nm admin_nodemap\n\twait_nm_sync $nm trusted_nodemap\n}\n\n# fileset test directory needs to be initialized on a privileged client\nfileset_test_cleanup() {\n\tlocal nm=$1\n\tlocal admin=$(do_facet mgs $LCTL get_param -n \\\n\t\tnodemap.${nm}.admin_nodemap)\n\tlocal trust=$(do_facet mgs $LCTL get_param -n \\\n\t\tnodemap.${nm}.trusted_nodemap)\n\n\tdo_facet mgs $LCTL nodemap_modify --name $nm --property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name $nm --property trusted \\\n\t\t--value 1\n\n\twait_nm_sync $nm admin_nodemap\n\twait_nm_sync $nm trusted_nodemap\n\n\t# cleanup directory created for subdir mount\n\tdo_node ${clients_arr[0]} rm -rf $MOUNT/$subdir ||\n\t\terror \"unable to remove dir $MOUNT/$subdir\"\n\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t--property admin --value $admin\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t--property trusted --value $trust\n\n\t# flush MDT locks to make sure they are reacquired before test\n\tdo_node ${clients_arr[0]} $LCTL set_param \\\n\t\tldlm.namespaces.$FSNAME-MDT*.lru_size=clear\n\n\twait_nm_sync $nm admin_nodemap\n\twait_nm_sync $nm trusted_nodemap\n\tif [ -n \"$FILESET\" -a -z \"$SKIP_FILESET\" ]; then\n\t\tcleanup_mount $MOUNT\n\t\tzconf_mount_clients $CLIENTS $MOUNT\n\tfi\n}\n\ndo_create_delete() {\n\tlocal run_u=$1\n\tlocal key=$2\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal rc=0\n\tlocal c=0 d=0\n\tlocal qused_new\n\tif $run_u touch $testfile >& /dev/null; then\n\t\tc=1\n\t\t$run_u rm $testfile && d=1\n\tfi >& /dev/null\n\n\tlocal res=\"$c $d\"\n\tlocal expected=$(get_cr_del_expected $key)\n\t[ \"$res\" != \"$expected\" ] &&\n\t\terror \"test $key, wanted $expected, got $res\" && rc=$((rc + 1))\n\treturn $rc\n}\n\nnodemap_check_quota() {\n\tlocal run_u=\"$1\"\n\t$run_u lfs quota -q $DIR | awk '{ print $2; exit; }'\n}\n\ndo_fops_quota_test() {\n\tlocal run_u=$1\n\t# fuzz quota used to account for possible indirect blocks, etc\n\tlocal quota_fuzz=$(fs_log_size)\n\tlocal qused_orig=$(nodemap_check_quota \"$run_u\")\n\tlocal qused_high=$((qused_orig + quota_fuzz))\n\tlocal qused_low=$((qused_orig - quota_fuzz))\n\tlocal testfile=$DIR/$tdir/$tfile\n\t$run_u dd if=/dev/zero of=$testfile oflag=sync bs=1M count=1 \\\n\t\t>& /dev/null || error \"unable to write quota test file\"\n\tsync; sync_all_data || true\n\n\tlocal qused_new=$(nodemap_check_quota \"$run_u\")\n\t[ $((qused_new)) -lt $((qused_low + 1024)) -o \\\n\t  $((qused_new)) -gt $((qused_high + 1024)) ] &&\n\t\terror \"$qused_new != $qused_orig + 1M after write, \" \\\n\t\t      \"fuzz is $quota_fuzz\"\n\t$run_u rm $testfile || error \"unable to remove quota test file\"\n\twait_delete_completed_mds\n\n\tqused_new=$(nodemap_check_quota \"$run_u\")\n\t[ $((qused_new)) -lt $((qused_low)) \\\n\t\t-o $((qused_new)) -gt $((qused_high)) ] &&\n\t\terror \"quota not reclaimed, expect $qused_orig, \" \\\n\t\t      \"got $qused_new, fuzz $quota_fuzz\"\n}\n\nget_fops_mapped_user() {\n\tlocal cli_user=$1\n\n\tfor ((i=0; i < ${#FOPS_IDMAPS[@]}; i++)); do\n\t\tfor map in ${FOPS_IDMAPS[i]}; do\n\t\t\tif [ $(cut -d: -f1 <<< \"$map\") == $cli_user ]; then\n\t\t\t\tcut -d: -f2 <<< \"$map\"\n\t\t\t\treturn\n\t\t\tfi\n\t\tdone\n\tdone\n\techo -1\n}\n\nget_cr_del_expected() {\n\tlocal -a key\n\tIFS=\":\" read -a key <<< \"$1\"\n\tlocal mapmode=\"${key[0]}\"\n\tlocal mds_user=\"${key[1]}\"\n\tlocal cluster=\"${key[2]}\"\n\tlocal cli_user=\"${key[3]}\"\n\tlocal mode=\"0${key[4]}\"\n\tlocal SUCCESS=\"1 1\"\n\tlocal FAILURE=\"0 0\"\n\tlocal noadmin=0\n\tlocal mapped=0\n\tlocal other=0\n\n\t[[ $mapmode == *mapped* ]] && mapped=1\n\t# only c1 is mapped in these test cases\n\t[[ $mapmode == mapped_trusted* ]] && [ \"$cluster\" == \"c0\" ] && mapped=0\n\t[[ $mapmode == *noadmin* ]] && noadmin=1\n\n\t# o+wx works as long as the user isn't mapped\n\tif [ $((mode & 3)) -eq 3 ]; then\n\t\tother=1\n\tfi\n\n\t# if client user is root, check if root is squashed\n\tif [ \"$cli_user\" == \"0\" ]; then\n\t\t# squash root succeed, if other bit is on\n\t\tcase $noadmin in\n\t\t\t0) echo $SUCCESS;;\n\t\t\t1) [ \"$other\" == \"1\" ] && echo $SUCCESS\n\t\t\t   [ \"$other\" == \"0\" ] && echo $FAILURE;;\n\t\tesac\n\t\treturn\n\tfi\n\tif [ \"$mapped\" == \"0\" ]; then\n\t\t[ \"$other\" == \"1\" ] && echo $SUCCESS\n\t\t[ \"$other\" == \"0\" ] && echo $FAILURE\n\t\treturn\n\tfi\n\n\t# if mapped user is mds user, check for u+wx\n\tmapped_user=$(get_fops_mapped_user $cli_user)\n\t[ \"$mapped_user\" == \"-1\" ] &&\n\t\terror \"unable to find mapping for client user $cli_user\"\n\n\tif [ \"$mapped_user\" == \"$mds_user\" -a \\\n\t     $(((mode & 0300) == 0300)) -eq 1 ]; then\n\t\techo $SUCCESS\n\t\treturn\n\tfi\n\tif [ \"$mapped_user\" != \"$mds_user\" -a \"$other\" == \"1\" ]; then\n\t\techo $SUCCESS\n\t\treturn\n\tfi\n\techo $FAILURE\n}\n\ntest_fops_admin_cli_i=\"\"\ntest_fops_chmod_dir() {\n\tlocal current_cli_i=$1\n\tlocal perm_bits=$2\n\tlocal dir_to_chmod=$3\n\tlocal new_admin_cli_i=\"\"\n\n\t# do we need to set up a new admin client?\n\t[ \"$current_cli_i\" == \"0\" ] && [ \"$test_fops_admin_cli_i\" != \"1\" ] &&\n\t\tnew_admin_cli_i=1\n\t[ \"$current_cli_i\" != \"0\" ] && [ \"$test_fops_admin_cli_i\" != \"0\" ] &&\n\t\tnew_admin_cli_i=0\n\n\t# if only one client, and non-admin, need to flip admin everytime\n\tif [ \"$num_clients\" == \"1\" ]; then\n\t\ttest_fops_admin_client=$clients\n\t\ttest_fops_admin_val=$(do_facet mgs $LCTL get_param -n \\\n\t\t\tnodemap.c0.admin_nodemap)\n\t\tif [ \"$test_fops_admin_val\" != \"1\" ]; then\n\t\t\tdo_facet mgs $LCTL nodemap_modify \\\n\t\t\t\t--name c0 \\\n\t\t\t\t--property admin \\\n\t\t\t\t--value 1\n\t\t\twait_nm_sync c0 admin_nodemap\n\t\tfi\n\telif [ \"$new_admin_cli_i\" != \"\" ]; then\n\t\t# restore admin val to old admin client\n\t\tif [ \"$test_fops_admin_cli_i\" != \"\" ] &&\n\t\t\t\t[ \"$test_fops_admin_val\" != \"1\" ]; then\n\t\t\tdo_facet mgs $LCTL nodemap_modify \\\n\t\t\t\t--name c${test_fops_admin_cli_i} \\\n\t\t\t\t--property admin \\\n\t\t\t\t--value $test_fops_admin_val\n\t\t\twait_nm_sync c${test_fops_admin_cli_i} admin_nodemap\n\t\tfi\n\n\t\ttest_fops_admin_cli_i=$new_admin_cli_i\n\t\ttest_fops_admin_client=${clients_arr[$new_admin_cli_i]}\n\t\ttest_fops_admin_val=$(do_facet mgs $LCTL get_param -n \\\n\t\t\tnodemap.c${new_admin_cli_i}.admin_nodemap)\n\n\t\tif [ \"$test_fops_admin_val\" != \"1\" ]; then\n\t\t\tdo_facet mgs $LCTL nodemap_modify \\\n\t\t\t\t--name c${new_admin_cli_i} \\\n\t\t\t\t--property admin \\\n\t\t\t\t--value 1\n\t\t\twait_nm_sync c${new_admin_cli_i} admin_nodemap\n\t\tfi\n\tfi\n\n\tdo_node $test_fops_admin_client chmod $perm_bits $DIR/$tdir || return 1\n\n\t# remove admin for single client if originally non-admin\n\tif [ \"$num_clients\" == \"1\" ] && [ \"$test_fops_admin_val\" != \"1\" ]; then\n\t\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin \\\n\t\t\t--value 0\n\t\twait_nm_sync c0 admin_nodemap\n\tfi\n\n\treturn 0\n}\n\ntest_fops() {\n\tlocal mapmode=\"$1\"\n\tlocal single_client=\"$2\"\n\tlocal client_user_list=([0]=\"0 $((IDBASE+3)) $((IDBASE+4))\"\n\t\t\t\t[1]=\"0 $((IDBASE+5)) $((IDBASE+6))\")\n\tlocal mds_i\n\tlocal rc=0\n\tlocal perm_bit_list=\"0 3 $((0300)) $((0303))\"\n\t# SLOW tests 000-007, 010-070, 100-700 (octal modes)\n\t[ \"$SLOW\" == \"yes\" ] &&\n\t\tperm_bit_list=\"0 $(seq 1 7) $(seq 8 8 63) $(seq 64 64 511) \\\n\t\t\t       $((0303))\"\n\n\t# step through mds users. -1 means root\n\tfor mds_i in -1 0 1 2; do\n\t\tlocal user=$((mds_i + IDBASE))\n\t\tlocal client\n\t\tlocal x\n\n\t\t[ \"$mds_i\" == \"-1\" ] && user=0\n\n\t\techo mkdir -p $DIR/$tdir\n\t\tfops_test_setup\n\t\tlocal cli_i=0\n\t\tfor client in $clients; do\n\t\t\tlocal u\n\t\t\tfor u in ${client_user_list[$cli_i]}; do\n\t\t\t\tlocal run_u=\"do_node $client \\\n\t\t\t\t\t     $RUNAS_CMD -u$u -g$u -G$u\"\n\t\t\t\tfor perm_bits in $perm_bit_list; do\n\t\t\t\t\tlocal mode=$(printf %03o $perm_bits)\n\t\t\t\t\tlocal key\n\t\t\t\t\tkey=\"$mapmode:$user:c$cli_i:$u:$mode\"\n\t\t\t\t\ttest_fops_chmod_dir $cli_i $mode \\\n\t\t\t\t\t\t$DIR/$tdir ||\n\t\t\t\t\t\t\terror cannot chmod $key\n\t\t\t\t\tdo_create_delete \"$run_u\" \"$key\"\n\t\t\t\tdone\n\n\t\t\t\t# check quota\n\t\t\t\ttest_fops_chmod_dir $cli_i 777 $DIR/$tdir ||\n\t\t\t\t\terror cannot chmod $key\n\t\t\t\tdo_fops_quota_test \"$run_u\"\n\t\t\tdone\n\n\t\t\tcli_i=$((cli_i + 1))\n\t\t\t[ \"$single_client\" == \"1\" ] && break\n\t\tdone\n\t\trm -rf $DIR/$tdir\n\tdone\n\treturn $rc\n}\n\nnodemap_version_check () {\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\" && return 1\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.5.53) ] &&\n\t\tskip \"No nodemap on $MGS_VERSION MGS < 2.5.53\" &&\n\t\treturn 1\n\treturn 0\n}\n\nnodemap_test_setup() {\n\tlocal rc\n\tlocal active_nodemap=1\n\n\t[ \"$1\" == \"0\" ] && active_nodemap=0\n\n\tdo_nodes $(comma_list $(all_mdts_nodes)) \\\n\t\t$LCTL set_param mdt.*.identity_upcall=NONE\n\n\trc=0\n\tcreate_fops_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"adding fops nodemaps failed $rc\"\n\n\tdo_facet mgs $LCTL nodemap_activate $active_nodemap\n\twait_nm_sync active\n\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t--property admin --value 1\n\twait_nm_sync default admin_nodemap\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t--property trusted --value 1\n\twait_nm_sync default trusted_nodemap\n}\n\nnodemap_test_cleanup() {\n\ttrap 0\n\tdelete_fops_nodemaps\n\trc=$?\n\t[[ $rc != 0 ]] && error \"removing fops nodemaps failed $rc\"\n\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t --property admin --value 0\n\twait_nm_sync default admin_nodemap\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t --property trusted --value 0\n\twait_nm_sync default trusted_nodemap\n\n\tdo_facet mgs $LCTL nodemap_activate 0\n\twait_nm_sync active 0\n\n\texport SK_UNIQUE_NM=false\n\treturn 0\n}\n\nnodemap_clients_admin_trusted() {\n\tlocal admin=$1\n\tlocal tr=$2\n\tlocal i=0\n\tfor client in $clients; do\n\t\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t\t--property admin --value $admin\n\t\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t\t--property trusted --value $tr\n\t\ti=$((i + 1))\n\tdone\n\twait_nm_sync c$((i - 1)) admin_nodemap\n\twait_nm_sync c$((i - 1)) trusted_nodemap\n}\n\ntest_16() {\n\tnodemap_version_check || return 0\n\tnodemap_test_setup 0\n\n\ttrap nodemap_test_cleanup EXIT\n\ttest_fops all_off\n\tnodemap_test_cleanup\n}\nrun_test 16 \"test nodemap all_off fileops\"\n\ntest_17() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tnodemap_clients_admin_trusted 0 1\n\ttest_fops trusted_noadmin 1\n\tnodemap_test_cleanup\n}\nrun_test 17 \"test nodemap trusted_noadmin fileops\"\n\ntest_18() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tnodemap_clients_admin_trusted 0 0\n\ttest_fops mapped_noadmin 1\n\tnodemap_test_cleanup\n}\nrun_test 18 \"test nodemap mapped_noadmin fileops\"\n\ntest_19() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tnodemap_clients_admin_trusted 1 1\n\ttest_fops trusted_admin 1\n\tnodemap_test_cleanup\n}\nrun_test 19 \"test nodemap trusted_admin fileops\"\n\ntest_20() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tnodemap_clients_admin_trusted 1 0\n\ttest_fops mapped_admin 1\n\tnodemap_test_cleanup\n}\nrun_test 20 \"test nodemap mapped_admin fileops\"\n\ntest_21() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tlocal x=1\n\tlocal i=0\n\tfor client in $clients; do\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property admin --value 0\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property trusted --value $x\n\t\tx=0\n\t\ti=$((i + 1))\n\tdone\n\twait_nm_sync c$((i - 1)) trusted_nodemap\n\n\ttest_fops mapped_trusted_noadmin\n\tnodemap_test_cleanup\n}\nrun_test 21 \"test nodemap mapped_trusted_noadmin fileops\"\n\ntest_22() {\n\tif $SHARED_KEY &&\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.55) ]; then\n\t\tskip \"Need MDS >= 2.11.55\"\n\tfi\n\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tlocal x=1\n\tlocal i=0\n\tfor client in $clients; do\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property admin --value 1\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property trusted --value $x\n\t\tx=0\n\t\ti=$((i + 1))\n\tdone\n\twait_nm_sync c$((i - 1)) trusted_nodemap\n\n\ttest_fops mapped_trusted_admin\n\tnodemap_test_cleanup\n}\nrun_test 22 \"test nodemap mapped_trusted_admin fileops\"\n\n# acl test directory needs to be initialized on a privileged client\nnodemap_acl_test_setup() {\n\tlocal admin=$(do_facet mgs $LCTL get_param -n \\\n\t\t      nodemap.c0.admin_nodemap)\n\tlocal trust=$(do_facet mgs $LCTL get_param -n \\\n\t\t      nodemap.c0.trusted_nodemap)\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property trusted --value 1\n\n\twait_nm_sync c0 admin_nodemap\n\twait_nm_sync c0 trusted_nodemap\n\n\tdo_node ${clients_arr[0]} rm -rf $DIR/$tdir\n\tnm_test_mkdir\n\tdo_node ${clients_arr[0]} chmod a+rwx $DIR/$tdir ||\n\t\terror unable to chmod a+rwx test dir $DIR/$tdir\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t--property admin --value $admin\n\tdo_facet mgs $LCTL nodemap_modify --name c0 \\\n\t\t--property trusted --value $trust\n\n\twait_nm_sync c0 trusted_nodemap\n}\n\n# returns 0 if the number of ACLs does not change on the second (mapped) client\n# after being set on the first client\nnodemap_acl_test() {\n\tlocal user=\"$1\"\n\tlocal set_client=\"$2\"\n\tlocal get_client=\"$3\"\n\tlocal check_setfacl=\"$4\"\n\tlocal setfacl_error=0\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal RUNAS_USER=\"$RUNAS_CMD -u $user\"\n\tlocal acl_count=0\n\tlocal acl_count_post=0\n\n\tnodemap_acl_test_setup\n\tsleep 5\n\n\tdo_node $set_client $RUNAS_USER touch $testfile\n\n\t# ACL masks aren't filtered by nodemap code, so we ignore them\n\tacl_count=$(do_node $get_client getfacl $testfile | grep -v mask |\n\t\twc -l)\n\tdo_node $set_client $RUNAS_USER setfacl -m $user:rwx $testfile ||\n\t\tsetfacl_error=1\n\n\t# if check setfacl is set to 1, then it's supposed to error\n\tif [ \"$check_setfacl\" == \"1\" ]; then\n\t\t[ \"$setfacl_error\" != \"1\" ] && return 1\n\t\treturn 0\n\tfi\n\t[ \"$setfacl_error\" == \"1\" ] && echo \"WARNING: unable to setfacl\"\n\n\tacl_count_post=$(do_node $get_client getfacl $testfile | grep -v mask |\n\t\twc -l)\n\t[ $acl_count -eq $acl_count_post ] && return 0\n\treturn 1\n}\n\ntest_23a() {\n\t[ $num_clients -lt 2 ] && skip \"Need 2 clients at least\" && return\n\tnodemap_version_check || return 0\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\t# 1 trusted cluster, 1 mapped cluster\n\tlocal unmapped_fs=$((IDBASE+0))\n\tlocal unmapped_c1=$((IDBASE+5))\n\tlocal mapped_fs=$((IDBASE+2))\n\tlocal mapped_c0=$((IDBASE+4))\n\tlocal mapped_c1=$((IDBASE+6))\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property trusted --value 1\n\n\tdo_facet mgs $LCTL nodemap_modify --name c1 --property admin --value 0\n\tdo_facet mgs $LCTL nodemap_modify --name c1 --property trusted --value 0\n\n\twait_nm_sync c1 trusted_nodemap\n\n\t# setfacl on trusted cluster to unmapped user, verify it's not seen\n\tnodemap_acl_test $unmapped_fs ${clients_arr[0]} ${clients_arr[1]} ||\n\t\terror \"acl count (1)\"\n\n\t# setfacl on trusted cluster to mapped user, verify it's seen\n\tnodemap_acl_test $mapped_fs ${clients_arr[0]} ${clients_arr[1]} &&\n\t\terror \"acl count (2)\"\n\n\t# setfacl on mapped cluster to mapped user, verify it's seen\n\tnodemap_acl_test $mapped_c1 ${clients_arr[1]} ${clients_arr[0]} &&\n\t\terror \"acl count (3)\"\n\n\t# setfacl on mapped cluster to unmapped user, verify error\n\tnodemap_acl_test $unmapped_fs ${clients_arr[1]} ${clients_arr[0]} 1 ||\n\t\terror \"acl count (4)\"\n\n\t# 2 mapped clusters\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin --value 0\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property trusted --value 0\n\n\twait_nm_sync c0 trusted_nodemap\n\n\t# setfacl to mapped user on c1, also mapped to c0, verify it's seen\n\tnodemap_acl_test $mapped_c1 ${clients_arr[1]} ${clients_arr[0]} &&\n\t\terror \"acl count (5)\"\n\n\t# setfacl to mapped user on c1, not mapped to c0, verify not seen\n\tnodemap_acl_test $unmapped_c1 ${clients_arr[1]} ${clients_arr[0]} ||\n\t\terror \"acl count (6)\"\n\n\tnodemap_test_cleanup\n}\nrun_test 23a \"test mapped regular ACLs\"\n\ntest_23b() { #LU-9929\n\t[ $num_clients -lt 2 ] && skip \"Need 2 clients at least\"\n\t[ \"$MGS_VERSION\" -lt $(version_code 2.10.53) ] &&\n\t\tskip \"Need MGS >= 2.10.53\"\n\n\texport SK_UNIQUE_NM=true\n\tnodemap_test_setup\n\ttrap nodemap_test_cleanup EXIT\n\n\tlocal testdir=$DIR/$tdir\n\tlocal fs_id=$((IDBASE+10))\n\tlocal unmapped_id\n\tlocal mapped_id\n\tlocal fs_user\n\n\tdo_facet mgs $LCTL nodemap_modify --name c0 --property admin --value 1\n\twait_nm_sync c0 admin_nodemap\n\tdo_facet mgs $LCTL nodemap_modify --name c1 --property admin --value 1\n\twait_nm_sync c1 admin_nodemap\n\tdo_facet mgs $LCTL nodemap_modify --name c1 --property trusted --value 1\n\twait_nm_sync c1 trusted_nodemap\n\n\t# Add idmap $ID0:$fs_id (500:60010)\n\tdo_facet mgs $LCTL nodemap_add_idmap --name c0 --idtype gid \\\n\t\t--idmap $ID0:$fs_id ||\n\t\terror \"add idmap $ID0:$fs_id to nodemap c0 failed\"\n\twait_nm_sync c0 idmap\n\n\t# set/getfacl default acl on client 1 (unmapped gid=500)\n\tdo_node ${clients_arr[0]} rm -rf $testdir\n\tdo_node ${clients_arr[0]} mkdir -p $testdir\n\t# Here, USER0=$(getent passwd | grep :$ID0:$ID0: | cut -d: -f1)\n\tdo_node ${clients_arr[0]} setfacl -R -d -m group:$USER0:rwx $testdir ||\n\t\terror \"setfacl $testdir on ${clients_arr[0]} failed\"\n\tunmapped_id=$(do_node ${clients_arr[0]} getfacl $testdir |\n\t\t\tgrep -E \"default:group:.*:rwx\" | awk -F: '{print $3}')\n\t[ \"$unmapped_id\" = \"$USER0\" ] ||\n\t\terror \"gid=$ID0 was not unmapped correctly on ${clients_arr[0]}\"\n\n\t# getfacl default acl on client 2 (mapped gid=60010)\n\tmapped_id=$(do_node ${clients_arr[1]} getfacl $testdir |\n\t\t\tgrep -E \"default:group:.*:rwx\" | awk -F: '{print $3}')\n\tfs_user=$(do_node ${clients_arr[1]} getent passwd |\n\t\t\tgrep :$fs_id:$fs_id: | cut -d: -f1)\n\t[ -z \"$fs_user\" ] && fs_user=$fs_id\n\t[ $mapped_id -eq $fs_id -o \"$mapped_id\" = \"$fs_user\" ] ||\n\t\terror \"Should return gid=$fs_id or $fs_user on client2\"\n\n\trm -rf $testdir\n\tnodemap_test_cleanup\n\texport SK_UNIQUE_NM=false\n}\nrun_test 23b \"test mapped default ACLs\"\n\ntest_24() {\n\tnodemap_test_setup\n\n\ttrap nodemap_test_cleanup EXIT\n\tdo_nodes $(comma_list $(all_server_nodes)) $LCTL get_param -R nodemap\n\n\tnodemap_test_cleanup\n}\nrun_test 24 \"check nodemap proc files for LBUGs and Oopses\"\n\ntest_25() {\n\tlocal tmpfile=$(mktemp)\n\tlocal tmpfile2=$(mktemp)\n\tlocal tmpfile3=$(mktemp)\n\tlocal tmpfile4=$(mktemp)\n\tlocal subdir=c0dir\n\tlocal client\n\n\tnodemap_version_check || return 0\n\n\t# stop clients for this test\n\tzconf_umount_clients $CLIENTS $MOUNT ||\n\t    error \"unable to umount clients $CLIENTS\"\n\n\texport SK_UNIQUE_NM=true\n\tnodemap_test_setup\n\n\t# enable trusted/admin for setquota call in cleanup_and_setup_lustre()\n\ti=0\n\tfor client in $clients; do\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property admin --value 1\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t--property trusted --value 1\n\t\t((i++))\n\tdone\n\twait_nm_sync c$((i - 1)) trusted_nodemap\n\n\ttrap nodemap_test_cleanup EXIT\n\n\t# create a new, empty nodemap, and add fileset info to it\n\tdo_facet mgs $LCTL nodemap_add test25 ||\n\t\terror \"unable to create nodemap $testname\"\n\tdo_facet mgs $LCTL set_param -P nodemap.$testname.fileset=/$subdir ||\n\t\terror \"unable to add fileset info to nodemap test25\"\n\n\twait_nm_sync test25 id\n\n\tdo_facet mgs $LCTL nodemap_info > $tmpfile\n\tdo_facet mds $LCTL nodemap_info > $tmpfile2\n\n\tif ! $SHARED_KEY; then\n\t\t# will conflict with SK's nodemaps\n\t\tcleanup_and_setup_lustre\n\tfi\n\t# stop clients for this test\n\tzconf_umount_clients $CLIENTS $MOUNT ||\n\t    error \"unable to umount clients $CLIENTS\"\n\n\tdo_facet mgs $LCTL nodemap_info > $tmpfile3\n\tdiff -q $tmpfile3 $tmpfile >& /dev/null ||\n\t\terror \"nodemap_info diff on MGS after remount\"\n\n\tdo_facet mds $LCTL nodemap_info > $tmpfile4\n\tdiff -q $tmpfile4 $tmpfile2 >& /dev/null ||\n\t\terror \"nodemap_info diff on MDS after remount\"\n\n\t# cleanup nodemap\n\tdo_facet mgs $LCTL nodemap_del test25 ||\n\t    error \"cannot delete nodemap test25 from config\"\n\tnodemap_test_cleanup\n\t# restart clients previously stopped\n\tzconf_mount_clients $CLIENTS $MOUNT ||\n\t    error \"unable to mount clients $CLIENTS\"\n\n\trm -f $tmpfile $tmpfile2\n\texport SK_UNIQUE_NM=false\n}\nrun_test 25 \"test save and reload nodemap config\"\n\ntest_26() {\n\tnodemap_version_check || return 0\n\n\tlocal large_i=32000\n\n\tdo_facet mgs \"seq -f 'c%g' $large_i | xargs -n1 $LCTL nodemap_add\"\n\twait_nm_sync c$large_i admin_nodemap\n\n\tdo_facet mgs \"seq -f 'c%g' $large_i | xargs -n1 $LCTL nodemap_del\"\n\twait_nm_sync c$large_i admin_nodemap\n}\nrun_test 26 \"test transferring very large nodemap\"\n\nnodemap_exercise_fileset() {\n\tlocal nm=\"$1\"\n\tlocal loop=0\n\n\t# setup\n\tif [ \"$nm\" == \"default\" ]; then\n\t\tdo_facet mgs $LCTL nodemap_activate 1\n\t\twait_nm_sync active\n\telse\n\t\tnodemap_test_setup\n\tfi\n\tif $SHARED_KEY; then\n\t\texport SK_UNIQUE_NM=true\n\telse\n\t\t# will conflict with SK's nodemaps\n\t\ttrap \"fileset_test_cleanup $nm\" EXIT\n\tfi\n\tfileset_test_setup \"$nm\"\n\n\t# add fileset info to $nm nodemap\n\tif ! combined_mgs_mds; then\n\t    do_facet mgs $LCTL set_param nodemap.${nm}.fileset=/$subdir ||\n\t\terror \"unable to add fileset info to $nm nodemap on MGS\"\n\tfi\n\tdo_facet mgs $LCTL set_param -P nodemap.${nm}.fileset=/$subdir ||\n\t       error \"unable to add fileset info to $nm nodemap for servers\"\n\twait_nm_sync $nm fileset \"nodemap.${nm}.fileset=/$subdir\"\n\n\t# re-mount client\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount client ${clients_arr[0]}\"\n\t# set some generic fileset to trigger SSK code\n\texport FILESET=/\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"unable to remount client ${clients_arr[0]}\"\n\tunset FILESET\n\n\t# test mount point content\n\tdo_node ${clients_arr[0]} test -f $MOUNT/this_is_$subdir ||\n\t\terror \"fileset not taken into account\"\n\n\t# re-mount client with sub-subdir\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount client ${clients_arr[0]}\"\n\texport FILESET=/$subsubdir\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"unable to remount client ${clients_arr[0]}\"\n\tunset FILESET\n\n\t# test mount point content\n\tdo_node ${clients_arr[0]} test -f $MOUNT/this_is_$subsubdir ||\n\t\terror \"subdir of fileset not taken into account\"\n\n\t# remove fileset info from nodemap\n\tdo_facet mgs $LCTL nodemap_set_fileset --name $nm --fileset clear ||\n\t\terror \"unable to delete fileset info on $nm nodemap\"\n\twait_update_facet mgs \"$LCTL get_param nodemap.${nm}.fileset\" \\\n\t\t\t  \"nodemap.${nm}.fileset=\" ||\n\t\terror \"fileset info still not cleared on $nm nodemap\"\n\tdo_facet mgs $LCTL set_param -P nodemap.${nm}.fileset=clear ||\n\t\terror \"unable to reset fileset info on $nm nodemap\"\n\twait_nm_sync $nm fileset \"nodemap.${nm}.fileset=\"\n\n\t# re-mount client\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount client ${clients_arr[0]}\"\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"unable to remount client ${clients_arr[0]}\"\n\n\t# test mount point content\n\tif ! $(do_node ${clients_arr[0]} test -d $MOUNT/$subdir); then\n\t\tls $MOUNT\n\t\terror \"fileset not cleared on $nm nodemap\"\n\tfi\n\n\t# back to non-nodemap setup\n\tif $SHARED_KEY; then\n\t\texport SK_UNIQUE_NM=false\n\t\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\t\terror \"unable to umount client ${clients_arr[0]}\"\n\tfi\n\tfileset_test_cleanup \"$nm\"\n\tif [ \"$nm\" == \"default\" ]; then\n\t\tdo_facet mgs $LCTL nodemap_activate 0\n\t\twait_nm_sync active 0\n\t\ttrap 0\n\t\texport SK_UNIQUE_NM=false\n\telse\n\t\tnodemap_test_cleanup\n\tfi\n\tif $SHARED_KEY; then\n\t\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\t\terror \"unable to remount client ${clients_arr[0]}\"\n\tfi\n}\n\ntest_27a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS >= 2.11.50\"\n\n\tfor nm in \"default\" \"c0\"; do\n\t\tlocal subdir=\"subdir_${nm}\"\n\t\tlocal subsubdir=\"subsubdir_${nm}\"\n\n\t\tif [ \"$nm\" == \"default\" ] && [ \"$SHARED_KEY\" == \"true\" ]; then\n\t\t\techo \"Skipping nodemap $nm with SHARED_KEY\";\n\t\t\tcontinue;\n\t\tfi\n\n\t\techo \"Exercising fileset for nodemap $nm\"\n\t\tnodemap_exercise_fileset \"$nm\"\n\tdone\n}\nrun_test 27a \"test fileset in various nodemaps\"\n\ntest_27b() { #LU-10703\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS >= 2.11.50\"\n\t[[ $MDSCOUNT -lt 2 ]] && skip \"needs >= 2 MDTs\"\n\n\tnodemap_test_setup\n\ttrap nodemap_test_cleanup EXIT\n\n\t# Add the nodemaps and set their filesets\n\tfor i in $(seq 1 $MDSCOUNT); do\n\t\tdo_facet mgs $LCTL nodemap_del nm$i 2>/dev/null\n\t\tdo_facet mgs $LCTL nodemap_add nm$i ||\n\t\t\terror \"add nodemap nm$i failed\"\n\t\twait_nm_sync nm$i \"\" \"\" \"-N\"\n\n\t\tif ! combined_mgs_mds; then\n\t\t\tdo_facet mgs \\\n\t\t\t\t$LCTL set_param nodemap.nm$i.fileset=/dir$i ||\n\t\t\t\terror \"set nm$i.fileset=/dir$i failed on MGS\"\n\t\tfi\n\t\tdo_facet mgs $LCTL set_param -P nodemap.nm$i.fileset=/dir$i ||\n\t\t\terror \"set nm$i.fileset=/dir$i failed on servers\"\n\t\twait_nm_sync nm$i fileset \"nodemap.nm$i.fileset=/dir$i\"\n\tdone\n\n\t# Check if all the filesets are correct\n\tfor i in $(seq 1 $MDSCOUNT); do\n\t\tfileset=$(do_facet mds$i \\\n\t\t\t  $LCTL get_param -n nodemap.nm$i.fileset)\n\t\t[ \"$fileset\" = \"/dir$i\" ] ||\n\t\t\terror \"nm$i.fileset $fileset != /dir$i on mds$i\"\n\t\tdo_facet mgs $LCTL nodemap_del nm$i ||\n\t\t\terror \"delete nodemap nm$i failed\"\n\tdone\n\n\tnodemap_test_cleanup\n}\nrun_test 27b \"The new nodemap won't clear the old nodemap's fileset\"\n\ntest_28() {\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\" && return\n\tfi\n\tmkdir -p $DIR/$tdir || error \"mkdir failed\"\n\ttouch $DIR/$tdir/$tdir.out || error \"touch failed\"\n\tif [ ! -f $DIR/$tdir/$tdir.out ]; then\n\t\terror \"read before rotation failed\"\n\tfi\n\t# store top key identity to ensure rotation has occurred\n\tSK_IDENTITY_OLD=$(lctl get_param *.*.*srpc* | grep \"expire\" |\n\t\thead -1 | awk '{print $15}' | cut -c1-8)\n\tdo_facet $SINGLEMDS lfs flushctx ||\n\t\t error \"could not run flushctx on $SINGLEMDS\"\n\tsleep 5\n\tlfs flushctx || error \"could not run flushctx on client\"\n\tsleep 5\n\t# verify new key is in place\n\tSK_IDENTITY_NEW=$(lctl get_param *.*.*srpc* | grep \"expire\" |\n\t\thead -1 | awk '{print $15}' | cut -c1-8)\n\tif [ $SK_IDENTITY_OLD == $SK_IDENTITY_NEW ]; then\n\t\terror \"key did not rotate correctly\"\n\tfi\n\tif [ ! -f $DIR/$tdir/$tdir.out ]; then\n\t\terror \"read after rotation failed\"\n\tfi\n}\nrun_test 28 \"check shared key rotation method\"\n\ntest_29() {\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\" && return\n\tfi\n\tif [ $SK_FLAVOR != \"ski\" ] && [ $SK_FLAVOR != \"skpi\" ]; then\n\t\tskip \"test only valid if integrity is active\"\n\tfi\n\trm -r $DIR/$tdir\n\tmkdir $DIR/$tdir || error \"mkdir\"\n\ttouch $DIR/$tdir/$tfile || error \"touch\"\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount clients\"\n\tdo_node ${clients_arr[0]} \"keyctl show |\n\t\tawk '/lustre/ { print \\\\\\$1 }' | xargs -IX keyctl unlink X\"\n\tOLD_SK_PATH=$SK_PATH\n\texport SK_PATH=/dev/null\n\tif zconf_mount_clients ${clients_arr[0]} $MOUNT; then\n\t\texport SK_PATH=$OLD_SK_PATH\n\t\tdo_node ${clients_arr[0]} \"ls $DIR/$tdir/$tfile\"\n\t\tif [ $? -eq 0 ]; then\n\t\t\terror \"able to mount and read without key\"\n\t\telse\n\t\t\terror \"able to mount without key\"\n\t\tfi\n\telse\n\t\texport SK_PATH=$OLD_SK_PATH\n\t\tdo_node ${clients_arr[0]} \"keyctl show |\n\t\t\tawk '/lustre/ { print \\\\\\$1 }' |\n\t\t\txargs -IX keyctl unlink X\"\n\tfi\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to mount clients\"\n}\nrun_test 29 \"check for missing shared key\"\n\ntest_30() {\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\" && return\n\tfi\n\tif [ $SK_FLAVOR != \"ski\" ] && [ $SK_FLAVOR != \"skpi\" ]; then\n\t\tskip \"test only valid if integrity is active\"\n\tfi\n\tmkdir -p $DIR/$tdir || error \"mkdir failed\"\n\ttouch $DIR/$tdir/$tdir.out || error \"touch failed\"\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount clients\"\n\t# unload keys from ring\n\tdo_node ${clients_arr[0]} \"keyctl show |\n\t\tawk '/lustre/ { print \\\\\\$1 }' | xargs -IX keyctl unlink X\"\n\t# generate key with bogus filesystem name\n\tdo_node ${clients_arr[0]} \"lgss_sk -w $SK_PATH/$FSNAME-bogus.key \\\n\t\t-f $FSNAME.bogus -t client -d /dev/urandom\" ||\n\t\terror \"lgss_sk failed (1)\"\n\tdo_facet $SINGLEMDS lfs flushctx || error \"could not run flushctx\"\n\tOLD_SK_PATH=$SK_PATH\n\texport SK_PATH=$SK_PATH/$FSNAME-bogus.key\n\tif zconf_mount_clients ${clients_arr[0]} $MOUNT; then\n\t\tSK_PATH=$OLD_SK_PATH\n\t\tdo_node ${clients_arr[0]} \"ls $DIR/$tdir/$tdir.out\"\n\t\tif [ $? -eq 0 ]; then\n\t\t\terror \"mount and read file with invalid key\"\n\t\telse\n\t\t\terror \"mount with invalid key\"\n\t\tfi\n\tfi\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to umount clients\"\n\t# unload keys from ring\n\tdo_node ${clients_arr[0]} \"keyctl show |\n\t\tawk '/lustre/ { print \\\\\\$1 }' | xargs -IX keyctl unlink X\"\n\trm -f $SK_PATH\n\tSK_PATH=$OLD_SK_PATH\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"unable to mount clients\"\n}\nrun_test 30 \"check for invalid shared key\"\n\nbasic_ios() {\n\tlocal flvr=$1\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $flvr\"\n\ttouch $DIR/$tdir/f0 || error \"touch $flvr\"\n\tls $DIR/$tdir || error \"ls $flvr\"\n\tdd if=/dev/zero of=$DIR/$tdir/f0 conv=fsync bs=1M count=10 \\\n\t\t>& /dev/null || error \"dd $flvr\"\n\trm -f $DIR/$tdir/f0 || error \"rm $flvr\"\n\trmdir $DIR/$tdir || error \"rmdir $flvr\"\n\n\tsync ; sync\n\techo 3 > /proc/sys/vm/drop_caches\n}\n\ntest_30b() {\n\tlocal save_flvr=$SK_FLAVOR\n\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\"\n\tfi\n\n\tstack_trap restore_to_default_flavor EXIT\n\n\tfor flvr in skn ska ski skpi; do\n\t\t# set flavor\n\t\tSK_FLAVOR=$flvr\n\t\trestore_to_default_flavor || error \"cannot set $flvr flavor\"\n\t\tSK_FLAVOR=$save_flvr\n\n\t\tbasic_ios $flvr\n\tdone\n}\nrun_test 30b \"basic test of all different SSK flavors\"\n\ncleanup_31() {\n\t# unmount client\n\tzconf_umount $HOSTNAME $MOUNT || error \"unable to umount client\"\n\n\t# remove ${NETTYPE}999 network on all nodes\n\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t \"$LNETCTL net del --net ${NETTYPE}999 && \\\n\t\t  $LNETCTL lnet unconfigure 2>/dev/null || true\"\n\n\t# necessary to do writeconf in order to de-register\n\t# @${NETTYPE}999 nid for targets\n\tKZPOOL=$KEEP_ZPOOL\n\texport KEEP_ZPOOL=\"true\"\n\tstopall\n\texport SK_MOUNTED=false\n\twriteconf_all\n\tsetupall || echo 1\n\texport KEEP_ZPOOL=\"$KZPOOL\"\n}\n\ntest_31() {\n\tlocal nid=$(lctl list_nids | grep ${NETTYPE} | head -n1)\n\tlocal addr=${nid%@*}\n\tlocal net=${nid#*@}\n\n\texport LNETCTL=$(which lnetctl 2> /dev/null)\n\n\t[ -z \"$LNETCTL\" ] && skip \"without lnetctl support.\" && return\n\tlocal_mode && skip \"in local mode.\"\n\n\tstack_trap cleanup_31 EXIT\n\n\t# umount client\n\tif [ \"$MOUNT_2\" ] && $(grep -q $MOUNT2' ' /proc/mounts); then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif $(grep -q $MOUNT' ' /proc/mounts); then\n\t\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\n\t# check exports on servers are empty for client\n\tdo_facet mgs \"lctl get_param -n *.MGS*.exports.'$nid'.uuid 2>/dev/null |\n\t\t      grep -q -\" && error \"export on MGS should be empty\"\n\tdo_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \\\n\t\t \"lctl get_param -n *.${FSNAME}*.exports.'$nid'.uuid \\\n\t\t  2>/dev/null | grep -q -\" &&\n\t\terror \"export on servers should be empty\"\n\n\t# add network ${NETTYPE}999 on all nodes\n\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t \"$LNETCTL lnet configure && $LNETCTL net add --if \\\n\t\t  \\$($LNETCTL net show --net $net | awk 'BEGIN{inf=0} \\\n\t\t  {if (inf==1) print \\$2; fi; inf=0} /interfaces/{inf=1}') \\\n\t\t  --net ${NETTYPE}999\" ||\n\t\terror \"unable to configure NID ${NETTYPE}999\"\n\n\t# necessary to do writeconf in order to register\n\t# new @${NETTYPE}999 nid for targets\n\tKZPOOL=$KEEP_ZPOOL\n\texport KEEP_ZPOOL=\"true\"\n\tstopall\n\texport SK_MOUNTED=false\n\twriteconf_all\n\tsetupall server_only || echo 1\n\texport KEEP_ZPOOL=\"$KZPOOL\"\n\n\t# backup MGSNID\n\tlocal mgsnid_orig=$MGSNID\n\t# compute new MGSNID\n\tMGSNID=$(do_facet mgs \"$LCTL list_nids | grep ${NETTYPE}999\")\n\n\t# on client, turn LNet Dynamic Discovery on\n\tlnetctl set discovery 1\n\n\t# mount client with -o network=${NETTYPE}999 option:\n\t# should fail because of LNet Dynamic Discovery\n\tmount_client $MOUNT ${MOUNT_OPTS},network=${NETTYPE}999 &&\n\t\terror \"client mount with '-o network' option should be refused\"\n\n\t# on client, reconfigure LNet and turn LNet Dynamic Discovery off\n\t$LNETCTL net del --net ${NETTYPE}999 && lnetctl lnet unconfigure\n\tlustre_rmmod\n\tmodprobe lnet\n\tlnetctl set discovery 0\n\tmodprobe ptlrpc\n\t$LNETCTL lnet configure && $LNETCTL net add --if \\\n\t  $($LNETCTL net show --net $net | awk 'BEGIN{inf=0} \\\n\t  {if (inf==1) print $2; fi; inf=0} /interfaces/{inf=1}') \\\n\t  --net ${NETTYPE}999 ||\n\terror \"unable to configure NID ${NETTYPE}999 on client\"\n\n\t# mount client with -o network=${NETTYPE}999 option\n\tmount_client $MOUNT ${MOUNT_OPTS},network=${NETTYPE}999 ||\n\t\terror \"unable to remount client\"\n\n\t# restore MGSNID\n\tMGSNID=$mgsnid_orig\n\n\t# check export on MGS\n\tdo_facet mgs \"lctl get_param -n *.MGS*.exports.'$nid'.uuid 2>/dev/null |\n\t\t      grep -q -\"\n\t[ $? -ne 0 ] ||\terror \"export for $nid on MGS should not exist\"\n\n\tdo_facet mgs \\\n\t\t\"lctl get_param -n *.MGS*.exports.'${addr}@${NETTYPE}999'.uuid \\\n\t\t 2>/dev/null | grep -q -\"\n\t[ $? -eq 0 ] ||\n\t\terror \"export for ${addr}@${NETTYPE}999 on MGS should exist\"\n\n\t# check {mdc,osc} imports\n\tlctl get_param mdc.${FSNAME}-*.import | grep current_connection |\n\t    grep -q ${NETTYPE}999\n\t[ $? -eq 0 ] ||\n\t\terror \"import for mdc should use ${addr}@${NETTYPE}999\"\n\tlctl get_param osc.${FSNAME}-*.import | grep current_connection |\n\t    grep -q ${NETTYPE}999\n\t[ $? -eq 0 ] ||\n\t\terror \"import for osc should use ${addr}@${NETTYPE}999\"\n}\nrun_test 31 \"client mount option '-o network'\"\n\ncleanup_32() {\n\t# umount client\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT\n\n\t# disable sk flavor enforcement on MGS\n\tset_rule _mgs any any null\n\n\t# stop gss daemon on MGS\n\tif ! combined_mgs_mds ; then\n\t\tsend_sigint $mgs_HOST lsvcgssd\n\tfi\n\n\t# re-mount client\n\tMOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)\n\tmountcli\n\n\trestore_to_default_flavor\n}\n\ntest_32() {\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\"\n\tfi\n\n\tstack_trap cleanup_32 EXIT\n\n\t# restore to default null flavor\n\tsave_flvr=$SK_FLAVOR\n\tSK_FLAVOR=null\n\trestore_to_default_flavor || error \"cannot set null flavor\"\n\tSK_FLAVOR=$save_flvr\n\n\t# umount client\n\tif [ \"$MOUNT_2\" ] && $(grep -q $MOUNT2' ' /proc/mounts); then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif $(grep -q $MOUNT' ' /proc/mounts); then\n\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\n\t# start gss daemon on MGS\n\tif combined_mgs_mds ; then\n\t\tsend_sigint $mds_HOST lsvcgssd\n\tfi\n\tstart_gss_daemons $mgs_HOST \"$LSVCGSSD -vvv -s -g\"\n\n\t# add mgs key type and MGS NIDs in key on MGS\n\tdo_nodes $mgs_HOST \"lgss_sk -t mgs,server -g $MGSNID -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not modify keyfile on MGS\"\n\n\t# load modified key file on MGS\n\tdo_nodes $mgs_HOST \"lgss_sk -l $SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not load keyfile on MGS\"\n\n\t# add MGS NIDs in key on client\n\tdo_nodes ${clients_arr[0]} \"lgss_sk -g $MGSNID -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not modify keyfile on MGS\"\n\n\t# set perms for per-nodemap keys else permission denied\n\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t \"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\n\t# re-mount client with mgssec=skn\n\tsave_opts=$MOUNT_OPTS\n\tif [ -z \"$MOUNT_OPTS\" ]; then\n\t\tMOUNT_OPTS=\"-o mgssec=skn\"\n\telse\n\t\tMOUNT_OPTS=\"$MOUNT_OPTS,mgssec=skn\"\n\tfi\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"mount ${clients_arr[0]} with mgssec=skn failed\"\n\tMOUNT_OPTS=$save_opts\n\n\t# umount client\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT ||\n\t\terror \"umount ${clients_arr[0]} failed\"\n\n\t# enforce ska flavor on MGS\n\tset_rule _mgs any any ska\n\n\t# re-mount client without mgssec\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS &&\n\t\terror \"mount ${clients_arr[0]} without mgssec should fail\"\n\n\t# re-mount client with mgssec=skn\n\tsave_opts=$MOUNT_OPTS\n\tif [ -z \"$MOUNT_OPTS\" ]; then\n\t\tMOUNT_OPTS=\"-o mgssec=skn\"\n\telse\n\t\tMOUNT_OPTS=\"$MOUNT_OPTS,mgssec=skn\"\n\tfi\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS &&\n\t\terror \"mount ${clients_arr[0]} with mgssec=skn should fail\"\n\tMOUNT_OPTS=$save_opts\n\n\t# re-mount client with mgssec=ska\n\tsave_opts=$MOUNT_OPTS\n\tif [ -z \"$MOUNT_OPTS\" ]; then\n\t\tMOUNT_OPTS=\"-o mgssec=ska\"\n\telse\n\t\tMOUNT_OPTS=\"$MOUNT_OPTS,mgssec=ska\"\n\tfi\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"mount ${clients_arr[0]} with mgssec=ska failed\"\n\tMOUNT_OPTS=$save_opts\n\n\texit 0\n}\nrun_test 32 \"check for mgssec\"\n\ncleanup_33() {\n\t# disable sk flavor enforcement\n\tset_rule $FSNAME any cli2mdt null\n\twait_flavor cli2mdt null\n\n\t# umount client\n\tzconf_umount_clients ${clients_arr[0]} $MOUNT\n\n\t# stop gss daemon on MGS\n\tif ! combined_mgs_mds ; then\n\t\tsend_sigint $mgs_HOST lsvcgssd\n\tfi\n\n\t# re-mount client\n\tMOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)\n\tmountcli\n\n\trestore_to_default_flavor\n}\n\ntest_33() {\n\tif ! $SHARED_KEY; then\n\t\tskip \"need shared key feature for this test\"\n\tfi\n\n\tstack_trap cleanup_33 EXIT\n\n\t# restore to default null flavor\n\tsave_flvr=$SK_FLAVOR\n\tSK_FLAVOR=null\n\trestore_to_default_flavor || error \"cannot set null flavor\"\n\tSK_FLAVOR=$save_flvr\n\n\t# umount client\n\tif [ \"$MOUNT_2\" ] && $(grep -q $MOUNT2' ' /proc/mounts); then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif $(grep -q $MOUNT' ' /proc/mounts); then\n\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\n\t# start gss daemon on MGS\n\tif combined_mgs_mds ; then\n\t\tsend_sigint $mds_HOST lsvcgssd\n\tfi\n\tstart_gss_daemons $mgs_HOST \"$LSVCGSSD -vvv -s -g\"\n\n\t# add mgs key type and MGS NIDs in key on MGS\n\tdo_nodes $mgs_HOST \"lgss_sk -t mgs,server -g $MGSNID -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not modify keyfile on MGS\"\n\n\t# load modified key file on MGS\n\tdo_nodes $mgs_HOST \"lgss_sk -l $SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not load keyfile on MGS\"\n\n\t# add MGS NIDs in key on client\n\tdo_nodes ${clients_arr[0]} \"lgss_sk -g $MGSNID -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\" ||\n\t\terror \"could not modify keyfile on MGS\"\n\n\t# set perms for per-nodemap keys else permission denied\n\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t \"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\n\t# re-mount client with mgssec=skn\n\tsave_opts=$MOUNT_OPTS\n\tif [ -z \"$MOUNT_OPTS\" ]; then\n\t\tMOUNT_OPTS=\"-o mgssec=skn\"\n\telse\n\t\tMOUNT_OPTS=\"$MOUNT_OPTS,mgssec=skn\"\n\tfi\n\tzconf_mount_clients ${clients_arr[0]} $MOUNT $MOUNT_OPTS ||\n\t\terror \"mount ${clients_arr[0]} with mgssec=skn failed\"\n\tMOUNT_OPTS=$save_opts\n\n\t# enforce ska flavor for cli2mdt\n\tset_rule $FSNAME any cli2mdt ska\n\twait_flavor cli2mdt ska\n\n\t# check error message\n\t$LCTL dk | grep \"faked source\" &&\n\t\terror \"MGS connection srpc flags incorrect\"\n\n\texit 0\n}\nrun_test 33 \"correct srpc flags for MGS connection\"\n\ncleanup_34_deny() {\n\t# restore deny_unknown\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t\t   --property deny_unknown --value $denydefault\n\tif [ $? -ne 0 ]; then\n\t\terror_noexit \"cannot reset deny_unknown on default nodemap\"\n\t\treturn\n\tfi\n\n\twait_nm_sync default deny_unknown\n}\n\ntest_34() {\n\tlocal denynew\n\tlocal activedefault\n\n\t[ $MGS_VERSION -lt $(version_code 2.12.51) ] &&\n\t\tskip \"deny_unknown on default nm not supported before 2.12.51\"\n\n\tactivedefault=$(do_facet mgs $LCTL get_param -n nodemap.active)\n\n\tif [[ \"$activedefault\" != \"1\" ]]; then\n\t\tdo_facet mgs $LCTL nodemap_activate 1\n\t\twait_nm_sync active\n\t\tstack_trap cleanup_active EXIT\n\tfi\n\n\tdenydefault=$(do_facet mgs $LCTL get_param -n \\\n\t\t      nodemap.default.deny_unknown)\n\t[ -z \"$denydefault\" ] &&\n\t\terror \"cannot get deny_unknown on default nodemap\"\n\tif [ \"$denydefault\" -eq 0 ]; then\n\t\tdenynew=1;\n\telse\n\t\tdenynew=0;\n\tfi\n\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t\t--property deny_unknown --value $denynew ||\n\t\terror \"cannot set deny_unknown on default nodemap\"\n\n\t[ \"$(do_facet mgs $LCTL get_param -n nodemap.default.deny_unknown)\" \\\n\t\t\t-eq $denynew ] ||\n\t\terror \"setting deny_unknown on default nodemap did not work\"\n\n\tstack_trap cleanup_34_deny EXIT\n\n\twait_nm_sync default deny_unknown\n}\nrun_test 34 \"deny_unknown on default nodemap\"\n\ntest_35() {\n\t[ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.13.50) ] ||\n\t\tskip \"Need MDS >= 2.13.50\"\n\n\t# activate changelogs\n\tchangelog_register || error \"changelog_register failed\"\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User $cl_user not found in changelog_users\"\n\tchangelog_chmask ALL\n\n\t# do some IOs\n\tmkdir $DIR/$tdir || error \"failed to mkdir $tdir\"\n\ttouch $DIR/$tdir/$tfile || error \"failed to touch $tfile\"\n\n\t# access changelogs with root\n\tchangelog_dump || error \"failed to dump changelogs\"\n\tchangelog_clear 0 || error \"failed to clear changelogs\"\n\n\t# put clients in non-admin nodemap\n\tnodemap_test_setup\n\tstack_trap nodemap_test_cleanup EXIT\n\tfor i in $(seq 0 $((num_clients-1))); do\n\t\tdo_facet mgs $LCTL nodemap_modify --name c${i} \\\n\t\t\t --property admin --value 0\n\tdone\n\tfor i in $(seq 0 $((num_clients-1))); do\n\t\twait_nm_sync c${i} admin_nodemap\n\tdone\n\n\t# access with mapped root\n\tchangelog_dump && error \"dump changelogs should have failed\"\n\tchangelog_clear 0 && error \"clear changelogs should have failed\"\n\n\texit 0\n}\nrun_test 35 \"Check permissions when accessing changelogs\"\n\nsetup_for_enc_tests() {\n\t# remount client with test_dummy_encryption option\n\tif is_mounted $MOUNT; then\n\t\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\tmount_client $MOUNT ${MOUNT_OPTS},test_dummy_encryption ||\n\t\terror \"mount with '-o test_dummy_encryption' failed\"\n\n\t# this directory will be encrypted, because of dummy mode\n\tmkdir $DIR/$tdir\n}\n\ncleanup_for_enc_tests() {\n\t# remount client normally\n\tif is_mounted $MOUNT; then\n\t\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\tmount_client $MOUNT ${MOUNT_OPTS} ||\n\t\terror \"remount failed\"\n\n\tif is_mounted $MOUNT2; then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif [ \"$MOUNT_2\" ]; then\n\t\tmount_client $MOUNT2 ${MOUNT_OPTS} ||\n\t\t\terror \"remount failed\"\n\tfi\n}\n\ncleanup_nodemap_after_enc_tests() {\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t--property forbid_encryption --value 1\n\twait_nm_sync default forbid_encryption\n\tdo_facet mgs $LCTL nodemap_activate 0\n\twait_nm_sync active\n}\n\ntest_36() {\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\n\t# first make sure it is possible to enable encryption\n\t# when nodemap is not active\n\tsetup_for_enc_tests\n\trmdir $DIR/$tdir\n\tumount_client $MOUNT || error \"umount $MOUNT failed (1)\"\n\n\t# then activate nodemap, and retry\n\t# should succeed as encryption is not forbidden on default nodemap\n\t# by default\n\tstack_trap cleanup_nodemap_after_enc_tests EXIT\n\tdo_facet mgs $LCTL nodemap_activate 1\n\twait_nm_sync active\n\tforbid=$(do_facet mgs lctl get_param -n nodemap.default.forbid_encryption)\n\t[ $forbid -eq 0 ] || error \"wrong default value for forbid_encryption\"\n\tmount_client $MOUNT ${MOUNT_OPTS},test_dummy_encryption ||\n\t\terror \"mount '-o test_dummy_encryption' failed with default\"\n\tumount_client $MOUNT || error \"umount $MOUNT failed (2)\"\n\n\t# then forbid encryption, and retry\n\tdo_facet mgs $LCTL nodemap_modify --name default \\\n\t\t--property forbid_encryption --value 1\n\twait_nm_sync default forbid_encryption\n\tmount_client $MOUNT ${MOUNT_OPTS},test_dummy_encryption &&\n\t\terror \"mount '-o test_dummy_encryption' should have failed\"\n\treturn 0\n}\nrun_test 36 \"control if clients can use encryption\"\n\ntest_37() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal objdump=$TMP/objdump\n\tlocal objid\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\t[ \"$ost1_FSTYPE\" = ldiskfs ] || skip \"ldiskfs only test (using debugfs)\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# write a few bytes in file\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=$tmpfile of=$testfile bs=4 count=1 conv=fsync\n\tdo_facet ost1 \"sync; sync\"\n\n\t# check that content on ost is encrypted\n\tobjid=$($LFS getstripe $testfile | awk '/obdidx/{getline; print $2}')\n\tdo_facet ost1 \"$DEBUGFS -c -R 'cat O/0/d$(($objid % 32))/$objid' \\\n\t\t $(ostdevname 1)\" > $objdump\n\tcmp -s $objdump $tmpfile &&\n\t\terror \"file $testfile is not encrypted on ost\"\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl ${tmpfile} ${testfile} ||\n\t\terror \"file $testfile is corrupted in memory\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl ${tmpfile} ${testfile} ||\n\t\terror \"file $testfile is corrupted on server\"\n\n\trm -f $tmpfile $objdump\n}\nrun_test 37 \"simple encrypted file\"\n\ntest_38() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal objid\n\tlocal blksz\n\tlocal srvsz=0\n\tlocal filesz\n\tlocal bsize\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# get block size on ost\n\tblksz=$($LCTL get_param osc.$FSNAME*.import |\n\t\tawk '/grant_block_size:/ { print $2; exit; }')\n\t# write a few bytes in file at offset $blksz\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$blksz \\\n\t\toflag=seek_bytes conv=fsync\n\n\t# check that in-memory representation of file is correct\n\tbsize=$(stat --format=%B $testfile)\n\tfilesz=$(stat --format=%b $testfile)\n\tfilesz=$((filesz*bsize))\n\t[ $filesz -le $blksz ] ||\n\t\terror \"file $testfile is $filesz long in memory\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tbsize=$(stat --format=%B $testfile)\n\tfilesz=$(stat --format=%b $testfile)\n\tfilesz=$((filesz*bsize))\n\t[ $filesz -le $blksz ] ||\n\t\terror \"file $testfile is $filesz long on server\"\n\n\trm -f $tmpfile\n}\nrun_test 38 \"encrypted file with hole\"\n\ntest_39() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# write a few bytes in file\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=$tmpfile of=$testfile bs=4 count=1 conv=fsync\n\n\t# write a few more bytes in the same page\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=1024 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\tdd if=$tmpfile of=$tmpfile bs=4 count=1 seek=1024 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server\"\n\n\trm -f $tmpfile\n}\nrun_test 39 \"rewrite data in already encrypted page\"\n\ntest_40() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal tmpfile2=$TMP/abc2\n\tlocal seek\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# write a few bytes in file\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=$tmpfile of=$testfile bs=4 count=1 conv=fsync\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory (1)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server (1)\"\n\n\t# write a few other bytes in same page\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=256 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\tdd if=$tmpfile of=$tmpfile bs=4 count=1 seek=256 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory (2)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server (2)\"\n\n\trm -f $testfile $tmpfile\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# write a few bytes in file, at end of first page\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tseek=$(getconf PAGESIZE)\n\tseek=$((seek - 4))\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# write a few other bytes at beginning of first page\n\tdd if=$tmpfile of=$testfile bs=4 count=1 conv=fsync,notrunc\n\n\tdd if=$tmpfile of=$tmpfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory (3)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server (3)\"\n\n\trm -f $testfile $tmpfile\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# write a few bytes in file, at beginning of second page\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -c1 -i0 $testfile\n\tseek=$(getconf PAGESIZE)\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# write a few other bytes at end of first page\n\tseek=$((seek - 4))\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted in memory (4)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted on server (4)\"\n\n\trm -f $testfile $tmpfile $tmpfile2\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# write a few bytes in file, at beginning of first stripe\n\techo \"abc\" > $tmpfile\n\t$LFS setstripe -S 256k -c2 $testfile\n\tdd if=$tmpfile of=$testfile bs=4 count=1 conv=fsync,notrunc\n\n\t# write a few other bytes, at beginning of second stripe\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=262144 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tdd if=$tmpfile of=$tmpfile bs=4 count=1 seek=262144 oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory (5)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server (5)\"\n\n\trm -f $tmpfile\n}\nrun_test 40 \"exercise size of encrypted file\"\n\ntest_41() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal tmpfile2=$TMP/abc2\n\tlocal seek\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\techo \"abc\" > $tmpfile\n\tseek=$(getconf PAGESIZE)\n\tseek=$((seek - 204))\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync\n\tseek=$(getconf PAGESIZE)\n\tseek=$((seek + 1092))\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# write a few bytes in file\n\t$LFS setstripe -c1 -i0 -S 256k $testfile\n\tseek=$(getconf PAGESIZE)\n\tseek=$((seek - 204))\n\t#define OBD_FAIL_OST_WR_ATTR_DELAY\t 0x250\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x250 fail_val=15\"\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync &\n\n\tsleep 5\n\t# write a few other bytes, at a different offset\n\tseek=$(getconf PAGESIZE)\n\tseek=$((seek + 1092))\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc &\n\twait\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x0\"\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted in memory (1)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted on server (1)\"\n\n\trm -f $tmpfile $tmpfile2\n}\nrun_test 41 \"test race on encrypted file size (1)\"\n\ntest_42() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal testfile2=$DIR2/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal tmpfile2=$TMP/abc2\n\tlocal pagesz=$(getconf PAGESIZE)\n\tlocal seek\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\tif is_mounted $MOUNT2; then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tmount_client $MOUNT2 ${MOUNT_OPTS},test_dummy_encryption ||\n\t\terror \"mount2 with '-o test_dummy_encryption' failed\"\n\n\t# create file by writting one whole page\n\t$LFS setstripe -c1 -i0 -S 256k $testfile\n\tdd if=/dev/zero of=$testfile bs=$pagesz count=1 conv=fsync\n\n\t# read file from 2nd mount point\n\tcat $testfile2 > /dev/null\n\n\techo \"abc\" > $tmpfile\n\tdd if=/dev/zero of=$tmpfile2 bs=$pagesz count=1 conv=fsync\n\tseek=$((2*pagesz - 204))\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tseek=$((2*pagesz + 1092))\n\tdd if=$tmpfile of=$tmpfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\n\t# write a few bytes in file from 1st mount point\n\tseek=$((2*pagesz - 204))\n\t#define OBD_FAIL_OST_WR_ATTR_DELAY\t 0x250\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x250 fail_val=15\"\n\tdd if=$tmpfile of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc &\n\n\tsleep 5\n\t# write a few other bytes, at a different offset from 2nd mount point\n\tseek=$((2*pagesz + 1092))\n\tdd if=$tmpfile of=$testfile2 bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc &\n\twait\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x0\"\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted in memory (1)\"\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile2 $testfile2 ||\n\t\terror \"file $testfile is corrupted in memory (2)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile2 $testfile ||\n\t\terror \"file $testfile is corrupted on server (1)\"\n\n\trm -f $tmpfile $tmpfile2\n}\nrun_test 42 \"test race on encrypted file size (2)\"\n\ntest_43() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal testfile2=$DIR2/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal tmpfile2=$TMP/abc2\n\tlocal resfile=$TMP/res\n\tlocal pagesz=$(getconf PAGESIZE)\n\tlocal seek\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\tif is_mounted $MOUNT2; then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tmount_client $MOUNT2 ${MOUNT_OPTS},test_dummy_encryption ||\n\t\terror \"mount2 with '-o test_dummy_encryption' failed\"\n\n\t# create file\n\ttr '\\0' '1' < /dev/zero |\n\t\tdd of=$tmpfile bs=$pagesz count=1 conv=fsync\n\t$LFS setstripe -c1 -i0 -S 256k $testfile\n\tcp $tmpfile $testfile\n\n\t# read file from 2nd mount point\n\tcat $testfile2 > /dev/null\n\n\t# write a few bytes in file from 1st mount point\n\techo \"abc\" > $tmpfile2\n\tseek=$((2*pagesz - 204))\n\t#define OBD_FAIL_OST_WR_ATTR_DELAY\t 0x250\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x250 fail_val=15\"\n\tdd if=$tmpfile2 of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc &\n\n\tsleep 5\n\t# read file from 2nd mount point\n\tdd if=$testfile2 of=$resfile bs=$pagesz count=1 conv=fsync,notrunc\n\tcmp -bl $tmpfile $resfile ||\n\t\terror \"file $testfile is corrupted in memory (1)\"\n\n\twait\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x0\"\n\n\t# check that in-memory representation of file is correct\n\tdd if=$tmpfile2 of=$tmpfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tcmp -bl $tmpfile $testfile2 ||\n\t\terror \"file $testfile is corrupted in memory (2)\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server (1)\"\n\n\trm -f $tmpfile $tmpfile2\n}\nrun_test 43 \"test race on encrypted file size (3)\"\n\ntest_44() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\twhich vmtouch || skip \"This test needs vmtouch utility\"\n\n\t# Direct I/O is not supported on encrypted files.\n\t# Attempts to use direct I/O on such files should fall back to\n\t# buffered I/O.\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# write a page in file with O_DIRECT\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=/dev/urandom of=$testfile bs=4096 count=1 conv=fsync oflag=direct\n\n\trespage=$(vmtouch $testfile | awk '/Resident\\ Pages:/ {print $3}')\n\t[ \"$respage\" == \"1/1\" ] ||\n\t\terror \"write to enc file did not fall back to buffered IO\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\tdd if=$testfile of=/dev/null bs=4096 count=1 iflag=direct\n\n\trespage=$(vmtouch $testfile | awk '/Resident\\ Pages:/ {print $3}')\n\t[ \"$respage\" == \"1/1\" ] ||\n\t\terror \"write to enc file did not fall back to buffered IO\"\n}\nrun_test 44 \"encrypted file access semantics: direct IO\"\n\ntest_45() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/junk\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t$LFS setstripe -c1 -i0 $testfile\n\tdd if=/dev/zero of=$testfile bs=512K count=1\n\t$MULTIOP $testfile OSMRUc || error \"$MULTIOP $testfile failed (1)\"\n\t$MULTIOP $testfile OSMWUc || error \"$MULTIOP $testfile failed (2)\"\n\n\tdd if=/dev/zero of=$tmpfile bs=512K count=1\n\t$MULTIOP $tmpfile OSMWUc || error \"$MULTIOP $tmpfile failed\"\n\t$MMAP_CAT $tmpfile > ${tmpfile}2\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t$MMAP_CAT $testfile > ${testfile}2\n\tcmp -bl ${tmpfile}2 ${testfile}2 ||\n\t\terror \"file $testfile is corrupted\"\n\n\trm -f $tmpfile ${tmpfile}2\n}\nrun_test 45 \"encrypted file access semantics: MMAP\"\n\ntest_46() {\n\tlocal testdir=$DIR/$tdir/mydir\n\tlocal testfile=$testdir/myfile\n\tlocal lsfile=$TMP/lsfile\n\tlocal scrambleddir\n\tlocal scrambledfile\n\n\tlocal testfile2=$DIR/$tdir/${tfile}.2\n\tlocal tmpfile=$DIR/junk\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\ttouch $DIR/onefile\n\ttouch $DIR/$tdir/$tfile\n\tmkdir $testdir\n\techo test > $testfile\n\tsync ; echo 3 > /proc/sys/vm/drop_caches\n\n\t# remove fscrypt key from keyring\n\tkeyctl revoke $(keyctl show | awk '$7 ~ \"^fscrypt:\" {print $1}')\n\tkeyctl reap\n\n\tscrambleddir=$(find $DIR/$tdir/ -maxdepth 1 -mindepth 1 -type d)\n\tls -1 $scrambleddir > $lsfile || error \"ls $testdir failed\"\n\n\tscrambledfile=$scrambleddir/$(head -n 1 $lsfile)\n\tstat $scrambledfile || error \"stat $scrambledfile failed\"\n\trm -f $lsfile\n\n\tcat $scrambledfile && error \"cat $scrambledfile should have failed\"\n\n\ttouch $scrambleddir/otherfile &&\n\t\terror \"touch otherfile should have failed\"\n\tls $scrambleddir/otherfile && error \"otherfile should not exist\"\n\tmkdir $scrambleddir/otherdir &&\n\t\terror \"mkdir otherdir should have failed\"\n\tls -d $scrambleddir/otherdir && error \"otherdir should not exist\"\n\n\trm -f $scrambledfile || error \"rm $scrambledfile failed\"\n\trmdir $scrambleddir || error \"rmdir $scrambleddir failed\"\n\n\trm -f $DIR/onefile\n}\nrun_test 46 \"encrypted file access semantics without key\"\n\ntest_47() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal testfile2=$DIR/$tdir/${tfile}.2\n\tlocal tmpfile=$DIR/junk\n\tlocal scrambleddir\n\tlocal scrambledfile\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\tdd if=/dev/zero of=$tmpfile bs=512K count=1\n\tmrename $tmpfile $testfile &&\n\t\terror \"rename from unencrypted to encrypted dir should fail\"\n\n\tln $tmpfile $testfile &&\n\t\terror \"link from unencrypted to encrypted dir should fail\"\n\n\tcp $tmpfile $testfile ||\n\t\terror \"cp from unencrypted to encrypted dir should succeed\"\n\trm -f $tmpfile\n\n\tmrename $testfile $testfile2 ||\n\t\terror \"rename from within encrypted dir should succeed\"\n\n\tln $testfile2 $testfile ||\n\t\terror \"link from within encrypted dir should succeed\"\n\trm -f $testfile\n\n\tln $testfile2 $tmpfile ||\n\t\terror \"link from encrypted to unencrypted dir should succeed\"\n\trm -f $tmpfile\n\n\tmrename $testfile2 $tmpfile ||\n\t\terror \"rename from encrypted to unencrypted dir should succeed\"\n\n\tdd if=/dev/zero of=$testfile bs=512K count=1\n\tmkdir $DIR/$tdir/mydir\n\tsync ; echo 3 > /proc/sys/vm/drop_caches\n\n\t# remove fscrypt key from keyring\n\tkeyctl revoke $(keyctl show | awk '$7 ~ \"^fscrypt:\" {print $1}')\n\tkeyctl reap\n\n\tscrambleddir=$(find $DIR/$tdir/ -maxdepth 1 -mindepth 1 -type d)\n\tscrambledfile=$(find $DIR/$tdir/ -maxdepth 1 -type f)\n\tln $scrambledfile $scrambleddir/linkfile &&\n\t\terror \"ln linkfile should have failed\"\n\tmrename $scrambledfile $DIR/onefile2 &&\n\t\terror \"mrename from $scrambledfile should have failed\"\n\ttouch $DIR/onefile\n\tmrename $DIR/onefile $scrambleddir/otherfile &&\n\t\terror \"mrename to $scrambleddir should have failed\"\n\n\trm -f $tmpfile $DIR/onefile\n}\nrun_test 47 \"encrypted file access semantics: rename/link\"\n\ntest_48a() {\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/111\n\tlocal tmpfile2=$TMP/abc\n\tlocal pagesz=$(getconf PAGESIZE)\n\tlocal sz\n\tlocal seek\n\tlocal scrambledfile\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# create file, 4 x PAGE_SIZE long\n\ttr '\\0' '1' < /dev/zero |\n\t\tdd of=$tmpfile bs=4x$pagesz count=1 conv=fsync\n\t$LFS setstripe -c1 -i0 $testfile\n\tcp $tmpfile $testfile\n\techo \"abc\" > $tmpfile2\n\n\t# decrease size: truncate to PAGE_SIZE\n\t$TRUNCATE $tmpfile $pagesz\n\t$TRUNCATE $testfile $pagesz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (1)\"\n\n\t# increase size: truncate to 2 x PAGE_SIZE\n\tsz=$((pagesz*2))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (2)\"\n\n\t# write in 2nd page\n\tseek=$((pagesz+100))\n\tdd if=$tmpfile2 of=$tmpfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tdd if=$tmpfile2 of=$testfile bs=4 count=1 seek=$seek oflag=seek_bytes \\\n\t\tconv=fsync,notrunc\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (3)\"\n\n\t# truncate to PAGE_SIZE / 2\n\tsz=$((pagesz/2))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (4)\"\n\n\t# lockless truncate should be turned into regular truncate for enc file\n\tsave_lustre_params client \"osc.*.lockless_truncate\" > $save\n\t# restore lockless_truncate default values on exit\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tlctl set_param -n osc.*.lockless_truncate 1\n\tcancel_lru_locks osc\n\tclear_stats osc.*.osc_stats\n\t$TRUNCATE $testfile 8000000 || error \"truncate failed (1)\"\n\t[ $(calc_stats osc.*.osc_stats lockless_truncate) -eq 0 ] ||\n\t\terror \"lockless truncate should be turned into regular truncate\"\n\tlctl set_param -n osc.*.lockless_truncate 0\n\n\t# truncate to a smaller, non-multiple of PAGE_SIZE, non-multiple of 16\n\tsz=$((sz-7))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (5)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, non-multiple of 16\n\tsz=$((sz+18))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (6)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, in a different page\n\tsz=$((sz+pagesz+30))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (7)\"\n\n\tsync ; echo 3 > /proc/sys/vm/drop_caches\n\n\t# remove fscrypt key from keyring\n\tkeyctl revoke $(keyctl show | awk '$7 ~ \"^fscrypt:\" {print $1}')\n\tkeyctl reap\n\n\tscrambledfile=$(find $DIR/$tdir/ -maxdepth 1 -type f)\n\t$TRUNCATE $scrambledfile 0 &&\n\t\terror \"truncate $scrambledfile should have failed without key\"\n\n\trm -f $tmpfile $tmpfile2\n}\nrun_test 48a \"encrypted file access semantics: truncate\"\n\ncleanup_for_enc_tests_othercli() {\n\tlocal othercli=$1\n\n\t# remount othercli normally\n\tzconf_umount $othercli $MOUNT ||\n\t\terror \"umount $othercli $MOUNT failed\"\n\tzconf_mount $othercli $MOUNT ||\n\t\terror \"remount $othercli $MOUNT failed\"\n}\n\ntest_48b() {\n\tlocal othercli\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\t[ \"$num_clients\" -ge 2 ] || skip \"Need at least 2 clients\"\n\n\tif [ \"$HOSTNAME\" == ${clients_arr[0]} ]; then\n\t\tothercli=${clients_arr[1]}\n\telse\n\t\tothercli=${clients_arr[0]}\n\tfi\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tstack_trap \"cleanup_for_enc_tests_othercli $othercli\" EXIT\n\tsetup_for_enc_tests\n\tzconf_umount $othercli $MOUNT ||\n\t\terror \"umount $othercli $MOUNT failed\"\n\n\tcp /bin/sleep $DIR/$tdir/\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\t$DIR/$tdir/sleep 30 &\n\t# mount and IOs must be done in the same shell session, otherwise\n\t# encryption key in session keyring is missing\n\tdo_node $othercli \"$MOUNT_CMD -o ${MOUNT_OPTS},test_dummy_encryption \\\n\t\t\t   $MGSNID:/$FSNAME $MOUNT && \\\n\t\t\t   $TRUNCATE $DIR/$tdir/sleep 7\"\n\twait || error \"wait error\"\n\tcmp --silent /bin/sleep $DIR/$tdir/sleep ||\n\t\terror \"/bin/sleep and $DIR/$tdir/sleep differ\"\n}\nrun_test 48b \"encrypted file: concurrent truncate\"\n\ntrace_cmd() {\n\tlocal cmd=\"$@\"\n\tlocal xattr_name=\"security.c\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\t$LCTL set_param debug=+info\n\t$LCTL clear\n\n\techo $cmd\n\teval $cmd\n\n\t$LCTL dk | grep -E \"get xattr '${xattr_name}'|get xattrs\"\n\t[ $? -ne 0 ] || error \"get xattr event was triggered\"\n}\n\ntest_49() {\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\tlocal dirname=$DIR/$tdir/subdir\n\n\tmkdir $dirname\n\n\ttrace_cmd stat $dirname\n\ttrace_cmd touch $dirname/f1\n\ttrace_cmd stat $dirname/f1\n\ttrace_cmd cat $dirname/f1\n\tdd if=/dev/zero of=$dirname/f1 bs=1M count=10 conv=fsync\n\ttrace_cmd $TRUNCATE $dirname/f1 10240\n\ttrace_cmd $LFS setstripe -E -1 -S 4M $dirname/f2\n\ttrace_cmd $LFS migrate -E -1 -S 256K $dirname/f2\n\ttrace_cmd $LFS setdirstripe -i 1 $dirname/d2\n\ttrace_cmd $LFS migrate -m 0 $dirname/d2\n\n\t$LFS setdirstripe -i 1 -c 1 $dirname/d3\n\tdirname=$dirname/d3/subdir\n\tmkdir $dirname\n\n\ttrace_cmd stat $dirname\n\ttrace_cmd touch $dirname/f1\n\ttrace_cmd stat $dirname/f1\n\ttrace_cmd cat $dirname/f1\n\tdd if=/dev/zero of=$dirname/f1 bs=1M count=10 conv=fsync\n\ttrace_cmd $TRUNCATE $dirname/f1 10240\n\ttrace_cmd $LFS setstripe -E -1 -S 4M $dirname/f2\n\ttrace_cmd $LFS migrate -E -1 -S 256K $dirname/f2\n}\nrun_test 49 \"Avoid getxattr for encryption context\"\n\ntest_50() {\n\tlocal testfile=$DIR/$tdir/$tfile\n\tlocal tmpfile=$TMP/abc\n\tlocal pagesz=$(getconf PAGESIZE)\n\tlocal sz\n\n\t$LCTL get_param mdc.*.import | grep -q client_encryption ||\n\t\tskip \"client encryption not supported\"\n\n\tmount.lustre --help |& grep -q \"test_dummy_encryption:\" ||\n\t\tskip \"need dummy encryption support\"\n\n\tstack_trap cleanup_for_enc_tests EXIT\n\tsetup_for_enc_tests\n\n\t# write small file, data on MDT only\n\ttr '\\0' '1' < /dev/zero |\n\t    dd of=$tmpfile bs=1 count=5000 conv=fsync\n\t$LFS setstripe -E 1M -L mdt -E EOF $testfile\n\tcp $tmpfile $testfile\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server\"\n\n\t# decrease size: truncate to PAGE_SIZE\n\t$TRUNCATE $tmpfile $pagesz\n\t$TRUNCATE $testfile $pagesz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (1)\"\n\n\t# increase size: truncate to 2 x PAGE_SIZE\n\tsz=$((pagesz*2))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (2)\"\n\n\t# truncate to PAGE_SIZE / 2\n\tsz=$((pagesz/2))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (3)\"\n\n\t# truncate to a smaller, non-multiple of PAGE_SIZE, non-multiple of 16\n\tsz=$((sz-7))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (4)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, non-multiple of 16\n\tsz=$((sz+18))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (5)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, in a different page\n\tsz=$((sz+pagesz+30))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (6)\"\n\n\trm -f $testfile\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# write hole in file, data spread on MDT and OST\n\ttr '\\0' '2' < /dev/zero |\n\t    dd of=$tmpfile bs=1 count=1539 seek=1539074 conv=fsync,notrunc\n\t$LFS setstripe -E 1M -L mdt -E EOF $testfile\n\tcp --sparse=always $tmpfile $testfile\n\n\t# check that in-memory representation of file is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted in memory\"\n\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\n\t# check that file read from server is correct\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted on server\"\n\n\t# truncate to a smaller, non-multiple of PAGE_SIZE, non-multiple of 16,\n\t# inside OST part of data\n\tsz=$((1024*1024+13))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (7)\"\n\n\t# truncate to a smaller, non-multiple of PAGE_SIZE, non-multiple of 16,\n\t# inside MDT part of data\n\tsz=7\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (8)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, non-multiple of 16,\n\t# inside MDT part of data\n\tsz=$((1024*1024-13))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (9)\"\n\n\t# truncate to a larger, non-multiple of PAGE_SIZE, non-multiple of 16,\n\t# inside OST part of data\n\tsz=$((1024*1024+7))\n\t$TRUNCATE $tmpfile $sz\n\t$TRUNCATE $testfile $sz\n\tcancel_lru_locks osc ; cancel_lru_locks mdc\n\tcmp -bl $tmpfile $testfile ||\n\t\terror \"file $testfile is corrupted (10)\"\n\n\trm -f $tmpfile\n}\nrun_test 50 \"DoM encrypted file\"\n\ntest_51() {\n\t[ \"$MDS1_VERSION\" -gt $(version_code 2.13.53) ] ||\n\t\tskip \"Need MDS version at least 2.13.53\"\n\n\tmkdir $DIR/$tdir || error \"mkdir $tdir\"\n\n\ttouch $DIR/$tdir/$tfile || error \"touch $tfile\"\n\tcp $(which chown) $DIR/$tdir || error \"cp chown\"\n\t$RUNAS_CMD -u $ID0 $DIR/$tdir/chown $ID0 $DIR/$tdir/$tfile &&\n\t\terror \"chown $tfile should fail\"\n\tsetcap 'CAP_CHOWN=ep' $DIR/$tdir/chown || error \"setcap CAP_CHOWN\"\n\t$RUNAS_CMD -u $ID0 $DIR/$tdir/chown $ID0 $DIR/$tdir/$tfile ||\n\t\terror \"chown $tfile\"\n\trm $DIR/$tdir/$tfile || error \"rm $tfile\"\n\n\ttouch $DIR/$tdir/$tfile || error \"touch $tfile\"\n\tcp $(which touch) $DIR/$tdir || error \"cp touch\"\n\t$RUNAS_CMD -u $ID0 $DIR/$tdir/touch $DIR/$tdir/$tfile &&\n\t\terror \"touch should fail\"\n\tsetcap 'CAP_FOWNER=ep' $DIR/$tdir/touch || error \"setcap CAP_FOWNER\"\n\t$RUNAS_CMD -u $ID0 $DIR/$tdir/touch $DIR/$tdir/$tfile ||\n\t\terror \"touch $tfile\"\n\trm $DIR/$tdir/$tfile || error \"rm $tfile\"\n\n\tlocal cap\n\tfor cap in \"CAP_DAC_OVERRIDE\" \"CAP_DAC_READ_SEARCH\"; do\n\t\ttouch $DIR/$tdir/$tfile || error \"touch $tfile\"\n\t\tchmod 600 $DIR/$tdir/$tfile || error \"chmod $tfile\"\n\t\tcp $(which cat) $DIR/$tdir || error \"cp cat\"\n\t\t$RUNAS_CMD -u $ID0 $DIR/$tdir/cat $DIR/$tdir/$tfile &&\n\t\t\terror \"cat should fail\"\n\t\tsetcap $cap=ep $DIR/$tdir/cat || error \"setcap $cap\"\n\t\t$RUNAS_CMD -u $ID0 $DIR/$tdir/cat $DIR/$tdir/$tfile ||\n\t\t\terror \"cat $tfile\"\n\t\trm $DIR/$tdir/$tfile || error \"rm $tfile\"\n\tdone\n}\nrun_test 51 \"FS capabilities ===============\"\n\nlog \"cleanup: ======================================================\"\n\nsec_unsetup() {\n\tfor num in $(seq $MDSCOUNT); do\n\t\tif [ \"${identity_old[$num]}\" = 1 ]; then\n\t\t\tswitch_identity $num false || identity_old[$num]=$?\n\t\tfi\n\tdone\n\n\t$RUNAS_CMD -u $ID0 ls $DIR\n\t$RUNAS_CMD -u $ID1 ls $DIR\n}\nsec_unsetup\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 3784}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# NOTE\n# In order to be able to do the runcon commands in test_4,\n# the SELinux policy must allow transitions from unconfined_t\n# to user_t and guest_t:\n# #============= unconfined_r ==============\n# allow unconfined_r guest_r;\n# allow unconfined_r user_r;\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# e.g. ONLY=\"22 23\" or ONLY=\"`seq 32 39`\" or EXCEPT=\"31\"\nset -e\n\nONLY=${ONLY:-\"$*\"}\n# bug number for skipped test:\nALWAYS_EXCEPT=${ALWAYS_EXCEPT:-\"$SANITY_SELINUX_EXCEPT\"}\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nSRCDIR=$(dirname $0)\nSAVE_PWD=$PWD\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\nrequire_dsh_mds || exit 0\n\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"xxx\"\n\nRUNAS_CMD=${RUNAS_CMD:-runas}\n# $RUNAS_ID may get set incorrectly somewhere else\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&\n\terror \"RUNAS_ID set to 0, but UID is also 0!\"\n\n#\n# global variables of this  sanity\n#\n\ncheck_selinux() {\n\techo -n \"Checking SELinux environment... \"\n\tlocal selinux_status=$(getenforce)\n\tif [ \"$selinux_status\" != \"Enforcing\" ]; then\n\t    skip \"SELinux is currently in $selinux_status mode,\" \\\n\t\t \"but it must be enforced to run sanity-selinux\" && exit 0\n\tfi\n\tlocal selinux_policy=$(sestatus |\n\t\tawk -F':' '$1 == \"Loaded policy name\" {print $2}' | xargs)\n\tif [ -z \"$selinux_policy\" ]; then\n\t    selinux_policy=$(sestatus |\n\t\tawk -F':' '$1 == \"Policy from config file\" {print $2}' | xargs)\n\tfi\n\t[ \"$selinux_policy\" == \"targeted\" ] ||\n\t\terror \"Accepting only targeted policy\"\n\techo \"$selinux_status, $selinux_policy\"\n}\n\ncheck_selinux\n\n# we want double mount\nMOUNT_2=${MOUNT_2:-\"yes\"}\ncheck_and_setup_lustre\n\nrm -rf $DIR/[df][0-9]*\n\ncheck_runas_id $RUNAS_ID $RUNAS_ID $RUNAS\n\nbuild_test_filter\n\numask 077\n\ncheck_selinux_xattr() {\n\tlocal mds=$1\n\tlocal mds_path=$2\n\tlocal mds_dev=$(facet_device $mds)\n\tlocal mntpt=\"/tmp/mdt_\"\n\tlocal opts\n\n\tdo_facet $mds mkdir -p $mntpt  || error \"mkdir $mntpt failed\"\n\tmount_fstype $mds $mntpt  || error \"mount $mds failed\"\n\n\tlocal xattrval=$(do_facet $mds getfattr -n security.selinux \\\n\t\t\t\t${mntpt}/ROOT/$mds_path |\n\t\t\t awk -F\"=\" '$1==\"security.selinux\" {print $2}')\n\n\tunmount_fstype $mds $mntpt || error \"umount $mds failed\"\n\tdo_facet $mds rmdir $mntpt || error \"rmdir $mntpt failed\"\n\n\techo $xattrval\n}\n\nget_sel_ctx() {\n\tlocal file=$1\n\n\t[ -n \"$file\" ] || return;\n\t[ -f $file ] || return;\n\tstat $file | awk '$1 == \"Context:\" {print $2}'\n}\n\ntest_1() {\n\tlocal devname=$(mdsdevname 1)\n\tlocal filename=${DIR}/${tdir}/df1\n\tlocal mds_path=${filename#$MOUNT}\n\n\tmds_path=${mds_path#/}\n\n\t$LFS setdirstripe -i0 -c1 ${DIR}/$tdir || error \"create dir $tdir failed\"\n\ttouch $filename || error \"cannot touch $filename\"\n\n\tlocal xattrval=$(check_selinux_xattr \"mds1\" $mds_path)\n\n\t[ -n \"$xattrval\" -a \"$xattrval\" != '\"\"' ] ||\n\t\terror \"security.selinux xattr is not set\"\n}\nrun_test 1 \"create file and check security.selinux xattr is set on MDT\"\n\ntest_2a() {\n\tlocal devname=$(mdsdevname 1)\n\tlocal dirname=${DIR}/${tdir}/dir2a\n\tlocal mds_path=${dirname#$MOUNT}\n\n\tmds_path=${mds_path#/}\n\n\t$LFS setdirstripe -i0 -c1 ${DIR}/$tdir || error \"create dir failed\"\n\tmkdir $dirname || error \"cannot mkdir $dirname\"\n\n\tlocal xattrval=$(check_selinux_xattr \"mds1\" $mds_path)\n\n\t[ -n \"$xattrval\" -a \"$xattrval\" != '\"\"' ] ||\n\t\terror \"security.selinux xattr is not set\"\n}\nrun_test 2a \"create dir (mkdir) and check security.selinux xattr is set on MDT\"\n\ntest_2b() {\n\tlocal devname=$(mdsdevname 1)\n\tlocal dirname1=${DIR}/$tdir/dir2b1\n\tlocal dirname2=${DIR}/$tdir/dir2b2\n\tlocal mds_path=${dirname1#$MOUNT}\n\n\tmds_path=${mds_path#/}\n\n\t$LFS setdirstripe -i0 -c1 ${DIR}/$tdir || error \"create dir failed\"\n\t$LFS mkdir -c0 -i0 $dirname1 || error \"cannot 'lfs mkdir' $dirname1\"\n\n\tlocal xattrval=$(check_selinux_xattr \"mds1\" $mds_path)\n\n\tmds_path=${dirname2#$MOUNT}\n\tmds_path=${mds_path#/}\n\n\t[ -n \"$xattrval\" -a \"$xattrval\" != '\"\"' ] ||\n\t\terror \"security.selinux xattr is not set\"\n\n\t$LFS setdirstripe -i0 $dirname2 ||\n\t    error \"cannot 'lfs setdirstripe' $dirname2\"\n\n\txattrval=$(check_selinux_xattr \"mds1\" $mds_path)\n\n\t[ -n \"$xattrval\" -a \"$xattrval\" != '\"\"' ] ||\n\t\terror \"security.selinux xattr is not set\"\n}\nrun_test 2b \"create dir with lfs and check security.selinux xattr is set on MDT\"\n\ntest_3() {\n\tlocal filename=$DIR/$tdir/df3\n\tlocal level=$(id -Z | cut -d':' -f4-)\n\tlocal unconctx=\"-u unconfined_u -r unconfined_r -t unconfined_t \\\n\t\t\t-l $level\"\n\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\t# \"access\" Lustre\n\techo \"As unconfined_u: touch $filename\"\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx touch $filename ||\n\t\terror \"can't touch $filename\"\n\techo \"As unconfined_u: rm -f $filename\"\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx rm -f $filename ||\n\t\terror \"can't remove $filename\"\n\n\treturn 0\n}\nrun_test 3 \"access with unconfined user\"\n\ntest_4() {\n\tlocal filename=$DIR/$tdir/df4\n\tlocal guestctx=\"-u guest_u -r guest_r -t guest_t -l s0\"\n\tlocal usrctx=\"-u user_u -r user_r -t user_t -l s0\"\n\n\tsesearch --role_allow | grep -q \"allow unconfined_r user_r\"\n\tif [ $? -ne 0 ]; then\n\t    skip \"SELinux policy module must allow transition from \\\n\t\t   unconfined_r to user_r for this test.\" && exit 0\n\tfi\n\tsesearch --role_allow | grep -q \"allow unconfined_r guest_r\"\n\tif [ $? -ne 0 ]; then\n\t    skip \"SELinux policy module must allow transition from \\\n\t\t   unconfined_r to guest_r for this test.\" && exit 0\n\tfi\n\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\t# \"access\" Lustre\n\techo \"As guest_u: touch $filename\"\n\t$RUNAS_CMD -u $RUNAS_ID runcon $guestctx touch $filename &&\n\t\terror \"touch $filename should have failed\"\n\n\t# \"access\" Lustre\n\techo \"As user_u: touch $filename\"\n\t$RUNAS_CMD -u $RUNAS_ID runcon $usrctx touch $filename ||\n\t\terror \"can't touch $filename\"\n\techo \"As user_u: rm -f $filename\"\n\t$RUNAS_CMD -u $RUNAS_ID runcon $usrctx rm -f $filename ||\n\t\terror \"can't remove $filename\"\n\n\treturn 0\n}\nrun_test 4 \"access with specific SELinux user\"\n\ntest_5() {\n\tlocal filename=$DIR/df5\n\tlocal newsecctx=\"nfs_t\"\n\n\t# create file\n\ttouch $filename || error \"cannot touch $filename\"\n\n\t# change sec context\n\tchcon -t $newsecctx $filename\n\tls -lZ $filename\n\n\t# purge client's cache\n\tsync ; echo 3 > /proc/sys/vm/drop_caches\n\n\t# get sec context\n\tls -lZ $filename\n\tlocal secctxseen=$(get_sel_ctx $filename | cut -d: -f3)\n\n\t[ \"$newsecctx\" == \"$secctxseen\" ] ||\n\t\terror \"sec context seen from 1st mount point is not correct\"\n\n\treturn 0\n}\nrun_test 5 \"security context retrieval from MDT xattr\"\n\ntest_10() {\n\tlocal filename1=$DIR/df10\n\tlocal filename2=$DIR2/df10\n\tlocal newsecctx=\"nfs_t\"\n\n\t# create file from 1st mount point\n\ttouch $filename1 || error \"cannot touch $filename1\"\n\tls -lZ $filename1\n\n\t# change sec context from 2nd mount point\n\tchcon -t $newsecctx $filename2\n\tls -lZ $filename2\n\n\t# get sec context from 1st mount point\n\tls -lZ $filename1\n\tlocal secctxseen=$(get_sel_ctx $filename1 | cut -d: -f3)\n\n\t[ \"$newsecctx\" == \"$secctxseen\" ] ||\n\t\terror_ignore LU-6784 \\\n\t\t    \"sec context seen from 1st mount point is not correct\"\n\n\treturn 0\n}\nrun_test 10 \"[consistency] concurrent security context change\"\n\ntest_20a() {\n\tlocal filename1=$DIR/$tdir/df20a\n\tlocal filename2=$DIR2/$tdir/df20a\n\tlocal req_delay=20\n\tlocal unconctx=\"-u unconfined_u -r unconfined_r -t unconfined_t -l s0\"\n\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\t# sleep some time in ll_create_nd()\n\t#define OBD_FAIL_LLITE_CREATE_FILE_PAUSE   0x1409\n\tdo_facet client \"$LCTL set_param fail_val=$req_delay fail_loc=0x1409\"\n\n\t# create file on first mount point\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx touch $filename1 &\n\tlocal touchpid=$!\n\tsleep 5\n\n\tif [[ -z \"$(ps h -o comm -p $touchpid)\" ]]; then\n\t\terror \"touch failed to sleep, pid=$touchpid\"\n\tfi\n\n\t# get sec info on second mount point\n\tif [ -e \"$filename2\" ]; then\n\t\tsecinfo2=$(get_sel_ctx $filename2)\n\tfi\n\n\t# get sec info on first mount point\n\twait $touchpid\n\tsecinfo1=$(get_sel_ctx $filename1)\n\n\t# compare sec contexts\n\t[ -z \"$secinfo2\" -o \"$secinfo1\" == \"$secinfo2\" ] ||\n\t\terror \"sec context seen from 2nd mount point is not correct\"\n\n\treturn 0\n}\nrun_test 20a \"[atomicity] concurrent access from another client (file)\"\n\ntest_20b() {\n\tlocal dirname1=$DIR/$tdir/dd20b\n\tlocal dirname2=$DIR2/$tdir/dd20b\n\tlocal req_delay=20\n\tlocal unconctx=\"-u unconfined_u -r unconfined_r -t unconfined_t -l s0\"\n\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\n\t# sleep some time in ll_create_nd()\n\t#define OBD_FAIL_LLITE_NEWNODE_PAUSE     0x140a\n\tdo_facet client \"$LCTL set_param fail_val=$req_delay fail_loc=0x140a\"\n\n\t# create file on first mount point\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx mkdir $dirname1 &\n\tlocal mkdirpid=$!\n\tsleep 5\n\n\tif [[ -z \"$(ps h -o comm -p $mkdirpid)\" ]]; then\n\t\terror \"mkdir failed to sleep, pid=$mkdirpid\"\n\tfi\n\n\t# get sec info on second mount point\n\tif [ -e \"$dirname2\" ]; then\n\t\tsecinfo2=$(ls -ldZ $dirname2 | awk '{print $4}')\n\telse\n\t\tsecinfo2=\"\"\n\tfi\n\n\t# get sec info on first mount point\n\twait $mkdirpid\n\tsecinfo1=$(ls -ldZ $dirname1 | awk '{print $4}')\n\n\t# compare sec contexts\n\t[ -z \"$secinfo2\" -o \"$secinfo1\" == \"$secinfo2\" ] ||\n\t\terror \"sec context seen from 2nd mount point is not correct\"\n\n\treturn 0\n}\nrun_test 20b \"[atomicity] concurrent access from another client (dir)\"\n\ntest_20c() {\n\tlocal dirname1=$DIR/dd20c\n\tlocal dirname2=$DIR2/dd20c\n\tlocal req_delay=20\n\n\t# sleep some time in ll_create_nd()\n\t#define OBD_FAIL_LLITE_SETDIRSTRIPE_PAUSE     0x140b\n\tdo_facet client \"$LCTL set_param fail_val=$req_delay fail_loc=0x140b\"\n\n\t# create file on first mount point\n\t$LFS mkdir -c0 -i0 $dirname1 &\n\tlocal mkdirpid=$!\n\tsleep 5\n\n\tif [[ -z \"$(ps h -o comm -p $mkdirpid)\" ]]; then\n\t\terror \"lfs mkdir failed to sleep, pid=$mkdirpid\"\n\tfi\n\n\t# get sec info on second mount point\n\tif [ -e \"$dirname2\" ]; then\n\t\tsecinfo2=$(ls -ldZ $dirname2 | awk '{print $4}')\n\telse\n\t\tsecinfo2=\"\"\n\tfi\n\n\t# get sec info on first mount point\n\twait $mkdirpid\n\tsecinfo1=$(ls -ldZ $dirname1 | awk '{print $4}')\n\n\t# compare sec contexts\n\t[ -z \"$secinfo2\" -o \"$secinfo1\" == \"$secinfo2\" ] ||\n\t\terror \"sec context seen from 2nd mount point is not correct\"\n\n\treturn 0\n}\nrun_test 20c \"[atomicity] concurrent access from another client (dir via lfs)\"\n\ncleanup_20d() {\n\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tmountcli\n}\n\ntrace_cmd() {\n\tlocal cmd=\"$@\"\n\tlocal xattr_prefix=$(grep -E \\\n\t\t\"#define[[:space:]]+XATTR_SECURITY_PREFIX[[:space:]]+\" \\\n\t\t/usr/include/linux/xattr.h 2>/dev/null |\n\t\tawk '{print $3}' | sed s+\\\"++g)\n\tlocal xattr_suffix=$(grep -E \\\n\t\t\"#define[[:space:]]+XATTR_SELINUX_SUFFIX[[:space:]]+\" \\\n\t\t/usr/include/linux/xattr.h 2>/dev/null |\n\t\tawk '{print $3}' | sed s+\\\"++g)\n\tlocal xattr_name=${xattr_prefix}${xattr_suffix}\n\n\t[ -z \"$xattr_name\" ] && xattr_name=\"security.selinux\"\n\n\t# umount client\n\tif [ \"$MOUNT_2\" ] && $(grep -q $MOUNT2' ' /proc/mounts); then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif $(grep -q $MOUNT' ' /proc/mounts); then\n\t\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\tlustre_rmmod\n\t# remount client\n\tmount_client $MOUNT ${MOUNT_OPTS} || error \"mount client failed\"\n\n\t$LCTL set_param debug=+info\n\t$LCTL clear\n\n\techo $cmd\n\teval $cmd\n\n\t$LCTL dk | grep \"get xattr '${xattr_name}'\"\n\t[ $? -eq 0 ] && error \"get xattr event was triggered\" || true\n}\n\ntest_20d() {\n\tif [ \"$MDS1_VERSION\" -lt $(version_code 2.12.50) ] ||\n\t   [ \"$CLIENT_VERSION\" -lt $(version_code 2.12.50) ]; then\n\t\tskip \"Need version >= 2.12.50\"\n\tfi\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\n\tstack_trap cleanup_20d EXIT\n\n\tlocal dirname=$DIR/$tdir/subdir\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $dirname\n\n\ttrace_cmd stat $dirname\n\ttrace_cmd touch $dirname/f1\n\ttrace_cmd stat $dirname/f1\n\ttrace_cmd cat $dirname/f1\n\tdd if=/dev/zero of=$dirname/f1 bs=1M count=10\n\ttrace_cmd /usr/bin/truncate -s 10240 $dirname/f1\n\ttrace_cmd lfs setstripe -E -1 -S 4M $dirname/f2\n\ttrace_cmd lfs migrate -E -1 -S 256K $dirname/f2\n\ttrace_cmd lfs setdirstripe -i 1 $dirname/d2\n\ttrace_cmd lfs migrate -m 0 $dirname/d2\n\n\tlfs setdirstripe -i 1 -c 1 $dirname/d3\n\tdirname=$dirname/d3/subdir\n\tmkdir $dirname\n\n\ttrace_cmd stat $dirname\n\ttrace_cmd touch $dirname/f1\n\ttrace_cmd stat $dirname/f1\n\ttrace_cmd cat $dirname/f1\n\tdd if=/dev/zero of=$dirname/f1 bs=1M count=10\n\ttrace_cmd /usr/bin/truncate -s 10240 $dirname/f1\n\ttrace_cmd lfs setstripe -E -1 -S 4M $dirname/f2\n\ttrace_cmd lfs migrate -E -1 -S 256K $dirname/f2\n}\nrun_test 20d \"[atomicity] avoid getxattr for security context\"\n\ntest_20e() {\n\t[ \"$CLIENT_VERSION\" -lt $(version_code 2.13.54) ] &&\n\t\tskip \"Need client version >= 2.13.54\"\n\tlocal filename1=$DIR/$tdir/df20e\n\tlocal delay=5\n\tlocal evict\n\tlocal unconctx=\"-u unconfined_u -r unconfined_r -t unconfined_t -l s0\"\n\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\t#define OBD_FAIL_LLITE_CREATE_FILE_PAUSE2   0x1416\n\tdo_facet client \"$LCTL set_param fail_val=$delay fail_loc=0x80001416\"\n\n\t# create file on first mount point\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx touch $filename1 &\n\tlocal touchpid=$!\n\tsleep 1\n\tcancel_lru_locks mdc\n\tsysctl -w vm.drop_caches=2\n\t$RUNAS_CMD -u $RUNAS_ID runcon $unconctx stat $DIR/$tdir &\n\n\twait $touchpid\n\n\tevict=$($LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] || error \"eviction happened\"\n}\nrun_test 20e \"client deadlock and eviction form MDS\"\n\ncheck_nodemap() {\n\tlocal nm=$1\n\tlocal key=$2\n\tlocal val=$3\n\tlocal facets=\"\"\n\tlocal i\n\n\tif [ \"$nm\" == \"active\" ]; then\n\t\tproc_param=\"active\"\n\telse\n\t\tproc_param=\"$nm.$key\"\n\tfi\n\t# check all MDS nodes, in reverse order to privilege remote ones first\n\tfor i in $(seq $MDSCOUNT); do\n\t\tfacets=\"mds$i $facets\"\n\tdone\n\tfor facet in $facets; do\n\t\tis_sync=false\n\t\tfor i in {1..20}; do\n\t\t\tout=$(do_facet $facet $LCTL get_param -n \\\n\t\t\t\t   nodemap.$proc_param 2>/dev/null)\n\t\t\techo \"On $facet, ${proc_param} = $out\"\n\t\t\t[ \"$val\" == \"$out\" ] && is_sync=true && break\n\t\t\tsleep 1\n\t\tdone\n\t\tif ! $is_sync; then\n\t\t\terror \"$proc_param not updated on $facet after 20 secs\"\n\t\tfi\n\tdone\n}\n\ncreate_nodemap() {\n\tlocal nm=$1\n\tlocal sepol\n\tlocal client_ip=$(host_nids_address $HOSTNAME $NETTYPE)\n\tlocal client_nid=$(h2nettype $client_ip)\n\n\tdo_facet mgs $LCTL nodemap_activate 1\n\n\tdo_facet mgs $LCTL nodemap_add $nm\n\tdo_facet mgs $LCTL nodemap_add_range \\\n\t\t\t--name $nm --range $client_nid\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t\t--property admin --value 1\n\tdo_facet mgs $LCTL nodemap_modify --name $nm \\\n\t\t\t--property trusted --value 1\n\n\tcheck_nodemap $nm admin_nodemap 1\n\tcheck_nodemap $nm trusted_nodemap 1\n\n\tsleep 10\n\tsepol=$(l_getsepol | cut -d':' -f2- | xargs)\n\tdo_facet mgs $LCTL set_param -P nodemap.$nm.sepol=\"$sepol\"\n\n\tcheck_nodemap $nm sepol $sepol\n}\n\nremove_nodemap() {\n\tlocal nm=$1\n\n\tdo_facet mgs $LCTL nodemap_del $nm\n\n\twait_update_facet --verbose mds1 \\\n\t\t\"$LCTL get_param nodemap.$nm.id 2>/dev/null | \\\n\t\tgrep -c $nm || true\" 0 30 ||\n\t\terror \"nodemap $nm could not be removed\"\n\n\tdo_facet mgs $LCTL nodemap_activate 0\n\n\tcheck_nodemap active x  0\n}\n\ntest_21a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS >= 2.11.56\"\n\n\tlocal sepol\n\n\t# umount client\n\tif [ \"$MOUNT_2\" ] && $(grep -q $MOUNT2' ' /proc/mounts); then\n\t\tumount_client $MOUNT2 || error \"umount $MOUNT2 failed\"\n\tfi\n\tif $(grep -q $MOUNT' ' /proc/mounts); then\n\t\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\tfi\n\n\t# create nodemap entry with sepol\n\tcreate_nodemap c0\n\n\tif $GSS_SK; then\n\t\t# update mount option with skpath\n\t\tMOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)\n\t\texport SK_UNIQUE_NM=true\n\n\t\t# load specific key on servers\n\t\tdo_nodes $(comma_list $(all_server_nodes)) \"lgss_sk -t server \\\n\t\t\t\t\t\t    -l $SK_PATH/nodemap/c0.key\"\n\n\t\t# set perms for per-nodemap keys else permission denied\n\t\tdo_nodes $(comma_list $(all_server_nodes)) \\\n\t\t \"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\n\tfi\n\n\t# mount client without sending sepol\n\tmount_client $MOUNT $MOUNT_OPTS &&\n\t\terror \"client mount without sending sepol should be refused\"\n\n\t# mount client with sepol\n\techo -1 > /sys/module/ptlrpc/parameters/send_sepol\n\tmount_client $MOUNT $MOUNT_OPTS ||\n\t\terror \"client mount with sepol failed\"\n\n\t# umount client\n\tumount_client $MOUNT || error \"umount $MOUNT failed\"\n\n\t# store wrong sepol in nodemap\n\tsepol=\"0:policy:0:0000000000000000000000000000000000000000000000000000000000000000\"\n\tdo_facet mgs $LCTL set_param -P nodemap.c0.sepol=\"$sepol\"\n\tcheck_nodemap c0 sepol $sepol\n\n\t# mount client with sepol\n\tmount_client $MOUNT $MOUNT_OPTS &&\n\t\terror \"client mount without matching sepol should be refused\"\n\n\t# remove nodemap\n\tremove_nodemap c0\n\n\tif $GSS_SK; then\n\t\texport SK_UNIQUE_NM=false\n\tfi\n\n\t# remount client normally\n\techo 0 > /sys/module/ptlrpc/parameters/send_sepol\n\tmountcli || error \"normal client mount failed\"\n}\nrun_test 21a \"Send sepol at connect\"\n\ntest_21b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS >= 2.11.56\"\n\n\tlocal sepol\n\n\tmkdir -p $DIR/$tdir || error \"failed to create $DIR/$tdir\"\n\techo test > $DIR/$tdir/toopen ||\n\t\terror \"failed to write to $DIR/$tdir/toopen\"\n\ttouch $DIR/$tdir/ftoremove ||\n\t\terror \"failed to create $DIR/$tdir/ftoremove\"\n\ttouch $DIR/$tdir/ftoremove2 ||\n\t\terror \"failed to create $DIR/$tdir/ftoremove2\"\n\ttouch $DIR/$tdir/ftoremove3 ||\n\t\terror \"failed to create $DIR/$tdir/ftoremove3\"\n\ttouch $DIR/$tdir/ftoremove4 ||\n\t\terror \"failed to create $DIR/$tdir/ftoremove4\"\n\tmkdir $DIR/$tdir/dtoremove ||\n\t\terror \"failed to create $DIR/$tdir/dtoremove\"\n\tmkdir $DIR/$tdir/dtoremove2 ||\n\t\terror \"failed to create $DIR/$tdir/dtoremove2\"\n\tmkdir $DIR/$tdir/dtoremove3 ||\n\t\terror \"failed to create $DIR/$tdir/dtoremove3\"\n\tmkdir $DIR/$tdir/dtoremove4 ||\n\t\terror \"failed to create $DIR/$tdir/dtoremove4\"\n\ttouch $DIR/$tdir/ftorename ||\n\t\terror \"failed to create $DIR/$tdir/ftorename\"\n\tmkdir $DIR/$tdir/dtorename ||\n\t\terror \"failed to create $DIR/$tdir/dtorename\"\n\tsetfattr -n user.myattr -v myval $DIR/$tdir/toopen ||\n\t\terror \"failed to set xattr on $DIR/$tdir/toopen\"\n\techo 3 > /proc/sys/vm/drop_caches\n\n\t# create nodemap entry with sepol\n\tcreate_nodemap c0\n\n\tif $GSS_SK; then\n\t\texport SK_UNIQUE_NM=true\n\n\t\t# load specific key on servers\n\t\tdo_nodes $(comma_list $(all_server_nodes)) \"lgss_sk -t server \\\n\t\t\t\t\t\t    -l $SK_PATH/nodemap/c0.key\"\n\n\t\t# set perms for per-nodemap keys else permission denied\n\t\tdo_nodes $(comma_list $(all_server_nodes)) \\\n\t\t \"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\n\tfi\n\n\t# metadata ops without sending sepol\n\ttouch $DIR/$tdir/f0 && error \"touch (1)\"\n\tlfs setstripe -c1 $DIR/$tdir/f1 && error \"lfs setstripe (1)\"\n\tmkdir $DIR/$tdir/d0 && error \"mkdir (1)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d1 && error \"lfs setdirstripe (1)\"\n\tcat $DIR/$tdir/toopen && error \"cat (1)\"\n\trm -f $DIR/$tdir/ftoremove && error \"rm (1)\"\n\trmdir $DIR/$tdir/dtoremove && error \"rmdir (1)\"\n\tmv $DIR/$tdir/ftorename $DIR/$tdir/ftorename2 && error \"mv (1)\"\n\tmv $DIR/$tdir/dtorename $DIR/$tdir/dtorename2 && error \"mv (2)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen && error \"getfattr (1)\"\n\tsetfattr -n user.myattr -v myval2 $DIR/$tdir/toopen &&\n\t\terror \"setfattr (1)\"\n\tchattr +i $DIR/$tdir/toopen && error \"chattr (1)\"\n\tlsattr $DIR/$tdir/toopen && error \"lsattr (1)\"\n\tchattr -i $DIR/$tdir/toopen && error \"chattr (1)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl1 && error \"symlink (1)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl1 && error \"hardlink (1)\"\n\n\t# metadata ops with sepol\n\techo -1 > /sys/module/ptlrpc/parameters/send_sepol\n\ttouch $DIR/$tdir/f2 || error \"touch (2)\"\n\tlfs setstripe -c1 $DIR/$tdir/f3 || error \"lfs setstripe (2)\"\n\tmkdir $DIR/$tdir/d2 || error \"mkdir (2)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d3 || error \"lfs setdirstripe (2)\"\n\tcat $DIR/$tdir/toopen || error \"cat (2)\"\n\trm -f $DIR/$tdir/ftoremove || error \"rm (2)\"\n\trmdir $DIR/$tdir/dtoremove || error \"rmdir (2)\"\n\tmv $DIR/$tdir/ftorename $DIR/$tdir/ftorename2 || error \"mv (3)\"\n\tmv $DIR/$tdir/dtorename $DIR/$tdir/dtorename2 || error \"mv (4)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen || error \"getfattr (2)\"\n\tsetfattr -n user.myattr -v myval2 $DIR/$tdir/toopen ||\n\t\terror \"setfattr (2)\"\n\tchattr +i $DIR/$tdir/toopen || error \"chattr (2)\"\n\tlsattr $DIR/$tdir/toopen || error \"lsattr (2)\"\n\tchattr -i $DIR/$tdir/toopen || error \"chattr (2)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl2 || error \"symlink (2)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl2 || error \"hardlink (2)\"\n\techo 3 > /proc/sys/vm/drop_caches\n\n\t# store wrong sepol in nodemap\n\tsepol=\"0:policy:0:0000000000000000000000000000000000000000000000000000000000000000\"\n\tdo_facet mgs $LCTL set_param -P nodemap.c0.sepol=\"$sepol\"\n\tcheck_nodemap c0 sepol $sepol\n\n\t# metadata ops with sepol\n\ttouch $DIR/$tdir/f4 && error \"touch (3)\"\n\tlfs setstripe -c1 $DIR/$tdir/f5 && error \"lfs setstripe (3)\"\n\tmkdir $DIR/$tdir/d4 && error \"mkdir (3)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d5 && error \"lfs setdirstripe (3)\"\n\tcat $DIR/$tdir/toopen && error \"cat (3)\"\n\trm -f $DIR/$tdir/ftoremove2 && error \"rm (3)\"\n\trmdir $DIR/$tdir/dtoremove2 && error \"rmdir (3)\"\n\tmv $DIR/$tdir/ftorename2 $DIR/$tdir/ftorename && error \"mv (5)\"\n\tmv $DIR/$tdir/dtorename2 $DIR/$tdir/dtorename && error \"mv (6)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen && error \"getfattr (3)\"\n\tsetfattr -n user.myattr -v myval3 $DIR/$tdir/toopen &&\n\t\terror \"setfattr (3)\"\n\tchattr +i $DIR/$tdir/toopen && error \"chattr (3)\"\n\tlsattr $DIR/$tdir/toopen && error \"lsattr (3)\"\n\tchattr -i $DIR/$tdir/toopen && error \"chattr (3)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl3 && error \"symlink (3)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl3 && error \"hardlink (3)\"\n\n\t# reset correct sepol\n\tsepol=$(l_getsepol | cut -d':' -f2- | xargs)\n\tdo_facet mgs $LCTL set_param -P nodemap.c0.sepol=\"$sepol\"\n\tcheck_nodemap c0 sepol $sepol\n\n\t# metadata ops with sepol every 1000 seconds only\n\techo 1000 > /sys/module/ptlrpc/parameters/send_sepol\n\tlocal before=$(date +%s)\n\ttouch $DIR/$tdir/f6 || error \"touch (4)\"\n\tlfs setstripe -c1 $DIR/$tdir/f7 || error \"lfs setstripe (4)\"\n\tmkdir $DIR/$tdir/d6 || error \"mkdir (4)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d7 || error \"lfs setdirstripe (4)\"\n\tcat $DIR/$tdir/toopen || error \"cat (4)\"\n\trm -f $DIR/$tdir/ftoremove2 || error \"rm (4)\"\n\trmdir $DIR/$tdir/dtoremove2 || error \"rmdir (4)\"\n\tmv $DIR/$tdir/ftorename2 $DIR/$tdir/ftorename || error \"mv (7)\"\n\tmv $DIR/$tdir/dtorename2 $DIR/$tdir/dtorename || error \"mv (8)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen || error \"getfattr (4)\"\n\tsetfattr -n user.myattr -v myval3 $DIR/$tdir/toopen ||\n\t\terror \"setfattr (4)\"\n\tchattr +i $DIR/$tdir/toopen || error \"chattr (4)\"\n\tlsattr $DIR/$tdir/toopen || error \"lsattr (4)\"\n\tchattr -i $DIR/$tdir/toopen || error \"chattr (4)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl4 || error \"symlink (4)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl4 || error \"hardlink (4)\"\n\techo 3 > /proc/sys/vm/drop_caches\n\n\t# change one SELinux boolean value\n\tsebool=$(getsebool deny_ptrace | awk '{print $3}')\n\tif [ \"$sebool\" == \"off\" ]; then\n\t\tsetsebool -P deny_ptrace on\n\telse\n\t\tsetsebool -P deny_ptrace off\n\tfi\n\n\t# sepol should not be checked yet, so metadata ops without matching\n\t# sepol should succeed\n\ttouch $DIR/$tdir/f8 || error \"touch (5)\"\n\tlfs setstripe -c1 $DIR/$tdir/f9 || error \"lfs setstripe (5)\"\n\tmkdir $DIR/$tdir/d8 || error \"mkdir (5)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d9 || error \"lfs setdirstripe (5)\"\n\tcat $DIR/$tdir/toopen || error \"cat (5)\"\n\trm -f $DIR/$tdir/ftoremove3 || error \"rm (5)\"\n\trmdir $DIR/$tdir/dtoremove3 || error \"rmdir (5)\"\n\tmv $DIR/$tdir/ftorename $DIR/$tdir/ftorename2 || error \"mv (9)\"\n\tmv $DIR/$tdir/dtorename $DIR/$tdir/dtorename2 || error \"mv (10)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen || error \"getfattr (5)\"\n\tsetfattr -n user.myattr -v myval4 $DIR/$tdir/toopen ||\n\t\terror \"setfattr (5)\"\n\tchattr +i $DIR/$tdir/toopen || error \"chattr (5)\"\n\tlsattr $DIR/$tdir/toopen || error \"lsattr (5)\"\n\tchattr -i $DIR/$tdir/toopen || error \"chattr (5)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl5 || error \"symlink (5)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl5 || error \"hardlink (5)\"\n\techo 3 > /proc/sys/vm/drop_caches\n\n\tlocal after=$(date +%s)\n\t# change send_sepol to a smaller, already expired, value\n\techo $((after-before-1)) > /sys/module/ptlrpc/parameters/send_sepol\n\t# metadata ops without matching sepol: should fail now\n\ttouch $DIR/$tdir/f10 && error \"touch (6)\"\n\tlfs setstripe -c1 $DIR/$tdir/f11 && error \"lfs setstripe (6)\"\n\tmkdir $DIR/$tdir/d10 && error \"mkdir (6)\"\n\tlfs setdirstripe -i0 -c1 $DIR/$tdir/d11 && error \"lfs setdirstripe (6)\"\n\tcat $DIR/$tdir/toopen && error \"cat (6)\"\n\trm -f $DIR/$tdir/ftoremove4 && error \"rm (6)\"\n\trmdir $DIR/$tdir/dtoremove4 && error \"rmdir (6)\"\n\tmv $DIR/$tdir/ftorename2 $DIR/$tdir/ftorename && error \"mv (11)\"\n\tmv $DIR/$tdir/dtorename2 $DIR/$tdir/dtorename && error \"mv (12)\"\n\tgetfattr -n user.myattr $DIR/$tdir/toopen && error \"getfattr (6)\"\n\tsetfattr -n user.myattr -v myval5 $DIR/$tdir/toopen &&\n\t\terror \"setfattr (6)\"\n\tchattr +i $DIR/$tdir/toopen && error \"chattr (6)\"\n\tlsattr $DIR/$tdir/toopen && error \"lsattr (6)\"\n\tchattr -i $DIR/$tdir/toopen && error \"chattr (6)\"\n\tln -s $DIR/$tdir/toopen $DIR/$tdir/toopen_sl6 && error \"symlink (6)\"\n\tln $DIR/$tdir/toopen $DIR/$tdir/toopen_hl6 && error \"hardlink (6)\"\n\n\t# restore SELinux boolean value\n\tif [ \"$sebool\" == \"off\" ]; then\n\t\tsetsebool -P deny_ptrace off\n\telse\n\t\tsetsebool -P deny_ptrace on\n\tfi\n\n\t# remove nodemap\n\tremove_nodemap c0\n\techo 0 > /sys/module/ptlrpc/parameters/send_sepol\n\n\tif $GSS_SK; then\n\t\texport SK_UNIQUE_NM=false\n\tfi\n}\nrun_test 21b \"Send sepol for metadata ops\"\n\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 854}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run select tests by setting ONLY, or as arguments to the script.\n# Skip specific tests by setting EXCEPT.\n#\n# e.g. ONLY=\"22 23\" or ONLY=\"`seq 32 39`\" or EXCEPT=\"31\"\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\n# Check Grants after these tests\nGRANT_CHECK_LIST=\"$GRANT_CHECK_LIST 42a 42b 42c 42d 42e 63a 63b 64a 64b 64c 64d\"\n\nOSC=${OSC:-\"osc\"}\n\nCC=${CC:-cc}\nCREATETEST=${CREATETEST:-createtest}\nLVERIFY=${LVERIFY:-ll_dirstripe_verify}\nOPENFILE=${OPENFILE:-openfile}\nOPENUNLINK=${OPENUNLINK:-openunlink}\nREADS=${READS:-\"reads\"}\nMUNLINK=${MUNLINK:-munlink}\nSOCKETSERVER=${SOCKETSERVER:-socketserver}\nSOCKETCLIENT=${SOCKETCLIENT:-socketclient}\nMEMHOG=${MEMHOG:-memhog}\nDIRECTIO=${DIRECTIO:-directio}\nACCEPTOR_PORT=${ACCEPTOR_PORT:-988}\nDEF_STRIPE_COUNT=-1\nCHECK_GRANT=${CHECK_GRANT:-\"yes\"}\nGRANT_CHECK_LIST=${GRANT_CHECK_LIST:-\"\"}\nexport PARALLEL=${PARALLEL:-\"no\"}\n\nTRACE=${TRACE:-\"\"}\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\nLUSTRE_TESTS_API_DIR=${LUSTRE_TESTS_API_DIR:-${LUSTRE}/tests/clientapi}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITY_EXCEPT \"\n# bug number for skipped test: LU-9693 LU-6493 LU-9693\nALWAYS_EXCEPT+=\"               42a     42b     42c \"\n# bug number:    LU-8411 LU-9054\nALWAYS_EXCEPT+=\" 407     312\"\n\nif $SHARED_KEY; then\n\t# bug number:    LU-9795 LU-9795 LU-9795 LU-9795\n\tALWAYS_EXCEPT+=\" 17n     60a     133g    300f\"\nfi\n\nselinux_status=$(getenforce)\nif [ \"$selinux_status\" != \"Disabled\" ]; then\n\t# bug number:\n\tALWAYS_EXCEPT+=\"\"\nfi\n\n# skip the grant tests for ARM until they are fixed\nif [[ $(uname -m) = aarch64 ]]; then\n\t# bug number:\t LU-11596\n\tALWAYS_EXCEPT+=\" $GRANT_CHECK_LIST\"\n\t# bug number:\t LU-11671 LU-11667\n\tALWAYS_EXCEPT+=\" 45\t  317\"\nfi\n\n# skip nfs tests on kernels >= 4.14.0 until they are fixed\nif [ $LINUX_VERSION_CODE -ge $(version_code 4.14.0) ]; then\n\t# bug number:\tLU-12661\n\tALWAYS_EXCEPT+=\" 817\"\nfi\n# skip cgroup tests on RHEL8.1 kernels until they are fixed\nif (( $LINUX_VERSION_CODE >= $(version_code 4.18.0) &&\n      $LINUX_VERSION_CODE <  $(version_code 5.4.0) )); then\n\t# bug number:\tLU-13063\n\tALWAYS_EXCEPT+=\" 411\"\nfi\n\n#                                  5          12     8   12  (min)\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"27m 64b 68 71 115 135 136 300o\"\n\nif [ \"$mds1_FSTYPE\" = \"zfs\" ]; then\n\t# bug number for skipped test:\n\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT  \"\n\t#                                               13    (min)\"\n\t[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"$EXCEPT_SLOW 51b\"\nfi\n\n# Get the SLES distro version\n#\n# Returns a version string that should only be used in comparing\n# strings returned by version_code()\nsles_version_code()\n{\n\tlocal version=$(grep VERSION_ID /etc/os-release | cut -d'\"' -f2)\n\n\t# All SuSE Linux versions have one decimal. version_code expects two\n\tlocal sles_version=$version.0\n\tversion_code $sles_version\n}\n\n# Check if we are running on Ubuntu or SLES so we can make decisions on\n# what tests to run\nif [ -r /etc/SuSE-release ]; then\n\tsles_version=$(sles_version_code)\n\t[ $sles_version -lt $(version_code 11.4.0) ] &&\n\t\t# bug number for skipped test: LU-4341\n\t\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT  170\"\n\t[ $sles_version -lt $(version_code 12.0.0) ] &&\n\t\t# bug number for skipped test: LU-3703\n\t\tALWAYS_EXCEPT=\"$ALWAYS_EXCEPT  234\"\nelif [ -r /etc/os-release ]; then\n\tif grep -qi ubuntu /etc/os-release; then\n\t\tubuntu_version=$(version_code $(sed -n -e 's/\"//g' \\\n\t\t\t\t\t\t-e 's/^VERSION=//p' \\\n\t\t\t\t\t\t/etc/os-release |\n\t\t\t\t\t\tawk '{ print $1 }'))\n\n\t\tif [[ $ubuntu_version -gt $(version_code 16.0.0) ]]; then\n\t\t\t# bug number for skipped test:\n\t\t\t#                LU-10334 LU-10366\n\t\t\tALWAYS_EXCEPT+=\" 103a\t  410\"\n\t\tfi\n\tfi\nfi\n\nbuild_test_filter\nFAIL_ON_ERROR=false\n\ncleanup() {\n\techo -n \"cln..\"\n\tpgrep ll_sa > /dev/null && { echo \"There are ll_sa thread not exit!\"; exit 20; }\n\tcleanupall ${FORCE} $* || { echo \"FAILed to clean up\"; exit 20; }\n}\nsetup() {\n\techo -n \"mnt..\"\n        load_modules\n\tsetupall || exit 10\n\techo \"done\"\n}\n\ncheck_swap_layouts_support()\n{\n\t$LCTL get_param -n llite.*.sbi_flags | grep -q layout ||\n\t\tskip \"Does not support layout lock.\"\n}\n\ncheck_swap_layout_no_dom()\n{\n\tlocal FOLDER=$1\n\tlocal SUPP=$(lfs getstripe $FOLDER | grep \"pattern:       mdt\" | wc -l)\n\t[ $SUPP -eq 0 ] || skip \"layout swap does not support DOM files so far\"\n}\n\ncheck_and_setup_lustre\nDIR=${DIR:-$MOUNT}\nassert_DIR\n\nMAXFREE=${MAXFREE:-$((200000 * $OSTCOUNT))}\n\n[ -f $DIR/d52a/foo ] && chattr -a $DIR/d52a/foo\n[ -f $DIR/d52b/foo ] && chattr -i $DIR/d52b/foo\nrm -rf $DIR/[Rdfs][0-9]*\n\n# $RUNAS_ID may get set incorrectly somewhere else\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] &&\n\terror \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\n\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\n\nif [ \"${ONLY}\" = \"MOUNT\" ] ; then\n\techo \"Lustre is up, please go on\"\n\texit\nfi\n\necho \"preparing for tests involving mounts\"\nEXT2_DEV=${EXT2_DEV:-$TMP/SANITY.LOOP}\ntouch $EXT2_DEV\nmke2fs -j -F $EXT2_DEV 8000 > /dev/null\necho # add a newline after mke2fs.\n\numask 077\n\nOLDDEBUG=$(lctl get_param -n debug 2> /dev/null)\nlctl set_param debug=-1 2> /dev/null || true\ntest_0a() {\n\ttouch $DIR/$tfile\n\t$CHECKSTAT -t file $DIR/$tfile || error \"$tfile is not a file\"\n\trm $DIR/$tfile\n\t$CHECKSTAT -a $DIR/$tfile || error \"$tfile was not removed\"\n}\nrun_test 0a \"touch; rm =====================\"\n\ntest_0b() {\n\tchmod 0755 $DIR || error \"chmod 0755 $DIR failed\"\n\t$CHECKSTAT -p 0755 $DIR || error \"$DIR permission is not 0755\"\n}\nrun_test 0b \"chmod 0755 $DIR =============================\"\n\ntest_0c() {\n\t$LCTL get_param mdc.*.import | grep \"state: FULL\" ||\n\t\terror \"import not FULL\"\n\t$LCTL get_param mdc.*.import | grep \"target: $FSNAME-MDT\" ||\n\t\terror \"bad target\"\n}\nrun_test 0c \"check import proc\"\n\ntest_0d() { # LU-3397\n\t[ $MGS_VERSION -lt $(version_code 2.10.57) ] &&\n\t\tskip \"proc exports not supported before 2.10.57\"\n\n\tlocal mgs_exp=\"mgs.MGS.exports\"\n\tlocal client_uuid=$($LCTL get_param -n mgc.*.uuid)\n\tlocal exp_client_nid\n\tlocal exp_client_version\n\tlocal exp_val\n\tlocal imp_val\n\tlocal temp_imp=$DIR/$tfile.import\n\tlocal temp_exp=$DIR/$tfile.export\n\n\t# save mgc import file to $temp_imp\n\t$LCTL get_param mgc.*.import | tee $temp_imp\n\t# Check if client uuid is found in MGS export\n\tfor exp_client_nid in $(do_facet mgs $LCTL get_param -N $mgs_exp.*); do\n\t\t[ $(do_facet mgs $LCTL get_param -n $exp_client_nid.uuid) == \\\n\t\t\t$client_uuid ] &&\n\t\t\tbreak;\n\tdone\n\t# save mgs export file to $temp_exp\n\tdo_facet mgs $LCTL get_param $exp_client_nid.export | tee $temp_exp\n\n\t# Compare the value of field \"connect_flags\"\n\timp_val=$(grep \"connect_flags\" $temp_imp)\n\texp_val=$(grep \"connect_flags\" $temp_exp)\n\t[ \"$exp_val\" == \"$imp_val\" ] ||\n\t\terror \"export flags '$exp_val' != import flags '$imp_val'\"\n\n\t# Compare the value of client version\n\texp_client_version=$(awk '/target_version:/ { print $2 }' $temp_exp)\n\texp_val=$(version_code $exp_client_version)\n\timp_val=$CLIENT_VERSION\n\t[ \"$exp_val\" == \"$imp_val\" ] ||\n\t\terror \"export client version '$exp_val' != '$imp_val'\"\n}\nrun_test 0d \"check export proc =============================\"\n\ntest_1() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d2\n\tmkdir $DIR/$tdir/d2 && error \"we expect EEXIST, but not returned\"\n\t$CHECKSTAT -t dir $DIR/$tdir/d2 || error \"$tdir/d2 is not a dir\"\n\trmdir $DIR/$tdir/d2\n\trmdir $DIR/$tdir\n\t$CHECKSTAT -a $DIR/$tdir || error \"$tdir was not removed\"\n}\nrun_test 1 \"mkdir; remkdir; rmdir\"\n\ntest_2() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile || error \"touch $tdir/$tfile failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile || error \"$tdir/$tfile not a file\"\n\trm -r $DIR/$tdir\n\t$CHECKSTAT -a $DIR/$tdir/$tfile || error \"$tdir/$file is not removed\"\n}\nrun_test 2 \"mkdir; touch; rmdir; check file\"\n\ntest_3() {\n\ttest_mkdir $DIR/$tdir\n\t$CHECKSTAT -t dir $DIR/$tdir || error \"$tdir is not a directory\"\n\ttouch $DIR/$tdir/$tfile\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile || error \"$tdir/$tfile not a file\"\n\trm -r $DIR/$tdir\n\t$CHECKSTAT -a $DIR/$tdir || error \"$tdir is not removed\"\n}\nrun_test 3 \"mkdir; touch; rmdir; check dir\"\n\n# LU-4471 - failed rmdir on remote directories still removes directory on MDT0\ntest_4() {\n\ttest_mkdir -i 1 $DIR/$tdir\n\n\ttouch $DIR/$tdir/$tfile ||\n\t\terror \"Create file under remote directory failed\"\n\n\trmdir $DIR/$tdir &&\n\t\terror \"Expect error removing in-use dir $DIR/$tdir\"\n\n\ttest -d $DIR/$tdir || error \"Remote directory disappeared\"\n\n\trm -rf $DIR/$tdir || error \"remove remote dir error\"\n}\nrun_test 4 \"mkdir; touch dir/file; rmdir; checkdir (expect error)\"\n\ntest_5() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d2\n\tchmod 0707 $DIR/$tdir/d2 || error \"chmod 0707 $tdir/d2 failed\"\n\t$CHECKSTAT -t dir -p 0707 $DIR/$tdir/d2 || error \"$tdir/d2 not mode 707\"\n\t$CHECKSTAT -t dir $DIR/$tdir/d2 || error \"$tdir/d2 is not a directory\"\n}\nrun_test 5 \"mkdir .../d5 .../d5/d2; chmod .../d5/d2\"\n\ntest_6a() {\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\tchmod 0666 $DIR/$tfile || error \"chmod 0666 $tfile failed\"\n\t$CHECKSTAT -t file -p 0666 -u \\#$UID $DIR/$tfile ||\n\t\terror \"$tfile does not have perm 0666 or UID $UID\"\n\t$RUNAS chmod 0444 $DIR/$tfile && error \"chmod $tfile worked on UID $UID\"\n\t$CHECKSTAT -t file -p 0666 -u \\#$UID $DIR/$tfile ||\n\t\terror \"$tfile should be 0666 and owned by UID $UID\"\n}\nrun_test 6a \"touch f6a; chmod f6a; $RUNAS chmod f6a (should return error) ==\"\n\ntest_6c() {\n\t[ $RUNAS_ID -eq $UID ] && skip_env \"RUNAS_ID = UID = $UID\"\n\n\ttouch $DIR/$tfile\n\tchown $RUNAS_ID $DIR/$tfile || error \"chown $RUNAS_ID $file failed\"\n\t$CHECKSTAT -t file -u \\#$RUNAS_ID $DIR/$tfile ||\n\t\terror \"$tfile should be owned by UID $RUNAS_ID\"\n\t$RUNAS chown $UID $DIR/$tfile && error \"chown $UID $file succeeded\"\n\t$CHECKSTAT -t file -u \\#$RUNAS_ID $DIR/$tfile ||\n\t\terror \"$tfile should be owned by UID $RUNAS_ID\"\n}\nrun_test 6c \"touch f6c; chown f6c; $RUNAS chown f6c (should return error) ==\"\n\ntest_6e() {\n\t[ $RUNAS_ID -eq $UID ] && skip_env \"RUNAS_ID = UID = $UID\"\n\n\ttouch $DIR/$tfile\n\tchgrp $RUNAS_ID $DIR/$tfile || error \"chgrp $RUNAS_ID $file failed\"\n\t$CHECKSTAT -t file -u \\#$UID -g \\#$RUNAS_ID $DIR/$tfile ||\n\t\terror \"$tfile should be owned by GID $UID\"\n\t$RUNAS chgrp $UID $DIR/$tfile && error \"chgrp $UID $file succeeded\"\n\t$CHECKSTAT -t file -u \\#$UID -g \\#$RUNAS_ID $DIR/$tfile ||\n\t\terror \"$tfile should be owned by UID $UID and GID $RUNAS_ID\"\n}\nrun_test 6e \"touch+chgrp $tfile; $RUNAS chgrp $tfile (should return error)\"\n\ntest_6g() {\n\t[ $RUNAS_ID -eq $UID ] && skip_env \"RUNAS_ID = UID = $UID\"\n\n\ttest_mkdir $DIR/$tdir\n\tchmod 777 $DIR/$tdir || error \"chmod 0777 $tdir failed\"\n\t$RUNAS mkdir $DIR/$tdir/d || error \"mkdir $tdir/d failed\"\n\tchmod g+s $DIR/$tdir/d || error \"chmod g+s $tdir/d failed\"\n\ttest_mkdir $DIR/$tdir/d/subdir\n\t$CHECKSTAT -g \\#$RUNAS_GID $DIR/$tdir/d/subdir ||\n\t\terror \"$tdir/d/subdir should be GID $RUNAS_GID\"\n\tif [[ $MDSCOUNT -gt 1 ]]; then\n\t\t# check remote dir sgid inherite\n\t\t$LFS mkdir -i 0 $DIR/$tdir.local ||\n\t\t\terror \"mkdir $tdir.local failed\"\n\t\tchmod g+s $DIR/$tdir.local ||\n\t\t\terror \"chmod $tdir.local failed\"\n\t\tchgrp $RUNAS_GID $DIR/$tdir.local ||\n\t\t\terror \"chgrp $tdir.local failed\"\n\t\t$LFS mkdir -i 1 $DIR/$tdir.local/$tdir.remote ||\n\t\t\terror \"mkdir $tdir.remote failed\"\n\t\t$CHECKSTAT -g \\#$RUNAS_GID $DIR/$tdir.local/$tdir.remote ||\n\t\t\terror \"$tdir.remote should be owned by $UID.$RUNAS_ID\"\n\t\t$CHECKSTAT -p 02755 $DIR/$tdir.local/$tdir.remote ||\n\t\t\terror \"$tdir.remote should be mode 02755\"\n\tfi\n}\nrun_test 6g \"verify new dir in sgid dir inherits group\"\n\ntest_6h() { # bug 7331\n\t[ $RUNAS_ID -eq $UID ] && skip_env \"RUNAS_ID = UID = $UID\"\n\n\ttouch $DIR/$tfile || error \"touch failed\"\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tfile || error \"initial chown failed\"\n\t$RUNAS -G$RUNAS_GID chown $RUNAS_ID:0 $DIR/$tfile &&\n\t\terror \"chown $RUNAS_ID:0 $tfile worked as GID $RUNAS_GID\"\n\t$CHECKSTAT -t file -u \\#$RUNAS_ID -g \\#$RUNAS_GID $DIR/$tfile ||\n\t\terror \"$tdir/$tfile should be UID $RUNAS_UID GID $RUNAS_GID\"\n}\nrun_test 6h \"$RUNAS chown RUNAS_ID.0 .../$tfile (should return error)\"\n\ntest_7a() {\n\ttest_mkdir $DIR/$tdir\n\t$MCREATE $DIR/$tdir/$tfile\n\tchmod 0666 $DIR/$tdir/$tfile\n\t$CHECKSTAT -t file -p 0666 $DIR/$tdir/$tfile ||\n\t\terror \"$tdir/$tfile should be mode 0666\"\n}\nrun_test 7a \"mkdir .../d7; mcreate .../d7/f; chmod .../d7/f ====\"\n\ntest_7b() {\n\tif [ ! -d $DIR/$tdir ]; then\n\t\ttest_mkdir $DIR/$tdir\n\tfi\n\t$MCREATE $DIR/$tdir/$tfile\n\techo -n foo > $DIR/$tdir/$tfile\n\t[ \"$(cat $DIR/$tdir/$tfile)\" = \"foo\" ] || error \"$tdir/$tfile not 'foo'\"\n\t$CHECKSTAT -t file -s 3 $DIR/$tdir/$tfile || error \"$tfile size not 3\"\n}\nrun_test 7b \"mkdir .../d7; mcreate d7/f2; echo foo > d7/f2 =====\"\n\ntest_8() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\tchmod 0666 $DIR/$tdir/$tfile\n\t$CHECKSTAT -t file -p 0666 $DIR/$tdir/$tfile ||\n\t\terror \"$tfile mode not 0666\"\n}\nrun_test 8 \"mkdir .../d8; touch .../d8/f; chmod .../d8/f =======\"\n\ntest_9() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d2\n\ttest_mkdir $DIR/$tdir/d2/d3\n\t$CHECKSTAT -t dir $DIR/$tdir/d2/d3 || error \"$tdir/d2/d3 not a dir\"\n}\nrun_test 9 \"mkdir .../d9 .../d9/d2 .../d9/d2/d3 ================\"\n\ntest_10() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d2\n\ttouch $DIR/$tdir/d2/$tfile\n\t$CHECKSTAT -t file $DIR/$tdir/d2/$tfile ||\n\t\terror \"$tdir/d2/$tfile not a file\"\n}\nrun_test 10 \"mkdir .../d10 .../d10/d2; touch .../d10/d2/f ======\"\n\ntest_11() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d2\n\tchmod 0666 $DIR/$tdir/d2\n\tchmod 0705 $DIR/$tdir/d2\n\t$CHECKSTAT -t dir -p 0705 $DIR/$tdir/d2 ||\n\t\terror \"$tdir/d2 mode not 0705\"\n}\nrun_test 11 \"mkdir .../d11 d11/d2; chmod .../d11/d2 ============\"\n\ntest_12() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\tchmod 0666 $DIR/$tdir/$tfile\n\tchmod 0654 $DIR/$tdir/$tfile\n\t$CHECKSTAT -t file -p 0654 $DIR/$tdir/$tfile ||\n\t\terror \"$tdir/d2 mode not 0654\"\n}\nrun_test 12 \"touch .../d12/f; chmod .../d12/f .../d12/f ========\"\n\ntest_13() {\n\ttest_mkdir $DIR/$tdir\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile count=10\n\t>  $DIR/$tdir/$tfile\n\t$CHECKSTAT -t file -s 0 $DIR/$tdir/$tfile ||\n\t\terror \"$tdir/$tfile size not 0 after truncate\"\n}\nrun_test 13 \"creat .../d13/f; dd .../d13/f; > .../d13/f ========\"\n\ntest_14() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\trm $DIR/$tdir/$tfile\n\t$CHECKSTAT -a $DIR/$tdir/$tfile || error \"$tdir/$tfile not removed\"\n}\nrun_test 14 \"touch .../d14/f; rm .../d14/f; rm .../d14/f =======\"\n\ntest_15() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\tmv $DIR/$tdir/$tfile $DIR/$tdir/${tfile}_2\n\t$CHECKSTAT -t file $DIR/$tdir/${tfile}_2 ||\n\t\terror \"$tdir/${tfile_2} not a file after rename\"\n\trm $DIR/$tdir/${tfile}_2 || error \"unlink failed after rename\"\n}\nrun_test 15 \"touch .../d15/f; mv .../d15/f .../d15/f2 ==========\"\n\ntest_16() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\trm -rf $DIR/$tdir/$tfile\n\t$CHECKSTAT -a $DIR/$tdir/$tfile || error \"$tdir/$tfile not removed\"\n}\nrun_test 16 \"touch .../d16/f; rm -rf .../d16/f\"\n\ntest_17a() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\tln -s $DIR/$tdir/$tfile $DIR/$tdir/l-exist\n\tls -l $DIR/$tdir\n\t$CHECKSTAT -l $DIR/$tdir/$tfile $DIR/$tdir/l-exist ||\n\t\terror \"$tdir/l-exist not a symlink\"\n\t$CHECKSTAT -f -t f $DIR/$tdir/l-exist ||\n\t\terror \"$tdir/l-exist not referencing a file\"\n\trm -f $DIR/$tdir/l-exist\n\t$CHECKSTAT -a $DIR/$tdir/l-exist || error \"$tdir/l-exist not removed\"\n}\nrun_test 17a \"symlinks: create, remove (real)\"\n\ntest_17b() {\n\ttest_mkdir $DIR/$tdir\n\tln -s no-such-file $DIR/$tdir/l-dangle\n\tls -l $DIR/$tdir\n\t$CHECKSTAT -l no-such-file $DIR/$tdir/l-dangle ||\n\t\terror \"$tdir/l-dangle not referencing no-such-file\"\n\t$CHECKSTAT -fa $DIR/$tdir/l-dangle ||\n\t\terror \"$tdir/l-dangle not referencing non-existent file\"\n\trm -f $DIR/$tdir/l-dangle\n\t$CHECKSTAT -a $DIR/$tdir/l-dangle || error \"$tdir/l-dangle not removed\"\n}\nrun_test 17b \"symlinks: create, remove (dangling)\"\n\ntest_17c() { # bug 3440 - don't save failed open RPC for replay\n\ttest_mkdir $DIR/$tdir\n\tln -s foo $DIR/$tdir/$tfile\n\tcat $DIR/$tdir/$tfile && error \"opened non-existent symlink\" || true\n}\nrun_test 17c \"symlinks: open dangling (should return error)\"\n\ntest_17d() {\n\ttest_mkdir $DIR/$tdir\n\tln -s foo $DIR/$tdir/$tfile\n\ttouch $DIR/$tdir/$tfile || error \"creating to new symlink\"\n}\nrun_test 17d \"symlinks: create dangling\"\n\ntest_17e() {\n\ttest_mkdir $DIR/$tdir\n\tlocal foo=$DIR/$tdir/$tfile\n\tln -s $foo $foo || error \"create symlink failed\"\n\tls -l $foo || error \"ls -l failed\"\n\tls $foo && error \"ls not failed\" || true\n}\nrun_test 17e \"symlinks: create recursive symlink (should return error)\"\n\ntest_17f() {\n\ttest_mkdir $DIR/$tdir\n\tln -s 1234567890/2234567890/3234567890/4234567890 $DIR/$tdir/111\n\tln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890 $DIR/$tdir/222\n\tln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890 $DIR/$tdir/333\n\tln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890 $DIR/$tdir/444\n\tln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890/c234567890/d234567890/f234567890 $DIR/$tdir/555\n\tln -s 1234567890/2234567890/3234567890/4234567890/5234567890/6234567890/7234567890/8234567890/9234567890/a234567890/b234567890/c234567890/d234567890/f234567890/aaaaaaaaaa/bbbbbbbbbb/cccccccccc/dddddddddd/eeeeeeeeee/ffffffffff/ $DIR/$tdir/666\n\tls -l  $DIR/$tdir\n}\nrun_test 17f \"symlinks: long and very long symlink name\"\n\n# str_repeat(S, N) generate a string that is string S repeated N times\nstr_repeat() {\n\tlocal s=$1\n\tlocal n=$2\n\tlocal ret=''\n\twhile [ $((n -= 1)) -ge 0 ]; do\n\t\tret=$ret$s\n\tdone\n\techo $ret\n}\n\n# Long symlinks and LU-2241\ntest_17g() {\n\ttest_mkdir $DIR/$tdir\n\tlocal TESTS=\"59 60 61 4094 4095\"\n\n\t# Fix for inode size boundary in 2.1.4\n\t[ $MDS1_VERSION -lt $(version_code 2.1.4) ] &&\n\t\tTESTS=\"4094 4095\"\n\n\t# Patch not applied to 2.2 or 2.3 branches\n\t[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&\n\t[ $MDS1_VERSION -le $(version_code 2.3.55) ] &&\n\t\tTESTS=\"4094 4095\"\n\n\tfor i in $TESTS; do\n\t\tlocal SYMNAME=$(str_repeat 'x' $i)\n\t\tln -s $SYMNAME $DIR/$tdir/f$i || error \"failed $i-char symlink\"\n\t\treadlink $DIR/$tdir/f$i\t|| error \"failed $i-char readlink\"\n\tdone\n}\nrun_test 17g \"symlinks: really long symlink name and inode boundaries\"\n\ntest_17h() { #bug 17378\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal mdt_idx\n\n\ttest_mkdir $DIR/$tdir\n\tmdt_idx=$($LFS getdirstripe -i $DIR/$tdir)\n\t$LFS setstripe -c -1 $DIR/$tdir\n\t#define OBD_FAIL_MDS_LOV_PREP_CREATE 0x141\n\tdo_facet mds$((mdt_idx + 1)) lctl set_param fail_loc=0x80000141\n\ttouch $DIR/$tdir/$tfile || true\n}\nrun_test 17h \"create objects: lov_free_memmd() doesn't lbug\"\n\ntest_17i() { #bug 20018\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal foo=$DIR/$tdir/$tfile\n\tlocal mdt_idx\n\n\ttest_mkdir -c1 $DIR/$tdir\n\tmdt_idx=$($LFS getdirstripe -i $DIR/$tdir)\n\tln -s $foo $foo || error \"create symlink failed\"\n#define OBD_FAIL_MDS_READLINK_EPROTO     0x143\n\tdo_facet mds$((mdt_idx + 1)) lctl set_param fail_loc=0x80000143\n\tls -l $foo && error \"error not detected\"\n\treturn 0\n}\nrun_test 17i \"don't panic on short symlink (should return error)\"\n\ntest_17k() { #bug 22301\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ -z \"$(which rsync 2>/dev/null)\" ]] &&\n\t\tskip \"no rsync command\"\n\trsync --help | grep -q xattr ||\n\t\tskip_env \"$(rsync --version | head -n1) does not support xattrs\"\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir.new\n\ttouch $DIR/$tdir/$tfile\n\tln -s $DIR/$tdir/$tfile $DIR/$tdir/$tfile.lnk\n\trsync -av -X $DIR/$tdir/ $DIR/$tdir.new ||\n\t\terror \"rsync failed with xattrs enabled\"\n}\nrun_test 17k \"symlinks: rsync with xattrs enabled\"\n\ntest_17l() { # LU-279\n\t[[ -z \"$(which getfattr 2>/dev/null)\" ]] &&\n\t\tskip \"no getfattr command\"\n\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\tln -s $DIR/$tdir/$tfile $DIR/$tdir/$tfile.lnk\n\tfor path in \"$DIR/$tdir\" \"$DIR/$tdir/$tfile\" \"$DIR/$tdir/$tfile.lnk\"; do\n\t\t# -h to not follow symlinks. -m '' to list all the xattrs.\n\t\t# grep to remove first line: '# file: $path'.\n\t\tfor xattr in `getfattr -hm '' $path 2>/dev/null | grep -v '^#'`;\n\t\tdo\n\t\t\tlgetxattr_size_check $path $xattr ||\n\t\t\t\terror \"lgetxattr_size_check $path $xattr failed\"\n\t\tdone\n\tdone\n}\nrun_test 17l \"Ensure lgetxattr's returned xattr size is consistent\"\n\n# LU-1540\ntest_17m() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&\n\t[ $MDS1_VERSION -le $(version_code 2.2.93) ] &&\n\t\tskip \"MDS 2.2.0-2.2.93 do not NUL-terminate symlinks\"\n\n\tlocal short_sym=\"0123456789\"\n\tlocal wdir=$DIR/$tdir\n\tlocal i\n\n\ttest_mkdir $wdir\n\tlong_sym=$short_sym\n\t# create a long symlink file\n\tfor ((i = 0; i < 4; ++i)); do\n\t\tlong_sym=${long_sym}${long_sym}\n\tdone\n\n\techo \"create 512 short and long symlink files under $wdir\"\n\tfor ((i = 0; i < 256; ++i)); do\n\t\tln -sf ${long_sym}\"a5a5\" $wdir/long-$i\n\t\tln -sf ${short_sym}\"a5a5\" $wdir/short-$i\n\tdone\n\n\techo \"erase them\"\n\trm -f $wdir/*\n\tsync\n\twait_delete_completed\n\n\techo \"recreate the 512 symlink files with a shorter string\"\n\tfor ((i = 0; i < 512; ++i)); do\n\t\t# rewrite the symlink file with a shorter string\n\t\tln -sf ${long_sym} $wdir/long-$i || error \"long_sym failed\"\n\t\tln -sf ${short_sym} $wdir/short-$i || error \"short_sym failed\"\n\tdone\n\n\tlocal mds_index=$(($($LFS getstripe -m $wdir) + 1))\n\tlocal devname=$(mdsdevname $mds_index)\n\n\techo \"stop and checking mds${mds_index}:\"\n\t# e2fsck should not return error\n\tstop mds${mds_index}\n\trun_e2fsck $(facet_active_host mds${mds_index}) $devname -n\n\trc=$?\n\n\tstart mds${mds_index} $devname $MDS_MOUNT_OPTS ||\n\t\terror \"start mds${mds_index} failed\"\n\tdf $MOUNT > /dev/null 2>&1\n\t[ $rc -eq 0 ] ||\n\t\terror \"e2fsck detected error for short/long symlink: rc=$rc\"\n\trm -f $wdir/*\n}\nrun_test 17m \"run e2fsck against MDT which contains short/long symlink\"\n\ncheck_fs_consistency_17n() {\n\tlocal mdt_index\n\tlocal rc=0\n\n\t# create/unlink in 17n only change 2 MDTs(MDT1/MDT2),\n\t# so it only check MDT1/MDT2 instead of all of MDTs.\n\tfor mdt_index in 1 2; do\n\t\tlocal devname=$(mdsdevname $mdt_index)\n\t\t# e2fsck should not return error\n\t\tstop mds${mdt_index}\n\t\trun_e2fsck $(facet_active_host mds$mdt_index) $devname -n ||\n\t\t\trc=$((rc + $?))\n\n\t\tstart mds${mdt_index} $devname $MDS_MOUNT_OPTS ||\n\t\t\terror \"mount mds$mdt_index failed\"\n\t\tdf $MOUNT > /dev/null 2>&1\n\tdone\n\treturn $rc\n}\n\ntest_17n() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -ge $(version_code 2.2.0) ] &&\n\t[ $MDS1_VERSION -le $(version_code 2.2.93) ] &&\n\t\tskip \"MDS 2.2.0-2.2.93 do not NUL-terminate symlinks\"\n\n\tlocal i\n\n\ttest_mkdir $DIR/$tdir\n\tfor ((i=0; i<10; i++)); do\n\t\t$LFS mkdir -i1 -c2 $DIR/$tdir/remote_dir_${i} ||\n\t\t\terror \"create remote dir error $i\"\n\t\tcreatemany -o $DIR/$tdir/remote_dir_${i}/f 10 ||\n\t\t\terror \"create files under remote dir failed $i\"\n\tdone\n\n\tcheck_fs_consistency_17n ||\n\t\terror \"e2fsck report error after create files under remote dir\"\n\n\tfor ((i = 0; i < 10; i++)); do\n\t\trm -rf $DIR/$tdir/remote_dir_${i} ||\n\t\t\terror \"destroy remote dir error $i\"\n\tdone\n\n\tcheck_fs_consistency_17n ||\n\t\terror \"e2fsck report error after unlink files under remote dir\"\n\n\t[ $MDS1_VERSION -lt $(version_code 2.4.50) ] &&\n\t\tskip \"lustre < 2.4.50 does not support migrate mv\"\n\n\tfor ((i = 0; i < 10; i++)); do\n\t\tmkdir -p $DIR/$tdir/remote_dir_${i}\n\t\tcreatemany -o $DIR/$tdir/remote_dir_${i}/f 10 ||\n\t\t\terror \"create files under remote dir failed $i\"\n\t\t$LFS migrate --mdt-index 1 $DIR/$tdir/remote_dir_${i} ||\n\t\t\terror \"migrate remote dir error $i\"\n\tdone\n\tcheck_fs_consistency_17n || error \"e2fsck report error after migration\"\n\n\tfor ((i = 0; i < 10; i++)); do\n\t\trm -rf $DIR/$tdir/remote_dir_${i} ||\n\t\t\terror \"destroy remote dir error $i\"\n\tdone\n\n\tcheck_fs_consistency_17n || error \"e2fsck report error after unlink\"\n}\nrun_test 17n \"run e2fsck against master/slave MDT which contains remote dir\"\n\ntest_17o() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -lt $(version_code 2.3.64) ] &&\n\t\tskip \"Need MDS version at least 2.3.64\"\n\n\tlocal wdir=$DIR/${tdir}o\n\tlocal mdt_index\n\tlocal rc=0\n\n\ttest_mkdir $wdir\n\ttouch $wdir/$tfile\n\tmdt_index=$($LFS getstripe -m $wdir/$tfile)\n\tmdt_index=$((mdt_index + 1))\n\n\tcancel_lru_locks mdc\n\t#fail mds will wait the failover finish then set\n\t#following fail_loc to avoid interfer the recovery process.\n\tfail mds${mdt_index}\n\n\t#define OBD_FAIL_OSD_LMA_INCOMPAT 0x194\n\tdo_facet mds${mdt_index} lctl set_param fail_loc=0x194\n\tls -l $wdir/$tfile && rc=1\n\tdo_facet mds${mdt_index} lctl set_param fail_loc=0\n\t[[ $rc -eq 0 ]] || error \"stat file should fail\"\n}\nrun_test 17o \"stat file with incompat LMA feature\"\n\ntest_18() {\n\ttouch $DIR/$tfile || error \"Failed to touch $DIR/$tfile: $?\"\n\tls $DIR || error \"Failed to ls $DIR: $?\"\n}\nrun_test 18 \"touch .../f ; ls ... ==============================\"\n\ntest_19a() {\n\ttouch $DIR/$tfile\n\tls -l $DIR\n\trm $DIR/$tfile\n\t$CHECKSTAT -a $DIR/$tfile || error \"$tfile was not removed\"\n}\nrun_test 19a \"touch .../f19 ; ls -l ... ; rm .../f19 ===========\"\n\ntest_19b() {\n\tls -l $DIR/$tfile && error \"ls -l $tfile failed\"|| true\n}\nrun_test 19b \"ls -l .../f19 (should return error) ==============\"\n\ntest_19c() {\n\t[ $RUNAS_ID -eq $UID ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\n\t$RUNAS touch $DIR/$tfile && error \"create non-root file failed\" || true\n}\nrun_test 19c \"$RUNAS touch .../f19 (should return error) ==\"\n\ntest_19d() {\n\tcat $DIR/f19 && error || true\n}\nrun_test 19d \"cat .../f19 (should return error) ==============\"\n\ntest_20() {\n\ttouch $DIR/$tfile\n\trm $DIR/$tfile\n\ttouch $DIR/$tfile\n\trm $DIR/$tfile\n\ttouch $DIR/$tfile\n\trm $DIR/$tfile\n\t$CHECKSTAT -a $DIR/$tfile || error \"$tfile was not removed\"\n}\nrun_test 20 \"touch .../f ; ls -l ...\"\n\ntest_21() {\n\ttest_mkdir $DIR/$tdir\n\t[ -f $DIR/$tdir/dangle ] && rm -f $DIR/$tdir/dangle\n\tln -s dangle $DIR/$tdir/link\n\techo foo >> $DIR/$tdir/link\n\tcat $DIR/$tdir/dangle\n\t$CHECKSTAT -t link $DIR/$tdir/link || error \"$tdir/link not a link\"\n\t$CHECKSTAT -f -t file $DIR/$tdir/link ||\n\t\terror \"$tdir/link not linked to a file\"\n}\nrun_test 21 \"write to dangling link\"\n\ntest_22() {\n\tlocal wdir=$DIR/$tdir\n\ttest_mkdir $wdir\n\tchown $RUNAS_ID:$RUNAS_GID $wdir\n\t(cd $wdir || error \"cd $wdir failed\";\n\t\t$RUNAS tar cf - /etc/hosts /etc/sysconfig/network |\n\t\t$RUNAS tar xf -)\n\tls -lR $wdir/etc || error \"ls -lR $wdir/etc failed\"\n\t$CHECKSTAT -t dir $wdir/etc || error \"checkstat -t dir failed\"\n\t$CHECKSTAT -u \\#$RUNAS_ID -g \\#$RUNAS_GID $wdir/etc ||\n\t\terror \"checkstat -u failed\"\n}\nrun_test 22 \"unpack tar archive as non-root user\"\n\n# was test_23\ntest_23a() {\n\ttest_mkdir $DIR/$tdir\n\tlocal file=$DIR/$tdir/$tfile\n\n\topenfile -f O_CREAT:O_EXCL $file || error \"$file create failed\"\n\topenfile -f O_CREAT:O_EXCL $file &&\n\t\terror \"$file recreate succeeded\" || true\n}\nrun_test 23a \"O_CREAT|O_EXCL in subdir\"\n\ntest_23b() { # bug 18988\n\ttest_mkdir $DIR/$tdir\n\tlocal file=$DIR/$tdir/$tfile\n\n\trm -f $file\n\techo foo > $file || error \"write filed\"\n\techo bar >> $file || error \"append filed\"\n\t$CHECKSTAT -s 8 $file || error \"wrong size\"\n\trm $file\n}\nrun_test 23b \"O_APPEND check\"\n\n# LU-9409, size with O_APPEND and tiny writes\ntest_23c() {\n\tlocal file=$DIR/$tfile\n\n\t# single dd\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800\n\t$CHECKSTAT -s 6400 $file || error \"wrong size, expected 6400\"\n\trm -f $file\n\n\t# racing tiny writes\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800 &\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=800 &\n\twait\n\t$CHECKSTAT -s 12800 $file || error \"wrong size, expected 12800\"\n\trm -f $file\n\n\t#racing tiny & normal writes\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=4096 count=4 &\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=8 count=100 &\n\twait\n\t$CHECKSTAT -s 17184 $file || error \"wrong size, expected 17184\"\n\trm -f $file\n\n\t#racing tiny & normal writes 2, ugly numbers\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=4099 count=11 &\n\tdd conv=notrunc oflag=append if=/dev/zero of=$file bs=17 count=173 &\n\twait\n\t$CHECKSTAT -s 48030 $file || error \"wrong size, expected 48030\"\n\trm -f $file\n}\nrun_test 23c \"O_APPEND size checks for tiny writes\"\n\n# LU-11069 file offset is correct after appending writes\ntest_23d() {\n\tlocal file=$DIR/$tfile\n\tlocal offset\n\n\techo CentaurHauls > $file\n\toffset=$($MULTIOP $file oO_WRONLY:O_APPEND:w13Zp)\n\tif ((offset != 26)); then\n\t\terror \"wrong offset, expected 26, got '$offset'\"\n\tfi\n}\nrun_test 23d \"file offset is correct after appending writes\"\n\n# rename sanity\ntest_24a() {\n\techo '-- same directory rename'\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile.1\n\tmv $DIR/$tdir/$tfile.1 $DIR/$tdir/$tfile.2\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile.2 || error \"$tfile.2 not a file\"\n}\nrun_test 24a \"rename file to non-existent target\"\n\ntest_24b() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile.{1,2}\n\tmv $DIR/$tdir/$tfile.1 $DIR/$tdir/$tfile.2\n\t$CHECKSTAT -a $DIR/$tdir/$tfile.1 || error \"$tfile.1 exists\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile.2 || error \"$tfile.2 not a file\"\n}\nrun_test 24b \"rename file to existing target\"\n\ntest_24c() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/d$testnum.1\n\tmv $DIR/$tdir/d$testnum.1 $DIR/$tdir/d$testnum.2\n\t$CHECKSTAT -a $DIR/$tdir/d$testnum.1 || error \"d$testnum.1 exists\"\n\t$CHECKSTAT -t dir $DIR/$tdir/d$testnum.2 || error \"d$testnum.2 not dir\"\n}\nrun_test 24c \"rename directory to non-existent target\"\n\ntest_24d() {\n\ttest_mkdir -c1 $DIR/$tdir\n\ttest_mkdir -c1 $DIR/$tdir/d$testnum.1\n\ttest_mkdir -c1 $DIR/$tdir/d$testnum.2\n\tmrename $DIR/$tdir/d$testnum.1 $DIR/$tdir/d$testnum.2\n\t$CHECKSTAT -a $DIR/$tdir/d$testnum.1 || error \"d$testnum.1 exists\"\n\t$CHECKSTAT -t dir $DIR/$tdir/d$testnum.2 || error \"d$testnum.2 not dir\"\n}\nrun_test 24d \"rename directory to existing target\"\n\ntest_24e() {\n\techo '-- cross directory renames --'\n\ttest_mkdir $DIR/R5a\n\ttest_mkdir $DIR/R5b\n\ttouch $DIR/R5a/f\n\tmv $DIR/R5a/f $DIR/R5b/g\n\t$CHECKSTAT -a $DIR/R5a/f || error \"$DIR/R5a/f exists\"\n\t$CHECKSTAT -t file $DIR/R5b/g || error \"$DIR/R5b/g not file type\"\n}\nrun_test 24e \"touch .../R5a/f; rename .../R5a/f .../R5b/g ======\"\n\ntest_24f() {\n\ttest_mkdir $DIR/R6a\n\ttest_mkdir $DIR/R6b\n\ttouch $DIR/R6a/f $DIR/R6b/g\n\tmv $DIR/R6a/f $DIR/R6b/g\n\t$CHECKSTAT -a $DIR/R6a/f || error \"$DIR/R6a/f exists\"\n\t$CHECKSTAT -t file $DIR/R6b/g || error \"$DIR/R6b/g not file type\"\n}\nrun_test 24f \"touch .../R6a/f R6b/g; mv .../R6a/f .../R6b/g ====\"\n\ntest_24g() {\n\ttest_mkdir $DIR/R7a\n\ttest_mkdir $DIR/R7b\n\ttest_mkdir $DIR/R7a/d\n\tmv $DIR/R7a/d $DIR/R7b/e\n\t$CHECKSTAT -a $DIR/R7a/d || error \"$DIR/R7a/d exists\"\n\t$CHECKSTAT -t dir $DIR/R7b/e || error \"$DIR/R7b/e not dir type\"\n}\nrun_test 24g \"mkdir .../R7{a,b}/d; mv .../R7a/d .../R7b/e ======\"\n\ntest_24h() {\n\ttest_mkdir -c1 $DIR/R8a\n\ttest_mkdir -c1 $DIR/R8b\n\ttest_mkdir -c1 $DIR/R8a/d\n\ttest_mkdir -c1 $DIR/R8b/e\n\tmrename $DIR/R8a/d $DIR/R8b/e\n\t$CHECKSTAT -a $DIR/R8a/d || error \"$DIR/R8a/d exists\"\n\t$CHECKSTAT -t dir $DIR/R8b/e || error \"$DIR/R8b/e not dir type\"\n}\nrun_test 24h \"mkdir .../R8{a,b}/{d,e}; rename .../R8a/d .../R8b/e\"\n\ntest_24i() {\n\techo \"-- rename error cases\"\n\ttest_mkdir $DIR/R9\n\ttest_mkdir $DIR/R9/a\n\ttouch $DIR/R9/f\n\tmrename $DIR/R9/f $DIR/R9/a\n\t$CHECKSTAT -t file $DIR/R9/f || error \"$DIR/R9/f not file type\"\n\t$CHECKSTAT -t dir  $DIR/R9/a || error \"$DIR/R9/a not dir type\"\n\t$CHECKSTAT -a $DIR/R9/a/f || error \"$DIR/R9/a/f exists\"\n}\nrun_test 24i \"rename file to dir error: touch f ; mkdir a ; rename f a\"\n\ntest_24j() {\n\ttest_mkdir $DIR/R10\n\tmrename $DIR/R10/f $DIR/R10/g\n\t$CHECKSTAT -t dir $DIR/R10 || error \"$DIR/R10 not dir type\"\n\t$CHECKSTAT -a $DIR/R10/f || error \"$DIR/R10/f exists\"\n\t$CHECKSTAT -a $DIR/R10/g || error \"$DIR/R10/g exists\"\n}\nrun_test 24j \"source does not exist ============================\"\n\ntest_24k() {\n\ttest_mkdir $DIR/R11a\n\ttest_mkdir $DIR/R11a/d\n\ttouch $DIR/R11a/f\n\tmv $DIR/R11a/f $DIR/R11a/d\n\t$CHECKSTAT -a $DIR/R11a/f || error \"$DIR/R11a/f exists\"\n\t$CHECKSTAT -t file $DIR/R11a/d/f || error \"$DIR/R11a/d/f not file type\"\n}\nrun_test 24k \"touch .../R11a/f; mv .../R11a/f .../R11a/d =======\"\n\n# bug 2429 - rename foo foo foo creates invalid file\ntest_24l() {\n\tf=\"$DIR/f24l\"\n\t$MULTIOP $f OcNs || error \"rename of ${f} to itself failed\"\n}\nrun_test 24l \"Renaming a file to itself ========================\"\n\ntest_24m() {\n\tf=\"$DIR/f24m\"\n\t$MULTIOP $f OcLN ${f}2 ${f}2 || error \"link ${f}2 ${f}2 failed\"\n\t# on ext3 this does not remove either the source or target files\n\t# though the \"expected\" operation would be to remove the source\n\t$CHECKSTAT -t file ${f} || error \"${f} missing\"\n\t$CHECKSTAT -t file ${f}2 || error \"${f}2 missing\"\n}\nrun_test 24m \"Renaming a file to a hard link to itself =========\"\n\ntest_24n() {\n    f=\"$DIR/f24n\"\n    # this stats the old file after it was renamed, so it should fail\n    touch ${f}\n    $CHECKSTAT ${f} || error \"${f} missing\"\n    mv ${f} ${f}.rename\n    $CHECKSTAT ${f}.rename || error \"${f}.rename missing\"\n    $CHECKSTAT -a ${f} || error \"${f} exists\"\n}\nrun_test 24n \"Statting the old file after renaming (Posix rename 2)\"\n\ntest_24o() {\n\ttest_mkdir $DIR/$tdir\n\trename_many -s random -v -n 10 $DIR/$tdir\n}\nrun_test 24o \"rename of files during htree split\"\n\ntest_24p() {\n\ttest_mkdir $DIR/R12a\n\ttest_mkdir $DIR/R12b\n\tDIRINO=`ls -lid $DIR/R12a | awk '{ print $1 }'`\n\tmrename $DIR/R12a $DIR/R12b\n\t$CHECKSTAT -a $DIR/R12a || error \"$DIR/R12a exists\"\n\t$CHECKSTAT -t dir $DIR/R12b || error \"$DIR/R12b not dir type\"\n\tDIRINO2=`ls -lid $DIR/R12b | awk '{ print $1 }'`\n\t[ \"$DIRINO\" = \"$DIRINO2\" ] || error \"R12a $DIRINO != R12b $DIRINO2\"\n}\nrun_test 24p \"mkdir .../R12{a,b}; rename .../R12a .../R12b\"\n\ncleanup_multiop_pause() {\n\ttrap 0\n\tkill -USR1 $MULTIPID\n}\n\ntest_24q() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/R13a\n\ttest_mkdir $DIR/R13b\n\tlocal DIRINO=$(ls -lid $DIR/R13a | awk '{ print $1 }')\n\tmultiop_bg_pause $DIR/R13b D_c || error \"multiop failed to start\"\n\tMULTIPID=$!\n\n\ttrap cleanup_multiop_pause EXIT\n\tmrename $DIR/R13a $DIR/R13b\n\t$CHECKSTAT -a $DIR/R13a || error \"R13a still exists\"\n\t$CHECKSTAT -t dir $DIR/R13b || error \"R13b does not exist\"\n\tlocal DIRINO2=$(ls -lid $DIR/R13b | awk '{ print $1 }')\n\t[ \"$DIRINO\" = \"$DIRINO2\" ] || error \"R13a $DIRINO != R13b $DIRINO2\"\n\tcleanup_multiop_pause\n\twait $MULTIPID || error \"multiop close failed\"\n}\nrun_test 24q \"mkdir .../R13{a,b}; open R13b rename R13a R13b ===\"\n\ntest_24r() { #bug 3789\n\ttest_mkdir $DIR/R14a\n\ttest_mkdir $DIR/R14a/b\n\tmrename $DIR/R14a $DIR/R14a/b && error \"rename to subdir worked!\"\n\t$CHECKSTAT -t dir $DIR/R14a || error \"$DIR/R14a missing\"\n\t$CHECKSTAT -t dir $DIR/R14a/b || error \"$DIR/R14a/b missing\"\n}\nrun_test 24r \"mkdir .../R14a/b; rename .../R14a .../R14a/b =====\"\n\ntest_24s() {\n\ttest_mkdir $DIR/R15a\n\ttest_mkdir $DIR/R15a/b\n\ttest_mkdir $DIR/R15a/b/c\n\tmrename $DIR/R15a $DIR/R15a/b/c && error \"rename to sub-subdir worked!\"\n\t$CHECKSTAT -t dir $DIR/R15a || error \"$DIR/R15a missing\"\n\t$CHECKSTAT -t dir $DIR/R15a/b/c || error \"$DIR/R15a/b/c missing\"\n}\nrun_test 24s \"mkdir .../R15a/b/c; rename .../R15a .../R15a/b/c =\"\ntest_24t() {\n\ttest_mkdir $DIR/R16a\n\ttest_mkdir $DIR/R16a/b\n\ttest_mkdir $DIR/R16a/b/c\n\tmrename $DIR/R16a/b/c $DIR/R16a && error \"rename to sub-subdir worked!\"\n\t$CHECKSTAT -t dir $DIR/R16a || error \"$DIR/R16a missing\"\n\t$CHECKSTAT -t dir $DIR/R16a/b/c || error \"$DIR/R16a/b/c missing\"\n}\nrun_test 24t \"mkdir .../R16a/b/c; rename .../R16a/b/c .../R16a =\"\n\ntest_24u() { # bug12192\n\t$MULTIOP $DIR/$tfile C2w$((2048 * 1024))c || error \"multiop failed\"\n\t$CHECKSTAT -s $((2048 * 1024)) $DIR/$tfile || error \"wrong file size\"\n}\nrun_test 24u \"create stripe file\"\n\nsimple_cleanup_common() {\n\tlocal rc=0\n\ttrap 0\n\t[ -z \"$DIR\" ] || [ -z \"$tdir\" ] && return 0\n\n\tlocal start=$SECONDS\n\trm -rf $DIR/$tdir\n\trc=$?\n\twait_delete_completed\n\techo \"cleanup time $((SECONDS - start))\"\n\treturn $rc\n}\n\nmax_pages_per_rpc() {\n\tlocal mdtname=\"$(printf \"MDT%04x\" ${1:-0})\"\n\t$LCTL get_param -n mdc.*$mdtname*.max_pages_per_rpc\n}\n\ntest_24v() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal nrfiles=${COUNT:-100000}\n\tlocal fname=\"$DIR/$tdir/$tfile\"\n\n\t# Performance issue on ZFS see LU-4072 (c.f. LU-2887)\n\t[ \"$mds1_FSTYPE\" = \"zfs\" ] && nrfiles=${COUNT:-10000}\n\n\ttest_mkdir \"$(dirname $fname)\"\n\t# assume MDT0000 has the fewest inodes\n\tlocal stripes=$($LFS getdirstripe -c $(dirname $fname))\n\tlocal free_inodes=$(($(mdt_free_inodes 0) * stripes))\n\t[[ $free_inodes -lt $nrfiles ]] && nrfiles=$free_inodes\n\n\ttrap simple_cleanup_common EXIT\n\n\tcreatemany -m \"$fname\" $nrfiles\n\n\tcancel_lru_locks mdc\n\tlctl set_param mdc.*.stats clear\n\n\t# was previously test_24D: LU-6101\n\t# readdir() returns correct number of entries after cursor reload\n\tlocal num_ls=$(ls $DIR/$tdir | wc -l)\n\tlocal num_uniq=$(ls $DIR/$tdir | sort -u | wc -l)\n\tlocal num_all=$(ls -a $DIR/$tdir | wc -l)\n\tif [ $num_ls -ne $nrfiles ] || [ $num_uniq -ne $nrfiles ] ||\n\t\t[ $num_all -ne $((nrfiles + 2)) ]; then\n\t\t\terror \"Expected $nrfiles files, got $num_ls \" \\\n\t\t\t\t\"($num_uniq unique $num_all .&..)\"\n\tfi\n\t# LU-5 large readdir\n\t# dirent_size = 32 bytes for sizeof(struct lu_dirent) +\n\t#               N bytes for name (len($nrfiles) rounded to 8 bytes) +\n\t#               8 bytes for luda_type (4 bytes rounded to 8 bytes)\n\t# take into account of overhead in lu_dirpage header and end mark in\n\t# each page, plus one in rpc_num calculation.\n\tlocal dirent_size=$((32 + (${#tfile} | 7) + 1 + 8))\n\tlocal page_entries=$(((PAGE_SIZE - 24) / dirent_size))\n\tlocal mdt_idx=$($LFS getdirstripe -i $(dirname $fname))\n\tlocal rpc_pages=$(max_pages_per_rpc $mdt_idx)\n\tlocal rpc_max=$((nrfiles / (page_entries * rpc_pages) + stripes))\n\tlocal mds_readpage=$(calc_stats mdc.*.stats mds_readpage)\n\techo \"readpages: $mds_readpage rpc_max: $rpc_max\"\n\t(( $mds_readpage < $rpc_max - 2 || $mds_readpage > $rpc_max + 1)) &&\n\t\terror \"large readdir doesn't take effect: \" \\\n\t\t      \"$mds_readpage should be about $rpc_max\"\n\n\tsimple_cleanup_common\n}\nrun_test 24v \"list large directory (test hash collision, b=17560)\"\n\ntest_24w() { # bug21506\n        SZ1=234852\n        dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=4096 || return 1\n        dd if=/dev/zero bs=$SZ1 count=1 >> $DIR/$tfile || return 2\n        dd if=$DIR/$tfile of=$DIR/${tfile}_left bs=1M skip=4097 || return 3\n        SZ2=`ls -l $DIR/${tfile}_left | awk '{print $5}'`\n\t[[ \"$SZ1\" -eq \"$SZ2\" ]] ||\n                error \"Error reading at the end of the file $tfile\"\n}\nrun_test 24w \"Reading a file larger than 4Gb\"\n\ntest_24x() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.56) ]] &&\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX $remote_dir ||\n\t\terror \"create remote directory failed\"\n\n\ttest_mkdir $DIR/$tdir/src_dir\n\ttouch $DIR/$tdir/src_file\n\ttest_mkdir $remote_dir/tgt_dir\n\ttouch $remote_dir/tgt_file\n\n\tmrename $DIR/$tdir/src_dir $remote_dir/tgt_dir ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tmrename $DIR/$tdir/src_file $remote_dir/tgt_file ||\n\t\terror \"rename file cross MDT failed!\"\n\n\ttouch $DIR/$tdir/ln_file\n\tln $DIR/$tdir/ln_file $remote_dir/ln_name ||\n\t\terror \"ln file cross MDT failed\"\n\n\trm -rf $DIR/$tdir || error \"Can not delete directories\"\n}\nrun_test 24x \"cross MDT rename/link\"\n\ntest_24y() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal mdtidx=1\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS mkdir -i $mdtidx $remote_dir ||\n\t\terror \"create remote directory failed\"\n\n\ttest_mkdir $remote_dir/src_dir\n\ttouch $remote_dir/src_file\n\ttest_mkdir $remote_dir/tgt_dir\n\ttouch $remote_dir/tgt_file\n\n\tmrename $remote_dir/src_dir $remote_dir/tgt_dir ||\n\t\terror \"rename subdir in the same remote dir failed!\"\n\n\tmrename $remote_dir/src_file $remote_dir/tgt_file ||\n\t\terror \"rename files in the same remote dir failed!\"\n\n\tln $remote_dir/tgt_file $remote_dir/tgt_file1 ||\n\t\terror \"link files in the same remote dir failed!\"\n\n\trm -rf $DIR/$tdir || error \"Can not delete directories\"\n}\nrun_test 24y \"rename/link on the same dir should succeed\"\n\ntest_24z() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.12.51) ]] &&\n\t\tskip \"Need MDS version at least 2.12.51\"\n\n\tlocal index\n\n\tfor index in 0 1; do\n\t\t$LFS mkdir -i $index $DIR/$tdir.$index || error \"mkdir failed\"\n\t\ttouch $DIR/$tdir.0/$tfile.$index || error \"touch failed\"\n\tdone\n\n\tmv $DIR/$tdir.0/$tfile.0 $DIR/$tdir.1 || error \"mv $tfile.0 failed\"\n\n\tindex=$($LFS getstripe -m $DIR/$tdir.1/$tfile.0)\n\t[ $index -eq 0 ] || error \"$tfile.0 is on MDT$index\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\tdo_nodes $mdts $LCTL set_param mdt.*.enable_remote_rename=0\n\tstack_trap \"do_nodes $mdts $LCTL \\\n\t\tset_param mdt.*.enable_remote_rename=1\" EXIT\n\n\tmv $DIR/$tdir.0/$tfile.1 $DIR/$tdir.1 || error \"mv $tfile.1 failed\"\n\n\tindex=$($LFS getstripe -m $DIR/$tdir.1/$tfile.1)\n\t[ $index -eq 1 ] || error \"$tfile.1 is on MDT$index\"\n}\nrun_test 24z \"cross-MDT rename is done as cp\"\n\ntest_24A() { # LU-3182\n\tlocal NFILES=5000\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\ttrap simple_cleanup_common EXIT\n\tcreatemany -m $DIR/$tdir/$tfile $NFILES\n\tlocal t=$(ls $DIR/$tdir | wc -l)\n\tlocal u=$(ls $DIR/$tdir | sort -u | wc -l)\n\tlocal v=$(ls -ai $DIR/$tdir | sort -u | wc -l)\n\tif [ $t -ne $NFILES ] || [ $u -ne $NFILES ] ||\n\t   [ $v -ne $((NFILES + 2)) ] ; then\n\t\terror \"Expected $NFILES files, got $t ($u unique $v .&..)\"\n\tfi\n\n\tsimple_cleanup_common || error \"Can not delete directories\"\n}\nrun_test 24A \"readdir() returns correct number of entries.\"\n\ntest_24B() { # LU-4805\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal count\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"create striped dir failed\"\n\n\tcount=$(ls -ai $DIR/$tdir/striped_dir | wc -l)\n\t[ $count -eq 2 ] || error \"Expected 2, got $count\"\n\n\ttouch $DIR/$tdir/striped_dir/a\n\n\tcount=$(ls -ai $DIR/$tdir/striped_dir | wc -l)\n\t[ $count -eq 3 ] || error \"Expected 3, got $count\"\n\n\ttouch $DIR/$tdir/striped_dir/.f\n\n\tcount=$(ls -ai $DIR/$tdir/striped_dir | wc -l)\n\t[ $count -eq 4 ] || error \"Expected 4, got $count\"\n\n\trm -rf $DIR/$tdir || error \"Can not delete directories\"\n}\nrun_test 24B \"readdir for striped dir return correct number of entries\"\n\ntest_24C() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tmkdir $DIR/$tdir\n\tmkdir $DIR/$tdir/d0\n\tmkdir $DIR/$tdir/d1\n\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/d0/striped_dir ||\n\t\terror \"create striped dir failed\"\n\n\tcd $DIR/$tdir/d0/striped_dir\n\n\tlocal d0_ino=$(ls -i -l -a $DIR/$tdir | grep \"d0\" | awk '{print $1}')\n\tlocal d1_ino=$(ls -i -l -a $DIR/$tdir | grep \"d1\" | awk '{print $1}')\n\tlocal parent_ino=$(ls -i -l -a | grep \"\\.\\.\" | awk '{print $1}')\n\n\t[ \"$d0_ino\" = \"$parent_ino\" ] ||\n\t\terror \".. wrong, expect $d0_ino, get $parent_ino\"\n\n\tmv $DIR/$tdir/d0/striped_dir $DIR/$tdir/d1/ ||\n\t\terror \"mv striped dir failed\"\n\n\tparent_ino=$(ls -i -l -a | grep \"\\.\\.\" | awk '{print $1}')\n\n\t[ \"$d1_ino\" = \"$parent_ino\" ] ||\n\t\terror \".. wrong after mv, expect $d1_ino, get $parent_ino\"\n}\nrun_test 24C \"check .. in striped dir\"\n\ntest_24E() {\n\t[[ $MDSCOUNT -lt 4 ]] && skip_env \"needs >= 4 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $DIR/$tdir/src_dir\n\t$LFS mkdir -i 1 $DIR/$tdir/src_dir/src_child ||\n\t\terror \"create remote source failed\"\n\n\ttouch $DIR/$tdir/src_dir/src_child/a\n\n\t$LFS mkdir -i 2 $DIR/$tdir/tgt_dir ||\n\t\terror \"create remote target dir failed\"\n\n\t$LFS mkdir -i 3 $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"create remote target child failed\"\n\n\tmrename $DIR/$tdir/src_dir/src_child $DIR/$tdir/tgt_dir/tgt_child ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\tfind $DIR/$tdir\n\n\t$CHECKSTAT -t dir $DIR/$tdir/src_dir/src_child &&\n\t\terror \"src_child still exists after rename\"\n\n\t$CHECKSTAT -t file $DIR/$tdir/tgt_dir/tgt_child/a ||\n\t\terror \"missing file(a) after rename\"\n\n\trm -rf $DIR/$tdir || error \"Can not delete directories\"\n}\nrun_test 24E \"cross MDT rename/link\"\n\ntest_24F () {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\n\tlocal repeats=1000\n\t[ \"$SLOW\" = \"no\" ] && repeats=100\n\n\tmkdir -p $DIR/$tdir\n\n\techo \"$repeats repeats\"\n\tfor ((i = 0; i < repeats; i++)); do\n\t\t$LFS mkdir -i0 -c2 $DIR/$tdir/test || error \"mkdir fails\"\n\t\ttouch $DIR/$tdir/test/a || error \"touch fails\"\n\t\tmkdir $DIR/$tdir/test/b || error \"mkdir fails\"\n\t\trm -rf $DIR/$tdir/test || error \"rmdir fails\"\n\tdone\n\n\ttrue\n}\nrun_test 24F \"hash order vs readdir (LU-11330)\"\n\ntest_25a() {\n\techo '== symlink sanity ============================================='\n\n\ttest_mkdir $DIR/d25\n\tln -s d25 $DIR/s25\n\ttouch $DIR/s25/foo ||\n\t\terror \"File creation in symlinked directory failed\"\n}\nrun_test 25a \"create file in symlinked directory ===============\"\n\ntest_25b() {\n\t[ ! -d $DIR/d25 ] && test_25a\n\t$CHECKSTAT -t file $DIR/s25/foo || error \"$DIR/s25/foo not file type\"\n}\nrun_test 25b \"lookup file in symlinked directory ===============\"\n\ntest_26a() {\n\ttest_mkdir $DIR/d26\n\ttest_mkdir $DIR/d26/d26-2\n\tln -s d26/d26-2 $DIR/s26\n\ttouch $DIR/s26/foo || error \"File creation failed\"\n}\nrun_test 26a \"multiple component symlink =======================\"\n\ntest_26b() {\n\ttest_mkdir -p $DIR/$tdir/d26-2\n\tln -s $tdir/d26-2/foo $DIR/s26-2\n\ttouch $DIR/s26-2 || error \"File creation failed\"\n}\nrun_test 26b \"multiple component symlink at end of lookup ======\"\n\ntest_26c() {\n\ttest_mkdir $DIR/d26.2\n\ttouch $DIR/d26.2/foo\n\tln -s d26.2 $DIR/s26.2-1\n\tln -s s26.2-1 $DIR/s26.2-2\n\tln -s s26.2-2 $DIR/s26.2-3\n\tchmod 0666 $DIR/s26.2-3/foo\n}\nrun_test 26c \"chain of symlinks\"\n\n# recursive symlinks (bug 439)\ntest_26d() {\n\tln -s d26-3/foo $DIR/d26-3\n}\nrun_test 26d \"create multiple component recursive symlink\"\n\ntest_26e() {\n\t[ ! -h $DIR/d26-3 ] && test_26d\n\trm $DIR/d26-3\n}\nrun_test 26e \"unlink multiple component recursive symlink\"\n\n# recursive symlinks (bug 7022)\ntest_26f() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/$tfile\n\tcd $DIR/$tdir/$tfile           || error \"cd $DIR/$tdir/$tfile failed\"\n\ttest_mkdir -p lndir/bar1\n\ttest_mkdir $DIR/$tdir/$tfile/$tfile\n\tcd $tfile                || error \"cd $tfile failed\"\n\tln -s .. dotdot          || error \"ln dotdot failed\"\n\tln -s dotdot/lndir lndir || error \"ln lndir failed\"\n\tcd $DIR/$tdir                 || error \"cd $DIR/$tdir failed\"\n\toutput=`ls $tfile/$tfile/lndir/bar1`\n\t[ \"$output\" = bar1 ] && error \"unexpected output\"\n\trm -r $tfile             || error \"rm $tfile failed\"\n\t$CHECKSTAT -a $DIR/$tfile || error \"$tfile not gone\"\n}\nrun_test 26f \"rm -r of a directory which has recursive symlink\"\n\ntest_27a() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS getstripe $DIR/$tdir\n\t$LFS setstripe -c 1 $DIR/$tdir/$tfile || error \"setstripe failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile || error \"checkstat failed\"\n\tcp /etc/hosts $DIR/$tdir/$tfile || error \"Can't copy to one stripe file\"\n}\nrun_test 27a \"one stripe file\"\n\ntest_27b() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile || error \"setstripe failed\"\n\t$LFS getstripe -c $DIR/$tdir/$tfile\n\t[ $($LFS getstripe -c $DIR/$tdir/$tfile) -eq 2 ] ||\n\t\terror \"two-stripe file doesn't have two stripes\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error \"dd failed\"\n}\nrun_test 27b \"create and write to two stripe file\"\n\n# 27c family tests specific striping, setstripe -o\ntest_27ca() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"skipping 2-stripe test\"\n\ttest_mkdir -p $DIR/$tdir\n\tlocal osts=\"1\"\n\n\t$LFS setstripe -o $osts $DIR/$tdir/$tfile  || error \"setstripe failed\"\n\t$LFS getstripe -i $DIR/$tdir/$tfile\n\t[ $($LFS getstripe -i $DIR/$tdir/$tfile ) -eq $osts ] ||\n\t\terror \"stripe not on specified OST\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile  bs=1M count=4 || error \"dd failed\"\n}\nrun_test 27ca \"one stripe on specified OST\"\n\ntest_27cb() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"skipping 2-stripe test\"\n\ttest_mkdir -p $DIR/$tdir\n\tlocal osts=\"1,0\"\n\t$LFS setstripe -o $osts $DIR/$tdir/$tfile || error \"setstripe failed\"\n\tlocal getstripe=$($LFS getstripe $DIR/$tdir/$tfile)\n\techo \"$getstripe\"\n\n\t# Strip getstripe output to a space separated list of OSTs\n\tlocal getstripe_osts=$(echo \"$getstripe\" | sed -e '1,/obdidx/d' |\\\n\t\tawk '{print $1}' | tr '\\n' '\\ ' | sed -e 's/[[:space:]]*$//')\n\t[ \"$getstripe_osts\" = \"${osts//,/ }\" ] ||\n\t\terror \"stripes not on specified OSTs\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error \"dd failed\"\n}\nrun_test 27cb \"two stripes on specified OSTs\"\n\ntest_27cc() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"skipping 2-stripe test\"\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\n\ttest_mkdir -p $DIR/$tdir\n\tlocal osts=\"0,0\"\n\t$LFS setstripe -o $osts $DIR/$tdir/$tfile || error \"setstripe failed\"\n\tlocal getstripe=$($LFS getstripe $DIR/$tdir/$tfile)\n\techo \"$getstripe\"\n\n\t# Strip getstripe output to a space separated list of OSTs\n\tlocal getstripe_osts=$(echo \"$getstripe\" | sed -e '1,/obdidx/d' |\\\n\t\tawk '{print $1}' | tr '\\n' '\\ ' | sed -e 's/[[:space:]]*$//')\n\t[ \"$getstripe_osts\" = \"${osts//,/ }\" ] ||\n\t\terror \"stripes not on specified OSTs\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error \"dd failed\"\n}\nrun_test 27cc \"two stripes on the same OST\"\n\ntest_27cd() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"skipping 2-stripe test\"\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\ttest_mkdir -p $DIR/$tdir\n\tlocal osts=\"0,1,1,0\"\n\t$LFS setstripe -o $osts $DIR/$tdir/$tfile || error \"setstripe failed\"\n\tlocal getstripe=$($LFS getstripe $DIR/$tdir/$tfile)\n\techo \"$getstripe\"\n\n\t# Strip getstripe output to a space separated list of OSTs\n\tlocal getstripe_osts=$(echo \"$getstripe\" | sed -e '1,/obdidx/d' |\\\n\t\tawk '{print $1}' | tr '\\n' '\\ ' | sed -e 's/[[:space:]]*$//')\n\t[ \"$getstripe_osts\" = \"${osts//,/ }\" ] ||\n\t\terror \"stripes not on specified OSTs\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error \"dd failed\"\n}\nrun_test 27cd \"four stripes on two OSTs\"\n\ntest_27ce() {\n\t[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&\n\t\tskip_env \"too many osts, skipping\"\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\t# We do one more stripe than we have OSTs\n\t[ $OSTCOUNT -ge 159 ] || large_xattr_enabled ||\n\t\tskip_env \"ea_inode feature disabled\"\n\n\ttest_mkdir -p $DIR/$tdir\n\tlocal osts=\"\"\n\tfor i in $(seq 0 $OSTCOUNT);\n\tdo\n\t\tosts=$osts\"0\"\n\t\tif [ $i -ne $OSTCOUNT ]; then\n\t\t\tosts=$osts\",\"\n\t\tfi\n\tdone\n\t$LFS setstripe -o $osts $DIR/$tdir/$tfile || error \"setstripe failed\"\n\tlocal getstripe=$($LFS getstripe $DIR/$tdir/$tfile)\n\techo \"$getstripe\"\n\n\t# Strip getstripe output to a space separated list of OSTs\n\tlocal getstripe_osts=$(echo \"$getstripe\" | sed -e '1,/obdidx/d' |\\\n\t\tawk '{print $1}' | tr '\\n' '\\ ' | sed -e 's/[[:space:]]*$//')\n\t[ \"$getstripe_osts\" = \"${osts//,/ }\" ] ||\n\t\terror \"stripes not on specified OSTs\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 || error \"dd failed\"\n}\nrun_test 27ce \"more stripes than OSTs with -o\"\n\ntest_27cf() {\n\tlocal osp_proc=\"osp.$FSNAME-OST0000-osc-MDT000*.active\"\n\tlocal pid=0\n\n\ttest_mkdir -p $DIR/$tdir || error \"failed to mkdir $DIR/$tdir\"\n\tdo_facet $SINGLEMDS \"$LCTL set_param -n $osp_proc=0\"\n\tstack_trap \"do_facet $SINGLEMDS $LCTL set_param -n $osp_proc=1\" EXIT\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n $osp_proc | grep 1\" ||\n\t\terror \"failed to set $osp_proc=0\"\n\n\t$LFS setstripe -o 0 $DIR/$tdir/$tfile &\n\tpid=$!\n\tsleep 1\n\tdo_facet $SINGLEMDS \"$LCTL set_param -n $osp_proc=1\"\n\twait_update_facet $SINGLEMDS \"$LCTL get_param -n $osp_proc | grep 0\" ||\n\t\terror \"failed to set $osp_proc=1\"\n\twait $pid\n\t[[ $pid -ne 0 ]] ||\n\t\terror \"should return error due to $osp_proc=0\"\n}\nrun_test 27cf \"'setstripe -o' on inactive OSTs should return error\"\n\ntest_27d() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 0 -i -1 -S 0 $DIR/$tdir/$tfile ||\n\t\terror \"setstripe failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile || error \"checkstat failed\"\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error \"dd failed\"\n}\nrun_test 27d \"create file with default settings\"\n\ntest_27e() {\n\t# LU-5839 adds check for existed layout before setting it\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.56) ]] &&\n\t\tskip \"Need MDS version at least 2.7.56\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile || error \"setstripe failed\"\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile && error \"setstripe worked twice\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile || error \"checkstat failed\"\n}\nrun_test 27e \"setstripe existing file (should return error)\"\n\ntest_27f() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -S 100 -i 0 -c 1 $DIR/$tdir/$tfile &&\n\t\terror \"$LFS setstripe $DIR/$tdir/$tfile failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/$tfile &&\n\t\terror \"$CHECKSTAT -t file $DIR/$tdir/$tfile should fail\"\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error \"dd failed\"\n\t$LFS getstripe $DIR/$tdir/$tfile || error \"$LFS getstripe failed\"\n}\nrun_test 27f \"setstripe with bad stripe size (should return error)\"\n\ntest_27g() {\n\ttest_mkdir $DIR/$tdir\n\t$MCREATE $DIR/$tdir/$tfile || error \"mcreate failed\"\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"no stripe info\" ||\n\t\terror \"$DIR/$tdir/$tfile has object\"\n}\nrun_test 27g \"$LFS getstripe with no objects\"\n\ntest_27ga() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile || error \"touch failed\"\n\tln -s bogus $DIR/$tdir/$tfile.2 || error \"ln failed\"\n\t$LFS getstripe -m $DIR/$tdir/$tfile $DIR/$tdir/$tfile.2\n\tlocal rc=$?\n\t(( rc == 2 )) || error \"getstripe did not return ENOENT\"\n}\nrun_test 27ga \"$LFS getstripe with missing file (should return error)\"\n\ntest_27i() {\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile || error \"touch failed\"\n\t[[ $($LFS getstripe -c $DIR/$tdir/$tfile) -gt 0 ]] ||\n\t\terror \"missing objects\"\n}\nrun_test 27i \"$LFS getstripe with some objects\"\n\ntest_27j() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -i $OSTCOUNT $DIR/$tdir/$tfile &&\n\t\terror \"setstripe failed\" || true\n}\nrun_test 27j \"setstripe with bad stripe offset (should return error)\"\n\ntest_27k() { # bug 2844\n\ttest_mkdir $DIR/$tdir\n\tlocal file=$DIR/$tdir/$tfile\n\tlocal ll_max_blksize=$((4 * 1024 * 1024))\n\t$LFS setstripe -S 67108864 $file || error \"setstripe failed\"\n\tlocal blksize=$(stat $file | awk '/IO Block:/ { print $7 }')\n\t[ $blksize -le $ll_max_blksize ] || error \"1:$blksize > $ll_max_blksize\"\n\tdd if=/dev/zero of=$file bs=4k count=1\n\tblksize=$(stat $file | awk '/IO Block:/ { print $7 }')\n\t[ $blksize -le $ll_max_blksize ] || error \"2:$blksize > $ll_max_blksize\"\n}\nrun_test 27k \"limit i_blksize for broken user apps\"\n\ntest_27l() {\n\tmcreate $DIR/$tfile || error \"creating file\"\n\t$RUNAS $LFS setstripe -c 1 $DIR/$tfile &&\n\t\terror \"setstripe should have failed\" || true\n}\nrun_test 27l \"check setstripe permissions (should return error)\"\n\ntest_27m() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\t[ -n \"$RCLIENTS\" -o -n \"$MOUNT_2\" ] &&\n\t\tskip_env \"multiple clients -- skipping\"\n\n\tORIGFREE=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |\n\t\t   head -n1)\n\tif [[ $ORIGFREE -gt $MAXFREE ]]; then\n\t\tskip \"$ORIGFREE > $MAXFREE skipping out-of-space test on OST0\"\n\tfi\n\ttrap simple_cleanup_common EXIT\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir/$tfile.1\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.1 bs=1024 count=$MAXFREE &&\n\t\terror \"dd should fill OST0\"\n\ti=2\n\twhile $LFS setstripe -i 0 -c 1 $DIR/$tdir/$tfile.$i; do\n\t\ti=$((i + 1))\n\t\t[ $i -gt 256 ] && break\n\tdone\n\ti=$((i + 1))\n\ttouch $DIR/$tdir/$tfile.$i\n\t[ $($LFS getstripe $DIR/$tdir/$tfile.$i | grep -A 10 obdidx |\n\t    awk '{print $1}'| grep -w \"0\") ] &&\n\t\terror \"OST0 was full but new created file still use it\"\n\ti=$((i + 1))\n\ttouch $DIR/$tdir/$tfile.$i\n\t[ $($LFS getstripe $DIR/$tdir/$tfile.$i | grep -A 10 obdidx |\n\t    awk '{print $1}'| grep -w \"0\") ] &&\n\t\terror \"OST0 was full but new created file still use it\"\n\tsimple_cleanup_common\n}\nrun_test 27m \"create file while OST0 was full\"\n\n# OSCs keep a NOSPC flag that will be reset after ~5s (qos_maxage)\n# if the OST isn't full anymore.\nreset_enospc() {\n\tlocal ostidx=${1:-\"\"}\n\tlocal delay\n\tlocal ready\n\tlocal get_prealloc\n\n\tlocal list=$(comma_list $(osts_nodes))\n\t[ \"$ostidx\" ] && list=$(facet_host ost$((ostidx + 1)))\n\n\tdo_nodes $list lctl set_param fail_loc=0\n\twait_delete_completed\t# initiate all OST_DESTROYs from MDS to OST\n\tdelay=$(do_facet $SINGLEMDS lctl get_param -n lov.*.qos_maxage |\n\t\tawk '{print $1 * 2;exit;}')\n\tget_prealloc=\"$LCTL get_param -n osc.*MDT*.prealloc_status |\n\t\t\tgrep -v \\\"^0$\\\"\"\n\twait_update_facet $SINGLEMDS \"$get_prealloc\" \"\" $delay\n}\n\n__exhaust_precreations() {\n\tlocal OSTIDX=$1\n\tlocal FAILLOC=$2\n\tlocal FAILIDX=${3:-$OSTIDX}\n\tlocal ofacet=ost$((OSTIDX + 1))\n\n\ttest_mkdir -p -c1 $DIR/$tdir\n\tlocal mdtidx=$($LFS getstripe -m $DIR/$tdir)\n\tlocal mfacet=mds$((mdtidx + 1))\n\techo OSTIDX=$OSTIDX MDTIDX=$mdtidx\n\n\tlocal OST=$(ostname_from_index $OSTIDX)\n\n\t# on the mdt's osc\n\tlocal mdtosc_proc1=$(get_mdtosc_proc_path $mfacet $OST)\n\tlocal last_id=$(do_facet $mfacet lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_last_id)\n\tlocal next_id=$(do_facet $mfacet lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_next_id)\n\n\tlocal mdtosc_proc2=$(get_mdtosc_proc_path $mfacet)\n\tdo_facet $mfacet lctl get_param osp.$mdtosc_proc2.prealloc*\n\n\ttest_mkdir -p $DIR/$tdir/${OST}\n\t$LFS setstripe -i $OSTIDX -c 1 $DIR/$tdir/${OST}\n#define OBD_FAIL_OST_ENOSPC              0x215\n\tdo_facet $ofacet lctl set_param fail_val=$FAILIDX fail_loc=0x215\n\techo \"Creating to objid $last_id on ost $OST...\"\n\tcreatemany -o $DIR/$tdir/${OST}/f $next_id $((last_id - next_id + 2))\n\tdo_facet $mfacet lctl get_param osp.$mdtosc_proc2.prealloc*\n\tdo_facet $ofacet lctl set_param fail_loc=$FAILLOC\n}\n\nexhaust_precreations() {\n\t__exhaust_precreations $1 $2 $3\n\tsleep_maxage\n}\n\nexhaust_all_precreations() {\n\tlocal i\n\tfor (( i=0; i < OSTCOUNT; i++ )) ; do\n\t\t__exhaust_precreations $i $1 -1\n\tdone\n\tsleep_maxage\n}\n\ntest_27n() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_enospc\n\trm -f $DIR/$tdir/$tfile\n\texhaust_precreations 0 0x80000215\n\t$LFS setstripe -c -1 $DIR/$tdir || error \"setstripe failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch failed\"\n\t$LFS getstripe $DIR/$tdir/$tfile\n\treset_enospc\n}\nrun_test 27n \"create file with some full OSTs\"\n\ntest_27o() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_enospc\n\trm -f $DIR/$tdir/$tfile\n\texhaust_all_precreations 0x215\n\n\ttouch $DIR/$tdir/$tfile && error \"able to create $DIR/$tdir/$tfile\"\n\n\treset_enospc\n\trm -rf $DIR/$tdir/*\n}\nrun_test 27o \"create file with all full OSTs (should error)\"\n\ntest_27p() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_enospc\n\trm -f $DIR/$tdir/$tfile\n\ttest_mkdir $DIR/$tdir\n\n\t$MCREATE $DIR/$tdir/$tfile || error \"mcreate failed\"\n\t$TRUNCATE $DIR/$tdir/$tfile 80000000 || error \"truncate failed\"\n\t$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error \"checkstat failed\"\n\n\texhaust_precreations 0 0x80000215\n\techo foo >> $DIR/$tdir/$tfile || error \"append failed\"\n\t$CHECKSTAT -s 80000004 $DIR/$tdir/$tfile || error \"checkstat failed\"\n\t$LFS getstripe $DIR/$tdir/$tfile\n\n\treset_enospc\n}\nrun_test 27p \"append to a truncated file with some full OSTs\"\n\ntest_27q() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_enospc\n\trm -f $DIR/$tdir/$tfile\n\n\ttest_mkdir $DIR/$tdir\n\t$MCREATE $DIR/$tdir/$tfile || error \"mcreate $DIR/$tdir/$tfile failed\"\n\t$TRUNCATE $DIR/$tdir/$tfile 80000000 ||\n\t\terror \"truncate $DIR/$tdir/$tfile failed\"\n\t$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error \"checkstat failed\"\n\n\texhaust_all_precreations 0x215\n\n\techo foo >> $DIR/$tdir/$tfile && error \"append succeeded\"\n\t$CHECKSTAT -s 80000000 $DIR/$tdir/$tfile || error \"checkstat 2 failed\"\n\n\treset_enospc\n}\nrun_test 27q \"append to truncated file with all OSTs full (should error)\"\n\ntest_27r() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_enospc\n\trm -f $DIR/$tdir/$tfile\n\texhaust_precreations 0 0x80000215\n\n\t$LFS setstripe -i 0 -c 2 $DIR/$tdir/$tfile || error \"setstripe failed\"\n\n\treset_enospc\n}\nrun_test 27r \"stripe file with some full OSTs (shouldn't LBUG) =\"\n\ntest_27s() { # bug 10725\n\ttest_mkdir $DIR/$tdir\n\tlocal stripe_size=$((4096 * 1024 * 1024))\t# 2^32\n\tlocal stripe_count=0\n\t[ $OSTCOUNT -eq 1 ] || stripe_count=2\n\t$LFS setstripe -S $stripe_size -c $stripe_count $DIR/$tdir &&\n\t\terror \"stripe width >= 2^32 succeeded\" || true\n\n}\nrun_test 27s \"lsm_xfersize overflow (should error) (bug 10725)\"\n\ntest_27t() { # bug 10864\n\tWDIR=$(pwd)\n\tWLFS=$(which lfs)\n\tcd $DIR\n\ttouch $tfile\n\t$WLFS getstripe $tfile\n\tcd $WDIR\n}\nrun_test 27t \"check that utils parse path correctly\"\n\ntest_27u() { # bug 4900\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal index\n\tlocal list=$(comma_list $(mdts_nodes))\n\n#define OBD_FAIL_MDS_OSC_PRECREATE      0x139\n\tdo_nodes $list $LCTL set_param fail_loc=0x139\n\ttest_mkdir -p $DIR/$tdir\n\ttrap simple_cleanup_common EXIT\n\tcreatemany -o $DIR/$tdir/t- 1000\n\tdo_nodes $list $LCTL set_param fail_loc=0\n\n\tTLOG=$TMP/$tfile.getstripe\n\t$LFS getstripe $DIR/$tdir > $TLOG\n\tOBJS=$(awk -vobj=0 '($1 == 0) { obj += 1 } END { print obj; }' $TLOG)\n\tunlinkmany $DIR/$tdir/t- 1000\n\ttrap 0\n\t[[ $OBJS -gt 0 ]] &&\n\t\terror \"$OBJS objects created on OST-0. See $TLOG\" ||\n\t\trm -f $TLOG\n}\nrun_test 27u \"skip object creation on OSC w/o objects\"\n\ntest_27v() { # bug 4900\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\texhaust_all_precreations 0x215\n\treset_enospc\n\n\t$LFS setstripe -c 1 $DIR/$tdir         # 1 stripe / file\n\n        touch $DIR/$tdir/$tfile\n        #define OBD_FAIL_TGT_DELAY_PRECREATE     0x705\n        # all except ost1\n        for (( i=1; i < OSTCOUNT; i++ )); do\n                do_facet ost$i lctl set_param fail_loc=0x705\n        done\n        local START=`date +%s`\n        createmany -o $DIR/$tdir/$tfile 32\n\n        local FINISH=`date +%s`\n        local TIMEOUT=`lctl get_param -n timeout`\n        local PROCESS=$((FINISH - START))\n        [ $PROCESS -ge $((TIMEOUT / 2)) ] && \\\n               error \"$FINISH - $START >= $TIMEOUT / 2\"\n        sleep $((TIMEOUT / 2 - PROCESS))\n        reset_enospc\n}\nrun_test 27v \"skip object creation on slow OST\"\n\ntest_27w() { # bug 10997\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -S 65536 $DIR/$tdir/f0 || error \"setstripe failed\"\n\t[ $($LFS getstripe -S $DIR/$tdir/f0) -ne 65536 ] &&\n\t\terror \"stripe size $size != 65536\" || true\n\t[ $($LFS getstripe -d $DIR/$tdir | grep -c \"stripe_count\") -eq 0 ] &&\n\t\terror \"$LFS getstripe -d $DIR/$tdir no 'stripe_count'\" || true\n}\nrun_test 27w \"check $LFS setstripe -S and getstrip -d options\"\n\ntest_27wa() {\n\t[[ $OSTCOUNT -lt 2 ]] &&\n\t\tskip_env \"skipping multiple stripe count/offset test\"\n\n\ttest_mkdir $DIR/$tdir\n\tfor i in $(seq 1 $OSTCOUNT); do\n\t\toffset=$((i - 1))\n\t\t$LFS setstripe -c $i -i $offset $DIR/$tdir/f$i ||\n\t\t\terror \"setstripe -c $i -i $offset failed\"\n\t\tcount=$($LFS getstripe -c $DIR/$tdir/f$i)\n\t\tindex=$($LFS getstripe -i $DIR/$tdir/f$i)\n\t\t[ $count -ne $i ] && error \"stripe count $count != $i\" || true\n\t\t[ $index -ne $offset ] &&\n\t\t\terror \"stripe offset $index != $offset\" || true\n\tdone\n}\nrun_test 27wa \"check $LFS setstripe -c -i options\"\n\ntest_27x() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tOFFSET=$(($OSTCOUNT - 1))\n\tOSTIDX=0\n\tlocal OST=$(ostname_from_index $OSTIDX)\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 $DIR/$tdir\t# 1 stripe per file\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param -n obdfilter.$OST.degraded 1\n\tsleep_maxage\n\tcreatemany -o $DIR/$tdir/$tfile $OSTCOUNT\n\tfor i in $(seq 0 $OFFSET); do\n\t\t[ $($LFS getstripe $DIR/$tdir/$tfile$i | grep -A 10 obdidx |\n\t\t\tawk '{print $1}' | grep -w \"$OSTIDX\") ] &&\n\t\terror \"OST0 was degraded but new created file still use it\"\n\tdone\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param -n obdfilter.$OST.degraded 0\n}\nrun_test 27x \"create files while OST0 is degraded\"\n\ntest_27y() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS $FSNAME-OST0000)\n\tlocal last_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\tosp.$mdtosc.prealloc_last_id)\n\tlocal next_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\tosp.$mdtosc.prealloc_next_id)\n\tlocal fcount=$((last_id - next_id))\n\t[[ $fcount -eq 0 ]] && skip \"not enough space on OST0\"\n\t[[ $fcount -gt $OSTCOUNT ]] && fcount=$OSTCOUNT\n\n\tlocal MDS_OSCS=$(do_facet $SINGLEMDS lctl dl |\n\t\t\t awk '/[oO][sS][cC].*md[ts]/ { print $4 }')\n\tlocal OST_DEACTIVE_IDX=-1\n\tlocal OSC\n\tlocal OSTIDX\n\tlocal OST\n\n\tfor OSC in $MDS_OSCS; do\n\t\tOST=$(osc_to_ost $OSC)\n\t\tOSTIDX=$(index_from_ostuuid $OST)\n\t\tif [ $OST_DEACTIVE_IDX == -1 ]; then\n\t\t\tOST_DEACTIVE_IDX=$OSTIDX\n\t\tfi\n\t\tif [ $OSTIDX != $OST_DEACTIVE_IDX ]; then\n\t\t\techo $OSC \"is Deactivated:\"\n\t\t\tdo_facet $SINGLEMDS lctl --device  %$OSC deactivate\n\t\tfi\n\tdone\n\n\tOSTIDX=$(index_from_ostuuid $OST)\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 $DIR/$tdir      # 1 stripe / file\n\n\tfor OSC in $MDS_OSCS; do\n\t\tOST=$(osc_to_ost $OSC)\n\t\tOSTIDX=$(index_from_ostuuid $OST)\n\t\tif [ $OSTIDX == $OST_DEACTIVE_IDX ]; then\n\t\t\techo $OST \"is degraded:\"\n\t\t\tdo_facet ost$((OSTIDX+1)) lctl set_param -n \\\n\t\t\t\t\t\tobdfilter.$OST.degraded=1\n\t\tfi\n\tdone\n\n\tsleep_maxage\n\tcreatemany -o $DIR/$tdir/$tfile $fcount\n\n\tfor OSC in $MDS_OSCS; do\n\t\tOST=$(osc_to_ost $OSC)\n\t\tOSTIDX=$(index_from_ostuuid $OST)\n\t\tif [ $OSTIDX == $OST_DEACTIVE_IDX ]; then\n\t\t\techo $OST \"is recovered from degraded:\"\n\t\t\tdo_facet ost$((OSTIDX+1)) lctl set_param -n \\\n\t\t\t\t\t\tobdfilter.$OST.degraded=0\n\t\telse\n\t\t\tdo_facet $SINGLEMDS lctl --device %$OSC activate\n\t\tfi\n\tdone\n\n\t# all osp devices get activated, hence -1 stripe count restored\n\tlocal stripe_count=0\n\n\t# sleep 2*lod_qos_maxage seconds waiting for lod qos to notice osp\n\t# devices get activated.\n\tsleep_maxage\n\t$LFS setstripe -c -1 $DIR/$tfile\n\tstripe_count=$($LFS getstripe -c $DIR/$tfile)\n\trm -f $DIR/$tfile\n\t[ $stripe_count -ne $OSTCOUNT ] &&\n\t\terror \"Of $OSTCOUNT OSTs, only $stripe_count is available\"\n\treturn 0\n}\nrun_test 27y \"create files while OST0 is degraded and the rest inactive\"\n\ncheck_seq_oid()\n{\n\tlog \"check file $1\"\n\n\tlmm_count=$($LFS getstripe -c $1)\n\tlmm_seq=$($LFS getstripe -v $1 | awk '/lmm_seq/ { print $2 }')\n\tlmm_oid=$($LFS getstripe -v $1 | awk '/lmm_object_id/ { print $2 }')\n\n\tlocal old_ifs=\"$IFS\"\n\tIFS=$'[:]'\n\tfid=($($LFS path2fid $1))\n\tIFS=\"$old_ifs\"\n\n\tlog \"FID seq ${fid[1]}, oid ${fid[2]} ver ${fid[3]}\"\n\tlog \"LOV seq $lmm_seq, oid $lmm_oid, count: $lmm_count\"\n\n\t# compare lmm_seq and lu_fid->f_seq\n\t[ $lmm_seq = ${fid[1]} ] || { error \"SEQ mismatch\"; return 1; }\n\t# compare lmm_object_id and lu_fid->oid\n\t[ $lmm_oid = ${fid[2]} ] || { error \"OID mismatch\"; return 2; }\n\n\t# check the trusted.fid attribute of the OST objects of the file\n\tlocal have_obdidx=false\n\tlocal stripe_nr=0\n\t$LFS getstripe $1 | while read obdidx oid hex seq; do\n\t\t# skip lines up to and including \"obdidx\"\n\t\t[ -z \"$obdidx\" ] && break\n\t\t[ \"$obdidx\" = \"obdidx\" ] && have_obdidx=true && continue\n\t\t$have_obdidx || continue\n\n\t\tlocal ost=$((obdidx + 1))\n\t\tlocal dev=$(ostdevname $ost)\n\t\tlocal oid_hex\n\n\t\tlog \"want: stripe:$stripe_nr ost:$obdidx oid:$oid/$hex seq:$seq\"\n\n\t\tseq=$(echo $seq | sed -e \"s/^0x//g\")\n\t\tif [ $seq == 0 ] || [ $(facet_fstype ost$ost) == zfs ]; then\n\t\t\toid_hex=$(echo $oid)\n\t\telse\n\t\t\toid_hex=$(echo $hex | sed -e \"s/^0x//g\")\n\t\tfi\n\t\tlocal obj_file=\"O/$seq/d$((oid %32))/$oid_hex\"\n\n\t\tlocal ff=\"\"\n\t\t#\n\t\t# Don't unmount/remount the OSTs if we don't need to do that.\n\t\t# LU-2577 changes filter_fid to be smaller, so debugfs needs\n\t\t# update too, until that use mount/ll_decode_filter_fid/mount.\n\t\t# Re-enable when debugfs will understand new filter_fid.\n\t\t#\n\t\tif [ $(facet_fstype ost$ost) == ldiskfs ]; then\n\t\t\tff=$(do_facet ost$ost \"$DEBUGFS -c -R 'stat $obj_file' \\\n\t\t\t\t$dev 2>/dev/null\" | grep \"parent=\")\n\t\tfi\n\t\tif [ -z \"$ff\" ]; then\n\t\t\tstop ost$ost\n\t\t\tmount_fstype ost$ost\n\t\t\tff=$(do_facet ost$ost $LL_DECODE_FILTER_FID \\\n\t\t\t\t$(facet_mntpt ost$ost)/$obj_file)\n\t\t\tunmount_fstype ost$ost\n\t\t\tstart ost$ost $dev $OST_MOUNT_OPTS\n\t\t\tclients_up\n\t\tfi\n\n\t\t[ -z \"$ff\" ] && error \"$obj_file: no filter_fid info\"\n\n\t\techo \"$ff\" | sed -e 's#.*objid=#got: objid=#'\n\n\t\t# /mnt/O/0/d23/23: objid=23 seq=0 parent=[0x200000400:0x1e:0x1]\n\t\t# fid: objid=23 seq=0 parent=[0x200000400:0x1e:0x0] stripe=1\n\t\t#\n\t\t# fid: parent=[0x200000400:0x1e:0x0] stripe=1 stripe_count=2 \\\n\t\t#\tstripe_size=1048576 component_id=1 component_start=0 \\\n\t\t#\tcomponent_end=33554432\n\t\tlocal ff_parent=$(sed -e 's/.*parent=.//' <<<$ff)\n\t\tlocal ff_pseq=$(cut -d: -f1 <<<$ff_parent)\n\t\tlocal ff_poid=$(cut -d: -f2 <<<$ff_parent)\n\t\tlocal ff_pstripe\n\t\tif grep -q 'stripe=' <<<$ff; then\n\t\t\tff_pstripe=$(sed -e 's/.*stripe=//' -e 's/ .*//' <<<$ff)\n\t\telse\n\t\t\t# $LL_DECODE_FILTER_FID does not print \"stripe=\"; look\n\t\t\t# into f_ver in this case.  See comment on ff_parent.\n\t\t\tff_pstripe=$(cut -d: -f3 <<<$ff_parent | sed -e 's/]//')\n\t\tfi\n\n\t\t# compare lmm_seq and filter_fid->ff_parent.f_seq\n\t\t[ $ff_pseq = $lmm_seq ] ||\n\t\t\terror \"FF parent SEQ $ff_pseq != $lmm_seq\"\n\t\t# compare lmm_object_id and filter_fid->ff_parent.f_oid\n\t\t[ $ff_poid = $lmm_oid ] ||\n\t\t\terror \"FF parent OID $ff_poid != $lmm_oid\"\n\t\t(($ff_pstripe == $stripe_nr)) ||\n\t\t\terror \"FF stripe $ff_pstripe != $stripe_nr\"\n\n\t\tstripe_nr=$((stripe_nr + 1))\n\t\t[ $CLIENT_VERSION -lt $(version_code 2.9.55) ] &&\n\t\t\tcontinue\n\t\tif grep -q 'stripe_count=' <<<$ff; then\n\t\t\tlocal ff_scnt=$(sed -e 's/.*stripe_count=//' \\\n\t\t\t\t\t    -e 's/ .*//' <<<$ff)\n\t\t\t[ $lmm_count = $ff_scnt ] ||\n\t\t\t\terror \"FF stripe count $lmm_count != $ff_scnt\"\n\t\tfi\n\tdone\n}\n\ntest_27z() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 -S 64k $DIR/$tdir/$tfile-1 ||\n\t\t{ error \"setstripe -c -1 failed\"; return 1; }\n\t# We need to send a write to every object to get parent FID info set.\n\t# This _should_ also work for setattr, but does not currently.\n\t# touch $DIR/$tdir/$tfile-1 ||\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile-1 bs=1M count=1 ||\n\t\t{ error \"dd $tfile-1 failed\"; return 2; }\n\t$LFS setstripe -c -1 -i $((OSTCOUNT - 1)) -S 1M $DIR/$tdir/$tfile-2 ||\n\t\t{ error \"setstripe -c -1 failed\"; return 3; }\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile-2 bs=1M count=$OSTCOUNT ||\n\t\t{ error \"dd $tfile-2 failed\"; return 4; }\n\n\t# make sure write RPCs have been sent to OSTs\n\tsync; sleep 5; sync\n\n\tcheck_seq_oid $DIR/$tdir/$tfile-1 || return 5\n\tcheck_seq_oid $DIR/$tdir/$tfile-2 || return 6\n}\nrun_test 27z \"check SEQ/OID on the MDT and OST filesystems\"\n\ntest_27A() { # b=19102\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsave_layout_restore_at_exit $MOUNT\n\t$LFS setstripe -c 0 -i -1 -S 0 $MOUNT\n\twait_update $HOSTNAME \"$LFS getstripe -c $MOUNT | sed 's/  *//g'\" \"1\" 20 ||\n\t\terror \"stripe count $($LFS getstripe -c $MOUNT) != 1\"\n\tlocal default_size=$($LFS getstripe -S $MOUNT)\n\tlocal default_offset=$($LFS getstripe -i $MOUNT)\n\tlocal dsize=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize\")\n\t[ $default_size -eq $dsize ] ||\n\t\terror \"stripe size $default_size != $dsize\"\n\t[ $default_offset -eq -1 ] ||\n\t\terror \"stripe offset $default_offset != -1\"\n}\nrun_test 27A \"check filesystem-wide default LOV EA values\"\n\ntest_27B() { # LU-2523\n\ttest_mkdir $DIR/$tdir\n\trm -f $DIR/$tdir/f0 $DIR/$tdir/f1\n\ttouch $DIR/$tdir/f0\n\t# open f1 with O_LOV_DELAY_CREATE\n\t# rename f0 onto f1\n\t# call setstripe ioctl on open file descriptor for f1\n\t# close\n\tmultiop $DIR/$tdir/f1 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:nB1c \\\n\t\t$DIR/$tdir/f0\n\n\trm -f $DIR/$tdir/f1\n\t# open f1 with O_LOV_DELAY_CREATE\n\t# unlink f1\n\t# call setstripe ioctl on open file descriptor for f1\n\t# close\n\tmultiop $DIR/$tdir/f1 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:uB1c\n\n\t# Allow multiop to fail in imitation of NFS's busted semantics.\n\ttrue\n}\nrun_test 27B \"call setstripe on open unlinked file/rename victim\"\n\n# 27C family tests full striping and overstriping\ntest_27Ca() { #LU-2871\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tdeclare -a ost_idx\n\tlocal index\n\tlocal found\n\tlocal i\n\tlocal j\n\n\ttest_mkdir $DIR/$tdir\n\tcd $DIR/$tdir\n\tfor i in $(seq 0 $((OSTCOUNT - 1))); do\n\t\t# set stripe across all OSTs starting from OST$i\n\t\t$LFS setstripe -i $i -c -1 $tfile$i\n\t\t# get striping information\n\t\tost_idx=($($LFS getstripe $tfile$i |\n\t\t         tail -n $((OSTCOUNT + 1)) | awk '{print $1}'))\n\t\techo ${ost_idx[@]}\n\n\t\t# check the layout\n\t\t[ ${#ost_idx[@]} -eq $OSTCOUNT ] ||\n\t\t\terror \"${#ost_idx[@]} != $OSTCOUNT\"\n\n\t\tfor index in $(seq 0 $((OSTCOUNT - 1))); do\n\t\t\tfound=0\n\t\t\tfor j in $(echo ${ost_idx[@]}); do\n\t\t\t\tif [ $index -eq $j ]; then\n\t\t\t\t\tfound=1\n\t\t\t\t\tbreak\n\t\t\t\tfi\n\t\t\tdone\n\t\t\t[ $found = 1 ] ||\n\t\t\t\terror \"Can not find $index in ${ost_idx[@]}\"\n\t\tdone\n\tdone\n}\nrun_test 27Ca \"check full striping across all OSTs\"\n\ntest_27Cb() {\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\t[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&\n\t\tskip_env \"too many osts, skipping\"\n\n\ttest_mkdir -p $DIR/$tdir\n\tlocal setcount=$(($OSTCOUNT * 2))\n\t[ $setcount -ge 160 ] || large_xattr_enabled ||\n\t\tskip_env \"ea_inode feature disabled\"\n\n\t$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||\n\t\terror \"setstripe failed\"\n\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/$tfile)\n\t[ $count -eq $setcount ] ||\n\t\terror \"stripe count $count, should be $setcount\"\n\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"overstriped\" ||\n\t\terror \"overstriped should be set in pattern\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||\n\t\terror \"dd failed\"\n}\nrun_test 27Cb \"more stripes than OSTs with -C\"\n\ntest_27Cc() {\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"need > 1 OST\"\n\n\ttest_mkdir -p $DIR/$tdir\n\tlocal setcount=$(($OSTCOUNT - 1))\n\n\t[ $setcount -ge 160 ] || large_xattr_enabled ||\n\t\tskip_env \"ea_inode feature disabled\"\n\n\t$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||\n\t\terror \"setstripe failed\"\n\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/$tfile)\n\t[ $count -eq $setcount ] ||\n\t\terror \"stripe count $count, should be $setcount\"\n\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"overstriped\" &&\n\t\terror \"overstriped should not be set in pattern\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||\n\t\terror \"dd failed\"\n}\nrun_test 27Cc \"fewer stripes than OSTs does not set overstriping\"\n\ntest_27Cd() {\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"need > 1 OST\"\n\tlarge_xattr_enabled || skip_env \"ea_inode feature disabled\"\n\n\ttest_mkdir -p $DIR/$tdir\n\tlocal setcount=$LOV_MAX_STRIPE_COUNT\n\n\t$LFS setstripe -C $setcount $DIR/$tdir/$tfile ||\n\t\terror \"setstripe failed\"\n\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/$tfile)\n\t[ $count -eq $setcount ] ||\n\t\terror \"stripe count $count, should be $setcount\"\n\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"overstriped\" ||\n\t\terror \"overstriped should be set in pattern\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||\n\t\terror \"dd failed\"\n\n\trm -f $DIR/$tdir/$tfile || error \"Delete $tfile failed\"\n}\nrun_test 27Cd \"test maximum stripe count\"\n\ntest_27Ce() {\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\ttest_mkdir -p $DIR/$tdir\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"pool_add_targets failed\"\n\n\tlocal setcount=8\n\n\t$LFS setstripe  -C $setcount -p \"$TESTNAME\" $DIR/$tdir/$tfile ||\n\t\terror \"setstripe failed\"\n\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/$tfile)\n\t[ $count -eq $setcount ] ||\n\t\terror \"stripe count $count, should be $setcount\"\n\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"overstriped\" ||\n\t\terror \"overstriped should be set in pattern\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||\n\t\terror \"dd failed\"\n\n\trm -f $DIR/$tdir/$tfile || error \"Delete $tfile failed\"\n}\nrun_test 27Ce \"test pool with overstriping\"\n\ntest_27Cf() {\n\t[[ $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ]] ||\n\t\tskip \"server does not support overstriping\"\n\t[[ $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&\n\t\tskip_env \"too many osts, skipping\"\n\n\ttest_mkdir -p $DIR/$tdir\n\n\tlocal setcount=$(($OSTCOUNT * 2))\n\t[ $setcount -ge 160 ] || large_xattr_enabled ||\n\t\tskip_env \"ea_inode feature disabled\"\n\n\t$LFS setstripe  -C $setcount $DIR/$tdir/ ||\n\t\terror \"setstripe failed\"\n\n\techo 1 > $DIR/$tdir/$tfile\n\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/$tfile)\n\t[ $count -eq $setcount ] ||\n\t\terror \"stripe count $count, should be $setcount\"\n\n\t$LFS getstripe $DIR/$tdir/$tfile 2>&1 | grep \"overstriped\" ||\n\t\terror \"overstriped should be set in pattern\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=4 conv=notrunc ||\n\t\terror \"dd failed\"\n\n\trm -f $DIR/$tdir/$tfile || error \"Delete $tfile failed\"\n}\nrun_test 27Cf \"test default inheritance with overstriping\"\n\ntest_27D() {\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal POOL=${POOL:-testpool}\n\tlocal first_ost=0\n\tlocal last_ost=$(($OSTCOUNT - 1))\n\tlocal ost_step=1\n\tlocal ost_list=$(seq $first_ost $ost_step $last_ost)\n\tlocal ost_range=\"$first_ost $last_ost $ost_step\"\n\n\ttest_mkdir $DIR/$tdir\n\tpool_add $POOL || error \"pool_add failed\"\n\tpool_add_targets $POOL $ost_range || error \"pool_add_targets failed\"\n\n\tlocal skip27D\n\t[ $MDS1_VERSION -lt $(version_code 2.8.55) ] &&\n\t\tskip27D+=\"-s 29\"\n\t[ $MDS1_VERSION -lt $(version_code 2.9.55) ] ||\n\t\t[ $CLIENT_VERSION -lt $(version_code 2.9.55) ] &&\n\t\t\tskip27D+=\" -s 30,31\"\n\t[[ ! $($LCTL get_param mdc.*.import) =~ connect_flags.*overstriping ||\n\t  $OSTCOUNT -ge $(($LOV_MAX_STRIPE_COUNT / 2)) ]] &&\n\t\tskip27D+=\" -s 32,33\"\n\t[[ $MDS_VERSION -lt $(version_code $SEL_VER) ]] &&\n\t\tskip27D+=\" -s 34\"\n\tllapi_layout_test -d$DIR/$tdir -p$POOL -o$OSTCOUNT $skip27D ||\n\t\terror \"llapi_layout_test failed\"\n\n\tdestroy_test_pools || error \"destroy test pools failed\"\n}\nrun_test 27D \"validate llapi_layout API\"\n\n# Verify that default_easize is increased from its initial value after\n# accessing a widely striped file.\ntest_27E() {\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\t[ $CLIENT_VERSION -lt $(version_code 2.5.57) ] &&\n\t\tskip \"client does not have LU-3338 fix\"\n\n\t# 72 bytes is the minimum space required to store striping\n\t# information for a file striped across one OST:\n\t# (sizeof(struct lov_user_md_v3) +\n\t#  sizeof(struct lov_user_ost_data_v1))\n\tlocal min_easize=72\n\t$LCTL set_param -n llite.*.default_easize $min_easize ||\n\t\terror \"lctl set_param failed\"\n\tlocal easize=$($LCTL get_param -n llite.*.default_easize)\n\n\t[ $easize -eq $min_easize ] ||\n\t\terror \"failed to set default_easize\"\n\n\t$LFS setstripe -c $OSTCOUNT $DIR/$tfile ||\n\t\terror \"setstripe failed\"\n\t# In order to ensure stat() call actually talks to MDS we need to\n\t# do something drastic to this file to shake off all lock, e.g.\n\t# rename it (kills lookup lock forcing cache cleaning)\n\tmv $DIR/$tfile $DIR/${tfile}-1\n\tls -l $DIR/${tfile}-1\n\trm $DIR/${tfile}-1\n\n\teasize=$($LCTL get_param -n llite.*.default_easize)\n\n\t[ $easize -gt $min_easize ] ||\n\t\terror \"default_easize not updated\"\n}\nrun_test 27E \"check that default extended attribute size properly increases\"\n\ntest_27F() { # LU-5346/LU-7975\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip \"needs >= 2 OSTs\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.8.51) ]] &&\n\t\tskip \"Need MDS version at least 2.8.51\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\ttest_mkdir $DIR/$tdir\n\trm -f $DIR/$tdir/f0\n\t$LFS setstripe -c 2 $DIR/$tdir\n\n\t# stop all OSTs to reproduce situation for LU-7975 ticket\n\tfor num in $(seq $OSTCOUNT); do\n\t\tstop ost$num\n\tdone\n\n\t# open/create f0 with O_LOV_DELAY_CREATE\n\t# truncate f0 to a non-0 size\n\t# close\n\tmultiop $DIR/$tdir/f0 oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:T1050000c\n\n\t$CHECKSTAT -s 1050000 $DIR/$tdir/f0 || error \"checkstat failed\"\n\t# open/write it again to force delayed layout creation\n\tcat /etc/hosts > $DIR/$tdir/f0 &\n\tcatpid=$!\n\n\t# restart OSTs\n\tfor num in $(seq $OSTCOUNT); do\n\t\tstart ost$num $(ostdevname $num) $OST_MOUNT_OPTS ||\n\t\t\terror \"ost$num failed to start\"\n\tdone\n\n\twait $catpid || error \"cat failed\"\n\n\tcmp /etc/hosts $DIR/$tdir/f0 || error \"cmp failed\"\n\t[[ $($LFS getstripe -c $DIR/$tdir/f0) == 2 ]] ||\n\t\terror \"wrong stripecount\"\n\n}\nrun_test 27F \"Client resend delayed layout creation with non-zero size\"\n\ntest_27G() { #LU-10629\n\t[ $MDS1_VERSION -lt $(version_code 2.11.51) ] &&\n\t\tskip \"Need MDS version at least 2.11.51\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tlocal POOL=${POOL:-testpool}\n\tlocal ostrange=\"0 0 1\"\n\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile.nopool\n\tpool_add $POOL || error \"pool_add failed\"\n\tpool_add_targets $POOL $ostrange || error \"pool_add_targets failed\"\n\t$LFS setstripe -p $POOL $DIR/$tdir\n\n\tlocal pool=$($LFS getstripe -p $DIR/$tdir)\n\n\t[ \"$pool\" = \"$POOL\" ] || error \"Striping failed got '$pool' not '$POOL'\"\n\ttouch $DIR/$tdir/$tfile.default\n\t$LFS setstripe -E 1M --pool $POOL -c 1 -E eof -c 1 $DIR/$tdir/$tfile.pfl\n\t$LFS find $DIR/$tdir -type f --pool $POOL\n\tlocal found=$($LFS find $DIR/$tdir -type f --pool $POOL | wc -l)\n\t[[ \"$found\" == \"2\" ]] ||\n\t\terror \"found $found != 2 files in '$DIR/$tdir' in '$POOL'\"\n\n\t$LFS setstripe -d $DIR/$tdir\n\n\tpool=$($LFS getstripe -p -d $DIR/$tdir)\n\n\t[[ \"$pool\" != \"$POOL\" ]] || error \"$DIR/$tdir is still '$pool'\"\n}\nrun_test 27G \"Clear OST pool from stripe\"\n\ntest_27H() {\n\t[[ $MDS1_VERSION -le $(version_code 2.11.54) ]] &&\n\t\tskip \"Need MDS version newer than 2.11.54\"\n\t[[ $OSTCOUNT -lt 3 ]] && skip_env \"needs >= 3 OSTs\"\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -o 0 -o 2 $DIR/$tdir || error \"setstripe failed\"\n\ttouch $DIR/$tdir/$tfile\n\t$LFS getstripe -c $DIR/$tdir/$tfile\n\t[ $($LFS getstripe -c $DIR/$tdir/$tfile) -eq 2 ] ||\n\t\terror \"two-stripe file doesn't have two stripes\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=4k count=4 || error \"dd failed\"\n\t$LFS getstripe -y $DIR/$tdir/$tfile\n\t(( $($LFS getstripe -y $DIR/$tdir/$tfile |\n\t     egrep -c \"l_ost_idx: [02]$\") == \"2\" )) ||\n\t\terror \"expected l_ost_idx: [02]$ not matched\"\n\n\t# make sure ost list has been cleared\n\tlocal stripesize=$($LFS getstripe -S $DIR/$tdir)\n\t$LFS setstripe -S $((stripesize * 4)) -i 1 \\\n\t\t-c $((OSTCOUNT - 1)) $DIR/$tdir || error \"setstripe\"\n\ttouch $DIR/$tdir/f3\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f3 || error \"lverify failed\"\n}\nrun_test 27H \"Set specific OSTs stripe\"\n\ntest_27I() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[[ $MDS1_VERSION -gt $(version_code 2.12.52) ]] ||\n\t\tskip \"Need MDS version newer than 2.12.52\"\n\tlocal pool=$TESTNAME\n\tlocal ostrange=\"1 1 1\"\n\n\tsave_layout_restore_at_exit $MOUNT\n\t$LFS setstripe -c 2 -i 0 $MOUNT\n\tpool_add $pool || error \"pool_add failed\"\n\tpool_add_targets $pool $ostrange || \"pool_add_targets failed\"\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -p $pool $DIR/$tdir\n\t$MULTIOP $DIR/$tdir/$tfile Oc || error \"multiop failed\"\n\t$LFS getstripe $DIR/$tdir/$tfile\n}\nrun_test 27I \"check that root dir striping does not break parent dir one\"\n\ntest_27J() {\n\t[[ $MDS1_VERSION -le $(version_code 2.12.51) ]] &&\n\t\tskip \"Need MDS version newer than 2.12.51\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal uuid1=$(cat /proc/sys/kernel/random/uuid)\n\tlocal uuid2=$(cat /proc/sys/kernel/random/uuid)\n\n\t# create foreign file (raw way)\n\tcreate_foreign_file -f $DIR/$tdir/$tfile -x \"${uuid1}@${uuid2}\" \\\n\t\t-t 1 -F 0xda08 || error \"create_foreign_file failed\"\n\n\t# verify foreign file (raw way)\n\tparse_foreign_file -f $DIR/$tdir/$tfile |\n\t\tgrep \"lov_foreign_magic: 0x0BD70BD0\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign magic\"\n\tparse_foreign_file -f $DIR/$tdir/$tfile | grep \"lov_xattr_size: 89\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign size\"\n\tparse_foreign_file -f $DIR/$tdir/$tfile |\n\t\tgrep \"lov_foreign_size: 73\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign size\"\n\tparse_foreign_file -f $DIR/$tdir/$tfile |\n\t\tgrep \"lov_foreign_type: 1\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign type\"\n\tparse_foreign_file -f $DIR/$tdir/$tfile |\n\t\tgrep \"lov_foreign_flags: 0x0000DA08\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign flags\"\n\tlocal lov=$(parse_foreign_file -f $DIR/$tdir/$tfile |\n\t\tgrep \"lov_foreign_value: 0x\" |\n\t\tsed -e 's/lov_foreign_value: 0x//')\n\tlocal lov2=$(echo -n \"${uuid1}@${uuid2}\" | od -A n -t x1 -w160)\n\t[[ $lov = ${lov2// /} ]] ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LOV EA foreign value\"\n\n\t# create foreign file (lfs + API)\n\t$LFS setstripe --foreign=daos --flags 0xda08 \\\n\t\t-x \"${uuid1}@${uuid2}\" $DIR/$tdir/${tfile}2 ||\n\t\terror \"$DIR/$tdir/${tfile}2: create failed\"\n\n\t$LFS getstripe -v $DIR/$tdir/${tfile}2 |\n\t\tgrep \"lfm_magic:.*0x0BD70BD0\" ||\n\t\terror \"$DIR/$tdir/${tfile}2: invalid LOV EA foreign magic\"\n\t# lfm_length is LOV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t$LFS getstripe -v $DIR/$tdir/${tfile}2 | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/${tfile}2: invalid LOV EA foreign size\"\n\t$LFS getstripe -v $DIR/$tdir/${tfile}2 | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/${tfile}2: invalid LOV EA foreign type\"\n\t$LFS getstripe -v $DIR/$tdir/${tfile}2 |\n\t\tgrep \"lfm_flags:.*0x0000DA08\" ||\n\t\terror \"$DIR/$tdir/${tfile}2: invalid LOV EA foreign flags\"\n\t$LFS getstripe $DIR/$tdir/${tfile}2 |\n\t\tgrep \"lfm_value:.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/${tfile}2: invalid LOV EA foreign value\"\n\n\t# modify striping should fail\n\t$LFS setstripe -c 2 $DIR/$tdir/$tfile &&\n\t\terror \"$DIR/$tdir/$tfile: setstripe should fail\"\n\t$LFS setstripe -c 2 $DIR/$tdir/${tfile}2 &&\n\t\terror \"$DIR/$tdir/${tfile}2: setstripe should fail\"\n\n\t# R/W should fail\n\tcat $DIR/$tdir/$tfile && error \"$DIR/$tdir/$tfile: read should fail\"\n\tcat $DIR/$tdir/${tfile}2 &&\n\t\terror \"$DIR/$tdir/${tfile}2: read should fail\"\n\tcat /etc/passwd > $DIR/$tdir/$tfile &&\n\t\terror \"$DIR/$tdir/$tfile: write should fail\"\n\tcat /etc/passwd > $DIR/$tdir/${tfile}2 &&\n\t\terror \"$DIR/$tdir/${tfile}2: write should fail\"\n\n\t# chmod should work\n\tchmod 222 $DIR/$tdir/$tfile ||\n\t\terror \"$DIR/$tdir/$tfile: chmod failed\"\n\tchmod 222 $DIR/$tdir/${tfile}2 ||\n\t\terror \"$DIR/$tdir/${tfile}2: chmod failed\"\n\n\t# chown should work\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/$tfile ||\n\t\terror \"$DIR/$tdir/$tfile: chown failed\"\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tfile}2 ||\n\t\terror \"$DIR/$tdir/${tfile}2: chown failed\"\n\n\t# rename should work\n\tmv $DIR/$tdir/$tfile $DIR/$tdir/${tfile}.new ||\n\t\terror \"$DIR/$tdir/$tfile: rename of foreign file has failed\"\n\tmv $DIR/$tdir/${tfile}2 $DIR/$tdir/${tfile}2.new ||\n\t\terror \"$DIR/$tdir/${tfile}2: rename of foreign file has failed\"\n\n\t#remove foreign file\n\trm $DIR/$tdir/${tfile}.new ||\n\t\terror \"$DIR/$tdir/${tfile}.new: remove of foreign file has failed\"\n\trm $DIR/$tdir/${tfile}2.new ||\n\t\terror \"$DIR/$tdir/${tfile}2.new: remove of foreign file has failed\"\n}\nrun_test 27J \"basic ops on file with foreign LOV\"\n\ntest_27K() {\n\t[[ $MDS1_VERSION -le $(version_code 2.12.49) ]] &&\n\t\tskip \"Need MDS version newer than 2.12.49\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal uuid1=$(cat /proc/sys/kernel/random/uuid)\n\tlocal uuid2=$(cat /proc/sys/kernel/random/uuid)\n\n\t# create foreign dir (raw way)\n\tcreate_foreign_dir -d $DIR/$tdir/$tdir -x \"${uuid1}@${uuid2}\" -t 1 ||\n\t\terror \"create_foreign_dir FAILED\"\n\n\t# verify foreign dir (raw way)\n\tparse_foreign_dir -d $DIR/$tdir/$tdir |\n\t\tgrep \"lmv_foreign_magic:.*0xcd50cd0\" ||\n\t\terror \"$DIR/$tdir/$tfile: invalid LMV EA magic\"\n\tparse_foreign_dir -d $DIR/$tdir/$tdir | grep \"lmv_xattr_size:.*89$\" ||\n\t\terror \"$DIR/$tdir/$tdir: invalid LMV EA size\"\n\tparse_foreign_dir -d $DIR/$tdir/$tdir | grep \"lmv_foreign_type: 1$\" ||\n\t\terror \"$DIR/$tdir/$tdir: invalid LMV EA type\"\n\tparse_foreign_dir -d $DIR/$tdir/$tdir | grep \"lmv_foreign_flags: 0$\" ||\n\t\terror \"$DIR/$tdir/$tdir: invalid LMV EA flags\"\n\tlocal lmv=$(parse_foreign_dir -d $DIR/$tdir/$tdir |\n\t\tgrep \"lmv_foreign_value: 0x\" |\n\t\tsed 's/lmv_foreign_value: 0x//')\n\tlocal lmv2=$(echo -n \"${uuid1}@${uuid2}\" | od -A n -t x1 -w160 |\n\t\tsed 's/ //g')\n\t[[ $lmv == $lmv2 ]] || error \"$DIR/$tdir/$tdir: invalid LMV EA value\"\n\n\t# create foreign dir (lfs + API)\n\t$LFS mkdir --foreign=daos --xattr=\"${uuid1}@${uuid2}\" --flags=0xda05 \\\n\t\t$DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/$tdir/${tdir}2: create failed\"\n\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_magic:.*0x0CD50CD0\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA magic\"\n\t# lfm_length is LMV EA size - sizeof(lfm_magic) - sizeof(lfm_length)\n\t# - sizeof(lfm_type) - sizeof(lfm_flags)\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_length:.*73\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA size\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 | grep \"lfm_type:.*daos\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA type\"\n\t$LFS getdirstripe -v $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_flags:.*0x0000DA05\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA flags\"\n\t$LFS getdirstripe $DIR/$tdir/${tdir}2 |\n\t\tgrep \"lfm_value.*${uuid1}@${uuid2}\" ||\n\t\terror \"$DIR/$tdir/${tdir}2: invalid LMV EA value\"\n\n\t# file create in dir should fail\n\ttouch $DIR/$tdir/$tdir/$tfile && \"$DIR/$tdir: file create should fail\"\n\ttouch $DIR/$tdir/${tdir}2/$tfile &&\n\t\t\"$DIR/${tdir}2: file create should fail\"\n\n\t# chmod should work\n\tchmod 777 $DIR/$tdir/$tdir ||\n\t\terror \"$DIR/$tdir: chmod failed\"\n\tchmod 777 $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chmod failed\"\n\n\t# chown should work\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/$tdir ||\n\t\terror \"$DIR/$tdir: chown failed\"\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/${tdir}2 ||\n\t\terror \"$DIR/${tdir}2: chown failed\"\n\n\t# rename should work\n\tmv $DIR/$tdir/$tdir $DIR/$tdir/${tdir}.new ||\n\t\terror \"$DIR/$tdir/$tdir: rename of foreign dir has failed\"\n\tmv $DIR/$tdir/${tdir}2 $DIR/$tdir/${tdir}2.new ||\n\t\terror \"$DIR/$tdir/${tdir}2: rename of foreign dir has failed\"\n\n\t#remove foreign dir\n\trmdir $DIR/$tdir/${tdir}.new ||\n\t\terror \"$DIR/$tdir/${tdir}.new: remove of foreign dir has failed\"\n\trmdir $DIR/$tdir/${tdir}2.new ||\n\t\terror \"$DIR/$tdir/${tdir}2.new: remove of foreign dir has failed\"\n}\nrun_test 27K \"basic ops on dir with foreign LMV\"\n\ntest_27L() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal POOL=${POOL:-$TESTNAME}\n\n\tpool_add $POOL || error \"pool_add failed\"\n\n\tlfs pool_list $MOUNT | grep -Fx \"${FSNAME}.${POOL}\" ||\n\t\t error \"pool_list does not contain ${FSNAME}.${POOL}:\" \\\n\t\t       \"$(lfs pool_list $MOUNT | grep -F \"${POOL}\")\"\n}\nrun_test 27L \"lfs pool_list gives correct pool name\"\n\ntest_27M() {\n\t[[ $(lustre_version_code $SINGLEMDS) -lt $(version_code 2.12.57) ]] &&\n\t\tskip \"Need MDS version >= than 2.12.57\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"need > 1 OST\"\n\n\ttest_mkdir $DIR/$tdir\n\n\t# Set default striping on directory\n\t$LFS setstripe -C 4 $DIR/$tdir\n\n\techo 1 > $DIR/$tdir/${tfile}.1\n\tlocal count=$($LFS getstripe -c $DIR/$tdir/${tfile}.1)\n\tlocal setcount=4\n\t[ $count -eq $setcount ] ||\n\t\terror \"(1) stripe count $count, should be $setcount\"\n\n\t# Capture existing append_stripe_count setting for restore\n\tlocal orig_count=$(do_facet mds1 $LCTL get_param -n mdd.$FSNAME-MDT0000.append_stripe_count)\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\tstack_trap \"do_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=$orig_count\" EXIT\n\n\tlocal appendcount=$orig_count\n\techo 1 >> $DIR/$tdir/${tfile}.2_append\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.2_append)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(2)stripe count $count, should be $appendcount for append\"\n\n\t# Disable O_APPEND striping, verify it works\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=0\n\n\t# Should now get the default striping, which is 4\n\tsetcount=4\n\techo 1 >> $DIR/$tdir/${tfile}.3_append\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.3_append)\n\t[ $count -eq $setcount ] ||\n\t\terror \"(3) stripe count $count, should be $setcount\"\n\n\t# Try changing the stripe count for append files\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=2\n\n\t# Append striping is now 2 (directory default is still 4)\n\tappendcount=2\n\techo 1 >> $DIR/$tdir/${tfile}.4_append\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.4_append)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(4) stripe count $count, should be $appendcount for append\"\n\n\t# Test append stripe count of -1\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=-1\n\tappendcount=$OSTCOUNT\n\techo 1 >> $DIR/$tdir/${tfile}.5\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.5)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(5) stripe count $count, should be $appendcount for append\"\n\n\t# Set append striping back to default of 1\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=1\n\n\t# Try a new default striping, PFL + DOM\n\t$LFS setstripe -L mdt -E 1M -E -1 -c 2 $DIR/$tdir\n\n\t# Create normal DOM file, DOM returns stripe count == 0\n\tsetcount=0\n\ttouch $DIR/$tdir/${tfile}.6\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.6)\n\t[ $count -eq $setcount ] ||\n\t\terror \"(6) stripe count $count, should be $setcount\"\n\n\t# Show\n\tappendcount=1\n\techo 1 >> $DIR/$tdir/${tfile}.7_append\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.7_append)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(7) stripe count $count, should be $appendcount for append\"\n\n\t# Clean up DOM layout\n\t$LFS setstripe -d $DIR/$tdir\n\n\t# Now test that append striping works when layout is from root\n\t$LFS setstripe -c 2 $MOUNT\n\t# Make a special directory for this\n\tmkdir $DIR/${tdir}/${tdir}.2\n\tstack_trap \"$LFS setstripe -d $MOUNT\" EXIT\n\n\t# Verify for normal file\n\tsetcount=2\n\techo 1 > $DIR/${tdir}/${tdir}.2/${tfile}.8\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tdir}.2/${tfile}.8)\n\t[ $count -eq $setcount ] ||\n\t\terror \"(8) stripe count $count, should be $setcount\"\n\n\tappendcount=1\n\techo 1 >> $DIR/${tdir}/${tdir}.2/${tfile}.9_append\n\tcount=$($LFS getstripe -c $DIR/${tdir}/${tdir}.2/${tfile}.9_append)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(9) stripe count $count, should be $appendcount for append\"\n\n\t# Now test O_APPEND striping with pools\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_pool=\"$TESTNAME\"\n\tstack_trap \"do_nodes $mdts $LCTL set_param mdd.*.append_pool='none'\" EXIT\n\n\t# Create the pool\n\tpool_add $TESTNAME || error \"pool creation failed\"\n\tpool_add_targets $TESTNAME 0 1 || error \"Pool add targets failed\"\n\n\techo 1 >> $DIR/$tdir/${tfile}.10_append\n\n\tpool=$($LFS getstripe -p $DIR/$tdir/${tfile}.10_append)\n\t[ \"$pool\" = \"$TESTNAME\" ] || error \"(10) incorrect pool: $pool\"\n\n\t# Check that count is still correct\n\tappendcount=1\n\techo 1 >> $DIR/$tdir/${tfile}.11_append\n\tcount=$($LFS getstripe -c $DIR/$tdir/${tfile}.11_append)\n\t[ $count -eq $appendcount ] ||\n\t\terror \"(11) stripe count $count, should be $appendcount for append\"\n\n\t# Disable O_APPEND stripe count, verify pool works separately\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_stripe_count=0\n\n\techo 1 >> $DIR/$tdir/${tfile}.12_append\n\n\tpool=$($LFS getstripe -p $DIR/$tdir/${tfile}.12_append)\n\t[ \"$pool\" = \"$TESTNAME\" ] || error \"(12) incorrect pool: $pool\"\n\n\t# Remove pool setting, verify it's not applied\n\tdo_nodes $mdts $LCTL set_param mdd.*.append_pool='none'\n\n\techo 1 >> $DIR/$tdir/${tfile}.13_append\n\n\tpool=$($LFS getstripe -p $DIR/$tdir/${tfile}.13_append)\n\t[ \"$pool\" = \"\" ] || error \"(13) pool found: $pool\"\n}\nrun_test 27M \"test O_APPEND striping\"\n\ntest_27N() {\n\tcombined_mgs_mds && skip \"needs separate MGS/MDT\"\n\n\tpool_add $TESTNAME || error \"pool_add failed\"\n\tdo_facet mgs \"$LCTL pool_list $FSNAME\" |\n\t\tgrep -Fx \"${FSNAME}.${TESTNAME}\" ||\n\t\terror \"lctl pool_list on MGS failed\"\n}\nrun_test 27N \"lctl pool_list on separate MGS gives correct pool name\"\n\n# createtest also checks that device nodes are created and\n# then visible correctly (#2091)\ntest_28() { # bug 2091\n\ttest_mkdir $DIR/d28\n\t$CREATETEST $DIR/d28/ct || error \"createtest failed\"\n}\nrun_test 28 \"create/mknod/mkdir with bad file types ============\"\n\ntest_29() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsync; sleep 1; sync # flush out any dirty pages from previous tests\n\tcancel_lru_locks\n\ttest_mkdir $DIR/d29\n\ttouch $DIR/d29/foo\n\tlog 'first d29'\n\tls -l $DIR/d29\n\n\tdeclare -i LOCKCOUNTORIG=0\n\tfor lock_count in $(lctl get_param -n ldlm.namespaces.*mdc*.lock_count); do\n\t\tlet LOCKCOUNTORIG=$LOCKCOUNTORIG+$lock_count\n\tdone\n\t[ $LOCKCOUNTORIG -eq 0 ] && error \"No mdc lock count\" && return 1\n\n\tdeclare -i LOCKUNUSEDCOUNTORIG=0\n\tfor unused_count in $(lctl get_param -n ldlm.namespaces.*mdc*.lock_unused_count); do\n\t\tlet LOCKUNUSEDCOUNTORIG=$LOCKUNUSEDCOUNTORIG+$unused_count\n\tdone\n\n\tlog 'second d29'\n\tls -l $DIR/d29\n\tlog 'done'\n\n\tdeclare -i LOCKCOUNTCURRENT=0\n\tfor lock_count in $(lctl get_param -n ldlm.namespaces.*mdc*.lock_count); do\n\t\tlet LOCKCOUNTCURRENT=$LOCKCOUNTCURRENT+$lock_count\n\tdone\n\n\tdeclare -i LOCKUNUSEDCOUNTCURRENT=0\n\tfor unused_count in $(lctl get_param -n ldlm.namespaces.*mdc*.lock_unused_count); do\n\t\tlet LOCKUNUSEDCOUNTCURRENT=$LOCKUNUSEDCOUNTCURRENT+$unused_count\n\tdone\n\n\tif [[ $LOCKCOUNTCURRENT -gt $LOCKCOUNTORIG ]]; then\n\t\t$LCTL set_param -n ldlm.dump_namespaces \"\"\n\t\terror \"CURRENT: $LOCKCOUNTCURRENT > $LOCKCOUNTORIG\"\n\t\t$LCTL dk | sort -k4 -t: > $TMP/test_29.dk\n\t\tlog \"dumped log to $TMP/test_29.dk (bug 5793)\"\n\t\treturn 2\n\tfi\n\tif [[ $LOCKUNUSEDCOUNTCURRENT -gt $LOCKUNUSEDCOUNTORIG ]]; then\n\t\terror \"UNUSED: $LOCKUNUSEDCOUNTCURRENT > $LOCKUNUSEDCOUNTORIG\"\n\t\t$LCTL dk | sort -k4 -t: > $TMP/test_29.dk\n\t\tlog \"dumped log to $TMP/test_29.dk (bug 5793)\"\n\t\treturn 3\n\tfi\n}\nrun_test 29 \"IT_GETATTR regression  ============================\"\n\ntest_30a() { # was test_30\n\tcp $(which ls) $DIR || cp /bin/ls $DIR\n\t$DIR/ls / || error \"Can't execute binary from lustre\"\n\trm $DIR/ls\n}\nrun_test 30a \"execute binary from Lustre (execve) ==============\"\n\ntest_30b() {\n\tcp `which ls` $DIR || cp /bin/ls $DIR\n\tchmod go+rx $DIR/ls\n\t$RUNAS $DIR/ls / || error \"Can't execute binary from lustre as non-root\"\n\trm $DIR/ls\n}\nrun_test 30b \"execute binary from Lustre as non-root ===========\"\n\ntest_30c() { # b=22376\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tcp $(which ls) $DIR || cp /bin/ls $DIR\n\tchmod a-rw $DIR/ls\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\t$RUNAS $DIR/ls / || error \"Can't execute binary from lustre\"\n\trm -f $DIR/ls\n}\nrun_test 30c \"execute binary from Lustre without read perms ====\"\n\ntest_30d() {\n\tcp $(which dd) $DIR || error \"failed to copy dd to $DIR/dd\"\n\n\tfor i in {1..10}; do\n\t\t$DIR/dd bs=1M count=128 if=/dev/zero of=$DIR/$tfile &\n\t\tlocal PID=$!\n\t\tsleep 1\n\t\t$LCTL set_param ldlm.namespaces.*MDT*.lru_size=clear\n\t\twait $PID || error \"executing dd from Lustre failed\"\n\t\trm -f $DIR/$tfile\n\tdone\n\n\trm -f $DIR/dd\n}\nrun_test 30d \"execute binary from Lustre while clear locks\"\n\ntest_31a() {\n\t$OPENUNLINK $DIR/f31 $DIR/f31 || error \"openunlink failed\"\n\t$CHECKSTAT -a $DIR/f31 || error \"$DIR/f31 exists\"\n}\nrun_test 31a \"open-unlink file ==================================\"\n\ntest_31b() {\n\ttouch $DIR/f31 || error \"touch $DIR/f31 failed\"\n\tln $DIR/f31 $DIR/f31b || error \"ln failed\"\n\t$MULTIOP $DIR/f31b Ouc || error \"multiop failed\"\n\t$CHECKSTAT -t file $DIR/f31 || error \"$DIR/f31 not file type\"\n}\nrun_test 31b \"unlink file with multiple links while open =======\"\n\ntest_31c() {\n\ttouch $DIR/f31 || error \"touch $DIR/f31 failed\"\n\tln $DIR/f31 $DIR/f31c || error \"ln failed\"\n\tmultiop_bg_pause $DIR/f31 O_uc ||\n\t\terror \"multiop_bg_pause for $DIR/f31 failed\"\n\tMULTIPID=$!\n\t$MULTIOP $DIR/f31c Ouc\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID\n}\nrun_test 31c \"open-unlink file with multiple links =============\"\n\ntest_31d() {\n\topendirunlink $DIR/d31d $DIR/d31d || error \"opendirunlink failed\"\n\t$CHECKSTAT -a $DIR/d31d || error \"$DIR/d31d exists\"\n}\nrun_test 31d \"remove of open directory =========================\"\n\ntest_31e() { # bug 2904\n\topenfilleddirunlink $DIR/d31e || error \"openfilleddirunlink failed\"\n}\nrun_test 31e \"remove of open non-empty directory ===============\"\n\ntest_31f() { # bug 4554\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tset -vx\n\ttest_mkdir $DIR/d31f\n\t$LFS setstripe -S 1048576 -c 1 $DIR/d31f\n\tcp /etc/hosts $DIR/d31f\n\tls -l $DIR/d31f\n\t$LFS getstripe $DIR/d31f/hosts\n\tmultiop_bg_pause $DIR/d31f D_c || return 1\n\tMULTIPID=$!\n\n\trm -rv $DIR/d31f || error \"first of $DIR/d31f\"\n\ttest_mkdir $DIR/d31f\n\t$LFS setstripe -S 1048576 -c 1 $DIR/d31f\n\tcp /etc/hosts $DIR/d31f\n\tls -l $DIR/d31f\n\t$LFS getstripe $DIR/d31f/hosts\n\tmultiop_bg_pause $DIR/d31f D_c || return 1\n\tMULTIPID2=$!\n\n\tkill -USR1 $MULTIPID || error \"first opendir $MULTIPID not running\"\n\twait $MULTIPID || error \"first opendir $MULTIPID failed\"\n\n\tsleep 6\n\n\tkill -USR1 $MULTIPID2 || error \"second opendir $MULTIPID not running\"\n\twait $MULTIPID2 || error \"second opendir $MULTIPID2 failed\"\n\tset +vx\n}\nrun_test 31f \"remove of open directory with open-unlink file ===\"\n\ntest_31g() {\n\techo \"-- cross directory link --\"\n\ttest_mkdir -c1 $DIR/${tdir}ga\n\ttest_mkdir -c1 $DIR/${tdir}gb\n\ttouch $DIR/${tdir}ga/f\n\tln $DIR/${tdir}ga/f $DIR/${tdir}gb/g\n\t$CHECKSTAT -t file $DIR/${tdir}ga/f || error \"source\"\n\t[ `stat -c%h $DIR/${tdir}ga/f` == '2' ] || error \"source nlink\"\n\t$CHECKSTAT -t file $DIR/${tdir}gb/g || error \"target\"\n\t[ `stat -c%h $DIR/${tdir}gb/g` == '2' ] || error \"target nlink\"\n}\nrun_test 31g \"cross directory link===============\"\n\ntest_31h() {\n\techo \"-- cross directory link --\"\n\ttest_mkdir -c1 $DIR/${tdir}\n\ttest_mkdir -c1 $DIR/${tdir}/dir\n\ttouch $DIR/${tdir}/f\n\tln $DIR/${tdir}/f $DIR/${tdir}/dir/g\n\t$CHECKSTAT -t file $DIR/${tdir}/f || error \"source\"\n\t[ `stat -c%h $DIR/${tdir}/f` == '2' ] || error \"source nlink\"\n\t$CHECKSTAT -t file $DIR/${tdir}/dir/g || error \"target\"\n\t[ `stat -c%h $DIR/${tdir}/dir/g` == '2' ] || error \"target nlink\"\n}\nrun_test 31h \"cross directory link under child===============\"\n\ntest_31i() {\n\techo \"-- cross directory link --\"\n\ttest_mkdir -c1 $DIR/$tdir\n\ttest_mkdir -c1 $DIR/$tdir/dir\n\ttouch $DIR/$tdir/dir/f\n\tln $DIR/$tdir/dir/f $DIR/$tdir/g\n\t$CHECKSTAT -t file $DIR/$tdir/dir/f || error \"source\"\n\t[ `stat -c%h $DIR/$tdir/dir/f` == '2' ] || error \"source nlink\"\n\t$CHECKSTAT -t file $DIR/$tdir/g || error \"target\"\n\t[ `stat -c%h $DIR/$tdir/g` == '2' ] || error \"target nlink\"\n}\nrun_test 31i \"cross directory link under parent===============\"\n\ntest_31j() {\n\ttest_mkdir -c1 -p $DIR/$tdir\n\ttest_mkdir -c1 -p $DIR/$tdir/dir1\n\tln $DIR/$tdir/dir1 $DIR/$tdir/dir2 && error \"ln for dir\"\n\tlink $DIR/$tdir/dir1 $DIR/$tdir/dir3 && error \"link for dir\"\n\tmlink $DIR/$tdir/dir1 $DIR/$tdir/dir4 && error \"mlink for dir\"\n\tmlink $DIR/$tdir/dir1 $DIR/$tdir/dir1 && error \"mlink to the same dir\"\n\treturn 0\n}\nrun_test 31j \"link for directory===============\"\n\ntest_31k() {\n        test_mkdir -c1 -p $DIR/$tdir\n        touch $DIR/$tdir/s\n        touch $DIR/$tdir/exist\n        mlink $DIR/$tdir/s $DIR/$tdir/t || error \"mlink\"\n        mlink $DIR/$tdir/s $DIR/$tdir/exist && error \"mlink to exist file\"\n        mlink $DIR/$tdir/s $DIR/$tdir/s && error \"mlink to the same file\"\n        mlink $DIR/$tdir/s $DIR/$tdir && error \"mlink to parent dir\"\n        mlink $DIR/$tdir $DIR/$tdir/s && error \"mlink parent dir to target\"\n        mlink $DIR/$tdir/not-exist $DIR/$tdir/foo && error \"mlink non-existing to new\"\n        mlink $DIR/$tdir/not-exist $DIR/$tdir/s && error \"mlink non-existing to exist\"\n\treturn 0\n}\nrun_test 31k \"link to file: the same, non-existing, dir===============\"\n\ntest_31m() {\n        mkdir $DIR/d31m\n        touch $DIR/d31m/s\n        mkdir $DIR/d31m2\n        touch $DIR/d31m2/exist\n        mlink $DIR/d31m/s $DIR/d31m2/t || error \"mlink\"\n        mlink $DIR/d31m/s $DIR/d31m2/exist && error \"mlink to exist file\"\n        mlink $DIR/d31m/s $DIR/d31m2 && error \"mlink to parent dir\"\n        mlink $DIR/d31m2 $DIR/d31m/s && error \"mlink parent dir to target\"\n        mlink $DIR/d31m/not-exist $DIR/d31m2/foo && error \"mlink non-existing to new\"\n        mlink $DIR/d31m/not-exist $DIR/d31m2/s && error \"mlink non-existing to exist\"\n\treturn 0\n}\nrun_test 31m \"link to file: the same, non-existing, dir===============\"\n\ntest_31n() {\n\ttouch $DIR/$tfile || error \"cannot create '$DIR/$tfile'\"\n\tnlink=$(stat --format=%h $DIR/$tfile)\n\t[ ${nlink:--1} -eq 1 ] || error \"nlink is $nlink, expected 1\"\n\tlocal fd=$(free_fd)\n\tlocal cmd=\"exec $fd<$DIR/$tfile\"\n\teval $cmd\n\tcmd=\"exec $fd<&-\"\n\ttrap \"eval $cmd\" EXIT\n\tnlink=$(stat --dereference --format=%h /proc/self/fd/$fd)\n\t[ ${nlink:--1} -eq 1 ] || error \"nlink is $nlink, expected 1\"\n\trm $DIR/$tfile || error \"cannot remove '$DIR/$tfile'\"\n\tnlink=$(stat --dereference --format=%h /proc/self/fd/$fd)\n\t[ ${nlink:--1} -eq 0 ] || error \"nlink is $nlink, expected 0\"\n\teval $cmd\n}\nrun_test 31n \"check link count of unlinked file\"\n\nlink_one() {\n\tlocal tempfile=$(mktemp $1_XXXXXX)\n\tmlink $tempfile $1 2> /dev/null &&\n\t\techo \"$BASHPID: link $tempfile to $1 succeeded\"\n\tmunlink $tempfile\n}\n\ntest_31o() { # LU-2901\n\ttest_mkdir $DIR/$tdir\n\tfor LOOP in $(seq 100); do\n\t\trm -f $DIR/$tdir/$tfile*\n\t\tfor THREAD in $(seq 8); do\n\t\t\tlink_one $DIR/$tdir/$tfile.$LOOP &\n\t\tdone\n\t\twait\n\t\tlocal LINKS=$(ls -1 $DIR/$tdir | grep -c $tfile.$LOOP)\n\t\t[[ $LINKS -gt 1 ]] && ls $DIR/$tdir &&\n\t\t\terror \"$LINKS duplicate links to $tfile.$LOOP\" &&\n\t\t\tbreak || true\n\tdone\n}\nrun_test 31o \"duplicate hard links with same filename\"\n\ntest_31p() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -D -c2 -H all_char $DIR/$tdir/striped_dir\n\n\topendirunlink $DIR/$tdir/striped_dir/test1 ||\n\t\terror \"open unlink test1 failed\"\n\topendirunlink $DIR/$tdir/striped_dir/test2 ||\n\t\terror \"open unlink test2 failed\"\n\n\t$CHECKSTAT -a $DIR/$tdir/striped_dir/test1 ||\n\t\terror \"test1 still exists\"\n\t$CHECKSTAT -a $DIR/$tdir/striped_dir/test2 ||\n\t\terror \"test2 still exists\"\n}\nrun_test 31p \"remove of open striped directory\"\n\ncleanup_test32_mount() {\n\tlocal rc=0\n\ttrap 0\n\tlocal loopdev=$(losetup -a | grep $EXT2_DEV | sed -ne 's/:.*$//p')\n\t$UMOUNT $DIR/$tdir/ext2-mountpoint || rc=$?\n\tlosetup -d $loopdev || true\n\trm -rf $DIR/$tdir\n\treturn $rc\n}\n\ntest_32a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\techo \"== more mountpoints and symlinks =================\"\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\t$CHECKSTAT -t dir $DIR/$tdir/ext2-mountpoint/.. ||\n\t\terror \"$DIR/$tdir/ext2-mountpoint/.. not dir type\"\n\tcleanup_test32_mount\n}\nrun_test 32a \"stat d32a/ext2-mountpoint/.. =====================\"\n\ntest_32b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\tls -al $DIR/$tdir/ext2-mountpoint/.. ||\n\t\terror \"Can't list $DIR/$tdir/ext2-mountpoint/..\"\n\tcleanup_test32_mount\n}\nrun_test 32b \"open d32b/ext2-mountpoint/.. =====================\"\n\ntest_32c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttest_mkdir -p $DIR/$tdir/d2/test_dir\n\t$CHECKSTAT -t dir $DIR/$tdir/ext2-mountpoint/../d2/test_dir ||\n\t\terror \"$DIR/$tdir/ext2-mountpoint/../d2/test_dir not dir type\"\n\tcleanup_test32_mount\n}\nrun_test 32c \"stat d32c/ext2-mountpoint/../d2/test_dir =========\"\n\ntest_32d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttest_mkdir -p $DIR/$tdir/d2/test_dir\n\tls -al $DIR/$tdir/ext2-mountpoint/../d2/test_dir ||\n\t\terror \"Can't list $DIR/$tdir/ext2-mountpoint/../d2/test_dir\"\n\tcleanup_test32_mount\n}\nrun_test 32d \"open d32d/ext2-mountpoint/../d2/test_dir\"\n\ntest_32e() {\n\trm -fr $DIR/$tdir\n\ttest_mkdir -p $DIR/$tdir/tmp\n\tlocal tmp_dir=$DIR/$tdir/tmp\n\tln -s $DIR/$tdir $tmp_dir/symlink11\n\tln -s $tmp_dir/symlink11 $tmp_dir/../symlink01\n\t$CHECKSTAT -t link $DIR/$tdir/tmp/symlink11 || error \"symlink11 bad\"\n\t$CHECKSTAT -t link $DIR/$tdir/symlink01 || error \"symlink01 bad\"\n}\nrun_test 32e \"stat d32e/symlink->tmp/symlink->lustre-subdir\"\n\ntest_32f() {\n\trm -fr $DIR/$tdir\n\ttest_mkdir -p $DIR/$tdir/tmp\n\tlocal tmp_dir=$DIR/$tdir/tmp\n\tln -s $DIR/$tdir $tmp_dir/symlink11\n\tln -s $tmp_dir/symlink11 $tmp_dir/../symlink01\n\tls $DIR/$tdir/tmp/symlink11  || error \"symlink11 bad\"\n\tls $DIR/$tdir/symlink01 || error \"symlink01 bad\"\n}\nrun_test 32f \"open d32f/symlink->tmp/symlink->lustre-subdir\"\n\ntest_32g() {\n\tlocal tmp_dir=$DIR/$tdir/tmp\n\ttest_mkdir -p $tmp_dir\n\ttest_mkdir $DIR/${tdir}2\n\tln -s $DIR/${tdir}2 $tmp_dir/symlink12\n\tln -s $tmp_dir/symlink12 $tmp_dir/../symlink02\n\t$CHECKSTAT -t link $tmp_dir/symlink12 || error \"symlink12 not a link\"\n\t$CHECKSTAT -t link $DIR/$tdir/symlink02 || error \"symlink02 not a link\"\n\t$CHECKSTAT -t dir -f $tmp_dir/symlink12 || error \"symlink12 not a dir\"\n\t$CHECKSTAT -t dir -f $DIR/$tdir/symlink02 || error \"symlink12 not a dir\"\n}\nrun_test 32g \"stat d32g/symlink->tmp/symlink->lustre-subdir/${tdir}2\"\n\ntest_32h() {\n\trm -fr $DIR/$tdir $DIR/${tdir}2\n\ttmp_dir=$DIR/$tdir/tmp\n\ttest_mkdir -p $tmp_dir\n\ttest_mkdir $DIR/${tdir}2\n\tln -s $DIR/${tdir}2 $tmp_dir/symlink12\n\tln -s $tmp_dir/symlink12 $tmp_dir/../symlink02\n\tls $tmp_dir/symlink12 || error \"listing symlink12\"\n\tls $DIR/$tdir/symlink02  || error \"listing symlink02\"\n}\nrun_test 32h \"open d32h/symlink->tmp/symlink->lustre-subdir/${tdir}2\"\n\ntest_32i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttouch $DIR/$tdir/test_file\n\t$CHECKSTAT -t file $DIR/$tdir/ext2-mountpoint/../test_file ||\n\t\terror \"$DIR/$tdir/ext2-mountpoint/../test_file not file type\"\n\tcleanup_test32_mount\n}\nrun_test 32i \"stat d32i/ext2-mountpoint/../test_file ===========\"\n\ntest_32j() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttouch $DIR/$tdir/test_file\n\tcat $DIR/$tdir/ext2-mountpoint/../test_file ||\n\t\terror \"Can't open $DIR/$tdir/ext2-mountpoint/../test_file\"\n\tcleanup_test32_mount\n}\nrun_test 32j \"open d32j/ext2-mountpoint/../test_file ===========\"\n\ntest_32k() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttest_mkdir -p $DIR/$tdir/d2\n\ttouch $DIR/$tdir/d2/test_file || error \"touch failed\"\n\t$CHECKSTAT -t file $DIR/$tdir/ext2-mountpoint/../d2/test_file ||\n\t\terror \"$DIR/$tdir/ext2-mountpoint/../d2/test_file not file type\"\n\tcleanup_test32_mount\n}\nrun_test 32k \"stat d32k/ext2-mountpoint/../d2/test_file ========\"\n\ntest_32l() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\ttest_mkdir -p $DIR/$tdir/d2\n\ttouch $DIR/$tdir/d2/test_file || error \"touch failed\"\n\tcat  $DIR/$tdir/ext2-mountpoint/../d2/test_file ||\n\t\terror \"Can't open $DIR/$tdir/ext2-mountpoint/../d2/test_file\"\n\tcleanup_test32_mount\n}\nrun_test 32l \"open d32l/ext2-mountpoint/../d2/test_file ========\"\n\ntest_32m() {\n\trm -fr $DIR/d32m\n\ttest_mkdir -p $DIR/d32m/tmp\n\tTMP_DIR=$DIR/d32m/tmp\n\tln -s $DIR $TMP_DIR/symlink11\n\tln -s $TMP_DIR/symlink11 $TMP_DIR/../symlink01\n\t$CHECKSTAT -t link $DIR/d32m/tmp/symlink11 ||\n\t\terror \"symlink11 not a link\"\n\t$CHECKSTAT -t link $DIR/d32m/symlink01 ||\n\t\terror \"symlink01 not a link\"\n}\nrun_test 32m \"stat d32m/symlink->tmp/symlink->lustre-root ======\"\n\ntest_32n() {\n\trm -fr $DIR/d32n\n\ttest_mkdir -p $DIR/d32n/tmp\n\tTMP_DIR=$DIR/d32n/tmp\n\tln -s $DIR $TMP_DIR/symlink11\n\tln -s $TMP_DIR/symlink11 $TMP_DIR/../symlink01\n\tls -l $DIR/d32n/tmp/symlink11  || error \"listing symlink11\"\n\tls -l $DIR/d32n/symlink01 || error \"listing symlink01\"\n}\nrun_test 32n \"open d32n/symlink->tmp/symlink->lustre-root ======\"\n\ntest_32o() {\n\ttouch $DIR/$tfile\n\ttest_mkdir -p $DIR/d32o/tmp\n\tTMP_DIR=$DIR/d32o/tmp\n\tln -s $DIR/$tfile $TMP_DIR/symlink12\n\tln -s $TMP_DIR/symlink12 $TMP_DIR/../symlink02\n\t$CHECKSTAT -t link $DIR/d32o/tmp/symlink12 ||\n\t\terror \"symlink12 not a link\"\n\t$CHECKSTAT -t link $DIR/d32o/symlink02 || error \"symlink02 not a link\"\n\t$CHECKSTAT -t file -f $DIR/d32o/tmp/symlink12 ||\n\t\terror \"$DIR/d32o/tmp/symlink12 not file type\"\n\t$CHECKSTAT -t file -f $DIR/d32o/symlink02 ||\n\t\terror \"$DIR/d32o/symlink02 not file type\"\n}\nrun_test 32o \"stat d32o/symlink->tmp/symlink->lustre-root/$tfile\"\n\ntest_32p() {\n\tlog 32p_1\n\trm -fr $DIR/d32p\n\tlog 32p_2\n\trm -f $DIR/$tfile\n\tlog 32p_3\n\ttouch $DIR/$tfile\n\tlog 32p_4\n\ttest_mkdir -p $DIR/d32p/tmp\n\tlog 32p_5\n\tTMP_DIR=$DIR/d32p/tmp\n\tlog 32p_6\n\tln -s $DIR/$tfile $TMP_DIR/symlink12\n\tlog 32p_7\n\tln -s $TMP_DIR/symlink12 $TMP_DIR/../symlink02\n\tlog 32p_8\n\tcat $DIR/d32p/tmp/symlink12 ||\n\t\terror \"Can't open $DIR/d32p/tmp/symlink12\"\n\tlog 32p_9\n\tcat $DIR/d32p/symlink02 || error \"Can't open $DIR/d32p/symlink02\"\n\tlog 32p_10\n}\nrun_test 32p \"open d32p/symlink->tmp/symlink->lustre-root/$tfile\"\n\ntest_32q() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\ttouch $DIR/$tdir/ext2-mountpoint/under_the_mount || error \"touch failed\"\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\tls $DIR/$tdir/ext2-mountpoint | grep \"\\<under_the_mount\\>\" && error\n\tcleanup_test32_mount\n}\nrun_test 32q \"stat follows mountpoints in Lustre (should return error)\"\n\ntest_32r() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t[ -e $DIR/$tdir ] && rm -fr $DIR/$tdir\n\ttrap cleanup_test32_mount EXIT\n\ttest_mkdir -p $DIR/$tdir/ext2-mountpoint\n\ttouch $DIR/$tdir/ext2-mountpoint/under_the_mount || error \"touch failed\"\n\tmount -t ext2 -o loop $EXT2_DEV $DIR/$tdir/ext2-mountpoint ||\n\t\terror \"mount failed for $EXT2_DEV $DIR/$tdir/ext2-mountpoint\"\n\tls $DIR/$tdir/ext2-mountpoint | grep -q under_the_mount && error || true\n\tcleanup_test32_mount\n}\nrun_test 32r \"opendir follows mountpoints in Lustre (should return error)\"\n\ntest_33aa() {\n\trm -f $DIR/$tfile\n\ttouch $DIR/$tfile\n\tchmod 444 $DIR/$tfile\n\tchown $RUNAS_ID $DIR/$tfile\n\tlog 33_1\n\t$RUNAS $OPENFILE -f O_RDWR $DIR/$tfile && error || true\n\tlog 33_2\n}\nrun_test 33aa \"write file with mode 444 (should return error)\"\n\ntest_33a() {\n\trm -fr $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\tchown $RUNAS_ID $DIR/$tdir\n\t$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $DIR/$tdir/$tfile ||\n\t\terror \"$RUNAS create $tdir/$tfile failed\"\n\t$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $DIR/$tdir/$tfile &&\n\t\terror \"open RDWR\" || true\n}\nrun_test 33a \"test open file(mode=0444) with O_RDWR (should return error)\"\n\ntest_33b() {\n\trm -fr $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\tchown $RUNAS_ID $DIR/$tdir\n\t$RUNAS $OPENFILE -f 1286739555 $DIR/$tdir/$tfile || true\n}\nrun_test 33b \"test open file with malformed flags (No panic)\"\n\ntest_33c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal ostnum\n\tlocal ostname\n\tlocal write_bytes\n\tlocal all_zeros\n\n\tall_zeros=:\n\trm -fr $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\t# Read: 0, Write: 4, create/destroy: 2/0, stat: 1, punch: 0\n\n        sync\n        for ostnum in $(seq $OSTCOUNT); do\n                # test-framework's OST numbering is one-based, while Lustre's\n                # is zero-based\n                ostname=$(printf \"$FSNAME-OST%.4x\" $((ostnum - 1)))\n                # Parsing llobdstat's output sucks; we could grep the /proc\n                # path, but that's likely to not be as portable as using the\n                # llobdstat utility.  So we parse lctl output instead.\n                write_bytes=$(do_facet ost$ostnum lctl get_param -n \\\n                        obdfilter/$ostname/stats |\n                        awk '/^write_bytes/ {print $7}' )\n                echo \"baseline_write_bytes@$OSTnum/$ostname=$write_bytes\"\n                if (( ${write_bytes:-0} > 0 ))\n                then\n                        all_zeros=false\n                        break;\n                fi\n        done\n\n        $all_zeros || return 0\n\n\t# Write four bytes\n\techo foo > $DIR/$tdir/bar\n\t# Really write them\n\tsync\n\n        # Total up write_bytes after writing.  We'd better find non-zeros.\n        for ostnum in $(seq $OSTCOUNT); do\n                ostname=$(printf \"$FSNAME-OST%.4x\" $((ostnum - 1)))\n                write_bytes=$(do_facet ost$ostnum lctl get_param -n \\\n                        obdfilter/$ostname/stats |\n                        awk '/^write_bytes/ {print $7}' )\n                echo \"write_bytes@$OSTnum/$ostname=$write_bytes\"\n                if (( ${write_bytes:-0} > 0 ))\n                then\n                        all_zeros=false\n                        break;\n                fi\n        done\n\n        if $all_zeros\n        then\n                for ostnum in $(seq $OSTCOUNT); do\n                        ostname=$(printf \"$FSNAME-OST%.4x\" $((ostnum - 1)))\n                        echo \"Check that write_bytes is present in obdfilter/*/stats:\"\n                        do_facet ost$ostnum lctl get_param -n \\\n                                obdfilter/$ostname/stats\n                done\n                error \"OST not keeping write_bytes stats (b22312)\"\n        fi\n}\nrun_test 33c \"test llobdstat and write_bytes\"\n\ntest_33d() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX $remote_dir ||\n\t\terror \"create remote directory failed\"\n\n\ttouch $remote_dir/$tfile\n\tchmod 444 $remote_dir/$tfile\n\tchown $RUNAS_ID $remote_dir/$tfile\n\n\t$RUNAS $OPENFILE -f O_RDWR $DIR/$tfile && error || true\n\n\tchown $RUNAS_ID $remote_dir\n\t$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $remote_dir/f33 ||\n\t\t\t\t\terror \"create\" || true\n\t$RUNAS $OPENFILE -f O_RDWR:O_CREAT -m 0444 $remote_dir/f33 &&\n\t\t\t\t    error \"open RDWR\" || true\n\t$RUNAS $OPENFILE -f 1286739555 $remote_dir/f33 || true\n}\nrun_test 33d \"openfile with 444 modes and malformed flags under remote dir\"\n\ntest_33e() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tmkdir $DIR/$tdir\n\n\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1\n\tmkdir $DIR/$tdir/local_dir\n\n\tlocal s0_mode=$(stat -c%f $DIR/$tdir/striped_dir)\n\tlocal s1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)\n\tlocal l_mode=$(stat -c%f $DIR/$tdir/local_dir)\n\n\t[ \"$l_mode\" = \"$s0_mode\" -a \"$l_mode\" = \"$s1_mode\" ] ||\n\t\terror \"mkdir $l_mode striped0 $s0_mode striped1 $s1_mode\"\n\n\trmdir $DIR/$tdir/* || error \"rmdir failed\"\n\n\tumask 777\n\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1\n\tmkdir $DIR/$tdir/local_dir\n\n\ts0_mode=$(stat -c%f $DIR/$tdir/striped_dir)\n\ts1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)\n\tl_mode=$(stat -c%f $DIR/$tdir/local_dir)\n\n\t[ \"$l_mode\" = \"$s0_mode\" -a \"$l_mode\" = \"$s1_mode\" ] ||\n\t\terror \"mkdir $l_mode striped0 $s0_mode striped1 $s1_mode 777\"\n\n\trmdir $DIR/$tdir/* || error \"rmdir(umask 777) failed\"\n\n\tumask 000\n\t$LFS setdirstripe -i0 -c2 $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -i1 -c2 $DIR/$tdir/striped_dir1\n\tmkdir $DIR/$tdir/local_dir\n\n\ts0_mode=$(stat -c%f $DIR/$tdir/striped_dir)\n\ts1_mode=$(stat -c%f $DIR/$tdir/striped_dir1)\n\tl_mode=$(stat -c%f $DIR/$tdir/local_dir)\n\n\t[ \"$l_mode\" = \"$s0_mode\" -a \"$l_mode\" = \"$s1_mode\" ] ||\n\t\terror \"mkdir $l_mode striped0 $s0_mode striped1 $s1_mode 0\"\n}\nrun_test 33e \"mkdir and striped directory should have same mode\"\n\ncleanup_33f() {\n\ttrap 0\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.enable_remote_dir_gid=0\n}\n\ntest_33f() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tmkdir $DIR/$tdir\n\tchmod go+rwx $DIR/$tdir\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.enable_remote_dir_gid=-1\n\ttrap cleanup_33f EXIT\n\n\t$RUNAS lfs mkdir -i 0 -c$MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"cannot create striped directory\"\n\n\t$RUNAS touch $DIR/$tdir/striped_dir/{0..16} ||\n\t\terror \"cannot create files in striped directory\"\n\n\t$RUNAS rm $DIR/$tdir/striped_dir/{0..16} ||\n\t\terror \"cannot remove files in striped directory\"\n\n\t$RUNAS rmdir $DIR/$tdir/striped_dir ||\n\t\terror \"cannot remove striped directory\"\n\n\tcleanup_33f\n}\nrun_test 33f \"nonroot user can create, access, and remove a striped directory\"\n\ntest_33g() {\n\tmkdir -p $DIR/$tdir/dir2\n\n\tlocal err=$($RUNAS mkdir $DIR/$tdir/dir2 2>&1)\n\techo $err\n\t[[ $err =~ \"exists\" ]] || error \"Not exists error\"\n}\nrun_test 33g \"nonroot user create already existing root created file\"\n\ntest_33h() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.13.50) ] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\n\ttest_mkdir -c $MDSCOUNT -H crush $DIR/$tdir ||\n\t\terror \"mkdir $tdir failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch $tfile failed\"\n\n\tlocal index=$($LFS getstripe -m $DIR/$tdir/$tfile)\n\tlocal index2\n\n\tfor fname in $DIR/$tdir/$tfile.bak \\\n\t\t     $DIR/$tdir/$tfile.SAV \\\n\t\t     $DIR/$tdir/$tfile.orig \\\n\t\t     $DIR/$tdir/$tfile~; do\n\t\ttouch $fname  || error \"touch $fname failed\"\n\t\tindex2=$($LFS getstripe -m $fname)\n\t\t[ $index -eq $index2 ] ||\n\t\t\terror \"$fname MDT index mismatch $index != $index2\"\n\tdone\n\n\tlocal failed=0\n\tfor i in {1..250}; do\n\t\tfor fname in $(mktemp -u $DIR/$tdir/.$tfile.XXXXXX) \\\n\t\t\t     $(mktemp $DIR/$tdir/$tfile.XXXXXXXX); do\n\t\t\ttouch $fname  || error \"touch $fname failed\"\n\t\t\tindex2=$($LFS getstripe -m $fname)\n\t\t\tif [[ $index != $index2 ]]; then\n\t\t\t\tfailed=$((failed + 1))\n\t\t\t\techo \"$fname MDT index mismatch $index != $index2\"\n\t\t\tfi\n\t\tdone\n\tdone\n\techo \"$failed MDT index mismatches\"\n\t(( failed < 20 )) || error \"MDT index mismatch $failed times\"\n\n}\nrun_test 33h \"temp file is located on the same MDT as target\"\n\nTEST_34_SIZE=${TEST_34_SIZE:-2000000000000}\ntest_34a() {\n\trm -f $DIR/f34\n\t$MCREATE $DIR/f34 || error \"mcreate failed\"\n\t$LFS getstripe $DIR/f34 2>&1 | grep -q \"no stripe info\" ||\n\t\terror \"getstripe failed\"\n\t$TRUNCATE $DIR/f34 $TEST_34_SIZE || error \"truncate failed\"\n\t$LFS getstripe $DIR/f34 2>&1 | grep -q \"no stripe info\" ||\n\t\terror \"getstripe failed\"\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n}\nrun_test 34a \"truncate file that has not been opened ===========\"\n\ntest_34b() {\n\t[ ! -f $DIR/f34 ] && test_34a\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n\t$OPENFILE -f O_RDONLY $DIR/f34\n\t$LFS getstripe $DIR/f34 2>&1 | grep -q \"no stripe info\" ||\n\t\terror \"getstripe failed\"\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n}\nrun_test 34b \"O_RDONLY opening file doesn't create objects =====\"\n\ntest_34c() {\n\t[ ! -f $DIR/f34 ] && test_34a\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n\t$OPENFILE -f O_RDWR $DIR/f34\n\t$LFS getstripe $DIR/f34 2>&1 | grep -q \"no stripe info\" &&\n\t\terror \"$LFS getstripe failed\"\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n}\nrun_test 34c \"O_RDWR opening file-with-size works ==============\"\n\ntest_34d() {\n\t[ ! -f $DIR/f34 ] && test_34a\n\tdd if=/dev/zero of=$DIR/f34 conv=notrunc bs=4k count=1 ||\n\t\terror \"dd failed\"\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/f34 ||\n\t\terror \"Size of $DIR/f34 not equal to $TEST_34_SIZE bytes\"\n\trm $DIR/f34\n}\nrun_test 34d \"write to sparse file =============================\"\n\ntest_34e() {\n\trm -f $DIR/f34e\n\t$MCREATE $DIR/f34e || error \"mcreate failed\"\n\t$TRUNCATE $DIR/f34e 1000 || error \"truncate failed\"\n\t$CHECKSTAT -s 1000 $DIR/f34e ||\n\t\terror \"Size of $DIR/f34e not equal to 1000 bytes\"\n\t$OPENFILE -f O_RDWR $DIR/f34e\n\t$CHECKSTAT -s 1000 $DIR/f34e ||\n\t\terror \"Size of $DIR/f34e not equal to 1000 bytes\"\n}\nrun_test 34e \"create objects, some with size and some without ==\"\n\ntest_34f() { # bug 6242, 6243\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tSIZE34F=48000\n\trm -f $DIR/f34f\n\t$MCREATE $DIR/f34f || error \"mcreate failed\"\n\t$TRUNCATE $DIR/f34f $SIZE34F || error \"truncating $DIR/f3f to $SIZE34F\"\n\tdd if=$DIR/f34f of=$TMP/f34f\n\t$CHECKSTAT -s $SIZE34F $TMP/f34f || error \"$TMP/f34f not $SIZE34F bytes\"\n\tdd if=/dev/zero of=$TMP/f34fzero bs=$SIZE34F count=1\n\tcmp $DIR/f34f $TMP/f34fzero || error \"$DIR/f34f not all zero\"\n\tcmp $TMP/f34f $TMP/f34fzero || error \"$TMP/f34f not all zero\"\n\trm $TMP/f34f $TMP/f34fzero $DIR/f34f\n}\nrun_test 34f \"read from a file with no objects until EOF =======\"\n\ntest_34g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1 count=100 seek=$TEST_34_SIZE ||\n\t\terror \"dd failed\"\n\t$TRUNCATE $DIR/$tfile $((TEST_34_SIZE / 2))|| error \"truncate failed\"\n\t$CHECKSTAT -s $((TEST_34_SIZE / 2)) $DIR/$tfile ||\n\t\terror \"Size of $DIR/$tfile not equal to $((TEST_34_SIZE / 2))\"\n\tcancel_lru_locks osc\n\t$CHECKSTAT -s $((TEST_34_SIZE / 2)) $DIR/$tfile ||\n\t\terror \"wrong size after lock cancel\"\n\n\t$TRUNCATE $DIR/$tfile $TEST_34_SIZE || error \"truncate failed\"\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/$tfile ||\n\t\terror \"expanding truncate failed\"\n\tcancel_lru_locks osc\n\t$CHECKSTAT -s $TEST_34_SIZE $DIR/$tfile ||\n\t\terror \"wrong expanded size after lock cancel\"\n}\nrun_test 34g \"truncate long file ===============================\"\n\ntest_34h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal gid=10\n\tlocal sz=1000\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=10 || error \"dd failed\"\n\tsync # Flush the cache so that multiop below does not block on cache\n\t     # flush when getting the group lock\n\t$MULTIOP $DIR/$tfile OG${gid}T${sz}g${gid}c &\n\tMULTIPID=$!\n\n\t# Since just timed wait is not good enough, let's do a sync write\n\t# that way we are sure enough time for a roundtrip + processing\n\t# passed + 2 seconds of extra margin.\n\tdd if=/dev/zero of=$DIR/${tfile}-1 bs=$PAGE_SIZE oflag=direct count=1\n\trm $DIR/${tfile}-1\n\tsleep 2\n\n\tif [[ `ps h -o comm -p $MULTIPID` == \"multiop\" ]]; then\n\t\terror \"Multiop blocked on ftruncate, pid=$MULTIPID\"\n\t\tkill -9 $MULTIPID\n\tfi\n\twait $MULTIPID\n\tlocal nsz=`stat -c %s $DIR/$tfile`\n\t[[ $nsz == $sz ]] || error \"New size wrong $nsz != $sz\"\n}\nrun_test 34h \"ftruncate file under grouplock should not block\"\n\ntest_35a() {\n\tcp /bin/sh $DIR/f35a\n\tchmod 444 $DIR/f35a\n\tchown $RUNAS_ID $DIR/f35a\n\t$RUNAS $DIR/f35a && error || true\n\trm $DIR/f35a\n}\nrun_test 35a \"exec file with mode 444 (should return and not leak)\"\n\ntest_36a() {\n\trm -f $DIR/f36\n\tutime $DIR/f36 || error \"utime failed for MDS\"\n}\nrun_test 36a \"MDS utime check (mknod, utime)\"\n\ntest_36b() {\n\techo \"\" > $DIR/f36\n\tutime $DIR/f36 || error \"utime failed for OST\"\n}\nrun_test 36b \"OST utime check (open, utime)\"\n\ntest_36c() {\n\trm -f $DIR/d36/f36\n\ttest_mkdir $DIR/d36\n\tchown $RUNAS_ID $DIR/d36\n\t$RUNAS utime $DIR/d36/f36 || error \"utime failed for MDS as non-root\"\n}\nrun_test 36c \"non-root MDS utime check (mknod, utime)\"\n\ntest_36d() {\n\t[ ! -d $DIR/d36 ] && test_36c\n\techo \"\" > $DIR/d36/f36\n\t$RUNAS utime $DIR/d36/f36 || error \"utime failed for OST as non-root\"\n}\nrun_test 36d \"non-root OST utime check (open, utime)\"\n\ntest_36e() {\n\t[ $RUNAS_ID -eq $UID ] && skip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\t$RUNAS utime $DIR/$tdir/$tfile &&\n\t\terror \"utime worked, expected failure\" || true\n}\nrun_test 36e \"utime on non-owned file (should return error)\"\n\nsubr_36fh() {\n\tlocal fl=\"$1\"\n\tlocal LANG_SAVE=$LANG\n\tlocal LC_LANG_SAVE=$LC_LANG\n\texport LANG=C LC_LANG=C # for date language\n\n\tDATESTR=\"Dec 20  2000\"\n\ttest_mkdir $DIR/$tdir\n\tlctl set_param fail_loc=$fl\n\tdate; date +%s\n\tcp /etc/hosts $DIR/$tdir/$tfile\n\tsync & # write RPC generated with \"current\" inode timestamp, but delayed\n\tsleep 1\n\ttouch --date=\"$DATESTR\" $DIR/$tdir/$tfile # setattr timestamp in past\n\tLS_BEFORE=\"`ls -l $DIR/$tdir/$tfile`\" # old timestamp from client cache\n\tcancel_lru_locks $OSC\n\tLS_AFTER=\"`ls -l $DIR/$tdir/$tfile`\"  # timestamp from OST object\n\tdate; date +%s\n\t[ \"$LS_BEFORE\" != \"$LS_AFTER\" ] && \\\n\t\techo \"BEFORE: $LS_BEFORE\" && \\\n\t\techo \"AFTER : $LS_AFTER\" && \\\n\t\techo \"WANT  : $DATESTR\" && \\\n\t\terror \"$DIR/$tdir/$tfile timestamps changed\" || true\n\n\texport LANG=$LANG_SAVE LC_LANG=$LC_LANG_SAVE\n}\n\ntest_36f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_OST_BRW_PAUSE_BULK 0x214\n\tsubr_36fh \"0x80000214\"\n}\nrun_test 36f \"utime on file racing with OST BRW write ==========\"\n\ntest_36g() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDS1_VERSION -lt $(version_code 2.12.51) ] &&\n\t\tskip \"Need MDS version at least 2.12.51\"\n\n\tlocal fmd_max_age\n\tlocal fmd\n\tlocal facet=\"ost1\"\n\tlocal tgt=\"obdfilter\"\n\n\t[[ $OSC == \"mdc\" ]] && tgt=\"mdt\" && facet=\"mds1\"\n\n\ttest_mkdir $DIR/$tdir\n\tfmd_max_age=$(do_facet $facet \\\n\t\t\"lctl get_param -n $tgt.*.tgt_fmd_seconds 2> /dev/null | \\\n\t\thead -n 1\")\n\n\techo \"FMD max age: ${fmd_max_age}s\"\n\ttouch $DIR/$tdir/$tfile\n\tfmd=$(do_facet $facet \"lctl get_param -n $tgt.*.exports.*.fmd_count\" |\n\t\tgawk '{cnt=cnt+$1}  END{print cnt}')\n\techo \"FMD before: $fmd\"\n\t[[ $fmd == 0 ]] &&\n\t\terror \"FMD wasn't create by touch\"\n\tsleep $((fmd_max_age + 12))\n\tfmd=$(do_facet $facet \"lctl get_param -n $tgt.*.exports.*.fmd_count\" |\n\t\tgawk '{cnt=cnt+$1}  END{print cnt}')\n\techo \"FMD after: $fmd\"\n\t[[ $fmd == 0 ]] ||\n\t\terror \"FMD wasn't expired by ping\"\n}\nrun_test 36g \"FMD cache expiry =====================\"\n\ntest_36h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_OST_BRW_PAUSE_BULK2 0x227\n\tsubr_36fh \"0x80000227\"\n}\nrun_test 36h \"utime on file racing with OST BRW write ==========\"\n\ntest_36i() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir\n\n\tlocal mtime=$(stat -c%Y $DIR/$tdir/striped_dir)\n\tlocal new_mtime=$((mtime + 200))\n\n\t#change Modify time of striped dir\n\ttouch -m -d @$new_mtime\t$DIR/$tdir/striped_dir ||\n\t\t\terror \"change mtime failed\"\n\n\tlocal got=$(stat -c%Y $DIR/$tdir/striped_dir)\n\n\t[ \"$new_mtime\" = \"$got\" ] || error \"expect $new_mtime got $got\"\n}\nrun_test 36i \"change mtime on striped directory\"\n\n# test_37 - duplicate with tests 32q 32r\n\ntest_38() {\n\tlocal file=$DIR/$tfile\n\ttouch $file\n\topenfile -f O_DIRECTORY $file\n\tlocal RC=$?\n\tlocal ENOTDIR=20\n\t[ $RC -eq 0 ] && error \"opened file $file with O_DIRECTORY\" || true\n\t[ $RC -eq $ENOTDIR ] || error \"error $RC should be ENOTDIR ($ENOTDIR)\"\n}\nrun_test 38 \"open a regular file with O_DIRECTORY should return -ENOTDIR ===\"\n\ntest_39a() { # was test_39\n\ttouch $DIR/$tfile\n\ttouch $DIR/${tfile}2\n#\tls -l  $DIR/$tfile $DIR/${tfile}2\n#\tls -lu  $DIR/$tfile $DIR/${tfile}2\n#\tls -lc  $DIR/$tfile $DIR/${tfile}2\n\tsleep 2\n\t$OPENFILE -f O_CREAT:O_TRUNC:O_WRONLY $DIR/${tfile}2\n\tif [ ! $DIR/${tfile}2 -nt $DIR/$tfile ]; then\n\t\techo \"mtime\"\n\t\tls -l --full-time $DIR/$tfile $DIR/${tfile}2\n\t\techo \"atime\"\n\t\tls -lu --full-time $DIR/$tfile $DIR/${tfile}2\n\t\techo \"ctime\"\n\t\tls -lc --full-time $DIR/$tfile $DIR/${tfile}2\n\t\terror \"O_TRUNC didn't change timestamps\"\n\tfi\n}\nrun_test 39a \"mtime changed on create\"\n\ntest_39b() {\n\ttest_mkdir -c1 $DIR/$tdir\n\tcp -p /etc/passwd $DIR/$tdir/fopen\n\tcp -p /etc/passwd $DIR/$tdir/flink\n\tcp -p /etc/passwd $DIR/$tdir/funlink\n\tcp -p /etc/passwd $DIR/$tdir/frename\n\tln $DIR/$tdir/funlink $DIR/$tdir/funlink2\n\n\tsleep 1\n\techo \"aaaaaa\" >> $DIR/$tdir/fopen\n\techo \"aaaaaa\" >> $DIR/$tdir/flink\n\techo \"aaaaaa\" >> $DIR/$tdir/funlink\n\techo \"aaaaaa\" >> $DIR/$tdir/frename\n\n\tlocal open_new=`stat -c %Y $DIR/$tdir/fopen`\n\tlocal link_new=`stat -c %Y $DIR/$tdir/flink`\n\tlocal unlink_new=`stat -c %Y $DIR/$tdir/funlink`\n\tlocal rename_new=`stat -c %Y $DIR/$tdir/frename`\n\n\tcat $DIR/$tdir/fopen > /dev/null\n\tln $DIR/$tdir/flink $DIR/$tdir/flink2\n\trm -f $DIR/$tdir/funlink2\n\tmv -f $DIR/$tdir/frename $DIR/$tdir/frename2\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal open_new2=`stat -c %Y $DIR/$tdir/fopen`\n\t\tlocal link_new2=`stat -c %Y $DIR/$tdir/flink`\n\t\tlocal unlink_new2=`stat -c %Y $DIR/$tdir/funlink`\n\t\tlocal rename_new2=`stat -c %Y $DIR/$tdir/frename2`\n\n\t\t[ $open_new2 -eq $open_new ] || error \"open file reverses mtime\"\n\t\t[ $link_new2 -eq $link_new ] || error \"link file reverses mtime\"\n\t\t[ $unlink_new2 -eq $unlink_new ] || error \"unlink file reverses mtime\"\n\t\t[ $rename_new2 -eq $rename_new ] || error \"rename file reverses mtime\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39b \"mtime change on open, link, unlink, rename  ======\"\n\n# this should be set to past\nTEST_39_MTIME=`date -d \"1 year ago\" +%s`\n\n# bug 11063\ntest_39c() {\n\ttouch $DIR1/$tfile\n\tsleep 2\n\tlocal mtime0=`stat -c %Y $DIR1/$tfile`\n\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\t[ \"$mtime1\" = $TEST_39_MTIME ] || \\\n\t\terror \"mtime is not set to past: $mtime1, should be $TEST_39_MTIME\"\n\n\tlocal d1=`date +%s`\n\techo hello >> $DIR1/$tfile\n\tlocal d2=`date +%s`\n\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\t[ \"$mtime2\" -ge \"$d1\" ] && [ \"$mtime2\" -le \"$d2\" ] || \\\n\t\terror \"mtime is not updated on write: $d1 <= $mtime2 <= $d2\"\n\n\tmv $DIR1/$tfile $DIR1/$tfile-1\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime3=`stat -c %Y $DIR1/$tfile-1`\n\t\t[ \"$mtime2\" = \"$mtime3\" ] || \\\n\t\t\terror \"mtime ($mtime2) changed (to $mtime3) on rename\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39c \"mtime change on rename ===========================\"\n\n# bug 21114\ntest_39d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime=`stat -c %Y $DIR1/$tfile`\n\t\t[ $mtime = $TEST_39_MTIME ] || \\\n\t\t\terror \"mtime($mtime) is not set to $TEST_39_MTIME\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39d \"create, utime, stat ==============================\"\n\n# bug 21114\ntest_39e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\t\t[ $mtime2 = $TEST_39_MTIME ] || \\\n\t\t\terror \"mtime($mtime2) is not set to $TEST_39_MTIME\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39e \"create, stat, utime, stat ========================\"\n\n# bug 21114\ntest_39f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tmtime1=`stat -c %Y $DIR1/$tfile`\n\n\tsleep 2\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\t\t[ $mtime2 = $TEST_39_MTIME ] || \\\n\t\t\terror \"mtime($mtime2) is not set to $TEST_39_MTIME\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39f \"create, stat, sleep, utime, stat =================\"\n\n# bug 11063\ntest_39g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\techo hello >> $DIR1/$tfile\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\tsleep 2\n\tchmod o+r $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\t\t[ \"$mtime1\" = \"$mtime2\" ] || \\\n\t\t\terror \"lost mtime: $mtime2, should be $mtime1\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39g \"write, chmod, stat ===============================\"\n\n# bug 11063\ntest_39h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tsleep 1\n\n\tlocal d1=`date`\n\techo hello >> $DIR1/$tfile\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\tlocal d2=`date`\n\tif [ \"$d1\" != \"$d2\" ]; then\n\t\techo \"write and touch not within one second\"\n\telse\n\t\tfor (( i=0; i < 2; i++ )) ; do\n\t\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\t\t\t[ \"$mtime2\" = $TEST_39_MTIME ] || \\\n\t\t\t\terror \"lost mtime: $mtime2, should be $TEST_39_MTIME\"\n\n\t\t\tcancel_lru_locks $OSC\n\t\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\t\tdone\n\tfi\n}\nrun_test 39h \"write, utime within one second, stat =============\"\n\ntest_39i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tsleep 1\n\n\techo hello >> $DIR1/$tfile\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\tmv $DIR1/$tfile $DIR1/$tfile-1\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile-1`\n\n\t\t[ \"$mtime1\" = \"$mtime2\" ] || \\\n\t\t\terror \"lost mtime: $mtime2, should be $mtime1\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39i \"write, rename, stat ==============================\"\n\ntest_39j() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tstart_full_debug_logging\n\ttouch $DIR1/$tfile\n\tsleep 1\n\n\t#define OBD_FAIL_OSC_DELAY_SETTIME\t 0x412\n\tlctl set_param fail_loc=0x80000412\n\tmultiop_bg_pause $DIR1/$tfile oO_RDWR:w2097152_c ||\n\t\terror \"multiop failed\"\n\tlocal multipid=$!\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\tmv $DIR1/$tfile $DIR1/$tfile-1\n\n\tkill -USR1 $multipid\n\twait $multipid || error \"multiop close failed\"\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile-1`\n\t\t[ \"$mtime1\" = \"$mtime2\" ] ||\n\t\t\terror \"mtime is lost on close: $mtime2, \" \\\n\t\t\t      \"should be $mtime1\"\n\n\t\tcancel_lru_locks\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n\tlctl set_param fail_loc=0\n\tstop_full_debug_logging\n}\nrun_test 39j \"write, rename, close, stat =======================\"\n\ntest_39k() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tsleep 1\n\n\tmultiop_bg_pause $DIR1/$tfile oO_RDWR:w2097152_c || error \"multiop failed\"\n\tlocal multipid=$!\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tkill -USR1 $multipid\n\twait $multipid || error \"multiop close failed\"\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime2=`stat -c %Y $DIR1/$tfile`\n\n\t\t[ \"$mtime2\" = $TEST_39_MTIME ] || \\\n\t\t\terror \"mtime is lost on close: $mtime2, should be $TEST_39_MTIME\"\n\n\t\tcancel_lru_locks\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39k \"write, utime, close, stat ========================\"\n\n# this should be set to future\nTEST_39_ATIME=`date -d \"1 year\" +%s`\n\ntest_39l() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal atime_diff=$(do_facet $SINGLEMDS \\\n\t\t\t\tlctl get_param -n mdd.*MDT0000*.atime_diff)\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\t# test setting directory atime to future\n\ttouch -a -d @$TEST_39_ATIME $DIR/$tdir\n\tlocal atime=$(stat -c %X $DIR/$tdir)\n\t[ \"$atime\" = $TEST_39_ATIME ] ||\n\t\terror \"atime is not set to future: $atime, $TEST_39_ATIME\"\n\n\t# test setting directory atime from future to now\n\tlocal now=$(date +%s)\n\ttouch -a -d @$now $DIR/$tdir\n\n\tatime=$(stat -c %X $DIR/$tdir)\n\t[ \"$atime\" -eq \"$now\"  ] ||\n\t\terror \"atime is not updated from future: $atime, $now\"\n\n\tdo_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=2\n\tsleep 3\n\n\t# test setting directory atime when now > dir atime + atime_diff\n\tlocal d1=$(date +%s)\n\tls $DIR/$tdir\n\tlocal d2=$(date +%s)\n\tcancel_lru_locks mdc\n\tatime=$(stat -c %X $DIR/$tdir)\n\t[ \"$atime\" -ge \"$d1\" -a \"$atime\" -le \"$d2\" ] ||\n\t\terror \"atime is not updated  : $atime, should be $d2\"\n\n\tdo_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=60\n\tsleep 3\n\n\t# test not setting directory atime when now < dir atime + atime_diff\n\tls $DIR/$tdir\n\tcancel_lru_locks mdc\n\tatime=$(stat -c %X $DIR/$tdir)\n\t[ \"$atime\" -ge \"$d1\" -a \"$atime\" -le \"$d2\" ] ||\n\t\terror \"atime is updated to $atime, should remain $d1<atime<$d2\"\n\n\tdo_facet $SINGLEMDS \\\n\t\tlctl set_param -n mdd.*MDT0000*.atime_diff=$atime_diff\n}\nrun_test 39l \"directory atime update ===========================\"\n\ntest_39m() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR1/$tfile\n\tsleep 2\n\tlocal far_past_mtime=$(date -d \"May 29 1953\" +%s)\n\tlocal far_past_atime=$(date -d \"Dec 17 1903\" +%s)\n\n\ttouch -m -d @$far_past_mtime $DIR1/$tfile\n\ttouch -a -d @$far_past_atime $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal timestamps=$(stat -c \"%X %Y\" $DIR1/$tfile)\n\t\t[ \"$timestamps\" = \"$far_past_atime $far_past_mtime\" ] || \\\n\t\t\terror \"atime or mtime set incorrectly\"\n\n\t\tcancel_lru_locks $OSC\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39m \"test atime and mtime before 1970\"\n\ntest_39n() { # LU-3832\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal atime_diff=$(do_facet $SINGLEMDS \\\n\t\tlctl get_param -n mdd.*MDT0000*.atime_diff)\n\tlocal atime0\n\tlocal atime1\n\tlocal atime2\n\n\tdo_facet $SINGLEMDS lctl set_param -n mdd.*MDT0000*.atime_diff=1\n\n\trm -rf $DIR/$tfile\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 status=noxfer\n\tatime0=$(stat -c %X $DIR/$tfile)\n\n\tsleep 5\n\t$MULTIOP $DIR/$tfile oO_RDONLY:O_NOATIME:r4096c\n\tatime1=$(stat -c %X $DIR/$tfile)\n\n\tsleep 5\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\t$MULTIOP $DIR/$tfile oO_RDONLY:O_NOATIME:r4096c\n\tatime2=$(stat -c %X $DIR/$tfile)\n\n\tdo_facet $SINGLEMDS \\\n\t\tlctl set_param -n mdd.*MDT0000*.atime_diff=$atime_diff\n\n\t[ \"$atime0\" -eq \"$atime1\" ] || error \"atime0 $atime0 != atime1 $atime1\"\n\t[ \"$atime1\" -eq \"$atime2\" ] || error \"atime0 $atime0 != atime1 $atime1\"\n}\nrun_test 39n \"check that O_NOATIME is honored\"\n\ntest_39o() {\n\tTESTDIR=$DIR/$tdir/$tfile\n\t[ -e $TESTDIR ] && rm -rf $TESTDIR\n\tmkdir -p $TESTDIR\n\tcd $TESTDIR\n\tlinks1=2\n\tls\n\tmkdir a b\n\tls\n\tlinks2=$(stat -c %h .)\n\t[ $(($links1 + 2)) != $links2 ] &&\n\t\terror \"wrong links count $(($links1 + 2)) != $links2\"\n\trmdir b\n\tlinks3=$(stat -c %h .)\n\t[ $(($links1 + 1)) != $links3 ] &&\n\t\terror \"wrong links count $links1 != $links3\"\n\treturn 0\n}\nrun_test 39o \"directory cached attributes updated after create\"\n\ntest_39p() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal MDTIDX=1\n\tTESTDIR=$DIR/$tdir/$tdir\n\t[ -e $TESTDIR ] && rm -rf $TESTDIR\n\ttest_mkdir -p $TESTDIR\n\tcd $TESTDIR\n\tlinks1=2\n\tls\n\ttest_mkdir -i $MDTIDX $TESTDIR/remote_dir1\n\ttest_mkdir -i $MDTIDX $TESTDIR/remote_dir2\n\tls\n\tlinks2=$(stat -c %h .)\n\t[ $(($links1 + 2)) != $links2 ] &&\n\t\terror \"wrong links count $(($links1 + 2)) != $links2\"\n\trmdir remote_dir2\n\tlinks3=$(stat -c %h .)\n\t[ $(($links1 + 1)) != $links3 ] &&\n\t\terror \"wrong links count $links1 != $links3\"\n\treturn 0\n}\nrun_test 39p \"remote directory cached attributes updated after create ========\"\n\ntest_39r() {\n\t[ $OST1_VERSION -ge $(version_code 2.13.52) ] ||\n\t\tskip \"no atime update on old OST\"\n\tif [ \"$ost1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\tlocal saved_adiff\n\tsaved_adiff=$(do_facet ost1 \\\n\t\tlctl get_param -n obdfilter.*OST0000.atime_diff)\n\tstack_trap \"do_facet ost1 \\\n\t\tlctl set_param obdfilter.*.atime_diff=$saved_adiff\"\n\n\tdo_facet ost1 \"lctl set_param obdfilter.*.atime_diff=5\"\n\n\t$LFS setstripe -i 0 $DIR/$tfile\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=1 ||\n\t\terror \"can't write initial file\"\n\tcancel_lru_locks osc\n\n\t# exceed atime_diff and access file\n\tsleep 6\n\tdd if=$DIR/$tfile of=/dev/null || error \"can't udpate atime\"\n\n\tlocal atime_cli=$(stat -c %X $DIR/$tfile)\n\techo \"client atime: $atime_cli\"\n\t# allow atime update to be written to device\n\tdo_facet ost1 \"$LCTL set_param -n osd*.*OST*.force_sync 1\"\n\tsleep 5\n\n\tlocal ostdev=$(ostdevname 1)\n\tlocal fid=($(lfs getstripe -y $DIR/$tfile |\n\t\t\tawk '/l_fid:/ { print $2 }' | tr ':' ' '))\n\tlocal objpath=\"O/0/d$((${fid[1]} % 32))/$((${fid[1]}))\"\n\tlocal cmd=\"debugfs -c -R \\\\\\\"stat $objpath\\\\\\\" $ostdev\"\n\n\techo \"OST atime: $(do_facet ost1 \"$cmd\" |& grep atime)\"\n\tlocal atime_ost=$(do_facet ost1 \"$cmd\" |&\n\t\t\t  awk -F'[: ]' '/atime:/ { print $4 }')\n\t(( atime_cli == atime_ost )) ||\n\t\terror \"atime on client $atime_cli != ost $atime_ost\"\n}\nrun_test 39r \"lazy atime update on OST\"\n\ntest_39q() { # LU-8041\n\tlocal testdir=$DIR/$tdir\n\tmkdir -p $testdir\n\tmultiop_bg_pause $testdir D_c || error \"multiop failed\"\n\tlocal multipid=$!\n\tcancel_lru_locks mdc\n\tkill -USR1 $multipid\n\tlocal atime=$(stat -c %X $testdir)\n\t[ \"$atime\" -ne 0 ] || error \"atime is zero\"\n}\nrun_test 39q \"close won't zero out atime\"\n\ntest_40() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1\n\t$RUNAS $OPENFILE -f O_WRONLY:O_TRUNC $DIR/$tfile &&\n\t\terror \"openfile O_WRONLY:O_TRUNC $tfile failed\"\n\t$CHECKSTAT -t file -s 4096 $DIR/$tfile ||\n\t\terror \"$tfile is not 4096 bytes in size\"\n}\nrun_test 40 \"failed open(O_TRUNC) doesn't truncate =============\"\n\ntest_41() {\n\t# bug 1553\n\tsmall_write $DIR/f41 18\n}\nrun_test 41 \"test small file write + fstat =====================\"\n\ncount_ost_writes() {\n\tlctl get_param -n ${OSC}.*.stats |\n\t\tawk -vwrites=0 '/ost_write/ { writes += $2 } \\\n\t\t\tEND { printf(\"%0.0f\", writes) }'\n}\n\n# decent default\nWRITEBACK_SAVE=500\nDIRTY_RATIO_SAVE=40\nMAX_DIRTY_RATIO=50\nBG_DIRTY_RATIO_SAVE=10\nMAX_BG_DIRTY_RATIO=25\n\nstart_writeback() {\n\ttrap 0\n\t# in 2.6, restore /proc/sys/vm/dirty_writeback_centisecs,\n\t# dirty_ratio, dirty_background_ratio\n\tif [ -f /proc/sys/vm/dirty_writeback_centisecs ]; then\n\t\tsysctl -w vm.dirty_writeback_centisecs=$WRITEBACK_SAVE\n\t\tsysctl -w vm.dirty_background_ratio=$BG_DIRTY_RATIO_SAVE\n\t\tsysctl -w vm.dirty_ratio=$DIRTY_RATIO_SAVE\n\telse\n\t\t# if file not here, we are a 2.4 kernel\n\t\tkill -CONT `pidof kupdated`\n\tfi\n}\n\nstop_writeback() {\n\t# setup the trap first, so someone cannot exit the test at the\n\t# exact wrong time and mess up a machine\n\ttrap start_writeback EXIT\n\t# in 2.6, save and 0 /proc/sys/vm/dirty_writeback_centisecs\n\tif [ -f /proc/sys/vm/dirty_writeback_centisecs ]; then\n\t\tWRITEBACK_SAVE=`sysctl -n vm.dirty_writeback_centisecs`\n\t\tsysctl -w vm.dirty_writeback_centisecs=0\n\t\tsysctl -w vm.dirty_writeback_centisecs=0\n\t\t# save and increase /proc/sys/vm/dirty_ratio\n\t\tDIRTY_RATIO_SAVE=`sysctl -n vm.dirty_ratio`\n\t\tsysctl -w vm.dirty_ratio=$MAX_DIRTY_RATIO\n\t\t# save and increase /proc/sys/vm/dirty_background_ratio\n\t\tBG_DIRTY_RATIO_SAVE=`sysctl -n vm.dirty_background_ratio`\n\t\tsysctl -w vm.dirty_background_ratio=$MAX_BG_DIRTY_RATIO\n\telse\n\t\t# if file not here, we are a 2.4 kernel\n\t\tkill -STOP `pidof kupdated`\n\tfi\n}\n\n# ensure that all stripes have some grant before we test client-side cache\nsetup_test42() {\n\tfor i in `seq -f $DIR/f42-%g 1 $OSTCOUNT`; do\n\t\tdd if=/dev/zero of=$i bs=4k count=1\n\t\trm $i\n\tdone\n}\n\n# Tests 42* verify that our behaviour is correct WRT caching, file closure,\n# file truncation, and file removal.\ntest_42a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsetup_test42\n\tcancel_lru_locks $OSC\n\tstop_writeback\n\tsync; sleep 1; sync # just to be safe\n\tBEFOREWRITES=`count_ost_writes`\n        lctl get_param -n osc.*[oO][sS][cC][_-]*.cur_grant_bytes | grep \"[0-9]\"\n        dd if=/dev/zero of=$DIR/f42a bs=1024 count=100\n\tAFTERWRITES=`count_ost_writes`\n\t[ $BEFOREWRITES -eq $AFTERWRITES ] || \\\n\t\terror \"$BEFOREWRITES < $AFTERWRITES\"\n\tstart_writeback\n}\nrun_test 42a \"ensure that we don't flush on close\"\n\ntest_42b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsetup_test42\n\tcancel_lru_locks $OSC\n\tstop_writeback\n\tsync\n\tdd if=/dev/zero of=$DIR/f42b bs=1024 count=100\n\tBEFOREWRITES=$(count_ost_writes)\n\t$MUNLINK $DIR/f42b || error \"$MUNLINK $DIR/f42b: $?\"\n\tAFTERWRITES=$(count_ost_writes)\n\tif [[ $BEFOREWRITES -lt $AFTERWRITES ]]; then\n\t\terror \"$BEFOREWRITES < $AFTERWRITES on unlink\"\n\tfi\n\tBEFOREWRITES=$(count_ost_writes)\n\tsync || error \"sync: $?\"\n\tAFTERWRITES=$(count_ost_writes)\n\tif [[ $BEFOREWRITES -lt $AFTERWRITES ]]; then\n\t\terror \"$BEFOREWRITES < $AFTERWRITES on sync\"\n\tfi\n\tdmesg | grep 'error from obd_brw_async' && error 'error writing back'\n\tstart_writeback\n\treturn 0\n}\nrun_test 42b \"test destroy of file with cached dirty data ======\"\n\n# if these tests just want to test the effect of truncation,\n# they have to be very careful.  consider:\n# - the first open gets a {0,EOF}PR lock\n# - the first write conflicts and gets a {0, count-1}PW\n# - the rest of the writes are under {count,EOF}PW\n# - the open for truncate tries to match a {0,EOF}PR\n#   for the filesize and cancels the PWs.\n# any number of fixes (don't get {0,EOF} on open, match\n# composite locks, do smarter file size management) fix\n# this, but for now we want these tests to verify that\n# the cancellation with truncate intent works, so we\n# start the file with a full-file pw lock to match against\n# until the truncate.\ntrunc_test() {\n\ttest=$1\n\tfile=$DIR/$test\n\toffset=$2\n\tcancel_lru_locks $OSC\n\tstop_writeback\n\t# prime the file with 0,EOF PW to match\n\ttouch $file\n        $TRUNCATE $file 0\n        sync; sync\n\t# now the real test..\n\tdd if=/dev/zero of=$file bs=1024 count=100\n\tBEFOREWRITES=`count_ost_writes`\n\t$TRUNCATE $file $offset\n\tcancel_lru_locks $OSC\n\tAFTERWRITES=`count_ost_writes`\n\tstart_writeback\n}\n\ntest_42c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttrunc_test 42c 1024\n\t[ $BEFOREWRITES -eq $AFTERWRITES ] &&\n\t\terror \"beforewrites $BEFOREWRITES == afterwrites $AFTERWRITES on truncate\"\n\trm $file\n}\nrun_test 42c \"test partial truncate of file with cached dirty data\"\n\ntest_42d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttrunc_test 42d 0\n\t[ $BEFOREWRITES -eq $AFTERWRITES ] ||\n\t\terror \"beforewrites $BEFOREWRITES != afterwrites $AFTERWRITES on truncate\"\n\trm $file\n}\nrun_test 42d \"test complete truncate of file with cached dirty data\"\n\ntest_42e() { # bug22074\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal TDIR=$DIR/${tdir}e\n\tlocal pages=16 # hardcoded 16 pages, don't change it.\n\tlocal files=$((OSTCOUNT * 500)) # hopefully 500 files on each OST\n\tlocal proc_osc0=\"osc.${FSNAME}-OST0000-osc-[^MDT]*\"\n\tlocal max_dirty_mb\n\tlocal warmup_files\n\n\ttest_mkdir $DIR/${tdir}e\n\t$LFS setstripe -c 1 $TDIR\n\tcreatemany -o $TDIR/f $files\n\n\tmax_dirty_mb=$($LCTL get_param -n $proc_osc0/max_dirty_mb)\n\n\t# we assume that with $OSTCOUNT files, at least one of them will\n\t# be allocated on OST0.\n\twarmup_files=$((OSTCOUNT * max_dirty_mb))\n\tcreatemany -o $TDIR/w $warmup_files\n\n\t# write a large amount of data into one file and sync, to get good\n\t# avail_grant number from OST.\n\tfor ((i=0; i<$warmup_files; i++)); do\n\t\tidx=$($LFS getstripe -i $TDIR/w$i)\n\t\t[ $idx -ne 0 ] && continue\n\t\tdd if=/dev/zero of=$TDIR/w$i bs=\"$max_dirty_mb\"M count=1\n\t\tbreak\n\tdone\n\t[[ $i -gt $warmup_files ]] && error \"OST0 is still cold\"\n\tsync\n\t$LCTL get_param $proc_osc0/cur_dirty_bytes\n\t$LCTL get_param $proc_osc0/cur_grant_bytes\n\n\t# create as much dirty pages as we can while not to trigger the actual\n\t# RPCs directly. but depends on the env, VFS may trigger flush during this\n\t# period, hopefully we are good.\n\tfor ((i=0; i<$warmup_files; i++)); do\n\t\tidx=$($LFS getstripe -i $TDIR/w$i)\n\t\t[ $idx -ne 0 ] && continue\n\t\tdd if=/dev/zero of=$TDIR/w$i bs=1M count=1 2>/dev/null\n\tdone\n\t$LCTL get_param $proc_osc0/cur_dirty_bytes\n\t$LCTL get_param $proc_osc0/cur_grant_bytes\n\n\t# perform the real test\n\t$LCTL set_param $proc_osc0/rpc_stats 0\n\tfor ((;i<$files; i++)); do\n\t\t[ $($LFS getstripe -i $TDIR/f$i) -eq 0 ] || continue\n\t\tdd if=/dev/zero of=$TDIR/f$i bs=$PAGE_SIZE count=$pages 2>/dev/null\n\tdone\n\tsync\n\t$LCTL get_param $proc_osc0/rpc_stats\n\n        local percent=0\n        local have_ppr=false\n        $LCTL get_param $proc_osc0/rpc_stats |\n                while read PPR RRPC RPCT RCUM BAR WRPC WPCT WCUM; do\n                        # skip lines until we are at the RPC histogram data\n                        [ \"$PPR\" == \"pages\" ] && have_ppr=true && continue\n                        $have_ppr || continue\n\n                        # we only want the percent stat for < 16 pages\n\t\t\t[[ $(echo $PPR | tr -d ':') -ge $pages ]] && break\n\n                        percent=$((percent + WPCT))\n\t\t\tif [[ $percent -gt 15 ]]; then\n                                error \"less than 16-pages write RPCs\" \\\n                                      \"$percent% > 15%\"\n                                break\n                        fi\n                done\n        rm -rf $TDIR\n}\nrun_test 42e \"verify sub-RPC writes are not done synchronously\"\n\ntest_43A() { # was test_43\n\ttest_mkdir $DIR/$tdir\n\tcp -p /bin/ls $DIR/$tdir/$tfile\n\t$MULTIOP $DIR/$tdir/$tfile Ow_c &\n\tpid=$!\n\t# give multiop a chance to open\n\tsleep 1\n\n\t$DIR/$tdir/$tfile && error \"execute $DIR/$tdir/$tfile succeeded\" || true\n\tkill -USR1 $pid\n}\nrun_test 43A \"execution of file opened for write should return -ETXTBSY\"\n\ntest_43a() {\n\ttest_mkdir $DIR/$tdir\n\tcp -p $(which sleep) $DIR/$tdir/sleep || error \"can't copy\"\n\t$DIR/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\t# Make sure exec of $tdir/sleep wins race with truncate\n\tsleep 1\n\t$MULTIOP $DIR/$tdir/sleep Oc && error \"expected error, got success\"\n\tkill $SLEEP_PID\n}\nrun_test 43a \"open(RDWR) of file being executed should return -ETXTBSY\"\n\ntest_43b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tcp -p $(which sleep) $DIR/$tdir/sleep || error \"can't copy\"\n\t$DIR/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\t# Make sure exec of $tdir/sleep wins race with truncate\n\tsleep 1\n\t$TRUNCATE $DIR/$tdir/sleep 0 && error \"expected error, got success\"\n\tkill $SLEEP_PID\n}\nrun_test 43b \"truncate of file being executed should return -ETXTBSY\"\n\ntest_43c() {\n\tlocal testdir=\"$DIR/$tdir\"\n\ttest_mkdir $testdir\n\tcp $SHELL $testdir/\n\t( cd $(dirname $SHELL) && md5sum $(basename $SHELL) ) |\n\t\t( cd $testdir && md5sum -c )\n}\nrun_test 43c \"md5sum of copy into lustre\"\n\ntest_44A() { # was test_44\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tdd if=/dev/zero of=$DIR/f1 bs=4k count=1 seek=1023\n\tdd if=$DIR/f1 bs=4k count=1 > /dev/null\n}\nrun_test 44A \"zero length read from a sparse stripe\"\n\ntest_44a() {\n\tlocal nstripe=$($LCTL lov_getconfig $DIR | grep default_stripe_count: |\n\t\tawk '{ print $2 }')\n\t[ -z \"$nstripe\" ] && skip \"can't get stripe info\"\n\t[[ $nstripe -gt $OSTCOUNT ]] &&\n\t\tskip \"Wrong default_stripe_count: $nstripe OSTCOUNT: $OSTCOUNT\"\n\n\tlocal stride=$($LCTL lov_getconfig $DIR | grep default_stripe_size: |\n\t\tawk '{ print $2 }')\n\tif [[ $nstripe -eq 0 || $nstripe -eq -1 ]]; then\n\t\tnstripe=$($LCTL lov_getconfig $DIR | grep obd_count: |\n\t\t\tawk '{ print $2 }')\n\tfi\n\n\tOFFSETS=\"0 $((stride/2)) $((stride-1))\"\n\tfor offset in $OFFSETS; do\n\t\tfor i in $(seq 0 $((nstripe-1))); do\n\t\t\tlocal GLOBALOFFSETS=\"\"\n\t\t\t# size in Bytes\n\t\t\tlocal size=$((((i + 2 * $nstripe )*$stride + $offset)))\n\t\t\tlocal myfn=$DIR/d44a-$size\n\t\t\techo \"--------writing $myfn at $size\"\n\t\t\tll_sparseness_write $myfn $size ||\n\t\t\t\terror \"ll_sparseness_write\"\n\t\t\tGLOBALOFFSETS=\"$GLOBALOFFSETS $size\"\n\t\t\tll_sparseness_verify $myfn $GLOBALOFFSETS ||\n\t\t\t\terror \"ll_sparseness_verify $GLOBALOFFSETS\"\n\n\t\t\tfor j in $(seq 0 $((nstripe-1))); do\n\t\t\t\t# size in Bytes\n\t\t\t\tsize=$((((j + $nstripe )*$stride + $offset)))\n\t\t\t\tll_sparseness_write $myfn $size ||\n\t\t\t\t\terror \"ll_sparseness_write\"\n\t\t\t\tGLOBALOFFSETS=\"$GLOBALOFFSETS $size\"\n\t\t\tdone\n\t\t\tll_sparseness_verify $myfn $GLOBALOFFSETS ||\n\t\t\t\terror \"ll_sparseness_verify $GLOBALOFFSETS\"\n\t\t\trm -f $myfn\n\t\tdone\n\tdone\n}\nrun_test 44a \"test sparse pwrite ===============================\"\n\ndirty_osc_total() {\n\ttot=0\n\tfor d in `lctl get_param -n ${OSC}.*.cur_dirty_bytes`; do\n\t\ttot=$(($tot + $d))\n\tdone\n\techo $tot\n}\ndo_dirty_record() {\n\tbefore=`dirty_osc_total`\n\techo executing \"\\\"$*\\\"\"\n\teval $*\n\tafter=`dirty_osc_total`\n\techo before $before, after $after\n}\ntest_45() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tf=\"$DIR/f45\"\n\t# Obtain grants from OST if it supports it\n\techo blah > ${f}_grant\n\tstop_writeback\n\tsync\n\tdo_dirty_record \"echo blah > $f\"\n\t[[ $before -eq $after ]] && error \"write wasn't cached\"\n\tdo_dirty_record \"> $f\"\n\t[[ $before -gt $after ]] || error \"truncate didn't lower dirty count\"\n\tdo_dirty_record \"echo blah > $f\"\n\t[[ $before -eq $after ]] && error \"write wasn't cached\"\n\tdo_dirty_record \"sync\"\n\t[[ $before -gt $after ]] || error \"writeback didn't lower dirty count\"\n\tdo_dirty_record \"echo blah > $f\"\n\t[[ $before -eq $after ]] && error \"write wasn't cached\"\n\tdo_dirty_record \"cancel_lru_locks osc\"\n\t[[ $before -gt $after ]] ||\n\t\terror \"lock cancellation didn't lower dirty count\"\n\tstart_writeback\n}\nrun_test 45 \"osc io page accounting ============================\"\n\n# in a 2 stripe file (lov.sh), page 1023 maps to page 511 in its object.  this\n# test tickles a bug where re-dirtying a page was failing to be mapped to the\n# objects offset and an assert hit when an rpc was built with 1023's mapped\n# offset 511 and 511's raw 511 offset. it also found general redirtying bugs.\ntest_46() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tf=\"$DIR/f46\"\n\tstop_writeback\n\tsync\n\tdd if=/dev/zero of=$f bs=$PAGE_SIZE seek=511 count=1\n\tsync\n\tdd conv=notrunc if=/dev/zero of=$f bs=$PAGE_SIZE seek=1023 count=1\n\tdd conv=notrunc if=/dev/zero of=$f bs=$PAGE_SIZE seek=511 count=1\n\tsync\n\tstart_writeback\n}\nrun_test 46 \"dirtying a previously written page ================\"\n\n# test_47 is removed \"Device nodes check\" is moved to test_28\n\ntest_48a() { # bug 2399\n\t[ \"$mds1_FSTYPE\" = \"zfs\" ] &&\n\t[ $MDS1_VERSION -lt $(version_code 2.3.63) ] &&\n\t\tskip \"MDS prior to 2.3.63 handle ZFS dir .. incorrectly\"\n\n\ttest_mkdir $DIR/$tdir\n\tcd $DIR/$tdir\n\tmv $DIR/$tdir $DIR/$tdir.new || error \"move directory failed\"\n\ttest_mkdir $DIR/$tdir\n\ttouch foo || error \"'touch foo' failed after recreating cwd\"\n\ttest_mkdir bar\n\ttouch .foo || error \"'touch .foo' failed after recreating cwd\"\n\ttest_mkdir .bar\n\tls . > /dev/null || error \"'ls .' failed after recreating cwd\"\n\tls .. > /dev/null || error \"'ls ..' failed after removing cwd\"\n\tcd . || error \"'cd .' failed after recreating cwd\"\n\tmkdir . && error \"'mkdir .' worked after recreating cwd\"\n\trmdir . && error \"'rmdir .' worked after recreating cwd\"\n\tln -s . baz || error \"'ln -s .' failed after recreating cwd\"\n\tcd .. || error \"'cd ..' failed after recreating cwd\"\n}\nrun_test 48a \"Access renamed working dir (should return errors)=\"\n\ntest_48b() { # bug 2399\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\tcd $DIR/$tdir\n\trmdir $DIR/$tdir || error \"remove cwd $DIR/$tdir failed\"\n\ttouch foo && error \"'touch foo' worked after removing cwd\"\n\tmkdir foo && error \"'mkdir foo' worked after removing cwd\"\n\ttouch .foo && error \"'touch .foo' worked after removing cwd\"\n\tmkdir .foo && error \"'mkdir .foo' worked after removing cwd\"\n\tls . > /dev/null && error \"'ls .' worked after removing cwd\"\n\tls .. > /dev/null || error \"'ls ..' failed after removing cwd\"\n\tmkdir . && error \"'mkdir .' worked after removing cwd\"\n\trmdir . && error \"'rmdir .' worked after removing cwd\"\n\tln -s . foo && error \"'ln -s .' worked after removing cwd\"\n\tcd .. || echo \"'cd ..' failed after removing cwd `pwd`\"  #bug 3517\n}\nrun_test 48b \"Access removed working dir (should return errors)=\"\n\ntest_48c() { # bug 2350\n\t#lctl set_param debug=-1\n\t#set -vx\n\trm -rf $DIR/$tdir\n\ttest_mkdir -p $DIR/$tdir/dir\n\tcd $DIR/$tdir/dir\n\t$TRACE rmdir $DIR/$tdir/dir || error \"remove cwd $DIR/$tdir/dir failed\"\n\t$TRACE touch foo && error \"touch foo worked after removing cwd\"\n\t$TRACE mkdir foo && error \"'mkdir foo' worked after removing cwd\"\n\ttouch .foo && error \"touch .foo worked after removing cwd\"\n\tmkdir .foo && error \"mkdir .foo worked after removing cwd\"\n\t$TRACE ls . && error \"'ls .' worked after removing cwd\"\n\t$TRACE ls .. || error \"'ls ..' failed after removing cwd\"\n\t$TRACE mkdir . && error \"'mkdir .' worked after removing cwd\"\n\t$TRACE rmdir . && error \"'rmdir .' worked after removing cwd\"\n\t$TRACE ln -s . foo && error \"'ln -s .' worked after removing cwd\"\n\t$TRACE cd .. || echo \"'cd ..' failed after removing cwd `pwd`\" #bug 3415\n}\nrun_test 48c \"Access removed working subdir (should return errors)\"\n\ntest_48d() { # bug 2350\n\t#lctl set_param debug=-1\n\t#set -vx\n\trm -rf $DIR/$tdir\n\ttest_mkdir -p $DIR/$tdir/dir\n\tcd $DIR/$tdir/dir\n\t$TRACE rmdir $DIR/$tdir/dir || error \"remove cwd $DIR/$tdir/dir failed\"\n\t$TRACE rmdir $DIR/$tdir || error \"remove parent $DIR/$tdir failed\"\n\t$TRACE touch foo && error \"'touch foo' worked after removing parent\"\n\t$TRACE mkdir foo && error \"mkdir foo worked after removing parent\"\n\ttouch .foo && error \"'touch .foo' worked after removing parent\"\n\tmkdir .foo && error \"mkdir .foo worked after removing parent\"\n\t$TRACE ls . && error \"'ls .' worked after removing parent\"\n\t$TRACE ls .. && error \"'ls ..' worked after removing parent\"\n\t$TRACE mkdir . && error \"'mkdir .' worked after removing parent\"\n\t$TRACE rmdir . && error \"'rmdir .' worked after removing parent\"\n\t$TRACE ln -s . foo && error \"'ln -s .' worked after removing parent\"\n\ttrue\n}\nrun_test 48d \"Access removed parent subdir (should return errors)\"\n\ntest_48e() { # bug 4134\n\t#lctl set_param debug=-1\n\t#set -vx\n\trm -rf $DIR/$tdir\n\ttest_mkdir -p $DIR/$tdir/dir\n\tcd $DIR/$tdir/dir\n\t$TRACE rmdir $DIR/$tdir/dir || error \"remove cwd $DIR/$tdir/dir failed\"\n\t$TRACE rmdir $DIR/$tdir || error \"remove parent $DIR/$tdir failed\"\n\t$TRACE touch $DIR/$tdir || error \"'touch $DIR/$tdir' failed\"\n\t$TRACE chmod +x $DIR/$tdir || error \"'chmod +x $DIR/$tdir' failed\"\n\t# On a buggy kernel addition of \"touch foo\" after cd .. will\n\t# produce kernel oops in lookup_hash_it\n\ttouch ../foo && error \"'cd ..' worked after recreate parent\"\n\tcd $DIR\n\t$TRACE rm $DIR/$tdir || error \"rm '$DIR/$tdir' failed\"\n}\nrun_test 48e \"Access to recreated parent subdir (should return errors)\"\n\ntest_49() { # LU-1030\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\t# get ost1 size - $FSNAME-OST0000\n\tost1_size=$(do_facet ost1 $LFS df | grep ${ost1_svc} |\n\t\tawk '{ print $4 }')\n\t# write 800M at maximum\n\t[[ $ost1_size -lt 2 ]] && ost1_size=2\n\t[[ $ost1_size -gt 819200 ]] && ost1_size=819200\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=$((ost1_size >> 2)) &\n\tlocal dd_pid=$!\n\n\t# change max_pages_per_rpc while writing the file\n\tlocal osc1_mppc=osc.$(get_osc_import_name client ost1).max_pages_per_rpc\n\tlocal orig_mppc=$($LCTL get_param -n $osc1_mppc)\n\t# loop until dd process exits\n\twhile ps ax -opid | grep -wq $dd_pid; do\n\t\t$LCTL set_param $osc1_mppc=$((RANDOM % 256 + 1))\n\t\tsleep $((RANDOM % 5 + 1))\n\tdone\n\t# restore original max_pages_per_rpc\n\t$LCTL set_param $osc1_mppc=$orig_mppc\n\trm $DIR/$tfile || error \"rm $DIR/$tfile failed\"\n}\nrun_test 49 \"Change max_pages_per_rpc won't break osc extent\"\n\ntest_50() {\n\t# bug 1485\n\ttest_mkdir $DIR/$tdir\n\tcd $DIR/$tdir\n\tls /proc/$$/cwd || error \"ls /proc/$$/cwd failed\"\n}\nrun_test 50 \"special situations: /proc symlinks  ===============\"\n\ntest_51a() {\t# was test_51\n\t# bug 1516 - create an empty entry right after \"..\" then split dir\n\ttest_mkdir -c1 $DIR/$tdir\n\ttouch $DIR/$tdir/foo\n\t$MCREATE $DIR/$tdir/bar\n\trm $DIR/$tdir/foo\n\tcreatemany -m $DIR/$tdir/longfile 201\n\tFNUM=202\n\twhile [[ $(ls -sd $DIR/$tdir | awk '{ print $1 }') -eq 4 ]]; do\n\t\t$MCREATE $DIR/$tdir/longfile$FNUM\n\t\tFNUM=$(($FNUM + 1))\n\t\techo -n \"+\"\n\tdone\n\techo\n\tls -l $DIR/$tdir > /dev/null || error \"ls -l $DIR/$tdir failed\"\n}\nrun_test 51a \"special situations: split htree with empty entry ==\"\n\ncleanup_print_lfs_df () {\n\ttrap 0\n\t$LFS df\n\t$LFS df -i\n}\n\ntest_51b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal nrdirs=$((65536 + 100))\n\n\t# cleanup the directory\n\trm -fr $dir\n\n\ttest_mkdir -c1 $dir\n\n\t$LFS df\n\t$LFS df -i\n\tlocal mdtidx=$(printf \"%04x\" $($LFS getstripe -m $dir))\n\tlocal numfree=$(lctl get_param -n mdc.$FSNAME-MDT$mdtidx*.filesfree)\n\t[[ $numfree -lt $nrdirs ]] &&\n\t\tskip \"not enough free inodes ($numfree) on MDT$mdtidx\"\n\n\t# need to check free space for the directories as well\n\tlocal blkfree=$(lctl get_param -n mdc.$FSNAME-MDT$mdtidx*.kbytesavail)\n\tnumfree=$(( blkfree / $(fs_inode_ksize) ))\n\t[[ $numfree -lt $nrdirs ]] && skip \"not enough blocks ($numfree)\"\n\n\ttrap cleanup_print_lfs_df EXIT\n\n\t# create files\n\tcreatemany -d $dir/d $nrdirs || {\n\t\tunlinkmany $dir/d $nrdirs\n\t\terror \"failed to create $nrdirs subdirs in MDT$mdtidx:$dir\"\n\t}\n\n\t# really created :\n\tnrdirs=$(ls -U $dir | wc -l)\n\n\t# unlink all but 100 subdirectories, then check it still works\n\tlocal left=100\n\tlocal delete=$((nrdirs - left))\n\n\t$LFS df\n\t$LFS df -i\n\n\t# for ldiskfs the nlink count should be 1, but this is OSD specific\n\t# and so this is listed for informational purposes only\n\techo \"nlink before: $(stat -c %h $dir), created before: $nrdirs\"\n\tunlinkmany -d $dir/d $delete ||\n\t\terror \"unlink of first $delete subdirs failed\"\n\n\techo \"nlink between: $(stat -c %h $dir)\"\n\tlocal found=$(ls -U $dir | wc -l)\n\t[ $found -ne $left ] &&\n\t\terror \"can't find subdirs: found only $found, expected $left\"\n\n\tunlinkmany -d $dir/d $delete $left ||\n\t\terror \"unlink of second $left subdirs failed\"\n\t# regardless of whether the backing filesystem tracks nlink accurately\n\t# or not, the nlink count shouldn't be more than \".\" and \"..\" here\n\tlocal after=$(stat -c %h $dir)\n\t[[ $after -gt 2 ]] && error \"nlink after: $after > 2\" ||\n\t\techo \"nlink after: $after\"\n\n\tcleanup_print_lfs_df\n}\nrun_test 51b \"exceed 64k subdirectory nlink limit on create, verify unlink\"\n\ntest_51d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 3 ]] && skip_env \"needs >= 3 OSTs\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/t- 1000\n\t$LFS getstripe $DIR/$tdir > $TMP/$tfile\n\tfor N in $(seq 0 $((OSTCOUNT - 1))); do\n\t\tOBJS[$N]=$(awk -vobjs=0 '($1 == '$N') { objs += 1 } \\\n\t\t\tEND { printf(\"%0.0f\", objs) }' $TMP/$tfile)\n\t\tOBJS0[$N]=$(grep -A 1 idx $TMP/$tfile | awk -vobjs=0 \\\n\t\t\t'($1 == '$N') { objs += 1 } \\\n\t\t\tEND { printf(\"%0.0f\", objs) }')\n\t\tlog \"OST$N has ${OBJS[$N]} objects, ${OBJS0[$N]} are index 0\"\n\tdone\n\tunlinkmany $DIR/$tdir/t- 1000\n\n\tNLAST=0\n\tfor N in $(seq 1 $((OSTCOUNT - 1))); do\n\t\t[[ ${OBJS[$N]} -lt $((${OBJS[$NLAST]} - 20)) ]] &&\n\t\t\terror \"OST $N has less objects vs OST $NLAST\" \\\n\t\t\t      \" (${OBJS[$N]} < ${OBJS[$NLAST]}\"\n\t\t[[ ${OBJS[$N]} -gt $((${OBJS[$NLAST]} + 20)) ]] &&\n\t\t\terror \"OST $N has less objects vs OST $NLAST\" \\\n\t\t\t      \" (${OBJS[$N]} < ${OBJS[$NLAST]}\"\n\n\t\t[[ ${OBJS0[$N]} -lt $((${OBJS0[$NLAST]} - 20)) ]] &&\n\t\t\terror \"OST $N has less #0 objects vs OST $NLAST\" \\\n\t\t\t      \" (${OBJS0[$N]} < ${OBJS0[$NLAST]}\"\n\t\t[[ ${OBJS0[$N]} -gt $((${OBJS0[$NLAST]} + 20)) ]] &&\n\t\t\terror \"OST $N has less #0 objects vs OST $NLAST\" \\\n\t\t\t      \" (${OBJS0[$N]} < ${OBJS0[$NLAST]}\"\n\t\tNLAST=$N\n\tdone\n\trm -f $TMP/$tfile\n}\nrun_test 51d \"check object distribution\"\n\ntest_51e() {\n\tif [ \"$mds1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\ttest_mkdir -c1 $DIR/$tdir\n\ttest_mkdir -c1 $DIR/$tdir/d0\n\n\ttouch $DIR/$tdir/d0/foo\n\tcreatemany -l $DIR/$tdir/d0/foo $DIR/$tdir/d0/f- 65001 &&\n\t\terror \"file exceed 65000 nlink limit!\"\n\tunlinkmany $DIR/$tdir/d0/f- 65001\n\treturn 0\n}\nrun_test 51e \"check file nlink limit\"\n\ntest_51f() {\n\ttest_mkdir $DIR/$tdir\n\n\tlocal max=100000\n\tlocal ulimit_old=$(ulimit -n)\n\tlocal spare=20 # number of spare fd's for scripts/libraries, etc.\n\tlocal mdt=$($LFS getstripe -m $DIR/$tdir)\n\tlocal numfree=$($LFS df -i $DIR/$tdir | awk '/MDT:'$mdt'/ { print $4 }')\n\n\techo \"MDT$mdt numfree=$numfree, max=$max\"\n\t[[ $numfree -gt $max ]] && numfree=$max || numfree=$((numfree * 7 / 8))\n\tif [ $((numfree + spare)) -gt $ulimit_old ]; then\n\t\twhile ! ulimit -n $((numfree + spare)); do\n\t\t\tnumfree=$((numfree * 3 / 4))\n\t\tdone\n\t\techo \"changed ulimit from $ulimit_old to $((numfree + spare))\"\n\telse\n\t\techo \"left ulimit at $ulimit_old\"\n\tfi\n\n\tcreatemany -o -k -t 120 $DIR/$tdir/f $numfree || {\n\t\tunlinkmany $DIR/$tdir/f $numfree\n\t\terror \"create+open $numfree files in $DIR/$tdir failed\"\n\t}\n\tulimit -n $ulimit_old\n\n\t# if createmany exits at 120s there will be fewer than $numfree files\n\tunlinkmany $DIR/$tdir/f $numfree || true\n}\nrun_test 51f \"check many open files limit\"\n\ntest_52a() {\n\t[ -f $DIR/$tdir/foo ] && chattr -a $DIR/$tdir/foo\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/foo\n\tchattr +a $DIR/$tdir/foo || error \"chattr +a failed\"\n\techo bar >> $DIR/$tdir/foo || error \"append bar failed\"\n\tcp /etc/hosts $DIR/$tdir/foo && error \"cp worked\"\n\trm -f $DIR/$tdir/foo 2>/dev/null && error \"rm worked\"\n\tlink $DIR/$tdir/foo $DIR/$tdir/foo_link 2>/dev/null &&\n\t\t\t\t\terror \"link worked\"\n\techo foo >> $DIR/$tdir/foo || error \"append foo failed\"\n\tmrename $DIR/$tdir/foo $DIR/$tdir/foo_ren && error \"rename worked\"\n\tlsattr $DIR/$tdir/foo | egrep -q \"^-+a[-e]+ $DIR/$tdir/foo\" ||\n\t\t\t\t\t\t     error \"lsattr\"\n\tchattr -a $DIR/$tdir/foo || error \"chattr -a failed\"\n\tcp -r $DIR/$tdir $TMP/\n\trm -fr $DIR/$tdir $TMP/$tdir || error \"cleanup rm failed\"\n}\nrun_test 52a \"append-only flag test (should return errors)\"\n\ntest_52b() {\n\t[ -f $DIR/$tdir/foo ] && chattr -i $DIR/$tdir/foo\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/foo\n\tchattr +i $DIR/$tdir/foo || error \"chattr +i failed\"\n\tcat test > $DIR/$tdir/foo && error \"cat test worked\"\n\tcp /etc/hosts $DIR/$tdir/foo && error \"cp worked\"\n\trm -f $DIR/$tdir/foo 2>/dev/null && error \"rm worked\"\n\tlink $DIR/$tdir/foo $DIR/$tdir/foo_link 2>/dev/null &&\n\t\t\t\t\terror \"link worked\"\n\techo foo >> $DIR/$tdir/foo && error \"echo worked\"\n\tmrename $DIR/$tdir/foo $DIR/$tdir/foo_ren && error \"rename worked\"\n\t[ -f $DIR/$tdir/foo ] || error \"$tdir/foo is not a file\"\n\t[ -f $DIR/$tdir/foo_ren ] && error \"$tdir/foo_ren is not a file\"\n\tlsattr $DIR/$tdir/foo | egrep -q \"^-+i[-e]+ $DIR/$tdir/foo\" ||\n\t\t\t\t\t\t\terror \"lsattr\"\n\tchattr -i $DIR/$tdir/foo || error \"chattr failed\"\n\n\trm -fr $DIR/$tdir || error \"unable to remove $DIR/$tdir\"\n}\nrun_test 52b \"immutable flag test (should return errors) =======\"\n\ntest_53() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal param\n\tlocal param_seq\n\tlocal ostname\n\tlocal mds_last\n\tlocal mds_last_seq\n\tlocal ost_last\n\tlocal ost_last_seq\n\tlocal ost_last_id\n\tlocal ostnum\n\tlocal node\n\tlocal found=false\n\tlocal support_last_seq=true\n\n\t[[ $MDS1_VERSION -ge $(version_code 2.3.60) ]] ||\n\t\tsupport_last_seq=false\n\n\t# only test MDT0000\n\tlocal mdtosc=$(get_mdtosc_proc_path $SINGLEMDS)\n\tlocal value\n\tfor value in $(do_facet $SINGLEMDS \\\n\t\t       $LCTL get_param osp.$mdtosc.prealloc_last_id) ; do\n\t\tparam=$(echo ${value[0]} | cut -d \"=\" -f1)\n\t\tostname=$(echo $param | cut -d \".\" -f2 | cut -d - -f 1-2)\n\n\t\tif $support_last_seq; then\n\t\t\tparam_seq=$(echo $param |\n\t\t\t\tsed -e s/prealloc_last_id/prealloc_last_seq/g)\n\t\t\tmds_last_seq=$(do_facet $SINGLEMDS \\\n\t\t\t\t       $LCTL get_param -n $param_seq)\n\t\tfi\n\t\tmds_last=$(do_facet $SINGLEMDS $LCTL get_param -n $param)\n\n\t\tostnum=$(index_from_ostuuid ${ostname}_UUID)\n\t\tnode=$(facet_active_host ost$((ostnum+1)))\n\t\tparam=\"obdfilter.$ostname.last_id\"\n\t\tfor ost_last in $(do_node $node $LCTL get_param -n $param) ; do\n\t\t\techo \"$ostname.last_id=$ost_last; MDS.last_id=$mds_last\"\n\t\t\tost_last_id=$ost_last\n\n\t\t\tif $support_last_seq; then\n\t\t\t\tost_last_id=$(echo $ost_last |\n\t\t\t\t\t      awk -F':' '{print $2}' |\n\t\t\t\t\t      sed -e \"s/^0x//g\")\n\t\t\t\tost_last_seq=$(echo $ost_last |\n\t\t\t\t\t       awk -F':' '{print $1}')\n\t\t\t\t[[ $ost_last_seq = $mds_last_seq ]] || continue\n\t\t\tfi\n\n\t\t\tif [[ $ost_last_id != $mds_last ]]; then\n\t\t\t\terror \"$ost_last_id != $mds_last\"\n\t\t\telse\n\t\t\t\tfound=true\n\t\t\t\tbreak\n\t\t\tfi\n\t\tdone\n\tdone\n\t$found || error \"can not match last_seq/last_id for $mdtosc\"\n\treturn 0\n}\nrun_test 53 \"verify that MDS and OSTs agree on pre-creation ====\"\n\ntest_54a() {\n\tperl -MSocket -e ';' || skip \"no Socket perl module installed\"\n\n\t$SOCKETSERVER $DIR/socket ||\n\t\terror \"$SOCKETSERVER $DIR/socket failed: $?\"\n\t$SOCKETCLIENT $DIR/socket ||\n\t\terror \"$SOCKETCLIENT $DIR/socket failed: $?\"\n\t$MUNLINK $DIR/socket || error \"$MUNLINK $DIR/socket failed: $?\"\n}\nrun_test 54a \"unix domain socket test ==========================\"\n\ntest_54b() {\n\tf=\"$DIR/f54b\"\n\tmknod $f c 1 3\n\tchmod 0666 $f\n\tdd if=/dev/zero of=$f bs=$PAGE_SIZE count=1\n}\nrun_test 54b \"char device works in lustre ======================\"\n\nfind_loop_dev() {\n\t[ -b /dev/loop/0 ] && LOOPBASE=/dev/loop/\n\t[ -b /dev/loop0 ] && LOOPBASE=/dev/loop\n\t[ -z \"$LOOPBASE\" ] && echo \"/dev/loop/0 and /dev/loop0 gone?\" && return\n\n\tfor i in $(seq 3 7); do\n\t\tlosetup $LOOPBASE$i > /dev/null 2>&1 && continue\n\t\tLOOPDEV=$LOOPBASE$i\n\t\tLOOPNUM=$i\n\t\tbreak\n\tdone\n}\n\ncleanup_54c() {\n\tlocal rc=0\n\tloopdev=\"$DIR/loop54c\"\n\n\ttrap 0\n\t$UMOUNT $DIR/$tdir || rc=$?\n\tlosetup -d $loopdev || true\n\tlosetup -d $LOOPDEV || true\n\trm -rf $loopdev $DIR/$tfile $DIR/$tdir\n\treturn $rc\n}\n\ntest_54c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tloopdev=\"$DIR/loop54c\"\n\n\tfind_loop_dev\n\t[ -z \"$LOOPNUM\" ] && skip_env \"couldn't find empty loop device\"\n\ttrap cleanup_54c EXIT\n\tmknod $loopdev b 7 $LOOPNUM\n\techo \"make a loop file system with $DIR/$tfile on $loopdev ($LOOPNUM).\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE seek=1024 count=1 > /dev/null\n\tlosetup $loopdev $DIR/$tfile ||\n\t\terror \"can't set up $loopdev for $DIR/$tfile\"\n\tmkfs.ext2 $loopdev || error \"mke2fs on $loopdev\"\n\ttest_mkdir $DIR/$tdir\n\tmount -t ext2 $loopdev $DIR/$tdir ||\n\t\terror \"error mounting $loopdev on $DIR/$tdir\"\n\tdd if=/dev/zero of=$DIR/$tdir/tmp bs=$PAGE_SIZE count=30 ||\n\t\terror \"dd write\"\n\tdf $DIR/$tdir\n\tdd if=$DIR/$tdir/tmp of=/dev/zero bs=$PAGE_SIZE count=30 ||\n\t\terror \"dd read\"\n\tcleanup_54c\n}\nrun_test 54c \"block device works in lustre =====================\"\n\ntest_54d() {\n\tf=\"$DIR/f54d\"\n\tstring=\"aaaaaa\"\n\tmknod $f p\n\t[ \"$string\" = $(echo $string > $f | cat $f) ] || error \"$f != $string\"\n}\nrun_test 54d \"fifo device works in lustre ======================\"\n\ntest_54e() {\n\tf=\"$DIR/f54e\"\n\tstring=\"aaaaaa\"\n\tcp -aL /dev/console $f\n\techo $string > $f || error \"echo $string to $f failed\"\n}\nrun_test 54e \"console/tty device works in lustre ======================\"\n\ntest_56a() {\n\tlocal numfiles=3\n\tlocal dir=$DIR/$tdir\n\n\trm -rf $dir\n\ttest_mkdir -p $dir/dir\n\tfor i in $(seq $numfiles); do\n\t\ttouch $dir/file$i\n\t\ttouch $dir/dir/file$i\n\tdone\n\n\tlocal numcomp=$($LFS getstripe --component-count $dir)\n\n\t[[ $numcomp == 0 ]] && numcomp=1\n\n\t# test lfs getstripe with --recursive\n\tlocal filenum=$($LFS getstripe -r $dir | egrep -c \"obdidx|l_ost_idx\")\n\n\t[[ $filenum -eq $((numfiles * 2)) ]] ||\n\t\terror \"$LFS getstripe -r: found $filenum != $((numfiles * 2))\"\n\tfilenum=$($LFS getstripe $dir | egrep -c \"obdidx|l_ost_idx\")\n\t[[ $filenum -eq $numfiles ]] ||\n\t\terror \"$LFS getstripe $dir: found $filenum, not $numfiles\"\n\techo \"$LFS getstripe showed obdidx or l_ost_idx\"\n\n\t# test lfs getstripe with file instead of dir\n\tfilenum=$($LFS getstripe $dir/file1 | egrep -c \"obdidx|l_ost_idx\")\n\t[[ $filenum -eq 1 ]] ||\n\t\terror \"$LFS getstripe $dir/file1: found $filenum, not 1\"\n\techo \"$LFS getstripe file1 passed\"\n\n\t#test lfs getstripe with --verbose\n\tfilenum=$($LFS getstripe --verbose $dir | grep -c lmm_magic)\n\t[[ $filenum -eq $((numfiles * numcomp)) ]] ||\n\t\terror \"$LFS getstripe --verbose $dir: \"\\\n\t\t      \"got $filenum want $((numfiles * numcomp)) lmm_magic\"\n\t[[ $($LFS getstripe $dir | grep -c lmm_magic) -eq 0 ]] ||\n\t\terror \"$LFS getstripe $dir: showed lmm_magic\"\n\n\t#test lfs getstripe with -v prints lmm_fid\n\tfilenum=$($LFS getstripe -v $dir | grep -c lmm_fid)\n\t[[ $filenum -eq $((numfiles * numcomp)) ]] ||\n\t\terror \"$LFS getstripe -v $dir: \"\\\n\t\t      \"got $filenum want $((numfiles * numcomp)) lmm_fid\"\n\t[[ $($LFS getstripe $dir | grep -c lmm_fid) -eq 0 ]] ||\n\t\terror \"$LFS getstripe $dir: showed lmm_fid by default\"\n\techo \"$LFS getstripe --verbose passed\"\n\n\t#check for FID information\n\tlocal fid1=$($LFS getstripe --fid $dir/file1)\n\tlocal fid2=$($LFS getstripe --verbose $dir/file1 |\n\t\t     awk '/lmm_fid: / { print $2; exit; }')\n\tlocal fid3=$($LFS path2fid $dir/file1)\n\n\t[ \"$fid1\" != \"$fid2\" ] &&\n\t\terror \"getstripe --fid '$fid1' != getstripe --verbose '$fid2'\"\n\t[ \"$fid1\" != \"$fid3\" ] &&\n\t\terror \"getstripe --fid '$fid1' != lfs path2fid '$fid3'\"\n\techo \"$LFS getstripe --fid passed\"\n\n\t#test lfs getstripe with --obd\n\t$LFS getstripe --obd wrong_uuid $dir 2>&1 | grep -q \"unknown obduuid\" ||\n\t\terror \"$LFS getstripe --obd wrong_uuid: should return error\"\n\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal ostidx=1\n\tlocal obduuid=$(ostuuid_from_index $ostidx)\n\tlocal found=$($LFS getstripe -r --obd $obduuid $dir |\n\t\tgrep 'lmm_stripe_offset:' | grep -c \" $ostidx\\$\")\n\n\tfilenum=$($LFS getstripe -ir $dir | grep -c \"^$ostidx\\$\")\n\t[[ $($LFS getstripe -id $dir) -ne $ostidx ]] ||\n\t\t((filenum--))\n\t[[ $($LFS getstripe -id $dir/dir) -ne $ostidx ]] ||\n\t\t((filenum--))\n\n\t[[ $found -eq $filenum ]] ||\n\t\terror \"$LFS getstripe --obd: found $found expect $filenum\"\n\t[[ $($LFS getstripe -r -v --obd $obduuid $dir |\n\t\tsed '/^[\t ]*'${ostidx}'[\t ]/d' |\n\t\tsed -n '/^[\t ]*[0-9][0-9]*[\t ]/p' | wc -l) -eq 0 ]] ||\n\t\terror \"$LFS getstripe --obd: should not show file on other obd\"\n\techo \"$LFS getstripe --obd passed\"\n}\nrun_test 56a \"check $LFS getstripe\"\n\ntest_56b() {\n\tlocal dir=$DIR/$tdir\n\tlocal numdirs=3\n\n\ttest_mkdir $dir\n\tfor i in $(seq $numdirs); do\n\t\ttest_mkdir $dir/dir$i\n\tdone\n\n\t# test lfs getdirstripe default mode is non-recursion, which is\n\t# different from lfs getstripe\n\tlocal dircnt=$($LFS getdirstripe $dir | grep -c lmv_stripe_count)\n\n\t[[ $dircnt -eq 1 ]] ||\n\t\terror \"$LFS getdirstripe: found $dircnt, not 1\"\n\tdircnt=$($LFS getdirstripe --recursive $dir |\n\t\tgrep -c lmv_stripe_count)\n\t[[ $dircnt -eq $((numdirs + 1)) ]] ||\n\t\terror \"$LFS getdirstripe -r: $dircnt, != $((numdirs + 1))\"\n}\nrun_test 56b \"check $LFS getdirstripe\"\n\ntest_56c() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal ost_idx=0\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\tlocal old_status=$(ost_dev_status $ost_idx)\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\t[[ -z \"$old_status\" ]] ||\n\t\tskip_env \"OST $ost_name is in $old_status status\"\n\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name.degraded=1\n\t[[ $OST1_VERSION -lt $(version_code 2.12.55) ]] || do_facet ost1 \\\n\t\t$LCTL set_param -n obdfilter.$ost_name.no_precreate=1\n\tif [[ $OST1_VERSION -ge $(version_code 2.12.57) ]]; then\n\t\tsave_lustre_params ost1 osd-*.$ost_name.nonrotational > $p\n\t\tdo_facet ost1 $LCTL set_param -n osd-*.$ost_name.nonrotational=1\n\tfi\n\n\t[[ $($LFS df -v $MOUNT |& grep -c \"inactive device\") -eq 0 ]] ||\n\t\terror \"$LFS df -v showing inactive devices\"\n\tsleep_maxage\n\n\tlocal new_status=$(ost_dev_status $ost_idx $MOUNT -v)\n\n\t[[ \"$new_status\" =~ \"D\" ]] ||\n\t\terror \"$ost_name status is '$new_status', missing 'D'\"\n\tif [[ $OST1_VERSION -ge $(version_code 2.12.55) ]]; then\n\t\t[[ \"$new_status\" =~ \"N\" ]] ||\n\t\t\terror \"$ost_name status is '$new_status', missing 'N'\"\n\tfi\n\tif [[ $OST1_VERSION -ge $(version_code 2.12.57) ]]; then\n\t\t[[ \"$new_status\" =~ \"f\" ]] ||\n\t\t\terror \"$ost_name status is '$new_status', missing 'f'\"\n\tfi\n\n\tdo_facet ost1 $LCTL set_param -n obdfilter.$ost_name.degraded=0\n\t[[ $OST1_VERSION -lt $(version_code 2.12.55) ]] || do_facet ost1 \\\n\t\t$LCTL set_param -n obdfilter.$ost_name.no_precreate=0\n\t[[ -z \"$p\" ]] && restore_lustre_params < $p || true\n\tsleep_maxage\n\n\tnew_status=$(ost_dev_status $ost_idx)\n\t[[ ! \"$new_status\" =~ \"D\" && ! \"$new_status\" =~ \"N\" ]] ||\n\t\terror \"$ost_name status is '$new_status', has 'D' and/or 'N'\"\n\t# can't check 'f' as devices may actually be on flash\n}\nrun_test 56c \"check 'lfs df' showing device status\"\n\ntest_56d() {\n\tlocal mdts=$($LFS df -v $MOUNT | grep -c MDT)\n\tlocal osts=$($LFS df -v $MOUNT | grep -c OST)\n\n\t$LFS df $MOUNT\n\n\t(( mdts == MDSCOUNT )) ||\n\t\terror \"lfs df -v showed $mdts MDTs, not $MDSCOUNT\"\n\t(( osts == OSTCOUNT )) ||\n\t\terror \"lfs df -v showed $osts OSTs, not $OSTCOUNT\"\n}\nrun_test 56d \"'lfs df -v' prints only configured devices\"\n\nNUMFILES=3\nNUMDIRS=3\nsetup_56() {\n\tlocal local_tdir=\"$1\"\n\tlocal local_numfiles=\"$2\"\n\tlocal local_numdirs=\"$3\"\n\tlocal dir_params=\"$4\"\n\tlocal dir_stripe_params=\"$5\"\n\n\tif [ ! -d \"$local_tdir\" ] ; then\n\t\ttest_mkdir -p $dir_stripe_params $local_tdir\n\t\t[ \"$dir_params\" ] && $LFS setstripe $dir_params $local_tdir\n\t\tfor i in $(seq $local_numfiles) ; do\n\t\t\ttouch $local_tdir/file$i\n\t\tdone\n\t\tfor i in $(seq $local_numdirs) ; do\n\t\t\ttest_mkdir $dir_stripe_params $local_tdir/dir$i\n\t\t\tfor j in $(seq $local_numfiles) ; do\n\t\t\t\ttouch $local_tdir/dir$i/file$j\n\t\t\tdone\n\t\tdone\n\tfi\n}\n\nsetup_56_special() {\n\tlocal local_tdir=$1\n\tlocal local_numfiles=$2\n\tlocal local_numdirs=$3\n\n\tsetup_56 $local_tdir $local_numfiles $local_numdirs\n\n\tif [ ! -e \"$local_tdir/loop${local_numfiles}b\" ] ; then\n\t\tfor i in $(seq $local_numfiles) ; do\n\t\t\tmknod $local_tdir/loop${i}b b 7 $i\n\t\t\tmknod $local_tdir/null${i}c c 1 3\n\t\t\tln -s $local_tdir/file1 $local_tdir/link${i}\n\t\tdone\n\t\tfor i in $(seq $local_numdirs) ; do\n\t\t\tmknod $local_tdir/dir$i/loop${i}b b 7 $i\n\t\t\tmknod $local_tdir/dir$i/null${i}c c 1 3\n\t\t\tln -s $local_tdir/dir$i/file1 $local_tdir/dir$i/link${i}\n\t\tdone\n\tfi\n}\n\ntest_56g() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\tlocal expected=$(($NUMDIRS + 2))\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\n\t# test lfs find with -name\n\tfor i in $(seq $NUMFILES) ; do\n\t\tlocal nums=$($LFS find -name \"*$i\" $dir | wc -l)\n\n\t\t[ $nums -eq $expected ] ||\n\t\t\terror \"lfs find -name '*$i' $dir wrong: \"\\\n\t\t\t      \"found $nums, expected $expected\"\n\tdone\n}\nrun_test 56g \"check lfs find -name\"\n\ntest_56h() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\tlocal expected=$(((NUMDIRS + 1) * (NUMFILES - 1) + NUMFILES))\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\n\t# test lfs find with ! -name\n\tfor i in $(seq $NUMFILES) ; do\n\t\tlocal nums=$($LFS find ! -name \"*$i\" $dir | wc -l)\n\n\t\t[ $nums -eq $expected ] ||\n\t\t\terror \"lfs find ! -name '*$i' $dir wrong: \"\\\n\t\t\t      \"found $nums, expected $expected\"\n\tdone\n}\nrun_test 56h \"check lfs find ! -name\"\n\ntest_56i() {\n\tlocal dir=$DIR/$tdir\n\n\ttest_mkdir $dir\n\n\tlocal cmd=\"$LFS find -ost $(ostuuid_from_index 0 $dir) $dir\"\n\tlocal out=$($cmd)\n\n\t[ -z \"$out\" ] || error \"'$cmd' returned directory '$out'\"\n}\nrun_test 56i \"check 'lfs find -ost UUID' skips directories\"\n\ntest_56j() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\n\tsetup_56_special $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=$((NUMDIRS + 1))\n\tlocal cmd=\"$LFS find -type d $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56j \"check lfs find -type d\"\n\ntest_56k() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\n\tsetup_56_special $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=$(((NUMDIRS + 1) * NUMFILES))\n\tlocal cmd=\"$LFS find -type f $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56k \"check lfs find -type f\"\n\ntest_56l() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\n\tsetup_56_special $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=$((NUMDIRS + NUMFILES))\n\tlocal cmd=\"$LFS find -type b $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56l \"check lfs find -type b\"\n\ntest_56m() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\n\tsetup_56_special $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=$((NUMDIRS + NUMFILES))\n\tlocal cmd=\"$LFS find -type c $dir\"\n\tlocal nums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56m \"check lfs find -type c\"\n\ntest_56n() {\n\tlocal dir=$DIR/d$(basetest $testnum)g.$TESTSUITE\n\tsetup_56_special $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=$((NUMDIRS + NUMFILES))\n\tlocal cmd=\"$LFS find -type l $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56n \"check lfs find -type l\"\n\ntest_56o() {\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\tutime $dir/file1 > /dev/null || error \"utime (1)\"\n\tutime $dir/file2 > /dev/null || error \"utime (2)\"\n\tutime $dir/dir1 > /dev/null || error \"utime (3)\"\n\tutime $dir/dir2 > /dev/null || error \"utime (4)\"\n\tutime $dir/dir1/file1 > /dev/null || error \"utime (5)\"\n\tdd if=/dev/zero count=1 >> $dir/dir1/file1 && sync\n\n\tlocal expected=4\n\tlocal nums=$($LFS find -mtime +0 $dir | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"lfs find -mtime +0 $dir: found $nums expect $expected\"\n\n\texpected=12\n\tcmd=\"$LFS find -mtime 0 $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56o \"check lfs find -mtime for old files\"\n\ntest_56ob() {\n\tlocal dir=$DIR/$tdir\n\tlocal expected=1\n\tlocal count=0\n\n\t# just to make sure there is something that won't be found\n\ttest_mkdir $dir\n\ttouch $dir/$tfile.now\n\n\tfor age in year week day hour min; do\n\t\tcount=$((count + 1))\n\n\t\ttouch $dir/$tfile-a.$age $dir/$tfile-m.$age\n\t\ttouch --date=\"$count $age ago\" -a $dir/$tfile-a.$age\n\t\ttouch --date=\"$count $age ago\" -m $dir/$tfile-m.$age\n\n\t\tlocal cmd=\"$LFS find $dir -mtime $count${age:0:1}\"\n\t\tlocal nums=$($cmd | wc -l)\n\t\t[ $nums -eq $expected ] ||\n\t\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\t\tcmd=\"$LFS find $dir -atime $count${age:0:1}\"\n\t\tnums=$($cmd | wc -l)\n\t\t[ $nums -eq $expected ] ||\n\t\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tdone\n\n\tsleep 2\n\tcmd=\"$LFS find $dir -ctime +1s -type f\"\n\tnums=$($cmd | wc -l)\n\t(( $nums == $count * 2 + 1)) ||\n\t\terror \"'$cmd' wrong: found $nums, expected $((count * 2 + 1))\"\n}\nrun_test 56ob \"check lfs find -atime -mtime -ctime with units\"\n\ntest_newerXY_base() {\n\tlocal x=$1\n\tlocal y=$2\n\tlocal dir=$DIR/$tdir\n\tlocal ref\n\tlocal negref\n\n\tif [ $y == \"t\" ]; then\n\t\tif [ $x == \"b\" ]; then\n\t\t\tref=\"\\\"$(do_facet mds1 date +\"%Y-%m-%d\\ %H:%M:%S\")\\\"\"\n\t\telse\n\t\t\tref=\"\\\"$(date +\"%Y-%m-%d %H:%M:%S\")\\\"\"\n\t\tfi\n\telse\n\t\tref=$DIR/$tfile.newer.$x$y\n\t\ttouch $ref || error \"touch $ref failed\"\n\tfi\n\tsleep 2\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"-i0 -c1\" \"-i0 -c1\"\n\tsleep 2\n\tif [ $y == \"t\" ]; then\n\t\tif [ $x == \"b\" ]; then\n\t\t\tnegref=\"\\\"$(do_facet mds1 date +\"%Y-%m-%d\\ %H:%M:%S\")\\\"\"\n\t\telse\n\t\t\tnegref=\"\\\"$(date +\"%Y-%m-%d %H:%M:%S\")\\\"\"\n\t\tfi\n\telse\n\t\tnegref=$DIR/$tfile.negnewer.$x$y\n\t\ttouch $negref || error \"touch $negref failed\"\n\tfi\n\n\tlocal cmd=\"$LFS find $dir -newer$x$y $ref\"\n\tlocal nums=$(eval $cmd | wc -l)\n\tlocal expected=$(((NUMFILES + 2) * NUMDIRS + 1))\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find $dir ! -newer$x$y $negref\"\n\tnums=$(eval $cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find $dir -newer$x$y $ref ! -newer$x$y $negref\"\n\tnums=$(eval $cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\trm -rf $DIR/*\n}\n\ntest_56oc() {\n\ttest_newerXY_base \"b\" \"t\"\n\ttest_newerXY_base \"a\" \"a\"\n\ttest_newerXY_base \"a\" \"m\"\n\ttest_newerXY_base \"a\" \"c\"\n\ttest_newerXY_base \"m\" \"a\"\n\ttest_newerXY_base \"m\" \"m\"\n\ttest_newerXY_base \"m\" \"c\"\n\ttest_newerXY_base \"c\" \"a\"\n\ttest_newerXY_base \"c\" \"m\"\n\ttest_newerXY_base \"c\" \"c\"\n\ttest_newerXY_base \"b\" \"b\"\n\ttest_newerXY_base \"a\" \"t\"\n\ttest_newerXY_base \"m\" \"t\"\n\ttest_newerXY_base \"c\" \"t\"\n\ttest_newerXY_base \"b\" \"t\"\n}\nrun_test 56oc \"check lfs find -newerXY work\"\n\nbtime_supported() {\n\tlocal dir=$DIR/$tdir\n\tlocal rc\n\n\tmkdir -p $dir\n\ttouch $dir/$tfile\n\t$LFS find $dir -btime -1d -type f\n\trc=$?\n\trm -rf $dir\n\treturn $rc\n}\n\ntest_56od() {\n\t[ $MDS1_VERSION -lt $(version_code 2.13.53) ] &&\n\t\t! btime_supported && skip \"btime unsupported on MDS\"\n\n\t[ $CLIENT_VERSION -lt $(version_code 2.13.53) ] &&\n\t\t! btime_supported && skip \"btime unsupported on clients\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal ref=$DIR/$tfile.ref\n\tlocal negref=$DIR/$tfile.negref\n\n\tmkdir $dir || error \"mkdir $dir failed\"\n\ttouch $dir/$tfile.n1 || error \"touch $dir/$tfile.n1 failed\"\n\ttouch $dir/$tfile.n2 || error \"touch $dir/$tfile.n2 failed\"\n\tmkdir $dir/$tdir.n1 || error \"mkdir $dir/$tdir.n1 failed\"\n\tmkdir $dir/$tdir.n2 || error \"mkdir $dir/$tdir.n2 failed\"\n\ttouch $ref || error \"touch $ref failed\"\n\t# sleep 3 seconds at least\n\tsleep 3\n\n\tlocal before=$(do_facet mds1 date +%s)\n\tlocal skew=$(($(date +%s) - before + 1))\n\n\tif (( skew < 0 && skew > -5 )); then\n\t\tsleep $((0 - skew + 1))\n\t\tskew=0\n\tfi\n\n\t# Set the dir stripe params to limit files all on MDT0,\n\t# otherwise we need to calc the max clock skew between\n\t# the client and MDTs.\n\tsetup_56 $dir/d.btime $NUMFILES $NUMDIRS \"-i0 -c1\" \"-i0 -c1\"\n\tsleep 2\n\ttouch $negref || error \"touch $negref failed\"\n\n\tlocal cmd=\"$LFS find $dir -newerbb $ref ! -newerbb $negref -type f\"\n\tlocal nums=$($cmd | wc -l)\n\tlocal expected=$(((NUMFILES + 1) * NUMDIRS))\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find $dir -newerbb $ref ! -newerbb $negref -type d\"\n\tnums=$($cmd | wc -l)\n\texpected=$((NUMFILES + 1))\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\t[ $skew -lt 0 ] && return\n\n\tlocal after=$(do_facet mds1 date +%s)\n\tlocal age=$((after - before + 1 + skew))\n\n\tcmd=\"$LFS find $dir -btime -${age}s -type f\"\n\tnums=$($cmd | wc -l)\n\texpected=$(((NUMFILES + 1) * NUMDIRS))\n\n\techo \"Clock skew between client and server: $skew, age:$age\"\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=$(($NUMDIRS + 1))\n\tcmd=\"$LFS find $dir -btime -${age}s -type d\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\trm -f $ref $negref || error \"Failed to remove $ref $negref\"\n}\nrun_test 56od \"check lfs find -btime with units\"\n\ntest_56p() {\n\t[ $RUNAS_ID -eq $UID ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\tchown $RUNAS_ID $dir/file* || error \"chown $DIR/${tdir}g/file$i failed\"\n\n\tlocal expected=$NUMFILES\n\tlocal cmd=\"$LFS find -uid $RUNAS_ID $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=$(((NUMFILES + 1) * NUMDIRS + 1))\n\tcmd=\"$LFS find ! -uid $RUNAS_ID $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56p \"check lfs find -uid and ! -uid\"\n\ntest_56q() {\n\t[ $RUNAS_ID -eq $UID ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\tchgrp $RUNAS_GID $dir/file* || error \"chown $dir/file$i failed\"\n\n\tlocal expected=$NUMFILES\n\tlocal cmd=\"$LFS find -gid $RUNAS_GID $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=$(( ($NUMFILES+1) * $NUMDIRS + 1))\n\tcmd=\"$LFS find ! -gid $RUNAS_GID $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56q \"check lfs find -gid and ! -gid\"\n\ntest_56r() {\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\n\tlocal expected=12\n\tlocal cmd=\"$LFS find -size 0 -type f -lazy $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find -size 0 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=0\n\tcmd=\"$LFS find ! -size 0 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find ! -size 0 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\techo \"test\" > $dir/$tfile\n\techo \"test2\" > $dir/$tfile.2 && sync\n\texpected=1\n\tcmd=\"$LFS find -size 5 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find -size 5 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=1\n\tcmd=\"$LFS find -size +5 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find -size +5 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=2\n\tcmd=\"$LFS find -size +0 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find -size +0 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=2\n\tcmd=\"$LFS find ! -size -5 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find ! -size -5 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=12\n\tcmd=\"$LFS find -size -5 -type f -lazy $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tcmd=\"$LFS find -size -5 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56r \"check lfs find -size works\"\n\ntest_56ra_sub() {\n\tlocal expected=$1\n\tlocal glimpses=$2\n\tlocal cmd=\"$3\"\n\n\tcancel_lru_locks $OSC\n\n\tlocal rpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tlocal rpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\n\tif (( rpcs_before + glimpses != rpcs_after )); then\n\t\techo \"Before: $rpcs_before After: $rpcs_after $NUMFILES\"\n\t\t$LCTL get_param osc.*.stats | grep ldlm_glimpse_enqueue\n\n\t\tif [[ $glimpses == 0 ]]; then\n\t\t\terror \"'$cmd' should not send glimpse RPCs to OST\"\n\t\telse\n\t\t\terror \"'$cmd' should send $glimpses glimpse RPCs to OST\"\n\t\tfi\n\tfi\n}\n\ntest_56ra() {\n\t[[ $MDS1_VERSION -gt $(version_code 2.12.58) ]] ||\n\t\tskip \"MDS < 2.12.58 doesn't return LSOM data\"\n\tlocal dir=$DIR/$tdir\n\n\t[[ $OSC == \"mdc\" ]] && skip \"DoM files\" && return\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"-c 1\"\n\t# open and close all files to ensure LSOM is updated\n\tcancel_lru_locks $OSC\n\tfind $dir -type f | xargs cat > /dev/null\n\n\t#   expect_found  glimpse_rpcs  command_to_run\n\ttest_56ra_sub 12  0 \"$LFS find -size 0 -type f -lazy $dir\"\n\ttest_56ra_sub 12 12 \"$LFS find -size 0 -type f $dir\"\n\ttest_56ra_sub  0  0 \"$LFS find ! -size 0 -type f -lazy $dir\"\n\ttest_56ra_sub  0 12 \"$LFS find ! -size 0 -type f $dir\"\n\n\techo \"test\" > $dir/$tfile\n\techo \"test2\" > $dir/$tfile.2 && sync\n\tcancel_lru_locks $OSC\n\tcat $dir/$tfile $dir/$tfile.2 > /dev/null\n\n\ttest_56ra_sub  1  0 \"$LFS find -size 5 -type f -lazy $dir\"\n\ttest_56ra_sub  1 14 \"$LFS find -size 5 -type f $dir\"\n\ttest_56ra_sub  1  0 \"$LFS find -size +5 -type f -lazy $dir\"\n\ttest_56ra_sub  1 14 \"$LFS find -size +5 -type f $dir\"\n\n\ttest_56ra_sub  2  0 \"$LFS find -size +0 -type f -lazy $dir\"\n\ttest_56ra_sub  2 14 \"$LFS find -size +0 -type f $dir\"\n\ttest_56ra_sub  2  0 \"$LFS find ! -size -5 -type f -lazy $dir\"\n\ttest_56ra_sub  2 14 \"$LFS find ! -size -5 -type f $dir\"\n\ttest_56ra_sub 12  0 \"$LFS find -size -5 -type f -lazy $dir\"\n\ttest_56ra_sub 12 14 \"$LFS find -size -5 -type f $dir\"\n}\nrun_test 56ra \"check lfs find -size -lazy works for data on OSTs\"\n\ntest_56rb() {\n\tlocal dir=$DIR/$tdir\n\tlocal tmp=$TMP/$tfile.log\n\tlocal mdt_idx;\n\n\ttest_mkdir -p $dir || error \"failed to mkdir $dir\"\n\t$LFS setstripe -c 1 -i 0 $dir/$tfile ||\n\t\terror \"failed to setstripe $dir/$tfile\"\n\tmdt_idx=$($LFS getdirstripe -i $dir)\n\tdd if=/dev/zero of=$dir/$tfile bs=1M count=1\n\n\tstack_trap \"rm -f $tmp\" EXIT\n\t$LFS find --size +100K --ost 0 $dir |& tee $tmp\n\t! grep -q obd_uuid $tmp ||\n\t\terror \"failed to find --size +100K --ost 0 $dir\"\n\t$LFS find --size +100K --mdt $mdt_idx $dir |& tee $tmp\n\t! grep -q obd_uuid $tmp ||\n\t\terror \"failed to find --size +100K --mdt $mdt_idx $dir\"\n}\nrun_test 56rb \"check lfs find --size --ost/--mdt works\"\n\ntest_56s() { # LU-611 #LU-9369\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"need at least 2 OSTs\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal onestripe=$(((NUMDIRS + 1) * NUMFILES))\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"-c 1\"\n\tfor i in $(seq $NUMDIRS); do\n\t\t$LFS setstripe -c $((OSTCOUNT + 1)) $dir/dir$i/$tfile\n\tdone\n\n\tlocal expected=$NUMDIRS\n\tlocal cmd=\"$LFS find -c $OSTCOUNT $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n\n\texpected=$((NUMDIRS + onestripe))\n\tcmd=\"$LFS find -stripe-count +0 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n\n\texpected=$onestripe\n\tcmd=\"$LFS find -stripe-count 1 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n\n\tcmd=\"$LFS find -stripe-count -2 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n\n\texpected=0\n\tcmd=\"$LFS find -stripe-count $((OSTCOUNT + 1)) -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n}\nrun_test 56s \"check lfs find -stripe-count works\"\n\ntest_56t() { # LU-611 #LU-9369\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir 0 $NUMDIRS\n\tfor i in $(seq $NUMDIRS); do\n\t\t$LFS setstripe -S 8M $dir/dir$i/$tfile\n\tdone\n\n\tlocal expected=$NUMDIRS\n\tlocal cmd=\"$LFS find -S 8M $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] || {\n\t\t$LFS getstripe -R $dir\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\t}\n\trm -rf $dir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"--stripe-size 512k\"\n\n\t$LFS setstripe -S 256k $dir/$tfile.{0,1,2,3}\n\n\texpected=$(((NUMDIRS + 1) * NUMFILES))\n\tcmd=\"$LFS find -stripe-size 512k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find -stripe-size +320k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=$(((NUMDIRS + 1) * NUMFILES + 4))\n\tcmd=\"$LFS find -stripe-size +200k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find -stripe-size -640k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=4\n\tcmd=\"$LFS find -stripe-size 256k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find -stripe-size -320k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=0\n\tcmd=\"$LFS find -stripe-size 1024k -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n}\nrun_test 56t \"check lfs find -stripe-size works\"\n\ntest_56u() { # LU-611\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"-i 0 -c 1\"\n\n\tif [[ $OSTCOUNT -gt 1 ]]; then\n\t\t$LFS setstripe -i 1 -c 1 $dir/$tfile.{0,1,2,3}\n\t\tonestripe=4\n\telse\n\t\tonestripe=0\n\tfi\n\n\tlocal expected=$(((NUMDIRS + 1) * NUMFILES))\n\tlocal cmd=\"$LFS find -stripe-index 0 -type f $dir\"\n\tlocal nums=$($cmd | wc -l)\n\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=$onestripe\n\tcmd=\"$LFS find -stripe-index 1 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tcmd=\"$LFS find ! -stripe-index 0 -type f $dir\"\n\tnums=$($cmd | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\texpected=0\n\t# This should produce an error and not return any files\n\tcmd=\"$LFS find -stripe-index $OSTCOUNT -type f $dir\"\n\tnums=$($cmd 2>/dev/null | wc -l)\n\t[ $nums -eq $expected ] ||\n\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\n\tif [[ $OSTCOUNT -gt 1 ]]; then\n\t\texpected=$(((NUMDIRS + 1) * NUMFILES + onestripe))\n\t\tcmd=\"$LFS find -stripe-index 0,1 -type f $dir\"\n\t\tnums=$($cmd | wc -l)\n\t\t[ $nums -eq $expected ] ||\n\t\t\terror \"'$cmd' wrong: found $nums, expected $expected\"\n\tfi\n}\nrun_test 56u \"check lfs find -stripe-index works\"\n\ntest_56v() {\n\tlocal mdt_idx=0\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS\n\n\tUUID=$(mdtuuid_from_index $mdt_idx $dir)\n\t[ -z \"$UUID\" ] && error \"mdtuuid_from_index cannot find MDT $mdt_idx\"\n\n\tfor file in $($LFS find -m $UUID $dir); do\n\t\tfile_midx=$($LFS getstripe -m $file)\n\t\t[ $file_midx -eq $mdt_idx ] ||\n\t\t\terror \"lfs find -m $UUID != getstripe -m $file_midx\"\n\tdone\n}\nrun_test 56v \"check 'lfs find -m match with lfs getstripe -m'\"\n\ntest_56w() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir $NUMFILES $NUMDIRS \"-c $OSTCOUNT\" \"-c1\"\n\n\tlocal stripe_size=$($LFS getstripe -S -d $dir) ||\n\t\terror \"$LFS getstripe -S -d $dir failed\"\n\tstripe_size=${stripe_size%% *}\n\n\tlocal file_size=$((stripe_size * OSTCOUNT))\n\tlocal file_num=$((NUMDIRS * NUMFILES + NUMFILES))\n\tlocal required_space=$((file_num * file_size))\n\tlocal free_space=$($LCTL get_param -n lov.$FSNAME-clilov-*.kbytesavail |\n\t\t\t   head -n1)\n\t[[ $free_space -le $((required_space / 1024)) ]] &&\n\t\tskip_env \"need $required_space, have $free_space kbytes\"\n\n\tlocal dd_bs=65536\n\tlocal dd_count=$((file_size / dd_bs))\n\n\t# write data into the files\n\tlocal i\n\tlocal j\n\tlocal file\n\n\tfor i in $(seq $NUMFILES); do\n\t\tfile=$dir/file$i\n\t\tyes | dd bs=$dd_bs count=$dd_count of=$file &>/dev/null ||\n\t\t\terror \"write data into $file failed\"\n\tdone\n\tfor i in $(seq $NUMDIRS); do\n\t\tfor j in $(seq $NUMFILES); do\n\t\t\tfile=$dir/dir$i/file$j\n\t\t\tyes|dd bs=$dd_bs count=$dd_count of=$file &>/dev/null ||\n\t\t\t\terror \"write data into $file failed\"\n\t\tdone\n\tdone\n\n\t# $LFS_MIGRATE will fail if hard link migration is unsupported\n\tif [[ $MDS1_VERSION -gt $(version_code 2.5.55) ]]; then\n\t\tcreatemany -l$dir/dir1/file1 $dir/dir1/link 200 ||\n\t\t\terror \"creating links to $dir/dir1/file1 failed\"\n\tfi\n\n\tlocal expected=-1\n\n\t[[ $OSTCOUNT -gt 1 ]] && expected=$((OSTCOUNT - 1))\n\n\t# lfs_migrate file\n\tlocal cmd=\"$LFS_MIGRATE -y -c $expected $dir/file1\"\n\n\techo \"$cmd\"\n\teval $cmd || error \"$cmd failed\"\n\n\tcheck_stripe_count $dir/file1 $expected\n\n\tif [ $MDS1_VERSION -ge $(version_code 2.6.90) ];\n\tthen\n\t\t# lfs_migrate file onto OST 0 if it is on OST 1, or onto\n\t\t# OST 1 if it is on OST 0. This file is small enough to\n\t\t# be on only one stripe.\n\t\tfile=$dir/migr_1_ost\n\t\tdd bs=$dd_bs count=1 if=/dev/urandom of=$file >/dev/null 2>&1 ||\n\t\t\terror \"write data into $file failed\"\n\t\tlocal obdidx=$($LFS getstripe -i $file)\n\t\tlocal oldmd5=$(md5sum $file)\n\t\tlocal newobdidx=0\n\n\t\t[[ $obdidx -eq 0 ]] && newobdidx=1\n\t\tcmd=\"$LFS migrate -i $newobdidx $file\"\n\t\techo $cmd\n\t\teval $cmd || error \"$cmd failed\"\n\n\t\tlocal realobdix=$($LFS getstripe -i $file)\n\t\tlocal newmd5=$(md5sum $file)\n\n\t\t[[ $newobdidx -ne $realobdix ]] &&\n\t\t\terror \"new OST is different (was=$obdidx, \"\\\n\t\t\t      \"wanted=$newobdidx, got=$realobdix)\"\n\t\t[[ \"$oldmd5\" != \"$newmd5\" ]] &&\n\t\t\terror \"md5sum differ: $oldmd5, $newmd5\"\n\tfi\n\n\t# lfs_migrate dir\n\tcmd=\"$LFS_MIGRATE -y -c $expected $dir/dir1\"\n\techo \"$cmd\"\n\teval $cmd || error \"$cmd failed\"\n\n\tfor j in $(seq $NUMFILES); do\n\t\tcheck_stripe_count $dir/dir1/file$j $expected\n\tdone\n\n\t# lfs_migrate works with lfs find\n\tcmd=\"$LFS find -stripe_count $OSTCOUNT -type f $dir |\n\t     $LFS_MIGRATE -y -c $expected\"\n\techo \"$cmd\"\n\teval $cmd || error \"$cmd failed\"\n\n\tfor i in $(seq 2 $NUMFILES); do\n\t\tcheck_stripe_count $dir/file$i $expected\n\tdone\n\tfor i in $(seq 2 $NUMDIRS); do\n\t\tfor j in $(seq $NUMFILES); do\n\t\tcheck_stripe_count $dir/dir$i/file$j $expected\n\t\tdone\n\tdone\n}\nrun_test 56w \"check lfs_migrate -c stripe_count works\"\n\ntest_56wb() {\n\tlocal file1=$DIR/$tdir/file1\n\tlocal create_pool=false\n\tlocal initial_pool=$($LFS getstripe -p $DIR)\n\tlocal pool_list=()\n\tlocal pool=\"\"\n\n\techo -n \"Creating test dir...\"\n\ttest_mkdir $DIR/$tdir &> /dev/null || error \"cannot create dir\"\n\techo \"done.\"\n\n\techo -n \"Creating test file...\"\n\ttouch $file1 || error \"cannot create file\"\n\techo \"done.\"\n\n\techo -n \"Detecting existing pools...\"\n\tpool_list=($($LFS pool_list $FSNAME | grep \"$FSNAME\\.\" | cut -d. -f2))\n\n\tif [ ${#pool_list[@]} -gt 0 ]; then\n\t\techo \"${pool_list[@]}\"\n\t\tfor thispool in \"${pool_list[@]}\"; do\n\t\t\tif [[ -z \"$initial_pool\" ||\n\t\t\t      \"$initial_pool\" != \"$thispool\" ]]; then\n\t\t\t\tpool=\"$thispool\"\n\t\t\t\techo \"Using existing pool '$pool'\"\n\t\t\t\tbreak\n\t\t\tfi\n\t\tdone\n\telse\n\t\techo \"none detected.\"\n\tfi\n\tif [ -z \"$pool\" ]; then\n\t\tpool=${POOL:-testpool}\n\t\t[ \"$initial_pool\" = \"$pool\" ] && pool=\"testpool2\"\n\t\techo -n \"Creating pool '$pool'...\"\n\t\tcreate_pool=true\n\t\tpool_add $pool &> /dev/null ||\n\t\t\terror \"pool_add failed\"\n\t\techo \"done.\"\n\n\t\techo -n \"Adding target to pool...\"\n\t\tpool_add_targets $pool 0 0 1 &> /dev/null ||\n\t\t\terror \"pool_add_targets failed\"\n\t\techo \"done.\"\n\tfi\n\n\techo -n \"Setting pool using -p option...\"\n\t$LFS_MIGRATE -y -q --no-rsync -p $pool $file1 &> /dev/null ||\n\t\terror \"migrate failed rc = $?\"\n\techo \"done.\"\n\n\techo -n \"Verifying test file is in pool after migrating...\"\n\t[ \"$($LFS getstripe -p $file1)\" = $pool ] ||\n\t\terror \"file was not migrated to pool $pool\"\n\techo \"done.\"\n\n\techo -n \"Removing test file from pool '$pool'...\"\n\t# \"lfs migrate $file\" won't remove the file from the pool\n\t# until some striping information is changed.\n\t$LFS migrate -c 1 $file1 &> /dev/null ||\n\t\terror \"cannot remove from pool\"\n\t[ \"$($LFS getstripe -p $file1)\" ] &&\n\t\terror \"pool still set\"\n\techo \"done.\"\n\n\techo -n \"Setting pool using --pool option...\"\n\t$LFS_MIGRATE -y -q --no-rsync --pool $pool $file1 &> /dev/null ||\n\t\terror \"migrate failed rc = $?\"\n\techo \"done.\"\n\n\t# Clean up\n\trm -f $file1\n\tif $create_pool; then\n\t\tdestroy_test_pools 2> /dev/null ||\n\t\t\terror \"destroy test pools failed\"\n\tfi\n}\nrun_test 56wb \"check lfs_migrate pool support\"\n\ntest_56wc() {\n\tlocal file1=\"$DIR/$tdir/file1\"\n\tlocal parent_ssize\n\tlocal parent_scount\n\tlocal cur_ssize\n\tlocal cur_scount\n\tlocal orig_ssize\n\n\techo -n \"Creating test dir...\"\n\ttest_mkdir $DIR/$tdir &> /dev/null || error \"cannot create dir\"\n\t$LFS setstripe -S 1M -c 1 \"$DIR/$tdir\" &> /dev/null ||\n\t\terror \"cannot set stripe by '-S 1M -c 1'\"\n\techo \"done\"\n\n\techo -n \"Setting initial stripe for test file...\"\n\t$LFS setstripe -S 512K -c 1 \"$file1\" &> /dev/null ||\n\t\terror \"cannot set stripe\"\n\tcur_ssize=$($LFS getstripe -S \"$file1\")\n\t[ $cur_ssize -eq 524288 ] || error \"setstripe -S $cur_ssize != 524288\"\n\techo \"done.\"\n\n\t# File currently set to -S 512K -c 1\n\n\t# Ensure -c and -S options are rejected when -R is set\n\techo -n \"Verifying incompatible options are detected...\"\n\t$LFS_MIGRATE -y -R -c 1 \"$file1\" &> /dev/null &&\n\t\terror \"incompatible -c and -R options not detected\"\n\t$LFS_MIGRATE -y -R -S 1M \"$file1\" &> /dev/null &&\n\t\terror \"incompatible -S and -R options not detected\"\n\techo \"done.\"\n\n\t# Ensure unrecognized options are passed through to 'lfs migrate'\n\techo -n \"Verifying -S option is passed through to lfs migrate...\"\n\t$LFS_MIGRATE -y -S 1M \"$file1\" &> /dev/null ||\n\t\terror \"migration failed\"\n\tcur_ssize=$($LFS getstripe -S \"$file1\")\n\t[ $cur_ssize -eq 1048576 ] || error \"migrate -S $cur_ssize != 1048576\"\n\techo \"done.\"\n\n\t# File currently set to -S 1M -c 1\n\n\t# Ensure long options are supported\n\techo -n \"Verifying long options supported...\"\n\t$LFS_MIGRATE -y --non-block \"$file1\" &> /dev/null ||\n\t\terror \"long option without argument not supported\"\n\t$LFS_MIGRATE -y --stripe-size 512K \"$file1\" &> /dev/null ||\n\t\terror \"long option with argument not supported\"\n\tcur_ssize=$($LFS getstripe -S \"$file1\")\n\t[ $cur_ssize -eq 524288 ] ||\n\t\terror \"migrate --stripe-size $cur_ssize != 524288\"\n\techo \"done.\"\n\n\t# File currently set to -S 512K -c 1\n\n\tif [ \"$OSTCOUNT\" -gt 1 ]; then\n\t\techo -n \"Verifying explicit stripe count can be set...\"\n\t\t$LFS_MIGRATE -y -c 2 \"$file1\" &> /dev/null ||\n\t\t\terror \"migrate failed\"\n\t\tcur_scount=$($LFS getstripe -c \"$file1\")\n\t\t[ $cur_scount -eq 2 ] || error \"migrate -c $cur_scount != 2\"\n\t\techo \"done.\"\n\tfi\n\n\t# File currently set to -S 512K -c 1 or -S 512K -c 2\n\n\t# Ensure parent striping is used if -R is set, and no stripe\n\t# count or size is specified\n\techo -n \"Setting stripe for parent directory...\"\n\t$LFS setstripe -S 2M -c 1 \"$DIR/$tdir\" &> /dev/null ||\n\t\terror \"cannot set stripe '-S 2M -c 1'\"\n\techo \"done.\"\n\n\techo -n \"Verifying restripe option uses parent stripe settings...\"\n\tparent_ssize=$($LFS getstripe -S $DIR/$tdir 2>/dev/null)\n\tparent_scount=$($LFS getstripe -c $DIR/$tdir 2>/dev/null)\n\t$LFS_MIGRATE -y -R \"$file1\" &> /dev/null ||\n\t\terror \"migrate failed\"\n\tcur_ssize=$($LFS getstripe -S \"$file1\")\n\t[ $cur_ssize -eq $parent_ssize ] ||\n\t\terror \"migrate -R stripe_size $cur_ssize != $parent_ssize\"\n\tcur_scount=$($LFS getstripe -c \"$file1\")\n\t[ $cur_scount -eq $parent_scount ] ||\n\t\terror \"migrate -R stripe_count $cur_scount != $parent_scount\"\n\techo \"done.\"\n\n\t# File currently set to -S 1M -c 1\n\n\t# Ensure striping is preserved if -R is not set, and no stripe\n\t# count or size is specified\n\techo -n \"Verifying striping size preserved when not specified...\"\n\torig_ssize=$($LFS getstripe -S \"$file1\" 2>/dev/null)\n\t$LFS setstripe -S 2M -c 1 \"$DIR/$tdir\" &> /dev/null ||\n\t\terror \"cannot set stripe on parent directory\"\n\t$LFS_MIGRATE -y \"$file1\" &> /dev/null ||\n\t\terror \"migrate failed\"\n\tcur_ssize=$($LFS getstripe -S \"$file1\")\n\t[ $cur_ssize -eq $orig_ssize ] ||\n\t\terror \"migrate by default $cur_ssize != $orig_ssize\"\n\techo \"done.\"\n\n\t# Ensure file name properly detected when final option has no argument\n\techo -n \"Verifying file name properly detected...\"\n\t$LFS_MIGRATE -y \"$file1\" &> /dev/null ||\n\t\terror \"file name interpreted as option argument\"\n\techo \"done.\"\n\n\t# Clean up\n\trm -f \"$file1\"\n}\nrun_test 56wc \"check unrecognized options for lfs_migrate are passed through\"\n\ntest_56wd() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal file1=$DIR/$tdir/file1\n\n\techo -n \"Creating test dir...\"\n\ttest_mkdir $DIR/$tdir || error \"cannot create dir\"\n\techo \"done.\"\n\n\techo -n \"Creating test file...\"\n\ttouch $file1\n\techo \"done.\"\n\n\t# Ensure 'lfs migrate' will fail by using a non-existent option,\n\t# and make sure rsync is not called to recover\n\techo -n \"Make sure --no-rsync option works...\"\n\t$LFS_MIGRATE -y --no-rsync --invalid-opt $file1 2>&1 |\n\t\tgrep -q 'refusing to fall back to rsync' ||\n\t\terror \"rsync was called with --no-rsync set\"\n\techo \"done.\"\n\n\t# Ensure rsync is called without trying 'lfs migrate' first\n\techo -n \"Make sure --rsync option works...\"\n\t$LFS_MIGRATE -y --rsync --invalid-opt $file1 2>&1 |\n\t\tgrep -q 'falling back to rsync' &&\n\t\terror \"lfs migrate was called with --rsync set\"\n\techo \"done.\"\n\n\techo -n \"Make sure --rsync and --no-rsync options are exclusive...\"\n\t$LFS_MIGRATE -y --rsync --no-rsync $file1 2>&1 |\n\t\tgrep -q 'at the same time' ||\n\t\terror \"--rsync and --no-rsync accepted concurrently\"\n\techo \"done.\"\n\n\t# Clean up\n\trm -f $file1\n}\nrun_test 56wd \"check lfs_migrate --rsync and --no-rsync work\"\n\ntest_56we() {\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\n\ttest_mkdir $td || error \"cannot create $td\"\n\ttouch $tf || error \"cannot touch $tf\"\n\n\techo -n \"Make sure --non-direct|-D works...\"\n\t$LFS_MIGRATE -y --non-direct -v $tf 2>&1 |\n\t\tgrep -q \"lfs migrate --non-direct\" ||\n\t\terror \"--non-direct option cannot work correctly\"\n\t$LFS_MIGRATE -y -D -v $tf 2>&1 |\n\t\tgrep -q \"lfs migrate -D\" ||\n\t\terror \"-D option cannot work correctly\"\n\techo \"done.\"\n}\nrun_test 56we \"check lfs_migrate --non-direct|-D support\"\n\ntest_56x() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tcheck_swap_layouts_support\n\n\tlocal dir=$DIR/$tdir\n\tlocal ref1=/etc/passwd\n\tlocal file1=$dir/file1\n\n\ttest_mkdir $dir || error \"creating dir $dir\"\n\t$LFS setstripe -c 2 $file1\n\tcp $ref1 $file1\n\t$LFS migrate -c 1 $file1 || error \"migrate failed rc = $?\"\n\tstripe=$($LFS getstripe -c $file1)\n\t[[ $stripe == 1 ]] || error \"stripe of $file1 is $stripe != 1\"\n\tcmp $file1 $ref1 || error \"content mismatch $file1 differs from $ref1\"\n\n\t# clean up\n\trm -f $file1\n}\nrun_test 56x \"lfs migration support\"\n\ntest_56xa() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tcheck_swap_layouts_support\n\n\tlocal dir=$DIR/$tdir/$testnum\n\n\ttest_mkdir -p $dir\n\n\tlocal ref1=/etc/passwd\n\tlocal file1=$dir/file1\n\n\t$LFS setstripe -c 2 $file1\n\tcp $ref1 $file1\n\t$LFS migrate --block -c 1 $file1 || error \"migrate failed rc = $?\"\n\n\tlocal stripe=$($LFS getstripe -c $file1)\n\n\t[[ $stripe == 1 ]] || error \"stripe of $file1 is $stripe != 1\"\n\tcmp $file1 $ref1 || error \"content mismatch $file1 differs from $ref1\"\n\n\t# clean up\n\trm -f $file1\n}\nrun_test 56xa \"lfs migration --block support\"\n\ncheck_migrate_links() {\n\tlocal dir=\"$1\"\n\tlocal file1=\"$dir/file1\"\n\tlocal begin=\"$2\"\n\tlocal count=\"$3\"\n\tlocal runas=\"$4\"\n\tlocal total_count=$(($begin + $count - 1))\n\tlocal symlink_count=10\n\tlocal uniq_count=10\n\n\tif [ ! -f \"$file1\" ]; then\n\t\techo -n \"creating initial file...\"\n\t\t$LFS setstripe -c 1 -S \"512k\" \"$file1\" ||\n\t\t\terror \"cannot setstripe initial file\"\n\t\techo \"done\"\n\n\t\techo -n \"creating symlinks...\"\n\t\tfor s in $(seq 1 $symlink_count); do\n\t\t\tln -s \"$file1\" \"$dir/slink$s\" ||\n\t\t\t\terror \"cannot create symlinks\"\n\t\tdone\n\t\techo \"done\"\n\n\t\techo -n \"creating nonlinked files...\"\n\t\tcreatemany -o \"$dir/uniq\" 1 10 &> /dev/null ||\n\t\t\terror \"cannot create nonlinked files\"\n\t\techo \"done\"\n\tfi\n\n\t# create hard links\n\tif [ ! -f \"$dir/file$total_count\" ]; then\n\t\techo -n \"creating hard links $begin:$total_count...\"\n\t\tcreatemany -l\"$file1\" \"$dir/file\" \"$begin\" \"$count\" &>\t\\\n\t\t\t/dev/null || error \"cannot create hard links\"\n\t\techo \"done\"\n\tfi\n\n\techo -n \"checking number of hard links listed in xattrs...\"\n\tlocal fid=$($LFS getstripe -F \"$file1\")\n\tlocal paths=($($LFS fid2path \"$MOUNT\" \"$fid\" 2> /dev/null))\n\n\techo \"${#paths[*]}\"\n\tif [ ${#paths[*]} -lt $total_count -a \"$begin\" -eq 2  ]; then\n\t\t\tskip \"hard link list has unexpected size, skipping test\"\n\tfi\n\tif [ ${#paths[*]} -ge $total_count -a \"$begin\" -ne 2  ]; then\n\t\t\terror \"link names should exceed xattrs size\"\n\tfi\n\n\techo -n \"migrating files...\"\n\tlocal migrate_out=$($runas $LFS_MIGRATE -y -S '1m' $dir)\n\tlocal rc=$?\n\t[ $rc -eq 0 ] || error \"migrate failed rc = $rc\"\n\techo \"done\"\n\n\t# make sure all links have been properly migrated\n\techo -n \"verifying files...\"\n\tfid=$($LFS getstripe -F \"$file1\") ||\n\t\terror \"cannot get fid for file $file1\"\n\tfor i in $(seq 2 $total_count); do\n\t\tlocal fid2=$($LFS getstripe -F $dir/file$i)\n\n\t\t[ \"$fid2\" == \"$fid\" ] ||\n\t\t\terror \"migrated hard link has mismatched FID\"\n\tdone\n\n\t# make sure hard links were properly detected, and migration was\n\t# performed only once for the entire link set; nonlinked files should\n\t# also be migrated\n\tlocal actual=$(grep -c 'done' <<< \"$migrate_out\")\n\tlocal expected=$(($uniq_count + 1))\n\n\t[ \"$actual\" -eq  \"$expected\" ] ||\n\t\terror \"hard links individually migrated ($actual != $expected)\"\n\n\t# make sure the correct number of hard links are present\n\tlocal hardlinks=$(stat -c '%h' \"$file1\")\n\n\t[ $hardlinks -eq $total_count ] ||\n\t\terror \"num hard links $hardlinks != $total_count\"\n\techo \"done\"\n\n\treturn 0\n}\n\ntest_56xb() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dir=\"$DIR/$tdir\"\n\n\ttest_mkdir \"$dir\" || error \"cannot create dir $dir\"\n\n\techo \"testing lfs migrate mode when all links fit within xattrs\"\n\tLFS_MIGRATE_RSYNC_MODE=false check_migrate_links \"$dir\" 2 99\n\n\techo \"testing rsync mode when all links fit within xattrs\"\n\tLFS_MIGRATE_RSYNC_MODE=true check_migrate_links \"$dir\" 2 99\n\n\techo \"testing lfs migrate mode when all links do not fit within xattrs\"\n\tLFS_MIGRATE_RSYNC_MODE=false check_migrate_links \"$dir\" 101 100\n\n\techo \"testing rsync mode when all links do not fit within xattrs\"\n\tLFS_MIGRATE_RSYNC_MODE=true check_migrate_links \"$dir\" 101 100\n\n\tchown -R $RUNAS_ID $dir\n\techo \"testing non-root lfs migrate mode when not all links are in xattr\"\n\tLFS_MIGRATE_RSYNC_MODE=false check_migrate_links \"$dir\" 101 100 \"$RUNAS\"\n\n\t# clean up\n\trm -rf $dir\n}\nrun_test 56xb \"lfs migration hard link support\"\n\ntest_56xc() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal dir=\"$DIR/$tdir\"\n\n\ttest_mkdir \"$dir\" || error \"cannot create dir $dir\"\n\n\t# Test 1: ensure file < 1 GB is always migrated with 1 stripe\n\techo -n \"Setting initial stripe for 20MB test file...\"\n\t$LFS setstripe -c 2 -i 0 \"$dir/20mb\" ||\n\t\terror \"cannot setstripe 20MB file\"\n\techo \"done\"\n\techo -n \"Sizing 20MB test file...\"\n\ttruncate \"$dir/20mb\" 20971520 || error \"cannot create 20MB test file\"\n\techo \"done\"\n\techo -n \"Verifying small file autostripe count is 1...\"\n\t$LFS_MIGRATE -y -A -C 1 \"$dir/20mb\" ||\n\t\terror \"cannot migrate 20MB file\"\n\tlocal stripe_count=$($LFS getstripe -c \"$dir/20mb\") ||\n\t\terror \"cannot get stripe for $dir/20mb\"\n\t[ $stripe_count -eq 1 ] ||\n\t\terror \"unexpected stripe count $stripe_count for 20MB file\"\n\trm -f \"$dir/20mb\"\n\techo \"done\"\n\n\t# Test 2: File is small enough to fit within the available space on\n\t# sqrt(size_in_gb) + 1 OSTs but is larger than 1GB.  The file must\n\t# have at least an additional 1KB for each desired stripe for test 3\n\techo -n \"Setting stripe for 1GB test file...\"\n\t$LFS setstripe -c 1 -i 0 \"$dir/1gb\" || error \"cannot setstripe 1GB file\"\n\techo \"done\"\n\techo -n \"Sizing 1GB test file...\"\n\t# File size is 1GB + 3KB\n\ttruncate \"$dir/1gb\" 1073744896 || error \"cannot create 1GB test file\"\n\techo \"done\"\n\n\t# need at least 512MB per OST for 1GB file to fit in 2 stripes\n\tlocal avail=$($LCTL get_param -n llite.$FSNAME*.kbytesavail)\n\tif (( avail > 524288 * OSTCOUNT )); then\n\t\techo -n \"Migrating 1GB file...\"\n\t\t$LFS_MIGRATE -y -A -C 1 \"$dir/1gb\" ||\n\t\t\terror \"cannot migrate 1GB file\"\n\t\techo \"done\"\n\t\techo -n \"Verifying autostripe count is sqrt(n) + 1...\"\n\t\tstripe_count=$($LFS getstripe -c \"$dir/1gb\") ||\n\t\t\terror \"cannot getstripe for 1GB file\"\n\t\t[ $stripe_count -eq 2 ] ||\n\t\t\terror \"unexpected stripe count $stripe_count != 2\"\n\t\techo \"done\"\n\tfi\n\n\t# Test 3: File is too large to fit within the available space on\n\t# sqrt(n) + 1 OSTs.  Simulate limited available space with -X\n\tif [ $OSTCOUNT -ge 3 ]; then\n\t\t# The required available space is calculated as\n\t\t# file size (1GB + 3KB) / OST count (3).\n\t\tlocal kb_per_ost=349526\n\n\t\techo -n \"Migrating 1GB file with limit...\"\n\t\t$LFS_MIGRATE -y -A -C 1 -X $kb_per_ost \"$dir/1gb\" ||\n\t\t\terror \"cannot migrate 1GB file with limit\"\n\t\techo \"done\"\n\n\t\tstripe_count=$($LFS getstripe -c \"$dir/1gb\")\n\t\techo -n \"Verifying 1GB autostripe count with limited space...\"\n\t\t[ \"$stripe_count\" -a $stripe_count -ge 3 ] ||\n\t\t\terror \"unexpected stripe count $stripe_count (min 3)\"\n\t\techo \"done\"\n\tfi\n\n\t# clean up\n\trm -rf $dir\n}\nrun_test 56xc \"lfs migration autostripe\"\n\ntest_56xd() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal f_mgrt=$dir/$tfile.mgrt\n\tlocal f_yaml=$dir/$tfile.yaml\n\tlocal f_copy=$dir/$tfile.copy\n\tlocal layout_yaml=\"-E 1M -S 512K -c 1 -E -1 -S 1M -c 2 -i 0\"\n\tlocal layout_copy=\"-c 2 -S 2M -i 1\"\n\tlocal yamlfile=$dir/yamlfile\n\tlocal layout_before;\n\tlocal layout_after;\n\n\ttest_mkdir \"$dir\" || error \"cannot create dir $dir\"\n\t$LFS setstripe $layout_yaml $f_yaml ||\n\t\terror \"cannot setstripe $f_yaml with layout $layout_yaml\"\n\t$LFS getstripe --yaml $f_yaml > $yamlfile\n\t$LFS setstripe $layout_copy $f_copy ||\n\t\terror \"cannot setstripe $f_copy with layout $layout_copy\"\n\ttouch $f_mgrt\n\tdd if=/dev/zero of=$f_mgrt bs=1M count=4\n\n\t# 1. test option --yaml\n\t$LFS_MIGRATE -y --yaml $yamlfile $f_mgrt ||\n\t\terror \"cannot migrate $f_mgrt with --yaml $yamlfile\"\n\tlayout_before=$(get_layout_param $f_yaml)\n\tlayout_after=$(get_layout_param $f_mgrt)\n\t[ \"$layout_after\" == \"$layout_before\" ] ||\n\t\terror \"lfs_migrate --yaml: $layout_after != $layout_before\"\n\n\t# 2. test option --copy\n\t$LFS_MIGRATE -y --copy $f_copy $f_mgrt ||\n\t\terror \"cannot migrate $f_mgrt with --copy $f_copy\"\n\tlayout_before=$(get_layout_param $f_copy)\n\tlayout_after=$(get_layout_param $f_mgrt)\n\t[ \"$layout_after\" == \"$layout_before\" ] ||\n\t\terror \"lfs_migrate --copy: $layout_after != $layout_before\"\n}\nrun_test 56xd \"check lfs_migrate --yaml and --copy support\"\n\ntest_56xe() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal f_comp=$dir/$tfile\n\tlocal layout=\"-E 1M -S 512K -c 1 -E -1 -S 1M -c 2 -i 0\"\n\tlocal layout_before=\"\"\n\tlocal layout_after=\"\"\n\n\ttest_mkdir \"$dir\" || error \"cannot create dir $dir\"\n\t$LFS setstripe $layout $f_comp ||\n\t\terror \"cannot setstripe $f_comp with layout $layout\"\n\tlayout_before=$(get_layout_param $f_comp)\n\tdd if=/dev/zero of=$f_comp bs=1M count=4\n\n\t# 1. migrate a comp layout file by lfs_migrate\n\t$LFS_MIGRATE -y $f_comp || error \"cannot migrate $f_comp by lfs_migrate\"\n\tlayout_after=$(get_layout_param $f_comp)\n\t[ \"$layout_before\" == \"$layout_after\" ] ||\n\t\terror \"lfs_migrate: $layout_before != $layout_after\"\n\n\t# 2. migrate a comp layout file by lfs migrate\n\t$LFS migrate $f_comp || error \"cannot migrate $f_comp by lfs migrate\"\n\tlayout_after=$(get_layout_param $f_comp)\n\t[ \"$layout_before\" == \"$layout_after\" ] ||\n\t\terror \"lfs migrate: $layout_before != $layout_after\"\n}\nrun_test 56xe \"migrate a composite layout file\"\n\ntest_56xf() {\n\t[[ $OSTCOUNT -ge 2 ]] || skip_env \"needs >= 2 OSTs\"\n\n\t[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||\n\t\tskip \"Need server version at least 2.13.53\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal f_comp=$dir/$tfile\n\tlocal layout=\"-E 1M -c1 -E -1 -c2\"\n\tlocal fid_before=\"\"\n\tlocal fid_after=\"\"\n\n\ttest_mkdir \"$dir\" || error \"cannot create dir $dir\"\n\t$LFS setstripe $layout $f_comp ||\n\t\terror \"cannot setstripe $f_comp with layout $layout\"\n\tfid_before=$($LFS getstripe --fid $f_comp)\n\tdd if=/dev/zero of=$f_comp bs=1M count=4\n\n\t# 1. migrate a comp layout file to a comp layout\n\t$LFS migrate $f_comp || error \"cannot migrate $f_comp by lfs migrate\"\n\tfid_after=$($LFS getstripe --fid $f_comp)\n\t[ \"$fid_before\" == \"$fid_after\" ] ||\n\t\terror \"comp-to-comp migrate: $fid_before != $fid_after\"\n\n\t# 2. migrate a comp layout file to a plain layout\n\t$LFS migrate -c2 $f_comp ||\n\t\terror \"cannot migrate $f_comp by lfs migrate\"\n\tfid_after=$($LFS getstripe --fid $f_comp)\n\t[ \"$fid_before\" == \"$fid_after\" ] ||\n\t\terror \"comp-to-plain migrate: $fid_before != $fid_after\"\n\n\t# 3. migrate a plain layout file to a comp layout\n\t$LFS migrate $layout $f_comp ||\n\t\terror \"cannot migrate $f_comp by lfs migrate\"\n\tfid_after=$($LFS getstripe --fid $f_comp)\n\t[ \"$fid_before\" == \"$fid_after\" ] ||\n\t\terror \"plain-to-comp migrate: $fid_before != $fid_after\"\n}\nrun_test 56xf \"FID is not lost during migration of a composite layout file\"\n\ntest_56y() {\n\t[ $MDS1_VERSION -lt $(version_code 2.4.53) ] &&\n\t\tskip \"No HSM $(lustre_build_version $SINGLEMDS) MDS < 2.4.53\"\n\n\tlocal res=\"\"\n\tlocal dir=$DIR/$tdir\n\tlocal f1=$dir/file1\n\tlocal f2=$dir/file2\n\n\ttest_mkdir -p $dir || error \"creating dir $dir\"\n\ttouch $f1 || error \"creating std file $f1\"\n\t$MULTIOP $f2 H2c || error \"creating released file $f2\"\n\n\t# a directory can be raid0, so ask only for files\n\tres=$($LFS find $dir -L raid0 -type f | wc -l)\n\t[[ $res == 2 ]] || error \"search raid0: found $res files != 2\"\n\n\tres=$($LFS find $dir \\! -L raid0 -type f | wc -l)\n\t[[ $res == 0 ]] || error \"search !raid0: found $res files != 0\"\n\n\t# only files can be released, so no need to force file search\n\tres=$($LFS find $dir -L released)\n\t[[ $res == $f2 ]] || error \"search released: found $res != $f2\"\n\n\tres=$($LFS find $dir -type f \\! -L released)\n\t[[ $res == $f1 ]] || error \"search !released: found $res != $f1\"\n}\nrun_test 56y \"lfs find -L raid0|released\"\n\ntest_56z() { # LU-4824\n\t# This checks to make sure 'lfs find' continues after errors\n\t# There are two classes of errors that should be caught:\n\t# - If multiple paths are provided, all should be searched even if one\n\t#   errors out\n\t# - If errors are encountered during the search, it should not terminate\n\t#   early\n\tlocal dir=$DIR/$tdir\n\tlocal i\n\n\ttest_mkdir $dir\n\tfor i in d{0..9}; do\n\t\ttest_mkdir $dir/$i\n\t\ttouch $dir/$i/$tfile\n\tdone\n\t$LFS find $DIR/non_existent_dir $dir &&\n\t\terror \"$LFS find did not return an error\"\n\t# Make a directory unsearchable. This should NOT be the last entry in\n\t# directory order.  Arbitrarily pick the 6th entry\n\tchmod 700 $($LFS find $dir -type d | sed '6!d')\n\n\t$RUNAS $LFS find $DIR/non_existent $dir\n\tlocal count=$($RUNAS $LFS find $DIR/non_existent $dir | wc -l)\n\n\t# The user should be able to see 10 directories and 9 files\n\t(( count == 19 )) ||\n\t\terror \"$LFS find found $count != 19 entries after error\"\n}\nrun_test 56z \"lfs find should continue after an error\"\n\ntest_56aa() { # LU-5937\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal dir=$DIR/$tdir\n\n\tmkdir $dir\n\t$LFS setdirstripe -c$MDSCOUNT $dir/striped_dir\n\n\tcreatemany -o $dir/striped_dir/${tfile}- 1024\n\tlocal dirs=$($LFS find --size +8k $dir/)\n\n\t[ -n \"$dirs\" ] || error \"lfs find --size wrong under striped dir\"\n}\nrun_test 56aa \"lfs find --size under striped dir\"\n\ntest_56ab() { # LU-10705\n\ttest_mkdir $DIR/$tdir\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.1 bs=8k count=1 seek=2k\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.2 bs=4k count=1 seek=4k\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.3 bs=1M count=2 seek=16\n\t# Flush writes to ensure valid blocks.  Need to be more thorough for\n\t# ZFS, since blocks are not allocated/returned to client immediately.\n\tsync_all_data\n\twait_zfs_commit ost1 2\n\tcancel_lru_locks osc\n\tls -ls $DIR/$tdir\n\n\tlocal files=$($LFS find --size +16M $DIR/$tdir | wc -l)\n\n\t[[ $files == 3 ]] || error \">16M size files $files isn't 3 as expected\"\n\n\tfiles=$($LFS find --blocks +1M $DIR/$tdir | wc -l)\n\t[[ $files == 1 ]] || error \">1M blocks files $files isn't 1 as expected\"\n\n\trm -f $DIR/$tdir/$tfile.[123]\n}\nrun_test 56ab \"lfs find --blocks\"\n\ntest_56ba() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.50) ] &&\n\t\tskip \"Need MDS version at least 2.10.50\"\n\n\t# Create composite files with one component\n\tlocal dir=$DIR/$tdir\n\n\tsetup_56 $dir/1Mfiles 5 1 \"-S 1M --component-end 1M\"\n\t# Create composite files with three components\n\tsetup_56 $dir/2Mfiles 5 2 \"-E 2M -S 1M -E 4M -E 6M\"\n\t# Create non-composite files\n\tcreatemany -o $dir/${tfile}- 10\n\n\tlocal nfiles=$($LFS find --component-end 1M --type f $dir | wc -l)\n\n\t[[ $nfiles == 10 ]] ||\n\t\terror \"lfs find -E 1M found $nfiles != 10 files\"\n\n\tnfiles=$($LFS find ! -E 1M --type f $dir | wc -l)\n\t[[ $nfiles == 25 ]] ||\n\t\terror \"lfs find ! -E 1M found $nfiles != 25 files\"\n\n\t# All files have a component that starts at 0\n\tnfiles=$($LFS find --component-start 0 --type f $dir | wc -l)\n\t[[ $nfiles == 35 ]] ||\n\t\terror \"lfs find --component-start 0 - $nfiles != 35 files\"\n\n\tnfiles=$($LFS find --component-start 2M --type f $dir | wc -l)\n\t[[ $nfiles == 15 ]] ||\n\t\terror \"lfs find --component-start 2M - $nfiles != 15 files\"\n\n\t# All files created here have a componenet that does not starts at 2M\n\tnfiles=$($LFS find ! --component-start 2M --type f $dir | wc -l)\n\t[[ $nfiles == 35 ]] ||\n\t\terror \"lfs find ! --component-start 2M - $nfiles != 35 files\"\n\n\t# Find files with a specified number of components\n\tlocal nfiles=$($LFS find --component-count 3 --type f $dir | wc -l)\n\t[[ $nfiles == 15 ]] ||\n\t\terror \"lfs find --component-count 3 - $nfiles != 15 files\"\n\n\t# Remember non-composite files have a component count of zero\n\tlocal nfiles=$($LFS find --component-count 0 --type f $dir | wc -l)\n\t[[ $nfiles == 10 ]] ||\n\t\terror \"lfs find --component-count 0 - $nfiles != 10 files\"\n\n\tnfiles=$($LFS find ! --component-count 3 --type f $dir | wc -l)\n\t[[ $nfiles == 20 ]] ||\n\t\terror \"lfs find ! --component-count 3 - $nfiles != 20 files\"\n\n\t# All files have a flag called \"init\"\n\tlocal nfiles=$($LFS find --component-flags init --type f $dir | wc -l)\n\t[[ $nfiles == 35 ]] ||\n\t\terror \"lfs find --component-flags init - $nfiles != 35 files\"\n\n\t# Multi-component files will have a component not initialized\n\tlocal nfiles=$($LFS find ! --component-flags init --type f $dir | wc -l)\n\t[[ $nfiles == 15 ]] ||\n\t\terror \"lfs find !--component-flags init - $nfiles != 15 files\"\n\n\trm -rf $dir\n\n}\nrun_test 56ba \"test lfs find --component-end, -start, -count, and -flags\"\n\ntest_56ca() {\n\t[[ $MDS1_VERSION -ge $(version_code 2.10.57) ]] ||\n\t\tskip \"Need MDS version at least 2.10.57\"\n\n\tlocal td=$DIR/$tdir\n\tlocal tf=$td/$tfile\n\tlocal dir\n\tlocal nfiles\n\tlocal cmd\n\tlocal i\n\tlocal j\n\n\t# create mirrored directories and mirrored files\n\tmkdir $td || error \"mkdir $td failed\"\n\t$LFS mirror create -N3 $td || error \"create mirrored dir $td failed\"\n\tcreatemany -o $tf- 10 || error \"create $tf- failed\"\n\n\tfor i in $(seq 2); do\n\t\tdir=$td/dir$i\n\t\tmkdir $dir || error \"mkdir $dir failed\"\n\t\t$LFS mirror create -N$((3 + i)) $dir ||\n\t\t\terror \"create mirrored dir $dir failed\"\n\t\tcreatemany -o $dir/$tfile- 10 ||\n\t\t\terror \"create $dir/$tfile- failed\"\n\tdone\n\n\t# change the states of some mirrored files\n\techo foo > $tf-6\n\tfor i in $(seq 2); do\n\t\tdir=$td/dir$i\n\t\tfor j in $(seq 4 9); do\n\t\t\techo foo > $dir/$tfile-$j\n\t\tdone\n\tdone\n\n\t# find mirrored files with specific mirror count\n\tcmd=\"$LFS find --mirror-count 3 --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 10 ]] || error \"$cmd: $nfiles != 10 files\"\n\n\tcmd=\"$LFS find ! --mirror-count 3 --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 20 ]] || error \"$cmd: $nfiles != 20 files\"\n\n\tcmd=\"$LFS find --mirror-count +2 --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 30 ]] || error \"$cmd: $nfiles != 30 files\"\n\n\tcmd=\"$LFS find --mirror-count -6 --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 30 ]] || error \"$cmd: $nfiles != 30 files\"\n\n\t# find mirrored files with specific file state\n\tcmd=\"$LFS find --maxdepth 1 --mirror-state=^ro --type f $td\"\n\t[[ $($cmd) = $tf-6 ]] || error \"$cmd: didn't return $tf-6\"\n\n\tcmd=\"$LFS find --mirror-state=ro --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 17 ]] || error \"$cmd: $nfiles != 17 files\"\n\n\tcmd=\"$LFS find ! --mirror-state=ro --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 13 ]] || error \"$cmd: $nfiles != 13 files\"\n\n\tcmd=\"$LFS find --mirror-state=wp --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 13 ]] || error \"$cmd: $nfiles != 13 files\"\n\n\tcmd=\"$LFS find ! --mirror-state=sp --type f $td\"\n\tnfiles=$($cmd | wc -l)\n\t[[ $nfiles = 30 ]] || error \"$cmd: $nfiles != 30 files\"\n}\nrun_test 56ca \"check lfs find --mirror-count|-N and --mirror-state\"\n\ntest_57a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t# note test will not do anything if MDS is not local\n\tif [ \"$mds1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal MNTDEV=\"osd*.*MDT*.mntdev\"\n\tDEV=$(do_facet $SINGLEMDS lctl get_param -n $MNTDEV)\n\t[ -z \"$DEV\" ] && error \"can't access $MNTDEV\"\n\tfor DEV in $(do_facet $SINGLEMDS lctl get_param -n $MNTDEV); do\n\t\tdo_facet $SINGLEMDS $DUMPE2FS -h $DEV > $TMP/t57a.dump ||\n\t\t\terror \"can't access $DEV\"\n\t\tDEVISIZE=$(awk '/Inode size:/ { print $3 }' $TMP/t57a.dump)\n\t\t[[ $DEVISIZE -gt 128 ]] || error \"inode size $DEVISIZE\"\n\t\trm $TMP/t57a.dump\n\tdone\n}\nrun_test 57a \"verify MDS filesystem created with large inodes ==\"\n\ntest_57b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tif [ \"$mds1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal filecount=100\n\tlocal file1=$dir/f1\n\tlocal fileN=$dir/f$filecount\n\n\trm -rf $dir || error \"removing $dir\"\n\ttest_mkdir -c1 $dir\n\tlocal mdtidx=$($LFS getstripe -m $dir)\n\tlocal mdtname=MDT$(printf %04x $mdtidx)\n\tlocal facet=mds$((mdtidx + 1))\n\n\techo \"mcreating $filecount files\"\n\tcreatemany -m $dir/f 1 $filecount || error \"creating files in $dir\"\n\n\t# verify that files do not have EAs yet\n\t$LFS getstripe $file1 2>&1 | grep -q \"no stripe\" ||\n\t\terror \"$file1 has an EA\"\n\t$LFS getstripe $fileN 2>&1 | grep -q \"no stripe\" ||\n\t\terror \"$fileN has an EA\"\n\n\tsync\n\tsleep 1\n\tdf $dir  #make sure we get new statfs data\n\tlocal mdsfree=$(do_facet $facet \\\n\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\tlocal mdcfree=$(lctl get_param -n mdc.*$mdtname-mdc-*.kbytesfree)\n\tlocal file\n\n\techo \"opening files to create objects/EAs\"\n\tfor file in $(seq -f $dir/f%g 1 $filecount); do\n\t\t$OPENFILE -f O_RDWR $file > /dev/null 2>&1 ||\n\t\t\terror \"opening $file\"\n\tdone\n\n\t# verify that files have EAs now\n\t$LFS getstripe $file1 | grep -q \"obdidx\" || error \"$file1 missing EA\"\n\t$LFS getstripe $fileN | grep -q \"obdidx\" || error \"$fileN missing EA\"\n\n\tsleep 1  #make sure we get new statfs data\n\tdf $dir\n\tlocal mdsfree2=$(do_facet $facet \\\n\t\t\t lctl get_param -n osd*.*$mdtname.kbytesfree)\n\tlocal mdcfree2=$(lctl get_param -n mdc.*$mdtname-mdc-*.kbytesfree)\n\n\tif [[ $mdcfree2 -lt $((mdcfree - 16)) ]]; then\n\t\tif [ \"$mdsfree\" != \"$mdsfree2\" ]; then\n\t\t\terror \"MDC before $mdcfree != after $mdcfree2\"\n\t\telse\n\t\t\techo \"MDC before $mdcfree != after $mdcfree2\"\n\t\t\techo \"unable to confirm if MDS has large inodes\"\n\t\tfi\n\tfi\n\trm -rf $dir\n}\nrun_test 57b \"default LOV EAs are stored inside large inodes ===\"\n\ntest_58() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ -z \"$(which wiretest 2>/dev/null)\" ] &&\n\t\t\tskip_env \"could not find wiretest\"\n\n\twiretest\n}\nrun_test 58 \"verify cross-platform wire constants ==============\"\n\ntest_59() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\techo \"touch 130 files\"\n\tcreatemany -o $DIR/f59- 130\n\techo \"rm 130 files\"\n\tunlinkmany $DIR/f59- 130\n\tsync\n\t# wait for commitment of removal\n\twait_delete_completed\n}\nrun_test 59 \"verify cancellation of llog records async =========\"\n\nTEST60_HEAD=\"test_60 run $RANDOM\"\ntest_60a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\tdo_facet mgs \"! which run-llog.sh &> /dev/null\" &&\n\t\tdo_facet mgs \"! ls run-llog.sh &> /dev/null\" &&\n\t\t\tskip_env \"missing subtest run-llog.sh\"\n\n\tlog \"$TEST60_HEAD - from kernel mode\"\n\tdo_facet mgs \"$LCTL dk > /dev/null\"\n\tdo_facet mgs \"bash run-llog.sh\" || error \"run-llog.sh failed\"\n\tdo_facet mgs $LCTL dk > $TMP/$tfile\n\n\t# LU-6388: test llog_reader\n\tlocal llog_reader=$(do_facet mgs \"which llog_reader 2> /dev/null\")\n\tllog_reader=${llog_reader:-$LUSTRE/utils/llog_reader}\n\t[ -z $(do_facet mgs ls -d $llog_reader 2> /dev/null) ] &&\n\t\t\tskip_env \"missing llog_reader\"\n\tlocal fstype=$(facet_fstype mgs)\n\t[ $fstype != ldiskfs -a $fstype != zfs ] &&\n\t\tskip_env \"Only for ldiskfs or zfs type mgs\"\n\n\tlocal mntpt=$(facet_mntpt mgs)\n\tlocal mgsdev=$(mgsdevname 1)\n\tlocal fid_list\n\tlocal fid\n\tlocal rec_list\n\tlocal rec\n\tlocal rec_type\n\tlocal obj_file\n\tlocal path\n\tlocal seq\n\tlocal oid\n\tlocal pass=true\n\n\t#get fid and record list\n\tfid_list=($(awk '/9_sub.*record/ { print $NF }' $TMP/$tfile |\n\t\ttail -n 4))\n\trec_list=($(awk '/9_sub.*record/ { print $((NF-3)) }' $TMP/$tfile |\n\t\ttail -n 4))\n\t#remount mgs as ldiskfs or zfs type\n\tstop mgs || error \"stop mgs failed\"\n\tmount_fstype mgs || error \"remount mgs failed\"\n\tfor ((i = 0; i < ${#fid_list[@]}; i++)); do\n\t\tfid=${fid_list[i]}\n\t\trec=${rec_list[i]}\n\t\tseq=$(echo $fid | awk -F ':' '{ print $1 }' | sed -e \"s/^0x//g\")\n\t\toid=$(echo $fid | awk -F ':' '{ print $2 }' | sed -e \"s/^0x//g\")\n\t\toid=$((16#$oid))\n\n\t\tcase $fstype in\n\t\t\tldiskfs )\n\t\t\t\tobj_file=$mntpt/O/$seq/d$((oid%32))/$oid ;;\n\t\t\tzfs )\n\t\t\t\tobj_file=$mntpt/oi.$(($((16#$seq))&127))/$fid ;;\n\t\tesac\n\t\techo \"obj_file is $obj_file\"\n\t\tdo_facet mgs $llog_reader $obj_file\n\n\t\trec_type=$(do_facet mgs $llog_reader $obj_file | grep \"type=\" |\n\t\t\tawk '{ print $3 }' | sed -e \"s/^type=//g\")\n\t\tif [ $rec_type != $rec ]; then\n\t\t\techo \"FAILED test_60a wrong record type $rec_type,\" \\\n\t\t\t      \"should be $rec\"\n\t\t\tpass=false\n\t\t\tbreak\n\t\tfi\n\n\t\t#check obj path if record type is LLOG_LOGID_MAGIC\n\t\tif [ \"$rec\" == \"1064553b\" ]; then\n\t\t\tpath=$(do_facet mgs $llog_reader $obj_file |\n\t\t\t\tgrep \"path=\" | awk '{ print $NF }' |\n\t\t\t\tsed -e \"s/^path=//g\")\n\t\t\tif [ $obj_file != $mntpt/$path ]; then\n\t\t\t\techo \"FAILED test_60a wrong obj path\" \\\n\t\t\t\t      \"$montpt/$path, should be $obj_file\"\n\t\t\t\tpass=false\n\t\t\t\tbreak\n\t\t\tfi\n\t\tfi\n\tdone\n\trm -f $TMP/$tfile\n\t#restart mgs before \"error\", otherwise it will block the next test\n\tstop mgs || error \"stop mgs failed\"\n\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS || error \"start mgs failed\"\n\t$pass || error \"test failed, see FAILED test_60a messages for specifics\"\n}\nrun_test 60a \"llog_test run from kernel module and test llog_reader\"\n\ntest_60b() { # bug 6411\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdmesg > $DIR/$tfile\n\tLLOG_COUNT=$(do_facet mgs dmesg |\n\t\t     awk \"/$TEST60_HEAD/ { marker = 1; from_marker = 0; }\n\t\t\t  /llog_[a-z]*.c:[0-9]/ {\n\t\t\t\tif (marker)\n\t\t\t\t\tfrom_marker++\n\t\t\t\tfrom_begin++\n\t\t\t  }\n\t\t\t  END {\n\t\t\t\tif (marker)\n\t\t\t\t\tprint from_marker\n\t\t\t\telse\n\t\t\t\t\tprint from_begin\n\t\t\t  }\")\n\n\t[[ $LLOG_COUNT -gt 120 ]] &&\n\t\terror \"CDEBUG_LIMIT not limiting messages ($LLOG_COUNT)\" || true\n}\nrun_test 60b \"limit repeated messages from CERROR/CWARN\"\n\ntest_60c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\techo \"create 5000 files\"\n\tcreatemany -o $DIR/f60c- 5000\n#define OBD_FAIL_MDS_LLOG_CREATE_FAILED  0x137\n\tlctl set_param fail_loc=0x80000137\n\tunlinkmany $DIR/f60c- 5000\n\tlctl set_param fail_loc=0\n}\nrun_test 60c \"unlink file when mds full\"\n\ntest_60d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tSAVEPRINTK=$(lctl get_param -n printk)\n\t# verify \"lctl mark\" is even working\"\n\tMESSAGE=\"test message ID $RANDOM $$\"\n\t$LCTL mark \"$MESSAGE\" || error \"$LCTL mark failed\"\n\tdmesg | grep -q \"$MESSAGE\" || error \"didn't find debug marker in log\"\n\n\tlctl set_param printk=0 || error \"set lnet.printk failed\"\n\tlctl get_param -n printk | grep emerg || error \"lnet.printk dropped emerg\"\n\tMESSAGE=\"new test message ID $RANDOM $$\"\n\t# Assume here that libcfs_debug_mark_buffer() uses D_WARNING\n\t$LCTL mark \"$MESSAGE\" || error \"$LCTL mark failed\"\n\tdmesg | grep -q \"$MESSAGE\" && error \"D_WARNING wasn't masked\" || true\n\n\tlctl set_param -n printk=\"$SAVEPRINTK\"\n}\nrun_test 60d \"test printk console message masking\"\n\ntest_60e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\ttouch $DIR/$tfile\n#define OBD_FAIL_MDS_LLOG_CREATE_FAILED2  0x15b\n\tdo_facet mds1 lctl set_param fail_loc=0x15b\n\trm $DIR/$tfile\n}\nrun_test 60e \"no space while new llog is being created\"\n\ntest_60g() {\n\tlocal pid\n\tlocal i\n\n\ttest_mkdir -c $MDSCOUNT $DIR/$tdir\n\n\t(\n\t\tlocal index=0\n\t\twhile true; do\n\t\t\t$LFS setdirstripe -i $(($index % $MDSCOUNT)) \\\n\t\t\t\t-c $MDSCOUNT $DIR/$tdir/subdir$index \\\n\t\t\t\t2>/dev/null\n\t\t\tmkdir $DIR/$tdir/subdir$index 2>/dev/null\n\t\t\trmdir $DIR/$tdir/subdir$index 2>/dev/null\n\t\t\tindex=$((index + 1))\n\t\tdone\n\t) &\n\n\tpid=$!\n\n\tfor i in {0..100}; do\n\t\t# define OBD_FAIL_OSD_TXN_START    0x19a\n\t\tlocal index=$((i % MDSCOUNT + 1))\n\n\t\tdo_facet mds$index $LCTL set_param fail_loc=0x8000019a \\\n\t\t\t> /dev/null\n\t\tusleep 100\n\tdone\n\n\tkill -9 $pid\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$i $LCTL set_param fail_loc=0 > /dev/null\n\tdone\n\n\tmkdir $DIR/$tdir/new || error \"mkdir failed\"\n\trmdir $DIR/$tdir/new || error \"rmdir failed\"\n\n\tdo_facet mds1 $LCTL lfsck_start -M $(facet_svc mds1) -A -C \\\n\t\t-t namespace\n\tfor i in $(seq $MDSCOUNT); do\n\t\twait_update_facet mds$i \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds$i).lfsck_namespace |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\"\n\tdone\n\n\tls -R $DIR/$tdir || error \"ls failed\"\n\trm -rf $DIR/$tdir || error \"rmdir failed\"\n}\nrun_test 60g \"transaction abort won't cause MDT hung\"\n\ntest_60h() {\n\t[ $MDS1_VERSION -le $(version_code 2.12.52) ] &&\n\t\tskip \"Need MDS version at least 2.12.52\"\n\t[ $MDSCOUNT -lt 2 ] && skip \"Need at least 2 MDTs\"\n\n\tlocal f\n\n\t#define OBD_FAIL_MDS_STRIPE_CREATE\t 0x188\n\t#define OBD_FAIL_MDS_STRIPE_FID\t\t 0x189\n\tfor fail_loc in 0x80000188 0x80000189; do\n\t\tdo_facet mds1 \"$LCTL set_param fail_loc=$fail_loc\"\n\t\t$LFS mkdir -c $MDSCOUNT -i 0 $DIR/$tdir-$fail_loc ||\n\t\t\terror \"mkdir $dir-$fail_loc failed\"\n\t\tfor i in {0..10}; do\n\t\t\t# create may fail on missing stripe\n\t\t\techo $i > $DIR/$tdir-$fail_loc/$i\n\t\tdone\n\t\t$LFS getdirstripe $DIR/$tdir-$fail_loc ||\n\t\t\terror \"getdirstripe $tdir-$fail_loc failed\"\n\t\t$LFS migrate -m 1 $DIR/$tdir-$fail_loc ||\n\t\t\terror \"migrate $tdir-$fail_loc failed\"\n\t\t$LFS getdirstripe $DIR/$tdir-$fail_loc ||\n\t\t\terror \"getdirstripe $tdir-$fail_loc failed\"\n\t\tpushd $DIR/$tdir-$fail_loc\n\t\tfor f in *; do\n\t\t\techo $f | cmp $f - || error \"$f data mismatch\"\n\t\tdone\n\t\tpopd\n\t\trm -rf $DIR/$tdir-$fail_loc\n\tdone\n}\nrun_test 60h \"striped directory with missing stripes can be accessed\"\n\ntest_61a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tf=\"$DIR/f61\"\n\tdd if=/dev/zero of=$f bs=$PAGE_SIZE count=1 || error \"dd $f failed\"\n\tcancel_lru_locks osc\n\t$MULTIOP $f OSMWUc || error \"$MULTIOP $f failed\"\n\tsync\n}\nrun_test 61a \"mmap() writes don't make sync hang ================\"\n\ntest_61b() {\n\tmmap_mknod_test $DIR/$tfile || error \"mmap_mknod_test failed\"\n}\nrun_test 61b \"mmap() of unstriped file is successful\"\n\n# bug 2330 - insufficient obd_match error checking causes LBUG\ntest_62() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tf=\"$DIR/f62\"\n\techo foo > $f\n\tcancel_lru_locks osc\n\tlctl set_param fail_loc=0x405\n\tcat $f && error \"cat succeeded, expect -EIO\"\n\tlctl set_param fail_loc=0\n}\n# This test is now irrelevant (as of bug 10718 inclusion), we no longer\n# match every page all of the time.\n#run_test 62 \"verify obd_match failure doesn't LBUG (should -EIO)\"\n\n# bug 2319 - oig_wait() interrupted causes crash because of invalid waitq.\n# Though this test is irrelevant anymore, it helped to reveal some\n# other grant bugs (LU-4482), let's keep it.\ntest_63a() {   # was test_63\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tMAX_DIRTY_MB=$(lctl get_param -n osc.*.max_dirty_mb | head -n 1)\n\n\tfor i in `seq 10` ; do\n\t\tdd if=/dev/zero of=$DIR/f63 bs=8k &\n\t\tsleep 5\n\t\tkill $!\n\t\tsleep 1\n\tdone\n\n\trm -f $DIR/f63 || true\n}\nrun_test 63a \"Verify oig_wait interruption does not crash =======\"\n\n# bug 2248 - async write errors didn't return to application on sync\n# bug 3677 - async write errors left page locked\ntest_63b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdebugsave\n\tlctl set_param debug=-1\n\n\t# ensure we have a grant to do async writes\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=1\n\trm $DIR/$tfile\n\n\tsync\t# sync lest earlier test intercept the fail_loc\n\n\t#define OBD_FAIL_OSC_BRW_PREP_REQ        0x406\n\tlctl set_param fail_loc=0x80000406\n\t$MULTIOP $DIR/$tfile Owy && \\\n\t\terror \"sync didn't return ENOMEM\"\n\tsync; sleep 2; sync\t# do a real sync this time to flush page\n\tlctl get_param -n llite.*.dump_page_cache | grep locked && \\\n\t\terror \"locked page left in cache after async error\" || true\n\tdebugrestore\n}\nrun_test 63b \"async write errors should be returned to fsync ===\"\n\ntest_64a () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlfs df $DIR\n\tlctl get_param osc.*[oO][sS][cC][_-]*.cur* | grep \"=[1-9]\"\n}\nrun_test 64a \"verify filter grant calculations (in kernel) =====\"\n\ntest_64b () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsh oos.sh $MOUNT || error \"oos.sh failed: $?\"\n}\nrun_test 64b \"check out-of-space detection on client\"\n\ntest_64c() {\n\t$LCTL set_param osc.*OST0000-osc-[^mM]*.cur_grant_bytes=0\n}\nrun_test 64c \"verify grant shrink\"\n\nimport_param() {\n\tlocal tgt=$1\n\tlocal param=$2\n\n\t$LCTL get_param osc.$tgt.import | awk \"/$param/ { print \\$2 }\"\n}\n\n# this does exactly what osc_request.c:osc_announce_cached() does in\n# order to calculate max amount of grants to ask from server\nwant_grant() {\n\tlocal tgt=$1\n\n\tlocal nrpages=$($LCTL get_param -n osc.$tgt.max_pages_per_rpc)\n\tlocal rpc_in_flight=$($LCTL get_param -n osc.$tgt.max_rpcs_in_flight)\n\n\t((rpc_in_flight++));\n\tnrpages=$((nrpages * rpc_in_flight))\n\n\tlocal dirty_max_pages=$($LCTL get_param -n osc.$tgt.max_dirty_mb)\n\n\tdirty_max_pages=$((dirty_max_pages * 1024 * 1024 / PAGE_SIZE))\n\n\t[[ $dirty_max_pages -gt $nrpages ]] && nrpages=$dirty_max_pages\n\tlocal undirty=$((nrpages * PAGE_SIZE))\n\n\tlocal max_extent_pages\n\tmax_extent_pages=$(import_param $tgt grant_max_extent_size)\n\tmax_extent_pages=$((max_extent_pages / PAGE_SIZE))\n\tlocal nrextents=$(((nrpages + max_extent_pages - 1) / max_extent_pages))\n\tlocal grant_extent_tax\n\tgrant_extent_tax=$(import_param $tgt grant_extent_tax)\n\n\tundirty=$((undirty + nrextents * grant_extent_tax))\n\n\techo $undirty\n}\n\n# this is size of unit for grant allocation. It should be equal to\n# what tgt_grant.c:tgt_grant_chunk() calculates\ngrant_chunk() {\n\tlocal tgt=$1\n\tlocal max_brw_size\n\tlocal grant_extent_tax\n\n\tmax_brw_size=$(import_param $tgt max_brw_size)\n\n\tgrant_extent_tax=$(import_param $tgt grant_extent_tax)\n\n\techo $(((max_brw_size + grant_extent_tax) * 2))\n}\n\ntest_64d() {\n\t[ $OST1_VERSION -ge $(version_code 2.10.56) ] ||\n\t\tskip \"OST < 2.10.55 doesn't limit grants enough\"\n\n\tlocal tgt=$($LCTL dl | awk '/OST0000-osc-[^mM]/ { print $4 }')\n\n\t[[ \"$($LCTL get_param osc.${tgt}.import)\" =~ \"grant_param\" ]] ||\n\t\tskip \"no grant_param connect flag\"\n\n\tlocal olddebug=\"$($LCTL get_param -n debug 2> /dev/null)\"\n\n\t$LCTL set_param -n -n debug=\"$OLDDEBUG\" || true\n\tstack_trap \"$LCTL set_param -n debug='$olddebug'\" EXIT\n\n\n\tlocal max_cur_granted=$(($(want_grant $tgt) + $(grant_chunk $tgt)))\n\tstack_trap \"rm -f $DIR/$tfile && wait_delete_completed\" EXIT\n\n\t$LFS setstripe $DIR/$tfile -i 0 -c 1\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1000 &\n\tddpid=$!\n\n\twhile kill -0 $ddpid; do\n\t\tlocal cur_grant=$($LCTL get_param -n osc.$tgt.cur_grant_bytes)\n\n\t\tif [[ $cur_grant -gt $max_cur_granted ]]; then\n\t\t\tkill $ddpid\n\t\t\terror \"cur_grant $cur_grant > $max_cur_granted\"\n\t\tfi\n\n\t\tsleep 1\n\tdone\n}\nrun_test 64d \"check grant limit exceed\"\n\ncheck_grants() {\n\tlocal tgt=$1\n\tlocal expected=$2\n\tlocal msg=$3\n\tlocal cur_grants=$($LCTL get_param -n osc.$tgt.cur_grant_bytes)\n\n\t((cur_grants == expected)) ||\n\t\terror \"$msg: grants mismatch: $cur_grants, expected $expected\"\n}\n\nround_up_p2() {\n\techo $((($1 + $2 - 1) & ~($2 - 1)))\n}\n\ntest_64e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $OST1_VERSION -ge $(version_code 2.11.56) ] ||\n\t\tskip \"Need OSS version at least 2.11.56\"\n\n\t# Remount client to reset grant\n\tremount_client $MOUNT || error \"failed to remount client\"\n\tlocal osc_tgt=\"$FSNAME-OST0000-osc-$($LFS getname -i $DIR)\"\n\n\tlocal init_grants=$(import_param $osc_tgt initial_grant)\n\n\tcheck_grants $osc_tgt $init_grants \"init grants\"\n\n\tlocal extent_tax=$(import_param $osc_tgt grant_extent_tax)\n\tlocal max_brw_size=$(import_param $osc_tgt max_brw_size)\n\tlocal gbs=$(import_param $osc_tgt grant_block_size)\n\n\t# write random number of bytes from max_brw_size / 4 to max_brw_size\n\tlocal write_bytes=$(shuf -i $((max_brw_size / 4))-$max_brw_size -n 1)\n\t# align for direct io\n\twrite_bytes=$(round_up_p2 $write_bytes PAGE_SIZE)\n\t# round to grant consumption unit\n\tlocal wb_round_up=$(round_up_p2 $write_bytes gbs)\n\n\tlocal grants=$((wb_round_up + extent_tax))\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile  || error \"lfs setstripe failed\"\n\n\t# define OBD_FAIL_TGT_NO_GRANT 0x725\n\t# make the server not grant more back\n\tdo_facet ost1 $LCTL set_param fail_loc=0x725\n\tdd if=/dev/zero of=$DIR/$tfile bs=$write_bytes count=1 oflag=direct\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tcheck_grants $osc_tgt $((init_grants - grants)) \"dio w/o grant alloc\"\n\n\trm -f $DIR/$tfile || error \"rm failed\"\n\n\t# Remount client to reset grant\n\tremount_client $MOUNT || error \"failed to remount client\"\n\tosc_tgt=\"$FSNAME-OST0000-osc-$($LFS getname -i $DIR)\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile || error \"lfs setstripe failed\"\n\n\t# define OBD_FAIL_TGT_NO_GRANT 0x725\n\t# make the server not grant more back\n\tdo_facet ost1 $LCTL set_param fail_loc=0x725\n\t$MULTIOP $DIR/$tfile \"oO_WRONLY:w${write_bytes}yc\"\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\tcheck_grants $osc_tgt $((init_grants - grants)) \"buf io w/o grant alloc\"\n}\nrun_test 64e \"check grant consumption (no grant allocation)\"\n\ntest_64f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t# Remount client to reset grant\n\tremount_client $MOUNT || error \"failed to remount client\"\n\tlocal osc_tgt=\"$FSNAME-OST0000-osc-$($LFS getname -i $DIR)\"\n\n\tlocal init_grants=$(import_param $osc_tgt initial_grant)\n\tlocal extent_tax=$(import_param $osc_tgt grant_extent_tax)\n\tlocal max_brw_size=$(import_param $osc_tgt max_brw_size)\n\tlocal gbs=$(import_param $osc_tgt grant_block_size)\n\tlocal chunk=$(grant_chunk $osc_tgt)\n\n\t# write random number of bytes from max_brw_size / 4 to max_brw_size\n\tlocal write_bytes=$(shuf -i $((max_brw_size / 4))-$max_brw_size -n 1)\n\t# align for direct io\n\twrite_bytes=$(round_up_p2 $write_bytes PAGE_SIZE)\n\t# round to grant consumption unit\n\tlocal wb_round_up=$(round_up_p2 $write_bytes gbs)\n\n\tlocal grants=$((wb_round_up + extent_tax))\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile || error \"lfs setstripe failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=$write_bytes count=1 oflag=direct ||\n\t\terror \"error writing to $DIR/$tfile\"\n\n\tcheck_grants $osc_tgt $((init_grants - grants + chunk)) \\\n\t\t\"direct io with grant allocation\"\n\n\trm -f $DIR/$tfile || error \"rm failed\"\n\n\t# Remount client to reset grant\n\tremount_client $MOUNT || error \"failed to remount client\"\n\tosc_tgt=\"$FSNAME-OST0000-osc-$($LFS getname -i $DIR)\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile || error \"lfs setstripe failed\"\n\n\tlocal cmd=\"oO_WRONLY:w${write_bytes}_yc\"\n\n\t$MULTIOP $DIR/$tfile $cmd &\n\tMULTIPID=$!\n\tsleep 1\n\n\tcheck_grants $osc_tgt $((init_grants - grants)) \\\n\t\t\"buffered io, not write rpc\"\n\n\tkill -USR1 $MULTIPID\n\twait\n\n\tcheck_grants $osc_tgt $((init_grants - grants + chunk)) \\\n\t\t\"buffered io, one RPC\"\n}\nrun_test 64f \"check grant consumption (with grant allocation)\"\n\n# bug 1414 - set/get directories' stripe info\ntest_65a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/f1\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f1 || error \"lverify failed\"\n}\nrun_test 65a \"directory with no stripe info\"\n\ntest_65b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)\n\n\t$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||\n\t\t\t\t\t\terror \"setstripe\"\n\ttouch $DIR/$tdir/f2\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f2 || error \"lverify failed\"\n}\nrun_test 65b \"directory setstripe -S stripe_size*2 -i 0 -c 1\"\n\ntest_65c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"need at least 2 OSTs\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal stripesize=$($LFS getstripe -S $DIR/$tdir)\n\n\t$LFS setstripe -S $((stripesize * 4)) -i 1 \\\n\t\t-c $((OSTCOUNT - 1)) $DIR/$tdir || error \"setstripe\"\n\ttouch $DIR/$tdir/f3\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f3 || error \"lverify failed\"\n}\nrun_test 65c \"directory setstripe -S stripe_size*4 -i 1 -c $((OSTCOUNT-1))\"\n\ntest_65d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal STRIPECOUNT=$($LFS getstripe -c $DIR/$tdir)\n\tlocal STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)\n\n\tif [[ $STRIPECOUNT -le 0 ]]; then\n\t\tsc=1\n\telif [[ $STRIPECOUNT -gt $LOV_MAX_STRIPE_COUNT ]]; then\n\t\t[[ $OSTCOUNT -gt $LOV_MAX_STRIPE_COUNT ]] &&\n\t\t\tsc=$LOV_MAX_STRIPE_COUNT || sc=$(($OSTCOUNT - 1))\n\telse\n\t\tsc=$(($STRIPECOUNT - 1))\n\tfi\n\t$LFS setstripe -S $STRIPESIZE -c $sc $DIR/$tdir || error \"setstripe\"\n\ttouch $DIR/$tdir/f4 $DIR/$tdir/f5\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f4 $DIR/$tdir/f5 ||\n\t\terror \"lverify failed\"\n}\nrun_test 65d \"directory setstripe -S stripe_size -c stripe_count\"\n\ntest_65e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\n\t$LFS setstripe $DIR/$tdir || error \"setstripe\"\n\t$LFS getstripe -v $DIR/$tdir | grep \"Default\" ||\n\t\t\t\t\terror \"no stripe info failed\"\n\ttouch $DIR/$tdir/f6\n\t$LVERIFY $DIR/$tdir $DIR/$tdir/f6 || error \"lverify failed\"\n}\nrun_test 65e \"directory setstripe defaults\"\n\ntest_65f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/${tdir}f\n\t$RUNAS $LFS setstripe $DIR/${tdir}f &&\n\t\terror \"setstripe succeeded\" || true\n}\nrun_test 65f \"dir setstripe permission (should return error) ===\"\n\ntest_65g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)\n\n\t$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||\n\t\terror \"setstripe -S failed\"\n\t$LFS setstripe -d $DIR/$tdir || error \"setstripe -d failed\"\n\t$LFS getstripe -v $DIR/$tdir | grep \"Default\" ||\n\t\terror \"delete default stripe failed\"\n}\nrun_test 65g \"directory setstripe -d\"\n\ntest_65h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tlocal STRIPESIZE=$($LFS getstripe -S $DIR/$tdir)\n\n\t$LFS setstripe -S $((STRIPESIZE * 2)) -i 0 -c 1 $DIR/$tdir ||\n\t\terror \"setstripe -S failed\"\n\ttest_mkdir $DIR/$tdir/dd1\n\t[ $($LFS getstripe -c $DIR/$tdir) = $($LFS getstripe -c $DIR/$tdir/dd1) ] ||\n\t\terror \"stripe info inherit failed\"\n}\nrun_test 65h \"directory stripe info inherit ====================\"\n\ntest_65i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsave_layout_restore_at_exit $MOUNT\n\n\t# bug6367: set non-default striping on root directory\n\t$LFS setstripe -S 65536 -c -1 $MOUNT || error \"error setting stripe\"\n\n\t# bug12836: getstripe on -1 default directory striping\n\t$LFS getstripe $MOUNT || error \"getstripe $MOUNT failed\"\n\n\t# bug12836: getstripe -v on -1 default directory striping\n\t$LFS getstripe -v $MOUNT || error \"getstripe -v $MOUNT failed\"\n\n\t# bug12836: new find on -1 default directory striping\n\t$LFS find -mtime -1 $MOUNT > /dev/null || error \"find $MOUNT failed\"\n}\nrun_test 65i \"various tests to set root directory striping\"\n\ntest_65j() { # bug6367\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tsync; sleep 1\n\n\t# if we aren't already remounting for each test, do so for this test\n\tif [ \"$I_MOUNTED\" = \"yes\" ]; then\n\t\tcleanup || error \"failed to unmount\"\n\t\tsetup\n\tfi\n\n\tsave_layout_restore_at_exit $MOUNT\n\n\t$LFS setstripe -d $MOUNT || error \"setstripe failed\"\n}\nrun_test 65j \"set default striping on root directory (bug 6367)=\"\n\ncleanup_65k() {\n\trm -rf $DIR/$tdir\n\twait_delete_completed\n\tdo_facet $SINGLEMDS \"lctl set_param -n \\\n\t\tosp.$ost*MDT0000.max_create_count=$max_count\"\n\tdo_facet $SINGLEMDS \"lctl set_param -n \\\n\t\tosp.$ost*MDT0000.create_count=$count\"\n\tdo_facet $SINGLEMDS lctl --device  %$INACTIVE_OSC activate\n\techo $INACTIVE_OSC \"is Activate\"\n\n\twait_osc_import_state mds ost$(( ostnum + 1 )) FULL\n}\n\ntest_65k() { # bug11679\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal disable_precreate=true\n\t[ $MDS1_VERSION -le $(version_code 2.8.54) ] &&\n\t\tdisable_precreate=false\n\n\techo \"Check OST status: \"\n\tlocal MDS_OSCS=$(do_facet $SINGLEMDS lctl dl |\n\t\tawk '/[oO][sS][cC].*md[ts]/ { print $4 }')\n\n\tfor OSC in $MDS_OSCS; do\n\t\techo $OSC \"is active\"\n\t\tdo_facet $SINGLEMDS lctl --device %$OSC activate\n\tdone\n\n\tfor INACTIVE_OSC in $MDS_OSCS; do\n\t\tlocal ost=$(osc_to_ost $INACTIVE_OSC)\n\t\tlocal ostnum=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\t       lov.*md*.target_obd |\n\t\t\t       awk -F: /$ost/'{ print $1 }' | head -n 1)\n\n\t\tmkdir -p $DIR/$tdir\n\t\t$LFS setstripe -i $ostnum -c 1 $DIR/$tdir\n\t\tcreatemany -o $DIR/$tdir/$tfile.$ostnum. 1000\n\n\t\techo \"Deactivate: \" $INACTIVE_OSC\n\t\tdo_facet $SINGLEMDS lctl --device %$INACTIVE_OSC deactivate\n\n\t\tlocal count=$(do_facet $SINGLEMDS \"lctl get_param -n \\\n\t\t\t      osp.$ost*MDT0000.create_count\")\n\t\tlocal max_count=$(do_facet $SINGLEMDS \"lctl get_param -n \\\n\t\t\t\t  osp.$ost*MDT0000.max_create_count\")\n\t\t$disable_precreate &&\n\t\t\tdo_facet $SINGLEMDS \"lctl set_param -n \\\n\t\t\t\tosp.$ost*MDT0000.max_create_count=0\"\n\n\t\tfor idx in $(seq 0 $((OSTCOUNT - 1))); do\n\t\t\t[ -f $DIR/$tdir/$idx ] && continue\n\t\t\techo \"$LFS setstripe -i $idx -c 1 $DIR/$tdir/$idx\"\n\t\t\t$LFS setstripe -i $idx -c 1 $DIR/$tdir/$idx ||\n\t\t\t\t{ cleanup_65k;\n\t\t\t\t  error \"setstripe $idx should succeed\"; }\n\t\t\trm -f $DIR/$tdir/$idx || error \"rm $idx failed\"\n\t\tdone\n\t\tunlinkmany $DIR/$tdir/$tfile.$ostnum. 1000\n\t\trmdir $DIR/$tdir\n\n\t\tdo_facet $SINGLEMDS \"lctl set_param -n \\\n\t\t\tosp.$ost*MDT0000.max_create_count=$max_count\"\n\t\tdo_facet $SINGLEMDS \"lctl set_param -n \\\n\t\t\tosp.$ost*MDT0000.create_count=$count\"\n\t\tdo_facet $SINGLEMDS lctl --device  %$INACTIVE_OSC activate\n\t\techo $INACTIVE_OSC \"is Activate\"\n\n\t\twait_osc_import_state mds ost$(( ostnum + 1 )) FULL\n\tdone\n}\nrun_test 65k \"validate manual striping works properly with deactivated OSCs\"\n\ntest_65l() { # bug 12836\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir -p $DIR/$tdir/test_dir\n\t$LFS setstripe -c -1 $DIR/$tdir/test_dir\n\t$LFS find -mtime -1 $DIR/$tdir >/dev/null\n}\nrun_test 65l \"lfs find on -1 stripe dir ========================\"\n\ntest_65m() {\n\tlocal layout=$(save_layout $MOUNT)\n\t$RUNAS $LFS setstripe -c 2 $MOUNT && {\n\t\trestore_layout $MOUNT $layout\n\t\terror \"setstripe should fail by non-root users\"\n\t}\n\ttrue\n}\nrun_test 65m \"normal user can't set filesystem default stripe\"\n\ntest_65n() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.12.50) ]] ||\n\t\tskip \"Need MDS version at least 2.12.50\"\n\t[[ $PARALLEL != \"yes\" ]] || skip \"skip parallel run\"\n\n\t[[ $OSTCOUNT -ge 2 ]] || skip_env \"needs >= 2 OSTs\"\n\twhich getfattr > /dev/null 2>&1 || skip_env \"no getfattr command\"\n\twhich setfattr > /dev/null 2>&1 || skip_env \"no setfattr command\"\n\n\tlocal root_layout=$(save_layout $MOUNT)\n\tstack_trap \"restore_layout $MOUNT $root_layout\" EXIT\n\n\t# new subdirectory under root directory should not inherit\n\t# the default layout from root\n\tlocal dir1=$MOUNT/$tdir-1\n\tmkdir $dir1 || error \"mkdir $dir1 failed\"\n\t! getfattr -n trusted.lov $dir1 &> /dev/null ||\n\t\terror \"$dir1 shouldn't have LOV EA\"\n\n\t# delete the default layout on root directory\n\t$LFS setstripe -d $MOUNT || error \"delete root default layout failed\"\n\n\tlocal dir2=$MOUNT/$tdir-2\n\tmkdir $dir2 || error \"mkdir $dir2 failed\"\n\t! getfattr -n trusted.lov $dir2 &> /dev/null ||\n\t\terror \"$dir2 shouldn't have LOV EA\"\n\n\t# set a new striping pattern on root directory\n\tlocal def_stripe_size=$($LFS getstripe -S $MOUNT)\n\tlocal new_def_stripe_size=$((def_stripe_size * 2))\n\t$LFS setstripe -S $new_def_stripe_size $MOUNT ||\n\t\terror \"set stripe size on $MOUNT failed\"\n\n\t# new file created in $dir2 should inherit the new stripe size from\n\t# the filesystem default\n\tlocal file2=$dir2/$tfile-2\n\ttouch $file2 || error \"touch $file2 failed\"\n\n\tlocal file2_stripe_size=$($LFS getstripe -S $file2)\n\t[[ $file2_stripe_size -eq $new_def_stripe_size ]] ||\n\t\terror \"$file2 didn't inherit stripe size $new_def_stripe_size\"\n\n\tlocal dir3=$MOUNT/$tdir-3\n\tmkdir $dir3 || error \"mkdir $dir3 failed\"\n\t# $dir3 shouldn't have LOV EA, but \"lfs getstripe -d $dir3\" should show\n\t# the root layout, which is the actual default layout that will be used\n\t# when new files are created in $dir3.\n\tlocal dir3_layout=$(get_layout_param $dir3)\n\tlocal root_dir_layout=$(get_layout_param $MOUNT)\n\t[[ \"$dir3_layout\" = \"$root_dir_layout\" ]] ||\n\t\terror \"$dir3 should show the default layout from $MOUNT\"\n\n\t# set OST pool on root directory\n\tlocal pool=$TESTNAME\n\tpool_add $pool || error \"add $pool failed\"\n\tpool_add_targets $pool 0 $((OSTCOUNT - 1)) 1 ||\n\t\terror \"add targets to $pool failed\"\n\n\t$LFS setstripe -p $pool $MOUNT ||\n\t\terror \"set OST pool on $MOUNT failed\"\n\n\t# new file created in $dir3 should inherit the pool from\n\t# the filesystem default\n\tlocal file3=$dir3/$tfile-3\n\ttouch $file3 || error \"touch $file3 failed\"\n\n\tlocal file3_pool=$($LFS getstripe -p $file3)\n\t[[ \"$file3_pool\" = \"$pool\" ]] ||\n\t\terror \"$file3 didn't inherit OST pool $pool\"\n\n\tlocal dir4=$MOUNT/$tdir-4\n\tmkdir $dir4 || error \"mkdir $dir4 failed\"\n\tlocal dir4_layout=$(get_layout_param $dir4)\n\troot_dir_layout=$(get_layout_param $MOUNT)\n\techo \"$LFS getstripe -d $dir4\"\n\t$LFS getstripe -d $dir4\n\techo \"$LFS getstripe -d $MOUNT\"\n\t$LFS getstripe -d $MOUNT\n\t[[ \"$dir4_layout\" = \"$root_dir_layout\" ]] ||\n\t\terror \"$dir4 should show the default layout from $MOUNT\"\n\n\t# new file created in $dir4 should inherit the pool from\n\t# the filesystem default\n\tlocal file4=$dir4/$tfile-4\n\ttouch $file4 || error \"touch $file4 failed\"\n\n\tlocal file4_pool=$($LFS getstripe -p $file4)\n\t[[ \"$file4_pool\" = \"$pool\" ]] ||\n\t\terror \"$file4 didn't inherit OST pool $pool\"\n\n\t# new subdirectory under non-root directory should inherit\n\t# the default layout from its parent directory\n\t$LFS setstripe -S $new_def_stripe_size -p $pool $dir4 ||\n\t\terror \"set directory layout on $dir4 failed\"\n\n\tlocal dir5=$dir4/$tdir-5\n\tmkdir $dir5 || error \"mkdir $dir5 failed\"\n\n\tdir4_layout=$(get_layout_param $dir4)\n\tlocal dir5_layout=$(get_layout_param $dir5)\n\t[[ \"$dir4_layout\" = \"$dir5_layout\" ]] ||\n\t\terror \"$dir5 should inherit the default layout from $dir4\"\n\n\t# though subdir under ROOT doesn't inherit default layout, but\n\t# its sub dir/file should be created with default layout.\n\t[[ $MDSCOUNT -ge 2 ]] || skip_env \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.12.59) ]] ||\n\t\tskip \"Need MDS version at least 2.12.59\"\n\n\tlocal default_lmv_count=$($LFS getdirstripe -D -c $MOUNT)\n\tlocal default_lmv_index=$($LFS getdirstripe -D -i $MOUNT)\n\tlocal default_lmv_hash=$($LFS getdirstripe -D -H $MOUNT)\n\n\tif [ $default_lmv_hash == \"none\" ]; then\n\t\tstack_trap \"$LFS setdirstripe -D -d $MOUNT\" EXIT\n\telse\n\t\tstack_trap \"$LFS setdirstripe -D -i $default_lmv_index \\\n\t\t\t-c $default_lmv_count -H $default_lmv_hash $MOUNT\" EXIT\n\tfi\n\n\t$LFS setdirstripe -D -c 2 $MOUNT ||\n\t\terror \"setdirstripe -D -c 2 failed\"\n\tmkdir $MOUNT/$tdir-6 || error \"mkdir $tdir-6 failed\"\n\tlocal lmv_count=$($LFS getdirstripe -c $MOUNT/$tdir-6)\n\t[ $lmv_count -eq 2 ] || error \"$tdir-6 stripe count $lmv_count\"\n}\nrun_test 65n \"don't inherit default layout from root for new subdirectories\"\n\n# bug 2543 - update blocks count on client\ntest_66() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tCOUNT=${COUNT:-8}\n\tdd if=/dev/zero of=$DIR/f66 bs=1k count=$COUNT\n\tsync; sync_all_data; sync; sync_all_data\n\tcancel_lru_locks osc\n\tBLOCKS=`ls -s $DIR/f66 | awk '{ print $1 }'`\n\t[ $BLOCKS -ge $COUNT ] || error \"$DIR/f66 blocks $BLOCKS < $COUNT\"\n}\nrun_test 66 \"update inode blocks count on client ===============\"\n\nmeminfo() {\n\tawk '($1 == \"'$1':\") { print $2 }' /proc/meminfo\n}\n\nswap_used() {\n\tswapon -s | awk '($1 == \"'$1'\") { print $4 }'\n}\n\n# bug5265, obdfilter oa2dentry return -ENOENT\n# #define OBD_FAIL_SRV_ENOENT 0x217\ntest_69() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tf=\"$DIR/$tfile\"\n\t$LFS setstripe -c 1 -i 0 $f\n\n\t$DIRECTIO write ${f}.2 0 1 || error \"directio write error\"\n\n\tdo_facet ost1 lctl set_param fail_loc=0x217\n\t$TRUNCATE $f 1 # vmtruncate() will ignore truncate() error.\n\t$DIRECTIO write $f 0 2 && error \"write succeeded, expect -ENOENT\"\n\n\tdo_facet ost1 lctl set_param fail_loc=0\n\t$DIRECTIO write $f 0 2 || error \"write error\"\n\n\tcancel_lru_locks osc\n\t$DIRECTIO read $f 0 1 || error \"read error\"\n\n\tdo_facet ost1 lctl set_param fail_loc=0x217\n\t$DIRECTIO read $f 1 1 && error \"read succeeded, expect -ENOENT\"\n\n\tdo_facet ost1 lctl set_param fail_loc=0\n\trm -f $f\n}\nrun_test 69 \"verify oa2dentry return -ENOENT doesn't LBUG ======\"\n\ntest_71() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setdirstripe -D -c$MDSCOUNT $DIR/$tdir\n\tsh rundbench -C -D $DIR/$tdir 2 || error \"dbench failed!\"\n}\nrun_test 71 \"Running dbench on lustre (don't segment fault) ====\"\n\ntest_72a() { # bug 5695 - Test that on 2.6 remove_suid works properly\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ \"$RUNAS_ID\" = \"$UID\" ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\t# Check that testing environment is properly set up. Skip if not\n\tFAIL_ON_ERROR=false check_runas_id_ret $RUNAS_ID $RUNAS_GID $RUNAS ||\n\t\tskip_env \"User $RUNAS_ID does not exist - skipping\"\n\n\ttouch $DIR/$tfile\n\tchmod 777 $DIR/$tfile\n\tchmod ug+s $DIR/$tfile\n\t$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=512 count=1 ||\n\t\terror \"$RUNAS dd $DIR/$tfile failed\"\n\t# See if we are still setuid/sgid\n\t[ -u $DIR/$tfile ] || [ -g $DIR/$tfile ] &&\n\t\terror \"S/gid is not dropped on write\"\n\t# Now test that MDS is updated too\n\tcancel_lru_locks mdc\n\t[ -u $DIR/$tfile ] || [ -g $DIR/$tfile ] &&\n\t\terror \"S/gid is not dropped on MDS\"\n\trm -f $DIR/$tfile\n}\nrun_test 72a \"Test that remove suid works properly (bug5695) ====\"\n\ntest_72b() { # bug 24226 -- keep mode setting when size is not changing\n\tlocal perm\n\n\t[ \"$RUNAS_ID\" = \"$UID\" ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\t[ \"$RUNAS_ID\" -eq 0 ] &&\n\t\tskip_env \"RUNAS_ID = 0 -- skipping\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t# Check that testing environment is properly set up. Skip if not\n\tFAIL_ON_ERROR=false check_runas_id_ret $RUNAS_ID $RUNAS_ID $RUNAS ||\n\t\tskip_env \"User $RUNAS_ID does not exist - skipping\"\n\n\ttouch $DIR/${tfile}-f{g,u}\n\ttest_mkdir $DIR/${tfile}-dg\n\ttest_mkdir $DIR/${tfile}-du\n\tchmod 770 $DIR/${tfile}-{f,d}{g,u}\n\tchmod g+s $DIR/${tfile}-{f,d}g\n\tchmod u+s $DIR/${tfile}-{f,d}u\n\tfor perm in 777 2777 4777; do\n\t\t$RUNAS chmod $perm $DIR/${tfile}-fg && error \"S/gid file allowed improper chmod to $perm\"\n\t\t$RUNAS chmod $perm $DIR/${tfile}-fu && error \"S/uid file allowed improper chmod to $perm\"\n\t\t$RUNAS chmod $perm $DIR/${tfile}-dg && error \"S/gid dir allowed improper chmod to $perm\"\n\t\t$RUNAS chmod $perm $DIR/${tfile}-du && error \"S/uid dir allowed improper chmod to $perm\"\n\tdone\n\ttrue\n}\nrun_test 72b \"Test that we keep mode setting if without file data changed (bug 24226)\"\n\n# bug 3462 - multiple simultaneous MDC requests\ntest_73() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/d73-1\n\ttest_mkdir $DIR/d73-2\n\tmultiop_bg_pause $DIR/d73-1/f73-1 O_c || return 1\n\tpid1=$!\n\n\tlctl set_param fail_loc=0x80000129\n\t$MULTIOP $DIR/d73-1/f73-2 Oc &\n\tsleep 1\n\tlctl set_param fail_loc=0\n\n\t$MULTIOP $DIR/d73-2/f73-3 Oc &\n\tpid3=$!\n\n\tkill -USR1 $pid1\n\twait $pid1 || return 1\n\n\tsleep 25\n\n\t$CHECKSTAT -t file $DIR/d73-1/f73-1 || return 4\n\t$CHECKSTAT -t file $DIR/d73-1/f73-2 || return 5\n\t$CHECKSTAT -t file $DIR/d73-2/f73-3 || return 6\n\n\trm -rf $DIR/d73-*\n}\nrun_test 73 \"multiple MDC requests (should not deadlock)\"\n\ntest_74a() { # bug 6149, 6184\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR/f74a\n\t#define OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT 0x30e\n\t#\n\t# very important to OR with OBD_FAIL_ONCE (0x80000000) -- otherwise it\n\t# will spin in a tight reconnection loop\n\t$LCTL set_param fail_loc=0x8000030e\n\t# get any lock that won't be difficult - lookup works.\n\tls $DIR/f74a\n\t$LCTL set_param fail_loc=0\n\trm -f $DIR/f74a\n\ttrue\n}\nrun_test 74a \"ldlm_enqueue freed-export error path, ls (shouldn't LBUG)\"\n\ntest_74b() { # bug 13310\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_LDLM_ENQUEUE_OLD_EXPORT 0x30e\n\t#\n\t# very important to OR with OBD_FAIL_ONCE (0x80000000) -- otherwise it\n\t# will spin in a tight reconnection loop\n\t$LCTL set_param fail_loc=0x8000030e\n\t# get a \"difficult\" lock\n\ttouch $DIR/f74b\n\t$LCTL set_param fail_loc=0\n\trm -f $DIR/f74b\n\ttrue\n}\nrun_test 74b \"ldlm_enqueue freed-export error path, touch (shouldn't LBUG)\"\n\ntest_74c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_LDLM_NEW_LOCK\n\t$LCTL set_param fail_loc=0x319\n\ttouch $DIR/$tfile && error \"touch successful\"\n\t$LCTL set_param fail_loc=0\n\ttrue\n}\nrun_test 74c \"ldlm_lock_create error path, (shouldn't LBUG)\"\n\nnum_inodes() {\n\t[ -f /sys/kernel/slab/lustre_inode_cache/shrink ] &&\n\t\techo 1 > /sys/kernel/slab/lustre_inode_cache/shrink\n\tawk '/lustre_inode_cache/ {print $2; exit}' /proc/slabinfo\n}\n\ntest_76() { # Now for bug 20433, added originally in bug 1443\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tcancel_lru_locks osc\n\tlocal cpus=$(getconf _NPROCESSORS_ONLN 2>/dev/null)\n\tlocal before=$(num_inodes)\n\tlocal count=$((512 * cpus))\n\t[ \"$SLOW\" = \"no\" ] && count=$((64 * cpus))\n\n\techo \"before inodes: $before\"\n\tfor i in $(seq $count); do\n\t\ttouch $DIR/$tfile\n\t\trm -f $DIR/$tfile\n\tdone\n\tcancel_lru_locks osc\n\tlocal after=$(num_inodes)\n\techo \"after inodes: $after\"\n\twhile (( after > before + 8 * ${cpus:-1} )); do\n\t\tsleep 1\n\t\tafter=$(num_inodes)\n\t\twait=$((wait + 1))\n\t\t(( wait % 5 == 0 )) && echo \"wait $wait seconds inodes: $after\"\n\t\tif (( wait > 30 )); then\n\t\t\terror \"inode slab grew from $before to $after\"\n\t\tfi\n\tdone\n}\nrun_test 76 \"confirm clients recycle inodes properly ====\"\n\n\nexport ORIG_CSUM=\"\"\nset_checksums()\n{\n\t# Note: in sptlrpc modes which enable its own bulk checksum, the\n\t# original crc32_le bulk checksum will be automatically disabled,\n\t# and the OBD_FAIL_OSC_CHECKSUM_SEND/OBD_FAIL_OSC_CHECKSUM_RECEIVE\n\t# will be checked by sptlrpc code against sptlrpc bulk checksum.\n\t# In this case set_checksums() will not be no-op, because sptlrpc\n\t# bulk checksum will be enabled all through the test.\n\n\t[ \"$ORIG_CSUM\" ] || ORIG_CSUM=`lctl get_param -n osc.*.checksums | head -n1`\n        lctl set_param -n osc.*.checksums $1\n\treturn 0\n}\n\nexport ORIG_CSUM_TYPE=\"`lctl get_param -n osc.*osc-[^mM]*.checksum_type |\n                        sed 's/.*\\[\\(.*\\)\\].*/\\1/g' | head -n1`\"\nCKSUM_TYPES=${CKSUM_TYPES:-$(lctl get_param -n osc.*osc-[^mM]*.checksum_type |\n\t\t\t     tr -d [] | head -n1)}\nset_checksum_type()\n{\n\tlctl set_param -n osc.*osc-[^mM]*.checksum_type $1\n\trc=$?\n\tlog \"set checksum type to $1, rc = $rc\"\n\treturn $rc\n}\n\nget_osc_checksum_type()\n{\n\t# arugment 1: OST name, like OST0000\n\tost=$1\n\tchecksum_type=$(lctl get_param -n osc.*${ost}-osc-[^mM]*.checksum_type |\n\t\t\tsed 's/.*\\[\\(.*\\)\\].*/\\1/g')\n\trc=$?\n\t[ $rc -ne 0 ] && error \"failed to get checksum type of $ost, rc = $rc, output = $checksum_type\"\n\techo $checksum_type\n}\n\nF77_TMP=$TMP/f77-temp\nF77SZ=8\nsetup_f77() {\n\tdd if=/dev/urandom of=$F77_TMP bs=1M count=$F77SZ || \\\n\t\terror \"error writing to $F77_TMP\"\n}\n\ntest_77a() { # bug 10889\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\t[ ! -f $F77_TMP ] && setup_f77\n\tset_checksums 1\n\tdd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ || error \"dd error\"\n\tset_checksums 0\n\trm -f $DIR/$tfile\n}\nrun_test 77a \"normal checksum read/write operation\"\n\ntest_77b() { # bug 10889\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\t[ ! -f $F77_TMP ] && setup_f77\n\t#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409\n\t$LCTL set_param fail_loc=0x80000409\n\tset_checksums 1\n\n\tdd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ conv=sync ||\n\t\terror \"dd error: $?\"\n\t$LCTL set_param fail_loc=0\n\n\tfor algo in $CKSUM_TYPES; do\n\t\tcancel_lru_locks osc\n\t\tset_checksum_type $algo\n\t\t#define OBD_FAIL_OSC_CHECKSUM_RECEIVE    0x408\n\t\t$LCTL set_param fail_loc=0x80000408\n\t\tcmp $F77_TMP $DIR/$tfile || error \"file compare failed\"\n\t\t$LCTL set_param fail_loc=0\n\tdone\n\tset_checksums 0\n\tset_checksum_type $ORIG_CSUM_TYPE\n\trm -f $DIR/$tfile\n}\nrun_test 77b \"checksum error on client write, read\"\n\ncleanup_77c() {\n\ttrap 0\n\tset_checksums 0\n\t$LCTL set_param osc.*osc-[^mM]*.checksum_dump=0\n\t$check_ost &&\n\t\tdo_facet ost1 $LCTL set_param obdfilter.*-OST*.checksum_dump=0\n\t[ -n \"$osc_file_prefix\" ] && rm -f ${osc_file_prefix}*\n\t$check_ost && [ -n \"$ost_file_prefix\" ] &&\n\t\tdo_facet ost1 rm -f ${ost_file_prefix}\\*\n}\n\ntest_77c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal bad1\n\tlocal osc_file_prefix\n\tlocal osc_file\n\tlocal check_ost=false\n\tlocal ost_file_prefix\n\tlocal ost_file\n\tlocal orig_cksum\n\tlocal dump_cksum\n\tlocal fid\n\n\t# ensure corruption will occur on first OSS/OST\n\t$LFS setstripe -i 0 $DIR/$tfile\n\n\t[ ! -f $F77_TMP ] && setup_f77\n\tdd if=$F77_TMP of=$DIR/$tfile bs=1M count=$F77SZ conv=sync ||\n\t\terror \"dd write error: $?\"\n\tfid=$($LFS path2fid $DIR/$tfile)\n\n\tif [ $OST1_VERSION -ge $(version_code 2.9.57) ]\n\tthen\n\t\tcheck_ost=true\n\t\tost_file_prefix=$(do_facet ost1 $LCTL get_param -n debug_path)\n\t\tost_file_prefix=${ost_file_prefix}-checksum_dump-ost-\\\\${fid}\n\telse\n\t\techo \"OSS do not support bulk pages dump upon error\"\n\tfi\n\n\tosc_file_prefix=$($LCTL get_param -n debug_path)\n\tosc_file_prefix=${osc_file_prefix}-checksum_dump-osc-\\\\${fid}\n\n\ttrap cleanup_77c EXIT\n\n\tset_checksums 1\n\t# enable bulk pages dump upon error on Client\n\t$LCTL set_param osc.*osc-[^mM]*.checksum_dump=1\n\t# enable bulk pages dump upon error on OSS\n\t$check_ost &&\n\t\tdo_facet ost1 $LCTL set_param obdfilter.*-OST*.checksum_dump=1\n\n\t# flush Client cache to allow next read to reach OSS\n\tcancel_lru_locks osc\n\n\t#define OBD_FAIL_OSC_CHECKSUM_RECEIVE       0x408\n\t$LCTL set_param fail_loc=0x80000408\n\tdd if=$DIR/$tfile of=/dev/null bs=1M || error \"dd read error: $?\"\n\t$LCTL set_param fail_loc=0\n\n\trm -f $DIR/$tfile\n\n\t# check cksum dump on Client\n\tosc_file=$(ls ${osc_file_prefix}*)\n\t[ -n \"$osc_file\" ] || error \"no checksum dump file on Client\"\n\t# OBD_FAIL_OSC_CHECKSUM_RECEIVE corrupts with \"bad1\" at start of file\n\tbad1=$(dd if=$osc_file bs=1 count=4 2>/dev/null) || error \"dd error: $?\"\n\t[ $bad1 == \"bad1\" ] || error \"unexpected corrupt pattern\"\n\torig_cksum=$(dd if=$F77_TMP bs=1 skip=4 count=1048572 2>/dev/null |\n\t\t     cksum)\n\tdump_cksum=$(dd if=$osc_file bs=1 skip=4 2>/dev/null | cksum)\n\t[[ \"$orig_cksum\" == \"$dump_cksum\" ]] ||\n\t\terror \"dump content does not match on Client\"\n\n\t$check_ost || skip \"No need to check cksum dump on OSS\"\n\n\t# check cksum dump on OSS\n\tost_file=$(do_facet ost1 ls ${ost_file_prefix}\\*)\n\t[ -n \"$ost_file\" ] || error \"no checksum dump file on OSS\"\n\torig_cksum=$(dd if=$F77_TMP bs=1048576 count=1 2>/dev/null | cksum)\n\tdump_cksum=$(do_facet ost1 dd if=$ost_file 2>/dev/null \\| cksum)\n\t[[ \"$orig_cksum\" == \"$dump_cksum\" ]] ||\n\t\terror \"dump content does not match on OSS\"\n\n\tcleanup_77c\n}\nrun_test 77c \"checksum error on client read with debug\"\n\ntest_77d() { # bug 10889\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\t#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409\n\t$LCTL set_param fail_loc=0x80000409\n\tset_checksums 1\n\t$DIRECTIO write $DIR/$tfile 0 $F77SZ $((1024 * 1024)) ||\n\t\terror \"direct write: rc=$?\"\n\t$LCTL set_param fail_loc=0\n\tset_checksums 0\n\n\t#define OBD_FAIL_OSC_CHECKSUM_RECEIVE    0x408\n\t$LCTL set_param fail_loc=0x80000408\n\tset_checksums 1\n\tcancel_lru_locks osc\n\t$DIRECTIO read $DIR/$tfile 0 $F77SZ $((1024 * 1024)) ||\n\t\terror \"direct read: rc=$?\"\n\t$LCTL set_param fail_loc=0\n\tset_checksums 0\n}\nrun_test 77d \"checksum error on OST direct write, read\"\n\ntest_77f() { # bug 10889\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\tset_checksums 1\n\tfor algo in $CKSUM_TYPES; do\n\t\tcancel_lru_locks osc\n\t\tset_checksum_type $algo\n\t\t#define OBD_FAIL_OSC_CHECKSUM_SEND       0x409\n\t\t$LCTL set_param fail_loc=0x409\n\t\t$DIRECTIO write $DIR/$tfile 0 $F77SZ $((1024 * 1024)) &&\n\t\t\terror \"direct write succeeded\"\n\t\t$LCTL set_param fail_loc=0\n\tdone\n\tset_checksum_type $ORIG_CSUM_TYPE\n\tset_checksums 0\n}\nrun_test 77f \"repeat checksum error on write (expect error)\"\n\ntest_77g() { # bug 10889\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\t[ ! -f $F77_TMP ] && setup_f77\n\n\tlocal file=$DIR/$tfile\n\tstack_trap \"rm -f $file\" EXIT\n\n\t$LFS setstripe -c 1 -i 0 $file\n\t#define OBD_FAIL_OST_CHECKSUM_RECEIVE       0x21a\n\tdo_facet ost1 lctl set_param fail_loc=0x8000021a\n\tset_checksums 1\n\tdd if=$F77_TMP of=$file bs=1M count=$F77SZ ||\n\t\terror \"write error: rc=$?\"\n\tdo_facet ost1 lctl set_param fail_loc=0\n\tset_checksums 0\n\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_OST_CHECKSUM_SEND          0x21b\n\tdo_facet ost1 lctl set_param fail_loc=0x8000021b\n\tset_checksums 1\n\tcmp $F77_TMP $file || error \"file compare failed\"\n\tdo_facet ost1 lctl set_param fail_loc=0\n\tset_checksums 0\n}\nrun_test 77g \"checksum error on OST write, read\"\n\ntest_77k() { # LU-10906\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\tlocal cksum_param=\"osc.$FSNAME*.checksums\"\n\tlocal get_checksum=\"$LCTL get_param -n $cksum_param | head -n1\"\n\tlocal checksum\n\tlocal i\n\n\t[ \"$ORIG_CSUM\" ] || ORIG_CSUM=$(eval $get_checksum)\n\tstack_trap \"wait_update $HOSTNAME '$get_checksum' $ORIG_CSUM || true\"\n\tstack_trap \"do_facet mgs $LCTL set_param -P $cksum_param=$ORIG_CSUM\"\n\n\tfor i in 0 1; do\n\t\tdo_facet mgs $LCTL set_param -P $cksum_param=$i ||\n\t\t\terror \"failed to set checksum=$i on MGS\"\n\t\twait_update $HOSTNAME \"$get_checksum\" $i\n\t\t#remount\n\t\techo \"remount client, checksum should be $i\"\n\t\tremount_client $MOUNT || error \"failed to remount client\"\n\t\tchecksum=$(eval $get_checksum)\n\t\t[ $checksum -eq $i ] || error \"checksum($checksum) != $i\"\n\tdone\n\t# remove persistent param to avoid races with checksum mountopt below\n\tdo_facet mgs $LCTL set_param -P -d $cksum_param ||\n\t\terror \"failed to delete checksum on MGS\"\n\n\tfor opt in \"checksum\" \"nochecksum\"; do\n\t\t#remount with mount option\n\t\techo \"remount client with option $opt, checksum should be $i\"\n\t\tumount_client $MOUNT || error \"failed to umount client\"\n\t\tmount_client $MOUNT \"$MOUNT_OPTS,$opt\" ||\n\t\t\terror \"failed to mount client with option '$opt'\"\n\t\tchecksum=$(eval $get_checksum)\n\t\t[ $checksum -eq $i ] || error \"checksum($checksum) != $i\"\n\t\ti=$((i - 1))\n\tdone\n\n\tremount_client $MOUNT || error \"failed to remount client\"\n}\nrun_test 77k \"enable/disable checksum correctly\"\n\ntest_77l() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\n\tset_checksums 1\n\tstack_trap \"set_checksums $ORIG_CSUM\" EXIT\n\tstack_trap \"set_checksum_type $ORIG_CSUM_TYPE\" EXIT\n\n\tset_checksum_type invalid && error \"unexpected success of invalid checksum type\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\tfor algo in $CKSUM_TYPES; do\n\t\tset_checksum_type $algo || error \"fail to set checksum type $algo\"\n\t\tosc_algo=$(get_osc_checksum_type OST0000)\n\t\t[ \"$osc_algo\" != \"$algo\" ] && error \"checksum type is $osc_algo after setting it to $algo\"\n\n\t\t# no locks, no reqs to let the connection idle\n\t\tcancel_lru_locks osc\n\t\tlru_resize_disable osc\n\t\twait_osc_import_state client ost1 IDLE\n\n\t\t# ensure ost1 is connected\n\t\tstat $DIR/$tfile >/dev/null || error \"can't stat\"\n\t\twait_osc_import_state client ost1 FULL\n\n\t\tosc_algo=$(get_osc_checksum_type OST0000)\n\t\t[ \"$osc_algo\" != \"$algo\" ] && error \"checksum type changed from $algo to $osc_algo after reconnection\"\n\tdone\n\treturn 0\n}\nrun_test 77l \"preferred checksum type is remembered after reconnected\"\n\n[ \"$ORIG_CSUM\" ] && set_checksums $ORIG_CSUM || true\nrm -f $F77_TMP\nunset F77_TMP\n\ncleanup_test_78() {\n\ttrap 0\n\trm -f $DIR/$tfile\n}\n\ntest_78() { # bug 10901\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost || skip_env \"local OST\"\n\n\tNSEQ=5\n\tF78SIZE=$(($(awk '/MemFree:/ { print $2 }' /proc/meminfo) / 1024))\n\techo \"MemFree: $F78SIZE, Max file size: $MAXFREE\"\n\tMEMTOTAL=$(($(awk '/MemTotal:/ { print $2 }' /proc/meminfo) / 1024))\n\techo \"MemTotal: $MEMTOTAL\"\n\n\t# reserve 256MB of memory for the kernel and other running processes,\n\t# and then take 1/2 of the remaining memory for the read/write buffers.\n\tif [ $MEMTOTAL -gt 512 ] ;then\n\t\tMEMTOTAL=$(((MEMTOTAL - 256 ) / 2))\n\telse\n\t\t# for those poor memory-starved high-end clusters...\n\t\tMEMTOTAL=$((MEMTOTAL / 2))\n\tfi\n\techo \"Mem to use for directio: $MEMTOTAL\"\n\n\t[[ $F78SIZE -gt $MEMTOTAL ]] && F78SIZE=$MEMTOTAL\n\t[[ $F78SIZE -gt 512 ]] && F78SIZE=512\n\t[[ $F78SIZE -gt $((MAXFREE / 1024)) ]] && F78SIZE=$((MAXFREE / 1024))\n\tSMALLESTOST=$($LFS df $DIR | grep OST | awk '{ print $4 }' | sort -n |\n\t\thead -n1)\n\techo \"Smallest OST: $SMALLESTOST\"\n\t[[ $SMALLESTOST -lt 10240 ]] &&\n\t\tskip \"too small OSTSIZE, useless to run large O_DIRECT test\"\n\n\ttrap cleanup_test_78 EXIT\n\n\t[[ $F78SIZE -gt $((SMALLESTOST * $OSTCOUNT / 1024 - 80)) ]] &&\n\t\tF78SIZE=$((SMALLESTOST * $OSTCOUNT / 1024 - 80))\n\n\t[ \"$SLOW\" = \"no\" ] && NSEQ=1 && [ $F78SIZE -gt 32 ] && F78SIZE=32\n\techo \"File size: $F78SIZE\"\n\t$LFS setstripe -c $OSTCOUNT $DIR/$tfile || error \"setstripe failed\"\n\tfor i in $(seq 1 $NSEQ); do\n\t\tFSIZE=$(($F78SIZE / ($NSEQ - $i + 1)))\n\t\techo directIO rdwr round $i of $NSEQ\n\t\t$DIRECTIO rdwr $DIR/$tfile 0 $FSIZE 1048576||error \"rdwr failed\"\n\tdone\n\n\tcleanup_test_78\n}\nrun_test 78 \"handle large O_DIRECT writes correctly ============\"\n\ntest_79() { # bug 12743\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\twait_delete_completed\n\n\tBKTOTAL=$(calc_osc_kbytes kbytestotal)\n\tBKFREE=$(calc_osc_kbytes kbytesfree)\n\tBKAVAIL=$(calc_osc_kbytes kbytesavail)\n\n        STRING=`df -P $MOUNT | tail -n 1 | awk '{print $2\",\"$3\",\"$4}'`\n        DFTOTAL=`echo $STRING | cut -d, -f1`\n        DFUSED=`echo $STRING  | cut -d, -f2`\n        DFAVAIL=`echo $STRING | cut -d, -f3`\n        DFFREE=$(($DFTOTAL - $DFUSED))\n\n        ALLOWANCE=$((64 * $OSTCOUNT))\n\n        if [ $DFTOTAL -lt $(($BKTOTAL - $ALLOWANCE)) ] ||\n           [ $DFTOTAL -gt $(($BKTOTAL + $ALLOWANCE)) ] ; then\n                error \"df total($DFTOTAL) mismatch OST total($BKTOTAL)\"\n        fi\n        if [ $DFFREE -lt $(($BKFREE - $ALLOWANCE)) ] ||\n           [ $DFFREE -gt $(($BKFREE + $ALLOWANCE)) ] ; then\n                error \"df free($DFFREE) mismatch OST free($BKFREE)\"\n        fi\n        if [ $DFAVAIL -lt $(($BKAVAIL - $ALLOWANCE)) ] ||\n           [ $DFAVAIL -gt $(($BKAVAIL + $ALLOWANCE)) ] ; then\n                error \"df avail($DFAVAIL) mismatch OST avail($BKAVAIL)\"\n        fi\n}\nrun_test 79 \"df report consistency check =======================\"\n\ntest_80() { # bug 10718\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t# relax strong synchronous semantics for slow backends like ZFS\n\tif [ \"$ost1_FSTYPE\" != \"ldiskfs\" ]; then\n\t\tlocal soc=\"obdfilter.*.sync_lock_cancel\"\n\t\tlocal save=$(do_facet ost1 $LCTL get_param -n $soc | head -n1)\n\n\t\t# \"sync_on_lock_cancel\" was broken by v2_11_55_0-26-g7059644e9a\n\t\tif [ -z \"$save\" ]; then\n\t\t\tsoc=\"obdfilter.*.sync_on_lock_cancel\"\n\t\t\tsave=$(do_facet ost1 $LCTL get_param -n $soc | head -n1)\n\t\tfi\n\n\t\tif [ \"$save\" != \"never\" ]; then\n\t\t\tlocal hosts=$(comma_list $(osts_nodes))\n\n\t\t\tdo_nodes $hosts $LCTL set_param $soc=never\n\t\t\tstack_trap \"do_nodes $hosts $LCTL set_param $soc=$save\"\n\t\tfi\n\tfi\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=1M\n\tsync; sleep 1; sync\n\tlocal before=$(date +%s)\n\tcancel_lru_locks osc\n\tlocal after=$(date +%s)\n\tlocal diff=$((after - before))\n\t[ $diff -le 1 ] || error \"elapsed for 1M@1T = $diff\"\n\n\trm -f $DIR/$tfile\n}\nrun_test 80 \"Page eviction is equally fast at high offsets too\"\n\ntest_81a() { # LU-456\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\t# define OBD_FAIL_OST_MAPBLK_ENOSPC    0x228\n\t# MUST OR with the OBD_FAIL_ONCE (0x80000000)\n\tdo_facet ost1 lctl set_param fail_loc=0x80000228\n\n\t# write should trigger a retry and success\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\tRC=$?\n\tif [ $RC -ne 0 ] ; then\n\t\terror \"write should success, but failed for $RC\"\n\tfi\n}\nrun_test 81a \"OST should retry write when get -ENOSPC ===============\"\n\ntest_81b() { # LU-456\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\t# define OBD_FAIL_OST_MAPBLK_ENOSPC    0x228\n\t# Don't OR with the OBD_FAIL_ONCE (0x80000000)\n\tdo_facet ost1 lctl set_param fail_loc=0x228\n\n\t# write should retry several times and return -ENOSPC finally\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\tRC=$?\n\tENOSPC=28\n\tif [ $RC -ne $ENOSPC ] ; then\n\t\terror \"dd should fail for -ENOSPC, but succeed.\"\n\tfi\n}\nrun_test 81b \"OST should return -ENOSPC when retry still fails =======\"\n\ntest_99() {\n\t[ -z \"$(which cvs 2>/dev/null)\" ] && skip_env \"could not find cvs\"\n\n\ttest_mkdir $DIR/$tdir.cvsroot\n\tchown $RUNAS_ID $DIR/$tdir.cvsroot\n\n\tcd $TMP\n\t$RUNAS cvs -d $DIR/$tdir.cvsroot init || error \"cvs init failed\"\n\n\tcd /etc/init.d\n\t# some versions of cvs import exit(1) when asked to import links or\n\t# files they can't read.  ignore those files.\n\tlocal toignore=$(find . -type l -printf '-I %f\\n' -o \\\n\t\t\t ! -perm /4 -printf '-I %f\\n')\n\t$RUNAS cvs -d $DIR/$tdir.cvsroot import -m \"nomesg\" $toignore \\\n\t\t$tdir.reposname vtag rtag\n\n\tcd $DIR\n\ttest_mkdir $DIR/$tdir.reposname\n\tchown $RUNAS_ID $DIR/$tdir.reposname\n\t$RUNAS cvs -d $DIR/$tdir.cvsroot co $tdir.reposname\n\n\tcd $DIR/$tdir.reposname\n\t$RUNAS touch foo99\n\t$RUNAS cvs add -m 'addmsg' foo99\n\t$RUNAS cvs update\n\t$RUNAS cvs commit -m 'nomsg' foo99\n\trm -fr $DIR/$tdir.cvsroot\n}\nrun_test 99 \"cvs strange file/directory operations\"\n\ntest_100() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ \"$NETTYPE\" =~ tcp ]] ||\n\t\tskip_env \"TCP secure port test, not useful for NETTYPE=$NETTYPE\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_servers ||\n\t\tskip \"useless for local single node setup\"\n\n\tnetstat -tna | ( rc=1; while read PROT SND RCV LOCAL REMOTE STAT; do\n\t\t[ \"$PROT\" != \"tcp\" ] && continue\n\t\tRPORT=$(echo $REMOTE | cut -d: -f2)\n\t\t[ \"$RPORT\" != \"$ACCEPTOR_PORT\" ] && continue\n\n\t\trc=0\n\t\tLPORT=`echo $LOCAL | cut -d: -f2`\n\t\tif [ $LPORT -ge 1024 ]; then\n\t\t\techo \"bad: $PROT $SND $RCV $LOCAL $REMOTE $STAT\"\n\t\t\tnetstat -tna\n\t\t\terror_exit \"local: $LPORT > 1024, remote: $RPORT\"\n\t\tfi\n\tdone\n\t[ \"$rc\" = 0 ] || error_exit \"privileged port not found\" )\n}\nrun_test 100 \"check local port using privileged port ===========\"\n\nfunction get_named_value()\n{\n    local tag\n\n    tag=$1\n    while read ;do\n        line=$REPLY\n        case $line in\n        $tag*)\n            echo $line | sed \"s/^$tag[ ]*//\"\n            break\n            ;;\n        esac\n    done\n}\n\nexport CACHE_MAX=$($LCTL get_param -n llite.*.max_cached_mb |\n\t\t   awk '/^max_cached_mb/ { print $2 }')\n\ncleanup_101a() {\n\t$LCTL set_param -n llite.*.max_cached_mb $CACHE_MAX\n\ttrap 0\n}\n\ntest_101a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal s\n\tlocal discard\n\tlocal nreads=10000\n\tlocal cache_limit=32\n\n\t$LCTL set_param -n osc.*-osc*.rpc_stats 0\n\ttrap cleanup_101a EXIT\n\t$LCTL set_param -n llite.*.read_ahead_stats 0\n\t$LCTL set_param -n llite.*.max_cached_mb $cache_limit\n\n\t#\n\t# randomly read 10000 of 64K chunks from file 3x 32MB in size\n\t#\n\techo \"nreads: $nreads file size: $((cache_limit * 3))MB\"\n\t$READS -f $DIR/$tfile -s$((cache_limit * 3192 * 1024)) -b65536 -C -n$nreads -t 180\n\n\tdiscard=0\n\tfor s in $($LCTL get_param -n llite.*.read_ahead_stats |\n\t\tget_named_value 'read but discarded' | cut -d\" \" -f1); do\n\t\t\tdiscard=$(($discard + $s))\n\tdone\n\tcleanup_101a\n\n\t$LCTL get_param osc.*-osc*.rpc_stats\n\t$LCTL get_param llite.*.read_ahead_stats\n\n\t# Discard is generally zero, but sometimes a few random reads line up\n\t# and trigger larger readahead, which is wasted & leads to discards.\n\tif [[ $(($discard)) -gt $nreads ]]; then\n\t\terror \"too many ($discard) discarded pages\"\n\tfi\n\trm -f $DIR/$tfile || true\n}\nrun_test 101a \"check read-ahead for random reads\"\n\nsetup_test101bc() {\n\ttest_mkdir $DIR/$tdir\n\tlocal ssize=$1\n\tlocal FILE_LENGTH=$2\n\tSTRIPE_OFFSET=0\n\n\tlocal FILE_SIZE_MB=$((FILE_LENGTH / ssize))\n\n\tlocal list=$(comma_list $(osts_nodes))\n\tset_osd_param $list '' read_cache_enable 0\n\tset_osd_param $list '' writethrough_cache_enable 0\n\n\ttrap cleanup_test101bc EXIT\n\t# prepare the read-ahead file\n\t$LFS setstripe -S $ssize -i $STRIPE_OFFSET -c $OSTCOUNT $DIR/$tfile\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=$ssize \\\n\t\t\t\tcount=$FILE_SIZE_MB 2> /dev/null\n\n}\n\ncleanup_test101bc() {\n\ttrap 0\n\trm -rf $DIR/$tdir\n\trm -f $DIR/$tfile\n\n\tlocal list=$(comma_list $(osts_nodes))\n\tset_osd_param $list '' read_cache_enable 1\n\tset_osd_param $list '' writethrough_cache_enable 1\n}\n\ncalc_total() {\n\tawk 'BEGIN{total=0}; {total+=$1}; END{print total}'\n}\n\nra_check_101() {\n\tlocal READ_SIZE=$1\n\tlocal STRIPE_SIZE=$2\n\tlocal FILE_LENGTH=$3\n\tlocal RA_INC=1048576\n\tlocal STRIDE_LENGTH=$((STRIPE_SIZE/READ_SIZE))\n\tlocal discard_limit=$((((STRIDE_LENGTH - 1)*3/(STRIDE_LENGTH*OSTCOUNT))* \\\n\t\t\t     (STRIDE_LENGTH*OSTCOUNT - STRIDE_LENGTH)))\n\tDISCARD=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t\tget_named_value 'read but discarded' |\n\t\t\tcut -d\" \" -f1 | calc_total)\n\tif [[ $DISCARD -gt $discard_limit ]]; then\n\t\t$LCTL get_param llite.*.read_ahead_stats\n\t\terror \"Too many ($DISCARD) discarded pages with size (${READ_SIZE})\"\n\telse\n\t\techo \"Read-ahead success for size ${READ_SIZE}\"\n\tfi\n}\n\ntest_101b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal STRIPE_SIZE=1048576\n\tlocal STRIDE_SIZE=$((STRIPE_SIZE*OSTCOUNT))\n\n\tif [ $SLOW == \"yes\" ]; then\n\t\tlocal FILE_LENGTH=$((STRIDE_SIZE * 64))\n\telse\n\t\tlocal FILE_LENGTH=$((STRIDE_SIZE * 8))\n\tfi\n\n\tlocal ITERATION=$((FILE_LENGTH / STRIDE_SIZE))\n\n\t# prepare the read-ahead file\n\tsetup_test101bc $STRIPE_SIZE $FILE_LENGTH\n\tcancel_lru_locks osc\n\tfor BIDX in 2 4 8 16 32 64 128 256\n\tdo\n\t\tlocal BSIZE=$((BIDX*4096))\n\t\tlocal READ_COUNT=$((STRIPE_SIZE/BSIZE))\n\t\tlocal STRIDE_LENGTH=$((STRIDE_SIZE/BSIZE))\n\t\tlocal OFFSET=$((STRIPE_SIZE/BSIZE*(OSTCOUNT - 1)))\n\t\t$LCTL set_param -n llite.*.read_ahead_stats 0\n\t\t$READS -f $DIR/$tfile  -l $STRIDE_LENGTH -o $OFFSET \\\n\t\t\t      -s $FILE_LENGTH -b $STRIPE_SIZE -a $READ_COUNT -n $ITERATION\n\t\tcancel_lru_locks osc\n\t\tra_check_101 $BSIZE $STRIPE_SIZE $FILE_LENGTH\n\tdone\n\tcleanup_test101bc\n\ttrue\n}\nrun_test 101b \"check stride-io mode read-ahead =================\"\n\ntest_101c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal STRIPE_SIZE=1048576\n\tlocal FILE_LENGTH=$((STRIPE_SIZE*100))\n\tlocal nreads=10000\n\tlocal rsize=65536\n\tlocal osc_rpc_stats\n\n\tsetup_test101bc $STRIPE_SIZE $FILE_LENGTH\n\n\tcancel_lru_locks osc\n\t$LCTL set_param osc.*.rpc_stats 0\n\t$READS -f $DIR/$tfile -s$FILE_LENGTH -b$rsize -n$nreads -t 180\n\t$LCTL get_param osc.*.rpc_stats\n\tfor osc_rpc_stats in $($LCTL get_param -N osc.*.rpc_stats); do\n\t\tlocal stats=$($LCTL get_param -n $osc_rpc_stats)\n\t\tlocal lines=$(echo \"$stats\" | awk 'END {print NR;}')\n\t\tlocal size\n\n\t\tif [ $lines -le 20 ]; then\n\t\t\techo \"continue debug\"\n\t\t\tcontinue\n\t\tfi\n\t\tfor size in 1 2 4 8; do\n\t\t\tlocal rpc=$(echo \"$stats\" |\n\t\t\t\t    awk '($1 == \"'$size':\") {print $2; exit; }')\n\t\t\t[ $rpc != 0 ] && ((size * PAGE_SIZE < rsize)) &&\n\t\t\t\terror \"Small $((size*PAGE_SIZE)) read IO $rpc!\"\n\t\tdone\n\t\techo \"$osc_rpc_stats check passed!\"\n\tdone\n\tcleanup_test101bc\n\ttrue\n}\nrun_test 101c \"check stripe_size aligned read-ahead =================\"\n\ntest_101d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal file=$DIR/$tfile\n\tlocal sz_MB=${FILESIZE_101d:-80}\n\tlocal ra_MB=${READAHEAD_MB:-40}\n\n\tlocal free_MB=$(($(df -P $DIR | tail -n 1 | awk '{ print $4 }') / 1024))\n\t[ $free_MB -lt $sz_MB ] &&\n\t\tskip \"Need free space ${sz_MB}M, have ${free_MB}M\"\n\n\techo \"Create test file $file size ${sz_MB}M, ${free_MB}M free\"\n\t$LFS setstripe -c -1 $file || error \"setstripe failed\"\n\n\tdd if=/dev/zero of=$file bs=1M count=$sz_MB || error \"dd failed\"\n\techo Cancel LRU locks on lustre client to flush the client cache\n\tcancel_lru_locks osc\n\n\techo Disable read-ahead\n\tlocal old_RA=$($LCTL get_param -n llite.*.max_read_ahead_mb | head -n 1)\n\t$LCTL set_param -n llite.*.max_read_ahead_mb=0\n\tstack_trap \"$LCTL set_param -n llite.*.max_read_ahead_mb $old_RA\" EXIT\n\t$LCTL get_param -n llite.*.max_read_ahead_mb\n\n\techo \"Reading the test file $file with read-ahead disabled\"\n\tlocal sz_KB=$((sz_MB * 1024 / 4))\n\t# 10485760 bytes transferred in 0.000938 secs (11179579337 bytes/sec)\n\t# 104857600 bytes (105 MB) copied, 0.00876352 s, 12.0 GB/s\n\tlocal raOFF=$(LANG=C dd if=$file of=/dev/null bs=4k count=$sz_KB |&\n\t\t      sed -e '/records/d' -e 's/.* \\([0-9]*\\.[0-9]*\\) *s.*/\\1/')\n\n\techo \"Cancel LRU locks on lustre client to flush the client cache\"\n\tcancel_lru_locks osc\n\techo Enable read-ahead with ${ra_MB}MB\n\t$LCTL set_param -n llite.*.max_read_ahead_mb=$ra_MB\n\n\techo \"Reading the test file $file with read-ahead enabled\"\n\tlocal raON=$(LANG=C dd if=$file of=/dev/null bs=4k count=$sz_KB |&\n\t\t     sed -e '/records/d' -e 's/.* \\([0-9]*\\.[0-9]*\\) *s.*/\\1/')\n\n\techo \"read-ahead disabled time read $raOFF\"\n\techo \"read-ahead enabled time read $raON\"\n\n\trm -f $file\n\twait_delete_completed\n\n\t# use awk for this check instead of bash because it handles decimals\n\tawk \"{ exit !($raOFF < 1.0 || $raOFF > $raON) }\" <<<\"ignore_me\" ||\n\t\terror \"readahead ${raON}s > no-readahead ${raOFF}s ${sz_MB}M\"\n}\nrun_test 101d \"file read with and without read-ahead enabled\"\n\ntest_101e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal file=$DIR/$tfile\n\tlocal size_KB=500  #KB\n\tlocal count=100\n\tlocal bsize=1024\n\n\tlocal free_KB=$(df -P $DIR | tail -n 1 | awk '{ print $4 }')\n\tlocal need_KB=$((count * size_KB))\n\t[[ $free_KB -le $need_KB ]] &&\n\t\tskip_env \"Need free space $need_KB, have $free_KB\"\n\n\techo \"Creating $count ${size_KB}K test files\"\n\tfor ((i = 0; i < $count; i++)); do\n\t\tdd if=/dev/zero of=$file.$i bs=$bsize count=$size_KB 2>/dev/null\n\tdone\n\n\techo \"Cancel LRU locks on lustre client to flush the client cache\"\n\tcancel_lru_locks $OSC\n\n\techo \"Reset readahead stats\"\n\t$LCTL set_param -n llite.*.read_ahead_stats 0\n\n\tfor ((i = 0; i < $count; i++)); do\n\t\tdd if=$file.$i of=/dev/null bs=$bsize count=$size_KB 2>/dev/null\n\tdone\n\n\tlocal miss=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t     get_named_value 'misses' | cut -d\" \" -f1 | calc_total)\n\n\tfor ((i = 0; i < $count; i++)); do\n\t\trm -rf $file.$i 2>/dev/null\n\tdone\n\n\t#10000 means 20% reads are missing in readahead\n\t[[ $miss -lt 10000 ]] ||  error \"misses too much for small reads\"\n}\nrun_test 101e \"check read-ahead for small read(1k) for small files(500k)\"\n\ntest_101f() {\n\twhich iozone || skip_env \"no iozone installed\"\n\n\tlocal old_debug=$($LCTL get_param debug)\n\told_debug=${old_debug#*=}\n\t$LCTL set_param debug=\"reada mmap\"\n\n\t# create a test file\n\tiozone -i 0 -+n -r 1m -s 128m -w -f $DIR/$tfile > /dev/null 2>&1\n\n\techo Cancel LRU locks on lustre client to flush the client cache\n\tcancel_lru_locks osc\n\n\techo Reset readahead stats\n\t$LCTL set_param -n llite.*.read_ahead_stats 0\n\n\techo mmap read the file with small block size\n\tiozone -i 1 -u 1 -l 1 -+n -r 32k -s 128m -B -f $DIR/$tfile \\\n\t\t> /dev/null 2>&1\n\n\techo checking missing pages\n\t$LCTL get_param llite.*.read_ahead_stats\n\tlocal miss=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t\tget_named_value 'misses' | cut -d\" \" -f1 | calc_total)\n\n\t$LCTL set_param debug=\"$old_debug\"\n\t[ $miss -lt 3 ] || error \"misses too much pages ('$miss')!\"\n\trm -f $DIR/$tfile\n}\nrun_test 101f \"check mmap read performance\"\n\ntest_101g_brw_size_test() {\n\tlocal mb=$1\n\tlocal pages=$((mb * 1048576 / PAGE_SIZE))\n\tlocal file=$DIR/$tfile\n\n\t$LCTL set_param osc.*.max_pages_per_rpc=${mb}M ||\n\t\t{ error \"unable to set max_pages_per_rpc=${mb}M\"; return 1; }\n\tfor mp in $($LCTL get_param -n osc.*.max_pages_per_rpc); do\n\t\t[ $mp -ne $pages ] && error \"max_pages_per_rpc $mp != $pages\" &&\n\t\t\treturn 2\n\tdone\n\n\tstack_trap \"rm -f $file\" EXIT\n\t$LCTL set_param -n osc.*.rpc_stats=0\n\n\t# 10 RPCs should be enough for the test\n\tlocal count=10\n\tdd if=/dev/zero of=$file bs=${mb}M count=$count ||\n\t\t{ error \"dd write ${mb} MB blocks failed\"; return 3; }\n\tcancel_lru_locks osc\n\tdd of=/dev/null if=$file bs=${mb}M count=$count ||\n\t\t{ error \"dd write ${mb} MB blocks failed\"; return 4; }\n\n\t# calculate number of full-sized read and write RPCs\n\trpcs=($($LCTL get_param -n 'osc.*.rpc_stats' |\n\t\tsed -n '/pages per rpc/,/^$/p' |\n\t\tawk '/'$pages':/ { reads += $2; writes += $6 }; \\\n\t\tEND { print reads,writes }'))\n\t[ ${rpcs[0]} -ne $count ] && error \"${rpcs[0]} != $count read RPCs\" &&\n\t\treturn 5\n\t[ ${rpcs[1]} -ne $count ] && error \"${rpcs[1]} != $count write RPCs\" &&\n\t\treturn 6\n\n\treturn 0\n}\n\ntest_101g() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal rpcs\n\tlocal osts=$(get_facets OST)\n\tlocal list=$(comma_list $(osts_nodes))\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tlocal brw_size=\"obdfilter.*.brw_size\"\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\n\tlocal orig_mb=$(do_facet ost1 $LCTL get_param -n $brw_size | head -n 1)\n\n\tif { [ $OST1_VERSION -ge $(version_code 2.8.52) ] ||\n\t\t{ [ $OST1_VERSION -ge $(version_code 2.7.17) ] &&\n\t\t  [ $OST1_VERSION -lt $(version_code 2.7.50) ]; }; } &&\n\t   { [ $CLIENT_VERSION -ge $(version_code 2.8.52) ] ||\n\t\t{ [ $CLIENT_VERSION -ge $(version_code 2.7.17) ] &&\n\t\t  [ $CLIENT_VERSION -lt $(version_code 2.7.50) ]; }; }; then\n\n\t\t[ $OST1_VERSION -ge $(version_code 2.9.52) ] &&\n\t\t\tsuffix=\"M\"\n\n\t\tif [[ $orig_mb -lt 16 ]]; then\n\t\t\tsave_lustre_params $osts \"$brw_size\" > $p\n\t\t\tdo_nodes $list $LCTL set_param -n $brw_size=16$suffix ||\n\t\t\t\terror \"set 16MB RPC size failed\"\n\n\t\t\techo \"remount client to enable new RPC size\"\n\t\t\tremount_client $MOUNT || error \"remount_client failed\"\n\t\tfi\n\n\t\ttest_101g_brw_size_test 16 || error \"16MB RPC test failed\"\n\t\t# should be able to set brw_size=12, but no rpc_stats for that\n\t\ttest_101g_brw_size_test 8 || error \"8MB RPC test failed\"\n\tfi\n\n\ttest_101g_brw_size_test 4 || error \"4MB RPC test failed\"\n\n\tif [[ $orig_mb -lt 16 ]]; then\n\t\trestore_lustre_params < $p\n\t\tremount_client $MOUNT || error \"remount_client restore failed\"\n\tfi\n\n\trm -f $p $DIR/$tfile\n}\nrun_test 101g \"Big bulk(4/16 MiB) readahead\"\n\ntest_101h() {\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=70 ||\n\t\terror \"dd 70M file failed\"\n\techo Cancel LRU locks on lustre client to flush the client cache\n\tcancel_lru_locks osc\n\n\techo \"Reset readahead stats\"\n\t$LCTL set_param -n llite.*.read_ahead_stats 0\n\n\techo \"Read 10M of data but cross 64M bundary\"\n\tdd if=$DIR/$tfile of=/dev/null bs=10M skip=6 count=1\n\tlocal miss=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t\tget_named_value 'misses' | cut -d\" \" -f1 | calc_total)\n\t[ $miss -eq 1 ] || error \"expected miss 1 but got $miss\"\n\trm -f $p $DIR/$tfile\n}\nrun_test 101h \"Readahead should cover current read window\"\n\ntest_101i() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=10 ||\n\t\terror \"dd 10M file failed\"\n\n\tlocal max_per_file_mb=$($LCTL get_param -n \\\n\t\tllite.*.max_read_ahead_per_file_mb 2>/dev/null)\n\tcancel_lru_locks osc\n\tstack_trap \"$LCTL set_param llite.*.max_read_ahead_per_file_mb=$max_per_file_mb\"\n\t$LCTL set_param llite.*.max_read_ahead_per_file_mb=1 ||\n\t\terror \"set max_read_ahead_per_file_mb to 1 failed\"\n\n\techo \"Reset readahead stats\"\n\t$LCTL set_param llite.*.read_ahead_stats=0\n\n\tdd if=$DIR/$tfile of=/dev/null bs=2M\n\n\t$LCTL get_param llite.*.read_ahead_stats\n\tlocal miss=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t     awk '/misses/ { print $2 }')\n\t[ $miss -eq 5 ] || error \"expected misses 5 but got $miss\"\n\trm -f $DIR/$tfile\n}\nrun_test 101i \"allow current readahead to exceed reservation\"\n\ntest_101j() {\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile ||\n\t\terror \"setstripe $DIR/$tfile failed\"\n\tlocal file_size=$((1048576 * 16))\n\tlocal old_ra=$($LCTL get_param -n llite.*.max_read_ahead_mb | head -n 1)\n\tstack_trap \"$LCTL set_param -n llite.*.max_read_ahead_mb $old_ra\" EXIT\n\n\techo Disable read-ahead\n\t$LCTL set_param -n llite.*.max_read_ahead_mb=0\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=$(($file_size / 1048576))\n\tfor blk in $PAGE_SIZE 1048576 $file_size; do\n\t\tcancel_lru_locks osc\n\t\techo \"Reset readahead stats\"\n\t\t$LCTL set_param -n llite.*.read_ahead_stats=0\n\t\tlocal count=$(($file_size / $blk))\n\t\tdd if=$DIR/$tfile bs=$blk count=$count of=/dev/null\n\t\tlocal miss=$($LCTL get_param -n llite.*.read_ahead_stats |\n\t\t\t     get_named_value 'failed to fast read' |\n\t\t\t     cut -d\" \" -f1 | calc_total)\n\t\t$LCTL get_param -n llite.*.read_ahead_stats\n\t\t[ $miss -eq $count ] || error \"expected $count got $miss\"\n\tdone\n\n\trm -f $p $DIR/$tfile\n}\nrun_test 101j \"A complete read block should be submitted when no RA\"\n\nsetup_test102() {\n\ttest_mkdir $DIR/$tdir\n\tchown $RUNAS_ID $DIR/$tdir\n\tSTRIPE_SIZE=65536\n\tSTRIPE_OFFSET=1\n\tSTRIPE_COUNT=$OSTCOUNT\n\t[[ $OSTCOUNT -gt 4 ]] && STRIPE_COUNT=4\n\n\ttrap cleanup_test102 EXIT\n\tcd $DIR\n\t$1 $LFS setstripe -S $STRIPE_SIZE -i $STRIPE_OFFSET -c $STRIPE_COUNT $tdir\n\tcd $DIR/$tdir\n\tfor num in 1 2 3 4; do\n\t\tfor count in $(seq 1 $STRIPE_COUNT); do\n\t\t\tfor idx in $(seq 0 $[$STRIPE_COUNT - 1]); do\n\t\t\t\tlocal size=`expr $STRIPE_SIZE \\* $num`\n\t\t\t\tlocal file=file\"$num-$idx-$count\"\n\t\t\t\t$1 $LFS setstripe -S $size -i $idx -c $count $file\n\t\t\tdone\n\t\tdone\n\tdone\n\n\tcd $DIR\n\t$1 tar cf $TMP/f102.tar $tdir --xattrs\n}\n\ncleanup_test102() {\n\ttrap 0\n\trm -f $TMP/f102.tar\n\trm -rf $DIR/d0.sanity/d102\n}\n\ntest_102a() {\n\t[ \"$UID\" != 0 ] && skip \"must run as root\"\n\t[ -z \"$(lctl get_param -n mdc.*-mdc-*.connect_flags | grep xattr)\" ] &&\n\t\tskip_env \"must have user_xattr\"\n\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find setfattr\"\n\n\tlocal testfile=$DIR/$tfile\n\n\ttouch $testfile\n\techo \"set/get xattr...\"\n\tsetfattr -n trusted.name1 -v value1 $testfile ||\n\t\terror \"setfattr -n trusted.name1=value1 $testfile failed\"\n\tgetfattr -n trusted.name1 $testfile 2> /dev/null |\n\t  grep \"trusted.name1=.value1\" ||\n\t\terror \"$testfile missing trusted.name1=value1\"\n\n\tsetfattr -n user.author1 -v author1 $testfile ||\n\t\terror \"setfattr -n user.author1=author1 $testfile failed\"\n\tgetfattr -n user.author1 $testfile 2> /dev/null |\n\t  grep \"user.author1=.author1\" ||\n\t\terror \"$testfile missing trusted.author1=author1\"\n\n\techo \"listxattr...\"\n\tsetfattr -n trusted.name2 -v value2 $testfile ||\n\t\terror \"$testfile unable to set trusted.name2\"\n\tsetfattr -n trusted.name3 -v value3 $testfile ||\n\t\terror \"$testfile unable to set trusted.name3\"\n\t[ $(getfattr -d -m \"^trusted\" $testfile 2> /dev/null |\n\t    grep \"trusted.name\" | wc -l) -eq 3 ] ||\n\t\terror \"$testfile missing 3 trusted.name xattrs\"\n\n\tsetfattr -n user.author2 -v author2 $testfile ||\n\t\terror \"$testfile unable to set user.author2\"\n\tsetfattr -n user.author3 -v author3 $testfile ||\n\t\terror \"$testfile unable to set user.author3\"\n\t[ $(getfattr -d -m \"^user\" $testfile 2> /dev/null |\n\t    grep \"user.author\" | wc -l) -eq 3 ] ||\n\t\terror \"$testfile missing 3 user.author xattrs\"\n\n\techo \"remove xattr...\"\n\tsetfattr -x trusted.name1 $testfile ||\n\t\terror \"$testfile error deleting trusted.name1\"\n\tgetfattr -d -m trusted $testfile 2> /dev/null | grep \"trusted.name1\" &&\n\t\terror \"$testfile did not delete trusted.name1 xattr\"\n\n\tsetfattr -x user.author1 $testfile ||\n\t\terror \"$testfile error deleting user.author1\"\n\techo \"set lustre special xattr ...\"\n\t$LFS setstripe -c1 $testfile\n\tlocal lovea=$(getfattr -n \"trusted.lov\" -e hex $testfile |\n\t\tawk -F \"=\" '/trusted.lov/ { print $2 }' )\n\tsetfattr -n \"trusted.lov\" -v $lovea $testfile ||\n\t\terror \"$testfile doesn't ignore setting trusted.lov again\"\n\tsetfattr -n \"trusted.lov\" -v \"invalid_value\" $testfile &&\n\t\terror \"$testfile allow setting invalid trusted.lov\"\n\trm -f $testfile\n}\nrun_test 102a \"user xattr test ==================================\"\n\ncheck_102b_layout() {\n\tlocal layout=\"$*\"\n\tlocal testfile=$DIR/$tfile\n\n\techo \"test layout '$layout'\"\n\t$LFS setstripe $layout $testfile || error \"setstripe failed\"\n\t$LFS getstripe -y $testfile\n\n\techo \"get/set/list trusted.lov xattr ...\" # b=10930\n\tlocal value=$(getfattr -n trusted.lov -e hex $testfile | grep trusted)\n\t[[ \"$value\" =~ \"trusted.lov\" ]] ||\n\t\terror \"can't get trusted.lov from $testfile\"\n\tlocal stripe_count_orig=$($LFS getstripe -c $testfile) ||\n\t\terror \"getstripe failed\"\n\n\t$MCREATE $testfile.2 || error \"mcreate $testfile.2 failed\"\n\n\tvalue=$(cut -d= -f2 <<<$value)\n\t# LU-13168: truncated xattr should fail if short lov_user_md header\n\t[ $CLIENT_VERSION -lt $(version_code 2.13.53) ] &&\n\t\tlens=\"${#value}\" || lens=\"$(seq 4 2 ${#value})\"\n\tfor len in $lens; do\n\t\techo \"setfattr $len $testfile.2\"\n\t\tsetfattr -n trusted.lov -v ${value:0:$len} $testfile.2 &&\n\t\t\t[ $len -lt 66 ] && error \"short xattr len=$len worked\"\n\tdone\n\tlocal stripe_size=$($LFS getstripe -S $testfile.2)\n\tlocal stripe_count=$($LFS getstripe -c $testfile.2)\n\t[[ $stripe_size -eq 65536 ]] ||\n\t\terror \"stripe size $stripe_size != 65536\"\n\t[[ $stripe_count -eq $stripe_count_orig ]] ||\n\t\terror \"stripe count $stripe_count != $stripe_count_orig\"\n\trm $testfile $testfile.2\n}\n\ntest_102b() {\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find setfattr\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\t# check plain layout\n\tcheck_102b_layout -S 65536 -i 1 -c $OSTCOUNT\n\n\t# and also check composite layout\n\tcheck_102b_layout -E 1M -S 65536 -i 1 -c $OSTCOUNT -Eeof -S4M\n\n}\nrun_test 102b \"getfattr/setfattr for trusted.lov EAs\"\n\ntest_102c() {\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find setfattr\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\t# b10930: get/set/list lustre.lov xattr\n\techo \"get/set/list lustre.lov xattr ...\"\n\ttest_mkdir $DIR/$tdir\n\tchown $RUNAS_ID $DIR/$tdir\n\tlocal testfile=$DIR/$tdir/$tfile\n\t$RUNAS $LFS setstripe -S 65536 -i 1 -c $OSTCOUNT $testfile ||\n\t\terror \"setstripe failed\"\n\tlocal STRIPECOUNT=$($RUNAS $LFS getstripe -c $testfile) ||\n\t\terror \"getstripe failed\"\n\t$RUNAS getfattr -d -m \"^lustre\" $testfile 2> /dev/null | \\\n\tgrep \"lustre.lov\" || error \"can't get lustre.lov from $testfile\"\n\n\tlocal testfile2=${testfile}2\n\tlocal value=`getfattr -n lustre.lov $testfile 2> /dev/null | \\\n\t\t     grep \"lustre.lov\" |sed -e 's/[^=]\\+=//'  `\n\n\t$RUNAS $MCREATE $testfile2\n\t$RUNAS setfattr -n lustre.lov -v $value $testfile2\n\tlocal stripe_size=$($RUNAS $LFS getstripe -S $testfile2)\n\tlocal stripe_count=$($RUNAS $LFS getstripe -c $testfile2)\n\t[ $stripe_size -eq 65536 ] || error \"stripe size $stripe_size != 65536\"\n\t[ $stripe_count -eq $STRIPECOUNT ] ||\n\t\terror \"stripe count $stripe_count != $STRIPECOUNT\"\n}\nrun_test 102c \"non-root getfattr/setfattr for lustre.lov EAs ===========\"\n\ncompare_stripe_info1() {\n\tlocal stripe_index_all_zero=true\n\n\tfor num in 1 2 3 4; do\n\t\tfor count in $(seq 1 $STRIPE_COUNT); do\n\t\t\tfor offset in $(seq 0 $[$STRIPE_COUNT - 1]); do\n\t\t\t\tlocal size=$((STRIPE_SIZE * num))\n\t\t\t\tlocal file=file\"$num-$offset-$count\"\n\t\t\t\tstripe_size=$($LFS getstripe -S $PWD/$file)\n\t\t\t\t[[ $stripe_size -ne $size ]] &&\n\t\t\t\t    error \"$file: size $stripe_size != $size\"\n\t\t\t\tstripe_count=$($LFS getstripe -c $PWD/$file)\n\t\t\t\t# allow fewer stripes to be created, ORI-601\n\t\t\t\t[[ $stripe_count -lt $(((3 * count + 3) / 4)) ]] &&\n\t\t\t\t    error \"$file: count $stripe_count != $count\"\n\t\t\t\tstripe_index=$($LFS getstripe -i $PWD/$file)\n\t\t\t\t[[ $stripe_index -ne 0 ]] &&\n\t\t\t\t\tstripe_index_all_zero=false\n\t\t\tdone\n\t\tdone\n\tdone\n\t$stripe_index_all_zero &&\n\t\terror \"all files are being extracted starting from OST index 0\"\n\treturn 0\n}\n\nhave_xattrs_include() {\n\ttar --help | grep -q xattrs-include &&\n\t\techo --xattrs-include=\"lustre.*\"\n}\n\ntest_102d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tXINC=$(have_xattrs_include)\n\tsetup_test102\n\ttar xf $TMP/f102.tar -C $DIR/$tdir --xattrs $XINC\n\tcd $DIR/$tdir/$tdir\n\tcompare_stripe_info1\n}\nrun_test 102d \"tar restore stripe info from tarfile,not keep osts\"\n\ntest_102f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tXINC=$(have_xattrs_include)\n\tsetup_test102\n\ttest_mkdir $DIR/$tdir.restore\n\tcd $DIR\n\ttar cf - --xattrs $tdir | tar xf - \\\n\t\t-C $DIR/$tdir.restore --xattrs $XINC\n\tcd $DIR/$tdir.restore/$tdir\n\tcompare_stripe_info1\n}\nrun_test 102f \"tar copy files, not keep osts\"\n\ngrow_xattr() {\n\t[ -z \"$(lctl get_param -n mdc.*.connect_flags | grep xattr)\" ] &&\n\t\tskip \"must have user_xattr\"\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find setfattr\"\n\t[ -z \"$(which getfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find getfattr\"\n\n\tlocal xsize=${1:-1024}\t# in bytes\n\tlocal file=$DIR/$tfile\n\tlocal value=\"$(generate_string $xsize)\"\n\tlocal xbig=trusted.big\n\tlocal toobig=$2\n\n\ttouch $file\n\tlog \"save $xbig on $file\"\n\tif [ -z \"$toobig\" ]\n\tthen\n\t\tsetfattr -n $xbig -v $value $file ||\n\t\t\terror \"saving $xbig on $file failed\"\n\telse\n\t\tsetfattr -n $xbig -v $value $file &&\n\t\t\terror \"saving $xbig on $file succeeded\"\n\t\treturn 0\n\tfi\n\n\tlocal orig=$(get_xattr_value $xbig $file)\n\t[[ \"$orig\" != \"$value\" ]] && error \"$xbig different after saving $xbig\"\n\n\tlocal xsml=trusted.sml\n\tlog \"save $xsml on $file\"\n\tsetfattr -n $xsml -v val $file || error \"saving $xsml on $file failed\"\n\n\tlocal new=$(get_xattr_value $xbig $file)\n\t[[ \"$new\" != \"$orig\" ]] && error \"$xbig different after saving $xsml\"\n\n\tlog \"grow $xsml on $file\"\n\tsetfattr -n $xsml -v \"$value\" $file ||\n\t\terror \"growing $xsml on $file failed\"\n\n\tnew=$(get_xattr_value $xbig $file)\n\t[[ \"$new\" != \"$orig\" ]] && error \"$xbig different after growing $xsml\"\n\tlog \"$xbig still valid after growing $xsml\"\n\n\trm -f $file\n}\n\ntest_102h() { # bug 15777\n\tgrow_xattr 1024\n}\nrun_test 102h \"grow xattr from inside inode to external block\"\n\ntest_102ha() {\n\tlarge_xattr_enabled || skip_env \"ea_inode feature disabled\"\n\n\techo \"setting xattr of max xattr size: $(max_xattr_size)\"\n\tgrow_xattr $(max_xattr_size)\n\n\techo \"setting xattr of > max xattr size: $(max_xattr_size) + 10\"\n\techo \"This should fail:\"\n\tgrow_xattr $(($(max_xattr_size) + 10)) 1\n}\nrun_test 102ha \"grow xattr from inside inode to external inode\"\n\ntest_102i() { # bug 17038\n\t[ -z \"$(which getfattr 2>/dev/null)\" ] &&\n\t\tskip \"could not find getfattr\"\n\n\ttouch $DIR/$tfile\n\tln -s $DIR/$tfile $DIR/${tfile}link\n\tgetfattr -n trusted.lov $DIR/$tfile ||\n\t\terror \"lgetxattr on $DIR/$tfile failed\"\n\tgetfattr -h -n trusted.lov $DIR/${tfile}link 2>&1 |\n\t\tgrep -i \"no such attr\" ||\n\t\terror \"error for lgetxattr on $DIR/${tfile}link is not ENODATA\"\n\trm -f $DIR/$tfile $DIR/${tfile}link\n}\nrun_test 102i \"lgetxattr test on symbolic link ============\"\n\ntest_102j() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tXINC=$(have_xattrs_include)\n\tsetup_test102 \"$RUNAS\"\n\tchown $RUNAS_ID $DIR/$tdir\n\t$RUNAS tar xf $TMP/f102.tar -C $DIR/$tdir --xattrs $XINC\n\tcd $DIR/$tdir/$tdir\n\tcompare_stripe_info1 \"$RUNAS\"\n}\nrun_test 102j \"non-root tar restore stripe info from tarfile, not keep osts ===\"\n\ntest_102k() {\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip \"could not find setfattr\"\n\n\ttouch $DIR/$tfile\n\t# b22187 just check that does not crash for regular file.\n\tsetfattr -n trusted.lov $DIR/$tfile\n\t# b22187 'setfattr -n trusted.lov' should remove LOV EA for directories\n\tlocal test_kdir=$DIR/$tdir\n\ttest_mkdir $test_kdir\n\tlocal default_size=$($LFS getstripe -S $test_kdir)\n\tlocal default_count=$($LFS getstripe -c $test_kdir)\n\tlocal default_offset=$($LFS getstripe -i $test_kdir)\n\t$LFS setstripe -S 65536 -i 0 -c $OSTCOUNT $test_kdir ||\n\t\terror 'dir setstripe failed'\n\tsetfattr -n trusted.lov $test_kdir\n\tlocal stripe_size=$($LFS getstripe -S $test_kdir)\n\tlocal stripe_count=$($LFS getstripe -c $test_kdir)\n\tlocal stripe_offset=$($LFS getstripe -i $test_kdir)\n\t[ $stripe_size -eq $default_size ] ||\n\t\terror \"stripe size $stripe_size != $default_size\"\n\t[ $stripe_count -eq $default_count ] ||\n\t\terror \"stripe count $stripe_count != $default_count\"\n\t[ $stripe_offset -eq $default_offset ] ||\n\t\terror \"stripe offset $stripe_offset != $default_offset\"\n\trm -rf $DIR/$tfile $test_kdir\n}\nrun_test 102k \"setfattr without parameter of value shouldn't cause a crash\"\n\ntest_102l() {\n\t[ -z \"$(which getfattr 2>/dev/null)\" ] &&\n\t\tskip \"could not find getfattr\"\n\n\t# LU-532 trusted. xattr is invisible to non-root\n\tlocal testfile=$DIR/$tfile\n\n\ttouch $testfile\n\n\techo \"listxattr as user...\"\n\tchown $RUNAS_ID $testfile\n\t$RUNAS getfattr -d -m '.*' $testfile 2>&1 |\n\t    grep -q \"trusted\" &&\n\t\terror \"$testfile trusted xattrs are user visible\"\n\n\treturn 0;\n}\nrun_test 102l \"listxattr size test ==================================\"\n\ntest_102m() { # LU-3403 llite: error of listxattr when buffer is small\n\tlocal path=$DIR/$tfile\n\ttouch $path\n\n\tlistxattr_size_check $path || error \"listattr_size_check $path failed\"\n}\nrun_test 102m \"Ensure listxattr fails on small bufffer ========\"\n\ncleanup_test102\n\ngetxattr() { # getxattr path name\n\t# Return the base64 encoding of the value of xattr name on path.\n\tlocal path=$1\n\tlocal name=$2\n\n\t# # getfattr --absolute-names --encoding=base64 --name=trusted.lov $path\n\t# file: $path\n\t# trusted.lov=0s0AvRCwEAAAAGAAAAAAAAAAAEAAACAAAAAAAQAAEAA...AAAAAAAAA=\n\t#\n\t# We print just 0s0AvRCwEAAAAGAAAAAAAAAAAEAAACAAAAAAAQAAEAA...AAAAAAAAA=\n\n\tgetfattr --absolute-names --encoding=base64 --name=$name $path |\n\t\tawk -F= -v name=$name '$1 == name {\n\t\t\tprint substr($0, index($0, \"=\") + 1);\n\t}'\n}\n\ntest_102n() { # LU-4101 mdt: protect internal xattrs\n\t[ -z \"$(which setfattr 2>/dev/null)\" ] &&\n\t\tskip \"could not find setfattr\"\n\tif [ $MDS1_VERSION -lt $(version_code 2.5.50) ]\n\tthen\n\t\tskip \"MDT < 2.5.50 allows setxattr on internal trusted xattrs\"\n\tfi\n\n\tlocal file0=$DIR/$tfile.0\n\tlocal file1=$DIR/$tfile.1\n\tlocal xattr0=$TMP/$tfile.0\n\tlocal xattr1=$TMP/$tfile.1\n\tlocal namelist=\"lov lma lmv link fid version som hsm\"\n\tlocal name\n\tlocal value\n\n\trm -rf $file0 $file1 $xattr0 $xattr1\n\ttouch $file0 $file1\n\n\t# Get 'before' xattrs of $file1.\n\tgetfattr --absolute-names --dump --match=- $file1 > $xattr0\n\n\t[ $MDS1_VERSION -lt $(version_code 2.8.53) ] &&\n\t\tnamelist+=\" lfsck_namespace\"\n\tfor name in $namelist; do\n\t\t# Try to copy xattr from $file0 to $file1.\n\t\tvalue=$(getxattr $file0 trusted.$name 2> /dev/null)\n\n\t\tsetfattr --name=trusted.$name --value=\"$value\" $file1 ||\n\t\t\terror \"setxattr 'trusted.$name' failed\"\n\n\t\t# Try to set a garbage xattr.\n\t\tvalue=0sVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIGl0c2VsZi4=\n\n\t\tif [[ x$name == \"xlov\" ]]; then\n\t\t\tsetfattr --name=trusted.lov --value=\"$value\" $file1 &&\n\t\t\terror \"setxattr invalid 'trusted.lov' success\"\n\t\telse\n\t\t\tsetfattr --name=trusted.$name --value=\"$value\" $file1 ||\n\t\t\t\terror \"setxattr invalid 'trusted.$name' failed\"\n\t\tfi\n\n\t\t# Try to remove the xattr from $file1. We don't care if this\n\t\t# appears to succeed or fail, we just don't want there to be\n\t\t# any changes or crashes.\n\t\tsetfattr --remove=$trusted.$name $file1 2> /dev/null\n\tdone\n\n\tif [ $MDS1_VERSION -gt $(version_code 2.6.50) ]\n\tthen\n\t\tname=\"lfsck_ns\"\n\t\t# Try to copy xattr from $file0 to $file1.\n\t\tvalue=$(getxattr $file0 trusted.$name 2> /dev/null)\n\n\t\tsetfattr --name=trusted.$name --value=\"$value\" $file1 ||\n\t\t\terror \"setxattr 'trusted.$name' failed\"\n\n\t\t# Try to set a garbage xattr.\n\t\tvalue=0sVGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIGl0c2VsZi4=\n\n\t\tsetfattr --name=trusted.$name --value=\"$value\" $file1 ||\n\t\t\terror \"setxattr 'trusted.$name' failed\"\n\n\t\t# Try to remove the xattr from $file1. We don't care if this\n\t\t# appears to succeed or fail, we just don't want there to be\n\t\t# any changes or crashes.\n\t\tsetfattr --remove=$trusted.$name $file1 2> /dev/null\n\tfi\n\n\t# Get 'after' xattrs of file1.\n\tgetfattr --absolute-names --dump --match=- $file1 > $xattr1\n\n\tif ! diff $xattr0 $xattr1; then\n\t\terror \"before and after xattrs of '$file1' differ\"\n\tfi\n\n\trm -rf $file0 $file1 $xattr0 $xattr1\n\n\treturn 0\n}\nrun_test 102n \"silently ignore setxattr on internal trusted xattrs\"\n\ntest_102p() { # LU-4703 setxattr did not check ownership\n\t[ $MDS1_VERSION -lt $(version_code 2.5.56) ] &&\n\t\tskip \"MDS needs to be at least 2.5.56\"\n\n\tlocal testfile=$DIR/$tfile\n\n\ttouch $testfile\n\n\techo \"setfacl as user...\"\n\t$RUNAS setfacl -m \"u:$RUNAS_ID:rwx\" $testfile\n\t[ $? -ne 0 ] || error \"setfacl by $RUNAS_ID was allowed on $testfile\"\n\n\techo \"setfattr as user...\"\n\tsetfacl -m \"u:$RUNAS_ID:---\" $testfile\n\t$RUNAS setfattr -x system.posix_acl_access $testfile\n\t[ $? -ne 0 ] || error \"setfattr by $RUNAS_ID was allowed on $testfile\"\n}\nrun_test 102p \"check setxattr(2) correctly fails without permission\"\n\ntest_102q() {\n\t[ $MDS1_VERSION -lt $(version_code 2.6.92) ] &&\n\t\tskip \"MDS needs to be at least 2.6.92\"\n\n\torphan_linkea_check $DIR/$tfile || error \"orphan_linkea_check\"\n}\nrun_test 102q \"flistxattr should not return trusted.link EAs for orphans\"\n\ntest_102r() {\n\t[ $MDS1_VERSION -lt $(version_code 2.6.93) ] &&\n\t\tskip \"MDS needs to be at least 2.6.93\"\n\n\ttouch $DIR/$tfile || error \"touch\"\n\tsetfattr -n user.$(basename $tfile) $DIR/$tfile || error \"setfattr\"\n\tgetfattr -n user.$(basename $tfile) $DIR/$tfile || error \"getfattr\"\n\trm $DIR/$tfile || error \"rm\"\n\n\t#normal directory\n\tmkdir -p $DIR/$tdir || error \"mkdir\"\n\tsetfattr -n user.$(basename $tdir) $DIR/$tdir || error \"setfattr dir\"\n\tgetfattr -n user.$(basename $tdir) $DIR/$tdir || error \"getfattr dir\"\n\tsetfattr -x user.$(basename $tdir) $DIR/$tdir ||\n\t\terror \"$testfile error deleting user.author1\"\n\tgetfattr -d -m user.$(basename $tdir) 2> /dev/null |\n\t\tgrep \"user.$(basename $tdir)\" &&\n\t\terror \"$tdir did not delete user.$(basename $tdir)\"\n\trmdir $DIR/$tdir || error \"rmdir\"\n\n\t#striped directory\n\ttest_mkdir $DIR/$tdir\n\tsetfattr -n user.$(basename $tdir) $DIR/$tdir || error \"setfattr dir\"\n\tgetfattr -n user.$(basename $tdir) $DIR/$tdir || error \"getfattr dir\"\n\tsetfattr -x user.$(basename $tdir) $DIR/$tdir ||\n\t\terror \"$testfile error deleting user.author1\"\n\tgetfattr -d -m user.$(basename $tdir) 2> /dev/null |\n\t\tgrep \"user.$(basename $tdir)\" &&\n\t\terror \"$tdir did not delete user.$(basename $tdir)\"\n\trmdir $DIR/$tdir || error \"rm striped dir\"\n}\nrun_test 102r \"set EAs with empty values\"\n\ntest_102s() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"MDS needs to be at least 2.11.52\"\n\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $save\n\n\tfor cache in 0 1; do\n\t\tlctl set_param llite.*.xattr_cache=$cache\n\n\t\trm -f $DIR/$tfile\n\t\ttouch $DIR/$tfile || error \"touch\"\n\t\tfor prefix in lustre security system trusted user; do\n\t\t\t# Note getxattr() may fail with 'Operation not\n\t\t\t# supported' or 'No such attribute' depending\n\t\t\t# on prefix and cache.\n\t\t\tgetfattr -n $prefix.n102s $DIR/$tfile &&\n\t\t\t\terror \"getxattr '$prefix.n102s' should fail (cache = $cache)\"\n\t\tdone\n\tdone\n\n\trestore_lustre_params < $save\n}\nrun_test 102s \"getting nonexistent xattrs should fail\"\n\ntest_102t() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"MDS needs to be at least 2.11.52\"\n\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $save\n\n\tfor cache in 0 1; do\n\t\tlctl set_param llite.*.xattr_cache=$cache\n\n\t\tfor buf_size in 0 256; do\n\t\t\trm -f $DIR/$tfile\n\t\t\ttouch $DIR/$tfile || error \"touch\"\n\t\t\tsetfattr -n user.multiop $DIR/$tfile\n\t\t\t$MULTIOP $DIR/$tfile oa$buf_size ||\n\t\t\t\terror \"cannot get zero length xattr value (buf_size = $buf_size)\"\n\t\tdone\n\tdone\n\n\trestore_lustre_params < $save\n}\nrun_test 102t \"zero length xattr values handled correctly\"\n\nrun_acl_subtest()\n{\n    $LUSTRE/tests/acl/run $LUSTRE/tests/acl/$1.test\n    return $?\n}\n\ntest_103a() {\n\t[ \"$UID\" != 0 ] && skip \"must run as root\"\n\t$GSS && skip_env \"could not run under gss\"\n\t[ -z \"$(lctl get_param -n mdc.*-mdc-*.connect_flags | grep acl)\" ] &&\n\t\tskip_env \"must have acl enabled\"\n\t[ -z \"$(which setfacl 2>/dev/null)\" ] &&\n\t\tskip_env \"could not find setfacl\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tgpasswd -a daemon bin\t\t\t\t# LU-5641\n\tdo_facet $SINGLEMDS gpasswd -a daemon bin\t# LU-5641\n\n\tdeclare -a identity_old\n\n\tfor num in $(seq $MDSCOUNT); do\n\t\tswitch_identity $num true || identity_old[$num]=$?\n\tdone\n\n\tSAVE_UMASK=$(umask)\n\tumask 0022\n\tmkdir -p $DIR/$tdir\n\tcd $DIR/$tdir\n\n\techo \"performing cp ...\"\n\trun_acl_subtest cp || error \"run_acl_subtest cp failed\"\n\techo \"performing getfacl-noacl...\"\n\trun_acl_subtest getfacl-noacl || error \"getfacl-noacl test failed\"\n\techo \"performing misc...\"\n\trun_acl_subtest misc || error  \"misc test failed\"\n\techo \"performing permissions...\"\n\trun_acl_subtest permissions || error \"permissions failed\"\n\t# LU-1482 mdd: Setting xattr are properly checked with and without ACLs\n\tif [ $MDS1_VERSION -gt $(version_code 2.8.55) ] ||\n\t\t{ [ $MDS1_VERSION -lt $(version_code 2.6) ] &&\n\t\t\t[ $MDS1_VERSION -ge $(version_code 2.5.29) ]; }\n\tthen\n\t\techo \"performing permissions xattr...\"\n\t\trun_acl_subtest permissions_xattr ||\n\t\t\terror \"permissions_xattr failed\"\n\tfi\n\techo \"performing setfacl...\"\n\trun_acl_subtest setfacl || error  \"setfacl test failed\"\n\n\t# inheritance test got from HP\n\techo \"performing inheritance...\"\n\tcp $LUSTRE/tests/acl/make-tree . || error \"cannot copy make-tree\"\n\tchmod +x make-tree || error \"chmod +x failed\"\n\trun_acl_subtest inheritance || error \"inheritance test failed\"\n\trm -f make-tree\n\n\techo \"LU-974 ignore umask when acl is enabled...\"\n\trun_acl_subtest 974 || error \"LU-974 umask test failed\"\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\trun_acl_subtest 974_remote ||\n\t\t\terror \"LU-974 umask test failed under remote dir\"\n\tfi\n\n\techo \"LU-2561 newly created file is same size as directory...\"\n\tif [ \"$mds1_FSTYPE\" != \"zfs\" ]; then\n\t\trun_acl_subtest 2561 || error \"LU-2561 test failed\"\n\telse\n\t\trun_acl_subtest 2561_zfs || error \"LU-2561 zfs test failed\"\n\tfi\n\n\trun_acl_subtest 4924 || error \"LU-4924 test failed\"\n\n\tcd $SAVE_PWD\n\tumask $SAVE_UMASK\n\n\tfor num in $(seq $MDSCOUNT); do\n\t\tif [ \"${identity_old[$num]}\" = 1 ]; then\n\t\t\tswitch_identity $num false || identity_old[$num]=$?\n\t\tfi\n\tdone\n}\nrun_test 103a \"acl test\"\n\ntest_103b() {\n\tdeclare -a pids\n\tlocal U\n\n\tfor U in {0..511}; do\n\t\t{\n\t\tlocal O=$(printf \"%04o\" $U)\n\n\t\tumask $(printf \"%04o\" $((511 ^ $O)))\n\t\t$LFS setstripe -c 1 $DIR/$tfile.s$O\n\t\tlocal S=$(printf \"%04o\" 0$(stat -c%a $DIR/$tfile.s$O))\n\n\t\t(( $S == ($O & 0666) )) ||\n\t\t\terror \"lfs setstripe $DIR/$tfile.s$O '$S' != '$O'\"\n\n\t\t$LFS setstripe -E16M -c 1 -E1G -S4M $DIR/$tfile.p$O\n\t\tS=$(printf \"%04o\" 0$(stat -c%a $DIR/$tfile.p$O))\n\t\t(( $S == ($O & 0666) )) ||\n\t\t\terror \"lfs setstripe -E $DIR/$tfile.p$O '$S' != '$O'\"\n\n\t\t$LFS setstripe -N2 -c 1 $DIR/$tfile.m$O\n\t\tS=$(printf \"%04o\" 0$(stat -c%a $DIR/$tfile.m$O))\n\t\t(( $S == ($O & 0666) )) ||\n\t\t\terror \"lfs setstripe -N2 $DIR/$tfile.m$O '$S' != '$O'\"\n\t\trm -f $DIR/$tfile.[smp]$0\n\t\t} &\n\t\tlocal pid=$!\n\n\t\t# limit the concurrently running threads to 64. LU-11878\n\t\tlocal idx=$((U % 64))\n\t\t[ -z \"${pids[idx]}\" ] || wait ${pids[idx]}\n\t\tpids[idx]=$pid\n\tdone\n\twait\n}\nrun_test 103b \"umask lfs setstripe\"\n\ntest_103c() {\n\tmkdir -p $DIR/$tdir\n\tcp -rp $DIR/$tdir $DIR/$tdir.bak\n\n\t[ -n \"$(getfattr -d -m. $DIR/$tdir | grep posix_acl_default)\" ] &&\n\t\terror \"$DIR/$tdir shouldn't contain default ACL\"\n\t[ -n \"$(getfattr -d -m. $DIR/$tdir.bak | grep posix_acl_default)\" ] &&\n\t\terror \"$DIR/$tdir.bak shouldn't contain default ACL\"\n\ttrue\n}\nrun_test 103c \"'cp -rp' won't set empty acl\"\n\ntest_104a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttouch $DIR/$tfile\n\tlfs df || error \"lfs df failed\"\n\tlfs df -ih || error \"lfs df -ih failed\"\n\tlfs df -h $DIR || error \"lfs df -h $DIR failed\"\n\tlfs df -i $DIR || error \"lfs df -i $DIR failed\"\n\tlfs df $DIR/$tfile || error \"lfs df $DIR/$tfile failed\"\n\tlfs df -ih $DIR/$tfile || error \"lfs df -ih $DIR/$tfile failed\"\n\n\tlocal OSC=$(lctl dl | grep OST0000-osc-[^M] | awk '{ print $4 }')\n\tlctl --device %$OSC deactivate\n\tlfs df || error \"lfs df with deactivated OSC failed\"\n\tlctl --device %$OSC activate\n\t# wait the osc back to normal\n\twait_osc_import_ready client ost\n\n\tlfs df || error \"lfs df with reactivated OSC failed\"\n\trm -f $DIR/$tfile\n}\nrun_test 104a \"lfs df [-ih] [path] test =========================\"\n\ntest_104b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $RUNAS_ID -eq $UID ] &&\n\t\tskip_env \"RUNAS_ID = UID = $UID -- skipping\"\n\n\tdenied_cnt=$(($($RUNAS $LFS check servers 2>&1 |\n\t\t\tgrep \"Permission denied\" | wc -l)))\n\tif [ $denied_cnt -ne 0 ]; then\n\t\terror \"lfs check servers test failed\"\n\tfi\n}\nrun_test 104b \"$RUNAS lfs check servers test ====================\"\n\ntest_105a() {\n\t# doesn't work on 2.4 kernels\n\ttouch $DIR/$tfile\n\tif $(flock_is_enabled); then\n\t\tflocks_test 1 on -f $DIR/$tfile || error \"fail flock on\"\n\telse\n\t\tflocks_test 1 off -f $DIR/$tfile || error \"fail flock off\"\n\tfi\n\trm -f $DIR/$tfile\n}\nrun_test 105a \"flock when mounted without -o flock test ========\"\n\ntest_105b() {\n\ttouch $DIR/$tfile\n\tif $(flock_is_enabled); then\n\t\tflocks_test 1 on -c $DIR/$tfile || error \"fail flock on\"\n\telse\n\t\tflocks_test 1 off -c $DIR/$tfile || error \"fail flock off\"\n\tfi\n\trm -f $DIR/$tfile\n}\nrun_test 105b \"fcntl when mounted without -o flock test ========\"\n\ntest_105c() {\n\ttouch $DIR/$tfile\n\tif $(flock_is_enabled); then\n\t\tflocks_test 1 on -l $DIR/$tfile || error \"fail flock on\"\n\telse\n\t\tflocks_test 1 off -l $DIR/$tfile || error \"fail flock off\"\n\tfi\n\trm -f $DIR/$tfile\n}\nrun_test 105c \"lockf when mounted without -o flock test\"\n\ntest_105d() { # bug 15924\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tflock_is_enabled || skip_env \"mount w/o flock enabled\"\n\t#define OBD_FAIL_LDLM_CP_CB_WAIT  0x315\n\t$LCTL set_param fail_loc=0x80000315\n\tflocks_test 2 $DIR/$tdir\n}\nrun_test 105d \"flock race (should not freeze) ========\"\n\ntest_105e() { # bug 22660 && 22040\n\tflock_is_enabled || skip_env \"mount w/o flock enabled\"\n\n\ttouch $DIR/$tfile\n\tflocks_test 3 $DIR/$tfile\n}\nrun_test 105e \"Two conflicting flocks from same process\"\n\ntest_106() { #bug 10921\n\ttest_mkdir $DIR/$tdir\n\t$DIR/$tdir && error \"exec $DIR/$tdir succeeded\"\n\tchmod 777 $DIR/$tdir || error \"chmod $DIR/$tdir failed\"\n}\nrun_test 106 \"attempt exec of dir followed by chown of that dir\"\n\ntest_107() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tCDIR=`pwd`\n\tlocal file=core\n\n\tcd $DIR\n\trm -f $file\n\n        local save_pattern=$(sysctl -n kernel.core_pattern)\n        local save_uses_pid=$(sysctl -n kernel.core_uses_pid)\n        sysctl -w kernel.core_pattern=$file\n        sysctl -w kernel.core_uses_pid=0\n\n        ulimit -c unlimited\n        sleep 60 &\n        SLEEPPID=$!\n\n        sleep 1\n\n        kill -s 11 $SLEEPPID\n        wait $SLEEPPID\n        if [ -e $file ]; then\n                size=`stat -c%s $file`\n                [ $size -eq 0 ] && error \"Fail to create core file $file\"\n        else\n                error \"Fail to create core file $file\"\n        fi\n        rm -f $file\n        sysctl -w kernel.core_pattern=$save_pattern\n        sysctl -w kernel.core_uses_pid=$save_uses_pid\n        cd $CDIR\n}\nrun_test 107 \"Coredump on SIG\"\n\ntest_110() {\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir $DIR/$tdir/$(str_repeat 'a' 255)\n\t$LFS mkdir -c $MDSCOUNT $DIR/$tdir/$(str_repeat 'b' 256) &&\n\t\terror \"mkdir with 256 char should fail, but did not\"\n\ttouch $DIR/$tdir/$(str_repeat 'x' 255) ||\n\t\terror \"create with 255 char failed\"\n\ttouch $DIR/$tdir/$(str_repeat 'y' 256) &&\n\t\terror \"create with 256 char should fail, but did not\"\n\n\tls -l $DIR/$tdir\n\trm -rf $DIR/$tdir\n}\nrun_test 110 \"filename length checking\"\n\n#\n# Purpose: To verify dynamic thread (OSS) creation.\n#\ntest_115() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\t# Lustre does not stop service threads once they are started.\n\t# Reset number of running threads to default.\n\tstopall\n\tsetupall\n\n\tlocal OSTIO_pre\n\tlocal save_params=\"$TMP/sanity-$TESTNAME.parameters\"\n\n\t# Get ll_ost_io count before I/O\n\tOSTIO_pre=$(do_facet ost1 \\\n\t\t\"$LCTL get_param ost.OSS.ost_io.threads_started | cut -d= -f2\")\n\t# Exit if lustre is not running (ll_ost_io not running).\n\t[ -z \"$OSTIO_pre\" ] && error \"no OSS threads\"\n\n\techo \"Starting with $OSTIO_pre threads\"\n\tlocal thread_max=$((OSTIO_pre * 2))\n\tlocal rpc_in_flight=$((thread_max * 2))\n\t# Number of I/O Process proposed to be started.\n\tlocal nfiles\n\tlocal facets=$(get_facets OST)\n\n\tsave_lustre_params client \"osc.*OST*.max_rpcs_in_flight\" > $save_params\n\tsave_lustre_params $facets \"ost.OSS.ost_io.threads_max\" >> $save_params\n\n\t# Set in_flight to $rpc_in_flight\n\t$LCTL set_param osc.*OST*.max_rpcs_in_flight=$rpc_in_flight ||\n\t\terror \"Failed to set max_rpcs_in_flight to $rpc_in_flight\"\n\tnfiles=${rpc_in_flight}\n\t# Set ost thread_max to $thread_max\n\tdo_facet ost1 \"$LCTL set_param ost.OSS.ost_io.threads_max=$thread_max\"\n\n\t# 5 Minutes should be sufficient for max number of OSS\n\t# threads(thread_max) to be created.\n\tlocal timeout=300\n\n\t# Start I/O.\n\tlocal WTL=${WTL:-\"$LUSTRE/tests/write_time_limit\"}\n\ttest_mkdir $DIR/$tdir\n\tfor i in $(seq $nfiles); do\n\t\tlocal file=$DIR/$tdir/${tfile}-$i\n\t\t$LFS setstripe -c -1 -i 0 $file\n\t\t($WTL $file $timeout)&\n\tdone\n\n\t# I/O Started - Wait for thread_started to reach thread_max or report\n\t# error if thread_started is more than thread_max.\n\techo \"Waiting for thread_started to reach thread_max\"\n\tlocal thread_started=0\n\tlocal end_time=$((SECONDS + timeout))\n\n\twhile [ $SECONDS -le $end_time ] ; do\n\t\techo -n \".\"\n\t\t# Get ost i/o thread_started count.\n\t\tthread_started=$(do_facet ost1 \\\n\t\t\t\"$LCTL get_param \\\n\t\t\tost.OSS.ost_io.threads_started | cut -d= -f2\")\n\t\t# Break out if thread_started is equal/greater than thread_max\n\t\tif [[ $thread_started -ge $thread_max ]]; then\n\t\t\techo ll_ost_io thread_started $thread_started, \\\n\t\t\t\tequal/greater than thread_max $thread_max\n\t\t\tbreak\n\t\tfi\n\t\tsleep 1\n\tdone\n\n\t# Cleanup - We have the numbers, Kill i/o jobs if running.\n\tjobcount=($(jobs -p))\n\tfor i in $(seq 0 $((${#jobcount[@]}-1)))\n\tdo\n\t\tkill -9 ${jobcount[$i]}\n\t\tif [ $? -ne 0 ] ; then\n\t\t\techo Warning: \\\n\t\t\tFailed to Kill \\'WTL\\(I/O\\)\\' with pid ${jobcount[$i]}\n\t\tfi\n\tdone\n\n\t# Cleanup files left by WTL binary.\n\tfor i in $(seq $nfiles); do\n\t\tlocal file=$DIR/$tdir/${tfile}-$i\n\t\trm -rf $file\n\t\tif [ $? -ne 0 ] ; then\n\t\t\techo \"Warning: Failed to delete file $file\"\n\t\tfi\n\tdone\n\n\trestore_lustre_params <$save_params\n\trm -f $save_params || echo \"Warning: delete file '$save_params' failed\"\n\n\t# Error out if no new thread has started or Thread started is greater\n\t# than thread max.\n\tif [[ $thread_started -le $OSTIO_pre ||\n\t\t\t$thread_started -gt $thread_max ]]; then\n\t\terror \"ll_ost_io: thread_started $thread_started\" \\\n\t\t      \"OSTIO_pre $OSTIO_pre, thread_max $thread_max.\" \\\n\t\t      \"No new thread started or thread started greater \" \\\n\t\t      \"than thread_max.\"\n\tfi\n}\nrun_test 115 \"verify dynamic thread creation====================\"\n\nfree_min_max () {\n\twait_delete_completed\n\tAVAIL=($(lctl get_param -n osc.*[oO][sS][cC]-[^M]*.kbytesavail))\n\techo \"OST kbytes available: ${AVAIL[@]}\"\n\tMAXV=${AVAIL[0]}\n\tMAXI=0\n\tMINV=${AVAIL[0]}\n\tMINI=0\n\tfor ((i = 0; i < ${#AVAIL[@]}; i++)); do\n\t\t#echo OST $i: ${AVAIL[i]}kb\n\t\tif [[ ${AVAIL[i]} -gt $MAXV ]]; then\n\t\t\tMAXV=${AVAIL[i]}\n\t\t\tMAXI=$i\n\t\tfi\n\t\tif [[ ${AVAIL[i]} -lt $MINV ]]; then\n\t\t\tMINV=${AVAIL[i]}\n\t\t\tMINI=$i\n\t\tfi\n\tdone\n\techo \"Min free space: OST $MINI: $MINV\"\n\techo \"Max free space: OST $MAXI: $MAXV\"\n}\n\ntest_116a() { # was previously test_116()\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\techo -n \"Free space priority \"\n\tdo_facet $SINGLEMDS lctl get_param -n lo[vd].*-mdtlov.qos_prio_free |\n\t\thead -n1\n\tdeclare -a AVAIL\n\tfree_min_max\n\n\t[ $MINV -eq 0 ] && skip \"no free space in OST$MINI, skip\"\n\t[ $MINV -gt 10000000 ] && skip \"too much free space in OST$MINI, skip\"\n\ttrap simple_cleanup_common EXIT\n\n\t# Check if we need to generate uneven OSTs\n\ttest_mkdir -p $DIR/$tdir/OST${MINI}\n\tlocal FILL=$((MINV / 4))\n\tlocal DIFF=$((MAXV - MINV))\n\tlocal DIFF2=$((DIFF * 100 / MINV))\n\n\tlocal threshold=$(do_facet $SINGLEMDS \\\n\t\tlctl get_param -n *.*MDT0000-mdtlov.qos_threshold_rr | head -n1)\n\tthreshold=${threshold%%%}\n\techo -n \"Check for uneven OSTs: \"\n\techo -n \"diff=${DIFF}KB (${DIFF2}%) must be > ${threshold}% ...\"\n\n\tif [[ $DIFF2 -gt $threshold ]]; then\n\t\techo \"ok\"\n\t\techo \"Don't need to fill OST$MINI\"\n\telse\n\t\t# generate uneven OSTs. Write 2% over the QOS threshold value\n\t\techo \"no\"\n\t\tDIFF=$((threshold - DIFF2 + 2))\n\t\tDIFF2=$((MINV * DIFF / 100))\n\t\techo \"Fill $DIFF% remaining space in OST$MINI with ${DIFF2}KB\"\n\t\t$LFS setstripe -i $MINI -c 1 $DIR/$tdir/OST${MINI} ||\n\t\t\terror \"setstripe failed\"\n\t\tDIFF=$((DIFF2 / 2048))\n\t\ti=0\n\t\twhile [ $i -lt $DIFF ]; do\n\t\t\ti=$((i + 1))\n\t\t\tdd if=/dev/zero of=$DIR/$tdir/OST${MINI}/$tfile-$i \\\n\t\t\t\tbs=2M count=1 2>/dev/null\n\t\t\techo -n .\n\t\tdone\n\t\techo .\n\t\tsync\n\t\tsleep_maxage\n\t\tfree_min_max\n\tfi\n\n\tDIFF=$((MAXV - MINV))\n\tDIFF2=$((DIFF * 100 / MINV))\n\techo -n \"diff=$DIFF=$DIFF2% must be > $threshold% for QOS mode...\"\n\tif [ $DIFF2 -gt $threshold ]; then\n\t\techo \"ok\"\n\telse\n\t\techo \"failed - QOS mode won't be used\"\n\t\tsimple_cleanup_common\n\t\tskip \"QOS imbalance criteria not met\"\n\tfi\n\n\tMINI1=$MINI\n\tMINV1=$MINV\n\tMAXI1=$MAXI\n\tMAXV1=$MAXV\n\n\t# now fill using QOS\n\t$LFS setstripe -c 1 $DIR/$tdir\n\tFILL=$((FILL / 200))\n\tif [ $FILL -gt 600 ]; then\n\t\tFILL=600\n\tfi\n\techo \"writing $FILL files to QOS-assigned OSTs\"\n\ti=0\n\twhile [ $i -lt $FILL ]; do\n\t\ti=$((i + 1))\n\t\tdd if=/dev/zero of=$DIR/$tdir/$tfile-$i bs=200k \\\n\t\t\tcount=1 2>/dev/null\n\t\techo -n .\n\tdone\n\techo \"wrote $i 200k files\"\n\tsync\n\tsleep_maxage\n\n\techo \"Note: free space may not be updated, so measurements might be off\"\n\tfree_min_max\n\tDIFF2=$((MAXV - MINV))\n\techo \"free space delta: orig $DIFF final $DIFF2\"\n\t[ $DIFF2 -gt $DIFF ] && echo \"delta got worse!\"\n\tDIFF=$((MINV1 - ${AVAIL[$MINI1]}))\n\techo \"Wrote ${DIFF}KB to smaller OST $MINI1\"\n\tDIFF2=$((MAXV1 - ${AVAIL[$MAXI1]}))\n\techo \"Wrote ${DIFF2}KB to larger OST $MAXI1\"\n\tif [[ $DIFF -gt 0 ]]; then\n\t\tFILL=$((DIFF2 * 100 / DIFF - 100))\n\t\techo \"Wrote ${FILL}% more data to larger OST $MAXI1\"\n\tfi\n\n\t# Figure out which files were written where\n\tUUID=$(lctl get_param -n lov.${FSNAME}-clilov-*.target_obd |\n\t       awk '/'$MINI1': / {print $2; exit}')\n\techo $UUID\n\tMINC=$($LFS getstripe --ost $UUID $DIR/$tdir | grep $DIR | wc -l)\n\techo \"$MINC files created on smaller OST $MINI1\"\n\tUUID=$(lctl get_param -n lov.${FSNAME}-clilov-*.target_obd |\n\t       awk '/'$MAXI1': / {print $2; exit}')\n\techo $UUID\n\tMAXC=$($LFS getstripe --ost $UUID $DIR/$tdir | grep $DIR | wc -l)\n\techo \"$MAXC files created on larger OST $MAXI1\"\n\tif [[ $MINC -gt 0 ]]; then\n\t\tFILL=$((MAXC * 100 / MINC - 100))\n\t\techo \"Wrote ${FILL}% more files to larger OST $MAXI1\"\n\tfi\n\t[[ $MAXC -gt $MINC ]] ||\n\t\terror_ignore LU-9 \"stripe QOS didn't balance free space\"\n\tsimple_cleanup_common\n}\nrun_test 116a \"stripe QOS: free space balance ===================\"\n\ntest_116b() { # LU-2093\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n#define OBD_FAIL_MDS_OSC_CREATE_FAIL     0x147\n\tlocal old_rr=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t       lo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr | head -1)\n\t[ -z \"$old_rr\" ] && skip \"no QOS\"\n\tdo_facet $SINGLEMDS lctl set_param \\\n\t\tlo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr=0\n\tmkdir -p $DIR/$tdir\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x147\n\tcreatemany -o $DIR/$tdir/f- 20 || error \"can't create\"\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0\n\trm -rf $DIR/$tdir\n\tdo_facet $SINGLEMDS lctl set_param \\\n\t\tlo[vd].$FSNAME-MDT0000-mdtlov.qos_threshold_rr=$old_rr\n}\nrun_test 116b \"QoS shouldn't LBUG if not enough OSTs found on the 2nd pass\"\n\ntest_117() # bug 10891\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\t#define OBD_FAIL_OST_SETATTR_CREDITS 0x21e\n\tlctl set_param fail_loc=0x21e\n\t> $DIR/$tfile || error \"truncate failed\"\n\tlctl set_param fail_loc=0\n\techo \"Truncate succeeded.\"\n\trm -f $DIR/$tfile\n}\nrun_test 117 \"verify osd extend ==========\"\n\nNO_SLOW_RESENDCOUNT=4\nexport OLD_RESENDCOUNT=\"\"\nset_resend_count () {\n\tlocal PROC_RESENDCOUNT=\"osc.${FSNAME}-OST*-osc-*.resend_count\"\n\tOLD_RESENDCOUNT=$(lctl get_param -n $PROC_RESENDCOUNT | head -n1)\n\tlctl set_param -n $PROC_RESENDCOUNT $1\n\techo resend_count is set to $(lctl get_param -n $PROC_RESENDCOUNT)\n}\n\n# for reduce test_118* time (b=14842)\n[ \"$SLOW\" = \"no\" ] && set_resend_count $NO_SLOW_RESENDCOUNT\n\n# Reset async IO behavior after error case\nreset_async() {\n\tFILE=$DIR/reset_async\n\n\t# Ensure all OSCs are cleared\n\t$LFS setstripe -c -1 $FILE\n\tdd if=/dev/zero of=$FILE bs=64k count=$OSTCOUNT\n\tsync\n\trm $FILE\n}\n\ntest_118a() #bug 11710\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\treset_async\n\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\tDIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\t\treturn 1;\n        fi\n\trm -f $DIR/$tfile\n}\nrun_test 118a \"verify O_SYNC works ==========\"\n\ntest_118b()\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_SRV_ENOENT 0x217\n\tset_nodes_failloc \"$(osts_nodes)\" 0x217\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\tRC=$?\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\n\tif [[ $RC -eq 0 ]]; then\n\t\terror \"Must return error due to dropped pages, rc=$RC\"\n\t\treturn 1;\n\tfi\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\t\treturn 1;\n\tfi\n\n\techo \"Dirty pages not leaked on ENOENT\"\n\n\t# Due to the above error the OSC will issue all RPCs syncronously\n\t# until a subsequent RPC completes successfully without error.\n\t$MULTIOP $DIR/$tfile Ow4096yc\n\trm -f $DIR/$tfile\n\n\treturn 0\n}\nrun_test 118b \"Reclaim dirty pages on fatal error ==========\"\n\ntest_118c()\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t# for 118c, restore the original resend count, LU-1940\n\t[ \"$SLOW\" = \"no\" ] && [ -n \"$OLD_RESENDCOUNT\" ] &&\n\t\t\t\tset_resend_count $OLD_RESENDCOUNT\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_OST_EROFS               0x216\n\tset_nodes_failloc \"$(osts_nodes)\" 0x216\n\n\t# multiop should block due to fsync until pages are written\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &\n\tMULTIPID=$!\n\tsleep 1\n\n\tif [[ `ps h -o comm -p $MULTIPID` != \"multiop\" ]]; then\n\t\terror \"Multiop failed to block on fsync, pid=$MULTIPID\"\n\tfi\n\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $WRITEBACK -eq 0 ]]; then\n\t\terror \"No page in writeback, writeback=$WRITEBACK\"\n\tfi\n\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n        wait $MULTIPID\n\tRC=$?\n\tif [[ $RC -ne 0 ]]; then\n\t\terror \"Multiop fsync failed, rc=$RC\"\n\tfi\n\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"Dirty pages flushed via fsync on EROFS\"\n\treturn 0\n}\nrun_test 118c \"Fsync blocks on EROFS until dirty pages are flushed ==========\"\n\n# continue to use small resend count to reduce test_118* time (b=14842)\n[ \"$SLOW\" = \"no\" ] && set_resend_count $NO_SLOW_RESENDCOUNT\n\ntest_118d()\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_OST_BRW_PAUSE_BULK\n\tset_nodes_failloc \"$(osts_nodes)\" 0x214\n\t# multiop should block due to fsync until pages are written\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &\n\tMULTIPID=$!\n\tsleep 1\n\n\tif [[ `ps h -o comm -p $MULTIPID` != \"multiop\" ]]; then\n\t\terror \"Multiop failed to block on fsync, pid=$MULTIPID\"\n\tfi\n\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $WRITEBACK -eq 0 ]]; then\n\t\terror \"No page in writeback, writeback=$WRITEBACK\"\n\tfi\n\n        wait $MULTIPID || error \"Multiop fsync failed, rc=$?\"\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"Dirty pages gaurenteed flushed via fsync\"\n\treturn 0\n}\nrun_test 118d \"Fsync validation inject a delay of the bulk ==========\"\n\ntest_118f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\treset_async\n\n\t#define OBD_FAIL_OSC_BRW_PREP_REQ2        0x40a\n\tlctl set_param fail_loc=0x8000040a\n\n\t# Should simulate EINVAL error which is fatal\n        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n        RC=$?\n\tif [[ $RC -eq 0 ]]; then\n\t\terror \"Must return error due to dropped pages, rc=$RC\"\n\tfi\n\n        lctl set_param fail_loc=0x0\n\n        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $LOCKED -ne 0 ]]; then\n\t\terror \"Locked pages remain in cache, locked=$LOCKED\"\n\tfi\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"No pages locked after fsync\"\n\n        reset_async\n\treturn 0\n}\nrun_test 118f \"Simulate unrecoverable OSC side error ==========\"\n\ntest_118g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\treset_async\n\n\t#define OBD_FAIL_OSC_BRW_PREP_REQ        0x406\n\tlctl set_param fail_loc=0x406\n\n\t# simulate local -ENOMEM\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n\tRC=$?\n\n\tlctl set_param fail_loc=0\n\tif [[ $RC -eq 0 ]]; then\n\t\terror \"Must return error due to dropped pages, rc=$RC\"\n\tfi\n\n\tLOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)\n\tDIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n\tWRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n\t\t\tgrep -c writeback)\n\tif [[ $LOCKED -ne 0 ]]; then\n\t\terror \"Locked pages remain in cache, locked=$LOCKED\"\n\tfi\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"No pages locked after fsync\"\n\n\treset_async\n\treturn 0\n}\nrun_test 118g \"Don't stay in wait if we got local -ENOMEM  ==========\"\n\ntest_118h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e\n        set_nodes_failloc \"$(osts_nodes)\" 0x20e\n\t# Should simulate ENOMEM error which is recoverable and should be handled by timeout\n        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n        RC=$?\n\n        set_nodes_failloc \"$(osts_nodes)\" 0\n\tif [[ $RC -eq 0 ]]; then\n\t\terror \"Must return error due to dropped pages, rc=$RC\"\n\tfi\n\n        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache |\n                    grep -c writeback)\n\tif [[ $LOCKED -ne 0 ]]; then\n\t\terror \"Locked pages remain in cache, locked=$LOCKED\"\n\tfi\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"No pages locked after fsync\"\n\n\treturn 0\n}\nrun_test 118h \"Verify timeout in handling recoverables errors  ==========\"\n\n[ \"$SLOW\" = \"no\" ] && [ -n \"$OLD_RESENDCOUNT\" ] && set_resend_count $OLD_RESENDCOUNT\n\ntest_118i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e\n        set_nodes_failloc \"$(osts_nodes)\" 0x20e\n\n\t# Should simulate ENOMEM error which is recoverable and should be handled by timeout\n        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c &\n\tPID=$!\n\tsleep 5\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n\n\twait $PID\n        RC=$?\n\tif [[ $RC -ne 0 ]]; then\n\t\terror \"got error, but should be not, rc=$RC\"\n\tfi\n\n        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)\n\tif [[ $LOCKED -ne 0 ]]; then\n\t\terror \"Locked pages remain in cache, locked=$LOCKED\"\n\tfi\n\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"No pages locked after fsync\"\n\n\treturn 0\n}\nrun_test 118i \"Fix error before timeout in recoverable error  ==========\"\n\n[ \"$SLOW\" = \"no\" ] && set_resend_count 4\n\ntest_118j() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\treset_async\n\n\t#define OBD_FAIL_OST_BRW_WRITE_BULK2     0x220\n        set_nodes_failloc \"$(osts_nodes)\" 0x220\n\n\t# return -EIO from OST\n        $MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:O_SYNC:w4096c\n        RC=$?\n        set_nodes_failloc \"$(osts_nodes)\" 0x0\n\tif [[ $RC -eq 0 ]]; then\n\t\terror \"Must return error due to dropped pages, rc=$RC\"\n\tfi\n\n        LOCKED=$(lctl get_param -n llite.*.dump_page_cache | grep -c locked)\n        DIRTY=$(lctl get_param -n llite.*.dump_page_cache | grep -c dirty)\n        WRITEBACK=$(lctl get_param -n llite.*.dump_page_cache | grep -c writeback)\n\tif [[ $LOCKED -ne 0 ]]; then\n\t\terror \"Locked pages remain in cache, locked=$LOCKED\"\n\tfi\n\n\t# in recoverable error on OST we want resend and stay until it finished\n\tif [[ $DIRTY -ne 0 || $WRITEBACK -ne 0 ]]; then\n\t\terror \"Dirty pages not flushed to disk, dirty=$DIRTY, writeback=$WRITEBACK\"\n\tfi\n\n\trm -f $DIR/$tfile\n\techo \"No pages locked after fsync\"\n\n \treturn 0\n}\nrun_test 118j \"Simulate unrecoverable OST side error ==========\"\n\ntest_118k()\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OSTs with nodsh\"\n\n\t#define OBD_FAIL_OST_BRW_WRITE_BULK      0x20e\n\tset_nodes_failloc \"$(osts_nodes)\" 0x20e\n\ttest_mkdir $DIR/$tdir\n\n\tfor ((i=0;i<10;i++)); do\n\t\t(dd if=/dev/zero of=$DIR/$tdir/$tfile-$i bs=1M count=10 || \\\n\t\t\terror \"dd to $DIR/$tdir/$tfile-$i failed\" )&\n\t\tSLEEPPID=$!\n\t\tsleep 0.500s\n\t\tkill $SLEEPPID\n\t\twait $SLEEPPID\n\tdone\n\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n\trm -rf $DIR/$tdir\n}\nrun_test 118k \"bio alloc -ENOMEM and IO TERM handling =========\"\n\ntest_118l() # LU-646\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\t$MULTIOP $DIR/$tdir Dy || error \"fsync dir failed\"\n\trm -rf $DIR/$tdir\n}\nrun_test 118l \"fsync dir\"\n\ntest_118m() # LU-3066\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\t$MULTIOP $DIR/$tdir DY || error \"fdatasync dir failed\"\n\trm -rf $DIR/$tdir\n}\nrun_test 118m \"fdatasync dir =========\"\n\n[ \"$SLOW\" = \"no\" ] && [ -n \"$OLD_RESENDCOUNT\" ] && set_resend_count $OLD_RESENDCOUNT\n\ntest_118n()\n{\n\tlocal begin\n\tlocal end\n\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OSTs with nodsh\"\n\n\t# Sleep to avoid a cached response.\n\t#define OBD_STATFS_CACHE_SECONDS 1\n\tsleep 2\n\n\t# Inject a 10 second delay in the OST_STATFS handler.\n\t#define OBD_FAIL_OST_STATFS_DELAY 0x242\n\tset_nodes_failloc \"$(osts_nodes)\" 0x242\n\n\tbegin=$SECONDS\n\tstat --file-system $MOUNT > /dev/null\n\tend=$SECONDS\n\n\tset_nodes_failloc \"$(osts_nodes)\" 0\n\n\tif ((end - begin > 20)); then\n\t    error \"statfs took $((end - begin)) seconds, expected 10\"\n\tfi\n}\nrun_test 118n \"statfs() sends OST_STATFS requests in parallel\"\n\ntest_119a() # bug 11737\n{\n        BSIZE=$((512 * 1024))\n        directio write $DIR/$tfile 0 1 $BSIZE\n        # We ask to read two blocks, which is more than a file size.\n        # directio will indicate an error when requested and actual\n        # sizes aren't equeal (a normal situation in this case) and\n        # print actual read amount.\n        NOB=`directio read $DIR/$tfile 0 2 $BSIZE | awk '/error/ {print $6}'`\n        if [ \"$NOB\" != \"$BSIZE\" ]; then\n                error \"read $NOB bytes instead of $BSIZE\"\n        fi\n        rm -f $DIR/$tfile\n}\nrun_test 119a \"Short directIO read must return actual read amount\"\n\ntest_119b() # bug 11737\n{\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\t$LFS setstripe -c 2 $DIR/$tfile || error \"setstripe failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 seek=1 || error \"dd failed\"\n\tsync\n\t$MULTIOP $DIR/$tfile oO_RDONLY:O_DIRECT:r$((2048 * 1024)) ||\n\t\terror \"direct read failed\"\n\trm -f $DIR/$tfile\n}\nrun_test 119b \"Sparse directIO read must return actual read amount\"\n\ntest_119c() # bug 13099\n{\n        BSIZE=1048576\n        directio write $DIR/$tfile 3 1 $BSIZE || error \"direct write failed\"\n        directio readhole $DIR/$tfile 0 2 $BSIZE || error \"reading hole failed\"\n        rm -f $DIR/$tfile\n}\nrun_test 119c \"Testing for direct read hitting hole\"\n\ntest_119d() # bug 15950\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n        MAX_RPCS_IN_FLIGHT=`$LCTL get_param -n osc.*OST0000-osc-[^mM]*.max_rpcs_in_flight`\n        $LCTL set_param -n osc.*OST0000-osc-[^mM]*.max_rpcs_in_flight 1\n        BSIZE=1048576\n        $LFS setstripe $DIR/$tfile -i 0 -c 1 || error \"setstripe failed\"\n        $DIRECTIO write $DIR/$tfile 0 1 $BSIZE || error \"first directio failed\"\n        #define OBD_FAIL_OSC_DIO_PAUSE           0x40d\n        lctl set_param fail_loc=0x40d\n        $DIRECTIO write $DIR/$tfile 1 4 $BSIZE &\n        pid_dio=$!\n        sleep 1\n        cat $DIR/$tfile > /dev/null &\n        lctl set_param fail_loc=0\n        pid_reads=$!\n        wait $pid_dio\n        log \"the DIO writes have completed, now wait for the reads (should not block very long)\"\n        sleep 2\n        [ -n \"`ps h -p $pid_reads -o comm`\" ] && \\\n        error \"the read rpcs have not completed in 2s\"\n        rm -f $DIR/$tfile\n        $LCTL set_param -n osc.*OST0000-osc-[^mM]*.max_rpcs_in_flight $MAX_RPCS_IN_FLIGHT\n}\nrun_test 119d \"The DIO path should try to send a new rpc once one is completed\"\n\ntest_120a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\ttest_mkdir -i0 -c1 $DIR/$tdir\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\tcancel_lru_locks mdc\n\t# asynchronous object destroy at MDT could cause bl ast to client\n\tcancel_lru_locks osc\n\n\tstat $DIR/$tdir > /dev/null\n\tcan1=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\ttest_mkdir -i0 -c1 $DIR/$tdir/d1\n\tcan2=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -eq $can2 ] || error $((can2-can1)) \"cancel RPC occured.\"\n\t[ $blk1 -eq $blk2 ] || error $((blk2-blk1)) \"blocking RPC occured.\"\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120a \"Early Lock Cancel: mkdir test\"\n\ntest_120b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\ttest_mkdir $DIR/$tdir\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\tcancel_lru_locks mdc\n\tstat $DIR/$tdir > /dev/null\n\tcan1=$(do_facet $SINGLEMDS \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\ttouch $DIR/$tdir/f1\n\tcan2=$(do_facet $SINGLEMDS \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -eq $can2 ] || error $((can2-can1)) \"cancel RPC occured.\"\n\t[ $blk1 -eq $blk2 ] || error $((blk2-blk1)) \"blocking RPC occured.\"\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120b \"Early Lock Cancel: create test\"\n\ntest_120c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\ttest_mkdir -i0 -c1 $DIR/$tdir\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip \"no early lock cancel on server\"\n\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\ttest_mkdir -i0 -c1 $DIR/$tdir/d1\n\ttest_mkdir -i0 -c1 $DIR/$tdir/d2\n\ttouch $DIR/$tdir/d1/f1\n\tcancel_lru_locks mdc\n\tstat $DIR/$tdir/d1 $DIR/$tdir/d2 $DIR/$tdir/d1/f1 > /dev/null\n\tcan1=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tln $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2\n\tcan2=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -eq $can2 ] || error $((can2-can1)) \"cancel RPC occured.\"\n\t[ $blk1 -eq $blk2 ] || error $((blk2-blk1)) \"blocking RPC occured.\"\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120c \"Early Lock Cancel: link test\"\n\ntest_120d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\ttest_mkdir -i0 -c1 $DIR/$tdir\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\ttouch $DIR/$tdir\n\tcancel_lru_locks mdc\n\tstat $DIR/$tdir > /dev/null\n\tcan1=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tchmod a+x $DIR/$tdir\n\tcan2=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -eq $can2 ] || error $((can2-can1)) \"cancel RPC occured.\"\n\t[ $blk1 -eq $blk2 ] || error $((blk2-blk1)) \"blocking RPC occured.\"\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120d \"Early Lock Cancel: setattr test\"\n\ntest_120e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal dlmtrace_set=false\n\n\ttest_mkdir -i0 -c1 $DIR/$tdir\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\t! $LCTL get_param debug | grep -q dlmtrace &&\n\t\t$LCTL set_param debug=+dlmtrace && dlmtrace_set=true\n\tdd if=/dev/zero of=$DIR/$tdir/f1 count=1\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tdd if=$DIR/$tdir/f1 of=/dev/null\n\tstat $DIR/$tdir $DIR/$tdir/f1 > /dev/null\n\t# XXX client can not do early lock cancel of OST lock\n\t# during unlink (LU-4206), so cancel osc lock now.\n\tsleep 2\n\tcancel_lru_locks osc\n\tcan1=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tunlink $DIR/$tdir/f1\n\tsleep 5\n\tcan2=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -ne $can2 ] && error \"$((can2 - can1)) cancel RPC occured\" &&\n\t\t$LCTL dk $TMP/cancel.debug.txt\n\t[ $blk1 -ne $blk2 ] && error \"$((blk2 - blk1)) blocking RPC occured\" &&\n\t\t$LCTL dk $TMP/blocking.debug.txt\n\t$dlmtrace_set && $LCTL set_param debug=-dlmtrace\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120e \"Early Lock Cancel: unlink test\"\n\ntest_120f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\ttest_mkdir -i0 -c1 $DIR/$tdir\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\ttest_mkdir -i0 -c1 $DIR/$tdir/d1\n\ttest_mkdir -i0 -c1 $DIR/$tdir/d2\n\tdd if=/dev/zero of=$DIR/$tdir/d1/f1 count=1\n\tdd if=/dev/zero of=$DIR/$tdir/d2/f2 count=1\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tdd if=$DIR/$tdir/d1/f1 of=/dev/null\n\tdd if=$DIR/$tdir/d2/f2 of=/dev/null\n\tstat $DIR/$tdir/d1 $DIR/$tdir/d2 $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2 > /dev/null\n\t# XXX client can not do early lock cancel of OST lock\n\t# during rename (LU-4206), so cancel osc lock now.\n\tsleep 2\n\tcancel_lru_locks osc\n\tcan1=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tmrename $DIR/$tdir/d1/f1 $DIR/$tdir/d2/f2\n\tsleep 5\n\tcan2=$(do_facet mds1 \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\t[ $can1 -eq $can2 ] || error $((can2-can1)) \"cancel RPC occured.\"\n\t[ $blk1 -eq $blk2 ] || error $((blk2-blk1)) \"blocking RPC occured.\"\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120f \"Early Lock Cancel: rename test\"\n\ntest_120g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q early_lock_cancel ||\n\t\tskip_env \"no early lock cancel on server\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlru_resize_disable mdc\n\tlru_resize_disable osc\n\tcount=10000\n\techo create $count files\n\ttest_mkdir $DIR/$tdir\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tt0=$(date +%s)\n\n\tcan0=$(do_facet $SINGLEMDS \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk0=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tcreatemany -o $DIR/$tdir/f $count\n\tsync\n\tcan1=$(do_facet $SINGLEMDS \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk1=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tt1=$(date +%s)\n\techo total: $((can1-can0)) cancels, $((blk1-blk0)) blockings\n\techo rm $count files\n\trm -r $DIR/$tdir\n\tsync\n\tcan2=$(do_facet $SINGLEMDS \\\n\t       \"$LCTL get_param -n ldlm.services.ldlm_canceld.stats\" |\n\t       awk '/ldlm_cancel/ {print $2}')\n\tblk2=$($LCTL get_param -n ldlm.services.ldlm_cbd.stats |\n\t       awk '/ldlm_bl_callback/ {print $2}')\n\tt2=$(date +%s)\n\techo total: $count removes in $((t2-t1))\n\techo total: $((can2-can1)) cancels, $((blk2-blk1)) blockings\n\tsleep 2\n\t# wait for commitment of removal\n\tlru_resize_enable mdc\n\tlru_resize_enable osc\n}\nrun_test 120g \"Early Lock Cancel: performance test\"\n\ntest_121() { #bug #10589\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -rf $DIR/$tfile\n\twrites=$(LANG=C dd if=/dev/zero of=$DIR/$tfile count=1 2>&1 | awk -F '+' '/out$/ {print $1}')\n#define OBD_FAIL_LDLM_CANCEL_RACE        0x310\n\tlctl set_param fail_loc=0x310\n\tcancel_lru_locks osc > /dev/null\n\treads=$(LANG=C dd if=$DIR/$tfile of=/dev/null 2>&1 | awk -F '+' '/in$/ {print $1}')\n\tlctl set_param fail_loc=0\n\t[[ $reads -eq $writes ]] ||\n\t\terror \"read $reads blocks, must be $writes blocks\"\n}\nrun_test 121 \"read cancel race =========\"\n\ntest_123a_base() { # was test 123, statahead(bug 11401)\n\tlocal lsx=\"$1\"\n\n\tSLOWOK=0\n\tif ! grep -q \"processor.*: 1\" /proc/cpuinfo; then\n\t\tlog \"testing UP system. Performance may be lower than expected.\"\n\t\tSLOWOK=1\n\tfi\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\tNUMFREE=$(df -i -P $DIR | tail -n 1 | awk '{ print $4 }')\n\t[[ $NUMFREE -gt 100000 ]] && NUMFREE=100000 || NUMFREE=$((NUMFREE-1000))\n\tMULT=10\n\tfor ((i=100, j=0; i<=$NUMFREE; j=$i, i=$((i * MULT)) )); do\n\t\tcreatemany -o $DIR/$tdir/$tfile $j $((i - j))\n\n\t\tmax=$(lctl get_param -n llite.*.statahead_max | head -n 1)\n\t\tlctl set_param -n llite.*.statahead_max 0\n\t\tlctl get_param llite.*.statahead_max\n\t\tcancel_lru_locks mdc\n\t\tcancel_lru_locks osc\n\t\tstime=$(date +%s)\n\t\ttime $lsx $DIR/$tdir | wc -l\n\t\tetime=$(date +%s)\n\t\tdelta=$((etime - stime))\n\t\tlog \"$lsx $i files without statahead: $delta sec\"\n\t\tlctl set_param llite.*.statahead_max=$max\n\n\t\tswrong=$(lctl get_param -n llite.*.statahead_stats |\n\t\t\tgrep \"statahead wrong:\" | awk '{print $3}')\n\t\tlctl get_param -n llite.*.statahead_max | grep '[0-9]'\n\t\tcancel_lru_locks mdc\n\t\tcancel_lru_locks osc\n\t\tstime=$(date +%s)\n\t\ttime $lsx $DIR/$tdir | wc -l\n\t\tetime=$(date +%s)\n\t\tdelta_sa=$((etime - stime))\n\t\tlog \"$lsx $i files with statahead: $delta_sa sec\"\n\t\tlctl get_param -n llite.*.statahead_stats\n\t\tewrong=$(lctl get_param -n llite.*.statahead_stats |\n\t\t\tgrep \"statahead wrong:\" | awk '{print $3}')\n\n\t\t[[ $swrong -lt $ewrong ]] &&\n\t\t\tlog \"statahead was stopped, maybe too many locks held!\"\n\t\t[[ $delta -eq 0 || $delta_sa -eq 0 ]] && continue\n\n\t\tif [ $((delta_sa * 100)) -gt $((delta * 105)) -a $delta_sa -gt $((delta + 2)) ]; then\n\t\t\tmax=$(lctl get_param -n llite.*.statahead_max |\n\t\t\t\thead -n 1)\n\t\t\tlctl set_param -n llite.*.statahead_max 0\n\t\t\tlctl get_param llite.*.statahead_max\n\t\t\tcancel_lru_locks mdc\n\t\t\tcancel_lru_locks osc\n\t\t\tstime=$(date +%s)\n\t\t\ttime $lsx $DIR/$tdir | wc -l\n\t\t\tetime=$(date +%s)\n\t\t\tdelta=$((etime - stime))\n\t\t\tlog \"$lsx $i files again without statahead: $delta sec\"\n\t\t\tlctl set_param llite.*.statahead_max=$max\n\t\t\tif [ $((delta_sa * 100 > delta * 105 && delta_sa > delta + 2)) ]; then\n\t\t\t\tif [  $SLOWOK -eq 0 ]; then\n\t\t\t\t\terror \"$lsx $i files is slower with statahead!\"\n\t\t\t\telse\n\t\t\t\t\tlog \"$lsx $i files is slower with statahead!\"\n\t\t\t\tfi\n\t\t\t\tbreak\n\t\t\tfi\n\t\tfi\n\n\t\t[ $delta -gt 20 ] && break\n\t\t[ $delta -gt 8 ] && MULT=$((50 / delta))\n\t\t[ \"$SLOW\" = \"no\" -a $delta -gt 5 ] && break\n\tdone\n\tlog \"$lsx done\"\n\n\tstime=$(date +%s)\n\trm -r $DIR/$tdir\n\tsync\n\tetime=$(date +%s)\n\tdelta=$((etime - stime))\n\tlog \"rm -r $DIR/$tdir/: $delta seconds\"\n\tlog \"rm done\"\n\tlctl get_param -n llite.*.statahead_stats\n}\n\ntest_123aa() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_123a_base \"ls -l\"\n}\nrun_test 123aa \"verify statahead work\"\n\ntest_123ab() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tstatx_supported || skip_env \"Test must be statx() syscall supported\"\n\n\ttest_123a_base \"$STATX -l\"\n}\nrun_test 123ab \"verify statahead work by using statx\"\n\ntest_123ac() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tstatx_supported || skip_env \"Test must be statx() syscall supported\"\n\n\tlocal rpcs_before\n\tlocal rpcs_after\n\tlocal agl_before\n\tlocal agl_after\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\tagl_before=$($LCTL get_param -n llite.*.statahead_stats |\n\t\tawk '/agl.total:/ {print $3}')\n\ttest_123a_base \"$STATX -c \\\"%n %i %A %h %u %g %W %X %Z\\\" -D\"\n\ttest_123a_base \"$STATX --cached=always -D\"\n\tagl_after=$($LCTL get_param -n llite.*.statahead_stats |\n\t\tawk '/agl.total:/ {print $3}')\n\t[ $agl_before -eq $agl_after ] ||\n\t\terror \"Should not trigger AGL thread - $agl_before:$agl_after\"\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $rpcs_before ] ||\n\t\terror \"$STATX should not send glimpse RPCs to $OSC\"\n}\nrun_test 123ac \"verify statahead work by using statx without glimpse RPCs\"\n\ntest_123b () { # statahead(bug 15027)\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/$tfile-%d 1000\n\n        cancel_lru_locks mdc\n        cancel_lru_locks osc\n\n#define OBD_FAIL_MDC_GETATTR_ENQUEUE     0x803\n        lctl set_param fail_loc=0x80000803\n        ls -lR $DIR/$tdir > /dev/null\n        log \"ls done\"\n        lctl set_param fail_loc=0x0\n        lctl get_param -n llite.*.statahead_stats\n        rm -r $DIR/$tdir\n        sync\n\n}\nrun_test 123b \"not panic with network error in statahead enqueue (bug 15027)\"\n\ntest_123c() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\n\ttest_mkdir -i 0 -c 1 $DIR/$tdir.0\n\ttest_mkdir -i 1 -c 1 $DIR/$tdir.1\n\ttouch $DIR/$tdir.1/{1..3}\n\tmv $DIR/$tdir.1/{1..3} $DIR/$tdir.0\n\n\tremount_client $MOUNT\n\n\t$MULTIOP $DIR/$tdir.0 Q\n\n\t# let statahead to complete\n\tls -l $DIR/$tdir.0 > /dev/null\n\n\ttestid=$(echo $TESTNAME | tr '_' ' ')\n\tdmesg | tac | sed \"/$testid/,$ d\" | grep \"Can not initialize inode\" &&\n\t\terror \"statahead warning\" || true\n}\nrun_test 123c \"Can not initialize inode warning on DNE statahead\"\n\ntest_124a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||\n\t\tskip_env \"no lru resize on server\"\n\n\tlocal NR=2000\n\n\ttest_mkdir $DIR/$tdir\n\n\tlog \"create $NR files at $DIR/$tdir\"\n\tcreatemany -o $DIR/$tdir/f $NR ||\n\t\terror \"failed to create $NR files in $DIR/$tdir\"\n\n\tcancel_lru_locks mdc\n\tls -l $DIR/$tdir > /dev/null\n\n\tlocal NSDIR=\"\"\n\tlocal LRU_SIZE=0\n\tfor VALUE in $($LCTL get_param ldlm.namespaces.*mdc-*.lru_size); do\n\t\tlocal PARAM=$(echo ${VALUE[0]} | cut -d \"=\" -f1)\n\t\tLRU_SIZE=$($LCTL get_param -n $PARAM)\n\t\tif [[ $LRU_SIZE -gt $(default_lru_size) ]]; then\n\t\t\tNSDIR=$(echo $PARAM | cut -d \".\" -f1-3)\n\t\t\tlog \"NSDIR=$NSDIR\"\n                        log \"NS=$(basename $NSDIR)\"\n                        break\n                fi\n        done\n\n\tif [[ -z \"$NSDIR\" || $LRU_SIZE -lt $(default_lru_size) ]]; then\n\t\tskip \"Not enough cached locks created!\"\n\tfi\n\tlog \"LRU=$LRU_SIZE\"\n\n\tlocal SLEEP=30\n\n\t# We know that lru resize allows one client to hold $LIMIT locks\n\t# for 10h. After that locks begin to be killed by client.\n\tlocal MAX_HRS=10\n\tlocal LIMIT=$($LCTL get_param -n $NSDIR.pool.limit)\n\tlog \"LIMIT=$LIMIT\"\n\tif [ $LIMIT -lt $LRU_SIZE ]; then\n\t\tskip \"Limit is too small $LIMIT\"\n\tfi\n\n        # Make LVF so higher that sleeping for $SLEEP is enough to _start_\n        # killing locks. Some time was spent for creating locks. This means\n        # that up to the moment of sleep finish we must have killed some of\n        # them (10-100 locks). This depends on how fast ther were created.\n        # Many of them were touched in almost the same moment and thus will\n        # be killed in groups.\n        local LVF=$(($MAX_HRS * 60 * 60 / $SLEEP * $LIMIT / $LRU_SIZE))\n\n        # Use $LRU_SIZE_B here to take into account real number of locks\n        # created in the case of CMD, LRU_SIZE_B != $NR in most of cases\n        local LRU_SIZE_B=$LRU_SIZE\n        log \"LVF=$LVF\"\n\tlocal OLD_LVF=$($LCTL get_param -n $NSDIR.pool.lock_volume_factor)\n\tlog \"OLD_LVF=$OLD_LVF\"\n\t$LCTL set_param -n $NSDIR.pool.lock_volume_factor $LVF\n\n        # Let's make sure that we really have some margin. Client checks\n        # cached locks every 10 sec.\n        SLEEP=$((SLEEP+20))\n        log \"Sleep ${SLEEP} sec\"\n        local SEC=0\n        while ((SEC<$SLEEP)); do\n                echo -n \"...\"\n                sleep 5\n                SEC=$((SEC+5))\n\t\tLRU_SIZE=$($LCTL get_param -n $NSDIR/lru_size)\n                echo -n \"$LRU_SIZE\"\n        done\n        echo \"\"\n\t$LCTL set_param -n $NSDIR.pool.lock_volume_factor $OLD_LVF\n\tlocal LRU_SIZE_A=$($LCTL get_param -n $NSDIR.lru_size)\n\n\t[[ $LRU_SIZE_B -gt $LRU_SIZE_A ]] || {\n                error \"No locks dropped in ${SLEEP}s. LRU size: $LRU_SIZE_A\"\n                unlinkmany $DIR/$tdir/f $NR\n                return\n        }\n\n        log \"Dropped \"$((LRU_SIZE_B-LRU_SIZE_A))\" locks in ${SLEEP}s\"\n        log \"unlink $NR files at $DIR/$tdir\"\n        unlinkmany $DIR/$tdir/f $NR\n}\nrun_test 124a \"lru resize =======================================\"\n\nget_max_pool_limit()\n{\n\tlocal limit=$($LCTL get_param \\\n\t\t      -n ldlm.namespaces.*-MDT0000-mdc-*.pool.limit)\n\tlocal max=0\n\tfor l in $limit; do\n\t\tif [[ $l -gt $max ]]; then\n\t\t\tmax=$l\n\t\tfi\n\tdone\n\techo $max\n}\n\ntest_124b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||\n\t\tskip_env \"no lru resize on server\"\n\n\tLIMIT=$(get_max_pool_limit)\n\n\tNR=$(($(default_lru_size)*20))\n\tif [[ $NR -gt $LIMIT ]]; then\n\t\tlog \"Limit lock number by $LIMIT locks\"\n\t\tNR=$LIMIT\n\tfi\n\n\tIFree=$(mdsrate_inodes_available)\n\tif [ $IFree -lt $NR ]; then\n\t\tlog \"Limit lock number by $IFree inodes\"\n\t\tNR=$IFree\n\tfi\n\n\tlru_resize_disable mdc\n\ttest_mkdir -p $DIR/$tdir/disable_lru_resize\n\n        createmany -o $DIR/$tdir/disable_lru_resize/f $NR\n        log \"doing ls -la $DIR/$tdir/disable_lru_resize 3 times\"\n        cancel_lru_locks mdc\n        stime=`date +%s`\n        PID=\"\"\n        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        sleep 2\n        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        sleep 2\n        ls -la $DIR/$tdir/disable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        wait $PID\n        etime=`date +%s`\n        nolruresize_delta=$((etime-stime))\n        log \"ls -la time: $nolruresize_delta seconds\"\n        log \"lru_size = $(lctl get_param -n ldlm.namespaces.*mdc*.lru_size)\"\n        unlinkmany $DIR/$tdir/disable_lru_resize/f $NR\n\n\tlru_resize_enable mdc\n\ttest_mkdir -p $DIR/$tdir/enable_lru_resize\n\n        createmany -o $DIR/$tdir/enable_lru_resize/f $NR\n        log \"doing ls -la $DIR/$tdir/enable_lru_resize 3 times\"\n        cancel_lru_locks mdc\n        stime=`date +%s`\n        PID=\"\"\n        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        sleep 2\n        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        sleep 2\n        ls -la $DIR/$tdir/enable_lru_resize > /dev/null &\n        PID=\"$PID $!\"\n        wait $PID\n        etime=`date +%s`\n        lruresize_delta=$((etime-stime))\n        log \"ls -la time: $lruresize_delta seconds\"\n        log \"lru_size = $(lctl get_param -n ldlm.namespaces.*mdc*.lru_size)\"\n\n        if [ $lruresize_delta -gt $nolruresize_delta ]; then\n                log \"ls -la is $(((lruresize_delta - $nolruresize_delta) * 100 / $nolruresize_delta))% slower with lru resize enabled\"\n        elif [ $nolruresize_delta -gt $lruresize_delta ]; then\n                log \"ls -la is $(((nolruresize_delta - $lruresize_delta) * 100 / $nolruresize_delta))% faster with lru resize enabled\"\n        else\n                log \"lru resize performs the same with no lru resize\"\n        fi\n        unlinkmany $DIR/$tdir/enable_lru_resize/f $NR\n}\nrun_test 124b \"lru resize (performance test) =======================\"\n\ntest_124c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||\n\t\tskip_env \"no lru resize on server\"\n\n\t# cache ununsed locks on client\n\tlocal nr=100\n\tcancel_lru_locks mdc\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f $nr ||\n\t\terror \"failed to create $nr files in $DIR/$tdir\"\n\tls -l $DIR/$tdir > /dev/null\n\n\tlocal nsdir=\"ldlm.namespaces.*-MDT0000-mdc-*\"\n\tlocal unused=$($LCTL get_param -n $nsdir.lock_unused_count)\n\tlocal max_age=$($LCTL get_param -n $nsdir.lru_max_age)\n\tlocal recalc_p=$($LCTL get_param -n $nsdir.pool.recalc_period)\n\techo \"unused=$unused, max_age=$max_age, recalc_p=$recalc_p\"\n\n\t# set lru_max_age to 1 sec\n\t$LCTL set_param $nsdir.lru_max_age=1000 # milliseconds\n\techo \"sleep $((recalc_p * 2)) seconds...\"\n\tsleep $((recalc_p * 2))\n\n\tlocal remaining=$($LCTL get_param -n $nsdir.lock_unused_count)\n\t# restore lru_max_age\n\t$LCTL set_param -n $nsdir.lru_max_age $max_age\n\t[ $remaining -eq 0 ] || error \"$remaining locks are not canceled\"\n\tunlinkmany $DIR/$tdir/f $nr\n}\nrun_test 124c \"LRUR cancel very aged locks\"\n\ntest_124d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$LCTL get_param -n mdc.*.connect_flags | grep -q lru_resize ||\n\t\tskip_env \"no lru resize on server\"\n\n\t# cache ununsed locks on client\n\tlocal nr=100\n\n\tlru_resize_disable mdc\n\tstack_trap \"lru_resize_enable mdc\" EXIT\n\n\tcancel_lru_locks mdc\n\n\t# asynchronous object destroy at MDT could cause bl ast to client\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f $nr ||\n\t\terror \"failed to create $nr files in $DIR/$tdir\"\n\tstack_trap \"unlinkmany $DIR/$tdir/f $nr\" EXIT\n\n\tls -l $DIR/$tdir > /dev/null\n\n\tlocal nsdir=\"ldlm.namespaces.*-MDT0000-mdc-*\"\n\tlocal unused=$($LCTL get_param -n $nsdir.lock_unused_count)\n\tlocal max_age=$($LCTL get_param -n $nsdir.lru_max_age)\n\tlocal recalc_p=$($LCTL get_param -n $nsdir.pool.recalc_period)\n\n\techo \"unused=$unused, max_age=$max_age, recalc_p=$recalc_p\"\n\n\t# set lru_max_age to 1 sec\n\t$LCTL set_param $nsdir.lru_max_age=1000 # milliseconds\n\tstack_trap \"$LCTL set_param -n $nsdir.lru_max_age $max_age\" EXIT\n\n\techo \"sleep $((recalc_p * 2)) seconds...\"\n\tsleep $((recalc_p * 2))\n\n\tlocal remaining=$($LCTL get_param -n $nsdir.lock_unused_count)\n\n\t[ $remaining -eq 0 ] || error \"$remaining locks are not canceled\"\n}\nrun_test 124d \"cancel very aged locks if lru-resize diasbaled\"\n\ntest_125() { # 13358\n\t$LCTL get_param -n llite.*.client_type | grep -q local ||\n\t\tskip \"must run as local client\"\n\t$LCTL get_param -n mdc.*-mdc-*.connect_flags | grep -q acl ||\n\t\tskip_env \"must have acl enabled\"\n\t[ -z \"$(which setfacl)\" ] && skip_env \"must have setfacl tool\"\n\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -S 65536 -c -1 $DIR/$tdir || error \"setstripe failed\"\n\tsetfacl -R -m u:bin:rwx $DIR/$tdir || error \"setfacl $DIR/$tdir failed\"\n\tls -ld $DIR/$tdir || error \"cannot access $DIR/$tdir\"\n}\nrun_test 125 \"don't return EPROTO when a dir has a non-default striping and ACLs\"\n\ntest_126() { # bug 12829/13455\n\t$GSS && skip_env \"must run as gss disabled\"\n\t$LCTL get_param -n llite.*.client_type | grep -q local ||\n\t\tskip \"must run as local client\"\n\t[ \"$UID\" != 0 ] && skip \"must run as root, not UID $UID\"\n\n\t$RUNAS -u 0 -g 1 touch $DIR/$tfile || error \"touch failed\"\n\tgid=`ls -n $DIR/$tfile | awk '{print $4}'`\n\trm -f $DIR/$tfile\n\t[ $gid -eq \"1\" ] || error \"gid is set to\" $gid \"instead of 1\"\n}\nrun_test 126 \"check that the fsgid provided by the client is taken into account\"\n\ntest_127a() { # bug 15521\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tlocal name count samp unit min max sum sumsq\n\n\t$LFS setstripe -i 0 -c 1 $DIR/$tfile || error \"setstripe failed\"\n\techo \"stats before reset\"\n\t$LCTL get_param osc.*.stats\n\t$LCTL set_param osc.*.stats=0\n\tlocal fsize=$((2048 * 1024))\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=$fsize count=1\n\tcancel_lru_locks osc\n\tdd if=$DIR/$tfile of=/dev/null bs=$fsize\n\n\t$LCTL get_param osc.*0000-osc-*.stats | grep samples > $DIR/$tfile.tmp\n\tstack_trap \"rm -f $TMP/$tfile.tmp\"\n\twhile read name count samp unit min max sum sumsq; do\n\t\techo \"got name=$name count=$count unit=$unit min=$min max=$max\"\n\t\t[ ! $min ] && error \"Missing min value for $name proc entry\"\n\t\teval $name=$count || error \"Wrong proc format\"\n\n\t\tcase $name in\n\t\tread_bytes|write_bytes)\n\t\t\t[[ \"$unit\" =~ \"bytes\" ]] ||\n\t\t\t\terror \"unit is not 'bytes': $unit\"\n\t\t\t(( $min >= 4096 )) || error \"min is too small: $min\"\n\t\t\t(( $min <= $fsize )) || error \"min is too big: $min\"\n\t\t\t(( $max >= 4096 )) || error \"max is too small: $max\"\n\t\t\t(( $max <= $fsize )) || error \"max is too big: $max\"\n\t\t\t(( $sum == $fsize )) || error \"sum is wrong: $sum\"\n\t\t\t(( $sumsq >= ($fsize / 4096) * (4096 * 4096) )) ||\n\t\t\t\terror \"sumsquare is too small: $sumsq\"\n\t\t\t(( $sumsq <= $fsize * $fsize )) ||\n\t\t\t\terror \"sumsquare is too big: $sumsq\"\n\t\t\t;;\n\t\tost_read|ost_write)\n\t\t\t[[ \"$unit\" =~ \"usec\" ]] ||\n\t\t\t\terror \"unit is not 'usec': $unit\"\n\t\t\t;;\n\t\t*)\t;;\n\t\tesac\n\tdone < $DIR/$tfile.tmp\n\n\t#check that we actually got some stats\n\t[ \"$read_bytes\" ] || error \"Missing read_bytes stats\"\n\t[ \"$write_bytes\" ] || error \"Missing write_bytes stats\"\n\t[ \"$read_bytes\" != 0 ] || error \"no read done\"\n\t[ \"$write_bytes\" != 0 ] || error \"no write done\"\n}\nrun_test 127a \"verify the client stats are sane\"\n\ntest_127b() { # bug LU-333\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tlocal name count samp unit min max sum sumsq\n\n\techo \"stats before reset\"\n\t$LCTL get_param llite.*.stats\n\t$LCTL set_param llite.*.stats=0\n\n\t# perform 2 reads and writes so MAX is different from SUM.\n\tdd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1\n\tdd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1\n\tcancel_lru_locks osc\n\tdd if=$DIR/$tfile of=/dev/null bs=$PAGE_SIZE count=1\n\tdd if=$DIR/$tfile of=/dev/null bs=$PAGE_SIZE count=1\n\n\t$LCTL get_param llite.*.stats | grep samples > $TMP/$tfile.tmp\n\tstack_trap \"rm -f $TMP/$tfile.tmp\"\n\twhile read name count samp unit min max sum sumsq; do\n\t\techo \"got name=$name count=$count unit=$unit min=$min max=$max\"\n\t\teval $name=$count || error \"Wrong proc format\"\n\n\t\tcase $name in\n\t\tread_bytes|write_bytes)\n\t\t\t[[ \"$unit\" =~ \"bytes\" ]] ||\n\t\t\t\terror \"unit is not 'bytes': $unit\"\n\t\t\t(( $count == 2 )) || error \"count is not 2: $count\"\n\t\t\t(( $min == $PAGE_SIZE )) ||\n\t\t\t\terror \"min is not $PAGE_SIZE: $min\"\n\t\t\t(( $max == $PAGE_SIZE )) ||\n\t\t\t\terror \"max is not $PAGE_SIZE: $max\"\n\t\t\t(( $sum == $PAGE_SIZE * 2 )) ||\n\t\t\t\terror \"sum is not $((PAGE_SIZE * 2)): $sum\"\n\t\t\t;;\n\t\tread|write)\n\t\t\t[[ \"$unit\" =~ \"usec\" ]] ||\n\t\t\t\terror \"unit is not 'usec': $unit\"\n\t\t\t;;\n\t\t*)\t;;\n\t\tesac\n\tdone < $TMP/$tfile.tmp\n\n\t#check that we actually got some stats\n\t[ \"$read_bytes\" ] || error \"Missing read_bytes stats\"\n\t[ \"$write_bytes\" ] || error \"Missing write_bytes stats\"\n\t[ \"$read_bytes\" != 0 ] || error \"no read done\"\n\t[ \"$write_bytes\" != 0 ] || error \"no write done\"\n}\nrun_test 127b \"verify the llite client stats are sane\"\n\ntest_127c() { # LU-12394\n\t[ \"$OSTCOUNT\" -lt \"2\" ] && skip_env \"needs >= 2 OSTs\"\n\tlocal size\n\tlocal bsize\n\tlocal reads\n\tlocal writes\n\tlocal count\n\n\t$LCTL set_param llite.*.extents_stats=1\n\tstack_trap \"$LCTL set_param llite.*.extents_stats=0\" EXIT\n\n\t# Use two stripes so there is enough space in default config\n\t$LFS setstripe -c 2 $DIR/$tfile\n\n\t# Extent stats start at 0-4K and go in power of two buckets\n\t# LL_HIST_START = 12 --> 2^12 = 4K\n\t# We do 3K*2^i, so 3K, 6K, 12K, 24K... hitting each bucket.\n\t# We do not do buckets larger than 64 MiB to avoid ENOSPC issues on\n\t# small configs\n\tfor size in 3K 6K 12K 24K 48K 96K 192K 384K 768K 1536K 3M 6M 12M 24M 48M;\n\t\tdo\n\t\t# Write and read, 2x each, second time at a non-zero offset\n\t\tdd if=/dev/zero of=$DIR/$tfile bs=$size count=1\n\t\tdd if=/dev/zero of=$DIR/$tfile bs=$size count=1 seek=10\n\t\tdd if=$DIR/$tfile of=/dev/null bs=$size count=1\n\t\tdd if=$DIR/$tfile of=/dev/null bs=$size count=1 seek=10\n\t\trm -f $DIR/$tfile\n\tdone\n\n\t$LCTL get_param llite.*.extents_stats\n\n\tcount=2\n\tfor bsize in 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M;\n\t\tdo\n\t\tlocal bucket=$($LCTL get_param -n llite.*.extents_stats |\n\t\t\t\tgrep -m 1 $bsize)\n\t\treads=$(echo $bucket | awk '{print $5}')\n\t\twrites=$(echo $bucket | awk '{print $9}')\n\t\t[ \"$reads\" -eq $count ] ||\n\t\t\terror \"$reads reads in < $bsize bucket, expect $count\"\n\t\t[ \"$writes\" -eq $count ] ||\n\t\t\terror \"$writes writes in < $bsize bucket, expect $count\"\n\tdone\n\n\t# Test mmap write and read\n\t$LCTL set_param llite.*.extents_stats=c\n\tsize=512\n\tdd if=/dev/zero of=$DIR/$tfile bs=${size}K count=1\n\t$MULTIOP $DIR/$tfile OSMRUc || error \"$MULTIOP $DIR/$tfile failed\"\n\t$MULTIOP $DIR/$tfile OSMWUc || error \"$MULTIOP $DIR/$tfile failed\"\n\n\t$LCTL get_param llite.*.extents_stats\n\n\tcount=$(((size*1024) / PAGE_SIZE))\n\n\tbsize=$((2 * PAGE_SIZE / 1024))K\n\n\tbucket=$($LCTL get_param -n llite.*.extents_stats |\n\t\t\tgrep -m 1 $bsize)\n\treads=$(echo $bucket | awk '{print $5}')\n\twrites=$(echo $bucket | awk '{print $9}')\n\t# mmap writes fault in the page first, creating an additonal read\n\t[ \"$reads\" -eq $((2 * count)) ] ||\n\t\terror \"$reads reads in < $bsize bucket, expect $count\"\n\t[ \"$writes\" -eq $count ] ||\n\t\terror \"$writes writes in < $bsize bucket, expect $count\"\n}\nrun_test 127c \"test llite extent stats with regular & mmap i/o\"\n\ntest_128() { # bug 15212\n\ttouch $DIR/$tfile\n\t$LFS 2>&1 <<-EOF | tee $TMP/$tfile.log\n\t\tfind $DIR/$tfile\n\t\tfind $DIR/$tfile\n\tEOF\n\n\tresult=$(grep error $TMP/$tfile.log)\n\trm -f $DIR/$tfile $TMP/$tfile.log\n\t[ -z \"$result\" ] ||\n\t\terror \"consecutive find's under interactive lfs failed\"\n}\nrun_test 128 \"interactive lfs for 2 consecutive find's\"\n\nset_dir_limits () {\n\tlocal mntdev\n\tlocal canondev\n\tlocal node\n\n\tlocal ldproc=/proc/fs/ldiskfs\n\tlocal facets=$(get_facets MDS)\n\n\tfor facet in ${facets//,/ }; do\n\t\tcanondev=$(ldiskfs_canon \\\n\t\t\t   *.$(convert_facet2label $facet).mntdev $facet)\n\t\tdo_facet $facet \"test -e $ldproc/$canondev/max_dir_size\" ||\n\t\t\tldproc=/sys/fs/ldiskfs\n\t\tdo_facet $facet \"echo $1 >$ldproc/$canondev/max_dir_size\"\n\t\tdo_facet $facet \"echo $2 >$ldproc/$canondev/warning_dir_size\"\n\tdone\n}\n\ncheck_mds_dmesg() {\n\tlocal facets=$(get_facets MDS)\n\tfor facet in ${facets//,/ }; do\n\t\tdo_facet $facet \"dmesg | tail -3 | grep $1\" && return 0\n\tdone\n\treturn 1\n}\n\ntest_129() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.5.56) ]] ||\n\t\tskip \"Need MDS version with at least 2.5.56\"\n\tif [ \"$mds1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal ENOSPC=28\n\tlocal has_warning=false\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\t# block size of mds1\n\tlocal maxsize=$(($($LCTL get_param -n mdc.*MDT0000*.blocksize) * 8))\n\tset_dir_limits $maxsize $((maxsize * 6 / 8))\n\tstack_trap \"set_dir_limits 0 0\"\n\tstack_trap \"unlinkmany $DIR/$tdir/file_base_ 2000 || true\"\n\tlocal dirsize=$(stat -c%s \"$DIR/$tdir\")\n\tlocal nfiles=0\n\twhile (( $dirsize <= $maxsize )); do\n\t\t$MCREATE $DIR/$tdir/file_base_$nfiles\n\t\trc=$?\n\t\t# check two errors:\n\t\t# ENOSPC for ext4 max_dir_size, which has been used since\n\t\t# kernel v3.6-rc1-8-gdf981d03ee, lustre v2_4_50_0-79-gaed82035c0\n\t\tif (( rc == ENOSPC )); then\n\t\t\tset_dir_limits 0 0\n\t\t\techo \"rc=$rc returned as expected after $nfiles files\"\n\n\t\t\tcreatemany -o $DIR/$tdir/file_extra_$nfiles. 5 ||\n\t\t\t\terror \"create failed w/o dir size limit\"\n\n\t\t\t# messages may be rate limited if test is run repeatedly\n\t\t\tcheck_mds_dmesg '\"is approaching max\"' ||\n\t\t\t\techo \"warning message should be output\"\n\t\t\tcheck_mds_dmesg '\"has reached max\"' ||\n\t\t\t\techo \"reached message should be output\"\n\n\t\t\tdirsize=$(stat -c%s \"$DIR/$tdir\")\n\n\t\t\t[[ $dirsize -ge $maxsize ]] && return 0\n\t\t\terror \"dirsize $dirsize < $maxsize after $nfiles files\"\n\t\telif (( rc != 0 )); then\n\t\t\tbreak\n\t\tfi\n\t\tnfiles=$((nfiles + 1))\n\t\tdirsize=$(stat -c%s \"$DIR/$tdir\")\n\tdone\n\n\terror \"rc=$rc, size=$dirsize/$maxsize, mdt=$MDSCOUNT, nfiles=$nfiles\"\n}\nrun_test 129 \"test directory size limit ========================\"\n\nOLDIFS=\"$IFS\"\ncleanup_130() {\n\ttrap 0\n\tIFS=\"$OLDIFS\"\n}\n\ntest_130a() {\n\tlocal filefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip_env \"filefrag does not support FIEMAP\"\n\n\ttrap cleanup_130 EXIT RETURN\n\n\tlocal fm_file=$DIR/$tfile\n\t$LFS setstripe -S 65536 -c 1 $fm_file || error \"setstripe on $fm_file\"\n\tdd if=/dev/zero of=$fm_file bs=65536 count=1 ||\n\t\terror \"dd failed for $fm_file\"\n\n\t# LU-1795: test filefrag/FIEMAP once, even if unsupported\n\tfilefrag -ves $fm_file\n\tRC=$?\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $fm_file) + 1)))\" = \"zfs\" ] &&\n\t\tskip_env \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\"\n\t[ $RC != 0 ] && error \"filefrag $fm_file failed\"\n\n\tfilefrag_op=$(filefrag -ve -k $fm_file |\n\t\t\tsed -n '/ext:/,/found/{/ext:/d; /found/d; p}')\n\tlun=$($LFS getstripe -i $fm_file)\n\n\tstart_blk=`echo $filefrag_op | cut -d: -f2 | cut -d. -f1`\n\tIFS=$'\\n'\n\ttot_len=0\n\tfor line in $filefrag_op\n\tdo\n\t\tfrag_lun=`echo $line | cut -d: -f5`\n\t\text_len=`echo $line | cut -d: -f4`\n\t\tif (( $frag_lun != $lun )); then\n\t\t\tcleanup_130\n\t\t\terror \"FIEMAP on 1-stripe file($fm_file) failed\"\n\t\t\treturn\n\t\tfi\n\t\t(( tot_len += ext_len ))\n\tdone\n\n\tif (( lun != frag_lun || start_blk != 0 || tot_len != 64 )); then\n\t\tcleanup_130\n\t\terror \"FIEMAP on 1-stripe file($fm_file) failed;\"\n\t\treturn\n\tfi\n\n\tcleanup_130\n\n\techo \"FIEMAP on single striped file succeeded\"\n}\nrun_test 130a \"FIEMAP (1-stripe file)\"\n\ntest_130b() {\n\t[ \"$OSTCOUNT\" -lt \"2\" ] && skip_env \"needs >= 2 OSTs\"\n\n\tlocal filefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip_env \"filefrag does not support FIEMAP\"\n\n\ttrap cleanup_130 EXIT RETURN\n\n\tlocal fm_file=$DIR/$tfile\n\t$LFS setstripe -S 65536 -c $OSTCOUNT $fm_file ||\n\t\t\terror \"setstripe on $fm_file\"\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $fm_file) + 1)))\" = \"zfs\" ] &&\n\t\tskip_env \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\"\n\n\tdd if=/dev/zero of=$fm_file bs=1M count=$OSTCOUNT ||\n\t\terror \"dd failed on $fm_file\"\n\n\tfilefrag -ves $fm_file || error \"filefrag $fm_file failed\"\n\tfilefrag_op=$(filefrag -ve -k $fm_file |\n\t\t\tsed -n '/ext:/,/found/{/ext:/d; /found/d; p}')\n\n\tlast_lun=$(echo $filefrag_op | cut -d: -f5 |\n\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\n\tIFS=$'\\n'\n\ttot_len=0\n\tnum_luns=1\n\tfor line in $filefrag_op\n\tdo\n\t\tfrag_lun=$(echo $line | cut -d: -f5 |\n\t\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\t\text_len=$(echo $line | cut -d: -f4)\n\t\tif (( $frag_lun != $last_lun )); then\n\t\t\tif (( tot_len != 1024 )); then\n\t\t\t\tcleanup_130\n\t\t\t\terror \"FIEMAP on $fm_file failed; returned \" \\\n\t\t\t\t\"len $tot_len for OST $last_lun instead of 1024\"\n\t\t\t\treturn\n\t\t\telse\n\t\t\t\t(( num_luns += 1 ))\n\t\t\t\ttot_len=0\n\t\t\tfi\n\t\tfi\n\t\t(( tot_len += ext_len ))\n\t\tlast_lun=$frag_lun\n\tdone\n\tif (( num_luns != $OSTCOUNT || tot_len != 1024 )); then\n\t\tcleanup_130\n\t\terror \"FIEMAP on $fm_file failed; returned wrong number of \" \\\n\t\t\t\"luns or wrong len for OST $last_lun\"\n\t\treturn\n\tfi\n\n\tcleanup_130\n\n\techo \"FIEMAP on $OSTCOUNT-stripe file succeeded\"\n}\nrun_test 130b \"FIEMAP ($OSTCOUNT-stripe file)\"\n\ntest_130c() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tfilefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip \"filefrag does not support FIEMAP\"\n\n\ttrap cleanup_130 EXIT RETURN\n\n\tlocal fm_file=$DIR/$tfile\n\t$LFS setstripe -S 65536 -c 2 $fm_file || error \"setstripe on $fm_file\"\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $fm_file) + 1)))\" = \"zfs\" ] &&\n\t\tskip_env \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\"\n\n\tdd if=/dev/zero of=$fm_file seek=1 bs=1M count=1 ||\n\t\t\terror \"dd failed on $fm_file\"\n\n\tfilefrag -ves $fm_file || error \"filefrag $fm_file failed\"\n\tfilefrag_op=$(filefrag -ve -k $fm_file |\n\t\tsed -n '/ext:/,/found/{/ext:/d; /found/d; p}')\n\n\tlast_lun=$(echo $filefrag_op | cut -d: -f5 |\n\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\n\tIFS=$'\\n'\n\ttot_len=0\n\tnum_luns=1\n\tfor line in $filefrag_op\n\tdo\n\t\tfrag_lun=$(echo $line | cut -d: -f5 |\n\t\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\t\text_len=$(echo $line | cut -d: -f4)\n\t\tif (( $frag_lun != $last_lun )); then\n\t\t\tlogical=`echo $line | cut -d: -f2 | cut -d. -f1`\n\t\t\tif (( logical != 512 )); then\n\t\t\t\tcleanup_130\n\t\t\t\terror \"FIEMAP on $fm_file failed; returned \" \\\n\t\t\t\t\"logical start for lun $logical instead of 512\"\n\t\t\t\treturn\n\t\t\tfi\n\t\t\tif (( tot_len != 512 )); then\n\t\t\t\tcleanup_130\n\t\t\t\terror \"FIEMAP on $fm_file failed; returned \" \\\n\t\t\t\t\"len $tot_len for OST $last_lun instead of 1024\"\n\t\t\t\treturn\n\t\t\telse\n\t\t\t\t(( num_luns += 1 ))\n\t\t\t\ttot_len=0\n\t\t\tfi\n\t\tfi\n\t\t(( tot_len += ext_len ))\n\t\tlast_lun=$frag_lun\n\tdone\n\tif (( num_luns != 2 || tot_len != 512 )); then\n\t\tcleanup_130\n\t\terror \"FIEMAP on $fm_file failed; returned wrong number of \" \\\n\t\t\t\"luns or wrong len for OST $last_lun\"\n\t\treturn\n\tfi\n\n\tcleanup_130\n\n\techo \"FIEMAP on 2-stripe file with hole succeeded\"\n}\nrun_test 130c \"FIEMAP (2-stripe file with hole)\"\n\ntest_130d() {\n\t[[ $OSTCOUNT -lt 3 ]] && skip_env \"needs >= 3 OSTs\"\n\n\tfilefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip \"filefrag does not support FIEMAP\"\n\n\ttrap cleanup_130 EXIT RETURN\n\n\tlocal fm_file=$DIR/$tfile\n\t$LFS setstripe -S 65536 -c $OSTCOUNT $fm_file ||\n\t\t\terror \"setstripe on $fm_file\"\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $fm_file) + 1)))\" = \"zfs\" ] &&\n\t\tskip_env \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\"\n\n\tlocal actual_stripe_count=$($LFS getstripe -c $fm_file)\n\tdd if=/dev/zero of=$fm_file bs=1M count=$actual_stripe_count ||\n\t\terror \"dd failed on $fm_file\"\n\n\tfilefrag -ves $fm_file || error \"filefrag $fm_file failed\"\n\tfilefrag_op=$(filefrag -ve -k $fm_file |\n\t\t\tsed -n '/ext:/,/found/{/ext:/d; /found/d; p}')\n\n\tlast_lun=$(echo $filefrag_op | cut -d: -f5 |\n\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\n\tIFS=$'\\n'\n\ttot_len=0\n\tnum_luns=1\n\tfor line in $filefrag_op\n\tdo\n\t\tfrag_lun=$(echo $line | cut -d: -f5 |\n\t\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\t\text_len=$(echo $line | cut -d: -f4)\n\t\tif (( $frag_lun != $last_lun )); then\n\t\t\tif (( tot_len != 1024 )); then\n\t\t\t\tcleanup_130\n\t\t\t\terror \"FIEMAP on $fm_file failed; returned \" \\\n\t\t\t\t\"len $tot_len for OST $last_lun instead of 1024\"\n\t\t\t\treturn\n\t\t\telse\n\t\t\t\t(( num_luns += 1 ))\n\t\t\t\ttot_len=0\n\t\t\tfi\n\t\tfi\n\t\t(( tot_len += ext_len ))\n\t\tlast_lun=$frag_lun\n\tdone\n\tif (( num_luns != actual_stripe_count || tot_len != 1024 )); then\n\t\tcleanup_130\n\t\terror \"FIEMAP on $fm_file failed; returned wrong number of \" \\\n\t\t\t\"luns or wrong len for OST $last_lun\"\n\t\treturn\n\tfi\n\n\tcleanup_130\n\n\techo \"FIEMAP on N-stripe file succeeded\"\n}\nrun_test 130d \"FIEMAP (N-stripe file)\"\n\ntest_130e() {\n\t[[ $OSTCOUNT -lt 2 ]] && skip_env \"needs >= 2 OSTs\"\n\n\tfilefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip_env \"filefrag does not support FIEMAP\"\n\n\ttrap cleanup_130 EXIT RETURN\n\n\tlocal fm_file=$DIR/$tfile\n\t$LFS setstripe -S 131072 -c 2 $fm_file || error \"setstripe on $fm_file\"\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $fm_file) + 1)))\" = \"zfs\" ] &&\n\t\tskip_env \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\"\n\n\tNUM_BLKS=512\n\tEXPECTED_LEN=$(( (NUM_BLKS / 2) * 64 ))\n\tfor ((i = 0; i < $NUM_BLKS; i++))\n\tdo\n\t\tdd if=/dev/zero of=$fm_file count=1 bs=64k seek=$((2*$i)) conv=notrunc > /dev/null 2>&1\n\tdone\n\n\tfilefrag -ves $fm_file || error \"filefrag $fm_file failed\"\n\tfilefrag_op=$(filefrag -ve -k $fm_file |\n\t\t\tsed -n '/ext:/,/found/{/ext:/d; /found/d; p}')\n\n\tlast_lun=$(echo $filefrag_op | cut -d: -f5 |\n\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\n\tIFS=$'\\n'\n\ttot_len=0\n\tnum_luns=1\n\tfor line in $filefrag_op\n\tdo\n\t\tfrag_lun=$(echo $line | cut -d: -f5 |\n\t\t\tsed -e 's/^[ \\t]*/0x/' | sed -e 's/0x0x/0x/')\n\t\text_len=$(echo $line | cut -d: -f4)\n\t\tif (( $frag_lun != $last_lun )); then\n\t\t\tif (( tot_len != $EXPECTED_LEN )); then\n\t\t\t\tcleanup_130\n\t\t\t\terror \"FIEMAP on $fm_file failed; returned \" \\\n\t\t\t\t\"len $tot_len for OST $last_lun instead \" \\\n\t\t\t\t\"of $EXPECTED_LEN\"\n\t\t\t\treturn\n\t\t\telse\n\t\t\t\t(( num_luns += 1 ))\n\t\t\t\ttot_len=0\n\t\t\tfi\n\t\tfi\n\t\t(( tot_len += ext_len ))\n\t\tlast_lun=$frag_lun\n\tdone\n\tif (( num_luns != 2 || tot_len != $EXPECTED_LEN )); then\n\t\tcleanup_130\n\t\terror \"FIEMAP on $fm_file failed; returned wrong number \" \\\n\t\t\t\"of luns or wrong len for OST $last_lun\"\n\t\treturn\n\tfi\n\n\tcleanup_130\n\n\techo \"FIEMAP with continuation calls succeeded\"\n}\nrun_test 130e \"FIEMAP (test continuation FIEMAP calls)\"\n\ntest_130f() {\n\tfilefrag_op=$(filefrag -e 2>&1 | grep \"invalid option\")\n\t[ -n \"$filefrag_op\" ] && skip \"filefrag does not support FIEMAP\"\n\n\tlocal fm_file=$DIR/$tfile\n\t$MULTIOP $fm_file oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:T33554432c ||\n\t\terror \"multiop create with lov_delay_create on $fm_file\"\n\n\tfilefrag -ves $fm_file || error \"filefrag $fm_file failed\"\n\tfilefrag_extents=$(filefrag -vek $fm_file |\n\t\t\t   awk '/extents? found/ { print $2 }')\n\tif [[ \"$filefrag_extents\" != \"0\" ]]; then\n\t\terror \"FIEMAP on $fm_file failed; \" \\\n\t\t      \"returned $filefrag_extents expected 0\"\n\tfi\n\n\trm -f $fm_file\n}\nrun_test 130f \"FIEMAP (unstriped file)\"\n\n# Test for writev/readv\ntest_131a() {\n\trwv -f $DIR/$tfile -w -n 3 524288 1048576 1572864 ||\n\t\terror \"writev test failed\"\n\trwv -f $DIR/$tfile -r -v -n 2 1572864 1048576 ||\n\t\terror \"readv failed\"\n\trm -f $DIR/$tfile\n}\nrun_test 131a \"test iov's crossing stripe boundary for writev/readv\"\n\ntest_131b() {\n\tlocal fsize=$((524288 + 1048576 + 1572864))\n\trwv -f $DIR/$tfile -w -a -n 3 524288 1048576 1572864 &&\n\t\t$CHECKSTAT -t file $DIR/$tfile -s $fsize ||\n\t\t\terror \"append writev test failed\"\n\n\t((fsize += 1572864 + 1048576))\n\trwv -f $DIR/$tfile -w -a -n 2 1572864 1048576 &&\n\t\t$CHECKSTAT -t file $DIR/$tfile -s $fsize ||\n\t\t\terror \"append writev test failed\"\n\trm -f $DIR/$tfile\n}\nrun_test 131b \"test append writev\"\n\ntest_131c() {\n\trwv -f $DIR/$tfile -w -d -n 1 1048576 || return 0\n\terror \"NOT PASS\"\n}\nrun_test 131c \"test read/write on file w/o objects\"\n\ntest_131d() {\n\trwv -f $DIR/$tfile -w -n 1 1572864\n\tNOB=`rwv -f $DIR/$tfile -r -n 3 524288 524288 1048576 | awk '/error/ {print $6}'`\n\tif [ \"$NOB\" != 1572864 ]; then\n\t\terror \"Short read filed: read $NOB bytes instead of 1572864\"\n\tfi\n\trm -f $DIR/$tfile\n}\nrun_test 131d \"test short read\"\n\ntest_131e() {\n\trwv -f $DIR/$tfile -w -s 1048576 -n 1 1048576\n\trwv -f $DIR/$tfile -r -z -s 0 -n 1 524288 || \\\n\terror \"read hitting hole failed\"\n\trm -f $DIR/$tfile\n}\nrun_test 131e \"test read hitting hole\"\n\ncheck_stats() {\n\tlocal facet=$1\n\tlocal op=$2\n\tlocal want=${3:-0}\n\tlocal res\n\n\tcase $facet in\n\tmds*) res=$(do_facet $facet \\\n\t\t   $LCTL get_param mdt.$FSNAME-MDT0000.md_stats | grep \"$op\")\n\t\t ;;\n\tost*) res=$(do_facet $facet \\\n\t\t   $LCTL get_param obdfilter.$FSNAME-OST0000.stats | grep \"$op\")\n\t\t ;;\n\t*) error \"Wrong facet '$facet'\" ;;\n\tesac\n\t[ \"$res\" ] || error \"The counter for $op on $facet was not incremented\"\n\t# if the argument $3 is zero, it means any stat increment is ok.\n\tif [[ $want -gt 0 ]]; then\n\t\tlocal count=$(echo $res | awk '{ print $2 }')\n\t\t[[ $count -ne $want ]] &&\n\t\t\terror \"The $op counter on $facet is $count, not $want\"\n\tfi\n}\n\ntest_133a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tdo_facet $SINGLEMDS $LCTL list_param mdt.*.rename_stats ||\n\t\tskip_env \"MDS doesn't support rename stats\"\n\n\tlocal testdir=$DIR/${tdir}/stats_testdir\n\n\tmkdir -p $DIR/${tdir}\n\n\t# clear stats.\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tdo_facet ost1 $LCTL set_param obdfilter.*.stats=clear\n\n\t# verify mdt stats first.\n\tmkdir ${testdir} || error \"mkdir failed\"\n\tcheck_stats $SINGLEMDS \"mkdir\" 1\n\ttouch ${testdir}/${tfile} || error \"touch failed\"\n\tcheck_stats $SINGLEMDS \"open\" 1\n\tcheck_stats $SINGLEMDS \"close\" 1\n\t[ $MDS1_VERSION -ge $(version_code 2.8.54) ] && {\n\t\tmknod ${testdir}/${tfile}-pipe p || error \"mknod failed\"\n\t\tcheck_stats $SINGLEMDS \"mknod\" 2\n\t}\n\trm -f ${testdir}/${tfile}-pipe || error \"pipe remove failed\"\n\tcheck_stats $SINGLEMDS \"unlink\" 1\n\trm -f ${testdir}/${tfile} || error \"file remove failed\"\n\tcheck_stats $SINGLEMDS \"unlink\" 2\n\n\t# remove working dir and check mdt stats again.\n\trmdir ${testdir} || error \"rmdir failed\"\n\tcheck_stats $SINGLEMDS \"rmdir\" 1\n\n\tlocal testdir1=$DIR/${tdir}/stats_testdir1\n\tmkdir -p ${testdir}\n\tmkdir -p ${testdir1}\n\ttouch ${testdir1}/test1\n\tmv ${testdir1}/test1 ${testdir} || error \"file crossdir rename\"\n\tcheck_stats $SINGLEMDS \"crossdir_rename\" 1\n\n\tmv ${testdir}/test1 ${testdir}/test0 || error \"file samedir rename\"\n\tcheck_stats $SINGLEMDS \"samedir_rename\" 1\n\n\trm -rf $DIR/${tdir}\n}\nrun_test 133a \"Verifying MDT stats ========================================\"\n\ntest_133b() {\n\tlocal res\n\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal testdir=$DIR/${tdir}/stats_testdir\n\n\tmkdir -p ${testdir} || error \"mkdir failed\"\n\ttouch ${testdir}/${tfile} || error \"touch failed\"\n\tcancel_lru_locks mdc\n\n\t# clear stats.\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tdo_facet ost1 $LCTL set_param obdfilter.*.stats=clear\n\n\t# extra mdt stats verification.\n\tchmod 444 ${testdir}/${tfile} || error \"chmod failed\"\n\tcheck_stats $SINGLEMDS \"setattr\" 1\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tif [ $MDS1_VERSION -ne $(version_code 2.2.0) ]\n\tthen\t\t# LU-1740\n\t\tls -l ${testdir}/${tfile} > /dev/null|| error \"ls failed\"\n\t\tcheck_stats $SINGLEMDS \"getattr\" 1\n\tfi\n\trm -rf $DIR/${tdir}\n\n\t# when DNE is enabled, MDT uses STATFS RPC to ping other targets\n\t# so the check below is not reliable\n\t[ $MDSCOUNT -eq 1 ] || return 0\n\n\t# Sleep to avoid a cached response.\n\t#define OBD_STATFS_CACHE_SECONDS 1\n\tsleep 2\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tdo_facet ost1 $LCTL set_param obdfilter.*.exports.*.stats=clear\n\t$LFS df || error \"lfs failed\"\n\tcheck_stats $SINGLEMDS \"statfs\" 1\n\n\t# check aggregated statfs (LU-10018)\n\t[ $MDS1_VERSION -lt $(version_code 2.11.54) ] &&\n\t\treturn 0\n\t[ $CLIENT_VERSION -lt $(version_code 2.11.54) ] &&\n\t\treturn 0\n\tsleep 2\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tdo_facet ost1 $LCTL set_param obdfilter.*.exports.*.stats=clear\n\tdf $DIR\n\tcheck_stats $SINGLEMDS \"statfs\" 1\n\n\t# We want to check that the client didn't send OST_STATFS to\n\t# ost1 but the MDT also uses OST_STATFS for precreate. So some\n\t# extra care is needed here.\n\tif remote_mds; then\n\t\tlocal nid=$($LCTL list_nids | head -1 | sed  \"s/\\./\\\\\\./g\")\n\t\tlocal param=\"obdfilter.$FSNAME-OST0000.exports.'$nid'.stats\"\n\n\t\tres=$(do_facet ost1 $LCTL get_param $param | grep statfs)\n\t\t[ \"$res\" ] && error \"OST got STATFS\"\n\tfi\n\n\treturn 0\n}\nrun_test 133b \"Verifying extra MDT stats ==================================\"\n\ntest_133c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal testdir=$DIR/$tdir/stats_testdir\n\n\ttest_mkdir -p $testdir\n\n\t# verify obdfilter stats.\n\t$LFS setstripe -c 1 -i 0 $testdir/$tfile\n\tsync\n\tcancel_lru_locks osc\n\twait_delete_completed\n\n\t# clear stats.\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.md_stats=clear\n\tdo_facet ost1 $LCTL set_param obdfilter.*.stats=clear\n\n\tdd if=/dev/zero of=$testdir/$tfile conv=notrunc bs=512k count=1 ||\n\t\terror \"dd failed\"\n\tsync\n\tcancel_lru_locks osc\n\tcheck_stats ost1 \"write\" 1\n\n\tdd if=$testdir/$tfile of=/dev/null bs=1k count=1 || error \"dd failed\"\n\tcheck_stats ost1 \"read\" 1\n\n\t> $testdir/$tfile || error \"truncate failed\"\n\tcheck_stats ost1 \"punch\" 1\n\n\trm -f $testdir/$tfile || error \"file remove failed\"\n\twait_delete_completed\n\tcheck_stats ost1 \"destroy\" 1\n\n\trm -rf $DIR/$tdir\n}\nrun_test 133c \"Verifying OST stats ========================================\"\n\norder_2() {\n\tlocal value=$1\n\tlocal orig=$value\n\tlocal order=1\n\n\twhile [ $value -ge 2 ]; do\n\t\torder=$((order*2))\n\t\tvalue=$((value/2))\n\tdone\n\n\tif [ $orig -gt $order ]; then\n\t\torder=$((order*2))\n\tfi\n\techo $order\n}\n\nsize_in_KMGT() {\n    local value=$1\n    local size=('K' 'M' 'G' 'T');\n    local i=0\n    local size_string=$value\n\n    while [ $value -ge 1024 ]; do\n        if [ $i -gt 3 ]; then\n            #T is the biggest unit we get here, if that is bigger,\n            #just return XXXT\n            size_string=${value}T\n            break\n        fi\n        value=$((value >> 10))\n        if [ $value -lt 1024 ]; then\n            size_string=${value}${size[$i]}\n            break\n        fi\n        i=$((i + 1))\n    done\n\n    echo $size_string\n}\n\nget_rename_size() {\n\tlocal size=$1\n\tlocal context=${2:-.}\n\tlocal sample=$(do_facet $SINGLEMDS $LCTL \\\n\t\tget_param mdt.$FSNAME-MDT0000.rename_stats |\n\t\tgrep -A1 $context |\n\t\tawk '/ '${size}'/ {print $4}' | sed -e \"s/,//g\")\n\techo $sample\n}\n\ntest_133d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tdo_facet $SINGLEMDS $LCTL list_param mdt.*.rename_stats ||\n\t\tskip_env \"MDS doesn't support rename stats\"\n\n\tlocal testdir1=$DIR/${tdir}/stats_testdir1\n\tlocal testdir2=$DIR/${tdir}/stats_testdir2\n\tmkdir -p $DIR/${tdir}\n\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.rename_stats=clear\n\n\tlfs mkdir -i 0 -c 1 ${testdir1} || error \"mkdir failed\"\n\tlfs mkdir -i 0 -c 1 ${testdir2} || error \"mkdir failed\"\n\n\tcreatemany -o $testdir1/test 512 || error \"createmany failed\"\n\n\t# check samedir rename size\n\tmv ${testdir1}/test0 ${testdir1}/test_0\n\n\tlocal testdir1_size=$(ls -l $DIR/${tdir} |\n\t\tawk '/stats_testdir1/ {print $5}')\n\tlocal testdir2_size=$(ls -l $DIR/${tdir} |\n\t\tawk '/stats_testdir2/ {print $5}')\n\n\ttestdir1_size=$(order_2 $testdir1_size)\n\ttestdir2_size=$(order_2 $testdir2_size)\n\n\ttestdir1_size=$(size_in_KMGT $testdir1_size)\n\ttestdir2_size=$(size_in_KMGT $testdir2_size)\n\n\techo \"source rename dir size: ${testdir1_size}\"\n\techo \"target rename dir size: ${testdir2_size}\"\n\n\tlocal cmd=\"do_facet $SINGLEMDS $LCTL \"\n\tcmd+=\"get_param mdt.$FSNAME-MDT0000.rename_stats\"\n\n\teval $cmd || error \"$cmd failed\"\n\tlocal samedir=$($cmd | grep 'same_dir')\n\tlocal same_sample=$(get_rename_size $testdir1_size)\n\t[ -z \"$samedir\" ] && error \"samedir_rename_size count error\"\n\t[[ $same_sample -eq 1 ]] ||\n\t\terror \"samedir_rename_size error $same_sample\"\n\techo \"Check same dir rename stats success\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.rename_stats=clear\n\n\t# check crossdir rename size\n\tmv ${testdir1}/test_0 ${testdir2}/test_0\n\n\ttestdir1_size=$(ls -l $DIR/${tdir} |\n\t\tawk '/stats_testdir1/ {print $5}')\n\ttestdir2_size=$(ls -l $DIR/${tdir} |\n\t\tawk '/stats_testdir2/ {print $5}')\n\n\ttestdir1_size=$(order_2 $testdir1_size)\n\ttestdir2_size=$(order_2 $testdir2_size)\n\n\ttestdir1_size=$(size_in_KMGT $testdir1_size)\n\ttestdir2_size=$(size_in_KMGT $testdir2_size)\n\n\techo \"source rename dir size: ${testdir1_size}\"\n\techo \"target rename dir size: ${testdir2_size}\"\n\n\teval $cmd || error \"$cmd failed\"\n\tlocal crossdir=$($cmd | grep 'crossdir')\n\tlocal src_sample=$(get_rename_size $testdir1_size crossdir_src)\n\tlocal tgt_sample=$(get_rename_size $testdir2_size crossdir_tgt)\n\t[ -z \"$crossdir\" ] && error \"crossdir_rename_size count error\"\n\t[[ $src_sample -eq 1 ]] ||\n\t\terror \"crossdir_rename_size error $src_sample\"\n\t[[ $tgt_sample -eq 1 ]] ||\n\t\terror \"crossdir_rename_size error $tgt_sample\"\n\techo \"Check cross dir rename stats success\"\n\trm -rf $DIR/${tdir}\n}\nrun_test 133d \"Verifying rename_stats ========================================\"\n\ntest_133e() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal testdir=$DIR/${tdir}/stats_testdir\n\tlocal ctr f0 f1 bs=32768 count=42 sum\n\n\tmkdir -p ${testdir} || error \"mkdir failed\"\n\n\t$LFS setstripe -c 1 -i 0 ${testdir}/${tfile}\n\n\tfor ctr in {write,read}_bytes; do\n\t\tsync\n\t\tcancel_lru_locks osc\n\n\t\tdo_facet ost1 $LCTL set_param -n \\\n\t\t\t\"obdfilter.*.exports.clear=clear\"\n\n\t\tif [ $ctr = write_bytes ]; then\n\t\t\tf0=/dev/zero\n\t\t\tf1=${testdir}/${tfile}\n\t\telse\n\t\t\tf0=${testdir}/${tfile}\n\t\t\tf1=/dev/null\n\t\tfi\n\n\t\tdd if=$f0 of=$f1 conv=notrunc bs=$bs count=$count || \\\n\t\t\terror \"dd failed\"\n\t\tsync\n\t\tcancel_lru_locks osc\n\n\t\tsum=$(do_facet ost1 $LCTL get_param \\\n\t\t\t\"obdfilter.*.exports.*.stats\" |\n\t\t\tawk -v ctr=$ctr 'BEGIN { sum = 0 }\n\t\t\t\t$1 == ctr { sum += $7 }\n\t\t\t\tEND { printf(\"%0.0f\", sum) }')\n\n\t\tif ((sum != bs * count)); then\n\t\t\terror \"Bad $ctr sum, expected $((bs * count)), got $sum\"\n\t\tfi\n\tdone\n\n\trm -rf $DIR/${tdir}\n}\nrun_test 133e \"Verifying OST {read,write}_bytes nid stats =================\"\n\ntest_133f() {\n\t[[ $(lustre_version_code $facet) -ge $(version_code 2.7.65) ]] ||\n\t\tskip \"too old lustre for get_param -R ($facet_ver)\"\n\n\t# verifying readability.\n\t$LCTL get_param -R '*' &> /dev/null\n\n\t# Verifing writability with badarea_io.\n\t$LCTL list_param -FR '*' | grep '=' | tr -d = |\n\t\tegrep -v 'force_lbug|changelog_mask' | xargs badarea_io ||\n\t\terror \"client badarea_io failed\"\n\n\t# remount the FS in case writes/reads /proc break the FS\n\tcleanup || error \"failed to unmount\"\n\tsetup || error \"failed to setup\"\n}\nrun_test 133f \"Check reads/writes of client lustre proc files with bad area io\"\n\ntest_133g() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal facet\n\tfor facet in mds1 ost1; do\n\t\tlocal facet_ver=$(lustre_version_code $facet)\n\t\tif [ $facet_ver -ge $(version_code 2.7.65) ]; then\n\t\t\tdo_facet $facet \"$LCTL get_param -R '*'\" &> /dev/null\n\t\telse\n\t\t\tlog \"$facet: too old lustre for get_param -R\"\n\t\tfi\n\t\tif [ $facet_ver -ge $(version_code 2.5.54) ]; then\n\t\t\tdo_facet $facet \"$LCTL list_param -FR '*' | grep '=' |\n\t\t\t\ttr -d = | egrep -v 'force_lbug|changelog_mask' |\n\t\t\t\txargs badarea_io\" ||\n\t\t\t\t\terror \"$facet badarea_io failed\"\n\t\telse\n\t\t\tskip_noexit \"$facet: too old lustre for get_param -R\"\n\t\tfi\n\tdone\n\n\t# remount the FS in case writes/reads /proc break the FS\n\tcleanup || error \"failed to unmount\"\n\tsetup || error \"failed to setup\"\n}\nrun_test 133g \"Check reads/writes of server lustre proc files with bad area io\"\n\ntest_133h() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.9.54) ]] &&\n\t\tskip \"Need MDS version at least 2.9.54\"\n\n\tlocal facet\n\tfor facet in client mds1 ost1; do\n\t\t# Get the list of files that are missing the terminating newline\n\t\tlocal plist=$(do_facet $facet\n\t\t\t$LCTL list_param -FR '*' | grep '=' | tr -d =)\n\t\tlocal ent\n\t\tfor ent in $plist; do\n\t\t\tlocal missing=$(do_facet $facet $LCTL get_param $ent \\|\\\n\t\t\t\tawk -v FS='\\v' -v RS='\\v\\v' \\\n\t\t\t\t\"'END { if(NR>0 && \\\\\\$NF !~ /.*\\\\\\n\\$/) \\\n\t\t\t\t\tprint FILENAME}'\" 2>/dev/null)\n\t\t\t[ -z $missing ] || {\n\t\t\t\tdo_facet $facet $LCTL get_param $ent | od -An -tx1\n\t\t\t\terror \"file does not end with newline: $facet-$ent\"\n\t\t\t}\n\t\tdone\n\tdone\n}\nrun_test 133h \"Proc files should end with newlines\"\n\ntest_134a() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.54) ]] &&\n\t\tskip \"Need MDS version at least 2.7.54\"\n\n\tmkdir -p $DIR/$tdir || error \"failed to create $DIR/$tdir\"\n\tcancel_lru_locks mdc\n\n\tlocal nsdir=\"ldlm.namespaces.*-MDT0000-mdc-*\"\n\tlocal unused=$($LCTL get_param -n $nsdir.lock_unused_count)\n\t[ $unused -eq 0 ] || error \"$unused locks are not cleared\"\n\n\tlocal nr=1000\n\tcreatemany -o $DIR/$tdir/f $nr ||\n\t\terror \"failed to create $nr files in $DIR/$tdir\"\n\tunused=$($LCTL get_param -n $nsdir.lock_unused_count)\n\n\t#define OBD_FAIL_LDLM_WATERMARK_LOW     0x327\n\tdo_facet mds1 $LCTL set_param fail_loc=0x327\n\tdo_facet mds1 $LCTL set_param fail_val=500\n\ttouch $DIR/$tdir/m\n\n\techo \"sleep 10 seconds ...\"\n\tsleep 10\n\tlocal lck_cnt=$($LCTL get_param -n $nsdir.lock_unused_count)\n\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tdo_facet mds1 $LCTL set_param fail_val=0\n\t[ $lck_cnt -lt $unused ] ||\n\t\terror \"No locks reclaimed, before:$unused, after:$lck_cnt\"\n\n\trm $DIR/$tdir/m\n\tunlinkmany $DIR/$tdir/f $nr\n}\nrun_test 134a \"Server reclaims locks when reaching lock_reclaim_threshold\"\n\ntest_134b() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.54) ]] &&\n\t\tskip \"Need MDS version at least 2.7.54\"\n\n\tmkdir -p $DIR/$tdir || error \"failed to create $DIR/$tdir\"\n\tcancel_lru_locks mdc\n\n\tlocal low_wm=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\tldlm.lock_reclaim_threshold_mb)\n\t# disable reclaim temporarily\n\tdo_facet mds1 $LCTL set_param ldlm.lock_reclaim_threshold_mb=0\n\n\t#define OBD_FAIL_LDLM_WATERMARK_HIGH     0x328\n\tdo_facet mds1 $LCTL set_param fail_loc=0x328\n\tdo_facet mds1 $LCTL set_param fail_val=500\n\n\t$LCTL set_param debug=+trace\n\n\tlocal nr=600\n\tcreatemany -o $DIR/$tdir/f $nr &\n\tlocal create_pid=$!\n\n\techo \"Sleep $TIMEOUT seconds ...\"\n\tsleep $TIMEOUT\n\tif ! ps -p $create_pid  > /dev/null 2>&1; then\n\t\tdo_facet mds1 $LCTL set_param fail_loc=0\n\t\tdo_facet mds1 $LCTL set_param fail_val=0\n\t\tdo_facet mds1 $LCTL set_param \\\n\t\t\tldlm.lock_reclaim_threshold_mb=${low_wm}m\n\t\terror \"createmany finished incorrectly!\"\n\tfi\n\tdo_facet mds1 $LCTL set_param fail_loc=0\n\tdo_facet mds1 $LCTL set_param fail_val=0\n\tdo_facet mds1 $LCTL set_param ldlm.lock_reclaim_threshold_mb=${low_wm}m\n\twait $create_pid || return 1\n\n\tunlinkmany $DIR/$tdir/f $nr\n}\nrun_test 134b \"Server rejects lock request when reaching lock_limit_mb\"\n\ntest_135() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.13.50) ]] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\tlocal fname\n\n\tmkdir -p $DIR/$tdir || error \"failed to create $DIR/$tdir\"\n\n#define OBD_FAIL_PLAIN_RECORDS 0x1319\n\t#set only one record at plain llog\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x1319 fail_val=1\n\n\t#fill already existed plain llog each 64767\n\t#wrapping whole catalog\n\tcreatemany -o -u $DIR/$tdir/$tfile- $((64767 * 1))\n\n\tcreatemany -o $DIR/$tdir/$tfile_ 64700\n\tfor (( i = 0; i < 64700; i = i + 2 ))\n\tdo\n\t\trm $DIR/$tdir/$tfile_$i &\n\t\trm $DIR/$tdir/$tfile_$((i + 1)) &\n\t\tlocal pid=$!\n\t\twait $pid\n\tdone\n\n\t#waiting osp synchronization\n\twait_delete_completed\n}\nrun_test 135 \"Race catalog processing\"\n\ntest_136() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.13.50) ]] &&\n\t\tskip \"Need MDS version at least 2.13.50\"\n\tlocal fname\n\n\tmkdir -p $DIR/$tdir || error \"failed to create $DIR/$tdir\"\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir || error \"failed to set striping\"\n\t#set only one record at plain llog\n#define OBD_FAIL_CATALOG_FULL_CHECK                0x131a\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x131a fail_val=1\n\n\t#fill already existed 2 plain llogs each 64767\n\t#wrapping whole catalog\n\tcreatemany -o -u $DIR/$tdir/$tfile- $((64767 * 1))\n\tcreatemany -o -u $DIR/$tdir/$tfile- $((64767 * 3 / 2))\n\twait_delete_completed\n\n\tcreatemany -o $DIR/$tdir/$tfile_ 10\n\tsleep 25\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_val=3\n\tfor (( i = 0; i < 10; i = i + 3 ))\n\tdo\n\t\trm $DIR/$tdir/$tfile_$i &\n\t\trm $DIR/$tdir/$tfile_$((i + 1)) &\n\t\tlocal pid=$!\n\t\twait $pid\n\t\tsleep 7\n\t\trm $DIR/$tdir/$tfile_$((i + 2)) &\n\tdone\n\n\t#waiting osp synchronization\n\twait_delete_completed\n}\nrun_test 136 \"Race catalog processing 2\"\n\ntest_140() { #bug-17379\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir $DIR/$tdir\n\tcd $DIR/$tdir || error \"Changing to $DIR/$tdir\"\n\tcp $(which stat) . || error \"Copying stat to $DIR/$tdir\"\n\n\t# VFS limits max symlink depth to 5(4KSTACK) or 7(8KSTACK) or 8\n\t# For kernel > 3.5, bellow only tests consecutive symlink (MAX 40)\n\tlocal i=0\n\twhile i=$((i + 1)); do\n\t\ttest_mkdir $i\n\t\tcd $i || error \"Changing to $i\"\n\t\tln -s ../stat stat || error \"Creating stat symlink\"\n\t\t# Read the symlink until ELOOP present,\n\t\t# not LBUGing the system is considered success,\n\t\t# we didn't overrun the stack.\n\t\t$OPENFILE -f O_RDONLY stat >/dev/null 2>&1; ret=$?\n\t\tif [ $ret -ne 0 ]; then\n\t\t\tif [ $ret -eq 40 ]; then\n\t\t\t\tbreak  # -ELOOP\n\t\t\telse\n\t\t\t\terror \"Open stat symlink\"\n\t\t\t\t\treturn\n\t\t\tfi\n\t\tfi\n\tdone\n\ti=$((i - 1))\n\techo \"The symlink depth = $i\"\n\t[ $i -eq 5 ] || [ $i -eq 7 ] || [ $i -eq 8 ] || [ $i -eq 40 ] ||\n\t\terror \"Invalid symlink depth\"\n\n\t# Test recursive symlink\n\tln -s symlink_self symlink_self\n\t$OPENFILE -f O_RDONLY symlink_self >/dev/null 2>&1; ret=$?\n\techo \"open symlink_self returns $ret\"\n\t[ $ret -eq 40 ] || error \"recursive symlink doesn't return -ELOOP\"\n}\nrun_test 140 \"Check reasonable stack depth (shouldn't LBUG) ====\"\n\ntest_150a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal TF=\"$TMP/$tfile\"\n\n\tdd if=/dev/urandom of=$TF bs=6096 count=1 || error \"dd failed\"\n\tcp $TF $DIR/$tfile\n\tcancel_lru_locks $OSC\n\tcmp $TF $DIR/$tfile || error \"$TMP/$tfile $DIR/$tfile differ\"\n\tremount_client $MOUNT\n\tdf -P $MOUNT\n\tcmp $TF $DIR/$tfile || error \"$TF $DIR/$tfile differ (remount)\"\n\n\t$TRUNCATE $TF 6000\n\t$TRUNCATE $DIR/$tfile 6000\n\tcancel_lru_locks $OSC\n\tcmp $TF $DIR/$tfile || error \"$TF $DIR/$tfile differ (truncate1)\"\n\n\techo \"12345\" >>$TF\n\techo \"12345\" >>$DIR/$tfile\n\tcancel_lru_locks $OSC\n\tcmp $TF $DIR/$tfile || error \"$TF $DIR/$tfile differ (append1)\"\n\n\techo \"12345\" >>$TF\n\techo \"12345\" >>$DIR/$tfile\n\tcancel_lru_locks $OSC\n\tcmp $TF $DIR/$tfile || error \"$TF $DIR/$tfile differ (append2)\"\n\n\trm -f $TF\n\ttrue\n}\nrun_test 150a \"truncate/append tests\"\n\ntest_150b() {\n\t[ \"$ost1_FSTYPE\" != ldiskfs ] && skip \"non-ldiskfs backend\"\n\t[ $OST1_VERSION -lt $(version_code 2.13.50) ] &&\n\t\tskip \"Need OST version at least 2.13.53\"\n\ttouch $DIR/$tfile\n\tcheck_fallocate $DIR/$tfile || error \"fallocate failed\"\n}\nrun_test 150b \"Verify fallocate (prealloc) functionality\"\n\ntest_150c() {\n\tlocal bytes\n\tlocal want\n\n\t[ \"$ost1_FSTYPE\" != ldiskfs ] && skip \"non-ldiskfs backend\"\n\t[ $OST1_VERSION -lt $(version_code 2.13.50) ] &&\n\t\tskip \"Need OST version at least 2.13.53\"\n\n\t$LFS setstripe -c $OSTCOUNT -S1M $DIR/$tdir || error \"setstripe failed\"\n\tfallocate -l ${OSTCOUNT}m $DIR/$tdir || error \"fallocate failed\"\n\tsync; sync_all_data\n\tcancel_lru_locks $OSC\n\tsleep 5\n\tbytes=$(($(stat -c '%b * %B' $DIR/$tdir)))\n\twant=$((OSTCOUNT * 1048576))\n\n\t# Must allocate all requested space, not more than 5% extra\n\t(( $bytes >= $want && $bytes < $want * 105 / 100 )) ||\n\t\terror \"bytes $bytes is not $want\"\n}\nrun_test 150c \"Verify fallocate Size and Blocks\"\n\ntest_150d() {\n\tlocal bytes\n\tlocal want\n\n\t[ \"$ost1_FSTYPE\" != ldiskfs ] && skip \"non-ldiskfs backend\"\n\t[ $OST1_VERSION -lt $(version_code 2.13.50) ] &&\n\t\tskip \"Need OST version at least 2.13.53\"\n\n\t$LFS setstripe -c $OSTCOUNT -S1M $DIR/$tdir || error \"setstripe failed\"\n\tfallocate -o 1G -l ${OSTCOUNT}m $DIR/$tdir || error \"fallocate failed\"\n\tsync; sync_all_data\n\tcancel_lru_locks $OSC\n\tsleep 5\n\tbytes=$(($(stat -c '%b * %B' $DIR/$tdir)))\n\twant=$((OSTCOUNT * 1048576))\n\n\t# Must allocate all requested space, not more than 5% extra\n\t(( $bytes >= $want && $bytes < $want * 105 / 100 )) ||\n\t\terror \"bytes $bytes is not $want\"\n}\nrun_test 150d \"Verify fallocate Size and Blocks - Non zero start\"\n\n#LU-2902 roc_hit was not able to read all values from lproc\nfunction roc_hit_init() {\n\tlocal list=$(comma_list $(osts_nodes))\n\tlocal dir=$DIR/$tdir-check\n\tlocal file=$dir/$tfile\n\tlocal BEFORE\n\tlocal AFTER\n\tlocal idx\n\n\ttest_mkdir $dir\n\t#use setstripe to do a write to every ost\n\tfor i in $(seq 0 $((OSTCOUNT-1))); do\n\t\t$LFS setstripe -c 1 -i $i $dir || error \"$LFS setstripe $file failed\"\n\t\tdd if=/dev/urandom of=$file bs=4k count=4 2>&1 > /dev/null\n\t\tidx=$(printf %04x $i)\n\t\tBEFORE=$(get_osd_param $list *OST*$idx stats |\n\t\t\tawk '$1 == \"cache_access\" {sum += $7}\n\t\t\t\tEND { printf(\"%0.0f\", sum) }')\n\n\t\tcancel_lru_locks osc\n\t\tcat $file >/dev/null\n\n\t\tAFTER=$(get_osd_param $list *OST*$idx stats |\n\t\t\tawk '$1 == \"cache_access\" {sum += $7}\n\t\t\t\tEND { printf(\"%0.0f\", sum) }')\n\n\t\techo BEFORE:$BEFORE AFTER:$AFTER\n\t\tif ! let \"AFTER - BEFORE == 4\"; then\n\t\t\trm -rf $dir\n\t\t\terror \"roc_hit is not safe to use\"\n\t\tfi\n\t\trm $file\n\tdone\n\n\trm -rf $dir\n}\n\nfunction roc_hit() {\n\tlocal list=$(comma_list $(osts_nodes))\n\techo $(get_osd_param $list '' stats |\n\t\tawk '$1 == \"cache_hit\" {sum += $7}\n\t\t\tEND { printf(\"%0.0f\", sum) }')\n}\n\nfunction set_cache() {\n\tlocal on=1\n\n\tif [ \"$2\" == \"off\" ]; then\n\t\ton=0;\n\tfi\n\tlocal list=$(comma_list $(osts_nodes))\n\tset_osd_param $list '' $1_cache_enable $on\n\n\tcancel_lru_locks osc\n}\n\ntest_151() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal CPAGES=3\n\tlocal list=$(comma_list $(osts_nodes))\n\n\t# check whether obdfilter is cache capable at all\n\tif ! get_osd_param $list '' read_cache_enable >/dev/null; then\n\t\tskip \"not cache-capable obdfilter\"\n\tfi\n\n\t# check cache is enabled on all obdfilters\n\tif get_osd_param $list '' read_cache_enable | grep 0; then\n\t\tskip \"oss cache is disabled\"\n\tfi\n\n\tset_osd_param $list '' writethrough_cache_enable 1\n\n\t# check write cache is enabled on all obdfilters\n\tif get_osd_param $list '' writethrough_cache_enable | grep 0; then\n\t\tskip \"oss write cache is NOT enabled\"\n\tfi\n\n\troc_hit_init\n\n\t#define OBD_FAIL_OBD_NO_LRU  0x609\n\tdo_nodes $list $LCTL set_param fail_loc=0x609\n\n\t# pages should be in the case right after write\n\tdd if=/dev/urandom of=$DIR/$tfile bs=4k count=$CPAGES ||\n\t\terror \"dd failed\"\n\n\tlocal BEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $DIR/$tfile >/dev/null\n\tlocal AFTER=$(roc_hit)\n\n\tdo_nodes $list $LCTL set_param fail_loc=0\n\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE: before: $BEFORE, after: $AFTER\"\n\tfi\n\n        cancel_lru_locks osc\n\t# invalidates OST cache\n\tdo_nodes $list \"echo 1 > /proc/sys/vm/drop_caches\"\n\tset_osd_param $list '' read_cache_enable 0\n        cat $DIR/$tfile >/dev/null\n\n        # now data shouldn't be found in the cache\n\tBEFORE=$(roc_hit)\n        cancel_lru_locks osc\n        cat $DIR/$tfile >/dev/null\n\tAFTER=$(roc_hit)\n        if let \"AFTER - BEFORE != 0\"; then\n                error \"IN CACHE: before: $BEFORE, after: $AFTER\"\n        fi\n\n\tset_osd_param $list '' read_cache_enable 1\n        rm -f $DIR/$tfile\n}\nrun_test 151 \"test cache on oss and controls ===============================\"\n\ntest_152() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal TF=\"$TMP/$tfile\"\n\n\t# simulate ENOMEM during write\n#define OBD_FAIL_OST_NOMEM      0x226\n        lctl set_param fail_loc=0x80000226\n        dd if=/dev/urandom of=$TF bs=6096 count=1 || error \"dd failed\"\n        cp $TF $DIR/$tfile\n        sync || error \"sync failed\"\n        lctl set_param fail_loc=0\n\n        # discard client's cache\n        cancel_lru_locks osc\n\n        # simulate ENOMEM during read\n        lctl set_param fail_loc=0x80000226\n        cmp $TF $DIR/$tfile || error \"cmp failed\"\n        lctl set_param fail_loc=0\n\n        rm -f $TF\n}\nrun_test 152 \"test read/write with enomem ============================\"\n\ntest_153() {\n        $MULTIOP $DIR/$tfile Ow4096Ycu || error \"multiop failed\"\n}\nrun_test 153 \"test if fdatasync does not crash =======================\"\n\ndot_lustre_fid_permission_check() {\n\tlocal fid=$1\n\tlocal ffid=$MOUNT/.lustre/fid/$fid\n\tlocal test_dir=$2\n\n\techo \"stat fid $fid\"\n\tstat $ffid > /dev/null || error \"stat $ffid failed.\"\n\techo \"touch fid $fid\"\n\ttouch $ffid || error \"touch $ffid failed.\"\n\techo \"write to fid $fid\"\n\tcat /etc/hosts > $ffid || error \"write $ffid failed.\"\n\techo \"read fid $fid\"\n\tdiff /etc/hosts $ffid || error \"read $ffid failed.\"\n\techo \"append write to fid $fid\"\n\tcat /etc/hosts >> $ffid || error \"append write $ffid failed.\"\n\techo \"rename fid $fid\"\n\tmv $ffid $test_dir/$tfile.1 &&\n\t\terror \"rename $ffid to $tfile.1 should fail.\"\n\ttouch $test_dir/$tfile.1\n\tmv $test_dir/$tfile.1 $ffid &&\n\t\terror \"rename $tfile.1 to $ffid should fail.\"\n\trm -f $test_dir/$tfile.1\n\techo \"truncate fid $fid\"\n\t$TRUNCATE $ffid 777 || error \"truncate $ffid failed.\"\n\techo \"link fid $fid\"\n\tln -f $ffid $test_dir/tfile.lnk || error \"link $ffid failed.\"\n\tif [[ $($LCTL get_param -n mdc.*-mdc-*.connect_flags) =~ acl ]]; then\n\t\techo \"setfacl fid $fid\"\n\t\tsetfacl -R -m u:bin:rwx $ffid || error \"setfacl $ffid failed.\"\n\t\techo \"getfacl fid $fid\"\n\t\tgetfacl $ffid >/dev/null || error \"getfacl $ffid failed.\"\n\tfi\n\techo \"unlink fid $fid\"\n\tunlink $MOUNT/.lustre/fid/$fid && error \"unlink $ffid should fail.\"\n\techo \"mknod fid $fid\"\n\tmknod $ffid c 1 3 && error \"mknod $ffid should fail.\"\n\n\tfid=[0xf00000400:0x1:0x0]\n\tffid=$MOUNT/.lustre/fid/$fid\n\n\techo \"stat non-exist fid $fid\"\n\tstat $ffid > /dev/null && error \"stat non-exist $ffid should fail.\"\n\techo \"write to non-exist fid $fid\"\n\tcat /etc/hosts > $ffid && error \"write non-exist $ffid should fail.\"\n\techo \"link new fid $fid\"\n\tln $test_dir/$tfile $ffid && error \"link $ffid should fail.\"\n\n\tmkdir -p $test_dir/$tdir\n\ttouch $test_dir/$tdir/$tfile\n\tfid=$($LFS path2fid $test_dir/$tdir)\n\trc=$?\n\t[ $rc -ne 0 ] &&\n\t\terror \"error: could not get fid for $test_dir/$dir/$tfile.\"\n\n\tffid=$MOUNT/.lustre/fid/$fid\n\n\techo \"ls $fid\"\n\tls $ffid > /dev/null || error \"ls $ffid failed.\"\n\techo \"touch $fid/$tfile.1\"\n\ttouch $ffid/$tfile.1 || error \"touch $ffid/$tfile.1 failed.\"\n\n\techo \"touch $MOUNT/.lustre/fid/$tfile\"\n\ttouch $MOUNT/.lustre/fid/$tfile && \\\n\t\terror \"touch $MOUNT/.lustre/fid/$tfile should fail.\"\n\n\techo \"setxattr to $MOUNT/.lustre/fid\"\n\tsetfattr -n trusted.name1 -v value1 $MOUNT/.lustre/fid\n\n\techo \"listxattr for $MOUNT/.lustre/fid\"\n\tgetfattr -d -m \"^trusted\" $MOUNT/.lustre/fid\n\n\techo \"delxattr from $MOUNT/.lustre/fid\"\n\tsetfattr -x trusted.name1 $MOUNT/.lustre/fid\n\n\techo \"touch invalid fid: $MOUNT/.lustre/fid/[0x200000400:0x2:0x3]\"\n\ttouch $MOUNT/.lustre/fid/[0x200000400:0x2:0x3] &&\n\t\terror \"touch invalid fid should fail.\"\n\n\techo \"touch non-normal fid: $MOUNT/.lustre/fid/[0x1:0x2:0x0]\"\n\ttouch $MOUNT/.lustre/fid/[0x1:0x2:0x0] &&\n\t\terror \"touch non-normal fid should fail.\"\n\n\techo \"rename $tdir to $MOUNT/.lustre/fid\"\n\tmrename $test_dir/$tdir $MOUNT/.lustre/fid &&\n\t\terror \"rename to $MOUNT/.lustre/fid should fail.\"\n\n\tif [ $MDS1_VERSION -ge $(version_code 2.3.51) ]\n\tthen\t\t# LU-3547\n\t\tlocal old_obf_mode=$(stat --format=\"%a\" $DIR/.lustre/fid)\n\t\tlocal new_obf_mode=777\n\n\t\techo \"change mode of $DIR/.lustre/fid to $new_obf_mode\"\n\t\tchmod $new_obf_mode $DIR/.lustre/fid ||\n\t\t\terror \"chmod $new_obf_mode $DIR/.lustre/fid failed\"\n\n\t\tlocal obf_mode=$(stat --format=%a $DIR/.lustre/fid)\n\t\t[ $obf_mode -eq $new_obf_mode ] ||\n\t\t\terror \"stat $DIR/.lustre/fid returned wrong mode $obf_mode\"\n\n\t\techo \"restore mode of $DIR/.lustre/fid to $old_obf_mode\"\n\t\tchmod $old_obf_mode $DIR/.lustre/fid ||\n\t\t\terror \"chmod $old_obf_mode $DIR/.lustre/fid failed\"\n\tfi\n\n\t$OPENFILE -f O_LOV_DELAY_CREATE:O_CREAT $test_dir/$tfile-2\n\tfid=$($LFS path2fid $test_dir/$tfile-2)\n\n\tif [ $MDS1_VERSION -ge $(version_code 2.6.50) ]\n\tthen # LU-5424\n\t\techo \"cp /etc/passwd $MOUNT/.lustre/fid/$fid\"\n\t\tcp /etc/passwd $MOUNT/.lustre/fid/$fid ||\n\t\t\terror \"create lov data thru .lustre failed\"\n\tfi\n\techo \"cp /etc/passwd $test_dir/$tfile-2\"\n\tcp /etc/passwd $test_dir/$tfile-2 ||\n\t\terror \"copy to $test_dir/$tfile-2 failed.\"\n\techo \"diff /etc/passwd $MOUNT/.lustre/fid/$fid\"\n\tdiff /etc/passwd $MOUNT/.lustre/fid/$fid ||\n\t\terror \"diff /etc/passwd $MOUNT/.lustre/fid/$fid failed.\"\n\n\trm -rf $test_dir/tfile.lnk\n\trm -rf $test_dir/$tfile-2\n}\n\ntest_154A() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&\n\t\tskip \"Need MDS version at least 2.4.1\"\n\n\tlocal tf=$DIR/$tfile\n\ttouch $tf\n\n\tlocal fid=$($LFS path2fid $tf)\n\t[ -z \"$fid\" ] && error \"path2fid unable to get $tf FID\"\n\n\t# check that we get the same pathname back\n\tlocal rootpath\n\tlocal found\n\tfor rootpath in \"$MOUNT\" \"$MOUNT///\" \"$MOUNT/$tfile\"; do\n\t\techo \"$rootpath $fid\"\n\t\tfound=$($LFS fid2path $rootpath \"$fid\")\n\t\t[ -z \"$found\" ] && error \"fid2path unable to get '$fid' path\"\n\t\t[ \"$found\" == \"$tf\" ] || error \"fid2path $found != $tf\"\n\tdone\n\n\t# check wrong root path format\n\trootpath=$MOUNT\"_wrong\"\n\tfound=$($LFS fid2path $rootpath \"$fid\")\n\t[ -z \"$found\" ] || error \"should fail ($rootpath != $MOUNT)\"\n}\nrun_test 154A \"lfs path2fid and fid2path basic checks\"\n\ntest_154B() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&\n\t\tskip \"Need MDS version at least 2.4.1\"\n\n\tmkdir -p $DIR/$tdir || error \"mkdir $tdir failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch $DIR/$tdir/$tfile failed\"\n\tlocal linkea=$($LL_DECODE_LINKEA $DIR/$tdir/$tfile | grep 'pfid')\n\t[ -z \"$linkea\" ] && error \"decode linkea $DIR/$tdir/$tfile failed\"\n\n\tlocal name=$(echo $linkea | awk '/pfid/ {print $5}' | sed -e \"s/'//g\")\n\tlocal PFID=$(echo $linkea | awk '/pfid/ {print $3}' | sed -e \"s/,//g\")\n\n\t# check that we get the same pathname\n\techo \"PFID: $PFID, name: $name\"\n\tlocal FOUND=$($LFS fid2path $MOUNT \"$PFID\")\n\t[ -z \"$FOUND\" ] && error \"fid2path unable to get $PFID path\"\n\t[ \"$FOUND/$name\" != \"$DIR/$tdir/$tfile\" ] &&\n\t\terror \"ll_decode_linkea has $FOUND/$name != $DIR/$tdir/$tfile\"\n\n\trm -rf $DIR/$tdir || error \"Can not delete directory $DIR/$tdir\"\n}\nrun_test 154B \"verify the ll_decode_linkea tool\"\n\ntest_154a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.2.51) ]] ||\n\t\tskip \"Need MDS version at least 2.2.51\"\n\t[ -z \"$(which setfacl)\" ] && skip_env \"must have setfacl tool\"\n\n\tcp /etc/hosts $DIR/$tfile\n\n\tfid=$($LFS path2fid $DIR/$tfile)\n\trc=$?\n\t[ $rc -ne 0 ] && error \"error: could not get fid for $DIR/$tfile.\"\n\n\tdot_lustre_fid_permission_check \"$fid\" $DIR ||\n\t\terror \"dot lustre permission check $fid failed\"\n\n\tls -a $MOUNT | grep \"\\.lustre\" && error \".lustre should not be listed\"\n\n\trm -rf $MOUNT/.lustre && error \".lustre is not allowed to be unlinked\"\n\n\ttouch $MOUNT/.lustre/file &&\n\t\terror \"creation is not allowed under .lustre\"\n\n\tmkdir $MOUNT/.lustre/dir &&\n\t\terror \"mkdir is not allowed under .lustre\"\n\n\trm -rf $DIR/$tfile\n}\nrun_test 154a \"Open-by-FID\"\n\ntest_154b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.2.51) ]] ||\n\t\tskip \"Need MDS version at least 2.2.51\"\n\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\tlocal MDTIDX=1\n\tlocal rc=0\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX $remote_dir ||\n\t\terror \"create remote directory failed\"\n\n\tcp /etc/hosts $remote_dir/$tfile\n\n\tfid=$($LFS path2fid $remote_dir/$tfile)\n\trc=$?\n\t[ $rc -ne 0 ] && error \"error: could not get fid for $remote_dir/$tfile\"\n\n\tdot_lustre_fid_permission_check \"$fid\" $remote_dir ||\n\t\terror \"dot lustre permission check $fid failed\"\n\trm -rf $DIR/$tdir\n}\nrun_test 154b \"Open-by-FID for remote directory\"\n\ntest_154c() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.4.1) ]] &&\n\t\tskip \"Need MDS version at least 2.4.1\"\n\n\ttouch $DIR/$tfile.1 $DIR/$tfile.2 $DIR/$tfile.3\n\tlocal FID1=$($LFS path2fid $DIR/$tfile.1)\n\tlocal FID2=$($LFS path2fid $DIR/$tfile.2)\n\tlocal FID3=$($LFS path2fid $DIR/$tfile.3)\n\n\tlocal N=1\n\t$LFS path2fid $DIR/$tfile.[123] | while read PATHNAME FID; do\n\t\t[ \"$PATHNAME\" = \"$DIR/$tfile.$N:\" ] ||\n\t\t\terror \"path2fid pathname $PATHNAME != $DIR/$tfile.$N:\"\n\t\tlocal want=FID$N\n\t\t[ \"$FID\" = \"${!want}\" ] ||\n\t\t\terror \"path2fid $PATHNAME FID $FID != FID$N ${!want}\"\n\t\tN=$((N + 1))\n\tdone\n\n\t$LFS fid2path $MOUNT \"$FID1\" \"$FID2\" \"$FID3\" | while read PATHNAME;\n\tdo\n\t\t[ \"$PATHNAME\" = \"$DIR/$tfile.$N\" ] ||\n\t\t\terror \"fid2path pathname $PATHNAME != $DIR/$tfile.$N:\"\n\t\tN=$((N + 1))\n\tdone\n}\nrun_test 154c \"lfs path2fid and fid2path multiple arguments\"\n\ntest_154d() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.5.53) ]] &&\n\t\tskip \"Need MDS version at least 2.5.53\"\n\n\tif remote_mds; then\n\t\tnid=$($LCTL list_nids | sed  \"s/\\./\\\\\\./g\")\n\telse\n\t\tnid=\"0@lo\"\n\tfi\n\tlocal proc_ofile=\"mdt.*.exports.'$nid'.open_files\"\n\tlocal fd\n\tlocal cmd\n\n\trm -f $DIR/$tfile\n\ttouch $DIR/$tfile\n\n\tlocal fid=$($LFS path2fid $DIR/$tfile)\n\t# Open the file\n\tfd=$(free_fd)\n\tcmd=\"exec $fd<$DIR/$tfile\"\n\teval $cmd\n\tlocal fid_list=$(do_facet $SINGLEMDS $LCTL get_param $proc_ofile)\n\techo \"$fid_list\" | grep \"$fid\"\n\trc=$?\n\n\tcmd=\"exec $fd>/dev/null\"\n\teval $cmd\n\tif [ $rc -ne 0 ]; then\n\t\terror \"FID $fid not found in open files list $fid_list\"\n\tfi\n}\nrun_test 154d \"Verify open file fid\"\n\ntest_154e()\n{\n\t[[ $MDS1_VERSION -lt $(version_code 2.6.50) ]] &&\n\t\tskip \"Need MDS version at least 2.6.50\"\n\n\tif ls -a $MOUNT | grep -q '^\\.lustre$'; then\n\t\terror \".lustre returned by readdir\"\n\tfi\n}\nrun_test 154e \".lustre is not returned by readdir\"\n\ntest_154f() {\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\n\t# create parent directory on a single MDT to avoid cross-MDT hardlinks\n\ttest_mkdir -p -c1 $DIR/$tdir/d\n\t# test dirs inherit from its stripe\n\tmkdir -p $DIR/$tdir/d/foo1 || error \"mkdir error\"\n\tmkdir -p $DIR/$tdir/d/foo2 || error \"mkdir error\"\n\tcp /etc/hosts $DIR/$tdir/d/foo1/$tfile\n\tln $DIR/$tdir/d/foo1/$tfile $DIR/$tdir/d/foo2/link\n\ttouch $DIR/f\n\n\t# get fid of parents\n\tlocal FID0=$($LFS path2fid $DIR/$tdir/d)\n\tlocal FID1=$($LFS path2fid $DIR/$tdir/d/foo1)\n\tlocal FID2=$($LFS path2fid $DIR/$tdir/d/foo2)\n\tlocal FID3=$($LFS path2fid $DIR)\n\n\t# check that path2fid --parents returns expected <parent_fid>/name\n\t# 1) test for a directory (single parent)\n\tlocal parent=$($LFS path2fid --parents $DIR/$tdir/d/foo1)\n\t[ \"$parent\" == \"$FID0/foo1\" ] ||\n\t\terror \"expected parent: $FID0/foo1, got: $parent\"\n\n\t# 2) test for a file with nlink > 1 (multiple parents)\n\tparent=$($LFS path2fid --parents $DIR/$tdir/d/foo1/$tfile)\n\techo \"$parent\" | grep -F \"$FID1/$tfile\" ||\n\t\terror \"$FID1/$tfile not returned in parent list\"\n\techo \"$parent\" | grep -F \"$FID2/link\" ||\n\t\terror \"$FID2/link not returned in parent list\"\n\n\t# 3) get parent by fid\n\tlocal file_fid=$($LFS path2fid $DIR/$tdir/d/foo1/$tfile)\n\tparent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)\n\techo \"$parent\" | grep -F \"$FID1/$tfile\" ||\n\t\terror \"$FID1/$tfile not returned in parent list (by fid)\"\n\techo \"$parent\" | grep -F \"$FID2/link\" ||\n\t\terror \"$FID2/link not returned in parent list (by fid)\"\n\n\t# 4) test for entry in root directory\n\tparent=$($LFS path2fid --parents $DIR/f)\n\techo \"$parent\" | grep -F \"$FID3/f\" ||\n\t\terror \"$FID3/f not returned in parent list\"\n\n\t# 5) test it on root directory\n\t[ -z \"$($LFS path2fid --parents $MOUNT 2>/dev/null)\" ] ||\n\t\terror \"$MOUNT should not have parents\"\n\n\t# enable xattr caching and check that linkea is correctly updated\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $save\n\tlctl set_param llite.*.xattr_cache 1\n\n\t# 6.1) linkea update on rename\n\tmv $DIR/$tdir/d/foo1/$tfile $DIR/$tdir/d/foo2/$tfile.moved\n\n\t# get parents by fid\n\tparent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)\n\t# foo1 should no longer be returned in parent list\n\techo \"$parent\" | grep -F \"$FID1\" &&\n\t\terror \"$FID1 should no longer be in parent list\"\n\t# the new path should appear\n\techo \"$parent\" | grep -F \"$FID2/$tfile.moved\" ||\n\t\terror \"$FID2/$tfile.moved is not in parent list\"\n\n\t# 6.2) linkea update on unlink\n\trm -f $DIR/$tdir/d/foo2/link\n\tparent=$($LFS path2fid --parents $MOUNT/.lustre/fid/$file_fid)\n\t# foo2/link should no longer be returned in parent list\n\techo \"$parent\" | grep -F \"$FID2/link\" &&\n\t\terror \"$FID2/link should no longer be in parent list\"\n\ttrue\n\n\trm -f $DIR/f\n\trestore_lustre_params < $save\n\trm -f $save\n}\nrun_test 154f \"get parent fids by reading link ea\"\n\ntest_154g()\n{\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.6.92) &&\n\t   $CLIENT_VERSION -gt $(version_code 2.6.99) ]] ||\n\t\tskip \"Need MDS version at least 2.6.92\"\n\n\tmkdir -p $DIR/$tdir\n\tllapi_fid_test -d $DIR/$tdir\n}\nrun_test 154g \"various llapi FID tests\"\n\ntest_155_small_load() {\n    local temp=$TMP/$tfile\n    local file=$DIR/$tfile\n\n    dd if=/dev/urandom of=$temp bs=6096 count=1 || \\\n        error \"dd of=$temp bs=6096 count=1 failed\"\n    cp $temp $file\n    cancel_lru_locks $OSC\n    cmp $temp $file || error \"$temp $file differ\"\n\n    $TRUNCATE $temp 6000\n    $TRUNCATE $file 6000\n    cmp $temp $file || error \"$temp $file differ (truncate1)\"\n\n    echo \"12345\" >>$temp\n    echo \"12345\" >>$file\n    cmp $temp $file || error \"$temp $file differ (append1)\"\n\n    echo \"12345\" >>$temp\n    echo \"12345\" >>$file\n    cmp $temp $file || error \"$temp $file differ (append2)\"\n\n    rm -f $temp $file\n    true\n}\n\ntest_155_big_load() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal temp=$TMP/$tfile\n\tlocal file=$DIR/$tfile\n\n\tfree_min_max\n\tlocal cache_size=$(do_facet ost$((MAXI+1)) \\\n\t\t\"awk '/cache/ {sum+=\\\\\\$4} END {print sum}' /proc/cpuinfo\")\n\tlocal large_file_size=$((cache_size * 2))\n\n\techo \"OSS cache size: $cache_size KB\"\n\techo \"Large file size: $large_file_size KB\"\n\n\t[ $MAXV -le $large_file_size ] &&\n\t\tskip_env \"max available OST size needs > $large_file_size KB\"\n\n\t$LFS setstripe $file -c 1 -i $MAXI || error \"$LFS setstripe $file failed\"\n\n\tdd if=/dev/urandom of=$temp bs=$large_file_size count=1k ||\n\t\terror \"dd of=$temp bs=$large_file_size count=1k failed\"\n\tcp $temp $file\n\tls -lh $temp $file\n\tcancel_lru_locks osc\n\tcmp $temp $file || error \"$temp $file differ\"\n\n\trm -f $temp $file\n\ttrue\n}\n\nsave_writethrough() {\n\tlocal facets=$(get_facets OST)\n\n\tsave_lustre_params $facets \"osd-*.*.writethrough_cache_enable\" > $1\n}\n\ntest_155a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read on\n\tset_cache writethrough on\n\ttest_155_small_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155a \"Verify small file correctness: read cache:on write_cache:on\"\n\ntest_155b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read on\n\tset_cache writethrough off\n\ttest_155_small_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155b \"Verify small file correctness: read cache:on write_cache:off\"\n\ntest_155c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read off\n\tset_cache writethrough on\n\ttest_155_small_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155c \"Verify small file correctness: read cache:off write_cache:on\"\n\ntest_155d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read off\n\tset_cache writethrough off\n\ttest_155_small_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155d \"Verify small file correctness: read cache:off write_cache:off\"\n\ntest_155e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read on\n\tset_cache writethrough on\n\ttest_155_big_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155e \"Verify big file correctness: read cache:on write_cache:on\"\n\ntest_155f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read on\n\tset_cache writethrough off\n\ttest_155_big_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155f \"Verify big file correctness: read cache:on write_cache:off\"\n\ntest_155g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read off\n\tset_cache writethrough on\n\ttest_155_big_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155g \"Verify big file correctness: read cache:off write_cache:on\"\n\ntest_155h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\n\tset_cache read off\n\tset_cache writethrough off\n\ttest_155_big_load\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 155h \"Verify big file correctness: read cache:off write_cache:off\"\n\ntest_156() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $OST1_VERSION -lt $(version_code 2.6.93) ] &&\n\t\tskip \"stats not implemented on old servers\"\n\t[ \"$ost1_FSTYPE\" = \"zfs\" ] &&\n\t\tskip \"LU-1956/LU-2261: stats not implemented on OSD ZFS\"\n\n\tlocal CPAGES=3\n\tlocal BEFORE\n\tlocal AFTER\n\tlocal file=\"$DIR/$tfile\"\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_writethrough $p\n\troc_hit_init\n\n\tlog \"Turn on read and write cache\"\n\tset_cache read on\n\tset_cache writethrough on\n\n\tlog \"Write data and read it back.\"\n\tlog \"Read should be satisfied from the cache.\"\n\tdd if=/dev/urandom of=$file bs=4k count=$CPAGES || error \"dd failed\"\n\tBEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE (2): before: $BEFORE, after: $AFTER\"\n\telse\n\t\tlog \"cache hits: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tlog \"Read again; it should be satisfied from the cache.\"\n\tBEFORE=$AFTER\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE (3): before: $BEFORE, after: $AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tlog \"Turn off the read cache and turn on the write cache\"\n\tset_cache read off\n\tset_cache writethrough on\n\n\tlog \"Read again; it should be satisfied from the cache.\"\n\tBEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE (4): before: $BEFORE, after: $AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tif [ $OST1_VERSION -lt $(version_code 2.12.55) ]; then\n\t\t# > 2.12.56 uses pagecache if cached\n\t\tlog \"Read again; it should not be satisfied from the cache.\"\n\t\tBEFORE=$AFTER\n\t\tcancel_lru_locks osc\n\t\tcat $file >/dev/null\n\t\tAFTER=$(roc_hit)\n\t\tif ! let \"AFTER - BEFORE == 0\"; then\n\t\t\terror \"IN CACHE (5): before: $BEFORE, after: $AFTER\"\n\t\telse\n\t\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\t\tfi\n\tfi\n\n\tlog \"Write data and read it back.\"\n\tlog \"Read should be satisfied from the cache.\"\n\tdd if=/dev/urandom of=$file bs=4k count=$CPAGES || error \"dd failed\"\n\tBEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE (6): before: $BEFORE, after: $AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tif [ $OST1_VERSION -lt $(version_code 2.12.55) ]; then\n\t\t# > 2.12.56 uses pagecache if cached\n\t\tlog \"Read again; it should not be satisfied from the cache.\"\n\t\tBEFORE=$AFTER\n\t\tcancel_lru_locks osc\n\t\tcat $file >/dev/null\n\t\tAFTER=$(roc_hit)\n\t\tif ! let \"AFTER - BEFORE == 0\"; then\n\t\t\terror \"IN CACHE (7): before: $BEFORE, after: $AFTER\"\n\t\telse\n\t\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\t\tfi\n\tfi\n\n\tlog \"Turn off read and write cache\"\n\tset_cache read off\n\tset_cache writethrough off\n\n\tlog \"Write data and read it back\"\n\tlog \"It should not be satisfied from the cache.\"\n\trm -f $file\n\tdd if=/dev/urandom of=$file bs=4k count=$CPAGES || error \"dd failed\"\n\tcancel_lru_locks osc\n\tBEFORE=$(roc_hit)\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == 0\"; then\n\t\terror_ignore bz20762 \"IN CACHE (8):before:$BEFORE,after:$AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tlog \"Turn on the read cache and turn off the write cache\"\n\tset_cache read on\n\tset_cache writethrough off\n\n\tlog \"Write data and read it back\"\n\tlog \"It should not be satisfied from the cache.\"\n\trm -f $file\n\tdd if=/dev/urandom of=$file bs=4k count=$CPAGES || error \"dd failed\"\n\tBEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == 0\"; then\n\t\terror_ignore bz20762 \"IN CACHE (9):before:$BEFORE,after:$AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\tlog \"Read again; it should be satisfied from the cache.\"\n\tBEFORE=$(roc_hit)\n\tcancel_lru_locks osc\n\tcat $file >/dev/null\n\tAFTER=$(roc_hit)\n\tif ! let \"AFTER - BEFORE == CPAGES\"; then\n\t\terror \"NOT IN CACHE (1): before: $BEFORE, after: $AFTER\"\n\telse\n\t\tlog \"cache hits:: before: $BEFORE, after: $AFTER\"\n\tfi\n\n\trestore_lustre_params < $p\n\trm -f $p $file\n}\nrun_test 156 \"Verification of tunables\"\n\ntest_160a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -ge $(version_code 2.2.0) ] ||\n\t\tskip \"Need MDS version at least 2.2.0\"\n\n\tchangelog_register || error \"changelog_register failed\"\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User $cl_user not found in changelog_users\"\n\n\t# change something\n\ttest_mkdir -p $DIR/$tdir/pics/2008/zachy\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\ttouch $DIR/$tdir/pics/2008/zachy/$tfile\t\t\t# open 1\n\tcp /etc/hosts $DIR/$tdir/pics/2008/zachy/pic1.jpg\t# open 2\n\tmv $DIR/$tdir/pics/2008/zachy $DIR/$tdir/pics/zach\n\tln $DIR/$tdir/pics/zach/pic1.jpg $DIR/$tdir/pics/2008/portland.jpg\n\tln -s $DIR/$tdir/pics/2008/portland.jpg $DIR/$tdir/pics/desktop.jpg\n\trm $DIR/$tdir/pics/desktop.jpg\n\n\tchangelog_dump | tail -10\n\n\techo \"verifying changelog mask\"\n\tchangelog_chmask \"-MKDIR\"\n\tchangelog_chmask \"-CLOSE\"\n\n\ttest_mkdir -p $DIR/$tdir/pics/zach/sofia\t\t# not logged\n\techo \"zzzzzz\" > $DIR/$tdir/pics/zach/file\t\t# not logged\n\n\tchangelog_chmask \"+MKDIR\"\n\tchangelog_chmask \"+CLOSE\"\n\n\ttest_mkdir -p $DIR/$tdir/pics/2008/sofia\t\t# mkdir 1\n\techo \"zzzzzz\" > $DIR/$tdir/pics/zach/file\t\t# open 3\n\n\tchangelog_dump | tail -10\n\tMKDIRS=$(changelog_dump | grep -c \"MKDIR\")\n\tCLOSES=$(changelog_dump | grep -c \"CLOSE\")\n\t[ $MKDIRS -eq 1 ] || error \"MKDIR changelog mask count $MKDIRS != 1\"\n\t[ $CLOSES -eq 3 ] || error \"CLOSE changelog mask count $CLOSES != 3\"\n\n\t# verify contents\n\techo \"verifying target fid\"\n\tlocal fidc=$(changelog_extract_field \"CREAT\" \"$tfile\" \"t=\")\n\tlocal fidf=$($LFS path2fid $DIR/$tdir/pics/zach/$tfile)\n\t[ \"$fidc\" == \"$fidf\" ] ||\n\t\terror \"changelog '$tfile' fid $fidc != file fid $fidf\"\n\techo \"verifying parent fid\"\n\t# The FID returned from the Changelog may be the directory shard on\n\t# a different MDT, and not the FID returned by path2fid on the parent.\n\t# Instead of comparing FIDs, verify that fid2path(fidp) is correct,\n\t# since this is what will matter when recreating this file in the tree.\n\tlocal fidp=$(changelog_extract_field \"CREAT\" \"$tfile\" \"p=\")\n\tlocal pathp=$($LFS fid2path $MOUNT \"$fidp\")\n\t[ \"${pathp%/}\" == \"$DIR/$tdir/pics/zach\" ] ||\n\t\terror \"changelog fid2path($fidc) $pathp != $DIR/$tdir/pics/zach\"\n\n\techo \"getting records for $cl_user\"\n\tchangelog_users $SINGLEMDS\n\tlocal user_rec1=$(changelog_user_rec $SINGLEMDS $cl_user)\n\tlocal nclr=3\n\t__changelog_clear $SINGLEMDS $cl_user +$nclr ||\n\t\terror \"changelog_clear failed\"\n\tlocal user_rec2=$(changelog_user_rec $SINGLEMDS $cl_user)\n\techo \"verifying user clear: $user_rec1 + $nclr == $user_rec2\"\n\t[ $user_rec2 == $((user_rec1 + nclr)) ] ||\n\t\terror \"user index expect $user_rec1 + $nclr != $user_rec2\"\n\n\tlocal min0_rec=$(changelog_users $SINGLEMDS |\n\t\tawk 'min == \"\" || $2 < min { min = $2 }; END { print min }')\n\tlocal first_rec=$($LFS changelog $(facet_svc $SINGLEMDS) |\n\t\t\t  awk '{ print $1; exit; }')\n\n\tchangelog_dump | tail -n 5\n\techo \"verifying user min purge: $min0_rec + 1 == $first_rec\"\n\t[ $first_rec == $((min0_rec + 1)) ] ||\n\t\terror \"first index should be $min0_rec + 1 not $first_rec\"\n\n\t# LU-3446 changelog index reset on MDT restart\n\tlocal cur_rec1=$(changelog_users $SINGLEMDS |\n\t\t\t awk '/^current.index:/ { print $NF }')\n\tchangelog_clear 0 ||\n\t\terror \"clear all changelog records for $cl_user failed\"\n\tstop $SINGLEMDS || error \"Fail to stop $SINGLEMDS\"\n\tstart $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS ||\n\t\terror \"Fail to start $SINGLEMDS\"\n\tlocal cur_rec2=$(changelog_users $SINGLEMDS |\n\t\t\t awk '/^current.index:/ { print $NF }')\n\techo \"verifying index survives MDT restart: $cur_rec1 == $cur_rec2\"\n\t[ $cur_rec1 == $cur_rec2 ] ||\n\t\terror \"current index should be $cur_rec1 not $cur_rec2\"\n\n\techo \"verifying users from this test are deregistered\"\n\tchangelog_deregister || error \"changelog_deregister failed\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user &&\n\t\terror \"User '$cl_user' still in changelog_users\"\n\n\t# lctl get_param -n mdd.*.changelog_users\n\t# current index: 144\n\t# ID    index (idle seconds)\n\t# cl3   144 (2)\n\tif ! changelog_users $SINGLEMDS | grep \"^cl\"; then\n\t\t# this is the normal case where all users were deregistered\n\t\t# make sure no new records are added when no users are present\n\t\tlocal last_rec1=$(changelog_users $SINGLEMDS |\n\t\t\t\t  awk '/^current.index:/ { print $NF }')\n\t\ttouch $DIR/$tdir/chloe\n\t\tlocal last_rec2=$(changelog_users $SINGLEMDS |\n\t\t\t\t  awk '/^current.index:/ { print $NF }')\n\t\techo \"verify changelogs are off: $last_rec1 == $last_rec2\"\n\t\t[ $last_rec1 == $last_rec2 ] || error \"changelogs not off\"\n\telse\n\t\t# any changelog users must be leftovers from a previous test\n\t\tchangelog_users $SINGLEMDS\n\t\techo \"other changelog users; can't verify off\"\n\tfi\n}\nrun_test 160a \"changelog sanity\"\n\ntest_160b() { # LU-3587\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -ge $(version_code 2.2.0) ] ||\n\t\tskip \"Need MDS version at least 2.2.0\"\n\n\tchangelog_register || error \"changelog_register failed\"\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User '$cl_user' not found in changelog_users\"\n\n\tlocal longname1=$(str_repeat a 255)\n\tlocal longname2=$(str_repeat b 255)\n\n\tcd $DIR\n\techo \"creating very long named file\"\n\ttouch $longname1 || error \"create of '$longname1' failed\"\n\techo \"renaming very long named file\"\n\tmv $longname1 $longname2\n\n\tchangelog_dump | grep RENME | tail -n 5\n\trm -f $longname2\n}\nrun_test 160b \"Verify that very long rename doesn't crash in changelog\"\n\ntest_160c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\t[[ $MDS1_VERSION -gt $(version_code 2.5.57) ]] ||\n\t\t[[ $MDS1_VERSION -gt $(version_code 2.5.1) &&\n\t\t   $MDS1_VERSION -lt $(version_code 2.5.50) ]] ||\n\t\tskip \"Need MDS version at least 2.5.58 or 2.5.2+\"\n\n\tlocal rc=0\n\n\t# Registration step\n\tchangelog_register || error \"changelog_register failed\"\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\t$MCREATE $DIR/$tdir/foo_160c\n\tchangelog_chmask \"-TRUNC\"\n\t$TRUNCATE $DIR/$tdir/foo_160c 200\n\tchangelog_chmask \"+TRUNC\"\n\t$TRUNCATE $DIR/$tdir/foo_160c 199\n\tchangelog_dump | tail -n 5\n\tlocal truncs=$(changelog_dump | tail -n 5 | grep -c TRUNC)\n\t[ $truncs -eq 1 ] || error \"TRUNC changelog mask count $truncs != 1\"\n}\nrun_test 160c \"verify that changelog log catch the truncate event\"\n\ntest_160d() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.7.60) ]] ||\n\t\tskip \"Need MDS version at least 2.7.60\"\n\n\t# Registration step\n\tchangelog_register || error \"changelog_register failed\"\n\n\tmkdir -p $DIR/$tdir/migrate_dir\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\n\t$LFS migrate -m 1 $DIR/$tdir/migrate_dir || error \"migrate fails\"\n\tchangelog_dump | tail -n 5\n\tlocal migrates=$(changelog_dump | grep -c \"MIGRT\")\n\t[ $migrates -eq 1 ] || error \"MIGRATE changelog count $migrates != 1\"\n}\nrun_test 160d \"verify that changelog log catch the migrate event\"\n\ntest_160e() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\t# Create a user\n\tchangelog_register || error \"changelog_register failed\"\n\n\t# Delete a future user (expect fail)\n\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\tdo_facet $SINGLEMDS $LCTL --device $MDT0 changelog_deregister \"cl77\"\n\tlocal rc=$?\n\n\tif [ $rc -eq 0 ]; then\n\t\terror \"Deleted non-existant user cl77\"\n\telif [ $rc -ne 2 ]; then\n\t\terror \"changelog_deregister failed with $rc, expect 2 (ENOENT)\"\n\tfi\n\n\t# Clear to a bad index (1 billion should be safe)\n\t$LFS changelog_clear $MDT0 \"${CL_USERS[$SINGLEMDS]%% *}\" 1000000000\n\trc=$?\n\n\tif [ $rc -eq 0 ]; then\n\t\terror \"Successfully cleared to invalid CL index\"\n\telif [ $rc -ne 22 ]; then\n\t\terror \"changelog_clear failed with $rc, expected 22 (EINVAL)\"\n\tfi\n}\nrun_test 160e \"changelog negative testing (should return errors)\"\n\ntest_160f() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\t[[ $MDS1_VERSION -ge $(version_code 2.10.56) ]] ||\n\t\tskip \"Need MDS version at least 2.10.56\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\t# Create a user\n\tchangelog_register || error \"first changelog_register failed\"\n\tchangelog_register || error \"second changelog_register failed\"\n\tlocal cl_users\n\tdeclare -A cl_user1\n\tdeclare -A cl_user2\n\tlocal user_rec1\n\tlocal user_rec2\n\tlocal i\n\n\t# generate some changelog records to accumulate on each MDT\n\t# use fnv1a because created files should be evenly distributed\n\ttest_mkdir -c $MDSCOUNT -H fnv_1a_64 $DIR/$tdir ||\n\t\terror \"test_mkdir $tdir failed\"\n\tlog \"$(date +%s): creating first files\"\n\tcreatemany -m $DIR/$tdir/$tfile $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/$tfile failed\"\n\n\t# check changelogs have been generated\n\tlocal start=$SECONDS\n\tlocal idle_time=$((MDSCOUNT * 5 + 5))\n\tlocal nbcl=$(changelog_dump | wc -l)\n\t[[ $nbcl -eq 0 ]] && error \"no changelogs found\"\n\n\tfor param in \"changelog_max_idle_time=$idle_time\" \\\n\t\t     \"changelog_gc=1\" \\\n\t\t     \"changelog_min_gc_interval=2\" \\\n\t\t     \"changelog_min_free_cat_entries=3\"; do\n\t\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\t\tlocal var=\"${param%=*}\"\n\t\tlocal old=$(do_facet mds1 \"$LCTL get_param -n mdd.$MDT0.$var\")\n\n\t\tstack_trap \"do_nodes $mdts $LCTL set_param mdd.*.$var=$old\" EXIT\n\t\tdo_nodes $mdts $LCTL set_param mdd.*.$param\n\tdone\n\n\t# force cl_user2 to be idle (1st part), but also cancel the\n\t# cl_user1 records so that it is not evicted later in the test.\n\tlocal sleep1=$((idle_time / 2))\n\techo \"$(date +%s): sleep1 $sleep1/${idle_time}s\"\n\tsleep $sleep1\n\n\t# simulate changelog catalog almost full\n\t#define OBD_FAIL_CAT_FREE_RECORDS\t0x1313\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x1313 fail_val=3\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tcl_users=(${CL_USERS[mds$i]})\n\t\tcl_user1[mds$i]=\"${cl_users[0]}\"\n\t\tcl_user2[mds$i]=\"${cl_users[1]}\"\n\n\t\t[ -n \"${cl_user1[mds$i]}\" ] ||\n\t\t\terror \"mds$i: no user registered\"\n\t\t[ -n \"${cl_user2[mds$i]}\" ] ||\n\t\t\terror \"mds$i: only ${cl_user2[mds$i]} is registered\"\n\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t__changelog_clear mds$i ${cl_user1[mds$i]} +2\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\techo \"mds$i: verifying user ${cl_user1[mds$i]} clear: \" \\\n\t\t     \"$user_rec1 + 2 == $user_rec2\"\n\t\t[ $((user_rec1 + 2)) == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user1[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1 + 2, but is $user_rec2\"\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} not registered\"\n\t\t[ $user_rec1 == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user2[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1, but is $user_rec2\"\n\tdone\n\n\t# force cl_user2 idle (2nd part) to just exceed changelog_max_idle_time\n\tlocal sleep2=$((idle_time - (SECONDS - start) + 1))\n\techo \"$(date +%s): sleep2 $sleep2/${idle_time}s\"\n\tsleep $sleep2\n\n\t# Generate one more changelog to trigger GC at fail_loc for cl_user2.\n\t# cl_user1 should be OK because it recently processed records.\n\techo \"$(date +%s): creating $((MDSCOUNT * 2)) files\"\n\tcreatemany -m $DIR/$tdir/${tfile}b $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/${tfile}b failed\"\n\n\t# ensure gc thread is done\n\tfor i in $(mdts_nodes); do\n\t\twait_update $i \\\n\t\t\t\"ps -e -o comm= | grep chlg_gc_thread\" \"\" 20 ||\n\t\t\terror \"$i: GC-thread not done\"\n\tdone\n\n\tlocal first_rec\n\tfor i in $(seq $MDSCOUNT); do\n\t\t# check cl_user1 still registered\n\t\tchangelog_users mds$i | grep -q \"${cl_user1[mds$i]}\" ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t# check cl_user2 unregistered\n\t\tchangelog_users mds$i | grep -q \"${cl_user2[mds$i]}\" &&\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} still registered\"\n\n\t\t# check changelogs are present and starting at $user_rec1 + 1\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\tfirst_rec=$($LFS changelog $(facet_svc mds$i) |\n\t\t\t    awk '{ print $1; exit; }')\n\n\t\techo \"mds$i: verifying first index $user_rec1 + 1 == $first_rec\"\n\t\t[ $((user_rec1 + 1)) == $first_rec ] ||\n\t\t\terror \"mds$i: first index should be $user_rec1 + 1, \" \\\n\t\t\t      \"but is $first_rec\"\n\tdone\n}\nrun_test 160f \"changelog garbage collect (timestamped users)\"\n\ntest_160g() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.10.56) ]] ||\n\t\tskip \"Need MDS version at least 2.10.56\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\t#define OBD_FAIL_TIME_IN_CHLOG_USER\t0x1314\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x1314\n\n\t# Create a user\n\tchangelog_register || error \"first changelog_register failed\"\n\tchangelog_register || error \"second changelog_register failed\"\n\tlocal cl_users\n\tdeclare -A cl_user1\n\tdeclare -A cl_user2\n\tlocal user_rec1\n\tlocal user_rec2\n\tlocal i\n\n\t# generate some changelog records to accumulate on each MDT\n\t# use fnv1a because created files should be evenly distributed\n\ttest_mkdir -c $MDSCOUNT -H fnv_1a_64 $DIR/$tdir ||\n\t\terror \"mkdir $tdir failed\"\n\tcreatemany -m $DIR/$tdir/$tfile $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/$tfile failed\"\n\n\t# check changelogs have been generated\n\tlocal nbcl=$(changelog_dump | wc -l)\n\t[[ $nbcl -eq 0 ]] && error \"no changelogs found\"\n\n\t# reduce the max_idle_indexes value to make sure we exceed it\n\tmax_ndx=$((nbcl / 2 - 1))\n\n\tfor param in \"changelog_max_idle_indexes=$max_ndx\" \\\n\t\t     \"changelog_gc=1\" \\\n\t\t     \"changelog_min_gc_interval=2\" \\\n\t\t     \"changelog_min_free_cat_entries=3\"; do\n\t\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\t\tlocal var=\"${param%=*}\"\n\t\tlocal old=$(do_facet mds1 \"$LCTL get_param -n mdd.$MDT0.$var\")\n\n\t\tstack_trap \"do_nodes $mdts $LCTL set_param mdd.*.$var=$old\" EXIT\n\t\tdo_nodes $mdts $LCTL set_param mdd.*.$param ||\n\t\t\terror \"unable to set mdd.*.$param\"\n\tdone\n\n\t# simulate changelog catalog almost full\n\t#define OBD_FAIL_CAT_FREE_RECORDS\t0x1313\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x1313 fail_val=3\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tcl_users=(${CL_USERS[mds$i]})\n\t\tcl_user1[mds$i]=\"${cl_users[0]}\"\n\t\tcl_user2[mds$i]=\"${cl_users[1]}\"\n\n\t\t[ -n \"${cl_user1[mds$i]}\" ] ||\n\t\t\terror \"mds$i: no user registered\"\n\t\t[ -n \"${cl_user2[mds$i]}\" ] ||\n\t\t\terror \"mds$i: only ${cl_user1[mds$i]} is registered\"\n\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t__changelog_clear mds$i ${cl_user1[mds$i]} +2\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\techo \"mds$i: verifying user ${cl_user1[mds$i]} clear: \" \\\n\t\t     \"$user_rec1 + 2 == $user_rec2\"\n\t\t[ $((user_rec1 + 2)) == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user1[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1 + 2, but is $user_rec2\"\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} not registered\"\n\t\t[ $user_rec1 == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user2[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1, but is $user_rec2\"\n\tdone\n\n\t# ensure we are past the previous changelog_min_gc_interval set above\n\tsleep 2\n\n\t# generate one more changelog to trigger fail_loc\n\tcreatemany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/${tfile}bis failed\"\n\n\t# ensure gc thread is done\n\tfor i in $(mdts_nodes); do\n\t\twait_update $i \\\n\t\t\t\"ps -e -o comm= | grep chlg_gc_thread\" \"\" 20 ||\n\t\t\terror \"$i: GC-thread not done\"\n\tdone\n\n\tlocal first_rec\n\tfor i in $(seq $MDSCOUNT); do\n\t\t# check cl_user1 still registered\n\t\tchangelog_users mds$i | grep -q \"${cl_user1[mds$i]}\" ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t# check cl_user2 unregistered\n\t\tchangelog_users mds$i | grep -q \"${cl_user2[mds$i]}\" &&\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} still registered\"\n\n\t\t# check changelogs are present and starting at $user_rec1 + 1\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\tfirst_rec=$($LFS changelog $(facet_svc mds$i) |\n\t\t\t    awk '{ print $1; exit; }')\n\n\t\techo \"mds$i: verifying first index $user_rec1 + 1 == $first_rec\"\n\t\t[ $((user_rec1 + 1)) == $first_rec ] ||\n\t\t\terror \"mds$i: first index should be $user_rec1 + 1, \" \\\n\t\t\t      \"but is $first_rec\"\n\tdone\n}\nrun_test 160g \"changelog garbage collect (old users)\"\n\ntest_160h() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\t[[ $MDS1_VERSION -ge $(version_code 2.10.56) ]] ||\n\t\tskip \"Need MDS version at least 2.10.56\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\t# Create a user\n\tchangelog_register || error \"first changelog_register failed\"\n\tchangelog_register || error \"second changelog_register failed\"\n\tlocal cl_users\n\tdeclare -A cl_user1\n\tdeclare -A cl_user2\n\tlocal user_rec1\n\tlocal user_rec2\n\tlocal i\n\n\t# generate some changelog records to accumulate on each MDT\n\t# use fnv1a because created files should be evenly distributed\n\ttest_mkdir -c $MDSCOUNT -H fnv_1a_64 $DIR/$tdir ||\n\t\terror \"test_mkdir $tdir failed\"\n\tcreatemany -m $DIR/$tdir/$tfile $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/$tfile failed\"\n\n\t# check changelogs have been generated\n\tlocal nbcl=$(changelog_dump | wc -l)\n\t[[ $nbcl -eq 0 ]] && error \"no changelogs found\"\n\n\tfor param in \"changelog_max_idle_time=10\" \\\n\t\t     \"changelog_gc=1\" \\\n\t\t     \"changelog_min_gc_interval=2\"; do\n\t\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\t\tlocal var=\"${param%=*}\"\n\t\tlocal old=$(do_facet mds1 \"$LCTL get_param -n mdd.$MDT0.$var\")\n\n\t\tstack_trap \"do_nodes $mdts $LCTL set_param mdd.*.$var=$old\" EXIT\n\t\tdo_nodes $mdts $LCTL set_param mdd.*.$param\n\tdone\n\n\t# force cl_user2 to be idle (1st part)\n\tsleep 9\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tcl_users=(${CL_USERS[mds$i]})\n\t\tcl_user1[mds$i]=\"${cl_users[0]}\"\n\t\tcl_user2[mds$i]=\"${cl_users[1]}\"\n\n\t\t[ -n \"${cl_user1[mds$i]}\" ] ||\n\t\t\terror \"mds$i: no user registered\"\n\t\t[ -n \"${cl_user2[mds$i]}\" ] ||\n\t\t\terror \"mds$i: only ${cl_user2[mds$i]} is registered\"\n\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t__changelog_clear mds$i ${cl_user1[mds$i]} +2\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\techo \"mds$i: verifying user ${cl_user1[mds$i]} clear: \" \\\n\t\t     \"$user_rec1 + 2 == $user_rec2\"\n\t\t[ $((user_rec1 + 2)) == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user1[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1 + 2, but is $user_rec2\"\n\t\tuser_rec2=$(changelog_user_rec mds$i ${cl_user2[mds$i]})\n\t\t[ -n \"$user_rec2\" ] ||\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} not registered\"\n\t\t[ $user_rec1 == $user_rec2 ] ||\n\t\t\terror \"mds$i: user ${cl_user2[mds$i]} index expected \" \\\n\t\t\t      \"$user_rec1, but is $user_rec2\"\n\tdone\n\n\t# force cl_user2 to be idle (2nd part) and to reach\n\t# changelog_max_idle_time\n\tsleep 2\n\n\t# force each GC-thread start and block then\n\t# one per MDT/MDD, set fail_val accordingly\n\t#define OBD_FAIL_FORCE_GC_THREAD 0x1316\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x1316\n\n\t# generate more changelogs to trigger fail_loc\n\tcreatemany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/${tfile}bis failed\"\n\n\t# stop MDT to stop GC-thread, should be done in back-ground as it will\n\t# block waiting for the thread to be released and exit\n\tdeclare -A stop_pids\n\tfor i in $(seq $MDSCOUNT); do\n\t\tstop mds$i &\n\t\tstop_pids[mds$i]=$!\n\tdone\n\n\tfor i in $(mdts_nodes); do\n\t\tlocal facet\n\t\tlocal nb=0\n\t\tlocal facets=$(facets_up_on_host $i)\n\n\t\tfor facet in ${facets//,/ }; do\n\t\t\tif [[ $facet == mds* ]]; then\n\t\t\t\tnb=$((nb + 1))\n\t\t\tfi\n\t\tdone\n\t\t# ensure each MDS's gc threads are still present and all in \"R\"\n\t\t# state (OBD_FAIL_FORCE_GC_THREAD effect!)\n\t\t[[ $(do_node $i pgrep chlg_gc_thread | wc -l) -eq $nb ]] ||\n\t\t\terror \"$i: expected $nb GC-thread\"\n\t\twait_update $i \\\n\t\t\t\"ps -C chlg_gc_thread -o state --no-headers | uniq\" \\\n\t\t\t\"R\" 20 ||\n\t\t\terror \"$i: GC-thread not found in R-state\"\n\t\t# check umounts of each MDT on MDS have reached kthread_stop()\n\t\t[[ $(do_node $i pgrep umount | wc -l) -eq $nb ]] ||\n\t\t\terror \"$i: expected $nb umount\"\n\t\twait_update $i \\\n\t\t\t\"ps -C umount -o state --no-headers | uniq\" \"D\" 20 ||\n\t\t\terror \"$i: umount not found in D-state\"\n\tdone\n\n\t# release all GC-threads\n\tdo_nodes $mdts $LCTL set_param fail_loc=0\n\n\t# wait for MDT stop to complete\n\tfor i in $(seq $MDSCOUNT); do\n\t\twait ${stop_pids[mds$i]} || error \"mds$i: stop failed\"\n\tdone\n\n\t# XXX\n\t# may try to check if any orphan changelog records are present\n\t# via ldiskfs/zfs and llog_reader...\n\n\t# re-start/mount MDTs\n\tfor i in $(seq $MDSCOUNT); do\n\t\tstart mds$i $(mdsdevname $i) $MDS_MOUNT_OPTS ||\n\t\t\terror \"Fail to start mds$i\"\n\tdone\n\n\tlocal first_rec\n\tfor i in $(seq $MDSCOUNT); do\n\t\t# check cl_user1 still registered\n\t\tchangelog_users mds$i | grep -q \"${cl_user1[mds$i]}\" ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\t# check cl_user2 unregistered\n\t\tchangelog_users mds$i | grep -q \"${cl_user2[mds$i]}\" &&\n\t\t\terror \"mds$i: User ${cl_user2[mds$i]} still registered\"\n\n\t\t# check changelogs are present and starting at $user_rec1 + 1\n\t\tuser_rec1=$(changelog_user_rec mds$i ${cl_user1[mds$i]})\n\t\t[ -n \"$user_rec1\" ] ||\n\t\t\terror \"mds$i: User ${cl_user1[mds$i]} not registered\"\n\t\tfirst_rec=$($LFS changelog $(facet_svc mds$i) |\n\t\t\t    awk '{ print $1; exit; }')\n\n\t\techo \"mds$i: verifying first index $user_rec1 + 1 == $first_rec\"\n\t\t[ $((user_rec1 + 1)) == $first_rec ] ||\n\t\t\terror \"mds$i: first index should be $user_rec1 + 1, \" \\\n\t\t\t      \"but is $first_rec\"\n\tdone\n}\nrun_test 160h \"changelog gc thread stop upon umount, orphan records delete \" \\\n\t      \"during mount\"\n\ntest_160i() {\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\tchangelog_register || error \"first changelog_register failed\"\n\n\t# generate some changelog records to accumulate on each MDT\n\t# use fnv1a because created files should be evenly distributed\n\ttest_mkdir -c $MDSCOUNT -H fnv_1a_64 $DIR/$tdir ||\n\t\terror \"mkdir $tdir failed\"\n\tcreatemany -m $DIR/$tdir/$tfile $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/$tfile failed\"\n\n\t# check changelogs have been generated\n\tlocal nbcl=$(changelog_dump | wc -l)\n\t[[ $nbcl -eq 0 ]] && error \"no changelogs found\"\n\n\t# simulate race between register and unregister\n\t# XXX as fail_loc is set per-MDS, with DNE configs the race\n\t# simulation will only occur for one MDT per MDS and for the\n\t# others the normal race scenario will take place\n\t#define CFS_FAIL_CHLOG_USER_REG_UNREG_RACE          0x1315\n\tdo_nodes $mdts $LCTL set_param fail_loc=0x10001315\n\tdo_nodes $mdts $LCTL set_param fail_val=1\n\n\t# unregister 1st user\n\tchangelog_deregister &\n\tlocal pid1=$!\n\t# wait some time for deregister work to reach race rdv\n\tsleep 2\n\t# register 2nd user\n\tchangelog_register || error \"2nd user register failed\"\n\n\twait $pid1 || error \"1st user deregister failed\"\n\n\tlocal i\n\tlocal last_rec\n\tdeclare -A LAST_REC\n\tfor i in $(seq $MDSCOUNT); do\n\t\tif changelog_users mds$i | grep \"^cl\"; then\n\t\t\t# make sure new records are added with one user present\n\t\t\tLAST_REC[mds$i]=$(changelog_users $SINGLEMDS |\n\t\t\t\t\t  awk '/^current.index:/ { print $NF }')\n\t\telse\n\t\t\terror \"mds$i has no user registered\"\n\t\tfi\n\tdone\n\n\t# generate more changelog records to accumulate on each MDT\n\tcreatemany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/${tfile}bis failed\"\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tlast_rec=$(changelog_users $SINGLEMDS |\n\t\t\t   awk '/^current.index:/ { print $NF }')\n\t\techo \"verify changelogs are on: $last_rec != ${LAST_REC[mds$i]}\"\n\t\t[ $last_rec != ${LAST_REC[mds$i]} ] ||\n\t\t\terror \"changelogs are off on mds$i\"\n\tdone\n}\nrun_test 160i \"changelog user register/unregister race\"\n\ntest_160j() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.12.56) ]] &&\n\t\tskip \"Need MDS version at least 2.12.56\"\n\n\tmount_client $MOUNT2 || error \"mount_client on $MOUNT2 failed\"\n\tstack_trap \"umount $MOUNT2\" EXIT\n\n\tchangelog_register || error \"first changelog_register failed\"\n\tstack_trap \"changelog_deregister\" EXIT\n\n\t# generate some changelog\n\t# use fnv1a because created files should be evenly distributed\n\ttest_mkdir -c $MDSCOUNT -H fnv_1a_64 $DIR/$tdir ||\n\t\terror \"mkdir $tdir failed\"\n\tcreatemany -m $DIR/$tdir/${tfile}bis $((MDSCOUNT * 2)) ||\n\t\terror \"create $DIR/$tdir/${tfile}bis failed\"\n\n\t# open the changelog device\n\texec 3>/dev/changelog-$FSNAME-MDT0000\n\tstack_trap \"exec 3>&-\" EXIT\n\texec 4</dev/changelog-$FSNAME-MDT0000\n\tstack_trap \"exec 4<&-\" EXIT\n\n\t# umount the first lustre mount\n\tumount $MOUNT\n\tstack_trap \"mount_client $MOUNT\" EXIT\n\n\t# read changelog\n\tcat <&4 >/dev/null || error \"read changelog failed\"\n\n\t# clear changelog\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User $cl_user not found in changelog_users\"\n\n\tprintf 'clear:'$cl_user':0' >&3\n}\nrun_test 160j \"client can be umounted  while its chanangelog is being used\"\n\ntest_160k() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tmkdir -p $DIR/$tdir/1/1\n\n\tchangelog_register || error \"changelog_register failed\"\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User '$cl_user' not found in changelog_users\"\n#define OBD_FAIL_MDS_CHANGELOG_REORDER 0x15d\n\tdo_facet mds1 $LCTL set_param fail_loc=0x8000015d fail_val=3\n\trmdir $DIR/$tdir/1/1 & sleep 1\n\tmkdir $DIR/$tdir/2\n\ttouch $DIR/$tdir/2/2\n\trm -rf $DIR/$tdir/2\n\n\twait\n\tsleep 4\n\n\tchangelog_dump | grep rmdir || error \"rmdir not recorded\"\n\n\trm -rf $DIR/$tdir\n\tchangelog_deregister\n}\nrun_test 160k \"Verify that changelog records are not lost\"\n\ntest_161a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\ttest_mkdir -c1 $DIR/$tdir\n\tcp /etc/hosts $DIR/$tdir/$tfile\n\ttest_mkdir -c1 $DIR/$tdir/foo1\n\ttest_mkdir -c1 $DIR/$tdir/foo2\n\tln $DIR/$tdir/$tfile $DIR/$tdir/foo1/sofia\n\tln $DIR/$tdir/$tfile $DIR/$tdir/foo2/zachary\n\tln $DIR/$tdir/$tfile $DIR/$tdir/foo1/luna\n\tln $DIR/$tdir/$tfile $DIR/$tdir/foo2/thor\n\tlocal FID=$($LFS path2fid $DIR/$tdir/$tfile | tr -d '[]')\n\tif [ \"$($LFS fid2path $DIR $FID | wc -l)\" != \"5\" ]; then\n\t\t$LFS fid2path $DIR $FID\n\t\terror \"bad link ea\"\n\tfi\n\t# middle\n\trm $DIR/$tdir/foo2/zachary\n\t# last\n\trm $DIR/$tdir/foo2/thor\n\t# first\n\trm $DIR/$tdir/$tfile\n\t# rename\n\tmv $DIR/$tdir/foo1/sofia $DIR/$tdir/foo2/maggie\n\t[ \"$($LFS fid2path $FSNAME --link 1 $FID)\" != \"$tdir/foo2/maggie\" ] &&\n\t\t{ $LFS fid2path $DIR $FID; error \"bad link rename\"; }\n\trm $DIR/$tdir/foo2/maggie\n\n\t# overflow the EA\n\tlocal longname=$tfile.avg_len_is_thirty_two_\n\tstack_trap \"unlinkmany $DIR/$tdir/foo2/$longname 1000 || \\\n\t\terror_noexit 'failed to unlink many hardlinks'\" EXIT\n\tcreatemany -l$DIR/$tdir/foo1/luna $DIR/$tdir/foo2/$longname 1000 ||\n\t\terror \"failed to hardlink many files\"\n\tlinks=$($LFS fid2path $DIR $FID | wc -l)\n\techo -n \"${links}/1000 links in link EA\"\n\t[[ $links -gt 60 ]] || error \"expected at least 60 links in link EA\"\n}\nrun_test 161a \"link ea sanity\"\n\ntest_161b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"skipping remote directory test\"\n\n\tlocal MDTIDX=1\n\tlocal remote_dir=$DIR/$tdir/remote_dir\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -i $MDTIDX $remote_dir ||\n\t\terror \"create remote directory failed\"\n\n\tcp /etc/hosts $remote_dir/$tfile\n\tmkdir -p $remote_dir/foo1\n\tmkdir -p $remote_dir/foo2\n\tln $remote_dir/$tfile $remote_dir/foo1/sofia\n\tln $remote_dir/$tfile $remote_dir/foo2/zachary\n\tln $remote_dir/$tfile $remote_dir/foo1/luna\n\tln $remote_dir/$tfile $remote_dir/foo2/thor\n\n\tlocal FID=$($LFS path2fid $remote_dir/$tfile | tr -d '[' |\n\t\t     tr -d ']')\n\tif [ \"$($LFS fid2path $DIR $FID | wc -l)\" != \"5\" ]; then\n\t\t$LFS fid2path $DIR $FID\n\t\terror \"bad link ea\"\n\tfi\n\t# middle\n\trm $remote_dir/foo2/zachary\n\t# last\n\trm $remote_dir/foo2/thor\n\t# first\n\trm $remote_dir/$tfile\n\t# rename\n\tmv $remote_dir/foo1/sofia $remote_dir/foo2/maggie\n\tlocal link_path=$($LFS fid2path $FSNAME --link 1 $FID)\n\tif [ \"$DIR/$link_path\" != \"$remote_dir/foo2/maggie\" ]; then\n\t\t$LFS fid2path $DIR $FID\n\t\terror \"bad link rename\"\n\tfi\n\trm $remote_dir/foo2/maggie\n\n\t# overflow the EA\n\tlocal longname=filename_avg_len_is_thirty_two_\n\tcreatemany -l$remote_dir/foo1/luna $remote_dir/foo2/$longname 1000 ||\n\t\terror \"failed to hardlink many files\"\n\tlinks=$($LFS fid2path $DIR $FID | wc -l)\n\techo -n \"${links}/1000 links in link EA\"\n\t[[ ${links} -gt 60 ]] ||\n\t\terror \"expected at least 60 links in link EA\"\n\tunlinkmany $remote_dir/foo2/$longname 1000 ||\n\terror \"failed to unlink many hardlinks\"\n}\nrun_test 161b \"link ea sanity under remote directory\"\n\ntest_161c() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.1.5) ]] &&\n\t\tskip \"Need MDS version at least 2.1.5\"\n\n\t# define CLF_RENAME_LAST 0x0001\n\t# rename overwrite a target having nlink = 1 (changelog flag 0x1)\n\tchangelog_register || error \"changelog_register failed\"\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir\n\ttouch $DIR/$tdir/foo_161c\n\ttouch $DIR/$tdir/bar_161c\n\tmv -f $DIR/$tdir/foo_161c $DIR/$tdir/bar_161c\n\tchangelog_dump | grep RENME | tail -n 5\n\tlocal flags=$(changelog_dump | grep \"RENME.*bar_161c\" | cut -f5 -d' ')\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\tif [ x$flags != \"x0x1\" ]; then\n\t\terror \"flag $flags is not 0x1\"\n\tfi\n\n\techo \"rename overwrite target with nlink = 1, changelog flags=$flags\"\n\t# rename overwrite a target having nlink > 1 (changelog flag 0x0)\n\ttouch $DIR/$tdir/foo_161c\n\ttouch $DIR/$tdir/bar_161c\n\tln $DIR/$tdir/bar_161c $DIR/$tdir/foobar_161c\n\tmv -f $DIR/$tdir/foo_161c $DIR/$tdir/bar_161c\n\tchangelog_dump | grep RENME | tail -n 5\n\tflags=$(changelog_dump | grep \"RENME.*bar_161c\" | cut -f5 -d' ')\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\tif [ x$flags != \"x0x0\" ]; then\n\t\terror \"flag $flags is not 0x0\"\n\tfi\n\techo \"rename overwrite a target having nlink > 1,\" \\\n\t\t\"changelog record has flags of $flags\"\n\n\t# rename doesn't overwrite a target (changelog flag 0x0)\n\ttouch $DIR/$tdir/foo_161c\n\tmv -f $DIR/$tdir/foo_161c $DIR/$tdir/foo2_161c\n\tchangelog_dump | grep RENME | tail -n 5\n\tflags=$(changelog_dump | grep RENME | tail -1 | cut -f5 -d' ')\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\tif [ x$flags != \"x0x0\" ]; then\n\t\terror \"flag $flags is not 0x0\"\n\tfi\n\techo \"rename doesn't overwrite a target,\" \\\n\t\t\"changelog record has flags of $flags\"\n\n\t# define CLF_UNLINK_LAST 0x0001\n\t# unlink a file having nlink = 1 (changelog flag 0x1)\n\trm -f $DIR/$tdir/foo2_161c\n\tchangelog_dump | grep UNLNK | tail -n 5\n\tflags=$(changelog_dump | grep UNLNK | tail -1 | cut -f5 -d' ')\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\tif [ x$flags != \"x0x1\" ]; then\n\t\terror \"flag $flags is not 0x1\"\n\tfi\n\techo \"unlink a file having nlink = 1,\" \\\n\t\t\"changelog record has flags of $flags\"\n\n\t# unlink a file having nlink > 1 (changelog flag 0x0)\n\tln -f $DIR/$tdir/bar_161c $DIR/$tdir/foobar_161c\n\trm -f $DIR/$tdir/foobar_161c\n\tchangelog_dump | grep UNLNK | tail -n 5\n\tflags=$(changelog_dump | grep UNLNK | tail -1 | cut -f5 -d' ')\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\tif [ x$flags != \"x0x0\" ]; then\n\t\terror \"flag $flags is not 0x0\"\n\tfi\n\techo \"unlink a file having nlink > 1, changelog record flags '$flags'\"\n}\nrun_test 161c \"check CL_RENME[UNLINK] changelog record flags\"\n\ntest_161d() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\n\tlocal pid\n\tlocal fid\n\n\tchangelog_register || error \"changelog_register failed\"\n\n\t# work in a standalone dir to avoid locking on $DIR/$MOUNT to\n\t# interfer with $MOUNT/.lustre/fid/ access\n\tmkdir $DIR/$tdir\n\t[[ $? -eq 0 ]] || error \"mkdir failed\"\n\n\t#define OBD_FAIL_LLITE_CREATE_NODE_PAUSE 0x140c | OBD_FAIL_ONCE\n\t$LCTL set_param fail_loc=0x8000140c\n\t# 5s pause\n\t$LCTL set_param fail_val=5\n\n\t# create file\n\techo foofoo > $DIR/$tdir/$tfile &\n\tpid=$!\n\n\t# wait for create to be delayed\n\tsleep 2\n\n\tps -p $pid\n\t[[ $? -eq 0 ]] || error \"create should be blocked\"\n\n\tlocal tempfile=\"$(mktemp --tmpdir $tfile.XXXXXX)\"\n\tstack_trap \"rm -f $tempfile\"\n\tfid=$(changelog_extract_field \"CREAT\" \"$tfile\" \"t=\")\n\tcat $MOUNT/.lustre/fid/$fid 2>/dev/null >$tempfile || error \"cat failed\"\n\t# some delay may occur during ChangeLog publishing and file read just\n\t# above, that could allow file write to happen finally\n\t[[ -s $tempfile ]] && echo \"file should be empty\"\n\n\t$LCTL set_param fail_loc=0\n\n\twait $pid\n\t[[ $? -eq 0 ]] || error \"create failed\"\n}\nrun_test 161d \"create with concurrent .lustre/fid access\"\n\ncheck_path() {\n\tlocal expected=\"$1\"\n\tshift\n\tlocal fid=\"$2\"\n\n\tlocal path\n\tpath=$($LFS fid2path \"$@\")\n\tlocal rc=$?\n\n\tif [ $rc -ne 0 ]; then\n\t\terror \"path looked up of '$expected' failed: rc=$rc\"\n\telif [ \"$path\" != \"$expected\" ]; then\n\t\terror \"path looked up '$path' instead of '$expected'\"\n\telse\n\t\techo \"FID '$fid' resolves to path '$path' as expected\"\n\tfi\n}\n\ntest_162a() { # was test_162\n\ttest_mkdir -p -c1 $DIR/$tdir/d2\n\ttouch $DIR/$tdir/d2/$tfile\n\ttouch $DIR/$tdir/d2/x1\n\ttouch $DIR/$tdir/d2/x2\n\ttest_mkdir -p -c1 $DIR/$tdir/d2/a/b/c\n\ttest_mkdir -p -c1 $DIR/$tdir/d2/p/q/r\n\t# regular file\n\tlocal fid=$($LFS path2fid $DIR/$tdir/d2/$tfile | tr -d '[]')\n\tcheck_path \"$tdir/d2/$tfile\" $FSNAME \"$fid\" --link 0\n\n\t# softlink\n\tln -s $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/p/q/r/slink\n\tfid=$($LFS path2fid $DIR/$tdir/d2/p/q/r/slink | tr -d '[]')\n\tcheck_path \"$tdir/d2/p/q/r/slink\" $FSNAME \"$fid\" --link 0\n\n\t# softlink to wrong file\n\tln -s /this/is/garbage $DIR/$tdir/d2/p/q/r/slink.wrong\n\tfid=$($LFS path2fid $DIR/$tdir/d2/p/q/r/slink.wrong | tr -d '[]')\n\tcheck_path \"$tdir/d2/p/q/r/slink.wrong\" $FSNAME \"$fid\" --link 0\n\n\t# hardlink\n\tln $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/p/q/r/hlink\n\tmv $DIR/$tdir/d2/$tfile $DIR/$tdir/d2/a/b/c/new_file\n\tfid=$($LFS path2fid $DIR/$tdir/d2/a/b/c/new_file | tr -d '[]')\n\t# fid2path dir/fsname should both work\n\tcheck_path \"$tdir/d2/a/b/c/new_file\" $FSNAME \"$fid\" --link 1\n\tcheck_path \"$DIR/$tdir/d2/p/q/r/hlink\" $DIR \"$fid\" --link 0\n\n\t# hardlink count: check that there are 2 links\n\tlocal nlinks=$($LFS fid2path $DIR \"$fid\" | wc -l)\n\t[ $nlinks -eq 2 ] || error \"expect 2 links, found $nlinks\"\n\n\t# hardlink indexing: remove the first link\n\trm $DIR/$tdir/d2/p/q/r/hlink\n\tcheck_path \"$tdir/d2/a/b/c/new_file\" $FSNAME $fid --link 0\n}\nrun_test 162a \"path lookup sanity\"\n\ntest_162b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tmkdir $DIR/$tdir\n\t$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||\n\t\t\t\terror \"create striped dir failed\"\n\n\tlocal FID=$($LFS getdirstripe $DIR/$tdir/striped_dir |\n\t\t\t\t\ttail -n 1 | awk '{print $2}')\n\tstat $MOUNT/.lustre/fid/$FID && error \"sub_stripe can be accessed\"\n\n\ttouch $DIR/$tdir/striped_dir/f{0..4} || error \"touch f0..4 failed\"\n\tmkdir $DIR/$tdir/striped_dir/d{0..4} || error \"mkdir d0..4 failed\"\n\n\t# regular file\n\tfor ((i=0;i<5;i++)); do\n\t\tFID=$($LFS path2fid $DIR/$tdir/striped_dir/f$i | tr -d '[]') ||\n\t\t\terror \"get fid for f$i failed\"\n\t\tcheck_path \"$tdir/striped_dir/f$i\" $FSNAME $FID --link 0\n\n\t\tFID=$($LFS path2fid $DIR/$tdir/striped_dir/d$i | tr -d '[]') ||\n\t\t\terror \"get fid for d$i failed\"\n\t\tcheck_path \"$tdir/striped_dir/d$i\" $FSNAME $FID --link 0\n\tdone\n\n\treturn 0\n}\nrun_test 162b \"striped directory path lookup sanity\"\n\n# LU-4239: Verify fid2path works with paths 100 or more directories deep\ntest_162c() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.7.51) ]] &&\n\t\tskip \"Need MDS version at least 2.7.51\"\n\n\tlocal lpath=$tdir.local\n\tlocal rpath=$tdir.remote\n\n\ttest_mkdir $DIR/$lpath\n\ttest_mkdir $DIR/$rpath\n\n\tfor ((i = 0; i <= 101; i++)); do\n\t\tlpath=\"$lpath/$i\"\n\t\tmkdir $DIR/$lpath\n\t\tFID=$($LFS path2fid $DIR/$lpath | tr -d '[]') ||\n\t\t\terror \"get fid for local directory $DIR/$lpath failed\"\n\t\tcheck_path \"$DIR/$lpath\" $MOUNT $FID --link 0\n\n\t\trpath=\"$rpath/$i\"\n\t\ttest_mkdir $DIR/$rpath\n\t\tFID=$($LFS path2fid $DIR/$rpath | tr -d '[]') ||\n\t\t\terror \"get fid for remote directory $DIR/$rpath failed\"\n\t\tcheck_path \"$DIR/$rpath\" $MOUNT $FID --link 0\n\tdone\n\n\treturn 0\n}\nrun_test 162c \"fid2path works with paths 100 or more directories deep\"\n\noalr_event_count() {\n\tlocal event=\"${1}\"\n\tlocal trace=\"${2}\"\n\n\tawk -v name=\"${FSNAME}-OST0000\" \\\n\t    -v event=\"${event}\" \\\n\t    '$1 == \"TRACE\" && $2 == event && $3 == name' \\\n\t    \"${trace}\" |\n\twc -l\n}\n\noalr_expect_event_count() {\n\tlocal event=\"${1}\"\n\tlocal trace=\"${2}\"\n\tlocal expect=\"${3}\"\n\tlocal count\n\n\tcount=$(oalr_event_count \"${event}\" \"${trace}\")\n\tif ((count == expect)); then\n\t\treturn 0\n\tfi\n\n\terror_noexit \"${event} event count was '${count}', expected ${expect}\"\n\tcat \"${trace}\" >&2\n\texit 1\n}\n\ncleanup_165() {\n\tdo_facet ost1 killall --quiet -KILL ofd_access_log_reader || true\n\tstop ost1\n\tstart ost1 \"$(ostdevname 1)\" $OST_MOUNT_OPTS\n}\n\nsetup_165() {\n\tsync # Flush previous IOs so we can count log entries.\n\tdo_facet ost1 $LCTL set_param \"obdfilter.${FSNAME}-OST0000.access_log_size=4096\"\n\tstack_trap cleanup_165 EXIT\n}\n\ntest_165a() {\n\tlocal trace=\"/tmp/${tfile}.trace\"\n\tlocal rc\n\tlocal count\n\n\tdo_facet ost1 ofd_access_log_reader --debug=- --trace=- > \"${trace}\" &\n\tsetup_165\n\tsleep 5\n\n\tdo_facet ost1 ofd_access_log_reader --list\n\tstop ost1\n\n\tdo_facet ost1 killall -TERM ofd_access_log_reader\n\twait\n\trc=$?\n\n\tif ((rc != 0)); then\n\t\terror \"ofd_access_log_reader exited with rc = '${rc}'\"\n\tfi\n\n\t# Parse trace file for discovery events:\n\toalr_expect_event_count alr_log_add \"${trace}\" 1\n\toalr_expect_event_count alr_log_eof \"${trace}\" 1\n\toalr_expect_event_count alr_log_free \"${trace}\" 1\n}\nrun_test 165a \"ofd access log discovery\"\n\ntest_165b() {\n\tlocal trace=\"/tmp/${tfile}.trace\"\n\tlocal file=\"${DIR}/${tfile}\"\n\tlocal pfid1\n\tlocal pfid2\n\tlocal -a entry\n\tlocal rc\n\tlocal count\n\tlocal size\n\tlocal flags\n\n\tsetup_165\n\n\tlfs setstripe -c 1 -i 0 \"${file}\"\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c || error \"cannot create '${file}'\"\n\tdo_facet ost1 ofd_access_log_reader --list\n\n\tdo_facet ost1 ofd_access_log_reader --debug=- --trace=- > \"${trace}\" &\n\tsleep 5\n\tdo_facet ost1 killall -TERM ofd_access_log_reader\n\twait\n\trc=$?\n\n\tif ((rc != 0)); then\n\t\terror \"ofd_access_log_reader exited with rc = '${rc}'\"\n\tfi\n\n\toalr_expect_event_count alr_log_entry \"${trace}\" 1\n\n\tpfid1=$($LFS path2fid \"${file}\")\n\n\t# 1     2             3   4    5     6   7    8    9     10\n\t# TRACE alr_log_entry OST PFID BEGIN END TIME SIZE COUNT FLAGS\n\tentry=( - $(awk -v pfid=\"${pfid}\" '$1 == \"TRACE\" && $2 == \"alr_log_entry\"' \"${trace}\" ) )\n\n\techo \"entry = '${entry[*]}'\" >&2\n\n\tpfid2=${entry[4]}\n\tif [[ \"${pfid1}\" != \"${pfid2}\" ]]; then\n\t\terror \"entry '${entry[*]}' has invalid PFID '${pfid2}', expected ${pfid1}\"\n\tfi\n\n\tsize=${entry[8]}\n\tif ((size != 1048576)); then\n\t\terror \"entry '${entry[*]}' has invalid io size '${size}', expected 1048576\"\n\tfi\n\n\tflags=${entry[10]}\n\tif [[ \"${flags}\" != \"w\" ]]; then\n\t\terror \"entry '${entry[*]}' has invalid io flags '${flags}', expected 'w'\"\n\tfi\n\n\tdo_facet ost1 ofd_access_log_reader --debug=- --trace=- > \"${trace}\" &\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_RDONLY:r524288c || error \"cannot read '${file}'\"\n\tsleep 5\n\tdo_facet ost1 killall -TERM ofd_access_log_reader\n\twait\n\trc=$?\n\n\tif ((rc != 0)); then\n\t\terror \"ofd_access_log_reader exited with rc = '${rc}'\"\n\tfi\n\n\toalr_expect_event_count alr_log_entry \"${trace}\" 1\n\n\tentry=( - $(awk -v pfid=\"${pfid}\" '$1 == \"TRACE\" && $2 == \"alr_log_entry\"' \"${trace}\" ) )\n\techo \"entry = '${entry[*]}'\" >&2\n\n\tpfid2=${entry[4]}\n\tif [[ \"${pfid1}\" != \"${pfid2}\" ]]; then\n\t\terror \"entry '${entry[*]}' has invalid PFID '${pfid2}', expected ${pfid1}\"\n\tfi\n\n\tsize=${entry[8]}\n\tif ((size != 524288)); then\n\t\terror \"entry '${entry[*]}' has invalid io size '${size}', 524288\"\n\tfi\n\n\tflags=${entry[10]}\n\tif [[ \"${flags}\" != \"r\" ]]; then\n\t\terror \"entry '${entry[*]}' has invalid io flags '${flags}', expected 'r'\"\n\tfi\n}\nrun_test 165b \"ofd access log entries are produced and consumed\"\n\ntest_165c() {\n\tlocal file=\"${DIR}/${tdir}/${tfile}\"\n\ttest_mkdir \"${DIR}/${tdir}\"\n\n\tsetup_165\n\n\tlfs setstripe -c 1 -i 0 \"${DIR}/${tdir}\"\n\n\t# 4096 / 64 = 64. Create twice as many entries.\n\tfor ((i = 0; i < 128; i++)); do\n\t\t$MULTIOP \"${file}-${i}\" oO_CREAT:O_WRONLY:w512c || error \"cannot create file\"\n\tdone\n\n\tsync\n\tdo_facet ost1 ofd_access_log_reader --list\n\tunlinkmany  \"${file}-%d\" 128\n}\nrun_test 165c \"full ofd access logs do not block IOs\"\n\noal_peek_entry_count() {\n\tdo_facet ost1 ofd_access_log_reader --list | awk '$1 == \"_entry_count:\" { print $2; }'\n}\n\noal_expect_entry_count() {\n\tlocal entry_count=$(oal_peek_entry_count)\n\tlocal expect=\"$1\"\n\n\tif ((entry_count == expect)); then\n\t\treturn 0\n\tfi\n\n\terror_noexit \"bad entry count, got ${entry_count}, expected ${expect}\"\n\tdo_facet ost1 ofd_access_log_reader --list >&2\n\texit 1\n}\n\ntest_165d() {\n\tlocal trace=\"/tmp/${tfile}.trace\"\n\tlocal file=\"${DIR}/${tdir}/${tfile}\"\n\tlocal param=\"obdfilter.${FSNAME}-OST0000.access_log_mask\"\n\tlocal entry_count\n\ttest_mkdir \"${DIR}/${tdir}\"\n\n\tsetup_165\n\tlfs setstripe -c 1 -i 0 \"${file}\"\n\n\tdo_facet ost1 lctl set_param \"${param}=rw\"\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c || error \"cannot create '${file}'\"\n\toal_expect_entry_count 1\n\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c || error \"cannot read '${file}'\"\n\toal_expect_entry_count 2\n\n\tdo_facet ost1 lctl set_param \"${param}=r\"\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c || error \"cannot create '${file}'\"\n\toal_expect_entry_count 2\n\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c || error \"cannot read '${file}'\"\n\toal_expect_entry_count 3\n\n\tdo_facet ost1 lctl set_param \"${param}=w\"\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c || error \"cannot create '${file}'\"\n\toal_expect_entry_count 4\n\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c || error \"cannot read '${file}'\"\n\toal_expect_entry_count 4\n\n\tdo_facet ost1 lctl set_param \"${param}=0\"\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_WRONLY:w1048576c || error \"cannot create '${file}'\"\n\toal_expect_entry_count 4\n\n\t$MULTIOP \"${file}\" oO_CREAT:O_DIRECT:O_RDONLY:r1048576c || error \"cannot read '${file}'\"\n\toal_expect_entry_count 4\n}\nrun_test 165d \"ofd_access_log mask works\"\n\ntest_169() {\n\t# do directio so as not to populate the page cache\n\tlog \"creating a 10 Mb file\"\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_DIRECT:O_RDWR:w$((10*1048576))c || error \"multiop failed while creating a file\"\n\tlog \"starting reads\"\n\tdd if=$DIR/$tfile of=/dev/null bs=4096 &\n\tlog \"truncating the file\"\n\t$MULTIOP $DIR/$tfile oO_TRUNC:c || error \"multiop failed while truncating the file\"\n\tlog \"killing dd\"\n\tkill %+ || true # reads might have finished\n\techo \"wait until dd is finished\"\n\twait\n\tlog \"removing the temporary file\"\n\trm -rf $DIR/$tfile || error \"tmp file removal failed\"\n}\nrun_test 169 \"parallel read and truncate should not deadlock\"\n\ntest_170() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t$LCTL clear\t# bug 18514\n\t$LCTL debug_daemon start $TMP/${tfile}_log_good\n\ttouch $DIR/$tfile\n\t$LCTL debug_daemon stop\n\tsed -e \"s/^...../a/g\" $TMP/${tfile}_log_good > $TMP/${tfile}_log_bad ||\n\t\terror \"sed failed to read log_good\"\n\n\t$LCTL debug_daemon start $TMP/${tfile}_log_good\n\trm -rf $DIR/$tfile\n\t$LCTL debug_daemon stop\n\n        $LCTL df $TMP/${tfile}_log_bad > $TMP/${tfile}_log_bad.out 2>&1 ||\n               error \"lctl df log_bad failed\"\n\n        local bad_line=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $9}')\n        local good_line1=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $5}')\n\n        $LCTL df $TMP/${tfile}_log_good > $TMP/${tfile}_log_good.out 2>&1\n        local good_line2=$(tail -n 1 $TMP/${tfile}_log_good.out | awk '{print $5}')\n\n\t[ \"$bad_line\" ] && [ \"$good_line1\" ] && [ \"$good_line2\" ] ||\n\t\terror \"bad_line good_line1 good_line2 are empty\"\n\n        cat $TMP/${tfile}_log_good >> $TMP/${tfile}_logs_corrupt\n        cat $TMP/${tfile}_log_bad >> $TMP/${tfile}_logs_corrupt\n        cat $TMP/${tfile}_log_good >> $TMP/${tfile}_logs_corrupt\n\n        $LCTL df $TMP/${tfile}_logs_corrupt > $TMP/${tfile}_log_bad.out 2>&1\n        local bad_line_new=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $9}')\n        local good_line_new=$(tail -n 1 $TMP/${tfile}_log_bad.out | awk '{print $5}')\n\n\t[ \"$bad_line_new\" ] && [ \"$good_line_new\" ] ||\n\t\terror \"bad_line_new good_line_new are empty\"\n\n        local expected_good=$((good_line1 + good_line2*2))\n\n        rm -f $TMP/${tfile}*\n\t# LU-231, short malformed line may not be counted into bad lines\n        if [ $bad_line -ne $bad_line_new ] &&\n\t\t   [ $bad_line -ne $((bad_line_new - 1)) ]; then\n                error \"expected $bad_line bad lines, but got $bad_line_new\"\n                return 1\n        fi\n\n        if [ $expected_good -ne $good_line_new ]; then\n                error \"expected $expected_good good lines, but got $good_line_new\"\n                return 2\n        fi\n        true\n}\nrun_test 170 \"test lctl df to handle corrupted log =====================\"\n\ntest_171() { # bug20592\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_PTLRPC_DUMP_LOG         0x50e\n\t$LCTL set_param fail_loc=0x50e\n\t$LCTL set_param fail_val=3000\n\tmultiop_bg_pause $DIR/$tfile O_s || true\n\tlocal MULTIPID=$!\n\tkill -USR1 $MULTIPID\n\t# cause log dump\n\tsleep 3\n\twait $MULTIPID\n\tif dmesg | grep \"recursive fault\"; then\n\t\terror \"caught a recursive fault\"\n\tfi\n\t$LCTL set_param fail_loc=0\n\ttrue\n}\nrun_test 171 \"test libcfs_debug_dumplog_thread stuck in do_exit() ======\"\n\n# it would be good to share it with obdfilter-survey/iokit-libecho code\nsetup_obdecho_osc () {\n        local rc=0\n        local ost_nid=$1\n        local obdfilter_name=$2\n        echo \"Creating new osc for $obdfilter_name on $ost_nid\"\n        # make sure we can find loopback nid\n        $LCTL add_uuid $ost_nid $ost_nid >/dev/null 2>&1\n\n        [ $rc -eq 0 ] && { $LCTL attach osc ${obdfilter_name}_osc     \\\n                           ${obdfilter_name}_osc_UUID || rc=2; }\n        [ $rc -eq 0 ] && { $LCTL --device ${obdfilter_name}_osc setup \\\n                           ${obdfilter_name}_UUID  $ost_nid || rc=3; }\n        return $rc\n}\n\ncleanup_obdecho_osc () {\n        local obdfilter_name=$1\n        $LCTL --device ${obdfilter_name}_osc cleanup >/dev/null\n        $LCTL --device ${obdfilter_name}_osc detach  >/dev/null\n        return 0\n}\n\nobdecho_test() {\n        local OBD=$1\n        local node=$2\n\tlocal pages=${3:-64}\n        local rc=0\n        local id\n\n\tlocal count=10\n\tlocal obd_size=$(get_obd_size $node $OBD)\n\tlocal page_size=$(get_page_size $node)\n\tif [[ -n \"$obd_size\" ]]; then\n\t\tlocal new_count=$((obd_size / (pages * page_size / 1024)))\n\t\t[[ $new_count -ge $count ]] || count=$new_count\n\tfi\n\n        do_facet $node \"$LCTL attach echo_client ec ec_uuid\" || rc=1\n        [ $rc -eq 0 ] && { do_facet $node \"$LCTL --device ec setup $OBD\" ||\n                           rc=2; }\n        if [ $rc -eq 0 ]; then\n            id=$(do_facet $node \"$LCTL --device ec create 1\"  | awk '/object id/ {print $6}')\n            [ ${PIPESTATUS[0]} -eq 0 -a -n \"$id\" ] || rc=3\n        fi\n        echo \"New object id is $id\"\n\t[ $rc -eq 0 ] && { do_facet $node \"$LCTL --device ec getattr $id\" ||\n\t\t\t   rc=4; }\n\t[ $rc -eq 0 ] && { do_facet $node \"$LCTL --device ec \"\t\t       \\\n\t\t\t   \"test_brw $count w v $pages $id\" || rc=4; }\n\t[ $rc -eq 0 ] && { do_facet $node \"$LCTL --device ec destroy $id 1\" ||\n\t\t\t   rc=4; }\n\t[ $rc -eq 0 ] || [ $rc -gt 2 ] &&\n\t\t{ do_facet $node \"$LCTL --device ec cleanup\" || rc=5; }\n\t[ $rc -eq 0 ] || [ $rc -gt 1 ] &&\n\t\t{ do_facet $node \"$LCTL --device ec detach\" || rc=6; }\n\t[ $rc -ne 0 ] && echo \"obecho_create_test failed: $rc\"\n\treturn $rc\n}\n\ntest_180a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tif ! module_loaded obdecho; then\n\t\tload_module obdecho/obdecho &&\n\t\t\tstack_trap \"rmmod obdecho\" EXIT ||\n\t\t\terror \"unable to load obdecho on client\"\n\tfi\n\n\tlocal osc=$($LCTL dl | grep -v mdt | awk '$3 == \"osc\" {print $4; exit}')\n\tlocal host=$($LCTL get_param -n osc.$osc.import |\n\t\t     awk '/current_connection:/ { print $2 }' )\n\tlocal target=$($LCTL get_param -n osc.$osc.import |\n\t\t       awk '/target:/ { print $2 }' )\n\ttarget=${target%_UUID}\n\n\tif [ -n \"$target\" ]; then\n\t\tsetup_obdecho_osc $host $target &&\n\t\t\tstack_trap \"cleanup_obdecho_osc $target\" EXIT ||\n\t\t\t{ error \"obdecho setup failed with $?\"; return; }\n\n\t\tobdecho_test ${target}_osc client ||\n\t\t\terror \"obdecho_test failed on ${target}_osc\"\n\telse\n\t\t$LCTL get_param osc.$osc.import\n\t\terror \"there is no osc.$osc.import target\"\n\tfi\n}\nrun_test 180a \"test obdecho on osc\"\n\ntest_180b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tdo_rpc_nodes $(facet_active_host ost1) load_module obdecho/obdecho &&\n\t\tstack_trap \"do_facet ost1 rmmod obdecho\" EXIT ||\n\t\terror \"failed to load module obdecho\"\n\n\tlocal target=$(do_facet ost1 $LCTL dl |\n\t\t       awk '/obdfilter/ { print $4; exit; }')\n\n\tif [ -n \"$target\" ]; then\n\t\tobdecho_test $target ost1 || error \"obdecho_test failed with $?\"\n\telse\n\t\tdo_facet ost1 $LCTL dl\n\t\terror \"there is no obdfilter target on ost1\"\n\tfi\n}\nrun_test 180b \"test obdecho directly on obdfilter\"\n\ntest_180c() { # LU-2598\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.4.0) ]] &&\n\t\tskip \"Need MDS version at least 2.4.0\"\n\n\tdo_rpc_nodes $(facet_active_host ost1) load_module obdecho/obdecho &&\n\t\tstack_trap \"do_facet ost1 rmmod obdecho\" EXIT ||\n\t\terror \"failed to load module obdecho\"\n\n\tlocal target=$(do_facet ost1 $LCTL dl |\n\t\t       awk '/obdfilter/ { print $4; exit; }')\n\n\tif [ -n \"$target\" ]; then\n\t\tlocal pages=16384 # 64MB bulk I/O RPC size\n\n\t\tobdecho_test \"$target\" ost1 \"$pages\" ||\n\t\t\terror \"obdecho_test with pages=$pages failed with $?\"\n\telse\n\t\tdo_facet ost1 $LCTL dl\n\t\terror \"there is no obdfilter target on ost1\"\n\tfi\n}\nrun_test 180c \"test huge bulk I/O size on obdfilter, don't LASSERT\"\n\ntest_181() { # bug 22177\n\ttest_mkdir $DIR/$tdir\n\t# create enough files to index the directory\n\tcreatemany -o $DIR/$tdir/foobar 4000\n\t# print attributes for debug purpose\n\tlsattr -d .\n\t# open dir\n\tmultiop_bg_pause $DIR/$tdir D_Sc || return 1\n\tMULTIPID=$!\n\t# remove the files & current working dir\n\tunlinkmany $DIR/$tdir/foobar 4000\n\trmdir $DIR/$tdir\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID\n\tstat $DIR/$tdir && error \"open-unlinked dir was not removed!\"\n\treturn 0\n}\nrun_test 181 \"Test open-unlinked dir ========================\"\n\ntest_182() {\n\tlocal fcount=1000\n\tlocal tcount=10\n\n\tmkdir -p $DIR/$tdir || error \"creating dir $DIR/$tdir\"\n\n\t$LCTL set_param mdc.*.rpc_stats=clear\n\n\tfor (( i = 0; i < $tcount; i++ )) ; do\n\t\tmkdir $DIR/$tdir/$i\n\tdone\n\n\tfor (( i = 0; i < $tcount; i++ )) ; do\n\t\tcreatemany -o $DIR/$tdir/$i/f- $fcount &\n\tdone\n\twait\n\n\tfor (( i = 0; i < $tcount; i++ )) ; do\n\t\tunlinkmany $DIR/$tdir/$i/f- $fcount &\n\tdone\n\twait\n\n\t$LCTL get_param mdc.*.rpc_stats\n\n\trm -rf $DIR/$tdir\n}\nrun_test 182 \"Test parallel modify metadata operations ================\"\n\ntest_183() { # LU-2275\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.3.56) ]] &&\n\t\tskip \"Need MDS version at least 2.3.56\"\n\n\tmkdir -p $DIR/$tdir || error \"creating dir $DIR/$tdir\"\n\techo aaa > $DIR/$tdir/$tfile\n\n#define OBD_FAIL_MDS_NEGATIVE_POSITIVE  0x148\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x148\n\n\tls -l $DIR/$tdir && error \"ls succeeded, should have failed\"\n\tcat $DIR/$tdir/$tfile && error \"cat succeeded, should have failed\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\n\t# Flush negative dentry cache\n\ttouch $DIR/$tdir/$tfile\n\n\t# We are not checking for any leaked references here, they'll\n\t# become evident next time we do cleanup with module unload.\n\trm -rf $DIR/$tdir\n}\nrun_test 183 \"No crash or request leak in case of strange dispositions ========\"\n\n# test suite 184 is for LU-2016, LU-2017\ntest_184a() {\n\tcheck_swap_layouts_support\n\n\tdir0=$DIR/$tdir/$testnum\n\ttest_mkdir -p -c1 $dir0\n\tref1=/etc/passwd\n\tref2=/etc/group\n\tfile1=$dir0/f1\n\tfile2=$dir0/f2\n\t$LFS setstripe -c1 $file1\n\tcp $ref1 $file1\n\t$LFS setstripe -c2 $file2\n\tcp $ref2 $file2\n\tgen1=$($LFS getstripe -g $file1)\n\tgen2=$($LFS getstripe -g $file2)\n\n\t$LFS swap_layouts $file1 $file2 || error \"swap of file layout failed\"\n\tgen=$($LFS getstripe -g $file1)\n\t[[ $gen1 != $gen ]] ||\n\t\t\"Layout generation on $file1 does not change\"\n\tgen=$($LFS getstripe -g $file2)\n\t[[ $gen2 != $gen ]] ||\n\t\t\"Layout generation on $file2 does not change\"\n\n\tcmp $ref1 $file2 || error \"content compare failed ($ref1 != $file2)\"\n\tcmp $ref2 $file1 || error \"content compare failed ($ref2 != $file1)\"\n\n\tlfsck_verify_pfid $file1 $file2 || error \"PFID are not transferred\"\n}\nrun_test 184a \"Basic layout swap\"\n\ntest_184b() {\n\tcheck_swap_layouts_support\n\n\tdir0=$DIR/$tdir/$testnum\n\tmkdir -p $dir0 || error \"creating dir $dir0\"\n\tfile1=$dir0/f1\n\tfile2=$dir0/f2\n\tfile3=$dir0/f3\n\tdir1=$dir0/d1\n\tdir2=$dir0/d2\n\tmkdir $dir1 $dir2\n\t$LFS setstripe -c1 $file1\n\t$LFS setstripe -c2 $file2\n\t$LFS setstripe -c1 $file3\n\tchown $RUNAS_ID $file3\n\tgen1=$($LFS getstripe -g $file1)\n\tgen2=$($LFS getstripe -g $file2)\n\n\t$LFS swap_layouts $dir1 $dir2 &&\n\t\terror \"swap of directories layouts should fail\"\n\t$LFS swap_layouts $dir1 $file1 &&\n\t\terror \"swap of directory and file layouts should fail\"\n\t$RUNAS $LFS swap_layouts $file1 $file2 &&\n\t\terror \"swap of file we cannot write should fail\"\n\t$LFS swap_layouts $file1 $file3 &&\n\t\terror \"swap of file with different owner should fail\"\n\t/bin/true # to clear error code\n}\nrun_test 184b \"Forbidden layout swap (will generate errors)\"\n\ntest_184c() {\n\tlocal cmpn_arg=$(cmp -n 2>&1 | grep \"invalid option\")\n\t[ -n \"$cmpn_arg\" ] && skip_env \"cmp does not support -n\"\n\tcheck_swap_layouts_support\n\tcheck_swap_layout_no_dom $DIR\n\n\tlocal dir0=$DIR/$tdir/$testnum\n\tmkdir -p $dir0 || error \"creating dir $dir0\"\n\n\tlocal ref1=$dir0/ref1\n\tlocal ref2=$dir0/ref2\n\tlocal file1=$dir0/file1\n\tlocal file2=$dir0/file2\n\t# create a file large enough for the concurrent test\n\tdd if=/dev/urandom of=$ref1 bs=1M count=$((RANDOM % 50 + 20))\n\tdd if=/dev/urandom of=$ref2 bs=1M count=$((RANDOM % 50 + 20))\n\techo \"ref file size: ref1($(stat -c %s $ref1)),\" \\\n\t     \"ref2($(stat -c %s $ref2))\"\n\n\tcp $ref2 $file2\n\tdd if=$ref1 of=$file1 bs=16k &\n\tlocal DD_PID=$!\n\n\t# Make sure dd starts to copy file\n\twhile [ ! -f $file1 ]; do sleep 0.1; done\n\n\t$LFS swap_layouts $file1 $file2\n\tlocal rc=$?\n\twait $DD_PID\n\t[[ $? == 0 ]] || error \"concurrent write on $file1 failed\"\n\t[[ $rc == 0 ]] || error \"swap of $file1 and $file2 failed\"\n\n\t# how many bytes copied before swapping layout\n\tlocal copied=$(stat -c %s $file2)\n\tlocal remaining=$(stat -c %s $ref1)\n\tremaining=$((remaining - copied))\n\techo \"Copied $copied bytes before swapping layout...\"\n\n\tcmp -n $copied $file1 $ref2 | grep differ &&\n\t\terror \"Content mismatch [0, $copied) of ref2 and file1\"\n\tcmp -n $copied $file2 $ref1 ||\n\t\terror \"Content mismatch [0, $copied) of ref1 and file2\"\n\tcmp -i $copied:$copied -n $remaining $file1 $ref1 ||\n\t\terror \"Content mismatch [$copied, EOF) of ref1 and file1\"\n\n\t# clean up\n\trm -f $ref1 $ref2 $file1 $file2\n}\nrun_test 184c \"Concurrent write and layout swap\"\n\ntest_184d() {\n\tcheck_swap_layouts_support\n\tcheck_swap_layout_no_dom $DIR\n\t[ -z \"$(which getfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"no getfattr command\"\n\n\tlocal file1=$DIR/$tdir/$tfile-1\n\tlocal file2=$DIR/$tdir/$tfile-2\n\tlocal file3=$DIR/$tdir/$tfile-3\n\tlocal lovea1\n\tlocal lovea2\n\n\tmkdir -p $DIR/$tdir\n\ttouch $file1 || error \"create $file1 failed\"\n\t$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file2 ||\n\t\terror \"create $file2 failed\"\n\t$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file3 ||\n\t\terror \"create $file3 failed\"\n\tlovea1=$(get_layout_param $file1)\n\n\t$LFS swap_layouts $file2 $file3 ||\n\t\terror \"swap $file2 $file3 layouts failed\"\n\t$LFS swap_layouts $file1 $file2 ||\n\t\terror \"swap $file1 $file2 layouts failed\"\n\n\tlovea2=$(get_layout_param $file2)\n\techo \"$lovea1\"\n\techo \"$lovea2\"\n\t[ \"$lovea1\" == \"$lovea2\" ] || error \"lovea $lovea1 != $lovea2\"\n\n\tlovea1=$(getfattr -n trusted.lov $file1 | grep ^trusted)\n\t[[ -z \"$lovea1\" ]] || error \"$file1 shouldn't have lovea\"\n}\nrun_test 184d \"allow stripeless layouts swap\"\n\ntest_184e() {\n\t[[ $MDS1_VERSION -ge $(version_code 2.6.94) ]] ||\n\t\tskip \"Need MDS version at least 2.6.94\"\n\tcheck_swap_layouts_support\n\tcheck_swap_layout_no_dom $DIR\n\t[ -z \"$(which getfattr 2>/dev/null)\" ] &&\n\t\tskip_env \"no getfattr command\"\n\n\tlocal file1=$DIR/$tdir/$tfile-1\n\tlocal file2=$DIR/$tdir/$tfile-2\n\tlocal file3=$DIR/$tdir/$tfile-3\n\tlocal lovea\n\n\tmkdir -p $DIR/$tdir\n\ttouch $file1 || error \"create $file1 failed\"\n\t$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file2 ||\n\t\terror \"create $file2 failed\"\n\t$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE $file3 ||\n\t\terror \"create $file3 failed\"\n\n\t$LFS swap_layouts $file1 $file2 ||\n\t\terror \"swap $file1 $file2 layouts failed\"\n\n\tlovea=$(getfattr -n trusted.lov $file1 | grep ^trusted)\n\t[[ -z \"$lovea\" ]] || error \"$file1 shouldn't have lovea\"\n\n\techo 123 > $file1 || error \"Should be able to write into $file1\"\n\n\t$LFS swap_layouts $file1 $file3 ||\n\t\terror \"swap $file1 $file3 layouts failed\"\n\n\techo 123 > $file1 || error \"Should be able to write into $file1\"\n\n\trm -rf $file1 $file2 $file3\n}\nrun_test 184e \"Recreate layout after stripeless layout swaps\"\n\ntest_184f() {\n\t# Create a file with name longer than sizeof(struct stat) ==\n\t# 144 to see if we can get chars from the file name to appear\n\t# in the returned striping. Note that 'f' == 0x66.\n\tlocal file=$(for ((i = 0; i < 200; i++)); do echo -n f; done)\n\n\tmkdir -p $DIR/$tdir\n\tmcreate $DIR/$tdir/$file\n\tif lfs find --stripe-count 0x6666 $DIR/$tdir | grep $file; then\n\t\terror \"IOC_MDC_GETFILEINFO returned garbage striping\"\n\tfi\n}\nrun_test 184f \"IOC_MDC_GETFILEINFO for files with long names but no striping\"\n\ntest_185() { # LU-2441\n\t# LU-3553 - no volatile file support in old servers\n\t[[ $MDS1_VERSION -ge $(version_code 2.3.60) ]] ||\n\t\tskip \"Need MDS version at least 2.3.60\"\n\n\tmkdir -p $DIR/$tdir || error \"creating dir $DIR/$tdir\"\n\ttouch $DIR/$tdir/spoo\n\tlocal mtime1=$(stat -c \"%Y\" $DIR/$tdir)\n\tlocal fid=$($MULTIOP $DIR/$tdir VFw4096c) ||\n\t\terror \"cannot create/write a volatile file\"\n\t[ \"$FILESET\" == \"\" ] &&\n\t$CHECKSTAT -t file $MOUNT/.lustre/fid/$fid 2>/dev/null &&\n\t\terror \"FID is still valid after close\"\n\n\tmultiop_bg_pause $DIR/$tdir vVw4096_c\n\tlocal multi_pid=$!\n\n\tlocal OLD_IFS=$IFS\n\tIFS=\":\"\n\tlocal fidv=($fid)\n\tIFS=$OLD_IFS\n\t# assume that the next FID for this client is sequential, since stdout\n\t# is unfortunately eaten by multiop_bg_pause\n\tlocal n=$((${fidv[1]} + 1))\n\tlocal next_fid=\"${fidv[0]}:$(printf \"0x%x\" $n):${fidv[2]}\"\n\tif [ \"$FILESET\" == \"\" ]; then\n\t\t$CHECKSTAT -t file $MOUNT/.lustre/fid/$next_fid ||\n\t\t\terror \"FID is missing before close\"\n\tfi\n\tkill -USR1 $multi_pid\n\t# 1 second delay, so if mtime change we will see it\n\tsleep 1\n\tlocal mtime2=$(stat -c \"%Y\" $DIR/$tdir)\n\t[[ $mtime1 == $mtime2 ]] || error \"mtime has changed\"\n}\nrun_test 185 \"Volatile file support\"\n\nfunction create_check_volatile() {\n\tlocal idx=$1\n\tlocal tgt\n\n\t$MULTIOP $MOUNT/.lustre/fid V${idx}Fw4096_c >&/tmp/${tfile}.fid &\n\tlocal PID=$!\n\tsleep 1\n\tlocal FID=$(cat /tmp/${tfile}.fid)\n\t[ \"$FID\" == \"\" ] && error \"can't get FID for volatile\"\n\t$CHECKSTAT -t file $MOUNT/.lustre/fid/$FID || error \"can't stat $FID\"\n\ttgt=$($LFS getstripe -m $MOUNT/.lustre/fid/$FID)\n\t[ \"$tgt\" != \"$idx\" ] && error \"wrong MDS $tgt, expected $idx\"\n\tkill -USR1 $PID\n\twait\n\tsleep 1\n\tcancel_lru_locks mdc # flush opencache\n\t$CHECKSTAT -t file $MOUNT/.lustre/fid/$FID && error \"can stat $FID\"\n\treturn 0\n}\n\ntest_185a(){\n\t# LU-12516 - volatile creation via .lustre\n\t[[ $MDS1_VERSION -ge $(version_code 2.12.55) ]] ||\n\t\tskip \"Need MDS version at least 2.3.55\"\n\n\tcreate_check_volatile 0\n\t[ $MDSCOUNT -lt 2 ] && return 0\n\n\t# DNE case\n\tcreate_check_volatile 1\n\n\treturn 0\n}\nrun_test 185a \"Volatile file creation in .lustre/fid/\"\n\ntest_187a() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -lt $(version_code 2.3.0) ] &&\n\t\tskip \"Need MDS version at least 2.3.0\"\n\n\tlocal dir0=$DIR/$tdir/$testnum\n\tmkdir -p $dir0 || error \"creating dir $dir0\"\n\n\tlocal file=$dir0/file1\n\tdd if=/dev/urandom of=$file count=10 bs=1M conv=fsync\n\tlocal dv1=$($LFS data_version $file)\n\tdd if=/dev/urandom of=$file seek=10 count=1 bs=1M conv=fsync\n\tlocal dv2=$($LFS data_version $file)\n\t[[ $dv1 != $dv2 ]] ||\n\t\terror \"data version did not change on write $dv1 == $dv2\"\n\n\t# clean up\n\trm -f $file1\n}\nrun_test 187a \"Test data version change\"\n\ntest_187b() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -lt $(version_code 2.3.0) ] &&\n\t\tskip \"Need MDS version at least 2.3.0\"\n\n\tlocal dir0=$DIR/$tdir/$testnum\n\tmkdir -p $dir0 || error \"creating dir $dir0\"\n\n\tdeclare -a DV=$($MULTIOP $dir0 Vw1000xYw1000xY | cut -f3 -d\" \")\n\t[[ ${DV[0]} != ${DV[1]} ]] ||\n\t\terror \"data version did not change on write\"\\\n\t\t      \" ${DV[0]} == ${DV[1]}\"\n\n\t# clean up\n\trm -f $file1\n}\nrun_test 187b \"Test data version change on volatile file\"\n\ntest_200() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\n\tlocal POOL=${POOL:-cea1}\n\tlocal POOL_ROOT=${POOL_ROOT:-$DIR/d200.pools}\n\tlocal POOL_DIR_NAME=${POOL_DIR_NAME:-dir_tst}\n\t# Pool OST targets\n\tlocal first_ost=0\n\tlocal last_ost=$(($OSTCOUNT - 1))\n\tlocal ost_step=2\n\tlocal ost_list=$(seq $first_ost $ost_step $last_ost)\n\tlocal ost_range=\"$first_ost $last_ost $ost_step\"\n\tlocal test_path=$POOL_ROOT/$POOL_DIR_NAME\n\tlocal file_dir=$POOL_ROOT/file_tst\n\tlocal subdir=$test_path/subdir\n\tlocal rc=0\n\n\twhile : ; do\n\t\t# former test_200a test_200b\n\t\tpool_add $POOL\t\t\t\t|| { rc=$? ; break; }\n\t\tpool_add_targets  $POOL $ost_range\t|| { rc=$? ; break; }\n\t\t# former test_200c test_200d\n\t\tmkdir -p $test_path\n\t\tpool_set_dir      $POOL $test_path\t|| { rc=$? ; break; }\n\t\tpool_check_dir    $POOL $test_path\t|| { rc=$? ; break; }\n\t\tmkdir -p $subdir\n\t\tpool_check_dir    $POOL $subdir\t\t|| { rc=$? ; break; }\n\t\tpool_dir_rel_path $POOL $POOL_DIR_NAME $POOL_ROOT \\\n\t\t\t\t\t\t\t|| { rc=$? ; break; }\n\t\t# former test_200e test_200f\n\t\tlocal files=$((OSTCOUNT*3))\n\t\tpool_alloc_files  $POOL $test_path $files \"$ost_list\" \\\n\t\t\t\t\t\t\t|| { rc=$? ; break; }\n\t\tpool_create_files $POOL $file_dir $files \"$ost_list\" \\\n\t\t\t\t\t\t\t|| { rc=$? ; break; }\n\t\t# former test_200g test_200h\n\t\tpool_lfs_df $POOL\t\t\t|| { rc=$? ; break; }\n\t\tpool_file_rel_path $POOL $test_path\t|| { rc=$? ; break; }\n\n\t\t# former test_201a test_201b test_201c\n\t\tpool_remove_first_target $POOL\t\t|| { rc=$? ; break; }\n\n\t\tlocal f=$test_path/$tfile\n\t\tpool_remove_all_targets $POOL $f\t|| { rc=$? ; break; }\n\t\tpool_remove $POOL $f\t\t\t|| { rc=$? ; break; }\n\t\tbreak\n\tdone\n\n\tdestroy_test_pools\n\n\treturn $rc\n}\nrun_test 200 \"OST pools\"\n\n# usage: default_attr <count | size | offset>\ndefault_attr() {\n\t$LCTL get_param -n lov.$FSNAME-clilov-\\*.stripe${1}\n}\n\n# usage: check_default_stripe_attr\ncheck_default_stripe_attr() {\n\tACTUAL=$($LFS getstripe $* $DIR/$tdir)\n\tcase $1 in\n\t--stripe-count|-c)\n\t\t[ -n \"$2\" ] && EXPECTED=0 || EXPECTED=$(default_attr count);;\n\t--stripe-size|-S)\n\t\t[ -n \"$2\" ] && EXPECTED=0 || EXPECTED=$(default_attr size);;\n\t--stripe-index|-i)\n\t\tEXPECTED=-1;;\n\t*)\n\t\terror \"unknown getstripe attr '$1'\"\n\tesac\n\n\t[ $ACTUAL == $EXPECTED ] ||\n\t\terror \"$DIR/$tdir has $1 '$ACTUAL', not '$EXPECTED'\"\n}\n\ntest_204a() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-count 0 --stripe-size 0 --stripe-index -1 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count\n\tcheck_default_stripe_attr --stripe-size\n\tcheck_default_stripe_attr --stripe-index\n}\nrun_test 204a \"Print default stripe attributes\"\n\ntest_204b() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-count 1 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-size\n\tcheck_default_stripe_attr --stripe-index\n}\nrun_test 204b \"Print default stripe size and offset\"\n\ntest_204c() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-size 65536 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count\n\tcheck_default_stripe_attr --stripe-index\n}\nrun_test 204c \"Print default stripe count and offset\"\n\ntest_204d() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-index 0 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count\n\tcheck_default_stripe_attr --stripe-size\n}\nrun_test 204d \"Print default stripe count and size\"\n\ntest_204e() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -d $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count --raw\n\tcheck_default_stripe_attr --stripe-size --raw\n\tcheck_default_stripe_attr --stripe-index --raw\n}\nrun_test 204e \"Print raw stripe attributes\"\n\ntest_204f() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-count 1 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-size --raw\n\tcheck_default_stripe_attr --stripe-index --raw\n}\nrun_test 204f \"Print raw stripe size and offset\"\n\ntest_204g() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-size 65536 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count --raw\n\tcheck_default_stripe_attr --stripe-index --raw\n}\nrun_test 204g \"Print raw stripe count and offset\"\n\ntest_204h() {\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe --stripe-index 0 $DIR/$tdir\n\n\tcheck_default_stripe_attr --stripe-count --raw\n\tcheck_default_stripe_attr --stripe-size --raw\n}\nrun_test 204h \"Print raw stripe count and size\"\n\n# Figure out which job scheduler is being used, if any,\n# or use a fake one\nif [ -n \"$SLURM_JOB_ID\" ]; then # SLURM\n\tJOBENV=SLURM_JOB_ID\nelif [ -n \"$LSB_JOBID\" ]; then # Load Sharing Facility\n\tJOBENV=LSB_JOBID\nelif [ -n \"$PBS_JOBID\" ]; then # PBS/Maui/Moab\n\tJOBENV=PBS_JOBID\nelif [ -n \"$LOADL_STEPID\" ]; then # LoadLeveller\n\tJOBENV=LOADL_STEP_ID\nelif [ -n \"$JOB_ID\" ]; then # Sun Grid Engine\n\tJOBENV=JOB_ID\nelse\n\t$LCTL list_param jobid_name > /dev/null 2>&1\n\tif [ $? -eq 0 ]; then\n\t\tJOBENV=nodelocal\n\telse\n\t\tJOBENV=FAKE_JOBID\n\tfi\nfi\nLUSTRE_JOBID_SIZE=31 # plus NUL terminator\n\nverify_jobstats() {\n\tlocal cmd=($1)\n\tshift\n\tlocal facets=\"$@\"\n\n# we don't really need to clear the stats for this test to work, since each\n# command has a unique jobid, but it makes debugging easier if needed.\n#\tfor facet in $facets; do\n#\t\tlocal dev=$(convert_facet2label $facet)\n#\t\t# clear old jobstats\n#\t\tdo_facet $facet lctl set_param *.$dev.job_stats=\"clear\"\n#\tdone\n\n\t# use a new JobID for each test, or we might see an old one\n\t[ \"$JOBENV\" = \"FAKE_JOBID\" ] &&\n\t\tFAKE_JOBID=id.$testnum.$(basename ${cmd[0]}).$RANDOM\n\n\tJOBVAL=${!JOBENV:0:$LUSTRE_JOBID_SIZE}\n\n\t[ \"$JOBENV\" = \"nodelocal\" ] && {\n\t\tFAKE_JOBID=id.$testnum.%e.$RANDOM\n\t\t$LCTL set_param jobid_name=$FAKE_JOBID\n\t\tJOBVAL=${FAKE_JOBID/\\%e/$(basename ${cmd[0]})}\n\t}\n\n\tlog \"Test: ${cmd[*]}\"\n\tlog \"Using JobID environment $($LCTL get_param -n jobid_var)=$JOBVAL\"\n\n\tif [ $JOBENV = \"FAKE_JOBID\" ]; then\n\t\tFAKE_JOBID=$JOBVAL ${cmd[*]}\n\telse\n\t\t${cmd[*]}\n\tfi\n\n\t# all files are created on OST0000\n\tfor facet in $facets; do\n\t\tlocal stats=\"*.$(convert_facet2label $facet).job_stats\"\n\n\t\t# strip out libtool wrappers for in-tree executables\n\t\tif [ $(do_facet $facet lctl get_param $stats |\n\t\t       sed -e 's/\\.lt-/./' | grep -c $JOBVAL) -ne 1 ]; then\n\t\t\tdo_facet $facet lctl get_param $stats\n\t\t\terror \"No jobstats for $JOBVAL found on $facet::$stats\"\n\t\tfi\n\tdone\n}\n\njobstats_set() {\n\tlocal new_jobenv=$1\n\n\tset_persistent_param_and_check client \"jobid_var\" \\\n\t\t\"$FSNAME.sys.jobid_var\" $new_jobenv\n}\n\ntest_205a() { # Job stats\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.7.1) ]] ||\n\t\tskip \"Need MDS version with at least 2.7.1\"\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ -z \"$(lctl get_param -n mdc.*.connect_flags | grep jobstats)\" ] &&\n\t\tskip \"Server doesn't support jobstats\"\n\t[[ $JOBID_VAR = disable ]] && skip_env \"jobstats is disabled\"\n\n\tlocal old_jobenv=$($LCTL get_param -n jobid_var)\n\t[ $old_jobenv != $JOBENV ] && jobstats_set $JOBENV\n\n\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\tstack_trap \"do_facet mgs $PERM_CMD jobid_var=$old_jobenv\" EXIT\n\telse\n\t\tstack_trap \"do_facet mgs $PERM_CMD \\\n\t\t\t$FSNAME.sys.jobid_var=$old_jobenv\" EXIT\n\tfi\n\tchangelog_register\n\n\tlocal old_interval=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\t\tmdt.*.job_cleanup_interval | head -n 1)\n\tlocal new_interval=5\n\tdo_facet $SINGLEMDS \\\n\t\t$LCTL set_param mdt.*.job_cleanup_interval=$new_interval\n\tstack_trap \"do_facet $SINGLEMDS \\\n\t\t$LCTL set_param mdt.*.job_cleanup_interval=$old_interval\" EXIT\n\tlocal start=$SECONDS\n\n\tlocal cmd\n\t# mkdir\n\tcmd=\"mkdir $DIR/$tdir\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# rmdir\n\tcmd=\"rmdir $DIR/$tdir\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# mkdir on secondary MDT\n\tif [ $MDSCOUNT -gt 1 ]; then\n\t\tcmd=\"lfs mkdir -i 1 $DIR/$tdir.remote\"\n\t\tverify_jobstats \"$cmd\" \"mds2\"\n\tfi\n\t# mknod\n\tcmd=\"mknod $DIR/$tfile c 1 3\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# unlink\n\tcmd=\"rm -f $DIR/$tfile\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# create all files on OST0000 so verify_jobstats can find OST stats\n\t# open & close\n\tcmd=\"$LFS setstripe -i 0 -c 1 $DIR/$tfile\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# setattr\n\tcmd=\"touch $DIR/$tfile\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS ost1\"\n\t# write\n\tcmd=\"dd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=sync\"\n\tverify_jobstats \"$cmd\" \"ost1\"\n\t# read\n\tcancel_lru_locks osc\n\tcmd=\"dd if=$DIR/$tfile of=/dev/null bs=1M count=1 iflag=direct\"\n\tverify_jobstats \"$cmd\" \"ost1\"\n\t# truncate\n\tcmd=\"$TRUNCATE $DIR/$tfile 0\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS ost1\"\n\t# rename\n\tcmd=\"mv -f $DIR/$tfile $DIR/$tdir.rename\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t# jobstats expiry - sleep until old stats should be expired\n\tlocal left=$((new_interval + 5 - (SECONDS - start)))\n\t[ $left -ge 0 ] && wait_update_facet $SINGLEMDS \\\n\t\t\"lctl get_param *.*.job_stats | grep -c 'job_id.*mkdir'\" \\\n\t\t\t\"0\" $left\n\tcmd=\"mkdir $DIR/$tdir.expire\"\n\tverify_jobstats \"$cmd\" \"$SINGLEMDS\"\n\t[ $(do_facet $SINGLEMDS lctl get_param *.*.job_stats |\n\t    grep -c \"job_id.*mkdir\") -gt 1 ] && error \"old jobstats not expired\"\n\n\t# Ensure that jobid are present in changelog (if supported by MDS)\n\tif [ $MDS1_VERSION -ge $(version_code 2.6.52) ];then\n\t\tchangelog_dump | tail -10\n\t\tjobids=$(changelog_dump | tail -9 | grep -c \"j=\")\n\t\t[ $jobids -eq 9 ] ||\n\t\t\terror \"Wrong changelog jobid count $jobids != 9\"\n\n\t\t# LU-5862\n\t\tJOBENV=\"disable\"\n\t\tjobstats_set $JOBENV\n\t\ttouch $DIR/$tfile\n\t\tchangelog_dump | grep $tfile\n\t\tjobids=$(changelog_dump | grep $tfile | tail -1 | grep -c \"j=\")\n\t\t[ $jobids -eq 0 ] ||\n\t\t\terror \"Unexpected jobids when jobid_var=$JOBENV\"\n\tfi\n\n\tlctl set_param jobid_var=USER jobid_name=\"S.%j.%e.%u.%h.E\"\n\tJOBENV=\"JOBCOMPLEX\"\n\tJOBCOMPLEX=\"S.$USER.touch.$(id -u).$(hostname).E\"\n\n\tverify_jobstats \"touch $DIR/$tfile\" $SINGLEMDS\n}\nrun_test 205a \"Verify job stats\"\n\n# LU-13117, LU-13597\ntest_205b() {\n\tjob_stats=\"mdt.*.job_stats\"\n\t$LCTL set_param $job_stats=clear\n\t$LCTL set_param jobid_var=USER jobid_name=\"%e.%u\"\n\tenv -i USERTESTJOBSTATS=foolish touch $DIR/$tfile.1\n\tdo_facet $SINGLEMDS $LCTL get_param $job_stats |\n\t\tgrep \"job_id:.*foolish\" &&\n\t\t\terror \"Unexpected jobid found\"\n\tdo_facet $SINGLEMDS $LCTL get_param $job_stats |\n\t\tgrep \"open:.*min.*max.*sum\" ||\n\t\t\terror \"wrong job_stats format found\"\n}\nrun_test 205b \"Verify job stats jobid and output format\"\n\n# LU-13733\ntest_205c() {\n\t$LCTL set_param llite.*.stats=0\n\tdd if=/dev/zero of=$DIR/$tfile.1 bs=4k count=1\n\t$LCTL get_param llite.*.stats\n\t$LCTL get_param llite.*.stats | grep \\\n\t\t\"write_bytes *1 samples \\[bytes\\] 4096 4096 4096 16777216\" ||\n\t\t\terror \"wrong client stats format found\"\n}\nrun_test 205c \"Verify client stats format\"\n\n# LU-1480, LU-1773 and LU-1657\ntest_206() {\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c -1 $DIR/$tdir\n#define OBD_FAIL_LOV_INIT 0x1403\n\t$LCTL set_param fail_loc=0xa0001403\n\t$LCTL set_param fail_val=1\n\ttouch $DIR/$tdir/$tfile || true\n}\nrun_test 206 \"fail lov_init_raid0() doesn't lbug\"\n\ntest_207a() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=$((RANDOM%10+1))\n\tlocal fsz=`stat -c %s $DIR/$tfile`\n\tcancel_lru_locks mdc\n\n\t# do not return layout in getattr intent\n#define OBD_FAIL_MDS_NO_LL_GETATTR 0x170\n\t$LCTL set_param fail_loc=0x170\n\tlocal sz=`stat -c %s $DIR/$tfile`\n\n\t[ $fsz -eq $sz ] || error \"file size expected $fsz, actual $sz\"\n\n\trm -rf $DIR/$tfile\n}\nrun_test 207a \"can refresh layout at glimpse\"\n\ntest_207b() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=$((RANDOM%10+1))\n\tlocal cksum=`md5sum $DIR/$tfile`\n\tlocal fsz=`stat -c %s $DIR/$tfile`\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t# do not return layout in getattr intent\n#define OBD_FAIL_MDS_NO_LL_OPEN 0x171\n\t$LCTL set_param fail_loc=0x171\n\n\t# it will refresh layout after the file is opened but before read issues\n\techo checksum is \"$cksum\"\n\techo \"$cksum\" |md5sum -c --quiet || error \"file differs\"\n\n\trm -rf $DIR/$tfile\n}\nrun_test 207b \"can refresh layout at open\"\n\ntest_208() {\n\t# FIXME: in this test suite, only RD lease is used. This is okay\n\t# for now as only exclusive open is supported. After generic lease\n\t# is done, this test suite should be revised. - Jinshan\n\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.4.52) ]] ||\n\t\tskip \"Need MDS version at least 2.4.52\"\n\n\techo \"==== test 1: verify get lease work\"\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:eRE+eU || error \"get lease error\"\n\n\techo \"==== test 2: verify lease can be broken by upcoming open\"\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eR_E-eUc &\n\tlocal PID=$!\n\tsleep 1\n\n\t$MULTIOP $DIR/$tfile oO_RDONLY:c\n\tkill -USR1 $PID && wait $PID || error \"break lease error\"\n\n\techo \"==== test 3: verify lease can't be granted if an open already exists\"\n\t$MULTIOP $DIR/$tfile oO_RDONLY:_c &\n\tlocal PID=$!\n\tsleep 1\n\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eReUc && error \"apply lease should fail\"\n\tkill -USR1 $PID && wait $PID || error \"open file error\"\n\n\techo \"==== test 4: lease can sustain over recovery\"\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eR_E+eUc &\n\tPID=$!\n\tsleep 1\n\n\tfail mds1\n\n\tkill -USR1 $PID && wait $PID || error \"lease broken over recovery\"\n\n\techo \"==== test 5: lease broken can't be regained by replay\"\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eR_E-eUc &\n\tPID=$!\n\tsleep 1\n\n\t# open file to break lease and then recovery\n\t$MULTIOP $DIR/$tfile oO_RDWR:c || error \"open file error\"\n\tfail mds1\n\n\tkill -USR1 $PID && wait $PID || error \"lease not broken over recovery\"\n\n\trm -f $DIR/$tfile\n}\nrun_test 208 \"Exclusive open\"\n\ntest_209() {\n\t[ -z \"$(lctl get_param -n mdc.*.connect_flags | grep disp_stripe)\" ] &&\n\t\tskip_env \"must have disp_stripe\"\n\n\ttouch $DIR/$tfile\n\tsync; sleep 5; sync;\n\n\techo 3 > /proc/sys/vm/drop_caches\n\t[ -f /sys/kernel/slab/ptlrpc_cache/shrink ] &&\n\t\techo 1 > /sys/kernel/slab/ptlrpc_cache/shrink\n\treq_before=$(awk '/ptlrpc_cache / { print $2 }' /proc/slabinfo)\n\n\t# open/close 500 times\n\tfor i in $(seq 500); do\n\t\tcat $DIR/$tfile\n\tdone\n\n\techo 3 > /proc/sys/vm/drop_caches\n\t[ -f /sys/kernel/slab/ptlrpc_cache/shrink ] &&\n\t\techo 1 > /sys/kernel/slab/ptlrpc_cache/shrink\n\treq_after=$(awk '/ptlrpc_cache / { print $2 }' /proc/slabinfo)\n\n\techo \"before: $req_before, after: $req_after\"\n\t[ $((req_after - req_before)) -ge 300 ] &&\n\t\terror \"open/close requests are not freed\"\n\treturn 0\n}\nrun_test 209 \"read-only open/close requests should be freed promptly\"\n\ntest_210() {\n\tlocal pid\n\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:eW_E+eUc &\n\tpid=$!\n\tsleep 1\n\n\t$LFS getstripe $DIR/$tfile\n\tkill -USR1 $pid\n\twait $pid || error \"multiop failed\"\n\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eR_E+eUc &\n\tpid=$!\n\tsleep 1\n\n\t$LFS getstripe $DIR/$tfile\n\tkill -USR1 $pid\n\twait $pid || error \"multiop failed\"\n}\nrun_test 210 \"lfs getstripe does not break leases\"\n\ntest_212() {\n\tsize=`date +%s`\n\tsize=$((size % 8192 + 1))\n\tdd if=/dev/urandom of=$DIR/f212 bs=1k count=$size\n\tsendfile $DIR/f212 $DIR/f212.xyz || error \"sendfile wrong\"\n\trm -f $DIR/f212 $DIR/f212.xyz\n}\nrun_test 212 \"Sendfile test ============================================\"\n\ntest_213() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=4\n\tcancel_lru_locks osc\n\tlctl set_param fail_loc=0x8000040f\n\t# generate a read lock\n\tcat $DIR/$tfile > /dev/null\n\t# write to the file, it will try to cancel the above read lock.\n\tcat /etc/hosts >> $DIR/$tfile\n}\nrun_test 213 \"OSC lock completion and cancel race don't crash - bug 18829\"\n\ntest_214() { # for bug 20133\n\tmkdir -p $DIR/$tdir/d214c || error \"mkdir $DIR/$tdir/d214c failed\"\n\tfor (( i=0; i < 340; i++ )) ; do\n\t\ttouch $DIR/$tdir/d214c/a$i\n\tdone\n\n\tls -l $DIR/$tdir || error \"ls -l $DIR/d214p failed\"\n\tmv $DIR/$tdir/d214c $DIR/ || error \"mv $DIR/d214p/d214c $DIR/ failed\"\n\tls $DIR/d214c || error \"ls $DIR/d214c failed\"\n\trm -rf $DIR/$tdir || error \"rm -rf $DIR/d214* failed\"\n\trm -rf $DIR/d214* || error \"rm -rf $DIR/d214* failed\"\n}\nrun_test 214 \"hash-indexed directory test - bug 20133\"\n\n# having \"abc\" as 1st arg, creates $TMP/lnet_abc.out and $TMP/lnet_abc.sys\ncreate_lnet_proc_files() {\n\tlctl get_param -n $1 >$TMP/lnet_$1.sys || error \"cannot read lnet.$1\"\n}\n\n# counterpart of create_lnet_proc_files\nremove_lnet_proc_files() {\n\trm -f $TMP/lnet_$1.sys\n}\n\n# uses 1st arg as trailing part of filename, 2nd arg as description for reports,\n# 3rd arg as regexp for body\ncheck_lnet_proc_stats() {\n\tlocal l=$(cat \"$TMP/lnet_$1\" |wc -l)\n\t[ $l = 1 ] || (cat \"$TMP/lnet_$1\" && error \"$2 is not of 1 line: $l\")\n\n\tgrep -E \"$3\" \"$TMP/lnet_$1\" || (cat \"$TMP/lnet_$1\" && error \"$2 misformatted\")\n}\n\n# uses 1st arg as trailing part of filename, 2nd arg as description for reports,\n# 3rd arg as regexp for body, 4th arg as regexp for 1st line, 5th arg is\n# optional and can be regexp for 2nd line (lnet.routes case)\ncheck_lnet_proc_entry() {\n\tlocal blp=2          # blp stands for 'position of 1st line of body'\n\t[ -z \"$5\" ] || blp=3 # lnet.routes case\n\n\tlocal l=$(cat \"$TMP/lnet_$1\" |wc -l)\n\t# subtracting one from $blp because the body can be empty\n\t[ \"$l\" -ge \"$(($blp - 1))\" ] || (cat \"$TMP/lnet_$1\" && error \"$2 is too short: $l\")\n\n\tsed -n '1 p' \"$TMP/lnet_$1\" |grep -E \"$4\" >/dev/null ||\n\t\t(cat \"$TMP/lnet_$1\" && error \"1st line of $2 misformatted\")\n\n\t[ \"$5\" = \"\" ] || sed -n '2 p' \"$TMP/lnet_$1\" |grep -E \"$5\" >/dev/null ||\n\t\t(cat \"$TMP/lnet_$1\" && error \"2nd line of $2 misformatted\")\n\n\t# bail out if any unexpected line happened\n\tsed -n \"$blp p\" \"$TMP/lnet_$1\" | grep -Ev \"$3\"\n\t[ \"$?\" != 0 ] || error \"$2 misformatted\"\n}\n\ntest_215() { # for bugs 18102, 21079, 21517\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal N='(0|[1-9][0-9]*)'       # non-negative numeric\n\tlocal P='[1-9][0-9]*'           # positive numeric\n\tlocal I='(0|-?[1-9][0-9]*|NA)'  # any numeric (0 | >0 | <0) or NA if no value\n\tlocal NET='[a-z][a-z0-9]*'      # LNET net like o2ib2\n\tlocal ADDR='[0-9.]+'            # LNET addr like 10.0.0.1\n\tlocal NID=\"$ADDR@$NET\"          # LNET nid like 10.0.0.1@o2ib2\n\n\tlocal L1 # regexp for 1st line\n\tlocal L2 # regexp for 2nd line (optional)\n\tlocal BR # regexp for the rest (body)\n\n\t# lnet.stats should look as 11 space-separated non-negative numerics\n\tBR=\"^$N $N $N $N $N $N $N $N $N $N $N$\"\n\tcreate_lnet_proc_files \"stats\"\n\tcheck_lnet_proc_stats \"stats.sys\" \"lnet.stats\" \"$BR\"\n\tremove_lnet_proc_files \"stats\"\n\n\t# lnet.routes should look like this:\n\t# Routing disabled/enabled\n\t# net hops priority state router\n\t# where net is a string like tcp0, hops > 0, priority >= 0,\n\t# state is up/down,\n\t# router is a string like 192.168.1.1@tcp2\n\tL1=\"^Routing (disabled|enabled)$\"\n\tL2=\"^net +hops +priority +state +router$\"\n\tBR=\"^$NET +$N +(0|1) +(up|down) +$NID$\"\n\tcreate_lnet_proc_files \"routes\"\n\tcheck_lnet_proc_entry \"routes.sys\" \"lnet.routes\" \"$BR\" \"$L1\" \"$L2\"\n\tremove_lnet_proc_files \"routes\"\n\n\t# lnet.routers should look like this:\n\t# ref rtr_ref alive_cnt state last_ping ping_sent deadline down_ni router\n\t# where ref > 0, rtr_ref > 0, alive_cnt >= 0, state is up/down,\n\t# last_ping >= 0, ping_sent is boolean (0/1), deadline and down_ni are\n\t# numeric (0 or >0 or <0), router is a string like 192.168.1.1@tcp2\n\tL1=\"^ref +rtr_ref +alive +router$\"\n\tBR=\"^$P +$P +(up|down) +$NID$\"\n\tcreate_lnet_proc_files \"routers\"\n\tcheck_lnet_proc_entry \"routers.sys\" \"lnet.routers\" \"$BR\" \"$L1\"\n\tremove_lnet_proc_files \"routers\"\n\n\t# lnet.peers should look like this:\n\t# nid refs state last max rtr min tx min queue\n\t# where nid is a string like 192.168.1.1@tcp2, refs > 0,\n\t# state is up/down/NA, max >= 0. last, rtr, min, tx, min are\n\t# numeric (0 or >0 or <0), queue >= 0.\n\tL1=\"^nid +refs +state +last +max +rtr +min +tx +min +queue$\"\n\tBR=\"^$NID +$P +(up|down|NA) +$I +$N +$I +$I +$I +$I +$N$\"\n\tcreate_lnet_proc_files \"peers\"\n\tcheck_lnet_proc_entry \"peers.sys\" \"lnet.peers\" \"$BR\" \"$L1\"\n\tremove_lnet_proc_files \"peers\"\n\n\t# lnet.buffers  should look like this:\n\t# pages count credits min\n\t# where pages >=0, count >=0, credits and min are numeric (0 or >0 or <0)\n\tL1=\"^pages +count +credits +min$\"\n\tBR=\"^ +$N +$N +$I +$I$\"\n\tcreate_lnet_proc_files \"buffers\"\n\tcheck_lnet_proc_entry \"buffers.sys\" \"lnet.buffers\" \"$BR\" \"$L1\"\n\tremove_lnet_proc_files \"buffers\"\n\n\t# lnet.nis should look like this:\n\t# nid status alive refs peer rtr max tx min\n\t# where nid is a string like 192.168.1.1@tcp2, status is up/down,\n\t# alive is numeric (0 or >0 or <0), refs >= 0, peer >= 0,\n\t# rtr >= 0, max >=0, tx and min are numeric (0 or >0 or <0).\n\tL1=\"^nid +status +alive +refs +peer +rtr +max +tx +min$\"\n\tBR=\"^$NID +(up|down) +$I +$N +$N +$N +$N +$I +$I$\"\n\tcreate_lnet_proc_files \"nis\"\n\tcheck_lnet_proc_entry \"nis.sys\" \"lnet.nis\" \"$BR\" \"$L1\"\n\tremove_lnet_proc_files \"nis\"\n\n\t# can we successfully write to lnet.stats?\n\tlctl set_param -n stats=0 || error \"cannot write to lnet.stats\"\n}\nrun_test 215 \"lnet exists and has proper content - bugs 18102, 21079, 21517\"\n\ntest_216() { # bug 20317\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal node\n\tlocal facets=$(get_facets OST)\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params client \"osc.*.contention_seconds\" > $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.max_nolock_bytes\" >> $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.contended_locks\" >> $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.contention_seconds\" >> $p\n\tclear_stats osc.*.osc_stats\n\n\t# agressive lockless i/o settings\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\"lctl set_param -n ldlm.namespaces.*.max_nolock_bytes=2000000 \\\n\t\t\tldlm.namespaces.filter-*.contended_locks=0 \\\n\t\t\tldlm.namespaces.filter-*.contention_seconds=60\"\n\tlctl set_param -n osc.*.contention_seconds=60\n\n\t$DIRECTIO write $DIR/$tfile 0 10 4096\n\t$CHECKSTAT -s 40960 $DIR/$tfile\n\n\t# disable lockless i/o\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\"lctl set_param -n ldlm.namespaces.filter-*.max_nolock_bytes=0 \\\n\t\t\tldlm.namespaces.filter-*.contended_locks=32 \\\n\t\t\tldlm.namespaces.filter-*.contention_seconds=0\"\n\tlctl set_param -n osc.*.contention_seconds=0\n\tclear_stats osc.*.osc_stats\n\n\tdd if=/dev/zero of=$DIR/$tfile count=0\n\t$CHECKSTAT -s 0 $DIR/$tfile\n\n\trestore_lustre_params <$p\n\trm -f $p\n\trm $DIR/$tfile\n}\nrun_test 216 \"check lockless direct write updates file size and kms correctly\"\n\ntest_217() { # bug 22430\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal node\n\tlocal nid\n\n\tfor node in $(nodes_list); do\n\t\tnid=$(host_nids_address $node $NETTYPE)\n\t\tif [[ $nid = *-* ]] ; then\n\t\t\techo \"lctl ping $(h2nettype $nid)\"\n\t\t\tlctl ping $(h2nettype $nid)\n\t\telse\n\t\t\techo \"skipping $node (no hyphen detected)\"\n\t\tfi\n\tdone\n}\nrun_test 217 \"check lctl ping for hostnames with hiphen ('-')\"\n\ntest_218() {\n       # do directio so as not to populate the page cache\n       log \"creating a 10 Mb file\"\n       $MULTIOP $DIR/$tfile oO_CREAT:O_DIRECT:O_RDWR:w$((10*1048576))c || error \"multiop failed while creating a file\"\n       log \"starting reads\"\n       dd if=$DIR/$tfile of=/dev/null bs=4096 &\n       log \"truncating the file\"\n       $MULTIOP $DIR/$tfile oO_TRUNC:c || error \"multiop failed while truncating the file\"\n       log \"killing dd\"\n       kill %+ || true # reads might have finished\n       echo \"wait until dd is finished\"\n       wait\n       log \"removing the temporary file\"\n       rm -rf $DIR/$tfile || error \"tmp file removal failed\"\n}\nrun_test 218 \"parallel read and truncate should not deadlock\"\n\ntest_219() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t# write one partial page\n\tdd if=/dev/zero of=$DIR/$tfile bs=1024 count=1\n\t# set no grant so vvp_io_commit_write will do sync write\n\t$LCTL set_param fail_loc=0x411\n\t# write a full page at the end of file\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 seek=1 conv=notrunc\n\n\t$LCTL set_param fail_loc=0\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 seek=3\n\t$LCTL set_param fail_loc=0x411\n\tdd if=/dev/zero of=$DIR/$tfile bs=1024 count=1 seek=2 conv=notrunc\n\n\t# LU-4201\n\tdd if=/dev/zero of=$DIR/$tfile-2 bs=1024 count=1\n\t$CHECKSTAT -s 1024 $DIR/$tfile-2 || error \"checkstat wrong size\"\n}\nrun_test 219 \"LU-394: Write partial won't cause uncontiguous pages vec at LND\"\n\ntest_220() { #LU-325\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\n\tlocal OSTIDX=0\n\n\t# create on MDT0000 so the last_id and next_id are correct\n\tmkdir $DIR/$tdir\n\tlocal OST=$($LFS df $DIR | awk '/OST:'$OSTIDX'/ { print $1 }')\n\tOST=${OST%_UUID}\n\n\t# on the mdt's osc\n\tlocal mdtosc_proc1=$(get_mdtosc_proc_path $SINGLEMDS $OST)\n\tlocal last_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_last_id)\n\tlocal next_id=$(do_facet $SINGLEMDS lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_next_id)\n\n\t$LFS df -i\n\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param fail_val=-1\n\t#define OBD_FAIL_OST_ENOINO              0x229\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param fail_loc=0x229\n\tcreate_pool $FSNAME.$TESTNAME || return 1\n\tdo_facet mgs $LCTL pool_add $FSNAME.$TESTNAME $OST || return 2\n\n\t$LFS setstripe $DIR/$tdir -i $OSTIDX -c 1 -p $FSNAME.$TESTNAME\n\n\tMDSOBJS=$((last_id - next_id))\n\techo \"preallocated objects on MDS is $MDSOBJS\" \"($last_id - $next_id)\"\n\n\tblocks=$($LFS df $MOUNT | awk '($1 == '$OSTIDX') { print $4 }')\n\techo \"OST still has $count kbytes free\"\n\n\techo \"create $MDSOBJS files @next_id...\"\n\tcreatemany -o $DIR/$tdir/f $MDSOBJS || return 3\n\n\tlocal last_id2=$(do_facet mds${MDSIDX} lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_last_id)\n\tlocal next_id2=$(do_facet mds${MDSIDX} lctl get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_next_id)\n\n\techo \"after creation, last_id=$last_id2, next_id=$next_id2\"\n\t$LFS df -i\n\n\techo \"cleanup...\"\n\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param fail_val=0\n\tdo_facet ost$((OSTIDX + 1)) lctl set_param fail_loc=0\n\n\tdo_facet mgs $LCTL pool_remove $FSNAME.$TESTNAME $OST ||\n\t\terror \"$LCTL pool_remove $FSNAME.$TESTNAME $OST failed\"\n\tdo_facet mgs $LCTL pool_destroy $FSNAME.$TESTNAME ||\n\t\terror \"$LCTL pool_destroy $FSNAME.$TESTNAME failed\"\n\techo \"unlink $MDSOBJS files @$next_id...\"\n\tunlinkmany $DIR/$tdir/f $MDSOBJS || error \"unlinkmany failed\"\n}\nrun_test 220 \"preallocated MDS objects still used if ENOSPC from OST\"\n\ntest_221() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdd if=`which date` of=$MOUNT/date oflag=sync\n\tchmod +x $MOUNT/date\n\n\t#define OBD_FAIL_LLITE_FAULT_TRUNC_RACE  0x1401\n\t$LCTL set_param fail_loc=0x80001401\n\n\t$MOUNT/date > /dev/null\n\trm -f $MOUNT/date\n}\nrun_test 221 \"make sure fault and truncate race to not cause OOM\"\n\ntest_222a () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/$tfile 10\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_LDLM_AGL_DELAY           0x31a\n\t$LCTL set_param fail_loc=0x31a\n\tls -l $DIR/$tdir > /dev/null || error \"AGL for ls failed\"\n\t$LCTL set_param fail_loc=0\n\trm -r $DIR/$tdir\n}\nrun_test 222a \"AGL for ls should not trigger CLIO lock failure\"\n\ntest_222b () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/$tfile 10\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_LDLM_AGL_DELAY           0x31a\n\t$LCTL set_param fail_loc=0x31a\n\trm -r $DIR/$tdir || error \"AGL for rmdir failed\"\n\t$LCTL set_param fail_loc=0\n}\nrun_test 222b \"AGL for rmdir should not trigger CLIO lock failure\"\n\ntest_223 () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/$tfile 10\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_LDLM_AGL_NOLOCK          0x31b\n\t$LCTL set_param fail_loc=0x31b\n\tls -l $DIR/$tdir > /dev/null || error \"reenqueue failed\"\n\t$LCTL set_param fail_loc=0\n\trm -r $DIR/$tdir\n}\nrun_test 223 \"osc reenqueue if without AGL lock granted =======================\"\n\ntest_224a() { # LU-1039, MRP-303\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB   0x508\n\t$LCTL set_param fail_loc=0x508\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1 conv=fsync\n\t$LCTL set_param fail_loc=0\n\tdf $DIR\n}\nrun_test 224a \"Don't panic on bulk IO failure\"\n\ntest_224b() { # LU-1039, MRP-303\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=4096 count=1\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB2   0x515\n\t$LCTL set_param fail_loc=0x515\n\tdd of=/dev/null if=$DIR/$tfile bs=4096 count=1\n\t$LCTL set_param fail_loc=0\n\tdf $DIR\n}\nrun_test 224b \"Don't panic on bulk IO failure\"\n\ntest_224c() { # LU-6441\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_writethrough $p\n\tset_cache writethrough on\n\n\tlocal pages_per_rpc=$($LCTL get_param osc.*.max_pages_per_rpc)\n\tlocal at_max=$($LCTL get_param -n at_max)\n\tlocal timeout=$($LCTL get_param -n timeout)\n\tlocal test_at=\"at_max\"\n\tlocal param_at=\"$FSNAME.sys.at_max\"\n\tlocal test_timeout=\"timeout\"\n\tlocal param_timeout=\"$FSNAME.sys.timeout\"\n\n\t$LCTL set_param -n osc.*.max_pages_per_rpc=1024\n\n\tset_persistent_param_and_check client \"$test_at\" \"$param_at\" 0\n\tset_persistent_param_and_check client \"$test_timeout\" \"$param_timeout\" 5\n\n\t#define OBD_FAIL_PTLRPC_CLIENT_BULK_CB3 0x520\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x520\"\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\tdd if=/dev/zero of=$DIR/$tfile bs=8MB count=1\n\tsync\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0\"\n\n\tset_persistent_param_and_check client \"$test_at\" \"$param_at\" $at_max\n\tset_persistent_param_and_check client \"$test_timeout\" \"$param_timeout\" \\\n\t\t$timeout\n\n\t$LCTL set_param -n $pages_per_rpc\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 224c \"Don't hang if one of md lost during large bulk RPC\"\n\nMDSSURVEY=${MDSSURVEY:-$(which mds-survey 2>/dev/null || true)}\ntest_225a () {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tif [ -z ${MDSSURVEY} ]; then\n\t\tskip_env \"mds-survey not found\"\n\tfi\n\t[ $MDS1_VERSION -ge $(version_code 2.2.51) ] ||\n\t\tskip \"Need MDS version at least 2.2.51\"\n\n\tlocal mds=$(facet_host $SINGLEMDS)\n\tlocal target=$(do_nodes $mds 'lctl dl' |\n\t\t       awk '{ if ($2 == \"UP\" && $3 == \"mdt\") { print $4 }}')\n\n\tlocal cmd1=\"file_count=1000 thrhi=4\"\n\tlocal cmd2=\"dir_count=2 layer=mdd stripe_count=0\"\n\tlocal cmd3=\"rslt_loc=${TMP} targets=\\\"$mds:$target\\\" $MDSSURVEY\"\n\tlocal cmd=\"$cmd1 $cmd2 $cmd3\"\n\n\trm -f ${TMP}/mds_survey*\n\techo + $cmd\n\teval $cmd || error \"mds-survey with zero-stripe failed\"\n\tcat ${TMP}/mds_survey*\n\trm -f ${TMP}/mds_survey*\n}\nrun_test 225a \"Metadata survey sanity with zero-stripe\"\n\ntest_225b () {\n\tif [ -z ${MDSSURVEY} ]; then\n\t\tskip_env \"mds-survey not found\"\n\tfi\n\t[ $MDS1_VERSION -ge $(version_code 2.2.51) ] ||\n\t\tskip \"Need MDS version at least 2.2.51\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tif [ $($LCTL dl | grep -c osc) -eq 0 ]; then\n\t\tskip_env \"Need to mount OST to test\"\n\tfi\n\n\tlocal mds=$(facet_host $SINGLEMDS)\n\tlocal target=$(do_nodes $mds 'lctl dl' |\n\t\t       awk '{ if ($2 == \"UP\" && $3 == \"mdt\") { print $4 }}')\n\n\tlocal cmd1=\"file_count=1000 thrhi=4\"\n\tlocal cmd2=\"dir_count=2 layer=mdd stripe_count=1\"\n\tlocal cmd3=\"rslt_loc=${TMP} targets=\\\"$mds:$target\\\" $MDSSURVEY\"\n\tlocal cmd=\"$cmd1 $cmd2 $cmd3\"\n\n\trm -f ${TMP}/mds_survey*\n\techo + $cmd\n\teval $cmd || error \"mds-survey with stripe_count failed\"\n\tcat ${TMP}/mds_survey*\n\trm -f ${TMP}/mds_survey*\n}\nrun_test 225b \"Metadata survey sanity with stripe_count = 1\"\n\nmcreate_path2fid () {\n\tlocal mode=$1\n\tlocal major=$2\n\tlocal minor=$3\n\tlocal name=$4\n\tlocal desc=$5\n\tlocal path=$DIR/$tdir/$name\n\tlocal fid\n\tlocal rc\n\tlocal fid_path\n\n\t$MCREATE --mode=$1 --major=$2 --minor=$3 $path ||\n\t\terror \"cannot create $desc\"\n\n\tfid=$($LFS path2fid $path | tr -d '[' | tr -d ']')\n\trc=$?\n\t[ $rc -ne 0 ] && error \"cannot get fid of a $desc\"\n\n\tfid_path=$($LFS fid2path $MOUNT $fid)\n\trc=$?\n\t[ $rc -ne 0 ] && error \"cannot get path of $desc by $DIR $path $fid\"\n\n\t[ \"$path\" == \"$fid_path\" ] ||\n\t\terror \"fid2path returned $fid_path, expected $path\"\n\n\techo \"pass with $path and $fid\"\n}\n\ntest_226a () {\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\tmcreate_path2fid 0010666 0 0 fifo \"FIFO\"\n\tmcreate_path2fid 0020666 1 3 null \"character special file (null)\"\n\tmcreate_path2fid 0020666 1 255 none \"character special file (no device)\"\n\tmcreate_path2fid 0040666 0 0 dir \"directory\"\n\tmcreate_path2fid 0060666 7 0 loop0 \"block special file (loop)\"\n\tmcreate_path2fid 0100666 0 0 file \"regular file\"\n\tmcreate_path2fid 0120666 0 0 link \"symbolic link\"\n\tmcreate_path2fid 0140666 0 0 sock \"socket\"\n}\nrun_test 226a \"call path2fid and fid2path on files of all type\"\n\ntest_226b () {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal MDTIDX=1\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\t$LFS setdirstripe -i $MDTIDX $DIR/$tdir/remote_dir ||\n\t\terror \"create remote directory failed\"\n\tmcreate_path2fid 0010666 0 0 \"remote_dir/fifo\" \"FIFO\"\n\tmcreate_path2fid 0020666 1 3 \"remote_dir/null\" \\\n\t\t\t\t\"character special file (null)\"\n\tmcreate_path2fid 0020666 1 255 \"remote_dir/none\" \\\n\t\t\t\t\"character special file (no device)\"\n\tmcreate_path2fid 0040666 0 0 \"remote_dir/dir\" \"directory\"\n\tmcreate_path2fid 0060666 7 0 \"remote_dir/loop0\" \\\n\t\t\t\t\"block special file (loop)\"\n\tmcreate_path2fid 0100666 0 0 \"remote_dir/file\" \"regular file\"\n\tmcreate_path2fid 0120666 0 0 \"remote_dir/link\" \"symbolic link\"\n\tmcreate_path2fid 0140666 0 0 \"remote_dir/sock\" \"socket\"\n}\nrun_test 226b \"call path2fid and fid2path on files of all type under remote dir\"\n\ntest_226c () {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.13.55) ]] ||\n\t\tskip \"Need MDS version at least 2.13.55\"\n\n\tlocal submnt=/mnt/submnt\n\tlocal srcfile=/etc/passwd\n\tlocal dstfile=$submnt/passwd\n\tlocal path\n\tlocal fid\n\n\trm -rf $DIR/$tdir\n\trm -rf $submnt\n\t$LFS setdirstripe -c -1 -i 1 $DIR/$tdir ||\n\t\terror \"create remote directory failed\"\n\tmkdir -p $submnt || error \"create $submnt failed\"\n\t$MOUNT_CMD $MGSNID:/$FSNAME/$tdir $submnt ||\n\t\terror \"mount $submnt failed\"\n\tstack_trap \"umount $submnt\" EXIT\n\n\tcp $srcfile $dstfile\n\tfid=$($LFS path2fid $dstfile)\n\tpath=$($LFS fid2path $submnt \"$fid\")\n\t[ \"$path\" = \"$dstfile\" ] ||\n\t\terror \"fid2path $submnt $fid failed ($path != $dstfile)\"\n}\nrun_test 226c \"call path2fid and fid2path under remote dir with subdir mount\"\n\n# LU-1299 Executing or running ldd on a truncated executable does not\n# cause an out-of-memory condition.\ntest_227() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ -z \"$(which ldd)\" ] && skip_env \"should have ldd tool\"\n\n\tdd if=$(which date) of=$MOUNT/date bs=1k count=1\n\tchmod +x $MOUNT/date\n\n\t$MOUNT/date > /dev/null\n\tldd $MOUNT/date > /dev/null\n\trm -f $MOUNT/date\n}\nrun_test 227 \"running truncated executable does not cause OOM\"\n\n# LU-1512 try to reuse idle OI blocks\ntest_228a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\n\tlocal MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})\n\tlocal myDIR=$DIR/$tdir\n\n\tmkdir -p $myDIR\n\t#define OBD_FAIL_SEQ_EXHAUST             0x1002\n\t$LCTL set_param fail_loc=0x80001002\n\tcreatemany -o $myDIR/t- 10000\n\t$LCTL set_param fail_loc=0\n\t# The guard is current the largest FID holder\n\ttouch $myDIR/guard\n\tlocal SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |\n\t\t    tr -d '[')\n\tlocal IDX=$(($SEQ % 64))\n\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk1=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t# Remove old files, some OI blocks will become idle.\n\tunlinkmany $myDIR/t- 10000\n\t# Create new files, idle OI blocks should be reused.\n\tcreatemany -o $myDIR/t- 2000\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk2=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t[ $blk1 == $blk2 ] || error \"old blk1=$blk1, new blk2=$blk2, unmatched!\"\n}\nrun_test 228a \"try to reuse idle OI blocks\"\n\ntest_228b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\n\tlocal MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})\n\tlocal myDIR=$DIR/$tdir\n\n\tmkdir -p $myDIR\n\t#define OBD_FAIL_SEQ_EXHAUST             0x1002\n\t$LCTL set_param fail_loc=0x80001002\n\tcreatemany -o $myDIR/t- 10000\n\t$LCTL set_param fail_loc=0\n\t# The guard is current the largest FID holder\n\ttouch $myDIR/guard\n\tlocal SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |\n\t\t    tr -d '[')\n\tlocal IDX=$(($SEQ % 64))\n\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk1=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t# Remove old files, some OI blocks will become idle.\n\tunlinkmany $myDIR/t- 10000\n\n\t# stop the MDT\n\tstop $SINGLEMDS || error \"Fail to stop MDT.\"\n\t# remount the MDT\n\tstart $SINGLEMDS $MDT_DEV $MDS_MOUNT_OPTS || error \"Fail to start MDT.\"\n\n\tdf $MOUNT || error \"Fail to df.\"\n\t# Create new files, idle OI blocks should be reused.\n\tcreatemany -o $myDIR/t- 2000\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk2=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t[ $blk1 == $blk2 ] || error \"old blk1=$blk1, new blk2=$blk2, unmatched!\"\n}\nrun_test 228b \"idle OI blocks can be reused after MDT restart\"\n\n#LU-1881\ntest_228c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\n\tlocal MDT_DEV=$(mdsdevname ${SINGLEMDS//mds/})\n\tlocal myDIR=$DIR/$tdir\n\n\tmkdir -p $myDIR\n\t#define OBD_FAIL_SEQ_EXHAUST             0x1002\n\t$LCTL set_param fail_loc=0x80001002\n\t# 20000 files can guarantee there are index nodes in the OI file\n\tcreatemany -o $myDIR/t- 20000\n\t$LCTL set_param fail_loc=0\n\t# The guard is current the largest FID holder\n\ttouch $myDIR/guard\n\tlocal SEQ=$($LFS path2fid $myDIR/guard | awk -F ':' '{print $1}' |\n\t\t    tr -d '[')\n\tlocal IDX=$(($SEQ % 64))\n\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk1=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t# Remove old files, some OI blocks will become idle.\n\tunlinkmany $myDIR/t- 20000\n\trm -f $myDIR/guard\n\t# The OI file should become empty now\n\n\t# Create new files, idle OI blocks should be reused.\n\tcreatemany -o $myDIR/t- 2000\n\tdo_facet $SINGLEMDS sync\n\t# Make sure journal flushed.\n\tsleep 6\n\tlocal blk2=$(do_facet $SINGLEMDS \\\n\t\t     \"$DEBUGFS -c -R \\\\\\\"stat oi.16.${IDX}\\\\\\\" $MDT_DEV\" |\n\t\t     grep Blockcount | awk '{print $4}')\n\n\t[ $blk1 == $blk2 ] || error \"old blk1=$blk1, new blk2=$blk2, unmatched!\"\n}\nrun_test 228c \"NOT shrink the last entry in OI index node to recycle idle leaf\"\n\ntest_229() { # LU-2482, LU-3448\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.4.53) ] &&\n\t\tskip \"No HSM $(lustre_build_version $SINGLEMDS) MDS < 2.4.53\"\n\n\trm -f $DIR/$tfile\n\n\t# Create a file with a released layout and stripe count 2.\n\t$MULTIOP $DIR/$tfile H2c ||\n\t\terror \"failed to create file with released layout\"\n\n\t$LFS getstripe -v $DIR/$tfile\n\n\tlocal pattern=$($LFS getstripe -L $DIR/$tfile)\n\t[ X\"$pattern\" = X\"released\" ] || error \"pattern error ($pattern)\"\n\n\tlocal stripe_count=$($LFS getstripe -c $DIR/$tfile) ||\n\t\terror \"getstripe\"\n\t[ $stripe_count -eq 2 ] || error \"stripe count not 2 ($stripe_count)\"\n\tstat $DIR/$tfile || error \"failed to stat released file\"\n\n\tchown $RUNAS_ID $DIR/$tfile ||\n\t\terror \"chown $RUNAS_ID $DIR/$tfile failed\"\n\n\tchgrp $RUNAS_ID $DIR/$tfile ||\n\t\terror \"chgrp $RUNAS_ID $DIR/$tfile failed\"\n\n\ttouch $DIR/$tfile || error \"touch $DIR/$tfile failed\"\n\trm $DIR/$tfile || error \"failed to remove released file\"\n}\nrun_test 229 \"getstripe/stat/rm/attr changes work on released files\"\n\ntest_230a() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal MDTIDX=1\n\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir -i0 -c1 $DIR/$tdir/test_230_local\n\tlocal mdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230_local)\n\t[ $mdt_idx -ne 0 ] &&\n\t\terror \"create local directory on wrong MDT $mdt_idx\"\n\n\t$LFS mkdir -i $MDTIDX $DIR/$tdir/test_230 ||\n\t\t\terror \"create remote directory failed\"\n\tlocal mdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230)\n\t[ $mdt_idx -ne $MDTIDX ] &&\n\t\terror \"create remote directory on wrong MDT $mdt_idx\"\n\n\tcreatemany -o $DIR/$tdir/test_230/t- 10 ||\n\t\terror \"create files on remote directory failed\"\n\tmdt_idx=$($LFS getstripe -m $DIR/$tdir/test_230/t-0)\n\t[ $mdt_idx -ne $MDTIDX ] && error \"create files on wrong MDT $mdt_idx\"\n\trm -r $DIR/$tdir || error \"unlink remote directory failed\"\n}\nrun_test 230a \"Create remote directory and files under the remote directory\"\n\ntest_230b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal MDTIDX=1\n\tlocal mdt_index\n\tlocal i\n\tlocal file\n\tlocal pid\n\tlocal stripe_count\n\tlocal migrate_dir=$DIR/$tdir/migrate_dir\n\tlocal other_dir=$DIR/$tdir/other_dir\n\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir -i0 -c1 $migrate_dir\n\ttest_mkdir -i0 -c1 $other_dir\n\tfor ((i=0; i<10; i++)); do\n\t\tmkdir -p $migrate_dir/dir_${i}\n\t\tcreatemany -o $migrate_dir/dir_${i}/f 10 ||\n\t\t\terror \"create files under remote dir failed $i\"\n\tdone\n\n\tcp /etc/passwd $migrate_dir/$tfile\n\tcp /etc/passwd $other_dir/$tfile\n\tchattr +SAD $migrate_dir\n\tchattr +SAD $migrate_dir/$tfile\n\n\tlocal old_dir_flag=$(lsattr -a $migrate_dir | awk '/\\/\\.$/ {print $1}')\n\tlocal old_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')\n\tlocal old_dir_mode=$(stat -c%f $migrate_dir)\n\tlocal old_file_mode=$(stat -c%f $migrate_dir/$tfile)\n\n\tmkdir -p $migrate_dir/dir_default_stripe2\n\t$LFS setstripe -c 2 $migrate_dir/dir_default_stripe2\n\t$LFS setstripe -c 2 $migrate_dir/${tfile}_stripe2\n\n\tmkdir -p $other_dir\n\tln $migrate_dir/$tfile $other_dir/luna\n\tln $migrate_dir/$tfile $migrate_dir/sofia\n\tln $other_dir/$tfile $migrate_dir/david\n\tln -s $migrate_dir/$tfile $other_dir/zachary\n\tln -s $migrate_dir/$tfile $migrate_dir/${tfile}_ln\n\tln -s $other_dir/$tfile $migrate_dir/${tfile}_ln_other\n\n\tlocal len\n\tlocal lnktgt\n\n\t# inline symlink\n\tfor len in 58 59 60; do\n\t\tlnktgt=$(str_repeat 'l' $len)\n\t\ttouch $migrate_dir/$lnktgt\n\t\tln -s $lnktgt $migrate_dir/${len}char_ln\n\tdone\n\n\t# PATH_MAX\n\tfor len in 4094 4095; do\n\t\tlnktgt=$(str_repeat 'l' $len)\n\t\tln -s $lnktgt $migrate_dir/${len}char_ln\n\tdone\n\n\t# NAME_MAX\n\tfor len in 254 255; do\n\t\ttouch $migrate_dir/$(str_repeat 'l' $len)\n\tdone\n\n\t$LFS migrate -m $MDTIDX $migrate_dir ||\n\t\terror \"fails on migrating remote dir to MDT1\"\n\n\techo \"migratate to MDT1, then checking..\"\n\tfor ((i = 0; i < 10; i++)); do\n\t\tfor file in $(find $migrate_dir/dir_${i}); do\n\t\t\tmdt_index=$($LFS getstripe -m $file)\n\t\t\t# broken symlink getstripe will fail\n\t\t\t[ $mdt_index -ne $MDTIDX ] && stat -L $file &&\n\t\t\t\terror \"$file is not on MDT${MDTIDX}\"\n\t\tdone\n\tdone\n\n\t# the multiple link file should still in MDT0\n\tmdt_index=$($LFS getstripe -m $migrate_dir/$tfile)\n\t[ $mdt_index == 0 ] ||\n\t\terror \"$file is not on MDT${MDTIDX}\"\n\n\tlocal new_dir_flag=$(lsattr -a $migrate_dir | awk '/\\/\\.$/ {print $1}')\n\t[ \"$old_dir_flag\" = \"$new_dir_flag\" ] ||\n\t\terror \" expect $old_dir_flag get $new_dir_flag\"\n\n\tlocal new_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')\n\t[ \"$old_file_flag\" = \"$new_file_flag\" ] ||\n\t\terror \" expect $old_file_flag get $new_file_flag\"\n\n\tlocal new_dir_mode=$(stat -c%f $migrate_dir)\n\t[ \"$old_dir_mode\" = \"$new_dir_mode\" ] ||\n\t\terror \"expect mode $old_dir_mode get $new_dir_mode\"\n\n\tlocal new_file_mode=$(stat -c%f $migrate_dir/$tfile)\n\t[ \"$old_file_mode\" = \"$new_file_mode\" ] ||\n\t\terror \"expect mode $old_file_mode get $new_file_mode\"\n\n\tdiff /etc/passwd $migrate_dir/$tfile ||\n\t\terror \"$tfile different after migration\"\n\n\tdiff /etc/passwd $other_dir/luna ||\n\t\terror \"luna different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/sofia ||\n\t\terror \"sofia different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/david ||\n\t\terror \"david different after migration\"\n\n\tdiff /etc/passwd $other_dir/zachary ||\n\t\terror \"zachary different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/${tfile}_ln ||\n\t\terror \"${tfile}_ln different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/${tfile}_ln_other ||\n\t\terror \"${tfile}_ln_other different after migration\"\n\n\tstripe_count=$($LFS getstripe -c $migrate_dir/dir_default_stripe2)\n\t[ $stripe_count = 2 ] ||\n\t\terror \"dir strpe_count $d != 2 after migration.\"\n\n\tstripe_count=$($LFS getstripe -c $migrate_dir/${tfile}_stripe2)\n\t[ $stripe_count = 2 ] ||\n\t\terror \"file strpe_count $d != 2 after migration.\"\n\n\t#migrate back to MDT0\n\tMDTIDX=0\n\n\t$LFS migrate -m $MDTIDX $migrate_dir ||\n\t\terror \"fails on migrating remote dir to MDT0\"\n\n\techo \"migrate back to MDT0, checking..\"\n\tfor file in $(find $migrate_dir); do\n\t\tmdt_index=$($LFS getstripe -m $file)\n\t\t[ $mdt_index -ne $MDTIDX ] && stat -L $file &&\n\t\t\terror \"$file is not on MDT${MDTIDX}\"\n\tdone\n\n\tlocal new_dir_flag=$(lsattr -a $migrate_dir | awk '/\\/\\.$/ {print $1}')\n\t[ \"$old_dir_flag\" = \"$new_dir_flag\" ] ||\n\t\terror \" expect $old_dir_flag get $new_dir_flag\"\n\n\tlocal new_file_flag=$(lsattr $migrate_dir/$tfile | awk '{print $1}')\n\t[ \"$old_file_flag\" = \"$new_file_flag\" ] ||\n\t\terror \" expect $old_file_flag get $new_file_flag\"\n\n\tlocal new_dir_mode=$(stat -c%f $migrate_dir)\n\t[ \"$old_dir_mode\" = \"$new_dir_mode\" ] ||\n\t\terror \"expect mode $old_dir_mode get $new_dir_mode\"\n\n\tlocal new_file_mode=$(stat -c%f $migrate_dir/$tfile)\n\t[ \"$old_file_mode\" = \"$new_file_mode\" ] ||\n\t\terror \"expect mode $old_file_mode get $new_file_mode\"\n\n\tdiff /etc/passwd ${migrate_dir}/$tfile ||\n\t\terror \"$tfile different after migration\"\n\n\tdiff /etc/passwd ${other_dir}/luna ||\n\t\terror \"luna different after migration\"\n\n\tdiff /etc/passwd ${migrate_dir}/sofia ||\n\t\terror \"sofia different after migration\"\n\n\tdiff /etc/passwd ${other_dir}/zachary ||\n\t\terror \"zachary different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/${tfile}_ln ||\n\t\terror \"${tfile}_ln different after migration\"\n\n\tdiff /etc/passwd $migrate_dir/${tfile}_ln_other ||\n\t\terror \"${tfile}_ln_other different after migration\"\n\n\tstripe_count=$($LFS getstripe -c ${migrate_dir}/dir_default_stripe2)\n\t[ $stripe_count = 2 ] ||\n\t\terror \"dir strpe_count $d != 2 after migration.\"\n\n\tstripe_count=$($LFS getstripe -c ${migrate_dir}/${tfile}_stripe2)\n\t[ $stripe_count = 2 ] ||\n\t\terror \"file strpe_count $d != 2 after migration.\"\n\n\trm -rf $DIR/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 230b \"migrate directory\"\n\ntest_230c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal MDTIDX=1\n\tlocal total=3\n\tlocal mdt_index\n\tlocal file\n\tlocal migrate_dir=$DIR/$tdir/migrate_dir\n\n\t#If migrating directory fails in the middle, all entries of\n\t#the directory is still accessiable.\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir -i0 -c1 $migrate_dir\n\ttest_mkdir -i1 -c1 $DIR/$tdir/remote_dir\n\tstat $migrate_dir\n\tcreatemany -o $migrate_dir/f $total ||\n\t\terror \"create files under ${migrate_dir} failed\"\n\n\t# fail after migrating top dir, and this will fail only once, so the\n\t# first sub file migration will fail (currently f3), others succeed.\n\t#OBD_FAIL_MIGRATE_ENTRIES\t0x1801\n\tdo_facet mds1 lctl set_param fail_loc=0x1801\n\tlocal t=$(ls $migrate_dir | wc -l)\n\t$LFS migrate --mdt-index $MDTIDX $migrate_dir &&\n\t\terror \"migrate should fail\"\n\tlocal u=$(ls $migrate_dir | wc -l)\n\t[ \"$u\" == \"$t\" ] || error \"$u != $t during migration\"\n\n\t# add new dir/file should succeed\n\tmkdir $migrate_dir/dir ||\n\t\terror \"mkdir failed under migrating directory\"\n\ttouch $migrate_dir/file ||\n\t\terror \"create file failed under migrating directory\"\n\n\t# add file with existing name should fail\n\tfor file in $migrate_dir/f*; do\n\t\tstat $file > /dev/null || error \"stat $file failed\"\n\t\t$OPENFILE -f O_CREAT:O_EXCL $file &&\n\t\t\terror \"open(O_CREAT|O_EXCL) $file should fail\"\n\t\t$MULTIOP $file m && error \"create $file should fail\"\n\t\ttouch $DIR/$tdir/remote_dir/$tfile ||\n\t\t\terror \"touch $tfile failed\"\n\t\tln $DIR/$tdir/remote_dir/$tfile $file &&\n\t\t\terror \"link $file should fail\"\n\t\tmdt_index=$($LFS getstripe -m $file)\n\t\tif [ $mdt_index == 0 ]; then\n\t\t\t# file failed to migrate is not allowed to rename to\n\t\t\tmv $DIR/$tdir/remote_dir/$tfile $file &&\n\t\t\t\terror \"rename to $file should fail\"\n\t\telse\n\t\t\tmv $DIR/$tdir/remote_dir/$tfile $file ||\n\t\t\t\terror \"rename to $file failed\"\n\t\tfi\n\t\techo hello >> $file || error \"write $file failed\"\n\tdone\n\n\t# resume migration with different options should fail\n\t$LFS migrate -m 0 $migrate_dir &&\n\t\terror \"migrate -m 0 $migrate_dir should fail\"\n\n\t$LFS migrate -m $MDTIDX -c 2 $migrate_dir &&\n\t\terror \"migrate -c 2 $migrate_dir should fail\"\n\n\t# resume migration should succeed\n\t$LFS migrate -m $MDTIDX $migrate_dir ||\n\t\terror \"migrate $migrate_dir failed\"\n\n\techo \"Finish migration, then checking..\"\n\tfor file in $(find $migrate_dir); do\n\t\tmdt_index=$($LFS getstripe -m $file)\n\t\t[ $mdt_index == $MDTIDX ] ||\n\t\t\terror \"$file is not on MDT${MDTIDX}\"\n\tdone\n\n\trm -rf $DIR/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 230c \"check directory accessiblity if migration failed\"\n\ntest_230d() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\t# LU-11235\n\t[ \"$mds1_FSTYPE\" == \"zfs\" ] && skip \"skip ZFS backend\"\n\n\tlocal migrate_dir=$DIR/$tdir/migrate_dir\n\tlocal old_index\n\tlocal new_index\n\tlocal old_count\n\tlocal new_count\n\tlocal new_hash\n\tlocal mdt_index\n\tlocal i\n\tlocal j\n\n\told_index=$((RANDOM % MDSCOUNT))\n\told_count=$((MDSCOUNT - old_index))\n\tnew_index=$((RANDOM % MDSCOUNT))\n\tnew_count=$((MDSCOUNT - new_index))\n\tnew_hash=1 # for all_char\n\n\t[ $old_count -gt 1 ] && old_count=$((old_count - RANDOM % old_count))\n\t[ $new_count -gt 1 ] && new_count=$((new_count - RANDOM % new_count))\n\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir -i $old_index -c $old_count $migrate_dir\n\n\tfor ((i=0; i<100; i++)); do\n\t\ttest_mkdir -i0 -c1 $migrate_dir/dir_${i}\n\t\tcreatemany -o $migrate_dir/dir_${i}/f 100 ||\n\t\t\terror \"create files under remote dir failed $i\"\n\tdone\n\n\techo -n \"Migrate from MDT$old_index \"\n\t[ $old_count -gt 1 ] && echo -n \"... MDT$((old_index + old_count - 1)) \"\n\techo -n \"to MDT$new_index\"\n\t[ $new_count -gt 1 ] && echo -n \" ... MDT$((new_index + new_count - 1))\"\n\techo\n\n\techo \"$LFS migrate -m$new_index -c$new_count -H $new_hash $migrate_dir\"\n\t$LFS migrate -m $new_index -c $new_count -H $new_hash $migrate_dir ||\n\t\terror \"migrate remote dir error\"\n\n\techo \"Finish migration, then checking..\"\n\tfor file in $(find $migrate_dir); do\n\t\tmdt_index=$($LFS getstripe -m $file)\n\t\tif [ $mdt_index -lt $new_index ] ||\n\t\t   [ $mdt_index -gt $((new_index + new_count - 1)) ]; then\n\t\t\terror \"$file is on MDT$mdt_index\"\n\t\tfi\n\tdone\n\n\trm -rf $DIR/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 230d \"check migrate big directory\"\n\ntest_230e() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal i\n\tlocal j\n\tlocal a_fid\n\tlocal b_fid\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $DIR/$tdir/migrate_dir\n\tmkdir $DIR/$tdir/other_dir\n\ttouch $DIR/$tdir/migrate_dir/a\n\tln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/b\n\tls $DIR/$tdir/other_dir\n\n\t$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||\n\t\terror \"migrate dir fails\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir)\n\t[ $mdt_index == 1 ] || error \"migrate_dir is not on MDT1\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)\n\t[ $mdt_index == 0 ] || error \"a is not on MDT0\"\n\n\t$LFS migrate -m 1 $DIR/$tdir/other_dir ||\n\t\terror \"migrate dir fails\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/other_dir)\n\t[ $mdt_index == 1 ] || error \"other_dir is not on MDT1\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)\n\t[ $mdt_index == 1 ] || error \"a is not on MDT1\"\n\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/other_dir/b)\n\t[ $mdt_index == 1 ] || error \"b is not on MDT1\"\n\n\ta_fid=$($LFS path2fid $DIR/$tdir/migrate_dir/a)\n\tb_fid=$($LFS path2fid $DIR/$tdir/other_dir/b)\n\n\t[ \"$a_fid\" = \"$b_fid\" ] || error \"different fid after migration\"\n\n\trm -rf $DIR/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 230e \"migrate mulitple local link files\"\n\ntest_230f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal a_fid\n\tlocal ln_fid\n\n\tmkdir -p $DIR/$tdir\n\tmkdir $DIR/$tdir/migrate_dir\n\t$LFS mkdir -i1 $DIR/$tdir/other_dir\n\ttouch $DIR/$tdir/migrate_dir/a\n\tln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/ln1\n\tln $DIR/$tdir/migrate_dir/a $DIR/$tdir/other_dir/ln2\n\tls $DIR/$tdir/other_dir\n\n\t# a should be migrated to MDT1, since no other links on MDT0\n\t$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||\n\t\terror \"#1 migrate dir fails\"\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir)\n\t[ $mdt_index == 1 ] || error \"migrate_dir is not on MDT1\"\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)\n\t[ $mdt_index == 1 ] || error \"a is not on MDT1\"\n\n\t# a should stay on MDT1, because it is a mulitple link file\n\t$LFS migrate -m 0 $DIR/$tdir/migrate_dir ||\n\t\terror \"#2 migrate dir fails\"\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)\n\t[ $mdt_index == 1 ] || error \"a is not on MDT1\"\n\n\t$LFS migrate -m 1 $DIR/$tdir/migrate_dir ||\n\t\terror \"#3 migrate dir fails\"\n\n\ta_fid=$($LFS path2fid $DIR/$tdir/migrate_dir/a)\n\tln_fid=$($LFS path2fid $DIR/$tdir/other_dir/ln1)\n\t[ \"$a_fid\" = \"$ln_fid\" ] || error \"different fid after migrate to MDT1\"\n\n\trm -rf $DIR/$tdir/other_dir/ln1 || error \"unlink ln1 fails\"\n\trm -rf $DIR/$tdir/other_dir/ln2 || error \"unlink ln2 fails\"\n\n\t# a should be migrated to MDT0, since no other links on MDT1\n\t$LFS migrate -m 0 $DIR/$tdir/migrate_dir ||\n\t\terror \"#4 migrate dir fails\"\n\tmdt_index=$($LFS getstripe -m $DIR/$tdir/migrate_dir/a)\n\t[ $mdt_index == 0 ] || error \"a is not on MDT0\"\n\n\trm -rf $DIR/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 230f \"migrate mulitple remote link files\"\n\ntest_230g() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tmkdir -p $DIR/$tdir/migrate_dir\n\n\t$LFS migrate -m 1000 $DIR/$tdir/migrate_dir &&\n\t\terror \"migrating dir to non-exist MDT succeeds\"\n\ttrue\n}\nrun_test 230g \"migrate dir to non-exist MDT\"\n\ntest_230h() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal mdt_index\n\n\tmkdir -p $DIR/$tdir/migrate_dir\n\n\t$LFS migrate -m1 $DIR &&\n\t\terror \"migrating mountpoint1 should fail\"\n\n\t$LFS migrate -m1 $DIR/$tdir/.. &&\n\t\terror \"migrating mountpoint2 should fail\"\n\n\t# same as mv\n\t$LFS migrate -m1 $DIR/$tdir/migrate_dir/.. &&\n\t\terror \"migrating $tdir/migrate_dir/.. should fail\"\n\n\ttrue\n}\nrun_test 230h \"migrate .. and root\"\n\ntest_230i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tmkdir -p $DIR/$tdir/migrate_dir\n\n\t$LFS migrate -m 1 $DIR/$tdir/migrate_dir/ ||\n\t\terror \"migration fails with a tailing slash\"\n\n\t$LFS migrate -m 0 $DIR/$tdir/migrate_dir// ||\n\t\terror \"migration fails with two tailing slashes\"\n}\nrun_test 230i \"lfs migrate -m tolerates trailing slashes\"\n\ntest_230j() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.13.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\t$LFS mkdir -m 0 -c 1 $DIR/$tdir || error \"mkdir $tdir failed\"\n\t$LFS setstripe -E 1M -L mdt $DIR/$tdir/$tfile ||\n\t\terror \"create $tfile failed\"\n\tcat /etc/passwd > $DIR/$tdir/$tfile\n\n\t$LFS migrate -m 1 $DIR/$tdir || error \"migrate failed\"\n\n\tcmp /etc/passwd $DIR/$tdir/$tfile ||\n\t\terror \"DoM file mismatch after migration\"\n}\nrun_test 230j \"DoM file data not changed after dir migration\"\n\ntest_230k() {\n\t[ $MDSCOUNT -lt 4 ] && skip \"needs >= 4 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\tlocal total=20\n\tlocal files_on_starting_mdt=0\n\n\t$LFS mkdir -i -1 -c 2 $DIR/$tdir || error \"mkdir failed\"\n\t$LFS getdirstripe $DIR/$tdir\n\tfor i in $(seq $total); do\n\t\techo $((i*i - i)) > $DIR/$tdir/$tfile.$i || error \"write failed\"\n\t\t[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 0 ]] &&\n\t\t\tfiles_on_starting_mdt=$((files_on_starting_mdt + 1))\n\tdone\n\n\techo \"$files_on_starting_mdt files on MDT0\"\n\n\t$LFS migrate -m 1,3 $DIR/$tdir || error \"migrate -m 1,3 failed\"\n\t$LFS getdirstripe $DIR/$tdir\n\n\tfiles_on_starting_mdt=0\n\tfor i in $(seq $total); do\n\t\t$(echo $((i*i - i)) | cmp $DIR/$tdir/$tfile.$i -) ||\n\t\t\terror \"file $tfile.$i mismatch after migration\"\n\t\t[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 1 ]] &&\n\t\t\tfiles_on_starting_mdt=$((files_on_starting_mdt + 1))\n\tdone\n\n\techo \"$files_on_starting_mdt files on MDT1 after migration\"\n\t[[ $files_on_starting_mdt -eq $total ]] && error \"all files on MDT1\"\n\n\t$LFS migrate -m 0 -c 2 $DIR/$tdir || error \"migrate -m 0 -c 2 failed\"\n\t$LFS getdirstripe $DIR/$tdir\n\n\tfiles_on_starting_mdt=0\n\tfor i in $(seq $total); do\n\t\t$(echo $((i*i - i)) | cmp $DIR/$tdir/$tfile.$i -) ||\n\t\t\terror \"file $tfile.$i mismatch after 2nd migration\"\n\t\t[[ $($LFS getstripe -m $DIR/$tdir/$tfile.$i) -eq 0 ]] &&\n\t\t\tfiles_on_starting_mdt=$((files_on_starting_mdt + 1))\n\tdone\n\n\techo \"$files_on_starting_mdt files on MDT0 after 2nd migration\"\n\t[[ $files_on_starting_mdt -eq $total ]] && error \"all files on MDT0\"\n\n\ttrue\n}\nrun_test 230k \"file data not changed after dir migration\"\n\ntest_230l() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir || error \"mkdir failed\"\n\tcreatemany -o $DIR/$tdir/f___________________________________ 1000 ||\n\t\terror \"create files under remote dir failed $i\"\n\t$LFS migrate -m 1 $DIR/$tdir || error \"migrate failed\"\n}\nrun_test 230l \"readdir between MDTs won't crash\"\n\ntest_230m() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\tlocal MDTIDX=1\n\tlocal mig_dir=$DIR/$tdir/migrate_dir\n\tlocal longstr=\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\"\n\tlocal shortstr=\"b\"\n\tlocal val\n\n\techo \"Creating files and dirs with xattrs\"\n\ttest_mkdir $DIR/$tdir\n\ttest_mkdir -i0 -c1 $mig_dir\n\tmkdir $mig_dir/dir\n\tsetfattr -n user.attr1 -v $longstr $mig_dir/dir ||\n\t\terror \"cannot set xattr attr1 on dir\"\n\tsetfattr -n user.attr2 -v $shortstr $mig_dir/dir ||\n\t\terror \"cannot set xattr attr2 on dir\"\n\ttouch $mig_dir/dir/f0\n\tsetfattr -n user.attr1 -v $longstr $mig_dir/dir/f0 ||\n\t\terror \"cannot set xattr attr1 on file\"\n\tsetfattr -n user.attr2 -v $shortstr $mig_dir/dir/f0 ||\n\t\terror \"cannot set xattr attr2 on file\"\n\tsync ; sync ; echo 3 > /proc/sys/vm/drop_caches\n\tval=$(getfattr --only-values -n user.attr1 $mig_dir/dir 2>/dev/null)\n\t[ \"$val\" = $longstr ] || error \"xattr attr1 not set properly on dir\"\n\tval=$(getfattr --only-values -n user.attr2 $mig_dir/dir 2>/dev/null)\n\t[ \"$val\" = $shortstr ] || error \"xattr attr2 not set properly on dir\"\n\tval=$(getfattr --only-values -n user.attr1 $mig_dir/dir/f0 2>/dev/null)\n\t[ \"$val\" = $longstr ] || error \"xattr attr1 not set properly on file\"\n\tval=$(getfattr --only-values -n user.attr2 $mig_dir/dir/f0 2>/dev/null)\n\t[ \"$val\" = $shortstr ] || error \"xattr attr2 not set properly on file\"\n\n\techo \"Migrating to MDT1\"\n\t$LFS migrate -m $MDTIDX $mig_dir ||\n\t\terror \"fails on migrating dir to MDT1\"\n\n\tsync ; sync ; echo 3 > /proc/sys/vm/drop_caches\n\techo \"Checking xattrs\"\n\tval=$(getfattr --only-values -n user.attr1 $mig_dir/dir 2>/dev/null)\n\t[ \"$val\" = $longstr ] ||\n\t\terror \"expecting xattr1 $longstr on dir, found $val\"\n\tval=$(getfattr --only-values -n user.attr2 $mig_dir/dir 2>/dev/null)\n\t[ \"$val\" = $shortstr ] ||\n\t\terror \"expecting xattr2 $shortstr on dir, found $val\"\n\tval=$(getfattr --only-values -n user.attr1 $mig_dir/dir/f0 2>/dev/null)\n\t[ \"$val\" = $longstr ] ||\n\t\terror \"expecting xattr1 $longstr on file, found $val\"\n\tval=$(getfattr --only-values -n user.attr2 $mig_dir/dir/f0 2>/dev/null)\n\t[ \"$val\" = $shortstr ] ||\n\t\terror \"expecting xattr2 $shortstr on file, found $val\"\n}\nrun_test 230m \"xattrs not changed after dir migration\"\n\ntest_230n() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||\n\t\tskip \"Need MDS version at least 2.13.53\"\n\n\t$LFS mkdir -i 0 $DIR/$tdir || error \"mkdir $tdir failed\"\n\tcat /etc/hosts > $DIR/$tdir/$tfile\n\t$LFS mirror extend -N1 $DIR/$tdir/$tfile || error \"Mirroring failed\"\n\t$LFS migrate -m 1 $DIR/$tdir || error \"Migration failed\"\n\n\tcmp /etc/hosts $DIR/$tdir/$tfile ||\n\t\terror \"File data mismatch after migration\"\n}\nrun_test 230n \"Dir migration with mirrored file\"\n\ntest_230o() {\n\t[ $MDSCOUNT -ge 2 ] || skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||\n\t\tskip \"Need MDS version at least 2.13.52\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\tlocal timeout=100\n\n\tlocal restripe_status\n\tlocal delta\n\tlocal i\n\tlocal j\n\n\t[[ $(facet_fstype mds1) == zfs ]] && timeout=300\n\n\t# in case \"crush\" hash type is not set\n\tdo_nodes $mdts \"$LCTL set_param lod.*.mdt_hash=crush\"\n\n\trestripe_status=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t   mdt.*MDT0000.enable_dir_restripe)\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.enable_dir_restripe=1\"\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\t    mdt.*.enable_dir_restripe=$restripe_status\"\n\n\tmkdir $DIR/$tdir\n\tcreatemany -m $DIR/$tdir/f 100 ||\n\t\terror \"create files under remote dir failed $i\"\n\tcreatemany -d $DIR/$tdir/d 100 ||\n\t\terror \"create dirs under remote dir failed $i\"\n\n\tfor i in $(seq 2 $MDSCOUNT); do\n\t\tdo_nodes $mdts \"$LCTL set_param mdt.*.md_stats=clear > /dev/null\"\n\t\t$LFS setdirstripe -c $i $DIR/$tdir ||\n\t\t\terror \"split -c $i $tdir failed\"\n\t\twait_update $HOSTNAME \\\n\t\t\t\"$LFS getdirstripe -H $DIR/$tdir\" \"crush\" $timeout ||\n\t\t\terror \"dir split not finished\"\n\t\tdelta=$(do_nodes $mdts \"lctl get_param -n mdt.*MDT*.md_stats\" |\n\t\t\tawk '/migrate/ {sum += $2} END { print sum }')\n\t\techo \"$delta files migrated when dir split from $((i - 1)) to $i stripes\"\n\t\t# delta is around total_files/stripe_count\n\t\t[ $delta -lt $((200 /(i - 1))) ] ||\n\t\t\terror \"$delta files migrated\"\n\tdone\n}\nrun_test 230o \"dir split\"\n\ntest_230p() {\n\t[ $MDSCOUNT -ge 2 ] || skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||\n\t\tskip \"Need MDS version at least 2.13.52\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\tlocal timeout=100\n\n\tlocal restripe_status\n\tlocal delta\n\tlocal i\n\tlocal j\n\n\t[[ $(facet_fstype mds1) == zfs ]] && timeout=300\n\n\tdo_nodes $mdts \"$LCTL set_param lod.*.mdt_hash=crush\"\n\n\trestripe_status=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t   mdt.*MDT0000.enable_dir_restripe)\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.enable_dir_restripe=1\"\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\t    mdt.*.enable_dir_restripe=$restripe_status\"\n\n\ttest_mkdir -c $MDSCOUNT -H crush $DIR/$tdir\n\tcreatemany -m $DIR/$tdir/f 100 ||\n\t\terror \"create files under remote dir failed $i\"\n\tcreatemany -d $DIR/$tdir/d 100 ||\n\t\terror \"create dirs under remote dir failed $i\"\n\n\tfor i in $(seq $((MDSCOUNT - 1)) -1 1); do\n\t\tlocal mdt_hash=\"crush\"\n\n\t\tdo_nodes $mdts \"$LCTL set_param mdt.*.md_stats=clear > /dev/null\"\n\t\t$LFS setdirstripe -c $i $DIR/$tdir ||\n\t\t\terror \"split -c $i $tdir failed\"\n\t\t[ $i -eq 1 ] && mdt_hash=\"none\"\n\t\twait_update $HOSTNAME \\\n\t\t\t\"$LFS getdirstripe -H $DIR/$tdir\" $mdt_hash $timeout ||\n\t\t\terror \"dir merge not finished\"\n\t\tdelta=$(do_nodes $mdts \"lctl get_param -n mdt.*MDT*.md_stats\" |\n\t\t\tawk '/migrate/ {sum += $2} END { print sum }')\n\t\techo \"$delta files migrated when dir merge from $((i + 1)) to $i stripes\"\n\t\t# delta is around total_files/stripe_count\n\t\t[ $delta -lt $((200 / i)) ] ||\n\t\t\terror \"$delta files migrated\"\n\tdone\n}\nrun_test 230p \"dir merge\"\n\ntest_230q() {\n\t[ $MDSCOUNT -ge 2 ] || skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||\n\t\tskip \"Need MDS version at least 2.13.52\"\n\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\tlocal saved_threshold=$(do_facet mds1 \\\n\t\t\t$LCTL get_param -n mdt.*-MDT0000.dir_split_count)\n\tlocal saved_delta=$(do_facet mds1 \\\n\t\t\t$LCTL get_param -n mdt.*-MDT0000.dir_split_delta)\n\tlocal threshold=100\n\tlocal delta=2\n\tlocal total=0\n\tlocal stripe_count=0\n\tlocal stripe_index\n\tlocal nr_files\n\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\t    mdt.*.dir_split_count=$saved_threshold\"\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\t    mdt.*.dir_split_delta=$saved_delta\"\n\tstack_trap \"do_nodes $mdts $LCTL set_param mdt.*.dir_restripe_nsonly=1\"\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.enable_dir_auto_split=1\"\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.dir_split_count=$threshold\"\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.dir_split_delta=$delta\"\n\tdo_nodes $mdts \"$LCTL set_param mdt.*.dir_restripe_nsonly=0\"\n\tdo_nodes $mdts \"$LCTL set_param lod.*.mdt_hash=crush\"\n\n\t$LFS mkdir -i -1 -c 1 $DIR/$tdir || error \"mkdir $tdir failed\"\n\tstripe_index=$($LFS getdirstripe -i $DIR/$tdir)\n\n\twhile [ $stripe_count -lt $MDSCOUNT ]; do\n\t\tcreatemany -m $DIR/$tdir/f $total $((threshold * 3 / 2)) ||\n\t\t\terror \"create sub files failed\"\n\t\tstat $DIR/$tdir > /dev/null\n\t\ttotal=$((total + threshold * 3 / 2))\n\t\tstripe_count=$((stripe_count + delta))\n\t\t[ $stripe_count -gt $MDSCOUNT ] && stripe_count=$MDSCOUNT\n\n\t\twait_update $HOSTNAME \\\n\t\t\t\"$LFS getdirstripe -c $DIR/$tdir\" \"$stripe_count\" 40 ||\n\t\t\terror \"stripe count $($LFS getdirstripe -c $DIR/$tdir) != $stripe_count\"\n\n\t\twait_update $HOSTNAME \\\n\t\t\t\"$LFS getdirstripe -H $DIR/$tdir\" \"crush\" 200 ||\n\t\t\terror \"stripe hash $($LFS getdirstripe -H $DIR/$tdir) != crush\"\n\n\t\tnr_files=$($LFS getstripe -m $DIR/$tdir/* |\n\t\t\t   grep -w $stripe_index | wc -l)\n\t\techo \"$nr_files files on MDT$stripe_index after split\"\n\t\t[ $nr_files -lt $((total / (stripe_count - 1))) ] ||\n\t\t\terror \"$nr_files files on MDT$stripe_index after split\"\n\n\t\tnr_files=$(ls $DIR/$tdir | wc -w)\n\t\t[ $nr_files -eq $total ] ||\n\t\t\terror \"total sub files $nr_files != $total\"\n\tdone\n}\nrun_test 230q \"dir auto split\"\n\ntest_231a()\n{\n\t# For simplicity this test assumes that max_pages_per_rpc\n\t# is the same across all OSCs\n\tlocal max_pages=$($LCTL get_param -n osc.*.max_pages_per_rpc | head -n1)\n\tlocal bulk_size=$((max_pages * PAGE_SIZE))\n\tlocal brw_size=$(do_facet ost1 $LCTL get_param -n obdfilter.*.brw_size |\n\t\t\t\t       head -n 1)\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -S ${brw_size}M $DIR/$tdir ||\n\t\terror \"failed to set stripe with -S ${brw_size}M option\"\n\n\t# clear the OSC stats\n\t$LCTL set_param osc.*.stats=0 &>/dev/null\n\tstop_writeback\n\n\t# Client writes $bulk_size - there must be 1 rpc for $max_pages.\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=$bulk_size count=1 \\\n\t\toflag=direct &>/dev/null || error \"dd failed\"\n\n\tsync; sleep 1; sync # just to be safe\n\tlocal nrpcs=$($LCTL get_param osc.*.stats |awk '/ost_write/ {print $2}')\n\tif [ x$nrpcs != \"x1\" ]; then\n\t\t$LCTL get_param osc.*.stats\n\t\terror \"found $nrpcs ost_write RPCs, not 1 as expected\"\n\tfi\n\n\tstart_writeback\n\t# Drop the OSC cache, otherwise we will read from it\n\tcancel_lru_locks osc\n\n\t# clear the OSC stats\n\t$LCTL set_param osc.*.stats=0 &>/dev/null\n\n\t# Client reads $bulk_size.\n\tdd if=$DIR/$tdir/$tfile of=/dev/null bs=$bulk_size count=1 \\\n\t\tiflag=direct &>/dev/null || error \"dd failed\"\n\n\tnrpcs=$($LCTL get_param osc.*.stats | awk '/ost_read/ { print $2 }')\n\tif [ x$nrpcs != \"x1\" ]; then\n\t\t$LCTL get_param osc.*.stats\n\t\terror \"found $nrpcs ost_read RPCs, not 1 as expected\"\n\tfi\n}\nrun_test 231a \"checking that reading/writing of BRW RPC size results in one RPC\"\n\ntest_231b() {\n\tmkdir -p $DIR/$tdir\n\tlocal i\n\tfor i in {0..1023}; do\n\t\tdd if=/dev/zero of=$DIR/$tdir/$tfile conv=notrunc \\\n\t\t\tseek=$((2 * i)) bs=4096 count=1 &>/dev/null ||\n\t\t\terror \"dd of=$DIR/$tdir/$tfile seek=$((2 * i)) failed\"\n\tdone\n\tsync\n}\nrun_test 231b \"must not assert on fully utilized OST request buffer\"\n\ntest_232a() {\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c1 -i0 $DIR/$tdir/$tfile\n\n\t#define OBD_FAIL_LDLM_OST_LVB\t\t 0x31c\n\tdo_facet ost1 $LCTL set_param fail_loc=0x31c\n\n\t# ignore dd failure\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=1 || true\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\tumount_client $MOUNT || error \"umount failed\"\n\tmount_client $MOUNT || error \"mount failed\"\n\tstop ost1 || error \"cannot stop ost1\"\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error \"cannot start ost1\"\n}\nrun_test 232a \"failed lock should not block umount\"\n\ntest_232b() {\n\t[ $MDS1_VERSION -ge $(version_code 2.10.58) ] ||\n\t\tskip \"Need MDS version at least 2.10.58\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c1 -i0 $DIR/$tdir/$tfile\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=1\n\tsync\n\tcancel_lru_locks osc\n\n\t#define OBD_FAIL_LDLM_OST_LVB\t\t 0x31c\n\tdo_facet ost1 $LCTL set_param fail_loc=0x31c\n\n\t# ignore failure\n\t$LFS data_version $DIR/$tdir/$tfile || true\n\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\tumount_client $MOUNT || error \"umount failed\"\n\tmount_client $MOUNT || error \"mount failed\"\n\tstop ost1 || error \"cannot stop ost1\"\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error \"cannot start ost1\"\n}\nrun_test 232b \"failed data version lock should not block umount\"\n\ntest_233a() {\n\t[ $MDS1_VERSION -ge $(version_code 2.3.64) ] ||\n\t\tskip \"Need MDS version at least 2.3.64\"\n\t[ -n \"$FILESET\" ] && skip_env \"SKIP due to FILESET set\"\n\n\tlocal fid=$($LFS path2fid $MOUNT)\n\n\tstat $MOUNT/.lustre/fid/$fid > /dev/null ||\n\t\terror \"cannot access $MOUNT using its FID '$fid'\"\n}\nrun_test 233a \"checking that OBF of the FS root succeeds\"\n\ntest_233b() {\n\t[ $MDS1_VERSION -ge $(version_code 2.5.90) ] ||\n\t\tskip \"Need MDS version at least 2.5.90\"\n\t[ -n \"$FILESET\" ] && skip_env \"SKIP due to FILESET set\"\n\n\tlocal fid=$($LFS path2fid $MOUNT/.lustre)\n\n\tstat $MOUNT/.lustre/fid/$fid > /dev/null ||\n\t\terror \"cannot access $MOUNT/.lustre using its FID '$fid'\"\n\n\tfid=$($LFS path2fid $MOUNT/.lustre/fid)\n\tstat $MOUNT/.lustre/fid/$fid > /dev/null ||\n\t\terror \"cannot access $MOUNT/.lustre/fid using its FID '$fid'\"\n}\nrun_test 233b \"checking that OBF of the FS .lustre succeeds\"\n\ntest_234() {\n\tlocal p=\"$TMP/sanityN-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $p\n\tlctl set_param llite.*.xattr_cache 1 ||\n\t\tskip_env \"xattr cache is not supported\"\n\n\tmkdir -p $DIR/$tdir || error \"mkdir failed\"\n\ttouch $DIR/$tdir/$tfile || error \"touch failed\"\n\t# OBD_FAIL_LLITE_XATTR_ENOMEM\n\t$LCTL set_param fail_loc=0x1405\n\tgetfattr -n user.attr $DIR/$tdir/$tfile &&\n\t\terror \"getfattr should have failed with ENOMEM\"\n\t$LCTL set_param fail_loc=0x0\n\trm -rf $DIR/$tdir\n\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 234 \"xattr cache should not crash on ENOMEM\"\n\ntest_235() {\n\t[ $MDS1_VERSION -lt $(version_code 2.4.52) ] &&\n\t\tskip \"Need MDS version at least 2.4.52\"\n\n\tflock_deadlock $DIR/$tfile\n\tlocal RC=$?\n\tcase $RC in\n\t\t0)\n\t\t;;\n\t\t124) error \"process hangs on a deadlock\"\n\t\t;;\n\t\t*) error \"error executing flock_deadlock $DIR/$tfile\"\n\t\t;;\n\tesac\n}\nrun_test 235 \"LU-1715: flock deadlock detection does not work properly\"\n\n#LU-2935\ntest_236() {\n\tcheck_swap_layouts_support\n\n\tlocal ref1=/etc/passwd\n\tlocal ref2=/etc/group\n\tlocal file1=$DIR/$tdir/f1\n\tlocal file2=$DIR/$tdir/f2\n\n\ttest_mkdir -c1 $DIR/$tdir\n\t$LFS setstripe -c 1 $file1 || error \"cannot setstripe on '$file1': rc = $?\"\n\tcp $ref1 $file1 || error \"cp $ref1 $file1 failed: rc = $?\"\n\t$LFS setstripe -c 2 $file2 || error \"cannot setstripe on '$file2': rc = $?\"\n\tcp $ref2 $file2 || error \"cp $ref2 $file2 failed: rc = $?\"\n\tlocal fd=$(free_fd)\n\tlocal cmd=\"exec $fd<>$file2\"\n\teval $cmd\n\trm $file2\n\t$LFS swap_layouts $file1 /proc/self/fd/${fd} ||\n\t\terror \"cannot swap layouts of '$file1' and /proc/self/fd/${fd}\"\n\tcmd=\"exec $fd>&-\"\n\teval $cmd\n\tcmp $ref2 $file1 || error \"content compare failed ($ref2 != $file1)\"\n\n\t#cleanup\n\trm -rf $DIR/$tdir\n}\nrun_test 236 \"Layout swap on open unlinked file\"\n\n# LU-4659 linkea consistency\ntest_238() {\n\t[[ $MDS1_VERSION -gt $(version_code 2.5.57) ]] ||\n\t\t[[ $MDS1_VERSION -gt $(version_code 2.5.1) &&\n\t\t   $MDS1_VERSION -lt $(version_code 2.5.50) ]] ||\n\t\tskip \"Need MDS version at least 2.5.58 or 2.5.2+\"\n\n\ttouch $DIR/$tfile\n\tln $DIR/$tfile $DIR/$tfile.lnk\n\ttouch $DIR/$tfile.new\n\tmv $DIR/$tfile.new $DIR/$tfile\n\tlocal fid1=$($LFS path2fid $DIR/$tfile)\n\tlocal fid2=$($LFS path2fid $DIR/$tfile.lnk)\n\tlocal path1=$($LFS fid2path $FSNAME \"$fid1\")\n\t[ $tfile == $path1 ] || error \"linkea inconsistent: $tfile $fid1 $path1\"\n\tlocal path2=$($LFS fid2path $FSNAME \"$fid2\")\n\t[ $tfile.lnk == $path2 ] ||\n\t\terror \"linkea inconsistent: $tfile.lnk $fid2 $path2!\"\n\trm -f $DIR/$tfile*\n}\nrun_test 238 \"Verify linkea consistency\"\n\ntest_239A() { # was test_239\n\t[ $MDS1_VERSION -lt $(version_code 2.5.60) ] &&\n\t\tskip \"Need MDS version at least 2.5.60\"\n\n\tlocal list=$(comma_list $(mdts_nodes))\n\n\tmkdir -p $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f- 5000\n\tunlinkmany $DIR/$tdir/f- 5000\n\t[ $MDS1_VERSION -gt $(version_code 2.10.4) ] &&\n\t\tdo_nodes $list \"lctl set_param -n osp.*.force_sync=1\"\n\tchanges=$(do_nodes $list \"lctl get_param -n osp.*MDT*.sync_changes \\\n\t\t\tosp.*MDT*.sync_in_flight\" | calc_sum)\n\t[ \"$changes\" -eq 0 ] || error \"$changes not synced\"\n}\nrun_test 239A \"osp_sync test\"\n\ntest_239a() { #LU-5297\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\ttouch $DIR/$tfile\n\t#define OBD_FAIL_OSP_CHECK_INVALID_REC     0x2100\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x2100\n\tchgrp $RUNAS_GID $DIR/$tfile\n\twait_delete_completed\n}\nrun_test 239a \"process invalid osp sync record correctly\"\n\ntest_239b() { #LU-5297\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\ttouch $DIR/$tfile1\n\t#define OBD_FAIL_OSP_CHECK_ENOMEM     0x2101\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x2101\n\tchgrp $RUNAS_GID $DIR/$tfile1\n\twait_delete_completed\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\ttouch $DIR/$tfile2\n\tchgrp $RUNAS_GID $DIR/$tfile2\n\twait_delete_completed\n}\nrun_test 239b \"process osp sync record with ENOMEM error correctly\"\n\ntest_240() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS mkdir -i 0 $DIR/$tdir/d0 ||\n\t\terror \"failed to mkdir $DIR/$tdir/d0 on MDT0\"\n\t$LFS mkdir -i 1 $DIR/$tdir/d0/d1 ||\n\t\terror \"failed to mkdir $DIR/$tdir/d0/d1 on MDT1\"\n\n\tumount_client $MOUNT || error \"umount failed\"\n\t#define OBD_FAIL_TGT_DELAY_CONDITIONAL\t 0x713\n\tdo_facet mds2 lctl set_param fail_loc=0x713 fail_val=1\n\tmount_client $MOUNT || error \"failed to mount client\"\n\n\techo \"stat $DIR/$tdir/d0/d1, should not fail/ASSERT\"\n\tstat $DIR/$tdir/d0/d1 || error \"fail to stat $DIR/$tdir/d0/d1\"\n}\nrun_test 240 \"race between ldlm enqueue and the connection RPC (no ASSERT)\"\n\ntest_241_bio() {\n\tlocal count=$1\n\tlocal bsize=$2\n\n\tfor LOOP in $(seq $count); do\n\t\tdd if=$DIR/$tfile of=/dev/null bs=$bsize count=1 2>/dev/null\n\t\tcancel_lru_locks $OSC || true\n\tdone\n}\n\ntest_241_dio() {\n\tlocal count=$1\n\tlocal bsize=$2\n\n\tfor LOOP in $(seq $1); do\n\t\tdd if=$DIR/$tfile of=/dev/null bs=$bsize count=1 iflag=direct \\\n\t\t\t2>/dev/null\n\tdone\n}\n\ntest_241a() { # was test_241\n\tlocal bsize=$PAGE_SIZE\n\n\t(( bsize < 40960 )) && bsize=40960\n\tdd if=/dev/zero of=$DIR/$tfile count=1 bs=$bsize\n\tls -la $DIR/$tfile\n\tcancel_lru_locks $OSC\n\ttest_241_bio 1000 $bsize &\n\tPID=$!\n\ttest_241_dio 1000 $bsize\n\twait $PID\n}\nrun_test 241a \"bio vs dio\"\n\ntest_241b() {\n\tlocal bsize=$PAGE_SIZE\n\n\t(( bsize < 40960 )) && bsize=40960\n\tdd if=/dev/zero of=$DIR/$tfile count=1 bs=$bsize\n\tls -la $DIR/$tfile\n\ttest_241_dio 1000 $bsize &\n\tPID=$!\n\ttest_241_dio 1000 $bsize\n\twait $PID\n}\nrun_test 241b \"dio vs dio\"\n\ntest_242() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tmkdir -p $DIR/$tdir\n\ttouch $DIR/$tdir/$tfile\n\n\t#define OBD_FAIL_MDS_READPAGE_PACK\t0x105\n\tdo_facet mds1 lctl set_param fail_loc=0x105\n\t/bin/ls $DIR/$tdir && error \"ls $DIR/$tdir should fail\"\n\n\tdo_facet mds1 lctl set_param fail_loc=0\n\t/bin/ls $DIR/$tdir || error \"ls $DIR/$tdir failed\"\n}\nrun_test 242 \"mdt_readpage failure should not cause directory unreadable\"\n\ntest_243()\n{\n\ttest_mkdir $DIR/$tdir\n\tgroup_lock_test -d $DIR/$tdir || error \"A group lock test failed\"\n}\nrun_test 243 \"various group lock tests\"\n\ntest_244a()\n{\n\ttest_mkdir $DIR/$tdir\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile bs=1M count=35\n\tsendfile_grouplock $DIR/$tdir/$tfile || \\\n\t\terror \"sendfile+grouplock failed\"\n\trm -rf $DIR/$tdir\n}\nrun_test 244a \"sendfile with group lock tests\"\n\ntest_244b()\n{\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\" && return\n\n\tlocal threads=50\n\tlocal size=$((1024*1024))\n\n\ttest_mkdir $DIR/$tdir\n\tfor i in $(seq 1 $threads); do\n\t\tlocal file=$DIR/$tdir/file_$((i / 10))\n\t\t$MULTIOP $file OG1234w$size_$((i % 3))w$size_$((i % 4))g1234c &\n\t\tlocal pids[$i]=$!\n\tdone\n\tfor i in $(seq 1 $threads); do\n\t\twait ${pids[$i]}\n\tdone\n}\nrun_test 244b \"multi-threaded write with group lock\"\n\ntest_245() {\n\tlocal flagname=\"multi_mod_rpcs\"\n\tlocal connect_data_name=\"max_mod_rpcs\"\n\tlocal out\n\n\t# check if multiple modify RPCs flag is set\n\tout=$($LCTL get_param mdc.$FSNAME-MDT0000-*.import |\n\t\tgrep \"connect_flags:\")\n\techo \"$out\"\n\n\techo \"$out\" | grep -qw $flagname\n\tif [ $? -ne 0 ]; then\n\t\techo \"connect flag $flagname is not set\"\n\t\treturn\n\tfi\n\n\t# check if multiple modify RPCs data is set\n\tout=$($LCTL get_param mdc.$FSNAME-MDT0000-*.import)\n\techo \"$out\"\n\n\techo \"$out\" | grep -qw $connect_data_name ||\n\t\terror \"import should have connect data $connect_data_name\"\n}\nrun_test 245 \"check mdc connection flag/data: multiple modify RPCs\"\n\ncleanup_247() {\n\tlocal submount=$1\n\n\ttrap 0\n\tumount_client $submount\n\trmdir $submount\n}\n\ntest_247a() {\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import |\n\t\tgrep -q subtree ||\n\t\tskip_env \"Fileset feature is not supported\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\tmkdir $MOUNT/$tdir\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\tFILESET=\"$FILESET/$tdir\" mount_client $submount ||\n\t\terror \"mount $submount failed\"\n\ttrap \"cleanup_247 $submount\" EXIT\n\techo foo > $submount/$tfile || error \"write $submount/$tfile failed\"\n\t[ $(cat $MOUNT/$tdir/$tfile) = \"foo\" ] ||\n\t\terror \"read $MOUNT/$tdir/$tfile failed\"\n\tcleanup_247 $submount\n}\nrun_test 247a \"mount subdir as fileset\"\n\ntest_247b() {\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||\n\t\tskip_env \"Fileset feature is not supported\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\trm -rf $MOUNT/$tdir\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\tSKIP_FILESET=1\n\tFILESET=\"$FILESET/$tdir\" mount_client $submount &&\n\t\terror \"mount $submount should fail\"\n\trmdir $submount\n}\nrun_test 247b \"mount subdir that dose not exist\"\n\ntest_247c() {\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||\n\t\tskip_env \"Fileset feature is not supported\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\tmkdir -p $MOUNT/$tdir/dir1\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\ttrap \"cleanup_247 $submount\" EXIT\n\tFILESET=\"$FILESET/$tdir\" mount_client $submount ||\n\t\terror \"mount $submount failed\"\n\tlocal fid=$($LFS path2fid $MOUNT/)\n\t$LFS fid2path $submount $fid && error \"fid2path should fail\"\n\tcleanup_247 $submount\n}\nrun_test 247c \"running fid2path outside subdirectory root\"\n\ntest_247d() {\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import | grep -q subtree ||\n\t\tskip \"Fileset feature is not supported\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\tmkdir -p $MOUNT/$tdir/dir1\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\tFILESET=\"$FILESET/$tdir\" mount_client $submount ||\n\t\terror \"mount $submount failed\"\n\ttrap \"cleanup_247 $submount\" EXIT\n\n\tlocal td=$submount/dir1\n\tlocal fid=$($LFS path2fid $td)\n\t[ -z \"$fid\" ] && error \"path2fid unable to get $td FID\"\n\n\t# check that we get the same pathname back\n\tlocal rootpath\n\tlocal found\n\tfor rootpath in \"$submount\" \"$submount///\" \"$submount/dir1\"; do\n\t\techo \"$rootpath $fid\"\n\t\tfound=$($LFS fid2path $rootpath \"$fid\")\n\t\t[ -n \"found\" ] || error \"fid2path should succeed\"\n\t\t[ \"$found\" == \"$td\" ] || error \"fid2path $found != $td\"\n\tdone\n\t# check wrong root path format\n\trootpath=$submount\"_wrong\"\n\tfound=$($LFS fid2path $rootpath \"$fid\")\n\t[ -z \"$found\" ] || error \"fid2path should fail ($rootpath != $submount)\"\n\n\tcleanup_247 $submount\n}\nrun_test 247d \"running fid2path inside subdirectory root\"\n\n# LU-8037\ntest_247e() {\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import |\n\t\tgrep -q subtree ||\n\t\tskip \"Fileset feature is not supported\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\tmkdir $MOUNT/$tdir\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\tFILESET=\"$FILESET/..\" mount_client $submount &&\n\t\terror \"mount $submount should fail\"\n\trmdir $submount\n}\nrun_test 247e \"mount .. as fileset\"\n\ntest_247f() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.13.52) ] &&\n\t\tskip \"Need at least version 2.13.52\"\n\tlctl get_param -n mdc.$FSNAME-MDT0000*.import |\n\t\tgrep -q subtree ||\n\t\tskip \"Fileset feature is not supported\"\n\n\tmkdir $DIR/$tdir || error \"mkdir $tdir failed\"\n\t$LFS mkdir -i $((MDSCOUNT - 1)) $DIR/$tdir/remote ||\n\t\terror \"mkdir remote failed\"\n\tmkdir $DIR/$tdir/remote/subdir || error \"mkdir remote/subdir failed\"\n\t$LFS mkdir -c $MDSCOUNT $DIR/$tdir/striped ||\n\t\terror \"mkdir striped failed\"\n\tmkdir $DIR/$tdir/striped/subdir || error \"mkdir striped/subdir failed\"\n\n\tlocal submount=${MOUNT}_$tdir\n\n\tmkdir -p $submount || error \"mkdir $submount failed\"\n\n\tlocal dir\n\tlocal fileset=$FILESET\n\n\tfor dir in $tdir/remote $tdir/remote/subdir \\\n\t\t   $tdir/striped $tdir/striped/subdir $tdir/striped/. ; do\n\t\tFILESET=\"$fileset/$dir\" mount_client $submount ||\n\t\t\terror \"mount $dir failed\"\n\t\tumount_client $submount\n\tdone\n}\nrun_test 247f \"mount striped or remote directory as fileset\"\n\ntest_248a() {\n\tlocal fast_read_sav=$($LCTL get_param -n llite.*.fast_read 2>/dev/null)\n\t[ -z \"$fast_read_sav\" ] && skip \"no fast read support\"\n\n\t# create a large file for fast read verification\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=128 > /dev/null 2>&1\n\n\t# make sure the file is created correctly\n\t$CHECKSTAT -s $((128*1024*1024)) $DIR/$tfile ||\n\t\t{ rm -f $DIR/$tfile; skip \"file creation error\"; }\n\n\techo \"Test 1: verify that fast read is 4 times faster on cache read\"\n\n\t# small read with fast read enabled\n\t$LCTL set_param -n llite.*.fast_read=1\n\tlocal t_fast=$(dd if=$DIR/$tfile of=/dev/null bs=4k 2>&1 |\n\t\tegrep -o '([[:digit:]\\.\\,e-]+) s' | cut -d's' -f1 |\n\t\tsed -e 's/,/./' -e 's/[eE]+*/\\*10\\^/')\n\t# small read with fast read disabled\n\t$LCTL set_param -n llite.*.fast_read=0\n\tlocal t_slow=$(dd if=$DIR/$tfile of=/dev/null bs=4k 2>&1 |\n\t\tegrep -o '([[:digit:]\\.\\,e-]+) s' | cut -d's' -f1 |\n\t\tsed -e 's/,/./' -e 's/[eE]+*/\\*10\\^/')\n\n\t# verify that fast read is 4 times faster for cache read\n\t[ $(bc <<< \"4 * $t_fast < $t_slow\") -eq 1 ] ||\n\t\terror_not_in_vm \"fast read was not 4 times faster: \" \\\n\t\t\t   \"$t_fast vs $t_slow\"\n\n\techo \"Test 2: verify the performance between big and small read\"\n\t$LCTL set_param -n llite.*.fast_read=1\n\n\t# 1k non-cache read\n\tcancel_lru_locks osc\n\tlocal t_1k=$(dd if=$DIR/$tfile of=/dev/null bs=1k 2>&1 |\n\t\tegrep -o '([[:digit:]\\.\\,e-]+) s' | cut -d's' -f1 |\n\t\tsed -e 's/,/./' -e 's/[eE]+*/\\*10\\^/')\n\n\t# 1M non-cache read\n\tcancel_lru_locks osc\n\tlocal t_1m=$(dd if=$DIR/$tfile of=/dev/null bs=1k 2>&1 |\n\t\tegrep -o '([[:digit:]\\.\\,e-]+) s' | cut -d's' -f1 |\n\t\tsed -e 's/,/./' -e 's/[eE]+*/\\*10\\^/')\n\n\t# verify that big IO is not 4 times faster than small IO\n\t[ $(bc <<< \"4 * $t_1k >= $t_1m\") -eq 1 ] ||\n\t\terror_not_in_vm \"bigger IO is way too fast: $t_1k vs $t_1m\"\n\n\t$LCTL set_param -n llite.*.fast_read=$fast_read_sav\n\trm -f $DIR/$tfile\n}\nrun_test 248a \"fast read verification\"\n\ntest_248b() {\n\t# Default short_io_bytes=16384, try both smaller and larger sizes.\n\t# Lustre O_DIRECT read and write needs to be a multiple of PAGE_SIZE.\n\t# 6017024 = 2^12*13*113 = 47008*128 = 11752*512 = 4096*1469 = 53248*113\n\techo \"bs=53248 count=113 normal buffered write\"\n\tdd if=/dev/urandom of=$TMP/$tfile.0 bs=53248 count=113 ||\n\t\terror \"dd of initial data file failed\"\n\tstack_trap \"rm -f $DIR/$tfile.[0-3] $TMP/$tfile.[0-3]\" EXIT\n\n\techo \"bs=47008 count=128 oflag=dsync normal write $tfile.0\"\n\tdd if=$TMP/$tfile.0 of=$DIR/$tfile.0 bs=47008 count=128 oflag=dsync ||\n\t\terror \"dd with sync normal writes failed\"\n\tcmp $TMP/$tfile.0 $DIR/$tfile.0 || error \"compare $DIR/$tfile.0 failed\"\n\n\techo \"bs=11752 count=512 oflag=dsync small write $tfile.1\"\n\tdd if=$TMP/$tfile.0 of=$DIR/$tfile.1 bs=11752 count=512 oflag=dsync ||\n\t\terror \"dd with sync small writes failed\"\n\tcmp $TMP/$tfile.0 $DIR/$tfile.1 || error \"compare $DIR/$tfile.1 failed\"\n\n\tcancel_lru_locks osc\n\n\t# calculate the small O_DIRECT size and count for the client PAGE_SIZE\n\tlocal num=$((13 * 113 / (PAGE_SIZE / 4096)))\n\techo \"bs=$PAGE_SIZE count=$num iflag=direct small read $tfile.1\"\n\tdd if=$DIR/$tfile.1 of=$TMP/$tfile.1 bs=$PAGE_SIZE count=$num \\\n\t\tiflag=direct || error \"dd with O_DIRECT small read failed\"\n\t# adjust bytes checked to handle larger PAGE_SIZE for ARM/PPC\n\tcmp --bytes=$((PAGE_SIZE * num)) $TMP/$tfile.0 $TMP/$tfile.1 ||\n\t\terror \"compare $TMP/$tfile.1 failed\"\n\n\tlocal save=$($LCTL get_param -n osc.*OST000*.short_io_bytes | head -n 1)\n\tstack_trap \"$LCTL set_param osc.$FSNAME-*.short_io_bytes=$save\" EXIT\n\n\t# just to see what the maximum tunable value is, and test parsing\n\techo \"test invalid parameter 2MB\"\n\t$LCTL set_param osc.$FSNAME-OST0000*.short_io_bytes=2M &&\n\t\terror \"too-large short_io_bytes allowed\"\n\techo \"test maximum parameter 512KB\"\n\t# if we can set a larger short_io_bytes, run test regardless of version\n\tif ! $LCTL set_param osc.$FSNAME-OST0000*.short_io_bytes=512K; then\n\t\t# older clients may not allow setting it this large, that's OK\n\t\t[ $CLIENT_VERSION -ge $(version_code 2.13.50) ] ||\n\t\t\tskip \"Need at least client version 2.13.50\"\n\t\terror \"medium short_io_bytes failed\"\n\tfi\n\t$LCTL get_param osc.$FSNAME-OST0000*.short_io_bytes\n\tsize=$($LCTL get_param -n osc.$FSNAME-OST0000*.short_io_bytes)\n\n\techo \"test large parameter 64KB\"\n\t$LCTL set_param osc.$FSNAME-*.short_io_bytes=65536\n\t$LCTL get_param osc.$FSNAME-OST0000*.short_io_bytes\n\n\techo \"bs=47008 count=128 oflag=dsync large write $tfile.2\"\n\tdd if=$TMP/$tfile.0 of=$DIR/$tfile.2 bs=47008 count=128 oflag=dsync ||\n\t\terror \"dd with sync large writes failed\"\n\tcmp $TMP/$tfile.0 $DIR/$tfile.2 || error \"compare $DIR/$tfile.2 failed\"\n\n\t# calculate the large O_DIRECT size and count for the client PAGE_SIZE\n\tlocal size=$(((4096 * 13 + PAGE_SIZE - 1) / PAGE_SIZE * PAGE_SIZE))\n\tnum=$((113 * 4096 / PAGE_SIZE))\n\techo \"bs=$size count=$num oflag=direct large write $tfile.3\"\n\tdd if=$TMP/$tfile.0 of=$DIR/$tfile.3 bs=$size count=$num oflag=direct ||\n\t\terror \"dd with O_DIRECT large writes failed\"\n\tcmp --bytes=$((size * num)) $TMP/$tfile.0 $DIR/$tfile.3 ||\n\t\terror \"compare $DIR/$tfile.3 failed\"\n\n\tcancel_lru_locks osc\n\n\techo \"bs=$size count=$num iflag=direct large read $tfile.2\"\n\tdd if=$DIR/$tfile.2 of=$TMP/$tfile.2 bs=$size count=$num iflag=direct ||\n\t\terror \"dd with O_DIRECT large read failed\"\n\tcmp --bytes=$((size * num)) $TMP/$tfile.0 $TMP/$tfile.2 ||\n\t\terror \"compare $TMP/$tfile.2 failed\"\n\n\techo \"bs=$size count=$num iflag=direct large read $tfile.3\"\n\tdd if=$DIR/$tfile.3 of=$TMP/$tfile.3 bs=$size count=$num iflag=direct ||\n\t\terror \"dd with O_DIRECT large read failed\"\n\tcmp --bytes=$((size * num)) $TMP/$tfile.0 $TMP/$tfile.3 ||\n\t\terror \"compare $TMP/$tfile.3 failed\"\n}\nrun_test 248b \"test short_io read and write for both small and large sizes\"\n\ntest_249() { # LU-7890\n\t[ $MDS1_VERSION -lt $(version_code 2.8.53) ] &&\n\t\tskip \"Need at least version 2.8.54\"\n\n\trm -f $DIR/$tfile\n\t$LFS setstripe -c 1 $DIR/$tfile\n\t# Offset 2T == 4k * 512M\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=1 seek=512M ||\n\t\terror \"dd to 2T offset failed\"\n}\nrun_test 249 \"Write above 2T file size\"\n\ntest_250() {\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $DIR/$tfile) + 1)))\" = \"zfs\" ] \\\n\t && skip \"no 16TB file size limit on ZFS\"\n\n\t$LFS setstripe -c 1 $DIR/$tfile\n\t# ldiskfs extent file size limit is (16TB - 4KB - 1) bytes\n\tlocal size=$((16 * 1024 * 1024 * 1024 * 1024 - 4096 - 1))\n\t$TRUNCATE $DIR/$tfile $size || error \"truncate $tfile to $size failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=10 count=1 oflag=append \\\n\t\tconv=notrunc,fsync && error \"append succeeded\"\n\treturn 0\n}\nrun_test 250 \"Write above 16T limit\"\n\ntest_251() {\n\t$LFS setstripe -c -1 -S 1048576 $DIR/$tfile\n\n\t#define OBD_FAIL_LLITE_LOST_LAYOUT 0x1407\n\t#Skip once - writing the first stripe will succeed\n\t$LCTL set_param fail_loc=0xa0001407 fail_val=1\n\t$MULTIOP $DIR/$tfile o:O_RDWR:w2097152c 2>&1 | grep -q \"short write\" &&\n\t\terror \"short write happened\"\n\n\t$LCTL set_param fail_loc=0xa0001407 fail_val=1\n\t$MULTIOP $DIR/$tfile or2097152c 2>&1 | grep -q \"short read\" &&\n\t\terror \"short read happened\"\n\n\trm -f $DIR/$tfile\n}\nrun_test 251 \"Handling short read and write correctly\"\n\ntest_252() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tif [ \"$ost1_FSTYPE\" != ldiskfs ] || [ \"$mds1_FSTYPE\" != ldiskfs ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\tlocal tgt\n\tlocal dev\n\tlocal out\n\tlocal uuid\n\tlocal num\n\tlocal gen\n\n\t# check lr_reader on OST0000\n\ttgt=ost1\n\tdev=$(facet_device $tgt)\n\tout=$(do_facet $tgt $LR_READER $dev)\n\t[ $? -eq 0 ] || error \"$LR_READER failed on target $tgt device $dev\"\n\techo \"$out\"\n\tuuid=$(echo \"$out\" | grep -i uuid | awk '{ print $2 }')\n\t[ \"$uuid\" == \"$(ostuuid_from_index 0)\" ] ||\n\t\terror \"Invalid uuid returned by $LR_READER on target $tgt\"\n\techo -e \"uuid returned by $LR_READER is '$uuid'\\n\"\n\n\t# check lr_reader -c on MDT0000\n\ttgt=mds1\n\tdev=$(facet_device $tgt)\n\tif ! do_facet $tgt $LR_READER -h | grep -q OPTIONS; then\n\t\tskip \"$LR_READER does not support additional options\"\n\tfi\n\tout=$(do_facet $tgt $LR_READER -c $dev)\n\t[ $? -eq 0 ] || error \"$LR_READER failed on target $tgt device $dev\"\n\techo \"$out\"\n\tnum=$(echo \"$out\" | grep -c \"mdtlov\")\n\t[ \"$num\" -eq $((MDSCOUNT - 1)) ] ||\n\t\terror \"Invalid number of mdtlov clients returned by $LR_READER\"\n\techo -e \"Number of mdtlov clients returned by $LR_READER is '$num'\\n\"\n\n\t# check lr_reader -cr on MDT0000\n\tout=$(do_facet $tgt $LR_READER -cr $dev)\n\t[ $? -eq 0 ] || error \"$LR_READER failed on target $tgt device $dev\"\n\techo \"$out\"\n\techo \"$out\" | grep -q \"^reply_data:$\" ||\n\t\terror \"$LR_READER should have returned 'reply_data' section\"\n\tnum=$(echo \"$out\" | grep -c \"client_generation\")\n\techo -e \"Number of reply data returned by $LR_READER is '$num'\\n\"\n}\nrun_test 252 \"check lr_reader tool\"\n\ntest_253() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tremote_mgs_nodsh && skip \"remote MGS with nodsh\"\n\n\tlocal ostidx=0\n\tlocal rc=0\n\tlocal ost_name=$(ostname_from_index $ostidx)\n\n\t# on the mdt's osc\n\tlocal mdtosc_proc1=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)\n\tdo_facet $SINGLEMDS $LCTL get_param -n \\\n\t\tosp.$mdtosc_proc1.reserved_mb_high ||\n\t\tskip  \"remote MDS does not support reserved_mb_high\"\n\n\trm -rf $DIR/$tdir\n\twait_mds_ost_sync\n\twait_delete_completed\n\tmkdir $DIR/$tdir\n\n\tpool_add $TESTNAME || error \"Pool creation failed\"\n\tpool_add_targets $TESTNAME 0 || error \"Pool add targets failed\"\n\n\t$LFS setstripe $DIR/$tdir -i $ostidx -c 1 -p $FSNAME.$TESTNAME ||\n\t\terror \"Setstripe failed\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.0 bs=1M count=10\n\n\tlocal wms=$(ost_watermarks_set_enospc $tfile $ostidx |\n\t\t    grep \"watermarks\")\n\tstack_trap \"ost_watermarks_clear_enospc $tfile $ostidx $wms\" EXIT\n\n\tlocal oa_status=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_status)\n\techo \"prealloc_status $oa_status\"\n\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.1 bs=1M count=1 &&\n\t\terror \"File creation should fail\"\n\n\t#object allocation was stopped, but we still able to append files\n\tdd if=/dev/zero of=$DIR/$tdir/$tfile.0 bs=1M seek=6 count=5 \\\n\t\toflag=append || error \"Append failed\"\n\n\trm -f $DIR/$tdir/$tfile.0\n\n\t# For this test, we want to delete the files we created to go out of\n\t# space but leave the watermark, so we remain nearly out of space\n\tost_watermarks_enospc_delete_files $tfile $ostidx\n\n\twait_delete_completed\n\n\tsleep_maxage\n\n\tfor i in $(seq 10 12); do\n\t\tdd if=/dev/zero of=$DIR/$tdir/$tfile.$i bs=1M count=1 \\\n\t\t\t2>/dev/null || error \"File creation failed after rm\"\n\tdone\n\n\toa_status=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\tosp.$mdtosc_proc1.prealloc_status)\n\techo \"prealloc_status $oa_status\"\n\n\tif (( oa_status != 0 )); then\n\t\terror \"Object allocation still disable after rm\"\n\tfi\n}\nrun_test 253 \"Check object allocation limit\"\n\ntest_254() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tdo_facet $SINGLEMDS $LCTL get_param -n mdd.$MDT0.changelog_size ||\n\t\tskip \"MDS does not support changelog_size\"\n\n\tlocal cl_user\n\tlocal MDT0=$(facet_svc $SINGLEMDS)\n\n\tchangelog_register || error \"changelog_register failed\"\n\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\n\tlocal size1=$(do_facet $SINGLEMDS \\\n\t\t      $LCTL get_param -n mdd.$MDT0.changelog_size)\n\techo \"Changelog size $size1\"\n\n\trm -rf $DIR/$tdir\n\t$LFS mkdir -i 0 $DIR/$tdir\n\t# change something\n\tmkdir -p $DIR/$tdir/pics/2008/zachy\n\ttouch $DIR/$tdir/pics/2008/zachy/timestamp\n\tcp /etc/hosts $DIR/$tdir/pics/2008/zachy/pic1.jpg\n\tmv $DIR/$tdir/pics/2008/zachy $DIR/$tdir/pics/zach\n\tln $DIR/$tdir/pics/zach/pic1.jpg $DIR/$tdir/pics/2008/portland.jpg\n\tln -s $DIR/$tdir/pics/2008/portland.jpg $DIR/$tdir/pics/desktop.jpg\n\trm $DIR/$tdir/pics/desktop.jpg\n\n\tlocal size2=$(do_facet $SINGLEMDS \\\n\t\t      $LCTL get_param -n mdd.$MDT0.changelog_size)\n\techo \"Changelog size after work $size2\"\n\n\t(( $size2 > $size1 )) ||\n\t\terror \"new Changelog size=$size2 less than old size=$size1\"\n}\nrun_test 254 \"Check changelog size\"\n\nladvise_no_type()\n{\n\tlocal type=$1\n\tlocal file=$2\n\n\tlfs ladvise -a invalid $file 2>&1 | grep \"Valid types\" |\n\t\tawk -F: '{print $2}' | grep $type > /dev/null\n\tif [ $? -ne 0 ]; then\n\t\treturn 0\n\tfi\n\treturn 1\n}\n\nladvise_no_ioctl()\n{\n\tlocal file=$1\n\n\tlfs ladvise -a willread $file > /dev/null 2>&1\n\tif [ $? -eq 0 ]; then\n\t\treturn 1\n\tfi\n\n\tlfs ladvise -a willread $file 2>&1 |\n\t\tgrep \"Inappropriate ioctl for device\" > /dev/null\n\tif [ $? -eq 0 ]; then\n\t\treturn 0\n\tfi\n\treturn 1\n}\n\npercent() {\n\tbc <<<\"scale=2; ($1 - $2) * 100 / $2\"\n}\n\n# run a random read IO workload\n# usage: random_read_iops <filename> <filesize> <iosize>\nrandom_read_iops() {\n\tlocal file=$1\n\tlocal fsize=$2\n\tlocal iosize=${3:-4096}\n\n\t$READS -f $file -s $fsize -b $iosize -n $((fsize / iosize)) -t 60 |\n\t\tsed -e '/^$/d' -e 's#.*s, ##' -e 's#MB/s##'\n}\n\ndrop_file_oss_cache() {\n\tlocal file=\"$1\"\n\tlocal nodes=\"$2\"\n\n\t$LFS ladvise -a dontneed $file 2>/dev/null ||\n\t\tdo_nodes $nodes \"echo 3 > /proc/sys/vm/drop_caches\"\n}\n\nladvise_willread_performance()\n{\n\tlocal repeat=10\n\tlocal average_origin=0\n\tlocal average_cache=0\n\tlocal average_ladvise=0\n\n\tfor ((i = 1; i <= $repeat; i++)); do\n\t\techo \"Iter $i/$repeat: reading without willread hint\"\n\t\tcancel_lru_locks osc\n\t\tdrop_file_oss_cache $DIR/$tfile $(comma_list $(osts_nodes))\n\t\tlocal speed_origin=$(random_read_iops $DIR/$tfile $size)\n\t\techo \"Iter $i/$repeat: uncached speed: $speed_origin\"\n\t\taverage_origin=$(bc <<<\"$average_origin + $speed_origin\")\n\n\t\tcancel_lru_locks osc\n\t\tlocal speed_cache=$(random_read_iops $DIR/$tfile $size)\n\t\techo \"Iter $i/$repeat: OSS cache speed: $speed_cache\"\n\t\taverage_cache=$(bc <<<\"$average_cache + $speed_cache\")\n\n\t\tcancel_lru_locks osc\n\t\tdrop_file_oss_cache $DIR/$tfile $(comma_list $(osts_nodes))\n\t\t$LFS ladvise -a willread $DIR/$tfile || error \"ladvise failed\"\n\t\tlocal speed_ladvise=$(random_read_iops $DIR/$tfile $size)\n\t\techo \"Iter $i/$repeat: ladvise speed: $speed_ladvise\"\n\t\taverage_ladvise=$(bc <<<\"$average_ladvise + $speed_ladvise\")\n\tdone\n\taverage_origin=$(bc <<<\"scale=2; $average_origin / $repeat\")\n\taverage_cache=$(bc <<<\"scale=2; $average_cache / $repeat\")\n\taverage_ladvise=$(bc <<<\"scale=2; $average_ladvise / $repeat\")\n\n\tspeedup_cache=$(percent $average_cache $average_origin)\n\tspeedup_ladvise=$(percent $average_ladvise $average_origin)\n\n\techo \"Average uncached read: $average_origin\"\n\techo \"Average speedup with OSS cached read: \" \\\n\t\t\"$average_cache = +$speedup_cache%\"\n\techo \"Average speedup with ladvise willread: \" \\\n\t\t\"$average_ladvise = +$speedup_ladvise%\"\n\n\tlocal lowest_speedup=20\n\tif [ ${average_cache%.*} -lt $lowest_speedup ]; then\n\t\techo \"Speedup with OSS cached read less than $lowest_speedup%,\" \\\n\t\t\t\"got $average_cache%. Skipping ladvise willread check.\"\n\t\treturn 0\n\tfi\n\n\t# the test won't work on ZFS until it supports 'ladvise dontneed', but\n\t# it is still good to run until then to exercise 'ladvise willread'\n\t! $LFS ladvise -a dontneed $DIR/$tfile &&\n\t\t[ \"$ost1_FSTYPE\" = \"zfs\" ] &&\n\t\techo \"osd-zfs does not support dontneed or drop_caches\" &&\n\t\treturn 0\n\n\tlowest_speedup=$(bc <<<\"scale=2; $average_cache / 2\")\n\t[ ${average_ladvise%.*} -gt $lowest_speedup ] ||\n\t\terror_not_in_vm \"Speedup with willread is less than \" \\\n\t\t\t\"$lowest_speedup%, got $average_ladvise%\"\n}\n\ntest_255a() {\n\t[ $OST1_VERSION -lt $(version_code 2.8.54) ] &&\n\t\tskip \"lustre < 2.8.54 does not support ladvise \"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlfs setstripe -c -1 -i 0 $DIR/$tfile || error \"$tfile failed\"\n\n\tladvise_no_type willread $DIR/$tfile &&\n\t\tskip \"willread ladvise is not supported\"\n\n\tladvise_no_ioctl $DIR/$tfile &&\n\t\tskip \"ladvise ioctl is not supported\"\n\n\tlocal size_mb=100\n\tlocal size=$((size_mb * 1048576))\n\tdd if=/dev/zero of=$DIR/$tfile bs=1048576 count=$size_mb ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\n\tlfs ladvise -a willread $DIR/$tfile ||\n\t\terror \"Ladvise failed with no range argument\"\n\n\tlfs ladvise -a willread -s 0 $DIR/$tfile ||\n\t\terror \"Ladvise failed with no -l or -e argument\"\n\n\tlfs ladvise -a willread -e 1 $DIR/$tfile ||\n\t\terror \"Ladvise failed with only -e argument\"\n\n\tlfs ladvise -a willread -l 1 $DIR/$tfile ||\n\t\terror \"Ladvise failed with only -l argument\"\n\n\tlfs ladvise -a willread -s 2 -e 1 $DIR/$tfile &&\n\t\terror \"End offset should not be smaller than start offset\"\n\n\tlfs ladvise -a willread -s 2 -e 2 $DIR/$tfile &&\n\t\terror \"End offset should not be equal to start offset\"\n\n\tlfs ladvise -a willread -s $size -l 1 $DIR/$tfile ||\n\t\terror \"Ladvise failed with overflowing -s argument\"\n\n\tlfs ladvise -a willread -s 1 -e $((size + 1)) $DIR/$tfile ||\n\t\terror \"Ladvise failed with overflowing -e argument\"\n\n\tlfs ladvise -a willread -s 1 -l $size $DIR/$tfile ||\n\t\terror \"Ladvise failed with overflowing -l argument\"\n\n\tlfs ladvise -a willread -l 1 -e 2 $DIR/$tfile &&\n\t\terror \"Ladvise succeeded with conflicting -l and -e arguments\"\n\n\techo \"Synchronous ladvise should wait\"\n\tlocal delay=4\n#define OBD_FAIL_OST_LADVISE_PAUSE\t 0x237\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param fail_val=$delay fail_loc=0x237\n\n\tlocal start_ts=$SECONDS\n\tlfs ladvise -a willread $DIR/$tfile ||\n\t\terror \"Ladvise failed with no range argument\"\n\tlocal end_ts=$SECONDS\n\tlocal inteval_ts=$((end_ts - start_ts))\n\n\tif [ $inteval_ts -lt $(($delay - 1)) ]; then\n\t\terror \"Synchronous advice didn't wait reply\"\n\tfi\n\n\techo \"Asynchronous ladvise shouldn't wait\"\n\tlocal start_ts=$SECONDS\n\tlfs ladvise -a willread -b $DIR/$tfile ||\n\t\terror \"Ladvise failed with no range argument\"\n\tlocal end_ts=$SECONDS\n\tlocal inteval_ts=$((end_ts - start_ts))\n\n\tif [ $inteval_ts -gt $(($delay / 2)) ]; then\n\t\terror \"Asynchronous advice blocked\"\n\tfi\n\n\tdo_nodes $(comma_list $(osts_nodes)) $LCTL set_param fail_loc=0\n\tladvise_willread_performance\n}\nrun_test 255a \"check 'lfs ladvise -a willread'\"\n\nfacet_meminfo() {\n\tlocal facet=$1\n\tlocal info=$2\n\n\tdo_facet $facet \"cat /proc/meminfo | grep ^${info}:\" | awk '{print $2}'\n}\n\ntest_255b() {\n\t[ $OST1_VERSION -lt $(version_code 2.8.54) ] &&\n\t\tskip \"lustre < 2.8.54 does not support ladvise \"\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlfs setstripe -c 1 -i 0 $DIR/$tfile\n\n\tladvise_no_type dontneed $DIR/$tfile &&\n\t\tskip \"dontneed ladvise is not supported\"\n\n\tladvise_no_ioctl $DIR/$tfile &&\n\t\tskip \"ladvise ioctl is not supported\"\n\n\t! $LFS ladvise -a dontneed $DIR/$tfile &&\n\t\t[ \"$ost1_FSTYPE\" = \"zfs\" ] &&\n\t\tskip \"zfs-osd does not support 'ladvise dontneed'\"\n\n\tlocal size_mb=100\n\tlocal size=$((size_mb * 1048576))\n\t# In order to prevent disturbance of other processes, only check 3/4\n\t# of the memory usage\n\tlocal kibibytes=$((size_mb * 1024 * 3 / 4))\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1048576 count=$size_mb ||\n\t\terror \"dd to $DIR/$tfile failed\"\n\n\t#force write to complete before dropping OST cache & checking memory\n\tsync\n\n\tlocal total=$(facet_meminfo ost1 MemTotal)\n\techo \"Total memory: $total KiB\"\n\n\tdo_facet ost1 \"sync && echo 3 > /proc/sys/vm/drop_caches\"\n\tlocal before_read=$(facet_meminfo ost1 Cached)\n\techo \"Cache used before read: $before_read KiB\"\n\n\tlfs ladvise -a willread $DIR/$tfile ||\n\t\terror \"Ladvise willread failed\"\n\tlocal after_read=$(facet_meminfo ost1 Cached)\n\techo \"Cache used after read: $after_read KiB\"\n\n\tlfs ladvise -a dontneed $DIR/$tfile ||\n\t\terror \"Ladvise dontneed again failed\"\n\tlocal no_read=$(facet_meminfo ost1 Cached)\n\techo \"Cache used after dontneed ladvise: $no_read KiB\"\n\n\tif [ $total -lt $((before_read + kibibytes)) ]; then\n\t\techo \"Memory is too small, abort checking\"\n\t\treturn 0\n\tfi\n\n\tif [ $((before_read + kibibytes)) -gt $after_read ]; then\n\t\terror \"Ladvise willread should use more memory\" \\\n\t\t\t\"than $kibibytes KiB\"\n\tfi\n\n\tif [ $((no_read + kibibytes)) -gt $after_read ]; then\n\t\terror \"Ladvise dontneed should release more memory\" \\\n\t\t\t\"than $kibibytes KiB\"\n\tfi\n}\nrun_test 255b \"check 'lfs ladvise -a dontneed'\"\n\ntest_255c() {\n\t[ $OST1_VERSION -lt $(version_code 2.10.50) ] &&\n\t\tskip \"lustre < 2.10.50 does not support lockahead\"\n\n\tlocal count\n\tlocal new_count\n\tlocal difference\n\tlocal i\n\tlocal rc\n\n\ttest_mkdir -p $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir\n\n\t#test 10 returns only success/failure\n\ti=10\n\tlockahead_test -d $DIR/$tdir -t $i -f $tfile\n\trc=$?\n\tif [ $rc -eq 255 ]; then\n\t\terror \"Ladvise test${i} failed, ${rc}\"\n\tfi\n\n\t#test 11 counts lock enqueue requests, all others count new locks\n\ti=11\n\tcount=$(do_facet ost1 \\\n\t\t$LCTL get_param -n ost.OSS.ost.stats)\n\tcount=$(echo \"$count\" | grep ldlm_extent_enqueue | awk '{ print $2 }')\n\n\tlockahead_test -d $DIR/$tdir -t $i -f $tfile\n\trc=$?\n\tif [ $rc -eq 255 ]; then\n\t\terror \"Ladvise test${i} failed, ${rc}\"\n\tfi\n\n\tnew_count=$(do_facet ost1 \\\n\t\t$LCTL get_param -n ost.OSS.ost.stats)\n\tnew_count=$(echo \"$new_count\" | grep ldlm_extent_enqueue | \\\n\t\t   awk '{ print $2 }')\n\n\tdifference=\"$((new_count - count))\"\n\tif [ $difference -ne $rc ]; then\n\t\terror \"Ladvise test${i}, bad enqueue count, returned \" \\\n\t\t      \"${rc}, actual ${difference}\"\n\tfi\n\n\tfor i in $(seq 12 21); do\n\t\t# If we do not do this, we run the risk of having too many\n\t\t# locks and starting lock cancellation while we are checking\n\t\t# lock counts.\n\t\tcancel_lru_locks osc\n\n\t\tcount=$($LCTL get_param -n \\\n\t\t       ldlm.namespaces.$FSNAME-OST0000*osc-[-0-9a-f]*.lock_unused_count)\n\n\t\tlockahead_test -d $DIR/$tdir -t $i -f $tfile\n\t\trc=$?\n\t\tif [ $rc -eq 255 ]; then\n\t\t\terror \"Ladvise test ${i} failed, ${rc}\"\n\t\tfi\n\n\t\tnew_count=$($LCTL get_param -n \\\n\t\t       ldlm.namespaces.$FSNAME-OST0000*osc-[-0-9a-f]*.lock_unused_count)\n\t\tdifference=\"$((new_count - count))\"\n\n\t\t# Test 15 output is divided by 100 to map down to valid return\n\t\tif [ $i -eq 15 ]; then\n\t\t\trc=\"$((rc * 100))\"\n\t\tfi\n\n\t\tif [ $difference -ne $rc ]; then\n\t\t\terror \"Ladvise test ${i}, bad lock count, returned \" \\\n\t\t\t      \"${rc}, actual ${difference}\"\n\t\tfi\n\tdone\n\n\t#test 22 returns only success/failure\n\ti=22\n\tlockahead_test -d $DIR/$tdir -t $i -f $tfile\n\trc=$?\n\tif [ $rc -eq 255 ]; then\n\t\terror \"Ladvise test${i} failed, ${rc}\"\n\tfi\n}\nrun_test 255c \"suite of ladvise lockahead tests\"\n\ntest_256() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip \"ldiskfs only test\"\n\tchangelog_users $SINGLEMDS | grep \"^cl\" &&\n\t\tskip \"active changelog user\"\n\n\tlocal cl_user\n\tlocal cat_sl\n\tlocal mdt_dev\n\n\tmdt_dev=$(mdsdevname 1)\n\techo $mdt_dev\n\n\tchangelog_register || error \"changelog_register failed\"\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\n\t# change something\n\ttouch $DIR/$tdir/{1..10}\n\n\t# stop the MDT\n\tstop $SINGLEMDS || error \"Fail to stop MDT\"\n\n\t# remount the MDT\n\n\tstart $SINGLEMDS $mdt_dev $MDS_MOUNT_OPTS || error \"Fail to start MDT\"\n\n\t#after mount new plainllog is used\n\ttouch $DIR/$tdir/{11..19}\n\tlocal tmpfile=\"$(mktemp --tmpdir -u $tfile.XXXXXX)\"\n\tstack_trap \"rm -f $tmpfile\"\n\tcat_sl=$(do_facet $SINGLEMDS \"sync; \\\n\t\t $DEBUGFS -c -R 'dump changelog_catalog $tmpfile' $mdt_dev; \\\n\t\t llog_reader $tmpfile | grep -c type=1064553b\")\n\tdo_facet $SINGLEMDS llog_reader $tmpfile\n\n\t[ $cat_sl != 2 ] && error \"Changelog catalog has $cat_sl != 2 slots\"\n\n\tchangelog_clear 0 || error \"changelog_clear failed\"\n\n\tcat_sl=$(do_facet $SINGLEMDS \"sync; \\\n\t\t $DEBUGFS -c -R 'dump changelog_catalog $tmpfile' $mdt_dev; \\\n\t\t llog_reader $tmpfile | grep -c type=1064553b\")\n\n\tif (( cat_sl == 2 )); then\n\t\terror \"Empty plain llog was not deleted from changelog catalog\"\n\telif (( cat_sl != 1 )); then\n\t\terror \"Active plain llog shouldn't be deleted from catalog\"\n\tfi\n}\nrun_test 256 \"Check llog delete for empty and not full state\"\n\ntest_257() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.8.55) ]] &&\n\t\tskip \"Need MDS version at least 2.8.55\"\n\n\ttest_mkdir $DIR/$tdir\n\n\tsetfattr -n trusted.name1 -v value1 $DIR/$tdir ||\n\t\terror \"setfattr -n trusted.name1=value1 $DIR/$tdir failed\"\n\tstat $DIR/$tdir\n\n#define OBD_FAIL_MDS_XATTR_REP\t\t\t0x161\n\tlocal mdtidx=$($LFS getstripe -m $DIR/$tdir)\n\tlocal facet=mds$((mdtidx + 1))\n\tset_nodes_failloc $(facet_active_host $facet) 0x80000161\n\tgetfattr -n trusted.name1 $DIR/$tdir 2> /dev/null\n\n\tstop $facet || error \"stop MDS failed\"\n\tstart $facet $(mdsdevname $((mdtidx + 1))) $MDS_MOUNT_OPTS ||\n\t\terror \"start MDS fail\"\n\twait_recovery_complete $facet\n}\nrun_test 257 \"xattr locks are not lost\"\n\n# Verify we take the i_mutex when security requires it\ntest_258a() {\n#define OBD_FAIL_IMUTEX_SEC 0x141c\n\t$LCTL set_param fail_loc=0x141c\n\ttouch $DIR/$tfile\n\tchmod u+s $DIR/$tfile\n\tchmod a+rwx $DIR/$tfile\n\t$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 oflag=append\n\tRC=$?\n\tif [ $RC -ne 0 ]; then\n\t\terror \"error, failed to take i_mutex, rc=$?\"\n\tfi\n\trm -f $DIR/$tfile\n}\nrun_test 258a \"verify i_mutex security behavior when suid attributes is set\"\n\n# Verify we do NOT take the i_mutex in the normal case\ntest_258b() {\n#define OBD_FAIL_IMUTEX_NOSEC 0x141d\n\t$LCTL set_param fail_loc=0x141d\n\ttouch $DIR/$tfile\n\tchmod a+rwx $DIR\n\tchmod a+rw $DIR/$tfile\n\t$RUNAS dd if=/dev/zero of=$DIR/$tfile bs=4k count=1 oflag=append\n\tRC=$?\n\tif [ $RC -ne 0 ]; then\n\t\terror \"error, took i_mutex unnecessarily, rc=$?\"\n\tfi\n\trm -f $DIR/$tfile\n\n}\nrun_test 258b \"verify i_mutex security behavior\"\n\ntest_259() {\n\tlocal file=$DIR/$tfile\n\tlocal before\n\tlocal after\n\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip \"ldiskfs only test\"\n\n\tstack_trap \"rm -f $file\" EXIT\n\n\twait_delete_completed\n\tbefore=$(do_facet ost1 \"$LCTL get_param -n osd-*.*OST0000.kbytesfree\")\n\techo \"before: $before\"\n\n\t$LFS setstripe -i 0 -c 1 $file\n\tdd if=/dev/zero of=$file bs=1M count=10 || error \"couldn't write\"\n\tsync_all_data\n\tafter=$(do_facet ost1 \"$LCTL get_param -n osd-*.*OST0000.kbytesfree\")\n\techo \"after write: $after\"\n\n#define OBD_FAIL_OSD_FAIL_AT_TRUNCATE          0x2301\n\tdo_facet ost1 $LCTL set_param fail_loc=0x2301\n\t$TRUNCATE $file 0\n\tafter=$(do_facet ost1 \"$LCTL get_param -n osd-*.*OST0000.kbytesfree\")\n\techo \"after truncate: $after\"\n\n\tstop ost1\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS || error \"cannot start ost1\"\n\tsleep 2\n\tafter=$(do_facet ost1 \"$LCTL get_param -n osd-*.*OST0000.kbytesfree\")\n\techo \"after restart: $after\"\n\t[ $((after - before)) -ge $(fs_log_size ost1) ] &&\n\t\terror \"missing truncate?\"\n\n\treturn 0\n}\nrun_test 259 \"crash at delayed truncate\"\n\ntest_260() {\n#define OBD_FAIL_MDC_CLOSE               0x806\n\t$LCTL set_param fail_loc=0x80000806\n\ttouch $DIR/$tfile\n\n}\nrun_test 260 \"Check mdc_close fail\"\n\n### Data-on-MDT sanity tests ###\ntest_270a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55 for DoM\"\n\n\t# create DoM file\n\tlocal dom=$DIR/$tdir/dom_file\n\tlocal tmp=$DIR/$tdir/tmp_file\n\n\tmkdir -p $DIR/$tdir\n\n\t# basic checks for DoM component creation\n\t$LFS setstripe -E 1024K -E 2048K -L mdt $dom 2>/dev/null &&\n\t\terror \"Can set MDT layout to non-first entry\"\n\n\t$LFS setstripe -E 1024K -L mdt -E 2048K -L mdt $dom 2>/dev/null &&\n\t\terror \"Can define multiple entries as MDT layout\"\n\n\t$LFS setstripe -E 1M -L mdt $dom || error \"Can't create DoM layout\"\n\n\t[ $($LFS getstripe -L $dom) == \"mdt\" ] || error \"bad pattern\"\n\t[ $($LFS getstripe -c $dom) == 0 ] || error \"bad stripe count\"\n\t[ $($LFS getstripe -S $dom) == 1048576 ] || error \"bad stripe size\"\n\n\tlocal mdtidx=$($LFS getstripe -m $dom)\n\tlocal mdtname=MDT$(printf %04x $mdtidx)\n\tlocal facet=mds$((mdtidx + 1))\n\tlocal space_check=1\n\n\t# Skip free space checks with ZFS\n\t[ \"$(facet_fstype $facet)\" == \"zfs\" ] && space_check=0\n\n\t# write\n\tsync\n\tlocal size_tmp=$((65536 * 3))\n\tlocal mdtfree1=$(do_facet $facet \\\n\t\t\t lctl get_param -n osd*.*$mdtname.kbytesfree)\n\n\tdd if=/dev/urandom of=$tmp bs=1024 count=$((size_tmp / 1024))\n\t# check also direct IO along write\n\t# IO size must be a multiple of PAGE_SIZE on all platforms (ARM=64KB)\n\tdd if=$tmp of=$dom bs=65536 count=$((size_tmp / 65536)) oflag=direct\n\tsync\n\tcmp $tmp $dom || error \"file data is different\"\n\t[ $(stat -c%s $dom) == $size_tmp ] ||\n\t\terror \"bad size after write: $(stat -c%s $dom) != $size_tmp\"\n\tif [ $space_check == 1 ]; then\n\t\tlocal mdtfree2=$(do_facet $facet \\\n\t\t\t\t lctl get_param -n osd*.*$mdtname.kbytesfree)\n\n\t\t# increase in usage from by $size_tmp\n\t\t[ $(($mdtfree1 - $mdtfree2)) -ge $((size_tmp / 1024)) ] ||\n\t\t\terror \"MDT free space wrong after write: \" \\\n\t\t\t      \"$mdtfree1 >= $mdtfree2 + $size_tmp/1024\"\n\tfi\n\n\t# truncate\n\tlocal size_dom=10000\n\n\t$TRUNCATE $dom $size_dom\n\t[ $(stat -c%s $dom) == $size_dom ] ||\n\t\terror \"bad size after truncate: $(stat -c%s $dom) != $size_dom\"\n\tif [ $space_check == 1 ]; then\n\t\tmdtfree1=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t# decrease in usage from $size_tmp to new $size_dom\n\t\t[ $(($mdtfree1 - $mdtfree2)) -ge \\\n\t\t  $(((size_tmp - size_dom) / 1024)) ] ||\n\t\t\terror \"MDT free space is wrong after truncate: \" \\\n\t\t\t      \"$mdtfree1 >= $mdtfree2 + ($size_tmp - $size_dom) / 1024\"\n\tfi\n\n\t# append\n\tcat $tmp >> $dom\n\tsync\n\tsize_dom=$((size_dom + size_tmp))\n\t[ $(stat -c%s $dom) == $size_dom ] ||\n\t\terror \"bad size after append: $(stat -c%s $dom) != $size_dom\"\n\tif [ $space_check == 1 ]; then\n\t\tmdtfree2=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t# increase in usage by $size_tmp from previous\n\t\t[ $(($mdtfree1 - $mdtfree2)) -ge $((size_tmp / 1024)) ] ||\n\t\t\terror \"MDT free space is wrong after append: \" \\\n\t\t\t      \"$mdtfree1 >= $mdtfree2 + $size_tmp/1024\"\n\tfi\n\n\t# delete\n\trm $dom\n\tif [ $space_check == 1 ]; then\n\t\tmdtfree1=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t# decrease in usage by $size_dom from previous\n\t\t[ $(($mdtfree1 - $mdtfree2)) -ge $((size_dom / 1024)) ] ||\n\t\t\terror \"MDT free space is wrong after removal: \" \\\n\t\t\t      \"$mdtfree1 >= $mdtfree2 + $size_dom/1024\"\n\tfi\n\n\t# combined striping\n\t$LFS setstripe -E 1024K -L mdt -E EOF $dom ||\n\t\terror \"Can't create DoM + OST striping\"\n\n\tsize_tmp=2031616 # must be a multiple of PAGE_SIZE=65536 on ARM\n\tdd if=/dev/urandom of=$tmp bs=1024 count=$((size_tmp / 1024))\n\t# check also direct IO along write\n\tdd if=$tmp of=$dom bs=65536 count=$((size_tmp / 65536)) oflag=direct\n\tsync\n\tcmp $tmp $dom || error \"file data is different\"\n\t[ $(stat -c%s $dom) == $size_tmp ] ||\n\t\terror \"bad size after write: $(stat -c%s $dom) != $size_tmp\"\n\trm $dom $tmp\n\n\treturn 0\n}\nrun_test 270a \"DoM: basic functionality tests\"\n\ntest_270b() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dom=$DIR/$tdir/dom_file\n\tlocal max_size=1048576\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E $max_size -L mdt $dom\n\n\t# truncate over the limit\n\t$TRUNCATE $dom $(($max_size + 1)) &&\n\t\terror \"successful truncate over the maximum size\"\n\t# write over the limit\n\tdd if=/dev/zero of=$dom bs=$max_size seek=1 count=1 &&\n\t\terror \"successful write over the maximum size\"\n\t# append over the limit\n\tdd if=/dev/zero of=$dom bs=$(($max_size - 3)) count=1\n\techo \"12345\" >> $dom && error \"successful append over the maximum size\"\n\trm $dom\n\n\treturn 0\n}\nrun_test 270b \"DoM: maximum size overflow checks for DoM-only file\"\n\ntest_270c() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\t# check files inherit DoM EA\n\ttouch $DIR/$tdir/first\n\t[ $($LFS getstripe -L $DIR/$tdir/first) == \"mdt\" ] ||\n\t\terror \"bad pattern\"\n\t[ $($LFS getstripe -c $DIR/$tdir/first) == 0 ] ||\n\t\terror \"bad stripe count\"\n\t[ $($LFS getstripe -S $DIR/$tdir/first) == 1048576 ] ||\n\t\terror \"bad stripe size\"\n\n\t# check directory inherits DoM EA and uses it as default\n\tmkdir $DIR/$tdir/subdir\n\ttouch $DIR/$tdir/subdir/second\n\t[ $($LFS getstripe -L $DIR/$tdir/subdir/second) == \"mdt\" ] ||\n\t\terror \"bad pattern in sub-directory\"\n\t[ $($LFS getstripe -c $DIR/$tdir/subdir/second) == 0 ] ||\n\t\terror \"bad stripe count in sub-directory\"\n\t[ $($LFS getstripe -S $DIR/$tdir/subdir/second) == 1048576 ] ||\n\t\terror \"bad stripe size in sub-directory\"\n\treturn 0\n}\nrun_test 270c \"DoM: DoM EA inheritance tests\"\n\ntest_270d() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\t# inherit default DoM striping\n\tmkdir $DIR/$tdir/subdir\n\ttouch $DIR/$tdir/subdir/f1\n\n\t# change default directory striping\n\t$LFS setstripe -c 1 $DIR/$tdir/subdir\n\ttouch $DIR/$tdir/subdir/f2\n\t[ $($LFS getstripe -c $DIR/$tdir/subdir/f2) == 1 ] ||\n\t\terror \"wrong default striping in file 2\"\n\t[ $($LFS getstripe -L $DIR/$tdir/subdir/f2) == \"raid0\" ] ||\n\t\terror \"bad pattern in file 2\"\n\treturn 0\n}\nrun_test 270d \"DoM: change striping from DoM to RAID0\"\n\ntest_270e() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir/dom\n\tmkdir -p $DIR/$tdir/norm\n\tDOMFILES=20\n\tNORMFILES=10\n\t$LFS setstripe -E 1M -L mdt $DIR/$tdir/dom\n\t$LFS setstripe -i 0 -S 2M $DIR/$tdir/norm\n\n\tcreatemany -o $DIR/$tdir/dom/dom- $DOMFILES\n\tcreatemany -o $DIR/$tdir/norm/norm- $NORMFILES\n\n\t# find DoM files by layout\n\tNUM=$($LFS find -L mdt -type f $DIR/$tdir 2>/dev/null | wc -l)\n\t[ $NUM -eq  $DOMFILES ] ||\n\t\terror \"lfs find -L: found $NUM, expected $DOMFILES\"\n\techo \"Test 1: lfs find 20 DOM files by layout: OK\"\n\n\t# there should be 1 dir with default DOM striping\n\tNUM=$($LFS find -L mdt -type d $DIR/$tdir 2>/dev/null | wc -l)\n\t[ $NUM -eq  1 ] ||\n\t\terror \"lfs find -L: found $NUM, expected 1 dir\"\n\techo \"Test 2: lfs find 1 DOM dir by layout: OK\"\n\n\t# find DoM files by stripe size\n\tNUM=$($LFS find -S -1200K -type f $DIR/$tdir 2>/dev/null | wc -l)\n\t[ $NUM -eq  $DOMFILES ] ||\n\t\terror \"lfs find -S: found $NUM, expected $DOMFILES\"\n\techo \"Test 4: lfs find 20 DOM files by stripe size: OK\"\n\n\t# find files by stripe offset except DoM files\n\tNUM=$($LFS find -i 0 -type f $DIR/$tdir 2>/dev/null | wc -l)\n\t[ $NUM -eq  $NORMFILES ] ||\n\t\terror \"lfs find -i: found $NUM, expected $NORMFILES\"\n\techo \"Test 5: lfs find no DOM files by stripe index: OK\"\n\treturn 0\n}\nrun_test 270e \"DoM: lfs find with DoM files test\"\n\ntest_270f() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal mdtname=${FSNAME}-MDT0000-mdtlov\n\tlocal dom=$DIR/$tdir/dom_file\n\tlocal dom_limit_saved=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\t\tlod.$mdtname.dom_stripesize)\n\tlocal dom_limit=131072\n\n\tdo_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=$dom_limit\n\tlocal dom_current=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\t\tlod.$mdtname.dom_stripesize)\n\t[ ${dom_limit} -eq ${dom_current} ] ||\n\t\terror \"Cannot change per-MDT DoM stripe limit to $dom_limit\"\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir\n\t$LFS setstripe -d $DIR/$tdir\n\t$LFS setstripe -E $dom_limit -L mdt $DIR/$tdir ||\n\t\terror \"Can't set directory default striping\"\n\n\t# exceed maximum stripe size\n\t$LFS setstripe -E $((dom_limit * 2)) -L mdt $dom ||\n\t\terror \"Can't create file with $((dom_limit * 2)) DoM stripe\"\n\t[ $($LFS getstripe -S $dom) -eq $((dom_limit * 2)) ] &&\n\t\terror \"Able to create DoM component size more than LOD limit\"\n\n\tdo_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=0\n\tdom_current=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\t\tlod.$mdtname.dom_stripesize)\n\t[ 0 -eq ${dom_current} ] ||\n\t\terror \"Can't set zero DoM stripe limit\"\n\trm $dom\n\n\t# attempt to create DoM file on server with disabled DoM should\n\t# remove DoM entry from layout and be succeed\n\t$LFS setstripe -E $dom_limit -L mdt -E -1 $dom ||\n\t\terror \"Can't create DoM file (DoM is disabled)\"\n\t[ $($LFS getstripe -L $dom) == \"mdt\" ] &&\n\t\terror \"File has DoM component while DoM is disabled\"\n\trm $dom\n\n\t# attempt to create DoM file with only DoM stripe should return error\n\t$LFS setstripe -E $dom_limit -L mdt $dom &&\n\t\terror \"Able to create DoM-only file while DoM is disabled\"\n\n\t# too low values to be aligned with smallest stripe size 64K\n\tdo_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=30000\n\tdom_current=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\t\tlod.$mdtname.dom_stripesize)\n\t[ 30000 -eq ${dom_current} ] &&\n\t\terror \"Can set too small DoM stripe limit\"\n\n\t# 64K is a minimal stripe size in Lustre, expect limit of that size\n\t[ 65536 -eq ${dom_current} ] ||\n\t\terror \"Limit is not set to 64K but ${dom_current}\"\n\n\tdo_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=2147483648\n\tdom_current=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\t\tlod.$mdtname.dom_stripesize)\n\techo $dom_current\n\t[ 2147483648 -eq ${dom_current} ] &&\n\t\terror \"Can set too large DoM stripe limit\"\n\n\tdo_facet mds1 $LCTL set_param -n \\\n\t\t\t\tlod.$mdtname.dom_stripesize=$((dom_limit * 2))\n\t$LFS setstripe -E $((dom_limit * 2)) -L mdt $dom ||\n\t\terror \"Can't create DoM component size after limit change\"\n\tdo_facet mds1 $LCTL set_param -n \\\n\t\t\t\tlod.$mdtname.dom_stripesize=$((dom_limit / 2))\n\t$LFS setstripe -E $dom_limit -L mdt ${dom}_big ||\n\t\terror \"Can't create DoM file after limit decrease\"\n\t[ $($LFS getstripe -S ${dom}_big) -eq $((dom_limit / 2)) ] ||\n\t\terror \"Can create big DoM component after limit decrease\"\n\ttouch ${dom}_def ||\n\t\terror \"Can't create file with old default layout\"\n\n\tdo_facet mds1 $LCTL set_param -n lod.*.dom_stripesize=$dom_limit_saved\n\treturn 0\n}\nrun_test 270f \"DoM: maximum DoM stripe size checks\"\n\ntest_270g() {\n\t[ $MDS1_VERSION -ge $(version_code 2.13.52) ] ||\n\t\tskip \"Need MDS version at least 2.13.52\"\n\tlocal dom=$DIR/$tdir/$tfile\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir\n\tlocal lodname=${FSNAME}-MDT0000-mdtlov\n\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_lustre_params mds1 \"lod.${lodname}.dom_stripesize_max_kb\" > $save\n\tsave_lustre_params mds1 \"lod.${lodname}.dom_threshold_free_mb\" >> $save\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\n\tlocal dom_limit=1024\n\tlocal dom_threshold=\"50%\"\n\n\t$LFS setstripe -d $DIR/$tdir\n\t$LFS setstripe -E ${dom_limit}K -L mdt $DIR/$tdir ||\n\t\terror \"Can't set directory default striping\"\n\n\tdo_facet mds1 $LCTL set_param -n \\\n\t\t\t\tlod.${lodname}.dom_stripesize_max_kb=$dom_limit\n\t# set 0 threshold and create DOM file to change tunable stripesize\n\tdo_facet mds1 $LCTL set_param -n lod.${lodname}.dom_threshold_free_mb=0\n\t$LFS setstripe -E ${dom_limit}K -L mdt -E -1 $dom ||\n\t\terror \"Failed to create $dom file\"\n\t# now tunable dom_cur_stripesize should reach maximum\n\tlocal dom_current=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\tlod.${lodname}.dom_stripesize_cur_kb)\n\t[[ $dom_current == $dom_limit ]] ||\n\t\terror \"Current DOM stripesize is not maximum\"\n\trm $dom\n\n\t# set threshold for further tests\n\tdo_facet mds1 $LCTL set_param -n \\\n\t\t\tlod.${lodname}.dom_threshold_free_mb=$dom_threshold\n\techo \"DOM threshold is $dom_threshold free space\"\n\tlocal dom_def\n\tlocal dom_set\n\t# Spoof bfree to exceed threshold\n\t#define OBD_FAIL_MDS_STATFS_SPOOF   0x168\n\tdo_facet mds1 $LCTL set_param -n fail_loc=0x0168\n\tfor spfree in 40 20 0 15 30 55; do\n\t\tdo_facet mds1 $LCTL set_param -n fail_val=$spfree\n\t\t$LFS setstripe -E ${dom_limit}K -L mdt -E -1 $dom ||\n\t\t\terror \"Failed to create $dom file\"\n\t\tdom_def=$(do_facet mds1 $LCTL get_param -n \\\n\t\t\t\t\tlod.${lodname}.dom_stripesize_cur_kb)\n\t\techo \"Free space: ${spfree}%, default DOM stripe: ${dom_def}K\"\n\t\t[[ $dom_def != $dom_current ]] ||\n\t\t\terror \"Default stripe size was not changed\"\n\t\tif [[ $spfree > 0 ]] ; then\n\t\t\tdom_set=$($LFS getstripe -S $dom)\n\t\t\t[[ $dom_set == $((dom_def * 1024)) ]] ||\n\t\t\t\terror \"DOM component size is still old\"\n\t\telse\n\t\t\t[[ $($LFS getstripe -L $dom) != \"mdt\" ]] ||\n\t\t\t\terror \"DoM component is set with no free space\"\n\t\tfi\n\t\trm $dom\n\t\tdom_current=$dom_def\n\tdone\n}\nrun_test 270g \"DoM: default DoM stripe size depends on free space\"\n\ntest_270h() {\n\t[[ $MDS1_VERSION -ge $(version_code 2.13.53) ]] ||\n\t\tskip \"Need MDS version at least 2.13.53\"\n\n\tlocal mdtname=${FSNAME}-MDT0000-mdtlov\n\tlocal dom=$DIR/$tdir/$tfile\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params mds1 \"lod.*.dom_stripesize\" > $save\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir\n\t$LFS setstripe -E 1M -c1  -E -1 -c2 ${dom}_1 ||\n\t\terror \"can't create OST file\"\n\t# mirrored file with DOM entry in the second mirror\n\t$LFS mirror extend -N -E 1M -L mdt -E eof -c2 ${dom}_1 ||\n\t\terror \"can't create mirror with DoM component\"\n\n\tdo_facet mds1 $LCTL set_param -n lod.$mdtname.dom_stripesize=0\n\n\t# DOM component in the middle and has other enries in the same mirror,\n\t# should succeed but lost DoM component\n\t$LFS setstripe --copy=${dom}_1 $dom ||\n\t\terror \"Can't create file from OST|DOM mirror layout\"\n\t# check new file has no DoM layout after all\n\t[[ $($LFS getstripe -L $dom) != \"mdt\" ]] ||\n\t\terror \"File has DoM component while DoM is disabled\"\n}\nrun_test 270h \"DoM: DoM stripe removal when disabled on server\"\n\ntest_271a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dom=$DIR/$tdir/dom\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt $dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tdd if=/dev/zero of=$dom bs=4096 count=1 || return 1\n\tcat $dom > /dev/null\n\tlocal reads=$(lctl get_param -n mdc.*.stats | grep -c ost_read)\n\t[ $reads -eq 0 ] || error \"Unexpected $reads READ RPCs\"\n\tls $dom\n\trm -f $dom\n}\nrun_test 271a \"DoM: data is cached for read after write\"\n\ntest_271b() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dom=$DIR/$tdir/dom\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tdd if=/dev/zero of=$dom bs=4096 count=1 || return 1\n\tcancel_lru_locks mdc\n\t$CHECKSTAT -t file -s 4096 $dom || error \"stat #1 fails\"\n\t# second stat to check size is cached on client\n\t$CHECKSTAT -t file -s 4096 $dom || error \"stat #2 fails\"\n\tlocal gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls -eq 0 ] || error \"Unexpected $gls glimpse RPCs\"\n\trm -f $dom\n}\nrun_test 271b \"DoM: no glimpse RPC for stat (DoM only file)\"\n\ntest_271ba() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dom=$DIR/$tdir/dom\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tlctl set_param -n osc.*.stats=clear\n\tdd if=/dev/zero of=$dom bs=2048K count=1 || return 1\n\tcancel_lru_locks mdc\n\t$CHECKSTAT -t file -s 2097152 $dom || error \"stat\"\n\t# second stat to check size is cached on client\n\t$CHECKSTAT -t file -s 2097152 $dom || error \"stat\"\n\tlocal gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls == 0 ] || error \"Unexpected $gls glimpse RPCs\"\n\tlocal gls=$(lctl get_param -n osc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls == 0 ] || error \"Unexpected $gls OSC glimpse RPCs\"\n\trm -f $dom\n}\nrun_test 271ba \"DoM: no glimpse RPC for stat (combined file)\"\n\n\nget_mdc_stats() {\n\tlocal mdtidx=$1\n\tlocal param=$2\n\tlocal mdt=MDT$(printf %04x $mdtidx)\n\n\tif [ -z $param ]; then\n\t\tlctl get_param -n mdc.*$mdt*.stats\n\telse\n\t\tlctl get_param -n mdc.*$mdt*.stats | awk \"/$param/\"'{print $2}'\n\tfi\n}\n\ntest_271c() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tlocal dom=$DIR/$tdir/dom\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\tlocal mdtidx=$($LFS getstripe -m $DIR/$tdir)\n\tlocal facet=mds$((mdtidx + 1))\n\n\tcancel_lru_locks mdc\n\tdo_facet $facet lctl set_param -n mdt.*.dom_lock=0\n\tcreatemany -o $dom 1000\n\tlctl set_param -n mdc.*.stats=clear\n\tsmalliomany -w $dom 1000 200\n\tget_mdc_stats $mdtidx\n\tlocal enq=$(get_mdc_stats $mdtidx ldlm_ibits_enqueue)\n\t# Each file has 1 open, 1 IO enqueues, total 2000\n\t# but now we have also +1 getxattr for security.capability, total 3000\n\t[ $enq -ge 2000 ] || error \"Too few enqueues $enq, expected > 2000\"\n\tunlinkmany $dom 1000\n\n\tcancel_lru_locks mdc\n\tdo_facet $facet lctl set_param -n mdt.*.dom_lock=1\n\tcreatemany -o $dom 1000\n\tlctl set_param -n mdc.*.stats=clear\n\tsmalliomany -w $dom 1000 200\n\tlocal enq_2=$(get_mdc_stats $mdtidx ldlm_ibits_enqueue)\n\t# Expect to see reduced amount of RPCs by 1000 due to single enqueue\n\t# for OPEN and IO lock.\n\t[ $((enq - enq_2)) -ge 1000 ] ||\n\t\terror \"Too many enqueues $enq_2, expected about $((enq - 1000))\"\n\tunlinkmany $dom 1000\n\treturn 0\n}\nrun_test 271c \"DoM: IO lock at open saves enqueue RPCs\"\n\ncleanup_271def_tests() {\n\ttrap 0\n\trm -f $1\n}\n\ntest_271d() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.57) ] &&\n\t\tskip \"Need MDS version at least 2.10.57\"\n\n\tlocal dom=$DIR/$tdir/dom\n\tlocal tmp=$TMP/$tfile\n\ttrap \"cleanup_271def_tests $tmp\" EXIT\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\tlocal mdtidx=$($LFS getstripe --mdt-index $DIR/$tdir)\n\n\tcancel_lru_locks mdc\n\tdd if=/dev/urandom of=$tmp bs=1000 count=1\n\tdd if=$tmp of=$dom bs=1000 count=1\n\tcancel_lru_locks mdc\n\n\tcat /etc/hosts >> $tmp\n\tlctl set_param -n mdc.*.stats=clear\n\n\t# append data to the same file it should update local page\n\techo \"Append to the same page\"\n\tcat /etc/hosts >> $dom\n\tlocal num=$(get_mdc_stats $mdtidx ost_read)\n\tlocal ra=$(get_mdc_stats $mdtidx req_active)\n\tlocal rw=$(get_mdc_stats $mdtidx req_waittime)\n\n\t[ -z $num ] || error \"$num READ RPC occured\"\n\t[ $ra == $rw ] || error \"$((ra - rw)) resend occured\"\n\techo \"... DONE\"\n\n\t# compare content\n\tcmp $tmp $dom || error \"file miscompare\"\n\n\tcancel_lru_locks mdc\n\tlctl set_param -n mdc.*.stats=clear\n\n\techo \"Open and read file\"\n\tcat $dom > /dev/null\n\tlocal num=$(get_mdc_stats $mdtidx ost_read)\n\tlocal ra=$(get_mdc_stats $mdtidx req_active)\n\tlocal rw=$(get_mdc_stats $mdtidx req_waittime)\n\n\t[ -z $num ] || error \"$num READ RPC occured\"\n\t[ $ra == $rw ] || error \"$((ra - rw)) resend occured\"\n\techo \"... DONE\"\n\n\t# compare content\n\tcmp $tmp $dom || error \"file miscompare\"\n\n\treturn 0\n}\nrun_test 271d \"DoM: read on open (1K file in reply buffer)\"\n\ntest_271f() {\n\t[ $MDS1_VERSION -lt $(version_code 2.10.57) ] &&\n\t\tskip \"Need MDS version at least 2.10.57\"\n\n\tlocal dom=$DIR/$tdir/dom\n\tlocal tmp=$TMP/$tfile\n\ttrap \"cleanup_271def_tests $tmp\" EXIT\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\tlocal mdtidx=$($LFS getstripe --mdt-index $DIR/$tdir)\n\n\tcancel_lru_locks mdc\n\tdd if=/dev/urandom of=$tmp bs=265000 count=1\n\tdd if=$tmp of=$dom bs=265000 count=1\n\tcancel_lru_locks mdc\n\tcat /etc/hosts >> $tmp\n\tlctl set_param -n mdc.*.stats=clear\n\n\techo \"Append to the same page\"\n\tcat /etc/hosts >> $dom\n\tlocal num=$(get_mdc_stats $mdtidx ost_read)\n\tlocal ra=$(get_mdc_stats $mdtidx req_active)\n\tlocal rw=$(get_mdc_stats $mdtidx req_waittime)\n\n\t[ -z $num ] || error \"$num READ RPC occured\"\n\t[ $ra == $rw ] || error \"$((ra - rw)) resend occured\"\n\techo \"... DONE\"\n\n\t# compare content\n\tcmp $tmp $dom || error \"file miscompare\"\n\n\tcancel_lru_locks mdc\n\tlctl set_param -n mdc.*.stats=clear\n\n\techo \"Open and read file\"\n\tcat $dom > /dev/null\n\tlocal num=$(get_mdc_stats $mdtidx ost_read)\n\tlocal ra=$(get_mdc_stats $mdtidx req_active)\n\tlocal rw=$(get_mdc_stats $mdtidx req_waittime)\n\n\t[ -z $num ] && num=0\n\t[ $num -eq 1 ] || error \"expect 1 READ RPC, $num occured\"\n\t[ $ra == $rw ] || error \"$((ra - rw)) resend occured\"\n\techo \"... DONE\"\n\n\t# compare content\n\tcmp $tmp $dom || error \"file miscompare\"\n\n\treturn 0\n}\nrun_test 271f \"DoM: read on open (200K file and read tail)\"\n\ntest_271g() {\n\t[[ $($LCTL get_param mdc.*.import) =~ async_discard ]] ||\n\t\tskip \"Skipping due to old client or server version\"\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR1/$tfile\n\t# to get layout\n\t$CHECKSTAT -t file $DIR1/$tfile\n\n\t$MULTIOP $DIR1/$tfile Ow40960_w4096c &\n\tMULTIOP_PID=$!\n\tsleep 1\n\t#define OBD_FAIL_LDLM_CANCEL_BL_CB_RACE\n\t$LCTL set_param fail_loc=0x80000314\n\trm $DIR1/$tfile || error \"Unlink fails\"\n\tRC=$?\n\tkill -USR1 $MULTIOP_PID && wait $MULTIOP_PID || error \"multiop failure\"\n\t[ $RC -eq 0 ] || error \"Failed write to stale object\"\n}\nrun_test 271g \"Discard DoM data vs client flush race\"\n\ntest_272a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS version at least 2.11.50\"\n\n\tlocal dom=$DIR/$tdir/dom\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 256K -L mdt -E -1 -c1 $dom\n\tdd if=/dev/urandom of=$dom bs=512K count=1 ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\n\t$LFS migrate -E 256K -L mdt -E -1 -c2 $dom ||\n\t\terror \"failed to migrate to the same DoM component\"\n\n\tlocal new_md5=$(md5sum $dom)\n\n\t[ \"$old_md5\" == \"$new_md5\" ] ||\n\t\terror \"md5sum differ: $old_md5, $new_md5\"\n\n\t[ $($LFS getstripe -c $dom) -eq 2 ] ||\n\t\terror \"bad final stripe count: $($LFS getstripe -c $dom) != 2\"\n}\nrun_test 272a \"DoM migration: new layout with the same DOM component\"\n\ntest_272b() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS version at least 2.11.50\"\n\n\tlocal dom=$DIR/$tdir/dom\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom\n\n\tlocal mdtidx=$($LFS getstripe -m $dom)\n\tlocal mdtname=MDT$(printf %04x $mdtidx)\n\tlocal facet=mds$((mdtidx + 1))\n\n\tlocal mdtfree1=$(do_facet $facet \\\n\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\tdd if=/dev/urandom of=$dom bs=2M count=1 ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\tcancel_lru_locks mdc\n\tlocal mdtfree1=$(do_facet $facet \\\n\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\n\t$LFS migrate -c2 $dom ||\n\t\terror \"failed to migrate to the new composite layout\"\n\t[ $($LFS getstripe -L $dom) != 'mdt' ] ||\n\t\terror \"MDT stripe was not removed\"\n\n\tcancel_lru_locks mdc\n\tlocal new_md5=$(md5sum $dom)\n\t[ \"$old_md5\" == \"$new_md5\" ] ||\n\t\terror \"$old_md5 != $new_md5\"\n\n\t# Skip free space checks with ZFS\n\tif [ \"$(facet_fstype $facet)\" != \"zfs\" ]; then\n\t\tlocal mdtfree2=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t[ $mdtfree2 -gt $mdtfree1 ] ||\n\t\t\terror \"MDT space is not freed after migration\"\n\tfi\n\treturn 0\n}\nrun_test 272b \"DoM migration: DOM file to the OST-striped file (plain)\"\n\ntest_272c() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS version at least 2.11.50\"\n\n\tlocal dom=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom\n\n\tlocal mdtidx=$($LFS getstripe -m $dom)\n\tlocal mdtname=MDT$(printf %04x $mdtidx)\n\tlocal facet=mds$((mdtidx + 1))\n\n\tdd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\tcancel_lru_locks mdc\n\tlocal mdtfree1=$(do_facet $facet \\\n\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\n\t$LFS migrate -E 2M -c1 -E -1 -c2 $dom ||\n\t\terror \"failed to migrate to the new composite layout\"\n\t[ $($LFS getstripe -L $dom) == 'mdt' ] &&\n\t\terror \"MDT stripe was not removed\"\n\n\tcancel_lru_locks mdc\n\tlocal new_md5=$(md5sum $dom)\n\t[ \"$old_md5\" == \"$new_md5\" ] ||\n\t\terror \"$old_md5 != $new_md5\"\n\n\t# Skip free space checks with ZFS\n\tif [ \"$(facet_fstype $facet)\" != \"zfs\" ]; then\n\t\tlocal mdtfree2=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t[ $mdtfree2 -gt $mdtfree1 ] ||\n\t\t\terror \"MDS space is not freed after migration\"\n\tfi\n\treturn 0\n}\nrun_test 272c \"DoM migration: DOM file to the OST-striped file (composite)\"\n\ntest_272d() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&\n\t\tskip \"Need MDS version at least 2.12.55\"\n\n\tlocal dom=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -E 1M -L mdt -E -1 -c1 $dom\n\n\tlocal mdtidx=$($LFS getstripe -m $dom)\n\tlocal mdtname=MDT$(printf %04x $mdtidx)\n\tlocal facet=mds$((mdtidx + 1))\n\n\tdd if=/dev/urandom of=$dom bs=2M count=1 oflag=direct ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\tcancel_lru_locks mdc\n\tlocal mdtfree1=$(do_facet $facet \\\n\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\n\t$LFS mirror extend -N -E 2M -c1 -E -1 -c2 $dom ||\n\t\terror \"failed mirroring to the new composite layout\"\n\t$LFS mirror resync $dom ||\n\t\terror \"failed mirror resync\"\n\t$LFS mirror split --mirror-id 1 -d $dom ||\n\t\terror \"failed mirror split\"\n\n\t[ $($LFS getstripe -L $dom) != 'mdt' ] ||\n\t\terror \"MDT stripe was not removed\"\n\n\tcancel_lru_locks mdc\n\tlocal new_md5=$(md5sum $dom)\n\t[ \"$old_md5\" == \"$new_md5\" ] ||\n\t\terror \"$old_md5 != $new_md5\"\n\n\t# Skip free space checks with ZFS\n\tif [ \"$(facet_fstype $facet)\" != \"zfs\" ]; then\n\t\tlocal mdtfree2=$(do_facet $facet \\\n\t\t\t\tlctl get_param -n osd*.*$mdtname.kbytesfree)\n\t\t[ $mdtfree2 -gt $mdtfree1 ] ||\n\t\t\terror \"MDS space is not freed after DOM mirror deletion\"\n\tfi\n\treturn 0\n}\nrun_test 272d \"DoM mirroring: OST-striped mirror to DOM file\"\n\ntest_272e() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&\n\t\tskip \"Need MDS version at least 2.12.55\"\n\n\tlocal dom=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c 2 $dom\n\n\tdd if=/dev/urandom of=$dom bs=512K count=1 oflag=direct ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\tcancel_lru_locks mdc\n\n\t$LFS mirror extend -N -E 1M -L mdt -E eof -c2 $dom ||\n\t\terror \"failed mirroring to the DOM layout\"\n\t$LFS mirror resync $dom ||\n\t\terror \"failed mirror resync\"\n\t$LFS mirror split --mirror-id 1 -d $dom ||\n\t\terror \"failed mirror split\"\n\n\t[ $($LFS getstripe -L $dom) != 'mdt' ] ||\n\t\terror \"MDT stripe was not removed\"\n\n\tcancel_lru_locks mdc\n\tlocal new_md5=$(md5sum $dom)\n\t[ \"$old_md5\" == \"$new_md5\" ] ||\n\t\terror \"$old_md5 != $new_md5\"\n\n\treturn 0\n}\nrun_test 272e \"DoM mirroring: DOM mirror to the OST-striped file\"\n\ntest_272f() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&\n\t\tskip \"Need MDS version at least 2.12.55\"\n\n\tlocal dom=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c 2 $dom\n\n\tdd if=/dev/urandom of=$dom bs=512K count=1 oflag=direct ||\n\t\terror \"failed to write data into $dom\"\n\tlocal old_md5=$(md5sum $dom)\n\tcancel_lru_locks mdc\n\n\t$LFS migrate -E 1M -L mdt -E eof -c2 -v $dom ||\n\t\terror \"failed migrating to the DOM file\"\n\n\tcancel_lru_locks mdc\n\tlocal new_md5=$(md5sum $dom)\n\t[ \"$old_md5\" != \"$new_md5\" ] &&\n\t\terror \"$old_md5 != $new_md5\"\n\n\treturn 0\n}\nrun_test 272f \"DoM migration: OST-striped file to DOM file\"\n\ntest_273a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS version at least 2.11.50\"\n\n\t# Layout swap cannot be done if either file has DOM component,\n\t# this will never be supported, migration should be used instead\n\n\tlocal dom=$DIR/$tdir/$tfile\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -c2 ${dom}_plain\n\t$LFS setstripe -E 1M -L mdt -E -1 -c2 ${dom}_dom\n\t$LFS swap_layouts ${dom}_plain ${dom}_dom &&\n\t\terror \"can swap layout with DoM component\"\n\t$LFS swap_layouts ${dom}_dom ${dom}_plain &&\n\t\terror \"can swap layout with DoM component\"\n\n\t$LFS setstripe -E 1M -c1 -E -1 -c2 ${dom}_comp\n\t$LFS swap_layouts ${dom}_comp ${dom}_dom &&\n\t\terror \"can swap layout with DoM component\"\n\t$LFS swap_layouts ${dom}_dom ${dom}_comp &&\n\t\terror \"can swap layout with DoM component\"\n\treturn 0\n}\nrun_test 273a \"DoM: layout swapping should fail with DOM\"\n\ntest_275() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ $OST1_VERSION -lt $(version_code 2.10.57) ] &&\n\t\tskip \"Need OST version >= 2.10.57\"\n\n\tlocal file=$DIR/$tfile\n\tlocal oss\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdd if=/dev/urandom of=$file bs=1M count=2 ||\n\t\terror \"failed to create a file\"\n\tcancel_lru_locks osc\n\n\t#lock 1\n\tdd if=$file of=/dev/null bs=1M count=1 iflag=direct ||\n\t\terror \"failed to read a file\"\n\n#define OBD_FAIL_LDLM_PAUSE_CANCEL2      0x31f\n\t$LCTL set_param fail_loc=0x8000031f\n\n\tcancel_lru_locks osc &\n\tsleep 1\n\n#define OBD_FAIL_LDLM_PROLONG_PAUSE      0x32b\n\tdo_nodes $oss $LCTL set_param fail_loc=0x8000032b\n\t#IO takes another lock, but matches the PENDING one\n\t#and places it to the IO RPC\n\tdd if=$file of=/dev/null bs=1M count=1 iflag=direct ||\n\t\terror \"failed to read a file with PENDING lock\"\n}\nrun_test 275 \"Read on a canceled duplicate lock\"\n\ntest_276() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tlocal pid\n\n\tdo_facet ost1 \"(while true; do \\\n\t\t$LCTL get_param obdfilter.*.filesfree > /dev/null 2>&1; \\\n\t\tdone) & pid=\\\\\\$!; echo \\\\\\$pid > $TMP/sanity_276_pid\" &\n\tpid=$!\n\n\tfor LOOP in $(seq 20); do\n\t\tstop ost1\n\t\tstart ost1 $(ostdevname 1) $OST_MOUNT_OPTS\n\tdone\n\tkill -9 $pid\n\tdo_facet ost1 \"pid=\\\\\\$(cat $TMP/sanity_276_pid); kill -9 \\\\\\$pid; \\\n\t\trm $TMP/sanity_276_pid\"\n}\nrun_test 276 \"Race between mount and obd_statfs\"\n\ntest_277() {\n\t$LCTL set_param ldlm.namespaces.*.lru_size=0\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\tlocal cached_mb=$($LCTL get_param llite.*.max_cached_mb |\n\t\t\tgrep ^used_mb | awk '{print $2}')\n\t[ $cached_mb -eq 1 ] || error \"expected mb 1 got $cached_mb\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 \\\n\t\toflag=direct conv=notrunc\n\tcached_mb=$($LCTL get_param llite.*.max_cached_mb |\n\t\t\tgrep ^used_mb | awk '{print $2}')\n\t[ $cached_mb -eq 0 ] || error \"expected mb 0 got $cached_mb\"\n}\nrun_test 277 \"Direct IO shall drop page cache\"\n\ntest_278() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\" && return\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\t[[ \"$(facet_host mds1)\" != \"$(facet_host mds2)\" ]] &&\n\t\tskip \"needs the same host for mdt1 mdt2\" && return\n\n\tlocal pid1\n\tlocal pid2\n\n#define OBD_FAIL_OBD_STOP_MDS_RACE     0x60b\n\tdo_facet mds2 $LCTL set_param fail_loc=0x8000060c\n\tstop mds2 &\n\tpid2=$!\n\n\tstop mds1\n\n\techo \"Starting MDTs\"\n\tstart mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS\n\twait $pid2\n#For the error assertion will happen. lu_env_get_key(..., &mdt_thread_key)\n#will return NULL\n\tdo_facet mds2 $LCTL set_param fail_loc=0\n\n\tstart mds2 $(mdsdevname 2) $MDS_MOUNT_OPTS\n\twait_recovery_complete mds2\n}\nrun_test 278 \"Race starting MDS between MDTs stop/start\"\n\ntest_280() {\n\t[ $MGS_VERSION -lt $(version_code 2.13.52) ] &&\n\t\tskip \"Need MGS version at least 2.13.52\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tcombined_mgs_mds || skip \"needs combined MGS/MDT\"\n\n\tumount_client $MOUNT\n#define OBD_FAIL_MDS_LLOG_UMOUNT_RACE   0x15e\n\tdo_facet mgs $LCTL set_param fail_loc=0x8000015e fail_val=0\n\n\tmount_client $MOUNT &\n\tsleep 1\n\tstop mgs || error \"stop mgs failed\"\n\t#for a race mgs would crash\n\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS || error \"start mgs failed\"\n\tmount_client $MOUNT || error \"mount client failed\"\n}\nrun_test 280 \"Race between MGS umount and client llog processing\"\n\ncleanup_test_300() {\n\ttrap 0\n\tumask $SAVE_UMASK\n}\ntest_striped_dir() {\n\tlocal mdt_index=$1\n\tlocal stripe_count\n\tlocal stripe_index\n\n\tmkdir -p $DIR/$tdir\n\n\tSAVE_UMASK=$(umask)\n\ttrap cleanup_test_300 RETURN EXIT\n\n\t$LFS setdirstripe -i $mdt_index -c 2 -H all_char -o 755 \\\n\t\t\t\t\t\t$DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\tlocal mode=$(stat -c%a $DIR/$tdir/striped_dir)\n\t[ \"$mode\" = \"755\" ] || error \"expect 755 got $mode\"\n\n\t$LFS getdirstripe $DIR/$tdir/striped_dir > /dev/null 2>&1 ||\n\t\terror \"getdirstripe failed\"\n\tstripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir)\n\tif [ \"$stripe_count\" != \"2\" ]; then\n\t\terror \"1:stripe_count is $stripe_count, expect 2\"\n\tfi\n\tstripe_count=$($LFS getdirstripe -T $DIR/$tdir/striped_dir)\n\tif [ \"$stripe_count\" != \"2\" ]; then\n\t\terror \"2:stripe_count is $stripe_count, expect 2\"\n\tfi\n\n\tstripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir)\n\tif [ \"$stripe_index\" != \"$mdt_index\" ]; then\n\t\terror \"stripe_index is $stripe_index, expect $mdt_index\"\n\tfi\n\n\t[ $(stat -c%h $DIR/$tdir/striped_dir) == '2' ] ||\n\t\terror \"nlink error after create striped dir\"\n\n\tmkdir $DIR/$tdir/striped_dir/a\n\tmkdir $DIR/$tdir/striped_dir/b\n\n\tstat $DIR/$tdir/striped_dir/a ||\n\t\terror \"create dir under striped dir failed\"\n\tstat $DIR/$tdir/striped_dir/b ||\n\t\terror \"create dir under striped dir failed\"\n\n\t[ $(stat -c%h $DIR/$tdir/striped_dir) == '4' ] ||\n\t\terror \"nlink error after mkdir\"\n\n\trmdir $DIR/$tdir/striped_dir/a\n\t[ $(stat -c%h $DIR/$tdir/striped_dir) == '3' ] ||\n\t\terror \"nlink error after rmdir\"\n\n\trmdir $DIR/$tdir/striped_dir/b\n\t[ $(stat -c%h $DIR/$tdir/striped_dir) == '2' ] ||\n\t\terror \"nlink error after rmdir\"\n\n\tchattr +i $DIR/$tdir/striped_dir\n\tcreatemany -o $DIR/$tdir/striped_dir/f 10 &&\n\t\terror \"immutable flags not working under striped dir!\"\n\tchattr -i $DIR/$tdir/striped_dir\n\n\trmdir $DIR/$tdir/striped_dir ||\n\t\terror \"rmdir striped dir error\"\n\n\tcleanup_test_300\n\n\ttrue\n}\n\ntest_300a() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&\n\t\tskip \"skipped for lustre < 2.7.0\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\ttest_striped_dir 0 || error \"failed on striped dir on MDT0\"\n\ttest_striped_dir 1 || error \"failed on striped dir on MDT0\"\n}\nrun_test 300a \"basic striped dir sanity test\"\n\ntest_300b() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&\n\t\tskip \"skipped for lustre < 2.7.0\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal i\n\tlocal mtime1\n\tlocal mtime2\n\tlocal mtime3\n\n\ttest_mkdir $DIR/$tdir || error \"mkdir fail\"\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\tfor i in {0..9}; do\n\t\tmtime1=$(stat -c %Y $DIR/$tdir/striped_dir)\n\t\tsleep 1\n\t\ttouch $DIR/$tdir/striped_dir/file_$i || error \"touch error $i\"\n\t\tmtime2=$(stat -c %Y $DIR/$tdir/striped_dir)\n\t\t[ $mtime1 -eq $mtime2 ] && error \"mtime unchanged after create\"\n\t\tsleep 1\n\t\trm -f $DIR/$tdir/striped_dir/file_$i || error \"unlink error $i\"\n\t\tmtime3=$(stat -c %Y $DIR/$tdir/striped_dir)\n\t\t[ $mtime2 -eq $mtime3 ] && error \"mtime unchanged after unlink\"\n\tdone\n\ttrue\n}\nrun_test 300b \"check ctime/mtime for striped dir\"\n\ntest_300c() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&\n\t\tskip \"skipped for lustre < 2.7.0\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal file_count\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $DIR/$tdir/striped_dir ||\n\t\terror \"chown striped dir failed\"\n\n\t$RUNAS createmany -o $DIR/$tdir/striped_dir/f 5000 ||\n\t\terror \"create 5k files failed\"\n\n\tfile_count=$(ls $DIR/$tdir/striped_dir | wc -l)\n\n\t[ \"$file_count\" = 5000 ] || error \"file count $file_count != 5000\"\n\n\trm -rf $DIR/$tdir\n}\nrun_test 300c \"chown && check ls under striped directory\"\n\ntest_300d() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.0) ] &&\n\t\tskip \"skipped for lustre < 2.7.0\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal stripe_count\n\tlocal file\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -c 2 $DIR/$tdir\n\n\t#local striped directory\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n        #look at the directories for debug purposes\n\tls -l $DIR/$tdir\n\t$LFS getdirstripe $DIR/$tdir\n\tls -l $DIR/$tdir/striped_dir\n\t$LFS getdirstripe $DIR/$tdir/striped_dir\n\tcreatemany -o $DIR/$tdir/striped_dir/f 10 ||\n\t\terror \"create 10 files failed\"\n\n\t#remote striped directory\n\t$LFS setdirstripe -i 1 -c 2 $DIR/$tdir/remote_striped_dir ||\n\t\terror \"set striped dir error\"\n        #look at the directories for debug purposes\n\tls -l $DIR/$tdir\n\t$LFS getdirstripe $DIR/$tdir\n\tls -l $DIR/$tdir/remote_striped_dir\n\t$LFS getdirstripe $DIR/$tdir/remote_striped_dir\n\tcreatemany -o $DIR/$tdir/remote_striped_dir/f 10 ||\n\t\terror \"create 10 files failed\"\n\n\tfor file in $(find $DIR/$tdir); do\n\t\tstripe_count=$($LFS getstripe -c $file)\n\t\t[ $stripe_count -eq 2 ] ||\n\t\t\terror \"wrong stripe $stripe_count for $file\"\n\tdone\n\n\trm -rf $DIR/$tdir\n}\nrun_test 300d \"check default stripe under striped directory\"\n\ntest_300e() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal stripe_count\n\tlocal file\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\ttouch $DIR/$tdir/striped_dir/a\n\ttouch $DIR/$tdir/striped_dir/b\n\ttouch $DIR/$tdir/striped_dir/c\n\n\tmkdir $DIR/$tdir/striped_dir/dir_a\n\tmkdir $DIR/$tdir/striped_dir/dir_b\n\tmkdir $DIR/$tdir/striped_dir/dir_c\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_a ||\n\t\terror \"set striped adir under striped dir error\"\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_b ||\n\t\terror \"set striped bdir under striped dir error\"\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir/stp_c ||\n\t\terror \"set striped cdir under striped dir error\"\n\n\tmrename $DIR/$tdir/striped_dir/dir_a $DIR/$tdir/striped_dir/dir_b ||\n\t\terror \"rename dir under striped dir fails\"\n\n\tmrename $DIR/$tdir/striped_dir/stp_a $DIR/$tdir/striped_dir/stp_b ||\n\t\terror \"rename dir under different stripes fails\"\n\n\tmrename $DIR/$tdir/striped_dir/a $DIR/$tdir/striped_dir/c ||\n\t\terror \"rename file under striped dir should succeed\"\n\n\tmrename $DIR/$tdir/striped_dir/dir_b $DIR/$tdir/striped_dir/dir_c ||\n\t\terror \"rename dir under striped dir should succeed\"\n\n\trm -rf $DIR/$tdir\n}\nrun_test 300e \"check rename under striped directory\"\n\ntest_300f() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal stripe_count\n\tlocal file\n\n\trm -rf $DIR/$tdir\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\t$LFS setdirstripe -i 0 -c 2 -H all_char $DIR/$tdir/striped_dir1 ||\n\t\terror \"set striped dir error\"\n\n\ttouch $DIR/$tdir/striped_dir/a\n\tmkdir $DIR/$tdir/striped_dir/dir_a\n\t$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir/stp_a ||\n\t\terror \"create striped dir under striped dir fails\"\n\n\ttouch $DIR/$tdir/striped_dir1/b\n\tmkdir $DIR/$tdir/striped_dir1/dir_b\n\t$LFS setdirstripe -i 0 -c 2 $DIR/$tdir/striped_dir/stp_b ||\n\t\terror \"create striped dir under striped dir fails\"\n\n\tmrename $DIR/$tdir/striped_dir/dir_a $DIR/$tdir/striped_dir1/dir_b ||\n\t\terror \"rename dir under different striped dir should fail\"\n\n\tmrename $DIR/$tdir/striped_dir/stp_a $DIR/$tdir/striped_dir1/stp_b ||\n\t\terror \"rename striped dir under diff striped dir should fail\"\n\n\tmrename $DIR/$tdir/striped_dir/a $DIR/$tdir/striped_dir1/a ||\n\t\terror \"rename file under diff striped dirs fails\"\n\n\trm -rf $DIR/$tdir\n}\nrun_test 300f \"check rename cross striped directory\"\n\ntest_300_check_default_striped_dir()\n{\n\tlocal dirname=$1\n\tlocal default_count=$2\n\tlocal default_index=$3\n\tlocal stripe_count\n\tlocal stripe_index\n\tlocal dir_stripe_index\n\tlocal dir\n\n\techo \"checking $dirname $default_count $default_index\"\n\t$LFS setdirstripe -D -c $default_count -i $default_index \\\n\t\t\t\t-t all_char $DIR/$tdir/$dirname ||\n\t\terror \"set default stripe on striped dir error\"\n\tstripe_count=$($LFS getdirstripe -D -c $DIR/$tdir/$dirname)\n\t[ $stripe_count -eq $default_count ] ||\n\t\terror \"expect $default_count get $stripe_count for $dirname\"\n\n\tstripe_index=$($LFS getdirstripe -D -i $DIR/$tdir/$dirname)\n\t[ $stripe_index -eq $default_index ] ||\n\t\terror \"expect $default_index get $stripe_index for $dirname\"\n\n\tmkdir $DIR/$tdir/$dirname/{test1,test2,test3,test4} ||\n\t\t\t\t\t\terror \"create dirs failed\"\n\n\tcreatemany -o $DIR/$tdir/$dirname/f- 10 || error \"create files failed\"\n\tunlinkmany $DIR/$tdir/$dirname/f- 10\t|| error \"unlink files failed\"\n\tfor dir in $(find $DIR/$tdir/$dirname/*); do\n\t\tstripe_count=$($LFS getdirstripe -c $dir)\n\t\t[ $stripe_count -eq $default_count ] ||\n\t\t[ $stripe_count -eq 0 ] || [ $default_count -eq 1 ] ||\n\t\terror \"stripe count $default_count != $stripe_count for $dir\"\n\n\t\tstripe_index=$($LFS getdirstripe -i $dir)\n\t\t[ $default_index -eq -1 ] ||\n\t\t\t[ $stripe_index -eq $default_index ] ||\n\t\t\terror \"$stripe_index != $default_index for $dir\"\n\n\t\t#check default stripe\n\t\tstripe_count=$($LFS getdirstripe -D -c $dir)\n\t\t[ $stripe_count -eq $default_count ] ||\n\t\terror \"default count $default_count != $stripe_count for $dir\"\n\n\t\tstripe_index=$($LFS getdirstripe -D -i $dir)\n\t\t[ $stripe_index -eq $default_index ] ||\n\t\terror \"default index $default_index != $stripe_index for $dir\"\n\tdone\n\trmdir $DIR/$tdir/$dirname/* || error \"rmdir failed\"\n}\n\ntest_300g() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal dir\n\tlocal stripe_count\n\tlocal stripe_index\n\n\tmkdir $DIR/$tdir\n\tmkdir $DIR/$tdir/normal_dir\n\n\t#Checking when client cache stripe index\n\t$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -D -i1 $DIR/$tdir/striped_dir ||\n\t\terror \"create striped_dir failed\"\n\n\t$LFS setdirstripe -i0 $DIR/$tdir/striped_dir/dir0 ||\n\t\terror \"create dir0 fails\"\n\tstripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/dir0)\n\t[ $stripe_index -eq 0 ] ||\n\t\terror \"dir0 expect index 0 got $stripe_index\"\n\n\tmkdir $DIR/$tdir/striped_dir/dir1 ||\n\t\terror \"create dir1 fails\"\n\tstripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/dir1)\n\t[ $stripe_index -eq 1 ] ||\n\t\terror \"dir1 expect index 1 got $stripe_index\"\n\n\t#check default stripe count/stripe index\n\ttest_300_check_default_striped_dir normal_dir $MDSCOUNT 1\n\ttest_300_check_default_striped_dir normal_dir 1 0\n\ttest_300_check_default_striped_dir normal_dir 2 1\n\ttest_300_check_default_striped_dir normal_dir 2 -1\n\n\t#delete default stripe information\n\techo \"delete default stripeEA\"\n\t$LFS setdirstripe -d $DIR/$tdir/normal_dir ||\n\t\terror \"set default stripe on striped dir error\"\n\n\tmkdir -p $DIR/$tdir/normal_dir/{test1,test2,test3,test4}\n\tfor dir in $(find $DIR/$tdir/normal_dir/*); do\n\t\tstripe_count=$($LFS getdirstripe -c $dir)\n\t\t[ $stripe_count -eq 0 ] ||\n\t\t\terror \"expect 1 get $stripe_count for $dir\"\n\t\tstripe_index=$($LFS getdirstripe -i $dir)\n\t\t[ $stripe_index -eq 0 ] ||\n\t\t\terror \"expect 0 get $stripe_index for $dir\"\n\tdone\n}\nrun_test 300g \"check default striped directory for normal directory\"\n\ntest_300h() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal dir\n\tlocal stripe_count\n\n\tmkdir $DIR/$tdir\n\t$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\ttest_300_check_default_striped_dir striped_dir $MDSCOUNT 1\n\ttest_300_check_default_striped_dir striped_dir 1 0\n\ttest_300_check_default_striped_dir striped_dir 2 1\n\ttest_300_check_default_striped_dir striped_dir 2 -1\n\n\t#delete default stripe information\n\t$LFS setdirstripe -d $DIR/$tdir/striped_dir ||\n\t\terror \"set default stripe on striped dir error\"\n\n\tmkdir -p $DIR/$tdir/striped_dir/{test1,test2,test3,test4}\n\tfor dir in $(find $DIR/$tdir/striped_dir/*); do\n\t\tstripe_count=$($LFS getdirstripe -c $dir)\n\t\t[ $stripe_count -eq 0 ] ||\n\t\t\terror \"expect 1 get $stripe_count for $dir\"\n\tdone\n}\nrun_test 300h \"check default striped directory for striped directory\"\n\ntest_300i() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal stripe_count\n\tlocal file\n\n\tmkdir $DIR/$tdir\n\n\t$LFS setdirstripe -i 0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\tcreatemany -o $DIR/$tdir/striped_dir/f- 10 ||\n\t\terror \"create files under striped dir failed\"\n\n\t$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/hashdir ||\n\t\terror \"set striped hashdir error\"\n\n\t$LFS setdirstripe -i0 -c$MDSCOUNT -H all_char $DIR/$tdir/hashdir/d0 ||\n\t\terror \"create dir0 under hash dir failed\"\n\t$LFS setdirstripe -i0 -c$MDSCOUNT -H fnv_1a_64 $DIR/$tdir/hashdir/d1 ||\n\t\terror \"create dir1 under hash dir failed\"\n\n\t# unfortunately, we need to umount to clear dir layout cache for now\n\t# once we fully implement dir layout, we can drop this\n\tumount_client $MOUNT || error \"umount failed\"\n\tmount_client $MOUNT || error \"mount failed\"\n\n\t$LFS find -H fnv_1a_64 $DIR/$tdir/hashdir\n\tlocal dircnt=$($LFS find -H fnv_1a_64 $DIR/$tdir/hashdir | wc -l)\n\t[ $dircnt -eq 1 ] || error \"lfs find striped dir got:$dircnt,except:1\"\n\n\t#set the stripe to be unknown hash type\n\t#define OBD_FAIL_UNKNOWN_LMV_STRIPE\t0x1901\n\t$LCTL set_param fail_loc=0x1901\n\tfor ((i = 0; i < 10; i++)); do\n\t\t$CHECKSTAT -t file $DIR/$tdir/striped_dir/f-$i ||\n\t\t\terror \"stat f-$i failed\"\n\t\trm $DIR/$tdir/striped_dir/f-$i || error \"unlink f-$i failed\"\n\tdone\n\n\ttouch $DIR/$tdir/striped_dir/f0 &&\n\t\terror \"create under striped dir with unknown hash should fail\"\n\n\t$LCTL set_param fail_loc=0\n\n\tumount_client $MOUNT || error \"umount failed\"\n\tmount_client $MOUNT || error \"mount failed\"\n\n\treturn 0\n}\nrun_test 300i \"client handle unknown hash type striped directory\"\n\ntest_300j() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal stripe_count\n\tlocal file\n\n\tmkdir $DIR/$tdir\n\n\t#define OBD_FAIL_SPLIT_UPDATE_REC\t0x1702\n\t$LCTL set_param fail_loc=0x1702\n\t$LFS setdirstripe -i 0 -c$MDSCOUNT -H all_char $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\tcreatemany -o $DIR/$tdir/striped_dir/f- 10 ||\n\t\terror \"create files under striped dir failed\"\n\n\t$LCTL set_param fail_loc=0\n\n\trm -rf $DIR/$tdir || error \"unlink striped dir fails\"\n\n\treturn 0\n}\nrun_test 300j \"test large update record\"\n\ntest_300k() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\t# this test needs a huge transaction\n\tlocal kb\n\tkb=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t     osd*.$FSNAME-MDT0000.kbytestotal\")\n\t[ $kb -lt $((1024*1024)) ] && skip \"MDT0 too small: $kb\"\n\n\tlocal stripe_count\n\tlocal file\n\n\tmkdir $DIR/$tdir\n\n\t#define OBD_FAIL_LARGE_STRIPE\t0x1703\n\t$LCTL set_param fail_loc=0x1703\n\t$LFS setdirstripe -i 0 -c192 $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\t$LCTL set_param fail_loc=0\n\n\t$LFS getdirstripe $DIR/$tdir/striped_dir ||\n\t\terror \"getstripeddir fails\"\n\trm -rf $DIR/$tdir/striped_dir ||\n\t\terror \"unlink striped dir fails\"\n\n\treturn 0\n}\nrun_test 300k \"test large striped directory\"\n\ntest_300l() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal stripe_index\n\n\ttest_mkdir -p $DIR/$tdir/striped_dir\n\tchown $RUNAS_ID $DIR/$tdir/striped_dir ||\n\t\t\terror \"chown $RUNAS_ID failed\"\n\t$LFS setdirstripe -i 1 -D $DIR/$tdir/striped_dir ||\n\t\terror \"set default striped dir failed\"\n\n\t#define OBD_FAIL_MDS_STALE_DIR_LAYOUT\t 0x158\n\t$LCTL set_param fail_loc=0x80000158\n\t$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir || error \"create dir fails\"\n\n\tstripe_index=$($LFS getdirstripe -i $DIR/$tdir/striped_dir/test_dir)\n\t[ $stripe_index -eq 1 ] ||\n\t\terror \"expect 1 get $stripe_index for $dir\"\n}\nrun_test 300l \"non-root user to create dir under striped dir with stale layout\"\n\ntest_300m() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -ge 2 ] && skip_env \"Only for single MDT\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tmkdir -p $DIR/$tdir/striped_dir\n\t$LFS setdirstripe -D -c 1 $DIR/$tdir/striped_dir ||\n\t\terror \"set default stripes dir error\"\n\n\tmkdir $DIR/$tdir/striped_dir/a || error \"mkdir a fails\"\n\n\tstripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir/a)\n\t[ $stripe_count -eq 0 ] ||\n\t\t\terror \"expect 0 get $stripe_count for a\"\n\n\t$LFS setdirstripe -D -c 2 $DIR/$tdir/striped_dir ||\n\t\terror \"set default stripes dir error\"\n\n\tmkdir $DIR/$tdir/striped_dir/b || error \"mkdir b fails\"\n\n\tstripe_count=$($LFS getdirstripe -c $DIR/$tdir/striped_dir/b)\n\t[ $stripe_count -eq 0 ] ||\n\t\t\terror \"expect 0 get $stripe_count for b\"\n\n\t$LFS setdirstripe -D -c1 -i2 $DIR/$tdir/striped_dir ||\n\t\terror \"set default stripes dir error\"\n\n\tmkdir $DIR/$tdir/striped_dir/c &&\n\t\terror \"default stripe_index is invalid, mkdir c should fails\"\n\n\trm -rf $DIR/$tdir || error \"rmdir fails\"\n}\nrun_test 300m \"setstriped directory on single MDT FS\"\n\ncleanup_300n() {\n\tlocal list=$(comma_list $(mdts_nodes))\n\n\ttrap 0\n\tdo_nodes $list $LCTL set_param -n mdt.*.enable_remote_dir_gid=0\n}\n\ntest_300n() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal stripe_index\n\tlocal list=$(comma_list $(mdts_nodes))\n\n\ttrap cleanup_300n RETURN EXIT\n\tmkdir -p $DIR/$tdir\n\tchmod 777 $DIR/$tdir\n\t$RUNAS $LFS setdirstripe -i0 -c$MDSCOUNT \\\n\t\t\t\t$DIR/$tdir/striped_dir > /dev/null 2>&1 &&\n\t\terror \"create striped dir succeeds with gid=0\"\n\n\tdo_nodes $list $LCTL set_param -n mdt.*.enable_remote_dir_gid=-1\n\t$RUNAS $LFS setdirstripe -i0 -c$MDSCOUNT $DIR/$tdir/striped_dir ||\n\t\terror \"create striped dir fails with gid=-1\"\n\n\tdo_nodes $list $LCTL set_param -n mdt.*.enable_remote_dir_gid=0\n\t$RUNAS $LFS setdirstripe -i 1 -c$MDSCOUNT -D \\\n\t\t\t\t$DIR/$tdir/striped_dir > /dev/null 2>&1 &&\n\t\terror \"set default striped dir succeeds with gid=0\"\n\n\n\tdo_nodes $list $LCTL set_param -n mdt.*.enable_remote_dir_gid=-1\n\t$RUNAS $LFS setdirstripe -i 1 -c$MDSCOUNT -D $DIR/$tdir/striped_dir ||\n\t\terror \"set default striped dir fails with gid=-1\"\n\n\n\tdo_nodes $list $LCTL set_param -n mdt.*.enable_remote_dir_gid=0\n\t$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir ||\n\t\t\t\t\terror \"create test_dir fails\"\n\t$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir1 ||\n\t\t\t\t\terror \"create test_dir1 fails\"\n\t$RUNAS mkdir $DIR/$tdir/striped_dir/test_dir2 ||\n\t\t\t\t\terror \"create test_dir2 fails\"\n\tcleanup_300n\n}\nrun_test 300n \"non-root user to create dir under striped dir with default EA\"\n\ntest_300o() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\"\n\n\tlocal numfree1\n\tlocal numfree2\n\n\tmkdir -p $DIR/$tdir\n\n\tnumfree1=$(lctl get_param -n mdc.*MDT0000*.filesfree)\n\tnumfree2=$(lctl get_param -n mdc.*MDT0001*.filesfree)\n\tif [ $numfree1 -lt 66000 ] || [ $numfree2 -lt 66000 ]; then\n\t\tskip \"not enough free inodes $numfree1 $numfree2\"\n\tfi\n\n\tnumfree1=$(lctl get_param -n mdc.*MDT0000-mdc-*.kbytesfree)\n\tnumfree2=$(lctl get_param -n mdc.*MDT0001-mdc-*.kbytesfree)\n\tif [ $numfree1 -lt 300000 ] || [ $numfree2 -lt 300000 ]; then\n\t\tskip \"not enough free space $numfree1 $numfree2\"\n\tfi\n\n\t$LFS setdirstripe -c2 $DIR/$tdir/striped_dir ||\n\t\terror \"setdirstripe fails\"\n\n\tcreatemany -d $DIR/$tdir/striped_dir/d 131000 ||\n\t\terror \"create dirs fails\"\n\n\t$LCTL set_param ldlm.namespaces.*mdc-*.lru_size=0\n\tls $DIR/$tdir/striped_dir > /dev/null ||\n\t\terror \"ls striped dir fails\"\n\tunlinkmany -d $DIR/$tdir/striped_dir/d 131000 ||\n\t\terror \"unlink big striped dir fails\"\n}\nrun_test 300o \"unlink big sub stripe(> 65000 subdirs)\"\n\ntest_300p() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tmkdir -p $DIR/$tdir\n\n\t#define OBD_FAIL_OUT_ENOSPC\t0x1704\n\tdo_facet mds2 lctl set_param fail_loc=0x80001704\n\t$LFS setdirstripe -i 0 -c2 $DIR/$tdir/bad_striped_dir > /dev/null 2>&1 \\\n\t\t && error \"create striped directory should fail\"\n\n\t[ -e $DIR/$tdir/bad_striped_dir ] && error \"striped dir exists\"\n\n\t$LFS setdirstripe -c2 $DIR/$tdir/bad_striped_dir\n\ttrue\n}\nrun_test 300p \"create striped directory without space\"\n\ntest_300q() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\n\tlocal fd=$(free_fd)\n\tlocal cmd=\"exec $fd<$tdir\"\n\tcd $DIR\n\t$LFS mkdir -c $MDSCOUNT $tdir || error \"create $tdir fails\"\n\teval $cmd\n\tcmd=\"exec $fd<&-\"\n\ttrap \"eval $cmd\" EXIT\n\tcd $tdir || error \"cd $tdir fails\"\n\trmdir  ../$tdir || error \"rmdir $tdir fails\"\n\tmkdir local_dir && error \"create dir succeeds\"\n\t$LFS setdirstripe -i1 remote_dir && error \"create remote dir succeeds\"\n\teval $cmd\n\treturn 0\n}\nrun_test 300q \"create remote directory under orphan directory\"\n\ntest_300r() {\n\t[ $MDS1_VERSION -lt $(version_code 2.7.55) ] &&\n\t\tskip \"Need MDS version at least 2.7.55\" && return\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tmkdir $DIR/$tdir\n\n\t$LFS setdirstripe -i 0 -c -1 $DIR/$tdir/striped_dir ||\n\t\terror \"set striped dir error\"\n\n\t$LFS getdirstripe $DIR/$tdir/striped_dir ||\n\t\terror \"getstripeddir fails\"\n\n\tlocal stripe_count\n\tstripe_count=$($LFS getdirstripe $DIR/$tdir/striped_dir |\n\t\t      awk '/lmv_stripe_count:/ { print $2 }')\n\n\t[ $MDSCOUNT -ne $stripe_count ] &&\n\t\terror \"wrong stripe count $stripe_count expected $MDSCOUNT\"\n\n\trm -rf $DIR/$tdir/striped_dir ||\n\t\terror \"unlink striped dir fails\"\n}\nrun_test 300r \"test -1 striped directory\"\n\nprepare_remote_file() {\n\tmkdir $DIR/$tdir/src_dir ||\n\t\terror \"create remote source failed\"\n\n\tcp /etc/hosts $DIR/$tdir/src_dir/a ||\n\t\t error \"cp to remote source failed\"\n\ttouch $DIR/$tdir/src_dir/a\n\n\t$LFS mkdir -i 1 $DIR/$tdir/tgt_dir ||\n\t\terror \"create remote target dir failed\"\n\n\ttouch $DIR/$tdir/tgt_dir/b\n\n\tmrename $DIR/$tdir/src_dir/a $DIR/$tdir/tgt_dir/b ||\n\t\terror \"rename dir cross MDT failed!\"\n\n\t$CHECKSTAT -t file $DIR/$tdir/src_dir/a &&\n\t\terror \"src_child still exists after rename\"\n\n\t$CHECKSTAT -t file $DIR/$tdir/tgt_dir/b ||\n\t\terror \"missing file(a) after rename\"\n\n\tdiff /etc/hosts $DIR/$tdir/tgt_dir/b ||\n\t\terror \"diff after rename\"\n}\n\ntest_310a() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 4 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal remote_file=$DIR/$tdir/tgt_dir/b\n\n\tmkdir -p $DIR/$tdir\n\n\tprepare_remote_file || error \"prepare remote file failed\"\n\n\t#open-unlink file\n\t$OPENUNLINK $remote_file $remote_file ||\n\t\terror \"openunlink $remote_file failed\"\n\t$CHECKSTAT -a $remote_file || error \"$remote_file exists\"\n}\nrun_test 310a \"open unlink remote file\"\n\ntest_310b() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 4 MDTs\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal remote_file=$DIR/$tdir/tgt_dir/b\n\n\tmkdir -p $DIR/$tdir\n\n\tprepare_remote_file || error \"prepare remote file failed\"\n\n\tln $remote_file $DIR/$tfile || error \"link failed for remote file\"\n\t$MULTIOP $DIR/$tfile Ouc || error \"mulitop failed\"\n\t$CHECKSTAT -t file $remote_file || error \"check file failed\"\n}\nrun_test 310b \"unlink remote file with multiple links while open\"\n\ntest_310c() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[[ $MDSCOUNT -lt 4 ]] && skip_env \"needs >= 4 MDTs\"\n\n\tlocal remote_file=$DIR/$tdir/tgt_dir/b\n\n\tmkdir -p $DIR/$tdir\n\n\tprepare_remote_file || error \"prepare remote file failed\"\n\n\tln $remote_file $DIR/$tfile || error \"link failed for remote file\"\n\tmultiop_bg_pause $remote_file O_uc ||\n\t\t\terror \"mulitop failed for remote file\"\n\tMULTIPID=$!\n\t$MULTIOP $DIR/$tfile Ouc\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID\n}\nrun_test 310c \"open-unlink remote file with multiple links\"\n\n#LU-4825\ntest_311() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.8.54) ] &&\n\t\tskip \"lustre < 2.8.54 does not contain LU-4825 fix\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal old_iused=$($LFS df -i | grep OST0000 | awk '{ print $3 }')\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setstripe -i 0 -c 1 $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/$tfile. 1000\n\n\t# statfs data is not real time, let's just calculate it\n\told_iused=$((old_iused + 1000))\n\n\tlocal count=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\tosp.*OST0000*MDT0000.create_count\")\n\tlocal max_count=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\t\t\tosp.*OST0000*MDT0000.max_create_count\")\n\tdo_nodes $mdts \"$LCTL set_param -n osp.*OST0000*.max_create_count=0\"\n\n\t$LFS setstripe -i 0 $DIR/$tdir/$tfile || error \"setstripe failed\"\n\tlocal index=$($LFS getstripe -i $DIR/$tdir/$tfile)\n\t[ $index -ne 0 ] || error \"$tfile stripe index is 0\"\n\n\tunlinkmany $DIR/$tdir/$tfile. 1000\n\n\tdo_nodes $mdts \"$LCTL set_param -n \\\n\t\t\tosp.*OST0000*.max_create_count=$max_count\"\n\t[ $MDS1_VERSION -lt $(version_code 2.12.51) ] &&\n\t\tdo_nodes $mdts \"$LCTL set_param -n \\\n\t\t\t\tosp.*OST0000*.create_count=$count\"\n\tdo_nodes $mdts \"$LCTL get_param osp.*OST0000*.create_count\" |\n\t\t\tgrep \"=0\" && error \"create_count is zero\"\n\n\tlocal new_iused\n\tfor i in $(seq 120); do\n\t\tnew_iused=$($LFS df -i | grep OST0000 | awk '{ print $3 }')\n\t\t# system may be too busy to destroy all objs in time, use\n\t\t# a somewhat small value to not fail autotest\n\t\t[ $((old_iused - new_iused)) -gt 400 ] && break\n\t\tsleep 1\n\tdone\n\n\techo \"waited $i sec, old Iused $old_iused, new Iused $new_iused\"\n\t[ $((old_iused - new_iused)) -gt 400 ] ||\n\t\terror \"objs not destroyed after unlink\"\n}\nrun_test 311 \"disable OSP precreate, and unlink should destroy objs\"\n\nzfs_oid_to_objid()\n{\n\tlocal ost=$1\n\tlocal objid=$2\n\n\tlocal vdevdir=$(dirname $(facet_vdevice $ost))\n\tlocal cmd=\"$ZDB -e -p $vdevdir -ddddd $(facet_device $ost)\"\n\tlocal zfs_zapid=$(do_facet $ost $cmd |\n\t\t\t  grep -w \"/O/0/d$((objid%32))\" -C 5 |\n\t\t\t  awk '/Object/{getline; print $1}')\n\tlocal zfs_objid=$(do_facet $ost $cmd $zfs_zapid |\n\t\t\t  awk \"/$objid = /\"'{printf $3}')\n\n\techo $zfs_objid\n}\n\nzfs_object_blksz() {\n\tlocal ost=$1\n\tlocal objid=$2\n\n\tlocal vdevdir=$(dirname $(facet_vdevice $ost))\n\tlocal cmd=\"$ZDB -e -p $vdevdir -dddd $(facet_device $ost)\"\n\tlocal blksz=$(do_facet $ost $cmd $objid |\n\t\t      awk '/dblk/{getline; printf $4}')\n\n\tcase \"${blksz: -1}\" in\n\t\tk|K) blksz=$((${blksz:0:$((${#blksz} - 1))}*1024)) ;;\n\t\tm|M) blksz=$((${blksz:0:$((${#blksz} - 1))}*1024*1024)) ;;\n\t\t*) ;;\n\tesac\n\n\techo $blksz\n}\n\ntest_312() { # LU-4856\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\t[ \"$ost1_FSTYPE\" = \"zfs\" ] ||\n\t\tskip_env \"the test only applies to zfs\"\n\n\tlocal max_blksz=$(do_facet ost1 \\\n\t\t\t  $ZFS get -p recordsize $(facet_device ost1) |\n\t\t\t  awk '!/VALUE/{print $3}')\n\n\t# to make life a little bit easier\n\t$LFS mkdir -c 1 -i 0 $DIR/$tdir\n\t$LFS setstripe -c 1 -i 0 $DIR/$tdir\n\n\tlocal tf=$DIR/$tdir/$tfile\n\ttouch $tf\n\tlocal oid=$($LFS getstripe $tf | awk '/obdidx/{getline; print $2}')\n\n\t# Get ZFS object id\n\tlocal zfs_objid=$(zfs_oid_to_objid ost1 $oid)\n\t# block size change by sequential overwrite\n\tlocal bs\n\n\tfor ((bs=$PAGE_SIZE; bs <= max_blksz; bs *= 4)) ; do\n\t\tdd if=/dev/zero of=$tf bs=$bs count=1 oflag=sync conv=notrunc\n\n\t\tlocal blksz=$(zfs_object_blksz ost1 $zfs_objid)\n\t\t[ $blksz -eq $bs ] || error \"blksz error: $blksz, expected: $bs\"\n\tdone\n\trm -f $tf\n\n\t# block size change by sequential append write\n\tdd if=/dev/zero of=$tf bs=$PAGE_SIZE count=1 oflag=sync conv=notrunc\n\toid=$($LFS getstripe $tf | awk '/obdidx/{getline; print $2}')\n\tzfs_objid=$(zfs_oid_to_objid ost1 $oid)\n\tlocal count\n\n\tfor ((count = 1; count < $((max_blksz / PAGE_SIZE)); count *= 2)); do\n\t\tdd if=/dev/zero of=$tf bs=$PAGE_SIZE count=$count seek=$count \\\n\t\t\toflag=sync conv=notrunc\n\n\t\tblksz=$(zfs_object_blksz ost1 $zfs_objid)\n\t\t[ $blksz -eq $((2 * count * PAGE_SIZE)) ] ||\n\t\t\terror \"blksz error, actual $blksz, \" \\\n\t\t\t\t\"expected: 2 * $count * $PAGE_SIZE\"\n\tdone\n\trm -f $tf\n\n\t# random write\n\ttouch $tf\n\toid=$($LFS getstripe $tf | awk '/obdidx/{getline; print $2}')\n\tzfs_objid=$(zfs_oid_to_objid ost1 $oid)\n\n\tdd if=/dev/zero of=$tf bs=1K count=1 oflag=sync conv=notrunc\n\tblksz=$(zfs_object_blksz ost1 $zfs_objid)\n\t[ $blksz -eq $PAGE_SIZE ] ||\n\t\terror \"blksz error: $blksz, expected: $PAGE_SIZE\"\n\n\tdd if=/dev/zero of=$tf bs=64K count=1 oflag=sync conv=notrunc seek=128\n\tblksz=$(zfs_object_blksz ost1 $zfs_objid)\n\t[ $blksz -eq 65536 ] || error \"blksz error: $blksz, expected: 64k\"\n\n\tdd if=/dev/zero of=$tf bs=1M count=1 oflag=sync conv=notrunc\n\tblksz=$(zfs_object_blksz ost1 $zfs_objid)\n\t[ $blksz -eq 65536 ] || error \"rewrite error: $blksz, expected: 64k\"\n}\nrun_test 312 \"make sure ZFS adjusts its block size by write pattern\"\n\ntest_313() {\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\tlocal file=$DIR/$tfile\n\n\trm -f $file\n\t$LFS setstripe -c 1 -i 0 $file || error \"setstripe failed\"\n\n\t# define OBD_FAIL_TGT_RCVD_EIO\t\t 0x720\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x720\"\n\tdd if=/dev/zero of=$file bs=$PAGE_SIZE oflag=direct count=1 &&\n\t\terror \"write should failed\"\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0\"\n\trm -f $file\n}\nrun_test 313 \"io should fail after last_rcvd update fail\"\n\ntest_314() {\n\t[ $OSTCOUNT -lt 2 ] && skip \"needs >= 2 OSTs\"\n\n\t$LFS setstripe -c 2 -i 0 $DIR/$tfile || error \"setstripe failed\"\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x720\"\n\trm -f $DIR/$tfile\n\twait_delete_completed\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0\"\n}\nrun_test 314 \"OSP shouldn't fail after last_rcvd update failure\"\n\ntest_315() { # LU-618\n\t[ -f /proc/$$/io ] || skip_env \"no IO accounting in kernel\"\n\n\tlocal file=$DIR/$tfile\n\trm -f $file\n\n\t$MULTIOP $file oO_CREAT:O_DIRECT:O_RDWR:w4063232c ||\n\t\terror \"multiop file write failed\"\n\t$MULTIOP $file oO_RDONLY:r4063232_c &\n\tPID=$!\n\n\tsleep 2\n\n\tlocal rbytes=$(awk '/read_bytes/ { print $2 }' /proc/$PID/io)\n\tkill -USR1 $PID\n\n\t[ $rbytes -gt 4000000 ] || error \"read is not accounted ($rbytes)\"\n\trm -f $file\n}\nrun_test 315 \"read should be accounted\"\n\ntest_316() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\tlarge_xattr_enabled || skip_env \"ea_inode feature disabled\"\n\n\trm -rf $DIR/$tdir/d\n\tmkdir -p $DIR/$tdir/d\n\tchown nobody $DIR/$tdir/d\n\ttouch $DIR/$tdir/d/file\n\n\t$LFS mv -m1 $DIR/$tdir/d || error \"lfs mv failed\"\n}\nrun_test 316 \"lfs mv\"\n\ntest_317() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.53) ] &&\n\t\tskip \"Need MDS version at least 2.11.53\"\n\tif [ \"$ost1_FSTYPE\" == \"zfs\" ]; then\n\t\tskip \"LU-10370: no implementation for ZFS\"\n\tfi\n\n\tlocal trunc_sz\n\tlocal grant_blk_size\n\n\tgrant_blk_size=$($LCTL get_param osc.$FSNAME*.import |\n\t\t\tawk '/grant_block_size:/ { print $2; exit; }')\n\t#\n\t# Create File of size 5M. Truncate it to below size's and verify\n\t# blocks count.\n\t#\n\tdd if=/dev/zero of=$DIR/$tfile bs=5M count=1 conv=fsync ||\n\t\terror \"Create file $DIR/$tfile failed\"\n\tstack_trap \"rm -f $DIR/$tfile\" EXIT\n\n\tfor trunc_sz in 2097152 4097 4000 509 0; do\n\t\t$TRUNCATE $DIR/$tfile $trunc_sz ||\n\t\t\terror \"truncate $tfile to $trunc_sz failed\"\n\t\tlocal sz=$(stat --format=%s $DIR/$tfile)\n\t\tlocal blk=$(stat --format=%b $DIR/$tfile)\n\t\tlocal trunc_blk=$((((trunc_sz + (grant_blk_size - 1) ) /\n\t\t\t\t     grant_blk_size) * 8))\n\n\t\tif [[ $blk -ne $trunc_blk ]]; then\n\t\t\t$(which stat) $DIR/$tfile\n\t\t\terror \"Expected Block $trunc_blk got $blk for $tfile\"\n\t\tfi\n\n\t\t$CHECKSTAT -s $trunc_sz $DIR/$tfile ||\n\t\t\terror \"Expected Size $trunc_sz got $sz for $tfile\"\n\tdone\n\n\t#\n\t# sparse file test\n\t# Create file with a hole and write actual two blocks. Block count\n\t# must be 16.\n\t#\n\tdd if=/dev/zero of=$DIR/$tfile bs=$grant_blk_size count=2 seek=5 \\\n\t\tconv=fsync || error \"Create file : $DIR/$tfile\"\n\n\t# Calculate the final truncate size.\n\ttrunc_sz=$(($(stat --format=%s $DIR/$tfile) - (grant_blk_size + 1)))\n\n\t#\n\t# truncate to size $trunc_sz bytes. Strip the last block\n\t# The block count must drop to 8\n\t#\n\t$TRUNCATE $DIR/$tfile $trunc_sz ||\n\t\terror \"truncate $tfile to $trunc_sz failed\"\n\n\tlocal trunc_bsz=$((grant_blk_size / $(stat --format=%B $DIR/$tfile)))\n\tsz=$(stat --format=%s $DIR/$tfile)\n\tblk=$(stat --format=%b $DIR/$tfile)\n\n\tif [[ $blk -ne $trunc_bsz ]]; then\n\t\t$(which stat) $DIR/$tfile\n\t\terror \"Expected Block $trunc_bsz got $blk for $tfile\"\n\tfi\n\n\t$CHECKSTAT -s $trunc_sz $DIR/$tfile ||\n\t\terror \"Expected Size $trunc_sz got $sz for $tfile\"\n}\nrun_test 317 \"Verify blocks get correctly update after truncate\"\n\ntest_318() {\n\tlocal old_max_active=$($LCTL get_param -n \\\n\t\t\t    llite.*.max_read_ahead_async_active 2>/dev/null)\n\n\t$LCTL set_param llite.*.max_read_ahead_async_active=256\n\tlocal max_active=$($LCTL get_param -n \\\n\t\t\t   llite.*.max_read_ahead_async_active 2>/dev/null)\n\t[ $max_active -ne 256 ] && error \"expected 256 but got $max_active\"\n\n\t$LCTL set_param llite.*.max_read_ahead_async_active=0 ||\n\t\terror \"set max_read_ahead_async_active should succeed\"\n\n\t$LCTL set_param llite.*.max_read_ahead_async_active=512\n\tmax_active=$($LCTL get_param -n \\\n\t\t     llite.*.max_read_ahead_async_active 2>/dev/null)\n\t[ $max_active -eq 512 ] || error \"expected 512 but got $max_active\"\n\n\t# restore @max_active\n\t[ $old_max_active -ne 0 ] && $LCTL set_param \\\n\t\tllite.*.max_read_ahead_async_active=$old_max_active\n\n\tlocal old_threshold=$($LCTL get_param -n \\\n\t\tllite.*.read_ahead_async_file_threshold_mb 2>/dev/null)\n\tlocal max_per_file_mb=$($LCTL get_param -n \\\n\t\tllite.*.max_read_ahead_per_file_mb 2>/dev/null)\n\n\tlocal invalid=$(($max_per_file_mb + 1))\n\t$LCTL set_param \\\n\t\tllite.*.read_ahead_async_file_threshold_mb=$invalid\\\n\t\t\t&& error \"set $invalid should fail\"\n\n\tlocal valid=$(($invalid - 1))\n\t$LCTL set_param \\\n\t\tllite.*.read_ahead_async_file_threshold_mb=$valid ||\n\t\t\terror \"set $valid should succeed\"\n\tlocal threshold=$($LCTL get_param -n \\\n\t\tllite.*.read_ahead_async_file_threshold_mb 2>/dev/null)\n\t[ $threshold -eq $valid ] || error \\\n\t\t\"expect threshold $valid got $threshold\"\n\t$LCTL set_param \\\n\t\tllite.*.read_ahead_async_file_threshold_mb=$old_threshold\n}\nrun_test 318 \"Verify async readahead tunables\"\n\ntest_319() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return 0\n\n\tlocal before=$(date +%s)\n\tlocal evict\n\tlocal mdir=$DIR/$tdir\n\tlocal file=$mdir/xxx\n\n\t$LFS mkdir -i0 $mdir || error \"mkdir $mdir fails\"\n\ttouch $file\n\n#define OBD_FAIL_LDLM_LOCAL_CANCEL_PAUSE 0x32c\n\t$LCTL set_param fail_val=5 fail_loc=0x8000032c\n\t$LFS mv -m1 $file &\n\n\tsleep 1\n\tdd if=$file of=/dev/null\n\twait\n\tevict=$($LCTL get_param mdc.$FSNAME-MDT*.state |\n\t  awk -F\"[ [,]\" '/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] || error \"eviction happened\"\n}\nrun_test 319 \"lost lease lock on migrate error\"\n\ntest_398a() { # LU-4198\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\t$LCTL set_param ldlm.namespaces.*.lru_size=clear\n\n\t# request a new lock on client\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=direct conv=notrunc\n\tlocal lock_count=$($LCTL get_param -n \\\n\t\t\t   ldlm.namespaces.*-OST0000-osc-ffff*.lru_size)\n\t[[ $lock_count -eq 0 ]] || error \"lock should be cancelled by direct IO\"\n\n\t$LCTL set_param ldlm.namespaces.*-OST0000-osc-ffff*.lru_size=clear\n\n\t# no lock cached, should use lockless IO and not enqueue new lock\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1 oflag=direct conv=notrunc\n\tlock_count=$($LCTL get_param -n \\\n\t\t     ldlm.namespaces.*-OST0000-osc-ffff*.lru_size)\n\t[[ $lock_count -eq 0 ]] || error \"no lock should be held by direct IO\"\n}\nrun_test 398a \"direct IO should cancel lock otherwise lockless\"\n\ntest_398b() { # LU-4198\n\twhich fio || skip_env \"no fio installed\"\n\t$LFS setstripe -c -1 $DIR/$tfile\n\n\tlocal size=12\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=$size\n\n\tlocal njobs=4\n\techo \"mix direct rw ${size}M to OST0 by fio with $njobs jobs...\"\n\tfio --name=rand-rw --rw=randrw --bs=$PAGE_SIZE --direct=1 \\\n\t\t--numjobs=$njobs --fallocate=none \\\n\t\t--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \\\n\t\t--filename=$DIR/$tfile &\n\tbg_pid=$!\n\n\techo \"mix buffer rw ${size}M to OST0 by fio with $njobs jobs...\"\n\tfio --name=rand-rw --rw=randrw --bs=$PAGE_SIZE \\\n\t\t--numjobs=$njobs --fallocate=none \\\n\t\t--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \\\n\t\t--filename=$DIR/$tfile || true\n\twait $bg_pid\n\n\trm -rf $DIR/$tfile\n}\nrun_test 398b \"DIO and buffer IO race\"\n\ntest_398c() { # LU-4198\n\twhich fio || skip_env \"no fio installed\"\n\n\tsaved_debug=$($LCTL get_param -n debug)\n\t$LCTL set_param debug=0\n\n\tlocal size=$(lctl get_param -n osc.$FSNAME-OST0000*.kbytesavail | head -1)\n\t((size /= 1024)) # by megabytes\n\t((size /= 2)) # write half of the OST at most\n\t[ $size -gt 40 ] && size=40 #reduce test time anyway\n\n\t$LFS setstripe -c 1 $DIR/$tfile\n\n\t# it seems like ldiskfs reserves more space than necessary if the\n\t# writing blocks are not mapped, so it extends the file firstly\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=$size && sync\n\tcancel_lru_locks osc\n\n\t# clear and verify rpc_stats later\n\t$LCTL set_param osc.${FSNAME}-OST0000-osc-ffff*.rpc_stats=clear\n\n\tlocal njobs=4\n\techo \"writing ${size}M to OST0 by fio with $njobs jobs...\"\n\tfio --name=rand-write --rw=randwrite --bs=$PAGE_SIZE --direct=1 \\\n\t\t--numjobs=$njobs --fallocate=none --ioengine=libaio \\\n\t\t--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \\\n\t\t--filename=$DIR/$tfile\n\t[ $? -eq 0 ] || error \"fio write error\"\n\n\t[ $($LCTL get_param -n \\\n\t ldlm.namespaces.${FSNAME}-OST0000-osc-ffff*.lock_count) -eq 0 ] ||\n\t\terror \"Locks were requested while doing AIO\"\n\n\t# get the percentage of 1-page I/O\n\tpct=$($LCTL get_param osc.${FSNAME}-OST0000-osc-ffff*.rpc_stats |\n\t\tgrep -A 1 'pages per rpc' | grep -v 'pages per rpc' |\n\t\tawk '{print $7}')\n\t[ $pct -le 50 ] || error \"$pct% of I/O are 1-page\"\n\n\techo \"mix rw ${size}M to OST0 by fio with $njobs jobs...\"\n\tfio --name=rand-rw --rw=randrw --bs=$PAGE_SIZE --direct=1 \\\n\t\t--numjobs=$njobs --fallocate=none --ioengine=libaio \\\n\t\t--iodepth=16 --allow_file_create=0 --size=$((size/njobs))M \\\n\t\t--filename=$DIR/$tfile\n\t[ $? -eq 0 ] || error \"fio mixed read write error\"\n\n\techo \"AIO with large block size ${size}M\"\n\tfio --name=rand-rw --rw=randrw --bs=${size}M --direct=1 \\\n\t\t--numjobs=1 --fallocate=none --ioengine=libaio \\\n\t\t--iodepth=16 --allow_file_create=0 --size=${size}M \\\n\t\t--filename=$DIR/$tfile\n\t[ $? -eq 0 ] || error \"fio large block size failed\"\n\n\trm -rf $DIR/$tfile\n\t$LCTL set_param debug=\"$saved_debug\"\n}\nrun_test 398c \"run fio to test AIO\"\n\ntest_398d() { #  LU-13846\n\ttest -f aiocp || skip_env \"no aiocp installed\"\n\tlocal aio_file=$DIR/aio_file\n\n\t$LFS setstripe -c -1 -S 1M $DIR/$tfile $aio_file\n\n\tdd if=/dev/urandom of=$DIR/$tfile bs=1M count=64\n\taiocp -a $PAGE_SIZE -b 64M -s 64M -f O_DIRECT $DIR/$tfile $aio_file\n\n\tdiff $DIR/$tfile $aio_file || \"file diff after aiocp\"\n\trm -rf $DIR/$tfile $aio_file\n}\nrun_test 398d \"run aiocp to verify block size > stripe size\"\n\ntest_fake_rw() {\n\tlocal read_write=$1\n\tif [ \"$read_write\" = \"write\" ]; then\n\t\tlocal dd_cmd=\"dd if=/dev/zero of=$DIR/$tfile\"\n\telif [ \"$read_write\" = \"read\" ]; then\n\t\tlocal dd_cmd=\"dd of=/dev/null if=$DIR/$tfile\"\n\telse\n\t\terror \"argument error\"\n\tfi\n\n\t# turn off debug for performance testing\n\tlocal saved_debug=$($LCTL get_param -n debug)\n\t$LCTL set_param debug=0\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\n\t# get ost1 size - $FSNAME-OST0000\n\tlocal ost1_avail_size=$($LFS df | awk /${ost1_svc}/'{ print $4 }')\n\tlocal blocks=$((ost1_avail_size/2/1024)) # half avail space by megabytes\n\t[ $blocks -gt 1000 ] && blocks=1000 # 1G in maximum\n\n\tif [ \"$read_write\" = \"read\" ]; then\n\t\ttruncate -s $(expr 1048576 \\* $blocks) $DIR/$tfile\n\tfi\n\n\tlocal start_time=$(date +%s.%N)\n\t$dd_cmd bs=1M count=$blocks oflag=sync ||\n\t\terror \"real dd $read_write error\"\n\tlocal duration=$(bc <<< \"$(date +%s.%N) - $start_time\")\n\n\tif [ \"$read_write\" = \"write\" ]; then\n\t\trm -f $DIR/$tfile\n\tfi\n\n\t# define OBD_FAIL_OST_FAKE_RW\t\t0x238\n\tdo_facet ost1 $LCTL set_param fail_loc=0x238\n\n\tlocal start_time=$(date +%s.%N)\n\t$dd_cmd bs=1M count=$blocks oflag=sync ||\n\t\terror \"fake dd $read_write error\"\n\tlocal duration_fake=$(bc <<< \"$(date +%s.%N) - $start_time\")\n\n\tif [ \"$read_write\" = \"write\" ]; then\n\t\t# verify file size\n\t\tcancel_lru_locks osc\n\t\t$CHECKSTAT -t file -s $((blocks * 1024 * 1024)) $DIR/$tfile ||\n\t\t\terror \"$tfile size not $blocks MB\"\n\tfi\n\tdo_facet ost1 $LCTL set_param fail_loc=0\n\n\techo \"fake $read_write $duration_fake vs. normal $read_write\" \\\n\t\t\"$duration in seconds\"\n\t[ $(bc <<< \"$duration_fake < $duration\") -eq 1 ] ||\n\t\terror_not_in_vm \"fake write is slower\"\n\n\t$LCTL set_param -n debug=\"$saved_debug\"\n\trm -f $DIR/$tfile\n}\ntest_399a() { # LU-7655 for OST fake write\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\n\ttest_fake_rw write\n}\nrun_test 399a \"fake write should not be slower than normal write\"\n\ntest_399b() { # LU-8726 for OST fake read\n\tremote_ost_nodsh && skip \"remote OST with nodsh\"\n\tif [ \"$ost1_FSTYPE\" != \"ldiskfs\" ]; then\n\t\tskip_env \"ldiskfs only test\"\n\tfi\n\n\ttest_fake_rw read\n}\nrun_test 399b \"fake read should not be slower than normal read\"\n\ntest_400a() { # LU-1606, was conf-sanity test_74\n\tif ! which $CC > /dev/null 2>&1; then\n\t\tskip_env \"$CC is not installed\"\n\tfi\n\n\tlocal extra_flags=''\n\tlocal out=$TMP/$tfile\n\tlocal prefix=/usr/include/lustre\n\tlocal prog\n\n\t# Oleg removes c files in his test rig so test if any c files exist\n\t[ -z \"$(ls -A $LUSTRE_TESTS_API_DIR)\" ] && \\\n\t\tskip_env \"Needed c test files are missing\"\n\n\tif ! [[ -d $prefix ]]; then\n\t\t# Assume we're running in tree and fixup the include path.\n\t\textra_flags+=\" -I$LUSTRE/../lnet/include/uapi -I$LUSTRE/include/uapi -I$LUSTRE/include\"\n\t\textra_flags+=\" -L$LUSTRE/utils/.lib\"\n\tfi\n\n\tfor prog in $LUSTRE_TESTS_API_DIR/*.c; do\n\t\t$CC -Wall -Werror -std=c99 $extra_flags -o $out $prog -llustreapi ||\n\t\t\terror \"client api broken\"\n\tdone\n\trm -f $out\n}\nrun_test 400a \"Lustre client api program can compile and link\"\n\ntest_400b() { # LU-1606, LU-5011\n\tlocal header\n\tlocal out=$TMP/$tfile\n\tlocal prefix=/usr/include/linux/lustre\n\n\t# We use a hard coded prefix so that this test will not fail\n\t# when run in tree. There are headers in lustre/include/lustre/\n\t# that are not packaged (like lustre_idl.h) and have more\n\t# complicated include dependencies (like config.h and lnet/types.h).\n\t# Since this test about correct packaging we just skip them when\n\t# they don't exist (see below) rather than try to fixup cppflags.\n\n\tif ! which $CC > /dev/null 2>&1; then\n\t\tskip_env \"$CC is not installed\"\n\tfi\n\n\tfor header in $prefix/*.h; do\n\t\tif ! [[ -f \"$header\" ]]; then\n\t\t\tcontinue\n\t\tfi\n\n\t\tif [[ \"$(basename $header)\" == lustre_ioctl.h ]]; then\n\t\t\tcontinue # lustre_ioctl.h is internal header\n\t\tfi\n\n\t\t$CC -Wall -Werror -std=c99 -include $header -c -x c /dev/null -o $out ||\n\t\t\terror \"cannot compile '$header'\"\n\tdone\n\trm -f $out\n}\nrun_test 400b \"packaged headers can be compiled\"\n\ntest_401a() { #LU-7437\n\tlocal printf_arg=$(find -printf 2>&1 | grep \"unrecognized:\")\n\t[ -n \"$printf_arg\" ] && skip_env \"find does not support -printf\"\n\n\t#count the number of parameters by \"list_param -R\"\n\tlocal params=$($LCTL list_param -R '*' 2>/dev/null | wc -l)\n\t#count the number of parameters by listing proc files\n\tlocal proc_regexp=\"/{proc,sys}/{fs,sys,kernel/debug}/{lustre,lnet}/\"\n\tlocal proc_dirs=$(eval \\ls -d $proc_regexp 2>/dev/null)\n\techo \"proc_dirs='$proc_dirs'\"\n\t[ -n \"$proc_dirs\" ] || error \"no proc_dirs on $HOSTNAME\"\n\tlocal procs=$(find -L $proc_dirs -mindepth 1 -printf '%P\\n' 2>/dev/null|\n\t\t      sort -u | wc -l)\n\n\t[ $params -eq $procs ] ||\n\t\terror \"found $params parameters vs. $procs proc files\"\n\n\t# test the list_param -D option only returns directories\n\tparams=$($LCTL list_param -R -D '*' 2>/dev/null | wc -l)\n\t#count the number of parameters by listing proc directories\n\tprocs=$(find -L $proc_dirs -mindepth 1 -type d -printf '%P\\n' 2>/dev/null |\n\t\tsort -u | wc -l)\n\n\t[ $params -eq $procs ] ||\n\t\terror \"found $params parameters vs. $procs proc files\"\n}\nrun_test 401a \"Verify if 'lctl list_param -R' can list parameters recursively\"\n\ntest_401b() {\n\tlocal save=$($LCTL get_param -n jobid_var)\n\tlocal tmp=testing\n\n\t$LCTL set_param foo=bar jobid_var=$tmp bar=baz &&\n\t\terror \"no error returned when setting bad parameters\"\n\n\tlocal jobid_new=$($LCTL get_param -n foe jobid_var baz)\n\t[[ \"$jobid_new\" == \"$tmp\" ]] || error \"jobid tmp $jobid_new != $tmp\"\n\n\t$LCTL set_param -n fog=bam jobid_var=$save bat=fog\n\tlocal jobid_old=$($LCTL get_param -n foe jobid_var bag)\n\t[[ \"$jobid_old\" == \"$save\" ]] || error \"jobid new $jobid_old != $save\"\n}\nrun_test 401b \"Verify 'lctl {get,set}_param' continue after error\"\n\ntest_401c() {\n\tlocal jobid_var_old=$($LCTL get_param -n jobid_var)\n\tlocal jobid_var_new\n\n\t$LCTL set_param jobid_var= &&\n\t\terror \"no error returned for 'set_param a='\"\n\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_old\" == \"$jobid_var_new\" ]] ||\n\t\terror \"jobid_var was changed by setting without value\"\n\n\t$LCTL set_param jobid_var &&\n\t\terror \"no error returned for 'set_param a'\"\n\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_old\" == \"$jobid_var_new\" ]] ||\n\t\terror \"jobid_var was changed by setting without value\"\n}\nrun_test 401c \"Verify 'lctl set_param' without value fails in either format.\"\n\ntest_401d() {\n\tlocal jobid_var_old=$($LCTL get_param -n jobid_var)\n\tlocal jobid_var_new\n\tlocal new_value=\"foo=bar\"\n\n\t$LCTL set_param jobid_var=$new_value ||\n\t\terror \"'set_param a=b' did not accept a value containing '='\"\n\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_new\" == \"$new_value\" ]] ||\n\t\terror \"'set_param a=b' failed on a value containing '='\"\n\n\t# Reset the jobid_var to test the other format\n\t$LCTL set_param jobid_var=$jobid_var_old\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_new\" == \"$jobid_var_old\" ]] ||\n\t\terror \"failed to reset jobid_var\"\n\n\t$LCTL set_param jobid_var $new_value ||\n\t\terror \"'set_param a b' did not accept a value containing '='\"\n\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_new\" == \"$new_value\" ]] ||\n\t\terror \"'set_param a b' failed on a value containing '='\"\n\n\t$LCTL set_param jobid_var $jobid_var_old\n\tjobid_var_new=$($LCTL get_param -n jobid_var)\n\t[[ \"$jobid_var_new\" == \"$jobid_var_old\" ]] ||\n\t\terror \"failed to reset jobid_var\"\n}\nrun_test 401d \"Verify 'lctl set_param' accepts values containing '='\"\n\ntest_402() {\n\t[[ $MDS1_VERSION -ge $(version_code 2.7.66) ]] ||\n\t[[ $MDS1_VERSION -ge $(version_code 2.7.18.4) &&\n\t\t$MDS1_VERSION -lt $(version_code 2.7.50) ]] ||\n\t[[ $MDS1_VERSION -ge $(version_code 2.7.2) &&\n\t\t$MDS1_VERSION -lt $(version_code 2.7.11) ]] ||\n\t\tskip \"Need MDS version 2.7.2+ or 2.7.18.4+ or 2.7.66+\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\t$LFS setdirstripe -i 0 $DIR/$tdir || error \"setdirstripe -i 0 failed\"\n#define OBD_FAIL_MDS_FLD_LOOKUP 0x15c\n\tdo_facet mds1 \"lctl set_param fail_loc=0x8000015c\"\n\ttouch $DIR/$tdir/$tfile && error \"touch should fail with ENOENT\" ||\n\t\techo \"Touch failed - OK\"\n}\nrun_test 402 \"Return ENOENT to lod_generate_and_set_lovea\"\n\ntest_403() {\n\tlocal file1=$DIR/$tfile.1\n\tlocal file2=$DIR/$tfile.2\n\tlocal tfile=$TMP/$tfile\n\n\trm -f $file1 $file2 $tfile\n\n\ttouch $file1\n\tln $file1 $file2\n\n\t# 30 sec OBD_TIMEOUT in ll_getattr()\n\t# right before populating st_nlink\n\t$LCTL set_param fail_loc=0x80001409\n\tstat -c %h $file1 > $tfile &\n\n\t# create an alias, drop all locks and reclaim the dentry\n\t< $file2\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\tsysctl -w vm.drop_caches=2\n\n\twait\n\n\t[ $(cat $tfile) -gt 0 ] || error \"wrong nlink count: $(cat $tfile)\"\n\n\trm -f $tfile $file1 $file2\n}\nrun_test 403 \"i_nlink should not drop to zero due to aliasing\"\n\ntest_404() { # LU-6601\n\t[[ $MDS1_VERSION -ge $(version_code 2.8.53) ]] ||\n\t\tskip \"Need server version newer than 2.8.52\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tlocal mosps=$(do_facet $SINGLEMDS $LCTL dl |\n\t\tawk '/osp .*-osc-MDT/ { print $4}')\n\n\tlocal osp\n\tfor osp in $mosps; do\n\t\techo \"Deactivate: \" $osp\n\t\tdo_facet $SINGLEMDS $LCTL --device %$osp deactivate\n\t\tlocal stat=$(do_facet $SINGLEMDS $LCTL dl |\n\t\t\tawk -vp=$osp '$4 == p { print $2 }')\n\t\t[ $stat = IN ] || {\n\t\t\tdo_facet $SINGLEMDS $LCTL dl | grep -w $osp\n\t\t\terror \"deactivate error\"\n\t\t}\n\t\techo \"Activate: \" $osp\n\t\tdo_facet $SINGLEMDS $LCTL --device %$osp activate\n\t\tlocal stat=$(do_facet $SINGLEMDS $LCTL dl |\n\t\t\tawk -vp=$osp '$4 == p { print $2 }')\n\t\t[ $stat = UP ] || {\n\t\t\tdo_facet $SINGLEMDS $LCTL dl | grep -w $osp\n\t\t\terror \"activate error\"\n\t\t}\n\tdone\n}\nrun_test 404 \"validate manual {de}activated works properly for OSPs\"\n\ntest_405() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\t[ $MDS1_VERSION -lt $(version_code 2.6.92) ] ||\n\t\t[ $CLIENT_VERSION -lt $(version_code 2.6.99) ] &&\n\t\t\tskip \"Layout swap lock is not supported\"\n\n\tcheck_swap_layouts_support\n\tcheck_swap_layout_no_dom $DIR\n\n\ttest_mkdir $DIR/$tdir\n\tswap_lock_test -d $DIR/$tdir ||\n\t\terror \"One layout swap locked test failed\"\n}\nrun_test 405 \"Various layout swap lock tests\"\n\ntest_406() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[ $OSTCOUNT -lt 2 ] && skip_env \"needs >= 2 OSTs\"\n\t[ -n \"$FILESET\" ] && skip \"SKIP due to FILESET set\"\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDS1_VERSION -lt $(version_code 2.8.50) ] &&\n\t\tskip \"Need MDS version at least 2.8.50\"\n\n\tlocal def_stripe_size=$($LFS getstripe -S $MOUNT)\n\tlocal test_pool=$TESTNAME\n\n\tpool_add $test_pool || error \"pool_add failed\"\n\tpool_add_targets $test_pool 0 $(($OSTCOUNT - 1)) 1 ||\n\t\terror \"pool_add_targets failed\"\n\n\tsave_layout_restore_at_exit $MOUNT\n\n\t# parent set default stripe count only, child will stripe from both\n\t# parent and fs default\n\t$LFS setstripe -c 1 -i 1 -S $((def_stripe_size * 2)) -p $test_pool $MOUNT ||\n\t\terror \"setstripe $MOUNT failed\"\n\t$LFS mkdir -c $MDSCOUNT $DIR/$tdir || error \"mkdir $tdir failed\"\n\t$LFS setstripe -c $OSTCOUNT $DIR/$tdir || error \"setstripe $tdir failed\"\n\tfor i in $(seq 10); do\n\t\tlocal f=$DIR/$tdir/$tfile.$i\n\t\ttouch $f || error \"touch failed\"\n\t\tlocal count=$($LFS getstripe -c $f)\n\t\t[ $count -eq $OSTCOUNT ] ||\n\t\t\terror \"$f stripe count $count != $OSTCOUNT\"\n\t\tlocal offset=$($LFS getstripe -i $f)\n\t\t[ $offset -eq 1 ] || error \"$f stripe offset $offset != 1\"\n\t\tlocal size=$($LFS getstripe -S $f)\n\t\t[ $size -eq $((def_stripe_size * 2)) ] ||\n\t\t\terror \"$f stripe size $size != $((def_stripe_size * 2))\"\n\t\tlocal pool=$($LFS getstripe -p $f)\n\t\t[ $pool == $test_pool ] || error \"$f pool $pool != $test_pool\"\n\tdone\n\n\t# change fs default striping, delete parent default striping, now child\n\t# will stripe from new fs default striping only\n\t$LFS setstripe -c 1 -S $def_stripe_size -i 0 $MOUNT ||\n\t\terror \"change $MOUNT default stripe failed\"\n\t$LFS setstripe -c 0 $DIR/$tdir ||\n\t\terror \"delete $tdir default stripe failed\"\n\tfor i in $(seq 11 20); do\n\t\tlocal f=$DIR/$tdir/$tfile.$i\n\t\ttouch $f || error \"touch $f failed\"\n\t\tlocal count=$($LFS getstripe -c $f)\n\t\t[ $count -eq 1 ] || error \"$f stripe count $count != 1\"\n\t\tlocal offset=$($LFS getstripe -i $f)\n\t\t[ $offset -eq 0 ] || error \"$f stripe offset $offset != 0\"\n\t\tlocal size=$($LFS getstripe -S $f)\n\t\t[ $size -eq $def_stripe_size ] ||\n\t\t\terror \"$f stripe size $size != $def_stripe_size\"\n\t\tlocal pool=$($LFS getstripe -p $f)\n\t\t[ $pool == $test_pool ] || error \"$f pool $pool isn't set\"\n\tdone\n\n\tunlinkmany $DIR/$tdir/$tfile. 1 20\n\n\tlocal f=$DIR/$tdir/$tfile\n\tpool_remove_all_targets $test_pool $f\n\tpool_remove $test_pool $f\n}\nrun_test 406 \"DNE support fs default striping\"\n\ntest_407() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.8.55) ]] &&\n\t\tskip \"Need MDS version at least 2.8.55\"\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir.0 ||\n\t\terror \"$LFS mkdir -i 0 -c 1 $tdir.0 failed\"\n\t$LFS mkdir -i 1 -c 1 $DIR/$tdir.1 ||\n\t\terror \"$LFS mkdir -i 1 -c 1 $tdir.1 failed\"\n\ttouch $DIR/$tdir.0/$tfile.0 || error \"touch $tdir.0/$tfile.0 failed\"\n\n\t#define OBD_FAIL_DT_TXN_STOP\t0x2019\n\tfor idx in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$idx \"lctl set_param fail_loc=0x2019\"\n\tdone\n\t$LFS mkdir -c 2 $DIR/$tdir && error \"$LFS mkdir -c 2 $tdir should fail\"\n\tmv $DIR/$tdir.0/$tfile.0 $DIR/$tdir.1/$tfile.1 &&\n\t\terror \"mv $tdir.0/$tfile.0 $tdir.1/$tfile.1 should fail\"\n\ttrue\n}\nrun_test 407 \"transaction fail should cause operation fail\"\n\ntest_408() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=$PAGE_SIZE count=1 oflag=direct\n\n\t#define OBD_FAIL_OSC_BRW_PREP_REQ2        0x40a\n\tlctl set_param fail_loc=0x8000040a\n\t# let ll_prepare_partial_page() fail\n\tdd if=/dev/zero of=$DIR/$tfile bs=2048 count=1 conv=notrunc || true\n\n\trm -f $DIR/$tfile\n\n\t# create at least 100 unused inodes so that\n\t# shrink_icache_memory(0) should not return 0\n\ttouch $DIR/$tfile-{0..100}\n\trm -f $DIR/$tfile-{0..100}\n\tsync\n\n\techo 2 > /proc/sys/vm/drop_caches\n}\nrun_test 408 \"drop_caches should not hang due to page leaks\"\n\ntest_409()\n{\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\n\tmkdir -p $DIR/$tdir || error \"(0) Fail to mkdir\"\n\t$LFS mkdir -i 1 -c 2 $DIR/$tdir/foo || error \"(1) Fail to mkdir\"\n\ttouch $DIR/$tdir/guard || error \"(2) Fail to create\"\n\n\tlocal PREFIX=$(str_repeat 'A' 128)\n\techo \"Create 1K hard links start at $(date)\"\n\tcreatemany -l $DIR/$tdir/guard $DIR/$tdir/foo/${PREFIX}_ 1000 ||\n\t\terror \"(3) Fail to hard link\"\n\n\techo \"Links count should be right although linkEA overflow\"\n\tstat $DIR/$tdir/guard || error \"(4) Fail to stat\"\n\tlocal linkcount=$(stat --format=%h $DIR/$tdir/guard)\n\t[ $linkcount -eq 1001 ] ||\n\t\terror \"(5) Unexpected hard links count: $linkcount\"\n\n\techo \"List all links start at $(date)\"\n\tls -l $DIR/$tdir/foo > /dev/null ||\n\t\terror \"(6) Fail to list $DIR/$tdir/foo\"\n\n\techo \"Unlink hard links start at $(date)\"\n\tunlinkmany $DIR/$tdir/foo/${PREFIX}_ 1000 ||\n\t\terror \"(7) Fail to unlink\"\n\techo \"Unlink hard links finished at $(date)\"\n}\nrun_test 409 \"Large amount of cross-MDTs hard links on the same file\"\n\ntest_410()\n{\n\t[[ $CLIENT_VERSION -lt $(version_code 2.9.59) ]] &&\n\t\tskip \"Need client version at least 2.9.59\"\n\t[ -f $LUSTRE/tests/kernel/kinode.ko ] ||\n\t\tskip \"Need MODULES build\"\n\n\t# Create a file, and stat it from the kernel\n\tlocal testfile=$DIR/$tfile\n\ttouch $testfile\n\n\tlocal run_id=$RANDOM\n\tlocal my_ino=$(stat --format \"%i\" $testfile)\n\n\t# Try to insert the module. This will always fail as the\n\t# module is designed to not be inserted.\n\tinsmod $LUSTRE/tests/kernel/kinode.ko run_id=$run_id fname=$testfile \\\n\t    &> /dev/null\n\n\t# Anything but success is a test failure\n\tdmesg | grep -q \\\n\t    \"lustre_kinode_$run_id: inode numbers are identical: $my_ino\" ||\n\t    error \"no inode match\"\n}\nrun_test 410 \"Test inode number returned from kernel thread\"\n\ncleanup_test411_cgroup() {\n\ttrap 0\n\trmdir \"$1\"\n}\n\ntest_411() {\n\tlocal cg_basedir=/sys/fs/cgroup/memory\n\t# LU-9966\n\ttest -f \"$cg_basedir/memory.kmem.limit_in_bytes\" ||\n\t\tskip \"no setup for cgroup\"\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=100 conv=fsync ||\n\t\terror \"test file creation failed\"\n\tcancel_lru_locks osc\n\n\t# Create a very small memory cgroup to force a slab allocation error\n\tlocal cgdir=$cg_basedir/osc_slab_alloc\n\tmkdir $cgdir || error \"cgroup mkdir '$cgdir' failed\"\n\ttrap \"cleanup_test411_cgroup $cgdir\" EXIT\n\techo 2M > $cgdir/memory.kmem.limit_in_bytes\n\techo 1M > $cgdir/memory.limit_in_bytes\n\n\t# Should not LBUG, just be killed by oom-killer\n\t# dd will return 0 even allocation failure in some environment.\n\t# So don't check return value\n\tsh -c \"echo \\$$ > $cgdir/tasks && dd if=$DIR/$tfile of=/dev/null\"\n\tcleanup_test411_cgroup $cgdir\n\n\treturn 0\n}\nrun_test 411 \"Slab allocation error with cgroup does not LBUG\"\n\ntest_412() {\n\t[ $MDSCOUNT -lt 2 ] && skip_env \"needs >= 2 MDTs\"\n\tif [ $MDS1_VERSION -lt $(version_code 2.10.55) ]; then\n\t\tskip \"Need server version at least 2.10.55\"\n\tfi\n\n\t$LFS mkdir -i $((MDSCOUNT - 1)),$((MDSCOUNT - 2)) $DIR/$tdir ||\n\t\terror \"mkdir failed\"\n\t$LFS getdirstripe $DIR/$tdir\n\tlocal stripe_index=$($LFS getdirstripe -i $DIR/$tdir)\n\t[ $stripe_index -eq $((MDSCOUNT - 1)) ] ||\n\t\terror \"expect $((MDSCOUT - 1)) get $stripe_index\"\n\tlocal stripe_count=$($LFS getdirstripe -T $DIR/$tdir)\n\t[ $stripe_count -eq 2 ] ||\n\t\terror \"expect 2 get $stripe_count\"\n}\nrun_test 412 \"mkdir on specific MDTs\"\n\ntest_qos_mkdir() {\n\tlocal mkdir_cmd=$1\n\tlocal stripe_count=$2\n\tlocal mdts=$(comma_list $(mdts_nodes))\n\n\tlocal testdir\n\tlocal lmv_qos_prio_free\n\tlocal lmv_qos_threshold_rr\n\tlocal lmv_qos_maxage\n\tlocal lod_qos_prio_free\n\tlocal lod_qos_threshold_rr\n\tlocal lod_qos_maxage\n\tlocal count\n\tlocal i\n\n\tlmv_qos_prio_free=$($LCTL get_param -n lmv.*.qos_prio_free | head -n1)\n\tlmv_qos_prio_free=${lmv_qos_prio_free%%%}\n\tlmv_qos_threshold_rr=$($LCTL get_param -n lmv.*.qos_threshold_rr |\n\t\thead -n1)\n\tlmv_qos_threshold_rr=${lmv_qos_threshold_rr%%%}\n\tlmv_qos_maxage=$($LCTL get_param -n lmv.*.qos_maxage)\n\tstack_trap \"$LCTL set_param \\\n\t\tlmv.*.qos_prio_free=$lmv_qos_prio_free > /dev/null\" EXIT\n\tstack_trap \"$LCTL set_param \\\n\t\tlmv.*.qos_threshold_rr=$lmv_qos_threshold_rr > /dev/null\" EXIT\n\tstack_trap \"$LCTL set_param \\\n\t\tlmv.*.qos_maxage=$lmv_qos_maxage > /dev/null\" EXIT\n\n\tlod_qos_prio_free=$(do_facet mds1 $LCTL get_param -n \\\n\t\tlod.$FSNAME-MDT0000-mdtlov.mdt_qos_prio_free | head -n1)\n\tlod_qos_prio_free=${lod_qos_prio_free%%%}\n\tlod_qos_threshold_rr=$(do_facet mds1 $LCTL get_param -n \\\n\t\tlod.$FSNAME-MDT0000-mdtlov.mdt_qos_threshold_rr | head -n1)\n\tlod_qos_threshold_rr=${lod_qos_threshold_rr%%%}\n\tlod_qos_maxage=$(do_facet mds1 $LCTL get_param -n \\\n\t\tlod.$FSNAME-MDT0000-mdtlov.qos_maxage | awk '{ print $1 }')\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\tlod.*.mdt_qos_prio_free=$lod_qos_prio_free > /dev/null\" EXIT\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\tlod.*.mdt_qos_threshold_rr=$lod_qos_threshold_rr > /dev/null\" \\\n\t\tEXIT\n\tstack_trap \"do_nodes $mdts $LCTL set_param \\\n\t\tlod.*.mdt_qos_maxage=$lod_qos_maxage > /dev/null\" EXIT\n\n\techo\n\techo \"Mkdir (stripe_count $stripe_count) roundrobin:\"\n\n\t$LCTL set_param lmv.*.qos_threshold_rr=100 > /dev/null\n\tdo_nodes $mdts $LCTL set_param lod.*.mdt_qos_threshold_rr=100 > /dev/null\n\n\ttestdir=$DIR/$tdir-s$stripe_count/rr\n\n\tfor i in $(seq $((100 * MDSCOUNT))); do\n\t\teval $mkdir_cmd $testdir/subdir$i ||\n\t\t\terror \"$mkdir_cmd subdir$i failed\"\n\tdone\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tcount=$($LFS getdirstripe -i $testdir/* |\n\t\t\t\tgrep ^$((i - 1))$ | wc -l)\n\t\techo \"$count directories created on MDT$((i - 1))\"\n\t\t[ $count -eq 100 ] || error \"subdirs are not evenly distributed\"\n\n\t\tif [ $stripe_count -gt 1 ]; then\n\t\t\tcount=$($LFS getdirstripe $testdir/* |\n\t\t\t\tgrep -P \"^\\s+$((i - 1))\\t\" | wc -l)\n\t\t\techo \"$count stripes created on MDT$((i - 1))\"\n\t\t\t# deviation should < 5% of average\n\t\t\t[ $count -lt $((95 * stripe_count)) ] ||\n\t\t\t[ $count -gt $((105 * stripe_count)) ] &&\n\t\t\t\terror \"stripes are not evenly distributed\"\n\t\tfi\n\tdone\n\n\t$LCTL set_param lmv.*.qos_threshold_rr=$lmv_qos_threshold_rr > /dev/null\n\tdo_nodes $mdts $LCTL set_param \\\n\t\tlod.*.mdt_qos_threshold_rr=$lod_qos_threshold_rr > /dev/null\n\n\techo\n\techo \"Check for uneven MDTs: \"\n\n\tlocal ffree\n\tlocal bavail\n\tlocal max\n\tlocal min\n\tlocal max_index\n\tlocal min_index\n\tlocal tmp\n\n\tffree=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.filesfree))\n\tbavail=($(lctl get_param -n mdc.*[mM][dD][cC]-[^M]*.kbytesavail))\n\tbsize=$(lctl get_param -n mdc.*MDT0000*.blocksize)\n\n\tmax=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))\n\tmin=$(((${ffree[0]} >> 8) * (${bavail[0]} * bsize >> 16)))\n\tmax_index=0\n\tmin_index=0\n\tfor ((i = 1; i < ${#ffree[@]}; i++)); do\n\t\ttmp=$(((${ffree[i]} >> 8) * (${bavail[i]} * bsize >> 16)))\n\t\tif [ $tmp -gt $max ]; then\n\t\t\tmax=$tmp\n\t\t\tmax_index=$i\n\t\tfi\n\t\tif [ $tmp -lt $min ]; then\n\t\t\tmin=$tmp\n\t\t\tmin_index=$i\n\t\tfi\n\tdone\n\n\t[ ${ffree[min_index]} -eq 0 ] &&\n\t\tskip \"no free files in MDT$min_index\"\n\t[ ${ffree[min_index]} -gt 100000000 ] &&\n\t\tskip \"too much free files in MDT$min_index\"\n\n\t# Check if we need to generate uneven MDTs\n\tlocal threshold=50\n\tlocal diff=$(((max - min) * 100 / min))\n\tlocal value=\"$(generate_string 1024)\"\n\n\twhile [ $diff -lt $threshold ]; do\n\t\t# generate uneven MDTs, create till $threshold% diff\n\t\techo -n \"weight diff=$diff% must be > $threshold% ...\"\n\t\tcount=$((${ffree[min_index]} / 10))\n\t\t# 50 sec per 10000 files in vm\n\t\t[ $count -gt 40000 ] && [ \"$SLOW\" = \"no\" ] &&\n\t\t\tskip \"$count files to create\"\n\t\techo \"Fill MDT$min_index with $count files\"\n\t\t[ -d $DIR/$tdir-MDT$min_index ] ||\n\t\t\t$LFS mkdir -i $min_index $DIR/$tdir-MDT$min_index ||\n\t\t\terror \"mkdir $tdir-MDT$min_index failed\"\n\t\tfor i in $(seq $count); do\n\t\t\t$OPENFILE -f O_CREAT:O_LOV_DELAY_CREATE \\\n\t\t\t\t$DIR/$tdir-MDT$min_index/f$j_$i > /dev/null ||\n\t\t\t\terror \"create f$j_$i failed\"\n\t\t\tsetfattr -n user.413b -v $value \\\n\t\t\t\t$DIR/$tdir-MDT$min_index/f$j_$i ||\n\t\t\t\terror \"setfattr f$j_$i failed\"\n\t\tdone\n\n\t\tffree=($(lctl get_param -n mdc.*[mM][dD][cC]-*.filesfree))\n\t\tbavail=($(lctl get_param -n mdc.*[mM][dD][cC]-*.kbytesavail))\n\t\tmax=$(((${ffree[max_index]} >> 8) * \\\n\t\t\t(${bavail[max_index]} * bsize >> 16)))\n\t\tmin=$(((${ffree[min_index]} >> 8) * \\\n\t\t\t(${bavail[min_index]} * bsize >> 16)))\n\t\tdiff=$(((max - min) * 100 / min))\n\tdone\n\n\techo \"MDT filesfree available: ${ffree[@]}\"\n\techo \"MDT blocks available: ${bavail[@]}\"\n\techo \"weight diff=$diff%\"\n\n\techo\n\techo \"Mkdir (stripe_count $stripe_count) with balanced space usage:\"\n\n\t$LCTL set_param lmv.*.qos_prio_free=100 > /dev/null\n\tdo_nodes $mdts $LCTL set_param lod.*.mdt_qos_prio_free=100 > /dev/null\n\t# decrease statfs age, so that it can be updated in time\n\t$LCTL set_param lmv.*.qos_maxage=1 > /dev/null\n\tdo_nodes $mdts $LCTL set_param lod.*.mdt_qos_maxage=1 > /dev/null\n\n\tsleep 1\n\n\ttestdir=$DIR/$tdir-s$stripe_count/qos\n\n\tfor i in $(seq $((100 * MDSCOUNT))); do\n\t\teval $mkdir_cmd $testdir/subdir$i ||\n\t\t\terror \"$mkdir_cmd subdir$i failed\"\n\tdone\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\tcount=$($LFS getdirstripe -i $testdir/* | grep ^$((i - 1))$ |\n\t\t\twc -l)\n\t\techo \"$count directories created on MDT$((i - 1))\"\n\n\t\tif [ $stripe_count -gt 1 ]; then\n\t\t\tcount=$($LFS getdirstripe $testdir/* |\n\t\t\t\tgrep -P \"^\\s+$((i - 1))\\t\" | wc -l)\n\t\t\techo \"$count stripes created on MDT$((i - 1))\"\n\t\tfi\n\tdone\n\n\tmax=$($LFS getdirstripe -i $testdir/* | grep ^$max_index$ | wc -l)\n\tmin=$($LFS getdirstripe -i $testdir/* | grep ^$min_index$ | wc -l)\n\n\t# D-value should > 10% of averge\n\t[ $((max - min)) -lt 10 ] &&\n\t\terror \"subdirs shouldn't be evenly distributed\"\n\n\t# ditto\n\tif [ $stripe_count -gt 1 ]; then\n\t\tmax=$($LFS getdirstripe $testdir/* |\n\t\t\tgrep -P \"^\\s+$max_index\\t\" | wc -l)\n\t\tmin=$($LFS getdirstripe $testdir/* |\n\t\t\tgrep -P \"^\\s+$min_index\\t\" | wc -l)\n\t\t[ $((max - min)) -le $((10 * stripe_count)) ] &&\n\t\t\terror \"stripes shouldn't be evenly distributed\"|| true\n\tfi\n}\n\ntest_413a() {\n\t[ $MDSCOUNT -lt 2 ] &&\n\t\tskip \"We need at least 2 MDTs for this test\"\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.52) ] &&\n\t\tskip \"Need server version at least 2.12.52\"\n\n\tlocal stripe_count\n\n\tfor stripe_count in $(seq 1 $((MDSCOUNT - 1))); do\n\t\tmkdir $DIR/$tdir-s$stripe_count || error \"mkdir failed\"\n\t\tmkdir $DIR/$tdir-s$stripe_count/rr || error \"mkdir failed\"\n\t\tmkdir $DIR/$tdir-s$stripe_count/qos || error \"mkdir failed\"\n\t\ttest_qos_mkdir \"$LFS mkdir -c $stripe_count\" $stripe_count\n\tdone\n}\nrun_test 413a \"QoS mkdir with 'lfs mkdir -i -1'\"\n\ntest_413b() {\n\t[ $MDSCOUNT -lt 2 ] &&\n\t\tskip \"We need at least 2 MDTs for this test\"\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.52) ] &&\n\t\tskip \"Need server version at least 2.12.52\"\n\n\tlocal stripe_count\n\n\tfor stripe_count in $(seq 1 $((MDSCOUNT - 1))); do\n\t\tmkdir $DIR/$tdir-s$stripe_count || error \"mkdir failed\"\n\t\tmkdir $DIR/$tdir-s$stripe_count/rr || error \"mkdir failed\"\n\t\tmkdir $DIR/$tdir-s$stripe_count/qos || error \"mkdir failed\"\n\t\t$LFS setdirstripe -D -c $stripe_count \\\n\t\t\t$DIR/$tdir-s$stripe_count/rr ||\n\t\t\terror \"setdirstripe failed\"\n\t\t$LFS setdirstripe -D -c $stripe_count \\\n\t\t\t$DIR/$tdir-s$stripe_count/qos ||\n\t\t\terror \"setdirstripe failed\"\n\t\ttest_qos_mkdir \"mkdir\" $stripe_count\n\tdone\n}\nrun_test 413b \"QoS mkdir under dir whose default LMV starting MDT offset is -1\"\n\ntest_414() {\n#define OBD_FAIL_PTLRPC_BULK_ATTACH      0x521\n\t$LCTL set_param fail_loc=0x80000521\n\tdd if=/dev/zero of=$DIR/$tfile bs=2M count=1 oflag=sync\n\trm -f $DIR/$tfile\n}\nrun_test 414 \"simulate ENOMEM in ptlrpc_register_bulk()\"\n\ntest_415() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need server version at least 2.11.52\"\n\n\t# LU-11102\n\tlocal total\n\tlocal setattr_pid\n\tlocal start_time\n\tlocal end_time\n\tlocal duration\n\n\ttotal=500\n\t# this test may be slow on ZFS\n\t[ \"$mds1_FSTYPE\" == \"zfs\" ] && total=100\n\n\t# though this test is designed for striped directory, let's test normal\n\t# directory too since lock is always saved as CoS lock.\n\ttest_mkdir $DIR/$tdir || error \"mkdir $tdir\"\n\tcreatemany -o $DIR/$tdir/$tfile. $total || error \"createmany\"\n\n\t(\n\t\twhile true; do\n\t\t\ttouch $DIR/$tdir\n\t\tdone\n\t) &\n\tsetattr_pid=$!\n\n\tstart_time=$(date +%s)\n\tfor i in $(seq $total); do\n\t\tmrename $DIR/$tdir/$tfile.$i $DIR/$tdir/$tfile-new.$i \\\n\t\t\t> /dev/null\n\tdone\n\tend_time=$(date +%s)\n\tduration=$((end_time - start_time))\n\n\tkill -9 $setattr_pid\n\n\techo \"rename $total files took $duration sec\"\n\t[ $duration -lt 100 ] || error \"rename took $duration sec\"\n}\nrun_test 415 \"lock revoke is not missing\"\n\ntest_416() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&\n\t\tskip \"Need server version at least 2.11.55\"\n\n\t# define OBD_FAIL_OSD_TXN_START    0x19a\n\tdo_facet mds1 lctl set_param fail_loc=0x19a\n\n\tlfs mkdir -c $MDSCOUNT $DIR/$tdir\n\n\ttrue\n}\nrun_test 416 \"transaction start failure won't cause system hung\"\n\ncleanup_417() {\n\ttrap 0\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_dir_migration=1\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_remote_dir=1\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_striped_dir=1\"\n}\n\ntest_417() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.11.56) ]] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\ttrap cleanup_417 RETURN EXIT\n\n\t$LFS mkdir -i 1 $DIR/$tdir.1 || error \"create remote dir $tdir.1 failed\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_dir_migration=0\"\n\t$LFS migrate -m 0 $DIR/$tdir.1 &&\n\t\terror \"migrate dir $tdir.1 should fail\"\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_remote_dir=0\"\n\t$LFS mkdir -i 1 $DIR/$tdir.2 &&\n\t\terror \"create remote dir $tdir.2 should fail\"\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"$LCTL set_param -n mdt.*MDT*.enable_striped_dir=0\"\n\t$LFS mkdir -c 2 $DIR/$tdir.3 &&\n\t\terror \"create striped dir $tdir.3 should fail\"\n\ttrue\n}\nrun_test 417 \"disable remote dir, striped dir and dir migration\"\n\n# Checks that the outputs of df [-i] and lfs df [-i] match\n#\n# usage: check_lfs_df <blocks | inodes> <mountpoint>\ncheck_lfs_df() {\n\tlocal dir=$2\n\tlocal inodes\n\tlocal df_out\n\tlocal lfs_df_out\n\tlocal count\n\tlocal passed=false\n\n\t# blocks or inodes\n\t[ \"$1\" == \"blocks\" ] && inodes= || inodes=\"-i\"\n\n\tfor count in {1..100}; do\n\t\tcancel_lru_locks\n\t\tsync; sleep 0.2\n\n\t\t# read the lines of interest\n\t\tdf_out=($(df -P $inodes $dir | tail -n +2)) ||\n\t\t\terror \"df $inodes $dir | tail -n +2 failed\"\n\t\tlfs_df_out=($($LFS df $inodes $dir | grep summary:)) ||\n\t\t\terror \"lfs df $inodes $dir | grep summary: failed\"\n\n\t\t# skip first substrings of each output as they are different\n\t\t# \"<NID>:/<fsname>\" for df, \"filesystem_summary:\" for lfs df\n\t\t# compare the two outputs\n\t\tpassed=true\n\t\tfor i in {1..5}; do\n\t\t\t[ \"${df_out[i]}\" != \"${lfs_df_out[i]}\" ] && passed=false\n\t\tdone\n\t\t$passed && break\n\tdone\n\n\tif ! $passed; then\n\t\tdf -P $inodes $dir\n\t\techo\n\t\tlfs df $inodes $dir\n\t\terror \"df and lfs df $1 output mismatch: \"\t\\\n\t\t      \"df ${inodes}: ${df_out[*]}, \"\t\t\\\n\t\t      \"lfs df ${inodes}: ${lfs_df_out[*]}\"\n\tfi\n}\n\ntest_418() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\tlocal dir=$DIR/$tdir\n\tlocal numfiles=$((RANDOM % 4096 + 2))\n\tlocal numblocks=$((RANDOM % 256 + 1))\n\n\twait_delete_completed\n\ttest_mkdir $dir\n\n\t# check block output\n\tcheck_lfs_df blocks $dir\n\t# check inode output\n\tcheck_lfs_df inodes $dir\n\n\t# create a single file and retest\n\techo \"Creating a single file and testing\"\n\tcreatemany -o $dir/$tfile- 1 &>/dev/null ||\n\t\terror \"creating 1 file in $dir failed\"\n\tcheck_lfs_df blocks $dir\n\tcheck_lfs_df inodes $dir\n\n\t# create a random number of files\n\techo \"Creating $((numfiles - 1)) files and testing\"\n\tcreatemany -o $dir/$tfile- 1 $((numfiles - 1)) &>/dev/null ||\n\t\terror \"creating $((numfiles - 1)) files in $dir failed\"\n\n\t# write a random number of blocks to the first test file\n\techo \"Writing $numblocks 4K blocks and testing\"\n\tdd if=/dev/urandom of=$dir/${tfile}-0 bs=4K conv=fsync \\\n\t\tcount=$numblocks &>/dev/null ||\n\t\terror \"dd to $dir/${tfile}-0 failed\"\n\n\t# retest\n\tcheck_lfs_df blocks $dir\n\tcheck_lfs_df inodes $dir\n\n\tunlinkmany $dir/$tfile- $numfiles &>/dev/null ||\n\t\terror \"unlinking $numfiles files in $dir failed\"\n}\nrun_test 418 \"df and lfs df outputs match\"\n\ntest_419()\n{\n\tlocal dir=$DIR/$tdir\n\n\tmkdir -p $dir\n\ttouch $dir/file\n\n\tcancel_lru_locks mdc\n\n\t#OBD_FAIL_LLITE_OPEN_BY_NAME\t0x1410\n\t$LCTL set_param fail_loc=0x1410\n\tcat $dir/file\n\t$LCTL set_param fail_loc=0\n\trm -rf $dir\n}\nrun_test 419 \"Verify open file by name doesn't crash kernel\"\n\ntest_420()\n{\n\t[[ $MDS1_VERSION -ge $(version_code 2.12.53) ]] ||\n\t\tskip \"Need MDS version at least 2.12.53\"\n\n\tlocal SAVE_UMASK=$(umask)\n\tlocal dir=$DIR/$tdir\n\tlocal uname=$(getent passwd $RUNAS_ID | cut -d: -f1)\n\n\tmkdir -p $dir\n\tumask 0000\n\tmkdir -m03777 $dir/testdir\n\tls -dn $dir/testdir\n\t# Need to remove trailing '.' when SELinux is enabled\n\tlocal dirperms=$(ls -dn $dir/testdir |\n\t\t\t awk '{ sub(/\\.$/, \"\", $1); print $1}')\n\t[ $dirperms == \"drwxrwsrwt\" ] ||\n\t\terror \"incorrect perms on $dir/testdir\"\n\n\tsu - $uname -c \"PATH=$LUSTRE/tests:\\$PATH; \\\n\t\topenfile -f O_RDONLY:O_CREAT -m 02755 $dir/testdir/testfile\"\n\tls -n $dir/testdir/testfile\n\tlocal fileperms=$(ls -n $dir/testdir/testfile |\n\t\t\t  awk '{ sub(/\\.$/, \"\", $1); print $1}')\n\t[ $fileperms == \"-rwxr-xr-x\" ] ||\n\t\terror \"incorrect perms on $dir/testdir/testfile\"\n\n\tumask $SAVE_UMASK\n}\nrun_test 420 \"clear SGID bit on non-directories for non-members\"\n\ntest_421a() {\n\tlocal cnt\n\tlocal fid1\n\tlocal fid2\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f 3\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 3 ] && error \"unexpected #files: $cnt\"\n\n\tfid1=$(lfs path2fid $DIR/$tdir/f1)\n\tfid2=$(lfs path2fid $DIR/$tdir/f2)\n\t$LFS rmfid $DIR $fid1 $fid2 || error \"rmfid failed\"\n\n\tstat $DIR/$tdir/f1 && error \"f1 still visible on the client\"\n\tstat $DIR/$tdir/f2 && error \"f2 still visible on the client\"\n\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt == 1 ] || error \"unexpected #files after: $cnt\"\n\n\trm -f $DIR/$tdir/f3 || error \"can't remove f3\"\n\tcreatemany -o $DIR/$tdir/f 3\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 3 ] && error \"unexpected #files: $cnt\"\n\n\tfid1=$(lfs path2fid $DIR/$tdir/f1)\n\tfid2=$(lfs path2fid $DIR/$tdir/f2)\n\techo \"remove using fsname $FSNAME\"\n\t$LFS rmfid $FSNAME $fid1 $fid2 || error \"rmfid with fsname failed\"\n\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt == 1 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421a \"simple rm by fid\"\n\ntest_421b() {\n\tlocal cnt\n\tlocal FID1\n\tlocal FID2\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f 3\n\tmultiop_bg_pause $DIR/$tdir/f1 o_c || error \"multiop failed to start\"\n\tMULTIPID=$!\n\n\tFID1=$(lfs path2fid $DIR/$tdir/f1)\n\tFID2=$(lfs path2fid $DIR/$tdir/f2)\n\t$LFS rmfid $DIR $FID1 $FID2 && error \"rmfid didn't fail\"\n\n\tkill -USR1 $MULTIPID\n\twait\n\n\tcnt=$(ls $DIR/$tdir | wc -l)\n\t[ $cnt == 2 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421b \"rm by fid on open file\"\n\ntest_421c() {\n\tlocal cnt\n\tlocal FIDS\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f 3\n\ttouch $DIR/$tdir/$tfile\n\tcreatemany -l$DIR/$tdir/$tfile $DIR/$tdir/h 180\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 184 ] && error \"unexpected #files: $cnt\"\n\n\tFID1=$(lfs path2fid $DIR/$tdir/$tfile)\n\t$LFS rmfid $DIR $FID1 || error \"rmfid failed\"\n\n\tcnt=$(ls $DIR/$tdir | wc -l)\n\t[ $cnt == 3 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421c \"rm by fid against hardlinked files\"\n\ntest_421d() {\n\tlocal cnt\n\tlocal FIDS\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\ttest_mkdir $DIR/$tdir\n\tcreatemany -o $DIR/$tdir/f 4097\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 4097 ] && error \"unexpected #files: $cnt\"\n\n\tFIDS=$(lfs path2fid $DIR/$tdir/f* | sed \"s/[/][^:]*://g\")\n\t$LFS rmfid $DIR $FIDS || error \"rmfid failed\"\n\n\tcnt=$(ls $DIR/$tdir | wc -l)\n\trm -rf $DIR/$tdir\n\t[ $cnt == 0 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421d \"rmfid en masse\"\n\ntest_421e() {\n\tlocal cnt\n\tlocal FID\n\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tcreatemany -o $DIR/$tdir/striped_dir/f 512\n\tcnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)\n\t[ $cnt != 512 ] && error \"unexpected #files: $cnt\"\n\n\tFIDS=$(lfs path2fid $DIR/$tdir/striped_dir/f* |\n\t\tsed \"s/[/][^:]*://g\")\n\t$LFS rmfid $DIR $FIDS || error \"rmfid failed\"\n\n\tcnt=$(ls $DIR/$tdir/striped_dir | wc -l)\n\trm -rf $DIR/$tdir\n\t[ $cnt == 0 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421e \"rmfid in DNE\"\n\ntest_421f() {\n\tlocal cnt\n\tlocal FID\n\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\ttest_mkdir $DIR/$tdir\n\ttouch $DIR/$tdir/f\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 1 ] && error \"unexpected #files: $cnt\"\n\n\tFID=$(lfs path2fid $DIR/$tdir/f)\n\t$RUNAS $LFS rmfid $DIR $FID && error \"rmfid didn't fail (1)\"\n\t# rmfid should fail\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 1 ] && error \"unexpected #files after (2): $cnt\"\n\n\tchmod a+rw $DIR/$tdir\n\tls -la $DIR/$tdir\n\t$RUNAS $LFS rmfid $DIR $FID && error \"rmfid didn't fail (2)\"\n\t# rmfid should fail\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 1 ] && error \"unexpected #files after (3): $cnt\"\n\n\trm -f $DIR/$tdir/f\n\t$RUNAS touch $DIR/$tdir/f\n\tFID=$(lfs path2fid $DIR/$tdir/f)\n\techo \"rmfid as root\"\n\t$LFS rmfid $DIR $FID || error \"rmfid as root failed\"\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt == 0 ] || error \"unexpected #files after (4): $cnt\"\n\n\trm -f $DIR/$tdir/f\n\t$RUNAS touch $DIR/$tdir/f\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt != 1 ] && error \"unexpected #files (4): $cnt\"\n\tFID=$(lfs path2fid $DIR/$tdir/f)\n\t# rmfid w/o user_fid2path mount option should fail\n\t$RUNAS $LFS rmfid $DIR $FID && error \"rmfid didn't fail(3)\"\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt == 1 ] || error \"unexpected #files after (5): $cnt\"\n\n\tumount_client $MOUNT || error \"failed to umount client\"\n\tmount_client $MOUNT \"$MOUNT_OPTS,user_fid2path\" ||\n\t\terror \"failed to mount client'\"\n\n\t$RUNAS $LFS rmfid $DIR $FID || error \"rmfid failed\"\n\t# rmfid should succeed\n\tcnt=$(ls -1 $DIR/$tdir | wc -l)\n\t[ $cnt == 0 ] || error \"unexpected #files after (6): $cnt\"\n\n\t# rmfid shouldn't allow to remove files due to dir's permission\n\tchmod a+rwx $DIR/$tdir\n\ttouch $DIR/$tdir/f\n\tls -la $DIR/$tdir\n\tFID=$(lfs path2fid $DIR/$tdir/f)\n\t$RUNAS $LFS rmfid $DIR $FID && error \"rmfid didn't fail\"\n\n\tumount_client $MOUNT || error \"failed to umount client\"\n\tmount_client $MOUNT \"$MOUNT_OPTS\" ||\n\t\terror \"failed to mount client'\"\n\n}\nrun_test 421f \"rmfid checks permissions\"\n\ntest_421g() {\n\tlocal cnt\n\tlocal FIDS\n\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.12.54) ] &&\n\t\tskip \"Need MDS version at least 2.12.54\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS setdirstripe -c$MDSCOUNT $DIR/$tdir/striped_dir\n\tcreatemany -o $DIR/$tdir/striped_dir/f 512\n\tcnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)\n\t[ $cnt != 512 ] && error \"unexpected #files: $cnt\"\n\n\tFIDS=$(lfs path2fid $DIR/$tdir/striped_dir/f* |\n\t\tsed \"s/[/][^:]*://g\")\n\n\trm -f $DIR/$tdir/striped_dir/f1*\n\tcnt=$(ls -1 $DIR/$tdir/striped_dir | wc -l)\n\tremoved=$((512 - cnt))\n\n\t# few files have been just removed, so we expect\n\t# rmfid to fail on their fids\n\terrors=$($LFS rmfid $DIR $FIDS 2>&1 | wc -l)\n\t[ $removed != $errors ] && error \"$errors != $removed\"\n\n\tcnt=$(ls $DIR/$tdir/striped_dir | wc -l)\n\trm -rf $DIR/$tdir\n\t[ $cnt == 0 ] || error \"unexpected #files after: $cnt\"\n}\nrun_test 421g \"rmfid to return errors properly\"\n\ntest_422() {\n\ttest_mkdir -i 0 -c 1 -p $DIR/$tdir/d1\n\ttest_mkdir -i 0 -c 1 -p $DIR/$tdir/d2\n\ttest_mkdir -i 0 -c 1 -p $DIR/$tdir/d3\n\tdd if=/dev/zero of=$DIR/$tdir/d1/file1 bs=1k count=1\n\tdd if=/dev/zero of=$DIR/$tdir/d2/file1 bs=1k count=1\n\n\tlocal amc=$(at_max_get client)\n\tlocal amo=$(at_max_get mds1)\n\tlocal timeout=`lctl get_param -n timeout`\n\n\tat_max_set 0 client\n\tat_max_set 0 mds1\n\n#define OBD_FAIL_PTLRPC_PAUSE_REQ        0x50a\n\tdo_facet mds1 $LCTL set_param fail_loc=0x8000050a \\\n\t\t\tfail_val=$(((2*timeout + 10)*1000))\n\ttouch $DIR/$tdir/d3/file &\n\tsleep 2\n#define OBD_FAIL_TGT_REPLY_DATA_RACE\t 0x722\n\tdo_facet mds1 $LCTL set_param fail_loc=0x80000722 \\\n\t\t\tfail_val=$((2*timeout + 5))\n\tmv $DIR/$tdir/d1/file1 $DIR/$tdir/d1/file2 &\n\tlocal pid=$!\n\tsleep 1\n\tkill -9 $pid\n\tsleep $((2 * timeout))\n\techo kill $pid\n\tkill -9 $pid\n\tlctl mark touch\n\ttouch $DIR/$tdir/d2/file3\n\ttouch $DIR/$tdir/d2/file4\n\ttouch $DIR/$tdir/d2/file5\n\n\twait\n\tat_max_set $amc client\n\tat_max_set $amo mds1\n\n\t# LU-12838 - verify the ptlrpc thread watchdog is not always throttled\n\tdo_facet mds1 \"dmesg | grep 'Dumping the stack trace for debugging'\" ||\n\t\terror \"Watchdog is always throttled\"\n}\nrun_test 422 \"kill a process with RPC in progress\"\n\nstat_test() {\n    df -h $MOUNT &\n    df -h $MOUNT &\n    df -h $MOUNT &\n    df -h $MOUNT &\n    df -h $MOUNT &\n    df -h $MOUNT &\n}\n\ntest_423() {\n    local _stats\n    # ensure statfs cache is expired\n    sleep 2;\n\n    _stats=$(stat_test | grep $MOUNT | sort -u | wc -l)\n    [[ ${_stats} -ne 1 ]] && error \"statfs wrong\"\n\n    return 0\n}\nrun_test 423 \"statfs should return a right data\"\n\ntest_424() {\n#define OBD_FAIL_PTLRPC_BULK_REPLY_ATTACH      0x522 | OBD_FAIL_ONCE\n\t$LCTL set_param fail_loc=0x80000522\n\tdd if=/dev/zero of=$DIR/$tfile bs=2M count=1 oflag=sync\n\trm -f $DIR/$tfile\n}\nrun_test 424 \"simulate ENOMEM in ptl_send_rpc bulk reply ME attach\"\n\nprep_801() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.9.55) ]] ||\n\t[[ $OST1_VERSION -lt $(version_code 2.9.55) ]] &&\n\t\tskip \"Need server version at least 2.9.55\"\n\n\tstart_full_debug_logging\n}\n\npost_801() {\n\tstop_full_debug_logging\n}\n\nbarrier_stat() {\n\tif [ $MGS_VERSION -le $(version_code 2.10.0) ]; then\n\t\tlocal st=$(do_facet mgs $LCTL barrier_stat $FSNAME |\n\t\t\t   awk '/The barrier for/ { print $7 }')\n\t\techo $st\n\telse\n\t\tlocal st=$(do_facet mgs $LCTL barrier_stat -s $FSNAME)\n\t\techo \\'$st\\'\n\tfi\n}\n\nbarrier_expired() {\n\tlocal expired\n\n\tif [ $MGS_VERSION -le $(version_code 2.10.0) ]; then\n\t\texpired=$(do_facet mgs $LCTL barrier_stat $FSNAME |\n\t\t\t  awk '/will be expired/ { print $7 }')\n\telse\n\t\texpired=$(do_facet mgs $LCTL barrier_stat -t $FSNAME)\n\tfi\n\n\techo $expired\n}\n\ntest_801a() {\n\tprep_801\n\n\techo \"Start barrier_freeze at: $(date)\"\n\t#define OBD_FAIL_BARRIER_DELAY\t\t0x2202\n\tdo_facet mgs $LCTL set_param fail_val=5 fail_loc=0x2202\n\t# Do not reduce barrier time - See LU-11873\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME 20 &\n\n\tsleep 2\n\tlocal b_status=$(barrier_stat)\n\techo \"Got barrier status at: $(date)\"\n\t[ \"$b_status\" = \"'freezing_p1'\" ] ||\n\t\terror \"(1) unexpected barrier status $b_status\"\n\n\tdo_facet mgs $LCTL set_param fail_val=0 fail_loc=0\n\twait\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(2) unexpected barrier status $b_status\"\n\n\tlocal expired=$(barrier_expired)\n\techo \"sleep $((expired + 3)) seconds, then the barrier will be expired\"\n\tsleep $((expired + 3))\n\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'expired'\" ] ||\n\t\terror \"(3) unexpected barrier status $b_status\"\n\n\t# Do not reduce barrier time - See LU-11873\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME 20 ||\n\t\terror \"(4) fail to freeze barrier\"\n\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(5) unexpected barrier status $b_status\"\n\n\techo \"Start barrier_thaw at: $(date)\"\n\t#define OBD_FAIL_BARRIER_DELAY\t\t0x2202\n\tdo_facet mgs $LCTL set_param fail_val=5 fail_loc=0x2202\n\tdo_facet mgs $LCTL barrier_thaw $FSNAME &\n\n\tsleep 2\n\tb_status=$(barrier_stat)\n\techo \"Got barrier status at: $(date)\"\n\t[ \"$b_status\" = \"'thawing'\" ] ||\n\t\terror \"(6) unexpected barrier status $b_status\"\n\n\tdo_facet mgs $LCTL set_param fail_val=0 fail_loc=0\n\twait\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'thawed'\" ] ||\n\t\terror \"(7) unexpected barrier status $b_status\"\n\n\t#define OBD_FAIL_BARRIER_FAILURE\t0x2203\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x2203\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME\n\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'failed'\" ] ||\n\t\terror \"(8) unexpected barrier status $b_status\"\n\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\tdo_facet mgs $LCTL barrier_thaw $FSNAME\n\n\tpost_801\n}\nrun_test 801a \"write barrier user interfaces and stat machine\"\n\ntest_801b() {\n\tprep_801\n\n\tmkdir $DIR/$tdir || error \"(1) fail to mkdir\"\n\tcreatemany -d $DIR/$tdir/d 6 || \"(2) fail to mkdir\"\n\ttouch $DIR/$tdir/d2/f10 || error \"(3) fail to touch\"\n\ttouch $DIR/$tdir/d3/f11 || error \"(4) fail to touch\"\n\ttouch $DIR/$tdir/d4/f12 || error \"(5) fail to touch\"\n\n\tcancel_lru_locks mdc\n\n\t# 180 seconds should be long enough\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME 180\n\n\tlocal b_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(6) unexpected barrier status $b_status\"\n\n\tmkdir $DIR/$tdir/d0/d10 &\n\tmkdir_pid=$!\n\n\ttouch $DIR/$tdir/d1/f13 &\n\ttouch_pid=$!\n\n\tln $DIR/$tdir/d2/f10 $DIR/$tdir/d2/f14 &\n\tln_pid=$!\n\n\tmv $DIR/$tdir/d3/f11 $DIR/$tdir/d3/f15 &\n\tmv_pid=$!\n\n\trm -f $DIR/$tdir/d4/f12 &\n\trm_pid=$!\n\n\tstat $DIR/$tdir/d5 || error \"(7) stat should succeed\"\n\n\t# To guarantee taht the 'stat' is not blocked\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(8) unexpected barrier status $b_status\"\n\n\t# let above commands to run at background\n\tsleep 5\n\n\tps -p $mkdir_pid || error \"(9) mkdir should be blocked\"\n\tps -p $touch_pid || error \"(10) touch should be blocked\"\n\tps -p $ln_pid || error \"(11) link should be blocked\"\n\tps -p $mv_pid || error \"(12) rename should be blocked\"\n\tps -p $rm_pid || error \"(13) unlink should be blocked\"\n\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(14) unexpected barrier status $b_status\"\n\n\tdo_facet mgs $LCTL barrier_thaw $FSNAME\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'thawed'\" ] ||\n\t\terror \"(15) unexpected barrier status $b_status\"\n\n\twait $mkdir_pid || error \"(16) mkdir should succeed\"\n\twait $touch_pid || error \"(17) touch should succeed\"\n\twait $ln_pid || error \"(18) link should succeed\"\n\twait $mv_pid || error \"(19) rename should succeed\"\n\twait $rm_pid || error \"(20) unlink should succeed\"\n\n\tpost_801\n}\nrun_test 801b \"modification will be blocked by write barrier\"\n\ntest_801c() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\n\tprep_801\n\n\tstop mds2 || error \"(1) Fail to stop mds2\"\n\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME 30\n\n\tlocal b_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'expired'\" ] || [ \"$b_status\" = \"'failed'\" ] || {\n\t\tdo_facet mgs $LCTL barrier_thaw $FSNAME\n\t\terror \"(2) unexpected barrier status $b_status\"\n\t}\n\n\tdo_facet mgs $LCTL barrier_rescan $FSNAME ||\n\t\terror \"(3) Fail to rescan barrier bitmap\"\n\n\t# Do not reduce barrier time - See LU-11873\n\tdo_facet mgs $LCTL barrier_freeze $FSNAME 20\n\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'frozen'\" ] ||\n\t\terror \"(4) unexpected barrier status $b_status\"\n\n\tdo_facet mgs $LCTL barrier_thaw $FSNAME\n\tb_status=$(barrier_stat)\n\t[ \"$b_status\" = \"'thawed'\" ] ||\n\t\terror \"(5) unexpected barrier status $b_status\"\n\n\tlocal devname=$(mdsdevname 2)\n\n\tstart mds2 $devname $MDS_MOUNT_OPTS || error \"(6) Fail to start mds2\"\n\n\tdo_facet mgs $LCTL barrier_rescan $FSNAME ||\n\t\terror \"(7) Fail to rescan barrier bitmap\"\n\n\tpost_801\n}\nrun_test 801c \"rescan barrier bitmap\"\n\nsaved_MGS_MOUNT_OPTS=$MGS_MOUNT_OPTS\nsaved_MDS_MOUNT_OPTS=$MDS_MOUNT_OPTS\nsaved_OST_MOUNT_OPTS=$OST_MOUNT_OPTS\nsaved_MOUNT_OPTS=$MOUNT_OPTS\n\ncleanup_802a() {\n\ttrap 0\n\n\tstopall\n\tMGS_MOUNT_OPTS=$saved_MGS_MOUNT_OPTS\n\tMDS_MOUNT_OPTS=$saved_MDS_MOUNT_OPTS\n\tOST_MOUNT_OPTS=$saved_OST_MOUNT_OPTS\n\tMOUNT_OPTS=$saved_MOUNT_OPTS\n\tsetupall\n}\n\ntest_802a() {\n\t[[ $mds1_FSTYPE = zfs ]] || skip \"ZFS specific test\"\n\t[[ $MDS1_VERSION -lt $(version_code 2.9.55) ]] ||\n\t[[ $OST1_VERSION -lt $(version_code 2.9.55) ]] &&\n\t\tskip \"Need server version at least 2.9.55\"\n\n\t[[ $ENABLE_QUOTA ]] && skip \"Quota enabled for read-only test\"\n\n\tmkdir $DIR/$tdir || error \"(1) fail to mkdir\"\n\n\tcp $LUSTRE/tests/test-framework.sh $DIR/$tdir/ ||\n\t\terror \"(2) Fail to copy\"\n\n\ttrap cleanup_802a EXIT\n\n\t# sync by force before remount as readonly\n\tsync; sync_all_data; sleep 3; sync_all_data\n\n\tstopall\n\n\tMGS_MOUNT_OPTS=$(csa_add \"$MGS_MOUNT_OPTS\" -o rdonly_dev)\n\tMDS_MOUNT_OPTS=$(csa_add \"$MDS_MOUNT_OPTS\" -o rdonly_dev)\n\tOST_MOUNT_OPTS=$(csa_add \"$OST_MOUNT_OPTS\" -o rdonly_dev)\n\n\techo \"Mount the server as read only\"\n\tsetupall server_only || error \"(3) Fail to start servers\"\n\n\techo \"Mount client without ro should fail\"\n\tmount_client $MOUNT &&\n\t\terror \"(4) Mount client without 'ro' should fail\"\n\n\techo \"Mount client with ro should succeed\"\n\tMOUNT_OPTS=$(csa_add \"$MOUNT_OPTS\" -o ro)\n\tmount_client $MOUNT ||\n\t\terror \"(5) Mount client with 'ro' should succeed\"\n\n\techo \"Modify should be refused\"\n\ttouch $DIR/$tdir/guard && error \"(6) Touch should fail under ro mode\"\n\n\techo \"Read should be allowed\"\n\tdiff $LUSTRE/tests/test-framework.sh $DIR/$tdir/test-framework.sh ||\n\t\terror \"(7) Read should succeed under ro mode\"\n\n\tcleanup_802a\n}\nrun_test 802a \"simulate readonly device\"\n\ntest_802b() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n        remote_mds_nodsh && skip \"remote MDS with nodsh\"\n\n\tdo_facet $SINGLEMDS $LCTL get_param mdt.*.readonly ||\n\t\tskip \"readonly option not available\"\n\n\t$LFS mkdir -i 0 -c 1 $DIR/$tdir || error \"(1) fail to mkdir\"\n\n\tcp $LUSTRE/tests/test-framework.sh $DIR/$tdir/ ||\n\t\terror \"(2) Fail to copy\"\n\n\t# write back all cached data before setting MDT to readonly\n\tcancel_lru_locks\n\tsync_all_data\n\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=1\n\tstack_trap \"do_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=0\" EXIT\n\n\techo \"Modify should be refused\"\n\ttouch $DIR/$tdir/guard && error \"(6) Touch should fail under ro mode\"\n\n\techo \"Read should be allowed\"\n\tdiff $LUSTRE/tests/test-framework.sh $DIR/$tdir/test-framework.sh ||\n\t\terror \"(7) Read should succeed under ro mode\"\n\n\t# disable readonly\n\tdo_facet $SINGLEMDS $LCTL set_param mdt.*.readonly=0\n}\nrun_test 802b \"be able to set MDTs to readonly\"\n\ntest_803() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.10.54) ] &&\n\t\tskip \"MDS needs to be newer than 2.10.54\"\n\n\tmkdir -p $DIR/$tdir\n\t# Create some objects on all MDTs to trigger related logs objects\n\tfor idx in $(seq $MDSCOUNT); do\n\t\t$LFS mkdir -c $MDSCOUNT -i $((idx % $MDSCOUNT)) \\\n\t\t\t$DIR/$tdir/dir${idx} ||\n\t\t\terror \"Fail to create $DIR/$tdir/dir${idx}\"\n\tdone\n\n\tsync; sleep 3\n\twait_delete_completed # ensure old test cleanups are finished\n\techo \"before create:\"\n\t$LFS df -i $MOUNT\n\tlocal before_used=$($LFS df -i | grep MDT0000_UUID | awk '{print $3}')\n\n\tfor i in {1..10}; do\n\t\t$LFS mkdir -c 1 -i 1 $DIR/$tdir/foo$i ||\n\t\t\terror \"Fail to create $DIR/$tdir/foo$i\"\n\tdone\n\n\tsync; sleep 3\n\techo \"after create:\"\n\t$LFS df -i $MOUNT\n\tlocal after_used=$($LFS df -i | grep MDT0000_UUID | awk '{print $3}')\n\n\t# allow for an llog to be cleaned up during the test\n\t[ $after_used -ge $((before_used + 10 - 1)) ] ||\n\t\terror \"before ($before_used) + 10 > after ($after_used)\"\n\n\tfor i in {1..10}; do\n\t\trm -rf $DIR/$tdir/foo$i ||\n\t\t\terror \"Fail to remove $DIR/$tdir/foo$i\"\n\tdone\n\n\tsleep 3 # avoid MDT return cached statfs\n\twait_delete_completed\n\techo \"after unlink:\"\n\t$LFS df -i $MOUNT\n\tafter_used=$($LFS df -i | grep MDT0000_UUID | awk '{print $3}')\n\n\t# allow for an llog to be created during the test\n\t[ $after_used -le $((before_used + 1)) ] ||\n\t\terror \"after ($after_used) > before ($before_used) + 1\"\n}\nrun_test 803 \"verify agent object for remote object\"\n\ntest_804() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.10.54) ] &&\n\t\tskip \"MDS needs to be newer than 2.10.54\"\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && skip_env \"ldiskfs only test\"\n\n\tmkdir -p $DIR/$tdir\n\t$LFS mkdir -c 1 -i 1 $DIR/$tdir/dir0 ||\n\t\terror \"Fail to create $DIR/$tdir/dir0\"\n\n\tlocal fid=$($LFS path2fid $DIR/$tdir/dir0)\n\tlocal dev=$(mdsdevname 2)\n\n\tdo_facet mds2 \"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev\" |\n\t\tgrep ${fid} || error \"NOT found agent entry for dir0\"\n\n\t$LFS mkdir -c $MDSCOUNT -i 0 $DIR/$tdir/dir1 ||\n\t\terror \"Fail to create $DIR/$tdir/dir1\"\n\n\ttouch $DIR/$tdir/dir1/foo0 ||\n\t\terror \"Fail to create $DIR/$tdir/dir1/foo0\"\n\tfid=$($LFS path2fid $DIR/$tdir/dir1/foo0)\n\tlocal rc=0\n\n\tfor idx in $(seq $MDSCOUNT); do\n\t\tdev=$(mdsdevname $idx)\n\t\tdo_facet mds${idx} \\\n\t\t\t\"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev\" |\n\t\t\tgrep ${fid} && rc=$idx\n\tdone\n\n\tmv $DIR/$tdir/dir1/foo0 $DIR/$tdir/dir1/foo1 ||\n\t\terror \"Fail to rename foo0 to foo1\"\n\tif [ $rc -eq 0 ]; then\n\t\tfor idx in $(seq $MDSCOUNT); do\n\t\t\tdev=$(mdsdevname $idx)\n\t\t\tdo_facet mds${idx} \\\n\t\t\t\"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev\" |\n\t\t\tgrep ${fid} && rc=$idx\n\t\tdone\n\tfi\n\n\tmv $DIR/$tdir/dir1/foo1 $DIR/$tdir/dir1/foo2 ||\n\t\terror \"Fail to rename foo1 to foo2\"\n\tif [ $rc -eq 0 ]; then\n\t\tfor idx in $(seq $MDSCOUNT); do\n\t\t\tdev=$(mdsdevname $idx)\n\t\t\tdo_facet mds${idx} \\\n\t\t\t\"$DEBUGFS -c -R 'ls /REMOTE_PARENT_DIR' $dev\" |\n\t\t\tgrep ${fid} && rc=$idx\n\t\tdone\n\tfi\n\n\t[ $rc -ne 0 ] || error \"NOT found agent entry for foo\"\n\n\tln $DIR/$tdir/dir1/foo2 $DIR/$tdir/dir0/guard ||\n\t\terror \"Fail to link to $DIR/$tdir/dir1/foo2\"\n\tmv $DIR/$tdir/dir1/foo2 $DIR/$tdir/dir1/foo0 ||\n\t\terror \"Fail to rename foo2 to foo0\"\n\tunlink $DIR/$tdir/dir1/foo0 ||\n\t\terror \"Fail to unlink $DIR/$tdir/dir1/foo0\"\n\trm -rf $DIR/$tdir/dir0 ||\n\t\terror \"Fail to rm $DIR/$tdir/dir0\"\n\n\tfor idx in $(seq $MDSCOUNT); do\n\t\tdev=$(mdsdevname $idx)\n\t\trc=0\n\n\t\tstop mds${idx}\n\t\trun_e2fsck $(facet_active_host mds$idx) $dev -n ||\n\t\t\trc=$?\n\t\tstart mds${idx} $dev $MDS_MOUNT_OPTS ||\n\t\t\terror \"mount mds$idx failed\"\n\t\tdf $MOUNT > /dev/null 2>&1\n\n\t\t# e2fsck should not return error\n\t\t[ $rc -eq 0 ] ||\n\t\t\terror \"e2fsck detected error on MDT${idx}: rc=$rc\"\n\tdone\n}\nrun_test 804 \"verify agent entry for remote entry\"\n\ncleanup_805() {\n\tdo_facet $SINGLEMDS zfs set quota=$old $fsset\n\tunlinkmany $DIR/$tdir/f- 1000000\n\ttrap 0\n}\n\ntest_805() {\n\tlocal zfs_version=$(do_facet mds1 cat /sys/module/zfs/version)\n\t[ \"$mds1_FSTYPE\" != \"zfs\" ] && skip \"ZFS specific test\"\n\t[ $(version_code $zfs_version) -lt $(version_code 0.7.2) ] &&\n\t\tskip \"netfree not implemented before 0.7\"\n\t[[ $MDS1_VERSION -ge $(version_code 2.10.57) ]] ||\n\t\tskip \"Need MDS version at least 2.10.57\"\n\n\tlocal fsset\n\tlocal freekb\n\tlocal usedkb\n\tlocal old\n\tlocal quota\n\tlocal pref=\"osd-zfs.$FSNAME-MDT0000.\"\n\n\t# limit available space on MDS dataset to meet nospace issue\n\t# quickly. then ZFS 0.7.2 can use reserved space if asked\n\t# properly (using netfree flag in osd_declare_destroy()\n\tfsset=$(do_facet $SINGLEMDS lctl get_param -n $pref.mntdev)\n\told=$(do_facet $SINGLEMDS zfs get -H quota $fsset | \\\n\t\tgawk '{print $3}')\n\tfreekb=$(do_facet $SINGLEMDS lctl get_param -n $pref.kbytesfree)\n\tusedkb=$(do_facet $SINGLEMDS lctl get_param -n $pref.kbytestotal)\n\tlet \"usedkb=usedkb-freekb\"\n\tlet \"freekb=freekb/2\"\n\tif let \"freekb > 5000\"; then\n\t\tlet \"freekb=5000\"\n\tfi\n\tdo_facet $SINGLEMDS zfs set quota=$(((usedkb+freekb)*1024)) $fsset\n\ttrap cleanup_805 EXIT\n\tmkdir $DIR/$tdir\n\t$LFS setstripe -E 1M -c2 -E 4M -c2 -E -1 -c2 $DIR/$tdir ||\n\t\terror \"Can't set PFL layout\"\n\tcreatemany -m $DIR/$tdir/f- 1000000 && error \"ENOSPC wasn't met\"\n\trm -rf $DIR/$tdir || error \"not able to remove\"\n\tdo_facet $SINGLEMDS zfs set quota=$old $fsset\n\ttrap 0\n}\nrun_test 805 \"ZFS can remove from full fs\"\n\n# Size-on-MDS test\ncheck_lsom_data()\n{\n\tlocal file=$1\n\tlocal size=$($LFS getsom -s $file)\n\tlocal expect=$(stat -c %s $file)\n\n\t[[ $size == $expect ]] ||\n\t\terror \"$file expected size: $expect, got: $size\"\n\n\tlocal blocks=$($LFS getsom -b $file)\n\texpect=$(stat -c %b $file)\n\t[[ $blocks == $expect ]] ||\n\t\terror \"$file expected blocks: $expect, got: $blocks\"\n}\n\ncheck_lsom_size()\n{\n\tlocal size=$($LFS getsom -s $1)\n\tlocal expect=$2\n\n\t[[ $size == $expect ]] ||\n\t\terror \"$file expected size: $expect, got: $size\"\n}\n\ntest_806() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\tlocal bs=1048576\n\n\ttouch $DIR/$tfile || error \"touch $tfile failed\"\n\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $save\n\tlctl set_param llite.*.xattr_cache=0\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\n\t# single-threaded write\n\techo \"Test SOM for single-threaded write\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=$bs count=1 ||\n\t\terror \"write $tfile failed\"\n\tcheck_lsom_size $DIR/$tfile $bs\n\n\tlocal num=32\n\tlocal size=$(($num * $bs))\n\tlocal offset=0\n\tlocal i\n\n\techo \"Test SOM for single client multi-threaded($num) write\"\n\t$TRUNCATE $DIR/$tfile 0\n\tfor ((i = 0; i < $num; i++)); do\n\t\t$MULTIOP $DIR/$tfile Oz${offset}w${bs}c &\n\t\tlocal pids[$i]=$!\n\t\toffset=$((offset + $bs))\n\tdone\n\tfor (( i=0; i < $num; i++ )); do\n\t\twait ${pids[$i]}\n\tdone\n\tcheck_lsom_size $DIR/$tfile $size\n\n\t$TRUNCATE $DIR/$tfile 0\n\tfor ((i = 0; i < $num; i++)); do\n\t\toffset=$((offset - $bs))\n\t\t$MULTIOP $DIR/$tfile Oz${offset}w${bs}c &\n\t\tlocal pids[$i]=$!\n\tdone\n\tfor (( i=0; i < $num; i++ )); do\n\t\twait ${pids[$i]}\n\tdone\n\tcheck_lsom_size $DIR/$tfile $size\n\n\t# multi-client writes\n\tnum=$(get_node_count ${CLIENTS//,/ })\n\tsize=$(($num * $bs))\n\toffset=0\n\ti=0\n\n\techo \"Test SOM for multi-client ($num) writes\"\n\t$TRUNCATE $DIR/$tfile 0\n\tfor client in ${CLIENTS//,/ }; do\n\t\tdo_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &\n\t\tlocal pids[$i]=$!\n\t\ti=$((i + 1))\n\t\toffset=$((offset + $bs))\n\tdone\n\tfor (( i=0; i < $num; i++ )); do\n\t\twait ${pids[$i]}\n\tdone\n\tcheck_lsom_size $DIR/$tfile $offset\n\n\ti=0\n\t$TRUNCATE $DIR/$tfile 0\n\tfor client in ${CLIENTS//,/ }; do\n\t\toffset=$((offset - $bs))\n\t\tdo_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &\n\t\tlocal pids[$i]=$!\n\t\ti=$((i + 1))\n\tdone\n\tfor (( i=0; i < $num; i++ )); do\n\t\twait ${pids[$i]}\n\tdone\n\tcheck_lsom_size $DIR/$tfile $size\n\n\t# verify truncate\n\techo \"Test SOM for truncate\"\n\t$TRUNCATE $DIR/$tfile 1048576\n\tcheck_lsom_size $DIR/$tfile 1048576\n\t$TRUNCATE $DIR/$tfile 1234\n\tcheck_lsom_size $DIR/$tfile 1234\n\n\t# verify SOM blocks count\n\techo \"Verify SOM block count\"\n\t$TRUNCATE $DIR/$tfile 0\n\t$MULTIOP $DIR/$tfile oO_TRUNC:O_RDWR:w1048576YSc ||\n\t\terror \"failed to write file $tfile\"\n\tcheck_lsom_data $DIR/$tfile\n}\nrun_test 806 \"Verify Lazy Size on MDS\"\n\ntest_807() {\n\t[ -n \"$FILESET\" ] && skip \"Not functional for FILESET set\"\n\t[ $MDS1_VERSION -lt $(version_code 2.11.52) ] &&\n\t\tskip \"Need MDS version at least 2.11.52\"\n\n\t# Registration step\n\tchangelog_register || error \"changelog_register failed\"\n\tlocal cl_user=\"${CL_USERS[$SINGLEMDS]%% *}\"\n\tchangelog_users $SINGLEMDS | grep -q $cl_user ||\n\t\terror \"User $cl_user not found in changelog_users\"\n\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $save\n\tlctl set_param llite.*.xattr_cache=0\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\n\trm -rf $DIR/$tdir || error \"rm $tdir failed\"\n\tmkdir -p $DIR/$tdir || error \"mkdir $tdir failed\"\n\ttouch $DIR/$tdir/trunc || error \"touch $tdir/trunc failed\"\n\t$TRUNCATE $DIR/$tdir/trunc 1024 || error \"truncate $tdir/trunc failed\"\n\t$TRUNCATE $DIR/$tdir/trunc 1048576 ||\n\t\terror \"truncate $tdir/trunc failed\"\n\n\tlocal bs=1048576\n\tdd if=/dev/zero of=$DIR/$tdir/single_dd bs=$bs count=1 conv=fsync ||\n\t\terror \"write $tfile failed\"\n\n\t# multi-client wirtes\n\tlocal num=$(get_node_count ${CLIENTS//,/ })\n\tlocal offset=0\n\tlocal i=0\n\n\techo \"Test SOM for multi-client ($num) writes\"\n\ttouch $DIR/$tfile || error \"touch $tfile failed\"\n\t$TRUNCATE $DIR/$tfile 0\n\tfor client in ${CLIENTS//,/ }; do\n\t\tdo_node $client $MULTIOP $DIR/$tfile Oz${offset}w${bs}c &\n\t\tlocal pids[$i]=$!\n\t\ti=$((i + 1))\n\t\toffset=$((offset + $bs))\n\tdone\n\tfor (( i=0; i < $num; i++ )); do\n\t\twait ${pids[$i]}\n\tdone\n\n\tdo_rpc_nodes \"$CLIENTS\" cancel_lru_locks osc\n\tdo_nodes \"$CLIENTS\" \"sync ; sleep 5 ; sync\"\n\t$LSOM_SYNC -u $cl_user -m $FSNAME-MDT0000 $MOUNT\n\tcheck_lsom_data $DIR/$tdir/trunc\n\tcheck_lsom_data $DIR/$tdir/single_dd\n\tcheck_lsom_data $DIR/$tfile\n\n\trm -rf $DIR/$tdir\n\t# Deregistration step\n\tchangelog_deregister || error \"changelog_deregister failed\"\n}\nrun_test 807 \"verify LSOM syncing tool\"\n\ncheck_som_nologged()\n{\n\tlocal lines=$($LFS changelog $FSNAME-MDT0000 |\n\t\tgrep 'x=trusted.som' | wc -l)\n\t[ $lines -ne 0 ] && error \"trusted.som xattr is logged in Changelogs\"\n}\n\ntest_808() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.55) ] &&\n\t\tskip \"Need MDS version at least 2.11.55\"\n\n\t# Registration step\n\tchangelog_register || error \"changelog_register failed\"\n\n\ttouch $DIR/$tfile || error \"touch $tfile failed\"\n\tcheck_som_nologged\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1048576 count=1 ||\n\t\terror \"write $tfile failed\"\n\tcheck_som_nologged\n\n\t$TRUNCATE $DIR/$tfile 1234\n\tcheck_som_nologged\n\n\t$TRUNCATE $DIR/$tfile 1048576\n\tcheck_som_nologged\n\n\t# Deregistration step\n\tchangelog_deregister || error \"changelog_deregister failed\"\n}\nrun_test 808 \"Check trusted.som xattr not logged in Changelogs\"\n\ncheck_som_nodata()\n{\n\t$LFS getsom $1\n\t[[ $? -eq 61 ]] || error \"DoM-only file $1 has SOM xattr\"\n}\n\ntest_809() {\n\t[ $MDS1_VERSION -lt $(version_code 2.11.56) ] &&\n\t\tskip \"Need MDS version at least 2.11.56\"\n\n\t$LFS setstripe -E 1M -L mdt $DIR/$tfile ||\n\t\terror \"failed to create DoM-only file $DIR/$tfile\"\n\ttouch $DIR/$tfile || error \"touch $tfile failed\"\n\tcheck_som_nodata $DIR/$tfile\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=2048 count=1 ||\n\t\terror \"write $tfile failed\"\n\tcheck_som_nodata $DIR/$tfile\n\n\t$TRUNCATE $DIR/$tfile 1234\n\tcheck_som_nodata $DIR/$tfile\n\n\t$TRUNCATE $DIR/$tfile 4097\n\tcheck_som_nodata $DIR/$file\n}\nrun_test 809 \"Verify no SOM xattr store for DoM-only files\"\n\ntest_810() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\t$GSS && skip_env \"could not run with gss\"\n\t[[ $OST1_VERSION -gt $(version_code 2.12.58) ]] ||\n\t\tskip \"OST < 2.12.58 doesn't align checksum\"\n\n\tset_checksums 1\n\tstack_trap \"set_checksums $ORIG_CSUM\" EXIT\n\tstack_trap \"set_checksum_type $ORIG_CSUM_TYPE\" EXIT\n\n\tlocal csum\n\tlocal before\n\tlocal after\n\tfor csum in $CKSUM_TYPES; do\n\t\t#define OBD_FAIL_OSC_NO_GRANT\t0x411\n\t\t$LCTL set_param osc.*.checksum_type=$csum fail_loc=0x411\n\t\tfor i in \"10240 0\" \"10000 0\" \"4000 1\" \"500 1\"; do\n\t\t\teval set -- $i\n\t\t\tdd if=/dev/urandom of=$DIR/$tfile bs=$1 count=2 seek=$2\n\t\t\tbefore=$(md5sum $DIR/$tfile)\n\t\t\t$LCTL set_param ldlm.namespaces.*osc*.lru_size=clear\n\t\t\tafter=$(md5sum $DIR/$tfile)\n\t\t\t[ \"$before\" == \"$after\" ] ||\n\t\t\t\terror \"$csum: $before != $after bs=$1 seek=$2\"\n\t\tdone\n\tdone\n}\nrun_test 810 \"partial page writes on ZFS (LU-11663)\"\n\ntest_812a() {\n\t[ $OST1_VERSION -lt $(version_code 2.12.51) ] &&\n\t\tskip \"OST < 2.12.51 doesn't support this fail_loc\"\n\t[ \"$SHARED_KEY\" = true ] &&\n\t\tskip \"OSC connections never go IDLE with Shared-Keys enabled\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\t# ensure ost1 is connected\n\tstat $DIR/$tfile >/dev/null || error \"can't stat\"\n\twait_osc_import_state client ost1 FULL\n\t# no locks, no reqs to let the connection idle\n\tcancel_lru_locks osc\n\n\t# delay OST_DISCONNECT on OST1 to put OSC into intermediate state\n#define OBD_FAIL_OST_DISCONNECT_DELAY\t 0x245\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x245 fail_val=8\"\n\twait_osc_import_state client ost1 CONNECTING\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0 fail_val=0\"\n\n\tstat $DIR/$tfile >/dev/null || error \"can't stat file\"\n}\nrun_test 812a \"do not drop reqs generated when imp is going to idle (LU-11951)\"\n\ntest_812b() { # LU-12378\n\t[ $OST1_VERSION -lt $(version_code 2.12.51) ] &&\n\t\tskip \"OST < 2.12.51 doesn't support this fail_loc\"\n\t[ \"$SHARED_KEY\" = true ] &&\n\t\tskip \"OSC connections never go IDLE with Shared-Keys enabled\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile || error \"setstripe failed\"\n\t# ensure ost1 is connected\n\tstat $DIR/$tfile >/dev/null || error \"can't stat\"\n\twait_osc_import_state client ost1 FULL\n\t# no locks, no reqs to let the connection idle\n\tcancel_lru_locks osc\n\n\t# delay OST_DISCONNECT on OST1 to put OSC into intermediate state\n#define OBD_FAIL_OST_DISCONNECT_DELAY\t 0x245\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0x245 fail_val=8\"\n\twait_osc_import_state client ost1 CONNECTING\n\tdo_facet ost1 \"$LCTL set_param fail_loc=0 fail_val=0\"\n\n\t$LFS quota -u 0 $DIR/ || error \"lfs quota should succeed\"\n\twait_osc_import_state client ost1 IDLE\n}\nrun_test 812b \"do not drop no resend request for idle connect\"\n\ntest_813() {\n\tlocal file_heat_sav=$($LCTL get_param -n llite.*.file_heat 2>/dev/null)\n\t[ -z \"$file_heat_sav\" ] && skip \"no file heat support\"\n\n\tlocal readsample\n\tlocal writesample\n\tlocal readbyte\n\tlocal writebyte\n\tlocal readsample1\n\tlocal writesample1\n\tlocal readbyte1\n\tlocal writebyte1\n\n\tlocal period_second=$($LCTL get_param -n llite.*.heat_period_second)\n\tlocal decay_pct=$($LCTL get_param -n llite.*.heat_decay_percentage)\n\n\t$LCTL set_param -n llite.*.file_heat=1\n\techo \"Turn on file heat\"\n\techo \"Period second: $period_second, Decay percentage: $decay_pct\"\n\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\n\tlocal out=$($LFS heat_get $DIR/$tfile)\n\n\t$LFS heat_get $DIR/$tfile\n\treadsample=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $readsample -le 4 ] || error \"read sample ($readsample) is wrong\"\n\t[ $writesample -le 3 ] || error \"write sample ($writesample) is wrong\"\n\t[ $readbyte -le 20 ] || error \"read bytes ($readbyte) is wrong\"\n\t[ $writebyte -le 15 ] || error \"write bytes ($writebyte) is wrong\"\n\n\tsleep $((period_second + 3))\n\techo \"Sleep $((period_second + 3)) seconds...\"\n\t# The recursion formula to calculate the heat of the file f is as\n\t# follow:\n\t# Hi+1(f) = (1-P)*Hi(f)+ P*Ci\n\t# Where Hi is the heat value in the period between time points i*I and\n\t# (i+1)*I; Ci is the access count in the period; the symbol P refers\n\t# to the weight of Ci.\n\tout=$($LFS heat_get $DIR/$tfile)\n\t$LFS heat_get $DIR/$tfile\n\treadsample=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $(bc <<< \"$readsample <= 4 * $decay_pct / 100\") -eq 1 ] ||\n\t\terror \"read sample ($readsample) is wrong\"\n\t[ $(bc <<< \"$writesample <= 3 * $decay_pct / 100\") -eq 1 ] ||\n\t\terror \"write sample ($writesample) is wrong\"\n\t[ $(bc <<< \"$readbyte <= 20 * $decay_pct / 100\") -eq 1 ] ||\n\t\terror \"read bytes ($readbyte) is wrong\"\n\t[ $(bc <<< \"$writebyte <= 15 * $decay_pct / 100\") -eq 1 ] ||\n\t\terror \"write bytes ($writebyte) is wrong\"\n\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\n\tsleep $((period_second + 3))\n\techo \"Sleep $((period_second + 3)) seconds...\"\n\n\tout=$($LFS heat_get $DIR/$tfile)\n\t$LFS heat_get $DIR/$tfile\n\treadsample1=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample1=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte1=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte1=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $(bc <<< \"$readsample1 <= ($readsample * (100 - $decay_pct) + \\\n\t\t4 * $decay_pct) / 100\") -eq 1 ] ||\n\t\terror \"read sample ($readsample1) is wrong\"\n\t[ $(bc <<< \"$writesample1 <= ($writesample * (100 - $decay_pct) + \\\n\t\t3 * $decay_pct) / 100\") -eq 1 ] ||\n\t\terror \"write sample ($writesample1) is wrong\"\n\t[ $(bc <<< \"$readbyte1 <= ($readbyte * (100 - $decay_pct) + \\\n\t\t20 * $decay_pct) / 100\") -eq 1 ] ||\n\t\terror \"read bytes ($readbyte1) is wrong\"\n\t[ $(bc <<< \"$writebyte1 <= ($writebyte * (100 - $decay_pct) + \\\n\t\t15 * $decay_pct) / 100\") -eq 1 ] ||\n\t\terror \"write bytes ($writebyte1) is wrong\"\n\n\techo \"Turn off file heat for the file $DIR/$tfile\"\n\t$LFS heat_set -o $DIR/$tfile\n\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\n\tout=$($LFS heat_get $DIR/$tfile)\n\t$LFS heat_get $DIR/$tfile\n\treadsample=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $readsample -eq 0 ] || error \"read sample ($readsample) is wrong\"\n\t[ $writesample -eq 0 ] || error \"write sample ($writesample) is wrong\"\n\t[ $readbyte -eq 0 ] || error \"read bytes ($readbyte) is wrong\"\n\t[ $writebyte -eq 0 ] || error \"write bytes ($writebyte) is wrong\"\n\n\techo \"Trun on file heat for the file $DIR/$tfile\"\n\t$LFS heat_set -O $DIR/$tfile\n\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\n\tout=$($LFS heat_get $DIR/$tfile)\n\t$LFS heat_get $DIR/$tfile\n\treadsample=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $readsample -gt 0 ] || error \"read sample ($readsample) is wrong\"\n\t[ $writesample -gt 0 ] || error \"write sample ($writesample) is wrong\"\n\t[ $readbyte -gt 0 ] || error \"read bytes ($readbyte) is wrong\"\n\t[ $writebyte -gt 0 ] || error \"write bytes ($writebyte) is wrong\"\n\n\t$LFS heat_set -c $DIR/$tfile\n\t$LCTL set_param -n llite.*.file_heat=0\n\techo \"Turn off file heat support for the Lustre filesystem\"\n\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\techo \"QQQQ\" > $DIR/$tfile\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\tcat $DIR/$tfile > /dev/null\n\n\tout=$($LFS heat_get $DIR/$tfile)\n\t$LFS heat_get $DIR/$tfile\n\treadsample=$(echo \"$out\" | grep 'readsample' | awk '{ print $2 }')\n\twritesample=$(echo \"$out\" | grep 'writesample' | awk '{ print $2 }')\n\treadbyte=$(echo \"$out\" | grep 'readbyte' | awk '{ print $2 }')\n\twritebyte=$(echo \"$out\" | grep 'writebyte' | awk '{ print $2 }')\n\n\t[ $readsample -eq 0 ] || error \"read sample ($readsample) is wrong\"\n\t[ $writesample -eq 0 ] || error \"write sample ($writesample) is wrong\"\n\t[ $readbyte -eq 0 ] || error \"read bytes ($readbyte) is wrong\"\n\t[ $writebyte -eq 0 ] || error \"write bytes ($writebyte) is wrong\"\n\n\t$LCTL set_param -n llite.*.file_heat=$file_heat_sav\n\trm -f $DIR/$tfile\n}\nrun_test 813 \"File heat verfication\"\n\ntest_814()\n{\n\tdd of=$DIR/$tfile seek=128 bs=1k < /dev/null\n\techo -n y >> $DIR/$tfile\n\tcp --sparse=always $DIR/$tfile $DIR/${tfile}.cp || error \"copy failed\"\n\tdiff $DIR/$tfile $DIR/${tfile}.cp || error \"files should be same\"\n}\nrun_test 814 \"sparse cp works as expected (LU-12361)\"\n\ntest_815()\n{\n\twriteme -b 100 $DIR/$tfile || error \"write 100 bytes failed\"\n\twriteme -b 0 $DIR/$tfile || error \"write 0 byte failed\"\n}\nrun_test 815 \"zero byte tiny write doesn't hang (LU-12382)\"\n\ntest_816() {\n\t[ \"$SHARED_KEY\" = true ] &&\n\t\tskip \"OSC connections never go IDLE with Shared-Keys enabled\"\n\n\t$LFS setstripe -c 1 -i 0 $DIR/$tfile\n\t# ensure ost1 is connected\n\tstat $DIR/$tfile >/dev/null || error \"can't stat\"\n\twait_osc_import_state client ost1 FULL\n\t# no locks, no reqs to let the connection idle\n\tcancel_lru_locks osc\n\tlru_resize_disable osc\n\tlocal before\n\tlocal now\n\tbefore=$($LCTL get_param -n \\\n\t\t ldlm.namespaces.$FSNAME-OST0000-osc-[^M]*.lru_size)\n\n\twait_osc_import_state client ost1 IDLE\n\tdd if=/dev/null of=$DIR/$tfile bs=1k count=1 conv=sync\n\tnow=$($LCTL get_param -n \\\n\t      ldlm.namespaces.$FSNAME-OST0000-osc-[^M]*.lru_size)\n\t[ $before == $now ] || error \"lru_size changed $before != $now\"\n}\nrun_test 816 \"do not reset lru_resize on idle reconnect\"\n\ncleanup_817() {\n\tumount $tmpdir\n\texportfs -u localhost:$DIR/nfsexp\n\trm -rf $DIR/nfsexp\n}\n\ntest_817() {\n\tsystemctl restart nfs-server.service || skip \"failed to restart nfsd\"\n\n\tmkdir -p $DIR/nfsexp\n\texportfs -orw,no_root_squash localhost:$DIR/nfsexp ||\n\t\terror \"failed to export nfs\"\n\n\ttmpdir=$(mktemp -d /tmp/nfs-XXXXXX)\n\tstack_trap cleanup_817 EXIT\n\n\tmount -t nfs -orw localhost:$DIR/nfsexp $tmpdir ||\n\t\terror \"failed to mount nfs to $tmpdir\"\n\n\tcp /bin/true $tmpdir\n\t$DIR/nfsexp/true || error \"failed to execute 'true' command\"\n}\nrun_test 817 \"nfsd won't cache write lock for exec file\"\n\ntest_818() {\n\tmkdir $DIR/$tdir\n\t$LFS setstripe -c1 -i0 $DIR/$tfile\n\t$LFS setstripe -c1 -i1 $DIR/$tfile\n\tstop $SINGLEMDS\n\t#define OBD_FAIL_OSP_CANT_PROCESS_LLOG\t\t0x2105\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x80002105\n\tstart $SINGLEMDS $(mdsdevname ${SINGLEMDS//mds/}) $MDS_MOUNT_OPTS ||\n\t\terror \"start $SINGLEMDS failed\"\n\trm -rf $DIR/$tdir\n}\nrun_test 818 \"unlink with failed llog\"\n\ntest_819a() {\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\tcancel_lru_locks osc\n\t#define OBD_FAIL_OST_2BIG_NIOBUF\t\t0x248\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x80000248\n\tdd if=$DIR/$tfile of=/dev/null bs=1M count=1\n\trm -f $TDIR/$tfile\n}\nrun_test 819a \"too big niobuf in read\"\n\ntest_819b() {\n\t#define OBD_FAIL_OST_2BIG_NIOBUF\t\t0x248\n\tdo_facet $SINGLEMDS lctl set_param fail_loc=0x80000248\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\tcancel_lru_locks osc\n\tsleep 1\n\trm -f $TDIR/$tfile\n}\nrun_test 819b \"too big niobuf in write\"\n\n\nfunction test_820_start_ost() {\n\tsleep 5\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tstart ost$num $(ostdevname $num) $OST_MOUNT_OPTS\n\tdone\n}\n\ntest_820() {\n\t[[ $MDSCOUNT -lt 2 ]] && skip_env \"needs >= 2 MDTs\"\n\n\tmkdir $DIR/$tdir\n\tumount_client $MOUNT || error \"umount failed\"\n\tfor num in $(seq $OSTCOUNT); do\n\t\tstop ost$num\n\tdone\n\n\t# mount client with no active OSTs\n\t# so that the client can't initialize max LOV EA size\n\t# from OSC notifications\n\tmount_client $MOUNT || error \"mount failed\"\n\t# delay OST starting to keep this 0 max EA size for a while\n\ttest_820_start_ost &\n\n\t# create a directory on MDS2\n\ttest_mkdir -i 1 -c1 $DIR/$tdir/mds2 ||\n\t\terror \"Failed to create directory\"\n\t# open intent should update default EA size\n\t# see mdc_update_max_ea_from_body()\n\t# notice this is the very first RPC to MDS2\n\tcp /etc/services $DIR/$tdir/mds2 ||\n\t\terror \"Failed to copy files to mds$n\"\n}\nrun_test 820 \"update max EA from open intent\"\n\n#\n# tests that do cleanup/setup should be run at the end\n#\n\ntest_900() {\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\tlocal ls\n\n\t#define OBD_FAIL_MGC_PAUSE_PROCESS_LOG   0x903\n\t$LCTL set_param fail_loc=0x903\n\n\tcancel_lru_locks MGC\n\n\tFAIL_ON_ERROR=true cleanup\n\tFAIL_ON_ERROR=true setup\n}\nrun_test 900 \"umount should not race with any mgc requeue thread\"\n\n# LUS-6253/LU-11185\ntest_901() {\n\tlocal oldc\n\tlocal newc\n\tlocal olds\n\tlocal news\n\t[ $PARALLEL == \"yes\" ] && skip \"skip parallel run\"\n\n\t# some get_param have a bug to handle dot in param name\n\tcancel_lru_locks MGC\n\toldc=$($LCTL get_param -n 'ldlm.namespaces.MGC*.lock_count')\n\tolds=$(do_facet mgs $LCTL get_param -n 'ldlm.namespaces.MGS*.lock_count')\n\tumount_client $MOUNT || error \"umount failed\"\n\tmount_client $MOUNT || error \"mount failed\"\n\tcancel_lru_locks MGC\n\tnewc=$($LCTL get_param -n 'ldlm.namespaces.MGC*.lock_count')\n\tnews=$(do_facet mgs $LCTL get_param -n 'ldlm.namespaces.MGS*.lock_count')\n\n\t[ $oldc -lt $newc ] && error \"mgc lock leak ($oldc != $newc)\"\n\t[ $olds -lt $news ] && error \"mgs lock leak ($olds != $news)\"\n\n\treturn 0\n}\nrun_test 901 \"don't leak a mgc lock on client umount\"\n\n# LU-13377\ntest_902() {\n\t[ $CLIENT_VERSION -lt $(version_code 2.13.52) ] &&\n\t\tskip \"client does not have LU-13377 fix\"\n\t#define OBD_FAIL_LLITE_SHORT_COMMIT 0x1415\n\t$LCTL set_param fail_loc=0x1415\n\tdd if=/dev/zero of=$DIR/$tfile bs=1M count=1\n\tcancel_lru_locks osc\n\trm -f $DIR/$tfile\n}\nrun_test 902 \"test short write doesn't hang lustre\"\n\ncomplete $SECONDS\n[ -f $EXT2_DEV ] && rm $EXT2_DEV || true\ncheck_and_cleanup_lustre\nif [ \"$I_MOUNTED\" != \"yes\" ]; then\n\tlctl set_param debug=\"$OLDDEBUG\" 2> /dev/null || true\nfi\nexit_status\n", "num_lines": 24401}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\n\nSIZE=${SIZE:-40960}\nOPENFILE=${OPENFILE:-openfile}\nOPENUNLINK=${OPENUNLINK:-openunlink}\nexport TMP=${TMP:-/tmp}\nMOUNT_2=${MOUNT_2:-\"yes\"}\nCHECK_GRANT=${CHECK_GRANT:-\"yes\"}\nGRANT_CHECK_LIST=${GRANT_CHECK_LIST:-\"\"}\n\nLUSTRE=${LUSTRE:-$(dirname $0)/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\ninit_logging\n\nALWAYS_EXCEPT=\"$SANITYN_EXCEPT \"\n# bug number for skipped test:  LU-7105\nALWAYS_EXCEPT+=\"                28 \"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\n# skip tests for PPC until they are fixed\nif [[ $(uname -m) = ppc64 ]]; then\n\t# bug number:    LU-11597 LU-11787\n\tALWAYS_EXCEPT+=\" 16a      71a\"\nfi\n\nif [ $mds1_FSTYPE = \"zfs\" ]; then\n\t# LU-2829 / LU-2887 - make allowances for ZFS slowness\n\tTEST33_NFILES=${TEST33_NFILES:-1000}\nfi\n\n#                                  23   (min)\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"33a\"\n\nbuild_test_filter\n\nFAIL_ON_ERROR=false\n\nSETUP=${SETUP:-:}\nTRACE=${TRACE:-\"\"}\n\ncheck_and_setup_lustre\n\nOSC=${OSC:-\"osc\"}\n\nassert_DIR\nrm -rf $DIR1/[df][0-9]* $DIR1/lnk $DIR/[df].${TESTSUITE}*\n\nSAMPLE_FILE=$TMP/$(basename $0 .sh).junk\ndd if=/dev/urandom of=$SAMPLE_FILE bs=1M count=1\n\n# $RUNAS_ID may get set incorrectly somewhere else\n[ $UID -eq 0 -a $RUNAS_ID -eq 0 ] && error \"\\$RUNAS_ID set to 0, but \\$UID is also 0!\"\n\ncheck_runas_id $RUNAS_ID $RUNAS_GID $RUNAS\n\ntest_1() {\n\ttouch $DIR1/$tfile\n\t[ -f $DIR2/$tfile ] || error \"Check create\"\n\tchmod 777 $DIR2/$tfile\n\t$CHECKSTAT -t file -p 0777 $DIR1/$tfile ||\n\t\terror \"Check attribute update for 0777\"\n\n\tchmod a-x $DIR2/$tfile\n\t$CHECKSTAT -t file -p 0666 $DIR1/$tfile ||\n\t\terror \"Check attribute update for 0666\"\n\n\trm $DIR2/$tfile\n\t$CHECKSTAT -a $DIR1/$tfile ||\n\t\terror \"Check unlink - removes file on other mountpoint\"\n}\nrun_test 1 \"Check attribute updates on 2 mount points\"\n\ntest_2a() {\n\ttouch $DIR1/f2a\n\tls -l $DIR2/f2a\n\tchmod 777 $DIR2/f2a\n\t$CHECKSTAT -t file -p 0777 $DIR1/f2a ||\n\t\terror \"Either not file type or perms not 0777\"\n}\nrun_test 2a \"check cached attribute updates on 2 mtpt's ========\"\n\ntest_2b() {\n\ttouch $DIR1/f2b\n\tls -l $DIR2/f2b\n\tchmod 777 $DIR1/f2b\n\t$CHECKSTAT -t file -p 0777 $DIR2/f2b ||\n\t\terror \"Either not file type or perms not 0777\"\n}\nrun_test 2b \"check cached attribute updates on 2 mtpt's ========\"\n\n# NEED TO SAVE ROOT DIR MODE\ntest_2c() {\n\tchmod 777 $DIR1\n\t$CHECKSTAT -t dir -p 0777 $DIR2 ||\n\t\terror \"Either not dir type or perms not 0777\"\n}\nrun_test 2c \"check cached attribute updates on 2 mtpt's root ===\"\n\ntest_2d() {\n\tchmod 755 $DIR1\n\t$CHECKSTAT -t dir -p 0755 $DIR2 ||\n\t\terror \"Either not file type or perms not 0775\"\n}\nrun_test 2d \"check cached attribute updates on 2 mtpt's root ===\"\n\ntest_2e() {\n        chmod 755 $DIR1\n        ls -l $DIR1\n        ls -l $DIR2\n        chmod 777 $DIR1\n\t\t$RUNAS dd if=/dev/zero of=$DIR2/$tfile count=1 ||\n\t\t\terror \"dd failed\"\n}\nrun_test 2e \"check chmod on root is propagated to others\"\n\ntest_2f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal MDTIDX=1\n\tlocal remote_dir=$tdir/remote_dir\n\n\tmkdir -p $DIR1/$tdir\n\t$LFS mkdir -i $MDTIDX $DIR1/$remote_dir ||\n\t           error \"Create remote directory failed\"\n\n\ttouch $DIR1/$remote_dir/$tfile ||\n\t\terror \"Create file under remote directory failed\"\n\tchmod 777 $DIR1/$remote_dir/$tfile ||\n\t\terror \"Chmod file under remote directory failed\"\n\n\t$CHECKSTAT -t file -p 0777 $DIR2/$remote_dir/$tfile ||\n\t\terror \"Check attr of file under remote directory failed\"\n\n\tchown $RUNAS_ID:$RUNAS_GID $DIR1/$remote_dir/$tfile ||\n\t\terror \"Chown file under remote directory failed\"\n\n\t$CHECKSTAT -u \\#$RUNAS_ID -g \\#$RUNAS_GID $DIR2/$remote_dir/$tfile ||\n\t\terror \"Check owner of file under remote directory failed\"\n\n\tcd $DIR2/$remote_dir || error \"enter remote dir\"\n\trm -rf $DIR1/$remote_dir/$tfile ||\n\t\terror \"Unlink remote directory failed\"\n\n\t$CHECKSTAT -t file $DIR2/$remote_dir/$tfile &&\n\t\terror \"unlink file still exists!\"\n\n        cd $DIR2/$tdir || error \"exit remote dir\"\n\trm -rf $DIR1/$tdir || error \"unlink directory failed\"\n}\nrun_test 2f \"check attr/owner updates on DNE with 2 mtpt's\"\n\ntest_2g() {\n\tdd if=/dev/zero of=$DIR1/$tfile oflag=sync bs=1M count=2\n\n\tlocal block1=$(stat $DIR1/$tfile | awk '/Blocks/ {print $4} ')\n\tcancel_lru_locks osc\n\tlocal block2=$(stat $DIR2/$tfile | awk '/Blocks/ {print $4} ')\n\techo \"$DIR1/$tfile has $block1 blocks\"\n\techo \"$DIR2/$tfile has $block2 blocks\"\n\t[ $block1 -eq $block2 ] || error \"$block1 not equal to $block2\"\n}\nrun_test 2g \"check blocks update on sync write\"\n\ntest_3() {\n\tlocal target=\"this/is/good\"\n\tln -s $target $DIR1/$tfile || error \"ln -s $target $DIR1/$tfile failed\"\n\t[ \"$(ls -l $DIR2/$tfile | sed -e 's/.* -> //')\" = \"$target\" ] ||\n\t\terror \"link $DIR2/$tfile not as expected\"\n}\nrun_test 3 \"symlink on one mtpt, readlink on another ===========\"\n\ntest_4() {\n\tmultifstat $DIR1/f4 $DIR2/f4\n}\nrun_test 4 \"fstat validation on multiple mount points ==========\"\n\ntest_5() {\n\tmcreate $DIR1/f5\n\t$TRUNCATE $DIR2/f5 100\n\t$CHECKSTAT -t file -s 100 $DIR1/f5 ||\n\t\terror \"Either not file type or size not equal to 100 bytes\"\n\trm $DIR1/f5\n}\nrun_test 5 \"create a file on one mount, truncate it on the other\"\n\ntest_6() {\n\topenunlink $DIR1/$tfile $DIR2/$tfile || \\\n\t\terror \"openunlink $DIR1/$tfile $DIR2/$tfile\"\n}\nrun_test 6 \"remove of open file on other node ==================\"\n\ntest_7() {\n\tlocal dir=d7\n\topendirunlink $DIR1/$dir $DIR2/$dir || \\\n\t\terror \"opendirunlink $DIR1/$dir $DIR2/$dir\"\n}\nrun_test 7 \"remove of open directory on other node =============\"\n\ntest_8() {\n\topendevunlink $DIR1/$tfile $DIR2/$tfile || \\\n\t\terror \"opendevunlink $DIR1/$tfile $DIR2/$tfile\"\n}\nrun_test 8 \"remove of open special file on other node ==========\"\n\ntest_9a() {\n\tMTPT=1\n\tlocal dir\n\t> $DIR2/f9\n\tfor C in a b c d e f g h i j k l; do\n\t\tdir=`eval echo \\\\$DIR$MTPT`\n\t\techo -n $C >> $dir/f9\n\t\t[ \"$MTPT\" -eq 1 ] && MTPT=2 || MTPT=1\n\tdone\n\t[ \"`cat $DIR1/f9`\" = \"abcdefghijkl\" ] || \\\n\t\terror \"`od -a $DIR1/f9` != abcdefghijkl\"\n}\nrun_test 9a \"append of file with sub-page size on multiple mounts\"\n\n#LU-10681 - tiny writes & appending to sparse striped file\ntest_9b() {\n\t[[ $OSTCOUNT -ge 2 ]] || { skip \"needs >= 2 OSTs\"; return; }\n\n\t$LFS setstripe -c 2 -S 1M $DIR/$tfile\n\techo \"foo\" >> $DIR/$tfile\n\tdd if=/dev/zero of=$DIR2/$tfile bs=1M count=1 seek=1 conv=notrunc ||\n\t\terror \"sparse dd $DIR2/$tfile failed\"\n\techo \"foo\" >> $DIR/$tfile\n\n\tdata=$(dd if=$DIR2/$tfile bs=1 count=3 skip=$((2 * 1048576)) conv=notrunc)\n\techo \"Data read (expecting 'foo')\": $data\n\t[ \"$data\" = \"foo\" ] || error \"append to sparse striped file failed\"\n}\nrun_test 9b \"append to striped sparse file\"\n\ntest_10a() {\n\tMTPT=1\n\tlocal dir\n\tOFFSET=0\n\t> $DIR2/f10\n\tfor C in a b c d e f g h i j k l; do\n\t\tdir=`eval echo \\\\$DIR$MTPT`\n\t\techo -n $C | dd of=$dir/f10 bs=1 seek=$OFFSET count=1\n\t\t[ \"$MTPT\" -eq 1 ] && MTPT=2 || MTPT=1\n\t\tOFFSET=`expr $OFFSET + 1`\n\tdone\n\t[ \"`cat $DIR1/f10`\" = \"abcdefghijkl\" ] || \\\n\t\terror \"`od -a $DIR1/f10` != abcdefghijkl\"\n}\nrun_test 10a \"write of file with sub-page size on multiple mounts \"\n\ntest_10b() {\n\t# create a seed file\n\tyes \"R\" | head -c 4000 >$TMP/f10b-seed\n\tdd if=$TMP/f10b-seed of=$DIR1/f10b bs=3k count=1 || error \"dd $DIR1\"\n\n\t$TRUNCATE $DIR1/f10b 4096 || error \"truncate 4096\"\n\n\tdd if=$DIR2/f10b of=$TMP/f10b-lustre bs=4k count=1 || error \"dd $DIR2\"\n\n\t# create a test file locally to compare\n\tdd if=$TMP/f10b-seed of=$TMP/f10b bs=3k count=1 || error \"dd random\"\n\t$TRUNCATE $TMP/f10b 4096 || error \"truncate 4096\"\n\tcmp $TMP/f10b $TMP/f10b-lustre || error \"file miscompare\"\n\trm $TMP/f10b $TMP/f10b-lustre $TMP/f10b-seed\n}\nrun_test 10b \"write of file with sub-page size on multiple mounts \"\n\ntest_11() {\n\ttest_mkdir $DIR1/d11\n\tmultiop_bg_pause $DIR1/d11/f O_c || return 1\n\tMULTIPID=$!\n\tcp -p /bin/ls $DIR1/d11/f\n\t$DIR2/d11/f\n\tRC=$?\n\tkill -USR1 $MULTIPID\n\twait $MULTIPID || error \"wait for PID $MULTIPID failed\"\n\t[ $RC -eq 0 ] && error || true\n}\nrun_test 11 \"execution of file opened for write should return error ====\"\n\ntest_12() {\n\tDIR=$DIR DIR2=$DIR2 sh lockorder.sh\n}\nrun_test 12 \"test lock ordering (link, stat, unlink)\"\n\ntest_13() {\t# bug 2451 - directory coherency\n\ttest_mkdir $DIR1/d13\n\tcd $DIR1/d13 || error \"cd to $DIR1/d13 failed\"\n\tls\n\t( touch $DIR1/d13/f13 ) # needs to be a separate shell\n\tls\n\trm -f $DIR2/d13/f13 || error \"Cannot remove $DIR2/d13/f13\"\n\tls 2>&1 | grep f13 && error \"f13 shouldn't return an error (1)\" || true\n\t# need to run it twice\n\t( touch $DIR1/d13/f13 ) # needs to be a separate shell\n\tls\n\trm -f $DIR2/d13/f13 || error \"Cannot remove $DIR2/d13/f13\"\n\tls 2>&1 | grep f13 && error \"f13 shouldn't return an error (2)\" || true\n}\nrun_test 13 \"test directory page revocation\"\n\ntest_14aa() {\n\ttest_mkdir $DIR1/$tdir\n\tcp -p /bin/ls $DIR1/$tdir/$tfile\n\tmultiop_bg_pause $DIR1/$tdir/$tfile Ow_c || return 1\n\tMULTIPID=$!\n\n\t$DIR2/$tdir/$tfile && error || true\n\tkill $MULTIPID\n}\nrun_test 14aa \"execution of file open for write returns -ETXTBSY\"\n\ntest_14ab() {\n\ttest_mkdir $DIR1/$tdir\n\tcp -p $(which sleep) $DIR1/$tdir/sleep || error \"cp failed\"\n\t$DIR1/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\t$MULTIOP $DIR2/$tdir/sleep Oc && error \"expected error, got success\"\n\tkill $SLEEP_PID\n}\nrun_test 14ab \"open(RDWR) of executing file returns -ETXTBSY\"\n\ntest_14b() { # bug 3192, 7040\n\ttest_mkdir $DIR1/$tdir\n\tcp -p $(which sleep) $DIR1/$tdir/sleep || error \"cp failed\"\n\t$DIR1/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\t$TRUNCATE $DIR2/$tdir/sleep 60 && kill -9 $SLEEP_PID && \\\n\t\terror \"expected truncate error, got success\"\n\tkill $SLEEP_PID\n\tcmp $(which sleep) $DIR1/$tdir/sleep || error \"binary changed\"\n}\nrun_test 14b \"truncate of executing file returns -ETXTBSY ======\"\n\ntest_14c() { # bug 3430, 7040\n\ttest_mkdir $DIR1/$tdir\n\tcp -p $(which sleep) $DIR1/$tdir/sleep || error \"cp failed\"\n\t$DIR1/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\tcp /etc/hosts $DIR2/$tdir/sleep && error \"expected error, got success\"\n\tkill $SLEEP_PID\n\tcmp $(which sleep) $DIR1/$tdir/sleep || error \"binary changed\"\n}\nrun_test 14c \"open(O_TRUNC) of executing file return -ETXTBSY ==\"\n\ntest_14d() { # bug 10921\n\ttest_mkdir $DIR1/$tdir\n\tcp -p $(which sleep) $DIR1/$tdir/sleep || error \"cp failed\"\n\t$DIR1/$tdir/sleep 60 &\n\tSLEEP_PID=$!\n\tlog chmod\n\tchmod 600 $DIR1/$tdir/sleep || error \"chmod failed\"\n\tkill $SLEEP_PID\n\tcmp $(which sleep) $DIR1/$tdir/sleep || error \"binary changed\"\n}\nrun_test 14d \"chmod of executing file is still possible ========\"\n\ntest_15() {\t# bug 974 - ENOSPC\n\techo \"PATH=$PATH\"\n\tsh oos2.sh $MOUNT1 $MOUNT2\n\twait_delete_completed\n\tgrant_error=$(dmesg | grep \"< tot_grant\")\n\t[ -z \"$grant_error\" ] || error \"$grant_error\"\n}\nrun_test 15 \"test out-of-space with multiple writers ===========\"\n\nCOUNT=${COUNT:-2500}\n# The FSXNUM reduction for ZFS is needed until ORI-487 is fixed.\n# We don't want to skip it entirely, but ZFS is VERY slow and cannot\n# pass a 2500 operation dual-mount run within the time limit.\nif [ \"$ost1_FSTYPE\" = \"zfs\" ]; then\n\tFSXNUM=$((COUNT / 5))\n\tFSXP=1\nelif [ \"$SLOW\" = \"yes\" ]; then\n\tFSXNUM=$((COUNT * 5))\n\tFSXP=500\nelse\n\tFSXNUM=$COUNT\n\tFSXP=100\nfi\n\ntest_16a() {\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\tlocal stripe_size=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize\")\n\n\t# to allocate grant because it may run out due to test_15.\n\t$LFS setstripe -c -1 $file1\n\tdd if=/dev/zero of=$file1 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\tdd if=/dev/zero of=$file2 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\trm -f $file1\n\n\t$LFS setstripe -c -1 $file1 # b=10919\n\tfsx -c 50 -p $FSXP -N $FSXNUM -l $((SIZE * 256)) -S 0 $file1 $file2 ||\n\t\terror \"fsx failed\"\n\trm -f $file1\n\n\t# O_DIRECT reads and writes must be aligned to the device block size.\n\tfsx -c 50 -p $FSXP -N $FSXNUM -l $((SIZE * 256)) -S 0 -Z -r 4096 \\\n\t\t-w 4096 $file1 $file2 || error \"fsx with O_DIRECT failed.\"\n}\nrun_test 16a \"$FSXNUM iterations of dual-mount fsx\"\n\n# Consistency check for tiny writes, LU-9409\ntest_16b() {\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\tlocal stripe_size=($($LFS getstripe -S $DIR))\n\n\t# to allocate grant because it may run out due to test_15.\n\tlfs setstripe -c -1 $file1\n\tdd if=/dev/zero of=$file1 bs=$stripe_size count=$OSTCOUNT oflag=sync ||\n\t\terror \"dd failed writing to file=$file1\"\n\tdd if=/dev/zero of=$file2 bs=$stripe_size count=$OSTCOUNT oflag=sync ||\n\t\terror \"dd failed writing to file=$file2\"\n\trm -f $file1\n\n\tlfs setstripe -c -1 $file1 # b=10919\n\t# -o is set to 8192 because writes < 1 page and between 1 and 2 pages\n\t# create a mix of tiny writes & normal writes\n\tfsx -c 50 -p $FSXP -N $FSXNUM -l $((SIZE * 256)) -o 8192 -S 0 \\\n\t\t$file1 $file2 || error \"fsx with tiny write failed.\"\n}\nrun_test 16b \"$FSXNUM iterations of dual-mount fsx at small size\"\n\ntest_16c() {\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\tlocal stripe_size=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize\")\n\n\t[ \"$ost1_FSTYPE\" != ldiskfs ] && skip \"dio on ldiskfs only\"\n\n\t# to allocate grant because it may run out due to test_15.\n\t$LFS setstripe -c -1 $file1\n\tdd if=/dev/zero of=$file1 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\tdd if=/dev/zero of=$file2 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\trm -f $file1\n\twait_delete_completed\n\n\tlocal list=$(comma_list $(osts_nodes))\n\tif ! get_osd_param $list '' read_cache_enable >/dev/null; then\n\t\tskip \"not cache-capable obdfilter\"\n\tfi\n\n\tset_osd_param $list '' read_cache_enable 0\n\tset_osd_param $list '' writethrough_cache_enable 0\n\n\t$LFS setstripe -c -1 $file1 # b=10919\n\tfsx -c 50 -p $FSXP -N $FSXNUM -l $((SIZE * 256)) -S 0 $file1 $file2 ||\n\t\terror \"fsx failed\"\n\trm -f $file1\n\n\tset_osd_param $list '' read_cache_enable 1\n\tset_osd_param $list '' writethrough_cache_enable 1\n\n\treturn 0\n}\nrun_test 16c \"verify data consistency on ldiskfs with cache disabled (b=17397)\"\n\ntest_16d() {\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\tlocal file3=$DIR1/file\n\tlocal stripe_size=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize\")\n\n\t# to allocate grant because it may run out due to test_15.\n\t$LFS setstripe -c -1 $file1\n\tdd if=/dev/zero of=$file1 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\tdd if=/dev/zero of=$file2 bs=$stripe_size count=$OSTCOUNT oflag=sync\n\trm -f $file1\n\n\tlocal tmpfile=`mktemp`\n\t$LFS setstripe -c -1 $file1 # b=10919\n\t$LCTL set_param ldlm.namespaces.*.lru_size=clear\n\t\n\t# direct write on one client and direct read from another\n\tdd if=/dev/urandom of=$file1 bs=1M count=100 oflag=direct\n\tdd if=$file2 of=$tmpfile iflag=direct bs=1M\n\tdiff $file1 $tmpfile || error \"file different(1)\"\n\trm -f $file1\n\n\t# buffer write on one client, but direct read from another\n\tdd if=$tmpfile of=$file1 bs=1M count=100\n\tdd if=$file2 of=$file3 bs=1M iflag=direct count=100\n\tdiff $file3 $tmpfile || error \"file different(2)\"\n\n\trm -f $file3 $file2 $file1\n\t# direct write on one client\n\tdd if=$tmpfile of=$file1 bs=1M count=100 oflag=direct\n\t# buffer read from another client\n\tdd if=$file2 of=$file3 bs=1M count=100\n\tdiff $file3 $tmpfile || error \"file different(3)\"\n\n\trm -f $file1 $file2 $file3 $tmpfile\n\n}\nrun_test 16d \"Verify DIO and buffer IO with two clients\"\n\ntest_16e() { # LU-13227\n\tlocal file1=$DIR1/$tfile\n\tlocal file2=$DIR2/$tfile\n\n\t# client1 write 10M data\n\tdd if=/dev/zero of=$file1 bs=1M count=10\n\t# drop locks\n\tcancel_lru_locks osc > /dev/null\n\t# use lockahead to generate one PW lock to keep LVB loaded.\n\t$LFS ladvise -a lockahead --start 0 --length 1M \\\n\t\t--mode WRITE $file1\n\t# direct write to extend file size on client2\n\tdd if=/dev/zero of=$file2 bs=1M seek=20 count=1 \\\n\t\toflag=direct conv=notrunc\n\tlocal filesize=$(stat -c %s $file2)\n\t[ \"$filesize\" -eq 22020096 ] ||\n\t\terror \"expected filesize 22020096 got $filesize\"\n\trm -f $file1\n}\nrun_test 16e \"Verify size consistency for O_DIRECT write\"\n\ntest_17() { # bug 3513, 3667\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return\n\n\tlfs setstripe $DIR1/$tfile -i 0 -c 1\n\tcp $SAMPLE_FILE $DIR1/$tfile\n\tcancel_lru_locks osc > /dev/null\n\t#define OBD_FAIL_ONCE|OBD_FAIL_LDLM_CREATE_RESOURCE    0x30a\n\tdo_facet ost1 lctl set_param fail_loc=0x8000030a\n\tls -ls $DIR1/$tfile | awk '{ print $1,$6 }' > $DIR1/$tfile-1 & \\\n\tls -ls $DIR2/$tfile | awk '{ print $1,$6 }' > $DIR2/$tfile-2\n\twait\n\tdiff -u $DIR1/$tfile-1 $DIR2/$tfile-2 || error \"files are different\"\n}\nrun_test 17 \"resource creation/LVB creation race ===============\"\n\ntest_18() {\n        # turn e.g. ALWAYS_EXCEPT=\"18c\" into \"-e 3\"\n        local idx\n        local excepts=\n        for idx in {a..z}; do\n                local ptr=EXCEPT_ALWAYS_18$idx\n                [ x${!ptr} = xtrue ] || continue\n\n                excepts=\"$excepts -e $(($(printf %d \\'$idx)-96))\"\n        done\n\n\texcepts=\"$excepts -e 7 -e 8 -e 9\"\n\t$LUSTRE/tests/mmap_sanity -d $MOUNT1 -m $MOUNT2 $excepts ||\n\t\terror \"mmap_sanity test failed\"\n\tsync; sleep 1; sync\n}\nrun_test 18 \"mmap sanity check =================================\"\n\ntest_19() { # bug3811\n\tlocal node=$(facet_active_host ost1)\n\n\t[ \"x$DOM\" = \"xyes\" ] && node=$(facet_active_host $SINGLEMDS)\n\n\t# check whether obdfilter is cache capable at all\n\tget_osd_param $node '' read_cache_enable >/dev/null ||\n\t\tskip \"not cache-capable obdfilter\"\n\n\tlocal MAX=$(get_osd_param $node '' readcache_max_filesize | head -n 1)\n\tset_osd_param $node '' readcache_max_filesize 4096\n\tdd if=/dev/urandom of=$TMP/$tfile bs=512k count=32\n\tlocal SUM=$(cksum $TMP/$tfile | cut -d\" \" -f 1,2)\n\tcp $TMP/$tfile $DIR1/$tfile\n\tfor i in `seq 1 20`; do\n\t\t[ $((i % 5)) -eq 0 ] && log \"$testname loop $i\"\n\t\tcancel_lru_locks $OSC > /dev/null\n\t\tcksum $DIR1/$tfile | cut -d\" \" -f 1,2 > $TMP/sum1 & \\\n\t\tcksum $DIR2/$tfile | cut -d\" \" -f 1,2 > $TMP/sum2\n\t\twait\n\t\t[ \"$(cat $TMP/sum1)\" = \"$SUM\" ] || \\\n\t\t\terror \"$DIR1/$tfile $(cat $TMP/sum1) != $SUM\"\n\t\t[ \"$(cat $TMP/sum2)\" = \"$SUM\" ] || \\\n\t\t\terror \"$DIR2/$tfile $(cat $TMP/sum2) != $SUM\"\n\tdone\n\tset_osd_param $node '' readcache_max_filesize $MAX\n\trm $DIR1/$tfile\n}\nrun_test 19 \"test concurrent uncached read races ===============\"\n\ntest_20() {\n\ttest_mkdir $DIR1/$tdir\n\tcancel_lru_locks\n\tCNT=$($LCTL get_param -n llite.*.dump_page_cache | wc -l)\n\t$MULTIOP $DIR1/$tdir/$tfile Ow8190c\n\t$MULTIOP $DIR2/$tdir/$tfile Oz8194w8190c\n\t$MULTIOP $DIR1/$tdir/$tfile Oz0r8190c\n\tcancel_lru_locks\n\tCNT2=$($LCTL get_param -n llite.*.dump_page_cache | wc -l)\n\t[[ $CNT2 == $CNT ]] ||\n\t\terror $((CNT2 - CNT))\" page left in cache after lock cancel\"\n}\nrun_test 20 \"test extra readahead page left in cache ====\"\n\ncleanup_21() {\n\ttrap 0\n\tumount $DIR1/$tdir\n}\n\ntest_21() { # Bug 5907\n\ttest_mkdir $DIR1/$tdir\n\tmount /etc $DIR1/$tdir --bind || error \"mount failed\" # Poor man's mount.\n\ttrap cleanup_21 EXIT\n\trmdir -v $DIR1/$tdir && error \"Removed mounted directory\"\n\trmdir -v $DIR2/$tdir && echo \"Removed mounted directory from another mountpoint, needs to be fixed\"\n\ttest -d $DIR1/$tdir || error \"Mounted directory disappeared\"\n\tcleanup_21\n\ttest -d $DIR2/$tdir || test -d $DIR1/$tdir && error \"Removed dir still visible after umount\"\n\ttrue\n}\nrun_test 21 \" Try to remove mountpoint on another dir ====\"\n\ntest_23() { # Bug 5972\n\tlocal at_diff=$(do_facet $SINGLEMDS \\\n\t\t$LCTL get_param -n mdd.*MDT0000*.atime_diff | head -n1)\n\techo \"atime should be updated while another read\" > $DIR1/$tfile\n\n\t# clear the lock(mode: LCK_PW) gotten from creating operation\n\tcancel_lru_locks $OSC\n\ttime1=$(date +%s)\n\techo \"now is $time1\"\n\tsleep $((at_diff + 1))\n\n\techo \"starting reads\"\n\tmultiop_bg_pause $DIR1/$tfile or20_c || return 1\n        # with SOM and opencache enabled, we need to close a file and cancel\n        # open lock to get atime propogated to MDS\n        kill -USR1 $! || return 2\n        cancel_lru_locks mdc\n\n\ttime2=$(stat -c \"%X\" $DIR/$tfile)\n\techo \"new atime is $time2\"\n\n\t[ $time2 -gt $time1 ] || error \"atime was not updated\"\n\trm -f $DIR1/$tfile || error \"rm -f $DIR1/$tfile failed\"\n\ttrue\n}\nrun_test 23 \" others should see updated atime while another read====\"\n\ntest_24a() {\n\ttouch $DIR1/$tfile\n\tlfs df || error \"lfs df failed\"\n\tlfs df -ih || error \"lfs df -ih failed\"\n\tlfs df -h $DIR1 || error \"lfs df -h $DIR1 failed\"\n\tlfs df -i $DIR2 || error \"lfs df -i $DIR2 failed\"\n\tlfs df $DIR1/$tfile || error \"lfs df $DIR1/$tfile failed\"\n\tlfs df -ih $DIR2/$tfile || error \"lfs df -ih $DIR2/$tfile failed\"\n\n\tOSC=`lctl dl | awk '/-osc-|OSC.*MNT/ {print $4}' | head -n 1`\n#\tOSC=`lctl dl | awk '/-osc-/ {print $4}' | head -n 1`\n\tlctl --device %osc deactivate\n\tlfs df -i || error \"lfs df -i with deactivated OSC failed\"\n\tlctl --device %osc activate\n\tlfs df || error \"lfs df with reactivated OSC failed\"\n}\nrun_test 24a \"lfs df [-ih] [path] test =========================\"\n\ntest_24b() {\n\ttouch $DIR1/$tfile\n\tfsnum=$(lfs_df | grep -c \"summary\")\n\t[ $fsnum -eq 2 ] || error \"lfs df shows $fsnum != 2 filesystems.\"\n}\nrun_test 24b \"lfs df should show both filesystems ===============\"\n\ntest_25a() {\n\tlocal acl=$(lctl get_param -n mdc.*MDT0000-mdc-*.connect_flags |\n\t\t\t\t\t\t\t\tgrep -c acl)\n\t[ \"$acl\" -lt 1 ] && skip \"must have acl, skipping\" && return\n\n\tmkdir -p $DIR1/$tdir\n\ttouch $DIR1/$tdir/f1 || error \"touch $DIR1/$tdir/f1\"\n\tchmod 0755 $DIR1/$tdir/f1 || error \"chmod 0755 $DIR1/$tdir/f1\"\n\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #1\"\n\tsetfacl -m u:$RUNAS_ID:--- -m g:$RUNAS_GID:--- $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #1\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 && error \"checkstat $DIR2/$tdir/f1 #2\"\n\tsetfacl -m u:$RUNAS_ID:r-x -m g:$RUNAS_GID:r-x $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #2\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #3\"\n\tsetfacl -m u:$RUNAS_ID:--- -m g:$RUNAS_GID:--- $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #3\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 && error \"checkstat $DIR2/$tdir/f1 #4\"\n\tsetfacl -x u:$RUNAS_ID: -x g:$RUNAS_GID: $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #4\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #5\"\n\n\trm -rf $DIR1/$tdir\n}\nrun_test 25a \"change ACL on one mountpoint be seen on another ===\"\n\ntest_25b() {\n\tlocal acl=$(lctl get_param -n mdc.*MDT0000-mdc-*.connect_flags |\n\t\t\t\t\t\t\tgrep -c acl)\n\t[ \"$acl\" -lt 1 ] && skip \"must have acl, skipping\" && return\n\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\trm -rf $DIR1/$tdir\n\t$LFS mkdir -i 1 $DIR1/$tdir\n\ttouch $DIR1/$tdir/f1 || error \"touch $DIR1/$tdir/f1\"\n\tchmod 0755 $DIR1/$tdir/f1 || error \"chmod 0755 $DIR1/$tdir/f1\"\n\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #1\"\n\tsetfacl -m u:$RUNAS_ID:--- -m g:$RUNAS_GID:--- $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #1\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 && error \"checkstat $DIR2/$tdir/f1 #2\"\n\tsetfacl -m u:$RUNAS_ID:r-x -m g:$RUNAS_GID:r-x $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #2\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #3\"\n\tsetfacl -m u:$RUNAS_ID:--- -m g:$RUNAS_GID:--- $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #3\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 && error \"checkstat $DIR2/$tdir/f1 #4\"\n\tsetfacl -x u:$RUNAS_ID: -x g:$RUNAS_GID: $DIR1/$tdir ||\n\t\terror \"setfacl $DIR2/$tdir #4\"\n\t$RUNAS $CHECKSTAT $DIR2/$tdir/f1 || error \"checkstat $DIR2/$tdir/f1 #5\"\n\n\trm -rf $DIR1/$tdir\n}\nrun_test 25b \"change ACL under remote dir on one mountpoint be seen on another\"\n\ntest_26a() {\n\tutime $DIR1/f26a -s $DIR2/f26a || error \"utime failed for $DIR1/f26a\"\n}\nrun_test 26a \"allow mtime to get older\"\n\ntest_26b() {\n        touch $DIR1/$tfile\n        sleep 1\n        echo \"aaa\" >> $DIR1/$tfile\n        sleep 1\n        chmod a+x $DIR2/$tfile\n        mt1=`stat -c %Y $DIR1/$tfile`\n        mt2=`stat -c %Y $DIR2/$tfile`\n\n        if [ x\"$mt1\" != x\"$mt2\" ]; then\n                error \"not equal mtime, client1: \"$mt1\", client2: \"$mt2\".\"\n        fi\n}\nrun_test 26b \"sync mtime between ost and mds\"\n\ntest_27() {\n\tcancel_lru_locks $OSC\n\tlctl clear\n\tdd if=/dev/zero of=$DIR2/$tfile bs=$((4096+4))k conv=notrunc count=4 seek=3 &\n\tDD2_PID=$!\n\tusleep 50\n\tlog \"dd 1 started\"\n\n\tdd if=/dev/zero of=$DIR1/$tfile bs=$((16384-1024))k conv=notrunc count=1 seek=4 &\n\tDD1_PID=$!\n\tlog \"dd 2 started\"\n\n\tsleep 1\n\tdd if=/dev/zero of=$DIR1/$tfile bs=8k conv=notrunc count=1 seek=0\n\tlog \"dd 3 finished\"\n\tlctl set_param -n ldlm.dump_namespaces \"\"\n\twait $DD1_PID $DD2_PID\n\t[ $? -ne 0 ] && lctl dk $TMP/debug || true\n}\nrun_test 27 \"align non-overlapping extent locks from request ===\"\n\ntest_28() { # bug 9977\n\tECHO_UUID=\"ECHO_osc1_UUID\"\n\ttOST=$($LCTL dl | awk '/-osc-|OSC.*MNT/ { print $4 }' | head -n1)\n\n\t$LFS setstripe $DIR1/$tfile -S 1048576 -i 0 -c 2\n\ttOBJID=`$LFS getstripe $DIR1/$tfile | awk '$1 == 1 {print $2}'`\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1024k count=2\n\n\t$LCTL <<-EOF\n\t\tnewdev\n\t\tattach echo_client ECHO_osc1 $ECHO_UUID\n\t\tsetup $tOST\n\tEOF\n\n\ttECHOID=`$LCTL dl | grep $ECHO_UUID | awk '{ print $1 }'`\n\t$LCTL --device $tECHOID destroy \"${tOBJID}:0\"\n\n    \t$LCTL <<-EOF\n\t\tcfg_device ECHO_osc1\n\t\tcleanup\n\t\tdetach\n\tEOF\n\n\t# reading of 1st stripe should pass\n\tdd if=$DIR2/$tfile of=/dev/null bs=1024k count=1 || error \"dd failed\"\n\t# reading of 2nd stripe should fail (this stripe was destroyed)\n\tdd if=$DIR2/$tfile of=/dev/null bs=1024k count=1 skip=1 && error\n\n\t# now, recreating test file\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1024k count=2 || error \"dd failed\"\n\t# reading of 1st stripe should pass\n\tdd if=$DIR2/$tfile of=/dev/null bs=1024k count=1 || error \"dd failed\"\n\t# reading of 2nd stripe should pass\n\tdd if=$DIR2/$tfile of=/dev/null bs=1024k count=1 skip=1 ||\n\t\terror \"dd failed\"\n}\nrun_test 28 \"read/write/truncate file with lost stripes\"\n\ntest_30() { #b=11110, LU-2523\n\ttest_mkdir $DIR1/$tdir\n\tcp -f /bin/bash $DIR1/$tdir/bash\n\t/bin/sh -c 'sleep 1; rm -f $DIR2/$tdir/bash; cp /bin/bash $DIR2/$tdir' &\n\t$DIR1/$tdir/bash -c 'sleep 2;\n\t\topenfile -f O_RDONLY /proc/$$/exe >& /dev/null; echo $?'\n\twait\n\ttrue\n}\nrun_test 30 \"recreate file race\"\n\ntest_31a() {\n\ttest_mkdir $DIR1/$tdir\n\tlocal writes=$(LANG=C dd if=/dev/zero of=$DIR/$tdir/$tfile \\\n\t\t       count=1 2>&1 | awk 'BEGIN { FS=\"+\" } /out/ {print $1}')\n\t#define OBD_FAIL_LDLM_CANCEL_BL_CB_RACE   0x314\n\tlctl set_param fail_loc=0x314\n\tlocal reads=$(LANG=C dd if=$DIR2/$tdir/$tfile of=/dev/null 2>&1 |\n\t\t      awk 'BEGIN { FS=\"+\" } /in/ {print $1}')\n\t[ $reads -eq $writes ] || error \"read\" $reads \"blocks, must be\" $writes\n}\nrun_test 31a \"voluntary cancel / blocking ast race==============\"\n\ntest_31b() {\n\tremote_ost || { skip \"local OST\" && return 0; }\n\tremote_ost_nodsh && skip \"remote OST w/o dsh\" && return 0\n\n\t# make sure there is no local locks due to destroy\n\twait_mds_ost_sync || error \"wait_mds_ost_sync()\"\n\twait_delete_completed || error \"wait_delete_completed()\"\n\n\ttest_mkdir $DIR1/$tdir\n        lfs setstripe $DIR/$tdir/$tfile -i 0 -c 1\n        cp /etc/hosts $DIR/$tdir/$tfile\n        #define OBD_FAIL_LDLM_CANCEL_BL_CB_RACE   0x314\n        lctl set_param fail_loc=0x314\n        #define OBD_FAIL_LDLM_OST_FAIL_RACE      0x316\n        do_facet ost1 lctl set_param fail_loc=0x316\n        # Don't crash kernel\n        cat $DIR2/$tdir/$tfile > /dev/null 2>&1\n        lctl set_param fail_loc=0\n        do_facet ost1 lctl set_param fail_loc=0\n        # cleanup: reconnect the client back\n        df $DIR2\n}\nrun_test 31b \"voluntary OST cancel / blocking ast race==============\"\n\n# enable/disable lockless truncate feature, depending on the arg 0/1\nenable_lockless_truncate() {\n\tlctl set_param -n $OSC.*.lockless_truncate $1\n}\n\ntest_32a() { # bug 11270\n\tlocal save=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tlocal stripe_size=$(do_facet $SINGLEMDS \\\n\t\t\"$LCTL get_param -n lod.$(facet_svc $SINGLEMDS)*.stripesize\")\n\n\tsave_lustre_params client \"$OSC.*.lockless_truncate\" > $save\n\t# restore lockless_truncate default values on exit\n\tstack_trap \"restore_lustre_params < $save; rm -f $save\" EXIT\n\tcancel_lru_locks $OSC\n\tenable_lockless_truncate 1\n\trm -f $DIR1/$tfile\n\tlfs setstripe -c -1 $DIR1/$tfile\n\tdd if=/dev/zero of=$DIR1/$tfile count=$OSTCOUNT bs=$stripe_size > \\\n\t\t/dev/null 2>&1\n\tclear_stats $OSC.*.${OSC}_stats\n\n\tlog \"checking cached lockless truncate\"\n\t$TRUNCATE $DIR1/$tfile 8000000\n\t$CHECKSTAT -s 8000000 $DIR2/$tfile || error \"wrong file size\"\n\t[ $(calc_stats $OSC.*.${OSC}_stats lockless_truncate) -ne 0 ] ||\n\t\terror \"cached truncate isn't lockless\"\n\n\tlog \"checking not cached lockless truncate\"\n\t$TRUNCATE $DIR2/$tfile 5000000\n\t$CHECKSTAT -s 5000000 $DIR1/$tfile || error \"wrong file size\"\n\t[ $(calc_stats $OSC.*.${OSC}_stats lockless_truncate) -ne 0 ] ||\n\t\terror \"not cached truncate isn't lockless\"\n\n\tlog \"disabled lockless truncate\"\n\tenable_lockless_truncate 0\n\tclear_stats $OSC.*.${OSC}_stats\n\t$TRUNCATE $DIR2/$tfile 3000000\n\t$CHECKSTAT -s 3000000 $DIR1/$tfile || error \"wrong file size\"\n\t[ $(calc_stats $OSC.*.${OSC}_stats lockless_truncate) -eq 0 ] ||\n\t\terror \"lockless truncate disabling failed\"\n\trm -f $DIR1/$tfile\n}\nrun_test 32a \"lockless truncate\"\n\ntest_32b() { # bug 11270\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return\n\n\tlocal node\n\tlocal facets=$(get_facets OST)\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\n\tsave_lustre_params client \"osc.*.contention_seconds\" > $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.max_nolock_bytes\" >> $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.contended_locks\" >> $p\n\tsave_lustre_params $facets \\\n\t\t\"ldlm.namespaces.filter-*.contention_seconds\" >> $p\n\tclear_stats $OSC.*.${OSC}_stats\n\n\t# agressive lockless i/o settings\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\"lctl set_param -n ldlm.namespaces.*.max_nolock_bytes=2000000 \\\n\t\t\tldlm.namespaces.filter-*.contended_locks=0 \\\n\t\t\tldlm.namespaces.filter-*.contention_seconds=60\"\n\tlctl set_param -n $OSC.*.contention_seconds=60\n\tfor i in {1..5}; do\n\t\tdd if=/dev/zero of=$DIR1/$tfile bs=4k count=1 conv=notrunc > \\\n\t\t\t/dev/null 2>&1\n\t\tdd if=/dev/zero of=$DIR2/$tfile bs=4k count=1 conv=notrunc > \\\n\t\t\t/dev/null 2>&1\n\tdone\n\t[ $(calc_stats $OSC.*.${OSC}_stats lockless_write_bytes) -ne 0 ] ||\n\t\terror \"lockless i/o was not triggered\"\n\t# disable lockless i/o (it is disabled by default)\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\"lctl set_param -n ldlm.namespaces.filter-*.max_nolock_bytes=0 \\\n\t\t\tldlm.namespaces.filter-*.contended_locks=32 \\\n\t\t\tldlm.namespaces.filter-*.contention_seconds=0\"\n\t# set contention_seconds to 0 at client too, otherwise Lustre still\n\t# remembers lock contention\n\tlctl set_param -n $OSC.*.contention_seconds=0\n\tclear_stats $OSC.*.${OSC}_stats\n\tfor i in {1..1}; do\n\t\tdd if=/dev/zero of=$DIR1/$tfile bs=4k count=1 conv=notrunc > \\\n\t\t\t/dev/null 2>&1\n\t\tdd if=/dev/zero of=$DIR2/$tfile bs=4k count=1 conv=notrunc > \\\n\t\t\t/dev/null 2>&1\n\tdone\n\t[ $(calc_stats $OSC.*.${OSC}_stats lockless_write_bytes) -eq 0 ] ||\n\t\terror \"lockless i/o works when disabled\"\n\trm -f $DIR1/$tfile\n\trestore_lustre_params <$p\n\trm -f $p\n}\nrun_test 32b \"lockless i/o\"\n\nprint_jbd_stat () {\n    local dev\n    local mdts=$(get_facets MDS)\n    local varcvs\n    local mds\n\n    local stat=0\n    for mds in ${mdts//,/ }; do\n        varsvc=${mds}_svc\n        dev=$(basename $(do_facet $mds \"lctl get_param -n osd*.${!varsvc}.mntdev|\\\n\t\txargs readlink -f\" ))\n\tval=$(do_facet $mds \"cat /proc/fs/jbd*/${dev}{,:*,-*}/info 2>/dev/null |\n\t\thead -n1\")\n        val=${val%% *};\n        stat=$(( stat + val))\n    done\n    echo $stat\n}\n\n# commit on sharing tests\ntest_33a() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\n\t[ -z \"$CLIENTS\" ] && skip \"Need two or more clients, have $CLIENTS\"\n\t[ $CLIENTCOUNT -lt 2 ] &&\n\t\tskip \"Need two or more clients, have $CLIENTCOUNT\"\n\n\tlocal nfiles=${TEST33_NFILES:-10000}\n\tlocal param_file=$TMP/$tfile-params\n\tlocal COS\n\tlocal jbdold=\"N/A\"\n\tlocal jbdnew=\"N/A\"\n\tlocal jbd\n\n\tsave_lustre_params $(get_facets MDS) \\\n\t\t\"mdt.*.commit_on_sharing\" > $param_file\n\n\tfor COS in 0 1; do\n\t\tdo_facet $SINGLEMDS lctl set_param mdt.*.commit_on_sharing=$COS\n\t\tavgjbd=0\n\t\tavgtime=0\n\t\tfor i in 1 2 3; do\n\t\t\tdo_nodes $CLIENT1,$CLIENT2 \"mkdir -p $DIR1/$tdir-\\\\\\$(hostname)-$i\"\n\n\t\t[ \"$mds1_FSTYPE\" = ldiskfs ] && jbdold=$(print_jbd_stat)\n\t\techo \"=== START createmany old: $jbdold transaction\"\n\t\tlocal elapsed=$(do_and_time \"do_nodes $CLIENT1,$CLIENT2 createmany -o $DIR1/$tdir-\\\\\\$(hostname)-$i/f- -r$DIR2/$tdir-\\\\\\$(hostname)-$i/f- $nfiles > /dev/null 2>&1\")\n\t\t[ \"$mds1_FSTYPE\" = ldiskfs ] && jbdnew=$(print_jbd_stat)\n\t\t[ \"$mds1_FSTYPE\" = ldiskfs ] && jbd=$(( jbdnew - jbdold ))\n\t\techo \"=== END   createmany new: $jbdnew transaction :  $jbd transactions  nfiles $nfiles time $elapsed COS=$COS\"\n\t\t[ \"$mds1_FSTYPE\" = ldiskfs ] && avgjbd=$(( avgjbd + jbd ))\n\t\tavgtime=$(( avgtime + elapsed ))\n\t\tdone\n\teval cos${COS}_jbd=$((avgjbd / 3))\n\teval cos${COS}_time=$((avgtime / 3))\n\tdone\n\n\techo \"COS=0 transactions (avg): $cos0_jbd  time (avg): $cos0_time\"\n\techo \"COS=1 transactions (avg): $cos1_jbd  time (avg): $cos1_time\"\n\t[ \"$cos0_jbd\" != 0 ] &&\n\t\techo \"COS=1 vs COS=0 jbd:  $((((cos1_jbd/cos0_jbd - 1)) * 100 )) %\"\n\t[ \"$cos0_time\" != 0 ] &&\n\t\techo \"COS=1 vs COS=0 time: $((((cos1_time/cos0_time - 1)) * 100 )) %\"\n\n\trestore_lustre_params < $param_file\n\trm -f $param_file\n\treturn 0\n}\nrun_test 33a \"commit on sharing, cross crete/delete, 2 clients, benchmark\"\n\n# commit on sharing tests\ntest_33b() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\n\t[ -n \"$CLIENTS\" ] || { skip \"Need two or more clients\" && return 0; }\n\t[ $CLIENTCOUNT -ge 2 ] ||\n\t\t{ skip \"Need two or more clients, have $CLIENTCOUNT\" &&\n\t\t\t\t\t\t\t\treturn 0; }\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tlocal nfiles=${TEST33_NFILES:-10000}\n\tlocal param_file=$TMP/$tfile-params\n\n\tsave_lustre_params $(get_facets MDS) \\\n\t\t\"mdt.*.commit_on_sharing\" > $param_file\n\n\tlocal COS\n\tlocal jbdold\n\tlocal jbdnew\n\tlocal jbd\n\tlocal MDTIDX=1\n\n\tfor COS in 0 1; do\n\t\tdo_facet $SINGLEMDS lctl set_param mdt.*.commit_on_sharing=$COS\n\t\tavgjbd=0\n\t\tavgtime=0\n\t\tfor i in 1 2 3; do\n\t\t\tdo_node $CLIENT1 \"$LFS mkdir -i $MDTIDX \\\n\t\t\t\t\t  $DIR1/$tdir-\\\\\\$(hostname)-$i\"\n\n\t\t\tjbdold=$(print_jbd_stat)\n\t\t\techo \"=== START createmany old: $jbdold transaction\"\n\t\t\tlocal elapsed=$(do_and_time \"do_nodes $CLIENT1,$CLIENT2\\\n\t\t\t\tcreatemany -o $DIR1/$tdir-\\\\\\$(hostname)-$i/f- \\\n\t\t\t\t-r$DIR2/$tdir-\\\\\\$(hostname)-$i/f- $nfiles > \\\n\t\t\t\t\t\t\t\t/dev/null 2>&1\")\n\t\t\tjbdnew=$(print_jbd_stat)\n\t\t\tjbd=$(( jbdnew - jbdold ))\n\t\t\techo \"=== END   createmany new: $jbdnew transaction : \\\n\t\t\t$jbd transactions nfiles $nfiles time $elapsed COS=$COS\"\n\t\t\tavgjbd=$(( avgjbd + jbd ))\n\t\t\tavgtime=$(( avgtime + elapsed ))\n\t\tdone\n\t\teval cos${COS}_jbd=$((avgjbd / 3))\n\t\teval cos${COS}_time=$((avgtime / 3))\n\tdone\n\n\techo \"COS=0 transactions (avg): $cos0_jbd  time (avg): $cos0_time\"\n\techo \"COS=1 transactions (avg): $cos1_jbd  time (avg): $cos1_time\"\n\t[ \"$cos0_jbd\" != 0 ] &&\n\t    echo \"COS=1 vs COS=0 jbd: $(((cos1_jbd/cos0_jbd - 1) * 100)) %\"\n\t[ \"$cos0_time\" != 0 ] &&\n\t    echo \"COS=1 vs COS=0 time: $(((cos1_time/cos0_time - 1) * 100)) %\"\n\n\trestore_lustre_params < $param_file\n\trm -f $param_file\n\treturn 0\n}\nrun_test 33b \"COS: cross create/delete, 2 clients, benchmark under remote dir\"\n\ntest_33c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.63) ] &&\n\t\tskip \"DNE CoS not supported\"\n\n\t# LU-13522\n\tstop mds1\n\tstart mds1 $(mdsdevname 1) $MDS_MOUNT_OPTS || error \"start mds1 failed\"\n\n\tlocal sync_count\n\n\tmkdir $DIR/$tdir\n\tsync_all_data\n\tdo_facet mds1 \"lctl set_param -n mdt.*.sync_count=0\"\n\t# do twice in case transaction is committed before unlock, see LU-8200\n\tfor i in 1 2; do\n\t\t# remote dir is created on MDT1, which enqueued lock of $tdir on\n\t\t# MDT0\n\t\t$LFS mkdir -i 1 $DIR/$tdir/remote.$i\n\t\tmkdir $DIR/$tdir/local.$i\n\tdone\n\tsync_count=$(do_facet mds1 \"lctl get_param -n mdt.*MDT0000.sync_count\")\n\techo \"sync_count $sync_count\"\n\t[ $sync_count -eq 0 ] && error \"Sync-Lock-Cancel not triggered\"\n\n\tsync_all_data\n\tdo_facet mds1 \"lctl set_param -n mdt.*.sync_count=0\"\n\t$LFS mkdir -i 1 $DIR/$tdir/remote.3\n\t# during sleep remote mkdir should have been committed and canceled\n\t# remote lock spontaneously, which shouldn't trigger sync\n\tsleep 6\n\tmkdir $DIR/$tdir/local.3\n\tsync_count=$(do_facet mds1 \"lctl get_param -n mdt.*MDT0000.sync_count\")\n\techo \"sync_count $sync_count\"\n\t[ $sync_count -eq 0 ] || error \"Sync-Lock-Cancel triggered\"\n}\nrun_test 33c \"Cancel cross-MDT lock should trigger Sync-Lock-Cancel\"\n\n# arg1 is operations done before CoS, arg2 is the operation that triggers CoS\nop_trigger_cos() {\n\tlocal commit_nr\n\tlocal total=0\n\tlocal nodes=$(comma_list $(mdts_nodes))\n\n\tsync_all_data\n\n\t# trigger CoS twice in case transaction commit before unlock\n\tfor i in 1 2; do\n\t\tsh -c \"$1\"\n\t\tdo_nodes $nodes \"lctl set_param -n mdt.*.async_commit_count=0\"\n\t\tsh -c \"$2\"\n\t\tcommit_nr=$(do_nodes $nodes \\\n\t\t\t\"lctl get_param -n mdt.*.async_commit_count\" | calc_sum)\n\t\ttotal=$((total + commit_nr));\n\t\trm -rf $DIR/$tdir\n\t\tsync_all_data\n\tdone\n\n\techo \"CoS count $total\"\n\t[ $total -gt 0 ] || error \"$2 didn't trigger CoS\"\n}\n\ntest_33d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.63) ] &&\n\t\tskip \"DNE CoS not supported\"\n\n\t# remote directory create\n\top_trigger_cos \"mkdir $DIR/$tdir\" \"$LFS mkdir -i 1 $DIR/$tdir/subdir\"\n\t# remote directory unlink\n\top_trigger_cos \"$LFS mkdir -i 1 $DIR/$tdir\" \"rmdir $DIR/$tdir\"\n\t# striped directory create\n\top_trigger_cos \"mkdir $DIR/$tdir\" \"$LFS mkdir -c 2 $DIR/$tdir/subdir\"\n\t# striped directory setattr\n\top_trigger_cos \"$LFS mkdir -c 2 $DIR/$tdir; touch $DIR/$tdir\" \\\n\t\t\"chmod 713 $DIR/$tdir\"\n\t# striped directory unlink\n\top_trigger_cos \"$LFS mkdir -c 2 $DIR/$tdir; touch $DIR/$tdir\" \\\n\t\t\"rmdir $DIR/$tdir\"\n\t# cross-MDT link\n\top_trigger_cos \"$LFS mkdir -c 2 $DIR/$tdir; \\\n\t\t\t$LFS mkdir -i 0 $DIR/$tdir/d1; \\\n\t\t\t$LFS mkdir -i 1 $DIR/$tdir/d2; \\\n\t\t\ttouch $DIR/$tdir/d1/tgt\" \\\n\t\t\"ln $DIR/$tdir/d1/tgt $DIR/$tdir/d2/src\"\n\t# cross-MDT rename\n\top_trigger_cos \"$LFS mkdir -c 2 $DIR/$tdir; \\\n\t\t\t$LFS mkdir -i 0 $DIR/$tdir/d1; \\\n\t\t\t$LFS mkdir -i 1 $DIR/$tdir/d2; \\\n\t\t\ttouch $DIR/$tdir/d1/src\" \\\n\t\t\"mv $DIR/$tdir/d1/src $DIR/$tdir/d2/tgt\"\n\t# migrate\n\top_trigger_cos \"$LFS mkdir -i 0 $DIR/$tdir\" \\\n\t\t\"$LFS migrate -m 1 $DIR/$tdir\"\n\n\treturn 0\n}\nrun_test 33d \"DNE distributed operation should trigger COS\"\n\ntest_33e() {\n\t[ -n \"$CLIENTS\" ] || skip \"Need two or more clients\"\n\t[ $CLIENTCOUNT -ge 2 ] ||\n\t\tskip \"Need two or more clients, have $CLIENTCOUNT\"\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\"\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.7.63) ] &&\n\t\tskip \"DNE CoS not supported\"\n\n\tlocal client2=${CLIENT2:-$(hostname)}\n\n\tsync\n\n\tlocal nodes=$(comma_list $(mdts_nodes))\n\tdo_nodes $nodes \"lctl set_param -n mdt.*.async_commit_count=0\"\n\n\t$LFS mkdir -c 2 $DIR/$tdir\n\tmkdir $DIR/$tdir/subdir\n\techo abc > $DIR/$tdir/$tfile\n\tdo_node $client2 echo dfg >> $DIR/$tdir/$tfile\n\tdo_node $client2 touch $DIR/$tdir/subdir\n\n\tlocal async_commit_count=$(do_nodes $nodes \\\n\t\t\"lctl get_param -n mdt.*.async_commit_count\" | calc_sum)\n\t[ $async_commit_count -gt 0 ] && error \"CoS triggerred\"\n\n\treturn 0\n}\nrun_test 33e \"DNE local operation shouldn't trigger COS\"\n\n# End commit on sharing tests\n\nget_ost_lock_timeouts() {\n    local nodes=${1:-$(comma_list $(osts_nodes))}\n\n    local locks=$(do_nodes $nodes \\\n        \"lctl get_param -n ldlm.namespaces.filter-*.lock_timeouts\" | calc_sum)\n\n    echo $locks\n}\n\ncleanup_34() {\n\tlocal i\n\ttrap 0\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tfor i in $(seq $OSTCOUNT); do\n\t\twait_osc_import_ready client ost$i\n\tdone\n}\n\ntest_34() { #16129\n\tremote_ost_nodsh && skip \"remote OST with nodsh\" && return\n        local OPER\n        local lock_in\n        local lock_out\n\ttrap cleanup_34 EXIT RETURN\n        for OPER in notimeout timeout ; do\n                rm $DIR1/$tfile 2>/dev/null\n                lock_in=$(get_ost_lock_timeouts)\n                if [ $OPER == \"timeout\" ] ; then\n                        for j in `seq $OSTCOUNT`; do\n                                #define OBD_FAIL_PTLRPC_HPREQ_TIMEOUT    0x511\n                                do_facet ost$j lctl set_param fail_loc=0x511\n                        done\n                        echo lock should expire\n                else\n                        for j in `seq $OSTCOUNT`; do\n                                #define OBD_FAIL_PTLRPC_HPREQ_NOTIMEOUT  0x512\n                                do_facet ost$j lctl set_param fail_loc=0x512\n                        done\n                        echo lock should not expire\n                fi\n                echo writing on client1\n                dd if=/dev/zero of=$DIR1/$tfile count=100 conv=notrunc > /dev/null 2>&1\n                sync &\n                echo reading on client2\n                dd of=/dev/null if=$DIR2/$tfile > /dev/null 2>&1\n                # wait for a lock timeout\n                sleep 4\n                lock_out=$(get_ost_lock_timeouts)\n                if [ $OPER == \"timeout\" ] ; then\n                        if [ $lock_in == $lock_out ]; then\n                                error \"no lock timeout happened\"\n                        else\n                                echo \"success\"\n                        fi\n                else\n                        if [ $lock_in != $lock_out ]; then\n                                error \"lock timeout happened\"\n                        else\n                                echo \"success\"\n                        fi\n                fi\n        done\n\tcleanup_34\n}\nrun_test 34 \"no lock timeout under IO\"\n\ntest_35() { # bug 17645\n\tlocal generation=[]\n\tlocal count=0\n\tgen=$(lctl get_param mdc.$FSNAME-MDT*-mdc-*.import | grep generation |\n\t      awk '/generation/{print $2}')\n\tfor g in $gen; do\n\t\tgeneration[count]=$g\n\t\tlet count=count+1\n\tdone\n\n\ttest_mkdir $MOUNT1/$tdir\n\tcancel_lru_locks mdc\n\n\t# Let's initiate -EINTR situation by setting fail_loc and take\n\t# write lock on same file from same client. This will not cause\n\t# bl_ast yet as lock is already in local cache.\n\t#define OBD_FAIL_LDLM_INTR_CP_AST        0x317\n\tdo_facet client \"lctl set_param fail_loc=0x80000317\"\n\tlocal timeout=$(do_facet $SINGLEMDS lctl get_param  -n timeout)\n\tlet timeout=timeout*3\n\tlocal nr=0\n\twhile test $nr -lt 10; do\n\t\tlog \"Race attempt $nr\"\n\t\tlocal blk1=$(lctl get_param -n ldlm.services.ldlm_cbd.stats |\n\t\t\t     awk '/ldlm_bl_callback/ { print $2 }')\n\t\ttest \"x$blk1\" = \"x\" && blk1=0\n\t\tcreatemany -o $MOUNT2/$tdir/a 4000 &\n\t\tpid1=$!\n\t\tsleep 1\n\n\t\t# Let's make conflict and bl_ast\n\t\tls -la $MOUNT1/$tdir > /dev/null &\n\t\tpid2=$!\n\n\t\tlog \"Wait for $pid1 $pid2 for $timeout sec...\"\n\t\tsleep $timeout\n\t\tkill -9 $pid1 $pid2 > /dev/null 2>&1\n\t\twait\n\t\tlocal blk2=$(lctl get_param -n ldlm.services.ldlm_cbd.stats |\n\t\t\t     awk '/ldlm_bl_callback/ { print $2 }')\n\t\ttest \"x$blk2\" = \"x\" && blk2=0\n\t\ttest $blk2 -gt $blk1 && break\n\t\trm -fr $MOUNT1/$tdir\n\t\tcancel_lru_locks mdc\n\t\tlet nr=nr+1\n\tdone\n\tdo_facet client \"lctl set_param fail_loc=0x0\"\n\tdf -h $MOUNT1 $MOUNT2\n\tcount=0\n\tgen=$(lctl get_param mdc.$FSNAME-MDT*-mdc-*.import | grep generation |\n\t\tawk '/generation/{print $2}')\n\tfor g in $gen; do\n\t    if ! test \"$g\" -eq \"${generation[count]}\"; then\n\t\tlist=$(lctl list_param mdc.$FSNAME-MDT*-mdc-*.import)\n\t\tlocal c=0\n\t\tfor imp in $list; do\n\t\t\tif [ $c = $count ]; then\n\t\t\t\tbreak\n\t\t\tfi\n\t\t\tc=c+1\n\t\tdone\n\t\timp=$(echo \"$imp\" | awk -F\".\" '{print $2}')\n\t\terror \"Eviction happened on import $imp\"\n            fi\n            let count=count+1\n        done\n}\nrun_test 35 \"-EINTR cp_ast vs. bl_ast race does not evict client\"\n\ntest_36() { #bug 16417\n\tlocal SIZE\n\tlocal SIZE_B\n\tlocal i\n\n\ttest_mkdir $DIR1/$tdir\n\t$LFS setstripe -c -1 $DIR1/$tdir\n\ti=0\n\tSIZE=50\n\tlet SIZE_B=SIZE*1024*1024\n\tsync; sleep 2; sync # wait for delete thread\n\twait_mds_ost_sync || error \"wait_mds_ost_sync failed\"\n\twait_destroy_complete || error \"wait_destroy_complete failed\"\n\n\twhile [ $i -le 10 ]; do\n\t\tlctl mark \"start test - cycle ($i)\"\n\t\tlocal before=$(lfs_df $MOUNT1 | awk '/^filesystem/{ print $4; exit }')\n\t\tdd if=/dev/zero of=$DIR1/$tdir/$tfile bs=1M count=$SIZE ||\n\t\t\terror \"dd $DIR1/$tdir/$tfile ${SIZE}MB failed\"\n\t\tsync          # sync data from client cache\n\t\tsync_all_data # sync data from server cache (delayed allocation)\n\t\tsleep 2\n\t\tlocal after_dd=$(lfs_df $MOUNT1 | awk '/^filesystem/{ print $4; exit }')\n\t\tmultiop_bg_pause $DIR2/$tdir/$tfile O_r${SIZE_B}c || return 3\n\t\tread_pid=$!\n\t\trm -f $DIR1/$tdir/$tfile\n\t\tkill -USR1 $read_pid\n\t\twait $read_pid\n\t\tsync; sleep 2; sync # Ensure new statfs\n\t\twait_delete_completed\n\t\tlocal after=$(lfs_df $MOUNT1 | awk '/^filesystem/{ print $4; exit }')\n\t\techo \"*** cycle($i) *** before($before) after_dd($after_dd)\" \\\n\t\t\t\"after($after)\"\n\t\t# this free space! not used\n\t\t(( $after_dd <= $after)) ||\n\t\t\terror \"space leaked after_dd:$after_dd > after:$after\"\n\t\tlet i=i+1\n\tdone\n}\nrun_test 36 \"handle ESTALE/open-unlink correctly\"\n\ntest_37() { # bug 18695\n\ttest_mkdir $DIR1/$tdir\n\tmultiop_bg_pause $DIR1/$tdir D_c || return 1\n\tMULTIPID=$!\n\t# create large directory (32kB seems enough from e2fsck, ~= 1000 files)\n\tcreatemany -m $DIR2/$tdir/f 10000\n\t# set mtime/atime backward\n\ttouch -t 198001010000 $DIR2/$tdir\n\tkill -USR1 $MULTIPID\n\tnr_files=`lfs find $DIR1/$tdir -type f | wc -l`\n\t[ $nr_files -eq 10000 ] || error \"$nr_files != 10000 truncated directory?\"\n\n}\nrun_test 37 \"check i_size is not updated for directory on close (bug 18695) ==============\"\n\n# this should be set to past\nTEST_39_MTIME=`date -d \"1 year ago\" +%s`\n\n# bug 11063\ntest_39a() {\n\tlocal client1=${CLIENT1:-`hostname`}\n\tlocal client2=${CLIENT2:-`hostname`}\n\n\tdo_node $client1 \"touch $DIR1/$tfile\"\n\n\tdo_node $client1 \"touch -m -d @$TEST_39_MTIME $DIR1/$tfile\"\n\tlocal mtime1=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\t[ \"$mtime1\" = $TEST_39_MTIME ] || \\\n\t\terror \"mtime is not set to past: $mtime1, should be $TEST_39_MTIME\"\n\n\tlocal d1=`do_node $client1 date +%s`\n\tdo_node $client1 'echo hello >> '$DIR1/$tfile\n\tlocal d2=`do_node $client1 date +%s`\n\n\tlocal mtime2=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\t[ \"$mtime2\" -ge \"$d1\" ] && [ \"$mtime2\" -le \"$d2\" ] || \\\n\t\terror \"mtime is not updated on write: $d1 <= $mtime2 <= $d2\"\n\n\tdo_node $client1 \"mv $DIR1/$tfile $DIR1/$tfile-1\"\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime3=`do_node $client2 \"stat -c %Y $DIR1/$tfile-1\"`\n\t\t[ \"$mtime2\" = \"$mtime3\" ] || \\\n\t\t\terror \"mtime ($mtime2) changed (to $mtime3) on rename\"\n\n\t\tcancel_lru_locks osc\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39a \"test from 11063 ==================================\"\n\ntest_39b() {\n\tlocal client1=${CLIENT1:-`hostname`}\n\tlocal client2=${CLIENT2:-`hostname`}\n\n\ttouch $DIR1/$tfile\n\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\tlocal mtime2=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\n\tsleep 1\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime3=`stat -c %Y $DIR1/$tfile`\n\t\tlocal mtime4=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\n\t\t[ \"$mtime3\" = \"$mtime4\" ] || \\\n\t\t\terror \"different mtime on clients: $mtime3, $mtime4\"\n\t\t[ \"$mtime3\" = $TEST_39_MTIME ] || \\\n\t\t\terror \"lost mtime: $mtime3, should be $TEST_39_MTIME\"\n\n\t\tcancel_lru_locks osc\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39b \"11063 problem 1 ==================================\"\n\ntest_39c() {\n\tlocal client1=${CLIENT1:-`hostname`}\n\tlocal client2=${CLIENT2:-`hostname`}\n\n\techo hello > $DIR1/$tfile\n\n\tlocal mtime1=`stat -c %Y $DIR1/$tfile`\n\tlocal mtime2=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\t[ \"$mtime1\" = \"$mtime2\" ] || \\\n\t\terror \"create: different mtime on clients: $mtime1, $mtime2\"\n\n\tsleep 1\n\t$TRUNCATE $DIR1/$tfile 1\n\n\tfor (( i=0; i < 2; i++ )) ; do\n\t\tlocal mtime3=`stat -c %Y $DIR1/$tfile`\n\t\tlocal mtime4=`do_node $client2 \"stat -c %Y $DIR1/$tfile\"`\n\n\t\t[ \"$mtime3\" = \"$mtime4\" ] || \\\n\t\t\terror \"different mtime on clients: $mtime3, $mtime4\"\n\t\t[ \"$mtime3\" -gt $mtime2 ] || \\\n\t\t\terror \"truncate did not update mtime: $mtime2, $mtime3\"\n\n\t\tcancel_lru_locks osc\n\t\tif [ $i = 0 ] ; then echo \"repeat after cancel_lru_locks\"; fi\n\tdone\n}\nrun_test 39c \"check truncate mtime update ======================\"\n\ntest_39d() { # LU-7310\n\ttouch $DIR1/$tfile\n\ttouch -m -d @$TEST_39_MTIME $DIR1/$tfile\n\n\tlocal mtime1=$(stat -c %Y $DIR2/$tfile)\n\t[ \"$mtime1\" = $TEST_39_MTIME ] ||\n\t\terror \"mtime: $mtime1, should be $TEST_39_MTIME\"\n\n\t# force sync write\n\t# define OBD_FAIL_OSC_NO_GRANT 0x411\n\t$LCTL set_param fail_loc=0x411\n\n\tlocal d1=$(date +%s)\n\techo hello >> $DIR1/$tfile\n\tlocal d2=$(date +%s)\n\n\t$LCTL set_param fail_loc=0\n\n\tcancel_lru_locks $OSC\n\n\tlocal mtime2=$(stat -c %Y $DIR2/$tfile)\n\t[ \"$mtime2\" -ge \"$d1\" ] && [ \"$mtime2\" -le \"$d2\" ] ||\n\t\terror \"mtime is not updated on write: $d1 <= $mtime2 <= $d2\"\n}\nrun_test 39d \"sync write should update mtime\"\n\npdo_sched() {\n\t# how long 40-47 take with specific delay\n\t# sleep 0.1 # 78s\n\t# sleep 0.2 # 103s\n\t# sleep 0.3 # 124s\n\tsleep 0.5 # 164s\n}\n\n# for pdo testing, we must cancel MDT-MDT locks as well as client locks to\n# avoid unexpected delays due to previous tests\npdo_lru_clear() {\n\tcancel_lru_locks mdc\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param -n ldlm.namespaces.*mdt*.lru_size=clear\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL get_param ldlm.namespaces.*mdt*.lock_unused_count \\\n\t\t\tldlm.namespaces.*mdt*.lock_count | grep -v '=0'\n}\n\n# check that pid exists hence second operation wasn't blocked by first one\n# if it is so then there is no conflict, return 0\n# else second operation is conflicting with first one, return 1\ncheck_pdo_conflict() {\n\tlocal pid=$1\n\tlocal conflict=0\n\tpdo_sched # to ensure OP1 is finished on client if OP2 is blocked by OP1\n\tif [[ `ps --pid $pid | wc -l` == 1 ]]; then\n\t\tconflict=1\n\t\techo \"Conflict\"\n\telse\n\t\techo \"No conflict\"\n\tfi\n\treturn $conflict\n}\n\n# pdirop tests\n# test 40: check non-blocking operations\ntest_40a() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\ttouch $DIR2\n\tmkdir $DIR1/$tfile &\n\tPID1=$!; pdo_sched\n\ttouch $DIR2/$tfile-2\n\tcheck_pdo_conflict $PID1 || error \"create is blocked\"\n\tmkdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"mkdir is blocked\"\n\tlink $DIR2/$tfile-2 $DIR2/$tfile-4\n\tcheck_pdo_conflict $PID1 || error \"link is blocked\"\n\tmv $DIR2/$tfile-2 $DIR2/$tfile-5\n\tcheck_pdo_conflict $PID1 || error \"rename is blocked\"\n\tstat $DIR2/$tfile-3 $DIR2/$tfile-4 > /dev/null\n\tcheck_pdo_conflict $PID1 || error \"getattr is blocked\"\n\trm $DIR2/$tfile-4 $DIR2/$tfile-5\n\trmdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"unlink is blocked\"\n\n\t#  all operations above shouldn't wait the first one\n\tcheck_pdo_conflict $PID1 || error \"parallel operation is blocked\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\twait $PID1\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 40a \"pdirops: create vs others ==============\"\n\ntest_40b() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\ttouch $DIR1/$tfile &\n\tPID1=$!; pdo_sched\n\t# open|create\n\ttouch $DIR2/$tfile-2\n\tcheck_pdo_conflict $PID1 || error \"create is blocked\"\n\tmkdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"mkdir is blocked\"\n\tlink $DIR2/$tfile-2 $DIR2/$tfile-4\n\tcheck_pdo_conflict $PID1 || error \"link is blocked\"\n\tmv $DIR2/$tfile-2 $DIR2/$tfile-5\n\tcheck_pdo_conflict $PID1 || error \"rename is blocked\"\n\tstat $DIR2/$tfile-3 $DIR2/$tfile-4 > /dev/null\n\tcheck_pdo_conflict $PID1 || error \"getattr is blocked\"\n\trm $DIR2/$tfile-4 $DIR2/$tfile-5\n\trmdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"unlink is blocked\"\n\t# all operations above shouldn't wait the first one\n\n        check_pdo_conflict $PID1 || error \"parallel operation is blocked\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\twait $PID1\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 40b \"pdirops: open|create and others ==============\"\n\ntest_40c() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile $DIR1/$tfile-0 &\n\tPID1=$!; pdo_sched\n\t# open|create\n\ttouch $DIR2/$tfile-2\n\tcheck_pdo_conflict $PID1 || error \"create is blocked\"\n\tmkdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"mkdir is blocked\"\n\tlink $DIR2/$tfile-2 $DIR2/$tfile-4\n\tcheck_pdo_conflict $PID1 || error \"link is blocked\"\n\tmv $DIR2/$tfile-2 $DIR2/$tfile-5\n\tcheck_pdo_conflict $PID1 || error \"rename is blocked\"\n\tstat $DIR2/$tfile-3 $DIR2/$tfile-4 > /dev/null\n\tcheck_pdo_conflict $PID1 || error \"getattr is blocked\"\n\trm $DIR2/$tfile-4 $DIR2/$tfile-5\n\trmdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"unlink is blocked\"\n\n        # all operations above shouldn't wait the first one\n\tcheck_pdo_conflict $PID1 || error \"parallel operation is blocked\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\twait $PID1\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 40c \"pdirops: link and others ==============\"\n\ntest_40d() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$!; pdo_sched\n\t# open|create\n\ttouch $DIR2/$tfile-2\n\tcheck_pdo_conflict $PID1 || error \"create is blocked\"\n\tmkdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"mkdir is blocked\"\n\tlink $DIR2/$tfile-2 $DIR2/$tfile-4\n\tcheck_pdo_conflict $PID1 || error \"link is blocked\"\n\tmv $DIR2/$tfile-2 $DIR2/$tfile-5\n\tcheck_pdo_conflict $PID1 || error \"rename is blocked\"\n\tstat $DIR2/$tfile-3 $DIR2/$tfile-4 > /dev/null\n\tcheck_pdo_conflict $PID1 || error \"getattr is blocked\"\n\trm $DIR2/$tfile-4 $DIR2/$tfile-5\n\trmdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"unlink is blocked\"\n\n\t# all operations above shouldn't wait the first one\n\tcheck_pdo_conflict $PID1 || error \"parallel operation is blocked\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\twait $PID1\n\treturn 0\n}\nrun_test 40d \"pdirops: unlink and others ==============\"\n\ntest_40e() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-0 &\n\tPID1=$!; pdo_sched\n\t# open|create\n\ttouch $DIR2/$tfile-2\n\tcheck_pdo_conflict $PID1 || error \"create is blocked\"\n\tmkdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"mkdir is blocked\"\n\tlink $DIR2/$tfile-2 $DIR2/$tfile-4\n\tcheck_pdo_conflict $PID1 || error \"link is blocked\"\n\tstat $DIR2/$tfile-3 $DIR2/$tfile-4 > /dev/null\n\tcheck_pdo_conflict $PID1 || error \"getattr is blocked\"\n\trm $DIR2/$tfile-4 $DIR2/$tfile-2\n\trmdir $DIR2/$tfile-3\n\tcheck_pdo_conflict $PID1 || error \"unlink is blocked\"\n\n       # all operations above shouldn't wait the first one\n\tcheck_pdo_conflict $PID1 || error \"parallel operation is blocked\"\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\twait $PID1\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 40e \"pdirops: rename and others ==============\"\n\n# test 41: create blocking operations\ntest_41a() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tmkdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; echo \"mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41a \"pdirops: create vs mkdir ==============\"\n\ntest_41b() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"create must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41b \"pdirops: create vs create ==============\"\n\ntest_41c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"link must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41c \"pdirops: create vs link ==============\"\n\ntest_41d() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\trm $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"unlink must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41d \"pdirops: create vs unlink ==============\"\n\ntest_41e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41e \"pdirops: create and rename (tgt) ==============\"\n\ntest_41f() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-2 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41f \"pdirops: create and rename (src) ==============\"\n\ntest_41g() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"stat must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41g \"pdirops: create vs getattr ==============\"\n\ntest_41h() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$MULTIOP $DIR1/$tfile oO_CREAT:O_RDWR:c &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 41h \"pdirops: create vs readdir ==============\"\n\n# test 42: unlink and blocking operations\ntest_42a() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmkdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42a \"pdirops: mkdir vs mkdir ==============\"\n\ntest_42b() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"create must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42b \"pdirops: mkdir vs create ==============\"\n\ntest_42c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"link must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42c \"pdirops: mkdir vs link ==============\"\n\ntest_42d() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\trmdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"unlink must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42d \"pdirops: mkdir vs unlink ==============\"\n\ntest_42e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv -T $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"rename must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42e \"pdirops: mkdir and rename (tgt) ==============\"\n\ntest_42f() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-2 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42f \"pdirops: mkdir and rename (src) ==============\"\n\ntest_42g() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"stat must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42g \"pdirops: mkdir vs getattr ==============\"\n\ntest_42h() {\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmkdir $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 42h \"pdirops: mkdir vs readdir ==============\"\n\n# test 43: rmdir,mkdir won't return -EEXIST\ntest_43a() {\n\tfor i in {1..1000}; do\n\t\tmkdir $DIR1/$tdir || error \"mkdir $tdir failed\"\n\t\trmdir $DIR2/$tdir || error \"rmdir $tdir failed\"\n\tdone\n\treturn 0\n}\nrun_test 43a \"rmdir,mkdir doesn't return -EEXIST ==============\"\n\ntest_43b() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"create must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43b \"pdirops: unlink vs create ==============\"\n\ntest_43c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"link must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43c \"pdirops: unlink vs link ==============\"\n\ntest_43d() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\trm $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"unlink must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43d \"pdirops: unlink vs unlink ==============\"\n\ntest_43e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv -u $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43e \"pdirops: unlink and rename (tgt) ==============\"\n\ntest_43f() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-2 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"rename must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43f \"pdirops: unlink and rename (src) ==============\"\n\ntest_43g() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"stat must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43g \"pdirops: unlink vs getattr ==============\"\n\ntest_43h() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43h \"pdirops: unlink vs readdir ==============\"\n\ntest_43i() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\trm $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$LFS mkdir -i 1 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 &&\n\t\t{ wait $PID1; error \"remote mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"remote mkdir must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 43i \"pdirops: unlink vs remote mkdir\"\n\ntest_43j() {\n\t[[ $MDS1_VERSION -lt $(version_code 2.13.52) ]] &&\n\t\tskip \"Need MDS version newer than 2.13.52\"\n\n\tfor i in {1..100}; do\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_CREATE_RACE         0x167\n\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\"lctl set_param -n fail_loc=0x80000167 2>/dev/null ||\n\t\t\t\ttrue\"\n\t\tOK=0\n\t\tmkdir $DIR1/$tdir &\n\t\tPID1=$!\n\t\tmkdir $DIR2/$tdir && ((OK++))\n\t\twait $PID1 && ((OK++))\n\t\t(( OK == 1 )) || error \"exactly one mkdir should succeed\"\n\n\t\trmdir $DIR1/$tdir || error \"rmdir failed\"\n\tdone\n\treturn 0\n}\nrun_test 43j \"racy mkdir return EEXIST ==============\"\n\n# test 44: rename tgt and blocking operations\ntest_44a() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2   0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmkdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; date;error \"mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"mkdir must fail\"\n\tdate\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44a \"pdirops: rename tgt vs mkdir ==============\"\n\ntest_44b() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"create must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44b \"pdirops: rename tgt vs create ==============\"\n\ntest_44c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-3 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"link must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44c \"pdirops: rename tgt vs link ==============\"\n\ntest_44d() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\trm $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"unlink must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44d \"pdirops: rename tgt vs unlink ==============\"\n\ntest_44e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n\ttouch $DIR1/$tfile-2\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile-3 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44e \"pdirops: rename tgt and rename (tgt) ==============\"\n\ntest_44f() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-3 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44f \"pdirops: rename tgt and rename (src) ==============\"\n\ntest_44g() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"stat must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44g \"pdirops: rename tgt vs getattr ==============\"\n\ntest_44h() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2    0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44h \"pdirops: rename tgt vs readdir ==============\"\n\n# test 44: rename tgt and blocking operations\ntest_44i() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK2   0x146\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000146 2>/dev/null || true\"\n\tmv $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$LFS mkdir -i 1 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\terror \"remote mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"remote mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 44i \"pdirops: rename tgt vs remote mkdir\"\n\n# test 45: rename,mkdir doesn't fail with -EEXIST\ntest_45a() {\n\tfor i in {1..1000}; do\n\t\tmkdir $DIR1/$tdir || error \"mkdir $tdir failed\"\n\t\tmrename $DIR2/$tdir $DIR2/$tdir.$i > /dev/null ||\n\t\t\terror \"mrename to $tdir.$i failed\"\n\tdone\n\trm -rf $DIR/$tdir*\n\treturn 0\n}\nrun_test 45a \"rename,mkdir doesn't return -EEXIST ==============\"\n\ntest_45b() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"create must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45b \"pdirops: rename src vs create ==============\"\n\ntest_45c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-3 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"link must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45c \"pdirops: rename src vs link ==============\"\n\ntest_45d() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\trm $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"unlink must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45d \"pdirops: rename src vs unlink ==============\"\n\ntest_45e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile-3 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45e \"pdirops: rename src and rename (tgt) ==============\"\n\ntest_45f() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-3 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"rename must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45f \"pdirops: rename src and rename (src) ==============\"\n\ntest_45g() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"stat must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45g \"pdirops: rename src vs getattr ==============\"\n\ntest_45h() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45h \"pdirops: unlink vs readdir ==============\"\n\ntest_45i() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tmv $DIR1/$tfile $DIR1/$tfile-2 &\n\tPID1=$! ; pdo_sched\n\t$LFS mkdir -i 1 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\terror \"create remote dir isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"create remote dir must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 45i \"pdirops: rename src vs remote mkdir\"\n\n# test 46: link and blocking operations\ntest_46a() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmkdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46a \"pdirops: link vs mkdir ==============\"\n\ntest_46b() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$MULTIOP $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"create must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46b \"pdirops: link vs create ==============\"\n\ntest_46c() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"link must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46c \"pdirops: link vs link ==============\"\n\ntest_46d() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\trm $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"unlink must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46d \"pdirops: link vs unlink ==============\"\n\ntest_46e() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile-3 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46e \"pdirops: link and rename (tgt) ==============\"\n\ntest_46f() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n\ttouch $DIR1/$tfile-3\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-3 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46f \"pdirops: link and rename (src) ==============\"\n\ntest_46g() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"stat must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46g \"pdirops: link vs getattr ==============\"\n\ntest_46h() {\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tls -lia $DIR2/ > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"readdir isn't blocked\"; }\n\twait $PID2\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46h \"pdirops: link vs readdir ==============\"\n\ntest_46i() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\tlink $DIR1/$tfile-2 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\t$LFS mkdir -i 1 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\terror \"remote mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"remote mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 46i \"pdirops: link vs remote mkdir\"\n\n# test 47: remote mkdir and blocking operations\ntest_47a() {\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmkdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"mkdir isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"mkdir must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47a \"pdirops: remote mkdir vs mkdir\"\n\ntest_47b() {\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tsleep 1 # please do not remove this sleep, see LU-10754\n\tmultiop $DIR2/$tfile oO_CREAT:O_EXCL:c &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\t\terror \"create isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"create must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47b \"pdirops: remote mkdir vs create\"\n\ntest_47c() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tlink $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1; error \"link isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"link must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47c \"pdirops: remote mkdir vs link\"\n\ntest_47d() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\trmdir $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\t\terror \"unlink isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rmdir must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47d \"pdirops: remote mkdir vs unlink\"\n\ntest_47e() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n\ttouch $DIR1/$tfile-2\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv -T $DIR2/$tfile-2 $DIR2/$tfile &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\t\terror \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -ne 0 ] || error \"rename must fail\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47e \"pdirops: remote mkdir and rename (tgt)\"\n\ntest_47f() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tmv $DIR2/$tfile $DIR2/$tfile-2 &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\t\terror \"rename isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"rename must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47f \"pdirops: remote mkdir and rename (src)\"\n\ntest_47g() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tsync\n\tsync_all_data\n\tpdo_lru_clear\n#define OBD_FAIL_ONCE|OBD_FAIL_MDS_PDO_LOCK    0x145\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0x80000145 2>/dev/null || true\"\n\t$LFS mkdir -i 1 $DIR1/$tfile &\n\tPID1=$! ; pdo_sched\n\tstat $DIR2/$tfile > /dev/null &\n\tPID2=$! ; pdo_sched\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\"lctl set_param -n fail_loc=0 2>/dev/null || true\"\n\tcheck_pdo_conflict $PID1 && { wait $PID1;\n\t\t\t\t\terror \"getattr isn't blocked\"; }\n\twait $PID2 ; [ $? -eq 0 ] || error \"stat must succeed\"\n\trm -rf $DIR/$tfile*\n\treturn 0\n}\nrun_test 47g \"pdirops: remote mkdir vs getattr\"\n\ntest_50() {\n        trunc_size=4096\n        dd if=/dev/zero of=$DIR1/$tfile bs=1K count=10\n#define OBD_FAIL_OSC_CP_ENQ_RACE         0x410\n        do_facet client \"lctl set_param fail_loc=0x410\"\n        $TRUNCATE $DIR2/$tfile $trunc_size\n        do_facet client \"lctl set_param fail_loc=0x0\"\n        sleep 3\n        size=`stat -c %s $DIR2/$tfile`\n        [ $size -eq $trunc_size ] || error \"wrong size\"\n}\nrun_test 50 \"osc lvb attrs: enqueue vs. CP AST ==============\"\n\ntest_51a() {\n\tlocal filesize\n\tlocal origfile=/etc/hosts\n\n\tfilesize=$(stat -c %s $origfile)\n\n\t# create an empty file\n\t$MCREATE $DIR1/$tfile || error \"can't create $DIR1/$tfile\"\n\t# cache layout lock on both mount point\n\tstat $DIR1/$tfile > /dev/null || error \"stat $DIR1/$tfile failed\"\n\tstat $DIR2/$tfile > /dev/null || error \"stat $DIR2/$tfile failed\"\n\n\t# open and sleep 2 seconds then read\n\t$MULTIOP $DIR2/$tfile o_2r${filesize}c &\n\tlocal pid=$!\n\tsleep 1\n\n\t# create the layout of testing file\n\tdd if=$origfile of=$DIR1/$tfile conv=notrunc > /dev/null ||\n\t\terror \"dd $DIR1/$tfile failed\"\n\n\t# MULTIOP proc should be able to read enough bytes and exit\n\tfor ((i = 0; i < 6; i++)); do\n\t\tsleep 1\n\t\tkill -0 $pid || break\n\tdone\n\tkill -0 $pid 2> /dev/null && error \"multiop is still there\"\n\tcmp $origfile $DIR2/$tfile || error \"$origfile and $DIR2/$tfile differs\"\n\n\trm -f $DIR1/$tfile\n}\nrun_test 51a \"layout lock: refresh layout should work\"\n\ntest_51b() {\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.3.59) ]] ||\n\t\tskip \"Need MDS version at least 2.3.59\"\n\n\tlocal tmpfile=`mktemp`\n\n\t$LFS setstripe -E 1M -c 1 -E -1 --extension-size 64M $DIR1/$tfile ||\n\t\terror \"Create $DIR1/$tfile failed\"\n\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1k count=1 conv=notrunc ||\n\t\terror \"dd $DIR1/$tfile failed\"\n\n\t# delay glimpse so that layout has changed when glimpse finish\n#define OBD_FAIL_GLIMPSE_DELAY 0x1404\n\t$LCTL set_param fail_loc=0x1404 fail_val=4\n\tstat -c %s $DIR2/$tfile |tee $tmpfile &\n\tlocal pid=$!\n\tsleep 0.2\n\n\t# extend layout of testing file\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1M count=1 seek=2 conv=notrunc ||\n\t\terror \"dd $DIR1/$tfile failed\"\n\n\twait $pid\n\tlocal fsize=$(cat $tmpfile)\n\n\t[ x$fsize = x3145728 ] || error \"file size is $fsize, should be 3145728\"\n\n\trm -f $DIR1/$tfile $tmpfile\n}\nrun_test 51b \"layout lock: glimpse should be able to restart if layout changed\"\n\ntest_51c() {\n\t[ $OSTCOUNT -ge 2 ] || { skip \"needs >= 2 osts\"; return; }\n\n\t# set default layout to have 1 stripe\n\tmkdir $DIR1/$tdir\n\t$LFS setstripe -c 1 $DIR1/$tdir\n\n\t# create a file with empty layout\n\t$MCREATE $DIR1/$tdir/$tfile ||\n\t\terror \"$MCREATE $DIR1/$tdir/$tfile failed\"\n\n#define OBD_FAIL_MDS_LL_BLOCK 0x172\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x172\n\n\t# change the layout of testing file\n\techo \"Setting layout to have $OSTCOUNT stripes ...\"\n\t$LFS setstripe -c $OSTCOUNT $DIR1/$tdir/$tfile &\n\tpid=$!\n\tsleep 1\n\n\t# write something to the file, it should be blocked on fetching layout\n\tdd if=/dev/zero of=$DIR2/$tdir/$tfile bs=1k count=1 conv=notrunc\n\tlocal stripe_count=$($LFS getstripe -c $DIR2/$tdir/$tfile)\n\twait $pid\n\n\t# lod_qos.c::min_stripe_count() allows setstripe with a default stripe\n\t# count to succeed with only 3/4 of the number of stripes (rounded up),\n\t# so creating striped files does not fail if an OST is offline or full\n\t[ $stripe_count -ge $((OSTCOUNT - $OSTCOUNT / 4)) ] ||\n\t\terror \"bad layout: getstripe -c $stripe_count < $OSTCOUNT * 3/4\"\n\n\trm -fr $DIR1/$tdir\n}\nrun_test 51c \"layout lock: IT_LAYOUT blocked and correct layout can be returned\"\n\ntest_51d() {\n\tdd if=/dev/zero of=/$DIR1/$tfile bs=1M count=1\n\tcancel_lru_locks mdc\n\n\t# open should grant LAYOUT lock, mmap and read will install pages\n\t$MULTIOP $DIR1/$tfile oO_RDWR:SMR_Uc &\n\tlocal PID=$!\n\tsleep 1\n\n\t# rss before revoking\n\tlocal br=$(grep -A 10 $tfile /proc/$PID/smaps | awk '/^Rss/{print $2}')\n\techo \"Before revoking layout lock: $br KB mapped\"\n\n\t# cancel layout lock manually\n\tcancel_lru_locks mdc\n\n\t# rss after revoking\n\tlocal ar=$(grep -A 10 $tfile /proc/$PID/smaps | awk '/^Rss/{print $2}')\n\n\tkill -USR1 $PID\n\twait $PID || error \"wait PID $PID failed\"\n\n\t[ $ar -eq 0 ] || error \"rss before: $br, after $ar, some pages remained\"\n}\nrun_test 51d \"layout lock: losing layout lock should clean up memory map region\"\n\ntest_51e() {\n\tlocal pid\n\n\t$MULTIOP $DIR/$tfile oO_CREAT:O_RDWR:eW_E+eUc &\n\tpid=$!\n\tsleep 1\n\n\t$LFS getstripe $DIR2/$tfile\n\tkill -USR1 $pid\n\twait $pid || error \"multiop failed\"\n\n\t$MULTIOP $DIR/$tfile oO_RDONLY:eR_E+eUc &\n\tpid=$!\n\tsleep 1\n\n\t$LFS getstripe $DIR2/$tfile\n\tkill -USR1 $pid\n\twait $pid || error \"multiop failed\"\n}\nrun_test 51e \"lfs getstripe does not break leases, part 2\"\n\ntest_54_part1()\n{\n\techo \"==> rename vs getattr vs setxattr should not deadlock\"\n\tmkdir -p $DIR/d1/d2/d3 || error \"(1) mkdir failed\"\n\n\tdo_facet mds1 $LCTL set_param fail_loc=$1\n\n\tmv -T $DIR/d1/d2/d3 $DIR/d1/d3 &\n\tPID1=$!\n\tsleep 1\n\n\tstat $DIR/d1/d2 &\n\tPID2=$!\n\tsleep 1\n\n\tsetfattr -n user.attr1 -v value1 $DIR2/d1 || error \"(2) setfattr failed\"\n\twait $PID1 || error \"(3) mv failed\"\n\twait $PID2 || error \"(4) stat failed\"\n\techo\n\n\trm -rf $DIR/d1\n}\n\ntest_54_part2() {\n\techo \"==> rename vs getattr vs open vs getattr should not deadlock\"\n\tmkdir -p $DIR/d1/d2/d3 || error \"(1) mkdir failed\"\n\n\tdo_facet mds1 $LCTL set_param fail_loc=$1\n\n\tmv -T $DIR/d1/d2/d3 $DIR/d1/d3 &\n\tPID1=$!\n\tsleep 1\n\n\tstat $DIR/d1/d2 &\n\tPID2=$!\n\tsleep 1\n\n\t$MULTIOP $DIR2/d1/d2 Oc &\n\tPID3=$!\n\tsleep 1\n\n\tstat $DIR/d1 || error \"(2) stat failed\"\n\n\twait $PID1 || error \"(3) mv failed\"\n\twait $PID2 || error \"(4) stat failed\"\n\twait $PID3 && error \"(5) multiop failed\"\n\techo\n\trm -rf $DIR/d1\n}\n\ntest_54() {\n\tlocal p=\"$TMP/$TESTSUITE-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $p\n\tlctl set_param llite.*.xattr_cache 1 ||\n\t\t{ skip \"xattr cache is not supported\"; return 0; }\n\n#define OBD_FAIL_MDS_RENAME              0x153\n#define OBD_FAIL_MDS_RENAME2             0x154\n\ttest_54_part1 0x80000153 || error 10\n\ttest_54_part1 0x80000154 || error 11\n\ttest_54_part2 0x80000153 || error 12\n\ttest_54_part2 0x80000154 || error 13\n\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 54 \"rename locking\"\n\ntest_55a() {\n\tmkdir -p $DIR/d1/d2 $DIR/d3 || error \"(1) mkdir failed\"\n\n#define OBD_FAIL_MDS_RENAME4              0x156\n\tdo_facet mds1 $LCTL set_param fail_loc=0x80000156\n\n\tmv -T $DIR/d1/d2 $DIR/d3/d2 &\n\tPID1=$!\n\tsleep 1\n\n\trm -r $DIR2/d3\n\twait $PID1 && error \"(2) mv succeeded\"\n\n\trm -rf $DIR/d1\n}\nrun_test 55a \"rename vs unlink target dir\"\n\ntest_55b()\n{\n\tmkdir -p $DIR/d1/d2 $DIR/d3 || error \"(1) mkdir failed\"\n\n#define OBD_FAIL_MDS_RENAME4             0x156\n\tdo_facet mds1 $LCTL set_param fail_loc=0x80000156\n\n\tmv -T $DIR/d1/d2 $DIR/d3/d2 &\n\tPID1=$!\n\tsleep 1\n\n\trm -r $DIR2/d1\n\twait $PID1 && error \"(2) mv succeeded\"\n\n\trm -rf $DIR/d3\n}\nrun_test 55b \"rename vs unlink source dir\"\n\ntest_55c()\n{\n\tmkdir -p $DIR/d1/d2 $DIR/d3 || error \"(1) mkdir failed\"\n\n#define OBD_FAIL_MDS_RENAME4              0x156\n\tdo_facet mds1 $LCTL set_param fail_loc=0x156\n\n\tmv -T $DIR/d1/d2 $DIR/d3/d2 &\n\tPID1=$!\n\tsleep 1\n\n\t# while rename is sleeping, open and remove d3\n\t$MULTIOP $DIR2/d3 D_c &\n\tPID2=$!\n\tsleep 1\n\trm -rf $DIR2/d3\n\tsleep 5\n\n\t# while rename is sleeping 2nd time, close d3\n\tkill -USR1 $PID2\n\twait $PID2 || error \"(3) multiop failed\"\n\n\twait $PID1 && error \"(2) mv succeeded\"\n\n\trm -rf $DIR/d1\n}\nrun_test 55c \"rename vs unlink orphan target dir\"\n\ntest_55d()\n{\n\ttouch $DIR/f1\n\n#define OBD_FAIL_MDS_RENAME3              0x155\n\tdo_facet mds1 $LCTL set_param fail_loc=0x155\n\tmv $DIR/f1 $DIR/$tdir &\n\tPID1=$!\n\tsleep 2\n\n\t# while rename is sleeping, create $tdir, but as a directory\n\tmkdir -p $DIR2/$tdir || error \"(1) mkdir failed\"\n\n\t# link in reverse locking order\n\tln $DIR2/f1 $DIR2/$tdir/\n\n\twait $PID1 && error \"(2) mv succeeded\"\n\trm -rf $DIR/f1\n}\nrun_test 55d \"rename file vs link\"\n\ntest_60() {\n\t[ $MDS1_VERSION -lt $(version_code 2.3.0) ] &&\n\t\tskip \"MDS version must be >= 2.3.0\"\n\n\t# Create a file\n\ttest_mkdir $DIR1/$tdir\n\tfile1=$DIR1/$tdir/file\n\tfile2=$DIR2/$tdir/file\n\n\techo orig > $file2 || error \"Could not create $file2\"\n\tversion=$($LFS data_version $file1)\n\n\t# Append data\n\techo append >> $file2 || error \"Could not append to $file2\"\n\tversion2=$($LFS data_version $file1)\n\t[ \"$version\" != \"$version2\" ] ||\n\t    error \"append did not change data version: $version\"\n\n\t# Overwrite data\n\techo overwrite > $file2 || error \"Could not overwrite $file2\"\n\tversion3=$($LFS data_version $file1)\n\t[ \"$version2\" != \"$version3\" ] ||\n\t    error \"overwrite did not change data version: $version2\"\n\n\t# Truncate before EOF\n\t$TRUNCATE $file2 3 || error \"Could not truncate $file2\"\n\tversion4=$($LFS data_version $file1)\n\t[ \"$version3\" != \"$version4\" ] ||\n\t    error \"truncate did not change data version: $version3\"\n\n\t# Truncate after EOF\n\t$TRUNCATE $file2 123456 || error \"Could not truncate $file2\"\n\tversion5=$($LFS data_version $file1)\n\t[ \"$version4\" != \"$version5\" ] ||\n\t    error \"truncate did not change data version: $version4\"\n\n\t# Chmod do not change version\n\tchmod 400 $file2 || error \"Could not chmod 400 $file2\"\n\tversion6=$($LFS data_version $file1)\n\t[ \"$version5\" == \"$version6\" ] ||\n\t    error \"chmod should not change data version: $version5 != $version6\"\n\n\t# Chown do not change version\n\tchown $RUNAS_ID $file2 || error \"Could not chown $RUNAS_ID $file2\"\n\tversion7=$($LFS data_version $file1)\n\t[ \"$version5\" == \"$version7\" ] ||\n\t    error \"chown should not change data version: $version5 != $version7\"\n}\nrun_test 60 \"Verify data_version behaviour\"\n\ntest_70a() {\n\tlocal test_dir=$tdir/test_dir\n\n\tmkdir -p $DIR1/$tdir\n\tif [ $MDSCOUNT -ge 2 ]; then\n\t\tlocal MDTIDX=1\n\t\t$LFS mkdir -i $MDTIDX $DIR1/$test_dir ||\n\t\t\terror \"Create remote directory failed\"\n\telse\n\t\tmkdir -p $DIR1/$test_dir\n\tfi\n\tcd $DIR2/$test_dir || error \"cd directory failed\"\n\trm -rf $DIR1/$test_dir || error \"unlink directory failed\"\n\n\tcd $DIR2/$tdir || error \"exit directory\"\n}\nrun_test 70a \"cd directory && rm directory\"\n\ntest_70b() { # LU-2781\n\tlocal i\n\tmkdir -p $DIR1/$tdir\n\n\ttouch $DIR1/$tdir/file\n\tfor ((i = 0; i < 32; i++)); do\n\t    $LFS rm_entry $DIR1/$tdir/non_existent_dir &>/dev/null\n\tdone\n\trm $DIR1/$tdir/file || error \"cannot remove file after rm_entry\"\n\n\ttouch $DIR1/$tdir/file\n\t$LFS mkdir -i0 $DIR1/$tdir/test_dir\n\t$LFS rm_entry $DIR1/$tdir/test_dir &>/dev/null\n\trm -rf $DIR1/$tdir/test_dir ||\n\t\terror \"cannot remove directory after rm_entry\"\n\trm $DIR1/$tdir/file || error \"cannot remove file after rm_entry\"\n}\nrun_test 70b \"remove files after calling rm_entry\"\n\ntest_71a() {\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.1.6) ]] &&\n\t\tskip \"Need MDS version at least 2.1.6\"\n\n\t# Patch not applied to 2.2 and 2.3 branches\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.2.0) ]] &&\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.4.0) ]] &&\n\t\tskip \"Need MDS version earlier than 2.2.0 or at least 2.4.0\"\n\n\tcheckfiemap --test ||\n\t\tskip \"checkfiemap not runnable: $?\"\n\t# write data this way: hole - data - hole - data\n\tdd if=/dev/urandom of=$DIR1/$tfile bs=40K seek=1 count=1\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $DIR1/$tfile) + 1)))\" = \\\n\t\t\"zfs\" ] &&\n\t\tskip \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\" && return 0\n\tdd if=/dev/urandom of=$DIR1/$tfile bs=40K seek=3 count=1\n\tGET_STAT=\"lctl get_param -n ldlm.services.ldlm_cbd.stats\"\n\tstat $DIR2/$tfile\n\tlocal can1=$($GET_STAT | awk '/ldlm_bl_callback/ {print $2}')\n\techo $can1\n\tcheckfiemap $DIR2/$tfile 81920 ||\n\t\terror \"data is not flushed from client\"\n\tlocal can2=$($GET_STAT | awk '/ldlm_bl_callback/ {print $2}')\n\techo $can2\n\n\t# common case of \"create file, copy file\" on a single node\n\t# should not flush data from ost\n\tdd if=/dev/urandom of=$DIR1/$tfile bs=40K seek=1 count=1\n\tdd if=/dev/urandom of=$DIR1/$tfile bs=40K seek=3 count=1\n\tstat $DIR1/$tfile\n\tlocal can3=$($GET_STAT | awk '/ldlm_bl_callback/ {print $2}')\n\techo $can3\n\tcheckfiemap $DIR1/$tfile 81920 ||\n\terror 4\n\tlocal can4=$($GET_STAT | awk '/ldlm_bl_callback/ {print $2}')\n\techo $can2\n\t[ $can3 -eq $can4 ] || error $((can2-can1)) \"cancel RPC occured.\"\n}\nrun_test 71a \"correct file map just after write operation is finished\"\n\ntest_71b() {\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.1.6) ]] &&\n\t\tskip \"Need MDS version at least 2.1.6\"\n\n\t# Patch not applied to 2.2 and 2.3 branches\n\t[[ \"$MDS1_VERSION\" -ge $(version_code 2.2.0) ]] &&\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.4.0) ]] &&\n\t\tskip \"Need MDS version earlier than 2.2.0 or at least 2.4.0\"\n\t[[ $OSTCOUNT -ge 2 ]] || skip \"needs >= 2 OSTs\"\n\n\tcheckfiemap --test ||\n\t\tskip \"error $?: checkfiemap failed\"\n\n\tmkdir -p $DIR1/$tdir\n\n\t$LFS setstripe -c -1 $DIR1/$tdir || error \"setstripe failed\"\n\tdd if=/dev/urandom of=$DIR1/$tdir/$tfile bs=40K count=1\n\t[ \"$(facet_fstype ost$(($($LFS getstripe -i $DIR1/$tdir/$tfile) + 1)))\" = \\\n\t\t\"zfs\" ] &&\n\t\tskip \"ORI-366/LU-1941: FIEMAP unimplemented on ZFS\" && return 0\n\tcheckfiemap $DIR1/$tdir/$tfile 40960 || error \"checkfiemap failed\"\n}\nrun_test 71b \"check fiemap support for stripecount > 1\"\n\ntest_72() {\n\tlocal p=\"$TMP/sanityN-$TESTNAME.parameters\"\n\tlocal tlink1\n\tlocal tlink2\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $p\n\tlctl set_param llite.*.xattr_cache 1 ||\n\t\t{ skip \"xattr cache is not supported\"; return 0; }\n\n\ttouch $DIR1/$tfile\n\tsetfattr -n user.attr1 -v value1 $DIR1/$tfile ||\n\t\terror \"setfattr1 failed\"\n\tgetfattr -n user.attr1 $DIR2/$tfile | grep value1 ||\n\t\terror \"getfattr1 failed\"\n\tsetfattr -n user.attr1 -v value2 $DIR2/$tfile ||\n\t\terror \"setfattr2 failed\"\n\tgetfattr -n user.attr1 $DIR1/$tfile | grep value2 ||\n\t\terror \"getfattr2 failed\"\n\n\t# check that trusted.link is consistent\n\ttlink1=$(getfattr -n trusted.link $DIR1/$tfile | md5sum)\n\tln $DIR2/$tfile $DIR2/$tfile-2 || error \"failed to link\"\n\ttlink2=$(getfattr -n trusted.link $DIR1/$tfile | md5sum)\n\techo \"$tlink1 $tlink2\"\n\t[ \"$tlink1\" = \"$tlink2\" ] && error \"trusted.link should have changed!\"\n\n\trm -f $DIR2/$tfile\n\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 72 \"getxattr/setxattr cache should be consistent between nodes\"\n\ntest_73() {\n\tlocal p=\"$TMP/sanityN-$TESTNAME.parameters\"\n\tsave_lustre_params client \"llite.*.xattr_cache\" > $p\n\tlctl set_param llite.*.xattr_cache 1 ||\n\t\t{ skip \"xattr cache is not supported\"; return 0; }\n\n\ttouch $DIR1/$tfile\n\tsetfattr -n user.attr1 -v value1 $DIR1/$tfile ||\n\t\terror \"setfattr1 failed\"\n\tgetfattr -n user.attr1 $DIR2/$tfile || error \"getfattr1 failed\"\n\tgetfattr -n user.attr1 $DIR1/$tfile || error \"getfattr2 failed\"\n\tclear_stats llite.*.stats\n\t# PR lock should be cached by now on both clients\n\tgetfattr -n user.attr1 $DIR1/$tfile || error \"getfattr3 failed\"\n\t# 2 hits for getfattr(0)+getfattr(size)\n\t[ $(calc_stats llite.*.stats getxattr_hits) -eq 2 ] ||\n\t\terror \"not cached in $DIR1\"\n\tgetfattr -n user.attr1 $DIR2/$tfile || error \"getfattr4 failed\"\n\t# 4 hits for more getfattr(0)+getfattr(size)\n\t[ $(calc_stats llite.*.stats getxattr_hits) -eq 4 ] ||\n\t\terror \"not cached in $DIR2\"\n\trm -f $DIR2/$tfile\n\n\trestore_lustre_params < $p\n\trm -f $p\n}\nrun_test 73 \"getxattr should not cause xattr lock cancellation\"\n\ntest_74() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.4.93) ] &&\n\t\tskip \"Need MDS version at least 2.4.93\"\n\n\tdd if=/dev/zero of=$DIR1/$tfile-1 bs=1K count=1\n\tdd if=/dev/zero of=$DIR1/$tfile-2 bs=1K count=1\n\tflocks_test 4 $DIR1/$tfile-1 $DIR2/$tfile-2\n}\nrun_test 74 \"flock deadlock: different mounts ==============\"\n\n# LU-3889\ntest_75() {\n\t$LFS setstripe -c 2 -S 1m -i 0 $DIR1/$tfile\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1M count=2\n\tcancel_lru_locks osc\n\n\tdd of=$DIR1/$tfile if=/dev/zero bs=1M count=1 seek=1 conv=notrunc\n\tsync\n\n\t# define OBD_FAIL_LDLM_ENQUEUE_HANG 0x31d\n\t$LCTL set_param fail_loc=0x31d\n\tstat -c %s $DIR1/$tfile &\n\tlocal pid=$!\n\tsleep 1\n\tkill -9 $pid\n\n\t# For bad lock error handler we should ASSERT and got kernel panic here\n\tsleep 4\n\t$LCTL set_param fail_loc=0\n}\nrun_test 75 \"osc: upcall after unuse lock===================\"\n\ntest_76() { #LU-946\n\t[[ \"$MDS1_VERSION\" -lt $(version_code 2.5.53) ]] &&\n\t\tskip \"Need MDS version at least 2.5.53\"\n\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\"\n\tlocal fcount=$((MDSCOUNT * 256))\n\tdeclare -a fd_list\n\tdeclare -a fid_list\n\n\tif remote_mds; then\n\t\tnid=$($LCTL list_nids | sed  \"s/\\./\\\\\\./g\")\n\telse\n\t\tnid=\"0@lo\"\n\tfi\n\n\trm -rf $DIR/$tdir\n\ttest_mkdir $DIR/$tdir\n\n\t# drop all open locks and close any cached \"open\" files on the client\n\tcancel_lru_locks mdc\n\n\tlocal open_fids_cmd=\"$LCTL get_param -n mdt.*.exports.'$nid'.open_files\"\n\tlocal fid_list=($(do_nodes $(comma_list $(mdts_nodes)) $open_fids_cmd))\n\tlocal already=${#fid_list[@]}\n\tfor (( i = 0; i < $already; i++ )) ; do\n\t\tlog \"already open[$i]: $($LFS fid2path $DIR2 ${fid_list[i]})\"\n\tdone\n\n\techo -n \"opening files: \"\n\tulimit -n $((fcount + 50))\n\tfor ((i = 0; i < $fcount; i++)); do\n\t\ttouch $DIR/$tdir/f_$i\n\t\tlocal fd=$(free_fd ${fd_list[i]})\n\t\tlocal open_cmd=\"exec $fd<$DIR/$tdir/f_$i\"\n\t\teval $open_cmd\n\n\t\tfd_list[i]=$fd\n\n\t\t(( $i % 32 == 0 )) && echo -n \".\"\n\tdone\n\techo\n\n\tfid_list=($(do_nodes $(comma_list $(mdts_nodes)) $open_fids_cmd))\n\n\t# Possible errors in openfiles FID list.\n\t# 1. Missing FIDs. Check 1\n\t# 2. Extra FIDs. Check 1\n\t# 3. Duplicated FID. Check 2\n\t# 4. Invalid FIDs. Check 2\n\t# 5. Valid FID, points to some other file. Check 3\n\n\t# Check 1\n\t[ ${#fid_list[@]} -ne $((fcount + already)) ] &&\n\t\terror \"${#fid_list[@]} != $fcount (+$already old) open files\"\n\n\techo -n \"closing files: \"\n\tfor (( fd = 0, fid = 0; fd < $fcount; fd++, fid++ )) ; do\n\t\tlocal close_cmd=\"exec ${fd_list[fd]}<&-\"\n\t\teval $close_cmd\n\t\tfilename=$($LFS fid2path $DIR2 ${fid_list[fid]})\n\n\t\twhile [[ ! \"$filename\" =~ \"$DIR2/$tdir/f_\" ]]; do\n\t\t\techo \"skip old open file $filename\"\n\t\t\t((fid++))\n\t\t\tfilename=$($LFS fid2path $DIR2 ${fid_list[fid]})\n\t\tdone\n\n\t\t# Check 2\n\t\trm --interactive=no $filename\n\t\t[ $? -ne 0 ] &&\n\t\t\terror \"Nonexisting fid ${fid_list[fid]} listed.\"\n\t\t(( $fd % 32 == 0 )) && echo -n \".\"\n\tdone\n\techo\n\n\t# Check 3\n\tls_op=$(ls $DIR2/$tdir | wc -l)\n\t[ $ls_op -ne 0 ] &&\n\t\terror \"Some openfiles are missing in lproc output\"\n\n\trm -rf $DIR/$tdir\n}\nrun_test 76 \"Verify MDT open_files listing\"\n\nnrs_write_read() {\n\tlocal n=16\n\tlocal dir=$DIR/$tdir\n\tlocal myRUNAS=\"$1\"\n\n\tmkdir $dir || error \"mkdir $dir failed\"\n\t$LFS setstripe -c $OSTCOUNT $dir || error \"setstripe to $dir failed\"\n\tchmod 777 $dir\n\n\tdo_nodes $CLIENTS $myRUNAS \\\n\t\tdd if=/dev/zero of=\"$dir/nrs_r_\\$HOSTNAME\" bs=1M count=$n ||\n\t\terror \"dd at 0 on client failed (1)\"\n\n\tdo_nodes $CLIENTS $myRUNAS \\\n\t\t\"declare -a pids_w;\n\t\tfor ((i = 0; i < $n; i++)); do\n\t\t\tdd if=/dev/zero of=$dir/nrs_w_\\$HOSTNAME bs=1M \\\nseek=\\\\\\$i count=1 conv=notrunc &\n\t\t\tpids_w[\\\\\\$i]=\\\\\\$!;\n\t\tdone;\n\t\trc_w=0;\n\t\tfor ((i = 0; i < $n; i++)); do\n\t\t\twait \\\\\\${pids_w[\\\\\\$i]};\n\t\t\tnewrc=\\\\\\$?;\n\t\t\t[ \\\\\\$newrc -gt \\\\\\$rc_w ] && rc_w=\\\\\\$newrc;\n\t\tdone;\n\t\texit \\\\\\$rc_w\" &\n\tlocal pid_w=$!\n\tdo_nodes $CLIENTS sync;\n\tcancel_lru_locks osc\n\n\tdo_nodes $CLIENTS $myRUNAS \\\n\t\t\"declare -a pids_r;\n\t\tfor ((i = 0; i < $n; i++)); do\n\t\t\tdd if=$dir/nrs_r_\\$HOSTNAME bs=1M of=/dev/null \\\nseek=\\\\\\$i count=1 &\n\t\t\tpids_r[\\\\\\$i]=\\\\\\$!;\n\t\tdone;\n\t\trc_r=0;\n\t\tfor ((i = 0; i < $n; i++)); do\n\t\t\twait \\\\\\${pids_r[\\\\\\$i]};\n\t\t\tnewrc=\\\\\\$?;\n\t\t\t[ \\\\\\$newrc -gt \\\\\\$rc_r ] && rc_r=\\\\\\$newrc;\n\t\tdone;\n\t\texit \\\\\\$rc_r\" &\n\tlocal pid_r=$!\n\tcancel_lru_locks osc\n\n\twait $pid_w || error \"dd (write) failed (2)\"\n\twait $pid_r || error \"dd (read) failed (3)\"\n\trm -rvf $dir || error \"rm -rf $dir failed\"\n}\n\ntest_77a() { #LU-3266\n\tlocal rc\n\n\toss=$(comma_list $(osts_nodes))\n\tdo_nodes $oss lctl set_param ost.OSS.*.nrs_policies=\"fifo\" ||\n\t\trc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS exists\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to set fifo policy\"\n\tnrs_write_read\n\n\treturn 0\n}\nrun_test 77a \"check FIFO NRS policy\"\n\ntest_77b() { #LU-3266\n\tlocal rc\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdo_nodes $oss lctl set_param ost.OSS.*.nrs_policies=\"crrn\" \\\n\t\tost.OSS.*.nrs_crrn_quantum=1 || rc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS exists\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to set crrn_quantum to 1\"\n\n\techo \"policy: crr-n, crrn_quantum 1\"\n\tnrs_write_read\n\n\tdo_nodes $oss lctl set_param \\\n\t\tost.OSS.*.nrs_crrn_quantum=64 || rc=$?\n\t[[ $rc -ne 0 ]] && error \"failed to set crrn_quantum to 64\"\n\n\techo \"policy: crr-n, crrn_quantum 64\"\n\tnrs_write_read\n\n\t# cleanup\n\tdo_nodes $oss lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"fifo\" || rc=$?\n\t[[ $rc -ne 0 ]] && error \"failed to set fifo policy\"\n\treturn 0\n}\nrun_test 77b \"check CRR-N NRS policy\"\n\norr_trr() {\n\tlocal policy=$1\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=$policy \\\n\t\tost.OSS.*.nrs_\"$policy\"_quantum=1 \\\n\t\tost.OSS.*.nrs_\"$policy\"_offset_type=\"physical\" \\\n\t\tost.OSS.*.nrs_\"$policy\"_supported=\"reads\" || return $?\n\n\techo \"policy: $policy, ${policy}_quantum 1, ${policy}_offset_type \" \\\n\t\t\"physical, ${policy}_supported reads\"\n\tnrs_write_read\n\n\tdo_nodes $oss lctl set_param \\\n\t\tost.OSS.*.nrs_${policy}_supported=\"writes\" \\\n\t\tost.OSS.*.nrs_${policy}_quantum=64 || return $?\n\n\techo \"policy: $policy, ${policy}_quantum 64, ${policy}_offset_type \" \\\n\t\t\"physical, ${policy}_supported writes\"\n\tnrs_write_read\n\n\tdo_nodes $oss lctl set_param \\\n\t\tost.OSS.*.nrs_${policy}_supported=\"reads_and_writes\" \\\n\t\tost.OSS.*.nrs_${policy}_offset_type=\"logical\" || return $?\n\techo \"policy: $policy, ${policy}_quantum 64, ${policy}_offset_type \" \\\n\t\t\"logical, ${policy}_supported reads_and_writes\"\n\tnrs_write_read\n\n\t# cleanup\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\" ||\n\t\treturn $?\n\treturn 0\n}\n\ntest_77c() { #LU-3266\n\tlocal rc\n\torr_trr \"orr\" || rc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS exists\" && return\n\t[[ $rc -ne 0 ]] && error \"orr_trr failed rc:$rc\"\n\treturn 0\n}\nrun_test 77c \"check ORR NRS policy\"\n\ntest_77d() { #LU-3266\n\tlocal rc\n\torr_trr \"trr\" || rc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS exists\" && return\n\t[[ $rc -ne 0 ]] && error \"orr_trr failed rc:$rc\"\n\treturn 0\n}\nrun_test 77d \"check TRR nrs policy\"\n\ntbf_rule_operate()\n{\n\tlocal facet=$1\n\tshift 1\n\n\tdo_facet $facet lctl set_param \\\n\t\tost.OSS.ost_io.nrs_tbf_rule=\"$*\"\n\t[ $? -ne 0 ] &&\n\t\terror \"failed to run operate '$*' on TBF rules\"\n}\n\ncleanup_tbf_verify()\n{\n\tlocal rc=0\n\ttrap 0\n\techo \"cleanup_tbf $DIR/$tdir\"\n\trm -rf $DIR/$tdir\n\trc=$?\n\twait_delete_completed\n\treturn $rc\n}\n\ntbf_verify() {\n\tlocal dir=$DIR/$tdir\n\tlocal client1=${CLIENT1:-$(hostname)}\n\tlocal myRUNAS=\"$3\"\n\n\tlocal np=$(check_cpt_number ost1)\n\t[ $np -gt 0 ] || error \"CPU partitions should not be $np.\"\n\techo \"cpu_npartitions on ost1 is $np\"\n\n\tmkdir $dir || error \"mkdir $dir failed\"\n\t$LFS setstripe -c 1 -i 0 $dir || error \"setstripe to $dir failed\"\n\tchmod 777 $dir\n\n\ttrap cleanup_tbf_verify EXIT\n\techo \"Limited write rate: $1, read rate: $2\"\n\techo \"Verify the write rate is under TBF control\"\n\tlocal start=$SECONDS\n\tdo_node $client1 $myRUNAS dd if=/dev/zero of=$dir/tbf \\\n\t\tbs=1M count=100 oflag=direct 2>&1\n\tlocal runtime=$((SECONDS - start + 1))\n\tlocal rate=$(bc <<< \"scale=6; 100 / $runtime\")\n\techo \"Write runtime is $runtime s, speed is $rate IOPS\"\n\n\t# verify the write rate does not exceed TBF rate limit\n\t[ $(bc <<< \"$rate < 1.1 * $np * $1\") -eq 1 ] ||\n\t\terror \"The write rate ($rate) exceeds 110% of rate limit ($1 * $np)\"\n\n\tcancel_lru_locks osc\n\n\techo \"Verify the read rate is under TBF control\"\n\tstart=$SECONDS\n\tdo_node $client1 $myRUNAS dd if=$dir/tbf of=/dev/null \\\n\t\tbs=1M count=100 iflag=direct 2>&1\n\truntime=$((SECONDS - start + 1))\n\trate=$(bc <<< \"scale=6; 100 / $runtime\")\n\techo \"Read runtime is $runtime s, speed is $rate IOPS\"\n\n\t# verify the read rate does not exceed TBF rate limit\n\t[ $(bc <<< \"$rate < 1.1 * $np * $2\") -eq 1 ] ||\n\t\terror \"The read rate ($rate) exceeds 110% of rate limit ($2 * $np)\"\n\n\tcancel_lru_locks osc\n\tcleanup_tbf_verify || error \"rm -rf $dir failed\"\n}\n\ntest_77e() {\n\tlocal rc\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\\ nid\" ||\n\t\trc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS TBF exists\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to set TBF NID policy\"\n\n\tlocal idis\n\tlocal rateis\n\tif [ \"$OST1_VERSION\" -ge $(version_code 2.8.54) ]; then\n\t\tidis=\"nid=\"\n\t\trateis=\"rate=\"\n\tfi\n\n\t# Only operate rules on ost1 since OSTs might run on the same OSS\n\t# Add some rules\n\ttbf_rule_operate ost1 \"start\\ localhost\\ ${idis}{0@lo}\\ ${rateis}1000\"\n\tlocal address=$(comma_list \"$(host_nids_address $CLIENTS $NETTYPE)\")\n\tlocal client_nids=$(nids_list $address \"\\\\\")\n\ttbf_rule_operate ost1 \"start\\ clients\\ ${idis}{$client_nids}\\ ${rateis}100\"\n\ttbf_rule_operate ost1 \"start\\ others\\ ${idis}{*.*.*.*@$NETTYPE}\\ ${rateis}50\"\n\tnrs_write_read\n\n\t# Change the rules\n\ttbf_rule_operate ost1 \"change\\ localhost\\ ${rateis}1001\"\n\ttbf_rule_operate ost1 \"change\\ clients\\ ${rateis}101\"\n\ttbf_rule_operate ost1 \"change\\ others\\ ${rateis}51\"\n\tnrs_write_read\n\n\t# Stop the rules\n\ttbf_rule_operate ost1 \"stop\\ localhost\"\n\ttbf_rule_operate ost1 \"stop\\ clients\"\n\ttbf_rule_operate ost1 \"stop\\ others\"\n\tnrs_write_read\n\n\t# Cleanup the TBF policy\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n\t[ $? -ne 0 ] && error \"failed to set policy back to fifo\"\n\tnrs_write_read\n\treturn 0\n}\nrun_test 77e \"check TBF NID nrs policy\"\n\ntest_77f() {\n\tlocal rc\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdo_nodes $oss $LCTL set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ jobid\" || rc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS TBF exists\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to set TBF JOBID policy\"\n\n\t# Configure jobid_var\n\tlocal saved_jobid_var=$($LCTL get_param -n jobid_var)\n\trc=$?\n\t[[ $rc -eq 3 ]] && skip \"jobid_var not found\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to get param jobid_var\"\n\tif [ $saved_jobid_var != procname_uid ]; then\n\t\tset_persistent_param_and_check client \\\n\t\t\t\"jobid_var\" \"$FSNAME.sys.jobid_var\" procname_uid\n\tfi\n\n\tlocal idis\n\tlocal rateis\n\tif [ \"$OST1_VERSION\" -ge $(version_code 2.8.54) ]; then\n\t\tidis=\"jobid=\"\n\t\trateis=\"rate=\"\n\tfi\n\n\t# Only operate rules on ost1 since OSTs might run on the same OSS\n\t# Add some rules\n\ttbf_rule_operate ost1 \"start\\ runas\\ ${idis}{iozone.$RUNAS_ID\\ dd.$RUNAS_ID\\ tiotest.$RUNAS_ID}\\ ${rateis}1000\"\n\ttbf_rule_operate ost1 \"start\\ iozone_runas\\ ${idis}{iozone.$RUNAS_ID}\\ ${rateis}100\"\n\ttbf_rule_operate ost1 \"start\\ dd_runas\\ ${idis}{dd.$RUNAS_ID}\\ ${rateis}50\"\n\tnrs_write_read \"$RUNAS\"\n\n\t# Change the rules\n\ttbf_rule_operate ost1 \"change\\ runas\\ ${rateis}1001\"\n\ttbf_rule_operate ost1 \"change\\ iozone_runas\\ ${rateis}101\"\n\ttbf_rule_operate ost1 \"change\\ dd_runas\\ ${rateis}51\"\n\tnrs_write_read \"$RUNAS\"\n\n\t# Stop the rules\n\ttbf_rule_operate ost1 \"stop\\ runas\"\n\ttbf_rule_operate ost1 \"stop\\ iozone_runas\"\n\ttbf_rule_operate ost1 \"stop\\ dd_runas\"\n\tnrs_write_read \"$RUNAS\"\n\n\t# Cleanup the TBF policy\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n\t[ $? -ne 0 ] && error \"failed to set policy back to fifo\"\n\tnrs_write_read \"$RUNAS\"\n\n\tlocal current_jobid_var=$($LCTL get_param -n jobid_var)\n\t[[ $? -ne 0 ]] && error \"failed to get param jobid_var\"\n\tif [ $saved_jobid_var != $current_jobid_var ]; then\n\t\tset_persistent_param_and_check client \\\n\t\t\t\"jobid_var\" \"$FSNAME.sys.jobid_var\" $saved_jobid_var\n\tfi\n\treturn 0\n}\nrun_test 77f \"check TBF JobID nrs policy\"\n\ntest_77g() {\n\tlocal rc=0\n\n\toss=$(comma_list $(osts_nodes))\n\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\\ nid\" ||\n\t\trc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS TBF exists\" && return\n\t[[ $rc -ne 0 ]] && error \"failed to set TBF NID policy\"\n\n\tdo_nodes $oss lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ jobid\" || rc=$?\n\t[[ $rc -ne 0 ]] && error \"failed to set TBF JOBID policy\"\n\n\tlocal idis\n\tlocal rateis\n\tif [ \"$OST1_VERSION\" -ge $(version_code 2.8.54) ]; then\n\t\tidis=\"jobid=\"\n\t\trateis=\"rate=\"\n\tfi\n\n\t# Add a rule that only valid for Jobid TBF. If direct change between\n\t# TBF types is not supported, this operation will fail.\n\ttbf_rule_operate ost1 \"start\\ dd_runas\\ ${idis}{dd.$RUNAS_ID}\\ ${rateis}50\"\n\n\t# Cleanup the TBF policy\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n\t[ $? -ne 0 ] && error \"failed to set policy back to fifo\"\n\treturn 0\n}\nrun_test 77g \"Change TBF type directly\"\n\ntest_77h() {\n\t[ \"$OST1_VERSION\" -ge $(version_code 2.8.55) ] ||\n\t\tskip \"Need OST version at least 2.8.55\"\n\n\tlocal old_policy=$(do_facet ost1 \\\n\t\tlctl get_param ost.OSS.ost_io.nrs_policies)\n\tlocal new_policy\n\n\tdo_facet ost1 lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"abc\"\n\t[ $? -eq 0 ] && error \"should return error\"\n\n\tdo_facet ost1 lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ abc\"\n\t[ $? -eq 0 ] && error \"should return error\"\n\n\tdo_facet ost1 lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ reg\\ abc\"\n\t[ $? -eq 0 ] && error \"should return error\"\n\n\tdo_facet ost1 lctl set_param \\\n\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ abc\\ efg\"\n\t[ $? -eq 0 ] && error \"should return error\"\n\n\tnew_policy=$(do_facet ost1 lctl get_param ost.OSS.ost_io.nrs_policies)\n\t[ $? -eq 0 ] || error \"shouldn't LBUG\"\n\n\t[ \"$old_policy\" = \"$new_policy\" ] || error \"NRS policy should be same\"\n\n\treturn 0\n}\nrun_test 77h \"Wrong policy name should report error, not LBUG\"\n\ntbf_rule_check()\n{\n\tlocal facet=$1\n\tlocal expected=$2\n\tlocal error_message=$3\n\tlocal rule_number=0\n\tfor rule in $expected; do\n\t\trule_number=$((rule_number + 1))\n\tdone\n\tlocal stop_line=$(($rule_number + 3))\n\tlocal awk_command=\"awk 'NR >= 4 && NR <= $stop_line {print \\$1}'\"\n\n\tlocal output=$(do_facet $facet lctl get_param \\\n\t\tost.OSS.ost_io.nrs_tbf_rule |\n\t\teval $awk_command |\n\t\ttr \"\\n\" \" \" |\n\t\tsed 's/[ ]*$//')\n\tif [ \"$output\" != \"$expected\" ]; then\n\t\terror \"$error_message, expected '$expected', got '$output'\"\n\tfi\n}\n\ntest_77i() {\n\t[ \"$OST1_VERSION\" -ge $(version_code 2.8.55) ] ||\n\t\tskip \"Need OST version at least 2.8.55\"\n\n\tfor i in $(seq 1 $OSTCOUNT)\n\tdo\n\t\tdo_facet ost\"$i\" lctl set_param \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ jobid\"\n\t\t[ $? -ne 0 ] &&\n\t\t\terror \"failed to set TBF policy\"\n\tdone\n\n\ttbf_rule_check ost1 \"default\" \"error before inserting any rule\"\n\n\ttbf_rule_operate ost1 \"start\\ before\\ jobid={jobid}\\ rate=1000\"\n\ttbf_rule_check ost1 \"before default\" \\\n\t\t\"error when inserting rule 'before'\"\n\n\ttbf_rule_operate ost1 \"start\\ after\\ jobid={jobid}\\ rate=1000\\ rank=default\"\n\ttbf_rule_check ost1 \"before after default\" \\\n\t\t\"error when inserting rule 'after'\"\n\n\ttbf_rule_operate ost1 \"start\\ target\\ jobid={jobid}\\ rate=1000\\ rank=after\"\n\ttbf_rule_check ost1 \"before target after default\" \\\n\t\t\"error when inserting rule 'target'\"\n\n\techo \"Move before itself\"\n\ttbf_rule_operate ost1 \"change\\ target\\ rank=target\"\n\ttbf_rule_check ost1 \"before target after default\" \\\n\t\t\"error when moving before itself\"\n\n\techo \"Move to higher rank\"\n\ttbf_rule_operate ost1 \"change\\ target\\ rank=before\"\n\ttbf_rule_check ost1 \"target before after default\" \\\n\t\t\"error when moving to higher rank\"\n\n\techo \"Move to lower rank\"\n\ttbf_rule_operate ost1 \"change\\ target\\ rank=after\"\n\ttbf_rule_check ost1 \"before target after default\" \\\n\t\t\"error when moving to lower rank\"\n\n\techo \"Move before default\"\n\ttbf_rule_operate ost1 \"change\\ target\\ rank=default\"\n\ttbf_rule_check ost1 \"before after target default\" \\\n\t\terror \"error when moving before default\"\n\n\t# Cleanup the TBF policy\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t$LCTL set_param ost.OSS.ost_io.nrs_policies=fifo\n\treturn 0\n}\nrun_test 77i \"Change rank of TBF rule\"\n\ntest_77j() {\n\tlocal idis\n\tlocal rateis\n\n\t[ \"$OST1_VERSION\" -ge $(version_code 2.9.53) ] ||\n\t\tskip \"Need OST version at least 2.9.53\"\n\tif [ \"$OST1_VERSION\" -ge $(version_code 2.8.60) ]; then\n\t\tidis=\"opcode=\"\n\t\trateis=\"rate=\"\n\tfi\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param jobid_var=procname_uid \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ opcode\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ost_r\\ ${idis}{ost_read}\\ ${rateis}5\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ost_w\\ ${idis}{ost_write}\\ ${rateis}20\"\n\t[ $? -ne 0 ] && error \"failed to set TBF OPCode policy\"\n\n\tnrs_write_read\n\ttbf_verify 20 5\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ost_r\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ost_w\" \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"fifo\"\n\n\t# sleep 3 seconds to wait the tbf policy stop completely,\n\t# or the next test case is possible get -EAGAIN when\n\t# setting the tbf policy\n\tsleep 3\n}\nrun_test 77j \"check TBF-OPCode NRS policy\"\n\ntest_id() {\n\tlocal idstr=\"${1}id\"\n\tlocal policy=\"${idstr}={$2}\"\n\tlocal rate=\"rate=$3\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param jobid_var=procname_uid \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"tbf\\ ${idstr}\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ost_${idstr}\\ ${policy}\\ ${rate}\"\n\t[ $? -ne 0 ] && error \"failed to set tbf ${idstr} policy\"\n\n\tnrs_write_read \"runas $4\"\n\ttbf_verify $3 $3 \"runas $4\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ost_${idstr}\" \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"fifo\"\n\n\t# sleep 3 seconds to wait the tbf policy stop completely,\n\t# or the next test case is possible get -eagain when\n\t# setting the tbf policy\n\tsleep 3\n}\n\ntest_77ja(){\n\tif [ \"$OST1_VERSION\" -lt $(version_code 2.11.50) ]; then\n\t\tskip \"Need OST version at least 2.11.50\"\n\tfi\n\n\ttest_id \"u\" \"500\" \"5\" \"-u 500\"\n\ttest_id \"g\" \"500\" \"5\" \"-u 500 -g 500\"\n}\nrun_test 77ja \"check TBF-UID/GID NRS policy\"\n\ncleanup_77k()\n{\n\tlocal rule_lists=$1\n\tlocal old_nrs=$2\n\n\ttrap 0\n\tfor rule in $rule_lists; do\n\t\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ $rule\"\n\tdone\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_policies=\"$old_nrs\"\n\n\tsleep 3\n}\n\ntest_77k() {\n\t[[ \"$OST1_VERSION\" -ge $(version_code 2.9.53) ]] ||\n\t\tskip \"Need OST version at least 2.9.53\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_w\\ jobid={dd.$RUNAS_ID}\\&opcode={ost_write}\\ rate=20\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_r\\ jobid={dd.$RUNAS_ID}\\&opcode={ost_read}\\ rate=10\"\n\n\tnrs_write_read \"$RUNAS\"\n\ttbf_verify 20 10 \"$RUNAS\"\n\n\tlocal address=$(comma_list \"$(host_nids_address $CLIENTS $NETTYPE)\")\n\tlocal client_nids=$(nids_list $address \"\\\\\")\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_w\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_r\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_w\\ nid={0@lo\\ $client_nids}\\&opcode={ost_write}\\ rate=20\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_r\\ nid={0@lo\\ $client_nids}\\&opcode={ost_read}\\ rate=10\"\n\n\tnrs_write_read\n\ttbf_verify 20 10\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_w\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_r\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext\\ nid={0@lo\\ $client_nids}\\&jobid={dd.$RUNAS_ID}\\ rate=20\"\n\n\tnrs_write_read \"$RUNAS\"\n\ttbf_verify 20 20 \"$RUNAS\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_a\\ jobid={dd.$RUNAS_ID},opcode={ost_write}\\ rate=20\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_b\\ jobid={dd.$RUNAS_ID},opcode={ost_read}\\ rate=10\"\n\n\tnrs_write_read \"$RUNAS\"\n\t# with parameter \"RUNAS\", it will match the latest rule\n\t# \"ext_b\" first, so the limited write rate is 10.\n\ttbf_verify 10 10 \"$RUNAS\"\n\ttbf_verify 20 10\n\n\ttrap \"cleanup_77k \\\"ext_a ext_b\\\" \\\"fifo\\\"\" EXIT\n\n\t[[ \"$OST1_VERSION\" -ge $(version_code 2.10.58) ]] ||\n\t\tskip \"Need OST version at least 2.10.58\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_a\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_b\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_ug\\ uid={500}\\&gid={1000}\\ rate=5\"\n\tnrs_write_read \"runas -u 500 -g 1000\"\n\ttbf_verify 5 5 \"runas -u 500 -g 1000\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_ug\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_uw\\ uid={500}\\&opcode={ost_write}\\ rate=20\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_ur\\ uid={500}\\&opcode={ost_read}\\ rate=10\"\n\n\tnrs_write_read \"runas -u 500\"\n\ttbf_verify 20 10 \"runas -u 500\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_uw\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ ext_ur\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_a\\ uid={500},opcode={ost_write}\\ rate=20\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ ext_b\\ uid={500},opcode={ost_read}\\ rate=10\"\n\tnrs_write_read \"runas -u 500\"\n\ttbf_verify 10 10 \"runas -u 500\"\n\ttbf_verify 20 10 \"runas -u 500\"\n\tcleanup_77k \"ext_a ext_b\" \"fifo\"\n}\nrun_test 77k \"check TBF policy with NID/JobID/OPCode expression\"\n\ntest_77l() {\n\t[[ \"$OST1_VERSION\" -ge $(version_code 2.10.56) ]] ||\n\t\tskip \"Need OST version at least 2.10.56\"\n\n\tdo_facet ost1 lctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\\ nid\"\n\tdo_facet ost1 lctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\"\n\n\tlocal output=$(do_facet ost1 lctl get_param \\\n\t\t\tost.OSS.ost_io.nrs_policies | \\\n\t\t\tawk '/name: tbf/ {print;exit}' | \\\n\t\t\tawk -F ': ' '{print $2}')\n\n\tif [ \"$output\" != \"tbf\" ]; then\n\t\terror \"The generic TBF output is '$output', not 'tbf'\"\n\tfi\n\n\tdo_facet ost1 lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n}\nrun_test 77l \"check the output of NRS policies for generic TBF\"\n\ntest_77m() {\n\tif [ \"$OST1_VERSION\" -lt $(version_code 2.9.54) ]; then\n\t\tskip \"Need OST version at least 2.9.54\"\n\tfi\n\n\tlocal dir=$DIR/$tdir\n\n\tmkdir $dir || error \"mkdir $dir failed\"\n\t$LFS setstripe -c $OSTCOUNT $dir || error \"setstripe to $dir failed\"\n\tchmod 777 $dir\n\n\tlocal nodes=$(comma_list $(osts_nodes))\n\tdo_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=delay \\\n\t\t\t\t       ost.OSS.ost_io.nrs_delay_min=4 \\\n\t\t\t\t       ost.OSS.ost_io.nrs_delay_max=4 \\\n\t\t\t\t       ost.OSS.ost_io.nrs_delay_pct=100\n\t[ $? -ne 0 ] && error \"Failed to set delay policy\"\n\n\tlocal start=$SECONDS\n\tdo_nodes \"${SINGLECLIENT:-$HOSTNAME}\" \"$RUNAS\" \\\n\t\t dd if=/dev/zero of=\"$dir/nrs_delay_$HOSTNAME\" bs=1M count=1 \\\n\t\t   oflag=direct conv=fdatasync ||\n\t\t{ do_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\";\n\t\t  error \"dd on client failed (1)\"; }\n\tlocal elapsed=$((SECONDS - start))\n\n\t# NRS delay doesn't do sub-second timing, so a request enqueued at\n\t# 0.9 seconds can be dequeued at 4.0\n\t[ $elapsed -lt 3 ] &&\n\t\t{ do_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\";\n\t\t  error \"Single 1M write should take at least 3 seconds\"; }\n\n\tstart=$SECONDS\n\tdo_nodes \"${SINGLECLIENT:-$HOSTNAME}\" \"$RUNAS\" \\\n\t\t dd if=/dev/zero of=\"$dir/nrs_delay_$HOSTNAME\" bs=1M count=10 \\\n\t\t   oflag=direct conv=fdatasync ||\n\t\t{ do_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\";\n\t\t  error \"dd on client failed (2)\"; }\n\telapsed=$((SECONDS - start))\n\n\t[ $elapsed -lt 30 ] &&\n\t\t{ do_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\";\n\t\t  error \"Ten 1M writes should take at least 30 seconds\"; }\n\n\tdo_nodes $nodes lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n\t[ $? -ne 0 ] && error \"failed to set policy back to fifo\"\n\n\treturn 0\n}\nrun_test 77m \"check NRS Delay slows write RPC processing\"\n\ntest_77n() { #LU-10802\n\tif [ \"$OST1_VERSION\" -lt $(version_code 2.10.58) ]; then\n\t\tskip \"Need OST version at least 2.10.58\"\n\tfi\n\n\t# Configure jobid_var\n\tlocal saved_jobid_var=$($LCTL get_param -n jobid_var)\n\tif [ $saved_jobid_var != procname_uid ]; then\n\t\tset_persistent_param_and_check client \\\n\t\t\t\"jobid_var\" \"$FSNAME.sys.jobid_var\" procname_uid\n\tfi\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_policies=\"tbf\\ jobid\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"stop\\ dd_runas\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ dd_runas\\ jobid={*.$RUNAS_ID}\\ rate=20\"\n\n\tnrs_write_read\n\ttbf_verify 20 20 \"$RUNAS\"\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ dd_runas\" \\\n\t\t\tost.OSS.ost_io.nrs_tbf_rule=\"start\\ dd_runas\\ jobid={dd.*}\\ rate=20\"\n\n\tnrs_write_read\n\ttbf_verify 20 20\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\tlctl set_param ost.OSS.ost_io.nrs_tbf_rule=\"stop\\ dd_runas\" \\\n\t\t\tost.OSS.ost_io.nrs_policies=\"fifo\"\n\n\tsleep 3\n\n\tlocal current_jobid_var=$($LCTL get_param -n jobid_var)\n\tif [ $saved_jobid_var != $current_jobid_var ]; then\n\t\tset_persistent_param_and_check client \\\n\t\t\t\"jobid_var\" \"$FSNAME.sys.jobid_var\" $saved_jobid_var\n\tfi\n}\nrun_test 77n \"check wildcard support for TBF JobID NRS policy\"\n\ntest_78() { #LU-6673\n\tlocal rc\n\n\toss=$(comma_list $(osts_nodes))\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"orr\" &\n\tdo_nodes $oss lctl set_param ost.OSS.*.nrs_orr_quantum=1\n\trc=$?\n\t[[ $rc -eq 3 ]] && skip \"no NRS exists\" && return\n\t# Valid return codes are:\n\t# 0: Tuning succeeded\n\t# ENODEV: Policy is still stopped\n\t# EAGAIN: Policy is being initialized\n\t[ $rc -eq 0 -o $rc -eq 19 -o $rc -eq 11 ] ||\n\t\terror \"Expected set_param to return 0|ENODEV|EAGAIN\"\n\n\t# Cleanup the ORR policy\n\tdo_nodes $oss lctl set_param ost.OSS.ost_io.nrs_policies=\"fifo\"\n\t[ $? -ne 0 ] && error \"failed to set policy back to fifo\"\n\treturn 0\n}\nrun_test 78 \"Enable policy and specify tunings right away\"\n\ntest_79() {\n\tremote_mds_nodsh && skip \"remote MDS with nodsh\" && return\n\ttest_mkdir $DIR/$tdir\n\n\t# Prevent interference from layout intent RPCs due to\n\t# asynchronous writeback. These will be tested in 130c below.\n\tdo_nodes ${CLIENTS:-$HOSTNAME} sync\n\n\tsetfattr -n trusted.name1 -v value1 $DIR/$tdir ||\n\t\terror \"setfattr -n trusted.name1=value1 $DIR/$tdir failed\"\n\n#define OBD_FAIL_MDS_INTENT_DELAY\t\t0x160\n\tlocal mdtidx=$($LFS getstripe -m $DIR/$tdir)\n\tlocal facet=mds$((mdtidx + 1))\n\tstat $DIR/$tdir\n\tset_nodes_failloc $(facet_active_host $facet) 0x80000160\n\tgetfattr -n trusted.name1 $DIR/$tdir 2> /dev/null  &\n\tlocal pid=$!\n\tsleep 2\n\n#define OBD_FAIL_MDS_GETXATTR_PACK       0x131\n\tset_nodes_failloc $(facet_active_host $facet) 0x80000131\n\n\twait $pid\n\treturn 0\n}\nrun_test 79 \"xattr: intent error\"\n\ntest_80a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal MDTIDX=1\n\tlocal mdt_index\n\tlocal i\n\tlocal file\n\tlocal pid\n\n\tmkdir -p $DIR1/$tdir/dir\n\tcreatemany -o $DIR1/$tdir/dir/f 10 ||\n\t\terror \"create files under remote dir failed $i\"\n\n\tcp /etc/passwd $DIR1/$tdir/$tfile\n\n\t#migrate open file should fails\n\tmultiop_bg_pause $DIR2/$tdir/$tfile O_c || error \"open $file failed\"\n\tpid=$!\n\t# give multiop a chance to open\n\tsleep 1\n\n\t$LFS migrate -m $MDTIDX $DIR1/$tdir &&\n\t\terror \"migrate open files should failed with open files\"\n\n\tkill -USR1 $pid\n\n\t$LFS migrate -m $MDTIDX $DIR1/$tdir ||\n\t\t\terror \"migrate remote dir error\"\n\n\techo \"Finish migration, then checking..\"\n\tfor file in $(find $DIR1/$tdir); do\n\t\tmdt_index=$($LFS getstripe -m $file)\n\t\t[ $mdt_index == $MDTIDX ] ||\n\t\t\terror \"$file is not on MDT${MDTIDX}\"\n\tdone\n\n\tdiff /etc/passwd $DIR1/$tdir/$tfile ||\n\t\terror \"file different after migration\"\n\n\trm -rf $DIR1/$tdir || error \"rm dir failed after migration\"\n}\nrun_test 80a \"migrate directory when some children is being opened\"\n\ncleanup_80b() {\n\ttrap 0\n\tkill -9 $migrate_pid\n}\n\ntest_80b() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal migrate_dir1=$DIR1/$tdir/migrate_dir\n\tlocal migrate_dir2=$DIR2/$tdir/migrate_dir\n\tlocal migrate_run=$LUSTRE/tests/migrate.sh\n\tlocal start_time\n\tlocal end_time\n\tlocal show_time=1\n\tlocal mdt_idx\n\tlocal rc=0\n\tlocal rc1=0\n\n\ttrap cleanup_80b EXIT\n\t#prepare migrate directory\n\tmkdir -p $migrate_dir1\n\tfor F in {1,2,3,4,5}; do\n\t\techo \"$F$F$F$F$F\" > $migrate_dir1/file$F\n\t\techo \"$F$F$F$F$F\" > $DIR/$tdir/file$F\n\tdone\n\n\t#migrate the directories among MDTs\n\t(\n\t\twhile true; do\n\t\t\tmdt_idx=$((RANDOM % MDSCOUNT))\n\t\t\t$LFS migrate -m $mdt_idx $migrate_dir1 &>/dev/null ||\n\t\t\t\trc=$?\n\t\t\t[ $rc -ne 0 -o $rc -ne 16 ] || break\n\t\tdone\n\t) &\n\tmigrate_pid=$!\n\n\techo \"start migration thread $migrate_pid\"\n\t#Access the files at the same time\n\tstart_time=$(date +%s)\n\techo \"accessing the migrating directory for 5 minutes...\"\n\twhile true; do\n\t\tls $migrate_dir2 > /dev/null || {\n\t\t\techo \"read dir fails\"\n\t\t\tbreak\n\t\t}\n\t\tdiff -u $DIR2/$tdir/file1 $migrate_dir2/file1 || {\n\t\t\techo \"access file1 fails\"\n\t\t\tbreak\n\t\t}\n\n\t\tcat $migrate_dir2/file2 > $migrate_dir2/file3 || {\n\t\t\techo \"access file2/3 fails\"\n\t\t\tbreak\n\t\t}\n\n\t\techo \"aaaaa\" > $migrate_dir2/file4 > /dev/null || {\n\t\t\techo \"access file4 fails\"\n\t\t\tbreak\n\t\t}\n\n\t\tstat $migrate_dir2/file5 > /dev/null || {\n\t\t\techo \"stat file5 fails\"\n\t\t\tbreak\n\t\t}\n\n\t\ttouch $migrate_dir2/source_file > /dev/null || rc1=$?\n\t\t[ $rc1 -ne 0 -o $rc1 -ne 1 ] || {\n\t\t\techo \"touch file failed with $rc1\"\n\t\t\tbreak;\n\t\t}\n\n\t\tif [ -e $migrate_dir2/source_file ]; then\n\t\t\tln $migrate_dir2/source_file $migrate_dir2/link_file \\\n\t\t\t\t\t&>/dev/null || rc1=$?\n\t\t\tif [ -e $migrate_dir2/link_file ]; then\n\t\t\t\trm -rf $migrate_dir2/link_file\n\t\t\tfi\n\n\t\t\tmrename $migrate_dir2/source_file \\\n\t\t\t\t$migrate_dir2/target_file &>/dev/null || rc1=$?\n\t\t\t[ $rc1 -ne 0 -o $rc1 -ne 1 ] || {\n\t\t\t\techo \"rename failed with $rc1\"\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif [ -e $migrate_dir2/target_file ]; then\n\t\t\t\trm -rf $migrate_dir2/target_file &>/dev/null ||\n\t\t\t\t\t\t\t\trc1=$?\n\t\t\telse\n\t\t\t\trm -rf $migrate_dir2/source_file &>/dev/null ||\n\t\t\t\t\t\t\t\trc1=$?\n\t\t\tfi\n\t\t\t[ $rc1 -ne 0 -o $rc1 -ne 1 ] || {\n\t\t\t\techo \"unlink failed with $rc1\"\n\t\t\t\tbreak\n\t\t\t}\n\t\tfi\n\n\t\tend_time=$(date +%s)\n\t\tduration=$((end_time - start_time))\n\t\tif [ $((duration % 10)) -eq 0 ]; then\n\t\t\tif [ $show_time -eq 1 ]; then\n\t\t\t\techo \"...$duration seconds\"\n\t\t\t\tshow_time=0\n\t\t\tfi\n\t\telse\n\t\t\tshow_time=1\n\t\tfi\n\n\t\tkill -0 $migrate_pid || {\n\t\t\techo \"migration stopped 1\"\n\t\t\tbreak\n\t\t}\n\n\t\t[ $duration -ge 300 ] && break\n\tdone\n\n\t#check migration are still there\n\tkill -0 $migrate_pid || error \"migration stopped 2\"\n\tcleanup_80b\n}\nrun_test 80b \"Accessing directory during migration\"\n\ntest_81a() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\trm -rf $DIR1/$tdir\n\n\tmkdir -p $DIR1/$tdir\n\n\t$LFS setdirstripe -i0 -c$MDSCOUNT  $DIR1/$tdir/d0\n\t$LFS setdirstripe -i0 -c$MDSCOUNT  $DIR1/$tdir/d1\n\n\tcd $DIR1/$tdir\n\ttouch d0/0\t|| error \"create 0 failed\"\n\tmv d0/0\td1/0\t|| error \"rename d0/0 d1/0 failed\"\n\tstat d0/0\t&& error \"stat mv filed succeed\"\n\tmv $DIR2/$tdir/d1/0 $DIR2/$tdir/d0/0 || error \"rename d1/0 d0/0 failed\"\n\tstat d0/0\t|| error \"stat failed\"\n\n\tlocal t=$(ls -ai $DIR1/$tdir/d0 | sort -u | wc -l)\n\n\tif [ $t -ne 3 ]; then\n\t\tls -ai $DIR1/$tdir/d0\n\t\terror \"expect 3 get $t\"\n\tfi\n\n\treturn 0\n}\nrun_test 81a \"rename and stat under striped directory\"\n\ntest_81b() {\n\t[ $MDSCOUNT -lt 2 ] &&\n\t\tskip \"We need at least 2 MDTs for this test\"\n\n\tlocal total\n\tlocal setattr_pid\n\n\ttotal=1000\n\n\t$LFS mkdir -c $MDSCOUNT $DIR1/$tdir || error \"$LFS mkdir\"\n\tcreatemany -o $DIR1/$tdir/$tfile. $total || error \"createmany\"\n\n\t(\n\t\twhile true; do\n\t\t\ttouch $DIR1/$tdir\n\t\tdone\n\t) &\n\tsetattr_pid=$!\n\n\tfor i in $(seq $total); do\n\t\tmrename $DIR2/$tdir/$tfile.$i $DIR2/$tdir/$tfile-new.$i \\\n\t\t\t> /dev/null\n\tdone\n\n\tkill -9 $setattr_pid\n}\nrun_test 81b \"rename under striped directory doesn't deadlock\"\n\ntest_81c() {\n\t[ $MDSCOUNT -lt 4 ] && skip_env \"needs >= 4 MDTs\"\n\t[ $MDS1_VERSION -lt $(version_code 2.13.52) ] &&\n\t\tskip \"Need MDS version at least 2.13.52\"\n\n\t# source is local, source parent is remote\n\t$LFS mkdir -i 0 $DIR1/${tdir}_src || error \"mkdir ${tdir}_src\"\n\t$LFS mkdir -i 1 $DIR1/${tdir}_tgt || error \"mkdir ${tdir}_tgt\"\n\t$LFS mkdir -i 3 $DIR1/${tdir}_src/sub || error \"mkdir sub\"\n\t$LFS mkdir -i 3 $DIR1/${tdir}_tgt/sub || error \"mkdir sub\"\n\tstat $DIR2/${tdir}_src/sub || error \"stat sub failed\"\n\tmv $DIR1/${tdir}_src/sub $DIR1/${tdir}_tgt/ || error \"mv failed\"\n\t[ -f $DIR2/${tdir}_src/sub ] && error \"sub should be gone\"\n\trm -rf $DIR1/${tdir}_src $DIR1/${tdir}_tgt\n\n\t# source is remote, source parent is local\n\t$LFS mkdir -i 3 $DIR1/${tdir}_src || error \"mkdir ${tdir}_src\"\n\t$LFS mkdir -i 1 $DIR1/${tdir}_tgt || error \"mkdir ${tdir}_tgt\"\n\t$LFS mkdir -i 0 $DIR1/${tdir}_src/sub || error \"mkdir sub\"\n\t$LFS mkdir -i 3 $DIR1/${tdir}_tgt/sub || error \"mkdir sub\"\n\tstat $DIR2/${tdir}_src/sub || error \"stat sub failed\"\n\tmv $DIR1/${tdir}_src/sub $DIR1/${tdir}_tgt/ || error \"mv failed\"\n\t[ -f $DIR2/${tdir}_src/sub ] && error \"sub should be gone\"\n\trm -rf $DIR1/${tdir}_src $DIR1/${tdir}_tgt\n\n\t# source and source parent are remote\n\t$LFS mkdir -i 0 $DIR1/${tdir}_src || error \"mkdir ${tdir}_src\"\n\t$LFS mkdir -i 1 $DIR1/${tdir}_tgt || error \"mkdir ${tdir}_tgt\"\n\tmkdir $DIR1/${tdir}_src/sub || error \"mkdir sub\"\n\t$LFS mkdir -i 3 $DIR1/${tdir}_tgt/sub || error \"mkdir sub\"\n\tstat $DIR2/${tdir}_src/sub || error \"stat sub failed\"\n\tmv $DIR1/${tdir}_src/sub $DIR1/${tdir}_tgt/ || error \"mv failed\"\n\t[ -f $DIR2/${tdir}_src/sub ] && error \"sub should be gone\"\n\trm -rf $DIR1/${tdir}_src $DIR1/${tdir}_tgt\n\n\t# source and source parent are remote, and source is remote object\n\t$LFS mkdir -i 0 $DIR1/${tdir}_src || error \"mkdir ${tdir}_src\"\n\t$LFS mkdir -i 1 $DIR1/${tdir}_tgt || error \"mkdir ${tdir}_tgt\"\n\t$LFS mkdir -i 2 $DIR1/${tdir}_src/sub || error \"mkdir sub\"\n\t$LFS mkdir -i 3 $DIR1/${tdir}_tgt/sub || error \"mkdir sub\"\n\tstat $DIR2/${tdir}_src/sub || error \"stat sub failed\"\n\tmv $DIR1/${tdir}_src/sub $DIR1/${tdir}_tgt/ || error \"mv failed\"\n\t[ -f $DIR2/${tdir}_src/sub ] && error \"sub should be gone\" || true\n}\nrun_test 81c \"rename revoke LOOKUP lock for remote object\"\n\ntest_82() {\n\t[[ \"$MDS1_VERSION\" -gt $(version_code 2.6.91) ]] ||\n\t\tskip \"Need MDS version at least 2.6.92\"\n\n\t# Client 1 creates a file.\n\tmultiop_bg_pause $DIR1/$tfile O_ac || error \"multiop_bg_pause 1\"\n\tpid1=$!\n\t# Client 2 opens the file.\n\tmultiop_bg_pause $DIR2/$tfile o_Ac || error \"multiop_bg_pause 2\"\n\tpid2=$!\n\t# Client 1 makes the file an orphan.\n\trm $DIR1/$tfile || error \"rm\"\n\t# Client 2 sets EA \"user.multiop\".\n\tkill -s USR1 $pid2\n\twait $pid2 || error \"multiop 2\"\n\t# Client 1 gets EA \"user.multiop\".  This used to fail because the EA\n\t# cache refill would get \"trusted.link\" from mdd_xattr_list() but\n\t# -ENOENT when trying to get \"trusted.link\"'s value.  See also sanity\n\t# 102q.\n\tkill -s USR1 $pid1\n\twait $pid1 || error \"multiop 1\"\n}\nrun_test 82 \"fsetxattr and fgetxattr on orphan files\"\n\ntest_83() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal pid1\n\tlocal pid2\n\n\t(\n\t\tcd $DIR1\n\t\twhile true; do\n\t\t\t$LFS mkdir -i1 -c2 $tdir\n\t\t\trmdir $tdir\n\t\tdone\n\t) &\n\tpid1=$!\n\techo \"start pid $pid1 to create/unlink striped directory\"\n\n\t# Access the directory at the same time\n\t(\n\t\tcd $DIR2\n\t\twhile true; do\n\t\t\tstat $tdir > /dev/null 2>&1\n\t\tdone\n\t) &\n\tpid2=$!\n\techo \"start pid $pid2 to stat striped directory\"\n\n\tsleep 120\n\tkill $pid1 $pid2\n\twait $pid1 $pid2\n\n\treturn 0\n}\nrun_test 83 \"access striped directory while it is being created/unlinked\"\n\ntest_84() {\n\t[ $MDS1_VERSION -lt $(version_code 2.12.55) ] &&\n\t\tskip \"lustre < 2.12.55 does not contain LU-12485 fix\"\n\n\tlocal mtime\n\n\t$MULTIOP $DIR/$tfile oO_RDWR:O_CREAT:O_LOV_DELAY_CREATE:c ||\n\t\terror \"create $tfile failed\"\n\tmtime=$(stat -c%Y $DIR/$tfile)\n\tmtime=$((mtime + 200))\n\n\t#define OBD_FAIL_OBD_0NLINK_RACE  0x60b\n\tdo_facet mds1 $LCTL set_param fail_loc=0x8000060b\n\n\ttouch -c -m $mtime $DIR/$tfile &\n\tsetattr_pid=$!\n\t# sleep a while to let 'touch' run first\n\tsleep 5\n\trm -f $DIR2/$tfile || error \"unlink $tfile failed\"\n\n\t# touch may fail\n\twait $setattr_pid || true\n}\nrun_test 84 \"0-nlink race in lu_object_find()\"\n\ntest_90() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal pid1\n\tlocal pid2\n\tlocal duration=180\n\n\t[ \"$SLOW\" = \"yes\" ] && duration=600\n\t# Open/Create under striped directory\n\t(\n\t\tcd $DIR1\n\t\twhile true; do\n\t\t\t$LFS mkdir -c$MDSCOUNT $tdir > /dev/null 2>&1\n\t\t\ttouch $tdir/f{0..3} > /dev/null 2>&1\n\t\tdone\n\t) &\n\tpid1=$!\n\techo \"start pid $pid1 to open/create under striped directory\"\n\n\t# unlink the striped directory at the same time\n\t(\n\t\tcd $DIR2\n\t\twhile true; do\n\t\t\trm -rf $tdir > /dev/null 2>&1\n\t\tdone\n\t) &\n\tpid2=$!\n\techo \"start pid $pid2 to unlink striped directory\"\n\n\tsleep $duration\n\n\tkill $pid1 $pid2\n\twait $pid1 $pid2\n\n\treturn 0\n}\nrun_test 90 \"open/create and unlink striped directory\"\n\ntest_91() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\tlocal pid1\n\tlocal pid2\n\tlocal duration=180\n\n\t[ \"$SLOW\" = \"yes\" ] && duration=600\n\t# chmod striped directory\n\t(\n\t\tcd $DIR1\n\t\twhile true; do\n\t\t\t$LFS mkdir -c$MDSCOUNT $tdir > /dev/null 2>&1\n\t\t\tchmod go+w $tdir > /dev/null 2>&1\n\t\tdone\n\t) &\n\tpid1=$!\n\techo \"start pid $pid1 to chmod striped directory\"\n\n\t# unlink the striped directory at the same time\n\t(\n\t\tcd $DIR2\n\t\twhile true; do\n\t\t\trm -rf $tdir > /dev/null 2>&1\n\t\tdone\n\t) &\n\tpid2=$!\n\techo \"start pid $pid2 to unlink striped directory\"\n\n\tsleep $duration\n\n\tkill $pid1 $pid2\n\twait $pid1 $pid2\n\n\treturn 0\n}\nrun_test 91 \"chmod and unlink striped directory\"\n\ntest_92() {\n\t[ $MDSCOUNT -lt 2 ] && skip \"needs >= 2 MDTs\" && return\n\n\tlocal fd=$(free_fd)\n\tlocal cmd=\"exec $fd<$DIR1/$tdir\"\n\t$LFS setdirstripe -c$MDSCOUNT $DIR1/$tdir || error \"mkdir $tdir fails\"\n\teval $cmd\n\tcmd=\"exec $fd<&-\"\n\ttrap \"eval $cmd\" EXIT\n\tcd $DIR1/$tdir || error \"cd $DIR1/$tdir fails\"\n\trmdir ../$tdir || error \"rmdir ../$tdir fails\"\n\n\t#define OBD_FAIL_LLITE_NO_CHECK_DEAD  0x1408\n\t$LCTL set_param fail_loc=0x1408\n\tmkdir $DIR2/$tdir/dir && error \"create dir succeeds\"\n\t$LFS setdirstripe -i1 $DIR2/$tdir/remote_dir &&\n\t\terror \"create remote dir succeeds\"\n\t$LCTL set_param fail_loc=0\n\teval $cmd\n\treturn 0\n}\nrun_test 92 \"create remote directory under orphan directory\"\n\ntest_93() {\n\tlocal rc1=0\n\tlocal rc2=0\n\tlocal old_rr\n\n\tmkdir -p $DIR1/$tfile-1/\n\tmkdir -p $DIR2/$tfile-2/\n\tlocal old_rr=$(do_facet $SINGLEMDS \"$LCTL get_param -n \\\n\t\tlod.$FSNAME-MDT0000-*/qos_threshold_rr\" | sed -e 's/%//')\n\tdo_facet $SINGLEMDS \"$LCTL set_param -n \\\n\t\tlod.$FSNAME-MDT0000-*/qos_threshold_rr=100\"\n\t#define OBD_FAIL_MDS_LOV_CREATE_RACE     0x163\n\tdo_facet $SINGLEMDS \"$LCTL set_param fail_loc=0x00000163\"\n\n\t$LFS setstripe -c -1 $DIR1/$tfile-1/file1 &\n\tlocal PID1=$!\n\tsleep 1\n\t$LFS setstripe -c -1 $DIR2/$tfile-2/file2 &\n\tlocal PID2=$!\n\twait $PID2\n\twait $PID1\n\tdo_facet $SINGLEMDS \"$LCTL set_param fail_loc=0x0\"\n\tdo_facet $SINGLEMDS \"$LCTL set_param -n \\\n\t\tlod.$FSNAME-MDT0000-*/qos_threshold_rr=$old_rr\"\n\n\t$LFS getstripe $DIR1/$tfile-1/file1\n\trc1=$($LFS getstripe -q $DIR1/$tfile-1/file1 |\n\t\tawk '{if (/[0-9]/) print $1 }' | sort | uniq -d | wc -l)\n\t$LFS getstripe $DIR2/$tfile-2/file2\n\trc2=$($LFS getstripe -q $DIR2/$tfile-2/file2 |\n\t\tawk '{if (/[0-9]/) print $1 }' | sort | uniq -d | wc -l)\n\techo \"rc1=$rc1 and rc2=$rc2 \"\n\t[ $rc1 -eq 0 ] && [ $rc2 -eq 0 ] ||\n\t\terror \"object allocate on same ost detected\"\n}\nrun_test 93 \"alloc_rr should not allocate on same ost\"\n\ntest_94() {\n\t$LCTL set_param osc.*.idle_timeout=0\n\tdd if=/dev/zero of=$DIR2/$tfile bs=4k count=2 conv=fsync\n\n\tlocal before=$(date +%s)\n\tlocal evict\n\n\t$LCTL mark write\n#define OBD_FAIL_LDLM_PAUSE_CANCEL       0x312\n\t$LCTL set_param fail_val=5 fail_loc=0x80000312\n\tdd if=/dev/zero of=$DIR/$tfile conv=notrunc oflag=append bs=4k count=1 &\n\tlocal pid=$!\n\tsleep 2\n\n#define OBD_FAIL_LDLM_PAUSE_CANCEL_LOCAL 0x329\n\t$LCTL set_param fail_val=6 fail_loc=0x80000329\n\t$LCTL mark kill $pid\n\tkill -ALRM $pid\n\n\tdd if=/dev/zero of=$DIR2/$tfile conv=notrunc oflag=append bs=4k count=1\n\n\twait $pid\n\tdd if=/dev/zero of=$DIR/$tfile bs=4k count=1 conv=fsync\n\n\tevict=$(do_facet client $LCTL get_param \\\n\t\tosc.$FSNAME-OST*-osc-*/state |\n\t    awk -F\"[ [,]\" '/EVICTED ]$/ { if (t<$5) {t=$5;} } END { print t }')\n\n\t[ -z \"$evict\" ] || [[ $evict -le $before ]] ||\n\t\t(do_facet client $LCTL get_param \\\n\t\t\tosc.$FSNAME-OST*-osc-*/state;\n\t\t    error \"eviction happened: $evict before:$before\")\n\t$LCTL set_param osc.*.idle_timeout=debug\n}\nrun_test 94 \"signal vs CP callback race\"\n\n# Data-on-MDT tests\ntest_100a() {\n\tskip \"Reserved for glimpse-ahead\" && return\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR/$tdir/dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tdd if=/dev/zero of=$DIR2/$tdir/dom bs=4096 count=1 || return 1\n\n\t$CHECKSTAT -t file -s 4096 $DIR/$tdir/dom || error \"stat #1\"\n\t# first stat from server should return size data and save glimpse\n\tlocal gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls -eq 0 ] || error \"Unexpected $gls glimpse RPCs\"\n\t# second stat to check size is NOT cached on client without IO lock\n\t$CHECKSTAT -t file -s 4096 $DIR/$tdir/dom || error \"stat #2\"\n\n\tlocal gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls -ge 1 ] || error \"Expect glimpse RPCs but none\"\n\trm -f $dom\n}\nrun_test 100a \"DoM: glimpse RPCs for stat without IO lock (DoM only file)\"\n\ntest_100b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR/$tdir/dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tdd if=/dev/zero of=$DIR2/$tdir/dom bs=4096 count=1 || return 1\n\tcancel_lru_locks mdc\n\t# first stat data from server should have size\n\t$CHECKSTAT -t file -s 4096 $DIR/$tdir/dom || error \"stat #1\"\n\t# second stat to check size is cached on client\n\t$CHECKSTAT -t file -s 4096 $DIR/$tdir/dom || error \"stat #2\"\n\n\tlocal gls=$(lctl get_param -n mdc.*.stats | grep -c ldlm_glimpse)\n\t# both stats should cause no glimpse requests\n\t[ $gls == 0 ] || error \"Unexpected $gls glimpse RPCs\"\n\trm -f $dom\n}\nrun_test 100b \"DoM: no glimpse RPC for stat with IO lock (DoM only file)\"\n\ntest_100c() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR/$tdir/dom\n\n\tlctl set_param -n mdc.*.stats=clear\n\tlctl set_param -n osc.*.stats=clear\n\tdd if=/dev/zero of=$DIR2/$tdir/dom bs=2048K count=1 || return 1\n\n\t# check that size is merged from MDT and OST correctly\n\t$CHECKSTAT -t file -s 2097152 $DIR/$tdir/dom ||\n\t\terror \"Wrong size from stat #1\"\n\n\tlocal gls=$(lctl get_param -n osc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls -eq 0 ] && error \"Expect OST glimpse RPCs but got none\"\n\n\trm -f $dom\n}\nrun_test 100c \"DoM: write vs stat without IO lock (combined file)\"\n\ntest_100d() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR/$tdir/dom\n\n\n\tdd if=/dev/zero of=$DIR2/$tdir/dom bs=2048K count=1 || return 1\n\tlctl set_param -n mdc.*.stats=clear\n\t$TRUNCATE $DIR2/$tdir/dom 4096\n\n\t# check that reported size is valid after file grows to OST and\n\t# is truncated back to MDT stripe size\n\t$CHECKSTAT -t file -s 4096 $DIR/$tdir/dom ||\n\t\terror \"Wrong size from stat #1\"\n\n\tlocal gls=$(lctl get_param -n osc.*.stats | grep -c ldlm_glimpse)\n\t[ $gls -eq 0 ] && error \"Expect OST glimpse but got none\"\n\n\trm -f $dom\n}\nrun_test 100d \"DoM: write+truncate vs stat without IO lock (combined file)\"\n\ntest_100e() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.50) ] &&\n\t\tskip \"Need MDS version at least 2.11.50\"\n\n\tlocal dom=$DIR/$tdir/dom\n\tlocal dom2=$DIR2/$tdir/dom\n\tmkdir -p $DIR/$tdir\n\n\t$LFS setstripe -E 1024K -L mdt $DIR/$tdir\n\n\tcancel_lru_locks mdc\n\tdd if=/dev/urandom of=$dom bs=12000 count=1\n\t$TRUNCATE $dom2 6000\n\tcancel_lru_locks mdc\n\tlctl set_param -n mdc.*.stats=clear\n\t# expect read-on-open to return all data before write\n\tcat /etc/hosts >> $dom\n\tlocal read=$(lctl get_param -n mdc.*.stats | grep -c ost_read)\n\t[[ $read -eq 0 ]] || error \"Unexpected $read READ RPCs\"\n}\nrun_test 100e \"DoM: read on open and file size\"\n\ntest_101a() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR1/$tfile\n\t# to get layout\n\t$CHECKSTAT -t file $DIR1/$tfile\n\n\tlocal old_wb=$(sysctl -n vm.dirty_writeback_centisecs)\n\tsysctl -wq vm.dirty_writeback_centisecs=0\n\n\ttrap \"sysctl -wq vm.dirty_writeback_centisecs=$old_wb\" EXIT\n\n\t# open + IO lock\n\tdd if=/dev/zero of=$DIR1/$tfile bs=4096 count=1 ||\n\t\terror_noexit \"Write fails\"\n\t# must discard pages\n\tlctl set_param -n mdc.*.stats=clear\n\trm $DIR2/$tfile || error \"Unlink fails\"\n\n\tlocal writes=$(lctl get_param -n mdc.*.stats | grep -c ost_write)\n\t[ $writes -eq 0 ] || error \"Found WRITE RPC but expect none\"\n}\nrun_test 101a \"Discard DoM data on unlink\"\n\ntest_101b() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR1/$tfile\n\ttouch $DIR1/${tfile}_2\n\t# to get layout\n\t$CHECKSTAT -t file $DIR1/$tfile\n\n\tlocal old_wb=$(sysctl -n vm.dirty_writeback_centisecs)\n\tsysctl -wq vm.dirty_writeback_centisecs=0\n\n\ttrap \"sysctl -wq vm.dirty_writeback_centisecs=$old_wb\" EXIT\n\n\t# open + IO lock\n\tdd if=/dev/zero of=$DIR1/$tfile bs=4096 count=1 || error \"Write fails\"\n\t# must discard pages\n\tlctl set_param -n mdc.*.stats=clear\n\tmv $DIR2/${tfile}_2 $DIR2/$tfile || error \"Rename fails\"\n\n\tlocal writes=$(lctl get_param -n mdc.*.stats | grep -c ost_write)\n\t[ $writes -eq 0 ] || error \"Found WRITE RPC but expect none\"\n}\nrun_test 101b \"Discard DoM data on rename\"\n\ntest_101c() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.10.55) ] &&\n\t\tskip \"Need MDS version at least 2.10.55\"\n\n\t$LFS setstripe -E 1024K -L mdt -E EOF $DIR1/$tfile\n\t# to get layout\n\t$CHECKSTAT -t file $DIR1/$tfile\n\n\tlocal old_wb=$(sysctl -n vm.dirty_writeback_centisecs)\n\tsysctl -wq vm.dirty_writeback_centisecs=0\n\n\ttrap \"sysctl -wq vm.dirty_writeback_centisecs=$old_wb\" EXIT\n\n\t# open + IO lock\n\tdd if=/dev/zero of=$DIR1/$tfile bs=4096 count=1 || error \"Write fails\"\n\t$MULTIOP $DIR1/$tfile O_c &\n\tMULTIOP_PID=$!\n\tsleep 1\n\tlctl set_param -n mdc.*.stats=clear\n\trm $DIR2/$tfile > /dev/null || error \"Unlink fails for opened file\"\n\tkill -USR1 $MULTIOP_PID && wait $MULTIOP_PID || error \"multiop failure\"\n\n\tlocal writes=$(lctl get_param -n mdc.*.stats | grep -c ost_write)\n\t[ $writes -eq 0 ] || error \"Found WRITE RPC but expect none\"\n}\nrun_test 101c \"Discard DoM data on close-unlink\"\n\n# test to verify file handle related system calls\n# (name_to_handle_at/open_by_handle_at)\n# The new system calls are supported in glibc >= 2.14.\n\n# test to verify we can open by handle an unlinked file from > 1 client\n# This test opens the file normally on $DIR1, which is on one mount, and then\n# opens it by handle on $DIR2, which is on a different mount.\ntest_102() {\n\t[ \"$MDS1_VERSION\" -lt $(version_code 2.11.57) ] &&\n\t\tskip \"Needs MDS version 2.11.57 or later\"\n\n\techo \"Test file_handle syscalls\" > $DIR/$tfile ||\n\t\terror \"write failed\"\n\tcheck_fhandle_syscalls $DIR/$tfile $DIR2 ||\n\t\terror \"check_fhandle_syscalls failed\"\n\trm -f $DIR2/$tfile\n}\nrun_test 102 \"Test open by handle of unlinked file\"\n\n# Compare file size between first & second mount, ensuring the client correctly\n# glimpses even with unused speculative locks - LU-11670\ntest_103() {\n\t[ $OST1_VERSION -lt $(version_code 2.10.50) ] &&\n\t\tskip \"Lockahead needs OST version at least 2.10.50\"\n\n\tlocal locktest=23\n\n\ttest_mkdir -p $DIR/$tdir\n\n\t# Force file on to OST0\n\t$LFS setstripe -i 0 $DIR/$tdir\n\n\t# Do not check multiple locks on glimpse\n\t# OBD_FAIL_OSC_NO_SIZE_DATA 0x415\n\t$LCTL set_param fail_loc=0x415\n\n\t# Delay write commit by 2 seconds to guarantee glimpse wins race\n\t# The same fail_loc is used on client & server so it can work in the\n\t# single node sanity setup\n\tdo_facet ost1 $LCTL set_param fail_loc=0x415 fail_val=2\n\n\techo \"Incorrect size expected (no glimpse fix):\"\n\tlockahead_test -d $DIR/$tdir -D $DIR2/$tdir -t $locktest -f $tfile\n\trc=$?\n\tif [ $rc -eq 0 ]; then\n\t\techo \"This doesn't work 100%, but this is just reproducing the bug, not testing the fix, so OK to not fail test.\"\n\tfi\n\n\t# guarantee write commit timeout has expired\n\tsleep 2\n\n\t# Clear fail_loc on client\n\t$LCTL set_param fail_loc=0\n\n\t# Delay write commit by 2 seconds to guarantee glimpse wins race\n\t# OBD_FAIL_OST_BRW_PAUSE_BULK 0x214\n\tdo_facet ost1 $LCTL set_param fail_loc=0x214 fail_val=2\n\n\t# Write commit is still delayed by 2 seconds\n\tlockahead_test -d $DIR/$tdir -D $DIR2/$tdir -t $locktest -f $tfile\n\trc=$?\n\t[ $rc -eq 0 ] || error \"Lockahead test$locktest failed, $rc\"\n\n\t# guarantee write commit timeout has expired\n\tsleep 2\n\n\trm -f $DIR/$tfile || error \"unable to delete $DIR/$tfile\"\n}\nrun_test 103 \"Test size correctness with lockahead\"\n\nget_stat_xtimes()\n{\n\tlocal xtimes\n\n\txtimes=$(stat -c \"%X %Y %Z\" $DIR/$tfile)\n\n\techo ${xtimes[*]}\n}\n\nget_mdt_xtimes()\n{\n\tlocal mdtdev=$1\n\tlocal output\n\tlocal xtimes\n\n\toutput=$(do_facet mds1 \"$DEBUGFS -c -R 'stat ROOT/$tfile' $mdtdev\")\n\t((xtimes[0]=$(awk -F ':' /atime/'{ print $2 }' <<< \"$output\")))\n\t((xtimes[1]=$(awk -F ':' /mtime/'{ print $2 }' <<< \"$output\")))\n\t((xtimes[2]=$(awk -F ':' /ctime/'{ print $2 }' <<< \"$output\")))\n\n\techo ${xtimes[*]}\n}\n\ncheck_mdt_xtimes()\n{\n\tlocal mdtdev=$1\n\tlocal xtimes=($(get_stat_xtimes))\n\tlocal mdt_xtimes=($(get_mdt_xtimes $mdtdev))\n\n\techo \"STAT a|m|ctime ${xtimes[*]}\"\n\techo \"MDT a|m|ctime ${xtimes[*]}\"\n\t[[ ${xtimes[0]} == ${mdt_xtimes[0]} ]] ||\n\t\terror \"$DIR/$tfile atime (${xtimes[0]}:${mdt_xtimes[0]}) diff\"\n\t[[ ${xtimes[1]} == ${mdt_xtimes[1]} ]] ||\n\t\terror \"$DIR/$tfile mtime (${xtimes[1]}:${mdt_xtimes[1]}) diff\"\n\t[[ ${xtimes[2]} == ${mdt_xtimes[2]} ]] ||\n\t\terror \"$DIR/$tfile ctime (${xtimes[2]}:${mdt_xtimes[2]}) diff\"\n}\n\ntest_104() {\n\t[ \"$mds1_FSTYPE\" == \"ldiskfs\" ] || skip_env \"ldiskfs only test\"\n\t[ $MDS1_VERSION -lt $(version_code 2.12.4) ] &&\n\t\tskip \"Need MDS version at least 2.12.4\"\n\n\tlocal pid\n\tlocal mdtdev=$(mdsdevname ${SINGLEMDS//mds/})\n\tlocal atime_diff=$(do_facet $SINGLEMDS \\\n\t\tlctl get_param -n mdd.*MDT0000*.atime_diff)\n\n\tdo_facet $SINGLEMDS \\\n\t\tlctl set_param -n mdd.*MDT0000*.atime_diff=0\n\n\tstack_trap \"do_facet $SINGLEMDS \\\n\t\tlctl set_param -n mdd.*MDT0000*.atime_diff=$atime_diff\" EXIT\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1k count=1 conv=notrunc\n\tcheck_mdt_xtimes $mdtdev\n\tsleep 2\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1k count=1 conv=notrunc\n\tcheck_mdt_xtimes $mdtdev\n\tsleep 2\n\t$MULTIOP $DIR2/$tfile Oz8192w8192_c &\n\tpid=$!\n\tsleep 2\n\tdd if=/dev/zero of=$DIR/$tfile bs=1k count=1 conv=notrunc\n\tsleep 2\n\tkill -USR1 $pid && wait $pid || error \"multiop failure\"\n\tcheck_mdt_xtimes $mdtdev\n\n\tlocal xtimes\n\tlocal mdt_xtimes\n\n\t# Verify mtime/ctime is NOT upated on MDS when there is no modification\n\t# on the client side\n\txtimes=($(get_stat_xtimes))\n\t$MULTIOP $DIR/$tfile O_c &\n\tpid=$!\n\tsleep 2\n\tkill -USR1 $pid && wait $pid || error \"multiop failure\"\n\tmdt_xtimes=($(get_mdt_xtimes $mdtdev))\n\t[[ ${xtimes[1]} == ${mdt_xtimes[1]} ]] ||\n\t\terror \"$DIR/$tfile mtime (${xtimes[1]}:${mdt_xtimes[1]}) diff\"\n\t[[ ${xtimes[2]} == ${mdt_xtimes[2]} ]] ||\n\t\terror \"$DIR/$tfile ctime (${xtimes[2]}:${mdt_xtimes[2]}) diff\"\n\tcheck_mdt_xtimes $mdtdev\n\n\tsleep 2\n\t# Change ctime via chmod\n\t$MULTIOP $DIR/$tfile o_tc &\n\tpid=$!\n\tsleep 2\n\tkill -USR1 $pid && wait $pid || error \"multiop failure\"\n\tcheck_mdt_xtimes $mdtdev\n}\nrun_test 104 \"Verify that MDS stores atime/mtime/ctime during close\"\n\ntest_105() {\n\ttest_mkdir -p $DIR/$tdir\n\techo test > $DIR/$tdir/$tfile\n\t$LCTL set_param fail_loc=0x416\n\tcancel_lru_locks osc & sleep 1\n\tfsize1=$(stat -c %s $DIR2/$tdir/$tfile)\n\twait\n\t[[ $fsize1 = 5 ]] ||  error \"Glimpse returned wrong file size $fsize1\"\n}\nrun_test 105 \"Glimpse and lock cancel race\"\n\ntest_106a() {\n\t[ \"$mds1_FSTYPE\" == \"ldiskfs\" ] && statx_supported ||\n\t\tskip_env \"Test only for ldiskfs and statx() supported\"\n\n\tlocal btime\n\tlocal mdt_btime\n\tlocal output\n\tlocal mdtdev=$(mdsdevname ${SINGLEMDS//mds/})\n\n\tdd if=/dev/zero of=$DIR/$tfile bs=1k count=1 conv=notrunc\n\tbtime=$($STATX -c %W $DIR/$tfile)\n\toutput=$(do_facet mds1 \"$DEBUGFS -c -R 'stat ROOT/$tfile' $mdtdev\")\n\techo $output\n\t((mdt_btime=$(awk -F ':' /crtime/'{ print $2 }' <<< \"$output\")))\n\t[[ $btime == $mdt_btime ]] ||\n\t\terror \"$DIR/$tfile btime ($btime:$mdt_btime) diff\"\n\n}\nrun_test 106a \"Verify the btime via statx()\"\n\ntest_106b() {\n\tstatx_supported || skip_env \"statx() only test\"\n\n\tlocal rpcs_before\n\tlocal rpcs_after\n\n\t$LFS setstripe -c 1 $DIR/$tfile || error \"$DIR/$tfile setstripe failed\"\n\tdd if=/dev/zero of=$DIR/$tfile bs=1k count=1 conv=notrunc\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t$STATX $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $((rpcs_before + 1)) ] ||\n\t\terror \"$STATX should send 1 glimpse RPC to $OSC\"\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t# %n: FILENAME; %i: STATX_INO; %A STATX_MODE; %h STATX_NLINK;\n\t# %u: STATX_UID; %g: STATX_GID; %W STATX_BTIME; %X STATX_ATIME;\n\t# %Z: STATX_CTIME\n\t$STATX -c \"%n %i %A %h %u %g %W %X %Z\" $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $rpcs_before ] ||\n\t\terror \"$STATX should not send glimpse RPCs to $OSC\"\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t$STATX --cached=always $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $rpcs_before ] ||\n\t\terror \"$STATX should not send glimpse RPCs to $OSC\"\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t$STATX -c %Y $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $((rpcs_before + 1)) ] ||\n\t\terror \"$STATX -c %Y should send 1 glimpse RPC to $OSC\"\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t$STATX -c %s $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $((rpcs_before + 1)) ] ||\n\t\terror \"$STATX -c %s should send 1 glimpse RPC to $OSC\"\n\n\tcancel_lru_locks $OSC\n\trpcs_before=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t$STATX -c %b $DIR/$tfile\n\trpcs_after=$(calc_stats $OSC.*$OSC*.stats ldlm_glimpse_enqueue)\n\t[ $rpcs_after -eq $((rpcs_before + 1)) ] ||\n\t\terror \"$STATX -c %b should send 1 glimpse RPC to $OSC\"\n}\nrun_test 106b \"Glimpse RPCs test for statx\"\n\ntest_106c() {\n\tstatx_supported || skip_env \"statx() only test\"\n\n\tlocal mask\n\n\ttouch $DIR/$tfile\n\t# Mask supported in stx_attributes by Lustre is\n\t# STATX_ATTR_IMMUTABLE(0x10) | STATX_ATTR_APPEND(0x20) : (0x30).\n\tmask=$($STATX -c %p $DIR/$tfile)\n\t[[ $mask == \"30\" ]] ||\n\t\terror \"supported stx_attributes: got '$mask', expected '30'\"\n\tchattr +i $DIR/$tfile || error \"chattr +i $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"10\" ]] ||\n\t\terror \"got immutable flags '$mask', expected '10'\"\n\tchattr -i $DIR/$tfile || error \"chattr -i $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"0\" ]] || error \"got flags '$mask', expected '0'\"\n\tchattr +a $DIR/$tfile || error \"chattr +a $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"20\" ]] || error \"got flags '$mask', expected '20'\"\n\tchattr -a $DIR/$tfile || error \"chattr -a $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"0\" ]] || error \"got flags '$mask', expected '0'\"\n\tchattr +ia $DIR/$tfile || error \"chattr +ia $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"30\" ]] || error \"got flags '$mask', expected '30'\"\n\tchattr -ia $DIR/$tfile || error \"chattr -ia $DIR/$tfile failed\"\n\tmask=$($STATX -c %r $DIR/$tfile)\n\t[[ $mask == \"0\" ]] || error \"got flags '$mask', expected '0'\"\n}\nrun_test 106c \"Verify statx attributes mask\"\n\ntest_107() { # LU-1031\n\tdd if=/dev/zero of=$DIR1/$tfile bs=1M count=10\n\tlocal gid1=14091995\n\tlocal gid2=16022000\n\n\t$LFS getstripe $DIR1/$tfile\n\n\tmultiop_bg_pause $DIR1/$tfile OG${gid1}_g${gid1}c || return 1\n\tlocal MULTIPID1=$!\n\tmultiop_bg_pause $DIR2/$tfile O_G${gid2}r10g${gid2}c || return 2\n\tlocal MULTIPID2=$!\n\tkill -USR1 $MULTIPID2\n\tsleep 2\n\tif [[ `ps h -o comm -p $MULTIPID2` == \"\" ]]; then\n\t\terror \"First grouplock does not block second one\"\n\telse\n\t\techo \"First grouplock blocks second one\"\n\tfi\n\tkill -USR1 $MULTIPID1\n\twait $MULTIPID1\n\twait $MULTIPID2\n}\nrun_test 107 \"Basic grouplock conflict\"\n\nlog \"cleanup: ======================================================\"\n\n# kill and wait in each test only guarentee script finish, but command in script\n# like 'rm' 'chmod' may still be running, wait for all commands to finish\n# otherwise umount below will fail\n[ \"$(mount | grep $MOUNT2)\" ] && wait_update $HOSTNAME \"fuser -m $MOUNT2\" \"\" ||\n\ttrue\n\ncomplete $SECONDS\nrm -f $SAMPLE_FILE\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 5334}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nONLY=${ONLY:-\"$*\"}\nALWAYS_EXCEPT=\"$SCRUB_PERFORMANCE_EXCEPT\"\n[ \"$SLOW\" = \"no\" ] && EXCEPT_SLOW=\"\"\n# UPDATE THE COMMENT ABOVE WITH BUG NUMBERS WHEN CHANGING ALWAYS_EXCEPT!\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n[ \"$SLOW\" = \"no\" ] &&\n\tskip \"skip scrub performance test under non-SLOW mode\" && exit 0\n\n[ \"$mds1_FSTYPE\" != ldiskfs ] &&\n\tskip \"ldiskfs only test\"\n[[ \"$MDS1_VERSION\" -lt $(version_code 2.2.90) ]] &&\n\tskip \"Need MDS version at least 2.2.90\"\nrequire_dsh_mds || exit 0\n\nNTHREADS=${NTHREADS:-0}\nUNIT=${UNIT:-1048576}\nBACKUP=${BACKUP:-0}\nMINCOUNT=${MINCOUNT:-8192}\nMAXCOUNT=${MAXCOUNT:-32768}\nFACTOR=${FACTOR:-2}\n\nRCMD=\"do_facet ${SINGLEMDS}\"\nRLCTL=\"${RCMD} ${LCTL}\"\nMDT_DEV=\"${FSNAME}-MDT0000\"\nMDT_DEVNAME=$(mdsdevname ${SINGLEMDS//mds/})\nSHOW_SCRUB=\"${RLCTL} get_param -n osd-ldiskfs.${MDT_DEV}.oi_scrub\"\nremote_mds && ECHOCMD=${RCMD} || ECHOCMD=\"eval\"\n\nif [ ${NTHREADS} -eq 0 ]; then\n\tCPUCORE=$(${RCMD} cat /proc/cpuinfo | grep \"processor.*:\" | wc -l)\n\tNTHREADS=$((CPUCORE * 2))\nfi\n\ncleanupall\n\nif ! combined_mgs_mds ; then\n\tdo_rpc_nodes $(facet_active_host mgs) load_modules_local\n\tadd mgs $(mkfs_opts mgs $(mgsdevname)) --backfstype ldiskfs \\\n\t\t--reformat $(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} ||\n\t\texit 1\n\n\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS || error \"Fail to start MGS!\"\nfi\n\ndo_rpc_nodes $(facet_active_host $SINGLEMDS) load_modules_local\nreformat_external_journal ${SINGLEMDS}\nadd ${SINGLEMDS} $(mkfs_opts ${SINGLEMDS} ${MDT_DEVNAME}) --backfstype ldiskfs \\\n\t--reformat ${MDT_DEVNAME} $(mdsvdevname 1) ${quiet:+>/dev/null} ||\n\texit 2\n\nscrub_attach() {\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tattach echo_client scrub-MDT0000 scrub-MDT0000_UUID\n\t\tsetup ${MDT_DEV} mdd\n\tEOF\"\n}\n\nscrub_detach() {\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tdevice scrub-MDT0000\n\t\tcleanup\n\t\tdetach\n\tEOF\"\n}\n\nscrub_create() {\n\tlocal echodev=$(${RLCTL} dl | grep echo_client|awk '{print $1}')\n\tlocal j\n\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tcfg_device ${echodev}\n\t\ttest_mkdir ${tdir}\n\tEOF\"\n\n\tfor ((j=1; j<${threads}; j++)); do\n\t\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\t\tcfg_device ${echodev}\n\t\t\ttest_mkdir ${tdir}${j}\n\t\tEOF\"\n\tdone\n\n\t${ECHOCMD} \"${LCTL} <<-EOF\n\t\tcfg_device ${echodev}\n\t\t--threads ${threads} 0 ${echodev} test_create \\\n\t\t-d ${tdir} -D ${threads} -b ${lbase} -c 0 -n ${usize}\n\tEOF\"\n}\n\nscrub_cleanup() {\n\tcleanupall\n\tdo_rpc_nodes $(facet_active_host $SINGLEMDS) unload_modules\n\tif ! combined_mgs_mds ; then\n\t\tdo_rpc_nodes $(facet_active_host mgs) unload_modules\n\tfi\n\tREFORMAT=\"yes\" cleanup_and_setup_lustre\n}\n\nscrub_create_nfiles() {\n\tlocal total=$1\n\tlocal lbase=$2\n\tlocal threads=$3\n\tlocal ldir=\"/test-${lbase}\"\n\tlocal cycle=0\n\tlocal count=${UNIT}\n\n\twhile true; do\n\t\t[ ${count} -eq 0 -o  ${count} -gt ${total} ] && count=${total}\n\t\tlocal usize=$((count / NTHREADS))\n\t\t[ ${usize} -eq 0 ] && break\n\t\tlocal tdir=${ldir}-${cycle}-\n\n\t\techo \"[cycle: ${cycle}] [threads: ${threads}]\"\\\n\t\t     \"[files: ${count}] [basedir: ${tdir}]\"\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MDS_MOUNT_OPTS ||\n\t\t\terror \"Fail to start MDS!\"\n\t\tscrub_attach\n\t\tscrub_create\n\t\tscrub_detach\n\t\tstop ${SINGLEMDS} || error \"Fail to stop MDS!\"\n\n\t\ttotal=$((total - usize * NTHREADS))\n\t\t[ ${total} -eq 0 ] && break\n\t\tlbase=$((lbase + usize))\n\t\tcycle=$((cycle + 1))\n\tdone\n}\n\nbuild_test_filter\n\ntest_0() {\n\tlocal BASECOUNT=0\n\tlocal i\n\n\tfor ((i=$MINCOUNT; i<=$MAXCOUNT; i=$((i * FACTOR)))); do\n\t\tlocal nfiles=$((i - BASECOUNT))\n\t\tlocal stime=$(date +%s)\n\n\t\techo \"+++ start to create for ${i} files set at: $(date) +++\"\n\t\tscrub_create_nfiles ${nfiles} ${BASECOUNT} ${NTHREADS} ||\n\t\t\terror \"Fail to create files!\"\n\t\techo \"+++ end to create for ${i} files set at: $(date) +++\"\n\t\tlocal etime=$(date +%s)\n\t\tlocal delta=$((etime - stime))\n\t\t[ $delta -gt 0 ] || delta=1\n\t\techo \"create ${nfiles} files used ${delta} seconds\"\n\t\techo \"create speed is $((nfiles / delta))/sec\"\n\n\t\tBASECOUNT=${i}\n\t\tif [ ${BACKUP} -ne 0 ]; then\n\t\t\tstime=$(date +%s)\n\t\t\techo \"backup/restore ${i} files start at: $(date)\"\n\t\t\tmds_backup_restore $SINGLEMDS ||\n\t\t\t\terror \"Fail to backup/restore!\"\n\t\t\techo \"backup/restore ${i} files end at: $(date)\"\n\t\t\tetime=$(date +%s)\n\t\t\tdelta=$((etime - stime))\n\t\t\t[ $delta -gt 0 ] || delta=1\n\t\t\techo \"backup/restore ${i} files used ${delta} seconds\"\n\t\t\techo \"backup/restore speed is $((i / delta))/sec\"\n\t\telse\n\t\t\tmds_remove_ois $SINGLEMDS ||\n\t\t\t\terror \"Fail to remove/recreate!\"\n\t\tfi\n\n\t\techo \"--- start to rebuild OI for $i files set at: $(date) ---\"\n\t\tstart ${SINGLEMDS} $MDT_DEVNAME $MDS_MOUNT_OPTS > /dev/null ||\n\t\t\terror \"Fail to start MDS!\"\n\n\t\twhile true; do\n\t\t\tlocal STATUS=$($SHOW_SCRUB |\n\t\t\t\t\tawk '/^status/ { print $2 }')\n\t\t\t[ \"$STATUS\" == \"completed\" ] && break\n\t\t\tsleep 3 # check status every 3 seconds\n\t\tdone\n\n\t\techo \"--- end to rebuild OI for ${i} files set at: $(date) ---\"\n\t\tlocal RTIME=$($SHOW_SCRUB | awk '/^run_time/ { print $2 }')\n\t\techo \"rebuild OI for ${i} files used ${RTIME} seconds\"\n\t\tlocal SPEED=$($SHOW_SCRUB | awk '/^average_speed/ { print $2 }')\n\t\techo \"rebuild speed is ${SPEED}/sec\"\n\t\tstop ${SINGLEMDS} > /dev/null || error \"Fail to stop MDS!\"\n\tdone\n}\nrun_test 0 \"OI scrub performance test\"\n\n# cleanup the system at last\nscrub_cleanup\ncomplete $SECONDS\ncheck_and_cleanup_lustre\nexit_status\n", "num_lines": 201}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Requires the pre-configured samba machine\n# RPMS required are :\n# server:\n#      samba\n#      samba-common\n#      cifs-utils\n# clients:\n#      samba-client\n#      samba-common\n#      cifs-utils\n\n#set -vx\n\nsmb_status() {\n\tlocal smbsrv=${1}\n\tlocal rc=0\n\n\tdo_node $smbsrv \"service smb status\" || rc=$?\n\treturn $rc\n}\n\nconfigure_smb() {\n\tlocal smbsrv=${1}\n\tlocal smbshare=${2}\n\tlocal smbuser=${3}\n\tlocal smbpasswd=${4}\n\tlocal path=${5}\n\tlocal smbconftmp=${6}\n\tlocal smbconf\n\tlocal path\n\n\tsmbconf=$(do_node $smbsrv \\\n\t\tsmbd -b | grep CONFIGFILE | sed -re 's/\\s+CONFIGFILE: //g')\n\tgrep -q $smbshare $smbconf && return\n\n\tdo_node $smbsrv \"cp $smbconf $smbconftmp\"\n\tdo_node $smbsrv \"cat <<EOF >> $smbconf\n\t[$smbshare]\n\tpath = $path\n\tbrowseable = yes\n\twritable = yes\n\tguest ok = yes\n\twrite list = $smbuser\nEOF\"\n\t# The samba daemons are constantly (once every 60 seconds) checking the\n\t# smb.conf file, so it is good practice to keep this file small.\n\tlocal smbsmall=$(do_nodes $smbsrv \"mktemp -t smb.conf.small.XXX\")\n\tdo_node $smbsrv \"testparm -s >$smbsmall\"\n\tdo_node $smbsrv \"testparm -s $smbsmall >$smbconf\"\n\n\tdo_node $smbsrv \"echo $smbpasswd | tee - | smbpasswd -a $smbuser -s\"\n}\n\nrestore_config_smb() {\n\tlocal smbsrv=${1}\n\tlocal smbconftmp=${2}\n\tlocal smbconf\n\n\tsmbconf=$(do_node $smbsrv \\\n\t\tsmbd -b | grep CONFIGFILE | sed -re 's/\\s+CONFIGFILE: //g')\n\n\techo -e \"\\nRestoring smb config from $smbconftmp ...\"\n\tdo_node $smbsrv \"cp $smbconftmp $smbconf\"\n}\n\nsetup_cifs() {\n\tlocal smbsrv=${1}\n\tlocal smbshare=${2}\n\tlocal smbclimntpt=${3}\n\tlocal smbuser=${4}\n\tlocal smbpasswd=${5}\n\tlocal smbclients=${6}\n\n\tdo_node $smbsrv \"service smb restart\" || return 1\n\tlocal parameter_path=$(do_node $smbsrv \\\n\t\t\"testparm -s --section-name $smbshare --parameter-name path 2> /dev/null\")\n\t[[ -z $parameter_path ]] && return 1\n\tdo_nodesv $smbsrv \"chmod a+xrw $parameter_path\"\n\tdo_nodesv $smbsrv \"ls -ald $parameter_path\"\n\n\tlocal cmd=\"mount -t cifs //$smbsrv/$smbshare $smbclimntpt -o user=$smbuser,pass=$smbpasswd\"\n\techo -e \"\\nMounting CIFS clients $smbclients : $cmd\"\n\tdo_nodesv $smbclients \"$cmd\" || return 1\n\tdo_nodesv $smbclients mount | grep $smbclimntpt\n}\n\ncleanup_cifs() {\n\tlocal smbsrv=${1}\n\tlocal smbclimntpt=${2}\n\tlocal smbclients=${3}\n\n\techo -e \"\\nUnmounting CIFS clients...\"\n\tdo_nodes $smbclients \"umount -f $smbclimntpt\" || return 1\n\tdo_node $smbsrv \"service smb stop\"\n}\n", "num_lines": 98}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\nEXPORT_OPTS=${EXPORT_OPTS:-\"rw,async,no_root_squash\"}\n\nsetup_nfs() {\n\tlocal NFS_VER=${1}\n\tlocal MNTPNT=${2}\n\tlocal LUSTRE_CLIENT=${3}\n\tlocal NFS_CLIENTS=${4}\n\tlocal nfs_climntpt=${5:-$MNTPNT}\n\n    local export_opts_v=$EXPORT_OPTS\n\n    echo \"Exporting Lustre filesystem...\"\n\n    if [ \"$NFS_VER\" = \"4\" ]; then\n        export_opts_v=\"$EXPORT_OPTS,fsid=0\"\n        do_nodes $LUSTRE_CLIENT \"mkdir -p /var/lib/nfs/v4recovery\"\n    fi\n\n    do_nodes $LUSTRE_CLIENT,$NFS_CLIENTS \"grep -q rpc_pipefs' ' /proc/mounts ||\\\n        { mkdir -p /var/lib/nfs/rpc_pipefs && \\\n        mount -t rpc_pipefs sunrpc /var/lib/nfs/rpc_pipefs; }\" || return 1\n    sleep 5\n\n\tdo_nodes $LUSTRE_CLIENT \"echo $MNTPNT *\\($export_opts_v\\) \\\n\t\t\t\t >> /etc/exports\" || return 1\n\n\t# restart nfs server according to distro\n\tdo_nodes $LUSTRE_CLIENT \"{ [[ -e /etc/SuSE-release ]] &&\n\t\t\t\t service nfsserver restart; } ||\n\t\t\t\t service nfs restart ||\n\t\t\t\t service nfs-server restart\" || return 1\n\n\tdo_nodes $NFS_CLIENTS \"chkconfig --list rpcidmapd 2>/dev/null |\n\t\t\t       grep -q rpcidmapd && service rpcidmapd restart ||\n\t\t\t       true\"\n\n\techo -e \"\\nMounting NFS clients (version $NFS_VER)...\"\n\n\tdo_nodes $NFS_CLIENTS \"mkdir -p $nfs_climntpt\" || return 1\n\tif [ \"$NFS_VER\" = \"4\" ]; then\n\t\tdo_nodes $NFS_CLIENTS \\\n\t\t\t\"mount -t nfs$NFS_VER -o async \\\n\t\t\t$LUSTRE_CLIENT:/ $nfs_climntpt\" || return 1\n\telse\n\t\tdo_nodes $NFS_CLIENTS \\\n\t\t\t\"mount -t nfs -o nfsvers=$NFS_VER,async \\\n\t\t\t$LUSTRE_CLIENT:$MNTPNT $nfs_climntpt\" || return 1\n\tfi\n\treturn 0\n}\n\ncleanup_nfs() {\n\tlocal MNTPNT=${1}\n\tlocal LUSTRE_CLIENT=${2}\n\tlocal NFS_CLIENTS=${3}\n\n\techo -e \"\\nUnmounting NFS clients...\"\n\tdo_nodes $NFS_CLIENTS \"umount -f $MNTPNT\" || true\n\n\techo -e \"\\nUnexporting Lustre filesystem...\"\n\tdo_nodes $NFS_CLIENTS \"chkconfig --list rpcidmapd 2>/dev/null |\n\t\t\t       grep -q rpcidmapd && service rpcidmapd stop ||\n\t\t\t       true\"\n\n\tdo_nodes $LUSTRE_CLIENT \"{ [[ -e /etc/SuSE-release ]] &&\n\t\t\t\t service nfsserver stop; } ||\n\t\t\t\t service nfs stop ||\n\t\t\t\t service nfs-server stop\" || return 1\n\n\tdo_nodes $LUSTRE_CLIENT \"sed -i '/${MNTPNT##*/}/d' /etc/exports\" || return 1\n\n\tdo_nodes $LUSTRE_CLIENT \"exportfs -v\"\n}\n", "num_lines": 76}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# -*- mode: Bash; tab-width: 4; indent-tabs-mode: t; -*-\n# vim:shiftwidth=4:softtabstop=4:tabstop=4:\n\n#\n# setup_kerberos.sh - setup the Kerberos environment on Lustre cluster\n#\n# Notes:\n#  * Only one KDC involved, no slave KDC.\n#  * Only one Kerberos realm involved, no multiple Kerberos realms.\n#\n###############################################################################\n\n# usage\nmy_usage() {\n    cat <<EOF\nUsage: $(basename $0) <KDC_distro> <KDC_node> <MGS_node> <MDS_node>[:MDS_node:...]\n                      <OSS_node>[:OSS_node:...] <CLIENT_node>[:CLIENT_node:...]\n\n    This script is used to setup the Kerberos environment on Lustre cluster.\n\n    KDC_distro      distribution on the KDC node (rhel5 or sles10)\n    KDC_node        KDC node name\n    MGS_node        Lustre MGS node name\n    MDS_node        Lustre MDS node name\n    OSS_node        Lustre OSS node name\n    CLIENT_node     Lustre client node name\n\n    e.g.: $(basename $0) rhel5 scsi2 scsi2 sata2 sata3 client5\n    e.g.: $(basename $0) sles10 scsi2 scsi2 scsi2 sata3:sata5 client2:client3\n    e.g.: $(basename $0) rhel5 scsi2 scsi2 scsi2 scsi2 scsi2\n\n    Notes:\n    1) The script will destroy all the old Kerberos settings by default. If you\n    want to reserve the original krb5.conf and KDC configuration, please set\n    \"RESET_KDC=false\".\n\n    2) The script will create principals for some runas users and add them into\n    the Kerberos database by default. The UIDs of the runas users specified in\n    \"LOCAL_UIDS\" variable need exist on KDC, MDS and Client nodes. If you do not\n    need runas users, please set \"CFG_RUNAS=false\".\n\nEOF\n}\n\n# ************************ Parameters and Variables ************************ #\nMY_KDC_DISTRO=$1\nMY_KDCNODE=$2\nMY_MGSNODE=$3\nMY_MDSNODES=$4\nMY_OSSNODES=$5\nMY_CLIENTNODES=$6\n\n# translate to lower case letters\nMY_KDC_DISTRO=$(echo $MY_KDC_DISTRO | tr '[A-Z]' '[a-z]')\n\nif [ -z \"$MY_KDC_DISTRO\" -o -z \"$MY_KDCNODE\" -o -z \"$MY_MDSNODES\" -o \\\n    -z \"$MY_OSSNODES\" -o -z \"$MY_CLIENTNODES\" -o -z \"$MY_MGSNODE\" ]; then\n    my_usage\n    exit 1\nfi\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nSCP=${SCP:-\"scp -q\"}\nACCEPTOR_PORT=${ACCEPTOR_PORT:-988}\n\n# check and configure runas users\nCFG_RUNAS=${CFG_RUNAS:-true}\n# uids for local users\nLOCAL_UIDS=${LOCAL_UIDS:-\"500 501\"}\n\n# remove the original Kerberos and KDC settings\nRESET_KDC=${RESET_KDC:-true}\n\n# generate unique keytab for each client node\nSPLIT_KEYTAB=${SPLIT_KEYTAB:-true}\n\n# encryption types for generating keytab\nMDS_ENCTYPE=${MDS_ENCTYPE:-\"aes128-cts\"}\nMGS_ENCTYPE=${MGS_ENCTYPE:-\"$MDS_ENCTYPE\"}\nOSS_ENCTYPE=${OSS_ENCTYPE:-\"aes128-cts\"}\nCLIENT_ENCTYPE=${CLIENT_ENCTYPE:-\"aes128-cts\"}\n\n# configuration file for Kerberos\nKRB5_CONF=${KRB5_CONF:-\"/etc/krb5.conf\"}\nKRB5_KEYTAB=${KRB5_KEYTAB:-\"/etc/krb5.keytab\"}\nKRB5_TICKET_LIFETIME=${KRB5_TICKET_LIFETIME:-\"24h\"}\n\n# configuration files for libgssapi and keyutils\nGSSAPI_MECH_CONF=${GSSAPI_MECH_CONF:-\"/etc/gssapi_mech.conf\"}\nREQUEST_KEY_CONF=${REQUEST_KEY_CONF:-\"/etc/request-key.conf\"}\n\n# krb5 realm & domain\nKRB5_REALM=${KRB5_REALM:-\"CO.CFS\"}\nKRB5_DOMAIN=$(echo $KRB5_REALM | tr '[A-Z]' '[a-z]')\n\nMY_MDSNODES=${MY_MDSNODES//:/ }\nMY_OSSNODES=${MY_OSSNODES//:/ }\nMY_CLIENTNODES=${MY_CLIENTNODES//:/ }\n\n# set vars according to the KDC distribution\nKRB5PKG_SVR=\"krb5-server\"\nKRB5PKG_DEV=\"krb5-devel\"\ncase $MY_KDC_DISTRO in\n    rhel5)\n        KRB5PKG_CLI=\"krb5-workstation\"\n        KRB5PKG_LIB=\"krb5-libs\"\n        KDC_CONF_DIR=\"/var/kerberos/krb5kdc\"\n        ;;\n    sles10)\n        KRB5PKG_CLI=\"krb5-client\"\n        KRB5PKG_LIB=\"krb5\"\n        KDC_CONF_DIR=\"/var/lib/kerberos/krb5kdc\"\n        ;;\n    *)\n        echo \"Unsupported KDC distro: $MY_KDC_DISTRO!\"\n        exit 1\nesac\nKDC_CONF=\"$KDC_CONF_DIR/kdc.conf\"\nKDC_ACL=\"$KDC_CONF_DIR/kadm5.acl\"\n\n# ******************************** Functions ******************************** #\nis_part_of() {\n    local name=\"$1\"\n    shift\n    local list=\"$@\"\n\n    if [ -z \"$name\" -o -z \"$list\" ]; then\n        false\n        return\n    fi\n\n    if [[ \" $list \" == *\\ $name\\ * ]]; then\n        true\n    else\n        false\n    fi\n\n    return\n}\n\nmy_do_node() {\n    local node=$1\n    shift\n    local nodename=${node%.$KRB5_DOMAIN}\n    do_node $node \"PATH=\\$PATH:/usr/kerberos/sbin:/usr/kerberos/bin:\\\n/usr/lib/mit/sbin:/usr/lib/mit/bin $@\" | sed \"s/^${nodename}: //\"\n    return ${PIPESTATUS[0]}\n}\n\ndo_node_mute() {\n    local output\n    output=$(my_do_node \"$@\" 2>&1)\n    return ${PIPESTATUS[0]}\n}\n\ndo_kdc() {\n    my_do_node $MY_KDCNODE \"$@\"\n    return ${PIPESTATUS[0]}\n}\n\ndo_kdc_mute() {\n    do_node_mute $MY_KDCNODE \"$@\"\n    return ${PIPESTATUS[0]}\n}\n\n#\n# convert a space-delimited node name list to a canonical name list\n#\nget_fqdn() {\n    local nodename_list=\"$@\"\n    local fqdn_list=\"\"\n    local name\n    local fqdn\n    local rc\n\n    for name in $nodename_list; do\n        fqdn=$(do_kdc \"gethostip -n $name 2>&1\")\n        rc=${PIPESTATUS[0]}\n        if [ $rc -ne 0 ]; then\n            echo \"Can not get the FQDN of node $name: $fqdn\"\n            return $rc\n        fi\n        [ -z \"$fqdn_list\" ] && fqdn_list=\"$fqdn\" \\\n        || fqdn_list=\"$fqdn_list $fqdn\"\n\n    done\n\n    echo \"$fqdn_list\"\n    return 0\n}\n\n#\n# convert MDS/OSS nodes to their canonical name, it required by\n# kerberos. we also convert kdc and client too in order to make\n# node name comparison easier\n#\nnormalize_names() {\n    local rc\n\n    # KDC\n    MY_KDCNODE=$(get_fqdn $MY_KDCNODE)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $MY_KDCNODE\n        return $rc\n    fi\n\n    # MGS node\n    MY_MGSNODE=$(get_fqdn $MY_MGSNODE)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $MY_MGSNODE\n        return $rc\n    fi\n\n    # MDS nodes\n    MY_MDSNODES=$(get_fqdn $MY_MDSNODES)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $MY_MDSNODES\n        return $rc\n    fi\n\n    # OSS nodes\n    MY_OSSNODES=$(get_fqdn $MY_OSSNODES)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $MY_OSSNODES\n        return $rc\n    fi\n\n    # client nodes\n    MY_CLIENTNODES=$(get_fqdn $MY_CLIENTNODES)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $MY_CLIENTNODES\n        return $rc\n    fi\n\n    return 0\n}\n\n#\n# verify remote shell works on all nodes\n#\ncheck_rsh() {\n    local checked=\"\"\n    local node\n\n    echo \"+++ Checking remote shell\"\n\n    for node in $MY_KDCNODE $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES\n    do\n        is_part_of $node $checked && continue\n\n        echo -n \"Checking remote shell on $node...\"\n        do_node_mute $node true || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n\n        checked=\"$checked $node\"\n    done\n}\n\n#\n# verify the entropy (random numbers) on the KDC node, which is\n# used by kdb5_util to create Kerberos database\n#\ncheck_entropy() {\n    local limit=170\n    local avail\n\n    echo \"+++ Checking the entropy on the KDC\"\n\n    echo -n \"Checking $MY_KDCNODE...\"\n    avail=$(do_kdc \"sysctl -n kernel.random.entropy_avail\")\n    local rc=${PIPESTATUS[0]}\n    if [ $rc -eq 0 ]; then\n        if [ $avail -lt $limit ]; then\n            echo -e \"\\nWarning: The entropy on the KDC node is only $avail, \\\nwhich is not enough for kdb5_util to create Kerberos database! \\\nLet's use /dev/urandom!\"\n            do_kdc \"rm -f /dev/random.bak && mv /dev/random{,.bak} && \\\nmknod /dev/random c 1 9\"\n            return ${PIPESTATUS[0]}\n        fi\n    else\n        echo \"Can not get the entropy on the KDC node!\"\n        return $rc\n    fi\n    echo \"OK!\"\n}\n\n#\n# verify runas users and groups\n#\ncheck_users() {\n    local checked=\"\"\n    local node\n    local id\n    local user\n\n    echo \"+++ Checking users and groups\"\n\n    for node in $MY_KDCNODE $MY_MGSNODE $MY_MDSNODES $MY_CLIENTNODES; do\n        is_part_of $node $checked && continue\n\n        for id in $LOCAL_UIDS; do\n            echo -n \"Checking uid/gid $id/$id on $node...\"\n            user=$(my_do_node $node getent passwd | grep :$id:$id: | cut -d: -f1)\n            if [ -z \"$user\" ]; then\n\t\t\t\techo -e \"\\nPlease set LOCAL_UIDS to some users \\\nwhich exist on KDC, MDS and client or add user/group $id/$id on these nodes.\"\n                return 1\n            fi\n            echo \"OK!\"\n        done\n        checked=\"$checked $node\"\n    done\n}\n\ncfg_mount() {\n    local node=$1\n    local dev=$2\n    local dir=$3\n\n    echo -n \"Checking $dev mount on $node...\"\n    if do_node_mute $node \"grep -q $dir' ' /proc/mounts\"; then\n        echo \"OK!\"\n        return 0\n    fi\n\n    if ! do_node_mute $node \"grep -q ^$dev /etc/fstab\"; then\n        my_do_node $node \"echo '$dev $dir $dev defaults 0 0' >> /etc/fstab\" || \\\n            return ${PIPESTATUS[0]}\n    fi\n    my_do_node $node \"mkdir -p $dir && mount $dir\" || true\n\n    if ! do_node_mute $node \"grep -q $dir' ' /proc/mounts\"; then\n        echo \"Failed to mount fs $dev at $dir!\"\n        return 1\n    fi\n    echo \"OK!\"\n}\n\n#\n# configure nfsd mount on MDS and OSS nodes\n#\ncfg_nfs_mount() {\n    local checked=\"\"\n    local node\n\n    echo \"+++ Configuring nfsd mount\"\n\n    for node in $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES; do\n        is_part_of $node $checked && continue\n        cfg_mount $node nfsd /proc/fs/nfsd || return ${PIPESTATUS[0]}\n        checked=\"$checked $node\"\n    done\n}\n\nget_pkgname() {\n    local node=$1\n    local pkg=$2\n\n    my_do_node $node \"rpm -q $pkg 2>&1\" | tail -n1\n    return ${PIPESTATUS[0]}\n}\n\nget_krb5pkgname() {\n    local node=$1\n    local flavor=$2\n\n    my_do_node $node cat /etc/SuSE-release 2>/dev/null | \\\n    grep -q 'Enterprise Server 10'\n    if [ ${PIPESTATUS[1]} -eq 0 ]; then\n        case $flavor in\n            cli) echo \"krb5-client\";;\n            lib) echo \"krb5\";;\n        esac\n    else\n        case $flavor in\n            cli) echo \"krb5-workstation\";;\n            lib) echo \"krb5-libs\";;\n        esac\n    fi\n}\n\ncheck_kdc() {\n    local pkg\n    local rc\n\n    echo \"+++ Checking KDC installation\"\n\n    echo -n \"Checking $MY_KDCNODE...\"\n    pkg=$(get_pkgname $MY_KDCNODE $KRB5PKG_SVR)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo -e \"\\nCan not find $KRB5PKG_SVR package on $MY_KDCNODE: $pkg\"\n        return $rc\n    fi\n    echo \"OK!\"\n}\n\ncheck_krb5() {\n    local checked=\"\"\n    local pkg\n    local rc\n    local krb5pkg_cli\n\n    echo \"+++ Checking Kerberos 5 installation\"\n    for node in $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES; do\n        is_part_of $node $checked && continue\n\n        echo -n \"Checking $node...\"\n        krb5pkg_cli=$(get_krb5pkgname $node cli)\n\n        pkg=$(get_pkgname $node $krb5pkg_cli)\n        rc=${PIPESTATUS[0]}\n        if [ $rc -ne 0 ]; then\n            echo -e \"\\nCan not find $krb5pkg_cli package on $node: $pkg\"\n            return $rc\n        fi\n        echo \"OK!\"\n        checked=\"$checked $node\"\n    done\n}\n\ncheck_libgssapi() {\n    local checked=\"\"\n    local node\n    local pkg\n    local rc\n\n    echo \"+++ Checking libgssapi installation\"\n\n    LIBGSSAPI=$(get_pkgname $MY_KDCNODE libgssapi)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo \"Can not find libgssapi package on $MY_KDCNODE: $LIBGSSAPI\"\n        return $rc\n    fi\n\n    for node in $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES; do\n        is_part_of $node $checked && continue\n\n        echo -n \"Checking $node...\"\n        pkg=$(get_pkgname $node libgssapi)\n        rc=${PIPESTATUS[0]}\n        if [ $rc -ne 0 ]; then\n            echo -e \"\\nCan not find libgssapi package on $node: $pkg\"\n            return $rc\n        fi\n        echo \"OK!\"\n        checked=\"$checked $node\"\n    done\n}\n\n#\n# check and update the /etc/gssapi_mech.conf file on each node\n# We only support MIT Kerberos 5 GSS-API mechanism.\n#\ncfg_libgssapi() {\n    local checked=\"\"\n    local node\n    local pkg\n    local rc\n    local krb5pkg_lib\n    local krb5_lib \n\n    echo \"+++ Updating $GSSAPI_MECH_CONF\"\n\n    for node in $MY_KDCNODE $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES\n    do\n        is_part_of $node $checked && continue\n\n        krb5pkg_lib=$(get_krb5pkgname $node lib)\n        pkg=$(get_pkgname $node $krb5pkg_lib)\n        rc=${PIPESTATUS[0]}\n        if [ $rc -ne 0 ]; then\n            echo -e \"\\nCan not find $krb5pkg_lib package on $node: $pkg\"\n            return $rc\n        fi\n\n        krb5_lib=$(my_do_node $node \"rpm -ql $pkg\" | \\\n                    grep libgssapi_krb5.so | head -n1)\n\n        if ! do_node_mute $node \\\n\"egrep -q \\\\\\\"^$krb5_lib|^$(basename $krb5_lib)\\\\\\\" $GSSAPI_MECH_CONF\"; then\n            do_node_mute $node \\\n\"echo '$krb5_lib mechglue_internal_krb5_init' >> $GSSAPI_MECH_CONF\"\n        fi\n        checked=\"$checked $node\"\n    done\n    echo \"OK!\"\n}\n\n#\n# check and update the /etc/request-key.conf file on each MDS and client node\n#\ncfg_keyutils() {\n    local checked=\"\"\n    local node\n    local lgss_keyring\n\n    echo \"+++ Updating $REQUEST_KEY_CONF\"\n\n    for node in $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES; do\n        is_part_of $node $checked && continue\n        lgss_keyring=$(my_do_node $node \"which lgss_keyring\") || \\\n            return ${PIPESTATUS[0]}\n\n        if ! do_node_mute $node \\\n\"grep -q \\\\\\\"^create.*$lgss_keyring\\\\\\\" $REQUEST_KEY_CONF\"; then\n            do_node_mute $node \\\n\"echo 'create lgssc * * $lgss_keyring %o %k %t %d %c %u %g %T %P %S' \\\n>> $REQUEST_KEY_CONF\"\n        fi\n        checked=\"$checked $node\"\n    done\n    echo \"OK!\"\n}\n\nadd_svc_princ() {\n    local fqdn=$1\n    local type=$2\n\n    echo -n \"Creating service principal lustre_$type/$fqdn@$KRB5_REALM...\"\n    do_kdc_mute \"kadmin.local -r $KRB5_REALM <<EOF\naddprinc -randkey lustre_$type/$fqdn@$KRB5_REALM\nEOF\"\n    local rc=${PIPESTATUS[0]}\n    [ $rc -ne 0 ] && echo \"Failed!\" || echo \"OK!\"\n\n    return $rc\n}\n\nadd_svc_princ_root() {\n    echo -n \"Creating service principal lustre_root@$KRB5_REALM...\"\n    do_kdc_mute \"kadmin.local -r $KRB5_REALM <<EOF\naddprinc -randkey lustre_root@$KRB5_REALM\nEOF\"\n    local rc=${PIPESTATUS[0]}\n    [ $rc -ne 0 ] && echo \"Failed!\" || echo \"OK!\"\n\n    return $rc\n}\n\nadd_user_princ() {\n    local user=$1\n\n    echo -n \"Creating user principal $user@$KRB5_REALM...\"\n    do_kdc_mute \"kadmin.local -r $KRB5_REALM <<EOF\naddprinc -pw $user $user@$KRB5_REALM\nEOF\"\n    local rc=${PIPESTATUS[0]}\n    [ $rc -ne 0 ] && echo \"Failed!\" || echo \"OK!\"\n\n    return $rc\n}\n\nadd_test_princ_id() {\n    local id=$1\n    local user\n\n    user=$(do_kdc getent passwd $id | cut -d: -f1)\n    if [ -z \"$user\" ]; then\n        echo \"Can not find the user with uid $id on the KDC!\"\n        return 1\n    fi\n\n    add_user_princ $user || return ${PIPESTATUS[0]}\n}\n\n#\n# create principals for the client, MDS, OSS, runas users and add them to \n# the Kerberos database\n#\ncfg_kdc_princs() {\n    local node\n\n    add_svc_princ $MY_MGSNODE mgs || return ${PIPESTATUS[0]}\n\n    for node in $MY_MDSNODES; do\n        add_svc_princ $node mds || return ${PIPESTATUS[0]}\n    done\n\n    for node in $MY_OSSNODES; do\n        add_svc_princ $node oss || return ${PIPESTATUS[0]}\n    done\n\n    for node in $MY_CLIENTNODES; do\n        if $SPLIT_KEYTAB; then\n            add_svc_princ $node root || return ${PIPESTATUS[0]}\n        else\n            add_svc_princ_root || return ${PIPESTATUS[0]}\n        fi\n    done\n\n    if ! $SPLIT_KEYTAB; then \n        add_user_princ lustre_root || return ${PIPESTATUS[0]}\n    fi\n    add_user_princ bin || return ${PIPESTATUS[0]}\n    add_user_princ daemon || return ${PIPESTATUS[0]}\n    add_user_princ games || return ${PIPESTATUS[0]}\n\n    if $CFG_RUNAS; then\n        for uid in $LOCAL_UIDS; do\n            add_test_princ_id $uid || return ${PIPESTATUS[0]}\n        done\n    fi\n}\n\n#\n# create and install the KDC configuration file kdc.conf on the KDC, which \n# will destroy the old KDC setting\n#\ncfg_kdc() {\n    local tmpdir=\"$TMP/krb5_cfg_tmp_$UID\"\n    local tmpcfg=$tmpdir/kdc.conf\n    local tmpacl=$tmpdir/kadm5.acl\n\n    echo \"+++ Configuring KDC on $MY_KDCNODE\"\n    echo \"Warning: old KDC setting on $MY_KDCNODE will be destroied!!!\"\n\n    echo -n \"Checking the existence of KDC config dir...\"\n    do_kdc_mute \"[ -d $KDC_CONF_DIR ]\"\n    if [ ${PIPESTATUS[0]} -ne 0 ]; then\n        echo -e \"\\nUnrecognized krb5 distribution!\"\n        return 1\n    else\n        echo \"OK!\"\n    fi\n\n    # stop KDC daemon\n    do_kdc_mute \"/etc/init.d/krb5kdc stop < /dev/null\" || true\n\n    echo -n \"Removing old KDC configurations...\"\n    do_kdc_mute \"rm -f $KDC_CONF_DIR/*\"\n    echo \"OK!\"\n\n    # create kdc.conf locally\n    rm -rf $tmpdir\n    mkdir -p $tmpdir || return ${PIPESTATUS[0]}\n    cat <<EOF > $tmpcfg\n[kdcdefaults]\n acl_file = $KDC_ACL\n\n[realms]\n $KRB5_REALM = {\n  master_key_type = aes128-cts\n  supported_enctypes = des3-hmac-sha1:normal aes128-cts:normal aes256-cts:normal des-cbc-md5:normal\n }\nEOF\n\n    # install kdc.conf remotely\n    echo -n \"Installing kdc.conf on $MY_KDCNODE...\"\n    $SCP $tmpcfg root@$MY_KDCNODE:$KDC_CONF || return ${PIPESTATUS[0]}\n    echo \"OK!\"\n\n    # initialize KDC database\n    echo -n \"Creating Kerberos database on $MY_KDCNODE...\"\n    do_kdc_mute \"kdb5_util create -r $KRB5_REALM -s -P 111111\"\n    local rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo \"Failed!\"\n        return $rc\n    else\n        echo \"OK!\"\n    fi\n\n    # create ACL file locally & install remotely\n    cat <<EOF > $tmpacl\n*/admin@$KRB5_REALM   *\nroot@$KRB5_REALM      *\nEOF\n    echo -n \"Installing kadm5.acl on $MY_KDCNODE...\"\n    $SCP $tmpacl root@$MY_KDCNODE:$KDC_ACL || return ${PIPESTATUS[0]}\n    echo \"OK!\"\n    rm -rf $tmpdir || true\n\n    # start KDC daemon\n    do_kdc \"/etc/init.d/krb5kdc restart < /dev/null\" || return ${PIPESTATUS[0]}\n}\n\n#\n# create and install the Kerberos configuration file krb5.conf on the KDC, \n# client, MDS and OSS\n#\ncfg_krb5_conf() {\n    local tmpdir=\"$TMP/krb5_cfg_tmp_$UID\"\n    local tmpcfg=\"$tmpdir/krb5.conf\"\n    local checked=\"\"\n\n    echo \"+++ Installing krb5.conf on all nodes\"\n\n    # create krb5.conf locally\n    rm -rf $tmpdir\n    mkdir -p $tmpdir || return ${PIPESTATUS[0]}\n    cat <<EOF > $tmpcfg\n[libdefaults]\n default_realm = $KRB5_REALM\n dns_lookup_realm = false\n dns_lookup_kdc = false\n ticket_lifetime = $KRB5_TICKET_LIFETIME\n forwardable = yes\n\n[realms]\n $KRB5_REALM = {\n  kdc = $MY_KDCNODE:88\n  admin_server = $MY_KDCNODE:749\n  default_domain = $KRB5_DOMAIN\n }\n\n[domain_realm]\n .$KRB5_DOMAIN = $KRB5_REALM\n $KRB5_DOMAIN = $KRB5_REALM\n\n[kdc]\n profile = $KDC_CONF\n\n[appdefaults]\n pam = {\n  debug = false\n  forwardable = true\n  krb4_convert = false\n }\nEOF\n\n    # install krb5.conf remotely\n    for node in $MY_KDCNODE $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES\n    do\n        is_part_of $node $checked && continue\n\n        echo -n \"Installing krb5.conf on $node...\"\n        $SCP $tmpcfg root@$node:$KRB5_CONF || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n\n        checked=\"$checked $node\"\n    done\n    rm -rf $tmpdir || true\n}\n\nadd_keytab() {\n    local tab=$1\n    local princ=$2\n    local enctype=$3\n\n    do_kdc_mute \"kadmin.local -r $KRB5_REALM <<EOF\nktadd -k $tab -e $enctype:normal $princ@$KRB5_REALM\nEOF\"\n}\n\nadd_keytab_svc() {\n    local tab=$1\n    local fqdn=$2\n    local type=$3\n    local enctype=$4\n\n    add_keytab $tab lustre_$type/$fqdn $enctype\n}\n\nadd_keytab_root() {\n    local tab=$1\n    local enctype=$2\n\n    add_keytab $tab lustre_root $enctype\n}\n\nmerge_keytab() {\n    local tab=$1\n    local node=$2\n\n    $SCP $tab root@$node:$tab || return ${PIPESTATUS[0]}\n    do_node_mute $node \"ktutil <<EOF\nrkt $tab\nwkt $KRB5_KEYTAB\nEOF\" || return ${PIPESTATUS[0]}\n}\n\n#\n# create and install the keytab file krb5.keytab on the client, MDS and OSS\n#\ncfg_keytab() {\n    local tmptab=\"$TMP/keytab.tmp\"\n    local node\n\n    echo \"+++ Generating keytabs\"\n\n    # remove old keytabs\n    echo -n \"Deleting old keytabs on all nodes...\"\n    for node in $MY_MGSNODE $MY_OSSNODES $MY_MDSNODES $MY_CLIENTNODES; do\n        do_node_mute $node \"rm -f $KRB5_KEYTAB $TMP/krb5cc*\"\n    done\n    echo \"OK!\"\n\n    # install for MDS nodes\n    for node in $MY_MDSNODES; do\n        echo -n \"Preparing for MDS $node...\"\n        do_kdc_mute \"rm -f $tmptab\"\n        add_keytab_svc $tmptab $node mds $MDS_ENCTYPE || return ${PIPESTATUS[0]}\n\n        if is_part_of $node $MY_MGSNODE; then\n            echo -n \"also be an MGS...\"\n            add_keytab_svc $tmptab $node mgs $MGS_ENCTYPE || \\\n                return ${PIPESTATUS[0]}\n        fi\n\n        if is_part_of $node $MY_OSSNODES; then\n            echo -n \"also be an OSS...\"\n            add_keytab_svc $tmptab $node oss $OSS_ENCTYPE || \\\n                return ${PIPESTATUS[0]}\n        fi\n        echo \"OK!\"\n\n        echo -n \"Installing krb5.keytab on $node...\"\n        $SCP root@$MY_KDCNODE:$tmptab $tmptab || return ${PIPESTATUS[0]}\n        $SCP $tmptab root@$node:$KRB5_KEYTAB || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n        rm -f $tmptab\n    done\n\n    # install for MGS node\n    echo -n \"Preparing for MGS $MY_MGSNODE...\"\n    if ! is_part_of $MY_MGSNODE $MY_MDSNODES; then\n        do_kdc_mute \"rm -f $tmptab\"\n        add_keytab_svc $tmptab $MY_MGSNODE mgs $MGS_ENCTYPE || \\\n            return ${PIPESTATUS[0]}\n\n        if is_part_of $MY_MGSNODE $MY_OSSNODES; then\n            echo -n \"also be an OSS...\"\n            add_keytab_svc $tmptab $MY_MGSNODE oss $OSS_ENCTYPE || \\\n                return ${PIPESTATUS[0]}\n        fi\n        echo \"OK!\"\n\n        echo -n \"Installing krb5.keytab on $MY_MGSNODE...\"\n        $SCP root@$MY_KDCNODE:$tmptab $tmptab || return ${PIPESTATUS[0]}\n        $SCP $tmptab root@$MY_MGSNODE:$KRB5_KEYTAB || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n        rm -f $tmptab\n    else\n        echo \"also be an MDS, already done, skip\"\n    fi\n\n    # install for OSS nodes\n    for node in $MY_OSSNODES; do\n        echo -n \"Preparing for OSS $node...\"\n        if is_part_of $node $MY_MDSNODES; then\n            echo \"also be an MDS, already done, skip\"\n        elif is_part_of $node $MY_MGSNODE; then\n            echo \"also be an MGS, already done, skip\"\n        else\n            do_kdc_mute \"rm -f $tmptab\"\n            add_keytab_svc $tmptab $node oss $OSS_ENCTYPE || \\\n                return ${PIPESTATUS[0]}\n            echo \"OK!\"\n\n            echo -n \"Installing krb5.keytab on $node...\"\n            $SCP root@$MY_KDCNODE:$tmptab $tmptab || return ${PIPESTATUS[0]}\n            $SCP $tmptab root@$node:$KRB5_KEYTAB || return ${PIPESTATUS[0]}\n            echo \"OK!\"\n            rm -f $tmptab\n        fi\n    done\n\n    # install for client nodes\n    do_kdc_mute \"rm -f $tmptab\"\n    if ! $SPLIT_KEYTAB; then\n        echo -n \"Preparing for client...\"\n        add_keytab_root $tmptab $CLIENT_ENCTYPE || return ${PIPESTATUS[0]}\n        $SCP root@$MY_KDCNODE:$tmptab $tmptab || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n    else\n        for node in $MY_CLIENTNODES; do\n            echo -n \"Preparing for client $node...\"\n            # don't generate keytabs if it's also an MDS\n            if is_part_of $node $MY_MDSNODES; then\n                echo \"also be an MDS, already done, skip\"\n                continue\n            fi\n\n            add_keytab_svc $tmptab $node root $CLIENT_ENCTYPE || \\\n                return ${PIPESTATUS[0]}\n            $SCP root@$MY_KDCNODE:$tmptab $tmptab || return ${PIPESTATUS[0]}\n            echo \"OK!\"\n        done\n    fi\n    for node in $MY_CLIENTNODES; do\n        echo -n \"Installing krb5.keytab on client $node...\"\n\n        # don't install if it's also an MDS\n        if is_part_of $node $MY_MDSNODES; then\n            echo \"also be an MDS, already done, skip\"\n            continue\n        fi\n\n        # merge keytab if it's also an MGS\n        if is_part_of $node $MY_MGSNODE; then\n            echo -n \"also be an MGS, merging keytab...\"\n            merge_keytab $tmptab $node || return ${PIPESTATUS[0]}\n            echo \"OK!\"\n            continue \n        fi\n\n        # merge keytab if it's also an OSS\n        if is_part_of $node $MY_OSSNODES; then\n            echo -n \"also be an OSS, merging keytab...\"\n            merge_keytab $tmptab $node || return ${PIPESTATUS[0]}\n            echo \"OK!\"\n            continue \n        fi\n\n        # simply install otherwise\n        $SCP $tmptab root@$node:$KRB5_KEYTAB || return ${PIPESTATUS[0]}\n        echo \"OK!\"\n    done\n    rm -f $tmptab || true\n}\n\ncheck_acceptor_port() {\n    local node=$1\n    local port=$2\n\n    if [ -z \"$port\" ]; then\n        echo \"Missing acceptor port!\"\n        return 1\n    fi\n\n    local WAIT=0\n    local MAX_WAIT=300\n    while [ $WAIT -lt $MAX_WAIT ]; do\n        sleep 5\n        my_do_node $node \"netstat -tpan\" | grep -q \":$port .*TIME_WAIT\"\n        if [ ${PIPESTATUS[1]} -ne 0 ]; then\n            return 0\n        fi\n        WAIT=$((WAIT + 5))\n    done\n\n    echo \"LNET acceptor port $port is in use on node $node!\"\n    return 2\n}\n\nget_client_nids() {\n    local client_nids=\"\"\n    local node\n    local nid\n    local local_fqdn\n    local rc\n\n    # get the fqdn of the local host\n    local_fqdn=$(get_fqdn $HOSTNAME)\n    rc=${PIPESTATUS[0]}\n    if [ $rc -ne 0 ]; then\n        echo $local_fqdn\n        return $rc\n    fi\n\n    for node in $MY_CLIENTNODES; do\n        my_do_node $node lsmod | grep -q lnet || \\\n        my_do_node $node \"modprobe lnet\" || {\n            if [ \"$node\" = \"$local_fqdn\" ]; then\n                lsmod | grep -q lnet || load_modules\n            else\n                echo \"Failed to load lnet module on node $node!\"\n                return 1\n            fi\n        }\n\n        check_acceptor_port $node $ACCEPTOR_PORT || return ${PIPESTATUS[0]}\n\n        nid=$(set +x; my_do_node $node \\\n\"$LCTL net up 1>/dev/null && $LCTL list_nids\" 2>&1 | head -n1\nexit ${PIPESTATUS[0]})\n        rc=${PIPESTATUS[0]}\n        if [ $rc -ne 0 ]; then\n            echo \"Failed to get the nid for node $node: $nid\"\n            return $rc\n        fi\n        [ -z \"$client_nids\" ] && client_nids=\"$nid\" \\\n        || client_nids=\"$client_nids $nid\"\n\n        my_do_node $node \"$LCTL net down 1>/dev/null\" || true\n    done\n\n    echo \"$client_nids\"\n    return 0\n}\n\n# ******************************** Main Flow ******************************** #\nnormalize_names || exit ${PIPESTATUS[0]}\ncheck_rsh || exit ${PIPESTATUS[0]}\ncheck_entropy || exit ${PIPESTATUS[0]}\n\nif $CFG_RUNAS; then\n    check_users || exit ${PIPESTATUS[0]}\nfi\n\ncheck_kdc || exit ${PIPESTATUS[0]}\ncheck_krb5 || exit ${PIPESTATUS[0]}\ncheck_libgssapi || exit ${PIPESTATUS[0]}\n\necho \"====================================================================\"\necho \" Configure Kerberos testing environment for Lustre\"\necho \" KDC: $MY_KDCNODE\"\necho \" realm: $KRB5_REALM, domain: $KRB5_DOMAIN\"\necho \" Using gssapi package: $LIBGSSAPI\"\necho \" MGS node:\"\necho \"     $MY_MGSNODE\"\necho \" OSS nodes:\"\nfor i in $MY_OSSNODES; do echo \"     $i\"; done\necho \" MDS nodes:\"\nfor i in $MY_MDSNODES; do echo \"     $i\"; done\necho \" CLIENT nodes:\"\nfor i in $MY_CLIENTNODES; do echo \"     $i\"; done\necho \"====================================================================\"\n\ncfg_nfs_mount || exit ${PIPESTATUS[0]}\ncfg_libgssapi || exit ${PIPESTATUS[0]}\ncfg_keyutils || exit ${PIPESTATUS[0]}\n\nif $RESET_KDC; then\n    cfg_krb5_conf || exit ${PIPESTATUS[0]}\n    cfg_kdc || exit ${PIPESTATUS[0]}\nfi\n\ncfg_kdc_princs || exit ${PIPESTATUS[0]}\ncfg_keytab || exit ${PIPESTATUS[0]}\n\necho \"Complete successfully!\"\n", "num_lines": 1036}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\nset -e\n\nLUSTRE=${LUSTRE:-`dirname $0`/..}\n. $LUSTRE/tests/test-framework.sh\ninit_test_env $@\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\ninit_logging\n\n# QE uses the following parameters:\n# size=128 crghi=16 thrhi=32\ncrghi=${crghi:-2}\nthrhi=${thrhi:-16}\nsize=${size:-1024}\n\n[ \"$SLOW\" = no ] && { crghi=2; thrhi=2; }\n\nif [ \"$SGPDD_YES\" != \"yes\" -o \"$REFORMAT\" != \"yes\" ]; then\n\tskip_env \"$0 reformats all devices, set SGPDD_YES=yes REFORMAT=yes\"\n\texit 0\nfi\n\n# Skip these tests\nALWAYS_EXCEPT=\"$SGPDD_SURVEY_EXCEPT\"\n\nbuild_test_filter\n\ninit_facets_vars\n\ncleanupall\n\nrun_sgpdd_host () {\n    local host=$1\n    local devs=$2\n\n    local params=\"size=$size crghi=$crghi thrhi=$thrhi\"\n    do_rpc_nodes $host run_sgpdd $devs \"$params\"\n}\n\nrun_sgpdd_facets () {\n    local facets=$1\n    local facet\n\n    local facetshosts\n    for facet in ${facets//,/ }; do\n        local host=$(facet_host $facet)\n        local dev=${facet}_dev\n        local var=$(node_var_name ${host}_devs)\n        eval ${var}=$(expand_list ${!var} ${!dev})\n        facetshosts=$(expand_list $facetshosts $host)\n    done\n\n    for host in ${facetshosts//,/ }; do\n        var=$(node_var_name ${host}_devs)\n        echo \"=== $facets === $host === ${!var} ===\"\n        local scsidevs=${!var}\n        run_sgpdd_host $host ${scsidevs}\n    done\n}\n\ntest_1 () {\n\tlocal mdss=$(get_facets MDS)\n\n\tcheck_progs_installed $(facets_hosts $mdss) $SGPDDSURVEY sg_map ||\n\t\tskip_env \"SGPDDSURVEY=$SGPDDSURVEY or sg_map not found\"\n\n\trun_sgpdd_facets $mdss\n}\nrun_test 1 \"sgpdd-survey, mds, scsidevs\"\n\ntest_2 () {\n\tlocal osts=$(get_facets OST)\n\n\tcheck_progs_installed $(facets_hosts $osts) $SGPDDSURVEY sg_map ||\n\t\tskip_env \"SGPDDSURVEY=$SGPDDSURVEY or sg_map not found\"\n\n\trun_sgpdd_facets $osts\n}\nrun_test 2 \"sgpdd-survey, osts, scsidevs\"\n\ncomplete $SECONDS\nexit_status\n", "num_lines": 84}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ntrap 'print_summary && print_stack_trace | tee $TF_FAIL && \\\n    echo \"$TESTSUITE: FAIL: test-framework exiting on error\"' ERR\nset -e\n\nexport LANG=en_US\nexport REFORMAT=${REFORMAT:-\"\"}\nexport WRITECONF=${WRITECONF:-\"\"}\nexport VERBOSE=${VERBOSE:-false}\nexport GSS=${GSS:-false}\nexport GSS_SK=${GSS_SK:-false}\nexport GSS_KRB5=false\nexport GSS_PIPEFS=false\nexport SHARED_KEY=${SHARED_KEY:-false}\nexport SK_PATH=${SK_PATH:-/tmp/test-framework-keys}\nexport SK_OM_PATH=$SK_PATH'/tmp-request-mount'\nexport SK_MOUNTED=${SK_MOUNTED:-false}\nexport SK_FLAVOR=${SK_FLAVOR:-ski}\nexport SK_NO_KEY=${SK_NO_KEY:-true}\nexport SK_UNIQUE_NM=${SK_UNIQUE_NM:-false}\nexport SK_S2S=${SK_S2S:-false}\nexport SK_S2SNM=${SK_S2SNM:-TestFrameNM}\nexport SK_S2SNMCLI=${SK_S2SNMCLI:-TestFrameNMCli}\nexport SK_SKIPFIRST=${SK_SKIPFIRST:-true}\nexport IDENTITY_UPCALL=default\nexport QUOTA_AUTO=1\nexport FLAKEY=${FLAKEY:-true}\n# specify environment variable containing batch job name for server statistics\nexport JOBID_VAR=${JOBID_VAR:-\"procname_uid\"}  # or \"existing\" or \"disable\"\n\n#export PDSH=\"pdsh -S -Rssh -w\"\nexport MOUNT_CMD=${MOUNT_CMD:-\"mount -t lustre\"}\nexport UMOUNT=${UMOUNT:-\"umount -d\"}\n\nexport LSNAPSHOT_CONF=\"/etc/ldev.conf\"\nexport LSNAPSHOT_LOG=\"/var/log/lsnapshot.log\"\n\n# sles12 umount has a issue with -d option\n[ -e /etc/SuSE-release ] && grep -w VERSION /etc/SuSE-release | grep -wq 12 && {\n\texport UMOUNT=\"umount\"\n}\n\n# function used by scripts run on remote nodes\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/..; echo $PWD)}\n. $LUSTRE/tests/functions.sh\n. $LUSTRE/tests/yaml.sh\n\nexport LD_LIBRARY_PATH=${LUSTRE}/utils/.libs:${LUSTRE}/utils:${LD_LIBRARY_PATH}\n\nLUSTRE_TESTS_CFG_DIR=${LUSTRE_TESTS_CFG_DIR:-${LUSTRE}/tests/cfg}\n\nEXCEPT_LIST_FILE=${EXCEPT_LIST_FILE:-${LUSTRE_TESTS_CFG_DIR}/tests-to-skip.sh}\n\nif [ -f \"$EXCEPT_LIST_FILE\" ]; then\n    echo \"Reading test skip list from $EXCEPT_LIST_FILE\"\n    cat $EXCEPT_LIST_FILE\n    . $EXCEPT_LIST_FILE\nfi\n\n# check config files for options in decreasing order of preference\n[ -z \"$MODPROBECONF\" -a -f /etc/modprobe.d/lustre.conf ] &&\n    MODPROBECONF=/etc/modprobe.d/lustre.conf\n[ -z \"$MODPROBECONF\" -a -f /etc/modprobe.d/Lustre ] &&\n    MODPROBECONF=/etc/modprobe.d/Lustre\n[ -z \"$MODPROBECONF\" -a -f /etc/modprobe.conf ] &&\n    MODPROBECONF=/etc/modprobe.conf\n\nsanitize_parameters() {\n\tfor i in DIR DIR1 DIR2 MOUNT MOUNT1 MOUNT2\n\tdo\n\t\tlocal path=${!i}\n\t\tif [ -d \"$path\" ]; then\n\t\t\teval export $i=$(echo $path | sed -r 's/\\/+$//g')\n\t\tfi\n\tdone\n}\nassert_DIR () {\n\tlocal failed=\"\"\n\t[[ $DIR/ = $MOUNT/* ]] ||\n\t\t{ failed=1 && echo \"DIR=$DIR not in $MOUNT. Aborting.\"; }\n\t[[ $DIR1/ = $MOUNT1/* ]] ||\n\t\t{ failed=1 && echo \"DIR1=$DIR1 not in $MOUNT1. Aborting.\"; }\n\t[[ $DIR2/ = $MOUNT2/* ]] ||\n\t\t{ failed=1 && echo \"DIR2=$DIR2 not in $MOUNT2. Aborting\"; }\n\n\t[ -n \"$failed\" ] && exit 99 || true\n}\n\nusage() {\n    echo \"usage: $0 [-r] [-f cfgfile]\"\n    echo \"       -r: reformat\"\n\n    exit\n}\n\nprint_summary () {\n\ttrap 0\n\t[ -z \"$DEFAULT_SUITES\" ] && return 0\n\t[ -n \"$ONLY\" ] && echo \"WARNING: ONLY is set to $(echo $ONLY)\"\n\tlocal details\n\tlocal form=\"%-13s %-17s %-9s %s %s\\n\"\n\n\tprintf \"$form\" \"status\" \"script\" \"Total(sec)\" \"E(xcluded) S(low)\"\n\techo \"---------------------------------------------------------------\"\n    for O in $DEFAULT_SUITES; do\n        O=$(echo $O  | tr \"-\" \"_\" | tr \"[:lower:]\" \"[:upper:]\")\n        [ \"${!O}\" = \"no\" ] && continue || true\n        local o=$(echo $O  | tr \"[:upper:]_\" \"[:lower:]-\")\n        local log=${TMP}/${o}.log\n        if is_sanity_benchmark $o; then\n            log=${TMP}/sanity-benchmark.log\n        fi\n        local slow=\n        local skipped=\n        local total=\n        local status=Unfinished\n        if [ -f $log ]; then\n\t\tskipped=$(grep excluded $log | awk '{ printf \" %s\", $3 }' |\n\t\t\tsed 's/test_//g')\n\t\tslow=$(egrep \"^PASS|^FAIL\" $log | tr -d \"(\"| sed s/s\\)$//g |\n\t\t\tsort -nr -k 3  | head -n5 |  awk '{ print $2\":\"$3\"s\" }')\n\t\ttotal=$(grep duration $log | awk '{ print $2 }')\n\t\tif [ \"${!O}\" = \"done\" ]; then\n\t\t\tstatus=Done\n\t\tfi\n\t\tif $DDETAILS; then\n\t\t\tlocal durations=$(egrep \"^PASS|^FAIL\" $log |\n\t\t\t\ttr -d \"(\"| sed s/s\\)$//g |\n\t\t\t\tawk '{ print $2\":\"$3\"|\" }')\n\t\t\tdetails=$(printf \"%s\\n%s %s %s\\n\" \"$details\" \\\n\t\t\t\t\"DDETAILS\" \"$O\" \"$(echo $durations)\")\n\t\tfi\n        fi\n        printf \"$form\" $status \"$O\" \"${total}\" \"E=$skipped\"\n        printf \"$form\" \"-\" \"-\" \"-\" \"S=$(echo $slow)\"\n    done\n\n    for O in $DEFAULT_SUITES; do\n        O=$(echo $O  | tr \"-\" \"_\" | tr \"[:lower:]\" \"[:upper:]\")\n        if [ \"${!O}\" = \"no\" ]; then\n            printf \"$form\" \"Skipped\" \"$O\" \"\"\n        fi\n    done\n\n    # print the detailed tests durations if DDETAILS=true\n    if $DDETAILS; then\n        echo \"$details\"\n    fi\n}\n\n# Get information about the Lustre environment. The information collected\n# will be used in Lustre tests.\n# usage: get_lustre_env\n# input: No required or optional arguments\n# output: No return values, environment variables are exported\n\nget_lustre_env() {\n\n\texport mds1_FSTYPE=${mds1_FSTYPE:-$(facet_fstype mds1)}\n\texport ost1_FSTYPE=${ost1_FSTYPE:-$(facet_fstype ost1)}\n\n\texport MGS_VERSION=$(lustre_version_code mgs)\n\texport MDS1_VERSION=$(lustre_version_code mds1)\n\texport OST1_VERSION=$(lustre_version_code ost1)\n\texport CLIENT_VERSION=$(lustre_version_code client)\n\n\t# Prefer using \"mds1\" directly instead of SINGLEMDS.\n\t# Keep this for compat until it is removed from scripts.\n\texport SINGLEMDS=${SINGLEMDS:-mds1}\n}\n\ninit_test_env() {\n\texport LUSTRE=$(absolute_path $LUSTRE)\n\texport TESTSUITE=$(basename $0 .sh)\n\texport TEST_FAILED=false\n\texport FAIL_ON_SKIP_ENV=${FAIL_ON_SKIP_ENV:-false}\n\texport RPC_MODE=${RPC_MODE:-false}\n\texport DO_CLEANUP=${DO_CLEANUP:-true}\n\texport KEEP_ZPOOL=${KEEP_ZPOOL:-false}\n\texport CLEANUP_DM_DEV=false\n\texport PAGE_SIZE=$(get_page_size client)\n\n\texport MKE2FS=$MKE2FS\n\tif [ -z \"$MKE2FS\" ]; then\n\t\tif which mkfs.ldiskfs >/dev/null 2>&1; then\n\t\t\texport MKE2FS=mkfs.ldiskfs\n\t\telse\n\t\t\texport MKE2FS=mke2fs\n\t\tfi\n\tfi\n\n\texport DEBUGFS=$DEBUGFS\n\tif [ -z \"$DEBUGFS\" ]; then\n\t\tif which debugfs.ldiskfs >/dev/null 2>&1; then\n\t\t\texport DEBUGFS=debugfs.ldiskfs\n\t\telse\n\t\t\texport DEBUGFS=debugfs\n\t\tfi\n\tfi\n\n\texport TUNE2FS=$TUNE2FS\n\tif [ -z \"$TUNE2FS\" ]; then\n\t\tif which tunefs.ldiskfs >/dev/null 2>&1; then\n\t\t\texport TUNE2FS=tunefs.ldiskfs\n\t\telse\n\t\t\texport TUNE2FS=tune2fs\n\t\tfi\n\tfi\n\n\texport E2LABEL=$E2LABEL\n\tif [ -z \"$E2LABEL\" ]; then\n\t\tif which label.ldiskfs >/dev/null 2>&1; then\n\t\t\texport E2LABEL=label.ldiskfs\n\t\telse\n\t\t\texport E2LABEL=e2label\n\t\tfi\n\tfi\n\n\texport DUMPE2FS=$DUMPE2FS\n\tif [ -z \"$DUMPE2FS\" ]; then\n\t\tif which dumpfs.ldiskfs >/dev/null 2>&1; then\n\t\t\texport DUMPE2FS=dumpfs.ldiskfs\n\t\telse\n\t\t\texport DUMPE2FS=dumpe2fs\n\t\tfi\n\tfi\n\n\texport E2FSCK=$E2FSCK\n\tif [ -z \"$E2FSCK\" ]; then\n\t\tif which fsck.ldiskfs >/dev/null 2>&1; then\n\t\t\texport E2FSCK=fsck.ldiskfs\n\t\telse\n\t\t\t export E2FSCK=e2fsck\n\t\tfi\n\tfi\n\n\texport RESIZE2FS=$RESIZE2FS\n\tif [ -z \"$RESIZE2FS\" ]; then\n\t\tif which resizefs.ldiskfs >/dev/null 2>&1; then\n\t\t\texport RESIZE2FS=resizefs.ldiskfs\n\t\telse\n\t\t\texport RESIZE2FS=resize2fs\n\t\tfi\n\tfi\n\n\texport LFSCK_ALWAYS=${LFSCK_ALWAYS:-\"no\"} # check fs after test suite\n\texport FSCK_MAX_ERR=4   # File system errors left uncorrected\n\n\texport ZFS=${ZFS:-zfs}\n\texport ZPOOL=${ZPOOL:-zpool}\n\texport ZDB=${ZDB:-zdb}\n\texport PARTPROBE=${PARTPROBE:-partprobe}\n\n\t#[ -d /r ] && export ROOT=${ROOT:-/r}\n\texport TMP=${TMP:-$ROOT/tmp}\n\texport TESTSUITELOG=${TMP}/${TESTSUITE}.log\n\texport LOGDIR=${LOGDIR:-${TMP}/test_logs/$(date +%s)}\n\texport TESTLOG_PREFIX=$LOGDIR/$TESTSUITE\n\n\texport HOSTNAME=${HOSTNAME:-$(hostname -s)}\n\tif ! echo $PATH | grep -q $LUSTRE/utils; then\n\t\texport PATH=$LUSTRE/utils:$PATH\n\tfi\n\tif ! echo $PATH | grep -q $LUSTRE/utils/gss; then\n\t\texport PATH=$LUSTRE/utils/gss:$PATH\n\tfi\n\tif ! echo $PATH | grep -q $LUSTRE/tests; then\n\t\texport PATH=$LUSTRE/tests:$PATH\n\tfi\n\tif ! echo $PATH | grep -q $LUSTRE/../lustre-iokit/sgpdd-survey; then\n\t\texport PATH=$LUSTRE/../lustre-iokit/sgpdd-survey:$PATH\n\tfi\n\texport LST=${LST:-\"$LUSTRE/../lnet/utils/lst\"}\n\t[ ! -f \"$LST\" ] && export LST=$(which lst)\n\texport SGPDDSURVEY=${SGPDDSURVEY:-\"$LUSTRE/../lustre-iokit/sgpdd-survey/sgpdd-survey\")}\n\t[ ! -f \"$SGPDDSURVEY\" ] && export SGPDDSURVEY=$(which sgpdd-survey)\n\texport MCREATE=${MCREATE:-mcreate}\n\texport MULTIOP=${MULTIOP:-multiop}\n\texport MMAP_CAT=${MMAP_CAT:-mmap_cat}\n\texport STATX=${STATX:-statx}\n\t# Ubuntu, at least, has a truncate command in /usr/bin\n\t# so fully path our truncate command.\n\texport TRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}\n\texport FSX=${FSX:-$LUSTRE/tests/fsx}\n\texport MDSRATE=${MDSRATE:-\"$LUSTRE/tests/mpi/mdsrate\"}\n\t[ ! -f \"$MDSRATE\" ] && export MDSRATE=$(which mdsrate 2> /dev/null)\n\tif ! echo $PATH | grep -q $LUSTRE/tests/racer; then\n\t\texport PATH=$LUSTRE/tests/racer:$PATH:\n\tfi\n\tif ! echo $PATH | grep -q $LUSTRE/tests/mpi; then\n\t\texport PATH=$LUSTRE/tests/mpi:$PATH\n\tfi\n\texport RSYNC_RSH=${RSYNC_RSH:-rsh}\n\n\texport LCTL=${LCTL:-\"$LUSTRE/utils/lctl\"}\n\t[ ! -f \"$LCTL\" ] && export LCTL=$(which lctl)\n\texport LFS=${LFS:-\"$LUSTRE/utils/lfs\"}\n\t[ ! -f \"$LFS\" ] && export LFS=$(which lfs)\n\n\texport PERM_CMD=${PERM_CMD:-\"$LCTL conf_param\"}\n\n\texport L_GETIDENTITY=${L_GETIDENTITY:-\"$LUSTRE/utils/l_getidentity\"}\n\tif [ ! -f \"$L_GETIDENTITY\" ]; then\n\t\tif `which l_getidentity > /dev/null 2>&1`; then\n\t\t\texport L_GETIDENTITY=$(which l_getidentity)\n\t\telse\n\t\t\texport L_GETIDENTITY=NONE\n\t\tfi\n\tfi\n\texport LL_DECODE_FILTER_FID=${LL_DECODE_FILTER_FID:-\"$LUSTRE/utils/ll_decode_filter_fid\"}\n\t[ ! -f \"$LL_DECODE_FILTER_FID\" ] && export LL_DECODE_FILTER_FID=\"ll_decode_filter_fid\"\n\texport LL_DECODE_LINKEA=${LL_DECODE_LINKEA:-\"$LUSTRE/utils/ll_decode_linkea\"}\n\t[ ! -f \"$LL_DECODE_LINKEA\" ] && export LL_DECODE_LINKEA=\"ll_decode_linkea\"\n\texport MKFS=${MKFS:-\"$LUSTRE/utils/mkfs.lustre\"}\n\t[ ! -f \"$MKFS\" ] && export MKFS=\"mkfs.lustre\"\n\texport TUNEFS=${TUNEFS:-\"$LUSTRE/utils/tunefs.lustre\"}\n\t[ ! -f \"$TUNEFS\" ] && export TUNEFS=\"tunefs.lustre\"\n\texport CHECKSTAT=\"${CHECKSTAT:-\"checkstat -v\"} \"\n\texport LUSTRE_RMMOD=${LUSTRE_RMMOD:-$LUSTRE/scripts/lustre_rmmod}\n\t[ ! -f \"$LUSTRE_RMMOD\" ] &&\n\t\texport LUSTRE_RMMOD=$(which lustre_rmmod 2> /dev/null)\n\texport LUSTRE_ROUTES_CONVERSION=${LUSTRE_ROUTES_CONVERSION:-$LUSTRE/scripts/lustre_routes_conversion}\n\t[ ! -f \"$LUSTRE_ROUTES_CONVERSION\" ] &&\n\t\texport LUSTRE_ROUTES_CONVERSION=$(which lustre_routes_conversion 2> /dev/null)\n\texport LFS_MIGRATE=${LFS_MIGRATE:-$LUSTRE/scripts/lfs_migrate}\n\t[ ! -f \"$LFS_MIGRATE\" ] &&\n\t\texport LFS_MIGRATE=$(which lfs_migrate 2> /dev/null)\n\texport LR_READER=${LR_READER:-\"$LUSTRE/utils/lr_reader\"}\n\t[ ! -f \"$LR_READER\" ] &&\n\t\texport LR_READER=$(which lr_reader 2> /dev/null)\n\t[ -z \"$LR_READER\" ] && export LR_READER=\"/usr/sbin/lr_reader\"\n\texport LSOM_SYNC=${LSOM_SYNC:-\"$LUSTRE/utils/llsom_sync\"}\n\t[ ! -f \"$LSOM_SYNC\" ] &&\n\t\texport LSOM_SYNC=$(which llsom_sync 2> /dev/null)\n\t[ -z \"$LSOM_SYNC\" ] && export LSOM_SYNC=\"/usr/sbin/llsom_sync\"\n\texport NAME=${NAME:-local}\n\texport LGSSD=${LGSSD:-\"$LUSTRE/utils/gss/lgssd\"}\n\t[ \"$GSS_PIPEFS\" = \"true\" ] && [ ! -f \"$LGSSD\" ] &&\n\t\texport LGSSD=$(which lgssd)\n\texport LSVCGSSD=${LSVCGSSD:-\"$LUSTRE/utils/gss/lsvcgssd\"}\n\t[ ! -f \"$LSVCGSSD\" ] && export LSVCGSSD=$(which lsvcgssd 2> /dev/null)\n\texport KRB5DIR=${KRB5DIR:-\"/usr/kerberos\"}\n\texport DIR2\n\texport SAVE_PWD=${SAVE_PWD:-$LUSTRE/tests}\n\texport AT_MAX_PATH\n\texport LDEV=${LDEV:-\"$LUSTRE/scripts/ldev\"}\n\t[ ! -f \"$LDEV\" ] && export LDEV=$(which ldev 2> /dev/null)\n\n\texport DMSETUP=${DMSETUP:-dmsetup}\n\texport DM_DEV_PATH=${DM_DEV_PATH:-/dev/mapper}\n\texport LOSETUP=${LOSETUP:-losetup}\n\n\tif [ \"$ACCEPTOR_PORT\" ]; then\n\t\texport PORT_OPT=\"--port $ACCEPTOR_PORT\"\n\tfi\n\n\tif $SHARED_KEY; then\n\t\t$RPC_MODE || echo \"Using GSS shared-key feature\"\n\t\twhich lgss_sk > /dev/null 2>&1 ||\n\t\t\terror_exit \"built with lgss_sk disabled! SEC=$SEC\"\n\t\tGSS=true\n\t\tGSS_SK=true\n\t\tSEC=$SK_FLAVOR\n\tfi\n\n\tcase \"x$SEC\" in\n\t\txkrb5*)\n\t\t$RPC_MODE || echo \"Using GSS/krb5 ptlrpc security flavor\"\n\t\twhich lgss_keyring > /dev/null 2>&1 ||\n\t\t\terror_exit \"built with gss disabled! SEC=$SEC\"\n\t\tGSS=true\n\t\tGSS_KRB5=true\n\t\t;;\n\tesac\n\n\tcase \"x$IDUP\" in\n\t\txtrue)\n\t\t\tIDENTITY_UPCALL=true\n\t\t\t;;\n\t\txfalse)\n\t\t\tIDENTITY_UPCALL=false\n\t\t\t;;\n\tesac\n\n\texport LOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}\n\n\t# Paths on remote nodes, if different\n\texport RLUSTRE=${RLUSTRE:-$LUSTRE}\n\texport RPWD=${RPWD:-$PWD}\n\texport I_MOUNTED=${I_MOUNTED:-\"no\"}\n\texport AUSTER_CLEANUP=${AUSTER_CLEANUP:-false}\n\tif [ ! -f /lib/modules/$(uname -r)/kernel/fs/lustre/mdt.ko -a \\\n\t     ! -f /lib/modules/$(uname -r)/updates/kernel/fs/lustre/mdt.ko -a \\\n\t     ! -f /lib/modules/$(uname -r)/extra/kernel/fs/lustre/mdt.ko -a \\\n\t     ! -f $LUSTRE/mdt/mdt.ko ]; then\n\t    export CLIENTMODSONLY=yes\n\tfi\n\n\texport SHUTDOWN_ATTEMPTS=${SHUTDOWN_ATTEMPTS:-3}\n\texport OSD_TRACK_DECLARES_LBUG=${OSD_TRACK_DECLARES_LBUG:-\"yes\"}\n\n\t# command line\n\n\twhile getopts \"rvwf:\" opt $*; do\n\t\tcase $opt in\n\t\t\tf) CONFIG=$OPTARG;;\n\t\t\tr) REFORMAT=yes;;\n\t\t\tv) VERBOSE=true;;\n\t\t\tw) WRITECONF=writeconf;;\n\t\t\t\\?) usage;;\n\t\tesac\n\tdone\n\n\tshift $((OPTIND - 1))\n\tONLY=${ONLY:-$*}\n\n\t# print the durations of each test if \"true\"\n\tDDETAILS=${DDETAILS:-false}\n\t[ \"$TESTSUITELOG\" ] && rm -f $TESTSUITELOG || true\n\tif ! $RPC_MODE; then\n\t\trm -f $TMP/*active\n\tfi\n\n\texport TF_FAIL=${TF_FAIL:-$TMP/tf.fail}\n\n\t# Constants used in more than one test script\n\texport LOV_MAX_STRIPE_COUNT=2000\n\n\texport MACHINEFILE=${MACHINEFILE:-$TMP/$(basename $0 .sh).machines}\n\t. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\tget_lustre_env\n\n\t# use localrecov to enable recovery for local clients, LU-12722\n\t[[ $MDS1_VERSION -lt $(version_code 2.13.52) ]] ||\n\t\texport MDS_MOUNT_OPTS=${MDS_MOUNT_OPTS:-\"-o localrecov\"}\n\t[[ $OST1_VERSION -lt $(version_code 2.13.52) ]] ||\n\t\texport OST_MOUNT_OPTS=${OST_MOUNT_OPTS:-\"-o localrecov\"}\n}\n\ncheck_cpt_number() {\n\tlocal facet=$1\n\tlocal ncpts\n\n\tncpts=$(do_facet $facet \"lctl get_param -n \" \\\n\t\t\"cpu_partition_table 2>/dev/null| wc -l\" || echo 1)\n\n\tif [ $ncpts -eq 0 ]; then\n\t\techo \"1\"\n\telse\n\t\techo $ncpts\n\tfi\n}\n\n# Return a numeric version code based on a version string.  The version\n# code is useful for comparison two version strings to see which is newer.\nversion_code() {\n\t# split arguments like \"1.8.6-wc3\" into \"1\", \"8\", \"6\", \"wc3\"\n\teval set -- $(tr \"[:punct:]\" \" \" <<< $*)\n\n\techo -n $(((${1:-0} << 16) | (${2:-0} << 8) | ${3:-0}))\n}\n\nexport LINUX_VERSION=$(uname -r | sed -e \"s/\\([0-9]*\\.[0-9]*\\.[0-9]*\\).*/\\1/\")\nexport LINUX_VERSION_CODE=$(version_code ${LINUX_VERSION//\\./ })\n\n# Report the Lustre build version string (e.g. 1.8.7.3 or 2.4.1).\n#\n# usage: lustre_build_version\n#\n# All Lustre versions support \"lctl get_param\" to report the version of the\n# code running in the kernel (what our tests are interested in), but it\n# doesn't work without modules loaded.  After 2.9.53 and in upstream kernels\n# the \"version\" parameter doesn't include \"lustre: \" at the beginning.\n# If that fails, call \"lctl lustre_build_version\" which prints either (or both)\n# the userspace and kernel build versions, but until 2.8.55 required root\n# access to get the Lustre kernel version.  If that also fails, fall back to\n# using \"lctl --version\", which is easy to parse and works without the kernel\n# modules, but was only added in 2.6.50 and only prints the lctl tool version,\n# not the module version, though they are usually the same.\n#\n# Various commands and their output format for different Lustre versions:\n# lctl get_param version:\t2.9.55\n# lctl get_param version:\tlustre: 2.8.53\n# lctl get_param version:\tlustre: 2.6.52\n#\t\t\t\tkernel: patchless_client\n#\t\t\t\tbuild: v2_6_92_0-2.6.32-431.el6_lustre.x86_64\n# lctl lustre_build_version:\tLustre version: 2.8.53_27_gae67fc01\n# lctl lustre_build_version:\terror: lustre_build_version: Permission denied\n#\t(as non-root user)\tlctl   version: v2_6_92_0-2.6.32-431.el6.x86_64\n# lctl lustre_build_version:\tLustre version: 2.5.3-2.6.32.26-175.fc12.x86_64\n#\t\t\t\tlctl   version: 2.5.3-2.6.32..26-175fc12.x86_64\n# lctl --version:\t\tlctl 2.6.50\n#\n# output: prints version string to stdout in (up to 4) dotted-decimal values\nlustre_build_version() {\n\tlocal facet=${1:-client}\n\tlocal facet_version=${facet}_VERSION\n\n\t# if the global variable is already set, then use that\n\t[ -n \"${!facet_version}\" ] && echo ${!facet_version} && return\n\n\t# this is the currently-running version of the kernel modules\n\tlocal ver=$(do_facet $facet \"$LCTL get_param -n version 2>/dev/null\")\n\t# we mostly test 2.10+ systems, only try others if the above fails\n\tif [ -z \"$ver\" ]; then\n\t\tver=$(do_facet $facet \"$LCTL lustre_build_version 2>/dev/null\")\n\tfi\n\tif [ -z \"$ver\" ]; then\n\t\tver=$(do_facet $facet \"$LCTL --version 2>/dev/null\" |\n\t\t      cut -d' ' -f2)\n\tfi\n\tlocal lver=$(egrep -i \"lustre: |version: \" <<<\"$ver\" | head -n 1)\n\t[ -n \"$lver\" ] && ver=\"$lver\"\n\n\tlver=$(sed -e 's/[^:]*: //' -e 's/^v//' -e 's/[ -].*//' <<<$ver |\n\t       tr _ . | cut -d. -f1-4)\n\n\t# save in global variable for the future\n\texport $facet_version=$lver\n\n\techo $lver\n}\n\n# Report the Lustre numeric build version code for the supplied facet.\nlustre_version_code() {\n\tversion_code $(lustre_build_version $1)\n}\n\nmodule_loaded () {\n\t/sbin/lsmod | grep -q \"^\\<$1\\>\"\n}\n\nPRLFS=false\nlustre_insmod() {\n\tlocal module=$1\n\tshift\n\tlocal args=\"$@\"\n\tlocal msg\n\tlocal rc=0\n\n\tif ! $PRLFS; then\n\t\tmsg=\"$(insmod $module $args 2>&1)\" && return 0 || rc=$?\n\tfi\n\n\t# parallels can't load modules directly from prlfs, use /tmp instead\n\tif $PRLFS || [[ \"$(stat -f -c%t $module)\" == \"7c7c6673\" ]]; then\n\t\tlocal target=\"$(mktemp)\"\n\n\t\tcp \"$module\" \"$target\"\n\t\tinsmod $target $args\n\t\trc=$?\n\t\t[[ $rc == 0 ]] && PRLFS=true\n\t\trm -f $target\n\telse\n\t\techo \"$msg\"\n\tfi\n\treturn $rc\n}\n\n# Load a module on the system where this is running.\n#\n# usage: load_module module_name [module arguments for insmod/modprobe]\n#\n# If module arguments are not given but MODOPTS_<MODULE> is set, then its value\n# will be used as the arguments.  Otherwise arguments will be obtained from\n# /etc/modprobe.conf, from /etc/modprobe.d/Lustre, or else none will be used.\n#\nload_module() {\n\tlocal module=$1 # '../libcfs/libcfs/libcfs', 'obdclass/obdclass', ...\n\tshift\n\tlocal ext=\".ko\"\n\tlocal base=$(basename $module $ext)\n\tlocal path\n\tlocal -A module_is_loaded_aa\n\tlocal optvar\n\tlocal mod\n\n\tfor mod in $(lsmod | awk '{ print $1; }'); do\n\t\tmodule_is_loaded_aa[${mod//-/_}]=true\n\tdone\n\n\tmodule_is_loaded() {\n\t\t${module_is_loaded_aa[${1//-/_}]:-false}\n\t}\n\n\tif module_is_loaded $base; then\n\t\treturn\n\tfi\n\n\tif [[ -f $LUSTRE/$module$ext ]]; then\n\t\tpath=$LUSTRE/$module$ext\n\telif [[ \"$base\" == lnet_selftest ]] &&\n\t     [[ -f $LUSTRE/../lnet/selftest/$base$ext ]]; then\n\t\tpath=$LUSTRE/../lnet/selftest/$base$ext\n\telse\n\t\tpath=''\n\tfi\n\n\tif [[ -n \"$path\" ]]; then\n\t\t# Try to load any non-Lustre modules that $module depends on.\n\t\tfor mod in $(modinfo --field=depends $path | tr ',' ' '); do\n\t\t\tif ! module_is_loaded $mod; then\n\t\t\t\tmodprobe $mod\n\t\t\tfi\n\t\tdone\n\tfi\n\n\t# If no module arguments were passed then get them from\n\t# $MODOPTS_<MODULE>, otherwise from modprobe.conf.\n\tif [ $# -eq 0 ]; then\n\t\t# $MODOPTS_<MODULE>; we could use associative arrays, but that's\n\t\t# not in Bash until 4.x, so we resort to eval.\n\t\toptvar=\"MODOPTS_$(basename $module | tr a-z A-Z)\"\n\t\teval set -- \\$$optvar\n\t\tif [ $# -eq 0 -a -n \"$MODPROBECONF\" ]; then\n\t\t\t# Nothing in $MODOPTS_<MODULE>; try modprobe.conf\n\t\t\tlocal opt\n\t\t\topt=$(awk -v var=\"^options $base\" '$0 ~ var \\\n\t\t\t      {gsub(\"'\"options $base\"'\",\"\"); print}' \\\n\t\t\t\t$MODPROBECONF)\n\t\t\tset -- $(echo -n $opt)\n\n\t\t\t# Ensure we have accept=all for lnet\n\t\t\tif [[ \"$base\" == lnet ]]; then\n\t\t\t\t# OK, this is a bit wordy...\n\t\t\t\tlocal arg accept_all_present=false\n\n\t\t\t\tfor arg in \"$@\"; do\n\t\t\t\t\t[[ \"$arg\" == accept=all ]] &&\n\t\t\t\t\t\taccept_all_present=true\n\t\t\t\tdone\n\n\t\t\t\t$accept_all_present || set -- \"$@\" accept=all\n\t\t\tfi\n\n\t\t\texport $optvar=\"$*\"\n\t\tfi\n\tfi\n\n\t[ $# -gt 0 ] && echo \"${module} options: '$*'\"\n\n\t# Note that insmod will ignore anything in modprobe.conf, which is why\n\t# we're passing options on the command-line. If $path does not exist\n\t# then we must be testing a \"make install\" or\"rpm\" installation. Also\n\t# note that failing to load ptlrpc_gss is not considered fatal.\n\tif [[ -n \"$path\" ]]; then\n\t\tlustre_insmod $path \"$@\"\n\telif [[ \"$base\" == ptlrpc_gss ]]; then\n\t\tif ! modprobe $base \"$@\" 2>/dev/null; then\n\t\t\techo \"gss/krb5 is not supported\"\n\t\tfi\n\telse\n\t\tmodprobe $base \"$@\"\n\tfi\n}\n\nload_modules_local() {\n\tif [ -n \"$MODPROBE\" ]; then\n\t\t# use modprobe\n\t\techo \"Using modprobe to load modules\"\n\t\treturn 0\n\tfi\n\n\t# Create special udev test rules on every node\n\tif [ -f $LUSTRE/lustre/conf/99-lustre.rules ]; then {\n\t\tsed -e 's|/usr/sbin/lctl|$LCTL|g' $LUSTRE/lustre/conf/99-lustre.rules > /etc/udev/rules.d/99-lustre-test.rules\n\t} else {\n\t\techo \"SUBSYSTEM==\\\"lustre\\\", ACTION==\\\"change\\\", ENV{PARAM}==\\\"?*\\\", RUN+=\\\"$LCTL set_param '\\$env{PARAM}=\\$env{SETTING}'\\\"\" > /etc/udev/rules.d/99-lustre-test.rules\n\t} fi\n\tudevadm control --reload-rules\n\tudevadm trigger\n\n\t# For kmemleak-enabled kernels we need clear all past state\n\t# that obviously has nothing to do with this Lustre run\n\t# Disable automatic memory scanning to avoid perf hit.\n\tif [ -f /sys/kernel/debug/kmemleak ] ; then\n\t\techo scan=off > /sys/kernel/debug/kmemleak\n\t\techo scan > /sys/kernel/debug/kmemleak\n\t\techo clear > /sys/kernel/debug/kmemleak\n\tfi\n\n\techo Loading modules from $LUSTRE\n\n\tlocal ncpus\n\n\tif [ -f /sys/devices/system/cpu/online ]; then\n\t\tncpus=$(($(cut -d \"-\" -f 2 /sys/devices/system/cpu/online) + 1))\n\t\techo \"detected $ncpus online CPUs by sysfs\"\n\telse\n\t\tncpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)\n\t\tlocal rc=$?\n\t\tif [ $rc -eq 0 ]; then\n\t\t\techo \"detected $ncpus online CPUs by getconf\"\n\t\telse\n\t\t\techo \"Can't detect number of CPUs\"\n\t\t\tncpus=1\n\t\tfi\n\tfi\n\n\t# if there is only one CPU core, libcfs can only create one partition\n\t# if there is more than 4 CPU cores, libcfs should create multiple CPU\n\t# partitions. So we just force libcfs to create 2 partitions for\n\t# system with 2 or 4 cores\n\tlocal saved_opts=\"$MODOPTS_LIBCFS\"\n\tif [ $ncpus -le 4 ] && [ $ncpus -gt 1 ]; then\n\t\t# force to enable multiple CPU partitions\n\t\techo \"Force libcfs to create 2 CPU partitions\"\n\t\tMODOPTS_LIBCFS=\"cpu_npartitions=2 $MODOPTS_LIBCFS\"\n\telse\n\t\techo \"libcfs will create CPU partition based on online CPUs\"\n\tfi\n\n\tload_module ../libcfs/libcfs/libcfs\n\t# Prevent local MODOPTS_LIBCFS being passed as part of environment\n\t# variable to remote nodes\n\tMODOPTS_LIBCFS=$saved_opts\n\n\tset_default_debug\n\tload_module ../lnet/lnet/lnet\n\n\tLNDPATH=${LNDPATH:-\"../lnet/klnds\"}\n\tif [ -z \"$LNETLND\" ]; then\n\t\tcase $NETTYPE in\n\t\to2ib*)  LNETLND=\"o2iblnd/ko2iblnd\" ;;\n\t\ttcp*)   LNETLND=\"socklnd/ksocklnd\" ;;\n\t\t*)      local lnd=\"${NETTYPE%%[0-9]}lnd\"\n\t\t\t[ -f \"$LNDPATH/$lnd/k$lnd.ko\" ] &&\n\t\t\t\tLNETLND=\"$lnd/k$lnd\" ||\n\t\t\t\tLNETLND=\"socklnd/ksocklnd\"\n\t\tesac\n\tfi\n\tload_module ../lnet/klnds/$LNETLND\n\tload_module obdclass/obdclass\n\tload_module ptlrpc/ptlrpc\n\tload_module ptlrpc/gss/ptlrpc_gss\n\tload_module fld/fld\n\tload_module fid/fid\n\tload_module lmv/lmv\n\tload_module osc/osc\n\tload_module lov/lov\n\tload_module mdc/mdc\n\tload_module mgc/mgc\n\tload_module obdecho/obdecho\n\tif ! client_only; then\n\t\tload_module lfsck/lfsck\n\t\t[ \"$LQUOTA\" != \"no\" ] &&\n\t\t\tload_module quota/lquota $LQUOTAOPTS\n\t\tif [[ $(node_fstypes $HOSTNAME) == *zfs* ]]; then\n\t\t\tload_module osd-zfs/osd_zfs\n\t\telif [[ $(node_fstypes $HOSTNAME) == *ldiskfs* ]]; then\n\t\t\tload_module ../ldiskfs/ldiskfs\n\t\t\tload_module osd-ldiskfs/osd_ldiskfs\n\t\tfi\n\t\tload_module mgs/mgs\n\t\tload_module mdd/mdd\n\t\tload_module mdt/mdt\n\t\tload_module ost/ost\n\t\tload_module lod/lod\n\t\tload_module osp/osp\n\t\tload_module ofd/ofd\n\t\tload_module osp/osp\n\tfi\n\n\tload_module llite/lustre\n\t[ -d /r ] && OGDB=${OGDB:-\"/r/tmp\"}\n\tOGDB=${OGDB:-$TMP}\n\trm -f $OGDB/ogdb-$HOSTNAME\n\t$LCTL modules > $OGDB/ogdb-$HOSTNAME\n\n\t# 'mount' doesn't look in $PATH, just sbin\n\tlocal mount_lustre=$LUSTRE/utils/mount.lustre\n\tif [ -f $mount_lustre ]; then\n\t\tlocal sbin_mount=$(readlink -f /sbin)/mount.lustre\n\t\tif grep -qw \"$sbin_mount\" /proc/mounts; then\n\t\t\tcmp -s $mount_lustre $sbin_mount || umount $sbin_mount\n\t\tfi\n\t\tif ! grep -qw \"$sbin_mount\" /proc/mounts; then\n\t\t\t[ ! -f \"$sbin_mount\" ] && touch \"$sbin_mount\"\n\t\t\tif [ ! -s \"$sbin_mount\" -a -w \"$sbin_mount\" ]; then\n\t\t\t\tcat <<- EOF > \"$sbin_mount\"\n\t\t\t\t#!/bin/sh\n\t\t\t\t#STUB MARK\n\t\t\t\techo \"This $sbin_mount just a mountpoint.\" 1>&2\n\t\t\t\techo \"It is never supposed to be run.\" 1>&2\n\t\t\t\tlogger -p emerg -- \"using stub $sbin_mount $@\"\n\t\t\t\texit 1\n\t\t\t\tEOF\n\t\t\t\tchmod a+x $sbin_mount\n\t\t\tfi\n\t\t\tmount --bind $mount_lustre $sbin_mount ||\n\t\t\t\terror \"can't bind $mount_lustre to $sbin_mount\"\n\t\tfi\n\tfi\n}\n\nload_modules () {\n\tload_modules_local\n\t# bug 19124\n\t# load modules on remote nodes optionally\n\t# lustre-tests have to be installed on these nodes\n\tif $LOAD_MODULES_REMOTE; then\n\t\tlocal list=$(comma_list $(remote_nodes_list))\n\t\tif [ -n \"$list\" ]; then\n\t\t\techo \"loading modules on: '$list'\"\n\t\t\tdo_rpc_nodes \"$list\" load_modules_local\n\t\tfi\n\tfi\n}\n\ncheck_mem_leak () {\n    LEAK_LUSTRE=$(dmesg | tail -n 30 | grep \"obd_memory.*leaked\" || true)\n    LEAK_PORTALS=$(dmesg | tail -n 20 | grep \"Portals memory leaked\" || true)\n    if [ \"$LEAK_LUSTRE\" -o \"$LEAK_PORTALS\" ]; then\n        echo \"$LEAK_LUSTRE\" 1>&2\n        echo \"$LEAK_PORTALS\" 1>&2\n        mv $TMP/debug $TMP/debug-leak.`date +%s` || true\n        echo \"Memory leaks detected\"\n        [ -n \"$IGNORE_LEAK\" ] && { echo \"ignoring leaks\" && return 0; } || true\n        return 1\n    fi\n}\n\nunload_modules() {\n\twait_exit_ST client # bug 12845\n\n\t$LUSTRE_RMMOD ldiskfs || return 2\n\n\t[ -f /etc/udev/rules.d/99-lustre-test.rules ] &&\n\t\trm /etc/udev/rules.d/99-lustre-test.rules\n\tudevadm control --reload-rules\n\tudevadm trigger\n\n\tif $LOAD_MODULES_REMOTE; then\n\t\tlocal list=$(comma_list $(remote_nodes_list))\n\t\tif [ -n \"$list\" ]; then\n\t\t\techo \"unloading modules on: '$list'\"\n\t\t\tdo_rpc_nodes \"$list\" $LUSTRE_RMMOD ldiskfs\n\t\t\tdo_rpc_nodes \"$list\" check_mem_leak\n\t\t\tdo_rpc_nodes \"$list\" \"rm -f /etc/udev/rules.d/99-lustre-test.rules\"\n\t\t\tdo_rpc_nodes \"$list\" \"udevadm control --reload-rules\"\n\t\t\tdo_rpc_nodes \"$list\" \"udevadm trigger\"\n\t\tfi\n\tfi\n\n\tlocal sbin_mount=$(readlink -f /sbin)/mount.lustre\n\tif grep -qe \"$sbin_mount \" /proc/mounts; then\n\t\tumount $sbin_mount || true\n\t\t[ -s $sbin_mount ] && ! grep -q \"STUB MARK\" $sbin_mount ||\n\t\t\trm -f $sbin_mount\n\tfi\n\n\tcheck_mem_leak || return 254\n\n\techo \"modules unloaded.\"\n\treturn 0\n}\n\nfs_log_size() {\n\tlocal facet=${1:-$SINGLEMDS}\n\tlocal size=0\n\n\tcase $(facet_fstype $facet) in\n\t\tldiskfs) size=50;; # largest seen is 44, leave some headroom\n\t\t# grant_block_size is in bytes, allow at least 2x max blocksize\n\t\tzfs)     size=$(lctl get_param osc.$FSNAME*.import |\n\t\t\t\tawk '/grant_block_size:/ {print $2/512; exit;}')\n\t\t\t  ;;\n\tesac\n\n\techo -n $((size * MDSCOUNT))\n}\n\nfs_inode_ksize() {\n\tlocal facet=${1:-$SINGLEMDS}\n\tlocal fstype=$(facet_fstype $facet)\n\tlocal size=0\n\tcase $fstype in\n\t\tldiskfs) size=4;;  # ~4KB per inode\n\t\tzfs)     size=11;; # 10 to 11KB per inode\n\tesac\n\n\techo -n $size\n}\n\ncheck_gss_daemon_nodes() {\n    local list=$1\n    dname=$2\n\n    do_nodesv $list \"num=\\\\\\$(ps -o cmd -C $dname | grep $dname | wc -l);\nif [ \\\\\\\"\\\\\\$num\\\\\\\" -ne 1 ]; then\n    echo \\\\\\$num instance of $dname;\n    exit 1;\nfi; \"\n}\n\ncheck_gss_daemon_facet() {\n    facet=$1\n    dname=$2\n\n    num=`do_facet $facet ps -o cmd -C $dname | grep $dname | wc -l`\n    if [ $num -ne 1 ]; then\n        echo \"$num instance of $dname on $facet\"\n        return 1\n    fi\n    return 0\n}\n\nsend_sigint() {\n    local list=$1\n    shift\n    echo Stopping $@ on $list\n    do_nodes $list \"killall -2 $@ 2>/dev/null || true\"\n}\n\n# start gss daemons on all nodes, or \"daemon\" on \"nodes\" if set\nstart_gss_daemons() {\n\tlocal nodes=$1\n\tlocal daemon=$2\n\n\tif [ \"$nodes\" ] && [ \"$daemon\" ] ; then\n\t\techo \"Starting gss daemon on nodes: $nodes\"\n\t\tdo_nodes $nodes \"$daemon\" || return 8\n\t\treturn 0\n\tfi\n\n\tnodes=$(comma_list $(mdts_nodes))\n\techo \"Starting gss daemon on mds: $nodes\"\n\tif $GSS_SK; then\n\t\t# Start all versions, in case of switching\n\t\tdo_nodes $nodes \"$LSVCGSSD -vvv -s -m -o -z\" || return 1\n\telse\n\t\tdo_nodes $nodes \"$LSVCGSSD -v\" || return 1\n\tfi\n\tif $GSS_PIPEFS; then\n\t\tdo_nodes $nodes \"$LGSSD -v\" || return 2\n\tfi\n\n\tnodes=$(comma_list $(osts_nodes))\n\techo \"Starting gss daemon on ost: $nodes\"\n\tif $GSS_SK; then\n\t\t# Start all versions, in case of switching\n\t\tdo_nodes $nodes \"$LSVCGSSD -vvv -s -m -o -z\" || return 3\n\telse\n\t\tdo_nodes $nodes \"$LSVCGSSD -v\" || return 3\n\tfi\n\t# starting on clients\n\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tif $GSS_PIPEFS; then\n\t\techo \"Starting $LGSSD on clients $clients \"\n\t\tdo_nodes $clients  \"$LGSSD -v\" || return 4\n\tfi\n\n\t# wait daemons entering \"stable\" status\n\tsleep 5\n\n\t#\n\t# check daemons are running\n\t#\n\tnodes=$(comma_list $(mdts_nodes) $(osts_nodes))\n\tcheck_gss_daemon_nodes $nodes lsvcgssd || return 5\n\tif $GSS_PIPEFS; then\n\t\tnodes=$(comma_list $(mdts_nodes))\n\t\tcheck_gss_daemon_nodes $nodes lgssd || return 6\n\tfi\n\tif $GSS_PIPEFS; then\n\t\tcheck_gss_daemon_nodes $clients lgssd || return 7\n\tfi\n}\n\nstop_gss_daemons() {\n\tlocal nodes=$(comma_list $(mdts_nodes))\n\n\tsend_sigint $nodes lsvcgssd lgssd\n\n\tnodes=$(comma_list $(osts_nodes))\n\tsend_sigint $nodes lsvcgssd\n\n\tnodes=${CLIENTS:-$HOSTNAME}\n\tsend_sigint $nodes lgssd\n}\n\nadd_sk_mntflag() {\n\t# Add mount flags for shared key\n\tlocal mt_opts=$@\n\tif grep -q skpath <<< \"$mt_opts\" ; then\n\t\tmt_opts=$(echo $mt_opts |\n\t\t\tsed -e \"s#skpath=[^ ,]*#skpath=$SK_PATH#\")\n\telse\n\t\tif [ -z \"$mt_opts\" ]; then\n\t\t\tmt_opts=\"-o skpath=$SK_PATH\"\n\t\telse\n\t\t\tmt_opts=\"$mt_opts,skpath=$SK_PATH\"\n\t\tfi\n\tfi\n\techo -n $mt_opts\n}\n\nfrom_build_tree() {\n\tlocal from_tree\n\n\tcase $LUSTRE in\n\t/usr/lib/lustre/* | /usr/lib64/lustre/* | /usr/lib/lustre | \\\n\t/usr/lib64/lustre )\n\t\tfrom_tree=false\n\t\t;;\n\t*)\n\t\tfrom_tree=true\n\t\t;;\n\tesac\n\n\t[ $from_tree = true ]\n}\n\ninit_gss() {\n\tif $SHARED_KEY; then\n\t\tGSS=true\n\t\tGSS_SK=true\n\tfi\n\n\tif ! $GSS; then\n\t\treturn\n\tfi\n\n\tif ! module_loaded ptlrpc_gss; then\n\t\tload_module ptlrpc/gss/ptlrpc_gss\n\t\tmodule_loaded ptlrpc_gss ||\n\t\t\terror_exit \"init_gss: GSS=$GSS, but gss/krb5 missing\"\n\tfi\n\n\tif $GSS_KRB5 || $GSS_SK; then\n\t\tstart_gss_daemons || error_exit \"start gss daemon failed! rc=$?\"\n\tfi\n\n\tif $GSS_SK && $SK_NO_KEY; then\n\t\tlocal numclients=${1:-$CLIENTCOUNT}\n\t\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\t\t# security ctx config for keyring\n\t\tSK_NO_KEY=false\n\t\tlocal lgssc_conf_file=\"/etc/request-key.d/lgssc.conf\"\n\n\t\tif from_build_tree; then\n\t\t\tmkdir -p $SK_OM_PATH\n\t\t\tif grep -q request-key /proc/mounts > /dev/null; then\n\t\t\t\techo \"SSK: Request key already mounted.\"\n\t\t\telse\n\t\t\t\tmount -o bind $SK_OM_PATH /etc/request-key.d/\n\t\t\tfi\n\t\t\tlocal lgssc_conf_line='create lgssc * * '\n\t\t\tlgssc_conf_line+=$(which lgss_keyring)\n\t\t\tlgssc_conf_line+=' %o %k %t %d %c %u %g %T %P %S'\n\t\t\techo \"$lgssc_conf_line\" > $lgssc_conf_file\n\t\tfi\n\n\t\t[ -e $lgssc_conf_file ] ||\n\t\t\terror_exit \"Could not find key options in $lgssc_conf_file\"\n\t\techo \"$lgssc_conf_file content is:\"\n\t\tcat $lgssc_conf_file\n\n\t\tif ! local_mode; then\n\t\t\tif from_build_tree; then\n\t\t\t\tdo_nodes $(comma_list $(all_nodes)) \"mkdir -p \\\n\t\t\t\t\t$SK_OM_PATH\"\n\t\t\t\tdo_nodes $(comma_list $(all_nodes)) \"mount \\\n\t\t\t\t\t-o bind $SK_OM_PATH \\\n\t\t\t\t\t/etc/request-key.d/\"\n\t\t\t\tdo_nodes $(comma_list $(all_nodes)) \"rsync \\\n\t\t\t\t\t-aqv $HOSTNAME:$lgssc_conf_file \\\n\t\t\t\t\t$lgssc_conf_file >/dev/null 2>&1\"\n\t\t\telse\n\t\t\t\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t\t\t\t\"echo $lgssc_conf_file: ; \\\n\t\t\t\t\tcat $lgssc_conf_file\"\n\t\t\tfi\n\t\tfi\n\n\t\t# create shared key on all nodes\n\t\tmkdir -p $SK_PATH/nodemap\n\t\trm -f $SK_PATH/$FSNAME.key $SK_PATH/nodemap/c*.key \\\n\t\t\t$SK_PATH/$FSNAME-*.key\n\t\t# for nodemap testing each client may need own key,\n\t\t# and S2S now requires keys as well, both for \"client\"\n\t\t# and for \"server\"\n\t\tif $SK_S2S; then\n\t\t\tlgss_sk -t server -f$FSNAME -n $SK_S2SNMCLI \\\n\t\t\t\t-w $SK_PATH/$FSNAME-nmclient.key \\\n\t\t\t\t-d /dev/urandom >/dev/null 2>&1\n\t\t\tlgss_sk -t mgs,server -f$FSNAME -n $SK_S2SNM \\\n\t\t\t\t-w $SK_PATH/$FSNAME-s2s-server.key \\\n\t\t\t\t-d /dev/urandom >/dev/null 2>&1\n\t\tfi\n\t\t# basic key create\n\t\tlgss_sk -t server -f$FSNAME -w $SK_PATH/$FSNAME.key \\\n\t\t\t-d /dev/urandom >/dev/null 2>&1\n\t\t# per-nodemap keys\n\t\tfor i in $(seq 0 $((numclients - 1))); do\n\t\t\tlgss_sk -t server -f$FSNAME -n c$i \\\n\t\t\t\t-w $SK_PATH/nodemap/c$i.key -d /dev/urandom \\\n\t\t\t\t>/dev/null 2>&1\n\t\tdone\n\t\t# Distribute keys\n\t\tif ! local_mode; then\n\t\t\tfor lnode in $(all_nodes); do\n\t\t\t\tscp -r $SK_PATH ${lnode}:$(dirname $SK_PATH)/\n\t\t\tdone\n\t\tfi\n\t\t# Set client keys to client type to generate prime P\n\t\tif local_mode; then\n\t\t\tdo_nodes $(all_nodes) \"lgss_sk -t client,server -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\"\n\t\telse\n\t\t\tdo_nodes $clients \"lgss_sk -t client -m \\\n\t\t\t\t$SK_PATH/$FSNAME.key >/dev/null 2>&1\"\n\t\t\tdo_nodes $clients \"find $SK_PATH/nodemap -name \\*.key | \\\n\t\t\t\txargs -IX lgss_sk -t client -m X >/dev/null 2>&1\"\n\t\tfi\n\t\t# This is required for servers as well, if S2S in use\n\t\tif $SK_S2S; then\n\t\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\t\"cp $SK_PATH/$FSNAME-s2s-server.key \\\n\t\t\t\t$SK_PATH/$FSNAME-s2s-client.key; lgss_sk \\\n\t\t\t\t-t client -m $SK_PATH/$FSNAME-s2s-client.key \\\n\t\t\t\t>/dev/null 2>&1\"\n\t\t\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\t\t\"cp $SK_PATH/$FSNAME-s2s-server.key \\\n\t\t\t\t$SK_PATH/$FSNAME-s2s-client.key; lgss_sk \\\n\t\t\t\t-t client -m $SK_PATH/$FSNAME-s2s-client.key \\\n\t\t\t\t>/dev/null 2>&1\"\n\t\t\tdo_nodes $clients \"lgss_sk -t client \\\n\t\t\t\t-m $SK_PATH/$FSNAME-nmclient.key \\\n\t\t\t\t >/dev/null 2>&1\"\n\t\tfi\n\tfi\n\tif $GSS_SK; then\n\t\t# mount options for servers and clients\n\t\tMGS_MOUNT_OPTS=$(add_sk_mntflag $MGS_MOUNT_OPTS)\n\t\tMDS_MOUNT_OPTS=$(add_sk_mntflag $MDS_MOUNT_OPTS)\n\t\tOST_MOUNT_OPTS=$(add_sk_mntflag $OST_MOUNT_OPTS)\n\t\tMOUNT_OPTS=$(add_sk_mntflag $MOUNT_OPTS)\n\t\tSEC=$SK_FLAVOR\n\t\tif [ -z \"$LGSS_KEYRING_DEBUG\" ]; then\n\t\t\tLGSS_KEYRING_DEBUG=4\n\t\tfi\n\tfi\n\n\tif [ -n \"$LGSS_KEYRING_DEBUG\" ] && \\\n\t       ( local_mode || from_build_tree ); then\n\t\tlctl set_param -n \\\n\t\t     sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG\n\telif [ -n \"$LGSS_KEYRING_DEBUG\" ]; then\n\t\tdo_nodes $(comma_list $(all_nodes)) \"modprobe ptlrpc_gss && \\\n\t\tlctl set_param -n \\\n\t\t   sptlrpc.gss.lgss_keyring.debug_level=$LGSS_KEYRING_DEBUG\"\n\tfi\n}\n\ncleanup_gss() {\n\tif $GSS; then\n\t\tstop_gss_daemons\n\t\t# maybe cleanup credential cache?\n\tfi\n}\n\ncleanup_sk() {\n\tif $GSS_SK; then\n\t\tif $SK_S2S; then\n\t\t\tdo_node $(mgs_node) \"$LCTL nodemap_del $SK_S2SNM\"\n\t\t\tdo_node $(mgs_node) \"$LCTL nodemap_del $SK_S2SNMCLI\"\n\t\t\t$RPC_MODE || echo \"Sleeping for 10 sec for Nodemap..\"\n\t\t\tsleep 10\n\t\tfi\n\t\tstop_gss_daemons\n\t\t$RPC_MODE || echo \"Cleaning up Shared Key..\"\n\t\tdo_nodes $(comma_list $(all_nodes)) \"rm -f \\\n\t\t\t$SK_PATH/$FSNAME*.key $SK_PATH/nodemap/$FSNAME*.key\"\n\t\tdo_nodes $(comma_list $(all_nodes)) \"keyctl show | \\\n\t\t  awk '/lustre/ { print \\\\\\$1 }' | xargs -IX keyctl unlink X\"\n\t\tif from_build_tree; then\n\t\t\t# Remove the mount and clean up the files we added to\n\t\t\t# SK_PATH\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \"while grep -q \\\n\t\t\t\trequest-key.d /proc/mounts; do umount \\\n\t\t\t\t/etc/request-key.d/; done\"\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \"rm -f \\\n\t\t\t\t$SK_OM_PATH/lgssc.conf\"\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \"rmdir $SK_OM_PATH\"\n\t\tfi\n\t\tSK_NO_KEY=true\n\tfi\n}\n\nfacet_svc() {\n\tlocal facet=$1\n\tlocal var=${facet}_svc\n\n\techo -n ${!var}\n}\n\nfacet_type() {\n\tlocal facet=$1\n\n\techo -n $facet | sed -e 's/^fs[0-9]\\+//' -e 's/[0-9_]\\+//' |\n\t\ttr '[:lower:]' '[:upper:]'\n}\n\nfacet_number() {\n\tlocal facet=$1\n\n\tif [ $facet == mgs ] || [ $facet == client ]; then\n\t\treturn 1\n\tfi\n\n\techo -n $facet | sed -e 's/^fs[0-9]\\+//' | sed -e 's/^[a-z]\\+//'\n}\n\nfacet_fstype() {\n\tlocal facet=$1\n\tlocal var\n\n\tvar=${facet}_FSTYPE\n\tif [ -n \"${!var}\" ]; then\n\t\techo -n ${!var}\n\t\treturn\n\tfi\n\n\tvar=$(facet_type $facet)FSTYPE\n\tif [ -n \"${!var}\" ]; then\n\t\techo -n ${!var}\n\t\treturn\n\tfi\n\n\tif [ -n \"$FSTYPE\" ]; then\n\t\techo -n $FSTYPE\n\t\treturn\n\tfi\n\n\tif [[ $facet == mgs ]] && combined_mgs_mds; then\n\t\tfacet_fstype mds1\n\t\treturn\n\tfi\n\n\treturn 1\n}\n\nnode_fstypes() {\n\tlocal node=$1\n\tlocal fstypes\n\tlocal fstype\n\tlocal facets=$(get_facets)\n\tlocal facet\n\n\tfor facet in ${facets//,/ }; do\n\t\tif [ $node == $(facet_host $facet) ] ||\n\t\t   [ $node == \"$(facet_failover_host $facet)\" ]; then\n\t\t\tfstype=$(facet_fstype $facet)\n\t\t\tif [[ $fstypes != *$fstype* ]]; then\n\t\t\t\tfstypes+=\"${fstypes:+,}$fstype\"\n\t\t\tfi\n\t\tfi\n\tdone\n\techo -n $fstypes\n}\n\nfacet_index() {\n\tlocal facet=$1\n\tlocal num=$(facet_number $facet)\n\tlocal index\n\n\tif [[ $(facet_type $facet) = OST ]]; then\n\t\tindex=OSTINDEX${num}\n\t\tif [[ -n \"${!index}\" ]]; then\n\t\t\techo -n ${!index}\n\t\t\treturn\n\t\tfi\n\n\t\tindex=${OST_INDICES[num - 1]}\n\tfi\n\n\t[[ -n \"$index\" ]] || index=$((num - 1))\n\techo -n $index\n}\n\ndevicelabel() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal label\n\tlocal fstype=$(facet_fstype $facet)\n\n\tcase $fstype in\n\tldiskfs)\n\t\tlabel=$(do_facet ${facet} \"$E2LABEL ${dev} 2>/dev/null\");;\n\tzfs)\n\t\tlabel=$(do_facet ${facet} \"$ZFS get -H -o value lustre:svname \\\n\t\t                           ${dev} 2>/dev/null\");;\n\t*)\n\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $label\n}\n\nmdsdevlabel() {\n\tlocal num=$1\n\tlocal device=$(mdsdevname $num)\n\tlocal label=$(devicelabel mds$num ${device} | grep -v \"CMD: \")\n\techo -n $label\n}\n\nostdevlabel() {\n\tlocal num=$1\n\tlocal device=$(ostdevname $num)\n\tlocal label=$(devicelabel ost$num ${device} | grep -v \"CMD: \")\n\techo -n $label\n}\n\n#\n# Get the device of a facet.\n#\nfacet_device() {\n\tlocal facet=$1\n\tlocal device\n\n\tcase $facet in\n\t\tmgs) device=$(mgsdevname) ;;\n\t\tmds*) device=$(mdsdevname $(facet_number $facet)) ;;\n\t\tost*) device=$(ostdevname $(facet_number $facet)) ;;\n\t\tfs2mds) device=$(mdsdevname 1_2) ;;\n\t\tfs2ost) device=$(ostdevname 1_2) ;;\n\t\tfs3ost) device=$(ostdevname 2_2) ;;\n\t\t*) ;;\n\tesac\n\n\techo -n $device\n}\n\n#\n# Get the virtual device of a facet.\n#\nfacet_vdevice() {\n\tlocal facet=$1\n\tlocal device\n\n\tcase $facet in\n\t\tmgs) device=$(mgsvdevname) ;;\n\t\tmds*) device=$(mdsvdevname $(facet_number $facet)) ;;\n\t\tost*) device=$(ostvdevname $(facet_number $facet)) ;;\n\t\tfs2mds) device=$(mdsvdevname 1_2) ;;\n\t\tfs2ost) device=$(ostvdevname 1_2) ;;\n\t\tfs3ost) device=$(ostvdevname 2_2) ;;\n\t\t*) ;;\n\tesac\n\n\techo -n $device\n}\n\nrunning_in_vm() {\n\tlocal virt=$(virt-what 2> /dev/null)\n\n\t[ $? -eq 0 ] && [ -n \"$virt\" ] && { echo $virt; return; }\n\n\tvirt=$(dmidecode -s system-product-name | awk '{print $1}')\n\n\tcase $virt in\n\t\tVMware|KVM|VirtualBox|Parallels|Bochs)\n\t\t\techo $virt | tr '[A-Z]' '[a-z]' ;;\n\t\t*) ;;\n\tesac\n}\n\n#\n# Re-read the partition table on failover partner host.\n# After a ZFS storage pool is created on a shared device, the partition table\n# on the device may change. However, the operating system on the failover\n# host may not notice the change automatically. Without the up-to-date partition\n# block devices, 'zpool import ..' cannot find the labels, whose positions are\n# relative to partition rather than disk beginnings.\n#\n# This function performs partprobe on the failover host to make it re-read the\n# partition table.\n#\nrefresh_partition_table() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal host\n\n\thost=$(facet_passive_host $facet)\n\tif [[ -n \"$host\" ]]; then\n\t\tdo_node $host \"$PARTPROBE $device\"\n\tfi\n}\n\n#\n# Get ZFS storage pool name.\n#\nzpool_name() {\n\tlocal facet=$1\n\tlocal device\n\tlocal poolname\n\n\tdevice=$(facet_device $facet)\n\t# poolname is string before \"/\"\n\tpoolname=\"${device%%/*}\"\n\n\techo -n $poolname\n}\n\n#\n#\n# Get ZFS local fsname.\n#\nzfs_local_fsname() {\n\tlocal facet=$1\n\tlocal lfsname=$(basename $(facet_device $facet))\n\n\techo -n $lfsname\n}\n\n#\n# Create ZFS storage pool.\n#\ncreate_zpool() {\n\tlocal facet=$1\n\tlocal poolname=$2\n\tlocal vdev=$3\n\tshift 3\n\tlocal opts=${@:-\"-o cachefile=none\"}\n\n\tdo_facet $facet \"lsmod | grep zfs >&/dev/null || modprobe zfs;\n\t\t$ZPOOL list -H $poolname >/dev/null 2>&1 ||\n\t\t$ZPOOL create -f $opts $poolname $vdev\"\n}\n\n#\n# Create ZFS file system.\n#\ncreate_zfs() {\n\tlocal facet=$1\n\tlocal dataset=$2\n\tshift 2\n\tlocal opts=${@:-\"-o mountpoint=legacy\"}\n\n\tdo_facet $facet \"$ZFS list -H $dataset >/dev/null 2>&1 ||\n\t\t$ZFS create $opts $dataset\"\n}\n\n#\n# Export ZFS storage pool.\n# Before exporting the pool, all datasets within the pool should be unmounted.\n#\nexport_zpool() {\n\tlocal facet=$1\n\tshift\n\tlocal opts=\"$@\"\n\tlocal poolname\n\n\tpoolname=$(zpool_name $facet)\n\n\tif [[ -n \"$poolname\" ]]; then\n\t\tdo_facet $facet \"! $ZPOOL list -H $poolname >/dev/null 2>&1 ||\n\t\t\tgrep -q ^$poolname/ /proc/mounts ||\n\t\t\t$ZPOOL export $opts $poolname\"\n\tfi\n}\n\n#\n# Destroy ZFS storage pool.\n# Destroy the given pool and free up any devices for other use. This command\n# tries to unmount any active datasets before destroying the pool.\n# -f    Force any active datasets contained within the pool to be unmounted.\n#\ndestroy_zpool() {\n\tlocal facet=$1\n\tlocal poolname=${2:-$(zpool_name $facet)}\n\n\tif [[ -n \"$poolname\" ]]; then\n\t\tdo_facet $facet \"! $ZPOOL list -H $poolname >/dev/null 2>&1 ||\n\t\t\t$ZPOOL destroy -f $poolname\"\n\tfi\n}\n\n#\n# Import ZFS storage pool.\n# Force importing, even if the pool appears to be potentially active.\n#\nimport_zpool() {\n\tlocal facet=$1\n\tshift\n\tlocal opts=${@:-\"-o cachefile=none -o failmode=panic\"}\n\tlocal poolname\n\n\tpoolname=$(zpool_name $facet)\n\n\tif [[ -n \"$poolname\" ]]; then\n\t\topts+=\" -d $(dirname $(facet_vdevice $facet))\"\n\t\tdo_facet $facet \"lsmod | grep zfs >&/dev/null || modprobe zfs;\n\t\t\t$ZPOOL list -H $poolname >/dev/null 2>&1 ||\n\t\t\t$ZPOOL import -f $opts $poolname\"\n\tfi\n}\n\n#\n# Reimport ZFS storage pool with new name\n#\nreimport_zpool() {\n\tlocal facet=$1\n\tlocal newpool=$2\n\tlocal opts=\"-o cachefile=none\"\n\tlocal poolname=$(zpool_name $facet)\n\n\topts+=\" -d $(dirname $(facet_vdevice $facet))\"\n\tdo_facet $facet \"$ZPOOL export $poolname;\n\t\t\t $ZPOOL import $opts $poolname $newpool\"\n}\n\n#\n# Set the \"cachefile=none\" property on ZFS storage pool so that the pool\n# is not automatically imported on system startup.\n#\n# In a failover environment, this will provide resource level fencing which\n# will ensure that the same ZFS storage pool will not be imported concurrently\n# on different nodes.\n#\ndisable_zpool_cache() {\n\tlocal facet=$1\n\tlocal poolname\n\n\tpoolname=$(zpool_name $facet)\n\n\tif [[ -n \"$poolname\" ]]; then\n\t\tdo_facet $facet \"$ZPOOL set cachefile=none $poolname\"\n\tfi\n}\n\n#\n# This and set_osd_param() shall be used to access OSD parameters\n# once existed under \"obdfilter\":\n#\n#   mntdev\n#   stats\n#   read_cache_enable\n#   writethrough_cache_enable\n#\nget_osd_param() {\n\tlocal nodes=$1\n\tlocal device=${2:-$FSNAME-OST*}\n\tlocal name=$3\n\n\tdo_nodes $nodes \"$LCTL get_param -n obdfilter.$device.$name \\\n\t\tosd-*.$device.$name 2>&1\" | grep -v 'error:'\n}\n\nset_osd_param() {\n\tlocal nodes=$1\n\tlocal device=${2:-$FSNAME-OST*}\n\tlocal name=$3\n\tlocal value=$4\n\n\tdo_nodes $nodes \"$LCTL set_param -n obdfilter.$device.$name=$value \\\n\t\tosd-*.$device.$name=$value 2>&1\" | grep -v 'error:'\n}\n\nset_debug_size () {\n    local dz=${1:-$DEBUG_SIZE}\n\n    if [ -f /sys/devices/system/cpu/possible ]; then\n        local cpus=$(($(cut -d \"-\" -f 2 /sys/devices/system/cpu/possible)+1))\n    else\n        local cpus=$(getconf _NPROCESSORS_CONF 2>/dev/null)\n    fi\n\n    # bug 19944, adjust size to be -gt num_possible_cpus()\n    # promise 2MB for every cpu at least\n    if [ -n \"$cpus\" ] && [ $((cpus * 2)) -gt $dz ]; then\n        dz=$((cpus * 2))\n    fi\n    lctl set_param debug_mb=$dz\n}\n\nset_default_debug () {\n\tlocal debug=${1:-\"$PTLDEBUG\"}\n\tlocal subsys=${2:-\"$SUBSYSTEM\"}\n\tlocal debug_size=${3:-$DEBUG_SIZE}\n\n\t[ -n \"$debug\" ] && lctl set_param debug=\"$debug\" >/dev/null\n\t[ -n \"$subsys\" ] && lctl set_param subsystem_debug=\"${subsys# }\" >/dev/null\n\n\t[ -n \"$debug_size\" ] && set_debug_size $debug_size > /dev/null\n}\n\nset_default_debug_nodes () {\n\tlocal nodes=\"$1\"\n\tlocal debug=\"${2:-\"$PTLDEBUG\"}\"\n\tlocal subsys=\"${3:-\"$SUBSYSTEM\"}\"\n\tlocal debug_size=\"${4:-$DEBUG_SIZE}\"\n\n\tif [[ ,$nodes, = *,$HOSTNAME,* ]]; then\n\t\tnodes=$(exclude_items_from_list \"$nodes\" \"$HOSTNAME\")\n\t\tset_default_debug\n\tfi\n\n\t[[ -z \"$nodes\" ]] ||\n\t\tdo_rpc_nodes \"$nodes\" set_default_debug \\\n\t\t\t\\\\\\\"$debug\\\\\\\" \\\\\\\"$subsys\\\\\\\" $debug_size || true\n}\n\nset_default_debug_facet () {\n\tlocal facet=$1\n\tlocal debug=\"${2:-\"$PTLDEBUG\"}\"\n\tlocal subsys=\"${3:-\"$SUBSYSTEM\"}\"\n\tlocal debug_size=\"${4:-$DEBUG_SIZE}\"\n\tlocal node=$(facet_active_host $facet)\n\n\t[ -n \"$node\" ] || error \"No host defined for facet $facet\"\n\n\tset_default_debug_nodes $node \"$debug\" \"$subsys\" $debug_size\n}\n\nset_hostid () {\n    local hostid=${1:-$(hostid)}\n\n    if [ ! -s /etc/hostid ]; then\n\tprintf $(echo -n $hostid |\n\t    sed 's/\\(..\\)\\(..\\)\\(..\\)\\(..\\)/\\\\x\\4\\\\x\\3\\\\x\\2\\\\x\\1/') >/etc/hostid\n    fi\n}\n\n# Facet functions\nmount_facets () {\n\tlocal facets=${1:-$(get_facets)}\n\tlocal facet\n\n\tfor facet in ${facets//,/ }; do\n\t\tmount_facet $facet\n\t\tlocal RC=$?\n\t\t[ $RC -eq 0 ] && continue\n\n\t\tif [ \"$TESTSUITE.$TESTNAME\" = \"replay-dual.test_0a\" ]; then\n\t\t\tskip_noexit \"Restart of $facet failed!.\" &&\n\t\t\t\ttouch $LU482_FAILED\n\t\telse\n\t\t\terror \"Restart of $facet failed!\"\n\t\tfi\n\t\treturn $RC\n\tdone\n}\n\n#\n# Add argument \"arg\" (e.g., \"loop\") to the comma-separated list\n# of arguments for option \"opt\" (e.g., \"-o\") on command\n# line \"opts\" (e.g., \"-o flock\").\n#\ncsa_add() {\n\tlocal opts=$1\n\tlocal opt=$2\n\tlocal arg=$3\n\tlocal opt_pattern=\"\\([[:space:]]\\+\\|^\\)$opt\"\n\n\tif echo \"$opts\" | grep -q $opt_pattern; then\n\t\topts=$(echo \"$opts\" | sed -e \\\n\t\t\t\"s/$opt_pattern[[:space:]]*[^[:space:]]\\+/&,$arg/\")\n\telse\n\t\topts+=\"${opts:+ }$opt $arg\"\n\tfi\n\techo -n \"$opts\"\n}\n\n#\n# Associate loop device with a given regular file.\n# Return the loop device.\n#\nsetup_loop_device() {\n\tlocal facet=$1\n\tlocal file=$2\n\n\tdo_facet $facet \"loop_dev=\\\\\\$($LOSETUP -j $file | cut -d : -f 1);\n\t\t\t if [[ -z \\\\\\$loop_dev ]]; then\n\t\t\t\tloop_dev=\\\\\\$($LOSETUP -f);\n\t\t\t\t$LOSETUP \\\\\\$loop_dev $file || loop_dev=;\n\t\t\t fi;\n\t\t\t echo -n \\\\\\$loop_dev\"\n}\n\n#\n# Detach a loop device.\n#\ncleanup_loop_device() {\n\tlocal facet=$1\n\tlocal loop_dev=$2\n\n\tdo_facet $facet \"! $LOSETUP $loop_dev >/dev/null 2>&1 ||\n\t\t\t $LOSETUP -d $loop_dev\"\n}\n\n#\n# Check if a given device is a block device.\n#\nis_blkdev() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal size=${3:-\"\"}\n\n\t[[ -n \"$dev\" ]] || return 1\n\tdo_facet $facet \"test -b $dev\" || return 1\n\tif [[ -n \"$size\" ]]; then\n\t\tlocal in=$(do_facet $facet \"dd if=$dev of=/dev/null bs=1k \\\n\t\t\t\t\t    count=1 skip=$size 2>&1\" |\n\t\t\t\t\t    awk '($3 == \"in\") { print $1 }')\n\t\t[[ \"$in\" = \"1+0\" ]] || return 1\n\tfi\n}\n\n#\n# Check if a given device is a device-mapper device.\n#\nis_dm_dev() {\n\tlocal facet=$1\n\tlocal dev=$2\n\n\t[[ -n \"$dev\" ]] || return 1\n\tdo_facet $facet \"$DMSETUP status $dev >/dev/null 2>&1\"\n}\n\n#\n# Check if a given device is a device-mapper flakey device.\n#\nis_dm_flakey_dev() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal type\n\n\t[[ -n \"$dev\" ]] || return 1\n\n\ttype=$(do_facet $facet \"$DMSETUP status $dev 2>&1\" |\n\t       awk '{print $3}')\n\t[[ $type = flakey ]] && return 0 || return 1\n}\n\n#\n# Check if device-mapper flakey device is supported by the kernel\n# of $facet node or not.\n#\ndm_flakey_supported() {\n\tlocal facet=$1\n\n\t$FLAKEY || return 1\n\tdo_facet $facet \"modprobe dm-flakey;\n\t\t\t $DMSETUP targets | grep -q flakey\" &> /dev/null\n}\n\n#\n# Get the device-mapper flakey device name of a given facet.\n#\ndm_facet_devname() {\n\tlocal facet=$1\n\t[[ $facet = mgs ]] && combined_mgs_mds && facet=mds1\n\n\techo -n ${facet}_flakey\n}\n\n#\n# Get the device-mapper flakey device of a given facet.\n# A device created by dmsetup will appear as /dev/mapper/<device-name>.\n#\ndm_facet_devpath() {\n\tlocal facet=$1\n\n\techo -n $DM_DEV_PATH/$(dm_facet_devname $facet)\n}\n\n#\n# Set a device-mapper device with a new table.\n#\n# The table has the following format:\n# <logical_start_sector> <num_sectors> <target_type> <target_args>\n#\n# flakey <target_args> includes:\n# <destination_device> <offset> <up_interval> <down_interval> \\\n# [<num_features> [<feature_arguments>]]\n#\n# linear <target_args> includes:\n# <destination_device> <start_sector>\n#\ndm_set_dev_table() {\n\tlocal facet=$1\n\tlocal dm_dev=$2\n\tlocal target_type=$3\n\tlocal num_sectors\n\tlocal real_dev\n\tlocal tmp\n\tlocal table\n\n\tread tmp num_sectors tmp real_dev tmp \\\n\t\t<<< $(do_facet $facet \"$DMSETUP table $dm_dev\")\n\n\tcase $target_type in\n\tflakey)\n\t\ttable=\"0 $num_sectors flakey $real_dev 0 0 1800 1 drop_writes\"\n\t\t;;\n\tlinear)\n\t\ttable=\"0 $num_sectors linear $real_dev 0\"\n\t\t;;\n\t*) error \"invalid target type $target_type\" ;;\n\tesac\n\n\tdo_facet $facet \"$DMSETUP suspend --nolockfs --noflush $dm_dev\" ||\n\t\terror \"failed to suspend $dm_dev\"\n\tdo_facet $facet \"$DMSETUP load $dm_dev --table \\\\\\\"$table\\\\\\\"\" ||\n\t\terror \"failed to load $target_type table into $dm_dev\"\n\tdo_facet $facet \"$DMSETUP resume $dm_dev\" ||\n\t\terror \"failed to resume $dm_dev\"\n}\n\n#\n# Set a device-mapper flakey device as \"read-only\" by using the \"drop_writes\"\n# feature parameter.\n#\n# drop_writes:\n#\tAll write I/O is silently ignored.\n#\tRead I/O is handled correctly.\n#\ndm_set_dev_readonly() {\n\tlocal facet=$1\n\tlocal dm_dev=${2:-$(dm_facet_devpath $facet)}\n\n\tdm_set_dev_table $facet $dm_dev flakey\n}\n\n#\n# Set a device-mapper device to traditional linear mapping mode.\n#\ndm_clear_dev_readonly() {\n\tlocal facet=$1\n\tlocal dm_dev=${2:-$(dm_facet_devpath $facet)}\n\n\tdm_set_dev_table $facet $dm_dev linear\n}\n\n#\n# Set the device of a given facet as \"read-only\".\n#\nset_dev_readonly() {\n\tlocal facet=$1\n\tlocal svc=${facet}_svc\n\n\tif [[ $(facet_fstype $facet) = zfs ]] ||\n\t   ! dm_flakey_supported $facet; then\n\t\tdo_facet $facet $LCTL --device ${!svc} readonly\n\telse\n\t\tdm_set_dev_readonly $facet\n\tfi\n}\n\n#\n# Get size in 512-byte sectors (BLKGETSIZE64 / 512) of a given device.\n#\nget_num_sectors() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal num_sectors\n\n\tnum_sectors=$(do_facet $facet \"blockdev --getsz $dev 2>/dev/null\")\n\t[[ ${PIPESTATUS[0]} = 0 && -n \"$num_sectors\" ]] || num_sectors=0\n\techo -n $num_sectors\n}\n\n#\n# Create a device-mapper device with a given block device or regular file (will\n# be associated with loop device).\n# Return the full path of the device-mapper device.\n#\ndm_create_dev() {\n\tlocal facet=$1\n\tlocal real_dev=$2\t\t\t\t   # destination device\n\tlocal dm_dev_name=${3:-$(dm_facet_devname $facet)} # device name\n\tlocal dm_dev=$DM_DEV_PATH/$dm_dev_name\t\t  # device-mapper device\n\n\t# check if the device-mapper device to be created already exists\n\tif is_dm_dev $facet $dm_dev; then\n\t\t# if the existing device was set to \"read-only\", then clear it\n\t\t! is_dm_flakey_dev $facet $dm_dev ||\n\t\t\tdm_clear_dev_readonly $facet $dm_dev\n\n\t\techo -n $dm_dev\n\t\treturn 0\n\tfi\n\n\t# check if the destination device is a block device, and if not,\n\t# associate it with a loop device\n\tis_blkdev $facet $real_dev ||\n\t\treal_dev=$(setup_loop_device $facet $real_dev)\n\t[[ -n \"$real_dev\" ]] || { echo -n $real_dev; return 2; }\n\n\t# now create the device-mapper device\n\tlocal num_sectors=$(get_num_sectors $facet $real_dev)\n\tlocal table=\"0 $num_sectors linear $real_dev 0\"\n\tlocal rc=0\n\n\tdo_facet $facet \"$DMSETUP create $dm_dev_name --table \\\\\\\"$table\\\\\\\"\" ||\n\t\t{ rc=${PIPESTATUS[0]}; dm_dev=; }\n\tdo_facet $facet \"$DMSETUP mknodes >/dev/null 2>&1\"\n\n\techo -n $dm_dev\n\treturn $rc\n}\n\n#\n# Map the facet name to its device variable name.\n#\nfacet_device_alias() {\n\tlocal facet=$1\n\tlocal dev_alias=$facet\n\n\tcase $facet in\n\t\tfs2mds) dev_alias=mds1_2 ;;\n\t\tfs2ost) dev_alias=ost1_2 ;;\n\t\tfs3ost) dev_alias=ost2_2 ;;\n\t\t*) ;;\n\tesac\n\n\techo -n $dev_alias\n}\n\n#\n# Save the original value of the facet device and export the new value.\n#\nexport_dm_dev() {\n\tlocal facet=$1\n\tlocal dm_dev=$2\n\n\tlocal active_facet=$(facet_active $facet)\n\tlocal dev_alias=$(facet_device_alias $active_facet)\n\tlocal dev_name=${dev_alias}_dev\n\tlocal dev=${!dev_name}\n\n\tif [[ $active_facet = $facet ]]; then\n\t\tlocal failover_dev=${dev_alias}failover_dev\n\t\tif [[ ${!failover_dev} = $dev ]]; then\n\t\t\teval export ${failover_dev}_saved=$dev\n\t\t\teval export ${failover_dev}=$dm_dev\n\t\tfi\n\telse\n\t\tdev_alias=$(facet_device_alias $facet)\n\t\tlocal facet_dev=${dev_alias}_dev\n\t\tif [[ ${!facet_dev} = $dev ]]; then\n\t\t\teval export ${facet_dev}_saved=$dev\n\t\t\teval export ${facet_dev}=$dm_dev\n\t\tfi\n\tfi\n\n\teval export ${dev_name}_saved=$dev\n\teval export ${dev_name}=$dm_dev\n}\n\n#\n# Restore the saved value of the facet device.\n#\nunexport_dm_dev() {\n\tlocal facet=$1\n\n\t[[ $facet = mgs ]] && combined_mgs_mds && facet=mds1\n\tlocal dev_alias=$(facet_device_alias $facet)\n\n\tlocal saved_dev=${dev_alias}_dev_saved\n\t[[ -z ${!saved_dev} ]] ||\n\t\teval export ${dev_alias}_dev=${!saved_dev}\n\n\tsaved_dev=${dev_alias}failover_dev_saved\n\t[[ -z ${!saved_dev} ]] ||\n\t\teval export ${dev_alias}failover_dev=${!saved_dev}\n}\n\n#\n# Remove a device-mapper device.\n# If the destination device is a loop device, then also detach it.\n#\ndm_cleanup_dev() {\n\tlocal facet=$1\n\tlocal dm_dev=${2:-$(dm_facet_devpath $facet)}\n\tlocal major\n\tlocal minor\n\n\tis_dm_dev $facet $dm_dev || return 0\n\n\tread major minor <<< $(do_facet $facet \"$DMSETUP table $dm_dev\" |\n\t\tawk '{ print $4 }' | awk -F: '{ print $1\" \"$2 }')\n\n\tdo_facet $facet \"$DMSETUP remove $dm_dev\"\n\tdo_facet $facet \"$DMSETUP mknodes >/dev/null 2>&1\"\n\n\tunexport_dm_dev $facet\n\n\t# detach a loop device\n\t[[ $major -ne 7 ]] || cleanup_loop_device $facet /dev/loop$minor\n\n\t# unload dm-flakey module\n\tdo_facet $facet \"modprobe -r dm-flakey\" || true\n}\n\nmount_facet() {\n\tlocal facet=$1\n\tshift\n\tlocal active_facet=$(facet_active $facet)\n\tlocal dev_alias=$(facet_device_alias $active_facet)\n\tlocal dev=${dev_alias}_dev\n\tlocal opt=${facet}_opt\n\tlocal mntpt=$(facet_mntpt $facet)\n\tlocal opts=\"${!opt} $@\"\n\tlocal fstype=$(facet_fstype $facet)\n\tlocal devicelabel\n\tlocal dm_dev=${!dev}\n\n\tmodule_loaded lustre || load_modules\n\n\tcase $fstype in\n\tldiskfs)\n\t\tif dm_flakey_supported $facet; then\n\t\t\tdm_dev=$(dm_create_dev $facet ${!dev})\n\t\t\t[[ -n \"$dm_dev\" ]] || dm_dev=${!dev}\n\t\tfi\n\n\t\tis_blkdev $facet $dm_dev || opts=$(csa_add \"$opts\" -o loop)\n\n\t\tdevicelabel=$(do_facet ${facet} \"$E2LABEL $dm_dev\");;\n\tzfs)\n\t\t# import ZFS storage pool\n\t\timport_zpool $facet || return ${PIPESTATUS[0]}\n\n\t\tdevicelabel=$(do_facet ${facet} \"$ZFS get -H -o value \\\n\t\t\t\t\t\tlustre:svname $dm_dev\");;\n\t*)\n\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo \"Starting ${facet}: $opts $dm_dev $mntpt\"\n\t# for testing LU-482 error handling in mount_facets() and test_0a()\n\tif [ -f $TMP/test-lu482-trigger ]; then\n\t\tRC=2\n\telse\n\t\tdo_facet ${facet} \\\n\t\t\t\"mkdir -p $mntpt; $MOUNT_CMD $opts $dm_dev $mntpt\"\n\t\tRC=${PIPESTATUS[0]}\n\tfi\n\n\tif [ $RC -ne 0 ]; then\n\t\techo \"Start of $dm_dev on ${facet} failed ${RC}\"\n\t\treturn $RC\n\tfi\n\n\thealth=$(do_facet ${facet} \"$LCTL get_param -n health_check\")\n\tif [[ \"$health\" != \"healthy\" ]]; then\n\t\terror \"$facet is in a unhealthy state\"\n\tfi\n\n\tset_default_debug_facet $facet\n\n\tif [[ $opts =~ .*nosvc.* ]]; then\n\t\techo \"Start $dm_dev without service\"\n\telse\n\n\t\tcase $fstype in\n\t\tldiskfs)\n\t\t\twait_update_facet ${facet} \"$E2LABEL $dm_dev \\\n\t\t\t\t2>/dev/null | grep -E ':[a-zA-Z]{3}[0-9]{4}'\" \\\n\t\t\t\t\"\" || error \"$dm_dev failed to initialize!\";;\n\t\tzfs)\n\t\t\twait_update_facet ${facet} \"$ZFS get -H -o value \\\n\t\t\t\tlustre:svname $dm_dev 2>/dev/null | \\\n\t\t\t\tgrep -E ':[a-zA-Z]{3}[0-9]{4}'\" \"\" ||\n\t\t\t\terror \"$dm_dev failed to initialize!\";;\n\n\t\t*)\n\t\t\terror \"unknown fstype!\";;\n\t\tesac\n\tfi\n\n\t# commit the device label change to disk\n\tif [[ $devicelabel =~ (:[a-zA-Z]{3}[0-9]{4}) ]]; then\n\t\techo \"Commit the device label on ${!dev}\"\n\t\tdo_facet $facet \"sync; sleep 1; sync\"\n\tfi\n\n\n\tlabel=$(devicelabel ${facet} $dm_dev)\n\t[ -z \"$label\" ] && echo no label for $dm_dev && exit 1\n\teval export ${facet}_svc=${label}\n\techo Started ${label}\n\n\texport_dm_dev $facet $dm_dev\n\n\treturn $RC\n}\n\n# start facet device options\nstart() {\n\tlocal facet=$1\n\tshift\n\tlocal device=$1\n\tshift\n\tlocal dev_alias=$(facet_device_alias $facet)\n\n\teval export ${dev_alias}_dev=${device}\n\teval export ${facet}_opt=\\\"$@\\\"\n\n\tlocal varname=${dev_alias}failover_dev\n\tif [ -n \"${!varname}\" ] ; then\n\t\teval export ${dev_alias}failover_dev=${!varname}\n\telse\n\t\teval export ${dev_alias}failover_dev=$device\n\tfi\n\n\tlocal mntpt=$(facet_mntpt $facet)\n\tdo_facet ${facet} mkdir -p $mntpt\n\teval export ${facet}_MOUNT=$mntpt\n\tmount_facet ${facet}\n\tRC=$?\n\n\treturn $RC\n}\n\nstop() {\n\tlocal running\n\tlocal facet=$1\n\tshift\n\tlocal HOST=$(facet_active_host $facet)\n\t[[ -z $HOST ]] && echo stop: no host for $facet && return 0\n\n\tlocal mntpt=$(facet_mntpt $facet)\n\trunning=$(do_facet ${facet} \"grep -c $mntpt' ' /proc/mounts || true\")\n\tif [ ${running} -ne 0 ]; then\n\t\techo \"Stopping $mntpt (opts:$@) on $HOST\"\n\t\tdo_facet ${facet} $UMOUNT $@ $mntpt\n\tfi\n\n\t# umount should block, but we should wait for unrelated obd's\n\t# like the MGS or MGC to also stop.\n\twait_exit_ST ${facet} || return ${PIPESTATUS[0]}\n\n\tif [[ $(facet_fstype $facet) == zfs ]]; then\n\t\t# export ZFS storage pool\n\t\t[ \"$KEEP_ZPOOL\" = \"true\" ] || export_zpool $facet\n\telif dm_flakey_supported $facet; then\n\t\tlocal host=${facet}_HOST\n\t\tlocal failover_host=${facet}failover_HOST\n\t\tif [[ -n ${!failover_host} && ${!failover_host} != ${!host} ]]||\n\t\t\t$CLEANUP_DM_DEV || [[ $facet = fs* ]]; then\n\t\t\tdm_cleanup_dev $facet\n\t\tfi\n\tfi\n}\n\n# get mdt quota type\nmdt_quota_type() {\n\tlocal varsvc=${SINGLEMDS}_svc\n\tdo_facet $SINGLEMDS $LCTL get_param -n \\\n\t\tosd-$(facet_fstype $SINGLEMDS).${!varsvc}.quota_slave.enabled\n}\n\n# get ost quota type\nost_quota_type() {\n\t# All OSTs should have same quota type\n\tlocal varsvc=ost1_svc\n\tdo_facet ost1 $LCTL get_param -n \\\n\t\tosd-$(facet_fstype ost1).${!varsvc}.quota_slave.enabled\n}\n\n# restore old quota type settings\nrestore_quota() {\n\tif [ \"$old_MDT_QUOTA_TYPE\" ]; then\n\t\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\t\tdo_facet mgs $PERM_CMD \\\n\t\t\t\tosd-*.$FSNAME-MDT*.quota_slave.enable = \\\n\t\t\t\t$old_MDT_QUOTA_TYPE\n\t\telse\n\t\t\tdo_facet mgs $PERM_CMD \\\n\t\t\t\t$FSNAME.quota.mdt=$old_MDT_QUOTA_TYPE\n\t\tfi\n\tfi\n\tif [ \"$old_OST_QUOTA_TYPE\" ]; then\n\t\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\t\tdo_facet mgs $PERM_CMD \\\n\t\t\t\tosd-*.$FSNAME-OST*.quota_slave.enable = \\\n\t\t\t\t$old_OST_QUOTA_TYPE\n\t\telse\n\t\t\tdo_facet mgs $LCTL conf_param \\\n\t\t\t\t$FSNAME.quota.ost=$old_OST_QUOTA_TYPE\n\t\tfi\n\tfi\n}\n\n# Handle the case when there is a space in the lfs df\n# \"filesystem summary\" line the same as when there is no space.\n# This will allow fixing the \"lfs df\" summary line in the future.\nlfs_df() {\n\t$LFS df $* | sed -e 's/filesystem /filesystem_/'\n}\n\n# Get free inodes on the MDT specified by mdt index, free indoes on\n# the whole filesystem will be returned when index == -1.\nmdt_free_inodes() {\n\tlocal index=$1\n\tlocal free_inodes\n\tlocal mdt_uuid\n\n\tif [ $index -eq -1 ]; then\n\t\tmdt_uuid=\"summary\"\n\telse\n\t\tmdt_uuid=$(mdtuuid_from_index $index)\n\tfi\n\n\tfree_inodes=$(lfs_df -i $MOUNT | grep $mdt_uuid | awk '{print $4}')\n\techo $free_inodes\n}\n\n#\n# Get the OST device status from 'lfs df' with a given OST index.\n#\nost_dev_status() {\n\tlocal ost_idx=$1\n\tlocal mnt_pnt=${2:-$MOUNT}\n\tlocal opts=$3\n\tlocal ost_uuid\n\n\tost_uuid=$(ostuuid_from_index $ost_idx $mnt_pnt)\n\tlfs_df $opts $mnt_pnt | awk '/'$ost_uuid'/ { print $7 }'\n}\n\nsetup_quota(){\n\tlocal mntpt=$1\n\n\t# save old quota type & set new quota type\n\tlocal mdt_qtype=$(mdt_quota_type)\n\tlocal ost_qtype=$(ost_quota_type)\n\n\techo \"[HOST:$HOSTNAME] [old_mdt_qtype:$mdt_qtype]\" \\\n\t\t\"[old_ost_qtype:$ost_qtype] [new_qtype:$QUOTA_TYPE]\"\n\n\texport old_MDT_QUOTA_TYPE=$mdt_qtype\n\texport old_OST_QUOTA_TYPE=$ost_qtype\n\n\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\tdo_facet mgs $PERM_CMD \\\n\t\t\tosd-*.$FSNAME-MDT*.quota_slave.enable=$QUOTA_TYPE\n\t\tdo_facet mgs $PERM_CMD \\\n\t\t\tosd-*.$FSNAME-OST*.quota_slave.enable=$QUOTA_TYPE\n\telse\n\t\tdo_facet mgs $PERM_CMD $FSNAME.quota.mdt=$QUOTA_TYPE ||\n\t\t\terror \"set mdt quota type failed\"\n\t\tdo_facet mgs $PERM_CMD $FSNAME.quota.ost=$QUOTA_TYPE ||\n\t\t\terror \"set ost quota type failed\"\n\tfi\n\n\tlocal quota_usrs=$QUOTA_USERS\n\n\t# get_filesystem_size\n\tlocal disksz=$(lfs_df $mntpt | grep \"summary\" | awk '{print $2}')\n\tlocal blk_soft=$((disksz + 1024))\n\tlocal blk_hard=$((blk_soft + blk_soft / 20)) # Go 5% over\n\n\tlocal inodes=$(lfs_df -i $mntpt | grep \"summary\" | awk '{print $2}')\n\tlocal i_soft=$inodes\n\tlocal i_hard=$((i_soft + i_soft / 20))\n\n\techo \"Total disk size: $disksz  block-softlimit: $blk_soft\" \\\n\t\t\"block-hardlimit: $blk_hard inode-softlimit: $i_soft\" \\\n\t\t\"inode-hardlimit: $i_hard\"\n\n\tlocal cmd\n\tfor usr in $quota_usrs; do\n\t\techo \"Setting up quota on $HOSTNAME:$mntpt for $usr...\"\n\t\tfor type in u g; do\n\t\t\tcmd=\"$LFS setquota -$type $usr -b $blk_soft\"\n\t\t\tcmd=\"$cmd -B $blk_hard -i $i_soft -I $i_hard $mntpt\"\n\t\t\techo \"+ $cmd\"\n\t\t\teval $cmd || error \"$cmd FAILED!\"\n\t\tdone\n\t\t# display the quota status\n\t\techo \"Quota settings for $usr : \"\n\t\t$LFS quota -v -u $usr $mntpt || true\n\tdone\n}\n\nzconf_mount() {\n\tlocal client=$1\n\tlocal mnt=$2\n\tlocal opts=${3:-$MOUNT_OPTS}\n\topts=${opts:+-o $opts}\n\tlocal flags=${4:-$MOUNT_FLAGS}\n\n\tlocal device=$MGSNID:/$FSNAME$FILESET\n\tif [ -z \"$mnt\" -o -z \"$FSNAME\" ]; then\n\t\techo \"Bad mount command: opt=$flags $opts dev=$device \" \\\n\t\t     \"mnt=$mnt\"\n\t\texit 1\n\tfi\n\n\tif $GSS_SK; then\n\t\t# update mount option with skpath\n\t\topts=$(add_sk_mntflag $opts)\n\tfi\n\n\techo \"Starting client: $client: $flags $opts $device $mnt\"\n\tdo_node $client mkdir -p $mnt\n\tif [ -n \"$FILESET\" -a -z \"$SKIP_FILESET\" ];then\n\t\tdo_node $client $MOUNT_CMD $flags $opts $MGSNID:/$FSNAME \\\n\t\t\t$mnt || return 1\n\t\t#disable FILESET if not supported\n\t\tdo_nodes $client lctl get_param -n \\\n\t\t\tmdc.$FSNAME-MDT0000*.import | grep -q subtree ||\n\t\t\t\tdevice=$MGSNID:/$FSNAME\n\t\tdo_node $client mkdir -p $mnt/$FILESET\n\t\tdo_node $client \"! grep -q $mnt' ' /proc/mounts ||\n\t\t\tumount $mnt\"\n\tfi\n\tif $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then\n\t\t# Mount using nodemap key\n\t\tlocal mountkey=$SK_PATH/$FSNAME-nmclient.key\n\t\tif $SK_UNIQUE_NM; then\n\t\t\tmountkey=$SK_PATH/nodemap/c0.key\n\t\tfi\n\t\tlocal prunedopts=$(echo $opts |\n\t\t\t\tsed -e \"s#skpath=[^,^ ]*#skpath=$mountkey#g\")\n\t\tdo_node $client $MOUNT_CMD $flags $prunedopts $device $mnt ||\n\t\t\t\treturn 1\n\telse\n\t\tdo_node $client $MOUNT_CMD $flags $opts $device $mnt ||\n\t\t\t\treturn 1\n\tfi\n\n\tset_default_debug_nodes $client\n\n\treturn 0\n}\n\nzconf_umount() {\n\tlocal client=$1\n\tlocal mnt=$2\n\tlocal force\n\tlocal busy\n\tlocal need_kill\n\tlocal running=$(do_node $client \"grep -c $mnt' ' /proc/mounts\") || true\n\n\t[ \"$3\" ] && force=-f\n\t[ $running -eq 0 ] && return 0\n\n\techo \"Stopping client $client $mnt (opts:$force)\"\n\tdo_node $client lsof -t $mnt || need_kill=no\n\tif [ \"x$force\" != \"x\" ] && [ \"x$need_kill\" != \"xno\" ]; then\n\t\tpids=$(do_node $client lsof -t $mnt | sort -u);\n\t\tif [ -n \"$pids\" ]; then\n\t\t\tdo_node $client kill -9 $pids || true\n\t\tfi\n\tfi\n\n\tbusy=$(do_node $client \"umount $force $mnt 2>&1\" | grep -c \"busy\") ||\n\t\ttrue\n\tif [ $busy -ne 0 ] ; then\n\t\techo \"$mnt is still busy, wait one second\" && sleep 1\n\t\tdo_node $client umount $force $mnt\n\tfi\n}\n\n# Mount the file system on the MDS\nmount_mds_client() {\n\tlocal mds_HOST=${SINGLEMDS}_HOST\n\techo $mds_HOST\n\tzconf_mount $mds1_HOST $MOUNT2 $MOUNT_OPTS ||\n\t\terror \"unable to mount $MOUNT2 on MDS\"\n}\n\n# Unmount the file system on the MDS\numount_mds_client() {\n\tlocal mds_HOST=${SINGLEMDS}_HOST\n\tzconf_umount $mds1_HOST $MOUNT2\n\tdo_facet $SINGLEMDS \"rmdir $MOUNT2\"\n}\n\n# nodes is comma list\nsanity_mount_check_nodes () {\n    local nodes=$1\n    shift\n    local mnts=\"$@\"\n    local mnt\n\n    # FIXME: assume that all cluster nodes run the same os\n    [ \"$(uname)\" = Linux ] || return 0\n\n    local rc=0\n    for mnt in $mnts ; do\n        do_nodes $nodes \"running=\\\\\\$(grep -c $mnt' ' /proc/mounts);\nmpts=\\\\\\$(mount | grep -c $mnt' ');\nif [ \\\\\\$running -ne \\\\\\$mpts ]; then\n    echo \\\\\\$(hostname) env are INSANE!;\n    exit 1;\nfi\"\n    [ $? -eq 0 ] || rc=1\n    done\n    return $rc\n}\n\nsanity_mount_check_servers () {\n    [ -n \"$CLIENTONLY\" ] &&\n        { echo \"CLIENTONLY mode, skip mount_check_servers\"; return 0; } || true\n    echo Checking servers environments\n\n    # FIXME: modify get_facets to display all facets wo params\n    local facets=\"$(get_facets OST),$(get_facets MDS),mgs\"\n    local node\n    local mntpt\n    local facet\n    for facet in ${facets//,/ }; do\n        node=$(facet_host ${facet})\n        mntpt=$(facet_mntpt $facet)\n        sanity_mount_check_nodes $node $mntpt ||\n            { error \"server $node environments are insane!\"; return 1; }\n    done\n}\n\nsanity_mount_check_clients () {\n    local clients=${1:-$CLIENTS}\n    local mntpt=${2:-$MOUNT}\n    local mntpt2=${3:-$MOUNT2}\n\n    [ -z $clients ] && clients=$(hostname)\n    echo Checking clients $clients environments\n\n    sanity_mount_check_nodes $clients $mntpt $mntpt2 ||\n       error \"clients environments are insane!\"\n}\n\nsanity_mount_check () {\n    sanity_mount_check_servers || return 1\n    sanity_mount_check_clients || return 2\n}\n\n# mount clients if not mouted\nzconf_mount_clients() {\n\tlocal clients=$1\n\tlocal mnt=$2\n\tlocal opts=${3:-$MOUNT_OPTS}\n\topts=${opts:+-o $opts}\n\tlocal flags=${4:-$MOUNT_FLAGS}\n\tlocal device=$MGSNID:/$FSNAME$FILESET\n\tif [ -z \"$mnt\" -o -z \"$FSNAME\" ]; then\n\t\techo \"Bad conf mount command: opt=$flags $opts dev=$device \" \\\n\t\t     \"mnt=$mnt\"\n\t\texit 1\n\tfi\n\n\techo \"Starting client $clients: $flags $opts $device $mnt\"\n\tdo_nodes $clients mkdir -p $mnt\n\tif [ -n \"$FILESET\" -a -z \"$SKIP_FILESET\" ]; then\n\t\tif $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then\n\t\t\t# Mount with own nodemap key\n\t\t\tlocal i=0\n\t\t\t# Mount all server nodes first with per-NM keys\n\t\t\tfor nmclient in ${clients//,/ }; do\n#\t\t\t\tdo_nodes $(comma_list $(all_server_nodes)) \"lgss_sk -t server -l $SK_PATH/nodemap/c$i.key -n c$i\"\n\t\t\t\tdo_nodes $(comma_list $(all_server_nodes)) \"lgss_sk -t server -l $SK_PATH/nodemap/c$i.key\"\n\t\t\t\ti=$((i + 1))\n\t\t\tdone\n\t\t\t# set perms for per-nodemap keys else permission denied\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t\t\t\"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\t\t\tlocal mountkey=$SK_PATH/$FSNAME-nmclient.key\n\t\t\ti=0\n\t\t\tfor nmclient in ${clients//,/ }; do\n\t\t\t\tif $SK_UNIQUE_NM; then\n\t\t\t\t\tmountkey=$SK_PATH/nodemap/c$i.key\n\t\t\t\tfi\n\t\t\t\tdo_node $nmclient \"! grep -q $mnt' ' \\\n\t\t\t\t\t/proc/mounts || umount $mnt\"\n\t\t\t\tlocal prunedopts=$(add_sk_mntflag $prunedopts);\n\t\t\t\tprunedopts=$(echo $prunedopts | sed -e \\\n\t\t\t\t\t\"s#skpath=[^ ^,]*#skpath=$mountkey#g\")\n\t\t\t\tset -x\n\t\t\t\tdo_nodes $(comma_list $(all_server_nodes)) \\\n\t\t\t\t\t\"keyctl show\"\n\t\t\t\tset +x\n\t\t\t\tdo_node $nmclient $MOUNT_CMD $flags \\\n\t\t\t\t\t$prunedopts $MGSNID:/$FSNAME $mnt ||\n\t\t\t\t\treturn 1\n\t\t\t\ti=$((i + 1))\n\t\t\tdone\n\t\telse\n\t\t\tdo_nodes $clients \"! grep -q $mnt' ' /proc/mounts ||\n\t\t\t\t\tumount $mnt\"\n\t\t\tdo_nodes $clients $MOUNT_CMD $flags $opts \\\n\t\t\t\t\t$MGSNID:/$FSNAME $mnt || return 1\n\t\tfi\n\t\t#disable FILESET if not supported\n\t\tdo_nodes $clients lctl get_param -n \\\n\t\t\tmdc.$FSNAME-MDT0000*.import | grep -q subtree ||\n\t\t\t\tdevice=$MGSNID:/$FSNAME\n\t\tdo_nodes $clients mkdir -p $mnt/$FILESET\n\t\tdo_nodes $clients \"! grep -q $mnt' ' /proc/mounts ||\n\t\t\tumount $mnt\"\n\tfi\n\n\tif $GSS_SK && ($SK_UNIQUE_NM || $SK_S2S); then\n\t\t# Mount with nodemap key\n\t\tlocal i=0\n\t\tlocal mountkey=$SK_PATH/$FSNAME-nmclient.key\n\t\tfor nmclient in ${clients//,/ }; do\n\t\t\tif $SK_UNIQUE_NM; then\n\t\t\t\tmountkey=$SK_PATH/nodemap/c$i.key\n\t\t\tfi\n\t\t\tlocal prunedopts=$(echo $opts | sed -e \\\n\t\t\t\t\"s#skpath=[^ ^,]*#skpath=$mountkey#g\");\n\t\t\tdo_node $nmclient \"! grep -q $mnt' ' /proc/mounts ||\n\t\t\t\tumount $mnt\"\n\t\t\tdo_node $nmclient \"\n\t\trunning=\\\\\\$(mount | grep -c $mnt' ');\n\t\trc=0;\n\t\tif [ \\\\\\$running -eq 0 ] ; then\n\t\t\tmkdir -p $mnt;\n\t\t\t$MOUNT_CMD $flags $prunedopts $device $mnt;\n\t\t\trc=\\\\\\$?;\n\t\telse\n\t\t\tlustre_mnt_count=\\\\\\$(mount | grep $mnt' ' | \\\n\t\t\t\tgrep 'type lustre' | wc -l);\n\t\t\tif [ \\\\\\$running -ne \\\\\\$lustre_mnt_count ] ; then\n\t\t\t\techo zconf_mount_clients FAILED: \\\n\t\t\t\t\tmount count \\\\\\$running, not matching \\\n\t\t\t\t\twith mount count of 'type lustre' \\\n\t\t\t\t\t\\\\\\$lustre_mnt_count;\n\t\t\t\trc=1;\n\t\t\tfi;\n\t\tfi;\n\texit \\\\\\$rc\" || return ${PIPESTATUS[0]}\n\n\t\t\ti=$((i + 1))\n\t\tdone\n\telse\n\n\t\tlocal tmpopts=$opts\n\t\tif $SHARED_KEY; then\n\t\t\ttmpopts=$(add_sk_mntflag $opts)\n\t\tfi\n\t\tdo_nodes $clients \"\nrunning=\\\\\\$(mount | grep -c $mnt' ');\nrc=0;\nif [ \\\\\\$running -eq 0 ] ; then\n\tmkdir -p $mnt;\n\t$MOUNT_CMD $flags $tmpopts $device $mnt;\n\trc=\\\\\\$?;\nfi;\nexit \\\\\\$rc\" || return ${PIPESTATUS[0]}\n\tfi\n\n\techo \"Started clients $clients: \"\n\tdo_nodes $clients \"mount | grep $mnt' '\"\n\n\tset_default_debug_nodes $clients\n\n\treturn 0\n}\n\nzconf_umount_clients() {\n    local clients=$1\n    local mnt=$2\n    local force\n\n    [ \"$3\" ] && force=-f\n\n    echo \"Stopping clients: $clients $mnt (opts:$force)\"\n    do_nodes $clients \"running=\\\\\\$(grep -c $mnt' ' /proc/mounts);\nif [ \\\\\\$running -ne 0 ] ; then\necho Stopping client \\\\\\$(hostname) $mnt opts:$force;\nlsof $mnt || need_kill=no;\nif [ \"x$force\" != \"x\" -a \"x\\\\\\$need_kill\" != \"xno\" ]; then\n    pids=\\\\\\$(lsof -t $mnt | sort -u);\n    if [ -n \\\\\\\"\\\\\\$pids\\\\\\\" ]; then\n             kill -9 \\\\\\$pids;\n    fi\nfi;\nwhile umount $force $mnt 2>&1 | grep -q \"busy\"; do\n    echo \"$mnt is still busy, wait one second\" && sleep 1;\ndone;\nfi\"\n}\n\nshutdown_node () {\n    local node=$1\n    echo + $POWER_DOWN $node\n    $POWER_DOWN $node\n}\n\nshutdown_node_hard () {\n    local host=$1\n    local attempts=$SHUTDOWN_ATTEMPTS\n\n    for i in $(seq $attempts) ; do\n        shutdown_node $host\n        sleep 1\n        wait_for_function --quiet \"! ping -w 3 -c 1 $host\" 5 1 && return 0\n        echo \"waiting for $host to fail attempts=$attempts\"\n        [ $i -lt $attempts ] || \\\n            { echo \"$host still pingable after power down! attempts=$attempts\" && return 1; }\n    done\n}\n\nshutdown_client() {\n    local client=$1\n    local mnt=${2:-$MOUNT}\n    local attempts=3\n\n    if [ \"$FAILURE_MODE\" = HARD ]; then\n        shutdown_node_hard $client\n    else\n       zconf_umount_clients $client $mnt -f\n    fi\n}\n\nfacets_on_host () {\n    local host=$1\n    local facets=\"$(get_facets OST),$(get_facets MDS)\"\n    local affected\n\n    combined_mgs_mds || facets=\"$facets,mgs\"\n\n    for facet in ${facets//,/ }; do\n        if [ $(facet_active_host $facet) == $host ]; then\n           affected=\"$affected $facet\"\n        fi\n    done\n\n    echo $(comma_list $affected)\n}\n\nfacet_up() {\n\tlocal facet=$1\n\tlocal host=${2:-$(facet_host $facet)}\n\n\tlocal label=$(convert_facet2label $facet)\n\tdo_node $host $LCTL dl | awk '{ print $4 }' | grep -q \"^$label\\$\"\n}\n\nfacets_up_on_host () {\n    local host=$1\n    local facets=$(facets_on_host $host)\n    local affected_up\n\n    for facet in ${facets//,/ }; do\n        if $(facet_up $facet $host); then\n            affected_up=\"$affected_up $facet\"\n        fi\n    done\n\n    echo $(comma_list $affected_up)\n}\n\nshutdown_facet() {\n\tlocal facet=$1\n\tlocal affected_facet\n\tlocal affected_facets\n\n\tif [[ \"$FAILURE_MODE\" = HARD ]]; then\n\t\tif [[ $(facet_fstype $facet) = ldiskfs ]] &&\n\t\t\tdm_flakey_supported $facet; then\n\t\t\taffected_facets=$(affected_facets $facet)\n\t\t\tfor affected_facet in ${affected_facets//,/ }; do\n\t\t\t\tunexport_dm_dev $affected_facet\n\t\t\tdone\n\t\tfi\n\n\t\tshutdown_node_hard $(facet_active_host $facet)\n\telse\n\t\tstop $facet\n\tfi\n}\n\nreboot_node() {\n    local node=$1\n    echo + $POWER_UP $node\n    $POWER_UP $node\n}\n\nremount_facet() {\n    local facet=$1\n\n    stop $facet\n    mount_facet $facet\n}\n\nreboot_facet() {\n\tlocal facet=$1\n\tif [ \"$FAILURE_MODE\" = HARD ]; then\n\t\treboot_node $(facet_active_host $facet)\n\telse\n\t\tsleep 10\n\tfi\n}\n\nboot_node() {\n    local node=$1\n    if [ \"$FAILURE_MODE\" = HARD ]; then\n       reboot_node $node\n       wait_for_host $node\n    fi\n}\n\nfacets_hosts () {\n    local facets=$1\n    local hosts\n\n    for facet in ${facets//,/ }; do\n        hosts=$(expand_list $hosts $(facet_host $facet) )\n    done\n\n    echo $hosts\n}\n\n_check_progs_installed () {\n    local progs=$@\n    local rc=0\n\n    for prog in $progs; do\n        if ! [ \"$(which $prog)\"  -o  \"${!prog}\" ]; then\n           echo $prog missing on $(hostname)\n           rc=1\n        fi\n    done\n    return $rc\n}\n\ncheck_progs_installed () {\n\tlocal nodes=$1\n\tshift\n\n\tdo_rpc_nodes \"$nodes\" _check_progs_installed $@\n}\n\n# recovery-scale functions\nnode_var_name() {\n    echo __$(echo $1 | tr '-' '_' | tr '.' '_')\n}\n\nstart_client_load() {\n\tlocal client=$1\n\tlocal load=$2\n\tlocal var=$(node_var_name $client)_load\n\teval export ${var}=$load\n\n\tdo_node $client \"PATH=$PATH MOUNT=$MOUNT ERRORS_OK=$ERRORS_OK \\\n\t\t\tBREAK_ON_ERROR=$BREAK_ON_ERROR \\\n\t\t\tEND_RUN_FILE=$END_RUN_FILE \\\n\t\t\tLOAD_PID_FILE=$LOAD_PID_FILE \\\n\t\t\tTESTLOG_PREFIX=$TESTLOG_PREFIX \\\n\t\t\tTESTNAME=$TESTNAME \\\n\t\t\tDBENCH_LIB=$DBENCH_LIB \\\n\t\t\tDBENCH_SRC=$DBENCH_SRC \\\n\t\t\tCLIENT_COUNT=$((CLIENTCOUNT - 1)) \\\n\t\t\tLFS=$LFS \\\n\t\t\tLCTL=$LCTL \\\n\t\t\tFSNAME=$FSNAME \\\n\t\t\tMPIRUN=$MPIRUN \\\n\t\t\tMPIRUN_OPTIONS=\\\\\\\"$MPIRUN_OPTIONS\\\\\\\" \\\n\t\t\tMACHINEFILE_OPTION=\\\\\\\"$MACHINEFILE_OPTION\\\\\\\" \\\n\t\t\tnum_clients=$(get_node_count ${CLIENTS//,/ }) \\\n\t\t\tior_THREADS=$ior_THREADS ior_iteration=$ior_iteration \\\n\t\t\tior_blockSize=$ior_blockSize \\\n\t\t\tior_blockUnit=$ior_blockUnit \\\n\t\t\tior_xferSize=$ior_xferSize ior_type=$ior_type \\\n\t\t\tior_DURATION=$ior_DURATION \\\n\t\t\tior_stripe_params=\\\\\\\"$ior_stripe_params\\\\\\\" \\\n\t\t\tior_custom_params=\\\\\\\"$ior_custom_param\\\\\\\" \\\n\t\t\tmpi_ior_custom_threads=$mpi_ior_custom_threads \\\n\t\t\trun_${load}.sh\" &\n\tlocal ppid=$!\n\tlog \"Started client load: ${load} on $client\"\n\n\t# get the children process IDs\n\tlocal pids=$(ps --ppid $ppid -o pid= | xargs)\n\tCLIENT_LOAD_PIDS=\"$CLIENT_LOAD_PIDS $ppid $pids\"\n\treturn 0\n}\n\nstart_client_loads () {\n\tlocal -a clients=(${1//,/ })\n\tlocal numloads=${#CLIENT_LOADS[@]}\n\n\tfor ((nodenum=0; nodenum < ${#clients[@]}; nodenum++ )); do\n\t\tlocal load=$((nodenum % numloads))\n\t\tstart_client_load ${clients[nodenum]} ${CLIENT_LOADS[load]}\n\tdone\n\t# bug 22169: wait the background threads to start\n\tsleep 2\n}\n\n# only for remote client\ncheck_client_load () {\n\tlocal client=$1\n\tlocal var=$(node_var_name $client)_load\n\tlocal testload=run_${!var}.sh\n\n\tps auxww | grep -v grep | grep $client | grep -q $testload || return 1\n\n\t# bug 18914: try to connect several times not only when\n\t# check ps, but  while check_node_health also\n\n\tlocal tries=3\n\tlocal RC=254\n\twhile [ $RC = 254 -a $tries -gt 0 ]; do\n\t\tlet tries=$tries-1\n\t\t# assume success\n\t\tRC=0\n\t\tif ! check_node_health $client; then\n\t\t\tRC=${PIPESTATUS[0]}\n\t\t\tif [ $RC -eq 254 ]; then\n\t\t\t\t# FIXME: not sure how long we shuold sleep here\n\t\t\t\tsleep 10\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\techo \"check node health failed: RC=$RC \"\n\t\t\treturn $RC\n\t\tfi\n\tdone\n\t# We can continue try to connect if RC=254\n\t# Just print the warning about this\n\tif [ $RC = 254 ]; then\n\t\techo \"got a return status of $RC from do_node while checking \" \\\n\t\t\"node health on $client\"\n\tfi\n\n\t# see if the load is still on the client\n\ttries=3\n\tRC=254\n\twhile [ $RC = 254 -a $tries -gt 0 ]; do\n\t\tlet tries=$tries-1\n\t\t# assume success\n\t\tRC=0\n\t\tif ! do_node $client \\\n\t\t\t\"ps auxwww | grep -v grep | grep -q $testload\"; then\n\t\t\tRC=${PIPESTATUS[0]}\n\t\t\tsleep 30\n\t\tfi\n\tdone\n\tif [ $RC = 254 ]; then\n\t\techo \"got a return status of $RC from do_node while checking \" \\\n\t\t\"(node health and 'ps') the client load on $client\"\n\t\t# see if we can diagnose a bit why this is\n\tfi\n\n\treturn $RC\n}\ncheck_client_loads () {\n   local clients=${1//,/ }\n   local client=\n   local rc=0\n\n   for client in $clients; do\n      check_client_load $client\n      rc=${PIPESTATUS[0]}\n      if [ \"$rc\" != 0 ]; then\n        log \"Client load failed on node $client, rc=$rc\"\n        return $rc\n      fi\n   done\n}\n\nrestart_client_loads () {\n    local clients=${1//,/ }\n    local expectedfail=${2:-\"\"}\n    local client=\n    local rc=0\n\n    for client in $clients; do\n        check_client_load $client\n        rc=${PIPESTATUS[0]}\n        if [ \"$rc\" != 0 -a \"$expectedfail\" ]; then\n            local var=$(node_var_name $client)_load\n            start_client_load $client ${!var}\n            echo \"Restarted client load ${!var}: on $client. Checking ...\"\n            check_client_load $client\n            rc=${PIPESTATUS[0]}\n            if [ \"$rc\" != 0 ]; then\n                log \"Client load failed to restart on node $client, rc=$rc\"\n                # failure one client load means test fail\n                # we do not need to check other\n                return $rc\n            fi\n        else\n            return $rc\n        fi\n    done\n}\n\n# Start vmstat and save its process ID in a file.\nstart_vmstat() {\n    local nodes=$1\n    local pid_file=$2\n\n    [ -z \"$nodes\" -o -z \"$pid_file\" ] && return 0\n\n    do_nodes $nodes \\\n        \"vmstat 1 > $TESTLOG_PREFIX.$TESTNAME.vmstat.\\\\\\$(hostname -s).log \\\n        2>/dev/null </dev/null & echo \\\\\\$! > $pid_file\"\n}\n\n# Display the nodes on which client loads failed.\nprint_end_run_file() {\n    local file=$1\n    local node\n\n    [ -s $file ] || return 0\n\n    echo \"Found the END_RUN_FILE file: $file\"\n    cat $file\n\n    # A client load will stop if it finds the END_RUN_FILE file.\n    # That does not mean the client load actually failed though.\n    # The first node in END_RUN_FILE is the one we are interested in.\n    read node < $file\n\n    if [ -n \"$node\" ]; then\n        local var=$(node_var_name $node)_load\n\n        local prefix=$TESTLOG_PREFIX\n        [ -n \"$TESTNAME\" ] && prefix=$prefix.$TESTNAME\n        local stdout_log=$prefix.run_${!var}_stdout.$node.log\n        local debug_log=$(echo $stdout_log | sed 's/\\(.*\\)stdout/\\1debug/')\n\n        echo \"Client load ${!var} failed on node $node:\"\n        echo \"$stdout_log\"\n        echo \"$debug_log\"\n    fi\n}\n\n# Stop the process which had its PID saved in a file.\nstop_process() {\n    local nodes=$1\n    local pid_file=$2\n\n    [ -z \"$nodes\" -o -z \"$pid_file\" ] && return 0\n\n    do_nodes $nodes \"test -f $pid_file &&\n        { kill -s TERM \\\\\\$(cat $pid_file); rm -f $pid_file; }\" || true\n}\n\n# Stop all client loads.\nstop_client_loads() {\n    local nodes=${1:-$CLIENTS}\n    local pid_file=$2\n\n    # stop the client loads\n    stop_process $nodes $pid_file\n\n    # clean up the processes that started them\n    [ -n \"$CLIENT_LOAD_PIDS\" ] && kill -9 $CLIENT_LOAD_PIDS 2>/dev/null || true\n}\n# End recovery-scale functions\n\n# verify that lustre actually cleaned up properly\ncleanup_check() {\n\tVAR=$(lctl get_param -n catastrophe 2>&1)\n\tif [ $? = 0 ] ; then\n\t\tif [ $VAR != 0 ]; then\n\t\t\terror \"LBUG/LASSERT detected\"\n\t\tfi\n\tfi\n\tBUSY=$(dmesg | grep -i destruct || true)\n\tif [ -n \"$BUSY\" ]; then\n\t\techo \"$BUSY\" 1>&2\n\t\t[ -e $TMP/debug ] && mv $TMP/debug $TMP/debug-busy.$(date +%s)\n\t\texit 205\n\tfi\n\n\tcheck_mem_leak || exit 204\n\n\t[[ $($LCTL dl 2>/dev/null | wc -l) -gt 0 ]] && $LCTL dl &&\n\t\techo \"$TESTSUITE: lustre didn't clean up...\" 1>&2 &&\n\t\treturn 202 || true\n\n\tif module_loaded lnet || module_loaded libcfs; then\n\t\techo \"$TESTSUITE: modules still loaded...\" 1>&2\n\t\t/sbin/lsmod 1>&2\n\t\treturn 203\n\tfi\n\treturn 0\n}\n\n##\n# wait for a command to return the expected result\n#\n# This will run @check on @node repeatedly until the output matches @expect\n# based on the supplied condition, or until @max_wait seconds have elapsed,\n# whichever comes first.  @cond may be one of the normal bash operators,\n# \"-gt\", \"-ge\", \"-eq\", \"-le\", \"-lt\", \"==\", \"!=\", or \"=~\", and must be quoted\n# in the caller to avoid unintentional evaluation by the shell in the caller.\n#\n# If @max_wait is not specified, the condition will be checked for up to 90s.\n#\n# If --verbose is passed as the first argument, the result is printed on each\n# value change, otherwise it is only printed after every 10s interval.\n#\n# Using wait_update_cond() or related helper function is preferable to adding\n# a \"long enough\" wait for some state to change in the background, since\n# \"long enough\" may be too short due to tunables, system config, or running in\n# a VM, and must by necessity wait too long for most cases or risk failure.\n#\n# usage: wait_update_cond [--verbose] node check cond expect [max_wait]\nwait_update_cond() {\n\tlocal verbose=false\n\t[[ \"$1\" == \"--verbose\" ]] && verbose=true && shift\n\n\tlocal node=$1\n\tlocal check=\"$2\"\n\tlocal cond=\"$3\"\n\tlocal expect=\"$4\"\n\tlocal max_wait=${5:-90}\n\tlocal result\n\tlocal prev_result\n\tlocal waited=0\n\tlocal begin=$SECONDS\n\tlocal sleep=1\n\tlocal print=10\n\n\twhile (( $waited <= $max_wait )); do\n\t\tresult=$(do_node $node \"$check\")\n\n\t\teval [[ \"'$result'\" $cond \"'$expect'\" ]]\n\t\tif [[ $? == 0 ]]; then\n\t\t\t[[ -z \"$result\" || $waited -le $sleep ]] ||\n\t\t\t\techo \"Updated after ${waited}s: want '$expect' got '$result'\"\n\t\t\treturn 0\n\t\tfi\n\t\tif $verbose && [[ \"$result\" != \"$prev_result\" ]]; then\n\t\t\t[[ -n \"$prev_result\" ]] &&\n\t\t\t\techo \"Changed after ${waited}s: from '$prev_result' to '$result'\"\n\t\t\tprev_result=\"$result\"\n\t\tfi\n\t\t(( $waited % $print == 0 )) &&\n\t\t\techo \"Waiting $((max_wait - waited))s for '$expect'\"\n\t\tsleep $sleep\n\t\twaited=$((SECONDS - begin))\n\tdone\n\techo \"Update not seen after ${max_wait}s: want '$expect' got '$result'\"\n\treturn 3\n}\n\n# usage: wait_update [--verbose] node check expect [max_wait]\nwait_update() {\n\tlocal verbose=\n\t[ \"$1\" = \"--verbose\" ] && verbose=\"$1\" && shift\n\n\tlocal node=\"$1\"\n\tlocal check=\"$2\"\n\tlocal expect=\"$3\"\n\tlocal max_wait=$4\n\n\twait_update_cond $verbose $node \"$check\" \"==\" \"$expect\" $max_wait\n}\n\n# usage: wait_update_facet_cond [--verbose] facet check cond expect [max_wait]\nwait_update_facet_cond() {\n\tlocal verbose=\n\t[ \"$1\" = \"--verbose\" ] && verbose=\"$1\" && shift\n\n\tlocal node=$(facet_active_host $1)\n\tlocal check=\"$2\"\n\tlocal cond=\"$3\"\n\tlocal expect=\"$4\"\n\tlocal max_wait=$5\n\n\twait_update_cond $verbose $node \"$check\" \"$cond\" \"$expect\" $max_wait\n}\n\n# usage: wait_update_facet [--verbose] facet check expect [max_wait]\nwait_update_facet() {\n\tlocal verbose=\n\t[ \"$1\" = \"--verbose\" ] && verbose=\"$1\" && shift\n\n\tlocal node=$(facet_active_host $1)\n\tlocal check=\"$2\"\n\tlocal expect=\"$3\"\n\tlocal max_wait=$4\n\n\twait_update_cond $verbose $node \"$check\" \"==\" \"$expect\" $max_wait\n}\n\nsync_all_data() {\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t    \"lctl set_param -n os[cd]*.*MDT*.force_sync=1\"\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t    \"lctl set_param -n osd*.*OS*.force_sync=1\" 2>&1 |\n\t\tgrep -v 'Found no match'\n}\n\nwait_zfs_commit() {\n\tlocal zfs_wait=${2:-5}\n\n\t# the occupied disk space will be released\n\t# only after TXGs are committed\n\tif [[ $(facet_fstype $1) == zfs ]]; then\n\t\techo \"sleep $zfs_wait for ZFS $(facet_fstype $1)\"\n\t\tsleep $zfs_wait\n\tfi\n}\n\nfill_ost() {\n\tlocal filename=$1\n\tlocal ost_idx=$2\n\tlocal lwm=$3  #low watermark\n\tlocal size_mb #how many MB should we write to pass watermark\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\n\tfree_kb=$($LFS df $MOUNT | awk \"/$ost_name/ { print \\$4 }\")\n\tsize_mb=0\n\tif (( $free_kb / 1024 > lwm )); then\n\t\tsize_mb=$((free_kb / 1024 - lwm))\n\tfi\n\t#If 10% of free space cross low watermark use it\n\tif (( $free_kb / 10240 > size_mb )); then\n\t\tsize_mb=$((free_kb / 10240))\n\telse\n\t\t#At least we need to store 1.1 of difference between\n\t\t#free space and low watermark\n\t\tsize_mb=$((size_mb + size_mb / 10))\n\tfi\n\tif (( lwm <= $free_kb / 1024 )) ||\n\t   [ ! -f $DIR/${filename}.fill_ost$ost_idx ]; then\n\t\t$LFS setstripe -i $ost_idx -c1 $DIR/${filename}.fill_ost$ost_idx\n\t\tdd if=/dev/zero of=$DIR/${filename}.fill_ost$ost_idx bs=1M \\\n\t\t\tcount=$size_mb oflag=append conv=notrunc\n\tfi\n\n\tsleep_maxage\n\n\tfree_kb=$($LFS df $MOUNT | awk \"/$ost_name/ { print \\$4 }\")\n\techo \"OST still has $((free_kb / 1024)) MB free\"\n}\n\n# This checks only the primary MDS\nost_watermarks_get() {\n\tlocal ost_idx=$1\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\tlocal mdtosc_proc=$(get_mdtosc_proc_path $SINGLEMDS $ost_name)\n\n\tlocal hwm=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\tosp.$mdtosc_proc.reserved_mb_high)\n\tlocal lwm=$(do_facet $SINGLEMDS $LCTL get_param -n \\\n\t\t\tosp.$mdtosc_proc.reserved_mb_low)\n\n\techo \"$lwm $hwm\"\n}\n\n# Note that we set watermarks on all MDSes (necessary for striped dirs)\nost_watermarks_set() {\n\tlocal ost_idx=$1\n\tlocal lwm=$2\n\tlocal hwm=$3\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\tlocal facets=$(get_facets MDS)\n\n\tdo_nodes $(comma_list $(mdts_nodes)) $LCTL set_param -n \\\n\t\tosp.*$ost_name*.reserved_mb_low=$lwm \\\n\t\tosp.*$ost_name*.reserved_mb_high=$hwm > /dev/null\n\n\t# sleep to ensure we see the change\n\tsleep_maxage\n}\n\nost_watermarks_set_low_space() {\n\tlocal ost_idx=$1\n\tlocal wms=$(ost_watermarks_get $ost_idx)\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\n\tlocal old_lwm=$(echo $wms | awk '{ print $1 }')\n\tlocal old_hwm=$(echo $wms | awk '{ print $2 }')\n\n\tlocal blocks=$($LFS df $MOUNT | awk \"/$ost_name/ { print \\$4 }\")\n\t# minimal extension size is 64M\n\tlocal new_lwm=50\n\tif (( $blocks / 1024 > 50 )); then\n\t\tnew_lwm=$((blocks / 1024 - 50))\n\tfi\n\tlocal new_hwm=$((new_lwm + 5))\n\n\tost_watermarks_set $ost_idx $new_lwm $new_hwm\n\techo \"watermarks: $old_lwm $old_hwm $new_lwm $new_hwm\"\n}\n\n# Set watermarks to ~current available space & then write data to fill it\n# Note OST is not *actually* full after this, it just reports ENOSPC in the\n# internal statfs used by the stripe allocator\n#\n# first parameter is the filename-prefix, which must get under t-f cleanup\n# requirements (rm -rf $DIR/[Rdfs][0-9]*), i.e. $tfile work fine\nost_watermarks_set_enospc() {\n\tlocal filename=$1\n\tlocal ost_idx=$2\n\t# on the mdt's osc\n\tlocal ost_name=$(ostname_from_index $ost_idx)\n\tlocal facets=$(get_facets MDS)\n\tlocal wms\n\tlocal MDS\n\n\tfor MDS in ${facets//,/ }; do\n\t\tlocal mdtosc_proc=$(get_mdtosc_proc_path $MDS $ost_name)\n\n\t\tdo_facet $MDS $LCTL get_param -n \\\n\t\t\tosp.$mdtosc_proc.reserved_mb_high ||\n\t\t\tskip  \"remote MDS does not support reserved_mb_high\"\n\tdone\n\n\twms=$(ost_watermarks_set_low_space $ost_idx)\n\tlocal new_lwm=$(echo $wms | awk '{ print $4 }')\n\tfill_ost $filename $ost_idx $new_lwm\n\t#First enospc could execute orphan deletion so repeat\n\tfill_ost $filename $ost_idx $new_lwm\n\techo $wms\n}\n\nost_watermarks_enospc_delete_files() {\n\tlocal filename=$1\n\tlocal ost_idx=$2\n\n\trm -f $DIR/${filename}.fill_ost$ost_idx\n\n\twait_delete_completed\n\twait_mds_ost_sync\n}\n\n# clean up from \"ost_watermarks_set_enospc\"\nost_watermarks_clear_enospc() {\n\tlocal filename=$1\n\tlocal ost_idx=$2\n\tlocal old_lwm=$4\n\tlocal old_hwm=$5\n\n\tost_watermarks_enospc_delete_files $filename $ost_idx\n\tost_watermarks_set $ost_idx $old_lwm $old_hwm\n\techo \"set OST$ost_idx lwm back to $old_lwm, hwm back to $old_hwm\"\n}\n\nwait_delete_completed_mds() {\n\tlocal max_wait=${1:-20}\n\tlocal mds2sync=\"\"\n\tlocal stime=$(date +%s)\n\tlocal etime\n\tlocal node\n\tlocal changes\n\n\t# find MDS with pending deletions\n\tfor node in $(mdts_nodes); do\n\t\tchanges=$(do_node $node \"$LCTL get_param -n osc.*MDT*.sync_*\" \\\n\t\t\t2>/dev/null | calc_sum)\n\t\tif [[ $changes -eq 0 ]]; then\n\t\t\tcontinue\n\t\tfi\n\t\tmds2sync=\"$mds2sync $node\"\n\tdone\n\tif [ -z \"$mds2sync\" ]; then\n\t\twait_zfs_commit $SINGLEMDS\n\t\treturn 0\n\tfi\n\tmds2sync=$(comma_list $mds2sync)\n\n\t# sync MDS transactions\n\tdo_nodes $mds2sync \"$LCTL set_param -n os[cd]*.*MD*.force_sync 1\"\n\n\t# wait till all changes are sent and commmitted by OSTs\n\t# for ldiskfs space is released upon execution, but DMU\n\t# do this upon commit\n\n\tlocal WAIT=0\n\twhile [[ $WAIT -ne $max_wait ]]; do\n\t\tchanges=$(do_nodes $mds2sync \\\n\t\t\t\"$LCTL get_param -n osc.*MDT*.sync_*\" | calc_sum)\n\t\t#echo \"$node: $changes changes on all\"\n\t\tif [[ $changes -eq 0 ]]; then\n\t\t\twait_zfs_commit $SINGLEMDS\n\n\t\t\t# the occupied disk space will be released\n\t\t\t# only after TXGs are committed\n\t\t\twait_zfs_commit ost1\n\t\t\treturn 0\n\t\tfi\n\t\tsleep 1\n\t\tWAIT=$((WAIT + 1))\n\tdone\n\n\tetime=$(date +%s)\n\techo \"Delete is not completed in $((etime - stime)) seconds\"\n\tdo_nodes $mds2sync \"$LCTL get_param osc.*MDT*.sync_*\"\n\treturn 1\n}\n\nwait_for_host() {\n\tlocal hostlist=$1\n\n\t# we can use \"for\" here because we are waiting the slowest\n\tfor host in ${hostlist//,/ }; do\n\t\tcheck_network \"$host\" 900\n\tdone\n\twhile ! do_nodes $hostlist hostname  > /dev/null; do sleep 5; done\n}\n\nwait_for_facet() {\n    local facetlist=$1\n    local hostlist\n\n    for facet in ${facetlist//,/ }; do\n        hostlist=$(expand_list $hostlist $(facet_active_host $facet))\n    done\n    wait_for_host $hostlist\n}\n\n_wait_recovery_complete () {\n    local param=$1\n\n    # Use default policy if $2 is not passed by caller.\n    local MAX=${2:-$(max_recovery_time)}\n\n    local WAIT=0\n    local STATUS=\n\n    while [ $WAIT -lt $MAX ]; do\n        STATUS=$(lctl get_param -n $param | grep status)\n        echo $param $STATUS\n        [[ $STATUS = \"status: COMPLETE\" || $STATUS = \"status: INACTIVE\" ]] && return 0\n        sleep 5\n        WAIT=$((WAIT + 5))\n        echo \"Waiting $((MAX - WAIT)) secs for $param recovery done. $STATUS\"\n    done\n    echo \"$param recovery not done in $MAX sec. $STATUS\"\n    return 1\n}\n\nwait_recovery_complete () {\n    local facet=$1\n\n    # with an assumption that at_max is the same on all nodes\n    local MAX=${2:-$(max_recovery_time)}\n\n    local facets=$facet\n    if [ \"$FAILURE_MODE\" = HARD ]; then\n        facets=$(facets_on_host $(facet_active_host $facet))\n    fi\n    echo affected facets: $facets\n\n\t# we can use \"for\" here because we are waiting the slowest\n\tfor facet in ${facets//,/ }; do\n\t\tlocal var_svc=${facet}_svc\n\t\tlocal param=\"*.${!var_svc}.recovery_status\"\n\n\t\tlocal host=$(facet_active_host $facet)\n\t\tdo_rpc_nodes \"$host\" _wait_recovery_complete $param $MAX\n\tdone\n}\n\nwait_mds_ost_sync () {\n\t# just because recovery is done doesn't mean we've finished\n\t# orphan cleanup. Wait for llogs to get synchronized.\n\techo \"Waiting for orphan cleanup...\"\n\t# MAX value includes time needed for MDS-OST reconnection\n\tlocal MAX=$(( TIMEOUT * 2 ))\n\tlocal WAIT_TIMEOUT=${1:-$MAX}\n\tlocal WAIT=0\n\tlocal new_wait=true\n\tlocal list=$(comma_list $(mdts_nodes))\n\tlocal cmd=\"$LCTL get_param -n osp.*osc*.old_sync_processed\"\n\tif ! do_facet $SINGLEMDS \\\n\t\t\"$LCTL list_param osp.*osc*.old_sync_processed 2> /dev/null\"\n\tthen\n\t\t# old way, use mds_sync\n\t\tnew_wait=false\n\t\tlist=$(comma_list $(osts_nodes))\n\t\tcmd=\"$LCTL get_param -n obdfilter.*.mds_sync\"\n\tfi\n\n\techo \"wait $WAIT_TIMEOUT secs maximumly for $list mds-ost sync done.\"\n\twhile [ $WAIT -lt $WAIT_TIMEOUT ]; do\n\t\tlocal -a sync=($(do_nodes $list \"$cmd\"))\n\t\tlocal con=1\n\t\tlocal i\n\t\tfor ((i=0; i<${#sync[@]}; i++)); do\n\t\t\tif $new_wait; then\n\t\t\t\t[ ${sync[$i]} -eq 1 ] && continue\n\t\t\telse\n\t\t\t\t[ ${sync[$i]} -eq 0 ] && continue\n\t\t\tfi\n\t\t\t# there is a not finished MDS-OST synchronization\n\t\t\tcon=0\n\t\t\tbreak;\n\t\tdone\n\t\tsleep 2 # increase waiting time and cover statfs cache\n\t\t[ ${con} -eq 1 ] && return 0\n\t\techo \"Waiting $WAIT secs for $list $i mds-ost sync done.\"\n\t\tWAIT=$((WAIT + 2))\n\tdone\n\n\t# show which nodes are not finished.\n\tcmd=$(echo $cmd | sed 's/-n//')\n\tdo_nodes $list \"$cmd\"\n\techo \"$facet recovery node $i not done in $WAIT_TIMEOUT sec. $STATUS\"\n\treturn 1\n}\n\n# Wait OSTs to be active on both client and MDT side.\nwait_osts_up() {\n\tlocal cmd=\"$LCTL get_param -n lov.$FSNAME-clilov-*.target_obd |\n\t\tawk 'BEGIN {c = 0} /ACTIVE/{c += 1} END {printf \\\\\\\"%d\\\\\\\", c}'\"\n\twait_update $HOSTNAME \"eval $cmd\" $OSTCOUNT ||\n\t\terror \"wait_update OSTs up on client failed\"\n\n\tcmd=\"$LCTL get_param osp.$FSNAME-OST*-MDT0000.prealloc_last_id |\n\t     awk '/=[1-9][0-9]/ { c += 1 } END { printf \\\\\\\"%d\\\\\\\", c }'\"\n\twait_update_facet $SINGLEMDS \"eval $cmd\" $OSTCOUNT ||\n\t\terror \"wait_update OSTs up on MDT0000 failed\"\n}\n\nwait_destroy_complete () {\n\techo \"Waiting for local destroys to complete\"\n\t# MAX value shouldn't be big as this mean server responsiveness\n\t# never increase this just to make test pass but investigate\n\t# why it takes so long time\n\tlocal MAX=5\n\tlocal WAIT=0\n\twhile [ $WAIT -lt $MAX ]; do\n\t\tlocal -a RPCs=($($LCTL get_param -n osc.*.destroys_in_flight))\n\t\tlocal con=1\n\t\tlocal i\n\n\t\tfor ((i=0; i<${#RPCs[@]}; i++)); do\n\t\t\t[ ${RPCs[$i]} -eq 0 ] && continue\n\t\t\t# there are still some destroy RPCs in flight\n\t\t\tcon=0\n\t\t\tbreak;\n\t\tdone\n\t\tsleep 1\n\t\t[ ${con} -eq 1 ] && return 0 # done waiting\n\t\techo \"Waiting ${WAIT}s for local destroys to complete\"\n\t\tWAIT=$((WAIT + 1))\n\tdone\n\techo \"Local destroys weren't done in $MAX sec.\"\n\treturn 1\n}\n\nwait_delete_completed() {\n\twait_delete_completed_mds $1 || return $?\n\twait_destroy_complete || return $?\n}\n\nwait_exit_ST () {\n    local facet=$1\n\n    local WAIT=0\n    local INTERVAL=1\n    local running\n    # conf-sanity 31 takes a long time cleanup\n    while [ $WAIT -lt 300 ]; do\n\trunning=$(do_facet ${facet} \"lsmod | grep lnet > /dev/null &&\nlctl dl | grep ' ST ' || true\")\n        [ -z \"${running}\" ] && return 0\n        echo \"waited $WAIT for${running}\"\n        [ $INTERVAL -lt 64 ] && INTERVAL=$((INTERVAL + INTERVAL))\n        sleep $INTERVAL\n        WAIT=$((WAIT + INTERVAL))\n    done\n    echo \"service didn't stop after $WAIT seconds.  Still running:\"\n    echo ${running}\n    return 1\n}\n\nwait_remote_prog () {\n   local prog=$1\n   local WAIT=0\n   local INTERVAL=5\n   local rc=0\n\n   [ \"$PDSH\" = \"no_dsh\" ] && return 0\n\n   while [ $WAIT -lt $2 ]; do\n        running=$(ps uax | grep \"$PDSH.*$prog.*$MOUNT\" | grep -v grep) || true\n        [ -z \"${running}\" ] && return 0 || true\n        echo \"waited $WAIT for: \"\n        echo \"$running\"\n        [ $INTERVAL -lt 60 ] && INTERVAL=$((INTERVAL + INTERVAL))\n        sleep $INTERVAL\n        WAIT=$((WAIT + INTERVAL))\n    done\n    local pids=$(ps  uax | grep \"$PDSH.*$prog.*$MOUNT\" | grep -v grep | awk '{print $2}')\n    [ -z \"$pids\" ] && return 0\n    echo \"$PDSH processes still exists after $WAIT seconds.  Still running: $pids\"\n    # FIXME: not portable\n    for pid in $pids; do\n        cat /proc/${pid}/status || true\n        cat /proc/${pid}/wchan || true\n        echo \"Killing $pid\"\n        kill -9 $pid || true\n        sleep 1\n        ps -P $pid && rc=1\n    done\n\n    return $rc\n}\n\nlfs_df_check() {\n\tlocal clients=${1:-$CLIENTS}\n\n\tif [ -z \"$clients\" ]; then\n\t\t$LFS df $MOUNT\n\telse\n\t\t$PDSH $clients \"$LFS df $MOUNT\" > /dev/null\n\tfi\n}\n\nclients_up() {\n\t# not every config has many clients\n\tsleep 1\n\tlfs_df_check\n}\n\nclient_up() {\n\t# usually checked on particular client or locally\n\tsleep 1\n\tlfs_df_check $1\n}\n\nclient_evicted() {\n    ! client_up $1\n}\n\nclient_reconnect_try() {\n\tlocal f=$MOUNT/recon\n\n\tuname -n >> $f\n\tif [ -z \"$CLIENTS\" ]; then\n\t\t$LFS df $MOUNT; uname -n >> $f\n\telse\n\t\tdo_nodes $CLIENTS \"$LFS df $MOUNT; uname -n >> $f\" > /dev/null\n\tfi\n\techo \"Connected clients: $(cat $f)\"\n\tls -l $f > /dev/null\n\trm $f\n}\n\nclient_reconnect() {\n\t# one client_reconnect_try call does not always do the job...\n\twhile true ; do\n\t\tclient_reconnect_try && break\n\t\tsleep 1\n\tdone\n}\n\naffected_facets () {\n    local facet=$1\n\n    local host=$(facet_active_host $facet)\n    local affected=$facet\n\n    if [ \"$FAILURE_MODE\" = HARD ]; then\n        affected=$(facets_up_on_host $host)\n    fi\n    echo $affected\n}\n\nfacet_failover() {\n\tlocal E2FSCK_ON_MDT0=false\n\tif [ \"$1\" == \"--fsck\" ]; then\n\t\tshift\n\t\t[ $(facet_fstype $SINGLEMDS) == ldiskfs ] &&\n\t\t\tE2FSCK_ON_MDT0=true\n\tfi\n\n\tlocal facets=$1\n\tlocal sleep_time=$2\n\tlocal -a affecteds\n\tlocal facet\n\tlocal total=0\n\tlocal index=0\n\tlocal skip\n\n\t#Because it will only get up facets, we need get affected\n\t#facets before shutdown\n\t#For HARD Failure mode, it needs make sure facets on the same\n\t#HOST will only be shutdown and reboot once\n\tfor facet in ${facets//,/ }; do\n\t\tlocal affected_facet\n\t\tskip=0\n\t\t#check whether facet has been included in other affected facets\n\t\tfor ((index=0; index<$total; index++)); do\n\t\t\t[[ *,$facet,* == ,${affecteds[index]}, ]] && skip=1\n\t\tdone\n\n\t\tif [ $skip -eq 0 ]; then\n\t\t\taffecteds[$total]=$(affected_facets $facet)\n\t\t\ttotal=$((total+1))\n\t\tfi\n\tdone\n\n\tfor ((index=0; index<$total; index++)); do\n\t\tfacet=$(echo ${affecteds[index]} | tr -s \" \" | cut -d\",\" -f 1)\n\t\tlocal host=$(facet_active_host $facet)\n\t\techo \"Failing ${affecteds[index]} on $host\"\n\t\tshutdown_facet $facet\n\tdone\n\n\t$E2FSCK_ON_MDT0 && (run_e2fsck $(facet_active_host $SINGLEMDS) \\\n\t\t$(mdsdevname 1) \"-n\" || error \"Running e2fsck\")\n\n\tfor ((index=0; index<$total; index++)); do\n\t\tfacet=$(echo ${affecteds[index]} | tr -s \" \" | cut -d\",\" -f 1)\n\t\techo reboot facets: ${affecteds[index]}\n\n\t\treboot_facet $facet\n\n\t\tchange_active ${affecteds[index]}\n\n\t\twait_for_facet ${affecteds[index]}\n\t\tif $GSS_SK; then\n\t\t\tinit_gss\n\t\t\tinit_facets_vars_simple\n\t\tfi\n\t\t# start mgs first if it is affected\n\t\tif ! combined_mgs_mds &&\n\t\t\tlist_member ${affecteds[index]} mgs; then\n\t\t\tmount_facet mgs || error \"Restart of mgs failed\"\n\t\tfi\n\t\t# FIXME; has to be changed to mount all facets concurrently\n\t\taffected=$(exclude_items_from_list ${affecteds[index]} mgs)\n\t\techo mount facets: ${affecteds[index]}\n\t\tmount_facets ${affecteds[index]}\n\t\tif $GSS_SK; then\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t\t\t\"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\t\tfi\n\tdone\n}\n\nobd_name() {\n    local facet=$1\n}\n\nreplay_barrier() {\n\tlocal facet=$1\n\tdo_facet $facet \"sync; sync; sync\"\n\t$LFS df $MOUNT\n\n\t# make sure there will be no seq change\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal f=fsa-\\\\\\$\\(hostname\\)\n\tdo_nodes $clients \"mcreate $MOUNT/$f; rm $MOUNT/$f\"\n\tdo_nodes $clients \"if [ -d $MOUNT2 ]; then mcreate $MOUNT2/$f; rm $MOUNT2/$f; fi\"\n\n\tlocal svc=${facet}_svc\n\tdo_facet $facet $LCTL --device ${!svc} notransno\n\t#\n\t# If a ZFS OSD is made read-only here, its pool is \"freezed\". This\n\t# in-memory state has to be cleared by either rebooting the host or\n\t# exporting and reimporting the pool.\n\t#\n\t# Although the uberblocks are not updated when a pool is freezed,\n\t# transactions are still written to the disks. Modified blocks may be\n\t# cached in memory when tests try reading them back. The\n\t# export-and-reimport process also evicts any cached pool data from\n\t# memory to provide the correct \"data loss\" semantics.\n\t#\n\t# In the test framework, the exporting and importing operations are\n\t# handled by stop() and mount_facet() separately, which are used\n\t# inside fail() and fail_abort().\n\t#\n\tset_dev_readonly $facet\n\tdo_facet $facet $LCTL mark \"$facet REPLAY BARRIER on ${!svc}\"\n\t$LCTL mark \"local REPLAY BARRIER on ${!svc}\"\n}\n\nreplay_barrier_nodf() {\n\tlocal facet=$1    echo running=${running}\n\tdo_facet $facet \"sync; sync; sync\"\n\tlocal svc=${facet}_svc\n\techo Replay barrier on ${!svc}\n\tdo_facet $facet $LCTL --device ${!svc} notransno\n\tset_dev_readonly $facet\n\tdo_facet $facet $LCTL mark \"$facet REPLAY BARRIER on ${!svc}\"\n\t$LCTL mark \"local REPLAY BARRIER on ${!svc}\"\n}\n\nreplay_barrier_nosync() {\n\tlocal facet=$1    echo running=${running}\n\tlocal svc=${facet}_svc\n\techo Replay barrier on ${!svc}\n\tdo_facet $facet $LCTL --device ${!svc} notransno\n\tset_dev_readonly $facet\n\tdo_facet $facet $LCTL mark \"$facet REPLAY BARRIER on ${!svc}\"\n\t$LCTL mark \"local REPLAY BARRIER on ${!svc}\"\n}\n\n#\n# Get Lustre client uuid for a given Lustre mount point.\n#\nget_client_uuid() {\n\tlocal mntpnt=${1:-$MOUNT}\n\n\tlocal name=$($LFS getname $mntpnt | cut -d' ' -f1)\n\tlocal uuid=$($LCTL get_param -n llite.$name.uuid)\n\n\techo -n $uuid\n}\n\nmds_evict_client() {\n\tlocal mntpnt=${1:-$MOUNT}\n\tlocal uuid=$(get_client_uuid $mntpnt)\n\n\tdo_facet $SINGLEMDS \\\n\t\t\"$LCTL set_param -n mdt.${mds1_svc}.evict_client $uuid\"\n}\n\nost_evict_client() {\n\tlocal mntpnt=${1:-$MOUNT}\n\tlocal uuid=$(get_client_uuid $mntpnt)\n\n\tdo_facet ost1 \\\n\t\t\"$LCTL set_param -n obdfilter.${ost1_svc}.evict_client $uuid\"\n}\n\nfail() {\n\tlocal facets=$1\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\tSK_NO_KEY_save=$SK_NO_KEY\n\tif $GSS_SK; then\n\t\texport SK_NO_KEY=false\n\tfi\n\tfacet_failover $* || error \"failover: $?\"\n\texport SK_NO_KEY=$SK_NO_KEY_save\n\t# to initiate all OSC idling connections\n\tclients_up\n\twait_clients_import_state \"$clients\" \"$facets\" \"\\(FULL\\|IDLE\\)\"\n\tclients_up || error \"post-failover stat: $?\"\n}\n\nfail_nodf() {\n        local facet=$1\n        facet_failover $facet\n}\n\nfail_abort() {\n\tlocal facet=$1\n\tstop $facet\n\tchange_active $facet\n\twait_for_facet $facet\n\tmount_facet $facet -o abort_recovery\n\tclients_up || echo \"first stat failed: $?\"\n\tclients_up || error \"post-failover stat: $?\"\n}\n\nhost_nids_address() {\n\tlocal nodes=$1\n\tlocal net=${2:-\".\"}\n\n\tdo_nodes $nodes \"$LCTL list_nids | grep -w $net | cut -f 1 -d @\"\n}\n\nh2name_or_ip() {\n\tif [ \"$1\" = \"'*'\" ]; then echo \\'*\\'; else\n\t\techo $1\"@$2\"\n\tfi\n}\n\nh2nettype() {\n\tif [[ -n \"$NETTYPE\" ]]; then\n\t\th2name_or_ip \"$1\" \"$NETTYPE\"\n\telse\n\t\th2name_or_ip \"$1\" \"$2\"\n\tfi\n}\ndeclare -fx h2nettype\n\n# Wrapper function to print the deprecation warning\nh2tcp() {\n\techo \"h2tcp: deprecated, use h2nettype instead\" 1>&2\n\tif [[ -n \"$NETTYPE\" ]]; then\n\t\th2nettype \"$@\"\n\telse\n\t\th2nettype \"$1\" \"tcp\"\n\tfi\n}\n\n# Wrapper function to print the deprecation warning\nh2o2ib() {\n\techo \"h2o2ib: deprecated, use h2nettype instead\" 1>&2\n\tif [[ -n \"$NETTYPE\" ]]; then\n\t\th2nettype \"$@\"\n\telse\n\t\th2nettype \"$1\" \"o2ib\"\n\tfi\n}\n\n# This enables variables in cfg/\"setup\".sh files to support the pdsh HOSTLIST\n# expressions format. As a bonus we can then just pass in those variables\n# to pdsh. What this function does is take a HOSTLIST type string and\n# expand it into a space deliminated list for us.\nhostlist_expand() {\n    local hostlist=$1\n    local offset=$2\n    local myList\n    local item\n    local list\n\n    [ -z \"$hostlist\" ] && return\n\n    # Translate the case of [..],..,[..] to [..] .. [..]\n    list=\"${hostlist/],/] }\"\n    front=${list%%[*}\n    [[ \"$front\" == *,* ]] && {\n        new=\"${list%,*} \"\n        old=\"${list%,*},\"\n        list=${list/${old}/${new}}\n    }\n\n    for item in $list; do\n        # Test if we have any []'s at all\n        if [ \"$item\" != \"${item/\\[/}\" ]; then {\n            # Expand the [*] into list\n            name=${item%%[*}\n            back=${item#*]}\n\n            if [ \"$name\" != \"$item\" ]; then\n                group=${item#$name[*}\n                group=${group%%]*}\n\n                for range in ${group//,/ }; do\n\t\t    local order\n\n                    begin=${range%-*}\n                    end=${range#*-}\n\n                    # Number of leading zeros\n                    padlen=${#begin}\n                    padlen2=${#end}\n                    end=$(echo $end | sed 's/0*//')\n                    [[ -z \"$end\" ]] && end=0\n                    [[ $padlen2 -gt $padlen ]] && {\n                        [[ $padlen2 -eq ${#end} ]] && padlen2=0\n                        padlen=$padlen2\n                    }\n                    begin=$(echo $begin | sed 's/0*//')\n                    [ -z $begin ] && begin=0\n\n\t\t    if [ ! -z \"${begin##[!0-9]*}\" ]; then\n\t\t\torder=$(seq -f \"%0${padlen}g\" $begin $end)\n\t\t    else\n\t\t\torder=$(eval echo {$begin..$end});\n\t\t    fi\n\n\t\t    for num in $order; do\n                        value=\"${name#*,}${num}${back}\"\n                        [ \"$value\" != \"${value/\\[/}\" ] && {\n                            value=$(hostlist_expand \"$value\")\n                        }\n                        myList=\"$myList $value\"\n                    done\n                done\n            fi\n        } else {\n            myList=\"$myList $item\"\n        } fi\n    done\n    myList=${myList//,/ }\n    myList=${myList:1} # Remove first character which is a space\n\n    # Filter any duplicates without sorting\n    list=\"$myList \"\n    myList=\"${list%% *}\"\n\n    while [[ \"$list\" != ${myList##* } ]]; do\n\tlocal tlist=\" $list\"\n\tlist=${tlist// ${list%% *} / }\n\tlist=${list:1}\n\tmyList=\"$myList ${list%% *}\"\n    done\n    myList=\"${myList%* }\";\n\n    # We can select an object at an offset in the list\n    [ $# -eq 2 ] && {\n        cnt=0\n        for item in $myList; do\n            let cnt=cnt+1\n            [ $cnt -eq $offset ] && {\n                myList=$item\n            }\n        done\n        [ $(get_node_count $myList) -ne 1 ] && myList=\"\"\n    }\n    echo $myList\n}\n\nfacet_host() {\n\tlocal facet=$1\n\tlocal varname\n\n\t[ \"$facet\" == client ] && echo -n $HOSTNAME && return\n\tvarname=${facet}_HOST\n\tif [ -z \"${!varname}\" ]; then\n\t\tif [ \"${facet:0:3}\" == \"ost\" ]; then\n\t\t\tlocal fh=${facet%failover}_HOST\n\t\t\teval export ${facet}_HOST=${!fh}\n\t\t\tif [ -z \"${!varname}\" ]; then\n\t\t\t\teval export ${facet}_HOST=${ost_HOST}\n\t\t\tfi\n\t\telif [ \"${facet:0:3}\" == \"mdt\" -o \\\n\t\t\t\"${facet:0:3}\" == \"mds\" -o \\\n\t\t\t\"${facet:0:3}\" == \"mgs\" ]; then\n\t\t\teval export ${facet}_HOST=${mds_HOST}\n\t\tfi\n\tfi\n\techo -n ${!varname}\n}\n\nfacet_failover_host() {\n\tlocal facet=$1\n\tlocal varname\n\n\tvar=${facet}failover_HOST\n\tif [ -n \"${!var}\" ]; then\n\t\techo ${!var}\n\t\treturn\n\tfi\n\n\tif [ \"${facet:0:3}\" == \"mdt\" -o \"${facet:0:3}\" == \"mds\" -o \\\n\t     \"${facet:0:3}\" == \"mgs\" ]; then\n\n\t\teval export ${facet}failover_host=${mds_HOST}\n\t\techo ${mds_HOST}\n\t\treturn\n\tfi\n\n\tif [[ $facet == ost* ]]; then\n\t\teval export ${facet}failover_host=${ost_HOST}\n\t\techo ${ost_HOST}\n\t\treturn\n\tfi\n}\n\nfacet_active() {\n    local facet=$1\n    local activevar=${facet}active\n\n    if [ -f $TMP/${facet}active ] ; then\n        source $TMP/${facet}active\n    fi\n\n    active=${!activevar}\n    if [ -z \"$active\" ] ; then\n        echo -n ${facet}\n    else\n        echo -n ${active}\n    fi\n}\n\nfacet_active_host() {\n\tfacet_host $(facet_active $1)\n}\n\n# Get the passive failover partner host of facet.\nfacet_passive_host() {\n\tlocal facet=$1\n\t[[ $facet = client ]] && return\n\n\tlocal host=${facet}_HOST\n\tlocal failover_host=${facet}failover_HOST\n\tlocal active_host=$(facet_active_host $facet)\n\n\t[[ -z ${!failover_host} || ${!failover_host} = ${!host} ]] && return\n\n\tif [[ $active_host = ${!host} ]]; then\n\t\techo -n ${!failover_host}\n\telse\n\t\techo -n ${!host}\n\tfi\n}\n\nchange_active() {\n    local facetlist=$1\n    local facet\n\n    facetlist=$(exclude_items_from_list $facetlist mgs)\n\n    for facet in ${facetlist//,/ }; do\n    local failover=${facet}failover\n    local host=`facet_host $failover`\n    [ -z \"$host\" ] && return\n\n    local curactive=`facet_active $facet`\n    if [ -z \"${curactive}\" -o \"$curactive\" == \"$failover\" ] ; then\n        eval export ${facet}active=$facet\n    else\n        eval export ${facet}active=$failover\n    fi\n    # save the active host for this facet\n    local activevar=${facet}active\n    echo \"$activevar=${!activevar}\" > $TMP/$activevar\n    [[ $facet = mds1 ]] && combined_mgs_mds && \\\n        echo \"mgsactive=${!activevar}\" > $TMP/mgsactive\n    local TO=`facet_active_host $facet`\n    echo \"Failover $facet to $TO\"\n    done\n}\n\ndo_node() {\n    local verbose=false\n    # do not stripe off hostname if verbose, bug 19215\n    if [ x$1 = x--verbose ]; then\n        shift\n        verbose=true\n    fi\n\n    local HOST=$1\n    shift\n    local myPDSH=$PDSH\n    if [ \"$HOST\" = \"$HOSTNAME\" ]; then\n        myPDSH=\"no_dsh\"\n    elif [ -z \"$myPDSH\" -o \"$myPDSH\" = \"no_dsh\" ]; then\n        echo \"cannot run remote command on $HOST with $myPDSH\"\n        return 128\n    fi\n    if $VERBOSE; then\n        echo \"CMD: $HOST $@\" >&2\n        $myPDSH $HOST \"$LCTL mark \\\"$@\\\"\" > /dev/null 2>&1 || :\n    fi\n\n\tif [[ \"$myPDSH\" == \"rsh\" ]] ||\n\t   [[ \"$myPDSH\" == *pdsh* && \"$myPDSH\" != *-S* ]]; then\n\t\t# we need this because rsh and pdsh do not return\n\t\t# exit code of an executed command\n\t\tlocal command_status=\"$TMP/cs\"\n\t\teval $myPDSH $HOST \":> $command_status\"\n\t\teval $myPDSH $HOST \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests;\n\t\t\t\t     PATH=\\$PATH:/sbin:/usr/sbin;\n\t\t\t\t     cd $RPWD;\n\t\t\t\t     LUSTRE=\\\"$RLUSTRE\\\" sh -c \\\"$@\\\") ||\n\t\t\t\t     echo command failed >$command_status\"\n\t\t[[ -n \"$($myPDSH $HOST cat $command_status)\" ]] && return 1 ||\n\t\t\treturn 0\n\tfi\n\n    if $verbose ; then\n        # print HOSTNAME for myPDSH=\"no_dsh\"\n        if [[ $myPDSH = no_dsh ]]; then\n            $myPDSH $HOST \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\\\"$RLUSTRE\\\" sh -c \\\"$@\\\")\" | sed -e \"s/^/${HOSTNAME}: /\"\n        else\n            $myPDSH $HOST \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\\\"$RLUSTRE\\\" sh -c \\\"$@\\\")\"\n        fi\n    else\n        $myPDSH $HOST \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\\\"$RLUSTRE\\\" sh -c \\\"$@\\\")\" | sed \"s/^${HOST}: //\"\n    fi\n    return ${PIPESTATUS[0]}\n}\n\ndo_nodev() {\n    do_node --verbose \"$@\"\n}\n\nsingle_local_node () {\n   [ \"$1\" = \"$HOSTNAME\" ]\n}\n\n# Outputs environment variable assignments that should be passed to remote nodes\nget_env_vars() {\n\tlocal var\n\tlocal value\n\tlocal facets=$(get_facets)\n\tlocal facet\n\n\tfor var in ${!MODOPTS_*}; do\n\t\tvalue=${!var//\\\"/\\\\\\\"}\n\t\techo -n \" ${var}=\\\"$value\\\"\"\n\tdone\n\n\tfor facet in ${facets//,/ }; do\n\t\tvar=${facet}_FSTYPE\n\t\tif [ -n \"${!var}\" ]; then\n\t\t\techo -n \" $var=${!var}\"\n\t\tfi\n\tdone\n\n\tfor var in MGSFSTYPE MDSFSTYPE OSTFSTYPE; do\n\t\tif [ -n \"${!var}\" ]; then\n\t\t\techo -n \" $var=${!var}\"\n\t\tfi\n\tdone\n\n\tfor var in VERBOSE; do\n\t\tif [ -n \"${!var}\" ]; then\n\t\t\techo -n \" $var=${!var}\"\n\t\tfi\n\tdone\n\n\tif [ -n \"$FSTYPE\" ]; then\n\t\techo -n \" FSTYPE=$FSTYPE\"\n\tfi\n\n\tfor var in LNETLND NETTYPE; do\n\t\tif [ -n \"${!var}\" ]; then\n\t\t\techo -n \" $var=${!var}\"\n\t\tfi\n\tdone\n}\n\ndo_nodes() {\n    local verbose=false\n    # do not stripe off hostname if verbose, bug 19215\n    if [ x$1 = x--verbose ]; then\n        shift\n        verbose=true\n    fi\n\n    local rnodes=$1\n    shift\n\n    if single_local_node $rnodes; then\n        if $verbose; then\n           do_nodev $rnodes \"$@\"\n        else\n           do_node $rnodes \"$@\"\n        fi\n        return $?\n    fi\n\n    # This is part from do_node\n    local myPDSH=$PDSH\n\n    [ -z \"$myPDSH\" -o \"$myPDSH\" = \"no_dsh\" -o \"$myPDSH\" = \"rsh\" ] && \\\n        echo \"cannot run remote command on $rnodes with $myPDSH\" && return 128\n\n    export FANOUT=$(get_node_count \"${rnodes//,/ }\")\n    if $VERBOSE; then\n        echo \"CMD: $rnodes $@\" >&2\n        $myPDSH $rnodes \"$LCTL mark \\\"$@\\\"\" > /dev/null 2>&1 || :\n    fi\n\n    # do not replace anything from pdsh output if -N is used\n    # -N     Disable hostname: prefix on lines of output.\n    if $verbose || [[ $myPDSH = *-N* ]]; then\n        $myPDSH $rnodes \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\\\"$RLUSTRE\\\" $(get_env_vars) sh -c \\\"$@\\\")\"\n    else\n        $myPDSH $rnodes \"(PATH=\\$PATH:$RLUSTRE/utils:$RLUSTRE/tests:/sbin:/usr/sbin; cd $RPWD; LUSTRE=\\\"$RLUSTRE\\\" $(get_env_vars) sh -c \\\"$@\\\")\" | sed -re \"s/^[^:]*: //g\"\n    fi\n    return ${PIPESTATUS[0]}\n}\n\n##\n# Execute commands on a single service's host\n#\n# The \\a facet (service) may be on a local or remote node, which is\n# determined at the time the command is run.\n#\n# usage: do_facet $facet command [arg ...]\ndo_facet() {\n\tlocal facet=$1\n\tshift\n\tlocal HOST=$(facet_active_host $facet)\n\t[ -z $HOST ] && echo \"No host defined for facet ${facet}\" && exit 1\n\tdo_node $HOST \"$@\"\n}\n\n# Function: do_facet_random_file $FACET $FILE $SIZE\n# Creates FILE with random content on the given FACET of given SIZE\n\ndo_facet_random_file() {\n\tlocal facet=\"$1\"\n\tlocal fpath=\"$2\"\n\tlocal fsize=\"$3\"\n\tlocal cmd=\"dd if=/dev/urandom of='$fpath' bs=$fsize count=1\"\n\tdo_facet $facet \"$cmd 2>/dev/null\"\n}\n\ndo_facet_create_file() {\n\tlocal facet=\"$1\"\n\tlocal fpath=\"$2\"\n\tlocal fsize=\"$3\"\n\tlocal cmd=\"dd if=/dev/zero of='$fpath' bs=$fsize count=1\"\n\tdo_facet $facet \"$cmd 2>/dev/null\"\n}\n\ndo_nodesv() {\n    do_nodes --verbose \"$@\"\n}\n\nadd() {\n\tlocal facet=$1\n\tshift\n\t# make sure its not already running\n\tstop ${facet} -f\n\trm -f $TMP/${facet}active\n\t[[ $facet = mds1 ]] && combined_mgs_mds && rm -f $TMP/mgsactive\n\tdo_facet ${facet} $MKFS $* || return ${PIPESTATUS[0]}\n\n\tif [[ $(facet_fstype $facet) == zfs ]]; then\n\t\t#\n\t\t# After formatting a ZFS target, \"cachefile=none\" property will\n\t\t# be set on the ZFS storage pool so that the pool is not\n\t\t# automatically imported on system startup. And then the pool\n\t\t# will be exported so as to leave the importing and exporting\n\t\t# operations handled by mount_facet() and stop() separately.\n\t\t#\n\t\trefresh_partition_table $facet $(facet_vdevice $facet)\n\t\tdisable_zpool_cache $facet\n\t\texport_zpool $facet\n\tfi\n}\n\n# Device formatted as ost\nostdevname() {\n\tlocal num=$1\n\tlocal DEVNAME=OSTDEV$num\n\n\tlocal fstype=$(facet_fstype ost$num)\n\n\tcase $fstype in\n\t\tldiskfs )\n\t\t\tlocal dev=ost${num}_dev\n\t\t\t[[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||\n\t\t\t#if $OSTDEVn isn't defined, default is $OSTDEVBASE + num\n\t\t\teval DEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;\n\t\tzfs )\n\t\t\t#try $OSTZFSDEVn - independent of vdev\n\t\t\tDEVNAME=OSTZFSDEV$num\n\t\t\teval DEVPTR=${!DEVNAME:=${FSNAME}-ost${num}/ost${num}};;\n\t\t* )\n\t\t\terror \"unknown fstype!\";;\n\tesac\n\n    echo -n $DEVPTR\n}\n\n# Physical device location of data\nostvdevname() {\n\tlocal num=$1\n\tlocal DEVNAME\n\tlocal VDEVPTR\n\n\tlocal fstype=$(facet_fstype ost$num)\n\n\tcase $fstype in\n\t\tldiskfs )\n\t\t\t# vdevs are not supported by ldiskfs\n\t\t\teval VDEVPTR=\"\";;\n\t\tzfs )\n\t\t\t#if $OSTDEVn isn't defined, default is $OSTDEVBASE{n}\n\t\t\t# Device formatted by zfs\n\t\t\tDEVNAME=OSTDEV$num\n\t\t\teval VDEVPTR=${!DEVNAME:=${OSTDEVBASE}${num}};;\n\t\t* )\n\t\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $VDEVPTR\n}\n\n# Logical device formatted for lustre\nmdsdevname() {\n\tlocal num=$1\n\tlocal DEVNAME=MDSDEV$num\n\n\tlocal fstype=$(facet_fstype mds$num)\n\n\tcase $fstype in\n\t\tldiskfs )\n\t\t\tlocal dev=mds${num}_dev\n\t\t\t[[ -n ${!dev} ]] && eval DEVPTR=${!dev} ||\n\t\t\t#if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}\n\t\t\teval DEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;\n\t\tzfs )\n\t\t\t# try $MDSZFSDEVn - independent of vdev\n\t\t\tDEVNAME=MDSZFSDEV$num\n\t\t\teval DEVPTR=${!DEVNAME:=${FSNAME}-mdt${num}/mdt${num}};;\n\t\t* )\n\t\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $DEVPTR\n}\n\n# Physical location of data\nmdsvdevname() {\n\tlocal VDEVPTR=\"\"\n\tlocal num=$1\n\tlocal fstype=$(facet_fstype mds$num)\n\n\tcase $fstype in\n\t\tldiskfs )\n\t\t\t# vdevs are not supported by ldiskfs\n\t\t\teval VDEVPTR=\"\";;\n\t\tzfs )\n\t\t\t# if $MDSDEVn isn't defined, default is $MDSDEVBASE{n}\n\t\t\t# Device formatted by ZFS\n\t\t\tlocal DEVNAME=MDSDEV$num\n\t\t\teval VDEVPTR=${!DEVNAME:=${MDSDEVBASE}${num}};;\n\t\t* )\n\t\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $VDEVPTR\n}\n\nmgsdevname() {\n\tlocal DEVPTR\n\tlocal fstype=$(facet_fstype mgs)\n\n\tcase $fstype in\n\tldiskfs )\n\t\tif [ $(facet_host mgs) = $(facet_host mds1) ] &&\n\t\t   ( [ -z \"$MGSDEV\" ] || [ $MGSDEV = $MDSDEV1 ] ); then\n\t\t\tDEVPTR=$(mdsdevname 1)\n\t\telse\n\t\t\t[[ -n $mgs_dev ]] && DEVPTR=$mgs_dev ||\n\t\t\tDEVPTR=$MGSDEV\n\t\tfi;;\n\tzfs )\n\t\tif [ $(facet_host mgs) = $(facet_host mds1) ] &&\n\t\t    ( [ -z \"$MGSZFSDEV\" ] &&\n\t\t\t[ -z \"$MGSDEV\" -o \"$MGSDEV\" = $(mdsvdevname 1) ] ); then\n\t\t\tDEVPTR=$(mdsdevname 1)\n\t\telse\n\t\t\tDEVPTR=${MGSZFSDEV:-${FSNAME}-mgs/mgs}\n\t\tfi;;\n\t* )\n\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $DEVPTR\n}\n\nmgsvdevname() {\n\tlocal VDEVPTR=\"\"\n\n\tlocal fstype=$(facet_fstype mgs)\n\n\tcase $fstype in\n\tldiskfs )\n\t\t# vdevs are not supported by ldiskfs\n\t\t;;\n\tzfs )\n\t\tif [ $(facet_host mgs) = $(facet_host mds1) ] &&\n\t\t   ( [ -z \"$MGSDEV\" ] &&\n\t\t       [ -z \"$MGSZFSDEV\" -o \"$MGSZFSDEV\" = $(mdsdevname 1) ]); then\n\t\t\tVDEVPTR=$(mdsvdevname 1)\n\t\telif [ -n \"$MGSDEV\" ]; then\n\t\t\tVDEVPTR=$MGSDEV\n\t\tfi;;\n\t* )\n\t\terror \"unknown fstype!\";;\n\tesac\n\n\techo -n $VDEVPTR\n}\n\nfacet_mntpt () {\n    local facet=$1\n    [[ $facet = mgs ]] && combined_mgs_mds && facet=\"mds1\"\n\n    local var=${facet}_MOUNT\n    eval mntpt=${!var:-${MOUNT}-$facet}\n\n    echo -n $mntpt\n}\n\nmount_ldiskfs() {\n\tlocal facet=$1\n\tlocal dev=$(facet_device $facet)\n\tlocal mnt=${2:-$(facet_mntpt $facet)}\n\tlocal opts\n\tlocal dm_dev=$dev\n\n\tif dm_flakey_supported $facet; then\n\t\tdm_dev=$(dm_create_dev $facet $dev)\n\t\t[[ -n \"$dm_dev\" ]] || dm_dev=$dev\n\tfi\n\tis_blkdev $facet $dm_dev || opts=$(csa_add \"$opts\" -o loop)\n\texport_dm_dev $facet $dm_dev\n\n\tdo_facet $facet mount -t ldiskfs $opts $dm_dev $mnt\n}\n\nunmount_ldiskfs() {\n\tlocal facet=$1\n\tlocal dev=$(facet_device $facet)\n\tlocal mnt=${2:-$(facet_mntpt $facet)}\n\n\tdo_facet $facet $UMOUNT $mnt\n}\n\nvar_name() {\n\techo -n \"$1\" | tr -c '[:alnum:]\\n' '_'\n}\n\nmount_zfs() {\n\tlocal facet=$1\n\tlocal ds=$(facet_device $facet)\n\tlocal mnt=${2:-$(facet_mntpt $facet)}\n\tlocal canmnt\n\tlocal mntpt\n\n\timport_zpool $facet\n\tcanmnt=$(do_facet $facet $ZFS get -H -o value canmount $ds)\n\tmntpt=$(do_facet $facet $ZFS get -H -o value mountpoint $ds)\n\tdo_facet $facet $ZFS set canmount=noauto $ds\n\t#\n\t# The \"legacy\" mount method is used here because \"zfs unmount $mnt\"\n\t# calls stat(2) on $mnt/../*, which may include $MOUNT.  If certain\n\t# targets are not available at the time, the stat(2) on $MOUNT will\n\t# hang.\n\t#\n\tdo_facet $facet $ZFS set mountpoint=legacy $ds\n\tdo_facet $facet mount -t zfs $ds $mnt\n\teval export mz_$(var_name ${facet}_$ds)_canmount=$canmnt\n\teval export mz_$(var_name ${facet}_$ds)_mountpoint=$mntpt\n}\n\nunmount_zfs() {\n\tlocal facet=$1\n\tlocal ds=$(facet_device $facet)\n\tlocal mnt=${2:-$(facet_mntpt $facet)}\n\tlocal var_mntpt=mz_$(var_name ${facet}_$ds)_mountpoint\n\tlocal var_canmnt=mz_$(var_name ${facet}_$ds)_canmount\n\tlocal mntpt=${!var_mntpt}\n\tlocal canmnt=${!var_canmnt}\n\n\tunset $var_mntpt\n\tunset $var_canmnt\n\tdo_facet $facet umount $mnt\n\tdo_facet $facet $ZFS set mountpoint=$mntpt $ds\n\tdo_facet $facet $ZFS set canmount=$canmnt $ds\n\texport_zpool $facet\n}\n\nmount_fstype() {\n\tlocal facet=$1\n\tlocal mnt=$2\n\tlocal fstype=$(facet_fstype $facet)\n\n\tmount_$fstype $facet $mnt\n}\n\nunmount_fstype() {\n\tlocal facet=$1\n\tlocal mnt=$2\n\tlocal fstype=$(facet_fstype $facet)\n\n\tunmount_$fstype $facet $mnt\n}\n\n########\n## MountConf setup\n\nstopall() {\n\t# make sure we are using the primary server, so test-framework will\n\t# be able to clean up properly.\n\tactivemds=`facet_active mds1`\n\tif [ $activemds != \"mds1\" ]; then\n\t\tfail mds1\n\tfi\n\n\tlocal clients=$CLIENTS\n\t[ -z $clients ] && clients=$(hostname)\n\n\tzconf_umount_clients $clients $MOUNT \"$*\" || true\n\t[ -n \"$MOUNT2\" ] && zconf_umount_clients $clients $MOUNT2 \"$*\" || true\n\n\t[ -n \"$CLIENTONLY\" ] && return\n\n\t# The add fn does rm ${facet}active file, this would be enough\n\t# if we use do_facet <facet> only after the facet added, but\n\t# currently we use do_facet mds in local.sh\n\tfor num in `seq $MDSCOUNT`; do\n\t\tstop mds$num -f\n\t\trm -f ${TMP}/mds${num}active\n\tdone\n\tcombined_mgs_mds && rm -f $TMP/mgsactive\n\n\tfor num in `seq $OSTCOUNT`; do\n\t\tstop ost$num -f\n\t\trm -f $TMP/ost${num}active\n\tdone\n\n\tif ! combined_mgs_mds ; then\n\t\tstop mgs\n\tfi\n\n\tif $SHARED_KEY; then\n\t\texport SK_MOUNTED=false\n\tfi\n\n\treturn 0\n}\n\ncleanup_echo_devs () {\n\ttrap 0\n\tlocal dev\n\tlocal devs=$($LCTL dl | grep echo | awk '{print $4}')\n\n\tfor dev in $devs; do\n\t\t$LCTL --device $dev cleanup\n\t\t$LCTL --device $dev detach\n\tdone\n}\n\ncleanupall() {\n\tnfs_client_mode && return\n\tcifs_client_mode && return\n\n\tcleanup_echo_devs\n\tCLEANUP_DM_DEV=true stopall $*\n\n\tunload_modules\n\tcleanup_sk\n\tcleanup_gss\n}\n\ncombined_mgs_mds () {\n\t[[ \"$(mdsdevname 1)\" = \"$(mgsdevname)\" ]] &&\n\t\t[[ \"$(facet_host mds1)\" = \"$(facet_host mgs)\" ]]\n}\n\nlower() {\n\techo -n \"$1\" | tr '[:upper:]' '[:lower:]'\n}\n\nupper() {\n\techo -n \"$1\" | tr '[:lower:]' '[:upper:]'\n}\n\nsquash_opt() {\n\tlocal var=\"$*\"\n\tlocal other=\"\"\n\tlocal opt_o=\"\"\n\tlocal opt_e=\"\"\n\tlocal first_e=0\n\tlocal first_o=0\n\tlocal take=\"\"\n\n\tvar=$(echo \"$var\" | sed -e 's/,\\( \\)*/,/g')\n\tfor i in $(echo \"$var\"); do\n\t\tif [ \"$i\" == \"-O\" ]; then\n\t\t\ttake=\"o\";\n\t\t\tfirst_o=$(($first_o + 1))\n\t\t\tcontinue;\n\t\tfi\n\t\tif [ \"$i\" == \"-E\" ]; then\n\t\t\ttake=\"e\";\n\t\t\tfirst_e=$(($first_e + 1 ))\n\t\t\tcontinue;\n\t\tfi\n\t\tcase $take in\n\t\t\t\"o\")\n\t\t\t\t[ $first_o -gt 1 ] && opt_o+=\",\";\n\t\t\t\topt_o+=\"$i\";\n\t\t\t\t;;\n\t\t\t\"e\")\n\t\t\t\t[ $first_e -gt 1 ] && opt_e+=\",\";\n\t\t\t\topt_e+=\"$i\";\n\t\t\t\t;;\n\t\t\t*)\n\t\t\t\tother+=\" $i\";\n\t\t\t\t;;\n\t\tesac\n\t\ttake=\"\"\n\tdone\n\n\techo -n \"$other\"\n\t[ -n \"$opt_o\" ] && echo \" -O $opt_o\"\n\t[ -n \"$opt_e\" ] && echo \" -E $opt_e\"\n}\n\nmkfs_opts() {\n\tlocal facet=$1\n\tlocal dev=$2\n\tlocal fsname=${3:-\"$FSNAME\"}\n\tlocal type=$(facet_type $facet)\n\tlocal index=$(facet_index $facet)\n\tlocal fstype=$(facet_fstype $facet)\n\tlocal host=$(facet_host $facet)\n\tlocal opts\n\tlocal fs_mkfs_opts\n\tlocal var\n\n\tif [ $type == MGS ] || ( [ $type == MDS ] &&\n                                 [ \"$dev\" == $(mgsdevname) ] &&\n\t\t\t\t [ \"$host\" == \"$(facet_host mgs)\" ] ); then\n\t\topts=\"--mgs\"\n\telse\n\t\topts=\"--mgsnode=$MGSNID\"\n\tfi\n\n\tif [ $type != MGS ]; then\n\t\topts+=\" --fsname=$fsname --$(lower ${type/MDS/MDT}) \\\n\t\t\t--index=$index\"\n\tfi\n\n\tvar=${facet}failover_HOST\n\tif [ -n \"${!var}\" ] && [ ${!var} != $(facet_host $facet) ]; then\n\t\topts+=\" --failnode=$(h2nettype ${!var})\"\n\tfi\n\n\topts+=${TIMEOUT:+\" --param=sys.timeout=$TIMEOUT\"}\n\topts+=${LDLM_TIMEOUT:+\" --param=sys.ldlm_timeout=$LDLM_TIMEOUT\"}\n\n\tif [ $type == MDS ]; then\n\t\topts+=${MDSCAPA:+\" --param-mdt.capa=$MDSCAPA\"}\n\t\topts+=${DEF_STRIPE_SIZE:+\" --param=lov.stripesize=$DEF_STRIPE_SIZE\"}\n\t\topts+=${DEF_STRIPE_COUNT:+\" --param=lov.stripecount=$DEF_STRIPE_COUNT\"}\n\t\topts+=${L_GETIDENTITY:+\" --param=mdt.identity_upcall=$L_GETIDENTITY\"}\n\n\t\tif [ $fstype == ldiskfs ]; then\n\t\t\tfs_mkfs_opts+=\"-O ea_inode,large_dir\"\n\n\t\t\tvar=${facet}_JRN\n\t\t\tif [ -n \"${!var}\" ]; then\n\t\t\t\tfs_mkfs_opts+=\" -J device=${!var}\"\n\t\t\telse\n\t\t\t\tfs_mkfs_opts+=${MDSJOURNALSIZE:+\" -J size=$MDSJOURNALSIZE\"}\n\t\t\tfi\n\t\t\tfs_mkfs_opts+=${MDSISIZE:+\" -i $MDSISIZE\"}\n\t\tfi\n\tfi\n\n\tif [ $type == OST ]; then\n\t\topts+=${OSSCAPA:+\" --param=ost.capa=$OSSCAPA\"}\n\n\t\tif [ $fstype == ldiskfs ]; then\n\t\t\tvar=${facet}_JRN\n\t\t\tif [ -n \"${!var}\" ]; then\n\t\t\t\tfs_mkfs_opts+=\" -J device=${!var}\"\n\t\t\telse\n\t\t\t\tfs_mkfs_opts+=${OSTJOURNALSIZE:+\" -J size=$OSTJOURNALSIZE\"}\n\t\t\tfi\n\t\tfi\n\tfi\n\n\topts+=\" --backfstype=$fstype\"\n\n\tvar=${type}SIZE\n\tif [ -n \"${!var}\" ]; then\n\t\topts+=\" --device-size=${!var}\"\n\tfi\n\n\tvar=$(upper $fstype)_MKFS_OPTS\n\tfs_mkfs_opts+=${!var:+\" ${!var}\"}\n\n\tvar=${type}_FS_MKFS_OPTS\n\tfs_mkfs_opts+=${!var:+\" ${!var}\"}\n\n\t[[ \"$QUOTA_TYPE\" =~ \"p\" ]] && fs_mkfs_opts+=\" -O project\"\n\n\t[ $fstype == ldiskfs ] && fs_mkfs_opts=$(squash_opt $fs_mkfs_opts)\n\n\tif [ -n \"${fs_mkfs_opts## }\" ]; then\n\t\topts+=\" --mkfsoptions=\\\\\\\"${fs_mkfs_opts## }\\\\\\\"\"\n\tfi\n\n\tvar=${type}OPT\n\topts+=${!var:+\" ${!var}\"}\n\n\techo -n \"$opts\"\n}\n\nmountfs_opts() {\n\tlocal facet=$1\n\tlocal type=$(facet_type $facet)\n\tlocal var=${type}_MOUNT_FS_OPTS\n\tlocal opts=\"\"\n\tif [ -n \"${!var}\" ]; then\n\t\topts+=\" --mountfsoptions=${!var}\"\n\tfi\n\techo -n \"$opts\"\n}\n\ncheck_ost_indices() {\n\tlocal index_count=${#OST_INDICES[@]}\n\t[[ $index_count -eq 0 || $OSTCOUNT -le $index_count ]] && return 0\n\n\t# OST count is greater than the index count in $OST_INDEX_LIST.\n\t# We need check whether there are duplicate indices.\n\tlocal i\n\tlocal j\n\tlocal index\n\tfor i in $(seq $((index_count + 1)) $OSTCOUNT); do\n\t\tindex=$(facet_index ost$i)\n\t\tfor j in $(seq 0 $((index_count - 1))); do\n\t\t\t[[ $index -ne ${OST_INDICES[j]} ]] ||\n\t\t\terror \"ost$i has the same index $index as ost$((j+1))\"\n\t\tdone\n\tdone\n}\n\n__touch_device()\n{\n\tlocal facet_type=$1 # mgs || mds || ost\n\tlocal facet_num=$2\n\tlocal facet=${1}${2}\n\tlocal device\n\n\tcase \"$(facet_fstype $facet)\" in\n\tldiskfs)\n\t\tdevice=$(${facet_type}devname $facet_num)\n\t\t;;\n\tzfs)\n\t\tdevice=$(${facet_type}vdevname $facet_num)\n\t\t;;\n\t*)\n\t\terror \"Unhandled filesystem type\"\n\t\t;;\n\tesac\n\n\tdo_facet $facet \"[ -e \\\"$device\\\" ]\" && return\n\n\t# Note: the following check only works with absolute paths\n\t[[ ! \"$device\" =~ ^/dev/ ]] || [[ \"$device\" =~ ^/dev/shm/ ]] ||\n\t\terror \"$facet: device '$device' does not exist\"\n\n\t# zpool create doesn't like empty files\n\t[[ $(facet_fstype $facet) == zfs ]] && return 0\n\n\tdo_facet $facet \"touch \\\"${device}\\\"\"\n}\n\nformat_mgs() {\n\tlocal quiet\n\n\tif ! $VERBOSE; then\n\t\tquiet=yes\n\tfi\n\techo \"Format mgs: $(mgsdevname)\"\n\treformat_external_journal mgs\n\n\t# touch \"device\" in case it is a loopback file for testing and needs to\n\t# be created. mkfs.lustre doesn't do this to avoid accidentally writing\n\t# to non-existent files in /dev if the admin made a typo during setup\n\t__touch_device mgs\n\n\tadd mgs $(mkfs_opts mgs $(mgsdevname)) $(mountfs_opts mgs) --reformat \\\n\t\t$(mgsdevname) $(mgsvdevname) ${quiet:+>/dev/null} || exit 10\n}\n\nformat_mdt() {\n\tlocal num=$1\n\tlocal quiet\n\n\tif ! $VERBOSE; then\n\t\tquiet=yes\n\tfi\n\techo \"Format mds$num: $(mdsdevname $num)\"\n\treformat_external_journal mds$num\n\n\t__touch_device mds $num\n\n\tadd mds$num $(mkfs_opts mds$num $(mdsdevname ${num})) \\\n\t\t$(mountfs_opts mds$num) --reformat $(mdsdevname $num) \\\n\t\t$(mdsvdevname $num) ${quiet:+>/dev/null} || exit 10\n}\n\nformat_ost() {\n\tlocal num=$1\n\n\tif ! $VERBOSE; then\n\t\tquiet=yes\n\tfi\n\techo \"Format ost$num: $(ostdevname $num)\"\n\treformat_external_journal ost$num\n\n\t__touch_device ost $num\n\n\tadd ost$num $(mkfs_opts ost$num $(ostdevname ${num})) \\\n\t\t$(mountfs_opts ost$num) --reformat $(ostdevname $num) \\\n\t\t$(ostvdevname ${num}) ${quiet:+>/dev/null} || exit 10\n}\n\nformatall() {\n\tstopall -f\n\t# Set hostid for ZFS/SPL zpool import protection\n\t# (Assumes MDS version is also OSS version)\n\tif [ $(lustre_version_code $SINGLEMDS) -ge $(version_code 2.8.54) ];\n\tthen\n\t\tdo_rpc_nodes \"$(comma_list $(all_server_nodes))\" set_hostid\n\tfi\n\n\t# We need ldiskfs here, may as well load them all\n\tload_modules\n\t[ -n \"$CLIENTONLY\" ] && return\n\techo Formatting mgs, mds, osts\n\tif ! combined_mgs_mds ; then\n\t\tformat_mgs\n\tfi\n\n\tfor num in $(seq $MDSCOUNT); do\n\t\tformat_mdt $num\n\tdone\n\n\texport OST_INDICES=($(hostlist_expand \"$OST_INDEX_LIST\"))\n\tcheck_ost_indices\n\tfor num in $(seq $OSTCOUNT); do\n\t\tformat_ost $num\n\tdone\n}\n\nmount_client() {\n\tgrep \" $1 \" /proc/mounts || zconf_mount $HOSTNAME $*\n}\n\numount_client() {\n\tgrep \" $1 \" /proc/mounts && zconf_umount $HOSTNAME $*\n}\n\n# return value:\n# 0: success, the old identity set already.\n# 1: success, the old identity does not set.\n# 2: fail.\nswitch_identity() {\n    local num=$1\n    local switch=$2\n    local j=`expr $num - 1`\n    local MDT=\"`(do_facet mds$num lctl get_param -N mdt.*MDT*$j 2>/dev/null | cut -d\".\" -f2 2>/dev/null) || true`\"\n\n    if [ -z \"$MDT\" ]; then\n        return 2\n    fi\n\n    local old=\"`do_facet mds$num \"lctl get_param -n mdt.$MDT.identity_upcall\"`\"\n\n    if $switch; then\n        do_facet mds$num \"lctl set_param -n mdt.$MDT.identity_upcall \\\"$L_GETIDENTITY\\\"\"\n    else\n        do_facet mds$num \"lctl set_param -n mdt.$MDT.identity_upcall \\\"NONE\\\"\"\n    fi\n\n    do_facet mds$num \"lctl set_param -n mdt/$MDT/identity_flush=-1\"\n\n    if [ $old = \"NONE\" ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\nremount_client()\n{\n\tzconf_umount $HOSTNAME $1 || error \"umount failed\"\n\tzconf_mount $HOSTNAME $1 || error \"mount failed\"\n}\n\nwriteconf_facet() {\n\tlocal facet=$1\n\tlocal dev=$2\n\n\tstop ${facet} -f\n\trm -f $TMP/${facet}active\n\tdo_facet ${facet} \"$TUNEFS --quiet --writeconf $dev\" || return 1\n\treturn 0\n}\n\nwriteconf_all () {\n\tlocal mdt_count=${1:-$MDSCOUNT}\n\tlocal ost_count=${2:-$OSTCOUNT}\n\tlocal rc=0\n\n\tfor num in $(seq $mdt_count); do\n\t\tDEVNAME=$(mdsdevname $num)\n\t\twriteconf_facet mds$num $DEVNAME || rc=$?\n\tdone\n\n\tfor num in $(seq $ost_count); do\n\t\tDEVNAME=$(ostdevname $num)\n\t\twriteconf_facet ost$num $DEVNAME || rc=$?\n\tdone\n\treturn $rc\n}\n\nmountmgs() {\n\tif ! combined_mgs_mds ; then\n\t\tstart mgs $(mgsdevname) $MGS_MOUNT_OPTS\n\tfi\n}\n\nmountmds() {\n\tlocal num\n\tlocal devname\n\tlocal host\n\tlocal varname\n\tfor num in $(seq $MDSCOUNT); do\n\t\tdevname=$(mdsdevname $num)\n\t\tstart mds$num $devname $MDS_MOUNT_OPTS\n\n\t\t# We started mds$num, now we should set mds${num}_HOST\n\t\t# and mds${num}failover_HOST variables properly if they\n\t\t# are not set.\n\t\thost=$(facet_host mds$num)\n\t\tfor varname in mds${num}_HOST mds${num}failover_HOST; do\n\t\t\tif [[ -z \"${!varname}\" ]]; then\n\t\t\t\teval $varname=$host\n\t\t\tfi\n\t\tdone\n\t\tif [ $IDENTITY_UPCALL != \"default\" ]; then\n\t\t\tswitch_identity $num $IDENTITY_UPCALL\n\t\tfi\n\tdone\n}\n\nmountoss() {\n\tlocal num\n\tlocal devname\n\tlocal host\n\tlocal varname\n\tfor num in $(seq $OSTCOUNT); do\n\t\tdevname=$(ostdevname $num)\n\t\tstart ost$num $devname $OST_MOUNT_OPTS\n\n\t\t# We started ost$num, now we should set ost${num}_HOST\n\t\t# and ost${num}failover_HOST variables properly if they\n\t\t# are not set.\n\t\thost=$(facet_host ost$num)\n\t\tfor varname in ost${num}_HOST ost${num}failover_HOST; do\n\t\t\tif [[ -z \"${!varname}\" ]]; then\n\t\t\t\teval $varname=$host\n\t\t\tfi\n\t\tdone\n\tdone\n}\n\nmountcli() {\n\t[ \"$DAEMONFILE\" ] && $LCTL debug_daemon start $DAEMONFILE $DAEMONSIZE\n\tif [ ! -z $arg1 ]; then\n\t\t[ \"$arg1\" = \"server_only\" ] && return\n\tfi\n\tmount_client $MOUNT\n\tif [ -n \"$CLIENTS\" ]; then\n\t\tzconf_mount_clients $CLIENTS $MOUNT\n\tfi\n\tclients_up\n\n\tif [ \"$MOUNT_2\" ]; then\n\t\tmount_client $MOUNT2\n\t\tif [ -n \"$CLIENTS\" ]; then\n\t\t\tzconf_mount_clients $CLIENTS $MOUNT2\n\t\tfi\n\tfi\n}\n\nsk_nodemap_setup() {\n\tlocal sk_map_name=${1:-$SK_S2SNM}\n\tlocal sk_map_nodes=${2:-$HOSTNAME}\n\tdo_node $(mgs_node) \"$LCTL nodemap_add $sk_map_name\"\n\tfor servernode in $sk_map_nodes; do\n\t\tlocal nids=$(do_nodes $servernode \"$LCTL list_nids\")\n\t\tfor nid in $nids; do\n\t\t\tdo_node $(mgs_node) \"$LCTL nodemap_add_range --name \\\n\t\t\t\t$sk_map_name --range $nid\"\n\t\tdone\n\tdone\n}\n\nsetupall() {\n\tlocal arg1=$1\n\n\tnfs_client_mode && return\n\tcifs_client_mode && return\n\n\tsanity_mount_check || error \"environments are insane!\"\n\n\tload_modules\n\n\tinit_gss\n\n\tif [ -z \"$CLIENTONLY\" ]; then\n\t\techo Setup mgs, mdt, osts\n\t\techo $WRITECONF | grep -q \"writeconf\" && writeconf_all\n\n\t\tif $SK_MOUNTED; then\n\t\t\techo \"Shared Key file system already mounted\"\n\t\telse\n\t\t\tmountmgs\n\t\t\tmountmds\n\t\t\tmountoss\n\t\t\tif $SHARED_KEY; then\n\t\t\t\texport SK_MOUNTED=true\n\t\t\tfi\n\t\tfi\n\t\tif $GSS_SK; then\n\t\t\techo \"GSS_SK: setting kernel keyring perms\"\n\t\t\tdo_nodes $(comma_list $(all_nodes)) \\\n\t\t\t\t\"keyctl show | grep lustre | cut -c1-11 |\n\t\t\t\tsed -e 's/ //g;' |\n\t\t\t\txargs -IX keyctl setperm X 0x3f3f3f3f\"\n\n\t\t\tif $SK_S2S; then\n\t\t\t\t# Need to start one nodemap for servers,\n\t\t\t\t# and one for clients.\n\t\t\t\tsk_nodemap_setup $SK_S2SNM \\\n\t\t\t\t\t$(comma_list $(all_server_nodes))\n\t\t\t\tmountcli\n\t\t\t\tsk_nodemap_setup $SK_S2SNMCLI \\\n\t\t\t\t\t${CLIENTS:-$HOSTNAME}\n\t\t\t\techo \"Nodemap set up for SK S2S, remounting.\"\n\t\t\t\tstopall\n\t\t\t\tmountmgs\n\t\t\t\tmountmds\n\t\t\t\tmountoss\n\t\t\tfi\n\t\tfi\n\tfi\n\n\t# wait a while to allow sptlrpc configuration be propogated to targets,\n\t# only needed when mounting new target devices.\n\tif $GSS; then\n\t\tsleep 10\n\tfi\n\n\tmountcli\n\tinit_param_vars\n\n\t# by remounting mdt before ost, initial connect from mdt to ost might\n\t# timeout because ost is not ready yet. wait some time to its fully\n\t# recovery. initial obd_connect timeout is 5s; in GSS case it's\n\t# preceeded by a context negotiation rpc with $TIMEOUT.\n\t# FIXME better by monitoring import status.\n\tif $GSS; then\n\t\tif $GSS_SK; then\n\t\t\tset_rule $FSNAME any cli2mdt $SK_FLAVOR\n\t\t\tset_rule $FSNAME any cli2ost $SK_FLAVOR\n\t\t\tif $SK_SKIPFIRST; then\n\t\t\t\texport SK_SKIPFIRST=false\n\n\t\t\t\tsleep 30\n\t\t\t\tdo_nodes $CLIENTS \\\n\t\t\t\t\t \"lctl set_param osc.*.idle_connect=1\"\n\t\t\t\treturn\n\t\t\telse\n\t\t\t\twait_flavor cli2mdt $SK_FLAVOR\n\t\t\t\twait_flavor cli2ost $SK_FLAVOR\n\t\t\tfi\n\t\telse\n\t\t\tset_flavor_all $SEC\n\t\tfi\n\t\tsleep $((TIMEOUT + 5))\n\telse\n\t\tsleep 5\n\tfi\n}\n\nmounted_lustre_filesystems() {\n        awk '($3 ~ \"lustre\" && $1 ~ \":\") { print $2 }' /proc/mounts\n}\n\ninit_facet_vars () {\n\t[ -n \"$CLIENTONLY\" ] && return 0\n\tlocal facet=$1\n\tshift\n\tlocal device=$1\n\n\tshift\n\n\teval export ${facet}_dev=${device}\n\teval export ${facet}_opt=\\\"$@\\\"\n\n\tlocal dev=${facet}_dev\n\n\t# We need to loop for the label\n\t# in case its not initialized yet.\n\tfor wait_time in {0,1,3,5,10}; do\n\n\t\tif [ $wait_time -gt 0 ]; then\n\t\t\techo \"${!dev} not yet initialized,\"\\\n\t\t\t\t\"waiting ${wait_time} seconds.\"\n\t\t\tsleep $wait_time\n\t\tfi\n\n\t\tlocal label=$(devicelabel ${facet} ${!dev})\n\n\t\t# Check to make sure the label does\n\t\t# not include ffff at the end of the label.\n\t\t# This indicates it has not been initialized yet.\n\n\t\tif [[ $label =~ [f|F]{4}$ ]]; then\n\t\t\t# label is not initialized, unset the result\n\t\t\t# and either try again or fail\n\t\t\tunset label\n\t\telse\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t[ -z \"$label\" ] && echo no label for ${!dev} && exit 1\n\n\teval export ${facet}_svc=${label}\n\n\tlocal varname=${facet}failover_HOST\n\tif [ -z \"${!varname}\" ]; then\n\t\teval export $varname=$(facet_host $facet)\n\tfi\n\n\tvarname=${facet}_HOST\n\tif [ -z \"${!varname}\" ]; then\n\t\teval export $varname=$(facet_host $facet)\n \tfi\n\n\t# ${facet}failover_dev is set in cfg file\n\tvarname=${facet}failover_dev\n\tif [ -n \"${!varname}\" ] ; then\n\t\teval export ${facet}failover_dev=${!varname}\n\telse\n\t\teval export ${facet}failover_dev=$device\n\tfi\n\n\t# get mount point of already mounted device\n\t# is facet_dev is already mounted then use the real\n\t#  mount point of this facet; otherwise use $(facet_mntpt $facet)\n\t# i.e. ${facet}_MOUNT if specified by user or default\n\tlocal mntpt=$(do_facet ${facet} cat /proc/mounts | \\\n\t\t\tawk '\"'${!dev}'\" == $1 && $3 == \"lustre\" { print $2 }')\n\tif [ -z $mntpt ]; then\n\t\tmntpt=$(facet_mntpt $facet)\n\tfi\n\teval export ${facet}_MOUNT=$mntpt\n}\n\ninit_facets_vars () {\n\tlocal DEVNAME\n\n\tif ! remote_mds_nodsh; then\n\t\tfor num in $(seq $MDSCOUNT); do\n\t\t\tDEVNAME=`mdsdevname $num`\n\t\t\tinit_facet_vars mds$num $DEVNAME $MDS_MOUNT_OPTS\n\t\tdone\n\tfi\n\n\tcombined_mgs_mds || init_facet_vars mgs $(mgsdevname) $MGS_MOUNT_OPTS\n\n\tif ! remote_ost_nodsh; then\n\t\tfor num in $(seq $OSTCOUNT); do\n\t\t\tDEVNAME=$(ostdevname $num)\n\t\t\tinit_facet_vars ost$num $DEVNAME $OST_MOUNT_OPTS\n\t\tdone\n\tfi\n}\n\ninit_facets_vars_simple () {\n\tlocal devname\n\n\tif ! remote_mds_nodsh; then\n\t\tfor num in $(seq $MDSCOUNT); do\n\t\t\tdevname=$(mdsdevname $num)\n\t\t\teval export mds${num}_dev=${devname}\n\t\t\teval export mds${num}_opt=\\\"${MDS_MOUNT_OPTS}\\\"\n\t\tdone\n\tfi\n\n\tif ! combined_mgs_mds ; then\n\t\teval export mgs_dev=$(mgsdevname)\n\t\teval export mgs_opt=\\\"${MGS_MOUNT_OPTS}\\\"\n\tfi\n\n\tif ! remote_ost_nodsh; then\n\t\tfor num in $(seq $OSTCOUNT); do\n\t\t\tdevname=$(ostdevname $num)\n\t\t\teval export ost${num}_dev=${devname}\n\t\t\teval export ost${num}_opt=\\\"${OST_MOUNT_OPTS}\\\"\n\t\tdone\n\tfi\n}\n\nosc_ensure_active () {\n    local facet=$1\n    local timeout=$2\n    local period=0\n\n    while [ $period -lt $timeout ]; do\n        count=$(do_facet $facet \"lctl dl | grep ' IN osc ' 2>/dev/null | wc -l\")\n        if [ $count -eq 0 ]; then\n            break\n        fi\n\n        echo \"There are $count OST are inactive, wait $period seconds, and try again\"\n        sleep 3\n        period=$((period+3))\n    done\n\n    [ $period -lt $timeout ] || log \"$count OST are inactive after $timeout seconds, give up\"\n}\n\nset_conf_param_and_check() {\n\tlocal myfacet=$1\n\tlocal TEST=$2\n\tlocal PARAM=$3\n\tlocal ORIG=$(do_facet $myfacet \"$TEST\")\n\tif [ $# -gt 3 ]; then\n\t\tlocal FINAL=$4\n\telse\n\t\tlocal -i FINAL\n\t\tFINAL=$((ORIG + 5))\n\tfi\n\techo \"Setting $PARAM from $ORIG to $FINAL\"\n\tdo_facet mgs \"$LCTL conf_param $PARAM='$FINAL'\" ||\n\t\terror \"conf_param $PARAM failed\"\n\n\twait_update_facet $myfacet \"$TEST\" \"$FINAL\" ||\n\t\terror \"check $PARAM failed!\"\n}\n\nset_persistent_param() {\n\tlocal myfacet=$1\n\tlocal test_param=$2\n\tlocal param=$3\n\tlocal orig=$(do_facet $myfacet \"$LCTL get_param -n $test_param\")\n\n\tif [ $# -gt 3 ]; then\n\t\tlocal final=$4\n\telse\n\t\tlocal -i final\n\t\tfinal=$((orig + 5))\n\tfi\n\n\tif [[ $PERM_CMD == *\"set_param -P\"* ]]; then\n\t\techo \"Setting $test_param from $orig to $final\"\n\t\tdo_facet mgs \"$PERM_CMD $test_param='$final'\" ||\n\t\t\terror \"$PERM_CMD $test_param failed\"\n\telse\n\t\techo \"Setting $param from $orig to $final\"\n\t\tdo_facet mgs \"$PERM_CMD $param='$final'\" ||\n\t\t\terror \"$PERM_CMD $param failed\"\n\tfi\n}\n\nset_persistent_param_and_check() {\n\tlocal myfacet=$1\n\tlocal test_param=$2\n\tlocal param=$3\n\tlocal orig=$(do_facet $myfacet \"$LCTL get_param -n $test_param\")\n\n\tif [ $# -gt 3 ]; then\n\t\tlocal final=$4\n\telse\n\t\tlocal -i final\n\t\tfinal=$((orig + 5))\n\tfi\n\n\tset_persistent_param $myfacet $test_param $param \"$final\"\n\n\twait_update_facet $myfacet \"$LCTL get_param -n $test_param\" \"$final\" ||\n\t\terror \"check $param failed!\"\n}\n\ninit_param_vars () {\n\tTIMEOUT=$(lctl get_param -n timeout)\n\tTIMEOUT=${TIMEOUT:-20}\n\n\tif [ -n \"$arg1\" ]; then\n\t\t[ \"$arg1\" = \"server_only\" ] && return\n\tfi\n\n\tremote_mds_nodsh && log \"Using TIMEOUT=$TIMEOUT\" && return 0\n\n\tTIMEOUT=$(do_facet $SINGLEMDS \"lctl get_param -n timeout\")\n\tlog \"Using TIMEOUT=$TIMEOUT\"\n\n\tosc_ensure_active $SINGLEMDS $TIMEOUT\n\tosc_ensure_active client $TIMEOUT\n\t$LCTL set_param osc.*.idle_timeout=debug\n\n\tif [ -n \"$(lctl get_param -n mdc.*.connect_flags|grep jobstats)\" ]; then\n\t\tlocal current_jobid_var=$($LCTL get_param -n jobid_var)\n\n\t\tif [ $JOBID_VAR = \"existing\" ]; then\n\t\t\techo \"keeping jobstats as $current_jobid_var\"\n\t\telif [ $current_jobid_var != $JOBID_VAR ]; then\n\t\t\techo \"setting jobstats to $JOBID_VAR\"\n\n\t\t\tset_persistent_param_and_check client \\\n\t\t\t\t\"jobid_var\" \"$FSNAME.sys.jobid_var\" $JOBID_VAR\n\t\tfi\n\telse\n\t\techo \"jobstats not supported by server\"\n\tfi\n\n\tif [ $QUOTA_AUTO -ne 0 ]; then\n\t\tif [ \"$ENABLE_QUOTA\" ]; then\n\t\t\techo \"enable quota as required\"\n\t\t\tsetup_quota $MOUNT || return 2\n\t\telse\n\t\t\techo \"disable quota as required\"\n\t\t\t# $LFS quotaoff -ug $MOUNT > /dev/null 2>&1\n\t\tfi\n\tfi\n\n\t(( MDS1_VERSION <= $(version_code 2.13.52) )) ||\n\t\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t\"$LCTL set_param lod.*.mdt_hash=crush\"\n\treturn 0\n}\n\nnfs_client_mode () {\n    if [ \"$NFSCLIENT\" ]; then\n        echo \"NFSCLIENT mode: setup, cleanup, check config skipped\"\n        local clients=$CLIENTS\n        [ -z $clients ] && clients=$(hostname)\n\n        # FIXME: remove hostname when 19215 fixed\n        do_nodes $clients \"echo \\\\\\$(hostname); grep ' '$MOUNT' ' /proc/mounts\"\n        declare -a nfsexport=(`grep ' '$MOUNT' ' /proc/mounts | awk '{print $1}' | awk -F: '{print $1 \" \"  $2}'`)\n        if [[ ${#nfsexport[@]} -eq 0 ]]; then\n                error_exit NFSCLIENT=$NFSCLIENT mode, but no NFS export found!\n        fi\n        do_nodes ${nfsexport[0]} \"echo \\\\\\$(hostname); df -T  ${nfsexport[1]}\"\n        return\n    fi\n    return 1\n}\n\ncifs_client_mode () {\n\t[ x$CIFSCLIENT = xyes ] &&\n\t\techo \"CIFSCLIENT=$CIFSCLIENT mode: setup, cleanup, check config skipped\"\n}\n\ncheck_config_client () {\n    local mntpt=$1\n\n    local mounted=$(mount | grep \" $mntpt \")\n    if [ -n \"$CLIENTONLY\" ]; then\n        # bug 18021\n        # CLIENTONLY should not depend on *_HOST settings\n        local mgc=$($LCTL device_list | awk '/MGC/ {print $4}')\n        # in theory someone could create a new,\n        # client-only config file that assumed lustre was already\n        # configured and didn't set the MGSNID. If MGSNID is not set,\n        # then we should use the mgs nid currently being used\n        # as the default value. bug 18021\n        [[ x$MGSNID = x ]] &&\n            MGSNID=${mgc//MGC/}\n\n        if [[ x$mgc != xMGC$MGSNID ]]; then\n            if [ \"$mgs_HOST\" ]; then\n                local mgc_ip=$(ping -q -c1 -w1 $mgs_HOST | grep PING | awk '{print $3}' | sed -e \"s/(//g\" -e \"s/)//g\")\n#                [[ x$mgc = xMGC$mgc_ip@$NETTYPE ]] ||\n#                    error_exit \"MGSNID=$MGSNID, mounted: $mounted, MGC : $mgc\"\n            fi\n        fi\n        return 0\n    fi\n\n    echo Checking config lustre mounted on $mntpt\n    local mgshost=$(mount | grep \" $mntpt \" | awk -F@ '{print $1}')\n    mgshost=$(echo $mgshost | awk -F: '{print $1}')\n\n}\n\ncheck_config_clients () {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal mntpt=$1\n\n\tnfs_client_mode && return\n\tcifs_client_mode && return\n\n\tdo_rpc_nodes \"$clients\" check_config_client $mntpt\n\n\tsanity_mount_check || error \"environments are insane!\"\n}\n\ncheck_timeout () {\n    local mdstimeout=$(do_facet $SINGLEMDS \"lctl get_param -n timeout\")\n    local cltimeout=$(lctl get_param -n timeout)\n    if [ $mdstimeout -ne $TIMEOUT ] || [ $mdstimeout -ne $cltimeout ]; then\n        error \"timeouts are wrong! mds: $mdstimeout, client: $cltimeout, TIMEOUT=$TIMEOUT\"\n        return 1\n    fi\n}\n\nis_mounted () {\n\tlocal mntpt=$1\n\t[ -z $mntpt ] && return 1\n\tlocal mounted=$(mounted_lustre_filesystems)\n\n\techo $mounted' ' | grep -w -q $mntpt' '\n}\n\nis_empty_dir() {\n\t[ $(find $1 -maxdepth 1 -print | wc -l) = 1 ] && return 0\n\treturn 1\n}\n\n# empty lustre filesystem may have empty directories lost+found and .lustre\nis_empty_fs() {\n\t# exclude .lustre & lost+found\n\t[ $(find $1 -maxdepth 1 -name lost+found -o -name .lustre -prune -o \\\n\t\t-print | wc -l) = 1 ] || return 1\n\t[ ! -d $1/lost+found ] || is_empty_dir $1/lost+found || return 1\n\tif [ $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.4.0) ]; then\n\t\t# exclude .lustre/fid (LU-2780)\n\t\t[ $(find $1/.lustre -maxdepth 1 -name fid -prune -o \\\n\t\t\t-print | wc -l) = 1 ] || return 1\n\telse\n\t\t[ ! -d $1/.lustre ] || is_empty_dir $1/.lustre || return 1\n\tfi\n\treturn 0\n}\n\ncheck_and_setup_lustre() {\n\tsanitize_parameters\n\tnfs_client_mode && return\n\tcifs_client_mode && return\n\n\tlocal MOUNTED=$(mounted_lustre_filesystems)\n\n\tlocal do_check=true\n\t# 1.\n\t# both MOUNT and MOUNT2 are not mounted\n\tif ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then\n\t\t[ \"$REFORMAT\" = \"yes\" ] && CLEANUP_DM_DEV=true formatall\n\t\t# setupall mounts both MOUNT and MOUNT2 (if MOUNT_2 is set)\n\t\tsetupall\n\t\tis_mounted $MOUNT || error \"NAME=$NAME not mounted\"\n\t\texport I_MOUNTED=yes\n\t\tdo_check=false\n    # 2.\n    # MOUNT2 is mounted\n    elif is_mounted $MOUNT2; then\n            # 3.\n            # MOUNT2 is mounted, while MOUNT_2 is not set\n            if ! [ \"$MOUNT_2\" ]; then\n                cleanup_mount $MOUNT2\n                export I_UMOUNTED2=yes\n\n            # 4.\n            # MOUNT2 is mounted, MOUNT_2 is set\n            else\n                # FIXME: what to do if check_config failed?\n                # i.e. if:\n                # 1) remote client has mounted other Lustre fs ?\n                # 2) it has insane env ?\n                # let's try umount MOUNT2 on all clients and mount it again:\n                if ! check_config_clients $MOUNT2; then\n                    cleanup_mount $MOUNT2\n                    restore_mount $MOUNT2\n                    export I_MOUNTED2=yes\n                fi\n            fi\n\n    # 5.\n    # MOUNT is mounted MOUNT2 is not mounted\n    elif [ \"$MOUNT_2\" ]; then\n        restore_mount $MOUNT2\n        export I_MOUNTED2=yes\n    fi\n\n    if $do_check; then\n        # FIXME: what to do if check_config failed?\n        # i.e. if:\n        # 1) remote client has mounted other Lustre fs?\n        # 2) lustre is mounted on remote_clients atall ?\n        check_config_clients $MOUNT\n        init_facets_vars\n        init_param_vars\n\n        set_default_debug_nodes $(comma_list $(nodes_list))\n    fi\n\n\tif [ -z \"$CLIENTONLY\" -a $(lower $OSD_TRACK_DECLARES_LBUG) == 'yes' ]; then\n\t\tlocal facets=\"\"\n\t\t[ \"$(facet_fstype ost1)\" = \"ldiskfs\" ] &&\n\t\t\tfacets=\"$(get_facets OST)\"\n\t\t[ \"$(facet_fstype mds1)\" = \"ldiskfs\" ] &&\n\t\t\tfacets=\"$facets,$(get_facets MDS)\"\n\t\t[ \"$(facet_fstype mgs)\" = \"ldiskfs\" ] &&\n\t\t\tfacets=\"$facets,mgs\"\n\t\tlocal nodes=\"$(facets_hosts ${facets})\"\n\t\tif [ -n \"$nodes\" ] ; then\n\t\t\tdo_nodes $nodes \"$LCTL set_param \\\n\t\t\t\t osd-ldiskfs.track_declares_assert=1 || true\"\n\t\tfi\n\tfi\n\n\tif [ -n \"$fs_STRIPEPARAMS\" ]; then\n\t\tsetstripe_getstripe $MOUNT $fs_STRIPEPARAMS\n\tfi\n\tif $GSS_SK; then\n\t\tset_flavor_all null\n\telif $GSS; then\n\t\tset_flavor_all $SEC\n\tfi\n\n\tif [ \"$ONLY\" == \"setup\" ]; then\n\t\texit 0\n\tfi\n}\n\nrestore_mount () {\n   local clients=${CLIENTS:-$HOSTNAME}\n   local mntpt=$1\n\n   zconf_mount_clients $clients $mntpt\n}\n\ncleanup_mount () {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\tlocal mntpt=$1\n\n\tzconf_umount_clients $clients $mntpt\n}\n\ncleanup_and_setup_lustre() {\n    if [ \"$ONLY\" == \"cleanup\" -o \"`mount | grep $MOUNT`\" ]; then\n        lctl set_param debug=0 || true\n        cleanupall\n        if [ \"$ONLY\" == \"cleanup\" ]; then\n            exit 0\n        fi\n    fi\n    check_and_setup_lustre\n}\n\n# Get all of the server target devices from a given server node and type.\nget_mnt_devs() {\n\tlocal node=$1\n\tlocal type=$2\n\tlocal devs\n\tlocal dev\n\n\tif [ \"$type\" == ost ]; then\n\t\tdevs=$(get_osd_param $node \"\" mntdev)\n\telse\n\t\tdevs=$(do_node $node $LCTL get_param -n osd-*.$FSNAME-M*.mntdev)\n\tfi\n\tfor dev in $devs; do\n\t\tcase $dev in\n\t\t*loop*) do_node $node \"losetup $dev\" | \\\n\t\t\t\tsed -e \"s/.*(//\" -e \"s/).*//\" ;;\n\t\t*) echo $dev ;;\n\t\tesac\n\tdone\n}\n\n# Get all of the server target devices.\nget_svr_devs() {\n\tlocal node\n\tlocal i\n\n\t# Master MDS parameters used by lfsck\n\tMDTNODE=$(facet_active_host $SINGLEMDS)\n\tMDTDEV=$(echo $(get_mnt_devs $MDTNODE mdt) | awk '{print $1}')\n\n\t# MDT devices\n\ti=0\n\tfor node in $(mdts_nodes); do\n\t\tMDTDEVS[i]=$(get_mnt_devs $node mdt)\n\t\ti=$((i + 1))\n\tdone\n\n\t# OST devices\n\ti=0\n\tfor node in $(osts_nodes); do\n\t\tOSTDEVS[i]=$(get_mnt_devs $node ost)\n\t\ti=$((i + 1))\n\tdone\n}\n\n# Run e2fsck on MDT or OST device.\nrun_e2fsck() {\n\tlocal node=$1\n\tlocal target_dev=$2\n\tlocal extra_opts=$3\n\tlocal cmd=\"$E2FSCK -d -v -t -t -f $extra_opts $target_dev\"\n\tlocal log=$TMP/e2fsck.log\n\tlocal rc=0\n\n\techo $cmd\n\tdo_node $node $cmd 2>&1 | tee $log\n\trc=${PIPESTATUS[0]}\n\tif [ -n \"$(grep \"DNE mode isn't supported\" $log)\" ]; then\n\t\trm -f $log\n\t\tif [ $MDSCOUNT -gt 1 ]; then\n\t\t\tskip_noexit \"DNE mode isn't supported!\"\n\t\t\tcleanupall\n\t\t\texit_status\n\t\telse\n\t\t\terror \"It's not DNE mode.\"\n\t\tfi\n\tfi\n\trm -f $log\n\n\t[ $rc -le $FSCK_MAX_ERR ] ||\n\t\terror \"$cmd returned $rc, should be <= $FSCK_MAX_ERR\"\n\n\treturn 0\n}\n\n#\n# Run resize2fs on MDT or OST device.\n#\nrun_resize2fs() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal size=$3\n\tshift 3\n\tlocal opts=\"$@\"\n\n\tdo_facet $facet \"$RESIZE2FS $opts $device $size\"\n}\n\n# verify a directory is shared among nodes.\ncheck_shared_dir() {\n\tlocal dir=$1\n\tlocal list=${2:-$(comma_list $(nodes_list))}\n\n\t[ -z \"$dir\" ] && return 1\n\tdo_rpc_nodes \"$list\" check_logdir $dir\n\tcheck_write_access $dir \"$list\" || return 1\n\treturn 0\n}\n\nrun_lfsck() {\n\tdo_nodes $(comma_list $(mdts_nodes) $(osts_nodes)) \\\n\t\t$LCTL set_param printk=+lfsck\n\tdo_facet $SINGLEMDS \"$LCTL lfsck_start -M $FSNAME-MDT0000 -r -A -t all\"\n\n\tfor k in $(seq $MDSCOUNT); do\n\t\t# wait up to 10+1 minutes for LFSCK to complete\n\t\twait_update_facet --verbose mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_layout |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 600 ||\n\t\t\terror \"MDS${k} layout isn't the expected 'completed'\"\n\t\twait_update_facet --verbose mds${k} \"$LCTL get_param -n \\\n\t\t\tmdd.$(facet_svc mds${k}).lfsck_namespace |\n\t\t\tawk '/^status/ { print \\\\\\$2 }'\" \"completed\" 60 ||\n\t\t\terror \"MDS${k} namespace isn't the expected 'completed'\"\n\tdone\n\tlocal rep_mdt=$(do_nodes $(comma_list $(mdts_nodes)) \\\n\t\t\t$LCTL get_param -n mdd.$FSNAME-*.lfsck_* |\n\t\t\tawk '/repaired/ { print $2 }' | calc_sum)\n\tlocal rep_ost=$(do_nodes $(comma_list $(osts_nodes)) \\\n\t\t\t$LCTL get_param -n obdfilter.$FSNAME-*.lfsck_* |\n\t\t\tawk '/repaired/ { print $2 }' | calc_sum)\n\tlocal repaired=$((rep_mdt + rep_ost))\n\t[ $repaired -eq 0 ] ||\n\t\terror \"lfsck repaired $rep_mdt MDT and $rep_ost OST errors\"\n}\n\ndump_file_contents() {\n\tlocal nodes=$1\n\tlocal dir=$2\n\tlocal logname=$3\n\tlocal node\n\n\tif [ -z \"$nodes\" -o -z \"$dir\" -o -z \"$logname\" ]; then\n\t\terror_noexit false \\\n\t\t\t\"Invalid parameters for dump_file_contents()\"\n\t\treturn 1\n\tfi\n\tfor node in ${nodes}; do\n\t\tdo_node $node \"for i in \\\\\\$(find $dir -type f); do\n\t\t\t\techo ====\\\\\\${i}=======================;\n\t\t\t\tcat \\\\\\${i};\n\t\t\t\tdone\" >> ${logname}.${node}.log\n\tdone\n}\n\ndump_command_output() {\n\tlocal nodes=$1\n\tlocal cmd=$2\n\tlocal logname=$3\n\tlocal node\n\n\tif [ -z \"$nodes\" -o -z \"$cmd\" -o -z \"$logname\" ]; then\n\t\terror_noexit false \\\n\t\t\t\"Invalid parameters for dump_command_output()\"\n\t\treturn 1\n\tfi\n\n\tfor node in ${nodes}; do\n\t\tdo_node $node \"echo ====${cmd}=======================;\n\t\t\t\t$cmd\" >> ${logname}.${node}.log\n\tdone\n}\n\nlog_zfs_info() {\n\tlocal logname=$1\n\n\t# dump file contents from /proc/spl in case of zfs test\n\tif [ \"$(facet_fstype ost1)\" = \"zfs\" ]; then\n\t\tdump_file_contents \"$(osts_nodes)\" \"/proc/spl\" \"${logname}\"\n\t\tdump_command_output \\\n\t\t\t\"$(osts_nodes)\" \"zpool events -v\" \"${logname}\"\n\tfi\n\n\tif [ \"$(facet_fstype $SINGLEMDS)\" = \"zfs\" ]; then\n\t\tdump_file_contents \"$(mdts_nodes)\" \"/proc/spl\" \"${logname}\"\n\t\tdump_command_output \\\n\t\t\t\"$(mdts_nodes)\" \"zpool events -v\" \"${logname}\"\n\tfi\n}\n\ncheck_and_cleanup_lustre() {\n\tif [ \"$LFSCK_ALWAYS\" = \"yes\" -a \"$TESTSUITE\" != \"sanity-lfsck\" -a \\\n\t     \"$TESTSUITE\" != \"sanity-scrub\" ]; then\n\t\trun_lfsck\n\tfi\n\n\tif is_mounted $MOUNT; then\n\t\tif $DO_CLEANUP; then\n\t\t\t[ -n \"$DIR\" ] && rm -rf $DIR/[Rdfs][0-9]* ||\n\t\t\t\terror \"remove sub-test dirs failed\"\n\t\telse\n\t\t\techo \"skip cleanup\"\n\t\tfi\n\t\t[ \"$ENABLE_QUOTA\" ] && restore_quota || true\n\tfi\n\n\tif [ \"$I_UMOUNTED2\" = \"yes\" ]; then\n\t\trestore_mount $MOUNT2 || error \"restore $MOUNT2 failed\"\n\tfi\n\n\tif [ \"$I_MOUNTED2\" = \"yes\" ]; then\n\t\tcleanup_mount $MOUNT2\n\tfi\n\n\tif [[ \"$I_MOUNTED\" = \"yes\" ]] && ! $AUSTER_CLEANUP; then\n\t\tcleanupall -f || error \"cleanup failed\"\n\t\tunset I_MOUNTED\n\tfi\n}\n\n#######\n# General functions\n\nwait_for_function () {\n    local quiet=\"\"\n\n    # suppress fn both stderr and stdout\n    if [ \"$1\" = \"--quiet\" ]; then\n        shift\n        quiet=\" > /dev/null 2>&1\"\n\n    fi\n\n    local fn=$1\n    local max=${2:-900}\n    local sleep=${3:-5}\n\n    local wait=0\n\n    while true; do\n\n        eval $fn $quiet && return 0\n\n        wait=$((wait + sleep))\n        [ $wait -lt $max ] || return 1\n        echo waiting $fn, $((max - wait)) secs left ...\n        sleep $sleep\n    done\n}\n\ncheck_network() {\n\tlocal host=$1\n\tlocal max=$2\n\tlocal sleep=${3:-5}\n\n\t[ \"$host\" = \"$HOSTNAME\" ] && return 0\n\n\tif ! wait_for_function --quiet \"ping -c 1 -w 3 $host\" $max $sleep; then\n\t\techo \"$(date +'%H:%M:%S (%s)') waited for $host network ${max}s\"\n\t\texit 1\n\tfi\n}\n\nno_dsh() {\n    shift\n    eval $@\n}\n\n# Convert a space-delimited list to a comma-delimited list.  If the input is\n# only whitespace, ensure the output is empty (i.e. \"\") so [ -n $list ] works\ncomma_list() {\n\t# echo is used to convert newlines to spaces, since it doesn't\n\t# introduce a trailing space as using \"tr '\\n' ' '\" does\n\techo $(tr -s \" \" \"\\n\" <<< $* | sort -b -u) | tr ' ' ','\n}\n\nlist_member () {\n    local list=$1\n    local item=$2\n    echo $list | grep -qw $item\n}\n\n# list, excluded are the comma separated lists\nexclude_items_from_list () {\n    local list=$1\n    local excluded=$2\n    local item\n\n    list=${list//,/ }\n    for item in ${excluded//,/ }; do\n        list=$(echo \" $list \" | sed -re \"s/\\s+$item\\s+/ /g\")\n    done\n    echo $(comma_list $list)\n}\n\n# list, expand  are the comma separated lists\nexpand_list () {\n    local list=${1//,/ }\n    local expand=${2//,/ }\n    local expanded=\n\n    expanded=$(for i in $list $expand; do echo $i; done | sort -u)\n    echo $(comma_list $expanded)\n}\n\ntestslist_filter () {\n    local script=$LUSTRE/tests/${TESTSUITE}.sh\n\n    [ -f $script ] || return 0\n\n    local start_at=$START_AT\n    local stop_at=$STOP_AT\n\n    local var=${TESTSUITE//-/_}_START_AT\n    [ x\"${!var}\" != x ] && start_at=${!var}\n    var=${TESTSUITE//-/_}_STOP_AT\n    [ x\"${!var}\" != x ] && stop_at=${!var}\n\n    sed -n 's/^test_\\([^ (]*\\).*/\\1/p' $script | \\\n        awk ' BEGIN { if (\"'${start_at:-0}'\" != 0) flag = 1 }\n            /^'${start_at}'$/ {flag = 0}\n            {if (flag == 1) print $0}\n            /^'${stop_at}'$/ { flag = 1 }'\n}\n\nabsolute_path() {\n    (cd `dirname $1`; echo $PWD/`basename $1`)\n}\n\nget_facets () {\n    local types=${1:-\"OST MDS MGS\"}\n\n    local list=\"\"\n\n    for entry in $types; do\n        local name=$(echo $entry | tr \"[:upper:]\" \"[:lower:]\")\n        local type=$(echo $entry | tr \"[:lower:]\" \"[:upper:]\")\n\n        case $type in\n                MGS ) list=\"$list $name\";;\n            MDS|OST|AGT ) local count=${type}COUNT\n                       for ((i=1; i<=${!count}; i++)) do\n                          list=\"$list ${name}$i\"\n                      done;;\n                  * ) error \"Invalid facet type\"\n                 exit 1;;\n        esac\n    done\n    echo $(comma_list $list)\n}\n\n##################################\n# Adaptive Timeouts funcs\n\nat_is_enabled() {\n    # only check mds, we assume at_max is the same on all nodes\n    local at_max=$(do_facet $SINGLEMDS \"lctl get_param -n at_max\")\n    if [ $at_max -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\nat_get() {\n    local facet=$1\n    local at=$2\n\n    # suppose that all ost-s have the same $at value set\n    [ $facet != \"ost\" ] || facet=ost1\n\n    do_facet $facet \"lctl get_param -n $at\"\n}\n\nat_max_get() {\n    at_get $1 at_max\n}\n\nat_min_get() {\n\tat_get $1 at_min\n}\n\nat_max_set() {\n    local at_max=$1\n    shift\n\n    local facet\n    local hosts\n    for facet in $@; do\n        if [ $facet == \"ost\" ]; then\n            facet=$(get_facets OST)\n        elif [ $facet == \"mds\" ]; then\n            facet=$(get_facets MDS)\n        fi\n        hosts=$(expand_list $hosts $(facets_hosts $facet))\n    done\n\n    do_nodes $hosts lctl set_param at_max=$at_max\n}\n\n##################################\n# OBD_FAIL funcs\n\ndrop_request() {\n# OBD_FAIL_MDS_ALL_REQUEST_NET\n    RC=0\n    do_facet $SINGLEMDS lctl set_param fail_val=0 fail_loc=0x123\n    do_facet client \"$1\" || RC=$?\n    do_facet $SINGLEMDS lctl set_param fail_loc=0\n    return $RC\n}\n\ndrop_reply() {\n# OBD_FAIL_MDS_ALL_REPLY_NET\n\tRC=0\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x122\n\teval \"$@\" || RC=$?\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\treturn $RC\n}\n\ndrop_reint_reply() {\n# OBD_FAIL_MDS_REINT_NET_REP\n\tRC=0\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0x119\n\teval \"$@\" || RC=$?\n\tdo_facet $SINGLEMDS $LCTL set_param fail_loc=0\n\treturn $RC\n}\n\ndrop_update_reply() {\n# OBD_FAIL_OUT_UPDATE_NET_REP\n\tlocal index=$1\n\tshift 1\n\tRC=0\n\tdo_facet mds${index} lctl set_param fail_loc=0x1701\n\tdo_facet client \"$@\" || RC=$?\n\tdo_facet mds${index} lctl set_param fail_loc=0\n\treturn $RC\n}\n\npause_bulk() {\n#define OBD_FAIL_OST_BRW_PAUSE_BULK      0x214\n\tRC=0\n\n\tlocal timeout=${2:-0}\n\t# default is (obd_timeout / 4) if unspecified\n\techo \"timeout is $timeout/$2\"\n\tdo_facet ost1 lctl set_param fail_val=$timeout fail_loc=0x80000214\n\tdo_facet client \"$1\" || RC=$?\n\tdo_facet client \"sync\"\n\tdo_facet ost1 lctl set_param fail_loc=0\n\treturn $RC\n}\n\ndrop_ldlm_cancel() {\n#define OBD_FAIL_LDLM_CANCEL_NET\t\t\t0x304\n\tlocal RC=0\n\tlocal list=$(comma_list $(mdts_nodes) $(osts_nodes))\n\tdo_nodes $list lctl set_param fail_loc=0x304\n\n\tdo_facet client \"$@\" || RC=$?\n\n\tdo_nodes $list lctl set_param fail_loc=0\n\treturn $RC\n}\n\ndrop_bl_callback_once() {\n\tlocal rc=0\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0\n#define OBD_FAIL_LDLM_BL_CALLBACK_NET\t\t\t0x305\n\tdo_facet client lctl set_param fail_loc=0x80000305\n\tdo_facet client \"$@\" || rc=$?\n\tdo_facet client lctl set_param fail_loc=0\n\tdo_facet client lctl set_param fail_val=0\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1\n\treturn $rc\n}\n\ndrop_bl_callback() {\n\trc=0\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=0\n#define OBD_FAIL_LDLM_BL_CALLBACK_NET\t\t\t0x305\n\tdo_facet client lctl set_param fail_loc=0x305\n\tdo_facet client \"$@\" || rc=$?\n\tdo_facet client lctl set_param fail_loc=0\n\tdo_facet client lctl set_param fail_val=0\n\tdo_facet client lctl set_param ldlm.namespaces.*.early_lock_cancel=1\n\treturn $rc\n}\n\ndrop_mdt_ldlm_reply() {\n#define OBD_FAIL_MDS_LDLM_REPLY_NET\t0x157\n    RC=0\n    local list=$(comma_list $(mdts_nodes))\n    do_nodes $list lctl set_param fail_loc=0x157\n\n    do_facet client \"$@\" || RC=$?\n\n    do_nodes $list lctl set_param fail_loc=0\n    return $RC\n}\n\ndrop_mdt_ldlm_reply_once() {\n#define OBD_FAIL_MDS_LDLM_REPLY_NET\t0x157\n    RC=0\n    local list=$(comma_list $(mdts_nodes))\n    do_nodes $list lctl set_param fail_loc=0x80000157\n\n    do_facet client \"$@\" || RC=$?\n\n    do_nodes $list lctl set_param fail_loc=0\n    return $RC\n}\n\nclear_failloc() {\n    facet=$1\n    pause=$2\n    sleep $pause\n    echo \"clearing fail_loc on $facet\"\n    do_facet $facet \"lctl set_param fail_loc=0 2>/dev/null || true\"\n}\n\nset_nodes_failloc () {\n\tlocal fv=${3:-0}\n\tdo_nodes $(comma_list $1)  lctl set_param fail_val=$fv fail_loc=$2\n}\n\ncancel_lru_locks() {\n\t#$LCTL mark \"cancel_lru_locks $1 start\"\n\t$LCTL set_param -n ldlm.namespaces.*$1*.lru_size=clear\n\t$LCTL get_param ldlm.namespaces.*$1*.lock_unused_count | grep -v '=0'\n\t#$LCTL mark \"cancel_lru_locks $1 stop\"\n}\n\ndefault_lru_size()\n{\n        NR_CPU=$(grep -c \"processor\" /proc/cpuinfo)\n        DEFAULT_LRU_SIZE=$((100 * NR_CPU))\n        echo \"$DEFAULT_LRU_SIZE\"\n}\n\nlru_resize_enable()\n{\n    lctl set_param ldlm.namespaces.*$1*.lru_size=0\n}\n\nlru_resize_disable()\n{\n    lctl set_param ldlm.namespaces.*$1*.lru_size $(default_lru_size)\n}\n\nflock_is_enabled()\n{\n\tlocal mountpath=${1:-$MOUNT}\n\tlocal RC=0\n\n\t[ -z \"$(mount | grep \"$mountpath .*flock\" | grep -v noflock)\" ] && RC=1\n\treturn $RC\n}\n\npgcache_empty() {\n    local FILE\n    for FILE in `lctl get_param -N \"llite.*.dump_page_cache\"`; do\n        if [ `lctl get_param -n $FILE | wc -l` -gt 1 ]; then\n            echo there is still data in page cache $FILE ?\n            lctl get_param -n $FILE\n            return 1\n        fi\n    done\n    return 0\n}\n\ndebugsave() {\n\tDEBUGSAVE=\"$(lctl get_param -n debug)\"\n\tDEBUGSAVE_SERVER=$(do_facet $SINGLEMDS \"$LCTL get_param -n debug\")\n}\n\ndebugrestore() {\n\t[ -n \"$DEBUGSAVE\" ] &&\n\t\tdo_nodes $CLIENTS \"$LCTL set_param debug=\\\\\\\"${DEBUGSAVE}\\\\\\\"\"||\n\t\ttrue\n\tDEBUGSAVE=\"\"\n\n\t[ -n \"$DEBUGSAVE_SERVER\" ] &&\n\t\tdo_nodes $(comma_list $(all_server_nodes)) \\\n\t\t\t \"$LCTL set_param debug=\\\\\\\"${DEBUGSAVE_SERVER}\\\\\\\"\" ||\n\t\t\t true\n\tDEBUGSAVE_SERVER=\"\"\n}\n\ndebug_size_save() {\n    DEBUG_SIZE_SAVED=\"$(lctl get_param -n debug_mb)\"\n}\n\ndebug_size_restore() {\n    [ -n \"$DEBUG_SIZE_SAVED\" ] && \\\n        do_nodes $(comma_list $(nodes_list)) \"$LCTL set_param debug_mb=$DEBUG_SIZE_SAVED\"\n    DEBUG_SIZE_SAVED=\"\"\n}\n\nstart_full_debug_logging() {\n\tdebugsave\n\tdebug_size_save\n\n\tlocal fulldebug=-1\n\tlocal debug_size=150\n\tlocal nodes=$(comma_list $(nodes_list))\n\n\tdo_nodes $nodes \"$LCTL set_param debug=$fulldebug debug_mb=$debug_size\"\n}\n\nstop_full_debug_logging() {\n\tdebug_size_restore\n\tdebugrestore\n}\n\n# prints bash call stack\nprint_stack_trace() {\n\tlocal skip=${1:-1}\n\techo \"  Trace dump:\"\n\tfor (( i=$skip; i < ${#BASH_LINENO[*]} ; i++ )) ; do\n\t\tlocal src=${BASH_SOURCE[$i]}\n\t\tlocal lineno=${BASH_LINENO[$i-1]}\n\t\tlocal funcname=${FUNCNAME[$i]}\n\t\techo \"  = $src:$lineno:$funcname()\"\n\tdone\n}\n\nreport_error() {\n\tlocal TYPE=${TYPE:-\"FAIL\"}\n\n\tlocal dump=true\n\t# do not dump logs if $1=false\n\tif [ \"x$1\" = \"xfalse\" ]; then\n\t\tshift\n\t\tdump=false\n\tfi\n\n\tlog \" ${TESTSUITE} ${TESTNAME}: @@@@@@ ${TYPE}: $@ \"\n\t(print_stack_trace 2) >&2\n\tmkdir -p $LOGDIR\n\t# We need to dump the logs on all nodes\n\tif $dump; then\n\t\tgather_logs $(comma_list $(nodes_list))\n\tfi\n\n\tdebugrestore\n\t[ \"$TESTSUITELOG\" ] &&\n\t\techo \"$TESTSUITE: $TYPE: $TESTNAME $@\" >> $TESTSUITELOG\n\tif [ -z \"$*\" ]; then\n\t\techo \"error() without useful message, please fix\" > $LOGDIR/err\n\telse\n\t\tif [[ `echo $TYPE | grep ^IGNORE` ]]; then\n\t\t\techo \"$@\" > $LOGDIR/ignore\n\t\telse\n\t\t\techo \"$@\" > $LOGDIR/err\n\t\tfi\n\tfi\n\n\t# cleanup the env for failed tests\n\treset_fail_loc\n}\n\n##################################\n# Test interface\n##################################\n\n# usage: stack_trap arg sigspec\n#\n# stack_trap() behaves like bash's built-in trap, except that it \"stacks\" the\n# command \"arg\" on top of previously defined commands for \"sigspec\" instead\n# of overwriting them.\n# stacked traps are executed in reverse order of their registration\n#\n# arg and sigspec have the same meaning as in man (1) trap\nstack_trap()\n{\n\tlocal arg=\"$1\"\n\tlocal sigspec=\"${2:-EXIT}\"\n\n\t# Use \"trap -p\" to get the quoting right\n\tlocal old_trap=\"$(trap -p \"$sigspec\")\"\n\t# Append \";\" and remove the leading \"trap -- '\" added by \"trap -p\"\n\told_trap=\"${old_trap:+\"; ${old_trap#trap -- \\'}\"}\"\n\n\t# Once again, use \"trap -p\" to get the quoting right\n\tlocal new_trap=\"$(trap -- \"$arg\" \"$sigspec\"\n\t\t\t  trap -p \"$sigspec\"\n\t\t\t  trap -- '' \"$sigspec\")\"\n\n\t# Remove the trailing \"' $sigspec\" part added by \"trap -p\" and merge\n\t#\n\t# The resulting string should be safe to \"eval\" as it is (supposedly\n\t# correctly) quoted by \"trap -p\"\n\teval \"${new_trap%\\' $sigspec}${old_trap:-\"' $sigspec\"}\"\n}\n\nerror_noexit() {\n\treport_error \"$@\"\n}\n\nexit_status () {\n\tlocal status=0\n\tlocal logs=\"$TESTSUITELOG $1\"\n\n\tfor log in $logs; do\n\t\tif [ -f \"$log\" ]; then\n\t\t\tgrep -qw FAIL $log && status=1\n\t\tfi\n\tdone\n\n\texit $status\n}\n\nerror() {\n\treport_error \"$@\"\n\texit 1\n}\n\nerror_exit() {\n\treport_error \"$@\"\n\texit 1\n}\n\n# use only if we are ignoring failures for this test, bugno required.\n# (like ALWAYS_EXCEPT, but run the test and ignore the results.)\n# e.g. error_ignore bz5494 \"your message\" or\n# error_ignore LU-5494 \"your message\"\nerror_ignore() {\n\tlocal TYPE=\"IGNORE ($1)\"\n\tshift\n\treport_error \"$@\"\n}\n\nerror_and_remount() {\n\treport_error \"$@\"\n\tremount_client $MOUNT\n\texit 1\n}\n\n# Throw an error if it's not running in vm - usually for performance\n# verification\nerror_not_in_vm() {\n\tlocal virt=$(running_in_vm)\n\tif [[ -n \"$virt\" ]]; then\n\t\techo \"running in VM '$virt', ignore error\"\n\t\terror_ignore env=$virt \"$@\"\n\telse\n\t\terror \"$@\"\n\tfi\n}\n\n#\n# Function: skip_env()\n# Purpose:  to skip a test during developer testing because some tool\n#           is missing, but fail the test in release testing because the test\n#           environment is not configured properly\".\n#\nskip_env () {\n\t$FAIL_ON_SKIP_ENV && error false $@ || skip $@\n}\n\nskip_noexit() {\n\techo\n\tlog \" SKIP: $TESTSUITE $TESTNAME $@\"\n\n\tif [[ -n \"$ALWAYS_SKIPPED\" ]]; then\n\t\tskip_logged $TESTNAME \"$@\"\n\telse\n\t\tmkdir -p $LOGDIR\n\t\techo \"$@\" > $LOGDIR/skip\n\tfi\n\n\t[[ -n \"$TESTSUITELOG\" ]] &&\n\t\techo \"$TESTSUITE: SKIP: $TESTNAME $@\" >> $TESTSUITELOG || true\n\tunset TESTNAME\n}\n\nskip() {\n\tskip_noexit $@\n\texit 0\n}\n\nbuild_test_filter() {\n\tEXCEPT=\"$EXCEPT $(testslist_filter)\"\n\n\tfor O in $ONLY; do\n\t\tif [[ $O = [0-9]*-[0-9]* ]]; then\n\t\t\tfor num in $(seq $(echo $O | tr '-' ' ')); do\n\t\t\t\teval ONLY_$num=true\n\t\t\tdone\n\t\telse\n\t\t\teval ONLY_${O}=true\n\t\tfi\n\tdone\n\n\t[ \"$EXCEPT$ALWAYS_EXCEPT\" ] &&\n\t\tlog \"excepting tests: `echo $EXCEPT $ALWAYS_EXCEPT`\"\n\t[ \"$EXCEPT_SLOW\" ] &&\n\t\tlog \"skipping tests SLOW=no: `echo $EXCEPT_SLOW`\"\n\tfor E in $EXCEPT; do\n\t\teval EXCEPT_${E}=true\n\tdone\n\tfor E in $ALWAYS_EXCEPT; do\n\t\teval EXCEPT_ALWAYS_${E}=true\n\tdone\n\tfor E in $EXCEPT_SLOW; do\n\t\teval EXCEPT_SLOW_${E}=true\n\tdone\n\tfor G in $GRANT_CHECK_LIST; do\n\t\teval GCHECK_ONLY_${G}=true\n\tdone\n}\n\nbasetest() {\n    if [[ $1 = [a-z]* ]]; then\n        echo $1\n    else\n\techo ${1%%[a-zA-Z]*}\n    fi\n}\n\n# print a newline if the last test was skipped\nexport LAST_SKIPPED=\nexport ALWAYS_SKIPPED=\n#\n# Main entry into test-framework. This is called with the number and\n# description of a test. The number is used to find the function to run\n# the test using \"test_$name\".\n#\n# This supports a variety of methods of specifying specific test to\n# run or not run:\n# - ONLY= env variable with space-separated list of test numbers to run\n# - EXCEPT= env variable with space-separated list of test numbers to exclude\n#\nrun_test() {\n\tassert_DIR\n\tlocal testnum=$1\n\tlocal testmsg=$2\n\texport base=$(basetest $testnum)\n\texport TESTNAME=test_$testnum\n\tLAST_SKIPPED=\n\tALWAYS_SKIPPED=\n\n\t# Check the EXCEPT, ALWAYS_EXCEPT and SLOW lists to see if we\n\t# need to skip the current test. If so, set the ALWAYS_SKIPPED flag.\n\tlocal isexcept=EXCEPT_$testnum\n\tlocal isexcept_base=EXCEPT_$base\n\tif [ ${!isexcept}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping excluded test $testnum\"\n\telif [ ${!isexcept_base}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping excluded test $testnum (base $base)\"\n\tfi\n\n\tisexcept=EXCEPT_ALWAYS_$testnum\n\tisexcept_base=EXCEPT_ALWAYS_$base\n\tif [ ${!isexcept}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping ALWAYS excluded test $testnum\"\n\telif [ ${!isexcept_base}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping ALWAYS excluded test $testnum (base $base)\"\n\tfi\n\n\tisexcept=EXCEPT_SLOW_$testnum\n\tisexcept_base=EXCEPT_SLOW_$base\n\tif [ ${!isexcept}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping SLOW test $testnum\"\n\telif [ ${!isexcept_base}x != x ]; then\n\t\tALWAYS_SKIPPED=\"y\"\n\t\tskip_message=\"skipping SLOW test $testnum (base $base)\"\n\tfi\n\n\t# If there are tests on the ONLY list, check if the current test\n\t# is on that list and, if so, check if the test is to be skipped\n\t# and if we are supposed to honor the skip lists.\n\tif [ -n \"$ONLY\" ]; then\n\t\tlocal isonly=ONLY_$testnum\n\t\tlocal isonly_base=ONLY_$base\n\t\tif [[ ${!isonly}x != x || ${!isonly_base}x != x ]]; then\n\n\t\t\tif [[ -n \"$ALWAYS_SKIPPED\" && -n \"$HONOR_EXCEPT\" ]]; then\n\t\t\t\tLAST_SKIPPED=\"y\"\n\t\t\t\tskip_noexit \"$skip_message\"\n\t\t\t\treturn 0\n\t\t\telse\n\t\t\t\t[ -n \"$LAST_SKIPPED\" ] &&\n\t\t\t\t\techo \"\" && LAST_SKIPPED=\n\t\t\t\tALWAYS_SKIPPED=\n\t\t\t\trun_one_logged $testnum \"$testmsg\"\n\t\t\t\treturn $?\n\t\t\tfi\n\n\t\telse\n\t\t\tLAST_SKIPPED=\"y\"\n\t\t\treturn 0\n\t\tfi\n\tfi\n\n\tif [ -n \"$ALWAYS_SKIPPED\" ]; then\n\t\tLAST_SKIPPED=\"y\"\n\t\tskip_noexit \"$skip_message\"\n\t\treturn 0\n\telse\n\t\trun_one_logged $testnum \"$testmsg\"\n\t\treturn $?\n\tfi\n}\n\nlog() {\n\techo \"$*\" >&2\n\tload_module ../libcfs/libcfs/libcfs\n\n    local MSG=\"$*\"\n    # Get rid of '\n    MSG=${MSG//\\'/\\\\\\'}\n    MSG=${MSG//\\(/\\\\\\(}\n    MSG=${MSG//\\)/\\\\\\)}\n    MSG=${MSG//\\;/\\\\\\;}\n    MSG=${MSG//\\|/\\\\\\|}\n    MSG=${MSG//\\>/\\\\\\>}\n    MSG=${MSG//\\</\\\\\\<}\n    MSG=${MSG//\\//\\\\\\/}\n    do_nodes $(comma_list $(nodes_list)) $LCTL mark \"$MSG\" 2> /dev/null || true\n}\n\ntrace() {\n        log \"STARTING: $*\"\n        strace -o $TMP/$1.strace -ttt $*\n        RC=$?\n        log \"FINISHED: $*: rc $RC\"\n        return 1\n}\n\ncomplete () {\n    local duration=$1\n\n    banner test complete, duration $duration sec\n    [ -f \"$TESTSUITELOG\" ] && egrep .FAIL $TESTSUITELOG || true\n    echo duration $duration >>$TESTSUITELOG\n}\n\npass() {\n\t# Set TEST_STATUS here. It will be used for logging the result.\n\tTEST_STATUS=\"PASS\"\n\n\tif [[ -f $LOGDIR/err ]]; then\n\t\tTEST_STATUS=\"FAIL\"\n\telif [[ -f $LOGDIR/skip ]]; then\n\t\tTEST_STATUS=\"SKIP\"\n\tfi\n\techo \"$TEST_STATUS $@\" 2>&1 | tee -a $TESTSUITELOG\n}\n\ncheck_mds() {\n    local FFREE=$(do_node $SINGLEMDS \\\n        lctl get_param -n osd*.*MDT*.filesfree | calc_sum)\n    local FTOTAL=$(do_node $SINGLEMDS \\\n        lctl get_param -n osd*.*MDT*.filestotal | calc_sum)\n\n    [ $FFREE -ge $FTOTAL ] && error \"files free $FFREE > total $FTOTAL\" || true\n}\n\nreset_fail_loc () {\n\techo -n \"Resetting fail_loc on all nodes...\"\n\tdo_nodes $(comma_list $(nodes_list)) \"lctl set_param -n fail_loc=0 \\\n\t    fail_val=0 2>/dev/null\" || true\n\techo done.\n}\n\n\n#\n# Log a message (on all nodes) padded with \"=\" before and after.\n# Also appends a timestamp and prepends the testsuite name.\n#\n\nEQUALS=\"====================================================================================================\"\nbanner() {\n    msg=\"== ${TESTSUITE} $*\"\n    last=${msg: -1:1}\n    [[ $last != \"=\" && $last != \" \" ]] && msg=\"$msg \"\n    msg=$(printf '%s%.*s'  \"$msg\"  $((${#EQUALS} - ${#msg})) $EQUALS )\n    # always include at least == after the message\n    log \"$msg== $(date +\"%H:%M:%S (%s)\")\"\n}\n\ncheck_dmesg_for_errors() {\n\tlocal res\n\tlocal errors=\"VFS: Busy inodes after unmount of\\|\\\nldiskfs_check_descriptors: Checksum for group 0 failed\\|\\\ngroup descriptors corrupted\"\n\n\tres=$(do_nodes $(comma_list $(nodes_list)) \"dmesg\" | grep \"$errors\")\n\t[ -z \"$res\" ] && return 0\n\techo \"Kernel error detected: $res\"\n\treturn 1\n}\n\n#\n# Run a single test function and cleanup after it.\n#\n# This function should be run in a subshell so the test func can\n# exit() without stopping the whole script.\n#\nrun_one() {\n\tlocal testnum=$1\n\tlocal testmsg=\"$2\"\n\tlocal SAVE_UMASK=`umask`\n\tumask 0022\n\n\tif ! grep -q $DIR /proc/mounts; then\n\t\t$SETUP\n\tfi\n\n\tbanner \"test $testnum: $testmsg\"\n\ttest_${testnum} || error \"test_$testnum failed with $?\"\n\tcd $SAVE_PWD\n\treset_fail_loc\n\tcheck_grant ${testnum} || error \"check_grant $testnum failed with $?\"\n\tcheck_node_health\n\tcheck_dmesg_for_errors || error \"Error in dmesg detected\"\n\tif [ \"$PARALLEL\" != \"yes\" ]; then\n\t\tps auxww | grep -v grep | grep -q \"multiop \" &&\n\t\t\t\t\terror \"multiop still running\"\n\tfi\n\tumask $SAVE_UMASK\n\t$CLEANUP\n\treturn 0\n}\n\n#\n# Wrapper around run_one to ensure:\n#  - test runs in subshell\n#  - output of test is saved to separate log file for error reporting\n#  - test result is saved to data file\n#\nrun_one_logged() {\n\tlocal before=$SECONDS\n\tlocal testnum=$1\n\tlocal testmsg=$2\n\texport tfile=f${testnum}.${TESTSUITE}\n\texport tdir=d${testnum}.${TESTSUITE}\n\tlocal test_log=$TESTLOG_PREFIX.$TESTNAME.test_log.$(hostname -s).log\n\tlocal zfs_debug_log=$TESTLOG_PREFIX.$TESTNAME.zfs_log\n\tlocal SAVE_UMASK=$(umask)\n\tlocal rc=0\n\tumask 0022\n\n\trm -f $LOGDIR/err $LOGDIR/ignore $LOGDIR/skip\n\techo\n\t# if ${ONLY_$testnum} set, repeat $ONLY_REPEAT times, otherwise once\n\tlocal isonly=ONLY_$testnum\n\tlocal repeat=${!isonly:+$ONLY_REPEAT}\n\n\tfor testiter in $(seq ${repeat:-1}); do\n\t\tlocal before_sub=$SECONDS\n\t\tlog_sub_test_begin $TESTNAME\n\n\t\t# remove temp files between repetitions to avoid test failures\n\t\t[ -n \"$append\" -a -n \"$DIR\" -a -n \"$tdir\" -a -n \"$tfile\" ] &&\n\t\t\trm -rf $DIR/$tdir* $DIR/$tfile*\n\t\t# loop around subshell so stack_trap EXIT triggers each time\n\t\t(run_one $testnum \"$testmsg\") 2>&1 | tee -i $append $test_log\n\t\trc=${PIPESTATUS[0]}\n\t\tlocal append=-a\n\t\tlocal duration_sub=$((SECONDS - before_sub))\n\t\tlocal test_error\n\n\t\t[[ $rc != 0 && ! -f $LOGDIR/err ]] &&\n\t\t\techo \"$TESTNAME returned $rc\" | tee $LOGDIR/err\n\n\t\tif [[ -f $LOGDIR/err ]]; then\n\t\t\ttest_error=$(cat $LOGDIR/err)\n\t\t\tTEST_STATUS=\"FAIL\"\n\t\telif [[ -f $LOGDIR/ignore ]]; then\n\t\t\ttest_error=$(cat $LOGDIR/ignore)\n\t\telif [[ -f $LOGDIR/skip ]]; then\n\t\t\ttest_error=$(cat $LOGDIR/skip)\n\t\t\tTEST_STATUS=\"SKIP\"\n\t\telse\n\t\t\tTEST_STATUS=\"PASS\"\n\t\tfi\n\n\t\tpass \"$testnum\" \"(${duration_sub}s)\"\n\t\tlog_sub_test_end $TEST_STATUS $duration_sub \"$rc\" \"$test_error\"\n\t\t[[ $rc != 0 ]] && break\n\tdone\n\n\tif [[ \"$TEST_STATUS\" != \"SKIP\" && -f $TF_SKIP ]]; then\n\t\trm -f $TF_SKIP\n\tfi\n\n\tif [ -f $LOGDIR/err ]; then\n\t\tlog_zfs_info \"$zfs_debug_log\"\n\t\t$FAIL_ON_ERROR && exit $rc\n\tfi\n\n\tumask $SAVE_UMASK\n\n\tunset TESTNAME\n\tunset tdir\n\tunset tfile\n\n\treturn 0\n}\n\n#\n# Print information of skipped tests to result.yml\n#\nskip_logged(){\n\tlog_sub_test_begin $1\n\tshift\n\tlog_sub_test_end \"SKIP\" \"0\" \"0\" \"$@\"\n}\n\ncanonical_path() {\n\t(cd $(dirname $1); echo $PWD/$(basename $1))\n}\n\ngrant_from_clients() {\n\tlocal nodes=\"$1\"\n\n\t# get client grant\n\tdo_nodes $nodes \"$LCTL get_param -n osc.${FSNAME}-*.cur_*grant_bytes\" |\n\t\tcalc_sum\n}\n\ngrant_from_servers() {\n\tlocal nodes=\"$1\"\n\n\t# get server grant\n\t# which is tot_granted less grant_precreate\n\tdo_nodes $nodes \"$LCTL get_param obdfilter.${FSNAME}-OST*.tot_granted\" \\\n\t\t\" obdfilter.${FSNAME}-OST*.tot_pending\" \\\n\t\t\" obdfilter.${FSNAME}-OST*.grant_precreate\" |\n\t\ttr '=' ' ' | awk '/tot_granted/{ total += $2 };\n\t\t\t\t  /tot_pending/{ total -= $2 };\n\t\t\t\t  /grant_precreate/{ total -= $2 };\n\t\t\t\t  END { printf(\"%0.0f\", total) }'\n}\n\ncheck_grant() {\n\texport base=$(basetest $1)\n\t[ \"$CHECK_GRANT\" == \"no\" ] && return 0\n\n\tlocal isonly_base=GCHECK_ONLY_${base}\n\tlocal isonly=GCHECK_ONLY_$1\n\t[ ${!isonly_base}x == x -a ${!isonly}x == x ] && return 0\n\n\techo -n \"checking grant......\"\n\n\tlocal osts=$(comma_list $(osts_nodes))\n\tlocal clients=$CLIENTS\n\t[ -z \"$clients\" ] && clients=$(hostname)\n\n\t# sync all the data and make sure no pending data on server\n\tdo_nodes $clients sync\n\tclients_up # initiate all idling connections\n\n\t# get client grant\n\tcli_grant=$(grant_from_clients $clients)\n\n\t# get server grant\n\t# which is tot_granted less grant_precreate\n\tsrv_grant=$(grant_from_servers $osts)\n\n\tcount=0\n\t# check whether client grant == server grant\n\twhile [[ $cli_grant != $srv_grant && count++ -lt 30 ]]; do\n\t\techo \"wait for client:$cli_grant == server:$srv_grant\"\n\t\tsleep 1\n\t\tcli_grant=$(grant_from_clients $clients)\n\t\tsrv_grant=$(grant_from_servers $osts)\n\tdone\n\tif [[ $cli_grant -ne $srv_grant ]]; then\n\t\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t\t\t\"$LCTL get_param obdfilter.${FSNAME}-OST*.tot*\" \\\n\t\t\t\"obdfilter.${FSNAME}-OST*.grant_*\"\n\t\tdo_nodes $clients \"$LCTL get_param osc.${FSNAME}-*.cur_*_bytes\"\n\t\terror \"failed grant check: client:$cli_grant server:$srv_grant\"\n\telse\n\t\techo \"pass grant check: client:$cli_grant server:$srv_grant\"\n\tfi\n}\n\n########################\n# helper functions\n\nosc_to_ost()\n{\n    osc=$1\n    ost=`echo $1 | awk -F_ '{print $3}'`\n    if [ -z $ost ]; then\n        ost=`echo $1 | sed 's/-osc.*//'`\n    fi\n    echo $ost\n}\n\nostuuid_from_index()\n{\n    $LFS osts $2 | sed -ne \"/^$1: /s/.* \\(.*\\) .*$/\\1/p\"\n}\n\nostname_from_index() {\n    local uuid=$(ostuuid_from_index $1)\n    echo ${uuid/_UUID/}\n}\n\nmdtname_from_index() {\n\tlocal uuid=$(mdtuuid_from_index $1)\n\techo ${uuid/_UUID/}\n}\n\nmdssize_from_index () {\n\tlocal mdt=$(mdtname_from_index $2)\n\t$LFS df $1 | grep $mdt | awk '{ print $2 }'\n}\n\nindex_from_ostuuid()\n{\n    $LFS osts $2 | sed -ne \"/${1}/s/\\(.*\\): .* .*$/\\1/p\"\n}\n\nmdtuuid_from_index()\n{\n    $LFS mdts $2 | sed -ne \"/^$1: /s/.* \\(.*\\) .*$/\\1/p\"\n}\n\n# Description:\n#   Return unique identifier for given hostname\nhost_id() {\n\tlocal host_name=$1\n\techo $host_name | md5sum | cut -d' ' -f1\n}\n\n# Description:\n#   Returns list of ip addresses for each interface\nlocal_addr_list() {\n\tip addr | awk '/inet\\ / {print $2}' | awk -F\\/ '{print $1}'\n}\n\nis_local_addr() {\n\tlocal addr=$1\n\t# Cache address list to avoid mutiple execution of local_addr_list\n\tLOCAL_ADDR_LIST=${LOCAL_ADDR_LIST:-$(local_addr_list)}\n\tlocal i\n\tfor i in $LOCAL_ADDR_LIST ; do\n\t\t[[ \"$i\" == \"$addr\" ]] && return 0\n\tdone\n\treturn 1\n}\n\nlocal_node() {\n\tlocal host_name=$1\n\tlocal is_local=\"IS_LOCAL_$(host_id $host_name)\"\n\tif [ -z \"${!is_local-}\" ] ; then\n\t\teval $is_local=0\n\t\tlocal host_ip=$($LUSTRE/tests/resolveip $host_name)\n\t\tis_local_addr \"$host_ip\" && eval $is_local=1\n\tfi\n\t[[ \"${!is_local}\" == \"1\" ]]\n}\n\nremote_node () {\n\tlocal node=$1\n\tlocal_node $node && return 1\n\treturn 0\n}\n\nremote_mds ()\n{\n    local node\n    for node in $(mdts_nodes); do\n        remote_node $node && return 0\n    done\n    return 1\n}\n\nremote_mds_nodsh()\n{\n\t[ -n \"$CLIENTONLY\" ] && return 0 || true\n\tremote_mds && [ \"$PDSH\" = \"no_dsh\" -o -z \"$PDSH\" -o -z \"$mds_HOST\" ]\n}\n\nrequire_dsh_mds()\n{\n\tremote_mds_nodsh && echo \"SKIP: $TESTSUITE: remote MDS with nodsh\" &&\n\t\tMSKIPPED=1 && return 1\n\treturn 0\n}\n\nremote_ost ()\n{\n    local node\n    for node in $(osts_nodes) ; do\n        remote_node $node && return 0\n    done\n    return 1\n}\n\nremote_ost_nodsh()\n{\n\t[ -n \"$CLIENTONLY\" ] && return 0 || true\n\tremote_ost && [ \"$PDSH\" = \"no_dsh\" -o -z \"$PDSH\" -o -z \"$ost_HOST\" ]\n}\n\nrequire_dsh_ost()\n{\n        remote_ost_nodsh && echo \"SKIP: $TESTSUITE: remote OST with nodsh\" && \\\n            OSKIPPED=1 && return 1\n        return 0\n}\n\nremote_mgs_nodsh()\n{\n\t[ -n \"$CLIENTONLY\" ] && return 0 || true\n\tlocal MGS\n\tMGS=$(facet_host mgs)\n\tremote_node $MGS && [ \"$PDSH\" = \"no_dsh\" -o -z \"$PDSH\" -o -z \"$ost_HOST\" ]\n}\n\nlocal_mode ()\n{\n    remote_mds_nodsh || remote_ost_nodsh || \\\n        $(single_local_node $(comma_list $(nodes_list)))\n}\n\nremote_servers () {\n    remote_ost && remote_mds\n}\n\n# Get the active nodes for facets.\nfacets_nodes () {\n\tlocal facets=$1\n\tlocal facet\n\tlocal nodes\n\tlocal nodes_sort\n\tlocal i\n\n\tfor facet in ${facets//,/ }; do\n\t\tnodes=\"$nodes $(facet_active_host $facet)\"\n\tdone\n\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\n# Get name of the active MGS node.\nmgs_node () {\n\techo -n $(facets_nodes $(get_facets MGS))\n}\n\n# Get all of the active MDS nodes.\nmdts_nodes () {\n\techo -n $(facets_nodes $(get_facets MDS))\n}\n\n# Get all of the active OSS nodes.\nosts_nodes () {\n\techo -n $(facets_nodes $(get_facets OST))\n}\n\n# Get all of the active AGT (HSM agent) nodes.\nagts_nodes () {\n\techo -n $(facets_nodes $(get_facets AGT))\n}\n\n# Get all of the client nodes and active server nodes.\nnodes_list () {\n\tlocal nodes=$HOSTNAME\n\tlocal nodes_sort\n\tlocal i\n\n\t# CLIENTS (if specified) contains the local client\n\t[ -n \"$CLIENTS\" ] && nodes=${CLIENTS//,/ }\n\n\tif [ \"$PDSH\" -a \"$PDSH\" != \"no_dsh\" ]; then\n\t\tnodes=\"$nodes $(facets_nodes $(get_facets))\"\n\tfi\n\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\n# Get all of the remote client nodes and remote active server nodes.\nremote_nodes_list () {\n\techo -n $(nodes_list) | sed -re \"s/\\<$HOSTNAME\\>//g\"\n}\n\n# Get all of the MDS nodes, including active and passive nodes.\nall_mdts_nodes () {\n\tlocal host\n\tlocal failover_host\n\tlocal nodes\n\tlocal nodes_sort\n\tlocal i\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\thost=mds${i}_HOST\n\t\tfailover_host=mds${i}failover_HOST\n\t\tnodes=\"$nodes ${!host} ${!failover_host}\"\n\tdone\n\n\t[ -n \"$nodes\" ] || nodes=\"${mds_HOST} ${mdsfailover_HOST}\"\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\n# Get all of the OSS nodes, including active and passive nodes.\nall_osts_nodes () {\n\tlocal host\n\tlocal failover_host\n\tlocal nodes=\n\tlocal nodes_sort\n\tlocal i\n\n\tfor i in $(seq $OSTCOUNT); do\n\t\thost=ost${i}_HOST\n\t\tfailover_host=ost${i}failover_HOST\n\t\tnodes=\"$nodes ${!host} ${!failover_host}\"\n\tdone\n\n\t[ -n \"$nodes\" ] || nodes=\"${ost_HOST} ${ostfailover_HOST}\"\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\n# Get all of the server nodes, including active and passive nodes.\nall_server_nodes () {\n\tlocal nodes\n\tlocal nodes_sort\n\tlocal i\n\n\tnodes=\"$mgs_HOST $mgsfailover_HOST $(all_mdts_nodes) $(all_osts_nodes)\"\n\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\n# Get all of the client and server nodes, including active and passive nodes.\nall_nodes () {\n\tlocal nodes=$HOSTNAME\n\tlocal nodes_sort\n\tlocal i\n\n\t# CLIENTS (if specified) contains the local client\n\t[ -n \"$CLIENTS\" ] && nodes=${CLIENTS//,/ }\n\n\tif [ \"$PDSH\" -a \"$PDSH\" != \"no_dsh\" ]; then\n\t\tnodes=\"$nodes $(all_server_nodes)\"\n\tfi\n\n\tnodes_sort=$(for i in $nodes; do echo $i; done | sort -u)\n\techo -n $nodes_sort\n}\n\ninit_clients_lists () {\n    # Sanity check: exclude the local client from RCLIENTS\n    local clients=$(hostlist_expand \"$RCLIENTS\")\n    local rclients=$(exclude_items_from_list \"$clients\" $HOSTNAME)\n\n    # Sanity check: exclude the dup entries\n    RCLIENTS=$(for i in ${rclients//,/ }; do echo $i; done | sort -u)\n\n    clients=\"$SINGLECLIENT $HOSTNAME $RCLIENTS\"\n\n    # Sanity check: exclude the dup entries from CLIENTS\n    # for those configs which has SINGLCLIENT set to local client\n    clients=$(for i in $clients; do echo $i; done | sort -u)\n\n    CLIENTS=$(comma_list $clients)\n    local -a remoteclients=($RCLIENTS)\n    for ((i=0; $i<${#remoteclients[@]}; i++)); do\n            varname=CLIENT$((i + 2))\n            eval $varname=${remoteclients[i]}\n    done\n\n    CLIENTCOUNT=$((${#remoteclients[@]} + 1))\n}\n\nget_random_entry () {\n    local rnodes=$1\n\n    rnodes=${rnodes//,/ }\n\n    local -a nodes=($rnodes)\n    local num=${#nodes[@]}\n    local i=$((RANDOM * num * 2 / 65536))\n\n    echo ${nodes[i]}\n}\n\nclient_only () {\n\t[ -n \"$CLIENTONLY\" ] || [ \"x$CLIENTMODSONLY\" = \"xyes\" ]\n}\n\ncheck_versions () {\n    [ \"$(lustre_version_code client)\" = \"$(lustre_version_code $SINGLEMDS)\" -a \\\n      \"$(lustre_version_code client)\" = \"$(lustre_version_code ost1)\" ]\n}\n\nget_node_count() {\n    local nodes=\"$@\"\n    echo $nodes | wc -w || true\n}\n\nmixed_ost_devs () {\n    local nodes=$(osts_nodes)\n    local osscount=$(get_node_count \"$nodes\")\n    [ ! \"$OSTCOUNT\" = \"$osscount\" ]\n}\n\nmixed_mdt_devs () {\n    local nodes=$(mdts_nodes)\n    local mdtcount=$(get_node_count \"$nodes\")\n    [ ! \"$MDSCOUNT\" = \"$mdtcount\" ]\n}\n\ngenerate_machine_file() {\n    local nodes=${1//,/ }\n    local machinefile=$2\n    rm -f $machinefile\n    for node in $nodes; do\n        echo $node >>$machinefile || \\\n            { echo \"can not generate machinefile $machinefile\" && return 1; }\n    done\n}\n\nget_stripe () {\n\tlocal file=$1/stripe\n\n\ttouch $file\n\t$LFS getstripe -v $file || error \"getstripe $file failed\"\n\trm -f $file\n}\n\nsetstripe_nfsserver () {\n\tlocal dir=$1\n\tlocal nfsexportdir=$2\n\tshift\n\tshift\n\n\tlocal -a nfsexport=($(awk '\"'$dir'\" ~ $2 && $3 ~ \"nfs\" && $2 != \"/\" \\\n\t\t{ print $1 }' /proc/mounts | cut -f 1 -d :))\n\n\t# check that only one nfs mounted\n\t[[ -z $nfsexport ]] && echo \"$dir is not nfs mounted\" && return 1\n\t(( ${#nfsexport[@]} == 1 )) ||\n\t\terror \"several nfs mounts found for $dir: ${nfsexport[@]} !\"\n\n\tdo_nodev ${nfsexport[0]} lfs setstripe $nfsexportdir \"$@\"\n}\n\n# Check and add a test group.\nadd_group() {\n\tlocal group_id=$1\n\tlocal group_name=$2\n\tlocal rc=0\n\n\tlocal gid=$(getent group $group_name | cut -d: -f3)\n\tif [[ -n \"$gid\" ]]; then\n\t\t[[ \"$gid\" -eq \"$group_id\" ]] || {\n\t\t\terror_noexit \"inconsistent group ID:\" \\\n\t\t\t\t     \"new: $group_id, old: $gid\"\n\t\t\trc=1\n\t\t}\n\telse\n\t\tgroupadd -g $group_id $group_name\n\t\trc=${PIPESTATUS[0]}\n\tfi\n\n\treturn $rc\n}\n\n# Check and add a test user.\nadd_user() {\n\tlocal user_id=$1\n\tshift\n\tlocal user_name=$1\n\tshift\n\tlocal group_name=$1\n\tshift\n\tlocal home=$1\n\tshift\n\tlocal opts=\"$@\"\n\tlocal rc=0\n\n\tlocal uid=$(getent passwd $user_name | cut -d: -f3)\n\tif [[ -n \"$uid\" ]]; then\n\t\tif [[ \"$uid\" -eq \"$user_id\" ]]; then\n\t\t\tlocal dir=$(getent passwd $user_name | cut -d: -f6)\n\t\t\tif [[ \"$dir\" != \"$home\" ]]; then\n\t\t\t\tmkdir -p $home\n\t\t\t\tusermod -d $home $user_name\n\t\t\t\trc=${PIPESTATUS[0]}\n\t\t\tfi\n\t\telse\n\t\t\terror_noexit \"inconsistent user ID:\" \\\n\t\t\t\t     \"new: $user_id, old: $uid\"\n\t\t\trc=1\n\t\tfi\n\telse\n\t\tmkdir -p $home\n\t\tuseradd -M -u $user_id -d $home -g $group_name $opts $user_name\n\t\trc=${PIPESTATUS[0]}\n\tfi\n\n\treturn $rc\n}\n\ncheck_runas_id_ret() {\n    local myRC=0\n    local myRUNAS_UID=$1\n    local myRUNAS_GID=$2\n    shift 2\n    local myRUNAS=$@\n    if [ -z \"$myRUNAS\" ]; then\n        error_exit \"myRUNAS command must be specified for check_runas_id\"\n    fi\n    if $GSS_KRB5; then\n        $myRUNAS krb5_login.sh || \\\n            error \"Failed to refresh Kerberos V5 TGT for UID $myRUNAS_ID.\"\n    fi\n    mkdir $DIR/d0_runas_test\n    chmod 0755 $DIR\n    chown $myRUNAS_UID:$myRUNAS_GID $DIR/d0_runas_test\n    $myRUNAS touch $DIR/d0_runas_test/f$$ || myRC=$?\n    rm -rf $DIR/d0_runas_test\n    return $myRC\n}\n\ncheck_runas_id() {\n    local myRUNAS_UID=$1\n    local myRUNAS_GID=$2\n    shift 2\n    local myRUNAS=$@\n    check_runas_id_ret $myRUNAS_UID $myRUNAS_GID $myRUNAS || \\\n        error \"unable to write to $DIR/d0_runas_test as UID $myRUNAS_UID.\n        Please set RUNAS_ID to some UID which exists on MDS and client or\n        add user $myRUNAS_UID:$myRUNAS_GID on these nodes.\"\n}\n\n# obtain the UID/GID for MPI_USER\nget_mpiuser_id() {\n    local mpi_user=$1\n\n    MPI_USER_UID=$(do_facet client \"getent passwd $mpi_user | cut -d: -f3;\nexit \\\\\\${PIPESTATUS[0]}\") || error_exit \"failed to get the UID for $mpi_user\"\n\n    MPI_USER_GID=$(do_facet client \"getent passwd $mpi_user | cut -d: -f4;\nexit \\\\\\${PIPESTATUS[0]}\") || error_exit \"failed to get the GID for $mpi_user\"\n}\n\n# obtain and cache Kerberos ticket-granting ticket\nrefresh_krb5_tgt() {\n    local myRUNAS_UID=$1\n    local myRUNAS_GID=$2\n    shift 2\n    local myRUNAS=$@\n    if [ -z \"$myRUNAS\" ]; then\n        error_exit \"myRUNAS command must be specified for refresh_krb5_tgt\"\n    fi\n\n    CLIENTS=${CLIENTS:-$HOSTNAME}\n    do_nodes $CLIENTS \"set -x\nif ! $myRUNAS krb5_login.sh; then\n    echo \"Failed to refresh Krb5 TGT for UID/GID $myRUNAS_UID/$myRUNAS_GID.\"\n    exit 1\nfi\"\n}\n\n# Run multiop in the background, but wait for it to print\n# \"PAUSING\" to its stdout before returning from this function.\nmultiop_bg_pause() {\n    MULTIOP_PROG=${MULTIOP_PROG:-$MULTIOP}\n    FILE=$1\n    ARGS=$2\n\n    TMPPIPE=/tmp/multiop_open_wait_pipe.$$\n    mkfifo $TMPPIPE\n\n    echo \"$MULTIOP_PROG $FILE v$ARGS\"\n    $MULTIOP_PROG $FILE v$ARGS > $TMPPIPE &\n\n    echo \"TMPPIPE=${TMPPIPE}\"\n    read -t 60 multiop_output < $TMPPIPE\n    if [ $? -ne 0 ]; then\n        rm -f $TMPPIPE\n        return 1\n    fi\n    rm -f $TMPPIPE\n    if [ \"$multiop_output\" != \"PAUSING\" ]; then\n        echo \"Incorrect multiop output: $multiop_output\"\n        kill -9 $PID\n        return 1\n    fi\n\n    return 0\n}\n\ndo_and_time () {\n\tlocal cmd=\"$1\"\n\tlocal start\n\tlocal rc\n\n\tstart=$SECONDS\n\teval '$cmd'\n\t[ ${PIPESTATUS[0]} -eq 0 ] || rc=1\n\n\techo $((SECONDS - start))\n\treturn $rc\n}\n\ninodes_available () {\n\tlocal IFree=$($LFS df -i $MOUNT | grep ^$FSNAME | awk '{ print $4 }' |\n\t\tsort -un | head -n1) || return 1\n\techo $((IFree))\n}\n\nmdsrate_inodes_available () {\n\tlocal min_inodes=$(inodes_available)\n\techo $((min_inodes * 99 / 100))\n}\n\n# reset stat counters\nclear_stats() {\n\tlocal paramfile=\"$1\"\n\tlctl set_param -n $paramfile=0\n}\n\n# sum stat items\ncalc_stats() {\n\tlocal paramfile=\"$1\"\n\tlocal stat=\"$2\"\n\tlctl get_param -n $paramfile |\n\t\tawk '/^'$stat'/ { sum += $2 } END { printf(\"%0.0f\", sum) }'\n}\n\ncalc_sum () {\n\tawk '{sum += $1} END { printf(\"%0.0f\", sum) }'\n}\n\ncalc_osc_kbytes () {\n\t$LFS df $MOUNT > /dev/null\n\t$LCTL get_param -n osc.*[oO][sS][cC][-_][0-9a-f]*.$1 | calc_sum\n}\n\n# save_lustre_params(comma separated facet list, parameter_mask)\n# generate a stream of formatted strings (<facet> <param name>=<param value>)\nsave_lustre_params() {\n\tlocal facets=$1\n\tlocal facet\n\tlocal facet_svc\n\n\tfor facet in ${facets//,/ }; do\n\t\tfacet_svc=$(facet_svc $facet)\n\t\tdo_facet $facet \\\n\t\t\t\"params=\\\\\\$($LCTL get_param $2);\n\t\t\t [[ -z \\\\\\\"$facet_svc\\\\\\\" ]] && param= ||\n\t\t\t param=\\\\\\$(grep $facet_svc <<< \\\\\\\"\\\\\\$params\\\\\\\");\n\t\t\t [[ -z \\\\\\$param ]] && param=\\\\\\\"\\\\\\$params\\\\\\\";\n\t\t\t while read s; do echo $facet \\\\\\$s;\n\t\t\t done <<< \\\\\\\"\\\\\\$param\\\\\\\"\"\n\tdone\n}\n\n# restore lustre parameters from input stream, produces by save_lustre_params\nrestore_lustre_params() {\n\tlocal facet\n\tlocal name\n\tlocal val\n\n\twhile IFS=\" =\" read facet name val; do\n\t\tdo_facet $facet \"$LCTL set_param -n $name=$val\"\n\tdone\n}\n\ncheck_node_health() {\n\tlocal nodes=${1:-$(comma_list $(nodes_list))}\n\n\tfor node in ${nodes//,/ }; do\n\t\tcheck_network \"$node\" 5\n\t\tif [ $? -eq 0 ]; then\n\t\t\tdo_node $node \"$LCTL get_param catastrophe 2>&1\" |\n\t\t\t\tgrep -q \"catastrophe=1\" &&\n\t\t\t\terror \"$node:LBUG/LASSERT detected\" || true\n\t\tfi\n\tdone\n}\n\nmdsrate_cleanup () {\n\tif [ -d $4 ]; then\n\t\tmpi_run ${MACHINEFILE_OPTION} $2 -np $1 ${MDSRATE} --unlink \\\n\t\t\t--nfiles $3 --dir $4 --filefmt $5 $6\n\t\trmdir $4\n\tfi\n}\n\ndelayed_recovery_enabled () {\n    local var=${SINGLEMDS}_svc\n    do_facet $SINGLEMDS lctl get_param -n mdd.${!var}.stale_export_age > /dev/null 2>&1\n}\n\n########################\n\nconvert_facet2label() {\n\tlocal facet=$1\n\n\tif [ x$facet = xost ]; then\n\t\tfacet=ost1\n\telif [ x$facet = xmgs ] && combined_mgs_mds ; then\n\t\tfacet=mds1\n\tfi\n\n\tlocal varsvc=${facet}_svc\n\n\tif [ -n ${!varsvc} ]; then\n\t\techo ${!varsvc}\n\telse\n\t\terror \"No label for $facet!\"\n\tfi\n}\n\nget_clientosc_proc_path() {\n\techo \"${1}-osc-[-0-9a-f]*\"\n}\n\n# If the 2.0 MDS was mounted on 1.8 device, then the OSC and LOV names\n# used by MDT would not be changed.\n# mdt lov: fsname-mdtlov\n# mdt osc: fsname-OSTXXXX-osc\nmds_on_old_device() {\n    local mds=${1:-\"$SINGLEMDS\"}\n\n    if [ $(lustre_version_code $mds) -gt $(version_code 1.9.0) ]; then\n        do_facet $mds \"lctl list_param osc.$FSNAME-OST*-osc \\\n            > /dev/null 2>&1\" && return 0\n    fi\n    return 1\n}\n\nget_mdtosc_proc_path() {\n\tlocal mds_facet=$1\n\tlocal ost_label=${2:-\"*OST*\"}\n\n\t[ \"$mds_facet\" = \"mds\" ] && mds_facet=$SINGLEMDS\n\tlocal mdt_label=$(convert_facet2label $mds_facet)\n\tlocal mdt_index=$(echo $mdt_label | sed -e 's/^.*-//')\n\n\tif [[ $ost_label = *OST* ]]; then\n\t\techo \"${ost_label}-osc-${mdt_index}\"\n\telse\n\t\techo \"${ost_label}-osp-${mdt_index}\"\n\tfi\n}\n\nget_osc_import_name() {\n    local facet=$1\n    local ost=$2\n    local label=$(convert_facet2label $ost)\n\n    if [ \"${facet:0:3}\" = \"mds\" ]; then\n        get_mdtosc_proc_path $facet $label\n        return 0\n    fi\n\n    get_clientosc_proc_path $label\n    return 0\n}\n\n_wait_import_state () {\n    local expected=$1\n    local CONN_PROC=$2\n    local maxtime=${3:-$(max_recovery_time)}\n    local error_on_failure=${4:-1}\n    local CONN_STATE\n    local i=0\n\n\tCONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)\n    while ! echo \"${CONN_STATE}\" | egrep -q \"^${expected}\\$\" ; do\n        if [ \"${expected}\" == \"DISCONN\" ]; then\n            # for disconn we can check after proc entry is removed\n            [ \"x${CONN_STATE}\" == \"x\" ] && return 0\n            #  with AT enabled, we can have connect request timeout near of\n            # reconnect timeout and test can't see real disconnect\n            [ \"${CONN_STATE}\" == \"CONNECTING\" ] && return 0\n        fi\n\tif [ $i -ge $maxtime ]; then\n\t    [ $error_on_failure -ne 0 ] && \\\n\t\terror \"can't put import for $CONN_PROC into ${expected}\" \\\n\t\t      \"state after $i sec, have ${CONN_STATE}\"\n            return 1\n\tfi\n        sleep 1\n\t# Add uniq for multi-mount case\n\tCONN_STATE=$($LCTL get_param -n $CONN_PROC 2>/dev/null | cut -f2 | uniq)\n        i=$(($i + 1))\n    done\n\n    log \"$CONN_PROC in ${CONN_STATE} state after $i sec\"\n    return 0\n}\n\nwait_import_state() {\n    local state=$1\n    local params=$2\n    local maxtime=${3:-$(max_recovery_time)}\n    local error_on_failure=${4:-1}\n    local param\n\n    for param in ${params//,/ }; do\n\t_wait_import_state $state $param $maxtime $error_on_failure || return\n    done\n}\n\nwait_import_state_mount() {\n\tif ! is_mounted $MOUNT && ! is_mounted $MOUNT2; then\n\t\treturn 0\n\tfi\n\n\twait_import_state $*\n}\n\n# One client request could be timed out because server was not ready\n# when request was sent by client.\n# The request timeout calculation details :\n# ptl_send_rpc ()\n#      /* We give the server rq_timeout secs to process the req, and\n#      add the network latency for our local timeout. */\n#      request->rq_deadline = request->rq_sent + request->rq_timeout +\n#           ptlrpc_at_get_net_latency(request) ;\n#\n# ptlrpc_connect_import ()\n#      request->rq_timeout = INITIAL_CONNECT_TIMEOUT\n#\n# init_imp_at () ->\n#   -> at_init(&at->iat_net_latency, 0, 0) -> iat_net_latency=0\n# ptlrpc_at_get_net_latency(request) ->\n#       at_get (max (iat_net_latency=0, at_min)) = at_min\n#\n# i.e.:\n# request->rq_timeout + ptlrpc_at_get_net_latency(request) =\n# INITIAL_CONNECT_TIMEOUT + at_min\n#\n# We will use obd_timeout instead of INITIAL_CONNECT_TIMEOUT\n# because we can not get this value in runtime,\n# the value depends on configure options, and it is not stored in /proc.\n# obd_support.h:\n# #define CONNECTION_SWITCH_MIN 5U\n# #define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN,obd_timeout/20)\n\nrequest_timeout () {\n    local facet=$1\n\n    # request->rq_timeout = INITIAL_CONNECT_TIMEOUT\n    local init_connect_timeout=$TIMEOUT\n    [[ $init_connect_timeout -ge 5 ]] || init_connect_timeout=5\n\n    local at_min=$(at_get $facet at_min)\n\n    echo $(( init_connect_timeout + at_min ))\n}\n\n_wait_osc_import_state() {\n\tlocal facet=$1\n\tlocal ost_facet=$2\n\tlocal expected=$3\n\tlocal target=$(get_osc_import_name $facet $ost_facet)\n\tlocal param=\"os[cp].${target}.ost_server_uuid\"\n\tlocal params=$param\n\tlocal i=0\n\n\t# 1. wait the deadline of client 1st request (it could be skipped)\n\t# 2. wait the deadline of client 2nd request\n\tlocal maxtime=$(( 2 * $(request_timeout $facet)))\n\n\tif [[ $facet == client* ]]; then\n\t\t# During setup time, the osc might not be setup, it need wait\n\t\t# until list_param can return valid value.\n\t\tparams=$($LCTL list_param $param 2>/dev/null || true)\n\t\twhile [ -z \"$params\" ]; do\n\t\t\tif [ $i -ge $maxtime ]; then\n\t\t\t\techo \"can't get $param in $maxtime secs\"\n\t\t\t\treturn 1\n\t\t\tfi\n\t\t\tsleep 1\n\t\t\ti=$((i + 1))\n\t\t\tparams=$($LCTL list_param $param 2>/dev/null || true)\n\t\tdone\n\tfi\n\n\tif [[ $ost_facet = mds* ]]; then\n\t\t# no OSP connection to itself\n\t\tif [[ $facet = $ost_facet ]]; then\n\t\t\treturn 0\n\t\tfi\n\t\tparam=\"osp.${target}.mdt_server_uuid\"\n\t\tparams=$param\n\tfi\n\n\tif ! do_rpc_nodes \"$(facet_active_host $facet)\" \\\n\t\t\twait_import_state $expected \"$params\" $maxtime; then\n\t\terror \"$facet: import is not in $expected state after $maxtime\"\n\t\treturn 1\n\tfi\n\n\treturn 0\n}\n\nwait_osc_import_state() {\n\tlocal facet=$1\n\tlocal ost_facet=$2\n\tlocal expected=$3\n\tlocal num\n\n\tif [[ $facet = mds ]]; then\n\t\tfor num in $(seq $MDSCOUNT); do\n\t\t\t_wait_osc_import_state mds$num \"$ost_facet\" \"$expected\"\n\t\tdone\n\telse\n\t\t_wait_osc_import_state \"$facet\" \"$ost_facet\" \"$expected\"\n\tfi\n}\n\nwait_osc_import_ready() {\n\twait_osc_import_state $1 $2 \"\\(FULL\\|IDLE\\)\"\n}\n\n_wait_mgc_import_state() {\n\tlocal facet=$1\n\tlocal expected=$2\n\tlocal error_on_failure=${3:-1}\n\tlocal param=\"mgc.*.mgs_server_uuid\"\n\tlocal params=$param\n\tlocal i=0\n\n\t# 1. wait the deadline of client 1st request (it could be skipped)\n\t# 2. wait the deadline of client 2nd request\n\tlocal maxtime=$(( 2 * $(request_timeout $facet)))\n\n\tif [[ $facet == client* ]]; then\n\t\t# During setup time, the osc might not be setup, it need wait\n\t\t# until list_param can return valid value. And also if there\n\t\t# are mulitple osc entries we should list all of them before\n\t\t# go to wait.\n\t\tparams=$($LCTL list_param $param 2>/dev/null || true)\n\t\twhile [ -z \"$params\" ]; do\n\t\t\tif [ $i -ge $maxtime ]; then\n\t\t\t\techo \"can't get $param in $maxtime secs\"\n\t\t\t\treturn 1\n\t\t\tfi\n\t\t\tsleep 1\n\t\t\ti=$((i + 1))\n\t\t\tparams=$($LCTL list_param $param 2>/dev/null || true)\n\t\tdone\n\tfi\n\tif ! do_rpc_nodes \"$(facet_active_host $facet)\" \\\n\t\t\twait_import_state $expected \"$params\" $maxtime \\\n\t\t\t\t\t  $error_on_failure; then\n\t\tif [ $error_on_failure -ne 0 ]; then\n\t\t    error \"import is not in ${expected} state\"\n\t\tfi\n\t\treturn 1\n\tfi\n\n\treturn 0\n}\n\nwait_mgc_import_state() {\n\tlocal facet=$1\n\tlocal expected=$2\n\tlocal error_on_failure=${3:-1}\n\tlocal num\n\n\tif [[ $facet = mds ]]; then\n\t\tfor num in $(seq $MDSCOUNT); do\n\t\t\t_wait_mgc_import_state mds$num \"$expected\" \\\n\t\t\t\t\t       $error_on_failure || return\n\t\tdone\n\telse\n\t\t_wait_mgc_import_state \"$facet\" \"$expected\"\n\t\t\t\t       $error_on_failure || return\n\tfi\n}\n\nwait_dne_interconnect() {\n\tlocal num\n\n\tif [ $MDSCOUNT -gt 1 ]; then\n\t\tfor num in $(seq $MDSCOUNT); do\n\t\t\twait_osc_import_ready mds mds$num\n\t\tdone\n\tfi\n}\n\nget_clientmdc_proc_path() {\n    echo \"${1}-mdc-*\"\n}\n\nget_clientmgc_proc_path() {\n    echo \"*\"\n}\n\ndo_rpc_nodes () {\n\tlocal list=$1\n\tshift\n\n\t[ -z \"$list\" ] && return 0\n\n\t# Add paths to lustre tests for 32 and 64 bit systems.\n\tlocal LIBPATH=\"/usr/lib/lustre/tests:/usr/lib64/lustre/tests:\"\n\tlocal TESTPATH=\"$RLUSTRE/tests:\"\n\tlocal RPATH=\"PATH=${TESTPATH}${LIBPATH}${PATH}:/sbin:/bin:/usr/sbin:\"\n\tdo_nodesv $list \"${RPATH} NAME=${NAME} bash rpc.sh $@ \"\n}\n\nwait_clients_import_state () {\n\tlocal list=$1\n\tlocal facet=$2\n\tlocal expected=$3\n\n\tlocal facets=$facet\n\n\tif [ \"$FAILURE_MODE\" = HARD ]; then\n\t\tfacets=$(facets_on_host $(facet_active_host $facet))\n\tfi\n\n\tfor facet in ${facets//,/ }; do\n\t\tlocal label=$(convert_facet2label $facet)\n\t\tlocal proc_path\n\t\tcase $facet in\n\t\tost* ) proc_path=\"osc.$(get_clientosc_proc_path \\\n\t\t\t\t  $label).ost_server_uuid\" ;;\n\t\tmds* ) proc_path=\"mdc.$(get_clientmdc_proc_path \\\n\t\t\t\t  $label).mds_server_uuid\" ;;\n\t\tmgs* ) proc_path=\"mgc.$(get_clientmgc_proc_path \\\n\t\t\t\t  $label).mgs_server_uuid\" ;;\n\t\t*) error \"unknown facet!\" ;;\n\t\tesac\n\n\t\tlocal params=$(expand_list $params $proc_path)\n\tdone\n\n\tif ! do_rpc_nodes \"$list\" wait_import_state_mount \"$expected\" $params;\n\tthen\n\t\terror \"import is not in ${expected} state\"\n\t\treturn 1\n\tfi\n}\n\nwait_osp_active() {\n\tlocal facet=$1\n\tlocal tgt_name=$2\n\tlocal tgt_idx=$3\n\tlocal expected=$4\n\tlocal num\n\n\t# wait until all MDTs are in the expected state\n\tfor ((num = 1; num <= $MDSCOUNT; num++)); do\n\t\tlocal mdtosp=$(get_mdtosc_proc_path mds${num} ${tgt_name})\n\t\tlocal wait=0\n\t\tlocal mproc\n\n\t\tif [ $facet = \"mds\" ]; then\n\t\t\tmproc=\"osp.$mdtosp.active\"\n\t\t\t[ $num -eq $((tgt_idx + 1)) ] && continue\n\t\telse\n\t\t\tmproc=\"osc.$mdtosp.active\"\n\t\tfi\n\n\t\techo \"check $mproc\"\n\t\twhile [ 1 ]; do\n\t\t\tsleep 5\n\t\t\tlocal result=$(do_facet mds${num} \"$LCTL get_param -n $mproc\")\n\t\t\tlocal max=30\n\n\t\t\t[ ${PIPESTATUS[0]} = 0 ] || error \"Can't read $mproc\"\n\t\t\tif [ $result -eq $expected ]; then\n\t\t\t\techo -n \"target updated after \"\n\t\t\t\techo \"$wait sec (got $result)\"\n\t\t\t\tbreak\n\t\t\tfi\n\t\t\twait=$((wait + 5))\n\t\t\tif [ $wait -eq $max ]; then\n\t\t\t\terror \"$tgt_name: wanted $expected got $result\"\n\t\t\tfi\n\t\t\techo \"Waiting $((max - wait)) secs for $tgt_name\"\n\t\tdone\n\tdone\n}\n\noos_full() {\n\tlocal -a AVAILA\n\tlocal -a GRANTA\n\tlocal -a TOTALA\n\tlocal OSCFULL=1\n\tAVAILA=($(do_nodes $(comma_list $(osts_nodes)) \\\n\t          $LCTL get_param obdfilter.*.kbytesavail))\n\tGRANTA=($(do_nodes $(comma_list $(osts_nodes)) \\\n\t          $LCTL get_param -n obdfilter.*.tot_granted))\n\tTOTALA=($(do_nodes $(comma_list $(osts_nodes)) \\\n\t          $LCTL get_param -n obdfilter.*.kbytestotal))\n\tfor ((i=0; i<${#AVAILA[@]}; i++)); do\n\t\tlocal -a AVAIL1=(${AVAILA[$i]//=/ })\n\t\tlocal -a TOTAL=(${TOTALA[$i]//=/ })\n\t\tGRANT=$((${GRANTA[$i]}/1024))\n\t\t# allow 1% of total space in bavail because of delayed\n\t\t# allocation with ZFS which might release some free space after\n\t\t# txg commit.  For small devices, we set a mininum of 8MB\n\t\tlocal LIMIT=$((${TOTAL} / 100 + 8000))\n\t\techo -n $(echo ${AVAIL1[0]} | cut -d\".\" -f2) avl=${AVAIL1[1]} \\\n\t\t\tgrnt=$GRANT diff=$((AVAIL1[1] - GRANT)) limit=${LIMIT}\n\t\t[ $((AVAIL1[1] - GRANT)) -lt $LIMIT ] && OSCFULL=0 && \\\n\t\t\techo \" FULL\" || echo\n\tdone\n\treturn $OSCFULL\n}\n\nlist_pool() {\n\techo -e \"$(do_facet $SINGLEMDS $LCTL pool_list $1 | sed '1d')\"\n}\n\ncheck_pool_not_exist() {\n\tlocal fsname=${1%%.*}\n\tlocal poolname=${1##$fsname.}\n\t[[ $# -ne 1 ]] && return 0\n\t[[ x$poolname = x ]] &&  return 0\n\tlist_pool $fsname | grep -w $1 && return 1\n\treturn 0\n}\n\ncreate_pool() {\n\tlocal fsname=${1%%.*}\n\tlocal poolname=${1##$fsname.}\n\n\tstack_trap \"destroy_test_pools $fsname\" EXIT\n\tdo_facet mgs lctl pool_new $1\n\tlocal RC=$?\n\t# get param should return err unless pool is created\n\t[[ $RC -ne 0 ]] && return $RC\n\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$fsname-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \\\n\t\t\t\"lctl get_param -n lod.$lodname.pools.$poolname \\\n\t\t\t\t2>/dev/null || echo foo\" \"\" ||\n\t\t\terror \"mds$mds_id: pool_new failed $1\"\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n lov.$fsname-*.pools.$poolname \\\n\t\t2>/dev/null || echo foo\" \"\" || error \"pool_new failed $1\"\n\n\tadd_pool_to_list $1\n\treturn $RC\n}\n\nadd_pool_to_list () {\n\tlocal fsname=${1%%.*}\n\tlocal poolname=${1##$fsname.}\n\n\tlocal listvar=${fsname}_CREATED_POOLS\n\tlocal temp=${listvar}=$(expand_list ${!listvar} $poolname)\n\teval export $temp\n}\n\nremove_pool_from_list () {\n\tlocal fsname=${1%%.*}\n\tlocal poolname=${1##$fsname.}\n\n\tlocal listvar=${fsname}_CREATED_POOLS\n\tlocal temp=${listvar}=$(exclude_items_from_list ${!listvar} $poolname)\n\teval export $temp\n}\n\ndestroy_pool_int() {\n\tlocal ost\n\tlocal OSTS=$(list_pool $1)\n\tfor ost in $OSTS; do\n\t\tdo_facet mgs lctl pool_remove $1 $ost\n\tdone\n\twait_update_facet $SINGLEMDS \"lctl pool_list $1 | wc -l\" \"1\" ||\n\t\terror \"MDS: pool_list $1 failed\"\n\tdo_facet mgs lctl pool_destroy $1\n}\n\n# <fsname>.<poolname> or <poolname>\ndestroy_pool() {\n\tlocal fsname=${1%%.*}\n\tlocal poolname=${1##$fsname.}\n\n\t[[ x$fsname = x$poolname ]] && fsname=$FSNAME\n\n\tlocal RC\n\n\tcheck_pool_not_exist $fsname.$poolname\n\t[[ $? -eq 0 ]] && return 0\n\n\tdestroy_pool_int $fsname.$poolname\n\tRC=$?\n\t[[ $RC -ne 0 ]] && return $RC\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$fsname-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \\\n\t\t\t\"lctl get_param -n lod.$lodname.pools.$poolname \\\n\t\t\t\t2>/dev/null || echo foo\" \"foo\" ||\n\t\t\terror \"mds$mds_id: destroy pool failed $1\"\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n lov.$fsname-*.pools.$poolname \\\n\t\t2>/dev/null || echo foo\" \"foo\" || error \"destroy pool failed $1\"\n\n\tremove_pool_from_list $fsname.$poolname\n\n\treturn $RC\n}\n\ndestroy_pools () {\n\tlocal fsname=${1:-$FSNAME}\n\tlocal poolname\n\tlocal listvar=${fsname}_CREATED_POOLS\n\n\t[ x${!listvar} = x ] && return 0\n\n\techo \"Destroy the created pools: ${!listvar}\"\n\tfor poolname in ${!listvar//,/ }; do\n\t\tdestroy_pool $fsname.$poolname\n\tdone\n}\n\ndestroy_test_pools () {\n\ttrap 0\n\tlocal fsname=${1:-$FSNAME}\n\tdestroy_pools $fsname || true\n}\n\ngather_logs () {\n\tlocal list=$1\n\n\tlocal ts=$(date +%s)\n\tlocal docp=true\n\n\tif [[ ! -f \"$YAML_LOG\" ]]; then\n\t\t# init_logging is not performed before gather_logs,\n\t\t# so the $LOGDIR needs to be checked here\n\t\tcheck_shared_dir $LOGDIR && touch $LOGDIR/shared\n\tfi\n\n\t[ -f $LOGDIR/shared ] && docp=false\n\n\t# dump lustre logs, dmesg, and journal if GSS_SK=true\n\n\tprefix=\"$TESTLOG_PREFIX.$TESTNAME\"\n\tsuffix=\"$ts.log\"\n\techo \"Dumping lctl log to ${prefix}.*.${suffix}\"\n\n\tif [ -n \"$CLIENTONLY\" -o \"$PDSH\" == \"no_dsh\" ]; then\n\t\techo \"Dumping logs only on local client.\"\n\t\t$LCTL dk > ${prefix}.debug_log.$(hostname -s).${suffix}\n\t\tdmesg > ${prefix}.dmesg.$(hostname -s).${suffix}\n\t\t[ \"$SHARED_KEY\" = true ] && find $SK_PATH -name '*.key' -exec \\\n\t\t\tlgss_sk -r {} \\; &> \\\n\t\t\t${prefix}.ssk_keys.$(hostname -s).${suffix}\n\t\t[ \"$SHARED_KEY\" = true ] && lctl get_param 'nodemap.*.*' > \\\n\t\t\t${prefix}.nodemaps.$(hostname -s).${suffix}\n\t\t[ \"$GSS_SK\" = true ] && keyctl show > \\\n\t\t\t${prefix}.keyring.$(hostname -s).${suffix}\n\t\t[ \"$GSS_SK\" = true ] && journalctl -a > \\\n\t\t\t${prefix}.journal.$(hostname -s).${suffix}\n\t\treturn\n\tfi\n\n\tdo_nodesv $list \\\n\t\t\"$LCTL dk > ${prefix}.debug_log.\\\\\\$(hostname -s).${suffix};\n\t\tdmesg > ${prefix}.dmesg.\\\\\\$(hostname -s).${suffix}\"\n\tif [ \"$SHARED_KEY\" = true ]; then\n\t\tdo_nodesv $list \"find $SK_PATH -name '*.key' -exec \\\n\t\t\tlgss_sk -r {} \\; &> \\\n\t\t\t${prefix}.ssk_keys.\\\\\\$(hostname -s).${suffix}\"\n\t\tdo_facet mds1 \"lctl get_param 'nodemap.*.*' > \\\n\t\t\t${prefix}.nodemaps.\\\\\\$(hostname -s).${suffix}\"\n\tfi\n\tif [ \"$GSS_SK\" = true ]; then\n\t\tdo_nodesv $list \"keyctl show > \\\n\t\t\t${prefix}.keyring.\\\\\\$(hostname -s).${suffix}\"\n\t\tdo_nodesv $list \"journalctl -a > \\\n\t\t\t${prefix}.journal.\\\\\\$(hostname -s).${suffix}\"\n\tfi\n\n\tif [ ! -f $LOGDIR/shared ]; then\n\t\tdo_nodes $list rsync -az \"${prefix}.*.${suffix}\" \\\n\t\t\t $HOSTNAME:$LOGDIR\n\tfi\n}\n\ndo_ls () {\n    local mntpt_root=$1\n    local num_mntpts=$2\n    local dir=$3\n    local i\n    local cmd\n    local pids\n    local rc=0\n\n    for i in $(seq 0 $num_mntpts); do\n        cmd=\"ls -laf ${mntpt_root}$i/$dir\"\n        echo + $cmd;\n        $cmd > /dev/null &\n        pids=\"$pids $!\"\n    done\n    echo pids=$pids\n    for pid in $pids; do\n        wait $pid || rc=$?\n    done\n\n    return $rc\n}\n\n# check_and_start_recovery_timer()\n#\tservice_time = at_est2timeout(service_time);\n#\tservice_time += 2 * INITIAL_CONNECT_TIMEOUT;\n#\tservice_time += 2 * (CONNECTION_SWITCH_MAX + CONNECTION_SWITCH_INC);\n\n#define INITIAL_CONNECT_TIMEOUT max(CONNECTION_SWITCH_MIN, obd_timeout/20)\n#define CONNECTION_SWITCH_MAX min(50, max(CONNECTION_SWITCH_MIN, obd_timeout))\n#define CONNECTION_SWITCH_MIN 5\n#define CONNECTION_SWITCH_INC 5\nmax_recovery_time() {\n\tlocal init_connect_timeout=$((TIMEOUT / 20))\n\t((init_connect_timeout >= 5)) || init_connect_timeout=5\n\n\tlocal service_time=$(($(at_max_get client) * 9 / 4 + 5))\n\tservice_time=$((service_time + 2 * (init_connect_timeout + 50 + 5)))\n\n\techo -n $service_time\n}\n\nrecovery_time_min() {\n\tlocal connection_switch_min=5\n\tlocal connection_switch_inc=5\n\tlocal connection_switch_max\n\tlocal reconnect_delay_max\n\tlocal initial_connect_timeout\n\tlocal max\n\tlocal timout_20\n\n\t#connection_switch_max=min(50, max($connection_switch_min,$TIMEOUT)\n\t(($connection_switch_min > $TIMEOUT)) &&\n\t\tmax=$connection_switch_min || max=$TIMEOUT\n\t(($max < 50)) && connection_switch_max=$max || connection_switch_max=50\n\n\t#initial_connect_timeout = max(connection_switch_min, obd_timeout/20)\n\ttimeout_20=$((TIMEOUT/20))\n\t(($connection_switch_min > $timeout_20)) &&\n\t\tinitial_connect_timeout=$connection_switch_min ||\n\t\tinitial_connect_timeout=$timeout_20\n\n\treconnect_delay_max=$((connection_switch_max + connection_switch_inc + \\\n\t\t\t       initial_connect_timeout))\n\techo $((2 * reconnect_delay_max))\n}\n\nget_clients_mount_count () {\n\tlocal clients=${CLIENTS:-$HOSTNAME}\n\n\t# we need to take into account the clients mounts and\n\t# exclude mds/ost mounts if any;\n\tdo_nodes $clients cat /proc/mounts | grep lustre |\n\t\tgrep -w $MOUNT | wc -l\n}\n\n# gss functions\nPROC_CLI=\"srpc_info\"\nPROC_CON=\"srpc_contexts\"\n\ncombination()\n{\n    local M=$1\n    local N=$2\n    local R=1\n\n    if [ $M -lt $N ]; then\n        R=0\n    else\n        N=$((N + 1))\n        while [ $N -lt $M ]; do\n            R=$((R * N))\n            N=$((N + 1))\n        done\n    fi\n\n    echo $R\n    return 0\n}\n\ncalc_connection_cnt() {\n\tlocal dir=$1\n\n\t# MDT->MDT = 2 * C(M, 2)\n\t# MDT->OST = M * O\n\t# CLI->OST = C * O\n\t# CLI->MDT = C * M\n\tcomb_m2=$(combination $MDSCOUNT 2)\n\n\tlocal num_clients=$(get_clients_mount_count)\n\n\tlocal cnt_mdt2mdt=$((comb_m2 * 2))\n\tlocal cnt_mdt2ost=$((MDSCOUNT * OSTCOUNT))\n\tlocal cnt_cli2ost=$((num_clients * OSTCOUNT))\n\tlocal cnt_cli2mdt=$((num_clients * MDSCOUNT))\n\tif is_mounted $MOUNT2; then\n\t\tcnt_cli2mdt=$((cnt_cli2mdt * 2))\n\t\tcnt_cli2ost=$((cnt_cli2ost * 2))\n\tfi\n\tif local_mode; then\n\t\tcnt_mdt2mdt=0\n\t\tcnt_mdt2ost=0\n\t\tcnt_cli2ost=2\n\t\tcnt_cli2mdt=1\n\tfi\n\tlocal cnt_all2ost=$((cnt_mdt2ost + cnt_cli2ost))\n\tlocal cnt_all2mdt=$((cnt_mdt2mdt + cnt_cli2mdt))\n\tlocal cnt_all2all=$((cnt_mdt2ost + cnt_mdt2mdt \\\n\t\t+ cnt_cli2ost + cnt_cli2mdt))\n\n\tlocal var=cnt_$dir\n\tlocal res=${!var}\n\n\techo $res\n}\n\nset_rule()\n{\n    local tgt=$1\n    local net=$2\n    local dir=$3\n    local flavor=$4\n    local cmd=\"$tgt.srpc.flavor\"\n\n    if [ $net == \"any\" ]; then\n        net=\"default\"\n    fi\n    cmd=\"$cmd.$net\"\n\n    if [ $dir != \"any\" ]; then\n        cmd=\"$cmd.$dir\"\n    fi\n\n    cmd=\"$cmd=$flavor\"\n    log \"Setting sptlrpc rule: $cmd\"\n    do_facet mgs \"$LCTL conf_param $cmd\"\n}\n\ncount_contexts()\n{\n\tlocal output=$1\n\tlocal total_ctx=$(echo \"$output\" | grep -c \"expire.*key.*hdl\")\n\techo $total_ctx\n}\n\ncount_flvr()\n{\n    local output=$1\n    local flavor=$2\n    local count=0\n\n    rpc_flvr=`echo $flavor | awk -F - '{ print $1 }'`\n    bulkspec=`echo $flavor | awk -F - '{ print $2 }'`\n\n    count=`echo \"$output\" | grep \"rpc flavor\" | grep $rpc_flvr | wc -l`\n\n    if [ \"x$bulkspec\" != \"x\" ]; then\n        algs=`echo $bulkspec | awk -F : '{ print $2 }'`\n\n        if [ \"x$algs\" != \"x\" ]; then\n            bulk_count=`echo \"$output\" | grep \"bulk flavor\" | grep $algs | wc -l`\n        else\n            bulk=`echo $bulkspec | awk -F : '{ print $1 }'`\n            if [ $bulk == \"bulkn\" ]; then\n                bulk_count=`echo \"$output\" | grep \"bulk flavor\" \\\n                            | grep \"null/null\" | wc -l`\n            elif [ $bulk == \"bulki\" ]; then\n                bulk_count=`echo \"$output\" | grep \"bulk flavor\" \\\n                            | grep \"/null\" | grep -v \"null/\" | wc -l`\n            else\n                bulk_count=`echo \"$output\" | grep \"bulk flavor\" \\\n                            | grep -v \"/null\" | grep -v \"null/\" | wc -l`\n            fi\n        fi\n\n        [ $bulk_count -lt $count ] && count=$bulk_count\n    fi\n\n    echo $count\n}\n\nflvr_cnt_cli2mdt()\n{\n    local flavor=$1\n    local cnt\n\n    local clients=${CLIENTS:-$HOSTNAME}\n\n    for c in ${clients//,/ }; do\n\tlocal output=$(do_node $c lctl get_param -n \\\n\t\t mdc.*-*-mdc-*.$PROC_CLI 2>/dev/null)\n\tlocal tmpcnt=$(count_flvr \"$output\" $flavor)\n\tif $GSS_SK && [ $flavor != \"null\" ]; then\n\t\t# tmpcnt=min(contexts,flavors) to ensure SK context is on\n\t\toutput=$(do_node $c lctl get_param -n \\\n\t\t\t mdc.*-MDT*-mdc-*.$PROC_CON 2>/dev/null)\n\t\tlocal outcon=$(count_contexts \"$output\")\n\t\tif [ \"$outcon\" -lt \"$tmpcnt\" ]; then\n\t\t\ttmpcnt=$outcon\n\t\tfi\n\tfi\n\tcnt=$((cnt + tmpcnt))\n    done\n    echo $cnt\n}\n\nflvr_cnt_cli2ost()\n{\n    local flavor=$1\n    local cnt\n\n    local clients=${CLIENTS:-$HOSTNAME}\n\n    for c in ${clients//,/ }; do\n\t# reconnect if idle\n\tdo_node $c lctl set_param osc.*.idle_connect=1 >/dev/null 2>&1\n\tlocal output=$(do_node $c lctl get_param -n \\\n\t\t osc.*OST*-osc-[^M][^D][^T]*.$PROC_CLI 2>/dev/null)\n\tlocal tmpcnt=$(count_flvr \"$output\" $flavor)\n\tif $GSS_SK && [ $flavor != \"null\" ]; then\n\t\t# tmpcnt=min(contexts,flavors) to ensure SK context is on\n\t\toutput=$(do_node $c lctl get_param -n \\\n\t\t\t osc.*OST*-osc-[^M][^D][^T]*.$PROC_CON 2>/dev/null)\n\t\tlocal outcon=$(count_contexts \"$output\")\n\t\tif [ \"$outcon\" -lt \"$tmpcnt\" ]; then\n\t\t\ttmpcnt=$outcon\n\t\tfi\n\tfi\n        cnt=$((cnt + tmpcnt))\n    done\n    echo $cnt\n}\n\nflvr_cnt_mdt2mdt()\n{\n    local flavor=$1\n    local cnt=0\n\n    if [ $MDSCOUNT -le 1 ]; then\n        echo 0\n        return\n    fi\n\n    for num in `seq $MDSCOUNT`; do\n\tlocal output=$(do_facet mds$num lctl get_param -n \\\n\t\tosp.*-MDT*osp-MDT*.$PROC_CLI 2>/dev/null)\n\tlocal tmpcnt=$(count_flvr \"$output\" $flavor)\n\tif $GSS_SK && [ $flavor != \"null\" ]; then\n\t\t# tmpcnt=min(contexts,flavors) to ensure SK context is on\n\t\toutput=$(do_facet mds$num lctl get_param -n \\\n\t\t\tosp.*-MDT*osp-MDT*.$PROC_CON 2>/dev/null)\n\t\tlocal outcon=$(count_contexts \"$output\")\n\t\tif [ \"$outcon\" -lt \"$tmpcnt\" ]; then\n\t\t\ttmpcnt=$outcon\n\t\tfi\n\tfi\n        cnt=$((cnt + tmpcnt))\n    done\n    echo $cnt;\n}\n\nflvr_cnt_mdt2ost()\n{\n    local flavor=$1\n    local cnt=0\n    local mdtosc\n\n    for num in `seq $MDSCOUNT`; do\n        mdtosc=$(get_mdtosc_proc_path mds$num)\n        mdtosc=${mdtosc/-MDT*/-MDT\\*}\n\tlocal output=$(do_facet mds$num lctl get_param -n \\\n\t\t       os[cp].$mdtosc.$PROC_CLI 2>/dev/null)\n\tlocal tmpcnt=$(count_flvr \"$output\" $flavor)\n\tif $GSS_SK && [ $flavor != \"null\" ]; then\n\t\t# tmpcnt=min(contexts,flavors) to ensure SK context is on\n\t\toutput=$(do_facet mds$num lctl get_param -n \\\n\t\t\t os[cp].$mdtosc.$PROC_CON 2>/dev/null)\n\t\tlocal outcon=$(count_contexts \"$output\")\n\t\tif [ \"$outcon\" -lt \"$tmpcnt\" ]; then\n\t\t\ttmpcnt=$outcon\n\t\tfi\n\tfi\n        cnt=$((cnt + tmpcnt))\n    done\n    echo $cnt;\n}\n\nflvr_cnt_mgc2mgs()\n{\n    local flavor=$1\n\n    local output=$(do_facet client lctl get_param -n mgc.*.$PROC_CLI \\\n\t\t\t2>/dev/null)\n    count_flvr \"$output\" $flavor\n}\n\ndo_check_flavor()\n{\n    local dir=$1        # from to\n    local flavor=$2     # flavor expected\n    local res=0\n\n    if [ $dir == \"cli2mdt\" ]; then\n        res=`flvr_cnt_cli2mdt $flavor`\n    elif [ $dir == \"cli2ost\" ]; then\n        res=`flvr_cnt_cli2ost $flavor`\n    elif [ $dir == \"mdt2mdt\" ]; then\n        res=`flvr_cnt_mdt2mdt $flavor`\n    elif [ $dir == \"mdt2ost\" ]; then\n        res=`flvr_cnt_mdt2ost $flavor`\n    elif [ $dir == \"all2ost\" ]; then\n        res1=`flvr_cnt_mdt2ost $flavor`\n        res2=`flvr_cnt_cli2ost $flavor`\n        res=$((res1 + res2))\n    elif [ $dir == \"all2mdt\" ]; then\n        res1=`flvr_cnt_mdt2mdt $flavor`\n        res2=`flvr_cnt_cli2mdt $flavor`\n        res=$((res1 + res2))\n    elif [ $dir == \"all2all\" ]; then\n        res1=`flvr_cnt_mdt2ost $flavor`\n        res2=`flvr_cnt_cli2ost $flavor`\n        res3=`flvr_cnt_mdt2mdt $flavor`\n        res4=`flvr_cnt_cli2mdt $flavor`\n        res=$((res1 + res2 + res3 + res4))\n    fi\n\n    echo $res\n}\n\nwait_flavor()\n{\n\tlocal dir=$1        # from to\n\tlocal flavor=$2     # flavor expected\n\tlocal expect=${3:-$(calc_connection_cnt $dir)} # number expected\n\tlocal WAITFLAVOR_MAX=20 # how many retries before abort?\n\n\tlocal res=0\n\tfor ((i = 0; i < $WAITFLAVOR_MAX; i++)); do\n\t\techo -n \"checking $dir...\"\n\t\tres=$(do_check_flavor $dir $flavor)\n\t\techo \"found $res/$expect $flavor connections\"\n\t\t[ $res -ge $expect ] && return 0\n\t\tsleep 4\n\tdone\n\n\techo \"Error checking $flavor of $dir: expect $expect, actual $res\"\n#\techo \"Dumping additional logs for SK debug..\"\n\tdo_nodes $(comma_list $(all_server_nodes)) \"keyctl show\"\n\tif $dump; then\n\t\tgather_logs $(comma_list $(nodes_list))\n\tfi\n\treturn 1\n}\n\nrestore_to_default_flavor()\n{\n\tlocal proc=\"mgs.MGS.live.$FSNAME\"\n\n\techo \"restoring to default flavor...\"\n\n\tlocal nrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |\n\t\tgrep \".srpc.flavor\" | wc -l)\n\n\t# remove all existing rules if any\n\tif [ $nrule -ne 0 ]; then\n\t\techo \"$nrule existing rules\"\n\t\tfor rule in $(do_facet mgs lctl get_param -n $proc 2>/dev/null |\n\t\t    grep \".srpc.flavor.\"); do\n\t\t\techo \"remove rule: $rule\"\n\t\t\tspec=`echo $rule | awk -F = '{print $1}'`\n\t\t\tdo_facet mgs \"$LCTL conf_param -d $spec\"\n\t\tdone\n\tfi\n\n\t# verify no rules left\n\tnrule=$(do_facet mgs lctl get_param -n $proc 2>/dev/null |\n\t\tgrep \".srpc.flavor.\" | wc -l)\n\t[ $nrule -ne 0 ] && error \"still $nrule rules left\"\n\n\t# wait for default flavor to be applied\n\tif $GSS_SK; then\n\t\tif $SK_S2S; then\n\t\t\tset_rule $FSNAME any any $SK_FLAVOR\n\t\t\twait_flavor all2all $SK_FLAVOR\n\t\telse\n\t\t\tset_rule $FSNAME any cli2mdt $SK_FLAVOR\n\t\t\tset_rule $FSNAME any cli2ost $SK_FLAVOR\n\t\t\twait_flavor cli2mdt $SK_FLAVOR\n\t\t\twait_flavor cli2ost $SK_FLAVOR\n\t\tfi\n\t\techo \"GSS_SK now at default flavor: $SK_FLAVOR\"\n\telse\n\t\twait_flavor all2all null\n\tfi\n}\n\nset_flavor_all()\n{\n\tlocal flavor=${1:-null}\n\n\techo \"setting all flavor to $flavor\"\n\n\t# FIXME need parameter to this fn\n\t# and remove global vars\n\tlocal cnt_all2all=$(calc_connection_cnt all2all)\n\n\tlocal res=$(do_check_flavor all2all $flavor)\n\tif [ $res -eq $cnt_all2all ]; then\n\t\techo \"already have total $res $flavor connections\"\n\t\treturn\n\tfi\n\n\techo \"found $res $flavor out of total $cnt_all2all connections\"\n\trestore_to_default_flavor\n\n\t[[ $flavor = null ]] && return 0\n\n\tif $GSS_SK && [ $flavor != \"null\" ]; then\n\t\tif $SK_S2S; then\n\t\t\tset_rule $FSNAME any any $flavor\n\t\t\twait_flavor all2all $flavor\n\t\telse\n\t\t\tset_rule $FSNAME any cli2mdt $flavor\n\t\t\tset_rule $FSNAME any cli2ost $flavor\n\t\t\tset_rule $FSNAME any mdt2ost null\n\t\t\tset_rule $FSNAME any mdt2mdt null\n\t\t\twait_flavor cli2mdt $flavor\n\t\t\twait_flavor cli2ost $flavor\n\t\tfi\n\t\techo \"GSS_SK now at flavor: $flavor\"\n\telse\n\t\tset_rule $FSNAME any any $flavor\n\t\twait_flavor all2all $flavor\n\tfi\n}\n\n\ncheck_logdir() {\n    local dir=$1\n    # Checking for shared logdir\n    if [ ! -d $dir ]; then\n        # Not found. Create local logdir\n        mkdir -p $dir\n    else\n        touch $dir/check_file.$(hostname -s)\n    fi\n    return 0\n}\n\ncheck_write_access() {\n\tlocal dir=$1\n\tlocal list=${2:-$(comma_list $(nodes_list))}\n\tlocal node\n\tlocal file\n\n\tfor node in ${list//,/ }; do\n\t\tfile=$dir/check_file.$(short_nodename $node)\n\t\tif [[ ! -f \"$file\" ]]; then\n\t\t\t# Logdir not accessible/writable from this node.\n\t\t\treturn 1\n\t\tfi\n\t\trm -f $file || return 1\n\tdone\n\treturn 0\n}\n\ninit_logging() {\n\t[[ -n $YAML_LOG ]] && return\n\tlocal save_umask=$(umask)\n\tumask 0000\n\n\texport YAML_LOG=${LOGDIR}/results.yml\n\tmkdir -p $LOGDIR\n\tinit_clients_lists\n\n\t# If the yaml log already exists then we will just append to it\n\tif [ ! -f $YAML_LOG ]; then\n\t\tif check_shared_dir $LOGDIR; then\n\t\t\ttouch $LOGDIR/shared\n\t\t\techo \"Logging to shared log directory: $LOGDIR\"\n\t\telse\n\t\t\techo \"Logging to local directory: $LOGDIR\"\n\t\tfi\n\n\t\tyml_nodes_file $LOGDIR >> $YAML_LOG\n\t\tyml_results_file >> $YAML_LOG\n\tfi\n\n\tumask $save_umask\n\n\t# log actual client and server versions if needed for debugging\n\tlog \"Client: $(lustre_build_version client)\"\n\tlog \"MDS: $(lustre_build_version mds1)\"\n\tlog \"OSS: $(lustre_build_version ost1)\"\n}\n\nlog_test() {\n    yml_log_test $1 >> $YAML_LOG\n}\n\nlog_test_status() {\n     yml_log_test_status $@ >> $YAML_LOG\n}\n\nlog_sub_test_begin() {\n    yml_log_sub_test_begin \"$@\" >> $YAML_LOG\n}\n\nlog_sub_test_end() {\n    yml_log_sub_test_end \"$@\" >> $YAML_LOG\n}\n\nrun_llverdev()\n{\n        local dev=$1\n        local llverdev_opts=$2\n        local devname=$(basename $1)\n        local size=$(grep \"$devname\"$ /proc/partitions | awk '{print $3}')\n        # loop devices aren't in /proc/partitions\n        [ \"x$size\" == \"x\" ] && local size=$(ls -l $dev | awk '{print $5}')\n\n        size=$(($size / 1024 / 1024)) # Gb\n\n        local partial_arg=\"\"\n        # Run in partial (fast) mode if the size\n        # of a partition > 1 GB\n        [ $size -gt 1 ] && partial_arg=\"-p\"\n\n        llverdev --force $partial_arg $llverdev_opts $dev\n}\n\nrun_llverfs()\n{\n        local dir=$1\n        local llverfs_opts=$2\n        local use_partial_arg=$3\n        local partial_arg=\"\"\n        local size=$(df -B G $dir |tail -n 1 |awk '{print $2}' |sed 's/G//') #GB\n\n        # Run in partial (fast) mode if the size\n        # of a partition > 1 GB\n        [ \"x$use_partial_arg\" != \"xno\" ] && [ $size -gt 1 ] && partial_arg=\"-p\"\n\n        llverfs $partial_arg $llverfs_opts $dir\n}\n\n#Remove objects from OST\nremove_ost_objects() {\n\tlocal facet=$1\n\tlocal ostdev=$2\n\tlocal group=$3\n\tshift 3\n\tlocal objids=\"$@\"\n\tlocal mntpt=$(facet_mntpt $facet)\n\tlocal opts=$OST_MOUNT_OPTS\n\tlocal i\n\tlocal rc\n\n\techo \"removing objects from $ostdev on $facet: $objids\"\n\tif ! test -b $ostdev; then\n\t\topts=$(csa_add \"$opts\" -o loop)\n\tfi\n\tmount -t $(facet_fstype $facet) $opts $ostdev $mntpt ||\n\t\treturn $?\n\trc=0\n\tfor i in $objids; do\n\t\trm $mntpt/O/$group/d$((i % 32))/$i || { rc=$?; break; }\n\tdone\n\tumount -f $mntpt || return $?\n\treturn $rc\n}\n\n#Remove files from MDT\nremove_mdt_files() {\n\tlocal facet=$1\n\tlocal mdtdev=$2\n\tshift 2\n\tlocal files=\"$@\"\n\tlocal mntpt=$(facet_mntpt $facet)\n\tlocal opts=$MDS_MOUNT_OPTS\n\n\techo \"removing files from $mdtdev on $facet: $files\"\n\tif [ $(facet_fstype $facet) == ldiskfs ] &&\n\t   ! do_facet $facet test -b $mdtdev; then\n\t\topts=$(csa_add \"$opts\" -o loop)\n\tfi\n\tmount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||\n\t\treturn $?\n\trc=0\n\tfor f in $files; do\n\t\trm $mntpt/ROOT/$f || { rc=$?; break; }\n\tdone\n\tumount -f $mntpt || return $?\n\treturn $rc\n}\n\nduplicate_mdt_files() {\n\tlocal facet=$1\n\tlocal mdtdev=$2\n\tshift 2\n\tlocal files=\"$@\"\n\tlocal mntpt=$(facet_mntpt $facet)\n\tlocal opts=$MDS_MOUNT_OPTS\n\n\techo \"duplicating files on $mdtdev on $facet: $files\"\n\tmkdir -p $mntpt || return $?\n\tif [ $(facet_fstype $facet) == ldiskfs ] &&\n\t   ! do_facet $facet test -b $mdtdev; then\n\t\topts=$(csa_add \"$opts\" -o loop)\n\tfi\n\tmount -t $(facet_fstype $facet) $opts $mdtdev $mntpt ||\n\t\treturn $?\n\n    do_umount() {\n        trap 0\n        popd > /dev/null\n        rm $tmp\n        umount -f $mntpt\n    }\n    trap do_umount EXIT\n\n    tmp=$(mktemp $TMP/setfattr.XXXXXXXXXX)\n    pushd $mntpt/ROOT > /dev/null || return $?\n    rc=0\n    for f in $files; do\n        touch $f.bad || return $?\n        getfattr -n trusted.lov $f | sed \"s#$f#&.bad#\" > $tmp\n        rc=${PIPESTATUS[0]}\n        [ $rc -eq 0 ] || return $rc\n        setfattr --restore $tmp || return $?\n    done\n    do_umount\n}\n\nrun_sgpdd () {\n    local devs=${1//,/ }\n    shift\n    local params=$@\n    local rslt=$TMP/sgpdd_survey\n\n    # sgpdd-survey cleanups ${rslt}.* files\n\n    local cmd=\"rslt=$rslt $params scsidevs=\\\"$devs\\\" $SGPDDSURVEY\"\n    echo + $cmd\n    eval $cmd\n    cat ${rslt}.detail\n}\n\n# returns the canonical name for an ldiskfs device\nldiskfs_canon() {\n\tlocal dev=\"$1\"\n\tlocal facet=\"$2\"\n\n\tdo_facet $facet \"dv=\\\\\\$($LCTL get_param -n $dev);\n\t\t\t if foo=\\\\\\$(lvdisplay -c \\\\\\$dv 2>/dev/null); then\n\t\t\t\techo dm-\\\\\\${foo##*:};\n\t\t\t else\n\t\t\t\tname=\\\\\\$(basename \\\\\\$dv);\n\t\t\t\tif [[ \\\\\\$name = *flakey* ]]; then\n\t\t\t\t\tname=\\\\\\$(lsblk -o NAME,KNAME |\n\t\t\t\t\t\tawk /\\\\\\$name/'{print \\\\\\$NF}');\n\t\t\t\tfi;\n\t\t\t\techo \\\\\\$name;\n\t\t\t fi;\"\n}\n\nis_sanity_benchmark() {\n    local benchmarks=\"dbench bonnie iozone fsx\"\n    local suite=$1\n    for b in $benchmarks; do\n        if [ \"$b\" == \"$suite\" ]; then\n            return 0\n        fi\n    done\n    return 1\n}\n\nmin_ost_size () {\n\t$LFS df | grep OST | awk '{print $4}' | sort -un | head -1\n}\n\n#\n# Get the available size (KB) of a given obd target.\n#\nget_obd_size() {\n\tlocal facet=$1\n\tlocal obd=$2\n\tlocal size\n\n\t[[ $facet != client ]] || return 0\n\n\tsize=$(do_facet $facet $LCTL get_param -n *.$obd.kbytesavail | head -n1)\n\techo -n $size\n}\n\n#\n# Get the page size (bytes) on a given facet node.\n# The local client page_size is directly available in PAGE_SIZE.\n#\nget_page_size() {\n\tlocal facet=$1\n\tlocal page_size=$(getconf PAGE_SIZE 2>/dev/null)\n\n\t[ -z \"$CLIENTONLY\" -a \"$facet\" != \"client\" ] &&\n\t\tpage_size=$(do_facet $facet getconf PAGE_SIZE)\n\techo -n ${page_size:-4096}\n}\n\n#\n# Get the block count of the filesystem.\n#\nget_block_count() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal count\n\n\t[ -z \"$CLIENTONLY\" ] && count=$(do_facet $facet \"$DUMPE2FS -h $device 2>&1\" |\n\t\tawk '/^Block count:/ {print $3}')\n\techo -n ${count:-0}\n}\n\n# Get the block size of the filesystem.\nget_block_size() {\n\tlocal facet=$1\n\tlocal device=$2\n\tlocal size\n\n\t[ -z \"$CLIENTONLY\" ] && size=$(do_facet $facet \"$DUMPE2FS -h $device 2>&1\" |\n\t\tawk '/^Block size:/ {print $3}')\n\techo -n ${size:-0}\n}\n\n# Check whether the \"ea_inode\" feature is enabled or not, to allow\n# ldiskfs xattrs over one block in size.  Allow both the historical\n# Lustre feature name (large_xattr) and the upstream name (ea_inode).\nlarge_xattr_enabled() {\n\t[[ $(facet_fstype $SINGLEMDS) == zfs ]] && return 1\n\n\tlocal mds_dev=$(mdsdevname ${SINGLEMDS//mds/})\n\n\tdo_facet $SINGLEMDS \"$DUMPE2FS -h $mds_dev 2>&1 |\n\t\tgrep -E -q '(ea_inode|large_xattr)'\"\n\treturn ${PIPESTATUS[0]}\n}\n\n# Get the maximum xattr size supported by the filesystem.\nmax_xattr_size() {\n\t$LCTL get_param -n llite.*.max_easize\n}\n\n# Dump the value of the named xattr from a file.\nget_xattr_value() {\n    local xattr_name=$1\n    local file=$2\n\n    echo \"$(getfattr -n $xattr_name --absolute-names --only-values $file)\"\n}\n\n# Generate a string with size of $size bytes.\ngenerate_string() {\n    local size=${1:-1024} # in bytes\n\n    echo \"$(head -c $size < /dev/zero | tr '\\0' y)\"\n}\n\nreformat_external_journal() {\n\tlocal facet=$1\n\tlocal var\n\n\tvar=${facet}_JRN\n\tif [ -n \"${!var}\" ]; then\n\t\tlocal rcmd=\"do_facet $facet\"\n\n\t\techo \"reformat external journal on $facet:${!var}\"\n\t\t${rcmd} mke2fs -O journal_dev ${!var} || return 1\n\tfi\n}\n\n# MDT file-level backup/restore\nmds_backup_restore() {\n\tlocal facet=$1\n\tlocal igif=$2\n\tlocal devname=$(mdsdevname $(facet_number $facet))\n\tlocal mntpt=$(facet_mntpt brpt)\n\tlocal rcmd=\"do_facet $facet\"\n\tlocal metaea=${TMP}/backup_restore.ea\n\tlocal metadata=${TMP}/backup_restore.tgz\n\tlocal opts=${MDS_MOUNT_FS_OPTS}\n\tlocal svc=${facet}_svc\n\n\tif ! ${rcmd} test -b ${devname}; then\n\t\topts=$(csa_add \"$opts\" -o loop)\n\tfi\n\n\techo \"file-level backup/restore on $facet:${devname}\"\n\n\t# step 1: build mount point\n\t${rcmd} mkdir -p $mntpt\n\t# step 2: cleanup old backup\n\t${rcmd} rm -f $metaea $metadata\n\t# step 3: mount dev\n\t${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1\n\tif [ ! -z $igif ]; then\n\t\t# step 3.5: rm .lustre\n\t\t${rcmd} rm -rf $mntpt/ROOT/.lustre || return 1\n\tfi\n\t# step 4: backup metaea\n\techo \"backup EA\"\n\t${rcmd} \"cd $mntpt && getfattr -R -d -m '.*' -P . > $metaea && cd -\" ||\n\t\treturn 2\n\t# step 5: backup metadata\n\techo \"backup data\"\n\t${rcmd} tar zcf $metadata -C $mntpt/ . > /dev/null 2>&1 || return 3\n\t# step 6: umount\n\t${rcmd} $UMOUNT $mntpt || return 4\n\t# step 8: reformat dev\n\techo \"reformat new device\"\n\tformat_mdt $(facet_number $facet)\n\t# step 9: mount dev\n\t${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 7\n\t# step 10: restore metadata\n\techo \"restore data\"\n\t${rcmd} tar zxfp $metadata -C $mntpt > /dev/null 2>&1 || return 8\n\t# step 11: restore metaea\n\techo \"restore EA\"\n\t${rcmd} \"cd $mntpt && setfattr --restore=$metaea && cd - \" || return 9\n\t# step 12: remove recovery logs\n\techo \"remove recovery logs\"\n\t${rcmd} rm -fv $mntpt/OBJECTS/* $mntpt/CATALOGS\n\t# step 13: umount dev\n\t${rcmd} $UMOUNT $mntpt || return 10\n\t# step 14: cleanup tmp backup\n\t${rcmd} rm -f $metaea $metadata\n\t# step 15: reset device label - it's not virgin on\n\t${rcmd} e2label $devname ${!svc}\n}\n\n# remove OI files\nmds_remove_ois() {\n\tlocal facet=$1\n\tlocal idx=$2\n\tlocal devname=$(mdsdevname $(facet_number $facet))\n\tlocal mntpt=$(facet_mntpt brpt)\n\tlocal rcmd=\"do_facet $facet\"\n\tlocal opts=${MDS_MOUNT_FS_OPTS}\n\n\tif ! ${rcmd} test -b ${devname}; then\n\t\topts=$(csa_add \"$opts\" -o loop)\n\tfi\n\n\techo \"removing OI files on $facet: idx=${idx}\"\n\n\t# step 1: build mount point\n\t${rcmd} mkdir -p $mntpt\n\t# step 2: mount dev\n\t${rcmd} mount -t ldiskfs $opts $devname $mntpt || return 1\n\tif [ -z $idx ]; then\n\t\t# step 3: remove all OI files\n\t\t${rcmd} rm -fv $mntpt/oi.16*\n\telif [ $idx -lt 2 ]; then\n\t\t${rcmd} rm -fv $mntpt/oi.16.${idx}\n\telse\n\t\tlocal i\n\n\t\t# others, rm oi.16.[idx, idx * idx, idx ** ...]\n\t\tfor ((i=${idx}; i<64; i=$((i * idx)))); do\n\t\t\t${rcmd} rm -fv $mntpt/oi.16.${i}\n\t\tdone\n\tfi\n\t# step 4: umount\n\t${rcmd} $UMOUNT $mntpt || return 2\n\t# OI files will be recreated when mounted as lustre next time.\n}\n\n# generate maloo upload-able log file name\n# \\param logname specify unique part of file name\ngenerate_logname() {\n\tlocal logname=${1:-\"default_logname\"}\n\n\techo \"$TESTLOG_PREFIX.$TESTNAME.$logname.$(hostname -s).log\"\n}\n\n# make directory on different MDTs\ntest_mkdir() {\n\tlocal path\n\tlocal p_option\n\tlocal hash_type\n\tlocal hash_name=(\"all_char\" \"fnv_1a_64\" \"crush\")\n\tlocal dirstripe_count=${DIRSTRIPE_COUNT:-\"2\"}\n\tlocal dirstripe_index=${DIRSTRIPE_INDEX:-$((base % $MDSCOUNT))}\n\tlocal OPTIND=1\n\n\twhile getopts \"c:H:i:p\" opt; do\n\t\tcase $opt in\n\t\t\tc) dirstripe_count=$OPTARG;;\n\t\t\tH) hash_type=$OPTARG;;\n\t\t\ti) dirstripe_index=$OPTARG;;\n\t\t\tp) p_option=\"-p\";;\n\t\t\t\\?) error \"only support -c -H -i -p\";;\n\t\tesac\n\tdone\n\n\tshift $((OPTIND - 1))\n\t[ $# -eq 1 ] || error \"Only creating single directory is supported\"\n\tpath=\"$*\"\n\n\tlocal parent=$(dirname $path)\n\tif [ \"$p_option\" == \"-p\" ]; then\n\t\t[ -d $path ] && return 0\n\t\tif [ ! -d ${parent} ]; then\n\t\t\tmkdir -p ${parent} ||\n\t\t\t\terror \"mkdir parent '$parent' failed\"\n\t\tfi\n\tfi\n\n\tif [ $MDSCOUNT -le 1 ] || ! is_lustre ${parent}; then\n\t\tmkdir $path || error \"mkdir '$path' failed\"\n\telse\n\t\tlocal mdt_index\n\n\t\tif [ $dirstripe_index -eq -1 ]; then\n\t\t\tmdt_index=$((base % MDSCOUNT))\n\t\telse\n\t\t\tmdt_index=$dirstripe_index\n\t\tfi\n\n\t\t# randomly choose hash type\n\t\t[ -z \"$hash_type\" ] &&\n\t\t\thash_type=${hash_name[$((RANDOM % ${#hash_name[@]}))]}\n\n\t\tif (($MDS1_VERSION >= $(version_code 2.8.0))); then\n\t\t\tif [ $dirstripe_count -eq -1 ]; then\n\t\t\t\tdirstripe_count=$((RANDOM % MDSCOUNT + 1))\n\t\t\tfi\n\t\telse\n\t\t\tdirstripe_count=1\n\t\tfi\n\n\t\techo \"striped dir -i$mdt_index -c$dirstripe_count -H $hash_type $path\"\n\t\t$LFS mkdir -i$mdt_index -c$dirstripe_count -H $hash_type $path ||\n\t\t\terror \"mkdir -i $mdt_index -c$dirstripe_count -H $hash_type $path failed\"\n\tfi\n}\n\n# free_fd: find the smallest and not in use file descriptor [above @last_fd]\n#\n# If called many times, passing @last_fd will avoid repeated searching\n# already-open FDs repeatedly if we know they are still in use.\n#\n# usage: free_fd [last_fd]\nfree_fd()\n{\n\tlocal max_fd=$(ulimit -n)\n\tlocal fd=$((${1:-2} + 1))\n\n\twhile [[ $fd -le $max_fd && -e /proc/self/fd/$fd ]]; do\n\t\t((++fd))\n\tdone\n\t[ $fd -lt $max_fd ] || error \"finding free file descriptor failed\"\n\techo $fd\n}\n\ncheck_mount_and_prep()\n{\n\tis_mounted $MOUNT || setupall\n\n\trm -rf $DIR/[df][0-9]* || error \"Fail to cleanup the env!\"\n\tmkdir $DIR/$tdir || error \"Fail to mkdir $DIR/$tdir.\"\n\tfor idx in $(seq $MDSCOUNT); do\n\t\tlocal name=\"MDT$(printf '%04x' $((idx - 1)))\"\n\t\trm -rf $MOUNT/.lustre/lost+found/$name/*\n\tdone\n}\n\n# calcule how many ost-objects to be created.\nprecreated_ost_obj_count()\n{\n\tlocal mdt_idx=$1\n\tlocal ost_idx=$2\n\tlocal mdt_name=\"MDT$(printf '%04x' $mdt_idx)\"\n\tlocal ost_name=\"OST$(printf '%04x' $ost_idx)\"\n\tlocal proc_path=\"${FSNAME}-${ost_name}-osc-${mdt_name}\"\n\tlocal last_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \\\n\t\t\tosp.$proc_path.prealloc_last_id)\n\tlocal next_id=$(do_facet mds$((mdt_idx + 1)) lctl get_param -n \\\n\t\t\tosp.$proc_path.prealloc_next_id)\n\techo $((last_id - next_id + 1))\n}\n\ncheck_file_in_pool()\n{\n\tlocal file=$1\n\tlocal pool=$2\n\tlocal tlist=\"$3\"\n\tlocal res=$($LFS getstripe $file | grep 0x | cut -f2)\n\tfor i in $res\n\tdo\n\t\tfor t in $tlist ; do\n\t\t\t[ \"$i\" -eq \"$t\" ] && continue 2\n\t\tdone\n\n\t\techo \"pool list: $tlist\"\n\t\techo \"striping: $res\"\n\t\terror_noexit \"$file not allocated in $pool\"\n\t\treturn 1\n\tdone\n\treturn 0\n}\n\npool_add() {\n\techo \"Creating new pool\"\n\tlocal pool=$1\n\n\tcreate_pool $FSNAME.$pool ||\n\t\t{ error_noexit \"No pool created, result code $?\"; return 1; }\n\t[ $($LFS pool_list $FSNAME | grep -c \"$FSNAME.${pool}\\$\") -eq 1 ] ||\n\t\t{ error_noexit \"$pool not in lfs pool_list\"; return 2; }\n}\n\npool_add_targets() {\n\techo \"Adding targets to pool\"\n\tlocal pool=$1\n\tlocal first=$2\n\tlocal last=$3\n\tlocal step=${4:-1}\n\n\tif [ -z $last ]; then\n\t\tlocal list=$first\n\telse\n\t\tlocal list=$(seq $first $step $last)\n\tfi\n\n\tlocal t=$(for i in $list; do printf \"$FSNAME-OST%04x_UUID \" $i; done)\n\tdo_facet mgs $LCTL pool_add \\\n\t\t\t$FSNAME.$pool $FSNAME-OST[$first-$last/$step]\n\n\t# wait for OSTs to be added to the pool\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$FSNAME-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \\\n\t\t\t\"lctl get_param -n lod.$lodname.pools.$pool |\n\t\t\t\tsort -u | tr '\\n' ' ' \" \"$t\" || {\n\t\t\terror_noexit \"mds$mds_id: Add to pool failed\"\n\t\t\treturn 3\n\t\t}\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n lov.$FSNAME-*.pools.$pool \\\n\t\t\t| sort -u | tr '\\n' ' ' \" \"$t\" || {\n\t\terror_noexit \"Add to pool failed\"\n\t\treturn 1\n\t}\n\tlocal lfscount=$($LFS pool_list $FSNAME.$pool | grep -c \"\\-OST\")\n\tlocal addcount=$(((last - first) / step + 1))\n\t[ $lfscount -eq $addcount ] || {\n\t\terror_noexit \"lfs pool_list bad ost count\" \\\n\t\t\t\t\t\t\"$lfscount != $addcount\"\n\t\treturn 2\n\t}\n}\n\npool_set_dir() {\n\tlocal pool=$1\n\tlocal tdir=$2\n\techo \"Setting pool on directory $tdir\"\n\n\t$LFS setstripe -c 2 -p $pool $tdir && return 0\n\n\terror_noexit \"Cannot set pool $pool to $tdir\"\n\treturn 1\n}\n\npool_check_dir() {\n\tlocal pool=$1\n\tlocal tdir=$2\n\techo \"Checking pool on directory $tdir\"\n\n\tlocal res=$($LFS getstripe --pool $tdir | sed \"s/\\s*$//\")\n\t[ \"$res\" = \"$pool\" ] && return 0\n\n\terror_noexit \"Pool on '$tdir' is '$res', not '$pool'\"\n\treturn 1\n}\n\npool_dir_rel_path() {\n\techo \"Testing relative path works well\"\n\tlocal pool=$1\n\tlocal tdir=$2\n\tlocal root=$3\n\n\tmkdir -p $root/$tdir/$tdir\n\tcd $root/$tdir\n\tpool_set_dir $pool $tdir          || return 1\n\tpool_set_dir $pool ./$tdir        || return 2\n\tpool_set_dir $pool ../$tdir       || return 3\n\tpool_set_dir $pool ../$tdir/$tdir || return 4\n\trm -rf $tdir; cd - > /dev/null\n}\n\npool_alloc_files() {\n\techo \"Checking files allocation from directory pool\"\n\tlocal pool=$1\n\tlocal tdir=$2\n\tlocal count=$3\n\tlocal tlist=\"$4\"\n\n\tlocal failed=0\n\tfor i in $(seq -w 1 $count)\n\tdo\n\t\tlocal file=$tdir/file-$i\n\t\ttouch $file\n\t\tcheck_file_in_pool $file $pool \"$tlist\" || \\\n\t\t\tfailed=$((failed + 1))\n\tdone\n\t[ \"$failed\" = 0 ] && return 0\n\n\terror_noexit \"$failed files not allocated in $pool\"\n\treturn 1\n}\n\npool_create_files() {\n\techo \"Creating files in pool\"\n\tlocal pool=$1\n\tlocal tdir=$2\n\tlocal count=$3\n\tlocal tlist=\"$4\"\n\n\tmkdir -p $tdir\n\tlocal failed=0\n\tfor i in $(seq -w 1 $count)\n\tdo\n\t\tlocal file=$tdir/spoo-$i\n\t\t$LFS setstripe -p $pool $file\n\t\tcheck_file_in_pool $file $pool \"$tlist\" || \\\n\t\t\tfailed=$((failed + 1))\n\tdone\n\t[ \"$failed\" = 0 ] && return 0\n\n\terror_noexit \"$failed files not allocated in $pool\"\n\treturn 1\n}\n\npool_lfs_df() {\n\techo \"Checking 'lfs df' output\"\n\tlocal pool=$1\n\n\tlocal t=$($LCTL get_param -n lov.$FSNAME-clilov-*.pools.$pool |\n\t\t\ttr '\\n' ' ')\n\tlocal res=$($LFS df --pool $FSNAME.$pool |\n\t\t\tawk '{print $1}' |\n\t\t\tgrep \"$FSNAME-OST\" |\n\t\t\ttr '\\n' ' ')\n\t[ \"$res\" = \"$t\" ] && return 0\n\n\terror_noexit \"Pools OSTs '$t' is not '$res' that lfs df reports\"\n\treturn 1\n}\n\npool_file_rel_path() {\n\techo \"Creating files in a pool with relative pathname\"\n\tlocal pool=$1\n\tlocal tdir=$2\n\n\tmkdir -p $tdir ||\n\t\t{ error_noexit \"unable to create $tdir\"; return 1 ; }\n\tlocal file=\"/..$tdir/$tfile-1\"\n\t$LFS setstripe -p $pool $file ||\n\t\t{ error_noexit \"unable to create $file\" ; return 2 ; }\n\n\tcd $tdir\n\t$LFS setstripe -p $pool $tfile-2 || {\n\t\terror_noexit \"unable to create $tfile-2 in $tdir\"\n\t\treturn 3\n\t}\n}\n\npool_remove_first_target() {\n\techo \"Removing first target from a pool\"\n\tpool_remove_target $1 -1\n}\n\npool_remove_target() {\n\tlocal pool=$1\n\tlocal index=$2\n\n\tlocal pname=\"lov.$FSNAME-*.pools.$pool\"\n\tif [ $index -eq -1 ]; then\n\t\tlocal t=$($LCTL get_param -n $pname | head -1)\n\telse\n\t\tlocal t=$(printf \"$FSNAME-OST%04x_UUID\" $index)\n\tfi\n\n\techo \"Removing $t from $pool\"\n\tdo_facet mgs $LCTL pool_remove $FSNAME.$pool $t\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$FSNAME-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \\\n\t\t\t\"lctl get_param -n lod.$lodname.pools.$pool |\n\t\t\t\tgrep $t\" \"\" || {\n\t\t\terror_noexit \"mds$mds_id: $t not removed from\" \\\n\t\t\t\"$FSNAME.$pool\"\n\t\t\treturn 2\n\t\t}\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n $pname | grep $t\" \"\" || {\n\t\terror_noexit \"$t not removed from $FSNAME.$pool\"\n\t\treturn 1\n\t}\n}\n\npool_remove_all_targets() {\n\techo \"Removing all targets from pool\"\n\tlocal pool=$1\n\tlocal file=$2\n\tlocal pname=\"lov.$FSNAME-*.pools.$pool\"\n\tfor t in $($LCTL get_param -n $pname | sort -u)\n\tdo\n\t\tdo_facet mgs $LCTL pool_remove $FSNAME.$pool $t\n\tdone\n\tfor mds_id in $(seq $MDSCOUNT); do\n\t\tlocal mdt_id=$((mds_id-1))\n\t\tlocal lodname=$FSNAME-MDT$(printf \"%04x\" $mdt_id)-mdtlov\n\t\twait_update_facet mds$mds_id \"lctl get_param -n \\\n\t\t\tlod.$lodname.pools.$pool\" \"\" || {\n\t\t\terror_noexit \"mds$mds_id: Pool $pool not drained\"\n\t\t\treturn 4\n\t\t}\n\tdone\n\twait_update $HOSTNAME \"lctl get_param -n $pname\" \"\" || {\n\t\terror_noexit \"Pool $FSNAME.$pool cannot be drained\"\n\t\treturn 1\n\t}\n\t# striping on an empty/nonexistant pool should fall back\n\t# to \"pool of everything\"\n\ttouch $file || {\n\t\terror_noexit \"failed to use fallback striping for empty pool\"\n\t\treturn 2\n\t}\n\t# setstripe on an empty pool should fail\n\t$LFS setstripe -p $pool $file 2>/dev/null && {\n\t\terror_noexit \"expected failure when creating file\" \\\n\t\t\t\t\t\t\t\"with empty pool\"\n\t\treturn 3\n\t}\n\treturn 0\n}\n\npool_remove() {\n\techo \"Destroying pool\"\n\tlocal pool=$1\n\tlocal file=$2\n\n\tdo_facet mgs $LCTL pool_destroy $FSNAME.$pool\n\n\tsleep 2\n\t# striping on an empty/nonexistant pool should fall back\n\t# to \"pool of everything\"\n\ttouch $file || {\n\t\terror_noexit \"failed to use fallback striping for missing pool\"\n\t\treturn 1\n\t}\n\t# setstripe on an empty pool should fail\n\t$LFS setstripe -p $pool $file 2>/dev/null && {\n\t\terror_noexit \"expected failure when creating file\" \\\n\t\t\t\t\t\t\t\"with missing pool\"\n\t\treturn 2\n\t}\n\n\t# get param should return err once pool is gone\n\tif wait_update $HOSTNAME \"lctl get_param -n \\\n\t\tlov.$FSNAME-*.pools.$pool 2>/dev/null || echo foo\" \"foo\"\n\tthen\n\t\tremove_pool_from_list $FSNAME.$pool\n\t\treturn 0\n\tfi\n\terror_noexit \"Pool $FSNAME.$pool is not destroyed\"\n\treturn 3\n}\n\n# Get and check the actual stripe count of one file.\n# Usage: check_stripe_count <file> <expected_stripe_count>\ncheck_stripe_count() {\n\tlocal file=$1\n\tlocal expected=$2\n\tlocal actual\n\n\t[[ -z \"$file\" || -z \"$expected\" ]] &&\n\t\terror \"check_stripe_count: invalid argument\"\n\n\tlocal cmd=\"$LFS getstripe -c $file\"\n\tactual=$($cmd) || error \"$cmd failed\"\n\tactual=${actual%% *}\n\n\tif [[ $actual -ne $expected ]]; then\n\t\t[[ $expected -eq -1 ]] || { $LFS getstripe $file;\n\t\t\terror \"$cmd not expected ($expected): found $actual\"; }\n\t\t[[ $actual -eq $OSTCOUNT ]] || { $LFS getstripe $file;\n\t\t\terror \"$cmd not OST count ($OSTCOUNT): found $actual\"; }\n\tfi\n}\n\n# Get and check the actual list of OST indices on one file.\n# Usage: check_obdidx <file> <expected_comma_separated_list_of_ost_indices>\ncheck_obdidx() {\n\tlocal file=$1\n\tlocal expected=$2\n\tlocal obdidx\n\n\t[[ -z \"$file\" || -z \"$expected\" ]] &&\n\t\terror \"check_obdidx: invalid argument!\"\n\n\tobdidx=$(comma_list $($LFS getstripe $file | grep -A $OSTCOUNT obdidx |\n\t\t\t      grep -v obdidx | awk '{print $1}' | xargs))\n\n\t[[ $obdidx = $expected ]] ||\n\t\terror \"list of OST indices on $file is $obdidx,\" \\\n\t\t      \"should be $expected\"\n}\n\n# Get and check the actual OST index of the first stripe on one file.\n# Usage: check_start_ost_idx <file> <expected_start_ost_idx>\ncheck_start_ost_idx() {\n\tlocal file=$1\n\tlocal expected=$2\n\tlocal start_ost_idx\n\n\t[[ -z \"$file\" || -z \"$expected\" ]] &&\n\t\terror \"check_start_ost_idx: invalid argument!\"\n\n\tstart_ost_idx=$($LFS getstripe $file | grep -A 1 obdidx |\n\t\t\t grep -v obdidx | awk '{print $1}')\n\n\t[[ $start_ost_idx = $expected ]] ||\n\t\terror \"OST index of the first stripe on $file is\" \\\n\t\t      \"$start_ost_idx, should be $expected\"\n}\n\nkillall_process () {\n\tlocal clients=${1:-$(hostname)}\n\tlocal name=$2\n\tlocal signal=$3\n\tlocal rc=0\n\n\tdo_nodes $clients \"killall $signal $name\"\n}\n\nlsnapshot_create()\n{\n\tdo_facet mgs \"$LCTL snapshot_create -F $FSNAME $*\"\n}\n\nlsnapshot_destroy()\n{\n\tdo_facet mgs \"$LCTL snapshot_destroy -F $FSNAME $*\"\n}\n\nlsnapshot_modify()\n{\n\tdo_facet mgs \"$LCTL snapshot_modify -F $FSNAME $*\"\n}\n\nlsnapshot_list()\n{\n\tdo_facet mgs \"$LCTL snapshot_list -F $FSNAME $*\"\n}\n\nlsnapshot_mount()\n{\n\tdo_facet mgs \"$LCTL snapshot_mount -F $FSNAME $*\"\n}\n\nlsnapshot_umount()\n{\n\tdo_facet mgs \"$LCTL snapshot_umount -F $FSNAME $*\"\n}\n\nlss_err()\n{\n\tlocal msg=$1\n\n\tdo_facet mgs \"cat $LSNAPSHOT_LOG\"\n\terror $msg\n}\n\nlss_cleanup()\n{\n\techo \"Cleaning test environment ...\"\n\n\t# Every lsnapshot command takes exclusive lock with others,\n\t# so can NOT destroy the snapshot during list with 'xargs'.\n\twhile true; do\n\t\tlocal ssname=$(lsnapshot_list | grep snapshot_name |\n\t\t\tgrep lss_ | awk '{ print $2 }' | head -n 1)\n\t\t[ -z \"$ssname\" ] && break\n\n\t\tlsnapshot_destroy -n $ssname -f ||\n\t\t\tlss_err \"Fail to destroy $ssname by force\"\n\tdone\n}\n\nlss_gen_conf_one()\n{\n\tlocal facet=$1\n\tlocal role=$2\n\tlocal idx=$3\n\n\tlocal host=$(facet_active_host $facet)\n\tlocal dir=$(dirname $(facet_vdevice $facet))\n\tlocal pool=$(zpool_name $facet)\n\tlocal lfsname=$(zfs_local_fsname $facet)\n\tlocal label=${FSNAME}-${role}$(printf '%04x' $idx)\n\n\tdo_facet mgs \\\n\t\t\"echo '$host - $label zfs:${dir}/${pool}/${lfsname} - -' >> \\\n\t\t$LSNAPSHOT_CONF\"\n}\n\nlss_gen_conf()\n{\n\tdo_facet mgs \"rm -f $LSNAPSHOT_CONF\"\n\techo \"Generating $LSNAPSHOT_CONF on MGS ...\"\n\n\tif ! combined_mgs_mds ; then\n\t\t[ $(facet_fstype mgs) != zfs ] &&\n\t\t\tskip \"Lustre snapshot 1 only works for ZFS backend\"\n\n\t\tlocal host=$(facet_active_host mgs)\n\t\tlocal dir=$(dirname $(facet_vdevice mgs))\n\t\tlocal pool=$(zpool_name mgs)\n\t\tlocal lfsname=$(zfs_local_fsname mgs)\n\n\t\tdo_facet mgs \\\n\t\t\t\"echo '$host - MGS zfs:${dir}/${pool}/${lfsname} - -' \\\n\t\t\t>> $LSNAPSHOT_CONF\" || lss_err \"generate lss conf (mgs)\"\n\tfi\n\n\tfor num in `seq $MDSCOUNT`; do\n\t\t[ $(facet_fstype mds$num) != zfs ] &&\n\t\t\tskip \"Lustre snapshot 1 only works for ZFS backend\"\n\n\t\tlss_gen_conf_one mds$num MDT $((num - 1)) ||\n\t\t\tlss_err \"generate lss conf (mds$num)\"\n\tdone\n\n\tfor num in `seq $OSTCOUNT`; do\n\t\t[ $(facet_fstype ost$num) != zfs ] &&\n\t\t\tskip \"Lustre snapshot 1 only works for ZFS backend\"\n\n\t\tlss_gen_conf_one ost$num OST $((num - 1)) ||\n\t\t\tlss_err \"generate lss conf (ost$num)\"\n\tdone\n\n\tdo_facet mgs \"cat $LSNAPSHOT_CONF\"\n}\n\n# Parse 'lfs getstripe -d <path_with_dir_name>' for non-composite dir\nparse_plain_dir_param()\n{\n\tlocal invalues=($1)\n\tlocal param=\"\"\n\n\tif [[ ${invalues[0]} =~ \"stripe_count:\" ]]; then\n\t\tparam=\"-c ${invalues[1]}\"\n\tfi\n\tif [[ ${invalues[2]} =~ \"stripe_size:\" ]]; then\n\t\tparam=\"$param -S ${invalues[3]}\"\n\tfi\n\tif [[ ${invalues[4]} =~ \"pattern:\" ]]; then\n\t\tif [[ ${invalues[5]} =~ \"stripe_offset:\" ]]; then\n\t\t\tparam=\"$param -i ${invalues[6]}\"\n\t\telse\n\t\t\tparam=\"$param -L ${invalues[5]} -i ${invalues[7]}\"\n\t\tfi\n\telif [[ ${invalues[4]} =~ \"stripe_offset:\" ]]; then\n\t\tparam=\"$param -i ${invalues[5]}\"\n\tfi\n\techo \"$param\"\n}\n\nparse_plain_param()\n{\n\tlocal line=$1\n\tlocal val=$(awk '{print $2}' <<< $line)\n\n\tif [[ $line =~ ^\"lmm_stripe_count:\" ]]; then\n\t\techo \"-c $val\"\n\telif [[ $line =~ ^\"lmm_stripe_size:\" ]]; then\n\t\techo \"-S $val\"\n\telif [[ $line =~ ^\"lmm_stripe_offset:\" ]]; then\n\t\techo \"-i $val\"\n\telif [[ $line =~ ^\"lmm_pattern:\" ]]; then\n\t\techo \"-L $val\"\n\tfi\n}\n\nparse_layout_param()\n{\n\tlocal mode=\"\"\n\tlocal val=\"\"\n\tlocal param=\"\"\n\n\twhile read line; do\n\t\tif [[ ! -z $line ]]; then\n\t\t\tif [[ -z $mode ]]; then\n\t\t\t\tif [[ $line =~ ^\"stripe_count:\" ]]; then\n\t\t\t\t\tmode=\"plain_dir\"\n\t\t\t\telif [[ $line =~ ^\"lmm_stripe_count:\" ]]; then\n\t\t\t\t\tmode=\"plain_file\"\n\t\t\t\telif [[ $line =~ ^\"lcm_layout_gen:\" ]]; then\n\t\t\t\t\tmode=\"pfl\"\n\t\t\t\tfi\n\t\t\tfi\n\n\t\t\tif [[ $mode = \"plain_dir\" ]]; then\n\t\t\t\tparam=$(parse_plain_dir_param \"$line\")\n\t\t\telif [[ $mode = \"plain_file\" ]]; then\n\t\t\t\tval=$(parse_plain_param \"$line\")\n\t\t\t\t[[ ! -z $val ]] && param=\"$param $val\"\n\t\t\telif [[ $mode = \"pfl\" ]]; then\n\t\t\t\tval=$(echo $line | awk '{print $2}')\n\t\t\t\tif [[ $line =~ ^\"lcme_extent.e_end:\" ]]; then\n\t\t\t\t\tif [[ $val = \"EOF\" ]]; then\n\t\t\t\t\t\tparam=\"$param -E -1\"\n\t\t\t\t\telse\n\t\t\t\t\t\tparam=\"$param -E $val\"\n\t\t\t\t\tfi\n\t\t\t\telif [[ $line =~ ^\"stripe_count:\" ]]; then\n\t\t\t\t\t# pfl dir\n\t\t\t\t\tval=$(parse_plain_dir_param \"$line\")\n\t\t\t\t\tparam=\"$param $val\"\n\t\t\t\telse\n\t\t\t\t\t#pfl file\n\t\t\t\t\tval=$(parse_plain_param \"$line\")\n\t\t\t\t\t[[ ! -z $val ]] && param=\"$param $val\"\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\tdone\n\techo \"$param\"\n}\n\nget_layout_param()\n{\n\tlocal param=$($LFS getstripe -d $1 | parse_layout_param)\n\techo \"$param\"\n}\n\nlfsck_verify_pfid()\n{\n\tlocal f\n\tlocal rc=0\n\n\t# Cancel locks before setting lfsck_verify_pfid so that errors are more\n        # controllable\n\tcancel_lru_locks mdc\n\tcancel_lru_locks osc\n\n\t# make sure PFID is set correctly for files\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t       \"$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=1\"\n\n\tfor f in \"$@\"; do\n\t\tcat $f &> /dev/nullA ||\n\t\t\t{ rc=$?; echo \"verify $f failed\"; break; }\n\tdone\n\n\tdo_nodes $(comma_list $(osts_nodes)) \\\n\t       \"$LCTL set_param -n obdfilter.${FSNAME}-OST*.lfsck_verify_pfid=0\"\n\treturn $rc\n}\n\n# check that clients \"oscs\" was evicted after \"before\"\ncheck_clients_evicted() {\n\tlocal before=$1\n\tshift\n\tlocal oscs=${@}\n\tlocal osc\n\tlocal rc=0\n\n\tfor osc in $oscs; do\n\t\t((rc++))\n\t\techo \"Check state for $osc\"\n\t\tlocal evicted=$(do_facet client $LCTL get_param osc.$osc.state |\n\t\t\ttail -n 3 | awk -F\"[ [,]\" \\\n\t\t\t'/EVICTED ]$/ { if (mx<$5) {mx=$5;} } END { print mx }')\n\t\tif (($? == 0)) && (($evicted > $before)); then\n\t\t\techo \"$osc is evicted at $evicted\"\n\t\t\t((rc--))\n\t\tfi\n\tdone\n\n\t[ $rc -eq 0 ] || error \"client not evicted from OST\"\n}\n\n# check that clients OSCS current_state is FULL\ncheck_clients_full() {\n\tlocal timeout=$1\n\tshift\n\tlocal oscs=${@}\n\n\tfor osc in $oscs; do\n\t\twait_update_facet client \\\n\t\t\t\"lctl get_param -n osc.$osc.state |\n\t\t\tgrep 'current_state: FULL'\" \\\n\t\t\t\"current_state: FULL\" $timeout\n\t\t[ $? -eq 0 ] || error \"$osc state is not FULL\"\n\tdone\n}\n\n#Changelogs\n__changelog_deregister() {\n\tlocal facet=$1\n\tlocal mdt=\"$(facet_svc $facet)\"\n\tlocal cl_user=$2\n\tlocal rc=0\n\n\t# skip cleanup if no user registered for this MDT\n\t[ -z \"$cl_user\" ] && echo \"$mdt: no changelog user\" && return 0\n\t# user is no longer registered, skip cleanup\n\tchangelog_users \"$facet\" | grep -q \"$cl_user\" ||\n\t\t{ echo \"$mdt: changelog user '$cl_user' not found\"; return 0; }\n\n\t# From this point, if any operation fails, it is an error\n\t__changelog_clear $facet $cl_user 0 ||\n\t\terror_noexit \"$mdt: changelog_clear $cl_user 0 fail: $rc\"\n\tdo_facet $facet $LCTL --device $mdt changelog_deregister $cl_user ||\n\t\terror_noexit \"$mdt: changelog_deregister '$cl_user' fail: $rc\"\n}\n\ndeclare -Ax CL_USERS\nchangelog_register() {\n\tfor M in $(seq $MDSCOUNT); do\n\t\tlocal facet=mds$M\n\t\tlocal mdt=\"$(facet_svc $facet)\"\n\t\tlocal cl_mask\n\n\t\tcl_mask=$(do_facet $facet $LCTL get_param \\\n\t\t\t     mdd.${mdt}.changelog_mask -n)\n\t\tstack_trap \"do_facet $facet $LCTL \\\n\t\t\tset_param mdd.$mdt.changelog_mask=\\'$cl_mask\\' -n\" EXIT\n\t\tdo_facet $facet $LCTL set_param mdd.$mdt.changelog_mask=+hsm ||\n\t\t\terror \"$mdt: changelog_mask=+hsm failed: $?\"\n\n\t\tlocal cl_user\n\t\tcl_user=$(do_facet $facet \\\n\t\t\t\t  $LCTL --device $mdt changelog_register -n) ||\n\t\t\terror \"$mdt: register changelog user failed: $?\"\n\t\tstack_trap \"__changelog_deregister $facet $cl_user\" EXIT\n\n\t\tstack_trap \"CL_USERS[$facet]='${CL_USERS[$facet]}'\" EXIT\n\t\t# Bash does not support nested arrays, but the format of a\n\t\t# cl_user is constrained enough to use whitespaces as separators\n\t\tCL_USERS[$facet]+=\"$cl_user \"\n\tdone\n\techo \"Registered $MDSCOUNT changelog users: '${CL_USERS[@]% }'\"\n}\n\nchangelog_deregister() {\n\tlocal cl_user\n\t# bash assoc arrays do not guarantee to list keys in created order\n\t# so reorder to get same order than in changelog_register()\n\tlocal cl_facets=$(echo \"${!CL_USERS[@]}\" | tr \" \" \"\\n\" | sort |\n\t\t\t  tr \"\\n\" \" \")\n\n\tfor facet in $cl_facets; do\n\t\tfor cl_user in ${CL_USERS[$facet]}; do\n\t\t\t__changelog_deregister $facet $cl_user || return $?\n\t\tdone\n\t\tunset CL_USERS[$facet]\n\tdone\n}\n\nchangelog_users() {\n\tlocal facet=$1\n\tlocal service=$(facet_svc $facet)\n\n\tdo_facet $facet $LCTL get_param -n mdd.$service.changelog_users\n}\n\nchangelog_user_rec() {\n\tlocal facet=$1\n\tlocal cl_user=$2\n\tlocal service=$(facet_svc $facet)\n\n\tchangelog_users $facet | awk '$1 == \"'$cl_user'\" { print $2 }'\n}\n\nchangelog_chmask() {\n\tlocal mask=$1\n\n\tdo_nodes $(comma_list $(mdts_nodes)) \\\n\t\t$LCTL set_param mdd.*.changelog_mask=\"$mask\"\n}\n\n# usage: __changelog_clear FACET CL_USER [+]INDEX\n__changelog_clear()\n{\n\tlocal facet=$1\n\tlocal mdt=\"$(facet_svc $facet)\"\n\tlocal cl_user=$2\n\tlocal -i rec\n\n\tcase \"$3\" in\n\t+*)\n\t\t# Remove the leading '+'\n\t\trec=${3:1}\n\t\trec+=$(changelog_user_rec $facet $cl_user)\n\t\t;;\n\t*)\n\t\trec=$3\n\t\t;;\n\tesac\n\n\tif [ $rec -eq 0 ]; then\n\t\techo \"$mdt: clear the changelog for $cl_user of all records\"\n\telse\n\t\techo \"$mdt: clear the changelog for $cl_user to record #$rec\"\n\tfi\n\t$LFS changelog_clear $mdt $cl_user $rec\n}\n\n# usage: changelog_clear [+]INDEX\n#\n# If INDEX is prefixed with '+', increment every changelog user's record index\n# by INDEX. Otherwise, clear the changelog up to INDEX for every changelog\n# users.\nchangelog_clear() {\n\tlocal rc\n\t# bash assoc arrays do not guarantee to list keys in created order\n\t# so reorder to get same order than in changelog_register()\n\tlocal cl_facets=$(echo \"${!CL_USERS[@]}\" | tr \" \" \"\\n\" | sort |\n\t\t\t  tr \"\\n\" \" \")\n\n\tfor facet in $cl_facets; do\n\t\tfor cl_user in ${CL_USERS[$facet]}; do\n\t\t\t__changelog_clear $facet $cl_user $1 || rc=${rc:-$?}\n\t\tdone\n\tdone\n\n\treturn ${rc:-0}\n}\n\nchangelog_dump() {\n\tlocal rc\n\n\tfor M in $(seq $MDSCOUNT); do\n\t\tlocal facet=mds$M\n\t\tlocal mdt=\"$(facet_svc $facet)\"\n\t\tlocal output\n\t\tlocal ret\n\n\t\toutput=$($LFS changelog $mdt)\n\t\tret=$?\n\t\tif [ $ret -ne 0 ]; then\n\t\t\trc=${rc:-$ret}\n\t\telif [ -n \"$output\" ]; then\n\t\t\techo \"$output\" | sed -e 's/^/'$mdt'./'\n\t\tfi\n\tdone\n\n\treturn ${rc:-0}\n}\n\nchangelog_extract_field() {\n\tlocal cltype=$1\n\tlocal file=$2\n\tlocal identifier=$3\n\n\tchangelog_dump | gawk \"/$cltype.*$file$/ {\n\t\tprint gensub(/^.* \"$identifier'(\\[[^\\]]*\\]).*$/,\"\\\\1\",1)}' |\n\t\ttail -1\n}\n\n# Prints a changelog record produced by \"lfs changelog\" as an associative array\n#\n# Example:\n# $> changelog2array 16 01CREAT 10:28:46.968438800 2018.03.09 0x0 \\\n#                    t=[0x200000401:0x10:0x0] j=touch.501 ef=0xf u=501:501 \\\n#                    nid=0@lo p=[0x200000007:0x1:0x0] blob\n# ([index]='16' [type]='CREAT' [time]='10:28:46.968438800'\n#  [date]='2018.03.09' [flags]=0x0 ['target-fid']='[0x200000401:0x10:0x0]'\n#  ['jobid']='touch.501' ['extra-flags']='0x0f' [uid]='0' ['gid']='0'\n#  ['nid']='0@lo' ['parent-fid']='[0x200000007:0x1:0x0]')\n#\n# Note that the changelog record is not quoted\n# Also note that the line breaks in the output were only added for readability\n#\n# Typically, you want to eval the output of the command to fill an actual\n# associative array, like this:\n# $> eval declare -A changelog=$(changelog2array $entry)\n#\n# It can then be accessed like any bash associative array:\n# $> echo \"${changelog[index]}\" \"${changelog[type]}\" \"${changelog[flags]}\"\n# 16 CREAT 0x0\n# $> echo \"${changelog[uid]}\":\"${changelog[gid]}\"\n# 501:501\n#\nchangelog2array()\n{\n\t# Start the array\n\tprintf '('\n\n\t# A changelog, as printed by \"lfs changelog\" typically looks like this:\n\t# <index> <type> <time> <date> <flags> <key1=value1> <key2=value2> ...\n\n\t# Parse the positional part of the changelog\n\n\t# changelog_dump() prefixes records with their mdt's name\n\tlocal index=\"${1##*.}\"\n\n\tprintf \"[index]='%s' [type]='%s' [time]='%s' [date]='%s' [flags]='%s'\" \\\n\t       \"$index\" \"${2:2}\" \"$3\" \"$4\" \"$5\"\n\n\t# Parse the key/value part of the changelog\n\tfor arg in \"${@:5}\"; do\n\t\t# Check it matches a key=value syntax\n\t\t[[ \"$arg\" =~ ^[[:alpha:]]+= ]] || continue\n\n\t\tlocal key=\"${arg%%=*}\"\n\t\tlocal value=\"${arg#*=}\"\n\n\t\tcase \"$key\" in\n\t\tu)\n\t\t\t# u is actually for uid AND gid: u=UID:GID\n\t\t\tprintf \" [uid]='%s'\" \"${value%:*}\"\n\t\t\tkey=gid\n\t\t\tvalue=\"${value#*:}\"\n\t\t\t;;\n\t\tt)\n\t\t\tkey=target-fid\n\t\t\tvalue=\"${value#[}\"\n\t\t\tvalue=\"${value%]}\"\n\t\t\t;;\n\t\tj)\n\t\t\tkey=jobid\n\t\t\t;;\n\t\tp)\n\t\t\tkey=parent-fid\n\t\t\tvalue=\"${value#[}\"\n\t\t\tvalue=\"${value%]}\"\n\t\t\t;;\n\t\tef)\n\t\t\tkey=extra-flags\n\t\t\t;;\n\t\tm)\n\t\t\tkey=mode\n\t\t\t;;\n\t\tx)\n\t\t\tkey=xattr\n\t\t\t;;\n\t\t*)\n\t\t\t;;\n\t\tesac\n\n\t\tprintf \" ['%s']='%s'\" \"$key\" \"$value\"\n\tdone\n\n\t# end the array\n\tprintf ')'\n}\n\n# Format and print a changelog record\n#\n# Interpreted sequences are:\n#\t%%\ta single %\n#\t%f\tthe \"flags\" attribute of a changelog record\n__changelog_printf()\n{\n\tlocal format=\"$1\"\n\n\tlocal -i i\n\tfor ((i = 0; i < ${#format}; i++)); do\n\t\tlocal char=\"${format:$i:1}\"\n\t\tif [ \"$char\" != % ]; then\n\t\t\tprintf '%c' \"$char\"\n\t\t\tcontinue\n\t\tfi\n\n\t\ti+=1\n\t\tchar=\"${format:$i:1}\"\n\t\tcase \"$char\" in\n\t\tf)\n\t\t\tprintf '%s' \"${changelog[flags]}\"\n\t\t\t;;\n\t\t%)\n\t\t\tprintf '%'\n\t\t\t;;\n\t\tesac\n\tdone\n\tprintf '\\n'\n}\n\n# Filter changelog records\nchangelog_find()\n{\n\tlocal -A filter\n\tlocal action='print'\n\tlocal format\n\n\twhile [ $# -gt 0 ]; do\n\t\tcase \"$1\" in\n\t\t-print)\n\t\t\taction='print'\n\t\t\t;;\n\t\t-printf)\n\t\t\taction='printf'\n\t\t\tformat=\"$2\"\n\t\t\tshift\n\t\t\t;;\n\t\t-*)\n\t\t\tfilter[${1#-}]=\"$2\"\n\t\t\tshift\n\t\t\t;;\n\t\tesac\n\t\tshift\n\tdone\n\n\tlocal found=false\n\tlocal record\n\tchangelog_dump | { while read -r record; do\n\t\teval local -A changelog=$(changelog2array $record)\n\t\tfor key in \"${!filter[@]}\"; do\n\t\t\tcase \"$key\" in\n\t\t\t*)\n\t\t\t\t[ \"${changelog[$key]}\" == \"${filter[$key]}\" ]\n\t\t\t\t;;\n\t\t\tesac || continue 2\n\t\tdone\n\n\t\tfound=true\n\n\t\tcase \"${action:-print}\" in\n\t\tprint)\n\t\t\tprintf '%s\\n' \"$record\"\n\t\t\t;;\n\t\tprintf)\n\t\t\t__changelog_printf \"$format\"\n\t\t\t;;\n\t\tesac\n\tdone; $found; }\n}\n\nrestore_layout() {\n\tlocal dir=$1\n\tlocal layout=$2\n\n\t[ ! -d \"$dir\" ] && return\n\n\t[ -z \"$layout\" ] && {\n\t\t$LFS setstripe -d $dir || error \"error deleting stripe '$dir'\"\n\t\treturn\n\t}\n\n\tsetfattr -n trusted.lov -v $layout $dir ||\n\t\terror \"error restoring layout '$layout' to '$dir'\"\n}\n\n# save the layout of a directory, the returned string will be used by\n# restore_layout() to restore the layout\nsave_layout() {\n\tlocal dir=$1\n\tlocal str=$(getfattr -n trusted.lov --absolute-names -e hex $dir \\\n\t\t    2> /dev/null | awk -F'=' '/trusted.lov/{ print $2 }')\n\techo \"$str\"\n}\n\n# save layout of a directory and restore it at exit\nsave_layout_restore_at_exit() {\n\tlocal dir=$1\n\tlocal layout=$(save_layout $dir)\n\n\tstack_trap \"restore_layout $dir $layout\" EXIT\n}\n\nverify_yaml_layout() {\n\tlocal src=$1\n\tlocal dst=$2\n\tlocal temp=$3\n\tlocal msg_prefix=$4\n\n\techo \"getstripe --yaml $src\"\n\t$LFS getstripe --yaml $src > $temp || error \"getstripe $src failed\"\n\techo \"setstripe --yaml=$temp $dst\"\n\t$LFS setstripe --yaml=$temp $dst|| error \"setstripe $dst failed\"\n\n\techo \"compare\"\n\tlocal layout1=$(get_layout_param $src)\n\tlocal layout2=$(get_layout_param $dst)\n\t# compare their layout info\n\t[ \"$layout1\" == \"$layout2\" ] ||\n\t\terror \"$msg_prefix $src/$dst layouts are not equal\"\n}\n\nis_project_quota_supported() {\n\t$ENABLE_PROJECT_QUOTAS || return 1\n\n\t[[ \"$(facet_fstype $SINGLEMDS)\" == \"ldiskfs\" &&\n\t   $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.9.55) ]] &&\n\t\tdo_facet mds1 lfs --help |& grep -q project && return 0\n\n\t[[ \"$(facet_fstype $SINGLEMDS)\" == \"zfs\" &&\n\t   $(lustre_version_code $SINGLEMDS) -gt $(version_code 2.10.53) ]] &&\n\t\tdo_facet mds1 $ZPOOL get all | grep -q project_quota && return 0\n\n\treturn 1\n}\n\n# ZFS project quota enable/disable:\n#   This  feature  will  become  active as soon as it is enabled and will never\n#   return to being disabled. Each filesystem will be upgraded automatically\n#   when remounted or when [a] new file is created under that filesystem. The\n#   upgrade can also be triggered on filesystems via `zfs set version=current\n#   <pool/fs>`. The upgrade process runs in the background and may take a\n#   while to complete for the filesystems containing a large number of files.\nenable_project_quota() {\n\tis_project_quota_supported || return 0\n\tlocal zkeeper=${KEEP_ZPOOL}\n\tstack_trap \"KEEP_ZPOOL=$zkeeper\" EXIT\n\tKEEP_ZPOOL=\"true\"\n\tstopall || error \"failed to stopall (1)\"\n\n\tlocal zfeat_en=\"feature@project_quota=enabled\"\n\tfor facet in $(seq -f mds%g $MDSCOUNT) $(seq -f ost%g $OSTCOUNT); do\n\t\tlocal facet_fstype=${facet:0:3}1_FSTYPE\n\t\tlocal devname\n\n\t\tif [ \"${!facet_fstype}\" = \"zfs\" ]; then\n\t\t\tdevname=$(zpool_name ${facet})\n\t\t\tdo_facet ${facet} $ZPOOL set \"$zfeat_en\" $devname ||\n\t\t\t\terror \"$ZPOOL set $zfeat_en $devname\"\n\t\telse\n\t\t\t[ ${facet:0:3} == \"mds\" ] &&\n\t\t\t\tdevname=$(mdsdevname ${facet:3}) ||\n\t\t\t\tdevname=$(ostdevname ${facet:3})\n\t\t\tdo_facet ${facet} $TUNE2FS -O project $devname ||\n\t\t\t\terror \"tune2fs $devname failed\"\n\t\tfi\n\tdone\n\n\tKEEP_ZPOOL=\"${zkeeper}\"\n\tmount\n\tsetupall\n}\n\ndisable_project_quota() {\n\tis_project_quota_supported || return 0\n\t[ \"$mds1_FSTYPE\" != \"ldiskfs\" ] && return 0\n\tstopall || error \"failed to stopall (1)\"\n\n\tfor num in $(seq $MDSCOUNT); do\n\t\tdo_facet mds$num $TUNE2FS -Q ^prj $(mdsdevname $num) ||\n\t\t\terror \"tune2fs $(mdsdevname $num) failed\"\n\tdone\n\n\tfor num in $(seq $OSTCOUNT); do\n\t\tdo_facet ost$num $TUNE2FS -Q ^prj $(ostdevname $num) ||\n\t\t\terror \"tune2fs $(ostdevname $num) failed\"\n\tdone\n\n\tmount\n\tsetupall\n}\n\n#\n# In order to test multiple remote HSM agents, a new facet type named \"AGT\" and\n# the following associated variables are added:\n#\n# AGTCOUNT: number of agents\n# AGTDEV{N}: target HSM mount point (root path of the backend)\n# agt{N}_HOST: hostname of the agent agt{N}\n# SINGLEAGT: facet of the single agent\n#\n# The number of agents is initialized as the number of remote client nodes.\n# By default, only single copytool is started on a remote client/agent. If there\n# was no remote client, then the copytool will be started on the local client.\n#\ninit_agt_vars() {\n\tlocal n\n\tlocal agent\n\n\texport AGTCOUNT=${AGTCOUNT:-$((CLIENTCOUNT - 1))}\n\t[[ $AGTCOUNT -gt 0 ]] || AGTCOUNT=1\n\n\texport SHARED_DIRECTORY=${SHARED_DIRECTORY:-$TMP}\n\tif [[ $CLIENTCOUNT -gt 1 ]] &&\n\t\t! check_shared_dir $SHARED_DIRECTORY $CLIENTS; then\n\t\tskip_env \"SHARED_DIRECTORY should be accessible\"\\\n\t\t\t \"on all client nodes\"\n\t\texit 0\n\tfi\n\n\t# We used to put the HSM archive in $SHARED_DIRECTORY but that\n\t# meant NFS issues could hose sanity-hsm sessions. So now we\n\t# use $TMP instead.\n\tfor n in $(seq $AGTCOUNT); do\n\t\teval export AGTDEV$n=\\$\\{AGTDEV$n:-\"$TMP/arc$n\"\\}\n\t\tagent=CLIENT$((n + 1))\n\t\tif [[ -z \"${!agent}\" ]]; then\n\t\t\t[[ $CLIENTCOUNT -eq 1 ]] && agent=CLIENT1 ||\n\t\t\t\tagent=CLIENT2\n\t\tfi\n\t\teval export agt${n}_HOST=\\$\\{agt${n}_HOST:-${!agent}\\}\n\t\tlocal var=agt${n}_HOST\n\t\t[[ ! -z \"${!var}\" ]] || error \"agt${n}_HOST is empty!\"\n\tdone\n\n\texport SINGLEAGT=${SINGLEAGT:-agt1}\n\n\texport HSMTOOL=${HSMTOOL:-\"lhsmtool_posix\"}\n\texport HSMTOOL_VERBOSE=${HSMTOOL_VERBOSE:-\"\"}\n\texport HSMTOOL_UPDATE_INTERVAL=${HSMTOOL_UPDATE_INTERVAL:=\"\"}\n\texport HSMTOOL_EVENT_FIFO=${HSMTOOL_EVENT_FIFO:=\"\"}\n\texport HSMTOOL_TESTDIR\n\n\tHSM_ARCHIVE_NUMBER=2\n\n\t# The test only support up to 10 MDTs\n\tMDT_PREFIX=\"mdt.$FSNAME-MDT000\"\n\tHSM_PARAM=\"${MDT_PREFIX}0.hsm\"\n\n\t# archive is purged at copytool setup\n\tHSM_ARCHIVE_PURGE=true\n\n\t# Don't allow copytool error upon start/setup\n\tHSMTOOL_NOERROR=false\n}\n\n# Get the backend root path for the given agent facet.\ncopytool_device() {\n\tlocal facet=$1\n\tlocal dev=AGTDEV$(facet_number $facet)\n\n\techo -n ${!dev}\n}\n\nget_mdt_devices() {\n\tlocal mdtno\n\t# get MDT device for each mdc\n\tfor mdtno in $(seq 1 $MDSCOUNT); do\n\t\tlocal idx=$(($mdtno - 1))\n\t\tMDT[$idx]=$($LCTL get_param -n \\\n\t\t\tmdc.$FSNAME-MDT000${idx}-mdc-*.mds_server_uuid |\n\t\t\tawk '{gsub(/_UUID/,\"\"); print $1}' | head -n1)\n\tdone\n}\n\ncopytool_continue() {\n\tlocal agents=${1:-$(facet_active_host $SINGLEAGT)}\n\n\tdo_nodesv $agents \"libtool execute pkill -CONT -x $HSMTOOL\" || return 0\n\techo \"Copytool is continued on $agents\"\n}\n\nkill_copytools() {\n\tlocal hosts=${1:-$(facet_active_host $SINGLEAGT)}\n\n\techo \"Killing existing copytools on $hosts\"\n\tdo_nodesv $hosts \"libtool execute killall -q $HSMTOOL\" || true\n\tcopytool_continue \"$hosts\"\n}\n\ncopytool_monitor_cleanup() {\n\tlocal facet=${1:-$SINGLEAGT}\n\tlocal agent=$(facet_active_host $facet)\n\n\tif [ -n \"$HSMTOOL_MONITOR_DIR\" ]; then\n\t\t# Should die when the copytool dies, but just in case.\n\t\tlocal cmd=\"kill \\\\\\$(cat $HSMTOOL_MONITOR_DIR/monitor_pid)\"\n\t\tcmd+=\" 2>/dev/null || true\"\n\t\tdo_node $agent \"$cmd\"\n\t\tdo_node $agent \"rm -fr $HSMTOOL_MONITOR_DIR\"\n\t\texport HSMTOOL_MONITOR_DIR=\n\tfi\n\n\t# The pdsh should die on its own when the monitor dies. Just\n\t# in case, though, try to clean up to avoid any cruft.\n\tif [ -n \"$HSMTOOL_MONITOR_PDSH\" ]; then\n\t\tkill $HSMTOOL_MONITOR_PDSH 2>/dev/null || true\n\t\texport HSMTOOL_MONITOR_PDSH=\n\tfi\n}\n\ncopytool_logfile()\n{\n\tlocal host=\"$(facet_host \"$1\")\"\n\tlocal prefix=$TESTLOG_PREFIX\n\t[ -n \"$TESTNAME\" ] && prefix+=.$TESTNAME\n\n\tprintf \"${prefix}.copytool${archive_id}_log.${host}.log\"\n}\n\n__lhsmtool_rebind()\n{\n\tdo_facet $facet $HSMTOOL -p \"$hsm_root\" --rebind \"$@\" \"$mountpoint\"\n}\n\n__lhsmtool_import()\n{\n\tmkdir -p \"$(dirname \"$2\")\" ||\n\t\terror \"cannot create directory '$(dirname \"$2\")'\"\n\tdo_facet $facet $HSMTOOL -p \"$hsm_root\" --import \"$@\" \"$mountpoint\"\n}\n\n__lhsmtool_setup()\n{\n\tlocal cmd=\"$HSMTOOL $HSMTOOL_VERBOSE --daemon --hsm-root \\\"$hsm_root\\\"\"\n\t[ -n \"$bandwidth\" ] && cmd+=\" --bandwidth $bandwidth\"\n\t[ -n \"$archive_id\" ] && cmd+=\" --archive $archive_id\"\n\t[ ${#misc_options[@]} -gt 0 ] &&\n\t\tcmd+=\" $(IFS=\" \" echo \"$@\")\"\n\tcmd+=\" \\\"$mountpoint\\\"\"\n\n\techo \"Starting copytool $facet on $(facet_host $facet)\"\n\tstack_trap \"do_facet $facet libtool execute pkill -x '$HSMTOOL' || true\" EXIT\n\tdo_facet $facet \"$cmd < /dev/null > \\\"$(copytool_logfile $facet)\\\" 2>&1\"\n}\n\nhsm_root() {\n\tlocal facet=\"${1:-$SINGLEAGT}\"\n\n\tprintf \"$(copytool_device \"$facet\")/${TESTSUITE}.${TESTNAME}/\"\n}\n\n# Main entry point to perform copytool related operations\n#\n# Sub-commands:\n#\n#\tsetup\tsetup a copytool to run in the background, that copytool will be\n#\t\tkilled on EXIT\n#\timport\timport a file from an HSM backend\n#\trebind\trebind an archived file to a new fid\n#\n# Although the semantics might suggest otherwise, one does not need to 'setup'\n# a copytool before a call to 'copytool import' or 'copytool rebind'.\n#\ncopytool()\n{\n\tlocal action=$1\n\tshift\n\n\t# Use default values\n\tlocal facet=$SINGLEAGT\n\tlocal mountpoint=\"${MOUNT2:-$MOUNT}\"\n\tlocal hsm_root=\"${hsm_root:-$(hsm_root \"$facet\")}\"\n\n\t# Parse arguments\n\tlocal fail_on_error=true\n\tlocal -a misc_options\n\twhile [ $# -gt 0 ]; do\n\t\tcase \"$1\" in\n\t\t-f|--facet)\n\t\t\tshift\n\t\t\tfacet=\"$1\"\n\t\t\t;;\n\t\t-m|--mountpoint)\n\t\t\tshift\n\t\t\tmountpoint=\"$1\"\n\t\t\t;;\n\t\t-a|--archive-id)\n\t\t\tshift\n\t\t\tlocal archive_id=\"$1\"\n\t\t\t;;\n\t\t-h|--hsm-root)\n\t\t\tshift\n\t\t\thsm_root=\"$1\"\n\t\t\t;;\n\t\t-b|--bwlimit)\n\t\t\tshift\n\t\t\tlocal bandwidth=\"$1\" # in MB/s\n\t\t\t;;\n\t\t-n|--no-fail)\n\t\t\tlocal fail_on_error=false\n\t\t\t;;\n\t\t*)\n\t\t\t# Uncommon(/copytool dependent) option\n\t\t\tmisc_options+=(\"$1\")\n\t\t\t;;\n\t\tesac\n\t\tshift\n\tdone\n\n\tstack_trap \"do_facet $facet rm -rf '$hsm_root'\" EXIT\n\tdo_facet $facet mkdir -p \"$hsm_root\" ||\n\t\terror \"mkdir '$hsm_root' failed\"\n\n\tcase \"$HSMTOOL\" in\n\tlhsmtool_posix)\n\t\tlocal copytool=lhsmtool\n\t\t;;\n\tesac\n\n\t__${copytool}_${action} \"${misc_options[@]}\"\n\tif [ $? -ne 0 ]; then\n\t\tlocal error_msg\n\n\t\tcase $action in\n\t\tsetup)\n\t\t\tlocal host=\"$(facet_host $facet)\"\n\t\t\terror_msg=\"Failed to start copytool $facet on '$host'\"\n\t\t\t;;\n\t\timport)\n\t\t\tlocal src=\"${misc_options[0]}\"\n\t\t\tlocal dest=\"${misc_options[1]}\"\n\t\t\terror_msg=\"Failed to import '$src' to '$dest'\"\n\t\t\t;;\n\t\trebind)\n\t\t\terror_msg=\"could not rebind file\"\n\t\t\t;;\n\t\tesac\n\n\t\t$fail_on_error && error \"$error_msg\" || echo \"$error_msg\"\n\tfi\n}\n\nneedclients() {\n\tlocal client_count=$1\n\tif [[ $CLIENTCOUNT -lt $client_count ]]; then\n\t\tskip \"Need $client_count or more clients, have $CLIENTCOUNT\"\n\t\treturn 1\n\tfi\n\treturn 0\n}\n\npath2fid() {\n\t$LFS path2fid $1 | tr -d '[]'\n\treturn ${PIPESTATUS[0]}\n}\n\nget_hsm_flags() {\n\tlocal f=$1\n\tlocal u=$2\n\tlocal st\n\n\tif [[ $u == \"user\" ]]; then\n\t\tst=$($RUNAS $LFS hsm_state $f)\n\telse\n\t\tu=root\n\t\tst=$($LFS hsm_state $f)\n\tfi\n\n\t[[ $? == 0 ]] || error \"$LFS hsm_state $f failed (run as $u)\"\n\n\tst=$(echo $st | cut -f 2 -d\" \" | tr -d \"(),\" )\n\techo $st\n}\n\ncheck_hsm_flags() {\n\tlocal f=$1\n\tlocal fl=$2\n\n\tlocal st=$(get_hsm_flags $f)\n\t[[ $st == $fl ]] || error \"hsm flags on $f are $st != $fl\"\n}\n\nmdts_set_param() {\n\tlocal arg=$1\n\tlocal key=$2\n\tlocal value=$3\n\tlocal mdtno\n\tlocal rc=0\n\tif [[ \"$value\" != \"\" ]]; then\n\t\tvalue=\"=$value\"\n\tfi\n\tfor mdtno in $(seq 1 $MDSCOUNT); do\n\t\tlocal idx=$(($mdtno - 1))\n\t\tlocal facet=mds${mdtno}\n\t\t# if $arg include -P option, run 1 set_param per MDT on the MGS\n\t\t# else, run set_param on each MDT\n\t\t[[ $arg = *\"-P\"* ]] && facet=mgs\n\t\tdo_facet $facet $LCTL set_param $arg mdt.${MDT[$idx]}.$key$value\n\t\t[[ $? != 0 ]] && rc=1\n\tdone\n\treturn $rc\n}\n\nmdts_check_param() {\n\tlocal key=\"$1\"\n\tlocal target=\"$2\"\n\tlocal timeout=\"$3\"\n\tlocal mdtno\n\n\tfor mdtno in $(seq 1 $MDSCOUNT); do\n\t\tlocal idx=$(($mdtno - 1))\n\t\twait_update_facet --verbose mds${mdtno} \\\n\t\t\t\"$LCTL get_param -n $MDT_PREFIX${idx}.$key\" \"$target\" \\\n\t\t\t$timeout ||\n\t\t\terror \"$key state is not '$target' on mds${mdtno}\"\n\tdone\n}\n\ncdt_set_mount_state() {\n\tmdts_set_param \"-P\" hsm_control \"$1\"\n\t# set_param -P is asynchronous operation and could race with set_param.\n\t# In such case configs could be retrieved and applied at mgc after\n\t# set_param -P completion. Sleep here to avoid race with set_param.\n\t# We need at least 20 seconds. 10 for mgc_requeue_thread to wake up\n\t# MGC_TIMEOUT_MIN_SECONDS + MGC_TIMEOUT_RAND_CENTISEC(5 + 5)\n\t# and 10 seconds to retrieve config from server.\n\tsleep 20\n}\n\ncdt_check_state() {\n\tmdts_check_param hsm_control \"$1\" 20\n}\n\ncdt_set_sanity_policy() {\n\tif [[ \"$CDT_POLICY_HAD_CHANGED\" ]]\n\tthen\n\t\t# clear all\n\t\tmdts_set_param \"\" hsm.policy \"+NRA\"\n\t\tmdts_set_param \"\" hsm.policy \"-NBR\"\n\t\tCDT_POLICY_HAD_CHANGED=\n\tfi\n}\n\nset_hsm_param() {\n\tlocal param=$1\n\tlocal value=$2\n\tlocal opt=$3\n\tmdts_set_param \"$opt -n\" \"hsm.$param\" \"$value\"\n\treturn $?\n}\n\nwait_request_state() {\n\tlocal fid=$1\n\tlocal request=$2\n\tlocal state=$3\n\t# 4th arg (mdt index) is optional\n\tlocal mdtidx=${4:-0}\n\tlocal mds=mds$(($mdtidx + 1))\n\n\tlocal cmd=\"$LCTL get_param -n ${MDT_PREFIX}${mdtidx}.hsm.actions\"\n\tcmd+=\" | awk '/'$fid'.*action='$request'/ {print \\\\\\$13}' | cut -f2 -d=\"\n\n\twait_update_facet --verbose $mds \"$cmd\" \"$state\" 200 ||\n\t\terror \"request on $fid is not $state on $mds\"\n}\n\n\nrmultiop_start() {\n\tlocal client=$1\n\tlocal file=$2\n\tlocal cmds=$3\n\tlocal WAIT_MAX=${4:-60}\n\tlocal wait_time=0\n\n\t# We need to run do_node in bg, because pdsh does not exit\n\t# if child process of run script exists.\n\t# I.e. pdsh does not exit when runmultiop_bg_pause exited,\n\t# because of multiop_bg_pause -> $MULTIOP_PROG &\n\t# By the same reason we need sleep a bit after do_nodes starts\n\t# to let runmultiop_bg_pause start muliop and\n\t# update /tmp/multiop_bg.pid ;\n\t# The rm /tmp/multiop_bg.pid guarantees here that\n\t# we have the updated by runmultiop_bg_pause\n\t# /tmp/multiop_bg.pid file\n\n\tlocal pid_file=$TMP/multiop_bg.pid.$$\n\n\tdo_node $client \"MULTIOP_PID_FILE=$pid_file LUSTRE= \\\n\t\t\trunmultiop_bg_pause $file $cmds\" &\n\tlocal pid=$!\n\tlocal multiop_pid\n\n\twhile [[ $wait_time -lt $WAIT_MAX ]]; do\n\t\tsleep 3\n\t\twait_time=$((wait_time + 3))\n\t\tmultiop_pid=$(do_node $client cat $pid_file)\n\t\tif [ -n \"$multiop_pid\" ]; then\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t[ -n \"$multiop_pid\" ] ||\n\t\terror \"$client : Can not get multiop_pid from $pid_file \"\n\n\teval export $(node_var_name $client)_multiop_pid=$multiop_pid\n\teval export $(node_var_name $client)_do_node_pid=$pid\n\tlocal var=$(node_var_name $client)_multiop_pid\n\techo client $client multiop_bg started multiop_pid=${!var}\n\treturn $?\n}\n\nrmultiop_stop() {\n\tlocal client=$1\n\tlocal multiop_pid=$(node_var_name $client)_multiop_pid\n\tlocal do_node_pid=$(node_var_name $client)_do_node_pid\n\n\techo \"Stopping multiop_pid=${!multiop_pid} (kill ${!multiop_pid} on $client)\"\n\tdo_node $client kill -USR1 ${!multiop_pid}\n\n\twait ${!do_node_pid}\n}\n\nsleep_maxage() {\n\tlocal delay=$(do_facet $SINGLEMDS lctl get_param -n lo[vd].*.qos_maxage |\n\t\t      awk '{ print $1 * 2; exit; }')\n\tsleep $delay\n}\n\ncheck_component_count() {\n\tlocal comp_cnt=$($LFS getstripe --component-count $1)\n\t[ $comp_cnt -eq $2 ] || error \"$1, component count $comp_cnt != $2\"\n}\n\n# Verify there are no init components with \"extension\" flag\nverify_no_init_extension() {\n\tlocal flg_opts=\"--component-flags init,extension\"\n\tlocal found=$($LFS find $flg_opts $1 | wc -l)\n\t[ $found -eq 0 ] || error \"$1 has component with initialized extension\"\n}\n\n# Verify there is at least one component starting at 0\nverify_comp_at_zero() {\n\tflg_opts=\"--component-flags init\"\n\tfound=$($LFS find --component-start 0M $flg_opts $1 | wc -l)\n\t[ $found -eq 1 ] ||\n\t\terror \"No component starting at zero(!)\"\n}\n\n# version after which Self-Extending Layouts are available\nSEL_VER=\"2.12.55\"\n\nsel_layout_sanity() {\n\tlocal file=$1\n\tlocal comp_cnt=$2\n\n\tverify_no_init_extension $file\n\tverify_comp_at_zero $file\n\tcheck_component_count $file $comp_cnt\n}\n\nstatx_supported() {\n\t$STATX --quiet --version\n\treturn $?\n}\n\n#\n# wrappers for createmany and unlinkmany\n# to set debug=0 if number of creates is high enough\n# this is to speedup testing\n#\nfunction createmany() {\n\tlocal count=${!#}\n\n\t(( count > 100 )) && {\n\t\tlocal saved_debug=$($LCTL get_param -n debug)\n\t\tlocal list=$(comma_list $(all_nodes))\n\n\t\tdo_nodes $list $LCTL set_param debug=0\n\t}\n\t$LUSTRE/tests/createmany $*\n\tlocal rc=$?\n\t(( count > 100 )) &&\n\t\tdo_nodes $list \"$LCTL set_param debug=\\\\\\\"$saved_debug\\\\\\\"\"\n\treturn $rc\n}\n\nfunction unlinkmany() {\n\tlocal count=${!#}\n\n\t(( count > 100 )) && {\n\t\tlocal saved_debug=$($LCTL get_param -n debug)\n\t\tlocal list=$(comma_list $(all_nodes))\n\n\t\tdo_nodes $list $LCTL set_param debug=0\n\t}\n\t$LUSTRE/tests/unlinkmany $*\n\tlocal rc=$?\n\t(( count > 100 )) &&\n\t\tdo_nodes $list \"$LCTL set_param debug=\\\\\\\"$saved_debug\\\\\\\"\"\n\treturn $rc\n}\n", "num_lines": 10499}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# vim:shiftwidth=4:softtabstop=4:tabstop=4:\n\n#\n# Shell routines for logging results to a yaml file.\n#\n\nsplit_output() {\n    while read line; do\n        host=${line%%:*};\n        echo \"$line\" | sed \"s/^${host}: //\" | sed \"s/^${host}://\" \\\n            >> $logdir/node.$host.yml;\n    done\n}\n\nyml_nodes_file() {\n    export logdir=$1\n\n    if [ -f $logdir/shared ]; then\n        do_rpc_nodes $(comma_list $(all_nodes)) \\\n            \"yml_node >> $logdir/node.\\\\\\$(hostname -s).yml\"\n    else\n        do_rpc_nodes $(comma_list $(all_nodes)) yml_node | split_output\n    fi\n    yml_entities\n}\n\nyml_results_file() {\n    export logdir=$1\n\n    #TestGroup\n    yml_test_group\n\n    #CodeReview\n    yml_code_review\n\n    # Tests\n    printf \"Tests:\\n\"\n}\n\n# Called on the node for which we the info is needed.\nyml_node() {\n    logdir=$1\n\n    printf \"Build:\\n\"\n    yml_build_info\n    printf \"\\n\"\n\n    printf \"Node:\\n\"\n    yml_node_info\n    printf \"\\n\"\n\n    printf \"LustreEntities:\\n\"\n}\n\nyml_test_group() {\n    TEST_GROUP=${TEST_GROUP:-\"acc-sm-$(hostname -s)\"}\n    TEST_HOST=${TEST_HOST:-$(hostname -s)}\n    TEST_USER=${TEST_USER:-$USER}\n    TEST_PROJECT=${TEST_PROJECT:-\"LUSTRE\"}\n\n    # TestGroup information\n    cat <<EOF\nTestGroup:\n    test_group: $TEST_GROUP\n    testhost: $TEST_HOST\n    submission: $(date)\n    user_name: $TEST_USER\nproject: $TEST_PROJECT\nEOF\n}\n\nyml_code_review() {\n    echo -e $CODE_REVIEW_YAML\n}\n\nrelease() {\n\tif [ -r /etc/SuSE-release ]; then\n\t\tname=$(awk '/SUSE/ { printf(\"%s %s %s %s\", $1, $2, $3, $4) }' \\\n\t\t\t/etc/SuSE-release)\n\t\tversion=$(sed -n -e 's/^VERSION = //p' /etc/SuSE-release)\n\t\tlevel=$(sed -n -e 's/^PATCHLEVEL = //p' /etc/SuSE-release)\n\t\tdist=\"${name} ${version}.${level}\"\n\telif [ -r /etc/os-release ]; then\n\t\tname=$(sed -n -e 's/\"//g' -e 's/^NAME=//p' /etc/os-release)\n\t\tversion=$(sed -n -e 's/\"//g' -e 's/^VERSION_ID=//p' \\\n\t\t\t/etc/os-release)\n\t\tdist=\"${name} ${version}\"\n\telif [ -r /etc/system-release ]; then\n\t\tdist=$(awk '/release/ \\\n\t\t\t{ printf(\"%s %s %s\", $1, $2, $3) }' \\\n\t\t\t/etc/system-release)\n\telif [ -r /etc/*-release ]; then\n\t\tdist=$(find /etc/ -maxdepth 1 -name '*release' 2> /dev/null | \\\n\t\t\tsed -e 's/\\/etc\\///' -e 's/-release//' | head -n1)\n\telse\n\t\tdist=\"UNKNOWN\"\n\tfi\n\n\techo $dist\n}\n\nyml_build_info() {\n\tlocal TEST_DISTRO=$(release)\n\tlocal LUSTRE_VERSION=$(lustre_build_version)\n\tlocal LUSTRE_BUILD=${LUSTRE_BUILD_SOURCE:-$LUSTRE_VERSION}\n\tlocal FILE_SYSTEM=$(node_fstypes $(hostname -s))\n\ncat <<EOF\n    lbats_build_id: $LBATS_ID\n    lbats_build_name: $LBATS_NAME\n    architecture: $(uname -m)\n    os: $(uname -o)\n    os_distribution: $TEST_DISTRO\n    lustre_version: $LUSTRE_VERSION\n    lustre_build: $LUSTRE_BUILD\n    lustre_branch: $LUSTRE_BRANCH\n    lustre_revision: $LUSTRE_REVISION\n    kernel_version: $(uname -r)\n    file_system: ${FILE_SYSTEM:-\"NA\"}\nEOF\n}\n\nyml_node_info()\n{\n    mem=$(awk '/MemTotal:/ {print $2 \" \" $3}' /proc/meminfo)\ncat <<EOF\n    node_name: $(hostname -s)\n    mem_size: $mem\n    architecture: $(uname -m)\n    networks:\nEOF\n    for nw in $(lctl list_nids | grep -v @lo | cut -f 2 -d '@' | uniq); do\n        printf \"        - $nw\\n\"\n    done\n}\n\nyml_entity() {\n    cat<<EOF\n-\n    node_type: $1\n    node_name: $2\nEOF\n}\n\nyml_entities() {\n\tlocal host\n\tlocal f_host\n\tlocal i\n\n\tif ! combined_mgs_mds; then\n\t\thost=$(short_hostname $(facet_active_host mgs))\n\t\tf_host=$(short_hostname $(facet_passive_host mgs))\n\n\t\tyml_entity \"MGS\" $host >> $logdir/node.$host.yml\n\t\t[[ -n $f_host ]] &&\n\t\t\tyml_entity \"MGS\" $f_host >> $logdir/node.$f_host.yml\n\tfi\n\n\tfor i in $(seq $MDSCOUNT); do\n\t\thost=$(short_hostname $(facet_active_host mds$i))\n\t\tf_host=$(short_hostname $(facet_passive_host mds$i))\n\n\t\tyml_entity \"MDS $i\" $host >> $logdir/node.$host.yml\n\t\t[[ -n $f_host ]] &&\n\t\t\tyml_entity \"MDS $i\" $f_host >> $logdir/node.$f_host.yml\n\tdone\n\n\tfor i in $(seq $OSTCOUNT); do\n\t\thost=$(short_hostname $(facet_active_host ost$i))\n\t\tf_host=$(short_hostname $(facet_passive_host ost$i))\n\n\t\tyml_entity \"OST $i\" $host >> $logdir/node.$host.yml\n\t\t[[ -n $f_host ]] &&\n\t\t\tyml_entity \"OST $i\" $f_host >> $logdir/node.$f_host.yml\n\tdone\n\n\ti=1\n\tfor host in ${CLIENTS//,/ }; do\n\t\thost=$(short_hostname $host)\n\t\tyml_entity \"Client $i\" $host >> $logdir/node.$host.yml\n\t\ti=$((i+1))\n\tdone\n}\n\nyml_log_test() {\n    if [ $1 != \"FINISHED\" ]; then\n        cat <<EOF\n-\n        name: $1\n        description: $TESTSUITE $1\n        submission: $(date)\n        report_version: 2\n        SubTests:\nEOF\n    fi\n}\n\nyml_log_test_status() {\n    cat <<EOF\n        duration: $1\n        status: $2\nEOF\n}\n\nyml_log_sub_test_begin() {\n    cat <<EOF\n        -\n            name: $1\nEOF\n}\n\nyml_log_sub_test_end() {\n    cat <<EOF\n            status: $1\n            duration: $2\n            return_code: $3\nEOF\n    shift 3\n    if [ -z \"$*\" ]; then\n        printf '            error:\\n'\n    else\n        printf '            error: \"%q\"\\n' \"$*\"\n    fi\n}\n\nyml_log_sub_test_log() {\n    cat <<EOF\n        -\n            name: $1\n            type: $2\n            location: $3\nEOF\n}\n", "num_lines": 235}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "FSNAME=${FSNAME:-lustre}\n\n# facet hosts\nmds_HOST=${mds_HOST:-$(hostname)}\nmdsfailover_HOST=${mdsfailover_HOST}\nmgs_HOST=${mgs_HOST:-$mds_HOST}\nost_HOST=${ost_HOST:-$(hostname)}\nostfailover_HOST=${ostfailover_HOST}\nCLIENTS=\"\"\n# FILESET variable is used by sanity.sh to verify fileset\n# feature, tests should pass even under subdirectory namespace.\nFILESET=${FILESET:-\"\"}\n[[ -z \"$FILESET\" ]] || [[ \"${FILESET:0:1}\" = \"/\" ]] || FILESET=\"/$FILESET\"\n\nTMP=${TMP:-/tmp}\n\nDAEMONSIZE=${DAEMONSIZE:-500}\nMDSCOUNT=${MDSCOUNT:-1}\nMDSDEVBASE=${MDSDEVBASE:-$TMP/${FSNAME}-mdt}\nMDSSIZE=${MDSSIZE:-250000}\n#\n# Format options of facets can be specified with these variables:\n#\n#   - <facet_type>OPT\n#\n# Arguments for \"--mkfsoptions\" shall be specified with these\n# variables:\n#\n#   - <fstype>_MKFS_OPTS\n#   - <facet_type>_FS_MKFS_OPTS\n#\n# A number of other options have their own specific variables.  See\n# mkfs_opts().\n#\nMDSOPT=${MDSOPT:-}\nMDS_FS_MKFS_OPTS=${MDS_FS_MKFS_OPTS:-}\nMDS_MOUNT_OPTS=${MDS_MOUNT_OPTS:-}\n# <facet_type>_MOUNT_FS_OPTS is the mount options specified when formatting\n# the underlying device by argument \"--mountfsoptions\"\nMDS_MOUNT_FS_OPTS=${MDS_MOUNT_FS_OPTS:-}\n\nMGSSIZE=${MGSSIZE:-$MDSSIZE}\nMGSOPT=${MGSOPT:-}\nMGS_FS_MKFS_OPTS=${MGS_FS_MKFS_OPTS:-}\nMGS_MOUNT_OPTS=${MGS_MOUNT_OPTS:-}\nMGS_MOUNT_FS_OPTS=${MGS_MOUNT_FS_OPTS:-}\n\nOSTCOUNT=${OSTCOUNT:-2}\nOSTDEVBASE=${OSTDEVBASE:-$TMP/${FSNAME}-ost}\nOSTSIZE=${OSTSIZE:-400000}\nOSTOPT=${OSTOPT:-}\nOST_FS_MKFS_OPTS=${OST_FS_MKFS_OPTS:-}\nOST_MOUNT_OPTS=${OST_MOUNT_OPTS:-}\nOST_MOUNT_FS_OPTS=${OST_MOUNT_FS_OPTS:-}\nOST_INDEX_LIST=${OST_INDEX_LIST:-}\n# Can specify individual ost devs with\n# OSTDEV1=\"/dev/sda\"\n# on specific hosts with\n# ost1_HOST=\"uml2\"\n# ost1_JRN=\"/dev/sdb1\"\n#\n# For ZFS, ost devices can be specified via either or both of the following:\n# OSTZFSDEV1=\"${FSNAME}-ost1/ost1\"\n# OSTDEV1=\"/dev/sdb1\"\n#\n# OST indices can be specified as follows:\n# OSTINDEX1=\"1\"\n# OSTINDEX2=\"2\"\n# OSTINDEX3=\"4\"\n# ......\n# or\n# OST_INDEX_LIST=\"[1,2,4-6,8]\"\t# [n-m,l-k,...], where n < m and l < k, etc.\n#\n# The default index value of an individual OST is its facet number minus 1.\n# More specific ones override more general ones. See facet_index().\n\nNETTYPE=${NETTYPE:-tcp}\nMGSNID=${MGSNID:-$(h2nettype $mgs_HOST)}\n\n#\n# Back end file system type(s) of facets can be specified with these\n# variables:\n#\n#   1. <facet>_FSTYPE\n#   2. <facet_type>FSTYPE\n#   3. FSTYPE\n#\n# More specific ones override more general ones.  See facet_fstype().\n#\nFSTYPE=${FSTYPE:-ldiskfs}\n\nLDISKFS_MKFS_OPTS=${LDISKFS_MKFS_OPTS:-}\nZFS_MKFS_OPTS=${ZFS_MKFS_OPTS:-}\n\nLOAD_MODULES_REMOTE=${LOAD_MODULES_REMOTE:-false}\n\nDEF_STRIPE_SIZE=${DEF_STRIPE_SIZE:-}   # filesystem default stripe size in bytes\nDEF_STRIPE_COUNT=${DEF_STRIPE_COUNT:-} # filesystem default stripe count\nTIMEOUT=${TIMEOUT:-20}\nPTLDEBUG=${PTLDEBUG:-\"vfstrace rpctrace dlmtrace neterror ha config \\\n\t\t      ioctl super lfsck\"}\nSUBSYSTEM=${SUBSYSTEM:-\"all\"}\n\n# promise 2MB for every cpu\nif [ -f /sys/devices/system/cpu/possible ]; then\n    _debug_mb=$((($(cut -d \"-\" -f 2 /sys/devices/system/cpu/possible)+1)*2))\nelse\n    _debug_mb=$(($(getconf _NPROCESSORS_CONF)*2))\nfi\n\nDEBUG_SIZE=${DEBUG_SIZE:-$_debug_mb}\n\nENABLE_QUOTA=${ENABLE_QUOTA:-\"\"}\nQUOTA_TYPE=${QUOTA_TYPE:-\"ug3\"}\nQUOTA_USERS=${QUOTA_USERS:-\"quota_usr quota_2usr sanityusr sanityusr1\"}\n# \"error: conf_param: No such device\" issue in every test suite logs\n# sanity-quota test_32 hash_lqs_cur_bits is not set properly\nLQUOTAOPTS=${LQUOTAOPTS:-\"hash_lqs_cur_bits=3\"}\n\n#client\nMOUNT=${MOUNT:-/mnt/${FSNAME}}\nMOUNT1=${MOUNT1:-$MOUNT}\nMOUNT2=${MOUNT2:-${MOUNT}2}\nMOUNT3=${MOUNT3:-${MOUNT}3}\n# Comma-separated option list used as \"mount [...] -o $MOUNT_OPTS [...]\"\nMOUNT_OPTS=${MOUNT_OPTS:-\"user_xattr,flock\"}\n# Mount flags (e.g. \"-n\") used as \"mount [...] $MOUNT_FLAGS [...]\"\nMOUNT_FLAGS=${MOUNT_FLAGS:-\"\"}\nDIR=${DIR:-$MOUNT}\nDIR1=${DIR:-$MOUNT1}\nDIR2=${DIR2:-$MOUNT2}\nDIR3=${DIR3:-$MOUNT3}\n\nif [ $UID -ne 0 ]; then\n        log \"running as non-root uid $UID\"\n        RUNAS_ID=\"$UID\"\n        RUNAS_GID=`id -g $USER`\n        RUNAS=\"\"\nelse\n        RUNAS_ID=${RUNAS_ID:-500}\n        RUNAS_GID=${RUNAS_GID:-$RUNAS_ID}\n        RUNAS=${RUNAS:-\"runas -u $RUNAS_ID -g $RUNAS_GID\"}\nfi\n\nPDSH=${PDSH:-no_dsh}\nFAILURE_MODE=${FAILURE_MODE:-SOFT} # or HARD\nPOWER_DOWN=${POWER_DOWN:-\"powerman --off\"}\nPOWER_UP=${POWER_UP:-\"powerman --on\"}\nSLOW=${SLOW:-no}\nFAIL_ON_ERROR=${FAIL_ON_ERROR:-true}\n\nMPIRUN=${MPIRUN:-$(which mpirun 2>/dev/null || true)}\nMPI_USER=${MPI_USER:-mpiuser}\nSHARED_DIR_LOGS=${SHARED_DIR_LOGS:-\"\"}\nMACHINEFILE_OPTION=${MACHINEFILE_OPTION:-\"-machinefile\"}\n\n# This is used by a small number of tests to share state between the client\n# running the tests, or in some cases between the servers (e.g. lfsck.sh).\n# It needs to be a non-lustre filesystem that is available on all the nodes.\nSHARED_DIRECTORY=${SHARED_DIRECTORY:-$TMP}\t# bug 17839 comment 65\n\n#\n# In order to test multiple remote HSM agents, a new facet type named \"AGT\" and\n# the following associated variables are added:\n#\n# AGTCOUNT: number of agents\n# AGTDEV{N}: target HSM mount point (root path of the backend)\n# agt{N}_HOST: hostname of the agent agt{N}\n# SINGLEAGT: facet of the single agent\n#\n# Please refer to init_agt_vars() in sanity-hsm.sh for the default values of\n# these variables.\n#\n", "num_lines": 174}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": ". $LUSTRE/tests/cfg/local.sh\n\n# For multiple clients testing, we need use the cfg/ncli.sh config file, and\n# only need specify the \"RCLIENTS\" variable. The \"CLIENTS\" and \"CLIENTCOUNT\"\n# variables are defined in init_clients_lists(), called from cfg/ncli.sh.\nCLIENT1=${CLIENT1:-$(hostname)}\nSINGLECLIENT=$CLIENT1\nRCLIENTS=${RCLIENTS:-\"\"}\n\ninit_clients_lists\n\n[ -n \"$RCLIENTS\" -a \"$PDSH\" = \"no_dsh\" ] &&\n\terror \"tests for remote clients $RCLIENTS needs pdsh != do_dsh \" || true\n\n[ -n \"$FUNCTIONS\" ] && . $FUNCTIONS || true\n\n# for recovery scale tests\n# default boulder cluster iozone location\nexport PATH=/opt/iozone/bin:$PATH\n\nLOADS=${LOADS:-\"dd tar dbench iozone\"}\nfor i in $LOADS; do\n\t[ -f $LUSTRE/tests/run_${i}.sh ] || error \"incorrect load: $i\"\ndone\nCLIENT_LOADS=($LOADS)\n\n# This is used when testing on SLURM environment.\n# Test will use srun when SRUN_PARTITION is set\nSRUN=${SRUN:-$(which srun 2>/dev/null || true)}\nSRUN_PARTITION=${SRUN_PARTITION:-\"\"}\nSRUN_OPTIONS=${SRUN_OPTIONS:-\"-W 1800 -l -O\"}\n", "num_lines": 32}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\ncreate(){\n    echo \"asdf\" > $DIR/$file/$file/$file\n}\n\nwhile /bin/true ; do\n    file=$((RANDOM % MAX))\n    mkdir -p $DIR/$file/$file/ 2> /dev/null\n    create 2> /dev/null\ndone\n", "num_lines": 16}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nMDTCOUNT=${MDSCOUNT:-$($LFS df $DIR 2> /dev/null | grep -c MDT)}\nwhile /bin/true ; do\n\tmigrate_dir=$((RANDOM % MAX))\n\tfile=$((RANDOM % MAX))\n\tmdt_idx=$((RANDOM % MDTCOUNT))\n\tmkdir -p $DIR/$migrate_dir 2> /dev/null\n\t$LFS mv -M$mdt_idx $DIR/$migrate_dir 2> /dev/null\n\ttouch $DIR/$migrate_dir/$file 2> /dev/null\n\t$LFS getdirstripe $DIR/$migrate_dir > /dev/null 2>&1\ndone\n", "num_lines": 17}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nMDTCOUNT=${MDSCOUNT:-$($LFS df $DIR 2> /dev/null | grep -c MDT)}\nwhile /bin/true ; do\n\tremote_dir=$((RANDOM % MAX))\n\tfile=$((RANDOM % MAX))\n\tmdt_idx=$((RANDOM % MDTCOUNT))\n\n\tif $RACER_ENABLE_STRIPED_DIRS; then\n\t\t# stripe_count in range [1,MDTCOUNT]\n\t\t# $LFS mkdir treats stripe_count 0 and 1 the same\n\t\tstripe_count_opt=\"-c$((RANDOM % MDTCOUNT + 1))\"\n\telse\n\t\tstripe_count_opt=\"\"\n\tfi\n\n\t$LFS mkdir -i$mdt_idx $stripe_count_opt $DIR/$remote_dir 2> /dev/null\n\ttouch $DIR/$remote_dir/$file 2> /dev/null\n\t$LFS getdirstripe $DIR/$remote_dir > /dev/null 2>&1\ndone\n", "num_lines": 25}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\tmode=$(printf '%o' $((RANDOM % 010000)))\n\tchmod $mode $file 2> /dev/null\ndone\n", "num_lines": 12}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\tchown $RANDOM:$RANDOM $file 2> /dev/null\ndone\n", "num_lines": 11}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nconcat(){\n    cat $DIR/$file >> $DIR/$new_file\n    cat $DIR/$file/$file/$file >> $DIR/$new_file\n\n}\n\nwhile /bin/true ; do\n    file=$((RANDOM % MAX))\n    new_file=$((RANDOM % MAX))\n    concat 2> /dev/null\ndone\n", "num_lines": 18}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\nRACER_ENABLE_PFL=${RACER_ENABLE_PFL:-true}\nRACER_ENABLE_DOM=${RACER_ENABLE_DOM:-true}\nRACER_ENABLE_FLR=${RACER_ENABLE_FLR:-true}\nRACER_ENABLE_SEL=${RACER_ENABLE_SEL:-true}\nDIR=$1\nMAX=$2\nMAX_MB=${RACER_MAX_MB:-8}\n\nlayout=(raid0 raid0)\n\n# check if it supports PFL layout\n$RACER_ENABLE_PFL && layout+=(pfl pfl pfl)\n\n# check if it supports DoM\n$RACER_ENABLE_DOM && layout+=(dom dom dom)\n\n# check if it supports FLR\n$RACER_ENABLE_FLR && layout+=(flr flr flr)\n\n# check if it supports PFL layout\n$RACER_ENABLE_SEL && layout+=(sel sel sel)\n\necho \"layout: ${layout[*]}\"\n\nwhile /bin/true; do\n\tfile=$((RANDOM % MAX))\n\t# $RANDOM is between 0 and 32767, and we want $blockcount in 64kB units\n\tblockcount=$((RANDOM * MAX_MB / 32 / 64))\n\tstripecount=$((RANDOM % (OSTCOUNT + 1)))\n\n\t[ $stripecount -gt 0 ] && {\n\t\tstripesize=$(((1 << (RANDOM % 5)) * 64))K\n\t\tcomp_end=$((${stripesize%K} * (RANDOM % 8 + 1)))K\n\t\tpattern=${layout[$RANDOM % ${#layout[*]}]}\n\n\t\tcase $pattern in\n\t\tdom) opt=\"setstripe -E $stripesize -L mdt -E eof -c $stripecount -S 1M\" ;;\n\t\tpfl) opt=\"setstripe -E $comp_end -S $stripesize -E eof -c $stripecount -S 2M\" ;;\n\t\tflr) opt=\"mirror create -N2 -E $comp_end -S $stripesize -E eof -c $stripecount -S 2M\" ;;\n\t\tsel) opt=\"setstripe -E 128M -S $stripesize -z 64M -E eof -c $stripecount -S 2M -z 128M\" ;;\n\t\traid0) opt=\"setstripe -S $stripesize -c $stripecount\" ;;\n\t\tesac\n\n\t\t$LFS $opt $DIR/$file 2> /dev/null || true\n\t}\n\n\t# offset between 0 and 16MB (256 64k chunks), with 1/2 at offset 0\n\tseek=$((RANDOM / 64)); [ $seek -gt 256 ] && seek=0\n\tdd if=/dev/zero of=$DIR/$file bs=64k count=$blockcount \\\n\t\tseek=$seek 2> /dev/null || true\ndone\n\n", "num_lines": 55}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\tattr=user.$((RANDOM % MAX))\n\tsetfattr -x $attr $file 2>/dev/null\ndone\n", "num_lines": 12}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\norg_LANG=$LANG\nexport LANG=C\n\nDIR=$1\nMAX=$2\nPROG=/bin/sleep\n\nwhile /bin/true ; do\n\tfile=$((RANDOM % MAX))\n\tcp -p $PROG $DIR/$file > /dev/null 2>&1\n\t$DIR/$file 0.$((RANDOM % 5 + 1)) 2> /dev/null\n\tsleep $((RANDOM % 3))\ndone 2>&1 | egrep -v \"Segmentation fault|Bus error\"\n\nexport LANG=$org_LANG\n", "num_lines": 19}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\tgetfattr -d -m- $file &> /dev/null\ndone\n", "num_lines": 11}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\told_path=$DIR/$((RANDOM % MAX))\n\tnew_path=$DIR/$((RANDOM % MAX))\n\tln $old_path $new_path 2> /dev/null\ndone\n", "num_lines": 12}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile /bin/true ; do\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n    ls -R $DIR/ > /dev/null 2> /dev/null &\n\n    wait\n    sleep 1\ndone\n", "num_lines": 23}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nMCREATE=${MCREATE:-$LUSTRE/tests/mcreate}\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\t$MCREATE $file 2> /dev/null\ndone\n", "num_lines": 13}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile /bin/true ; do\n    file=$((RANDOM % MAX))\n    new_file=$((RANDOM % MAX))\n    mv $DIR/$file $DIR/$new_file 2> /dev/null\ndone\n", "num_lines": 12}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile /bin/true ; do\n    file=$((RANDOM % MAX))\n    rm -rf $DIR/$file 2> /dev/null\n    sleep 1\ndone\n\n\n", "num_lines": 14}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\tattr=user.$((RANDOM % MAX))\n\tvalue=$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM$RANDOM\n\tsetfattr -n $attr -v $value $file 2> /dev/null\ndone\n", "num_lines": 13}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile : ; do\n\tfile=$((RANDOM % $MAX))\n\tnew_file=$((RANDOM % MAX))\n\t$LFS swap_layouts $DIR/$file $DIR/$new_file 2>/dev/null\ndone\n", "num_lines": 12}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nwhile /bin/true ; do\n    file=$((RANDOM % MAX))\n    new_file=$((RANDOM % MAX))\n    ln -s $file $DIR/$new_file 2> /dev/null\n    ln -s $file/$file/$file $DIR/$new_file 2> /dev/null\ndone\n", "num_lines": 13}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nDIR=$1\nMAX=$2\n\nTRUNCATE=${TRUNCATE:-$LUSTRE/tests/truncate}\n\nwhile true; do\n\tfile=$DIR/$((RANDOM % MAX))\n\t$TRUNCATE $file $RANDOM 2> /dev/null\ndone\n", "num_lines": 13}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/../..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ntrap - ERR\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nwhile /bin/true; do\n\tlsnapshot_create -n lss_$RANDOM || true\n\tsleep $((RANDOM % 9 + 11))\ndone\n", "num_lines": 13}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\ntrap 'kill $(jobs -p)' EXIT\n\nLUSTRE=${LUSTRE:-$(cd $(dirname $0)/../..; echo $PWD)}\n. $LUSTRE/tests/test-framework.sh\ntrap - ERR\n. ${CONFIG:=$LUSTRE/tests/cfg/$NAME.sh}\n\nwhile /bin/true; do\n\tsleep $((RANDOM % 9 + 11))\n\tssname=$(do_facet mgs \"$LCTL snapshot_list -F $FSNAME 2>/dev/null\" |\n\t\t awk '/snapshot_name.*lss_/ { print $2; exit; }')\n\t[ ! -z \"$ssname\" ] && lsnapshot_destroy -n $ssname -f || true\ndone\n", "num_lines": 15}
{"repo_name": "lustre", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\n\nDIR=\"$1\"\nMAX_FILES=${MAX_FILES:-20}\nDURATION=${DURATION:-$((60*5))}\nMDSCOUNT=${MDSCOUNT:-1}\n\nNUM_THREADS=${NUM_THREADS:-$2}\nNUM_THREADS=${NUM_THREADS:-3}\n\nRACER_MAX_CLEANUP_WAIT=${RACER_MAX_CLEANUP_WAIT:-$DURATION}\n\nmkdir -p $DIR\n\nRACER_PROGS=\"file_create dir_create file_rm file_rename file_link file_symlink \\\nfile_list file_concat file_exec file_chown file_chmod file_mknod file_truncate \\\nfile_delxattr file_getxattr file_setxattr\"\n\nif $RACER_ENABLE_REMOTE_DIRS || $RACER_ENABLE_STRIPED_DIRS; then\n\tRACER_PROGS+=' dir_remote'\nfi\n\nif $RACER_ENABLE_MIGRATION; then\n\tRACER_PROGS+=' dir_migrate'\nfi\n\nracer_cleanup()\n{\n\techo \"racer cleanup\"\n\tfor P in $RACER_PROGS; do\n\t\tkillall -q $P.sh\n\tdone\n\ttrap 0\n\n\tlocal TOT_WAIT=0\n\tlocal SHORT_WAIT=5\n\n\tlocal rc\n\twhile [[ $TOT_WAIT -le $RACER_MAX_CLEANUP_WAIT ]]; do\n\t\trc=0\n\t\techo sleeping $SHORT_WAIT sec ...\n\t\tsleep $SHORT_WAIT\n\t\t# this only checks whether processes exist\n\t\tfor P in $RACER_PROGS; do\n\t\t\tkillall -0 $P.sh\n\t\t\t[[ $? -eq 0 ]] && (( rc+=1 ))\n\t\tdone\n\n\t\t# Kill dd processes to speedup cleanup\n\t\tlocal pids=$(ps uax | grep \"$DIR\" | grep dd | grep -v grep |\n\t\t\t\tawk '{print $2}')\n\t\tfor pid in $pids; do\n\t\t\tkill $pid\n\t\tdone\n\n\t\tif [[ $rc -eq 0 ]]; then\n\t\t\techo there should be NO racer processes:\n\t\t\tps uww -C \"${RACER_PROGS// /.sh,}.sh\"\n\t\t\treturn 0\n\t\tfi\n\t\t(( TOT_WAIT+=SHORT_WAIT ))\n\t\techo -n \"Waited $TOT_WAIT, rc=$rc \"\n\t\t(( SHORT_WAIT+=SHORT_WAIT ))\n\tdone\n\tps uww -C \"${RACER_PROGS// /.sh,}.sh\"\n\treturn 1\n}\n\nRC=0\n\necho \"Running $0 for $DURATION seconds. CTRL-C to exit\"\ntrap \"\n\techo \\\"Cleaning up\\\" \n\tracer_cleanup\n\texit 0\n\" INT TERM\n\ncd `dirname $0`\nfor N in `seq 1 $NUM_THREADS`; do\n\tfor P in $RACER_PROGS; do\n\t\t./$P.sh $DIR $MAX_FILES &\n\tdone\ndone\n\nsleep $DURATION\nracer_cleanup || RC=$?\n\n# Check our to see whether our test DIR is still available.\ndf $DIR\n(( RC+=$? ))\n[ $RC -eq 0 ] && echo \"We survived $0 for $DURATION seconds.\"\nexit $RC\n", "num_lines": 94}
{"repo_name": "miniF2F", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Usage: mk_all.sh [subdirectory]\n#\n# Examples:\n#   ./scripts/mk_all.sh\n#   ./scripts/mk_all.sh data/real\n#\n# Makes a mathlib/src/$directory/all.lean importing all files inside $directory.\n# If $directory is omitted, creates `mathlib/src/all.lean`.\n\ncd \"$( dirname \"${BASH_SOURCE[0]}\" )\"/../src\nif [[ $# = 1 ]]; then\n    dir=\"$1\"\n  else\n      dir=\".\"\nfi\n\nfind \"$dir\" -name \\*.lean -not -name minif2f.lean \\\n    | sed 's,^\\./,,;s,\\.lean$,,;s,/,.,g;s,^,import ,' \\\n      | sort >\"$dir\"/minif2f.lean\n", "num_lines": 21}
{"repo_name": "miniF2F", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# usage: sh scripts/simple_formatter.sh src/test\n\nfor FILE in $1/*.lean\ndo\n    # remove lines between header and import \n    # remove space after (\n    # remove space before (\n    # remove trailing space in lines\n    # replace multiple empty line with one\n    # remove trailing/leading empty lines\n    # add newline to eof if not\n    sed '#^-/#,#^import#{//!d;}' $FILE \\\n    | sed 's/([[:blank:]]*/(/g' \\\n    | sed 's/[[:blank:]]*)/)/g' \\\n    | sed 's/[[:space:]]\\+$//g' \\\n    | sed -e :a -e '/./,$!d;/^\\n*$/{$d;N;};/\\n$/ba' \\\n    | sed -e '$a\\' \\\n    | cat -s > sillytmpfile\n    mv sillytmpfile $FILE\ndone\n", "num_lines": 22}
{"repo_name": "mitmproxy", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\nset -x\n\nPYVERSION=3.5\nVENV=\"venv$PYVERSION\"\n\necho \"Creating dev environment in $VENV using Python $PYVERSION\"\n\npython$PYVERSION -m virtualenv \"$VENV\" --always-copy\n. \"$VENV/bin/activate\"\npip$PYVERSION install -U pip setuptools\npip$PYVERSION install -r requirements.txt\n\necho \"\"\necho \"* Virtualenv created in $VENV and all dependencies installed.\"\necho \"* You can now activate the $(python --version) virtualenv with this command: \\`. $VENV/bin/activate\\`\"\n", "num_lines": 18}
{"repo_name": "mitmproxy", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -f ./private.key ]\nthen\n    openssl genrsa -out private.key 3072\nfi\nopenssl req \\\n    -batch \\\n    -new -x509 \\\n    -key private.key \\\n    -sha256 \\\n    -out cert.pem \\\n    -days 9999 \\\n    -config ./openssl.cnf\nopenssl x509 -in cert.pem -text -noout\ncat ./private.key ./cert.pem > testcert.pem\nrm ./private.key ./cert.pem\n", "num_lines": 18}
{"repo_name": "monorepo-diff-buildkite-plugin", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ueo pipefail\n\n# Script to output the diff where the branch was created\n# Usage: ./diff.sh $BUILDKITE_COMMIT\n\nCOMMIT_HASH=$1\n\nBRANCH_POINT_COMMIT=$(./find-branch-point.sh \"$COMMIT_HASH\")\necho >&2 \"Cannot find latest build. Running diff against: $BRANCH_POINT_COMMIT\"\ndiff=$(git diff --name-only \"$BRANCH_POINT_COMMIT\")\necho \"$diff\"\n\n", "num_lines": 14}
{"repo_name": "monorepo-diff-buildkite-plugin", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ue\n\ndiff -u <(git rev-list --first-parent \"$1\") \\\n        <(git rev-list --first-parent master) | \\\n        sed -ne 's/^ //p' | head -1\n", "num_lines": 7}
{"repo_name": "monorepo-diff-buildkite-plugin", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ueo pipefail\n\necho \"diff 2\"", "num_lines": 4}
{"repo_name": "multiagent-competition", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ntask=$1\nmax_episodes=3\ncorrect=0\n\nif [ $task == \"run-to-goal-ants\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 1: Run-to-Goal (Ants)\"\n  python main.py --env run-to-goal-ants --param-paths agent-zoo/run-to-goal/ants/agent1_parameters-v1.pkl agent-zoo/run-to-goal/ants/agent2_parameters-v1.pkl --max-episodes $max_episodes\n  correct=1\nfi\nif [ $task == \"run-to-goal-humans\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 1: Run-to-Goal (Humans)\"\n  python main.py --env run-to-goal-humans --param-paths agent-zoo/run-to-goal/humans/agent1_parameters-v1.pkl agent-zoo/run-to-goal/humans/agent2_parameters-v1.pkl --max-episodes $max_episodes\n  correct=1\nfi\nif [ $task == \"you-shall-not-pass\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 2: You-Shall-Not-Pass\"\n  python main.py --env you-shall-not-pass --param-paths agent-zoo/you-shall-not-pass/agent1_parameters-v1pkl agent-zoo/you-shall-not-pass/agent2_parameters-v1.pkl --max-episodes $max_episodes\nfi\nif [ $task == \"sumo-ants\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 3: Sumo (Ants)\"\n  python main.py --env sumo-ants --param-paths agent-zoo/sumo/ants/agent_parameters-v2.pkl agent-zoo/sumo/ants/agent_parameters-v2.pkl --max-episodes $max_episodes\n  correct=1\nfi\nif [ $task == \"sumo-humans\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 3: Sumo (Humans)\"\n  python main.py --env sumo-humans --param-paths agent-zoo/sumo/humans/agent_parameters-v1.pkl agent-zoo/sumo/humans/agent_parameters-v1.pkl --max-episodes $max_episodes\n  correct=1\nfi\nif [ $task == \"kick-and-defend\" ] || [ $task == \"all\" ]\nthen\n  echo \"Task 4: Kick-and-Defend\"\n  python main.py --env kick-and-defend --param-paths agent-zoo/kick-and-defend/kicker/agent1_parameters-v1.pkl agent-zoo/kick-and-defend/defender/agent2_parameters-v1.pkl --max-episodes $max_episodes\n  correct=1\nfi\nif [ $correct == 0 ]\nthen\n  echo \"Usage: bash demo_tasks.sh <task>\"\n  echo \"where <task> is all to demo all tasks or one of: run-to-goal-humans, run-to-goal-ants, you-shall-not-pass, sumo-humans, sumo-ants, kick-and-defend\"\nfi\n", "num_lines": 47}
{"repo_name": "neural-mmo", "repo_creator": "openai", "programming_language": "Shell", "code": "#tensorboard --logdir ./resource/logs/\ntensorboard --logdir ../results/interactive/gatests/\n\n", "num_lines": 4}
{"repo_name": "neural-mmo", "repo_creator": "openai", "programming_language": "Shell", "code": "rm resource/logs/events*\n", "num_lines": 2}
{"repo_name": "neural-mmo", "repo_creator": "openai", "programming_language": "Shell", "code": "find . -name \"*.py\" -type f -exec grep . {} \\; | wc -l\n", "num_lines": 2}
{"repo_name": "neural-mmo", "repo_creator": "openai", "programming_language": "Shell", "code": "#Pytorch\npip install http://download.pytorch.org/whl/cu90/torch-0.4.0-cp36-cp36m-linux_x86_64.whl\npip install torchvision\n\n#Ray -- will segfault in .backward with wrong version\n#pip uninstall -y ray\n#pip install -U https://s3-us-west-2.amazonaws.com/ray-wheels/68b11c8251dc41e79dc9dc4b1da31630708a6bd8/ray-0.4.0-cp36-cp36m-manylinux1_x86_64.whl\n\n#Ray\npip install ray\npip install setproctitle\npip install service_identity\n\n#Basics\npip install numpy\npip install scipy\npip install matplotlib\n\n\n#Tiled map loader\npip install pytmx\n\n#jsonpickle\npip install jsonpickle\npip install opensimplex\npip install twisted\n", "num_lines": 27}
{"repo_name": "oauth2_proxy", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# build binary distributions for linux/amd64 and darwin/amd64\nset -e\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\necho \"working dir $DIR\"\nmkdir -p $DIR/dist\ndep ensure || exit 1\n\nos=$(go env GOOS)\narch=$(go env GOARCH)\nversion=$(cat $DIR/version.go | grep \"const VERSION\" | awk '{print $NF}' | sed 's/\"//g')\ngoversion=$(go version | awk '{print $3}')\nsha256sum=()\n\necho \"... running tests\"\n./test.sh\n\nfor os in windows linux darwin; do\n    echo \"... building v$version for $os/$arch\"\n    EXT=\n    if [ $os = windows ]; then\n        EXT=\".exe\"\n    fi\n    BUILD=$(mktemp -d ${TMPDIR:-/tmp}/oauth2_proxy.XXXXXX)\n    TARGET=\"oauth2_proxy-$version.$os-$arch.$goversion\"\n    FILENAME=\"oauth2_proxy-$version.$os-$arch$EXT\"\n    GOOS=$os GOARCH=$arch CGO_ENABLED=0 \\\n        go build -ldflags=\"-s -w\" -o $BUILD/$TARGET/$FILENAME || exit 1\n    pushd $BUILD/$TARGET\n    sha256sum+=(\"$(shasum -a 256 $FILENAME || exit 1)\")\n    cd .. && tar czvf $TARGET.tar.gz $TARGET\n    mv $TARGET.tar.gz $DIR/dist\n    popd\ndone\n\nchecksum_file=\"sha256sum.txt\"\ncd $DIR/dist\nif [ -f $checksum_file ]; then\n    rm $checksum_file\nfi\ntouch $checksum_file\nfor checksum in \"${sha256sum[@]}\"; do\n    echo \"$checksum\" >> $checksum_file\ndone\n", "num_lines": 46}
{"repo_name": "orrb", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nwget http://openai-public.s3.amazonaws.com/github.com/openai/orrb/builds/builds-20190514.zip\nunzip builds-20190514.zip\nrm builds-201905014.zip\n\necho\necho\necho \"  Execute or add this to your .bashrc/.bashprofile.\"\necho \"  export ORRB_BINARIES_DIR=\\\"\"`pwd`\"\\\"\"\necho\necho\n", "num_lines": 12}
{"repo_name": "orrb", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ -z \"$1\" ]] ; then\n\techo \"Usage: build.sh version_id\"\n\texit 1\nfi\n\nif [[ -z \"$UNITY_CMD\" ]] ; then\n\techo \"Point \\$UNITY_CMD to the Unity editor binary.\"\n\texit 1\nfi\n\nbuild() {\n\tCURRENT_DIR=`pwd`\n\tPROJECT_DIR=$(dirname $CURRENT_DIR)\n        NAME=\"$1-$2-$3\"\n\tZIP_NAME=\"$NAME.zip\"\n\trm $ZIP_NAME\n\t$UNITY_CMD -batchmode -quit -logFile -projectPath $PROJECT_DIR -executeMethod BuildUtils.BuildCommandline +name $1 +target $2 +version $3 +scene $4 +devel $5\n\tcp -r resources/$2/* $NAME\n\tzip -r $ZIP_NAME $NAME\n}\n\nrm -rf StandaloneRenderer-*-$1*\nbuild StandaloneRenderer Darwin-x86_64 $1 Assets/Scenes/StandaloneRenderer.unity false\nbuild StandaloneRenderer Linux-x86_64 $1 Assets/Scenes/StandaloneRenderer.unity false\nbuild StandaloneRenderer Darwin-x86_64 $1-devel Assets/Scenes/StandaloneRenderer.unity true\nbuild StandaloneRenderer Linux-x86_64 $1-devel Assets/Scenes/StandaloneRenderer.unity true\n\nzip -r builds-$1.zip StandaloneRenderer-*-$1 StandaloneRenderer-*-$1-devel\n\n", "num_lines": 32}
{"repo_name": "orrb", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n./StandaloneRenderer.app/Contents/MacOS/StandaloneRenderer \"$@\"\n", "num_lines": 3}
{"repo_name": "orrb", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n./StandaloneRenderer.x86_64 \"$@\"\n", "num_lines": 3}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# $1: path to test results\n# $2: board size\n\n(cd \"$1\" && ls f$2-*summ*dat) | sed 's/^f'$2'-//; s/[-.].*$//;' | xargs git log --pretty=oneline --no-walk | while read c s; do\n\techo\n\techo ================================================\n\tgit log -1 --pretty=medium $c\n\tfor t in $(cd \"$1\" && ls f$2-${c:0:5}*summ*); do\n\t\techo\n\t\techo $t\n\t\tcat \"$1/$t\" | cut -f 1,2,7,8,12,13\n\tdone\ndone\n", "num_lines": 16}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# test-game: Run testcases within a single game\n#\n# Usage: test-game.sh FILENAME\n#\n# Examine a game record and run testcases for all moves described\n# in the \"game comment\".\n#\n# Pass any extra Pachi parameters in PACHIARGS. E.g.\n#\tPACHIARGS='-t =100000 -d 2 threads=2' testgame.sh ...\n\nsgf=\"$1\"\n\nsed -ne '/GC\\[[0-9][0-9]* .*\\]/{s/.*GC\\[\\([^]]*\\)\\].*/\\1/p; q;}; /GC\\[/,/\\]/{ s/.*GC\\[//; s/\\].*//; /^[0-9][0-9]* /p; }' <\"$sgf\" |\n\twhile read moven cases desc; do\n\t\techo \"Examining move $moven\"; sleep 1\n\t\ttools/sgf2gtp.pl -g -n $((moven-1)) <\"$sgf\" | ./pachi -t =20000 $PACHIARGS\n\t\techo \"Testcases: $cases ($desc)\"\n\t\techo \"Confirm and press enter...\"; read xx </dev/tty\n\tdone\n", "num_lines": 22}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nsize=\"$1\" # board size\nopts=\"$2\" # UCT engine options; must NOT specify different policy\npopts=\"$3\" # UCT policy options\n[ -n \"$size\" ] || size=9\n[ -z \"$opts\" ] || opts=\",$opts\"\n[ -z \"$popts\" ] || popts=\":$popts\"\n\nif [ \"$size\" -le 13 ]; then\n\tgames=400000\nelse\n\tgames=200000\nfi\n\nrm ucttbook-$size-7.5.pachitree\nn=0\ngentbook1()\n{\n\techo \"[#$n:$1]\"\n\tn=$((n+1))\n\techo -e 'boardsize '$size'\\nclear_board\\nkomi 7.5\\npachi-gentbook b' |\n\t\t./pachi -t =$games \"policy=ucb1amaf:explore_p=$1$popts$opts\"\n}\ngentbook1 0.0\ngentbook1 0.1\ngentbook1 0.2\ngentbook1 2.0\ngentbook1 0.2\ngentbook1 2.0\ngentbook1 0.1\ngentbook1 0.0\ngentbook1 0.0\ngentbook1 0.0\n", "num_lines": 34}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# pattern_bayes_gen: Generate pattern probability table from a SGF collection\n# (or stdin GTP stream).\n\n(if [ x\"$1\" = x\"-\" ]; then cat; else for i in \"$@\"; do echo $i >&2; tools/sgf2gtp.pl <$i; done; fi) |\n\t./pachi -d 0 -e patternscan competition,spat_split_sizes |\n\tperl -nle '\n\t\tBEGIN { use List::MoreUtils qw(uniq); }\n\n\t\ts/^= // or next;\n\t\tchomp;\n\t\tmy ($winner, $witness) = (/^\\[(.*)\\] \\[(.*)\\]$/);\n\n\t\tsub parse { $_ = $_[0]; s/\\) \\(/),(/g; return split(/,/); }\n\n\t\tfor (uniq(parse($winner))) {\n\t\t\t$choices{$_}++;\n\t\t}\n\t\tfor (uniq(parse($witness))) {\n\t\t\t$counts{$_}++;\n\t\t}\n\n\t\tEND {\n\t\t\tfor (keys %counts) {\n\t\t\t\t$p{$_} = $choices{$_} / $counts{$_};\n\t\t\t}\n\t\t\tfor (sort { $counts{$a} <=> $counts{$b} } keys %p) {\n\t\t\t\tnext if ($counts{$_} < 2);\n\t\t\t\tprintf(\"%.3f %d %d %s\\n\", $p{$_}, $choices{$_}, $counts{$_}, $_);\n\t\t\t}\n\t\t}'\n", "num_lines": 32}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# pattern_bayes_merge: Merge pattern probability tables; pass them\n# as arguments.\n\ncat \"$@\" | perl -nle '\n\tchomp;\n\tmy ($p, $ch, $co, $pa) = /^(.*?) (\\d+) (\\d+) (.*)$/;\n\t$pa or die \"parse error: $_\";\n\t$choices{$pa} += $ch;\n\t$counts{$pa} += $co;\n\n\tEND {\n\t\tfor (keys %counts) {\n\t\t\t$p{$_} = $choices{$_} / $counts{$_};\n\t\t}\n\t\tfor (sort { $counts{$a} <=> $counts{$b} } keys %p) {\n\t\t\tnext if ($counts{$_} < 2);\n\t\t\tprintf(\"%.3f %d %d %s\\n\", $p{$_}, $choices{$_}, $counts{$_}, $_);\n\t\t}\n\t}\n\t'\n", "num_lines": 22}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# pattern_byplayer - Build a per-player database of used patterns\n#\n# Invoke this script for each played game, it will add patterns\n# to the database incrementally; each file in the database contains\n# patterns played by one player.\n#\n# You must already have a spatial dictionary generated.\n\ndbdir=\"$1\"; shift\nsgf=\"$1\"; shift\n# rest of parameters is passed to the patternscan engine\n\nsgf_attr() {\n\t# TODO: Does not work correctly for attributes containing escaped ]\n\t# e.g. \"PB[Tony \\[Killer\\] Nowak]\" gets cropped to \"Tony \\[Killer\"\n\t# Not a big problem, since usually the player name is just\n\t# [a-zA-Z0-9]*\n\n\tsed -n 's/^.*'$1'\\[\\([^]]*\\)\\].*$/\\1/p' \"$sgf\"\n}\n\nblack=\"$(sgf_attr PB)\"\nwhite=\"$(sgf_attr PW)\"\nhandi=\"$(sgf_attr HA)\"\n\nif [ -n \"$handi\" ] && [ \"$handi\" -gt 0 ]; then\n\tto_play=white\n\t# Comment following out if you want to include handi games.\n\techo \"$sgf: Skipping handicap game\" >&2\n\texit 1\nfi\n\nto_play=black\ncat \"$sgf\" | tools/sgf2gtp.pl | ./pachi -d 0 -e patternscan \"$@\" |\n\tsed -n -e 's/^= //p' | grep -v '^ *$' | # skip irrelevant replies\n\twhile read pattern; do\n\t\tif [ \"$to_play\" = black ]; then\n\t\t\tplayer=\"$black\"\n\t\t\tto_play=white\n\t\telse\n\t\t\tplayer=\"$white\"\n\t\t\tto_play=black\n\t\tfi\n\t\techo \"$pattern\" >>\"$dbdir/$player\"\n\tdone\n", "num_lines": 47}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# pattern_spatial_gen: Initialize spatial dictionary from a SGF collection\n#\n# We will first gather all spatial features from the SGF collection\n# (we take files as arguments) and store these occuring more than 4 times\n# in a freshly created spatial dictionary; afterwards, you will probably want\n# to do standard pattern-matching.\n#\n# DO NOT RUN THIS CONCURRENTLY! The dictionary will get corrupted.\n#\n# To get spatials in competion mode (also get information about unplayed\n# spatials present at the board, not just the single played one per move),\n# run this script as:\n#\n#\tPATARGS=\"competition\" ./pattern_spatial_gen.sh ...\n#\n# Similarly, you can set SPATMIN to different number than 4 to include\n# spatial features with other number of occurences.\n\n[ -n \"$SPATMIN\" ] || SPATMIN=4\n\nrm -f patterns.spat\n\necho \" Gathering population of spatials occuring more than $SPATMIN times...\"\n(for i in \"$@\"; do echo $i >&2; tools/sgf2gtp.pl <$i; done) |\n\t./pachi -d 0 -e patternscan gen_spat_dict,no_pattern_match,spat_threshold=$SPATMIN${PATARGS:+,$PATARGS} >/dev/null\n\necho \" Renumbering patterns.spat...\"\nperl -i -pe '/^#/ and next; s/^\\d+/++$a/e' patterns.spat\n\necho -n \" Counting hash collisions... \"\nperl -lne 'chomp; my ($id, $d, $p, @h) = split(/ /, $_); foreach (@h) { next if $h{$_} = $id; print \"collision $id - $h{$_} ($_)\" if $h{$_}; $h{$_}=$id; }' patterns.spat | wc -l\n", "num_lines": 33}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# Simple script using Pachi for rating all moves in a given situation.\n# Pachi will analyse each followup move and suggest a winrate for it;\n# higher is better.\n#\n# Usage: tools/sgf-ratemove.sh SGF MOVENUM PACHIARGS...\n#\n# Note that this script assumes dynkomi=none and does not show\n# dynamic komi information. (Would be trivial to add but it's tricky\n# to interpret the data.)\n#\n# This script is dirty and insecure for untrusted input!\n#\n# Example: tools/sgf-ratemove.sh progame.sgf 120 -t =500 -d 0\n# ...to get 500 simulations per each possible move in programe.sgf\n# at move 120.\n# \n# If you want to know more details on what is Pachi thinking about the\n# various moves, remove the `-d 0` part. To improve the accuracy of values\n# (at the expense of run time), raise the value of 500 (try 2000 or 10000;\n# 100000 will usually already take couple of hours). The values will be\n# most useful in the middle game; in fuseki and most yose situations,\n# expect a lot of noise.\n\nsgf=$1; shift\nmovenum=$1; shift\ntools/sgf2gtp.pl -g -n $movenum <\"$sgf\" |\n\tsed -e 's/genmove/0 pachi-evaluate/' |\n\t./pachi \"$@\" |\n\tsed -ne '/^=0/,${s/^=0 //;p}' |\n\tsort -r -n -t ' ' -k 2\n", "num_lines": 32}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ $# -ne 3 ]; then\n\techo \"Usage: $0 PLAYER1 PLAYER2 BOOKDIR\" >&2\n\texit 1\nfi\n\nexport CMDDIR=$(pwd)\nexport SEQDIR=$(mktemp -d)\n\nif [ ! -d \"$3\" ]; then\n\tmkdir \"$3\"\n\t{ echo 12; echo 24; } >\"$3\"/stats\nfi\n\nwhile true; do\n\t(cd \"$3\"; \"$CMDDIR\"/walk.sh \"$1\" \"$2\")\n\tsleep 5\ndone\n", "num_lines": 20}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Config:\n# Minimal number of simulations for the result to be considered trustworthy\nmin_sims=50\n\nif [ $# -ne 1 ]; then\n\techo \"Usage: $0 BOOKDIR\" >&2\n\texit 1\nfi\n\nexport CMDDIR=$(pwd)\n\nscan() {\n\tseq=\"$1\"\n\tfor i in */; do echo $(sed -ne 2p $i/stats) $i; done | sort -rn |\n\t\t{ first=1\n\t\t\twhile read sims move; do\n\t\t\t\tmove=\"${move%/}\"\n\t\t\t\tif [ \"$sims\" -lt \"$min_sims\" ]; then\n\t\t\t\t\tbreak;\n\t\t\t\tfi\n\t\t\t\t[ -z \"$first\" ] || echo \"$seq | $move\"\n\t\t\t\tfirst=\n\t\t\t\t(cd \"$move\"; scan \"$seq $move\")\n\t\t\tdone\n\t\t}\n}\n\ncd \"$1\"\nscan \"\"\n", "num_lines": 32}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Choose next move to choose in the current directory (node)\n\n# Config:\n# Exploration coefficient\nexplore_p=0.8\n\nbest_move=\nbest_val=-9999\n\n{ read mwins; read msims; } <stats\n\nfor move in $(find . -maxdepth 1 -type d | tail -n +2); do\n\t{ read wins; read sims; } <\"$move\"/stats\n\tval=\"$(echo \"($wins/$sims+$explore_p*sqrt(l($msims)/$sims))*1000\" | bc -l)\"\n\tval=\"${val%.*}\"\n\tif [ \"$val\" -gt \"$best_val\" ]; then\n\t\tbest_val=\"$val\"\n\t\tbest_move=\"$move\"\n\tfi\ndone\n\necho ${best_move#./}\n", "num_lines": 25}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Create subdirectories (followup nodes) in the cwd\n\n# Config:\n# Prior value weight:\npriorsims=24\n\n# Expected env:\n# $CMDDIR\n# $SEQDIR\n\npachi=\"$1\"\n\ncat \"$SEQDIR/a.sgf\" | \"$CMDDIR/../sgf2gtp.pl\" -g |\n\tsed -e 's/genmove/pachi-evaluate/' |\n\t$pachi |\n\tsed -ne '/^=/,${s/^= //;/./p}' |\n\twhile read move val; do\n\t\tmkdir \"$move\" || continue\n\t\t{\n\t\techo \"$(echo \"$val * $priorsims\" | bc)\"\n\t\techo \"$priorsims\"\n\t\t} >\"$move\"/stats\n\tdone\n", "num_lines": 26}
{"repo_name": "pachi-py", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# A single iteration of the algorithm\n\n# Config:\n# After how many visits (including prior_sims!) a node is expanded.\nexpand_sims=26\n# Virtual loss\nvloss=4\n# Twogtp path\ntwogtp_path=/home/pasky/gogui-1.3.2/bin/gogui-twogtp\n\n# Expected env:\n# $CMDDIR\n# $SEQDIR\n\npachi=\"$1\"; shift\nopponent=\"$1\"\n\nseq=\"\"\ncolor=W\nwhile true; do\n\t{ read wins; read sims; } <stats\n\txsims=$((sims+vloss))\n\t{ echo $wins; echo $xsims; } >stats.new\n\tmv stats.new stats # atomic\n\n\tchildren=$(find . -maxdepth 1 -type d | wc -l);\n\tcase $children in\n\t\t1) expanded=;;\n\t\t*) expanded=1;;\n\tesac\n\n\tif [ -z \"$expanded\" -a \"$sims\" -ge \"$expand_sims\" ]; then\n\t\techo \"(;FF[4]GM[1]CA[UTF-8]RU[Chinese]SZ[9]HA[0]KM[7.5]PW[white]PB[black]$seq)\" >\"$SEQDIR/a.sgf\"\n\t\t\"$CMDDIR\"/expand.sh \"$pachi\"\n\t\texpanded=1\n\tfi\n\tif [ -z \"$expanded\" ]; then\n\t\tbreak;\n\tfi\n\n\tmove=$(\"$CMDDIR\"/eval.sh)\n\n\tcd \"$move\"\n\tcase $color in\n\t\tB) color=W;;\n\t\tW) color=B;;\n\tesac\n\n\tsgfmove=$(echo \"$move\" | perl -nle 'my ($x,$y) = /(.)(.)/; $x=lc($x); $x=chr(ord($x)-1) if ord(lc $x) > ord(\"i\"); $y = chr(96+10-$y); print \"$x$y\"')\n\tseq=\"$seq;${color}[$sgfmove]\"\ndone\n\necho \"   *** Sequence: $seq\"\necho \"(;FF[4]GM[1]CA[UTF-8]RU[Chinese]SZ[9]HA[0]KM[7.5]PW[white]PB[black]$seq)\" >\"$SEQDIR/a.sgf\"\nrm -f \"$SEQDIR\"/r*\n\n# last move has been... - we want to simulate this being _our_ move yet,\n# i.e. start the simulation with the opponent to play\ncase $color in\n\tB)\n\t\tblack=\"$pachi\"\n\t\twhite=\"$opponent\";;\n\tW)\n\t\tblack=\"$opponent\"\n\t\twhite=\"$pachi\";;\nesac\n$twogtp_path -black \"$black\" -white \"$white\" -auto -verbose -size 9 -komi 7.5 -sgffile \"$SEQDIR/r\" -games 1 -openings \"$SEQDIR\"\nwincolor=$(cat \"$SEQDIR\"/r-0.sgf | sed -ne 's/.*RE\\[\\(.\\).*/\\1/p')\ncase $wincolor in\n\tB) result=1;;\n\tW) result=0;;\nesac\necho \"   *** Result: $wincolor wins => $result\"\npwd; ls\n\nwhile [ -e stats ]; do\n\tcase $color in\n\t\tB) nresult=$result;;\n\t\tW) nresult=$((1-result));\n\tesac\n\techo \"    + Recording $nresult .. $(pwd) color $color\"\n\n\t{ read wins; read sims; } <stats\n\twins=$((${wins%.*}+nresult))\n\tsims=$((sims-vloss+1))\n\t{ echo $wins; echo $sims; } >stats.new\n\tmv stats.new stats # atomic\n\n\tcd ..\n\tcase $color in\n\t\tB) color=W;;\n\t\tW) color=B;;\n\tesac\ndone\n", "num_lines": 97}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -xe\n\n# Go-fuzz doesn't support modules yet, so ensure we do everything in the old style GOPATH way\nexport GO111MODULE=\"off\"\n\n# Install go-fuzz\ngo get -u github.com/dvyukov/go-fuzz/go-fuzz github.com/dvyukov/go-fuzz/go-fuzz-build\n\n# Target names on fuzzit.dev\nTARGETS=(\"promql-parse-metric\" \"promql-parse-open-metric\" \"promql-parse-metric-selector\" \"promql-parse-expr\")\n\n# Prometheus fuzz functions\nFUZZ_FUNCTIONS=(\"FuzzParseMetric\" \"FuzzParseOpenMetric\" \"FuzzParseMetricSelector\" \"FuzzParseExpr\")\n\n# Compiling prometheus fuzz targets in fuzz.go with go-fuzz (https://github.com/dvyukov/go-fuzz) and libFuzzer support\nfor ((i=0;i<${#TARGETS[@]};++i));\ndo\n    go-fuzz-build -libfuzzer -func ${FUZZ_FUNCTIONS[i]} -o ${TARGETS[i]}.a ./promql\n    clang-9 -fsanitize=fuzzer ${TARGETS[i]}.a -o ${TARGETS[i]}\ndone\n\n# Install fuzzit CLI\nwget -q -O fuzzit https://github.com/fuzzitdev/fuzzit/releases/download/v2.4.45/fuzzit_Linux_x86_64\nchmod a+x fuzzit\n\nfor TARGET in \"${TARGETS[@]}\"\ndo\n    ./fuzzit create job --type $1 prometheus/${TARGET} ${TARGET}\ndone\n", "num_lines": 31}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Build React web UI.\n# Run from repository root.\nset -e\nset -u\n\nif ! [[ \"$0\" =~ \"scripts/build_react_app.sh\" ]]; then\n\techo \"must be run from repository root\"\n\texit 255\nfi\n\ncd web/ui/react-app\n\necho \"building React app\"\nPUBLIC_URL=. yarn build\nrm -rf ../static/react\nmv build ../static/react\n", "num_lines": 19}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Generate all protobuf bindings.\n# Run from repository root.\nset -e\nset -u\n\nif ! [[ \"$0\" =~ \"scripts/genproto.sh\" ]]; then\n\techo \"must be run from repository root\"\n\texit 255\nfi\n\nif ! [[ $(protoc --version) =~ \"3.5.1\" ]]; then\n\techo \"could not find protoc 3.5.1, is it installed + in PATH?\"\n\texit 255\nfi\n\necho \"installing plugins\"\nGO111MODULE=on go mod download\n\nINSTALL_PKGS=\"golang.org/x/tools/cmd/goimports github.com/gogo/protobuf/protoc-gen-gogofast github.com/grpc-ecosystem/grpc-gateway/protoc-gen-grpc-gateway github.com/grpc-ecosystem/grpc-gateway/protoc-gen-swagger\"\nfor pkg in ${INSTALL_PKGS}; do\n    GO111MODULE=on go install -mod=vendor \"$pkg\"\ndone\n\nPROM_ROOT=\"${PWD}\"\nPROM_PATH=\"${PROM_ROOT}/prompb\"\nGOGOPROTO_ROOT=\"$(GO111MODULE=on go list -f '{{ .Dir }}' -m github.com/gogo/protobuf)\"\nGOGOPROTO_PATH=\"${GOGOPROTO_ROOT}:${GOGOPROTO_ROOT}/protobuf\"\nGRPC_GATEWAY_ROOT=\"$(GO111MODULE=on go list -f '{{ .Dir }}' -m github.com/grpc-ecosystem/grpc-gateway)\"\n\nDIRS=\"prompb\"\n\necho \"generating code\"\nfor dir in ${DIRS}; do\n\tpushd ${dir}\n\t\tprotoc --gogofast_out=plugins=grpc:. -I=. \\\n            -I=\"${GOGOPROTO_PATH}\" \\\n            -I=\"${PROM_PATH}\" \\\n            -I=\"${GRPC_GATEWAY_ROOT}/third_party/googleapis\" \\\n            ./*.proto\n\n\t\tprotoc -I. \\\n\t\t\t-I=\"${GOGOPROTO_PATH}\" \\\n\t\t\t-I=\"${PROM_PATH}\" \\\n\t\t\t-I=\"${GRPC_GATEWAY_ROOT}/third_party/googleapis\" \\\n\t\t\t--grpc-gateway_out=logtostderr=true:. \\\n\t\t\t--swagger_out=logtostderr=true:../documentation/dev/api/ \\\n\t\t\trpc.proto\n\t\tmv ../documentation/dev/api/rpc.swagger.json ../documentation/dev/api/swagger.json\n\n\t\tsed -i.bak -E 's/import _ \\\"github.com\\/gogo\\/protobuf\\/gogoproto\\\"//g' -- *.pb.go\n\t\tsed -i.bak -E 's/import _ \\\"google\\/protobuf\\\"//g' -- *.pb.go\n\t\tsed -i.bak -E 's/\\t_ \\\"google\\/protobuf\\\"//g' -- *.pb.go\n\t\tsed -i.bak -E 's/golang\\/protobuf/gogo\\/protobuf/g' -- *.go\n\t\trm -f -- *.bak\n\t\tgoimports -w ./*.pb.go\n\tpopd\ndone\n", "num_lines": 60}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Setting -x is absolutely forbidden as it could leak the GitHub token.\nset -uo pipefail\n\n# GITHUB_TOKEN required scope: repo.repo_public\n\ngit_mail=\"prometheus-team@googlegroups.com\"\ngit_user=\"prombot\"\nbranch=\"makefile_common\"\ncommit_msg=\"makefile: update Makefile.common with newer version\"\npr_title=\"Synchronize Makefile.common from prometheus/prometheus\"\npr_msg=\"Propagating changes from master Makefile.common located in prometheus/prometheus.\"\norg=\"prometheus\"\n\nGITHUB_TOKEN=\"${GITHUB_TOKEN:-}\"\nif [ -z \"${GITHUB_TOKEN}\" ]; then\n\techo -e \"\\e[31mGitHub token (GITHUB_TOKEN) not set. Terminating.\\e[0m\"\n\texit 1\nfi\n\n# Go to the root of the repo\ncd \"$(git rev-parse --show-cdup)\"\n\nsource_makefile=\"$(pwd)/Makefile.common\"\nsource_checksum=\"$(sha256sum Makefile.common | cut -d' ' -f1)\"\n\ntmp_dir=$(mktemp -d)\ntrap \"rm -rf ${tmp_dir}\" EXIT\n\n# Iterate over all repositories in ${org}. The GitHub API can return 100 items\n# at most but it should be enough for us as there are less than 40 repositories\n# currently.\ncurl --retry 5 --silent -u \"${git_user}:${GITHUB_TOKEN}\" https://api.github.com/users/${org}/repos?per_page=100 2>/dev/null | jq -r '.[] | select( .name != \"prometheus\" ) | .name' | while read -r; do\n\trepo=\"${REPLY}\"\n\techo -e \"\\e[32mAnalyzing '${repo}'\\e[0m\"\n\n\ttarget_makefile=\"$(curl -s --fail \"https://raw.githubusercontent.com/${org}/${repo}/master/Makefile.common\")\"\n\tif [ -z \"${target_makefile}\" ]; then\n\t\techo \"Makefile.common doesn't exist in ${repo}\"\n\t\tcontinue\n\tfi\n\ttarget_checksum=\"$(echo ${target_makefile} | sha256sum | cut -d' ' -f1)\"\n\tif [ \"${source_checksum}\" == \"${target_checksum}\" ]; then\n\t\techo \"Makefile.common is already in sync.\"\n\t\tcontinue\n\tfi\n\n\t# Clone target repo to temporary directory and checkout to new branch\n\tgit clone --quiet \"https://github.com/${org}/${repo}.git\" \"${tmp_dir}/${repo}\"\n\tcd \"${tmp_dir}/${repo}\"\n\tgit checkout -b \"${branch}\"\n\n\t# Replace Makefile.common in target repo by one from prometheus/prometheus\n\tcp -f \"${source_makefile}\" ./\n\tif [ -n \"$(git status --porcelain)\" ]; then\n\t\tgit config user.email \"${git_mail}\"\n\t\tgit config user.name \"${git_user}\"\n\t\tgit add .\n\t\tgit commit -s -m \"${commit_msg}\"\n\t\t# stdout and stderr are redirected to /dev/null otherwise git-push could leak the token in the logs.\n\t\tif git push --quiet \"https://${GITHUB_TOKEN}:@github.com/${org}/${repo}\" --set-upstream \"${branch}\" 1>/dev/null 2>&1; then\n\t\t\tcurl --show-error --silent \\\n\t\t\t\t-u \"${git_user}:${GITHUB_TOKEN}\" \\\n\t\t\t\t-X POST \\\n\t\t\t\t-d \"{\\\"title\\\":\\\"${pr_title}\\\",\\\"base\\\":\\\"master\\\",\\\"head\\\":\\\"${branch}\\\",\\\"body\\\":\\\"${pr_msg}\\\"}\" \\\n\t\t\t\t\"https://api.github.com/repos/${org}/${repo}/pulls\"\n\t\tfi\n\tfi\ndone\n", "num_lines": 71}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash \n\nset -eu -o pipefail\ndir=$(git rev-parse --show-toplevel)\nscratch=$(mktemp -d -t tmp.XXXXXXXXXX)\n\nfunction finish {\n  rm -rf \"$scratch\"\n}\ntrap finish EXIT SIGHUP SIGINT SIGTERM\n\ncd \"$scratch\"\ngit clone https://github.com/json-schema-org/JSON-Schema-Test-Suite Suite\ncp -r Suite/tests/draft4/* \"$dir/fixtures/jsonschema_suite\"\ncp -a Suite/remotes \"$dir/fixtures/jsonschema_suite\"\n", "num_lines": 16}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "go get github.com/golang/protobuf/protoc-gen-go\n\nprotoc \\\n--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto \n\n", "num_lines": 6}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"darwin\" ]; then\n\t\t\t        # pre-1.12, direct syscalls\n\t\t\t        echo \"$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos syscall_darwin_${GOARCH}.1_11.go $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go\";\n\t\t\t        # 1.12 and later, syscalls via libSystem\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\t\t# 1.13 and later, syscalls via libSystem (including syscallPtr)\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOARCH\"; fi\n) | $run\n", "num_lines": 230}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/errqueue.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/icmpv6.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/loop.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n\n#include <mtd/ubi-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|MCAST|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 685}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=$(mktemp -d /tmp/sdk.XXX) \\\n&& curl -o $TMP.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\" \\\n&& unzip -q $TMP.zip -d $TMP \\\n&& export PATH=\"$PATH:$TMP/go_appengine\"\n", "num_lines": 7}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ `uname -a` = *\"Darwin\"* ]]; then\n  echo \"It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047\"\n  exit 1\nfi\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | (! read)\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${GOPATH}/bin:${GOROOT}/bin:${PATH}\"\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Check for module support\n  if go help mod >& /dev/null; then\n    go install \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell \\\n      github.com/golang/protobuf/protoc-gen-go\n  else\n    # Ye olde `go get` incantation.\n    # Note: this gets the latest version of all tools (vs. the pinned versions\n    # with Go modules).\n    go get -u \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell \\\n      github.com/golang/protobuf/protoc-gen-go\n  fi\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.3.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif ! which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\ngit ls-files \"*.go\" | xargs grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" 2>&1 | fail_on_output\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\n(! grep 'func Test[^(]' *_test.go)\n(! grep 'func Test[^(]' test/*.go)\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit ls-files \"*.go\" | xargs grep -l '\"math/rand\"' 2>&1 | (! grep -v '^examples\\|^stress\\|grpcrand\\|wrr_test')\n\n# - Ensure all ptypes proto packages are renamed when importing.\ngit ls-files \"*.go\" | (! xargs grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\")\n\n# - Check imports that are illegal in appengine (until Go 1.11).\n# TODO: Remove when we drop Go 1.10 support\ngo list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet.\ngofmt -s -d -l . 2>&1 | fail_on_output\ngoimports -l . 2>&1 | (! grep -vE \"(_mock|\\.pb)\\.go:\") | fail_on_output\ngolint ./... 2>&1 | (! grep -vE \"(_mock|\\.pb)\\.go:\")\ngo vet -all .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Check that our module is tidy.\nif go help mod >& /dev/null; then\n  go mod tidy && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Collection of static analysis checks\n# TODO(menghanl): fix errors in transport_test.\nstaticcheck -go 1.9 -checks 'inherit,-ST1015' -ignore '\ngoogle.golang.org/grpc/balancer.go:SA1019\ngoogle.golang.org/grpc/balancer/roundrobin/roundrobin_test.go:SA1019\ngoogle.golang.org/grpc/balancer/xds/edsbalancer/balancergroup.go:SA1019\ngoogle.golang.org/grpc/balancer/xds/xds.go:SA1019\ngoogle.golang.org/grpc/balancer_conn_wrappers.go:SA1019\ngoogle.golang.org/grpc/balancer_test.go:SA1019\ngoogle.golang.org/grpc/benchmark/benchmain/main.go:SA1019\ngoogle.golang.org/grpc/benchmark/worker/benchmark_client.go:SA1019\ngoogle.golang.org/grpc/clientconn.go:S1024\ngoogle.golang.org/grpc/clientconn_state_transition_test.go:SA1019\ngoogle.golang.org/grpc/clientconn_test.go:SA1019\ngoogle.golang.org/grpc/internal/transport/handler_server.go:SA1019\ngoogle.golang.org/grpc/internal/transport/handler_server_test.go:SA1019\ngoogle.golang.org/grpc/resolver/dns/dns_resolver.go:SA1019\ngoogle.golang.org/grpc/stats/stats_test.go:SA1019\ngoogle.golang.org/grpc/test/channelz_test.go:SA1019\ngoogle.golang.org/grpc/test/end2end_test.go:SA1019\ngoogle.golang.org/grpc/test/healthcheck_test.go:SA1019\n' ./...\nmisspell -error .\n", "num_lines": 130}
{"repo_name": "prometheus", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2018 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eux -o pipefail\n\nTMP=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$TMP\"\n}\ntrap finish EXIT\n\npushd \"$TMP\"\nmkdir -p grpc/binarylog/grpc_binarylog_v1\ncurl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/binlog/v1/binarylog.proto > grpc/binarylog/grpc_binarylog_v1/binarylog.proto\n\nprotoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/binarylog/grpc_binarylog_v1/*.proto\npopd\nrm -f ./grpc_binarylog_v1/*.pb.go\ncp \"$TMP\"/grpc/binarylog/grpc_binarylog_v1/*.pb.go ../../binarylog/grpc_binarylog_v1/\n\n", "num_lines": 34}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -eux\n\nPYTORCH_DIR=\"$(cd $(dirname $0)/..; pwd -P)\"\nPYTORCH_ANDROID_DIR=$PYTORCH_DIR/android\n\necho \"PYTORCH_DIR:$PYTORCH_DIR\"\n\nsource \"$PYTORCH_ANDROID_DIR/common.sh\"\n\ncheck_android_sdk\ncheck_gradle\nparse_abis_list \"$@\"\nbuild_android\n\n# To set proxy for gradle add following lines to ./gradle/gradle.properties:\n# systemProp.http.proxyHost=...\n# systemProp.http.proxyPort=8080\n# systemProp.https.proxyHost=...\n# systemProp.https.proxyPort=8080\n\nif [ \"$CUSTOM_ABIS_LIST\" = true ]; then\n  NDK_DEBUG=1 $GRADLE_PATH -PnativeLibsDoNotStrip=true -PABI_FILTERS=$ABIS_LIST -p $PYTORCH_ANDROID_DIR clean test_app:assembleDebug\nelse\n  NDK_DEBUG=1 $GRADLE_PATH -PnativeLibsDoNotStrip=true -p $PYTORCH_ANDROID_DIR clean test_app:assembleDebug\nfi\n\nfind $PYTORCH_ANDROID_DIR -type f -name *apk\n\nfind $PYTORCH_ANDROID_DIR -type f -name *apk | xargs echo \"To install apk run: $ANDROID_HOME/platform-tools/adb install -r \"\n", "num_lines": 31}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n###############################################################################\n# This script tests the custom selective build flow for PyTorch Android, which\n# optimizes library size by only including ops used by a specific model.\n###############################################################################\n\nset -eux\n\nPYTORCH_DIR=\"$(cd $(dirname $0)/..; pwd -P)\"\nPYTORCH_ANDROID_DIR=\"${PYTORCH_DIR}/android\"\nBUILD_ROOT=\"${PYTORCH_DIR}/build_pytorch_android_custom\"\n\nsource \"${PYTORCH_ANDROID_DIR}/common.sh\"\n\nprepare_model_and_dump_root_ops() {\n  cd \"${BUILD_ROOT}\"\n  MODEL=\"${BUILD_ROOT}/MobileNetV2.pt\"\n  ROOT_OPS=\"${BUILD_ROOT}/MobileNetV2.yaml\"\n  python \"${PYTORCH_ANDROID_DIR}/test_app/make_assets_custom.py\"\n  cp \"${MODEL}\" \"${PYTORCH_ANDROID_DIR}/test_app/app/src/main/assets/mobilenet2.pt\"\n}\n\n# Start building\nmkdir -p \"${BUILD_ROOT}\"\ncheck_android_sdk\ncheck_gradle\nparse_abis_list \"$@\"\nprepare_model_and_dump_root_ops\nSELECTED_OP_LIST=\"${ROOT_OPS}\" build_android\n\n# TODO: change this to build test_app instead\n$GRADLE_PATH -PABI_FILTERS=$ABIS_LIST -p $PYTORCH_ANDROID_DIR clean assembleRelease\n", "num_lines": 33}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -eux\n\n##############################################################################\n# Common util functions for Android build scripts.\n##############################################################################\n\nif [ -z \"$PYTORCH_DIR\" ]; then\n  echo \"PYTORCH_DIR not set!\"\n  exit 1\nfi\n\ncheck_android_sdk() {\n  if [ -z \"$ANDROID_HOME\" ]; then\n    echo \"ANDROID_HOME not set; please set it to Android sdk directory\"\n    exit 1\n  fi\n\n  if [ ! -d \"$ANDROID_HOME\" ]; then\n    echo \"ANDROID_HOME not a directory; did you install it under $ANDROID_HOME?\"\n    exit 1\n  fi\n  echo \"ANDROID_HOME:$ANDROID_HOME\"\n}\n\ncheck_gradle() {\n  GRADLE_PATH=$PYTORCH_DIR/android/gradlew\n  echo \"GRADLE_PATH:$GRADLE_PATH\"\n}\n\nparse_abis_list() {\n  ABIS_LIST=\"x86\"\n  CUSTOM_ABIS_LIST=false\n  if [ $# -gt 0 ]; then\n    ABIS_LIST=$1\n    CUSTOM_ABIS_LIST=true\n  fi\n\n  echo \"ABIS_LIST:$ABIS_LIST\"\n  echo \"CUSTOM_ABIS_LIST:$CUSTOM_ABIS_LIST\"\n}\n\nbuild_android() {\n  PYTORCH_ANDROID_DIR=\"$PYTORCH_DIR/android\"\n  BUILD_ROOT=\"${BUILD_ROOT:-$PYTORCH_DIR}\"\n  echo \"BUILD_ROOT:$BUILD_ROOT\"\n\n  LIB_DIR=\"$PYTORCH_ANDROID_DIR/pytorch_android/src/main/jniLibs\"\n  INCLUDE_DIR=\"$PYTORCH_ANDROID_DIR/pytorch_android/src/main/cpp/libtorch_include\"\n\n  # These directories only contain symbolic links.\n  rm -rf \"$LIB_DIR\" && mkdir -p \"$LIB_DIR\"\n  rm -rf \"$INCLUDE_DIR\" && mkdir -p \"$INCLUDE_DIR\"\n\n  for abi in $(echo \"$ABIS_LIST\" | tr ',' '\\n')\n  do\n    echo \"abi:$abi\"\n    ANDROID_BUILD_ROOT=\"$BUILD_ROOT/build_android_$abi\"\n    ANDROID_ABI=\"$abi\" \\\n      BUILD_ROOT=\"$ANDROID_BUILD_ROOT\" \\\n      \"$PYTORCH_DIR/scripts/build_android.sh\" \\\n      -DANDROID_CCACHE=\"$(which ccache)\" \\\n      -DUSE_LITE_INTERPRETER_PROFILER=\"OFF\"\n\n    echo \"$abi build output lib,include at $ANDROID_BUILD_ROOT/install\"\n    ln -s \"$ANDROID_BUILD_ROOT/install/lib\" \"$LIB_DIR/$abi\"\n    ln -s \"$ANDROID_BUILD_ROOT/install/include\" \"$INCLUDE_DIR/$abi\"\n  done\n}\n", "num_lines": 70}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -eux\n\nPYTORCH_DIR=\"$(cd $(dirname $0)/..; pwd -P)\"\nPYTORCH_ANDROID_DIR=$PYTORCH_DIR/android\n\nsource \"$PYTORCH_ANDROID_DIR/common.sh\"\n\ncheck_android_sdk\ncheck_gradle\n\n# Run android instrumented tests on x86 emulator\n\nADB_PATH=$ANDROID_HOME/platform-tools/adb\n\necho \"Expecting running emulator\"\n$ADB_PATH devices\n\nDEVICES_COUNT=$($ADB_PATH devices | awk 'NF' | wc -l)\necho \"DEVICES_COUNT:$DEVICES_COUNT\"\n\nif [ \"$DEVICES_COUNT\" -eq 1 ]; then\n  echo \"Unable to found connected android emulators\"\ncat <<- EOF\n  To start android emulator:\n  1. Install android sdkmanager packages\n  $ANDROID_HOME/tools/bin/sdkmanager \"system-images;android-25;google_apis;x86\"\n\n  to specify proxy add params: --proxy=http --proxy_host=fwdproxy --proxy_port=8080\n\n  2. Create android virtual device\n  $ANDROID_HOME/tools/bin/avdmanager create avd --name \"x86_android25\" --package \"system-images;android-25;google_apis;x86\"\n\n  3. Start emulator in headless mode without audio\n  $ANDROID_HOME/tools/emulator -avd x86_android25 -no-audio -no-window\n\n  4. Check that emulator is running\n  $ANDROID_HOME/platform-tools/adb devices\n\n  If everything is ok the output will be:\n\n  List of devices attached\n  emulator-5554   device\nEOF\n  exit 1\nfi\n\necho \"Waiting for emulator boot completed\"\n$ADB_PATH wait-for-device shell 'while [[ -z $(getprop sys.boot_completed) ]]; do sleep 1; done;'\n\n$GRADLE_PATH -PABI_FILTERS=x86 -p $PYTORCH_ANDROID_DIR connectedAndroidTest\n", "num_lines": 52}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nif [ -z \"$PREFIX\" ]; then\n  PREFIX=\"$CONDA_PREFIX\"\nfi\n\n# When conda-build constructs a new working copy to perform a build\n# in, it recursively copies *all* files and directories in the original\n# source directory, including any pre-existing build products (e.g.,\n# if you previously ran cmake.)  This is problematic, because if\n# a 'build' directory already exists, cmake will reuse build settings\n# rather than recompute them from scratch.  We want a fresh build, so\n# we prophylactically remove the build directory.\nrm -rf build || true\n\nmkdir -p build\ncd build\ncmake -DCMAKE_INSTALL_PREFIX=\"$PREFIX\" -DCMAKE_PREFIX_PATH=\"$PREFIX\" -DCMAKE_BUILD_TYPE=Release $CONDA_CMAKE_ARGS ..\nmake install -j20\n", "num_lines": 22}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not set; please set it to the Android NDK directory\"\n  exit 1\nfi\n\nif [ ! -d \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not a directory; did you install it under ${ANDROID_NDK}?\"\n  exit 1\nfi\n\nmkdir -p build/android/arm64-v8a\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]\nthen\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=ON\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# Cross-compilation options for Google Benchmark\nCMAKE_ARGS+=(\"-DHAVE_POSIX_REGEX=0\")\nCMAKE_ARGS+=(\"-DHAVE_STEADY_CLOCK=0\")\nCMAKE_ARGS+=(\"-DHAVE_STD_REGEX=0\")\n\n# Android-specific options\nCMAKE_ARGS+=(\"-DANDROID_NDK=$ANDROID_NDK\")\nCMAKE_ARGS+=(\"-DANDROID_ABI=arm64-v8a\")\nCMAKE_ARGS+=(\"-DANDROID_PLATFORM=android-21\")\nCMAKE_ARGS+=(\"-DANDROID_PIE=ON\")\nCMAKE_ARGS+=(\"-DANDROID_STL=c++_static\")\nCMAKE_ARGS+=(\"-DANDROID_CPP_FEATURES=exceptions\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/android/arm64-v8a && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 69}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not set; please set it to the Android NDK directory\"\n  exit 1\nfi\n\nif [ ! -d \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not a directory; did you install it under ${ANDROID_NDK}?\"\n  exit 1\nfi\n\nmkdir -p build/android/armeabi-v7a\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]\nthen\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=ON\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# Cross-compilation options for Google Benchmark\nCMAKE_ARGS+=(\"-DHAVE_POSIX_REGEX=0\")\nCMAKE_ARGS+=(\"-DHAVE_STEADY_CLOCK=0\")\nCMAKE_ARGS+=(\"-DHAVE_STD_REGEX=0\")\n\n# Android-specific options\nCMAKE_ARGS+=(\"-DANDROID_NDK=$ANDROID_NDK\")\nCMAKE_ARGS+=(\"-DANDROID_ABI=armeabi-v7a\")\nCMAKE_ARGS+=(\"-DANDROID_PLATFORM=android-14\")\nCMAKE_ARGS+=(\"-DANDROID_PIE=ON\")\nCMAKE_ARGS+=(\"-DANDROID_STL=c++_static\")\nCMAKE_ARGS+=(\"-DANDROID_CPP_FEATURES=exceptions\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/android/armeabi-v7a && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 69}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not set; please set it to the Android NDK directory\"\n  exit 1\nfi\n\nif [ ! -d \"$ANDROID_NDK\" ]\nthen\n  echo \"ANDROID_NDK not a directory; did you install it under ${ANDROID_NDK}?\"\n  exit 1\nfi\n\nmkdir -p build/android/x86\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]\nthen\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=ON\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# Cross-compilation options for Google Benchmark\nCMAKE_ARGS+=(\"-DHAVE_POSIX_REGEX=0\")\nCMAKE_ARGS+=(\"-DHAVE_STEADY_CLOCK=0\")\nCMAKE_ARGS+=(\"-DHAVE_STD_REGEX=0\")\n\n# Android-specific options\nCMAKE_ARGS+=(\"-DANDROID_NDK=$ANDROID_NDK\")\nCMAKE_ARGS+=(\"-DANDROID_ABI=x86\")\nCMAKE_ARGS+=(\"-DANDROID_PLATFORM=android-14\")\nCMAKE_ARGS+=(\"-DANDROID_PIE=ON\")\nCMAKE_ARGS+=(\"-DANDROID_STL=c++_static\")\nCMAKE_ARGS+=(\"-DANDROID_CPP_FEATURES=exceptions\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/android/x86 && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 69}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/arm64\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=OFF\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=OFF\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=OS64\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=arm64\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/arm64 && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/arm64e\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=OFF\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=OFF\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=OS64\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=arm64e\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/arm64e && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/armv7\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=OFF\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=OFF\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=OS64\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=armv7\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/armv7 && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/armv7s\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=OFF\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=OFF\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=OS64\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=armv7s\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/armv7s && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/i386\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=OFF\") # Google Benchmark is broken on 32-bit iOS\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=SIMULATOR\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=i386\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/i386 && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nif [ -z \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not set; please set it to path of CMake toolchain file for iOS\"\n  exit 1\nfi\n\nif [ ! -f \"$IOS_CMAKE_TOOLCHAIN_FILE\" ]\nthen\n  echo \"IOS_CMAKE_TOOLCHAIN_FILE not a file path; did you properly setup ${IOS_CMAKE_TOOLCHAIN_FILE}?\"\n  exit 1\nfi\n\nmkdir -p build/ios/x86_64\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$IOS_CMAKE_TOOLCHAIN_FILE\")\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# QNNPACK-specific options\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=ON\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# Cross-compilation options for Google Benchmark\nCMAKE_ARGS+=(\"-DHAVE_POSIX_REGEX=0\")\nCMAKE_ARGS+=(\"-DHAVE_STEADY_CLOCK=0\")\nCMAKE_ARGS+=(\"-DHAVE_STD_REGEX=0\")\n\n# iOS-specific options\nCMAKE_ARGS+=(\"-DIOS_PLATFORM=SIMULATOR64\")\nCMAKE_ARGS+=(\"-DIOS_ARCH=x86_64\")\nCMAKE_ARGS+=(\"-DENABLE_BITCODE=OFF\")\nCMAKE_ARGS+=(\"-DENABLE_ARC=OFF\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/ios/x86_64 && cmake ../../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 61}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nmkdir -p build/local\n\nCMAKE_ARGS=()\n\n# CMake-level configuration\nCMAKE_ARGS+=(\"-DCMAKE_BUILD_TYPE=Release\")\nCMAKE_ARGS+=(\"-DCMAKE_POSITION_INDEPENDENT_CODE=ON\")\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]\nthen\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_LIBRARY_TYPE=static\")\n\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_BENCHMARKS=ON\")\nCMAKE_ARGS+=(\"-DPYTORCH_QNNPACK_BUILD_TESTS=ON\")\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\ncd build/local && cmake ../.. \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n  cmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\nelse\n  cmake --build . -- \"-j$(nproc)\"\nfi\n", "num_lines": 43}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nadb push build/android/arm64-v8a/convolution-test /data/local/tmp/convolution-test\nadb push build/android/arm64-v8a/deconvolution-test /data/local/tmp/deconvolution-test\nadb push build/android/arm64-v8a/q8gemm-test /data/local/tmp/q8gemm-test\nadb push build/android/arm64-v8a/q8conv-test /data/local/tmp/q8conv-test\nadb push build/android/arm64-v8a/q8dw-test /data/local/tmp/q8dw-test\nadb push build/android/arm64-v8a/hgemm-test /data/local/tmp/hgemm-test\nadb push build/android/arm64-v8a/sgemm-test /data/local/tmp/sgemm-test\n\nadb shell /data/local/tmp/convolution-test --gtest_color=yes\nadb shell /data/local/tmp/deconvolution-test --gtest_color=yes\nadb shell /data/local/tmp/q8gemm-test --gtest_color=yes\nadb shell /data/local/tmp/q8conv-test --gtest_color=yes\nadb shell /data/local/tmp/q8dw-test --gtest_color=yes\nadb shell /data/local/tmp/hgemm-test --gtest_color=yes\nadb shell /data/local/tmp/sgemm-test --gtest_color=yes\n", "num_lines": 26}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nadb push build/android/armeabi-v7a/convolution-test /data/local/tmp/convolution-test\nadb push build/android/armeabi-v7a/deconvolution-test /data/local/tmp/deconvolution-test\nadb push build/android/armeabi-v7a/q8gemm-test /data/local/tmp/q8gemm-test\nadb push build/android/armeabi-v7a/q8conv-test /data/local/tmp/q8conv-test\nadb push build/android/armeabi-v7a/q8dw-test /data/local/tmp/q8dw-test\nadb push build/android/armeabi-v7a/hgemm-test /data/local/tmp/hgemm-test\nadb push build/android/armeabi-v7a/sgemm-test /data/local/tmp/sgemm-test\n\nadb shell /data/local/tmp/convolution-test --gtest_color=yes\nadb shell /data/local/tmp/deconvolution-test --gtest_color=yes\nadb shell /data/local/tmp/q8gemm-test --gtest_color=yes\nadb shell /data/local/tmp/q8conv-test --gtest_color=yes\nadb shell /data/local/tmp/q8dw-test --gtest_color=yes\nadb shell /data/local/tmp/hgemm-test --gtest_color=yes\nadb shell /data/local/tmp/sgemm-test --gtest_color=yes\n", "num_lines": 26}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nset -e\n\nadb push build/android/x86/convolution-test /data/local/tmp/convolution-test\nadb push build/android/x86/deconvolution-test /data/local/tmp/deconvolution-test\nadb push build/android/x86/q8gemm-test /data/local/tmp/q8gemm-test\nadb push build/android/x86/q8conv-test /data/local/tmp/q8conv-test\nadb push build/android/x86/q8dw-test /data/local/tmp/q8dw-test\nadb push build/android/x86/hgemm-test /data/local/tmp/hgemm-test\nadb push build/android/x86/sgemm-test /data/local/tmp/sgemm-test\n\nadb shell /data/local/tmp/convolution-test --gtest_color=yes\nadb shell /data/local/tmp/deconvolution-test --gtest_color=yes\nadb shell /data/local/tmp/q8gemm-test --gtest_color=yes\nadb shell /data/local/tmp/q8conv-test --gtest_color=yes\nadb shell /data/local/tmp/q8dw-test --gtest_color=yes\nadb shell /data/local/tmp/hgemm-test --gtest_color=yes\nadb shell /data/local/tmp/sgemm-test --gtest_color=yes\n", "num_lines": 26}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nset -e\n\nVALGRIND_SUP=\"${PWD}/`dirname $0`/valgrind.sup\"\npushd $1\n\nVALGRIND=${VALGRIND:=ON}\n./basic\n./atest\n./scalar_test\n./broadcast_test\n./wrapdim_test\n./apply_utils_test\n./dlconvertor_test\n./native_test\n./scalar_tensor_test\n./tensor_interop_test\n./undefined_tensor_test\n./extension_backend_test\n./lazy_tensor_test\n./tensor_iterator_test\n./Dimname_test\n./Dict_test\n./NamedTensor_test\n./cpu_generator_test\n./vmap_test\n./operators_test\nif [[ -x ./cudnn_test ]]; then\n  ./cudnn_test\nfi\nif [[ -x ./cuda_generator_test ]]; then\n  ./cuda_generator_test\nfi\nif [[ -x ./apply_test ]]; then\n  ./apply_test\nfi\nif [[ -x ./stream_test ]]; then\n  ./stream_test\nfi\nif [[ -x ./cuda_half_test ]]; then\n  ./cuda_half_test\nfi\nif [[ -x ./cuda_vectorized_test ]]; then\n  ./cuda_vectorized_test\nfi\nif [[ -x ./cuda_distributions_test ]]; then\n  ./cuda_distributions_test\nfi\nif [[ -x ./cuda_optional_test ]]; then\n  ./cuda_optional_test\nfi\nif [[ -x ./cuda_tensor_interop_test ]]; then\n  ./cuda_tensor_interop_test\nfi\nif [[ -x ./cuda_complex_test ]]; then\n  ./cuda_complex_test\nfi\nif [[ -x ./cuda_complex_math_test ]]; then\n  ./cuda_complex_math_test\nfi\nif [[ -x ./cuda_cub_test ]]; then\n  ./cuda_cub_test\nfi\nif [ \"$VALGRIND\" == \"ON\" ]\nthen\n  valgrind --suppressions=\"$VALGRIND_SUP\" --error-exitcode=1 ./basic --gtest_filter='-*CUDA'\n  valgrind --suppressions=\"$VALGRIND_SUP\" --error-exitcode=1 ./tensor_interop_test\nfi\n\npopd\n", "num_lines": 72}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nset -e\nINSTALL_ROOT=$1\nSRC_ROOT=$2\nrm -rf test_build\nmkdir test_build\ncd test_build\ncmake -DCMAKE_PREFIX_PATH=$INSTALL_ROOT $SRC_ROOT/src/ATen/test/test_install\nmake\n./main\n", "num_lines": 12}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\npython -m fastrnns.bench --fuser=old --group=rnns --print-json oss > old.json\npython -m fastrnns.bench --fuser=te --group=rnns  --print-json oss > te.json\npython compare-fastrnn-results.py old.json te.json --format md\n", "num_lines": 5}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "OUTFILE=spmm-no-mkl-test.txt\nPYTORCH_HOME=$1\n\ncd $PYTORCH_HOME\n\necho \"\" >> $OUTFILE\necho \"----- USE_MKL=1 -----\" >> $OUTFILE\nrm -rf build\n\nexport USE_MKL=1\nexport CMAKE_PREFIX_PATH=${CONDA_PREFIX:-\"$(dirname $(which conda))/../\"}\npython setup.py build --cmake-only\nccmake build  # or cmake-gui build\n\npython setup.py install\n\ncd benchmarks\necho \"!! SPARSE SPMM TIME BENCHMARK!! \" >> $OUTFILE\nfor dim0 in 1000 5000 10000; do\n    for nnzr in 0.01 0.05 0.1 0.3; do\n        python -m sparse.spmm --format csr --m $dim0 --n $dim0 --k $dim0 --nnz_ratio $nnzr --outfile $OUTFILE\n        # python -m sparse.spmm --format coo --m $dim0 --n $dim0 --k $dim0 --nnz_ratio $nnzr --outfile $OUTFILE\n    done\ndone\necho \"----------------------\" >> $OUTFILE\n\ncd $PYTORCH_HOME\necho \"----- USE_MKL=0 ------\" >> $OUTFILE\nrm -rf build\n\nexport USE_MKL=0\npython setup.py install\n\ncd benchmarks\nfor dim0 in 1000 5000 10000; do\n    for nnzr in 0.01 0.05 0.1 0.3; do\n        python -m sparse.spmv --format csr --m $dim0 --nnz_ratio $nnzr --outfile $OUTFILE\n        python -m sparse.spmv --format coo --m $dim0 --nnz_ratio $nnzr --outfile $OUTFILE\n    done\ndone\necho \"----------------------\" >> $OUTFILE\n", "num_lines": 42}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nDATASET_ROOT_DIR=$HOME/datasets/\n\n# wget https://storage.googleapis.com/sgk-sc2020/dlmc.tar.gz -P $DATASET_ROOT_DIR\n# tar -xvf $DATASET_ROOT_DIR/dlmc.tar.gz\n\necho \"!! SPARSE SPMS TIME BENCHMARK!! \"\n\n# cpu\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@sparse\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@sparse --backward_test\n\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@dense\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@dense --backward_test\n\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@vector\n\n\n# cuda\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@sparse --with_cuda\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@sparse --with_cuda--backward_test\n\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@dense --with_cuda\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@dense --with_cuda --backward_test\n\npython -m dlmc.matmul_bench  --path $DATASET_ROOT_DIR/dlmc/rn50 --dataset magnitude_pruning --operation sparse@vector --with_cuda\n", "num_lines": 28}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Generate type stubs for .proto definition files.\n\n# This should be run from as\n# ./gen_proto_typestubs.sh\n# (i.e., from inside the proto/ directory)\n\n# assumes mypy-protobuf installed to ~/.local; i.e. via\n# pip3 install mypy-protobuf --user\n\nset -euxo pipefail\n\nMYPY_PROTOBUF_HOME=\"${1:-${HOME}/.local/bin}\"\n\npushd ../../\nbuck run fbsource//third-party/protobuf:protoc -- --plugin=protoc-gen-mypy=\"${MYPY_PROTOBUF_HOME}\"/protoc-gen-mypy --mypy_out=./ caffe2/proto/*.proto\npopd\n\n# get rid of 'builtins.' prefix, which pyre does not like\nsed -E -i 's/builtins\\.//g' ./*.pyi\n\n# mypy-protobuf references types from other mypy-protobuf-generated stubs as\n# 'type.V', but it should just be 'type', so we get rid of the '.V' suffix\n# when it's not followed by parens to indicate a particular enum value.\nsed -E -i 's/\\.V([^(_[:alnum:]])/\\1/g' ./*.pyi\n\n# ---------------------------\n# Freedom-patched DeviceTypes\n# ---------------------------\n#\n# In order to make DeviceTypes like CPU, CUDA, etc. directly accessible from\n# the caffe2_pb2 module, they are currently freedom-patched into it in\n# caffe2/python/__init__.py. This is not ideal: it would be better if these\n# were autogenerated when the protobuf definitions were created by using\n# allow_alias = true in the DeviceTypeProto definition in caffe2.proto.\n#\n# However, it is impossible to do this currently without significant effort.\n# The issue is that the generated proto constants would conflict with various\n# constants defined in the C++ caffe2 codebase (`caffe2_pb2.h`). We cannot\n# simply remove these constants and replace them with the caffe2\n# DeviceTypeProto constants, because a huge portion of code expects\n# at::DeviceType constants defined in `core/DeviceType.h` (apparently\n# duplicated to avoid having to figure out how to autogenerate the protobuf\n# definitions using cmake for ATen).\n#\n# Instead, we make a best-effort to add additional definitions in\n# `caffe2_pb2.py` by looking for any freedom-patched constants in\n# `caffe2/python/__init__.py` and making sure they have corresponding stubs in\n# the pyi (see `gen_proto_typestubs_helper.py`).\n\npython3 ./gen_proto_typestubs_helper.py >> caffe2_pb2.pyi\n", "num_lines": 53}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nignore_warning() {\n  # Invert match to filter out $1.\n  set +e\n  grep -v \"$1\" doxygen-log.txt > temp.txt\n  set -e\n  mv temp.txt doxygen-log.txt\n}\n\ncommand -v doxygen >/dev/null 2>&1 || { echo >&2 \"doxygen is not supported. Aborting.\"; exit 1; }\n\npushd \"$(dirname \"$0\")/../../..\"\n\ncp torch/_utils_internal.py tools/shared\n\npython -m tools.codegen.gen\n\npython tools/setup_helpers/generate_code.py                 \\\n  --declarations-path build/aten/src/ATen/Declarations.yaml \\\n  --native-functions-path aten/src/ATen/native/native_functions.yaml \\\n  --nn-path aten/src\n\npopd\n\n# Run doxygen and log all output.\ndoxygen \"$(dirname $0)\" 2> original-doxygen-log.txt\ncp original-doxygen-log.txt doxygen-log.txt\n\n# Uncomment this if you need it for debugging; we're not printing this\n# by default because it is confusing.\n# echo \"Original output\"\n# cat original-doxygen-log.txt\n\n# Filter out some warnings.\nignore_warning \"warning: no uniquely matching class member found for\"\nignore_warning \"warning: explicit link request to 'Item' could not be resolved\"\nignore_warning \"warning: Included by graph for 'types.h' not generated, too many nodes\"\n\n# Count the number of remaining warnings.\nwarnings=\"$(grep 'warning:' doxygen-log.txt | wc -l)\"\n\necho \"Treating all remaining warnings as errors\"\n\nif [[ \"$warnings\" -ne \"0\" ]]; then\n  echo \"Failing Doxygen test because the following warnings were treated fatally:\"\n  cat doxygen-log.txt\n  echo \"Please fix these warnings.  To run this test locally, use docs/cpp/source/check-doxygen.sh\"\n  rm -f doxygen-log.txt original-doxygen-log.txt\n  exit 1\nfi\n\nrm -f doxygen-log.txt original-doxygen-log.txt\n", "num_lines": 56}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "cat  apache_header.txt $1 > _add_apache_header.txt && mv _add_apache_header.txt $1\n", "num_lines": 2}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Example command to build the android target.\n##############################################################################\n#\n# This script shows how one can build a Caffe2 binary for the Android platform\n# using android-cmake. A few notes:\n#\n# (1) This build also does a host build for protobuf. You will need autoconf\n#     to carry out this. If autoconf is not possible, you will need to provide\n#     a pre-built protoc binary that is the same version as the protobuf\n#     version under third_party.\n#     If you are building on Mac, you might need to install autotool and\n#     libtool. The easiest way is via homebrew:\n#         brew install automake\n#         brew install libtool\n# (2) You will need to have android ndk installed. The current script assumes\n#     that you set ANDROID_NDK to the location of ndk.\n# (3) The toolchain and the build target platform can be specified with the\n#     cmake arguments below. For more details, check out android-cmake's doc.\n\nset -e\n\n# Android specific flags\nif [ -z \"$ANDROID_ABI\" ]; then\n  ANDROID_ABI=\"armeabi-v7a with NEON\"\nfi\nANDROID_NATIVE_API_LEVEL=\"21\"\necho \"Build with ANDROID_ABI[$ANDROID_ABI], ANDROID_NATIVE_API_LEVEL[$ANDROID_NATIVE_API_LEVEL]\"\n\nCAFFE2_ROOT=\"$( cd \"$(dirname \"$0\")\"/.. ; pwd -P)\"\nif [ -z \"$ANDROID_NDK\" ]; then\n  echo \"ANDROID_NDK not set; please set it to the Android NDK directory\"\n  exit 1\nfi\n\nif [ ! -d \"$ANDROID_NDK\" ]; then\n  echo \"ANDROID_NDK not a directory; did you install it under $ANDROID_NDK?\"\n  exit 1\nfi\n\nif [ -z \"$PYTHON\" ]; then\n  PYTHON=python\n  PYTHON_VERSION_MAJOR=$($PYTHON -c 'import sys; print(sys.version_info[0])')\n  if [ \"${PYTHON_VERSION_MAJOR}\" -le 2 ]; then\n    echo \"Default python executable is Python-2, trying to use python3 alias\"\n    PYTHON=python3\n  fi\nfi\n\nANDROID_NDK_PROPERTIES=\"$ANDROID_NDK/source.properties\"\n[ -f \"$ANDROID_NDK_PROPERTIES\" ] && ANDROID_NDK_VERSION=$(sed -n 's/^Pkg.Revision[^=]*= *\\([0-9]*\\)\\..*$/\\1/p' \"$ANDROID_NDK_PROPERTIES\")\n\necho \"Bash: $(/bin/bash --version | head -1)\"\necho \"Python: $($PYTHON -c 'import sys; print(sys.version)')\"\necho \"Caffe2 path: $CAFFE2_ROOT\"\necho \"Using Android NDK at $ANDROID_NDK\"\necho \"Android NDK version: $ANDROID_NDK_VERSION\"\n\nCMAKE_ARGS=()\n\nif [ -z \"${BUILD_CAFFE2_MOBILE:-}\" ]; then\n  # Build PyTorch mobile\n  CMAKE_ARGS+=(\"-DCMAKE_PREFIX_PATH=$($PYTHON -c 'import sysconfig; print(sysconfig.get_path(\"purelib\"))')\")\n  CMAKE_ARGS+=(\"-DPYTHON_EXECUTABLE=$($PYTHON -c 'import sys; print(sys.executable)')\")\n  CMAKE_ARGS+=(\"-DBUILD_CUSTOM_PROTOBUF=OFF\")\n  # custom build with selected ops\n  if [ -n \"${SELECTED_OP_LIST}\" ]; then\n    SELECTED_OP_LIST=\"$(cd $(dirname $SELECTED_OP_LIST); pwd -P)/$(basename $SELECTED_OP_LIST)\"\n    echo \"Choose SELECTED_OP_LIST file: $SELECTED_OP_LIST\"\n    if [ ! -r ${SELECTED_OP_LIST} ]; then\n      echo \"Error: SELECTED_OP_LIST file ${SELECTED_OP_LIST} not found.\"\n      exit 1\n    fi\n    CMAKE_ARGS+=(\"-DSELECTED_OP_LIST=${SELECTED_OP_LIST}\")\n  fi\nelse\n  # Build Caffe2 mobile\n  CMAKE_ARGS+=(\"-DBUILD_CAFFE2_MOBILE=ON\")\n  # Build protobuf from third_party so we have a host protoc binary.\n  echo \"Building protoc\"\n  $CAFFE2_ROOT/scripts/build_host_protoc.sh\n  # Use locally built protoc because we'll build libprotobuf for the\n  # target architecture and need an exact version match.\n  CMAKE_ARGS+=(\"-DCAFFE2_CUSTOM_PROTOC_EXECUTABLE=$CAFFE2_ROOT/build_host_protoc/bin/protoc\")\nfi\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]; then\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\n# Use android-cmake to build Android project from CMake.\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK/build/cmake/android.toolchain.cmake\")\n\nif [ -z \"$BUILD_MOBILE_BENCHMARK\" ]; then\n  BUILD_MOBILE_BENCHMARK=0\nfi\n\nif [ -z \"$BUILD_MOBILE_TEST\" ]; then\n  BUILD_MOBILE_TEST=0\nfi\n# Don't build artifacts we don't need\nCMAKE_ARGS+=(\"-DBUILD_TEST=OFF\")\nCMAKE_ARGS+=(\"-DBUILD_BINARY=OFF\")\n\n# If there exists env variable and it equals to 0, build full jit interpreter.\n# Default behavior is to build lite interpreter\n# cmd:  BUILD_LITE_INTERPRETER=0 ./scripts/build_android.sh\nif [ \"${BUILD_LITE_INTERPRETER}\" == 0 ]; then\n  CMAKE_ARGS+=(\"-DBUILD_LITE_INTERPRETER=OFF\")\nelse\n  CMAKE_ARGS+=(\"-DBUILD_LITE_INTERPRETER=ON\")\nfi\nCMAKE_ARGS+=(\"-DBUILD_MOBILE_BENCHMARK=$BUILD_MOBILE_BENCHMARK\")\nCMAKE_ARGS+=(\"-DBUILD_MOBILE_TEST=$BUILD_MOBILE_TEST\")\nCMAKE_ARGS+=(\"-DBUILD_PYTHON=OFF\")\nCMAKE_ARGS+=(\"-DBUILD_SHARED_LIBS=OFF\")\nif (( \"${ANDROID_NDK_VERSION:-0}\" < 18 )); then\n  CMAKE_ARGS+=(\"-DANDROID_TOOLCHAIN=gcc\")\nelse\n  CMAKE_ARGS+=(\"-DANDROID_TOOLCHAIN=clang\")\nfi\n# Disable unused dependencies\nCMAKE_ARGS+=(\"-DUSE_CUDA=OFF\")\nCMAKE_ARGS+=(\"-DUSE_GFLAGS=OFF\")\nCMAKE_ARGS+=(\"-DUSE_OPENCV=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LMDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LEVELDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_MPI=OFF\")\nCMAKE_ARGS+=(\"-DUSE_OPENMP=OFF\")\n# Only toggle if VERBOSE=1\nif [ \"${VERBOSE:-}\" == '1' ]; then\n  CMAKE_ARGS+=(\"-DCMAKE_VERBOSE_MAKEFILE=1\")\nfi\n\n# Android specific flags\nCMAKE_ARGS+=(\"-DANDROID_NDK=$ANDROID_NDK\")\nCMAKE_ARGS+=(\"-DANDROID_ABI=$ANDROID_ABI\")\nCMAKE_ARGS+=(\"-DANDROID_NATIVE_API_LEVEL=$ANDROID_NATIVE_API_LEVEL\")\nCMAKE_ARGS+=(\"-DANDROID_CPP_FEATURES=rtti exceptions\")\nif [ \"${ANDROID_STL_SHARED:-}\" == '1' ]; then\n  CMAKE_ARGS+=(\"-DANDROID_STL=c++_shared\")\nfi\nif [ \"${ANDROID_DEBUG_SYMBOLS:-}\" == '1' ]; then\n  CMAKE_ARGS+=(\"-DANDROID_DEBUG_SYMBOLS=1\")\nfi\n\nif [ -n \"${USE_VULKAN}\" ]; then\n  CMAKE_ARGS+=(\"-DUSE_VULKAN=ON\")\nfi\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=($@)\n\n# Now, actually build the Android target.\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build_android\"}\nINSTALL_PREFIX=${BUILD_ROOT}/install\nmkdir -p $BUILD_ROOT\ncd $BUILD_ROOT\ncmake \"$CAFFE2_ROOT\" \\\n    -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ -z \"$MAX_JOBS\" ]; then\n  if [ \"$(uname)\" == 'Darwin' ]; then\n    MAX_JOBS=$(sysctl -n hw.ncpu)\n  else\n    MAX_JOBS=$(nproc)\n  fi\nfi\n\necho \"Will install headers and libs to $INSTALL_PREFIX for further Android project usage.\"\ncmake --build . --target install -- \"-j${MAX_JOBS}\"\necho \"Installation completed, now you can copy the headers/libs from $INSTALL_PREFIX to your Android project directory.\"\n", "num_lines": 178}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Build script to build the protoc compiler for the host platform.\n##############################################################################\n# This script builds the protoc compiler for the host platform, which is needed\n# for any cross-compilation as we will need to convert the protobuf source\n# files to cc files.\n#\n# --other-flags accepts flags that should be passed to cmake. Optional.\n#\n# After the execution of the file, one should be able to find the host protoc\n# binary at build_host_protoc/bin/protoc.\n\nset -e\n\nCAFFE2_ROOT=\"$( cd \"$(dirname -- \"$0\")\"/.. ; pwd -P)\"\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build_host_protoc\"}\nmkdir -p $BUILD_ROOT/build\ncd $BUILD_ROOT/build\n\nCMAKE_ARGS=()\nCMAKE_ARGS+=(\"-DCMAKE_INSTALL_PREFIX=$BUILD_ROOT\")\nCMAKE_ARGS+=(\"-Dprotobuf_BUILD_TESTS=OFF\")\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]; then\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\nwhile true; do\n    case \"$1\" in\n        --other-flags)\n            shift;\n            CMAKE_ARGS+=(\"$@\")\n            break ;;\n        \"\")\n            break ;;\n        *)\n            echo \"Unknown option passed as argument: $1\"\n            break ;;\n    esac\ndone\n\n# Use ccache if available (this path is where Homebrew installs ccache symlinks)\nif [ \"$(uname)\" == 'Darwin' ] && [ -d /usr/local/opt/ccache/libexec ]; then\n  CMAKE_ARGS+=(\"-DCMAKE_C_COMPILER=/usr/local/opt/ccache/libexec/gcc\")\n  CMAKE_ARGS+=(\"-DCMAKE_CXX_COMPILER=/usr/local/opt/ccache/libexec/g++\")\nfi\n\ncmake \"$CAFFE2_ROOT/third_party/protobuf/cmake\" ${CMAKE_ARGS[@]}\n\nif [ -z \"$MAX_JOBS\" ]; then\n  if [ \"$(uname)\" == 'Darwin' ]; then\n    MAX_JOBS=$(sysctl -n hw.ncpu)\n  else\n    MAX_JOBS=$(nproc)\n  fi\nfi\ncmake --build . -- \"-j${MAX_JOBS}\" install\n", "num_lines": 60}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash -xe\n##############################################################################\n# Example command to build the iOS target.\n##############################################################################\n#\n# This script shows how one can build a Caffe2 binary for the iOS platform\n# using ios-cmake. This is very similar to the android-cmake - see\n# build_android.sh for more details.\n\nCAFFE2_ROOT=\"$( cd \"$(dirname \"$0\")\"/.. ; pwd -P)\"\n\nCMAKE_ARGS=()\n\nif [ -z \"${BUILD_CAFFE2_MOBILE:-}\" ]; then\n  # Build PyTorch mobile\n  CMAKE_ARGS+=(\"-DCMAKE_PREFIX_PATH=$(python -c 'import sysconfig; print(sysconfig.get_path(\"purelib\"))')\")\n  CMAKE_ARGS+=(\"-DPYTHON_EXECUTABLE=$(python -c 'import sys; print(sys.executable)')\")\n  CMAKE_ARGS+=(\"-DBUILD_CUSTOM_PROTOBUF=OFF\")\n  # custom build with selected ops\n  if [ -n \"${SELECTED_OP_LIST}\" ]; then\n    SELECTED_OP_LIST=\"$(cd $(dirname $SELECTED_OP_LIST); pwd -P)/$(basename $SELECTED_OP_LIST)\"\n    echo \"Choose SELECTED_OP_LIST file: $SELECTED_OP_LIST\"\n    if [ ! -r ${SELECTED_OP_LIST} ]; then\n      echo \"Error: SELECTED_OP_LIST file ${SELECTED_OP_LIST} not found.\"\n      exit 1\n    fi\n    CMAKE_ARGS+=(\"-DSELECTED_OP_LIST=${SELECTED_OP_LIST}\")\n  fi\n  # bitcode\n  if [ \"${ENABLE_BITCODE:-}\" == '1' ]; then\n    CMAKE_ARGS+=(\"-DCMAKE_C_FLAGS=-fembed-bitcode\")\n    CMAKE_ARGS+=(\"-DCMAKE_CXX_FLAGS=-fembed-bitcode\")\n  fi\nelse\n  # Build Caffe2 mobile\n  CMAKE_ARGS+=(\"-DBUILD_CAFFE2_MOBILE=ON\")\n  # Build protobuf from third_party so we have a host protoc binary.\n  echo \"Building protoc\"\n  BITCODE_FLAGS=\"-DCMAKE_C_FLAGS=-fembed-bitcode -DCMAKE_CXX_FLAGS=-fembed-bitcode \"\n  $CAFFE2_ROOT/scripts/build_host_protoc.sh --other-flags $BITCODE_FLAGS\n  # Use locally built protoc because we'll build libprotobuf for the\n  # target architecture and need an exact version match.\n  CMAKE_ARGS+=(\"-DCAFFE2_CUSTOM_PROTOC_EXECUTABLE=$CAFFE2_ROOT/build_host_protoc/bin/protoc\")\n  # Bitcode is enabled by default for caffe2\n  CMAKE_ARGS+=(\"-DCMAKE_C_FLAGS=-fembed-bitcode\")\n  CMAKE_ARGS+=(\"-DCMAKE_CXX_FLAGS=-fembed-bitcode\")\nfi\n\n# Use ios-cmake to build iOS project from CMake.\n# This projects sets CMAKE_C_COMPILER to /usr/bin/gcc and\n# CMAKE_CXX_COMPILER to /usr/bin/g++. In order to use ccache (if it is available) we\n# must override these variables via CMake arguments.\nCMAKE_ARGS+=(\"-DCMAKE_TOOLCHAIN_FILE=$CAFFE2_ROOT/cmake/iOS.cmake\")\nif [ -n \"${CCACHE_WRAPPER_PATH:-}\"]; then\n  CCACHE_WRAPPER_PATH=/usr/local/opt/ccache/libexec\nfi\nif [ -d \"$CCACHE_WRAPPER_PATH\" ]; then\n  CMAKE_ARGS+=(\"-DCMAKE_C_COMPILER=$CCACHE_WRAPPER_PATH/gcc\")\n  CMAKE_ARGS+=(\"-DCMAKE_CXX_COMPILER=$CCACHE_WRAPPER_PATH/g++\")\nfi\n\n# IOS_PLATFORM controls type of iOS platform (see ios-cmake)\nif [ -n \"${IOS_PLATFORM:-}\" ]; then\n  CMAKE_ARGS+=(\"-DIOS_PLATFORM=${IOS_PLATFORM}\")\n  if [ \"${IOS_PLATFORM}\" == \"WATCHOS\" ]; then\n      # enable bitcode by default for watchos\n      CMAKE_ARGS+=(\"-DCMAKE_C_FLAGS=-fembed-bitcode\")\n      CMAKE_ARGS+=(\"-DCMAKE_CXX_FLAGS=-fembed-bitcode\")\n      # disable the QNNPACK\n      CMAKE_ARGS+=(\"-DUSE_PYTORCH_QNNPACK=OFF\")\n  fi\nelse\n  # IOS_PLATFORM is not set, default to OS, which builds iOS.\n  CMAKE_ARGS+=(\"-DIOS_PLATFORM=OS\")\nfi\n\nif [ -n \"${IOS_ARCH:-}\" ]; then\n  CMAKE_ARGS+=(\"-DIOS_ARCH=${IOS_ARCH}\")\nfi\n\nif [ \"${BUILD_LITE_INTERPRETER}\" == 0 ]; then\n  CMAKE_ARGS+=(\"-DBUILD_LITE_INTERPRETER=OFF\")\nelse\n  CMAKE_ARGS+=(\"-DBUILD_LITE_INTERPRETER=ON\")\nfi\nCMAKE_ARGS+=(\"-DUSE_LITE_INTERPRETER_PROFILER=OFF\")\n\n# Don't build binaries or tests (only the library)\nCMAKE_ARGS+=(\"-DBUILD_TEST=OFF\")\nCMAKE_ARGS+=(\"-DBUILD_BINARY=OFF\")\nCMAKE_ARGS+=(\"-DBUILD_PYTHON=OFF\")\n\n# Disable unused dependencies\nCMAKE_ARGS+=(\"-DUSE_CUDA=OFF\")\nCMAKE_ARGS+=(\"-DUSE_GFLAGS=OFF\")\nCMAKE_ARGS+=(\"-DUSE_OPENCV=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LMDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LEVELDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_MPI=OFF\")\nCMAKE_ARGS+=(\"-DUSE_NUMPY=OFF\")\nCMAKE_ARGS+=(\"-DUSE_NNPACK=OFF\")\nCMAKE_ARGS+=(\"-DUSE_MKLDNN=OFF\")\n\n# Metal\nif [ \"${USE_PYTORCH_METAL:-}\" == \"1\" ]; then\n  CMAKE_ARGS+=(\"-DUSE_PYTORCH_METAL=ON\")\nfi\n\n# Core ML\nif [ \"${USE_COREML_DELEGATE}\" == \"1\" ]; then\n  CMAKE_ARGS+=(\"-DUSE_COREML_DELEGATE=ON\")\nfi\n\n# pthreads\nCMAKE_ARGS+=(\"-DCMAKE_THREAD_LIBS_INIT=-lpthread\")\nCMAKE_ARGS+=(\"-DCMAKE_HAVE_THREADS_LIBRARY=1\")\nCMAKE_ARGS+=(\"-DCMAKE_USE_PTHREADS_INIT=1\")\n\n# Only toggle if VERBOSE=1\nif [ \"${VERBOSE:-}\" == '1' ]; then\n  CMAKE_ARGS+=(\"-DCMAKE_VERBOSE_MAKEFILE=1\")\nfi\n\n# Now, actually build the iOS target.\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build_ios\"}\nINSTALL_PREFIX=${BUILD_ROOT}/install\nmkdir -p $BUILD_ROOT\ncd $BUILD_ROOT\ncmake \"$CAFFE2_ROOT\" \\\n    -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX \\\n    -DCMAKE_BUILD_TYPE=MinSizeRel \\\n    -DBUILD_SHARED_LIBS=OFF \\\n    ${CMAKE_ARGS[@]} \\\n    $@\n\ncmake --build . -- \"-j$(sysctl -n hw.ncpu)\"\n\n# copy headers and libs to install directory\necho \"Will install headers and libs to $INSTALL_PREFIX for further Xcode project usage.\"\nmake install\necho \"Installation completed, now you can copy the headers/libs from $INSTALL_PREFIX to your Xcode project directory.\"\n", "num_lines": 142}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n##############################################################################\n# Example command to build Caffe2\n##############################################################################\n#\n\nset -ex\n\nCAFFE2_ROOT=\"$( cd \"$(dirname \"$0\")\"/.. ; pwd -P)\"\n\nCMAKE_ARGS=()\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]; then\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\n# Use ccache if available (this path is where Homebrew installs ccache symlinks)\nif [ \"$(uname)\" == 'Darwin' ]; then\n  if [ -n \"${CCACHE_WRAPPER_PATH:-}\"]; then\n    CCACHE_WRAPPER_PATH=/usr/local/opt/ccache/libexec\n  fi\n  if [ -d \"$CCACHE_WRAPPER_PATH\" ]; then\n    CMAKE_ARGS+=(\"-DCMAKE_C_COMPILER=$CCACHE_WRAPPER_PATH/gcc\")\n    CMAKE_ARGS+=(\"-DCMAKE_CXX_COMPILER=$CCACHE_WRAPPER_PATH/g++\")\n  fi\nfi\n\n# Use special install script with Anaconda\nif [ -n \"${USE_ANACONDA}\" ]; then\n  export SKIP_CONDA_TESTS=1\n  export CONDA_INSTALL_LOCALLY=1\n  \"${ROOT_DIR}/scripts/build_anaconda.sh\" \"$@\"\nelse\n  # Make sure that pyyaml is installed for the codegen of building Aten to work\n  if [[ -n \"$(python -c 'import yaml' 2>&1)\" ]]; then\n    echo \"Installing pyyaml with pip at $(which pip)\"\n    pip install --user pyyaml\n  fi\n\n  # Make sure that typing is installed for the codegen of building Aten to work\n  if [[ -n \"$(python -c 'import typing' 2>&1)\" ]]; then\n    echo \"Installing typing with pip at $(which pip)\"\n    pip install --user typing\n  fi\n\n  # Build protobuf compiler from third_party if configured to do so\n  if [ -n \"${USE_HOST_PROTOC:-}\" ]; then\n    echo \"USE_HOST_PROTOC is set; building protoc before building Caffe2...\"\n    \"$CAFFE2_ROOT/scripts/build_host_protoc.sh\"\n    CUSTOM_PROTOC_EXECUTABLE=\"$CAFFE2_ROOT/build_host_protoc/bin/protoc\"\n    echo \"Built protoc $(\"$CUSTOM_PROTOC_EXECUTABLE\" --version)\"\n    CMAKE_ARGS+=(\"-DCAFFE2_CUSTOM_PROTOC_EXECUTABLE=$CUSTOM_PROTOC_EXECUTABLE\")\n  fi\n\n  # We are going to build the target into build.\n  BUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build\"}\n  mkdir -p \"$BUILD_ROOT\"\n  cd \"$BUILD_ROOT\"\n  echo \"Building Caffe2 in: $BUILD_ROOT\"\n\n  cmake \"$CAFFE2_ROOT\" \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        \"${CMAKE_ARGS[@]}\" \\\n        \"$@\"\n\n  # Determine the number of CPUs to build with.\n  # If the `CAFFE_MAKE_NCPUS` variable is not specified, use them all.\n  if [ -n \"${MAX_JOBS}\" ]; then\n      CAFFE_MAKE_NCPUS=\"$MAX_JOBS\"\n  elif [ -n \"${CAFFE_MAKE_NCPUS}\" ]; then\n      CAFFE_MAKE_NCPUS=\"$CAFFE_MAKE_NCPUS\"\n  elif [ \"$(uname)\" == 'Darwin' ]; then\n      CAFFE_MAKE_NCPUS=\"$(sysctl -n hw.ncpu)\"\n  else\n      CAFFE_MAKE_NCPUS=\"$(nproc)\"\n  fi\n\n  # Now, actually build the target.\n  cmake --build . -- \"-j$CAFFE_MAKE_NCPUS\"\nfi\n", "num_lines": 83}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Example command to build the mobile target.\n##############################################################################\n#\n# This script shows how one can build a libtorch library optimized for mobile\n# devices using host toolchain.\n\nset -e\n\nexport BUILD_PYTORCH_MOBILE_WITH_HOST_TOOLCHAIN=1\nCAFFE2_ROOT=\"$( cd \"$(dirname \"$0\")\"/.. ; pwd -P)\"\n\necho \"Bash: $(/bin/bash --version | head -1)\"\necho \"Caffe2 path: $CAFFE2_ROOT\"\n\nCMAKE_ARGS=()\nCMAKE_ARGS+=(\"-DCMAKE_PREFIX_PATH=$(python -c 'import sysconfig; print(sysconfig.get_path(\"purelib\"))')\")\nCMAKE_ARGS+=(\"-DPYTHON_EXECUTABLE=$(python -c 'import sys; print(sys.executable)')\")\nCMAKE_ARGS+=(\"-DBUILD_CUSTOM_PROTOBUF=OFF\")\nCMAKE_ARGS+=(\"-DBUILD_SHARED_LIBS=OFF\")\n# custom build with selected ops\nif [ -n \"${SELECTED_OP_LIST}\" ]; then\n  SELECTED_OP_LIST=\"$(cd $(dirname $SELECTED_OP_LIST); pwd -P)/$(basename $SELECTED_OP_LIST)\"\n  echo \"Choose SELECTED_OP_LIST file: $SELECTED_OP_LIST\"\n  if [ ! -r ${SELECTED_OP_LIST} ]; then\n    echo \"Error: SELECTED_OP_LIST file ${SELECTED_OP_LIST} not found.\"\n    exit 1\n  fi\n  CMAKE_ARGS+=(\"-DSELECTED_OP_LIST=${SELECTED_OP_LIST}\")\nfi\n\n# If Ninja is installed, prefer it to Make\nif [ -x \"$(command -v ninja)\" ]; then\n  CMAKE_ARGS+=(\"-GNinja\")\nfi\n\n# Disable unused dependencies\nCMAKE_ARGS+=(\"-DUSE_ROCM=OFF\")\nCMAKE_ARGS+=(\"-DUSE_CUDA=OFF\")\nCMAKE_ARGS+=(\"-DUSE_GFLAGS=OFF\")\nCMAKE_ARGS+=(\"-DUSE_OPENCV=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LMDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_LEVELDB=OFF\")\nCMAKE_ARGS+=(\"-DUSE_MPI=OFF\")\nCMAKE_ARGS+=(\"-DUSE_OPENMP=OFF\")\n\n# Only toggle if VERBOSE=1\nif [ \"${VERBOSE:-}\" == '1' ]; then\n  CMAKE_ARGS+=(\"-DCMAKE_VERBOSE_MAKEFILE=1\")\nfi\n\n# Use-specified CMake arguments go last to allow overridding defaults\nCMAKE_ARGS+=(\"$@\")\n\n# Now, actually build the Android target.\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build_mobile\"}\nINSTALL_PREFIX=${BUILD_ROOT}/install\nmkdir -p $BUILD_ROOT\ncd $BUILD_ROOT\ncmake \"$CAFFE2_ROOT\" \\\n    -DCMAKE_INSTALL_PREFIX=$INSTALL_PREFIX \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    \"${CMAKE_ARGS[@]}\"\n\n# Cross-platform parallel build\nif [ -z \"$MAX_JOBS\" ]; then\n  if [ \"$(uname)\" == 'Darwin' ]; then\n    MAX_JOBS=$(sysctl -n hw.ncpu)\n  else\n    MAX_JOBS=$(nproc)\n  fi\nfi\n\necho \"Will install headers and libs to $INSTALL_PREFIX for further project usage.\"\ncmake --build . --target install -- \"-j${MAX_JOBS}\"\necho \"Installation completed, now you can copy the headers/libs from $INSTALL_PREFIX to your project directory.\"\n", "num_lines": 78}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -eux\n\n##############################################################################\n# Master script to build PyTorch Android library with Java bindings.\n##############################################################################\n# Example usage:\n# - Build default AARs:\n#   scripts/build_pytorch_android.sh\n#\n# - Build for specific ABI(s):\n#   scripts/build_pytorch_android.sh armeabi-v7a\n#   scripts/build_pytorch_android.sh arm64-v8a,x86,x86_64\n#\n# Script's workflow:\n# 1. Builds libtorch for android for specified android abisi (by default for all 4).\n# Custom list of android abis can be specified as a bash argument as comma separated list.\n# For example just for testing on android x86 emulator we need only x86 build.\n# ./scripts/build_pytorch_android.sh x86\n# 2. Creates symbolic links to android/pytorch_android/src/main/jniLibs/${abi} for libtorch build output,\n# android/pytorch_android/src/main/cpp/libtorch_include/${abi} for headers.\n# 3. Runs pyotrch_android gradle build:\n# gradle assembleRelease\n\nPYTORCH_DIR=\"$(cd $(dirname $0)/..; pwd -P)\"\nPYTORCH_ANDROID_DIR=$PYTORCH_DIR/android\n\necho \"PYTORCH_DIR:$PYTORCH_DIR\"\n\nsource \"$PYTORCH_ANDROID_DIR/common.sh\"\n\ncheck_android_sdk\ncheck_gradle\nparse_abis_list \"$@\"\nbuild_android\n\n# To set proxy for gradle add following lines to ./gradle/gradle.properties:\n# systemProp.http.proxyHost=...\n# systemProp.http.proxyPort=8080\n# systemProp.https.proxyHost=...\n# systemProp.https.proxyPort=8080\n\nif [ \"$CUSTOM_ABIS_LIST\" = true ]; then\n  # Skipping clean task here as android gradle plugin 3.3.2 exteralNativeBuild has problems\n  # with it when abiFilters are specified.\n  $GRADLE_PATH -PABI_FILTERS=$ABIS_LIST -p $PYTORCH_ANDROID_DIR assembleRelease\nelse\n  $GRADLE_PATH -p $PYTORCH_ANDROID_DIR clean assembleRelease\nfi\n\nfind $PYTORCH_ANDROID_DIR -type f -name *aar | xargs ls -lah\n", "num_lines": 52}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Example command to build the Raspbian target.\n##############################################################################\n#\n# This script shows how one can build a Caffe2 binary for raspbian. The build\n# is essentially much similar to a host build, with one additional change\n# which is to specify -mfpu=neon for optimized speed.\n\nCAFFE2_ROOT=\"$( cd \"$(dirname -- \"$0\")\"/.. ; pwd -P)\"\necho \"Caffe2 codebase root is: $CAFFE2_ROOT\"\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build\"}\nmkdir -p $BUILD_ROOT\necho \"Build Caffe2 raspbian into: $BUILD_ROOT\"\n\n# obtain dependencies.\necho \"Installing dependencies.\"\nsudo apt-get install \\\n  cmake \\\n  libgflags-dev \\\n  libgoogle-glog-dev \\\n  libprotobuf-dev \\\n  libpython-dev \\\n  python-pip \\\n  python-numpy \\\n  protobuf-compiler \\\n  python-protobuf\n# python dependencies\nsudo pip install hypothesis\n\n# Now, actually build the raspbian target.\necho \"Building caffe2\"\ncd $BUILD_ROOT\n\n# Note: you can add more dependencies above if you need libraries such as\n# leveldb, lmdb, etc.\ncmake \"$CAFFE2_ROOT\" \\\n    -DCMAKE_VERBOSE_MAKEFILE=1 \\\n    -DCAFFE2_CPU_FLAGS=\"-mfpu=neon -mfloat-abi=hard\" \\\n    || exit 1\n\n# Note: while Raspberry pi has 4 cores, running too many builds in parallel may\n# cause out of memory errors so we will simply run -j 2 only.\nmake -j 2 || exit 1\n", "num_lines": 45}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Example command to build Caffe2 on Tegra X1.\n##############################################################################\n#\n# This script shows how one can build a Caffe2 binary for NVidia's TX1.\n# The build script assumes that you have the most recent libraries installed\n# via the JetPack toolkit available at\n#     https://developer.nvidia.com/embedded/jetpack\n# and it assumes that we are starting from a fresh system after the jetpack\n# installation. If you have already installed some of the dependencies, you\n# may be able to skip quite a few of the apt-get installs.\n\nCAFFE2_ROOT=\"$( cd \"$(dirname -- \"$0\")\"/.. ; pwd -P)\"\necho \"Caffe2 codebase root is: $CAFFE2_ROOT\"\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build\"}\nmkdir -p $BUILD_ROOT\necho \"Build Caffe2 raspbian into: $BUILD_ROOT\"\n\n# obtain necessary dependencies\necho \"Installing dependencies.\"\nsudo apt-get install \\\n  cmake \\\n  libgflags-dev \\\n  libgoogle-glog-dev \\\n  libprotobuf-dev \\\n  protobuf-compiler\n\n# obtain optional dependencies that are usually useful to have.\necho \"Installing optional dependencies.\"\nsudo apt-get install \\\n  libleveldb-dev \\\n  liblmdb-dev \\\n  libpython-dev \\\n  libsnappy-dev \\\n  python-numpy \\\n  python-pip \\\n  python-protobuf\n\n# Obtain python hypothesis, which Caffe2 uses for unit testing. Note that\n# the one provided by apt-get is quite old so we install it via pip\nsudo pip install hypothesis\n\n# Install the six module, which includes Python 2 and 3 compatibility utilities,\n# and is required for Caffe2\nsudo pip install six\n\n# Now, actually build the android target.\necho \"Building caffe2\"\ncd $BUILD_ROOT\n\n# CUDA_USE_STATIC_CUDA_RUNTIME needs to be set to off so that opencv can be\n# properly used. Otherwise, opencv will complain that opencv_dep_cudart cannot\n# be found.\ncmake \"$CAFFE2_ROOT\" -DCUDA_USE_STATIC_CUDA_RUNTIME=OFF \\\n    || exit 1\n\nmake -j 4 || exit 1\n", "num_lines": 59}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n#  Example command to build the Tizen target (RPi3).\n##############################################################################\n#\n# This script shows how one can build a Caffe2 binary for a Tizen device (RPi3).\n# The build is essentially much similar to a host build, with one additional change\n# which is to specify -mfpu=neon for optimized speed.\n\nsetup_environment(){\n# The rootfs image for a Tizen target (RPi3)is located at the below webpage:\n# http://download.tizen.org/releases/milestone/tizen/4.0.m1/tizen-unified_20170529.1/images/\n# If you do not have a Tizen device, Please, run qemu-arm-static and chroot command.\n# $ sudo chroot ~/tizen-rootfs qemu-arm-static /usr/bin/bash\n\nCAFFE2_ROOT=\"$( cd \"$(dirname -- \"$0\")\"/.. ; pwd -P)\"\necho \"Caffe2 codebase root is: $CAFFE2_ROOT\"\nBUILD_ROOT=${BUILD_ROOT:-\"$CAFFE2_ROOT/build\"}\nmkdir -p $BUILD_ROOT\necho \"Build Caffe2 Tizen into: $BUILD_ROOT\"\n}\n\ncaffe2_lite_dep_packages(){\n# Obtain necessary dependencies\n# You can set-up a rpm repository with zypper, yum, and dnf because Tizen\n# software platform officially support rpm format such as Fedora, OpenSUSE.\n# The official Tizen repository is as following:\n# http://download.tizen.org/releases/milestone/tizen/4.0.m1/\necho \"Installing dependencies.\"\nsudo zypper install \\\n  make \\\n  strace \\\n  cmake \\\n  gcc* \\\n  binutils \\\n  glibc* \\\n  cpp \\\n  protobuf-devel \\\n  libstdc++*\n}\n\ncaffe2_lite_build(){\n# Now, actually build the android target.\necho \"Building caffe2\"\ncd $BUILD_ROOT\n\n# Note: add more dependencies above if you need libraries such as leveldb, lmdb, etc.\n# If you have to disable a specific package due to a package absence\n# from https://git.tizen.org/cgit/, append -Dxxx_xxx=OFF option before executing cmake.\ncmake .. \\\n    -DCMAKE_VERBOSE_MAKEFILE=1 \\\n    -DUSE_GFLAGS=OFF  \\\n    -DUSE_GLOG=OFF -DUSE_NNPACK=OFF \\\n    -DRUN_HAVE_STD_REGEX=0 \\\n    -DRUN_HAVE_POSIX_REGEX=0 \\\n    -DHAVE_GNU_POSIX_REGEX=0 \\\n    -DUSE_MPI=OFF -DUSE_OPENMP=OFF \\\n    -DUSE_ROCKSDB=OFF \\\n    -DUSE_LEVELDB=OFF \\\n    -DUSE_LMDB=OFF \\\n    -DBUILD_PYTHON=OFF \\\n    -DUSE_GLOO=OFF \\\n    -DUSE_OPENCV=OFF \\\n    -DCAFFE2_CPU_FLAGS=\"-mfpu=neon -mfloat-abi=soft\" \\\n    || exit 1\n\nmake -j`nproc` || exit 1\n}\n\ncaffe2_full_dep_packages(){\n# Obtain necessary dependencies\n# You can set-up a rpm repository with zypper, yum, and dnf because Tizen\n# software platform officially support rpm format such as Fedora, OpenSUSE.\n# The official Tizen repository is as following:\n# http://download.tizen.org/releases/milestone/tizen/4.0.m1/\necho \"Installing dependencies.\"\nsudo zypper install \\\n  cmake \\\n  libgflags-dev \\\n  libgoogle-glog-dev \\\n  libprotobuf-dev \\\n  protobuf-compiler\n\n# Obtain optional dependencies that are usually useful to have.\necho \"Installing optional dependencies.\"\nsudo zypper install \\\n  libleveldb-dev \\\n  liblmdb-dev \\\n  libpython-dev \\\n  libsnappy-dev \\\n  python-numpy \\\n  python-pip \\\n  python-protobuf\n\n# Obtain python hypothesis, which Caffe2 uses for unit testing. Note that\n# the one provided by zypper is quite old so we install it via pip\nsudo pip install hypothesis\n\n# Install the six module, which includes Python 2 and 3 compatibility utilities,\n# and is required for Caffe2\nsudo pip install six\n}\n\ncaffe2_full_build(){\n# Now, actually build the android target.\necho \"Building caffe2\"\ncd $BUILD_ROOT\n\n# Note: add more dependencies above if you need libraries such as leveldb, lmdb, etc.\n# If you have to disable a specific package due to a package absence\n# from https://git.tizen.org/cgit/, append -Dxxx_xxx=OFF option before executing cmake.\ncmake \"$CAFFE2_ROOT\" \\\n    -DCMAKE_VERBOSE_MAKEFILE=1 \\\n    -DUSE_CUDA=OFF \\\n    -DUSE_OPENCV=OFF \\\n    -DUSE_LMDB=OFF \\\n    -DCAFFE2_CPU_FLAGS=\"-mfpu=neon -mfloat-abi=soft\" \\\n    || exit 1\n\nmake -j`nproc` || exit 1\n}\n\n#### Main\n# Setup a build environment to compile Caffe2 deeplearning framework in Tizen platform.\nsetup_environment\n# There are two build options to support 'full' version and 'lite' version (by default).\ncaffe2_lite_dep_packages\ncaffe2_lite_build\n", "num_lines": 129}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "# Simple script used to easily search all packages in conda for their\n# dependency requirements\n# TODO also search through output of ldd\n# TODO update conda info syntax for different channels\n\nif [ -z \"$CONDA_ROOT\" ]; then\n  # TODO create our own environment\n  echo \"Please set CONDA_ROOT so that I know where to search for conda libraries\"\n  echo \"I expect CONDA_ROOT to be the path to the current conda environment.\"\n  echo \"Also FYI I will probably mess up the current conda environment.\"\n  exit 1\nfi\n\nif [ -z \"$1\" ]; then\n  echo \"Please give me a package name to search for\"\n  exit 1\nfi\nPKG_NAME=\"$1\"\n\nif [ -n \"$2\" ]; then\n  echo \"Searching in channel $2\"\n  CONDA_CHANNEL=\"$2\"\nfi\n\n# These are the packages of interest to search the dependencies for\n# TODO use this\nPACKAGES_OF_INTEREST=( libgcc-ng libprotobuf numpy )\n\n# We will run `conda install` and `conda uninstall` a lot, but we don't want\n# this very noisy output to clutter the user experience\nVERBOSE_LOG='read_conda_versions.log'\necho \"Conda install/uninstall log for $PKG_NAME\" > $VERBOSE_LOG\n\n\n\n#\n# Build up the name of the installed library to call `nm` on\n#\nPKG_INSTALLED_LIB=\"$PKG_NAME\"\n\n# opencv installs a bunch of libraries. We'll just check libopencv_core\nif [[ $PKG_NAME == opencv ]]; then\n  PKG_INSTALLED_LIB=\"${PKG_INSTALLED_LIB}_core\"\nfi\n\n# Most packages prepend a 'lib' to the package name, but libprotobuf is an\n# exception\nif [[ $PKG_NAME != lib* ]]; then\n  PKG_INSTALLED_LIB=\"lib${PKG_INSTALLED_LIB}\"\nfi\n\n# The shared library suffix differs on macOS an Linux\nif [[ \"$(uname)\" == Darwin ]]; then\n  PKG_INSTALLED_LIB=\"${PKG_INSTALLED_LIB}.dylib\"\nelse\n  PKG_INSTALLED_LIB=\"${PKG_INSTALLED_LIB}.so\"\nfi\necho \"Determined the library name of $PKG_NAME to be $PKG_INSTALLED_LIB\"\necho \"Determined the library name of $PKG_NAME to be $PKG_INSTALLED_LIB\" >> $VERBOSE_LOG\n\n\n\n#\n# Get all available packages with conda-search\n#\n\n# Split the output from conda search into an array, one line per package (plus\n# the header)\nconda_search_packages=()\nwhile read -r line; do conda_search_packages+=(\"$line\"); done <<< \"$(conda search $PKG_NAME $CONDA_CHANNEL)\"\n\n### Typical `conda search` output looks like\n###   Loading channels: done\n###   Name                       Version                   Build  Channel\n###   protobuf                   2.6.1                    py27_0  defaults\n###                              2.6.1                    py27_1  defaults\n###                              3.2.0                    py27_0  defaults\n###                              3.2.0                    py35_0  defaults\n###                              3.2.0                    py36_0  defaults\n###                              3.4.1            py27h66c1d77_0  defaults\n###                              3.4.1            py35h9d33684_0  defaults\n###                              3.4.1            py36h314970b_0  defaults\n###                              3.5.1            py27h0a44026_0  defaults\n###                              3.5.1            py35h0a44026_0  defaults\n###                              3.5.1            py36h0a44026_0  defaults\n##\n### Typical `conda info` output looks like\n###   protobuf 3.5.1 py36h0a44026_0\n###     -----------------------------\n###   file name   : protobuf-3.5.1-py36h0a44026_0.tar.bz2\n###   name        : protobuf\n###   version     : 3.5.1\n###   build string: py36h0a44026_0\n###   build number: 0\n###   channel     : https://repo.continuum.io/pkgs/main/osx-64\n###   size        : 589 KB\n###   arch        : None\n###   constrains  : ()\n###   license     : New BSD License\n###   license_family: BSD\n###   md5         : 7dbdb06612e21c42fbb8a62354e13e10\n###   platform    : None\n###   subdir      : osx-64\n###   timestamp   : 1519951502766\n###   url         : https://repo.continuum.io/pkgs/main/osx-64/protobuf-3.5.1-py36h0a44026_0.tar.bz2\n###   dependencies:\n###       libcxx >=4.0.1\n###       libprotobuf >=3.5.1,<3.6.0a0\n###       python >=3.6,<3.7.0a0\n###       six\n\n# Echo what packages we'll look through.\necho \"Processing these packages:\"\nfor pkg in \"${conda_search_packages[@]:2}\"; do\n  echo \"  $pkg\"\ndone\n\n\n\n#\n# Look up each package in conda info, then install it and search the exported\n# symbols for signs of cxx11\n#\nfor pkg in \"${conda_search_packages[@]:2}\"; do\n  echo \"Processing $pkg\" >> $VERBOSE_LOG\n\n  # Split each line into an array and build the package specification\n  # <package_name (1st line only)>  maj.min.patch  build_string  channel_name\n  line_parts=( $pkg )\n  if [[ ${line_parts[0]} == $PKG_NAME ]]; then\n    # First line of output\n    PKG_VERSION=\"${line_parts[1]}\"\n    PKG_BUILD_STR=\"${line_parts[2]}\"\n  else\n    PKG_VERSION=\"${line_parts[0]}\"\n    PKG_BUILD_STR=\"${line_parts[1]}\"\n  fi\n  PKG_SPEC=\"$PKG_NAME=$PKG_VERSION=$PKG_BUILD_STR\"\n\n  # Output current pkg spec\n  echo\n  echo \"${PKG_SPEC}:\"\n  echo \"Determined that the package spec is $PKG_SPEC\" >> $VERBOSE_LOG\n\n  # Split the output of conda_info into an array of lines\n  pkg_dependencies=()\n  while read -r line; do pkg_dependencies+=(\"$line\"); done <<< \"$(conda info \"$PKG_SPEC\" $CONDA_CHANNEL)\"\n\n  # List all the listed dependencies in `conda info`\n  if [ \"${#pkg_dependencies[@]}\" -gt 19 ]; then\n    echo \"  Listed dependencies:\"\n    echo \"  Listed dependencies:\" >> $VERBOSE_LOG\n    for pkg_dependency in \"${pkg_dependencies[@]:20}\"; do\n      echo \"    $pkg_dependency\"\n      echo \"    $pkg_dependency\" >> $VERBOSE_LOG\n    done\n  else\n    echo \"  No listed dependencies in conda-info\" >> $VERBOSE_LOG\n  fi\n\n  # But sometimes (a lot of the time) the gcc with which a package was built\n  # against is not listed in dependencies. So we try to figure it out manually\n  # We install this exact package, and then grep the exported symbols for signs\n  # of cxx11\n  echo \"Calling conda-uninstall on $PKG_NAME\" >> $VERBOSE_LOG\n  echo \"conda uninstall -y $PKG_NAME --quiet\" >> $VERBOSE_LOG\n  conda uninstall -y \"$PKG_NAME\" --quiet >> $VERBOSE_LOG 2>&1\n\n  echo \"Calling conda-install on $PKG_SPEC\" >> $VERBOSE_LOG\n  echo \"conda install -y $PKG_SPEC --quiet --no-deps $CONDA_CHANNEL\" >> $VERBOSE_LOG\n  conda install -y \"$PKG_SPEC\" --quiet --no-deps $CONDA_CHANNEL >> $VERBOSE_LOG 2>&1\n  if [ $? -eq 0 ]; then\n    # Only grep the exported symbols if the library was installed correctly\n\n    MENTIONS_CXX11=\"$(nm \"$CONDA_ROOT/lib/$PKG_INSTALLED_LIB\" | grep cxx11 | wc -l)\"\n    if [ $MENTIONS_CXX11 -gt 0 ]; then\n      echo \"  This package is built against the recent gcc ABI ($MENTIONS_CXX11 mentions of cxx11)\"\n      echo \"$CONDA_ROOT/lib/$PKG_INSTALLED_LIB mentions cxx11 $MENTIONS_CXX11 times\" >> $VERBOSE_LOG\n    fi\n  else\n    echo \"Error installing $PKG_SPEC , continuing\"\n    echo \"Error installing $PKG_SPEC , continuing\" >> $VERBOSE_LOG\n  fi\ndone\n", "num_lines": 185}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "if [[ \"$1\" == *.py ]]; then\n  apache_header=\"apache_python.txt\"\nelse\n  apache_header=\"apache_header.txt\"\nfi\napache_lines=$(wc -l < \"${apache_header}\")\napache_md5=$(cat \"${apache_header}\" | md5)\nheader_md5=$(head -n ${apache_lines} $1 | md5)\nif [ \"${header_md5}\" == \"${apache_md5}\" ]; then\n  keep_lines=$(($(wc -l < $1) - ${apache_lines}))\n  tail -n ${keep_lines} $1 > _remove_apache_header.txt\n  mv _remove_apache_header.txt $1\nfi\n", "num_lines": 14}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "find ../caffe2 -name \"*.py\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.h\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.cc\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.cpp\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.cu\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.mm\" -exec ./remove_apache_header.sh {} \\;\nfind ../caffe2 -name \"*.m\" -exec ./remove_apache_header.sh {} \\;\n", "num_lines": 8}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script installs CCache with CUDA support.\n# Example usage:\n#     ./ccache_setup.sh --path /installed/folder\n\nset -e\nshopt -s expand_aliases\n\n# Setup the proxy\nalias with_proxy=\"HTTPS_PROXY=http://fwdproxy:8080 HTTP_PROXY=http://fwdproxy:8080 FTP_PROXY=http://fwdproxy:8080 https_proxy=http://fwdproxy:8080 http_proxy=http://fwdproxy:8080 ftp_proxy=http://fwdproxy:8080 http_no_proxy='*.facebook.com|*.tfbnw.net|*.fb.com'\"\n\n# Parse options\npath=\"$HOME/ccache\"\nforce=false\n\nwhile [[ $# -gt 0 ]]; do\n  case \"$1\" in\n    --path)\n      shift\n      path=\"$1\"\n      path=$(realpath \"$path\")\n      ;;\n    --force)  # Force install\n      force=true\n      ;;\n    --help)\n      echo 'usage: ./ccache_setup.py --path /installed/folder [--force]'\n      exit 0\n      ;;\n    *)\n      echo \"Invalid option: $1\"\n      exit 1\n      ;;\n  esac\n  shift\ndone\n\n# Check whether you put nvcc in PATH\nset +e\nnvcc_path=$(which nvcc)\nif [[ -z \"$nvcc_path\" ]]; then\n  nvcc_path=\"/usr/local/cuda/bin/nvcc\"\n  export PATH=\"/usr/local/cuda/bin:$PATH\"\nfi\nset -e\nif [ ! -f \"$nvcc_path\" ] && ! $force; then\n  # shellcheck disable=SC2016\n  echo 'nvcc is not detected in $PATH'\n  exit 1\nfi\necho \"nvcc is detected at $nvcc_path\"\n\nif [ -f \"$CUDA_NVCC_EXECUTABLE\" ] && [[ \"$CUDA_NVCC_EXECUTABLE\" == *\"ccache\"* ]]; then  # Heuristic rule\n  if $CUDA_NVCC_EXECUTABLE --version; then\n    if ! $force; then\n      echo \"CCache with nvcc support is already installed at $CUDA_NVCC_EXECUTABLE, please add --force\"\n      exit 0\n    fi\n  fi\nfi\n\n# Installing CCache\necho \"CCache will be installed at $path\"\nif [ -e \"$path\" ]; then\n  mv --backup=t -T \"$path\" \"${path}.old\"\nfi\n\nwith_proxy git clone https://github.com/colesbury/ccache.git \"$path\" -b ccbin\ncd \"$path\"\n./autogen.sh\n./configure\nmake install prefix=\"$path\"\n\nmkdir -p \"$path/lib\"\nmkdir -p \"$path/cuda\"\nln -sf \"$path/bin/ccache\" \"$path/lib/cc\"\nln -sf \"$path/bin/ccache\" \"$path/lib/c++\"\nln -sf \"$path/bin/ccache\" \"$path/lib/gcc\"\nln -sf \"$path/bin/ccache\" \"$path/lib/g++\"\nln -sf \"$path/bin/ccache\" \"$path/cuda/nvcc\"\n\"$path/bin/ccache\" -M 25Gi\n\n# Make sure the nvcc wrapped in CCache is runnable\n\"$path/cuda/nvcc\" --version\necho 'Congrats! The CCache with nvcc support is installed!'\necho -e \"Please add the following lines to your bash init script:\\\\n\"\necho \"################ Env Var for CCache with CUDA support ################\"\n# shellcheck disable=SC2016\necho 'export PATH=\"'\"$path\"'/lib:$PATH\"'\necho 'export CUDA_NVCC_EXECUTABLE=\"'\"$path\"'/cuda/nvcc\"'\necho '######################################################################'\n", "num_lines": 93}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\npython -c 'from caffe2.python import build; from pprint import pprint; pprint(build.build_options)'\npython -c 'from caffe2.python import core, workspace; print(\"GPUs found: \" + str(workspace.NumCudaDevices()))'\npython -c \"import onnx\"\npython -c \"import torch\"\n\necho \"Caffe2, PyTorch and ONNX installed successfully!!\"\n", "num_lines": 11}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script helps developers set up the ONNX Caffe2 and PyTorch develop environment on devgpu.\n# It creates an virtualenv instance, and installs all the dependencies in this environment.\n# The script will creates a folder called onnx-dev folder under the $HOME directory.\n# onnx, pytorch and caffe2 are installed separately.\n# Please source $HOME/onnx-dev/.onnx_env_init to initialize the development before starting developing.\n\n\n# TODO: support python 3.\n\n# Set script configuration\nset -e\nshopt -s expand_aliases\n\n# Proxy setup\nalias with_proxy=\"HTTPS_PROXY=http://fwdproxy:8080 HTTP_PROXY=http://fwdproxy:8080 FTP_PROXY=http://fwdproxy:8080 https_proxy=http://fwdproxy:8080 http_proxy=http://fwdproxy:8080 ftp_proxy=http://fwdproxy:8080 http_no_proxy='*.facebook.com|*.tfbnw.net|*.fb.com'\"\n\n# Set the variables\nRED='\\033[0;31m'\nCYAN='\\033[0;36m'\nNC='\\033[0m'\nonnx_root=\"$HOME/local/onnx-dev\"   # I think hardcoding the onnx root dir is fine, just like fbsource\nonnx_root_link=\"$HOME/onnx-dev\"\nvenv=\"$onnx_root/onnxvenv\"\nonnx_init_file=\"$onnx_root_link/.onnx_env_init\"\nccache_root=\"$onnx_root/ccache\"\nccache_script=\"$(pwd)/ccache_install.sh\"\nsanity_script=\"$onnx_root/sanity.sh\"\n\n# Check whether default CUDA exists\n# TODO check the required header and lib files\ndefault_cuda=\"/usr/local/cuda\"\nif [[ ! -e \"$default_cuda\" ]]; then\n  echo \"Default CUDA is not found at $default_cuda\"\nfi\n\n# Checking to see if CuDNN is present, and install it if not exists\nif [ -f /usr/local/cuda/include/cudnn.h ]; then\n  echo \"CuDNN header already exists!!\"\nelse\n  sudo cp -R /home/engshare/third-party2/cudnn/6.0.21/src/cuda/include/* /usr/local/cuda/include/\n  sudo cp -R /home/engshare/third-party2/cudnn/6.0.21/src/cuda/lib64/* /usr/local/cuda/lib64/\nfi\n\n# TODO set the specific version for each package\n# Install the dependencies for Caffe2\nsudo yum install python-virtualenv freetype-devel libpng-devel glog gflags protobuf protobuf-devel protobuf-compiler -y\nrpm -q protobuf  # check the version and if necessary update the value below\nprotoc --version  # check protoc\nprotoc_path=$(which protoc)\nif [[ \"$protoc_path\" != \"/bin/protoc\" ]]; then\n  echo \"Warning: Non-default protoc is detected, the script may not work with non-default protobuf!!!\"\n  echo \"Please try to remove the protoc at $protoc_path and rerun this script.\"\n  exit 1\nfi\n\n# Upgrade Cmake to the right version (>3.0)\nsudo yum remove cmake3 -y\nsudo yum install cmake -y\n\n# Install the dependencies for CCache\nsudo yum install autoconf asciidoc -y\n\n# Create the root folder\nif [ -e \"$onnx_root\" ]; then\n  timestamp=$(date \"+%Y.%m.%d-%H.%M.%S\")\n  mv --backup=t -T \"$onnx_root\" \"${onnx_root}.old.$timestamp\"\nfi\nmkdir -p \"$onnx_root\"\nif [ -e \"$onnx_root_link\"]; then\n  timestamp=$(date \"+%Y.%m.%d-%H.%M.%S\")\n  mv --backup=t -T \"$onnx_root_link\" \"${onnx_root_link}.old.$timestamp\"\nfi\nln -s \"$onnx_root\" \"$onnx_root_link\"\n\n# Set the name of virtualenv instance\nwith_proxy virtualenv \"$venv\"\n\n# Creating a script that can be sourced in the future for the environmental variable\ntouch \"$onnx_init_file\"\n{\n  # shellcheck disable=SC2016\n  echo 'if [ -z \"$LD_LIBRARY_PATH\" ]; then';\n  echo '  export LD_LIBRARY_PATH=/usr/local/cuda/lib64';\n  echo 'else'\n  # shellcheck disable=SC2016\n  echo '  export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH';\n  echo \"fi\"\n  # shellcheck disable=SC2016\n  echo 'export PATH='\"$ccache_root\"'/lib:/usr/local/cuda/bin:$PATH';\n  echo \"source $venv/bin/activate\";\n  echo 'alias with_proxy=\"HTTPS_PROXY=http://fwdproxy:8080 HTTP_PROXY=http://fwdproxy:8080 FTP_PROXY=http://fwdproxy:8080 https_proxy=http://fwdproxy:8080 http_proxy=http://fwdproxy:8080 ftp_proxy=http://fwdproxy:8080 http_no_proxy='\"'\"'*.facebook.com|*.tfbnw.net|*.fb.com'\"'\"'\"'\n} >> \"$onnx_init_file\"\nchmod u+x \"$onnx_init_file\"\n\n# Installing CCache\ncd \"$onnx_root\"\nif [ ! -f \"$ccache_script\" ]; then\n  ccache_script=\"$onnx_root/ccache_install.sh\"\n  with_proxy wget https://raw.githubusercontent.com/pytorch/pytorch/master/scripts/fbcode-dev-setup/ccache_setup.sh -O \"$ccache_script\"\nfi\nchmod u+x \"$ccache_script\"\n\"$ccache_script\" --path \"$ccache_root\"\n\n# Test nvcc with CCache\nown_ccache=true\nif [ -f \"$CUDA_NVCC_EXECUTABLE\" ] && [[ \"$ccache_root/cuda/nvcc\" != \"$CUDA_NVCC_EXECUTABLE\" ]] && \\\n  [[ \"$CUDA_NVCC_EXECUTABLE\" == *\"ccache\"* ]]; then  # Heuristic rule\n  if $CUDA_NVCC_EXECUTABLE --version; then\n    own_ccache=false\n  fi\nfi\nif [ \"$own_ccache\" = true ]; then\n  echo \"export CUDA_NVCC_EXECUTABLE=$ccache_root/cuda/nvcc\" >> \"$onnx_init_file\"\nfi\n\n# Loading env vars\n# shellcheck disable=SC1090\nsource \"$onnx_init_file\"\n\n\"$CUDA_NVCC_EXECUTABLE\" --version\n\n# Create a virtualenv, activate it, upgrade pip\nif [ -f \"$HOME/.pip/pip.conf\" ]; then\n  echo \"${RED}Warning: $HOME/.pip/pip.conf is detected, pip install may fail!${NC}\"\nfi\nwith_proxy python -m pip install -U pip setuptools\nwith_proxy python -m pip install future numpy \"protobuf>3.2\" pytest-runner pyyaml typing ipython\n\n# Cloning repos\ncd \"$onnx_root\"\nwith_proxy git clone https://github.com/onnx/onnx --recursive\nwith_proxy git clone https://github.com/pytorch/pytorch --recursive\n\n# Build ONNX\ncd \"$onnx_root/onnx\"\nwith_proxy python setup.py develop\n\n# Build PyTorch and Caffe2\ncd \"$onnx_root/pytorch\"\nwith_proxy pip install -r \"requirements.txt\"\nwith_proxy python setup.py develop\n\n# Sanity checks and useful info\ncd \"$onnx_root\"\nwith_proxy wget https://raw.githubusercontent.com/pytorch/pytorch/master/scripts/fbcode-dev-setup/onnx_c2_sanity_check.sh -O \"$sanity_script\"\nchmod u+x \"$sanity_script\"\n$sanity_script\n\necho \"Congrats, you are ready to rock!!\"\necho \"################ Please run the following command before development ################\"\necho -e \"${CYAN}source $onnx_init_file${NC}\"\necho \"#####################################################################################\"\n", "num_lines": 155}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# realpath might not be available on MacOS\nscript_path=$(python -c \"import os; import sys; print(os.path.realpath(sys.argv[1]))\" \"${BASH_SOURCE[0]}\")\ntop_dir=$(dirname $(dirname $(dirname \"$script_path\")))\ntp2_dir=\"$top_dir/third_party\"\n\npip install ninja\n\n# Install onnx\npip install --no-use-pep517 -e \"$tp2_dir/onnx\"\n\n# Install caffe2 and pytorch\npip install -r \"$top_dir/caffe2/requirements.txt\"\npip install -r \"$top_dir/requirements.txt\"\npython setup.py develop\n", "num_lines": 19}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# realpath might not be available on MacOS\nscript_path=$(python -c \"import os; import sys; print(os.path.realpath(sys.argv[1]))\" \"${BASH_SOURCE[0]}\")\ntop_dir=$(dirname $(dirname $(dirname \"$script_path\")))\ntp2_dir=\"$top_dir/third_party\"\nBUILD_DIR=\"$top_dir/build\"\nmkdir -p \"$BUILD_DIR\"\n\n_pip_install() {\n    if [[ -n \"$CI\" ]]; then\n        if [[ -z \"${SCCACHE_BUCKET}\" ]]; then\n            ccache -z\n        fi\n    fi\n    if [[ -n \"$CI\" ]]; then\n        time pip install \"$@\"\n    else\n        pip install \"$@\"\n    fi\n    if [[ -n \"$CI\" ]]; then\n        if [[ -n \"${SCCACHE_BUCKET}\" ]]; then\n            sccache --show-stats\n        else\n            ccache -s\n        fi\n    fi\n}\n\n# Install onnx\n_pip_install -b \"$BUILD_DIR/onnx\" \"file://$tp2_dir/onnx#egg=onnx\"\n\n# Install caffe2 and pytorch\npip install -r \"$top_dir/caffe2/requirements.txt\"\npip install -r \"$top_dir/requirements.txt\"\npython setup.py install\n", "num_lines": 39}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nUNKNOWN=()\n\n# defaults\nPARALLEL=0\n\nwhile [[ $# -gt 0 ]]\ndo\n    arg=\"$1\"\n    case $arg in\n        -p|--parallel)\n            PARALLEL=1\n            shift # past argument\n            ;;\n        *) # unknown option\n            UNKNOWN+=(\"$1\") # save it in an array for later\n            shift # past argument\n            ;;\n    esac\ndone\nset -- \"${UNKNOWN[@]}\" # leave UNKNOWN\n\nif [[ $PARALLEL == 1 ]]; then\n    pip install pytest-xdist\nfi\n\npip install pytest scipy hypothesis # these may not be necessary\npip install pytest-cov # installing since `coverage run -m pytest ..` doesn't work\npip install -e tools/coverage_plugins_package # allows coverage to run w/o failing due to a missing plug-in\n\n# realpath might not be available on MacOS\nscript_path=$(python -c \"import os; import sys; print(os.path.realpath(sys.argv[1]))\" \"${BASH_SOURCE[0]}\")\ntop_dir=$(dirname $(dirname $(dirname \"$script_path\")))\ntest_paths=(\n    \"$top_dir/test/onnx\"\n)\n\nargs=()\nargs+=(\"-v\")\nargs+=(\"--cov\")\nargs+=(\"--cov-report\")\nargs+=(\"xml:test/coverage.xml\")\nargs+=(\"--cov-append\")\nif [[ $PARALLEL == 1 ]]; then\n  args+=(\"-n\")\n  args+=(\"3\")\nfi\n\n# onnxruntime only support py3\n# \"Python.h\" not found in py2, needed by TorchScript custom op compilation.\nif [[ \"$BUILD_ENVIRONMENT\" == *ort_test1* ]]; then\n  # These exclusions are for tests that take a long time / a lot of GPU\n  # memory to run; they should be passing (and you will test them if you\n  # run them locally\n  pytest \"${args[@]}\" \\\n    --ignore \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime.py\" \\\n    --ignore \"$top_dir/test/onnx/test_custom_ops.py\" \\\n    --ignore \"$top_dir/test/onnx/test_models_onnxruntime.py\" \\\n    --ignore \"$top_dir/test/onnx/test_utility_funs.py\" \\\n    --ignore \"$top_dir/test/onnx/test_pytorch_onnx_caffe2.py\" \\\n    --ignore \"$top_dir/test/onnx/test_pytorch_onnx_shape_inference.py\" \\\n    --ignore \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime_cuda.py\" \\\n    --ignore \"$top_dir/test/onnx/test_pytorch_onnx_caffe2_quantized.py\" \\\n    \"${test_paths[@]}\"\n\n  pytest \"${args[@]}\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime.py::TestONNXRuntime_opset7\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime.py::TestONNXRuntime_opset8\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime.py::TestONNXRuntime\" \\\n    \"$top_dir/test/onnx/test_custom_ops.py\" \\\n    \"$top_dir/test/onnx/test_models_onnxruntime.py\" \\\n    \"$top_dir/test/onnx/test_utility_funs.py\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_caffe2.py\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_caffe2_quantized.py\" \\\n    \"$top_dir/test/onnx/test_pytorch_onnx_shape_inference.py\"\nfi\n\nif [[ \"$BUILD_ENVIRONMENT\" == *ort_test2* ]]; then\n  # Update the loop for new opsets\n  for i in $(seq 10 14); do\n    pytest \"${args[@]}\" \\\n      \"$top_dir/test/onnx/test_pytorch_onnx_onnxruntime.py::TestONNXRuntime_opset$i\"\n  done\nfi\n\n# Our CI expects both coverage.xml and .coverage to be within test/\nmv .coverage test/.coverage\n", "num_lines": 91}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nsource \"${DIR}/promote/common_utils.sh\"\n\nif [[ -z \"${RESTORE_FROM:-}\" ]]; then\n    echo \"ERROR: RESTORE_FROM environment variable must be specified\"\n    echo \"       example: RESTORE_FROM=v1.6.0-rc3 ${0}\"\n    exit 1\nfi\n\nDRY_RUN=${DRY_RUN:-enabled}\n\nPYTORCH_S3_BACKUP_BUCKET=${PYTORCH_S3_BACKUP_BUCKET:-s3://pytorch-backup/${RESTORE_FROM}}\nPYTORCH_S3_TEST_BUCKET=${PYTORCH_S3_TEST_BUCKET:-s3://pytorch/}\nPYTORCH_S3_FROM=${PYTORCH_S3_FROM:-${PYTORCH_S3_BACKUP_BUCKET}}\nPYTORCH_S3_TO=${PYTORCH_S3_TO:-s3://pytorch/}\n\nrestore_wheels() {\n    aws_promote torch whl\n}\n\nrestore_libtorch() {\n    aws_promote libtorch-* libtorch\n}\n\nANACONDA=\"true anaconda\"\nif [[ ${DRY_RUN} = \"disabled\" ]]; then\n    ANACONDA=\"anaconda\"\nfi\nPYTORCH_CONDA_TO=${PYTORCH_CONDA_TO:-pytorch-test}\n\nupload_conda() {\n    local pkg\n    pkg=${1}\n    (\n        set -x\n        ${ANACONDA} upload --skip -u \"${PYTORCH_CONDA_TO}\" \"${pkg}\"\n    )\n}\n\nexport -f upload_conda\n\nrestore_conda() {\n    TMP_DIR=\"$(mktemp -d)\"\n    trap 'rm -rf ${TMP_DIR}' EXIT\n    (\n        set -x\n        aws s3 cp --recursive \"${PYTORCH_S3_BACKUP_BUCKET}/conda\" \"${TMP_DIR}/\"\n    )\n    export ANACONDA\n    export PYTORCH_CONDA_TO\n    # Should upload all bz2 packages in parallel for quick restoration\n    find \"${TMP_DIR}\" -name '*.bz2' -type f \\\n        | xargs -P 10 -I % bash -c \"(declare -t upload_conda); upload_conda %\"\n}\n\n\nrestore_wheels\nrestore_libtorch\nrestore_conda\n", "num_lines": 64}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ngrab_prune_version() {\n    conda search -c \"${CHANNEL}\" --platform \"${platform}\" \"${PKG}\" 2>/dev/null | \\\n        grep \"${CHANNEL}\" | \\\n        awk -F '  *' '{print $2}' | \\\n        uniq | \\\n        head -n -1 | \\\n        xargs\n}\n\ngrab_latest_version() {\n    conda search -c \"${CHANNEL}\" --platform \"${platform}\" \"${PKG}\" 2>/dev/null | \\\n        grep \"${CHANNEL}\" | \\\n        awk -F '  *' '{print $2}' | \\\n        uniq | \\\n        tail -n 1 | \\\n        xargs\n}\n\ngrab_specs_for_version() {\n    conda search -c \"${CHANNEL}\" --platform \"${platform}\" \"${PKG}\" 2>/dev/null | \\\n        grep \"${CHANNEL}\" | \\\n        grep \"$1\" | \\\n        awk -F '  *' '{print $3}' | \\\n        uniq | \\\n        xargs\n}\n\nset -eou pipefail\n\nCHANNEL=${CHANNEL:-pytorch-nightly}\nPKG=${PKG:-pytorch}\nPLATFORMS=${PLATFORMS:-noarch osx-64 linux-64 win-64}\n\nfor platform in ${PLATFORMS}; do\n    latest_version=\"$(grab_latest_version || true)\"\n    specs_in_latest_version=\"$(grab_specs_for_version \"${latest_version}\" || true)\"\n    versions_to_prune=\"$(grab_prune_version || true)\"\n    for version in ${versions_to_prune}; do\n        specs_in_prune_version=\"$(grab_specs_for_version \"${version}\" || true)\"\n        for spec in ${specs_in_prune_version}; do\n        # If this spec is included in specs_in_latest_version, then remove it.\n        if [[ \"${specs_in_latest_version}\" =~ ${spec} ]];then\n            (\n                set -x\n                anaconda remove --force \"${CHANNEL}/${PKG}/${version}/${platform}/${PKG}-${version}-${spec}.tar.bz2\"\n            )\n        fi\n        done\n    done\ndone\n", "num_lines": 53}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\nCHANNEL=${CHANNEL:-pytorch-nightly}\nPACKAGES=${PACKAGES:-pytorch}\n\nfor pkg in ${PACKAGES}; do\n    echo \"+ Attempting to prune: ${CHANNEL}/${pkg}\"\n    CHANNEL=\"${CHANNEL}\" PKG=\"${pkg}\" \"${DIR}/prune.sh\"\n    echo\ndone\n", "num_lines": 15}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexit_if_not_on_git_tag() {\n    # Have an override for debugging purposes\n    if [[ -n \"${TEST_WITHOUT_GIT_TAG-}\" ]] ;then\n        >&2 echo \"+ WARN: Continuing without being on a git tag\"\n        exit 0\n    fi\n    # Exit if we're not currently on a git tag\n    if ! git describe --tags --exact >/dev/null 2>/dev/null; then\n        >&2 echo \"- ERROR: Attempting to promote on a non-git tag, must have tagged current commit locally first\"\n        exit 1\n    fi\n    # Exit if we're currently on an RC\n    if git describe --tags | grep \"-rc\" >/dev/null 2>/dev/null; then\n        >&2 echo \"- ERROR: Attempting to promote on a non GA git tag, current tag must be a GA tag\"\n        >&2 echo \"         Example: v1.5.0\"\n        exit 1\n    fi\n}\n\nget_pytorch_version() {\n    if [[ -n \"${TEST_WITHOUT_GIT_TAG-}\" ]];then\n        if  [[ -z \"${TEST_PYTORCH_PROMOTE_VERSION-}\" ]]; then\n            >&2 echo \"- ERROR: Specified TEST_WITHOUT_GIT_TAG without specifying TEST_PYTORCH_PROMOTE_VERSION\"\n            >&2 echo \"-        TEST_PYTORCH_PROMOTE_VERSION must be specified\"\n            exit 1\n        else\n            echo \"${TEST_PYTORCH_PROMOTE_VERSION}\"\n            exit 0\n        fi\n    fi\n    exit_if_not_on_git_tag\n    # Echo git tag, strip leading v\n    git describe --tags | sed -e 's/^v//'\n}\n\naws_promote() {\n    package_name=$1\n    pytorch_version=$(get_pytorch_version)\n    # Dry run by default\n    DRY_RUN=${DRY_RUN:-enabled}\n    DRY_RUN_FLAG=\"--dryrun\"\n    if [[ $DRY_RUN = \"disabled\" ]]; then\n        DRY_RUN_FLAG=\"\"\n    fi\n    AWS=${AWS:-aws}\n    (\n        set -x\n        ${AWS} s3 cp ${DRY_RUN_FLAG} \\\n            --only-show-errors \\\n            --acl public-read \\\n            --recursive \\\n            --exclude '*' \\\n            --include \"*${package_name}-${pytorch_version}*\" \\\n            \"${PYTORCH_S3_FROM/\\/$//}\" \\\n            \"${PYTORCH_S3_TO/\\/$//}\"\n    )\n    # ^ We grep for package_name-.*pytorch_version to avoid any situations where domain libraries have\n    #   the same version on our S3 buckets\n}\n", "num_lines": 62}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nsource \"${DIR}/common_utils.sh\"\n\n\n# Allow for users to pass PACKAGE_NAME\n# For use with other packages, i.e. torchvision, etc.\nPACKAGE_NAME=${PACKAGE_NAME:-pytorch}\nPYTORCH_CONDA_FROM=${PYTORCH_CONDA_FROM:-pytorch-test}\nPYTORCH_CONDA_TO=${PYTORCH_CONDA_TO:-pytorch}\nCONDA_PLATFORMS=\"linux-64 osx-64 win-64 noarch\"\n\npytorch_version=\"$(get_pytorch_version)\"\n\ntmp_dir=\"$(mktemp -d)\"\npushd \"${tmp_dir}\"\ntrap 'rm -rf ${tmp_dir}' EXIT\n\nconda_search() {\n    conda search -q \"${PYTORCH_CONDA_FROM}::${PACKAGE_NAME}==${pytorch_version}\" -c \"${PYTORCH_CONDA_FROM}\" --platform \"${platform}\" \\\n        | grep -e \"^${PACKAGE_NAME}\" \\\n        | awk -F ' *' '{print $3}' \\\n        | xargs -I % echo \"https://anaconda.org/${PYTORCH_CONDA_FROM}/${PACKAGE_NAME}/${pytorch_version}/download/${platform}/${PACKAGE_NAME}-${pytorch_version}-%.tar.bz2\"\n}\n\npkgs_to_download=()\nfor platform in ${CONDA_PLATFORMS}; do\n    pkgs_to_download+=($(\\\n        conda_search 2>/dev/null || true\n    ))\n    # Create directory where packages will eventually be downloaded\n    mkdir -p \"${platform}\"\ndone\n\nmy_curl() {\n    local dl_url=$1\n    local start=$(date +%s)\n    # downloads should be distinguished by platform which should be the second\n    # to last field in the url, this is to avoid clobbering same named files\n    # for different platforms\n    dl_dir=$(echo \"${dl_url}\" | rev | cut -d'/' -f 2 | rev)\n    dl_name=$(echo \"${dl_url}\" | rev | cut -d'/' -f 1 | rev)\n    curl -fsSL -o \"${dl_dir}/${dl_name}\" \"${dl_url}\"\n    local end=$(date +%s)\n    local diff=$(( end - start ))\n    echo \"+ ${dl_url} took ${diff}s\"\n}\nexport -f my_curl\n\n# Download all packages in parallel\nprintf '%s\\n' \"${pkgs_to_download[@]}\" \\\n    | xargs -P 10 -I % bash -c '(declare -t my_curl); my_curl %'\n\n# dry run by default\nDRY_RUN=${DRY_RUN:-enabled}\nANACONDA=\"true anaconda\"\nif [[ $DRY_RUN = \"disabled\" ]]; then\n    ANACONDA=\"anaconda\"\nfi\n(\n    # We use --skip here to avoid re-uploading files we've already uploaded\n    set -x\n    ${ANACONDA} upload --skip -u ${PYTORCH_CONDA_TO} $(find . -name '*.bz2')\n)\n\npopd\n", "num_lines": 70}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Preps binaries for publishing to pypi by removing the\n# version suffix we normally add for all binaries\n# (outside of default ones, CUDA 10.2 currently)\n\n# Usage is:\n# $ prep_binary_for_pypy.sh <path_to_whl_file> <path_to_multiple_whl_files>\n\n# Will output a whl in your current directory\n\nset -eou pipefail\nshopt -s globstar\n\nOUTPUT_DIR=${OUTPUT_DIR:-$(pwd)}\n\ntmp_dir=\"$(mktemp -d)\"\ntrap 'rm -rf ${tmp_dir}' EXIT\n\nfor whl_file in \"$@\"; do\n    whl_file=$(realpath \"${whl_file}\")\n    whl_dir=\"${tmp_dir}/$(basename \"${whl_file}\")_unzipped\"\n    mkdir -pv \"${whl_dir}\"\n    (\n        set -x\n        unzip -q \"${whl_file}\" -d \"${whl_dir}\"\n    )\n    version_with_suffix=$(grep '^Version:' \"${whl_dir}\"/*/METADATA | cut -d' ' -f2)\n    version_with_suffix_escaped=${version_with_suffix/+/%2B}\n    # Remove all suffixed +bleh versions\n    version_no_suffix=${version_with_suffix/+*/}\n    new_whl_file=${OUTPUT_DIR}/$(basename \"${whl_file/${version_with_suffix_escaped}/${version_no_suffix}}\")\n    dist_info_folder=$(find \"${whl_dir}\" -type d -name '*.dist-info' | head -1)\n    basename_dist_info_folder=$(basename \"${dist_info_folder}\")\n    dirname_dist_info_folder=$(dirname \"${dist_info_folder}\")\n    (\n        set -x\n        find \"${dist_info_folder}\" -type f -exec sed -i \"s!${version_with_suffix}!${version_no_suffix}!\" {} \\;\n        # Moves distinfo from one with a version suffix to one without\n        # Example: torch-1.8.0+cpu.dist-info => torch-1.8.0.dist-info\n        mv \"${dist_info_folder}\" \"${dirname_dist_info_folder}/${basename_dist_info_folder/${version_with_suffix}/${version_no_suffix}}\"\n        cd \"${whl_dir}\"\n        zip -qr \"${new_whl_file}\" .\n    )\ndone\n", "num_lines": 46}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nsource \"${DIR}/common_utils.sh\"\n\n# Allow for users to pass PACKAGE_NAME\n# For use with other packages, i.e. torchvision, etc.\nPACKAGE_NAME=${PACKAGE_NAME:-torch}\nPACKAGE_TYPE=${PACKAGE_TYPE:-whl}\n\nPYTORCH_S3_BUCKET=${PYTORCH_S3_BUCKET:-s3://pytorch}\nFROM=${FROM:-test}\nPYTORCH_S3_FROM=${PYTORCH_S3_FROM:-${PYTORCH_S3_BUCKET}/${PACKAGE_TYPE}/${FROM}}\nTO=${TO:-}\nPYTORCH_S3_TO=${PYTORCH_S3_TO:-${PYTORCH_S3_BUCKET}/${PACKAGE_TYPE}/${TO}}\n\naws_promote \"${PACKAGE_NAME}\"\n", "num_lines": 20}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eou pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nsource \"${DIR}/common_utils.sh\"\n\n# Allow for users to pass PACKAGE_NAME\n# For use with other packages, i.e. torchvision, etc.\nPACKAGE_NAME=${PACKAGE_NAME:-torch}\n\npytorch_version=\"$(get_pytorch_version)\"\n# Refers to the specific package we'd like to promote\n# i.e. VERSION_SUFFIX='%2Bcu102'\n#      torch-1.8.0+cu102 -> torch-1.8.0\nVERSION_SUFFIX=${VERSION_SUFFIX:-}\n# Refers to the specific platofmr we'd like to promote\n# i.e. PLATFORM=linux_x86_64\n# For domains like torchaudio / torchtext this is to be left blank\nPLATFORM=${PLATFORM:-}\n\npkgs_to_promote=$(\\\n    curl -fsSL https://download.pytorch.org/whl/torch_stable.html \\\n        | grep \"${PACKAGE_NAME}-${pytorch_version}${VERSION_SUFFIX}-\" \\\n        | grep \"${PLATFORM}\" \\\n        | cut -d '\"' -f2\n)\n\ntmp_dir=\"$(mktemp -d)\"\noutput_tmp_dir=\"$(mktemp -d)\"\ntrap 'rm -rf ${tmp_dir} ${output_tmp_dir}' EXIT\npushd \"${output_tmp_dir}\"\n\n# Dry run by default\nDRY_RUN=${DRY_RUN:-enabled}\n# On dry run just echo the commands that are meant to be run\nTWINE_UPLOAD=\"echo twine upload\"\nif [[ $DRY_RUN = \"disabled\" ]]; then\n    TWINE_UPLOAD=\"twine upload\"\nfi\n\nfor pkg in ${pkgs_to_promote}; do\n    pkg_basename=\"$(basename \"${pkg//linux/manylinux1}\")\"\n    orig_pkg=\"${tmp_dir}/${pkg_basename}\"\n    (\n        set -x\n        # Download package, sub out linux for manylinux1\n        curl -fsSL -o \"${orig_pkg}\" \"https://download.pytorch.org/whl/${pkg}\"\n    )\n\n    if [[ -n \"${VERSION_SUFFIX}\" ]]; then\n        OUTPUT_DIR=\"${output_tmp_dir}\" ${DIR}/prep_binary_for_pypi.sh \"${orig_pkg}\"\n    else\n        mv \"${orig_pkg}\" \"${output_tmp_dir}/\"\n    fi\n\n    (\n        set -x\n        ${TWINE_UPLOAD} \\\n            --disable-progress-bar \\\n            --non-interactive \\\n            ./*.whl\n        rm -rf ./*.whl\n    )\ndone\n", "num_lines": 66}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Facebook, Inc. and its affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nFILE=\"$1/$RANK\"\necho \"creating $FILE\"\ntouch \"$FILE\"\n", "num_lines": 12}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n###############################################################################\n# This script tests the flow to build libtorch locally with optimized binary\n# size for mobile devices and the flow to integrate it with a simple predictor\n# in c++.\n#\n# Supported custom build types:\n#\n# 1. `TEST_DEFAULT_BUILD=1 ./build.sh` - it is similar to the prebuilt libtorch\n# libraries released for Android and iOS (same CMake build options + host\n# toolchain), which doesn't contain autograd function nor backward ops thus is\n# smaller than full LibTorch.\n#\n# 2. `TEST_CUSTOM_BUILD_DYNAMIC=1 ./build.sh` - it further optimizes libtorch\n# size by only including ops used by a specific model.\n# Note that LLVM_DIR environment variable should be set to the location of\n# LLVM-dev toolchain.\n#\n# 3. `TEST_CUSTOM_BUILD_STATIC=1 ./build.sh` - similar as 2) except that it\n# relies on the static dispatch + linker to prune code.\n#\n###############################################################################\n\nset -ex -o pipefail\n\nSRC_ROOT=\"$( cd \"$(dirname \"$0\")\"/../../.. ; pwd -P)\"\nTEST_SRC_ROOT=\"${SRC_ROOT}/test/mobile/custom_build\"\nBUILD_ROOT=\"${BUILD_ROOT:-${SRC_ROOT}/build_test_custom_build}\"\nmkdir -p \"${BUILD_ROOT}\"\ncd \"${BUILD_ROOT}\"\n\nprepare_model_and_dump_root_ops() {\n  cd \"${BUILD_ROOT}\"\n  MODEL=\"${BUILD_ROOT}/MobileNetV2.pt\"\n  ROOT_OPS=\"${BUILD_ROOT}/MobileNetV2.yaml\"\n\n  python \"${TEST_SRC_ROOT}/prepare_model.py\"\n}\n\ngenerate_op_dependency_graph() {\n  # Regular users should get this graph from prebuilt package.\n  ANALYZER_BUILD_ROOT=\"${BUILD_ROOT}/build_analyzer\"\n  OP_DEPENDENCY=\"${ANALYZER_BUILD_ROOT}/work/torch_result.yaml\"\n\n  if [ ! -f \"${OP_DEPENDENCY}\" ]; then\n    BUILD_ROOT=\"${ANALYZER_BUILD_ROOT}\" \\\n      ANALYZE_TORCH=1 \\\n      \"${SRC_ROOT}/tools/code_analyzer/build.sh\"\n  fi\n}\n\nrun_default_build() {\n  LIBTORCH_BUILD_ROOT=\"${BUILD_ROOT}/build_default_libtorch\"\n  LIBTORCH_INSTALL_PREFIX=\"${LIBTORCH_BUILD_ROOT}/install\"\n\n  BUILD_ROOT=\"${LIBTORCH_BUILD_ROOT}\" \\\n    \"${SRC_ROOT}/scripts/build_mobile.sh\"\n}\n\nrun_custom_build_with_static_dispatch() {\n  LIBTORCH_BUILD_ROOT=\"${BUILD_ROOT}/build_custom_libtorch_static\"\n  LIBTORCH_INSTALL_PREFIX=\"${LIBTORCH_BUILD_ROOT}/install\"\n\n  # Here we omitted the OP_DEPENDENCY flag so it generates registration\n  # code for used ROOT ops only, whose unboxing kernels are still needed\n  # by the JIT runtime. The intermediate ops will be automatically kepted\n  # by the linker as they are statically referenced by the static dispatch\n  # code, for which we can bypass the registration.\n  # We don't set '-DSTATIC_DISPATCH_BACKEND=CPU' explicitly to test automatic\n  # fallback to static dispatch when '-DOP_DEPENDENCY' is omitted.\n  BUILD_ROOT=\"${LIBTORCH_BUILD_ROOT}\" \\\n    \"${SRC_ROOT}/scripts/build_mobile.sh\" \\\n    -DCMAKE_CXX_FLAGS=\"-DSTRIP_ERROR_MESSAGES\" \\\n    -DSELECTED_OP_LIST=\"${ROOT_OPS}\"\n}\n\nrun_custom_build_with_dynamic_dispatch() {\n  LIBTORCH_BUILD_ROOT=\"${BUILD_ROOT}/build_custom_libtorch_dynamic\"\n  LIBTORCH_INSTALL_PREFIX=\"${LIBTORCH_BUILD_ROOT}/install\"\n\n  BUILD_ROOT=\"${LIBTORCH_BUILD_ROOT}\" \\\n    \"${SRC_ROOT}/scripts/build_mobile.sh\" \\\n    -DCMAKE_CXX_FLAGS=\"-DSTRIP_ERROR_MESSAGES\" \\\n    -DSELECTED_OP_LIST=\"${ROOT_OPS}\" \\\n    -DOP_DEPENDENCY=\"${OP_DEPENDENCY}\"\n}\n\nbuild_predictor() {\n  PREDICTOR_BUILD_ROOT=\"${BUILD_ROOT}/predictor\"\n\n  rm -rf \"${PREDICTOR_BUILD_ROOT}\" && mkdir -p \"${PREDICTOR_BUILD_ROOT}\"\n  cd \"${PREDICTOR_BUILD_ROOT}\"\n\n  cmake \"${TEST_SRC_ROOT}\" \\\n    -DCMAKE_PREFIX_PATH=\"${LIBTORCH_INSTALL_PREFIX}\" \\\n    -DCMAKE_BUILD_TYPE=Release\n\n  make\n}\n\nrun_predictor() {\n  cd \"${PREDICTOR_BUILD_ROOT}\"\n  ./Predictor \"${MODEL}\" > output.txt\n\n  if cmp -s output.txt \"${TEST_SRC_ROOT}/expected_output.txt\"; then\n    echo \"Test result is the same as expected.\"\n  else\n    echo \"Test result is DIFFERENT from expected!\"\n    diff output.txt \"${TEST_SRC_ROOT}/expected_output.txt\"\n    exit 1\n  fi\n}\n\ntest_default_build() {\n  prepare_model_and_dump_root_ops\n  run_default_build\n  build_predictor\n  run_predictor\n}\n\ntest_custom_build_with_static_dispatch() {\n  prepare_model_and_dump_root_ops\n  run_custom_build_with_static_dispatch\n  build_predictor\n  run_predictor\n}\n\ntest_custom_build_with_dynamic_dispatch() {\n  prepare_model_and_dump_root_ops\n  generate_op_dependency_graph\n  run_custom_build_with_dynamic_dispatch\n  build_predictor\n  run_predictor\n}\n\nif [ -n \"${TEST_DEFAULT_BUILD}\" ]; then\n  test_default_build\nfi\n\nif [ -n \"${TEST_CUSTOM_BUILD_STATIC}\" ]; then\n  test_custom_build_with_static_dispatch\nfi\n\nif [ -n \"${TEST_CUSTOM_BUILD_DYNAMIC}\" ]; then\n  test_custom_build_with_dynamic_dispatch\nfi\n", "num_lines": 147}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# A simple project that uses C10 op registration API to create a bunch of\n# inter-dependent dummy ops in order to test op dependency analysis script for\n# mobile custom build workflow.\n##############################################################################\n\nset -ex\n\nSRC_ROOT=\"$( cd \"$(dirname \"$0\")\"/../../.. ; pwd -P)\"\nBUILD_ROOT=\"${BUILD_ROOT:-${SRC_ROOT}/build_test_op_deps}\"\nINSTALL_PREFIX=\"${BUILD_ROOT}/install\"\n\nmkdir -p \"${BUILD_ROOT}\"\ncd \"${BUILD_ROOT}\"\n\nif [ ! -d \"${TORCH_INSTALL_PREFIX:=${SRC_ROOT}/build_mobile/install}\" ]; then\n  echo \"Unable to find torch library in ${TORCH_INSTALL_PREFIX}\"\n  exit 1\nfi\n\ncmake \"${SRC_ROOT}/test/mobile/op_deps\" \\\n  -DCMAKE_INSTALL_PREFIX=\"${INSTALL_PREFIX}\" \\\n  -DCMAKE_BUILD_TYPE=Release \\\n  -DCMAKE_PREFIX_PATH=\"${TORCH_INSTALL_PREFIX}\" \\\n  \"$@\" # Use-specified CMake arguments\n\ncmake --build . --target install -- \"-j${MAX_JOBS}\"\necho \"Installation completed: ${INSTALL_PREFIX}\"\n", "num_lines": 30}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "\nth test.lua > lua.out\npython3 test.py > python.out\n\ndiff lua.out python.out >/dev/null 2>&1\nRESULT=$?\nif [[ RESULT -eq 0 ]]; then\n    echo \"PASS\"\nelse\n    echo \"FAIL\"\n    echo \"Press ENTER to open vimdiff\"\n    read\n    vimdiff lua.out python.out\nfi\n", "num_lines": 15}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# HOW TO USE:\n# 1) python setup.py ...\n# 2) tools/git_add_generated_dirs\n# 3) Edit codegen\n# 4) python setup.py ...\n# 5) git diff to see changes\n# 6) If satisfied: tools/git_reset_generated_dirs, commit, etc.\n#    If not satisfied: Go to 3)\n\nBASEDIR=$(dirname \"$0\")\n(< $BASEDIR/generated_dirs.txt xargs -i find {} -type f) | xargs git add -f\n", "num_lines": 14}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# HOW TO USE:\n# 1) python setup.py ...\n# 2) tools/git_add_generated_dirs\n# 3) Edit codegen\n# 4) python setup.py ...\n# 5) git diff to see changes\n# 6) If satisfied: tools/git_reset_generated_dirs, commit, etc.\n#    If not satisfied: Go to 3)\n\nBASEDIR=$(dirname \"$0\")\n(< $BASEDIR/generated_dirs.txt xargs -i find {} -type f) | xargs git reset HEAD\n", "num_lines": 14}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Build LLVM code analyzer and analyze torch code dependency.\n##############################################################################\n#\n# Example usage:\n#\n# 1. Analyze torch and generate yaml file of op dependency transitive closure:\n# LLVM_DIR=${HOME}/src/llvm8/build/install \\\n# ANALYZE_TORCH=1 tools/code_analyzer/build.sh\n#\n# 2. Analyze test project and compare with expected result:\n# LLVM_DIR=${HOME}/src/llvm8/build/install \\\n# ANALYZE_TEST=1 tools/code_analyzer/build.sh\n#\n# 3. Analyze torch and generate yaml file of op dependency with debug path:\n# LLVM_DIR=${HOME}/src/llvm8/build/install \\\n# ANALYZE_TORCH=1 tools/code_analyzer/build.sh -debug_path=true\n#\n# If you're a Facebook employee, chances are you're running on CentOS 8.\n# If that's the case, you can install all the dependencies you need with:\n#\n#   sudo dnf install llvm-devel llvm-static clang ncurses-devel\n#\n# and then set LLVM_DIR=/usr\n\nset -ex\n\nSRC_ROOT=\"$( cd \"$(dirname \"$0\")\"/../.. ; pwd -P)\"\nANALYZER_SRC_HOME=\"${SRC_ROOT}/tools/code_analyzer\"\n\n# Clang/LLVM path\nexport LLVM_DIR=\"${LLVM_DIR:-/usr/lib/llvm-8}\"\nexport CC=\"${LLVM_DIR}/bin/clang\"\nexport CXX=\"${LLVM_DIR}/bin/clang++\"\nEXTRA_ANALYZER_FLAGS=$@\n\nBUILD_ROOT=\"${BUILD_ROOT:-${SRC_ROOT}/build_code_analyzer}\"\nWORK_DIR=\"${BUILD_ROOT}/work\"\n\nrm -rf \"${BUILD_ROOT}\"\nmkdir -p \"${BUILD_ROOT}\"\nmkdir -p \"${WORK_DIR}\"\ncd \"${BUILD_ROOT}\"\n\nbuild_analyzer() {\n  cmake \"${ANALYZER_SRC_HOME}\" -DCMAKE_BUILD_TYPE=Release\n\n  if [ -z \"${MAX_JOBS}\" ]; then\n    if [ \"$(uname)\" == 'Darwin' ]; then\n      MAX_JOBS=$(sysctl -n hw.ncpu)\n    else\n      MAX_JOBS=$(nproc)\n    fi\n  fi\n\n  make \"-j${MAX_JOBS}\"\n}\n\nbuild_torch_mobile() {\n  TORCH_BUILD_ROOT=\"${BUILD_ROOT}/build_mobile\"\n  TORCH_INSTALL_PREFIX=\"${TORCH_BUILD_ROOT}/install\"\n\n  BUILD_ROOT=\"${TORCH_BUILD_ROOT}\" \"${SRC_ROOT}/scripts/build_mobile.sh\" \\\n    -DCMAKE_CXX_FLAGS=\"-S -emit-llvm -DSTRIP_ERROR_MESSAGES\" \\\n    ${MOBILE_BUILD_FLAGS}\n}\n\nbuild_test_project() {\n  TEST_SRC_ROOT=\"${SRC_ROOT}/test/mobile/op_deps\"\n  TEST_BUILD_ROOT=\"${BUILD_ROOT}/build_test\"\n  TEST_INSTALL_PREFIX=\"${TEST_BUILD_ROOT}/install\"\n\n  BUILD_ROOT=\"${TEST_BUILD_ROOT}\" \\\n    TORCH_INSTALL_PREFIX=\"${TORCH_INSTALL_PREFIX}\" \\\n    \"${TEST_SRC_ROOT}/build.sh\" \\\n    -DCMAKE_CXX_FLAGS=\"-S -emit-llvm -DSTRIP_ERROR_MESSAGES\"\n}\n\ncall_analyzer() {\n  ANALYZER_BIN=\"${BUILD_ROOT}/analyzer\" \\\n    INPUT=\"${INPUT}\" OUTPUT=\"${OUTPUT}\" \\\n    EXTRA_ANALYZER_FLAGS=\"${EXTRA_ANALYZER_FLAGS}\" \\\n    \"${ANALYZER_SRC_HOME}/run_analyzer.sh\"\n}\n\nanalyze_torch_mobile() {\n  INPUT=\"${WORK_DIR}/torch.ll\"\n  OUTPUT=\"${WORK_DIR}/torch_result.yaml\"\n\n  if [ ! -f \"${INPUT}\" ]; then\n    # Link libtorch into a single module\n    # TODO: invoke llvm-link from cmake directly to avoid this hack.\n    # TODO: include *.c.o when there is meaningful fan-out from pure-c code.\n    \"${LLVM_DIR}/bin/llvm-link\" -S \\\n    $(find \"${TORCH_BUILD_ROOT}\" -name '*.cpp.o' -o -name '*.cc.o') \\\n    -o \"${INPUT}\"\n  fi\n\n  # Analyze dependency\n  call_analyzer\n}\n\nprint_output_file_path() {\n  echo \"Deployed file at: ${OUTPUT}\"\n}\n\nanalyze_test_project() {\n  INPUT=\"${WORK_DIR}/test.ll\"\n  OUTPUT=\"${WORK_DIR}/test_result.yaml\"\n\n  # Link into a single module (only need c10 and OpLib srcs)\n  # TODO: invoke llvm-link from cmake directly to avoid this hack.\n  \"${LLVM_DIR}/bin/llvm-link\" -S \\\n  $(find \"${TORCH_BUILD_ROOT}\" -path '*/c10*' \\( -name '*.cpp.o' -o -name '*.cc.o' \\)) \\\n  $(find \"${TEST_BUILD_ROOT}\" -path '*/OpLib*' \\( -name '*.cpp.o' -o -name '*.cc.o' \\)) \\\n  -o \"${INPUT}\"\n\n  # Analyze dependency\n  call_analyzer\n}\n\ncheck_test_result() {\n  if cmp -s \"${OUTPUT}\" \"${TEST_SRC_ROOT}/expected_deps.yaml\"; then\n    echo \"Test result is the same as expected.\"\n  else\n    echo \"Test result is DIFFERENT from expected!\"\n    diff -u \"${TEST_SRC_ROOT}/expected_deps.yaml\" \"${OUTPUT}\"\n    exit 1\n  fi\n}\n\nbuild_analyzer\n\nif [ -n \"${ANALYZE_TORCH}\" ]; then\n  build_torch_mobile\n  analyze_torch_mobile\n  if [ -n \"${DEPLOY}\" ]; then\n    print_output_file_path\n  fi\nfi\n\nif [ -n \"${ANALYZE_TEST}\" ]; then\n  build_torch_mobile\n  build_test_project\n  analyze_test_project\n  check_test_result\nfi\n", "num_lines": 149}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n##############################################################################\n# Invoke code analyzer binary with pre-defined parameters for LibTorch.\n# This script should be called via build.sh. Do NOT use it directly.\n##############################################################################\n\nset -exu\n\necho \"Analyze: ${INPUT}\"\n\n# NB: op_register_pattern actually contains \"too\" many entries.  We only\n# need to regex for symbols which occur after inlining; and most of the\n# public API for the registration API disappears after inlining (e.g.,\n# only _def and _impl are retained).  But the inliner isn't guaranteed\n# to operate, so for safety we match a more expansive set.\n\"${ANALYZER_BIN}\" \\\n  -op_schema_pattern=\"^(_aten|_prim|aten|quantized|_quantized|prepacked|profiler|_test)::[a-zA-Z0-9_.]+(\\(.*)?$\" \\\n  -op_register_pattern=\"c10::RegisterOperators::(op|checkSchemaAndRegisterOp_)|c10::Module::(_?def|_?impl)|torch::Library::(_?def|_?impl)\" \\\n  -op_invoke_pattern=\"c10::Dispatcher::findSchema\" \\\n  -root_symbol_pattern=\"torch::jit::[^(]\" \\\n  -torch_library_init_pattern=\"^.*TORCH_LIBRARY_init_([^(]+)(\\(.*)?$\" \\\n  -torch_library_init_pattern=\"^.*TORCH_LIBRARY_FRAGMENT_init_([_]*[^_]+)_[0-9]+(\\(.*)?$\" \\\n  -torch_library_init_pattern=\"^.*TORCH_LIBRARY_IMPL_init_([_]*[^_]+)_([^_]+)_[0-9]+(\\(.*)?$\" \\\n  ${EXTRA_ANALYZER_FLAGS} \\\n  \"${INPUT}\" \\\n  > \"${OUTPUT}\"\n\necho \"Result: ${OUTPUT}\"\n", "num_lines": 29}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nset -eux\n\n# Runs clang-format on allowlisted files.\n# Requires a single argument, which is the <commit> argument to git-clang-format\n\n# If you edit this allowlist, please edit the one in clang_format_all.py as well\nfind . -type f \\\n  -path './c10/*' -or \\\n  -path './torch/csrc/jit/*' -or \\\n  -path './test/cpp/jit/*' -or \\\n  -path './test/cpp/tensorexpr/*' \\\n  | xargs tools/linter/git-clang-format --verbose \"$1\" --\n", "num_lines": 14}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nfind \"$@\" -name '*.sh' -print0 | xargs -0 -n1 shellcheck --external-sources\n", "num_lines": 3}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\nwget https://www.openssl.org/source/openssl-1.1.1k.tar.gz\ntar xf openssl-1.1.1k.tar.gz\n(cd openssl-1.1.1k && ./config --prefix=\"$PYTHON_INSTALL_DIR\" && make -j32 && make install)\nCFLAGS=-fPIC CPPFLAGS=-fPIC ./configure --prefix \"$PYTHON_INSTALL_DIR\" --with-openssl=\"$PYTHON_INSTALL_DIR\"\n", "num_lines": 7}
{"repo_name": "pytorch", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/bash\nset -e\n\nif [ -z \"${PYTORCH_REPO_PATH}\" ]; then\n  echo \"Please specify \\`PYTORCH_REPO_PATH\\`\"\n  exit 1\nfi\n\ncd \"${PYTORCH_REPO_PATH}\"\n\n# Helper function to manage conda environments.\nmake_clean_env(){\n    ENV_NAME=\"$1\"\n\n    # Cleanup prior if it exists\n    conda env remove --name \"${ENV_NAME}\" 2> /dev/null || true\n\n    conda create -yn \"${ENV_NAME}\" python=3\n    source activate \"${ENV_NAME}\"\n    conda install -y numpy ninja pyyaml mkl mkl-include setuptools cmake cffi hypothesis\n    conda install -y -c pytorch magma-cuda102\n    conda deactivate\n}\n\nmake_clean_env ref_39850\nmake_clean_env pr_39850\nmake_clean_env ref_39967\nmake_clean_env pr_39967\nmake_clean_env ref_39744\nmake_clean_env pr_39744\n\ngit submodule update --init --recursive --jobs 0\nwget https://github.com/pytorch/pytorch/pull/39850.diff\nwget https://github.com/pytorch/pytorch/pull/39744.diff\n\nsource activate ref_39850\ngit checkout 766889b6bfeb9802f892fa0782d629554b2c71b4\npython setup.py install\nconda deactivate\n\nsource activate pr_39850\ngit apply 39850.diff\npython setup.py install\ngit checkout .\nconda deactivate\n\nsource activate ref_39967\ngit checkout c4fc278fa8cbd0fb45b8130a679c62f673087484\npython setup.py install\nconda deactivate\n\nsource activate pr_39967\ngit checkout 7a3c223bbb711c7a93910ce406a0126b8000b43b\npython setup.py install\nconda deactivate\n\nsource activate ref_39744\ngit checkout 541814f2b7eacabacdc87ccb1b4495bf486f501a\npython setup.py install\nconda deactivate\n\nsource activate pr_39744\ngit apply 39744.diff\npython setup.py install\ngit checkout .\nconda deactivate\n", "num_lines": 67}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Run 'autoreconf' to build 'configure', 'Makefile.in' and other configure\n# control files.\n#\n# The first time this is run on a GIT checkout the only files that exist are\n# configure.ac and Makefile.am; all of the autotools support scripts are\n# missing.  They are instantiated with autoreconf --force --install.\n#\n# For regular (\"tarball\") distributions all the files should exist.  We do not\n# want them to be updated *under any circumstances*.  It should never be\n# necessary to run autogen.sh because ./configure --enable-maintainer-mode says\n# what to do if Makefile.am or configure.ac are changed.\n#\n# It is *probably* OK to update the files on a GIT checkout, because they have\n# come from the local tools, but leave that to the user who is assumed to know\n# whether it is ok or required.\n#\n# This script is intended to work without arguments, there are, however, hidden\n# arguments (a) for use while testing the script and (b) to fix up systems that\n# have been broken.  If (b) is required the script prompts for the correct\n# options.  For this reason the options are *NOT* documented in the help; this\n# is deliberate; UTSL.\n#\nclean=\nmaintainer=\nwhile test $# -gt 0\ndo\n   case \"$1\" in\n      --maintainer)\n         maintainer=1;;\n\n      --clean)\n         clean=1;;\n\n      *)\n         exec >&2\n         echo \"$0: usage: ./autogen.sh\"\n         if test -d .git\n         then\n            echo \"  ./autogen.sh generates the configure script and\"\n            echo \"  Makefile.in, or refreshes them after changes to Makefile.am\"\n            echo \"  or configure.ac.  You may prefer to just run autoreconf.\"\n         elif test -z \"$maintainer\"\n         then\n            echo \"  DO NOT RUN THIS SCRIPT.\"\n            echo \"  If you need to change Makefile.am or configure.ac then you\"\n            echo \"  also need to run ./configure --enable-maintainer-mode and\"\n            echo \"  use the appropriate autotools, *NOT* this script, to update\"\n            echo \"  everything, please check the documentation of autoreconf.\"\n            echo \"  WARNING: libpng is intentionally generated with a known,\"\n            echo \"  fixed, set of autotools.  It is known *NOT* to work with\"\n            echo \"  the collection of autotools distributed on highly reputable\"\n            echo \"  operating systems.\"\n            echo \"  Remember: autotools is GNU software, you are expected to\"\n            echo \"  pay for support.\"\n         else\n            echo \"  You have run autogen.sh with --maintainer enabled and you\"\n            echo \"  are not using a GIT distribution, then you have given an\"\n            echo \"  unrecognized argument.  This is not good. --maintainer\"\n            echo \"  switches off any assumptions that you might not know what\"\n            echo \"  you are doing.\"\n         fi\n         exit 1;;\n   esac\n\n   shift\ndone\n#\n# First check for a set of the autotools files; if absent then this is assumed\n# to be a GIT version and the local autotools must be used.  If present this\n# is a tarball distribution and the script should not be used.  If partially\n# present bad things are happening.\n#\n# The autotools generated files:\nlibpng_autotools_files=\"Makefile.in aclocal.m4 config.guess config.h.in\\\n   config.sub configure depcomp install-sh ltmain.sh missing test-driver\"\n#\n# Files generated by versions of configue >2.68 or automake >1.13 (i.e. later\n# versions than those required by configure.ac):\nlibpng_autotools_extra=\"compile\"\n#\n# These are separate because 'maintainer-clean' does not remove them.\nlibpng_libtool_files=\"scripts/libtool.m4 scripts/ltoptions.m4\\\n   scripts/ltsugar.m4 scripts/ltversion.m4 scripts/lt~obsolete.m4\"\n\nlibpng_autotools_dirs=\"autom4te.cache\" # not required\n#\n# The configure generated files:\nlibpng_configure_files=\"Makefile config.h config.log config.status\\\n   libpng-config libpng.pc libtool stamp-h1\"\n\nlibpng_configure_dirs=\".deps\"\n#\n# We must remove the configure generated files as well as the autotools\n# generated files if autotools are regenerated because otherwise if configure\n# has been run without \"--enable-maintainer-mode\" make can do a partial update\n# of Makefile.  These functions do the two bits of cleaning.\nclean_autotools(){\n   rm -rf $libpng_autotools_files $libpng_libtool_files $libpng_autotools_dirs\n   rm -rf $libpng_autotools_extra\n}\n\nclean_configure(){\n   rm -rf $libpng_configure_files $libpng_configure_dirs\n}\n#\n# Clean: remove everything (this is to help with testing)\nif test -n \"$clean\"\nthen\n   clean_configure\n   if test -n \"$maintainer\"\n   then\n      clean_autotools\n   fi\n\n   exit 0\nfi\n#\n# Validate the distribution.\nlibpng_autotools_file_found=\nlibpng_autotools_file_missing=\nfor file in $libpng_autotools_files\ndo\n   if test -f  \"$file\"\n   then\n      libpng_autotools_file_found=1\n   else\n      libpng_autotools_file_missing=1\n   fi\ndone\n#\n# Presence of one of these does not *invalidate* missing, but absence\n# invalidates found.\nfor file in $libpng_libtool_files\ndo\n   if test ! -f \"$file\"\n   then\n      libpng_autotools_file_missing=1\n   fi\ndone\n#\n# The cache directory doesn't matter - it will be regenerated and does not exist\n# anyway in a tarball.\n#\n# Either everything is missing or everything is there, the --maintainer option\n# just changes this so that the mode is set to generate all the files.\nmode=\nif test -z \"$libpng_autotools_file_found\" -o -n \"$maintainer\"\nthen\n   mode=\"autoreconf\"\nelse\n   if test -n \"$libpng_autotools_file_missing\"\n   then\n      mode=\"broken\"\n   else\n      mode=\"configure\"\n   fi\nfi\n#\n# So:\ncase \"$mode\" in\n   autoreconf)\n      # Clean in case configure files exist\n      clean_configure\n      clean_autotools\n      # Everything must be initialized, so use --force\n      if autoreconf --warnings=all --force --install\n      then\n         missing=\n         for file in $libpng_autotools_files\n         do\n            test -f \"$file\" || missing=1\n         done\n         # ignore the cache directory\n         test -z \"$missing\" || {\n            exec >&2\n            echo \"autoreconf was run, but did not produce all the expected\"\n            echo \"files.  It is likely that your autotools installation is\"\n            echo \"not compatible with that expected by libpng.\"\n            exit 1\n         }\n      else\n         exec >&2\n         echo \"autoreconf failed: your version of autotools is incompatible\"\n         echo \"with this libpng version.  Please use a distributed archive\"\n         echo \"(which includes the autotools generated files) and run configure\"\n         echo \"instead.\"\n         exit 1\n      fi;;\n\n   configure)\n      if test -d .git\n      then\n         exec >&2\n         echo \"ERROR: running autoreconf on an initialized sytem\"\n         echo \"  This is not necessary; it is only necessary to remake the\"\n         echo \"  autotools generated files if Makefile.am or configure.ac\"\n         echo \"  change and make does the right thing with:\"\n         echo\n         echo \"     ./configure --enable-maintainer-mode.\"\n         echo\n         echo \"  You can run autoreconf yourself if you don't like maintainer\"\n         echo \"  mode and you can also just run autoreconf -f -i to initialize\"\n         echo \"  everything in the first place; this script is only for\"\n         echo \"  compatibility with prior releases.\"\n         exit 1\n      else\n         exec >&2\n         echo \"autogen.sh is intended only to generate 'configure' on systems\"\n         echo \"that do not have it.  You have a complete 'configure', if you\"\n         echo \"need to change Makefile.am or configure.ac you also need to\"\n         echo \"run configure with the --enable-maintainer-mode option.\"\n         exit 1\n      fi;;\n\n   broken)\n      exec >&2\n      echo \"Your system has a partial set of autotools generated files.\"\n      echo \"autogen.sh is unable to proceed.  The full set of files is\"\n      echo \"contained in the libpng 'tar' distribution archive and you do\"\n      echo \"not need to run autogen.sh if you use it.\"\n      exit 1;;\nesac\n", "num_lines": 225}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=2.4.6\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='eval echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2014-01-07.03; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      eval $_G_hook '\"$@\"'\n\n      # store returned options list back into positional\n      # parameters for next 'cmd' execution.\n      eval _G_hook_result=\\$${_G_hook}_result\n      eval set dummy \"$_G_hook_result\"; shift\n    done\n\n    func_quote_for_eval ${1+\"$@\"}\n    func_run_hooks_result=$func_quote_for_eval_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, remove any\n# options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_options_prep_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=: ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         ;;\n#            *)            set dummy \"$_G_opt\" \"$*\"; shift; break ;;\n#          esac\n#        done\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_silent_option_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_option_validation_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll alse need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    func_options_prep ${1+\"$@\"}\n    eval func_parse_options \\\n        ${func_options_prep_result+\"$func_options_prep_result\"}\n    eval func_validate_options \\\n        ${func_parse_options_result+\"$func_parse_options_result\"}\n\n    eval func_run_hooks func_options \\\n        ${func_validate_options_result+\"$func_validate_options_result\"}\n\n    # save modified positional parameters for caller\n    func_options_result=$func_run_hooks_result\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propogate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning.\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    func_run_hooks func_options_prep ${1+\"$@\"}\n\n    # save modified positional parameters for caller\n    func_options_prep_result=$func_run_hooks_result\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      func_run_hooks func_parse_options ${1+\"$@\"}\n\n      # Adjust func_parse_options positional parameters to match\n      eval set dummy \"$func_run_hooks_result\"; shift\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      test $# = 0 && func_missing_arg $_G_opt && break\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n      esac\n    done\n\n    # save modified positional parameters for caller\n    func_quote_for_eval ${1+\"$@\"}\n    func_parse_options_result=$func_quote_for_eval_result\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    func_run_hooks func_validate_options ${1+\"$@\"}\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    # save modified positional parameters for caller\n    func_validate_options_result=$func_run_hooks_result\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname (GNU libtool) 2.4.6\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/software/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    esac\n\n    # Pass back the list of options.\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_options_prep_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n\t# An option not handled by this hook function:\n        *)\t\tset dummy \"$_G_opt\" ${1+\"$@\"};\tshift; break  ;;\n      esac\n    done\n\n\n    # save modified positional parameters for caller\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_parse_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -stdlib=*            select c++ std lib with clang\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink) libs=\"$deplibs %DEPLIBS% $dependency_libs\" ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    deplibs=\"$deplib $deplibs\"\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11148}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2013 John Cunningham Bowler\n#\n# Last changed in libpng 1.6.0 [February 14, 2013]\n#\n# This code is released under the libpng license.\n# For conditions of distribution and use, see the disclaimer\n# and license in png.h\n#\n# Generate a set of PNG test images.  The images are generated in a\n# sub-directory called 'tests' by default, however a command line argument will\n# change that name.  The generation requires a built version of makepng in the\n# current directory.\n#\nusage(){\n   exec >&2\n   echo \"$0 [<directory>]\"\n   echo '  Generate a set of PNG test files in \"directory\" (\"tests\" by default)'\n   exit 1\n}\n\nmp=\"$PWD/makepng\"\ntest -x \"$mp\" || {\n   exec >&2\n   echo \"$0: the 'makepng' program must exist\"\n   echo \"  in the directory within which this program:\"\n   echo \"    $mp\"\n   echo \"  is executed\"\n   usage\n}\n\n# Just one argument: the directory\ntestdir=\"tests\"\ntest $# -gt 1 && {\n   testdir=\"$1\"\n   shift\n}\ntest $# -eq 0 || usage\n\n# Take care not to clobber something\nif test -e \"$testdir\"\nthen\n   test -d \"$testdir\" || usage\nelse\n   # mkdir -p isn't portable, so do the following\n   mkdir \"$testdir\" 2>/dev/null || mkdir -p \"$testdir\" || usage\nfi\n\n# This fails in a very satisfactory way if it's not accessible\ncd \"$testdir\"\n:>\"test$$.png\" || {\n   exec >&2\n   echo \"$testdir: directory not writable\"\n   usage\n}\nrm \"test$$.png\" || {\n   exec >&2\n   echo \"$testdir: you have create but not write privileges here.\"\n   echo \"  This is unexpected.  You have a spurion; \"'\"'\"test$$.png\"'\"'\".\"\n   echo \"  You need to remove this yourself.  Try a different directory.\"\n   exit 1\n}\n\n# Now call makepng ($mp) to create every file we can think of with a\n# reasonable name\ndoit(){\n   for gamma in \"\" --sRGB --linear --1.8\n   do\n      case \"$gamma\" in\n         \"\")\n            gname=;;\n         --sRGB)\n            gname=\"-srgb\";;\n         --linear)\n            gname=\"-lin\";;\n         --1.8)\n            gname=\"-18\";;\n         *)\n            gname=\"-$gamma\";;\n      esac\n      \"$mp\" $gamma \"$1\" \"$2\" \"test-$1-$2$gname.png\"\n   done\n}\n#\nfor ct in gray palette\ndo\n   for bd in 1 2 4 8\n   do\n      doit \"$ct\" \"$bd\"\n   done\ndone\n#\ndoit \"gray\" \"16\"\n#\nfor ct in gray-alpha rgb rgb-alpha\ndo\n   for bd in 8 16\n   do\n      doit \"$ct\" \"$bd\"\n   done\ndone\n", "num_lines": 103}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# -- grayscale\n./png2pnm -noraw ../pngsuite/basn0g01.png basn0g01.pgm\n./png2pnm -noraw ../pngsuite/basn0g02.png basn0g02.pgm\n./png2pnm -noraw ../pngsuite/basn0g04.png basn0g04.pgm\n./png2pnm -noraw ../pngsuite/basn0g08.png basn0g08.pgm\n./png2pnm -noraw ../pngsuite/basn0g16.png basn0g16.pgm\n# -- full-color\n./png2pnm -noraw ../pngsuite/basn2c08.png basn2c08.ppm\n./png2pnm -noraw ../pngsuite/basn2c16.png basn2c16.ppm\n# -- palletted\n./png2pnm -noraw ../pngsuite/basn3p01.png basn3p01.ppm\n./png2pnm -noraw ../pngsuite/basn3p02.png basn3p02.ppm\n./png2pnm -noraw ../pngsuite/basn3p04.png basn3p04.ppm\n./png2pnm -noraw ../pngsuite/basn3p08.png basn3p08.ppm\n# -- gray with alpha-channel\n./png2pnm -noraw ../pngsuite/basn4a08.png basn4a08.pgm\n./png2pnm -noraw ../pngsuite/basn4a16.png basn4a16.pgm\n# -- color with alpha-channel\n./png2pnm -noraw -alpha basn6a08.pgm ../pngsuite/basn6a08.png basn6a08.ppm\n./png2pnm -noraw -alpha basn6a16.pgm ../pngsuite/basn6a16.png basn6a16.ppm\n# -- grayscale\n./png2pnm -raw ../pngsuite/basn0g01.png rawn0g01.pgm\n./png2pnm -raw ../pngsuite/basn0g02.png rawn0g02.pgm\n./png2pnm -raw ../pngsuite/basn0g04.png rawn0g04.pgm\n./png2pnm -raw ../pngsuite/basn0g08.png rawn0g08.pgm\n./png2pnm -raw ../pngsuite/basn0g16.png rawn0g16.pgm\n# -- full-color\n./png2pnm -raw ../pngsuite/basn2c08.png rawn2c08.ppm\n./png2pnm -raw ../pngsuite/basn2c16.png rawn2c16.ppm\n# -- palletted\n./png2pnm -raw ../pngsuite/basn3p01.png rawn3p01.ppm\n./png2pnm -raw ../pngsuite/basn3p02.png rawn3p02.ppm\n./png2pnm -raw ../pngsuite/basn3p04.png rawn3p04.ppm\n./png2pnm -raw ../pngsuite/basn3p08.png rawn3p08.ppm\n# -- gray with alpha-channel\n./png2pnm -raw ../pngsuite/basn4a08.png rawn4a08.pgm\n./png2pnm -raw ../pngsuite/basn4a16.png rawn4a16.pgm\n# -- color with alpha-channel\n./png2pnm -noraw -alpha rawn6a08.pgm ../pngsuite/basn6a08.png rawn6a08.ppm\n./png2pnm -noraw -alpha rawn6a16.pgm ../pngsuite/basn6a16.png rawn6a16.ppm\n\n", "num_lines": 43}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nmake -f makefile.std\nsh png2pnm.sh\nsh pnm2png.sh\n\n", "num_lines": 6}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# -- grayscale\n./pnm2png basn0g01.pgm basn0g01.png\n./pnm2png basn0g02.pgm basn0g02.png\n./pnm2png basn0g04.pgm basn0g04.png\n./pnm2png basn0g08.pgm basn0g08.png\n./pnm2png basn0g16.pgm basn0g16.png\n# -- full-color\n./pnm2png basn2c08.ppm basn2c08.png\n./pnm2png basn2c16.ppm basn2c16.png\n# -- palletted\n./pnm2png basn3p01.ppm basn3p01.png\n./pnm2png basn3p02.ppm basn3p02.png\n./pnm2png basn3p04.ppm basn3p04.png\n./pnm2png basn3p08.ppm basn3p08.png\n# -- gray with alpha-channel\n./pnm2png -alpha basn6a08.pgm basn4a08.pgm basn4a08.png\n./pnm2png -alpha basn6a16.pgm basn4a16.pgm basn4a16.png\n# -- color with alpha-channel\n./pnm2png -alpha basn6a08.pgm basn6a08.ppm basn6a08.png\n./pnm2png -alpha basn6a16.pgm basn6a16.ppm basn6a16.png\n# -- grayscale\n./pnm2png rawn0g01.pgm rawn0g01.png\n./pnm2png rawn0g02.pgm rawn0g02.png\n./pnm2png rawn0g04.pgm rawn0g04.png\n./pnm2png rawn0g08.pgm rawn0g08.png\n./pnm2png rawn0g16.pgm rawn0g16.png\n# -- full-color\n./pnm2png rawn2c08.ppm rawn2c08.png\n./pnm2png rawn2c16.ppm rawn2c16.png\n# -- palletted\n./pnm2png rawn3p01.ppm rawn3p01.png\n./pnm2png rawn3p02.ppm rawn3p02.png\n./pnm2png rawn3p04.ppm rawn3p04.png\n./pnm2png rawn3p08.ppm rawn3p08.png\n# -- gray with alpha-channel\n./pnm2png -alpha rawn6a08.pgm rawn4a08.pgm rawn4a08.png\n./pnm2png -alpha rawn6a16.pgm rawn4a16.pgm rawn4a16.png\n# -- color with alpha-channel\n./pnm2png -alpha rawn6a08.pgm rawn6a08.ppm rawn6a08.png\n./pnm2png -alpha rawn6a16.pgm rawn6a16.ppm rawn6a16.png\n\n", "num_lines": 43}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# intgamma.sh\n#\n# Last changed in libpng 1.6.0 [February 14, 2013]\n#\n# COPYRIGHT: Written by John Cunningham Bowler, 2013.\n# To the extent possible under law, the author has waived all copyright and\n# related or neighboring rights to this work.  This work is published from:\n# United States.\n#\n# Shell script to generate png.c 8-bit and 16-bit log tables (see the code in\n# png.c for details).\n#\n# This script uses the \"bc\" arbitrary precision calculator to calculate 32-bit\n# fixed point values of logarithms appropriate to finding the log of an 8-bit\n# (0..255) value and a similar table for the exponent calculation.\n#\n# \"bc\" must be on the path when the script is executed, and the math library\n# (-lm) must be available\n#\n# function to print out a list of numbers as integers; the function truncates\n# the integers which must be one-per-line\nfunction print(){\n   awk 'BEGIN{\n      str = \"\"\n   }\n   {\n      sub(\"\\\\.[0-9]*$\", \"\")\n      if ($0 == \"\")\n         $0 = \"0\"\n\n      if (str == \"\")\n         t = \"   \" $0 \"U\"\n      else\n         t = str \", \" $0 \"U\"\n\n      if (length(t) >= 80) {\n         print str \",\"\n         str = \"   \" $0 \"U\"\n      } else\n         str = t\n   }\n   END{\n      print str\n   }'\n}\n#\n# The logarithm table.\ncat <<END\n/* 8-bit log table: png_8bit_l2[128]\n * This is a table of -log(value/255)/log(2) for 'value' in the range 128 to\n * 255, so it's the base 2 logarithm of a normalized 8-bit floating point\n * mantissa.  The numbers are 32-bit fractions.\n */\nstatic const png_uint_32\npng_8bit_l2[128] =\n{\nEND\n#\nbc -lqws <<END | print\nf=65536*65536/l(2)\nfor (i=128;i<256;++i) { .5 - l(i/255)*f; }\nEND\necho '};'\necho\n#\n# The exponent table.\ncat <<END\n/* The 'exp()' case must invert the above, taking a 20-bit fixed point\n * logarithmic value and returning a 16 or 8-bit number as appropriate.  In\n * each case only the low 16 bits are relevant - the fraction - since the\n * integer bits (the top 4) simply determine a shift.\n *\n * The worst case is the 16-bit distinction between 65535 and 65534; this\n * requires perhaps spurious accuracy in the decoding of the logarithm to\n * distinguish log2(65535/65534.5) - 10^-5 or 17 bits.  There is little chance\n * of getting this accuracy in practice.\n *\n * To deal with this the following exp() function works out the exponent of the\n * frational part of the logarithm by using an accurate 32-bit value from the\n * top four fractional bits then multiplying in the remaining bits.\n */\nstatic const png_uint_32\npng_32bit_exp[16] =\n{\nEND\n#\nbc -lqws <<END | print\nf=l(2)/16\nfor (i=0;i<16;++i) {\n   x = .5 + e(-i*f)*2^32;\n   if (x >= 2^32) x = 2^32-1;\n   x;\n}\nEND\necho '};'\necho\n#\n# And the table of adjustment values.\ncat <<END\n/* Adjustment table; provided to explain the numbers in the code below. */\n#if 0\nEND\nbc -lqws <<END | awk '{ printf \"%5d %s\\n\", 12-NR, $0 }'\nfor (i=11;i>=0;--i){\n   (1 - e(-(2^i)/65536*l(2))) * 2^(32-i)\n}\nEND\necho '#endif'\n", "num_lines": 111}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nBINARY=$1\nINSTALLPATH=\"$2\"\nWORKDIR=\"$3\"\n\n\nif [ -z \"$DESTDIR\" ]; then\n\tOUTDIR=\"$INSTALLPATH\"\nelse\n\tif [ -n $(echo ${INSTALLPATH} | grep \"^[A-Z]:\") ]; then\n\t\tINSTALLPATH=\"${INSTALLPATH:3}\"\n\tfi\n\tOUTDIR=\"$WORKDIR/$DESTDIR/$INSTALLPATH\"\nfi\n\nIFS=$'\\n'\nif [ -n $(which ntldd 2>&1 | grep /ntldd) ]; then\n\tDLLS=$(ntldd -R \"$BINARY\" | grep -i mingw | cut -d\">\" -f2 | sed -e 's/(0x[0-9a-f]\\+)//' -e 's/^ \\+//' -e 's/ \\+$//' -e 's,\\\\,/,g')\nelif [ -n $(which gdb 2>&1 | grep /gdb) ]; then\n\tDLLS=$(gdb \"$BINARY\" --command=$(dirname $0)/dlls.gdb | grep -i mingw | cut -d\" \" -f7- | sed -e 's/^ \\+//' -e 's/ \\+$//' -e 's,\\\\,/,g')\nelse\n\techo \"Please install gdb or ntldd for deploying DLLs\"\nfi\ncp -vu $DLLS \"$OUTDIR\"\nif [ -n $(which windeployqt 2>&1 | grep /windeployqt) ]; then\n\twindeployqt --no-opengl-sw --no-svg --release --dir \"$OUTDIR\" \"$BINARY\"\nfi\n", "num_lines": 28}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n# Clean up the caveats that CPack leaves behind\nBINARY=mgba\n\nrmdep () {\n    local DEP=$1\n    echo Removing dependency $DEP\n    sed -i~ \"s/[^, ]*$DEP[^,]*//g\" deb-temp/DEBIAN/control\n}\n\nadddep() {\n    local DEP=$1\n    echo Adding dependency $DEP\n    sed -i~ \"s/^Depends: /&$DEP,/\" deb-temp/DEBIAN/control\n}\n\nwhile [ $# -gt 0 ]; do\n    DEB=$1\n    dpkg-deb -R $DEB deb-temp\n    mv $DEB $DEB~\n    sed -i~ s/mgba-// deb-temp/DEBIAN/control\n    PKG=`head -n1 deb-temp/DEBIAN/control | cut -f2 -d ' '`\n    echo Found pacakge $PKG\n\n    case $PKG in\n    lib$BINARY)\n        rmdep sdl\n        rmdep qt\n    ;;\n    $BINARY-qt)\n        rmdep libav\n        rmdep libedit\n        rmdep libpng\n        rmdep libzip\n        rmdep libmagickwand\n        rmdep libswscale\n        rmdep zlib\n        adddep lib$BINARY\n    ;;\n    $BINARY-sdl)\n        rmdep libav\n        rmdep libedit\n        rmdep libpng\n        rmdep qt\n        rmdep libzip\n        rmdep libmagickwand\n        rmdep libswscale\n        rmdep zlib\n        adddep lib$BINARY\n    ;;\n    *)\n        echo Unknown package!\n    esac\n\n    sed -i~ \"s/,,*/,/g\" deb-temp/DEBIAN/control\n    sed -i~ \"s/,$//g\" deb-temp/DEBIAN/control\n    sed -i~ \"/^[^:]*: $/d\" deb-temp/DEBIAN/control\n    rm deb-temp/DEBIAN/control~\n    chmod 644 deb-temp/DEBIAN/md5sums\n    chown -R root:root deb-temp\n    dpkg-deb -b deb-temp $DEB\n    rm -rf deb-temp\n    shift\ndone\n", "num_lines": 65}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\nrm -rf genplus.opk\nmksquashfs gen_gcw0 opk-data/* genplus.opk -all-root -noappend -no-exports -no-xattrs", "num_lines": 3}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "g++-4.5 -std=gnu++0x -I../../../.. -o generate generate.cpp\n", "num_lines": 2}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\ncd \"$(dirname $0)/../\"\n./docker/linux/build_scripts/prefetch.sh OPENSSL CURL\ndocker build . --tag openai/retro-build:linux-v2 --file docker/linux/Dockerfile\ndocker push openai/retro-build:linux-v2\ndocker build . --tag openai/retro-build:win64-v2 --file docker/windows/Dockerfile\ndocker push openai/retro-build:win64-v2", "num_lines": 8}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Top-level build script called from Dockerfile\n\n# Stop at any error, show all commands\nset -ex\n\n# Set build environment variables\nMY_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n. $MY_DIR/build_env.sh\n\n# Dependencies for compiling Python that we want to remove from\n# the final image after compiling Python\n# GPG installed to verify signatures on Python source tarballs.\nPYTHON_COMPILE_DEPS=\"zlib-devel bzip2-devel ncurses-devel sqlite-devel readline-devel tk-devel gdbm-devel db4-devel libpcap-devel xz-devel gpg libffi-devel\"\n\n# Libraries that are allowed as part of the manylinux1 profile\nMANYLINUX1_DEPS=\"glibc-devel libstdc++-devel glib2-devel libX11-devel libXext-devel libXrender-devel  mesa-libGL-devel libICE-devel libSM-devel ncurses-devel\"\n\n# Centos 5 is EOL and is no longer available from the usual mirrors, so switch\n# to http://vault.centos.org\n# From: https://github.com/rust-lang/rust/pull/41045\n# The location for version 5 was also removed, so now only the specific release\n# (5.11) can be referenced.\nsed -i 's/enabled=1/enabled=0/' /etc/yum/pluginconf.d/fastestmirror.conf\nsed -i 's/mirrorlist/#mirrorlist/' /etc/yum.repos.d/*.repo\nsed -i 's/#\\(baseurl.*\\)mirror.centos.org\\/centos\\/$releasever/\\1vault.centos.org\\/5.11/' /etc/yum.repos.d/*.repo\n\n# Get build utilities\nsource $MY_DIR/build_utils.sh\n\n# See https://unix.stackexchange.com/questions/41784/can-yum-express-a-preference-for-x86-64-over-i386-packages\necho \"multilib_policy=best\" >> /etc/yum.conf\n\n# https://hub.docker.com/_/centos/\n# \"Additionally, images with minor version tags that correspond to install\n# media are also offered. These images DO NOT recieve updates as they are\n# intended to match installation iso contents. If you choose to use these\n# images it is highly recommended that you include RUN yum -y update && yum\n# clean all in your Dockerfile, or otherwise address any potential security\n# concerns.\"\n# Decided not to clean at this point: https://github.com/pypa/manylinux/pull/129\nyum -y update\n\n# EPEL support\nyum -y install wget\nwget -q http://archives.fedoraproject.org/pub/archive/epel/5/x86_64/epel-release-5-4.noarch.rpm\ncheck_sha256sum epel-release-5-4.noarch.rpm $EPEL_RPM_HASH\n\n# Dev toolset (for LLVM and other projects requiring C++11 support)\nwget -q http://people.centos.org/tru/devtools-2/devtools-2.repo\ncheck_sha256sum devtools-2.repo $DEVTOOLS_HASH\nmv devtools-2.repo /etc/yum.repos.d/devtools-2.repo\nrpm -Uvh --replacepkgs epel-release-5*.rpm\nrm -f epel-release-5*.rpm\n\n# from now on, we shall only use curl to retrieve files\nyum -y erase wget\n\n# Development tools and libraries\nyum -y install \\\n    automake \\\n    bison \\\n    bzip2 \\\n    cmake28 \\\n    devtoolset-2-binutils \\\n    devtoolset-2-gcc \\\n    devtoolset-2-gcc-c++ \\\n    devtoolset-2-gcc-gfortran \\\n    diffutils \\\n    expat-devel \\\n    gettext \\\n    kernel-devel-`uname -r` \\\n    file \\\n    make \\\n    patch \\\n    unzip \\\n    which \\\n    yasm \\\n    ${PYTHON_COMPILE_DEPS}\n\n# Build an OpenSSL for both curl and the Pythons. We'll delete this at the end.\nbuild_openssl $OPENSSL_ROOT $OPENSSL_HASH\n\n# Install curl so we can have TLS 1.2 in this ancient container.\nbuild_curl $CURL_ROOT $CURL_HASH\nhash -r\ncurl --version\ncurl-config --features\n\n# Install a git we link against OpenSSL so that we can use TLS 1.2\nbuild_git $GIT_ROOT $GIT_HASH\ngit version\n\n# Install newest autoconf\nbuild_autoconf $AUTOCONF_ROOT $AUTOCONF_HASH\nautoconf --version\n\n# Install newest automake\nbuild_automake $AUTOMAKE_ROOT $AUTOMAKE_HASH\nautomake --version\n\n# Install newest libtool\nbuild_libtool $LIBTOOL_ROOT $LIBTOOL_HASH\nlibtool --version\n\n# Install a more recent SQLite3\ncurl -fsSLO $SQLITE_AUTOCONF_DOWNLOAD_URL/$SQLITE_AUTOCONF_VERSION.tar.gz\ncheck_sha256sum $SQLITE_AUTOCONF_VERSION.tar.gz $SQLITE_AUTOCONF_HASH\ntar xfz $SQLITE_AUTOCONF_VERSION.tar.gz\ncd $SQLITE_AUTOCONF_VERSION\ndo_standard_install\ncd ..\nrm -rf $SQLITE_AUTOCONF_VERSION*\n\n# Compile the latest Python releases.\n# (In order to have a proper SSL module, Python is compiled\n# against a recent openssl [see env vars above], which is linked\n# statically.\nmkdir -p /opt/python\nbuild_cpythons $CPYTHON_VERSIONS\n\nPY36_BIN=/opt/python/cp36-cp36m/bin\n\n# Install certifi and auditwheel\n$PY36_BIN/pip install --require-hashes -r $MY_DIR/py36-requirements.txt\n\n# Our openssl doesn't know how to find the system CA trust store\n#   (https://github.com/pypa/manylinux/issues/53)\n# And it's not clear how up-to-date that is anyway\n# So let's just use the same one pip and everyone uses\nln -s $($PY36_BIN/python -c 'import certifi; print(certifi.where())') \\\n      /opt/_internal/certs.pem\n# If you modify this line you also have to modify the versions in the\n# Dockerfiles:\nexport SSL_CERT_FILE=/opt/_internal/certs.pem\n\n# Now we can delete our built OpenSSL headers/static libs since we've linked everything we need\nrm -rf /usr/local/ssl\n\n# Install patchelf (latest with unreleased bug fixes)\ncurl -fsSL -o patchelf.tar.gz https://github.com/NixOS/patchelf/archive/$PATCHELF_VERSION.tar.gz\ncheck_sha256sum patchelf.tar.gz $PATCHELF_HASH\ntar -xzf patchelf.tar.gz\n(cd patchelf-$PATCHELF_VERSION && ./bootstrap.sh && do_standard_install)\nrm -rf patchelf.tar.gz patchelf-$PATCHELF_VERSION\n\nln -s $PY36_BIN/auditwheel /usr/local/bin/auditwheel\n\n# Clean up development headers and other unnecessary stuff for\n# final image\nyum -y erase \\\n    avahi \\\n    bitstream-vera-fonts \\\n    freetype \\\n    gtk2 \\\n    hicolor-icon-theme \\\n    libX11 \\\n    wireless-tools \\\n    ${PYTHON_COMPILE_DEPS}  > /dev/null 2>&1\nyum -y install ${MANYLINUX1_DEPS}\nyum -y clean all > /dev/null 2>&1\nyum list installed\n\n# we don't need libpython*.a, and they're many megabytes\nfind /opt/_internal -name '*.a' -print0 | xargs -0 rm -f\n\n# Strip what we can -- and ignore errors, because this just attempts to strip\n# *everything*, including non-ELF files:\nfind /opt/_internal -type f -print0 \\\n    | xargs -0 -n1 strip --strip-unneeded 2>/dev/null || true\n\n# We do not need the Python test suites, or indeed the precompiled .pyc and\n# .pyo files. Partially cribbed from:\n#    https://github.com/docker-library/python/blob/master/3.4/slim/Dockerfile\nfind /opt/_internal -depth \\\n     \\( -type d -a -name test -o -name tests \\) \\\n  -o \\( -type f -a -name '*.pyc' -o -name '*.pyo' \\) | xargs rm -rf\n\nfor PYTHON in /opt/python/*/bin/python; do\n    # Smoke test to make sure that our Pythons work, and do indeed detect as\n    # being manylinux compatible:\n    $PYTHON $MY_DIR/manylinux1-check.py\n    # Make sure that SSL cert checking works\n    $PYTHON $MY_DIR/ssl-check.py\ndone\n\n# Fix libc headers to remain compatible with C99 compilers.\nfind /usr/include/ -type f -exec sed -i 's/\\bextern _*inline_*\\b/extern __inline __attribute__ ((__gnu_inline__))/g' {} +\n", "num_lines": 189}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "# source me\n\nPYTHON_DOWNLOAD_URL=https://www.python.org/ftp/python\nCPYTHON_VERSIONS=\"3.5.6 3.6.7 3.7.1 3.8.2\"\n\n# openssl version to build, with expected sha256 hash of .tar.gz\n# archive.\nOPENSSL_ROOT=openssl-1.0.2p\nOPENSSL_HASH=50a98e07b1a89eb8f6a99477f262df71c6fa7bef77df4dc83025a2845c827d00\nOPENSSL_DOWNLOAD_URL=https://www.openssl.org/source/old/1.0.2\n\n# Update to slightly newer, verified Git commit:\n# https://github.com/NixOS/patchelf/commit/2a9cefd7d637d160d12dc7946393778fa8abbc58\nPATCHELF_VERSION=2a9cefd7d637d160d12dc7946393778fa8abbc58\nPATCHELF_HASH=12da4727f09be42ae0b54878e1b8e86d85cb7a5b595731cdc1a0a170c4873c6d\n\nCURL_ROOT=curl-7.60.0\nCURL_HASH=e9c37986337743f37fd14fe8737f246e97aec94b39d1b71e8a5973f72a9fc4f5\nCURL_DOWNLOAD_URL=https://curl.haxx.se/download\n\nAUTOCONF_ROOT=autoconf-2.69\nAUTOCONF_HASH=954bd69b391edc12d6a4a51a2dd1476543da5c6bbf05a95b59dc0dd6fd4c2969\nAUTOCONF_DOWNLOAD_URL=http://ftp.gnu.org/gnu/autoconf\nAUTOMAKE_ROOT=automake-1.16.1\nAUTOMAKE_HASH=608a97523f97db32f1f5d5615c98ca69326ced2054c9f82e65bade7fc4c9dea8\nAUTOMAKE_DOWNLOAD_URL=http://ftp.gnu.org/gnu/automake\nLIBTOOL_ROOT=libtool-2.4.6\nLIBTOOL_HASH=e3bd4d5d3d025a36c21dd6af7ea818a2afcd4dfc1ea5a17b39d7854bcd0c06e3\nLIBTOOL_DOWNLOAD_URL=http://ftp.gnu.org/gnu/libtool\n\nSQLITE_AUTOCONF_VERSION=sqlite-autoconf-3230100\nSQLITE_AUTOCONF_HASH=92842b283e5e744eff5da29ed3c69391de7368fccc4d0ee6bf62490ce555ef25\nSQLITE_AUTOCONF_DOWNLOAD_URL=https://www.sqlite.org/2018\n\nGIT_ROOT=2.17.0\nGIT_HASH=46f3a29c250313276ac747a3a221ca69dbc3218754f8db188841322cf7ab58d3\nGIT_DOWNLOAD_URL=https://github.com/git/git/archive\n\nGET_PIP_URL=https://bootstrap.pypa.io/get-pip.py\nEPEL_RPM_HASH=0dcc89f9bf67a2a515bad64569b7a9615edc5e018f676a578d5fd0f17d3c81d4\nDEVTOOLS_HASH=a8ebeb4bed624700f727179e6ef771dafe47651131a00a78b342251415646acc\n", "num_lines": 42}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Helper utilities for build\n\n\nfunction check_var {\n    if [ -z \"$1\" ]; then\n        echo \"required variable not defined\"\n        exit 1\n    fi\n}\n\n\nfunction lex_pyver {\n    # Echoes Python version string padded with zeros\n    # Thus:\n    # 3.2.1 -> 003002001\n    # 3     -> 003000000\n    echo $1 | awk -F \".\" '{printf \"%03d%03d%03d\", $1, $2, $3}'\n}\n\n\nfunction pyver_dist_dir {\n    # Echoes the dist directory name of given pyver, removing alpha/beta prerelease\n    # Thus:\n    # 3.2.1   -> 3.2.1\n    # 3.7.0b4 -> 3.7.0\n    echo $1 | awk -F \".\" '{printf \"%d.%d.%d\", $1, $2, $3}'\n}\n\n\nfunction do_cpython_build {\n    local py_ver=$1\n    check_var $py_ver\n    local ucs_setting=$2\n    check_var $ucs_setting\n    tar -xzf Python-$py_ver.tgz\n    pushd Python-$py_ver\n    if [ \"$ucs_setting\" = \"none\" ]; then\n        unicode_flags=\"\"\n        dir_suffix=\"\"\n    else\n        local unicode_flags=\"--enable-unicode=$ucs_setting\"\n        local dir_suffix=\"-$ucs_setting\"\n    fi\n    local prefix=\"/opt/_internal/cpython-${py_ver}${dir_suffix}\"\n    mkdir -p ${prefix}/lib\n    ./configure --prefix=${prefix} --disable-shared $unicode_flags > /dev/null\n    make -j2 > /dev/null\n    make install > /dev/null\n    popd\n    rm -rf Python-$py_ver\n    # Some python's install as bin/python3. Make them available as\n    # bin/python.\n    if [ -e ${prefix}/bin/python3 ]; then\n        ln -s python3 ${prefix}/bin/python\n    fi\n    # --force-reinstall is to work around:\n    #   https://github.com/pypa/pip/issues/5220\n    #   https://github.com/pypa/get-pip/issues/19\n    ${prefix}/bin/python get-pip.py --force-reinstall\n    if [ -e ${prefix}/bin/pip3 ] && [ ! -e ${prefix}/bin/pip ]; then\n        ln -s pip3 ${prefix}/bin/pip\n    fi\n    # Since we fall back on a canned copy of get-pip.py, we might not have\n    # the latest pip and friends. Upgrade them to make sure.\n    ${prefix}/bin/pip install -U --require-hashes -r ${MY_DIR}/requirements.txt\n    local abi_tag=$(${prefix}/bin/python ${MY_DIR}/python-tag-abi-tag.py)\n    ln -s ${prefix} /opt/python/${abi_tag}\n}\n\n\nfunction build_cpython {\n    local py_ver=$1\n    check_var $py_ver\n    check_var $PYTHON_DOWNLOAD_URL\n    local py_dist_dir=$(pyver_dist_dir $py_ver)\n    curl -fsSLO $PYTHON_DOWNLOAD_URL/$py_dist_dir/Python-$py_ver.tgz\n    curl -fsSLO $PYTHON_DOWNLOAD_URL/$py_dist_dir/Python-$py_ver.tgz.asc\n    gpg --verify Python-$py_ver.tgz.asc\n    if [ $(lex_pyver $py_ver) -lt $(lex_pyver 3.3) ]; then\n        do_cpython_build $py_ver ucs2\n        do_cpython_build $py_ver ucs4\n    else\n        do_cpython_build $py_ver none\n    fi\n    rm -f Python-$py_ver.tgz\n    rm -f Python-$py_ver.tgz.asc\n}\n\n\nfunction build_cpythons {\n    check_var $GET_PIP_URL\n    curl -fsSLO $GET_PIP_URL\n    # Import public keys used to verify downloaded Python source tarballs.\n    curl -fsSLO https://www.python.org/static/files/pubkeys.txt\n    gpg --import pubkeys.txt\n    for py_ver in $@; do\n        build_cpython $py_ver\n    done\n    # Remove GPG hidden directory.\n    rm -rf /root/.gnupg/\n    rm -f get-pip.py\n}\n\n\nfunction do_openssl_build {\n    ./config no-ssl2 no-shared -fPIC --prefix=/usr/local/ssl > /dev/null\n    make > /dev/null\n    make install_sw > /dev/null\n}\n\n\nfunction check_required_source {\n    local file=$1\n    check_var ${file}\n    if [ ! -f $file ]; then\n        echo \"Required source archive must be prefetched to docker/sources/ with prefetch.sh: $file\"\n        return 1\n    fi\n}\n\n\nfunction fetch_source {\n    # This is called both inside and outside the build context (e.g. in Travis) to prefetch\n    # source tarballs, where curl exists (and works)\n    local file=$1\n    check_var ${file}\n    local url=$2\n    check_var ${url}\n    if [ -f ${file} ]; then\n        echo \"${file} exists, skipping fetch\"\n    else\n        curl -fsSL -o ${file} ${url}/${file}\n    fi\n}\n\n\nfunction check_sha256sum {\n    local fname=$1\n    check_var ${fname}\n    local sha256=$2\n    check_var ${sha256}\n\n    echo \"${sha256}  ${fname}\" > ${fname}.sha256\n    sha256sum -c ${fname}.sha256\n    rm -f ${fname}.sha256\n}\n\n\nfunction build_openssl {\n    local openssl_fname=$1\n    check_var ${openssl_fname}\n    local openssl_sha256=$2\n    check_var ${openssl_sha256}\n    # Can't use curl here because we don't have it yet, OpenSSL must be prefetched\n    check_required_source ${openssl_fname}.tar.gz\n    check_sha256sum ${openssl_fname}.tar.gz ${openssl_sha256}\n    tar -xzf ${openssl_fname}.tar.gz\n    (cd ${openssl_fname} && do_openssl_build)\n    rm -rf ${openssl_fname} ${openssl_fname}.tar.gz\n}\n\n\nfunction build_git {\n    local git_fname=$1\n    check_var ${git_fname}\n    local git_sha256=$2\n    check_var ${git_sha256}\n    check_var ${GIT_DOWNLOAD_URL}\n    fetch_source v${git_fname}.tar.gz ${GIT_DOWNLOAD_URL}\n    check_sha256sum v${git_fname}.tar.gz ${git_sha256}\n    tar -xzf v${git_fname}.tar.gz\n    (cd git-${git_fname} && make install prefix=/usr/local LDFLAGS=\"-L/usr/local/ssl/lib -ldl\" CFLAGS=\"-I/usr/local/ssl/include\" > /dev/null)\n    rm -rf git-${git_fname} v${git_fname}.tar.gz\n}\n\n\nfunction do_curl_build {\n    # We do this shared to avoid obnoxious linker issues where git couldn't\n    # link properly. If anyone wants to make this build statically go for it.\n    LIBS=-ldl CFLAGS=-Wl,--exclude-libs,ALL ./configure --with-ssl --disable-static > /dev/null\n    make > /dev/null\n    make install > /dev/null\n}\n\n\nfunction build_curl {\n    local curl_fname=$1\n    check_var ${curl_fname}\n    local curl_sha256=$2\n    check_var ${curl_sha256}\n    check_var ${CURL_DOWNLOAD_URL}\n    # Can't use curl here because we don't have it yet...we are building it. It must be prefetched\n    check_required_source ${curl_fname}.tar.gz\n    check_sha256sum ${curl_fname}.tar.gz ${curl_sha256}\n    tar -zxf ${curl_fname}.tar.gz\n    (cd curl-* && do_curl_build)\n    rm -rf curl-*\n}\n\n\nfunction do_standard_install {\n    ./configure > /dev/null\n    make > /dev/null\n    make install > /dev/null\n}\n\n\nfunction build_autoconf {\n    local autoconf_fname=$1\n    check_var ${autoconf_fname}\n    local autoconf_sha256=$2\n    check_var ${autoconf_sha256}\n    check_var ${AUTOCONF_DOWNLOAD_URL}\n    fetch_source ${autoconf_fname}.tar.gz ${AUTOCONF_DOWNLOAD_URL}\n    check_sha256sum ${autoconf_fname}.tar.gz ${autoconf_sha256}\n    tar -zxf ${autoconf_fname}.tar.gz\n    (cd ${autoconf_fname} && do_standard_install)\n    rm -rf ${autoconf_fname} ${autoconf_fname}.tar.gz\n}\n\n\nfunction build_automake {\n    local automake_fname=$1\n    check_var ${automake_fname}\n    local automake_sha256=$2\n    check_var ${automake_sha256}\n    check_var ${AUTOMAKE_DOWNLOAD_URL}\n    fetch_source ${automake_fname}.tar.gz ${AUTOMAKE_DOWNLOAD_URL}\n    check_sha256sum ${automake_fname}.tar.gz ${automake_sha256}\n    tar -zxf ${automake_fname}.tar.gz\n    (cd ${automake_fname} && do_standard_install)\n    rm -rf ${automake_fname} ${automake_fname}.tar.gz\n}\n\n\nfunction build_libtool {\n    local libtool_fname=$1\n    check_var ${libtool_fname}\n    local libtool_sha256=$2\n    check_var ${libtool_sha256}\n    check_var ${LIBTOOL_DOWNLOAD_URL}\n    fetch_source ${libtool_fname}.tar.gz ${LIBTOOL_DOWNLOAD_URL}\n    check_sha256sum ${libtool_fname}.tar.gz ${libtool_sha256}\n    tar -zxf ${libtool_fname}.tar.gz\n    (cd ${libtool_fname} && do_standard_install)\n    rm -rf ${libtool_fname} ${libtool_fname}.tar.gz\n}\n", "num_lines": 249}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n# Prefetch tarballs so they don't need to be fetched in the container (which has\n# very old tools).\n#\n# usage: prefetch.sh [name ...]\nset -ex\n\nMY_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n. $MY_DIR/build_env.sh\n. $MY_DIR/build_utils.sh\n\nSOURCES=$MY_DIR/../sources\n\n[ -d \"$SOURCES\" ] || mkdir \"$SOURCES\"\ncd \"$SOURCES\"\n\nfor name in \"$@\"; do\n    name_upper=$(echo \"${name}\" | tr [:lower:] [:upper:])\n    root=${name_upper}_ROOT\n    ext=${name_upper}_EXTENSION\n    url=${name_upper}_DOWNLOAD_URL\n    file=${!root}${!ext:-.tar.gz}\n    fetch_source $file ${!url}\ndone\n", "num_lines": 25}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -n \"$CROSS\" ]; then\n\tTOOLCHAIN=-DCMAKE_TOOLCHAIN_FILE=../../cmake/$CROSS.cmake\nelse\n\tCROSS=native\nfi\n\ncd capnproto/c++\nmkdir build-$CROSS\ncd build-$CROSS\ncmake .. $TOOLCHAIN \\\n         -DCMAKE_INSTALL_PREFIX=$ROOT \\\n         -DBUILD_SHARED_LIBS=OFF \\\n         -DBUILD_STATIC_LIBS=ON \\\n         -DBUILD_TESTING=OFF\nsed -i -E -e 's,\\$<TARGET_FILE:CapnProto::capnp_tool>,/usr/bin/capnp,' -e 's,\\$<TARGET_FILE:CapnProto::capnpc_cpp>,/usr/bin/capnpc-c++,' cmake/CapnProtoConfig.cmake\nmake -j2 install\ncd ..\nrm -rf build-$CROSS\n", "num_lines": 21}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ncurl -LO https://www.samba.org/ftp/ccache/ccache-3.4.2.tar.bz2\ntar xjf ccache-*.tar.bz2\nrm ccache-*.tar.bz2\npushd ccache*\n./configure --prefix=/usr/local\nmake install\npopd\nrm -rf ccache\n\nmkdir -p /usr/local/libexec/ccache\npushd /usr/local/libexec/ccache\nln -s /usr/local/bin/ccache cc\nln -s /usr/local/bin/ccache c++\npopd\n", "num_lines": 17}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -n \"$CROSS\" ]; then\n\tTOOLCHAIN=-DCMAKE_TOOLCHAIN_FILE=../../cmake/$CROSS.cmake\nelse\n\tCROSS=native\nfi\n\ncd libzip\nsed -i -Ee \"/ADD_SUBDIRECTORY\\\\((examples|regress|src)\\\\)/d\" CMakeLists.txt\nmkdir build-$CROSS\ncd build-$CROSS\nrm -f $ROOT/lib/libz.dll.a # Prevent shared builds\ncmake .. $TOOLCHAIN \\\n         -DCMAKE_INSTALL_PREFIX=$ROOT \\\n         -DBUILD_SHARED_LIBS=OFF \\\n         -DBUILD_STATIC_LIBS=ON\nmake -j2 install\ncd ..\nrm -rf build-$CROSS\n", "num_lines": 21}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ncase $CROSS in\nwin32)\n\tCROSS_COMPILE=i686-w64-mingw32-\n\t;;\nwin64)\n\tCROSS_COMPILE=x86_64-w64-mingw32-\n\t;;\nesac\n\nif [ -n \"$CROSS_COMPILE\" ]; then\n\tCROSS_OPTS=\"-xplatform win32-g++ -device-option CROSS_COMPILE=$CROSS_COMPILE\"\nfi\n\nREMOVE_QT=\"\n3d\nactiveqt\ncanvas3d\nconnectivity\ndeclarative\ndoc\ndocgallery\nenginio\nfeedback\ngraphicaleffects\nimageformats\nlocation\npim\npurchasing\nqa\nquick1\nquickcontrols\nquickcontrols2\nrepotools\nscript\nsensors\nserialbus\nserialport\nsvg\nsystems\nwayland\nwebchannel\nwebengine\nwebkit\nwebkit-examples\nwebsockets\nwebview\nxmlpatterns\n\"\n\nif [ -d qt5 ]; then\n\tcd qt5\n\tgit clean -dfx\n\tgit submodule foreach git clean -dfx\nelse\n\tgit clone https://github.com/qt/qt5.git -b v5.6.3\n\tcd qt5\n\tgit submodule init\n\tfor dir in $REMOVE_QT; do\n\t    git submodule deinit -f qt$dir\n\tdone\n\tgit submodule update\nfi\n\n./configure \\\n\t-prefix $ROOT \\\n\t-opensource \\\n\t-confirm-license \\\n\t-platform linux-g++ \\\n\t$CROSS_OPTS \\\n\t-release \\\n\t-I $ROOT/include \\\n\t-L $ROOT/lib \\\n\t-v \\\n\t-static \\\n\t-c++std c++14 \\\n\t-opengl desktop \\\n\t-no-pch \\\n\t-no-avx2 \\\n\t-nomake examples \\\n\t-nomake tools \\\n\t-nomake tests \\\n\t-no-compile-examples \\\n\t-no-freetype \\\n\t-no-icu \\\n\t-no-gif \\\n\t-no-sql-odbc \\\n\t-no-harfbuzz \\\n\t-no-openssl \\\n\t-no-dbus && make -j$(nproc) install\n", "num_lines": 92}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ncase $CROSS in\nwin32)\n\tPLATFORM=win32\n\t;;\nwin64)\n\tPLATFORM=amd64\n\t;;\nesac\n\nfunction install_python {\n\tlocal MAJOR=$1\n\tlocal MINOR=$2\n\tlocal PATCH=$3\n\n\tcurl -LO https://www.python.org/ftp/python/$MAJOR.$MINOR.$PATCH/$PLATFORM/dev.msi\n\t7z x dev.msi\n\tmkdir -p $ROOT/lib/python$MAJOR.$MINOR include include/cpython include/internal\n\tmv libs_python.lib $ROOT/lib/python$MAJOR.$MINOR/python$MAJOR$MINOR.lib\n\tmv libs_python_stable.lib $ROOT/lib/python$MAJOR.$MINOR/python$MAJOR.lib\n\tmv libs_libpython.a $ROOT/lib/python$MAJOR.$MINOR/libpython.a\n\tfind . -maxdepth 1 -name include_cpython_\\*.h -print0 | xargs -0 -n1 -I% bash -c 'mv % $(echo % | sed -e \"s,_,/,\" | sed -e \"s,_,/,\")'\n\tfind . -maxdepth 1 -name include_internal_\\*.h -print0 | xargs -0 -n1 -I% bash -c 'mv % $(echo % | sed -e \"s,_,/,\" | sed -e \"s,_,/,\")'\n\tfind . -maxdepth 1 -name include_\\*.h -print0 | xargs -0 -n1 -I% bash -c 'mv % $(echo % | sed -e \"s,_,/,\")'\n\tmv include $ROOT/include/python$MAJOR.$MINOR\n\trm dev.msi\n\n\t# python 3.8 is missing this file, create it from the dll\n\t# https://github.com/openai/retro/pull/201#issuecomment-619326417\n\tif [[ ! -f $ROOT/lib/python$MAJOR.$MINOR/libpython.a ]]\n\tthen\n\t\tcurl -LO https://www.python.org/ftp/python/$MAJOR.$MINOR.$PATCH/$PLATFORM/core.msi\n\t\t7z x core.msi\n\t\tapt-get install --yes mingw-w64-tools\n\t\tgendef python.dll\n\t\t/usr/bin/x86_64-w64-mingw32-dlltool --as-flags=--64 -m i386:x86-64 -k --output-lib $ROOT/lib/python$MAJOR.$MINOR/libpython.a --input-def python.def\n\t\trm *.dll *.def core.msi\n\tfi\n}\n\ninstall_python 3 5 4\ninstall_python 3 6 6\ninstall_python 3 7 0\ninstall_python 3 8 2\n", "num_lines": 46}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nautopep8 -ir -j2 . &\nfind src \\( -name \\*.cpp -o -name \\*.h \\) -a \\( -not -name libretro.h -a -not -name *.capnp.* -a -not -path \\*CMake\\* -a -not -path \\*autogen\\* \\) -print0 | \\\n\txargs -0 -P2 clang-format -i &\n\nwait\n", "num_lines": 8}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -euo pipefail\n\nif [ \"$1\" != \"package\" ]; then\n  if (grep -r KJ_DBG c++/src | egrep -v '/debug(-test)?[.]' | grep -v 'See KJ_DBG\\.$'); then\n    echo '*** Error:  There are instances of KJ_DBG in the code.' >&2\n    exit 1\n  fi\n\n  if (egrep -r 'TODO\\((now|soon)\\)' *); then\n    echo '*** Error:  There are release-blocking TODOs in the code.' >&2\n    exit 1\n  fi\nfi\n\ndoit() {\n  echo \"@@@@ $@\"\n  \"$@\"\n}\n\nget_version() {\n  local VERSION=$(grep AC_INIT c++/configure.ac | sed -e 's/^[^]]*],\\[\\([^]]*\\)].*$/\\1/g')\n  if [[ ! \"$VERSION\" =~ $1 ]]; then\n    echo \"Couldn't parse version: $VERSION\" >&2\n    exit 1\n  fi\n  echo \"$VERSION\"\n}\n\nget_release_version() {\n  get_version '^[0-9]+[.][0-9]+[.][0-9]+(-rc[0-9]+|[.][0-9]+)?$'\n}\n\nupdate_version() {\n  local OLD=$1\n  local NEW=$2\n  local BRANCH_DESC=$3\n\n  local OLD_REGEX=${OLD//./[.]}\n  doit sed -i -e \"s/$OLD_REGEX/$NEW/g\" c++/configure.ac\n  doit sed -i -e \"s/set(VERSION.*)/set(VERSION $NEW)/g\" c++/CMakeLists.txt\n\n  local NEW_NOTAG=${NEW%%-*}\n  declare -a NEW_ARR=(${NEW_NOTAG//./ })\n  doit sed -i -re \"\n      s/^#define CAPNP_VERSION_MAJOR [0-9]+\\$/#define CAPNP_VERSION_MAJOR ${NEW_ARR[0]}/g;\n      s/^#define CAPNP_VERSION_MINOR [0-9]+\\$/#define CAPNP_VERSION_MINOR ${NEW_ARR[1]}/g;\n      s/^#define CAPNP_VERSION_MICRO [0-9]+\\$/#define CAPNP_VERSION_MICRO ${NEW_ARR[2]:-0}/g\" \\\n      c++/src/capnp/common.h\n\n  local NEW_COMBINED=$(( ${NEW_ARR[0]} * 1000000 + ${NEW_ARR[1]} * 1000 + ${NEW_ARR[2]:-0 }))\n  doit sed -i -re \"s/^#if CAPNP_VERSION != [0-9]*\\$/#if CAPNP_VERSION != $NEW_COMBINED/g\" \\\n      c++/src/*/*.capnp.h c++/src/*/*/*.capnp.h\n\n  doit git commit -a -m \"Set $BRANCH_DESC version to $NEW.\"\n}\n\nbuild_packages() {\n  local VERSION=$1\n  local VERSION_BASE=${VERSION%%-*}\n\n  echo \"=========================================================================\"\n  echo \"Building C++ package...\"\n  echo \"=========================================================================\"\n\n  # make dist tarball and move into ..\n  cd c++\n  doit autoreconf -i\n  doit ./configure\n  doit make -j6 distcheck\n  doit mv capnproto-c++-$VERSION.tar.gz ..\n  doit make distclean\n\n  # build windows executables\n  doit ./configure --host=i686-w64-mingw32 --with-external-capnp \\\n      --disable-shared CXXFLAGS='-static-libgcc -static-libstdc++'\n  doit make -j6 capnp.exe capnpc-c++.exe capnpc-capnp.exe\n  doit i686-w64-mingw32-strip capnp.exe capnpc-c++.exe capnpc-capnp.exe\n  doit mkdir capnproto-tools-win32-$VERSION\n  doit mv capnp.exe capnpc-c++.exe capnpc-capnp.exe capnproto-tools-win32-$VERSION\n  doit make maintainer-clean\n\n  # repack dist tarball and win32 tools into win32 zip, with DOS line endings\n  doit tar zxf ../capnproto-c++-$VERSION.tar.gz\n  find capnproto-c++-$VERSION -name '*.c++' -o -name '*.h' -o -name '*.capnp' -o -name '*.md' -o -name '*.txt' | grep -v testdata | doit xargs unix2dos\n  doit zip -r ../capnproto-c++-win32-$VERSION.zip capnproto-c++-$VERSION capnproto-tools-win32-$VERSION\n\n  rm -rf capnproto-c++-$VERSION capnproto-tools-win32-$VERSION\n  cd ..\n}\n\ncherry_pick() {\n  shift\n  if [ $# -gt 0 ]; then\n    echo \"=========================================================================\"\n    echo \"Cherry-picking fixes\"\n    echo \"=========================================================================\"\n    doit git cherry-pick \"$@\"\n  fi\n}\n\ndone_banner() {\n  local VERSION=$1\n  local PUSH=$2\n  local FINAL=$3\n  echo \"=========================================================================\"\n  echo \"Done\"\n  echo \"=========================================================================\"\n  echo \"Ready to release:\"\n  echo \"  capnproto-c++-$VERSION.tar.gz\"\n  echo \"  capnproto-c++-win32-$VERSION.zip\"\n  echo \"Don't forget to push changes:\"\n  echo \"  git push origin $PUSH\"\n\n  read -s -n 1 -p \"Shall I push to git and upload to capnproto.org now? (y/N)\" YESNO\n\n  echo\n  case \"$YESNO\" in\n    y | Y )\n      doit git push origin $PUSH\n      doit gce-ss copy-files capnproto-c++-$VERSION.tar.gz capnproto-c++-win32-$VERSION.zip \\\n          fe:/var/www/capnproto.org\n\n      if [ \"$FINAL\" = yes ]; then\n        echo \"=========================================================================\"\n        echo \"Publishing docs\"\n        echo \"=========================================================================\"\n        cd doc\n        doit ./push-site.sh\n        cd ..\n        echo \"=========================================================================\"\n        echo \"Really done\"\n        echo \"=========================================================================\"\n      fi\n\n      echo \"Release is available at:\"\n      echo \"  http://capnproto.org/capnproto-c++-$VERSION.tar.gz\"\n      ;;\n    * )\n      echo \"OK, do it yourself then.\"\n      ;;\n  esac\n}\n\nBRANCH=$(git rev-parse --abbrev-ref HEAD)\n\ncase \"${1-}:$BRANCH\" in\n  # ======================================================================================\n  candidate:master )\n    echo \"New major release.\"\n\n    if [ $# -gt 1 ]; then\n      echo \"Cannot cherry-pick when starting from master.  Do it yourself.\" >&2\n      exit 1\n    fi\n\n    HEAD_VERSION=$(get_version '^[0-9]+[.][0-9]+-dev$')\n    RELEASE_VERSION=${HEAD_VERSION%%-dev}.0\n\n    echo \"Version: $RELEASE_VERSION\"\n\n    echo \"=========================================================================\"\n    echo \"Creating release branch...\"\n    echo \"=========================================================================\"\n    doit git checkout -b release-$RELEASE_VERSION\n\n    update_version $HEAD_VERSION $RELEASE_VERSION-rc1 \"release branch\"\n\n    build_packages $RELEASE_VERSION-rc1\n\n    echo \"=========================================================================\"\n    echo \"Updating version in master branch...\"\n    echo \"=========================================================================\"\n\n    doit git checkout master\n    declare -a VERSION_ARR=(${RELEASE_VERSION//./ })\n    NEXT_VERSION=${VERSION_ARR[0]}.$((VERSION_ARR[1] + 1))\n\n    update_version $HEAD_VERSION $NEXT_VERSION-dev \"mainlaine\"\n\n    done_banner $RELEASE_VERSION-rc1 \"master release-$RELEASE_VERSION\" no\n    ;;\n\n  # ======================================================================================\n  candidate:release-* )\n    echo \"New release candidate.\"\n    OLD_VERSION=$(get_release_version)\n\n    if [[ $OLD_VERSION == *-rc* ]]; then\n      # New release candidate for existing release.\n\n      RC=${OLD_VERSION##*-rc}\n      BRANCH_VERSION=${OLD_VERSION%%-rc*}\n      RC_VERSION=$BRANCH_VERSION-rc$(( RC + 1 ))\n\n      echo \"Version: $RC_VERSION\"\n    else\n      # New micro release.\n\n      declare -a VERSION_ARR=(${OLD_VERSION//./ })\n      BRANCH_VERSION=${VERSION_ARR[0]}.${VERSION_ARR[1]}.$((VERSION_ARR[2] + 1))\n\n      RC_VERSION=$BRANCH_VERSION-rc1\n      echo \"Version: $RC_VERSION\"\n\n      echo \"=========================================================================\"\n      echo \"Creating new release branch...\"\n      echo \"=========================================================================\"\n\n      doit git checkout -b release-$BRANCH_VERSION\n    fi\n\n    echo \"=========================================================================\"\n    echo \"Updating version number to $RC_VERSION...\"\n    echo \"=========================================================================\"\n\n    update_version $OLD_VERSION $RC_VERSION \"release branch\"\n\n    cherry_pick \"$@\"\n\n    build_packages $RC_VERSION\n\n    done_banner $RC_VERSION release-$BRANCH_VERSION no\n    ;;\n\n  # ======================================================================================\n  final:release-* )\n    echo \"Final release.\"\n    OLD_VERSION=$(get_release_version)\n\n    if [[ $OLD_VERSION != *-rc* ]]; then\n      echo \"Current version is already a final release.  You need to create a new candidate first.\" >&2\n      exit 1\n    fi\n\n    if [ $# -gt 1 ]; then\n      echo \"Cannot cherry-pick into final release.  Make another candidate.\" >&2\n      exit 1\n    fi\n\n    RC=${OLD_VERSION##*-rc}\n    NEW_VERSION=${OLD_VERSION%%-rc*}\n\n    echo \"Version: $NEW_VERSION\"\n\n    echo \"=========================================================================\"\n    echo \"Updating version number to $NEW_VERSION...\"\n    echo \"=========================================================================\"\n\n    doit sed -i -re \"s/capnproto-c[+][+]-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-c++-$NEW_VERSION/g\" doc/install.md\n    doit sed -i -re \"s/capnproto-c[+][+]-win32-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-c++-win32-$NEW_VERSION/g\" doc/install.md\n    doit sed -i -re \"s/capnproto-tools-win32-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-tools-win32-$NEW_VERSION/g\" doc/install.md\n    update_version $OLD_VERSION $NEW_VERSION \"release branch\"\n\n    doit git tag v$NEW_VERSION\n\n    build_packages $NEW_VERSION\n\n    done_banner $NEW_VERSION \"v$NEW_VERSION release-$NEW_VERSION\" yes\n    ;;\n\n  # ======================================================================================\n  security:release-* )\n    echo \"Security release.\"\n    OLD_VERSION=$(get_release_version)\n\n    if [[ $OLD_VERSION == *-rc* ]]; then\n      echo \"Security releases don't have candidates.\" >&2\n      exit 1\n    fi\n\n    declare -a VERSION_ARR=(${OLD_VERSION//./ } 0)\n    NEW_VERSION=${VERSION_ARR[0]}.${VERSION_ARR[1]}.${VERSION_ARR[2]}.$((VERSION_ARR[3] + 1))\n\n    echo \"Version: $NEW_VERSION\"\n\n    echo \"=========================================================================\"\n    echo \"Updating version number to $NEW_VERSION...\"\n    echo \"=========================================================================\"\n\n    doit sed -i -re \"s/capnproto-c[+][+]-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-c++-$NEW_VERSION/g\" doc/install.md\n    doit sed -i -re \"s/capnproto-c[+][+]-win32-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-c++-win32-$NEW_VERSION/g\" doc/install.md\n    doit sed -i -re \"s/capnproto-tools-win32-[0-9]+[.][0-9]+[.][0-9]+([.][0-9]+)?\\>/capnproto-tools-win32-$NEW_VERSION/g\" doc/install.md\n    update_version $OLD_VERSION $NEW_VERSION \"release branch\"\n\n    cherry_pick \"$@\"\n\n    doit git tag v$NEW_VERSION\n\n    build_packages $NEW_VERSION\n\n    done_banner $NEW_VERSION \"v$NEW_VERSION release-$NEW_VERSION\" yes\n    ;;\n\n  # ======================================================================================\n  retry:release-* )\n    echo \"Retrying release.\"\n    OLD_VERSION=$(get_release_version)\n    echo \"Version: $OLD_VERSION\"\n\n    if [[ $OLD_VERSION == *-rc* ]]; then\n      # We can add more cherry-picks when retrying a candidate.\n      cherry_pick \"$@\"\n    else\n      if [ $# -gt 1 ]; then\n        echo \"Cannot cherry-pick into final release.  Make another candidate.\" >&2\n        exit 1\n      fi\n    fi\n\n    OLD_VERSION=$(get_release_version)\n    build_packages $OLD_VERSION\n\n    if [[ $OLD_VERSION == *-rc* ]]; then\n      BRANCH_VERSION=${OLD_VERSION%%-rc*}\n      done_banner $OLD_VERSION release-$BRANCH_VERSION no\n    else\n      doit git tag v$OLD_VERSION\n      done_banner $OLD_VERSION \"v$OLD_VERSION release-$OLD_VERSION\" no\n    fi\n    ;;\n\n  # ======================================================================================\n  package:* )\n    echo \"Just building a package.\"\n    build_packages $(get_version '.*')\n    ;;\n\n  # ======================================================================================\n  *:master )\n    echo \"Invalid command for mainline branch.  Only command is 'candidate'.\" >&2\n    exit 1\n    ;;\n\n  *:release-* )\n    echo \"Invalid command for release branch.  Commands are 'candidate', 'final', and 'retry'.\" >&2\n    exit 1\n    ;;\n\n  * )\n    echo \"Not a master or release branch.\" >&2\n    exit 1\n    ;;\nesac\n", "num_lines": 346}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -euo pipefail\n\ndoit() {\n  echo \"@@@@ $@\"\n  \"$@\"\n}\n\nQUICK=\n\nPARALLEL=$(nproc 2>/dev/null || echo 1)\n\nwhile [ $# -gt 0 ]; do\n  case \"$1\" in\n    -j* )\n      PARALLEL=${1#-j}\n      ;;\n    test )\n      ;;  # nothing\n    quick )\n      QUICK=quick\n      ;;\n    caffeinate )\n      # Re-run preventing sleep.\n      shift\n      exec caffeinate -ims $0 $@\n      ;;\n    tmpdir )\n      # Clone to a temp directory.\n      if [ \"$#\" -lt 2 ]; then\n        echo \"usage: $0 tmpdir NAME [COMMAND]\" >&2\n        exit 1\n      fi\n      DIR=/tmp/$2\n      shift 2\n      if [ -e $DIR ]; then\n        if [ \"${DIR/*..*}\" = \"\" ]; then\n          echo \"NO DO NOT PUT .. IN THERE IT'S GOING TO GO IN /tmp AND I'M GONNA DELETE IT\" >&2\n          exit 1\n        fi\n        if [ ! -e \"$DIR/super-test.sh\" ]; then\n          echo \"$DIR exists and it doesn't look like one of mine.\" >&2\n          exit 1\n        fi\n        # make distcheck leaves non-writable files when it fails, so we need to chmod to be safe.\n        chmod -R +w $DIR\n        rm -rf $DIR\n      fi\n      git clone . $DIR\n      cd $DIR\n      exec ./super-test.sh \"$@\"\n      ;;\n    remote )\n      if [ \"$#\" -lt 2 ]; then\n        echo \"usage: $0 remote HOST [COMMAND]\" >&2\n        exit 1\n      fi\n      HOST=$2\n      shift 2\n      echo \"=========================================================================\"\n      echo \"Pushing code to $HOST...\"\n      echo \"=========================================================================\"\n      BRANCH=$(git rev-parse --abbrev-ref HEAD)\n      ssh $HOST '(chmod -fR +w tmp-test-capnp || true) && rm -rf tmp-test-capnp && mkdir tmp-test-capnp && git init tmp-test-capnp'\n      git push ssh://$HOST/~/tmp-test-capnp \"$BRANCH:test\"\n      ssh $HOST \"cd tmp-test-capnp && git checkout test\"\n      exec ssh $HOST \"cd tmp-test-capnp && ./super-test.sh $@ && cd .. && rm -rf tmp-test-capnp\"\n      ;;\n    compiler )\n      if [ \"$#\" -lt 2 ]; then\n        echo \"usage: $0 compiler CXX_NAME\" >&2\n        exit 1\n      fi\n      export CXX=\"$2\"\n      shift\n      ;;\n    clang )\n      export CXX=clang++\n      ;;\n    gcc-4.9 )\n      export CXX=g++-4.9\n      ;;\n    gcc-4.8 )\n      export CXX=g++-4.8\n      ;;\n    gcc-4.7 )\n      export CXX=g++-4.7\n      ;;\n    mingw )\n      if [ \"$#\" -ne 2 ]; then\n        echo \"usage: $0 mingw CROSS_HOST\" >&2\n        exit 1\n      fi\n      CROSS_HOST=$2\n\n      cd c++\n      test -e configure || doit autoreconf -i\n      test ! -e Makefile || (echo \"ERROR: Directory unclean!\" >&2 && false)\n\n      export WINEPATH='Z:\\usr\\'\"$CROSS_HOST\"'\\lib;Z:\\usr\\lib\\gcc\\'\"$CROSS_HOST\"'\\6.3-win32;Z:'\"$PWD\"'\\.libs'\n\n      doit ./configure --host=\"$CROSS_HOST\" --disable-shared CXXFLAGS='-static-libgcc -static-libstdc++'\n\n      doit make -j$PARALLEL check\n      doit make distclean\n      rm -f *-mingw.exe\n      exit 0\n      ;;\n    android )\n      # To install Android SDK:\n      # - Download command-line tools: https://developer.android.com/studio/index.html#command-tools\n      # - Run $SDK_HOME/tools/bin/sdkmanager platform-tools 'platforms;android-25' 'system-images;android-25;google_apis;armeabi-v7a' emulator 'build-tools;25.0.2' ndk-bundle\n      # - Run $SDK_HOME/tools/bin/avdmanager create avd -n capnp -k 'system-images;android-25;google_apis;armeabi-v7a' -b google_apis/armeabi-v7a\n      # - Run $SDK_HOME/ndk-bundle/build/tools/make_standalone_toolchain.py --arch arm --api 24 --install-dir $TOOLCHAIN_HOME\n      if [ \"$#\" -ne 4 ]; then\n        echo \"usage: $0 android SDK_HOME TOOLCHAIN_HOME CROSS_HOST\" >&2\n        exit 1\n      fi\n      SDK_HOME=$2\n      TOOLCHAIN_HOME=$3\n      CROSS_HOST=$4\n\n      cd c++\n      test -e configure || doit autoreconf -i\n      test ! -e Makefile || (echo \"ERROR: Directory unclean!\" >&2 && false)\n      doit ./configure --disable-shared\n      doit make -j$PARALLEL capnp capnpc-c++\n\n      cp capnp capnp-host\n      cp capnpc-c++ capnpc-c++-host\n\n      export PATH=\"$TOOLCHAIN_HOME/bin:$PATH\"\n      doit make distclean\n      doit ./configure --host=\"$CROSS_HOST\" --with-external-capnp --disable-shared CXXFLAGS='-pie -fPIE' CAPNP=./capnp-host CAPNPC_CXX=./capnpc-c++-host\n\n      doit make -j$PARALLEL\n      doit make -j$PARALLEL capnp-test\n\n      echo \"Starting emulator...\"\n      trap 'kill $(jobs -p)' EXIT\n      # TODO(someday): Speed up with KVM? Then maybe we won't have to skip fuzz tests?\n      $SDK_HOME/emulator/emulator -avd capnp -no-window &\n      $SDK_HOME/platform-tools/adb 'wait-for-device'\n      echo \"Waiting for localhost to be resolvable...\"\n      doit $SDK_HOME/platform-tools/adb shell 'while ! ping -c 1 localhost > /dev/null 2>&1; do sleep 1; done'\n      # TODO(cleanup): With 'adb shell' I find I cannot put files anywhere, so I'm using 'su' a\n      #   lot here. There is probably a better way.\n      doit $SDK_HOME/platform-tools/adb shell 'su 0 tee /data/capnp-test > /dev/null' < capnp-test\n      doit $SDK_HOME/platform-tools/adb shell 'su 0 chmod a+rx /data/capnp-test'\n      doit $SDK_HOME/platform-tools/adb shell 'cd /data && CAPNP_SKIP_FUZZ_TEST=1 su 0 /data/capnp-test && echo ANDROID_\"\"TESTS_PASSED' | tee android-test.log\n      grep -q ANDROID_TESTS_PASSED android-test.log\n\n      doit make distclean\n      rm -f capnp-host capnpc-c++-host\n      exit 0\n      ;;\n    cmake )\n      cd c++\n      rm -rf cmake-build\n      mkdir cmake-build\n      cd cmake-build\n      doit cmake -G \"Unix Makefiles\" ..\n      doit make -j$PARALLEL check\n      exit 0\n      ;;\n    exotic )\n      echo \"=========================================================================\"\n      echo \"MinGW 64-bit\"\n      echo \"=========================================================================\"\n      \"$0\" mingw x86_64-w64-mingw32\n      echo \"=========================================================================\"\n      echo \"MinGW 32-bit\"\n      echo \"=========================================================================\"\n      \"$0\" mingw i686-w64-mingw32\n      echo \"=========================================================================\"\n      echo \"Android\"\n      echo \"=========================================================================\"\n      \"$0\" android /home/kenton/android-sdk-linux /home/kenton/android-24 arm-linux-androideabi\n      echo \"=========================================================================\"\n      echo \"CMake\"\n      echo \"=========================================================================\"\n      \"$0\" cmake\n      exit 0\n      ;;\n    clean )\n      rm -rf tmp-staging\n      cd c++\n      if [ -e Makefile ]; then\n        doit make maintainer-clean\n      fi\n      rm -f capnproto-*.tar.gz samples/addressbook samples/addressbook.capnp.c++ \\\n            samples/addressbook.capnp.h\n      exit 0\n      ;;\n    help )\n      echo \"usage: $0 [COMMAND]\"\n      echo \"commands:\"\n      echo \"  test          Runs tests (the default).\"\n      echo \"  clang         Runs tests using Clang compiler.\"\n      echo \"  gcc-4.7       Runs tests using gcc-4.7.\"\n      echo \"  gcc-4.8       Runs tests using gcc-4.8.\"\n      echo \"  gcc-4.9       Runs tests using gcc-4.9.\"\n      echo \"  remote HOST   Runs tests on HOST via SSH.\"\n      echo \"  mingw         Cross-compiles to MinGW and runs tests using WINE.\"\n      echo \"  android       Cross-compiles to Android and runs tests using emulator.\"\n      echo \"  clean         Delete temporary files that may be left after failure.\"\n      echo \"  help          Prints this help text.\"\n      exit 0\n      ;;\n    * )\n      echo \"unknown command: $1\" >&2\n      echo \"try: $0 help\" >&2\n      exit 1\n      ;;\n  esac\n  shift\ndone\n\n# Build optimized builds because they catch more problems, but also enable debugging macros.\n# Enable lots of warnings and make sure the build breaks if they fire.  Disable strict-aliasing\n# because GCC warns about code that I know is OK.  Disable sign-compare because I've fixed more\n# sign-compare warnings than probably all other warnings combined and I've never seen it flag a\n# real problem. Disable unused parameters because it's stupidly noisy and never a real problem.\n# Enable expensive release-gating tests.\nexport CXXFLAGS=\"-O2 -DDEBUG -Wall -Wextra -Werror -Wno-strict-aliasing -Wno-sign-compare -Wno-unused-parameter -DCAPNP_EXPENSIVE_TESTS=1\"\n\nSTAGING=$PWD/tmp-staging\n\nrm -rf \"$STAGING\"\nmkdir \"$STAGING\"\nmkdir \"$STAGING/bin\"\nmkdir \"$STAGING/lib\"\nexport PATH=$STAGING/bin:$PATH\nexport LD_LIBRARY_PATH=$STAGING/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}\nexport PKG_CONFIG_PATH=$STAGING/lib/pkgconfig\n\nif [ \"$QUICK\" = quick ]; then\n  echo \"************************** QUICK TEST ***********************************\"\nfi\n\necho \"=========================================================================\"\necho \"Building c++\"\necho \"=========================================================================\"\n\n# Apple now aliases gcc to clang, so probe to find out what compiler we're really using.\nif (${CXX:-g++} -dM -E -x c++ /dev/null 2>&1 | grep -q '__clang__'); then\n  IS_CLANG=yes\n  DISABLE_OPTIMIZATION_IF_GCC=\nelse\n  IS_CLANG=no\n  DISABLE_OPTIMIZATION_IF_GCC=-O0\nfi\n\nif [ $IS_CLANG = yes ]; then\n  # Don't fail out on this ridiculous \"argument unused during compilation\" warning.\n  export CXXFLAGS=\"$CXXFLAGS -Wno-error=unused-command-line-argument\"\nelse\n  # GCC emits uninitialized warnings all over and they seem bogus. We use valgrind to test for\n  # uninitialized memory usage later on. GCC 4 also emits strange bogus warnings with\n  # -Wstrict-overflow, so we disable it.\n  CXXFLAGS=\"$CXXFLAGS -Wno-maybe-uninitialized -Wno-strict-overflow\"\nfi\n\ncd c++\ndoit autoreconf -i\ndoit ./configure --prefix=\"$STAGING\"\ndoit make -j$PARALLEL check\n\nif [ $IS_CLANG = no ]; then\n  # Verify that generated code compiles with pedantic warnings.  Make sure to treat capnp headers\n  # as system headers so warnings in them are ignored.\n  doit ${CXX:-g++} -isystem src -std=c++11 -fno-permissive -pedantic -Wall -Wextra -Werror \\\n      -c src/capnp/test.capnp.c++ -o /dev/null\nfi\n\necho \"=========================================================================\"\necho \"Testing c++ install\"\necho \"=========================================================================\"\n\ndoit make install\n\ntest \"x$(which capnp)\" = \"x$STAGING/bin/capnp\"\ntest \"x$(which capnpc-c++)\" = \"x$STAGING/bin/capnpc-c++\"\n\ncd samples\n\ndoit capnp compile -oc++ addressbook.capnp -I\"$STAGING\"/include --no-standard-import\ndoit ${CXX:-g++} -std=c++11 addressbook.c++ addressbook.capnp.c++ -o addressbook \\\n    $CXXFLAGS $(pkg-config --cflags --libs capnp)\necho \"@@@@ ./addressbook (in various configurations)\"\n./addressbook write | ./addressbook read\n./addressbook dwrite | ./addressbook dread\nrm addressbook addressbook.capnp.c++ addressbook.capnp.h\n\ndoit capnp compile -oc++ calculator.capnp -I\"$STAGING\"/include --no-standard-import\ndoit ${CXX:-g++} -std=c++11 calculator-client.c++ calculator.capnp.c++ -o calculator-client \\\n    $CXXFLAGS $(pkg-config --cflags --libs capnp-rpc)\ndoit ${CXX:-g++} -std=c++11 calculator-server.c++ calculator.capnp.c++ -o calculator-server \\\n    $CXXFLAGS $(pkg-config --cflags --libs capnp-rpc)\nrm -f /tmp/capnp-calculator-example-$$\n./calculator-server unix:/tmp/capnp-calculator-example-$$ &\nsleep 0.1\n./calculator-client unix:/tmp/capnp-calculator-example-$$\nkill %+\nwait %+ || true\nrm calculator-client calculator-server calculator.capnp.c++ calculator.capnp.h /tmp/capnp-calculator-example-$$\n\ncd ..\n\nif [ \"$QUICK\" = quick ]; then\n  doit make maintainer-clean\n  rm -rf \"$STAGING\"\n  exit 0\nfi\n\necho \"=========================================================================\"\necho \"Testing --with-external-capnp\"\necho \"=========================================================================\"\n\ndoit make distclean\ndoit ./configure --prefix=\"$STAGING\" --disable-shared \\\n    --with-external-capnp CAPNP=$STAGING/bin/capnp\ndoit make -j$PARALLEL check\n\necho \"=========================================================================\"\necho \"Testing --disable-reflection\"\necho \"=========================================================================\"\n\ndoit make distclean\ndoit ./configure --prefix=\"$STAGING\" --disable-shared --disable-reflection \\\n    --with-external-capnp CAPNP=$STAGING/bin/capnp\ndoit make -j$PARALLEL check\ndoit make distclean\n\n# Test 32-bit build now while we have $STAGING available for cross-compiling.\nif [ \"x`uname -m`\" = \"xx86_64\" ]; then\n  echo \"=========================================================================\"\n  echo \"Testing 32-bit build\"\n  echo \"=========================================================================\"\n\n  if [[ \"`uname`\" =~ CYGWIN ]]; then\n    # It's just not possible to run cygwin32 binaries from within cygwin64.\n\n    # Build as if we are cross-compiling, using the capnp we installed to $STAGING.\n    doit ./configure --prefix=\"$STAGING\" --disable-shared --host=i686-pc-cygwin \\\n        --with-external-capnp CAPNP=$STAGING/bin/capnp\n    doit make -j$PARALLEL\n    doit make -j$PARALLEL capnp-test.exe\n\n    # Expect a cygwin32 sshd to be listening at localhost port 2222, and use it\n    # to run the tests.\n    doit scp -P 2222 capnp-test.exe localhost:~/tmp-capnp-test.exe\n    doit ssh -p 2222 localhost './tmp-capnp-test.exe && rm tmp-capnp-test.exe'\n\n    doit make distclean\n\n  elif [ \"x${CXX:-g++}\" != \"xg++-4.8\" ]; then\n    doit ./configure CXX=\"${CXX:-g++} -m32\" --disable-shared\n    doit make -j$PARALLEL check\n    doit make distclean\n  fi\nfi\n\necho \"=========================================================================\"\necho \"Testing c++ uninstall\"\necho \"=========================================================================\"\n\ndoit ./configure --prefix=\"$STAGING\"\ndoit make uninstall\n\necho \"=========================================================================\"\necho \"Testing c++ dist\"\necho \"=========================================================================\"\n\ndoit make -j$PARALLEL distcheck\ndoit make distclean\nrm capnproto-*.tar.gz\n\nif [ \"x`uname`\" = xLinux ]; then\n  echo \"=========================================================================\"\n  echo \"Testing generic Unix (no Linux-specific features)\"\n  echo \"=========================================================================\"\n\n  doit ./configure --disable-shared CXXFLAGS=\"$CXXFLAGS -DKJ_USE_FUTEX=0 -DKJ_USE_EPOLL=0\"\n  doit make -j$PARALLEL check\n  doit make distclean\nfi\n\necho \"=========================================================================\"\necho \"Testing with -fno-rtti and -fno-exceptions\"\necho \"=========================================================================\"\n\n# GCC miscompiles capnpc-c++ when -fno-exceptions and -O2 are specified together. The\n# miscompilation happens in one specific inlined call site of Array::dispose(), but this method\n# is inlined in hundreds of other places without issue, so I have no idea how to narrow down the\n# bug. Clang works fine. So, for now, we disable optimizations on GCC for -fno-exceptions tests.\n\ndoit ./configure --disable-shared CXXFLAGS=\"$CXXFLAGS -fno-rtti\"\ndoit make -j$PARALLEL check\ndoit make distclean\ndoit ./configure --disable-shared CXXFLAGS=\"$CXXFLAGS -fno-exceptions $DISABLE_OPTIMIZATION_IF_GCC\"\ndoit make -j$PARALLEL check\ndoit make distclean\ndoit ./configure --disable-shared CXXFLAGS=\"$CXXFLAGS -fno-rtti -fno-exceptions $DISABLE_OPTIMIZATION_IF_GCC\"\ndoit make -j$PARALLEL check\n\n# Valgrind is currently \"experimental and mostly broken\" on OSX and fails to run the full test\n# suite, but I have it installed because it did manage to help me track down a bug or two.  Anyway,\n# skip it on OSX for now.\nif [ \"x`uname`\" != xDarwin ] && which valgrind > /dev/null; then\n  doit make distclean\n\n  echo \"=========================================================================\"\n  echo \"Testing with valgrind\"\n  echo \"=========================================================================\"\n\n  doit ./configure --disable-shared CXXFLAGS=\"-g\"\n  doit make -j$PARALLEL\n  doit make -j$PARALLEL capnp-test\n  # Running the fuzz tests under Valgrind is a great thing to do -- but it takes\n  # some 40 minutes. So, it needs to be done as a separate step of the release\n  # process, perhaps along with the AFL tests.\n  CAPNP_SKIP_FUZZ_TEST=1 doit valgrind --leak-check=full --track-fds=yes --error-exitcode=1 ./capnp-test\nfi\n\ndoit make maintainer-clean\n\nrm -rf \"$STAGING\"\n", "num_lines": 430}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/bash\n\nset -euo pipefail\n\necho \"Choose test case:\"\necho \"1) TestAllTypes parsing\"\necho \"2) TestLists parsing\"\necho \"3) Canonicalization\"\n\nread -p \"choice: \" -n 1 TESTCASE\necho\n\ncase \"$TESTCASE\" in\n  1 )\n    TESTDATA=binary\n    FLAGS=\n    TESTNAME=default\n    ;;\n  2 )\n    TESTDATA=lists.binary\n    FLAGS=--lists\n    TESTNAME=lists\n    ;;\n  3 )\n    TESTDATA=binary\n    FLAGS=--canonicalize\n    TESTNAME=canonicalize\n    ;;\n  * )\n    echo \"Invalid choice: $TESTCASE\" >&2\n    exit 1\nesac\n\necho \"Choose compiler:\"\necho \"1) GCC\"\necho \"2) Clang\"\n\nread -p \"choice: \" -n 1 TESTCASE\necho\n\ncase \"$TESTCASE\" in\n  1 )\n    export CXX=afl-g++\n    ;;\n  2 )\n    export CXX=afl-clang++\n    ;;\n  * )\n    echo \"Invalid choice: $TESTCASE\" >&2\n    exit 1\nesac\n\nif [ -e Makefile ]; then\n  if ! grep -q '^CXX *= *'\"$CXX\" Makefile; then\n    # Wrong compiler used.\n    make distclean\n    $(dirname $0)/configure --disable-shared\n  fi\nelse\n  $(dirname $0)/configure --disable-shared\nfi\n\nmake -j$(nproc)\nmake -j$(nproc) capnp-afl-testcase\n\nNOW=$(date +%Y-%m-%d.%H-%M-%S).$TESTNAME.$CXX\n\nmkdir afl.$NOW.inputs afl.$NOW.findings\n\ncp $(dirname $0)/src/capnp/testdata/$TESTDATA afl.$NOW.inputs\n\nafl-fuzz -i afl.$NOW.inputs -o afl.$NOW.findings -- ./capnp-afl-testcase $FLAGS\n", "num_lines": 73}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -euo pipefail\n\nexport PATH=$PWD/bin:$PWD:$PATH\n\ncapnp compile -Isrc --no-standard-import --src-prefix=src -oc++:src \\\n    src/capnp/c++.capnp src/capnp/schema.capnp \\\n    src/capnp/compiler/lexer.capnp src/capnp/compiler/grammar.capnp \\\n    src/capnp/rpc.capnp src/capnp/rpc-twoparty.capnp src/capnp/persistent.capnp \\\n    src/capnp/compat/json.capnp\n", "num_lines": 12}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -euo pipefail\n\necho \"This script is no longer needed. Go ahead and run autoreconf. For example:\"\necho \"  autoreconf -i && ./configure && make -j6 check && sudo make install\"\n", "num_lines": 7}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -euo pipefail\n\nif ! uname | grep -iq Linux; then\n  echo \"Sorry, Ekam only works on Linux right now.\" >&2\n  exit 1\nfi\n\necho -n \"Looking for compiler... \"\nif [ \"x${CXX:-}\" == \"x\" ]; then\n  if ! (g++ --version | grep -q ' 4[.][789][.]'); then\n    if which g++-4.7 > /dev/null; then\n      CXX=g++-4.7\n    elif which g++-4.8 > /dev/null; then\n      CXX=g++-4.8\n    else\n      echo \"none\"\n      echo \"Please install G++ 4.7 or better.  Or, set the environment variable CXX \" >&2\n      echo \"to a compiler that you think will work.\" >&2\n      exit 1\n    fi\n  else\n    CXX=g++\n  fi\nfi\n\necho \"$CXX\"\nexport CXX\n\nif [ ! -e .ekam ]; then\n  echo \"================================================================================\"\n  echo \"Fetching Ekam and Protobuf code...\"\n  echo \"================================================================================\"\n  hg clone https://code.google.com/p/kentons-code/ .ekam\n\n  # You don't want these.\n  rm -rf .ekam/src/modc .ekam/src/evlan\nfi\n\nif [ ! -e .ekam/src/protobuf ]; then\n  echo \"================================================================================\"\n  echo \"Fetching Protobuf code...\"\n  echo \"================================================================================\"\n  svn checkout http://protobuf.googlecode.com/svn/tags/2.5.0/ .ekam/src/protobuf\nfi\n\nif [ ! -e .ekam/src/protobuf/src/config.h ]; then\n  echo \"================================================================================\"\n  echo \"Configuring Protobuf...\"\n  echo \"================================================================================\"\n  pushd .ekam/src/protobuf > /dev/null\n  ./autogen.sh\n  ./configure\n  cp config.h src\n  make maintainer-clean\n  popd\nfi\n\nif ! which ekam > /dev/null; then\n  if [ ! -e .ekam/bin/ekam ]; then\n    echo \"================================================================================\"\n    echo \"Bootstrapping Ekam...\"\n    echo \"================================================================================\"\n    pushd .ekam > /dev/null\n    ./bootstrap.sh\n    popd\n  fi\nelse\n  echo \"================================================================================\"\n  echo \"Using already-installed ekam binary: $(which ekam)\"\n  echo \"================================================================================\"\nfi\n\nif [ ! -e src/base ]; then\n  ln -s ../.ekam/src/base src/base\nfi\nif [ ! -e src/os ]; then\n  ln -s ../.ekam/src/os src/os\nfi\nif [ ! -e src/ekam ]; then\n  ln -s ../.ekam/src/ekam src/ekam\nfi\nif [ ! -e src/protobuf ]; then\n  ln -s ../.ekam/src/protobuf src/protobuf\nfi\n\necho \"================================================================================\"\necho \"All done...\"\necho \"================================================================================\"\necho \"Try:\"\necho \"  make -f Makefile.ekam once\"\necho \"  make -f Makefile.ekam continuous\"\necho \"  make -f Makefile.ekam continuous-opt\"\n", "num_lines": 95}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n#\n# Quick script that compiles and runs the samples, then cleans up.\n# Used for release testing.\n\nset -exuo pipefail\n\ncapnpc -oc++ addressbook.capnp\nc++ -std=c++11 -Wall addressbook.c++ addressbook.capnp.c++ \\\n    $(pkg-config --cflags --libs capnp) -o addressbook\n./addressbook write | ./addressbook read\n./addressbook dwrite | ./addressbook dread\nrm addressbook addressbook.capnp.c++ addressbook.capnp.h\n\ncapnpc -oc++ calculator.capnp\nc++ -std=c++11 -Wall calculator-client.c++ calculator.capnp.c++ \\\n    $(pkg-config --cflags --libs capnp-rpc) -o calculator-client\nc++ -std=c++11 -Wall calculator-server.c++ calculator.capnp.c++ \\\n    $(pkg-config --cflags --libs capnp-rpc) -o calculator-server\nrm -f /tmp/capnp-calculator-example-$$\n./calculator-server unix:/tmp/capnp-calculator-example-$$ &\nsleep 0.1\n./calculator-client unix:/tmp/capnp-calculator-example-$$\nkill %+\nwait %+ || true\nrm calculator-client calculator-server calculator.capnp.c++ calculator.capnp.h /tmp/capnp-calculator-example-$$\n", "num_lines": 27}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /bin/sh\n# Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors\n# Licensed under the MIT License:\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n# Tests the `capnp` tool's various commands, other than `compile`.\n\nset -eu\n\nfail() {\n  echo \"FAILED: $@\" >&2\n  exit 1\n}\n\nif test -f ./capnp; then\n  CAPNP=${CAPNP:-./capnp}\nelif test -f ./capnp.exe; then\n  CAPNP=${CAPNP:-./capnp.exe}\nelse\n  CAPNP=${CAPNP:-capnp}\nfi\n\nSCHEMA=`dirname \"$0\"`/../test.capnp\nTESTDATA=`dirname \"$0\"`/../testdata\n\n$CAPNP encode $SCHEMA TestAllTypes < $TESTDATA/short.txt | cmp $TESTDATA/binary - || fail encode\n$CAPNP encode --flat $SCHEMA TestAllTypes < $TESTDATA/short.txt | cmp $TESTDATA/flat - || fail encode flat\n$CAPNP encode --packed $SCHEMA TestAllTypes < $TESTDATA/short.txt | cmp $TESTDATA/packed - || fail encode packed\n$CAPNP encode --packed --flat $SCHEMA TestAllTypes < $TESTDATA/short.txt | cmp $TESTDATA/packedflat - || fail encode packedflat\n$CAPNP encode $SCHEMA TestAllTypes < $TESTDATA/pretty.txt | cmp $TESTDATA/binary - || fail parse pretty\n\n$CAPNP decode $SCHEMA TestAllTypes < $TESTDATA/binary | cmp $TESTDATA/pretty.txt - || fail decode\n$CAPNP decode --flat $SCHEMA TestAllTypes < $TESTDATA/flat | cmp $TESTDATA/pretty.txt - || fail decode flat\n$CAPNP decode --packed $SCHEMA TestAllTypes < $TESTDATA/packed | cmp $TESTDATA/pretty.txt - || fail decode packed\n$CAPNP decode --packed --flat $SCHEMA TestAllTypes < $TESTDATA/packedflat | cmp $TESTDATA/pretty.txt - || fail decode packedflat\n$CAPNP decode --short $SCHEMA TestAllTypes < $TESTDATA/binary | cmp $TESTDATA/short.txt - || fail decode short\n\n$CAPNP decode $SCHEMA TestAllTypes < $TESTDATA/segmented | cmp $TESTDATA/pretty.txt - || fail decode segmented\n$CAPNP decode --packed $SCHEMA TestAllTypes < $TESTDATA/segmented-packed | cmp $TESTDATA/pretty.txt - || fail decode segmented-packed\n\ntest_eval() {\n  test \"x`$CAPNP eval $SCHEMA $1 | tr -d '\\r'`\" = \"x$2\" || fail eval \"$1 == $2\"\n}\n\ntest_eval TestDefaults.uInt32Field 3456789012\ntest_eval TestDefaults.structField.textField '\"baz\"'\ntest_eval TestDefaults.int8List \"[111, -111]\"\ntest_eval 'TestDefaults.structList[1].textField' '\"structlist 2\"'\ntest_eval globalPrintableStruct '(someText = \"foo\")'\ntest_eval TestConstants.enumConst corge\ntest_eval 'TestListDefaults.lists.int32ListList[2][0]' 12341234\n\n$CAPNP compile -ofoo $TESTDATA/errors.capnp.nobuild 2>&1 | sed -e \"s,^.*/errors[.]capnp[.]nobuild,file,g\" | tr -d '\\r' |\n    cmp $TESTDATA/errors.txt - || fail error output\n", "num_lines": 72}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\nset -eu\nshopt -s extglob\n\nif grep 'localhost:4000' *.md _posts/*.md; then\n  echo \"ERROR: Your content has links to localhost:4000!\" >&2\n  exit 1\nfi\n\nif [ \"x$(git status --porcelain)\" != \"x\" ]; then\n  echo -n \"git repo has uncommited changes.  Continue anyway? (y/N) \" >&2\n  read -n 1 YESNO\n  echo >&2\n  if [ \"x$YESNO\" != xy ]; then\n    exit 1\n  fi\nfi\n\ncase $(git rev-parse --abbrev-ref HEAD) in\n  master )\n    echo \"On master branch.  Will generate to /next.\"\n    CONFIG=_config_next.yml\n    PREFIX=/next\n    LABEL=\"preview site\"\n    FUTURE=--future\n    ;;\n\n  release-* )\n    echo \"On release branch.  Will generate to /.\"\n    CONFIG=_config.yml\n    PREFIX=\n    LABEL=\"site\"\n    FUTURE=\n    ;;\n\n  * )\n    echo \"Unrecognized branch.\" >&2\n    exit 1\n    ;;\nesac\n\necho \"Regenerating site...\"\n\nrm -rf _site _site.tar.gz\n\njekyll build --safe $FUTURE --config $CONFIG\n\necho -n \"Push now? (y/N)\"\nread -n 1 YESNO\necho\n\nif [ \"x$YESNO\" == \"xy\" ]; then\n  echo \"Pushing...\"\n  tar cz --xform='s,_site/,,' _site/* | gce-ss ssh fe --command \"cd /var/www/capnproto.org$PREFIX && tar xz\"\nelse\n  echo \"Push CANCELED\"\nfi\n", "num_lines": 59}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env sh\nset -evx\nenv | sort\n\nmkdir build || true\nmkdir build/$GTEST_TARGET || true\ncd build/$GTEST_TARGET\ncmake -Dgtest_build_samples=ON \\\n      -Dgmock_build_samples=ON \\\n      -Dgtest_build_tests=ON \\\n      -Dgmock_build_tests=ON \\\n      -DCMAKE_CXX_FLAGS=$CXX_FLAGS \\\n      ../../$GTEST_TARGET\nmake\nCTEST_OUTPUT_ON_FAILURE=1 make test\n", "num_lines": 16}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Executes the samples and tests for the Google Test Framework.\n\n# Help the dynamic linker find the path to the libraries.\nexport DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR\nexport DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR\n\n# Create some executables.\ntest_executables=$@\n\n# Now execute each one in turn keeping track of how many succeeded and failed.\nsucceeded=0\nfailed=0\nfailed_list=()\nfor test in ${test_executables[*]}; do\n  \"$test\"\n  result=$?\n  if [ $result -eq 0 ]; then\n    succeeded=$(( $succeeded + 1 ))\n  else\n    failed=$(( failed + 1 ))\n    failed_list=\"$failed_list $test\"\n  fi\ndone\n\n# Report the successes and failures to the console.\necho \"Tests complete with $succeeded successes and $failed failures.\"\nif [ $failed -ne 0 ]; then\n  echo \"The following tests failed:\"\n  echo $failed_list\nfi\nexit $failed\n", "num_lines": 63}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Executes the samples and tests for the Google Test Framework.\n\n# Help the dynamic linker find the path to the libraries.\nexport DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR\nexport DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR\n\n# Create some executables.\ntest_executables=(\"$BUILT_PRODUCTS_DIR/gtest_unittest-framework\"\n                  \"$BUILT_PRODUCTS_DIR/gtest_unittest\"\n                  \"$BUILT_PRODUCTS_DIR/sample1_unittest-framework\"\n                  \"$BUILT_PRODUCTS_DIR/sample1_unittest-static\")\n\n# Now execute each one in turn keeping track of how many succeeded and failed. \nsucceeded=0\nfailed=0\nfailed_list=()\nfor test in ${test_executables[*]}; do\n  \"$test\"\n  result=$?\n  if [ $result -eq 0 ]; then\n    succeeded=$(( $succeeded + 1 ))\n  else\n    failed=$(( failed + 1 ))\n    failed_list=\"$failed_list $test\"\n  fi\ndone\n\n# Report the successes and failures to the console.\necho \"Tests complete with $succeeded successes and $failed failures.\"\nif [ $failed -ne 0 ]; then\n  echo \"The following tests failed:\"\n  echo $failed_list\nfi\nexit $failed\n", "num_lines": 66}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  make_zipconf.sh: create platform specific include file zipconf.h\n#  Copyright (C) 1999-2011 Dieter Baron and Thomas Klausner\n#\n#  This file is part of libzip, a library to manipulate ZIP archives.\n#  The authors can be contacted at <libzip@nih.at>\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions\n#  are met:\n#  1. Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#  2. Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in\n#     the documentation and/or other materials provided with the\n#     distribution.\n#  3. The names of the authors may not be used to endorse or promote\n#     products derived from this software without specific prior\n#     written permission.\n# \n#  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS\n#  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY\n#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n#  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n#  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n#  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nset -e\n\ndefine_type()\n{\n    short=$1\n    long=$2\n    bytes=$3\n    infile=\"$4\"\n    outfile=\"$5\"\n\n    bits=`expr $bytes '*' 8`\n    type=\"${short}int${bits}\"\n    TYPE=`echo $type | tr '[a-z]' '[A-Z]'`\n    if grep \"define HAVE_${TYPE}_T\" \"$infile\" > /dev/null\n    then\n\techo \"typedef ${type}_t zip_${type}_t;\" >> \"$outfile\"\n\tLTYPE=\"$TYPE\"\n    else\n\tSHORT=`echo $short | tr '[a-z]' '[A-Z]'`\n\tif [ -z \"$SHORT\" ]\n\tthen\n\t    SHORT='S'\n\tfi\n\tif [ \"$bytes\" -eq 1 ]\n\tthen\n\t    if [ -z \"$long\" ]\n\t    then\n\t\tlong='signed'\n\t    fi\n\t    echo \"typedef $long char ${type}_t;\" >> $outfile\n\t    LTYPE=\"${SHORT}CHAR\"\n\telse\n\t    ctype=`sed -n \"s/.define SIZEOF_\\([A-Z_]*\\) $bytes/\\1/p\" \"$infile\" \\\n\t\t| head -1 | tr '[A-Z_]' '[a-z ]'`\n\t    if [ -z \"$ctype\" ]\n\t    then\n\t\techo \"$0: no $bits bit type found\" >&2\n\t\texit 1\n\t    fi\n\t    echo \"typedef $long $ctype ${type}_t;\" >> \"$outfile\"\n\t    case \"$ctype\" in\n\t\tshort) LTYPE=${SHORT}SHRT;;\n\t\tint) LTYPE=${SHORT}INT;;\n                long) LTYPE=${SHORT}LONG;;\n\t\t\"long long\") LTYPE=${SHORT}LLONG;;\n            esac\n\tfi\n    fi\n\n    if [ -z \"$long\" ]\n    then\n\techo \"#define ZIP_${TYPE}_MIN ${LTYPE}_MIN\" >> \"$outfile\"\n    fi\n    echo \"#define ZIP_${TYPE}_MAX ${LTYPE}_MAX\" >> \"$outfile\"\n    echo >> \"$outfile\"\n}\n\n\nif [ \"$#\" -ne 2 ]\nthen\n    echo \"Usage: $0 config_h_file out_file\" >&2\n    echo \"       e.g. $0 ../config.h zip_err_str.c\" >&2\n    exit 1\nfi\n\nif [ \"$1\" = \"$2\" ]\nthen\n    echo \"$0: error: output file = input file\" >&2\n    exit 1\nfi\n\ncat <<EOF > \"$2.$$\"\n#ifndef _HAD_ZIPCONF_H\n#define _HAD_ZIPCONF_H\n\n/*\n   zipconf.h -- platform specific include file\n\n   This file was generated automatically by $0\n   based on $1.\n */\n\nEOF\n\nversion=`sed -n 's/^#define VERSION \"\\(.*\\)\"/\\1/p' \"$1\"`\n\nversion_major=`expr \"$version\" : '^\\([0-9]*\\)' || true`\nversion_minor=`expr \"$version\" : '^[0-9]*\\.\\([0-9]*\\)' || true`\nversion_micro=`expr \"$version\" : '^[0-9]*\\.[0-9]\\.\\([0-9]*\\)' || true`\n\nif [ -z \"$version_major\" ]\nthen\n    version_major=0\nfi\nif [ -z \"$version_minor\" ]\nthen\n    version_minor=0\nfi\nif [ -z \"$version_micro\" ]\nthen\n    version_micro=0\nfi\n\ncat <<EOF >> \"$2.$$\"\n#define LIBZIP_VERSION \"$version\"\n#define LIBZIP_VERSION_MAJOR $version_major\n#define LIBZIP_VERSION_MINOR $version_minor\n#define LIBZIP_VERSION_MICRO $version_micro\n\nEOF\n\nif grep 'define HAVE_INTTYPES_H' \"$1\" > /dev/null\nthen\n    echo '#include <inttypes.h>' >> \"$2.$$\"\nelse\n    echo '#include <limits.h>' >> \"$2.$$\"\nfi\necho >> \"$2.$$\"\n\nfor size in 1 2 4 8\ndo\n    define_type '' '' $size \"$1\" \"$2.$$\"\n    define_type u unsigned $size \"$1\" \"$2.$$\"\ndone\n\necho >> \"$2.$$\"\necho '#endif /* zipconf.h */' >> \"$2.$$\"\n\nmv \"$2.$$\" \"$2\"\n", "num_lines": 164}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  make_zip_err_str.sh: create zip_err_str.c from zip.h\n#  Copyright (C) 1999-2014 Dieter Baron and Thomas Klausner\n#\n#  This file is part of libzip, a library to manipulate ZIP archives.\n#  The authors can be contacted at <libzip@nih.at>\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions\n#  are met:\n#  1. Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#  2. Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in\n#     the documentation and/or other materials provided with the\n#     distribution.\n#  3. The names of the authors may not be used to endorse or promote\n#     products derived from this software without specific prior\n#     written permission.\n# \n#  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS\n#  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY\n#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n#  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n#  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n#  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nif [ \"$#\" -ne 2 ]\nthen\n    echo \"Usage: $0 in_file out_file\" >&2\n    echo \"       e.g. $0 zip.h zip_err_str.c\" >&2\n    exit 1\nfi\n\nif [ \"$1\" = \"$2\" ]\nthen\n    echo \"$0: error: output file = input file\" >&2\n    exit 1\nfi\n\ncat <<EOF >> \"$2.$$\" || exit 1\n/*\n   This file was generated automatically by $0\n   from $1; make changes there.\n */\n\n#include \"zipint.h\"\n\nconst char * const _zip_err_str[] = {\nEOF\n\nsed -n  '/^#define ZIP_ER_/ s/.*\\/\\* . \\([^*]*\\) \\*\\//    \"\\1\",/p' \"$1\" \\\n    >> \"$2.$$\" || exit 1\n\ncat <<EOF >> \"$2.$$\" || exit 1\n};\n\nconst int _zip_nerr_str = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]);\n\n#define N ZIP_ET_NONE\n#define S ZIP_ET_SYS\n#define Z ZIP_ET_ZLIB\n\nconst int _zip_err_type[] = {\nEOF\n\nsed -n  '/^#define ZIP_ER_/ s/.*\\/\\* \\(.\\) \\([^*]*\\) \\*\\//    \\1,/p' \"$1\" \\\n    >> \"$2.$$\" || exit 1\n\necho '};' >> \"$2.$$\" || exit 1\n\nmv \"$2.$$\" \"$2\" || exit 1\n", "num_lines": 80}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# <a class=\"link-man\" href=\"zip_errors.html\">\nLINKBASE='http://pubs.opengroup.org/onlinepubs/9699919799/functions/'\n\nsed -E -e 's,(<a class=\"Xr\" href=\")([^\"]*)(\">),\\1'\"$LINKBASE\"'\\2\\3,g' -e \"s,$LINKBASE\"'(libzip|zip),\\1,g'\n", "num_lines": 7}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  make_zip_errrors.sh: create zip_errors.mdoc from zip.h\n#  Copyright (C) 1999-2013 Dieter Baron and Thomas Klausner\n#\n#  This file is part of libzip, a library to manipulate ZIP archives.\n#  The authors can be contacted at <libzip@nih.at>\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions\n#  are met:\n#  1. Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#  2. Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in\n#     the documentation and/or other materials provided with the\n#     distribution.\n#  3. The names of the authors may not be used to endorse or promote\n#     products derived from this software without specific prior\n#     written permission.\n# \n#  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS\n#  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY\n#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n#  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n#  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n#  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\nif [ \"$#\" -ne 2 ]\nthen\n    echo \"Usage: $0 in_file out_file\" >&2\n    echo \"       e.g. $0 zip.h zip_errors.mdoc\" >&2\n    exit 1\nfi\n\nif [ \"$1\" = \"$2\" ]\nthen\n    echo \"$0: error: output file = input file\" >&2\n    exit 1\nfi\n\ndate=`LC_TIME=en_US date '+%B %e, %Y' | sed 's/  / /'`\n\ncat <<EOF >> \"$2.$$\" || exit 1\n.\\\" zip_errors.mdoc -- list of all libzip error codes\n.\\\" Copyright (C) 1999-2013 Dieter Baron and Thomas Klausner\n.\\\"\n.\\\" This file is part of libzip, a library to manipulate ZIP archives.\n.\\\" The authors can be contacted at <libzip@nih.at>\n.\\\"\n.\\\" Redistribution and use in source and binary forms, with or without\n.\\\" modification, are permitted provided that the following conditions\n.\\\" are met:\n.\\\" 1. Redistributions of source code must retain the above copyright\n.\\\"    notice, this list of conditions and the following disclaimer.\n.\\\" 2. Redistributions in binary form must reproduce the above copyright\n.\\\"    notice, this list of conditions and the following disclaimer in\n.\\\"    the documentation and/or other materials provided with the\n.\\\"    distribution.\n.\\\" 3. The names of the authors may not be used to endorse or promote\n.\\\"    products derived from this software without specific prior\n.\\\"    written permission.\n.\\\"\n.\\\" THIS SOFTWARE IS PROVIDED BY THE AUTHORS \\`\\`AS IS'' AND ANY EXPRESS\n.\\\" OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n.\\\" WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n.\\\" ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY\n.\\\" DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n.\\\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n.\\\" GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n.\\\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER\n.\\\" IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR\n.\\\" OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN\n.\\\" IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n.\\\"\n.\\\"   This file was generated automatically by $0\n.\\\"   from $1; make changes there.\n.\\\"\n.Dd $date\n.Dt ZIP_ERRORS 3\n.Os\n.Sh NAME\n.Nm zip_errors\n.Nd list of all libzip error codes\n.Sh LIBRARY\nlibzip (-lzip)\n.Sh SYNOPSIS\n.In zip.h\n.Sh DESCRIPTION\nThe following error codes are used by libzip:\n.Bl -tag -width XZIPXERXCOMPNOTSUPPXX\nEOF\n\nsed -n  's/^#define \\(ZIP_ER_[A-Z_0-9]*\\).*\\/\\* \\(.\\) \\([^*]*\\) \\*\\//.It Bq Er \\1@\\3./p' \"$1\" \\\n    | sort\\\n    | tr @ '\\012' \\\n    >> \"$2.$$\" || exit 1\n\ncat <<EOF >> \"$2.$$\" || exit 1\n.El\n.Sh AUTHORS\n.An -nosplit\n.An Dieter Baron Aq Mt dillo@nih.at\nand\n.An Thomas Klausner Aq Mt tk@giga.or.at\nEOF\n\nmv \"$2.$$\" \"$2\" || exit 1\n", "num_lines": 115}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Replace the value for PLIST_KEY with the resolved definition from the header file that was passed in.\n\nSOURCE_HEADER_FILE_PATH=$1\nSOURCE_PLIST_PATH=$2\n\nPLIST_KEY=\"CFBundleShortVersionString\"\n\nVERSION_KEY=`/usr/libexec/PlistBuddy -c \"Print :${PLIST_KEY}\" \"${SOURCE_PLIST_PATH}\"`\n\n#echo \"Key: ${VERSION_KEY}\"\n\nVERSION_NUM=`cat \"${SOURCE_HEADER_FILE_PATH}\" | sed -n \"s|#define ${VERSION_KEY} \\\"\\(.*\\)\\\".*|\\1|p\"`\n\n#echo \"Value: ${VERSION_NUM}\"\n\nTARGET_PLIST_PATH=\"${TARGET_BUILD_DIR}/${INFOPLIST_PATH}\"\n\n/usr/libexec/PlistBuddy -c \"Set :${PLIST_KEY} ${VERSION_NUM}\" \"${TARGET_PLIST_PATH}\"\n", "num_lines": 21}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\nDIR=tmp.$$\n\nmkdir -p $DIR/32 $DIR/64\n\n(cd $DIR/32; ../../../configure CFLAGS=-m32)\n(cd $DIR/64; ../../../configure CFLAGS=-m64)\n\ndiff -D __LP64__ $DIR/32/config.h $DIR/64/config.h > config.h\n\nrm -r $DIR\n", "num_lines": 13}
{"repo_name": "retro", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to check include/test code for common pybind11 code style errors.\n#\n# This script currently checks for\n#\n# 1. use of tabs instead of spaces\n# 2. MSDOS-style CRLF endings\n# 3. trailing spaces\n# 4. missing space between keyword and parenthesis, e.g.: for(, if(, while(\n# 5. Missing space between right parenthesis and brace, e.g. 'for (...){'\n# 6. opening brace on its own line. It should always be on the same line as the\n#    if/while/for/do statement.\n#\n# Invoke as: tools/check-style.sh\n#\n\ncheck_style_errors=0\nIFS=$'\\n'\n\nfound=\"$( GREP_COLORS='mt=41' GREP_COLOR='41' grep $'\\t' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )\"\nif [ -n \"$found\" ]; then\n    # The mt=41 sets a red background for matched tabs:\n    echo -e '\\033[31;01mError: found tab characters in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\n\nfound=\"$( grep -IUlr $'\\r' include tests/*.{cpp,py,h} docs/*.rst --color=always )\"\nif [ -n \"$found\" ]; then\n    echo -e '\\033[31;01mError: found CRLF characters in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(GREP_COLORS='mt=41' GREP_COLOR='41' grep '[[:blank:]]\\+$' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )\"\nif [ -n \"$found\" ]; then\n    # The mt=41 sets a red background for matched trailing spaces\n    echo -e '\\033[31;01mError: found trailing spaces in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(grep '\\<\\(if\\|for\\|while\\|catch\\)(\\|){' include tests/*.{cpp,h} -rn --color=always)\"\nif [ -n \"$found\" ]; then\n    echo -e '\\033[31;01mError: found the following coding style problems:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(awk '\nfunction prefix(filename, lineno) {\n    return \"    \\033[35m\" filename \"\\033[36m:\\033[32m\" lineno \"\\033[36m:\\033[0m\"\n}\nfunction mark(pattern, string) { sub(pattern, \"\\033[01;31m&\\033[0m\", string); return string }\nlast && /^\\s*{/ {\n    print prefix(FILENAME, FNR-1) mark(\"\\\\)\\\\s*$\", last)\n    print prefix(FILENAME, FNR)   mark(\"^\\\\s*{\", $0)\n    last=\"\"\n}\n{ last = /(if|for|while|catch|switch)\\s*\\(.*\\)\\s*$/ ? $0 : \"\" }\n' $(find include -type f) tests/*.{cpp,h} docs/*.rst)\"\nif [ -n \"$found\" ]; then\n    check_style_errors=1\n    echo -e '\\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\\033[0m'\n    echo \"$found\"\nfi\n\nexit $check_style_errors\n", "num_lines": 71}
{"repo_name": "retro-contest", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport NVIDIA_DOCKER=${NVIDIA_DOCKER:-\"nvidia-docker\"}\nexport COMPO_RESULTS=$(realpath $(dirname -- $0))/results\n\nmkdir -p $COMPO_RESULTS\n\nalias \\\n    docker-retro-contest-agent=\"\\$NVIDIA_DOCKER run --rm -v compo-tmp-vol:/root/compo/tmp agent retro-contest-agent\" \\\n    docker-retro-contest-remote=\"docker run --rm -v compo-tmp-vol:/root/compo/tmp -v \\$COMPO_RESULTS:/root/compo/results remote-env retro-contest-remote\"\n", "num_lines": 11}
{"repo_name": "retro-contest", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nDATA_PATH=$(python -c 'import retro; print(retro.data.path(retro.data.DATA_PATH))')\necho \"Importing games from $DATA_PATH...\"\nCONTAINER_ID=$(docker run -v \"$DATA_PATH\":/root/roms:ro -d remote-env 'python /tmp/gym-retro/scripts/import.py /root/roms')\ndocker attach $CONTAINER_ID\ndocker commit $CONTAINER_ID remote-env:full\ndocker rm $CONTAINER_ID\n", "num_lines": 9}
{"repo_name": "retro-contest", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/sh\n\ncd `dirname $0`\n\ntry_build () {\n\tdocker build -t $@ || exit $?\n}\n\necho - Pulling base images\ndocker pull -a openai/retro-agent\ndocker pull -a openai/retro-env\nif [ \"$1\" = \"rebuild\" ]; then\n\techo - Building base CPU image\n\ttry_build openai/retro-agent:bare           --build-arg BASE=ubuntu --build-arg TAG= --pull -f agent.docker ..\n\techo - Building base CUDA images\n\ttry_build openai/retro-agent:bare-cuda8     --build-arg CUDA=8.0 --build-arg CUDNN=6 --pull -f agent.docker ..\n\ttry_build openai/retro-agent:bare-cuda9     --build-arg CUDA=9.0 --build-arg CUDNN=7 --pull -f agent.docker ..\n\techo - Building base TensorFlow images\n\ttry_build openai/retro-agent:tensorflow-1.4 --build-arg CUDA=8 --build-arg TF=1.4.1        - < agent-tf.docker\n\ttry_build openai/retro-agent:tensorflow-1.5 --build-arg CUDA=9 --build-arg TF=1.5.1        - < agent-tf.docker\n\ttry_build openai/retro-agent:tensorflow-1.7 --build-arg CUDA=9 --build-arg TF=1.7.1        - < agent-tf.docker\n\ttry_build openai/retro-agent:tensorflow-1.8 --build-arg CUDA=9 --build-arg TF=1.8.0        - < agent-tf.docker\n\techo - Building base PyTorch images\n\ttry_build openai/retro-agent:pytorch-0.3    --build-arg PYTORCH=0.3.1                      - < agent-pytorch.docker\n\ttry_build openai/retro-agent:pytorch-0.4    --build-arg PYTORCH=0.4.0                      - < agent-pytorch.docker\n\techo - Building remote image\n\ttry_build openai/retro-env -f remote-env.docker ..\nfi\nif [ -n \"$(ls ../roms)\" ]; then\n\techo - Building remote image with ROMs\n\tdocker tag openai/retro-env openai/retro-env:bare\n\ttry_build openai/retro-env -f remote-env-roms.docker ..\nfi\necho - Tagging images\ndocker tag openai/retro-agent:tensorflow-1.8     openai/retro-agent:tensorflow-latest\ndocker tag openai/retro-agent:tensorflow-latest  openai/retro-agent:tensorflow\ndocker tag openai/retro-agent:pytorch-0.4        openai/retro-agent:pytorch\ndocker tag openai/retro-agent:tensorflow         openai/retro-agent:latest\ndocker tag openai/retro-agent agent\n\necho - Installing Python library\npip3 install -e '../support[docker,rest]'\n", "num_lines": 43}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nif [ $(uname) == 'Linux' ]; then\n    docker run -v $PWD:/io python:${MB_PYTHON_VERSION} /io/docker_build_wheel.sh\nfi\n\nif [ $(uname) == 'Darwin' ]; then\n    ./osx_build_wheel.sh\nfi\n", "num_lines": 11}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nfunction pre_build {\n    echo \"Hello world (this should not be run)\"\n}\n\nfunction run_tests {\n    echo \"Hello world (this should not be run)\"\n}\n\n", "num_lines": 10}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "# !/bin/bash\nset -ex\n# ** HACK - rename linux wheels to manylinux1 wheels\nif [ $(uname) == 'Linux' ]; then\n    cd wheelhouse\n    for whl in $(ls roboschool-*linux*.whl); do\n        echo \"HACK!!! Renaming $whl --> ${whl%linux_x86_64.whl}manylinux1_x86_64.whl\"\n        sudo mv $whl ${whl%linux_x86_64.whl}manylinux1_x86_64.whl\n    done \n    cd ..\n    pip install --user bleach==3.0.2\n    pip install --user twine==1.12.1\nfi\n# ** END HACK\n\nif [ $(uname) == 'Darwin' ]; then\n    export PATH=$PWD/venv/bin:$PATH\n    pip install twine\nfi\n\nif [[ ! -z \"$TRAVIS_TAG\" ]]; then\n    python -m twine upload wheelhouse/*\n\n    if [[ ! -z \"$DEPLOY_SDIST\" ]]; then\n        python setup.py sdist\n        python -m twine upload dist/*       \n    fi\nfi\n\n", "num_lines": 30}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\napt-get update && apt-get install -y libgl1-mesa-dev qtbase5-dev libqt5opengl5-dev libassimp-dev patchelf cmake > /dev/null\n\ncd $(dirname \"$0\")\n. ./exports.sh\n\n./install_boost.sh\n./install_bullet.sh\n./roboschool_compile_and_graft.sh\n\npip wheel --no-deps -w /io/wheelhouse .\n\n\n", "num_lines": 15}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\napt-get update && apt-get install -y libgl1-mesa-dev > /dev/null\npip install /io/wheelhouse/roboschool*.whl\n\npython -c \"import roboschool, gym; gym.make('RoboschoolAnt-v1')\"\n\n", "num_lines": 8}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "export ROBOSCHOOL_PATH=$( cd \"$(dirname \"$BASH_SOURCE\")\" ; pwd -P )\nexport CPP_HOUSEHOLD=$ROBOSCHOOL_PATH/roboschool/cpp-household\nexport BULLET_PATH=$HOME/.forked_bullet\n\nif [[ $(uname) == 'Linux' ]]; then\n    PYTHON_BIN=$(readlink -f $(which python))\n    PYTHON_ROOT=${PYTHON_BIN%/bin/python*}\n    PYTHON_VER=${PYTHON_BIN#$PYTHON_ROOT/bin/python}\nfi\nif [[ $(uname) == 'Darwin' ]]; then\n    brew install coreutils\n    PYTHON_BIN=$(greadlink -f $(which python))\n    PYTHON_ROOT=${PYTHON_BIN%/bin/python*}\n    PYTHON_VER=${PYTHON_BIN#$PYTHON_ROOT/bin/python}\n    export PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/usr/local/opt/qt/lib/pkgconfig:/Library/Frameworks/Python.framework/Versions/${PYTHON_VER}/lib/pkgconfig/\nfi\n\n\nexport PKG_CONFIG_PATH=${PYTHON_ROOT}/lib/pkgconfig:$BULLET_PATH/lib/pkgconfig/:$PKG_CONFIG_PATH\nexport CPATH=$CPATH:${PYTHON_ROOT}/include/python${PYTHON_VER}m:$HOME/.boost/include\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$BULLET_PATH/lib:$HOME/.boost/lib\n\n", "num_lines": 23}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nif [ $(uname) == 'Linux' ]; then\n    source ./exports.sh\n    BOOST_SRCDIR=$HOME/.boost_src\n    mkdir -p $BOOST_SRCDIR && cd $BOOST_SRCDIR\n    # curl -OL https://storage.googleapis.com/games-src/boost/boost_1_58_0.tar.bz2\n    curl -OL https://dl.bintray.com/boostorg/release/1.69.0/source/boost_1_69_0.tar.gz\n    tar -xf boost_1_69_0.tar.gz\n    cd boost_1_69_0\n\n     ./bootstrap.sh --with-python=$(which python) --with-libraries=python --prefix=$HOME/.boost --with-python-root=$PYTHON_ROOT\n     ./b2 install > $BOOST_SRCDIR/boost_make.log || (tail -100 $BOOST_SRCDIR/boost_make.log; exit 1)\nfi\n", "num_lines": 14}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nBULLET_SRCDIR=$(mktemp -d)/bullet3\nBULLET_PATH=$HOME/.forked_bullet\n\nrm -rf $BULLET_SRCDIR\nmkdir -p $BULLET_SRCDIR && cd $BULLET_SRCDIR\ngit clone https://github.com/olegklimov/bullet3 -b roboschool_self_collision .\n\nmkdir build && cd build\ncmake -DBUILD_SHARED_LIBS=ON -DUSE_DOUBLE_PRECISION=1 -DCMAKE_INSTALL_PREFIX:PATH=$BULLET_PATH -DBUILD_CPU_DEMOS=OFF -DBUILD_BULLET2_DEMOS=OFF -DBUILD_EXTRAS=OFF  -DBUILD_UNIT_TESTS=OFF -DBUILD_CLSOCKET=OFF -DBUILD_ENET=OFF -DBUILD_OPENGL3_DEMOS=OFF ..\n\nmake -j4 > /tmp/bullet_make.log || (tail -100 /tmp/bullet_make.log; exit 1)\nmake install > /tmp/bullet_install.log || (tail -100 /tmp/bullet_install.log; exit 1)\n\nif [ $(uname) == 'Darwin' ]; then\n    \n    for lib in $(find $BULLET_PATH/lib -name \"*.dylib\"); do\n        install_name_tool -id $lib $lib\n        for dep in $(otool -L $lib | grep \"@rpath\" | awk '{print $1}'); do \n            install_name_tool -change $dep \"$BULLET_PATH/lib/${dep##@rpath/}\" $lib\n        done\n    done\nfi\nif [ $(uname) == 'Linux' ]; then\n    \n    for lib in $(find $BULLET_PATH/lib -name \"*.so.2.87\"); do\n        patchelf --set-rpath $BULLET_PATH/lib $lib\n    done\nfi\n\n", "num_lines": 32}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\ngit clone https://github.com/matthew-brett/multibuild && cd multibuild && git checkout 254ad28 && cd ..\n. multibuild/common_utils.sh\n. multibuild/travis_steps.sh\nbefore_install\n\nbrew install qt assimp boost-python3 || echo \"warning - brew returned non-zero exit code. \\nThis may be a sign of error, but may also be because brew wants to point something out. Please inspect logs above\"\n\n. ./exports.sh\n./install_bullet.sh\n./roboschool_compile_and_graft.sh\npip wheel --no-deps -w wheelhouse .\n\n", "num_lines": 15}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n. multibuild/common_utils.sh\n. multibuild/travis_steps.sh\nbefore_install\n\npip install wheelhouse/roboschool*.whl\n\npython -c \"import roboschool, gym; gym.make('RoboschoolAnt-v1')\"\n\n", "num_lines": 11}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nfunction graft_libs {\n    local libfile=$1\n    local libdir=$(dirname $libfile)\n    if [ $(uname) == 'Darwin' ]; then\n        local relink=\"osx_relink\"\n        local origin=\"@loader_path\"\n        local deps=$(otool -L $libfile | awk 'FNR>2 {print $1}')\n    fi\n    if [ $(uname) == 'Linux' ]; then\n        local relink=\"linux_relink\"\n        local library_lister=\"ldd\"\n        local origin=\"\\$ORIGIN\"\n        local deps=$(ldd $libfile | awk '{print $3}')\n    fi\n\n    local patterns=${@:3}\n    \n    graft_dir=$2\n    mkdir -p $graft_dir\n\n    for dep in $deps; do\n        # echo $dep\n        for deppattern in $patterns; do\n            if [[ \"$dep\" =~ $deppattern ]]; then\n                new_depname=${dep##*/}\n                new_deppath=\"$graft_dir/$new_depname\"\n                rel_path=$(realpath --relative-to=\"$libdir\" $new_deppath) \n                new_dep=\"$origin/$rel_path\"\n                echo \"$libfile depends on $dep, relinking to $new_deppath ($new_dep)\"\n                $relink $dep $new_dep $libfile\n                if [ ! -f $new_deppath ]; then\n                    echo \"$new_deppath not found, copying and calling self\" \n                    cp $dep $new_deppath\n                    chmod 777 $new_deppath\n                    graft_libs $new_deppath $graft_dir $patterns\n                else\n                    echo \"grafted library $new_deppath already exists\"\n                fi\n            fi\n        done    \n    done\n}\n\nfunction osx_relink {\n    install_name_tool -change $1 $2 $3\n}\n\nfunction linux_relink {\n    # local depname=${2#*/}\n    local dep_dir=${2%/*}\n    patchelf --set-rpath $dep_dir $3\n}\n\ncd $(dirname \"$0\")\n\ncd roboschool/cpp-household\n# make clean\nmake -j4\ncd ..\n\n\ngraft_libs cpp_household.so .libs \\\n    ^/.+/libboost_python.+ \\\n    ^/.+Qt.+ \\\n    ^/.+/libassimp.+ \\\n    ^/.+/libLinearMath.+ \\\n    ^/.+/libBullet.+ \\\n    ^/.+/libPhysicsClientC_API.+ \\\n    ^/.+/libjpeg.+ \\\n    ^/.+/libpng.+ \\\n    ^/.+/libicu.+ \\\n    ^/.+/libpcre.+ \\\n    ^/.+/libdouble-conversion.+ \\\n    ^/.+/libminizip.+\n\nif [ $(uname) == 'Darwin' ]; then\n    # HACK - this should auto-detect plugins dir\n    cp -r /usr/local/Cellar/qt/5.10.1/plugins .qt_plugins\n    lib_pattern=\"*.dylib\"\nfi \nif [ $(uname) == 'Linux' ]; then\n    cp -r /usr/lib/x86_64-linux-gnu/qt5/plugins .qt_plugins\n    lib_pattern=\"*.so*\"\nfi\nfor lib in $(find .qt_plugins -name \"$lib_pattern\"); do \n     graft_libs $lib .libs ^/.+Qt.+ \\\n                ^/.+/libjpeg.+ \\\n                ^/.+/libpng.+ \\\n                ^/.+/libicu.+ \\\n                ^/.+/libpcre.+ \\\n                ^/.+/libdouble-conversion.+ \\\n                ^/.+/libminizip.+ \\\n                ^/.+/libxcb.+ \\\n                ^/.+/libxkb.+\ndone\n\n", "num_lines": 100}
{"repo_name": "roboschool", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nif [ $(uname) == 'Linux' ]; then\n    docker run -v $PWD:/io python:${MB_PYTHON_VERSION} /io/docker_test_wheel.sh\nfi\n\nif [ $(uname) == 'Darwin' ]; then\n    ./osx_test_wheel.sh\nfi\n", "num_lines": 11}
{"repo_name": "rosbridge", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\nxrandr --addmode VIRTUAL1 1280x1024_60.00\nxrandr --newmode \"1280x1024_60.00\"  109.00  1280 1368 1496 1712  1024 1027 1034 1063 -hsync +vsync\nxrandr --addmode VIRTUAL1 1280x1024_60.00\nxrandr --output VIRTUAL1 --mode \"1280x1024_60.00\"\n", "num_lines": 7}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is convenience to download and install etcd in third_party.\n# Mostly just used by CI.\n# Usage: `hack/install-etcd.sh`.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${SCRIPT_ROOT}/hack/lib/init.sh\"\n\nkube::etcd::install\n", "num_lines": 29}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")/..\nsource \"${SCRIPT_ROOT}/hack/lib/init.sh\"\n\ncheckEtcdOnPath() {\n  # If it's in a prow CI env, add etcd to path.\n  [[ ${CI:-} == \"true\" ]] && export PATH=\"$(pwd)/etcd:${PATH}\"\n  kube::log::status \"Checking etcd is on PATH\"\n  command -v etcd >/dev/null && return\n  kube::log::status \"Cannot find etcd, cannot run integration tests.\"\n  kube::log::status \"Please see https://git.k8s.io/community/contributors/devel/sig-testing/integration-tests.md#install-etcd-dependency for instructions.\"\n  # kube::log::usage \"You can use 'hack/install-etcd.sh' to install a copy in third_party/.\"\n  return 1\n}\n\nCLEANUP_REQUIRED=\ncleanup() {\n  [[ -z \"${CLEANUP_REQUIRED}\" ]] && return\n  kube::log::status \"Cleaning up etcd\"\n  kube::etcd::cleanup\n  CLEANUP_REQUIRED=\n  kube::log::status \"Integration test cleanup complete\"\n}\n\nrunTests() {\n  kube::log::status \"Starting etcd instance\"\n  CLEANUP_REQUIRED=1\n  kube::etcd::start\n  kube::log::status \"Running integration test cases\"\n\n  # TODO: make args customizable.\n  go test -timeout=40m -mod=vendor sigs.k8s.io/scheduler-plugins/test/integration/...\n\n  cleanup\n}\n\ncheckEtcdOnPath\n\n# Run cleanup to stop etcd on interrupt or other kill signal.\ntrap cleanup EXIT\n\nrunTests\n", "num_lines": 62}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")/..\nsource \"${SCRIPT_ROOT}/hack/lib/init.sh\"\n\n# TODO: make args customizable.\ngo test -mod=vendor \\\n  sigs.k8s.io/scheduler-plugins/cmd/... \\\n  sigs.k8s.io/scheduler-plugins/pkg/...\n", "num_lines": 28}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\n\nbash \"${CODEGEN_PKG}\"/generate-internal-groups.sh \\\n  \"deepcopy,defaulter,conversion\" \\\n  sigs.k8s.io/scheduler-plugins/pkg/generated \\\n  sigs.k8s.io/scheduler-plugins/pkg/apis \\\n  sigs.k8s.io/scheduler-plugins/pkg/apis \\\n  \"config:v1beta1\" \\\n  --go-header-file \"${SCRIPT_ROOT}\"/hack/boilerplate/boilerplate.generatego.txt\n\nbash \"${CODEGEN_PKG}\"/generate-groups.sh \\\n  all \\\n  sigs.k8s.io/scheduler-plugins/pkg/generated \\\n  sigs.k8s.io/scheduler-plugins/pkg/apis \\\n  \"scheduling:v1alpha1\" \\\n  --go-header-file \"${SCRIPT_ROOT}\"/hack/boilerplate/boilerplate.generatego.txt\n", "num_lines": 38}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# TODO: make this script run faster.\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\ngo install k8s.io/kube-openapi/cmd/openapi-gen\n\nKUBE_INPUT_DIRS=(\n  $(\n    grep --color=never -rl '+k8s:openapi-gen=' vendor/k8s.io | \\\n    xargs -n1 dirname | \\\n    sed \"s,^vendor/,,\" | \\\n    sort -u | \\\n    sed '/^k8s\\.io\\/kubernetes\\/build\\/root$/d' | \\\n    sed '/^k8s\\.io\\/kubernetes$/d' | \\\n    sed '/^k8s\\.io\\/kubernetes\\/staging$/d' | \\\n    sed 's,k8s\\.io/kubernetes/staging/src/,,' | \\\n    grep -v 'k8s.io/code-generator' | \\\n    grep -v 'k8s.io/sample-apiserver'\n  )\n)\n\nKUBE_INPUT_DIRS=$(IFS=,; echo \"${KUBE_INPUT_DIRS[*]}\")\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\n\necho \"Generating Kubernetes OpenAPI\"\n\n$GOPATH/bin/openapi-gen \\\n  --output-file-base zz_generated.openapi \\\n  --output-base=\"${GOPATH}/src\" \\\n  --go-header-file ${SCRIPT_ROOT}/hack/boilerplate/boilerplate.generatego.txt \\\n  --output-base=\"./\" \\\n  --input-dirs $(join , \"${KUBE_INPUT_DIRS[@]}\") \\\n  --output-package \"vendor/k8s.io/kubernetes/pkg/generated/openapi\" \\\n  --report-filename \"${SCRIPT_ROOT}/hack/openapi-violation.list\" \\\n  \"$@\"\n\n# TODO: verify hack/openapi-violation.list", "num_lines": 58}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCIPRT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${SCIPRT_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${SCIPRT_ROOT}\"\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './.git' \\\n        -o -wholename './_output' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n      \\) -prune \\\n    \\) -name '*.go'\n}\n\nfind_files | xargs gofmt -s -w\n", "num_lines": 44}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCIPRT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${SCIPRT_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ngo mod tidy\ngo mod vendor", "num_lines": 27}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script checks whether the source codes need to be formatted or not by\n# `gofmt`. We should run `hack/update-gofmt.sh` if actually formats them.\n# Usage: `hack/verify-gofmt.sh`.\n# Note: GoFmt apparently is changing @ head...\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nsource \"${SCRIPT_ROOT}/hack/lib/init.sh\"\n\nkube::golang::verify_go_version\n\ncd \"${SCRIPT_ROOT}\"\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './.git' \\\n        -o -wholename './_output' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './staging/src/k8s.io/client-go/*vendor/*' \\\n        -o -wholename '*/bindata.go' \\\n      \\) -prune \\\n    \\) -name '*.go'\n}\n\n\n# gofmt exits with non-zero exit code if it finds a problem unrelated to\n# formatting (e.g., a file does not parse correctly). Without \"|| true\" this\n# would have led to no useful error message from gofmt, because the script would\n# have failed before getting to the \"echo\" in the block below.\ndiff=$(find_files | xargs gofmt -d -s 2>&1) || true\nif [[ -n \"${diff}\" ]]; then\n  echo \"${diff}\" >&2\n  echo >&2\n  echo \"Run ./hack/update-gofmt.sh\" >&2\n  exit 1\nfi\n", "num_lines": 61}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# A set of helpers for starting/running etcd for tests\n\nETCD_VERSION=${ETCD_VERSION:-3.4.9}\nETCD_HOST=${ETCD_HOST:-127.0.0.1}\nETCD_PORT=${ETCD_PORT:-2379}\nexport KUBE_INTEGRATION_ETCD_URL=\"http://${ETCD_HOST}:${ETCD_PORT}\"\n\nkube::etcd::validate() {\n  # validate if in path\n  command -v etcd >/dev/null || {\n    kube::log::usage \"etcd must be in your PATH\"\n    kube::log::info \"You can use 'hack/install-etcd.sh' to install a copy in third_party/.\"\n    exit 1\n  }\n\n  # validate if etcd is running and $ETCD_PORT is in use\n  if ps -ef | grep \"etcd \" | grep ${ETCD_PORT} &> /dev/null; then\n    kube::log::usage \"unable to start etcd as port ${ETCD_PORT} is in use. please stop the process listening on this port and retry.\"\n    exit 1\n  fi\n\n  # need set the env of \"ETCD_UNSUPPORTED_ARCH\" on unstable arch.\n  arch=$(uname -m)\n  if [[ $arch =~ aarch* ]]; then\n\t  export ETCD_UNSUPPORTED_ARCH=arm64\n  elif [[ $arch =~ arm* ]]; then\n\t  export ETCD_UNSUPPORTED_ARCH=arm\n  fi\n  # validate installed version is at least equal to minimum\n  version=$(etcd --version | grep Version | head -n 1 | cut -d \" \" -f 3)\n  if [[ $(kube::etcd::version \"${ETCD_VERSION}\") -gt $(kube::etcd::version \"${version}\") ]]; then\n    kube::log::usage \"etcd version ${ETCD_VERSION} or greater required.\"\n    kube::log::info \"You can use 'hack/install-etcd.sh' to install.\"\n    exit 1\n  fi\n}\n\nkube::etcd::version() {\n  printf '%s\\n' \"${@}\" | awk -F . '{ printf(\"%d%03d%03d\\n\", $1, $2, $3) }'\n}\n\nkube::etcd::start() {\n  # validate before running\n  kube::etcd::validate\n\n  # Start etcd\n  ETCD_DIR=${ETCD_DIR:-$(mktemp -d 2>/dev/null || mktemp -d -t test-etcd.XXXXXX)}\n  if [[ -d \"${ARTIFACTS:-}\" ]]; then\n    ETCD_LOGFILE=\"${ARTIFACTS}/etcd.$(uname -n).$(id -un).log.DEBUG.$(date +%Y%m%d-%H%M%S).$$\"\n  else\n    ETCD_LOGFILE=${ETCD_LOGFILE:-\"/dev/null\"}\n  fi\n  kube::log::info \"etcd --advertise-client-urls ${KUBE_INTEGRATION_ETCD_URL} --data-dir ${ETCD_DIR} --listen-client-urls http://${ETCD_HOST}:${ETCD_PORT} --debug > \\\"${ETCD_LOGFILE}\\\" 2>/dev/null\"\n  etcd --advertise-client-urls \"${KUBE_INTEGRATION_ETCD_URL}\" --data-dir \"${ETCD_DIR}\" --listen-client-urls \"${KUBE_INTEGRATION_ETCD_URL}\" --debug 2> \"${ETCD_LOGFILE}\" >/dev/null &\n  ETCD_PID=$!\n\n  echo \"Waiting for etcd to come up.\"\n  kube::util::wait_for_url \"${KUBE_INTEGRATION_ETCD_URL}/health\" \"etcd: \" 0.25 80\n  curl -fs -X POST \"${KUBE_INTEGRATION_ETCD_URL}/v3/kv/put\" -d '{\"key\": \"X3Rlc3Q=\", \"value\": \"\"}'\n}\n\nkube::etcd::stop() {\n  if [[ -n \"${ETCD_PID-}\" ]]; then\n    kill \"${ETCD_PID}\" &>/dev/null || :\n    wait \"${ETCD_PID}\" &>/dev/null || :\n  fi\n}\n\nkube::etcd::clean_etcd_dir() {\n  if [[ -n \"${ETCD_DIR-}\" ]]; then\n    rm -rf \"${ETCD_DIR}\"\n  fi\n}\n\nkube::etcd::cleanup() {\n  kube::etcd::stop\n  kube::etcd::clean_etcd_dir\n}\n\nkube::etcd::install() {\n  (\n    local os\n    local arch\n\n    os=$(kube::util::host_os)\n    arch=$(kube::util::host_arch)\n\n    if [[ $(readlink etcd) == etcd-v${ETCD_VERSION}-${os}-* ]]; then\n      kube::log::info \"etcd v${ETCD_VERSION} already installed. To use:\"\n      kube::log::info \"export PATH=\\\"$(pwd)/etcd:\\${PATH}\\\"\"\n      return  #already installed\n    fi\n\n    if [[ ${os} == \"darwin\" ]]; then\n      download_file=\"etcd-v${ETCD_VERSION}-darwin-amd64.zip\"\n      url=\"https://github.com/etcd-io/etcd/releases/download/v${ETCD_VERSION}/${download_file}\"\n      kube::util::download_file \"${url}\" \"${download_file}\"\n      unzip -o \"${download_file}\"\n      ln -fns \"etcd-v${ETCD_VERSION}-darwin-amd64\" etcd\n      rm \"${download_file}\"\n    else\n      url=\"https://github.com/etcd-io/etcd/releases/download/v${ETCD_VERSION}/etcd-v${ETCD_VERSION}-linux-${arch}.tar.gz\"\n      download_file=\"etcd-v${ETCD_VERSION}-linux-${arch}.tar.gz\"\n      kube::util::download_file \"${url}\" \"${download_file}\"\n      tar xzf \"${download_file}\"\n      ln -fns \"etcd-v${ETCD_VERSION}-linux-${arch}\" etcd\n      rm \"${download_file}\"\n    fi\n    kube::log::info \"etcd v${ETCD_VERSION} installed. To use:\"\n    kube::log::info \"export PATH=\\\"$(pwd)/etcd:\\${PATH}\\\"\"\n  )\n}\n", "num_lines": 129}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Ensure the go tool exists and is a viable version.\nkube::golang::verify_go_version() {\n  if [[ -z \"$(command -v go)\" ]]; then\n    kube::log::usage_from_stdin <<EOF\nCan't find 'go' in PATH, please fix and retry.\nSee http://golang.org/doc/install for installation instructions.\nEOF\n    return 2\n  fi\n\n  local go_version\n  IFS=\" \" read -ra go_version <<< \"$(go version)\"\n  local minimum_go_version\n  minimum_go_version=go1.13.4\n  if [[ \"${minimum_go_version}\" != $(echo -e \"${minimum_go_version}\\n${go_version[2]}\" | sort -s -t. -k 1,1 -k 2,2n -k 3,3n | head -n1) && \"${go_version[2]}\" != \"devel\" ]]; then\n    kube::log::usage_from_stdin <<EOF\nDetected go version: ${go_version[*]}.\nKubernetes requires ${minimum_go_version} or greater.\nPlease install ${minimum_go_version} or later.\nEOF\n    return 2\n  fi\n}", "num_lines": 39}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nunset CDPATH\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")/../..\n\nsource \"${SCRIPT_ROOT}/hack/lib/logging.sh\"\nsource \"${SCRIPT_ROOT}/hack/lib/etcd.sh\"\nsource \"${SCRIPT_ROOT}/hack/lib/util.sh\"\nsource \"${SCRIPT_ROOT}/hack/lib/golang.sh\"", "num_lines": 24}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nkube::log::status() {\n  local timestamp=$(date +\"[%m%d %H:%M:%S]\")\n  echo \"+++ ${timestamp} ${1}\"\n  shift\n  for message; do\n    echo \"    ${message}\"\n  done\n}\n\nkube::log::info() {\n  for message; do\n    echo \"${message}\"\n  done\n}\n\n# Log an error but keep going.  Don't dump the stack or exit.\nkube::log::error() {\n  timestamp=$(date +\"[%m%d %H:%M:%S]\")\n  echo \"!!! ${timestamp} ${1-}\" >&2\n  shift\n  for message; do\n    echo \"    ${message}\" >&2\n  done\n}\n\n# Print an usage message to stderr.  The arguments are printed directly.\nkube::log::usage() {\n  echo >&2\n  local message\n  for message; do\n    echo \"${message}\" >&2\n  done\n  echo >&2\n}\n\nkube::log::usage_from_stdin() {\n  local messages=()\n  while read -r line; do\n    messages+=(\"${line}\")\n  done\n\n  kube::log::usage \"${messages[@]}\"\n}", "num_lines": 59}
{"repo_name": "scheduler-plugins", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nkube::util::host_os() {\n  local host_os\n  case \"$(uname -s)\" in\n    Darwin)\n      host_os=darwin\n      ;;\n    Linux)\n      host_os=linux\n      ;;\n    *)\n      kube::log::error \"Unsupported host OS.  Must be Linux or Mac OS X.\"\n      exit 1\n      ;;\n  esac\n  echo \"${host_os}\"\n}\n\nkube::util::host_arch() {\n  local host_arch\n  case \"$(uname -m)\" in\n    x86_64*)\n      host_arch=amd64\n      ;;\n    i?86_64*)\n      host_arch=amd64\n      ;;\n    amd64*)\n      host_arch=amd64\n      ;;\n    aarch64*)\n      host_arch=arm64\n      ;;\n    arm64*)\n      host_arch=arm64\n      ;;\n    arm*)\n      host_arch=arm\n      ;;\n    i?86*)\n      host_arch=x86\n      ;;\n    s390x*)\n      host_arch=s390x\n      ;;\n    ppc64le*)\n      host_arch=ppc64le\n      ;;\n    *)\n      kube::log::error \"Unsupported host arch. Must be x86_64, 386, arm, arm64, s390x or ppc64le.\"\n      exit 1\n      ;;\n  esac\n  echo \"${host_arch}\"\n}\n\nkube::util::wait_for_url() {\n  local url=$1\n  local prefix=${2:-}\n  local wait=${3:-1}\n  local times=${4:-30}\n  local maxtime=${5:-1}\n\n  command -v curl >/dev/null || {\n    kube::log::usage \"curl must be installed\"\n    exit 1\n  }\n\n  local i\n  for i in $(seq 1 \"${times}\"); do\n    local out\n    if out=$(curl --max-time \"${maxtime}\" -gkfs \"${url}\" 2>/dev/null); then\n      kube::log::status \"On try ${i}, ${prefix}: ${out}\"\n      return 0\n    fi\n    sleep \"${wait}\"\n  done\n  kube::log::error \"Timed out waiting for ${prefix} to answer at ${url}; tried ${times} waiting ${wait} between each\"\n  return 1\n}\n\nkube::util::download_file() {\n  local -r url=$1\n  local -r destination_file=$2\n\n  rm \"${destination_file}\" 2&> /dev/null || true\n\n  for i in $(seq 5)\n  do\n    if ! curl -fsSL --retry 3 --keepalive-time 2 \"${url}\" -o \"${destination_file}\"; then\n      echo \"Downloading ${url} failed. $((5-i)) retries left.\"\n      sleep 1\n    else\n      echo \"Downloading ${url} succeed\"\n      return 0\n    fi\n  done\n  return 1\n}\n", "num_lines": 115}
{"repo_name": "spinningup", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nmkdir -p $HOME/.mujoco\n\n# Avoid using pyenv in travis, since it adds ~7 minutes to turnaround time\nif [ \"$TRAVIS_OS_NAME\" == \"osx\" ]\nthen\n    # https://github.com/travis-ci/travis-ci/issues/9640\n    sudo softwareupdate --install \"Command Line Tools (macOS High Sierra version 10.13) for Xcode-9.4\"\n    brew update\n    brew install open-mpi\n    brew install gcc\n    brew link --overwrite gcc\n    curl $MUJOCO_FOR_OSX | tar xz -C $HOME/.mujoco/\nelif [ \"$TRAVIS_OS_NAME\" == \"linux\" ]\nthen\n    # Because this is flaky, try several times\n    set +e\n    COUNT=0\n    while [  $COUNT -lt 5 ]; do\n       sudo curl -o /usr/local/bin/patchelf https://s3-us-west-2.amazonaws.com/openai-sci-artifacts/manual-builds/patchelf_0.9_amd64.elf\n       if [ $? -eq 0 ];then\n          break\n       fi\n       let COUNT=COUNT+1\n    done\n    if [ $COUNT -ge 5 ]; then\n        echo \"Failed to download patchelf\"\n        exit 1\n    fi\n    set -e\n\n    sudo chmod +x /usr/local/bin/patchelf\n    curl $MUJOCO_FOR_LINUX | tar xz -C $HOME/.mujoco/\n\n    sudo apt-get update\n    sudo apt-get install -y openmpi-bin libopenmpi-dev libosmesa6-dev libglew-dev\nfi\n", "num_lines": 41}
{"repo_name": "staged-recipes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nmkdir build\ncd build\n\ncmake -DBACKWARD_TESTS=True -DCMAKE_PREFIX_PATH=$PREFIX -DCMAKE_INSTALL_PREFIX:PATH=$PREFIX ..\nmake -j${CPU_COUNT}\nctest -V\nmake install\n", "num_lines": 9}
{"repo_name": "staged-recipes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\nmkdir build\ncd build\ncmake $RECIPE_DIR -DCMAKE_BUILD_TYPE=Debug\nmake\n./main || true", "num_lines": 6}
{"repo_name": "staged-recipes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# Add `master` branch to the update list.\n# Otherwise CircleCI will give us a cached one.\nFETCH_REFS=\"+master:master\"\n\n# Update PR refs for testing.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/head:pr/${CIRCLE_PR_NUMBER}/head\"\n    FETCH_REFS=\"${FETCH_REFS} +refs/pull/${CIRCLE_PR_NUMBER}/merge:pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Retrieve the refs.\ngit fetch -u origin ${FETCH_REFS}\n\n# Checkout the PR merge ref.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    git checkout -qf \"pr/${CIRCLE_PR_NUMBER}/merge\"\nfi\n\n# Check for merge conflicts.\nif [[ -n \"${CIRCLE_PR_NUMBER}\" ]]\nthen\n    git branch --merged | grep master > /dev/null\n    git branch --merged | grep \"pr/${CIRCLE_PR_NUMBER}/head\" > /dev/null\nfi\n", "num_lines": 30}
{"repo_name": "staged-recipes", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# NOTE: This script has been adapted from content generated by github.com/conda-forge/conda-smithy\n\nREPO_ROOT=$(cd \"$(dirname \"$0\")/..\"; pwd;)\nIMAGE_NAME=\"condaforge/linux-anvil\"\n\nconfig=$(cat <<CONDARC\n\nchannels:\n - conda-forge\n - defaults\n\nconda-build:\n root-dir: /staged-recipes/build_artefacts\n\nalways_yes: true\nshow_channel_urls: true\n\nCONDARC\n)\n\ncat << EOF | docker run -i \\\n                        -v ${REPO_ROOT}:/staged-recipes \\\n                        -a stdin -a stdout -a stderr \\\n                        $IMAGE_NAME \\\n                        bash || exit $?\n\n# Copy the host recipes folder so we don't ever muck with it\ncp -r /staged-recipes/recipes /conda-recipes\n\n# Find the recipes from master in this PR and remove them.\necho \"Finding recipes merged in master and removing them from the build.\"\npushd /staged-recipes/recipes > /dev/null\ngit ls-tree --name-only master -- . | xargs -I {} sh -c \"rm -rf /conda-recipes/{} && echo Removing recipe: {}\"\npopd > /dev/null\n\nif [ \"${BINSTAR_TOKEN}\" ];then\n    export BINSTAR_TOKEN=${BINSTAR_TOKEN}\nfi\n\n# Unused, but needed by conda-build currently... :(\nexport CONDA_NPY='19'\n\necho \"$config\" > ~/.condarc\n\n# A lock sometimes occurs with incomplete builds. The lock file is stored in build_artefacts.\nconda clean --lock\n\nconda update conda conda-build\nconda install conda-build-all\nconda install conda-forge-build-setup\nsource run_conda_forge_build_setup\n\n# yum installs anything from a \"yum_requirements.txt\" file that isn't a blank line or comment.\nfind conda-recipes -mindepth 2 -maxdepth 2 -type f -name \"yum_requirements.txt\" \\\n    | xargs -n1 cat | grep -v -e \"^#\" -e \"^$\" | \\\n    xargs -r yum install -y\n\nconda-build-all /conda-recipes --matrix-conditions \"numpy >=1.10\" \"python >=2.7,<3|>=3.4\"\n\nEOF\n", "num_lines": 63}
{"repo_name": "supervised-reptile", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Fetch Omniglot and Mini-ImageNet.\n#\n\nOMNIGLOT_URL=https://github.com/brendenlake/omniglot/raw/master/python\nIMAGENET_URL=http://www.image-net.org/challenges/LSVRC/2012/nnoupb/ILSVRC2012_img_train.tar\n\nset -e\n\nmkdir tmp\ntrap 'rm -r tmp' EXIT\n\nif [ ! -d data ]; then\n    mkdir data\nfi\n\nif [ ! -d data/omniglot ]; then\n    mkdir tmp/omniglot\n    for name in images_background images_evaluation; do\n        echo \"Fetching omniglot/$name ...\"\n        curl -L -s \"$OMNIGLOT_URL/$name.zip\" > \"tmp/$name.zip\"\n        echo \"Extracting omniglot/$name ...\"\n        unzip -q \"tmp/$name.zip\" -d tmp\n        rm \"tmp/$name.zip\"\n        mv tmp/$name/* tmp/omniglot\n    done\n    mv tmp/omniglot data/omniglot\nfi\n\nif [ ! -d data/miniimagenet ]; then\n    mkdir tmp/miniimagenet\n    for subset in train test val; do\n        mkdir \"tmp/miniimagenet/$subset\"\n        echo \"Fetching Mini-ImageNet $subset set ...\"\n        for csv in $(ls metadata/miniimagenet/$subset); do\n            echo \"Fetching wnid: ${csv%.csv}\"\n            dst_dir=\"tmp/miniimagenet/$subset/${csv%.csv}\"\n            mkdir \"$dst_dir\"\n            for entry in $(cat metadata/miniimagenet/$subset/$csv); do\n                name=$(echo \"$entry\" | cut -f 1 -d ,)\n                range=$(echo \"$entry\" | cut -f 2 -d ,)\n                curl -s -H \"range: bytes=$range\" $IMAGENET_URL > \"$dst_dir/$name\" &\n            done\n            wait\n        done\n    done\n    mv tmp/miniimagenet data/miniimagenet\nfi\n", "num_lines": 50}
{"repo_name": "supervised-reptile", "repo_creator": "openai", "programming_language": "Shell", "code": "if [ -d 'build' ]; then\n    rm -r build\nfi\nmkdir build\n\nfor file in deps/jsnet.js deps/model.js src/webworker.js; do\n    cat $file >>build/webworker.js\ndone\n\nfor file in src/drawing.js src/evaluator.js src/predictions.js src/ui.js src/default.js deps/jsnet.js; do\n    cat $file >>build/app.js\ndone\necho >>build/app.js\necho -n 'var WORKER_DATA = \"' >>build/app.js\ncat build/webworker.js |\n    tr '\\n' '`' |\n    sed -E 's/\\\\/\\\\\\\\/g' |\n    sed -E 's/`/\\\\n/g' |\n    sed -E 's/\"/\\\\\"/g' >>build/app.js\nperl -pi -e 'chomp if eof' build/app.js\necho -n '\";' >>build/app.js\n", "num_lines": 22}
{"repo_name": "vdvae", "repo_creator": "openai", "programming_language": "Shell", "code": "wget https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\ntar -xf cifar-10-python.tar.gz\n", "num_lines": 3}
{"repo_name": "vdvae", "repo_creator": "openai", "programming_language": "Shell", "code": "# the first argument to this script should be the path to the ffhq_images1024x1024 folder\n# the same path should be provided as the `data_root` argument to train.py\ncd $1\nmkdir train\nmkdir train/0\nmkdir valid\nmkdir valid/0\nfor i in $(seq -f \"%05g\" 0 64999); do\n    mv $i.png train/0\ndone\nfor i in $(seq -f \"%05g\" 65000 69999); do\n    mv $i.png valid/0\ndone\n", "num_lines": 14}
{"repo_name": "vdvae", "repo_creator": "openai", "programming_language": "Shell", "code": "# we provide a copy of ffhq-256 for convenience, downsampled using the same function as NVAE (https://github.com/NVlabs/NVAE) (personal communication with author)\n\n# Resizing function is this one, with the default second argument and size=256\n# https://pytorch.org/docs/stable/torchvision/transforms.html#torchvision.transforms.Resize\n\n# 5-bit precision is calculated using the following lines, with num_bits=5 and for an x in [0, 1]\n# x = torch.floor(x * 255 / 2 ** (8 - num_bits))\n# x /= (2 ** num_bits - 1)\n\n# the DMOL loss should also be adjusted to have 32 buckets instead of 256 (this code, or NVAE, can be used as reference)\n\nwget https://openaipublic.blob.core.windows.net/very-deep-vaes-assets/vdvae-assets/ffhq-256.npy", "num_lines": 12}
{"repo_name": "vdvae", "repo_creator": "openai", "programming_language": "Shell", "code": "if [ \"$1\" == \"imagenet32\" ]; then\n\necho \"downloading imagenet32\"\nwget http://www.image-net.org/small/train_32x32.tar\nwget http://www.image-net.org/small/valid_32x32.tar\ntar -xvf train_32x32.tar\ntar -xvf valid_32x32.tar\npython files_to_npy.py train_32x32/ imagenet32-train.npy\npython files_to_npy.py valid_32x32/ imagenet32-valid.npy\n\nelif [ \"$1\" == \"imagenet64\" ]; then\n\necho \"downloading imagenet64\"\nwget http://www.image-net.org/small/train_64x64.tar\nwget http://www.image-net.org/small/valid_64x64.tar\ntar -xvf train_64x64.tar\ntar -xvf valid_64x64.tar\npython files_to_npy.py train_64x64/ imagenet64-train.npy\npython files_to_npy.py valid_64x64/ imagenet64-valid.npy\n\nelse\n\necho \"please pass the string imagenet32 or imagenet64 as an argument\"\n\nfi\n\n\n\n", "num_lines": 29}
{"repo_name": "websockify", "repo_creator": "openai", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nusage() {\n    if [ \"$*\" ]; then\n        echo \"$*\"\n        echo\n    fi\n    echo \"Usage: ${NAME} [--listen PORT] [--vnc VNC_HOST:PORT] [--cert CERT]\"\n    echo\n    echo \"Starts the WebSockets proxy and a mini-webserver and \"\n    echo \"provides a cut-and-paste URL to go to.\"\n    echo \n    echo \"    --listen PORT         Port for proxy/webserver to listen on\"\n    echo \"                          Default: 6080\"\n    echo \"    --vnc VNC_HOST:PORT   VNC server host:port proxy target\"\n    echo \"                          Default: localhost:5900\"\n    echo \"    --cert CERT           Path to combined cert/key file\"\n    echo \"                          Default: self.pem\"\n    echo \"    --web WEB             Path to web files (e.g. vnc.html)\"\n    echo \"                          Default: ./\"\n    exit 2\n}\n\nNAME=\"$(basename $0)\"\nHERE=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nPORT=\"6080\"\nVNC_DEST=\"localhost:5900\"\nCERT=\"\"\nWEB=\"\"\nproxy_pid=\"\"\n\ndie() {\n    echo \"$*\"\n    exit 1\n}\n\ncleanup() {\n    trap - TERM QUIT INT EXIT\n    trap \"true\" CHLD   # Ignore cleanup messages\n    echo\n    if [ -n \"${proxy_pid}\" ]; then\n        echo \"Terminating WebSockets proxy (${proxy_pid})\"\n        kill ${proxy_pid}\n    fi\n}\n\n# Process Arguments\n\n# Arguments that only apply to chrooter itself\nwhile [ \"$*\" ]; do\n    param=$1; shift; OPTARG=$1\n    case $param in\n    --listen)  PORT=\"${OPTARG}\"; shift            ;;\n    --vnc)     VNC_DEST=\"${OPTARG}\"; shift        ;;\n    --cert)    CERT=\"${OPTARG}\"; shift            ;;\n    --web)     WEB=\"${OPTARG}\"; shift            ;;\n    -h|--help) usage                              ;;\n    -*) usage \"Unknown chrooter option: ${param}\" ;;\n    *) break                                      ;;\n    esac\ndone\n\n# Sanity checks\nwhich netstat >/dev/null 2>&1 \\\n    || die \"Must have netstat installed\"\n\nnetstat -ltn | grep -qs \"${PORT} .*LISTEN\" \\\n    && die \"Port ${PORT} in use. Try --listen PORT\"\n\ntrap \"cleanup\" TERM QUIT INT EXIT\n\n# Find vnc.html\nif [ -n \"${WEB}\" ]; then\n    if [ ! -e \"${WEB}/vnc.html\" ]; then\n        die \"Could not find ${WEB}/vnc.html\"\n    fi\nelif [ -e \"$(pwd)/vnc.html\" ]; then\n    WEB=$(pwd)\nelif [ -e \"${HERE}/../vnc.html\" ]; then\n    WEB=${HERE}/../\nelif [ -e \"${HERE}/vnc.html\" ]; then\n    WEB=${HERE}\nelif [ -e \"${HERE}/../share/novnc/vnc.html\" ]; then\n    WEB=${HERE}/../share/novnc/\nelse\n    die \"Could not find vnc.html\"\nfi\n\n# Find self.pem\nif [ -n \"${CERT}\" ]; then\n    if [ ! -e \"${CERT}\" ]; then\n        die \"Could not find ${CERT}\"\n    fi\nelif [ -e \"$(pwd)/self.pem\" ]; then\n    CERT=\"$(pwd)/self.pem\"\nelif [ -e \"${HERE}/../self.pem\" ]; then\n    CERT=\"${HERE}/../self.pem\"\nelif [ -e \"${HERE}/self.pem\" ]; then\n    CERT=\"${HERE}/self.pem\"\nelse\n    echo \"Warning: could not find self.pem\"\nfi\n\necho \"Starting webserver and WebSockets proxy on port ${PORT}\"\n${HERE}/websockify --web ${WEB} ${CERT:+--cert ${CERT}} ${PORT} ${VNC_DEST} &\nproxy_pid=\"$!\"\nsleep 1\nif ! ps -p ${proxy_pid} >/dev/null; then\n    proxy_pid=\n    echo \"Failed to start WebSockets proxy\"\n    exit 1\nfi\n\necho -e \"\\n\\nNavigate to this URL:\\n\"\necho -e \"    http://$(hostname):${PORT}/vnc.html?host=$(hostname)&port=${PORT}\\n\"\necho -e \"Press Ctrl-C to exit\\n\\n\"\n\nwait ${proxy_pid}\n", "num_lines": 119}
{"repo_name": "zbarlight", "repo_creator": "openai", "programming_language": "Shell", "code": "# Generated from ltmain.m4sh.\n\n# ltmain.sh (GNU libtool) 2.2.6\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996, 1997, 1998, 1999, 2000, 2001, 2003, 2004, 2005, 2006, 2007 2008 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with GNU Libtool; see the file COPYING.  If not, a copy\n# can be downloaded from http://www.gnu.org/licenses/gpl.html,\n# or obtained by writing to the Free Software Foundation, Inc.,\n# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\n# Usage: $progname [OPTION]... [MODE-ARG]...\n#\n# Provide generalized library-building support services.\n#\n#     --config             show all configuration variables\n#     --debug              enable verbose shell tracing\n# -n, --dry-run            display commands without modifying any files\n#     --features           display basic configuration information and exit\n#     --mode=MODE          use operation mode MODE\n#     --preserve-dup-deps  don't remove duplicate dependency libraries\n#     --quiet, --silent    don't print informational messages\n#     --tag=TAG            use configuration variables from tag TAG\n# -v, --verbose            print informational messages (default)\n#     --version            print version information\n# -h, --help               print short or long help message\n#\n# MODE must be one of the following:\n#\n#       clean              remove files from the build directory\n#       compile            compile a source file into a libtool object\n#       execute            automatically set library path, then run a program\n#       finish             complete the installation of libtool libraries\n#       install            install libraries or executables\n#       link               create a library or an executable\n#       uninstall          remove libraries from an installed directory\n#\n# MODE-ARGS vary depending on the MODE.\n# Try `$progname --help --mode=MODE' for a more detailed description of MODE.\n#\n# When reporting a bug, please describe a test case to reproduce it and\n# include the following information:\n#\n#       host-triplet:\t$host\n#       shell:\t\t$SHELL\n#       compiler:\t\t$LTCC\n#       compiler flags:\t\t$LTCFLAGS\n#       linker:\t\t$LD (gnu? $with_gnu_ld)\n#       $progname:\t\t(GNU libtool) 2.2.6\n#       automake:\t\t$automake_version\n#       autoconf:\t\t$autoconf_version\n#\n# Report bugs to <bug-libtool@gnu.org>.\n\nPROGRAM=ltmain.sh\nPACKAGE=libtool\nVERSION=2.2.6\nTIMESTAMP=\"\"\npackage_revision=1.3012\n\n# Be Bourne compatible\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# NLS nuisances: We save the old values to restore during execute mode.\n# Only set LANG and LC_ALL to C if already set.\n# These must not be set unconditionally because not all systems understand\n# e.g. LANG=C (notably SCO).\nlt_user_locale=\nlt_safe_locale=\nfor lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test \\\"\\${$lt_var+set}\\\" = set; then\n          save_$lt_var=\\$$lt_var\n          $lt_var=C\n\t  export $lt_var\n\t  lt_user_locale=\\\"$lt_var=\\\\\\$save_\\$lt_var; \\$lt_user_locale\\\"\n\t  lt_safe_locale=\\\"$lt_var=C; \\$lt_safe_locale\\\"\n\tfi\"\ndone\n\n$lt_unset CDPATH\n\n\n\n\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"echo\"}\n: ${EGREP=\"/usr/bin/grep -E\"}\n: ${FGREP=\"/usr/bin/grep -F\"}\n: ${GREP=\"/usr/bin/grep\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SED=\"/opt/local/bin/gsed\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n: ${Xsed=\"$SED -e 1s/^X//\"}\n\n# Global variables:\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\nexit_status=$EXIT_SUCCESS\n\n# Make sure IFS has a sensible default\nlt_nl='\n'\nIFS=\" \t$lt_nl\"\n\ndirname=\"s,/[^/]*$,,\"\nbasename=\"s,^.*/,,\"\n\n# func_dirname_and_basename file append nondir_replacement\n# perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# Implementation must be kept synchronized with func_dirname\n# and func_basename. For efficiency, we do not delegate to\n# those functions but instead duplicate the functionality here.\nfunc_dirname_and_basename ()\n{\n  # Extract subdirectory from the argument.\n  func_dirname_result=`$ECHO \"X${1}\" | $Xsed -e \"$dirname\"`\n  if test \"X$func_dirname_result\" = \"X${1}\"; then\n    func_dirname_result=\"${3}\"\n  else\n    func_dirname_result=\"$func_dirname_result${2}\"\n  fi\n  func_basename_result=`$ECHO \"X${1}\" | $Xsed -e \"$basename\"`\n}\n\n# Generated shell functions inserted here.\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=\"$0\"\n\n# The name of this program:\n# In the unlikely event $progname began with a '-', it would play havoc with\n# func_echo (imagine progname=-n), so we prepend ./ in that case:\nfunc_dirname_and_basename \"$progpath\"\nprogname=$func_basename_result\ncase $progname in\n  -*) progname=./$progname ;;\nesac\n\n# Make sure we have an absolute path for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=$func_dirname_result\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=\"$progdir/$progname\"\n     ;;\n  *)\n     save_IFS=\"$IFS\"\n     IFS=:\n     for progdir in $PATH; do\n       IFS=\"$save_IFS\"\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=\"$save_IFS\"\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=\"$progdir/$progname\"\n     ;;\nesac\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nXsed=\"${SED}\"' -e 1s/^X//'\nsed_quote_subst='s/\\([`\"$\\\\]\\)/\\\\\\1/g'\n\n# Same as above, but do not quote variable references.\ndouble_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Re-`\\' parameter expansions in output of double_quote_subst that were\n# `\\'-ed in input to the same.  If an odd number of `\\' preceded a '$'\n# in input to double_quote_subst, that '$' was protected from expansion.\n# Since each input `\\' is now two `\\'s, look for any number of runs of\n# four `\\'s followed by two `\\'s and then a '$'.  `\\' that '$'.\nbs='\\\\'\nbs2='\\\\\\\\'\nbs4='\\\\\\\\\\\\\\\\'\ndollar='\\$'\nsed_double_backslash=\"\\\n  s/$bs4/&\\\\\n/g\n  s/^$bs2$dollar/$bs&/\n  s/\\\\([^$bs]\\\\)$bs2$dollar/\\\\1$bs2$bs$dollar/g\n  s/\\n//g\"\n\n# Standard options:\nopt_dry_run=false\nopt_help=false\nopt_quiet=false\nopt_verbose=false\nopt_warning=:\n\n# func_echo arg...\n# Echo program name prefixed message, along with the current mode\n# name if it has been set yet.\nfunc_echo ()\n{\n    $ECHO \"$progname${mode+: }$mode: $*\"\n}\n\n# func_verbose arg...\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $opt_verbose && func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n# func_error arg...\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $ECHO \"$progname${mode+: }$mode: \"${1+\"$@\"} 1>&2\n}\n\n# func_warning arg...\n# Echo program name prefixed warning message to standard error.\nfunc_warning ()\n{\n    $opt_warning && $ECHO \"$progname${mode+: }$mode: warning: \"${1+\"$@\"} 1>&2\n\n    # bash bug again:\n    :\n}\n\n# func_fatal_error arg...\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n# func_fatal_help arg...\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    func_error ${1+\"$@\"}\n    func_fatal_error \"$help\"\n}\nhelp=\"Try \\`$progname --help' for more information.\"  ## default\n\n\n# func_grep expression filename\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_mkdir_p directory-path\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    my_directory_path=\"$1\"\n    my_dir_list=\n\n    if test -n \"$my_directory_path\" && test \"$opt_dry_run\" != \":\"; then\n\n      # Protect directory names starting with `-'\n      case $my_directory_path in\n        -*) my_directory_path=\"./$my_directory_path\" ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$my_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        my_dir_list=\"$my_directory_path:$my_dir_list\"\n\n        # If the last portion added has no slash in it, the list is done\n        case $my_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        my_directory_path=`$ECHO \"X$my_directory_path\" | $Xsed -e \"$dirname\"`\n      done\n      my_dir_list=`$ECHO \"X$my_dir_list\" | $Xsed -e 's,:*$,,'`\n\n      save_mkdir_p_IFS=\"$IFS\"; IFS=':'\n      for my_dir in $my_dir_list; do\n\tIFS=\"$save_mkdir_p_IFS\"\n        # mkdir can fail with a `File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$my_dir\" 2>/dev/null || :\n      done\n      IFS=\"$save_mkdir_p_IFS\"\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$my_directory_path\" || \\\n        func_fatal_error \"Failed to create \\`$1'\"\n    fi\n}\n\n\n# func_mktempdir [string]\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, STRING is the basename for that directory.\nfunc_mktempdir ()\n{\n    my_template=\"${TMPDIR-/tmp}/${1-$progname}\"\n\n    if test \"$opt_dry_run\" = \":\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      my_tmpdir=\"${my_template}-$$\"\n    else\n\n      # If mktemp works, use that first and foremost\n      my_tmpdir=`mktemp -d \"${my_template}-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$my_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        my_tmpdir=\"${my_template}-${RANDOM-0}$$\"\n\n        save_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$my_tmpdir\"\n        umask $save_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$my_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory \\`$my_tmpdir'\"\n    fi\n\n    $ECHO \"X$my_tmpdir\" | $Xsed\n}\n\n\n# func_quote_for_eval arg\n# Aesthetically quote ARG to be evaled later.\n# This function returns two values: FUNC_QUOTE_FOR_EVAL_RESULT\n# is double-quoted, suitable for a subsequent eval, whereas\n# FUNC_QUOTE_FOR_EVAL_UNQUOTED_RESULT has merely all characters\n# which are still active within double quotes backslashified.\nfunc_quote_for_eval ()\n{\n    case $1 in\n      *[\\\\\\`\\\"\\$]*)\n\tfunc_quote_for_eval_unquoted_result=`$ECHO \"X$1\" | $Xsed -e \"$sed_quote_subst\"` ;;\n      *)\n        func_quote_for_eval_unquoted_result=\"$1\" ;;\n    esac\n\n    case $func_quote_for_eval_unquoted_result in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting, command substitution and and variable\n      # expansion for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        func_quote_for_eval_result=\"\\\"$func_quote_for_eval_unquoted_result\\\"\"\n        ;;\n      *)\n        func_quote_for_eval_result=\"$func_quote_for_eval_unquoted_result\"\n    esac\n}\n\n\n# func_quote_for_expand arg\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\tmy_arg=`$ECHO \"X$1\" | $Xsed \\\n\t    -e \"$double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        my_arg=\"$1\" ;;\n    esac\n\n    case $my_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        my_arg=\"\\\"$my_arg\\\"\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=\"$my_arg\"\n}\n\n\n# func_show_eval cmd [fail_exp]\n# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    my_cmd=\"$1\"\n    my_fail_exp=\"${2-:}\"\n\n    ${opt_silent-false} || {\n      func_quote_for_expand \"$my_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    if ${opt_dry_run-false}; then :; else\n      eval \"$my_cmd\"\n      my_status=$?\n      if test \"$my_status\" -eq 0; then :; else\n\teval \"(exit $my_status); $my_fail_exp\"\n      fi\n    fi\n}\n\n\n# func_show_eval_locale cmd [fail_exp]\n# Unless opt_silent is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    my_cmd=\"$1\"\n    my_fail_exp=\"${2-:}\"\n\n    ${opt_silent-false} || {\n      func_quote_for_expand \"$my_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    if ${opt_dry_run-false}; then :; else\n      eval \"$lt_user_locale\n\t    $my_cmd\"\n      my_status=$?\n      eval \"$lt_safe_locale\"\n      if test \"$my_status\" -eq 0; then :; else\n\teval \"(exit $my_status); $my_fail_exp\"\n      fi\n    fi\n}\n\n\n\n\n\n# func_version\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $SED -n '/^# '$PROGRAM' (GNU /,/# warranty; / {\n        s/^# //\n\ts/^# *$//\n        s/\\((C)\\)[ 0-9,-]*\\( [1-9][0-9]*\\)/\\1\\2/\n        p\n     }' < \"$progpath\"\n     exit $?\n}\n\n# func_usage\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $SED -n '/^# Usage:/,/# -h/ {\n        s/^# //\n\ts/^# *$//\n\ts/\\$progname/'$progname'/\n\tp\n    }' < \"$progpath\"\n    $ECHO\n    $ECHO \"run \\`$progname --help | more' for full usage\"\n    exit $?\n}\n\n# func_help\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $SED -n '/^# Usage:/,/# Report bugs to/ {\n        s/^# //\n\ts/^# *$//\n\ts*\\$progname*'$progname'*\n\ts*\\$host*'\"$host\"'*\n\ts*\\$SHELL*'\"$SHELL\"'*\n\ts*\\$LTCC*'\"$LTCC\"'*\n\ts*\\$LTCFLAGS*'\"$LTCFLAGS\"'*\n\ts*\\$LD*'\"$LD\"'*\n\ts/\\$with_gnu_ld/'\"$with_gnu_ld\"'/\n\ts/\\$automake_version/'\"`(automake --version) 2>/dev/null |$SED 1q`\"'/\n\ts/\\$autoconf_version/'\"`(autoconf --version) 2>/dev/null |$SED 1q`\"'/\n\tp\n     }' < \"$progpath\"\n    exit $?\n}\n\n# func_missing_arg argname\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    func_error \"missing argument for $1\"\n    exit_cmd=exit\n}\n\nexit_cmd=:\n\n\n\n\n\n# Check that we have a working $ECHO.\nif test \"X$1\" = X--no-reexec; then\n  # Discard the --no-reexec flag, and continue.\n  shift\nelif test \"X$1\" = X--fallback-echo; then\n  # Avoid inline document here, it may be left over\n  :\nelif test \"X`{ $ECHO '\\t'; } 2>/dev/null`\" = 'X\\t'; then\n  # Yippee, $ECHO works!\n  :\nelse\n  # Restart under the correct shell, and then maybe $ECHO will work.\n  exec $SHELL \"$progpath\" --no-reexec ${1+\"$@\"}\nfi\n\nif test \"X$1\" = X--fallback-echo; then\n  # used as fallback echo\n  shift\n  cat <<EOF\n$*\nEOF\n  exit $EXIT_SUCCESS\nfi\n\nmagic=\"%%%MAGIC variable%%%\"\nmagic_exe=\"%%%MAGIC EXE variable%%%\"\n\n# Global variables.\n# $mode is unset\nnonopt=\nexecute_dlfiles=\npreserve_args=\nlo2o=\"s/\\\\.lo\\$/.${objext}/\"\no2lo=\"s/\\\\.${objext}\\$/.lo/\"\nextracted_archives=\nextracted_serial=0\n\nopt_dry_run=false\nopt_duplicate_deps=false\nopt_silent=false\nopt_debug=:\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n# func_fatal_configuration arg...\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func_error ${1+\"$@\"}\n    func_error \"See the $PACKAGE documentation for more information.\"\n    func_fatal_error \"Fatal configuration error.\"\n}\n\n\n# func_config\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n# func_features\n# Display the features supported by this script.\nfunc_features ()\n{\n    $ECHO \"host: $host\"\n    if test \"$build_libtool_libs\" = yes; then\n      $ECHO \"enable shared libraries\"\n    else\n      $ECHO \"disable shared libraries\"\n    fi\n    if test \"$build_old_libs\" = yes; then\n      $ECHO \"enable static libraries\"\n    else\n      $ECHO \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n# func_enable_tag tagname\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n  # Global variable:\n  tagname=\"$1\"\n\n  re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n  re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n  sed_extractcf=\"/$re_begincf/,/$re_endcf/p\"\n\n  # Validate tagname.\n  case $tagname in\n    *[!-_A-Za-z0-9,/]*)\n      func_fatal_error \"invalid tag name: $tagname\"\n      ;;\n  esac\n\n  # Don't test for the \"default\" C tag, as we know it's\n  # there but not specially marked.\n  case $tagname in\n    CC) ;;\n    *)\n      if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\ttaglist=\"$taglist $tagname\"\n\n\t# Evaluate the configuration.  Be careful to quote the path\n\t# and the sed script, to avoid splitting on whitespace, but\n\t# also don't use non-portable quotes within backquotes within\n\t# quotes we have to do it in 2 steps:\n\textractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\teval \"$extractedcf\"\n      else\n\tfunc_error \"ignoring unknown tag $tagname\"\n      fi\n      ;;\n  esac\n}\n\n# Parse options once, thoroughly.  This comes as soon as possible in\n# the script to make things like `libtool --version' happen quickly.\n{\n\n  # Shorthand for --mode=foo, only valid as the first argument\n  case $1 in\n  clean|clea|cle|cl)\n    shift; set dummy --mode clean ${1+\"$@\"}; shift\n    ;;\n  compile|compil|compi|comp|com|co|c)\n    shift; set dummy --mode compile ${1+\"$@\"}; shift\n    ;;\n  execute|execut|execu|exec|exe|ex|e)\n    shift; set dummy --mode execute ${1+\"$@\"}; shift\n    ;;\n  finish|finis|fini|fin|fi|f)\n    shift; set dummy --mode finish ${1+\"$@\"}; shift\n    ;;\n  install|instal|insta|inst|ins|in|i)\n    shift; set dummy --mode install ${1+\"$@\"}; shift\n    ;;\n  link|lin|li|l)\n    shift; set dummy --mode link ${1+\"$@\"}; shift\n    ;;\n  uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n    shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n    ;;\n  esac\n\n  # Parse non-mode specific arguments:\n  while test \"$#\" -gt 0; do\n    opt=\"$1\"\n    shift\n\n    case $opt in\n      --config)\t\tfunc_config\t\t\t\t\t;;\n\n      --debug)\t\tpreserve_args=\"$preserve_args $opt\"\n\t\t\tfunc_echo \"enabling shell trace mode\"\n\t\t\topt_debug='set -x'\n\t\t\t$opt_debug\n\t\t\t;;\n\n      -dlopen)\t\ttest \"$#\" -eq 0 && func_missing_arg \"$opt\" && break\n\t\t\texecute_dlfiles=\"$execute_dlfiles $1\"\n\t\t\tshift\n\t\t\t;;\n\n      --dry-run | -n)\topt_dry_run=:\t\t\t\t\t;;\n      --features)       func_features\t\t\t\t\t;;\n      --finish)\t\tmode=\"finish\"\t\t\t\t\t;;\n\n      --mode)\t\ttest \"$#\" -eq 0 && func_missing_arg \"$opt\" && break\n\t\t\tcase $1 in\n\t\t\t  # Valid mode arguments:\n\t\t\t  clean)\t;;\n\t\t\t  compile)\t;;\n\t\t\t  execute)\t;;\n\t\t\t  finish)\t;;\n\t\t\t  install)\t;;\n\t\t\t  link)\t\t;;\n\t\t\t  relink)\t;;\n\t\t\t  uninstall)\t;;\n\n\t\t\t  # Catch anything else as an error\n\t\t\t  *) func_error \"invalid argument for $opt\"\n\t\t\t     exit_cmd=exit\n\t\t\t     break\n\t\t\t     ;;\n\t\t        esac\n\n\t\t\tmode=\"$1\"\n\t\t\tshift\n\t\t\t;;\n\n      --preserve-dup-deps)\n\t\t\topt_duplicate_deps=:\t\t\t\t;;\n\n      --quiet|--silent)\tpreserve_args=\"$preserve_args $opt\"\n\t\t\topt_silent=:\n\t\t\t;;\n\n      --verbose| -v)\tpreserve_args=\"$preserve_args $opt\"\n\t\t\topt_silent=false\n\t\t\t;;\n\n      --tag)\t\ttest \"$#\" -eq 0 && func_missing_arg \"$opt\" && break\n\t\t\tpreserve_args=\"$preserve_args $opt $1\"\n\t\t\tfunc_enable_tag \"$1\"\t# tagname is set here\n\t\t\tshift\n\t\t\t;;\n\n      # Separate optargs to long options:\n      -dlopen=*|--mode=*|--tag=*)\n\t\t\tfunc_opt_split \"$opt\"\n\t\t\tset dummy \"$func_opt_split_opt\" \"$func_opt_split_arg\" ${1+\"$@\"}\n\t\t\tshift\n\t\t\t;;\n\n      -\\?|-h)\t\tfunc_usage\t\t\t\t\t;;\n      --help)\t\topt_help=:\t\t\t\t\t;;\n      --version)\tfunc_version\t\t\t\t\t;;\n\n      -*)\t\tfunc_fatal_help \"unrecognized option \\`$opt'\"\t;;\n\n      *)\t\tnonopt=\"$opt\"\n\t\t\tbreak\n\t\t\t;;\n    esac\n  done\n\n\n  case $host in\n    *cygwin* | *mingw* | *pw32* | *cegcc*)\n      # don't eliminate duplications in $postdeps and $predeps\n      opt_duplicate_compiler_generated_deps=:\n      ;;\n    *)\n      opt_duplicate_compiler_generated_deps=$opt_duplicate_deps\n      ;;\n  esac\n\n  # Having warned about all mis-specified options, bail out if\n  # anything was wrong.\n  $exit_cmd $EXIT_FAILURE\n}\n\n# func_check_version_match\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n  if test \"$package_revision\" != \"$macro_revision\"; then\n    if test \"$VERSION\" != \"$macro_version\"; then\n      if test -z \"$macro_version\"; then\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n      fi\n    else\n      cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n    fi\n\n    exit $EXIT_MISMATCH\n  fi\n}\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\n$opt_help || {\n  # Sanity checks first:\n  func_check_version_match\n\n  if test \"$build_libtool_libs\" != yes && test \"$build_old_libs\" != yes; then\n    func_fatal_configuration \"not configured to build any kind of library\"\n  fi\n\n  test -z \"$mode\" && func_fatal_error \"error: you must specify a MODE.\"\n\n\n  # Darwin sucks\n  eval std_shrext=\\\"$shrext_cmds\\\"\n\n\n  # Only execute mode is allowed to have -dlopen flags.\n  if test -n \"$execute_dlfiles\" && test \"$mode\" != execute; then\n    func_error \"unrecognized option \\`-dlopen'\"\n    $ECHO \"$help\" 1>&2\n    exit $EXIT_FAILURE\n  fi\n\n  # Change the help message to a mode-specific one.\n  generic_help=\"$help\"\n  help=\"Try \\`$progname --help --mode=$mode' for more information.\"\n}\n\n\n# func_lalib_p file\n# True iff FILE is a libtool `.la' library or `.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null \\\n        | $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool `.la' library or `.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if `file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case \"$lalib_p_line\" in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test \"$lalib_p\" = yes\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    func_lalib_p \"$1\"\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_ltwrapper_scriptname_result=\"\"\n    if func_ltwrapper_executable_p \"$1\"; then\n\tfunc_dirname_and_basename \"$1\" \"\" \".\"\n\tfunc_stripname '' '.exe' \"$func_basename_result\"\n\tfunc_ltwrapper_scriptname_result=\"$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\"\n    fi\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $opt_debug\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$save_ifs\n      eval cmd=\\\"$cmd\\\"\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# `FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $opt_debug\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $opt_debug\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n        func_quote_for_eval \"$arg\"\n\tCC_quoted=\"$CC_quoted $func_quote_for_eval_result\"\n      done\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" `$ECHO $CC` \"* | \"`$ECHO $CC` \"* | \" $CC_quoted\"* | \"$CC_quoted \"* | \" `$ECHO $CC_quoted` \"* | \"`$ECHO $CC_quoted` \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`${SED} -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_quote_for_eval \"$arg\"\n\t      CC_quoted=\"$CC_quoted $func_quote_for_eval_result\"\n\t    done\n\t    case \"$@ \" in\n\t      \" $CC \"* | \"$CC \"* | \" `$ECHO $CC` \"* | \"`$ECHO $CC` \"* | \" $CC_quoted\"* | \"$CC_quoted \"* | \" `$ECHO $CC_quoted` \"* | \"`$ECHO $CC_quoted` \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with \\`--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=${1}\n    if test \"$build_libtool_libs\" = yes; then\n      write_lobj=\\'${2}\\'\n    else\n      write_lobj=none\n    fi\n\n    if test \"$build_old_libs\" = yes; then\n      write_oldobj=\\'${3}\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"${write_libobj}\"\n    }\n}\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $opt_debug\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=\"$nonopt\"  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=\"$arg\"\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=\"$arg\"\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify \\`-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          pie_flag=\"$pie_flag $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  later=\"$later $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=\"$IFS\"; IFS=','\n\t  for arg in $args; do\n\t    IFS=\"$save_ifs\"\n\t    func_quote_for_eval \"$arg\"\n\t    lastarg=\"$lastarg $func_quote_for_eval_result\"\n\t  done\n\t  IFS=\"$save_ifs\"\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  base_compile=\"$base_compile $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=\"$srcfile\"\n\t  srcfile=\"$arg\"\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_quote_for_eval \"$lastarg\"\n      base_compile=\"$base_compile $func_quote_for_eval_result\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with \\`-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=\"$func_basename_result\"\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.obj | *.sx)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from \\`$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest \"$build_libtool_libs\" != yes && \\\n\t  func_fatal_configuration \"can not build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name \\`$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=\"$func_basename_result\"\n    xdir=\"$func_dirname_result\"\n    lobj=${xdir}$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test \"$build_old_libs\" = yes; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test \"$pic_mode\" = no && test \"$deplibs_check_method\" != pass_all; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test \"$compiler_c_o\" = no; then\n      output_obj=`$ECHO \"X$srcfile\" | $Xsed -e 's%^.*/%%' -e 's%\\.[^.]*$%%'`.${objext}\n      lockfile=\"$output_obj.lock\"\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test \"$need_locks\" = yes; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test \"$need_locks\" = warn; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      removelist=\"$removelist $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    removelist=\"$removelist $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    if test -n \"$fix_srcfile_path\"; then\n      eval srcfile=\\\"$fix_srcfile_path\\\"\n    fi\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test \"$build_libtool_libs\" = yes; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test \"$pic_mode\" != no; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tcommand=\"$command -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test \"$need_locks\" = warn &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test \"$suppress_opt\" = yes; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test \"$build_old_libs\" = yes; then\n      if test \"$pic_mode\" != yes; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test \"$compiler_c_o\" = yes; then\n\tcommand=\"$command -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      command=\"$command$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test \"$need_locks\" = warn &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support \\`-c' and \\`-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test \"$need_locks\" != no; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\ntest \"$mode\" = compile && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically \\`/bin/rm').  RM-OPTIONS are options (such as \\`-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to building PIC objects only\n  -prefer-non-pic   try to building non-PIC objects only\n  -shared           do not build a \\`.o' file suitable for static linking\n  -static           only build a \\`.o' file suitable for static linking\n\nCOMPILE-COMMAND is a command to be used in creating a \\`standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix \\`.c' with the\nlibrary object suffix, \\`.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to \\`-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe \\`--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the \\`install' or \\`cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -dlopen FILE      \\`-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  Use a list of object files found in FILE to specify objects\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n\nAll other options (arguments beginning with \\`-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in \\`.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in \\`.la', then a libtool library is created,\nonly library objects (\\`.lo' files) may be specified, and \\`-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in \\`.a' or \\`.lib', then a standard library is created\nusing \\`ar' and \\`ranlib', or on Windows using \\`lib'.\n\nIf OUTPUT-FILE ends in \\`.lo' or \\`.${objext}', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically \\`/bin/rm').  RM-OPTIONS are options (such as \\`-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode \\`$mode'\"\n        ;;\n    esac\n\n    $ECHO\n    $ECHO \"Try \\`$progname --help' for more information about other modes.\"\n\n    exit $?\n}\n\n  # Now that we've collected a possible --mode arg, show help if necessary\n  $opt_help && func_mode_help\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $opt_debug\n    # The first argument is the command name.\n    cmd=\"$nonopt\"\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $execute_dlfiles; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"\\`$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"\\`$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"\\`$file' was not linked with \\`-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=\"$func_dirname_result\"\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  dir=\"$dir/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find \\`$dlname' in \\`$dir' or \\`$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=\"$func_dirname_result\"\n\t;;\n\n      *)\n\tfunc_warning \"\\`-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=\"$absdir\"\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=\"$magic\"\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -*) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=\"$progdir/$program\"\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=\"$progdir/$program\"\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_quote_for_eval \"$file\"\n      args=\"$args $func_quote_for_eval_result\"\n    done\n\n    if test \"X$opt_dry_run\" = Xfalse; then\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\"\\$cmd$args\"\n    else\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\t$ECHO \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest \"$mode\" = execute && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $opt_debug\n    libdirs=\"$nonopt\"\n    admincmds=\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for dir\n      do\n\tlibdirs=\"$libdirs $dir\"\n      done\n\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || admincmds=\"$admincmds\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_silent && exit $EXIT_SUCCESS\n\n    $ECHO \"X----------------------------------------------------------------------\" | $Xsed\n    $ECHO \"Libraries have been installed in:\"\n    for libdir in $libdirs; do\n      $ECHO \"   $libdir\"\n    done\n    $ECHO\n    $ECHO \"If you ever happen to want to link against installed libraries\"\n    $ECHO \"in a given directory, LIBDIR, you must either use libtool, and\"\n    $ECHO \"specify the full pathname of the library, or use the \\`-LLIBDIR'\"\n    $ECHO \"flag during linking and do at least one of the following:\"\n    if test -n \"$shlibpath_var\"; then\n      $ECHO \"   - add LIBDIR to the \\`$shlibpath_var' environment variable\"\n      $ECHO \"     during execution\"\n    fi\n    if test -n \"$runpath_var\"; then\n      $ECHO \"   - add LIBDIR to the \\`$runpath_var' environment variable\"\n      $ECHO \"     during linking\"\n    fi\n    if test -n \"$hardcode_libdir_flag_spec\"; then\n      libdir=LIBDIR\n      eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n      $ECHO \"   - use the \\`$flag' linker flag\"\n    fi\n    if test -n \"$admincmds\"; then\n      $ECHO \"   - have your system administrator run these commands:$admincmds\"\n    fi\n    if test -f /etc/ld.so.conf; then\n      $ECHO \"   - have your system administrator add LIBDIR to \\`/etc/ld.so.conf'\"\n    fi\n    $ECHO\n\n    $ECHO \"See any operating system documentation about shared libraries for\"\n    case $host in\n      solaris2.[6789]|solaris2.1[0-9])\n        $ECHO \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t$ECHO \"pages.\"\n\t;;\n      *)\n        $ECHO \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n        ;;\n    esac\n    $ECHO \"X----------------------------------------------------------------------\" | $Xsed\n    exit $EXIT_SUCCESS\n}\n\ntest \"$mode\" = finish && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $opt_debug\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$nonopt\" = \"$SHELL\" || test \"$nonopt\" = /bin/sh ||\n       # Allow the use of GNU shtool's install command.\n       $ECHO \"X$nonopt\" | $GREP shtool >/dev/null; then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    install_prog=\"$install_prog$func_quote_for_eval_result\"\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=no\n    stripme=\n    for arg\n    do\n      if test -n \"$dest\"; then\n\tfiles=\"$files $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=yes ;;\n      -f)\n\tcase \" $install_prog \" in\n\t*[\\\\\\ /]cp\\ *) ;;\n\t*) prev=$arg ;;\n\tesac\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      install_prog=\"$install_prog $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the \\`$prev' option requires an argument\"\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=yes\n    if test \"$isdir\" = yes; then\n      destdir=\"$dest\"\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=\"$func_dirname_result\"\n      destname=\"$func_basename_result\"\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"\\`$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"\\`$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=\"$magic\"\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tstaticlibs=\"$staticlibs $file\"\n\t;;\n\n      *.la)\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"\\`$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) current_libdirs=\"$current_libdirs $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) future_libdirs=\"$future_libdirs $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=\"$func_dirname_result\"\n\tdir=\"$dir$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"X$destdir\" | $Xsed -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install \\`$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"X$relink_command\" | $Xsed -e \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"X$relink_command\" | $Xsed -e \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking \\`$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink \\`$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=\"$1\"\n\t  shift\n\n\t  srcname=\"$realname\"\n\t  test -n \"$relink_command\" && srcname=\"$realname\"T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=\"$stripme\"\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\"\"\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try `ln -sf' first, because the `ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=\"$destdir/$realname\"\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=\"$func_basename_result\"\n\tinstname=\"$dir/$name\"i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && staticlibs=\"$staticlibs $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=\"$destdir/$destname\"\n\telse\n\t  func_basename \"$file\"\n\t  destfile=\"$func_basename_result\"\n\t  destfile=\"$destdir/$destfile\"\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=\"$destfile\"\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to \\`$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test \"$build_old_libs\" = yes; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=\"$destdir/$destname\"\n\telse\n\t  func_basename \"$file\"\n\t  destfile=\"$func_basename_result\"\n\t  destfile=\"$destdir/$destfile\"\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\"\"\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=\".exe\"\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script \\`$wrapper'\"\n\n\t  finalize=yes\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=\"$libdir/\"`$ECHO \"X$lib\" | $Xsed -e 's%^.*/%%g'` ### testsuite: skip nested quoting test\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"\\`$lib' has not been installed in \\`$libdir'\"\n\t      finalize=no\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test \"$fast_install\" = no && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if test \"$finalize\" = yes; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=\"$func_basename_result\"\n\t        outputname=\"$tmpdir/$file\"\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"X$relink_command\" | $Xsed -e 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_silent || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink \\`$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=\"$outputname\"\n\t      else\n\t        func_warning \"cannot relink \\`$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"X$file$stripped_ext\" | $Xsed -e \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=\"$func_basename_result\"\n\n      # Set up the ranlib parameters.\n      oldlib=\"$destdir/$name\"\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run \\`$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL $progpath $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest \"$mode\" = install && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $opt_debug\n    my_outputname=\"$1\"\n    my_originator=\"$2\"\n    my_pic_p=\"${3-no}\"\n    my_prefix=`$ECHO \"$my_originator\" | sed 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=\"${my_outputname}S.c\"\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=\"$output_objdir/${my_outputname}.nm\"\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for \\`$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test \"$dlself\" = yes; then\n\t  func_verbose \"generating symbol list for \\`$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"X$objs$old_deplibs\" | $SP2NL | $Xsed -e \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_verbose \"extracting global C symbols from \\`$progfile'\"\n\t    $opt_dry_run || eval \"$NM $progfile | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=\"$output_objdir/$outputname.exp\"\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"${SED} -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"${SED} -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from \\`$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=\"$func_basename_result\"\n\t  $opt_dry_run || {\n\t    eval '$ECHO \": $name \" >> \"$nlist\"'\n\t    eval \"$NM $dlprefile 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t  }\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    $ECHO '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  $ECHO >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\n\"\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* )\n\t    $ECHO >> \"$output_objdir/$my_dlsyms\" \"\\\n/* DATA imports from DLLs on WIN32 con't be const, because\n   runtime relocations are performed -- see ld's documentation\n   on pseudo-relocs.  */\"\n\t    lt_dlsym_const= ;;\n\t  *osf5*)\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n/* This system does not cope well with relocations in const data */\"\n\t    lt_dlsym_const= ;;\n\t  *)\n\t    lt_dlsym_const=const ;;\n\t  esac\n\n\t  $ECHO >> \"$output_objdir/$my_dlsyms\" \"\\\nextern $lt_dlsym_const lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\n$lt_dlsym_const lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{\\\n  { \\\"$my_originator\\\", (void *) 0 },\"\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  $ECHO >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    if test \"X$my_pic_p\" != Xno; then\n\t      pic_flag_for_symtable=\" $pic_flag\"\n\t    fi\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) symtab_cflags=\"$symtab_cflags $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=\"$output_objdir/${my_outputname}S.$objext\"\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"X$compile_command\" | $Xsed -e \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"X$finalize_command\" | $Xsed -e \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"X$compile_command\" | $Xsed -e \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"X$finalize_command\" | $Xsed -e \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"X$compile_command\" | $Xsed -e \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"X$finalize_command\" | $Xsed -e \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for \\`$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"X$compile_command\" | $Xsed -e \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"X$finalize_command\" | $Xsed -e \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\nfunc_win32_libid ()\n{\n  $opt_debug\n  win32_libid_type=\"unknown\"\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format pe-i386(.*architecture: i386)?' >/dev/null ; then\n      win32_nmres=`eval $NM -f posix -A $1 |\n\t$SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s,.*,import,\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $opt_debug\n    f_ex_an_ar_dir=\"$1\"; shift\n    f_ex_an_ar_oldlib=\"$1\"\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" 'exit $?'\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $opt_debug\n    my_gentop=\"$1\"; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\"\"\n    my_xlib=\"\"\n    my_xabs=\"\"\n    my_xdir=\"\"\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=\"$my_xlib\" ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=\"$func_basename_result\"\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=\"$my_gentop/$my_xlib_u\"\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  darwin_base_archive=`basename \"$darwin_archive\"`\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches ; do\n\t      func_mkdir_p \"unfat-$$/${darwin_base_archive}-${darwin_arch}\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}\" \"${darwin_archive}\"\n\t      cd \"unfat-$$/${darwin_base_archive}-${darwin_arch}\"\n\t      func_extract_an_archive \"`pwd`\" \"${darwin_base_archive}\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/${darwin_base_archive}-${darwin_arch}/${darwin_base_archive}\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | $NL2SP`\n    done\n\n    func_extract_archives_result=\"$my_oldobjs\"\n}\n\n\n\n# func_emit_wrapper_part1 [arg=no]\n#\n# Emit the first part of a libtool wrapper script on stdout.\n# For more information, see the description associated with\n# func_emit_wrapper(), below.\nfunc_emit_wrapper_part1 ()\n{\n\tfunc_emit_wrapper_part1_arg1=no\n\tif test -n \"$1\" ; then\n\t  func_emit_wrapper_part1_arg1=$1\n\tfi\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nXsed='${SED} -e 1s/^X//'\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    ECHO=\\\"$qecho\\\"\n    file=\\\"\\$0\\\"\n    # Make sure echo works.\n    if test \\\"X\\$1\\\" = X--no-reexec; then\n      # Discard the --no-reexec flag, and continue.\n      shift\n    elif test \\\"X\\`{ \\$ECHO '\\t'; } 2>/dev/null\\`\\\" = 'X\\t'; then\n      # Yippee, \\$ECHO works!\n      :\n    else\n      # Restart under the correct shell, and then maybe \\$ECHO will work.\n      exec $SHELL \\\"\\$0\\\" --no-reexec \\${1+\\\"\\$@\\\"}\n    fi\n  fi\\\n\"\n\t$ECHO \"\\\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"X\\$file\\\" | \\$Xsed -e 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | ${SED} -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"X\\$file\\\" | \\$Xsed -e 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"X\\$file\\\" | \\$Xsed -e 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | ${SED} -n 's/.*-> //p'\\`\n  done\n\"\n}\n# end: func_emit_wrapper_part1\n\n# func_emit_wrapper_part2 [arg=no]\n#\n# Emit the second part of a libtool wrapper script on stdout.\n# For more information, see the description associated with\n# func_emit_wrapper(), below.\nfunc_emit_wrapper_part2 ()\n{\n\tfunc_emit_wrapper_part2_arg1=no\n\tif test -n \"$1\" ; then\n\t  func_emit_wrapper_part2_arg1=$1\n\tfi\n\n\t$ECHO \"\\\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_part2_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"X\\$thisdir\\\" | \\$Xsed -e 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test \"$fast_install\" = yes; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | ${SED} 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# Export our shlibpath_var if we have one.\n\tif test \"$shlibpath_overrides_runpath\" = yes && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"X\\$$shlibpath_var\\\" | \\$Xsed -e 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t# fixup the dll searchpath if we need to.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n\"\n\tcase $host in\n\t# Backslashes separate directories on plain windows\n\t*-*-mingw | *-*-os2* | *-cegcc*)\n\t  $ECHO \"\\\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n\t  ;;\n\n\t*)\n\t  $ECHO \"\\\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n\t  ;;\n\tesac\n\t$ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: \\\\\\`\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    $ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n# end: func_emit_wrapper_part2\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory in which it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=no\n\tif test -n \"$1\" ; then\n\t  func_emit_wrapper_arg1=$1\n\tfi\n\n\t# split this up so that func_emit_cwrapperexe_src\n\t# can call each part independently.\n\tfunc_emit_wrapper_part1 \"${func_emit_wrapper_arg1}\"\n\tfunc_emit_wrapper_part2 \"${func_emit_wrapper_arg1}\"\n}\n\n\n# func_to_host_path arg\n#\n# Convert paths to host format when used with build tools.\n# Intended for use with \"native\" mingw (where libtool itself\n# is running under the msys shell), or in the following cross-\n# build environments:\n#    $build          $host\n#    mingw (msys)    mingw  [e.g. native]\n#    cygwin          mingw\n#    *nix + wine     mingw\n# where wine is equipped with the `winepath' executable.\n# In the native mingw case, the (msys) shell automatically\n# converts paths for any non-msys applications it launches,\n# but that facility isn't available from inside the cwrapper.\n# Similar accommodations are necessary for $host mingw and\n# $build cygwin.  Calling this function does no harm for other\n# $host/$build combinations not listed above.\n#\n# ARG is the path (on $build) that should be converted to\n# the proper representation for $host. The result is stored\n# in $func_to_host_path_result.\nfunc_to_host_path ()\n{\n  func_to_host_path_result=\"$1\"\n  if test -n \"$1\" ; then\n    case $host in\n      *mingw* )\n        lt_sed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n        case $build in\n          *mingw* ) # actually, msys\n            # awkward: cmd appends spaces to result\n            lt_sed_strip_trailing_spaces=\"s/[ ]*\\$//\"\n            func_to_host_path_tmp1=`( cmd //c echo \"$1\" |\\\n              $SED -e \"$lt_sed_strip_trailing_spaces\" ) 2>/dev/null || echo \"\"`\n            func_to_host_path_result=`echo \"$func_to_host_path_tmp1\" |\\\n              $SED -e \"$lt_sed_naive_backslashify\"`\n            ;;\n          *cygwin* )\n            func_to_host_path_tmp1=`cygpath -w \"$1\"`\n            func_to_host_path_result=`echo \"$func_to_host_path_tmp1\" |\\\n              $SED -e \"$lt_sed_naive_backslashify\"`\n            ;;\n          * )\n            # Unfortunately, winepath does not exit with a non-zero\n            # error code, so we are forced to check the contents of\n            # stdout. On the other hand, if the command is not\n            # found, the shell will set an exit code of 127 and print\n            # *an error message* to stdout. So we must check for both\n            # error code of zero AND non-empty stdout, which explains\n            # the odd construction:\n            func_to_host_path_tmp1=`winepath -w \"$1\" 2>/dev/null`\n            if test \"$?\" -eq 0 && test -n \"${func_to_host_path_tmp1}\"; then\n              func_to_host_path_result=`echo \"$func_to_host_path_tmp1\" |\\\n                $SED -e \"$lt_sed_naive_backslashify\"`\n            else\n              # Allow warning below.\n              func_to_host_path_result=\"\"\n            fi\n            ;;\n        esac\n        if test -z \"$func_to_host_path_result\" ; then\n          func_error \"Could not determine host path corresponding to\"\n          func_error \"  '$1'\"\n          func_error \"Continuing, but uninstalled executables may not work.\"\n          # Fallback:\n          func_to_host_path_result=\"$1\"\n        fi\n        ;;\n    esac\n  fi\n}\n# end: func_to_host_path\n\n# func_to_host_pathlist arg\n#\n# Convert pathlists to host format when used with build tools.\n# See func_to_host_path(), above. This function supports the\n# following $build/$host combinations (but does no harm for\n# combinations not listed here):\n#    $build          $host\n#    mingw (msys)    mingw  [e.g. native]\n#    cygwin          mingw\n#    *nix + wine     mingw\n#\n# Path separators are also converted from $build format to\n# $host format. If ARG begins or ends with a path separator\n# character, it is preserved (but converted to $host format)\n# on output.\n#\n# ARG is a pathlist (on $build) that should be converted to\n# the proper representation on $host. The result is stored\n# in $func_to_host_pathlist_result.\nfunc_to_host_pathlist ()\n{\n  func_to_host_pathlist_result=\"$1\"\n  if test -n \"$1\" ; then\n    case $host in\n      *mingw* )\n        lt_sed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n        # Remove leading and trailing path separator characters from\n        # ARG. msys behavior is inconsistent here, cygpath turns them\n        # into '.;' and ';.', and winepath ignores them completely.\n        func_to_host_pathlist_tmp2=\"$1\"\n        # Once set for this call, this variable should not be\n        # reassigned. It is used in tha fallback case.\n        func_to_host_pathlist_tmp1=`echo \"$func_to_host_pathlist_tmp2\" |\\\n          $SED -e 's|^:*||' -e 's|:*$||'`\n        case $build in\n          *mingw* ) # Actually, msys.\n            # Awkward: cmd appends spaces to result.\n            lt_sed_strip_trailing_spaces=\"s/[ ]*\\$//\"\n            func_to_host_pathlist_tmp2=`( cmd //c echo \"$func_to_host_pathlist_tmp1\" |\\\n              $SED -e \"$lt_sed_strip_trailing_spaces\" ) 2>/dev/null || echo \"\"`\n            func_to_host_pathlist_result=`echo \"$func_to_host_pathlist_tmp2\" |\\\n              $SED -e \"$lt_sed_naive_backslashify\"`\n            ;;\n          *cygwin* )\n            func_to_host_pathlist_tmp2=`cygpath -w -p \"$func_to_host_pathlist_tmp1\"`\n            func_to_host_pathlist_result=`echo \"$func_to_host_pathlist_tmp2\" |\\\n              $SED -e \"$lt_sed_naive_backslashify\"`\n            ;;\n          * )\n            # unfortunately, winepath doesn't convert pathlists\n            func_to_host_pathlist_result=\"\"\n            func_to_host_pathlist_oldIFS=$IFS\n            IFS=:\n            for func_to_host_pathlist_f in $func_to_host_pathlist_tmp1 ; do\n              IFS=$func_to_host_pathlist_oldIFS\n              if test -n \"$func_to_host_pathlist_f\" ; then\n                func_to_host_path \"$func_to_host_pathlist_f\"\n                if test -n \"$func_to_host_path_result\" ; then\n                  if test -z \"$func_to_host_pathlist_result\" ; then\n                    func_to_host_pathlist_result=\"$func_to_host_path_result\"\n                  else\n                    func_to_host_pathlist_result=\"$func_to_host_pathlist_result;$func_to_host_path_result\"\n                  fi\n                fi\n              fi\n              IFS=:\n            done\n            IFS=$func_to_host_pathlist_oldIFS\n            ;;\n        esac\n        if test -z \"$func_to_host_pathlist_result\" ; then\n          func_error \"Could not determine the host path(s) corresponding to\"\n          func_error \"  '$1'\"\n          func_error \"Continuing, but uninstalled executables may not work.\"\n          # Fallback. This may break if $1 contains DOS-style drive\n          # specifications. The fix is not to complicate the expression\n          # below, but for the user to provide a working wine installation\n          # with winepath so that path translation in the cross-to-mingw\n          # case works properly.\n          lt_replace_pathsep_nix_to_dos=\"s|:|;|g\"\n          func_to_host_pathlist_result=`echo \"$func_to_host_pathlist_tmp1\" |\\\n            $SED -e \"$lt_replace_pathsep_nix_to_dos\"`\n        fi\n        # Now, add the leading and trailing path separators back\n        case \"$1\" in\n          :* ) func_to_host_pathlist_result=\";$func_to_host_pathlist_result\"\n            ;;\n        esac\n        case \"$1\" in\n          *: ) func_to_host_pathlist_result=\"$func_to_host_pathlist_result;\"\n            ;;\n        esac\n        ;;\n    esac\n  fi\n}\n# end: func_to_host_pathlist\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n\n   Currently, it simply execs the wrapper *script* \"$SHELL $output\",\n   but could eventually absorb all of the scripts functionality and\n   exec $objdir/$outputname directly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n# define setmode _setmode\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n#  define HAVE_SETENV\n#  ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n#  endif\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#if defined(PATH_MAX)\n# define LT_PATHMAX PATH_MAX\n#elif defined(MAXPATHLEN)\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n#ifdef _MSC_VER\n# define S_IXUSR _S_IEXEC\n# define stat _stat\n# ifndef _INTPTR_T_DEFINED\n#  define intptr_t int\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined (_WIN32) || defined (__MSDOS__) || defined (__DJGPP__) || \\\n  defined (__OS2__)\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifdef __CYGWIN__\n# define FOPEN_WB \"wb\"\n#endif\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free ((void *) stale); stale = 0; } \\\n} while (0)\n\n#undef LTWRAPPER_DEBUGPRINTF\n#if defined DEBUGWRAPPER\n# define LTWRAPPER_DEBUGPRINTF(args) ltwrapper_debugprintf args\nstatic void\nltwrapper_debugprintf (const char *fmt, ...)\n{\n    va_list args;\n    va_start (args, fmt);\n    (void) vfprintf (stderr, fmt, args);\n    va_end (args);\n}\n#else\n# define LTWRAPPER_DEBUGPRINTF(args)\n#endif\n\nconst char *program_name = NULL;\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_fatal (const char *message, ...);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_opt_process_env_set (const char *arg);\nvoid lt_opt_process_env_prepend (const char *arg);\nvoid lt_opt_process_env_append (const char *arg);\nint lt_split_name_value (const char *arg, char** name, char** value);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\n\nstatic const char *script_text_part1 =\nEOF\n\n\t    func_emit_wrapper_part1 yes |\n\t        $SED -e 's/\\([\\\\\"]\\)/\\\\\\1/g' \\\n\t             -e 's/^/  \"/' -e 's/$/\\\\n\"/'\n\t    echo \";\"\n\t    cat <<EOF\n\nstatic const char *script_text_part2 =\nEOF\n\t    func_emit_wrapper_part2 yes |\n\t        $SED -e 's/\\([\\\\\"]\\)/\\\\\\1/g' \\\n\t             -e 's/^/  \"/' -e 's/$/\\\\n\"/'\n\t    echo \";\"\n\n\t    cat <<EOF\nconst char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test \"$shlibpath_overrides_runpath\" = yes && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_pathlist \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_pathlist_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_pathlist \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_pathlist_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test \"$fast_install\" = yes; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n#define LTWRAPPER_OPTION_PREFIX_LENGTH  5\n\nstatic const size_t opt_prefix_len         = LTWRAPPER_OPTION_PREFIX_LENGTH;\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\n\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\n\nstatic const size_t env_set_opt_len     = LTWRAPPER_OPTION_PREFIX_LENGTH + 7;\nstatic const char *env_set_opt          = LTWRAPPER_OPTION_PREFIX \"env-set\";\n  /* argument is putenv-style \"foo=bar\", value of foo is set to bar */\n\nstatic const size_t env_prepend_opt_len = LTWRAPPER_OPTION_PREFIX_LENGTH + 11;\nstatic const char *env_prepend_opt      = LTWRAPPER_OPTION_PREFIX \"env-prepend\";\n  /* argument is putenv-style \"foo=bar\", new value of foo is bar${foo} */\n\nstatic const size_t env_append_opt_len  = LTWRAPPER_OPTION_PREFIX_LENGTH + 10;\nstatic const char *env_append_opt       = LTWRAPPER_OPTION_PREFIX \"env-append\";\n  /* argument is putenv-style \"foo=bar\", new value of foo is ${foo}bar */\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  intptr_t rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  LTWRAPPER_DEBUGPRINTF ((\"(main) argv[0]      : %s\\n\", argv[0]));\n  LTWRAPPER_DEBUGPRINTF ((\"(main) program_name : %s\\n\", program_name));\n\n  /* very simple arg parsing; don't want to rely on getopt */\n  for (i = 1; i < argc; i++)\n    {\n      if (strcmp (argv[i], dumpscript_opt) == 0)\n\t{\nEOF\n\t    case \"$host\" in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  printf (\"%s\", script_text_part1);\n\t  printf (\"%s\", script_text_part2);\n\t  return 0;\n\t}\n    }\n\n  newargz = XMALLOC (char *, argc + 1);\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (\"Couldn't find %s\", argv[0]);\n  LTWRAPPER_DEBUGPRINTF ((\"(main) found exe (before symlink chase) at : %s\\n\",\n\t\t\t  tmp_pathspec));\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  LTWRAPPER_DEBUGPRINTF ((\"(main) found exe (after symlink chase) at : %s\\n\",\n\t\t\t  actual_cwrapper_path));\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup( base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  LTWRAPPER_DEBUGPRINTF ((\"(main) libtool target name: %s\\n\",\n\t\t\t  target_name));\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (strncmp (argv[i], env_set_opt, env_set_opt_len) == 0)\n        {\n          if (argv[i][env_set_opt_len] == '=')\n            {\n              const char *p = argv[i] + env_set_opt_len + 1;\n              lt_opt_process_env_set (p);\n            }\n          else if (argv[i][env_set_opt_len] == '\\0' && i + 1 < argc)\n            {\n              lt_opt_process_env_set (argv[++i]); /* don't copy */\n            }\n          else\n            lt_fatal (\"%s missing required argument\", env_set_opt);\n          continue;\n        }\n      if (strncmp (argv[i], env_prepend_opt, env_prepend_opt_len) == 0)\n        {\n          if (argv[i][env_prepend_opt_len] == '=')\n            {\n              const char *p = argv[i] + env_prepend_opt_len + 1;\n              lt_opt_process_env_prepend (p);\n            }\n          else if (argv[i][env_prepend_opt_len] == '\\0' && i + 1 < argc)\n            {\n              lt_opt_process_env_prepend (argv[++i]); /* don't copy */\n            }\n          else\n            lt_fatal (\"%s missing required argument\", env_prepend_opt);\n          continue;\n        }\n      if (strncmp (argv[i], env_append_opt, env_append_opt_len) == 0)\n        {\n          if (argv[i][env_append_opt_len] == '=')\n            {\n              const char *p = argv[i] + env_append_opt_len + 1;\n              lt_opt_process_env_append (p);\n            }\n          else if (argv[i][env_append_opt_len] == '\\0' && i + 1 < argc)\n            {\n              lt_opt_process_env_append (argv[++i]); /* don't copy */\n            }\n          else\n            lt_fatal (\"%s missing required argument\", env_append_opt);\n          continue;\n        }\n      if (strncmp (argv[i], ltwrapper_option_prefix, opt_prefix_len) == 0)\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (\"Unrecognized option in %s namespace: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\n  LTWRAPPER_DEBUGPRINTF     ((\"(main) lt_argv_zero : %s\\n\", (lt_argv_zero ? lt_argv_zero : \"<NULL>\")));\n  for (i = 0; i < newargc; i++)\n    {\n      LTWRAPPER_DEBUGPRINTF ((\"(main) newargz[%d]   : %s\\n\", i, (newargz[i] ? newargz[i] : \"<NULL>\")));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  rval = _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      LTWRAPPER_DEBUGPRINTF ((\"(main) failed to launch target \\\"%s\\\": errno = %d\\n\", lt_argv_zero, errno));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (\"Memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  LTWRAPPER_DEBUGPRINTF ((\"(check_executable)  : %s\\n\",\n\t\t\t  path ? (*path ? path : \"EMPTY!\") : \"NULL!\"));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  LTWRAPPER_DEBUGPRINTF ((\"(make_executable)   : %s\\n\",\n\t\t\t  path ? (*path ? path : \"EMPTY!\") : \"NULL!\"));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  int tmp_len;\n  char *concat_name;\n\n  LTWRAPPER_DEBUGPRINTF ((\"(find_executable)   : %s\\n\",\n\t\t\t  wrapper ? (*wrapper ? wrapper : \"EMPTY!\") : \"NULL!\"));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined (HAVE_DOS_BASED_FILE_SYSTEM)\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = q - p;\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (\"getcwd failed\");\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (\"getcwd failed\");\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      LTWRAPPER_DEBUGPRINTF ((\"checking path component for symlinks: %s\\n\",\n\t\t\t      tmp_pathspec));\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  char *errstr = strerror (errno);\n\t  lt_fatal (\"Error accessing file %s (%s)\", tmp_pathspec, errstr);\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (\"Could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (strcmp (str, pat) == 0)\n\t*str = '\\0';\n    }\n  return str;\n}\n\nstatic void\nlt_error_core (int exit_status, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s: %s: \", program_name, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  LTWRAPPER_DEBUGPRINTF ((\"(lt_setenv) setting '%s' to '%s'\\n\",\n                          (name ? name : \"<NULL>\"),\n                          (value ? value : \"<NULL>\")));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    int len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      int orig_value_len = strlen (orig_value);\n      int add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nint\nlt_split_name_value (const char *arg, char** name, char** value)\n{\n  const char *p;\n  int len;\n  if (!arg || !*arg)\n    return 1;\n\n  p = strchr (arg, (int)'=');\n\n  if (!p)\n    return 1;\n\n  *value = xstrdup (++p);\n\n  len = strlen (arg) - strlen (*value);\n  *name = XMALLOC (char, len);\n  strncpy (*name, arg, len-1);\n  (*name)[len - 1] = '\\0';\n\n  return 0;\n}\n\nvoid\nlt_opt_process_env_set (const char *arg)\n{\n  char *name = NULL;\n  char *value = NULL;\n\n  if (lt_split_name_value (arg, &name, &value) != 0)\n    {\n      XFREE (name);\n      XFREE (value);\n      lt_fatal (\"bad argument for %s: '%s'\", env_set_opt, arg);\n    }\n\n  lt_setenv (name, value);\n  XFREE (name);\n  XFREE (value);\n}\n\nvoid\nlt_opt_process_env_prepend (const char *arg)\n{\n  char *name = NULL;\n  char *value = NULL;\n  char *new_value = NULL;\n\n  if (lt_split_name_value (arg, &name, &value) != 0)\n    {\n      XFREE (name);\n      XFREE (value);\n      lt_fatal (\"bad argument for %s: '%s'\", env_prepend_opt, arg);\n    }\n\n  new_value = lt_extend_str (getenv (name), value, 0);\n  lt_setenv (name, new_value);\n  XFREE (new_value);\n  XFREE (name);\n  XFREE (value);\n}\n\nvoid\nlt_opt_process_env_append (const char *arg)\n{\n  char *name = NULL;\n  char *value = NULL;\n  char *new_value = NULL;\n\n  if (lt_split_name_value (arg, &name, &value) != 0)\n    {\n      XFREE (name);\n      XFREE (value);\n      lt_fatal (\"bad argument for %s: '%s'\", env_append_opt, arg);\n    }\n\n  new_value = lt_extend_str (getenv (name), value, 1);\n  lt_setenv (name, new_value);\n  XFREE (new_value);\n  XFREE (name);\n  XFREE (value);\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  LTWRAPPER_DEBUGPRINTF ((\"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                          (name ? name : \"<NULL>\"),\n                          (value ? value : \"<NULL>\")));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      int len = strlen (new_value);\n      while (((len = strlen (new_value)) > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[len-1] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  LTWRAPPER_DEBUGPRINTF ((\"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                          (name ? name : \"<NULL>\"),\n                          (value ? value : \"<NULL>\")));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\n\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $opt_debug\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # which system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll which has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=no\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=\"${wl}-single_module\"\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest \"$build_libtool_libs\" != yes && \\\n\t  func_fatal_configuration \"can not build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test \"$build_libtool_libs\" = yes && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=\"$1\"\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tdlfiles|dlprefiles)\n\t  if test \"$preload\" = no; then\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=yes\n\t  fi\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test \"$dlself\" = no; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test \"$prev\" = dlprefiles; then\n\t      dlself=yes\n\t    elif test \"$prev\" = dlfiles && test \"$dlopen_self\" != yes; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test \"$prev\" = dlfiles; then\n\t      dlfiles=\"$dlfiles $arg\"\n\t    else\n\t      dlprefiles=\"$dlprefiles $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=\"$arg\"\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file \\`$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) deplibs=\"$deplibs $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      moreargs=\"$moreargs $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test \"$pic_object\" = none &&\n\t\t   test \"$non_pic_object\" = none; then\n\t\t  func_fatal_error \"cannot find name of object for \\`$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=\"$func_dirname_result\"\n\n\t\tif test \"$pic_object\" != none; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=\"$xdir$pic_object\"\n\n\t\t  if test \"$prev\" = dlfiles; then\n\t\t    if test \"$build_libtool_libs\" = yes && test \"$dlopen_support\" = yes; then\n\t\t      dlfiles=\"$dlfiles $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test \"$prev\" = dlprefiles; then\n\t\t    # Preload the old-style object.\n\t\t    dlprefiles=\"$dlprefiles $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=\"$pic_object\"\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test \"$non_pic_object\" != none; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=\"$xdir$non_pic_object\"\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test \"$pic_object\" = none ; then\n\t\t    arg=\"$non_pic_object\"\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=\"$pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=\"$func_dirname_result\"\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"\\`$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file \\`$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=\"-$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test \"$prev\" = rpath; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) rpath=\"$rpath $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) xrpath=\"$xrpath $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=\"$arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  weak_libs=\"$weak_libs $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  linker_flags=\"$linker_flags $qarg\"\n\t  compiler_flags=\"$compiler_flags $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  compiler_flags=\"$compiler_flags $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  linker_flags=\"$linker_flags $qarg\"\n\t  compiler_flags=\"$compiler_flags $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=\"$arg\"\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"\\`-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test \"X$arg\" = \"X-export-symbols\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname '-L' '' \"$arg\"\n\tdir=$func_stripname_result\n\tif test -z \"$dir\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between \\`-L' and \\`$1'\"\n\t  else\n\t    func_fatal_error \"need path for \\`-L' option\"\n\t  fi\n\tfi\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of \\`$dir'\"\n\t  dir=\"$absdir\"\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"*) ;;\n\t*)\n\t  deplibs=\"$deplibs -L$dir\"\n\t  lib_search_path=\"$lib_search_path $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"X$dir\" | $Xsed -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) dllsearchpath=\"$dllsearchpath:$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) dllsearchpath=\"$dllsearchpath:$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test \"X$arg\" = \"X-lc\" || test \"X$arg\" = \"X-lm\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    deplibs=\"$deplibs System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test \"X$arg\" = \"X-lc\" && continue\n\t    ;;\n\t  esac\n\telif test \"X$arg\" = \"X-lc_r\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tdeplibs=\"$deplibs $arg\"\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot)\n\tcompiler_flags=\"$compiler_flags $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)\n\tcompiler_flags=\"$compiler_flags $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) new_inherited_linker_flags=\"$new_inherited_linker_flags $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=\"${wl}-multi_module\"\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"\\`-no-install' is ignored for $host\"\n\t  func_warning \"assuming \\`-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) xrpath=\"$xrpath $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=\"$IFS\"; IFS=','\n\tfor flag in $args; do\n\t  IFS=\"$save_ifs\"\n          func_quote_for_eval \"$flag\"\n\t  arg=\"$arg $wl$func_quote_for_eval_result\"\n\t  compiler_flags=\"$compiler_flags $func_quote_for_eval_result\"\n\tdone\n\tIFS=\"$save_ifs\"\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=\"$IFS\"; IFS=','\n\tfor flag in $args; do\n\t  IFS=\"$save_ifs\"\n          func_quote_for_eval \"$flag\"\n\t  arg=\"$arg $wl$func_quote_for_eval_result\"\n\t  compiler_flags=\"$compiler_flags $wl$func_quote_for_eval_result\"\n\t  linker_flags=\"$linker_flags $func_quote_for_eval_result\"\n\tdone\n\tIFS=\"$save_ifs\"\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n\n      # -64, -mips[0-9] enable 64-bit mode on the SGI compiler\n      # -r[0-9][0-9]* specifies the processor on the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode on the Sun compiler\n      # +DA*, +DD* enable 64-bit mode on the HP compiler\n      # -q* pass through compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* pass through architecture-specific\n      # compiler args for GCC\n      # -F/path gives path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-* pass through profiling flag for GCC\n      # @file GCC response files\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*)\n        func_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        compiler_flags=\"$compiler_flags $arg\"\n        continue\n        ;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tobjs=\"$objs $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test \"$pic_object\" = none &&\n\t     test \"$non_pic_object\" = none; then\n\t    func_fatal_error \"cannot find name of object for \\`$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=\"$func_dirname_result\"\n\n\t  if test \"$pic_object\" != none; then\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=\"$xdir$pic_object\"\n\n\t    if test \"$prev\" = dlfiles; then\n\t      if test \"$build_libtool_libs\" = yes && test \"$dlopen_support\" = yes; then\n\t\tdlfiles=\"$dlfiles $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test \"$prev\" = dlprefiles; then\n\t      # Preload the old-style object.\n\t      dlprefiles=\"$dlprefiles $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=\"$pic_object\"\n\t  fi\n\n\t  # Non-PIC object.\n\t  if test \"$non_pic_object\" != none; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=\"$xdir$non_pic_object\"\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test \"$pic_object\" = none ; then\n\t      arg=\"$non_pic_object\"\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=\"$pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=\"$func_dirname_result\"\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"\\`$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tdeplibs=\"$deplibs $arg\"\n\told_deplibs=\"$old_deplibs $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tif test \"$prev\" = dlfiles; then\n\t  # This library was specified with -dlopen.\n\t  dlfiles=\"$dlfiles $arg\"\n\t  prev=\n\telif test \"$prev\" = dlprefiles; then\n\t  # The library was specified with -dlpreopen.\n\t  dlprefiles=\"$dlprefiles $arg\"\n\t  prev=\n\telse\n\t  deplibs=\"$deplibs $arg\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=\"$func_quote_for_eval_result\"\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the \\`$prevarg' option requires an argument\"\n\n    if test \"$export_dynamic\" = yes && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=\"$func_basename_result\"\n    libobjs_save=\"$libobjs\"\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"X\\${$shlibpath_var}\\\" \\| \\$Xsed -e \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=\"$func_dirname_result$objdir\"\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_duplicate_deps ; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) specialdeplibs=\"$specialdeplibs $deplib\" ;;\n\tesac\n      fi\n      libs=\"$libs $deplib\"\n    done\n\n    if test \"$linkmode\" = lib; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) specialdeplibs=\"$specialdeplibs $pre_post_deps\" ;;\n\t  esac\n\t  pre_post_deps=\"$pre_post_deps $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can \\`-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=no\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test \"$linkmode,$pass\" = \"lib,link\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=\"$tmp_deplibs\"\n      fi\n\n      if test \"$linkmode,$pass\" = \"lib,link\" ||\n\t test \"$linkmode,$pass\" = \"prog,scan\"; then\n\tlibs=\"$deplibs\"\n\tdeplibs=\n      fi\n      if test \"$linkmode\" = prog; then\n\tcase $pass in\n\tdlopen) libs=\"$dlfiles\" ;;\n\tdlpreopen) libs=\"$dlprefiles\" ;;\n\tlink) libs=\"$deplibs %DEPLIBS% $dependency_libs\" ;;\n\tesac\n      fi\n      if test \"$linkmode,$pass\" = \"lib,dlpreopen\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  case $lib in\n\t  *.la)\tfunc_source \"$lib\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n            deplib_base=`$ECHO \"X$deplib\" | $Xsed -e \"$basename\"`\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) deplibs=\"$deplibs $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=\"$dlprefiles\"\n      fi\n      if test \"$pass\" = dlopen; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=\"$deplibs\"\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=no\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe|-threads)\n\t  if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    compiler_flags=\"$compiler_flags $deplib\"\n\t    if test \"$linkmode\" = lib ; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) new_inherited_linker_flags=\"$new_inherited_linker_flags $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test \"$linkmode\" != lib && test \"$linkmode\" != prog; then\n\t    func_warning \"\\`-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test \"$linkmode\" = lib; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=\"$searchdir/lib${name}${search_ext}\"\n\t      if test -f \"$lib\"; then\n\t\tif test \"$search_ext\" = \".la\"; then\n\t\t  found=yes\n\t\telse\n\t\t  found=no\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if test \"$found\" != yes; then\n\t    # deplib doesn't seem to be a libtool library\n\t    if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test \"$linkmode\" = lib && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  else # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=\"$l\"\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\" ; then # only static version available\n\t\t    found=no\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=\"$func_dirname_result\"\n\t\t    lib=$ladir/$old_library\n\t\t    if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test \"$linkmode\" = lib && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test \"$linkmode\" = lib ; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) new_inherited_linker_flags=\"$new_inherited_linker_flags $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test \"$pass\" = conv && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    newlib_search_path=\"$newlib_search_path $func_stripname_result\"\n\t    ;;\n\t  prog)\n\t    if test \"$pass\" = conv; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test \"$pass\" = scan; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    newlib_search_path=\"$newlib_search_path $func_stripname_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"\\`-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test \"$pass\" = link; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    dir=$func_stripname_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) xrpath=\"$xrpath $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la) lib=\"$deplib\" ;;\n\t*.$libext)\n\t  if test \"$pass\" = conv; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=no\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"X$deplib\\\"\" 2>/dev/null | $Xsed -e 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=yes\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=yes\n\t\t;;\n\t      esac\n\t      if test \"$valid_a_lib\" != yes; then\n\t\t$ECHO\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\t$ECHO \"*** I have the capability to make that library automatically link in when\"\n\t\t$ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t\t$ECHO \"*** shared version of the library, which you do not appear to have\"\n\t\t$ECHO \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\t$ECHO \"*** that it is just a static archive that I should not use here.\"\n\t      else\n\t\t$ECHO\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test \"$pass\" != link; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test \"$pass\" = conv; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test \"$linkmode\" = prog; then\n\t    if test \"$pass\" = dlpreopen || test \"$dlopen_support\" != yes || test \"$build_libtool_libs\" = no; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      newdlprefiles=\"$newdlprefiles $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      newdlfiles=\"$newdlfiles $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=yes\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\tif test \"$found\" = yes || test -f \"$lib\"; then :\n\telse\n\t  func_fatal_error \"cannot find the library \\`$lib' or unhandled argument \\`$deplib'\"\n\tfi\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=\"$func_dirname_result\"\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"X$inherited_linker_flags\" | $Xsed -e 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) new_inherited_linker_flags=\"$new_inherited_linker_flags $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \"X $dependency_libs\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test \"$linkmode,$pass\" = \"lib,link\" ||\n\t   test \"$linkmode,$pass\" = \"prog,scan\" ||\n\t   { test \"$linkmode\" != prog && test \"$linkmode\" != lib; }; then\n\t  test -n \"$dlopen\" && dlfiles=\"$dlfiles $dlopen\"\n\t  test -n \"$dlpreopen\" && dlprefiles=\"$dlprefiles $dlpreopen\"\n\tfi\n\n\tif test \"$pass\" = conv; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for \\`$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    convenience=\"$convenience $ladir/$objdir/$old_library\"\n\t    old_convenience=\"$old_convenience $ladir/$objdir/$old_library\"\n\t  elif test \"$linkmode\" != prog && test \"$linkmode\" != lib; then\n\t    func_fatal_error \"\\`$lib' is not a convenience library\"\n\t  fi\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    deplibs=\"$deplib $deplibs\"\n\t    if $opt_duplicate_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) specialdeplibs=\"$specialdeplibs $deplib\" ;;\n\t      esac\n\t    fi\n\t    tmp_libs=\"$tmp_libs $deplib\"\n\t  done\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tfor l in $old_library $library_names; do\n\t  linklib=\"$l\"\n\tdone\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for \\`$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test \"$pass\" = dlopen; then\n\t  if test -z \"$libdir\"; then\n\t    func_fatal_error \"cannot -dlopen a convenience library: \\`$lib'\"\n\t  fi\n\t  if test -z \"$dlname\" ||\n\t     test \"$dlopen_support\" != yes ||\n\t     test \"$build_libtool_libs\" = no; then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    dlprefiles=\"$dlprefiles $lib $dependency_libs\"\n\t  else\n\t    newdlfiles=\"$newdlfiles $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=\"$ladir\" ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of \\`$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=\"$ladir\"\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=\"$func_basename_result\"\n\n\t# Find the relevant object directory and library name.\n\tif test \"X$installed\" = Xyes; then\n\t  if test ! -f \"$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library \\`$lib' was moved.\"\n\t    dir=\"$ladir\"\n\t    absdir=\"$abs_ladir\"\n\t    libdir=\"$abs_ladir\"\n\t  else\n\t    dir=\"$libdir\"\n\t    absdir=\"$libdir\"\n\t  fi\n\t  test \"X$hardcode_automatic\" = Xyes && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=\"$ladir\"\n\t    absdir=\"$abs_ladir\"\n\t    # Remove this search path later\n\t    notinst_path=\"$notinst_path $abs_ladir\"\n\t  else\n\t    dir=\"$ladir/$objdir\"\n\t    absdir=\"$abs_ladir/$objdir\"\n\t    # Remove this search path later\n\t    notinst_path=\"$notinst_path $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test \"$pass\" = dlpreopen; then\n\t  if test -z \"$libdir\" && test \"$linkmode\" = prog; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: \\`$lib'\"\n\t  fi\n\t  # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t  # are required to link).\n\t  if test -n \"$old_library\"; then\n\t    newdlprefiles=\"$newdlprefiles $dir/$old_library\"\n\t    # Keep a list of preopened convenience libraries to check\n\t    # that they are being used correctly in the link pass.\n\t    test -z \"$libdir\" && \\\n\t\tdlpreconveniencelibs=\"$dlpreconveniencelibs $dir/$old_library\"\n\t  # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t  elif test -n \"$dlname\"; then\n\t    newdlprefiles=\"$newdlprefiles $dir/$dlname\"\n\t  else\n\t    newdlprefiles=\"$newdlprefiles $dir/$linklib\"\n\t  fi\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test \"$linkmode\" = lib; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test \"$linkmode,$pass\" = \"prog,link\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test \"$linkmode\" = prog && test \"$pass\" != link; then\n\t  newlib_search_path=\"$newlib_search_path $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=no\n\t  if test \"$link_all_deplibs\" != no || test -z \"$library_names\" ||\n\t     test \"$build_libtool_libs\" = no; then\n\t    linkalldeplibs=yes\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         newlib_search_path=\"$newlib_search_path $func_stripname_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if test \"$linkalldeplibs\" = yes; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_duplicate_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) specialdeplibs=\"$specialdeplibs $deplib\" ;;\n\t      esac\n\t    fi\n\t    tmp_libs=\"$tmp_libs $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test \"$linkmode,$pass\" = \"prog,link\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test \"$prefer_static_libs\" = no ||\n\t         test \"$prefer_static_libs,$installed\" = \"built,yes\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\" ; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case \"$temp_rpath:\" in\n\t      *\"$absdir:\"*) ;;\n\t      *) temp_rpath=\"$temp_rpath$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) compile_rpath=\"$compile_rpath $absdir\"\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) finalize_rpath=\"$finalize_rpath $libdir\"\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if test \"$alldeplibs\" = yes &&\n\t     { test \"$deplibs_check_method\" = pass_all ||\n\t       { test \"$build_libtool_libs\" = yes &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test \"$use_static_libs\" = built && test \"$installed\" = yes; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test \"$use_static_libs\" = no || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      notinst_deplibs=\"$notinst_deplibs $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test \"$installed\" = no; then\n\t      notinst_deplibs=\"$notinst_deplibs $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\"\"\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=\"$dlpremoduletest\"\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test \"$shouldnotlink\" = yes && test \"$pass\" = link; then\n\t    $ECHO\n\t    if test \"$linkmode\" = prog; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test \"$linkmode\" = lib &&\n\t     test \"$hardcode_into_libs\" = yes; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) compile_rpath=\"$compile_rpath $absdir\"\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) finalize_rpath=\"$finalize_rpath $libdir\"\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=\"$1\"\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=\"$dlname\"\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=\"-$major\"\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=\"$realname\"\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=\"$soname\"\n\t    func_basename \"$soroot\"\n\t    soname=\"$func_basename_result\"\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from \\`$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for \\`$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test \"$linkmode\" = prog || test \"$mode\" != relink; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test \"$hardcode_direct\" = no; then\n\t\tadd=\"$dir/$linklib\"\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-sysv4*uw2*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=\"-L$dir\" ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we can not\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null ; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\" ; then\n\t\t\t  $ECHO\n\t\t\t  $ECHO \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  $ECHO \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=\"$dir/$old_library\"\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=\"$dir/$old_library\"\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test \"$hardcode_minus_L\" = no; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=\"$dir\" ;;\n\t\tesac\n\t\tadd_dir=\"-L$dir\"\n\t\tadd=\"-l$name\"\n\t      elif test \"$hardcode_shlibpath_var\" = no; then\n\t\tadd_shlibpath=\"$dir\"\n\t\tadd=\"-l$name\"\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test \"$hardcode_direct\" = yes &&\n\t         test \"$hardcode_direct_absolute\" = no; then\n\t\tadd=\"$dir/$linklib\"\n\t      elif test \"$hardcode_minus_L\" = yes; then\n\t\tadd_dir=\"-L$dir\"\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      add_dir=\"$add_dir -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=\"-l$name\"\n\t      elif test \"$hardcode_shlibpath_var\" = yes; then\n\t\tadd_shlibpath=\"$dir\"\n\t\tadd=\"-l$name\"\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test \"$lib_linked\" != yes; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) compile_shlibpath=\"$compile_shlibpath$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test \"$linkmode\" = prog; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test \"$hardcode_direct\" != yes &&\n\t\t test \"$hardcode_minus_L\" != yes &&\n\t\t test \"$hardcode_shlibpath_var\" = yes; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) finalize_shlibpath=\"$finalize_shlibpath$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test \"$linkmode\" = prog || test \"$mode\" = relink; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test \"$hardcode_direct\" = yes &&\n\t       test \"$hardcode_direct_absolute\" = no; then\n\t      add=\"$libdir/$linklib\"\n\t    elif test \"$hardcode_minus_L\" = yes; then\n\t      add_dir=\"-L$libdir\"\n\t      add=\"-l$name\"\n\t    elif test \"$hardcode_shlibpath_var\" = yes; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) finalize_shlibpath=\"$finalize_shlibpath$libdir:\" ;;\n\t      esac\n\t      add=\"-l$name\"\n\t    elif test \"$hardcode_automatic\" = yes; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\" ; then\n\t\tadd=\"$inst_prefix_dir$libdir/$linklib\"\n\t      else\n\t\tadd=\"$libdir/$linklib\"\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=\"-L$libdir\"\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    add_dir=\"$add_dir -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=\"-l$name\"\n\t    fi\n\n\t    if test \"$linkmode\" = prog; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test \"$linkmode\" = prog; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test \"$hardcode_direct\" != unsupported; then\n\t    test -n \"$old_library\" && linklib=\"$old_library\"\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test \"$build_libtool_libs\" = yes; then\n\t  # Not a shared library\n\t  if test \"$deplibs_check_method\" != pass_all; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    $ECHO\n\t    $ECHO \"*** Warning: This system can not link to static lib archive $lib.\"\n\t    $ECHO \"*** I have the capability to make that library automatically link in when\"\n\t    $ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t    $ECHO \"*** shared version of the library, which you do not appear to have.\"\n\t    if test \"$module\" = yes; then\n\t      $ECHO \"*** But as you try to build a module library, libtool will still create \"\n\t      $ECHO \"*** a static module, that should work as long as the dlopening application\"\n\t      $ECHO \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\t$ECHO\n\t\t$ECHO \"*** However, this would only work if libtool was able to extract symbol\"\n\t\t$ECHO \"*** lists from a program, using \\`nm' or equivalent, but libtool could\"\n\t\t$ECHO \"*** not find such a program.  So, this module is probably useless.\"\n\t\t$ECHO \"*** \\`nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test \"$build_old_libs\" = no; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test \"$linkmode\" = lib; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test \"$hardcode_into_libs\" != yes ||\n\t       test \"$build_old_libs\" = yes ||\n\t       test \"$link_static\" = yes; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) xrpath=\"$xrpath $temp_xrpath\";;\n\t\t   esac;;\n\t      *) temp_deplibs=\"$temp_deplibs $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=\"$temp_deplibs\"\n\t  fi\n\n\t  newlib_search_path=\"$newlib_search_path $absdir\"\n\t  # Link against this library\n\t  test \"$link_static\" = no && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    if $opt_duplicate_deps ; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) specialdeplibs=\"$specialdeplibs $deplib\" ;;\n\t      esac\n\t    fi\n\t    tmp_libs=\"$tmp_libs $deplib\"\n\t  done\n\n\t  if test \"$link_all_deplibs\" != no; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      -L*) path=\"$deplib\" ;;\n\t      *.la)\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=\"$func_dirname_result\"\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=\"$dir\" ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of \\`$dir'\"\n\t\t    absdir=\"$dir\"\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`${SED} -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\" ; then\n\t\t    for tmp in $deplibrary_names ; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\" ; then\n\t\t      depdepl=\"$absdir/$objdir/$depdepl\"\n\t\t      darwin_install_name=`${OTOOL} -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`${OTOOL64} -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      compiler_flags=\"$compiler_flags ${wl}-dylib_file ${wl}${darwin_install_name}:${depdepl}\"\n\t\t      linker_flags=\"$linker_flags -dylib_file ${darwin_install_name}:${depdepl}\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=\"-L$absdir/$objdir\"\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"\\`$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"\\`$deplib' seems to be moved\"\n\n\t\t  path=\"-L$absdir\"\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test \"$pass\" = link; then\n\tif test \"$linkmode\" = \"prog\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \"X $new_inherited_linker_flags\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=\"$newdependency_libs\"\n      if test \"$pass\" = dlpreopen; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test \"$pass\" != dlopen; then\n\tif test \"$pass\" != conv; then\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) lib_search_path=\"$lib_search_path $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\tfi\n\n\tif test \"$linkmode,$pass\" != \"prog,link\"; then\n\t  vars=\"deplibs\"\n\telse\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) tmp_libs=\"$tmp_libs $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) tmp_libs=\"$tmp_libs $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs ; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\"\"\n\t  ;;\n\tesac\n\tif test -n \"$i\" ; then\n\t  tmp_libs=\"$tmp_libs $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test \"$linkmode\" = prog; then\n      dlfiles=\"$newdlfiles\"\n    fi\n    if test \"$linkmode\" = prog || test \"$linkmode\" = lib; then\n      dlprefiles=\"$newdlprefiles\"\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n\tfunc_warning \"\\`-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"\\`-l' and \\`-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"\\`-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"\\`-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"\\`-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=\"$output\"\n      objs=\"$objs$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form `libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest \"$module\" = no && \\\n\t  func_fatal_help \"libtool library \\`$output' must begin with \\`lib'\"\n\n\tif test \"$need_lib_prefix\" != no; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test \"$deplibs_check_method\" != pass_all; then\n\t  func_fatal_error \"cannot build libtool library \\`$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  $ECHO\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  libobjs=\"$libobjs $objs\"\n\tfi\n      fi\n\n      test \"$dlself\" != no && \\\n\tfunc_warning \"\\`-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test \"$#\" -gt 1 && \\\n\tfunc_warning \"ignoring multiple \\`-rpath's for a libtool library\"\n\n      install_libdir=\"$1\"\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test \"$build_libtool_libs\" = yes; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a `.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"\\`-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"\\`-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=\"$IFS\"; IFS=':'\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=\"$save_ifs\"\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to \\`-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=\"$1\"\n\t  number_minor=\"$2\"\n\t  number_revision=\"$3\"\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # which has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  darwin|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=\"$number_minor\"\n\t    revision=\"$number_revision\"\n\t    ;;\n\t  freebsd-aout|freebsd-elf|sunos)\n\t    current=\"$number_major\"\n\t    revision=\"$number_minor\"\n\t    age=\"0\"\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=\"$number_minor\"\n\t    revision=\"$number_minor\"\n\t    lt_irix_increment=no\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=\"$1\"\n\t  revision=\"$2\"\n\t  age=\"$3\"\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT \\`$current' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION \\`$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE \\`$age' must be a nonnegative integer\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE \\`$age' is greater than the current interface number \\`$current'\"\n\t  func_fatal_error \"\\`$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\"$major.$age.$revision\"\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"${wl}-compatibility_version ${wl}$minor_current ${wl}-current_version ${wl}$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=\".$current\"\n\t  versuffix=\".$current.$revision\";\n\t  ;;\n\n\tfreebsd-elf)\n\t  major=\".$current\"\n\t  versuffix=\".$current\"\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test \"X$lt_irix_increment\" = \"Xno\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=\"$verstring_prefix$major.$revision\"\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test \"$loop\" -ne 0; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=\"$verstring_prefix$major.$iface:$verstring\"\n\t  done\n\n\t  # Before this point, $major must not contain `.'.\n\t  major=.$major\n\t  versuffix=\"$major.$revision\"\n\t  ;;\n\n\tlinux)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\"$major.$age.$revision\"\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=\".$current.$age.$revision\"\n\t  verstring=\"$current.$age.$revision\"\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test \"$loop\" -ne 0; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=\"$verstring:${iface}.0\"\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  verstring=\"$verstring:${current}.0\"\n\t  ;;\n\n\tqnx)\n\t  major=\".$current\"\n\t  versuffix=\".$current\"\n\t  ;;\n\n\tsunos)\n\t  major=\".$current\"\n\t  versuffix=\".$current.$revision\"\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 filesystems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=\"-$major\"\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type \\`$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=\"0.0\"\n\t    ;;\n\t  esac\n\t  if test \"$need_version\" = no; then\n\t    versuffix=\n\t  else\n\t    versuffix=\".0.0\"\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test \"$avoid_version\" = yes && test \"$need_version\" = no; then\n\t  major=\n\t  versuffix=\n\t  verstring=\"\"\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test \"$allow_undefined\" = yes; then\n\t  if test \"$allow_undefined_flag\" = unsupported; then\n\t    func_warning \"undefined symbols not allowed in $host shared libraries\"\n\t    build_libtool_libs=no\n\t    build_old_libs=yes\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=\"$no_undefined_flag\"\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" \"yes\"\n      libobjs=\"$libobjs $symfileobj\"\n      test \"X$libobjs\" = \"X \" && libobjs=\n\n      if test \"$mode\" != relink; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/${libname}${release}.*)\n\t       if test \"X$precious_files_regex\" != \"X\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       removelist=\"$removelist $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test \"$build_old_libs\" = yes && test \"$build_libtool_libs\" != convenience ; then\n\toldlibs=\"$oldlibs $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"X$libobjs\" | $SP2NL | $Xsed -e '/\\.'${libext}'$/d' -e \"$lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"X$lib_search_path \" | $Xsed -e \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"X$deplibs \" | $Xsed -e \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"X$dependency_libs \" | $Xsed -e \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  temp_xrpath=\"$temp_xrpath -R$libdir\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) finalize_rpath=\"$finalize_rpath $libdir\" ;;\n\t  esac\n\tdone\n\tif test \"$hardcode_into_libs\" != yes || test \"$build_old_libs\" = yes; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=\"$dlfiles\"\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) dlfiles=\"$dlfiles $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=\"$dlprefiles\"\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) dlprefiles=\"$dlprefiles $lib\" ;;\n\tesac\n      done\n\n      if test \"$build_libtool_libs\" = yes; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    deplibs=\"$deplibs System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test \"$build_libtool_need_lc\" = \"yes\"; then\n\t      deplibs=\"$deplibs -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\"\"\n\tversuffix=\"\"\n\tmajor=\"\"\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    newdeplibs=\"$newdeplibs $i\"\n\t\t    i=\"\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\" ; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0 ; then\n\t\t    newdeplibs=\"$newdeplibs $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    $ECHO\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    $ECHO \"*** I have the capability to make that library automatically link in when\"\n\t\t    $ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    $ECHO \"*** shared version of the library, which I believe you do not have\"\n\t\t    $ECHO \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    $ECHO \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tnewdeplibs=\"$newdeplibs $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      newdeplibs=\"$newdeplibs $i\"\n\t\t      i=\"\"\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\" ; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0 ; then\n\t\t      newdeplibs=\"$newdeplibs $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      $ECHO\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      $ECHO \"*** I have the capability to make that library automatically link in when\"\n\t\t      $ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      $ECHO \"*** shared version of the library, which you do not appear to have\"\n\t\t      $ECHO \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      $ECHO \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  $ECHO\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  $ECHO \"*** make it link in!  You will probably need to install it or some\"\n\t\t  $ECHO \"*** library that it depends on before this library will be fully\"\n\t\t  $ECHO \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tnewdeplibs=\"$newdeplibs $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  newdeplibs=\"$newdeplibs $a_deplib\"\n\t\t  a_deplib=\"\"\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=\"$potent_lib\"\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | ${SED} 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=\"$potliblink\";;\n\t\t\t*) potlib=`$ECHO \"X$potlib\" | $Xsed -e 's,[^/]*$,,'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tnewdeplibs=\"$newdeplibs $a_deplib\"\n\t\t\ta_deplib=\"\"\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tdroppeddeps=yes\n\t\t$ECHO\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\t$ECHO \"*** I have the capability to make that library automatically link in when\"\n\t\t$ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t\t$ECHO \"*** shared version of the library, which you do not appear to have\"\n\t\t$ECHO \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\" ; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      newdeplibs=\"$newdeplibs $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  newdeplibs=\"$newdeplibs $a_deplib\"\n\t\t  a_deplib=\"\"\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=\"$potent_lib\" # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"X$potent_lib\\\"\" 2>/dev/null | $Xsed -e 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      newdeplibs=\"$newdeplibs $a_deplib\"\n\t\t      a_deplib=\"\"\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\" ; then\n\t\tdroppeddeps=yes\n\t\t$ECHO\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\t$ECHO \"*** I have the capability to make that library automatically link in when\"\n\t\t$ECHO \"*** you link to this library.  But I can only do this if you have a\"\n\t\t$ECHO \"*** shared version of the library, which you do not appear to have\"\n\t\t$ECHO \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\" ; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      newdeplibs=\"$newdeplibs $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\"\"\n\t  tmp_deplibs=`$ECHO \"X $deplibs\" | $Xsed \\\n\t      -e 's/ -lc$//' -e 's/ -[LR][^ ]*//g'`\n\t  if test \"X$allow_libtool_libs_with_static_runtimes\" = \"Xyes\" ; then\n\t    for i in $predeps $postdeps ; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \"X $tmp_deplibs\" | $Xsed -e \"s,$i,,\"`\n\t    done\n\t  fi\n\t  if $ECHO \"X $tmp_deplibs\" | $Xsed -e 's/[\t ]//g' |\n\t     $GREP . >/dev/null; then\n\t    $ECHO\n\t    if test \"X$deplibs_check_method\" = \"Xnone\"; then\n\t      $ECHO \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      $ECHO \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    $ECHO \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t  fi\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \"X $newdeplibs\" | $Xsed -e 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test \"$droppeddeps\" = yes; then\n\t  if test \"$module\" = yes; then\n\t    $ECHO\n\t    $ECHO \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    $ECHO \"*** a static module, that should work as long as the dlopening\"\n\t    $ECHO \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      $ECHO\n\t      $ECHO \"*** However, this would only work if libtool was able to extract symbol\"\n\t      $ECHO \"*** lists from a program, using \\`nm' or equivalent, but libtool could\"\n\t      $ECHO \"*** not find such a program.  So, this module is probably useless.\"\n\t      $ECHO \"*** \\`nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test \"$build_old_libs\" = no; then\n\t      oldlibs=\"$output_objdir/$libname.$libext\"\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    $ECHO \"*** The inter-library dependencies that have been dropped here will be\"\n\t    $ECHO \"*** automatically added whenever a program is linked with this library\"\n\t    $ECHO \"*** or is declared to -dlopen it.\"\n\n\t    if test \"$allow_undefined\" = no; then\n\t      $ECHO\n\t      $ECHO \"*** Since this library must not contain undefined symbols,\"\n\t      $ECHO \"*** because either the platform does not support them or\"\n\t      $ECHO \"*** it was explicitly requested with -no-undefined,\"\n\t      $ECHO \"*** libtool will only create a static version of it.\"\n\t      if test \"$build_old_libs\" = no; then\n\t\toldlibs=\"$output_objdir/$libname.$libext\"\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \"X $newdeplibs\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \"X $new_inherited_linker_flags\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \"X $deplibs\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    new_libs=\"$new_libs -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) new_libs=\"$new_libs $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) new_libs=\"$new_libs $deplib\" ;;\n\tesac\n      done\n      deplibs=\"$new_libs\"\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test \"$build_libtool_libs\" = yes; then\n\tif test \"$hardcode_into_libs\" = yes; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=\"$finalize_rpath\"\n\t  test \"$mode\" != relink && rpath=\"$compile_rpath$rpath\"\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=\"$libdir\"\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    hardcode_libdirs=\"$hardcode_libdirs$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tdep_rpath=\"$dep_rpath $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) perm_rpath=\"$perm_rpath $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=\"$hardcode_libdirs\"\n\t    if test -n \"$hardcode_libdir_flag_spec_ld\"; then\n\t      eval dep_rpath=\\\"$hardcode_libdir_flag_spec_ld\\\"\n\t    else\n\t      eval dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\n\t    fi\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      rpath=\"$rpath$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=\"$finalize_shlibpath\"\n\ttest \"$mode\" != relink && shlibpath=\"$compile_shlibpath$shlibpath\"\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=\"$1\"\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=\"$realname\"\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=\"$output_objdir/$realname\"\n\tlinknames=\n\tfor link\n\tdo\n\t  linknames=\"$linknames $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"X$libobjs\" | $SP2NL | $Xsed -e \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=\"$output_objdir/$libname.uexp\"\n\t  delfiles=\"$delfiles $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    if test \"x`$SED 1q $export_symbols`\" != xEXPORTS; then\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=\"$export_symbols\"\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    fi\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test \"$always_export_symbols\" = yes || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for \\`$libname.la'\"\n\t    export_symbols=\"$output_objdir/$libname.exp\"\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=\"$IFS\"; IFS='~'\n\t    for cmd in $cmds; do\n\t      IFS=\"$save_ifs\"\n\t      eval cmd=\\\"$cmd\\\"\n\t      func_len \" $cmd\"\n\t      len=$func_len_result\n\t      if test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=\"$save_ifs\"\n\t    if test -n \"$export_symbols_regex\" && test \"X$skipped_export\" != \"X:\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=\"$export_symbols\"\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=\"$orig_export_symbols\"\n\t  $opt_dry_run || eval '$ECHO \"X$include_expsyms\" | $Xsed | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test \"X$skipped_export\" != \"X:\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for \\`$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  delfiles=\"$delfiles $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    tmp_deplibs=\"$tmp_deplibs $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=\"$tmp_deplibs\"\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test \"$compiler_needs_object\" = yes &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=\"$output_objdir/${outputname}x\"\n\t    generated=\"$generated $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    libobjs=\"$libobjs $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test \"$thread_safe\" = yes && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  linker_flags=\"$linker_flags $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test \"$mode\" = relink; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test \"$module\" = yes && test -n \"$module_cmds\" ; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test \"X$skipped_export\" != \"X:\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  output_la=`$ECHO \"X$output\" | $Xsed -e \"$basename\"`\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test \"X$skipped_export\" != \"X:\" && test \"$with_gnu_ld\" = yes; then\n\t    output=${output_objdir}/${output_la}.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    $ECHO 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      $ECHO \"$obj\" >> $output\n\t    done\n\t    $ECHO ')' >> $output\n\t    delfiles=\"$delfiles $output\"\n\t  elif test -n \"$save_libobjs\" && test \"X$skipped_export\" != \"X:\" && test \"X$file_list_spec\" != X; then\n\t    output=${output_objdir}/${output_la}.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test \"$compiler_needs_object\" = yes; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      $ECHO \"$obj\" >> $output\n\t    done\n\t    delfiles=\"$delfiles $output\"\n\t    output=$firstobj\\\"$file_list_spec$output\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-${k}.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test \"X$objlist\" = X ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test \"$k\" -eq 1 ; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    eval concat_cmds=\\\"$reload_cmds $objlist $last_robj\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds $objlist $last_robj~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-${k}.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-${k}.$objext\n\t\t  objlist=$obj\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\${concat_cmds}$reload_cmds $objlist $last_robj\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\${concat_cmds}~\\$RM $last_robj\\\"\n\t      fi\n\t      delfiles=\"$delfiles $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    if ${skipped_export-false}; then\n\t      func_verbose \"generating symbol list for \\`$libname.la'\"\n\t      export_symbols=\"$output_objdir/$libname.exp\"\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    fi\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=\"$IFS\"; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=\"$save_ifs\"\n\t      $opt_silent || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test \"$mode\" = relink; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=\"$save_ifs\"\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          if ${skipped_export-false}; then\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=\"$export_symbols\"\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=\"$orig_export_symbols\"\n\t      $opt_dry_run || eval '$ECHO \"X$include_expsyms\" | $Xsed | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for \\`$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      delfiles=\"$delfiles $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  fi\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test \"$module\" = yes && test -n \"$module_cmds\" ; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  generated=\"$generated $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  libobjs=\"$libobjs $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=\"$IFS\"; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=\"$save_ifs\"\n\t  eval cmd=\\\"$cmd\\\"\n\t  $opt_silent || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test \"$mode\" = relink; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=\"$save_ifs\"\n\n\t# Restore the uninstalled library and exit\n\tif test \"$mode\" = relink; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test \"$module\" = yes || test \"$export_dynamic\" = yes; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=\"$soname\"\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test \"$dlself\" != no; then\n\tfunc_warning \"\\`-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"\\`-l' and \\`-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"\\`-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"\\`-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object \\`$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=\"$output\"\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # reload_cmds runs $LD directly, so let us get rid of\n      # -Wl from whole_archive_flag_spec and hope we can get by with\n      # turning comma into space..\n      wl=\n\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  reload_conv_objs=$reload_objs\\ `$ECHO \"X$tmp_whole_archive_flags\" | $Xsed -e 's|,| |g'`\n\telse\n\t  gentop=\"$output_objdir/${obj}x\"\n\t  generated=\"$generated $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # Create the old-style object.\n      reload_objs=\"$objs$old_deplibs \"`$ECHO \"X$libobjs\" | $SP2NL | $Xsed -e '/\\.'${libext}$'/d' -e '/\\.lib$/d' -e \"$lo2o\" | $NL2SP`\" $reload_conv_objs\" ### testsuite: skip nested quoting test\n\n      output=\"$obj\"\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      if test \"$build_libtool_libs\" != yes; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      fi\n\n      if test -n \"$pic_flag\" || test \"$pic_mode\" != default; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=\"$libobj\"\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"\\`-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"\\`-release' is ignored for programs\"\n\n      test \"$preload\" = yes \\\n        && test \"$dlopen_support\" = unknown \\\n\t&& test \"$dlopen_self\" = unknown \\\n\t&& test \"$dlopen_self_static\" = unknown && \\\n\t  func_warning \"\\`LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \"X $compile_deplibs\" | $Xsed -e 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \"X $finalize_deplibs\" | $Xsed -e 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test \"$tagname\" = CXX ; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      compile_command=\"$compile_command ${wl}-bind_at_load\"\n\t      finalize_command=\"$finalize_command ${wl}-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \"X $compile_deplibs\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \"X $finalize_deplibs\" | $Xsed -e 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    new_libs=\"$new_libs -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) new_libs=\"$new_libs $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) new_libs=\"$new_libs $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=\"$new_libs\"\n\n\n      compile_command=\"$compile_command $compile_deplibs\"\n      finalize_command=\"$finalize_command $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) finalize_rpath=\"$finalize_rpath $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=\"$libdir\"\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\thardcode_libdirs=\"$hardcode_libdirs$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    rpath=\"$rpath $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) perm_rpath=\"$perm_rpath $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`${ECHO} \"$libdir\" | ${SED} -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) dllsearchpath=\"$dllsearchpath:$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) dllsearchpath=\"$dllsearchpath:$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=\"$hardcode_libdirs\"\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=\"$rpath\"\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=\"$libdir\"\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\thardcode_libdirs=\"$hardcode_libdirs$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    rpath=\"$rpath $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) finalize_perm_rpath=\"$finalize_perm_rpath $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=\"$hardcode_libdirs\"\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=\"$rpath\"\n\n      if test -n \"$libobjs\" && test \"$build_old_libs\" = yes; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"X$compile_command\" | $SP2NL | $Xsed -e \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"X$finalize_command\" | $SP2NL | $Xsed -e \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" \"no\"\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=yes\n      case $host in\n      *cygwin* | *mingw* )\n        if test \"$build_libtool_libs\" != yes; then\n          wrappers_required=no\n        fi\n        ;;\n      *cegcc)\n        # Disable wrappers for cegcc, we are cross compiling anyway.\n        wrappers_required=no\n        ;;\n      *)\n        if test \"$need_relink\" = no || test \"$build_libtool_libs\" != yes; then\n          wrappers_required=no\n        fi\n        ;;\n      esac\n      if test \"$wrappers_required\" = no; then\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"X$compile_command\" | $Xsed -e 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=\"$compile_command$compile_rpath\"\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.${objext}\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.${objext}\"'\n\tfi\n\n\texit $exit_status\n      fi\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    rpath=\"$rpath$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    rpath=\"$rpath$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test \"$no_install\" = yes; then\n\t# We don't need to create a wrapper script.\n\tlink_command=\"$compile_var$compile_command$compile_rpath\"\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"X$link_command\" | $Xsed -e 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\texit $EXIT_SUCCESS\n      fi\n\n      if test \"$hardcode_action\" = relink; then\n\t# Fast installation is not supported\n\tlink_command=\"$compile_var$compile_command$compile_rpath\"\n\trelink_command=\"$finalize_var$finalize_command$finalize_rpath\"\n\n\tfunc_warning \"this platform does not like uninstalled shared libraries\"\n\tfunc_warning \"\\`$output' will be relinked during installation\"\n      else\n\tif test \"$fast_install\" != no; then\n\t  link_command=\"$finalize_var$compile_command$finalize_rpath\"\n\t  if test \"$fast_install\" = yes; then\n\t    relink_command=`$ECHO \"X$compile_var$compile_command$compile_rpath\" | $Xsed -e 's%@OUTPUT@%\\$progdir/\\$file%g'`\n\t  else\n\t    # fast_install is set to needless\n\t    relink_command=\n\t  fi\n\telse\n\t  link_command=\"$compile_var$compile_command$compile_rpath\"\n\t  relink_command=\"$finalize_var$finalize_command$finalize_rpath\"\n\tfi\n      fi\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"X$link_command\" | $Xsed -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"X$relink_command\" | $Xsed -e \"$sed_quote_subst\"`\n      fi\n\n      # Quote $ECHO for shipping.\n      if test \"X$ECHO\" = \"X$SHELL $progpath --fallback-echo\"; then\n\tcase $progpath in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) qecho=\"$SHELL $progpath --fallback-echo\";;\n\t*) qecho=\"$SHELL `pwd`/$progpath --fallback-echo\";;\n\tesac\n\tqecho=`$ECHO \"X$qecho\" | $Xsed -e \"$sed_quote_subst\"`\n      else\n\tqecho=`$ECHO \"X$ECHO\" | $Xsed -e \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=\"$output_path/$objdir/lt-$output_name.c\"\n\t    cwrapper=\"$output_path/$output_name.exe\"\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\" ; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      if test \"$build_libtool_libs\" = convenience; then\n\toldobjs=\"$libobjs_save $symfileobj\"\n\taddlibs=\"$convenience\"\n\tbuild_libtool_libs=no\n      else\n\tif test \"$build_libtool_libs\" = module; then\n\t  oldobjs=\"$libobjs_save\"\n\t  build_libtool_libs=no\n\telse\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  if test \"$preload\" = yes && test -f \"$symfileobj\"; then\n\t    oldobjs=\"$oldobjs $symfileobj\"\n\t  fi\n\tfi\n\taddlibs=\"$old_convenience\"\n      fi\n\n      if test -n \"$addlibs\"; then\n\tgentop=\"$output_objdir/${outputname}x\"\n\tgenerated=\"$generated $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\toldobjs=\"$oldobjs $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test \"$build_libtool_libs\" = yes; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  generated=\"$generated $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  oldobjs=\"$oldobjs $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  $ECHO \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=\"$output_objdir/${outputname}x\"\n\t  generated=\"$generated $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=\"$func_basename_result\"\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      oldobjs=\"$oldobjs $gentop/$newobj\"\n\t      ;;\n\t    *) oldobjs=\"$oldobjs $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\" ; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\${concat_cmds}$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test \"X$oldobjs\" = \"X\" ; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test \"$build_old_libs\" = yes && old_library=\"$libname.$libext\"\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL $progpath $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"X$relink_command\" | $Xsed -e \"$sed_quote_subst\"`\n      if test \"$hardcode_automatic\" = yes ; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test \"$installed\" = yes; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=\"$output_objdir/$outputname\"i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=\"$func_basename_result\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$deplib' is not a valid libtool archive\"\n\t\tnewdependency_libs=\"$newdependency_libs $libdir/$name\"\n\t\t;;\n\t      *) newdependency_libs=\"$newdependency_libs $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=\"$newdependency_libs\"\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=\"$func_basename_result\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\t\tnewdlfiles=\"$newdlfiles $libdir/$name\"\n\t\t;;\n\t      *) newdlfiles=\"$newdlfiles $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=\"$newdlfiles\"\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=\"$func_basename_result\"\n\t\teval libdir=`${SED} -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"\\`$lib' is not a valid libtool archive\"\n\t\tnewdlprefiles=\"$newdlprefiles $libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=\"$newdlprefiles\"\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=\"$lib\" ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      newdlfiles=\"$newdlfiles $abs\"\n\t    done\n\t    dlfiles=\"$newdlfiles\"\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=\"$lib\" ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      newdlprefiles=\"$newdlprefiles $abs\"\n\t    done\n\t    dlprefiles=\"$newdlprefiles\"\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll) tdlname=../bin/$dlname ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE$TIMESTAMP) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that can not go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test \"$installed\" = no && test \"$need_relink\" = yes; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\n{ test \"$mode\" = link || test \"$mode\" = relink; } &&\n    func_mode_link ${1+\"$@\"}\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $opt_debug\n    RM=\"$nonopt\"\n    files=\n    rmforce=\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=\"$magic\"\n\n    for arg\n    do\n      case $arg in\n      -f) RM=\"$RM $arg\"; rmforce=yes ;;\n      -*) RM=\"$RM $arg\" ;;\n      *) files=\"$files $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    origobjdir=\"$objdir\"\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=\"$func_dirname_result\"\n      if test \"X$dir\" = X.; then\n\tobjdir=\"$origobjdir\"\n      else\n\tobjdir=\"$dir/$origobjdir\"\n      fi\n      func_basename \"$file\"\n      name=\"$func_basename_result\"\n      test \"$mode\" = uninstall && objdir=\"$dir\"\n\n      # Remember objdir for removal later, being careful to avoid duplicates\n      if test \"$mode\" = clean; then\n\tcase \" $rmdirs \" in\n\t  *\" $objdir \"*) ;;\n\t  *) rmdirs=\"$rmdirs $objdir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif test \"$rmforce\" = yes; then\n\tcontinue\n      fi\n\n      rmfiles=\"$file\"\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    rmfiles=\"$rmfiles $objdir/$n\"\n\t  done\n\t  test -n \"$old_library\" && rmfiles=\"$rmfiles $objdir/$old_library\"\n\n\t  case \"$mode\" in\n\t  clean)\n\t    case \"  $library_names \" in\n\t    # \"  \" in the beginning catches empty $dlname\n\t    *\" $dlname \"*) ;;\n\t    *) rmfiles=\"$rmfiles $objdir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && rmfiles=\"$rmfiles $objdir/$name $objdir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" 'test \"$rmforce\" = yes || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" 'test \"$rmforce\" = yes || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" &&\n\t     test \"$pic_object\" != none; then\n\t    rmfiles=\"$rmfiles $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" &&\n\t     test \"$non_pic_object\" != none; then\n\t    rmfiles=\"$rmfiles $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test \"$mode\" = clean ; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    rmfiles=\"$rmfiles $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      rmfiles=\"$rmfiles $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    rmfiles=\"$rmfiles $objdir/$name $objdir/${name}S.${objext}\"\n\t    if test \"$fast_install\" = yes && test -n \"$relink_command\"; then\n\t      rmfiles=\"$rmfiles $objdir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\" ; then\n\t      rmfiles=\"$rmfiles $objdir/lt-${noexename}.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n    objdir=\"$origobjdir\"\n\n    # Try to remove the ${objdir}s in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\n{ test \"$mode\" = uninstall || test \"$mode\" = clean; } &&\n    func_mode_uninstall ${1+\"$@\"}\n\ntest -z \"$mode\" && {\n  help=\"$generic_help\"\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode \\`$mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# in which we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n# vi:sw=2\n\n", "num_lines": 8407}
{"repo_name": "scripts", "repo_creator": "TheAlgorithms", "programming_language": "Shell", "code": "#!/bin/bash\n\necho -e \"Arguments:\n[0] - Used by Bash (script filename)\n[1] - Base directory\n[2] - Filename type (maximum two values)\n[3] - Ignored files or folders (optional; use \"\\\"\"./<directory_name>\"\\\"\")\n\"\n\n# Separate $2 value (filename types) if it has a comma\nif [[ \"$2\" == *\",\"* ]];\nthen\n    string=\"$2\"\n\n    str_value=${string#*,}\n    str_value2=${string%%,*}\nelse\n    str_value=\"$2\"\n    str_value2=\"$2\"\nfi\n\n# Do not run script if there are no given arguments.\nif [[ \"$1\" == \"\" ]] || [[ \"$2\" == \"\" ]];\nthen\n    echo \"No arguments given. Please specify minimum two arguments.\"\n    exit 1\nfi\n\necho \"Changed files:\"\n\nIFS=$'\\n'; set -f\nfor fname in $(find $1 -type f -name \"*$str_value2\" -or -name \"*$str_value\")\ndo\n    ignored_files=\"$(echo \"$3\" | tr \",\" \"\\n\")\"\n\n    str=\"${fname}\"\n    value=${str%/*} # If the base directory is `.`, check in all directories for the ignored filenames\n\n    for files in $ignored_files\n    do\n        if [ \"${fname}\" == \"$value/$files\" ] || [ \"$value\" == \"$files\" ];\n        then\n            continue 2\n        fi\n    done\n\n    #echo ${fname}\n    new_fname=$(echo \"${fname}\" | tr ' ' '_')\n    #echo \"      ${new_fname}\"\n    new_fname=$(echo \"${new_fname}\" | tr '[:upper:]' '[:lower:]')\n    #echo \"      ${new_fname}\"\n    new_fname=$(echo \"${new_fname}\" | tr '-' '_')\n    #echo \"      ${new_fname}\"\n    if [ \"${fname}\" != \"${new_fname}\" ]\n    then\n        echo \"      ${fname} --> ${new_fname}\"\n        git \"mv\" \"${fname}\" \"${new_fname}\" # Requires you to be in version control\n    fi\ndone\nunset IFS; set +f\n", "num_lines": 61}
{"repo_name": "scripts", "repo_creator": "TheAlgorithms", "programming_language": "Shell", "code": "#!/bin/bash\n\necho -e \"Arguments:\n[0] - Used by Bash (script filename)\n[1] - Base directory\n[2] - Filename type (maximum two values)\n[3] - Ignored files or folders (optional; use \"\\\"\"./<directory_name>\"\\\"\")\n\"\n\n# Separate $2 value (filename types) if it has a comma\nif [[ \"$2\" == *\",\"* ]];\nthen\n    string=\"$2\"\n\n    str_value=${string#*,}\n    str_value2=${string%%,*}\nelse\n    str_value=\"$2\"\n    str_value2=\"$2\"\nfi\n\n# Do not run script if there are no given arguments.\nif [[ \"$1\" == \"\" ]] || [[ \"$2\" == \"\" ]];\nthen\n    echo \"No arguments given. Please specify minimum two arguments.\"\n    exit 1\nfi\n\necho \"Changed files:\"\n\nIFS=$'\\n'; set -f\nfor fname in $(find $1 -type f -name \"*$str_value2\" -or -name \"*$str_value\")\ndo\n    ignored_files=\"$(echo \"$3\" | tr \",\" \"\\n\")\"\n\n    str=\"${fname}\"\n    value=${str%/*} # If the base directory is `.`, check in all directories for the ignored filenames\n\n    for files in $ignored_files\n    do\n        if [ \"${fname}\" == \"$value/$files\" ] || [ \"$value\" == \"$files\" ];\n        then\n            continue 2\n        fi\n    done\n\n    #echo ${fname}\n    new_fname=$(echo \"${fname}\" | tr ' ' '_')\n    #echo \"      ${new_fname}\"\n    new_fname=$(echo \"${new_fname}\" | tr '[:upper:]' '[:lower:]')\n    #echo \"      ${new_fname}\"\n    new_fname=$(echo \"${new_fname}\" | tr '-' '_')\n    #echo \"      ${new_fname}\"\n    if [ \"${fname}\" != \"${new_fname}\" ]\n    then\n        echo \"      ${fname} --> ${new_fname}\"\n        git \"mv\" \"${fname}\" \"${new_fname}\" # Requires you to be in version control\n    fi\ndone\nunset IFS; set +f\n", "num_lines": 61}
{"repo_name": "Zig", "repo_creator": "TheAlgorithms", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nZIG_TEST='zig build test'\n\n# -fsummary                    Print the build summary, even on success\n# -freference-trace            Reference trace should be shown per compile error\nArgs='-fsummary -freference-trace'\n\n## Test all algorithms\n\n# Math\n$ZIG_TEST -Dalgorithm=math/ceil $Args\n$ZIG_TEST -Dalgorithm=math/crt $Args\n$ZIG_TEST -Dalgorithm=math/primes $Args\n$ZIG_TEST -Dalgorithm=math/fibonacci $Args\n$ZIG_TEST -Dalgorithm=math/factorial $Args\n$ZIG_TEST -Dalgorithm=math/euclidianGCDivisor $Args\n$ZIG_TEST -Dalgorithm=math/gcd $Args\n\n# Data Structures\n$ZIG_TEST -Dalgorithm=ds/linkedlist $Args\n$ZIG_TEST -Dalgorithm=ds/lrucache $Args\n\n# Dynamic Programming\n\n## Sort\n$ZIG_TEST -Dalgorithm=sort/quicksort $Args\n$ZIG_TEST -Dalgorithm=sort/bubblesort $Args\n$ZIG_TEST -Dalgorithm=sort/radixsort $Args\n$ZIG_TEST -Dalgorithm=sort/mergesort $Args\n$ZIG_TEST -Dalgorithm=sort/insertsort $Args\n\n## Search\n$ZIG_TEST -Dalgorithm=search/bSearchTree $Args\n$ZIG_TEST -Dalgorithm=search/rb $Args\n\n## Threads\n$ZIG_TEST -Dalgorithm=threads/threadpool $Args\n\n## Web\n$ZIG_TEST -Dalgorithm=web/httpClient $Args\n$ZIG_TEST -Dalgorithm=web/httpServer $Args\n$ZIG_TEST -Dalgorithm=web/tls1_3 $Args\n\n## Add more...", "num_lines": 45}
{"repo_name": "actions-dev-kit", "repo_creator": "aws", "programming_language": "Shell", "code": "yarn install\nyarn run all\n", "num_lines": 3}
{"repo_name": "actions-dev-kit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"cleaning up the generated files...\"\nfind . -type f \\( -name \"*.js\" -o -name \"*.d.ts\" -o -name \"*.js.map\" -o -name \"*.d.ts.map\" \\) -print | grep '/lib/\\|/test/\\|/bin/' | grep -v 'node_modules' | xargs -I{} rm {}\necho \"cleaning done!\"", "num_lines": 4}
{"repo_name": "actions-dev-kit", "repo_creator": "aws", "programming_language": "Shell", "code": "for TAG in \"$@\"\ndo\n   git push origin :refs/tags/$TAG\ndone", "num_lines": 4}
{"repo_name": "amazon-braket-default-simulator-python", "repo_creator": "aws", "programming_language": "Shell", "code": "# current openqasm commit: 429781bb9c95ef15944861f306ac6b9e4ff0abf0\n\n# This script rebuilds the parsers from the source g4 files. Use for\n# development when making changes to the grammar.\n\nif [ ! -f \"antlr-4.9.2-complete.jar\" ]; then\n    curl -O https://www.antlr.org/download/antlr-4.9.2-complete.jar\nfi\n\ncp antlr-4.9.2-complete.jar /usr/local/lib/antlr-4.9.2-complete.jar\n\nexport CLASSPATH=\".:/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH\"\nalias antlr4='java -Xmx500M -cp \"/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH\" org.antlr.v4.Tool'\nalias grun='java -Xmx500M -cp \"/usr/local/lib/antlr-4.9.2-complete.jar:$CLASSPATH\" org.antlr.v4.gui.TestRig'\n\ncd src/braket/default_simulator/openqasm/parser || exit\nantlr4 -Dlanguage=Python3 -visitor BraketPragmasLexer.g4 BraketPragmasParser.g4 -o generated\nantlr4 -Dlanguage=Python3 -visitor qasm3Lexer.g4 qasm3Parser.g4 -o generated\ncd generated || exit\nrm BraketPragmasParser.interp BraketPragmasParser.tokens BraketPragmasLexer.interp \\\n  BraketPragmasLexer.tokens BraketPragmasParserListener.py qasm3Lexer.interp \\\n  qasm3Lexer.tokens qasm3Parser.interp qasm3Parser.tokens qasm3ParserListener.py\ncd ../../../../../.. || exit\n", "num_lines": 24}
{"repo_name": "amazon-braket-default-simulator-python", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#!/bin/sh\n\nset -e\n\nREPOSITORY_ROOT=\"$(git rev-parse --show-toplevel)\"\nWORKING_BRANCH=\"$(git rev-parse --abbrev-ref HEAD)\"\nHAS_UNCOMMITTED_CHANGES=\"$(git status --porcelain)\"\n\n# Remove any old data from previous executions\nrm -rf \"$REPOSITORY_ROOT/test/.benchmarks\"\n# Stash uncommitted changes (if any)\nif [ -n \"$HAS_UNCOMMITTED_CHANGES\" ]; then git stash -u; fi\ngit checkout main\n# Execute performance tests against the latest commit on the main branch\npytest --benchmark-autosave --benchmark-only --benchmark-timer='time.process_time' --benchmark-warmup='on' --benchmark-warmup-iterations=100 performance\n# Stash the performance test execution results and switch back to the working branch\ngit stash -u && git checkout $WORKING_BRANCH\n# Retrieve the stashed performance test execution results for the main branch (to compare against)\ngit stash pop\n# Retrieve the uncommitted changes which had been stashed (if any)\nif [ -n \"$HAS_UNCOMMITTED_CHANGES\" ]; then git stash pop; fi\n# Execute the performance tests and compare the results against the main branch.\n# Fails if there >= 5% increase in the minimum execution time of any test\npytest --benchmark-autosave --benchmark-only --benchmark-timer='time.process_time' --benchmark-warmup='on' --benchmark-warmup-iterations=100 --benchmark-compare --benchmark-compare-fail=min:5% performance\n# Cleanup benchmark metadata\nrm -rf \"$REPOSITORY_ROOT/test/.benchmarks\"\n", "num_lines": 40}
{"repo_name": "amazon-braket-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by Braket.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\ndesc_output=$(aws ecr describe-repositories --repository-names ${image} 2>&1)\n\nif [ $? -ne 0 ]\nthen\n    if echo ${desc_output} | grep -q RepositoryNotFoundException\n    then\n        aws ecr create-repository --repository-name \"${image}\" > /dev/null\n    else\n        >&2 echo ${desc_output}\n    fi\nfi\n\naws ecr get-login-password --region us-west-2 | docker login -u AWS --password-stdin 292282985366.dkr.ecr.us-west-2.amazonaws.com\naws ecr get-login-password --region ${region} | docker login -u AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n\n\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} -f dockerfile .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 58}
{"repo_name": "amazon-braket-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "# This copied this file from https://github.com/aws/aws-codebuild-docker-images/tree/master/local_builds, and have modified a bit as per the use case here. \n\n#!/bin/bash\n\nCOMPOSE_HTTP_TIMEOUT=120 \n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -r        Used to specify a report output directory.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:r:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        r  ) report_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\necho \"${buildspec:-empty}\"\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run -i \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -n \"$report_dir\" ]\nthen\n    docker_command+=\" -e \\\"REPORTS=$(allOSRealPath \"$report_dir\")\\\"\"\nfi\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" $local_agent_image\"\nelse\n    docker_command+=\" public.ecr.aws/codebuild/local-builds:latest\"\nfi\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command", "num_lines": 211}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncd \"$(dirname \"$0\")\"\nk8sDirPrefix=\"./k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring\"\necsDirPrefix=\"./ecs-task-definition-templates/deployment-mode/daemon-service/cwagent-ecs-instance-metric\"\n\nnewK8sVersion=\"k8s/1.3.0\"\nagentVersion=\"amazon/cloudwatch-agent:1.247355.0b252062\"\nfluentdVersion=\"fluent/fluentd-kubernetes-daemonset:v1.7.3-debian-cloudwatch-1.0\"\nfluentBitVersion=\"amazon/aws-for-fluent-bit:2.10.0\"\n\nk8sPrometheusDirPrefix=\"./k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus\"\necsPrometheusDirPrefix=\"./ecs-task-definition-templates/deployment-mode/replica-service/cwagent-prometheus\"\n\n# replace agent version for ECS Prometheus\nsed -i'.bak' \"s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${agentVersion}|g\" ${ecsPrometheusDirPrefix}/cwagent-prometheus-task-definition.json\nrm ${ecsPrometheusDirPrefix}/cwagent-prometheus-task-definition.json.bak\nsed -i'.bak' \"s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${agentVersion}|g\" ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml\nrm ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-awsvpc.yaml.bak\nsed -i'.bak' \"s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${agentVersion}|g\" ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml\nrm ${ecsPrometheusDirPrefix}/cloudformation-quickstart/cwagent-ecs-prometheus-metric-for-bridge-host.yaml.bak\n\n# replace agent and k8s version for K8s Prometheus\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${agentVersion}|g\" ${k8sPrometheusDirPrefix}/prometheus-eks.yaml\nrm ${k8sPrometheusDirPrefix}/prometheus-eks.yaml.bak\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*\\(-prometheus\\)\\?|${agentVersion}|g\" ${k8sPrometheusDirPrefix}/prometheus-k8s.yaml\nrm ${k8sPrometheusDirPrefix}/prometheus-k8s.yaml.bak\n\n# replace agent version for ECS\nsed -i'.bak' \"s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*|${agentVersion}|g\" ${ecsDirPrefix}/cwagent-ecs-instance-metric.json\nrm ${ecsDirPrefix}/cwagent-ecs-instance-metric.json.bak\n\nsed -i'.bak' \"s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*|${agentVersion}|g\" ${ecsDirPrefix}/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json\nrm ${ecsDirPrefix}/cloudformation-quickstart/cwagent-ecs-instance-metric-cfn.json.bak\n\n# replace agent, fluentD and fluent-bit version for K8s\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/cloudwatch-agent:[0-9]*\\.[0-9]*\\.[0-9a-z]*|${agentVersion}|g\" ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml\nrm ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml.bak\n\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*|${newK8sVersion}|g;s|fluent/fluentd-kubernetes-daemonset:.*|${fluentdVersion}|g\" ${k8sDirPrefix}/fluentd/fluentd.yaml\nrm ${k8sDirPrefix}/fluentd/fluentd.yaml.bak\n\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/aws-for-fluent-bit.*|${fluentBitVersion}|g\" ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml\nrm ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml.bak\n\nsed -i'.bak' \"s|k8s/[0-9]*\\.[0-9]*\\.[0-9a-z]*|${newK8sVersion}|g;s|amazon/aws-for-fluent-bit.*|${fluentBitVersion}|g\" ${k8sDirPrefix}/fluent-bit/fluent-bit-compatible.yaml\nrm ${k8sDirPrefix}/fluent-bit/fluent-bit-compatible.yaml.bak\n\n# generate quickstart manifest for K8s\nOUTPUT=${k8sDirPrefix}/quickstart/cwagent-fluentd-quickstart.yaml\nOUTPUT_FLUENT_BIT=${k8sDirPrefix}/quickstart/cwagent-fluent-bit-quickstart.yaml\n\ncat ${k8sDirPrefix}/cloudwatch-namespace.yaml >${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ${k8sDirPrefix}/cwagent/cwagent-serviceaccount.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ${k8sDirPrefix}/cwagent/cwagent-configmap.yaml | sed \"s|\\\"logs|\\\"agent\\\": {\\\\\n        \\\"region\\\": \\\"{{region_name}}\\\"\\\\\n      },\\\\\n      \\\"logs|g\" >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ${k8sDirPrefix}/fluentd/fluentd-configmap.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ${k8sDirPrefix}/fluentd/fluentd.yaml >>${OUTPUT}\n\ncat ${k8sDirPrefix}/cloudwatch-namespace.yaml >${OUTPUT_FLUENT_BIT}\necho -e \"\\n---\\n\" >>${OUTPUT_FLUENT_BIT}\ncat ${k8sDirPrefix}/cwagent/cwagent-serviceaccount.yaml >>${OUTPUT_FLUENT_BIT}\necho -e \"\\n---\\n\" >>${OUTPUT_FLUENT_BIT}\ncat ${k8sDirPrefix}/cwagent/cwagent-configmap.yaml | sed \"s|\\\"logs|\\\"agent\\\": {\\\\\n        \\\"region\\\": \\\"{{region_name}}\\\"\\\\\n      },\\\\\n      \\\"logs|g\" >>${OUTPUT_FLUENT_BIT}\necho -e \"\\n---\\n\" >>${OUTPUT_FLUENT_BIT}\ncat ${k8sDirPrefix}/cwagent/cwagent-daemonset.yaml >>${OUTPUT_FLUENT_BIT}\necho -e \"\\n---\\n\" >>${OUTPUT_FLUENT_BIT}\ncat ${k8sDirPrefix}/fluent-bit/fluent-bit-configmap.yaml >>${OUTPUT_FLUENT_BIT}\necho -e \"\\n---\\n\" >>${OUTPUT_FLUENT_BIT}\ncat ${k8sDirPrefix}/fluent-bit/fluent-bit.yaml >>${OUTPUT_FLUENT_BIT}\n", "num_lines": 82}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncd \"$(dirname \"$0\")\"\n\nnewversion=\"k8s\\/1.0.1\"\n\nsed -i'.bak' \"s/k8s\\/[0-9]*\\.[0-9]*\\.[0-9]*/$newversion/g\" ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml\nrm ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml.bak\n\nsed -i'.bak' \"s/k8s\\/[0-9]*\\.[0-9]*\\.[0-9]*/$newversion/g\" ./fluentd/fluentd.yaml\nrm ./fluentd/fluentd.yaml.bak\n\nOUTPUT=./quickstart/cwagent-fluentd-quickstart.yaml\n\ncat ./cloudwatch-namespace.yaml >${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ./cwagent-kubernetes-monitoring/cwagent-serviceaccount.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ./cwagent-kubernetes-monitoring/cwagent-configmap.yaml | sed \"s|\\\"logs|\\\"agent\\\": {\\\\\n        \\\"region\\\": \\\"{{region_name}}\\\"\\\\\n      },\\\\\n      \\\"logs|g\" >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ./cwagent-kubernetes-monitoring/cwagent-daemonset.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ./fluentd/fluentd-configmap.yaml >>${OUTPUT}\necho -e \"\\n---\\n\" >>${OUTPUT}\ncat ./fluentd/fluentd.yaml >>${OUTPUT}\n", "num_lines": 29}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nset -u\nset -x\nset -o pipefail\necho \"****************************************\"\necho \"Creating tar file for Mac OS X ${ARCH}  \"\necho \"****************************************\"\n\nAGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION | sed -e \"s/-/+/g\")\necho \"BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}\"\n\nmkdir -p ${BUILD_SPACE}/bin/darwin/${ARCH}/\n\necho \"Creating darwin folders\"\nMACHINE_ROOT=\"/opt/aws/amazon-cloudwatch-agent/\"\nBUILD_ROOT=\"${BUILD_SPACE}/private/darwin_${ARCH}\"\nTAR_NAME=\"amazon-cloudwatch-agent.tar.gz\"\n\necho \"Creating darwin workspace\"\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}logs\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}bin\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}etc\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}etc/amazon-cloudwatch-agent.d\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}var\nmkdir -p ${BUILD_ROOT}${MACHINE_ROOT}doc\nmkdir -p ${BUILD_ROOT}/Library/LaunchDaemons\n\n############################# create the symbolic links\n# log\nmkdir -p ${BUILD_ROOT}/var/log/amazon\nln -f -s /opt/aws/amazon-cloudwatch-agent/logs ${BUILD_ROOT}/var/log/amazon/amazon-cloudwatch-agent\n\necho \"Copying application files\"\ncp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}${MACHINE_ROOT}\ncp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}${MACHINE_ROOT}\ncp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}${MACHINE_ROOT}\ncp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}${MACHINE_ROOT}\ncp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/config-translator ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}${MACHINE_ROOT}bin/\ncp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}${MACHINE_ROOT}etc/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}${MACHINE_ROOT}doc/\ncp ${PREPKGPATH}/com.amazon.cloudwatch.agent.plist ${BUILD_ROOT}/Library/LaunchDaemons/\n\necho \"Setting permissions as required by launchd\"\nchmod 600 ${BUILD_ROOT}/Library/LaunchDaemons/*\nchmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/amazon-cloudwatch-agent\nchmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/amazon-cloudwatch-agent-ctl\nchmod ug+rx ${BUILD_ROOT}${MACHINE_ROOT}bin/start-amazon-cloudwatch-agent\n\necho \"Creating tar\"\n(\n     cd ${BUILD_ROOT}\n     tar -czf $TAR_NAME *\n)\n\necho \"Archive created at ${BUILD_ROOT}/${TAR_NAME}\"\n\necho \"Copying tarball to bin\"\nmv ${BUILD_ROOT}/${TAR_NAME} ${BUILD_SPACE}/bin/darwin/${ARCH}/${TAR_NAME}\nls -ltr ${BUILD_SPACE}/bin/darwin/${ARCH}/*.tar.gz\n", "num_lines": 67}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating deb file for Debian Linux ${ARCH}\"\necho \"****************************************\"\nset -e\n\nAGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION)\nBUILD_ROOT=\"${BUILD_SPACE}/private/linux_${ARCH}/debian\"\necho \"BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}   pre-package location:${PREPKGPATH}\"\necho \"Creating debian folders\"\n\nmkdir -p ${BUILD_SPACE}/bin/linux/${ARCH}/\nmkdir -p ${BUILD_ROOT}/bin\nmkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/logs\nmkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/var\nmkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d\nmkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin\nmkdir -p ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/doc\nmkdir -p ${BUILD_ROOT}/etc/init\nmkdir -p ${BUILD_ROOT}/etc/systemd/system/\n\necho \"Copying application files\"\ncp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent.service ${BUILD_ROOT}/etc/systemd/system/\ncp ${PREPKGPATH}/config-translator ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/etc/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent.conf ${BUILD_ROOT}/etc/init/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/doc/\n\n############################# create the symbolic links here to make them managed by dpkg\n# bin\nmkdir -p ${BUILD_ROOT}/usr/bin\nln -f -s /opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/usr/bin/amazon-cloudwatch-agent-ctl\n# etc\nmkdir -p ${BUILD_ROOT}/etc/amazon\nln -f -s /opt/aws/amazon-cloudwatch-agent/etc ${BUILD_ROOT}/etc/amazon/amazon-cloudwatch-agent\n# log\nmkdir -p ${BUILD_ROOT}/var/log/amazon\nln -f -s /opt/aws/amazon-cloudwatch-agent/logs ${BUILD_ROOT}/var/log/amazon/amazon-cloudwatch-agent\n# pid\nmkdir -p ${BUILD_ROOT}/var/run/amazon\nln -f -s /opt/aws/amazon-cloudwatch-agent/var ${BUILD_ROOT}/var/run/amazon/amazon-cloudwatch-agent\n\ncp ${BUILD_SPACE}/packaging/debian/conffiles ${BUILD_ROOT}/\ncp ${BUILD_SPACE}/packaging/debian/preinst ${BUILD_ROOT}/\ncp ${BUILD_SPACE}/packaging/debian/prerm ${BUILD_ROOT}/\ncp ${BUILD_SPACE}/packaging/debian/debian-binary ${BUILD_ROOT}/\n\nchmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent\nchmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl\nchmod ug+rx ${BUILD_ROOT}/opt/aws/amazon-cloudwatch-agent/bin/start-amazon-cloudwatch-agent\n\necho \"Constructing the control file\"\necho 'Package: amazon-cloudwatch-agent' >${BUILD_ROOT}/control\necho \"Architecture: ${ARCH}\" >>${BUILD_ROOT}/control\necho -n 'Version: ' >>${BUILD_ROOT}/control\necho -n ${AGENT_VERSION} >>${BUILD_ROOT}/control\necho '-1' >>${BUILD_ROOT}/control\n\ncat ${BUILD_SPACE}/packaging/debian/control >>${BUILD_ROOT}/control\n\necho \"Setting permissioning as required by debian\"\ncd ${BUILD_ROOT}/..\nfind ./debian -type d | xargs chmod 755\ncd ~-\n\n# the below permissioning is required by debian\ncd ${BUILD_ROOT}\ntar czf data.tar.gz opt etc usr var --owner=0 --group=0\ncd ~-\ncd ${BUILD_ROOT}\ntar czf control.tar.gz control conffiles preinst prerm --owner=0 --group=0\ncd ~-\n\necho \"Creating the debian package\"\necho \"Constructing the deb packagage\"\nar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/debian-binary\nar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/control.tar.gz\nar r ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_ROOT}/data.tar.gz\n\necho \"Copying debian files to bin\"\n\nmv ${BUILD_ROOT}/bin/amazon-cloudwatch-agent-${AGENT_VERSION}-1.deb ${BUILD_SPACE}/bin/linux/${ARCH}/amazon-cloudwatch-agent.deb\nls -ltr ${BUILD_SPACE}/bin/linux/${ARCH}/*.deb\n", "num_lines": 94}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"*************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL ${ARCH}\"\necho \"*************************************************\"\nset -e\n\nSPEC_FILE=\"${PREPKGPATH}/amazon-cloudwatch-agent.spec\"\nBUILD_ROOT=\"${BUILD_SPACE}/private/linux_${ARCH}/rpm-build\"\nAGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION | sed -e \"s/-/+/g\")\n\necho \"BUILD_SPACE: ${BUILD_SPACE}  agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}\"\n\n\necho \"Creating rpm-build workspace\"\n\nmkdir -p ${BUILD_SPACE}/bin/linux/${ARCH}/\nmkdir -p ${BUILD_ROOT}/{RPMS,SRPMS,BUILD,SOURCES,SPECS,BUILDROOT}\nmkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/logs\nmkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/var\nmkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d\nmkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin\nmkdir -p ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/doc\nmkdir -p ${BUILD_ROOT}/SOURCES/etc/init\nmkdir -p ${BUILD_ROOT}/SOURCES/etc/systemd/system/\n\necho \"Copying application files\"\n\ncp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent.service ${BUILD_ROOT}/SOURCES/etc/systemd/system/\ncp ${PREPKGPATH}/config-translator ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/config-downloader ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/start-amazon-cloudwatch-agent ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/\ncp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/etc/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent.conf ${BUILD_ROOT}/SOURCES/etc/init/amazon-cloudwatch-agent.conf\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/doc/\n\nchmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent\nchmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl\nchmod ug+rx ${BUILD_ROOT}/SOURCES/opt/aws/amazon-cloudwatch-agent/bin/start-amazon-cloudwatch-agent\ntar -zcvf ${BUILD_ROOT}/SOURCES/amazon-cloudwatch-agent.tar.gz -C ${BUILD_ROOT}/SOURCES opt etc\n\nrm -rf ${BUILD_ROOT}/SOURCES/opt ${BUILD_ROOT}/SOURCES/etc\n\necho \"Creating the rpm package\"\n\nrpmbuild -bb -v --clean --define \"AGENT_VERSION $AGENT_VERSION\" --define \"_topdir ${BUILD_ROOT}\" ${SPEC_FILE} --target ${TARGET_SUPPORTED_ARCH}\n\necho \"Copying rpm files to bin\"\n\nmv ${BUILD_ROOT}/RPMS/${TARGET_SUPPORTED_ARCH}/amazon-cloudwatch-agent-${AGENT_VERSION}-1.${TARGET_SUPPORTED_ARCH}.rpm ${BUILD_SPACE}/bin/linux/${ARCH}/amazon-cloudwatch-agent.rpm\nls -ltr ${BUILD_SPACE}/bin/linux/${ARCH}/*.rpm\n", "num_lines": 59}
{"repo_name": "amazon-cloudwatch-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows amd64\"\necho \"****************************************\"\nset -e\n\nBUILD_ROOT=\"${BUILD_SPACE}/private/windows_${ARCH}/\"\nAGENT_VERSION=$(cat ${PREPKGPATH}/CWAGENT_VERSION)\necho \"BUILD_SPACE: ${BUILD_SPACE}    agent_version: ${AGENT_VERSION}  pre-package location:${PREPKGPATH}\"\necho \"Creating windows folders\"\n\nmkdir -p \"${BUILD_ROOT}/amazon-cloudwatch-agent\"\nmkdir -p ${BUILD_SPACE}/bin/windows/${ARCH}/\necho \"Copying application files\"\n\necho \"Copying application files\"\ncp ${PREPKGPATH}/LICENSE ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/NOTICE ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/THIRD-PARTY-LICENSES ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/RELEASE_NOTES ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/CWAGENT_VERSION ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-ctl.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/install.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/uninstall.ps1 ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/config-translator.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/config-downloader.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-config-wizard.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/start-amazon-cloudwatch-agent.exe ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/common-config.toml ${BUILD_ROOT}/amazon-cloudwatch-agent/\ncp ${PREPKGPATH}/amazon-cloudwatch-agent-schema.json ${BUILD_ROOT}/amazon-cloudwatch-agent/\n\necho \"Constructing the zip package\"\n\nif [ -f ${BUILD_ROOT}/amazon-cloudwatch-agent.zip ]; then\n     rm ${BUILD_ROOT}/amazon-cloudwatch-agent.zip\nfi\ncd ${BUILD_ROOT}\n\nzip -r amazon-cloudwatch-agent-${AGENT_VERSION}.zip *\n\nmv ${BUILD_ROOT}/amazon-cloudwatch-agent-${AGENT_VERSION}.zip ${BUILD_SPACE}/bin/windows/${ARCH}/amazon-cloudwatch-agent.zip\nls -ltr ${BUILD_SPACE}/bin/windows/${ARCH}/amazon-cloudwatch-agent.zip\n", "num_lines": 44}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#get the version of the agent\nAGENT_VERSION=$(</tmp/CWAGENT_VERSION)\n\n#create a .pkg file\nrm -rf /tmp/AmazonCWAgentPackage\nmkdir /tmp/AmazonCWAgentPackage\ngunzip -c /tmp/amazon-cloudwatch-agent.tar.gz | tar -C /tmp/AmazonCWAgentPackage -xvf -\nCOMMON_CONFIG_PATH=/tmp/AmazonCWAgentPackage/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml\nSAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY\nmv ${COMMON_CONFIG_PATH} ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX}\nif [ $? -ne 0 ]; then\n    echo \"Failed to mv common-config.toml\"\n    exit 1\nfi\n\nmkdir /tmp/AmazonAgentScripts\nmv preinstall.sh /tmp/AmazonAgentScripts/preinstall\nmv postinstall.sh /tmp/AmazonAgentScripts/postinstall\nchmod +x /tmp/AmazonAgentScripts/preinstall\nchmod +x /tmp/AmazonAgentScripts/postinstall\n\nrm -rf artifact\nmkdir artifact\nsudo pkgbuild --root /tmp/AmazonCWAgentPackage/ --install-location \"/\" --scripts /tmp/AmazonAgentScripts --identifier com.amazon.cloudwatch.agent --version=$AGENT_VERSION artifact/amazon-cloudwatch-agent.pkg\nbucketPath=\"s3://$1/integration-test/packaging/$2/$3/amazon-cloudwatch-agent.pkg\"\nif [[ $2 = \"nosha\" ]]; then\n    # SHA parameter is empty, this must be a prod, nonprod, or nightly build.\n    bucketPath=\"s3://$1/$3/amazon-cloudwatch-agent.pkg\"\nfi\naws s3 cp ./artifact/amazon-cloudwatch-agent.pkg $bucketPath\necho \"bucket path, $bucketPath\"\n\n#TODO uncomment for mac specific signing gpg is supported\n## create a package.tar.gz for the uploading it to signing bucket\n#tar -cvzf artifact.gz -C artifact .\n#tar -cvzf  package.tar.gz manifest.yaml artifact.gz\n#\n##upload the .pkg file created\n#/usr/local/bin/aws s3 cp /tmp/package.tar.gz \"s3://macos-cwagent-binaries/$AGENT_VERSION/pre-signed/package.tar.gz\" --acl public-read\n", "num_lines": 42}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Creating a default user cwagent\"\nCOMMON_CONFIG_PATH=/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml\nSAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY\nif [ ! -f ${COMMON_CONFIG_PATH} ]; then\n     cp ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} ${COMMON_CONFIG_PATH}\nfi\n\nif [[ cwagent == $(sudo dscl . -list /Users UniqueID | awk '{print $1}' | grep -w cwagent) ]]; then\n     echo \"User already exists!\"\n     exit 0\nfi\n\nLastID=$(sudo dscl . -list /Users UniqueID | awk '{print $2}' | sort -n | tail -1)\nNextID=$((LastID + 1))\n\n. /etc/rc.common\nsudo dscl . create /Users/cwagent\nsudo dscl . create /Users/cwagent RealName cwagent\n\nsudo dscl . create /Users/cwagent UniqueID $NextID\n# PrimaryGroupID of 20 to create a standard user\nsudo dscl . create /Users/cwagent PrimaryGroupID 20\nsudo dscl . create /Users/cwagent UserShell /usr/bin/false\nsudo dscl . create /Users/cwagent NFSHomeDirectory /Users/cwagent\nsudo createhomedir -u cwagent -c\n\necho \" \"\necho \"New user $(sudo dscl . -list /Users UniqueID | awk '{print $1}' | grep -w cwagent) has been created with unique ID $(sudo dscl . -list /Users UniqueID | grep -w cwagent | awk '{print $2}')\"\n", "num_lines": 31}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nCOMMON_CONFIG_PATH=/opt/aws/amazon-cloudwatch-agent/etc/common-config.toml\nSAMPLE_SUFFIX=SAMPLE_DO_NOT_MODIFY\nif [ -e ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} -a -e ${COMMON_CONFIG_PATH} ]; then\n     diff ${COMMON_CONFIG_PATH}.${SAMPLE_SUFFIX} ${COMMON_CONFIG_PATH} >/dev/null 2>&1\n     if [ $? -eq 0 ]; then\n          rm -r ${COMMON_CONFIG_PATH}\n     fi\nfi\n\nlaunchctl list com.amazon.cloudwatch.agent >/dev/null 2>&1\nif [ $? -eq 0 ]; then\n     echo \"Agent is running in the instance\"\n     echo \"Stopping the agent\"\n     launchctl unload /Library/LaunchDaemons/com.amazon.cloudwatch.agent.plist\n     echo \"Agent stopped\"\nfi\n", "num_lines": 19}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\necho sha ${cwa_github_sha}\necho clone and install agent\ncd /home/ec2-user/\ngit clone --branch ${github_test_repo_branch} ${github_test_repo}\ncd amazon-cloudwatch-agent-test\naws s3 cp s3://${binary_uri} .\nexport HOME=/root\nexport GOPATH=$HOME/go\nexport PATH=$PATH:$GOPATH/bin\necho Running command ${install_agent}\n${install_agent}\necho Starting agent now\n/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/home/ec2-user/amazon-cloudwatch-agent-test/test/userdata/agent_configs/config.json\ncloud-init status --wait", "num_lines": 15}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "countLogLines() {\n    log_path=\"${1:-}\"\n    if [ -f \"${log_path}\" ]; then\n        cat ${log_path} | wc -l\n    else\n        echo 0\n    fi\n}\ncwa_log=$(countLogLines \"/opt/aws/amazon-cloudwatch-agent/logs/amazon-cloudwatch-agent.log\")\necho \"cwa_log:${cwa_log}\"", "num_lines": 10}
{"repo_name": "amazon-cloudwatch-agent-test", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT\n\nassertStatus() {\n     keyToCheck=\"${1:-}\"\n     expectedVal=\"${2:-}\"\n\n     grepKey='unknown'\n     case \"${keyToCheck}\" in\n     cwa_running_status)\n          grepKey=\"\\\"status\\\"\"\n          ;;\n     cwa_config_status)\n          grepKey=\"\\\"configstatus\\\"\"\n          ;;\n     *)\n          echo \"Invalid Key To Check: ${keyToCheck}\" >&2\n          exit 1\n          ;;\n     esac\n\n     result=$(/usr/bin/amazon-cloudwatch-agent-ctl -a status | grep \"${grepKey}\" | awk -F: '{print $2}' | sed 's/ \"//; s/\",//')\n\n     if [ \"${result}\" = \"${expectedVal}\" ]; then\n          echo \"In step ${step}, ${keyToCheck} is expected\"\n     else\n          echo \"In step ${step}, ${keyToCheck} is NOT expected. (actual=\"${result}\"; expected=\"${expectedVal}\")\"\n          exit 1\n     fi\n}\n\n# init\nstep=0\n/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all\n/usr/bin/amazon-cloudwatch-agent-ctl -a stop\n\nstep=1\n/usr/bin/amazon-cloudwatch-agent-ctl -a status\nassertStatus \"cwa_running_status\" \"stopped\"\nassertStatus \"cwa_config_status\" \"not configured\"\n\nstep=2\n/usr/bin/amazon-cloudwatch-agent-ctl -a start\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=3\n/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c default -s\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=4\n/usr/bin/amazon-cloudwatch-agent-ctl -a prep-restart\n/usr/bin/amazon-cloudwatch-agent-ctl -a stop\nassertStatus \"cwa_running_status\" \"stopped\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=5\n/usr/bin/amazon-cloudwatch-agent-ctl -a cond-restart\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=6\n/usr/bin/amazon-cloudwatch-agent-ctl -a append-config -c default -s\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=7\n/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"not configured\"\n\nstep=8\n/usr/bin/amazon-cloudwatch-agent-ctl -a fetch-config -s\nassertStatus \"cwa_running_status\" \"running\"\nassertStatus \"cwa_config_status\" \"configured\"\n\nstep=9\n/usr/bin/amazon-cloudwatch-agent-ctl -a remove-config -c all\n/usr/bin/amazon-cloudwatch-agent-ctl -a stop\nassertStatus \"cwa_running_status\" \"stopped\"\nassertStatus \"cwa_config_status\" \"not configured\"", "num_lines": 84}
{"repo_name": "amazon-cloudwatch-logs-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n\nset -e\npackage=${1?Must provide package}\ninterfaces=${2?Must provide interface names}\noutputfile=${3?Must provide an output file}\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\ndata=$(\ncat << EOF\n// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n$(mockgen \"$package\" \"$interfaces\")\nEOF\n)\n\necho \"$data\" | goimports > \"${outputfile}\"\n", "num_lines": 45}
{"repo_name": "amazon-documentdb-jdbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -z \"$BASH_SOURCE\"\nthen\n      ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE:-$0}\")\" && pwd)/$(basename \"${BASH_SOURCE:-$0}\")\"\nelse\n      ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nfi\nCURRENT_FOLDER=\"${ABSOLUTE_PATH%/*}\"\necho \"ABSOLUTEPATH=${ABSOLUTE_PATH}\"\necho \"CURRENT_FOLDER=${CURRENT_FOLDER}\"\nTARGET_FOLDER=\"$CURRENT_FOLDER\"/target\necho TARGET_FOLDER=${TARGET_FOLDER}\nmkdir -p $TARGET_FOLDER\n\necho \"Building Docker Image\"\ndocker build -t taco-builder $CURRENT_FOLDER\n\necho \"Assembling Tableau Connector\"\ndocker run -d -it --name=taco-builder --mount type=bind,source=$TARGET_FOLDER,target=/output taco-builder\necho \"Copying Tableau Connector\"\ndocker exec taco-builder sh -c \"cp /tableau-sdk/connector-plugin-sdk/connector-packager/packaged-connector/documentdbjdbc.taco  /output\"\necho \"Verifying Tableau Connector\"\ndocker exec taco-builder sh -c \"ls -l /output\"\ndocker exec taco-builder pwd\necho \"Extracting Tableau Connector\"\ndocker cp taco-builder:/output/documentdbjdbc.taco $TARGET_FOLDER\necho \"Checking Resulting TACO FILE in $TARGET_FOLDER\"\nls -l $TARGET_FOLDER\ndocker stop taco-builder\ndocker rm taco-builder\n", "num_lines": 32}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "BUILD_DIR=cmake-build64\nBUILD_TYPE=Debug\nPROJECT_DIR=$(pwd)\nDRIVER_BIN_DIR=\"$PROJECT_DIR/build/odbc/bin\"\nDRIVER_LOG_DIR=\"$PROJECT_DIR/build/odbc/logs\"\n\nmkdir $DRIVER_LOG_DIR\n\nmkdir $BUILD_DIR\ncd $BUILD_DIR\ncmake ../src -DCMAKE_BUILD_TYPE=\"$BUILD_TYPE\" -DCODE_COVERAGE=\"ON\" -DBUILD_SHARED_LIBS=\"OFF\" -DWITH_TESTS=\"ON\" -DWITH_ODBC=\"ON\"\ncd ..\n\n# Download the DocumentDB JDBC Driver\nread -r JDBC_DRIVER_VERSION < \"${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt\"\nJDBC_DRIVER_FILENAME=\"documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar\"\nJDBC_DRIVER_FULLPATH=\"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\"\nexport DOCUMENTDB_HOME=\"$DRIVER_BIN_DIR\"\nif [ ! -f \"$JDBC_DRIVER_FULLPATH\" ]; then\n    mkdir \"$DRIVER_BIN_DIR/libs\"\n    echo \"Downloading version $JDBC_DRIVER_VERSION of JDBC driver...\"\n    curl -o \"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME\n    echo \"Download complete.\" \nfi\n\ncd cmake-build64\nmake -j 4\ncd ..\n", "num_lines": 29}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "BUILD_DIR=cmake-build64\nBUILD_TYPE=Release\nPROJECT_DIR=$(pwd)\nDRIVER_BIN_DIR=\"$PROJECT_DIR/build/odbc/bin\"\n\nmkdir cmake-build64\ncd cmake-build64\ncmake ../src -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DCODE_COVERAGE=\"OFF\" -DBUILD_SHARED_LIBS=\"OFF\" -DWITH_TESTS=\"ON\" -DWITH_ODBC=\"ON\"\ncd ..\n\n# Download the DocumentDB JDBC Driver\nread -r JDBC_DRIVER_VERSION < \"${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt\"\nJDBC_DRIVER_FILENAME=\"documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar\"\nJDBC_DRIVER_FULLPATH=\"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\"\nexport DOCUMENTDB_HOME=\"$DRIVER_BIN_DIR\"\nif [ ! -f \"$JDBC_DRIVER_FULLPATH\" ]; then\n    mkdir \"$DRIVER_BIN_DIR/libs\"\n    echo \"Downloading version $JDBC_DRIVER_VERSION of JDBC driver...\"\n    curl -o \"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME\n    echo \"Download complete.\" \nfi\n\ncd cmake-build64\nmake -j 4\ncd ..\n", "num_lines": 26}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "BUILD_DIR=cmake-build64\nBUILD_TYPE=Debug\nPROJECT_DIR=$(pwd)\nDRIVER_BIN_DIR=\"$PROJECT_DIR/build/odbc/bin\"\nDRIVER_LOG_DIR=\"$PROJECT_DIR/build/odbc/logs\"\n\nmkdir $DRIVER_LOG_DIR\n\nmkdir $BUILD_DIR\ncd $BUILD_DIR\ncmake ../src -DCMAKE_BUILD_TYPE=\"$BUILD_TYPE\" -DCODE_COVERAGE=\"ON\" -DBUILD_SHARED_LIBS=\"OFF\" -DWITH_TESTS=\"ON\" -DWITH_ODBC=\"ON\"\ncd ..\n\n# Download the DocumentDB JDBC Driver\nread -r JDBC_DRIVER_VERSION < \"${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt\"\nJDBC_DRIVER_FILENAME=\"documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar\"\nJDBC_DRIVER_FULLPATH=\"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\"\nexport DOCUMENTDB_HOME=\"$DRIVER_BIN_DIR\"\nif [ ! -f \"$JDBC_DRIVER_FULLPATH\" ]; then\n    mkdir \"$DRIVER_BIN_DIR/libs\"\n    echo \"Downloading version $JDBC_DRIVER_VERSION of JDBC driver...\"\n    curl -o \"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME\n    echo \"Download complete.\" \nfi\n\n#clean up the binary files used to generate code coverage report\nfind . -name \"*.gcda\" -type f -delete\n\ncd cmake-build64\nmake -j 4\ncd ..\n", "num_lines": 32}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "BUILD_DIR=cmake-build64\nBUILD_TYPE=Release\nPROJECT_DIR=$(pwd)\nDRIVER_BIN_DIR=\"$PROJECT_DIR/build/odbc/bin\"\n\nmkdir $BUILD_DIR\ncd $BUILD_DIR\ncmake ../src -DCMAKE_BUILD_TYPE=\"$BUILD_TYPE\" -DCODE_COVERAGE=\"OFF\" -DBUILD_SHARED_LIBS=\"OFF\" -DWITH_TESTS=\"ON\" -DWITH_ODBC=\"ON\"\nmake -j 4\n\n# Download the DocumentDB JDBC Driver\nread -r JDBC_DRIVER_VERSION < \"${PROJECT_DIR}/src/JDBC_DRIVER_VERSION.txt\"\nJDBC_DRIVER_FILENAME=\"documentdb-jdbc-$JDBC_DRIVER_VERSION-all.jar\"\nJDBC_DRIVER_FULLPATH=\"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\"\nexport DOCUMENTDB_HOME=\"$DRIVER_BIN_DIR\"\nif [ ! -f \"$JDBC_DRIVER_FULLPATH\" ]; then\n    mkdir \"$DRIVER_BIN_DIR/libs\"\n    echo \"Downloading version $JDBC_DRIVER_VERSION of JDBC driver...\"\n    curl -o \"$DRIVER_BIN_DIR/libs/$JDBC_DRIVER_FILENAME\" -L https://github.com/aws/amazon-documentdb-jdbc-driver/releases/download/v$JDBC_DRIVER_VERSION/$JDBC_DRIVER_FILENAME\n    echo \"Download complete.\" \nfi\n\ncd ..\n", "num_lines": 24}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nRESULTS_FILE=cppcheck-results.log\n\n# --force: force checks all define combinations (default max is 12)\n# -iaws-sdk-cpp: avoid checking AWS C++ SDK source files in our repo\ncppcheck --force --library=boost --library=documentdb -UWIN32 ./src/ 2>  ${RESULTS_FILE}\n\nif [ -s ${RESULTS_FILE} ]; then\n    echo \"!! Cppcheck errors found! Check ${RESULTS_FILE} for details.\"\n    exit 1\nelse\n    echo \"No Cppcheck errors found.\"\nfi\n", "num_lines": 15}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n#   Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n#   Licensed under the Apache License, Version 2.0 (the \"License\").\n#   You may not use this file except in compliance with the License.\n#   A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#   or in the \"license\" file accompanying this file. This file is distributed\n#   on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n#   express or implied. See the License for the specific language governing\n#   permissions and limitations under the License.\n#\n\n\nPROJECT_DIR=$(pwd)\nTEST_RUNNER_DIR=${PROJECT_DIR}/src/TestRunner\nWORKING_DIR=${PROJECT_DIR}\n\ncd ${WORKING_DIR}\n\npip3 install mako\n\npython3 ${TEST_RUNNER_DIR}/test_runner.py -i ${TEST_RUNNER_DIR}/mako_template.html -o ${PROJECT_DIR}/test_output.html -e ${TEST_RUNNER_DIR}/test_exclude_list.txt\n\nERROR_CODE=$?\n\ncd ..\n\nexit ${ERROR_CODE}\n", "num_lines": 34}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nSCRIPT_DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n\nCHECK=1\n\nif [[ -z \"${DOC_DB_USER_NAME}\" ]]; then\n  echo \"DOC_DB_USER_NAME environment variable is not set. Using default.\"\n  export DOC_DB_USER_NAME=documentdb\n  echo \"DOC_DB_USER_NAME=$DOC_DB_USER_NAME\"\nelse\n  echo \"DOC_DB_USER_NAME=$DOC_DB_USER_NAME\"\nfi\n\nif [[ -z \"${DOC_DB_PASSWORD}\" ]]; then\n  echo \"DOC_DB_PASSWORD environment variable is not set. Please set this variable explicitly.\"\n  CHECK=0\nelse\n  echo \"DOC_DB_PASSWORD=******\"\nfi\n\nif [[ -z \"${DOC_DB_USER}\" ]]; then\n  echo \"DOC_DB_USER environment variable is not set. Please set this variable explicitly.\"\n  CHECK=0\nelse\n  echo \"DOC_DB_USER=$DOC_DB_USER\"\nfi\n\nif [[ -z \"${DOC_DB_LOCAL_PORT}\" ]]; then\n  echo \"DOC_DB_LOCAL_PORT environment variable is not set. Please set this variable explicitly.\"\n  CHECK=0\nelse\n  echo \"DOC_DB_LOCAL_PORT=$DOC_DB_LOCAL_PORT\"\nfi\n\nif [[ -z \"${DOC_DB_PRIV_KEY_FILE}\" ]]; then\n  echo \"DOC_DB_PRIV_KEY_FILE environment variable is not set. Please set this variable explicitly.\"\n  CHECK=0\nelse\n  echo \"DOC_DB_PRIV_KEY_FILE$DOC_DB_PRIV_KEY_FILE\"\nfi\n\nif [[ -z \"${JAVA_HOME}\" ]]; then\n  echo \"JAVA_HOME environment variable is not set. Please set this variable explicitly.\"\n  CHECK=0\nelse\n  echo \"JAVA_HOME=$JAVA_HOME\"\nfi\n\nif [[ -z \"${DOCUMENTDB_HOME}\" ]]; then\n  echo \"DOCUMENTDB_HOME environment variable is not set. Using default.\"\n  export DOCUMENTDB_HOME=${SCRIPT_DIR}/../build/odbc/bin\n  echo \"DOCUMENTDB_HOME=$DOCUMENTDB_HOME\"\nelse\n  echo \"DOCUMENTDB_HOME=$DOCUMENTDB_HOME\"\nfi\n\nif [[ -z \"${ODBCINSTINI}\" ]]; then\n  echo \"ODBCINSTINI environment variable is not set. Using default.\"\n  export ODBCINSTINI=\"${SCRIPT_DIR}/../build/odbc/lib/documentdb-odbc-install.ini\"\n  echo \"ODBCINSTINI=ODBCINSTINI\"\nelse\n  echo \"ODBCINSTINI=ODBCINSTINI\"\nfi\n\n#if [[ -z \"${ODBC_LIB_PATH}\" ]]; then\n#  echo \"ODBC_LIB_PATH environment variable is not set. Using default.\"\n#  export ODBC_LIB_PATH=${SCRIPT_DIR}/../build/odbc/lib\n#  echo \"ODBC_LIB_PATH=$ODBC_LIB_PATH\"\n#else\n#  echo \"ODBC_LIB_PATH=$ODBC_LIB_PATH\"\n#fi\n\nif [[ \"${CHECK}\" -eq \"0\" ]]; then\n  echo \"Missing envrionment variables, please set them accordingly.\"\nelse\n  echo \"Environment variables are all set\"\nfi\n", "num_lines": 100}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# This script installs all required dependencies on Mac and sets the appropriate vars\n\n# get the current script directory\nPROJECT_DIR=$(pwd)\nMAC_SCRIPT_DIR=\"$PROJECT_DIR/scripts/mac\"\n\n# install formula dependencies via brew\nbrew tap homebrew/services\n\n# unlink unix ODBC driver manager\nif brew ls --versions unixodbc > /dev/null; then\n    echo \"unixodbc is installed via brew. unlink unixodbc\"\n    brew unlink unixodbc\nfi\n# check if dependnecies are installed\n\n# check if user is under the DocDB ODBC repository\nif [[ ! -f \"$MAC_SCRIPT_DIR/check_dependencies_mac.sh\" ]]; then\n    echo \"Cannot find file $MAC_SCRIPT_DIR/check_dependencies_mac.sh, please check that you're under the DocumentDB ODBC repository before executing this script\"\n    exit 1\nfi\n\nchmod +x $MAC_SCRIPT_DIR/check_dependencies_mac.sh\nsource $MAC_SCRIPT_DIR/check_dependencies_mac.sh\n# num_apps, apps_installed and req_apps are variables from check_dependencies_mac.sh\n\nif [[ \"${missing_formula}\" -eq \"0\" ]]; then\n    echo \"Most required dependencies are installed. Checking if JAVA is installed.\"\nelse\n    echo \"Installing the missing required dependencies\"\n    for (( i=0 ; i<$num_apps ; i++ )); \n    do\n        if [[ \"${apps_installed[i]}\" -eq \"0\" ]]; then\n            echo  \"${req_apps[i]} is not installed, attempt to install it with brew.\"\n            brew install ${req_apps[i]}\n            # The libiodbc package may conflict with the unixodbc package\n            if [[ \"${req_apps[i]}\" -eq \"libiodbc\" ]]; then\n                brew link --overwrite --force ${req_apps[i]}\n            fi\n        fi\n    done\nfi\n\n# [Re-]Install mongodb server\n# TODO: make re-installing mongodb server optional\n# https://github.com/aws/amazon-documentdb-odbc-driver/issues/172\nchmod +x $MAC_SCRIPT_DIR/reinstall_mongodb_mac.sh\n$MAC_SCRIPT_DIR/reinstall_mongodb_mac.sh\n\n# check if java dependency is installed\nchmod +x $MAC_SCRIPT_DIR/check_java_dependency_mac.sh\nsource $MAC_SCRIPT_DIR/check_java_dependency_mac.sh\n# jdkFound is a variable from check_java_dependency_mac.sh\n\njava_ver=corretto\nif [[ \"${jdkFound}\" -ne \"1\" ]]; then\n    echo \"$java_ver is not installed, attempt to install it with brew.\"\n    # install JAVA dependency via brew\n    brew tap homebrew/cask-versions\n    brew install --cask $java_ver\nfi\n\n# set JAVA_HOME and save JAVA /bin and JAVA /server paths to $PATH\nchmod +x $MAC_SCRIPT_DIR/set_java_def_mac.sh\nsource $MAC_SCRIPT_DIR/set_java_def_mac.sh\n\n# add llvm to path\nchmod +x $MAC_SCRIPT_DIR/set_llvm_mac.sh\nsource $MAC_SCRIPT_DIR/set_llvm_mac.sh\n\necho \"The mac dependency installation script has finshed running.\"\n", "num_lines": 89}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\n\nSCRIPT_DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n\nPROJECT_DIR=\"$SCRIPT_DIR/..\"\nODBC_LIB_PATH=\"$PROJECT_DIR/build/odbc/lib\"\nif [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n  ODBC_LIB_FILENAME=\"$ODBC_LIB_PATH/libdocumentdb-odbc.so\"\nelif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  ODBC_LIB_FILENAME=\"$ODBC_LIB_PATH/libdocumentdb-odbc.dylib\"\nfi\n\n\nif [ ! -f \"$ODBC_LIB_FILENAME\" ]\nthen\n  echo \"Cannot find ODBC library file: $ODBC_LIB_FILENAME\"\n  exit 1\nfi\n\necho \"[Amazon DocumentDB]\"            > \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\necho \"Description=Amazon DocumentDB\" >> \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\necho \"Driver=$ODBC_LIB_FILENAME\" >> \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\necho \"Setup=$ODBC_LIB_FILENAME\"  >> \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\necho \"DriverODBCVer=03.00\"       >> \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\necho \"FileUsage=0\"               >> \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\n\nif [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n  odbcinst -i -d -f \"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\nelif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  export ODBCINSTINI=\"$ODBC_LIB_PATH/documentdb-odbc-install.ini\"\n  echo \"Exported ODBCINSTINI=$ODBCINSTINI\"\nfi\n", "num_lines": 39}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# store project directory\nPROJECT_DIR=$(pwd)\n\n#find correct path to java_home_path\ndocdb_home=\"$PROJECT_DIR/build/odbc/bin\"\nset_docdb_home=\"export DOCUMENTDB_HOME=\\\"$docdb_home\\\"\"\nodbc_instini=\"$PROJECT_DIR/build/odbc/lib/documentdb-odbc-install.ini\"\nset_odbc_instini=\"export ODBCINSTINI=\\\"$odbc_instini\\\"\"\n\ncd ~\nenv_var_file=\".zshrc\"\nupdated=0\n\nif [[ ! -d \"${docdb_home}\" ]]\nthen\n    echo \"Cannot find directory \\\"${docdb_home}\\\", please check that you're under the DocumentDB ODBC repository before executing this script and that a build script has run successfully.\"\n    exit 1\nfi\n\nif [[ ! -f \"${odbc_instini}\" ]]\nthen\n    echo \"Cannot find file \\\"${odbc_instini}\\\", please check that you're under the DocumentDB ODBC repository before executing this script and that a build script has been run successfully.\"\n    exit 1\nfi\n\n# check enviornment variables and write them as needed\nif [[ \"${DOCUMENTDB_HOME}\" != \"${docdb_home}\" ]]; then\n    echo \"DOCUMENTDB_HOME is not set properly. Appending definition of DOCUMENTDB_HOME to end of ${env_var_file}\"\n    echo \"$set_docdb_home\" >> $env_var_file\n    echo \"DOCUMENTDB_HOME has been set\"\n    updated=1\nfi\n\nif [[ \"${ODBCINSTINI}\" != \"${odbc_instini}\" ]]; then\n    echo \"ODBCINSTINI is not set properly. Appending definition of ODBCINSTINI to end of ${env_var_file}\"\n    echo \"$set_odbc_instini\" >> $env_var_file\n    echo \"ODBCINSTINI has been set\"\n    updated=1\nfi\n\n# cd back to original directory\ncd $PROJECT_DIR\n\nif [[ ${updated} -eq \"0\" ]]; then\n    echo \"DOCUMENTDB_HOME and ODBCINSTINI are set properly. No new changes made to ~/$env_var_file\"\nelse\n    echo \"~/$env_var_file has been updated to set environment variables properly. Please restart your terminal to load the variables\"\nfi\n", "num_lines": 49}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# TODO: [Automate setting up environment variables when building driver on Linux](https://github.com/aws/amazon-documentdb-odbc-driver/issues/173)\n# store current directory\nCURRENT_DIR=$(pwd)\n\n#find correct path to java_home_path\n#java_home_path=\"/Library/Java/JavaVirtualMachines/temurin-18.jdk/Contents/Home\" \njava_home_path=\"/path/to/java/home\"\njava_server_path=\"$java_home_path/lib/server/\"\njava_bin_path=\"$java_home_path/bin\"\nset_java_home=\"export JAVA_HOME=\\\"$java_home_path\\\"\"\nset_java_bin_path=\"export PATH=\\\"$java_bin_path:\\$PATH\\\"\"\nset_java_server_path=\"export PATH=\\\"$java_server_path:\\$PATH\\\"\"\n# set_path=\"export PATH=\\\"$java_server_path:$java_bin_path:\\$PATH\\\"\"\n\nnew_zshrc=\"\"\n\ncd ~\nenv_var_file=\".bashrc\"\n# file=\".zshrc\"\n\n\njava_home_set=1\n# check enviornment variables\nif [[ \"${JAVA_HOME}\" != \"${java_home_path}\" ]]; then\n    echo \"JAVA_HOME is not set properly. Removing previous definitions to JAVA_HOME and give new definition\"\n    java_home_set=0\nfi\n  \n# Use IFS= to keep line indentations. \n# assumes that env_var_file may or may not end with a new line\n\ni=1  \nwhile IFS= read -r line || [ -n \"$line\" ]; do  \n  \n    #Reading each line  \n    echo \"Line No. $i : $line\"\n\n    # check if line is a comment. \n    if [[ ! \"$line\" =~ ^[[:space:]]*\\#.* ]]; then\n        echo \"TRACE - this line is not a comment, proceeding\"\n\n\n        # check that the line exports JAVA_HOME\n        if [[ \"${java_home_set}\" == \"0\"  ]] && [[ \"$line\" =~ \"export JAVA_HOME=\" ]]; then\n            # modify this line before writing to new_zshrc\n\n            # removes instances of export JAVA_HOME=\"anything\", except comments\n            line=$(echo $line | sed -e 's/(?<!(^[[:space:]]*\\#.*))(export JAVA_HOME=\\\".*?\\\")//g')\n\n            echo \"this line is setting JAVA_HOME\"\n            echo \"modified line: $line\"\n            change_zshrc=1\n        fi\n\n    fi\n\n    # remove duplicate of $set_path\n    # but this is not needed. We just need to make sure we export the path when we don't have it -AL-\n    # the search pattern is same as set_path except $var becomes '\"${var}\"', and all symbols are escaped (e.g., / becomes \\/, : becomes \\:)\n    # line=$(echo $line | sed -e 's/export PATH=\\\"'\"${JAVA_HOME}\"'\\/lib\\/server\\/\\:'\"${JAVA_HOME}\"'\\/bin:\\$PATH\\\"//g')\n\n    # if line is not white space\n    if [[ $line =~ [^[:space:]] ]]; then\n        echo \"line is not whitespace\"\n        # write this line to new_zshrc\n\n        # do not write new line if it is the first non-empty line\n        if [[ ! $new_zshrc =~ [^[:space:]] ]]; then\n            new_zshrc=\"$new_zshrc$line\"\n        else\n            new_zshrc=\"$new_zshrc\\n$line\"\n        fi\n    fi\n\n    i=$((i+1))  \ndone < $env_var_file  \n\nif [[ \"${change_zshrc}\" -eq \"1\" ]]; then\n    echo \"re-writing ${env_var_file}\"\n    echo \"$new_zshrc\" > $env_var_file\nfi\n\necho \"writing new lines to ${env_var_file}\"\n\nif [[ \"${java_home_set}\" == \"0\"  ]]; then\n    echo \"$set_java_home\" >> $env_var_file\n    java_home_set=1\nfi\n\nif [[ ! :$PATH: == *:\"$java_server_path\":* ]] ; then\n    echo \"setting JAVA server path\"\n    echo \"$set_java_server_path\" >> $env_var_file\nfi\n\nif [[ ! :$PATH: == *:\"$java_bin_path\":* ]] ; then\n    echo \"setting JAVA bin path\"\n    echo \"$set_java_bin_path\" >> $env_var_file\nfi\n\n# cd back to original directory\ncd $CURRENT_DIR\n", "num_lines": 102}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# script to check if formulas in req_apps are installed. \n\n# add the required dependencies to the req_apps array. \n# There is no need to change other variables\nreq_apps=(\"libiodbc\" \"cmake\" \"openssl\" \"boost\" \"mongo-cxx-driver\") \nnum_apps=${#req_apps[@]}\napps_installed=()\n\nfor (( i=0 ; i<$num_apps ; i++ )); \ndo\n  apps_installed+=(0)\n  if brew ls --versions ${req_apps[i]} > /dev/null; then\n    # ${req_apps[i]} is installed via brew\n    echo \"${req_apps[i]} is installed.\"\n    apps_installed[i]=1\n  else\n    # ${req_apps[i]} not installed via brew\n    echo \"${req_apps[i]} is not installed.\"\n    missing_formula=1\n  fi\ndone\n", "num_lines": 22}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# Checks that JAVA_HOME is defined, the path to JAVA_HOME exists \n# and is a JDK (i.e., include subdirectory)\nif [[ ! -z \"${JAVA_HOME}\" ]] && [[ -d \"${JAVA_HOME}\" ]] && [[ -d \"${JAVA_HOME}/include\" ]]; then\n    # Test Java in path and has minimum version\n    javaVersionString=`echo \"$(java --version)\" | head -1`\n    read -a javaVersionStringArrary <<< \"$javaVersionString\" # Reading a space-delimited string into an array\n    javaVersion=${javaVersionStringArrary[1]}\n    javaVersionArray=(${javaVersion//./ }) # separate javaVersion string by delimiter '.'\n    if [[ ${#javaVersionArray[@]} -ge 1 ]] && [[ ! -z ${javaVersionArray[0]} ]]; then\n        if [[ \"1\" -eq ${javaVersionArray[0]} ]] && [[ ! -z ${javaVersionArray[1]} ]]; then\n            if  [[ ${javaVersionArray[1]} -eq \"8\" || ${javaVersionArray[1]} -eq \"9\" ]]; then\n                jdkFound=1\n            fi\n        elif [[ ${javaVersionArray[0]} -ge \"10\" ]]; then\n            jdkFound=1\n        fi\n    fi\nfi\n\nif [[ \"${jdkFound}\" -eq \"1\" ]]; then\n    echo \"Found suitable JDK on user's machine.\"\nelse \n    echo \"Did not find JDK on user's machine. If you have JDK installed, please ensure to set JAVA_HOME to the home directory of JDK to help me find it next time.\"\nfi\n", "num_lines": 25}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n##################################################\n# Assumptions\n# 1. Environment variables DOC_DB_USER_NAME and DOC_DB_PASSWORD must be defined.\n# 2. This is running on MacOS Intel silicon\n##################################################\n\n# Get the path to the configuration file (Intel silicon)\nMONGO_CONFIG_FILE=/usr/local/etc/mongod.conf\nMONGODB_SERVICE_NAME=\"mongodb-community\"\n\nfunction update_mongod_config_authorization() {\n    MONGO_ENABLED_DISABLED=${1:-enabled}\n    if [ -f \"$MONGO_CONFIG_FILE\" ]\n    then\n        MONGO_AUTHORIZATION=$(grep -E '^[ \\t]*authorization:[ \\t]+[\"]?((enabled)?|(disabled)?)[\"]?' \"${MONGO_CONFIG_FILE}\")\n        if [ -z \"${MONGO_AUTHORIZATION}\" ]\n        then\n            echo 'security:' >> \"${MONGO_CONFIG_FILE}\"\n            echo \"    authorization: \\\"${MONGO_ENABLED_DISABLED}\\\"\" >> \"${MONGO_CONFIG_FILE}\"\n        else\n            echo \"Updating in place....\"\n            cat \"${MONGO_CONFIG_FILE}\"\n            sed \"s/^[ \\t]*authorization:.*$/    authorization: \\\"${MONGO_ENABLED_DISABLED}\\\"/g\" \"${MONGO_CONFIG_FILE}\" > \"${MONGO_CONFIG_FILE}.new\"\n            mv -f \"${MONGO_CONFIG_FILE}.new\" \"${MONGO_CONFIG_FILE}\"\n            echo \"Updated\"\n            cat \"${MONGO_CONFIG_FILE}\"\n        fi\n    else \n        echo \"Config file not found: \\\"${MONGO_CONFIG_FILE}\\\"\"\n    fi\n}\n\nbrew tap mongodb/brew\nbrew install ${MONGODB_SERVICE_NAME}\n\nupdate_mongod_config_authorization \"disabled\"\nbrew services restart ${MONGODB_SERVICE_NAME}\n\n# By reinstalling, we've disabled authorization - so we can reset the authorization from scratch.\nmongosh --eval \"db.dropAllUsers()\" \"admin\"\nmongosh --eval \"db.createUser({ user: '${DOC_DB_USER_NAME}', pwd: '${DOC_DB_PASSWORD}', roles: [ { role: 'root', db: 'admin' } ] })\" \"admin\"\nmongosh --eval \"db.createUser({ user: 'docDbRestricted', pwd: '${DOC_DB_PASSWORD}', roles: [ { role: 'readAnyDatabase', db: 'admin' } ] })\" \"admin\"\n\nupdate_mongod_config_authorization \"enabled\"\nbrew services restart ${MONGODB_SERVICE_NAME}\n", "num_lines": 48}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# store current directory\nCURRENT_DIR=$(pwd)\n\n#java_home_path points to JAVA_HOME\n#jdkFound is a variable from check_java_dependency_mac.sh.\nif [[ \"${jdkFound}\" -eq \"1\" ]]; then\n    java_home_path=$JAVA_HOME\nelse\n    java_home_path=\"/Library/Java/JavaVirtualMachines/amazon-corretto-18.jdk/Contents/Home\" \nfi\njava_server_path=\"$java_home_path/lib/server/\"\njava_bin_path=\"$java_home_path/bin\"\nset_java_home=\"export JAVA_HOME=\\\"$java_home_path\\\"\"\nset_java_bin_path=\"export PATH=\\\"$java_bin_path:\\$PATH\\\"\"\nset_java_server_path=\"export PATH=\\\"$java_server_path:\\$PATH\\\"\"\n\ncd ~\nenv_var_file=\".zshrc\"\nupdated=0\n\n# check enviornment variables\n# Checks that JAVA_HOME is defined, the path to JAVA_HOME exists \n# and is a JDK (i.e., include subdirectory)\nif [[ \"${JAVA_HOME}\" != \"${java_home_path}\" ]]; then\n    if [[ -d \"${java_home_path}\" ]]; then\n        echo \"JAVA_HOME is not set properly. Appending definition of JAVA_HOME to end of ${env_var_file}\"\n        echo \"$set_java_home\" >> $env_var_file\n        echo \"JAVA_HOME has been set\"\n        updated=1\n    else\n        echo \"cannot find directory \\\"${java_home_path}\\\", please check if JAVA 18 is installed.\"\n        dir_not_found=1\n    fi\nfi\n\nif [[ ! :$PATH: == *:\"$java_server_path\":* ]] ; then\n    if [[ -d \"${java_server_path}\" ]]; then\n        echo \"setting JAVA server path\"\n        echo \"$set_java_server_path\" >> $env_var_file\n        echo \"JAVA server path has been set\"\n        updated=1\n    else\n        echo \"cannot find directory \\\"${java_server_path}\\\", please check if JAVA 18 is installed or find JAVA /server path manually.\"        \n        dir_not_found=1\n    fi\nfi\n\nif [[ ! :$PATH: == *:\"$java_bin_path\":* ]] ; then\n    if [[ -d \"${java_bin_path}\" ]]; then\n        echo \"setting JAVA bin path\"\n        echo \"$set_java_bin_path\" >> $env_var_file\n        echo \"JAVA bin path has been set\"\n        updated=1\n    else\n        echo \"cannot find directory \\\"${java_bin_path}\\\", please check if JAVA 18 is installed or find JAVA /bin path manually.\"        \n        dir_not_found=1\n    fi\nfi\n\n# cd back to original directory\ncd $CURRENT_DIR\n\nif [[ ${dir_not_found} -eq \"1\" ]]; then\n    echo \"One or more JAVA directories not found. Please make sure JAVA_HOME, JAVA bin path, and JAVA server path are set properly manually.\"\nelif [[ ${updated} -eq \"0\" ]]; then\n    echo \"JAVA_HOME, JAVA bin path, and JAVA server path are set properly. No new changes made to ~/$env_var_file\"\nelse\n    echo \"~/$env_var_file has been updated to set environment variables properly. Please restart your terminal to load the variables\"\nfi\n", "num_lines": 70}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "# store project directory\nPROJECT_DIR=$(pwd)\n\n#llvm_path points to path to LLVM\nllvm_path=\"/Library/Developer/CommandLineTools/usr/bin/\"\nset_llvm_path=\"export PATH=\\\"$llvm_path:\\$PATH\\\"\"\nllvm_app_path\"/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/\"\nset_llvm_app_path=\"export PATH=\\\"$llvm_app_path:\\$PATH\\\"\"\n\ncd ~\nenv_var_file=\".zshrc\"\nupdated=0\n\nif [[ ! :$PATH: == *:\"$llvm_path\":* ]] && [[ ! :$PATH: == *:\"$llvm_app_path\":* ]]; then\n    echo \"attempt to add llvm to your path\"    \n    if [[ -d \"${llvm_path}\" ]]; then\n        echo \"setting llvm path\"\n        echo \"$set_llvm_path\" >> $env_var_file\n        echo \"llvm path has been set\"\n        updated=1\n    else\n        echo \"cannot find directory \\\"${llvm_path}\\\", checking if \\\"${llvm_app_path}\\\" exists.\"\n        if [[ -d \"${llvm_app_path}\" ]]; then\n            echo \"setting XCode application llvm path\"\n            echo \"$set_llvm_app_path\" >> $env_var_file\n            echo \"XCode application llvm path has been set\"\n            updated=1\n        else\n            echo \"cannot find directory \\\"${set_llvm_app_path}\\\". Will not update \\$PATH. XCode installation is required.\"\n            no_llvm_found=1\n        fi\n    fi\nfi\n\n# cd back to original directory\ncd $PROJECT_DIR\n\nif [[ ${no_llvm_found} -eq \"1\" ]]; then\n    echo \"No llvm found on your machine. No new updates has been made to ~/$env_var_file. XCode installation is required for DocumentDB ODBC driver to build. After XCode is installed, run ./scripts/mac/set_llvm_mac.sh to add the path to llvm to your \\$PATH.\"\nelif [[ ${updated} -eq \"0\" ]]; then\n    echo \"PATH includes at least 1 path to llvm. No new changes made to ~/$env_var_file\"\nelse\n    echo \"~/$env_var_file has been updated to include llvm in your \\$PATH. Please restart your terminal to load the system path\"\nfi\n", "num_lines": 45}
{"repo_name": "amazon-documentdb-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n##################################################\n# Assumptions\n# 1. Mongo server running and listening on port 27017\n# 2. Mongo started with the environment variables DOC_DB_USER_NAME and DOC_DB_PASSWORD\n##################################################\n\nif [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n  SCRIPT_DIR=$( cd -- \"$( dirname -- $0 )\"  && pwd )\nelif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n  SCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\nfi\n\nTEST_INPUT_FOLDER=\"${SCRIPT_DIR}/../input\"\nDATABASE_NAME=\"odbc-test\"\n\n# Clear the database so we don't have any existing data\nmongosh --quiet -u=\"${DOC_DB_USER_NAME}\" -p=\"${DOC_DB_PASSWORD}\" --authenticationDatabase=admin \\\n    --eval \"db.dropDatabase()\" \"${DATABASE_NAME}\"\n\n# Load each test input file\nfor FILENAME in \"${TEST_INPUT_FOLDER}\"/*.json\ndo\n    # Collection will be named the same as the input file base name\n    COLLECTION_NAME=\"$(basename -- ${FILENAME%.json})\"\n    TEST_FILE_NAME=\"$(basename -- ${FILENAME})\"\n\n    mongoimport -u=\"${DOC_DB_USER_NAME}\" -p=\"${DOC_DB_PASSWORD}\" --authenticationDatabase=admin \\\n        -d=\"${DATABASE_NAME}\" -c=\"${COLLECTION_NAME}\" --jsonArray \\\n        --file=\"\"\"${TEST_INPUT_FOLDER}/${TEST_FILE_NAME}\"\"\"\n    if [ $? -ne 0 ]\n    then\n        exit 1\n    fi\ndone\n", "num_lines": 37}
{"repo_name": "amazon-ec2-hibinit-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPATH=/sbin:/bin:/usr/bin\nfailed='false'\n\n# Hibernation selects the swapfile with highest priority. Since there may be\n# other swapfiles configured, ensure /swap is selected as hibernation\n# target by setting to maximum priority.\nswap_priority=32767\n\nhibernate()\n{\n        swapon --priority=$swap_priority /swap && /usr/sbin/pm-hibernate\n        if [ $? -ne 0 ]\n        then\n            logger \"Hibernation failed, Sleeping 2 mins before retry\"\n            failed='true'\n        else\n            failed='false'\n        fi\n        swapoff /swap\n}\n\ncase \"$2\" in\n    SBTN)\n        # The iteration had been placed here to add retry logic to hibernation \n        # in case of failures and to avoid force stop of instances after 20min\n        for i in 1 2 3\n        do\n          hibernate\n          if [ $failed == 'true' ];\n          then\n            sleep 2m\n          else\n           break\n          fi\n       done\n       ;;\n    *)\n        logger \"ACPI action undefined: $2\" ;;\nesac\n", "num_lines": 42}
{"repo_name": "amazon-ec2-hibinit-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPATH=/sbin:/bin:/usr/bin\nfailed='false'\n\nhibernate()\n{\n        swapon /swap\n        systemctl hibernate\n\n        if [ $? -ne 0 ]\n        then\n            logger \"Hibernation failed, Sleeping 2 mins before retry\"\n            failed='true'\n        else\n            failed='false'\n        fi\n}\n\ncase \"$2\" in\n    SBTN)\n        # The iteration had been placed here to add retry logic to hibernation \n        # in case of failures and to avoid force stop of instances after 20min\n        for i in 1 2 3\n        do\n          hibernate\n          if [ $failed == 'true' ];\n          then\n            sleep 2m\n          else\n           break\n          fi\n       done\n       ;;\n    *)\n        logger \"ACPI action undefined: $2\" ;;\nesac\n", "num_lines": 38}
{"repo_name": "amazon-ec2-hibinit-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n  \n# This is called before hibernating or after resuming, as follows:\n# $0=/usr/lib/systemd/system-sleep/sleepyhead, $1=pre, $2=suspend\n# ...and when the lid is opened, as follows:\n# $0=/usr/lib/systemd/system-sleep/sleepyhead, $1=post, $2=suspend\n\nif [ \"$1\" = \"post\" ] ; then\n    logger \"Resuming from sleep to swapoff\"\n    swapoff /swap\nfi\n", "num_lines": 12}
{"repo_name": "amazon-ec2-instance-selector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nROOT_PATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )/../../\"\nEXIT_CODE=0\n\nwhile read pkg_license_tuple; do\n    pkg=$(echo $pkg_license_tuple | tr -s \" \" | cut -d\" \" -f1)\n    license=$(echo $pkg_license_tuple | tr -s \" \" | cut -d\" \" -f2-)\n    if [[ \"$(grep -c ${pkg} ${ROOT_PATH}/THIRD_PARTY_LICENSES)\" -ge 1 ]]; then\n        echo \"\u00e2\u0153\u2026 FOUND ${pkg} (${license})\"\n    else\n        echo \"\u00f0\u0178\u201d\u00b4 MISSING for ${pkg} (${license})\"\n        EXIT_CODE=1\n    fi\ndone < \"${1:-/dev/stdin}\"\n\necho \"=================================================\"\nif [[ \"${EXIT_CODE}\" -eq 0 ]]; then\n    echo \"\u00e2\u0153\u2026 TEST PASSED\"\nelse\n    echo \"\u00f0\u0178\u201d\u00b4 TEST FAILED\"\nfi\n\nexit $EXIT_CODE\n", "num_lines": 26}
{"repo_name": "amazon-ec2-instance-selector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\nBUILD_DIR=\"$SCRIPTPATH/../../build\"\nmkdir -p $BUILD_DIR\nGOBIN=$(go env GOPATH | sed 's+:+/bin+g')/bin\nexport PATH=\"$PATH:$GOBIN\"\n\ngo install github.com/mitchellh/golicense@v0.2.0\ngo build -o $BUILD_DIR/aeis $SCRIPTPATH/../../.\ngolicense -out-xlsx=$BUILD_DIR/report.xlsx $SCRIPTPATH/license-config.hcl $BUILD_DIR/aeis\n\n", "num_lines": 14}
{"repo_name": "amazon-ec2-instance-selector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\nBUILD_PATH=\"$SCRIPTPATH/../../build\"\nBUILD_BIN=\"$BUILD_PATH/bin\"\n\nBINARY_NAME=\"ec2-instance-selector-linux-amd64\"\nLICENSE_TEST_TAG=\"aeis-license-test\"\nLICENSE_REPORT_FILE=\"$BUILD_PATH/license-report\"\nGOPROXY=\"direct|https://proxy.golang.org\"\n\nSUPPORTED_PLATFORMS_LINUX=\"linux/amd64\" make -s -f $SCRIPTPATH/../../Makefile build-binaries\ndocker buildx build --load --build-arg=GOPROXY=${GOPROXY} -t $LICENSE_TEST_TAG $SCRIPTPATH/\ndocker run -i -e GITHUB_TOKEN --rm -v $SCRIPTPATH/:/test -v $BUILD_BIN/:/aeis-bin $LICENSE_TEST_TAG golicense /test/license-config.hcl /aeis-bin/$BINARY_NAME | tee $LICENSE_REPORT_FILE\n$SCRIPTPATH/check-licenses.sh $LICENSE_REPORT_FILE\n", "num_lines": 17}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Test the current package under a different kernel.\n# Requires virtme and qemu to be installed.\n# Examples:\n#     Run all tests on a 5.4 kernel\n#     $ ./run-tests.sh 5.4\n#     Run a subset of tests:\n#     $ ./run-tests.sh 5.4 go test ./link\n\nset -euo pipefail\n\nscript=\"$(realpath \"$0\")\"\nreadonly script\n\n# This script is a bit like a Matryoshka doll since it keeps re-executing itself\n# in various different contexts:\n#\n#   1. invoked by the user like run-tests.sh 5.4\n#   2. invoked by go test like run-tests.sh --exec-vm\n#   3. invoked by init in the vm like run-tests.sh --exec-test\n#\n# This allows us to use all available CPU on the host machine to compile our\n# code, and then only use the VM to execute the test. This is because the VM\n# is usually slower at compiling than the host.\nif [[ \"${1:-}\" = \"--exec-vm\" ]]; then\n  shift\n\n  input=\"$1\"\n  shift\n\n  # Use sudo if /dev/kvm isn't accessible by the current user.\n  sudo=\"\"\n  if [[ ! -r /dev/kvm || ! -w /dev/kvm ]]; then\n    sudo=\"sudo\"\n  fi\n  readonly sudo\n\n  testdir=\"$(dirname \"$1\")\"\n  output=\"$(mktemp -d)\"\n  printf -v cmd \"%q \" \"$@\"\n\n  if [[ \"$(stat -c '%t:%T' -L /proc/$$/fd/0)\" == \"1:3\" ]]; then\n    # stdin is /dev/null, which doesn't play well with qemu. Use a fifo as a\n    # blocking substitute.\n    mkfifo \"${output}/fake-stdin\"\n    # Open for reading and writing to avoid blocking.\n    exec 0<> \"${output}/fake-stdin\"\n    rm \"${output}/fake-stdin\"\n  fi\n\n  $sudo virtme-run --kimg \"${input}/bzImage\" --memory 768M --pwd \\\n  --rwdir=\"${testdir}=${testdir}\" \\\n  --rodir=/run/input=\"${input}\" \\\n  --rwdir=/run/output=\"${output}\" \\\n  --script-sh \"PATH=\\\"$PATH\\\" \\\"$script\\\" --exec-test $cmd\" \\\n  --qemu-opts -smp 2 # need at least two CPUs for some tests\n\n  if [[ ! -e \"${output}/success\" ]]; then\n    exit 1\n  fi\n\n  $sudo rm -r \"$output\"\n  exit 0\nelif [[ \"${1:-}\" = \"--exec-test\" ]]; then\n  shift\n\n  mount -t bpf bpf /sys/fs/bpf\n  mount -t tracefs tracefs /sys/kernel/debug/tracing\n\n  if [[ -d \"/run/input/bpf\" ]]; then\n    export KERNEL_SELFTESTS=\"/run/input/bpf\"\n  fi\n\n  dmesg -C\n  if ! \"$@\"; then\n    dmesg\n    exit 1\n  fi\n  touch \"/run/output/success\"\n  exit 0\nfi\n\nreadonly kernel_version=\"${1:-}\"\nif [[ -z \"${kernel_version}\" ]]; then\n  echo \"Expecting kernel version as first argument\"\n  exit 1\nfi\nshift\n\nreadonly kernel=\"linux-${kernel_version}.bz\"\nreadonly selftests=\"linux-${kernel_version}-selftests-bpf.bz\"\nreadonly input=\"$(mktemp -d)\"\nreadonly tmp_dir=\"${TMPDIR:-/tmp}\"\nreadonly branch=\"${BRANCH:-master}\"\n\nfetch() {\n    echo Fetching \"${1}\"\n    wget -nv -N -P \"${tmp_dir}\" \"https://github.com/cilium/ci-kernels/raw/${branch}/${1}\"\n}\n\nfetch \"${kernel}\"\ncp \"${tmp_dir}/${kernel}\" \"${input}/bzImage\"\n\nif fetch \"${selftests}\"; then\n  mkdir \"${input}/bpf\"\n  tar --strip-components=4 -xjf \"${tmp_dir}/${selftests}\" -C \"${input}/bpf\"\nelse\n  echo \"No selftests found, disabling\"\nfi\n\nargs=(-v -short -coverpkg=./... -coverprofile=coverage.out -count 1 ./...)\nif (( $# > 0 )); then\n  args=(\"$@\")\nfi\n\nexport GOFLAGS=-mod=readonly\nexport CGO_ENABLED=0\n\necho Testing on \"${kernel_version}\"\ngo test -exec \"$script --exec-vm $input\" \"${args[@]}\"\necho \"Test successful on ${kernel_version}\"\n\nrm -r \"${input}\"\n", "num_lines": 124}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu -o pipefail\n\nWORKDIR=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$WORKDIR\"\n}\ntrap finish EXIT\n\nexport GOBIN=${WORKDIR}/bin\nexport PATH=${GOBIN}:${PATH}\nmkdir -p ${GOBIN}\n\necho \"remove existing generated files\"\n# grpc_testing_not_regenerate/*.pb.go is not re-generated,\n# see grpc_testing_not_regenerate/README.md for details.\nrm -f $(find . -name '*.pb.go' | grep -v 'grpc_testing_not_regenerate')\n\necho \"go install google.golang.org/protobuf/cmd/protoc-gen-go\"\n(cd test/tools && go install google.golang.org/protobuf/cmd/protoc-gen-go)\n\necho \"go install cmd/protoc-gen-go-grpc\"\n(cd cmd/protoc-gen-go-grpc && go install .)\n\necho \"git clone https://github.com/grpc/grpc-proto\"\ngit clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto\n\necho \"git clone https://github.com/protocolbuffers/protobuf\"\ngit clone --quiet https://github.com/protocolbuffers/protobuf ${WORKDIR}/protobuf\n\n# Pull in code.proto as a proto dependency\nmkdir -p ${WORKDIR}/googleapis/google/rpc\necho \"curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto\"\ncurl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto\n\nmkdir -p ${WORKDIR}/out\n\n# Generates sources without the embed requirement\nLEGACY_SOURCES=(\n  ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto\n  ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto\n  ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto\n  ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto\n  profiling/proto/service.proto\n  ${WORKDIR}/grpc-proto/grpc/reflection/v1alpha/reflection.proto\n  ${WORKDIR}/grpc-proto/grpc/reflection/v1/reflection.proto\n)\n\n# Generates only the new gRPC Service symbols\nSOURCES=(\n  $(git ls-files --exclude-standard --cached --others \"*.proto\" | grep -v '^\\(profiling/proto/service.proto\\|reflection/grpc_reflection_v1alpha/reflection.proto\\)$')\n  ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto\n  ${WORKDIR}/grpc-proto/grpc/testing/*.proto\n  ${WORKDIR}/grpc-proto/grpc/core/*.proto\n)\n\n# These options of the form 'Mfoo.proto=bar' instruct the codegen to use an\n# import path of 'bar' in the generated code when 'foo.proto' is imported in\n# one of the sources.\n#\n# Note that the protos listed here are all for testing purposes. All protos to\n# be used externally should have a go_package option (and they don't need to be\n# listed here).\nOPTS=Mgrpc/core/stats.proto=google.golang.org/grpc/interop/grpc_testing/core,\\\nMgrpc/testing/benchmark_service.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/stats.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/report_qps_scenario_service.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/messages.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/worker_service.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/control.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/test.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/payloads.proto=google.golang.org/grpc/interop/grpc_testing,\\\nMgrpc/testing/empty.proto=google.golang.org/grpc/interop/grpc_testing\n\nfor src in ${SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    ${src}\ndone\n\nfor src in ${LEGACY_SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},require_unimplemented_servers=false:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    ${src}\ndone\n\n# The go_package option in grpc/lookup/v1/rls.proto doesn't match the\n# current location. Move it into the right place.\nmkdir -p ${WORKDIR}/out/google.golang.org/grpc/internal/proto/grpc_lookup_v1\nmv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/internal/proto/grpc_lookup_v1\n\n# grpc_testing_not_regenerate/*.pb.go are not re-generated,\n# see grpc_testing_not_regenerate/README.md for details.\nrm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testing_not_regenerate/*.pb.go\n\ncp -R ${WORKDIR}/out/google.golang.org/grpc/* .\n", "num_lines": 124}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\n# not makes sure the command passed to it does not exit with a return code of 0.\nnot() {\n  # This is required instead of the earlier (! $COMMAND) because subshells and\n  # pipefail don't work the same on Darwin as in Linux.\n  ! \"$@\"\n}\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | not read\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${HOME}/go/bin:${GOROOT}/bin:${PATH}\"\ngo version\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Install the pinned versions as defined in module tools.\n  pushd ./test/tools\n  go install \\\n    golang.org/x/lint/golint \\\n    golang.org/x/tools/cmd/goimports \\\n    honnef.co/go/tools/cmd/staticcheck \\\n    github.com/client9/misspell/cmd/misspell\n  popd\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif [[ \"${GITHUB_ACTIONS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/runner/go\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif not which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\n# (Done in two parts because Darwin \"git grep\" has broken support for compound\n# exclusion matches.)\n(grep -L \"DO NOT EDIT\" $(git grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\" -- '*.go') || true) | fail_on_output\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\nnot grep 'func Test[^(]' *_test.go\nnot grep 'func Test[^(]' test/*.go\n\n# - Do not import x/net/context.\nnot git grep -l 'x/net/context' -- \"*.go\"\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit grep -l '\"math/rand\"' -- \"*.go\" 2>&1 | not grep -v '^examples\\|^stress\\|grpcrand\\|^benchmark\\|wrr_test'\n\n# - Do not call grpclog directly. Use grpclog.Component instead.\ngit grep -l -e 'grpclog.I' --or -e 'grpclog.W' --or -e 'grpclog.E' --or -e 'grpclog.F' --or -e 'grpclog.V' -- \"*.go\" | not grep -v '^grpclog/component.go\\|^internal/grpctest/tlogger_test.go'\n\n# - Ensure all ptypes proto packages are renamed when importing.\nnot git grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\" -- \"*.go\"\n\n# - Ensure all xds proto imports are renamed to *pb or *grpc.\ngit grep '\"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*.pb.go' | not grep -v 'pb \"\\|grpc \"'\n\nmisspell -error .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet,\n# go mod tidy.\n# Perform these checks on each module inside gRPC.\nfor MOD_FILE in $(find . -name 'go.mod'); do\n  MOD_DIR=$(dirname ${MOD_FILE})\n  pushd ${MOD_DIR}\n  go vet -all ./... | fail_on_output\n  gofmt -s -d -l . 2>&1 | fail_on_output\n  goimports -l . 2>&1 | not grep -vE \"\\.pb\\.go\"\n  golint ./... 2>&1 | not grep -vE \"/grpc_testing_not_regenerate/.*\\.pb\\.go:\"\n\n  go mod tidy\n  git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\n  popd\ndone\n\n# - Collection of static analysis checks\n#\n# TODO(dfawley): don't use deprecated functions in examples or first-party\n# plugins.\n# TODO(dfawley): enable ST1019 (duplicate imports) but allow for protobufs.\nSC_OUT=\"$(mktemp)\"\nstaticcheck -go 1.19 -checks 'inherit,-ST1015,-ST1019,-SA1019' ./... > \"${SC_OUT}\" || true\n# Error if anything other than deprecation warnings are printed.\nnot grep -v \"is deprecated:.*SA1019\" \"${SC_OUT}\"\n# Only ignore the following deprecated types/fields/functions.\nnot grep -Fv '.CredsBundle\n.HeaderMap\n.Metadata is deprecated: use Attributes\n.NewAddress\n.NewServiceConfig\n.Type is deprecated: use Attributes\nBuildVersion is deprecated\nbalancer.ErrTransientFailure\nbalancer.Picker\nextDesc.Filename is deprecated\ngithub.com/golang/protobuf/jsonpb is deprecated\ngrpc.CallCustomCodec\ngrpc.Code\ngrpc.Compressor\ngrpc.CustomCodec\ngrpc.Decompressor\ngrpc.MaxMsgSize\ngrpc.MethodConfig\ngrpc.NewGZIPCompressor\ngrpc.NewGZIPDecompressor\ngrpc.RPCCompressor\ngrpc.RPCDecompressor\ngrpc.ServiceConfig\ngrpc.WithCompressor\ngrpc.WithDecompressor\ngrpc.WithDialer\ngrpc.WithMaxMsgSize\ngrpc.WithServiceConfig\ngrpc.WithTimeout\nhttp.CloseNotifier\ninfo.SecurityVersion\nproto is deprecated\nproto.InternalMessageInfo is deprecated\nproto.EnumName is deprecated\nproto.ErrInternalBadWireType is deprecated\nproto.FileDescriptor is deprecated\nproto.Marshaler is deprecated\nproto.MessageType is deprecated\nproto.RegisterEnum is deprecated\nproto.RegisterFile is deprecated\nproto.RegisterType is deprecated\nproto.RegisterExtension is deprecated\nproto.RegisteredExtension is deprecated\nproto.RegisteredExtensions is deprecated\nproto.RegisterMapType is deprecated\nproto.Unmarshaler is deprecated\nresolver.Backend\nresolver.GRPCLB\nTarget is deprecated: Use the Target field in the BuildOptions instead.\nxxx_messageInfo_\n' \"${SC_OUT}\"\n\n# - special golint on package comments.\nlint_package_comment_per_package() {\n  # Number of files in this go package.\n  fileCount=$(go list -f '{{len .GoFiles}}' $1)\n  if [ ${fileCount} -eq 0 ]; then\n    return 0\n  fi\n  # Number of package errors generated by golint.\n  lintPackageCommentErrorsCount=$(golint --min_confidence 0 $1 | grep -c \"should have a package comment\")\n  # golint complains about every file that's missing the package comment. If the\n  # number of files for this package is greater than the number of errors, there's\n  # at least one file with package comment, good. Otherwise, fail.\n  if [ ${fileCount} -le ${lintPackageCommentErrorsCount} ]; then\n    echo \"Package $1 (with ${fileCount} files) is missing package comment\"\n    return 1\n  fi\n}\nlint_package_comment() {\n  set +ex\n\n  count=0\n  for i in $(go list ./...); do\n    lint_package_comment_per_package \"$i\"\n    ((count += $?))\n  done\n\n  set -ex\n  return $count\n}\nlint_package_comment\n\necho SUCCESS\n", "num_lines": 214}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\ncat > $(pwd)/logger.go <<EOF\n// Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// GENERATED FILE, DO NOT MODIFY BY HAND\n//go:generate bundle_log_config.sh\n\npackage config\n\n// Logger holds the bundled log configuration for seelog\nfunc Logger() string {\n\treturn \\`\n$(cat ../../seelog.xml)\n\\`\n}\nEOF\n", "num_lines": 42}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nDRYRUN=true\n\nAWS_PROFILE=\"\"\nAWS_REGION=\"us-east-1\"\nAMI_ID=\"ami-053b2a8c2f3e87928\" #amzn2-ami-hvm-2.0.20181020.0-aarch64-gp2\nARTIFACT_BUCKET=\"\"\nSOURCE_BUCKET=\"\"\nKEY_NAME=\"\"\nSECURITY_GROUP=\"\"\nINSTANCE_PROFILE=\"\"\n\nsource $(dirname \"${0}\")/publishing-common.sh\n\nusage() {\n\techo \"Usage: ${0} -a ARTIFACT_BUCKET -t SOURCE_BUCKET -k SSH_KEY -s SECURITY_GROUP -i IAM_ROLE [OPTIONS]\"\n\techo\n\techo \"This script stages a new version of the Amazon EC2 Container Agent\"\n\techo \"built on a freshly-launched EC2 instance.\"\n\techo \"To run this script, you must have the following resources:\"\n\techo \"* A local AWS profile with permissions for \\\"ec2:run-instances\\\",\"\n\techo \"  \\\"ec2:describe-instances\\\", \\\"s3:PutObject\\\", and \\\"s3:ListObjects\\\"\"\n\techo \"* An S3 bucket for the source\"\n\techo \"* An S3 bucket for the artifact destination\"\n\techo \"* An IAM profile with permissions to read from and write to the\"\n\techo \"  source bucket (\\\"s3:GetObject\\\", \\\"s3:PutObject\\\", and \\\"s3:PutObjectAcl\\\") \"\n\techo \"  and write to the destination S3 bucket (\\\"s3:PutObject\\\" and \"\n\techo \"  \\\"s3:PutObjectAcl\\\")\"\n\techo\n\techo \"Options\"\n\techo \"  -d  true|false      Dryrun (default is true)\"\n\techo \"  -p  PROFILE         AWS CLI Profile (default is none)\"\n\techo \"  -a  BUCKET          Artifact (Destination) AWS S3 Bucket\"\n\techo \"  -t  BUCKET          Source AWS S3 Bucket\"\n\techo \"  -k  SSH_KEY         SSH key name\"\n\techo \"  -s  SECURITY_GROUP  Security group name\"\n\techo \"  -i  IAM_ROLE        IAM Role name\"\n\techo \"  -r  Region          Region for EC2 instance launch\"\n\techo \"  -h                  Display this help message\"\n}\n\nwhile getopts \":d:p:a:t:k:s:i:r:h\" opt; do\n\tcase ${opt} in\n\t\td)\n\t\t\tif [[ \"${OPTARG}\" = \"false\" ]]; then\n\t\t\t\tDRYRUN=false\n\t\t\telse\n\t\t\t\tDRYRUN=true\n\t\t\tfi\n\t\t\t;;\n\t\tp)\n\t\t\tAWS_PROFILE=\"${OPTARG}\"\n\t\t\t;;\n\t\ta)\n\t\t\tARTIFACT_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\tt)\n\t\t\tSOURCE_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\tk)\n\t\t\tKEY_NAME=\"${OPTARG}\"\n\t\t\t;;\n\t\ts)\n\t\t\tSECURITY_GROUP=\"${OPTARG}\"\n\t\t\t;;\n\t\ti)\n\t\t\tINSTANCE_PROFILE=\"${OPTARG}\"\n\t\t\t;;\n\t\tr)\n\t\t    AWS_REGION=\"${OPTARG}\"\n\t\t    ;;\n\t\t\\?)\n\t\t\techo \"Invalid option -${OPTARG}\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\t:)\n\t\t\techo \"Option -${OPTARG} requires an argument.\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\th)\n\t\t\tusage\n\t\t\texit 0\n\t\t\t;;\n\tesac\ndone\n\nif [[ -z \"${ARTIFACT_BUCKET}\" ]] \\\n\t|| [[ -z \"${KEY_NAME}\" ]] \\\n\t|| [[ -z \"${INSTANCE_PROFILE}\" ]] \\\n\t|| [[ -z \"${SOURCE_BUCKET}\" ]]; then\n\tusage\n\texit 1\nfi\n\n\ncommit=$(git rev-parse HEAD)\nclone_url=$(git config --get remote.origin.url)\necho \"Packaging ${commit} for staging...\"\necho \"Clone url ${clone_url}\"\nagent_dir=$(pwd)\ns3_source_prefix=\"s3://${SOURCE_BUCKET}/$(hostname)-${RANDOM}\"\n\nec2_work_root=\"/var/lib/ec2-stage\"\nec2_gopath=\"${ec2_work_root}/go\"\nec2_build_root=\"${ec2_gopath}/src/github.com/aws\"\n\nuserdata=$(cat << EOU\n#!/bin/bash\n\nmkdir -p ${ec2_work_root}\nexec > >(tee -a ${ec2_work_root}/userdata.log) 2>&1\n\nyum -y install docker golang git zip unzip aws-cli\n\nsystemctl start docker --now\n\nmkdir -p ${ec2_build_root}\nexport GOPATH=${ec2_gopath}\ncd ${ec2_build_root}\n\necho \"Cloning....\"\ngit clone ${clone_url}\ncd amazon-ecs-agent\ngit checkout ${commit}\n\nmake get-deps\n\nscripts/stage_arm.sh -b ${ARTIFACT_BUCKET} -c ${commit} -d false\naws s3 cp \"${ec2_work_root}/userdata.log\" \"${s3_source_prefix}/userdata.log\"\nshutdown -hP now\nEOU\n)\n\nencoded_user_data=$(base64 <<< \"${userdata}\")\n\nprofile=\"\"\nif [[ -n \"${AWS_PROFILE}\" ]]; then\n\tprofile=\"--profile=${AWS_PROFILE}\"\nfi\n\necho \"Starting an EC2 instance with the following user-data:\"\necho \"======================================================\"\necho \"${userdata}\"\necho \"======================================================\"\necho\n\nec2_instance_id=$(dryval aws ${profile} \"--region=${AWS_REGION}\" \\\n\tec2 run-instances \\\n\t\"--count=1\" \\\n\t\"--image-id=${AMI_ID}\" \\\n\t\"--key-name=${KEY_NAME}\" \\\n\t\"--security-groups=${SECURITY_GROUP}\" \\\n\t\"--instance-type=a1.xlarge\" \\\n\t\"--instance-initiated-shutdown-behavior=terminate\" \\\n\t\"--iam-instance-profile=Name=${INSTANCE_PROFILE}\" \\\n\t\"--query=Instances[0].InstanceId\" \\\n\t\"--output=text\" \\\n\t\"--user-data=${userdata}\" )\n\nif ${DRYRUN} ; then\n\tec2_instance_id=\"dryrun-ec2-instance-id\"\nfi\n\necho \"Waiting for ${ec2_instance_id} to start...\"\ndryval aws ${profile} \"--region=${AWS_REGION}\" \\\n\t\"ec2\" \"wait\" \"instance-running\" \"--instance-ids=${ec2_instance_id}\"\n\necho \"Waiting for ${ec2_instance_id} to terminate...\"\ndryval aws ${profile} \"--region=${AWS_REGION}\" \\\n\t\"ec2\" \"wait\" \"instance-terminated\" \"--instance-ids=${ec2_instance_id}\"\n", "num_lines": 189}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e # exit on failure\n\nfail() {\n    echo \"\"\n    echo -e \"\\033[0;31mInstallation Failed\\033[0m\" # print it in red\n    exit 1\n}\n\ncheck-option-value() {\n    if [ \"${2:0:2}\" == \"--\" ]; then\n        echo \"Option $1 was passed an invalid value: $2. Perhaps you passed in an empty env var?\"\n        fail\n    fi\n}\n\nusage() {\n    echo \"$(basename \"$0\") [--help] --region REGION --activation-code CODE --activation-id ID [--cluster CLUSTER] [--enable-gpu] [--docker-install-source all|docker|distro|none] [--ecs-version VERSION] [--ecs-endpoint ENDPOINT] [--skip-registration] [--no-start]\n\n  --help\n        (optional) display this help message.\n  --region string\n        (required) this must match the region of your ECS cluster and SSM activation.\n  --activation-id string\n        (required) activation id from the create activation command. Not required if --skip-registration is specified.\n  --activation-code string\n        (required) activation code from the create activation command. Not required if --skip-registration is specified.\n  --cluster string\n        (optional) pass the cluster name that ECS agent will connect too. By default its value is 'default'.\n  --enable-gpu\n        (optional) if this flag is provided, GPU support for ECS will be enabled.\n  --docker-install-source\n        (optional) Source of docker installation. Possible values are 'all, docker, distro, none'. Defaults to 'all'.\n  --ecs-version string\n        (optional) Version of the ECS agent rpm/deb package to use. If not specified, default to latest.\n  --skip-registration\n        (optional) if this is enabled, SSM agent install and instance registration with SSM is skipped.\n  --certs-file\n        (optional) TLS certs for execute command feature. Defaults to searching for certs in known possible locations.\n  --no-start\n        (optional) if this flag is provided, SSM agent, docker and ECS agent will not be started by the script despite being installed.\"\n}\n\n# required:\nREGION=\"\"\nACTIVATION_CODE=\"\"\nACTIVATION_ID=\"\"\n# optional:\nSKIP_REGISTRATION=false\nECS_CLUSTER=\"\"\nDOCKER_SOURCE=\"\"\nECS_VERSION=\"\"\nDEB_URL=\"\"\nRPM_URL=\"\"\nECS_ENDPOINT=\"\"\nCERTS_FILE=\"\"\n# Whether to check signature for the downloaded amazon-ecs-init package. true unless --skip-gpg-check\n# specified. --skip-gpg-check is mostly for testing purpose (so that we can test a custom build of ecs init package\n# without having to sign it).\nCHECK_SIG=true\nNO_START=false\nwhile :; do\n    case \"$1\" in\n    --help)\n        usage\n        exit 0\n        ;;\n    --region)\n        check-option-value \"$1\" \"$2\"\n        REGION=\"$2\"\n        shift 2\n        ;;\n    --cluster)\n        check-option-value \"$1\" \"$2\"\n        ECS_CLUSTER=\"$2\"\n        shift 2\n        ;;\n    --activation-code)\n        check-option-value \"$1\" \"$2\"\n        ACTIVATION_CODE=\"$2\"\n        shift 2\n        ;;\n    --activation-id)\n        check-option-value \"$1\" \"$2\"\n        ACTIVATION_ID=\"$2\"\n        shift 2\n        ;;\n    --docker-install-source)\n        check-option-value \"$1\" \"$2\"\n        DOCKER_SOURCE=\"$2\"\n        shift 2\n        ;;\n    --ecs-version)\n        check-option-value \"$1\" \"$2\"\n        ECS_VERSION=\"$2\"\n        shift 2\n        ;;\n    --deb-url)\n        check-option-value \"$1\" \"$2\"\n        DEB_URL=\"$2\"\n        shift 2\n        ;;\n    --rpm-url)\n        check-option-value \"$1\" \"$2\"\n        RPM_URL=\"$2\"\n        shift 2\n        ;;\n    --ecs-endpoint)\n        check-option-value \"$1\" \"$2\"\n        ECS_ENDPOINT=\"$2\"\n        shift 2\n        ;;\n    --certs-file)\n        check-option-value \"$1\" \"$2\"\n        CERTS_FILE=\"$2\"\n        shift 2\n        ;;\n    --skip-registration)\n        SKIP_REGISTRATION=true\n        shift 1\n        ;;\n    --enable-gpu)\n        GPU_ENABLED=true\n        shift 1\n        ;;\n    --no-start)\n        NO_START=true\n        shift 1\n        ;;\n    --skip-gpg-check)\n        CHECK_SIG=false\n        shift 1\n        ;;\n    *)\n        [ -z \"$1\" ] && break\n        echo \"invalid option: [$1]\"\n        fail\n        ;;\n    esac\ndone\n\n# check if the script is run with root or sudo\nif [ $(id -u) -ne 0 ]; then\n    echo \"Please run as root.\"\n    fail\nfi\n\n# check if system is using systemd\n# from https://www.freedesktop.org/software/systemd/man/sd_booted.html\nif [ ! -d /run/systemd/system ]; then\n    echo \"The install script currently supports only systemd.\"\n    fail\nfi\n\nSSM_SERVICE_NAME=\"amazon-ssm-agent\"\nSSM_BIN_NAME=\"amazon-ssm-agent\"\nif systemctl is-enabled snap.amazon-ssm-agent.amazon-ssm-agent.service &>/dev/null; then\n    echo \"Detected SSM agent installed via snap.\"\n    SSM_SERVICE_NAME=\"snap.amazon-ssm-agent.amazon-ssm-agent.service\"\n    SSM_BIN_NAME=\"/snap/amazon-ssm-agent/current/amazon-ssm-agent\"\nfi\nSSM_MANAGED_INSTANCE_ID=\"\"\n\nif [ -z \"$REGION\" ]; then\n    echo \"--region is required\"\n    fail\nfi\n# If activation code is absent and skip activation flag is present, set flag to skip ssm registration\n# if both activation code is present\nif $SKIP_REGISTRATION; then\n    echo \"Skipping ssm registration.\"\n    if ! systemctl is-enabled $SSM_SERVICE_NAME &>/dev/null; then\n        echo \"--skip-registration flag specified but the SSM agent service is not running.\"\n        echo \"a running SSM agent service is required for ECS Anywhere.\"\n        fail\n    fi\nelse\n    if [[ -z $ACTIVATION_ID || -z $ACTIVATION_CODE ]]; then\n        echo \"Both --activation-id and --activation-code are required unless --skip-registration is specified.\"\n        fail\n    fi\nfi\nif [ -z \"$ECS_CLUSTER\" ]; then\n    ECS_CLUSTER=\"default\"\nfi\nif [ -z \"$DOCKER_SOURCE\" ]; then\n    DOCKER_SOURCE=\"all\"\nfi\nif [ -z \"$ECS_VERSION\" ]; then\n    ECS_VERSION=\"latest\"\nfi\n\nARCH=$(uname -m)\nif [ \"$ARCH\" == \"x86_64\" ]; then\n    ARCH_ALT=\"amd64\"\nelif [ \"$ARCH\" == \"aarch64\" ]; then\n    ARCH_ALT=\"arm64\"\nelse\n    echo \"Unsupported architecture: $ARCH\"\n    fail\nfi\n\nS3_BUCKET=\"amazon-ecs-agent-$REGION\"\nRPM_PKG_NAME=\"amazon-ecs-init-$ECS_VERSION.$ARCH.rpm\"\nDEB_PKG_NAME=\"amazon-ecs-init-$ECS_VERSION.$ARCH_ALT.deb\"\nS3_URL_SUFFIX=\"\"\nif grep -q \"^cn-\" <<< \"$REGION\"; then\n    S3_URL_SUFFIX=\".cn\"\nfi\nS3_URL=\"https://s3.${REGION}.amazonaws.com${S3_URL_SUFFIX}\"\nSSM_S3_BUCKET=\"amazon-ssm-$REGION\"\n\nif [ -z \"$RPM_URL\" ]; then\n    RPM_URL=\"${S3_URL}/${S3_BUCKET}/$RPM_PKG_NAME\"\nfi\nif [ -z \"$DEB_URL\" ]; then\n    DEB_URL=\"${S3_URL}/${S3_BUCKET}/$DEB_PKG_NAME\"\nfi\n\n# source /etc/os-release to get the VERSION_ID and ID fields\nsource /etc/os-release\necho \"Running ECS install script on $ID $VERSION_ID\"\necho \"###\"\necho \"\"\nDISTRO=\"\"\nif echo \"$ID\" | grep ubuntu; then\n    DISTRO=\"ubuntu\"\nelif echo \"$ID\" | grep debian; then\n    DISTRO=\"debian\"\nelif echo \"$ID\" | grep fedora; then\n    DISTRO=\"fedora\"\nelif echo \"$ID\" | grep centos; then\n    DISTRO=\"centos\"\nelif echo \"$ID\" | grep rhel; then\n    DISTRO=\"rhel\"\nelif [[ \"$ID\" == \"amzn\" && \"$VERSION_ID\" == \"2\" ]]; then\n    DISTRO=\"al2\"\nfi\n\nif [ \"$DISTRO\" == \"rhel\" ]; then\n    if [ ! \"$DOCKER_SOURCE\" == \"none\" ]; then\n        echo \"Docker install is not supported on RHEL. Please install yourself and rerun with --docker-install-source none\"\n        fail\n    fi\nfi\n\nok() {\n    echo \"\"\n    echo \"# ok\"\n    echo \"##########################\"\n    echo \"\"\n}\n\ntry() {\n    local action=$*\n    echo \"\"\n    echo \"##########################\"\n    echo \"# Trying to $action ... \"\n    echo \"\"\n}\n\nPKG_MANAGER=\"\"\nif [ -x \"$(command -v dnf)\" ]; then\n    PKG_MANAGER=\"dnf\"\n    dnf install -y jq\nelif [ -x \"$(command -v yum)\" ]; then\n    PKG_MANAGER=\"yum\"\n    if [ \"$DISTRO\" != \"al2\" ]; then\n        yum install epel-release -y\n    fi\n    yum install -y jq\nelif [ -x \"$(command -v apt)\" ]; then\n    PKG_MANAGER=\"apt\"\n    try \"Update apt repos\"\n    apt update -y\n    apt-get install -y curl jq\n    ok\nelif [ -x \"$(command -v zypper)\" ]; then\n    PKG_MANAGER=\"zypper\"\n    zypper install -y jq\nelse\n    echo \"Unsupported package manager. Could not find dnf, yum, or apt.\"\n    fail\nfi\n\nget-ssm-managed-instance-id() {\n    SSM_REGISTRATION_FILE='/var/lib/amazon/ssm/Vault/Store/RegistrationKey'\n    if [ -f ${SSM_REGISTRATION_FILE} ]; then\n        SSM_MANAGED_INSTANCE_ID=$(jq -r \".instanceID\" $SSM_REGISTRATION_FILE)\n    fi\n}\n\ncurl-helper() {\n    if ! curl -o \"$1\" \"$2\" -fSs; then\n        echo \"Failed to download $2\"\n        fail\n    fi\n}\n\nregister-ssm-agent() {\n    try \"Register SSM agent\"\n    get-ssm-managed-instance-id\n    if [ -z \"$SSM_MANAGED_INSTANCE_ID\" ]; then\n        systemctl stop \"$SSM_SERVICE_NAME\" &>/dev/null\n        $SSM_BIN_NAME -register -code \"$ACTIVATION_CODE\" -id \"$ACTIVATION_ID\" -region \"$REGION\"\n        systemctl enable \"$SSM_SERVICE_NAME\"\n        if ! $NO_START; then\n            systemctl start \"$SSM_SERVICE_NAME\"\n        else\n            echo \"Skip starting ssm agent because --no-start is specified.\"\n        fi\n        echo \"SSM agent has been registered.\"\n    else\n        echo \"SSM agent is already registered. Managed instance ID: $SSM_MANAGED_INSTANCE_ID\"\n    fi\n    ok\n}\n\ninstall-ssm-agent() {\n    try \"install ssm agent\"\n    if systemctl is-enabled $SSM_SERVICE_NAME &>/dev/null; then\n        echo \"SSM agent is already installed.\"\n    else\n        local dir\n        dir=\"$(mktemp -d)\"\n        local SSM_DEB_URL=\"${S3_URL}/${SSM_S3_BUCKET}/latest/debian_$ARCH_ALT/amazon-ssm-agent.deb\"\n        local SSM_RPM_URL=\"${S3_URL}/${SSM_S3_BUCKET}/latest/linux_$ARCH_ALT/amazon-ssm-agent.rpm\"\n        local SSM_DEB_PKG_NAME=\"ssm-agent.deb\"\n        local SSM_RPM_PKG_NAME=\"ssm-agent.rpm\"\n\n        case \"$PKG_MANAGER\" in\n        apt)\n            curl-helper \"$dir/$SSM_DEB_PKG_NAME\" \"$SSM_DEB_URL\"\n            curl-helper \"$dir/$SSM_DEB_PKG_NAME.sig\" \"$SSM_DEB_URL.sig\"\n            ssm-agent-signature-verify \"$dir/$SSM_DEB_PKG_NAME.sig\" \"$dir/$SSM_DEB_PKG_NAME\"\n            chmod -R a+rX \"$dir\"\n            dpkg -i \"$dir/ssm-agent.deb\"\n            ;;\n        dnf | yum | zypper)\n            curl-helper \"$dir/$SSM_RPM_PKG_NAME\" \"$SSM_RPM_URL\"\n            curl-helper \"$dir/$SSM_RPM_PKG_NAME.sig\" \"$SSM_RPM_URL.sig\"\n            ssm-agent-signature-verify \"$dir/$SSM_RPM_PKG_NAME.sig\" \"$dir/$SSM_RPM_PKG_NAME\"\n            local args=\"\"\n            local install_args=\"-y\"\n            if [[ \"$PKG_MANAGER\" == \"zypper\" ]]; then\n                install_args=\"${install_args} --allow-unsigned-rpm\"\n                args=\"--no-gpg-checks\"\n            fi\n            $PKG_MANAGER ${args} install ${install_args} \"$dir/$SSM_RPM_PKG_NAME\"\n            ;;\n        esac\n        rm -rf \"$dir\"\n    fi\n    # register the instance\n    register-ssm-agent\n    ok\n}\n\nssm-agent-signature-verify() {\n    try \"verify the signature of amazon-ssm-agent package\"\n    if ! command -v gpg; then\n        echo \"WARNING: gpg command not available on this server, not able to verify amazon-ssm-agent package signature.\"\n        ok\n        return\n    fi\n\n    curl-helper \"$dir/amazon-ssm-agent.gpg\" \"https://raw.githubusercontent.com/aws/amazon-ecs-init/master/scripts/amazon-ssm-agent.gpg\"\n    gpg --import \"$dir/amazon-ssm-agent.gpg\"\n\n    if gpg --verify \"$1\" \"$2\"; then\n        echo \"amazon-ssm-agent GPG verification passed. Install the amazon-ssm-agent.\"\n    else\n        echo \"amazon-ssm-agent GPG verification failed. Stop the installation of the amazon-ssm-agent. Please contact AWS Support.\"\n        fail\n    fi\n\n    ok\n}\n\n# order of operations:\n# all->docker->distro->none\ninstall-docker() {\n    if [ -x \"$(command -v docker)\" ]; then\n        echo \"docker is already installed, skipping installation\"\n        return\n    fi\n\n    case \"$1\" in\n    all)\n        install-docker \"docker\"\n        return\n        ;;\n    docker)\n        try \"install docker from docker repos\"\n        case \"$DISTRO\" in\n        centos)\n            # TODO use dnf on centos if available\n            yum install -y yum-utils\n            yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo\n            yum install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        fedora)\n            dnf install -y dnf-plugins-core\n            dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo\n            dnf install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        debian)\n            apt install -y apt-transport-https ca-certificates gnupg-agent software-properties-common\n            curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -\n            add-apt-repository \\\n                \"deb [arch=$ARCH_ALT] https://download.docker.com/linux/debian \\\n              $(lsb_release -cs) \\\n              stable\"\n            apt update -y\n            apt install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        ubuntu)\n            apt install -y apt-transport-https ca-certificates gnupg-agent software-properties-common\n            curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n            add-apt-repository \\\n                \"deb [arch=$ARCH_ALT] https://download.docker.com/linux/ubuntu \\\n              $(lsb_release -cs) \\\n              stable\"\n            apt update -y\n            apt install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        *)\n            echo \"Docker install repos not supported for this distro, trying distro install\"\n            install-docker \"distro\"\n            return\n            ;;\n        esac\n        ;;\n    distro)\n        try \"install docker from distribution repos\"\n\n        # centos and fedora enable selinux by default in their distro installs\n        case \"$DISTRO\" in\n        centos | fedora)\n            if [ \"$VERSION_ID\" == \"8\" ]; then\n                echo \"--docker-install-source distro is not supported on centos 8 because docker package is not available.\"\n            else\n                echo \"--docker-install-source distro is not supported on $DISTRO $VERSION_ID because distro enables selinux by default.\"\n            fi\n            echo \"We suggest installing using '--docker-install-source docker' or installing docker yourself before running this script.\"\n            fail\n            ;;\n        esac\n\n        case \"$PKG_MANAGER\" in\n        dnf)\n            dnf install -y docker\n            ;;\n        yum)\n            yum install -y docker\n            ;;\n        apt)\n            apt install -y docker.io\n            ;;\n        zypper)\n            zypper install -y docker\n            ;;\n        esac\n        ;;\n    none)\n        echo \"Docker install source is none, not installing docker\"\n        ;;\n    esac\n\n    ok\n}\n\ninstall-ecs-agent() {\n    try \"install ecs agent\"\n    if [ -x \"/usr/libexec/amazon-ecs-init\" ]; then\n        echo \"ecs agent is already installed\"\n        ok\n        return\n    fi\n\n    local dir\n    dir=\"$(mktemp -d)\"\n    case \"$PKG_MANAGER\" in\n    apt)\n        curl-helper \"$dir/$DEB_PKG_NAME\" \"$DEB_URL\"\n        if $CHECK_SIG; then\n            curl-helper \"$dir/$DEB_PKG_NAME.asc\" \"$DEB_URL.asc\"\n            ecs-init-signature-verify \"$dir/$DEB_PKG_NAME.asc\" \"$dir/$DEB_PKG_NAME\"\n        fi\n        chmod -R a+rX \"$dir\"\n        apt install -y \"$dir/$DEB_PKG_NAME\"\n        rm -rf \"$dir\"\n        ;;\n    dnf | yum | zypper)\n        curl-helper \"$dir/$RPM_PKG_NAME\" \"$RPM_URL\"\n        if $CHECK_SIG; then\n            curl-helper \"$dir/$RPM_PKG_NAME.asc\" \"$RPM_URL.asc\"\n            ecs-init-signature-verify \"$dir/$RPM_PKG_NAME.asc\" \"$dir/$RPM_PKG_NAME\"\n        fi\n        local args=\"-y\"\n        if [[ \"$PKG_MANAGER\" == \"zypper\" ]]; then\n            args=\"${args} --allow-unsigned-rpm\"\n        fi\n        $PKG_MANAGER install ${args} \"$dir/$RPM_PKG_NAME\"\n        rm -rf \"$dir\"\n        ;;\n    esac\n\n    if [ ! -f \"/etc/ecs/ecs.config\" ]; then\n        touch /etc/ecs/ecs.config\n    else\n        echo \"/etc/ecs/ecs.config already exists, preserving existing config and appending cluster name.\"\n    fi\n    echo \"ECS_CLUSTER=$ECS_CLUSTER\" >>/etc/ecs/ecs.config\n\n    if [ ! -f \"/var/lib/ecs/ecs.config\" ]; then\n        touch /var/lib/ecs/ecs.config\n    else\n        echo \"/var/lib/ecs/ecs.config already exists, preserving existing config and appending ECS anywhere requirements.\"\n    fi\n    echo \"AWS_DEFAULT_REGION=$REGION\" >>/var/lib/ecs/ecs.config\n    echo \"ECS_EXTERNAL=true\" >>/var/lib/ecs/ecs.config\n    if [ -n \"$ECS_ENDPOINT\" ]; then\n        echo \"ECS_BACKEND_HOST=$ECS_ENDPOINT\" >>/var/lib/ecs/ecs.config\n    fi\n    if [ -n \"$GPU_ENABLED\" ]; then\n        if ! nvidia-smi &>/dev/null; then\n            echo \"Failed to detect GPU with nvidia-smi command. Make sure that GPUs are attached and the latest NVIDIA driver is installed and running.\"\n            fail\n        fi\n        echo \"ECS_ENABLE_GPU_SUPPORT=true\" >>/var/lib/ecs/ecs.config\n    fi\n    systemctl enable ecs\n    if ! $NO_START; then\n        systemctl start ecs\n    else\n        echo \"Skip starting ecs agent because --no-start is specified.\"\n    fi\n\n    ok\n}\n\necs-init-signature-verify() {\n    try \"verify the signature of amazon-ecs-init package\"\n    if ! command -v gpg; then\n        echo \"WARNING: gpg command not available on this server, not able to verify amazon-ecs-init package signature.\"\n        ok\n        return\n    fi\n\n    curl-helper \"$dir/amazon-ecs-agent.gpg\" \"https://raw.githubusercontent.com/aws/amazon-ecs-init/master/scripts/amazon-ecs-agent.gpg\"\n    gpg --import \"$dir/amazon-ecs-agent.gpg\"\n    if gpg --verify \"$1\" \"$2\"; then\n        echo \"amazon-ecs-init GPG verification passed. Install amazon-ecs-init.\"\n    else\n        echo \"amazon-ecs-init GPG verification failed. Stop the installation of amazon-ecs-init. Please contact AWS Support.\"\n        fail\n    fi\n\n    ok\n}\n\nwait-agent-start() {\n    if $NO_START; then\n        echo \"--no-start is specified. Not verifying ecs agent startup.\"\n        return\n    fi\n    try \"wait for ECS agent to start\"\n\n    retryLimit=10\n    i=0\n    for ((i = 0 ; i < retryLimit ; i++))\n    do\n        curlResult=\"$(timeout 10 curl -s http://localhost:51678/v1/metadata | jq .ContainerInstanceArn)\"\n        if [ ! \"$curlResult\" == \"null\" ] && [ -n \"$curlResult\" ]; then\n            echo \"Ping ECS Agent registered successfully! Container instance arn: $curlResult\"\n            echo \"\"\n            echo \"You can check your ECS cluster here https://console.aws.amazon.com/ecs/home?region=$REGION#/clusters/$ECS_CLUSTER\"\n            ok\n            return\n        fi\n        sleep 10 # wait for 10s before next retry for agent to start up.\n    done\n\n    # TODO Update to ecs anywhere specific documentation when available.\n    echo \"Timed out waiting for ECS Agent to start. Please check logs at /var/log/ecs/ecs-agent.log and follow troubleshooting documentation at https://docs.aws.amazon.com/AmazonECS/latest/developerguide/troubleshooting.html\"\n    fail\n}\n\nexec-setup() {\n    find-copy-certs-exec\n    download-ssm-binaries-exec\n}\n\nfind-copy-certs-exec() {\n    # Reference for locations: https://golang.org/src/crypto/x509/root_linux.go\n    CERTS_FILES_LOCATIONS=(\"/etc/ssl/certs/ca-certificates.crt\"\n      \"/etc/pki/tls/certs/ca-bundle.crt\"\n      \"/etc/ssl/ca-bundle.pem\"\n      \"/etc/pki/tls/cacert.pem\"\n      \"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem\"\n      \"/etc/ssl/cert.pem\"\n    )\n    CERTS_PATH=\"/var/lib/ecs/deps/execute-command/certs\"\n\n    echo \"Copying certs for exec feature\"\n\n    # Determine certs file\n    certs=\"\"\n    if [ -n \"$CERTS_FILE\" ] && [ -f \"$CERTS_FILE\" ]; then\n        certs=$CERTS_FILE\n    else\n        if [ -n \"$CERTS_FILE\" ]; then\n            echo \"Provided certs file does not exist, looking for certs in known possible locations\"\n        fi\n        for f in \"${CERTS_FILES_LOCATIONS[@]}\"\n        do\n            if  [ -f \"$f\" ]; then\n                certs=$f\n                break\n            fi\n        done\n    fi\n\n    # Copy certs to exec directory\n    if [ -z \"$certs\" ]; then\n        echo \"Could not find certificates. Please rerun with --certs-file and provide a valid path\"\n        fail\n    else\n        echo \"Using $certs\"\n        openssl verify -x509_strict \"$certs\"\n        mkdir -p $CERTS_PATH\n        cp \"$certs\" $CERTS_PATH/tls-ca-bundle.pem\n        chmod 400 $CERTS_PATH/tls-ca-bundle.pem\n    fi\n    ok\n}\n\ndownload-ssm-binaries-exec() {\n    BINARY_VERSION=\"3.1.804.0\"\n    BINARY_PATH=\"/var/lib/ecs/deps/execute-command/bin/${BINARY_VERSION}\"\n    BINARY_DOWNLOAD_PATH=\"ssm-binaries\"\n\n    # Download SSM binaries from S3\n    echo \"Downloading SSM binaries for exec feature\"\n\n    mkdir -p $BINARY_DOWNLOAD_PATH\n    curl \"${S3_URL}/${SSM_S3_BUCKET}/${BINARY_VERSION}/linux_$ARCH_ALT/amazon-ssm-agent-binaries.tar.gz\" -o ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent.tar.gz\n    tar -xvf ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent.tar.gz -C ${BINARY_DOWNLOAD_PATH}/\n\n    # Copy binaries to exec directory\n    mkdir -p ${BINARY_PATH}\n    cp ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent ${BINARY_PATH}/amazon-ssm-agent\n    cp ${BINARY_DOWNLOAD_PATH}/ssm-agent-worker ${BINARY_PATH}/ssm-agent-worker\n    cp ${BINARY_DOWNLOAD_PATH}/ssm-session-worker ${BINARY_PATH}/ssm-session-worker\n    rm -rf ${BINARY_DOWNLOAD_PATH}\n    ok\n}\n\nshow-license() {\n    echo \"\"\n    echo \"##########################\"\n    echo \"This script installed three open source packages that all use Apache License 2.0.\"\n    echo \"You can view their license information here:\"\n    echo \"  - ECS Agent https://github.com/aws/amazon-ecs-agent/blob/master/LICENSE\"\n    echo \"  - SSM Agent https://github.com/aws/amazon-ssm-agent/blob/master/LICENSE\"\n    echo \"  - Docker engine https://github.com/moby/moby/blob/master/LICENSE\"\n    echo \"##########################\"\n    echo \"\"\n}\n\nif ! $SKIP_REGISTRATION; then\n    install-ssm-agent\nfi\ninstall-docker \"$DOCKER_SOURCE\"\nexec-setup\ninstall-ecs-agent\nwait-agent-start\nshow-license\n", "num_lines": 680}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -e\nexport TOPWD=\"$(pwd)\"\nexport BUILDDIR=\"$(mktemp -d)\"\nexport SRCPATH=\"${BUILDDIR}/src/github.com/aws/amazon-ecs-agent\"\nexport GOPATH=\"${TOPWD}:${BUILDDIR}\"\nexport GO111MODULE=\"auto\"\n\n# we need to make sure we've got the correct golang version installed\n# if it's already installed the script will set env vars and exit\nsource ./scripts/install-golang.sh\n\nif [ -d \"${TOPWD}/.git\" ]; then\n    version=$(cat \"${TOPWD}/ecs-init/ECSVERSION\")\n    git_hash=$(git rev-parse --short=8 HEAD)\n    git_dirty=false\n\n    if [[ \"$(git status --porcelain)\" != \"\" ]]; then\n\tgit_dirty=true\n    fi\n\n    VERSION_FLAG=\"-X github.com/aws/amazon-ecs-agent/ecs-init/version.Version=${version}\"\n    GIT_HASH_FLAG=\"-X github.com/aws/amazon-ecs-agent/ecs-init/version.GitShortHash=${git_hash}\"\n    GIT_DIRTY_FLAG=\"-X github.com/aws/amazon-ecs-agent/ecs-init/version.GitDirty=${git_dirty}\"\nfi\n\nmkdir -p \"${SRCPATH}\"\nln -s \"${TOPWD}/ecs-init\" \"${SRCPATH}\"\ncd \"${SRCPATH}/ecs-init\"\nif [[ \"$1\" == \"dev\" ]]; then\n\tCGO_ENABLED=1 CGO_LDFLAGS_ALLOW='-Wl,--unresolved-symbols=ignore-in-object-files' go build -tags 'development' -ldflags \"${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t   -o \"${TOPWD}/amazon-ecs-init\"\nelse\n\ttags=\"\"\n\tif [[ \"$1\" != \"\" ]]; then\n\t\ttags=\"-tags '$1'\"\n\tfi\n\tCGO_ENABLED=1 CGO_LDFLAGS_ALLOW='-Wl,--unresolved-symbols=ignore-in-object-files' go build -a ${tags} -x \\\n\t\t   -ldflags \"-s ${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t\t   -o \"${TOPWD}/amazon-ecs-init\"\nfi\nCGO_ENABLED=0 go build -x -ldflags \"-s ${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t-o \"${TOPWD}/amazon-ecs-volume-plugin\" \"./volumes/amazon-ecs-volume-plugin\"\nrm -r \"${BUILDDIR}\"\n", "num_lines": 59}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\narchitecture=\"\"\ncase $(uname -m) in\n    x86_64)\n        architecture=\"amd64\"\n        ;;\n    arm64)\n        architecture=\"arm64\"\n        ;;\n    aarch64)\n        architecture=\"arm64\"\n        ;;\n    *)\n        echo $\"Unknown architecture $0\"\n        exit 1\nesac\n\nif [ \"$architecture\" == \"amd64\" ]; then export GOARCH=amd64; fi\nif [ \"$architecture\" == \"arm64\" ]; then export GOARCH=arm64; fi\n\n# if golang isn't installed then we'll install it\ngo_bin_path=\"none\"\nif which go; then\n    export go_bin_path=$(which go)\nfi\nif [ $go_bin_path == \"/usr/bin/go\" ]; then\n    # rpm installs golang to the go_bin_path\n    echo \"golang exists on /usr/bin/go, using system golang version\"\nelif [ ${go_bin_path:0:10} == \"/usr/local\" ]; then\n    # using existing installed golang; re-export path to be sure it's there\n    export GOROOT=/usr/local/go\n    export PATH=$PATH:$GOROOT/bin\n    echo \"$GOROOT exists. Using installed golang version\"\nelse\n    # install golang defined in GO_VERSION file\n    echo \"$GOROOT doesn't exist, installing $(cat ./GO_VERSION)\"\n    GO_VERSION=$(cat ./GO_VERSION)\n    tmpdir=$(mktemp -d)\n    GOLANG_TAR=\"go${GO_VERSION}.linux-${GOARCH}.tar.gz\"\n    wget -O ${tmpdir}/${GOLANG_TAR} https://storage.googleapis.com/golang/${GOLANG_TAR}\n    # only use sudo if it's available\n    if ! sudo true; then\n        tar -C /usr/local -xzf ${tmpdir}/${GOLANG_TAR}\n    else\n\tsudo tar -C /usr/local -xzf ${tmpdir}/${GOLANG_TAR}\n    fi\n    export GOROOT=/usr/local/go\n    export PATH=$PATH:$GOROOT/bin\n    # confirm installation\n    which go\n    go version\nfi\n", "num_lines": 67}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nif [ -z \"$1\" ] || [ ! -z $(echo \"$1\" | tr -d \"[:digit:]\") ]; then\n\techo \"Must provide numeric argument\"\n\texit 1\nfi\n\nexit_code=\"$1\"\n\ndie() {\n\texit $exit_code\n}\n\nstart_wait() {\n\techo \"Waiting for SIGTERM or SIGINT to exit\"\n\twhile true\n\tdo\n\t\tsleep 1 &\n\t\twait ${!}\n\tdone\n}\n\nSIGINT=2\nSIGTERM=15\ntrap die $SIGINT $SIGTERM\nstart_wait\n", "num_lines": 40}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n# Usage: mockgen.sh target-package-name source-file-name [relative-output-directory-path]\n\npackage=\"$1\"\ninputfile=\"$2\"\noutputfile=\"$(echo ${inputfile} | sed -e 's/\\.go$/_mocks.go/')\"\nrelativeoutputdir=\"$3\"\n\necho \"Generating mocks from ${inputfile} to ${outputfile} in package ${package}\"\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\ntmp_gen=\"$(mktemp)\"\nyear=\"$(date +\"%Y\")\"\nmockgen -source \"$(pwd)/${inputfile}\" -package \"${package}\" | goimports > \"${tmp_gen}\"\ncat  > \"$(pwd)/${relativeoutputdir}/${outputfile}\" << EOF\n// Copyright 2015-${year} Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n//\n// Source: $(basename ${inputfile}) in package ${package}\n$(grep -v \"// Source: .*${inputfile}\" ${tmp_gen})\nEOF\nrm \"${tmp_gen}\"\n", "num_lines": 49}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nDIR=\"$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\"\nexport VERSION=$(cat \"${DIR}/../VERSION\")\n\nexport IMAGE_TAG_LATEST=\"latest\"\nexport IMAGE_TAG_SHA=$(git rev-parse --short=8 HEAD)\n\nexport IMAGE_TAG_VERSION=\"v${VERSION}\"\n\nexport IMAGE_TAG_LATEST_ARM=\"arm64-${IMAGE_TAG_LATEST}\"\nexport IMAGE_TAG_SHA_ARM=\"arm64-${IMAGE_TAG_SHA}\"\nexport IMAGE_TAG_VERSION_ARM=\"arm64-v${VERSION}\"\n\nexport IMAGE_TAG_LATEST_AMD=\"amd64-${IMAGE_TAG_LATEST}\"\nexport IMAGE_TAG_SHA_AMD=\"amd64-${IMAGE_TAG_SHA}\"\nexport IMAGE_TAG_VERSION_AMD=\"amd64-v${VERSION}\"\n\nSUPPORTED_OSES=(\"linux\" \"windows\")\n\nsupported_os() {\n\tlocal os=$1\n\tfor entry in ${SUPPORTED_OSES[@]} ; do\n\t\ttest \"${os}\" == \"${entry}\" && return $(true)\n\tdone\n\treturn $(false)\n}\n\ndryval() {\n\tcase ${DRYRUN} in\n\ttrue)\n\t\techo \"DRYRUN: ${@}\" 1>&2\n\t\t;;\n\tfalse)\n\t\techo \"RUNNING: ${@}\" 1>&2\n\t\t\"${@}\"\n\t\t;;\n\t*)\n\t\techo \"invalid DRYRUN flag\"\n\t\t;;\n\tesac\n}\n\ncheck_md5() {\n\ttest_md5=\"$(md5sum ${1} | sed 's/ .*//')\"\n\texpected_md5=\"$(cat ${2})\"\n\tif [ ! \"${test_md5}\" = \"${expected_md5}\" ]; then\n\t\techo \"Computed md5sum ${test_md5} did not match expected md5sum ${expected_md5}\"\n\t\treturn $(false)\n\tfi\n\n\treturn $(true)\n}\n\n\n\ntag_and_push_docker() {\n\tif [[ -z \"${1}\" ]] || [[ -z \"${2}\" ]]; then\n\t\treturn\n\tfi\n\n\tIMAGE_NAME=${1}\n\tIMAGE_TAG=${2}\n\n\techo \"Tagging as ${IMAGE_NAME}:${IMAGE_TAG}\"\n\tdocker tag amazon/amazon-ecs-agent:latest \"${IMAGE_NAME}:${IMAGE_TAG}\"\n\techo \"Pushing ${IMAGE_NAME}:${IMAGE_TAG}\"\n\tdryval docker push \"${IMAGE_NAME}:${IMAGE_TAG}\"\n}\n\ns3_ls() {\n\tprofile=\"\"\n\tif [[ ! -z \"${AWS_PROFILE}\" ]]; then\n\t\tprofile=\"--profile=${AWS_PROFILE}\"\n\tfi\n\taws ${profile} s3 ls \"${1}\"\n}\n\ns3_rm() {\n\tprofile=\"\"\n\tif [[ ! -z \"${AWS_PROFILE}\" ]]; then\n\t\tprofile=\"--profile=${AWS_PROFILE}\"\n\tfi\n\techo \"Removing ${1}\"\n\taws ${profile} s3 rm \"${1}\"\n}\n\ns3_cp() {\n\tprofile=\"\"\n\tif [[ ! -z \"${AWS_PROFILE}\" ]]; then\n\t\tprofile=\"--profile=${AWS_PROFILE}\"\n\tfi\n\tacl=\"public-read\"\n\tif [[ ! -z \"${S3_ACL_OVERRIDE}\" ]]; then\n\t\tacl=\"${S3_ACL_OVERRIDE}\"\n\tfi\n\techo \"Copying ${1} to ${2}\"\n\taws ${profile} s3 cp \"${1}\" \"${2}\" \"--acl=${acl}\"\n}\n", "num_lines": 113}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nDRYRUN=true\nSKIP_REBUILD=false\n\nS3_BUCKET=\"\"\nS3_ACL_OVERRIDE=\"\"\nCOMMIT_ID=\"\"\n\nsource $(dirname \"${0}\")/publishing-common.sh\nTARGET_OS=linux\n\nusage() {\n\techo \"Usage: ${0} -b BUCKET [OPTIONS]\"\n\techo\n\techo \"This script is responsible for staging new versions of the Amazon ECS Container Agent.\"\n\techo \"1. (Optionally) Push the image to a registry, tagged with :latest, :VERSION, and :SHA\"\n\techo \"2. Push the image (and its md5sum) to S3 with -latest, -VERSION, and -SHA\"\n\techo\n\techo \"Options\"\n\techo \"  -d  true|false  Dryrun (default is true)\"\n\techo \"  -b  BUCKET      AWS S3 Bucket\"\n\techo \"  -a  ACL         AWS S3 Object Canned ACL (default is public-read)\"\n\techo \"  -i  IMAGE       Docker image name\"\n\techo \"  -s              Skip re-build\"\n\techo \"  -h              Display this help message\"\n}\n\nstage_s3() {\n\ttarball=\"$(mktemp)\"\n\ttarball_md5=\"$(mktemp)\"\n\ttarball_manifest=\"$(mktemp)\"\n\n\ttrap \"rm -r \\\"${tarball}\\\" \\\"${tarball_md5}\\\" \\\"${tarball_manifest}\\\"\" RETURN EXIT\n\n\tgenerate_manifest ${IMAGE_TAG_VERSION} > \"${tarball_manifest}\"\n\n\tdocker save \"amazon/amazon-ecs-agent:latest\" > \"${tarball}\"\n\tmd5sum \"${tarball}\" | sed 's/ .*//' > \"${tarball_md5}\"\n\techo \"Saved with md5sum $(cat ${tarball_md5})\"\n\n    mkdir -p out\n\tfor tag in ${IMAGE_TAG_VERSION} ${IMAGE_TAG_SHA} ${IMAGE_TAG_LATEST}; do\n\t\techo \"Publishing as ecs-agent-arm64-${tag}\"\n\t\tcp \"${tarball}\" \"out/ecs-agent-arm64-${tag}.tar\"\n\t\tcp \"${tarball_md5}\" \"out/ecs-agent-arm64-${tag}.tar.md5\"\n\t\tcp \"${tarball_manifest}\" \"out/ecs-agent-arm64-${tag}.tar.json\"\n\n\tdone\n\n    zip -r artifacts_arm.zip out\n    dryval aws s3 cp artifacts_arm.zip \"s3://${S3_BUCKET}/${COMMIT_ID}/artifacts_arm.zip\"\n}\n\n\ngenerate_manifest() {\n\tlocal version=$1\n\n\techo \"{\\\"agentVersion\\\":\\\"${version}\\\"}\"\n}\n\nwhile getopts \"c:d:b:a:sh\" opt; do\n\tcase ${opt} in\n\t    c)\n\t    \tCOMMIT_ID=\"${OPTARG}\"\n\t\t\t;;\n\t\td)\n\t\t\tif [[ \"${OPTARG}\" = \"false\" ]]; then\n\t\t\t\tDRYRUN=false\n\t\t\telse\n\t\t\t\tDRYRUN=true\n\t\t\tfi\n\t\t\t;;\n\t\tb)\n\t\t\tS3_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\ta)\n\t\t\tS3_ACL_OVERRIDE=\"${OPTARG}\"\n\t\t\t;;\n\t\ts)\n\t\t\tSKIP_REBUILD=true\n\t\t\t;;\n\t\t\\?)\n\t\t\techo \"Invalid option -${OPTARG}\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\t:)\n\t\t\techo \"Option -${OPTARG} requires an argument.\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\th)\n\t\t\tusage\n\t\t\texit 0\n\t\t\t;;\n\tesac\ndone\n\nif [[ -z \"${S3_BUCKET}\" ]]; then\n\tusage\n\texit 1\nfi\n\nif ! $(${SKIP_REBUILD}); then\n    TARGET_OS=\"${TARGET_OS}\" make release\nfi\n\nstage_s3\n", "num_lines": 125}
{"repo_name": "amazon-ecs-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# This script will update the information of the ecs-init during building\nset -e -x\n\nCURRENTDIR=$(dirname \"${0}\")\nversion=$(cat \"${CURRENTDIR}\"/../ecs-init/ECSVERSION)\ngit_hash=$(git rev-parse --short=8 HEAD)\ngit_dirty=false\n\nif [[ \"$(git status --porcelain)\" != \"\" ]]; then\n\tgit_dirty=true\nfi\n\ncat << EOF > \"${CURRENTDIR}\"/../ecs-init/version/version.go\n// This is an autogenerated file and should not be edited.\n\n// Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//\thttp://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// Package version contains constants to indicate the current version of the\n// ecs-init. It is autogenerated.\npackage version\n\n// Version is the version of the ecs-init\nvar Version string = \"${version}\"\n\n// GitDirty indicates the cleanliness of the git repo when this ecs-init was built\nvar GitDirty string = \"${git_dirty}\"\n\n// GitShortHash is the short hash of this ecs-init build\nvar GitShortHash string = \"${git_hash}\"\nEOF\n\ncat << EOF > \"${CURRENTDIR}\"/../agent/version/version.go\n// This is an autogenerated file and should not be edited.\n\n// Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//\thttp://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// Package version contains constants to indicate the current version of the\n// ecs-agent. It is autogenerated.\npackage version\n\n// Version is the version of the ecs-agent\nconst Version = \"${version}\"\n\n// GitDirty indicates the cleanliness of the git repo when this ecs-init was built\nconst GitDirty = ${git_dirty}\n\n// GitShortHash is the short hash of this ecs-agent build\nconst GitShortHash = \"${git_hash}\"\nEOF\n", "num_lines": 87}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nusage() {\n    echo \"Usage:\"\n    echo \"  $0 AL2_GPU_NVIDIA_VERSION AL2_GPU_CUDA_VERSION [AL1_CONTAINERD_VERSION]\"\n    echo \"  AL1_CONTAINERD_VERSION should not be provided if there is no AL1 AMI release\"\n    echo \"Example:\"\n    echo \"  $0 470.182.03 11.4 1.4.13 # AL1 release included\"\n    echo \"  $0 470.182.03 11.4        # No AL1 release\"\n}\n\n# Parameters\nal2_gpu_nvidia_version=$1\nal2_gpu_cuda_version=$2\nal1_containerd_version=$3 # Optional, will include AL1 in the release notes if provided\n\nif [ \"$al2_gpu_nvidia_version\" == \"\" ]; then\n    echo \"Error: AL2 GPU NVIDIA version is empty\"\n    usage\n    exit 1\nfi\nif [ \"$al2_gpu_cuda_version\" == \"\" ]; then\n    echo \"Error: AL2 GPU CUDA version is empty\"\n    usage\n    exit 1\nfi\n\n# Read some information from pkrvars file\nreadonly pkrvars=\"release.auto.pkrvars.hcl\"\nreadonly ami_version=$(cat $pkrvars | grep -w 'ami_version' | cut -d '\"' -f2)\nreadonly containerd_version_al2023=$(cat $pkrvars | grep -w 'containerd_version_al2023' | cut -d '\"' -f2)\nreadonly distribution_release_al2023=$(cat $pkrvars | grep -w 'distribution_release_al2023' | cut -d '\"' -f2)\nreadonly containerd_version=$(cat $pkrvars | grep -w 'containerd_version' | cut -d '\"' -f2)\n\nif [ -z \"$ami_version\" ]; then\n    echo \"Error: AMI version was not found in $pkrvars\"\n    exit 1\nfi\nif [ -z \"$containerd_version_al2023\" ]; then\n    echo \"Error: Containerd version was not found for AL2023 in $pkrvars\"\n    exit 1\nfi\nif [ -z \"$distribution_release_al2023\" ]; then\n    echo \"Error: Distribution release version was not found for AL2023 in $pkrvars\"\n    exit 1\nfi\nif [ -z \"$containerd_version\" ]; then\n    echo \"Error: Containerd version was not found in $pkrvars\"\n    exit 1\nfi\n\n# Gets ECS Optimized AMI details from SSM parameter store given the paramter name.\n# Uses the default AWS credentials as the parameter is public and can be\n# fetched from a standard region (us-west-2 is used).\nget_ami_details() {\n    parameter_name=$1\n    ami_details=$(aws ssm --region \"us-west-2\" get-parameters --names $parameter_name --query 'Parameters[0].Value' --output text | jq .)\n    ami_name=$(echo \"$ami_details\" | jq -r '.image_name')\n    agent_version=$(echo \"$ami_details\" | jq -r '.ecs_agent_version')\n    docker_version=$(echo \"$ami_details\" | jq -r '.ecs_runtime_version' | awk '{print $3}')\n    source_ami_name=$(echo \"$ami_details\" | jq -r '.source_image_name')\n    echo \"$ami_name $agent_version $docker_version $source_ami_name\"\n}\n\n# AL2023 AMI details\nread ami_name_al2023_x86 agent_version_al2023_x86 docker_version_al2023_x86 source_ami_name_al2023_x86 <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2023/recommended\")\nread ami_name_al2023_arm agent_version_al2023_arm docker_version_al2023_arm source_ami_name_al2023_arm <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2023/arm64/recommended\")\nread ami_name_al2023_neuron agent_version_al2023_neuron docker_version_al2023_neuron source_ami_name_al2023_neuron <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2023/neuron/recommended\")\n\n# AL2 AMI details\nread ami_name_al2_x86 agent_version_al2_x86 docker_version_al2_x86 source_ami_name_al2_x86 <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/recommended\")\nread ami_name_al2_arm agent_version_al2_arm docker_version_al2_arm source_ami_name_al2_arm <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/arm64/recommended\")\nread ami_name_al2_gpu agent_version_al2_gpu docker_version_al2_gpu source_ami_name_al2_gpu <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/gpu/recommended\")\nread ami_name_al2_inf agent_version_al2_inf docker_version_al2_inf source_ami_name_al2_inf <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/inf/recommended\")\nread ami_name_al2_kernel_5_10 agent_version_al2_kernel_5_10 docker_version_al2_kernel_5_10 source_ami_name_al2_kernel_5_10 <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/kernel-5.10/recommended\")\nread ami_name_al2_kernel_5_10_arm agent_version_al2_kernel_5_10_arm docker_version_al2_kernel_5_10_arm source_ami_name_al2_kernel_5_10_arm <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux-2/kernel-5.10/arm64/recommended\")\n\n# AL1 AMI details\nread ami_name_al1 agent_version_al1 docker_version_al1 source_ami_name_al1 <<<$(get_ami_details \"/aws/service/ecs/optimized-ami/amazon-linux/recommended\")\n\n# Prepare release notes\nrelease_notes=\"### Source AMI release notes\n---\n* [Amazon Linux 2023 release notes](https://docs.aws.amazon.com/linux/al2023/release-notes/relnotes.html)\n* [Amazon Linux 2 release notes](https://docs.aws.amazon.com/AL2/latest/relnotes/relnotes-al2.html)\n* [Amazon Linux release notes](https://aws.amazon.com/amazon-linux-ami/2018.03-release-notes)\n\n### Changelog\n---\nhttps://github.com/aws/amazon-ecs-ami/blob/main/CHANGELOG.md#$ami_version\n\n### Amazon ECS-optimized Amazon Linux 2023 AMI\n---\n#### AMD64\n- AMI name: $ami_name_al2023_x86\n- ECS Agent version: [$agent_version_al2023_x86](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2023_x86)\n- Docker version: $docker_version_al2023_x86\n- Containerd version: $containerd_version_al2023\n- Source AMI name: $source_ami_name_al2023_x86\n- Distribution al2023 release: $distribution_release_al2023\n\n#### ARM64\n- AMI name: $ami_name_al2023_arm\n- ECS Agent version: [$agent_version_al2023_arm](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2023_arm)\n- Docker version: $docker_version_al2023_arm\n- Containerd version: $containerd_version_al2023\n- Source AMI name: $source_ami_name_al2023_arm\n- Distribution al2023 release: $distribution_release_al2023\n\n#### Neuron\n- AMI name: $ami_name_al2023_neuron\n- ECS Agent version: [$agent_version_al2023_neuron](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2023_neuron)\n- Docker version: $docker_version_al2023_neuron\n- Containerd version: $containerd_version_al2023\n- Source AMI name: $source_ami_name_al2023_neuron\n- Distribution al2023 release: $distribution_release_al2023\n\n### Amazon ECS-optimized Amazon Linux 2 AMI\n---\n#### AMD64 (Kernel 4.14)\n- AMI name: $ami_name_al2_x86\n- ECS Agent version: [$agent_version_al2_x86](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_x86)\n- Docker version: $docker_version_al2_x86\n- Containerd version: $containerd_version\n- Source AMI name: $source_ami_name_al2_x86\n\n#### ARM64 (Kernel 4.14)\n- AMI name: $ami_name_al2_arm\n- ECS Agent version: [$agent_version_al2_arm](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_arm)\n- Docker version: $docker_version_al2_arm\n- Containerd version: $containerd_version\n- Source AMI name: $source_ami_name_al2_arm\n\n#### Neuron (Kernel 4.14)\n- AMI name: $ami_name_al2_inf\n- ECS Agent version: [$agent_version_al2_inf](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_inf)\n- Docker version: $docker_version_al2_inf\n- Containerd version: $containerd_version\n- Source AMI name: $source_ami_name_al2_inf\n\n#### GPU (Kernel 4.14)\n- AMI name: $ami_name_al2_gpu\n- ECS Agent version: [$agent_version_al2_gpu](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_gpu)\n- Docker version: $docker_version_al2_gpu\n- Containerd version: $containerd_version\n- NVIDIA driver version: $al2_gpu_nvidia_version\n- CUDA version: $al2_gpu_cuda_version\n- Source AMI name: $source_ami_name_al2_gpu\n\n#### AMD64 (Kernel 5.10)\n- AMI name: $ami_name_al2_kernel_5_10\n- ECS Agent version: [$agent_version_al2_kernel_5_10](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_kernel_5_10)\n- Docker version: $docker_version_al2_kernel_5_10\n- Containerd version: $containerd_version\n- Source AMI name: $source_ami_name_al2_kernel_5_10\n\n#### ARM64 (Kernel 5.10)\n- AMI name: $ami_name_al2_kernel_5_10_arm\n- ECS Agent version: [$agent_version_al2_kernel_5_10_arm](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al2_kernel_5_10_arm)\n- Docker version: $docker_version_al2_kernel_5_10_arm\n- Containerd version: $containerd_version\n- Source AMI name: $source_ami_name_al2_kernel_5_10_arm\"\n\n# Include AL1 release notes if there was an AL1 release\nif [ -n \"$al1_containerd_version\" ]; then\n    al1_release_notes=\"\n\n### Amazon ECS-optimized Amazon Linux AMI\n---\nThe Amazon ECS-optimized Amazon Linux AMI is deprecated as of April 15, 2021. After that date, Amazon ECS will continue providing critical and important security updates for the AMI but will not add support for new features.\n\n- AMI name: $ami_name_al1\n- ECS Agent version: [$agent_version_al1](https://github.com/aws/amazon-ecs-agent/releases/tag/v$agent_version_al1)\n- Docker version: $docker_version_al1\n- Containerd version: $al1_containerd_version\n- Source AMI name: $source_ami_name_al1\"\n\n    release_notes=\"${release_notes}${al1_release_notes}\"\nfi\n\necho \"$release_notes\"\n", "num_lines": 184}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -eio pipefail\n\nusage() {\n    echo \"Usage:\"\n    echo \"  $0 ECS_INIT_VERSION AMI_VERSION\"\n    echo \"Example:\"\n    echo \"  $0 1.55.0-1 20210902\"\n}\n\nerror() {\n    local msg=\"$1\"\n    echo \"ERROR: $msg\"\n    usage\n    exit 1\n}\n\nreadonly ecs_init_version=\"$1\"\nif [ -z \"$ecs_init_version\" ]; then\n    error \"ecs-init version is required.\"\nfi\nreadonly ami_version=\"$2\"\nif [ -z \"$ami_version\" ]; then\n    error \"ami version is required.\"\nfi\n\nagent_version=$(echo \"$ecs_init_version\" | awk -F \"-\" '{ print $1 }')\necs_init_rev=$(echo \"$ecs_init_version\" | awk -F \"-\" '{ print $2 }')\nreadonly agent_version ecs_init_rev\nif [ -z \"$ecs_init_rev\" ]; then\n    error \"ecs-init rev was empty, did you forget the dash in ECS_INIT_VERSION? ie, 1.55.0-1\"\nfi\nif [ -z \"$agent_version\" ]; then\n    error \"agent version was empty, seems that your ECS_INIT_VERSION was malformed, it should look like: 1.55.0-1\"\nfi\n\n# this can be any region, as we use it to grab the latest AL2 AMI name so it should be the same across regions.\nreadonly region=\"us-west-2\"\n\nset -x\n\n# Get the latest source AMI names\n# AL1\nami_id_al1=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/amzn-ami-minimal-hvm-x86_64-ebs --query 'Parameters[0].[Value]' --output text)\nami_name_al1=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al1\" --query 'Images[0].Name' --output text)\n\n# AL2\nami_id_al2_x86=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/amzn2-ami-minimal-hvm-x86_64-ebs --query 'Parameters[0].[Value]' --output text)\nami_name_al2_x86=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2_x86\" --query 'Images[0].Name' --output text)\nami_id_al2_arm=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/amzn2-ami-minimal-hvm-arm64-ebs --query 'Parameters[0].[Value]' --output text)\nami_name_al2_arm=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2_arm\" --query 'Images[0].Name' --output text)\nami_id_al2_kernel5dot10=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/amzn2-ami-minimal-hvm-x86_64-ebs --query 'Parameters[0].[Value]' --output text)\nami_name_al2_kernel5dot10=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2_x86\" --query 'Images[0].Name' --output text)\nami_id_al2_kernel5dot10arm=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/amzn2-ami-minimal-hvm-arm64-ebs --query 'Parameters[0].[Value]' --output text)\nami_name_al2_kernel5dot10arm=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2_arm\" --query 'Images[0].Name' --output text)\n\n# AL2023\nami_id_al2023_x86=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64 --query 'Parameters[0].[Value]' --output text)\nami_name_al2023_x86=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2023_x86\" --query 'Images[0].Name' --output text)\nkernel_version_al2023_x86=$(grep -o -e \"-kernel-[1-9.]*\" <<<\"$ami_name_al2023_x86\")\n\n# AL2023 ARM\nami_id_al2023_arm=$(aws ssm get-parameters --region \"$region\" --names /aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-arm64 --query 'Parameters[0].[Value]' --output text)\nami_name_al2023_arm=$(aws ec2 describe-images --region \"$region\" --owner amazon --image-id \"$ami_id_al2023_arm\" --query 'Images[0].Name' --output text)\nkernel_version_al2023_arm=$(grep -o -e \"-kernel-[1-9.]*\" <<<\"$ami_name_al2023_arm\")\n\n# Get the latest AL2023 distribution release\n# Ref: https://docs.aws.amazon.com/linux/al2023/ug/managing-repos-os-updates.html\n# xmllint is required to find the latest distribution release from releasemd.xml in us-west-2\ndistribution_release_al2023=$(curl -s https://al2023-repos-us-west-2-de612dc2.s3.dualstack.us-west-2.amazonaws.com/core/releasemd.xml | xmllint --xpath \"string(//root/releases/release[last()]/@version)\" -)\n\nreadonly ami_name_al2_kernel5dot10arm ami_name_al2_kernel5dot10 ami_name_al2_arm ami_name_al2_x86 ami_name_al1 ami_name_al2023_arm ami_name_al2023_x86 distribution_release_al2023\n\ncat >|release.auto.pkrvars.hcl <<EOF\nami_version          = \"$ami_version\"\necs_agent_version    = \"$agent_version\"\necs_init_rev         = \"$ecs_init_rev\"\ndocker_version       = \"20.10.23\"\ndocker_version_al2023 = \"20.10.23\"\ncontainerd_version   = \"1.6.19\"\ncontainerd_version_al2023 = \"1.6.19\"\nsource_ami_al1       = \"$ami_name_al1\"\nsource_ami_al2       = \"$ami_name_al2_x86\"\nsource_ami_al2arm    = \"$ami_name_al2_arm\"\nsource_ami_al2kernel5dot10    = \"$ami_name_al2_kernel5dot10\"\nsource_ami_al2kernel5dot10arm = \"$ami_name_al2_kernel5dot10arm\"\nsource_ami_al2023    = \"$ami_name_al2023_x86\"\nsource_ami_al2023arm = \"$ami_name_al2023_arm\"\nkernel_version_al2023    = \"$kernel_version_al2023_x86\"\nkernel_version_al2023arm = \"$kernel_version_al2023_arm\"\ndistribution_release_al2023  = \"$distribution_release_al2023\"\nEOF\n", "num_lines": 93}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\ncat <<EOF | sudo tee -a /etc/amazon/efs/efs-utils.conf\n\n[client-info]\nsource = ecs.ec2\nEOF\n", "num_lines": 9}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# Below command actually runs `sudo dnf clean all` for AL2023.\n# See https://docs.aws.amazon.com/linux/al2023/ug/package-management.html for more details.\nsudo yum clean all\n\nfunction cleanup() {\n    FILES=(\"$@\")\n    for FILE in \"${FILES[@]}\"; do\n        if sudo test -f $FILE; then\n            echo \"Deleting $FILE\"\n            sudo shred -zuf $FILE\n        fi\n        if sudo test -f $FILE; then\n            echo \"Failed to delete '$FILE'. Failing.\"\n            exit 1\n        fi\n    done\n}\n\n# Clean up for cloud-init files\nCLOUD_INIT_FILES=(\n    \"/etc/locale.conf\"\n    \"/var/log/cloud-init.log\"\n    \"/var/log/cloud-init-output.log\"\n)\necho \"Cleaning up cloud init files\"\ncleanup \"${CLOUD_INIT_FILES[@]}\"\nif [[ $(sudo find /var/lib/cloud -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting files within /var/lib/cloud/*\"\n    sudo find /var/lib/cloud -type f -exec shred -zuf {} \\;\nfi\n\nif [[ $(sudo ls /var/lib/cloud | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting /var/lib/cloud/*\"\n    sudo rm -rf /var/lib/cloud/* || true\nfi\n\n# Clean up for temporary instance files\nINSTANCE_FILES=(\n    \"/etc/.updated\"\n    \"/etc/aliases.db\"\n    \"/etc/hostname\"\n    \"/var/lib/misc/postfix.aliasesdb-stamp\"\n    \"/var/lib/postfix/master.lock\"\n    \"/var/spool/postfix/pid/master.pid\"\n    \"/var/.updated\"\n    \"/var/cache/yum/x86_64/2/.gpgkeyschecked.yum\"\n)\necho \"Cleaning up instance files\"\ncleanup \"${INSTANCE_FILES[@]}\"\n\n# Clean up for ssh files\nSSH_FILES=(\n    \"/etc/ssh/ssh_host_rsa_key\"\n    \"/etc/ssh/ssh_host_rsa_key.pub\"\n    \"/etc/ssh/ssh_host_ecdsa_key\"\n    \"/etc/ssh/ssh_host_ecdsa_key.pub\"\n    \"/etc/ssh/ssh_host_ed25519_key\"\n    \"/etc/ssh/ssh_host_ed25519_key.pub\"\n    \"/root/.ssh/authorized_keys\"\n)\necho \"Cleaning up ssh files\"\ncleanup \"${SSH_FILES[@]}\"\nUSERS=$(ls /home/)\nfor user in $USERS; do\n    echo Deleting /home/\"$user\"/.ssh/authorized_keys\n    sudo find /home/\"$user\"/.ssh/authorized_keys -type f -exec shred -zuf {} \\;\ndone\nfor user in $USERS; do\n    if sudo test -f /home/\"$user\"/.ssh/authorized_keys; then\n        echo Failed to delete /home/\"$user\"/.ssh/authorized_keys\n        exit 1\n    fi\ndone\n\nINSTANCE_LOG_FILES=(\n    \"/var/log/audit/audit.log\"\n    \"/var/log/boot.log\"\n    \"/var/log/dmesg\"\n    \"/var/log/messages\"\n    \"/var/log/cron\"\n)\necho \"Cleaning up instance log files\"\ncleanup \"${INSTANCE_LOG_FILES[@]}\"\n\necho \"Cleaning TOE files\"\nif [[ $(sudo find {{workingDirectory}}/TOE_* -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting files within {{workingDirectory}}/TOE_*\"\n    sudo find {{workingDirectory}}/TOE_* -type f -exec shred -zuf {} \\;\nfi\nif [[ $(sudo find {{workingDirectory}}/TOE_* -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete {{workingDirectory}}/TOE_*\"\n    exit 1\nfi\nif [[ $(sudo find {{workingDirectory}}/TOE_* -type d | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting {{workingDirectory}}/TOE_*\"\n    sudo rm -rf {{workingDirectory}}/TOE_*\nfi\nif [[ $(sudo find {{workingDirectory}}/TOE_* -type d | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete {{workingDirectory}}/TOE_*\"\n    exit 1\nfi\n\necho \"Cleaning up ssm log files\"\nif [[ $(sudo find /var/log/amazon/ssm -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting files within /var/log/amazon/ssm/*\"\n    sudo find /var/log/amazon/ssm -type f -exec shred -zuf {} \\;\nfi\nif [[ $(sudo find /var/log/amazon/ssm -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete /var/log/amazon/ssm\"\n    exit 1\nfi\nif sudo test -d \"/var/log/amazon/ssm\"; then\n    echo \"Deleting /var/log/amazon/ssm/*\"\n    sudo rm -rf /var/log/amazon/ssm\nfi\nif sudo test -d \"/var/log/amazon/ssm\"; then\n    echo \"Failed to delete /var/log/amazon/ssm\"\n    exit 1\nfi\n\nif [[ $(sudo find /var/log/sa/sa* -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting /var/log/sa/sa*\"\n    sudo shred -zuf /var/log/sa/sa*\nfi\nif [[ $(sudo find /var/log/sa/sa* -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete /var/log/sa/sa*\"\n    exit 1\nfi\n\nif [[ $(sudo find /var/lib/dhclient/dhclient*.lease -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting /var/lib/dhclient/dhclient*.lease\"\n    sudo shred -zuf /var/lib/dhclient/dhclient*.lease\nfi\nif [[ $(sudo find /var/lib/dhclient/dhclient*.lease -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete /var/lib/dhclient/dhclient*.lease\"\n    exit 1\nfi\n\nif [[ $(sudo find /var/tmp -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting files within /var/tmp/*\"\n    sudo find /var/tmp -type f -exec shred -zuf {} \\;\nfi\nif [[ $(sudo find /var/tmp -type f | sudo wc -l) -gt 0 ]]; then\n    echo \"Failed to delete /var/tmp\"\n    exit 1\nfi\nif [[ $(sudo ls /var/tmp | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting /var/tmp/*\"\n    sudo rm -rf /var/tmp/*\nfi\n\n# Shredding is not guaranteed to work well on rolling logs\n\nif sudo test -f \"/var/lib/rsyslog/imjournal.state\"; then\n    echo \"Deleting /var/lib/rsyslog/imjournal.state\"\n    sudo shred -zuf /var/lib/rsyslog/imjournal.state\n    sudo rm -f /var/lib/rsyslog/imjournal.state\nfi\n\nif [[ $(sudo ls /var/log/journal/ | sudo wc -l) -gt 0 ]]; then\n    echo \"Deleting /var/log/journal/*\"\n    sudo find /var/log/journal/ -type f -exec shred -zuf {} \\;\n    sudo rm -rf /var/log/journal/*\nfi\n\n# delete a few items missed in https://docs.aws.amazon.com/imagebuilder/latest/userguide/security-best-practices.html\nsudo rm -rf \\\n    /etc/machine-id \\\n    /var/cache/dnf \\\n    /var/cache/yum \\\n    /tmp/* \\\n    /var/lib/dhcp/dhclient.* \\\n    /var/lib/dnf/history* \\\n    /var/lib/yum/history \\\n    /var/log/secure \\\n    /var/log/wtmp \\\n    /etc/ssh/ssh_host*\n\nsudo touch /etc/machine-id\n", "num_lines": 183}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif [[ $AMI_TYPE != \"al2gpu\" ]]; then\n    exit 0\nfi\n\nGPG_CHECK=1\n# don't do the gpg check in air-gapped regions\nif [ -n \"$AIR_GAPPED\" ]; then\n    GPG_CHECK=0\nfi\ntmpfile=$(mktemp)\ncat >$tmpfile <<EOF\n[amzn2-nvidia]\nname=Amazon Linux 2 Nvidia repository\nmirrorlist=\\$awsproto://\\$amazonlinux.\\$awsregion.\\$awsdomain/\\$releasever/amzn2-nvidia/latest/\\$basearch/mirror.list\npriority=20\ngpgcheck=$GPG_CHECK\ngpgkey=https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/7fa2af80.pub\nenabled=1\nexclude=libglvnd-*\nEOF\n\n# this repo is temporary and only used for installing the system-release-nvidia package\nsudo mv $tmpfile /etc/yum.repos.d/amzn2-nvidia-tmp.repo\n# system-release-nvidia creates an nvidia repo file at /etc/yum.repos.d/amzn2-nvidia.repo\nsudo yum install -y system-release-nvidia\nsudo rm /etc/yum.repos.d/amzn2-nvidia-tmp.repo\n\nsudo yum install -y kernel-devel-$(uname -r) \\\n    system-release-nvidia \\\n    nvidia-driver-latest-dkms \\\n    nvidia-fabric-manager \\\n    pciutils \\\n    xorg-x11-server-Xorg \\\n    docker-runtime-nvidia \\\n    oci-add-hooks \\\n    libnvidia-container \\\n    libnvidia-container-tools \\\n    nvidia-container-runtime-hook\n\nsudo yum install -y cuda-drivers \\\n    cuda\n\n# The Fabric Manager service needs be started and enabled on EC2 P4d instances\n# in order to configure NVLinks and NVSwitches\nsudo systemctl enable nvidia-fabricmanager\nmkdir -p /tmp/ecs\necho 'ECS_ENABLE_GPU_SUPPORT=true' >>/tmp/ecs/ecs.config\nsudo mv /tmp/ecs/ecs.config /var/lib/ecs/ecs.config\n", "num_lines": 52}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif [[ $AMI_TYPE != \"al2inf\" && $AMI_TYPE != \"al2023neu\" ]]; then\n    exit 0\nfi\n\n# docs about installing neuron docker environment on inferentia instances:\n# https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-deploy/tutorials/tutorial-docker-env-setup.html\n# https://awsdocs-neuron.readthedocs-hosted.com/en/latest/neuron-intro/mxnet-setup/mxnet-install.html#install-neuron-mxnet\n\n# Copy the neuron repo\ncat >/tmp/neuron.repo <<EOF\n[neuron]\nname=neuron\nbaseurl=https://yum.repos.neuron.amazonaws.com/\npriority=12\ngpgcheck=0\ngpgkey=https://yum.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB\nenabled=1\nkeepcache=0\nEOF\n\nsudo mv /tmp/neuron.repo /etc/yum.repos.d/neuron.repo\n\n# Install OS headers\nsudo yum install kernel-devel-$(uname -r) kernel-headers-$(uname -r) -y\n\n# Install Neuron Driver\nsudo yum install -y aws-neuronx-dkms-2.*\nsudo yum install -y aws-neuronx-oci-hook-2.*\n\n# Install oci-add-hooks\n# TODO: oci-add-hooks package has compatibility issue with AL2023 IMDSv2. Remove condition after root caused and resolved\nif [[ $AMI_TYPE == \"al2inf\" ]]; then\n    sudo yum install -y oci-add-hooks\nfi\n\n# Install Neuron Tools\n# TODO: use aws-neuronx-tools on al2inf when it is ready\nif [[ $AMI_TYPE == \"al2inf\" ]]; then # drop this dependency for AL2023 or later AMIs\n    sudo yum install -y aws-neuron-tools\nfi\n\n# disable neuron package upgrades by deleting the yum repo\nsudo rm /etc/yum.repos.d/neuron.repo\n\nNEURON_RUNTIME=/etc/docker-runtimes.d/neuron\n# Add env variable to identify if inf is supported on this ami\nmkdir -p /tmp/ecs\necho 'ECS_ENABLE_INF_SUPPORT=true' >>/tmp/ecs/ecs.config\nsudo mv /tmp/ecs/ecs.config /var/lib/ecs/ecs.config\n\n# Copy neuron runtime to docker runtime to be accessed as one of the runtimes supported.\nif [ ! -f $NEURON_RUNTIME ]; then\n    sudo cp /opt/aws/neuron/bin/oci_neuron_hook_wrapper.sh $NEURON_RUNTIME\n    sudo chmod +x $NEURON_RUNTIME\nfi\n", "num_lines": 59}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nsudo systemctl enable ecs\nsudo systemctl enable amazon-ecs-volume-plugin\nsudo systemctl enable amazon-ssm-agent\n", "num_lines": 7}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nARCH=$(uname -m)\n\n# install any rpm packages from the additional-packages/ directory\nif ls /tmp/additional-packages/*.\"${ARCH}\".rpm; then\n    echo \"Found additional packages with architecture ${ARCH} to be installed\"\n    sudo yum localinstall -y /tmp/additional-packages/*.\"${ARCH}\".rpm\nelse\n    echo \"No matching additional packages with architecture ${ARCH} found\"\nfi\nif ls /tmp/additional-packages/*.noarch.rpm; then\n    echo \"Found additional packages with no specific architecture to be installed\"\n    sudo yum localinstall -y /tmp/additional-packages/*.noarch.rpm\nelse\n    echo \"No matching additional packages with no architecture found\"\nfi\n", "num_lines": 19}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif [ -n \"$AIR_GAPPED\" ]; then\n    echo \"Air-gapped region, assuming docker and dependencies will be in additional-packages/ directory\"\n    exit 0\nfi\n\nif command -v amazon-linux-extras; then\n    # enable docker \"extras\" repo when available\n    sudo amazon-linux-extras enable docker\nfi\n\nsudo yum install -y \"docker-$DOCKER_VERSION\" \"containerd-$CONTAINERD_VERSION\"\n", "num_lines": 15}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif [ -n \"$AIR_GAPPED\" ]; then\n    echo \"Air-gapped region, assuming ecs-init and dependencies will be in additional-packages/ directory\"\n    exit 0\nfi\n\nif [ -n \"$INIT_LOCAL_OVERRIDE\" ]; then\n    echo \"ecs-init is provided locally, assuming it's in additional-packages/ directory\"\n    exit 0\nfi\n\nWORK_DIR=\"$(mktemp -d)\"\ntrap \"rm -rf ${WORK_DIR}\" EXIT\n\n# gpg key is taken from https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ecs-agent-install.html\ncat >\"$WORK_DIR/amazon-ecs-agent.gpg\" <<EOF\n-----BEGIN PGP PUBLIC KEY BLOCK-----\nVersion: GnuPG v2\n\nmQINBFq1SasBEADliGcT1NVJ1ydfN8DqebYYe9ne3dt6jqKFmKowLmm6LLGJe7HU\njGtqhCWRDkN+qPpHqdArRgDZAtn2pXY5fEipHgar4CP8QgRnRMO2fl74lmavr4Vg\n7K/KH8VHlq2uRw32/B94XLEgRbGTMdWFdKuxoPCttBQaMj3LGn6Pe+6xVWRkChQu\nBoQAhjBQ+bEm0kNy0LjNgjNlnL3UMAG56t8E3LANIgGgEnpNsB1UwfWluPoGZoTx\nN+6pHBJrKIL/1v/ETU4FXpYw2zvhWNahxeNRnoYj3uycHkeliCrw4kj0+skizBgO\n2K7oVX8Oc3j5+ZilhL/qDLXmUCb2az5cMM1mOoF8EKX5HaNuq1KfwJxqXE6NNIcO\nlFTrT7QwD5fMNld3FanLgv/ZnIrsSaqJOL6zRSq8O4LN1OWBVbndExk2Kr+5kFxn\n5lBPgfPgRj5hQ+KTHMa9Y8Z7yUc64BJiN6F9Nl7FJuSsfqbdkvRLsQRbcBG9qxX3\nrJAEhieJzVMEUNl+EgeCkxj5xuSkNU7zw2c3hQZqEcrADLV+hvFJktOz9Gm6xzbq\nlTnWWCz4xrIWtuEBA2qE+MlDheVd78a3gIsEaSTfQq0osYXaQbvlnSWOoc1y/5Zb\nzizHTJIhLtUyls9WisP2s0emeHZicVMfW61EgPrJAiupgc7kyZvFt4YwfwARAQAB\ntCRBbWF6b24gRUNTIDxlY3Mtc2VjdXJpdHlAYW1hem9uLmNvbT6JAhwEEAECAAYF\nAlrjL0YACgkQHivRXs0TaQrg1g/+JppwPqHnlVPmv7lessB8I5UqZeD6p6uVpHd7\nBs3pcPp8BV7BdRbs3sPLt5bV1+rkqOlw+0gZ4Q/ue/YbWtOAt4qY0OcEo0HgcnaX\nlsB827QIfZIVtGWMhuh94xzm/SJkvngml6KB3YJNnWP61A9qJ37/VbVVLzvcmazA\nMcWB4HUMNrhd0JgBCo0gIpqCbpJEvUc02Bjn23eEJsS9kC7OUAHyQkVnx4d9UzXF\n4OoISF6hmQKIBoLnRrAlj5Qvs3GhvHQ0ThYq0Grk/KMJJX2CSqt7tWJ8gk1n3H3Y\nSReRXJRnv7DsDDBwFgT6r5Q2HW1TBUvaoZy5hF6maD09nHcNnvBjqADzeT8Tr/Qu\nbBCLzkNSYqqkpgtwv7seoD2P4n1giRvDAOEfMZpVkUr+C252IaH1HZFEz+TvBVQM\nY8OWWxmIJW+J6evjo3N1eO19UHv71jvoF8zljbI4bsL2c+QTJmOv7nRqzDQgCWyp\nId/v2dUVVTk1j9omuLBBwNJzQCB+72LcIzJhYmaP1HC4LcKQG+/f41exuItenatK\nlEJQhYtyVXcBlh6Yn/wzNg2NWOwb3vqY/F7m6u9ixAwgtIMgPCDE4aJ86zrrXYFz\nN2HqkTSQh77Z8KPKmyGopsmN/reMuilPdINb249nA0dzoN+nj+tTFOYCIaLaFyjs\nZ0r1QAOJAjkEEwECACMFAlq1SasCGwMHCwkIBwMCAQYVCAIJCgsEFgIDAQIeAQIX\ngAAKCRC86dmkLVF4T9iFEACEnkm1dNXsWUx34R3c0vamHrPxvfkyI1FlEUen8D1h\nuX9xy6jCEROHWEp0rjGK4QDPgM93sWJ+s1UAKg214QRVzft0y9/DdR+twApA0fzy\nuavIthGd6+03jAAo6udYDE+cZC3P7XBbDiYEWk4XAF9I1JjB8hTZUgvXBL046JhG\neM17+crgUyQeetkiOQemLbsbXQ40Bd9V7zf7XJraFd8VrwNUwNb+9KFtgAsc9rk+\nYIT/PEf+YOPysgcxI4sTWghtyCulVnuGoskgDv4v73PALU0ieUrvvQVqWMRvhVx1\n0X90J7cC1KOyhlEQQ1aFTgmQjmXexVTwIBm8LvysFK6YXM41KjOrlz3+6xBIm/qe\nbFyLUnf4WoiuOplAaJhK9pRY+XEnGNxdtN4D26Kd0F+PLkm3Tr3Hy3b1Ok34FlGr\nKVHUq1TZD7cvMnnNKEELTUcKX+1mV3an16nmAg/my1JSUt6BNK2rJpY1s/kkSGSE\nXQ4zuF2IGCpvBFhYAlt5Un5zwqkwwQR3/n2kwAoDzonJcehDw/C/cGos5D0aIU7I\nK2X2aTD3+pA7Mx3IMe2hqmYqRt9X42yF1PIEVRneBRJ3HDezAgJrNh0GQWRQkhIx\ngz6/cTR+ekr5TptVszS9few2GpI5bCgBKBisZIssT89aw7mAKWut0Gcm4qM9/yK6\n1bkCDQRatUmrARAAxNPvVwreJ2yAiFcUpdRlVhsuOgnxvs1QgsIw3H7+Pacr9Hpe\n8uftYZqdC82KeSKhpHq7c8gMTMucIINtH25x9BCc73E33EjCL9Lqov1TL7+QkgHe\nT+JIhZwdD8Mx2K+LVVVu/aWkNrfMuNwyDUciSI4D5QHa8T+F8fgN4OTpwYjirzel\n5yoICMr9hVcbzDNv/ozKCxjx+XKgnFc3wrnDfJfntfDAT7ecwbUTL+viQKJ646s+\npsiqXRYtVvYInEhLVrJ0aV6zHFoigE/Bils6/g7ru1Q6CEHqEw++APs5CcE8VzJu\nWAGSVHZgun5Y9N4quR/M9Vm+IPMhTxrAg7rOvyRN9cAXfeSMf77I+XTifigNna8x\nt/MOdjXr1fjF4pThEi5u6WsuRdFwjY2azEv3vevodTi4HoJReH6dFRa6y8c+UDgl\n2iHiOKIpQqLbHEfQmHcDd2fix+AaJKMnPGNku9qCFEMbgSRJpXz6BfwnY1QuKE+I\nR6jA0frUNt2jhiGG/F8RceXzohaaC/Cx7LUCUFWc0n7z32C9/Dtj7I1PMOacdZzz\nbjJzRKO/ZDv+UN/c9dwAkllzAyPMwGBkUaY68EBstnIliW34aWm6IiHhxioVPKSp\nVJfyiXPO0EXqujtHLAeChfjcns3I12YshT1dv2PafG53fp33ZdzeUgsBo+EAEQEA\nAYkCHwQYAQIACQUCWrVJqwIbDAAKCRC86dmkLVF4T+ZdD/9x/8APzgNJF3o3STrF\njvnV1ycyhWYGAeBJiu7wjsNWwzMFOv15tLjB7AqeVxZn+WKDD/mIOQ45OZvnYZuy\nX7DR0JszaH9wrYTxZLVruAu+t6UL0y/XQ4L1GZ9QR6+r+7t1Mvbfy7BlHbvX/gYt\nRwe/uwdibI0CagEzyX+2D3kTOlHO5XThbXaNf8AN8zha91Jt2Q2UR2X5T6JcwtMz\nFBvZnl3LSmZyE0EQehS2iUurU4uWOpGppuqVnbi0jbCvCHKgDGrqZ0smKNAQng54\nF365W3g8AfY48s8XQwzmcliowYX9bT8PZiEi0J4QmQh0aXkpqZyFefuWeOL2R94S\nXKzr+gRh3BAULoqF+qK+IUMxTip9KTPNvYDpiC66yBiT6gFDji5Ca9pGpJXrC3xe\nTXiKQ8DBWDhBPVPrruLIaenTtZEOsPc4I85yt5U9RoPTStcOr34s3w5yEaJagt6S\nGc5r9ysjkfH6+6rbi1ujxMgROSqtqr+RyB+V9A5/OgtNZc8llK6u4UoOCde8jUUW\nvqWKvjJB/Kz3u4zaeNu2ZyyHaOqOuH+TETcW+jsY9IhbEzqN5yQYGi4pVmDkY5vu\nlXbJnbqPKpRXgM9BecV9AMbPgbDq/5LnHJJXg+G8YQOgp4lR/hC1TEFdIp5wM8AK\nCWsENyt2o1rjgMXiZOMF8A5oBLkCDQRatUuSARAAr77kj7j2QR2SZeOSlFBvV7oS\nmFeSNnz9xZssqrsm6bTwSHM6YLDwc7Sdf2esDdyzONETwqrVCg+FxgL8hmo9hS4c\nrR6tmrP0mOmptr+xLLsKcaP7ogIXsyZnrEAEsvW8PnfayoiPCdc3cMCR/lTnHFGA\n7EuR/XLBmi7Qg9tByVYQ5Yj5wB9V4B2yeCt3XtzPqeLKvaxl7PNelaHGJQY/xo+m\nV0bndxf9IY+4oFJ4blD32WqvyxESo7vW6WBh7oqv3Zbm0yQrr8a6mDBpqLkvWwNI\n3kpJR974tg5o5LfDu1BeeyHWPSGm4U/G4JB+JIG1ADy+RmoWEt4BqTCZ/knnoGvw\nD5sTCxbKdmuOmhGyTssoG+3OOcGYHV7pWYPhazKHMPm201xKCjH1RfzRULzGKjD+\nyMLT1I3AXFmLmZJXikAOlvE3/wgMqCXscbycbLjLD/bXIuFWo3rzoezeXjgi/DJx\njKBAyBTYO5nMcth1O9oaFd9d0HbsOUDkIMnsgGBE766Piro6MHo0T0rXl07Tp4pI\nrwuSOsc6XzCzdImj0Wc6axS/HeUKRXWdXJwno5awTwXKRJMXGfhCvSvbcbc2Wx+L\nIKvmB7EB4K3fmjFFE67yolmiw2qRcUBfygtH3eL5XZU28MiCpue8Y8GKJoBAUyvf\nKeM1rO8Jm3iRAc5a/D0AEQEAAYkEPgQYAQIACQUCWrVLkgIbAgIpCRC86dmkLVF4\nT8FdIAQZAQIABgUCWrVLkgAKCRDePL1hra+LjtHYD/9MucxdFe6bXO1dQR4tKhhQ\nP0LRqy6zlBY9ILCLowNdGZdqorogUiUymgn3VhEhVtxTOoHcN7qOuM01PNsRnOeS\nEYjf8Xrb1clzkD6xULwmOclTb9bBxnBc/4PFvHAbZW3QzusaZniNgkuxt6BTfloS\nOf4inq71kjmGK+TlzQ6mUMQUg228NUQC+a84EPqYyAeY1sgvgB7hJBhYL0QAxhcW\n6m20Rd8iEc6HyzJ3yCOCsKip/nRWAbf0OvfHfRBp0+m0ZwnJM8cPRFjOqqzFpKH9\nHpDmTrC4wKP1+TL52LyEqNh4yZitXmZNV7giSRIkk0eDSko+bFy6VbMzKUMkUJK3\nD3eHFAMkujmbfJmSMTJOPGn5SB1HyjCZNx6bhIIbQyEUB9gKCmUFaqXKwKpF6rj0\niQXAJxLR/shZ5Rk96VxzOphUl7T90m/PnUEEPwq8KsBhnMRgxa0RFidDP+n9fgtv\nHLmrOqX9zBCVXh0mdWYLrWvmzQFWzG7AoE55fkf8nAEPsalrCdtaNUBHRXA0OQxG\nAHMOdJQQvBsmqMvuAdjkDWpFu5y0My5ddU+hiUzUyQLjL5Hhd5LOUDdewlZgIw1j\nxrEAUzDKetnemM8GkHxDgg8koev5frmShJuce7vSjKpCNg3EIJSgqMOPFjJuLWtZ\nvjHeDNbJy6uNL65ckJy6WhGjEADS2WAW1D6Tfekkc21SsIXk/LqEpLMR/0g5OUif\nwcEN1rS9IJXBwIy8MelN9qr5KcKQLmfdfBNEyyceBhyVl0MDyHOKC+7PofMtkGBq\n13QieRHv5GJ8LB3fclqHV8pwTTo3Bc8z2g0TjmUYAN/ixETdReDoKavWJYSE9yoM\naaJu279ioVTrwpECse0XkiRyKToTjwOb73CGkBZZpJyqux/rmCV/fp4ALdSW8zbz\nFJVORaivhoWwzjpfQKhwcU9lABXi2UvVm14v0AfeI7oiJPSU1zM4fEny4oiIBXlR\nzhFNih1UjIu82X16mTm3BwbIga/s1fnQRGzyhqUIMii+mWra23EwjChaxpvjjcUH\n5ilLc5Zq781aCYRygYQw+hu5nFkOH1R+Z50Ubxjd/aqUfnGIAX7kPMD3Lof4KldD\nQ8ppQriUvxVo+4nPV6rpTy/PyqCLWDjkguHpJsEFsMkwajrAz0QNSAU5CJ0G2Zu4\nyxvYlumHCEl7nbFrm0vIiA75Sa8KnywTDsyZsu3XcOcf3g+g1xWTpjJqy2bYXlqz\n9uDOWtArWHOis6bq8l9RE6xr1RBVXS6uqgQIZFBGyq66b0dIq4D2JdsUvgEMaHbc\ne7tBfeB1CMBdA64e9Rq7bFR7Tvt8gasCZYlNr3lydh+dFHIEkH53HzQe6l88HEic\n+0jVnLkCDQRa55wJARAAyLya2Lx6gyoWoJN1a6740q3o8e9d4KggQOfGMTCflmeq\nivuzgN+3DZHN+9ty2KxXMtn0mhHBerZdbNJyjMNT1gAgrhPNB4HtXBXum2wS57WK\nDNmade914L7FWTPAWBG2Wn448OEHTqsClICXXWy9IICgclAEyIq0Yq5mAdTEgRJS\nZ8t4GpwtDL9gNQyFXaWQmDmkAsCygQMvhAlmu9xOIzQG5CxSnZFk7zcuL60k14Z3\nCmt49k4T/7ZU8goWi8tt+rU78/IL3J/fF9+1civ1OwuUidgfPCSvOUW1JojsdCQA\nL+RZJcoXq7lfOFj/eNjeOSstCTDPfTCL+kThE6E5neDtbQHBYkEX1BRiTedsV4+M\nucgiTrdQFWKf89G72xdv8ut9AYYQ2BbEYU+JAYhUH8rYYui2dHKJIgjNvJscuUWb\n+QEqJIRleJRhrO+/CHgMs4fZAkWF1VFhKBkcKmEjLn1f7EJJUUW84ZhKXjO/AUPX\n1CHsNjziRceuJCJYox1cwsoq6jTE50GiNzcIxTn9xUc0UMKFeggNAFys1K+TDTm3\nBzo8H5ucjCUEmUm9lhkGwqTZgOlRX5eqPX+JBoSaObqhgqCa5IPinKRa6MgoFPHK\n6sYKqroYwBGgZm6Js5chpNchvJMs/3WXNOEVg0J3z3vP0DMhxqWm+r+n9zlW8qsA\nEQEAAYkEPgQYAQgACQUCWuecCQIbAgIpCRC86dmkLVF4T8FdIAQZAQgABgUCWuec\nCQAKCRBQ3szEcQ5hr+ykD/4tOLRHFHXuKUcxgGaubUcVtsFrwBKma1cYjqaPms8u\n6Sk0wfGRI32G/GhOrp0Ts/MOkbObq6VLTh8N5Yc/53MEl8zQFw9Y5AmRoW4PZXER\nujs5s7p4oR7xHMihMjCCBn1bvrR+34YPfgzTcgLiOEFHYT8UTxwnGmXOvNkMM7md\nxD3CV5q6VAte8WKBo/220II3fcQlc9r/oWX4kXXkb0v9hoGwKbDJ1tzqTPrp/xFt\nyohqnvImpnlz+Q9zXmbrWYL9/g8VCmW/NN2gju2G3Lu/TlFUWIT4v/5OPK6TdeNb\nVKJO4+S8bTayqSG9CML1S57KSgCo5HUhQWeSNHI+fpe5oX6FALPT9JLDce8OZz1i\ncZZ0MELP37mOOQun0AlmHm/hVzf0f311PtbzcqWaE51tJvgUR/nZFo6Ta3O5Ezhs\n3VlEJNQ1Ijf/6DH87SxvAoRIARCuZd0qxBcDK0avpFzUtbJd24lRA3WJpkEiMqKv\nRDVZkE4b6TW61f0o+LaVfK6E8oLpixegS4fiqC16mFrOdyRk+RJJfIUyz0WTDVmt\ng0U1CO1ezokMSqkJ7724pyjr2xf/r9/sC6aOJwB/lKgZkJfC6NqL7TlxVA31dUga\nLEOvEJTTE4gl+tYtfsCDvALCtqL0jduSkUo+RXcBItmXhA+tShW0pbS2Rtx/ixua\nKohVD/0R4QxiSwQmICNtm9mw9ydIl1yjYXX5a9x4wMJracNY/LBybJPFnZnT4dYR\nz4XjqysDwvvYZByaWoIe3QxjX84V6MlI2IdAT/xImu8gbaCI8tmyfpIrLnPKiR9D\nVFYfGBXuAX7+HgPPSFtrHQONCALxxzlbNpS+zxt9r0MiLgcLyspWxSdmoYGZ6nQP\nRO5Nm/ZVS+u2imPCRzNUZEMa+dlE6kHx0rS0dPiuJ4O7NtPeYDKkoQtNagspsDvh\ncK7CSqAiKMq06UBTxqlTSRkm62eOCtcs3p3OeHu5GRZF1uzTET0ZxYkaPgdrQknx\nozjP5mC7X+45lcCfmcVt94TFNL5HwEUVJpmOgmzILCI8yoDTWzloo+i+fPFsXX4f\nkynhE83mSEcr5VHFYrTY3mQXGmNJ3bCLuc/jq7ysGq69xiKmTlUeXFm+aojcRO5i\nzyShIRJZ0GZfuzDYFDbMV9amA/YQGygLw//zP5ju5SW26dNxlf3MdFQE5JJ86rn9\nMgZ4gcpazHEVUsbZsgkLizRp9imUiH8ymLqAXnfRGlU/LpNSefnvDFTtEIRcpOHc\nbhayG0bk51Bd4mioOXnIsKy4j63nJXA27x5EVVHQ1sYRN8Ny4Fdr2tMAmj2O+X+J\nqX2yy/UX5nSPU492e2CdZ1UhoU0SRFY3bxKHKB7SDbVeav+K5g==\n=Gi5D\n-----END PGP PUBLIC KEY BLOCK-----\nEOF\n\nif [ -z \"$ECS_INIT_URL\" ]; then\n    ARCH=$(uname -m)\n    host_suffix=\"\"\n    if grep -q \"^cn-\" <<<\"$REGION\"; then\n        host_suffix=\".cn\"\n    fi\n    ECS_INIT_URL=\"https://s3.$REGION.amazonaws.com${host_suffix}/amazon-ecs-agent-$REGION/ecs-init-$AGENT_VERSION-$INIT_REV.$AL_NAME.$ARCH.rpm\"\nfi\n\ncurl -fLSs -o \"$WORK_DIR/ecs-init.rpm\" \"$ECS_INIT_URL\"\ncurl -fLSs -o \"$WORK_DIR/ecs-init.rpm.asc\" \"${ECS_INIT_URL}.asc\"\n# bypass gpg check until gpg util is available in minimal AMI\n# we've added a gpg check to our manual release steps until then\ngpg --import \"$WORK_DIR/amazon-ecs-agent.gpg\" || true\ngpg --verify \"$WORK_DIR/ecs-init.rpm.asc\" \"$WORK_DIR/ecs-init.rpm\" || true\n\nsudo yum install -y \"$WORK_DIR/ecs-init.rpm\"\n", "num_lines": 168}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif [ -n \"$AIR_GAPPED\" ]; then\n    echo \"Air-gapped region, exec feature is not supported\"\n    exit 0\nfi\n\nBINARY_PATH=\"/var/lib/ecs/deps/execute-command/bin/${EXEC_SSM_VERSION}\"\nCERTS_PATH=\"/var/lib/ecs/deps/execute-command/certs\"\nARCHITECTURE=\"$(uname -m)\"\n\nhost_suffix=\"\"\nif grep -q \"^cn-\" <<<\"$REGION\"; then\n    host_suffix=\".cn\"\nfi\n\n# Download ssm agent static binaries in BINARY_PATH\nmkdir -p /tmp/ssm-binaries && cd /tmp/ssm-binaries\ncase $ARCHITECTURE in\n'x86_64')\n    curl -fLSs \"https://amazon-ssm-${REGION}.s3.${REGION}.amazonaws.com${host_suffix}/${EXEC_SSM_VERSION}/linux_amd64/amazon-ssm-agent-binaries.tar.gz\" -o amazon-ssm-agent.tar.gz\n    echo \"0100e5f6299274150d9252eb56ace6f3ff797ee2e9c17be1d6b9b8035b75315c ./amazon-ssm-agent.tar.gz\" >./amazon-ssm-agent.tar.gz.sha256\n    sha256sum -c ./amazon-ssm-agent.tar.gz.sha256\n    ;;\n'aarch64')\n    curl -fLSs \"https://amazon-ssm-${REGION}.s3.${REGION}.amazonaws.com${host_suffix}/${EXEC_SSM_VERSION}/linux_arm64/amazon-ssm-agent-binaries.tar.gz\" -o amazon-ssm-agent.tar.gz\n    echo \"2f345a98ed25a9ffeb12355533b242110a502c929dd3abd61c2936000d22f230 ./amazon-ssm-agent.tar.gz\" >./amazon-ssm-agent.tar.gz.sha256\n    sha256sum -c ./amazon-ssm-agent.tar.gz.sha256\n    ;;\nesac\n\nsudo tar -xvf amazon-ssm-agent.tar.gz\nsudo mkdir -p \"${BINARY_PATH}\"\nsudo cp amazon-ssm-agent \"${BINARY_PATH}\"/amazon-ssm-agent\nsudo cp ssm-agent-worker \"${BINARY_PATH}\"/ssm-agent-worker\nsudo cp ssm-session-worker \"${BINARY_PATH}\"/ssm-session-worker\nrm -rf /tmp/ssm-binaries\n\n# Copy certs with 400 permission in CERTS_PATH\nsudo mkdir -p ${CERTS_PATH} && cd ${CERTS_PATH}\nsudo cp /etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem tls-ca-bundle.pem\nsudo chmod 400 tls-ca-bundle.pem\n", "num_lines": 44}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nsudo yum install -y ecs-service-connect-agent\n", "num_lines": 5}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\ncheck_ownership() {\n    path=$1\n    expected_user=$2\n    expected_group=$3\n\n    actual_user=$(stat -c '%U' \"${path}\")\n    if [ \"${actual_user}\" != \"${expected_user}\" ]; then\n        echo \"ERROR: Ownership for ${path}: expected user is ${expected_user}, actual user found was ${actual_user}\"\n        exit 1\n    fi\n\n    actual_group=$(stat -c '%G' \"${path}\")\n    if [ \"${actual_group}\" != \"${expected_group}\" ]; then\n        echo \"ERROR: Ownership for ${path}: expected group is ${expected_group}, actual group found was ${actual_group}\"\n        exit 1\n    fi\n}\n\ncheck_ownership /var/spool/mail root mail\n", "num_lines": 23}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# ECS-optimized AMIs are provisioned with two disks:\n# 1) Root volume at /dev/sda (GP2, 8GB, delete on terminate)\n# 2) Extra EBS volume at /dev/xvdcz just for Docker (GP2, 22GB, delete on terminate)\n#\n# We use docker-storage-setup to configure this additional device properly.\n# By default docker-storage-setup will configure 40% of the device, and will\n# then grow the available space over time up to the maximum in the pool\n# (volume group).  We can tweak the initial space higher if necessary, but\n# cannot set DATA_SIZE=100%FREE, as some space must be reserved for the\n# metadata and root of the pool.\n#\n# VG=docker because that's what the volume group is for.\ncat >>/tmp/docker-storage-setup <<EOF\nDEVS=/dev/xvdcz\nVG=docker\nDATA_SIZE=99%FREE\nAUTO_EXTEND_POOL=yes\nLV_ERROR_WHEN_FULL=yes\nEXTRA_DOCKER_STORAGE_OPTIONS=\"--storage-opt dm.fs=ext4 --storage-opt dm.use_deferred_deletion=true\"\nEOF\nsudo mv /tmp/docker-storage-setup /etc/sysconfig/docker-storage-setup\n", "num_lines": 25}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nsudo sed -i 's,^#releasever=,releasever=,' /etc/yum.conf\n", "num_lines": 5}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nyum update -y\nyum install -y openssh-clients\n", "num_lines": 6}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# TO-DO once Amazon Linux team has released AL2 kernel 5.10 minimal AMIs:\n#   - Disable/remove this script\n#   - Modify AL2 kernel 5.10 variables in generate-release-vars.sh to use SSM parameters of AL2 kernel 5.10 minimal AMIs\nset -ex\n\nif [[ $AMI_TYPE == \"al2kernel5dot10\" || $AMI_TYPE == \"al2kernel5dot10arm\" ]]; then\n    sudo amazon-linux-extras install -y kernel-5.10\n    sudo rpm -e kernel-4.*\nfi\n", "num_lines": 11}
{"repo_name": "amazon-ecs-ami", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# AL2023 uses pam-motd, for docs see:\n# http://www.linux-pam.org/Linux-PAM-html/sag-pam_motd.html\n\n# disable the Amazon Linux motd banner (found at /usr/lib/motd.d/30-banner):\nsudo ln -s /dev/null /etc/motd.d/30-banner\n\n# add the ECS motd banner\ncat <<'EOF' >>/tmp/31-banner\n   ,     #_\n   ~\\_  ####_\n  ~~  \\_#####\\\n  ~~     \\###|\n  ~~       \\#/ ___   Amazon Linux 2023 (ECS Optimized)\n   ~~       V~' '->\n    ~~~         /\n      ~~._.   _/\n         _/ _/\n       _/m/'\n\nFor documentation, visit http://aws.amazon.com/documentation/ecs\nEOF\nsudo mv /tmp/31-banner /etc/motd.d/31-banner\n", "num_lines": 26}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\ncd \"$(dirname \"$(readlink -f \"${BASH_SOURCE[*]}\")\")/../..\"\n\n# see also \".mailmap\" for how email addresses and names are deduplicated\n\n{\n\tcat <<-'EOH'\n\t# This file lists all individuals having contributed content to the repository.\n\t# For how it is generated, see `scripts/docs/generate-authors.sh`.\n\tEOH\n\techo\n\tgit log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf\n} > AUTHORS\n", "num_lines": 16}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\ncd \"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")/..\"\n\n# see also \".mailmap\" for how email addresses and names are deduplicated\n\n{\n\tcat <<-'EOH'\n\t# This file lists all individuals having contributed content to the repository.\n\t# For how it is generated, see `hack/generate-authors.sh`.\n\tEOH\n\techo\n\tgit log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf\n} > AUTHORS\n", "num_lines": 16}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\t# Use then new build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd -arm\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd -arm\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 189}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\tif [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\t\techo 1>&2 \"In the new build system, mkerrors should not be called directly.\"\n\t\techo 1>&2 \"See README.md\"\n\t\texit 1\n\tfi\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capability.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/keyctl.h>\n#include <linux/netlink.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/watchdog.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 579}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Normalize to working directory being build root (up one level from ./scripts)\nROOT=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\ncd \"${ROOT}\"\n\n# Builds the ecs-cli binary from source in the specified destination paths.\nmkdir -p $1\n\n# Versioning stuff. We run the generator to setup the version and then always\n# restore ourselves to a clean state\ncp ecs-cli/modules/version/version.go ecs-cli/modules/version/_version.go\ntrap \"cd \\\"${ROOT}\\\"; mv ecs-cli/modules/version/_version.go ecs-cli/modules/version/version.go\" EXIT SIGHUP SIGINT SIGTERM\n\ncd ./ecs-cli/modules/version/\ngo run gen/version-gen.go\n\ncd \"${ROOT}\"\n\nGOOS=$TARGET_GOOS CGO_ENABLED=0 go build -installsuffix cgo -a -ldflags '-s' -o $1/ecs-cli ./ecs-cli/\n\n", "num_lines": 34}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nDRYRUN=true\n\nAWS_PROFILE=\"\"\nAWS_REGION=\"us-west-2\"\nAMI_ID=\"ami-9ff7e8af\" #amzn-ami-hvm-2015.09.0.x86_64-gp2\nARTIFACT_BUCKET=\"\"\nSOURCE_BUCKET=\"\"\nKEY_NAME=\"\"\nSECURITY_GROUP=\"\"\nINSTANCE_PROFILE=\"\"\n\n\nsource $(dirname \"${0}\")/publish-functions.sh\n\nusage() {\n\techo \"Usage: ${0} -a BUCKET -k SSH_KEY -s SECURITY_GROUP -i IAM_ROLE [OPTIONS]\"\n\techo\n\techo \"This script stages a new version of the Amazon ECS CLI\"\n\techo \"built on a freshly-launched EC2 instance.\"\n\techo \"To run this script, you must have the following resources:\"\n\techo \"* A local AWS profile with permissions for \\\"ec2:run-instances\\\",\"\n\techo \"  \\\"ec2:describe-instances\\\", \\\"s3:PutObject\\\", and \\\"s3:ListObjects\\\"\"\n\techo \"* An S3 bucket for the source\"\n\techo \"* An S3 bucket for the artifact destination\"\n\techo \"* An IAM profile with permissions to read from and write to the\"\n\techo \"  source bucket (\\\"s3:GetObject\\\", \\\"s3:PutObject\\\", and \\\"s3:PutObjectAcl\\\") \"\n\techo \"  and write to the destination S3 bucket (\\\"s3:PutObject\\\" and \"\n\techo \"  \\\"s3:PutObjectAcl\\\")\"\n\techo\n\techo \"Options\"\n\techo \"  -d  true|false      Dryrun (default is true)\"\n\techo \"  -p  PROFILE         AWS CLI Profile (default is none)\"\n\techo \"  -a  BUCKET          Artifact (Destination) AWS S3 Bucket\"\n\techo \"  -t  BUCKET          Source AWS S3 Bucket\"\n\techo \"  -k  SSH_KEY         SSH key name\"\n\techo \"  -s  SECURITY_GROUP  Security group name\"\n\techo \"  -i  IAM_ROLE        IAM Role name\"\n\techo \"  -h                  Display this help message\"\n}\n\nwhile getopts \":d:p:a:t:k:s:i:h\" opt; do\n\tcase ${opt} in\n\t\td)\n\t\t\tif [[ \"${OPTARG}\" = \"false\" ]]; then\n\t\t\t\tDRYRUN=false\n\t\t\tfi\n\t\t\t;;\n\t\tp)\n\t\t\tAWS_PROFILE=\"${OPTARG}\"\n\t\t\t;;\n\t\ta)\n\t\t\tARTIFACT_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\tt)\n\t\t\tSOURCE_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\tk)\n\t\t\tKEY_NAME=\"${OPTARG}\"\n\t\t\t;;\n\t\ts)\n\t\t\tSECURITY_GROUP=\"${OPTARG}\"\n\t\t\t;;\n\t\ti)\n\t\t\tINSTANCE_PROFILE=\"${OPTARG}\"\n\t\t\t;;\n\t\t\\?)\n\t\t\techo \"Invalid option -${OPTARG}\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\t:)\n\t\t\techo \"Option -${OPTARG} requires an argument.\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\th)\n\t\t\tusage\n\t\t\texit 0\n\t\t\t;;\n\tesac\ndone\n\nif [ -z \"${ARTIFACT_BUCKET}\" ] \\\n\t|| [ -z \"${KEY_NAME}\" ] \\\n\t|| [ -z \"${INSTANCE_PROFILE}\" ] \\\n\t|| [ -z \"${SOURCE_BUCKET}\" ]; then\n\tusage\n\texit 1\nfi\n\nDIRTY_WARNING=$(cat <<EOW\n***ERROR***\nYou currently have uncommitted or unstaged changes in your git repository.\nPlease commit, stash, or remove all uncommitted or unstaged files before\nrunning this script.\nEOW\n)\nif [[ -n \"$(git status --porcelain)\" ]]; then\n\techo \"$DIRTY_WARNING\"\n\texit 1\nfi\n\ncommit=$(git rev-parse HEAD)\necho \"Packaging ${commit} for staging...\"\n\ncli_dir=$(pwd)\ntmpdir=$(mktemp -d)\n# Fresh clone to ensure our build doesn't rely on anything outside of vcs\ngit clone --quiet \"${cli_dir}\" \"${tmpdir}\"\ncd \"${tmpdir}\"\ns3_source_prefix=\"s3://${SOURCE_BUCKET}/$(hostname)-${RANDOM}\"\ns3_source_gz=\"${s3_source_prefix}/${commit}.tgz\"\nsource_gz=$(mktemp)\ntar -cz -f \"${source_gz}\" \".\"\n\necho \"Uploading ${source_gz} to ${s3_source_gz}...\"\nS3_ACL_OVERRIDE=\"private\"\ndexec s3_cp \"${source_gz}\" \"${s3_source_gz}\"\nrm \"${source_gz}\"\ncd \"${cli_dir}\"\nrm -rf \"${tmpdir}\"\n\nec2_work_root=\"/var/lib/ec2-stage\"\nec2_gopath=\"${ec2_work_root}/go\"\nec2_build_root=\"${ec2_gopath}/src/github.com/aws\"\n\nuserdata=$(cat << EOU\n#!/bin/bash\n\nmkdir -p ${ec2_work_root}\nexec > >(tee -a ${ec2_work_root}/userdata.log)\n\nyum -y install docker golang git\nservice docker start\naws s3 cp \"${s3_source_gz}\" \"${ec2_work_root}/source.tgz\"\nmkdir -p ${ec2_build_root}\nexport GOPATH=${ec2_gopath}\ncd ${ec2_build_root}\nmkdir -p amazon-ecs-cli\ncd amazon-ecs-cli\ntar -xvz -f \"${ec2_work_root}/source.tgz\"\ngit checkout \"${commit}\"\nscripts/stage.sh -b ${ARTIFACT_BUCKET} -d false\naws s3 cp \"${ec2_work_root}/userdata.log\" \"${s3_source_prefix}/userdata.log\"\nshutdown -hP now\nEOU\n)\n\nencoded_user_data=$(base64 <<< \"${userdata}\")\n\nprofile=\"\"\nif [[ -n \"${AWS_PROFILE}\" ]]; then\n\tprofile=\"--profile=${AWS_PROFILE}\"\nfi\n\necho \"Starting an EC2 instance with the following user-data:\"\necho \"======================================================\"\necho \"${userdata}\"\necho \"======================================================\"\necho\n\nec2_instance_id=$(dexec aws ${profile} \"--region=${AWS_REGION}\" \\\n\tec2 run-instances \\\n\t\"--count=1\" \\\n\t\"--image-id=${AMI_ID}\" \\\n\t\"--key-name=${KEY_NAME}\" \\\n\t\"--security-groups=${SECURITY_GROUP}\" \\\n\t\"--user-data=${encoded_user_data}\" \\\n\t\"--instance-type=t2.medium\" \\\n\t\"--instance-initiated-shutdown-behavior=terminate\" \\\n\t\"--iam-instance-profile=Name=${INSTANCE_PROFILE}\" \\\n\t\"--query=Instances[0].InstanceId\" \\\n\t\"--output=text\" )\n\nif ${DRYRUN} ; then\n\tec2_instance_id=\"dryrun-ec2-instance-id\"\nfi\n\necho \"Waiting for ${ec2_instance_id} to start...\"\ndexec aws ${profile} \"--region=${AWS_REGION}\" \\\n\t\"ec2\" \"wait\" \"instance-running\" \"--instance-ids=${ec2_instance_id}\"\n\necho \"Waiting for ${ec2_instance_id} to terminate...\"\ndexec aws ${profile} \"--region=${AWS_REGION}\" \\\n\t\"ec2\" \"wait\" \"instance-terminated\" \"--instance-ids=${ec2_instance_id}\"\n\nlog=$(mktemp)\n\ndexec s3_cp \"${s3_source_prefix}/userdata.log\" \"${log}\"\ncat \"${log}\"\nrm \"${log}\"\n", "num_lines": 209}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This script generates a file in go with the license contents as a constant\n\nset -e\noutputfile=${1?Must provide an output file}\ninputfile=\"$(<../../../../LICENSE)\"\n\nappendRepoLicense() {\n  repo=$1\n  inputfile+=$'\\n'\"***\"$'\\n'\"$repo\"$'\\n\\n'\n  # Copy LICENSE* files\n  for licensefile in $repo/LICENSE*; do\n    if [ -f $licensefile ]; then\n      inputfile+=\"$(<$licensefile)\"$'\\n'\n    fi;\n  done;\n\n  # Copy COPYING* file\n  if [ -f $repo/COPYING* ]; then\n    inputfile+=\"$(<$repo/COPYING*)\"$'\\n'\n  fi;\n\n  # Copy NOTICE*\n  if [ -f $repo/NOTICE* ]; then\n    inputfile+=\"NOTICE file reads:\"$'\\n'\n    inputfile+=\"$(<$repo/NOTICE*)\"$'\\n'\n  fi;\n}\n\nfor registry in github.com golang.org; do\n  for user in ./../../../vendor/$registry/*; do\n    for repo in $user/*; do\n      appendRepoLicense $repo\n    done;\n  done;\ndone;\n\nfor repo in ./../../../vendor/gopkg.in/*; do\n  appendRepoLicense $repo\ndone;\n\ncat << EOF > \"${outputfile}\"\n// Copyright 2015-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\npackage license\n\nconst License = \\`$inputfile\\`\nEOF\n", "num_lines": 73}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n\nset -e\npackage=${1?Must provide package}\ninterfaces=${2?Must provide interface names}\noutputfile=${3?Must provide an output file}\nPROJECT_VENDOR=\"github.com\\/aws\\/amazon-ecs-cli\\/ecs-cli\\/vendor\\/\"\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\ndata=$(\ncat << EOF\n// Copyright 2015-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n$(mockgen \"$package\" \"$interfaces\")\nEOF\n)\n\n# Explicitly removing the vendor directory from the mock imports\n# https://github.com/golang/mock/issues/30\necho \"$data\" | sed -e \"s/${PROJECT_VENDOR}//\" | goimports > \"${outputfile}\"\n", "num_lines": 48}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nexport VERSION=$(cat $(dirname \"${0}\")/../VERSION)\n\nexport ARTIFACT_TAG_LATEST=\"latest\"\nexport ARTIFACT_TAG_SHA=$(git rev-parse --short=7 HEAD)\nexport ARTIFACT_TAG_VERSION=\"v${VERSION}\"\n\n\ndexec() {\n\tif ${DRYRUN} ; then\n\t\techo \"DRYRUN: ${@}\" 1>&2\n\telse\n\t\techo \"RUNNING: ${@}\" 1>&2\n\t\t\"${@}\"\n\tfi\n}\n\ncheck_md5() {\n\ttest_md5=\"$(md5sum ${1} | sed 's/ .*//')\"\n\texpected_md5=\"$(cat ${2})\"\n\tif [ ! \"${test_md5}\" = \"${expected_md5}\" ]; then\n\t\techo \"Computed md5sum ${test_md5} did not match expected md5sum ${expected_md5}\"\n\t\treturn $(false)\n\tfi\n\treturn $(true)\n}\n\ns3_cp() {\n\tprofile=\"\"\n\tif [[ ! -z \"${AWS_PROFILE}\" ]]; then\n\t\tprofile=\"--profile=${AWS_PROFILE}\"\n\tfi\n\tacl=\"public-read\"\n\tif [[ ! -z \"${S3_ACL_OVERRIDE}\" ]]; then\n\t\tacl=\"${S3_ACL_OVERRIDE}\"\n\tfi\n\techo \"Copying ${1} to ${2}\"\n\taws ${profile} s3 cp \"${1}\" \"${2}\" \"--acl=${acl}\"\n}\n\ns3_pull_push() {\n\tprofile=\"\"\n\tif [[ ! -z \"${AWS_PROFILE}\" ]]; then\n\t\tprofile=\"--profile=${AWS_PROFILE}\"\n\tfi\n\tif [[ ! -z \"${AWS_PROFILE_PUSH}\" ]]; then\n\t\tprofile_push=\"--profile=${AWS_PROFILE_PUSH}\"\n\telse\n\t\tprofile_push=$profile\n\tfi\n\tacl=\"public-read\"\n\tif [[ ! -z \"${S3_ACL_OVERRIDE}\" ]]; then\n\t\tacl=\"${S3_ACL_OVERRIDE}\"\n\tfi\n\techo \"Copying ${1} to ${2}\"\n\t# for partitioned regions, we cannot copy files between buckets directly. Save it locally and copy it over\n\ttmp=$(mktemp)\n\taws ${profile} s3 cp \"${1}\" \"${tmp}\"\n\taws ${profile_push} s3 cp \"${tmp}\" \"${2}\" \"--acl=${acl}\"\n\trm $tmp\n}\n", "num_lines": 76}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\nDRYRUN=true\nALLOW_DIRTY=false\n\nAWS_PROFILE=\"\"\nS3_BUCKET=\"\"\nS3_ACL_OVERRIDE=\"\"\n\nsource $(dirname \"${0}\")/publish-functions.sh\n\nusage() {\n\techo \"Usage: ${0} -b BUCKET [OPTIONS]\"\n\techo\n\techo \"This script is responsible for staging new versions of the Amazon ECS CLI.\"\n\techo \"Push the image (and its md5sum) to S3 with -latest, -VERSION, and -SHA\"\n\techo\n\techo \"Options\"\n\techo \"  -d  true|false  Dryrun (default is true)\"\n\techo \"  -p  PROFILE     AWS CLI Profile (default is none)\"\n\techo \"  -b  BUCKET      AWS S3 Bucket\"\n\techo \"  -a  ACL         AWS S3 Object Canned ACL (default is public-read)\"\n\techo \"  -i  true|false  Allow dirty builds\"\n\techo \"  -h              Display this help message\"\n}\n\nwhile getopts \":d:p:b:a:i:h\" opt; do\n\tcase ${opt} in\n\t\td)\n\t\t\tif [[ \"${OPTARG}\" == \"false\" ]]; then\n\t\t\t\tDRYRUN=false\n\t\t\tfi\n\t\t\t;;\n\t\tp)\n\t\t\tAWS_PROFILE=\"${OPTARG}\"\n\t\t\t;;\n\t\tb)\n\t\t\tS3_BUCKET=\"${OPTARG}\"\n\t\t\t;;\n\t\ta)\n\t\t\tS3_ACL_OVERRIDE=\"${OPTARG}\"\n\t\t\t;;\n\t\ti)\n\t\t\tif [[ \"${OPTARG}\" == \"true\" ]]; then\n\t\t\t\tALLOW_DIRTY=true\n\t\t\tfi\n\t\t\t;;\n\t\t\\?)\n\t\t\techo \"Invalid option -${OPTARG}\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\t:)\n\t\t\techo \"Option -${OPTARG} requires an argument.\" >&2\n\t\t\tusage\n\t\t\texit 1\n\t\t\t;;\n\t\th)\n\t\t\tusage\n\t\t\texit 0\n\t\t\t;;\n\tesac\ndone\n\nif [ -z \"${S3_BUCKET}\" ]; then\n\tusage\n\texit 1\nfi\n\nDIRTY_WARNING=$(cat <<EOW\n***WARNING***\nYou currently have uncommitted or unstaged changes in your git repository.\nThe release build will not include those and the result may behave differently\nthan expected due to that. Please commit, stash, or remove all uncommitted or\nunstaged files before creating a release build.\nEOW\n)\n[ ! -z \"$(git status --porcelain)\" ] && echo \"$DIRTY_WARNING\"\n\nCWD=$(pwd)\nclean_directory=\"\"\nif ! ${ALLOW_DIRTY}; then\n\tclean_directory=$(mktemp -d)\n\techo \"Cloning to a clean directory ${clean_directory}\"\n\tgit clone --quiet \"${CWD}\" \"${clean_directory}\"\n\tcd \"${clean_directory}\"\n\texport ECS_RELEASE=\"cleanbuild\"\nfi\n\nmake docker-build\n\npublish_binary() {\n\tplatform=$1\n\textension=$2\n\tartifact=\"bin/${platform}/ecs-cli${extension}\"\n\tartifact_md5=\"$(mktemp)\"\n\tmd5sum \"${artifact}\" | sed 's/ .*//' > \"${artifact_md5}\"\n\n\tfor tag in ${ARTIFACT_TAG_VERSION} ${ARTIFACT_TAG_SHA} ${ARTIFACT_TAG_LATEST}; do\n\t\tkey_name=\"ecs-cli-${platform}-${tag}${extension}\"\n\t\techo \"Publishing as ${key_name} with md5sum $(cat ${artifact_md5})\"\n\t\tdexec s3_cp \"${artifact}\" \"s3://${S3_BUCKET}/${key_name}\"\n\t\tdexec s3_cp \"${artifact_md5}\" \"s3://${S3_BUCKET}/ecs-cli-${platform}-${tag}.md5\"\n\tdone\n\n\trm \"${artifact_md5}\"\n}\n\npublish_binary \"linux-amd64\" \"\"\npublish_binary \"darwin-amd64\" \"\"\npublish_binary \"windows-amd64\" \".exe\"\n\ncd \"${CWD}\"\n\nif [[ -n \"${clean_directory}\" ]]; then\n\techo \"Removing ${clean_directory}\"\n\trm -rf \"${clean_directory}\"\nfi\n", "num_lines": 134}
{"repo_name": "amazon-ecs-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# usage: source these functions and set the s3 endpoint to\n# either s3.<region>.amazonaws.com or s3.<region>.amazonaws.com.cn\n\n# usage: retry <command>\nfunction retry {\n    local delay=900 # 60 * 15 = 15 minutes\n    while true; do\n        \"$@\" && break\n        sleep $delay\n    done\n}\n\nfunction failBadPGPSignature {\n    echo \"PGP Signature failed. retrying in $delay s\" >&2\n    return 1\n}\n\nfunction failBadConnection {\n    echo \"Couldn't download artifact $bn. Retrying in $delay s\" >&2\n    return 1\n}\n\n#usage: verifyAll <manifestFile>\nfunction verifyAll {\n    for artifact in `cat $1`\n    do\n        bn=\"$(basename $artifact)\"\n        echo \"Downloading artifact $bn from endpoint https://$S3_ENDPOINT/$BUCKET\"\n        wget -q https://$S3_ENDPOINT/$BUCKET/$bn || failBadConnection || return 1\n        echo \"Downloading artifact signature $bn.asc from $S3_ENDPOINT_SIGNATURES\"\n        wget -q -T 300 https://$S3_ENDPOINT_SIGNATURES/$BUCKET/$bn.asc\n        echo \"verifying signature...\"\n        gpg --verify $bn.asc $bn || failBadPGPSignature || return 1\n    done\n}\n\nfunction setupGPG {\n    gpg --version\n    mkdir ~/.gnupg\n    echo \"disable-ipv6\" >> ~/.gnupg/dirmngr.conf\n    gpg --keyserver hkp://pool.sks-keyservers.net --recv BCE9D9A42D51784F || exit 1\n}\n\nsetupGPG\nretry verifyAll $1\n", "num_lines": 47}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# Usage:\n# build_binary.sh  <relative-path-to-binary-destination-from-build-root>\nset -e\n\n# Normalize to working directory being build root (up one level from ./scripts)\nROOT=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\n\ncd \"${ROOT}\"\nBINARY_DESTINATION_DIR=$1\nmkdir -p ${BINARY_DESTINATION_DIR}\n\n# Builds the handler binary from source in the specified destination paths\nGOOS=$TARGET_GOOS CGO_ENABLED=0 go build -installsuffix cgo -a -ldflags '-s' -o ${BINARY_DESTINATION_DIR}/cluster-state-service-canary ./\n", "num_lines": 28}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# This script is meant for use inside the build dockerfile\n# (scripts/dockerfiles/Dockerfile.build) and makes assumptions related to that.\n# It should not be run on its own.\n\necho \"Starting clean build\"\n\ncd /src/aws/amazon-ecs-cluster-state-service\nDIRTY_WARNING=$(cat <<EOW\n***WARNING***\nYou currently have uncommitted or unstaged changes in your git repository.\nThe release build will not include those and the result may behave differently\nthan expected due to that. Please commit, stash, or remove all uncommitted or\nunstaged files before creating a release build.\nEOW\n)\n[ ! -z \"$(git status --porcelain)\" ] && echo \"$DIRTY_WARNING\"\n\n# Fresh clone to ensure our build doesn't rely on anything outside of vcs\ngit clone --quiet /src/aws/amazon-ecs-cluster-state-service /go/src/github.com/aws/amazon-ecs-cluster-state-service\n\ncd /go/src/github.com/aws/amazon-ecs-cluster-state-service/canary\nexec ./scripts/build_binary.sh /out\n", "num_lines": 37}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# Usage:\n# build_binary.sh  <relative-path-to-binary-destination-from-build-root>\nset -e\n\n# Normalize to working directory being build root (up one level from ./scripts)\nROOT=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/..\" && pwd )\n\ncd \"${ROOT}\"\nBINARY_DESTINATION_DIR=$1\nmkdir -p ${BINARY_DESTINATION_DIR}\n\n# Versioning: run the generator to setup the version and then always\n# restore ourselves to a clean state\ncp versioning/version.go versioning/_version.go\ntrap \"mv versioning/_version.go versioning/version.go\" EXIT SIGHUP SIGINT SIGTERM\n\ncd versioning\ngo run gen/version-gen.go\n\ncd \"${ROOT}\"\n\n# Builds the handler binary from source in the specified destination paths\nGOOS=$TARGET_GOOS CGO_ENABLED=0 go build -installsuffix cgo -a -ldflags '-s' -o ${BINARY_DESTINATION_DIR}/cluster-state-service ./\ncp \"${ROOT}/LICENSE\"  ${BINARY_DESTINATION_DIR}/\n", "num_lines": 39}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This script generates a file in go with the license contents as a constant\n\n# Set language to C to make sorting consistent among different environments.\nexport LANG=C\n\nset -e\noutputfile=${1?Must provide an output file}\ninputfile=\"$(<../LICENSE)\"\n\nappendRepoLicense() {\n  repo=$1\n  echo \"Adding license for ${repo}\"\n  inputfile+=$'\\n'\"***\"$'\\n'\"$repo\"$'\\n\\n'\n  # Copy LICENSE* files\n  for licensefile in $repo/LICENSE*; do\n    if [ -f $licensefile ]; then\n      inputfile+=\"$(<$licensefile)\"$'\\n'\n    fi;\n  done;\n  # Copy COPYING* file\n  if [ -f $repo/COPYING* ]; then\n    inputfile+=\"$(<$repo/COPYING*)\"$'\\n'\n  fi;\n}\n\nfor registry in github.com golang.org; do\n  for user in ./../vendor/$registry/*; do\n    for repo in $user/*; do\n      if [[ $repo == *\"go-buffruneio\"* ]]; then\n        # nop, since we add this explicitliy\n\t:\n      else\n        appendRepoLicense $repo\n      fi\n    done;\n  done;\ndone;\n\nfor repo in ./../vendor/gopkg.in/* ./../vendor/google.golang.org/*; do\n  appendRepoLicense $repo\ndone;\n\ninputfile+=\"\n***\n./../vendor/github.com/pelletier/go-buffruneio\n\nCopyright (c) 2016 Thomas Pelletier\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \\\"Software\\\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \\\"AS IS\\\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\nFOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\nCOPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\nIN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\nCONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n\"\n\ntr -d '\\r' > \"${outputfile}\" << EOF\n// Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\npackage licenses\n\nconst License = \\`$inputfile\\`\nEOF\n", "num_lines": 100}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n\nset -e\npackage=${1?Must provide package}\ninterfaces=${2?Must provide interface names}\noutputfile=${3?Must provide an output file}\nPROJECT_VENDOR=\"github.com\\/aws\\/amazon-ecs-cluster-state-service\\/vendor\\/\"\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\nyear=\"$(date '+%Y')\"\ndata=$(\ncat << EOF\n// Copyright ${year} Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n$(mockgen \"${package}\" \"${interfaces}\")\nEOF\n)\n\nmkdir -p $(dirname ${outputfile})\n\n# Explicitly removing the vendor directory from the mock imports\n# https://github.com/golang/mock/issues/30\necho \"$data\" | sed -e \"s/${PROJECT_VENDOR}//\" | goimports > \"${outputfile}\"\n", "num_lines": 51}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This script generates a file in go with the license contents as a constant\n\nset -e\n\nif [ -z \"$1\" ]\n  then\n    echo \"Must provide at least one input directory\"\n    exit 1\nfi\n\nappendLicense(){\n  echo \"Slapping copyright notice on ${outputfile}\"\n  outputfile=${1?Must provide an output file}\n\n  echo \"// Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \\\"License\\\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \\\"license\\\" file accompanying this file. This file is distributed\n// on an \\\"AS IS\\\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n$(cat ${outputfile})\" > ${outputfile}\n}\nfor input in \"$@\"\ndo\n  if [ -d ${input} ] ; then\n    for file in `find ${input} -name \"*.go\"`; do\n      if ! grep -q \"// Copyright\" ${file} ; then\n        appendLicense ${file}\n      fi\n    done\n  else\n    if ! grep -q \"// Copyright\" ${input} ; then\n      appendLicense ${input}\n    fi\n  fi\ndone\n", "num_lines": 58}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file 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.\n\n# Usage instructions - From one level above the scripts directory, running the following command generates the binary into <path-to-binary-destination>\n#      . ./scripts/v1/generate_swagger_models.sh\n\n# Normalize to working directory being build root (up one level from ./scripts)\nROOT=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/../..\" && pwd )\n\nGENERATED_DIR=\"${ROOT}/swagger/v1/generated\"\ncd \"${GENERATED_DIR}\"\n\n# Remove models directory if it already exists\nREMOVE_MODELS=\"rm -rf ./models ||:\"\n${REMOVE_MODELS}\n\n# Remove client directory if it already exists\nREMOVE_CLIENT=\"rm -rf ./client ||:\"\n${REMOVE_CLIENT}\n\n# Generate models and client\nSWAGGER_GENERATE=\"swagger generate client -f ../swagger.json -A ecs_css\"\n${SWAGGER_GENERATE}\n\ncd ${ROOT}\n", "num_lines": 32}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash \n\nset -eu -o pipefail\ndir=$(git rev-parse --show-toplevel)\nscratch=$(mktemp -d -t tmp.XXXXXXXXXX)\n\nfunction finish {\n  rm -rf \"$scratch\"\n}\ntrap finish EXIT SIGHUP SIGINT SIGTERM\n\ncd \"$scratch\"\ngit clone https://github.com/json-schema-org/JSON-Schema-Test-Suite Suite\ncp -r Suite/tests/draft4/* \"$dir/fixtures/jsonschema_suite\"\ncp -a Suite/remotes \"$dir/fixtures/jsonschema_suite\"\n", "num_lines": 16}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nreference_ref=${1:-master}\nreference_git=${2:-.}\n\nif ! `hash benchstat 2>/dev/null`; then\n    echo \"Installing benchstat\"\n    go get golang.org/x/perf/cmd/benchstat\n    go install golang.org/x/perf/cmd/benchstat\nfi\n\ntempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX`\nref_tempdir=\"${tempdir}/ref\"\nref_benchmark=\"${ref_tempdir}/benchmark-`echo -n ${reference_ref}|tr -s '/' '-'`.txt\"\nlocal_benchmark=\"`pwd`/benchmark-local.txt\"\n\necho \"=== ${reference_ref} (${ref_tempdir})\"\ngit clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null\npushd ${ref_tempdir} >/dev/null\ngit checkout ${reference_ref} >/dev/null 2>/dev/null\ngo test -bench=. -benchmem | tee ${ref_benchmark}\npopd >/dev/null\n\necho \"\"\necho \"=== local\"\ngo test -bench=. -benchmem  | tee ${local_benchmark}\n\necho \"\"\necho \"=== diff\"\nbenchstat -delta-test=none ${ref_benchmark} ${local_benchmark}", "num_lines": 32}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# fail out of the script if anything here fails\nset -e\n\n# set the path to the present working directory\nexport GOPATH=`pwd`\n\nfunction git_clone() {\n  path=$1\n  branch=$2\n  version=$3\n  if [ ! -d \"src/$path\" ]; then\n    mkdir -p src/$path\n    git clone https://$path.git src/$path\n  fi\n  pushd src/$path\n  git checkout \"$branch\"\n  git reset --hard \"$version\"\n  popd\n}\n\n# Remove potential previous runs\nrm -rf src test_program_bin toml-test\n\n# Run go vet\ngo vet ./...\n\ngo get github.com/pelletier/go-buffruneio\ngo get github.com/davecgh/go-spew/spew\ngo get gopkg.in/yaml.v2\ngo get github.com/BurntSushi/toml\n\n# get code for BurntSushi TOML validation\n# pinning all to 'HEAD' for version 0.3.x work (TODO: pin to commit hash when tests stabilize)\ngit_clone github.com/BurntSushi/toml master HEAD\ngit_clone github.com/BurntSushi/toml-test master HEAD #was: 0.2.0 HEAD\n\n# build the BurntSushi test application\ngo build -o toml-test github.com/BurntSushi/toml-test\n\n# vendorize the current lib for testing\n# NOTE: this basically mocks an install without having to go back out to github for code\nmkdir -p src/github.com/pelletier/go-toml/cmd\nmkdir -p src/github.com/pelletier/go-toml/query\ncp *.go *.toml src/github.com/pelletier/go-toml\ncp -R cmd/* src/github.com/pelletier/go-toml/cmd\ncp -R query/* src/github.com/pelletier/go-toml/query\ngo build -o test_program_bin src/github.com/pelletier/go-toml/cmd/test_program.go\n\n# Run basic unit tests\ngo test github.com/pelletier/go-toml -covermode=count -coverprofile=coverage.out\ngo test github.com/pelletier/go-toml/cmd/tomljson\ngo test github.com/pelletier/go-toml/query\n\n# run the entire BurntSushi test suite\nif [[ $# -eq 0 ]] ; then\n  echo \"Running all BurntSushi tests\"\n  ./toml-test ./test_program_bin | tee test_out\nelse\n  # run a specific test\n  test=$1\n  test_path='src/github.com/BurntSushi/toml-test/tests'\n  valid_test=\"$test_path/valid/$test\"\n  invalid_test=\"$test_path/invalid/$test\"\n\n  if [ -e \"$valid_test.toml\" ]; then\n    echo \"Valid Test TOML for $test:\"\n    echo \"====\"\n    cat \"$valid_test.toml\"\n\n    echo \"Valid Test JSON for $test:\"\n    echo \"====\"\n    cat \"$valid_test.json\"\n\n    echo \"Go-TOML Output for $test:\"\n    echo \"====\"\n    cat \"$valid_test.toml\" | ./test_program_bin\n  fi\n\n  if [ -e \"$invalid_test.toml\" ]; then\n    echo \"Invalid Test TOML for $test:\"\n    echo \"====\"\n    cat \"$invalid_test.toml\"\n\n    echo \"Go-TOML Output for $test:\"\n    echo \"====\"\n    echo \"go-toml Output:\"\n    cat \"$invalid_test.toml\" | ./test_program_bin\n  fi\nfi\n", "num_lines": 91}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The unix package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl /usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_linux.pl /usr/include/asm/unistd_32.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_amd64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_ppc64)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_ppc64le)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_s390x)\n\tGOOSARCH_in=syscall_linux_s390x.go\n\tunistd_h=/usr/include/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\t# Let the type of C char be signed to make the bare sys\n\t# API more consistent between platforms.\n\t# This is a deliberate departure from the way the syscall\n\t# package generates its version of the types file.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go\";\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go >>ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 293}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" -eq \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <linux/if.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/filter.h>\n#include <linux/netlink.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 484}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "amazon-ecs-cluster-state-service", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nworkdir=.cover\nprofile=\"$workdir/cover.out\"\nmode=set\nend2endtest=\"google.golang.org/grpc/test\"\n\ngenerate_cover_data() {\n    rm -rf \"$workdir\"\n    mkdir \"$workdir\"\n\n    for pkg in \"$@\"; do\n        if [ $pkg == \"google.golang.org/grpc\" -o $pkg == \"google.golang.org/grpc/transport\" -o $pkg == \"google.golang.org/grpc/metadata\" -o $pkg == \"google.golang.org/grpc/credentials\" ]\n            then\n                f=\"$workdir/$(echo $pkg | tr / -)\"\n                go test -covermode=\"$mode\" -coverprofile=\"$f.cover\" \"$pkg\"\n                go test -covermode=\"$mode\" -coverpkg \"$pkg\" -coverprofile=\"$f.e2e.cover\" \"$end2endtest\"\n        fi\n    done\n\n    echo \"mode: $mode\" >\"$profile\"\n    grep -h -v \"^mode:\" \"$workdir\"/*.cover >>\"$profile\"\n}\n\nshow_cover_report() {\n    go tool cover -${1}=\"$profile\"\n}\n\npush_to_coveralls() {\n    goveralls -coverprofile=\"$profile\"\n}\n\ngenerate_cover_data $(go list ./...)\nshow_cover_report func\ncase \"$1\" in\n\"\")\n    ;;\n--html)\n    show_cover_report html ;;\n--coveralls)\n    push_to_coveralls ;;\n*)\n    echo >&2 \"error: invalid option: $1\" ;;\nesac\nrm -rf \"$workdir\"\n", "num_lines": 48}
{"repo_name": "amazon-ecs-cni-plugins", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#\thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n# This script generates a file in go with the license contents as a constant\n\n# Set language to C to make sorting consistent among different environments.\nexport LANG=C\n\nvendor_relative_path=\"./../../vendor/\"\n\nset -e\noutputfile=${1?Must provide an output file}\ninputfile=\"$(<../../LICENSE)\"\n\nappendRepoLicense() {\n  repo=$1\n\n  sanitized_repo=\"${repo/${vendor_relative_path}/}\"\n  echo \"Adding license for ${sanitized_repo}\"\n  inputfile+=$'\\n'\"***\"$'\\n'\"${sanitized_repo}\"$'\\n\\n'\n  # Copy LICENSE* files\n  for licensefile in $repo/LICENSE*; do\n    if [ -f $licensefile ]; then\n      inputfile+=\"$(<$licensefile)\"$'\\n'\n    fi\n  done\n  # Copy COPYING* file\n  if [ -f $repo/COPYING* ]; then\n    inputfile+=\"$(<$repo/COPYING*)\"$'\\n'\n  fi\n}\n\nfor registry in github.com golang.org; do\n  for user in ${vendor_relative_path}$registry/*; do\n    for repo in $user/*; do\n      if [[ $repo == *\"go-buffruneio\"* ]]; then\n        # nop, since we add this explicitliy\n\t:\n      else\n        appendRepoLicense $repo\n      fi\n    done\n  done\ndone\n\ntr -d '\\r' > \"${outputfile}\" << EOF\n// Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// Code generated by licenses.sh. DO NOT EDIT.\n\npackage licenses\n\nconst License = \\`$inputfile\\`\nEOF\n", "num_lines": 77}
{"repo_name": "amazon-ecs-cni-plugins", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The unix package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl /usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_linux.pl /usr/include/asm/unistd_32.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_amd64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_ppc64)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_ppc64le)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_s390x)\n\tGOOSARCH_in=syscall_linux_s390x.go\n\tunistd_h=/usr/include/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\t# Let the type of C char be signed to make the bare sys\n\t# API more consistent between platforms.\n\t# This is a deliberate departure from the way the syscall\n\t# package generates its version of the types file.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go\";\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go >>ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 293}
{"repo_name": "amazon-ecs-cni-plugins", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" -eq \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <linux/if.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/filter.h>\n#include <linux/netlink.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 484}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\ncd \"$(dirname \"$(readlink -f \"$BASH_SOURCE\")\")/..\"\n\n# see also \".mailmap\" for how email addresses and names are deduplicated\n\n{\n\tcat <<-'EOH'\n\t# This file lists all individuals having contributed content to the repository.\n\t# For how it is generated, see `hack/generate-authors.sh`.\n\tEOH\n\techo\n\tgit log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf\n} > AUTHORS\n", "num_lines": 16}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\t# Use then new build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl /usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 180}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" -eq \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\tif [[ \"$GOLANG_SYS_BUILD\" -ne \"docker\" ]]; then\n\t\techo 1>&2 \"In the new build system, mkerrors should not be called directly.\"\n\t\techo 1>&2 \"See README.md\"\n\t\texit 1\n\tfi\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" -eq \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/keyctl.h>\n#include <linux/netlink.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 549}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\ncat > $(pwd)/logger.go <<EOF\n// Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// GENERATED FILE, DO NOT MODIFY BY HAND\n//go:generate bundle_log_config.sh\n\npackage config\n\n// Logger holds the bundled log configuration for seelog\nfunc Logger() string {\n\treturn \\`\n$(cat ../../seelog.xml)\n\\`\n}\nEOF\n", "num_lines": 42}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e # exit on failure\n\nfail() {\n    echo \"\"\n    echo -e \"\\033[0;31mInstallation Failed\\033[0m\" # print it in red\n    exit 1\n}\n\ncheck-option-value() {\n    if [ \"${2:0:2}\" == \"--\" ]; then\n        echo \"Option $1 was passed an invalid value: $2. Perhaps you passed in an empty env var?\"\n        fail\n    fi\n}\n\nusage() {\n    echo \"$(basename \"$0\") [--help] --region REGION --activation-code CODE --activation-id ID [--cluster CLUSTER] [--enable-gpu] [--docker-install-source all|docker|distro|none] [--ecs-version VERSION] [--ecs-endpoint ENDPOINT] [--skip-registration] [--no-start]\n\n  --help\n        (optional) display this help message.\n  --region string\n        (required) this must match the region of your ECS cluster and SSM activation.\n  --activation-id string\n        (required) activation id from the create activation command. Not required if --skip-registration is specified.\n  --activation-code string\n        (required) activation code from the create activation command. Not required if --skip-registration is specified.\n  --cluster string\n        (optional) pass the cluster name that ECS agent will connect too. By default its value is 'default'.\n  --enable-gpu\n        (optional) if this flag is provided, GPU support for ECS will be enabled.\n  --docker-install-source\n        (optional) Source of docker installation. Possible values are 'all, docker, distro, none'. Defaults to 'all'.\n  --ecs-version string\n        (optional) Version of the ECS agent rpm/deb package to use. If not specified, default to latest.\n  --skip-registration\n        (optional) if this is enabled, SSM agent install and instance registration with SSM is skipped.\n  --certs-file\n        (optional) TLS certs for execute command feature. Defaults to searching for certs in known possible locations.\n  --no-start\n        (optional) if this flag is provided, SSM agent, docker and ECS agent will not be started by the script despite being installed.\"\n}\n\n# required:\nREGION=\"\"\nACTIVATION_CODE=\"\"\nACTIVATION_ID=\"\"\n# optional:\nSKIP_REGISTRATION=false\nECS_CLUSTER=\"\"\nDOCKER_SOURCE=\"\"\nECS_VERSION=\"\"\nDEB_URL=\"\"\nRPM_URL=\"\"\nECS_ENDPOINT=\"\"\nCERTS_FILE=\"\"\n# Whether to check signature for the downloaded amazon-ecs-init package. true unless --skip-gpg-check\n# specified. --skip-gpg-check is mostly for testing purpose (so that we can test a custom build of ecs init package\n# without having to sign it).\nCHECK_SIG=true\nNO_START=false\nwhile :; do\n    case \"$1\" in\n    --help)\n        usage\n        exit 0\n        ;;\n    --region)\n        check-option-value \"$1\" \"$2\"\n        REGION=\"$2\"\n        shift 2\n        ;;\n    --cluster)\n        check-option-value \"$1\" \"$2\"\n        ECS_CLUSTER=\"$2\"\n        shift 2\n        ;;\n    --activation-code)\n        check-option-value \"$1\" \"$2\"\n        ACTIVATION_CODE=\"$2\"\n        shift 2\n        ;;\n    --activation-id)\n        check-option-value \"$1\" \"$2\"\n        ACTIVATION_ID=\"$2\"\n        shift 2\n        ;;\n    --docker-install-source)\n        check-option-value \"$1\" \"$2\"\n        DOCKER_SOURCE=\"$2\"\n        shift 2\n        ;;\n    --ecs-version)\n        check-option-value \"$1\" \"$2\"\n        ECS_VERSION=\"$2\"\n        shift 2\n        ;;\n    --deb-url)\n        check-option-value \"$1\" \"$2\"\n        DEB_URL=\"$2\"\n        shift 2\n        ;;\n    --rpm-url)\n        check-option-value \"$1\" \"$2\"\n        RPM_URL=\"$2\"\n        shift 2\n        ;;\n    --ecs-endpoint)\n        check-option-value \"$1\" \"$2\"\n        ECS_ENDPOINT=\"$2\"\n        shift 2\n        ;;\n    --certs-file)\n        check-option-value \"$1\" \"$2\"\n        CERTS_FILE=\"$2\"\n        shift 2\n        ;;\n    --skip-registration)\n        SKIP_REGISTRATION=true\n        shift 1\n        ;;\n    --enable-gpu)\n        GPU_ENABLED=true\n        shift 1\n        ;;\n    --no-start)\n        NO_START=true\n        shift 1\n        ;;\n    --skip-gpg-check)\n        CHECK_SIG=false\n        shift 1\n        ;;\n    *)\n        [ -z \"$1\" ] && break\n        echo \"invalid option: [$1]\"\n        fail\n        ;;\n    esac\ndone\n\n# check if the script is run with root or sudo\nif [ $(id -u) -ne 0 ]; then\n    echo \"Please run as root.\"\n    fail\nfi\n\n# check if system is using systemd\n# from https://www.freedesktop.org/software/systemd/man/sd_booted.html\nif [ ! -d /run/systemd/system ]; then\n    echo \"The install script currently supports only systemd.\"\n    fail\nfi\n\nSSM_SERVICE_NAME=\"amazon-ssm-agent\"\nSSM_BIN_NAME=\"amazon-ssm-agent\"\nif systemctl is-enabled snap.amazon-ssm-agent.amazon-ssm-agent.service &>/dev/null; then\n    echo \"Detected SSM agent installed via snap.\"\n    SSM_SERVICE_NAME=\"snap.amazon-ssm-agent.amazon-ssm-agent.service\"\n    SSM_BIN_NAME=\"/snap/amazon-ssm-agent/current/amazon-ssm-agent\"\nfi\nSSM_MANAGED_INSTANCE_ID=\"\"\n\nif [ -z \"$REGION\" ]; then\n    echo \"--region is required\"\n    fail\nfi\n# If activation code is absent and skip activation flag is present, set flag to skip ssm registration\n# if both activation code is present\nif $SKIP_REGISTRATION; then\n    echo \"Skipping ssm registration.\"\n    if ! systemctl is-enabled $SSM_SERVICE_NAME &>/dev/null; then\n        echo \"--skip-registration flag specified but the SSM agent service is not running.\"\n        echo \"a running SSM agent service is required for ECS Anywhere.\"\n        fail\n    fi\nelse\n    if [[ -z $ACTIVATION_ID || -z $ACTIVATION_CODE ]]; then\n        echo \"Both --activation-id and --activation-code are required unless --skip-registration is specified.\"\n        fail\n    fi\nfi\nif [ -z \"$ECS_CLUSTER\" ]; then\n    ECS_CLUSTER=\"default\"\nfi\nif [ -z \"$DOCKER_SOURCE\" ]; then\n    DOCKER_SOURCE=\"all\"\nfi\nif [ -z \"$ECS_VERSION\" ]; then\n    ECS_VERSION=\"latest\"\nfi\n\nARCH=$(uname -m)\nif [ \"$ARCH\" == \"x86_64\" ]; then\n    ARCH_ALT=\"amd64\"\nelif [ \"$ARCH\" == \"aarch64\" ]; then\n    ARCH_ALT=\"arm64\"\nelse\n    echo \"Unsupported architecture: $ARCH\"\n    fail\nfi\n\nS3_BUCKET=\"amazon-ecs-agent-$REGION\"\nRPM_PKG_NAME=\"amazon-ecs-init-$ECS_VERSION.$ARCH.rpm\"\nDEB_PKG_NAME=\"amazon-ecs-init-$ECS_VERSION.$ARCH_ALT.deb\"\nS3_URL_SUFFIX=\"\"\nif grep -q \"^cn-\" <<< \"$REGION\"; then\n    S3_URL_SUFFIX=\".cn\"\nfi\nS3_URL=\"https://s3.${REGION}.amazonaws.com${S3_URL_SUFFIX}\"\nSSM_S3_BUCKET=\"amazon-ssm-$REGION\"\n\nif [ -z \"$RPM_URL\" ]; then\n    RPM_URL=\"${S3_URL}/${S3_BUCKET}/$RPM_PKG_NAME\"\nfi\nif [ -z \"$DEB_URL\" ]; then\n    DEB_URL=\"${S3_URL}/${S3_BUCKET}/$DEB_PKG_NAME\"\nfi\n\n# source /etc/os-release to get the VERSION_ID and ID fields\nsource /etc/os-release\necho \"Running ECS install script on $ID $VERSION_ID\"\necho \"###\"\necho \"\"\nDISTRO=\"\"\nif echo \"$ID\" | grep ubuntu; then\n    DISTRO=\"ubuntu\"\nelif echo \"$ID\" | grep debian; then\n    DISTRO=\"debian\"\nelif echo \"$ID\" | grep fedora; then\n    DISTRO=\"fedora\"\nelif echo \"$ID\" | grep centos; then\n    DISTRO=\"centos\"\nelif echo \"$ID\" | grep rhel; then\n    DISTRO=\"rhel\"\nelif [[ \"$ID\" == \"amzn\" && \"$VERSION_ID\" == \"2\" ]]; then\n    DISTRO=\"al2\"\nfi\n\nif [ \"$DISTRO\" == \"rhel\" ]; then\n    if [ ! \"$DOCKER_SOURCE\" == \"none\" ]; then\n        echo \"Docker install is not supported on RHEL. Please install yourself and rerun with --docker-install-source none\"\n        fail\n    fi\nfi\n\nok() {\n    echo \"\"\n    echo \"# ok\"\n    echo \"##########################\"\n    echo \"\"\n}\n\ntry() {\n    local action=$*\n    echo \"\"\n    echo \"##########################\"\n    echo \"# Trying to $action ... \"\n    echo \"\"\n}\n\nPKG_MANAGER=\"\"\nif [ -x \"$(command -v dnf)\" ]; then\n    PKG_MANAGER=\"dnf\"\n    dnf install -y jq\nelif [ -x \"$(command -v yum)\" ]; then\n    PKG_MANAGER=\"yum\"\n    if [ \"$DISTRO\" != \"al2\" ]; then\n        yum install epel-release -y\n    fi\n    yum install -y jq\nelif [ -x \"$(command -v apt)\" ]; then\n    PKG_MANAGER=\"apt\"\n    try \"Update apt repos\"\n    apt update -y\n    apt-get install -y curl jq\n    ok\nelif [ -x \"$(command -v zypper)\" ]; then\n    PKG_MANAGER=\"zypper\"\n    zypper install -y jq\nelse\n    echo \"Unsupported package manager. Could not find dnf, yum, or apt.\"\n    fail\nfi\n\nget-ssm-managed-instance-id() {\n    SSM_REGISTRATION_FILE='/var/lib/amazon/ssm/Vault/Store/RegistrationKey'\n    if [ -f ${SSM_REGISTRATION_FILE} ]; then\n        SSM_MANAGED_INSTANCE_ID=$(jq -r \".instanceID\" $SSM_REGISTRATION_FILE)\n    fi\n}\n\ncurl-helper() {\n    if ! curl -o \"$1\" \"$2\" -fSs; then\n        echo \"Failed to download $2\"\n        fail\n    fi\n}\n\nregister-ssm-agent() {\n    try \"Register SSM agent\"\n    get-ssm-managed-instance-id\n    if [ -z \"$SSM_MANAGED_INSTANCE_ID\" ]; then\n        systemctl stop \"$SSM_SERVICE_NAME\" &>/dev/null\n        $SSM_BIN_NAME -register -code \"$ACTIVATION_CODE\" -id \"$ACTIVATION_ID\" -region \"$REGION\"\n        systemctl enable \"$SSM_SERVICE_NAME\"\n        if ! $NO_START; then\n            systemctl start \"$SSM_SERVICE_NAME\"\n        else\n            echo \"Skip starting ssm agent because --no-start is specified.\"\n        fi\n        echo \"SSM agent has been registered.\"\n    else\n        echo \"SSM agent is already registered. Managed instance ID: $SSM_MANAGED_INSTANCE_ID\"\n    fi\n    ok\n}\n\ninstall-ssm-agent() {\n    try \"install ssm agent\"\n    if systemctl is-enabled $SSM_SERVICE_NAME &>/dev/null; then\n        echo \"SSM agent is already installed.\"\n    else\n        local dir\n        dir=\"$(mktemp -d)\"\n        local SSM_DEB_URL=\"${S3_URL}/${SSM_S3_BUCKET}/latest/debian_$ARCH_ALT/amazon-ssm-agent.deb\"\n        local SSM_RPM_URL=\"${S3_URL}/${SSM_S3_BUCKET}/latest/linux_$ARCH_ALT/amazon-ssm-agent.rpm\"\n        local SSM_DEB_PKG_NAME=\"ssm-agent.deb\"\n        local SSM_RPM_PKG_NAME=\"ssm-agent.rpm\"\n\n        case \"$PKG_MANAGER\" in\n        apt)\n            curl-helper \"$dir/$SSM_DEB_PKG_NAME\" \"$SSM_DEB_URL\"\n            curl-helper \"$dir/$SSM_DEB_PKG_NAME.sig\" \"$SSM_DEB_URL.sig\"\n            ssm-agent-signature-verify \"$dir/$SSM_DEB_PKG_NAME.sig\" \"$dir/$SSM_DEB_PKG_NAME\"\n            chmod -R a+rX \"$dir\"\n            dpkg -i \"$dir/ssm-agent.deb\"\n            ;;\n        dnf | yum | zypper)\n            curl-helper \"$dir/$SSM_RPM_PKG_NAME\" \"$SSM_RPM_URL\"\n            curl-helper \"$dir/$SSM_RPM_PKG_NAME.sig\" \"$SSM_RPM_URL.sig\"\n            ssm-agent-signature-verify \"$dir/$SSM_RPM_PKG_NAME.sig\" \"$dir/$SSM_RPM_PKG_NAME\"\n            local args=\"\"\n            local install_args=\"-y\"\n            if [[ \"$PKG_MANAGER\" == \"zypper\" ]]; then\n                install_args=\"${install_args} --allow-unsigned-rpm\"\n                args=\"--no-gpg-checks\"\n            fi\n            $PKG_MANAGER ${args} install ${install_args} \"$dir/$SSM_RPM_PKG_NAME\"\n            ;;\n        esac\n        rm -rf \"$dir\"\n    fi\n    # register the instance\n    register-ssm-agent\n    ok\n}\n\nssm-agent-signature-verify() {\n    try \"verify the signature of amazon-ssm-agent package\"\n    if ! command -v gpg; then\n        echo \"WARNING: gpg command not available on this server, not able to verify amazon-ssm-agent package signature.\"\n        ok\n        return\n    fi\n\n    curl-helper \"$dir/amazon-ssm-agent.gpg\" \"https://raw.githubusercontent.com/aws/amazon-ecs-init/master/scripts/amazon-ssm-agent.gpg\"\n    gpg --import \"$dir/amazon-ssm-agent.gpg\"\n\n    if gpg --verify \"$1\" \"$2\"; then\n        echo \"amazon-ssm-agent GPG verification passed. Install the amazon-ssm-agent.\"\n    else\n        echo \"amazon-ssm-agent GPG verification failed. Stop the installation of the amazon-ssm-agent. Please contact AWS Support.\"\n        fail\n    fi\n\n    ok\n}\n\n# order of operations:\n# all->docker->distro->none\ninstall-docker() {\n    if [ -x \"$(command -v docker)\" ]; then\n        echo \"docker is already installed, skipping installation\"\n        return\n    fi\n\n    case \"$1\" in\n    all)\n        install-docker \"docker\"\n        return\n        ;;\n    docker)\n        try \"install docker from docker repos\"\n        case \"$DISTRO\" in\n        centos)\n            # TODO use dnf on centos if available\n            yum install -y yum-utils\n            yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo\n            yum install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        fedora)\n            dnf install -y dnf-plugins-core\n            dnf config-manager --add-repo https://download.docker.com/linux/fedora/docker-ce.repo\n            dnf install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        debian)\n            apt install -y apt-transport-https ca-certificates gnupg-agent software-properties-common\n            curl -fsSL https://download.docker.com/linux/debian/gpg | sudo apt-key add -\n            add-apt-repository \\\n                \"deb [arch=$ARCH_ALT] https://download.docker.com/linux/debian \\\n              $(lsb_release -cs) \\\n              stable\"\n            apt update -y\n            apt install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        ubuntu)\n            apt install -y apt-transport-https ca-certificates gnupg-agent software-properties-common\n            curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n            add-apt-repository \\\n                \"deb [arch=$ARCH_ALT] https://download.docker.com/linux/ubuntu \\\n              $(lsb_release -cs) \\\n              stable\"\n            apt update -y\n            apt install -y docker-ce docker-ce-cli containerd.io\n            ;;\n        *)\n            echo \"Docker install repos not supported for this distro, trying distro install\"\n            install-docker \"distro\"\n            return\n            ;;\n        esac\n        ;;\n    distro)\n        try \"install docker from distribution repos\"\n\n        # centos and fedora enable selinux by default in their distro installs\n        case \"$DISTRO\" in\n        centos | fedora)\n            if [ \"$VERSION_ID\" == \"8\" ]; then\n                echo \"--docker-install-source distro is not supported on centos 8 because docker package is not available.\"\n            else\n                echo \"--docker-install-source distro is not supported on $DISTRO $VERSION_ID because distro enables selinux by default.\"\n            fi\n            echo \"We suggest installing using '--docker-install-source docker' or installing docker yourself before running this script.\"\n            fail\n            ;;\n        esac\n\n        case \"$PKG_MANAGER\" in\n        dnf)\n            dnf install -y docker\n            ;;\n        yum)\n            yum install -y docker\n            ;;\n        apt)\n            apt install -y docker.io\n            ;;\n        zypper)\n            zypper install -y docker\n            ;;\n        esac\n        ;;\n    none)\n        echo \"Docker install source is none, not installing docker\"\n        ;;\n    esac\n\n    ok\n}\n\ninstall-ecs-agent() {\n    try \"install ecs agent\"\n    if [ -x \"/usr/libexec/amazon-ecs-init\" ]; then\n        echo \"ecs agent is already installed\"\n        ok\n        return\n    fi\n\n    local dir\n    dir=\"$(mktemp -d)\"\n    case \"$PKG_MANAGER\" in\n    apt)\n        curl-helper \"$dir/$DEB_PKG_NAME\" \"$DEB_URL\"\n        if $CHECK_SIG; then\n            curl-helper \"$dir/$DEB_PKG_NAME.asc\" \"$DEB_URL.asc\"\n            ecs-init-signature-verify \"$dir/$DEB_PKG_NAME.asc\" \"$dir/$DEB_PKG_NAME\"\n        fi\n        chmod -R a+rX \"$dir\"\n        apt install -y \"$dir/$DEB_PKG_NAME\"\n        rm -rf \"$dir\"\n        ;;\n    dnf | yum | zypper)\n        curl-helper \"$dir/$RPM_PKG_NAME\" \"$RPM_URL\"\n        if $CHECK_SIG; then\n            curl-helper \"$dir/$RPM_PKG_NAME.asc\" \"$RPM_URL.asc\"\n            ecs-init-signature-verify \"$dir/$RPM_PKG_NAME.asc\" \"$dir/$RPM_PKG_NAME\"\n        fi\n        local args=\"-y\"\n        if [[ \"$PKG_MANAGER\" == \"zypper\" ]]; then\n            args=\"${args} --allow-unsigned-rpm\"\n        fi\n        $PKG_MANAGER install ${args} \"$dir/$RPM_PKG_NAME\"\n        rm -rf \"$dir\"\n        ;;\n    esac\n\n    if [ ! -f \"/etc/ecs/ecs.config\" ]; then\n        touch /etc/ecs/ecs.config\n    else\n        echo \"/etc/ecs/ecs.config already exists, preserving existing config and appending cluster name.\"\n    fi\n    echo \"ECS_CLUSTER=$ECS_CLUSTER\" >>/etc/ecs/ecs.config\n\n    if [ ! -f \"/var/lib/ecs/ecs.config\" ]; then\n        touch /var/lib/ecs/ecs.config\n    else\n        echo \"/var/lib/ecs/ecs.config already exists, preserving existing config and appending ECS anywhere requirements.\"\n    fi\n    echo \"AWS_DEFAULT_REGION=$REGION\" >>/var/lib/ecs/ecs.config\n    echo \"ECS_EXTERNAL=true\" >>/var/lib/ecs/ecs.config\n    if [ -n \"$ECS_ENDPOINT\" ]; then\n        echo \"ECS_BACKEND_HOST=$ECS_ENDPOINT\" >>/var/lib/ecs/ecs.config\n    fi\n    if [ -n \"$GPU_ENABLED\" ]; then\n        if ! nvidia-smi &>/dev/null; then\n            echo \"Failed to detect GPU with nvidia-smi command. Make sure that GPUs are attached and the latest NVIDIA driver is installed and running.\"\n            fail\n        fi\n        echo \"ECS_ENABLE_GPU_SUPPORT=true\" >>/var/lib/ecs/ecs.config\n    fi\n    systemctl enable ecs\n    if ! $NO_START; then\n        systemctl start ecs\n    else\n        echo \"Skip starting ecs agent because --no-start is specified.\"\n    fi\n\n    ok\n}\n\necs-init-signature-verify() {\n    try \"verify the signature of amazon-ecs-init package\"\n    if ! command -v gpg; then\n        echo \"WARNING: gpg command not available on this server, not able to verify amazon-ecs-init package signature.\"\n        ok\n        return\n    fi\n\n    curl-helper \"$dir/amazon-ecs-agent.gpg\" \"https://raw.githubusercontent.com/aws/amazon-ecs-init/master/scripts/amazon-ecs-agent.gpg\"\n    gpg --import \"$dir/amazon-ecs-agent.gpg\"\n    if gpg --verify \"$1\" \"$2\"; then\n        echo \"amazon-ecs-init GPG verification passed. Install amazon-ecs-init.\"\n    else\n        echo \"amazon-ecs-init GPG verification failed. Stop the installation of amazon-ecs-init. Please contact AWS Support.\"\n        fail\n    fi\n\n    ok\n}\n\nwait-agent-start() {\n    if $NO_START; then\n        echo \"--no-start is specified. Not verifying ecs agent startup.\"\n        return\n    fi\n    try \"wait for ECS agent to start\"\n\n    retryLimit=10\n    i=0\n    for ((i = 0 ; i < retryLimit ; i++))\n    do\n        curlResult=\"$(timeout 10 curl -s http://localhost:51678/v1/metadata | jq .ContainerInstanceArn)\"\n        if [ ! \"$curlResult\" == \"null\" ] && [ -n \"$curlResult\" ]; then\n            echo \"Ping ECS Agent registered successfully! Container instance arn: $curlResult\"\n            echo \"\"\n            echo \"You can check your ECS cluster here https://console.aws.amazon.com/ecs/home?region=$REGION#/clusters/$ECS_CLUSTER\"\n            ok\n            return\n        fi\n        sleep 10 # wait for 10s before next retry for agent to start up.\n    done\n\n    # TODO Update to ecs anywhere specific documentation when available.\n    echo \"Timed out waiting for ECS Agent to start. Please check logs at /var/log/ecs/ecs-agent.log and follow troubleshooting documentation at https://docs.aws.amazon.com/AmazonECS/latest/developerguide/troubleshooting.html\"\n    fail\n}\n\nexec-setup() {\n    find-copy-certs-exec\n    download-ssm-binaries-exec\n}\n\nfind-copy-certs-exec() {\n    # Reference for locations: https://golang.org/src/crypto/x509/root_linux.go\n    CERTS_FILES_LOCATIONS=(\"/etc/ssl/certs/ca-certificates.crt\"\n      \"/etc/pki/tls/certs/ca-bundle.crt\"\n      \"/etc/ssl/ca-bundle.pem\"\n      \"/etc/pki/tls/cacert.pem\"\n      \"/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem\"\n      \"/etc/ssl/cert.pem\"\n    )\n    CERTS_PATH=\"/var/lib/ecs/deps/execute-command/certs\"\n\n    echo \"Copying certs for exec feature\"\n\n    # Determine certs file\n    certs=\"\"\n    if [ -n \"$CERTS_FILE\" ] && [ -f \"$CERTS_FILE\" ]; then\n        certs=$CERTS_FILE\n    else\n        if [ -n \"$CERTS_FILE\" ]; then\n            echo \"Provided certs file does not exist, looking for certs in known possible locations\"\n        fi\n        for f in \"${CERTS_FILES_LOCATIONS[@]}\"\n        do\n            if  [ -f \"$f\" ]; then\n                certs=$f\n                break\n            fi\n        done\n    fi\n\n    # Copy certs to exec directory\n    if [ -z \"$certs\" ]; then\n        echo \"Could not find certificates. Please rerun with --certs-file and provide a valid path\"\n        fail\n    else\n        echo \"Using $certs\"\n        openssl verify -x509_strict \"$certs\"\n        mkdir -p $CERTS_PATH\n        cp \"$certs\" $CERTS_PATH/tls-ca-bundle.pem\n        chmod 400 $CERTS_PATH/tls-ca-bundle.pem\n    fi\n    ok\n}\n\ndownload-ssm-binaries-exec() {\n    BINARY_VERSION=\"3.1.804.0\"\n    BINARY_PATH=\"/var/lib/ecs/deps/execute-command/bin/${BINARY_VERSION}\"\n    BINARY_DOWNLOAD_PATH=\"ssm-binaries\"\n\n    # Download SSM binaries from S3\n    echo \"Downloading SSM binaries for exec feature\"\n\n    mkdir -p $BINARY_DOWNLOAD_PATH\n    curl \"${S3_URL}/${SSM_S3_BUCKET}/${BINARY_VERSION}/linux_$ARCH_ALT/amazon-ssm-agent-binaries.tar.gz\" -o ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent.tar.gz\n    tar -xvf ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent.tar.gz -C ${BINARY_DOWNLOAD_PATH}/\n\n    # Copy binaries to exec directory\n    mkdir -p ${BINARY_PATH}\n    cp ${BINARY_DOWNLOAD_PATH}/amazon-ssm-agent ${BINARY_PATH}/amazon-ssm-agent\n    cp ${BINARY_DOWNLOAD_PATH}/ssm-agent-worker ${BINARY_PATH}/ssm-agent-worker\n    cp ${BINARY_DOWNLOAD_PATH}/ssm-session-worker ${BINARY_PATH}/ssm-session-worker\n    rm -rf ${BINARY_DOWNLOAD_PATH}\n    ok\n}\n\nshow-license() {\n    echo \"\"\n    echo \"##########################\"\n    echo \"This script installed three open source packages that all use Apache License 2.0.\"\n    echo \"You can view their license information here:\"\n    echo \"  - ECS Agent https://github.com/aws/amazon-ecs-agent/blob/master/LICENSE\"\n    echo \"  - SSM Agent https://github.com/aws/amazon-ssm-agent/blob/master/LICENSE\"\n    echo \"  - Docker engine https://github.com/moby/moby/blob/master/LICENSE\"\n    echo \"##########################\"\n    echo \"\"\n}\n\nif ! $SKIP_REGISTRATION; then\n    install-ssm-agent\nfi\ninstall-docker \"$DOCKER_SOURCE\"\nexec-setup\ninstall-ecs-agent\nwait-agent-start\nshow-license\n", "num_lines": 680}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2014-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -e\nexport TOPWD=\"$(pwd)\"\nexport BUILDDIR=\"$(mktemp -d)\"\nexport GOPATH=\"${TOPWD}/ecs-init/:${BUILDDIR}\"\nexport SRCPATH=\"${BUILDDIR}/src/github.com/aws/amazon-ecs-init\"\nexport GO111MODULE=\"auto\"\n\nif [ -d \"${TOPWD}/.git\" ]; then\n    version=$(cat \"${TOPWD}/ecs-init/ECSVERSION\")\n    git_hash=$(git rev-parse --short=8 HEAD)\n    git_dirty=false\n\n    if [[ \"$(git status --porcelain)\" != \"\" ]]; then\n\tgit_dirty=true\n    fi\n\n    VERSION_FLAG=\"-X github.com/aws/amazon-ecs-init/ecs-init/version.Version=${version}\"\n    GIT_HASH_FLAG=\"-X github.com/aws/amazon-ecs-init/ecs-init/version.GitShortHash=${git_hash}\"\n    GIT_DIRTY_FLAG=\"-X github.com/aws/amazon-ecs-init/ecs-init/version.GitDirty=${git_dirty}\"\nfi\n\nmkdir -p \"${SRCPATH}\"\nln -s \"${TOPWD}/ecs-init\" \"${SRCPATH}\"\ncd \"${SRCPATH}/ecs-init\"\nif [[ \"$1\" == \"dev\" ]]; then\n\tCGO_ENABLED=1 CGO_LDFLAGS_ALLOW='-Wl,--unresolved-symbols=ignore-in-object-files' go build -tags 'development' -ldflags \"${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t   -o \"${TOPWD}/amazon-ecs-init\"\nelse\n\ttags=\"\"\n\tif [[ \"$1\" != \"\" ]]; then\n\t\ttags=\"-tags '$1'\"\n\tfi\n\tCGO_ENABLED=1 CGO_LDFLAGS_ALLOW='-Wl,--unresolved-symbols=ignore-in-object-files' go build -a ${tags} -x \\\n\t\t   -ldflags \"-s ${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t\t   -o \"${TOPWD}/amazon-ecs-init\"\nfi\nCGO_ENABLED=0 go build -x -ldflags \"-s ${VERSION_FLAG} ${GIT_HASH_FLAG} ${GIT_DIRTY_FLAG}\" \\\n\t-o \"${TOPWD}/amazon-ecs-volume-plugin\" \"./volumes/amazon-ecs-volume-plugin\"\nrm -r \"${BUILDDIR}\"\n", "num_lines": 55}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n\nif [ -z \"$1\" ] || [ ! -z $(echo \"$1\" | tr -d \"[:digit:]\") ]; then\n\techo \"Must provide numeric argument\"\n\texit 1\nfi\n\nexit_code=\"$1\"\n\ndie() {\n\texit $exit_code\n}\n\nstart_wait() {\n\techo \"Waiting for SIGTERM or SIGINT to exit\"\n\twhile true\n\tdo\n\t\tsleep 1 &\n\t\twait ${!}\n\tdone\n}\n\nSIGINT=2\nSIGTERM=15\ntrap die $SIGINT $SIGTERM\nstart_wait\n", "num_lines": 40}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n# Usage: mockgen.sh target-package-name source-file-name [relative-output-directory-path]\n\npackage=\"$1\"\ninputfile=\"$2\"\noutputfile=\"$(echo ${inputfile} | sed -e 's/\\.go$/_mocks.go/')\"\nrelativeoutputdir=\"$3\"\n\necho \"Generating mocks from ${inputfile} to ${outputfile} in package ${package}\"\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\ntmp_gen=\"$(mktemp)\"\nyear=\"$(date +\"%Y\")\"\nmockgen -source \"$(pwd)/${inputfile}\" -package \"${package}\" | goimports > \"${tmp_gen}\"\ncat  > \"$(pwd)/${relativeoutputdir}/${outputfile}\" << EOF\n// Copyright 2015-${year} Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n//\n// Source: $(basename ${inputfile}) in package ${package}\n$(grep -v \"// Source: .*${inputfile}\" ${tmp_gen})\nEOF\nrm \"${tmp_gen}\"\n", "num_lines": 49}
{"repo_name": "amazon-ecs-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not\n# use this file except in compliance with the License. A copy of the License\n# is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# This script will update the information of the ecs-init during building\nset -e -x\n\nCURRENTDIR=$(dirname \"${0}\")\nversion=$(cat \"${CURRENTDIR}\"/../ecs-init/ECSVERSION)\ngit_hash=$(git rev-parse --short=8 HEAD)\ngit_dirty=false\n\nif [[ \"$(git status --porcelain)\" != \"\" ]]; then\n\tgit_dirty=true\nfi\n\ncat << EOF > \"${CURRENTDIR}\"/../ecs-init/version/version.go\n// This is an autogenerated file and should not be edited.\n\n// Copyright 2014-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//\thttp://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n// Package version contains constants to indicate the current version of the\n// ecs-init. It is autogenerated.\npackage version\n\n// Version is the version of the ecs-init\nvar Version string = \"${version}\"\n\n// GitDirty indicates the cleanliness of the git repo when this ecs-init was built\nvar GitDirty string = \"${git_dirty}\"\n\n// GitShortHash is the short hash of this ecs-init build\nvar GitShortHash string = \"${git_hash}\"\nEOF\n", "num_lines": 57}
{"repo_name": "amazon-ecs-logs-collector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#    http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the License for the\n# specific language governing permissions and limitations under the License.\n#\n#\n# - Collects Docker daemon and Amazon ECS Container Agent logs on Amazon Linux,\n#   Redhat 7, Debian 8.\n# - Collects general operating system logs.\n# - Optional ability to enable debug mode for the Docker daemon and Amazon ECS\n#   Container Agent on Amazon Linux variants, such as the Amazon ECS-optimized\n#   AMI. For usage information, see --help.\n\nexport LANG=\"C\"\nexport LC_ALL=\"C\"\n\n# Collection configuration\n\n# curdir is the working root of collection.\ncurdir=\"$(dirname \"$0\")\"\n# collectdir is where all collected informaton is placed under. This\n# services as the top level for this script's operation.\nreadonly collectdir=\"${curdir}/collect\"\n\n# datetime is the date and time when the script was executed used in pack()\ndatetime=`date +%Y%m%d%H%M`\n\n# pack_name is the name of the resulting tarball. This will generally\n# be collect-i-ffffffffffffffffff-YYYYMMDDHHmm, where i-ffffffffffffffffff is the\n# instance id and YYYYMMDDHHmm is date and time.\npack_name=\"collect\"\n\n# Shared check variables\n\n# info_system is where the checks' data is placed.\ninfo_system=\"${collectdir}/system\"\n# pkgtype is the detected packaging system used on the host (eg: yum, deb)\npkgtype=''  # defined in get_pkgtype\n# jsonformatter is the detected tool to process JSON installed on the host\njsonformatter=''\n# init_type is the operating system type used for casing check behavior.\ninit_type=''  # defined in get_init_type\nprogname='' # defined in parse_options\n# dstdir is the destination where the logs collected are placed.\ndstdir=''  # defined in several routines\n\n# Script run defaults\n\nmode='brief' # defined in parse_options\n\n\n# Common functions\n# ---------------------------------------------------------------------------------------\n\nhelp() {\n  echo \"USAGE: ${progname} [--mode=[brief|enable-debug]]\"\n  echo \"       ${progname} --help\"\n  echo \"\"\n  echo \"OPTIONS:\"\n  echo \"     --mode  Sets the desired mode of the script. For more information,\"\n  echo \"             see the MODES section.\"\n  echo \"     --help  Show this help message.\"\n  echo \"\"\n  echo \"MODES:\"\n  echo \"     brief         Gathers basic operating system, Docker daemon, and Amazon\"\n  echo \"                   ECS Container Agent logs. This is the default mode.\"\n  echo \"     enable-debug  Enables debug mode for the Docker daemon and the Amazon\"\n  echo \"                   ECS Container Agent. Only supported on Systemd init systems\"\n  echo \"                   and Amazon Linux.\"\n}\n\nparse_options() {\n  local count=\"$#\"\n\n  progname=\"$0\"\n\n  for i in $(seq \"$count\"); do\n    eval arg=\\$\"$i\"\n    # shellcheck disable=SC2154\n    param=\"$(echo \"$arg\" | awk -F '=' '{print $1}' | sed -e 's|--||')\"\n    val=\"$(echo \"$arg\" | awk -F '=' '{print $2}')\"\n\n    case \"${param}\" in\n      mode)\n        eval \"$param\"=\"${val}\"\n        ;;\n      help)\n        help && exit 0\n        ;;\n      *)\n        echo \"Parameter not found: '$param'\"\n        help && exit 1\n        ;;\n    esac\n  done\n}\n\nok() {\n  echo \"ok\"\n}\n\ninfo() {\n  echo \"$*\"\n}\n\ntry() {\n  local action=$*\n  echo -n \"Trying to $action ... \"\n}\n\nwarning() {\n  local reason=$*\n  echo \"warning: $reason\"\n}\n\nfailed() {\n  local reason=$*\n  echo \"failed: $reason\"\n}\n\ndie() {\n  echo \"ERROR: $*\"\n  exit 1\n}\n\nis_root() {\n  try \"check if the script is running as root\"\n\n  if [[ \"$(id -u)\" != \"0\" ]]; then\n    die \"this script must be run as root!\"\n\n  fi\n\n  ok\n}\n\ncleanup() {\n  rm -rf \"$collectdir\" >/dev/null 2>&1\n  rm -f \"$curdir\"/collect.tgz\n}\n\ninit() {\n  is_root\n  try_set_instance_collectdir\n  get_init_type\n  get_pkgtype\n  get_jsonformatter\n}\n\ncollect_brief() {\n  init\n  is_diskfull\n  get_common_logs\n  get_kernel_logs\n  get_mounts_info\n  get_selinux_info\n  get_iptables_info\n  get_pkglist\n  get_system_services\n  get_docker_info\n  get_docker_containers_info\n  get_docker_logs\n  get_docker_systemd_config\n  get_docker_sysconfig\n  get_docker_daemon_json\n  get_ecs_agent_logs\n  get_ecs_agent_info\n  get_open_files\n  get_os_release\n  get_uname_info\n  get_dmidecode_info\n  get_lsmod_info\n  get_cgroupv2_events\n  get_systemd_slice_info\n  get_veth_info\n  get_gpu_info\n}\n\nenable_debug() {\n  is_root\n  get_init_type\n  enable_docker_debug\n  enable_ecs_agent_debug\n}\n\n# Routines\n# ---------------------------------------------------------------------------------------\n\n# uname gets basic system and kernel information.\nget_uname_info() {\n  try \"get uname kernel info\"\n\n  mkdir -p \"$info_system\"\n  uname -a > \"$info_system\"/uname.txt\n\n  ok\n}\n\n# dmidecode is a tool sometimes installed on VMs that provides detailed\n# information about the VM hypervisor, underlying hardware, and system.\nget_dmidecode_info() {\n  try \"get dmidecode info\"\n\n  if command -v dmidecode &>/dev/null; then\n    mkdir -p \"$info_system\"\n    dmidecode > \"$info_system\"/dmidecode.txt\n  fi\n\n  ok\n}\n\n# lsmod lists loadable kernel modules.\nget_lsmod_info() {\n  try \"get lsmod info\"\n\n  if command -v lsmod &>/dev/null; then\n    mkdir -p \"$info_system\"\n    lsmod > \"$info_system\"/lsmod.txt\n  fi\n\n  ok\n}\n\nget_init_type() {\n  try \"collect system information\"\n\n  case \"$(cat /proc/1/comm)\" in\n    systemd)\n      init_type=\"systemd\"\n    ;;\n    *)\n      init_type=\"other\"\n    ;;\n  esac\n\n  ok\n}\n\nget_pkgtype() {\n  if [[ -n \"$(command -v rpm)\" ]]; then\n    pkgtype=\"rpm\"\n  elif [[ -n \"$(command -v dpkg)\" ]]; then\n    pkgtype=\"dpkg\"\n  else\n    pkgtype=\"unknown\"\n  fi\n}\n\nget_jsonformatter(){\n  if [[ -n \"$(command -v python)\" ]]; then\n    jsonformatter=\"python -mjson.tool\"\n  elif [[ -n \"$(command -v jq)\" ]]; then\n    jsonformatter=\"jq\"\n  else\n    jsonformatter=\"\"\n  fi\n}\n\ntry_set_instance_collectdir() {\n  try \"resolve instance-id\"\n\n  if [ -f /var/lib/amazon/ssm/registration ]; then\n    info \"SSM managed instance detected, getting managed instance id\"\n    if command -v jq > /dev/null; then\n      instance_id=$(jq -r \".ManagedInstanceID\" < /var/lib/amazon/ssm/registration)\n    fi\n  fi\n\n  if test -z \"$instance_id\" && command -v curl > /dev/null; then\n    info \"getting instance id from ec2 metadata endpoint\"\n    imds=\"http://169.254.169.254/latest\"\n    token=$(curl -sS --retry 3 -X PUT \"${imds}/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" 2>/dev/null)\n    instance_id=$(curl -sS --retry 3 -H \"X-aws-ec2-metadata-token: $token\" \"${imds}/meta-data/instance-id\" 2>/dev/null)\n  fi\n\n  if [ -n \"$instance_id\" ]; then\n    # Put logs into a directory for this instance.\n    info_system=\"${collectdir}/${instance_id}\"\n    # And in a pack that includes the instance id in its name.\n    pack_name=\"collect-${instance_id}\"\n    mkdir -p \"${info_system}\"\n    echo \"$instance_id\" > \"$info_system\"/instance-id.txt\n  else\n    warning \"unable to get instance id\"\n    return 1\n  fi\n\n  ok\n}\n\npack() {\n  try \"archive gathered log information\"\n\n  local tar_bin\n  tar_bin=\"$(command -v tar 2>/dev/null)\"\n  [ -z \"${tar_bin}\" ] && warning \"TAR archiver not found, please install a TAR archiver to create the collection archive. You can still view the logs in the collect folder.\"\n\n  cd \"$curdir\" || { echo \"cd failed.\"; exit 1; }\n\n  ${tar_bin} -cvzf \"$curdir/$pack_name-$datetime\".tgz \"$collectdir\" > /dev/null 2>&1\n\n  ok\n}\n\nis_diskfull() {\n  try \"check disk space usage\"\n\n  threshold=70\n  i=2\n  result=$(df -kh | grep -ve \"Filesystem\" -ve \"loop\" | awk '{ print $5 }' | sed 's/%//g')\n  exceeded=0\n\n  for percent in ${result}; do\n    if [[ \"${percent}\" -gt \"${threshold}\" ]]; then\n      partition=$(df -kh | head -$i | tail -1| awk '{print $1}')\n      echo\n      warning \"${partition} is ${percent}% full, please ensure adequate disk space to collect and store the log files.\"\n      : $((exceeded++))\n    fi\n    i=$((i+1))\n  done\n\n  if [ \"$exceeded\" -gt 0 ]; then\n    return 1\n  else\n    ok\n  fi\n}\n\nget_mounts_info() {\n  try \"get mount points and volume information\"\n\n  mkdir -p \"$info_system\"\n  mount > \"$info_system\"/mounts.txt\n  echo \"\" >> \"$info_system\"/mounts.txt\n  df -h >> \"$info_system\"/mounts.txt\n\n  if command -v lvdisplay > /dev/null; then\n    lvdisplay > \"$info_system\"/lvdisplay.txt\n    vgdisplay > \"$info_system\"/vgdisplay.txt\n    pvdisplay > \"$info_system\"/pvdisplay.txt\n  fi\n\n  ok\n}\n\nget_veth_info() {\n  try \"get veth info\"\n\n  if command -v brctl >/dev/null; then\n    brctl show > \"$info_system\"/brctlshow.txt\n  fi\n\n  if command -v ip >/dev/null; then\n    ip addr show > \"$info_system\"/ipaddrshow.txt\n  fi\n\n  ok\n}\n\nget_selinux_info() {\n  try \"check SELinux status\"\n\n  enforced=\"$(getenforce 2>/dev/null)\"\n\n  { [ \"${pkgtype}\" != \"rpm\" ] || [ -z \"${enforced}\" ]; } \\\n    && info \"not installed\" \\\n    && return\n\n  mkdir -p \"$info_system\"\n  echo -e \"SELinux mode:\\\\n    ${enforced}\" >  \"$info_system\"/selinux.txt\n\n  ok\n}\n\nget_iptables_info() {\n  try \"get iptables list\"\n\n  mkdir -p \"$info_system\"\n  iptables -nvL -t filter > \"$info_system\"/iptables-filter.txt\n  iptables -nvL -t nat  > \"$info_system\"/iptables-nat.txt\n\n  ok\n}\n\nget_open_files() {\n  try \"get open files list\"\n\n  mkdir -p \"$info_system\"\n  for d in /proc/*/fd; do echo \"$d\"; find \"$d\" -maxdepth 1 | wc -l; done > \"$info_system\"/open-file-counts.txt\n  ls -l /proc/*/fd > \"$info_system\"/open-file-details.txt\n\n  ok\n}\n\nget_common_logs() {\n  try \"collect common operating system logs\"\n\n  mkdir -p \"$info_system\"\n  if command -v journalctl >/dev/null; then\n      journalctl > \"${info_system}\"/system.log\n  fi\n\n  dstdir=\"${info_system}/var_log\"\n  mkdir -p \"$dstdir\"\n\n  for entry in syslog messages; do\n    [ -e \"/var/log/${entry}\" ] && cp -f /var/log/${entry} \"$dstdir\"/\n  done\n\n  ok\n}\n\nget_kernel_logs() {\n  try \"collect kernel logs\"\n\n  dstdir=\"${info_system}/kernel\"\n  mkdir -p \"$dstdir\"\n  if [ -e \"/var/log/dmesg\" ]; then\n    cp -f /var/log/dmesg \"$dstdir/dmesg.boot\"\n  fi\n  dmesg > \"$dstdir/dmesg.current\"\n  dmesg --ctime > \"$dstdir/dmesg.human.current\"\n  ok\n}\n\nget_docker_logs() {\n  try \"collect Docker and containerd daemon logs\"\n\n  dstdir=\"${info_system}/docker_log\"\n  mkdir -p \"$dstdir\"\n  case \"${init_type}\" in\n    systemd)\n      journalctl -u docker > \"${dstdir}\"/docker\n      journalctl -u containerd > \"${info_system}\"/containerd.log\n      ;;\n    other)\n      for entry in docker upstart/docker; do\n        if [[ -e \"/var/log/${entry}\" ]]; then\n          cp -f /var/log/\"${entry}\" \"${dstdir}\"/docker\n        fi\n      done\n      ;;\n    *)\n      warning \"the current operating system is not supported.\"\n      return 1\n      ;;\n  esac\n\n  ok\n}\n\nget_ecs_agent_logs() {\n  try \"collect Amazon ECS Container Agent logs\"\n\n  dstdir=\"${info_system}/ecs_agent_logs\"\n\n  if [ ! -d /var/log/ecs ]; then\n    failed \"ECS log directory does not exist\"\n    return 1\n  fi\n\n  mkdir -p \"$dstdir\"\n\n  cp -f -r /var/log/ecs/* \"$dstdir\"/\n\n  ok\n}\n\nget_pkglist() {\n  try \"detect installed packages\"\n\n  mkdir -p \"$info_system\"\n  case \"${pkgtype}\" in\n    rpm)\n      rpm -qa >\"$info_system\"/pkglist.txt 2>&1\n      ;;\n    dpkg)\n      dpkg --list > \"$info_system\"/pkglist.txt 2>&1\n      ;;\n    *)\n      warning \"unknown package type.\"\n      return 1\n      ;;\n  esac\n\n  ok\n}\n\nget_system_services() {\n  try \"detect active system services list\"\n\n  mkdir -p \"$info_system\"\n  case \"${init_type}\" in\n    systemd)\n      systemctl list-units > \"$info_system\"/services.txt 2>&1\n      ;;\n    other)\n      service --status-all >> \"$info_system\"/services.txt 2>&1\n      ;;\n    *)\n      warning \"unable to determine active services.\"\n      return 1\n      ;;\n  esac\n\n  top -b -n 1 > \"$info_system\"/top.txt 2>&1\n  ps fauxwww > \"$info_system\"/ps.txt 2>&1\n  netstat -plant > \"$info_system\"/netstat.txt 2>&1\n\n  ok\n}\n\nget_docker_info() {\n  try \"gather Docker daemon information\"\n\n  mkdir -p \"$info_system\"/docker\n\n  if pgrep dockerd > /dev/null ; then\n\n    timeout 20 docker info > \"$info_system\"/docker/docker-info.txt 2>&1 || echo \"Timed out, ignoring \\\"docker info output \\\" \"\n    timeout 20 docker ps --all --no-trunc > \"$info_system\"/docker/docker-ps.txt 2>&1 || echo \"Timed out, ignoring \\\"docker ps --all --no-trunc output \\\" \"\n    timeout 20 docker images > \"$info_system\"/docker/docker-images.txt 2>&1 || echo \"Timed out, ignoring \\\"docker images output \\\" \"\n    timeout 20 docker version > \"$info_system\"/docker/docker-version.txt 2>&1 || echo \"Timed out, ignoring \\\"docker version output \\\" \"\n    timeout 60 docker stats --all --no-trunc --no-stream > \"$info_system\"/docker/docker-stats.txt 2>&1 || echo \"Timed out, ignoring \\\"docker stats\\\" output\"\n\n    ok\n  else\n    warning \"the Docker daemon is not running.\" | tee \"$info_system\"/docker/docker-not-running.txt\n  fi\n}\n\nget_ecs_agent_info() {\n  try \"collect Amazon ECS Container Agent state and config\"\n\n  mkdir -p \"$info_system\"/ecs-agent\n  if [ -e /var/lib/ecs/data/ecs_agent_data.json ]; then\n    cp -f /var/lib/ecs/data/ecs_agent_data.json \"$info_system\"/ecs-agent/ecs_agent_data.txt 2>&1\n    if [ -n \"$jsonformatter\" ]; then\n      cat \"$info_system\"/ecs-agent/ecs_agent_data.txt | $jsonformatter > \"$info_system\"/ecs-agent/ecs_agent_data_tmp.txt\n      mv \"$info_system\"/ecs-agent/ecs_agent_data_tmp.txt \"$info_system\"/ecs-agent/ecs_agent_data.txt\n    fi\n  fi\n\n  if [ -e /var/lib/ecs/data/agent.db ]; then\n    cp -f /var/lib/ecs/data/agent.db \"$info_system\"/ecs-agent/agent.db 2>&1\n    chmod +r \"$info_system\"/ecs-agent/agent.db\n  fi\n\n  if [ -e /etc/ecs/ecs.config ]; then\n    cp -f /etc/ecs/ecs.config \"$info_system\"/ecs-agent/ 2>&1\n    if grep --quiet \"ECS_ENGINE_AUTH_DATA\" \"$info_system\"/ecs-agent/ecs.config; then\n      sed -i 's/ECS_ENGINE_AUTH_DATA=.*/ECS_ENGINE_AUTH_DATA=/g' \"$info_system\"/ecs-agent/ecs.config\n    fi\n  fi\n  ok\n\n  try \"collect Amazon ECS Container Agent engine data\"\n\n  if pgrep agent > /dev/null ; then\n    if command -v curl >/dev/null; then\n      if curl --max-time 3 -s http://localhost:51678/v1/tasks > \"$info_system\"/ecs-agent/agent-running-info.txt 2>&1; then\n        if [ -n \"$jsonformatter\" ]; then\n          cat \"$info_system\"/ecs-agent/agent-running-info.txt | $jsonformatter > \"$info_system\"/ecs-agent/agent-running-info-tmp.txt\n          mv \"$info_system\"/ecs-agent/agent-running-info-tmp.txt \"$info_system\"/ecs-agent/agent-running-info.txt\n        fi\n          ok\n      else\n          warning \"failed to get agent data\"\n      fi\n    else\n      warning \"curl is unavailable for probing ECS Container Agent introspection endpoint\"\n    fi\n  else\n    warning \"The Amazon ECS Container Agent is not running\" | tee \"$info_system\"/ecs-agent/ecs-agent-not-running.txt\n    return 1\n  fi\n}\n\nget_docker_containers_info() {\n  try \"inspect all Docker containers\"\n\n  mkdir -p \"$info_system\"/docker\n\n  if pgrep dockerd > /dev/null ; then\n    for i in $(docker ps -a -q); do\n      timeout 10 docker inspect \"$i\" > \"$info_system\"/docker/container-\"$i\".txt 2>&1\n      if [ $? -eq 124 ]; then\n        touch \"$info_system\"/docker/container-inspect-timed-out.txt\n        failed \"'docker inspect' timed out, not gathering containers\"\n        return 1\n      fi\n\n      if grep --quiet \"ECS_ENGINE_AUTH_DATA\" \"$info_system\"/docker/container-\"$i\".txt; then\n        sed -i 's/ECS_ENGINE_AUTH_DATA=.*/ECS_ENGINE_AUTH_DATA=/g' \"$info_system\"/docker/container-\"$i\".txt\n      fi\n    done\n  else\n    warning \"the Docker daemon is not running.\" | tee \"$info_system\"/docker/docker-not-running.txt\n    return 1\n  fi\n  ok\n}\n\nget_docker_sysconfig() {\n  try \"collect Docker sysconfig\"\n\n  if [ -e /etc/sysconfig/docker ]; then\n    mkdir -p \"${info_system}\"/docker\n    cp /etc/sysconfig/docker \"${info_system}\"/docker/sysconfig-docker\n    ok\n  else\n    info \"/etc/sysconfig/docker not found\"\n  fi\n\n try \"collect Docker storage sysconfig\"\n\n  if [ -e /etc/sysconfig/docker-storage ]; then\n    mkdir -p \"${info_system}\"/docker\n    cp /etc/sysconfig/docker-storage \"${info_system}\"/docker/sysconfig-docker-storage\n    ok\n  else\n    info \"/etc/sysconfig/docker-storage not found\"\n  fi\n}\n\n\nget_docker_daemon_json(){\n  try \"collect Docker daemon.json\"\n\n  if [ -e /etc/docker/daemon.json ]; then\n    mkdir -p \"${info_system}\"/docker\n    cp /etc/docker/daemon.json \"${info_system}\"/docker/daemon.json\n    ok\n  else\n    info \"/etc/docker/daemon.json not found\"\n  fi\n}\n\nget_docker_systemd_config(){\n\n  if [[ \"$init_type\" != \"systemd\" ]]; then\n    return 0\n  fi\n\n  try \"collect Docker systemd unit file\"\n\n  mkdir -p \"${info_system}\"/docker\n  if systemctl cat docker.service > \"${info_system}\"/docker/docker.service 2>/dev/null; then\n   ok\n  else\n    rm -f \"$info_system/docker/docker.service\"\n    warning \"docker.service not found\"\n  fi\n\n  try \"collect containerd systemd unit file\"\n  if systemctl cat containerd.service > \"${info_system}\"/docker/containerd.service 2>/dev/null; then\n   ok\n  else\n    rm -f \"$info_system/docker/containerd.service\"\n    warning \"containerd.service not found\"\n  fi\n}\n\nget_os_release(){\n  try \"collect /etc/os-release\"\n\n  if [ -f /etc/os-release ]; then\n    cat /etc/os-release > \"${info_system}\"/os-release\n    ok\n  else\n    info \"/etc/os-release not found\"\n  fi\n}\n\nget_cgroupv2_events(){\n  # cgroup v2 is only supported on systemd systems\n  if [[ \"$init_type\" != \"systemd\" ]]; then\n    return 0\n  fi\n  # this file will only exist on systems with cgroup v2 enabled\n  if [ ! -f /sys/fs/cgroup/cgroup.controllers ]; then\n    return 0\n  fi\n  try \"collect cgroupv2 events\"\n\n  local outfile=\"${info_system}\"/cgroupv2.events\n  touch $outfile\n  # find cgroup memory event files for all ecs tasks with task resource limits and all\n  # docker containers running on the system.\n  for eventfile in $(find /sys/fs/cgroup/ -type f -name \"memory*events\" | grep -e \"docker-\" -e \"ecstask\"); do\n    echo \"$eventfile\" >> $outfile\n    cat $eventfile >> $outfile\n    echo \"\" >> $outfile\n  done\n  ok\n}\n\nget_systemd_slice_info(){\n  if [[ \"$init_type\" != \"systemd\" ]]; then\n    return 0\n  fi\n  try \"collect systemd slice info\"\n\n  # system.slice will exist on all systemd systems:\n  local outfile=\"${info_system}\"/system.slice\n  touch $outfile\n  systemctl status system.slice >$outfile\n  # ecstasks.slice will only exist if we're using the systemd cgroup driver and cgroups v2:\n  if systemctl status ecstasks.slice &>/dev/null; then\n    local outfile=\"${info_system}\"/ecstasks.slice\n    touch $outfile\n    systemctl status ecstasks.slice >$outfile\n  fi\n  ok\n}\n\nenable_docker_debug() {\n  try \"enable debug mode for the Docker daemon\"\n\n  if [ -e /etc/sysconfig/docker ] && grep -q \"^\\\\s*OPTIONS=\\\"-D\" /etc/sysconfig/docker; then\n    info \"Debug mode is already enabled.\"\n  else\n\n    if [ -e /etc/sysconfig/docker ]; then\n      case \"${init_type}\" in\n        systemd)\n          sed -i 's/^OPTIONS=\"\\(.*\\)/OPTIONS=\"-D \\1/g' /etc/sysconfig/docker\n          ok\n\n          try \"restart Docker daemon to enable debug mode\"\n          systemctl restart docker.service\n          ok\n          ;;\n        *)\n          echo \"OPTIONS=\\\"-D \\$OPTIONS\\\"\" >> /etc/sysconfig/docker\n\n          try \"restart Docker daemon to enable debug mode\"\n          service docker restart\n          ok\n\n        esac\n\n    else\n      warning \"the current operating system is not supported.\"\n    fi\n  fi\n}\n\nenable_ecs_agent_debug() {\n  try \"enable debug mode for the Amazon ECS Container Agent\"\n\n  if [ -e /etc/ecs/ecs.config ] &&  grep -q \"^\\\\s*ECS_LOGLEVEL=debug\" /etc/ecs/ecs.config; then\n    info \"Debug mode is already enabled.\"\n  else\n\n    case \"${init_type}\" in\n    systemd)\n      if [ ! -d /etc/ecs ]; then\n        mkdir /etc/ecs\n      fi\n\n      echo \"ECS_LOGLEVEL=debug\" >> /etc/ecs/ecs.config\n      ok\n\n      try \"restart the Amazon ECS Container Agent to enable debug mode\"\n      systemctl restart ecs\n      ok\n      ;;\n    *)\n      if rpm -q --quiet ecs-init; then\n        if [ ! -d /etc/ecs ]; then\n          mkdir /etc/ecs\n        fi\n\n        echo \"ECS_LOGLEVEL=debug\" >> /etc/ecs/ecs.config\n        ok\n\n        try \"restart the Amazon ECS Container Agent to enable debug mode\"\n        stop ecs; start ecs\n        ok\n      else\n        warning \"the current operating system is not supported.\"\n      fi\n      ;;\n    esac\n  fi\n}\n\n# nvidia-smi is a tool available on GPU based AMIs provides detailed\n# information about the GPU present on the VM.\nget_gpu_info() {\n  try \"get gpu info\"\n\n  if command -v nvidia-smi &>/dev/null; then\n    mkdir -p \"$info_system\"/gpu\n    nvidia-smi -L > \"$info_system\"/gpu/gpu-list.txt\n    nvidia-smi -q > \"$info_system\"/gpu/gpu-info.txt\n  fi\n\n  ok\n}\n# --------------------------------------------------------------------------------------------\n\nparse_options \"$@\"\n\ncase \"${mode}\" in\n  brief)\n    cleanup\n    collect_brief\n    pack\n    ;;\n  enable-debug)\n    enable_debug\n    ;;\n  *)\n    help && exit 1\n    ;;\nesac\n", "num_lines": 830}
{"repo_name": "amazon-ecs-service-connect-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nPROJECT_DIR=\"\"\nSDK_SOURCE_DIR=$(cd `dirname $0` && pwd)\n\nusage() {\n  echo \"Usage: $0 [-s SDK_SOURCE_DIR] [-d PROJECT_DIR]\" 1>&2\n  exit 1\n}\n\nwhile getopts \"hs:d:\" options; do\n  case \"${options}\" in\n  s)\n    SDK_SOURCE_DIR=${OPTARG}\n    if [ \"$SDK_SOURCE_DIR\" == \"\" ]; then\n      echo \"path to SDK source directory is required\" || exit\n      usage\n    fi\n    ;;\n  d)\n    PROJECT_DIR=${OPTARG}\n    ;;\n  h)\n    usage\n    ;;\n  *)\n    usage\n    ;;\n  esac\ndone\n\nif [ \"$PROJECT_DIR\" != \"\" ]; then\n  cd \"$PROJECT_DIR\" || exit\nfi\n\ngo mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep \"github.com/aws/aws-sdk-go-v2\" | while read x; do\n  repPath=${x/github.com\\/aws\\/aws-sdk-go-v2/${SDK_SOURCE_DIR}}\n  echo -replace $x=$repPath\ndone | xargs go mod edit\n", "num_lines": 40}
{"repo_name": "amazon-ecs-service-connect-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#1/usr/bin/env bash\n\nPROJECT_DIR=\"\"\nSMITHY_SOURCE_DIR=$(cd `dirname $0` && pwd)\n\nusage() {\n  echo \"Usage: $0 [-s SMITHY_SOURCE_DIR] [-d PROJECT_DIR]\" 1>&2\n  exit 1\n}\n\nwhile getopts \"hs:d:\" options; do\n  case \"${options}\" in\n  s)\n    SMITHY_SOURCE_DIR=${OPTARG}\n    if [ \"$SMITHY_SOURCE_DIR\" == \"\" ]; then\n      echo \"path to smithy-go source directory is required\" || exit\n      usage\n    fi\n    ;;\n  d)\n    PROJECT_DIR=${OPTARG}\n    ;;\n  h)\n    usage\n    ;;\n  *)\n    usage\n    ;;\n  esac\ndone\n\nif [ \"$PROJECT_DIR\" != \"\" ]; then\n  cd $PROJECT_DIR || exit\nfi\n\ngo mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep \"github.com/aws/smithy-go\" | while read x; do\n  repPath=${x/github.com\\/aws\\/smithy-go/${SMITHY_SOURCE_DIR}}\n  echo -replace $x=$repPath\ndone | xargs go mod edit\n", "num_lines": 40}
{"repo_name": "amazon-ecs-service-connect-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -eu -o pipefail\n\n# Small convenience script for running the tests with various combinations of\n# arch/tags. This assumes we're running on amd64 and have qemu available.\n\ngo test ./...\ngo test -tags purego ./...\nGOARCH=arm64 go test\nGOARCH=arm64 go test -tags purego\n", "num_lines": 11}
{"repo_name": "amazon-ecs-service-connect-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-ecs-service-connect-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <netinet/udp.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 782}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nreference_ref=${1:-master}\nreference_git=${2:-.}\n\nif ! `hash benchstat 2>/dev/null`; then\n    echo \"Installing benchstat\"\n    go get golang.org/x/perf/cmd/benchstat\nfi\n\ntempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX`\nref_tempdir=\"${tempdir}/ref\"\nref_benchmark=\"${ref_tempdir}/benchmark-`echo -n ${reference_ref}|tr -s '/' '-'`.txt\"\nlocal_benchmark=\"`pwd`/benchmark-local.txt\"\n\necho \"=== ${reference_ref} (${ref_tempdir})\"\ngit clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null\npushd ${ref_tempdir} >/dev/null\ngit checkout ${reference_ref} >/dev/null 2>/dev/null\ngo test -bench=. -benchmem | tee ${ref_benchmark}\ncd benchmark\ngo test -bench=. -benchmem | tee -a ${ref_benchmark}\npopd >/dev/null\n\necho \"\"\necho \"=== local\"\ngo test -bench=. -benchmem  | tee ${local_benchmark}\ncd benchmark\ngo test -bench=. -benchmem | tee -a ${local_benchmark}\n\necho \"\"\necho \"=== diff\"\nbenchstat -delta-test=none ${ref_benchmark} ${local_benchmark}\n", "num_lines": 36}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/sh\nset -eu\n\ngo get github.com/dvyukov/go-fuzz/go-fuzz\ngo get github.com/dvyukov/go-fuzz/go-fuzz-build\n\nif [ ! -e toml-fuzz.zip ]; then\n    go-fuzz-build github.com/pelletier/go-toml\nfi\n\nrm -fr fuzz\nmkdir -p fuzz/corpus\ncp *.toml fuzz/corpus\n\ngo-fuzz -bin=toml-fuzz.zip -workdir=fuzz\n", "num_lines": 16}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "amazon-eks-connector", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 781}
{"repo_name": "amazon-eks-pod-identity-webhook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Check arguments.\nif [ $# -ne 1 ]; then\n    echo \"Usage: ./generate_doc.sh sdk_root_directory\"\n    exit 1\nfi\n\n# Change to SDK root directory.\ncd $1\n\n# Check for doxygen.\ncommand -v doxygen > /dev/null || { echo \"Doxygen not found. Exiting.\"; exit 1; }\n\n# Doxygen must be run twice: once to generate tags and once more to link tags.\ni=0; while [ $i -le 1 ]; do\n    # Run for each library config file.\n    for file in doc/config/*; do\n        # Ignore directories.\n        if [ -d $file ]; then\n            continue\n        fi\n\n        # Ignore xml files.\n        if [ ${file##*.} = \"xml\" ]; then\n            continue\n        fi\n\n        # Ignore the common configuration file.\n        if [ $file = \"doc/config/common\" ]; then\n            continue\n        fi\n\n        # Generate Doxygen tags first. Once tags are generated, generate documentation.\n        if [ $i -eq 0 ]; then\n            echo \"Generating Doxygen tags for $file...\"\n            doxygen $file 2> /dev/null\n        else\n            echo \"Generating documentation for $file...\"\n\n            # Redirect errors to a file.\n            doxygen $file 2>>doxygen_warnings.txt\n        fi\n    done\n\n    i=$(($i+1));\ndone\n\necho \"Documentation written to doc/output\"\necho \"Doxygen warnings written to ./doxygen_warnings.txt\"\n\n# Print any doxygen errors or warnings and exit with a nonzero value.\nif [ -s doxygen_warnings.txt ]; then\n    cat doxygen_warnings.txt\n    exit 1\nfi", "num_lines": 56}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nscp * root@192.168.1.3:\nssh -t -t 192.168.1.3 -l root << 'ENDSSH'\nrm -rf \"/var/lib/bluetooth/*\"\nhciconfig hci0 reset\npython test1.py\nsleep 1\nENDSSH\n\n", "num_lines": 11}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_adc_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_adc_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ ! -z $1 ]; then\n    #Set dac output voltage\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_adc_rp3.py $1\"\nfi\n", "num_lines": 43}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\n# This is a shell script to secure copy the GPIO_RP3 to RP3\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_gpio_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_gpio_rp3.py ${LOGINID}@${IP}:/home/pi/Tests/\nelif [ \"$1\" == \"-w\" ]; then\n\n    #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to read the GPIO pin status\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_gpio_rp3.py -i $2 > /home/pi/Tests/gpio_rpi_res.txt\"\n\n    #Copy the GPIO pin status to host for validation\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/gpio_rpi_res.txt ${DIR}\n\nelif [ \"$1\" == \"-r\" ]; then\n    #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to set the GPIO pin output\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_gpio_rp3.py -o $2\"\n\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/gpio_rpi_res.txt\"\nfi\n\nexit 0\n", "num_lines": 57}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_adc_rp3.py from Host to RP3\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"mkdir -p /home/pi/Tests\"\n    sshpass -p \"$PASSWD\" scp ${DIR}/test_iot_i2c_master_rp3.py \"$LOGINID\"@\"$IP\":/home/pi/Tests\nelif [ \"$1\" == \"-s\" ]; then\n    #Run demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'\n    sleep .1\n    #Run rpi script\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"python /home/pi/Tests/test_iot_i2c_master_rp3.py\"\n    #Kill demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"sudo killall pigpiod\"\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"rm /home/pi/Tests/i2c_master_res.txt\"\nfi", "num_lines": 49}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_read_PWM.py and test_iot_wave_PWM.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_pwm_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    #Delete the result file on rpi\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/pwm_rpi_res.txt\"\nelse\n    #Run demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'\n    #Run two pwm scripts at same time\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'python /home/pi/Tests/test_iot_pwm_rp3.py > /home/pi/Tests/pwm_rpi_res.txt'\n    #Kill demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo killall pigpiod'\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/pwm_rpi_res.txt ${DIR}\nfi\n", "num_lines": 54}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nif [ \"$1\" == \"-t\" ]; then\n  for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do\n      (\n          syspath=\"${sysdevpath%/dev}\"\n          devname=\"$(udevadm info -q name -p $syspath)\"\n          [[ \"$devname\" == \"bus/\"* ]] && continue\n          eval \"$(udevadm info -q property --export -p $syspath)\"\n          [[ (-z \"$ID_SERIAL\") || (\"$ID_SERIAL\" != *\"MicroPython\"*)]] && continue\n          echo \"/dev/$devname\"\n          break\n      )\n  done\nfi\n", "num_lines": 41}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy test script from Host ubuntu to RP3\n    sshpass -p \"${PASSWD}\" ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p \"${PASSWD}\" scp ${DIR}/test_iot_tsensor_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    #Delete the result file on rpi\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/tsensor_rpi_res.txt\"\nelse\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_tsensor_rp3.py > /home/pi/Tests/tsensor_rpi_res.txt\"\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/tsensor_rpi_res.txt ${DIR}\nfi\n", "num_lines": 47}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_uart_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_uart_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/uart_res.txt\"\nelse\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python3 /home/pi/Tests/test_iot_uart_rp3.py $1 > /home/pi/Tests/uart_res.txt\"\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/uart_res.txt ${DIR}\nfi\n", "num_lines": 46}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nrm -rf ../../../.git/hooks/*\nln -s ../../tools/git/hooks/src/pre_commit.py ../../../.git/hooks/pre-commit\nln -s ../../tools/git/hooks/src/commit_msg.py ../../../.git/hooks/commit-msg\n", "num_lines": 6}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#/bin/sh\ngcc `echo $@ | sed -e 's/\\/cygdrive\\/\\([a-zA-Z]\\)\\//\\1:\\//g'`\n", "num_lines": 3}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (C) 2008-2019, Marvell International Ltd.\n# All Rights Reserved.\n#\n# This script can be invoked to resolve the dependencies required for wmsdk\n# application development.\n#\n#set -x\n\nif [ `uname` != \"Linux\" ]; then\n\techo \"This script is meant for only Linux Platforms\"\n\techo \"Exiting .... \"\n\texit 1\nfi\n\nconnectivity=0\nFILE=\"/tmp/tmpcon\"\nSCRIPT_DIR=`dirname $0`\n\nfed=$(cat /etc/issue | grep -c \"Fedora\")\nubu=$(cat /etc/issue | grep -c \"Ubuntu\")\nFED_PKGS=\"gcc-c++ glibc-static libusb libftdi ncurses-libs python texlive-latex openssl-devel ncurses-devel\"\nFED_64_PKGS=\"glibc.i686 libftdi.i686 libusb.i686 ncurses-libs.i686\"\nUBUNTU_PKGS=\"gcc libusb-dev libftdi-dev libncursesw5 python libssl-dev\"\nUBUNTU_64_PKGS=\"lib32ncursesw5 lib32z1 lib32ncurses5 libbz2-1.0:i386 libncurses5-dev lib32ncurses5-dev libncursesw5-dev\"\nVERSION=`uname -m`\n\ncheck_connectivity()\n{\n\tif [ $fed -gt 0 ]; then\n\t\tURL=\"www.fedoraproject.org\"\n\tfi\n\n\tif [ $ubu -gt 0 ]; then\n\t\tURL=\"www.ubuntu.com\"\n\tfi\n\n\techo -n \"Checking for internet connection...\"\n\twget $URL -O /dev/null -o $FILE\n\tif [ $(tail -5  $FILE | grep -c \"saved\") ]; then\n\t\techo \"ok.\"\n\t\tconnectivity=1\n\telse\n\t\techo \"failed.\"\n\t\tconnectivity=0\n\tfi\n}\n\ncheck_connectivity\nif [ $fed -gt 0 ]; then\n\tif [ $connectivity == 1 ]; then\n\t\techo \"\"\n\t\techo \"Installing packages, enter root password:\"\n\t\tsu - root -c \"yum install $FED_PKGS\"\n\t\tif [ $VERSION == \"x86_64\" ]; then\n\t\t    su - root -c \"yum install $FED_64_PKGS\"\n\t\tfi\n\telse\n\t\techo \"Cannot access the said package servers. Please install the following packages manually\"\n\t        echo \"$FED_PKGS\"\n\tfi\nfi\n\nif [ $ubu -gt 0 ]; then\n\tif [ $connectivity == 1 ]; then\n\t\tsudo apt-get update\n\t\tsudo apt-get install $UBUNTU_PKGS\n\t\tif [ $VERSION == \"x86_64\" ]; then\n\t\t    sudo apt-get install $UBUNTU_64_PKGS\n\t\tfi\n\telse\n\t\techo \"Cannot access the said package servers. Please install the following packages manually:\"\n\t\techo \"$UBUNTU_PKGS\"\n\tfi\nfi\n\nrm -f $FILE\n\n", "num_lines": 80}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (C) 2008-2019, Marvell International Ltd.\n# All Rights Reserved.\n#\n# This script can be invoked to add linux user to groups 'plugdev'\n# and 'dialout', and add udev rules for OpenOCD. After this step,\n# sudo is not required for invoking OpenOCD or serial console.\n# For eclipse and arm-none-eabi-gdb users, this step is mandatory.\n#\n#set -x\n\nif [ `uname` != \"Linux\" ]; then\n\techo \"This script is meant for only Linux Platforms\"\n\techo \"Exiting .... \"\n\texit 1\nfi\n\nSCRIPT_DIR=`dirname $0`\nUSER_NAME=$USER\n\nadd_user_groups()\n{\n\techo \"\"\n\techo \"* To use OpenOCD and serial console without root privileges, user '$USER_NAME' needs\"\n\techo \"* to be added to groups 'plugdev' and 'dialout'. After this, user needs to logout\"\n\techo \"* and login once for settings to take effect.\"\n\techo \"** For eclipse and arm-none-eabi-gdb users, this step is mandatory.\"\n\tread -p \"> Add user '$USER_NAME' to groups 'plugdev' and 'dialout' [y/N]? \" OK\n\tif [ \"$OK\" == 'y' ] || [ \"$OK\" == 'Y' ]; then\n\t\tif [ ! -e /etc/udev/rules.d/99-openocd.rules ]; then\n\t\t\tsudo cp $SCRIPT_DIR/99-openocd.rules /etc/udev/rules.d/\n\t\t\tsudo udevadm control --reload-rules\n\t\t\tsudo udevadm trigger\n\t\tfi\n\t\tgetent group plugdev > /dev/null || sudo groupadd plugdev\n\t\tsudo usermod -a -G dialout,plugdev $USER_NAME\n\t\tread -p \"> Please logout and login again after script is finished. OK? \" OK\n\telse\n\t\tread -p \"> Please use sudo to invoke OpenOCD and serial console. OK? \" OK\n\tfi\n\techo \"\"\n}\n\nadd_user_groups\n", "num_lines": 46}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script will use git (must be in $PATH) and arm-none-eabi tools in combination with GNU Make\n# to both fetch and compile all variants of micro-ecc for the nRF5 families\n\nif ! [ -x \"$(command -v git)\" ]; then\n    echo 'git is not installed. Please install and append to PATH.' >&2\n    exit\nfi\n\nif [ ! -f micro-ecc/uECC.c ]; then\n    echo \"micro-ecc not found! Let's pull it from HEAD.\"\n    git clone https://github.com/kmackay/micro-ecc.git\nfi\n\nmake -C nrf51_armgcc/armgcc &&\nmake -C nrf51_iar/armgcc &&\nmake -C nrf51_keil/armgcc &&\nmake -C nrf52hf_armgcc/armgcc &&\nmake -C nrf52hf_iar/armgcc &&\nmake -C nrf52hf_keil/armgcc &&\nmake -C nrf52nf_armgcc/armgcc &&\nmake -C nrf52nf_iar/armgcc &&\nmake -C nrf52nf_keil/armgcc\n", "num_lines": 25}
{"repo_name": "amazon-freertos", "repo_creator": "aws", "programming_language": "Shell", "code": "rm -rf html\ndoxygen nrfx.doxyfile\n", "num_lines": 3}
{"repo_name": "amazon-freertos-ble-ios-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "cd \"${SRCROOT}\"\n\"${PODS_ROOT}/LicensePlist/license-plist\" --output-path \"${SRCROOT}/AmazonFreeRTOSDemo/Support/Settings.bundle\" --prefix \"com.amazonaws.AmazonFreeRTOSDemo\"\n", "num_lines": 3}
{"repo_name": "amazon-freertos-ble-ios-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "\"${PODS_ROOT}/SwiftFormat/CommandLineTool/swiftformat\" \"${SRCROOT}\" --config \"${SRCROOT}/.swiftformat\"\n", "num_lines": 2}
{"repo_name": "amazon-freertos-ble-ios-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "xcodebuild -workspace AmazonFreeRTOSDemo.xcworkspace -scheme AmazonFreeRTOSDemo > xcodebuild.log\n./Pods/SwiftLint/swiftlint analyze --compiler-log-path ./xcodebuild.log", "num_lines": 2}
{"repo_name": "amazon-freertos-ble-ios-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "\"${PODS_ROOT}/SwiftLint/swiftlint\"", "num_lines": 1}
{"repo_name": "amazon-freertos-ble-ios-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "xunique \"${PROJECT_FILE_PATH}/project.pbxproj\"\n", "num_lines": 2}
{"repo_name": "amazon-ivs-react-native-player", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Creates an .env from ENV variables for use with react-native-config\nENV_WHITELIST=${ENV_WHITELIST:-\"^RN_\"}\nprintf \"Creating an .env file with the following whitelist:\\n\"\nprintf \"%s\\n\" $ENV_WHITELIST\nset | egrep -e $ENV_WHITELIST | sed 's/^RN_//g' > .env\nprintf \"\\n.env created with contents:\\n\\n\"\ncat .env\n\n# create dynamically app-center config based on .env variable\nif [ $RN_APP_SECRET_ANDROID ]\nthen\n  json_template='{\"app_secret\":\"%s\"}\\n'\n  json_string=$(printf \"$json_template\" \"$RN_APP_SECRET_ANDROID\")\n  file=\"./android/app/src/main/assets/appcenter-config.json\"\n  echo $json_string > $file\n  cat $file\nfi\n", "num_lines": 20}
{"repo_name": "amazon-kinesis-firehose-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the\n# \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR\n# CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script wraps the mockgen tool and inserts licensing information.\n\nset -e\npackage=${1?Must provide package}\ninterfaces=${2?Must provide interface names}\noutputfile=${3?Must provide an output file}\n\nexport PATH=\"${GOPATH//://bin:}/bin:$PATH\"\n\ndata=$(\ncat << EOF\n// Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n// not use this file except in compliance with the License. A copy of the\n// License is located at\n//\n//     http://aws.amazon.com/apache2.0/\n//\n// or in the \"license\" file accompanying this file. This file is distributed\n// on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language governing\n// permissions and limitations under the License.\n\n$(mockgen \"$package\" \"$interfaces\")\nEOF\n)\n\necho \"$data\" | goimports > \"${outputfile}\"\n", "num_lines": 45}
{"repo_name": "amazon-neptune-jdbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one\n# or more contributor license agreements.  See the NOTICE file\n# distributed with this work for additional information\n# regarding copyright ownership.  The ASF licenses this file\n# to you under the Apache License, Version 2.0 (the\n# \"License\"); you may not use this file except in compliance\n# with the License.  You may obtain a copy of the License at\n#\n#   http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing,\n# software distributed under the License is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n# KIND, either express or implied.  See the License for the\n# specific language governing permissions and limitations\n# under the License.\n#\n\n### BEGIN INIT INFO\n# Provides:          gremlin-server\n# Required-Start:    $remote_fs $syslog $network\n# Required-Stop:     $remote_fs $syslog $network\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# Short-Description: Gremlin Server\n# Description:       Apache Tinkerpop Gremlin Server\n# chkconfig:         2345 98 01\n### END INIT INFO\n\n[[ -n \"$DEBUG\" ]] && set -x\n\nSOURCE=\"$0\"\nwhile [[ -h \"$SOURCE\" ]]; do\n  cd -P \"$( dirname \"$SOURCE\" )\" || exit 1\n  DIR=\"$(pwd)\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\"\ndone\ncd -P \"$( dirname \"$SOURCE\" )\" || exit 1\nGREMLIN_BIN=\"$(pwd)\"\n\nGREMLIN_CONF=$GREMLIN_BIN/gremlin-server.conf\n\n[[ -r $GREMLIN_CONF ]] && source $GREMLIN_CONF\n[[ -n \"$DEBUG\" ]] && set -x\n\nif [[ -z \"$GREMLIN_HOME\" ]]; then\n  cd ..\n  GREMLIN_HOME=\"$(pwd)\"\nfi\n\nif [[ -z \"$LOG_DIR\" ]] ; then\n  LOG_DIR=\"$GREMLIN_HOME/logs\"\nfi\n\nif [[ -z \"$LOG_FILE\" ]]; then\n  LOG_FILE=\"$LOG_DIR/gremlin.log\"\nfi\n\nif [[ -z \"$PID_DIR\" ]] ; then\n  PID_DIR=\"$GREMLIN_HOME/run\"\nfi\n\nif [[ -z \"$PID_FILE\" ]]; then\n  PID_FILE=$PID_DIR/gremlin.pid\nfi\n\nif [[ -z \"$GREMLIN_YAML\" ]]; then\n  GREMLIN_YAML=$GREMLIN_HOME/conf/gremlin-server.yaml\nfi\n\nif [[ ! -r \"$GREMLIN_YAML\" ]]; then\n  # try relative to home\n  GREMLIN_YAML=\"$GREMLIN_HOME/$GREMLIN_YAML\"\n  if [[ ! -r \"$GREMLIN_YAML\" ]]; then\n    echo WARNING: $GREMLIN_YAML is unreadable\n  fi\nfi\n\n# absolute file path requires 'file:'\nLOG4J_CONF=\"file:$GREMLIN_HOME/conf/log4j-server.properties\"\n\n# Find Java\nif [[ \"$JAVA_HOME\" = \"\" ]] ; then\n    JAVA=\"java\"\nelse\n    JAVA=\"$JAVA_HOME/bin/java\"\nfi\n\n# Set Java options\nif [[ \"$JAVA_OPTIONS\" = \"\" ]] ; then\n    JAVA_OPTIONS=\"-Xms512m -Xmx4096m\"\nfi\n\n# Build Java CLASSPATH\nCP=\"$GREMLIN_HOME/conf/\"\nCP=\"$CP\":$( echo $GREMLIN_HOME/lib/*.jar . | sed 's/ /:/g')\nCP=\"$CP\":$( find -L \"$GREMLIN_HOME\"/ext -mindepth 1 -maxdepth 1 -type d | \\\n        sort | sed 's/$/\\/plugin\\/*/' | tr '\\n' ':' )\n\nCLASSPATH=\"${CLASSPATH:-}:$CP\"\n\nGREMLIN_SERVER_CMD=org.apache.tinkerpop.gremlin.server.GremlinServer\nGREMLIN_INSTALL_CMD=org.apache.tinkerpop.gremlin.server.util.GremlinServerInstall\n\n\nisRunning() {\n  if [[ -r \"$PID_FILE\" ]] ; then\n    PID=$(cat \"$PID_FILE\")\n    ps -p \"$PID\" &> /dev/null\n    return $?\n  else\n    return 1\n  fi\n}\n\nstatus() {\n  isRunning\n  RUNNING=$?\n    if [[ $RUNNING -gt 0 ]]; then\n      echo Server not running\n    else\n      echo Server running with PID $(cat \"$PID_FILE\")\n    fi\n}\n\nstop() {\n  isRunning\n  RUNNING=$?\n  if [[ $RUNNING -gt 0 ]]; then\n    echo Server not running\n    rm -f \"$PID_FILE\"\n  else\n    kill \"$PID\" &> /dev/null || { echo \"Unable to kill server [$PID]\"; exit 1; }\n    for i in $(seq 1 60); do\n      ps -p \"$PID\" &> /dev/null || { echo \"Server stopped [$PID]\"; rm -f \"$PID_FILE\"; return 0; }\n      [[ $i -eq 30 ]] && kill \"$PID\" &> /dev/null\n      sleep 1\n    done\n    echo \"Unable to kill server [$PID]\";\n    exit 1;\n  fi\n}\n\nstart() {\n  isRunning\n  RUNNING=$?\n  if [[ $RUNNING -eq 0 ]]; then\n    echo Server already running with PID $(cat \"$PID_FILE\").\n    exit 1\n  fi\n\n  if [[ -z \"$RUNAS\" ]]; then\n\n    mkdir -p \"$LOG_DIR\" &>/dev/null\n    if [[ ! -d \"$LOG_DIR\" ]]; then\n      echo ERROR: LOG_DIR $LOG_DIR does not exist and could not be created.\n      exit 1\n    fi\n\n    mkdir -p \"$PID_DIR\" &>/dev/null\n    if [[ ! -d \"$PID_DIR\" ]]; then\n      echo ERROR: PID_DIR $PID_DIR does not exist and could not be created.\n      exit 1\n    fi\n\n    $JAVA -Dlog4j.configuration=$LOG4J_CONF $JAVA_OPTIONS -cp $CLASSPATH $GREMLIN_SERVER_CMD \"$GREMLIN_YAML\" >> \"$LOG_FILE\" 2>&1 &\n    PID=$!\n    disown $PID\n    echo $PID > \"$PID_FILE\"\n  else\n\n    su -c \"mkdir -p $LOG_DIR &>/dev/null\"  \"$RUNAS\"\n    if [[ ! -d \"$LOG_DIR\" ]]; then\n      echo ERROR: LOG_DIR $LOG_DIR does not exist and could not be created.\n      exit 1\n    fi\n\n    su -c \"mkdir -p $PID_DIR &>/dev/null\"  \"$RUNAS\"\n    if [[ ! -d \"$PID_DIR\" ]]; then\n      echo ERROR: PID_DIR $PID_DIR does not exist and could not be created.\n      exit 1\n    fi\n\n    su -c \"$JAVA -Dlog4j.configuration=$LOG4J_CONF $JAVA_OPTIONS -cp $CLASSPATH $GREMLIN_SERVER_CMD \\\"$GREMLIN_YAML\\\" >> \\\"$LOG_FILE\\\" 2>&1 & echo \\$! \"  \"$RUNAS\" > \"$PID_FILE\"\n    chown \"$RUNAS\" \"$PID_FILE\"\n  fi\n\n  isRunning\n  RUNNING=$?\n  if [[ $RUNNING -eq 0 ]]; then\n    echo Server started $(cat \"$PID_FILE\").\n    exit 0\n  else\n    echo Server failed\n    exit 1\n  fi\n\n}\n\nstartForeground() {\n  isRunning\n  RUNNING=$?\n  if [[ $RUNNING -eq 0 ]]; then\n    echo Server already running with PID $(cat \"$PID_FILE\").\n    exit 1\n  fi\n\n  if [[ -z \"$RUNAS\" ]]; then\n    $JAVA -Dlog4j.configuration=$LOG4J_CONF $JAVA_OPTIONS -cp $CLASSPATH $GREMLIN_SERVER_CMD \"$GREMLIN_YAML\"\n    exit 0\n  else\n    echo Starting in foreground not supported with RUNAS\n    exit 1\n  fi\n\n}\n\ninstall() {\n\n  isRunning\n  RUNNING=$?\n  if [[ $RUNNING -eq 0 ]]; then\n    echo Server must be stopped before installing.\n    exit 1\n  fi\n\n  echo Installing dependency $@\n\n  DEPS=\"$@\"\n  if [[ -z \"$RUNAS\" ]]; then\n    $JAVA -Dlog4j.configuration=$LOG4J_CONF $JAVA_OPTIONS -cp $CLASSPATH $GREMLIN_INSTALL_CMD $DEPS\n  else\n    su -c \"$JAVA -Dlog4j.configuration=$LOG4J_CONF $JAVA_OPTIONS -cp $CLASSPATH $GREMLIN_INSTALL_CMD $DEPS \"  \"$RUNAS\"\n  fi\n\n}\n\ncase \"$1\" in\n  status)\n    status\n    ;;\n  restart)\n    stop\n    start\n    ;;\n  start)\n    start\n    ;;\n  stop)\n    stop\n    ;;\n  install)\n    shift\n    install \"$@\"\n    ;;\n  console)\n    startForeground\n    ;;\n  *)\n    if [[ -n \"$1\" ]] ; then\n      if [[ -r \"$1\" ]]; then\n        GREMLIN_YAML=\"$1\"\n        startForeground\n      elif [[ -r \"$GREMLIN_HOME/$1\" ]] ; then\n        GREMLIN_YAML=\"$GREMLIN_HOME/$1\"\n        startForeground\n      fi\n      echo Configuration file not found.\n    fi\n    echo \"Usage: $0 {start|stop|restart|status|console|install <group> <artifact> <version>|<conf file>}\"\n    echo\n    echo \"    start        Start the server in the background using conf/gremlin-server.yaml as the\"\n    echo \"                 default configuration file\"\n    echo \"    stop         Stop the server\"\n    echo \"    restart      Stop and start the server\"\n    echo \"    status       Check if the server is running\"\n    echo \"    console      Start the server in the foreground using conf/gremlin-server.yaml as the\"\n    echo \"                 default configuration file\"\n    echo \"    install      Install dependencies\"\n    echo\n    echo \"If using a custom YAML configuration file then specify it as the only argument for Gremlin\"\n    echo \"Server to run in the foreground or specify it via the GREMLIN_YAML environment variable.\"\n    echo\n    exit 1\n    ;;\nesac\n", "num_lines": 290}
{"repo_name": "amazon-neptune-jdbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -z \"$BASH_SOURCE\"\nthen\n      ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE:-$0}\")\" && pwd)/$(basename \"${BASH_SOURCE:-$0}\")\"\nelse\n      ABSOLUTE_PATH=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$(basename \"${BASH_SOURCE[0]}\")\"\nfi\nCURRENT_FOLDER=\"${ABSOLUTE_PATH%/*}\"\necho \"ABSOLUTEPATH=${ABSOLUTE_PATH}\"\necho \"CURRENT_FOLDER=${CURRENT_FOLDER}\"\nTARGET_FOLDER=\"$CURRENT_FOLDER\"/target\necho TARGET_FOLDER=${TARGET_FOLDER}\nmkdir -p $TARGET_FOLDER\n\necho \"Building Docker Image\"\ndocker build -t taco-builder $CURRENT_FOLDER --progress=plain --no-cache\n\necho \"Assembling Tableau Connector\"\ndocker run -d -it --name=taco-builder --mount type=bind,source=$TARGET_FOLDER,target=/output taco-builder\necho \"Copying Tableau Connector\"\ndocker exec taco-builder sh -c \"cp /tableau-sdk/connector-plugin-sdk/connector-packager/packaged-connector/neptune-jdbc.taco  /output\"\necho \"Verifying Tableau Connector\"\ndocker exec taco-builder sh -c \"ls -l /output\"\ndocker exec taco-builder pwd\necho \"Getting Logs\"\ndocker cp taco-builder:/tableau-sdk/connector-plugin-sdk/connector-packager/packaging_logs.txt $TARGET_FOLDER\necho \"Extracting Tableau Connector\"\ndocker cp taco-builder:/output/neptune-jdbc.taco $TARGET_FOLDER\necho \"Checking Logs and Resulting TACO FILE in $TARGET_FOLDER\"\nls -l $TARGET_FOLDER\ndocker stop taco-builder\ndocker rm taco-builder\n", "num_lines": 34}
{"repo_name": "amazon-redshift-jdbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": " #!/bin/bash\n \n # One option argument is version number.\n # When version needs to change, please provide version in n.n.n.n format. e.g.\n # ./build.sh 2.3.4.5\n\n check_version()\n {\n     MAJOR=$(echo $FULL_VERSION | cut -d'.' -f1)\n     MINOR=$(echo $FULL_VERSION | cut -d'.' -f2)\n     PATCH=$(echo $FULL_VERSION | cut -d'.' -f3) \n     RELEASE=$(echo $FULL_VERSION | cut -d'.' -f4)\n     EXTRA=$(echo $FULL_VERSION | cut -d'.' -f5)\n\n     if [ \"$MAJOR\" == \"\" ] || [ \"$MINOR\" == \"\" ] || [ \"$PATCH\" == \"\" ] || [ \"$RELEASE\" == \"\" ] || [ \"$EXTRA\" != \"\" ];\n     then\n         echo Invalid version format: $FULL_VERSION. please give it in n.n.n.n format.\n         exit 1\n     fi\n }\n\n if [ \"$1\" != \"\" ];\n then\n    # check version\n    FULL_VERSION=$1\n    check_version \n    echo \"version=${FULL_VERSION}\" >|./src/main/resources/redshift_jdbc_driver.properties\n    mvn versions:set -DartifactId=redshift-jdbc42 -DnewVersion=$1\n    mvn versions:commit\n fi\n\n#mvn install:install-file -Dfile=lib/aws-java-sdk-redshift-internal-1.12.x.jar -DgroupId=com.amazonaws -DartifactId=aws-java-sdk-redshift-internal -Dversion=1.12.x -Dpackaging=jar -DgeneratePom=true\n\n#mvn install:install-file -Dfile=lib/aws-java-sdk-redshift-arcadia-internal-1.0.jar -DgroupId=com.amazonaws -DartifactId=aws-java-sdk-redshift-arcadia-internal -Dversion=1.0 -Dpackaging=jar -DgeneratePom=true\n\nmvn -P release-artifacts clean install\n", "num_lines": 37}
{"repo_name": "amazon-redshift-jdbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": " #!/bin/bash\n \n # One option argument is version number.\n # When version needs to change, please provide version in n.n.n.n format. e.g.\n # ./build.sh 2.3.4.5\n\n check_version()\n {\n     MAJOR=$(echo $FULL_VERSION | cut -d'.' -f1)\n     MINOR=$(echo $FULL_VERSION | cut -d'.' -f2)\n     PATCH=$(echo $FULL_VERSION | cut -d'.' -f3) \n     RELEASE=$(echo $FULL_VERSION | cut -d'.' -f4)\n     EXTRA=$(echo $FULL_VERSION | cut -d'.' -f5)\n\n     if [ \"$MAJOR\" == \"\" ] || [ \"$MINOR\" == \"\" ] || [ \"$PATCH\" == \"\" ] || [ \"$RELEASE\" == \"\" ] || [ \"$EXTRA\" != \"\" ];\n     then\n         echo Invalid version format: $FULL_VERSION. please give it in n.n.n.n format.\n         exit 1\n     fi\n }\n\n FULL_VERSION=\"2.0.0.0\"\n\n if [ \"$1\" != \"\" ];\n then\n    # check version\n    FULL_VERSION=$1\n    check_version \n fi\n\n ./gradlew -PbuildVersion=$FULL_VERSION clean build javadoc\n\n\n", "num_lines": 34}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh [n.n.n n]\n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\necho Building 64 bit Linux Redshift ODBC Driver\n\nodbc_version=$1\nsvn_rev=$2\n\n# Build libpq & libpgport\ncd ./src/pgclient\n./build64.sh\ncheckExitCode $?\n\n# Build ODBC Driver Shared Object\ncd ../odbc/rsodbc\n./build64.sh $odbc_version $svn_rev\ncheckExitCode $?\n\ncd ../../..\n\nexit $?\n", "num_lines": 30}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh n.n.n n\n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\nodbc_version=$1\nsvn_rev=$2\nodbc_driver_full_version=\"${odbc_version}.${svn_rev}\"\n\necho $odbc_version\necho $svn_rev\necho $odbc_driver_full_version\n\necho Setting REDSHIFT_DRIVER_VERSION to $odbc_driver_full_version in rsodbc_setup/version.h\nsed -i \"s/#define REDSHIFT_DRIVER_VERSION.*/#define REDSHIFT_DRIVER_VERSION         \\\"${odbc_driver_full_version}\\\"/g\" rsodbc_setup/version.h\n\necho Setting Driver version in rsversion.h\nmajor=$(echo $odbc_version | cut -d '.' -f1)\nminor=$(echo $odbc_version | cut -d '.' -f2)\npatch=$(echo $odbc_version | cut -d '.' -f3)\n\npadded_full_version=$(printf \"%02d.%02d.%04d\\n\" \"$major\" \"$minor\" \"$patch\")\nsed -i \"s/#define ODBC_DRIVER_VERSION.*/#define ODBC_DRIVER_VERSION \\\"$padded_full_version\\\"/g\" rsversion.h\n\nsed -i \"s/#define FILEVER.*/#define FILEVER        $major,$minor,$patch,$svn_rev/g\" rsversion.h\nsed -i \"s/#define PRODUCTVER.*/#define PRODUCTVER     $major,$minor,$patch,$svn_rev/g\" rsversion.h\nsed -i \"s/#define STRFILEVER.*/#define STRFILEVER     \\\"$major, $minor, $patch, $svn_rev\\\\\\0\\\"/g\" rsversion.h \nsed -i \"s/#define STRPRODUCTVER.*/#define STRPRODUCTVER  \\\"$major, $minor, $patch, $svn_rev\\\"/g\" rsversion.h\n\necho Building 64 bit Linux Amazon Redshift ODBC Driver\n\ncd Release\nmake clean\ncheckExitCode $?\nmake\ncheckExitCode $?\n\necho Done building 64 bit Linux Amazon Redshift ODBC Driver\n\ncd ..\n\nexit $?\n", "num_lines": 49}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./clean64.sh\n\ncd Release\nmake clean\n\necho Done Cleaning 64 bit Linux Amazon Redshift ODBC Driver Build\n\ncd ..\n\n", "num_lines": 11}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#sudo ./create64bit-rpm.sh xyz\n\n# This routine packages the 64 bit rpm\nodbc_version=$1\nsvn_rev=$2\n\n\nif [ ! -d ./rpm ]\nthen\n\tmkdir -p ./rpm\nfi\n\n\nspec_file=rs-${odbc_version}-${svn_rev}-64.spec\n\n# Create the stamped 64 bit spec file\necho Creating the 64 bit stamped spec file..\nsed \"s|Version:.*$|Version: ${odbc_version} |\" < odbc_x64.spec > tt\nsed \"s|Name:.*$|Name: AmazonRedshiftODBC-64-bit |\" < tt > tt2\nsed \"s|Release:.*$|Release: ${svn_rev} |\" < tt2 > temp64.spec\ncat temp64.spec | tr -d \"\\r\" > $spec_file\n\nif [ $? -ne 0 ]\nthen\n    exit $?\nfi\nrm temp64.spec\nrm tt\nrm tt2\n\n\n# Copy the files to stage for RPM creation\nif [ -d \"/tmp/redshiftodbcx64\" ]\nthen\n   rm -Rf /tmp/redshiftodbcx64\nfi\n\nmkdir -p /tmp/redshiftodbcx64\nmkdir -p /tmp/redshiftodbcx64/samples/connect\n\ncp ./Release/librsodbc64.so /tmp/redshiftodbcx64/\ncp ./amazon.redshiftodbc.ini  /tmp/redshiftodbcx64/\ncp ./root.crt /tmp/redshiftodbcx64/\ncp ./odbc.ini.x64  /tmp/redshiftodbcx64/odbc.ini\ncp ./odbcinst.ini.x64 /tmp/redshiftodbcx64/odbcinst.ini\ncp ./odbc.csh.x64 /tmp/redshiftodbcx64/odbc.csh\ncp ./odbc.sh.x64 /tmp/redshiftodbcx64/odbc.sh\n\ncp ./samples/connect/connect.c /tmp/redshiftodbcx64/samples/connect/\ncp ./samples/connect/connect.mak /tmp/redshiftodbcx64/samples/connect/connect.mak\ncp ./samples/connect/connect64 /tmp/redshiftodbcx64/samples/connect/connect\n\ncp ./rsodbcsql/Release/rsodbcsql /tmp/redshiftodbcx64/\n\n# This is the directory used by RPMBUILD\ncp -avrf /tmp/redshiftodbcx64/ /var/tmp/redshiftodbcx64/ \n\n# Set rpm_src for EL5\n#rpm_src=/usr/src/rpm/RPMS/x86_64/AmazonRedshiftODBC-64-bit-${odbc_version}-${svn_rev}.x86_64.rpm\n\n# Set rpm_src for EL7\nrpm_src=$HOME/rpmbuild/RPMS/x86_64/AmazonRedshiftODBC-64-bit-${odbc_version}-${svn_rev}.x86_64.rpm\nrpm_new_name=AmazonRedshiftODBC-64-bit-${odbc_version}.${svn_rev}.x86_64.rpm\n\n# Build the 64 bit rpm \necho Running the 64 bit rpm build using this spec file: $spec_file\nrpmbuild -v --target x86_64 -bb $spec_file\nif [ $? -ne 0 ]\nthen\n    exit $?\nfi\n\nrm -rf /var/tmp/redshiftodbcx64\nrm -rf /tmp/redshiftodbcx64\nrm rs-${odbc_version}-${svn_rev}-64.spec\n\n# Move the 64 bit file to the current working directory\necho Moving the 64 bit rpm to the rpm folder..\nrm ./rpm/$rpm_new_name\nmv $rpm_src ./rpm/$rpm_new_name\nif [ $? -ne 0 ]\nthen\n    exit $?\nfi\n\nexit $?\n", "num_lines": 88}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./package64.sh [n.n.n n]\n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\necho Building and Packaging 64 bit Linux Redshift ODBC Driver\n\n# This routine packages the 64 bit rpm\nodbc_version=$1\nsvn_rev=$2\n\n# Build libpq & libpgport\ncd ../../pgclient\n./build64.sh\ncheckExitCode $?\n\n# Build ODBC Driver Shared Object\ncd ../odbc/rsodbc\n./build64.sh $odbc_version $svn_rev\ncheckExitCode $?\n\n# Build ODBC Driver Samples\ncd ./samples\n./build64.sh\ncheckExitCode $?\ncd ..\n\n# Build rsodbcsql\ncd ./rsodbcsql\n./build64.sh\ncheckExitCode $?\ncd ..\n\n\n# Now make the installer using RPM label provided\n./create64bit-rpm.sh ${odbc_version} ${svn_rev}\ncheckExitCode $?\n\necho Please get RPM package under \"./rpm\" directory.\n\nexit $?\n", "num_lines": 48}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh\n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\necho Building 64 bit Linux rsodbcsql\n\ncd Release\nmake  clean\ncheckExitCode $?\nmake\ncheckExitCode $?\ncd ..\n\necho Done building 64 bit Linux rsodbcsql\n\nexit $?\n", "num_lines": 24}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./clean64.sh\n\necho Cleaning 64 bit Linux rsodbcsql Build\n\ncd Release\nmake  clean\ncd ..\n\necho Done cleaning 64 bit Linux rsodbcsql Build\n\n", "num_lines": 12}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh \n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\necho Building 64 bit Linux Amazon Redshift Analytic Platform ODBC Driver Samples\n\ncd connect\n./build64.sh\ncheckExitCode $?\ncd ..\n\necho Done building 64 bit Linux Amazon Redshift Analytic Platform ODBC Driver Samples\n\nexit $?\n", "num_lines": 22}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./clean64.sh \n\necho Cleaning 64 bit Linux Amazon Redshift ODBC Driver Samples Build\n\ncd connect\n./clean64.sh\ncd ..\n\necho Done cleaning 64 bit Linux Amazon Redshift ODBC Driver Samples Build\n\n", "num_lines": 12}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh \n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\necho Building 64 bit Linux Amazon Redshift ODBC Driver connect Sample\n\nrm ./connect64\nmake -f connect.mak clean\nmake -f connect.mak\ncheckExitCode $?\nmv ./connect ./connect64\ncheckExitCode $?\n\necho Done building 64 bit Linux Amazon Redshift ODBC Driver connect Sample\n\nexit $?\n", "num_lines": 24}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./clean64.sh \n\necho Cleaning 64 bit Linux Amazon Redshift ODBC Driver connect Sample Build\n\nrm ./connect64\nmake -f connect.mak clean\n\necho Done cleaning 64 bit Linux Amazon Redshift ODBC Driver connect Sample Build\n\nexit $?\n", "num_lines": 12}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./build64.sh \n\nfunction checkExitCode {\n  retVal=$1;\n\n  if [ \"$retVal\" != 0 ]; then\n    exit $retVal;\n  fi\n}\n\n# Command-line switch to prevent removing of header files\nkeepFlag=on\nwhile [ $# -gt 0 ]\ndo\n  case \"$1\" in\n    -k)  keepFlag=on;;\n  esac\n  shift\ndone\n\necho Building 64 bit Linux 9.1.2 libpq\n\ncd src/interfaces/libpq\nmake clean\ncheckExitCode $?\ncd ../../port\nmake clean\ncheckExitCode $?\ncd ../..\n\ncp src/include/pg_config.h.linux64 src/include/pg_config.h\ncheckExitCode $?\ncp src/include/pg_config_os.h.linux64 src/include/pg_config_os.h\ncheckExitCode $?\n\ncd src/interfaces/libpq\nmake\ncheckExitCode $?\n\nif [ ! -d ./Release ]\nthen\n\tmkdir -p ./Release\nfi\n\nmv libpq.a ./Release/\ncheckExitCode $?\n\necho Done building 64 bit Linux 9.1.2 libpq\n\necho Building 64 bit Linux 9.1.2 libpgport\n\ncd ../../port\nmake\ncheckExitCode $?\n\nif [ ! -d ./Release ]\nthen\n\tmkdir -p ./Release\nfi\n\nmv libpgport.a ./Release/\ncheckExitCode $?\n\necho Done building 64 bit Linux 9.1.2 libpgport\n\ncd ../..\n\nif [ \"$keepFlag\" != \"on\" ];\nthen\n  rm  src/include/pg_config.h\n  rm  src/include/pg_config_os.h\n  rm  src/port/pg_config_paths.h\nfi\n\nexit $?\n", "num_lines": 77}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#./clean64.sh \n\necho Cleaning 64 bit Linux 9.1.2 libpq build\n\ncd src/interfaces/libpq\nmake clean\ncd ../../port\nmake clean\ncd ../..\n\necho Done cleaning 64 bit Linux 9.1.2 libpgport build\n\n", "num_lines": 14}
{"repo_name": "amazon-redshift-odbc-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Build libpq 9.1.2 with PA changes\n\ncp ../../include/pg_config.h.linux64 ../../include/pg_config.h\ncp ../../include/pg_config_os.h.linux64 ../../include/pg_config_os.h\nmake\n\n", "num_lines": 8}
{"repo_name": "amazon-redshift-python-driver", "repo_creator": "aws", "programming_language": "Shell", "code": "python3 setup.py sdist bdist_wheel\n", "num_lines": 2}
{"repo_name": "amazon-s3-encryption-client-java", "repo_creator": "aws", "programming_language": "Shell", "code": "## Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n## SPDX-License-Identifier: Apache-2.0\n\n#!bin/bash\n\nset -x\n\nVERSION=$1\nCOUNTER=0\nSTATUS=1\n\necho \"Looking for version $VERSION\"\n\nwhile [  $STATUS -ne 0 ]; do\n    mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.1:get \\\n        -Dartifact=software.amazon.encryption.s3:amazon-s3-encryption-client-java:$VERSION -U\n\n    STATUS=$?\n    if [ $STATUS -eq 0 ]; then\n        echo \"Found version $VERSION in Maven Central :)\"\n        break\n    fi\n\n    if [  $((COUNTER+=1)) -eq 15 ]; then\n        echo \"It has been an awfully long time, you should check Maven Central for issues\"\n        exit 1\n    fi\n\n    echo \"Could not find version $VERSION. Trying again.\"\n    sleep 60\ndone\n", "num_lines": 32}
{"repo_name": "amazon-s3-plugin-for-pytorch", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\necho \"Testing: import awsio\"\npython -c \"import awsio; print(awsio.__version__)\"\necho \"import awsio succeeded\"\n\nread -p \"S3 URL : \" s3_url\necho Testing: checking setup by quering whether or not $s3_url is an existing file\npython -c \"from awsio.python.lib.io.s3.s3dataset import file_exists; print(f\\\"file_exists: {file_exists($s3_url)}\\\")\"\necho Smoke test was successful.\n\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-2.0.3-1.docker17.09.1.ce.amzn1\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get account\naccount=${1}\n\n# Get the region defined in the current configuration\nregion=${2:-us-east-1}\n\n# The name of our algorithm\nalgorithm_name=${3:-sagemaker-autogluon-inference}\n\nuri_prefix=${4}\nfullname=\"${uri_prefix}/${algorithm_name}:latest\"\n\n# Get the registry id\nregistry_id=${5}\nregistry_uri=${6}\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${algorithm_name}\" > /dev/null 2>&1\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --region ${region} --repository-name \"${algorithm_name}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\n$(aws ecr get-login --registry-ids ${registry_id} --region ${region} --no-include-email)\n    \n# Build the docker image, tag with full name and then push it to ECR\ndocker build -t ${algorithm_name} -f container-inference/Dockerfile.inference . --build-arg REGISTRY_URI=${registry_uri}\ndocker tag ${algorithm_name} ${fullname}\ndocker push ${fullname}\n", "num_lines": 34}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get account\naccount=${1}\n\n# Get the region defined in the current configuration\nregion=${2:-us-east-1}\n\n# The name of our algorithm\nalgorithm_name=${3:-sagemaker-autogluon-training}\n\nuri_prefix=${4}\nfullname=\"${uri_prefix}/${algorithm_name}:latest\"\n\n# Get the registry id\nregistry_id=${5}\nregistry_uri=${6}\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${algorithm_name}\" > /dev/null 2>&1\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --region ${region} --repository-name \"${algorithm_name}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\n$(aws ecr get-login --registry-ids ${registry_id} --region ${region} --no-include-email)\n\n# Build the docker image, tag with full name and then push it to ECR\ndocker build -t ${algorithm_name} -f container-training/Dockerfile.training . --build-arg REGISTRY_URI=${registry_uri}\ndocker tag ${algorithm_name} ${fullname}\ndocker push ${fullname}\n", "num_lines": 34}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\nchmod +x causal_nex/train\nchmod +x causal_nex/serve\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${account}\".dkr.ecr.\"${region}\".amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-application/json}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\nmkdir -p test_dir/model\nmkdir -p test_dir/output\n\nrm test_dir/model/*\nrm test_dir/output/*\n\ndocker run -v $(pwd)/test_dir:/opt/ml --rm ${image} train\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\n$(aws ecr get-login --no-include-email --registry-ids $ACCOUNT_ID)\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ncd ../package/ && python setup.py sdist && cp dist/custom_framework_training-1.0.0.tar.gz ../docker/code/\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\n$(aws ecr get-login --no-include-email --registry-ids $ACCOUNT_ID)\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 16}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\n$(aws ecr get-login --no-include-email --registry-ids $ACCOUNT_ID)\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\n$(aws ecr get-login --no-include-email --registry-ids $ACCOUNT_ID)\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ \"$#\" -ne 1 ]; then\n    echo \"usage: $0 <s3-bucket-name>\"\n    exit 1\nfi\n\nS3_BUCKET=$1\nS3_PREFIX=\"mask-rcnn/sagemaker/input\"\n\nmounted=$(df -kh | grep \"$HOME/efs\" | wc -l)\nif [ \"$mounted\" -lt \"1\" ]; then\n   echo \"EFS file-system is not mounted\"\n   exit 1\nelse\n   echo \"EFS file-system is mounted\"\n   echo $(df -kh | grep \"$HOME/efs\")\nfi\n\nif [ -d $HOME/efs/$S3_PREFIX ]; then\n    echo \"$HOME/efs/$S3_PREFIX already exists\"\n    exit 1\nfi\nsudo mkdir -p $HOME/efs/$S3_PREFIX\n\necho \"`date`: Copying files from s3://$S3_BUCKET/$S3_PREFIX [ eta 46 minutes ]\"\nsudo aws s3 cp --recursive s3://$S3_BUCKET/$S3_PREFIX $HOME/efs/$S3_PREFIX | awk 'BEGIN {ORS=\"=\"} {if(NR%200==0)print \"=\"}'\necho \"Done.\"\n", "num_lines": 29}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n    echo \"usage: $0 <s3-bucket-name>\"\n    exit 1\nfi\n\nS3_BUCKET=$1\nS3_PREFIX=\"mask-rcnn/sagemaker/input\"\n\n# Stage directory must be on EBS volume with 100 GB available space\nSTAGE_DIR=$HOME/SageMaker/coco-2017-$(date +\"%Y-%m-%d-%H-%M-%S\")\n\necho \"Create stage directory: $STAGE_DIR\"\nmkdir -p $STAGE_DIR\n\nwget -O $STAGE_DIR/train2017.zip http://images.cocodataset.org/zips/train2017.zip\necho \"Extracting $STAGE_DIR/train2017.zip\"\nunzip -o $STAGE_DIR/train2017.zip  -d $STAGE_DIR | awk 'BEGIN {ORS=\"=\"} {if(NR%1000==0)print \"=\"}'\necho \"Done.\"\nrm $STAGE_DIR/train2017.zip\n\nwget -O $STAGE_DIR/val2017.zip http://images.cocodataset.org/zips/val2017.zip\necho \"Extracting $STAGE_DIR/val2017.zip\"\nunzip -o $STAGE_DIR/val2017.zip -d $STAGE_DIR | awk 'BEGIN {ORS=\"=\"} {if(NR%1000==0)print \"=\"}'\necho \"Done.\"\nrm $STAGE_DIR/val2017.zip\n\nwget -O $STAGE_DIR/annotations_trainval2017.zip http://images.cocodataset.org/annotations/annotations_trainval2017.zip\nunzip -o $STAGE_DIR/annotations_trainval2017.zip -d $STAGE_DIR\nrm $STAGE_DIR/annotations_trainval2017.zip\n\nmkdir $STAGE_DIR/pretrained-models\nwget -O $STAGE_DIR/pretrained-models/ImageNet-R50-AlignPadding.npz http://models.tensorpack.com/FasterRCNN/ImageNet-R50-AlignPadding.npz\n\necho \"`date`: Uploading extracted files to s3://$S3_BUCKET/$S3_PREFIX/train [ eta 12 minutes ]\"\naws s3 cp --recursive $STAGE_DIR s3://$S3_BUCKET/$S3_PREFIX/train | awk 'BEGIN {ORS=\"=\"} {if(NR%100==0)print \"=\"}'\necho \"Done.\"\n\necho \"Delete stage directory: $STAGE_DIR\"\nrm -rf $STAGE_DIR\necho \"Success.\"\n", "num_lines": 45}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ $# -lt 5 ]; then\n    echo \"usage: $0 <aws-region> <s3-import-path> <fsx-capacity> <subnet-id> <security-group-id>\"\n    exit 1\nfi\n\n# AWS Region\nAWS_REGION=$1\n\n# S3 import path\nS3_IMPORT_PATH=$2\n\n# FSx storage capacity in multiples of 3600\nSTORAGE_CAPACITY=$3\n\nSUBNET_ID=$4\n\nSG_ID=$5\n\nDATE=`date +%s`\n\n#Customize stack name as needed\nSTACK_NAME=\"fsx-stack-$DATE\"\n\n# cfn template name\nCFN_TEMPLATE='cfn-fsx.yaml'\n\naws cloudformation create-stack --region $AWS_REGION  --stack-name $STACK_NAME \\\n--template-body file://$CFN_TEMPLATE \\\n--capabilities CAPABILITY_NAMED_IAM \\\n--parameters \\\nParameterKey=S3ImportPath,ParameterValue=$S3_IMPORT_PATH \\\nParameterKey=StorageCapacityGiB,ParameterValue=$STORAGE_CAPACITY \\\nParameterKey=SecurityGroupId,ParameterValue=$SG_ID \\\nParameterKey=SubnetId,ParameterValue=$SUBNET_ID \n\necho \"Creating FSx Luster file-system [eta 600 seconds]\"\n\nsleep 30\n\nprogress=$(aws cloudformation list-stacks --stack-status-filter 'CREATE_IN_PROGRESS' | grep $STACK_NAME | wc -l)\nwhile [ $progress -ne 0 ]; do\nlet elapsed=\"`date +%s` - $DATE\"\necho \"Stack $STACK_NAME status: CREATE_IN_PROGRESS: [ $elapsed secs elapsed ]\"\nsleep 30 \nprogress=$(aws cloudformation list-stacks --stack-status-filter 'CREATE_IN_PROGRESS' | grep $STACK_NAME | wc -l)\ndone\nsleep 5 \naws cloudformation describe-stacks --stack-name $STACK_NAME\n", "num_lines": 51}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# AWS Region; customize as needed \nAWS_REGION=\n[[ -z \"${AWS_REGION}\" ]] && echo \"AWS_REGION is required\" && exit 1 \n\n# Cutomize bucket name\nS3_BUCKET=\n[[ -z \"${S3_BUCKET}\" ]] && echo \"S3_BUCKET is required\" && exit 1 \n\nDATE=`date +%s`\n\n#Customize stack name as needed\nSTACK_NAME=\"sm-stack-$DATE\"\n\n# customzie note book instance name as needed\nNOTEBOOK_INSTANCE_NAME=\"sm-nb-$DATE\"\n\n# cfn template name\nCFN_TEMPLATE='cfn-sm.yaml'\n\n# Leave blank if you need to create a new EFS file system\n# If you use an existing EFS file-system, it must not have any\n# existing mount targets\nEFS_ID=\n\n# Notebook instance type\n# ml.m5.2xlarge or ml.m4.2xlarge\nNOTEBOOK_INSTANCE_TYPE='ml.m5.2xlarge'\n\n# Code repository name\nCODE_REPO_NAME=\"code-repo-$DATE\"\n\n# Git hub user name\nGIT_USER=\n\n# Git hub token\nGIT_TOKEN=\n\n# Git Hub repo url\nGIT_URL=\n\n# EBS volume size 100 - 500 GB\nEBS_VOLUME_SIZE=100\n\naws cloudformation create-stack --region $AWS_REGION  --stack-name $STACK_NAME \\\n--template-body file://$CFN_TEMPLATE \\\n--capabilities CAPABILITY_NAMED_IAM \\\n--parameters \\\nParameterKey=EFSFileSystemId,ParameterValue=$EFS_ID \\\nParameterKey=NotebookInstanceType,ParameterValue=$NOTEBOOK_INSTANCE_TYPE \\\nParameterKey=NotebookInstanceName,ParameterValue=$NOTEBOOK_INSTANCE_NAME \\\nParameterKey=S3BucketName,ParameterValue=$S3_BUCKET \\\nParameterKey=CodeRepoName,ParameterValue=$CODE_REPO_NAME \\\nParameterKey=GitHubUsername,ParameterValue=$GIT_USER \\\nParameterKey=GitHubToken,ParameterValue=$GIT_TOKEN \\\nParameterKey=GitHubRepoUrl,ParameterValue=$GIT_URL \\\nParameterKey=EbsVolumeSize,ParameterValue=$EBS_VOLUME_SIZE\n\necho \"Creating stack [ eta 600 seconds ]\"\nsleep 30\n\nprogress=$(aws --region $AWS_REGION cloudformation list-stacks --stack-status-filter 'CREATE_IN_PROGRESS' | grep $STACK_NAME | wc -l)\nwhile [ $progress -ne 0 ]; do\nlet elapsed=\"`date +%s` - $DATE\"\necho \"Stack $STACK_NAME status: Create in progress: [ $elapsed secs elapsed ]\"\nsleep 30\nprogress=$(aws --region $AWS_REGION  cloudformation  list-stacks --stack-status-filter 'CREATE_IN_PROGRESS' | grep $STACK_NAME | wc -l)\ndone\nsleep 5\naws --region $AWS_REGION  cloudformation describe-stacks --stack-name $STACK_NAME\n", "num_lines": 72}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource $DIR/set_env.sh\n\n# set region\nregion=\nif [ \"$#\" -eq 1 ]; then\n    region=$1\nelse\n    echo \"usage: $0 <aws-region>\"\n    exit 1\nfi\n  \n\nimage=$IMAGE_NAME\ntag=$IMAGE_TAG\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\naws ecr get-login-password --region us-west-2 \\\n    | docker login --username AWS --password-stdin 763104351884.dkr.ecr.us-west-2.amazonaws.com\n\ndocker build  -t ${image} $DIR/..\ndocker tag ${image} ${fullname}\n\naws ecr get-login-password --region ${region} \\\n    | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n    \ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi\n", "num_lines": 62}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport IMAGE_NAME=mask-rcnn-tensorflow-sagemaker-script-mode\nexport IMAGE_TAG=tf1.15-99dda64\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource $DIR/set_env.sh\n\n# set region\nregion=\nif [ \"$#\" -eq 1 ]; then\n    region=$1\nelse\n    echo \"usage: $0 <aws-region>\"\n    exit 1\nfi\n  \n\nimage=$IMAGE_NAME\ntag=$IMAGE_TAG\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\naws ecr get-login-password --region us-west-2 \\\n    | docker login --username AWS --password-stdin 763104351884.dkr.ecr.us-west-2.amazonaws.com\n\ndocker build  -t ${image} $DIR/..\ndocker tag ${image} ${fullname}\n\naws ecr get-login-password --region ${region} \\\n    | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n    \ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi\n", "num_lines": 62}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport IMAGE_NAME=mask-rcnn-tensorpack-sagemaker-script-mode\nexport IMAGE_TAG=tf1.15-tpdb541e8\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource $DIR/set_env.sh\n\n# set region\nregion=\nif [ \"$#\" -eq 1 ]; then\n    region=$1\nelse\n    echo \"usage: $0 <aws-region>\"\n    exit 1\nfi\n  \n\nimage=$IMAGE_NAME\ntag=$IMAGE_TAG\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --no-include-email --region us-west-2  --registry-ids 763104351884)\n\ndocker build  -t ${image} $DIR/..\ndocker tag ${image} ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi\n", "num_lines": 61}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport IMAGE_NAME=mask-rcnn-tensorpack-serving-sagemaker\nexport IMAGE_TAG=tf1.15-tpdb541e8\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource $DIR/set_env.sh\n\n# set region\nregion=\nif [ \"$#\" -eq 1 ]; then\n    region=$1\nelse\n    echo \"usage: $0 <aws-region>\"\n    exit 1\nfi\n  \n\nimage=$IMAGE_NAME\ntag=$IMAGE_TAG\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --no-include-email --region us-west-2  --registry-ids 763104351884)\n\ndocker build  -t ${image} $DIR/..\ndocker tag ${image} ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi\n", "num_lines": 61}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport IMAGE_NAME=mask-rcnn-tensorflow-serving-sagemaker\nexport IMAGE_TAG=tf1.15-99dda64\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nalgorithm_name=$1\n\nchmod +x fairseq/train\nchmod +x fairseq/serve\n\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest\"\n\necho Getting from region $region and account $account\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --repository-names \"${algorithm_name}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${algorithm_name}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\n$(aws ecr get-login --registry-ids 520713654638 --region ${region} --no-include-email)\n\ndocker build -t ${algorithm_name} .\ndocker tag ${algorithm_name} ${fullname}\n\ndocker push ${fullname}", "num_lines": 36}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh\n\necho 'Cloning Moses github repository (for tokenization scripts)...'\ngit clone https://github.com/moses-smt/mosesdecoder.git\n\necho 'Cloning Subword NMT repository (for BPE pre-processing)...'\ngit clone https://github.com/rsennrich/subword-nmt.git\n\nSCRIPTS=mosesdecoder/scripts\nTOKENIZER=$SCRIPTS/tokenizer/tokenizer.perl\nLC=$SCRIPTS/tokenizer/lowercase.perl\nCLEAN=$SCRIPTS/training/clean-corpus-n.perl\nBPEROOT=subword-nmt\nBPE_TOKENS=10000\n\nURL=\"https://wit3.fbk.eu/archive/2014-01/texts/de/en/de-en.tgz\"\nGZ=de-en.tgz\n\nif [ ! -d \"$SCRIPTS\" ]; then\n    echo \"Please set SCRIPTS variable correctly to point to Moses scripts.\"\n    exit\nfi\n\nsrc=de\ntgt=en\nlang=de-en\nprep=iwslt14.tokenized.de-en\ntmp=$prep/tmp\norig=orig\n\nmkdir -p $orig $tmp $prep\n\necho \"Downloading data from ${URL}...\"\ncd $orig\nwget \"$URL\"\n\nif [ -f $GZ ]; then\n    echo \"Data successfully downloaded.\"\nelse\n    echo \"Data not successfully downloaded.\"\n    exit\nfi\n\ntar zxvf $GZ\ncd ..\n\necho \"pre-processing train data...\"\nfor l in $src $tgt; do\n    f=train.tags.$lang.$l\n    tok=train.tags.$lang.tok.$l\n\n    cat $orig/$lang/$f | \\\n    grep -v '<url>' | \\\n    grep -v '<talkid>' | \\\n    grep -v '<keywords>' | \\\n    sed -e 's/<title>//g' | \\\n    sed -e 's/<\\/title>//g' | \\\n    sed -e 's/<description>//g' | \\\n    sed -e 's/<\\/description>//g' | \\\n    perl $TOKENIZER -threads 8 -l $l > $tmp/$tok\n    echo \"\"\ndone\nperl $CLEAN -ratio 1.5 $tmp/train.tags.$lang.tok $src $tgt $tmp/train.tags.$lang.clean 1 175\nfor l in $src $tgt; do\n    perl $LC < $tmp/train.tags.$lang.clean.$l > $tmp/train.tags.$lang.$l\ndone\n\necho \"pre-processing valid/test data...\"\nfor l in $src $tgt; do\n    for o in `ls $orig/$lang/IWSLT14.TED*.$l.xml`; do\n    fname=${o##*/}\n    f=$tmp/${fname%.*}\n    echo $o $f\n    grep '<seg id' $o | \\\n        sed -e 's/<seg id=\"[0-9]*\">\\s*//g' | \\\n        sed -e 's/\\s*<\\/seg>\\s*//g' | \\\n        sed -e \"s/\\\u00e2\u20ac\u2122/\\'/g\" | \\\n    perl $TOKENIZER -threads 8 -l $l | \\\n    perl $LC > $f\n    echo \"\"\n    done\ndone\n\n\necho \"creating train, valid, test...\"\nfor l in $src $tgt; do\n    awk '{if (NR%23 == 0)  print $0; }' $tmp/train.tags.de-en.$l > $tmp/valid.$l\n    awk '{if (NR%23 != 0)  print $0; }' $tmp/train.tags.de-en.$l > $tmp/train.$l\n\n    cat $tmp/IWSLT14.TED.dev2010.de-en.$l \\\n        $tmp/IWSLT14.TEDX.dev2012.de-en.$l \\\n        $tmp/IWSLT14.TED.tst2010.de-en.$l \\\n        $tmp/IWSLT14.TED.tst2011.de-en.$l \\\n        $tmp/IWSLT14.TED.tst2012.de-en.$l \\\n        > $tmp/test.$l\ndone\n\nTRAIN=$tmp/train.en-de\nBPE_CODE=$prep/code\nrm -f $TRAIN\nfor l in $src $tgt; do\n    cat $tmp/train.$l >> $TRAIN\ndone\n\necho \"learn_bpe.py on ${TRAIN}...\"\npython $BPEROOT/learn_bpe.py -s $BPE_TOKENS < $TRAIN > $BPE_CODE\n\nfor L in $src $tgt; do\n    for f in train.$L valid.$L test.$L; do\n        echo \"apply_bpe.py to ${f}...\"\n        python $BPEROOT/apply_bpe.py -c $BPE_CODE < $tmp/$f > $prep/$f\n    done\ndone", "num_lines": 115}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Adapted from https://github.com/facebookresearch/MIXER/blob/master/prepareData.sh\n\necho 'Cloning Moses github repository (for tokenization scripts)...'\ngit clone https://github.com/moses-smt/mosesdecoder.git\n\necho 'Cloning Subword NMT repository (for BPE pre-processing)...'\ngit clone https://github.com/rsennrich/subword-nmt.git\n\nSCRIPTS=mosesdecoder/scripts\nTOKENIZER=$SCRIPTS/tokenizer/tokenizer.perl\nCLEAN=$SCRIPTS/training/clean-corpus-n.perl\nNORM_PUNC=$SCRIPTS/tokenizer/normalize-punctuation.perl\nREM_NON_PRINT_CHAR=$SCRIPTS/tokenizer/remove-non-printing-char.perl\nBPEROOT=subword-nmt\nBPE_TOKENS=40000\n\nURLS=(\n    \"http://statmt.org/wmt13/training-parallel-europarl-v7.tgz\"\n    \"http://statmt.org/wmt13/training-parallel-commoncrawl.tgz\"\n    \"http://statmt.org/wmt13/training-parallel-un.tgz\"\n    \"http://statmt.org/wmt14/training-parallel-nc-v9.tgz\"\n    \"http://statmt.org/wmt10/training-giga-fren.tar\"\n    \"http://statmt.org/wmt14/test-full.tgz\"\n)\nFILES=(\n    \"training-parallel-europarl-v7.tgz\"\n    \"training-parallel-commoncrawl.tgz\"\n    \"training-parallel-un.tgz\"\n    \"training-parallel-nc-v9.tgz\"\n    \"training-giga-fren.tar\"\n    \"test-full.tgz\"\n)\nCORPORA=(\n    \"training/europarl-v7.fr-en\"\n    \"commoncrawl.fr-en\"\n    \"un/undoc.2000.fr-en\"\n    \"training/news-commentary-v9.fr-en\"\n    \"giga-fren.release2.fixed\"\n)\n\nif [ ! -d \"$SCRIPTS\" ]; then\n    echo \"Please set SCRIPTS variable correctly to point to Moses scripts.\"\n    exit\nfi\n\nsrc=en\ntgt=fr\nlang=en-fr\nprep=wmt14_en_fr\ntmp=$prep/tmp\norig=orig\n\nmkdir -p $orig $tmp $prep\n\ncd $orig\n\nfor ((i=0;i<${#URLS[@]};++i)); do\n    file=${FILES[i]}\n    if [ -f $file ]; then\n        echo \"$file already exists, skipping download\"\n    else\n        url=${URLS[i]}\n        wget \"$url\"\n        if [ -f $file ]; then\n            echo \"$url successfully downloaded.\"\n        else\n            echo \"$url not successfully downloaded.\"\n            exit -1\n        fi\n        if [ ${file: -4} == \".tgz\" ]; then\n            tar zxvf $file\n        elif [ ${file: -4} == \".tar\" ]; then\n            tar xvf $file\n        fi\n    fi\ndone\n\ngunzip giga-fren.release2.fixed.*.gz\ncd ..\n\necho \"pre-processing train data...\"\nfor l in $src $tgt; do\n    rm $tmp/train.tags.$lang.tok.$l\n    for f in \"${CORPORA[@]}\"; do\n        cat $orig/$f.$l | \\\n            perl $NORM_PUNC $l | \\\n            perl $REM_NON_PRINT_CHAR | \\\n            perl $TOKENIZER -threads 8 -a -l $l >> $tmp/train.tags.$lang.tok.$l\n    done\ndone\n\necho \"pre-processing test data...\"\nfor l in $src $tgt; do\n    if [ \"$l\" == \"$src\" ]; then\n        t=\"src\"\n    else\n        t=\"ref\"\n    fi\n    grep '<seg id' $orig/test-full/newstest2014-fren-$t.$l.sgm | \\\n        sed -e 's/<seg id=\"[0-9]*\">\\s*//g' | \\\n        sed -e 's/\\s*<\\/seg>\\s*//g' | \\\n        sed -e \"s/\\\u00e2\u20ac\u2122/\\'/g\" | \\\n    perl $TOKENIZER -threads 8 -a -l $l > $tmp/test.$l\n    echo \"\"\ndone\n\necho \"splitting train and valid...\"\nfor l in $src $tgt; do\n    awk '{if (NR%1333 == 0)  print $0; }' $tmp/train.tags.$lang.tok.$l > $tmp/valid.$l\n    awk '{if (NR%1333 != 0)  print $0; }' $tmp/train.tags.$lang.tok.$l > $tmp/train.$l\ndone\n\nTRAIN=$tmp/train.fr-en\nBPE_CODE=$prep/code\nrm -f $TRAIN\nfor l in $src $tgt; do\n    cat $tmp/train.$l >> $TRAIN\ndone\n\necho \"learn_bpe.py on ${TRAIN}...\"\npython $BPEROOT/learn_bpe.py -s $BPE_TOKENS < $TRAIN > $BPE_CODE\n\nfor L in $src $tgt; do\n    for f in train.$L valid.$L test.$L; do\n        echo \"apply_bpe.py to ${f}...\"\n        python $BPEROOT/apply_bpe.py -c $BPE_CODE < $tmp/$f > $tmp/bpe.$f\n    done\ndone\n\nperl $CLEAN -ratio 1.5 $tmp/bpe.train $src $tgt $prep/train 1 250\nperl $CLEAN -ratio 1.5 $tmp/bpe.valid $src $tgt $prep/valid 1 250\n\nfor L in $src $tgt; do\n    cp $tmp/bpe.test.$L $prep/test.$L\ndone", "num_lines": 136}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" /changehostname.c\n\n    gcc -o /changehostname.o -c -fPIC -Wall /changehostname.c\n    gcc -o /libchangehostname.so -shared -export-dynamic /changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so train\nelse\n    serve\nfi", "num_lines": 15}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region $region | docker login --username AWS --password-stdin $account.dkr.ecr.$region.amazonaws.com\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\naws ecr get-login-password --region $region | docker login --username AWS --password-stdin 520713654638.dkr.ecr.$region.amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} . --build-arg REGION=${region}\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-2.0.3-1.docker17.09.1.ce.amzn1\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\ndockerfile=${2:-Dockerfile}\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\necho \"ECR image fullname: ${fullname}\"\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\nexport _DOCKER_REPO=\"$(aws ecr get-authorization-token --output text  --query 'authorizationData[].proxyEndpoint')\"\naws ecr get-login --no-include-email --region \"${region}\" | awk '{print $6}' | docker login -u AWS --password-stdin $_DOCKER_REPO\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\naws ecr get-login --no-include-email --region \"${region}\" | awk '{print $6}' | docker login -u AWS --password-stdin \"763104351884.dkr.ecr.${region}.amazonaws.com\"\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build -f ${dockerfile} -t ${image} . --build-arg REGION=${region}\ndocker tag ${image} ${fullname}\ndocker push ${fullname}\n# an alternative and simplified command that can be used instead of the code above is\n# sm-docker build ${1}", "num_lines": 48}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-2.0.3-1.docker17.09.1.ce.amzn1\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The name of our algorithm\nalgorithm_name=pytorch-training-container-extension-yolov5-cpu\n\ncd docker\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-east-1}\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${algorithm_name}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${algorithm_name}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${algorithm_name}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\n$(aws ecr get-login --registry-ids 763104351884 --region ${region} --no-include-email)\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${algorithm_name} . --build-arg REGION=${region}\ndocker tag ${algorithm_name} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 38}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\nchmod +x decision_trees/train\nchmod +x decision_trees/serve\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${account}\".dkr.ecr.\"${region}\".amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\nmkdir -p test_dir/model\nmkdir -p test_dir/output\n\nrm test_dir/model/*\nrm test_dir/output/*\n\ndocker run -v $(pwd)/test_dir:/opt/ml --rm ${image} train\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-2.0.3-1.docker17.09.1.ce.amzn1\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "c4b301c88fc1:amazon-sagemaker-examples julkroll$ git diff\ndiff --git a/advanced_functionality/xgboost_bring_your_own_model/xgboost_bring_your_own_model.ipynb b/advanced_functionality/xgboost_bring_your_own_model/xgboost_bring_your_own_model.ipynb\nindex 8df40914..f9b5a511 100644\n--- a/advanced_functionality/xgboost_bring_your_own_model/xgboost_bring_your_own_model.ipynb\n+++ b/advanced_functionality/xgboost_bring_your_own_model/xgboost_bring_your_own_model.ipynb\n@@ -1,18 +1,7 @@\n {\n  \"cells\": [\n-  {\n-   \"cell_type\": \"code\",\n-   \"execution_count\": null,\n-   \"id\": \"canadian-powell\",\n-   \"metadata\": {},\n-   \"outputs\": [],\n-   \"source\": [\n-    \"!pip install -Uq xgboost\"\n-   ]\n-  },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"animal-static\",\n    \"metadata\": {},\n    \"source\": [\n     \"# Amazon SageMaker XGBoost Bring Your Own Model\\n\",\n@@ -54,7 +43,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"comic-jonathan\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -77,7 +65,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"revolutionary-egypt\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -88,30 +75,15 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"second-traffic\",\n    \"metadata\": {},\n    \"source\": [\n     \"## Optionally, train a scikit learn XGBoost model\\n\",\n     \"\\n\",\n-    \"These steps are optional and are needed to generate the scikit-learn model that will eventually be hosted using the SageMaker Algorithm contained. \\n\",\n-    \"\\n\",\n-    \"### Install XGboost\\n\",\n-    \"Note that for conda based installation, you'll need to change the Notebook kernel to the environment with conda and Python3. \"\n-   ]\n-  },\n-  {\n-   \"cell_type\": \"code\",\n-   \"execution_count\": null,\n-   \"id\": \"expanded-dress\",\n-   \"metadata\": {},\n-   \"outputs\": [],\n-   \"source\": [\n-    \"!conda install -y -c conda-forge xgboost==0.90\"\n+    \"These steps are optional and are needed to generate the scikit-learn model that will eventually be hosted using the SageMaker Algorithm contained. \\n\"\n    ]\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"little-still\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Fetch the dataset\"\n@@ -120,7 +92,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"injured-crawford\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -129,7 +100,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"tough-facial\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Prepare the dataset for training\"\n@@ -138,7 +108,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"bright-powder\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -162,7 +131,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"wooden-thesis\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -178,7 +146,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"strong-height\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Train the XGBClassifier\"\n@@ -187,7 +154,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"sought-genome\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -202,7 +168,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"patient-endorsement\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Save the trained model file\\n\",\n@@ -212,7 +177,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"arctic-retail\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -223,7 +187,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"fatty-chapel\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -232,7 +195,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"forced-illustration\",\n    \"metadata\": {},\n    \"source\": [\n     \"## Upload the pre-trained model to S3\"\n@@ -241,7 +203,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"molecular-admission\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -252,7 +213,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"willing-miami\",\n    \"metadata\": {},\n    \"source\": [\n     \"## Set up hosting for the model\\n\",\n@@ -264,19 +224,17 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"juvenile-glossary\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n-    \"from sagemaker.amazon.amazon_estimator import get_image_uri\\n\",\n+    \"from sagemaker import image_uris\\n\",\n     \"\\n\",\n-    \"container = get_image_uri(boto3.Session().region_name, \\\"xgboost\\\", \\\"0.90-2\\\")\"\n+    \"container = image_uris.retrieve(region=boto3.Session().region_name, framework=\\\"xgboost\\\", version=\\\"0.90-2\\\")\"\n    ]\n   },\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"competitive-mozambique\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -303,7 +261,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"announced-affect\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Create endpoint configuration\\n\",\n@@ -314,7 +271,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"alike-experience\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -340,7 +296,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"otherwise-wiring\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Create endpoint\\n\",\n@@ -350,7 +305,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"experienced-makeup\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -380,7 +334,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"specific-sheffield\",\n    \"metadata\": {},\n    \"source\": [\n     \"## Validate the model for use\\n\",\n@@ -390,7 +343,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"pediatric-subject\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -399,7 +351,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"saving-ghost\",\n    \"metadata\": {},\n    \"source\": [\n     \"Lets generate the prediction for a single datapoint. We'll pick one from the test data generated earlier.\"\n@@ -408,7 +359,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"polish-laugh\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -423,7 +373,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"reported-coalition\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -447,7 +396,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"pursuant-cemetery\",\n    \"metadata\": {},\n    \"source\": [\n     \"### Post process the output\\n\",\n@@ -457,7 +405,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"broken-individual\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -469,7 +416,6 @@\n   },\n   {\n    \"cell_type\": \"markdown\",\n-   \"id\": \"going-popularity\",\n    \"metadata\": {},\n    \"source\": [\n     \"### (Optional) Delete the Endpoint\\n\",\n@@ -480,7 +426,6 @@\n   {\n    \"cell_type\": \"code\",\n    \"execution_count\": null,\n-   \"id\": \"foster-steps\",\n    \"metadata\": {},\n    \"outputs\": [],\n    \"source\": [\n@@ -490,10 +435,11 @@\n  ],\n  \"metadata\": {\n   \"anaconda-cloud\": {},\n+  \"instance_type\": \"ml.t3.medium\",\n   \"kernelspec\": {\n-   \"display_name\": \"Environment (conda_anaconda3)\",\n+   \"display_name\": \"Python 3 (Data Science)\",\n    \"language\": \"python\",\n-   \"name\": \"conda_anaconda3\"\n+   \"name\": \"python3__SAGEMAKER_INTERNAL__arn:aws:sagemaker:us-west-2:236514542706:image/datascience-1.0\"\n   },\n   \"language_info\": {\n    \"codemirror_mode\": {\n@@ -504,10 +450,11 @@\n    \"mimetype\": \"text/x-python\",\n    \"name\": \"python\",\n    \"nbconvert_exporter\": \"python\",\n-   \"pygments_lexer\": \"ipython3\"\n+   \"pygments_lexer\": \"ipython3\",\n+   \"version\": \"3.6.13\"\n   },\n   \"notice\": \"Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/ or in the \\\"license\\\" file accompanying this file. This file 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.\"\n  },\n  \"nbformat\": 4,\n  \"nbformat_minor\": 5\n-}\n\\ No newline at end of file\n+}\nc4b301c88fc1:amazon-sagemaker-examples julkroll$ \n", "num_lines": 325}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\nchmod +x decision_trees/train\nchmod +x decision_trees/serve\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\nmkdir -p test_dir/model\nmkdir -p test_dir/output\n\nrm test_dir/model/*\nrm test_dir/output/*\n\ndocker run -v $(pwd)/test_dir:/opt/ml --rm ${image} train\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-2.0.3-1.docker17.09.1.ce.amzn1\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# List all processes running from streamlit\necho \"Processes running from streamlit:\"\nps -Al | grep streamlit\n\n# Kill all processes running from streamlit\necho \"Killing all processes running from streamlit\"\npkill -9 streamlit\n\n# Delete the file temp.txt\nrm temp.txt", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nCURRENTDATE=`date +\"%Y-%m-%d %T\"`\nRED='\\033[0;31m'\nCYAN='\\033[1;36m'\nGREEN='\\033[1;32m'\nNC='\\033[0m'\nS3_PATH=$1\n\n# Run the Streamlit app and save the output to \"temp.txt\"\nstreamlit run app.py > temp.txt & \n\n# Read the text file using cat\necho \"Getting the URL to view your Streamlit app in the browser\"\n\n# Extract the last four digits of the port number from the Network URL\nsleep 5\nPORT=$(grep \"Network URL\" temp.txt | awk -F':' '{print $NF}' | awk '{print $1}' | tail -c 5)\necho -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Port Number ${PORT}\" \n\n\n\n# Get Studio domain information\nDOMAIN_ID=$(jq .DomainId /opt/ml/metadata/resource-metadata.json || exit 1)\nRESOURCE_NAME=$(jq .ResourceName /opt/ml/metadata/resource-metadata.json || exit 1)\nRESOURCE_ARN=$(jq .ResourceArn /opt/ml/metadata/resource-metadata.json || exit 1)\n\n# Remove quotes from string\nDOMAIN_ID=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$DOMAIN_ID\"`\nRESOURCE_NAME=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$RESOURCE_NAME\"`\nRESOURCE_ARN=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$RESOURCE_ARN\"`\nRESOURCE_ARN_ARRAY=($(echo \"$RESOURCE_ARN\" | tr ':' '\\n'))\n\n# Get Studio domain region\nREGION=$(echo \"${RESOURCE_ARN_ARRAY[3]}\")\n\n# Check if it's Collaborative Space\nSPACE_NAME=$(jq .SpaceName /opt/ml/metadata/resource-metadata.json || exit 1)\n\n# if it's not a collaborative space \nif [ -z \"$SPACE_NAME\" ] || [ $SPACE_NAME == \"null\" ] ;\nthen\n    # If it's a user-profile access\n    echo -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Domain Id ${DOMAIN_ID}\"\n    STUDIO_URL=\"https://${DOMAIN_ID}.studio.${REGION}.sagemaker.aws\"\n    \n# It is a collaborative space\nelse\n\n    SEM=true\n    SPACE_ID=\n\n    # Check if Space Id was previously configured\n    if [ -f /tmp/space-metadata.json ]; then\n        SAVED_SPACE_ID=$(jq .SpaceId /tmp/space-metadata.json || exit 1)\n        SAVED_SPACE_ID=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$SAVED_SPACE_ID\"`\n\n        if [ -z \"$SAVED_SPACE_ID\" ] || [ $SAVED_SPACE_ID == \"null\" ]; then\n            ASK_INPUT=true\n        else\n            ASK_INPUT=false\n        fi\n    else\n        ASK_INPUT=true\n    fi\n\n    # If Space Id is not available, ask for it\n    while [[ $SPACE_ID = \"\" ]] ; do\n        # If Space Id already configured, skeep the ask\n        if [ \"$ASK_INPUT\" = true ]; then\n            echo -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Please insert the Space Id from your url. e.g. https://${GREEN}<SPACE_ID>${NC}.studio.${REGION}.sagemaker.aws/jupyter/default/lab\"\n            read SPACE_ID\n            SEM=true\n        else\n            SPACE_ID=$SAVED_SPACE_ID\n        fi\n\n        if ! [ -z \"$SPACE_ID\" ] && ! [ $SPACE_ID == \"null\" ] ;\n        then\n            while $SEM; do\n                echo \"${SPACE_ID}\"\n                read -p \"Should this be used as Space Id? (y/N) \" yn\n                case $yn in\n                    [Yy]* )\n                        echo -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Domain Id ${DOMAIN_ID}\"\n                        echo -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Space Id ${SPACE_ID}\"\n\n                        jq -n --arg space_id $SPACE_ID '{\"SpaceId\":$space_id}' > /tmp/space-metadata.json\n\n                        STUDIO_URL=\"https://${SPACE_ID}.studio.${REGION}.sagemaker.aws\"\n\n                        SEM=false\n                        ;;\n                    [Nn]* ) \n                        SPACE_ID=\n                        ASK_INPUT=true\n                        SEM=false\n                        ;;\n                    * ) echo \"Please answer yes or no.\";;\n                esac\n            done\n        fi\n    done\nfi\n\necho -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Studio Url ${STUDIO_URL}\"\n\n\nlink=\"${STUDIO_URL}/jupyter/${RESOURCE_NAME}/proxy/${PORT}/\"\n\necho -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Starting Streamlit App\"\necho -e \"${CYAN}${CURRENTDATE}: [INFO]: ${GREEN}${link}${NC}\"\n\nexit 0\nfi\n", "num_lines": 115}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "pip install --no-cache-dir -r requirements.txt\nsudo yum install -y iproute\nsudo yum install -y jq\nsudo yum install -y lsof", "num_lines": 4}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Get all port numbers in use by Streamlit and output the URLs for all running streamlit apps. \n\nCURRENTDATE=`date +\"%Y-%m-%d %T\"`\nRED='\\033[0;31m'\nCYAN='\\033[1;36m'\nGREEN='\\033[1;32m'\nNC='\\033[0m'\nS3_PATH=$1\n\n\n# Get Studio domain information\nDOMAIN_ID=$(jq .DomainId /opt/ml/metadata/resource-metadata.json || exit 1)\nRESOURCE_NAME=$(jq .ResourceName /opt/ml/metadata/resource-metadata.json || exit 1)\nRESOURCE_ARN=$(jq .ResourceArn /opt/ml/metadata/resource-metadata.json || exit 1)\n\n# Remove quotes from string\nDOMAIN_ID=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$DOMAIN_ID\"`\nRESOURCE_NAME=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$RESOURCE_NAME\"`\nRESOURCE_ARN=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$RESOURCE_ARN\"`\nRESOURCE_ARN_ARRAY=($(echo \"$RESOURCE_ARN\" | tr ':' '\\n'))\n\n# Get Studio domain region\nREGION=$(echo \"${RESOURCE_ARN_ARRAY[3]}\")\n\n# Check if it's Collaborative Space\nSPACE_NAME=$(jq .SpaceName /opt/ml/metadata/resource-metadata.json || exit 1)\n\n\n# Find the process IDs of all running Streamlit instances\nstreamlit_pids=$(pgrep streamlit)\n\n# Initialize an empty array to hold the port numbers\nport_array=()\n# Loop through each process ID and find the port number in use\nfor pid in $streamlit_pids; do\n    # Get the port number for the process\n    port=$(lsof -a -i -P -n -p $pid | grep LISTEN | awk -F':' '{print $2}' | cut -d ' ' -f 1)\\\n    # port=$(lsof -a -i -P -n -p $pid | grep \".*:\\d\\+.*(LISTEN)$\" | awk -F':' '{print $2}' | cut -d ' ' -f 1)\n    port=\"${port:0:4}\"\n    \n    # Add the port number to the array\n    port_array+=(\"$port\")\n    \ndone\n\n\necho \"These are the Streamlit Apps Currently Running: \"\n# Loop through the array and print each port number\nfor PORT in \"${port_array[@]}\"; do\n    \n    # if it's not a collaborative space \n    if [ -z \"$SPACE_NAME\" ] || [ $SPACE_NAME == \"null\" ] ;\n    then\n        # If it's a user-profile access\n        STUDIO_URL=\"https://${DOMAIN_ID}.studio.${REGION}.sagemaker.aws\"\n\n    # It is a collaborative space\n    else\n\n        SEM=true\n        SPACE_ID=\n\n        # Check if Space Id was previously configured\n        if [ -f /tmp/space-metadata.json ]; then\n            SAVED_SPACE_ID=$(jq .SpaceId /tmp/space-metadata.json || exit 1)\n            SAVED_SPACE_ID=`sed -e 's/^\"//' -e 's/\"$//' <<< \"$SAVED_SPACE_ID\"`\n\n            if [ -z \"$SAVED_SPACE_ID\" ] || [ $SAVED_SPACE_ID == \"null\" ]; then\n                ASK_INPUT=true\n            else\n                ASK_INPUT=false\n            fi\n        else\n            ASK_INPUT=true\n        fi\n\n        # If Space Id is not available, ask for it\n        while [[ $SPACE_ID = \"\" ]] ; do\n            # If Space Id already configured, skeep the ask\n            if [ \"$ASK_INPUT\" = true ]; then\n                echo -e \"${CYAN}${CURRENTDATE}: [INFO]:${NC} Please insert the Space Id from your url. e.g. https://${GREEN}<SPACE_ID>${NC}.studio.${REGION}.sagemaker.aws/jupyter/default/lab\"\n                read SPACE_ID\n                SEM=true\n            else\n                SPACE_ID=$SAVED_SPACE_ID\n            fi\n\n            if ! [ -z \"$SPACE_ID\" ] && ! [ $SPACE_ID == \"null\" ] ;\n            then\n                while $SEM; do\n                    echo \"${SPACE_ID}\"\n                    read -p \"Should this be used as Space Id? (y/N) \" yn\n                    case $yn in\n                        [Yy]* )\n\n                            jq -n --arg space_id $SPACE_ID '{\"SpaceId\":$space_id}' > /tmp/space-metadata.json\n\n                            STUDIO_URL=\"https://${SPACE_ID}.studio.${REGION}.sagemaker.aws\"\n\n                            SEM=false\n                            ;;\n                        [Nn]* ) \n                            SPACE_ID=\n                            ASK_INPUT=true\n                            SEM=false\n                            ;;\n                        * ) echo \"Please answer yes or no.\";;\n                    esac\n                done\n            fi\n        done\n    fi\n\n    link=\"${STUDIO_URL}/jupyter/${RESOURCE_NAME}/proxy/${PORT}/\"\n\n    echo -e \"${GREEN}${link}${NC}\"\ndone\nexit 0\nfi\n\n\n\n\n", "num_lines": 125}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\naws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "ACCOUNT_ID=$1\nREGION=$2\nREPO_NAME=$3\n\ndocker build -f ../docker/Dockerfile -t $REPO_NAME ../docker\n\ndocker tag $REPO_NAME $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n\naws ecr get-login-password --region $REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com\n\naws ecr describe-repositories --repository-names $REPO_NAME || aws ecr create-repository --repository-name $REPO_NAME\n\ndocker push $ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$REPO_NAME:latest\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl -d @${payload} -H \"Content-Type: ${content}\" http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\nmkdir -p test_dir/model\nmkdir -p test_dir/output\n\nrm test_dir/model/*\nrm test_dir/output/*\n\ndocker run -v $(pwd)/test_dir:/opt/ml --rm ${image} train\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# COLLABORATORS: Jeremy Feltracco(jpfelt@), Vidya Sagar Ravipati (ravividy@)\n\n# Immediately stop if any intermediate step fails.\nset -e\n\nREPO_ROOT_PATH=\"$(dirname $0)/..\"\n\nPREFIX=\"smgt-workflow\"\n\necho \"[START] LAUNCHING SMGT-WORKFLOW\"\n\nif [[ -z \"${AWS_PROFILE}\" ]];\nthen\n  read -p \"Enter your AWS CLI IAM AWS_PROFILE : \" AWS_PROFILE\nfi\n\nif [[ -z \"${COGNITO_POOL_ID}\" ]];\nthen\n  read -p \"Enter your SageMaker Workforce cognito user pool id: \" COGNITO_POOL_ID\nfi\n\nif [[ -z \"${COGNITO_POOL_CLIENT_ID}\" ]];\nthen\n  read -p \"Enter your SageMaker Workforce cognito client id: \" COGNITO_POOL_CLIENT_ID\nfi\n\nstack_name=\"${PREFIX}-v0\"\naccount=$(aws sts get-caller-identity --query Account --output text --profile ${AWS_PROFILE})\nregion=$(aws configure get region --profile ${AWS_PROFILE})\necho \"We will be launching resources in ${region} in account ${account} with AWS CLI Profile ${AWS_PROFILE}.\"\n\nDEPLOY_BUCKET_NAME=\"${PREFIX}-${account}-${region}\"\naws s3 mb s3://${DEPLOY_BUCKET_NAME} --profile ${AWS_PROFILE}\n\n sam build \\\n     -t main-merged.yml \\\n     --use-container \\\n     --skip-pull-image\n\n sam package \\\n     --template-file .aws-sam/build/template.yaml \\\n     --output-template-file main-packaged.yml \\\n     --s3-bucket ${DEPLOY_BUCKET_NAME} \\\n     --profile ${AWS_PROFILE}\n\n sam deploy \\\n     --template-file main-packaged.yml \\\n     --stack-name ${stack_name} \\\n     --region ${region} \\\n     --tags Project=${stack_name} \\\n     --s3-bucket ${DEPLOY_BUCKET_NAME} \\\n     --parameter-overrides \\\n       ParameterKey=Prefix,ParameterValue=${PREFIX} \\\n       ParameterKey=CognitoUserPoolId,ParameterValue=${COGNITO_POOL_ID} \\\n       ParameterKey=CognitoUserPoolClientId,ParameterValue=${COGNITO_POOL_CLIENT_ID} \\\n     --capabilities CAPABILITY_IAM CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM \\\n     --profile ${AWS_PROFILE}\n\necho \"[SUCCESS] DONE BUILDING SMGT-WORKFLOW\"\n", "num_lines": 61}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_PATH=\"`dirname \\\"$0\\\"`\"\nINSTALL_PATH=\"$SCRIPT_PATH/target/python\"\n\nrm -rf $INSTALL_PATH\nmkdir -p $INSTALL_PATH\npip3 install -t $INSTALL_PATH -r $SCRIPT_PATH/requirements.txt\n", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_PATH=\"`dirname \\\"$0\\\"`\"\n\ngit clean -f -x -d $SCRIPT_PATH\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    #sudo pkill -SIGHUP dockerd\n    sudo yum -y remove docker\n    sudo yum -y install docker-17.09.1ce-1.111.amzn1\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c 169.254.0.2`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nsource activate rapids\nif [[ \"$1\" == \"serve\" ]]; then\n    echo -e \"@ entrypoint -> launching serving script \\n\"\n    python serve.py\nelse\n    echo -e \"@ entrypoint -> launching training script \\n\"\n    python train.py\nfi", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\npython pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n# python onnx_exporter.py", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython onnx_exporter.py\npython pt_exporter.py\ntrtexec --onnx=model.onnx --saveEngine=model.plan --explicitBatch --minShapes=input:1x3x224x224 --optShapes=input:128x3x224x224 --maxShapes=input:128x3x224x224 --fp16 --verbose | tee conversion.txt\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\npython pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n# python onnx_exporter.py", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\n#python pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n python onnx_exporter.py\n\n#use this command to generate a model plan that will be used to host SageMaker Endpoint\ntrtexec --onnx=model.onnx --saveEngine=model.plan --explicitBatch --minShapes=input:1x3x224x224 --optShapes=input:128x3x224x224 --maxShapes=input:128x3x224x224 --fp16 --verbose | tee conversion.txt\n\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\npython pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n# python onnx_exporter.py", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\n#python pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n python onnx_exporter.py\n\n#use this command to generate a model plan that will be used to host SageMaker Endpoint\ntrtexec --onnx=model.onnx --saveEngine=model.plan --explicitBatch --minShapes=input:1x3x224x224 --optShapes=input:128x3x224x224 --maxShapes=input:128x3x224x224 --fp16 --verbose | tee conversion.txt\n\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython -m pip install transformers==4.26.1\npython onnx_exporter.py\n\ntrtexec --onnx=model.onnx --saveEngine=model_bs16.plan --minShapes=token_ids:1x128,attn_mask:1x128 --optShapes=token_ids:16x128,attn_mask:16x128 --maxShapes=token_ids:128x128,attn_mask:128x128 --fp16 --verbose --workspace=14000 | tee conversion_bs16_dy.txt\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n hf_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nsource activate hf_env\nexport PYTHONNOUSERSITE=True\npip install torch --extra-index-url https://download.pytorch.org/whl/cu116\npip install transformers[sentencepiece]\npip install conda-pack\nconda-pack", "num_lines": 10}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython -m pip install transformers==4.26.1\npython onnx_exporter.py\n\ntrtexec --onnx=model.onnx --saveEngine=model_bs16.plan --minShapes=token_ids:1x128,attn_mask:1x128 --optShapes=token_ids:16x128,attn_mask:16x128 --maxShapes=token_ids:128x128,attn_mask:128x128 --fp16 --verbose --workspace=14000 | tee conversion_bs16_dy.txt\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n hf_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nsource activate hf_env\nexport PYTHONNOUSERSITE=True\npip install torch --extra-index-url https://download.pytorch.org/whl/cu116\npip install transformers[sentencepiece]\npip install conda-pack\nconda-pack", "num_lines": 10}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\nfreeMemory=$(awk '/MemFree/ { printf \"%.0f \\n\", $2 }' /proc/meminfo)\ntotalMemory=$(awk '/MemTotal/ { printf \"%.0f \\n\", $2 }' /proc/meminfo)\navailableMemory=$(awk '/MemAvailable/ { printf \"%.0f \\n\", $2 }' /proc/meminfo)\n\necho freeMemory = $freeMemory\necho availableMemory = $availableMemory\necho totalMemory = $totalMemory\n\nheapMemory=$((availableMemory*80/100))\n\necho Using 80% of availableMemory = $heapMemory\n\nheapMemoryInMBs=$((heapMemory/1024))M\n\necho heapMemoryInMBs = $heapMemoryInMBs\n\necho \"[server-startup] Starting java application\"\n\nexec java -Xmx$heapMemoryInMBs -Djava.security.egd=file:/dev/./urandom -Dapp.port=8080 -jar /work/app.jar\n\n", "num_lines": 24}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n preprocessing_env python=3.8\nsource /opt/conda/etc/profile.d/conda.sh\nconda activate preprocessing_env\nexport PYTHONNOUSERSITE=True\nconda install -y -c conda-forge pandas scikit-learn\npip install conda-pack\nconda-pack\n", "num_lines": 10}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsudo -u ec2-user -i <<'EOF'\n\nmkdir -p rapids_kernel\ncd rapids_kernel\nwget -q https://rapidsai-data.s3.us-east-2.amazonaws.com/conda-pack/rapidsai/rapids21.06_cuda11.0_py3.8.tar.gz\necho \"wget completed\"\ntar -xzf *.gz\necho \"unzip completed\"\nsource /home/ec2-user/rapids_kernel/bin/activate\nconda-unpack \necho \"unpack completed\"\npython -m ipykernel install --user --name rapids-2106\necho \"kernel install completed\"\n\nEOF\n", "num_lines": 20}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nreponame=$1\nversiontag=$2\nbaseimage=$3\nregionname=$4\naccount=$5\n\nif [ \"$reponame\" == \"\" ] || [ \"$versiontag\" == \"\" ]  || [ \"$baseimage\" == \"\" ] || [ \"$regionname\" == \"\" ] || [ \"$account\" == \"\" ]\nthen\n    echo \"Usage: $0 <repo-name> <version-tag> <base-image> <region> <account>\"\n    exit 1\nfi\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\nfullname=\"${account}.dkr.ecr.${regionname}.amazonaws.com/${reponame}:${versiontag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --repository-names \"${reponame}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${reponame}\" > /dev/null\nfi\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\naws ecr get-login-password --region $regionname | docker login --username AWS --password-stdin ${baseimage} \n\naws ecr get-login-password --region $regionname | docker login --username AWS --password-stdin ${account}.dkr.ecr.\"${regionname}\".amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\ndocker build  -t ${reponame} . --build-arg BASE_IMAGE=${baseimage}\ndocker tag ${reponame} ${fullname}\n\n# Get the login command from ECR in order to pull down the SageMaker PyTorch image\naws ecr get-login-password --region $regionname | docker login --username AWS --password-stdin ${account}.dkr.ecr.\"${regionname}\".amazonaws.com\n\ndocker push ${fullname}\necho \"${fullname}\"\n\n", "num_lines": 51}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#  ./patch_ssd.sh s3://my-bucket/my-model-output 5 s3://my-bucket/my-patched-output\n\n# This script requires you to have already cloned the incubator-mxnet project\n# to obtain the deploy.py script\n#git clone https://github.com/apache/incubator-mxnet\n\nBUCKET_AND_PREFIX=$1 # should enforce that target must contain 'deeplens', else import fails\nNUM_CLASSES=$2       # could be extracted from hyperparams.json for more robust implementation\nTARGET_PREFIX=$3\n\n# download and unpack the model artifacts\nrm -rf tmp && mkdir tmp\naws s3 cp $BUCKET_AND_PREFIX/model.tar.gz tmp\ngunzip -k -c tmp/model.tar.gz | tar -C tmp -xopf -\nls -l tmp/*\n\n# copy your parameters file and symbol file into the SSD model directory\nmv tmp/*-0000.params tmp/ssd_resnet50_512-0000.params\nmv tmp/*-symbol.json tmp/ssd_resnet50_512-symbol.json\n\n# run the deploy Python script, which creates patched versions of\n# your parameters and symbol file with a new prefix of \"deploy\"\npython incubator-mxnet/example/ssd/deploy.py --network resnet50 \\\n  --data-shape 512 --num-class $NUM_CLASSES --prefix tmp/ssd_\n\n# now re-package your updated model artifacts\nrm tmp/ssd_*  &&  rm tmp/model.tar.gz\ntar -cvzf ./patched_model.tar.gz -C tmp \\\n  ./deploy_ssd_resnet50_512-0000.params \\\n  ./deploy_ssd_resnet50_512-symbol.json \\\n  ./hyperparams.json\n\n# move the new artifacts to S3 for DeepLens model creation. Use a new\n# prefix to keep it distinct from the original model artifacts.\naws s3 cp patched_model.tar.gz $TARGET_PREFIX/\n\n# clean up\nrm -rf tmp\nrm *.gz\n", "num_lines": 41}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\npython pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n# python onnx_exporter.py", "num_lines": 9}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# use this script to save ResNet50 model as a .pt file\n#python pt_exporter.py\n\n# Optional Scripts\n# use this script to convert Pytorch model to ONNX format\n python onnx_exporter.py\n\n#use this command to generate a model plan that will be used to host SageMaker Endpoint\ntrtexec --onnx=model.onnx --saveEngine=model.plan --explicitBatch --minShapes=input:1x3x224x224 --optShapes=input:128x3x224x224 --maxShapes=input:128x3x224x224 --fp16 --verbose | tee conversion.txt\n", "num_lines": 13}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Starting the spot int handler\"\n\n\nif [ \"${QUEUE_URL}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `QUEUE_URL` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${NAMESPACE}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `NAMESPACE` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${POD_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `POD_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\necho \"Getting the node name\"\nNODE_NAME=$(kubectl --namespace ${NAMESPACE} get pod ${POD_NAME} --output jsonpath=\"{.spec.nodeName}\")\necho NODE_NAME=${NODE_NAME}\n\nif [ \"${NODE_NAME}\" == \"\" ]; then\n  echo \"[ERROR] Unable to fetch the name of the node running the pod \\\"${POD_NAME}\\\" in the namespace \\\"${NAMESPACE}\\\".\" 1>&2\n  exit 1\nfi\n\necho \"Gather some information\"\nINSTANCE_ID_URL=${INSTANCE_ID_URL:-http://169.254.169.254/latest/meta-data/instance-id}\nINSTANCE_ID=$(curl -s ${INSTANCE_ID_URL})\necho INSTANCE_ID_URL=${INSTANCE_ID_URL}\necho INSTANCE_ID=${INSTANCE_ID}\n\necho \"\\`kubectl drain ${NODE_NAME}\\` will be executed once a termination notice is made.\"\n\n\nPOLL_INTERVAL=${POLL_INTERVAL:-5}\nNOTICE_URL=${NOTICE_URL:-http://169.254.169.254/latest/meta-data/spot/termination-time}\n\necho \"Polling ${NOTICE_URL} every ${POLL_INTERVAL} second(s)\"\n\nwhile http_status=$(curl -o /dev/null -w '%{http_code}' -sL ${NOTICE_URL}); [ ${http_status} -ne 200 ]; do\n  echo $(date): ${http_status}\n  sleep ${POLL_INTERVAL}\ndone\n\necho $(date): ${http_status}\n\nMESSAGE=\"[{'status': 'spot termination', 'public_hostname': ${NODE_NAME}, 'public_port': NA, 'region': 'us-west'}]\"\nMESSAGE_GRP_ID=\"gsGrp_us-west-2\"\naws sqs send-message --queue-url ${QUEUE_URL} --message-body \"${MESSAGE}\" --message-group-id ${MESSAGE_GRP_ID}\n\necho \"Drain the node.\"\nkubectl drain ${NODE_NAME} --force --ignore-daemonsets\n\necho \"Sleep for 200 seconds to prevent raise condition\"\n# The instance should be terminated by the end of the sleep assumming 120 sec notification time\nsleep 200\n", "num_lines": 61}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource account.conf\nregion=\"us-west-2\"\nrepo='.dkr.ecr.'$region'.amazonaws.com/autopilot:latest'\nrepo_url=$account$repo\n\n$(aws ecr get-login --no-include-email --region $region)\ndocker build -t autopilot .\ndocker tag autopilot:latest $repo_url\ndocker push $repo_url\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport QUEUE_URL=\"https://sqs.us-west-2.amazonaws.com/356566070122/gameserver.fifo\"\nexport NAMESPACE=\"default\"\nexport POD_NAME=\"my_pod\"\nexport DEPLOY_NAME=\"minecraft\"\nexport CURRENT_SIZE_METRIC_NAME=\"num_of_gs\"\nexport NEW_SIZE_METRIC_NAME=\"new_size\"\nexport FREQUENCY=\"10\"\nexport MIN_GS_NUM=\"10\"\n", "num_lines": 11}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh -x\n#source ./export_locally.sh\necho \"Starting the game server auto-pilot\"\n\n# This process runs as daemon set per game server deployment. It attempt to get the required number of game-servers within a region.\n# It gets this number from an ML model. For testing purpose, it avoids the ML endpoint and uses random numbers instead. \n# In the case of scale down, individual game server pods should protect itself with a termination grace period to avoid player interruption \n# In such cases, an extra x min will be given where terminated pods status will turn to 'terminating'. \n# Game servers can listen to SIGKILL or SIGTERM and trigger a game-server drain (this is not k8s thing. it is a game-server logic)\n\nif [ \"${DEMAND_URL}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `DEMAND_URL` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${MODEL_URL}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `MODEL_URL` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${QUEUE_URL}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `QUEUE_URL` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${NAMESPACE}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `NAMESPACE` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${POD_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `POD_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${DEPLOY_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `DEPLOY_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${CURRENT_SIZE_METRIC_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `CURRENT_SIZE_METRIC_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${NEW_SIZE_METRIC_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `NEW_SIZE_METRIC_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${FREQUENCY}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `FREQUENCY` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${MIN_GS_NUM}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `MIN_GS_NUM` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${AWS_DEFAULT_REGION}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `AWS_DEFAULT_REGION` has no value set.' 1>&2\n  exit 1\nfi\n\nwhile true\ndo\n\n  #Testing only - generating random size for replica set. Realworld solution will get this number from an AI/ML endpoint\n  #NEW_RS_SIZE=$RANDOM\n  #RANGE=30\n  #let \"NEW_RS_SIZE %= $RANGE\"\n  #echo NEW_RS_SIZE=${NEW_RS_SIZE}\n  #End testing section\n\n  #Getting predictions from a trained model\n  TMP_PREDICTION_JSON=\"/tmp/prediction.json\"\n  DEMAND_URL=${DEMAND_URL}\n  MODEL_URL=${MODEL_URL}\n  MODEL_URL_PARAM=\"/\"\n  `curl -w \"\\n\" $MODEL_URL/$MODEL_URL_PARAM > $TMP_PREDICTION_JSON`\n  NEW_RS_SIZE_FLOAT=`cat $TMP_PREDICTION_JSON | jq '.Prediction.num_of_gameservers'`\n  IS_FALSE_POSITIVE=`cat $TMP_PREDICTION_JSON | jq '.Prediction.is_false_positive'`\n  if [ -n \"${NEW_RS_SIZE_FLOAT}\" ]; then\n    NEW_RS_SIZE=${NEW_RS_SIZE_FLOAT%.*}\n  else\n    echo \"api returned null, setting rs default=\"${MIN_GS_NUM}\n    NEW_RS_SIZE=${MIN_GS_NUM}\n  fi\n  echo NEW_RS_SIZE=${NEW_RS_SIZE}\n  CURRENT_RS_SIZE=`kubectl get deploy ${DEPLOY_NAME} -n ${NAMESPACE} -o=jsonpath='{.status.availableReplicas}'`\n  echo CURRENT_RS_SIZE=${CURRENT_RS_SIZE}\n\n  kubectl scale deploy/${DEPLOY_NAME} --replicas=${NEW_RS_SIZE} -n ${NAMESPACE}\n  echo \"sleeping for ${SLEEP_TIME_B4_NEXT_READ} to allow the scale operations\"\n\n  NUM_NODES=`kubectl get nodes -o json | jq '.items[].metadata.labels'| grep ${NODE_GROUP} | wc -l`\n  echo NUM_NODES=${NUM_NODES}\n\n  TIME_ST=\"$(date '+%Y-%m-%d %H:%M:%S')\"\n  echo TIMESTAMP=$TIME_ST\n\n  MESSAGE=\"[{'type': 'autopilot','timestamp':${TIME_ST},'deployment':${DEPLOY_NAME},'current_rs_size': ${CURRENT_RS_SIZE},'new_rs_size':${NEW_RS_SIZE},'region':${AWS_DEFAULT_REGION}}]\"\n  CURRENT_DEMAND=`curl -w \"\\n\" $DEMAND_URL | jq '.Prediction.num_of_gameservers'`\n  echo CURRENT_DEMAND=${CURRENT_DEMAND}\n  #aws sqs send-message --queue-url ${QUEUE_URL} --message-body \"${MESSAGE}\" \n  aws cloudwatch put-metric-data --metric-name ${CURRENT_SIZE_METRIC_NAME} --namespace ${DEPLOY_NAME} --value ${CURRENT_RS_SIZE}\n  #aws cloudwatch put-metric-data --metric-name ${NEW_SIZE_METRIC_NAME} --namespace ${DEPLOY_NAME} --value ${NEW_RS_SIZE}\n  aws cloudwatch put-metric-data --metric-name current_gs_demand --namespace ${DEPLOY_NAME} --value ${CURRENT_DEMAND}\n  aws cloudwatch put-metric-data --metric-name num_of_nodes --namespace ${DEPLOY_NAME} --value ${NUM_NODES}\n  aws cloudwatch put-metric-data --metric-name false_positive --namespace ${DEPLOY_NAME} --value ${IS_FALSE_POSITIVE}\n\n  sleep ${FREQUENCY}\n\ndone\n", "num_lines": 116}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Creating docker image repositories\"\naws cloudformation create-stack --stack-name ecr-repos --template-body file://./ecr-repos.json\n\necho \"Creating DynamoDB table latest-observations\"\naws cloudformation create-stack --stack-name latest-observations-dynamodb-table --template-body file://./latest_observations-table.json\n\necho \"Waiting for the DynamoDB table latest-observations to be created\"\naws dynamodb wait table-exists --table-name latest_observations\n\necho \"Initializing latest-observations\"\naws dynamodb put-item --table-name latest_observations --item file://./init_observation.json\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nsudo curl --silent --location -o /usr/local/bin/kubectl https://storage.googleapis.com/kubernetes-release/release/v1.13.7/bin/linux/amd64/kubectl\n\nsudo chmod +x /usr/local/bin/kubectl\n\nsudo yum -y install jq gettext\n\nfor command in kubectl jq envsubst\n  do\n    which $command &>/dev/null && echo \"$command in path\" || echo \"$command NOT FOUND\"\n  done\n\nssh-keygen -f ~/.ssh/id_rsa -t rsa -N ''\n\ncurl --silent --location \"https://github.com/weaveworks/eksctl/releases/download/latest_release/eksctl_$(uname -s)_amd64.tar.gz\" | tar xz -C /tmp\n\nsudo mv -v /tmp/eksctl /usr/local/bin\n\neksctl version\n\nrm -vf ${HOME}/.aws/credentials\n\nexport ACCOUNT_ID=$(aws sts get-caller-identity --output text --query Account)\nexport AWS_REGION=$(curl -s 169.254.169.254/latest/dynamic/instance-identity/document | jq -r '.region')\n\necho \"export ACCOUNT_ID=${ACCOUNT_ID}\" >> ~/.bash_profile\necho \"export AWS_REGION=${AWS_REGION}\" >> ~/.bash_profile\naws configure set default.region ${AWS_REGION}\naws configure get default.region\n", "num_lines": 31}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource account.conf\nrepo='.dkr.ecr.us-west-2.amazonaws.com/minecraft-server:latest'\nrepo_url=$account$repo\n\n$(aws ecr get-login --no-include-email --region us-west-2)\ndocker build -t minecraft-server .\ndocker tag minecraft-server:latest $repo_url\ndocker push $repo_url\n", "num_lines": 11}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nasg_name=`aws autoscaling describe-auto-scaling-groups| jq '.AutoScalingGroups[].AutoScalingGroupName' | grep rl-gs-autopilot`\naws autoscaling update-auto-scaling-group --auto-scaling-group-name $asg_name --mixed-instances-policy file://./mixed-instance-policy.json\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#region=us-east-1\nregion=us-west-2\nsource account.conf\nrepo='.dkr.ecr.'$region'.amazonaws.com/spot-sig-handler:latest'\nrepo_url=$account$repo\n\n$(aws ecr get-login --no-include-email --region $region)\ndocker build -t spot-sig-handler .\ndocker tag spot-sig-handler:latest $repo_url\ndocker push $repo_url\n", "num_lines": 13}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Starting the spot int handler\"\n\n\nif [ \"${QUEUE_URL}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `QUEUE_URL` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${NAMESPACE}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `NAMESPACE` has no value set.' 1>&2\n  exit 1\nfi\n\nif [ \"${POD_NAME}\" == \"\" ]; then\n  echo '[ERROR] Environment variable `POD_NAME` has no value set.' 1>&2\n  exit 1\nfi\n\necho \"Getting the node name\"\nNODE_NAME=$(kubectl --namespace ${NAMESPACE} get pod ${POD_NAME} --output jsonpath=\"{.spec.nodeName}\")\necho NODE_NAME=${NODE_NAME}\n\nif [ \"${NODE_NAME}\" == \"\" ]; then\n  echo \"[ERROR] Unable to fetch the name of the node running the pod \\\"${POD_NAME}\\\" in the namespace \\\"${NAMESPACE}\\\".\" 1>&2\n  exit 1\nfi\n\necho \"Gather some information\"\nINSTANCE_ID_URL=${INSTANCE_ID_URL:-http://169.254.169.254/latest/meta-data/instance-id}\nINSTANCE_ID=$(curl -s ${INSTANCE_ID_URL})\necho INSTANCE_ID_URL=${INSTANCE_ID_URL}\necho INSTANCE_ID=${INSTANCE_ID}\n\nINSTANCE_TYPE=$(kubectl get nodes ${NODE_NAME} -L beta.kubernetes.io/instance-type| grep -v INSTANCE-TYPE| awk '{print $NF}')\necho INSTANCE_TYPE=$INSTANCE_TYPE\n\nINSTANCE_AZ=$(kubectl get nodes ${NODE_NAME} -L failure-domain.beta.kubernetes.io/zone| grep -v ZONE| awk '{print $NF}')\necho INSTANCE_AZ=$INSTANCE_AZ\n\nINSTANCE_GROUP=$(kubectl get nodes ${NODE_NAME} -L alpha.eksctl.io/nodegroup-name| grep -v NODEGROUP-NAME| awk '{print $NF}')\necho INSTANCE_GROUP=$INSTANCE_GROUP\n\nTIME_ST=\"$(date '+%Y-%m-%d %H:%M:%S')\"\necho TIMESTAMP=$TIME_ST\n\necho \"\\`kubectl drain ${NODE_NAME}\\` will be executed once a termination notice is made.\"\n\n\nPOLL_INTERVAL=${POLL_INTERVAL:-5}\nNOTICE_URL=${NOTICE_URL:-http://169.254.169.254/latest/meta-data/spot/termination-time}\n\n#echo \"Send test message to queue ${QUEUE_URL} with message ${MESSAGE}\"\n#MESSAGE=\"[{'status': 'test spot termination', 'public_hostname': ${NODE_NAME}, 'public_port': NA, 'region': 'us-east'}]\"\n#MESSAGE_GRP_ID=\"gsGrp_us-east-1\"\n#aws sqs send-message --queue-url ${QUEUE_URL} --message-body \"${MESSAGE}\" --message-group-id ${MESSAGE_GRP_ID}\n\necho \"Polling ${NOTICE_URL} every ${POLL_INTERVAL} second(s)\"\nwhile http_status=$(curl -o /dev/null -w '%{http_code}' -sL ${NOTICE_URL}); [ ${http_status} -ne 200 ]; do\n  echo $(date): ${http_status}\n  sleep ${POLL_INTERVAL}\ndone\n\necho $(date): ${http_status}\n\nMESSAGE=\"[{'status': 'spot termination','instance_az': ${INSTANCE_AZ},'instance_group':${INSTANCE_GROUP},'time':${TIME_ST}, 'instance_type': ${INSTANCE_TYPE}, 'public_hostname': ${NODE_NAME}, 'public_port': NA, 'region': ${AWS_DEFAULT_REGION}]\"\necho MESSAGE=$MESSAGE\naws sqs send-message --queue-url ${QUEUE_URL} --message-body \"${MESSAGE}\" \n\necho \"Drain the node.\"\nkubectl drain ${NODE_NAME} --force --ignore-daemonsets\n\necho \"Sleep for 200 seconds to prevent raise condition\"\n# The instance should be terminated by the end of the sleep assumming 120 sec notification time\nsleep 200\n", "num_lines": 77}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    # Remove all nvidia gl libraries if they exists to run training in SageMaker.\n    rm -rf /usr/local/nvidia/lib/libGL*\n    rm -rf /usr/local/nvidia/lib/libEGL*\n    rm -rf /usr/local/nvidia/lib/libOpenGL*\n    rm -rf /usr/local/nvidia/lib64/libGL*\n    rm -rf /usr/local/nvidia/lib64/libEGL*\n    rm -rf /usr/local/nvidia/lib64/libOpenGL*\n\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" /changehostname.c\n\n    gcc -o /changehostname.o -c -fPIC -Wall /changehostname.c\n    gcc -o /libchangehostname.so -shared -export-dynamic /changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so xvfb-run --auto-servernum -s \"-screen 0 1400x900x24\" train\nelif [ $1 == 'serve' ]\nthen\n    serve\nfi\n", "num_lines": 25}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsed -ie \"s/PLACEHOLDER_HOSTNAME/$1/g\" /changehostname.c\n\ngcc -o /changehostname.o -c -fPIC -Wall /changehostname.c\ngcc -o /libchangehostname.so -shared -export-dynamic /changehostname.o -ldl\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\n\nchmod +x blazing_text/serve\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${account}\".dkr.ecr.\"${region}\".amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "docker build -t test:latest .\npython local_test/test_container.py\n", "num_lines": 3}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "# get my account name \n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\n\n# authenticate my account\naws ecr get-login-password --region ${region} | docker login --username AWS \\\n    --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n\n# create a repo in my ecr called test\naws ecr describe-repositories --repository-names \"test\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"test\" > /dev/null\nfi\n\n# tag the test image with account name \nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/test:latest\"\ndocker tag test:latest ${fullname}\ndocker push ${fullname}\n\n\n", "num_lines": 26}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\nimage=$1\n\nif [ \"$image\" == \"\" ]\nthen\n    echo \"Usage: $0 <image-name>\"\n    exit 1\nfi\n\nchmod +x decision_trees/train\nchmod +x decision_trees/serve\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\nfi\n\n# Get the login command from ECR and execute it directly\naws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${account}\".dkr.ecr.\"${region}\".amazonaws.com\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build  -t ${image} .\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npayload=$1\ncontent=${2:-text/csv}\n\ncurl --data-binary @${payload} -H \"Content-Type: ${content}\" -v http://localhost:8080/invocations\n", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\ndocker run -v $(pwd)/test_dir:/opt/ml -p 8080:8080 --rm ${image} serve\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nimage=$1\n\nmkdir -p test_dir/model\nmkdir -p test_dir/output\n\nrm test_dir/model/*\nrm test_dir/output/*\n\ndocker run -v $(pwd)/test_dir:/opt/ml --rm ${image} train\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "# \u00c2\u00a9 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.\n#\n# This AWS Content is provided subject to the terms of the AWS Customer Agreement\n# available at http://aws.amazon.com/agreement or other written agreement between\n# Customer and either Amazon Web Services, Inc. or Amazon Web Services EMEA SARL or both.\n\n#!/bin/sh\n\nREPO=$1\nS3_BUCKET_NAME=$2\n\nNAME=sourcedir\nPUSH=true\n\nif [ -z ${REPO} ] ;\nthen\n    echo \"Repository not specified\"\n    exit 1\nfi\n\nSCRIPT=$(readlink -f \"$0\")\n# Absolute path this script is in, thus /home/user/bin\nSCRIPTPATH=$(dirname \"$SCRIPT\")\n\ncd $SCRIPTPATH/$REPO/src\ntar --exclude='data' -czvf ${NAME}.tar.gz *\n\nrm -rf ../dist/$REPO\nmkdir ../dist\nmkdir ../dist/$REPO\n\nmv ${NAME}.tar.gz ../dist/$REPO\n\nif [ -z ${S3_BUCKET_NAME} ] ;\nthen\n  echo \"S3 Bucket not specified, no upload\"\n  PUSH=false\nfi\n\nif $PUSH ;\nthen\n  echo \"Uploading s3://${S3_BUCKET_NAME}/artifact/${REPO}/${NAME}.tar.gz\"\n\n  aws s3 cp ../dist/${REPO}/${NAME}.tar.gz s3://${S3_BUCKET_NAME}/artifact/${REPO}/${NAME}.tar.gz\nelse\n  exit 1\nfi", "num_lines": 47}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# The name of our algorithm\nrepo=$1\nregistry_name=$2\nimage_tag=$3\ndocker_file=$4\nplatforms=$5\n\necho \"[INFO]: registry_name=${registry_name}\"\necho \"[INFO]: image_tag=${image_tag}\"\necho \"[INFO]: docker_file=${docker_file}\"\necho \"[INFO]: platforms=${platforms}\"\n\ncd $repo\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\n\necho \"[INFO]: Region ${region}\"\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${registry_name}:${image_tag}\"\n\necho \"[INFO]: Image name: ${fullname}\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${registry_name}\" > /dev/null 2>&1\n\naws ecr create-repository --repository-name \"${registry_name}\" > /dev/null\n\n## If you are extending Amazon SageMaker Images, you need to login to the account\n# Get the login command from ECR and execute it directly\npassword=$(aws ecr --region ${region} get-login-password)\n\ndocker login -u AWS -p ${password} \"${account}.dkr.ecr.${region}.amazonaws.com\"\n\nif [ -z ${platforms} ]\nthen\n  docker build -t ${fullname} -f ${docker_file} .\nelse\n  echo \"Provided platform = ${platforms}\"\n  docker build -t ${fullname} -f ${docker_file} . --platform=${platforms}\nfi\n\ndocker push ${fullname}", "num_lines": 48}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 78}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -n true\nif [ $? -eq 0 ]; then\n  echo \"The user has root access.\"\nelse\n  echo \"The user does not have root access. Everything required to run the notebook is already installed and setup. We are good to go!\"\n  exit 0\nfi\n\n# Do we have GPU support?\nnvidia-smi > /dev/null 2>&1\nif [ $? -eq 0 ]; then\n  # check if we have nvidia-docker\n  NVIDIA_DOCKER=`rpm -qa | grep -c nvidia-docker2`\n  if [ $NVIDIA_DOCKER -eq 0 ]; then\n    # Install nvidia-docker2\n    DOCKER_VERSION=`yum list docker | tail -1 | awk '{print $2}' | head -c 2`\n\n    if [ $DOCKER_VERSION -eq 17 ]; then\n      DOCKER_PKG_VERSION='17.09.1ce-1.111.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker17.09.1.ce.amzn1'\n    else\n      DOCKER_PKG_VERSION='18.06.1ce-3.17.amzn1'\n      NVIDIA_DOCKER_PKG_VERSION='2.0.3-1.docker18.06.1.ce.amzn1'\n    fi\n\n    sudo yum -y remove docker\n    sudo yum -y install docker-$DOCKER_PKG_VERSION\n\n    sudo /etc/init.d/docker start\n\n    curl -s -L https://nvidia.github.io/nvidia-docker/amzn1/nvidia-docker.repo | sudo tee /etc/yum.repos.d/nvidia-docker.repo\n    sudo yum install -y nvidia-docker2-$NVIDIA_DOCKER_PKG_VERSION\n    sudo cp daemon.json /etc/docker/daemon.json\n    sudo pkill -SIGHUP dockerd\n    echo \"installed nvidia-docker2\"\n  else\n    echo \"nvidia-docker2 already installed. We are good to go!\"\n  fi\nfi\n\n# This is common for both GPU and CPU instances\n\n# check if we have docker-compose\ndocker-compose version >/dev/null 2>&1\nif [ $? -ne 0 ]; then\n  # install docker compose\n  pip install docker-compose\nfi\n\n# check if we need to configure our docker interface\nSAGEMAKER_NETWORK=`docker network ls | grep -c sagemaker-local`\nif [ $SAGEMAKER_NETWORK -eq 0 ]; then\n  docker network create --driver bridge sagemaker-local\nfi\n\n# Notebook instance Docker networking fixes\nRUNNING_ON_NOTEBOOK_INSTANCE=`sudo iptables -S OUTPUT -t nat | grep -c 169.254.0.2`\n\n# Get the Docker Network CIDR and IP for the sagemaker-local docker interface.\nSAGEMAKER_INTERFACE=br-`docker network ls | grep sagemaker-local | cut -d' ' -f1`\nDOCKER_NET=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f1`\nDOCKER_IP=`ip route | grep $SAGEMAKER_INTERFACE | cut -d\" \" -f12`\n\n# check if both IPTables and the Route Table are OK.\nIPTABLES_PATCHED=`sudo iptables -S PREROUTING -t nat | grep -c $SAGEMAKER_INTERFACE`\nROUTE_TABLE_PATCHED=`sudo ip route show table agent | grep -c $SAGEMAKER_INTERFACE`\n\nif [ $RUNNING_ON_NOTEBOOK_INSTANCE -gt 0 ]; then\n\n  if [ $ROUTE_TABLE_PATCHED -eq 0 ]; then\n    # fix routing\n    sudo ip route add $DOCKER_NET via $DOCKER_IP dev $SAGEMAKER_INTERFACE table agent\n  else\n    echo \"SageMaker instance route table setup is ok. We are good to go.\"\n  fi\n\n  if [ $IPTABLES_PATCHED -eq 0 ]; then\n    sudo iptables -t nat -A PREROUTING  -i $SAGEMAKER_INTERFACE -d 169.254.169.254/32 -p tcp -m tcp --dport 80 -j DNAT --to-destination 169.254.0.2:9081\n    echo \"iptables for Docker setup done\"\n  else\n    echo \"SageMaker instance routing for Docker is ok. We are good to go!\"\n  fi\nfi\n", "num_lines": 86}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython -m pip install transformers==4.9.1\npython pt_exporter.py", "num_lines": 3}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython -m pip install transformers==4.9.1\npython onnx_exporter.py\ntrtexec --onnx=model.onnx --saveEngine=model_bs16.plan --minShapes=token_ids:1x512,attn_mask:1x512 --optShapes=token_ids:16x512,attn_mask:16x512 --maxShapes=token_ids:128x512,attn_mask:128x512 --fp16 --verbose --workspace=14000 | tee conversion_bs16_dy.txt", "num_lines": 4}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n sd_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nsource activate sd_env\nexport PYTHONNOUSERSITE=True\npip install torch \npip install transformers ftfy scipy accelerate\npip install diffusers==0.9.0\npip install transformers[onnxruntime]\npip install conda-pack\nconda-pack", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npip install transformers ftfy scipy\npip install transformers[onnxruntime]\npip install diffusers\ncd /mount\npython export.py\n\n# Accelerating VAE with TensorRT\ntrtexec --onnx=vae.onnx --saveEngine=vae.plan --minShapes=latent_sample:1x4x64x64 --optShapes=latent_sample:4x4x64x64 --maxShapes=latent_sample:8x4x64x64 --fp16\n\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n processing_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nexport PYTHONNOUSERSITE=True\nconda activate processing_env && conda install -y transformers numpy conda-pack && conda install -y pytorch torchvision torchaudio -c pytorch\nconda-pack -n processing_env", "num_lines": 7}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nMODEL_NAME=$1\npython -m pip install transformers==4.9.1\npython onnx_exporter.py --model $MODEL_NAME\n\ntrtexec \\\n    --onnx=model.onnx \\\n    --saveEngine=model.plan \\\n    --minShapes=token_ids:1x128,attn_mask:1x128 \\\n    --optShapes=token_ids:16x128,attn_mask:16x128 \\\n    --maxShapes=token_ids:32x128,attn_mask:32x128 \\\n    --verbose \\\n    --workspace=14000 \\\n| tee conversion.txt", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n processing_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nsource activate processing_env\nexport PYTHONNOUSERSITE=True\npip install torch \npip install transformers\npip install conda-pack\nconda-pack", "num_lines": 10}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nMODEL_NAME=$1\npython -m pip install transformers==4.9.1\npython onnx_exporter.py --model $MODEL_NAME\n\ntrtexec \\\n    --onnx=model.onnx \\\n    --saveEngine=model.plan \\\n    --minShapes=token_ids:1x128,attn_mask:1x128 \\\n    --optShapes=token_ids:16x128,attn_mask:16x128 \\\n    --maxShapes=token_ids:32x128,attn_mask:32x128 \\\n    --verbose \\\n    --workspace=14000 \\\n| tee conversion.txt", "num_lines": 14}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# The name of our algorithm\nrepo=$1\nregistry_name=$2\nimage_tag=$3\ndocker_file=$4\nplatforms=$5\n\necho \"[INFO]: registry_name=${registry_name}\"\necho \"[INFO]: image_tag=${image_tag}\"\necho \"[INFO]: docker_file=${docker_file}\"\necho \"[INFO]: platforms=${platforms}\"\n\ncd $repo\n\naccount=$(aws sts get-caller-identity --query Account --output text)\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\n\necho \"[INFO]: Region ${region}\"\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${registry_name}:${image_tag}\"\n\necho \"[INFO]: Image name: ${fullname}\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${registry_name}\" > /dev/null 2>&1\n\naws ecr create-repository --repository-name \"${registry_name}\" > /dev/null\n\n## If you are extending Amazon SageMaker Images, you need to login to the account\n# Get the login command from ECR and execute it directly\npassword=$(aws ecr --region ${region} get-login-password)\n\ndocker login -u AWS -p ${password} \"${account}.dkr.ecr.${region}.amazonaws.com\"\n\nif [ -z ${platforms} ]\nthen\n  docker build -t ${fullname} -f ${docker_file} .\nelse\n  echo \"Provided platform = ${platforms}\"\n  docker build -t ${fullname} -f ${docker_file} . --platform=${platforms}\nfi\n\ndocker push ${fullname}", "num_lines": 48}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nIMAGE_NAME=$1\nREGISTRY_NAME=$2\nSM_IMAGE_NAME=$3\nROLE_ARN=$4\n\nif [ -z ${IMAGE_NAME} ]\nthen\n  echo \"[INFO]: IMAGE_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${REGISTRY_NAME} ]\nthen\n  echo \"[INFO]: REGISTRY_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${SM_IMAGE_NAME} ]\nthen\n  echo \"[INFO]: SM_IMAGE_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${ROLE_ARN} ]\nthen\n  echo \"[INFO]: ROLE_ARN not passed\"\n  exit 1\nfi\n\necho \"[INFO]: IMAGE_NAME=${IMAGE_NAME}\"\necho \"[INFO]: REGISTRY_NAME=${REGISTRY_NAME}\"\necho \"[INFO]: SM_IMAGE_NAME=${SM_IMAGE_NAME}\"\necho \"[INFO]: ROLE_ARN=${ROLE_ARN}\"\n\naws sagemaker create-image \\\n    --image-name ${SM_IMAGE_NAME} \\\n    --role-arn ${ROLE_ARN} \\\n    || exit 1\n\naccount=$(aws sts get-caller-identity --query Account --output text)\nregion=$(aws configure get region)\n\naws sagemaker create-image-version \\\n    --image-name ${SM_IMAGE_NAME} \\\n    --base-image \"${account}.dkr.ecr.${region}.amazonaws.com/${REGISTRY_NAME}:latest\" \\\n    || exit 1\n\naws sagemaker delete-app-image-config --app-image-config-name ${SM_IMAGE_NAME}-config\n\naws sagemaker describe-image-version --image-name ${SM_IMAGE_NAME}\n\naws sagemaker create-app-image-config --cli-input-json file://${IMAGE_NAME}/app-image-config.json", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"studio-domain-config.json\"\n\naws sagemaker update-domain --cli-input-json file://studio-domain-config.json", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nIMAGE_NAME=$1\nREGISTRY_NAME=$2\nSM_IMAGE_NAME=$3\nROLE_ARN=$4\n\nif [ -z ${IMAGE_NAME} ]\nthen\n  echo \"[INFO]: IMAGE_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${REGISTRY_NAME} ]\nthen\n  echo \"[INFO]: REGISTRY_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${SM_IMAGE_NAME} ]\nthen\n  echo \"[INFO]: SM_IMAGE_NAME not passed\"\n  exit 1\nfi\n\nif [ -z ${ROLE_ARN} ]\nthen\n  echo \"[INFO]: ROLE_ARN not passed\"\n  exit 1\nfi\n\necho \"[INFO]: IMAGE_NAME=${IMAGE_NAME}\"\necho \"[INFO]: REGISTRY_NAME=${REGISTRY_NAME}\"\necho \"[INFO]: SM_IMAGE_NAME=${SM_IMAGE_NAME}\"\necho \"[INFO]: ROLE_ARN=${ROLE_ARN}\"\n\naccount=$(aws sts get-caller-identity --query Account --output text)\nregion=$(aws configure get region)\n\naws sagemaker create-image-version \\\n    --image-name ${SM_IMAGE_NAME} \\\n    --base-image \"${account}.dkr.ecr.${region}.amazonaws.com/${REGISTRY_NAME}:latest\" \\\n    || exit 1\n\naws sagemaker delete-app-image-config --app-image-config-name ${SM_IMAGE_NAME}-config\n\naws sagemaker describe-image-version --image-name ${SM_IMAGE_NAME}\n\naws sagemaker create-app-image-config --cli-input-json file://${IMAGE_NAME}/app-image-config.json", "num_lines": 49}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda create -y -n preprocessing_env python=3.8\nsource ~/anaconda3/etc/profile.d/conda.sh\nconda activate preprocessing_env\nexport PYTHONNOUSERSITE=True\nconda install -y -c conda-forge pandas scikit-learn\npip install conda-pack\nconda-pack\n", "num_lines": 10}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsudo -u ec2-user -i <<'EOF'\n\nmkdir -p rapids_kernel\ncd rapids_kernel\nwget -q https://rapidsai-data.s3.us-east-2.amazonaws.com/conda-pack/rapidsai/rapids21.06_cuda11.0_py3.8.tar.gz\necho \"wget completed\"\ntar -xzf *.gz\necho \"unzip completed\"\nsource /home/ec2-user/rapids_kernel/bin/activate\nconda-unpack \necho \"unpack completed\"\npython -m ipykernel install --user --name rapids-2106\necho \"kernel install completed\"\n\nEOF\n", "num_lines": 20}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython -m pip install transformers==4.9.1\npython onnx_exporter.py\npython pt_exporter.py\ntrtexec --onnx=model.onnx --saveEngine=model_bs16.plan --minShapes=token_ids:1x128,attn_mask:1x128 --optShapes=token_ids:16x128,attn_mask:16x128 --maxShapes=token_ids:128x128,attn_mask:128x128 --fp16 --verbose --workspace=14000 | tee conversion_bs16_dy.txt\n", "num_lines": 6}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npython onnx_exporter.py\npython pt_exporter.py\ntrtexec --onnx=model.onnx --saveEngine=model.plan --explicitBatch --minShapes=input:1x3x224x224 --optShapes=input:128x3x224x224 --maxShapes=input:128x3x224x224 --fp16 --verbose | tee conversion.txt\n", "num_lines": 5}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ \"$1\" = \"serve\" ]]; then\n    shift 1\n    printenv\n    ls /opt\n    torchserve --start --ts-config /home/model-server/config.properties --model-store /opt/ml/model --models all \n     \nelse\n    eval \"$@\"\nfi\n\n# prevent docker exit\ntail -f /dev/null\n\n", "num_lines": 17}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /usr/bin/env bash\nset -e\n\n# Get the listen port from the SM env variable, otherwise default to 8080\nLISTEN_PORT=${SAGEMAKER_BIND_TO_PORT:-8080}\n\n# Set the number of gunicorn worker processes\nGUNICORN_WORKER_COUNT=$(nproc)\n\n# Start flask app\nexec gunicorn -w $GUNICORN_WORKER_COUNT -b 0.0.0.0:$LISTEN_PORT main:app\n", "num_lines": 12}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 4 ]; then\n    dlc_account_id=$1\n    region=$2\n    image=$3\n    tag=$4\nelse\n    echo \"usage: $0 <dlc-account-id> $1 <aws-region> $2 <image-repo> $3 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n\ndocker build . -t ${image} -f ${DIR}/Dockerfile  --build-arg dlc_account_id=${dlc_account_id} --build-arg region=${region}\ndocker tag ${image} ${fullname}\ndocker push ${fullname}\n\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 50}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "export HDF5_USE_FILE_LOCKING=FALSE\n\npython ./DeepLearningExamples/PyTorch/LanguageModeling/BERT/run_pretraining.py \\\n--input_dir=$SM_CHANNEL_TRAINING \\\n--output_dir=$SM_MODEL_DIR \\\n--config_file=./DeepLearningExamples/PyTorch/LanguageModeling/BERT/bert_config.json \\\n--bert_model=bert-large-uncased \\\n--train_batch_size=64 \\\n--max_seq_length=128 \\\n--max_predictions_per_seq=20 \\\n--max_steps=900864 \\\n--warmup_proportion=0.2843 \\\n--num_steps_per_checkpoint=900864 \\\n--learning_rate=1.12e-3 \\\n--seed=42 \\\n--fp16 \\\n--do_train \\\n--json-summary ./DeepLearningExamples/PyTorch/LanguageModeling/BERT/results/dllogger.json 2>&1\n\n", "num_lines": 20}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Change the active directory to the one that contains the training script\ncd ${DIR}/SMDDP-Examples/pytorch/image_classification\n\nif [ \"$#\" -eq 4 ]; then\n    dlc_account_id=$1\n    region=$2\n    image=$3\n    tag=$4\nelse\n    echo \"usage: $0 <dlc-account-id> $1 <aws-region> $2 <image-repo> $3 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\ndocker build . -t ${image} -f ${DIR}/Dockerfile  --build-arg dlc_account_id=${dlc_account_id} --build-arg region=${region}\ndocker tag ${image} ${fullname}\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 54}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 4 ]; then\n    dlc_account_id=$1\n    region=$2\n    image=$3\n    tag=$4\nelse\n    echo \"usage: $0 <dlc-account-id> $1 <aws-region> $2 <image-repo> $3 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\n\ndocker build . -t ${image} -f ${DIR}/Dockerfile  --build-arg dlc_account_id=${dlc_account_id} --build-arg region=${region}\ndocker tag ${image} ${fullname}\ndocker push ${fullname}\n\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 50}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to tag the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nif [ \"$#\" -eq 3 ]; then\n    region=$1\n    image=$2\n    tag=$3\nelse\n    echo \"usage: $0 <aws-region> $1 <image-repo> $2 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n$(aws ecr get-login --no-include-email --region ${region}  --registry-ids 763104351884)\ndocker tag mlperf/rnn_speech_recognition_smddp:latest ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ];\nthen\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 46}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 3 ]; then\n    region=$1\n    image=$2\n    tag=$3\nelse\n    echo \"usage: $0 <aws-region> $1 <image-repo> $2 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n$(aws ecr get-login --no-include-email --region ${region}  --registry-ids 763104351884)\ndocker build ${DIR}/ -t ${image} -f ${DIR}/Dockerfile  --build-arg region=${region}\ndocker tag ${image} ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi\n", "num_lines": 50}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 3 ]; then\n    region=$1\n    image=$2\n    tag=$3\nelse\n    echo \"usage: $0 <aws-region> $1 <image-repo> $2 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n$(aws ecr get-login --no-include-email --region us-west-2  --registry-ids 763104351884)\ndocker build ${DIR}/ -t ${image} -f ${DIR}/Dockerfile  --build-arg region=${region}\ndocker tag ${image} ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 49}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 3 ]; then\n    region=$1\n    image=$2\n    tag=$3\nelse\n    echo \"usage: $0 <aws-region> $1 <image-repo> $2 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\ndocker build ${DIR}/ -t ${image} -f ${DIR}/Dockerfile  --build-arg region=${region}\ndocker tag ${image} ${fullname}\n\naws ecr get-login-password --region ${region} \\\n| docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 50}
{"repo_name": "amazon-sagemaker-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This script shows how to build the Docker image and push it to ECR to be ready for use\n# by SageMaker.\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n# set region\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [ \"$#\" -eq 3 ]; then\n    region=$1\n    image=$2\n    tag=$3\nelse\n    echo \"usage: $0 <aws-region> $1 <image-repo> $2 <image-tag>\"\n    exit 1\nfi\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:${tag}\"\n\n# If the repository doesn't exist in ECR, create it.\naws ecr describe-repositories --region ${region} --repository-names \"${image}\" > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n    echo \"creating ECR repository : ${fullname} \"\n    aws ecr create-repository --region ${region} --repository-name \"${image}\" > /dev/null\nfi\n\n$(aws ecr get-login --no-include-email --region us-west-2  --registry-ids 763104351884)\ndocker build ${DIR}/ -t ${image} -f ${DIR}/Dockerfile  --build-arg region=${region}\ndocker tag ${image} ${fullname}\n\n# Get the login command from ECR and execute it directly\n$(aws ecr get-login --region ${region} --no-include-email)\ndocker push ${fullname}\nif [ $? -eq 0 ]; then\n\techo \"Amazon ECR URI: ${fullname}\"\nelse\n\techo \"Error: Image build and push failed\"\n\texit 1\nfi", "num_lines": 49}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# This function builds, packages and deploys a region-specific operator to an ECR repo and output bucket.\n# Parameter:\n#    $1: The region of the ECR repo.\n#    $2: The stage in the pipeline for the output account. (prod/beta/dev)\n# e.g. build_canary us-east-1 prod\nfunction build_canary()\n{\n  local account_region=\"$1\"\n  local stage=\"$2\"\n\n  # Match stage to pipeline type\n  if [ \"$stage\" != \"$PIPELINE_STAGE\" ]; then\n    return\n  fi\n\n  $(aws ecr get-login --no-include-email --region $CANARY_ECR_REGION --registry-ids $AWS_ACCOUNT_ID)\n\n  # Download the operator for this canary\n  pushd tests\n  aws s3 cp s3://$ALPHA_TARBALL_BUCKET/${CODEBUILD_RESOLVED_SOURCE_VERSION}/sagemaker-k8s-operator-${account_region}.tar.gz sagemaker-k8s-operator.tar.gz\n\n  # Build and push the newest canary tests with SHA1 and latest tags\n  IMAGE=$AWS_ACCOUNT_ID.dkr.ecr.$CANARY_ECR_REGION.amazonaws.com/$CANARY_ECR_REPOSITORY\n  SHA_REGION_TAG=${CODEBUILD_RESOLVED_SOURCE_VERSION}-${account_region}\n  REGION_TAG=$account_region\n\n  # Push a canary tagged with the SHA and the region\n  IMG=$IMAGE:$SHA_REGION_TAG COMMIT_SHA=$CODEBUILD_RESOLVED_SOURCE_VERSION bash build_canary.sh\n  docker push $IMAGE:$SHA_REGION_TAG\n\n  # Tag it with just the region name for latest\n  docker tag $IMAGE:$SHA_REGION_TAG $IMAGE:$REGION_TAG\n  docker push $IMAGE:$REGION_TAG\n  popd\n}\n\n# Replace JSON single quotes with double quotes for jq to understand\nACCOUNTS_ESCAPED=`echo $ACCOUNTS | sed \"s/'/\\\"/g\"`\nfor row in $(echo ${ACCOUNTS_ESCAPED} | jq -r '.[] | @base64'); do\n  _jq() {\n    echo ${row} | base64 --decode | jq -r ${1}\n  }\n\n  region=\"$(_jq '.region')\"\n  stage=\"$(_jq '.stage')\"\n  build_canary \"$region\" \"$stage\"\ndone", "num_lines": 51}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script will build the integration test container. This container contains\n# all the tools necessary for running the build and test steps for each of the\n# CodeBuild projects. The script will also tag the container with the latest\n# commit SHA, and with the \"latest\" tag, then push to an ECR repository.\n\nset -x\n\n# Build new integration test container\npushd tests\nIMG=$INTEGRATION_CONTAINER_REPOSITORY bash build_integration.sh\npopd\n\n# Log into ECR\n$(aws ecr get-login --no-include-email --region $REGION --registry-ids $AWS_ACCOUNT_ID)\n\n# Tag the container with SHA and latest\ndocker tag $INTEGRATION_CONTAINER_REPOSITORY $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$INTEGRATION_CONTAINER_REPOSITORY:$CODEBUILD_RESOLVED_SOURCE_VERSION\ndocker tag $INTEGRATION_CONTAINER_REPOSITORY $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$INTEGRATION_CONTAINER_REPOSITORY:latest\n\n# Push the newly tagged containers\ndocker push $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$INTEGRATION_CONTAINER_REPOSITORY:$CODEBUILD_RESOLVED_SOURCE_VERSION\ndocker push $AWS_ACCOUNT_ID.dkr.ecr.$REGION.amazonaws.com/$INTEGRATION_CONTAINER_REPOSITORY:latest", "num_lines": 24}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "RELEASE_BUCKET_NAME_FMT=\"%s-%s\"\n\nRELEASE_BINARY_PREFIX_FMT=\"s3://%s/kubectl-smlogs-plugin\"\nALPHA_BINARY_PREFIX_FMT=\"s3://%s/%s\"\n\nALPHA_LINUX_BINARY_PATH_FMT=\"%s/kubectl-smlogs-plugin.linux.amd64.tar.gz\"\nALPHA_DARWIN_BINARY_PATH_FMT=\"%s/kubectl-smlogs-plugin.darwin.amd64.tar.gz\"\n\nRELEASE_LINUX_BINARY_PATH_FMT=\"%s/%s/linux.amd64.tar.gz\"\nRELEASE_DARWIN_BINARY_PATH_FMT=\"%s/%s/darwin.amd64.tar.gz\"\n\nPUBLIC_CP_ARGS=\"--acl public-read\"", "num_lines": 12}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nBUNDLED_RELEASE_PATH=\"release/\"\nTMP_RELEASE_PATH=\"/tmp/release\"\n\nmkdir -p \"${TMP_RELEASE_PATH}\"\n\n# Create installers from CRDs into temporary directory\nINSTALLER_PATH=\"${TMP_RELEASE_PATH}\" make create-installers\n\n# Diff the two folders, excluding hidden files (such as .gitkeep)\ndiff -r --exclude=\".*\" \"${TMP_RELEASE_PATH}\" \"${BUNDLED_RELEASE_PATH}\"\n\nif [ $? -ne 0 ]; then\n  echo \"Release files did not match. See diff above for more details\"\n  exit 1\nfi", "num_lines": 17}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource codebuild/scripts/package_operators.sh\n\nset -x\n\n# Login to alpha ECR\n$(aws ecr get-login --no-include-email --region $ALPHA_REPOSITORY_REGION --registry-ids $ALPHA_ACCOUNT_ID)\n\n# Build the image with a temporary tag\nALPHA_IMAGE=$ALPHA_ACCOUNT_ID.dkr.ecr.$ALPHA_REPOSITORY_REGION.amazonaws.com/$REPOSITORY_NAME\nmake docker-build docker-push IMG=$ALPHA_IMAGE:$CODEBUILD_RESOLVED_SOURCE_VERSION\n\n# Ensure the smlogs are built and tarred into the alpha bucket\nSHOULD_PUSH_SMLOGS_ALPHA=\"true\"\n\n# Release the operator into the private alpha repository\n# Set as all to ensure it runs through the function\n# Add the alpha prefix for integration testing\npackage_operator \"$ALPHA_ACCOUNT_ID\" \"$ALPHA_REPOSITORY_REGION\" \"$REPOSITORY_NAME\" \"all\" \"-alpha\"", "num_lines": 20}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource codebuild/scripts/deployment_constants.sh\n\nset -e\n\n# Define alpha artifact locations\nprintf -v ALPHA_BUCKET_PREFIX $ALPHA_BINARY_PREFIX_FMT $ALPHA_TARBALL_BUCKET $CODEBUILD_RESOLVED_SOURCE_VERSION\n\nprintf -v ALPHA_LINUX_BINARY_PATH $ALPHA_LINUX_BINARY_PATH_FMT $ALPHA_BUCKET_PREFIX\nprintf -v ALPHA_DARWIN_BINARY_PATH $ALPHA_DARWIN_BINARY_PATH_FMT $ALPHA_BUCKET_PREFIX\n\n# This function deploys a region-specific operator to an ECR prod repo from the existing\n# image in the alpha repository. The function also copies across the smlogs binaries\n# from the alpha tarball bucket into the production buckets.\n# Parameter:\n#    $1: The account ID for the ECR repo.\n#    $2: The region of the ECR repo.\n#    $3: The name of the ECR repository.\nfunction deploy_from_alpha()\n{\n  local account_id=\"$1\"\n  local account_region=\"$2\"\n  local image_repository=\"$3\"\n\n  # Get the images from the alpha ECR repository\n  local dest_ecr_image=${account_id}.dkr.ecr.${account_region}.amazonaws.com/${image_repository}\n  local alpha_ecr_image=$ALPHA_ACCOUNT_ID.dkr.ecr.$ALPHA_REPOSITORY_REGION.amazonaws.com/${image_repository}\n\n  # Login to the alpha repository\n  $(aws ecr get-login --no-include-email --region $ALPHA_REPOSITORY_REGION --registry-ids $ALPHA_ACCOUNT_ID)\n  docker pull $alpha_ecr_image:$CODEBUILD_RESOLVED_SOURCE_VERSION\n\n  # Login to the prod repository\n  $(aws ecr get-login --no-include-email --region ${account_region} --registry-ids ${account_id})\n\n  # Clone the controller image to the repo\n  docker tag $alpha_ecr_image:$CODEBUILD_RESOLVED_SOURCE_VERSION ${dest_ecr_image}:$CODEBUILD_RESOLVED_SOURCE_VERSION\n  # TODO: Remove at the time of the next major version release\n  # This moves the `latest` tag along with master branch, which will cause backwards incompatibility for any major\n  # version updates.\n  docker tag $alpha_ecr_image:$CODEBUILD_RESOLVED_SOURCE_VERSION ${dest_ecr_image}:latest\n\n  # Push to the prod region\n  docker push ${dest_ecr_image}:$CODEBUILD_RESOLVED_SOURCE_VERSION\n\n  printf -v bucket_name $RELEASE_BUCKET_NAME_FMT $RELEASE_TARBALL_BUCKET_PREFIX $account_region\n  printf -v binary_prefix $RELEASE_BINARY_PREFIX_FMT $bucket_name\n\n  aws s3 cp \"$ALPHA_LINUX_BINARY_PATH\" \"$(printf $RELEASE_LINUX_BINARY_PATH_FMT $binary_prefix $CODEBUILD_RESOLVED_SOURCE_VERSION)\" $PUBLIC_CP_ARGS\n  aws s3 cp \"$ALPHA_DARWIN_BINARY_PATH\" \"$(printf $RELEASE_DARWIN_BINARY_PATH_FMT $binary_prefix $CODEBUILD_RESOLVED_SOURCE_VERSION)\" $PUBLIC_CP_ARGS\n}\n\n# This function builds, packages and deploys a region-specific operator to an ECR repo and output bucket.\n# Parameter:\n#    $1: The account ID for the ECR repo.\n#    $2: The region of the ECR repo.\n#    $3: The name of the ECR repository.\n#    $4: The stage in the pipeline for the output account. (prod/beta/dev)\n#    $5: (Optional) A suffix for the operator install bundle tarball.\n# e.g. package_operator 123456790 us-east-1 amazon-sagemaker-k8s-operator prod\nfunction package_operator()\n{\n  local account_id=\"$1\"\n  local account_region=\"$2\"\n  local image_repository=\"$3\"\n  local stage=\"$4\"\n  local tarball_suffix=\"${5:-}\"\n\n  # Only build images that match the release pipeline stage\n  if [ \"$stage\" != \"$PIPELINE_STAGE\" ] && [ \"$stage\" != \"all\" ]; then\n    return 0\n  fi\n\n  # Only push to ECR repos if this is run on the prod pipeline\n  if [ \"$stage\" == \"prod\" ] && [ \"$PIPELINE_STAGE\" == \"prod\" ]; then\n    deploy_from_alpha \"$account_id\" \"$account_region\" \"$image_repository\"\n  fi\n\n  # Build, push and update the CRD with controller image and current git SHA, create the tarball and extract it to pack\n  local ecr_image=${account_id}.dkr.ecr.${account_region}.amazonaws.com/${image_repository}\n  make modify-base-kustomize-us IMG=${ecr_image}:$CODEBUILD_RESOLVED_SOURCE_VERSION\n  make build-release-tarball\n  pushd bin\n    tar -xf sagemaker-k8s-operator-install-scripts.tar.gz\n  popd\n\n  # Create the smlog binary\n  pushd smlogs-kubectl-plugin\n    make build-release\n  popd\n\n  # Create a temporary dir and put all the necessary artifacts\n  rm -rf /tmp/sagemaker-k8s-operator\n  mkdir -p /tmp/sagemaker-k8s-operator\n  mkdir -p /tmp/sagemaker-k8s-operator/smlogs-plugin/darwin.amd64\n  mkdir -p /tmp/sagemaker-k8s-operator/smlogs-plugin/linux.amd64\n\n  cp -r bin/sagemaker-k8s-operator-install-scripts /tmp/sagemaker-k8s-operator\n  cp smlogs-kubectl-plugin/bin/kubectl-smlogs.linux.amd64 /tmp/sagemaker-k8s-operator/smlogs-plugin/linux.amd64/kubectl-smlogs\n  cp smlogs-kubectl-plugin/bin/kubectl-smlogs.darwin.amd64 /tmp/sagemaker-k8s-operator/smlogs-plugin/darwin.amd64/kubectl-smlogs\n\n  if [ \"$SHOULD_PUSH_SMLOGS_ALPHA\" == \"true\" ]; then\n    # Create temp dirs per binary and put smlogs into it\n    mkdir -p /tmp/kubectl-smlogs.linux.amd64\n    mkdir -p /tmp/kubectl-smlogs.darwin.amd64\n\n    cp smlogs-kubectl-plugin/bin/kubectl-smlogs.linux.amd64 /tmp/kubectl-smlogs.linux.amd64/kubectl-smlogs\n    cp smlogs-kubectl-plugin/bin/kubectl-smlogs.darwin.amd64 /tmp/kubectl-smlogs.darwin.amd64/kubectl-smlogs\n\n    pushd /tmp\n      tar cvzf kubectl-smlogs-plugin.linux.amd64.tar.gz kubectl-smlogs.linux.amd64\n      tar cvzf kubectl-smlogs-plugin.darwin.amd64.tar.gz kubectl-smlogs.darwin.amd64\n\n      aws s3 cp kubectl-smlogs-plugin.linux.amd64.tar.gz \"$ALPHA_LINUX_BINARY_PATH\"\n      aws s3 cp kubectl-smlogs-plugin.darwin.amd64.tar.gz \"$ALPHA_DARWIN_BINARY_PATH\"\n    popd\n  fi\n\n  # Create a tar ball which has CRDs, smlog and sm spec generator binaries\n  pushd /tmp\n    tar cvzf sagemaker-k8s-operator.tar.gz sagemaker-k8s-operator\n\n    # Upload the final tar ball to s3 with standard name and git SHA\n    aws s3 cp sagemaker-k8s-operator.tar.gz \"$ALPHA_BUCKET_PREFIX/sagemaker-k8s-operator-${account_region}${tarball_suffix}.tar.gz\"\n  popd\n}\n", "num_lines": 128}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource codebuild/scripts/package_operators.sh\n\n# Replace JSON single quotes with double quotes for jq to understand\nACCOUNTS_ESCAPED=`echo $ACCOUNTS | sed \"s/'/\\\"/g\"`\nfor row in $(echo ${ACCOUNTS_ESCAPED} | jq -r '.[] | @base64'); do\n  _jq() {\n    echo ${row} | base64 --decode | jq -r ${1}\n  }\n\n  repository_account=\"$(_jq '.repositoryAccount')\"\n  region=\"$(_jq '.region')\"\n  image_repository=\"${REPOSITORY_NAME}\"\n  stage=\"$(_jq '.stage')\"\n\n  package_operator \"$repository_account\" \"$region\" \"$image_repository\" \"$stage\"\ndone", "num_lines": 18}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource codebuild/scripts/deployment_constants.sh\n\nset -e\n\n# Define alpha artifact locations\nprintf -v ALPHA_BUCKET_PREFIX $ALPHA_BINARY_PREFIX_FMT $ALPHA_TARBALL_BUCKET $CODEBUILD_RESOLVED_SOURCE_VERSION\n\nprintf -v ALPHA_LINUX_BINARY_PATH $ALPHA_LINUX_BINARY_PATH_FMT $ALPHA_BUCKET_PREFIX\nprintf -v ALPHA_DARWIN_BINARY_PATH $ALPHA_DARWIN_BINARY_PATH_FMT $ALPHA_BUCKET_PREFIX\n\n# This function will pull an existing image + tag and push it with a new tag.\n# Parameter:\n#    $1: The repository and image to pull from.\n#    $2: The previous tag for that image.\n#    $3: The new tag to push for that image.\nfunction retag_image()\n{\n  local image=\"$1\"\n  local old_tag=\"$2\"\n  local new_tag=\"$3\"\n\n  docker pull $image:$old_tag\n  docker tag $image:$old_tag $image:$new_tag\n  docker push $image:$new_tag\n}\n\n# This function will push artifacts to their own folder with a given tag.\n# Parameter:\n#    $1: The new tag to push for the artifacts.\n#    $2: The region of the new artifacts.\nfunction retag_binaries()\n{\n  local new_tag=\"$1\"\n  local region=\"$2\"\n\n  printf -v release_bucket $RELEASE_BUCKET_NAME_FMT $RELEASE_TARBALL_BUCKET_PREFIX $region\n  printf -v binary_prefix $RELEASE_BINARY_PREFIX_FMT $release_bucket\n\n  aws s3 cp \"$ALPHA_LINUX_BINARY_PATH\" \"$(printf $RELEASE_LINUX_BINARY_PATH_FMT $binary_prefix $new_tag)\" $PUBLIC_CP_ARGS\n  aws s3 cp \"$ALPHA_DARWIN_BINARY_PATH\" \"$(printf $RELEASE_DARWIN_BINARY_PATH_FMT $binary_prefix $new_tag)\" $PUBLIC_CP_ARGS\n}\n\nGIT_TAG=\"$(git describe --tags --exact-match 2>/dev/null)\"\n\n# Only run the release process for tagged commits\nif [ \"$GIT_TAG\" == \"\" ]; then\n  exit 0\nfi\n\n# Replace JSON single quotes with double quotes for jq to understand\nACCOUNTS_ESCAPED=`echo $ACCOUNTS | sed \"s/'/\\\"/g\"`\nfor row in $(echo ${ACCOUNTS_ESCAPED} | jq -r '.[] | @base64'); do\n  _jq() {\n    echo ${row} | base64 --decode | jq -r ${1}\n  }\n\n  repository_account=\"$(_jq '.repositoryAccount')\"\n  region=\"$(_jq '.region')\"\n  image_repository=\"${REPOSITORY_NAME}\"\n  stage=\"$(_jq '.stage')\"\n\n  if [ \"$stage\" != \"$PIPELINE_STAGE\" ] && [ \"$stage\" != \"all\" ]; then\n    continue\n  fi\n\n  $(aws ecr get-login --no-include-email --region ${region} --registry-ids ${repository_account})\n\n  image=${repository_account}.dkr.ecr.${region}.amazonaws.com/${image_repository}\n  old_tag=\"${CODEBUILD_RESOLVED_SOURCE_VERSION}\"\n  full_tag=\"${GIT_TAG}\"\n\n  # Get minor and major version tags\n  [[ $GIT_TAG =~ ^v[0-9]+\\.[0-9]+ ]] && minor_tag=\"${BASH_REMATCH[0]}\"\n  [[ $GIT_TAG =~ ^v[0-9]+ ]] && major_tag=\"${BASH_REMATCH[0]}\"\n\n  echo \"Tagging $region with $full_tag\"\n\n  retag_image \"$image\" \"$old_tag\" \"$full_tag\"\n  retag_image \"$image\" \"$old_tag\" \"$minor_tag\"\n  retag_image \"$image\" \"$old_tag\" \"$major_tag\"\n\n  retag_binaries \"$full_tag\" \"$region\"\n  retag_binaries \"$minor_tag\" \"$region\"\n  retag_binaries \"$major_tag\" \"$region\"\n\n  echo \"Finished tagging $region with $full_tag\"\ndone", "num_lines": 89}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndocker build -f images/Dockerfile.canary . -t ${IMG:-canary-test-container} --build-arg DATA_BUCKET --build-arg COMMIT_SHA --build-arg RESULT_BUCKET", "num_lines": 3}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndocker build -f images/Dockerfile.integration -t ${IMG:-integration-test-container} .", "num_lines": 3}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndefault_operator_namespace=\"sagemaker-k8s-operator-system\"\n\n# Create a resource (run a test) given a specification within a given namespace.\n# Parameter:\n#    $1: Target namespace\n#    $2: Filename of the test\nfunction run_test()\n{\n  local target_namespace=\"$1\"\n  local file_name=\"$2\"\n\n  kubectl apply -n \"$target_namespace\" -f \"$file_name\"\n}\n\n# This function gets the sagemaker model name from k8s model\n# Parameter:\n#    $1: Namespace of the k8s model\n#    $2: Name of k8s model\n# e.g. get_sagemaker_model_from_k8s_model default k8s_model \nfunction get_sagemaker_model_from_k8s_model()\n{\n  local model_namespace=\"$1\"\n  local k8s_model_name=\"$2\"\n  # Get the second line and 3rd column, since valid output will be following\n  # NAME                    STATUS    SAGE-MAKER-MODEL-NAME\n  # xgboost-model           Created   model-5c06b18921e411ea91230292f5024981\n  kubectl get -n \"${model_namespace}\" model \"${k8s_model_name}\" | sed -n '2 p' |  awk '{print $3}' \n}\n\n# This function waits until a CRD has reached a particular state, or times out\n# Parameter:\n#    $1: Namespace of CRD\n#    $2: Kind of CRD\n#    $3: Instance of CRD\n#    $4: Timeout to complete the test\n#    $5: The status that verifies the job has succeeded.\nfunction wait_for_crd_status()\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$2\"\n  local crd_instance=\"$3\"\n  local timeout=\"$4\"\n  local desired_status=\"$5\"\n\n  timeout \"${timeout}\" bash -c \\\n    'until [ \"$(kubectl get -n \"$0\" \"$1\" \"$2\" -o=custom-columns=STATUS:.status | grep -i \"$3\" | wc -l)\" -eq \"1\" ]; do \\\n      sleep 5; \\\n    done' \"$crd_namespace\" \"$crd_type\" \"$crd_instance\" \"$desired_status\"\n\n  if [ $? -ne 0 ]; then\n    return 1\n  fi\n}\n\n# Force deletes all trainingJobs which might have been left dangling. \n# Parameter:\n#    $1: Namespace of CRD\nfunction force_delete_training_jobs()\n{\n  local crd_namespace=\"$1\"\n  training_jobs=$(kubectl get trainingjobs -n \"$crd_namespace\" -ojson | jq -r '.items | .[] | .metadata.name')\n \n  for job in $training_jobs\n  do\n      echo \"Removing finalizer for ${job}\"\n      kubectl patch -n \"$crd_namespace\" trainingjob $job -p '{\"metadata\":{\"finalizers\":null}}' --type=merge\n  done\n   \n  kubectl delete -n \"$crd_namespace\" trainingjob --all \n}\n\n# Cleans up all resources created during tests.\n# Parameter:\n#    $1: Namespace of CRD\nfunction delete_all_resources()\n{\n  local crd_namespace=\"$1\"\n  kubectl delete -n \"$crd_namespace\" hyperparametertuningjob --all\n  kubectl delete -n \"$crd_namespace\" processingjob --all\n  kubectl delete -n \"$crd_namespace\" batchtransformjob --all\n  # HAP must be deleted before hostingdeployment\n  kubectl delete -n \"$crd_namespace\" hostingautoscalingpolicies --all\n  kubectl delete -n \"$crd_namespace\" endpointconfig --all  \n  kubectl delete -n \"$crd_namespace\" hostingdeployment --all \n  kubectl delete -n \"$crd_namespace\" model --all\n\n  kubectl delete -n \"$crd_namespace\" trainingjob --all --timeout=3m\n  if [ $? -ne 0 ]; then\n    echo \"Delete failed, will need to force delete\"\n  fi\n\n  force_delete_training_jobs \"$crd_namespace\"\n}\n\n# A helper function to generate an IAM Role name for the current cluster and specified namespace\n# Parameter:\n#    $1: Namespace of CRD\nfunction generate_iam_role_name {\n    local crd_namespace=\"$1\"\n    local cluster=$(echo \"${cluster_name}\" | cut -d'/' -f2)\n\n    role_name=\"${cluster}-${crd_namespace}\"\n    # IAM Role name must have length less than 64\n    role_name=`echo $role_name|cut -c1-64`\n}\n\n# A function that cleans up an IAM Role after detaching the sagemaker access policy. \n# Parameter:\n#    $1: Name of the Role to be deleted\nfunction delete_generated_role {\n    local role_to_delete=\"${1}\"\n    # Delete the role associated with the cluster thats being deleted\n    aws iam detach-role-policy --role-name \"${role_to_delete}\" --policy-arn arn:aws:iam::aws:policy/AmazonSageMakerFullAccess\n    aws iam delete-role --role-name \"${role_to_delete}\"\n}\n\n# A function to print the operator logs for a given namespace\n# Parameter:\n#    $1: Namespace of the operator\nfunction get_manager_logs {\n    local crd_namespace=\"${1:-$default_operator_namespace}\"\n    if [ \"${PRINT_DEBUG}\" != \"false\" ]; then\n        echo \"Controller manager logs in the ${crd_namespace} namespace\"\n        kubectl -n \"${crd_namespace}\" logs \"$(kubectl get pods -n \"${crd_namespace}\" | grep sagemaker-k8s-operator-controller-manager | awk '{print $1}')\" manager\n    fi\n}\n\n# A function that cleans up Jobs, CRDs and Operator in the default namespace\nfunction cleanup_default_namespace {\n    set +e\n    get_manager_logs\n    delete_all_resources \"default\"\n    rolebased_operator_install_or_delete \"${default_operator_namespace}\" \"config/installers/rolebasedcreds\" \"${default_role_name}\" \"delete\"\n}\n\n# A helper function that generates the namespace-scoped operator installer yaml file with updated namespace and role.\n# It also applies/deletes the generated installer as specified.\n# Parameter:\n#    $1: Namespace to which the op pod is installed. For cluster scope, this value is not used.\n#    $2: Path to the kustomize source\n#    $3: Name of the IAM Role to use\n#    $4: kubectl action - apply or delete the resources defined in the installer\n# TODO:  Investigate if it is possible to overlay values when we build the Kustomize targets instead.\nfunction rolebased_operator_install_or_delete {\n    local crd_namespace=\"$1\"\n    local kustomize_file_path=\"$2\"\n    local role=\"$3\"\n    local kubectl_action=\"$4\"\n    local aws_account=$(aws sts get-caller-identity --query Account --output text)\n\n    kustomize build \"${kustomize_file_path}\" > temp_file.yaml\n    sed -i \"s/PLACEHOLDER-NAMESPACE/$crd_namespace/g\" temp_file.yaml\n    sed -i \"s/123456789012/$aws_account/g\" temp_file.yaml\n    sed -i \"s/DELETE_ME/$role/g\" temp_file.yaml\n\n    kubectl \"${kubectl_action}\" -f temp_file.yaml\n    rm temp_file.yaml\n}\n\n# A function that builds the kustomize target, then deploys the CRDs and operator in cluster scope.\n# Parameter:\n#    $1: Name of the IAM Role to use\nfunction operator_clusterscope_deploy {\n    local role=\"$1\"\n\n    # Allow for overriding the installation of the CRDs/controller image from the\n    # build scripts if we want to use our own installation\n\n        pushd sagemaker-k8s-operator/sagemaker-k8s-operator-install-scripts\n            echo \"Deploying the operator to the default namespace\"\n            rolebased_operator_install_or_delete \"${default_operator_namespace}\" \"config/installers/rolebasedcreds\" \"${role}\" \"apply\"\n        popd\n        echo \"Waiting for controller pod to be Ready\"\n        # Wait to increase chance that pod is ready\n        # TODO: Should upgrade kubectl to version that supports `kubectl wait pods --all`\n        sleep 60\n        kubectl get pods --all-namespaces | grep sagemaker\n}\n\n# A function that builds the kustomize target, then deploys the CRDs (cluster scope) and operator (namespace scope).\n# Parameter:\n#    $1: Namespace of CRD\n#    $2: Name of the IAM Role to use\nfunction operator_namespace_deploy {\n    local crd_namespace=\"$1\"\n    local role=\"$2\"\n\n    # Goto directory that holds the CRD\n    pushd sagemaker-k8s-operator/sagemaker-k8s-operator-install-scripts\n        kustomize build config/crd | kubectl apply -f -\n        rolebased_operator_install_or_delete ${crd_namespace} \"config/installers/rolebasedcreds/namespaced\" \"${role}\" \"apply\"\n    popd\n    echo \"Waiting for controller pod to be Ready\"\n    # Wait to increase chance that pod is ready\n    # TODO: Should upgrade kubectl to version that supports `kubectl wait pods --all`\n    sleep 60\n    echo \"Print manager pod status\"\n    kubectl get pods --all-namespaces | grep sagemaker\n}\n", "num_lines": 202}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource common.sh\nsource inject_tests.sh\n\n# Applies each of the resources needed for the canary tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction run_canary_tests\n{\n  local crd_namespace=\"$1\"\n\n  echo \"Injecting variables into tests\"\n  inject_all_variables\n\n  echo \"Starting Canary Tests\"\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-trainingjob.yaml\n  run_test \"${crd_namespace}\" testfiles/kmeans-mnist-processingjob.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-hpo.yaml\n  # Special code for batch transform till we fix issue-59\n  run_test \"${crd_namespace}\" testfiles/xgboost-model.yaml\n  # We need to get sagemaker model before running batch transform\n  verify_test \"${crd_namespace}\" Model xgboost-model 5m Created\n  yq w -i testfiles/xgboost-mnist-batchtransform.yaml \"spec.modelName\" \"$(get_sagemaker_model_from_k8s_model \"${crd_namespace}\" xgboost-model)\"\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-batchtransform.yaml \n  run_test \"${crd_namespace}\" testfiles/xgboost-hosting-deployment.yaml\n}\n\n# Applies each of the resources needed for the canary tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction run_canary_tests_china\n{\n  local crd_namespace=\"$1\"\n\n  echo \"Injecting variables into tests\"\n  inject_all_variables\n\n  echo \"Starting Canary Tests China\"\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-trainingjob-china.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-hpo-china.yaml\n  # Special code for batch transform till we fix issue-59\n  run_test \"${crd_namespace}\" testfiles/xgboost-model-china.yaml\n  # We need to get sagemaker model before running batch transform\n  verify_test \"${crd_namespace}\" Model xgboost-model-china 5m Created\n  yq w -i testfiles/xgboost-mnist-batchtransform-china.yaml \"spec.modelName\" \"$(get_sagemaker_model_from_k8s_model \"${crd_namespace}\" xgboost-model-china)\"\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-batchtransform-china.yaml\n}\n\n# Applies each of the resources needed for the integration tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction run_integration_tests\n{\n  local crd_namespace=\"$1\"\n  run_canary_tests \"${crd_namespace}\"\n\n  # TODO: Automate creation/testing of EFS file systems for relevant jobs\n  # Build prerequisite resources\n  if [ \"$FSX_ID\" == \"\" ]; then\n    echo \"Skipping build_fsx_from_s3 as fsx tests are disabled\"\n    #build_fsx_from_s3\n  fi\n\n  echo \"Starting integration tests\"\n  run_test \"${crd_namespace}\" testfiles/spot-xgboost-mnist-trainingjob.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-custom-endpoint.yaml\n  # run_test \"${crd_namespace}\" testfiles/efs-xgboost-mnist-trainingjob.yaml\n  # run_test \"${crd_namespace}\" testfiles/fsx-kmeans-mnist-trainingjob.yaml\n  run_test \"${crd_namespace}\" testfiles/spot-xgboost-mnist-hpo.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-hpo-custom-endpoint.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-trainingjob-debugger.yaml\n  run_test \"${crd_namespace}\" testfiles/xgboost-hosting-deployment-multi-container.yaml\n  run_hap_test \"${crd_namespace}\" named-xgboost-hosting testfiles/xgboost-hostingautoscaling.yaml testfiles/xgboost-hostingautoscaling-custom.yaml\n  run_test \"${crd_namespace}\" testfiles/hd-retain-varient-properties.yaml\n}\n\n# Verifies that all resources were created and are running/completed for the canary tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction verify_canary_tests\n{\n  local crd_namespace=\"$1\"\n  echo \"Verifying canary tests\"\n  verify_test \"${crd_namespace}\" TrainingJob xgboost-mnist 20m Completed\n  verify_test \"${crd_namespace}\" ProcessingJob kmeans-mnist 20m Completed\n  verify_test \"${crd_namespace}\" HyperparameterTuningJob xgboost-mnist-hpo 20m Completed\n  verify_test \"${crd_namespace}\" BatchTransformJob xgboost-batch 20m Completed \n  verify_test \"${crd_namespace}\" HostingDeployment xgboost-hosting 90m InService\n}\n\n# Verifies that all resources were created and are running/completed for the canary tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction verify_canary_tests_china\n{\n  local crd_namespace=\"$1\"\n  echo \"Verifying canary tests\"\n  verify_test \"${crd_namespace}\" TrainingJob xgboost-mnist-china 20m Completed\n  verify_test \"${crd_namespace}\" HyperparameterTuningJob xgboost-mnist-hpo-china 20m Completed\n  verify_test \"${crd_namespace}\" BatchTransformJob xgboost-batch-china 20m Completed\n}\n\n# Verifies that all resources were created and are running/completed for the integration tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction verify_integration_tests\n{\n  local crd_namespace=\"$1\"\n  echo \"Verifying integration tests\"\n  verify_canary_tests \"${crd_namespace}\"\n\n  verify_test \"${crd_namespace}\" TrainingJob spot-xgboost-mnist 20m Completed\n  verify_test \"${crd_namespace}\" TrainingJob xgboost-mnist-custom-endpoint 20m Completed\n  # verify_test \"${crd_namespace}\" TrainingJob efs-xgboost-mnist 20m Completed\n  # verify_test \"${crd_namespace}\" TrainingJob fsx-kmeans-mnist 20m Completed\n  verify_test \"${crd_namespace}\" HyperparameterTuningJob spot-xgboost-mnist-hpo 20m Completed\n  verify_test \"${crd_namespace}\" HyperparameterTuningJob xgboost-mnist-hpo-custom-endpoint 20m Completed\n  verify_test \"${crd_namespace}\" HostingDeployment xgboost-hosting-multi-container 90m InService\n  verify_test \"${crd_namespace}\" TrainingJob xgboost-mnist-debugger 20m Completed\n  # Verify that debug job has status\n  verify_debug_test \"${crd_namespace}\" TrainingJob xgboost-mnist-debugger 20m NoIssuesFound\n  verify_test \"${crd_namespace}\" HostingAutoscalingPolicy hap-predefined 5m Created\n  verify_test \"${crd_namespace}\" HostingAutoscalingPolicy hap-custom-metric 5m Created\n  # verify_hap_test \"3\"\n  verify_retain_varient_properties \"${crd_namespace}\" testfiles/hd-retain-varient-properties.yaml\n}\n\nfunction verify_retain_varient_properties(){\n  local crd_namespace=\"$1\"\n  local hostingdeployment_yaml_filepath=\"$2\"\n  local autoscaling_yaml_filepath=\"testfiles/hd-autoscaling-retain-varient-properties.yaml\"\n\n  echo \"Varifying retain varient properties\"\n\n  # endpoint is already created with instance count 1 and instance weight 2\n  enpoint_name=$(yq r $hostingdeployment_yaml_filepath \"spec.endpointName\")\n  endpoint_region=$(yq r $hostingdeployment_yaml_filepath \"spec.region\")\n  hostingdeployment_name=$(yq r $hostingdeployment_yaml_filepath \"metadata.name\")\n  wait_for_crd_status $crd_namespace HostingDeployment $hostingdeployment_name 90m InService\n\n  # verify that the already created endpoint has instance count 1 and weight 2\n  instance_count=$(aws sagemaker describe-endpoint --endpoint-name $enpoint_name --region $endpoint_region --query ProductionVariants[0].CurrentInstanceCount)\n  weight=$(aws sagemaker describe-endpoint --endpoint-name $enpoint_name --region $endpoint_region --query ProductionVariants[0].CurrentWeight | awk '{printf \"%.0f\\n\", $1}')\n  if [ \"${instance_count}\" == \"1\" ] && [ \"${weight}\" == \"2\" ]; then\n    echo \"Initial verification that instance_count is 1 and weight is 2\"\n  else\n    echo \"[FAILED] Ininitial hosting deployment has wrong properties. Maybe the default namespace test didn't reset the values\"\n    echo \"instance_count: $instance_count, weight: $weight\"\n    exit 1\n  fi\n\n  # autoscalling increases instance count to 2 (while keeping the previous weight 2)\n  yq w -i $autoscaling_yaml_filepath \"spec.resourceId[0].endpointName\" $enpoint_name\n  kubectl apply -n $crd_namespace -f $autoscaling_yaml_filepath\n  wait_for_crd_status $crd_namespace HostingDeployment $hostingdeployment_name 90m Updating\n  wait_for_crd_status $crd_namespace HostingDeployment $hostingdeployment_name 90m InService\n\n  # verify instance count is 2\n  instance_count=$(aws sagemaker describe-endpoint --endpoint-name $enpoint_name --region $endpoint_region --query ProductionVariants[0].CurrentInstanceCount)\n  if [ \"${instance_count}\" == \"2\" ]; then\n    echo \"Autoscalling applied to increase instance count to 2\"\n  else\n    echo \"[FAILED] Failed to apply autoscaling policy in retain varient properties test\"\n    echo \"instance_count: $instance_count\"\n    exit 1\n  fi\n\n  # re-apply hosting deployment with instance count 1 and instance weight 1\n  # retainAllVariantProperties \"true\" and excludeRetainedVariantProperties \"DesiredWeight\"\n  #\n  # This should retain the previous instance count of 2 and\n  # shouldn't retain the previous instance weight of 2 and change it to 3\n  yq w -i $hostingdeployment_yaml_filepath \"spec.productionVariants[0].initialVariantWeight\" 3\n  kubectl apply -n $crd_namespace -f $hostingdeployment_yaml_filepath\n  wait_for_crd_status $crd_namespace HostingDeployment $hostingdeployment_name 90m Updating\n  wait_for_crd_status $crd_namespace HostingDeployment $hostingdeployment_name 90m InService\n  # Check if it retained the previous instance count and did not retain previous weight\n  # sleep 5 && wait_for_crd_status \"${crd_namespace}\" HostingDeployment $hostingdeployment_name 40m InService && sleep 5\n  instance_count=$(aws sagemaker describe-endpoint --endpoint-name $enpoint_name --region $endpoint_region --query ProductionVariants[0].CurrentInstanceCount)\n  weight=$(aws sagemaker describe-endpoint --endpoint-name $enpoint_name --region $endpoint_region --query ProductionVariants[0].CurrentWeight | awk '{printf \"%.0f\\n\", $1}')\n  if [ \"${instance_count}\" == \"2\" ] && [ \"${weight}\" == \"3\" ]; then\n    echo \"[PASSED] Successfully tested retainAllVariantProperties and excludeRetainedVariantProperties\"\n  else\n    echo \"[FAILED] Failed to retain the variant properties\"\n    echo \"instance_count: $instance_count, weight: $weight\"\n    exit 1\n  fi\n\n  # changing weight back to 2 for namaspace based tests\n  yq w -i $hostingdeployment_yaml_filepath \"spec.productionVariants[0].initialVariantWeight\" 2\n}\n\n\n# Replaces the names of the endpoint generated in the previous test into the hap spec file and runs the test. \n# Parameter:\n#    $1: Target namespace\n#    $2: K8s Name and endpointName of the hostingdeployment to apply autoscaling \n#    $3: Filename of the hap test to run\n#    $4: Filename of the custom metric hap test to run\nfunction run_hap_test()\n{\n  local target_namespace=\"$1\"\n  local hosting_deployment_1=\"$2\"\n  local file_name=\"$3\"\n  local file_name_custom=\"$4\"\n  local hosting_deployment_2=\"${hosting_deployment_1}-2\"\n  local hosting_deployment_3=\"${hosting_deployment_1}-3\"\n  local hostingdeployment_type=\"hostingdeployment\"\n\n  # Create the 3 Endpoints\n  update_hostingdeployment_input_metadata \"${crd_namespace}\" \"${hosting_deployment_1}\" \"true\"\n  update_hostingdeployment_input_metadata \"${crd_namespace}\" \"${hosting_deployment_2}\" \"true\"\n  update_hostingdeployment_input_metadata \"${crd_namespace}\" \"${hosting_deployment_3}\" \"true\"\n\n  # This can be removed, but will make debugging easier with the same runtime. \n  verify_test \"${crd_namespace}\" HostingDeployment \"${hosting_deployment_1}\" 90m InService\n  verify_test \"${crd_namespace}\" HostingDeployment \"${hosting_deployment_2}\" 90m InService\n  verify_test \"${crd_namespace}\" HostingDeployment \"${hosting_deployment_3}\" 90m InService\n\n  # HAP Test 1: Using the Predefined Metric\n  yq w -i \"$file_name\" \"spec.resourceId[0].endpointName\" \"${hosting_deployment_1}\"\n  yq w -i \"$file_name\" \"spec.resourceId[1].endpointName\" \"${hosting_deployment_2}\"\n  run_test \"$target_namespace\" \"$file_name\"\n\n  # HAP Test 2: Using the Custom Metric\n  yq w -i \"$file_name_custom\" \"spec.resourceId[0].endpointName\" \"${hosting_deployment_3}\"\n  yq w -i \"$file_name_custom\" \"spec.targetTrackingScalingPolicyConfiguration.customizedMetricSpecification.dimensions[0].value\" \"${hosting_deployment_3}\"\n  run_test \"$target_namespace\" \"$file_name_custom\"\n\n  update_hostingdeployment_input_metadata \"${crd_namespace}\" \"${hosting_deployment_1}\" \"false\"\n}\n\n\n# This function verifies that the number of scaling policies applied is as expected \n# Parameter:\n#    $1: The expected number of policies\nfunction verify_hap_test()\n{\n  local expected_number_of_policies=\"$1\"\n  scaling_policies=\"$(aws application-autoscaling describe-scaling-policies --region us-west-2 --service-namespace sagemaker | jq .ScalingPolicies)\"\n  number_of_policies_applied=\"$(echo $scaling_policies | jq length)\"\n\n  if [ \"${number_of_policies_applied}\" == \"${expected_number_of_policies}\" ]; then\n    echo \"[PASSED] All Scaling Policies were successfully applied to the specified number of endpoints\"\n  else\n    echo \"[FAILED] ${number_of_policies_applied} scaling policy/policies were applied. Expected ${expected_number_of_policies}.\"\n    exit 1 \n  fi\n}\n\n# This function verifies that a given debug job has specific status\n# Parameter:\n#    $1: CRD namespace\n#    $1: CRD type\n#    $2: Instance of CRD\n#    $3: Single debug job status\nfunction verify_debug_test\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$2\"\n  local crd_instance=\"$3\"\n  local timeout=\"$4\"\n  local expected_debug_job_status=\"$5\"\n  # First verify that trainingjob has been completed\n  verify_test \"${crd_namespace}\" TrainingJob xgboost-mnist-debugger $timeout Completed\n\n  # TODO extend this for multiple debug job with debug job statuses parameter\n\n  echo \"Waiting for debug job to finish\"\n  timeout \"${timeout}\" bash -c \\\n    'until [ \"$(kubectl get -n \"$0\" \"$1\" \"$2\" -o json | jq -r .status.debugRuleEvaluationStatuses[0].ruleEvaluationStatus)\" == \"$3\" ]; do \\\n      echo \"Debug job has not completed yet\"; \\\n      sleep 1; \\\n    done' \"${crd_namespace}\" \"${crd_type}\" \"${crd_instance}\" \"${expected_debug_job_status}\"\n\n  if [ $? -ne 0 ]; then\n    echo \"[FAILED] Debug job ${crd_type} ${crd_instance} with expected status ${expected_debug_job_status} has timed out\"\n    exit 1\n  fi\n\n  echo \"Debug job has completed\"\n}\n\n# This function verifies that job has started and not failed\n# Parameter:\n#    $1: Namespace of the CRD\n#    $2: Kind of CRD\n#    $3: Instance of CRD\n#    $4: Timeout to complete the test\n#    $5: The status that verifies the job has succeeded.\n# e.g. verify_test default trainingjobs xgboost-mnist\nfunction verify_test()\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$2\"\n  local crd_instance=\"$3\"\n  local timeout=\"$4\"\n  local desired_status=\"$5\"\n\n  # Check if job exist\n  kubectl get -n \"${crd_namespace}\" \"${crd_type}\" \"${crd_instance}\"\n  if [ $? -ne 0 ]; then\n    echo \"[FAILED] ${crd_type} ${crd_namespace}:${crd_instance} job does not exist\"\n    exit 1\n  fi\n\n  # Wait until Training Job has started, there will be two rows, header(STATUS) and entry.\n  # Entry will be none if the job has not started yet. When job starts none will disappear \n  # and real status will be present.\n  echo \"Waiting for ${crd_type} ${crd_namespace}:${crd_instance} job to start\"\n  timeout 1m bash -c \\\n    'until [ \"$(kubectl get -n \"$0\" \"$1\" \"$2\" -o=custom-columns=STATUS:.status | grep -i none | wc -l)\" -eq \"0\" ]; do \\\n      echo \"${crd_type} ${crd_namespace}:${crd_instance} job has not started yet\"; \\\n      sleep 1; \\\n    done' \"${crd_namespace}\" \"${crd_type}\" \"${crd_instance}\"\n\n  # Job has started, check whether it has failed or not\n  kubectl get -n \"${crd_namespace}\" \"${crd_type}\" \"${crd_instance}\" -o=custom-columns=NAME:.status | grep -i fail \n  if [ $? -eq 0 ]; then\n    echo \"[FAILED] ${crd_type} ${crd_namespace}:${crd_instance} job has failed\" \n    exit 1\n  fi\n\n  echo \"Waiting for ${crd_type} ${crd_namespace}:${crd_instance} job to complete\"\n  if ! wait_for_crd_status \"$crd_namespace\" \"$crd_type\" \"$crd_instance\" \"$timeout\" \"$desired_status\"; then\n      echo \"[FAILED] Waiting for status Completed failed\"\n      exit 1\n  fi\n\n  # Check weather job has completed or not\n  echo \"[PASSED] Verified ${crd_type} ${crd_namespace}:${crd_instance} has completed\"\n}\n\n# Build a new FSX file system from an S3 data source to be used by FSX integration tests.\nfunction build_fsx_from_s3()\n{\n  echo \"Building FSX file system from S3 data source\"\n\n  NEW_FS=\"$(aws fsx create-file-system \\\n  --file-system-type LUSTRE \\\n  --lustre-configuration ImportPath=s3://${DATA_BUCKET}/kmeans_mnist_example \\\n  --storage-capacity 1200 \\\n  --subnet-ids subnet-187e9960 \\\n  --tags Key=\"Name\",Value=\"$(date '+%Y-%m-%d-%H-%M-%S')\" \\\n  --region us-west-2)\"\n\n  echo $NEW_FS\n\n  FSX_ID=\"$(echo \"$NEW_FS\" | jq -r \".FileSystem.FileSystemId\")\"\n  FS_AVAILABLE=CREATING\n  until [[ \"${FS_AVAILABLE}\" != \"CREATING\" ]]; do\n    FS_AVAILABLE=\"$(aws fsx --region us-west-2 describe-file-systems --file-system-id \"${FSX_ID}\" | jq -r \".FileSystems[0].Lifecycle\")\"\n    sleep 30\n  done\n  aws fsx --region us-west-2 describe-file-systems --file-system-id ${FSX_ID}\n\n  if [[ \"${FS_AVAILABLE}\" != \"AVAILABLE\" ]]; then\n    exit 1\n  fi\n\n  export FSX_ID=$FSX_ID\n}\n\n# Replaces the names of the endpoint and optionally  creates it\n# Parameter:\n#    $1: Target namespace\n#    $2: K8s Name and endpointName of the hostingdeployment to apply autoscaling \n#    $3: Boolean to indicate if the modified HostingDeployment should be applied\nfunction update_hostingdeployment_input_metadata()\n{ \n  local crd_namespace=\"$1\"\n  local hosting_deployment=\"$2\"\n  local is_create=\"$3\"\n  local file_name_hd=\"testfiles/xgboost-hosting-deployment-with-name.yaml\"\n  \n  yq w -i \"${file_name_hd}\" \"metadata.name\" $hosting_deployment\n  yq w -i \"${file_name_hd}\" \"spec.endpointName\" $hosting_deployment\n  \n  if [[ \"${is_create}\" == \"true\" ]]; then\n    run_test \"${crd_namespace}\" \"${file_name_hd}\"\n  fi\n}\n", "num_lines": 384}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource common.sh\nsource create_tests.sh # TODO: Remove temporary import for \"verify_test\" method\n\n# Verify that k8s and SageMaker resources are deleted when the user uses the delete verb.\n# Parameter:\n#    $1: CRD namespace\nfunction run_delete_canary_tests\n{\n  # Run verbose output for delete tests for simpler debugging\n  set -x\n  local crd_namespace=\"$1\"\n  echo \"Running delete canary tests\"\n  verify_delete \"${crd_namespace}\" TrainingJob testfiles/xgboost-mnist-trainingjob-debugger.yaml\n  verify_delete \"${crd_namespace}\" ProcessingJob testfiles/kmeans-mnist-processingjob.yaml\n  verify_delete \"${crd_namespace}\" HyperparameterTuningJob testfiles/xgboost-mnist-hpo.yaml\n\n  # Create model before running batch delete test\n  run_test \"${crd_namespace}\" testfiles/xgboost-model.yaml\n  verify_test \"${crd_namespace}\" Model xgboost-model 5m Created\n  yq w -i testfiles/xgboost-mnist-batchtransform.yaml \"spec.modelName\" \"$(get_sagemaker_model_from_k8s_model \"${crd_namespace}\" xgboost-model)\"\n\n  verify_delete \"${crd_namespace}\" BatchTransformJob testfiles/xgboost-mnist-batchtransform.yaml\n  set +x\n}\n\n# Parameter:\n#    $1: CRD namespace\nfunction run_delete_integration_tests\n{\n  echo \"Running delete integration tests\"\n  local crd_namespace=\"$1\"\n  run_delete_canary_tests \"${crd_namespace}\"\n}\n\n# Applies a k8s resource, waits for it to start and then immediately deletes\n# and ensure the state of the resource in k8s is stopping.\n# Parameter:\n#    $1: CRD namespace\n#    $2: CRD type\n#    $3: Filename of test\n#    $4: (Optional) Timeout\n# e.g. verify_delete default TrainingJob xgboost-mnist.yaml 60s\nfunction verify_delete()\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$(echo \"$2\" | awk '{print tolower($0)}')\"\n  local file_name=\"$3\"\n  local timeout=${4:-\"10m\"}\n\n  # Apply file and get name\n  local k8s_resource_name=\"$(kubectl apply -n \"${crd_namespace}\" -f \"${file_name}\" -o json | jq -r \".metadata.name\")\"\n\n  # Wait until job has started.\n  if ! wait_for_crd_status \"$crd_namespace\" \"$crd_type\" \"$k8s_resource_name\" \"$timeout\" \"InProgress\"; then\n      echo \"[FAILED] Waiting for ${crd_type} ${crd_namespace}:${k8s_resource_name} job status InProgress failed\"\n      exit 1\n  fi\n\n  local jobNamePath \n  case $crd_type in\n    trainingjob)\n      jobNamePath=\".status.sageMakerTrainingJobName\"\n      ;;\n    processingjob)\n      jobNamePath=\".status.sageMakerProcessingJobName\"\n      ;;\n    hyperparametertuningjob)\n      jobNamePath=\".status.sageMakerHyperParameterTuningJobName\"\n      ;;\n    batchtransformjob)\n      jobNamePath=\".status.sageMakerTransformJobName\"\n      ;;\n    hostingdeployment)\n      jobNamePath=\".status.endpointName\"\n      ;;\n    *)\n      echo \"[FAILED] Delete did not recognise CRD type ${crd_type}\"\n      exit 1\n      ;;\n  esac\n\n  local job_name=\"$(kubectl get -n \"${crd_namespace}\" \"${crd_type}\" \"${k8s_resource_name}\" -o json | jq -r \"${jobNamePath}\")\"\n\n  # Actually delete the resource\n  kubectl delete -n \"${crd_namespace}\" -f \"${file_name}\" &\n\n  # Wait for the status to be Stopping. If it does not happen, then check if the job still exists. If it doesn't, then the delete occurred. If it still exists, then the delete failed.\n  if ! wait_for_crd_status \"$crd_namespace\" \"${crd_type}\" \"${k8s_resource_name}\" \"${timeout}\" \"Stopping\" &&\n  kubectl get -n \"${crd_namespace}\" \"${crd_type}\" \"${k8s_resource_name}\"; then\n      echo \"[FAILED] Waiting for ${crd_type} ${crd_namespace}:${k8s_resource_name} job status Stopping failed\"\n      exit 1\n  fi\n  # Check that it has been stopped in SageMaker\n  verify_sm_resource_stopping_else_fail \"${crd_type}\" \"${job_name}\"\n\n  echo \"[PASSED] Verified ${crd_type} ${crd_namespace}:${k8s_resource_name} deleted from k8s successfully\"\n}\n\n# Queries AWS SageMaker to ensure that the job created by a k8s resource has\n# been marked as stopped or stopping.\n# Parameter:\n#    $1: CRD type\n#    $2: SageMaker job name\nfunction verify_sm_resource_stopping_else_fail()\n{\n  local crd_type=\"$(echo \"$1\" | awk '{print tolower($0)}')\"\n  local job_name=\"$2\"\n\n  local jobStatusPath sageMakerResourceType \n  case $crd_type in\n    trainingjob)\n      jobStatusPath=\".TrainingJobStatus\"\n      sageMakerResourceType=\"training-job\"\n      ;;\n\n    processingjob)\n      jobStatusPath=\".ProcessingJobStatus\"\n      sageMakerResourceType=\"processing-job\"\n      ;;\n\n    hyperparametertuningjob)\n      jobStatusPath=\".HyperParameterTuningJobStatus\"\n      sageMakerResourceType=\"hyper-parameter-tuning-job\"\n      ;;\n\n    batchtransformjob)\n      jobStatusPath=\".TransformJobStatus\"\n      sageMakerResourceType=\"transform-job\"\n      ;;\n\n    hostingdeployment)\n      jobStatusPath=\".EndpointStatus\"\n      sageMakerResourceType=\"endpoint\"\n      ;;\n\n    *)\n      echo \"[FAILED] Delete did not recognise CRD type ${crd_type}\"\n      exit 1\n      ;;\n  esac\n  \n  job_status=\"$(aws sagemaker \"describe-${sageMakerResourceType}\" \"--${sageMakerResourceType}-name\" \"${job_name}\" --region us-west-2 | jq -r \"${jobStatusPath}\")\"\n  # Job can go from Stopping to completed State if job is completing already like uploading model\n  if [ \"${job_status}\" != \"Stopping\" ] && [ \"${job_status}\" != \"Stopped\" ] && [\"${job_status}\" != \"Completed\"]; then\n    echo \"[FAILED] AWS SageMaker resource \\\"${job_name}\\\" did not stop (status \\\"${job_status}\\\")\" \n    exit 1\n  else\n    echo \"[PASSED] AWS SageMaker resource \\\"${job_name}\\\" deleted from SageMaker\" \n  fi\n}\n", "num_lines": 153}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource common.sh\nsource inject_tests.sh\n\n# Applies each of the resources needed for the canary tests.\nfunction run_feature_canary_tests\n{\n  echo \"Running feature canary tests\"\n  inject_all_variables\n}\n\n# Applies each of the resources needed for the integration tests.\n# Parameter:\n#    $1: CRD namespace\nfunction run_feature_integration_tests\n{\n  echo \"Running feature integration tests\"\n  local crd_namespace=\"$1\"\n  run_feature_canary_tests\n\n  run_test \"${crd_namespace}\" testfiles/failing-xgboost-mnist-hpo.yaml\n  run_test \"${crd_namespace}\" testfiles/failing-xgboost-mnist-trainingjob.yaml\n}\n\n# Creates a training job in the specified namespace\n# For this test, the job is created in a namespace that does not have the operator. \n# Parameter:\n#    $1: CRD namespace\nfunction run_namespace_deployment_tests\n{\n  echo \"Running feature namespaced test\"\n  local crd_namespace=\"$1\"\n  # Create the noop-namespace if it does not exist\n  kubectl create namespace \"${crd_namespace}\"\n  run_feature_canary_tests\n  run_test \"${crd_namespace}\" testfiles/xgboost-mnist-trainingjob-namespaced.yaml  \n}\n\n# Verifies that the job created in an incorrect namespace does not gain a status or sagemaker name.\n# Parameter:\n#    $1: CRD namespace\nfunction verify_job_fails_outside_operator_namespace\n{\n  echo \"Verifying namespace deployment test\"\n  local crd_namespace=\"$1\"\n  sleep 5\n\n  if verify_job_has_no_status \"$crd_namespace\" TrainingJob \"xgboost-mnist-namespaced\"; then\n    echo \"[FAILED] TrainingJob deployed to $crd_namespace namespace was created and has a job status\" \n    exit 1\n  fi\n  if verify_trainingjob_has_no_sagemaker_name \"$crd_namespace\" \"xgboost-mnist-namespaced\"; then\n    echo \"[FAILED] TrainingJob deployed to $crd_namespace namespace was created and has a sagemaker job name\" \n    exit 1\n  fi\n\n}\n\n# Verify that each canary feature test has completed successfully.\nfunction verify_feature_canary_tests\n{\n  echo \"Verifying feature canary tests\"\n}\n\n# Verifies that each integration feature test has completed successfully.\n# Parameter:\n#    $1: CRD namespace\nfunction verify_feature_integration_tests\n{\n  echo \"Verifying feature integration tests\"\n  local crd_namespace=\"$1\"\n  verify_feature_canary_tests\n\n  if ! wait_for_crd_status \"$crd_namespace\" TrainingJob failing-xgboost-mnist 5m Failed; then\n    echo \"[FAILED] Failing training job never reached status Failed\"\n    exit 1\n  fi\n  if ! verify_resource_has_additional \"$crd_namespace\" TrainingJob failing-xgboost-mnist; then\n    echo \"[FAILED] Failing training job does not have any additional status set\" \n    exit 1\n  fi\n  echo \"[SUCCESS] TrainingJob with Failed status has additional set\"\n\n  if ! wait_for_crd_status \"$crd_namespace\" HyperParameterTuningJob failing-xgboost-mnist-hpo 10m Failed; then\n    echo \"[FAILED] Failing hyperparameter tuning job never reached status Failed\"\n    exit 1\n  fi\n  if ! verify_resource_has_additional \"$crd_namespace\" HyperParameterTuningJob failing-xgboost-mnist-hpo; then\n    echo \"[FAILED] Failing hyperparameter tuning job does not have any additional status set\"\n    exit 1\n  fi\n  if ! verify_failed_trainingjobs_from_hpo_have_additional \"$crd_namespace\" failing-xgboost-mnist-hpo; then\n    echo \"[FAILED] Not all failed training jobs in failing HPO job contained the additional in their statuses\"\n    exit 1\n  fi\n  echo \"[SUCCESS] HyperParameterTuningJob with Failed status has its additional status set and set for all TrainingJobs\"\n}\n\n# This function verifies that a given training job has a failure reason in the \n# additional part of the status.\n# Parameter:\n#    $1: CRD namespace\n#    $2: CRD type\n#    $3: Instance of CRD\nfunction verify_resource_has_additional\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$2\"\n  local crd_instance=\"$3\"\n  local additional=\"$(kubectl get -n \"$crd_namespace\" \"$crd_type\" \"$crd_instance\" -o json | jq -r '.status.additional')\"\n\n  if [ -z \"$additional\" ]; then\n    return 1\n  fi\n}\n\n# This function verifies that each Failed trainingjob for a given HPO job have\n# the additional field in their status set.\n# Parameter:\n#    $1: Job namespace\n#    $2: Instance of HyperParameterTuningJob\nfunction verify_failed_trainingjobs_from_hpo_have_additional\n{\n  local crd_namespace=\"$1\"\n  local crd_instance=\"$2\"\n\n  local sagemaker_hpo_job_name=\"$(kubectl get -n \"$crd_namespace\" hyperparametertuningjob \"$crd_instance\" -o json | jq -r '.status.sageMakerHyperParameterTuningJobName')\"\n\n  # Loop over every failed training job and get the k8s resource name\n  for training_job in $(kubectl get -n \"$crd_namespace\" trainingjob | grep Failed | grep \"$sagemaker_hpo_job_name\" | awk '{print $1}'); do\n    if ! verify_resource_has_additional \"$crd_namespace\" TrainingJob \"$training_job\"; then\n      return 1\n    fi\n  done\n}\n\n# This function verifies that a given job does not have a status.\n# Returns 1 if job creation fails.\n# Parameter:\n#    $1: CRD namespace\n#    $2: CRD type\n#    $3: Instance of CRD\nfunction verify_job_has_no_status\n{\n  local crd_namespace=\"$1\"\n  local crd_type=\"$2\"\n  local crd_instance=\"$3\"\n  local sagemaker_job_status=\"$(kubectl get -n \"$crd_namespace\" \"$crd_type\" \"$crd_instance\" -o json | jq -r '.status')\"\n\n  if [ \"$sagemaker_job_status\" = null ]; then\n    echo \"[SUCCESS] $crd_type deployed to $crd_namespace namespace does not have a status\"\n    return 1\n  fi\n}\n\n# This function verifies that a given training job does not have a sagemaker job name. \n# Returns 1 if job creation fails.\n# Parameter:\n#    $1: CRD namespace\n#    $2: CRD type\n#    $3: Instance of CRD\nfunction verify_trainingjob_has_no_sagemaker_name\n{\n  local crd_namespace=\"$1\"\n  local crd_instance=\"$2\"\n  local crd_type=\"TrainingJob\"\n  local sagemaker_training_job_name=\"$(kubectl get -n \"$crd_namespace\" \"$crd_type\" \"$crd_instance\" -o json | jq -r '.status.sageMakerTrainingJobName')\"\n\n  if [ \"$sagemaker_training_job_name\" = null ]; then\n    echo \"[SUCCESS] $crd_type deployed to $crd_namespace namespace does not have a sagemaker job name\"\n    return 1\n  fi\n}", "num_lines": 174}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Helper script to generate an IAM Role needed to install operator using role-based authentication.\n# https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_operators_for_kubernetes.html#create-an-iam-role\n#\n# Run as:\n# $ ./generate_iam_role.sh ${cluster_arn/cluster_name} ${operator_namespace} ${role_name} ${cluster_region}\n#\n\nCLUSTER_ARN=\"${1}\"\nOPERATOR_NAMESPACE=\"${2}\"\nROLE_NAME=\"${3}\"\nCLUSTER_REGION=\"${4:-us-east-1}\"\naws_account=$(aws sts get-caller-identity --query Account --output text)\ntrustfile=\"trust.json\"\n\n# if using an existing cluster, use the cluster arn to get the region and cluster name\n# example, cluster_arn=arn:aws:eks:us-east-1:12345678910:cluster/test\ncluster_name=$(echo ${CLUSTER_ARN} | cut -d'/' -f2)\n\n# A function to get the OIDC_ID associated with an EKS cluster\nfunction get_oidc_id {\n    # TODO: Ideally this should be based on version compatibility instead of command failure\n    eksctl utils associate-iam-oidc-provider --cluster ${cluster_name} --region ${CLUSTER_REGION} --approve\n    if [[ $? -ge 1 ]]; then\n        eksctl utils associate-iam-oidc-provider --name ${cluster_name} --region ${CLUSTER_REGION} --approve\n    fi\n    \n    local oidc=$(aws eks describe-cluster --name ${cluster_name} --region ${CLUSTER_REGION} --query cluster.identity.oidc.issuer --output text)\n    oidc_id=$(echo ${oidc} | rev | cut -d'/' -f1 | rev)\n}\n\n# A function that generates an IAM role for the given account, cluster, namespace, region\n# Parameter:\n#    $1: Name of the trust file to generate.\nfunction create_namespaced_iam_role {\n    local trustfile=\"${1}\"\n    # Check if role already exists\n    aws iam get-role --role-name ${ROLE_NAME}\n    if [[ $? -eq 0 ]]; then\n        echo \"A role for this cluster and namespace already exists in this account, assuming sagemaker access and proceeding.\"\n    else\n        echo \"IAM Role does not exist, creating a new Role for the cluster\"\n        aws iam create-role --role-name ${ROLE_NAME} --assume-role-policy-document file://${trustfile} --output=text\n        aws iam attach-role-policy --role-name ${ROLE_NAME}  --policy-arn arn:aws:iam::aws:policy/AmazonSageMakerFullAccess\n    fi\n}\n\n# Remove the generated trust file\n# Parameter:\n#    $1: Name of the trust file to delete.\nfunction delete_generated_file {\n    rm \"${1}\" \n}\n\necho \"Get the OIDC ID for the cluster\"\nget_oidc_id\necho \"Delete the trust json file if it already exists\"\ndelete_generated_file \"${trustfile}\"\necho \"Generate a trust json\"\n./generate_trust_policy.sh ${CLUSTER_REGION} ${aws_account} ${oidc_id} ${OPERATOR_NAMESPACE} > \"${trustfile}\"\necho \"Create the IAM Role using these values\"\ncreate_namespaced_iam_role \"${trustfile}\"\necho \"Cleanup for the next run!\"\ndelete_generated_file \"${trustfile}\"\n\n", "num_lines": 67}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Helper script to generate trust policy needed to install operator using role-based authentication.\n# https://sagemaker.readthedocs.io/en/stable/amazon_sagemaker_operators_for_kubernetes.html#create-an-iam-role\n#\n# Run as:\n# $ ./generate_trust_policy ${EKS_CLUSTER_REGION} ${AWS_ACCOUNT_ID} ${OIDC_ID} [optional: ${OPERATOR_NAMESPACE}] > trust.json\n#\n# For example:\n# $ ./generate_trust_policy us-west-2 123456789012 D48675832CA65BD10A532F597OIDCID > trust.json\n# This will create a file `trust.json` containing a role policy that enables the operator in an EKS cluster to assume AWS roles.\n#\n# The OPERATOR_NAMESPACE parameter is for when you want to run the operator in a custom namespace other than \"sagemaker-k8s-operator-system\".\n\ncluster_region=\"$1\"\naccount_number=\"$2\"\noidc_id=\"$3\"\noperator_namespace=\"${4:-sagemaker-k8s-operator-system}\"\n\nprintf '{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Federated\": \"arn:aws:iam::'\"${account_number}\"':oidc-provider/oidc.eks.'\"${cluster_region}\"'.amazonaws.com/id/'\"${oidc_id}\"'\"\n      },\n      \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n      \"Condition\": {\n        \"StringEquals\": {\n          \"oidc.eks.'\"${cluster_region}\"'.amazonaws.com/id/'\"${oidc_id}\"':aud\": \"sts.amazonaws.com\",\n          \"oidc.eks.'\"${cluster_region}\"'.amazonaws.com/id/'\"${oidc_id}\"':sub\": \"system:serviceaccount:'\"${operator_namespace}\"':sagemaker-k8s-operator-default\"\n        }\n      }\n    }\n  ]\n}\n'", "num_lines": 38}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Inject environment variables into the job YAMLs\nfunction inject_variables()\n{\n  variables=(\"ROLE_ARN\" \"DATA_BUCKET\" \"FSX_ID\")\n\n  local file_name=\"$1\"\n  for i in \"${variables[@]}\"\n  do\n    local curr_var=${!i}\n    sed -i \"s|{$i}|${curr_var}|g\" \"${file_name}\"\n  done\n}\n\n# Injects necessary environment variables into resource yaml specs. This allows\n# for generic integration tests to be created, substituting values that are \n# specific to the account they are run within.\nfunction inject_all_variables\n{\n  inject_variables testfiles/xgboost-mnist-trainingjob.yaml\n  inject_variables testfiles/kmeans-mnist-processingjob.yaml\n  inject_variables testfiles/spot-xgboost-mnist-trainingjob.yaml\n  inject_variables testfiles/xgboost-mnist-custom-endpoint.yaml\n  # inject_variables testfiles/efs-xgboost-mnist-trainingjob.yaml\n  # inject_variables testfiles/fsx-kmeans-mnist-trainingjob.yaml\n  inject_variables testfiles/xgboost-mnist-hpo.yaml\n  inject_variables testfiles/spot-xgboost-mnist-hpo.yaml\n  inject_variables testfiles/xgboost-mnist-hpo-custom-endpoint.yaml\n  inject_variables testfiles/xgboost-model.yaml\n  inject_variables testfiles/xgboost-mnist-batchtransform.yaml\n  inject_variables testfiles/xgboost-hosting-deployment.yaml\n  inject_variables testfiles/xgboost-hosting-deployment-with-name.yaml\n  inject_variables testfiles/xgboost-hosting-deployment-multi-container.yaml\n  inject_variables testfiles/failing-xgboost-mnist-trainingjob.yaml\n  inject_variables testfiles/failing-xgboost-mnist-hpo.yaml\n  inject_variables testfiles/xgboost-mnist-trainingjob-debugger.yaml\n  inject_variables testfiles/xgboost-mnist-trainingjob-namespaced.yaml\n  inject_variables testfiles/xgboost-mnist-trainingjob-china.yaml\n  inject_variables testfiles/xgboost-mnist-hpo-china.yaml\n  inject_variables testfiles/xgboost-model-china.yaml\n  inject_variables testfiles/xgboost-mnist-batchtransform-china.yaml\n  inject_variables testfiles/hd-retain-varient-properties.yaml\n}\n", "num_lines": 45}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource create_tests.sh\nsource feature_tests.sh\nsource delete_tests.sh\nsource inject_tests.sh\nsource smlogs_tests.sh\n\nrun_canary_tests \"default\"\nrun_feature_canary_tests \"default\"\nverify_canary_tests \"default\"\nrun_update_canary_tests \"default\"\nverify_update_canary_tests \"default\"\nverify_feature_canary_tests \"default\"\nrun_smlogs_canary_tests \"default\"\ndelete_all_resources \"default\" # Delete all existing resources to re-use metadata names\nrun_delete_canary_tests \"default\" \n", "num_lines": 18}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource create_tests.sh\nsource feature_tests.sh\nsource delete_tests.sh\nsource inject_tests.sh\nsource smlogs_tests.sh\n\nrun_canary_tests_china \"default\"\nverify_canary_tests_china \"default\"\nrun_update_canary_tests \"default\"\nverify_update_canary_tests \"default\"\ndelete_all_resources \"default\" # Delete all existing resources to re-use metadata names\n", "num_lines": 14}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource create_tests.sh\nsource delete_tests.sh\nsource inject_tests.sh\nsource feature_tests.sh\n\ncrd_namespace=\"${1}\"\nnoop_namespace=\"noop-namespace\"\n\nrun_canary_tests \"${crd_namespace}\"\nverify_canary_tests \"${crd_namespace}\"\nrun_namespace_deployment_tests \"${noop_namespace}\" # Deploy job to namespace without operator.\nverify_job_fails_outside_operator_namespace \"${noop_namespace}\"\ndelete_all_resources \"${crd_namespace}\" # Delete all existing resources to re-use metadata names\ndelete_all_resources \"${noop_namespace}\"\nrun_delete_canary_tests \"${crd_namespace}\"", "num_lines": 17}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource create_tests.sh\nsource update_tests.sh\nsource feature_tests.sh\nsource delete_tests.sh\nsource inject_tests.sh\nsource smlogs_tests.sh\n\ncrd_namespace=${1}\n\nrun_integration_tests ${crd_namespace}\nrun_feature_integration_tests ${crd_namespace}\nverify_integration_tests ${crd_namespace}\n# run_update_integration_tests ${crd_namespace}\n# verify_update_integration_tests ${crd_namespace}\nverify_feature_integration_tests ${crd_namespace}\nrun_smlogs_integration_tests ${crd_namespace}\ndelete_all_resources ${crd_namespace} # Delete all existing resources to re-use metadata names\nrun_delete_integration_tests ${crd_namespace}", "num_lines": 20}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Verbose trace of commands, helpful since test iteration takes a long time.\nset -x \n\n# A function to delete cluster, if cluster was not launched this will fail, so test will fail ultimately too\nfunction cleanup {\n    # We want to run every command in this function, even if some fail.\n    set +e\n\n    # Managable to print logs for ephemeral cluster\n    get_manager_logs\n\n    delete_all_resources \"default\"\n\n    if [ -z \"${USE_EXISTING_CLUSTER}\" ]\n    then\n        # Delete the role associated with the cluster thats being deleted\n        delete_generated_role \"${role_name}\"\n        # Tear down the cluster if we set it up.\n        echo \"USE_EXISTING_CLUSTER is false, tearing down cluster we created.\"\n        eksctl delete cluster --name \"${cluster_name}\" --region \"${CLUSTER_REGION}\"\n    fi\n}\n\n# Set the trap to clean up resources\n# In case of error or normal exit delete the cluster\ntrap cleanup EXIT\n\n# If any command fails, exit the script with an error code.\nset -e\n\nsource ./common.sh\n\n# TODOs\n# 1. Add validation for each steps and abort the test if steps fails\n# Build environment `Docker image` has all prerequisite setup and credentials are being passed using AWS system manager\n\nCLUSTER_REGION=${CLUSTER_REGION:-us-east-1}\nCLUSTER_VERSION=1.21\n\n# Define the list of optional subnets for the EKS test cluster\nCLUSTER_PUBLIC_SUBNETS=${CLUSTER_PUBLIC_SUBNETS:-}\nCLUSTER_PRIVATE_SUBNETS=${CLUSTER_PRIVATE_SUBNETS:-}\n\n# Output the commit SHA for logging sake\necho \"Launching canary test for ${COMMIT_SHA}\"\n\n# Launch EKS cluster if we need to and define cluster_name,CLUSTER_REGION.\necho \"Launching the cluster\"\n\ncluster_name=\"sagemaker-k8s-canary-\"$(date '+%Y-%m-%d-%H-%M-%S')\"\"\n\nif [ -z \"${USE_EXISTING_CLUSTER}\" ]\nthen \n   eksctl_args=( --nodes 1 --node-type=c5.xlarge --region \"${CLUSTER_REGION}\" --version \"${CLUSTER_VERSION}\" )\n   [ \"${CLUSTER_PUBLIC_SUBNETS}\" != \"\" ] && eksctl_args+=( --vpc-public-subnets=\"${CLUSTER_PUBLIC_SUBNETS}\" )\n   [ \"${CLUSTER_PRIVATE_SUBNETS}\" != \"\" ] && eksctl_args+=( --vpc-private-subnets=\"${CLUSTER_PRIVATE_SUBNETS}\" )\n   \n   eksctl create cluster \"${cluster_name}\" \"${eksctl_args[@]}\" --dry-run > generated-cluster.yaml\n   yq w -i generated-cluster.yaml managedNodeGroups[0].disableIMDSv1 true\n\n   eksctl create cluster -f generated-cluster.yaml --auto-kubeconfig --timeout=40m\n\n   echo \"Setting kubeconfig\"\n   export KUBECONFIG=\"/root/.kube/eksctl/clusters/${cluster_name}\"\nelse\n   cluster_name=\"non-ephemeral-cluster\"\n   aws eks update-kubeconfig --name \"${cluster_name}\" --region \"${CLUSTER_REGION}\"\nfi\n\n\n# Download the CRD\ntar -xf sagemaker-k8s-operator.tar.gz\n\n# jump to the root dir of operator\npushd sagemaker-k8s-operator\n\n    # Setup the PATH for smlogs\n    mv smlogs-plugin/linux.amd64/kubectl-smlogs /usr/bin/kubectl-smlogs\npopd\n\ngenerate_iam_role_name \"${default_operator_namespace}\"\n./generate_iam_role.sh \"${cluster_name}\" \"${default_operator_namespace}\" \"${role_name}\" \"${CLUSTER_REGION}\"\n\n#smlogs depends on clusterscope\noperator_clusterscope_deploy \"${role_name}\"\n\n# Run the integration test file\n./run_all_sample_canary_tests.sh\n\n# Send results back to results bucket\nFILE_NAME=`TZ=UTC date +%Y-%m-%d-%H-%M-%S`\ntouch /tmp/$FILE_NAME\naws s3 cp /tmp/$FILE_NAME s3://${RESULT_BUCKET}/${CLUSTER_REGION}/$FILE_NAME\n", "num_lines": 96}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Env variables that need to be set before running this script\n# ROLE_ARN : SageMaker executor role arn\n# DATA_BUCKET : S3 bucket name where input data is stored\n\nif [[ -z \"${ROLE_ARN}\" ]]; then\n  echo \"ROLE_ARN environment variable not found\"\n  exit 1\nfi\nif [[ -z \"${DATA_BUCKET}\" ]]; then\n  echo \"DATA_BUCKET environment variable not found\"\n  exit 1\nfi\n\n# Optional Env variables\n\nif [ \"${EKS_PRIVATE_SUBNET_1}\" -a \"${EKS_PRIVATE_SUBNET_2}\" -a \"${EKS_PUBLIC_SUBNET_1}\" -a \"${EKS_PUBLIC_SUBNET_2}\" ];then\n  echo \"Will use existing subnets to create the EKS cluster\"\n  USE_EXISTING_SUBNET=True\nelse\n  echo \"Existing subnets not provided. Will Create new VPC during EKS cluster creation\"\nfi\n\n\n# local variables\nDEPLOYMENT_NAME=\"ephemeral-operator-canary-\"$(date '+%Y-%m-%d-%H-%M-%S')\"\"\nCLUSTER_NAME=${DEPLOYMENT_NAME}-cluster\nCLUSTER_REGION=${CLUSTER_REGION:-cn-northwest-1}\nOIDC_ROLE_NAME=pod-role-$DEPLOYMENT_NAME\nAWS_ACC_NUM=$(aws sts get-caller-identity --region $CLUSTER_REGION   --query Account --output text)\nCLUSTER_VERSION=1.21\n\nfunction download_installer_china(){\n  if [ -f ./installer_china.yaml ]; then\n    # codebuild spec copies this file from release/rolebased/china/installer_china.yaml to here\n    echo \"installer_china.yaml found in current path\"\n    return 0\n  fi\n\n  echo \"installer_china.yaml not found in current path\"\n  echo \"Trying to download it from github\"\n\n  n=0\n  until [ \"$n\" -ge 3 ]\n  do\n    wget --retry-connrefused --waitretry=30 --read-timeout=20 --timeout=15 -t 3 \\\n      -O installer_china.yaml https://raw.githubusercontent.com/aws/amazon-sagemaker-operator-for-k8s/master/release/rolebased/china/installer_china.yaml \\\n      && break\n    n=$((n+1))\n    if [[ \"$n\" -ge 3 ]]; then\n      echo \"Failed to download installer_china.yaml\"\n      exit 1\n    fi\n    echo \"Sleeping for\" $((60*2*n)) s\n    sleep $((60*2*n))\n  done\n}\n\nfunction create_eks_cluster() {\n  eksctl_args=( --managed --nodes 1 --node-type=c5.xlarge --region \"$CLUSTER_REGION\" --version \"${CLUSTER_VERSION}\" )\n  [ ! -z \"${USE_EXISTING_SUBNET}\" ] && eksctl_args+=( --vpc-public-subnets=\"${EKS_PUBLIC_SUBNET_1},${EKS_PUBLIC_SUBNET_2}\" )\n  [ ! -z \"${USE_EXISTING_SUBNET}\" ] && eksctl_args+=( --vpc-private-subnets=\"${EKS_PRIVATE_SUBNET_1},${EKS_PRIVATE_SUBNET_2}\" )\n  \n  eksctl create cluster \"${CLUSTER_NAME}\" \"${eksctl_args[@]}\" --dry-run > generated-cluster.yaml\n  yq w -i generated-cluster.yaml managedNodeGroups[0].disableIMDSv1 true\n\n  eksctl create cluster -f generated-cluster.yaml --auto-kubeconfig --timeout=40m\n}\n\nfunction install_k8s_operators() {\n  echo \"Installing SageMaker operators\"\n  aws --region $CLUSTER_REGION eks update-kubeconfig --name $CLUSTER_NAME\n  eksctl utils associate-iam-oidc-provider --cluster $CLUSTER_NAME --region $CLUSTER_REGION --approve\n\n  OIDC_URL=$(aws eks describe-cluster --region $CLUSTER_REGION --name $CLUSTER_NAME --query \"cluster.identity.oidc.issuer\" --output text | cut -c9-)\n\n  printf '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n      {\n        \"Effect\": \"Allow\",\n        \"Principal\": {\n          \"Federated\": \"arn:aws-cn:iam::'$AWS_ACC_NUM':oidc-provider/'$OIDC_URL'\"\n        },\n        \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n        \"Condition\": {\n          \"StringEquals\": {\n            \"'$OIDC_URL':aud\": \"sts.amazonaws.com\",\n            \"'$OIDC_URL':sub\": \"system:serviceaccount:sagemaker-k8s-operator-system:sagemaker-k8s-operator-default\"\n          }\n        }\n      }\n    ]\n  }\n  ' > ./trust.json\n\n  aws --region $CLUSTER_REGION iam create-role --role-name $OIDC_ROLE_NAME --assume-role-policy-document file://trust.json\n  aws --region $CLUSTER_REGION iam attach-role-policy --role-name $OIDC_ROLE_NAME --policy-arn arn:aws-cn:iam::aws:policy/AmazonSageMakerFullAccess\n  OIDC_ROLE_ARN=$(aws --region $CLUSTER_REGION iam get-role --role-name $OIDC_ROLE_NAME --output text --query 'Role.Arn')\n\n  download_installer_china\n\n  FIND_STR=$(yq r -d'*' installer_china.yaml 'metadata.annotations.\"eks.amazonaws.com/role-arn\"')\n  sed -i \"s#$FIND_STR#$OIDC_ROLE_ARN#g\" installer_china.yaml\n  kubectl apply -f installer_china.yaml\n\n  echo \"Waiting for controller pod to be Ready\"\n  # Wait to increase chance that pod is ready\n  # TODO: Should upgrade kubectl to version that supports `kubectl wait pods --all`\n  sleep 60\n\n}\n\nfunction delete_generated_oidc_role {\n    echo \"Deleting generated OIDC role\"\n    aws iam detach-role-policy --region $CLUSTER_REGION  --role-name ${OIDC_ROLE_NAME} --policy-arn arn:aws-cn:iam::aws:policy/AmazonSageMakerFullAccess\n    aws iam delete-role --region $CLUSTER_REGION --role-name ${OIDC_ROLE_NAME}\n}\n\nfunction delete_generated_cluster {\n  echo \"Deleting cluster\"\n  eksctl delete cluster --region $CLUSTER_REGION $CLUSTER_NAME\n}\n\nfunction cleanup() {\n  set +e\n\n  delete_generated_oidc_role\n  delete_generated_cluster\n}\n\ntrap cleanup EXIT\n\ncreate_eks_cluster\ninstall_k8s_operators\n\nset -e\n./run_all_sample_canary_tests_china.sh\n", "num_lines": 140}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# TODOs\n# 1. Add validation for each steps and abort the test if steps fails\n# Build environment `Docker image` has all prerequisite setup and credentials are being passed using AWS system manager\n# crd_namespace is currently hardcoded here for cleanup. Should be an env variable set in the pipeline and .env file\n\nsource tests/codebuild/common.sh\ncrd_namespace=${NAMESPACE_OVERRIDE:-\"test-namespace\"}\n\n# Verbose trace of commands, helpful since test iteration takes a long time.\nset -x \n\n# A function to cleanup resources before exit. If cluster was not launched by the script, only the CRDs, jobs and operator will be deleted.\nfunction cleanup {\n    # We want to run every command in this function, even if some fail.\n    set +e\n    echo \"[SECTION] Running final cluster cleanup, some commands may fail if resources do not exist.\"\n\n    get_manager_logs \"${crd_namespace}\"\n    delete_all_resources \"${crd_namespace}\"\n    cleanup_default_namespace\n    \n    # Tear down the cluster if we set it up.\n    if [ \"${need_setup_cluster}\" == \"true\" ]; then\n        echo \"need_setup_cluster is true, tearing down cluster we created.\"\n        eksctl delete cluster --name \"${cluster_name}\" --region \"${cluster_region}\"\n        # Delete the role associated with the cluster thats being deleted\n        delete_generated_role \"${role_name}\"\n        delete_generated_role \"${default_role_name}\"\n    else\n        echo \"need_setup_cluster is not true, will remove operator without deleting cluster\"\n        kustomize build \"$path_to_installer/config/default\" | kubectl delete -f -\n        # Delete the namespaced operator. TODO: This can be cleaner if parameterized\n        kustomize build \"$path_to_installer/config/crd\" | kubectl delete -f -\n        rolebased_operator_install_or_delete ${crd_namespace} \"config/installers/rolebasedcreds/namespaced\" \"${role_name}\" \"delete\"  \n    fi\n\n    if [ \"${existing_fsx}\" == \"false\" ] && [ \"$FSX_ID\" != \"\" ]; then\n        aws fsx --region us-west-2 delete-file-system --file-system-id \"$FSX_ID\"\n    fi\n}\n\n# Set the trap to clean up resources\n# In case of error or normal exit delete the cluster\ntrap cleanup EXIT\n\n# When we run integration tests locally, the default kubeconfig file will be present.\n# If we are not running locally, we will set up an EKS cluster for testing.\nif [ ! -f ~/.kube/config ]; then\n    echo \"No kubeconfig found, going to set up own cluster.\"\n    need_setup_cluster=\"true\"\nelse\n    echo \"kubeconfig present, no need to set up cluster.\"\n    need_setup_cluster=\"false\"\nfi\nreadonly need_setup_cluster\n\nif [ \"${FSX_ID}\" != \"\" ]; then\n    existing_fsx=\"true\"\nelse\n    existing_fsx=\"false\"\nfi\nreadonly existing_fsx\n\n# If any command fails, exit the script with an error code.\nset -e\n\n# Launch EKS cluster if we need to and define cluster_name,cluster_region.\necho \"[SECTION] Lauch EKS Cluster if needed\"\nif [ \"${need_setup_cluster}\" == \"true\" ]; then\n    echo \"Launching the cluster\"\n    readonly cluster_name=\"sagemaker-k8s-pipeline-\"$(date '+%Y-%m-%d-%H-%M-%S')\"\"\n    readonly cluster_region=\"us-east-1\"\n\n    # By default eksctl picks random AZ, which time to time leads to capacity issue.\n    eksctl create cluster \"${cluster_name}\" --timeout=40m --region \"${cluster_region}\" --zones us-east-1a,us-east-1b,us-east-1c --auto-kubeconfig --version=1.21 --fargate\n    eksctl create fargateprofile --namespace \"${crd_namespace}\" --cluster \"${cluster_name}\" --name namespace-profile --region \"${cluster_region}\"\n    eksctl create fargateprofile --namespace \"${default_operator_namespace}\" --cluster \"${cluster_name}\" --name operator-profile --region \"${cluster_region}\"\n\n    echo \"Setting kubeconfig\"\n    export KUBECONFIG=\"/root/.kube/eksctl/clusters/${cluster_name}\"\nelse\n    readonly cluster_info=\"$(kubectl config get-contexts | awk '$1 == \"*\" {print $3}' | sed 's/\\./ /g')\"\n    readonly cluster_name=\"$(echo \"${cluster_info}\" | awk '{print $1}')\"\n    readonly cluster_region=\"$(echo \"${cluster_info}\" | awk '{print $2}')\"\nfi\n\necho \"[SECTION] Setup for integration tests\"\n# Download the CRD from the tarball artifact bucket\naws s3 cp s3://$ALPHA_TARBALL_BUCKET/${CODEBUILD_RESOLVED_SOURCE_VERSION}/sagemaker-k8s-operator-us-west-2-alpha.tar.gz sagemaker-k8s-operator.tar.gz \ntar -xf sagemaker-k8s-operator.tar.gz\n# Jump to the root dir of the operator\npushd sagemaker-k8s-operator\n# Setup the PATH for smlogs\n    mv smlogs-plugin/linux.amd64/kubectl-smlogs /usr/bin/kubectl-smlogs\n    path_to_installer=$(pwd)/sagemaker-k8s-operator-install-scripts\npopd\n\necho \"[SECTION] Run integration tests for the cluster scoped operator deployment\"\n\ngenerate_iam_role_name \"${default_operator_namespace}\"\ndefault_role_name=\"${role_name}\"  # role_name will get overwritten, save for cleanup. \npushd tests/codebuild\n    ./generate_iam_role.sh \"${cluster_name}\" \"${default_operator_namespace}\" \"${default_role_name}\" \"${cluster_region}\"\npopd\n\nif [ \"${SKIP_INSTALLATION}\" == \"true\" ]; then\n    echo \"Skipping installation of CRDs and operator\"\nelse\n    operator_clusterscope_deploy \"${default_role_name}\"\nfi\n\necho \"[SECTION] Running integration tests in default namespace\"\npushd tests/codebuild\n    ./run_all_sample_test.sh \"default\"\npopd\n\necho \"Skipping private link test\"\n#pushd private-link-test && ./run_private_link_integration_test \"${cluster_name}\" \"us-west-2\" && popd\n\n\necho \"[SECTION] Run integration tests for the namespaced operator deployment\"\n\n# Cleanup \necho \"[SECTION] Cleaning the default namespace to test namespace deployment\"\ncleanup_default_namespace\n\n# If any command fails, exit the script with an error code.\n# Cleanup unsets this\nset -e\n\n#Create the IAM Role for the given namespace\ngenerate_iam_role_name \"${crd_namespace}\"\npushd tests/codebuild\n    ./generate_iam_role.sh \"${cluster_name}\" \"${crd_namespace}\" \"${role_name}\" \"${cluster_region}\"\npopd\n\n# Allow for overriding the installation of the CRDs/controller image from the\n# build scripts if we want to use our own installation\nif [ \"${SKIP_INSTALLATION}\" == \"true\" ]; then\n    echo \"Skipping installation of CRDs and operator\"\nelse\n    operator_namespace_deploy \"${crd_namespace}\" \"${role_name}\"\nfi \n\n# Run the integration test file\necho \"[SECTION] Running integration tests for namespace deployment\"\npushd tests/codebuild/ \n    ./run_all_sample_namespace_tests.sh \"${crd_namespace}\"\npopd\n\n", "num_lines": 153}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Ensure that the smlogs kubectl plugin is able to detect and properly process the output of each job type.\nfunction run_smlogs_canary_tests\n{\n  echo \"Running smlogs canary tests\"\n  # Verify smlogs worked.\n  if [ \"$(kubectl smlogs trainingjob xgboost-mnist | wc -l)\" -lt \"1\" ]; then\n    echo \"smlogs trainingjob did not produce any output.\"\n    exit 1\n  fi\n  if [ \"$(kubectl smlogs batchtransformjob xgboost-batch | wc -l)\" -lt \"1\" ]; then\n    echo \"smlogs batchtransformjob did not produce any output.\"\n    exit 1\n  fi\n}\n\nfunction run_smlogs_integration_tests\n{\n  echo \"Running smlogs integration tests\"\n  run_smlogs_canary_tests\n}\n", "num_lines": 23}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource common.sh\nsource inject_tests.sh\n\n# Updates the spec and re-applies to ensure updates work as expected.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction run_update_canary_tests\n{\n  local crd_namespace=\"$1\"\n}\n\n# Parameter:\n#    $1: CRD namespace\nfunction run_update_integration_tests\n{\n  echo \"Running update integration tests\"\n  local crd_namespace=\"$1\"\n  run_update_canary_tests \"${crd_namespace}\"\n\n  echo \"Injecting variables into tests\"\n  inject_all_variables\n\n  echo \"Starting Update Tests\"\n  update_hap_test \"${crd_namespace}\" named-xgboost-hosting testfiles/xgboost-hostingautoscaling.yaml\n}\n\n# Verifies that all resources were created and are running/completed for the canary tests.\n# Parameter:\n#    $1: Namespace of the CRD\nfunction verify_update_canary_tests\n{\n  local crd_namespace=\"$1\"\n  echo \"Verifying update tests\"\n}\n\n\n# Verifies that each integration update test has completed successfully.\n# Parameter:\n#    $1: CRD namespace\nfunction verify_update_integration_tests\n{\n  echo \"Verifying Update integration tests\"\n  local crd_namespace=\"$1\"\n  verify_update_canary_tests\n\n  # At this point there are two variants in total(1 predefined and 1 custom) that have HAP applied. \n  verify_test \"${crd_namespace}\" HostingAutoscalingPolicy hap-predefined 5m Created\n  # verify_hap_test \"2\"\n}\n\n# Updates the ResourceID List and the MaxCapacity in the spec to check for updates \n# Parameter:\n#    $1: Target namespace\n#    $2: K8s Name of the hostingdeployment to apply autoscaling \n#    $3: Filename of the hap test to update\nfunction update_hap_test()\n{\n  local target_namespace=\"$1\"\n  local hosting_deployment_1=\"$2\"\n  local file_name=\"$3\"\n  local hostingdeployment_type=\"hostingdeployment\"\n  local updated_filename=\"${file_name}-updated-${target_namespace}\"\n\n  # Copy and update the test file\n  cp \"${file_name}\" \"${updated_filename}\"\n  # Update the Resource ID list to remove one endpoint/variant\n  yq d -i \"${updated_filename}\" \"spec.resourceId[1]\"\n  yq w -i \"$updated_filename\" \"spec.resourceId[0].endpointName\" ${hosting_deployment_1}\n  yq w -i \"$updated_filename\" \"spec.maxCapacity\" 3\n\n  # HAP Test 1: Using the Predefined Metric\n  run_test \"$target_namespace\" \"$updated_filename\"\n\n  yq w -i testfiles/xgboost-hosting-deployment.yaml \"metadata.name\" ${hosting_deployment_1}\n  rm \"${updated_filename}\"\n}", "num_lines": 78}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script was downloaded from https://docs.aws.amazon.com/codebuild/latest/userguide/use-codebuild-agent.html\n# DO NOT MODIFY unless you want to maintain your changes.\n#\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\n\nwhile getopts \"cmi:a:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run -it \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath $artifact_dir)\\\"\"\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath $PWD)\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath ${source_dirs[$index]})\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath ${source_dirs[$index]#*:})\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath $buildspec)\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\ndocker_command+=\" amazon/aws-codebuild-local:latest\"\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 190}
{"repo_name": "amazon-sagemaker-operator-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ -z \"$KUBECONFIG\" ]; then\n    KUBECONFIG=~/.kube/config\nfi\n\nif [ ! -f \"$KUBECONFIG\" ]; then\n    echo \"Kubeconfig '$KUBECONFIG' does not seem to exist\"\n    exit 1\nfi\n\nset -e \n\necho \"Pulling latest aws-codebuild-local image\"\ndocker pull amazon/aws-codebuild-local:latest --disable-content-trust=false\n\necho \"Copying kubeconfig to ${pwd}, so that it can be included in local docker image.\"\ncp \"$KUBECONFIG\" local-kubeconfig\n\necho \"Adding layer to integration test container with your kubeconfig\"\ndocker build . -f local-codebuild-Dockerfile -t local-codebuild\n\necho \"Running integration test\"\n# AWS_REGION must be us-west-2 because our pipelines are defined there. \nAWS_REGION=us-west-2 ./codebuild_build.sh \\\n    -e .env \\\n    -i local-codebuild \\\n    -a ./artifact \\\n    -c \\\n    -b ../../../codebuild/integration_test.yaml \\\n    -s \"$(realpath ../../../)\"\n", "num_lines": 32}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "cp test.txt test_installed.txt\nexit 0\n", "num_lines": 3}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "cp test_installed.txt test_uninstalled.txt\nexit 0\n", "num_lines": 3}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "cp test.txt test_installed.txt\nexit 0\n", "num_lines": 3}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "cp test_installed.txt test_uninstalled.txt\nexit 0\n", "num_lines": 3}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ndeclare -r PERSISTENT_STORAGE_BASE_DIR=\"/.ssm/containers/current\"\ndeclare -r USER_DATA=\"${PERSISTENT_STORAGE_BASE_DIR}/user-data\"\ndeclare -r SSM_AGENT_LOCAL_STATE_DIR=\"/var/lib/amazon/ssm\"\n\nlog() {\n  echo \"$*\" >&2\n}\n\nenable_hybrid_env_ssm() {\n  # SSM parameters necessary to register with a hybrid activation\n  local activation_code\n  local activation_id\n  local region\n\n  activation_code=$(fetch_from_json '.[\"ActivationCode\"]' \"${USER_DATA}\")\n  activation_id=$(fetch_from_json '.[\"ActivationId\"]' \"${USER_DATA}\")\n  region=$(fetch_from_json '.[\"Region\"]' \"${USER_DATA}\")\n\n  # Register with AWS Systems Manager (SSM)\n  if ! amazon-ssm-agent -register -code \"${activation_code}\" -id \"${activation_id}\" -region \"${region}\"; then\n\n    # Print errors from ssm agent error log\n    cat \"/var/log/amazon/ssm/errors.log\" >&2\n\n    log \"Failed to register with AWS Systems Manager (SSM)\"\n    exit 1\n  fi\n}\n\n# Fetch the values from json, and exit on failure (if any)\nfetch_from_json() {\n  local key=\"${1:?}\"\n  local file=\"${2:?}\"\n  local value\n  if ! value=$(jq -e -r \"${key}\" \"${file}\"); then\n    log \"Unable to parse ${key} from ${file}\"\n    return 1\n  fi\n  if [[ -z \"${value}\" ]]; then\n    log \"No value set for ${key} in ${file}\"\n    return 1\n  fi\n  echo \"${value}\"\n}\n\nif [[ -s \"${USER_DATA}\" ]] \\\n&& [[ ! -s \"${SSM_AGENT_LOCAL_STATE_DIR}/registration\" ]] \\\n&& jq --exit-status '.[\"ActivationId\"]' \"${USER_DATA}\" &>/dev/null ; then\n  enable_hybrid_env_ssm\nfi\n\nif [[ -s \"${SSM_AGENT_LOCAL_STATE_DIR}/registration\" ]] ; then\n  echo \"SSM Agent instance id is $(jq -e -r '.[\"ManagedInstanceID\"]' ${SSM_AGENT_LOCAL_STATE_DIR}/registration)\"\nfi\n\n# Start an SSM Agent process in the foreground\nexec /usr/bin/amazon-ssm-agent\n", "num_lines": 62}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Run checkstyle script\"\n\n# run gofmt\necho \"Run 'gofmt'\"\nunformatted=$(gofmt -l `pwd`/agent/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by gofmt\"\n\tfor fi in $unformatted; do\n\t\techo >&2 $fi\n\tdone\n\techo \"Please run 'gofmt -w' for files listed.\"\n\texit 1\nfi\n\nunformatted=$(gofmt -l `pwd`/core/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by gofmt\"\n\tfor fi in $unformatted; do\n\t\techo >&2 $fi\n\tdone\n\techo \"Please run 'gofmt -w' for files listed.\"\n\texit 1\nfi\n\nunformatted=$(gofmt -l `pwd`/common/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by gofmt\"\n\tfor fi in $unformatted; do\n\t\techo >&2 $fi\n\tdone\n\techo \"Please run 'gofmt -w' for files listed.\"\n\texit 1\nfi\n\necho \"Run 'goimports'\"\nunformatted=$(Tools/bin/goimports -l `pwd`/agent/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by goimports\"\n\tfor f in $unformatted; do\n\t\techo >&2 $f\n\tdone\n\techo \"Please run 'goimports -w' for files listed.\"\n\texit 1\nfi\n\nunformatted=$(Tools/bin/goimports -l `pwd`/core/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by goimports\"\n\tfor f in $unformatted; do\n\t\techo >&2 $f\n\tdone\n\techo \"Please run 'goimports -w' for files listed.\"\n\texit 1\nfi\n\nunformatted=$(Tools/bin/goimports -l `pwd`/common/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by goimports\"\n\tfor f in $unformatted; do\n\t\techo >&2 $f\n\tdone\n\techo \"Please run 'goimports -w' for files listed.\"\n\texit 1\nfi\n\n# run govet\necho \"Run 'go vet'\"\ngo vet -composites=false ./agent/...\ngo vet -composites=false ./core/...\ngo vet -composites=false ./common/...\n", "num_lines": 72}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Copying DomainJoin and CloudWatch binaries\"\necho \"****************************************\"\n\nBIN_FOLDER=\"$GO_SPACE/bin/\"\n\nCLOUDWATCH_FOLDER=\"${BIN_FOLDER}awsCloudwatch/\"\nSESSION_MANAGER_SHELL_FOLDER=\"${BIN_FOLDER}SessionManagerShell/\"\n\nPLUGIN_DEPENDENCIES=\"$GO_SPACE/packaging/dependencies\"\n\n# Set DomainJoin path\nDJ_DEPENDENCIES=$PLUGIN_DEPENDENCIES\n\n# Copy DomainJoin dependencies\ncp $DJ_DEPENDENCIES/AWS.DomainJoin.exe $BIN_FOLDER\ncp $DJ_DEPENDENCIES/AWS.DomainJoin.exe.config $BIN_FOLDER\ncp $DJ_DEPENDENCIES/log4net.config $BIN_FOLDER\n\n# Set CloudWatch path\nCW_DEPENDENCIES=\"$PLUGIN_DEPENDENCIES/awsCloudwatch\"\n\n# Prepare CloudWatch folder\nif [[ -d \"$CLOUDWATCH_FOLDER\" ]]; then\n   rmdir \"$CLOUDWATCH_FOLDER\"\nfi\nmkdir \"$CLOUDWATCH_FOLDER\"\n\n# Copy CloudWatch dependencies\ncp $CW_DEPENDENCIES/AWS.CloudWatch.exe $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWS.CloudWatch.exe.config $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWS.CloudWatch.log4net.config $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.CloudWatch.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.CloudWatchLogs.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.Core.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.EC2Messaging.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWS.EC2.Windows.CloudWatch.Configuration.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWS.EC2.Windows.CloudWatch.DataFlowParser.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWS.EC2.Windows.CloudWatch.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.S3.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/AWSSDK.SimpleSystemsManagement.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Common.Logging.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Ec2Config.Common.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Ec2Config.Ec2ConsoleLogger.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Ec2Config.Plugin.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Ec2Config.Plugin.Internal.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Ec2Config.Plugin.Tools.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/ICSharpCode.SharpZipLib.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Jetbrains.Annotations.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/log4net.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.EnterpriseLibrary.Common.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.EnterpriseLibrary.Validation.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.ServiceLocation.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.Unity.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.Unity.Configuration.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Microsoft.Practices.Unity.Interception.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Newtonsoft.Json.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/Quartz.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/SmartThreadPool.dll $CLOUDWATCH_FOLDER\ncp $CW_DEPENDENCIES/System.Threading.dll $CLOUDWATCH_FOLDER\n\n# Set Session path\nSESSION_DEPENDENCIES=\"$PLUGIN_DEPENDENCIES\"\n\n# Prepare Session folder\nif [[ -d \"$SESSION_MANAGER_SHELL_FOLDER\" ]]; then\n   rmdir \"$SESSION_MANAGER_SHELL_FOLDER\"\nfi\nmkdir \"$SESSION_MANAGER_SHELL_FOLDER\"\n\n# Copy Session dependencies\nif [ -f \"$SESSION_DEPENDENCIES/winpty/winpty.dll\" ]; then\n  cp $SESSION_DEPENDENCIES/winpty/winpty.dll $SESSION_MANAGER_SHELL_FOLDER\n  cp $SESSION_DEPENDENCIES/winpty/winpty-agent.exe $SESSION_MANAGER_SHELL_FOLDER\nfi", "num_lines": 76}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Generate test coverage statistics for Go packages.\n#\n\necho \"Try update 'cover'\"\nGOPATH=`pwd`/Tools go get -u golang.org/x/tools/cmd/cover\n\nset -e\n\nwork_dir=.cover\nprofile=\"$work_dir/cover.out\"\nmode=count\ncode_coverage_roots=(\"$@\")\n\nmkdir -p \"$work_dir\"\n\ngenerate_code_coverage(){\n\tfor package in \"$@\"; do\n        f=\"$work_dir/$(echo $package | tr / -).cover\"\n        go test -covermode=\"$mode\" -coverprofile=\"$f\" \"$package\"\n    done\n    grep -h -v \"^mode:\" \"$work_dir\"/*.cover >>\"$profile\"\n}\n\necho \"mode: $mode\" >\"$profile\"\nfor root in ${code_coverage_roots[@]}; do\n    generate_code_coverage $(go list $root)\ndone\n\ngo tool cover -html=\"$profile\" -o ./bin/coverage.html\ngo tool cover -func=\"$profile\"\n\nrm -rf \"$work_dir\"", "num_lines": 33}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nFOLDER=$1\n\nif [ -z \"$FOLDER\" ]\n  then\n    echo \"Folder must be passed to this script\"\n    exit 1\nfi\n\necho \"************************************************************\"\necho \"Creating $FOLDER binary tar file\"\necho \"************************************************************\"\n\ntar --owner=0 --group=0 -zcvf ${GO_SPACE}/bin/${FOLDER}/amazon-ssm-agent-binaries.tar.gz  -C ${GO_SPACE}/bin/${FOLDER}/ amazon-ssm-agent ssm-agent-worker ssm-document-worker ssm-session-worker ssm-session-logger ssm-cli\n", "num_lines": 16}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nARCH=$1\n\necho \"****************************************\"\necho \"Creating tar file for Mac OS X $ARCH    \"\necho \"****************************************\"\n\nROOTFS=${GO_SPACE}/bin/darwin_$ARCH/darwin\nTAR_NAME=amazon-ssm-agent.tar.gz\nDESTINATION=${GO_SPACE}/bin/amazon-ssm-agent-darwin-$ARCH-`cat ${GO_SPACE}/VERSION`.tar.gz\nrm -rf ${ROOTFS}\n\necho \"Creating darwin folders\"\n\nmkdir -p ${ROOTFS}/Library/LaunchDaemons\n\nPROGRAM_FOLDER=${ROOTFS}/opt/aws/ssm\n\nmkdir -p ${PROGRAM_FOLDER}\nmkdir -p ${PROGRAM_FOLDER}/bin\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/darwin_$ARCH/amazon-ssm-agent ${PROGRAM_FOLDER}/bin/\ncp ${GO_SPACE}/bin/darwin_$ARCH/ssm-agent-worker ${PROGRAM_FOLDER}/bin/\ncp ${GO_SPACE}/bin/darwin_$ARCH/ssm-document-worker ${PROGRAM_FOLDER}/bin/\ncp ${GO_SPACE}/bin/darwin_$ARCH/ssm-cli ${PROGRAM_FOLDER}/bin/\ncp ${GO_SPACE}/bin/darwin_$ARCH/ssm-session-logger ${PROGRAM_FOLDER}/bin/\ncp ${GO_SPACE}/bin/darwin_$ARCH/ssm-session-worker ${PROGRAM_FOLDER}/bin/\n\ncp ${GO_SPACE}/seelog_unix.xml ${PROGRAM_FOLDER}/seelog.xml.template\ncp ${GO_SPACE}/amazon-ssm-agent.json.template ${PROGRAM_FOLDER}/\ncp ${GO_SPACE}/RELEASENOTES.md ${PROGRAM_FOLDER}/\ncp ${GO_SPACE}/README.md ${PROGRAM_FOLDER}/\ncp ${GO_SPACE}/packaging/darwin/com.amazon.aws.ssm.plist ${ROOTFS}/Library/LaunchDaemons/\n\necho \"Setting permissions as required by launchd\"\n\nchmod 600 ${ROOTFS}/Library/LaunchDaemons/*\n\necho \"Creating tar\"\n(\ncd ${ROOTFS}\ntar czf $TAR_NAME * --owner=0 --group=0\n)\n\necho \"Moving tar\"\ncp ${ROOTFS}/${TAR_NAME} ${DESTINATION}\n\necho \"Archive created at ${ROOTFS}/${TAR_NAME} and a versioned copy is at ${DESTINATION}\"\n", "num_lines": 53}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nARCH=$1\n\ncp ${GO_SPACE}/Tools/src/update/darwin/install_tar.sh ${GO_SPACE}/bin/darwin_$ARCH/darwin/install.sh\ncp ${GO_SPACE}/Tools/src/update/darwin/uninstall.sh ${GO_SPACE}/bin/darwin_$ARCH/darwin/uninstall.sh\n\nchmod 755 ${GO_SPACE}/bin/darwin_$ARCH/darwin/install.sh\nchmod 755 ${GO_SPACE}/bin/darwin_$ARCH/darwin/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/darwin_$ARCH/updater\n\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-darwin-$ARCH.tar.gz  -C ${GO_SPACE}/bin/darwin_$ARCH/darwin/ amazon-ssm-agent.tar.gz install.sh uninstall.sh\n\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-darwin-$ARCH.tar.gz  -C ${GO_SPACE}/bin/darwin_$ARCH/ updater\n\nrm ${GO_SPACE}/bin/darwin_$ARCH/darwin/install.sh\nrm ${GO_SPACE}/bin/darwin_$ARCH/darwin/uninstall.sh\n", "num_lines": 18}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nARCH=$1\n\necho \"****************************************\"\necho \"Creating deb file for Ubuntu Linux $ARCH\"\necho \"****************************************\"\n\nrm -rf ${GO_SPACE}/bin/debian_${ARCH}/debian\n\nif [[ \"$ARCH\" == \"arm\" ]]; then\n  DEB_ARCH=\"armhf\"\nelif [[ \"$ARCH\" == \"386\" ]]; then\n  DEB_ARCH=\"i386\"\nelse\n  DEB_ARCH=$ARCH\nfi\n\necho \"Creating debian folders debian_$ARCH\"\n\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/init/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/lintian/overrides/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/var/lib/amazon/ssm/\nmkdir -p ${GO_SPACE}/bin/debian_${ARCH}/debian/lib/systemd/system/\n\necho \"Copying application files debian_$ARCH\"\n\ncp ${GO_SPACE}/bin/linux_${ARCH}/amazon-ssm-agent ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/bin/linux_${ARCH}/ssm-agent-worker ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/bin/linux_${ARCH}/ssm-cli ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/bin/linux_${ARCH}/ssm-document-worker ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/bin/linux_${ARCH}/ssm-session-worker ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/bin/linux_${ARCH}/ssm-session-logger ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/seelog.xml.template\ncp ${GO_SPACE}/amazon-ssm-agent.json.template ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/\ncp ${GO_SPACE}/packaging/ubuntu/amazon-ssm-agent.conf ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/init/\ncp ${GO_SPACE}/packaging/ubuntu/amazon-ssm-agent.service ${GO_SPACE}/bin/debian_${ARCH}/debian/lib/systemd/system/\n\necho \"Copying debian package config files debian_$ARCH\"\n\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/RELEASENOTES.md\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/README.md\ncp ${GO_SPACE}/NOTICE.md ${GO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/ssm/\ncp ${GO_SPACE}/Tools/src/LICENSE ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/copyright\ncp ${GO_SPACE}/packaging/ubuntu/conffiles ${GO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${GO_SPACE}/packaging/ubuntu/docs ${GO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${GO_SPACE}/packaging/ubuntu/preinst ${GO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${GO_SPACE}/packaging/ubuntu/postinst ${GO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${GO_SPACE}/packaging/ubuntu/prerm ${GO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${GO_SPACE}/packaging/ubuntu/lintian-overrides ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/lintian/overrides/amazon-ssm-agent\n\necho \"Constructing the control file debian_$ARCH\"\n\necho 'Package: amazon-ssm-agent' > ${GO_SPACE}/bin/debian_${ARCH}/debian/control\necho \"Architecture: ${DEB_ARCH}\" >> ${GO_SPACE}/bin/debian_${ARCH}/debian/control\necho -n 'Version: ' >> ${GO_SPACE}/bin/debian_${ARCH}/debian/control\ncat ${GO_SPACE}/VERSION | tr -d \"\\n\" >> ${GO_SPACE}/bin/debian_${ARCH}/debian/control\necho '-1' >> ${GO_SPACE}/bin/debian_${ARCH}/debian/control\ncat ${GO_SPACE}/packaging/ubuntu/control >> ${GO_SPACE}/bin/debian_${ARCH}/debian/control\n\necho \"Constructing the changelog file debian_$ARCH\"\n\necho -n 'amazon-ssm-agent (' > ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog\ncat VERSION | tr -d \"\\n\"  >> ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog\necho '-1) unstable; urgency=low' >> ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog\ncat ${GO_SPACE}/packaging/ubuntu/changelog >> ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog\n\ncp ${GO_SPACE}/packaging/ubuntu/changelog.Debian ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/\ncp ${GO_SPACE}/packaging/ubuntu/debian-binary ${GO_SPACE}/bin/debian_${ARCH}/debian/\n\necho \"Setting permissions as required by debian_$ARCH\"\n\ncd ${GO_SPACE}/bin/debian_${ARCH}/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog for debian_$ARCH\"\n\ncd ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/; export GZIP=-9; tar cvzf changelog.Debian.gz changelog.Debian --owner=0 --group=0; cd ~-\n\nrm ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog\nrm ${GO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/amazon-ssm-agent/changelog.Debian\n\necho \"Creating tar for debian_$ARCH\"\n# the below permissioning is required by debian\ncd ${GO_SPACE}/bin/debian_${ARCH}/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_${ARCH}/debian/; tar czf control.tar.gz control conffiles docs preinst postinst prerm --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package debian_$ARCH\"\nar r ${GO_SPACE}/bin/debian_${ARCH}/amazon-ssm-agent.deb ${GO_SPACE}/bin/debian_${ARCH}/debian/debian-binary\nar r ${GO_SPACE}/bin/debian_${ARCH}/amazon-ssm-agent.deb ${GO_SPACE}/bin/debian_${ARCH}/debian/control.tar.gz\nar r ${GO_SPACE}/bin/debian_${ARCH}/amazon-ssm-agent.deb ${GO_SPACE}/bin/debian_${ARCH}/debian/data.tar.gz\n\n", "num_lines": 97}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_amd64/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_amd64/\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_386/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_386/\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_arm64/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_amd64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_amd64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/snap-install.sh ${GO_SPACE}/bin/debian_amd64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/snap-uninstall.sh ${GO_SPACE}/bin/debian_amd64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/snap-install.sh ${GO_SPACE}/bin/debian_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/snap-uninstall.sh ${GO_SPACE}/bin/debian_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_386/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_386/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_arm/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_arm/\n\n\nchmod 755 ${GO_SPACE}/bin/linux_amd64/install.sh ${GO_SPACE}/bin/linux_amd64/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/linux_386/install.sh ${GO_SPACE}/bin/linux_386/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/linux_arm64/install.sh ${GO_SPACE}/bin/linux_arm64/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_amd64/install.sh ${GO_SPACE}/bin/debian_amd64/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_amd64/snap-install.sh ${GO_SPACE}/bin/debian_amd64/snap-uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_arm64/snap-install.sh ${GO_SPACE}/bin/debian_arm64/snap-uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_386/install.sh ${GO_SPACE}/bin/debian_386/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_arm/install.sh ${GO_SPACE}/bin/debian_arm/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/debian_arm64/install.sh ${GO_SPACE}/bin/debian_arm64/uninstall.sh\nchmod 755 ${GO_SPACE}/bin/linux_amd64/updater\nchmod 755 ${GO_SPACE}/bin/linux_386/updater\nchmod 755 ${GO_SPACE}/bin/linux_arm/updater\nchmod 755 ${GO_SPACE}/bin/linux_arm64/updater\n\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-linux-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64/ amazon-ssm-agent.rpm install.sh uninstall.sh\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-linux-386.tar.gz  -C ${GO_SPACE}/bin/linux_386/ amazon-ssm-agent.rpm install.sh uninstall.sh\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-linux-arm64.tar.gz  -C ${GO_SPACE}/bin/linux_arm64/ amazon-ssm-agent.rpm install.sh uninstall.sh\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-ubuntu-arm.tar.gz  -C ${GO_SPACE}/bin/debian_arm/ amazon-ssm-agent.deb install.sh uninstall.sh\n\n# ubuntu is prepacked since snaps will be added later\ntar -cvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-ubuntu-amd64.tar  -C ${GO_SPACE}/bin/debian_amd64/ amazon-ssm-agent.deb install.sh uninstall.sh snap-install.sh snap-uninstall.sh\ntar -cvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-snap-amd64.tar  -C ${GO_SPACE}/bin/debian_amd64/ snap-install.sh snap-uninstall.sh\ntar -cvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-ubuntu-arm64.tar  -C ${GO_SPACE}/bin/debian_arm64/ amazon-ssm-agent.deb install.sh uninstall.sh snap-install.sh snap-uninstall.sh\ntar -cvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-snap-arm64.tar  -C ${GO_SPACE}/bin/debian_arm64/ snap-install.sh snap-uninstall.sh\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-ubuntu-386.tar.gz  -C ${GO_SPACE}/bin/debian_386/ amazon-ssm-agent.deb install.sh uninstall.sh\n\n\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-linux-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-ubuntu-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-snap-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-snap-arm64.tar.gz  -C ${GO_SPACE}/bin/linux_arm64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-ubuntu-arm64.tar.gz  -C ${GO_SPACE}/bin/linux_arm64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-linux-386.tar.gz  -C ${GO_SPACE}/bin/linux_386/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-linux-arm64.tar.gz  -C ${GO_SPACE}/bin/linux_arm64/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-ubuntu-386.tar.gz  -C ${GO_SPACE}/bin/linux_386/ updater\ntar -zcvf ${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-ubuntu-arm.tar.gz  -C ${GO_SPACE}/bin/linux_arm/ updater\n\nrm ${GO_SPACE}/bin/debian_amd64/install.sh\nrm ${GO_SPACE}/bin/debian_amd64/uninstall.sh\nrm ${GO_SPACE}/bin/debian_amd64/snap-install.sh\nrm ${GO_SPACE}/bin/debian_amd64/snap-uninstall.sh\nrm ${GO_SPACE}/bin/debian_arm64/snap-install.sh\nrm ${GO_SPACE}/bin/debian_arm64/snap-uninstall.sh\nrm ${GO_SPACE}/bin/debian_arm64/install.sh\nrm ${GO_SPACE}/bin/debian_arm64/uninstall.sh\nrm ${GO_SPACE}/bin/debian_386/install.sh\nrm ${GO_SPACE}/bin/debian_386/uninstall.sh\nrm ${GO_SPACE}/bin/debian_arm/install.sh\nrm ${GO_SPACE}/bin/debian_arm/uninstall.sh\nrm ${GO_SPACE}/bin/linux_amd64/install.sh\nrm ${GO_SPACE}/bin/linux_amd64/uninstall.sh\nrm ${GO_SPACE}/bin/linux_386/install.sh\nrm ${GO_SPACE}/bin/linux_386/uninstall.sh\nrm ${GO_SPACE}/bin/linux_arm64/install.sh\nrm ${GO_SPACE}/bin/linux_arm64/uninstall.sh", "num_lines": 77}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nFOLDER=$1\n\nif [ -z \"$FOLDER\" ]\n then\n   echo \"Folder name must be provided\"\n   exit 1\nfi\n\nif [[ \"$FOLDER\" == *amd64 ]]; then\n TARGET=x86_64\nelif [[ \"$FOLDER\" == *arm64 ]]; then\n TARGET=aarch64\nelif [[ \"$FOLDER\" == *386 ]]; then\n TARGET=i386\nelse\n echo \"Unsupported architecture\"\n exit 1\nfi\n\necho \"************************************************************\"\necho \"Creating $FOLDER rpm file for Amazon Linux and RHEL $TARGET\"\necho \"************************************************************\"\n\nrm -rf ${GO_SPACE}/bin/$FOLDER/linux\n\necho \"Creating rpmbuild workspace $FOLDER\"\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/\nmkdir -p ${GO_SPACE}/bin/$FOLDER/linux/var/lib/amazon/ssm/\n\n\necho \"Copying application files $FOLDER\"\n\ncp ${GO_SPACE}/bin/$FOLDER/amazon-ssm-agent ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/bin/$FOLDER/ssm-agent-worker ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/bin/$FOLDER/ssm-document-worker ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/bin/$FOLDER/ssm-session-worker ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/bin/$FOLDER/ssm-session-logger ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/bin/$FOLDER/ssm-cli ${GO_SPACE}/bin/$FOLDER/linux/usr/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/seelog.xml.template\ncp ${GO_SPACE}/amazon-ssm-agent.json.template ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/\ncp ${GO_SPACE}/NOTICE.md ${GO_SPACE}/bin/$FOLDER/linux/etc/amazon/ssm/\ncp ${GO_SPACE}/packaging/linux/amazon-ssm-agent.conf ${GO_SPACE}/bin/$FOLDER/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux/amazon-ssm-agent.service ${GO_SPACE}/bin/$FOLDER/linux/etc/systemd/system/\n\necho \"Creating the rpm package $FOLDER\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux/amazon-ssm-agent.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/$FOLDER/linux\"\n\nrpmbuild -bb --target $TARGET --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/$FOLDER/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\ncp ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/RPMS/$TARGET/*.rpm ${GO_SPACE}/bin/$FOLDER/amazon-ssm-agent.rpm\nrm -rf ${GO_SPACE}/bin/$FOLDER/linux/rpmbuild/RPMS/$TARGET/*\n", "num_lines": 67}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows amd64\"\necho \"****************************************\"\n\nBIN_FOLDER=${GO_SPACE}/bin\nBUILD_FOLDER=${BIN_FOLDER}/windows_amd64\nPACKAGE_FOLDER=${BUILD_FOLDER}/windows\nTOOLS_FOLDER=${GO_SPACE}/Tools/src\n\nrm -rf ${PACKAGE_FOLDER}\n\necho \"Creating windows folders\"\n\nmkdir -p ${PACKAGE_FOLDER}\n\necho \"Copying application files\"\n\ncp ${BUILD_FOLDER}/amazon-ssm-agent.exe ${PACKAGE_FOLDER}/amazon-ssm-agent.exe\ncp ${BUILD_FOLDER}/ssm-agent-worker.exe ${PACKAGE_FOLDER}/ssm-agent-worker.exe\ncp ${BUILD_FOLDER}/ssm-document-worker.exe ${PACKAGE_FOLDER}/ssm-document-worker.exe\ncp ${BUILD_FOLDER}/ssm-session-worker.exe ${PACKAGE_FOLDER}/ssm-session-worker.exe\ncp ${BUILD_FOLDER}/ssm-session-logger.exe ${PACKAGE_FOLDER}/ssm-session-logger.exe\ncp ${BUILD_FOLDER}/ssm-cli.exe ${PACKAGE_FOLDER}/ssm-cli.exe\ncp ${GO_SPACE}/seelog_windows.xml.template ${PACKAGE_FOLDER}/seelog.xml.template\ncp ${GO_SPACE}/amazon-ssm-agent.json.template ${PACKAGE_FOLDER}/amazon-ssm-agent.json.template\n\necho \"Copying windows package config files\"\n\ncp ${TOOLS_FOLDER}/LICENSE ${PACKAGE_FOLDER}/LICENSE\ncp ${GO_SPACE}/NOTICE.md ${PACKAGE_FOLDER}/NOTICE.md\n\necho \"Constructing the zip package\"\n\nif [ -f ${PACKAGE_FOLDER}/amazon-ssm-agent.zip ]\nthen\n    rm ${PACKAGE_FOLDER}/amazon-ssm-agent.zip\nfi\ncd ${PACKAGE_FOLDER}\nzip -r package *\n", "num_lines": 41}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nBUILD_PATH_AMD64=${GO_SPACE}/bin/windows_amd64\nPACKAGE_PATH_WINDOWS=${BUILD_PATH_AMD64}/windows\nPACKAGE_PATH_NANO=${PACKAGE_PATH_WINDOWS}_nano\n\nmkdir -p ${PACKAGE_PATH_NANO}\n\ncp ${GO_SPACE}/Tools/src/update/windows_nano/install.ps1 ${PACKAGE_PATH_NANO}/\ncp ${GO_SPACE}/Tools/src/update/windows_nano/uninstall.ps1 ${PACKAGE_PATH_NANO}/\ncp ${PACKAGE_PATH_WINDOWS}/package.zip ${PACKAGE_PATH_NANO}/\n\nWINDOWS_NANO_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-windows-nano-amd64.zip\nzip -j ${WINDOWS_NANO_ZIP} ${PACKAGE_PATH_NANO}/package.zip\nzip -j ${WINDOWS_NANO_ZIP} ${PACKAGE_PATH_NANO}/install.ps1\nzip -j ${WINDOWS_NANO_ZIP} ${PACKAGE_PATH_NANO}/uninstall.ps1\n\nWINDOWS_NANO_UPDATE_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-windows-nano-amd64.zip\nzip -j ${WINDOWS_NANO_UPDATE_ZIP} ${BUILD_PATH_AMD64}/updater.exe\n", "num_lines": 20}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nBUILD_PATH_AMD64=${GO_SPACE}/bin/windows_amd64\nBUILD_PATH_386=${GO_SPACE}/bin/windows_386\nPACKAGE_PATH_AMD64=${BUILD_PATH_AMD64}/windows\nPACKAGE_PATH_386=${BUILD_PATH_386}/windows\n\ncp ${GO_SPACE}/Tools/src/update/windows/install.bat ${PACKAGE_PATH_AMD64}/\ncp ${GO_SPACE}/Tools/src/update/windows/uninstall.bat ${PACKAGE_PATH_AMD64}/\ncp ${GO_SPACE}/Tools/src/update/windows/install.bat ${PACKAGE_PATH_386}/\ncp ${GO_SPACE}/Tools/src/update/windows/uninstall.bat ${PACKAGE_PATH_386}/\n\nWINDOWS_AMD64_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-windows-amd64.zip\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_PATH_AMD64}/package.zip\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_PATH_AMD64}/install.bat\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_PATH_AMD64}/uninstall.bat\n\nWINDOWS_386_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-windows-386.zip\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_PATH_386}/package.zip\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_PATH_386}/install.bat\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_PATH_386}/uninstall.bat\n\nWINDOWS_AMD64_UPDATER_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-windows-amd64.zip\nzip -j ${WINDOWS_AMD64_UPDATER_ZIP} ${BUILD_PATH_AMD64}/updater.exe\n\nWINDOWS_386_UPDATER_ZIP=${GO_SPACE}/bin/updates/amazon-ssm-agent-updater/`cat ${GO_SPACE}/VERSION`/amazon-ssm-agent-updater-windows-386.zip\nzip -j ${WINDOWS_386_UPDATER_ZIP} ${BUILD_PATH_386}/updater.exe\n", "num_lines": 28}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows 386\"\necho \"****************************************\"\n\nBIN_FOLDER=${GO_SPACE}/bin\nBUILD_FOLDER=${BIN_FOLDER}/windows_386\nPACKAGE_FOLDER=${BUILD_FOLDER}/windows\nTOOLS_FOLDER=${GO_SPACE}/Tools/src\n\nrm -rf ${PACKAGE_FOLDER}\n\necho \"Creating windows folders\"\n\nmkdir -p ${PACKAGE_FOLDER}\n\necho \"Copying application files\"\n\ncp ${BUILD_FOLDER}/amazon-ssm-agent.exe ${PACKAGE_FOLDER}/amazon-ssm-agent.exe\ncp ${BUILD_FOLDER}/ssm-agent-worker.exe ${PACKAGE_FOLDER}/ssm-agent-worker.exe\ncp ${BUILD_FOLDER}/ssm-document-worker.exe ${PACKAGE_FOLDER}/ssm-document-worker.exe\ncp ${BUILD_FOLDER}/ssm-session-worker.exe ${PACKAGE_FOLDER}/ssm-session-worker.exe\ncp ${BUILD_FOLDER}/ssm-session-logger.exe ${PACKAGE_FOLDER}/ssm-session-logger.exe\ncp ${BUILD_FOLDER}/ssm-cli.exe ${PACKAGE_FOLDER}/ssm-cli.exe\ncp ${GO_SPACE}/seelog_windows.xml.template ${PACKAGE_FOLDER}/seelog.xml.template\ncp ${GO_SPACE}/amazon-ssm-agent.json.template ${PACKAGE_FOLDER}/amazon-ssm-agent.json.template\n\necho \"Copying windows package config files\"\n\ncp ${TOOLS_FOLDER}/LICENSE ${PACKAGE_FOLDER}/LICENSE\ncp ${GO_SPACE}/NOTICE.md ${PACKAGE_FOLDER}/NOTICE.md\n\necho \"Constructing the zip package\"\n\nif [ -f ${PACKAGE_FOLDER}/amazon-ssm-agent.zip ]\nthen\n    rm ${PACKAGE_FOLDER}/amazon-ssm-agent.zip\nfi\ncd ${PACKAGE_FOLDER}\nzip -r package.zip *\n", "num_lines": 41}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"Install misspell, goreportcard, gometalinter and godep\"\ngo get github.com/client9/misspell/cmd/misspell\ngo get github.com/gojp/goreportcard\ngo get github.com/alecthomas/gometalinter\ngo get github.com/tools/godep\n\necho \"Setup Path\"\nBIN_FOLDER=${GO_SPACE}/vendor/bin\nLOCAL_REPORT_CARD_SRC_OVERRIDE=${GO_SPACE}/Tools/src/goreportcard/checks.go\nSOURCE_FOLDER=${GO_SPACE}/vendor/src/github.com/gojp/goreportcard\nREPOS_PACKAGE=${SOURCE_FOLDER}/repos/src/github.com/aws/amazon-ssm-agent\nPATH=${BIN_FOLDER}:${PATH}\n\necho \"Replace gojp/goreportcard/handlers/checks.go with local copy\"\ncp ${LOCAL_REPORT_CARD_SRC_OVERRIDE} ${SOURCE_FOLDER}/handlers/checks.go\n\necho \"Install gometalinter dependency\"\n${BIN_FOLDER}/gometalinter --install --update\n${BIN_FOLDER}/godep save\n\necho \"Copy amazon-ssm-agent package to the gocardreport repos directory\"\nrm -rf ${REPOS_PACKAGE}\nmkdir -p ${REPOS_PACKAGE}\ncp -R ${GO_SPACE}/agent ${REPOS_PACKAGE}/agent/\n\necho \"Start up goreportcard\"\ncd ${SOURCE_FOLDER}\n${BIN_FOLDER}/godep go run main.go", "num_lines": 30}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "# Insert license header at the top of each file \n# NOTE: this script has to be executed from the project root\nfind src/ -name \"*.go\" | while read fileName\ndo \n  if ! grep -q Copyright \"$fileName\"\n  then\n    echo Inserting license in $fileName\n    cat Tools/src/LICENSE > \"$fileName.new\"\n    \n    # add empty line after the license, in case the license doesn't have one\n    # (gofmt will clear it if not needed)\n    echo \"\" >> \"$fileName.new\"\n    \n    cat \"$fileName\" >> \"$fileName.new\"\n    mv \"$fileName.new\" \"$fileName\"\n  fi\ndone\n\n", "num_lines": 19}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Running Integration Tests\"\n\nmkdir -p src/github.com/aws/amazon-ssm-agent\ncp -r agent src/github.com/aws/amazon-ssm-agent\n\nGOROOT=`pwd`/test-runtime/lib CGO_ENABLED=0  GOPATH=`pwd`:`pwd`/vendor:`pwd`/test-runtime/lib `pwd`/test-runtime/lib/bin/go test -v --tags=integration github.com/aws/amazon-ssm-agent/agent/...\nexitCode=$?\n\nif [[ $exitCode == 0 ]]\nthen\n\t\techo \"TEST PASSED.\"\nelse\n\t\techo \"TEST FAILED.\"\nfi\n\nrm -rf src/github.com\n\nexit $exitCode\n", "num_lines": 20}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nchanged_golang_packages=$(git status --porcelain | awk '{print $2}' | grep '\\.go$' | xargs dirname | sort | uniq)\n\nif  [[ -x \"$(command -v golangci-lint)\" ]]; then\n  echo \"golangci-lint executable found.\"\n  echo \"Running golangci-lint on changed files\"\n  for package_dir in $changed_golang_packages\n  do\n    $(command -v golangci-lint) run \"$package_dir/...\"\n  done\nelse\n  bold=$(tput bold)\n  normal=$(tput sgr0)\n  echo \"${bold}golangci-lint executable not found. See https://golangci-lint.run/usage/install/ for installation instructions.${normal}\"\n  exit 1\nfi\n", "num_lines": 17}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# helper function to set error output\nfunction error_exit\n{\n\techo \"$1\" 1>&2\n\texit 1\n}\n\n# check parameters for registering managed instance\nDO_REGISTER=false\nif [ \"$1\" == \"register-managed-instance\" ]; then\n\tif [ $# -eq 4 ]; then\n\t\tDO_REGISTER=true\n\t\tRMI_CODE=$2\n\t\tRMI_ID=$3\n\t\tRMI_REGION=$4\n\telse\n\t\terror_exit '[ERROR] Not enough parameters for RegisterManagedInstance.'\n\tfi\nfi\n\nlaunchctl list com.amazon.aws.ssm >/dev/null 2>&1\nif [ $? -eq 0 ]; then\n    echo \"-> Agent is running in the instance\"\n    echo \"Stopping the agent\"\n    launchctl unload -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist\n    echo \"Agent stopped\"\nelse\n    echo \"-> Agent is not running in the instance\"\nfi\n\necho \"Installing agent\"\ninstaller -pkg ./amazon-ssm-agent.pkg -target /\n\nif [ \"$DO_REGISTER\" = true ]; then\n    /opt/aws/ssm/amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\nfi\n\necho \"Starting agent\"\nlaunchctl load -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist\nlaunchctl start com.amazon.aws.ssm\necho \"$(launchctl list com.amazon.aws.ssm)\"\n", "num_lines": 44}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# helper function to set error output\nfunction error_exit\n{\n\techo \"$1\" 1>&2\n\texit 1\n}\n\n# check parameters for registering managed instance\nDO_REGISTER=false\nif [ \"$1\" == \"register-managed-instance\" ]; then\n\tif [ $# -eq 4 ]; then\n\t\tDO_REGISTER=true\n\t\tRMI_CODE=$2\n\t\tRMI_ID=$3\n\t\tRMI_REGION=$4\n\telse\n\t\terror_exit '[ERROR] Not enough parameters for RegisterManagedInstance.'\n\tfi\nfi\n\nlaunchctl list com.amazon.aws.ssm >/dev/null 2>&1\nif [ $? -eq 0 ]; then\n    echo \"-> Agent is running in the instance\"\n    echo \"Stopping the agent\"\n    launchctl unload -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist\n    echo \"Agent stopped\"\nelse\n    echo \"-> Agent is not running in the instance\"\nfi\n\necho \"Installing agent\"\nsudo tar -xvf amazon-ssm-agent.tar.gz -C /\n\nif [ \"$DO_REGISTER\" = true ]; then\n    /opt/aws/ssm/amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\nfi\n\necho \"Starting agent\"\nlaunchctl load -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist\nlaunchctl start com.amazon.aws.ssm\necho \"$(launchctl list com.amazon.aws.ssm)\"\n\n\n", "num_lines": 46}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ns3path=$1\n\necho \"Uninstalling Amazon-ssm-agent\"\n\n# helper function to set error output\nfunction error_exit\n{\n\techo \"$1\" 1>&2\n\texit 1\n}\n\necho \"Checking if the agent is installed\"\nlaunchctl list com.amazon.aws.ssm >/dev/null 2>&1\nif [ $? -eq 0 ]; then\n    echo \"-> Agent is installed in this instance\"\n    echo \"Uninstalling the agent\"\n    launchctl unload -w /Library/LaunchDaemons/com.amazon.aws.ssm.plist\n    echo \"Agent stopped\"\n\n    rm -rf /opt/aws/ssm/bin\n    rm /opt/aws/ssm/seelog.xml.template\n    rm /opt/aws/ssm/amazon-ssm-agent.json.template\n    rm /opt/aws/ssm/RELEASENOTES.md\n    rm /opt/aws/ssm/README.md\n    rm /opt/aws/ssm/NOTICE.md\n    rm /Library/LaunchDaemons/com.amazon.aws.ssm.plist\nelse\n    echo \"-> Agent is not installed in this instance\"\nfi\n\n\npkgutil --pkg-info com.amazon.aws.ssm >/dev/null 2>&1\nif [ $? -eq 0 ]; then\n    echo \"Uninstall the Agent pkg\"\n    pkgutil --forget com.amazon.aws.ssm >/dev/null 2>&1\n    if [ $? -eq 0 ]; then\n        echo \"Agent uninstalled\"\n    fi\nfi", "num_lines": 41}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n\n# check parameters for registering managed instance\nDO_REGISTER=false\nif [ \"$1\" == \"register-managed-instance\" ]; then\n  if [ $# -eq 4 ]; then\n    DO_REGISTER=true\n    RMI_CODE=$2\n    RMI_ID=$3\n    RMI_REGION=$4\n  else\n    error_exit '[ERROR] Not enough parameters for RegisterManagedInstance.'\n  fi\nfi\n\n# allow ssm-agent to finish it's work\nsleep 2\n\nif [[ $(/sbin/init --version 2> /dev/null) =~ upstart ]]; then\n  echo \"upstart detected\"\n  echo \"Installing agent\"\n  pmOutput=$(rpm -U amazon-ssm-agent.rpm 2>&1)\n  pmExit=$?\n  echo \"RPM Output: $pmOutput\"\n\n  if [ \"$DO_REGISTER\" = true ]; then\n\t\t/sbin/stop amazon-ssm-agent\n\t\tamazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\n  fi\n\n  agentVersion=$(rpm -q --qf '%{VERSION}\\n' amazon-ssm-agent)\n  echo \"Installed version: '$agentVersion'\"\n\n  echo \"starting agent\"\n  /sbin/start amazon-ssm-agent\n  status amazon-ssm-agent\n\n  if [ \"$pmExit\" -ne 0 ]; then\n    if [[ $pmOutput == *\"is already installed\"* ]]; then\n      echo \"Install was successfull\"\n      exit 0\n    fi\n\n    echo \"Package manager failed with exit code '$pmExit'\"\n    echo \"Package manager output: $pmOutput\"\n    exit 125\n  fi\nelif [[ $(systemctl 2> /dev/null) =~ -\\.mount ]]; then\n  if [[ \"$(systemctl is-active amazon-ssm-agent.service)\" == \"active\" ]]; then\n    echo \"-> Agent is running in the instance\"\n    echo \"Stopping the agent\"\n    systemctl stop amazon-ssm-agent.service\n    echo \"Agent stopped\"\n    systemctl daemon-reload\n    echo \"Reload daemon\"\n  else\n\t\techo \"-> Agent is not running in the instance\"\n  fi\n\n  originalSvc=$(systemctl show -p FragmentPath amazon-ssm-agent.service)\n  \n  echo \"Installing agent\"\n  pmOutput=$(rpm -U amazon-ssm-agent.rpm 2>&1)\n  pmExit=$?\n  echo \"RPM Output: $pmOutput\"\n\n  updatedSvc=$(systemctl show -p FragmentPath amazon-ssm-agent.service)\n  if ! [ -z \"$originalSvc\" ] && ! [ -z \"$updatedSvc\" ]; then\n    if ! [ \"$originalSvc\" = \"$updatedSvc\" ]; then\n      echo \"Service file changed\"\n      originalSvc=${originalSvc#*=}\n      updatedSvc=${updatedSvc#*=}\n      SVC_SYMLINK=\"/etc/systemd/system/multi-user.target.wants/amazon-ssm-agent.service\"\n      if [ -f \"$updatedSvc\" ] && [ -L \"$SVC_SYMLINK\" ]; then\n        if ! [ -e \"$SVC_SYMLINK\" ]; then\n          echo \"Found broken symlink\"\n          ln -nfs \"$updatedSvc\" \"$SVC_SYMLINK\"\n        fi\n      fi\n    fi\n  fi\n\n  if [ \"$DO_REGISTER\" = true ]; then\n    systemctl stop amazon-ssm-agent.service\n    amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\n  fi\n\n  agentVersion=$(rpm -q --qf '%{VERSION}\\n' amazon-ssm-agent)\n  echo \"Installed version: '$agentVersion'\"\n\n  echo \"Starting agent\"\n  systemctl daemon-reload\n  systemctl start amazon-ssm-agent.service\n  systemctl status amazon-ssm-agent.service\n\n  if [ \"$pmExit\" -ne 0 ]; then\n    if [[ $pmOutput == *\"is already installed\"* ]]; then\n      echo \"Install was successful\"\n      exit 0\n    fi\n\n    echo \"Package manager failed with exit code '$pmExit'\"\n    echo \"Package manager output: $pmOutput\"\n    exit 125\n  fi\nelse\n  echo \"The amazon-ssm-agent is not supported on this platform. Please visit the documentation for the list of supported platforms\" 1>&2\n  exit 124\nfi\n", "num_lines": 117}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ns3path=$1\n\necho \"Uninstalling Amazon-ssm-agent\"\n\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n\nif [[ $(/sbin/init --version 2> /dev/null) =~ upstart ]]; then\n  echo \"Checking if the agent is installed\"\n  if [ \"$(rpm -q amazon-ssm-agent)\" != \"package amazon-ssm-agent is not installed\" ]; then\n\t\techo \"-> Agent is installed in this instance\"\n\t\techo \"Uninstalling the agent\"\n\t\trpm --erase amazon-ssm-agent\n\t\tsleep 1\n  else\n\t\techo \"-> Agent is not installed in this instance\"\n  fi\nelif [[ $(systemctl 2> /dev/null) =~ -\\.mount ]]; then\n  echo \"Checking if the agent is installed\"\n  if [[ \"$(systemctl status amazon-ssm-agent.service)\" != *\"Loaded: not-found\"* ]]; then\n\t\techo \"-> Agent is installed in this instance\"\n\t\techo \"Uninstalling the agent\"\n\t\trpm --erase amazon-ssm-agent\n\t\tsleep 1\n  else\n\t\techo \"-> Agent is not installed in this instance\"\n  fi\nelse\n  echo \"The amazon-ssm-agent is not supported on this platform. Please visit the documentation for the list of supported platforms\" 1>&2\n  exit 124\nfi", "num_lines": 37}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Installing ubuntu pkg\"\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n\nfunction get_installed_agent_version {\n  dpkg-query -f='${Status}\\t${version}\\n' -W amazon-ssm-agent | grep \"^install ok installed\" | awk -F'\\t' '{print $2}'\n}\n\n# helper function to check if agent is installed\nfunction is_agent_installed {\n  INSTALLED_AGENT_VERSION=`get_installed_agent_version`\n  DEB_AGENT_VERSION=`dpkg -I amazon-ssm-agent.deb | grep '^ Version: ' | awk '{print $2}'`\n\n  if [ -z \"$INSTALLED_AGENT_VERSION\" ]\n  then\n    echo \"Failed to get installed agent version\"\n    # 1 == false\n    return 1\n  fi\n\n  if [ -z \"$DEB_AGENT_VERSION\" ]\n  then\n    echo \"Failed to get deb agent version\"\n    # 1 == false\n    return 1\n  fi\n\n  if [ \"$INSTALLED_AGENT_VERSION\" == \"$DEB_AGENT_VERSION\" ]\n  then\n    echo \"Correct agent version '$INSTALLED_AGENT_VERSION' is installed\"\n    # 0 == true\n    return 0\n  else\n    echo \"Incorrect agent version is installed\"\n    echo \"  Installed agent version: $INSTALLED_AGENT_VERSION\"\n    echo \"  Requested agent version: $DEB_AGENT_VERSION\"\n    # 1 == false\n    return 1\n  fi\n}\n\n# check parameters for registering managed instance\nDO_REGISTER=false\nif [ \"$1\" == \"register-managed-instance\" ]; then\n  if [ $# -eq 4 ]; then\n    DO_REGISTER=true\n    RMI_CODE=$2\n    RMI_ID=$3\n    RMI_REGION=$4\n  else\n    error_exit '[ERROR] Not enough parameters for RegisterManagedInstance.'\n  fi\nfi\n\n# allow ssm-agent to finish it's work\nsleep 2\n\nif [[ \"$(cat /proc/1/comm)\" == \"init\" ]]; then\n  if [ \"$(dpkg -s amazon-ssm-agent | grep 'Status:')\" == \"Status: install ok installed\" ]; then\n    if [ \"$(status amazon-ssm-agent)\" != \"amazon-ssm-agent stop/waiting\" ]; then\n      echo \"-> Agent is running in the instance\"\n      echo \"Stopping the agent\"\n      /sbin/stop amazon-ssm-agent\n      sleep 1\n    fi\n  fi\n\n  echo \"Installing agent\"\n  dpkg -i amazon-ssm-agent.deb\n  pmExit=$?\n\n  agentVersion=$(get_installed_agent_version)\n  echo \"Installed version: '$agentVersion'\"\n\n  if [ \"$DO_REGISTER\" = true ]; then\n    /sbin/stop amazon-ssm-agent\n    amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\n  fi\n\n  echo \"Starting agent\"\n  /sbin/start amazon-ssm-agent\n\n  echo \"Status\"\n  status amazon-ssm-agent\n\n  if [ \"$pmExit\" -ne 0 ]; then\n    echo \"Package manager failed with exit code '$pmExit'\"\n\n    if is_agent_installed; then\n      echo \"The agent installed successfully\"\n      exit 0\n    fi\n\n    exit 125\n  fi\n\nelif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n  if [[ \"$(systemctl is-active amazon-ssm-agent.service)\" == \"active\" ]]; then\n    echo \"-> Agent is running in the instance\"\n    systemctl stop amazon-ssm-agent.service\n    echo \"Agent stopped\"\n    systemctl daemon-reload\n    echo \"Reload daemon\"\n  else\n    echo \"-> Agent is not running on the instance.\"\n  fi\n\n  echo \"Installing agent\"\n  dpkg -i amazon-ssm-agent.deb\n  pmExit=$?\n\n  if [ \"$DO_REGISTER\" = true ]; then\n    systemctl stop amazon-ssm-agent.service\n    amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\n  fi\n\n  agentVersion=$(get_installed_agent_version)\n  echo \"Installed version: '$agentVersion'\"\n\n  echo \"Starting agent\"\n  systemctl daemon-reload\n  systemctl start amazon-ssm-agent.service\n\n  echo \"Status\"\n  systemctl status amazon-ssm-agent.service\n\n  if [ \"$pmExit\" -ne 0 ]; then\n    echo \"Package manager failed with exit code '$pmExit'\"\n\n    if is_agent_installed; then\n      echo \"The agent installed successfully\"\n      exit 0\n    fi\n\n    exit 125\n  fi\n\nelse\n    echo \"The amazon-ssm-agent is not supported on this platform. Please visit the documentation for the list of supported platforms\" 1>&2\n    exit 124\nfi", "num_lines": 147}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n \necho \"Installing snap package\"\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n \n# check parameters for registering managed instance\nDO_REGISTER=false\nif [ \"$1\" == \"register-managed-instance\" ]; then\n  if [ $# -eq 4 ]; then\n\t\tDO_REGISTER=true\n\t\tRMI_CODE=$2\n\t\tRMI_ID=$3\n\t\tRMI_REGION=$4\n  else\n\t\terror_exit '[ERROR] Not enough parameters for RegisterManagedInstance.'\n  fi\nfi\n\nif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n \n  if [[ \"$(systemctl is-active snap.amazon-ssm-agent.amazon-ssm-agent.service)\" == \"active\" ]]; then\n    echo \"detected snap amazon-ssm-agent running on the system, installing new snaps...\"\n    # stop the current agent\n    systemctl stop snap.amazon-ssm-agent.amazon-ssm-agent.service\n    echo 'SSM Agent uninstalled'\n  else\n    echo \"-> Agent is not running in the instance \"\n  fi\n\n  if [[ ! -f amazon-ssm-agent.snap || ! -f amazon-ssm-agent.assert ]]; then\n    echo '[ERROR] Snap is not available for this version. Please uninstall the snap and install a debian if this agent version is required.'\n    exit 1\n  fi\n\n  # acknowledge the signature pulled from the s3 distro\n  snap ack amazon-ssm-agent.assert\n  # install snap in classic mode\n  echo 'installing snap'\n  snap install --classic amazon-ssm-agent.snap\n  pmExit=$?\n\n  # register onprem instance\n  if [ \"$DO_REGISTER\" = true ]; then\n    snap stop amazon-ssm-agent\n    SNAP_BIN=/snap/amazon-ssm-agent/current\n    \"$SNAP_BIN\"/amazon-ssm-agent -register -code \"$RMI_CODE\" -id \"$RMI_ID\" -region \"$RMI_REGION\"\n  fi\n\n  echo \"Starting agent...\"\n  snap start amazon-ssm-agent\n\n  if [ \"$pmExit\" -ne 0 ]; then\n    echo \"Package manager failed with exit code '$pmExit'\"\n    exit 125\n  fi\n\nelse\n  echo '[ERROR] Snap install is not supported on this instance. Please uninstall the snap agent and try again' 1>&2\n  exit 124\nfi\n        \n", "num_lines": 67}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Uninstalling snap pkg\"\n\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n\n# echo \"Checking if the agent is installed\"\n# uninstall the agent if it is present\nif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n  if [[ \"$(systemctl is-active snap.amazon-ssm-agent.amazon-ssm-agent.service)\" == \"active\" ]]; then\n\t\t# echo \"-> Agent is running in the instance\"\n\t\t# echo \"Stopping the agent\"\n\t\tsystemctl stop snap.amazon-ssm-agent.amazon-ssm-agent.service\n\t\techo \"Agent stopped\"\n  else\n\t\techo \"-> Agent is not running in the instance\"\n  fi\nelse\n    echo \"The amazon-ssm-agent is not supported on this platform. Please visit the documentation for the list of supported platforms\" 1>&2\n    exit 124\nfi", "num_lines": 25}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ns3path=$1\n\necho \"Uninstalling deb pkg\"\n\n# helper function to set error output\nfunction error_exit\n{\n  echo \"$1\" 1>&2\n  exit 1\n}\n\n# echo \"Checking if the agent is installed\"\n# uninstall the agent if it is present\nif [[ \"$(cat /proc/1/comm)\" == \"init\" ]]; then\n  if [ \"$(dpkg -s amazon-ssm-agent | grep 'Status:')\" == \"Status: install ok installed\" ]; then\n    if [ \"$(status amazon-ssm-agent)\" != \"amazon-ssm-agent stop/waiting\" ]; then\n      echo \"-> Agent is running in the instance\"\n      # echo \"Stopping the agent\"\n      /sbin/stop amazon-ssm-agent\n      sleep 1\n    else\n      echo \"-> Agent is not running\"\n    fi\n\n    # echo \"Uninstalling the agent\"\n    dpkg -r amazon-ssm-agent\n    sleep 1\n  else\n    echo \"-> Agent is not installed in this instance\"\n  fi\nelif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n  if [[ \"$(systemctl is-active amazon-ssm-agent.service)\" == \"active\" ]]; then\n\t\t# echo \"-> Agent is running in the instance\"\n\t\techo \"Stopping the agent\"\n\t\tsystemctl stop amazon-ssm-agent.service\n\t\tsystemctl daemon-reload\n  else\n\t\techo \"-> Agent is not running in the instance\"\n  fi\n\n  echo \"Uninstalling agent\"\n  dpkg -r amazon-ssm-agent\n\nelse\n  echo \"The amazon-ssm-agent is not supported on this platform. Please visit the documentation for the list of supported platforms\" 1>&2\n  exit 124\nfi", "num_lines": 49}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n\n# Test script checking that all expected os/arch compile properly.\n# Does not actually test the logic, just the compilation so we make sure we don't break code depending on the lib.\n\necho2() {\n    echo $@ >&2\n}\n\ntrap end 0\nend() {\n    [ \"$?\" = 0 ] && echo2 \"Pass.\" || (echo2 \"Fail.\"; exit 1)\n}\n\ncross() {\n    os=$1\n    shift\n    echo2 \"Build for $os.\"\n    for arch in $@; do\n\techo2 \"  - $os/$arch\"\n\tGOOS=$os GOARCH=$arch go build\n    done\n    echo2\n}\n\nset -e\n\ncross linux     amd64 386 arm arm64 ppc64 ppc64le s390x mips mipsle mips64 mips64le\ncross darwin    amd64 386 arm arm64\ncross freebsd   amd64 386 arm\ncross netbsd    amd64 386 arm\ncross openbsd   amd64 386 arm arm64\ncross dragonfly amd64\ncross solaris   amd64\n\n# Not expected to work but should still compile.\ncross windows amd64 386 arm\n\n# TODO: Fix compilation error on openbsd/arm.\n# TODO: Merge the solaris PR.\n\n# Some os/arch require a different compiler. Run in docker.\nif ! hash docker; then\n    # If docker is not present, stop here.\n    return\nfi\n\necho2 \"Build for linux.\"\necho2 \"  - linux/riscv\"\ndocker build -t test -f Dockerfile.riscv .\n", "num_lines": 51}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\nset -euo pipefail\n\ncd \"$(git rev-parse --show-toplevel)\"\n\nSTD_PATH=src/crypto/ed25519/internal/edwards25519/field\nLOCAL_PATH=curve25519/internal/field\nLAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint)\n\ngit fetch https://go.googlesource.com/go master\n\nif git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then\n    echo \"No changes.\"\nelse\n    NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint)\n    echo \"Applying changes from $LAST_SYNC_REF to $NEW_REF...\"\n    git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \\\n        git apply -3 --directory=$LOCAL_PATH\nfi\n", "num_lines": 20}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <netinet/udp.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 782}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "amazon-ssm-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "amazon-ssm-agent-selinux", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh -e\n\nDIRNAME=`dirname $0`\ncd $DIRNAME\nUSAGE=\"$0 [ --update ]\"\nif [ `id -u` != 0 ]; then\necho 'You must be root to run this script'\nexit 1\nfi\n\nif [ $# -eq 1 ]; then\n\tif [ \"$1\" = \"--update\" ] ; then\n\t\ttime=`ls -l --time-style=\"+%x %X\" amazon_ssm_agent.te | awk '{ printf \"%s %s\", $6, $7 }'`\n\t\trules=`ausearch --start $time -m avc --raw -se amazon_ssm_agent`\n\t\tif [ x\"$rules\" != \"x\" ] ; then\n\t\t\techo \"Found avc's to update policy with\"\n\t\t\techo -e \"$rules\" | audit2allow -R\n\t\t\techo \"Do you want these changes added to policy [y/n]?\"\n\t\t\tread ANS\n\t\t\tif [ \"$ANS\" = \"y\" -o \"$ANS\" = \"Y\" ] ; then\n\t\t\t\techo \"Updating policy\"\n\t\t\t\techo -e \"$rules\" | audit2allow -R >> amazon_ssm_agent.te\n\t\t\t\t# Fall though and rebuild policy\n\t\t\telse\n\t\t\t\texit 0\n\t\t\tfi\n\t\telse\n\t\t\techo \"No new avcs found\"\n\t\t\texit 0\n\t\tfi\n\telse\n\t\techo -e $USAGE\n\t\texit 1\n\tfi\nelif [ $# -ge 2 ] ; then\n\techo -e $USAGE\n\texit 1\nfi\n\necho \"Building and Loading Policy\"\nset -x\nmake -f /usr/share/selinux/devel/Makefile amazon_ssm_agent.pp || exit\n/usr/sbin/semodule -i amazon_ssm_agent.pp\n\n# Generate a man page off the installed module\nsepolicy manpage -p . -d amazon_ssm_agent_t\n# Fixing the file context on /usr/bin/amazon-ssm-agent\n/sbin/restorecon -F -R -v /usr/bin/amazon-ssm-agent\n# Fixing the file context on /var/lib/amazon/ssm\n/sbin/restorecon -F -R -v /var/lib/amazon/ssm\n# Fixing the file context on /var/log/amazon/ssm\n/sbin/restorecon -F -R -v /var/log/amazon/ssm\n# Fixing the file context on /var/lib/amazon/ssm/ipc/termination\n/sbin/restorecon -R -v /var/lib/amazon/ssm/ipc/termination\n# Fixing the file context on /usr/bin/ssm-session-worker\n/sbin/restorecon -R -v /usr/bin/ssm-session-worker\n# Fixing the file context on /usr/lib/systemd/system/amazon-ssm-agent.service\n/sbin/restorecon -F -R -v /usr/lib/systemd/system/amazon-ssm-agent.service\n# # Generate a rpm package for the newly generated policy\n\npwd=$(pwd)\nrpmbuild --define \"_sourcedir ${pwd}\" --define \"_specdir ${pwd}\" --define \"_builddir ${pwd}\" --define \"_srcrpmdir ${pwd}\" --define \"_rpmdir ${pwd}\" --define \"_buildrootdir ${pwd}/.build\"  -ba amazon_ssm_agent_selinux.spec\n", "num_lines": 63}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\n\nPLATFORM=$(uname | tr '[:upper:]' '[:lower:]')\nHELM_VERSION=\"3.11.0\"\nNAMESPACE=\"kube-system\"\n\nMAKEFILEPATH=$SCRIPTPATH/../Makefile\nVERSION=$(make -s -f $MAKEFILEPATH version)\nBUILD_DIR=$SCRIPTPATH/../build/cni-rel-yamls/$VERSION\n\nREGIONS_FILE=$SCRIPTPATH/../charts/regions.json\nCNI_RESOURCES_YAML=$BUILD_DIR/aws-k8s-cni\nMETRICS_RESOURCES_YAML=$BUILD_DIR/cni-metrics-helper\n\nmkdir -p $BUILD_DIR\n\nUSAGE=$(cat << 'EOM'\n  Usage: generate-cni-yaml  [-n <K8s_NAMESPACE>]\n  Generates the kubernetes yaml resource files from the helm chart\n  and places them into the build dir.\n  Example: generate-cni-yaml -n kube-system\n          Optional:\n            -n          Kubernetes namespace\nEOM\n)\n\n# Process our input arguments\nwhile getopts \"vn:\" opt; do\n  case ${opt} in\n    n ) # K8s namespace\n        NAMESPACE=$OPTARG\n      ;;\n    v ) # Verbose\n        set -x\n      ;;\n    \\? )\n        echo \"$USAGE\" 1>&2\n        exit\n      ;;\n  esac\ndone\n\ncurl -L https://get.helm.sh/helm-v$HELM_VERSION-$PLATFORM-amd64.tar.gz | tar zxf - -C $BUILD_DIR\nmv $BUILD_DIR/$PLATFORM-amd64/helm $BUILD_DIR/.\nrm -rf $BUILD_DIR/$PLATFORM-amd64\nchmod +x $BUILD_DIR/helm\n\njq -c '.[]' $REGIONS_FILE | while read i; do\n    ecrRegion=`echo $i | jq '.ecrRegion' -r`\n    ecrAccount=`echo $i | jq '.ecrAccount' -r`\n    ecrDomain=`echo $i | jq '.ecrDomain' -r`\n    if [ \"$ecrRegion\" = \"us-west-2\" ]; then\n        NEW_CNI_RESOURCES_YAML=\"${CNI_RESOURCES_YAML}.yaml\"\n        NEW_METRICS_RESOURCES_YAML=\"${METRICS_RESOURCES_YAML}.yaml\"\n    elif [ \"$ecrRegion\" = \"cn-northwest-1\" ]; then\n        NEW_CNI_RESOURCES_YAML=\"${CNI_RESOURCES_YAML}-cn.yaml\"\n        NEW_METRICS_RESOURCES_YAML=\"${METRICS_RESOURCES_YAML}-cn.yaml\"\n    else\n        NEW_CNI_RESOURCES_YAML=\"${CNI_RESOURCES_YAML}-${ecrRegion}.yaml\"\n        NEW_METRICS_RESOURCES_YAML=\"${METRICS_RESOURCES_YAML}-${ecrRegion}.yaml\"\n    fi\n\n    $BUILD_DIR/helm template aws-vpc-cni \\\n      --include-crds \\\n      --set originalMatchLabels=true,\\\n      --set init.image.region=$ecrRegion,\\\n      --set init.image.account=$ecrAccount,\\\n      --set init.image.domain=$ecrDomain,\\\n      --set init.image.tag=$VERSION,\\\n      --set image.tag=$VERSION,\\\n      --set image.region=$ecrRegion,\\\n      --set image.account=$ecrAccount,\\\n      --set image.domain=$ecrDomain \\\n      --namespace $NAMESPACE \\\n      $SCRIPTPATH/../charts/aws-vpc-cni > $NEW_CNI_RESOURCES_YAML\n    # Remove 'managed-by: Helm' annotation\n    sed -i '/helm.sh\\|app.kubernetes.io\\/managed-by: Helm/d' $NEW_CNI_RESOURCES_YAML\n\n    $BUILD_DIR/helm template cni-metrics-helper \\\n      --set image.region=$ecrRegion,\\\n      --set image.account=$ecrAccount,\\\n      --set image.domain=$ecrDomain \\\n      --set image.tag=$VERSION,\\\n      --namespace $NAMESPACE \\\n      $SCRIPTPATH/../charts/cni-metrics-helper > $NEW_METRICS_RESOURCES_YAML\n    # Remove 'managed-by: Helm' annotation\n    sed -i '/helm.sh\\|app.kubernetes.io\\/managed-by: Helm/d' $NEW_METRICS_RESOURCES_YAML\ndone\n\ncd $SCRIPTPATH\n\necho \"Generated aws-vpc-cni and cni-metrics-helper manifest resources files in:\"\necho \"    - $CNI_RESOURCES_YAML\"\necho \"    - $METRICS_RESOURCES_YAML\"\n", "num_lines": 98}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The script runs amazon-vpc-cni Canary tests on the default\n# addon version and then runs smoke test on the latest addon version.\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nGINKGO_TEST_BUILD=\"$SCRIPT_DIR/../test/build\"\n# TEST_IMAGE_REGISTRY is the registry in test-infra-* accounts where e2e test images are stored\nTEST_IMAGE_REGISTRY=${TEST_IMAGE_REGISTRY:-\"617930562442.dkr.ecr.us-west-2.amazonaws.com\"}\nADC_REGIONS=\"us-iso-east-1 us-isob-east-1 us-iso-west-1\"\n\nsource \"$SCRIPT_DIR\"/lib/add-on.sh\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/canary.sh\n\nfunction run_ginkgo_test() {\n  local focus=$1\n  echo \"Running ginkgo tests with focus: $focus\"\n  (CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS --no-color --focus=\"$focus\" -v --timeout 30m --fail-on-pending $GINKGO_TEST_BUILD/cni.test -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\" --test-image-registry=$TEST_IMAGE_REGISTRY)\n  (CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS --no-color --focus=\"$focus\" -v --timeout 30m --fail-on-pending $GINKGO_TEST_BUILD/ipamd.test -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\" --test-image-registry=$TEST_IMAGE_REGISTRY)\n}\n\nload_cluster_details\nload_addon_details\n\n# Run more comprehensive test on the default addon version. CANARY focused tests\n# cover basic functionlity plus test that could detect issues with dependencies\n# early on.\necho \"Running Canary tests on the default addon version\"\ninstall_add_on \"$DEFAULT_ADDON_VERSION\"\nrun_ginkgo_test \"CANARY\"\n\n# Run smoke test on the latest addon version. Smoke tests consist of a subset of tests\n# from Canary suite.\n# skip the latest addon version for ADC regions\nif [[ $ADC_REGIONS == *\"$REGION\"* ]]; then\n  echo \"Skipping Smoke tests on the latest addon version\"\nelse\n  echo \"Running Smoke tests on the latest addon version\"\n  install_add_on \"$LATEST_ADDON_VERSION\"\n  run_ginkgo_test \"SMOKE\"\nfi\n\necho \"all tests ran successfully in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 47}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# script to run integration tests (no cluster creation & deletion/installing addons)\n# use case: run script after CNI images are updated to the image to be verified (see update-cni-images.sh)\n\n# CLUSTER_NAME: name of the cluster to run the test\n# VPC_ID: cluster VPC ID\n# REGION: default us-west-2\n# KUBE_CONFIG_PATH: path to the kubeconfig file, default ~/.kube/config\n# NG_LABEL_KEY: nodegroup label key, default \"kubernetes.io/os\"\n# NG_LABEL_VAL: nodegroup label val, default \"linux\"\n# RUN_DEVEKS_TEST: Set this variable for tests to run on a deveks cluster\n# CNI_METRICS_HELPER: cni metrics helper image tag, default \"602401143452.dkr.ecr.us-west-2.amazonaws.com/cni-metrics-helper:v1.13.0\"\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nINTEGRATION_TEST_DIR=\"$SCRIPT_DIR/../test/integration\"\n\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/integration.sh\n\nfunction run_integration_test() {\n  : \"${NG_LABEL_KEY:=kubernetes.io/os}\"\n  : \"${NG_LABEL_VAL:=linux}\"\n  TEST_RESULT=success\n\n  echo \"Running ipamd integration tests\"\n  START=$SECONDS\n  # NOTE: skipping ipamd_event_test.go until it can be triaged further\n  cd $INTEGRATION_TEST_DIR/ipamd && CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS --skip-file=ipamd_event_test.go -v -timeout 90m --no-color --fail-on-pending -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"$NG_LABEL_KEY\" --ng-name-label-val=\"$NG_LABEL_VAL\" || TEST_RESULT=fail\n  echo \"ipamd test took $((SECONDS - START)) seconds.\"\n\n  echo \"Running cni integration tests\"\n  START=$SECONDS\n  cd $INTEGRATION_TEST_DIR/cni && CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS -v -timeout 60m --no-color --fail-on-pending -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"$NG_LABEL_KEY\" --ng-name-label-val=\"$NG_LABEL_VAL\" || TEST_RESULT=fail\n  echo \"cni test took $((SECONDS - START)) seconds.\"\n\n  : \"${CNI_METRICS_HELPER:=602401143452.dkr.ecr.us-west-2.amazonaws.com/cni-metrics-helper:v1.13.0}\"\n  REPO_NAME=$(echo $CNI_METRICS_HELPER | cut -d \":\" -f 1)\n  TAG=$(echo $CNI_METRICS_HELPER | cut -d \":\" -f 2)\n  echo \"Running cni-metrics-helper image($CNI_METRICS_HELPER) tests\"\n  START=$SECONDS\n  cd $INTEGRATION_TEST_DIR/metrics-helper && CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS -v -timeout 15m --no-color --fail-on-pending -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"$NG_LABEL_KEY\" --ng-name-label-val=\"$NG_LABEL_VAL\" --cni-metrics-helper-image-repo=$REPO_NAME --cni-metrics-helper-image-tag=$TAG || TEST_RESULT=fail\n  echo \"cni-metrics-helper test took $((SECONDS - START)) seconds.\"\n  if [[ \"$TEST_RESULT\" == fail ]]; then\n      echo \"Integration test failed.\"\n      exit 1\n  fi\n  echo \"Integration tests completed successfully!\"\n}\n\nif [[ -n \"${ENDPOINT}\" ]]; then\n  ENDPOINT_FLAG=\"--endpoint $ENDPOINT\"\nfi\n\necho \"Running release tests on cluster: $CLUSTER_NAME in region: $REGION\"\n\nif [[ -z $RUN_DEVEKS_TEST ]]; then\n  load_cluster_details\nelse\n  load_deveks_cluster_details\nfi\n\nSTART=$SECONDS\nrun_integration_test\n\necho \"Completed running all tests in $((SECONDS - START)) seconds.\"\n", "num_lines": 69}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script can be used to run any ginkgo integration suite using SUITE_NAME environment variable.\n# Prerequisite: cluster with at least three Linux nodes must already exist.\n# It is up to the caller to ensure that tests are valid to run against cluster, i.e. IPv6 tests require IPv6 cluster.\n# Set appropriate optional args for running test suite\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nGINKGO_TEST_BUILD=\"$SCRIPT_DIR/../test/build\"\nSKIP_MAKE_TEST_BINARIES=1\n\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/canary.sh\n\nfunction load_test_parameters(){\n\n  EXTRA_OPTIONS=\"\"\n  if [[ ! -z $INITIAL_ADDON_VERSION ]]; then\n    EXTRA_OPTIONS+=\" --initial-addon-version $INITIAL_ADDON_VERSION\"\n  fi\n\n  if [[ ! -z $TARGET_ADDON_VERSION ]]; then\n    EXTRA_OPTIONS+=\" --target-addon-version $TARGET_ADDON_VERSION\"\n  fi\n\n  if [[ ! -z $INITIAL_MANIFEST_FILE ]]; then\n    EXTRA_OPTIONS+=\" --initial-manifest-file $INITIAL_MANIFEST_FILE\"\n  fi\n\n  if [[ ! -z $TARGET_MANIFEST_FILE ]]; then\n    EXTRA_OPTIONS+=\" --target-manifest-file $TARGET_MANIFEST_FILE\"\n  fi\n\n}\n\nfunction run_ginkgo_test() {\n  (CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS -v --timeout 60m --no-color --fail-on-pending $GINKGO_TEST_BUILD/$SUITE_NAME.test -- \\\n    --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" \\\n    --cluster-name=\"$CLUSTER_NAME\" \\\n    --aws-region=\"$REGION\" \\\n    --aws-vpc-id=\"$VPC_ID\" \\\n    --ng-name-label-key=\"kubernetes.io/os\" \\\n    --ng-name-label-val=\"linux\" \\\n    $ENDPOINT_OPTION $EXTRA_OPTIONS\n  )\n}\n\nload_cluster_details\n\nload_test_parameters\n\necho \"Running $SUITE_NAME integration tests\"\n\nrun_ginkgo_test\n\necho \"all tests ran successfully in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 59}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -Euo pipefail\n\ntrap 'on_error $? $LINENO' ERR\n\nDIR=$(cd \"$(dirname \"$0\")\"; pwd)\nINTEGRATION_TEST_DIR=\"$DIR\"/../test/integration\n\nsource \"$DIR\"/lib/common.sh\nsource \"$DIR\"/lib/aws.sh\nsource \"$DIR\"/lib/cluster.sh\nsource \"$DIR\"/lib/integration.sh\nsource \"$DIR\"/lib/k8s.sh\nsource \"$DIR\"/lib/performance_tests.sh\n\n# Variables used in /lib/aws.sh\nOS=$(go env GOOS)\nARCH=$(go env GOARCH)\n\n: \"${AWS_DEFAULT_REGION:=us-west-2}\"\n: \"${K8S_VERSION:=1.25.7}\"\n: \"${EKS_CLUSTER_VERSION:=1.25}\"\n: \"${PROVISION:=true}\"\n: \"${DEPROVISION:=true}\"\n: \"${BUILD:=true}\"\n: \"${RUN_CONFORMANCE:=false}\"\n: \"${RUN_TESTER_LB_ADDONS:=false}\"\n: \"${RUN_KOPS_TEST:=false}\"\n: \"${RUN_BOTTLEROCKET_TEST:=false}\"\n: \"${RUN_PERFORMANCE_TESTS:=false}\"\n: \"${RUNNING_PERFORMANCE:=false}\"\n: \"${RUN_CALICO_TEST:=false}\"\n: \"${RUN_LATEST_CALICO_VERSION:=false}\"\n: \"${CALICO_VERSION:=v3.25.0}\"\n: \"${RUN_CALICO_TEST_WITH_PD:=true}\"\n: \"${KOPS_VERSION=v1.26.4}\"\n\n__cluster_created=0\n__cluster_deprovisioned=0\n\non_error() {\n    echo \"Error with exit code $1 occurred on line $2\"\n    emit_cloudwatch_metric \"error_occurred\" \"1\"\n\n    #Emit test specific error metric \n    if [[ $RUN_KOPS_TEST == true ]]; then\n        emit_cloudwatch_metric \"kops_test_status\" \"0\"\n    fi\n    if [[ $RUN_CALICO_TEST == true ]]; then\n        emit_cloudwatch_metric \"calico_test_status\" \"0\"\n    fi\n    if [[ $RUN_BOTTLEROCKET_TEST == true ]]; then\n        emit_cloudwatch_metric \"bottlerocket_test_status\" \"0\"\n    fi\n    if [[ $RUN_PERFORMANCE_TESTS == true ]]; then\n        emit_cloudwatch_metric \"performance_test_status\" \"0\"\n    fi\n    # Make sure we destroy any cluster that was created if we hit run into an\n    # error when attempting to run tests against the \n    if [[ $RUNNING_PERFORMANCE == false ]]; then\n        if [[ $__cluster_created -eq 1 && $__cluster_deprovisioned -eq 0 && \"$DEPROVISION\" == true ]]; then\n            # prevent double-deprovisioning with ctrl-c during deprovisioning...\n            __cluster_deprovisioned=1\n            echo \"Cluster was provisioned already. Deprovisioning it...\"\n            if [[ $RUN_KOPS_TEST == true ]]; then\n                down-kops-cluster\n            else\n                down-test-cluster\n            fi\n        fi\n        exit 1\n    fi\n}\n\n# test specific config, results location\n: \"${TEST_ID:=$RANDOM}\"\n: \"${TEST_BASE_DIR:=${DIR}/cni-test}\"\nTEST_DIR=${TEST_BASE_DIR}/$(date \"+%Y%M%d%H%M%S\")-$TEST_ID\nREPORT_DIR=${TEST_DIR}/report\nTEST_CONFIG_DIR=\"$TEST_DIR/config\"\n\n# test cluster config location\n# Pass in CLUSTER_ID to reuse a test cluster\n: \"${CLUSTER_ID:=$RANDOM}\"\nCLUSTER_NAME=cni-test-$CLUSTER_ID\nTEST_CLUSTER_DIR=${TEST_BASE_DIR}/cluster-$CLUSTER_NAME\nCLUSTER_MANAGE_LOG_PATH=$TEST_CLUSTER_DIR/cluster-manage.log\n: \"${CLUSTER_CONFIG:=${TEST_CLUSTER_DIR}/${CLUSTER_NAME}.yaml}\"\n: \"${KUBECONFIG_PATH:=${TEST_CLUSTER_DIR}/kubeconfig}\"\n\n# shared binaries\n: \"${TESTER_DIR:=${DIR}/aws-k8s-tester}\"\n: \"${TESTER_PATH:=$TESTER_DIR/aws-k8s-tester}\"\n: \"${KUBECTL_PATH:=kubectl}\"\nexport PATH=${PATH}:$TESTER_DIR\n\nLOCAL_GIT_VERSION=$(git rev-parse HEAD)\necho \"Testing git repository at commit $LOCAL_GIT_VERSION\"\nTEST_IMAGE_VERSION=${IMAGE_VERSION:-$LOCAL_GIT_VERSION}\n# We perform an upgrade to this manifest, with image replaced\n: \"${MANIFEST_CNI_VERSION:=master}\"\nBASE_CONFIG_PATH=\"$DIR/../config/$MANIFEST_CNI_VERSION/aws-k8s-cni.yaml\"\nTEST_CONFIG_PATH=\"$TEST_CONFIG_DIR/aws-k8s-cni.yaml\"\n# The manifest image version is the image tag we need to replace in the\n# aws-k8s-cni.yaml manifest\nMANIFEST_IMAGE_VERSION=`grep \"image:\" $BASE_CONFIG_PATH | cut -d \":\" -f3 | cut -d \"\\\"\" -f1 | head -1`\n\nif [[ ! -f \"$BASE_CONFIG_PATH\" ]]; then\n    echo \"$BASE_CONFIG_PATH DOES NOT exist. Set \\$MANIFEST_CNI_VERSION to an existing directory in ./config/\"\n    exit\nfi\n\n# double-check all our preconditions and requirements have been met\ncheck_is_installed ginkgo\ncheck_is_installed docker\ncheck_is_installed aws\ncheck_aws_credentials\n\n: \"${AWS_ACCOUNT_ID:=$(aws sts get-caller-identity --query Account --output text)}\"\n: \"${AWS_ECR_REGISTRY:=\"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com\"}\"\n: \"${AWS_ECR_REPO_NAME:=\"amazon-k8s-cni\"}\"\n: \"${IMAGE_NAME:=\"$AWS_ECR_REGISTRY/$AWS_ECR_REPO_NAME\"}\"\n: \"${AWS_INIT_ECR_REPO_NAME:=\"amazon-k8s-cni-init\"}\"\n: \"${INIT_IMAGE_NAME:=\"$AWS_ECR_REGISTRY/$AWS_INIT_ECR_REPO_NAME\"}\"\n: \"${ROLE_CREATE:=true}\"\n: \"${ROLE_ARN:=\"\"}\"\n: \"${MNG_ROLE_ARN:=\"\"}\"\n: \"${BUILDX_BUILDER:=\"multi-arch-image-builder\"}\"\n\n# S3 bucket initialization\n: \"${S3_BUCKET_CREATE:=true}\"\n: \"${S3_BUCKET_NAME:=\"\"}\"\n\necho \"Logging in to docker repo\"\naws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin ${AWS_ECR_REGISTRY}\nensure_ecr_repo \"$AWS_ACCOUNT_ID\" \"$AWS_ECR_REPO_NAME\"\nensure_ecr_repo \"$AWS_ACCOUNT_ID\" \"$AWS_INIT_ECR_REPO_NAME\"\n\n# Check to see if the image already exists in the ECR repository, and if\n# not, check out the CNI source code for that image tag, build the CNI\n# image and push it to the Docker repository\n\nCNI_IMAGES_BUILD=false\nif [[ $(aws ecr batch-get-image --repository-name=$AWS_ECR_REPO_NAME --image-ids imageTag=$TEST_IMAGE_VERSION \\\n--query 'images[].imageId.imageTag' --region us-west-2) != \"[]\" ]]; then\n    echo \"Image $AWS_ECR_REPO_NAME:$TEST_IMAGE_VERSION already exists. Skipping image build.\"\nelse\n    echo \"Image $AWS_ECR_REPO_NAME:$TEST_IMAGE_VERSION does not exist in repository.\"\n    ## $1=command, $2=args\n    build_and_push_image \"multi-arch-cni-build-push\" \"IMAGE=$IMAGE_NAME VERSION=$TEST_IMAGE_VERSION\"\n    CNI_IMAGES_BUILD=true\nfi\n\nif [[ $(aws ecr batch-get-image --repository-name=$AWS_INIT_ECR_REPO_NAME --image-ids imageTag=$TEST_IMAGE_VERSION \\\n--query 'images[].imageId.imageTag' --region us-west-2) != \"[]\" ]]; then\n    echo \"Image $AWS_INIT_ECR_REPO_NAME:$TEST_IMAGE_VERSION already exists. Skipping image build.\"\nelse\n    echo \"Image $AWS_INIT_ECR_REPO_NAME:$TEST_IMAGE_VERSION does not exist in repository.\"\n    ## $1=command, $2=args\n    build_and_push_image \"multi-arch-cni-init-build-push\" \"INIT_IMAGE=$INIT_IMAGE_NAME VERSION=$TEST_IMAGE_VERSION\"\n    CNI_IMAGES_BUILD=true\nfi\n\n# cleanup if we make docker build and push images\nif [[ \"$CNI_IMAGES_BUILD\" == true ]]; then\n    docker buildx rm \"$BUILDX_BUILDER\"\n    if [[ $TEST_IMAGE_VERSION != \"$LOCAL_GIT_VERSION\" ]]; then\n        popd\n    fi\nfi\n\necho \"*******************************************************************************\"\necho \"Running $TEST_ID on $CLUSTER_NAME in $AWS_DEFAULT_REGION\"\necho \"+ Cluster config dir: $TEST_CLUSTER_DIR\"\necho \"+ Result dir:         $TEST_DIR\"\necho \"+ Tester:             $TESTER_PATH\"\necho \"+ Kubeconfig:         $KUBECONFIG_PATH\"\necho \"+ Cluster config:     $CLUSTER_CONFIG\"\necho \"+ AWS Account ID:     $AWS_ACCOUNT_ID\"\necho \"+ CNI image to test:  $IMAGE_NAME:$TEST_IMAGE_VERSION\"\necho \"+ CNI init container: $INIT_IMAGE_NAME:$TEST_IMAGE_VERSION\"\n\nmkdir -p \"$TEST_DIR\"\nmkdir -p \"$REPORT_DIR\"\nmkdir -p \"$TEST_CLUSTER_DIR\"\nmkdir -p \"$TEST_CONFIG_DIR\"\n\nSTART=$SECONDS\nif [[ \"$PROVISION\" == true ]]; then\n    START=$SECONDS\n    if [[ \"$RUN_KOPS_TEST\" == true ]]; then\n        up-kops-cluster\n    else\n        up-test-cluster\n    fi\nfi\n__cluster_created=1\n\nUP_CLUSTER_DURATION=$((SECONDS - START))\necho \"TIMELINE: Upping test cluster took $UP_CLUSTER_DURATION seconds.\"\n\n# Fetch VPC_ID from created cluster\nif [[ \"$RUN_KOPS_TEST\" == true ]]; then\n    INSTANCE_ID=$(kubectl get nodes -l node-role.kubernetes.io/node -o jsonpath='{range .items[*]}{@.metadata.name}{\"\\n\"}' | head -1)\n    VPC_ID=$(aws ec2 describe-instances --instance-ids \"$INSTANCE_ID\" --no-cli-pager | jq -r '.Reservations[].Instances[].VpcId' )\nelse\n    DESCRIBE_CLUSTER_OP=$(aws eks describe-cluster --name \"$CLUSTER_NAME\" --region \"$AWS_DEFAULT_REGION\")\n    VPC_ID=$(echo \"$DESCRIBE_CLUSTER_OP\" | jq -r '.cluster.resourcesVpcConfig.vpcId')\nfi\n\necho \"Using VPC_ID: $VPC_ID\"\n\necho \"Using $BASE_CONFIG_PATH as a template\"\ncp \"$BASE_CONFIG_PATH\" \"$TEST_CONFIG_PATH\"\n\n# Daemonset template\n# Replace image value and tag in cni manifest and grep (to verify that replacement was successful)\necho \"IMAGE NAME ${IMAGE_NAME} \"\nsed -i'.bak' \"s,602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon-k8s-cni,$IMAGE_NAME,\" \"$TEST_CONFIG_PATH\"\ngrep -r -q $IMAGE_NAME $TEST_CONFIG_PATH\necho \"Replacing manifest image tag $MANIFEST_IMAGE_VERSION with image version of $TEST_IMAGE_VERSION\"\nsed -i'.bak' \"s,:$MANIFEST_IMAGE_VERSION,:$TEST_IMAGE_VERSION,\" \"$TEST_CONFIG_PATH\"\ngrep -r -q $TEST_IMAGE_VERSION $TEST_CONFIG_PATH\nsed -i'.bak' \"s,602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon-k8s-cni-init,$INIT_IMAGE_NAME,\" \"$TEST_CONFIG_PATH\"\ngrep -r -q $INIT_IMAGE_NAME $TEST_CONFIG_PATH\n\necho \"*******************************************************************************\"\necho \"Updating CNI to image $IMAGE_NAME:$TEST_IMAGE_VERSION\"\necho \"Updating CNI-INIT to image $INIT_IMAGE_NAME:$TEST_IMAGE_VERSION\"\nSTART=$SECONDS\n$KUBECTL_PATH apply -f \"$TEST_CONFIG_PATH\"\ncheck_ds_rollout \"aws-node\" \"kube-system\" \"10m\"\n\nCNI_IMAGE_UPDATE_DURATION=$((SECONDS - START))\necho \"TIMELINE: Updating CNI image took $CNI_IMAGE_UPDATE_DURATION seconds.\"\n\necho \"*******************************************************************************\"\necho \"Running integration tests against current image\"\necho \"\"\nSTART=$SECONDS\n\nfocus=\"CANARY\"\necho \"Running ginkgo tests with focus: $focus\"\n(cd \"$INTEGRATION_TEST_DIR/cni\" && CGO_ENABLED=0 ginkgo --focus=\"$focus\" -v --timeout 60m --no-color --fail-on-pending -- --cluster-kubeconfig=\"$KUBECONFIG\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$AWS_DEFAULT_REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\")\n(cd \"$INTEGRATION_TEST_DIR/ipamd\" && CGO_ENABLED=0 ginkgo --focus=\"$focus\" -v --timeout 60m --no-color --fail-on-pending -- --cluster-kubeconfig=\"$KUBECONFIG\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$AWS_DEFAULT_REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\")\nTEST_PASS=$?\nCURRENT_IMAGE_INTEGRATION_DURATION=$((SECONDS - START))\necho \"TIMELINE: Current image integration tests took $CURRENT_IMAGE_INTEGRATION_DURATION seconds.\"\nif [[ $TEST_PASS -eq 0 ]]; then\n  emit_cloudwatch_metric \"integration_test_status\" \"1\"\nfi\n\nif [[ $RUN_CALICO_TEST == true ]]; then\n  # need to install Calico\n  run_calico_test \"true\"\n  if [[ \"$RUN_CALICO_TEST_WITH_PD\" == true ]]; then\n      # if we run prefix delegation tests as well, we need update CNI env and terminate all nodes to restore iptables rules for following tests\n      echo \"Run Calico tests with Prefix Delegation enabled\"\n      $KUBECTL_PATH set env daemonset aws-node -n kube-system ENABLE_PREFIX_DELEGATION=true\n      # we shouldn't rely on other tests to set this required ENV\n      $KUBECTL_PATH set env ds aws-node -n kube-system WARM_PREFIX_TARGET=1\n      ids=( $(aws ec2 describe-instances --filters Name=vpc-id,Values=$VPC_ID --query 'Reservations[*].Instances[*].InstanceId' --output text) )\n      aws ec2 terminate-instances --instance-ids $ids\n      echo \"Waiting 15 minutes for new nodes being ready\"\n      sleep 900\n      # no longer need to install Calico again for PD\n      run_calico_test \"false\"\n  fi\n\n  emit_cloudwatch_metric \"calico_test_status\" \"1\"\nfi\n\nif [[ $TEST_PASS -eq 0 && \"$RUN_CONFORMANCE\" == true ]]; then\n  echo \"Running conformance tests against cluster.\"\n  START=$SECONDS\n\n  GOPATH=$(go env GOPATH)\n  echo \"PATH: $PATH\"\n\n  echo \"Downloading kubernetes test from: https://dl.k8s.io/v$K8S_VERSION/kubernetes-test-linux-amd64.tar.gz\"\n  wget -qO- https://dl.k8s.io/v$K8S_VERSION/kubernetes-test-linux-amd64.tar.gz | tar -zxvf - --strip-components=3 -C ${TEST_BASE_DIR}  kubernetes/test/bin/e2e.test\n\n  echo \"Running e2e tests: \"\n  ${TEST_BASE_DIR}/e2e.test --ginkgo.focus=\"\\[Serial\\].*Conformance\" --kubeconfig=$KUBECONFIG --ginkgo.fail-fast --ginkgo.no-color --ginkgo.flake-attempts 2 \\\n    --ginkgo.skip=\"(should support remote command execution over websockets)|(should support retrieving logs from the container over websockets)|\\[Slow\\]\"\n\n  CONFORMANCE_DURATION=$((SECONDS - START))\n  emit_cloudwatch_metric \"conformance_test_status\" \"1\"\n  echo \"TIMELINE: Conformance tests took $CONFORMANCE_DURATION seconds.\"\nfi\n\nif [[ \"$RUN_PERFORMANCE_TESTS\" == true ]]; then\n    echo \"*******************************************************************************\"\n    echo \"Running performance tests on current image:\"\n    echo \"\"\n    START=$SECONDS\n    run_performance_test_130_pods\n    run_performance_test_730_pods\n    run_performance_test_5000_pods\n    PERFORMANCE_DURATION=$((SECONDS - START))\nfi\n\nif [[ $RUN_KOPS_TEST == true ]]; then\n    run_kops_conformance\nfi\n\nif [[ \"$DEPROVISION\" == true ]]; then\n    START=$SECONDS\n\n    if [[ \"$RUN_KOPS_TEST\" == true ]]; then\n        down-kops-cluster\n    elif [[ \"$RUN_BOTTLEROCKET_TEST\" == true ]]; then\n        eksctl delete cluster $CLUSTER_NAME\n        emit_cloudwatch_metric \"bottlerocket_test_status\" \"1\"\n    elif [[ \"$RUN_PERFORMANCE_TESTS\" == true ]]; then\n        eksctl delete cluster $CLUSTER_NAME\n        emit_cloudwatch_metric \"performance_test_status\" \"1\"\n    else\n        down-test-cluster\n    fi\n\n    DOWN_DURATION=$((SECONDS - START))\n    echo \"TIMELINE: Down processes took $DOWN_DURATION seconds.\"\n    display_timelines\nfi\n\nif [[ $TEST_PASS -ne 0 ]]; then\n    exit 1\nfi\nemit_cloudwatch_metric \"error_occurred\" \"0\"\n", "num_lines": 332}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The script runs amazon-vpc-cni IPv6 canary tests\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nGINKGO_TEST_BUILD=\"$SCRIPT_DIR/../test/build\"\n\nsource \"$SCRIPT_DIR\"/lib/add-on.sh\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/canary.sh\n\nfunction run_ginkgo_test() {\n  local focus=$1\n  echo \"Running ginkgo tests with focus: $focus\"\n  (CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS --focus=\"$focus\" -v --timeout 15m --no-color --fail-on-pending $GINKGO_TEST_BUILD/ipv6.test -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\")\n}\n\nload_cluster_details\nload_addon_details\n\necho \"Running IPv6 Canary tests on the latest addon version\"\n\ninstall_add_on \"$LATEST_ADDON_VERSION\"\nrun_ginkgo_test \"CANARY\"\n\necho \"all tests ran successfully in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 29}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The script runs the full IPv6 integration test suite\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nGINKGO_TEST_BUILD=\"$SCRIPT_DIR/../test/build\"\n\nsource \"$SCRIPT_DIR\"/lib/add-on.sh\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/canary.sh\n\nfunction run_ginkgo_test() {\n  (CGO_ENABLED=0 ginkgo $EXTRA_GINKGO_FLAGS -v --timeout 30m --no-color --fail-on-pending $GINKGO_TEST_BUILD/ipv6.test -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\")\n}\n\nload_cluster_details\nload_addon_details\n\necho \"Running IPv6 integration tests against the latest addon version\"\n\ninstall_add_on \"$LATEST_ADDON_VERSION\"\nrun_ginkgo_test\n\necho \"all tests ran successfully in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 27}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The script runs multus tests on the lastest version with latest AWS-VPC-CNI addon version\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nINTEGRATION_TEST_DIR=\"$SCRIPT_DIR/../test/integration\"\n\nsource \"$SCRIPT_DIR\"/lib/common.sh\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\nsource \"$SCRIPT_DIR\"/lib/canary.sh\n\nfunction run_ginkgo_test() {\n  local focus=$1\n  (cd \"$INTEGRATION_TEST_DIR/multus\" && CGO_ENABLED=0 ginkgo --focus=\"$focus\" -v --timeout 20m --fail-on-pending -- --cluster-kubeconfig=\"$KUBE_CONFIG_PATH\" --cluster-name=\"$CLUSTER_NAME\" --aws-region=\"$REGION\" --aws-vpc-id=\"$VPC_ID\" --ng-name-label-key=\"kubernetes.io/os\" --ng-name-label-val=\"linux\")\n}\n\ncheck_is_installed kubectl\ncheck_is_installed ginkgo\n\nload_cluster_details\n\nLATEST_TAG=${1:-v3.8.0-eksbuild.1}\necho \"Installing latest multus manifest with tag: ${LATEST_TAG}\"\n\nkubectl apply -f https://raw.githubusercontent.com/aws/amazon-vpc-cni-k8s/master/config/multus/${LATEST_TAG}/aws-k8s-multus.yaml\n\necho \"Running multus ginkgo tests\"\nrun_ginkgo_test\n\necho \"all tests ran successfully in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 33}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "export RUN_BOTTLEROCKET_TEST=true\nchmod +x ./scripts/run-integration-tests.sh\necho \"Running bottlerocket test\"\n./scripts/run-integration-tests.sh\nunset RUN_BOTTLEROCKET_TEST\n\nexport RUN_WARM_IP_TEST=true\necho \"Running warm ip test\"\n./scripts/run-integration-tests.sh\nunset RUN_WARM_IP_TEST\n\nexport RUN_WARM_ENI_TEST=true\necho \"Running warm eni test\"\n./scripts/run-integration-tests.sh\nunset RUN_WARM_ENI_TEST\n\nexport RUN_CONFORMANCE=false\n\nexport RUN_KOPS_TEST=true\necho \"Running KOPS test\"\n./scripts/run-integration-tests.sh\nunset RUN_KOPS_TEST\n\nexport RUN_CALICO_TEST=true\necho \"Running calico test\"\n./scripts/run-integration-tests.sh\nunset RUN_CALICO_TEST\n", "num_lines": 28}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# script to set the image on aws-node daemonset for running tests\n\n# Usage: Set test images as ENV variables $AMAZON_K8S_CNI & $AMAZON_K8S_CNI_INIT\n# Run script to update aws-node daemonset images\n\nset -e\n\nSCRIPTS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\n\nAWS_K8S_CNI_MANIFEST=\"$SCRIPTS_DIR/../config/master/aws-k8s-cni.yaml\"\nMANIFEST_IMG_VERSION=`grep \"image:\" $AWS_K8S_CNI_MANIFEST | cut -d \":\" -f3 | cut -d \"\\\"\" -f1 | head -1`\n\n# Replace the images in aws-k8s-cni.yaml with the tester images when environment variables are set\nif [[ -z $AMAZON_K8S_CNI ]]; then\n    echo \"Using latest CNI image from aws-k8s-cni manifest\"\nelse\n    echo \"Replacing CNI image in aws-k8s-cni manifest with $AMAZON_K8S_CNI\"\n    sed -i'.bak' \"s,602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon-k8s-cni:$MANIFEST_IMG_VERSION,$AMAZON_K8S_CNI,\" \"$AWS_K8S_CNI_MANIFEST\"\nfi\nif [[ -z $AMAZON_K8S_CNI_INIT ]]; then\n    echo \"Using latest CNI init image from aws-k8s-cni manifest\"\nelse\n    echo \"Replacing CNI init image in aws-k8s-cni manifest with $AMAZON_K8S_CNI_INIT\"\n    sed -i'.bak' \"s,602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon-k8s-cni-init:$MANIFEST_IMG_VERSION,$AMAZON_K8S_CNI_INIT,\" \"$AWS_K8S_CNI_MANIFEST\"\nfi\n\necho \"Applying amazon-vpc-cni-k8s/config/master/aws-k8s-cni.yaml manifest\"\nkubectl apply -f $AWS_K8S_CNI_MANIFEST\n\ncheck_ds_rollout \"aws-node\" \"kube-system\" \"10m\"\n", "num_lines": 34}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nrm -rf ./vendor\ngo mod edit -dropreplace github.com/aws/aws-sdk-go\ngo mod tidy\n", "num_lines": 6}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n \nset -e\n\nmkdir -p ./vendor/github.com/aws\n\nSDK_MODEL_SOURCE=./hack/ec2_preview_models\nSDK_VENDOR_PATH=./vendor/github.com/aws/aws-sdk-go\nAPI_VERSION=2016-11-15\nAPI_PATH=$SDK_VENDOR_PATH/models/apis/ec2/$API_VERSION\n\n# Clone the SDK to the vendor path (removing an old one if necessary)\nrm -rf $SDK_VENDOR_PATH\ngit clone --depth 1 https://github.com/aws/aws-sdk-go.git $SDK_VENDOR_PATH\n\n# Override the SDK models for AWS VPC CNI \ncp $SDK_MODEL_SOURCE/api-2.json $API_PATH/api-2.json\ncp $SDK_MODEL_SOURCE/docs-2.json $API_PATH/docs-2.json\ncp $SDK_MODEL_SOURCE/examples-1.json $API_PATH/examples-1.json\ncp $SDK_MODEL_SOURCE/paginators-1.json $API_PATH/paginators-1.json\n\n# Generate the SDK\npushd ./vendor/github.com/aws/aws-sdk-go\nmake generate\npopd\n\n# Use the vendored version of aws-sdk-go\ngo mod edit -replace github.com/aws/aws-sdk-go=./vendor/github.com/aws/aws-sdk-go\ngo mod tidy\n", "num_lines": 30}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Helper script for performing operations on vpc-cni addons\n\nVPC_CNI_ADDON_NAME=\"vpc-cni\"\n\nfunction load_addon_details() {\n  echo \"loading $VPC_CNI_ADDON_NAME addon details\"\n  DESCRIBE_ADDON_VERSIONS=$(aws eks describe-addon-versions $ENDPOINT_FLAG --addon-name $VPC_CNI_ADDON_NAME --kubernetes-version \"$K8S_VERSION\")\n\n  LATEST_ADDON_VERSION=$(echo \"$DESCRIBE_ADDON_VERSIONS\" | jq '.addons[0].addonVersions[0].addonVersion' -r)\n  DEFAULT_ADDON_VERSION=$(echo \"$DESCRIBE_ADDON_VERSIONS\" | jq -r '.addons[].addonVersions[] | select(.compatibilities[0].defaultVersion == true) | .addonVersion')\n  EXISTING_SERVICE_ACCOUNT_ROLE_ARN=$(kubectl get serviceaccount -n kube-system aws-node -o json | jq '.metadata.annotations.\"eks.amazonaws.com/role-arn\"' -r)\n}\n\nfunction wait_for_addon_status() {\n  local expected_status=$1\n  local retry_attempt=0\n  if [ \"$expected_status\" =  \"DELETED\" ]; then\n    while $(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region \"$REGION\"); do\n      if [ $retry_attempt -ge 30 ]; then\n        echo \"failed to delete addon, qutting after too many attempts\"\n        exit 1\n      fi\n      echo \"addon is still not deleted\"\n      sleep 5\n      ((retry_attempt=retry_attempt+1))\n    done\n    echo \"addon deleted\"\n    # Even after the addon API Returns an error, if you immediately try to create a new addon it sometimes fails\n    sleep 10\n    return\n  fi\n\n  retry_attempt=0\n  while true\n  do\n    STATUS=$(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region \"$REGION\" | jq -r '.addon.status')\n    if [ \"$STATUS\" = \"$expected_status\" ]; then\n      echo \"addon status matches expected status\"\n      return\n    fi\n    # We have seen the canary test get stuck, we don't know what causes this but most likely suspect is\n    # the addon update/delete attempts. So adding limited retries.\n    if [ $retry_attempt -ge 30 ]; then\n      echo \"failed to get desired add-on status: $STATUS, qutting after too many attempts\"\n      exit 1\n    fi\n    echo \"addon status is not equal to $expected_status\"\n    sleep 10\n    ((retry_attempt=retry_attempt+1))\n  done\n}\n\nfunction patch_aws_node_maxunavialable() {\n   # Patch the aws-node, so any update in aws-node happens in parallel for faster overall test execution\n   local retry=0\n   while [ $retry -le 10 ]; do\n     if kubectl patch ds -n kube-system aws-node -p '{\"spec\":{\"updateStrategy\":{\"rollingUpdate\":{\"maxUnavailable\": \"100%\"}}}}'; then\n       break\n     else\n       # It's possible the ds is not yet created by the Addon APIs, so have couple of retries\n       echo \"failed to patch ds, will retry\"\n       sleep 5\n       ((retry=retry+1))\n     fi\n   done\n}\n\nfunction install_add_on() {\n  local new_addon_version=$1\n  if [[ -z \"$new_addon_version\" || \"$new_addon_version\" == \"null\" ]]; then\n    echo \"addon information for $VPC_CNI_ADDON_NAME not available, skipping EKS-managed addon installation.\"\n    return\n  fi\n\n  if DESCRIBE_ADDON=$(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region \"$REGION\"); then\n    local current_addon_version=$(echo \"$DESCRIBE_ADDON\" | jq '.addon.addonVersion' -r)\n    if [ \"$new_addon_version\" != \"$current_addon_version\" ]; then\n      echo \"deleting the $current_addon_version to install $new_addon_version\"\n      aws eks delete-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name \"$VPC_CNI_ADDON_NAME\" --region \"$REGION\"\n      wait_for_addon_status \"DELETED\"\n    else\n      echo \"addon version $current_addon_version already installed\"\n      patch_aws_node_maxunavialable\n      return\n    fi\n  fi\n\n  echo \"installing addon $new_addon_version\"\n\n  # If installing the addon after deleting it once, we should retain the Service Account Role ARN of the Addon\n  if [ \"$EXISTING_SERVICE_ACCOUNT_ROLE_ARN\" != \"null\" ]; then\n     SA_ROLE_ARN_ARG=\"--service-account-role-arn $EXISTING_SERVICE_ACCOUNT_ROLE_ARN\"\n  fi\n\n  aws eks create-addon $ENDPOINT_FLAG $SA_ROLE_ARN_ARG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --resolve-conflicts OVERWRITE --addon-version $new_addon_version --region \"$REGION\"\n  patch_aws_node_maxunavialable\n  wait_for_addon_status \"ACTIVE\"\n}\n", "num_lines": 101}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncheck_aws_credentials() {\n    aws sts get-caller-identity --query \"Account\" ||\n        ( echo \"No AWS credentials found. Please run \\`aws configure\\` to set up the CLI for your credentials.\" && exit 1)\n}\n\nensure_ecr_repo() {\n    echo \"Ensuring that $2 exists for account $1\"\n    local __registry_account_id=\"$1\"\n    local __repo_name=\"$2\"\n    if ! `aws ecr describe-repositories --registry-id \"$__registry_account_id\" --repository-names \"$__repo_name\" >/dev/null 2>&1`; then\n        echo \"creating ECR repo with name $__repo_name in registry account $__registry_account_id\"\n        aws ecr create-repository --repository-name \"$__repo_name\"\n    fi\n}\n\nemit_cloudwatch_metric() {\n    aws cloudwatch put-metric-data --metric-name $1 --namespace TestExecution --unit None --value $2 --region $AWS_DEFAULT_REGION\n}\n\n", "num_lines": 22}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Helper script used for running canary test for CNI IPv4 and IPv6\n\nSECONDS=0\n\necho \"Running tests for amazon-vpc-cni-k8s with the following variables\nKUBE_CONFIG_PATH:  $KUBE_CONFIG_PATH\nCLUSTER_NAME: $CLUSTER_NAME\nREGION: $REGION\nENDPOINT: $ENDPOINT\"\n\nif [[ -n \"${ENDPOINT}\" ]]; then\n  ENDPOINT_FLAG=\"--endpoint $ENDPOINT\"\n  ENDPOINT_OPTION=\" --eks-endpoint $ENDPOINT\"\nfi\n\nif [[ -z \"${SKIP_MAKE_TEST_BINARIES}\" ]]; then\n  echo \"making ginkgo test binaries\"\n  (cd $SCRIPT_DIR/../ && make build-test-binaries)\nelse\n  echo \"skipping making ginkgo test binaries\"\nfi\n\n# Request times out in China Regions with default proxy\nif [[ $REGION == \"cn-north-1\" || $REGION == \"cn-northwest-1\" ]]; then\n  go env -w GOPROXY=https://goproxy.cn,direct\n  go env -w GOSUMDB=sum.golang.google.cn\nfi\n", "num_lines": 30}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction load_cluster_details() {\n  echo \"loading cluster details $CLUSTER_NAME\"\n  DESCRIBE_CLUSTER_OP=$(aws eks describe-cluster --name \"$CLUSTER_NAME\" --region \"$REGION\" $ENDPOINT_FLAG)\n  VPC_ID=$(echo \"$DESCRIBE_CLUSTER_OP\" | jq -r '.cluster.resourcesVpcConfig.vpcId')\n  K8S_VERSION=$(echo \"$DESCRIBE_CLUSTER_OP\" | jq .cluster.version -r)\n}\n\nfunction load_deveks_cluster_details() {\n\n  echo \"loading cluster details $CLUSTER_NAME\"\n  PROVIDER_ID=$(kubectl get nodes --kubeconfig $KUBE_CONFIG_PATH -ojson | jq -r '.items[0].spec.providerID')\n  INSTANCE_ID=${PROVIDER_ID##*/}\n  VPC_ID=$(aws ec2 describe-instances --instance-ids ${INSTANCE_ID} --no-cli-pager | jq -r '.Reservations[].Instances[].VpcId')\n}\n\nfunction down-test-cluster() {\n    echo -n \"Deleting cluster  (this may take ~10 mins) ... \"\n    eksctl delete cluster $CLUSTER_NAME >>$CLUSTER_MANAGE_LOG_PATH 2>&1 ||\n        (echo \"failed. Check $CLUSTER_MANAGE_LOG_PATH.\" && exit 1)\n    echo \"ok.\"\n}\n\nfunction up-test-cluster() {\n    DIR=$(cd \"$(dirname \"$0\")\"; pwd)\n    CLUSTER_TEMPLATE_PATH=$DIR/test/config\n    if [[ \"$RUN_BOTTLEROCKET_TEST\" == true ]]; then\n        echo \"Copying bottlerocket config to $CLUSTER_CONFIG\"\n        cp $CLUSTER_TEMPLATE_PATH/bottlerocket.yaml $CLUSTER_CONFIG\n\n    elif [[ \"$RUN_PERFORMANCE_TESTS\" == true ]]; then\n        echo \"Copying perf test cluster config to $CLUSTER_CONFIG\"\n        cp $CLUSTER_TEMPLATE_PATH/perf-cluster.yml $CLUSTER_CONFIG\n        AMI_ID=`aws ssm get-parameter --name /aws/service/eks/optimized-ami/${EKS_CLUSTER_VERSION}/amazon-linux-2/recommended/image_id --region us-west-2 --query \"Parameter.Value\" --output text`\n        echo \"Obtained ami_id as $AMI_ID\"\n        sed -i'.bak' \"s,AMI_ID_PLACEHOLDER,$AMI_ID,\" $CLUSTER_CONFIG\n        grep -r -q $AMI_ID $CLUSTER_CONFIG\n        export RUN_CONFORMANCE=\"false\"\n        : \"${PERFORMANCE_TEST_S3_BUCKET_NAME:=\"\"}\"\n    \n    else\n        echo \"Copying test cluster config to $CLUSTER_CONFIG\"\n        cp $CLUSTER_TEMPLATE_PATH/test-cluster.yaml $CLUSTER_CONFIG\n        sed -i'.bak' \"s,K8S_VERSION_PLACEHOLDER,$EKS_CLUSTER_VERSION,\" $CLUSTER_CONFIG\n        grep -r -q $EKS_CLUSTER_VERSION $CLUSTER_CONFIG\n        : \"${ROLE_ARN:=\"\"}\"\n        sed -i'.bak' \"s,ROLE_ARN_PLACEHOLDER,$ROLE_ARN,\" $CLUSTER_CONFIG\n    fi\n\n    sed -i'.bak' \"s,CLUSTER_NAME_PLACEHOLDER,$CLUSTER_NAME,\" $CLUSTER_CONFIG\n    grep -r -q $CLUSTER_NAME $CLUSTER_CONFIG\n    echo -n \"Creating cluster $CLUSTER_NAME (this may take ~20 mins. details: tail -f $CLUSTER_MANAGE_LOG_PATH)... \"\n    eksctl create cluster -f $CLUSTER_CONFIG --kubeconfig $KUBECONFIG_PATH >>$CLUSTER_MANAGE_LOG_PATH 1>&2 ||\n        (echo \"failed. Check $CLUSTER_MANAGE_LOG_PATH.\" && exit 1)\n    echo \"ok.\"\n    export KUBECONFIG=$KUBECONFIG_PATH\n    \n    if [[ \"$RUN_PERFORMANCE_TESTS\" == true ]]; then\n        kubectl create -f $DIR/test/config/cluster-autoscaler-autodiscover.yml\n    fi\n}\n\nfunction up-kops-cluster {\n    KOPS_S3_BUCKET=kops-cni-test-eks-$AWS_ACCOUNT_ID\n    echo \"Using $KOPS_S3_BUCKET as kops state store\"\n    if ! aws s3api head-bucket --bucket $KOPS_S3_BUCKET 2>/dev/null; then\n        aws s3api create-bucket --bucket $KOPS_S3_BUCKET --region $AWS_DEFAULT_REGION --create-bucket-configuration LocationConstraint=$AWS_DEFAULT_REGION\n    fi\n    echo \"Using kops version $KOPS_VERSION\"\n    curl -LO https://github.com/kubernetes/kops/releases/download/$KOPS_VERSION/kops-linux-amd64\n    chmod +x kops-linux-amd64\n    mkdir -p ~/kops_bin\n    KOPS_BIN=~/kops_bin/kops\n    mv kops-linux-amd64 $KOPS_BIN\n    CLUSTER_NAME=kops-cni-test-cluster-${TEST_ID}.k8s.local\n    export KOPS_STATE_STORE=s3://${KOPS_S3_BUCKET}\n\n    SSH_KEYS=~/.ssh/devopsinuse\n    if [ ! -f \"$SSH_KEYS\" ]\n    then\n        echo -e \"\\nCreating SSH keys ...\"\n        ssh-keygen -t rsa -N '' -f ~/.ssh/devopsinuse\n    else\n        echo -e \"\\nSSH keys are already in place!\"\n    fi\n\n    $KOPS_BIN create cluster \\\n    --cloud aws \\\n    --zones ${AWS_DEFAULT_REGION}a,${AWS_DEFAULT_REGION}b \\\n    --networking amazonvpc \\\n    --container-runtime containerd \\\n    --node-count 2 \\\n    --node-size c5.xlarge \\\n    --ssh-public-key=~/.ssh/devopsinuse.pub \\\n    --kubernetes-version ${K8S_VERSION} \\\n    ${CLUSTER_NAME}\n\n    $KOPS_BIN update cluster --name ${CLUSTER_NAME} --yes\n    sleep 100\n    $KOPS_BIN export kubeconfig --admin\n    sleep 10\n    MAX_RETRIES=15\n    RETRY_ATTEMPT=0\n    while [[ ! $($KOPS_BIN validate cluster | grep \"is ready\") && $RETRY_ATTEMPT -lt $MAX_RETRIES ]]\n    do\n        sleep 60\n        let RETRY_ATTEMPT=RETRY_ATTEMPT+1\n        echo \"In attempt# $RETRY_ATTEMPT, waiting for cluster validation\"\n    done\n\n    # kOps cluster by default comes with ebs-csi-node and coredns-autoscaler as an add-on which cannot be excluded on cluster creation\n    # Since CNI tests don't really need any of these components for running tests, we delete these to avoid any flakiness\n    export KUBECONFIG=~/.kube/config\n    kubectl delete daemonset ebs-csi-node -n kube-system\n    kubectl delete deployment coredns-autoscaler -n kube-system\n\n    kubectl apply -f https://raw.githubusercontent.com/aws/amazon-vpc-cni-k8s/${MANIFEST_CNI_VERSION}/config/master/cni-metrics-helper.yaml\n}\n\nfunction down-kops-cluster {\n    KOPS_BIN=~/kops_bin/kops\n    $KOPS_BIN delete cluster --name ${CLUSTER_NAME} --yes\n    aws s3 rm ${KOPS_STATE_STORE} --recursive\n    aws s3 rb ${KOPS_STATE_STORE} --region $AWS_DEFAULT_REGION\n}", "num_lines": 126}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncheck_is_installed() {\n    local __name=\"$1\"\n    if ! is_installed \"$__name\"; then\n        echo \"Please install $__name before running this script.\"\n        exit 1\n    fi\n}\n\nis_installed() {\n    local __name=\"$1\"\n    if $(which $__name >/dev/null 2>&1); then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction display_timelines() {\n    echo \"\"\n    echo \"Displaying all step durations.\"\n    echo \"TIMELINE: Upping test cluster took $UP_CLUSTER_DURATION seconds.\"\n    if [[ $RUN_INTEGRATION_DEFAULT_CNI == true ]]; then\n        echo \"TIMELINE: Default CNI integration tests took $DEFAULT_INTEGRATION_DURATION seconds.\"\n    fi\n    echo \"TIMELINE: Current image integration tests took $CURRENT_IMAGE_INTEGRATION_DURATION seconds.\"\n    if [[ \"$RUN_CONFORMANCE\" == true ]]; then\n        echo \"TIMELINE: Conformance tests took $CONFORMANCE_DURATION seconds.\"\n    fi\n    if [[ \"$RUN_PERFORMANCE_TESTS\" == true ]]; then\n        echo \"TIMELINE: Performance tests took $PERFORMANCE_DURATION seconds.\"\n    fi\n    echo \"TIMELINE: Down processes took $DOWN_DURATION seconds.\"\n}\n\n", "num_lines": 37}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "function run_kops_conformance() {\n    START=$SECONDS\n\n    export KUBECONFIG=~/.kube/config\n    kubectl apply -f \"$TEST_CONFIG_PATH\"\n    sleep 5\n    while [[ $(kubectl describe ds aws-node -n=kube-system | grep \"Available Pods: 0\") ]]\n    do\n        sleep 5\n        echo \"Waiting for daemonset update\"\n    done\n    echo \"Updated!\"\n\n    wget -qO- https://dl.k8s.io/v$K8S_VERSION/kubernetes-test-linux-amd64.tar.gz | tar -zxvf - --strip-components=3 -C /tmp  kubernetes/test/bin/e2e.test\n\n    /tmp/e2e.test --ginkgo.focus=\"Conformance\" --ginkgo.timeout 120m --kubeconfig=$KUBECONFIG --ginkgo.fail-fast  --ginkgo.flake-attempts 2 \\\n\t    --ginkgo.skip=\"(works for CRD with validation schema)|(ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer)|(should support remote command execution over websockets)|(should support retrieving logs from the container over websockets)|(Basic StatefulSet functionality [StatefulSetBasic])|\\[Slow\\]|\\[Serial\\]\"\n\n    /tmp/e2e.test --ginkgo.focus=\"\\[Serial\\].*Conformance\" --kubeconfig=$KUBECONFIG --ginkgo.fail-fast --ginkgo.flake-attempts 2 \\\n\t    --ginkgo.skip=\"(ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer)|(should support remote command execution over websockets)|(should support retrieving logs from the container over websockets)|\\[Slow\\]\"\n    echo \"Kops conformance tests ran successfully!\"\n\n    KOPS_TEST_DURATION=$((SECONDS - START))\n    echo \"TIMELINE: KOPS tests took $KOPS_TEST_DURATION seconds.\"\n\n    sleep 240 #Workaround to avoid ENI leakage during cluster deletion: https://github.com/aws/amazon-vpc-cni-k8s/issues/1223\n\n}\n\nfunction run_calico_test() {\n  echo \"Starting Helm installing Tigera operator and running Calico STAR tests\"\n  pushd ./test\n  VPC_ID=$(eksctl get cluster $CLUSTER_NAME -oyaml | grep vpc | cut -d \":\" -f 2 | awk '{$1=$1};1')\n\n  calico_version=$CALICO_VERSION\n  if [[ $1 == \"true\" ]]; then\n    # we can automatically use latest version in Calico repo, or use the known highest version (currently v3.23.0)\n    if [[ $RUN_LATEST_CALICO_VERSION == true ]]; then\n      version_tag=$(curl -i https://api.github.com/repos/projectcalico/calico/releases/latest | grep \"tag_name\") || true\n      if [[ -n $version_tag ]]; then\n        calico_version=$(echo $version_tag | cut -d \":\" -f 2 | cut -d '\"' -f 2 )\n      else\n        echo \"Getting Calico latest version failed, will fall back to default/set version $calico_version instead\"\n      fi\n    else echo \"Using default Calico version\"\n    fi\n    echo \"Using Calico version $calico_version to test\"\n  else\n    version=$(kubectl describe ds -n calico-system calico-node | grep \"calico/node:\" | cut -d ':' -f3)\n    echo \"Calico has been installed in testing cluster, keep using the version $version\"\n  fi\n\n  echo \"Testing amd64\"\n  instance_type=\"amd64\"\n  ginkgo -v integration/calico -- --cluster-kubeconfig=$KUBECONFIG --cluster-name=$CLUSTER_NAME --aws-region=$AWS_DEFAULT_REGION --aws-vpc-id=$VPC_ID --calico-version=$calico_version --instance-type=$instance_type --install-calico=$1\n  echo \"Testing arm64\"\n  instance_type=\"arm64\"\n  ginkgo -v integration/calico -- --cluster-kubeconfig=$KUBECONFIG --cluster-name=$CLUSTER_NAME --aws-region=$AWS_DEFAULT_REGION --aws-vpc-id=$VPC_ID --calico-version=$calico_version --instance-type=$instance_type --install-calico=false\n  popd\n}\n\nfunction build_and_push_image(){\n  command=$1\n  args=$2\n  START=$SECONDS\n  # Refer to https://github.com/docker/buildx#building-multi-platform-images for the multi-arch image build process.\n  # create the buildx container only if it doesn't exist already.\n  docker buildx inspect \"$BUILDX_BUILDER\" >/dev/null 2<&1 || docker buildx create --name=\"$BUILDX_BUILDER\" --buildkitd-flags '--allow-insecure-entitlement network.host' --use >/dev/null\n  make $command $args\n  echo \"TIMELINE: Docker build took $(($SECONDS - $START)) seconds.\"\n}\n", "num_lines": 72}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# check_ds_rollout watches the status of the latest rollout until it's done or\n# until the timeout. Namespace and timeout are optional parameters\ncheck_ds_rollout() {\n    local __ds_name=${1:-}\n    local __namespace=${2:-}\n    local __timeout=${3:-\"2m\"}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl rollout status ds/\"$__ds_name\" $__args --timeout=$__timeout\n}", "num_lines": 14}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "function check_for_timeout() {\n    if [[ $((SECONDS - $1)) -gt 1500 ]]; then\n        FAILURE_COUNT=$((FAILURE_COUNT + 1))\n        HAS_FAILED=true\n        if [[ $FAILURE_COUNT -gt 1 ]]; then\n            RUNNING_PERFORMANCE=false\n            echo \"Failed twice, deprovisioning cluster\"\n            on_error 1 $LINENO\n        fi\n        echo \"Failed once, retrying\"\n    fi\n}\n\nfunction upload_results_to_s3_bucket() {\n    echo \"$filename\"\n    echo \"Date\", \"\\\"slot1\\\"\", \"\\\"slot2\\\"\" >> \"$filename\"\n    echo $(date +\"%Y-%m-%d-%T\"), $((SCALE_UP_DURATION_ARRAY[0])), $((SCALE_DOWN_DURATION_ARRAY[0])) >> \"$filename\"\n    echo $(date +\"%Y-%m-%d-%T\"), $((SCALE_UP_DURATION_ARRAY[1])), $((SCALE_DOWN_DURATION_ARRAY[1])) >> \"$filename\"\n    echo $(date +\"%Y-%m-%d-%T\"), $((SCALE_UP_DURATION_ARRAY[2])), $((SCALE_DOWN_DURATION_ARRAY[2])) >> \"$filename\"\n\n    cat \"$filename\"\n    if [[ ${#PERFORMANCE_TEST_S3_BUCKET_NAME} -gt 0 ]]; then\n        aws s3 cp \"$filename\" \"s3://${PERFORMANCE_TEST_S3_BUCKET_NAME}/${1}/\"\n    else\n        echo \"No S3 bucket name given, skipping test result upload.\"\n    fi\n}\n\nfunction check_for_slow_performance() {\n    BUCKET=\"s3://${PERFORMANCE_TEST_S3_BUCKET_NAME}/${1}/\"\n    FILE1=$(aws s3 ls \"${BUCKET}\" | sort | tail -n 2 | sed -n '1 p' | awk '{print $4}')\n    FILE2=$(aws s3 ls \"${BUCKET}\" | sort | tail -n 3 | sed -n '1 p' | awk '{print $4}')\n    FILE3=$(aws s3 ls \"${BUCKET}\" | sort | tail -n 4 | sed -n '1 p' | awk '{print $4}')\n    \n    PAST_PERFORMANCE_UP_AVERAGE_SUM=0\n    find_performance_duration_average $FILE1 1\n    find_performance_duration_average $FILE2 2\n    find_performance_duration_average $FILE3 3\n    PAST_PERFORMANCE_UP_AVERAGE=$((PAST_PERFORMANCE_UP_AVERAGE_SUM / 3))\n\n    # Divided by 3 to get current average, multiply past averages by 5/4 to get 25% window\n    if [[ $((CURRENT_PERFORMANCE_UP_SUM / 3)) -gt $((PAST_PERFORMANCE_UP_AVERAGE * 5 / 4)) ]]; then\n        echo \"FAILURE! Performance test pod UPPING took >25% longer than the past three tests\"\n        echo \"This tests time: $((CURRENT_PERFORMANCE_UP_SUM / 3))\"\n        echo \"Previous tests' time: ${PAST_PERFORMANCE_UP_AVERAGE}\"\n        echo \"********************************\"\n        echo \"Look into how current changes could cause cni inefficiency.\"\n        echo \"********************************\"\n        on_error 1 $LINENO\n    fi\n}\n\nfunction find_performance_duration_average() {\n    aws s3 cp ${BUCKET}${1} performance_test${2}.csv\n    SCALE_UP_TEMP_DURATION_SUM=0\n    for i in {2..4}\n    do\n        TEMP=$(sed -n \"${i} p\" performance_test${2}.csv)\n        PAIR=${TEMP#*,}\n        SCALE_UP_TEMP_DURATION_SUM=$((SCALE_UP_TEMP_DURATION_SUM + ${PAIR%%,*}))\n    done\n    PAST_PERFORMANCE_UP_AVERAGE_SUM=$(($PAST_PERFORMANCE_UP_AVERAGE_SUM + $((SCALE_UP_TEMP_DURATION_SUM / 3))))\n}\n\nfunction run_performance_test_130_pods() {\n    echo \"Running performance tests against cluster\"\n    RUNNING_PERFORMANCE=true\n    $KUBECTL_PATH apply -f ./testdata/deploy-130-pods.yaml\n\n    DEPLOY_START=$SECONDS\n    FAILURE_COUNT=0\n\n    SCALE_UP_DURATION_ARRAY=()\n    SCALE_DOWN_DURATION_ARRAY=()\n    CURRENT_PERFORMANCE_UP_SUM=0\n    CURRENT_PERFORMANCE_DOWN_SUM=0\n    while [ ${#SCALE_DOWN_DURATION_ARRAY[@]} -lt 3 ]\n    do\n        ITERATION_START=$SECONDS\n        HAS_FAILED=false\n        $KUBECTL_PATH scale -f ./testdata/deploy-130-pods.yaml --replicas=130\n        while [[ ! $($KUBECTL_PATH get deploy | grep 130/130) && \"$HAS_FAILED\" == false ]]\n        do\n            sleep 1\n            echo \"Scaling UP\"\n            echo $($KUBECTL_PATH get deploy)\n            check_for_timeout $ITERATION_START\n        done\n\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_UP_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_UP_SUM=$((CURRENT_PERFORMANCE_UP_SUM + DURATION))\n        fi\n        $KUBECTL_PATH scale -f ./testdata/deploy-130-pods.yaml --replicas=0\n        while [[ $($KUBECTL_PATH get pods) ]]\n        do\n            sleep 1\n            echo \"Scaling DOWN\"\n            echo $($KUBECTL_PATH get deploy)\n        done\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_DOWN_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_DOWN_SUM=$((CURRENT_PERFORMANCE_DOWN_SUM + DURATION))\n        fi\n    done\n\n    echo \"Times to scale up:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_UP_DURATION_ARRAY[@]} ]\n    do\n        echo ${SCALE_UP_DURATION_ARRAY[$INDEX]}\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    echo \"Times to scale down:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_DOWN_DURATION_ARRAY[@]} ]\n    do\n        echo \"${SCALE_DOWN_DURATION_ARRAY[$INDEX]} seconds\"\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    DEPLOY_DURATION=$((SECONDS - DEPLOY_START))\n\n    filename=\"pod-130-Test-${TEST_ID}-$(date +\"%m-%d-%Y-%T\")-${TEST_IMAGE_VERSION}.csv\"\n    upload_results_to_s3_bucket \"130-pods\"\n    \n    echo \"TIMELINE: 130 Pod performance test took $DEPLOY_DURATION seconds.\"\n    RUNNING_PERFORMANCE=false\n    if [[ ${#PERFORMANCE_TEST_S3_BUCKET_NAME} -gt 0 ]]; then\n        check_for_slow_performance \"130-pods\"\n    fi\n    $KUBECTL_PATH delete -f ./testdata/deploy-130-pods.yaml\n}\n\nfunction run_performance_test_730_pods() {\n    echo \"Running performance tests against cluster\"\n    RUNNING_PERFORMANCE=true\n    $KUBECTL_PATH apply -f ./testdata/deploy-730-pods.yaml\n\n    DEPLOY_START=$SECONDS\n    FAILURE_COUNT=0\n\n    SCALE_UP_DURATION_ARRAY=()\n    SCALE_DOWN_DURATION_ARRAY=()\n    CURRENT_PERFORMANCE_UP_SUM=0\n    CURRENT_PERFORMANCE_DOWN_SUM=0\n    while [ ${#SCALE_DOWN_DURATION_ARRAY[@]} -lt 3 ]\n    do\n        ITERATION_START=$SECONDS\n        HAS_FAILED=false\n        $KUBECTL_PATH scale -f ./testdata/deploy-730-pods.yaml --replicas=730\n        while [[ ! $($KUBECTL_PATH get deploy | grep 730/730) && \"$HAS_FAILED\" == false ]]\n        do\n            sleep 2\n            echo \"Scaling UP\"\n            echo $($KUBECTL_PATH get deploy)\n            check_for_timeout $ITERATION_START\n        done\n\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_UP_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_UP_SUM=$((CURRENT_PERFORMANCE_UP_SUM + DURATION))\n        fi\n        $KUBECTL_PATH scale -f ./testdata/deploy-730-pods.yaml --replicas=0\n        while [[ $($KUBECTL_PATH get pods) ]]\n        do\n            sleep 2\n            echo \"Scaling DOWN\"\n            echo $($KUBECTL_PATH get deploy)\n        done\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_DOWN_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_DOWN_SUM=$((CURRENT_PERFORMANCE_DOWN_SUM + DURATION))\n        fi\n    done\n\n    echo \"Times to scale up:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_UP_DURATION_ARRAY[@]} ]\n    do\n        echo ${SCALE_UP_DURATION_ARRAY[$INDEX]}\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    echo \"Times to scale down:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_DOWN_DURATION_ARRAY[@]} ]\n    do\n        echo \"${SCALE_DOWN_DURATION_ARRAY[$INDEX]} seconds\"\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    DEPLOY_DURATION=$((SECONDS - DEPLOY_START))\n\n    filename=\"pod-730-Test-${TEST_ID}-$(date +\"%m-%d-%Y-%T\")-${TEST_IMAGE_VERSION}.csv\"\n    upload_results_to_s3_bucket \"730-pods\"\n    \n    echo \"TIMELINE: 730 Pod performance test took $DEPLOY_DURATION seconds.\"\n    RUNNING_PERFORMANCE=false\n    if [[ ${#PERFORMANCE_TEST_S3_BUCKET_NAME} -gt 0 ]]; then\n        check_for_slow_performance \"730-pods\"\n    fi\n    $KUBECTL_PATH delete -f ./testdata/deploy-730-pods.yaml\n}\n\nfunction run_performance_test_5000_pods() {\n    echo \"Running performance tests against cluster\"\n    RUNNING_PERFORMANCE=true\n    $KUBECTL_PATH apply -f ./testdata/deploy-5000-pods.yaml\n    \n    DEPLOY_START=$SECONDS\n    FAILURE_COUNT=0\n\n    SCALE_UP_DURATION_ARRAY=()\n    SCALE_DOWN_DURATION_ARRAY=()\n    CURRENT_PERFORMANCE_UP_SUM=0\n    CURRENT_PERFORMANCE_DOWN_SUM=0\n    while [ ${#SCALE_DOWN_DURATION_ARRAY[@]} -lt 3 ]\n    do\n        ITERATION_START=$SECONDS\n        HAS_FAILED=false\n        $KUBECTL_PATH scale -f ./testdata/deploy-5000-pods.yaml --replicas=5000\n        while [[ ! $($KUBECTL_PATH get deploy | grep 5000/5000) && \"$HAS_FAILED\" == false ]]\n        do\n            sleep 2\n            echo \"Scaling UP\"\n            echo $($KUBECTL_PATH get deploy)\n            check_for_timeout $ITERATION_START\n        done\n\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_UP_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_UP_SUM=$((CURRENT_PERFORMANCE_UP_SUM + DURATION))\n        fi\n        $KUBECTL_PATH scale -f ./testdata/deploy-5000-pods.yaml --replicas=0\n        while [[ $($KUBECTL_PATH get pods) ]]\n        do\n            sleep 2\n            echo \"Scaling DOWN\"\n            echo $($KUBECTL_PATH get deploy)\n        done\n        if [[ \"$HAS_FAILED\" == false ]]; then\n            DURATION=$((SECONDS - ITERATION_START))\n            SCALE_DOWN_DURATION_ARRAY+=( $DURATION )\n            CURRENT_PERFORMANCE_DOWN_SUM=$((CURRENT_PERFORMANCE_DOWN_SUM + DURATION))\n        fi\n    done\n\n    echo \"Times to scale up:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_UP_DURATION_ARRAY[@]} ]\n    do\n        echo ${SCALE_UP_DURATION_ARRAY[$INDEX]}\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    echo \"Times to scale down:\"\n    INDEX=0\n    while [ $INDEX -lt ${#SCALE_DOWN_DURATION_ARRAY[@]} ]\n    do\n        echo \"${SCALE_DOWN_DURATION_ARRAY[$INDEX]} seconds\"\n        INDEX=$((INDEX + 1))\n    done\n    echo \"\"\n    DEPLOY_DURATION=$((SECONDS - DEPLOY_START))\n\n    filename=\"pod-5000-Test-${TEST_ID}-$(date +\"%m-%d-%Y-%T\")-${TEST_IMAGE_VERSION}.csv\"\n    upload_results_to_s3_bucket \"5000-pods\"\n    \n    echo \"TIMELINE: 5000 Pod performance test took $DEPLOY_DURATION seconds.\"\n    RUNNING_PERFORMANCE=false\n    if [[ ${#PERFORMANCE_TEST_S3_BUCKET_NAME} -gt 0 ]]; then\n        check_for_slow_performance \"5000-pods\"\n    fi\n    $KUBECTL_PATH delete -f ./testdata/deploy-5000-pods.yaml\n}\n", "num_lines": 283}
{"repo_name": "amazon-vpc-cni-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\npushd ./test/integration\n\necho \"Running integration test with the following configuration:\nKUBECONFIG: $KUBECONFIG\nCLUSTER_NAME: $CLUSTER_NAME\nAWS_REGION: $AWS_REGION\"\n\n\nif [[ -n \"${ENDPOINT}\" ]]; then\n  ENDPOINT_FLAG=\"--endpoint $ENDPOINT\"\nfi\n\nwhile getopts \"f:\" arg; do\n  case $arg in\n    f) FOCUS=$OPTARG;\n    echo \"FOCUS: $FOCUS\";\n  esac\ndone\n\nCLUSTER_INFO=$(aws eks describe-cluster --name $CLUSTER_NAME --region $AWS_REGION $ENDPOINT_FLAG)\n\nVPC_ID=$(echo $CLUSTER_INFO | jq -r '.cluster.resourcesVpcConfig.vpcId')\nSERVICE_ROLE_ARN=$(echo $CLUSTER_INFO | jq -r '.cluster.roleArn')\nROLE_NAME=${SERVICE_ROLE_ARN##*/}\nTEST_FAILED=false\n \nSTART=$SECONDS\n\nfor dir in */  \ndo\n\n    cd \"${dir%*/}\"  \n    if [ -n \"$FOCUS\" ]; then\n        ( ginkgo --focus=\"$FOCUS\" -v -r -- --cluster-kubeconfig=$KUBECONFIG --cluster-name=$CLUSTER_NAME --aws-region=$AWS_REGION --aws-vpc-id=$VPC_ID ) || TEST_FAILED=true\n    else\n        ( ginkgo -v -r -- --cluster-kubeconfig=$KUBECONFIG --cluster-name=$CLUSTER_NAME --aws-region=$AWS_REGION --aws-vpc-id=$VPC_ID ) || TEST_FAILED=true\n    fi\n    cd ..    \n     \ndone\n\nDEFAULT_INTEGRATION_DURATION=$((SECONDS - START))\necho \"TIMELINE: Integration tests took $DEFAULT_INTEGRATION_DURATION seconds.\"\n\npopd\n\n# If any of the test failed, exit with non zero exit code\nif [ $TEST_FAILED = true ]; then\n  exit 1\nfi", "num_lines": 54}
{"repo_name": "amazon-vpc-cni-plugins", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "amazon-vpc-cni-plugins", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 781}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nK8S_VERSION=\"${K8S_VERSION:=\"1.22.x\"}\"\nKUBEBUILDER_ASSETS=\"${KUBEBUILDER_ASSETS:=\"${HOME}/.kubebuilder/bin\"}\"\n\nmain() {\n    tools\n    kubebuilder\n}\n\ntools() {\n    go install sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.0.0-20220421205612-c162794a9b12\n    go install sigs.k8s.io/controller-tools/cmd/controller-gen@v0.6.2\n\n    if ! echo \"$PATH\" | grep -q \"${GOPATH:-undefined}/bin\\|$HOME/go/bin\"; then\n        echo \"Go workspace's \\\"bin\\\" directory is not in PATH. Run 'export PATH=\\\"\\$PATH:\\${GOPATH:-\\$HOME/go}/bin\\\"'.\"\n    fi\n}\n\nkubebuilder() {\n    mkdir -p $KUBEBUILDER_ASSETS\n    arch=$(go env GOARCH)\n    ## Kubebuilder does not support darwin/arm64, so use amd64 through Rosetta instead\n    if [[ $(go env GOOS) == \"darwin\" ]] && [[ $(go env GOARCH) == \"arm64\" ]]; then\n        arch=\"amd64\"\n    fi\n    ln -sf $(setup-envtest use -p path \"${K8S_VERSION}\" --arch=\"${arch}\" --bin-dir=\"${KUBEBUILDER_ASSETS}\")/* ${KUBEBUILDER_ASSETS}\n    find $KUBEBUILDER_ASSETS\n}\n\nmain \"$@\"\n", "num_lines": 33}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "alias mockgen='mockgen -copyright_file=templates/copyright.txt'\n# package aws mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/aws/ec2/api/mock_ec2_wrapper.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/aws/ec2/api EC2Wrapper\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/aws/ec2/api/mock_ec2_apihelper.go  github.com/aws/amazon-vpc-resource-controller-k8s/pkg/aws/ec2/api EC2APIHelper\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/aws/ec2/mock_instance.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/aws/ec2 EC2Instance\n# package k8s mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/k8s/mock_k8swrapper.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/k8s K8sWrapper\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/k8s/pod/mock_podapiwrapper.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/k8s/pod PodClientAPIWrapper\n# package worker mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/worker/mock_worker.go  github.com/aws/amazon-vpc-resource-controller-k8s/pkg/worker Worker\n# package handler mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/handler/mock_handler.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/handler Handler\n# package provider mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/provider/mock_provider.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/provider ResourceProvider\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/provider/branch/trunk/mock_trunk.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/provider/branch/trunk TrunkENI\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/provider/ip/eni/mock_eni.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/provider/ip/eni ENIManager\n# package node mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/node/manager/mock_manager.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/node/manager Manager\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/node/mock_node.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/node Node\n# package utils mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/utils/mock_k8shelper.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/utils SecurityGroupForPodsAPI\n# package pool mocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/pool/mock_pool.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/pool Pool\n# package resource maocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/resource/mock_resources.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/resource ResourceManager\n# package condition maocks\nmockgen -destination=../mocks/amazon-vcp-resource-controller-k8s/pkg/condition/mock_condition.go github.com/aws/amazon-vpc-resource-controller-k8s/pkg/condition Conditions\n", "num_lines": 28}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# The Scripts creates an eksctl cluster using a predefined template.\n# This cluster should have the required nodegroups for running the\n# Security Group for Pods and Windows IPAM integration tests.\n\nset -eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nTEMPLATE_FILE=\"$SCRIPTS_DIR/template/eksctl/eks-cluster.yaml\"\n\nUSAGE=$(cat << 'EOM'\nUsage: create-cluster.sh -n [cluster-name] -v [k8s-version]\n\nCreates an EKS Cluster with Nodegroups. The Cluster is\ncreated using eksctl with a pre-defined eksctl template.\n\n Required:\n -n   Name of the EKS cluster\n -v   K8s Version\n Optional:\n -r   Region of the EKS Cluster. Defaults to us-west-2\n -c   eksctl Cluster config path. Defaults to build/eks-cluster.yaml\n -s   Suffix that will be added to each resource. This is useful when\n      running in CI Setup to prevent parallel runs from modifying same\n      resources\nEOM\n)\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nwhile getopts \"n:v:r:c:s:\" o; do\n  case \"${o}\" in\n    n) # Name of the EKS Cluster\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    v) # K8s Version of the EKS Cluster\n      K8S_VERSION=${OPTARG}\n      ;;\n    r) # Region where EKS Cluster will be created\n      AWS_REGION=${OPTARG}\n      ;;\n    c) # eksctl cluster config file path\n      CLUSTER_CONFIG_PATH=${OPTARG}\n      ;;\n    s) # Suffix that will be attached to each AWS Resource\n      RESOURCE_SUFFIX=${OPTARG}\n      ;;\n    *)\n      echoerr \"${USAGE}\"\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [[ -z \"$CLUSTER_NAME\" ]]; then\n echoerr \"${USAGE}\\n\\nmissing: -n is a required flag\\n\"\n exit 1\nfi\n\nif [[ -z \"$K8S_VERSION\" ]]; then\n echoerr \"${USAGE}\\n\\nmissing: -v is a required flag\\n\"\n exit 1\nfi\n\nif [[ -z \"$AWS_REGION\" ]]; then\n  AWS_REGION=\"us-west-2\"\n  echo \"no regions defined, will fallback to default region $AWS_REGION\"\nfi\n\nif [[ -z \"$CLUSTER_CONFIG_PATH\" ]]; then\n  CLUSTER_CONFIG_DIR=\"$SCRIPTS_DIR/build\"\n  CLUSTER_CONFIG_PATH=\"$CLUSTER_CONFIG_DIR/eks-cluster.yaml\"\n\n  echo \"cluster config path not defined, will generate it at default path $CLUSTER_CONFIG_PATH\"\n\n  mkdir -p \"$CLUSTER_CONFIG_DIR\"\nfi\n\nsource \"$SCRIPTS_DIR/lib/config.sh\"\n\ncheck_is_installed eksctl\n\nCLUSTER_NAME=$(add_suffix \"$CLUSTER_NAME\")\n\nfunction create_eksctl_cluster() {\n  echo \"creating a $K8S_VERSION cluster named $CLUSTER_NAME using eksctl\"\n\n  # Using a static Instance Role Name so IAM Policies\n  # can be attached to it later without having to retrieve\n  # the auto generated eksctl name.\n  sed \"s/CLUSTER_NAME/$CLUSTER_NAME/g;\n  s/CLUSTER_REGION/$AWS_REGION/g;\n  s/K8S_VERSION/$K8S_VERSION/g;\n  s/INSTANCE_ROLE_NAME/$INSTANCE_ROLE_NAME/g\" \\\n  \"$TEMPLATE_FILE\" > \"$CLUSTER_CONFIG_PATH\"\n\n  eksctl create cluster -f \"$CLUSTER_CONFIG_PATH\"\n}\n\ncreate_eksctl_cluster\n", "num_lines": 103}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Deletes an EKS Cluster and it's nodegroup created using\n# eksctl. The script requires the cluster config path to delete\n# all resources associated with the cluster.\n\nset -eo pipefail\n\nUSAGE=$(cat << 'EOM'\nUsage: delete-cluster.sh -c [cluster-config]\n\nDeletes an EKS Cluster along with the Nodegroups. Takes in\nthe cluster config as an optional argument. If no arugment is\nprovided then it will use the cluster config in the default\npath i.e /build/eks-cluster.yaml\n\n Optional:\n -c   eksctl Cluster config path. Defaults to build/eks-cluster.yaml\nEOM\n)\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nCLUSTER_CONFIG_DIR=\"$SCRIPTS_DIR/build\"\nCLUSTER_CONFIG_PATH=\"$CLUSTER_CONFIG_DIR/eks-cluster.yaml\"\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\ncheck_is_installed eksctl\n\nwhile getopts \"c:\" o; do\n  case \"${o}\" in\n    c) # eksctl cluster config file path\n      CLUSTER_CONFIG_PATH=${OPTARG}\n      ;;\n    *)\n      echoerr \"${USAGE}\"\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\neksctl delete cluster -f \"$CLUSTER_CONFIG_PATH\" --wait\n", "num_lines": 44}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Cretes or Deletes the IAM Roles and IAM Policies required by\n# VPC Resource Controller for running the Integration test\n\nset -eo pipefail\n\nUSAGE=$(cat << 'EOM'\nUsage: create-iam-resources.sh -n [cluster-name] -o [create/delete]\n\nCreates the IAM Policies required by the VPC Resource\nController to Run.\n\n Required:\n -n   name of cluster for creating IAM Roles and Policies\n -o   [Only one of the value must be set]\n      create: To create the IAM Roles required by vpc-resource-controller\n      delete: To delete the IAM Roles required by vpc-resource-controller\n Optional:\n -s   Suffix that will be added to each resource. This is useful when\n      running in CI Setup to prevent parallel runs from modifying resources.\nEOM\n)\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nTEMPLATE_DIR=\"$SCRIPTS_DIR/template/iam\"\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nwhile getopts \"o:n:s:\" o; do\n  case \"${o}\" in\n    o) # creates the IAM Roles and Policies required by the Controller\n      OPERATION=${OPTARG}\n      ;;\n    n) # Cluster name for which IRSA will be created\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    s) # suffix attached to each IAM Resource\n      RESOURCE_SUFFIX=${OPTARG}\n      ;;\n    *)\n      echoerr \"${USAGE}\"\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [[ -z \"$CLUSTER_NAME\" ]]; then\n  echoerr \"$USAGE\\n\\n cluster name must be provided\"\n  exit  1\nfi\n\nif [[ -z \"$OPERATION\" ]]; then\n  echoerr \"$USAGE\\n\\n must provide either create or delete operation\"\n  exit  1\nfi\n\nsource \"$SCRIPTS_DIR/lib/config.sh\"\nsource \"$SCRIPTS_DIR/lib/aws.sh\"\n\ncheck_is_installed aws\n\nWORKSPACE=\"$SCRIPTS_DIR/build\"\nmkdir -p \"$WORKSPACE\"\n\nAWS_ACCOUNT_ID=\"${AWS_ACCOUNT_ID:-$(aws sts get-caller-identity | jq .Account -r)}\"\n\nTRUNK_ASSOC_POLICY_ARN=\"arn:aws:iam::$AWS_ACCOUNT_ID:policy/$TRUNK_ASSOC_POLICY_NAME\"\nINSTANCE_ROLE_ARN=\"arn:aws:iam::$AWS_ACCOUNT_ID:role/$INSTANCE_ROLE_NAME\"\n\nVPC_RC_POLICY_ARN=\"arn:aws:iam::$AWS_ACCOUNT_ID:policy/$VPC_RC_POLICY_NAME\"\nVPC_RC_ROLE_ARN=\"arn:aws:iam::$AWS_ACCOUNT_ID:role/$VPC_RC_ROLE_NAME\"\n\ncreate_iam_resources() {\n  echo \"creating IAM resources\"\n\n  # Create Policy with permission to associate Trunk to Branch Interface.\n  # This Policy is attached to the Instance Node Role where VPC RC Runs\n  create_policy \"$TRUNK_ASSOC_POLICY_NAME\" \"$TEMPLATE_DIR/associate-trunk-policy.json\"\n  attach_policy \"$TRUNK_ASSOC_POLICY_ARN\" \"$INSTANCE_ROLE_NAME\"\n\n  # Policy document that allows VPC RC Instance Role to assume the Role\n  # to manage Trunk/Branch Interfaces on user's behalf\n  local policy_document=\"$WORKSPACE/aws-trust-policy.json\"\n  sed \"s|AWS_ROLE_ARN|$INSTANCE_ROLE_ARN|g\" \\\n  \"$TEMPLATE_DIR/aws-trust-relationship.json\" > \"$policy_document\"\n  create_role \"$VPC_RC_ROLE_NAME\" \"$policy_document\"\n\n  # Finally, attach the policy with the permission to manage Trunk/Branch\n  # Interface to the above role\n  create_policy \"$VPC_RC_POLICY_NAME\" \"$TEMPLATE_DIR/vpc-resource-controller-policy.json\"\n  attach_policy \"$VPC_RC_POLICY_ARN\" \"$VPC_RC_ROLE_NAME\"\n}\n\ndelete_iam_resources() {\n  echo \"deleting IAM resources\"\n\n  detach_policy \"$VPC_RC_POLICY_ARN\" \"$VPC_RC_ROLE_NAME\"\n  delete_policy \"$VPC_RC_POLICY_ARN\"\n  delete_role \"$VPC_RC_ROLE_NAME\"\n\n  detach_policy \"$TRUNK_ASSOC_POLICY_ARN\" \"$INSTANCE_ROLE_NAME\"\n  delete_policy \"$TRUNK_ASSOC_POLICY_ARN\"\n  # The Instance Node Role is not deleted here as it's lifecycle\n  # is managed by eksctl\n}\n\nif [[ \"$OPERATION\" == \"create\" ]]; then\n  create_iam_resources\nelif [ \"$OPERATION\" == \"delete\" ]; then\n  delete_iam_resources\nelse\n  echoerr \"$USAGE\\n\\n operation can be create or delete only\"\n  exit 1\nfi\n", "num_lines": 116}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Installs a stable version of cert-manager\n\nset -eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nDEFAULT_CERT_MANAGER_VERSION=\"v1.4.0\"\n\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\ncheck_is_installed kubectl \"You can install kubectl with the helper scripts/install-kubectl.sh\"\n\n__cert_manager_version=\"$1\"\nif [ \"z$__cert_manager_version\" == \"z\" ]; then\n    __cert_manager_version=${CERT_MANAGER_VERSION:-$DEFAULT_CERT_MANAGER_VERSION}\nfi\n\ninstall() {\n    echo -n \"installing cert-manager ... \"\n    __cert_manager_url=\"https://github.com/jetstack/cert-manager/releases/download/${__cert_manager_version}/cert-manager.yaml\"\n    echo -n \"installing cert-manager from $__cert_manager_url ... \"\n    kubectl apply --validate=false -f $__cert_manager_url\n    echo \"ok.\"\n}\n\ncheck() {\n    echo -n \"checking cert-manager deployments have rolled out ... \"\n    local __ns=\"cert-manager\"\n    local __timeout=\"4m\"\n    check_deployment_rollout cert-manager-webhook $__ns $__timeout\n    check_deployment_rollout cert-manager $__ns\n    check_deployment_rollout cert-manager-cainjector $__ns\n    echo \"ok.\"\n}\n\ninstall\ncheck\n", "num_lines": 40}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Installs a stable version of vpc-cni\n\nset -eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nDEFAULT_VPC_CNI_VERSION=\"1.11\"\n\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\ncheck_is_installed kubectl\n\n__vpc_cni_version=\"$1\"\nif [ -z \"$__vpc_cni_version\" ]; then\n    __vpc_cni_version=${VPC_CNI_VERSION:-$DEFAULT_VPC_CNI_VERSION}\nfi\n\ninstall() {\n\n  echo \"installing vpc cni $__vpc_cni_version\"\n  # install the latest patch version for the release\n  __vpc_cni_url=\"https://raw.githubusercontent.com/aws/amazon-vpc-cni-k8s/release-$__vpc_cni_version/config/master/aws-k8s-cni.yaml\"\n  kubectl apply -f $__vpc_cni_url\n  echo \"ok..\"\n}\n\ncheck() {\n  echo \"checking vpc cni version has rolled out\"\n  check_ds_rollout \"aws-node\" \"kube-system\"\n  echo \"ok..\"\n}\n\ninstall\ncheck", "num_lines": 36}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script run integration tests on the EKS VPC Resource Controller\n# This is not intended to run integration tests when controller is running\n# on the data plane for development and testing purposes. The script expects\n# an EKS Cluster with atlest 3 Windows and Linux Nodes to be pre-created to\n# run the Canary tests. This scrip is invoked from external sources.\n\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nGINKGO_TEST_BUILD_DIR=\"$SCRIPT_DIR/../../build\"\nSECONDS=0\nVPC_CNI_ADDON_NAME=\"vpc-cni\"\n\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\n\necho \"Running VPC Resource Controller integration test with the following variables\nKUBE CONFIG: $KUBE_CONFIG_PATH\nCLUSTER_NAME: $CLUSTER_NAME\nREGION: $REGION\"\n\n# Default Proxy is not allowed in China Region\nif [[ $REGION == \"cn-north-1\" || $REGION == \"cn-northwest-1\" ]]; then\n  go env -w GOPROXY=https://goproxy.cn,direct\n  go env -w GOSUMDB=sum.golang.google.cn\nfi\n\nfunction load_addon_details() {\n  echo \"loading $VPC_CNI_ADDON_NAME addon details\"\n  DESCRIBE_ADDON_VERSIONS=$(aws eks describe-addon-versions $ENDPOINT_FLAG --addon-name $VPC_CNI_ADDON_NAME --kubernetes-version \"$K8S_VERSION\")\n\n  LATEST_ADDON_VERSION=$(echo \"$DESCRIBE_ADDON_VERSIONS\" | jq '.addons[0].addonVersions[0].addonVersion' -r)\n  DEFAULT_ADDON_VERSION=$(echo \"$DESCRIBE_ADDON_VERSIONS\" | jq -r '.addons[].addonVersions[] | select(.compatibilities[0].defaultVersion == true) | .addonVersion')\n}\n\nfunction wait_for_addon_status() {\n  local expected_status=$1\n  local retry_attempt=0\n  if [ \"$expected_status\" =  \"DELETED\" ]; then\n    while $(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region \"$REGION\"); do\n      if [ $retry_attempt -ge 30 ]; then\n        echo \"failed to delete addon, qutting after too many attempts\"\n        exit 1\n      fi\n      echo \"addon is still not deleted\"\n      sleep 5\n      ((retry_attempt=retry_attempt+1))\n    done\n    echo \"addon deleted\"\n    # Even after the addon API Returns an error, if you immediately try to create a new addon it sometimes fails\n    sleep 10\n    return\n  fi\n\n  retry_attempt=0\n  while true\n  do\n    STATUS=$(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region \"$REGION\" | jq -r '.addon.status')\n    if [ \"$STATUS\" = \"$expected_status\" ]; then\n      echo \"addon status matches expected status\"\n      return\n    fi\n    # We have seen the canary test get stuck, we don't know what causes this but most likely suspect is\n    # the addon update/delete attempts. So adding limited retries.\n    if [ $retry_attempt -ge 30 ]; then\n      echo \"failed to get desired add-on status: $STATUS, qutting after too many attempts\"\n      exit 1\n    fi\n    echo \"addon status is not equal to $expected_status\"\n    sleep 10\n    ((retry_attempt=retry_attempt+1))\n  done\n}\n\nfunction install_add_on() {\n  local new_addon_version=$1\n  if [[ -z \"$new_addon_version\" || \"$new_addon_version\" == \"null\" ]]; then\n    echo \"addon information for $VPC_CNI_ADDON_NAME not available, skipping EKS-managed addon installation. Tests will run against self-managed addon.\"\n    return\n  fi\n\n  if DESCRIBE_ADDON=$(aws eks describe-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --region $REGION); then\n    local current_addon_version=$(echo \"$DESCRIBE_ADDON\" | jq '.addon.addonVersion' -r)\n    if [ \"$new_addon_version\" != \"$current_addon_version\" ]; then\n      echo \"deleting the $current_addon_version to install $new_addon_version\"\n      aws eks delete-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name \"$VPC_CNI_ADDON_NAME\" --region $REGION\n      wait_for_addon_status \"DELETED\"\n    else\n      echo \"addon version $current_addon_version already installed\"\n      return\n    fi\n  fi\n\n  echo \"installing addon $new_addon_version\"\n  aws eks create-addon $ENDPOINT_FLAG --cluster-name \"$CLUSTER_NAME\" --addon-name $VPC_CNI_ADDON_NAME --resolve-conflicts OVERWRITE --addon-version $new_addon_version --region $REGION\n  wait_for_addon_status \"ACTIVE\"\n}\n\nfunction run_canary_tests() {\n  if [[ -z \"${SKIP_MAKE_TEST_BINARIES}\" ]]; then\n    echo \"making ginkgo test binaries\"\n    (cd $SCRIPT_DIR/../.. && make build-test-binaries)\n  else\n    echo \"skipping making ginkgo test binaries\"\n  fi\n\n  # For each component, we want to cover the most important test cases. We also don't want to take more than 30 minutes\n  # per repository as these tests are run sequentially along with tests from other repositories\n  # Currently the overall execution time is ~50 minutes and we will reduce it in future\n  (CGO_ENABLED=0 ginkgo --no-color --focus=\"CANARY\" $EXTRA_GINKGO_FLAGS -v --timeout 10m $GINKGO_TEST_BUILD_DIR/perpodsg.test -- --cluster-kubeconfig=$KUBE_CONFIG_PATH --cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id=$VPC_ID)\n  if [[ -z \"${SKIP_WINDOWS_TEST}\" ]]; then\n    (CGO_ENABLED=0 ginkgo --no-color --focus=\"CANARY\" $EXTRA_GINKGO_FLAGS -v --timeout 25m $GINKGO_TEST_BUILD_DIR/windows.test -- --cluster-kubeconfig=$KUBE_CONFIG_PATH --cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id=$VPC_ID)\n  else\n    echo \"skipping Windows tests\"\n  fi\n  (CGO_ENABLED=0 ginkgo --no-color --focus=\"CANARY\" $EXTRA_GINKGO_FLAGS -v --timeout 5m $GINKGO_TEST_BUILD_DIR/webhook.test -- --cluster-kubeconfig=$KUBE_CONFIG_PATH --cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id=$VPC_ID)\n}\n\necho \"Starting the ginkgo test suite\"\nload_cluster_details\n\n# Addons is supported from 1.18 onwards\nload_addon_details\ninstall_add_on \"$LATEST_ADDON_VERSION\"\n\nattach_controller_policy_cluster_role\nset_env_aws_node \"ENABLE_POD_ENI\" \"true\"\nrun_canary_tests\nset_env_aws_node \"ENABLE_POD_ENI\" \"false\"\ndetach_controller_policy_cluster_role\n\necho \"Successfully ran all tests in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n", "num_lines": 134}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Script to run vpc-resource-controller release tests: webhook, perpodsg, windows integration tests\n# This script does not install any addons nor update vpc-resource-controller. Please install all\n# required versions to be tests prior to running the script.\n\n# Parameters:\n# CLUSTER_NAME: name of the cluster\n# KUBE_CONFIG_PATH: path to the kubeconfig file, default ~/.kube/config\n# REGION: default us-west-2\n# RUN_DEVEKS_TEST: false\n\nset -euoE pipefail\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nINTEGRATION_TEST_DIR=\"$SCRIPT_DIR/../../test/integration\"\nSECONDS=0\n\n: \"${RUN_DEVEKS_TEST:=false}\"\n: \"${ENDPOINT:=\"\"}\"\n: \"${SKIP_WINDOWS_TEST:=\"\"}\"\n: \"${EXTRA_GINKGO_FLAGS:=\"\"}\"\n\nsource \"$SCRIPT_DIR\"/lib/cluster.sh\n\ncleanup(){\n\n  if [[ $? == 0 ]]; then\n    echo \"Successfully ran all tests in $(($SECONDS / 60)) minutes and $(($SECONDS % 60)) seconds\"\n  else\n    echo \"[Error] Integration tests failed\"\n  fi\n\n  echo \"Cleaning up the setup\"\n  set_env_aws_node \"ENABLE_POD_ENI\" \"false\"\n  detach_controller_policy_cluster_role\n}\n\ntrap cleanup EXIT\n\nfunction run_integration_tests(){\n  TEST_RESULT=success\n  (cd $INTEGRATION_TEST_DIR/perpodsg && CGO_ENABLED=0 ginkgo --skip=LOCAL $EXTRA_GINKGO_FLAGS -v -timeout=35m -- -cluster-kubeconfig=$KUBE_CONFIG_PATH -cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id $VPC_ID) || TEST_RESULT=fail\n  if [[ -z \"${SKIP_WINDOWS_TEST}\" ]]; then\n    (cd $INTEGRATION_TEST_DIR/windows && CGO_ENABLED=0 ginkgo --skip=LOCAL $EXTRA_GINKGO_FLAGS -v -timeout=100m -- -cluster-kubeconfig=$KUBE_CONFIG_PATH -cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id $VPC_ID) || TEST_RESULT=fail\n  else\n    echo \"skipping Windows tests\"\n  fi\n  (cd $INTEGRATION_TEST_DIR/webhook && CGO_ENABLED=0 ginkgo --skip=LOCAL $EXTRA_GINKGO_FLAGS -v -timeout=5m -- -cluster-kubeconfig=$KUBE_CONFIG_PATH -cluster-name=$CLUSTER_NAME --aws-region=$REGION --aws-vpc-id $VPC_ID) || TEST_RESULT=fail\n\n  if [[ \"$TEST_RESULT\" == fail ]]; then\n      exit 1\n  fi\n}\n\necho \"Running VPC Resource Controller integration test with the following variables\nKUBE CONFIG: $KUBE_CONFIG_PATH\nCLUSTER_NAME: $CLUSTER_NAME\nREGION: $REGION\"\n\nif [[ \"${RUN_DEVEKS_TEST}\" == \"true\" ]];then\n  load_deveks_cluster_details\nelse\n  load_cluster_details\nfi\n\nattach_controller_policy_cluster_role\nset_env_aws_node \"ENABLE_POD_ENI\" \"true\"\nrun_integration_tests\n", "num_lines": 70}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Builds and installs the controlller on EKS DataPlane. This is for\n# testing purposes only and it will not work for accounts that are\n# not allowlisted for ENI Trunking feature.\n\nset -eo pipefail\n\nUSAGE=$(cat << 'EOM'\nUsage: test-with-eksctl.sh -n [cluster-name] -r [user-role-arn]\n\nBuilds and installs the controlller on EKS DataPlane. This is for\ntesting purposes only and it will not work for accounts that are\nnot allowlisted for ENI Trunking feature.\n\n Required: [Only one of the flag must be set]\n -n   name of the existing EKS cluster\n Optional:\n -i   IAM role ARN that will be assumed by the controller to manage trunk/branch ENI\n -s   Suffix that will be added to each resource. This is useful when\n      running in CI Setup to prevent parallel runs from modifying resources.\n -r   AWS Region where the controller image will be hosted. Defaults to us-west-2\nEOM\n)\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nTEMPLATE_DIR=$SCRIPTS_DIR/template/rbac\nBASHPID=$$\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nwhile getopts \"n:i:r:s:\" o; do\n  case \"${o}\" in\n    n) # Name of the EKS Cluster\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    i) # Role ARN that will be assumed by the VPC Resource Controller\n      VPC_RC_ROLE_ARN=${OPTARG}\n      ;;\n    r) # Region where ECR image will be hosted\n      AWS_REGION=${OPTARG}\n      ;;\n    s) # Resource Suffix attached to AWS Resource Names\n      RESOURCE_SUFFIX=${OPTARG}\n      ;;\n    *)\n      echoerr \"${USAGE}\"\n      exit 1\n      ;;\n  esac\ndone\nshift $((OPTIND-1))\n\nif [[ -z \"$CLUSTER_NAME\" ]]; then\n echoerr \"${USAGE}\\n\\nmissing: -n is a required flag\\n\"\n exit 1\nfi\n\nif [[ -z \"$AWS_REGION\" ]]; then\n  AWS_REGION=\"us-west-2\"\n  echo \"no regions defined, will fallback to default region $AWS_REGION\"\nfi\n\nsource \"$SCRIPTS_DIR/lib/aws.sh\"\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\nsource \"$SCRIPTS_DIR/lib/config.sh\"\n\ncheck_is_installed aws\ncheck_is_installed docker\ncheck_is_installed ginkgo\ncheck_is_installed eksctl\ncheck_is_installed kubectl\ncheck_is_installed kustomize\ncheck_is_installed jq\n\nCLUSTER_NAME=$(add_suffix \"$CLUSTER_NAME\")\nAWS_ACCOUNT_ID=\"${AWS_ACCOUNT_ID:-$(aws sts get-caller-identity | jq .Account -r)}\"\nVPC_ID=$(aws eks describe-cluster --name $CLUSTER_NAME --region $AWS_REGION | jq -r '.cluster.resourcesVpcConfig.vpcId')\nKUBE_CONFIG_PATH=~/.kube/config\nCONTROLLER_LOG_FILE=/tmp/$CLUSTER_NAME.logs\nTEST_FAILED=false\n\n# If Role name is not provided, use the default role name\nif [[ -z \"$VPC_RC_ROLE_ARN\" ]]; then\n  VPC_RC_ROLE_ARN=\"arn:aws:iam::$AWS_ACCOUNT_ID:role/$VPC_RC_ROLE_NAME\"\nfi\n\nECR_URL=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com\nECR_REPOSITORY=amazon/vpc-resource-controller\nECR_IMAGE_TAG=$(add_suffix \"test\")\n\nIMAGE=$ECR_URL/$ECR_REPOSITORY:$ECR_IMAGE_TAG\n\nfunction build_and_push_image() {\n  echo \"building and pushing controller image to ECR\"\n  IMAGE=$IMAGE AWS_ACCOUNT=$AWS_ACCOUNT_ID AWS_REGION=$AWS_REGION make docker-build\n  IMAGE=$IMAGE AWS_ACCOUNT=$AWS_ACCOUNT_ID AWS_REGION=$AWS_REGION make docker-push\n}\n\nfunction install_controller() {\n  echo \"installing amazon-vpc-resource-controller-k8s\"\n  IMAGE=$IMAGE \\\n  AWS_ACCOUNT=$AWS_ACCOUNT_ID \\\n  AWS_REGION=$AWS_REGION \\\n  CLUSTER_NAME=$CLUSTER_NAME \\\n  USER_ROLE_ARN=$VPC_RC_ROLE_ARN \\\n  make deploy\n\n  check_deployment_rollout vpc-resource-local-controller kube-system 2m\n}\n\nfunction disable_eks_controller() {\n  echo \"disabling the default amazon-vpc-resource-controller-k8s controller\"\n\n  # Delete Mutating Webhook Configuration\n  kubectl delete mutatingwebhookconfigurations.admissionregistration.k8s.io vpc-resource-mutating-webhook\n  # Delete the Validating Webhook Configuration\n  kubectl delete validatingwebhookconfigurations.admissionregistration.k8s.io vpc-resource-validating-webhook\n\n  # Remove the patch/update permission on ConfigMap from the EKS VPC RC Leader election Role\n  kubectl patch roles -n kube-system vpc-resource-controller-leader-election-role \\\n  --patch \"$(cat \"$TEMPLATE_DIR/cp-vpc-leader-election-role-patch.yaml\")\"\n}\n\nfunction set_pod_eni_flag_on_ipamd() {\n  local flag=$1\n  echo \"Setting Pod ENI on aws-node/ipamd to $flag\"\n  kubectl set env daemonset aws-node -n kube-system ENABLE_POD_ENI=$flag\n\n  kubectl rollout status daemonset aws-node -n kube-system\n}\n\nfunction run_integration_test() {\n  local additional_gingko_params=$1\n\n  # SGP Tests\n  (cd test/integration/perpodsg && \\\n  CGO_ENABLED=0 ginkgo \"$additional_gingko_params\" \\\n  -v -timeout 40m -- \\\n  -cluster-kubeconfig=$KUBE_CONFIG_PATH \\\n  -cluster-name=$CLUSTER_NAME \\\n  --aws-region=$AWS_REGION \\\n  --aws-vpc-id $VPC_ID) || TEST_FAILED=true\n\n  # Windows Test\n  (cd test/integration/windows && \\\n  CGO_ENABLED=0 ginkgo \"$additional_gingko_params\" -v -timeout 85m -- \\\n  -cluster-kubeconfig=$KUBE_CONFIG_PATH \\\n  -cluster-name=$CLUSTER_NAME \\\n  --aws-region=$AWS_REGION \\\n  --aws-vpc-id=$VPC_ID) || TEST_FAILED=true\n\n  # SGP + Windows Webhook Test\n  (cd test/integration/webhook && \\\n  CGO_ENABLED=0 ginkgo \"$additional_gingko_params\" -v -timeout 10m -- \\\n  -cluster-kubeconfig=$KUBE_CONFIG_PATH \\\n  -cluster-name=$CLUSTER_NAME \\\n  --aws-region=$AWS_REGION \\\n  --aws-vpc-id=$VPC_ID) || TEST_FAILED=true\n\n  # SGP + Metrics for Regression Test\n  if [[ $additional_gingko_params == \"--focus=LOCAL\" ]]; then\n    # We need a larger group of nodes to test the regression of controllers\n    ng=$(eksctl get nodegroup --cluster=$CLUSTER_NAME --output=json | jq '.[0]')\n    ng_name=$(echo $ng | jq -r '.Name')\n    desired_size=$(echo $ng | jq '.DesiredCapacity')\n    max_size=$(echo $ng | jq '.MaxSize')\n    min_size=$(echo $ng | jq '.MinSize')\n    eksctl scale nodegroup --cluster=$CLUSTER_NAME --name=$ng_name --nodes=100 --nodes-min=0 --nodes-max=150\n    sleep 300\n    (cd test/integration/metrics && \\\n    CGO_ENABLED=0 ginkgo \"$additional_gingko_params\" -v -timeout 20m -- \\\n    -cluster-kubeconfig=$KUBE_CONFIG_PATH \\\n    -cluster-name=$CLUSTER_NAME \\\n    --aws-region=$AWS_REGION \\\n    --aws-vpc-id=$VPC_ID \\\n    --latest-released-rc-image-tag=v1.1.3 ) || TEST_FAILED=true\n    eksctl scale nodegroup --cluster=$CLUSTER_NAME --name=$ng_name --nodes=$desired_size --nodes-min=$min_size --nodes-max=$max_size\n  fi\n}\n\nfunction verify_controller_has_lease() {\n  # Get the name of the VPC Resource Controller Pod\n  local controller_pod_names=\"$(kubectl get pods -n kube-system -l app=vpc-resource-controller \\\n  --no-headers -o custom-columns=\":metadata.name\")\"\n\n  # Wait till the new controller has acquired the leader lease\n  i=0\n  while :\n  do\n    local lease_holder=\"$(kubectl get configmap -n kube-system cp-vpc-resource-controller -o json \\\n    | jq '.metadata.annotations.\"control-plane.alpha.kubernetes.io/leader\"' --raw-output \\\n    | jq .holderIdentity --raw-output)\"\n\n    for controller_pod_name in $controller_pod_names\n    do\n       if [[ $lease_holder == $controller_pod_name* ]]; then\n          echo \"one of the new controller has the lease: $lease_holder\"\n          break 2\n       fi\n    done\n    if  [[ i -ge 20 ]]; then\n      echo \"new controller failed to accquire leader lease in $i attempts\"\n      exit 1\n    else\n      echo \"new controller doesn't have the leader lease yet, will retry\"\n      sleep 10\n      i=$((i+1))\n    fi\n  done\n\n  # Get the lease transition count at the time the new controller acquired lease\n  LEADER_TRANSITION_BEFORE_TEST=$(get_leader_lease_transistion_count)\n}\n\nfunction verify_leader_lease_didnt_change() {\n  # Get the leader lease transition count after running all integration tests\n  LEADER_TRANSITION_AFTER_TEST=$(get_leader_lease_transistion_count)\n\n  # If the leader lease count increased between the time when the test was running, then\n  # we will assume the tests failed as it could mean either the controller failed to hold\n  # the lease or it restarted during test execution which should not happen ideally\n  if [[ $LEADER_TRANSITION_BEFORE_TEST != \"$LEADER_TRANSITION_AFTER_TEST\" ]]; then\n    echo \"leader transitioned during the tests, the new controller failed to keep the leader lease\"\n    exit 1\n  fi\n}\n\n# Get the number of times the leader lease transition between different owners\nfunction get_leader_lease_transistion_count() {\n  kubectl get configmap -n kube-system cp-vpc-resource-controller -o json \\\n  | jq '.metadata.annotations.\"control-plane.alpha.kubernetes.io/leader\"' --raw-output \\\n  | jq .leaderTransitions\n}\n\nfunction output_logs() {\n  cat $CONTROLLER_LOG_FILE\n}\n\nfunction clean_up() {\n  echo \"cleaning up...\"\n  delete_ecr_image \"$ECR_REPOSITORY\" \"$ECR_IMAGE_TAG\"\n  output_logs\n}\n\nfunction redirect_vpc_controller_logs() {\n  # Till the time the bash process keeps running, keep on redirecting the logs to the file\n  # The parent process will log the output of the file on exit\n  while ps -p $BASHPID > /dev/null\n  do\n    kubectl logs -n kube-system -l app=vpc-resource-controller \\\n    --tail -1 -f >> $CONTROLLER_LOG_FILE || echo \"LOG COLLECTOR:existing controller killed, will retry\"\n    # Allow for the new controller to come up\n    sleep 10\n  done\n\n  echo \"LOG COLLECTOR: exiting the process\"\n}\n\n# Delete the IAM Policies, Roles and the EKS Cluster\ntrap 'clean_up' EXIT\n\n# Cordon the Windows Nodes as cert manager and other future 3rd pary\n# dependency may not have nodeselectors to schedule pods on linux\nkubectl cordon -l kubernetes.io/os=windows\n\n# Install the stable version of VPC CNI\nbash \"$SCRIPTS_DIR/install-vpc-cni.sh\" \"1.11\"\n\n# Install Cert Manager which is used for generating the\n# certificates for the Webhooks\nbash \"$SCRIPTS_DIR/install-cert-manager.sh\"\n\n# Login to ECR to push the controller image\necr_login \"$AWS_REGION\" \"$ECR_URL\"\n\n# Create the repository but don't delete it as it can hold\n# test images from other GitHub runs\ncreate_repository \"$ECR_REPOSITORY\"\n\n# Push the image to ECR\nbuild_and_push_image\n\n# Install the CRD and the Controller on the Data Plane\ninstall_controller\n\n# Uncordon the Windows Node, all new deployment/pods fromt this\n# point must have nodeSelecotrs to be scheduled on the right OS\nkubectl uncordon -l kubernetes.io/os=windows\n\n# Start redirecting the logs to the log file which will be outputted at\n# when the script exits. This log should be run in background and exit\n# when the bash script exits\nredirect_vpc_controller_logs &\n\n# Disable the Controller on EKS Control Plane\ndisable_eks_controller\n\n# Verify the Controller on Data Plane has the leader lease\nverify_controller_has_lease\n\n# Enables the SGP feature on IPAMD, which lables the node\n# with a fetaure flag used by controller to start managing\n# the node for ENI Trunking/Branching\nset_pod_eni_flag_on_ipamd \"true\"\n\n# Allow for IPAMD to label the node after startup\n# TODO: Handle this in the Test Suite in more concrete manner\nsleep 60\n\n# Run Ginko Test for Security Group for Pods and skip all the local tests as\n# they require restarts and it will lead to leader lease being switched and the\n# next validation step failing\nrun_integration_test \"--skip=LOCAL\"\n\n# Verify the leader lease didn't transition during the execution of test cases\nverify_leader_lease_didnt_change\n\n# Run Local Ginko Test that require multiple restarts of controller for negative\n# scenarios testing\nrun_integration_test \"--focus=LOCAL\"\n\n# Revert back to initial state after the test\nset_pod_eni_flag_on_ipamd \"false\"\n\n# If any of the test failed, exit with non zero exit code\nif [ $TEST_FAILED = true ]; then\n  exit 1\nfi\n", "num_lines": 330}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    echo -n \"ecr login ... \"\n    local __aws_region=$1\n    local __ecr_url=$2\n    local __err_msg=\"Failed ECR login. Please make sure you have IAM permissions to access ECR.\"\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        ( aws ecr get-login-password --region $__aws_region | \\\n                docker login --username AWS --password-stdin $__ecr_url ) ||\n                ( echo \"\\n$__err_msg\" && exit 1 )\n    else\n        $( aws ecr get-login --no-include-email ) || ( echo \"\\n$__err_msg\" && exit 1 )\n    fi\n    echo \"ok.\"\n}\n\ncreate_repository() {\n  local __repository_name=$1\n\n  if ! (aws ecr describe-repositories --repository-name \"$__repository_name\"); then\n    echo \"creating new repository, $__repository_name\"\n    aws ecr create-repository --repository-name \"$__repository_name\"\n  else\n    echo \"repository already exists $__repository_name\"\n  fi\n}\n\ndelete_ecr_image() {\n  local __ecr_repository=$1\n  local __image_tag=$2\n\n  aws ecr batch-delete-image \\\n     --repository-name \"$__ecr_repository\" \\\n     --image-ids imageTag=\"$__image_tag\"\n}\n\ncreate_policy() {\n  local __policy_name=$1\n  local __policy_document=$2\n\n  echo \"creating IAM policy $__policy_arn\"\n  aws iam create-policy --policy-name \"$__policy_name\" --policy-document \"file:///$__policy_document\"\n}\n\ndelete_policy() {\n  local __policy_arn=$1\n\n  echo \"deleting IAM policy $__policy_arn\"\n  aws iam delete-policy --policy-arn \"$__policy_arn\"\n}\n\ncreate_role() {\n  local __role_name=$1\n  local __trust_policy_doc=$2\n\n  if [[ -z $__trust_policy_doc ]]; then\n    echo \"creating IAM role $__role_name\"\n    aws iam create-role --role-name \"$__role_name\"\n  else\n    echo \"creating IAM role $__role_name with trust policy $__trust_policy_doc\"\n    aws iam create-role --role-name \"$__role_name\" --assume-role-policy-document \"file:///$__trust_policy_doc\"\n  fi\n}\n\ndelete_role() {\n  local __role_name=$1\n\n  echo \"deleting IAM role $__role_name\"\n  aws iam delete-role --role-name \"$__role_name\"\n}\n\nattach_policy() {\n  local __policy_arn=$1\n  local __role_name=$2\n\n  echo \"attaching policy $__policy_arn to role $__role_name\"\n  aws iam attach-role-policy --policy-arn \"$__policy_arn\" --role-name \"$__role_name\"\n}\n\ndetach_policy() {\n  local __policy_arn=$1\n  local __role_name=$2\n\n  echo \"detaching policy $__policy_arn to role $__role_name\"\n  aws iam detach-role-policy --policy-arn \"$__policy_arn\" --role-name \"$__role_name\"\n}\n", "num_lines": 90}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nLIB_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nENDPOINT_FLAG=\"\"\n\nsource \"$LIB_DIR\"/k8s.sh\n\nif [[ -n \"${ENDPOINT}\" ]]; then\n  ENDPOINT_FLAG=\"--endpoint $ENDPOINT\"\nfi\n\nfunction load_cluster_details() {\n  CLUSTER_INFO=$(aws eks describe-cluster --name $CLUSTER_NAME --region $REGION $ENDPOINT_FLAG)\n  VPC_ID=$(echo $CLUSTER_INFO | jq -r '.cluster.resourcesVpcConfig.vpcId')\n  SERVICE_ROLE_ARN=$(echo $CLUSTER_INFO | jq -r '.cluster.roleArn')\n  K8S_VERSION=$(echo $CLUSTER_INFO | jq -r '.cluster.version')\n  ROLE_NAME=${SERVICE_ROLE_ARN##*/}\n\n  echo \"VPC ID: $VPC_ID, Service Role ARN: $SERVICE_ROLE_ARN, Role Name: $ROLE_NAME\"\n}\n\nfunction load_deveks_cluster_details() {\n\n  PROVIDER_ID=$(kubectl get nodes -ojson | jq -r '.items[0].spec.providerID')\n  INSTANCE_ID=${PROVIDER_ID##*/}\n  VPC_ID=$(aws ec2 describe-instances --instance-ids ${INSTANCE_ID} --no-cli-pager | jq -r '.Reservations[].Instances[].VpcId')\n  REGION_NAME=$(echo $REGION | tr -d '-')\n  ROLE_NAME=\"deveks-${CLUSTER_NAME}-cluster-ServiceRole-${REGION_NAME}\"\n  ACCOUNT_ID=$(aws sts get-caller-identity | jq -r '.Account')\n  SERVICE_ROLE_ARN=\"arn:aws:iam::${ACCOUNT_ID}:role/${ROLE_NAME}\"\n\n  echo \"VPC ID: $VPC_ID, Service Role ARN: $SERVICE_ROLE_ARN, Role Name: $ROLE_NAME\"\n}\n\n# This operation fails with rate limit exceeded when test is running for multiple K8s\n# version at same time, hence we increase the exponential retries on the aws call\nfunction attach_controller_policy_cluster_role() {\n  echo \"Attaching IAM Policy to Cluster Service Role\"\n  AWS_MAX_ATTEMPTS=10 aws iam attach-role-policy \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKSVPCResourceController \\\n    --role-name \"$ROLE_NAME\" > /dev/null\n}\n\nfunction detach_controller_policy_cluster_role() {\n  echo \"Detaching the IAM Policy from Cluster Service Role\"\n  aws iam detach-role-policy \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKSVPCResourceController \\\n    --role-name $ROLE_NAME > /dev/null\n}\n\nfunction set_env_aws_node() {\n  local KEY=$1\n  local VAL=$2\n\n  echo \"Setting environment variable $KEY to $VAL on aws-node\"\n  kubectl set env daemonset aws-node -n kube-system $KEY=$VAL\n  check_ds_rollout \"aws-node\" \"kube-system\"\n}\n", "num_lines": 59}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nechoerr() { echo -e \"$@\" 1>&2; }\n\ncheck_is_installed() {\n    local __name=\"$1\"\n    local __extra_msg=\"$2\"\n    if ! is_installed \"$__name\"; then\n        echo \"FATAL: Missing requirement '$__name'\"\n        echo \"Please install $__name before running this script.\"\n        if [[ -n $__extra_msg ]]; then\n            echo \"\"\n            echo \"$__extra_msg\"\n            echo \"\"\n        fi\n        exit 1\n    fi\n}\n\nis_installed() {\n    local __name=\"$1\"\n    if $(which $__name >/dev/null 2>&1); then\n        return 0\n    else\n        return 1\n    fi\n}\n", "num_lines": 28}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Add Suffix to each AWS Resource Name if supplied.\n# This is done to allow multiple concurrent runs on\n# same accounts from modifying same resources\nfunction add_suffix() {\n  local __resource=$1\n  if [[ $RESOURCE_SUFFIX ]]; then\n    echo \"$__resource-$RESOURCE_SUFFIX\"\n  else\n    echo \"$__resource\"\n  fi\n}\n\n# IAM Role Name for Linux Node Role where VPC Resource Controller Runs. It should\n# have the Trunk Association Policy\nTRUNK_ASSOC_POLICY_NAME=$(add_suffix \"AssociateTrunkInterfcePolicy\")\nINSTANCE_ROLE_NAME=$(add_suffix \"LinuxNodeRole\")\n\n# IAM Role and it's Policy Names which have the permission to manage Trunk/Branch\n# Interfaces\nVPC_RC_POLICY_NAME=$(add_suffix \"VPCResourceControllerPolicy\")\nVPC_RC_ROLE_NAME=$(add_suffix \"VPCResourceControllerRole\")\n", "num_lines": 24}
{"repo_name": "amazon-vpc-resource-controller-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# resource_exists returns 0 when the supplied resource can be found, 1\n# otherwise. An optional second parameter overrides the Kubernetes namespace\n# argument\nk8s_resource_exists() {\n    local __res_name=${1:-}\n    local __namespace=${2:-}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl get $__args \"$__res_name\" >/dev/null 2>&1\n}\n\n\n# check_deployment_rollout watches the status of the latest rollout\n# until it's done or until the timeout. Namespace and timeout are optional\n# parameters\ncheck_deployment_rollout() {\n    local __dep_name=${1:-}\n    local __namespace=${2:-}\n    local __timeout=${3:-\"2m\"}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl rollout status deployment/\"$__dep_name\" $__args --timeout=$__timeout\n}\n\n# check_ds_rollout watches the status of the latest rollout until it's done or\n# until the timeout. Namespace and timeout are optional parameters\ncheck_ds_rollout() {\n    local __ds_name=${1:-}\n    local __namespace=${2:-}\n    local __timeout=${3:-\"2m\"}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl rollout status ds/\"$__ds_name\" $__args --timeout=$__timeout\n}", "num_lines": 42}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nrm -rf ./vendor\ngo mod edit -dropreplace github.com/aws/aws-sdk-go\ngo mod tidy\n", "num_lines": 6}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nmkdir -p ./vendor/github.com/aws\n\nSDK_MODEL_SOURCE=https://raw.githubusercontent.com/aws/aws-app-mesh-roadmap/main/appmesh-preview/sdk\nSDK_VENDOR_PATH=./vendor/github.com/aws/aws-sdk-go\nAPI_VERSION=2019-01-25\nAPI_PATH=$SDK_VENDOR_PATH/models/apis/appmesh/$API_VERSION\nSERVICE_NAME=$([ \"$APPMESH_PREVIEW\" == \"y\" ] && echo \"appmesh-preview\" || echo \"appmesh\" )\n\n# Clone the SDK to the vendor path (removing an old one if necessary)\nrm -rf $SDK_VENDOR_PATH\ngit clone --depth 1 https://github.com/aws/aws-sdk-go.git $SDK_VENDOR_PATH\n\n# Override the SDK models for App Mesh\ncurl -s $SDK_MODEL_SOURCE/api.json |\\\n    # Always use the \"vanilla\" flavors of UID, Service ID, and Service Name.\n    # This ensures the SDK we generate is always the same interface objects, only changing\n    # the endpoint and signing name when using preview.\n    jq \"(.metadata.uid) |= \\\"appmesh-$API_VERSION\\\"\" |\\\n    jq \"(.metadata.serviceId) |= \\\"App Mesh\\\"\" |\\\n    jq \"(.metadata.serviceFullName) |= \\\"AWS App Mesh\\\"\" |\\\n    # Set the endpoint prefix and signing name to the desired value, based on\n    # whether or not we're using the preview endpoint\n    jq \"(.metadata | .endpointPrefix, .signingName) |= \\\"$SERVICE_NAME\\\"\" \\\n    > $API_PATH/api-2.json\ncurl -s $SDK_MODEL_SOURCE/docs.json > $API_PATH/docs-2.json\ncurl -s $SDK_MODEL_SOURCE/examples.json > $API_PATH/examples-1.json\ncurl -s $SDK_MODEL_SOURCE/paginators.json > $API_PATH/paginators-1.json\n\n# Generate the SDK\npushd ./vendor/github.com/aws/aws-sdk-go\nmake generate\npopd\n\n# Use the vendored version of aws-sdk-go\ngo mod edit -replace github.com/aws/aws-sdk-go=./vendor/github.com/aws/aws-sdk-go\ngo mod tidy\n", "num_lines": 41}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ncheck_kube_connection() {\n\n\tkube_err=$(kubectl cluster-info 2>&1 >/dev/null)\n    if [[ -z $kube_err ]]; then\n        echo \"kubectl context check: PASSED!\"\n        return 0\n    else\n        echo \"kubectl context check: FAILED -- context or permissions issue for kubectl\"\n        echo $kube_err\n        return 1\n    fi\n\n}\n\ncheck_kube_installation() {\n\n    kube_err=$(kubectl version --client 2>&1 >/dev/null)\n    if [[ -z $kube_err ]]; then\n        echo \"kubectl installation check: PASSED!\"\n        return 0\n    else\n        echo \"kubectl installation check: FAILED -- kubectl not installed\"\n        return 1\n    fi\n\n}\n\ncheck_jq_installation() {\n\n    jq_err=$(jq --version 2>&1 >/dev/null)\n    if [[ -z $jq_err ]]; then\n        echo \"jq installation check: PASSED!\"\n        return 0\n    else\n        echo \"jq installation check: FAILED -- jq not installed\"\n        return 1\n    fi\n\n}\n\ncheck_old_crds() {\n\n    vs=$(kubectl get crd virtualservices.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n    vn=$(kubectl get crd virtualnodes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n    ms=$(kubectl get crd meshes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n\n    if [[ -z $vs && -z $vn && -z $ms  ]]; then\n        echo \"App Mesh CRD check: PASSED!\"\n        return 0\n    else\n       echo \"App Mesh CRD check: FAILED -- v1beta1 CRDs are still installed\"\n       return 1\n    fi\n\n}\n\ncheck_controller_version() {\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller --ignore-not-found -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n    requiredver=\"v1.0.0\"\n\n    if [[ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" || -z \"$currentver\" ]]; then\n        echo \"Controller version check: PASSED!\"\n        return 0\n    else\n        echo \"Controller version check: FAILED -- old appmesh-controller ($currentver) is still running\"\n        return 1\n    \n    fi\n}\n\ncheck_injector() {\n    status=0\n    for ns in \"appmesh-inject\" \"appmesh-system\"; do\n\n        injector=$(kubectl get deployment -n ${ns} appmesh-inject --ignore-not-found -o json | jq -r .kind)\n\n        if [ -z $injector ]; then\n            echo \"Injector check for namespace ${ns}: PASSED!\"\n        else\n           echo \"Injector check: FAILED -- appmesh-inject is still running in namespace ${ns}\"\n           return 1\n        fi\n\n    done\n    return 0\n}\n\nmain() {\n\n    exitcode=0\n    check_kube_installation || exitcode=1\n    check_jq_installation || exitcode=1\n    check_kube_connection || exitcode=1\n    if [ ${exitcode} = 0 ]; then\n        check_old_crds || exitcode=1\n        check_controller_version || exitcode=1\n        check_injector || exitcode=1\n    fi\n\n    if [ ${exitcode} = 0 ]; then\n        echo -e \"\\nYour cluster is ready for upgrade. Please proceed to the installation instructions\"\n    else\n        echo -e \"\\nYour cluster is NOT ready for upgrade to v1.0.0. Please install/uninstall all the identified items before proceeding\"\n    fi\n\n}\n\nmain", "num_lines": 110}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "# aws-app-mesh-controller-for-k8\nmockgen -destination=./mocks/aws-app-mesh-controller-for-k8s/pkg/webhook/mock_mutator.go github.com/aws/aws-app-mesh-controller-for-k8s/pkg/webhook Mutator\nmockgen -destination=./mocks/aws-app-mesh-controller-for-k8s/pkg/webhook/mock_validator.go github.com/aws/aws-app-mesh-controller-for-k8s/pkg/webhook Validator\nmockgen -destination=./mocks/aws-app-mesh-controller-for-k8s/pkg/mesh/mock_membership_designator.go github.com/aws/aws-app-mesh-controller-for-k8s/pkg/mesh MembershipDesignator\nmockgen -destination=./mocks/aws-app-mesh-controller-for-k8s/pkg/virtualgateway/mock_membership_designator.go github.com/aws/aws-app-mesh-controller-for-k8s/pkg/virtualgateway MembershipDesignator\nmockgen -destination=./mocks/aws-app-mesh-controller-for-k8s/pkg/virtualnode/mock_membership_designator.go github.com/aws/aws-app-mesh-controller-for-k8s/pkg/virtualnode MembershipDesignator\n\n# apimachinery\nmockgen -destination=./mocks/apimachinery/pkg/conversion/mock_scope.go k8s.io/apimachinery/pkg/conversion Scope\n", "num_lines": 10}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -eo pipefail\n\nSCRIPTPATH=\"$( cd \"$(dirname \"$0\")\" ; pwd -P )\"\n\nUSAGE=$(cat << 'EOM'\n  Usage: delete-cluster  [-c <CLUSTER_CONTEXT>] [-o]\n  Deletes a kind cluster and context dir\n  Example: delete-cluster -c build/tmp-cluster-1234\n          Required:\n            -c          Cluster context directory\n          Optional:\n            -o          Override path w/ your own kubectl and kind binaries\nEOM\n)\n\n# Process our input arguments\nwhile getopts \"c:o\" opt; do\n  case ${opt} in\n    c ) # Cluster context directory\n        TMP_DIR=$OPTARG\n        CLUSTER_NAME=$(cat $TMP_DIR/clustername)\n      ;;\n    o ) # Override path with your own kubectl and kind binaries\n\t      OVERRIDE_PATH=1\n        export PATH=$PATH:$TMP_DIR\n      ;;\n    \\? )\n        echoerr \"$USAGE\" 1>&2\n        exit\n      ;;\n  esac\ndone\n\necho \"\u00f0\u0178\u00a5\u2018 Deleting k8s cluster using \\\"kind\\\"\"\nkind delete cluster --name \"$CLUSTER_NAME\"\nrm -r $TMP_DIR\n", "num_lines": 38}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/install-cert-manager.sh\n#\n# Installs a stable version of cert-manager\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\nDEFAULT_CERT_MANAGER_VERSION=\"v0.14.3\"\n\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\ncheck_is_installed kubectl \"You can install kubectl with the helper scripts/install-kubectl.sh\"\n\n__cert_manager_version=\"$1\"\nif [ \"z$__cert_manager_version\" == \"z\" ]; then\n    __cert_manager_version=${CERT_MANAGER_VERSION:-$DEFAULT_CERT_MANAGER_VERSION}\nfi\n\ninstall() {\n    echo -n \"installing cert-manager ... \"\n    __cert_manager_url=\"https://github.com/jetstack/cert-manager/releases/download/${__cert_manager_version}/cert-manager.yaml\"\n    echo -n \"installing cert-manager from $__cert_manager_url ... \"\n    kubectl apply --validate=false -f $__cert_manager_url\n    echo \"ok.\"\n}\n\ncheck() {\n    echo -n \"checking cert-manager deployments have rolled out ... \"\n    local __ns=\"cert-manager\"\n    local __timeout=\"4m\"\n    check_deployment_rollout cert-manager-webhook $__ns $__timeout\n    check_deployment_rollout cert-manager $__ns\n    check_deployment_rollout cert-manager-cainjector $__ns\n    echo \"ok.\"\n}\n\n\ninstall\ncheck\n", "num_lines": 43}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/install-controller-gen.sh\n#\n# Checks that the `controller-gen` binary is available on the host system and\n# if it is, that it matches the exact version that we require in order to\n# standardize the YAML manifests for CRDs and Kubernetes Roles.\n#\n# If the locally-installed controller-gen does not match the required version,\n# prints an error message asking the user to uninstall it.\n#\n# NOTE: We use this technique of building using `go build` within a temp\n# directory because controller-tools does not have a binary release artifact\n# for controller-gen.\n#\n# See: https://github.com/kubernetes-sigs/controller-tools/issues/500\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\"; pwd)\nROOT_DIR=\"$SCRIPTS_DIR/..\"\nCONTROLLER_TOOLS_VERSION=\"v0.4.0\"\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nif ! is_installed controller-gen; then\n    # GOBIN not always set... so default to installing into $GOPATH/bin if\n    # not...\n    __install_dir=${GOBIN:-$GOPATH/bin}\n    __install_path=\"$__install_dir/controller-gen\"\n    __work_dir=$(mktemp -d /tmp/controller-gen-XXX)\n\n    echo -n \"installing controller-gen ${CONTROLLER_TOOLS_VERSION} ... \"\n    cd \"$__work_dir\"\n\n    go mod init tmp 1>/dev/null 2>&1\n    go get -d \"sigs.k8s.io/controller-tools/cmd/controller-gen@${CONTROLLER_TOOLS_VERSION}\" 1>/dev/null 2>&1\n    go build -o \"$__work_dir/controller-gen\" sigs.k8s.io/controller-tools/cmd/controller-gen 1>/dev/null 2>&1\n    mv \"$__work_dir/controller-gen\" \"$__install_path\"\n\n    rm -rf \"$WORK_DIR\"\n    echo \"ok.\"\nfi\n", "num_lines": 44}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/install-kind.sh [<kind version>]\n#\n# Installs KinD if not installed. Optional parameter specifies the version of\n# KinD to install. Defaults to the value of the environment variable\n# \"KIND_VERSION\" and if that is not set, the value of the DEFAULT_KIND_VERSION\n# variable.\n#\n# NOTE: uses `sudo mv` to relocate a downloaded binary to /usr/local/bin/kind\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\"; pwd)\nROOT_DIR=\"$SCRIPTS_DIR/..\"\nDEFAULT_KIND_VERSION=\"0.9.0\"\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\n__kind_version=\"$1\"\nif [ \"x$__kind_version\" == \"x\" ]; then\n    __kind_version=${KIND_VERSION:-$DEFAULT_KIND_VERSION}\nfi\n\nif ! is_installed kind; then\n    __kind_url=\"https://kind.sigs.k8s.io/dl/v${__kind_version}/kind-linux-amd64\"\n    echo -n \"installing kind from $__kind_url ... \"\n    curl --silent -Lo ./kind \"$__kind_url\"\n    chmod +x ./kind\n    sudo mv ./kind /usr/local/bin/kind\n    echo \"ok.\"\nfi\n", "num_lines": 33}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/install-kubectl.sh\n#\n# Installs the latest stable version kubectl if not installed.\n#\n# NOTE: uses `sudo mv` to relocate a downloaded binary to /usr/local/bin/kubectl\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\"; pwd)\nROOT_DIR=\"$SCRIPTS_DIR/..\"\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nif ! is_installed kubectl; then\n    __platform=$(uname | tr '[:upper:]' '[:lower:]')\n    __stable_k8s_version=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)\n    __kubectl_url=\"https://storage.googleapis.com/kubernetes-release/release/$__stable_k8s_version/bin/$__platform/amd64/kubectl\"\n    echo -n \"installing kubectl from $__kubectl_url ... \"\n    curl --silent -Lo ./kubectl \"$__kubectl_url\"\n    chmod +x ./kubectl\n    sudo mv ./kubectl /usr/local/bin/kubectl\n    echo \"ok.\"\nfi\n", "num_lines": 26}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/install-kustomize.sh\n#\n# Installs the latest version kustomize if not installed.\n#\n# NOTE: uses `sudo mv` to relocate a downloaded binary to /usr/local/bin/kustomize\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\"; pwd)\nROOT_DIR=\"$SCRIPTS_DIR/..\"\n\nsource \"$SCRIPTS_DIR/lib/common.sh\"\n\nif ! is_installed kustomize ; then\n    __kustomize_url=\"https://raw.githubusercontent.com/kubernetes-sigs/kustomize/master/hack/install_kustomize.sh\"\n    echo -n \"installing kustomize from $__kustomize_url ... \"\n    curl --silent \"$__kustomize_url\" | bash 1>/dev/null\n    chmod +x kustomize\n    sudo mv kustomize /usr/local/bin/kustomize\n    echo \"ok.\"\nfi\n", "num_lines": 24}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# A script that provisions a KinD Kubernetes cluster for local development and\n# testing\n\nset -Eo pipefail\n\nSCRIPTS_DIR=$(cd \"$(dirname \"$0\")\"; pwd)\nROOT_DIR=\"$SCRIPTS_DIR/..\"\n\nsource \"$SCRIPTS_DIR\"/lib/common.sh\n\ncheck_is_installed uuidgen\ncheck_is_installed wget\ncheck_is_installed docker\ncheck_is_installed kind \"You can install kind with the helper scripts/install-kind.sh\"\n\nOVERRIDE_PATH=0\nKIND_CONFIG_FILE=\"$SCRIPTS_DIR/kind-two-node-cluster.yaml\"\n\nK8_1_26=\"kindest/node:v1.26.3@sha256:94eb63275ad6305210041cdb5aca87c8562cc50fa152dbec3fef8c58479db4ff\"\nK8_1_25=\"kindest/node:v1.25.8@sha256:b5ce984f5651f44457edf263c1fe93459df8d5d63db7f108ccf5ea4b8d4d9820\"\nK8_1_24=\"kindest/node:v1.24.12@sha256:0bdca26bd7fe65c823640b14253ea7bac4baad9336b332c94850f84d8102f873\"\nK8_1_23=\"kindest/node:v1.23.17@sha256:f935044f60483d33648d8c13decd79557cf3e916363a3c9ba7e82332cb249cba\"\nK8_1_22=\"kindest/node:v1.22.17@sha256:ed0f6a1cd1dcc0ff8b66257b3867e4c9e6a54adeb9ca31005f62638ad555315c\"\nK8_1_21=\"kindest/node:v1.21.14@sha256:75047f07ef306beff928fdc1f171a8b81fae1628f7515bdabc4fc9c31b698d6b\"\nK8_1_20=\"kindest/node:v1.20.15@sha256:cceb1bfeb9fe7c65e344a6372ef6ef4a349d6d7aefba621b822f44cff0070cfd\"\nK8_1_19=\"kindest/node:v1.19.4@sha256:796d09e217d93bed01ecf8502633e48fd806fe42f9d02fdd468b81cd4e3bd40b\"\n\nK8_VERSION=\"$K8_1_23\"\n\nUSAGE=\"\nUsage:\n  $(basename \"$0\") CLUSTER_NAME [-v K8S_VERSION]\n\nProvisions a KinD cluster for local development and testing.\n\nExample: $(basename \"$0\") my-test -v 1.16\n\n      Optional:\n        -v          K8s version to use in this test\n\"\n\ncluster_name=\"$1\"\nif [[ -z \"$cluster_name\" ]]; then\n    echo \"FATAL: required cluster name argument missing.\"\n    echo \"${USAGE}\" 1>&2\n    exit 1\nfi\n\nshift\n\n# Process our input arguments\nwhile getopts \"b:i:v:k:\" opt; do\n  case ${opt} in\n    v ) # K8s version to provision\n        OPTARG=\"K8_$(echo \"${OPTARG}\" | sed 's/\\./\\_/g')\"\n        if [ ! -z ${OPTARG+x} ]; then\n            K8_VERSION=${!OPTARG}\n        else\n            echo \"K8s version not supported\" 1>&2\n            exit 2\n        fi\n      ;;\n    \\? )\n        echo \"${USAGE}\" 1>&2\n        exit\n      ;;\n  esac\ndone\n\nTMP_DIR=$ROOT_DIR/build/tmp-$cluster_name\nmkdir -p \"${TMP_DIR}\"\n\ndebug_msg \"kind: using Kubernetes $K8_VERSION\"\necho -n \"creating kind cluster $cluster_name ... \"\nfor i in $(seq 0 5); do\n  if [[ -z $(kind get clusters 2>/dev/null | grep $cluster_name) ]]; then\n      kind create cluster -q --name \"$cluster_name\" --image $K8_VERSION --config \"$KIND_CONFIG_FILE\" --kubeconfig $TMP_DIR/kubeconfig 1>&2 || :\n  else\n      break\n  fi\ndone\necho \"ok.\"\n\necho \"$cluster_name\" > $TMP_DIR/clustername\n\n", "num_lines": 88}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# ./scripts/test-with-kind.sh\n#\n# Runs integration tests against a kind cluster. This is mostly intended for\n# automated build systems, but can be used by developers on appropriately configured\n# linux machines as well.\n#\n# Configuration is done through environment variables. All of the following\n# must be set:\n#\n#   AWS_ACCOUNT_ID: aws account id to use in testing\n#   VPC_ID: aws vpc id to use for the tests\n#   AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN: session tokens to use\n#\n# There are some additional options that may be set:\n#\n#   AWS_REGION: region to run tests in (defaults to us-west-2)\n#   TEST_SUITES: space-separated set of test suites to run (e.g. \"mesh sidecar virtualnode\").\n#                If unset, all test suites are run.\n#   K8S_VERSION: kubernetes version to use with the tests (default 1.17)\n#   CLUSTER_NAME, KUBECONFIG: can be set to an existing kind cluster. If unset,\n#                             a new cluster will be created and used for the tests.\n#\n\nset -eo pipefail\n\nSCRIPTS_DIR=\"$(cd \"$(dirname \"$0\")\" || exit 1; pwd)\"\nROOT_DIR=\"$(cd \"$SCRIPTS_DIR/..\" || exit 1; pwd)\"\nINT_TEST_DIR=\"$ROOT_DIR/test/integration\"\n\nsource \"$SCRIPTS_DIR/lib/aws.sh\"\nsource \"$SCRIPTS_DIR/lib/common.sh\"\nsource \"$SCRIPTS_DIR/lib/k8s.sh\"\n\ncheck_is_installed curl\ncheck_is_installed docker\ncheck_is_installed jq\ncheck_is_installed uuidgen\ncheck_is_installed wget\ncheck_is_installed kind \"You can install kind with the helper scripts/install-kind.sh\"\ncheck_is_installed kubectl \"You can install kubectl with the helper scripts/install-kubectl.sh\"\ncheck_is_installed kustomize \"You can install kustomize with the helper scripts/install-kustomize.sh\"\ncheck_is_installed controller-gen \"You can install controller-gen with the helper scripts/install-controller-gen.sh\"\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n  echo \"Must set 'AWS_ACCOUNT_ID'\" >&2\n  exit 1\nfi\nAWS_REGION=\"${AWS_REGION:-\"us-west-2\"}\"\n\nif [[ -z \"$VPC_ID\" ]]; then\n  echo \"Must set 'VPC_ID'\" >&2\n  exit 1\nfi\n\nif [[ -z \"$AWS_ACCESS_KEY_ID\" || -z \"$AWS_SECRET_ACCESS_KEY\" || -z \"$AWS_SESSION_TOKEN\" ]]; then\n  echo \"AWS credentials must be set in env: 'AWS_ACCESS_KEY_ID', 'AWS_SECRET_ACCESS_KEY',\" \\\n    \" and 'AWS_SESSION_TOKEN' must all be set\" >&2\n  exit 1\nfi\n\nif [[ -z \"$TEST_SUITES\" ]]; then\n  TEST_SUITES=\"$(ls \"$INT_TEST_DIR\")\"\nfi\n\nK8S_VERSION=${K8S_VERSION:-\"1.17\"}\n\n# Creates a kind test cluster if none was provided.\nif [[ -z \"$CLUSTER_NAME\" || -z \"$KUBECONFIG\" ]]; then\n  echo \"No test cluster detected, creating one...\"\n  CLUSTER_NAME=\"appmesh-test-$(uuidgen | cut -d'-' -f1 | tr '[:upper:]' '[:lower:]')\"\n  TMP_DIR=$ROOT_DIR/build/tmp-$CLUSTER_NAME\n  $SCRIPTS_DIR/provision-kind-cluster.sh \"${CLUSTER_NAME}\" -v \"${K8S_VERSION}\"\n  KUBECONFIG=\"$TMP_DIR\"/kubeconfig\nelse\n  echo \"Using existing cluster '$CLUSTER_NAME' for testing...\"\nfi\n\nCONTROLLER_IMAGE=\"appmesh-controller\"\nCONTROLLER_TAG=\"local\"\n\nIMAGE_HOST=\"840364872350.dkr.ecr.us-west-2.amazonaws.com\"\n\nENVOY_IMAGE=\"$IMAGE_HOST/aws-appmesh-envoy\"\nENVOY_LATEST_TAG=\"v1.25.4.0-prod\"\nENVOY_1_22_TAG=\"v1.22.2.0-prod\"\n\nPROXY_ROUTE_IMAGE=\"$IMAGE_HOST/aws-appmesh-proxy-route-manager\"\nPROXY_ROUTE_TAG=\"v7-prod\"\n\nfunction install_crds {\n    echo \"installing CRDs ... \"\n    make install\n    echo \"ok.\"\n}\n\n# Fetches and builds all required images, and loads them into kind. Kind does\n# not inherit the docker registration settings for the host, so preloading\n# the images is necessary to make sure it has the required values.\nfunction build_and_load_images {\n  docker buildx build --platform linux/amd64 --build-arg GOPROXY=\"$GOPROXY\" -t \"$CONTROLLER_IMAGE:$CONTROLLER_TAG\" . --load\n  kind load docker-image --name \"$CLUSTER_NAME\" \"$CONTROLLER_IMAGE:$CONTROLLER_TAG\"\n\n  ecr_login \"$AWS_REGION\" \"$IMAGE_HOST\"\n\n  local __images=(\n      \"$PROXY_ROUTE_IMAGE:$PROXY_ROUTE_TAG\"\n      \"$ENVOY_IMAGE:$ENVOY_LATEST_TAG\"\n      \"$ENVOY_IMAGE:$ENVOY_1_22_TAG\"\n  )\n  for image in \"${__images[@]}\"; do\n      docker pull \"$image\"\n      kind load docker-image --name \"$CLUSTER_NAME\" \"$image\"\n  done\n}\n\nfunction run_integration_tests {\n  echo running tests\n\n  kubectl delete ns appmesh-system || :\n  kubectl create ns appmesh-system\n\n  for __test in ${TEST_SUITES[@]}; do\n    local __test_dir=\"test/integration/$__test\"\n    local __envoy_version=\"$ENVOY_LATEST_TAG\"\n\n    # /test_app contains test app images, and is not itself an integration test\n    if [[ \"$__test\" == \"test_app\" ]]; then\n      continue\n    fi\n\n    # This test specifically tests behavior for an older version of envoy\n    if [[ \"$__test\" == \"sidecar-v1.22\" ]]; then\n        __envoy_version=\"$ENVOY_1_22_TAG\"\n    fi\n\n    # Try to delete the controller. Sometimes, carrying over controllers\n    # between tests can cause some minor issues.\n    helm delete -n=appmesh-system appmesh-controller || :\n\n    helm upgrade -i appmesh-controller config/helm/appmesh-controller --namespace appmesh-system \\\n      --set image.repository=\"$CONTROLLER_IMAGE\" \\\n      --set image.tag=\"$CONTROLLER_TAG\" \\\n      --set sidecar.image.repository=\"$ENVOY_IMAGE\" \\\n      --set sidecar.image.tag=\"$__envoy_version\" \\\n      --set enableBackendGroups=true \\\n      --set sidecar.waitUntilProxyReady=true \\\n      --set region=\"$AWS_REGION\" \\\n      --set accountId=\"$AWS_ACCOUNT_ID\" \\\n      --set \"env.AWS_DEFAULT_REGION='$AWS_REGION'\" \\\n      --set \"env.AWS_ACCESS_KEY_ID='$AWS_ACCESS_KEY_ID'\" \\\n      --set \"env.AWS_SECRET_ACCESS_KEY='$AWS_SECRET_ACCESS_KEY'\" \\\n      --set \"env.AWS_SESSION_TOKEN='$AWS_SESSION_TOKEN'\" \\\n      --set sidecar.envoyAwsAccessKeyId=\"$AWS_ACCESS_KEY_ID\" \\\n      --set sidecar.envoyAwsSecretAccessKey=\"$AWS_SECRET_ACCESS_KEY\" \\\n      --set sidecar.envoyAwsSessionToken=\"$AWS_SESSION_TOKEN\"\n\n    check_deployment_rollout appmesh-controller appmesh-system\n    kubectl get pod -n appmesh-system\n\n    echo -n \"running integration test type $__test ... \"\n    ginkgo --flakeAttempts=2 -vv -r $__test_dir -- \\\n      --cluster-kubeconfig=\"$KUBECONFIG\" \\\n      --cluster-name=\"$CLUSTER_NAME\" \\\n      --aws-region=\"$AWS_REGION\" \\\n      --aws-vpc-id=\"$VPC_ID\"\n    echo \"ok.\"\n  done\n}\n\naws_check_credentials\n\nbuild_and_load_images\n\n# Generate and install CRDs\ninstall_crds\nkubectl get crds\n\nrun_integration_tests\n", "num_lines": 181}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\n# aws_check_credentials() calls the STS::GetCallerIdentity API call and\n# verifies that there is a local identity for running AWS commands\naws_check_credentials() {\n    echo -n \"checking AWS credentials ... \"\n    aws sts get-caller-identity --query \"Account\" >/dev/null ||\n        ( echo \"\\nFATAL: No AWS credentials found. Please run \\`aws configure\\` to set up the CLI for your credentials.\" && exit 1 )\n    echo \"ok.\"\n}\n\naws_account_id() {\n    JSON=$( aws sts get-caller-identity --output json || exit 1 )\n    echo \"${JSON}\" | jq --raw-output \".Account\"\n}\n\necr_login() {\n    echo -n \"ecr login ... \"\n    local __aws_region=$1\n    local __ecr_url=$2\n    local __err_msg=\"Failed ECR login. Please make sure you have IAM permissions to access ECR.\"\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        ( aws ecr get-login-password --region $__aws_region | \\\n                docker login --username AWS --password-stdin $__ecr_url ) ||\n                ( echo \"\\n$__err_msg\" && exit 1 )\n    else\n        $( aws ecr get-login --no-include-email ) || ( echo \"\\n$__err_msg\" && exit 1 )\n    fi\n    echo \"ok.\"\n}\n", "num_lines": 33}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# check_is_installed checks to see if the supplied executable is installed and\n# exits if not. An optional second argument is an extra message to display when\n# the supplied executable is not installed.\n#\n# Usage:\n#\n#   check_is_installed PROGRAM [ MSG ]\n#\n# Example:\n#\n#   check_is_installed kind \"You can install kind with the helper scripts/install-kind.sh\"\ncheck_is_installed() {\n    local __name=\"$1\"\n    local __extra_msg=\"$2\"\n    if ! is_installed \"$__name\"; then\n        echo \"FATAL: Missing requirement '$__name'\"\n        echo \"Please install $__name before running this script.\"\n        if [[ -n $__extra_msg ]]; then\n            echo \"\"\n            echo \"$__extra_msg\"\n            echo \"\"\n        fi\n        exit 1\n    fi\n}\n\nis_installed() {\n    local __name=\"$1\"\n    if $(which $__name >/dev/null 2>&1); then\n        return 0\n    else\n        return 1\n    fi\n}\n\n# vpc_id fetches the vpc id of the GitHub Actions runner/EC2 instance.\n# vpc id is needed for setting up AWS CloudMap namespaces\nvpc_id() {\n    local __md_url=\"http://169.254.169.254/latest/meta-data/network/interfaces\"\n    local __macid=$( curl ${__md_url}/macs/ || exit 1 )\n    local __vpcid=$( curl ${__md_url}/macs/${__macid}vpc-id || exit 1 )\n    echo \"$__vpcid\"\n\n}\n\nDEFAULT_DEBUG_PREFIX=\"DEBUG: \"\n\n# debug_msg prints out a supplied message if the DEBUG environs variable is\n# set. An optional second argument indicates the \"indentation level\" for the\n# message. If the indentation level argument is missing, we look for the\n# existence of an environs variable called \"indent_level\" and use that\ndebug_msg() {\n    local __msg=${1:-}\n    local __indent_level=${2:-}\n    local __debug=\"${DEBUG:-\"\"}\"\n    local __debug_prefix=\"${DEBUG_PREFIX:-$DEFAULT_DEBUG_PREFIX}\"\n    if [ ! -n \"$__debug\" ]; then\n        return 0\n    fi\n    __indent=\"\"\n    if [ -n \"$__indent_level\" ]; then\n        __indent=\"$( for each in $( seq 0 $__indent_level ); do printf \" \"; done )\"\n    fi\n    echo \"$__debug_prefix$__indent$__msg\"\n}\n", "num_lines": 68}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nROOT_DIR=\"$THIS_DIR/../..\"\nSCRIPTS_DIR=\"$ROOT_DIR/scripts\"\n\n# resource_exists returns 0 when the supplied resource can be found, 1\n# otherwise. An optional second parameter overrides the Kubernetes namespace\n# argument\nk8s_resource_exists() {\n    local __res_name=${1:-}\n    local __namespace=${2:-}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl get $__args \"$__res_name\" >/dev/null 2>&1\n}\n\n\n# check_deployment_rollout watches the status of the latest rollout\n# until it's done or until the timeout. Namespace and timeout are optional\n# parameters\ncheck_deployment_rollout() {\n    local __dep_name=${1:-}\n    local __namespace=${2:-}\n    local __timeout=${3:-\"2m\"}\n    local __args=\"\"\n    if [ -n \"$__namespace\" ]; then\n        __args=\"$__args-n $__namespace\"\n    fi\n    kubectl rollout status deployment/\"$__dep_name\" $__args --timeout=$__timeout\n}\n", "num_lines": 34}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca\n\nrm $DIR/*.csr\n", "num_lines": 20}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nrm certs/*key\nrm certs/*pem\nrm certs/*cert_chain.pem\nrm certs/*.generated\nrm certs/node-*\n", "num_lines": 8}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate RSA certs for the Virtual Node passed in via $1\necho \"Generating backend certificate.\"\ngenerate_rsa_key $1 ca\ngenerate_x509_cert $1 ca\ngenerate_cert_chain $1 ca\n\nrm $DIR/*.csr\n", "num_lines": 42}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#/bin/bash\n\nset -e\n\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\n\necho \"Registering an entry for spire agent...\"\nregister_server_entries \\\n  -spiffeID spiffe://mtls-e2e.aws/ns/spire/sa/spire-agent \\\n  -selector k8s_sat:cluster:eks-cluster \\\n  -selector k8s_sat:agent_ns:spire \\\n  -selector k8s_sat:agent_sa:spire-agent \\\n  -node\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#/bin/bash\n\nset -e\n\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\necho \"Registering an entry for the virtualnode...\"\nregister_server_entries \\\n  -parentID spiffe://mtls-e2e.aws/ns/spire/sa/spire-agent \\\n  -spiffeID spiffe://mtls-e2e.aws/$1 \\\n  -selector k8s:ns:mtls-e2e \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app.kubernetes.io/instance:$1 \\\n  -selector k8s:container-name:envoy\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ndeploySpire() {\n    kubectl apply -f certs/spire_setup.yaml\n}\n\ndeleteSpire() {\n    kubectl delete -f certs/spire_setup.yaml\n}\n\necho \"Installing SPIRE Server and Agent\"\nif [ \"$1\" == \"deploy\" ]; then\n  deploySpire\nelif [ \"$1\" == \"delete\" ]; then\n  deleteSpire\nfi\n", "num_lines": 19}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca\n\nrm $DIR/*.csr\n", "num_lines": 20}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nrm certs/*key\nrm certs/*pem\nrm certs/*cert_chain.pem\nrm certs/*.generated\nrm certs/node-*\n", "num_lines": 8}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate RSA certs for the Virtual Node passed in via $1\necho \"Generating backend certificate.\"\ngenerate_rsa_key $1 ca\ngenerate_x509_cert $1 ca\ngenerate_cert_chain $1 ca\n\nrm $DIR/*.csr\n", "num_lines": 42}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#/bin/bash\n\nset -e\n\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\n\necho \"Registering an entry for spire agent...\"\nregister_server_entries \\\n  -spiffeID spiffe://mtls-e2e.aws/ns/spire/sa/spire-agent \\\n  -selector k8s_sat:cluster:eks-cluster \\\n  -selector k8s_sat:agent_ns:spire \\\n  -selector k8s_sat:agent_sa:spire-agent \\\n  -node\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#/bin/bash\n\nset -e\n\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\necho \"Registering an entry for the virtualnode...\"\nregister_server_entries \\\n  -parentID spiffe://mtls-e2e.aws/ns/spire/sa/spire-agent \\\n  -spiffeID spiffe://mtls-e2e.aws/$1 \\\n  -selector k8s:ns:mtls-e2e \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app.kubernetes.io/instance:$1 \\\n  -selector k8s:container-name:envoy\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ndeploySpire() {\n    kubectl apply -f certs/spire_setup.yaml\n}\n\ndeleteSpire() {\n    kubectl delete -f certs/spire_setup.yaml\n}\n\necho \"Installing SPIRE Server and Agent\"\nif [ \"$1\" == \"deploy\" ]; then\n  deploySpire\nelif [ \"$1\" == \"delete\" ]; then\n  deleteSpire\nfi\n", "num_lines": 19}
{"repo_name": "aws-app-mesh-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca_1\ngenerate_ca ca_2\n\n# Generate RSA cert for the backend-tls app\necho \"Generating backend certificate.\"\ngenerate_rsa_key backend-tls ca_1\ngenerate_x509_cert backend-tls ca_1\ngenerate_cert_chain backend-tls ca_1\n\nrm $DIR/*.csr\n", "num_lines": 55}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsource ~/.bash_profile\n\nbase_path=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-clusterresources\" \\\n    --capabilities CAPABILITY_NAMED_IAM \\\n    --template-file \"${base_path}/../templates/ecs-mesh.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    Namespace=\"${NAMESPACE}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\"\n\nAPP_URI=$(aws --region ${AWS_REGION} \\\n                cloudformation describe-stacks \\\n                --stack-name ${ENVIRONMENT_NAME}-clusterresources \\\n                --query \"Stacks[0].Outputs[?OutputKey=='PublicLoadBalancer'].OutputValue\" --output text)\n\necho \"export APP_URI=${APP_URI}\" | tee -a ~/.bash_profile\n", "num_lines": 25}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# Load environment variables\nsource ~/.bash_profile\n\nbase_path=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-monitoring-resources\" \\\n    --capabilities CAPABILITY_NAMED_IAM \\\n    --template-file \"${base_path}/../templates/create-prometheus-env.yaml\" \\\n    --parameter-overrides \\\n    ECSClusterName=\"${ENVIRONMENT_NAME}\" \\\n    CreateIAMRoles=\"True\"", "num_lines": 17}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n# Load environment variables\nsource ~/.bash_profile\n\nsample_microservices=(\n    \"yelb-db:5432:tcp\"\n    \"yelb-redisserver:6379:tcp\"\n    \"yelb-appserver:4567:http\"\n    \"yelb-ui:80:http\"\n)\n\nfor item in \"${sample_microservices[@]}\"; do\n    MICROSERVICE=$(echo $item | awk -F ':' '{print $1}')\n    PORT=$(echo $item | awk -F ':' '{print $2}')\n    PROTOCOL=$(echo $item | awk -F ':' '{print $3}')\n    echo \"Deploying ${MICROSERVICE}\"\n    aws cloudformation create-stack --stack-name ${ENVIRONMENT_NAME}-pipeline-${MICROSERVICE} \\\n    --template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/pipeline_stack/pipeline_cloudformation.yml\" \\\n    --parameters ParameterKey=MicroserviceName,ParameterValue=${MICROSERVICE} \\\n    ParameterKey=SharedStackName,ParameterValue=\"$SHARED_STACK_NAME\" \\\n    ParameterKey=EnvironmentName,ParameterValue=\"$ENVIRONMENT_NAME\" \\\n    ParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\n    ParameterKey=SampleMicroservices,ParameterValue=\"$USE_SAMPLE_MICROSERVICES\" \\\n    ParameterKey=Port,ParameterValue=\"$PORT\" \\\n    ParameterKey=Protocol,ParameterValue=\"$PROTOCOL\" \\\n    --capabilities CAPABILITY_IAM \\\n    --region $AWS_REGION\ndone\n\nfor item in \"${sample_microservices[@]}\"; do\n    microservice=\"${item%%:*}\"\n    while [ \"$(aws cloudformation describe-stacks --stack-name ${ENVIRONMENT_NAME}-pipeline-${MICROSERVICE} --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ] ; do\n        echo -n '.'\n        sleep 10\n    done\n    if [ \"$(aws cloudformation describe-stacks --stack-name ${ENVIRONMENT_NAME}-pipeline-${MICROSERVICE} --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" != \"CREATE_COMPLETE\" ] ; then\n        echo -e \"\\nAn error occurred while creating the stack ${MICROSERVICE}! Don't move forward before fixing it!\"\n        exit 1\n    fi\ndone\necho -e \"\\nAll CloudFormation stacks created successfully!\"\n", "num_lines": 45}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n# Load environment variables\nsource ~/.bash_profile\n\n# Get the base directory path that will be used to zip the resources before uploading to S3\nbase_path=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n#Checking for jq utility.\nif ! command -v jq >/dev/null 2>&1; then\n sudo yum install jq -y \nfi\n\n# Zip the microservice resources\necho \"Starting the zipping activity of the microservices code\"\ncd $base_path/../../microservices/yelb-ui && zip -r yelb-ui.zip ./* > /dev/null\ncd $base_path/../../microservices/yelb-db && zip -r yelb-db.zip ./* > /dev/null\ncd $base_path/../../microservices/yelb-appserver && zip -r yelb-appserver.zip ./* > /dev/null\ncd $base_path/../../microservices/yelb-redisserver && zip -r yelb-redisserver.zip ./* > /dev/null\necho \"Successfully completed the zipping activity of the microservices code\"\n\n# Zip the lambda function resources\necho \"Starting the zipping activity of the lambda code\"\ncd $base_path/../../shared_stack/lambda_functions/check_deployment_version && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/deploy_canary_infrastructure && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/gather_healthcheck_status && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/remove_previous_canary_components && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/rollbackto_previous_canary && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/start_canary && zip -r function.zip ./* > /dev/null\ncd $base_path/../../shared_stack/lambda_functions/update_deployment_version && zip -r function.zip ./* > /dev/null\necho \"Successfully completed the zipping activity of the lambda code\"\n\n# Move back to the base directory\ncd $base_path/../../\n\n# Create a new S3 bucket with a random name suffix because S3 bucket names are unique\nRANDOM_STRING=$(LC_ALL=C tr -dc 'a-z' </dev/urandom | head -c 10 ; echo)\nS3_BUCKET_NAME=$(aws s3 mb s3://ecs-canary-blogpost-cloudformation-files-$RANDOM_STRING --region $AWS_REGION | cut -d' ' -f2)\necho \"export S3_BUCKET_NAME=${S3_BUCKET_NAME}\" | tee -a ~/.bash_profile\n\n# Upload the resources to the bucket created\naws s3 cp ./ s3://$S3_BUCKET_NAME --recursive --exclude \"^\\.\" --region $AWS_REGION > /dev/null\n\n# Deploy AWS CloudFormation Stack\naws cloudformation create-stack --stack-name $SHARED_STACK_NAME \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/shared_stack/stepfunctions_cloudformation.yml\" \\\n--parameters ParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" ParameterKey=EnvironmentName,ParameterValue=\"${ENVIRONMENT_NAME}\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\n# aws cloudformation wait stack-create-complete --stack-name $SHARED_STACK_NAME <Until the bug gets fixed, use the below workaround>\necho -n \"Creating the AWS CloudFormation stack\"\nwhile [ \"$(aws cloudformation describe-stacks --stack-name $SHARED_STACK_NAME --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ]; do\n  echo -n '.'\n  sleep 10\ndone\necho -e \"\\n$(aws cloudformation describe-stacks --stack-name $SHARED_STACK_NAME --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\"\n", "num_lines": 59}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsource ~/.bash_profile\n\nbase_path=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${base_path}/../templates/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n# Default variables that were used on the blog post (you can change them to fit your needs)\nAWS_REGION=us-west-2\nENVIRONMENT_NAME=ecs-blogpost\nNAMESPACE=yelb.local\nENVOY_IMAGE=public.ecr.aws/appmesh/aws-appmesh-envoy:v1.25.1.0-prod\nSHARED_STACK_NAME=${ENVIRONMENT_NAME}-deployment-stepfunctions\nBUILD_COMPUTE_TYPE=BUILD_GENERAL1_SMALL\nUSE_SAMPLE_MICROSERVICES='True'\n\n# Add environment variables to bash_profile\necho \"export AWS_REGION=${AWS_REGION}\" | tee -a ~/.bash_profile\necho \"export ENVIRONMENT_NAME=${ENVIRONMENT_NAME}\" | tee -a ~/.bash_profile\necho \"export NAMESPACE=${NAMESPACE}\" | tee -a ~/.bash_profile\necho \"export ENVOY_IMAGE=${ENVOY_IMAGE}\" | tee -a ~/.bash_profile\necho \"export SHARED_STACK_NAME=${SHARED_STACK_NAME}\" | tee -a ~/.bash_profile\necho \"export BUILD_COMPUTE_TYPE=${BUILD_COMPUTE_TYPE}\" | tee -a ~/.bash_profile\necho \"export USE_SAMPLE_MICROSERVICES=${USE_SAMPLE_MICROSERVICES}\" | tee -a ~/.bash_profile\n", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nexport AWS_PAGER=\"\"\n\ndelete_cfn_stack() {\n    profile=$1\n    stack_name=$2\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\" in profile \\\"${profile}\\\"...\"\n    aws --profile $profile cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws --profile $profile cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo -e \"Done\\n\"\n}\n\nPROJECT_NAME=am-ecs-multi-account\n\ndelete_cfn_stack \"frontend\" \"${PROJECT_NAME}-frontend-and-appserver\"\ndelete_cfn_stack \"frontend\" \"${PROJECT_NAME}-appmesh-resources\"\ndelete_cfn_stack \"frontend\" \"${PROJECT_NAME}-infra\"\ndelete_cfn_stack \"backend\" \"${PROJECT_NAME}-resource-share\"\ndelete_cfn_stack \"backend\" \"${PROJECT_NAME}-redis-and-database\"\ndelete_cfn_stack \"backend\" \"${PROJECT_NAME}-appmesh-resources\"\ndelete_cfn_stack \"backend\" \"${PROJECT_NAME}-infra\"\n\naws --profile backend appmesh delete-mesh --mesh-name yelb\n\necho -e \"Cleanup complete.\"\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "# Delete the CF Stack\n\n\naws cloudformation delete-stack --stack-name appmesh-components\naws cloudformation delete-stack --stack-name appmesh-acm\naws cloudformation delete-stack --stack-name appmesh-nodejs\naws cloudformation delete-stack --stack-name appmesh-frontend-crystal\n\n", "num_lines": 9}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "# Please modify the envoy image parameter with the latest image from  https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html \n# Create YAML file #\ncat <<-\"EOF\" > /tmp/install_envoy.yml\n---\nschemaVersion: '2.2'\ndescription: Install Envoy Proxy\nparameters: \n  envoyimage:\n    type: String\n  region:\n    type: String\n  meshName:\n    type: String\n  vNodeName:\n    type: String \n  ignoredUID:\n    type: String\n    default: '1337'\n  proxyIngressPort:\n    type: String\n    default: '15000'\n  proxyEgressPort:\n    type: String\n    default: '15001'\n  appPorts:\n    type: String\n  egressIgnoredIPs:\n    type: String\n    default: '169.254.169.254,169.254.170.2'\n  egressIgnoredPorts:\n    type: String \n    default: '22'\nmainSteps:\n- action: aws:configureDocker\n  name: configureDocker\n  inputs:\n    action: Install\n- action: aws:runShellScript\n  name: installEnvoy\n  inputs:\n    runCommand: \n      - |\n        #! /bin/bash -ex\n        sudo yum install -y jq\n        $(aws ecr get-login --no-include-email --region {{region}} --registry-ids 840364872350)\n        # Install and run envoy\n        sudo docker run --detach \\\n          --env APPMESH_RESOURCE_ARN=mesh/{{meshName}}/virtualNode/{{vNodeName}} \\\n          --env ENABLE_ENVOY_XRAY_TRACING=1 \\\n          --log-driver=awslogs \\\n          --log-opt awslogs-region={{region}} \\\n          --log-opt awslogs-create-group=true \\\n          --log-opt awslogs-group=appmesh-workshop-frontend-envoy \\\n          --log-opt tag=ec2/envoy/{{.FullID}} \\\n          -u {{ignoredUID}} --network host \\\n          {{envoyimage}}\n- action: aws:runShellScript\n  name: installXRay\n  inputs:\n    runCommand: \n      - |\n        #! /bin/bash -ex\n        XRAY_HOST=https://s3.dualstack.{{region}}.amazonaws.com\n        XRAY_PATH=aws-xray-assets.{{region}}/xray-daemon/aws-xray-daemon-3.x.rpm\n        # Install and run xray daemon\n        sudo curl $XRAY_HOST/$XRAY_PATH -o /tmp/xray.rpm\n        sudo yum install -y /tmp/xray.rpm\n- action: aws:runShellScript\n  name: enableRouting\n  inputs:\n    runCommand: \n      - |\n        #! /bin/bash -ex\n        APPMESH_LOCAL_ROUTE_TABLE_ID=\"100\"\n        APPMESH_PACKET_MARK=\"0x1e7700ce\"\n        # Initialize chains\n        sudo iptables -t mangle -N APPMESH_INGRESS\n        sudo iptables -t nat -N APPMESH_INGRESS\n        sudo iptables -t nat -N APPMESH_EGRESS\n        sudo ip rule add fwmark \"$APPMESH_PACKET_MARK\" lookup $APPMESH_LOCAL_ROUTE_TABLE_ID\n        sudo ip route add local default dev lo table $APPMESH_LOCAL_ROUTE_TABLE_ID\n        # Enable egress routing\n          # Ignore egress redirect based UID, ports, and IPs\n          sudo iptables -t nat -A APPMESH_EGRESS \\\n            -m owner --uid-owner {{ignoredUID}} \\\n            -j RETURN\n          sudo iptables -t nat -A APPMESH_EGRESS \\\n            -p tcp \\\n            -m multiport --dports \"{{egressIgnoredPorts}}\" \\\n            -j RETURN\n          sudo iptables -t nat -A APPMESH_EGRESS \\\n            -p tcp \\\n            -d \"{{egressIgnoredIPs}}\" \\\n            -j RETURN\n          # Redirect everything that is not ignored\n          sudo iptables -t nat -A APPMESH_EGRESS \\\n            -p tcp \\\n            -j REDIRECT --to {{proxyEgressPort}}\n          # Apply APPMESH_EGRESS chain to non-local traffic\n          sudo iptables -t nat -A OUTPUT \\\n            -p tcp \\\n            -m addrtype ! --dst-type LOCAL \\\n            -j APPMESH_EGRESS\n        # Enable ingress routing\n          # Route everything arriving at the application port to Envoy\n          sudo iptables -t nat -A APPMESH_INGRESS \\\n            -p tcp \\\n            -m multiport --dports \"{{appPorts}}\" \\\n            -j REDIRECT --to-port \"{{proxyIngressPort}}\"\n          # Apply APPMESH_INGRESS chain to non-local traffic\n          sudo iptables -t nat -A PREROUTING \\\n            -p tcp \\\n            -m addrtype ! --src-type LOCAL \\\n            -j APPMESH_INGRESS\nEOF\n# Create ssm document #\naws ssm create-document \\\n  --name appmesh-workshop-installenvoy \\\n  --document-format YAML \\\n  --content file:///tmp/install_envoy.yml \\\n  --document-type Command\nAUTOSCALING_GROUP=$(jq < cfn-crystal.json -r '.RubyAutoScalingGroupName');\n# Create the association with the frontend EC2 instances\naws ssm create-association \\\n  --name appmesh-workshop-installenvoy \\\n  --association-name appmesh-workshop-state \\\n  --targets \"Key=tag:aws:autoscaling:groupName,Values=$AUTOSCALING_GROUP\" \\\n  --max-errors 0 \\\n  --max-concurrency 50% \\\n  --parameters \\\n      \"region=$AWS_REGION,\n        meshName=appmesh-workshop,\n        vNodeName=frontend,\n        envoyimage=$ENVOY_IMAGE,\n        appPorts=3000\"\n", "num_lines": 136}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "export YELB_DB_ENDPOINT=$(aws cloudformation describe-stacks --stack-name yelb-fargate --query \"Stacks[0].Outputs[?OutputKey=='YelbDBEndpointUrl'].OutputValue\" --output text)\nexport POSTGRES_PASSWORD=postgres_password\n\nsudo yum install -y postgresql postgresql-server postgresql-devel postgresql-contrib postgresql-docs\nsudo service postgresql initdb\n#!/bin/bash\nset -e\n\nPGPASSWORD=$POSTGRES_PASSWORD psql --host=$YELB_DB_ENDPOINT --port=5432 --username=postgres <<-EOSQL\n    \\connect yelbdatabase;\n\tCREATE TABLE restaurants (\n    \tname        char(30),\n    \tcount       integer,\n    \tPRIMARY KEY (name)\n\t);\n\tINSERT INTO restaurants (name, count) VALUES ('outback', 0);\n\tINSERT INTO restaurants (name, count) VALUES ('bucadibeppo', 0);\n\tINSERT INTO restaurants (name, count) VALUES ('chipotle', 0);\n\tINSERT INTO restaurants (name, count) VALUES ('ihop', 0);\nEOSQL\n\n", "num_lines": 22}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nsource ${DIR}/.settings\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $VPC ]; then\n    echo \"VPC environment variable is not set. Before proceeding setup a VPC with 2 public subnets and continue.\"\n    exit 1\nfi\n\nif [ -z $PUBLIC_SUBNET_1 ]; then\n    echo \"PUBLIC_SUBNET_1 environment variable is not set. Before proceeding setup a VPC with 2 public subnets and continue.\"\n    exit 1\nfi\n\n\nif [ -z $PUBLIC_SUBNET_2 ]; then\n    echo \"PUBLIC_SUBNET_2 environment variable is not set. Before proceeding setup a VPC with 2 public subnets and continue.\"\n    exit 1\nfi\n\n\nPROJECT_NAME=yelb\nECR_IMAGE_PREFIX=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\nYELB_UI_SRC=\"${DIR}/../../../../yelb-ui\"\nYELB_UI_IMAGE=\"${ECR_IMAGE_PREFIX}/yelb-ui:$(git log -1 --format=%h ${YELB_UI_SRC})\"\nYELB_APP_SRC=\"${DIR}/../../../../yelb-appserver\"\nYELB_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/yelb-appserver:$(git log -1 --format=%h ${YELB_APP_SRC})\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n\n    for f in yelb-ui; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${f} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${f}\n    done\n\n    ecr_login\n    docker build -t ${YELB_UI_IMAGE} ${YELB_UI_SRC} && docker push ${YELB_UI_IMAGE}\n    \n    for f in yelb-appserver; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${f} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${f}\n    done\n\n    docker build -t ${YELB_APP_IMAGE} ${YELB_APP_SRC} && docker push ${YELB_APP_IMAGE}\n    \n} \n\ndeploy_images\naws cloudformation deploy \\\n    --capabilities CAPABILITY_IAM --stack-name yelb-fargate  \\\n    --template-file $DIR/yelb-cloudformation-ECS-AppMesh-deployment.yaml \\\n    --parameter-overrides \\\n    \"VPC=${VPC}\" \\\n    \"PublicSubnetOne=${PUBLIC_SUBNET_1}\" \\\n    \"PublicSubnetTwo=${PUBLIC_SUBNET_2}\" \\\n    \"LaunchType=FARGATE\" \\\n    \"Domain=yelb.local\" \\\n    \"CountOfUiTasks=2\" \\\n    \"CountOfAppserverTasks=3\" \\\n    \"PublicIP=ENABLED\" \\\n    \"Mesh=yelb\" \\\n    \"EnvoyImage=${ENVOY_IMAGE}\" \\\n    \"YelbUIImage=${YELB_UI_IMAGE}\"\\\n    \"YelbAppServerImage=${YELB_APP_IMAGE}\"\n", "num_lines": 92}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install packages\nsudo yum update -y\nsudo yum install jq moreutils -y\n\n# Upgrade pip\nsudo pip3 install --upgrade pip\necho \"export PATH=~/.local/bin:$PATH\" >> ~/.bash_profile\nsource ~/.bash_profile\n\n# Install awscli\npip3 install awscli --upgrade --user\nsource ~/.bash_profile\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n# Delete Gateway Components\naws appmesh delete-gateway-route --gateway-route-name yelbapp-gatewayroute --virtual-gateway yelb-gateway --mesh-name yelb \n\naws appmesh delete-gateway-route --gateway-route-name yelbui-gatewayroute --virtual-gateway yelb-gateway --mesh-name yelb \n\naws appmesh delete-virtual-gateway --virtual-gateway yelb-gateway --mesh-name yelb\n\n\n# Delete Virtual Services (AppServer, UI, DB, Redis and RecipePuppy)\n\naws appmesh delete-virtual-service --mesh-name yelb --virtual-service-name yelb-appserver\n\naws appmesh delete-virtual-service --mesh-name yelb --virtual-service-name redis-server\n\naws appmesh delete-virtual-service --mesh-name yelb --virtual-service-name yelb-db\n\naws appmesh delete-virtual-service --mesh-name yelb --virtual-service-name www.recipepuppy.com\n\naws appmesh delete-virtual-service --mesh-name yelb --virtual-service-name yelb-ui\n\n\n# Delete Virtual Nodes (AppServer, UI, DB, Redis and RecipePuppy)\n\naws appmesh delete-virtual-node --mesh-name yelb --virtual-node-name yelb-redis-server\n\naws appmesh delete-virtual-node --mesh-name yelb --virtual-node-name yelb-db\n\naws appmesh delete-virtual-node --mesh-name yelb --virtual-node-name yelb-recipe\n\naws appmesh delete-virtual-node --mesh-name yelb --virtual-node-name yelb-app-server\n\naws appmesh delete-virtual-node --mesh-name yelb --virtual-node-name yelb-ui\n\n# Delete the mesh\n\naws appmesh delete-mesh --mesh-name yelb", "num_lines": 37}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#Create Virtual Node for Yelb App Server\naws appmesh create-virtual-node --mesh-name yelb --virtual-node-name yelb-app-server --cli-input-json file://yelb-app-vn.json\n\n#Create Virtual service and map it to yelb-app-server\naws appmesh create-virtual-service --cli-input-json file://yelb-app-vs.json", "num_lines": 5}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n#Gets the yelb db endpoint from yelb-fargate cloudformation stack\nexport YELB_DB_ENDPOINT=$(aws cloudformation describe-stacks --stack-name yelb-fargate --query \"Stacks[0].Outputs[?OutputKey=='YelbDBEndpointUrl'].OutputValue\" --output text)\n\n#Pass the DB endpoint to DNS_HostName\ncli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"${YELB_DB_ENDPOINT}\" \\\n        -f \"yelb-db-vn.json\" )\n        \n#Create Virtual Node yelb-db\naws appmesh create-virtual-node --mesh-name yelb --virtual-node-name yelb-db --cli-input-json \"$cli_input\"\n\n#Create Virtual Service and map yelb-db\naws appmesh create-virtual-service --cli-input-json file://yelb-db-vs.json\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n#Creates a Virtual Gateway\naws appmesh create-virtual-gateway --cli-input-json file://yelb-vg.json\n\n\n#Creates Virtual Gateway Route for App\naws appmesh create-gateway-route --cli-input-json file://yelb-app-gateway-route.json\n\n\n#Creates Virtual Gateway Route for UI \naws appmesh create-gateway-route --cli-input-json file://yelb-ui-gateway-route.json\n", "num_lines": 12}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n#Create Virtual Node for Yelb Recipe\naws appmesh create-virtual-node --mesh-name yelb --virtual-node-name yelb-recipe --cli-input-json file://yelb-recipe-vn.json\n\n#Create Virtual Service\naws appmesh create-virtual-service --cli-input-json file://yelb-recipe-vs.json", "num_lines": 6}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#Gets the yelb redis endpoint from yelb-fargate cloudformation stack\nexport YELB_REDIS_ENDPOINT=$(aws cloudformation describe-stacks --stack-name yelb-fargate --query \"Stacks[0].Outputs[?OutputKey=='YelbRedisCacheUrl'].OutputValue\" --output text)\n\n#Pass the endpoint to the dns hostname\ncli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"${YELB_REDIS_ENDPOINT}\" \\\n        -f \"yelb-redis-vn.json\" )\n\n#Create virtual node yelb-redis      \naws appmesh create-virtual-node --mesh-name yelb --virtual-node-name yelb-redis-server --cli-input-json \"$cli_input\"\n\n#Create virtual service and map it to the virtual node\naws appmesh create-virtual-service --cli-input-json file://yelb-redis-vs.json", "num_lines": 13}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n#create virtual node yelb-ui\naws appmesh create-virtual-node --mesh-name yelb --virtual-node-name yelb-ui --cli-input-json file://yelb-ui-vn.json\n\n#create virtual service\naws appmesh create-virtual-service --cli-input-json file://yelb-ui-vs.json", "num_lines": 6}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# when the variable is populated a search domain entry is added to resolv.conf at startup\n# this is needed for the ECS service discovery (a search domain can't be added with awsvpc mode) \nif [ $SEARCH_DOMAIN ]; then echo \"search ${SEARCH_DOMAIN}\" >> /etc/resolv.conf; fi \n\nruby /app/yelb-appserver.rb -o 0.0.0.0", "num_lines": 7}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nNGINX_CONF=/etc/nginx/conf.d/default.conf\ncd clarity-seed\n\n# when the variable is populated a search domain entry is added to resolv.conf at startup\n# this is needed for the ECS service discovery (a search domain can't be added with awsvpc mode) \nif [ $SEARCH_DOMAIN ]; then echo \"search ${SEARCH_DOMAIN}\" >> /etc/resolv.conf; fi \n\nsed -i -- 's#/usr/share/nginx/html#/clarity-seed/'$UI_ENV'/dist#g' $NGINX_CONF\n\n# this adds the reverse proxy configuration to nginx \n# everything that hits /api is proxied to the app server     \nif ! grep -q \"location /api\" \"$NGINX_CONF\"; then\n    eval \"cat <<EOF\n    location /api {\n        proxy_pass http://yelb-appserver:4567/api;\n        proxy_http_version 1.1;\n    }\nEOF\n\" > /proxycfg.txt\n    # echo \"        proxy_set_header Host $host;\" >> /proxycfg.txt\n    sed --in-place '/server_name  localhost;/ r /proxycfg.txt' $NGINX_CONF\nfi\nnginx -g \"daemon off;\" \n\n\n", "num_lines": 27}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nCLUSTER_NAME=\"${CLUSTER_NAME:=eks-appmesh}\"\n\nkubectl label ns default \\\nappmesh.k8s.aws/sidecarInjectorWebhook- gateway- mesh- --overwrite\n\n# Delete all objects from default namespace\nkubectl delete all --all\n\n# Delete appmesh\nkubectl delete mesh yelb-mesh\n\n# Delete IAM Service Account\neksctl delete iamserviceaccount \\\n  --cluster ${CLUSTER_NAME} \\\n  --namespace appmesh-system \\\n  --name appmesh-controller\n\n# uninstall appmesh helm\nhelm delete appmesh-controller --namespace appmesh-system\n\n# delete appmesh-system namespace\nkubectl delete ns appmesh-system\n\n# Delete db cluster\necho \"Deleting RDS Cluster\"\naws rds delete-db-cluster \\\n--db-cluster-identifier=yelb-db-cluster \\\n--skip-final-snapshot &> /dev/null\n\n# Delete ElastiCache cluster\necho \"Deleting ElastiCache cluster\"\naws elasticache delete-cache-cluster \\\n--cache-cluster-id=yelb-cache-cluster &> /dev/null\n", "num_lines": 36}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport AWS_DEFAULT_OUTPUT=\"json\"\n\nVPC_ID=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --output json \\\n    | jq -r '.Vpcs[0].VpcId')\n\naws ec2 create-security-group \\\n    --group-name yelb-es-security-group \\\n    --description \"Security Group for Yelb-Cache\" \\\n    --vpc-id ${VPC_ID} 2> /dev/null\n\naws ec2 wait security-group-exists \\\n    --filters Name=group-name,Values=yelb-es-security-group;Name=vpc-id,Values=${VPC_ID}\n\nSECURITY_GROUP_ID=$(echo $(aws ec2 describe-security-groups \\\n    --filters Name=group-name,Values=yelb-es-security-group;Name=vpc-id,Values=${VPC_ID} --output json)  \\\n    | jq -r '.SecurityGroups[0].GroupId')\n\necho \"Security Group Id: ${SECURITY_GROUP_ID}\"\n\naws ec2 authorize-security-group-ingress \\\n    --group-id ${SECURITY_GROUP_ID} \\\n    --protocol tcp \\\n    --port 6379 \\\n    --cidr 0.0.0.0/0 2> /dev/null\n\necho \"Creating cluster...\"\n\naws elasticache create-cache-cluster \\\n    --cache-cluster-id \"yelb-cache-cluster\" \\\n    --engine redis \\\n    --cache-node-type cache.t2.medium \\\n    --security-group-ids ${SECURITY_GROUP_ID} \\\n    --num-cache-nodes 1 &> /dev/null\n\naws elasticache wait cache-cluster-available \\\n    --cache-cluster-id \"yelb-cache-cluster\"\n\nCLUSTER_END_POINT=$(aws elasticache describe-cache-clusters \\\n    --cache-cluster-id yelb-cache-cluster \\\n    --show-cache-node-info --output json | jq -r '.CacheClusters[0].CacheNodes[0].Endpoint.Address')\n\necho \"ElastiCache endpoint: ${CLUSTER_END_POINT}\"\n", "num_lines": 45}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport AWS_DEFAULT_OUTPUT=\"json\"\n\nVPC_ID=$(aws ec2 describe-vpcs --filters Name=isDefault,Values=true --output json | jq -r '.Vpcs[0].VpcId')\n\naws ec2 create-security-group \\\n    --group-name yelb-db-security-group \\\n    --description \"Security Group for Yelb-db\" \\\n    --vpc-id ${VPC_ID} 2> /dev/null\n\naws ec2 wait security-group-exists \\\n    --filters Name=group-name,Values=yelb-es-security-group;Name=vpc-id,Values=${VPC_ID}\n\nSECURITY_GROUP_ID=$(echo $(aws ec2 describe-security-groups \\\n    --filters Name=group-name,Values=yelb-db-security-group;Name=vpc-id,Values=${VPC_ID}) --output json | jq -r '.SecurityGroups[0].GroupId')\n\necho \"Security Group Id: ${SECURITY_GROUP_ID}\"\n\naws ec2 authorize-security-group-ingress \\\n    --group-id ${SECURITY_GROUP_ID} \\\n    --protocol tcp \\\n    --port 5432 \\\n    --cidr 0.0.0.0/0 2> /dev/null\n\necho \"Creating database...\"\n\naws rds create-db-cluster \\\n    --db-cluster-identifier yelb-db-cluster \\\n    --engine aurora-postgresql \\\n    --master-username postgres \\\n    --master-user-password postgres_password \\\n    --vpc-security-group-ids ${SECURITY_GROUP_ID} 2> /dev/null\n\naws rds create-db-instance \\\n    --db-cluster-identifier yelb-db-cluster \\\n    --db-instance-identifier yelb-db-instance \\\n    --db-instance-class db.t3.micro \\\n    --engine aurora-postgresql &> /dev/null\n\naws rds wait db-instance-available \\\n    --db-instance-identifier yelb-db-instance\n\nCLUSTER_END_POINT=$(aws rds describe-db-clusters \\\n    --db-cluster-identifier yelb-db-cluster --output json | jq -r '.DBClusters[0].Endpoint')\n\necho \"RDS endpoint: ${CLUSTER_END_POINT}\"\n", "num_lines": 48}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"bulkhead-pattern\"\nAPP_NAMESPACE=${PROJECT_NAME}\nAPP=\"price-app\"\nEXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n\ndelete_ecr_repository() {\n    aws ecr delete-repository --repository-name $PROJECT_NAME/${APP} --force\n}\n\ndelete_kubernetes_and_mesh() {\n    kubectl delete -f ${EXAMPLES_OUT_DIR}/base.yaml\n}\n\nmain() {\n    delete_ecr_repository\n    delete_kubernetes_and_mesh\n}\n\nmain\n", "num_lines": 25}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"bulkhead-pattern\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nAPP=\"price-app\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\"\nPRICE_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nEXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.1.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/manifests/base.template.yaml)\nEOF\n\" >${EXAMPLES_OUT_DIR}/base.yaml\n\n    eval \"cat <<EOF\n$(<${DIR}/manifests/update.template.yaml)\nEOF\n\" >${EXAMPLES_OUT_DIR}/update.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/base.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 113}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nEXAMPLES_OUT_DIR=\"${DIR}/_output\"\n\nmain() {\n  kubectl apply -f ./${EXAMPLES_OUT_DIR}/update.yaml\n  echo \"Updated successfully\"\n}\n\nmain\n", "num_lines": 13}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\nkubectl delete ns yelb\n\nimages=(nginx node postgres redis redis-server yelb-appserver yelb-db yelb-ui)\necho \"Cleaning up image, will delete images:\\n\"\nprintf '%s\\n' \"${images[@]}\"\nread -r -p \"Are you sure you want to delete images? [y/N] \" response\n    if [[ \"$response\" =~ ^([yY][eE][sS]|[yY])$ ]]\n    then\n        for image in \"${images[@]}\"; do\n            aws ecr delete-repository --repository-name $image --region $AWS_REGION --force || true\n        done\n    else\n        echo \"OK, moving on!\"\n    fi\n\n\nstacks=(eks-pipeline-yelb-ui eks-pipeline-yelb-appserver eks-pipeline-yelb-redis eks-pipeline-yelb-db)\necho \"Cleaning up stacks\"\nfor stack in \"${stacks[@]}\"; do\n    aws cloudformation delete-stack --stack-name $stack --region $AWS_REGION|| true\ndone\n\necho \"Waiting on stack delete\"\nseconds=45; date1=$((`date +%s` + $seconds)); \nwhile [ \"$date1\" -ge `date +%s` ]; do \n  echo -ne \"$(date -u --date @$(($date1 - `date +%s` )) +%H:%M:%S)\\r\"; \ndone\n\necho \"Getting s3 buckets in stack eks-deployment-stepfunctions to remove.\"\nbucket=$(aws cloudformation describe-stack-resources --stack-name eks-deployment-stepfunctions --region $AWS_REGION --output json | jq -c -r '.StackResources[] | select( .ResourceType == \"AWS::S3::Bucket\" ) | .PhysicalResourceId')\necho \"Deleting bucket : $bucket\"\naws s3 rb s3://$bucket --force || true\necho \"Deleting stack eks-deployment-stepfunctions\"\naws cloudformation delete-stack --stack-name eks-deployment-stepfunctions --region $AWS_REGION|| true\necho \"Deleting stack kubectl-lambda-layer\"\naws cloudformation delete-stack --stack-name kubectl-lambda-layer --region $AWS_REGION|| true\n\necho \"Waiting on stack delete\"\nseconds=45; date1=$((`date +%s` + $seconds)); \nwhile [ \"$date1\" -ge `date +%s` ]; do \n  echo -ne \"$(date -u --date @$(($date1 - `date +%s` )) +%H:%M:%S)\\r\"; \ndone\n\neksctl delete iamserviceaccount --region $AWS_REGION --cluster $EKS_CLUSTER_NAME --namespace appmesh-system --name appmesh-controller\n\nroles=$(aws iam list-roles --output json | jq -c -r '.Roles[] | select(.RoleName | contains(\"eksctl-blogpost\"))| .RoleName')\nfor role in $roles; do\n    inlinepolicies=$(aws iam list-role-policies --role-name $role --output json | jq -r -c .PolicyNames[])\n    for policy in $inlinepolicies; do\n        aws iam delete-role-policy --role-name $role --policy-name $policy\n    done\n    attachedpoliciesarn=$(aws iam list-attached-role-policies --role-name $role --output json | jq -r -c .AttachedPolicies[].PolicyArn)\n        for policyarn in $attachedpoliciesarn; do\n            aws iam detach-role-policy --role-name $role --policy-arn $policyarn\n        done\n    aws iam delete-role --role-name $role\ndone\n\necho \"Removing parameters from parameter store.\"\nparameters=(eks-canary-redis-server-version eks-canary-yelb-appserver-version eks-canary-yelb-db-version eks-canary-yelb-ui-version)\nfor parameter in \"${parameters[@]}\"; do\n    aws ssm delete-parameter --name $parameter --region $AWS_REGION || true\ndone\n\n\necho \"Deleting EKS cluster : blogpost\"\neksctl delete cluster --region $AWS_REGION --name $EKS_CLUSTER_NAME\n\naws appmesh delete-mesh --mesh-name yelb --region $AWS_REGION\n\n", "num_lines": 76}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\n# Get the AWS Lambda role ARN\nSTATE_MACHINE_ROLE_ARN=$(aws cloudformation describe-stacks --region $AWS_REGION --stack-name $SHARED_STACK_NAME --output json \\\n| jq -r '.Stacks[0].Outputs[] | select(.OutputKey == \"EKSAccessRole\") | .OutputValue')\n\n# Add the role to Kubernetes RBAC\neksctl create iamidentitymapping --region $AWS_REGION --cluster $EKS_CLUSTER_NAME --arn $STATE_MACHINE_ROLE_ARN --output json \\\n--group system:masters --username eks_canary_stepfunctions", "num_lines": 12}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# AppID for the AWS Lambda Layer that has kubectl, awscli, helm, and jq\nAPP_ID='arn:aws:serverlessrepo:us-east-1:903779448426:applications/lambda-layer-kubectl'\n\n# Create the AWS CloudFormation template\nTEMPLATE_URL=$(aws --region $AWS_REGION serverlessrepo \\\ncreate-cloud-formation-template --application-id  ${APP_ID} --output json \\\n| jq -r '.TemplateUrl')\n\n# Deploy the AWS CloudFormation template\naws --region $AWS_REGION cloudformation create-stack \\\n--template-url $TEMPLATE_URL --stack-name \"kubectl-lambda-layer\" \\\n--capabilities CAPABILITY_AUTO_EXPAND \\\n--parameters ParameterKey=LayerName,ParameterValue=lambda-layer-kubectl\n\necho -n \"Creating the AWS CloudFormation stack\"\nwhile [ \"$(aws cloudformation describe-stacks --stack-name kubectl-lambda-layer --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ]; do\n  echo -n '.'\n  sleep 10\ndone\necho -e \"\\n$(aws cloudformation describe-stacks --stack-name kubectl-lambda-layer --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\"\n", "num_lines": 23}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Create EKS cluster\neksctl create cluster --name $EKS_CLUSTER_NAME --region $AWS_REGION --zones=\"$AWS_REGION\"a,\"$AWS_REGION\"b,\"$AWS_REGION\"c \\\n--managed --appmesh-access \\\n--alb-ingress-access --full-ecr-access\n\n# Export cluster ARN (this variable will be used later)\nexport EKS_CLUSTER_ARN=$(aws eks describe-cluster --region $AWS_REGION --name $EKS_CLUSTER_NAME --output json | jq -r '.cluster.arn')\necho \"export EKS_CLUSTER_ARN=${EKS_CLUSTER_ARN}\" | tee -a ~/.bash_profile\n\n# Export node group role name (this variable will be used later)\nexport STACK_NAME=$(eksctl get nodegroup --region $AWS_REGION --cluster $EKS_CLUSTER_NAME -o json | jq -r '.[].StackName')\nexport EKS_ROLE_NAME=$(aws cloudformation describe-stack-resources --region $AWS_REGION --stack-name $STACK_NAME --output json | jq -r '.StackResources[] | select(.ResourceType==\"AWS::IAM::Role\") | .PhysicalResourceId')\necho \"export EKS_ROLE_NAME=${EKS_ROLE_NAME}\" | tee -a ~/.bash_profile", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\n# Database\naws cloudformation create-stack --stack-name eks-pipeline-yelb-db \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/pipeline_stack/pipeline_cloudformation.yml\" \\\n--parameters ParameterKey=MicroserviceName,ParameterValue=\"yelb-db\" \\\nParameterKey=SharedStackName,ParameterValue=\"$SHARED_STACK_NAME\" \\\nParameterKey=BuildComputeType,ParameterValue=\"$BUILD_COMPUTE_TYPE\" \\\nParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\nParameterKey=SampleMicroservices,ParameterValue=\"$USE_SAMPLE_MICROSERVICES\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\n# Redis\naws cloudformation create-stack --stack-name eks-pipeline-yelb-redis \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/pipeline_stack/pipeline_cloudformation.yml\" \\\n--parameters ParameterKey=MicroserviceName,ParameterValue=\"redis-server\" \\\nParameterKey=SharedStackName,ParameterValue=\"$SHARED_STACK_NAME\" \\\nParameterKey=BuildComputeType,ParameterValue=\"$BUILD_COMPUTE_TYPE\" \\\nParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\nParameterKey=SampleMicroservices,ParameterValue=\"$USE_SAMPLE_MICROSERVICES\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\n# Application Server\naws cloudformation create-stack --stack-name eks-pipeline-yelb-appserver \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/pipeline_stack/pipeline_cloudformation.yml\" \\\n--parameters ParameterKey=MicroserviceName,ParameterValue=\"yelb-appserver\" \\\nParameterKey=SharedStackName,ParameterValue=\"$SHARED_STACK_NAME\" \\\nParameterKey=BuildComputeType,ParameterValue=\"$BUILD_COMPUTE_TYPE\" \\\nParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\nParameterKey=SampleMicroservices,ParameterValue=\"$USE_SAMPLE_MICROSERVICES\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\n# User Interface\naws cloudformation create-stack --stack-name eks-pipeline-yelb-ui \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/pipeline_stack/pipeline_cloudformation.yml\" \\\n--parameters ParameterKey=MicroserviceName,ParameterValue=\"yelb-ui\" \\\nParameterKey=SharedStackName,ParameterValue=\"$SHARED_STACK_NAME\" \\\nParameterKey=BuildComputeType,ParameterValue=\"$BUILD_COMPUTE_TYPE\" \\\nParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\nParameterKey=SampleMicroservices,ParameterValue=\"$USE_SAMPLE_MICROSERVICES\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\n\necho -n \"Creating the AWS CloudFormation stacks\"\nwhile [ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-db --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ] || \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-redis --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ] || \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-appserver --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ] || \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-ui --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ] ; do\n  echo -n '.'\n  sleep 10\ndone\n\nif [ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-db --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_COMPLETE\" ] && \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-redis --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_COMPLETE\" ] && \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-appserver --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_COMPLETE\" ] && \\\n[ \"$(aws cloudformation describe-stacks --stack-name eks-pipeline-yelb-ui --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_COMPLETE\" ] ; then\n    echo -e \"\\nAll four stacks created successfully!\"\nelse\n    echo -e \"\\nAn error occurred while creating the stacks! Don't move forward before fixing it!\"\nfi\n\n\n", "num_lines": 70}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\n# Create a new S3 bucket with a random name suffix because S3 bucket names are unique\nRANDOM_STRING=$(LC_ALL=C tr -dc 'a-z' </dev/urandom | head -c 10 ; echo)\nS3_BUCKET_NAME=$(aws s3 mb s3://eks-canary-blogpost-cloudformation-files-$RANDOM_STRING --region $AWS_REGION | cut -d' ' -f2)\necho \"export S3_BUCKET_NAME=${S3_BUCKET_NAME}\" | tee -a ~/.bash_profile\n\naws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com\n\n# Get the base directory path that will be used to zip the resources before uploading to S3\nbase_path=\"$(dirname $(dirname $(realpath $0)) )\"\n\n\nif [ $USE_SAMPLE_MICROSERVICES == \"True\" ]\nthen\n  cd /tmp\n  git clone https://github.com/mreferre/yelb.git\n  \n  cp /tmp/yelb/yelb-ui/* $base_path/microservices/yelb-ui/ -rf\n  cp /tmp/yelb/yelb-db/* $base_path/microservices/yelb-db/ -rf\n  cp /tmp/yelb/yelb-appserver/* $base_path/microservices/yelb-appserver/ -rf\n  \n  cd $base_path/microservices\n  \n  for dockerfile in `find ./ |grep Dockerfile`\n    do\n      for image in `cat $dockerfile |grep FROM|cut -d ' ' -f2`\n        do\n          if ! echo $image |grep -q '/'; then\n            echo \"Adding $image to ECR\"\n            docker pull $image\n            imagename=$(echo $image |cut -d ':' -f1)\n            aws ecr create-repository --repository-name $imagename --region $AWS_REGION\n            docker tag $image $ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$image\n            docker push $ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$image\n            sed -i.bak \"s#$image#$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$image#g\" $dockerfile\n            \n          fi\n        done\n    done\n  \n  #Modifying the increment to 2 to demonstrate in blog post\n  sed -i \"s/count +1 WHERE name/count +2 WHERE name/g\" $base_path/microservices/yelb-appserver/modules/restaurantsdbupdate.rb\n  \n  \n  \n  # Zip the microservice resources\n  cd $base_path/microservices/yelb-ui && zip -r yelb-ui.zip ./* > /dev/null\n  cd $base_path/microservices/yelb-db && zip -r yelb-db.zip ./* > /dev/null\n  cd $base_path/microservices/yelb-appserver && zip -r yelb-appserver.zip ./* > /dev/null\n  cd $base_path/microservices/redis-server && zip -r redis-server.zip ./* > /dev/null\nfi\n\n# Zip the lambda function resources\ncd $base_path/shared_stack/lambda_functions/check_deployment_version && zip -r function.zip ./* > /dev/null\ncd $base_path/shared_stack/lambda_functions/deploy_and_switch_traffic && zip -r function.zip ./* > /dev/null\ncd $base_path/shared_stack/lambda_functions/gather_healthcheck_status && zip -r function.zip ./* > /dev/null\ncd $base_path/shared_stack/lambda_functions/rollback_or_finish_upgrade && zip -r function.zip ./* > /dev/null\ncd $base_path/shared_stack/lambda_functions/update_deployment_version && zip -r function.zip ./* > /dev/null\n\n# Move back to the base directory\ncd $base_path\necho $S3_BUCKET_NAME\n# Upload the resources to the bucket created\naws s3 cp ./ s3://$S3_BUCKET_NAME --recursive --region $AWS_REGION > /dev/null\n\n# Get the AWS Lambda Layer ARN from last AWS CloudFormation stack output\nLAMBDA_LAYER_ARN=$(aws cloudformation describe-stacks --stack-name kubectl-lambda-layer \\\n--region $AWS_REGION --output json | jq -r '.Stacks[0].Outputs[] | select(.OutputKey == \"LayerVersionArn\") | .OutputValue')\n\n# Deploy AWS CloudFormation Stack\naws cloudformation create-stack --stack-name $SHARED_STACK_NAME \\\n--template-url \"https://$S3_BUCKET_NAME.s3.amazonaws.com/shared_stack/stepfuntions_cloudformation.yml\" \\\n--parameters ParameterKey=SourceCodeBucket,ParameterValue=\"$S3_BUCKET_NAME\" \\\nParameterKey=EKSClusterARN,ParameterValue=\"$EKS_CLUSTER_ARN\" \\\nParameterKey=LambdaLayerName,ParameterValue=\"$LAMBDA_LAYER_ARN\" \\\n--capabilities CAPABILITY_IAM \\\n--region $AWS_REGION\n\necho -n \"Creating the AWS CloudFormation stack\"\nwhile [ \"$(aws cloudformation describe-stacks --stack-name $SHARED_STACK_NAME --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\" == \"CREATE_IN_PROGRESS\" ]; do\n  echo -n '.'\n  sleep 10\ndone\necho -e \"\\n$(aws cloudformation describe-stacks --stack-name $SHARED_STACK_NAME --region $AWS_REGION --output json | jq -r '.Stacks[0].StackStatus')\"\n\n\n#Cleanup\nrm /tmp/yelb -rf\nrm $base_path/microservices/yelb-ui/* 2> /dev/null \nrm $base_path/microservices/yelb-ui/clarity-seed-newfiles -rf\nrm $base_path/microservices/yelb-db/* 2> /dev/null\nrm $base_path/microservices/yelb-appserver/* 2> /dev/null\nrm $base_path/microservices/yelb-appserver/modules -rf\nrm $base_path/microservices/redis-server/redis-server.zip\nrm $base_path/microservices/redis-server/Dockerfile 2> /dev/null\nmv $base_path/microservices/redis-server/Dockerfile.bak $base_path/microservices/redis-server/Dockerfile\nrm $base_path/shared_stack/lambda_functions/check_deployment_version/function.zip\nrm $base_path/shared_stack/lambda_functions/deploy_and_switch_traffic/function.zip\nrm $base_path/shared_stack/lambda_functions/gather_healthcheck_status/function.zip \nrm $base_path/shared_stack/lambda_functions/rollback_or_finish_upgrade/function.zip\nrm $base_path/shared_stack/lambda_functions/update_deployment_version/function.zip", "num_lines": 105}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Default variables that were used on the blog post (you can change them to fit your needs)\nAWS_REGION=us-west-2\nEKS_CLUSTER_NAME=blogpost\nSHARED_STACK_NAME=eks-deployment-stepfunctions\nBUILD_COMPUTE_TYPE=BUILD_GENERAL1_SMALL\nUSE_SAMPLE_MICROSERVICES='True'\n\n\nexport ACCOUNT_ID=$(aws sts get-caller-identity --output text --query Account)\n\n\n# Add environment variables to bash_profile\necho \"export ACCOUNT_ID=${ACCOUNT_ID}\" | tee -a ~/.bash_profile\necho \"export AWS_REGION=${AWS_REGION}\" | tee -a ~/.bash_profile\necho \"export EKS_CLUSTER_NAME=${EKS_CLUSTER_NAME}\" | tee -a ~/.bash_profile\necho \"export SHARED_STACK_NAME=${SHARED_STACK_NAME}\" | tee -a ~/.bash_profile\necho \"export BUILD_COMPUTE_TYPE=${BUILD_COMPUTE_TYPE}\" | tee -a ~/.bash_profile\necho \"export USE_SAMPLE_MICROSERVICES=${USE_SAMPLE_MICROSERVICES}\" | tee -a ~/.bash_profile", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\n# Add the eks-charts repository to Helm\nhelm repo add eks https://aws.github.io/eks-charts\n\n# Install the App Mesh Kubernetes custom resource definitions (CRD)\nkubectl apply -k \"https://github.com/aws/eks-charts/stable/appmesh-controller/crds?ref=master\"\n\n# Create a Kubernetes namespace for the controller\nkubectl create ns appmesh-system\n\n# Create an OpenID Connect (OIDC) identity provider for your cluster\neksctl utils associate-iam-oidc-provider --region=$AWS_REGION --cluster $EKS_CLUSTER_NAME --approve\n\n# Create an IAM role and attach the AWSAppMeshFullAccess (https://console.aws.amazon.com/iam/home?#policies/arn:aws:iam::aws:policy/AWSAppMeshFullAccess$jsonEditor) and AWSCloudMapFullAccess (https://console.aws.amazon.com/iam/home?#policies/arn:aws:iam::aws:policy/AWSCloudMapFullAccess$jsonEditor) AWS managed policies\neksctl create iamserviceaccount --region $AWS_REGION --cluster $EKS_CLUSTER_NAME --namespace appmesh-system --name appmesh-controller --attach-policy-arn  arn:aws:iam::aws:policy/AWSCloudMapFullAccess,arn:aws:iam::aws:policy/AWSAppMeshFullAccess --override-existing-serviceaccounts --approve\n\n# Deploy the App Mesh controller\nhelm upgrade -i appmesh-controller eks/appmesh-controller --namespace appmesh-system --set region=$AWS_REGION --set serviceAccount.create=false --set serviceAccount.name=appmesh-controller\n\n# Confirm that the controller version is v1.0.0 or later\nkubectl get deployment appmesh-controller -n appmesh-system -o json  | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'", "num_lines": 25}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Load environment variables\nsource ~/.bash_profile\n\n# Attach CloudWatchAgentServerPolicy to EKS nodegroup role\naws iam attach-role-policy --region $AWS_REGION --role-name $EKS_ROLE_NAME --policy-arn arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy\n\n# Install Container Insights\ncurl https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/latest/k8s-deployment-manifest-templates/deployment-mode/daemonset/container-insights-monitoring/quickstart/cwagent-fluentd-quickstart.yaml | sed \"s/{{cluster_name}}/$EKS_CLUSTER_NAME/;s/{{region_name}}/$AWS_REGION/\" | kubectl apply -f -\n\n# Configure Prometheus\nkubectl apply -f https://raw.githubusercontent.com/aws-samples/amazon-cloudwatch-container-insights/prometheus-beta/k8s-deployment-manifest-templates/deployment-mode/service/cwagent-prometheus/prometheus-eks.yaml", "num_lines": 13}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Install jq\nsudo yum install jq -y\n\n# Install eksctl\ncurl --silent --location \"https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz\" | tar xz -C /tmp\nsudo mv /tmp/eksctl /usr/local/bin\n\n# Install kubectl\ncurl -LO \"https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl\"\nchmod +x ./kubectl\nsudo mv ./kubectl /usr/local/bin/kubectl\n\n# Install helm\ncurl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 > get_helm.sh\nchmod 700 get_helm.sh\n./get_helm.sh\nrm get_helm.sh", "num_lines": 19}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "function handler () {\n    # Get variables\n    cluster_name=$(echo $1 | jq -r '.cluster_name')\n    new_version=$(echo $1 | jq -r '.deployment.new_version | tonumber')\n    container_image=$(echo $1 | jq -r '.container_image')\n    microservice_name=$(echo $1 | jq -r '.microservice_name')\n    kubernetes_namespace=$(echo $1 | jq -r '.kubernetes_namespace')\n\n    echo $1 | jq -r '.config_file' | base64 -d > /tmp/deployment.yml\n\n    # Create kubeconfig file\n    aws eks update-kubeconfig --name $cluster_name --kubeconfig /tmp/kubeconfig\n\n    # Check if first deployment then apply all traffic to deployed version\n    if [ $new_version -eq 1 ]; then\n        canary_routes='{\"virtualNodeRef\":{\"name\":\"'$microservice_name'-'$new_version'\"},\"weight\":1}'\n        new_percentage=100\n    else\n        percentage_step=$(echo $1 | jq -r '.percentage_step | tonumber')\n        current_percentage=$(echo $1 | jq -r '.deployment.current_percentage | tonumber')\n\n        new_percentage=$(($current_percentage + $percentage_step))\n        # Ensure that new percentage is not greater than 100%\n        if [ $new_percentage -gt 100 ]; then\n          new_percentage=100\n        fi\n        old_percentage=$((100 - $new_percentage))\n        old_version=$(($new_version - 1))\n        canary_routes='{\"virtualNodeRef\":{\"name\":\"'$microservice_name'-'$new_version'\"},\"weight\":'$new_percentage'},{\"virtualNodeRef\":{\"name\":\"'$microservice_name'-'$old_version'\"},\"weight\":'$old_percentage'}'\n    fi\n\n    # Apply configurations to deployment spec\n    sed -i 's@${CANARY_VERSION}@'\"$new_version\"'@' /tmp/deployment.yml\n    sed -i 's@${CONTAINER_IMAGE}@'\"$container_image\"'@' /tmp/deployment.yml\n    sed -i 's@${CANARY_ROUTES}@'\"$canary_routes\"'@' /tmp/deployment.yml\n    sed -i 's@${KUBERNETES_NAMESPACE}@'\"$kubernetes_namespace\"'@' /tmp/deployment.yml\n    sed -i 's@${MICROSERVICE_NAME}@'\"$microservice_name\"'@' /tmp/deployment.yml\n\n    # Apply deployment to kubernetes\n    kubectl apply -f /tmp/deployment.yml\n\n    # Output configured specfile to logs\n    echo \"Microservice: $microservice_name\"\n    echo \"Container Image: $container_image\"\n    echo \"Deployment Version: $new_version\"\n    echo \"Traffic Route: $canary_routes\"\n\n    # Lambda runtime response\n    export response=$new_percentage\n}", "num_lines": 50}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "function handler () {\n    # Get variables\n    cluster_name=$(echo $1 | jq -r '.cluster_name')\n    kubernetes_namespace=$(echo $1 | jq -r '.kubernetes_namespace')\n    new_version=$(echo $1 | jq -r '.deployment.new_version | tonumber')\n    microservice_name=$(echo $1 | jq -r '.microservice_name')\n    old_version=$(($new_version - 1))\n\n    # Create kubeconfig file\n    aws eks update-kubeconfig --name $cluster_name --kubeconfig /tmp/kubeconfig\n\n    # Check if should rollback or finish upgrade\n    is_healthy=$(echo $1 | jq '.deployment.is_healthy')\n    if [ $is_healthy = false ]; then\n        to_delete=$new_version\n        to_keep=$old_version\n    else\n        to_delete=$old_version\n        to_keep=$new_version\n    fi\n\n    # Get all listener protocols\n    protocols=$(kubectl get VirtualRouter $microservice_name -n $kubernetes_namespace -o json \\\n        | jq -r '.spec.listeners[].portMapping.protocol')\n\n    # For all protocols found\n    for p in $protocols;\n    do\n       # Ensure that all trafic is going to the new VirtualNode\n        kubectl get VirtualRouter $microservice_name -n $kubernetes_namespace -o json \\\n            | jq '.spec.routes[].'$p'Route.action.weightedTargets = [{\"virtualNodeRef\":{\"name\":\"'$microservice_name'-'$to_keep'\"},\"weight\":100}]' \\\n            | jq 'del(.metadata.resourceVersion)' | jq 'del(.spec.meshRef)' \\\n            | kubectl apply -f -\n    done\n\n    # Delete the to_delete version\n    kubectl -n $kubernetes_namespace delete VirtualNode \"$microservice_name-$to_delete\"\n    kubectl -n $kubernetes_namespace delete deploy/\"$microservice_name-$to_delete\" svc/\"$microservice_name-$to_delete\"\n\n    # Lambda runtime response\n    export response=true\n\n}", "num_lines": 43}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nMESH_OWNER=$(aws --profile shared sts get-caller-identity --output json | jq -r .Account)\n\ncat << EOF > app-mesh.yaml\napiVersion: appmesh.k8s.aws/v1beta2\nkind: Mesh\nmetadata:\n  name: am-multi-account-mesh\nspec:\n  meshOwner: \"${MESH_OWNER}\"\n  namespaceSelector:\n    matchLabels:\n      mesh: am-multi-account-mesh\nEOF\n\nfor PROFILE in shared frontend backend\n  do \n  \n    if [ \"$PROFILE\" == \"shared\" ]; then \n      kubectl config use-context $SHARED_CXT\n    elif [ \"$PROFILE\" == \"frontend\" ]; then \n      kubectl config use-context $FRONT_CXT\n    else \n      kubectl config use-context $BACK_CXT\n    fi\n\n    echo \"Creating the appmesh-system namespace...\"\n    kubectl create ns appmesh-system\n\n    echo \"Creating an OIDC identity provider for the cluster...\"\n    eksctl --profile $PROFILE utils associate-iam-oidc-provider \\\n      --cluster eks-cluster-$PROFILE \\\n      --approve\n\n    echo \"Creating an IAM role for the appmesh-controller service account...\"\n    eksctl --profile $PROFILE create iamserviceaccount \\\n      --cluster eks-cluster-$PROFILE \\\n      --namespace appmesh-system \\\n      --name appmesh-controller \\\n      --attach-policy-arn  arn:aws:iam::aws:policy/AWSCloudMapFullAccess,arn:aws:iam::aws:policy/AWSAppMeshFullAccess \\\n      --override-existing-serviceaccounts \\\n      --approve\n\n    echo \"Adding the eks-charts helm repo...\"\n    helm repo add eks https://aws.github.io/eks-charts\n\n    helm repo update\n\n    echo \"Installing the appmesh-controller...\"\n    helm upgrade -i appmesh-controller eks/appmesh-controller \\\n      --namespace appmesh-system \\\n      --set serviceAccount.create=false \\\n      --set serviceAccount.name=appmesh-controller \\\n      --set sds.enabled=true\n      # --set sidecar.image.tag=v1.25.1.0-prod\n\n    echo \"Creating the yelb namespace...\"\n    kubectl create ns yelb\n\n    echo \"Labeling the yelb namespace...\"\n    kubectl label namespace yelb mesh=am-multi-account-mesh \n\n    kubectl label namespace yelb \"appmesh.k8s.aws/sidecarInjectorWebhook\"=enabled\n\n    if [ \"$PROFILE\" != \"shared\" ]; then \n      INVITE_ARN=$(aws --profile $PROFILE ram get-resource-share-invitations --output json \\\n        | jq -r '.resourceShareInvitations[] | select(.resourceShareName==\"mesh-share\") | .resourceShareInvitationArn')\n      if [ \"$INVITE_ARN\" != \"\" ]; then\n        echo \"Accepting resource share...\"\n        aws --profile $PROFILE ram accept-resource-share-invitation \\\n          --resource-share-invitation-arn $INVITE_ARN > /dev/null\n      fi\n    fi \n\n    PHASE=$(kubectl get pods -n appmesh-system -o json | jq -r '.items[0].status.phase')\n\n    while [ \"$PHASE\" != \"Running\" ]\n      do \n        echo \"Waiting on appmesh-controller to be running...\"\n        PHASE=$(kubectl get pods -n appmesh-system -o json | jq -r '.items[0].status.phase')\n        sleep 10\n      done \n\n    echo \"Creating the am-multi-account-mesh...\"\n    kubectl apply -f app-mesh.yaml\n\n    if [ \"$PROFILE\" == \"shared\" ]; then \n      echo \"Sharing the am-multi-account-mesh with the frontend and backend accounts...\" \n      aws --profile shared ram create-resource-share \\\n        --name mesh-share \\\n        --resource-arns $(kubectl get meshes -o json \\\n        | jq -r '.items[] | select(.metadata.name ==\"am-multi-account-mesh\").status.meshARN') \\\n        --principals $(aws --profile frontend sts get-caller-identity --output json | jq -r .Account) \\\n        $(aws --profile backend sts get-caller-identity --output json | jq -r .Account) > /dev/null\n    fi\n\n    if [ \"$PROFILE\" == \"backend\" ]; then\n      echo \"Creating the Cloud Map namespace am-multi-account.local...\"\n      aws --profile backend servicediscovery create-http-namespace \\\n        --name am-multi-account.local > /dev/null\n    fi \n\n  done", "num_lines": 105}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nfor PROFILE in frontend backend shared\n  do \n    if [ \"$PROFILE\" == \"shared\" ]; then \n      kubectl config use-context $SHARED_CXT\n    elif [ \"$PROFILE\" == \"frontend\" ]; then \n      kubectl config use-context $FRONT_CXT\n    else \n      kubectl config use-context $BACK_CXT\n    fi\n\n    echo \"Deleting the yelb namespace...\"\n    kubectl delete ns yelb\n\n    echo \"Deleting the spire namespace...\"\n    kubectl delete ns spire\n\n    if [ \"$PROFILE\" == \"backend\" ]; then \n      echo \"Deleting the Cloud Map namespace am-multi-account.local...\"\n      aws --output json --profile backend servicediscovery get-operation \\\n        --operation-id $(aws --profile backend servicediscovery delete-namespace \\\n        --id $(aws --profile backend servicediscovery list-namespaces --output json \\\n        | jq -r '.Namespaces[] | select(.Name==\"am-multi-account.local\").Id') \\\n        | jq -r '.OperationId') > /dev/null\n    fi\n\n    echo \"Deleting the App Mesh am-multi-account-mesh...\"\n    kubectl delete mesh am-multi-account-mesh\n\n    if [ \"$PROFILE\" == \"shared\" ]; then \n      echo \"Deleting the mesh-share RAM resource share...\"\n      aws --profile shared ram delete-resource-share \\\n        --resource-share-arn $(aws --profile shared ram get-resource-shares \\\n        --resource-owner SELF --output json | jq -r '.resourceShares[] | select((.name==\"mesh-share\") and (.status==\"ACTIVE\")).resourceShareArn') > /dev/null\n    fi \n\n    echo \"Deleting the appmesh-controller...\"\n    helm -n appmesh-system delete appmesh-controller\n\n    echo \"Deleting the App Mesh custom resource definitions...\"\n    for i in $(kubectl get crd | grep appmesh | cut -d\" \" -f1)\n      do\n        kubectl delete crd $i\n      done\n    \n    echo \"Deleting the appmesh-controller IAM service account...\"\n    eksctl --profile $PROFILE delete iamserviceaccount \\\n      --cluster eks-cluster-$PROFILE \\\n      --namespace appmesh-system \\\n      --name appmesh-controller\n\n    echo \"Deleting the appmesh-system namespace...\"\n    kubectl delete namespace appmesh-system\n  done", "num_lines": 57}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "export EBS_CSI_POLICY_NAME=\"Amazon_EBS_CSI_Driver_For_Spire_Server\"\n\n\n# download the IAM policy document\ncurl -sSL -o ebs-csi-policy.json https://raw.githubusercontent.com/kubernetes-sigs/aws-ebs-csi-driver/master/docs/example-iam-policy.json\n\n# Create the IAM policy\naws iam create-policy \\\n  --profile shared \\\n  --policy-name ${EBS_CSI_POLICY_NAME} \\\n  --policy-document file://ebs-csi-policy.json\n\n# export the policy ARN as a variable\nexport EBS_CSI_POLICY_ARN=$(aws --profile shared iam list-policies --query 'Policies[?PolicyName==`'$EBS_CSI_POLICY_NAME'`].Arn' --output text)\n\n# Create a service account\neksctl create iamserviceaccount \\\n  --cluster eks-cluster-shared \\\n  --name spire-server \\\n  --profile shared \\\n  --namespace kube-system \\\n  --attach-policy-arn $EBS_CSI_POLICY_ARN \\\n  --override-existing-serviceaccounts \\\n  --approve\n\n# add the aws-ebs-csi-driver as a helm repo\nhelm repo add aws-ebs-csi-driver https://kubernetes-sigs.github.io/aws-ebs-csi-driver\n\nhelm upgrade --install aws-ebs-csi-driver \\\n  --version=1.2.4 \\\n  --namespace kube-system \\\n  --set serviceAccount.controller.create=false \\\n  --set serviceAccount.snapshot.create=false \\\n  --set enableVolumeScheduling=true \\\n  --set enableVolumeResizing=true \\\n  --set enableVolumeSnapshot=true \\\n  --set serviceAccount.snapshot.name=spire-server \\\n  --set serviceAccount.controller.name=spire-server \\\n  aws-ebs-csi-driver/aws-ebs-csi-driver\n\nkubectl -n kube-system rollout status deployment ebs-csi-controller", "num_lines": 41}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nkubectl config use-context $SHARED_CXT\n\necho \"Creating the spire namespace...\"\nkubectl create ns spire\n\necho \"Creating a separate kubeconfig file (front_config) for frontend cluster eks get-token authentication...\"\naws --profile frontend eks update-kubeconfig \\\n  --kubeconfig front_config \\\n  --name eks-cluster-frontend \\\n  --role-arn $(aws --profile frontend iam get-role \\\n  --role-name eks-cluster-frontend-access-role --output json | jq -r '.Role.Arn')\n\n# remove AWS_PROFILE from the frontend kubeconfig file\nsed \"$(( $(wc -l <front_config)-3+1 )),$ d\" front_config \\\n  > /tmp/front_config && mv /tmp/front_config front_config\n\necho \"Packaging the frontend kubeconfig file into a ConfigMap...\"\ncat << EOF > front_kubeconfig.yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: front-kubeconfig\n  namespace: spire\ndata:\n  frontend.conf: |\n$(awk '{printf \"    %s\\n\", $0}' < front_config)\nEOF\n\necho \"Creating the front-kubeconfig ConfigMap to be mounted as a volume to the SPIRE server...\"\nkubectl apply -f front_kubeconfig.yaml\n\necho \"Creating a separate kubeconfig file (back_config) for backend cluster eks get-token authentication...\"\naws --profile backend eks update-kubeconfig \\\n  --kubeconfig back_config \\\n  --name eks-cluster-backend \\\n  --role-arn $(aws --profile backend iam get-role \\\n  --role-name eks-cluster-backend-access-role --output json | jq -r '.Role.Arn')\n \n# remove AWS_PROFILE from the backend kubeconfig file\nsed \"$(( $(wc -l <back_config)-3+1 )),$ d\" back_config \\\n  > /tmp/back_config && mv /tmp/back_config back_config\n\necho \"Packaging the backend kubeconfig file into a ConfigMap...\"\ncat << EOF > back_kubeconfig.yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: back-kubeconfig\n  namespace: spire\ndata:\n  backend.conf: |\n$(awk '{printf \"    %s\\n\", $0}' < back_config)\nEOF\n\necho \"Creating the back-kubeconfig ConfigMap to be mounted as a volume to the SPIRE server...\"\nkubectl apply -f back_kubeconfig.yaml", "num_lines": 60}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\necho \"Registering a node entry for the frontend spire agent...\"\nregister_server_entries \\\n  -spiffeID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-front \\\n  -selector k8s_psat:cluster:frontend-k8s-cluster \\\n  -selector k8s_psat:agent_ns:spire \\\n  -selector k8s_psat:agent_sa:spire-agent-front \\\n  -node\necho \"Registering a node entry for the backend spire agent...\"\nregister_server_entries \\\n  -spiffeID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-back \\\n  -selector k8s_psat:cluster:backend-k8s-cluster \\\n  -selector k8s_psat:agent_ns:spire \\\n  -selector k8s_psat:agent_sa:spire-agent-back \\\n  -node\necho \"Registering a workload entry for the frontend app...\"\nregister_server_entries \\\n  -parentID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-front \\\n  -spiffeID spiffe://am-multi-account-mesh/frontend \\\n  -selector k8s:ns:yelb \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app:yelb-ui \\\n  -selector k8s:pod-label:tier:frontend \\\n  -selector k8s:container-name:envoy\necho \"Registering a workload entry for the redis-server...\"\nregister_server_entries \\\n  -parentID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-back \\\n  -spiffeID spiffe://am-multi-account-mesh/redis \\\n  -selector k8s:ns:yelb \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app:redis-server \\\n  -selector k8s:pod-label:tier:cache \\\n  -selector k8s:container-name:envoy\necho \"Registering a workload entry for the yelb-db...\"\nregister_server_entries \\\n  -parentID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-back \\\n  -spiffeID spiffe://am-multi-account-mesh/yelbdb \\\n  -selector k8s:ns:yelb \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app:yelb-db \\\n  -selector k8s:pod-label:tier:backenddb \\\n  -selector k8s:container-name:envoy\necho \"Registering a workload entry for the yelb-app...\"\nregister_server_entries \\\n  -parentID spiffe://am-multi-account-mesh/ns/spire/sa/spire-agent-back \\\n  -spiffeID spiffe://am-multi-account-mesh/yelbapp \\\n  -selector k8s:ns:yelb \\\n  -selector k8s:sa:default \\\n  -selector k8s:pod-label:app:yelb-appserver \\\n  -selector k8s:pod-label:tier:middletier \\\n  -selector k8s:container-name:envoy\n", "num_lines": 57}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nkubectl config use-context $FRONT_CXT\n\necho \"Retrieving the ARN of the yelb-appserver virtual service from the backend cluster...\"\nexport VS_ARN=$(kubectl --context $BACK_CXT -n yelb get virtualservice yelb-appserver -o json \\\n  | jq -r '.status.virtualServiceARN')\n \necho \"Creating an update for the yelb-ui virtual node (yelb-ui-final.yaml)...\"\n( echo \"cat <<EOF > mesh/yelb-ui-final.yaml\";\n  cat mesh/yelb-ui.yaml;\n  echo \"EOF\";\n) > temp.sh\nchmod +x temp.sh\n./temp.sh\nrm temp.sh\n", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "mkdir -p $DIR/_output\nCLOUDWATCH_NAMESPACE=\"AppMeshExample/gateway-envoy/StatsD\"\nMESH_NAME=\"<Name of your AppMesh>\"\nVIRTUAL_NODE_NAME=\"<Name of your Virtual Node\"\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"$(basename ${DIR})\"\n\neval \"cat <<EOF\n$(<${DIR}/cw-dashboard.yaml.template)\nEOF\n\" >$DIR/_output/${VIRTUAL_NODE_NAME}-cw-dashboard.yaml\n\n        echo \"Deploying stack ${VIRTUAL_NODE_NAME}-cw-dashboard, this may take a few minutes...\"\n        aws cloudformation deploy \\\n            --no-fail-on-empty-changeset \\\n            --stack-name ${PROJECT_NAME}-${VIRTUAL_NODE_NAME} \\\n            --template-file \"$DIR/_output/$VIRTUAL_NODE_NAME-cw-dashboard.yaml\" \\\n            --capabilities CAPABILITY_IAM \\\n            --parameter-overrides \\\n            \"DashboardName=${PROJECT_NAME}-${VIRTUAL_NODE_NAME}\"", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\nif [ -z \"${ENVOY_IMAGE}\" ]; then\n    echo \"ENVOY_IMAGE environment is not defined\"\n    exit 1\nfi\n\nif [ -z \"${COLOR_GATEWAY_IMAGE}\" ]; then\n    echo \"COLOR_GATEWAY_IMAGE environment is not defined\"\n    exit 1\nfi\n\nif [ -z \"${COLOR_TELLER_IMAGE}\" ]; then\n    echo \"COLOR_TELLER_IMAGE environment is not defined\"\n    exit 1\nfi\n\nstack_output=$(aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation describe-stacks --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" --output json \\\n    | jq '.Stacks[].Outputs[]')\n\ntask_role_arn=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"TaskIamRoleArn\") | .OutputValue'))\n\nexecution_role_arn=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"TaskExecutionIamRoleArn\") | .OutputValue'))\n\necs_service_log_group=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"ECSServiceLogGroup\") | .OutputValue'))\n\nenvoy_log_level=\"debug\"\n\ngenerate_xray_container_json() {\n    app_name=$1\n    xray_container_json=$(jq -n \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg AWS_LOG_STREAM_PREFIX \"${app_name}-xray\" \\\n    -f \"${DIR}/xray-container.json\")\n}\n\ngenerate_envoy_container_json() {\n    app_name=$1\n    envoy_container_json=$(jq -n \\\n    --arg ENVOY_IMAGE $ENVOY_IMAGE \\\n    --arg VIRTUAL_NODE \"mesh/$MESH_NAME/virtualNode/${app_name}-vn\" \\\n    --arg APPMESH_XDS_ENDPOINT \"${APPMESH_XDS_ENDPOINT}\" \\\n    --arg ENVOY_LOG_LEVEL $envoy_log_level \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg AWS_LOG_STREAM_PREFIX \"${app_name}-envoy\" \\\n    -f \"${DIR}/envoy-container.json\")\n}\n\ngenerate_sidecars() {\n    app_name=$1\n    generate_envoy_container_json ${app_name}\n    generate_xray_container_json ${app_name}\n}\n\ngenerate_color_teller_task_def() {\n    color=$1\n    task_def_json=$(jq -n \\\n    --arg NAME \"$ENVIRONMENT_NAME-ColorTeller-${color}\" \\\n    --arg STAGE \"$APPMESH_STAGE\" \\\n    --arg COLOR \"${color}\" \\\n    --arg APP_IMAGE $COLOR_TELLER_IMAGE \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_LOG_STREAM_PREFIX_APP \"colorteller-${color}-app\" \\\n    --arg TASK_ROLE_ARN $task_role_arn \\\n    --arg EXECUTION_ROLE_ARN $execution_role_arn \\\n    --argjson ENVOY_CONTAINER_JSON \"${envoy_container_json}\" \\\n    --argjson XRAY_CONTAINER_JSON \"${xray_container_json}\" \\\n    -f \"${DIR}/colorteller-base-task-def.json\")\n    task_def=$(aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    ecs register-task-definition \\\n    --cli-input-json \"$task_def_json\" \\\n    --output json)\n}\n\n# Color Gateway Task Definition\ngenerate_sidecars \"colorgateway\"\ntask_def_json=$(jq -n \\\n    --arg NAME \"$ENVIRONMENT_NAME-ColorGateway\" \\\n    --arg STAGE \"$APPMESH_STAGE\" \\\n    --arg COLOR_TELLER_ENDPOINT \"colorteller.$SERVICES_DOMAIN:9080\" \\\n    --arg TCP_ECHO_ENDPOINT \"tcpecho.$SERVICES_DOMAIN:2701\" \\\n    --arg APP_IMAGE $COLOR_GATEWAY_IMAGE \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_LOG_STREAM_PREFIX_APP \"colorgateway-app\" \\\n    --arg TASK_ROLE_ARN $task_role_arn \\\n    --arg EXECUTION_ROLE_ARN $execution_role_arn \\\n    --argjson ENVOY_CONTAINER_JSON \"${envoy_container_json}\" \\\n    --argjson XRAY_CONTAINER_JSON \"${xray_container_json}\" \\\n    -f \"${DIR}/colorgateway-base-task-def.json\")\ntask_def=$(aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    ecs register-task-definition \\\n    --cli-input-json \"$task_def_json\" \\\n    --output json )\ncolorgateway_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))\n\n# Color Teller White Task Definition\ngenerate_sidecars \"colorteller-white\"\ngenerate_color_teller_task_def \"white\"\ncolorteller_white_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))\n\n# Color Teller Red Task Definition\ngenerate_sidecars \"colorteller-red\"\ngenerate_color_teller_task_def \"red\"\ncolorteller_red_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))\n\n# Color Teller Blue Task Definition\ngenerate_sidecars \"colorteller-blue\"\ngenerate_color_teller_task_def \"blue\"\ncolorteller_blue_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))\n\n# Color Teller Black Task Definition\ngenerate_sidecars \"colorteller-black\"\ngenerate_color_teller_task_def \"black\"\ncolorteller_black_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))", "num_lines": 131}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# ecs-colorapp.yaml expects \"true\" or \"false\" (default is \"false\")\n# will deploy the TesterService, which perpetually invokes /color to generate history\n: \"${DEPLOY_TESTER:=false}\"\n\n# Creating Task Definitions\nsource ${DIR}/create-task-defs.sh\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-colorapp\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-colorapp.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    ColorGatewayTaskDefinition=\"${colorgateway_task_def_arn}\" \\\n    ColorTellerWhiteTaskDefinition=\"${colorteller_white_task_def_arn}\" \\\n    ColorTellerRedTaskDefinition=\"${colorteller_red_task_def_arn}\" \\\n    ColorTellerBlueTaskDefinition=\"${colorteller_blue_task_def_arn}\" \\\n    ColorTellerBlackTaskDefinition=\"${colorteller_black_task_def_arn}\" \\\n    DeployTester=\"${DEPLOY_TESTER}\"\n\n", "num_lines": 30}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\ncat << CONFIG_EOF > \"${DIR}/colorapp.yaml\"\napiVersion: v1\nkind: Service\nmetadata:\n  name: colorgateway\n  labels:\n    app: colorgateway\nspec:\n  ports:\n  - port: 9080\n    name: http\n  selector:\n    app: colorgateway\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: colorgateway\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: colorgateway\n      version: v1\n  template:\n    metadata:\n      labels:\n        app: colorgateway\n        version: v1\n    spec:\n      containers:\n        - name: colorgateway\n          image: \"${COLOR_GATEWAY_IMAGE}\"\n          ports:\n            - containerPort: 9080\n          env:\n            - name: \"SERVER_PORT\"\n              value: \"9080\"\n            - name: \"COLOR_TELLER_ENDPOINT\"\n              value: \"colorteller.${SERVICES_DOMAIN}:9080\"\n            - name: \"TCP_ECHO_ENDPOINT\"\n              value: \"tcpecho.${SERVICES_DOMAIN}:2701\"\n        - name: envoy\n          image: \"${ENVOY_IMAGE}\"\n          securityContext:\n            runAsUser: 1337\n          env:\n            - name: \"APPMESH_RESOURCE_ARN\"\n              value: \"mesh/${MESH_NAME}/virtualNode/colorgateway-vn\"\n            - name: \"ENVOY_LOG_LEVEL\"\n              value: \"debug\"\n            - name: \"AWS_REGION\"\n              value: \"${AWS_DEFAULT_REGION}\"\n      initContainers:\n        - name: proxyinit\n          image: 111345817488.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/aws-appmesh-proxy-route-manager:v2\n          securityContext:\n            capabilities:\n              add:\n                - NET_ADMIN\n          env:\n            - name: \"APPMESH_START_ENABLED\"\n              value: \"1\"\n            - name: \"APPMESH_IGNORE_UID\"\n              value: \"1337\"\n            - name: \"APPMESH_ENVOY_INGRESS_PORT\"\n              value: \"15000\"\n            - name: \"APPMESH_ENVOY_EGRESS_PORT\"\n              value: \"15001\"\n            - name: \"APPMESH_APP_PORTS\"\n              value: \"9080\"\n            - name: \"APPMESH_EGRESS_IGNORED_IP\"\n              value: \"169.254.169.254\"\n---\n\napiVersion: v1\nkind: Service\nmetadata:\n  name: colorteller\n  labels:\n    app: colorteller\nspec:\n  ports:\n  - port: 9080\n    name: http\n  selector:\n    app: colorteller\n    version: white\n---\n\n# white\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: colorteller-white\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: colorteller\n      version: white\n  template:\n    metadata:\n      labels:\n        app: colorteller\n        version: white\n    spec:\n      containers:\n        - name: colorteller\n          image: ${COLOR_TELLER_IMAGE}\n          ports:\n            - containerPort: 9080\n          env:\n            - name: \"SERVER_PORT\"\n              value: \"9080\"\n            - name: \"COLOR\"\n              value: \"white\"\n        - name: envoy\n          image: ${ENVOY_IMAGE}\n          securityContext:\n            runAsUser: 1337\n          env:\n            - name: \"APPMESH_RESOURCE_ARN\"\n              value: \"mesh/${MESH_NAME}/virtualNode/colorteller-white-vn\"\n            - name: \"ENVOY_LOG_LEVEL\"\n              value: \"debug\"\n            - name: \"AWS_REGION\"\n              value: ${AWS_DEFAULT_REGION}\n      initContainers:\n        - name: proxyinit\n          image: 111345817488.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/aws-appmesh-proxy-route-manager:v2\n          securityContext:\n            capabilities:\n              add:\n                - NET_ADMIN\n          env:\n            - name: \"APPMESH_START_ENABLED\"\n              value: \"1\"\n            - name: \"APPMESH_IGNORE_UID\"\n              value: \"1337\"\n            - name: \"APPMESH_ENVOY_INGRESS_PORT\"\n              value: \"15000\"\n            - name: \"APPMESH_ENVOY_EGRESS_PORT\"\n              value: \"15001\"\n            - name: \"APPMESH_APP_PORTS\"\n              value: \"9080\"\n            - name: \"APPMESH_EGRESS_IGNORED_IP\"\n              value: \"169.254.169.254\"\n---\n\n\n# black\napiVersion: v1\nkind: Service\nmetadata:\n  name: colorteller-black\n  labels:\n    app: colorteller\n    version: black\nspec:\n  ports:\n  - port: 9080\n    name: http\n  selector:\n    app: colorteller\n    version: black\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: colorteller-black\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: colorteller\n      version: black\n  template:\n    metadata:\n      labels:\n        app: colorteller\n        version: black\n    spec:\n      containers:\n        - name: colorteller\n          image: ${COLOR_TELLER_IMAGE}\n          ports:\n            - containerPort: 9080\n          env:\n            - name: \"SERVER_PORT\"\n              value: \"9080\"\n            - name: \"COLOR\"\n              value: \"black\"\n        - name: envoy\n          image: ${ENVOY_IMAGE}\n          securityContext:\n            runAsUser: 1337\n          env:\n            - name: \"APPMESH_RESOURCE_ARN\"\n              value: \"mesh/${MESH_NAME}/virtualNode/colorteller-black-vn\"\n            - name: \"ENVOY_LOG_LEVEL\"\n              value: \"debug\"\n            - name: \"AWS_REGION\"\n              value: ${AWS_DEFAULT_REGION}\n      initContainers:\n        - name: proxyinit\n          image: 111345817488.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/aws-appmesh-proxy-route-manager:v2\n          securityContext:\n            capabilities:\n              add:\n                - NET_ADMIN\n          env:\n            - name: \"APPMESH_START_ENABLED\"\n              value: \"1\"\n            - name: \"APPMESH_IGNORE_UID\"\n              value: \"1337\"\n            - name: \"APPMESH_ENVOY_INGRESS_PORT\"\n              value: \"15000\"\n            - name: \"APPMESH_ENVOY_EGRESS_PORT\"\n              value: \"15001\"\n            - name: \"APPMESH_APP_PORTS\"\n              value: \"9080\"\n            - name: \"APPMESH_EGRESS_IGNORED_IP\"\n              value: \"169.254.169.254\"\n---\n\n# blue\napiVersion: v1\nkind: Service\nmetadata:\n  name: colorteller-blue\n  labels:\n    app: colorteller\n    version: blue\nspec:\n  ports:\n  - port: 9080\n    name: http\n  selector:\n    app: colorteller\n    version: blue\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: colorteller-blue\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: colorteller\n      version: blue\n  template:\n    metadata:\n      labels:\n        app: colorteller\n        version: blue\n    spec:\n      containers:\n        - name: colorteller\n          image: ${COLOR_TELLER_IMAGE}\n          ports:\n            - containerPort: 9080\n          env:\n            - name: \"SERVER_PORT\"\n              value: \"9080\"\n            - name: \"COLOR\"\n              value: \"blue\"\n        - name: envoy\n          image: ${ENVOY_IMAGE}\n          securityContext:\n            runAsUser: 1337\n          env:\n            - name: \"APPMESH_RESOURCE_ARN\"\n              value: \"mesh/${MESH_NAME}/virtualNode/colorteller-blue-vn\"\n            - name: \"ENVOY_LOG_LEVEL\"\n              value: \"debug\"\n            - name: \"AWS_REGION\"\n              value: ${AWS_DEFAULT_REGION}\n      initContainers:\n        - name: proxyinit\n          image: 111345817488.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/aws-appmesh-proxy-route-manager:v2\n          securityContext:\n            capabilities:\n              add:\n                - NET_ADMIN\n          env:\n            - name: \"APPMESH_START_ENABLED\"\n              value: \"1\"\n            - name: \"APPMESH_IGNORE_UID\"\n              value: \"1337\"\n            - name: \"APPMESH_ENVOY_INGRESS_PORT\"\n              value: \"15000\"\n            - name: \"APPMESH_ENVOY_EGRESS_PORT\"\n              value: \"15001\"\n            - name: \"APPMESH_APP_PORTS\"\n              value: \"9080\"\n            - name: \"APPMESH_EGRESS_IGNORED_IP\"\n              value: \"169.254.169.254\"\n---\n\n# red\napiVersion: v1\nkind: Service\nmetadata:\n  name: colorteller-red\n  labels:\n    app: colorteller\n    version: red\nspec:\n  ports:\n  - port: 9080\n    name: http\n  selector:\n    app: colorteller\n    version: red\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: colorteller-red\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: colorteller\n      version: red\n  template:\n    metadata:\n      labels:\n        app: colorteller\n        version: red\n    spec:\n      containers:\n        - name: colorteller\n          image: ${COLOR_TELLER_IMAGE}\n          ports:\n            - containerPort: 9080\n          env:\n            - name: \"SERVER_PORT\"\n              value: \"9080\"\n            - name: \"COLOR\"\n              value: \"red\"\n        - name: envoy\n          image: ${ENVOY_IMAGE}\n          securityContext:\n            runAsUser: 1337\n          env:\n            - name: \"APPMESH_RESOURCE_ARN\"\n              value: \"mesh/${MESH_NAME}/virtualNode/colorteller-red-vn\"\n            - name: \"ENVOY_LOG_LEVEL\"\n              value: \"debug\"\n            - name: \"AWS_REGION\"\n              value: ${AWS_DEFAULT_REGION}\n      initContainers:\n        - name: proxyinit\n          image: 111345817488.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/aws-appmesh-proxy-route-manager:v2\n          securityContext:\n            capabilities:\n              add:\n                - NET_ADMIN\n          env:\n            - name: \"APPMESH_START_ENABLED\"\n              value: \"1\"\n            - name: \"APPMESH_IGNORE_UID\"\n              value: \"1337\"\n            - name: \"APPMESH_ENVOY_INGRESS_PORT\"\n              value: \"15000\"\n            - name: \"APPMESH_ENVOY_EGRESS_PORT\"\n              value: \"15001\"\n            - name: \"APPMESH_APP_PORTS\"\n              value: \"9080\"\n            - name: \"APPMESH_EGRESS_IGNORED_IP\"\n              value: \"169.254.169.254\"\n---\n\n# tester-app\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: tester-app\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: tester-app\n  template:\n    metadata:\n      labels:\n        app: tester-app\n    spec:\n      containers:\n        - name: tester-app\n          image: \"tstrohmeier/alpine-infinite-curl\"\n          env:\n            - name: \"HOST\"\n              value: \"http://colorgateway.${SERVICES_DOMAIN}:9080/color\"\n---\n\n# tcpecho\napiVersion: v1\nkind: Service\nmetadata:\n  name: tcpecho\n  labels:\n    app: tcpecho\nspec:\n  ports:\n  - port: 2701\n    name: tcpecho\n  selector:\n    app: tcpecho\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: tcpecho\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: tcpecho\n      version: v1\n  template:\n    metadata:\n      labels:\n        app: tcpecho\n        version: v1\n    spec:\n      containers:\n        - name: tcpecho\n          image: cjimti/go-echo\n          ports:\n            - containerPort: 2701\n          env:\n            - name: \"TCP_PORT\"\n              value: \"2701\"\n            - name: \"NODE_NAME\"\n              value: \"mesh/${MESH_NAME}/virtualNode/tcpecho-vn\"\n---\nCONFIG_EOF", "num_lines": 447}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-appmesh-colorapp\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/appmesh-colorapp.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nshopt -s nullglob\n\n# Optional pre-load script\nif [ -f meshvars.sh ]; then\n    source meshvars.sh\nfi\n\nif [ ! -z \"$AWS_PROFILE\" ]; then\n    PROFILE_OPT=\"--profile ${AWS_PROFILE}\"\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nUPDATE_ROUTES_DIR=\"${DIR}/config/update_routes/\"\n\nsource \"$DIR/.region-config.sh\"\n\n: ${AWS_DEFAULT_REGION:=$DEFAULT_REGION}\n\nif [ \"$APPMESH_ENDPOINT\" = \"\" ]; then\n    appmesh_cmd=\"aws appmesh\"\nelse\n    appmesh_cmd=\"aws --endpoint-url \"${APPMESH_ENDPOINT}\" appmesh\"\nfi\n\nprint() {\n    printf \"[MESH] [$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\ncontains() {\n    local e match=\"$1\"\n    shift\n    for e; do [[ \"$e\" == \"$match\" ]] && return 0; done\n    return 1\n}\n\nsanity_check() {\n    if ! contains \"${AWS_DEFAULT_REGION}\" \"${SUPPORTED_REGIONS[@]}\"; then\n        err \"Region ${AWS_DEFAULT_REGION} is not supported at this time (Supported regions: ${SUPPORTED_REGIONS[*]})\"\n    fi\n\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nupdate_route() {\n    route_spec_file=$1\n    cmd=( $appmesh_cmd update-route --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${route_spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    sanity_check\n    files=($(ls \"${UPDATE_ROUTES_DIR}\"))\n    while true; do \\\n        f=${files[$RANDOM % ${#files[@]}]}\n        print \"Using route in file ${f}\"\n        update_route \"${UPDATE_ROUTES_DIR}/${f}\"\n        sleep ${SLEEP_TIME:-\"600s\"}\n    done\n}\n\nmain\n", "num_lines": 79}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nCOLOR_TELLER_IMAGE=${COLOR_TELLER_IMAGE:-\"${ECR_URL}/colorteller\"}\nGO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndescribe_create_ecr_registry() {\n    local repo_name=$1\n    local region=$2\n    aws ecr describe-repositories --repository-names ${repo_name} --region ${region} \\\n        || aws ecr create-repository --repository-name ${repo_name} --region ${region}\n}\n\n# build\ndocker build --build-arg GO_PROXY=$GO_PROXY -t $COLOR_TELLER_IMAGE ${DIR}\n\n# push\necr_login\ndescribe_create_ecr_registry colorteller ${AWS_DEFAULT_REGION}\ndocker push $COLOR_TELLER_IMAGE\n", "num_lines": 44}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nCOLOR_GATEWAY_IMAGE=${COLOR_GATEWAY_IMAGE:-\"${ECR_URL}/gateway\"}\nGO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndescribe_create_ecr_registry() {\n    local repo_name=$1\n    local region=$2\n    aws ecr describe-repositories --repository-names ${repo_name} --region ${region} \\\n        || aws ecr create-repository --repository-name ${repo_name} --region ${region}\n}\n\n# build\ndocker build --build-arg GO_PROXY=$GO_PROXY -t $COLOR_GATEWAY_IMAGE ${DIR}\n\n# push\necr_login\ndescribe_create_ecr_registry gateway ${AWS_DEFAULT_REGION}\ndocker push $COLOR_GATEWAY_IMAGE\n", "num_lines": 45}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n\nMESH=$1\nDELETE=$2\n\naccount=($(aws sts get-caller-identity --query \"Account\" | sed -e 's/^\"//' -e 's/\"$//'))\necho Running for account $account\n\nmeshes=($(aws appmesh list-meshes --query \"meshes[*].meshName\" --output text))\nservices=($(aws appmesh list-virtual-services --mesh-name $MESH --query \"virtualServices[*].virtualServiceName\" --output text))\nrouters=($(aws appmesh list-virtual-routers --mesh-name $MESH --query \"virtualRouters[*].virtualRouterName\" --output text))\nnodes=($(aws appmesh list-virtual-nodes --mesh-name $MESH --query \"virtualNodes[*].virtualNodeName\" --output text))\n\npods=($(kubectl get pods -nprod | awk ' { printf sep $1; sep=\" \"} ' | sed -e 's/NAME//g'))\n\necho Found Mesh: ${meshes[*]}\necho Found Virtual Services: ${services[*]}\necho Found Virtual Routers: ${routers[*]}\necho Found Virtual Nodes: ${nodes[*]}\necho Found pods: ${pods[*]}\n\necho\n\nfor vs in \"${services[@]}\"\ndo\n  # echo \"Virtual Service: $vs\"\n  if [ -n \"$DELETE\" ]; then\n    echo Deleting Virtual Service: $vs\n    aws appmesh delete-virtual-service --mesh-name $MESH --virtual-service-name $vs\n    sleep 3\n  fi\ndone\n\n\nfor vr in \"${routers[@]}\"\ndo\n    # echo \"Router: $vr\"\n\n    routes=($(aws appmesh list-routes --mesh-name $MESH --virtual-router-name $vr --query 'routes[*].routeName' --output text))\n    echo Found Route in ${vr}: ${routes[*]}\n\n    # Delete routes\n    for r in \"${routes[@]}\"\n    do\n      if [ -n \"$DELETE\" ]; then\n        echo Deleting route: $r\n        aws appmesh delete-route --mesh-name $MESH --route-name $r --virtual-router-name $vr\n        sleep 3\n      fi\n    done\n\n\n    echo\n\n    # Delete routers\n\n    if [ -n \"$DELETE\" ]; then\n      echo Deleting router: $vr\n      aws appmesh delete-virtual-router --mesh-name $MESH --virtual-router-name $vr\n      sleep 3\n    fi\ndone\n\n# delete Nodes\n\nfor vn in \"${nodes[@]}\"\ndo\n  if [ -n \"$DELETE\" ]; then\n    echo Deleting Virtual Node: $vn\n    aws appmesh delete-virtual-node --mesh-name $MESH --virtual-node-name $vn\n    sleep 3\n  fi\ndone\n\n\n# delete meshes\n\nfor m in \"${meshes[@]}\"\ndo\n  if [ -n \"$DELETE\" ]; then\n    echo Deleting App Mesh: $m\n    aws appmesh delete-mesh --mesh-name $m\n    sleep 3\n  fi\ndone\n", "num_lines": 86}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "echo\necho Remove Injector and App Mesh Controller components\necho\n\nkubectl delete -f 3_add_crds/virtual-service-definition.yaml\nkubectl delete -f 3_add_crds/virtual-node-definition.yaml\nkubectl delete -f 3_add_crds/mesh-definition.yaml\nkubectl delete -f 3_add_crds/controller-deployment.yaml\n\nkubectl delete secret aws-app-mesh-inject -nappmesh-inject\nkubectl delete -f 2_create_injector/inject.yaml\n\necho\necho Remove k8s DJ App NS, Deployments, and Services\necho\n\nkubectl delete deployment -nprod dj\nkubectl delete deployment -nprod metal-v1\nkubectl delete deployment -nprod metal-v2\nkubectl delete deployment -nprod jazz-v1\nkubectl delete deployment -nprod jazz-v2\n\nkubectl delete service -nprod dj\nkubectl delete service -nprod metal-v1\nkubectl delete service -nprod metal-v1\nkubectl delete service -nprod metal\nkubectl delete service -nprod jazz-v1\nkubectl delete service -nprod jazz-v2\nkubectl delete service -nprod jazz\n\nkubectl delete ns prod\n", "num_lines": 32}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "echo\necho Create Prod Namespace\necho\n\nkubectl create -f 1_create_the_initial_architecture/1_prod_ns.yaml\n\necho\necho Initial Deployments and Services\necho\n\nkubectl create -nprod -f 1_create_the_initial_architecture/1_initial_architecture_deployment.yaml\nkubectl create -nprod -f 1_create_the_initial_architecture/1_initial_architecture_services.yaml\n\necho\necho Create Injector Controller\necho\n\ncd 2_create_injector\n./create.sh\ncd ..\nkubectl label namespace prod appmesh.k8s.aws/sidecarInjectorWebhook=enabled\n\necho\necho Create CRDs\necho\n\nsleep 5\n\nkubectl apply -f 3_add_crds/mesh-definition.yaml\nkubectl apply -f 3_add_crds/virtual-node-definition.yaml\nkubectl apply -f 3_add_crds/virtual-service-definition.yaml\nkubectl apply -f 3_add_crds/controller-deployment.yaml\n\nsleep 5\n\necho\necho Create Mesh\necho\n\nkubectl create -nprod -f 4_create_initial_mesh_components/mesh.yaml\n\nsleep 5\n\necho\necho Create Virtual Nodes for Virtual Services\necho\n\nkubectl create -nprod -f 4_create_initial_mesh_components/nodes_representing_virtual_services.yaml\n\necho\necho Create Placeholder Services for Virtual Nodes for Virtual Services\necho\n\nkubectl create -nprod -f 4_create_initial_mesh_components/metal_and_jazz_placeholder_services.yaml\n\necho\necho Create Virtual Nodes for Physical Services and Virtual Services\necho\n\nkubectl create -nprod -f 4_create_initial_mesh_components/nodes_representing_physical_services.yaml\nkubectl apply -nprod -f 4_create_initial_mesh_components/virtual-services.yaml\n\necho\necho Create Jazz and Metal v2 Resources\necho\n\nkubectl apply -nprod -f 5_canary/jazz_v2.yaml\nkubectl apply -nprod -f 5_canary/jazz_service_update.yaml\nkubectl apply -nprod -f 5_canary/metal_v2.yaml\nkubectl apply -nprod -f 5_canary/metal_service_update.yaml\n\nsleep 30\n\necho\necho Bounce the deployments to include sidecars\necho\n\nkubectl patch deployment dj -nprod -p \"{\\\"spec\\\":{\\\"template\\\":{\\\"metadata\\\":{\\\"labels\\\":{\\\"date\\\":\\\"`date +'%s'`\\\"}}}}}\"\nkubectl patch deployment metal-v1 -nprod -p \"{\\\"spec\\\":{\\\"template\\\":{\\\"metadata\\\":{\\\"labels\\\":{\\\"date\\\":\\\"`date +'%s'`\\\"}}}}}\"\nkubectl patch deployment jazz-v1 -nprod -p \"{\\\"spec\\\":{\\\"template\\\":{\\\"metadata\\\":{\\\"labels\\\":{\\\"date\\\":\\\"`date +'%s'`\\\"}}}}}\"\n\necho\necho \"Waiting for pods to come back up.\"\necho\nsleep 30\n", "num_lines": 86}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "target=$1\n\necho \"Execing into pod and curling http://$target.prod.svc.cluster.local:9080\"\n\n\nthepod=$(kubectl get pods -l app=dj -o json -nprod | jq .items[0].metadata.name | sed 's/\"//g')\nkubectl exec $thepod -nprod -t -- bash -c \"while [ 1 ]; do curl -s http://{$target}.prod.svc.cluster.local:9080;echo; done\"\n", "num_lines": 8}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -o errexit\nset -o nounset\nset -o pipefail\n\nexport MESH_NAME=dj-app\nexport IMAGE_NAME=602401143452.dkr.ecr.us-west-2.amazonaws.com/amazon/aws-app-mesh-inject:v0.1.0\nexport MESH_REGION=\"\" # Leave this empty\n\nROOT=$(cd $(dirname $0)/; pwd)\n\nif [[ -z ${CA_BUNDLE:-} ]]; then\n    export CA_BUNDLE=$(kubectl config view --raw -o json --minify | jq -r '.clusters[0].cluster.\"certificate-authority-data\"' | tr -d '\"')\nfi\n\necho \"processing templates\"\neval \"cat <<EOF\n$(<${ROOT}/inject.yaml.template)\nEOF\n\" > ${ROOT}/inject.yaml\n\necho \"Created injector manifest at:${ROOT}/inject.yaml\"\n", "num_lines": 23}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "\n\nkubectl apply -f appmesh-ns.yaml\n./gen-cert.sh\necho\n./ca-bundle.sh\necho\nkubectl apply -f inject.yaml\necho\necho Waiting for pods to come up...\nsleep 15\necho\necho App Inject Pods and Services After Install:\necho\nkubectl get svc -nappmesh-inject\nkubectl get pods -nappmesh-inject\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "echo App Inject Pods and Services Before Uninstall:\necho\nkubectl get svc -nappmesh-inject\nkubectl get pods -nappmesh-inject\necho\necho Uninstalling...\necho\nkubectl delete deployment aws-app-mesh-inject -nappmesh-inject\nkubectl delete -f inject.yaml -nappmesh-inject\nkubectl delete -f appmesh-ns.yaml\necho\necho App Inject Pods and Services After Uninstall:\necho\nkubectl get svc -nappmesh-inject\nkubectl get pods -nappmesh-inject\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\ntitle=\"aws-app-mesh-inject\"\nnamespace=\"appmesh-inject\"\n\ncsrName=${title}.${namespace}\ntmpdir=$(mktemp -d)\necho \"creating certs in tmpdir ${tmpdir} \"\n\ncat <<EOF >> ${tmpdir}/csr.conf\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nDNS.1 = ${title}\nDNS.2 = ${title}.${namespace}\nDNS.3 = ${title}.${namespace}.svc\nEOF\n\nopenssl genrsa -out ${tmpdir}/server-key.pem 2048\nopenssl req -new -key ${tmpdir}/server-key.pem -subj \"/CN=${title}.${namespace}.svc\" -out ${tmpdir}/server.csr -config ${tmpdir}/csr.conf\n\n# clean-up any previously created CSR for our service. Ignore errors if not present.\nkubectl delete csr ${csrName} 2>/dev/null || true\n\n# create  server cert/key CSR and  send to k8s API\ncat <<EOF | kubectl create -f -\napiVersion: certificates.k8s.io/v1beta1\nkind: CertificateSigningRequest\nmetadata:\n  name: ${csrName}\nspec:\n  groups:\n  - system:authenticated\n  request: $(cat ${tmpdir}/server.csr | base64 | tr -d '\\n')\n  usages:\n  - digital signature\n  - key encipherment\n  - server auth\nEOF\n\n# verify CSR has been created\nwhile true; do\n    kubectl get csr ${csrName}\n    if [ \"$?\" -eq 0 ]; then\n        break\n    fi\ndone\n\n# approve and fetch the signed certificate\nkubectl certificate approve ${csrName}\n# verify certificate has been signed\nfor x in $(seq 10); do\n    serverCert=$(kubectl get csr ${csrName} -o jsonpath='{.status.certificate}')\n    if [[ ${serverCert} != '' ]]; then\n        break\n    fi\n    sleep 1\ndone\nif [[ ${serverCert} == '' ]]; then\n    echo \"ERROR: After approving csr ${csrName}, the signed certificate did not appear on the resource. Giving up after 10 attempts.\" >&2\n    exit 1\nfi\necho ${serverCert} | openssl base64 -d -A -out ${tmpdir}/server-cert.pem\n\n\n# create the secret with CA cert and server cert/key\nkubectl create secret generic ${title} \\\n        --from-file=key.pem=${tmpdir}/server-key.pem \\\n        --from-file=cert.pem=${tmpdir}/server-cert.pem \\\n        --dry-run -o yaml | kubectl -n ${namespace} apply -f -\n", "num_lines": 77}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-appmesh-mesh\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/appmesh-mesh.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    ClusterSize=\"${CLUSTER_SIZE:-5}\"\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-eks-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/eks-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\"", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nif [ ! -z \"${AWS_PROFILE}\" ]; then\n    PROFILE_OPT=\"--profile ${AWS_PROFILE}\"\nfi\n\nif [ \"$APPMESH_ENDPOINT\" = \"\" ]; then\n    appmesh_cmd=\"aws appmesh\"\nelse\n    appmesh_cmd=\"aws --endpoint-url \"${APPMESH_ENDPOINT}\" appmesh\"\nfi\n\nvirtual_services=($($appmesh_cmd list-virtual-services \\\n    ${PROFILE_OPT} \\\n    --mesh-name \"${MESH_NAME}\" \\\n    | jq -r \".virtualServices[].virtualServiceName\"))\n\nfor virtual_service_name in ${virtual_services[@]}\ndo\n    $appmesh_cmd delete-virtual-service \\\n        ${PROFILE_OPT} \\\n        --mesh-name \"${MESH_NAME}\" \\\n        --virtual-service-name \"${virtual_service_name}\" || echo \"Unable to delete virtual-service $virtual_service_name $?\"\ndone\n\nvirtual_routers=($($appmesh_cmd list-virtual-routers \\\n    ${PROFILE_OPT} \\\n    --mesh-name \"${MESH_NAME}\" \\\n    | jq -r \".virtualRouters[].virtualRouterName\"))\n\nfor virtual_router_name in ${virtual_routers[@]}\ndo\n    routes=($($appmesh_cmd list-routes \\\n        ${PROFILE_OPT} \\\n        --mesh-name \"${MESH_NAME}\" \\\n        --virtual-router-name \"${virtual_router_name}\" \\\n        | jq -r \".routes[].routeName\"))\n\n    for route_name in ${routes[@]}\n    do\n        $appmesh_cmd delete-route \\\n            ${PROFILE_OPT} \\\n            --mesh-name \"${MESH_NAME}\" \\\n            --virtual-router-name \"${virtual_router_name}\" \\\n            --route-name \"${route_name}\" || echo \"Unable to delete route $route_name $?\"\n    done\ndone\n\nfor virtual_router_name in ${virtual_routers[@]}\ndo\n    $appmesh_cmd delete-virtual-router \\\n        ${PROFILE_OPT} \\\n        --mesh-name \"${MESH_NAME}\" \\\n        --virtual-router-name \"${virtual_router_name}\" || echo \"Unable to delete virtual-router $virtual_router_name $?\"\ndone\n\n\nvirtual_nodes=($($appmesh_cmd list-virtual-nodes \\\n    ${PROFILE_OPT} \\\n    --mesh-name \"${MESH_NAME}\" \\\n    | jq -r \".virtualNodes[].virtualNodeName\"))\n\nfor virtual_node_name in ${virtual_nodes[@]}\ndo\n    $appmesh_cmd delete-virtual-node \\\n        ${PROFILE_OPT} \\\n        --mesh-name \"${MESH_NAME}\" \\\n        --virtual-node-name \"$virtual_node_name\" || echo \"Unable to delete virtual-node $virtual_node_name $?\"\ndone\n\n$appmesh_cmd delete-mesh ${PROFILE_OPT} --mesh-name \"${MESH_NAME}\" || echo \"Unable to delete mesh ${MESH_NAME} $?\"\n", "num_lines": 74}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nECR_URL=$1\n\nbuild_vegeta() {\n    aws ecr describe-repositories --repository-name appmesh/vegeta-trafficgen >/dev/null 2>&1 || aws ecr create-repository --repository-name appmesh/vegeta-trafficgen >/dev/null\n    docker build -t ${ECR_URL}/appmesh/vegeta-trafficgen ${DIR}/.\n    docker push ${ECR_URL}/appmesh/vegeta-trafficgen\n}\n\nbuild_vegeta\n", "num_lines": 13}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nexport AWS_PAGER=\"\"\n\necho \"Deleting the EKS clusters\"\neksctl delete -p frontend cluster -f /tmp/eks-frontend-configuration.yml\neksctl delete -p backend cluster -f /tmp/eks-backend-configuration.yml\n\necho \"Deleting the App Mesh virtual services\"\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-db\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name redis-server\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-appserver\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-ui\n\necho \"Deleting the App Mesh virtual router\"\naws --profile frontend appmesh delete-route \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-router-name yelb-appserver-virtual-router \\\n    --route-name route-to-yelb-appserver\n\naws --profile frontend appmesh delete-virtual-router \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-router-name yelb-appserver-virtual-router\n\necho \"Deleting the App Mesh virtual nodes\"\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name redis-server_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-db_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-appserver_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-ui_yelb\n\necho \"Deleting the App Mesh mesh\"\naws --profile frontend appmesh delete-mesh \\\n    --mesh-name am-multi-account-mesh\n\necho \"Deleting Cloud Map Services\"\nNAMESPACE=$(aws --profile backend servicediscovery list-namespaces | \\\n  jq -r ' .Namespaces[] | select ( .Properties.HttpProperties.HttpName == \"am-multi-account.local\" ) | .Id ');\nSERVICE_ID=$(aws --profile backend servicediscovery list-services --filters Name=\"NAMESPACE_ID\",Values=$NAMESPACE,Condition=\"EQ\" | jq -r ' .Services[] | [ .Id ] | @tsv ' )\naws --profile backend servicediscovery list-instances --service-id $SERVICE_ID | jq -r ' .Instances[] | [ .Id ] | @tsv ' |\\\n  while IFS=$'\\t' read -r instanceId; do \n    aws --profile backend servicediscovery deregister-instance --service-id $SERVICE_ID --instance-id $instanceId\n  done\naws --profile backend servicediscovery list-services \\\n  --filters Name=\"NAMESPACE_ID\",Values=$NAMESPACE,Condition=\"EQ\" | \\\njq -r ' .Services[] | [ .Id ] | @tsv ' | \\\n  while IFS=$'\\t' read -r serviceId; do \n    aws --profile backend servicediscovery delete-service \\\n      --id $serviceId\n  done\n\necho \"Deleting CloudFormation templates\"\naws --profile backend cloudformation delete-stack \\\n  --stack-name am-multi-account-routes\naws --profile backend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-routes\n\naws --profile backend cloudformation delete-stack \\\n  --stack-name am-multi-account-infra\naws --profile backend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-infra\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-shared-mesh\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-shared-mesh\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-routes\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-routes\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-infra\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-infra\n\necho \"Cleanup finished\"", "num_lines": 100}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Creating a ClusterConfig file for the Frontend cluster...\"\n\nFRONTEND_AWS_REGION=$(aws --profile frontend configure get region);\nFRONTEND_PRIVSUB1_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet1\") | .Value');\nFRONTEND_PRIVSUB2_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet2\") | .Value');\nFRONTEND_PUBSUB1_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet1\") | .Value');\nFRONTEND_PUBSUB2_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet2\") | .Value');\nFRONTEND_PRIVSUB1_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PRIVSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PRIVSUB2_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PRIVSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PUBSUB1_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PUBSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PUBSUB2_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PUBSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_NODES_IAM_POLICY=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSDPolicy\") | .Value');\n\ncat > /tmp/eks-frontend-configuration.yml <<-EKS_FRONTEND_CONF\n  apiVersion: eksctl.io/v1alpha5\n  kind: ClusterConfig  \n  metadata:\n    name: am-multi-account-1\n    region: $FRONTEND_AWS_REGION\n    version: \"1.18\"\n  vpc:\n    subnets:\n      private:\n        $FRONTEND_PRIVSUB1_AZ: { id: $FRONTEND_PRIVSUB1_ID }\n        $FRONTEND_PRIVSUB2_AZ: { id: $FRONTEND_PRIVSUB2_ID }\n      public:\n        $FRONTEND_PUBSUB1_AZ: { id: $FRONTEND_PUBSUB1_ID }\n        $FRONTEND_PUBSUB2_AZ: { id: $FRONTEND_PUBSUB2_ID }\n  nodeGroups:\n    - name: am-multi-account-1-ng\n      labels: { role: workers }\n      instanceType: t3.large\n      desiredCapacity: 3\n      ssh: \n        allow: false\n      privateNetworking: true\n      iam:\n        attachPolicyARNs: \n          - $FRONTEND_NODES_IAM_POLICY\n          - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n          - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n          - arn:aws:iam::aws:policy/ElasticLoadBalancingFullAccess\n          - arn:aws:iam::aws:policy/AWSAppMeshFullAccess\n        withAddonPolicies:\n          xRay: true\n          cloudWatch: true\n          externalDNS: true\nEKS_FRONTEND_CONF\n\necho \"Creating the Frontend EKS cluster...\"\neksctl create -p frontend cluster -f /tmp/eks-frontend-configuration.yml\n\necho \"Creating a ClusterConfig file for the Backend cluster...\"\n\nBACKEND_AWS_REGION=$(aws --profile backend configure get region);\nBACKEND_PRIVSUB1_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet1\") | .Value');\nBACKEND_PRIVSUB2_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet2\") | .Value');\nBACKEND_PUBSUB1_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet1\") | .Value');\nBACKEND_PUBSUB2_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet2\") | .Value');\nBACKEND_PRIVSUB1_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PRIVSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PRIVSUB2_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PRIVSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PUBSUB1_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PUBSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PUBSUB2_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PUBSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_NODES_IAM_POLICY=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSDPolicy\") | .Value');\nBACKEND_NODES_SECURITY_GROUP=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSecurityGroup\") | .Value');\n\ncat > /tmp/eks-backend-configuration.yml <<-EKS_BACKEND_CONF\n  apiVersion: eksctl.io/v1alpha5\n  kind: ClusterConfig  \n  metadata:\n    name: am-multi-account-2\n    region: $BACKEND_AWS_REGION\n    version: \"1.18\"\n  vpc:\n    subnets:\n      private:\n        $BACKEND_PRIVSUB1_AZ: { id: $BACKEND_PRIVSUB1_ID }\n        $BACKEND_PRIVSUB2_AZ: { id: $BACKEND_PRIVSUB2_ID }\n      public:\n        $BACKEND_PUBSUB1_AZ: { id: $BACKEND_PUBSUB1_ID }\n        $BACKEND_PUBSUB2_AZ: { id: $BACKEND_PUBSUB2_ID }\n  nodeGroups:\n    - name: am-multi-account-2-ng\n      labels: { role: workers }\n      instanceType: t3.large\n      desiredCapacity: 3\n      ssh: \n        allow: false\n      privateNetworking: true\n      securityGroups:\n        withShared: true\n        withLocal: true\n        attachIDs: ['$BACKEND_NODES_SECURITY_GROUP']\n      iam:\n        attachPolicyARNs: \n          - $BACKEND_NODES_IAM_POLICY\n          - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n          - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n          - arn:aws:iam::aws:policy/ElasticLoadBalancingFullAccess\n          - arn:aws:iam::aws:policy/AWSAppMeshFullAccess\n        withAddonPolicies:\n          xRay: true\n          cloudWatch: true\n          externalDNS: true\nEKS_BACKEND_CONF\n\necho \"Creating the Backend EKS cluster...\"\neksctl create -p backend cluster -f /tmp/eks-backend-configuration.yml", "num_lines": 112}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Creating the Frontend Account VPC...\"\n\naws --profile frontend cloudformation deploy \\\n--template-file infrastructure/infrastructure_frontend.yaml \\\n--parameter-overrides \\\n\"BackendAccountId=$(aws --profile backend sts get-caller-identity | jq -r .Account)\" \\\n--stack-name am-multi-account-infra \\\n--capabilities CAPABILITY_IAM\n\necho \"Creating the Backend Account VPC...\"\n\naws --profile backend cloudformation deploy \\\n--template-file infrastructure/infrastructure_backend.yaml \\\n--parameter-overrides \\\n\"FrontendAccountId=$(aws --profile frontend sts get-caller-identity | jq -r .Account)\" \\\n\"PeerVPCId=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPC\") | .Value')\" \\\n\"PeerRoleArn=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPCPeerRole\") | .Value')\" \\\n--stack-name am-multi-account-infra \\\n--capabilities CAPABILITY_IAM\n\necho \"Creating the VPC peering routes...\"\n\naws --profile frontend cloudformation deploy \\\n--template-file infrastructure/frontend_vpc_peering_routes.yaml \\\n--parameter-overrides \\\n\"VPCPeeringConnectionId=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPCPeeringConnectionId\") | .Value')\" \\\n--stack-name am-multi-account-routes \\\n--capabilities CAPABILITY_IAM\n\naws --profile backend cloudformation deploy \\\n--template-file infrastructure/backend_vpc_peering_routes.yaml \\\n--stack-name am-multi-account-routes \\\n--capabilities CAPABILITY_IAM\n\n", "num_lines": 39}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#CreateCA\nexport certificateAuthorityArn=$(aws acm-pca create-certificate-authority --certificate-authority-configuration file://ca_config.txt --revocation-configuration file://revoke_config.txt --certificate-authority-type \"ROOT\" --idempotency-token 98256344 --tags  Key=Name,Value=MyAppMeshPCA --profile frontend |jq -r '.CertificateAuthorityArn' )\n\nsleep 0.5\n\nexport csr1=$(aws acm-pca get-certificate-authority-csr --certificate-authority-arn $certificateAuthorityArn --profile frontend |jq '.Csr')   \n\necho $csr1 > ca.csr\nawk '{gsub(/\\\\n/,\"\\n\")}1' ca.csr > ca_csr.csr\nsed -i 's/\\\"//g' ca_csr.csr\n\n\n\nexport CertificateArn=$(aws acm-pca issue-certificate --certificate-authority-arn $certificateAuthorityArn --csr file://ca_csr.csr --signing-algorithm SHA256WITHRSA --template-arn arn:aws:acm-pca:::template/RootCACertificate/V1 --validity Value=10,Type=\"YEARS\" --idempotency-token 1234 --profile frontend | jq -r '.CertificateArn' )\n\n\ncertificate=$(aws acm-pca get-certificate --certificate-authority-arn $certificateAuthorityArn --certificate-arn $CertificateArn --profile frontend |jq '.Certificate')\n\necho $certificate > certificate.cer\nawk '{gsub(/\\\\n/,\"\\n\")}1' certificate.cer  > cert.cer\nsed -i 's/\\\"//g' cert.cer\naws acm-pca import-certificate-authority-certificate --certificate-authority-arn $certificateAuthorityArn  --certificate file://cert.cer --profile frontend                       \n\naws acm-pca create-permission  --certificate-authority-arn $certificateAuthorityArn --actions IssueCertificate GetCertificate ListPermissions --principal acm.amazonaws.com --profile frontend\n\n#RAMShareCA\nexport frontendaccount=$(aws sts get-caller-identity --profile frontend | jq -r .'Account')\nexport backendaccount=$(aws sts get-caller-identity --profile backend | jq -r .'Account')\n\nexport resourceshareArn=$(aws ram create-resource-share --name Shared_Private_CA_MESH --resource-arn $certificateAuthorityArn --principals $backendaccount --profile frontend | jq -r '.resourceShare.resourceShareArn')\n\nsleep 1 \n\nexport CA_RESOURCE_INVITE_ARN=$(aws --profile backend ram get-resource-share-invitations | jq -r '.resourceShareInvitations[]|select (.resourceShareArn=='\\\"$resourceshareArn\\\"')|.resourceShareInvitationArn')\n\naws --profile backend ram accept-resource-share-invitation --resource-share-invitation-arn $CA_RESOURCE_INVITE_ARN\n\n\n#UpdateVirtualNodes\nexport backend_certificate_arn=$(aws acm request-certificate --domain-name \"*.example.com\" --certificate-authority-arn $certificateAuthorityArn  --query CertificateArn --output text --profile backend) \nexport frontend_certificate_arn=$(aws acm request-certificate --domain-name \"*.example.com\" --certificate-authority-arn $certificateAuthorityArn  --query CertificateArn --output text --profile frontend)\n\n\nexport frontendworkerrole=$(eksctl get iamidentitymapping --profile frontend --cluster am-multi-account-1  -o json |jq -r '.[].rolearn |split(\"/\")|.[1]')\nexport backendworkerrole=$(eksctl get iamidentitymapping --profile backend --cluster am-multi-account-2  -o json |jq -r '.[].rolearn |split(\"/\")|.[1]')\n\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSCertificateManagerReadOnly --role-name $frontendworkerrole --profile frontend\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSCertificateManagerPrivateCAReadOnly --role-name $frontendworkerrole --profile frontend\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSAppMeshPreviewEnvoyAccess --role-name $frontendworkerrole --profile frontend\n\n\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSCertificateManagerReadOnly --role-name $backendworkerrole  --profile backend\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSCertificateManagerPrivateCAReadOnly --role-name $backendworkerrole --profile backend\naws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AWSAppMeshPreviewEnvoyAccess --role-name $backendworkerrole --profile backend\n\n\n\nsed -e  \"s%CERTIFICATE_ARN%\"$backend_certificate_arn\"%g\" -e \"s%CA_ARN%\"$certificateAuthorityArn\"%g\" -e \"s%FRONTEND_ACCOUNT%\"$frontendaccount\"%g\" redis_update > redis_update.json\nsed -e  \"s%CERTIFICATE_ARN%\"$backend_certificate_arn\"%g\" -e \"s%CA_ARN%\"$certificateAuthorityArn\"%g\" -e \"s%FRONTEND_ACCOUNT%\"$frontendaccount\"%g\" appserver_update > appserver_update.json\nsed -e  \"s%CERTIFICATE_ARN%\"$backend_certificate_arn\"%g\" -e \"s%CA_ARN%\"$certificateAuthorityArn\"%g\" -e \"s%FRONTEND_ACCOUNT%\"$frontendaccount\"%g\" yelb_db_update > yelb_db_update.json\nsed -e  \"s%FRONTEND_CERTIFICATE_ARN%\"$frontend_certificate_arn\"%g\" -e \"s%CA_ARN%\"$certificateAuthorityArn\"%g\" -e \"s%FRONTEND_ACCOUNT%\"$frontendaccount\"%g\" yelb_ui_update > yelb_ui_update.json\n\n\nkubectl apply -f mesh/redis_update.yaml\nkubectl apply -f mesh/appserver_update.yaml\nkubectl apply -f mesh/yelb_db_update.yaml\nkubectl apply -f mesh/yelb_ui_update.yaml\n\n\n", "num_lines": 72}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nMESH_OWNER=$(aws --profile frontend sts get-caller-identity | jq -r .Account)\n\ncat > /tmp/app-mesh.yml <<-EKS_CONF\n  apiVersion: appmesh.k8s.aws/v1beta2\n  kind: Mesh\n  metadata:\n    name: am-multi-account-mesh\n  spec:\n    meshOwner: \"$MESH_OWNER\"\n    namespaceSelector:\n      matchLabels:\n        mesh: am-multi-account-mesh\nEKS_CONF\n\nkubectl apply -f /tmp/app-mesh.yml\n", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nexport AWS_PAGER=\"\"\n\necho \"Deleting the EKS clusters\"\neksctl delete -p frontend cluster -f /tmp/eks-frontend-configuration.yml\neksctl delete -p backend cluster -f /tmp/eks-backend-configuration.yml\n\necho \"Deleting the App Mesh virtual services\"\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-db\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name redis-server\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-appserver\n\naws --profile frontend appmesh delete-virtual-service \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-service-name yelb-ui\n\necho \"Deleting the App Mesh virtual router\"\naws --profile frontend appmesh delete-route \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-router-name yelb-appserver-virtual-router \\\n    --route-name route-to-yelb-appserver\n\naws --profile frontend appmesh delete-virtual-router \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-router-name yelb-appserver-virtual-router\n\necho \"Deleting the App Mesh virtual nodes\"\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name redis-server_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-db_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-appserver_yelb\n\naws --profile frontend appmesh delete-virtual-node \\\n    --mesh-name am-multi-account-mesh \\\n    --virtual-node-name yelb-ui_yelb\n\necho \"Deleting the App Mesh mesh\"\naws --profile frontend appmesh delete-mesh \\\n    --mesh-name am-multi-account-mesh\n\necho \"Deleting Cloud Map Services\"\nNAMESPACE=$(aws --profile backend servicediscovery list-namespaces | \\\n  jq -r ' .Namespaces[] | select ( .Properties.HttpProperties.HttpName == \"am-multi-account.local\" ) | .Id ');\nSERVICE_ID=$(aws --profile backend servicediscovery list-services --filters Name=\"NAMESPACE_ID\",Values=$NAMESPACE,Condition=\"EQ\" | jq -r ' .Services[] | [ .Id ] | @tsv ' )\naws --profile backend servicediscovery list-instances --service-id $SERVICE_ID | jq -r ' .Instances[] | [ .Id ] | @tsv ' |\\\n  while IFS=$'\\t' read -r instanceId; do \n    aws --profile backend servicediscovery deregister-instance --service-id $SERVICE_ID --instance-id $instanceId\n  done\naws --profile backend servicediscovery list-services \\\n  --filters Name=\"NAMESPACE_ID\",Values=$NAMESPACE,Condition=\"EQ\" | \\\njq -r ' .Services[] | [ .Id ] | @tsv ' | \\\n  while IFS=$'\\t' read -r serviceId; do \n    aws --profile backend servicediscovery delete-service \\\n      --id $serviceId\n  done\n\necho \"Deleting CloudFormation templates\"\naws --profile backend cloudformation delete-stack \\\n  --stack-name am-multi-account-routes\naws --profile backend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-routes\n\naws --profile backend cloudformation delete-stack \\\n  --stack-name am-multi-account-infra\naws --profile backend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-infra\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-shared-mesh\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-shared-mesh\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-routes\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-routes\n\naws --profile frontend cloudformation delete-stack \\\n  --stack-name am-multi-account-infra\naws --profile frontend cloudformation wait stack-delete-complete \\\n  --stack-name am-multi-account-infra\n\necho \"Cleanup finished\"", "num_lines": 100}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Creating a ClusterConfig file for the Frontend cluster...\"\n\nFRONTEND_AWS_REGION=$(aws --profile frontend configure get region);\nFRONTEND_PRIVSUB1_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet1\") | .Value');\nFRONTEND_PRIVSUB2_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet2\") | .Value');\nFRONTEND_PUBSUB1_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet1\") | .Value');\nFRONTEND_PUBSUB2_ID=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet2\") | .Value');\nFRONTEND_PRIVSUB1_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PRIVSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PRIVSUB2_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PRIVSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PUBSUB1_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PUBSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_PUBSUB2_AZ=$(aws --profile frontend ec2 describe-subnets --subnet-ids $FRONTEND_PUBSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nFRONTEND_NODES_IAM_POLICY=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSDPolicy\") | .Value');\n\ncat > /tmp/eks-frontend-configuration.yml <<-EKS_FRONTEND_CONF\n  apiVersion: eksctl.io/v1alpha5\n  kind: ClusterConfig  \n  metadata:\n    name: am-multi-account-1\n    region: $FRONTEND_AWS_REGION\n    version: \"1.22\"\n  vpc:\n    subnets:\n      private:\n        $FRONTEND_PRIVSUB1_AZ: { id: $FRONTEND_PRIVSUB1_ID }\n        $FRONTEND_PRIVSUB2_AZ: { id: $FRONTEND_PRIVSUB2_ID }\n      public:\n        $FRONTEND_PUBSUB1_AZ: { id: $FRONTEND_PUBSUB1_ID }\n        $FRONTEND_PUBSUB2_AZ: { id: $FRONTEND_PUBSUB2_ID }\n  nodeGroups:\n    - name: am-multi-account-1-ng\n      labels: { role: workers }\n      instanceType: t3.large\n      desiredCapacity: 3\n      ssh: \n        allow: false\n      privateNetworking: true\n      iam:\n        attachPolicyARNs: \n          - $FRONTEND_NODES_IAM_POLICY\n          - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n          - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n          - arn:aws:iam::aws:policy/ElasticLoadBalancingFullAccess\n          - arn:aws:iam::aws:policy/AWSAppMeshFullAccess\n        withAddonPolicies:\n          xRay: true\n          cloudWatch: true\n          externalDNS: true\nEKS_FRONTEND_CONF\n\necho \"Creating the Frontend EKS cluster...\"\neksctl create -p frontend cluster -f /tmp/eks-frontend-configuration.yml\n\necho \"Creating a ClusterConfig file for the Backend cluster...\"\n\nBACKEND_AWS_REGION=$(aws --profile backend configure get region);\nBACKEND_PRIVSUB1_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet1\") | .Value');\nBACKEND_PRIVSUB2_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PrivateSubnet2\") | .Value');\nBACKEND_PUBSUB1_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet1\") | .Value');\nBACKEND_PUBSUB2_ID=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:PublicSubnet2\") | .Value');\nBACKEND_PRIVSUB1_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PRIVSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PRIVSUB2_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PRIVSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PUBSUB1_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PUBSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_PUBSUB2_AZ=$(aws --profile backend ec2 describe-subnets --subnet-ids $BACKEND_PUBSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nBACKEND_NODES_IAM_POLICY=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSDPolicy\") | .Value');\nBACKEND_NODES_SECURITY_GROUP=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:NodesSecurityGroup\") | .Value');\n\ncat > /tmp/eks-backend-configuration.yml <<-EKS_BACKEND_CONF\n  apiVersion: eksctl.io/v1alpha5\n  kind: ClusterConfig  \n  metadata:\n    name: am-multi-account-2\n    region: $BACKEND_AWS_REGION\n    version: \"1.22\"\n  vpc:\n    subnets:\n      private:\n        $BACKEND_PRIVSUB1_AZ: { id: $BACKEND_PRIVSUB1_ID }\n        $BACKEND_PRIVSUB2_AZ: { id: $BACKEND_PRIVSUB2_ID }\n      public:\n        $BACKEND_PUBSUB1_AZ: { id: $BACKEND_PUBSUB1_ID }\n        $BACKEND_PUBSUB2_AZ: { id: $BACKEND_PUBSUB2_ID }\n  nodeGroups:\n    - name: am-multi-account-2-ng\n      labels: { role: workers }\n      instanceType: t3.large\n      desiredCapacity: 3\n      ssh: \n        allow: false\n      privateNetworking: true\n      securityGroups:\n        withShared: true\n        withLocal: true\n        attachIDs: ['$BACKEND_NODES_SECURITY_GROUP']\n      iam:\n        attachPolicyARNs: \n          - $BACKEND_NODES_IAM_POLICY\n          - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n          - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n          - arn:aws:iam::aws:policy/ElasticLoadBalancingFullAccess\n          - arn:aws:iam::aws:policy/AWSAppMeshFullAccess\n        withAddonPolicies:\n          xRay: true\n          cloudWatch: true\n          externalDNS: true\nEKS_BACKEND_CONF\n\necho \"Creating the Backend EKS cluster...\"\neksctl create -p backend cluster -f /tmp/eks-backend-configuration.yml", "num_lines": 112}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Creating the Frontend Account VPC...\"\n\naws --profile frontend cloudformation deploy \\\n--template-file infrastructure/infrastructure_frontend.yaml \\\n--parameter-overrides \\\n\"BackendAccountId=$(aws --profile backend sts get-caller-identity | jq -r .Account)\" \\\n--stack-name am-multi-account-infra \\\n--capabilities CAPABILITY_IAM\n\necho \"Creating the Backend Account VPC...\"\n\naws --profile backend cloudformation deploy \\\n--template-file infrastructure/infrastructure_backend.yaml \\\n--parameter-overrides \\\n\"FrontendAccountId=$(aws --profile frontend sts get-caller-identity | jq -r .Account)\" \\\n\"PeerVPCId=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPC\") | .Value')\" \\\n\"PeerRoleArn=$(aws --profile frontend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPCPeerRole\") | .Value')\" \\\n--stack-name am-multi-account-infra \\\n--capabilities CAPABILITY_IAM\n\necho \"Creating the VPC peering routes...\"\n\naws --profile frontend cloudformation deploy \\\n--template-file infrastructure/frontend_vpc_peering_routes.yaml \\\n--parameter-overrides \\\n\"VPCPeeringConnectionId=$(aws --profile backend cloudformation list-exports | jq -r '.Exports[] | select(.Name==\"am-multi-account:VPCPeeringConnectionId\") | .Value')\" \\\n--stack-name am-multi-account-routes \\\n--capabilities CAPABILITY_IAM\n\naws --profile backend cloudformation deploy \\\n--template-file infrastructure/backend_vpc_peering_routes.yaml \\\n--stack-name am-multi-account-routes \\\n--capabilities CAPABILITY_IAM\n\n", "num_lines": 39}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nMESH_OWNER=$(aws --profile frontend sts get-caller-identity | jq -r .Account)\n\ncat > /tmp/app-mesh.yml <<-EKS_CONF\n  apiVersion: appmesh.k8s.aws/v1beta2\n  kind: Mesh\n  metadata:\n    name: am-multi-account-mesh\n  spec:\n    meshOwner: \"$MESH_OWNER\"\n    namespaceSelector:\n      matchLabels:\n        mesh: am-multi-account-mesh\nEKS_CONF\n\nkubectl apply -f /tmp/app-mesh.yml\n", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\necho \"Setting up environment variables...\"\n\nACCOUNT_ID=$(aws sts get-caller-identity --output text --query Account)\n\n\necho \"Deploying CloudFormation template...\"\n\naws cloudformation deploy \\\n--template-file infrastructure/vpc_infrastructure.yaml \\\n--stack-name appmesh-getting-started-eks \\\n--capabilities CAPABILITY_IAM\n\necho \"Getting CloudFormation outputs...\"\n\naws cloudformation describe-stacks \\\n    --stack-name appmesh-getting-started-eks | \\\njq -r '[.Stacks[0].Outputs[] | {key: .OutputKey, value: .OutputValue}] | from_entries' > cfn-output.json ", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Build docker image\nAPPSERVER_ECR_REPO=$(jq < cfn-output.json -r '.AppServerEcrRepo');\ndocker build -t $APPSERVER_ECR_REPO ./yelb-appserver-v2/\n\n# Push image to ECR repo\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nif [[ ${AWS_CLI_VERSION} == 1 ]]\nthen\n  $(aws ecr get-login --no-include-email)\nelse\n  aws ecr get-login-password | docker login --username AWS --password-stdin $APPSERVER_ECR_REPO\nfi\n\n\ndocker push  $APPSERVER_ECR_REPO:latest\n\n# Update the Kubernetes deployment file\nsed -i \"s@<APPSERVER_V2_IMAGE_URI>@$APPSERVER_ECR_REPO@g\" infrastructure/yelb_appserver_v2_deployment.yaml", "num_lines": 21}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install packages\nsudo yum update\nsudo yum install jq moreutils -y\n\n# Upgrade pip\nsudo pip3 install --upgrade pip\necho \"export PATH=~/.local/bin:$PATH\" >> ~/.bash_profile\nsource ~/.bash_profile\n\n# Install awscli\npip3 install awscli --upgrade --user\nsource ~/.bash_profile\n\n# Install eksctl\ncurl --silent --location \"https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz\" | tar xz -C /tmp\nsudo mv /tmp/eksctl /usr/local/bin\n\n# Install kubectl\ncurl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl\nchmod +x ./kubectl\nsudo mv ./kubectl /usr/local/bin/kubectl\n\n# Create folder for YAML Files\nmkdir /tmp/eks-scripts\n\n# Install Helm\ncurl -fsSL -o get_helm.sh https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3\nchmod 700 get_helm.sh\n./get_helm.sh\n", "num_lines": 32}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Deleting the App Mesh virtual services\"\nkubectl delete virtualservice redis-server -n yelb\nkubectl delete virtualservice yelb-db -n yelb\nkubectl delete virtualservice yelb-ui -n yelb\nkubectl delete virtualservice yelb-appserver -n yelb\n\necho \"Deleting the App Mesh virtual router\"\nkubectl delete virtualrouter yelb-appserver -n yelb\n\necho \"Deleting the App Mesh virtual nodes\"\nkubectl delete virtualnode redis-server -n yelb\nkubectl delete virtualnode yelb-appserver -n yelb\nkubectl delete virtualnode yelb-appserver-v2 -n yelb\nkubectl delete virtualnode yelb-db -n yelb\nkubectl delete virtualnode yelb-ui -n yelb\n\necho \"Deleting the App Mesh mesh\"\nkubectl delete mesh yelb\n\necho \"Deleting the Yelb deployment\"\nkubectl delete -f infrastructure/yelb_initial_deployment.yaml\n\necho \"Deleting EKS cluster\"\neksctl delete cluster -f /tmp/eks-configuration.yml\n\necho \"Cleaning up ECR repository\"\nAPPSERVER_ECR_REPO=$(jq < cfn-output.json -r '.AppServerEcrRepo' | cut -d '/' -f 2 );\naws ecr list-images \\\n  --repository-name $APPSERVER_ECR_REPO | \\\njq -r ' .imageIds[] | [ .imageDigest ] | @tsv ' | \\\n  while IFS=$'\\t' read -r imageDigest; do \n    aws ecr batch-delete-image \\\n      --repository-name $APPSERVER_ECR_REPO \\\n      --image-ids imageDigest=$imageDigest\n  done\n\necho \"Deleting the baseline CloudFormation template\"\nSTACK_NAME=$(jq < cfn-output.json -r '.StackName');\naws cloudformation delete-stack \\\n  --stack-name $STACK_NAME\naws cloudformation wait stack-delete-complete \\\n  --stack-name $STACK_NAME\n\necho \"Cleanup finished\"", "num_lines": 46}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Create a ClusterConfig file\nAWS_REGION=$(jq < cfn-output.json -r '.StackRegion');\nPRIVSUB1_ID=$(jq < cfn-output.json -r '.PrivateSubnet1');\nPRIVSUB2_ID=$(jq < cfn-output.json -r '.PrivateSubnet2');\nPUBSUB1_ID=$(jq < cfn-output.json -r '.PublicSubnet1');\nPUBSUB2_ID=$(jq < cfn-output.json -r '.PublicSubnet2');\nPRIVSUB1_AZ=$(aws ec2 describe-subnets --subnet-ids $PRIVSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nPRIVSUB2_AZ=$(aws ec2 describe-subnets --subnet-ids $PRIVSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nPUBSUB1_AZ=$(aws ec2 describe-subnets --subnet-ids $PUBSUB1_ID | jq -r .Subnets[].AvailabilityZone);\nPUBSUB2_AZ=$(aws ec2 describe-subnets --subnet-ids $PUBSUB2_ID | jq -r .Subnets[].AvailabilityZone);\nNODES_IAM_POLICY=$(jq < cfn-output.json -r '.NodesSDPolicy');\n\ncat > /tmp/eks-configuration.yml <<-EKS_CONF\n  apiVersion: eksctl.io/v1alpha5\n  kind: ClusterConfig  \n  metadata:\n    name: appmesh-getting-started-eks\n    region: $AWS_REGION\n  vpc:\n    subnets:\n      private:\n        $PRIVSUB1_AZ: { id: $PRIVSUB1_ID }\n        $PRIVSUB2_AZ: { id: $PRIVSUB2_ID }\n      public:\n        $PUBSUB1_AZ: { id: $PUBSUB1_ID }\n        $PUBSUB2_AZ: { id: $PUBSUB2_ID }\n  nodeGroups:\n    - name: appmesh-cloudmap-ng\n      labels: { role: workers }\n      instanceType: t3.large\n      desiredCapacity: 3\n      ssh: \n        allow: false\n      privateNetworking: true\n      iam:\n        attachPolicyARNs: \n          - $NODES_IAM_POLICY\n          - arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n          - arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n          - arn:aws:iam::aws:policy/ElasticLoadBalancingFullAccess\n        withAddonPolicies:\n          appMesh: true\n          xRay: true\n          cloudWatch: true\n          externalDNS: true\nEKS_CONF\n\n# Create the EKS cluster\neksctl create cluster -f /tmp/eks-configuration.yml", "num_lines": 51}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# when the variable is populated a search domain entry is added to resolv.conf at startup\n# this is needed for the ECS service discovery given the app works by calling host names and not FQDNs\n# a search domain can't be added to the container when using the awsvpc mode \n# and the awsvpc mode is needed for A records (bridge only supports SRV records)\nif [ $SEARCH_DOMAIN ]; then echo \"search ${SEARCH_DOMAIN}\" >> /etc/resolv.conf; fi \n\nruby /app/yelb-appserver.rb -o 0.0.0.0", "num_lines": 9}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-appmesh-colorapp\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/appmesh-colorapp.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\nstack_output=$(aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation describe-stacks --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    | jq '.Stacks[].Outputs[]')\n\ntask_role_arn=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"TaskIamRoleArn\") | .OutputValue'))\n\nexecution_role_arn=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"TaskExecutionIamRoleArn\") | .OutputValue'))\n\necs_service_log_group=($(echo $stack_output \\\n    | jq -r 'select(.OutputKey == \"ECSServiceLogGroup\") | .OutputValue'))\n\nenvoy_log_level=\"debug\"\n\n# Color Teller Green Task Definition\nCOLOR=green\nenvoy_container_json=$(jq -n \\\n    --arg ENVOY_IMAGE $ENVOY_IMAGE \\\n    --arg VIRTUAL_NODE \"mesh/$MESH_NAME/virtualNode/colorteller-$COLOR-vn\" \\\n    --arg APPMESH_XDS_ENDPOINT \"${APPMESH_XDS_ENDPOINT}\" \\\n    --arg ENVOY_LOG_LEVEL $envoy_log_level \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg AWS_LOG_STREAM_PREFIX \"colorteller-$COLOR-envoy\" \\\n    -f \"${DIR}/envoy-container.json\")\nxray_container_json=$(jq -n \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg AWS_LOG_STREAM_PREFIX_ENVOY \"colorteller-$COLOR-xray\" \\\n    -f \"${DIR}/xray-container.json\")\ntask_def_json=$(jq -n \\\n    --arg NAME \"$ENVIRONMENT_NAME-colorteller-$COLOR\" \\\n    --arg STAGE \"$APPMESH_STAGE\" \\\n    --arg COLOR \"$COLOR\" \\\n    --arg APP_IMAGE $COLOR_TELLER_IMAGE \\\n    --arg AWS_REGION $AWS_DEFAULT_REGION \\\n    --arg ECS_SERVICE_LOG_GROUP $ecs_service_log_group \\\n    --arg AWS_LOG_STREAM_PREFIX_APP \"colorteller-$COLOR-app\" \\\n    --arg TASK_ROLE_ARN $task_role_arn \\\n    --arg EXECUTION_ROLE_ARN $execution_role_arn \\\n    --argjson ENVOY_CONTAINER_JSON \"${envoy_container_json}\" \\\n    --argjson XRAY_CONTAINER_JSON \"${xray_container_json}\" \\\n    -f \"${DIR}/fargate-colorteller-task-def.json\")\ntask_def=$(aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    ecs register-task-definition \\\n    --cli-input-json \"$task_def_json\")\ncolorteller_green_task_def_arn=($(echo $task_def \\\n    | jq -r '.taskDefinition | .taskDefinitionArn'))\n", "num_lines": 56}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# Create colorteller task definition\nsource ${DIR}/fargate-colorteller-task-def.sh\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-fargate-colorteller\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/fargate-colorteller.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    ColorTellerGreenTaskDefinition=\"${colorteller_green_task_def_arn}\"\n", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-alb\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    stack_name=\"${PROJECT_NAME}-infra\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name $stack_name\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\ndeploy_app() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorAppImage=${ECR_IMAGE_PREFIX}/colorapp\" \"FrontAppImage=${ECR_IMAGE_PREFIX}/feapp\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] ||\n        (echo \"Error: no service linked role for App Mesh\" && exit 1)\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='FrontEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}/color\"\n}\n\ndeploy_resources() {\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    echo \"deploy infra...\"\n    deploy_infra\n\n    echo \"deploy app...\"\n    deploy_app\n\n    confirm_service_linked_role\n    print_endpoint\n}\n\ndelete_images() {\n    for app in colorapp feapp; do\n        echo \"deleting repository...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\ndelete_resources() {\n    echo \"delete app...\"\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    echo \"delete infra...\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    echo \"delete images...\"\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_resources\n    exit 0\nfi\n\ndeploy_resources\n", "num_lines": 132}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    WrkToolImageName=\"${WRK_TOOL_IMAGE_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    WrkToolImageName=\"${WRK_TOOL_IMAGE_NAME}\"\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIP'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"ColorApp Endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-service\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='ColorAppEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\nprint_bastion\nprint_endpoint\n", "num_lines": 40}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    vgateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gateway_route() {\n    vgateway_name=$1\n    gatewayroute_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service  \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vrouter() {\n    spec_file=$1\n    vrouter_name=$2\n    cmd=( $appmesh_cmd create-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vrouter() {\n    vrouter_name=$1\n    cmd=( $appmesh_cmd delete-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd create-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_route() {\n    vrouter_name=$1\n    route_name=$2\n    cmd=( $appmesh_cmd delete-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    update_resource=\"$2\"\n    resource_name=\"$3\"\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-white-vn.json\" \"colorteller-white-vn\" \"colorteller-white\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-1.json\" \"colorteller-vr-1\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route-1.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-1.json\" \"colorteller-1.${SERVICES_DOMAIN}\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-black-vn.json\" \"colorteller-black-vn\" \"colorteller-black\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-2.json\" \"colorteller-vr-2\"        \n        create_route \"${TEST_MESH_DIR}/colorteller-route-2.json\" \"colorteller-vr-2\" \"colorteller-route-2\" \n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-2.json\" \"colorteller-2.${SERVICES_DOMAIN}\"\n\n        create_vgateway \"${TEST_MESH_DIR}/colorgateway-vg.json\" \"colorgateway-vg\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-1.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-2.json\" \"colorgateway-vg\" \"colorgateway-route-2\" \"colorteller-2.${SERVICES_DOMAIN}\"\n        ;;\n\n    update)\n        case \"$update_resource\" in\n        vnode)\n            update_vnode \"${TEST_MESH_DIR}/${resource_name}-vn-update.json\" \"${resource_name}-vn\" \"${resource_name}\"\n            ;;\n            \n        vgateway)\n            update_vgateway \"${TEST_MESH_DIR}/${resource_name}-vg-update.json\" \"${resource_name}-vg\"\n            ;;\n\n        *)\n            err \"Invalid resource provided for update: $update_resource\"\n            ;;\n        esac\n        ;;\n\n    down)\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-1\"\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-2\"\n        delete_vgateway \"colorgateway-vg\"\n\n        delete_vservice \"colorteller-1.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr-1\" \"colorteller-route-1\"\n        delete_vrouter \"colorteller-vr-1\"\n        delete_vnode \"colorteller-white-vn\"\n\n        delete_vservice \"colorteller-2.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr-2\" \"colorteller-route-2\"\n        delete_vrouter \"colorteller-vr-2\"\n        delete_vnode \"colorteller-black-vn\"\n\n        delete_mesh\n        ;;\n\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 310}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n# login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n         docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $WRK_TOOL_IMAGE_NAME ]; then\n    echo \" WRK_TOOL_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${WRK_TOOL_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR\n\n# login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n         docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $PROJECT_NAME ]; then\n    echo \"PROJECT_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_PRIMARY_ACCOUNT_ID ]; then\n    echo \"AWS_PRIMARY_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_SECONDARY_ACCOUNT_ID ]; then\n    echo \"AWS_SECONDARY_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_PRIMARY_PROFILE ]; then\n    echo \"AWS_PRIMARY_PROFILE environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_SECONDARY_PROFILE ]; then\n    echo \"AWS_SECONDARY_PROFILE environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $BACKEND_1_IMAGE ]; then\n    echo \"BACKEND_1_IMAGE environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $BACKEND_2_IMAGE ]; then\n    echo \"BACKEND_2_IMAGE environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $KEY_PAIR ]; then\n    echo \"KEY_PAIR environment variable is not set. This must be the name of an SSH key pair, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPRIMARY_ACCOUNT_DIR=\"${DIR}/primary-account\"\nSECONDARY_ACCOUNT_DIR=\"${DIR}/secondary-account\"\n\nprint_endpoint() {\n    echo \"Setting AWS_PROFILE=${AWS_PRIMARY_PROFILE} to get public endpoint\"\n    export AWS_PROFILE=${AWS_PRIMARY_PROFILE}\n    echo \"Public endpoint:\"\n    endpoint=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PublicEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"Application is available at ${endpoint}\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    ${SECONDARY_ACCOUNT_DIR}/deploy.sh delete\n    ${PRIMARY_ACCOUNT_DIR}/deploy.sh delete\n    exit 0\nfi\n\nif [ \"$action\" == \"deploy\" ]; then\n    ${PRIMARY_ACCOUNT_DIR}/deploy.sh deploy\n    ${SECONDARY_ACCOUNT_DIR}/deploy.sh deploy\n    print_endpoint\nfi\n", "num_lines": 82}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\necho \"Setting AWS_PROFILE=${AWS_PRIMARY_PROFILE}\"\nexport AWS_PROFILE=${AWS_PRIMARY_PROFILE}\n\nif [ -z $AWS_PROFILE ]; then\n    echo \"AWS_PROFILE environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\ndeploy_infra() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-infra\\\" containing VPC and Cloud Map namespace...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-infra\"\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"KeyPair=${KEY_PAIR}\"\n}\n\ndeploy_app() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-app\\\" containing ALB, ECS Tasks, and Services...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"BackendImage=${BACKEND_1_IMAGE}\"\n}\n\ndeploy_mesh() {\n    echo \"Creating Mesh: \\\"${PROJECT_NAME}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-mesh\"\\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\nenable_org_share() {\n    echo \"Enabling sharing with aws organization: \"\n    echo \"If this is not a primary account, comment the below command and rerun the script.\"\n    aws ram enable-sharing-with-aws-organization\n}\n\nshare_resources() {\n    echo \"Sharing the Private Subnets and Mesh with ${AWS_SECONDARY_ACCOUNT_ID}\"\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-share-subnets\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-share-resources\" \\\n        --template-file \"${DIR}/share-resources.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"ConsumerAccountId=${AWS_SECONDARY_ACCOUNT_ID}\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndeploy_stacks() {\n    deploy_infra\n    deploy_mesh\n    deploy_app\n    enable_org_share\n    share_resources\n}\n\ndelete_stacks() {\n    delete_cfn_stack \"${PROJECT_NAME}-mesh\"\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n    delete_cfn_stack \"${PROJECT_NAME}-share-resources\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    echo \"all resources for primary account have been deleted\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\nif [ \"$action\" == \"deploy\" ]; then\n    deploy_stacks\n    exit 0\nfi\n", "num_lines": 98}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\necho \"Setting AWS_PROFILE=${AWS_SECONDARY_PROFILE}\"\nexport AWS_PROFILE=${AWS_SECONDARY_PROFILE}\n\nif [ -z $AWS_PROFILE ]; then\n    echo \"AWS_PROFILE environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\ndeploy_infra() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-infra\\\" containing VPC and Cloud Map namespace...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-infra\"\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"VPC=${SHARED_VPC}\"\n}\n\ndeploy_app() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-app\\\" containing ECS Tasks, Services...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"MeshOwner=${AWS_PRIMARY_ACCOUNT_ID}\" \"VPC=${SHARED_VPC}\" \"PrivateSubnet1=${SHARED_PRIVATE_SUBNET_1}\" \"PrivateSubnet2=${SHARED_PRIVATE_SUBNET_2}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"BackendImage=${BACKEND_2_IMAGE}\"\n}\n\ndeploy_mesh() {\n    echo \"Creating reources in shared Mesh: \\\"${PROJECT_NAME}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-mesh\"\\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"MeshName=${PROJECT_NAME}-mesh\" \"MeshOwner=${AWS_PRIMARY_ACCOUNT_ID}\"\n}\n\nload_primary_vpc() {\n    echo \"Discovering primary VPC...\"\n    vpc=$(aws cloudformation describe-stacks \\\n        --profile ${AWS_PRIMARY_PROFILE} \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='VPC'].OutputValue\" \\\n        --output=text)\n    private_subnet_1=$(aws cloudformation describe-stacks \\\n        --profile ${AWS_PRIMARY_PROFILE} \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PrivateSubnet1'].OutputValue\" \\\n        --output=text)\n    private_subnet_2=$(aws cloudformation describe-stacks \\\n        --profile ${AWS_PRIMARY_PROFILE} \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PrivateSubnet2'].OutputValue\" \\\n        --output=text)\n\n    echo \"SHARED_VPC=${vpc}\"\n    echo \"SHARED_PRIVATE_SUBNET_1=${private_subnet_1}\"\n    echo \"SHARED_PRIVATE_SUBNET_2=${private_subnet_2}\"\n    export SHARED_VPC=${vpc}\n    export SHARED_PRIVATE_SUBNET_1=${private_subnet_1}\n    export SHARED_PRIVATE_SUBNET_2=${private_subnet_2}\n}\n\ndeploy_stacks() {\n    load_primary_vpc\n\n    deploy_infra\n    deploy_mesh\n    deploy_app\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_stacks() {\n    echo \"Deleting route to cleanly delete ${PROJECT_NAME}-mesh\"\n    aws --profile ${AWS_PRIMARY_PROFILE} appmesh delete-route --mesh-name ${PROJECT_NAME}-mesh --virtual-router-name backend-vr --route-name backend-route\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n    delete_cfn_stack \"${PROJECT_NAME}-mesh\"\n\n    echo \"all resources for secondary account have been deleted\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 105}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"$(basename ${DIR})\"\nSTACK_NAME=\"appmesh-${PROJECT_NAME}\"\n\ndeploy_cw_dashboards() {\n    mkdir -p $DIR/_output\n    MESH_NAME=${PROJECT_NAME}\n    CLOUDWATCH_NAMESPACE=${CLOUDWATCH_NAMESPACE:-${PROJECT_NAME}}\n    virtual_nodes=($(aws cloudformation describe-stack-resources --stack-name ${STACK_NAME} |\n        jq -r '.StackResources[] | select(.ResourceType == \"AWS::AppMesh::VirtualNode\") | .PhysicalResourceId'))\n    for vn in ${virtual_nodes[@]}; do\n        VIRTUAL_NODE_NAME=$(echo $vn | sed \"s#.*\\/##g\")\n        eval \"cat <<EOF\n$(<${DIR}/deploy/cw-dashboard.yaml.template)\nEOF\n\" >$DIR/_output/$VIRTUAL_NODE_NAME-cw-dashboard.yaml\n\n        echo \"Deploying stack ${VIRTUAL_NODE_NAME}-cw-dashboard, this may take a few minutes...\"\n        aws cloudformation deploy \\\n            --no-fail-on-empty-changeset \\\n            --stack-name ${PROJECT_NAME}-${VIRTUAL_NODE_NAME} \\\n            --template-file \"$DIR/_output/$VIRTUAL_NODE_NAME-cw-dashboard.yaml\" \\\n            --capabilities CAPABILITY_IAM \\\n            --parameter-overrides \\\n            \"DashboardName=${PROJECT_NAME}-${VIRTUAL_NODE_NAME}\"\n    done\n}\n\ndeploy_stacks() {\n    deploy_cw_dashboards\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo \"Waiting for the stack $stack_name to be deleted, this may take a few minutes...\"\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_stacks() {\n    virtual_nodes=($(aws cloudformation describe-stack-resources --stack-name ${STACK_NAME} |\n        jq -r '.StackResources[] | select(.ResourceType == \"AWS::AppMesh::VirtualNode\") | .PhysicalResourceId'))\n    for vn in ${virtual_nodes[@]}; do\n        VIRTUAL_NODE_NAME=$(echo $vn | sed \"s#.*\\/##g\")\n        delete_cfn_stack ${PROJECT_NAME}-${VIRTUAL_NODE_NAME}\n    done\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 71}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nPROJECT_NAME=\"$(basename ${DIR})\"\nSTACK_NAME=\"appmesh-${PROJECT_NAME}\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\nCW_AGENT_IMAGE=\"${ECR_IMAGE_PREFIX}/cwagent:$(git log -1 --format=%h src/cwagent)\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp:$(git log -1 --format=%h src/colorapp)\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp:$(git log -1 --format=%h src/feapp)\"\nGO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# deploy_images builds and pushes docker images for colorapp and feapp to ECR\ndeploy_images() {\n    for f in cwagent colorapp feapp; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${f} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${f} >/dev/null\n    done\n\n    ecr_login\n    docker build -t ${CW_AGENT_IMAGE} ${DIR}/src/cwagent && docker push ${CW_AGENT_IMAGE}\n    docker build -t ${COLOR_APP_IMAGE} --build-arg GO_PROXY=${GO_PROXY} ${DIR}/src/colorapp && docker push ${COLOR_APP_IMAGE}\n    docker build -t ${FRONT_APP_IMAGE} --build-arg GO_PROXY=${GO_PROXY} ${DIR}/src/feapp && docker push ${FRONT_APP_IMAGE}\n}\n\n# deploy deploys infra, colorapp and feapp.\ndeploy() {\n    stage=$1\n\n    echo \"Deploying stack ${STACK_NAME}, this may take a few minutes...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name ${STACK_NAME} \\\n        --template-file \"$DIR/deploy/$stage.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        \"ProjectName=${PROJECT_NAME}\" \\\n        \"EnvoyImage=${ENVOY_IMAGE}\" \\\n        \"CloudWatchAgentImage=${CW_AGENT_IMAGE}\" \\\n        \"ColorAppImage=${COLOR_APP_IMAGE}\" \\\n        \"FrontAppImage=${FRONT_APP_IMAGE}\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo \"Waiting for the stack $stack_name to be deleted, this may take a few minutes...\"\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] ||\n        (echo \"Error: no service linked role for App Mesh\" && exit 1)\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${STACK_NAME}\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='FrontEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}/color\"\n}\n\ndeploy_stacks() {\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    echo \"deploy app using stage ${stage}\"\n    deploy \"${stage}\"\n\n    if [ \"${stage}\" == \"2-meshify\" ]; then\n      confirm_service_linked_role\n    fi\n    print_endpoint\n}\n\ndelete_stacks() {\n    echo \"delete stack ${STACK_NAME}...\"\n    delete_cfn_stack ${STACK_NAME}\n}\n\naction=${1:-\"deploy\"}\nstage=${2:-\"0-prelude\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 122}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-mesh\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/mesh.yaml\" \\\n    --parameter-overrides \\\n    MeshName=\"${MESH_NAME}\" \\\n    ServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    CertificateAuthorityArn=\"${ROOT_CA_ARN}\" \\\n    CertificateArn=\"${CERTIFICATE_ARN}\"\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# build and push\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\necr_login\ndocker push $IMAGE\n", "num_lines": 41}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $PROJECT_NAME ]; then\n    echo \"PROJECT_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $KEY_PAIR ]; then\n    echo \"KEY_PAIR environment variable is not set. This must be the name of an SSH key pair, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    echo \"Deploying Color Client and Color Server images to ECR...\"\n    ecr_login\n    for app in color_client color_server; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${app} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${app} >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-infra\\\" containing VPC and Cloud Map namespace...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-infra\"\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"KeyPair=${KEY_PAIR}\"\n}\n\ndeploy_app() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-app\\\" containing ALB, ECS Tasks, and Cloud Map Services...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorClientImage=${ECR_IMAGE_PREFIX}/color_client\" \"ColorServerImage=${ECR_IMAGE_PREFIX}/color_server\"\n}\n\ndeploy_mesh() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-mesh\" \\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIp'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PublicEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_stacks() {\n    deploy_images\n    deploy_infra\n    deploy_mesh\n    deploy_app\n\n    print_bastion\n    print_endpoint\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in color_client color_server; do\n        echo \"deleting repository \\\"${app}\\\"...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\ndelete_stacks() {\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-mesh\"\n\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 149}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nprotoc ./color.proto --go_out=plugins=grpc:./color_client/color\nprotoc ./color.proto --go_out=plugins=grpc:./color_server/color\n", "num_lines": 7}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $PROJECT_NAME ]; then\n    echo \"PROJECT_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $KEY_PAIR ]; then\n    echo \"KEY_PAIR environment variable is not set. This must be the name of an SSH key pair, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    echo \"Deploying Color Client and Color Server images to ECR...\"\n    ecr_login\n    for app in color_server; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${app} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${app} >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-infra\\\" containing VPC and Cloud Map namespace...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-infra\"\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"KeyPair=${KEY_PAIR}\"\n}\n\ndeploy_app() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-app\\\" containing ALB, ECS Tasks, and Cloud Map Services...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorServerImage=${ECR_IMAGE_PREFIX}/color_server\"\n}\n\ndeploy_mesh() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-mesh\" \\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIp'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    endpoint=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PublicEndpoint'].OutputValue\" \\\n        --output=text)\n    prefix='http://'\n    suffix=':80'\n    echo \"${endpoint#$prefix}$suffix\"\n}\n\ndeploy_stacks() {\n    deploy_images\n    deploy_infra\n    deploy_mesh\n    deploy_app\n\n    print_bastion\n    print_endpoint\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in color_server; do\n        echo \"deleting repository \\\"${app}\\\"...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\ndelete_stacks() {\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-mesh\"\n\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 151}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nprotoc ./color.proto --go_out=plugins=grpc:./color_server/color\n", "num_lines": 6}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-http-headers\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    stack_name=\"${PROJECT_NAME}-infra\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name $stack_name\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\ndeploy_app() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorAppImage=${ECR_IMAGE_PREFIX}/colorapp\" \"FrontAppImage=${ECR_IMAGE_PREFIX}/feapp\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in colorapp feapp; do\n        image_digest=$(aws ecr describe-images \\\n            --repository-name=\"$PROJECT_NAME/$app\" \\\n            --query=\"imageDetails[0].imageDigest\" \\\n            --output=text)\n\n        aws ecr batch-delete-image \\\n           --repository-name $PROJECT_NAME/$app \\\n           --image-ids imageDigest=$image_digest >/dev/null\n\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app >/dev/null\n    done\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] ||\n        (echo \"Error: no service linked role for App Mesh\" && exit 1)\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[0].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_resources() {\n\n    echo \"deploy images...\"\n    deploy_images\n\n    echo \"deploy infra...\"\n    deploy_infra\n\n    echo \"deploy app...\"\n    deploy_app\n\n    confirm_service_linked_role\n    print_endpoint\n}\n\ndelete_resources() {\n    echo \"delete app...\"\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    echo \"delete infra...\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    echo \"delete images...\"\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_resources\n    exit 0\nfi\n\ndeploy_resources\n", "num_lines": 138}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-http-retries\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    stack_name=\"${PROJECT_NAME}-infra\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name $stack_name\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\ndeploy_app() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorAppImage=${ECR_IMAGE_PREFIX}/colorapp\" \"FrontAppImage=${ECR_IMAGE_PREFIX}/feapp\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in colorapp feapp; do\n        echo \"deleting repository...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] ||\n        (echo \"Error: no service linked role for App Mesh\" && exit 1)\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[0].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_stacks() {\n\n    echo \"deploy images...\"\n    deploy_images\n\n    echo \"deploy infra...\"\n    deploy_infra\n\n    echo \"deploy app...\"\n    deploy_app\n\n    confirm_service_linked_role\n    print_endpoint\n}\n\ndelete_stacks() {\n    echo \"delete app...\"\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    echo \"delete infra...\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    echo \"delete images...\"\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\nif [ \"$action\" == \"update-blue-service\" ]; then\n    echo \"updating app image...\"\n    deploy_images\n    echo \"updating blue service...\"\n    aws ecs update-service --force-new-deployment --cluster ${PROJECT_NAME} --service BlueService\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 139}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $PROJECT_NAME ]; then\n    echo \"PROJECT_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $KEY_PAIR ]; then\n    echo \"KEY_PAIR environment variable is not set. This must be the name of an SSH key pair, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    echo \"Deploying Color Client and Color Server images to ECR...\"\n    ecr_login\n    for app in color_client color_server; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${app} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${app} >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-infra\\\" containing VPC and Cloud Map namespace...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-infra\"\\\n        --template-file \"${DIR}/infra.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"KeyPair=${KEY_PAIR}\"\n}\n\ndeploy_app() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-app\\\" containing ALB, ECS Tasks, and Cloud Map Services...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorClientImage=${ECR_IMAGE_PREFIX}/color_client\" \"ColorServerImage=${ECR_IMAGE_PREFIX}/color_server\"\n}\n\ndeploy_mesh() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-mesh\" \\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-infra\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIp'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PublicEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_stacks() {\n    deploy_images\n    deploy_infra\n    deploy_mesh\n    deploy_app\n\n    print_bastion\n    print_endpoint\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in color_client color_server; do\n        echo \"deleting repository \\\"${app}\\\"...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\ndelete_stacks() {\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-mesh\"\n\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 149}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    LoadBalancerCertificateArn=\"${CERTIFICATE_ARN}\"\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIP'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"ColorApp Endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-service\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='ColorAppEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\nprint_bastion\nprint_endpoint\n", "num_lines": 40}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n    --arg ROOT_CA_ARN \"${ROOT_CA_ARN}\" \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    vgateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gateway_route() {\n    vgateway_name=$1\n    gatewayroute_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service  \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vrouter() {\n    spec_file=$1\n    vrouter_name=$2\n    cmd=( $appmesh_cmd create-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vrouter() {\n    vrouter_name=$1\n    cmd=( $appmesh_cmd delete-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd create-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_route() {\n    vrouter_name=$1\n    route_name=$2\n    cmd=( $appmesh_cmd delete-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-white-vn.json\" \"colorteller-white-vn\" \"colorteller-white\"\n        create_vnode \"${TEST_MESH_DIR}/colorteller-blue-vn.json\" \"colorteller-blue-vn\" \"colorteller-blue\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-1.json\" \"colorteller-vr-1\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route-1.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-1.json\" \"colorteller-1.${SERVICES_DOMAIN}\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-black-vn.json\" \"colorteller-black-vn\" \"colorteller-black\"\n        create_vnode \"${TEST_MESH_DIR}/colorteller-red-vn.json\" \"colorteller-red-vn\" \"colorteller-red\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-2.json\" \"colorteller-vr-2\"        \n        create_route \"${TEST_MESH_DIR}/colorteller-route-2.json\" \"colorteller-vr-2\" \"colorteller-route-2\" \n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-2.json\" \"colorteller-2.${SERVICES_DOMAIN}\"\n\n        create_vgateway \"${TEST_MESH_DIR}/colorgateway-vg.json\" \"colorgateway-vg\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-1.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-2.json\" \"colorgateway-vg\" \"colorgateway-route-2\" \"colorteller-2.${SERVICES_DOMAIN}\"\n        ;;\n    partial_tls_up)\n        update_vnode \"${TEST_MESH_DIR}/colorteller-white-vn-tls.json\" \"colorteller-white-vn\" \"colorteller-white\"\n        update_vgateway \"${TEST_MESH_DIR}/colorgateway-vg-backendDefaults.json\" \"colorgateway-vg\"\n        ;;\n    full_tls_up)\n        update_vnode \"${TEST_MESH_DIR}/colorteller-blue-vn-tls.json\" \"colorteller-blue-vn\" \"colorteller-blue\"\n        update_vnode \"${TEST_MESH_DIR}/colorteller-black-vn-tls.json\" \"colorteller-black-vn\" \"colorteller-black\"\n        update_vnode \"${TEST_MESH_DIR}/colorteller-red-vn-tls.json\" \"colorteller-red-vn\" \"colorteller-red\"\n        ;;\n    down)\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-1\"\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-2\"\n        delete_vgateway \"colorgateway-vg\"\n\n        delete_vservice \"colorteller-1.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr-1\" \"colorteller-route-1\"\n        delete_vrouter \"colorteller-vr-1\"\n        delete_vnode \"colorteller-white-vn\"\n        delete_vnode \"colorteller-blue-vn\"\n\n        delete_vservice \"colorteller-2.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr-2\" \"colorteller-route-2\"\n        delete_vrouter \"colorteller-vr-2\"\n        delete_vnode \"colorteller-black-vn\"\n        delete_vnode \"colorteller-red-vn\"\n\n        delete_mesh\n        ;;\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 306}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n# login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n         docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $PROJECT_NAME ]; then\n    echo \"PROJECT_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nif [ -z $KEY_PAIR_NAME ]; then\n    echo \"KEY_PAIR_NAME environment variable is not set. This must be the name of an SSH key pair, see https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    echo \"Deploying Color Client and Color Server images to ECR...\"\n    ecr_login\n    for app in color_client color_server_v4 color_server_dual color_server_v6; do\n        aws ecr describe-repositories --region ${AWS_DEFAULT_REGION} --repository-name ${PROJECT_NAME}/${app} >/dev/null 2>&1 || aws ecr create-repository --region ${AWS_DEFAULT_REGION} --repository-name ${PROJECT_NAME}/${app} >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cluster() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-ecs-cluster\\\" containing ECS cluster, Cloud Map namespace and bastion host...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --region \"${AWS_DEFAULT_REGION}\" \\\n        --stack-name \"${PROJECT_NAME}-ecs-cluster\" \\\n        --template-file \"${DIR}/infra/ecs-cluster.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        ProjectName=\"${PROJECT_NAME}\" \\\n        KeyName=\"${KEY_PAIR_NAME}\" \\\n        ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n}\n\ndeploy_vpc() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-vpc\\\" containing VPC and subnets...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --region \"${AWS_DEFAULT_REGION}\" \\\n        --stack-name \"${PROJECT_NAME}-vpc\" \\\n        --template-file \"${DIR}/infra/vpc.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        ProjectName=\"${PROJECT_NAME}\" \n}\n\ndeploy_cloud_service() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-cloud-ecs-service\\\" containing ECS service, task definitions, and tasks...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --region \"${AWS_DEFAULT_REGION}\" \\\n        --stack-name \"${PROJECT_NAME}-cloud-ecs-service\" \\\n        --template-file \"${DIR}/cloud/ecs-service.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        ProjectName=\"${PROJECT_NAME}\" \\\n        ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n        AppMeshMeshName=\"${MESH_NAME}-cloud-mesh\" \\\n        EnvoyImage=\"${ENVOY_IMAGE}\"\n}\n\ndeploy_dns_service() {\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-dns-ecs-service\\\" containing ECS service, task definitions, and tasks...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --region \"${AWS_DEFAULT_REGION}\" \\\n        --stack-name \"${PROJECT_NAME}-dns-ecs-service\"\\\n        --template-file \"${DIR}/dns/ecs-service.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        ProjectName=\"${PROJECT_NAME}\" \\\n        ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n        AppMeshMeshName=\"${MESH_NAME}-dns-mesh\" \\\n        EnvoyImage=\"${ENVOY_IMAGE}\"\n}\n\ndeploy_mesh() {\n    deployment_type=$1\n    template=$2\n    echo \"Deploying Cloud Formation stack: \\\"${PROJECT_NAME}-${deployment_type}-mesh\\\"...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --region \"${AWS_DEFAULT_REGION}\" \\\n        --stack-name \"${PROJECT_NAME}-${deployment_type}-mesh\" \\\n        --template-file \"${DIR}/${deployment_type}/mesh/${template}.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        AppMeshMeshName=\"${MESH_NAME}-${deployment_type}-mesh\" \\\n        ProjectName=\"${PROJECT_NAME}\"    \n}\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-ecs-cluster\" \\\n        --region ${AWS_DEFAULT_REGION} \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIP'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-$1-ecs-service\" \\\n        --region ${AWS_DEFAULT_REGION} \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='ColorAppEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_infra() {\n    deploy_images\n    deploy_vpc\n    deploy_cluster\n\n    print_bastion\n}\n\ndeploy_cloud() {\n    deploy_mesh \"cloud\" \"mesh-v4-only\"\n    deploy_cloud_service\n\n    print_endpoint \"cloud\"\n}\n\ndeploy_dns() {\n    deploy_mesh \"dns\" \"mesh-v4-only\"\n    deploy_dns_service\n\n    print_endpoint \"dns\"\n}\n\nupdate_mesh() {\n    deployment_type=$1\n    case $2 in\n        v6_preferred)\n            template=\"mesh-v6-preferred\"\n            ;;\n        v4_preferred)\n            template=\"mesh-v4-preferred\"\n            ;;\n        v6_only)\n            template=\"mesh-v6-only\"\n            ;;\n        override)\n            template=\"override-mesh-preference\"\n            ;;\n        custom)\n            template=\"custom-preference\"\n            ;;\n        *)\n            template=\"mesh-v4-only\"  \n            ;;                                  \n    esac\n\n    deploy_mesh ${deployment_type} ${template}\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name --region ${AWS_DEFAULT_REGION}\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name --region ${AWS_DEFAULT_REGION}\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in color_client color_server_v4 color_server_dual color_server_v6; do\n        echo \"deleting repository \\\"${app}\\\"...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --region ${AWS_DEFAULT_REGION} \\\n           --force >/dev/null\n    done\n}\n\ndelete_dns() {\n    delete_cfn_stack \"${PROJECT_NAME}-dns-ecs-service\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-dns-mesh\"\n}\n\ndelete_cloud() {\n    delete_cfn_stack \"${PROJECT_NAME}-cloud-ecs-service\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-cloud-mesh\"\n}\n\ndelete_infra() {\n    delete_cfn_stack \"${PROJECT_NAME}-ecs-cluster\"\n\n    delete_cfn_stack \"${PROJECT_NAME}-vpc\"\n\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1:-\"infra\"}\n\nif [ \"$action\" == \"infra\" ]; then\n    deploy_infra\n    exit 0\nfi\n\nif [ \"$action\" == \"cloud-service\" ]; then\n    deploy_cloud\n    exit 0\nfi\n\nif [ \"$action\" == \"dns-service\" ]; then\n    deploy_dns\n    exit 0\nfi\n\nif [ \"$action\" == \"update-mesh\" ]; then\n    update_mesh $2 $3\n    exit 0\nfi\n\nif [ \"$action\" == \"delete-infra\" ]; then\n    delete_infra\n    exit 0\nfi\n\nif [ \"$action\" == \"delete-cloud-service\" ]; then\n    delete_cloud\n    exit 0\nfi\n\nif [ \"$action\" == \"delete-dns-service\" ]; then\n    delete_dns\n    exit 0\nfi\n\necho \"invalid option chosen\"\n", "num_lines": 272}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"$(basename ${DIR})\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .http2? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support HTTP. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v030\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 113}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-cloudmap\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${PROJECT_NAME}.pvt.aws.local\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_virtualnode_v1beta1(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .cloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v012\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_virtualnode_v1beta2(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .awsCloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_virtualnode_v1beta2\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_virtualnode_v1beta1\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null \n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\"\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    deploy_cloudmap_ns\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 136}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-connection-pools\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nAPP=\"colorapp\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\nVEGETA_IMAGE=\"${ECR_URL}/appmesh/vegeta-trafficgen\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    #check CRD\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.1.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n\n        echo \"building the traffic gen tool vegeta\"\n        ../common/tools/vegeta-trafficgen/build.sh $ECR_URL\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 113}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $CLUSTER1 ]; then\n    echo \"CLUSTER1 Name not set\"\n    exit 1\nfi\n\nif [ -z $CLUSTER2 ]; then\n    echo \"CLUSTER2 Name not set\"\n    exit 1\nfi\n\nif [ -z $VPC_ID ]; then\n    echo \"VPC_ID is not set\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-cross-cluster\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${PROJECT_NAME}.pvt.aws.local\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\ncheck_virtualnode_v1beta1(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .cloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v030\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_virtualnode_v1beta2(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .awsCloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_virtualnode_v1beta2\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_virtualnode_v1beta1\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\" >/dev/null\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_apps_and_mesh() {\n    \n    EXAMPLES_OUT_DIR=\"${DIR}/_output\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/cluster2.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/cluster2_manifest.yaml\n\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/cluster1.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/cluster1_dummy_arn.yaml\n\n    KUBECONFIG=\"$HOME/.kube/eksctl/clusters/${CLUSTER1}\" kubectl apply -f ${EXAMPLES_OUT_DIR}/cluster2_manifest.yaml\n\n    sleep 120\n    ARN=$(KUBECONFIG=\"$HOME/.kube/eksctl/clusters/${CLUSTER1}\" kubectl get virtualservice colorapp -n howto-k8s-cross-cluster  | sed -n 2p | awk -F ' ' '{print $2}')\n    sed \"s|colorapp-service-ARN|$ARN|g\"  ${EXAMPLES_OUT_DIR}/cluster1_dummy_arn.yaml > ${EXAMPLES_OUT_DIR}/cluster1_manifest.yaml\n\n    KUBECONFIG=\"$HOME/.kube/eksctl/clusters/${CLUSTER2}\" kubectl apply -f ${EXAMPLES_OUT_DIR}/cluster1_manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    deploy_cloudmap_ns\n    \n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n    \n    deploy_apps_and_mesh\n}\n\nmain\n", "num_lines": 159}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-egress\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n    requiredver=\"v1.0.0\"\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 85}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_REGION ]; then\n    echo \"AWS_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-envoy-logging-custom-format\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\nmain() {\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n    eval \"cat <<EOF\n$(<${DIR}/manifest.yaml.template)\nEOF\n\" >${DIR}/manifest.yaml\n    kubectl apply -f ${DIR}/manifest.yaml\n}\n\nmain\n", "num_lines": 60}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"$(basename ${DIR})\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp:$(git log -1 --format=%h src/feapp)\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp:$(git log -1 --format=%h src/colorapp)\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support virtualRouter. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .virtualRouter? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support virtualRouter. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v030\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# deploy_images builds and pushes docker images for colorapp and feapp to ECR\ndeploy_images() {\n    for f in colorapp feapp; do\n        aws ecr describe-repositories --repository-name ${PROJECT_NAME}/${f} >/dev/null 2>&1 || aws ecr create-repository --repository-name ${PROJECT_NAME}/${f} >/dev/null\n    done\n\n    ecr_login\n    docker build --build-arg GOPROXY=${GOPROXY} -t ${COLOR_APP_IMAGE} ${DIR}/src/colorapp && docker push ${COLOR_APP_IMAGE}\n    docker build --build-arg GOPROXY=${GOPROXY} -t ${FRONT_APP_IMAGE} ${DIR}/src/feapp && docker push ${FRONT_APP_IMAGE}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 117}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-grpc\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${APP_NAMESPACE}.svc.cluster.local\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nCLIENT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_client\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_server\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support gRPC. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .grpc? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support gRPC. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v030\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in color_client color_server; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\"\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    deploy_cloudmap_ns\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 134}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nprotoc ./color.proto --go_out=plugins=grpc:./color_client/color\nprotoc ./color.proto --go_out=plugins=grpc:./color_server/color\n", "num_lines": 7}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nPROJECT_NAME=\"howto-k8s-grpc-ingress-v2\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAPP=\"greeter\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\"\nSERVER_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\n\nerror() {\n    echo $1\n    exit 1\n}\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    #check CRD\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    # check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.4.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 110}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-http-headers\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .match?.properties.headers | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v020\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.2.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 114}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\nPROJECT_NAME=\"howto-k8s-http-ingress-v2\"\nAPP=\"colorapp\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nGW_ROUTES=\"gatewayroutes\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nMESH_NAME=${PROJECT_NAME}\nAPP_NAMESPACE=${PROJECT_NAME}\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    #check CRD\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.4.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    \neval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\neval \"cat <<EOF\n$(<${DIR}//${MANIFEST_VERSION}/${GW_ROUTES}/prefix-match.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/prefix-match.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\nkubectl apply -f ${EXAMPLES_OUT_DIR}/prefix-match.yaml\n}\n\nmain() {\n    # check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n\n\n", "num_lines": 120}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\nPROJECT_NAME=\"howto-k8s-http-ingress-v2\"\nMESH_NAME=${PROJECT_NAME}\nAPP_NAMESPACE=${PROJECT_NAME}\nEXAMPLES_OUT_DIR=\"${DIR}/_output/\"\nGW_ROUTES=\"gatewayroutes\"\nMANIFEST_VERSION=\"${2:-v1beta2}\"\nmkdir -p ${EXAMPLES_OUT_DIR}\n\ngwRouteForPathMatch() {\n    echo \"Adding GWRoute for Path based match\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/path-match.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/path-match.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/path-match.yaml\n}\n\ngwRouteForHeaderMatch() {\n    echo \"Adding GWRoute for Header based match\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/header-match.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/header-match.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/header-match.yaml\n}\n\ngwRouteForQueryMatch() {\n    echo \"Adding GWRoute for Query based match\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/query-match.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/query-match.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/query-match.yaml\n}\n\ngwRouteForPrefixRewrite() {\n    echo \"Adding GWRoute with Prefix Rewrite\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/rewrite-prefix.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/prefix-rewrite.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/prefix-rewrite.yaml\n}\n\ngwRouteForPathRewrite(){\n    echo \"Adding GWRoute with Path Rewrite\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/rewrite-path.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/path-rewrite.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/path-rewrite.yaml\n}\n\ngwRouteForMethodMatch(){ \n    echo \"Adding GWRoute with Metod match\"\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/${GW_ROUTES}/method-match.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/method-match.yaml\n\nkubectl apply -f ${EXAMPLES_OUT_DIR}/method-match.yaml\n}\n\ngwRouteForAll() {\n    echo \"Adding all GWRoutes\"\n    gwRouteForPathMatch\n    gwRouteForHeaderMatch\n    gwRouteForQueryMatch\n    gwRouteForMethodMatch\n    gwRouteForPrefixRewrite\n    gwRouteForPathRewrite\n}\n\nfor i in $@\ndo\n    if [ $i == \"path-match\" ]; then\n        gwRouteForPathMatch\n    elif [ $i == \"header-match\" ]; then\n        gwRouteForHeaderMatch\n    elif [ $i == \"query-match\" ]; then\n        gwRouteForQueryMatch\n    elif [ $i == \"method-match\" ]; then\n        gwRouteForMethodMatch\n    elif [ $i == \"prefix-rewrite\" ]; then\n        gwRouteForPrefixRewrite\n    elif [ $i == \"path-rewrite\" ]; then\n        gwRouteForPathRewrite\n    elif [ $i == \"all\" ]; then\n        gwRouteForAll\n        break\n    fi\ndone\n", "num_lines": 114}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-http2\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${APP_NAMESPACE}.svc.cluster.local\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nCLIENT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_client\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_server\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP2. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .http2? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support HTTP2. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v030\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in color_client color_server; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app} --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces --output json |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\" >/dev/null\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    deploy_cloudmap_ns\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 134}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-ingress-gateway\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nAPP=\"colorapp\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/${PROJECT_NAME}\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    #check CRD\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.1.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 109}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-ipv6\"\nAPP_NAMESPACE=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${APP_NAMESPACE}.svc.cluster.local\"\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_client\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/color_server\"\nMANIFEST_VERSION=\"${2:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -r '.. | .match?.properties.headers | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualservices.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v020\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.2.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in color_client color_server; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces --output json |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\" >/dev/null\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_cloud() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/cloud\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/cloud/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\ndeploy_dns() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/dns\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/dns/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    #check_appmesh_k8s\n\n    action=\"$1\"\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    if [ \"$action\" = \"cloudmap\" ]; then\n        echo \"deploy cloudmap...\"\n        deploy_cloudmap_ns\n        deploy_cloud\n        exit 0\n    fi\n\n    if [ \"$action\" = \"dns\" ]; then\n        deploy_dns\n        exit 0\n    fi\n}\n\nmain $@\n", "num_lines": 156}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z \"$1\" ]; then\n  echo \"A file name is required\" >&2\n  exit 1\nfi\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\" >&2\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\" >&2\n    exit 1\nfi\n\nif [ -z \"$ENVOY_IMAGE\" ]; then\n    echo \"ENVOY_IMAGE environtment variable is not set, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\" >&2\n    exit 1\nfi\n\nif [ -z \"$CLUSTER_NAME\" ]; then\n    echo \"CLUSTER_NAME environment variable is not set.\" >&2\n    exit 1\nfi\n\nif [ -z \"$NAMESPACE_NAME\" ]; then\n    echo \"NAMESPACE_NAME environment variable is not set.\" >&2\n    exit 1\nfi\n\neval \"cat <<EOF\n$(<\"$1\")\nEOF\"\n", "num_lines": 38}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ncheck_command() {\n  if ! [ -x \"$(command -v \"$1\")\" ]; then\n    echo \"$1 is required to run this script\"\n    exit\n  fi\n}\n\ncheck_command aws\ncheck_command docker\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$NAMESPACE_NAME\" ]; then\n    echo \"NAMESPACE_NAME environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nAWS_CLI_VERSION=\"$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\"\nECR_URL=\"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com\"\nECR_IMAGE_PREFIX=\"$ECR_URL/$NAMESPACE_NAME\"\nDJAPP_IMAGE=\"$ECR_IMAGE_PREFIX/djapp\"\nDASHBOARD_V1_IMAGE=\"$ECR_IMAGE_PREFIX/dashboard-v1\"\nGO_PROXY=\"${GO_PROXY:-\"https://proxy.golang.org\"}\"\n\necr_login() {\n    if [ \"$AWS_CLI_VERSION\" -gt 1 ]; then\n        aws ecr get-login-password --region \"$AWS_DEFAULT_REGION\" | \\\n            docker login --username AWS --password-stdin \"$ECR_URL\"\n    else\n        # Note: we want to execute the output\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ncreate_repositories() {\n    for f in djapp dashboard-v1; do\n        aws ecr describe-repositories --repository-name \"$NAMESPACE_NAME/$f\" >/dev/null 2>&1 || \\\n            aws ecr create-repository --repository-name \"$NAMESPACE_NAME/$f\" >/dev/null\n    done\n}\n\n\ndeploy_images() {\n    create_repositories\n    ecr_login\n\n    docker build -t \"$DASHBOARD_V1_IMAGE\" \"$DIR/../howto-metrics-extension-ecs/src/dashboard-v1\" && \\\n        docker push \"$DASHBOARD_V1_IMAGE\"\n    docker build -t \"$DJAPP_IMAGE\" --build-arg GO_PROXY=\"$GO_PROXY\" \"$DIR/../howto-metrics-extension-ecs/src/djapp\" && \\\n        docker push \"$DJAPP_IMAGE\"\n}\n\n\ndelete_repositories() {\n    for f in djapp dashboard-v1; do\n        aws ecr delete-repository --force --repository-name \"$NAMESPACE_NAME/$f\" >/dev/null\n    done\n}\n\nusage() {\n    echo \"usage: $(basename \"$0\") [upload | delete]\"\n    exit 1\n}\n\naction=\"$1\"\n\ncase \"$action\" in\n    upload)\n      echo \"Building and uploading images...\"\n      deploy_images\n      echo \"Done\"\n      ;;\n    delete)\n      echo \"Deleting images...\"\n      delete_repositories\n      echo \"Done\"\n      ;;\n    *)\n      usage\n      ;;\nesac\n", "num_lines": 95}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ncheck_command() {\n  if ! [ -x \"$(command -v \"$1\")\" ]; then\n    echo \"$1 is required to run this script\"\n    exit\n  fi\n}\n\ncheck_command base64\ncheck_command aws\n\nif [ -x \"$(command -v jq)\" ]; then\n  image_extract=(jq -r '.MetricWidgetImage')\nelse\n  echo \"jq is reccomended to run this script. Will fall back to parsing JSON with sed\"\n  image_extract=(sed -En 's/\\{? *\"MetricWidgetImage\" *: *\"([^\"]+) *,? *\\}?\"/\\1/p')\nfi\n\ncase \"$(uname -a)\" in\n  Linux*)\n    open_cmd=xdg-open\n    ;;\n  Darwin*)\n    open_cmd=open\n    ;;\n  *)\n    echo \"This command only works on Linux or MacOS\"\n    exit 1\n    ;;\nesac\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nPROJECT_NAME=\"${PROJECT_NAME:-\"howto-metrics-extension\"}\"\n\nusage() {\n  echo \"usage: $(basename \"$0\") [-h]\n  -m <metric name>            envoy.appmesh.RequestCountPerTarget\n  [ -n <node name> ]          e.g. djapp\n  [ -t <node type> ]          VirtualNode, VirtualGateway\n  [ -q <search expression> ]  e.g. TargetVirtualNode=metal-v1 \n  [ -x <metric statistic> ]   Average, Sum, p50, etc. Default: Average\n  [ -s <start time> ]         e.g. -PT3H, -P2D, etc. Default: -PT15M\n  [ -p <period> ]             Period in seconds. Default: 60\"\n  exit 1\n}\n\nif [ -z \"$1\" ]; then\n  usage\nfi\n\nstatistic=\"Average\"\nstart_time=\"-PT15M\"\nperiod=\"60\"\n\nwhile getopts \":m:x:s:t:n:q:p:h\" options; do\n  case \"$options\" in\n    m)\n      metric_name=\"$OPTARG\"\n      ;;\n    x)\n      statistic=\"$OPTARG\"\n      ;;\n    s)\n      start_time=\"$OPTARG\"\n      ;;\n    t)\n      node_type=\"$OPTARG\"\n      ;;\n    n)\n      node_name=\"$OPTARG\"\n      ;;\n    q)\n      query=\"$OPTARG\"\n      ;;\n    p)\n      period=\"$OPTARG\"\n      ;;\n    h|:|*)\n      usage\n      ;;\n  esac\ndone\n\nif ! [ -z \"$node_name\" ]; then\n  if [ -z \"$node_type\" ]; then\n    echo \"Node type must be specified with a node name\"\n    exit 1\n  fi\nfi\n\nif ! [ -z \"$node_type\" ]; then\n  if [ -z \"$node_name\" ]; then\n    echo \"Node name must be specified with a node type\"\n    exit 1\n  fi\nfi\n\nif [ -z \"$node_name\" ]; then\n  title=\"$metric_name $statistic\"\n  expression=$(cat <<EOF\n{ \"expression\": \"SEARCH('Namespace=\\\"$PROJECT_NAME\\\" MetricName=\\\"$metric_name\\\" $query', '$statistic', $period)\" }\nEOF\n)\nelse\n  title=\"$node_name - $metric_name $statistic\"\n  expression=$(cat <<EOF\n{ \"expression\": \"SEARCH('Namespace=\\\"$PROJECT_NAME\\\" Mesh=\\\"$PROJECT_NAME\\\" $node_type=\\\"$node_name\\\" MetricName=\\\"$metric_name\\\" $query', '$statistic', $period)\" }\nEOF\n)\nfi\n\nwidget=$(cat <<EOF\n{\n  \"width\": 1200,\n  \"height\": 600,\n  \"period\": $period,\n  \"start\": \"$start_time\",\n  \"end\": \"PT0H\",\n  \"title\": \"$title\",\n  \"metrics\": [\n    [\n      $expression\n    ]\n  ]\n}\nEOF\n)\n\necho \"Metric widget:\"\necho \"$widget\"\n\nfile=\"$(mktemp -u).png\"\n\necho \"Saving metric snapshot to $file\"\n\naws cloudwatch get-metric-widget-image --metric-widget \"$widget\" | \"${image_extract[@]}\" | base64 -d > \"$file\"\n\n$open_cmd \"$file\"\n", "num_lines": 151}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\naction=\"$1\"\nif [ -z \"$action\" ]; then\n    echo \"Usage:\"\n    echo \"mesh.sh [up|addGreen|removeGreen]\"\nfi\n\ncase \"$action\" in\nup)\n    FRONT_APP_CA_CERT=ca_1_cert.pem\n    FRONT_APP_K8S_SECRET=front-ca1-tls\n    ;;\naddGreen)\n    FRONT_APP_CA_CERT=ca_1_ca_2_bundle.pem\n    FRONT_APP_K8S_SECRET=front-ca1-ca2-tls\n    ;;\nremoveGreen)\n    FRONT_APP_CA_CERT=ca_1_cert.pem\n    FRONT_APP_K8S_SECRET=front-ca1-tls\n    ;;\n*)\n    err \"Invalid action specified: $action\"\n    ;;\nesac\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-mtls-file-based\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n    requiredver=\"v1.3.0\"\n    check_k8s_virtualrouter\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 119}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca_1\ngenerate_ca ca_2\n\n# Generate RSA cert for the frontend app\necho \"Generating frontend certificate.\"\ngenerate_rsa_key front ca_1\ngenerate_x509_cert front ca_1\ngenerate_cert_chain front ca_1\n\n# Generate RSA cert for the blue color app\necho \"Generating backend certificate.\"\ngenerate_rsa_key colorapp-blue ca_1\ngenerate_x509_cert colorapp-blue ca_1\ngenerate_cert_chain colorapp-blue ca_1\n\n# Generate cert for the green color app\necho \"Generating backend certificate.\"\ngenerate_rsa_key colorapp-green ca_2\ngenerate_x509_cert colorapp-green ca_2\ngenerate_cert_chain colorapp-green ca_2\n\n#echo \"Generating CA Bundle\"\ngenerate_cert_bundle ca_1 ca_2\n\nrm $DIR/*.csr\nrm $DIR/*.srl\n", "num_lines": 71}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\nremoveSecret() {\n    echo \"Removing $1\"\n    kubectl delete secret $1 -n howto-k8s-mtls-file-based\n}\n\n\nmain() {\n    rm $DIR/*.pem\n    rm $DIR/*.generated\n\n    # Front App\n    removeSecret \"front-ca1-tls\"\n    removeSecret \"front-ca1-ca2-tls\"\n    # Blue Color App\n    removeSecret \"colorapp-blue-tls\"\n    # Green Color App\n    removeSecret \"colorapp-green-tls\"\n}\n\nmain $@\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1=Certificate Name; $2=AppCert/Private Key; $3=CA Cert Name\ndeployAppSecret() {\n    echo $1\n    kubectl create -n howto-k8s-mtls-file-based secret generic $1-tls --from-file=$DIR/$2_key.pem --from-file=$DIR/$2_cert_chain.pem --from-file=$DIR/$3.pem\n}\n\n\n#deployGenericSecret() {\n#    kubectl create -n howto-k8s-mtls-file-based secret generic $1 --from-file=$DIR/$2\n#}\n\nmain() {\n\n    kubectl create ns howto-k8s-mtls-file-based\n    # Front App\n    deployAppSecret \"front-ca1\" \"front\" \"ca_1_cert\"\n    deployAppSecret \"front-ca1-ca2\" \"front\" \"ca_1_ca_2_bundle\"\n    # Blue Color App\n    deployAppSecret \"colorapp-blue\" \"colorapp-blue\" \"ca_1_cert\"\n    # Green Color App\n    deployAppSecret \"colorapp-green\" \"colorapp-green\" \"ca_1_cert\"\n\n   #deployGenericSecret ca1-ca2-bundle-tls ca_1_ca_2_bundle.pem\n   #deployGenericSecret ca1-cert-tls ca_1_cert.pem \n}\n\nmain $@\n", "num_lines": 35}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nmain(){\n  kubectl delete -f _output/manifest.yaml\n  kubectl delete ns spire\n}\n\nmain\n", "num_lines": 9}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nSVID_CA_TRUST_DOMAIN=spiffe://howto-k8s-mtls-sds-based.aws\nFRONTEND_APP_SVID=spiffe://howto-k8s-mtls-sds-based.aws/front\nCOLORAPP_BLUE_SVID=spiffe://howto-k8s-mtls-sds-based.aws/colorblue\nCOLORAPP_GREEN_SVID=spiffe://howto-k8s-mtls-sds-based.aws/colorgreen\nCOLORAPP_RED_SVID=spiffe://howto-k8s-mtls-sds-based.aws/colorred\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-mtls-sds-based\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n    requiredver=\"v1.3.0\"\n    check_k8s_virtualrouter\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 106}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ndeploySpire() {\n    kubectl apply -f spire/spire_setup.yaml\n}\n\necho \"Installing SPIRE Server and Agent\"\ndeploySpire\n", "num_lines": 11}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nregister_server_entries() {\n    kubectl exec -n spire spire-server-0 -c spire-server -- /opt/spire/bin/spire-server entry create $@\n}\n\n\nif [ \"$1\" == \"register\" ]; then\n  echo \"Registering an entry for spire agent...\"\n  register_server_entries \\\n    -spiffeID spiffe://howto-k8s-mtls-sds-based.aws/ns/spire/sa/spire-agent \\\n    -selector k8s_sat:cluster:k8s-cluster \\\n    -selector k8s_sat:agent_ns:spire \\\n    -selector k8s_sat:agent_sa:spire-agent \\\n    -node\n\n  echo \"Registering an entry for the front app...\"\n  register_server_entries \\\n    -parentID spiffe://howto-k8s-mtls-sds-based.aws/ns/spire/sa/spire-agent \\\n    -spiffeID spiffe://howto-k8s-mtls-sds-based.aws/front \\\n    -selector k8s:ns:howto-k8s-mtls-sds-based \\\n    -selector k8s:sa:default \\\n    -selector k8s:pod-label:app:front \\\n    -selector k8s:container-name:envoy\n\n  echo \"Registering an entry for the color app - version:red...\"\n  register_server_entries \\\n    -parentID spiffe://howto-k8s-mtls-sds-based.aws/ns/spire/sa/spire-agent \\\n    -spiffeID spiffe://howto-k8s-mtls-sds-based.aws/colorred \\\n    -selector k8s:ns:howto-k8s-mtls-sds-based \\\n    -selector k8s:sa:default \\\n    -selector k8s:pod-label:app:color \\\n    -selector k8s:pod-label:version:red \\\n    -selector k8s:container-name:envoy\n\n  echo \"Registering an entry for the color app - version:blue...\"\n  register_server_entries \\\n    -parentID spiffe://howto-k8s-mtls-sds-based.aws/ns/spire/sa/spire-agent \\\n    -spiffeID spiffe://howto-k8s-mtls-sds-based.aws/colorblue \\\n    -selector k8s:ns:howto-k8s-mtls-sds-based \\\n    -selector k8s:sa:default \\\n    -selector k8s:pod-label:app:color \\\n    -selector k8s:pod-label:version:blue \\\n    -selector k8s:container-name:envoy\nelif [ \"$1\" == \"registerGreen\" ]; then\n  echo \"Registering an entry for the color app - version:green...\"\n  register_server_entries \\\n    -parentID spiffe://howto-k8s-mtls-sds-based.aws/ns/spire/sa/spire-agent \\\n    -spiffeID spiffe://howto-k8s-mtls-sds-based.aws/colorgreen \\\n    -selector k8s:ns:howto-k8s-mtls-sds-based \\\n    -selector k8s:sa:default \\\n    -selector k8s:pod-label:app:color \\\n    -selector k8s:pod-label:version:green \\\n    -selector k8s:container-name:envoy\nfi\n\n", "num_lines": 59}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_REGION ]; then\n    echo \"AWS_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $CLUSTER_NAME ]; then\n    echo \"CLUSTER_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_REPO ]; then\n    echo \"ENVOY_IMAGE_REPO environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_TAG ]; then\n    echo \"ENVOY_IMAGE_TAG environment variable is not set.\"\n    exit 1\nfi\n\necho \"Enabling IAM OIDC Provider\"\neksctl utils associate-iam-oidc-provider --region=$AWS_REGION \\\n    --cluster=$CLUSTER_NAME \\\n    --approve\n\necho \"Creating namespace appmesh-system\"\nkubectl create ns appmesh-system\n\necho \"Creating namespace howto-k8s-multi-region\"\nkubectl create ns howto-k8s-multi-region\n\necho \"Creating AppMesh Controller IAM service account\"\neksctl create iamserviceaccount --cluster $CLUSTER_NAME \\\n    --namespace appmesh-system \\\n    --name appmesh-controller \\\n    --attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess,arn:aws:iam::aws:policy/AWSAppMeshFullAccess \\\n    --override-existing-serviceaccounts \\\n    --approve\n\necho \"Creating Envoy IAM Service Account\"\n# The output is assigned to a variable just so that the script does not stop for a user input\nPolicyARN=$(aws iam create-policy \\\n    --policy-name ${CLUSTER_NAME}-${AWS_REGION}-AWSAppMeshK8sEnvoyIAMPolicy \\\n    --policy-document file://envoy-iam-policy.json \\\n    --output json --query 'Policy.Arn')\n\neksctl create iamserviceaccount --cluster $CLUSTER_NAME \\\n    --namespace howto-k8s-multi-region \\\n    --name appmesh-controller \\\n    --attach-policy-arn arn:aws:iam::$AWS_ACCOUNT_ID:policy/${CLUSTER_NAME}-${AWS_REGION}-AWSAppMeshK8sEnvoyIAMPolicy \\\n    --approve\n\necho \"Adding eks helm repo\"\nhelm repo add eks https://aws.github.io/eks-charts\n\nhelm repo update\n\necho \"Install appmesh-controller helm chart\"\nhelm upgrade -i appmesh-controller eks/appmesh-controller \\\n    --namespace appmesh-system \\\n    --set region=$AWS_REGION \\\n    --set serviceAccount.create=false \\\n    --set serviceAccount.name=appmesh-controller \\\n    --set sidecar.image.repository=$ENVOY_IMAGE_REPO \\\n    --set sidecar.image.tag=$ENVOY_IMAGE_TAG\n", "num_lines": 70}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nAWS_REGION_1=$1\nAWS_REGION_2=$2\nCLUSTER_NAME_1=$3\nCLUSTER_NAME_2=$4\nDOMAIN_NAME=$5\nSUB_DOMAIN_NAME=$6\nHOSTED_ZONE_ID=$7\n\nif [ -z $AWS_REGION_1 ]; then\n    echo \"Not a valid value for AWS region A.\"\n    exit 1\nfi\n\nif [ -z $AWS_REGION_2 ]; then\n    echo \"Not a valid value for AWS region B.\"\n    exit 1\nfi\n\nif [ -z $CLUSTER_NAME_1 ]; then\n    echo \"Not a valid value for cluster name in region A.\"\n    exit 1\nfi\n\nif [ -z $CLUSTER_NAME_2 ]; then\n    echo \"Not a valid value for cluster name in region B.\"\n    exit 1\nfi\n\nif [ -z $DOMAIN_NAME ]; then\n    echo \"Not a valid value for domain name.\"\n    exit 1\nfi\n\nif [ -z $SUB_DOMAIN_NAME ]; then\n    SUB_DOMAIN_NAME=`echo myapp.walkthrough.$DOMAIN_NAME`\nelse\n    SUB_DOMAIN_NAME=`echo $SUB_DOMAIN_NAME.$DOMAIN_NAME`\nfi\n\necho \"Creating health check records for region A\"\nexport KUBECONFIG=~/.kube/eksctl/clusters/$CLUSTER_NAME_1\nexport GW_ENDPOINT_1=$(kubectl get svc ingress-gw -n howto-k8s-multi-region --output jsonpath='{.status.loadBalancer.ingress[0].hostname}')\n\nuidRegioAWhite=`uuidgen`\nuidRegioARed=`uuidgen`\nuidRegioABlue=`uuidgen`\n\nregionAWhite=`aws route53 create-health-check --caller-reference $uidRegioAWhite --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/white\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_1\"'\"}' --query 'HealthCheck.Id' --output text`\nregionARed=`aws route53 create-health-check --caller-reference $uidRegioARed --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/red\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_1\"'\"}' --query 'HealthCheck.Id' --output text`\nregionABlue=`aws route53 create-health-check --caller-reference $uidRegioABlue --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/blue\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_1\"'\"}' --query 'HealthCheck.Id' --output text`\n\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionAWhite --add-tags Key=Name,Value=regionA-white\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionARed --add-tags Key=Name,Value=regionA-red\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionABlue --add-tags Key=Name,Value=regionA-blue\n\nuidRegioACombined=`uuidgen`\nregionACombinedHealthCheck=`aws route53 create-health-check --caller-reference $uidRegioACombined --health-check-config '{\"Type\": \"CALCULATED\", \"HealthThreshold\": 3, \"ChildHealthChecks\" : [\"'\"$regionAWhite\"'\",\"'\"$regionARed\"'\",\"'\"$regionABlue\"'\"]}' --query 'HealthCheck.Id' --output text`\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionACombinedHealthCheck --add-tags Key=Name,Value=regionA-health\n\necho \"Region A white path health check ID : $regionAWhite\"\necho \"Region A red path health check ID : $regionARed\"\necho \"Region A blue path health check ID : $regionABlue\"\necho \"Region A combined health check ID : $regionACombinedHealthCheck\"\n\n\necho \"Creating health check records for region B\"\nexport KUBECONFIG=~/.kube/eksctl/clusters/$CLUSTER_NAME_2\nexport GW_ENDPOINT_2=$(kubectl get svc ingress-gw -n howto-k8s-multi-region --output jsonpath='{.status.loadBalancer.ingress[0].hostname}')\n\nuidRegioBWhite=`uuidgen`\nuidRegioBRed=`uuidgen`\nuidRegioBBlue=`uuidgen`\n\nregionBWhite=`aws route53 create-health-check --caller-reference $uidRegioBWhite --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/white\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_2\"'\"}' --query 'HealthCheck.Id' --output text`\nregionBRed=`aws route53 create-health-check --caller-reference $uidRegioBRed --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/red\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_2\"'\"}' --query 'HealthCheck.Id' --output text`\nregionBBlue=`aws route53 create-health-check --caller-reference $uidRegioBBlue --health-check-config '{\"Port\": 80, \"Type\": \"HTTP\", \"ResourcePath\": \"paths/blue\", \"FullyQualifiedDomainName\": \"'\"$GW_ENDPOINT_2\"'\"}' --query 'HealthCheck.Id' --output text`\n\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionBWhite --add-tags Key=Name,Value=regionB-white\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionBRed --add-tags Key=Name,Value=regionB-red\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionBBlue --add-tags Key=Name,Value=regionB-blue\n\nuidRegioBCombined=`uuidgen`\nregionBCombinedHealthCheck=`aws route53 create-health-check --caller-reference $uidRegioBCombined --health-check-config '{\"Type\": \"CALCULATED\", \"HealthThreshold\": 3, \"ChildHealthChecks\" : [\"'\"$regionBWhite\"'\",\"'\"$regionBRed\"'\",\"'\"$regionBBlue\"'\"]}' --query 'HealthCheck.Id' --output text`\naws route53 change-tags-for-resource --resource-type healthcheck --resource-id $regionBCombinedHealthCheck --add-tags Key=Name,Value=regionB-health\n\necho \"Region B white path health check ID : $regionBWhite\"\necho \"Region B red path health check ID : $regionBRed\"\necho \"Region B blue path health check ID : $regionBBlue\"\necho \"Region B combined health check ID : $regionBCombinedHealthCheck\"\n\necho \"Completed creating health check records\"\n\nif [ -z $HOSTED_ZONE_ID ]; then\n    echo \"Creating route53 hostedzone\"\n    uidHostedZone=`uuidgen`\n    hostedZoneId=`aws route53 create-hosted-zone --name $DOMAIN_NAME --caller-reference $uidHostedZone --hosted-zone-config Comment=\"Hosted zone for app mesh multiregion walkthrough\" --query 'HostedZone.Id' --output text`\n    echo \"Created new Hosted Zone with ID: $hostedZoneId\"\nelse\n    hostedZoneId=$HOSTED_ZONE_ID\n    echo \"Using existing Hosted Zone ID: $hostedZoneId\" \nfi\n\necho \"Creating CNAME record for region A\"\nregionARecord=`aws route53 change-resource-record-sets --hosted-zone-id $hostedZoneId --change-batch '{\"Changes\": [{ \"Action\": \"CREATE\", \"ResourceRecordSet\":{ \"Name\": \"'\"$SUB_DOMAIN_NAME\"'\", \"Type\": \"CNAME\", \"SetIdentifier\": \"regionARecordID\", \"Region\": \"'\"$AWS_REGION_1\"'\", \"TTL\": 300, \"ResourceRecords\": [{ \"Value\": \"'\"$GW_ENDPOINT_1\"'\" }], \"HealthCheckId\": \"'\"$regionACombinedHealthCheck\"'\" }}]}'`\n\necho \"Creating CNAME record for region B\"\nregionBRecord=`aws route53 change-resource-record-sets --hosted-zone-id $hostedZoneId --change-batch '{\"Changes\": [{ \"Action\": \"CREATE\", \"ResourceRecordSet\":{ \"Name\": \"'\"$SUB_DOMAIN_NAME\"'\", \"Type\": \"CNAME\", \"SetIdentifier\": \"regionBRecordID\", \"Region\": \"'\"$AWS_REGION_2\"'\", \"TTL\": 300, \"ResourceRecords\": [{ \"Value\": \"'\"$GW_ENDPOINT_2\"'\" }], \"HealthCheckId\": \"'\"$regionBCombinedHealthCheck\"'\" }}]}'`\n\n\necho \"Completed configuring route53\"", "num_lines": 114}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_REGION ]; then\n    echo \"AWS_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_REPO ]; then\n    echo \"ENVOY_IMAGE_REPO environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_TAG ]; then\n    echo \"ENVOY_IMAGE_TAG environment variable is not set.\"\n    exit 1\nfi\n\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-multi-region\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nAPP=\"colorapp\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${PROJECT_NAME}\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/${APP}\"\nMANIFEST_VERSION=\"${1:-v1beta2}\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualgateway() {\n    #check CRD\n    crd=$(kubectl get crd virtualgateways.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualgateways.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_gatewayroutes() {\n    #check CRD\n    crd=$(kubectl get crd gatewayroutes.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires gatewayroutes.appmesh.k8s.aws CRD to support Ingress gateway. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.1.0\"\n        check_k8s_virtualgateway\n        check_k8s_gatewayroutes\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    aws ecr describe-repositories --repository-name $PROJECT_NAME/${APP} >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/${APP} >/dev/null\n    docker build -t ${ECR_IMAGE_PREFIX}/${APP} ${DIR}/${APP}\n    ecr_login\n    docker push ${ECR_IMAGE_PREFIX}/${APP}\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 120}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_REGION ]; then\n    echo \"AWS_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $CLUSTER_NAME ]; then\n    echo \"CLUSTER_NAME environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_REPO ]; then\n    echo \"ENVOY_IMAGE_REPO environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_TAG ]; then\n    echo \"ENVOY_IMAGE_TAG environment variable is not set.\"\n    exit 1\nfi\n\necho \"Creating EKS cluster $CLUSTER_NAME in region $AWS_REGION\"\n\neksctl create cluster --name=$CLUSTER_NAME --nodes=2 \\\n--region=$AWS_REGION --auto-kubeconfig\n", "num_lines": 34}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-outlier-detection\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${PROJECT_NAME}.pvt.aws.local\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\nVEGETA_IMAGE=\"${ECR_URL}/appmesh/vegeta-trafficgen\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_virtualnode_v1beta2(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .awsCloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.2.0\"\n        check_virtualnode_v1beta2\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Timeouts are only supported in v1beta2 and AppMesh controller version >= v1.2.0. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_cloudmap_ns() {\n    nsId=($(aws servicediscovery list-namespaces |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\"\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n\n\techo \"building the traffic gen tool vegeta\"\n\t../common/tools/vegeta-trafficgen/build.sh $ECR_URL\n    fi\n\n    deploy_cloudmap_ns\n    deploy_app\n}\n\nmain\n", "num_lines": 125}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-retry-policy\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support retryPolicy. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_k8s_virtualservice() {\n    #check CRD\n    crd=$(kubectl get crd virtualservices.appmesh.k8s.aws -o json | jq -e '.. | .retryPolicy? | select(. != null)')\n    if [ \"$crd\" = \"\" ]; then \n        echo \"$PROJECT_NAME requires CRD that supports retryPolicy. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md#v020\"\n        exit 1\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_k8s_virtualrouter\n    elif [ \"$MANIFEST_VERSION\" = \"v1beta1\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n        requiredver=\"v0.3.0\"\n        check_k8s_virtualservice\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Should be v1beta2 or v1beta1 based on the AppMesh controller version. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nredeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    kubectl delete -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n    deploy_app\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    if [ \"$REDEPLOY\" = true ]; then\n        echo \"redeploying app...\"    \n        redeploy_app\n        exit 0\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 126}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-timeout-policy\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\nCLOUDMAP_NAMESPACE=\"${PROJECT_NAME}.pvt.aws.local\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nMANIFEST_VERSION=\"${1:-v1beta2}\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_virtualnode_v1beta2(){\n    #check CRD\n    crd=$(kubectl get crd virtualnodes.appmesh.k8s.aws -o json | jq -r '.. | .awsCloudMap?.properties.namespaceName? | select(. != null)')\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualnodes.appmesh.k8s.aws CRD to support Cloud Map service-discovery. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    if [ \"$MANIFEST_VERSION\" = \"v1beta2\" ]; then\n        currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n        requiredver=\"v1.0.0\"\n        check_virtualnode_v1beta2\n    else\n        error \"$PROJECT_NAME unexpected manifest version input: $MANIFEST_VERSION. Timeouts are only supported in v1beta2 and AppMesh controller version >= v1.0.0. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_timeout_ns() {\n    nsId=($(aws servicediscovery list-namespaces |\n        jq -r \".Namespaces[] | select(.Name | contains(\\\"${CLOUDMAP_NAMESPACE}\\\")) | .Id\"))\n\n    if [ -z \"${nsId}\" ]; then\n        if [ -z \"${VPC_ID}\" ]; then\n            echo \"VPC_ID must be set. VPC_ID corresponds to vpc where applications are deployed.\"\n            exit 1\n        fi\n\n        aws servicediscovery create-private-dns-namespace \\\n            --name \"${CLOUDMAP_NAMESPACE}\" \\\n            --vpc \"${VPC_ID}\"\n        echo \"Created private-dns-namespace ${CLOUDMAP_NAMESPACE}\"\n        sleep 5\n    fi\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/${MANIFEST_VERSION}/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    deploy_timeout_ns\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 122}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\naction=\"$1\"\nif [ -z \"$action\" ]; then\n    echo \"Usage:\"\n    echo \"mesh.sh [up]\"\nfi\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-tls-acm\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n    requiredver=\"v1.0.0\"\n    check_k8s_virtualrouter\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 101}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eo pipefail\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\naction=\"$1\"\nif [ -z \"$action\" ]; then\n    echo \"Usage:\"\n    echo \"mesh.sh [up|addGreen|removeGreen]\"\nfi\n\ncase \"$action\" in\nup)\n    FRONTEND_APP_CERT=ca1-cert-tls\n    FRONTEND_CERT_CHAIN=ca_1_cert.pem\n    ;;\naddGreen)\n    FRONTEND_APP_CERT=ca1-ca2-bundle-tls\n    FRONTEND_CERT_CHAIN=ca_1_ca_2_bundle.pem\n    ;;\nremoveGreen)\n    FRONTEND_APP_CERT=ca1-cert-tls\n    FRONTEND_CERT_CHAIN=ca_1_cert.pem\n    ;;    \n*)\n    err \"Invalid action specified: $action\"\n    ;;\nesac\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-k8s-tls-file-based\"\nAPP_NAMESPACE=${PROJECT_NAME}\nMESH_NAME=${PROJECT_NAME}\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=\"${ECR_URL}/${PROJECT_NAME}\"\nFRONT_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/feapp\"\nCOLOR_APP_IMAGE=\"${ECR_IMAGE_PREFIX}/colorapp\"\n\nerror() {\n    echo $1\n    exit 1\n}\n\ncheck_k8s_virtualrouter() {\n    #check CRD\n    crd=$(kubectl get crd virtualrouters.appmesh.k8s.aws -o json )\n    if [ -z \"$crd\" ]; then\n        error \"$PROJECT_NAME requires virtualrouters.appmesh.k8s.aws CRD to support HTTP headers match. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    else\n        echo \"CRD check passed!\"\n    fi\n}\n\ncheck_appmesh_k8s() {\n    #check aws-app-mesh-controller version\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':'|tail -n1)\n    requiredver=\"v1.0.0\"\n    check_k8s_virtualrouter\n\n    if [ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" ]; then\n        echo \"aws-app-mesh-controller check passed! $currentver >= $requiredver\"\n    else\n        error \"$PROJECT_NAME requires aws-app-mesh-controller version >=$requiredver but found $currentver. See https://github.com/aws/aws-app-mesh-controller-for-k8s/blob/master/CHANGELOG.md\"\n    fi\n}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in colorapp feapp; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_app() {\n    EXAMPLES_OUT_DIR=\"${DIR}/_output/\"\n    mkdir -p ${EXAMPLES_OUT_DIR}\n    eval \"cat <<EOF\n$(<${DIR}/v1beta2/manifest.yaml.template)\nEOF\n\" >${EXAMPLES_OUT_DIR}/manifest.yaml\n\n    kubectl apply -f ${EXAMPLES_OUT_DIR}/manifest.yaml\n}\n\nmain() {\n    check_appmesh_k8s\n\n    if [ -z $SKIP_IMAGES ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    deploy_app\n}\n\nmain\n", "num_lines": 119}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca_1\ngenerate_ca ca_2\n\n# Generate RSA cert for the blue color app\necho \"Generating backend certificate.\"\ngenerate_rsa_key colorapp-blue ca_1\ngenerate_x509_cert colorapp-blue ca_1\ngenerate_cert_chain colorapp-blue ca_1\n\n# Generate cert for the green color app\necho \"Generating backend certificate.\"\ngenerate_rsa_key colorapp-green ca_2\ngenerate_x509_cert colorapp-green ca_2\ngenerate_cert_chain colorapp-green ca_2\n\necho \"Generating CA Bundle\"\ngenerate_cert_bundle ca_1 ca_2\n\nrm $DIR/*.csr\nrm $DIR/*.srl\n", "num_lines": 65}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\nremoveSecret() {\n    echo \"Removing $1\"\n    kubectl delete secret $1 -n howto-k8s-tls-file-based\n}\n\n\nmain() {\n    rm $DIR/*.pem\n    rm $DIR/*.generated\n\n    # Blue Color App\n    removeSecret \"colorapp-blue-tls\"\n    # Green Color App\n    removeSecret \"colorapp-green-tls\"\n    # Remove CA1 CA2 certs\n    removeSecret \"ca1-ca2-bundle-tls\"\n    removeSecret \"ca1-cert-tls\"\n}\n\nmain $@\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\ndeployAppSecret() {\n    echo $1\n    kubectl create -n howto-k8s-tls-file-based secret generic $1-tls --from-file=$DIR/$1_key.pem --from-file=$DIR/$1_cert_chain.pem\n}\n\n\ndeployGenericSecret() {\n    kubectl create -n howto-k8s-tls-file-based secret generic $1 --from-file=$DIR/$2\n}\n\nmain() {\n\n    kubectl create ns howto-k8s-tls-file-based\n    # Blue Color App\n    deployAppSecret \"colorapp-blue\"\n    # Green Color App\n    deployAppSecret \"colorapp-green\"\n\n    deployGenericSecret ca1-ca2-bundle-tls ca_1_ca_2_bundle.pem\n    deployGenericSecret ca1-cert-tls ca_1_cert.pem \n}\n\nmain $@\n", "num_lines": 32}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIP'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"ColorApp Endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-service\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='ColorAppEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\nprint_bastion\nprint_endpoint\n", "num_lines": 39}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    vgateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gateway_route() {\n    vgateway_name=$1\n    gatewayroute_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service  \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vrouter() {\n    spec_file=$1\n    vrouter_name=$2\n    cmd=( $appmesh_cmd create-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vrouter() {\n    vrouter_name=$1\n    cmd=( $appmesh_cmd delete-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd create-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd update-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_route() {\n    vrouter_name=$1\n    route_name=$2\n    cmd=( $appmesh_cmd delete-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    update_resource=\"$2\"\n    resource_name=\"$3\"\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-red-vn.json\" \"colorteller-red-vn\" \"colorteller-red\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-1.json\" \"colorteller-vr-1\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route-1.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-1.json\" \"colorteller-1.${SERVICES_DOMAIN}\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-yellow-vn.json\" \"colorteller-yellow-vn\" \"colorteller-yellow\"\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr-2.json\" \"colorteller-vr-2\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route-2.json\" \"colorteller-vr-2\" \"colorteller-route-2\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs-2.json\" \"colorteller-2.${SERVICES_DOMAIN}\"\n\n        create_vgateway \"${TEST_MESH_DIR}/colorgateway-vg.json\" \"colorgateway-vg\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-1.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        create_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-2.json\" \"colorgateway-vg\" \"colorgateway-route-2\" \"colorteller-2.${SERVICES_DOMAIN}\"\n        ;;\n    configure-query-parameter-match-rewrite)\n        update_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-updated-rewrite.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        update_route \"${TEST_MESH_DIR}/colorteller-route-updated-rewrite.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        ;;\n    disable-default-prefix-rewrite)\n        update_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-updated-disabled_rewrite.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        update_route \"${TEST_MESH_DIR}/colorteller-route-updated-rewrite.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        ;;\n    configure-hostname-match)\n        update_gateway_route \"${TEST_MESH_DIR}/colorgateway-route-updated-hostname-match.json\" \"colorgateway-vg\" \"colorgateway-route-1\" \"colorteller-1.${SERVICES_DOMAIN}\"\n        update_route \"${TEST_MESH_DIR}/colorteller-route-1.json\" \"colorteller-vr-1\" \"colorteller-route-1\"\n        ;;\n    down)\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-1\"\n        delete_gateway_route \"colorgateway-vg\" \"colorgateway-route-2\"\n        delete_vgateway \"colorgateway-vg\"\n\n        delete_vservice \"colorteller-1.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr-1\" \"colorteller-route-1\"\n        delete_vrouter \"colorteller-vr-1\"\n        delete_vservice \"colorteller-2.${SERVICES_DOMAIN}\"\n\n        delete_route \"colorteller-vr-2\" \"colorteller-route-2\"\n        delete_vrouter \"colorteller-vr-2\"\n        delete_vnode \"colorteller-red-vn\"\n        delete_vnode \"colorteller-yellow-vn\"\n\n        delete_mesh\n        ;;\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n``\nmain $@\n", "num_lines": 337}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n# login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n         docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncheck_command() {\n  if ! [ -x \"$(command -v \"$1\")\" ]; then\n    echo \"$1 is required to run this script\"\n    exit\n  fi\n}\n\ncheck_command aws\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\n\nusage() {\n  echo \"usage: $(basename \"$0\") [-h]\n    -c <command>                         deploy or delete\n    -s <stack name>                      Cloudformation stack name \n    [ -q <metric namespace> ]            Metric namespace name\n    [ -d <dashboard name> ]              Cloudformation dashboard name\n    [ -i <dashboard lambda image uri> ]  Dashboard generator lambda image URI\n    [ -m <mesh name> ]                   Mesh name\n    [ -g <virtual gateway name> ]        Virtual gateway name.\n    [ -n <virtual nodes> ]               Comma separated list of virtual node names.\"\n  exit 1\n}\n\ndelete_cfn_stack() {\n    stack_name=\"$1\"\n    aws cloudformation delete-stack --stack-name \"$stack_name\"\n    echo \"Waiting for the stack $stack_name to be deleted, this may take a few minutes...\"\n    aws cloudformation wait stack-delete-complete --stack-name \"$stack_name\"\n    echo \"Done\"\n}\n\ncheck_opt() {\n  name=\"$1\"\n  msg=\"$2\"\n  if [ -z \"$name\" ]; then\n    echo \"$msg\"\n    exit 1\n  fi\n}\n\nif [ -z \"$1\" ]; then\n  usage\nfi\n\nwhile getopts \":c:s:q:d:i:m:g:n:h\" options; do\n  case \"$options\" in\n    c)\n      cmd=\"$OPTARG\"\n      ;;\n    s)\n      stack_name=\"$OPTARG\"\n      ;;\n    q)\n      metric_namespace=\"$OPTARG\"\n      ;;\n    d)\n      dashboard_name=\"$OPTARG\"\n      ;;\n    i)\n      dashboard_image=\"$OPTARG\"\n      ;;\n    m)\n      mesh_name=\"$OPTARG\"\n      ;;\n    g)\n      resource_type=VirtualGateway\n      resources=\"$OPTARG\"\n      ;;\n    n)\n      resource_type=VirtualNodes\n      resources=\"$OPTARG\"\n      ;;\n    h|:|*)\n      usage\n      ;;\n  esac\ndone\n\ncheck_opt \"$cmd\" \"A command, deploy or delete must be specified\"\ncheck_opt \"$stack_name\" \"Stack name is required\"\n\ncase \"$cmd\" in\n  delete)\n    delete_cfn_stack \"$stack_name\" \n    ;;\n  deploy)\n    check_opt \"$dashboard_image\" \"Dashboard generator image URI is required\"\n    check_opt \"$metric_namespace\" \"Metric namespace is required\"\n    check_opt \"$mesh_name\" \"Mesh name is required\"\n    check_opt \"$dashboard_name\" \"Dashboard name is required\"\n    check_opt \"$resources\" \"Either a list of virtual node names or a virtual gateway name is required\"\n\n    echo \"Deploying stack $stack_name, this may take a few minutes...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"$stack_name\" \\\n        --template-file \"$DIR/deploy/dashboard-v1.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        \"DashboardImage=$dashboard_image\" \\\n        \"MetricNamespace=$metric_namespace\" \\\n        \"MeshName=$mesh_name\" \\\n        \"Name=$dashboard_name\" \\\n        \"$resource_type=$resources\"    \n    ;;\n  *)\n    echo \"Command must be either deploy or delete\"\n    exit 1\n    ;;\nesac\n", "num_lines": 124}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ncheck_command() {\n  if ! [ -x \"$(command -v \"$1\")\" ]; then\n    echo \"$1 is required to run this script\"\n    exit\n  fi\n}\n\ncheck_command aws\ncheck_command docker\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$ENVOY_IMAGE\" ]; then\n    echo \"ENVOY_IMAGE environtment variable is not set, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nAWS_CLI_VERSION=\"$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\"\n\nPROJECT_NAME=\"${PROJECT_NAME:-\"howto-metrics-extension\"}\"\nSTACK_NAME=\"appmesh-$PROJECT_NAME\"\nECR_URL=\"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com\"\nECR_IMAGE_PREFIX=\"$ECR_URL/$PROJECT_NAME\"\nCW_AGENT_IMAGE=\"$ECR_IMAGE_PREFIX/cwagent\"\nDJAPP_IMAGE=\"$ECR_IMAGE_PREFIX/djapp\"\nDASHBOARD_V1_IMAGE=\"$ECR_IMAGE_PREFIX/dashboard-v1\"\nGO_PROXY=\"${GO_PROXY:-\"https://proxy.golang.org\"}\"\n\necr_login() {\n    if [ \"$AWS_CLI_VERSION\" -gt 1 ]; then\n        aws ecr get-login-password --region \"$AWS_DEFAULT_REGION\" | \\\n            docker login --username AWS --password-stdin \"$ECR_URL\"\n    else\n        # Note: we want to execute the output\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ncreate_repositories() {\n    for f in cwagent djapp dashboard-v1; do\n        aws ecr describe-repositories --repository-name \"$PROJECT_NAME/$f\" >/dev/null 2>&1 || \\\n            aws ecr create-repository --repository-name \"$PROJECT_NAME/$f\" >/dev/null\n    done\n}\n\ndeploy_images() {\n    create_repositories\n    ecr_login\n\n    docker build -t \"$CW_AGENT_IMAGE\" \"$DIR/src/cwagent\" && \\\n        docker push \"$CW_AGENT_IMAGE\"\n    docker build -t \"$DASHBOARD_V1_IMAGE\" \"$DIR/src/dashboard-v1\" && \\\n        docker push \"$DASHBOARD_V1_IMAGE\"\n    docker build -t \"$DJAPP_IMAGE\" --build-arg GO_PROXY=\"$GO_PROXY\" \"$DIR/src/djapp\" && \\\n        docker push \"$DJAPP_IMAGE\"\n}\n\ndelete_repositories() {\n    for f in cwagent djapp dashboard-v1; do\n        aws ecr delete-repository --force --repository-name \"$PROJECT_NAME/$f\" >/dev/null\n    done\n}\n\ndeploy() {\n    stage=\"$1\"\n    \n    echo \"Deploying stack $STACK_NAME, this may take a few minutes...\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"$STACK_NAME\" \\\n        --template-file \"$DIR/deploy/$stage.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \\\n        \"ProjectName=$PROJECT_NAME\" \\\n        \"EnvoyImage=$ENVOY_IMAGE\" \\\n        \"CloudWatchAgentImage=$CW_AGENT_IMAGE\" \\\n        \"DJAppImage=$DJAPP_IMAGE\"\n}\n\ndelete_cfn_stack() {\n    stack_name=\"$1\"\n    aws cloudformation delete-stack --stack-name \"$stack_name\"\n    echo \"Waiting for the stack $stack_name to be deleted, this may take a few minutes...\"\n    aws cloudformation wait stack-delete-complete --stack-name \"$stack_name\"\n    echo \"Done\"\n}\n\nconfirm_service_linked_role() {\n    if ! (aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null); then\n        echo \"Error: no service linked role for App Mesh exists\"\n        echo \"see https://docs.aws.amazon.com/app-mesh/latest/userguide/using-service-linked-roles.html\"\n        exit 1\n    fi\n}\n\nprint_endpoint() {\n    echo \"Public endpoint is now available. Export it for later use:\"\n    prefix=\"$(aws cloudformation describe-stacks \\\n        --stack-name=\"$STACK_NAME\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='PublicEndpoint'].OutputValue\" \\\n        --output=text)\"\n    echo \"export PUBLIC_ENDPOINT=\\\"${prefix}\\\"\"\n}\n\ndeploy_stacks() {\n    if [ -z \"$SKIP_IMAGES\" ]; then\n        echo \"deploy images...\"\n        deploy_images\n    fi\n\n    echo \"deploy app using stage $stage\"\n    deploy \"$stage\"\n\n    if [ \"$stage\" == \"djapp-v1\" ]; then\n    \tconfirm_service_linked_role\n    fi\n    print_endpoint\n}\n\naction=\"${1:-\"deploy\"}\"\nstage=\"${2:-\"djapp-v1\"}\"\n\nif [ \"$action\" == \"delete\" ]; then\n    delete_cfn_stack \"$STACK_NAME\"\n    delete_repositories\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 143}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ncheck_command() {\n  if ! [ -x \"$(command -v \"$1\")\" ]; then\n    echo \"$1 is required to run this script\"\n    exit\n  fi\n}\n\ncheck_command base64\ncheck_command aws\n\nif [ -x \"$(command -v jq)\" ]; then\n  image_extract=(jq -r '.MetricWidgetImage')\nelse\n  echo \"jq is reccomended to run this script. Will fall back to parsing JSON with sed\"\n  image_extract=(sed -En 's/\\{? *\"MetricWidgetImage\" *: *\"([^\"]+) *,? *\\}?\"/\\1/p')\nfi\n\ncase \"$(uname -a)\" in\n  Linux*)\n    open_cmd=xdg-open\n    ;;\n  Darwin*)\n    open_cmd=open\n    ;;\n  *)\n    echo \"This command only works on Linux or MacOS\"\n    exit 1\n    ;;\nesac\n\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z \"$AWS_DEFAULT_REGION\" ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nPROJECT_NAME=\"${PROJECT_NAME:-\"howto-metrics-extension\"}\"\n\nusage() {\n  echo \"usage: $(basename \"$0\") [-h]\n  -m <metric name>            envoy.appmesh.RequestCountPerTarget\n  [ -n <node name> ]          e.g. djapp\n  [ -t <node type> ]          VirtualNode, VirtualGateway\n  [ -q <search expression> ]  e.g. TargetVirtualNode=metal-v1 \n  [ -x <metric statistic> ]   Average, Sum, p50, etc. Default: Average\n  [ -s <start time> ]         e.g. -PT3H, -P2D, etc. Default: -PT15M\n  [ -p <period> ]             Period in seconds. Default: 60\"\n  exit 1\n}\n\nif [ -z \"$1\" ]; then\n  usage\nfi\n\nstatistic=\"Average\"\nstart_time=\"-PT15M\"\nperiod=\"60\"\n\nwhile getopts \":m:x:s:t:n:q:p:h\" options; do\n  case \"$options\" in\n    m)\n      metric_name=\"$OPTARG\"\n      ;;\n    x)\n      statistic=\"$OPTARG\"\n      ;;\n    s)\n      start_time=\"$OPTARG\"\n      ;;\n    t)\n      node_type=\"$OPTARG\"\n      ;;\n    n)\n      node_name=\"$OPTARG\"\n      ;;\n    q)\n      query=\"$OPTARG\"\n      ;;\n    p)\n      period=\"$OPTARG\"\n      ;;\n    h|:|*)\n      usage\n      ;;\n  esac\ndone\n\nif ! [ -z \"$node_name\" ]; then\n  if [ -z \"$node_type\" ]; then\n    echo \"Node type must be specified with a node name\"\n    exit 1\n  fi\nfi\n\nif ! [ -z \"$node_type\" ]; then\n  if [ -z \"$node_name\" ]; then\n    echo \"Node name must be specified with a node type\"\n    exit 1\n  fi\nfi\n\nif [ -z \"$node_name\" ]; then\n  title=\"$metric_name $statistic\"\n  expression=$(cat <<EOF\n{ \"expression\": \"SEARCH('Namespace=\\\"$PROJECT_NAME\\\" MetricName=\\\"$metric_name\\\" $query', '$statistic', $period)\" }\nEOF\n)\nelse\n  title=\"$node_name - $metric_name $statistic\"\n  expression=$(cat <<EOF\n{ \"expression\": \"SEARCH('Namespace=\\\"$PROJECT_NAME\\\" Mesh=\\\"$PROJECT_NAME\\\" $node_type=\\\"$node_name\\\" MetricName=\\\"$metric_name\\\" $query', '$statistic', $period)\" }\nEOF\n)\nfi\n\nwidget=$(cat <<EOF\n{\n  \"width\": 1200,\n  \"height\": 600,\n  \"period\": $period,\n  \"start\": \"$start_time\",\n  \"end\": \"PT0H\",\n  \"title\": \"$title\",\n  \"metrics\": [\n    [\n      $expression\n    ]\n  ]\n}\nEOF\n)\n\necho \"Metric widget:\"\necho \"$widget\"\n\nfile=\"$(mktemp -u).png\"\n\necho \"Saving metric snapshot to $file\"\n\naws cloudwatch get-metric-widget-image --metric-widget \"$widget\" | \"${image_extract[@]}\" | base64 -d > \"$file\"\n\n$open_cmd \"$file\"\n", "num_lines": 151}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    TellerImageName=\"${TELLER_IMAGE_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    TellerImageName=\"${TELLER_IMAGE_NAME}\"\n\nprint_bastion() {\n    echo \"Bastion endpoint:\"\n    ip=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='BastionIP'].OutputValue\" \\\n        --output=text)\n    echo \"${ip}\"\n}\n\nprint_endpoint() {\n    echo \"ColorApp Endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${ENVIRONMENT_NAME}-ecs-service\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='TellerAppEndpoint'].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\nprint_bastion\nprint_endpoint\n", "num_lines": 39}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    vgateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gateway_route() {\n    vgateway_name=$1\n    gatewayroute_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service  \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vrouter() {\n    spec_file=$1\n    vrouter_name=$2\n    cmd=( $appmesh_cmd create-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vrouter() {\n    vrouter_name=$1\n    cmd=( $appmesh_cmd delete-virtual-router \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd create-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_route() {\n    vrouter_name=$1\n    route_name=$2\n    cmd=( $appmesh_cmd delete-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    update_resource=\"$2\"\n    resource_name=\"$3\"\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n\n        create_vnode \"${TEST_MESH_DIR}/colorteller-vn.json\" \"colorteller-vn\" \"colorteller\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs.json\" \"colorteller.${SERVICES_DOMAIN}\"\n\n        create_vnode \"${TEST_MESH_DIR}/foodteller-vn.json\" \"foodteller-vn\" \"foodteller\"\n        create_vrouter \"${TEST_MESH_DIR}/foodteller-vr.json\" \"foodteller-vr\"\n        create_vservice \"${TEST_MESH_DIR}/foodteller-vs.json\" \"foodteller.${SERVICES_DOMAIN}\"\n        create_route \"${TEST_MESH_DIR}/fruit-route.json\" \"foodteller-vr\" \"fruit-route\"\n        create_route \"${TEST_MESH_DIR}/vegetable-route.json\" \"foodteller-vr\" \"vegetable-route\"\n\n        create_vgateway \"${TEST_MESH_DIR}/tellergateway-vg.json\" \"tellergateway-vg\"\n        create_gateway_route \"${TEST_MESH_DIR}/color-gateway-route.json\" \"tellergateway-vg\" \"color-gateway-route\" \"colorteller.${SERVICES_DOMAIN}\"\n        create_gateway_route \"${TEST_MESH_DIR}/fruit-gateway-route.json\" \"tellergateway-vg\" \"fruit-gateway-route\" \"foodteller.${SERVICES_DOMAIN}\"\n        create_gateway_route \"${TEST_MESH_DIR}/vegetable-gateway-route.json\" \"tellergateway-vg\" \"vegetable-gateway-route\" \"foodteller.${SERVICES_DOMAIN}\"\n        ;;\n\n    down)\n        delete_gateway_route \"tellergateway-vg\" \"vegetable-gateway-route\"\n        delete_gateway_route \"tellergateway-vg\" \"fruit-gateway-route\"\n        delete_gateway_route \"tellergateway-vg\" \"color-gateway-route\"\n        delete_vgateway \"tellergateway-vg\"\n\n        delete_route \"foodteller-vr\" \"vegetable-route\"\n        delete_route \"foodteller-vr\" \"fruit-route\"\n        delete_vservice \"foodteller.${SERVICES_DOMAIN}\"\n        delete_vrouter \"foodteller-vr\"\n        delete_vnode \"foodteller-vn\"\n\n        delete_vservice \"colorteller.${SERVICES_DOMAIN}\"\n        delete_vnode \"colorteller-vn\"\n\n        delete_mesh\n        ;;\n\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 294}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $TELLER_IMAGE_NAME ]; then\n    echo \"TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${TELLER_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n# login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n         docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 29}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    ColorTellerEnvoyImageName=\"${ENVOY_IMAGE_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImageName=\"${ENVOY_IMAGE_NAME}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n\n", "num_lines": 19}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nshopt -s nullglob\nset -eo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    cli_input=$( jq -n \\\n        --arg SERVICES_DOMAIN $SERVICES_DOMAIN \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    gateway_san=$3\n    cli_input=$( jq -n \\\n        --arg SERVICES_DOMAIN $SERVICES_DOMAIN \\\n        --arg GATEWAY_SAN $gateway_san \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    gateway_name=$2\n    cli_input=$( jq -n \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vgateway() {\n    spec_file=$1\n    gateway_name=$2\n    backend_san=$3\n    cli_input=$( jq -n \\\n        --arg COLOR_TELLER_SAN $backend_san \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-gateway --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    gateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gwroute() {\n    spec_file=$1\n    route_name=$2\n    gateway_name=$3\n    vservice_name=$4\n    cli_input=$( jq -n \\\n        --arg VIRTUAL_SERVICE $vservice_name \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route --mesh-name \"${MESH_NAME}\" \\\n                --gateway-route-name \"${route_name}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_gwroute() {\n    spec_file=$1\n    route_name=$2\n    gateway_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUAL_SERVICE $service_name \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-gateway-route --mesh-name \"${MESH_NAME}\" \\\n                --gateway-route-name \"${route_name}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to update virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gwroute() {\n    route_name=$1\n    gateway_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${gateway_name}\" \\\n                --gateway-route-name \"${route_name}\" \\\n                ${PROFILE_OPT} \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n        create_vnode \"${TEST_MESH_DIR}/colorteller-vn.json\" \"colorteller-vn\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs.json\" \"colorteller.${SERVICES_DOMAIN}\"\n        create_vgateway \"${TEST_MESH_DIR}/gateway-vgw.json\" \"gateway-vgw\"\n        create_gwroute \"${TEST_MESH_DIR}/colorteller-gwroute.json\" \"colorteller-route\" \"gateway-vgw\" \"colorteller.${SERVICES_DOMAIN}\"\n        ;;\n    down)\n        delete_gwroute \"colorteller-route\" \"gateway-vgw\"\n        delete_vgateway \"gateway-vgw\"\n        delete_vservice \"colorteller.${SERVICES_DOMAIN}\"\n        delete_vnode \"colorteller-vn\"\n        delete_mesh\n        ;;\n    update_1_strict_tls)\n        update_vnode \"${TEST_MESH_DIR}/updates/colorteller-vn-strict-tls.json\" \"colorteller-vn\" \"gateway.$SERVICES_DOMAIN\"\n        ;;\n    update_2_client_policy_bad_san)\n        update_vgateway \"${TEST_MESH_DIR}/updates/gateway-vgw-client-policy.json\" \"gateway-vgw\" \"bogus.$SERVICES_DOMAIN\"\n        ;;\n    update_3_client_policy_good_san)\n        update_vgateway \"${TEST_MESH_DIR}/updates/gateway-vgw-client-policy.json\" \"gateway-vgw\" \"colorteller.$SERVICES_DOMAIN\"\n        ;;\n    update_4_require_client_cert)\n        update_vnode \"${TEST_MESH_DIR}/updates/colorteller-vn-strict-validation.json\" \"colorteller-vn\" \"gateway.$SERVICES_DOMAIN\"\n        ;;\n    update_5_client_cert)\n        update_vgateway \"${TEST_MESH_DIR}/updates/gateway-vgw-client-cert.json\" \"gateway-vgw\" \"colorteller.$SERVICES_DOMAIN\"\n        ;;\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 256}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# build and push\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\necr_login\ndocker push $IMAGE\n", "num_lines": 40}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_NAME ]; then\n    echo \"ENVOY_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nENVOY_REGISTRY_ID=840364872350\nDEMO_ECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${DEMO_ECR_URL}/${ENVOY_IMAGE_NAME}:latest\"\n\necr_login() {\n    REGISTRY_ID=$1\n\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n\tREGISTRY_URL=\"${REGISTRY_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${REGISTRY_URL}\n    else\n\t$(aws ecr get-login --no-include-email --registry-id ${REGISTRY_ID})\n    fi\n}\n\n# login to envoy registry for pull\necr_login $ENVOY_REGISTRY_ID\n\n# build and push\ndocker build -t $IMAGE $DIR \\\n    --build-arg ENVOY_IMAGE=$ENVOY_IMAGE \\\n    --build-arg AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION\necr_login $AWS_ACCOUNT_ID\ndocker push $IMAGE\n", "num_lines": 54}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# $1=Secret Name\ngetSecret() {\n    aws secretsmanager get-secret-value --secret-id $1 --region $AWS_DEFAULT_REGION | jq -r .SecretString > /keys/${1}.pem\n    echo \"Added $1 to container\"\n}\n\ngetCertificates() {\n    if [[ $CERTIFICATE_NAME = \"gateway\" ]];\n    then\n        getSecret \"ca_cert\"\n        getSecret \"gateway_key\"\n        getSecret \"gateway_cert_chain\"\n    fi\n    if [[ $CERTIFICATE_NAME = \"colorteller\" ]];\n    then\n        getSecret \"colorteller_key\"\n        getSecret \"colorteller_cert_chain\"\n        getSecret \"ca_cert\"\n    fi\n}\n\n# Get the appropriate certificates\ngetCertificates\n# Start Envoy\n/usr/bin/agent\n", "num_lines": 28}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\necho \"Generating CA certificate\"\ngenerate_ca ca\n\necho \"Generating gateway certificate\"\ngenerate_rsa_key gateway ca\ngenerate_x509_cert gateway ca\ngenerate_cert_chain gateway ca\n\necho \"Generating colorteller certificate\"\ngenerate_rsa_key colorteller ca\ngenerate_x509_cert colorteller ca\ngenerate_cert_chain colorteller ca\n\nrm $DIR/*.csr\nrm $DIR/*.srl\n", "num_lines": 53}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\nremoveSecret() {\n    aws secretsmanager delete-secret --secret-id $1 --force-delete-without-recovery\n}\n\n\nremoveSecret \"ca_cert\"\nremoveSecret \"gateway_cert\"\nremoveSecret \"gateway_key\"\nremoveSecret \"gateway_cert_chain\"\nremoveSecret \"colorteller_cert\"\nremoveSecret \"colorteller_key\"\nremoveSecret \"colorteller_cert_chain\"\nrm $DIR/*.pem\nrm $DIR/*.generated\n", "num_lines": 23}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\ndeploySecret() {\n    secret=`cat $DIR/$1.pem`\n    aws secretsmanager create-secret --name $1 --secret-string \"$secret\"\n}\n\n\nmain() {\n    deploySecret \"ca_cert\"\n    # deploySecret \"gateway_cert\"\n    deploySecret \"gateway_key\"\n    deploySecret \"gateway_cert_chain\"\n    # deploySecret \"colorteller_cert\"\n    deploySecret \"colorteller_key\"\n    deploySecret \"colorteller_cert_chain\"\n}\n\nmain $@\n", "num_lines": 26}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-acm\" \\\n    --capabilities CAPABILITY_IAM \\\n    --parameter-overrides \\\n    DomainName=\"${SERVICES_DOMAIN}\" \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    --template-file \"${DIR}/acmpca.yaml\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-deploy\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/deploy.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\\\n    DomainName=\"${SERVICES_DOMAIN}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    TlsState=$1 \\\n    EnvoyImageName=\"${ENVOY_IMAGE_NAME}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" ", "num_lines": 19}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    ColorTellerEnvoyImageName=\"${ENVOY_IMAGE_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImageName=\"${ENVOY_IMAGE_NAME}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n\n", "num_lines": 19}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-mesh\" \\\n    --capabilities CAPABILITY_IAM \\\n    --parameter-overrides \\\n    ServiceDomain=\"${SERVICES_DOMAIN}\" \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    MeshName=\"${MESH_NAME}\" \\\n    TlsState=$1 \\\n    --template-file \"${DIR}/mesh.yaml\"", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# build and push\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\necr_login\ndocker push $IMAGE\n", "num_lines": 41}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE_NAME ]; then\n    echo \"ENVOY_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nENVOY_REGISTRY_ID=840364872350\nDEMO_ECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${DEMO_ECR_URL}/${ENVOY_IMAGE_NAME}:latest\"\n\necr_login() {\n    REGISTRY_ID=$1\n\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n\tREGISTRY_URL=\"${REGISTRY_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${REGISTRY_URL}\n    else\n\t$(aws ecr get-login --no-include-email --registry-id ${REGISTRY_ID})\n    fi\n}\n\n# login to envoy registry for pull\necr_login $ENVOY_REGISTRY_ID\n\n# build and push\ndocker build -t $IMAGE $DIR \\\n    --build-arg ENVOY_IMAGE=$ENVOY_IMAGE \\\n    --build-arg AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION\necr_login $AWS_ACCOUNT_ID\ndocker push $IMAGE\n", "num_lines": 54}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -xe\n\nPASSPHRASE=`echo $CertSecret|jq -r '.Passphrase'`\nPASSPHRASE_B64=`echo -n $PASSPHRASE | base64`\n\n\n# -------- CollorGateway Cert ----------\necho $CertSecret|jq -r '.GatewayCertificate' > /keys/colorgateway_endpoint_cert.pem\necho $CertSecret|jq -r '.GatewayCertificateChain' > /keys/colorgateway_root_cert.pem\necho $CertSecret|jq -r '.GatewayPrivateKey' > /keys/colorgateway_endpoint_enc_pri_key.pem \n\ncat /keys/colorgateway_endpoint_cert.pem /keys/colorgateway_root_cert.pem > /keys/colorgateway_endpoint_cert_chain.pem\nopenssl rsa -in /keys/colorgateway_endpoint_enc_pri_key.pem -out /keys/colorgateway_endpoint_dec_pri_key.pem -passin pass:$PASSPHRASE_B64\nopenssl rsa -in /keys/colorgateway_endpoint_dec_pri_key.pem -check\n\n# Clear environment of secret values\nunset CertSecret\nunset PASSPHRASE\nunset PASSPHRASE_B64\n\n# Start Envoy\n/usr/bin/agent\n", "num_lines": 25}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\n\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\nDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null && pwd)\"\nPROJECT_NAME=\"howto-outlier-detection\"\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nECR_IMAGE_PREFIX=${ECR_URL}/${PROJECT_NAME}\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\ndeploy_images() {\n    ecr_login\n    for app in color-app frontend-app; do\n        aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null\n        docker build --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"} -t ${ECR_IMAGE_PREFIX}/${app} ${DIR}/src/${app}\n        docker push ${ECR_IMAGE_PREFIX}/${app}\n    done\n}\n\ndeploy_infra() {\n    stack_name=\"${PROJECT_NAME}-infra\"\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name $stack_name\\\n        --template-file \"${DIR}/infrastructure.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\"\n}\n\ndeploy_app() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${PROJECT_NAME}-app\" \\\n        --template-file \"${DIR}/application.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"ProjectName=${PROJECT_NAME}\" \"EnvoyImage=${ENVOY_IMAGE}\" \\\n                              \"ColorAppImage=${ECR_IMAGE_PREFIX}/color-app\" \"FrontAppImage=${ECR_IMAGE_PREFIX}/frontend-app\" \\\n                              \"ColorNodeName=mesh/${PROJECT_NAME}/virtualNode/color-node\" \"FrontNodeName=mesh/${PROJECT_NAME}/virtualNode/front-node\" \\\n                              \"BastionKeyName=${KEY_PAIR_NAME}\"\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo 'Waiting for the stack to be deleted, this may take a few minutes...'\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_images() {\n    for app in color-app frontend-app; do\n        echo \"deleting repository...\"\n        aws ecr delete-repository \\\n           --repository-name $PROJECT_NAME/$app \\\n           --force >/dev/null\n    done\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] ||\n        (echo \"Error: no service linked role for App Mesh\" && exit 1)\n}\n\nprint_alb_endpoint() {\n    echo \"Public ALB endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[0].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\nprint_bastion_endpoint() {\n    echo \"Public bastion endpoint:\"\n    prefix=$(aws cloudformation describe-stacks \\\n        --stack-name=\"${PROJECT_NAME}-app\" \\\n        --query=\"Stacks[0].Outputs[1].OutputValue\" \\\n        --output=text)\n    echo \"${prefix}\"\n}\n\ndeploy_stacks() {\n\n    echo \"deploy images...\"\n    deploy_images\n\n    echo \"deploy infra...\"\n    deploy_infra\n\n    echo \"deploy app...\"\n    deploy_app\n\n    #confirm_service_linked_role\n    print_alb_endpoint\n    print_bastion_endpoint\n}\n\ndelete_stacks() {\n    echo \"delete app...\"\n    delete_cfn_stack \"${PROJECT_NAME}-app\"\n\n    echo \"delete infra...\"\n    delete_cfn_stack \"${PROJECT_NAME}-infra\"\n\n    echo \"delete images...\"\n    delete_images\n\n    echo \"all resources from this tutorial have been removed\"\n}\n\naction=${1}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\ndeploy_stacks\n", "num_lines": 144}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nMESH_DIR=\"${DIR}/mesh\"\nPROJECT_NAME=\"howto-outlier-detection\"\nMESH_NAME=$PROJECT_NAME\nCLOUDMAP_NAMESPACE_NAME=${PROJECT_NAME}.local\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    cli_input=$( jq -n \\\n        --arg NAMESPACE_NAME \"${CLOUDMAP_NAMESPACE_NAME}\" \\\n        --arg BACKEND_VS_NAME \"color.${CLOUDMAP_NAMESPACE_NAME}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    cli_input=$( jq -n \\\n        --arg NAMESPACE_NAME \"${CLOUDMAP_NAMESPACE_NAME}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cli_input=$( jq -n \\\n    --arg VIRTUAL_SERVICE_NAME \"${vservice_name}\" \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down|add-outlier-detection|remove-outlier-detection]\"\n    fi\n\n    case \"$action\" in\n    up)\n        create_mesh\n        create_vnode \"${MESH_DIR}/front-vn.json\"\n        create_vnode \"${MESH_DIR}/color-vn.json\"\n        create_vservice \"${MESH_DIR}/color-vs.json\" \"color.${PROJECT_NAME}.local\"\n        ;;\n    down)\n        delete_vservice \"color.${PROJECT_NAME}.local\"\n        delete_vnode \"color-node\"\n        delete_vnode \"front-node\"\n        delete_mesh\n        ;;\n    add-outlier-detection)\n        update_vnode \"${MESH_DIR}/color-vn-with-outlier-detection.json\"\n        ;;\n    remove-outlier-detection)\n        update_vnode \"${MESH_DIR}/color-vn.json\"\n        ;;\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 134}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAPP_DIR=\"${DIR}/../../examples/apps/colorapp\"\n\n${APP_DIR}/src/colorteller/deploy.sh\necho \"Done deploying color/teller docker image\"\n", "num_lines": 8}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set to App Mesh Envoy, see https://docs.aws.amazon.com/app-mesh/latest/userguide/envoy.html\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAPP_DIR=\"${DIR}/../../examples/apps/colorapp\"\nCOLOR_TELLER_IMAGE=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com/colorteller\n\ndeploy_vpc() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${RESOURCE_PREFIX}-vpc\" \\\n        --template-file \"${DIR}/vpc.yaml\" \\\n        --capabilities CAPABILITY_IAM\n}\n\ndeploy_mesh() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${RESOURCE_PREFIX}-mesh\" \\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --capabilities CAPABILITY_IAM\n}\n\ndeploy_app() {\n    aws cloudformation deploy \\\n        --no-fail-on-empty-changeset \\\n        --stack-name \"${RESOURCE_PREFIX}\" \\\n        --template-file \"${DIR}/app.yaml\" \\\n        --capabilities CAPABILITY_IAM \\\n        --parameter-overrides \"EnvoyImage=${ENVOY_IMAGE}\" \"ColorTellerImage=${COLOR_TELLER_IMAGE}\"\n}\n\nconfirm_service_linked_role() {\n    aws iam get-role --role-name AWSServiceRoleForAppMesh >/dev/null\n    [[ $? -eq 0 ]] \\\n        || ( echo \"Error: no service linked role for App Mesh\" && exit 1 )\n}\n\nprint_endpoint() {\n    echo \"Public endpoint:\"\n    prefix=$( aws cloudformation describe-stacks \\\n        --stack-name=\"${RESOURCE_PREFIX}\" \\\n        --query=\"Stacks[0].Outputs[?OutputKey=='ColorGatewayEndpoint'].OutputValue\" \\\n        --output=text )\n    echo \"${prefix}/color\"\n}\n\nmain() {\n    echo \"deploy vpc...\"\n    deploy_vpc\n\n    echo \"deploy mesh...\"\n    deploy_mesh\n\n    echo \"deploy app...\"\n    deploy_app\n\n    confirm_service_linked_role\n    print_endpoint\n}\n\ndelete_cfn_stack() {\n    stack_name=$1\n    echo \"Deleting Cloud Formation stack: \\\"${stack_name}\\\"...\"\n    aws cloudformation delete-stack --stack-name $stack_name\n    echo \"Waiting for the stack $stack_name to be deleted, this may take a few minutes...\"\n    aws cloudformation wait stack-delete-complete --stack-name $stack_name\n    echo 'Done'\n}\n\ndelete_stacks() {\n    echo \"delete stack ${RESOURCE_PREFIX}...\"\n    delete_cfn_stack ${RESOURCE_PREFIX}\n    echo \"delete stack ${RESOURCE_PREFIX}-mesh...\"\n    delete_cfn_stack ${RESOURCE_PREFIX}-mesh\n    echo \"delete stack ${RESOURCE_PREFIX}-vpc...\"\n    delete_cfn_stack ${RESOURCE_PREFIX}-vpc\n}\n\naction=${1:-\"deploy\"}\nif [ \"$action\" == \"delete\" ]; then\n    delete_stacks\n    exit 0\nfi\n\nmain $@\n", "num_lines": 103}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    GatewayImageName=\"${COLOR_GATEWAY_IMAGE_NAME}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorGatewayImageName=\"${COLOR_GATEWAY_IMAGE_NAME}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nshopt -s nullglob\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nprint() {\n    printf \"[$(date)] : %s\\n\" \"$*\"\n}\n\nerr() {\n    msg=\"Error: $1\"\n    print \"${msg}\"\n    code=${2:-\"1\"}\n    exit ${code}\n}\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n}\n\nappmesh_cmd=\"aws appmesh\"\n\ncreate_mesh() {\n    spec_file=$1\n    cmd=( $appmesh_cmd create-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_mesh() {\n    cmd=( $appmesh_cmd delete-mesh --mesh-name \"${MESH_NAME}\" \\\n                ${PROFILE_OPT} \\\n                --query mesh.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete mesh\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg ROOT_CA_ARN \"${ROOT_CA_ARN}\" \\\n        --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        --arg COLOR_TELLER_VS \"colorteller.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\nupdate_vnode() {\n    spec_file=$1\n    vnode_name=$2\n    dns_hostname=\"$3.${SERVICES_DOMAIN}\"\n    cli_input=$( jq -n \\\n        --arg ROOT_CA_ARN \"${ROOT_CA_ARN}\" \\\n        --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n        --arg DNS_HOSTNAME \"$3.${SERVICES_DOMAIN}\" \\\n        --arg COLOR_TELLER_VS \"colorteller.${SERVICES_DOMAIN}\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd update-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vnode() {\n    vnode_name=$1\n    cmd=( $appmesh_cmd delete-virtual-node --mesh-name \"${MESH_NAME}\" \\\n                --virtual-node-name \"${vnode_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualNode.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual node\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vservice() {\n    spec_file=$1\n    vservice_name=$2\n    cmd=( $appmesh_cmd create-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vservice() {\n    vservice_name=$1\n    cmd=( $appmesh_cmd delete-virtual-service --mesh-name \"${MESH_NAME}\" \\\n                --virtual-service-name \"${vservice_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualService.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual service\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vrouter() {\n    spec_file=$1\n    vrouter_name=$2\n    cmd=( $appmesh_cmd create-virtual-router --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vrouter() {\n    vrouter_name=$1\n    cmd=( $appmesh_cmd delete-virtual-router --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                ${PROFILE_OPT} \\\n                --query virtualRouter.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual router\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_route() {\n    spec_file=$1\n    vrouter_name=$2\n    route_name=$3\n    cmd=( $appmesh_cmd create-route --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                ${PROFILE_OPT} \\\n                --cli-input-json \"file:///${spec_file}\" \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_route() {\n    vrouter_name=$1\n    route_name=$2\n    cmd=( $appmesh_cmd delete-route --mesh-name \"${MESH_NAME}\" \\\n                --virtual-router-name \"${vrouter_name}\" \\\n                --route-name \"${route_name}\" \\\n                ${PROFILE_OPT} \\\n                --query route.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_vgateway() {\n    spec_file=$1\n    vgateway_name=$2\n    cli_input=$( jq -n \\\n    --arg CERTIFICATE_ARN \"${CERTIFICATE_ARN}\" \\\n    -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_vgateway() {\n    vgateway_name=$1\n    cmd=( $appmesh_cmd delete-virtual-gateway \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --query virtualGateway.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete virtual gateway\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ncreate_gateway_route() {\n    spec_file=$1\n    vgateway_name=$2\n    gatewayroute_name=$3\n    cli_input=$( jq -n \\\n        --arg VIRTUALSERVICE_NAME \"$4\" \\\n        -f \"$spec_file\" )\n    cmd=( $appmesh_cmd create-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --cli-input-json \"$cli_input\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to create gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\ndelete_gateway_route() {\n    vgateway_name=$1\n    gatewayroute_name=$2\n    cmd=( $appmesh_cmd delete-gateway-route \\\n                --mesh-name \"${MESH_NAME}\" \\\n                --virtual-gateway-name \"${vgateway_name}\" \\\n                --gateway-route-name \"${gatewayroute_name}\" \\\n                --query gatewayRoute.metadata.uid --output text )\n    print \"${cmd[@]}\"\n    uid=$(\"${cmd[@]}\") || err \"Unable to delete gateway route\" \"$?\"\n    print \"--> ${uid}\"\n}\n\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|down]\"\n    fi\n    sanity_check\n\n    case \"$action\" in\n    up)\n        create_mesh \"${TEST_MESH_DIR}/mesh.json\"\n        create_vnode \"${TEST_MESH_DIR}/colorgateway-vn.json\" \"ColorGateway\" \"colorgateway\"\n        create_vnode \"${TEST_MESH_DIR}/colorteller-vn.json\" \"ColorTellerWhite\" \"colorteller\"\n\n        create_vrouter \"${TEST_MESH_DIR}/colorteller-vr.json\" \"colorteller-vr\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route.json\" \"colorteller-vr\" \"colorteller-route\"\n        create_vservice \"${TEST_MESH_DIR}/colorteller-vs.json\" \"colorteller.${SERVICES_DOMAIN}\"\n\n        ;;\n    down)\n        delete_vservice \"colorteller.${SERVICES_DOMAIN}\"\n        delete_route \"colorteller-vr\" \"colorteller-route\"\n        delete_vrouter \"colorteller-vr\"\n        delete_vnode \"ColorGateway\"\n        delete_vnode \"ColorTellerWhite\"\n        delete_mesh\n        ;;\n    add_virtual_gateway)\n        create_vgateway \"${TEST_MESH_DIR}/publicgateway-vg.json\" \"publicgateway-vg\"\n        create_gateway_route \"${TEST_MESH_DIR}/publicgateway-route.json\" \"publicgateway-vg\" \"publicgateway-route\" \"colorteller.${SERVICES_DOMAIN}\"   \n        ;;\n    add_red_node_and_routes)\n        create_vnode \"${TEST_MESH_DIR}/colorteller-vn.json\" \"ColorTellerRed\" \"colorteller-red\"\n        delete_route \"colorteller-vr\" \"colorteller-route\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route1.json\" \"colorteller-vr\" \"colorteller-route\"\n        create_route \"${TEST_MESH_DIR}/colorteller-route2.json\" \"colorteller-vr\" \"colorteller-route2\"       \n        ;;\n    delete_virtual_gateway_and_red_node_and_routes)\n        delete_gateway_route \"publicgateway-vg\" \"publicgateway-route\"\n        delete_vgateway \"publicgateway-vg\"\n        delete_route \"colorteller-vr\" \"colorteller-route2\"\n        delete_vnode \"ColorTellerRed\"\n        ;;\n    update_colorteller-white-vn)\n        update_vnode \"$2\" \"ColorTellerWhite\" \"colorteller\"\n        ;;\n    update_colorteller-red-vn)\n        update_vnode \"$2\" \"ColorTellerRed\" \"colorteller-red\"\n        ;;\n    update_colorgateway-vn)\n        update_vnode \"$2\" \"ColorGateway\" \"colorgateway\"\n        ;;\n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 293}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_GATEWAY_IMAGE_NAME ]; then\n    echo \"COLOR_GATEWAY_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n\nIMAGE=\"${ECR_URL}/${COLOR_GATEWAY_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n\n# ECR login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n        docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n\n", "num_lines": 34}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\n# build\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\n\n\n# ECR login\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nif [ $AWS_CLI_VERSION -gt 1 ]; then\n    aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n        docker login --username AWS --password-stdin ${ECR_URL}\nelse\n    $(aws ecr get-login --no-include-email)\nfi\n\n# push\ndocker push $IMAGE\n", "num_lines": 33}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    ColorAppEnvoyImageName=\"${COLOR_APP_ENVOY_IMAGE_NAME}\"\n", "num_lines": 15}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\" \\\n    ColorAppEnvoyImageName=\"${COLOR_APP_ENVOY_IMAGE_NAME}\"\n\n", "num_lines": 20}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nTEST_MESH_DIR=\"${DIR}\"\n\nsanity_check() {\n    if [ -z \"${MESH_NAME}\" ]; then\n        err \"MESH_NAME is not set\"\n    fi\n    if [ -z \"${ENVIRONMENT_NAME}\" ]; then\n        err \"ENVIRONMENT_NAME is not set\"\n    fi\n    if [ -z \"${SERVICES_DOMAIN}\" ]; then\n        err \"SERVICES_DOMAIN is not set\"\n    fi\n    if [ -z \"${AWS_DEFAULT_REGION}\" ]; then\n        err \"AWS_DEFAULT_REGION is not set\"\n    fi\n}\n\n\n# $1 ColorTellerGreenRouteWeight\n# $2 EnableClientValidationFlag\n# $3 ColorGatewayTlsValidationPath\ncallCloudformation() {\n    aws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n        cloudformation deploy \\\n        --stack-name \"${ENVIRONMENT_NAME}-mesh\" \\\n        --capabilities CAPABILITY_IAM \\\n        --template-file \"${DIR}/mesh.yaml\" \\\n        --parameter-overrides \\\n        MeshName=\"${MESH_NAME}\" \\\n        ServicesDomain=\"${SERVICES_DOMAIN}\" \\\n        ColorTellerGreenRouteWeight=$1 \\\n        EnableClientValidationFlag=$2 \\\n        ColorGatewayTlsValidationPath=$3\n}\n\n\nmain() {\n    action=\"$1\"\n    if [ -z \"$action\" ]; then\n        echo \"Usage:\"\n        echo \"mesh.sh [up|addGreen|updateGateway|updateGateway2]\"\n    fi\n    sanity_check\n\n    case \"$action\" in\n    up)\n        callCloudformation 0 \"false\"\n        ;;\n    addGreen)\n        callCloudformation 1 \"false\"\n        ;;\n    updateGateway)\n        callCloudformation 1 \"true\" \"/keys/ca_1_cert.pem\"\n        ;;\n    updateGateway2)\n        callCloudformation 1 \"true\" \"/keys/ca_1_ca_2_bundle.pem\"\n        ;;    \n    *)\n        err \"Invalid action specified: $action\"\n        ;;\n    esac\n}\n\nmain $@\n", "num_lines": 70}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# build and push\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\necr_login\ndocker push $IMAGE\n", "num_lines": 40}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $COLOR_APP_ENVOY_IMAGE_NAME ]; then\n    echo \"COLOR_APP_ENVOY_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $ENVOY_IMAGE ]; then\n    echo \"ENVOY_IMAGE environment variable is not set\"\n    exit 1\nfi\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nENVOY_REGISTRY_ID=840364872350\nDEMO_ECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${DEMO_ECR_URL}/${COLOR_APP_ENVOY_IMAGE_NAME}:latest\"\n\necr_login() {\n    REGISTRY_ID=$1\n\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n\tREGISTRY_URL=\"${REGISTRY_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${REGISTRY_URL}\n    else\n\t$(aws ecr get-login --no-include-email --registry-id ${REGISTRY_ID})\n    fi\n}\n\n# login to envoy registry for pull\necr_login $ENVOY_REGISTRY_ID\n\n# build and push\ndocker build -t $IMAGE $DIR \\\n    --build-arg ENVOY_IMAGE=$ENVOY_IMAGE \\\n    --build-arg AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION\necr_login $AWS_ACCOUNT_ID\ndocker push $IMAGE\n", "num_lines": 54}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# $1=Secret Name\ngetSecret() {\n    aws secretsmanager get-secret-value --secret-id $1 --region $AWS_DEFAULT_REGION | jq -r .SecretString > /keys/${1}.pem\n    echo \"Added $1 to container\"\n}\n\ngetCertificates() {\n    if [[ $CERTIFICATE_NAME = \"colorgateway\" ]];\n    then\n        getSecret \"ca_1_cert\"\n        getSecret \"ca_2_cert\"\n        getSecret \"ca_1_ca_2_bundle\"\n    fi\n    if [[ $CERTIFICATE_NAME = \"colorteller_green\" ]];\n    then\n        getSecret \"colorteller_green_cert\"\n        getSecret \"colorteller_green_key\"\n        getSecret \"colorteller_green_cert_chain\"\n    fi\n    if [[ $CERTIFICATE_NAME = \"colorteller_white\" ]];\n    then\n        getSecret \"colorteller_white_cert\"\n        getSecret \"colorteller_white_key\"\n        getSecret \"colorteller_white_cert_chain\"\n    fi\n}\n\n# Get the appropriate certificates\ngetCertificates\n# Start Envoy\n/usr/bin/agent\n", "num_lines": 34}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n# $1=<CA name>\ngenerate_ca() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -signkey $DIR/$1_key.pem -out $DIR/$1_cert.pem \\\n    -extensions v3_ca -extfile $DIR/$1_cert.cfg\n}\n\n# $1=<certificate name>\ngenerate_rsa_key() {\n  openssl genrsa -out $DIR/$1_key.pem 2048\n}\n\n# $1=<certificate_name>\ngenerate_cert_config() {\n  sed -e \"s/\\${services_domain}/${SERVICES_DOMAIN}/\" $DIR/$1_cert.cfg > $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_x509_cert() {\n  generate_cert_config $1\n  openssl req -new -key $DIR/$1_key.pem -out $DIR/$1_cert.csr -config $DIR/$1_cert.cfg.generated -batch -sha256\n  openssl x509 -req -days 3650 -in $DIR/$1_cert.csr -sha256 -CA $DIR/$2_cert.pem -CAkey \\\n    $DIR/$2_key.pem -CAcreateserial -out $DIR/$1_cert.pem -extensions v3_req -extfile $DIR/$1_cert.cfg.generated\n}\n\n# $1=<certificate name> $2=<CA name>\ngenerate_cert_chain() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_cert_chain.pem\n}\n\n# $1=<CA name> $2=<CA name>\ngenerate_cert_bundle() {\n  cat $DIR/$1_cert.pem $DIR/$2_cert.pem > $DIR/$1_$2_bundle.pem\n}\n\n# Generate cert for the CA.\necho \"Generating CA certificates.\"\ngenerate_ca ca_1\ngenerate_ca ca_2\n\n# Generate RSA cert for the white color teller.\necho \"Generating backend certificate.\"\ngenerate_rsa_key colorteller_white ca_1\ngenerate_x509_cert colorteller_white ca_1\ngenerate_cert_chain colorteller_white ca_1\n\n# Generate cert for the green color teller.\necho \"Generating frontend certificate.\"\ngenerate_rsa_key colorteller_green ca_2\ngenerate_x509_cert colorteller_green ca_2\ngenerate_cert_chain colorteller_green ca_2\n\necho \"Generating CA Bundle\"\ngenerate_cert_bundle ca_1 ca_2\n\nrm $DIR/*.csr\nrm $DIR/*.srl\n", "num_lines": 65}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\nremoveSecret() {\n    aws secretsmanager delete-secret --secret-id $1 --force-delete-without-recovery\n}\n\n\nmain() {\n    # Color Gateway\n    removeSecret \"ca_1_cert\"\n    removeSecret \"ca_2_cert\"\n    removeSecret \"ca_1_ca_2_bundle\"\n    # White Colorteller\n    removeSecret \"colorteller_white_cert\"\n    removeSecret \"colorteller_white_key\"\n    removeSecret \"colorteller_white_cert_chain\"\n    # Green Colorteller\n    removeSecret \"colorteller_green_cert\"\n    removeSecret \"colorteller_green_key\"\n    removeSecret \"colorteller_green_cert_chain\"\n    rm $DIR/*.pem\n    rm $DIR/*.generated\n}\n\nmain $@\n", "num_lines": 32}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\n\n# $1= Certificate Name\ndeploySecret() {\n    secret=`cat $DIR/$1.pem`\n    aws secretsmanager create-secret --name $1 --secret-string \"$secret\"\n}\n\n\nmain() {\n    # Color Gateway\n    deploySecret \"ca_1_cert\"\n    deploySecret \"ca_2_cert\"\n    deploySecret \"ca_1_ca_2_bundle\"\n    # White Colorteller\n    deploySecret \"colorteller_white_cert\"\n    deploySecret \"colorteller_white_key\"\n    deploySecret \"colorteller_white_cert_chain\"\n    # Green Colorteller\n    deploySecret \"colorteller_green_cert\"\n    deploySecret \"colorteller_green_key\"\n    deploySecret \"colorteller_green_cert_chain\"\n}\n\nmain $@\n", "num_lines": 31}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecr-repositories\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecr-repositories.yaml\" \\\n    --parameter-overrides \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex \n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-cluster\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-cluster.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    KeyName=\"${KEY_PAIR_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\"\n", "num_lines": 16}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-ecs-service\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/ecs-service.yaml\"  \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\" \\\n    ECSServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    AppMeshMeshName=\"${MESH_NAME}\" \\\n    EnvoyImage=\"${ENVOY_IMAGE}\" \\\n    ColorTellerImageName=\"${COLOR_TELLER_IMAGE_NAME}\"\n", "num_lines": 18}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-vpc\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/vpc.yaml\" \\\n    --parameter-overrides \\\n    EnvironmentName=\"${ENVIRONMENT_NAME}\"\n", "num_lines": 14}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\n\naws --profile \"${AWS_PROFILE}\" --region \"${AWS_DEFAULT_REGION}\" \\\n    cloudformation deploy \\\n    --stack-name \"${ENVIRONMENT_NAME}-mesh\" \\\n    --capabilities CAPABILITY_IAM \\\n    --template-file \"${DIR}/mesh.yaml\" \\\n    --parameter-overrides \\\n    MeshName=\"${MESH_NAME}\" \\\n    ServicesDomain=\"${SERVICES_DOMAIN}\" \\\n    CertificateAuthorityArn=\"${ROOT_CA_ARN}\" \\\n    CertificateArn=\"${CERTIFICATE_ARN}\"\n", "num_lines": 17}
{"repo_name": "aws-app-mesh-examples", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# vim:syn=sh:ts=4:sw=4:et:ai\n\nset -ex\n\nif [ -z $COLOR_TELLER_IMAGE_NAME ]; then\n    echo \"COLOR_TELLER_IMAGE_NAME environment variable is not set\"\n    exit 1\nfi\n\nif [ -z $AWS_ACCOUNT_ID ]; then\n    echo \"AWS_ACCOUNT_ID environment variable is not set.\"\n    exit 1\nfi\n\nif [ -z $AWS_DEFAULT_REGION ]; then\n    echo \"AWS_DEFAULT_REGION environment variable is not set.\"\n    exit 1\nfi\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null && pwd )\"\nAWS_CLI_VERSION=$(aws --version 2>&1 | cut -d/ -f2 | cut -d. -f1)\n\nECR_URL=\"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_DEFAULT_REGION}.amazonaws.com\"\nIMAGE=\"${ECR_URL}/${COLOR_TELLER_IMAGE_NAME}:latest\"\n\necr_login() {\n    if [ $AWS_CLI_VERSION -gt 1 ]; then\n        aws ecr get-login-password --region ${AWS_DEFAULT_REGION} | \\\n            docker login --username AWS --password-stdin ${ECR_URL}\n    else\n        $(aws ecr get-login --no-include-email)\n    fi\n}\n\n# build and push\ndocker build -t $IMAGE $DIR --build-arg GO_PROXY=${GO_PROXY:-\"https://proxy.golang.org\"}\necr_login\ndocker push $IMAGE\n", "num_lines": 41}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nSDK_VENDOR_PATH=\"./scripts/aws_sdk_model_override/aws-sdk-go\"\nSDK_MODEL_OVERRIDE_DST_PATH=\"${SDK_VENDOR_PATH}/models\"\nSDK_MODEL_OVERRIDE_SRC_PATH=\"./scripts/aws_sdk_model_override/models\"\n\n# Clone the SDK to the vendor path (removing an old one if necessary)\nrm -rf \"${SDK_VENDOR_PATH}\"\ngit clone --depth 1 https://github.com/aws/aws-sdk-go.git \"${SDK_VENDOR_PATH}\"\n\n# Override the SDK models\ncp -r \"${SDK_MODEL_OVERRIDE_SRC_PATH}\"/* \"${SDK_MODEL_OVERRIDE_DST_PATH}\"/.\n\n# Generate the SDK\npushd \"${SDK_VENDOR_PATH}\"\nmake generate\npopd\n\n# Use the vendored version of aws-sdk-go\ngo mod edit -replace github.com/aws/aws-sdk-go=\"${SDK_VENDOR_PATH}\"\n", "num_lines": 23}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nK8S_VERSION=\"${K8S_VERSION:=\"1.22.x\"}\"\nKUBEBUILDER_ASSETS=\"${KUBEBUILDER_ASSETS:=\"${HOME}/.kubebuilder/bin\"}\"\n\nmain() {\n    tools\n    kubebuilder\n}\n\ntools() {\n    if ! echo \"$PATH\" | grep -q \"${GOPATH:-undefined}/bin\\|$HOME/go/bin\"; then\n        echo \"Go workspace's \\\"bin\\\" directory is not in PATH. Run 'export PATH=\\\"\\$PATH:\\${GOPATH:-\\$HOME/go}/bin\\\"'.\"\n        exit 1\n    fi\n\n    go install github.com/golang/mock/mockgen@v1.6.0\n    go install sigs.k8s.io/kustomize/kustomize/v4@v4.5.7\n    go install sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.0.0-20220421205612-c162794a9b12\n}\n\nkubebuilder() {\n    mkdir -p $KUBEBUILDER_ASSETS\n    arch=$(go env GOARCH)\n    ## Kubebuilder does not support darwin/arm64, so use amd64 through Rosetta instead\n    if [[ $(go env GOOS) == \"darwin\" ]] && [[ $(go env GOARCH) == \"arm64\" ]]; then\n        arch=\"amd64\"\n    fi\n    ln -sf $(setup-envtest use -p path \"${K8S_VERSION}\" --arch=\"${arch}\" --bin-dir=\"${KUBEBUILDER_ASSETS}\")/* ${KUBEBUILDER_ASSETS}\n    find $KUBEBUILDER_ASSETS\n}\n\nmain \"$@\"\n", "num_lines": 35}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "## Note: mocks for interfaces from this project should be along with the original package.\n##       mocks for interfaces from 3rd-party project should be put inside ./mocks folder.\n## mockgen version v1.5.0\nmockgen -package=mock_client -destination=./mocks/controller-runtime/client/client_mocks.go sigs.k8s.io/controller-runtime/pkg/client Client\nmockgen -package=services -destination=./pkg/aws/services/eks_mocks.go -source=./pkg/aws/services/eks.go\nmockgen -package=services -destination=./pkg/aws/services/vpclattice_mocks.go -source=./pkg/aws/services/vpclattice.go\nmockgen -package=aws -destination=./pkg/aws/cloud_mocks.go -source=./pkg/aws/cloud.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/service_network_manager_mock.go -source=./pkg/deploy/lattice/service_network_manager.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/target_group_manager_mock.go -source=./pkg/deploy/lattice/target_group_manager.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/targets_manager_mock.go -source=./pkg/deploy/lattice/targets_manager.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/service_manager_mock.go -source=./pkg/deploy/lattice/service_manager.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/listener_manager_mock.go -source=./pkg/deploy/lattice/listener_manager.go\nmockgen -package=lattice -destination=./pkg/deploy/lattice/rule_manager_mock.go -source=./pkg/deploy/lattice/rule_manager.go\n# need some manual update to remote core for stack_mock.go\nmockgen -package=core -destination=./pkg/model/core/stack_mock.go -source=./pkg/model/core/stack.go\nmockgen -package=services -destination=./pkg/aws/services/vpclattice_service_api_mock.go -source=./scripts/aws_sdk_model_override/aws-sdk-go/service/vpclattice/vpclatticeiface/interface.go\n", "num_lines": 17}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# When Running the k8s Controller by GoLand IDE locally, it is required to set the environment variables, this script will generate a file called `envFile`\n# that contains all needed environment variables, this `envFile` file can be use by GoLand \"EnvFile\" plugin\n# When config the \"green arrow\"(how we `run` or `debug` this project) in  GoLand, we could set a \"before launch\" task to run this script `load_env_variables.sh`, and set the \"EnvFile\" plugin to load the `envFile` file\n# \"EnvFile\" is a plugin, you can install it from GoLand plugin marketplace\n\necho \"Setting environment variables\"\n\n> envFile\n\n# Set KUBEBUILDER_ASSETS if not set\nif [ -z \"$KUBEBUILDER_ASSETS\" ]; then\n  KUBEBUILDER_ASSETS=${HOME}/.kubebuilder/bin\nfi\necho \"KUBEBUILDER_ASSETS=$KUBEBUILDER_ASSETS\" >> envFile\n\n\n# Set CLUSTER_NAME if not set\nif [ -z \"$CLUSTER_NAME\" ]; then\n  CLUSTER_NAME=$(kubectl config view --minify -o jsonpath='{.clusters[].name}' | rev | cut -d\"/\" -f1 | rev | cut -d\".\" -f1)\nfi\necho \"CLUSTER_NAME=$CLUSTER_NAME\" >> envFile\n\n\n# Set CLUSTER_VPC_ID if not set\nif [ -z \"$CLUSTER_VPC_ID\" ]; then\n  CLUSTER_VPC_ID=$(aws eks describe-cluster --name ${CLUSTER_NAME} | jq -r \".cluster.resourcesVpcConfig.vpcId\")\nfi\necho \"CLUSTER_VPC_ID=$CLUSTER_VPC_ID\" >> envFile\n\n# Set AWS_ACCOUNT_ID if not set\nif [ -z \"$AWS_ACCOUNT_ID\" ]; then\n  AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\nfi\necho \"AWS_ACCOUNT_ID=$AWS_ACCOUNT_ID\" >> envFile\n\nif [ -z \"$REGION\" ]; then\n  REGION=us-west-2\nfi\necho \"REGION=$REGION\" >> envFile\n\n\nGATEWAY_API_CONTROLLER_LOGLEVEL=debug\necho \"GATEWAY_API_CONTROLLER_LOGLEVEL=$GATEWAY_API_CONTROLLER_LOGLEVEL\" >> envFile\n\n", "num_lines": 47}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eo pipefail\n\nDEFAULT_IMAGE_REPOSITORY=\"public.ecr.aws/aws-application-networking-k8s/aws-gateway-controller\"\nDEFAULT_CHART_REGISTRY=\"public.ecr.aws/aws-application-networking-k8s\"\nDEFAULT_CHART_REPOSITORY=\"aws-gateway-controller-chart\"\n\nUSAGE=\"\nUsage:\n  $(basename \"$0\")\n\nPublishes the controller image and helm chart for the AWS Gateway controller.\n\nWhen run as part of a CI job, when the source code repo is tagged with a semver\nformat '^v\\d+\\.\\d+\\.\\d+$'\n\nEnvironment variables:\n  SKIP_BUILD_IMAGE:         If set to 1, does not build and publish the\n                            controller container image, only the Helm chart.\n  PULL_BASE_REF:            The value of tag on the source code repository that triggered the\n                            postsubmit CI job. The value will either be in the format '^v\\d+\\.\\d+\\.\\d+$'\n                            or 'stable'.\n  IMAGE_REPOSITORY:         Name for the ECR Public repository to push controller images to\n                            Default: $DEFAULT_IMAGE_REPOSITORY\n  IMAGE_TAG:                Controller container image tag\n                            Default: \\$PULL_BASE_REF\n  QUIET:                    Build controller container image quietly (<true|false>)\n                            Default: false\n  CHART_REGISTRY:           Name for the OCI Artifact Registry to push to\n                            Default: $DEFAULT_CHART_REGISTRY\n  CHART_REPOSITORY:         Name for the Helm repository to push to\n                            Default: $DEFAULT_CHART_REPOSITORY\n  CHART_TAG:                Controller Helm Chart tag\n                            Default: Based on \\$PULL_BASE_REF\n  ECR_PUBLISH_ROLE_ARN      IAM Role ARN for the Role that has permission to\n                            publish to the image and Helm chart repositories on ECR Public. This role is\n                            assumed by this script in order to upload artifacts.\n\"\n\n# find out the service name and semver tag from the CI environment variable if not specified \nVERSION=${VERSION:-$PULL_BASE_REF}\n\n# Important Directory references based on prowjob configuration.\nSCRIPTS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nWORKSPACE_DIR=$SCRIPTS_DIR/..\n\n# Check all the dependencies are present in container.\nsource \"$SCRIPTS_DIR/lib/common.sh\"\nsource \"$SCRIPTS_DIR/lib/login.sh\"\ncheck_is_installed git\ncheck_is_installed jq\ncheck_is_installed yq\n\nif [[ $PULL_BASE_REF = stable ]]; then\n  pushd $WORKSPACE_DIR 1>/dev/null\n  echo \"Triggering for the stable branch\"\n  _semver_tag=$(git describe --tags --abbrev=0 2>/dev/null)\n  if [[ $? -ne 0 ]]; then\n    echo \"Unable to find semver tag on the 'stable' branch\"\n    exit 2\n  fi\n  echo \"Semver tag on stable branch is $_semver_tag\"\n\n  if ! (echo \"$_semver_tag\" | grep -Eq \"^v[0-9]+\\.[0-9]+\\.[0-9]+$\"); then\n    echo \"semver tag on stable branch should have format ^v[0-9]+\\.[0-9]+\\.[0-9]+$\"\n    exit 2\n  fi\n\n  _major_version=$(echo \"$_semver_tag\" | cut -d\".\" -f1)\n  if [[ -z \"$_major_version\" ]]; then\n    echo \"Unable to determine major version from latest semver tag on 'stable' branch\"\n    exit 2\n  fi\n\n  VERSION=\"$_major_version-stable\"\n  popd 1>/dev/null\nelse\n  echo \"release-controller.sh] Validating that controller image repository & tag in release artifacts is consistent with semver tag\"\n  pushd $WORKSPACE_DIR/helm 1>/dev/null\n    _repository=$(yq eval \".image.repository\" values.yaml)\n    _image_tag=$(yq eval \".image.tag\" values.yaml)\n    if [[ $_repository != public.ecr.aws/aws-application-networking-k8s/aws-gateway-controller ]]; then\n      echo \"release-controller.sh] [ERROR] 'image.repository' value in release artifacts should be $DEFAULT_IMAGE_REPOSITORY. Current value: $_repository\"\n      exit 1\n    fi\n    if [[ $_image_tag != $VERSION ]]; then\n      echo \"release-controller.sh] [ERROR] 'image.tag' value in release artifacts should be $VERSION. Current value: $_image_tag\"\n      exit 1\n    fi\n    echo \"release-controller.sh] Validation successful\"\n  popd 1>/dev/null\nfi\n\nIMAGE_REPOSITORY=${IMAGE_REPOSITORY:-$DEFAULT_IMAGE_REPOSITORY}\nIMAGE_TAG=${IMAGE_TAG:-$VERSION}\nCHART_REPOSITORY=${CHART_REPOSITORY:-$DEFAULT_CHART_REPOSITORY}\nCHART_REGISTRY=${CHART_REGISTRY:-$DEFAULT_CHART_REGISTRY}\n\nECR_PUBLISH_ROLE_ARN=${ECR_PUBLISH_ROLE_ARN:-\"undefined\"}\n\nif [[ \"$ECR_PUBLISH_ROLE_ARN\" = undefined ]]; then\n    error_msg \"Please set the ECR_PUBLISH_ROLE_ARN environment variable to the IAM Role ARN\"\n    error_msg  \"that has permissions to upload artifacts to the ECR Public registry for\"\n    error_msg \"$IMAGE_REPOSITORY\"\n    exit 2\nfi\n\necho \"VERSION is $VERSION\"\n\n# TODO(jaypipes): If we move to Prow setup like ACK, uncomment this. For now,\n# just pass in ECR_PUBLISH_ROLE_ARN manually.\n# ASSUME_EXIT_VALUE=0\n# ECR_PUBLISH_ROLE_ARN=$(aws ssm get-parameter --name /ack/prow/cd/public_ecr/publish_role --query Parameter.Value --output text 2>/dev/null) || ASSUME_EXIT_VALUE=$?\n# if [ \"$ASSUME_EXIT_VALUE\" -ne 0 ]; then\n#   echo \"release-controller.sh] [SETUP] Could not find the iam role to publish images to public ecr repository\"\n# exit 1\n# fi\nexport ECR_PUBLISH_ROLE_ARN\necho \"release-controller.sh] [SETUP] exported ECR_PUBLISH_ROLE_ARN\"\n\nASSUME_COMMAND=$(aws --output json sts assume-role --role-arn $ECR_PUBLISH_ROLE_ARN --role-session-name 'publish-images' --duration-seconds 3600 | jq -r '.Credentials | \"export AWS_ACCESS_KEY_ID=\\(.AccessKeyId)\\nexport AWS_SECRET_ACCESS_KEY=\\(.SecretAccessKey)\\nexport AWS_SESSION_TOKEN=\\(.SessionToken)\\n\"')\neval $ASSUME_COMMAND\necho \"release-controller.sh] [SETUP] Assumed ECR_PUBLISH_ROLE_ARN\"\n\n# Setup the destination repository for buildah and helm\nperform_buildah_and_helm_login\n\n# Do not rebuild controller image for stable releases\nif [[ \"$SKIP_IMAGE_BUILD\" != \"1\" ]]; then\n    if ! (echo \"$VERSION\" | grep -Eq \"stable$\"); then\n      # Determine parameters for docker-build command\n\n      cd \"$WORKSPACE_DIR\"\n\n      CONTROLLER_GIT_COMMIT=$(git rev-parse HEAD)\n      QUIET=${QUIET:-\"false\"}\n      BUILD_DATE=$(date +%Y-%m-%dT%H:%M)\n      CONTROLLER_IMAGE_DOCKERFILE_PATH=$WORKSPACE_DIR/Dockerfile\n\n      IMG=\"$IMAGE_REPOSITORY:$IMAGE_TAG\"\n      DOCKER_BUILD_CONTEXT=\"$WORKSPACE_DIR\"\n\n      if [[ $QUIET = \"false\" ]]; then\n          echo \"building aws-gateway-controller image with tag: ${IMG}\"\n          echo \" git commit: $CONTROLLER_GIT_COMMIT\"\n      fi\n\n      # build controller image\n      buildah bud \\\n        --quiet=\"$QUIET\" \\\n        -t \"$IMG\" \\\n        -f \"$CONTROLLER_IMAGE_DOCKERFILE_PATH\" \\\n        --build-arg service_controller_git_version=\"$VERSION\" \\\n        --build-arg service_controller_git_commit=\"$CONTROLLER_GIT_COMMIT\" \\\n        --build-arg build_date=\"$BUILD_DATE\" \\\n        \"${DOCKER_BUILD_CONTEXT}\"\n\n      if [ $? -ne 0 ]; then\n        exit 2\n      fi\n\n      echo \"Pushing aws-gateway-controller image with tag: ${IMG}\"\n\n      buildah push \"${IMG}\"\n\n      if [ $? -ne 0 ]; then\n        exit 2\n      fi\n    fi\nfi\n\nexport HELM_EXPERIMENTAL_OCI=1\n\necho \"Generating Helm chart package for $CHART_REGISTRY/$CHART_REPOSITORY@$VERSION ... \"\nhelm package \"$WORKSPACE_DIR\"/helm/\n# Path to tarballed package (eg. `aws-application-networking-controller-v0.0.1.tgz`)\nCHART_PACKAGE=\"$CHART_REPOSITORY-$VERSION.tgz\"\n\nhelm push \"$CHART_PACKAGE\" \"oci://$CHART_REGISTRY\"\n", "num_lines": 181}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# aws.sh contains functions for running common AWS command line methods.\n\nLIB_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\nsource \"$LIB_DIR/common.sh\"\nsource \"$LIB_DIR/config.sh\"\nsource \"$LIB_DIR/logging.sh\"\n\nAWS_CLI_VERSION=${DEFAULT_AWS_CLI_VERSION:-\"2.0.52\"}\n\n# daws() executes the AWS Python CLI tool from a Docker container.\n#\n# Instead of relying on developers having a particular version of the AWS\n# Python CLI tool, this method allows a specific version of the CLI tool to be\n# executed within a Docker container.\n#\n# You call the daws function just like you were calling the `aws` CLI tool.\n#\n# Usage:\n#\n#   daws SERVICE COMMAND [OPTIONS]\n#\n# Example:\n#\n#   daws ecr describe-repositories --repository-name my-repo\n#\n# To use a specific version of the AWS CLI, set the ACK_AWS_CLI_IMAGE_VERSION\n# environment variable, otherwise the value of DEFAULT_AWS_CLI_VERSION is used.\ndaws() {\n    local profile=\"$(get_aws_profile)\"\n    local identity_file=\"$(get_aws_token_file)\"\n    local default_region=\"$(get_aws_region)\"\n\n    aws_cli_profile_env=$([ ! -z \"$profile\" ] && echo \"--env AWS_PROFILE=$profile\")\n    aws_cli_web_identity_env=\"$([ ! -z \"$identity_file\" ] && \\\n        echo \"--env AWS_WEB_IDENTITY_TOKEN_FILE=/root/aws_token --env AWS_ROLE_ARN -v $identity_file:/root/aws_token:ro\" )\"\n    aws_cli_img=\"amazon/aws-cli:$AWS_CLI_VERSION\"\n\n    docker run --rm -v ~/.aws:/root/.aws:z $(echo $aws_cli_profile_env) $(echo $aws_cli_web_identity_env) --env AWS_DEFAULT_REGION=$default_region -v $(pwd):/aws \"$aws_cli_img\" \"$@\"\n}\n\n# ensure_aws_credentials() calls the STS::GetCallerIdentity API call and\n# verifies that there is a local identity for running AWS commands\nensure_aws_credentials() {\n    daws sts get-caller-identity --query \"Account\" >/dev/null ||\n        ( error_msg \"No AWS credentials found. Please run \\`aws configure\\` to set up the CLI for your credentials\" && exit 1)\n}\n\n# generate_aws_temp_creds function will generate temporary AWS credentials which\n# are valid for 3600 seconds\naws_generate_temp_creds() {\n    local __uuid=$(uuidgen | cut -d'-' -f1 | tr '[:upper:]' '[:lower:]')\n\n    local assumed_role=$(get_assumed_role_arn)\n\n    local json=$(daws sts assume-role \\\n           --role-arn \"$assumed_role\"  \\\n           --role-session-name tmp-role-\"$__uuid\" \\\n           --duration-seconds 3600 \\\n           --output json || exit 1)\n\n    AWS_ACCESS_KEY_ID=$(echo \"${json}\" | jq --raw-output \".Credentials[\\\"AccessKeyId\\\"]\")\n    AWS_SECRET_ACCESS_KEY=$(echo \"${json}\" | jq --raw-output \".Credentials[\\\"SecretAccessKey\\\"]\")\n    AWS_SESSION_TOKEN=$(echo \"${json}\" | jq --raw-output \".Credentials[\\\"SessionToken\\\"]\")\n}\n\naws_account_id() {\n    local json=$(daws sts get-caller-identity --output json || exit 1)\n    echo \"${json}\" | jq --raw-output \".Account\"\n}\n\nensure_binaries() {\n    check_is_installed \"docker\"\n    check_is_installed \"jq\"\n    check_is_installed \"uuidgen\"\n}\n\nensure_binaries", "num_lines": 80}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# common.sh contains commonly used functions, meant to be imported by other\n# bash scripts.\n\nLIB_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\nsource \"$LIB_DIR/logging.sh\"\n\n# check_is_installed checks to see if the supplied executable is installed and\n# exits if not. An optional second argument is an extra message to display when\n# the supplied executable is not installed.\n#\n# Usage:\n#\n#   check_is_installed PROGRAM [ MSG ]\n#\n# Example:\n#\n#   check_is_installed kind \"You can install kind with the helper scripts/install-kind.sh\"\ncheck_is_installed() {\n    local __name=\"$1\"\n    local __extra_msg=\"$2\"\n    if ! is_installed \"$__name\"; then\n        error_msg \"Missing required binary in PATH: '$__name'\"\n        error_msg \"Please install $__name before running this script.\"\n        if [[ -n $__extra_msg ]]; then\n            error_msg \"\"\n            error_msg \"$__extra_msg\"\n            error_msg \"\"\n        fi\n        exit 1\n    fi\n}\n\nis_installed() {\n    local __name=\"$1\"\n    if $(which $__name >/dev/null 2>&1); then\n        return 0\n    else\n        return 1\n    fi\n}", "num_lines": 43}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# config.sh contains functions for extracting configuration elements from an ACK\n# test config file, providing sane defaults when possible.\n\nset -Eeo pipefail\n\nLIB_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nSCRIPTS_DIR=\"$LIB_DIR/..\"\n\nTEST_CONFIG_PATH=${TEST_CONFIG_PATH:-\"$SCRIPTS_DIR/../test_config.yaml\"}\n\nASSUMED_ROLE_ARN=\"${ASSUMED_ROLE_ARN:-\"\"}\"\n\nsource \"$LIB_DIR/common.sh\"\nsource \"$LIB_DIR/logging.sh\"\n\n_get_config_field() {\n    local __field_path=\"$1\"\n    local __default=\"${2:-\"\"}\"\n\n    if [[ \"$__default\" != \"\" ]]; then\n        yq \"$__field_path // \\\"$__default\\\"\" $TEST_CONFIG_PATH 2>/dev/null\n    else\n        yq \"$__field_path // \\\"\\\"\" $TEST_CONFIG_PATH 2>/dev/null\n    fi\n}\n\n_get_config_boolean() {\n    # Booleans must be handled differently because the yq \"Alternative\" feature\n    # returns the alternative value if the value of the field is \"false\" - \n    # instead of simply returning \"false\" (as we would expect)\n    local __field_path=\"$1\"\n    local __default=\"${2:-\"\"}\"\n\n    local ret=$(yq \"$__field_path\" $TEST_CONFIG_PATH 2>/dev/null)\n    if [[ \"$ret\" == \"null\" ]]; then\n        echo $__default\n    fi\n    echo $ret\n}\n\nget_cluster_create() { _get_config_boolean \".cluster.create\"; }\nget_cluster_name() { _get_config_field \".cluster.name\"; }\nget_cluster_k8s_version() { _get_config_field \".cluster.k8s_version\"; }\nget_cluster_configuration_file_name() { _get_config_field \".cluster.configuration.file_name\" \"kind-two-node-cluster.yaml\"; }\nget_cluster_additional_controllers() { _get_config_field \".cluster.configuration.additional_controllers\"; }\nget_aws_profile() { _get_config_field \".aws.profile\"; }\nget_aws_token_file() { _get_config_field \".aws.token_file\"; }\nget_aws_region() { _get_config_field \".aws.region\" \"us-west-2\"; }\nget_assumed_role_arn() {\n    [[ ! -z \"${ASSUMED_ROLE_ARN}\" ]] && echo \"${ASSUMED_ROLE_ARN}\" || _get_config_field \".aws.assumed_role_arn\";\n}\nget_test_markers() { _get_config_field \".tests.markers\"; }\nget_test_methods() { _get_config_field \".tests.methods\"; }\nget_run_tests_locally() { _get_config_field \".tests.run_locally\"; }\nget_is_local_build() { _get_config_boolean \".local_build\" \"false\"; }\nget_debug_enabled() { _get_config_boolean \".debug.enabled\" \"false\"; }\nget_dump_controller_logs() { _get_config_boolean \".debug.dump_controller_logs\" \"false\"; }\n\nget_test_config_path() { echo \"$TEST_CONFIG_PATH\"; }\n\nensure_config_file_exists() {\n    [[ ! -f \"$TEST_CONFIG_PATH\" ]] && { error_msg \"Config file does not exist at path $TEST_CONFIG_PATH\"; exit 1; } || :\n}\n\nensure_required_fields() {\n    # Allow if the ASSUMED_ROLE_ARN is substituting\n    [[ -z $(_get_config_field \".aws.assumed_role_arn\") && -z ${ASSUMED_ROLE_ARN} ]] && { error_msg \"Required config path \\`.aws.assumed_role_arn\\` not provided\"; exit 1; } || :\n\n    local required_field_paths=( \".cluster.create\" )\n    for path in \"${required_field_paths[@]}\"; do\n        [[ -z $(_get_config_boolean $path) ]] && { error_msg \"Required config path \\`$path\\` not provided\"; exit 1; } || :\n    done\n}\n\nensure_binaries() {\n    check_is_installed \"yq\"\n}\n\nensure_binaries\nensure_config_file_exists\nensure_required_fields", "num_lines": 83}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# logging.sh contains functions for writing log messages to the console for \n# three different severities: debug, info and error.\n\n# Prints out a message with an optional second argument indicating the\n# \"indentation level\" for the message. If the indentation level argument is\n# missing, we look for the existence of an environs variable called\n# \"indent_level\" and use that.\n_indented_msg() {\n    local __msg=${1:-}\n    local __indent_level=${2:-}\n    local indent=\"\"\n    if [ -n \"$__indent_level\" ]; then\n        indent=\"$( for each in $( seq 0 $__indent_level ); do printf \" \"; done )\"\n    fi\n\n    local timestamp=$(date -Is)\n\n    echo \"$timestamp $__indent$__msg\"\n}\n\n# debug_msg prints out a supplied message if the ACK_TEST_DEBUGGING_MODE environ\n# variable is set.\ndebug_msg() {\n    local __debug=\"${ACK_TEST_DEBUGGING_MODE:-\"\"}\"\n    if [ ! -n \"$__debug\" ]; then\n        return 0\n    fi\n\n    local __msg=${1:-}\n    local __indent=${2:-}\n    local __debug_prefix=\"${DEBUG_PREFIX:-\"[DEBUG] \"}\"\n    _indented_msg \"$__debug_prefix$__msg\" $__indent\n}\n\n# info_msg prints out a supplied message if the DEBUG environs variable is\n# set.\ninfo_msg() {\n    local __msg=${1:-}\n    local __indent=${2:-}\n    local __info_prefix=\"${INFO_PREFIX:-\"[INFO] \"}\"\n    _indented_msg \"$__info_prefix$__msg\" $__indent\n}\n\n# debug_msg prints out a supplied message if the DEBUG environs variable is\n# set.\nerror_msg() {\n    local __msg=${1:-}\n    local __indent=${2:-}\n    local __error_prefix=\"${ERROR_PREFIX:-\"[ERROR] \"}\"\n    >&2 _indented_msg \"$__error_prefix$__msg\" $__indent\n}", "num_lines": 53}
{"repo_name": "aws-application-networking-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# login.sh contains functions for logging into container repositories.\n# Note: These functions are not placed inside tools specific file like\n# helm.sh, because those files ensure binaries(ex: kind) that are not\n# really needed for simple actions like repository login.\n# A future refactor can make those files more modular and then login\n# functions can be refactored in tool specific file like buildah.sh\n# and helm.sh\n\nperform_buildah_and_helm_login() {\n  #ecr-public only exists in us-east-1 so use that region specifically\n  local __pw=$(aws ecr-public get-login-password --region us-east-1)\n  echo \"$__pw\" | buildah login -u AWS --password-stdin public.ecr.aws\n  export HELM_EXPERIMENTAL_OCI=1\n  echo \"$__pw\" | helm registry login -u AWS --password-stdin public.ecr.aws\n}\n\nensure_binaries() {\n    check_is_installed \"aws\"\n    check_is_installed \"buildah\" \"See https://github.com/containers/buildah/blob/main/install.md\"\n    check_is_installed \"helm\"\n}\n\nensure_binaries\n", "num_lines": 26}
{"repo_name": "aws-auto-scaling-custom-resource", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nif [ $0 != \"/root/scripts/setup.sh\" ]; then\n\techo \"Script will not execute outside of Docker context.\"\n\texit\nfi\n/usr/bin/apt-get update\n/usr/bin/apt-get install -y apache2 libapache2-mod-python software-properties-common tzdata\n/usr/bin/add-apt-repository -y ppa:certbot/certbot\n/usr/bin/apt-get update\n/usr/bin/apt-get install -y python-certbot-apache \n/usr/sbin/a2enmod ssl cgi rewrite proxy_http allowmethods\n/usr/bin/certbot --apache --email $CERTBOT_EMAIL -d $CERTBOT_HOSTNAME --agree-tos --non-interactive\n/usr/sbin/a2ensite 0-api.conf\n/usr/sbin/a2ensite 1-api-80.conf\n/usr/sbin/a2ensite 2-api-internal.conf\n/usr/sbin/a2ensite 3-api-internal-80.conf\n/usr/sbin/a2dissite 000-default\n/usr/sbin/a2dissite 000-default-le-ssl\n\n/bin/chown -R www-data: /var/www/state\n/bin/chown -R www-data: /var/log/apache2\n\nCopy_ServerName=`/bin/egrep -o '^ServerName.*$' /etc/apache2/sites-available/000-default-le-ssl.conf`\n/bin/sed -i \"s|##ServerName##|$Copy_ServerName|\" /etc/apache2/sites-available/0-api.conf \n/bin/sed -i \"s|##ServerName##|$Copy_ServerName|\" /etc/apache2/sites-available/1-api-80.conf \nCopy_SSLCertificateFile=`/bin/egrep -o '^SSLCertificateFile.*$' /etc/apache2/sites-available/000-default-le-ssl.conf`\n/bin/sed -i \"s|##SSLCertificateFile##|$Copy_SSLCertificateFile|\" /etc/apache2/sites-available/0-api.conf \nCopy_SSLCertificateKeyFile=`/bin/egrep -o '^SSLCertificateKeyFile.*$' /etc/apache2/sites-available/000-default-le-ssl.conf`\n/bin/sed -i \"s|##SSLCertificateKeyFile##|$Copy_SSLCertificateKeyFile|\" /etc/apache2/sites-available/0-api.conf\nCopy_Include=`/bin/egrep -o '^Include.*$' /etc/apache2/sites-available/000-default-le-ssl.conf`\n/bin/sed -i \"s|##Include##|$Copy_Include|\" /etc/apache2/sites-available/0-api.conf \n\n\n\n", "num_lines": 35}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------------\n#\n# This script is intended to be used to bump the version of the CDK modules, update package.json,\n# package-lock.json, and create a commit.\n#\n# to start a version bump, run:\n#     bump.sh <version | version Type>\n#\n# If a version is not provided, the 'minor' version will be bumped.\n# The version can be an explicit version _or_ one of:\n# 'major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', or 'prerelease'.\n#\n# --------------------------------------------------------------------------------------------------\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\ncd ${scriptdir}\nyarn install --frozen-lockfile\nif [[ \"${LEGACY_BUMP:-}\" == \"\" ]]; then\n  #  if we're using 'cdk-release' for the bump, build that package, including all of its dependencies\n  npx lerna run build --include-dependencies --scope @aws-cdk/cdk-release\nfi\nVERBOSE=1 exec ${scriptdir}/scripts/bump.js ${1:-minor}\n", "num_lines": 24}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nmkdir -p .tools\n[[ ! -d .tools/git-secrets ]] && {\n    echo \"=============================================================================================\"\n    echo \"Downloading git-secrets...\"\n    (cd .tools && git clone --depth 1 https://github.com/awslabs/git-secrets.git)\n}\n\n# As the name implies, git-secrets heavily depends on git:\n#\n# a) the config is stored and fetched using 'git config'.\n# b) the search is performed using 'git grep' (other search methods don't work\n#    properly, see https://github.com/awslabs/git-secrets/issues/66)\n#\n# When we run in a CodeBuild build, we don't have a git repo, unfortunately. So\n# when that's the case, 'git init' one on the spot, add all files to it (which\n# because of the .gitignore will exclude dependencies and generated files) and\n# then call 'git-secrets' as usual.\ngit rev-parse --git-dir > /dev/null 2>&1 || {\n    git init --quiet\n    git add -A .\n}\n\n# AWS config needs to be added to this repository's config\n.tools/git-secrets/git-secrets --register-aws\n\n.tools/git-secrets/git-secrets --scan\necho \"git-secrets scan ok\"\n", "num_lines": 31}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nexec npx yarn install --frozen-lockfile\n", "num_lines": 4}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# creates symlinks under node_modules for all packages in this repo\n# can be used to work against this code base.\nset -euo pipefail\nroot=\"$(cd $(dirname $0) && pwd)\"\n\nmkdir -p node_modules node_modules/.bin\n\nmodules=\"$(find ${root}/packages -name package.json | grep -v node_modules | grep -v init-templates | xargs -n1 dirname)\"\nfor module in ${modules}; do\n  if [[ $(basename $(dirname $module)) == @* ]]; then\n    # This is a @scope/based package\n    scope=$(basename $(dirname $module))\n    link_dir=node_modules/$(basename $(dirname $module))\n    mkdir -p $link_dir\n  else\n    link_dir=node_modules\n  fi\n\n  module_dir=${link_dir}/$(basename $module)\n  echo \"${module} => ${module_dir}\"\n  rm -fr ${module_dir}\n  ln -fs ${module} ${link_dir}\n\n  # Symlink executable scripts into place as well. This is not completely\n  # according to spec (we look in the bin/ directory instead of the { \"scripts\"\n  # } entry in package.json but it's quite a bit easier.\n  if [[ -d $module/bin ]]; then\n    for script in $(find $module/bin -perm +111); do\n      echo \"${script} => node_modules/.bin/$(basename $script)\"\n      ln -fs ${script} node_modules/.bin\n    done\n  fi\ndone\n", "num_lines": 35}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Runs \"npm package\" in all modules. This will produce a \"dist/\" directory in each module.\n# Then, calls pack-collect.sh to merge all outputs into a root ./pack directory, which is\n# later read by bundle-beta.sh.\nset -eu\nexport PATH=$PWD/node_modules/.bin:$PATH\nexport NODE_OPTIONS=\"--max-old-space-size=8192 ${NODE_OPTIONS:-}\"\nroot=$PWD\n\n# Get version and changelog file name (these require that .versionrc.json would have been generated)\nversion=$(node -p \"require('./scripts/resolve-version').version\")\nchangelog_file=$(node -p \"require('./scripts/resolve-version').changelogFile\")\nmarker=$(node -p \"require('./scripts/resolve-version').marker\")\n\nPACMAK=${PACMAK:-jsii-pacmak}\nROSETTA=${ROSETTA:-jsii-rosetta}\nTMPDIR=${TMPDIR:-$(dirname $(mktemp -u))}\ndistdir=\"$PWD/dist\"\nrm -fr ${distdir}\nmkdir -p ${distdir}\n\nif ${CHECK_PREREQS:-true}; then\n  /bin/bash ./scripts/check-pack-prerequisites.sh\nfi\n\n# Split out jsii and non-jsii packages. Jsii packages will be built all at once.\n# Non-jsii packages will be run individually.\necho \"Collecting package list...\" >&2\nscripts/list-packages $TMPDIR/jsii.txt $TMPDIR/nonjsii.txt\n\n# Return lerna scopes from a package list\nfunction lerna_scopes() {\n  while [[ \"${1:-}\" != \"\" ]]; do\n    echo \"--scope $1 \"\n    shift\n  done\n}\n\nscripts/run-rosetta.sh --infuse --pkgs-from $TMPDIR/jsii.txt\n\n# Execute any pre-package steps for the jsii modules here:\necho \"Running aws-cdk-lib pre-package\"\nnpx lerna run --scope aws-cdk-lib package -- --pre-only\n\n# Jsii packaging (all at once using jsii-pacmak)\necho \"Packaging jsii modules\" >&2\n$PACMAK \\\n  --verbose \\\n  $(cat $TMPDIR/jsii.txt)\n\n# Execute any post-package steps for the jsii modules here:\necho \"Running aws-cdk-lib post-package\"\nnpx lerna run --scope aws-cdk-lib package -- --post-only\n\n# Non-jsii packaging, which means running 'package' in every individual\n# module\necho \"Packaging non-jsii modules\" >&2\nnpx lerna run $(lerna_scopes $(cat $TMPDIR/nonjsii.txt)) --sort --concurrency=1 --stream package\n\n# Finally rsync all 'dist' directories together into a global 'dist' directory\nfor dir in $(find packages -name dist | grep -v node_modules | grep -v run-wrappers); do\n  echo \"Merging ${dir} into ${distdir}\" >&2\n  rsync -a $dir/ ${distdir}/\ndone\n\n# Record the dependency order of NPM packages into a file\n# (This file will be opportunistically used during publishing)\n#\n# Manually sort 'aws-cdk' to the end, as the 'cdk init' command has implicit dependencies\n# on other packages (that should not appear in 'package.json' and so\n# there is no way to tell lerna about these).\nfor dir in $(lerna ls --toposort -p | grep -v packages/aws-cdk) $PWD/packages/aws-cdk; do\n  (cd $dir/dist/js && ls >> ${distdir}/js/npm-publish-order.txt) || true\ndone\n\n# Remove a JSII aggregate POM that may have snuk past\nrm -rf dist/java/software/amazon/jsii\n\n# Get commit from CodePipeline (or git, if we are in CodeBuild)\n# If CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local\n# build or CodePipeline build), use the HEAD commit hash).\ncommit=\"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\"\nif [ -z \"${commit}\" ]; then\n  commit=\"$(git rev-parse --verify HEAD)\"\nfi\n\ncat > ${distdir}/build.json <<HERE\n{\n  \"name\": \"aws-cdk\",\n  \"version\": \"${version}\",\n  \"commit\": \"${commit}\"\n}\nHERE\n\n# copy CHANGELOG.md and RELEASE_NOTES.md to dist/ for github releases\ncp ${changelog_file} ${distdir}/CHANGELOG.md\n# Release notes are not available for bump candidate builds.\nif ! ${BUMP_CANDIDATE:-false}; then\n  cp RELEASE_NOTES.md ${distdir}/RELEASE_NOTES.md\nfi\n\n# defensive: make sure our artifacts don't use the version marker (this means\n# that \"pack\" will always fails when building in a dev environment)\n# when we get to 10.0.0, we can fix this...\nif find dist/ | grep -F \"${marker}\"; then\n  echo \"ERROR: build artifacts use the version marker '${marker}' instead of a real version.\"\n  echo \"This is expected for builds in a development environment but should not happen in CI builds!\"\n  exit 1\nfi\n", "num_lines": 110}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run our integration tests in regression mode against the\n# candidate version of the framework, which is the one we just packed.\n#\nset -euo pipefail\nintegdir=$(cd $(dirname $0) && pwd)\n\nsource ${integdir}/test-cli-regression.bash\n\nrun_regression_against_framework_version CANDIDATE_VERSION\n", "num_lines": 12}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run our integration tests in regression mode against the\n# previous version of the framework, relative to the version being packed now.\n#\nset -euo pipefail\nintegdir=$(cd $(dirname $0) && pwd)\n\nsource ${integdir}/test-cli-regression.bash\n\nrun_regression_against_framework_version PREVIOUS_VERSION\n", "num_lines": 12}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\n\necho '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'\necho 'CLI Integration Tests'\necho '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'\n\ncd $scriptdir\n\nsource ../common/jest-test.bash\ninvokeJest \"$@\"\n", "num_lines": 13}
{"repo_name": "aws-cdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\n\necho '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'\necho 'CLI Integration Tests'\necho '~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~'\n\ncurrent_version=$(node -p \"require('${scriptdir}/../../../package.json').version\")\n\n# This allows injecting different versions, not just the current one.\n# Useful when testing.\nexport VERSION_UNDER_TEST=${VERSION_UNDER_TEST:-${current_version}}\n\ncd $scriptdir\n\n# Install these dependencies that the tests (written in Jest) need.\n# Only if we're not running from the repo, because if we are the\n# dependencies have already been installed by the containing 'aws-cdk' package's\n# package.json.\nif ! npx --no-install jest --version; then\n  echo 'Looks like we need to install jest first. Hold on.' >& 2\n  npm install --prefix . jest aws-sdk\nfi\n\nnpx jest --runInBand --verbose \"$@\"", "num_lines": 26}
{"repo_name": "aws-cdk-rfcs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# executes markdownlint on all RFCs\n# --fix to fix errors\nset -euo pipefail\nlinters=$PWD/tools/linters\n\nnpm install --prefix $linters\nfind . -type f -name '*.md' -not -path '*/node_modules/*' -not -path '*/.github/*' |\\\n  xargs -I'{}' $linters/node_modules/.bin/markdownlint -c $linters/markdownlint.json $@ '{}'\n", "num_lines": 10}
{"repo_name": "aws-cdk-rfcs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n(cd tools/rfc-render && npm install)\nnode tools/rfc-render/inject-table.js README.md\n", "num_lines": 5}
{"repo_name": "aws-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "# Source this file to activate auto completion for zsh using the bash\n# compatibility helper.  Make sure to run `compinit` before, which should be\n# given usually.\n#\n# % source /path/to/zsh_complete.sh\n#\n# Typically that would be called somewhere in your .zshrc.\n#\n# Note, the overwrite of _bash_complete() is to export COMP_LINE and COMP_POINT\n# That is only required for zsh <= edab1d3dbe61da7efe5f1ac0e40444b2ec9b9570\n#\n# https://github.com/zsh-users/zsh/commit/edab1d3dbe61da7efe5f1ac0e40444b2ec9b9570\n#\n# zsh releases prior to that version do not export the required env variables!\n\nautoload -Uz bashcompinit\nbashcompinit -i\n\n_bash_complete() {\n  local ret=1\n  local -a suf matches\n  local -x COMP_POINT COMP_CWORD\n  local -a COMP_WORDS COMPREPLY BASH_VERSINFO\n  local -x COMP_LINE=\"$words\"\n  local -A savejobstates savejobtexts\n\n  (( COMP_POINT = 1 + ${#${(j. .)words[1,CURRENT]}} + $#QIPREFIX + $#IPREFIX + $#PREFIX ))\n  (( COMP_CWORD = CURRENT - 1))\n  COMP_WORDS=( $words )\n  BASH_VERSINFO=( 2 05b 0 1 release )\n\n  savejobstates=( ${(kv)jobstates} )\n  savejobtexts=( ${(kv)jobtexts} )\n\n  [[ ${argv[${argv[(I)nospace]:-0}-1]} = -o ]] && suf=( -S '' )\n\n  matches=( ${(f)\"$(compgen $@ -- ${words[CURRENT]})\"} )\n\n  if [[ -n $matches ]]; then\n    if [[ ${argv[${argv[(I)filenames]:-0}-1]} = -o ]]; then\n      compset -P '*/' && matches=( ${matches##*/} )\n      compset -S '/*' && matches=( ${matches%%/*} )\n      compadd -Q -f \"${suf[@]}\" -a matches && ret=0\n    else\n      compadd -Q \"${suf[@]}\" -a matches && ret=0\n    fi\n  fi\n\n  if (( ret )); then\n    if [[ ${argv[${argv[(I)default]:-0}-1]} = -o ]]; then\n      _default \"${suf[@]}\" && ret=0\n    elif [[ ${argv[${argv[(I)dirnames]:-0}-1]} = -o ]]; then\n      _directories \"${suf[@]}\" && ret=0\n    fi\n  fi\n\n  return ret\n}\n\ncomplete -C aws_completer aws\n", "num_lines": 61}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Cleanup EKS cluster used for integration test.\n\nsource ./integration/eks-test/scripts/eks-common.sh\n\n# Delete service and namespace from export and import cluster\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN delete svc $SERVICE -n $NAMESPACE\n\n# Verfication to check if there are hanging ServiceExport or ServiceImport CRDs and clears the finalizers to allow cleanup process to continue\nfor CRD in $($KUBECTL_BIN get crd -n $NAMESPACE | grep multicluster | cut -d \" \" -f 1 | xargs); do \n    $KUBECTL_BIN patch crd -n $NAMESPACE $CRD --type merge -p '{\"metadata\":{\"finalizers\": [null]}}';\n    $KUBECTL_BIN delete crd $CRD -n $NAMESPACE # CRD needs to be explictly deleted in order to ensure zero resources are hanging for future tests\ndone\n\n$KUBECTL_BIN delete namespaces $NAMESPACE\n\n# IAM Service Account needs to be explictly deleted, as not doing so creates hanging service accounts that cause permissions issues in future tests\neksctl delete iamserviceaccount \\\n    --name cloud-map-mcs-controller-manager \\\n    --namespace $MCS_NAMESPACE \\\n    --cluster $EXPORT_CLS \\\n    --wait\n\n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN delete pod $CLIENT_POD -n $NAMESPACE\n$KUBECTL_BIN delete namespaces $NAMESPACE\neksctl delete iamserviceaccount \\\n    --name cloud-map-mcs-controller-manager \\\n    --namespace $MCS_NAMESPACE \\\n    --cluster $IMPORT_CLS \\\n    --wait\n\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN delete -k \"github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest\"\n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN delete -k \"github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest\"\n\necho \"EKS clusters cleaned!\"\n\n# ./integration/shared/scripts/cleanup-cloudmap.sh\ngo run ./integration/janitor/runner/main.go \"$NAMESPACE\" \"$CLUSTERID1\" \"$CLUSTERSETID1\"\ngo run ./integration/janitor/runner/main.go \"$NAMESPACE\" \"$CLUSTERID2\" \"$CLUSTERSETID1\"\n", "num_lines": 45}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport KIND_BIN='./bin/kind'\nexport KUBECTL_BIN='kubectl'\nexport LOGS='./integration/eks-test/testlog'\nexport CONFIGS='./integration/eks-test/configs'\nexport SCENARIOS='./integration/shared/scenarios'\nexport NAMESPACE='aws-cloud-map-mcs-eks-e2e'\nexport MCS_NAMESPACE='cloud-map-mcs-system'\nexport SERVICE='nginx-hello'\nexport SERVICE_TYPE='ClusterSetIP'\nexport CLIENT_POD='client-hello'\nexport ENDPT_PORT=80\nexport SERVICE_PORT=80 # from nginx-service.yaml\nexport EXPORT_CLS='cls1'\nexport IMPORT_CLS='cls2'\nexport CLUSTERID1='eks-e2e-clusterid-1'\nexport CLUSTERID2='eks-e2e-clusterid-2'\nexport CLUSTERSETID1='eks-e2e-clustersetid-1'\nexport EXPECTED_ENDPOINT_COUNT=3\nexport UPDATED_ENDPOINT_COUNT=4", "num_lines": 21}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Testing service consumption with client-hello pod\n\necho \"verifying cross-cluster service consumption...\"\n\n# Install curl if not installed\n$KUBECTL_BIN exec $CLIENT_POD -n $NAMESPACE /bin/sh -- curl --version &>/dev/null\nexit_code=$?\nif [ \"$exit_code\" -eq 126 ]; then\n    echo \"curl not installed, installing...\"\n    $KUBECTL_BIN exec $CLIENT_POD -n $NAMESPACE /bin/sh -- apk add curl\nfi\n\n# Perform an nslookup to cluster-local CoreDNS \necho \"performing nslookup...\"\n$KUBECTL_BIN exec -it $CLIENT_POD -n $NAMESPACE /bin/sh -- nslookup $SERVICE.$NAMESPACE.svc.clusterset.local\nexit_code=$?\n\nif [ \"$exit_code\" -ne 0 ]; then\n    echo \"ERROR: Unable to nslookup service $SERVICE.$NAMESPACE.svc.clusterset.local\"\n    exit $exit_code\nfi\nsleep 5\n\n# Call to DNS server, if unable to reach, importing cluster is not able to properly consume service\necho \"performing curl...\"\n$KUBECTL_BIN exec -it $CLIENT_POD -n $NAMESPACE /bin/sh -- curl $SERVICE.$NAMESPACE.svc.clusterset.local\nexit_code=$?\n\nif [ \"$exit_code\" -ne 0 ]; then\n    echo \"ERROR: Unable to reach service $SERVICE.$NAMESPACE.svc.clusterset.local\"\n    exit $exit_code\nfi\n\necho \"confirmed service consumption\"\nexit 0\n", "num_lines": 38}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Runs the AWS Cloud Map MCS Controller for K8s in EKS clusters and test services has been exported from one cluster and imported from the other\n\nsource ./integration/eks-test/scripts/eks-common.sh\n\n# Checking expected endpoints number in exporting cluster\n$KUBECTL_BIN config use-context $EXPORT_CLS\nif ! endpts=$(./integration/shared/scripts/poll-endpoints.sh \"$EXPECTED_ENDPOINT_COUNT\"); then\n    exit $?\nfi\n\n# Runner to verify expected endpoints are exported to Cloud Map\ngo run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE \"$endpts\"\nexit_code=$?\n\n# Check imported endpoints in importing cluster\nif [ \"$exit_code\" -eq 0 ] ; then\n  $KUBECTL_BIN config use-context $IMPORT_CLS\n  ./integration/shared/scripts/test-import.sh \"$EXPECTED_ENDPOINT_COUNT\" \"$endpts\"\n  exit_code=$?\nfi\n  \n# Verifying that importing cluster is properly consuming services\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/eks-test/scripts/eks-DNS-test.sh\n  exit_code=$?\nfi\n\necho \"sleeping...\"\nsleep 2\n\n# Scaling and verifying deployment\nif [ \"$exit_code\" -eq 0 ] ; then\n  $KUBECTL_BIN config use-context $EXPORT_CLS\n  deployment=$($KUBECTL_BIN get deployment --namespace \"$NAMESPACE\" -o json | jq -r '.items[0].metadata.name')\n\n  echo \"scaling the deployment $deployment to $UPDATED_ENDPOINT_COUNT\"\n  $KUBECTL_BIN scale deployment/\"$deployment\" --replicas=\"$UPDATED_ENDPOINT_COUNT\" --namespace \"$NAMESPACE\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  if ! updated_endpoints=$(./integration/shared/scripts/poll-endpoints.sh \"$UPDATED_ENDPOINT_COUNT\") ; then\n    exit $?\n  fi\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE \"$updated_endpoints\" \n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  $KUBECTL_BIN config use-context $IMPORT_CLS\n  ./integration/shared/scripts/test-import.sh \"$UPDATED_ENDPOINT_COUNT\" \"$updated_endpoints\"\n  exit_code=$?\nfi\n  \nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/eks-test/scripts/eks-DNS-test.sh\n  exit_code=$?\nfi\n\n\n# Dump logs\nmkdir -p \"$LOGS\"\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN logs -l control-plane=controller-manager -c manager --namespace $MCS_NAMESPACE &> \"$LOGS/ctl-1.log\" \n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN logs -l control-plane=controller-manager -c manager --namespace $MCS_NAMESPACE &> \"$LOGS/ctl-2.log\" \necho \"dumped logs\"\n\nexit $exit_code\n", "num_lines": 75}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Adding IAM service accounts\n$KUBECTL_BIN config use-context $1\n$KUBECTL_BIN create namespace $MCS_NAMESPACE\neksctl create iamserviceaccount \\\n--cluster $1 \\\n--namespace $MCS_NAMESPACE \\\n--name cloud-map-mcs-controller-manager \\\n--attach-policy-arn arn:aws:iam::aws:policy/AWSCloudMapFullAccess \\\n--override-existing-serviceaccounts \\\n--approve\n\n# Installing controller\n$KUBECTL_BIN config use-context $1\n$KUBECTL_BIN apply -k \"github.com/aws/aws-cloud-map-mcs-controller-for-k8s/config/controller_install_latest\"\n\n", "num_lines": 18}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource ./integration/eks-test/scripts/eks-common.sh\n\n# Call helper for service account and controller installation\n./integration/eks-test/scripts/eks-setup-helper.sh $EXPORT_CLS\n./integration/eks-test/scripts/eks-setup-helper.sh $IMPORT_CLS\n\n# Apply ClusterProperties\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN apply -f \"$CONFIGS/e2e-clusterproperty-1.yaml\"\n\n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN apply -f \"$CONFIGS/e2e-clusterproperty-2.yaml\"\n\n# Installing service\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN create namespace $NAMESPACE\n$KUBECTL_BIN apply -f \"$CONFIGS/nginx-deployment.yaml\"\n$KUBECTL_BIN apply -f \"$CONFIGS/nginx-service.yaml\"\n\n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN create namespace $NAMESPACE\n\n# Creating service export\n$KUBECTL_BIN config use-context $EXPORT_CLS\n$KUBECTL_BIN apply -f \"$CONFIGS/nginx-serviceexport.yaml\"\n\n# Create client-hello pod\n$KUBECTL_BIN config use-context $IMPORT_CLS\n$KUBECTL_BIN apply -f \"$CONFIGS/client-hello.yaml\"\nsleep 15\n", "num_lines": 33}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Deletes Kind cluster used for integration test.\n\nset -eo pipefail\nsource ./integration/kind-test/scripts/common.sh\n\n$KIND_BIN delete cluster --name \"$KIND_SHORT\"\n\n./integration/shared/scripts/cleanup-cloudmap.sh\n", "num_lines": 11}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport KIND_BIN='./bin/kind'\nexport KUBECTL_BIN='kubectl'\nexport LOGS='./integration/kind-test/testlog'\nexport KIND_CONFIGS='./integration/kind-test/configs'\nexport SHARED_CONFIGS='./integration/shared/configs'\nexport SCENARIOS='./integration/shared/scenarios'\nexport NAMESPACE='aws-cloud-map-mcs-e2e'\nexport ENDPT_PORT=80\nexport SERVICE_PORT=80\nexport CLUSTERIP_SERVICE='e2e-clusterset-ip-service'\nexport HEADLESS_SERVICE='e2e-headless-service'\nexport KIND_SHORT='cloud-map-e2e'\nexport CLUSTER='kind-cloud-map-e2e'\nexport CLUSTERID1='kind-e2e-clusterid-1'\nexport CLUSTERSETID1='kind-e2e-clustersetid-1'\nexport IMAGE='kindest/node:v1.21.12@sha256:f316b33dd88f8196379f38feb80545ef3ed44d9197dca1bfd48bcb1583210207'\nexport EXPECTED_ENDPOINT_COUNT=5\nexport UPDATED_ENDPOINT_COUNT=6\n", "num_lines": 21}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Testing service consumption with dnsutils pod\n\ndeployment=$1\n\necho \"performing curl to $SERVICE.$NAMESPACE.svc.clusterset.local\"\nhttp_code=$($KUBECTL_BIN exec deployment/$deployment --namespace \"$NAMESPACE\" -- curl -s -o /dev/null -w \"%{http_code}\" $SERVICE.$NAMESPACE.svc.clusterset.local)\nexit_code=$?\n\nif [ \"$exit_code\" -ne 0 ]; then\n    echo \"ERROR: Unable to curl $SERVICE.$NAMESPACE.svc.clusterset.local\"\n    exit $exit_code\nfi\n\nif [ \"$http_code\" -ne \"200\" ]; then\n    echo \"ERROR: curl $SERVICE.$NAMESPACE.svc.clusterset.local failed with $http_code\"\n    exit 1\nfi\n\nexit 0\n", "num_lines": 22}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# If the IP Type env var is not set, default it to IPv4\nif [[ -z \"${ADDRESS_TYPE}\" ]]; then\n  ADDRESS_TYPE=\"IPv4\"\nfi\n\n# Helper function to verify DNS results\ncheckDNS() {\n    dns_addresses_count=$(echo \"$1\" | wc -l | xargs)\n\n    if [ \"$SERVICE_TYPE\" = \"Headless\" ]; then\n        if [ \"$dns_addresses_count\" -ne \"$expected_endpoint_count\" ]; then\n            echo \"ERROR: Found $dns_addresses_count endpoints, expected $expected_endpoint_count endpoints\"\n            exit 1\n        fi\n    fi\n\n    if [ \"$SERVICE_TYPE\" = \"ClusterSetIP\" ]; then\n        if [ \"$dns_addresses_count\" -ne 1 ]; then\n            echo \"ERROR: Found $dns_addresses_count endpoints, expected 1 endpoint\"\n            exit 1\n        fi\n    fi\n}\n\n# Testing service consumption with dnsutils pod\n\necho \"verifying dns resolution...\"\n\nexpected_endpoint_count=$1\n\n# Install dnsutils pod\n$KUBECTL_BIN apply -f \"$KIND_CONFIGS/dnsutils-pod.yaml\"\n$KUBECTL_BIN wait --for=condition=ready pod/dnsutils # wait until pod is deployed\n\n# Perform a dig to cluster-local CoreDNS\n# TODO: parse dig outputs for more precise verification - check specifics IPs?\nif [[ $ADDRESS_TYPE == \"IPv4\" ]]; then\n    echo \"performing dig for A records for IPv4...\"\n    addresses=$($KUBECTL_BIN exec dnsutils -- dig +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local +short)\n    exit_code=$?\n    echo \"$addresses\"\nelif [[ $ADDRESS_TYPE == \"IPv6\" ]]; then\n    echo \"performing dig for AAAA records for IPv6...\"\n    addresses=$($KUBECTL_BIN exec dnsutils -- dig AAAA +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local +short)\n    exit_code=$?\n    echo \"$addresses\"\nelse\n    echo \"ADDRESS_TYPE invalid\"\n    exit 1\nfi\n\nif [ \"$exit_code\" -ne 0 ]; then\n    echo \"ERROR: Unable to dig service $SERVICE.$NAMESPACE.svc.clusterset.local\"\n    exit $exit_code\nfi\n\n# verify DNS results\ncheckDNS \"$addresses\"\n\necho \"performing dig for SRV records...\"\naddresses=$($KUBECTL_BIN exec dnsutils -- dig +all +ans $SERVICE.$NAMESPACE.svc.clusterset.local. SRV +short)\nexit_code=$?\necho \"$addresses\"\n\nif [ \"$exit_code\" -ne 0 ]; then\n    echo \"ERROR: Unable to dig service $SERVICE.$NAMESPACE.svc.clusterset.local\"\n    exit $exit_code\nfi\n\n# verify DNS results\ncheckDNS \"$addresses\"\n\necho \"confirmed dns resolution\"\nexit 0\n", "num_lines": 77}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Ensure jq is available to parse json output. Installs jq on debian/ubuntu\n\nif ! which -s jq ; then\n  echo \"jq not found, attempting to install\"\n  if ! sudo apt-get install -y jq ; then\n    echo \"failed to install jq, ensure it is available before running tests\"\n    exit 1\n  fi\nfi\n\nexit 0\n", "num_lines": 14}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Helper to run test and passing different Service names\n\nsource ./integration/kind-test/scripts/common.sh\n\n# create test namespace\n$KUBECTL_BIN create namespace \"$NAMESPACE\"\n\n# If the IP Type env var is not set, default it to IPV4\nif [[ -z \"${ADDRESS_TYPE}\" ]]; then\n  ADDRESS_TYPE=\"IPv4\"\nfi\n\n# ClusterIP service test\n./integration/kind-test/scripts/run-tests.sh \"$CLUSTERIP_SERVICE\" \"ClusterSetIP\" $ADDRESS_TYPE\nexit_code=$?\nif [ \"$exit_code\" -ne 0 ] ; then\n    echo \"ERROR: Testing $CLUSTERIP_SERVICE failed\"\n    exit $exit_code\nfi\n\nsleep 5\n\n# Headless service test\n./integration/kind-test/scripts/run-tests.sh \"$HEADLESS_SERVICE\" \"Headless\" $ADDRESS_TYPE\nexit_code=$?\nif [ \"$exit_code\" -ne 0 ] ; then\n    echo \"ERROR: Testing $HEADLESS_SERVICE failed\"\n    exit $exit_code\nfi\n", "num_lines": 32}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Runs the AWS Cloud Map MCS Controller for K8s as a background process and tests services have been exported\n\nsource ./integration/kind-test/scripts/common.sh\nexport SERVICE=$1\nexport SERVICE_TYPE=$2\nexport IP_TYPE=$3\n\n# Deploy pods\n$KUBECTL_BIN apply -f \"$KIND_CONFIGS/e2e-deployment.yaml\"\n# Get deployment\ndeployment=$($KUBECTL_BIN get deployment --namespace \"$NAMESPACE\" -o json | jq -r '.items[0].metadata.name')\n\nprintf \"\\n***Testing Service: $SERVICE***\\n\"\n\n$KUBECTL_BIN apply -f \"$KIND_CONFIGS/$SERVICE.yaml\"\n\nif ! endpts=$(./integration/shared/scripts/poll-endpoints.sh \"$EXPECTED_ENDPOINT_COUNT\") ; then\n  exit $?\nfi\n\nmkdir -p \"$LOGS\"\n./bin/manager --zap-devel=true --zap-time-encoding=rfc3339 &> \"$LOGS/ctl.log\" &\nCTL_PID=$!\necho \"controller PID:$CTL_PID\"\n\ngo run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE $IP_TYPE \"$endpts\"\nexit_code=$?\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/shared/scripts/test-import.sh \"$EXPECTED_ENDPOINT_COUNT\" \"$endpts\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/kind-test/scripts/dns-test.sh \"$EXPECTED_ENDPOINT_COUNT\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/kind-test/scripts/curl-test.sh \"$deployment\"\n  exit_code=$?\nfi\n\necho \"sleeping...\"\nsleep 2\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  echo \"scaling the deployment $deployment to $UPDATED_ENDPOINT_COUNT\"\n  $KUBECTL_BIN scale deployment/\"$deployment\" --replicas=\"$UPDATED_ENDPOINT_COUNT\" --namespace \"$NAMESPACE\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  if ! updated_endpoints=$(./integration/shared/scripts/poll-endpoints.sh \"$UPDATED_ENDPOINT_COUNT\") ; then\n    exit $?\n  fi\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  go run $SCENARIOS/runner/main.go $NAMESPACE $SERVICE $CLUSTERID1 $CLUSTERSETID1 $ENDPT_PORT $SERVICE_PORT $SERVICE_TYPE $IP_TYPE \"$updated_endpoints\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/shared/scripts/test-import.sh \"$UPDATED_ENDPOINT_COUNT\" \"$updated_endpoints\"\n  exit_code=$?\nfi\n\nif [ \"$exit_code\" -eq 0 ] ; then\n  ./integration/kind-test/scripts/dns-test.sh \"$UPDATED_ENDPOINT_COUNT\"\n  exit_code=$?\nfi\n\necho \"Test Successful. Cleaning up...\"\n\n# Remove the deployment and delete service (should also delete ServiceExport)\nif [ \"$exit_code\" -eq 0 ] ; then\n  $KUBECTL_BIN delete -f \"$KIND_CONFIGS/e2e-deployment.yaml\"\n  $KUBECTL_BIN delete Service $SERVICE -n $NAMESPACE\n  # TODO: verify service export is not found\n  # TODO: verify cloudmap resources are cleaned up\nfi\n\necho \"killing controller PID:$CTL_PID\"\nkill $CTL_PID\nexit $exit_code\n", "num_lines": 89}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Builds the AWS Cloud Map MCS Controller for K8s, provisions a Kubernetes clusters with Kind,\n# installs Cloud Map CRDs and controller into the cluster and applies export and deployment configs.\n\nset -e\n\nsource ./integration/kind-test/scripts/common.sh\n\n./integration/kind-test/scripts/ensure-jq.sh\n\n# If the IP Type env var is not set, default it to IPv4\nif [[ -z \"${ADDRESS_TYPE}\" ]]; then\n  ADDRESS_TYPE=\"IPv4\"\nfi\n\necho \"ADDRESS_TYPE: $ADDRESS_TYPE\"\nif [[ $ADDRESS_TYPE == \"IPv4\" ]]; then\n  $KIND_BIN create cluster --name \"$KIND_SHORT\" --image \"$IMAGE\"\nelif [[ $ADDRESS_TYPE == \"IPv6\" ]]; then\n  $KIND_BIN create cluster --name \"$KIND_SHORT\" --image \"$IMAGE\" --config=./integration/kind-test/configs/ipv6.yaml\nelse\n  echo \"ADDRESS_TYPE invalid\"\nfi\n\n$KUBECTL_BIN config use-context \"$CLUSTER\"\nmake install\n\n# Install CoreDNS plugin\n$KUBECTL_BIN apply -f \"$SHARED_CONFIGS/coredns-clusterrole.yaml\"\n$KUBECTL_BIN apply -f \"$SHARED_CONFIGS/coredns-configmap.yaml\"\n$KUBECTL_BIN apply -f \"$KIND_CONFIGS/coredns-deployment.yaml\"\n\n# Add ClusterId and ClusterSetId\n$KUBECTL_BIN apply -f \"$KIND_CONFIGS/e2e-clusterproperty.yaml\"\n", "num_lines": 36}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Deletes all AWS Cloud Map resources used for integration test.\n\nset -eo pipefail\n\ngo run ./integration/janitor/runner/main.go \"$NAMESPACE\" \"$CLUSTERID1\" \"$CLUSTERSETID1\"\n", "num_lines": 8}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Poll for endpoints to become active\n\nset -e\n\nendpt_count=0\npoll_count=0\nwhile ((endpt_count < $1))\ndo\n  if ((poll_count++ > 30)) ; then\n    echo \"timed out polling for endpoints\" >&2\n    exit 1\n  fi\n\n  sleep 2\n  if ! addresses=$($KUBECTL_BIN get endpointslices -o json --namespace \"$NAMESPACE\" | \\\n    jq --arg SERVICE \"$SERVICE\" '.items[] | select(.metadata.ownerReferences[].name==$SERVICE) | .endpoints[].addresses[0]' 2> /dev/null)\n  then\n    # no endpoints ready\n    continue\n  fi\n\n  endpt_count=$(echo \"$addresses\" | wc -l | xargs)\ndone\n\necho \"$addresses\" | tr -d '\"' | paste -sd \",\" - \necho \"matched number of endpoints to expected count\" >&2\nexit 0\n", "num_lines": 30}
{"repo_name": "aws-cloud-map-mcs-controller-for-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Test service imports were created during e2e test\n\nset -e\n\nexpected_endpoint_count=$1\nendpoints=$2\necho \"checking service imports...\"\n\nimport_count=0\npoll_count=0\nwhile ((import_count < expected_endpoint_count))\ndo\n  sleep 1\n  if ((poll_count++ > 30)) ; then\n    echo \"timed out polling for import endpoints\"\n    exit 1\n  fi\n\n  imports=$($KUBECTL_BIN get endpointslices -o json --namespace $NAMESPACE | \\\n    jq '.items[] | select(.metadata.ownerReferences[].name | startswith(\"imported\")) | .endpoints[].addresses[0]')\n  echo \"import endpoint list from kubectl:\"\n  echo \"$imports\"\n\n  import_count=$(echo \"$imports\" | wc -l | xargs)\ndone\n\necho \"$imports\" | tr -d '\"' | while read -r import; do\n  echo \"checking import: $import\"\n  if ! echo \"$endpoints\" | grep -q \"$import\" ; then\n    echo \"exported endpoint not found: $import\"\n    exit 1\n  fi\ndone\n\nif [ $? -ne 0 ]; then\n    exit $?\nfi\n\necho \"matched all imports to exported endpoints\"\nexit 0\n", "num_lines": 43}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -r        Used to specify a report output directory.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:r:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        r  ) report_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run -it \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -n \"$report_dir\" ]\nthen\n    docker_command+=\" -e \\\"REPORTS=$(allOSRealPath \"$report_dir\")\\\"\"\nfi\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" $local_agent_image\"\nelse\n    docker_command+=\" public.ecr.aws/codebuild/local-builds:latest\"\nfi\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 206}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n  \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n  }\n  eof\n}\n", "num_lines": 15}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n  \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n  }\n  eof\n}\n", "num_lines": 15}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n  \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n  }\n  eof\n}\n", "num_lines": 15}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n", "num_lines": 23}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dind docker daemon \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://0.0.0.0:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://0.0.0.0:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://0.0.0.0:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://0.0.0.0:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect -f\n\nset timeout 1800\nset cmd [lindex $argv 0]\nset licenses [lindex $argv 1]\n\nspawn {*}$cmd\nexpect {\n    \"Do you accept the license '*'*\" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Accept? (y/N): \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    \"Review licenses that have not been accepted (y/N)? \" {\n        exp_send \"y\\r\"\n        exp_continue\n    }\n    eof\n}\n\nlassign [wait] pid spawnid os_error waitvalue\n\nif {$os_error == 0} {\n    exit $waitvalue\n} else {\n    exit 1\n}\n", "num_lines": 31}
{"repo_name": "aws-codebuild-docker-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay &>/var/log/docker.log &\n\n\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\neval \"$@\"\n", "num_lines": 24}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterAllowTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterBlockTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterInstall\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ApplicationStart\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ApplicationStop\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeAllowTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeBlockTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeInstall\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ValidateService\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterAllowTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterBlockTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"AfterInstall\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ApplicationStart\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ApplicationStop\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeAllowTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeBlockTraffic\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"BeforeInstall\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"CustomEvent\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-codedeploy-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"ValidateService\" >> $SCRIPT_DIR/../../../../../executed_proof_file\n", "num_lines": 5}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\n\n#\n# This assumes all of the OS-level configuration has been completed and git repo has already been cloned\n#\n# This script should be run from the repo's deployment directory\n# cd deployment\n# ./build-s3-dist.sh solution-name\n#\n# Paramenters:\n#  - solution-name: name of the solution for consistency\n\n# Check to see if input has been provided:\nif [ -z \"$1\" ]; then\n    echo \"Please provide the trademark approved solution name for the open source package.\"\n    echo \"For example: ./build-s3-dist.sh trademarked-solution-name\"\n    exit 1\nfi\n\n# Get reference for all important folders\nsource_template_dir=\"$PWD\"\ndist_dir=\"$source_template_dir/open-source\"\ndist_template_dir=\"$dist_dir/deployment\"\nsource_dir=\"$source_template_dir/../source\"\n\necho \"------------------------------------------------------------------------------\"\necho \"[Init] Clean old open-source folder\"\necho \"------------------------------------------------------------------------------\"\necho \"rm -rf $dist_dir\"\nrm -rf $dist_dir\necho \"mkdir -p $dist_dir\"\nmkdir -p $dist_dir\necho \"mkdir -p $dist_template_dir\"\nmkdir -p $dist_template_dir\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Templates\"\necho \"------------------------------------------------------------------------------\"\necho \"cp $source_template_dir/*.template $dist_template_dir/\"\ncp $source_template_dir/*.template $dist_template_dir/\necho \"copy yaml templates and rename\"\ncp $source_template_dir/*.yaml $dist_template_dir/\ncd $dist_template_dir\n# Rename all *.yaml to *.template\nfor f in *.yaml; do \n    mv -- \"$f\" \"${f%.yaml}.template\"\ndone\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Build Script\"\necho \"------------------------------------------------------------------------------\"\necho \"cp $source_template_dir/build-s3-dist.sh $dist_template_dir\"\ncp $source_template_dir/build-s3-dist.sh $dist_template_dir\necho \"cp $source_template_dir/run-unit-tests.sh $dist_template_dir\"\ncp $source_template_dir/run-unit-tests.sh $dist_template_dir\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Source Folder\"\necho \"------------------------------------------------------------------------------\"\necho \"cp -r $source_dir $dist_dir\"\ncp -r $source_dir $dist_dir\necho \"cp $source_template_dir/../LICENSE.txt $dist_dir\"\ncp $source_template_dir/../LICENSE.txt $dist_dir\necho \"cp $source_template_dir/../NOTICE.txt $dist_dir\"\ncp $source_template_dir/../NOTICE.txt $dist_dir\necho \"cp $source_template_dir/../README.md $dist_dir\"\ncp $source_template_dir/../README.md $dist_dir\necho \"cp $source_template_dir/../CODE_OF_CONDUCT.md $dist_dir\"\ncp $source_template_dir/../CODE_OF_CONDUCT.md $dist_dir\necho \"cp $source_template_dir/../CONTRIBUTING.md $dist_dir\"\ncp $source_template_dir/../CONTRIBUTING.md $dist_dir\necho \"cp $source_template_dir/../CHANGELOG.md $dist_dir\"\ncp $source_template_dir/../CHANGELOG.md $dist_dir\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Clean dist, node_modules and bower_components folders\"\necho \"------------------------------------------------------------------------------\"\necho \"find $dist_dir -iname \"node_modules\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\"\nfind $dist_dir -iname \"node_modules\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\necho \"find $dist_dir -iname \"tests\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\"\nfind $dist_dir -iname \"tests\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\necho \"find $dist_dir -iname \"dist\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\"\nfind $dist_dir -iname \"dist\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\necho \"find $dist_dir -iname \"bower_components\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\"\nfind $dist_dir -iname \"bower_components\" -type d -exec rm -r \"{}\" \\; 2> /dev/null\necho \"find ../ -type f -name 'package-lock.json' -delete\"\nfind $dist_dir -type f -name 'package-lock.json' -delete\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Create GitHub (open-source) zip file\"\necho \"------------------------------------------------------------------------------\"\necho \"cd $dist_dir\"\ncd $dist_dir\necho \"zip -q -r9 ../$1.zip *\"\nzip -q -r9 ../$1.zip *\necho \"Clean up open-source folder\"\necho \"rm -rf *\"\nrm -rf *\necho \"mv ../$1.zip .\"\nmv ../$1.zip .\necho \"Completed building $1.zip dist\"\n", "num_lines": 114}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\n\n#\n# This assumes all of the OS-level configuration has been completed and git repo has already been cloned\n#\n# This script should be run from the repo's deployment directory\n# cd deployment\n# ./build-s3-dist.sh source-bucket-base-name solution-name version-code\n#\n# Paramenters:\n#  - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda\n#    code from. The template will append '-[region_name]' to this bucket name.\n#    For example: ./build-s3-dist.sh solutions my-solution v1.0.0\n#    The template will then expect the source code to be located in the solutions-[region_name] bucket\n#\n#  - solution-name: name of the solution for consistency\n#\n#  - version-code: version of the package\n\n# Check to see if input has been provided:\nif [ -z \"$1\" ] || [ -z \"$2\" ] || [ -z \"$3\" ] || [ -z \"$4\" ] || [ -z \"$5\" ] || [ -z \"$6\" ]; then\n    echo \"Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside.\"\n    echo \"For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0\"\n    exit 1\nfi\n\n# Get reference for all important folders\ntemplate_dir=\"$PWD\"\ntemplate_dist_dir=\"$template_dir/global-s3-assets\"\nbuild_dist_dir=\"$template_dir/regional-s3-assets\"\nsource_dir=\"$template_dir/../source\"\n\necho \"------------------------------------------------------------------------------\"\necho \"[Init] Clean old dist, node_modules and bower_components folders\"\necho \"------------------------------------------------------------------------------\"\necho \"rm -rf $template_dist_dir\"\nrm -rf $template_dist_dir\necho \"mkdir -p $template_dist_dir\"\nmkdir -p $template_dist_dir\necho \"rm -rf $build_dist_dir\"\nrm -rf $build_dist_dir\necho \"mkdir -p $build_dist_dir\"\nmkdir -p $build_dist_dir\n\necho \"------------------------------------------------------------------------------\"\necho \"[Rebuild] Bundle Application\"\necho \"------------------------------------------------------------------------------\"\nrepositoryRegion=''\n\nif [ -n \"$6\" ]; then\n    repositoryRegion=\"-R $6\"\nfi\n\nrepositoryUri=\"$5\"\ncd \"$source_dir/packages/services/simulation-launcher/src/containers/jmeter/infrastructure\"\n./deploy.bash -b -r $repositoryUri $repositoryRegion\n\ncd $source_dir\nrush bundle\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Templates\"\necho \"------------------------------------------------------------------------------\"\n\n# copy all the cfn templates in the source/infrastructure dir\ncp $source_dir/infrastructure/cfn-*.yaml $template_dist_dir/\n# copy all the cfn templates in source/infrastructure/cloudformation dir\ncp $source_dir/infrastructure/cloudformation/cfn-*.yaml $template_dist_dir/\n# copy all the cfn templates in source/infrastructure/lambdaLayers/openssl/infrastructure\ncp $source_dir/infrastructure/lambdaLayers/openssl/infrastructure/cfn-*.yml $template_dist_dir/\n# copy all the cfn templates ending in yml in source/package/*/infrastructure\ncp $source_dir/packages/services/*/infrastructure/cfn-*.yml $template_dist_dir/\n# copy all the cfn templates ending in yaml in source/package/*/infrastructure\ncp $source_dir/packages/services/*/infrastructure/cfn-*.yaml $template_dist_dir/\n# copy all cfn template snippets\ncp -a $source_dir/infrastructure/cloudformation/snippets/ $template_dist_dir/snippets/\n# copy all cfn templates in libraries/core\ncp $source_dir/packages/libraries/core/*/infrastructure/cfn-*.yaml $template_dist_dir/\n\ncd $template_dist_dir\n# Rename all *.yaml to *.template\nfor f in *.yaml; do\n    mv -- \"$f\" \"${f%.yaml}.template\"\ndone\n\n# Rename all *.yml to *.template\nfor f in *.yml; do\n    mv -- \"$f\" \"${f%.yml}.template\"\ndone\n\n# remove non-release templates\nrm $template_dist_dir/cfn-auth-jwt.template\nrm $template_dist_dir/cfn-auth-devicecert.template\n\n\n# override the S3 Code Uri and TemplateURL for the cfn templates to point to a S3 location\nfor f in *.template; do\n    if [ -f \"../transforms/${f%.*}.yaml\" ]; then\n        yq w -i -s \"../transforms/${f%.*}.yaml\" \"$f\"\n    fi\ndone\n\ncd ..\necho \"Updating code source bucket in template with $1\"\nreplace=\"s/%%BUCKET_NAME%%/$1/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\nreplace=\"s/%%SOLUTION_NAME%%/$2/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\nreplace=\"s/%%VERSION%%/$3/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\n\nreplace=\"s/%%TEMPLATE_BUCKET_NAME%%/$4/g\"\nsed -i '' -e $replace $template_dist_dir/*.template\n\n\necho \"------------------------------------------------------------------------------\"\necho \"[Rebuild] Package Dists\"\necho \"------------------------------------------------------------------------------\"\n\n\n# Copy and rename dists\ncd $build_dist_dir\ncp $source_dir/packages/libraries/core/deployment-helper/bundle.zip $build_dist_dir/cdf-deployment-helper.zip\ncp $source_dir/infrastructure/lambdaLayers/openssl/build/build.zip $build_dist_dir/cdf-openssl-layer.zip\ncp $source_dir/packages/services/assetlibrary/bundle.zip $build_dist_dir/cdf-assetLibrary.zip\ncp $source_dir/packages/services/assetlibraryhistory/bundle.zip $build_dist_dir/cdf-assetLibrary-history.zip\ncp $source_dir/packages/services/assetlibrary-export/bundle.zip $build_dist_dir/cdf-assetLibrary-export.zip\ncp $source_dir/packages/services/provisioning/bundle.zip $build_dist_dir/cdf-provisioning.zip\ncp $source_dir/packages/services/commands/bundle.zip $build_dist_dir/cdf-commands.zip\ncp $source_dir/packages/services/device-monitoring/bundle.zip $build_dist_dir/cdf-device-monitoring.zip\ncp $source_dir/packages/services/events-processor/bundle.zip $build_dist_dir/cdf-events-processor.zip\ncp $source_dir/packages/services/events-alerts/bundle.zip $build_dist_dir/cdf-events-alerts.zip\ncp $source_dir/packages/services/bulkcerts/bundle.zip $build_dist_dir/cdf-bulkcerts.zip\ncp $source_dir/packages/services/certificateactivator/bundle.zip $build_dist_dir/cdf-certificate-activator.zip\ncp $source_dir/packages/services/certificatevendor/bundle.zip $build_dist_dir/cdf-certificate-vendor.zip\ncp $source_dir/packages/services/simulation-launcher/bundle.zip $build_dist_dir/cdf-simulation-launcher.zip\ncp $source_dir/packages/services/simulation-manager/bundle.zip $build_dist_dir/cdf-simulation-manager.zip\ncp $source_dir/packages/services/device-patcher/bundle.zip $build_dist_dir/cdf-device-patcher.zip\ncp $source_dir/packages/services/greengrass2-provisioning/bundle.zip $build_dist_dir/cdf-greengrass2-provisioning.zip\ncp $source_dir/packages/services/greengrass2-installer-config-generators/bundle.zip $build_dist_dir/cdf-greengrass2-installer-config-generators.zip\n\n\n", "num_lines": 158}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\n\n#\n# This assumes all of the OS-level configuration has been completed and git repo has already been cloned\n#\n# This script should be run from the repo's deployment directory\n# cd deployment\n# ./run-unit-tests.sh\n#\n\n# Get reference for all important folders\ntemplate_dir=\"$PWD\"\nsource_dir=\"$template_dir/../source\"\n\n# note:  pnpm@3.5.7 has broken tsc\necho installing rush\nnpm i -g @microsoft/rush\n\necho installing jq...\ncurl -s -qL -o /usr/bin/jq https://stedolan.github.io/jq/download/linux64/jq\nchmod +x /usr/bin/jq\n\necho installing yq\ncurl -s -qL -o /usr/bin/yq https://github.com/mikefarah/yq/releases/download/3.4.0/yq_linux_amd64\nchmod +x /usr/bin/yq\n\naws --version\nyq --version\njq --version\ndocker --version\n", "num_lines": 43}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\n\n#\n# This assumes all of the OS-level configuration has been completed and git repo has already been cloned\n#\n# This script should be run from the repo's deployment directory\n# cd deployment\n# ./build-s3-dist.sh source-bucket-base-name solution-name version-code\n#\n# Parameters:\n#  - source-bucket-base-name: Name for the S3 bucket location where the template will source the Lambda\n#    code from. The template will append '-[region_name]' to this bucket name.\n#    For example: ./build-s3-dist.sh solutions my-solution v1.0.0\n#    The template will then expect the source code to be located in the solutions-[region_name] bucket\n#\n#  - solution-name: name of the solution for consistency\n#\n#  - version-code: version of the package\n\n# Check to see if input has been provided:\nif [ -z \"$1\" ] || [ -z \"$2\" ] || [ -z \"$3\" ] || [ -z \"$4\" ] ; then\n    echo \"Please provide the base source bucket name, trademark approved solution name and version where the lambda code will eventually reside.\"\n    echo \"For example: ./build-s3-dist.sh solutions trademarked-solution-name v1.0.0\"\n    exit 1\nfi\n\n# Get reference for all important folders\ntemplate_dir=\"$PWD\"\ntemplate_dist_dir=\"$template_dir/global-s3-assets\"\nbuild_dist_dir=\"$template_dir/regional-s3-assets\"\nsource_dir=\"$template_dir/../source\"\n\necho \"------------------------------------------------------------------------------\"\necho \"[Init] Clean old dist, node_modules and bower_components folders\"\necho \"------------------------------------------------------------------------------\"\necho \"rm -rf $template_dist_dir\"\nrm -rf $template_dist_dir\necho \"mkdir -p $template_dist_dir\"\nmkdir -p $template_dist_dir\necho \"rm -rf $build_dist_dir\"\nrm -rf $build_dist_dir\necho \"mkdir -p $build_dist_dir\"\nmkdir -p $build_dist_dir\n\n\necho \"------------------------------------------------------------------------------\"\necho \"[Packing] Templates\"\necho \"------------------------------------------------------------------------------\"\n\n# copy all the cfn templates in the source/infrastructure dir\ncp $source_dir/infrastructure/cfn-sample-tenant-component.yaml $template_dist_dir/\n# copy all the cfn templates in source/infrastructure/lambdaLayers/openssl/infrastructure\ncp $source_dir/infrastructure/lambdaLayers/openssl/infrastructure/cfn-*.yml $template_dist_dir/\n# copy all the cfn templates ending in yml in source/package/*/infrastructure\ncp $source_dir/packages/services/*/infrastructure/cfn-command-and-control.yml $template_dist_dir/\n# copy all cfn template snippets\ncp -a $source_dir/infrastructure/cloudformation/snippets/ $template_dist_dir/snippets/\n# copy all cfn templates in libraries/core\ncp $source_dir/packages/libraries/core/*/infrastructure/cfn-deployment-helper.yaml $template_dist_dir/\n\ncd \"$template_dist_dir\"\n# Rename all *.yaml to *.template\nfor f in *.yaml; do\n    mv -- \"$f\" \"${f%.yaml}.template\"\ndone\n\n# Rename all *.yml to *.template\nfor f in *.yml; do\n    mv -- \"$f\" \"${f%.yml}.template\"\ndone\n\n# remove non-release templates\nrm \"$template_dist_dir\"/cfn-auth-jwt.template\nrm \"$template_dist_dir\"/cfn-auth-devicecert.template\nrm \"$template_dist_dir\"/cfn-cdf-core*\nrm \"$template_dist_dir\"/cfn-bastion-host.template\n\n# override the S3 Code Uri and TemplateURL for the cfn templates to point to a S3 location\nfor f in *.template; do\n    if [ -f \"../transforms/${f%.*}.yaml\" ]; then\n      # Below only works in yq version 3.4.1\n      yq w -i -s \"../transforms/${f%.*}.yaml\" \"$f\"\n    fi\ndone\n\ncd ..\necho \"Updating code source bucket in template with $1\"\nreplace=\"s/%%BUCKET_NAME%%/$1/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\nreplace=\"s/%%SOLUTION_NAME%%/$2/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\nreplace=\"s/%%VERSION%%/$3/g\"\necho \"sed -i '' -e $replace $template_dist_dir/*.template\"\nsed -i '' -e $replace $template_dist_dir/*.template\n\nreplace=\"s/%%TEMPLATE_BUCKET_NAME%%/$4/g\"\nsed -i '' -e $replace $template_dist_dir/*.template\n\n\necho \"------------------------------------------------------------------------------\"\necho \"[Rebuild] Package Dists\"\necho \"------------------------------------------------------------------------------\"\n\n# Copy and rename dists\ncd $build_dist_dir\ncp $source_dir/packages/libraries/core/deployment-helper/bundle.zip $build_dist_dir/cdf-deployment-helper.zip\ncp $source_dir/infrastructure/lambdaLayers/openssl/build/build.zip $build_dist_dir/cdf-openssl-layer.zip\ncp $source_dir/packages/services/provisioning/bundle.zip $build_dist_dir/cdf-provisioning.zip\ncp $source_dir/packages/services/command-and-control/bundle.zip $build_dist_dir/cdf-command-and-control.zip\n\n", "num_lines": 125}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Export the sheets/tabs of cdf-core-hla.drawio as PNG files for embedding in readme and documentation\n# files. This script assumes that the draw.io executable is installed locally and available on the PATH. \n# See https://github.com/jgraph/drawio-desktop/ for draw.io installers.\n#\n# Unused HLA diagrams in cdf-core-hla.drawio (tab index, CDF module name):\n# 5 Commands (deprecated)\n# 11 Certificate Renewer\n\ndraw.io --export --format png --page-index 0 --output \"./cdf-core-hla-lifecycle.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"./cdf-core-hla-lifecycle.png.license\"\ndraw.io --export --format png --page-index 1 --output \"./cdf-core-hla-HLA.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"./cdf-core-hla-HLA.png.license\"\ndraw.io --export --format png --page-index 2 --output \"./cdf-core-hla-hla-aws.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"./cdf-core-hla-hla-aws.png.license\"\ndraw.io --export --format png --page-index 3 --output \"../../packages/services/assetlibrary/docs/images/cdf-core-hla-Asset Library.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/assetlibrary/docs/images/cdf-core-hla-Asset Library.png.license\"\ndraw.io --export --format png --page-index 4 --output \"../../packages/services/bulkcerts/docs/images/bulkcerts.hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/bulkcerts/docs/images/bulkcerts.hla.png.license\"\ndraw.io --export --format png --page-index 6 --output \"../../packages/services/device-patcher/docs/images/device-patcher-hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/device-patcher/docs/images/device-patcher-hla.png.license\"\ndraw.io --export --format png --page-index 7 --output \"../../packages/services/greengrass2-provisioning/docs/images/greengrass2-hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/greengrass2-provisioning/docs/images/greengrass2-hla.png.license\"\ndraw.io --export --format png --page-index 8 --output \"../../packages/services/provisioning/docs/images/provisioning.hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/provisioning/docs/images/provisioning.hla.png.license\"\ndraw.io --export --format png --page-index 9 --output \"../../packages/services/certificateactivator/docs/images/certificateactivator-hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/certificateactivator/docs/images/certificateactivator-hla.png.license\"\ndraw.io --export --format png --page-index 10 --output \"../../packages/services/certificatevendor/docs/images/certificatevendor-hla.png\" cdf-core-hla.drawio\ncp cdf-core-hla.drawio.license \"../../packages/services/certificatevendor/docs/images/certificatevendor-hla.png.license\"\n", "num_lines": 31}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\n\nexport JMETER_VERSION=\"5.4.3\"\nexport AWSCLI_VERSION=\"1.16.278\"\nexport JMETER_PLUGINS_MANAGER_VERSION=\"1.3\"\nexport CMDRUNNER_VERSION=\"2.2\"\nexport JSON_LIB_VERSION=\"2.4\"\nexport JSON_LIB_FULL_VERSION=\"${JSON_LIB_VERSION}-jdk15\"\n\nexport JMETER_HOME=/opt/apache-jmeter-${JMETER_VERSION}\nexport JMETER_BIN=${JMETER_HOME}/bin\nexport PATH=$PATH:$JMETER_BIN\nexport JMETER_DOWNLOAD_URL=https://archive.apache.org/dist/jmeter/binaries/apache-jmeter-${JMETER_VERSION}.tgz\nexport RESULTS_LOG=results.jtl\nexport PATH=/root/.local/bin:$PATH\n\n# install aws cli\napk add --update \\\n    python \\\n    python-dev \\\n    py-pip \\\n    build-base \\\n    && pip install awscli==$AWSCLI_VERSION --upgrade --user \\\n    && apk --purge -v del py-pip \\\n    && rm -rf /var/cache/apk/*\n\n# Install jmeter\napk update \\\n\t&& apk upgrade \\\n\t&& apk add ca-certificates \\\n\t&& update-ca-certificates \\\n\t&& apk add --update openjdk8-jre tzdata curl unzip bash \\\n\t&& apk add --no-cache nss \\\n\t&& rm -rf /var/cache/apk/* \\\n\t&& mkdir -p /tmp/dependencies  \\\n\t&& curl -L --silent ${JMETER_DOWNLOAD_URL} >  /tmp/dependencies/apache-jmeter-${JMETER_VERSION}.tgz  \\\n\t&& mkdir -p /opt  \\\n\t&& tar -xzf /tmp/dependencies/apache-jmeter-${JMETER_VERSION}.tgz -C /opt  \\\n\t&& rm -rf /tmp/dependencies\n\n# Install jmeter plugins\ncd /tmp/ \\\n && curl --location --silent --show-error --output ${JMETER_HOME}/lib/ext/jmeter-plugins-manager-${JMETER_PLUGINS_MANAGER_VERSION}.jar http://search.maven.org/remotecontent?filepath=kg/apc/jmeter-plugins-manager/${JMETER_PLUGINS_MANAGER_VERSION}/jmeter-plugins-manager-${JMETER_PLUGINS_MANAGER_VERSION}.jar \\\n && curl --location --silent --show-error --output ${JMETER_HOME}/lib/cmdrunner-${CMDRUNNER_VERSION}.jar http://search.maven.org/remotecontent?filepath=kg/apc/cmdrunner/${CMDRUNNER_VERSION}/cmdrunner-${CMDRUNNER_VERSION}.jar \\\n && curl --location --silent --show-error --output ${JMETER_HOME}/lib/json-lib-${JSON_LIB_FULL_VERSION}.jar https://search.maven.org/remotecontent?filepath=net/sf/json-lib/json-lib/${JSON_LIB_VERSION}/json-lib-${JSON_LIB_FULL_VERSION}.jar \\\n && curl --location --silent --show-error --output ${JMETER_HOME}/lib/ext/mqtt-xmeter-1.0.1-jar-with-dependencies.jar https://github.com/emqx/mqtt-jmeter/releases/download/1.0.1/mqtt-xmeter-1.0.1-jar-with-dependencies.jar \\\n && java -cp ${JMETER_HOME}/lib/ext/jmeter-plugins-manager-${JMETER_PLUGINS_MANAGER_VERSION}.jar org.jmeterplugins.repository.PluginManagerCMDInstaller \\\n && PluginsManagerCMD.sh install \\\nblazemeter-debugger=0.6,\\\nbzm-hls=2.0,\\\nbzm-http2=1.4.1,\\\nbzm-parallel=0.9,\\\nbzm-random-csv=0.6,\\\nbzm-rte=2.2,\\\nbzm-siebel=0.1.0-beta,\\\ncustom-soap=1.3.3,\\\njmeter.backendlistener.elasticsearch=2.6.9,\\\njmeter.backendlistener.kafka=1.0.0,\\\njmeter.pack-listener=1.7,\\\njpgc-autostop=0.1,\\\njpgc-casutg=2.9,\\\njpgc-cmd=2.2,\\\njpgc-csl=0.1,\\\njpgc-csvars=0.1,\\\njpgc-dbmon=0.1,\\\njpgc-directory-listing=0.3,\\\njpgc-dummy=0.4,\\\njpgc-ffw=2.0,\\\njpgc-fifo=0.2,\\\njpgc-filterresults=2.2,\\\njpgc-functions=2.1,\\\njpgc-ggl=2.0,\\\njpgc-graphs-additional=2.0,\\\njpgc-graphs-basic=2.0,\\\njpgc-graphs-composite=2.0,\\\njpgc-graphs-dist=2.0,\\\njpgc-graphs-vs=2.0,\\\njpgc-hadoop=2.0,\\\njpgc-httpraw=0.1,\\\njpgc-jms=0.2,\\\njpgc-jmxmon=0.2,\\\njpgc-json=2.7,\\\njpgc-lockfile=0.1,\\\njpgc-mergeresults=2.1,\\\njpgc-pde=0.1,\\\njpgc-perfmon=2.1,\\\njpgc-plancheck=2.4,\\\njpgc-prmctl=0.4,\\\njpgc-redis=0.3,\\\njpgc-rotating-listener=0.2,\\\njpgc-sense=3.5,\\\njpgc-standard=2.0,\\\njpgc-sts=2.4,\\\njpgc-synthesis=2.2,\\\njpgc-tst=2.5,\\\njpgc-udp=0.4,\\\njpgc-webdriver=3.1,\\\njpgc-wsc=0.7,\\\njpgc-xml=0.1,\\\njpgc-xmpp=1.5.1,\\\nkafkameter=0.2.0,\\\nnetflix-cassandra=0.2-SNAPSHOT,\\\nssh-sampler=1.1.1-SNAPSHOT,\\\ntilln-iso8583=1.0,\\\ntilln-sshmon=1.2,\\\ntilln-wssecurity=1.7,\\\nwebsocket-sampler=1.0.2-SNAPSHOT,\\\nwebsocket-samplers=1.2.2 \\\n && jmeter --version \\\n && PluginsManagerCMD.sh status \\\n && chmod +x ${JMETER_HOME}/bin/*.sh \\\n && rm -fr /tmp/*\n\n##### # node setup\n\nexport VERSION=v8.16.2 \nexport NPM_VERSION=6 \n\napk add --no-cache curl make gcc g++ python linux-headers binutils-gold gnupg libstdc++ && \\\n  for server in ipv4.pool.sks-keyservers.net keyserver.pgp.com ha.pool.sks-keyservers.net; do \\\n    gpg --keyserver $server --recv-keys \\\n      4ED778F539E3634C779C87C6D7062848A1AB005C \\\n      B9E2F5981AA6E0CD28160D9FF13993A75599653C \\\n      94AE36675C464D64BAFA68DD7434390BDBE9B9C5 \\\n      B9AE9905FFD7803F25714661B63B535A4C206CA9 \\\n      77984A986EBC2AA786BC0F66B01FBB92821C587A \\\n      71DCFD284A79C3B38668286BC97EC7A07EDE3FC1 \\\n      FD3A5288F042B6850C66B31F09FE44734EB7990E \\\n      8FCCA13FEF1D0C2E91008E09770F7A9A5AE15600 \\\n      C4F0DFFF4E8C1A8236409D08E73BC641CC11F4C8 \\\n      DD8F2338BAE7501E3DD5AC78C273792F7D83545D \\\n      A48C2BEE680E841632CD4E44F07496B3EB3C1762 && break; \\\n  done && \\\n  curl -sfSLO https://nodejs.org/dist/${VERSION}/node-${VERSION}.tar.xz && \\\n  curl -sfSL https://nodejs.org/dist/${VERSION}/SHASUMS256.txt.asc | gpg -d -o SHASUMS256.txt && \\\n  grep \" node-${VERSION}.tar.xz\\$\" SHASUMS256.txt | sha256sum -c | grep ': OK$' && \\\n  tar -xf node-${VERSION}.tar.xz && \\\n  cd node-${VERSION} && \\\n  ./configure --prefix=/usr ${CONFIG_FLAGS} && \\\n  make -j$(getconf _NPROCESSORS_ONLN) && \\\n  make install && \\\n  cd / && \\\n  if [ -z \"$CONFIG_FLAGS\" ]; then \\\n    if [ -n \"$NPM_VERSION\" ]; then \\\n      npm install -g npm@${NPM_VERSION}; \\\n    fi; \\\n    find /usr/lib/node_modules/npm -name test -o -name .bin -type d | xargs rm -rf; \\\n    if [ -n \"$YARN_VERSION\" ]; then \\\n      for server in ipv4.pool.sks-keyservers.net keyserver.pgp.com ha.pool.sks-keyservers.net; do \\\n        gpg --keyserver $server --recv-keys \\\n          6A010C5166006599AA17F08146C2130DFD2497F5 && break; \\\n      done && \\\n      curl -sfSL -O https://yarnpkg.com/${YARN_VERSION}.tar.gz -O https://yarnpkg.com/${YARN_VERSION}.tar.gz.asc && \\\n      gpg --batch --verify ${YARN_VERSION}.tar.gz.asc ${YARN_VERSION}.tar.gz && \\\n      mkdir /usr/local/share/yarn && \\\n      tar -xf ${YARN_VERSION}.tar.gz -C /usr/local/share/yarn --strip 1 && \\\n      ln -s /usr/local/share/yarn/bin/yarn /usr/local/bin/ && \\\n      ln -s /usr/local/share/yarn/bin/yarnpkg /usr/local/bin/ && \\\n      rm ${YARN_VERSION}.tar.gz*; \\\n    fi; \\\n  fi && \\\n  apk del curl make gcc g++ python linux-headers binutils-gold gnupg ${DEL_PKGS} && \\\n  rm -rf ${RM_DIRS} /node-${VERSION}* /SHASUMS256.txt /tmp/* /var/cache/apk/* \\\n    /usr/share/man/* /usr/share/doc /root/.npm /root/.node-gyp /root/.config \\\n    /usr/lib/node_modules/npm/man /usr/lib/node_modules/npm/doc /usr/lib/node_modules/npm/html /usr/lib/node_modules/npm/scripts && \\\n  { rm -rf /root/.gnupg || true; }\n\n\n", "num_lines": 181}
{"repo_name": "aws-connected-device-framework", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n#-----------------------------------------------------------------------------------------------------------------------\n#   Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n#  Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n#  with the License. A copy of the License is located at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n#  or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES\n#  OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions\n#  and limitations under the License.\n#-----------------------------------------------------------------------------------------------------------------------\nset -x\n\nfreeMem=`awk '/MemFree/ { print int($2/1024) }' /proc/meminfo`\ns=$(($freeMem/10*8))\nx=$(($freeMem/10*8))\nn=$(($freeMem/10*2))\nexport JVM_ARGS=\"-Xmn${n}m -Xms${s}m -Xmx${x}m\"\n\necho \"START Running Jmeter on `date`\"\necho \"JVM_ARGS=${JVM_ARGS}\"\necho \"jmeter args=$@\"\n\n# empty the logs directory, or jmeter may fail\nrm -rf /opt/jmeter/*.log /opt/jmeter/*.jtl\n\nrm -rf \"$JMETER_BIN/cdf\"\nmkdir -p \"$JMETER_BIN/cdf\"\n\n# download the test plan and properties from S3\naws s3 cp \"s3://$BUCKET/$TEST_PLAN\" \"$JMETER_BIN/cdf/plan.jmx\"\naws s3 cp \"s3://$BUCKET/$EXTERNAL_PROPERTIES\" \"$JMETER_BIN/cdf/config.properties\"\n\n# launch jmeter\nset +e\ncd /opt/jmeter\njmeter -n $JMETER_FLAGS \\\n  -p \"$JMETER_BIN/cdf/config.properties\" \\\n  -l results.jtl \\\n  -j logfile.txt \\\n  -t \"$JMETER_BIN/cdf/plan.jmx\" \\\n  || true\n\n# need to wait for jmeter to finish writing to the logs once it shuts down\nsleep 5\n\n# upload logs and results to s3\naws s3 cp logfile.txt \"s3://$BUCKET/$UPLOAD_DIR\"logfile.txt\naws s3 cp results.jtl \"s3://$BUCKET/$UPLOAD_DIR\"results.jtl\n\necho \"Logs....\"\ncat logfile.txt\n\necho \"Results...\"\ncat results.jtl\n", "num_lines": 58}
{"repo_name": "aws-database-encryption-sdk-dynamodb-java", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ \"$1\" == \"implementation\" ]]; then\n  mkdir -p runtimes/java/src/main/dafny-generated\n  for directory in runtimes/java/temp/AwsCryptographyDbEncryptionSdkDynamoDbMiddlewareInternal-java/*; do\n    mv \"$directory\" \"runtimes/java/src/main/dafny-generated/\"\n  done\n  exit 0\nelif [[ \"$1\" == \"test\" ]]; then\n  # With the runAllTests flag, dafny generates an entry point for the tests that we want,\n  # so we copy all files to the test destination.\n  mkdir -p runtimes/java/src/test/dafny-generated\n  for allFiles in runtimes/java/temp-tests/AwsCryptographyDbEncryptionSdkDynamoDbMiddlewareInternalTests-java/*; do\n    mv \"$allFiles\" \"runtimes/java/src/test/dafny-generated/\"\n  done\n  exit 0\nelse\n  echo \"makefile_helper needs either implementation or test argument\"\n  echo \"i.e: ./runtimes/java/makefile_helper.sh test\"\n  exit 1\nfi\n", "num_lines": 22}
{"repo_name": "aws-dotnet-deploy", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ndotnet build AWS.Deploy.sln --configuration Release\n\ndotnet test AWS.Deploy.sln --no-build\n", "num_lines": 6}
{"repo_name": "aws-dynamodb-encryption-python", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Minimal wrapper script for upstream requirements install and freeze.\n# We do this here rather than as tox commands because tox does not support output redirection.\nif [ -z ${1} ]; then\n    exit 1\nfi\n\npip install -r requirements.txt\npip install -r dev_requirements/test-requirements.txt\npip freeze > ${1}\n", "num_lines": 11}
{"repo_name": "aws-dynamodb-encryption-python", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Verify that tests can be successfully run from the source build.\n#\n#NOTE: Humans should not run this file directly. If you want to run this check, use the\n#   tox to run the \"sourcebuildcheck\" test environment.\n\nWORKINGDIR=${1}\nDISTDIR=${2}\n\necho \"Performing source build check\"\necho \"Using working directory ${WORKINGDIR}\"\necho \"Using dist directory ${DISTDIR}\"\n\necho \"Locating the source build and copying it into the working directory.\"\nDISTFILE=$(ls ${DISTDIR}/dynamodb-encryption-sdk-*.tar.gz | tail -1)\necho \"Found source build at ${DISTFILE}\"\ncp ${DISTFILE} ${WORKINGDIR}\n\necho \"Extracting the source build.\"\ncd ${WORKINGDIR}\nNEWDISTFILE=$(ls dynamodb-encryption-sdk-*.tar.gz | tail -1)\necho \"Using distfile ${NEWDISTFILE}\"\ntar xzvf ${NEWDISTFILE}\nrm ${NEWDISTFILE}\nEXTRACTEDDIR=$(ls | tail -1)\ncd ${EXTRACTEDDIR}\n\necho \"Installing requirements from extracted source build.\"\npip install -r dev_requirements/test-requirements.txt\npip install -e .\n\necho \"Running tests from extracted source build.\"\npytest --cov dynamodb_encryption_sdk -m \"local and not slow and not veryslow and not nope\"\n", "num_lines": 34}
{"repo_name": "aws-eb-glassfish-dockerfiles", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ndefaultVersion=4.1-jdk8\n\nversions=( 4.0-jdk7 4.1-jdk8 )\nurl='git://github.com/aws/aws-eb-glassfish'\n\necho '# maintainer: Amazon Web Services <https://aws.amazon.com/contact-us/> (@aws)'\n\nfor version in \"${versions[@]}\"; do\n\tcommit=\"$(git log -1 --format='format:%H' -- \"$version\")\"\n\t\n\tglassfishVersion=\"${version%%-*}\"\n\tjdkVersion=\"${version#*-}\" # \"jdk7\"\n\t\n\tversionAliases=( $glassfishVersion-$jdkVersion $glassfishVersion) # 4.0-jdk7 4.0\n\t\n\tif [ \"$glassfishVersion-$jdkVersion\" = \"$defaultVersion\" ]; then\n\t\tversionAliases+=( latest )\n\tfi\n\t\n\techo\n\tfor va in \"${versionAliases[@]}\"; do\n\t\techo \"$va: ${url}@${commit} $version\"\n\tdone\ndone\n", "num_lines": 28}
{"repo_name": "aws-eb-glassfish-dockerfiles", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPID_FILE=$GLASSFISH_HOME/glassfish/domains/domain1/config/pid\n\n# when deploying a directory, Glassfish expect all submodules to be extracted\n# which is usually not the case for EARs\n# zip app back into a bundle and let Glassfish handle it\nrm -f /var/app/Dockerfile\nrm -f /var/app/Dockerrun.aws.json\nzip /var/app.zip -r .\n\nasadmin start-domain\nasadmin deploy --contextroot / --name current-app /var/app.zip\n\ninotifywait -qq -e delete_self $PID_FILE\n\n", "num_lines": 17}
{"repo_name": "aws-eb-glassfish-dockerfiles", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPID_FILE=$GLASSFISH_HOME/glassfish/domains/domain1/config/pid\n\n# when deploying a directory, Glassfish expect all submodules to be extracted\n# which is usually not the case for EARs\n# zip app back into a bundle and let Glassfish handle it\nrm -f /var/app/Dockerfile\nrm -f /var/app/Dockerrun.aws.json\nzip /var/app.zip -r .\n\nasadmin start-domain\nasadmin deploy --contextroot / --name current-app /var/app.zip\n\ninotifywait -qq -e delete_self $PID_FILE\n\n", "num_lines": 17}
{"repo_name": "aws-eb-glassfish-dockerfiles", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPID_FILE=$GLASSFISH_HOME/glassfish/domains/domain1/config/pid\n\n# when deploying a directory, Glassfish expect all submodules to be extracted\n# which is usually not the case for EARs\n# zip app back into a bundle and let Glassfish handle it\nrm -f /var/app/Dockerfile\nrm -f /var/app/Dockerrun.aws.json\nzip -r /var/app.zip .\n\nasadmin start-domain\nasadmin deploy --contextroot / --name current-app /var/app.zip\n\ninotifywait -qq -e delete_self $PID_FILE\n", "num_lines": 16}
{"repo_name": "aws-eb-python-dockerfiles", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /var/app\n\n. bin/activate\n\n# Django support\nif cat requirements.txt | grep -q -i Django && [ -z \"$WSGI_PATH\" ]; then\n\tWSGI_PATH=`find /var/app | egrep '/var/app/[^/]+/wsgi.py'`\nfi\n\n# Flask support\nif cat requirements.txt | grep -q -i Flask && [ -z \"$WSGI_MODULE\" ]; then\n\tWSGI_MODULE=application:app\nfi\n\n[ -n \"$WSGI_MODULE\" ] && UWSGI_MODULE=\"--module $WSGI_MODULE\"\n\n# defaulting to application.py if not explicitly set\n[ -z \"$WSGI_PATH\" ] && WSGI_PATH=application.py\n\nuwsgi --http :8080 --chdir /var/app --wsgi-file $WSGI_PATH $UWSGI_MODULE --master --processes $UWSGI_NUM_PROCESSES --threads $UWSGI_NUM_THREADS --uid $UWSGI_UID --gid $UWSGI_GID --logto2 $UWSGI_LOG_FILE\n\n", "num_lines": 24}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Runs our full suite of integration tests against all known instance types\n\n# Basic string concat w/ newline\nconcat () {\n    printf \"%s\\n%s\" \"${1}\" \"${2}\"\n}\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd)\")\n\nif [ $# -lt 8 ] ; then\n    echo \"Usage: $0 -r region -a ami -k ec2-key-pair -s subnet -g security-group -p /private/key/path -u ec2-os-user -l ami-linux-distro-name -i /path/to/package/file [-d /test/output/directory] [-t instance,types,list]\"\n    exit 1\nfi\n\ntypes_specified=0\n\nwhile getopts \":r:a:k:s:g:d:p:t:u:l:i:\" opt ; do\n    case \"${opt}\" in\n        r)\n            region=\"${OPTARG}\"\n            ;;\n        a)\n            ami_id=\"${OPTARG}\"\n            ;;\n        k)\n            key_name=\"${OPTARG}\"\n            ;;\n        s)\n            subnet_id=\"${OPTARG}\"\n            ;;\n        g)\n            security_group_id=\"${OPTARG}\"\n            ;;\n        d)\n            output_directory=\"${OPTARG}\"\n            ;;\n        p)\n            private_key=\"${OPTARG}\"\n            ;;\n        t)\n            IFS=',' read -r -a instance_types <<< \"${OPTARG}\"\n            types_specified=1\n            ;;\n        u)\n            osuser=\"${OPTARG}\"\n            ;;\n        l)\n            distro=\"${OPTARG}\"\n            ;;\n        i)\n            package_path=\"${OPTARG}\"\n            ;;\n        *)\n            echo \"Usage: $0 -r region -a ami -k ec2-key-pair -s subnet -g security-group -p /private/key/path -u ec2-os-user -l ami-linux-distro-name -i /path/to/package/file [-d /test/output/directory] [-t instance,types,list]\"\n            exit 1\n            ;;\n    esac\ndone\n\n# Ensure we have config for this distro\nif [ ! -f \"${TOPDIR}/integration-test/config/${distro}\" ] ; then\n    echo \"Unsupported distro ${distro} will not be tested\"\n    exit 1\nfi\n\nsource \"${TOPDIR}/integration-test/config/${distro}\"\n\npackage_name=\"${package_path##*/}\"\n\nif [ -z \"${output_directory}\" ] ; then\n    timestamp=$(/bin/date -u \"+%Y-%m-%d_%H:%M:%S\")\n    # TODO: Better autogenerated directory.  Include AMI/test name?\n    output_directory=\"/tmp/eic_integ_test_${timestamp}\"\n    echo \"No output directory set.  Creating & using ${output_directory}\"\n    mkdir \"${output_directory}\"\nfi\n\n# Fetch information about the subnet (AZ, etc)\nsubnet_output=$(aws ec2 describe-subnets --subnet-ids \"${subnet_id}\")\nsubnet_status=$?\nif [ \"${subnet_status}\" -ne 0 ] ; then\n    echo \"Failed to query subnet information:\"\n    echo \"${subnet_output}\"\n    exit \"${subnet_status}\"\nfi\n\nzone=$(echo \"${subnet_output}\" | grep \"\\\"AvailabilityZone\\\"\" | cut -d '\"' -f 4)\n\nif [ $types_specified -eq 0 ] ; then\n    echo \"Instance types not specified.  Will test all supported in this subnet.\"\n    instance_types=$(\"${TOPDIR}/bin/integration-test/get_zone_instance_types.sh\" \"${region}\" \"${zone}\")\n    IFS=$'\\n' read -d '' -r -a instance_types <<< \"${instance_types}\"\nfi\n\noverall_exit=0\nfor instance_type in \"${instance_types[@]}\" ; do\n    echo \"Testing ${instance_type}\"\n    mkdir \"${output_directory}/${instance_type}\"\n    output=\"\"\n    instance_exit=0\n    # Run instance\n    launch_output=$(\"${TOPDIR}/bin/integration-test/run_instance.sh\" -t \"${instance_type}\" -a \"${ami_id}\" -k \"${key_name}\" -s \"${subnet_id}\" -g \"${security_group_id}\" -n \"EIC Integration Test ${instance_type}\" -r \"${region}\" -o \"${osuser}\" -p \"${private_key}\")\n    launch_status=$?\n    if [ \"${launch_status}\" -ne 0 ] ; then\n        output=$(concat \"${output}\" \"${launch_output}\")\n        instance_exit=1\n    else\n        instance_id=$launch_output\n        public_ip=$(aws ec2 describe-instances --instance-ids \"${instance_id}\" | grep \"PublicIp\" | cut -d '\"' -f 4 | uniq)\n        # scp the package file to the instance and install it\n        output=$(concat \"${output}\" \"scping package file to instance\")\n        scp_out=$(scp -i \"${private_key}\" -o StrictHostKeyChecking=no \"${package_path}\" \"${osuser}@${public_ip}:/tmp/${package_name}\" 2>&1)\n        install_status=$?\n        output=$(concat \"${output}\" \"${scp_out}\")\n        if [ \"${install_status}\" -eq 0 ] ; then\n            # FIXME: Ubuntu AMIs fail here due to dpkg lock contention\n            ssh -i \"${private_key}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" \"${INSTALL} /tmp/${package_name}\" 1>/dev/null 2>&1\n            install_status=$?\n            output=$(concat \"${output}\" \"${scp_out}\")\n        else\n            output=$(concat \"${output}\" \"Failed to scp package to instance.\")\n            instance_exit=1\n        fi\n        if [ \"${install_status}\" -ne 0 ] ; then\n            output=$(concat \"${output}\" \"Failed to install EIC package on instance.\")\n            instance_exit=1\n        else\n            # Run the actual tests\n            \"${TOPDIR}/bin/integration-test/run_test_sweep.sh\" -i \"${instance_id}\" -p \"${public_ip}\" -k \"${private_key}\" -u \"${osuser}\" -z \"${zone}\" -o \"${output_directory}/${instance_type}\" -l \"${distro}\" -f \"${package_path}\"\n            test_exit=$?\n            if [ \"${test_exit}\" -ne 0 ] ; then\n                overall_exit=1\n            else\n                rmdir \"${output_directory}/${instance_type}\"\n            fi\n        fi\n        # Terminate the instance\n        aws ec2 terminate-instances --instance-ids \"${instance_id}\" 1>/dev/null\n    fi\n    if [ \"${instance_exit}\" -ne 0 ] ; then\n        echo \"Could not run tests on instance.\"\n        echo \"${output}\" > \"${output_directory}/${instance_type}/setup\"\n        overall_exit=1\n    fi\ndone\n\nif [ \"${overall_exit}\" -ne 0 ] ; then\n    echo \"Some instance types failed.  Please check the contents of ${output_directory} for details.\"\nelse\n    echo \"All instance types passed!  Removing failed output directory since it is empty.\"\n    rmdir \"${output_directory}\"\nfi\n\nexit \"${overall_exit}\"\n", "num_lines": 174}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# XXX: This script builds a local 3.0 (native) package for testing purposes.\n# Any actual patches should be developed and submitted using apt-source and Quilt.\n\n# Note: this will only work on a system with dpkg build tools installed (ie, Debian & its derivatives)\n# It is also strongly recommended you install devtools (dch, etc) to assist with package building\n# You are *REQUIRED* to have debhelper and devscripts installed!\n\nif [ $# -ne 2 ] ; then\n    echo \"Usage: make_deb.sh [version] [release]\"\n    echo \"    ie, make_deb.sh [1.1] [1]\"\n    exit 1\nfi\n\nmd5 () {\n    echo -n \"${1}\" | md5sum | sed 's/\\s.*$//'\n}\n\nsha1 () {\n    echo -n \"${1}\" | sha1sum | sed 's/\\s.*$//'\n}\n\nsha256 () {\n    echo -n \"${1}\" | sha256sum | sed 's/\\s.*$//'\n}\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\")\n\nversion=$1\nrelease=$2\npkgdir=\"${TOPDIR}/ec2-instance-connect-${version}-${release}\"\n\n# Copy source files\nmkdir \"${pkgdir}\"\nmkdir -p \"${pkgdir}/ec2-instance-connect\"\ncp \"${TOPDIR}\"/src/bin/* \"${pkgdir}/ec2-instance-connect/\"\n# Dump /bin, /usr/bin, etc from binary paths names since we want to use $PATH on Ubuntu/etc\nsed -i \"s%/usr/bin/%%g\" \"${pkgdir}\"/ec2-instance-connect/*\nsed -i \"s%^/bin/%%g\" \"${pkgdir}\"/ec2-instance-connect/*\nsed -i \"s%\\([^\\#][^\\!]\\)/bin/%\\1%g\" \"${pkgdir}\"/ec2-instance-connect/*\n\nmkdir \"${pkgdir}/debian\"\ncp -r \"${TOPDIR}\"/debian/* \"${pkgdir}/debian/\"\nsed -i \"s/\\!VERSION\\!/${version}-${release}/\" \"${pkgdir}/debian/control\"\n\n# Do the actual packaging\nreturn_dir=$(pwd)\ncd \"${pkgdir}\" || exit 1\ndebuild\n\n# Clean up\ncd \"${return_dir}\" || exit 1\nrm -rf \"${pkgdir}\"\n", "num_lines": 72}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Note: this will only work on a system with rpm build tools installed (ie, RHEL & its derivatives)\n\nif [ $# -ne 2 ] ; then\n    echo \"Usage: make_rpm.sh [version] [release]\"\n    echo \"    ie, make_rpm.sh [1.1] [1]\"\n    exit 1\nfi\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\")\nBUILDDIR=\"${TOPDIR}/rpmbuild\"\nmkdir -p \"${BUILDDIR}\"\n\nversion=\"${1}\"\nrelease=\"${2}\"\n\nmkdir -p \"${BUILDDIR}\"/{BUILD,RPMS,SOURCES,SPECS,SRPMS,ec2-instance-connect-\"${version}\",tmp}\nmkdir -p \"${BUILDDIR}/ec2-instance-connect-${version}/opt/aws/bin\"\ncp \"${TOPDIR}\"/rpmsrc/SPECS/generic.spec \"${BUILDDIR}/SPECS/ec2-instance-connect.spec\"\ncp \"${TOPDIR}\"/src/bin/* \"${BUILDDIR}/ec2-instance-connect-${version}/opt/aws/bin/\"\ncp \"${TOPDIR}\"/rpmsrc/.rpmmacros \"${BUILDDIR}/\"\n\n/bin/sed -i \"s%^ca_path=/etc/ssl/certs$%ca_path=/etc/ssl/certs/ca-bundle.crt%\" \"${BUILDDIR}/ec2-instance-connect-${version}/opt/aws/bin/eic_curl_authorized_keys\"\n\n# Trick rpmbuild into thinking this is homedir to read .rpmmacros\nREALHOME=\"${HOME}\"\nexport HOME=\"${BUILDDIR}\"\n\nfunction cleanup {\n    export HOME=\"${REALHOME}\"\n    rm -rf \"${BUILDDIR}\"/{BUILD,SOURCES,tmp}\n    rm -rf \"${BUILDDIR}/BUILDROOT\" # In case we got far enough for this to exist\n    rm -rf \"${BUILDDIR}/ec2-instance-connect-${version}\"\n}\ntrap cleanup EXIT\n\nls \"${BUILDDIR}/SOURCES\"\n\ncd \"${BUILDDIR}\" || exit 1 # Will ensure some paths are set correctly in rpmbuild\n\n# Compress the scripts\ntar -czf \"${BUILDDIR}/SOURCES/ec2-instance-connect-${version}.tar.gz\" \"ec2-instance-connect-${version}/\"\n\n# Fill in the placeholders\nsed -i \"s/\\!VERSION\\!/${version}/\" \"${BUILDDIR}/SPECS/ec2-instance-connect.spec\"\nsed -i \"s/\\!RELEASE\\!/${release}/\" \"${BUILDDIR}/SPECS/ec2-instance-connect.spec\"\n\n# Build the package\nrpmbuild -ba \"${BUILDDIR}/SPECS/ec2-instance-connect.spec\"\n\ncp \"${BUILDDIR}/RPMS/noarch/ec2-instance-connect-${version}-${release}.noarch.rpm\" \"${TOPDIR}/\"\n", "num_lines": 70}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\")\n\nverrel=\"$(cat \"${TOPDIR}/VERSION\")\"\nversion=\"${verrel%-*}\"\npkgver=\"ec2-instance-connect-${version}\"\n\nmkdir -p \"${TOPDIR}/${pkgver}/opt/aws/bin\"\ncp \"${TOPDIR}\"/src/bin/* \"${TOPDIR}/${pkgver}/opt/aws/bin/\"\nif [ $# -eq 1 ] ; then # TODO: better check.  Low-priority.\n    /bin/sed -i \"s%^ca_path=/etc/ssl/certs$%ca_path=/etc/ssl/certs/ca-bundle.crt%\" \"${TOPDIR}/${pkgver}/opt/aws/bin/eic_curl_authorized_keys\"\nfi\ntar -czf \"${TOPDIR}/${pkgver}.tar.gz\" -C \"${TOPDIR}\" \"${pkgver}/\"\nrm -rf \"${TOPDIR:?}/${pkgver:?}\"/*\nrmdir \"${TOPDIR}/${pkgver}\"\n", "num_lines": 34}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Script to run our entire unit test suite.\n# Iterates over the contents of test/input/direct and test/input/unsigned and validates we get the matching contents of unit-test/expected-output\n\nOPENSSL=\"/usr/bin/openssl\"\nTOPDIR=$(dirname \"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd)\")\n\ntmpdir=$(mktemp -d /dev/shm/tmp-XXXXXXXX)\ntrap 'rm -rf \"${tmpdir}\"' EXIT\n\n# Generate test certificates\n\"${TOPDIR}/bin/unit-test/setup_certificates.sh\" \"${OPENSSL}\" \"${tmpdir}\"\n# Combine unittest & intermediate into the trust chain for the actual AuthorizedKeysCommand\ncat \"${tmpdir}/unittest.pem\" \"${tmpdir}/intermediate.pem\" \"${tmpdir}/ca.pem\" > \"${tmpdir}/chain.pem\"\n\nintermediate_fingerprint=\"$(openssl x509 -noout -fingerprint -sha1 -inform pem -in \"${tmpdir}/intermediate.pem\" | sed -n 's/SHA1 Fingerprint=\\(.*\\)/\\1/p' | tr -d ':')\"\nunittest_fingerprint=\"$(openssl x509 -noout -fingerprint -sha1 -inform pem -in \"${tmpdir}\"/unittest.pem | sed -n 's/SHA1 Fingerprint=\\(.*\\)/\\1/p' | tr -d ':')\"\n\n# Generate OCSP for those certificates\n\"${TOPDIR}/bin/unit-test/generate_ocsp.sh\" \"${OPENSSL}\" \"${tmpdir}/intermediate.crt\" \"${tmpdir}/ca\" \"${tmpdir}/${intermediate_fingerprint}\"\n\"${TOPDIR}/bin/unit-test/generate_ocsp.sh\" \"${OPENSSL}\" \"${tmpdir}/unittest.crt\" \"${tmpdir}/intermediate\" \"${tmpdir}/${unittest_fingerprint}\"\n\nexit_status=0\n\n# Direct input tests\nfor testfile in \"${TOPDIR}\"/unit-test/input/direct/* ; do\n    filename=\"${testfile##*/}\"\n    \"${TOPDIR}/bin/unit-test/test_authorized_keys.sh\" \"${OPENSSL}\" \"${TOPDIR}/src/bin/eic_parse_authorized_keys\" \"${tmpdir}/chain.pem\" \"${tmpdir}/ca.crt\" \"${tmpdir}\" \"${testfile}\" \"${TOPDIR}/unit-test/expected-output/${filename}\"\n    result=\"${?}\"\n    if [ \"${result}\" -ne 0 ] ; then\n        exit_status=1\n    fi\ndone\n\n# Tests that require signing input data\nfor testdir in \"${TOPDIR}\"/unit-test/input/unsigned/* ; do\n    # Generate signatures for key blobs\n    filename=\"${testdir##*/}\"\n    if [ \"$(\"${TOPDIR}/bin/unit-test/sign_data.sh\" \"${OPENSSL}\" \"${tmpdir}/unittest.key\" \"${testdir}\" \"${tmpdir}/${filename}\")\" ] ; then\n        echo \"Unable to run test ${filename}: signature generation failed\"\n    else\n        # Run the actual test\n        \"${TOPDIR}/bin/unit-test/test_authorized_keys.sh\" \"${OPENSSL}\" \"${TOPDIR}/src/bin/eic_parse_authorized_keys\" \"${tmpdir}/chain.pem\" \"${tmpdir}/ca.crt\" \"${tmpdir}\" \"${tmpdir}/${filename}\" \"${TOPDIR}/unit-test/expected-output/${filename}\"\n        result=\"${?}\"\n        if [ \"${result}\" -ne 0 ] ; then\n            exit_status=1\n        fi\n    fi\ndone\n\nrm -rf \"${tmpdir:?}\"\n\nexit \"${exit_status}\"\n", "num_lines": 72}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Load the list of instance types supported in a given zone.\n# XXX: The mechanism for this is based on reserved instances. This may not be exhaustive in every zone.\n\nregion=$1\nzone=$2\n\nraw=$(aws ec2 describe-reserved-instances-offerings --filters \"Name=availability-zone,Values=$zone\" --region \"${region}\")\ntypes=$(echo \"{$raw}\" | grep \"InstanceType\" | cut -d '\"' -f 4)\necho \"${types}\"\n", "num_lines": 29}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Attempts to launch an instance to the given specification\n# Outputs instance ID on success or where it failed otherwise\n\nwhile getopts \":t:r:a:k:s:g:n:o:p:\" opt ; do\n    case \"${opt}\" in\n        t)\n            instance_type=\"${OPTARG}\"\n            ;;\n        r)\n            region=\"${OPTARG}\"\n            ;;\n        a)\n            ami_id=\"${OPTARG}\"\n            ;;\n        k)\n            key_name=\"${OPTARG}\"\n            ;;\n        s)\n            subnet_id=\"${OPTARG}\"\n            ;;\n        g)\n            security_group_id=\"${OPTARG}\"\n            ;;\n        n)\n            name_tag=\"${OPTARG}\"\n            ;;\n        o)\n            osuser=\"${OPTARG}\"\n            ;;\n        p)\n            private_key=\"${OPTARG}\"\n            ;;\n        *)\n            echo \"Usage: $0 -t instance-type -r aws-region -a ami -k ec2-key-pair -s subnet -g security-group -n name-tag-value\"\n            exit 1\n            ;;\n    esac\ndone\n\nlaunch_output=$(aws ec2 run-instances --region \"${region}\" --image-id \"${ami_id}\" --key-name \"${key_name}\" --security-group-ids \"${security_group_id}\" --subnet-id \"${subnet_id}\" --instance-initiated-shutdown-behavior \"terminate\" --instance-type \"${instance_type}\" --tag-specifications \"[{\\\"ResourceType\\\":\\\"instance\\\",\\\"Tags\\\":[{\\\"Key\\\":\\\"Name\\\",\\\"Value\\\":\\\"${name_tag}\\\"}]}]\")\nlaunch_code=$?\nif [ \"${launch_code}\" -ne 0 ] ; then\n    echo \"Instance launch failed!\"\n    exit \"${launch_code}\"\nfi\n\ninstance_id=$(echo \"${launch_output}\" | grep \\\"InstanceId\\\" | cut -d '\"' -f 4)\nrunning=0\ntry=\"0\"\n# Wait up to 5 minutes for the instance to come up, checking every 5 seconds\nwhile [ $try -lt 60 ] ; do\n    aws ec2 describe-instances --instance-ids \"${instance_id}\" | grep \"Name\" | grep -q \"running\"\n    launch_code=$?\n    if [ \"${launch_code}\" -eq 0 ] ; then\n        try=\"60\"\n        running=1\n    else\n        try=$((try+1))\n        sleep 5\n    fi\ndone\nif [ $running -eq 0 ] ; then\n    echo \"Timed out waiting for instance to enter 'running' state\"\n    exit 1\nfi\n\n# Wait a bit extra to let sshd come up\nssh_try=\"0\"\npublic_ip=$(aws ec2 describe-instances --instance-ids \"${instance_id}\" | grep \"PublicIp\" | cut -d '\"' -f 4 | uniq)\nwhile [ $ssh_try -lt 30 ] ; do\n    ssh -q -i \"${private_key}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" exit 2>&1\n    launch_code=\"${?}\"\n    if [ \"${launch_code}\" -eq 0 ] ; then\n        # Everything's ready\n        echo \"${instance_id}\"\n        exit 0\n    fi\n    ssh_try=$((ssh_try+1))\n    sleep 10\ndone\necho \"Timed out waiting for sshd to start on instance (or keypair is misconfigured)\"\nexit 1\n", "num_lines": 102}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"$( dirname \"${BASH_SOURCE[0]}\" )\" )\" && pwd)\")\n\nwhile getopts \":i:p:k:u:z:o:l:f:\" opt ; do\n    case \"${opt}\" in\n        i)\n            instance_id=\"${OPTARG}\"\n            ;;\n        p)\n            public_ip=\"${OPTARG}\"\n            ;;\n        k)\n            keypath=\"${OPTARG}\"\n            ;;\n        u)\n            osuser=\"${OPTARG}\"\n            ;;\n        z)\n            zone=\"${OPTARG}\"\n            ;;\n        o)\n            output_directory=\"${OPTARG}\"\n            ;;\n        l)\n            distro=\"${OPTARG}\"\n            ;;\n        f)\n            package_path=\"${OPTARG}\"\n            ;;\n        *)\n            ;;\n    esac\ndone\n\noverall_success=0\nfor testscript in \"${TOPDIR}\"/integration-test/test/* ; do\n    filename=\"${testscript##*/}\"\n    test_output=$($testscript -i \"${instance_id}\" -p \"${public_ip}\" -z \"${zone}\" -u \"${osuser}\" -k \"${keypath}\" -l \"${distro}\" -t \"${package_path}\")\n    test_exit=\"${?}\"\n    if [ \"${test_exit}\" -ne 0 ] ; then\n        echo \"${test_output}\" > \"${output_directory}/${filename}\"\n        echo \"Test ${filename} FAILED\"\n        overall_success=1\n    else\n        echo \"Test ${filename} PASSED\"\n    fi\ndone\n\nexit \"${overall_success}\"\n", "num_lines": 68}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Unit test helper to generate an OCSP response in the desired location\n\nif [ -z \"${1}\" ] ; then\n    echo \"No openssl provided\"\n    exit 1\nfi\n\nif [ -z \"${2}\" ] ; then\n    echo \"No certificate file provided\"\n    exit 2\nfi\n\nif [ -z \"${3}\" ] ; then\n    echo \"No CA filepath provided (do not include file extension - this path will be used with .crt, .key, and .cdb.index)\"\n    exit 3\nfi\n\nif [ -z \"${4}\" ] ; then\n    echo \"No output file specified\"\n    exit 4\nfi\n\ntmpfile=$(mktemp /dev/shm/tmp-XXXXXXXX)\n\n# Generate the OCSP request\n\n\"${1}\" ocsp -no_nonce -issuer \"${3}.crt\" -cert \"${2}\" -VAfile \"${3}\".crt -reqout \"${tmpfile}\"\n\n# Generate the response\n# Yes, we're using the CA to sign the response as well.  Since this is for unit testing use we don't need strict security.\n\"${1}\" ocsp -index \"${3}.db.index\" -rsigner \"${3}.crt\" -rkey \"${3}.key\" -CA \"${3}.crt\" -VAfile \"${3}.crt\" -reqin \"${tmpfile}\" -respout \"${4}\" > /dev/null 2>&1\n\n# Drop the request, we don't need it anymore\nrm -f \"${tmpfile}\"\n", "num_lines": 54}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Quick script to generate a CA, intermediate, and end certificate\n\nif [ -z \"${1}\" ] ; then\n    echo \"No openssl provided\"\n    exit 1\nfi\n\nif [ -z \"${2}\" ] ; then\n    echo \"No target directory provided\"\n    exit 2\nfi\n\nOPENSSL=\"${1}\"\ncertpath=\"${2}\"\n\n# Configure the CA\nmkdir -p \"${certpath}/ca.db.certs\"\ntouch \"${certpath}/ca.db.index\"\necho 01 > \"${certpath}/ca.db.serial\"\n\ncat > \"${certpath}/ca.conf\" <<'EOF'\ndefault_ca = ca_default\n\n[ca_default]\ndir = REPLACE_WITH_CERTPATH\ncerts = $dir\nnew_certs_dir = $dir/ca.db.certs\ndatabase = $dir/ca.db.index\nserial = $dir/ca.db.serial\nRANDFILE = $dir/ca.db.rand\ncertificate = $dir/ca.crt\nprivate_key = $dir/ca.key\ndefault_days = 1\ndefault_crl_days = 1\ndefault_md = sha256\npreserve = no\npolicy = generic_policy\nx509_extensions = usr_cert\n\n[generic_policy]\ncountryName = optional\nstateOrProvinceName = optional\nlocalityName = optional\norganizationName = optional\norganizationalUnitName = optional\ncommonName = supplied\nemailAddress = optional\n\n[usr_cert]\nauthorityInfoAccess = OCSP;URI:http://localhost:8080\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n\n[v3_ocsp]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = OCSPSigning\n\n[v3_ca]\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always,issuer:always\nbasicConstraints = CA:TRUE\n\n[req]\ndistinguished_name = req_distinguished_name\n\n[req_distinguished_name]\n\nEOF\n\nsed -i \"s|REPLACE_WITH_CERTPATH|${certpath}|\" \"${certpath}/ca.conf\"\n\n# Generate the CA\n\"${OPENSSL}\" genrsa -out \"${certpath}/ca.key\" 2048 > /dev/null 2>&1\n\"${OPENSSL}\" req -x509 -new -nodes -key \"${certpath}/ca.key\" -sha256 -days 1 -out \"${certpath}/ca.crt\" -subj \"/CN=managedssh.amazonaws.com\" > /dev/null 2>&1\n\"${OPENSSL}\" x509 -in \"${certpath}/ca.crt\" -outform PEM -out \"${certpath}/ca.pem\"\nsubject=$(\"${OPENSSL}\" x509 -noout -subject -in \"${certpath}/ca.pem\" | sed -n -e 's/^.*CN=//p')\n# Add \"# subject\" to start\nsed -i '1s;^;# '\"$subject\"'\\n;' \"${certpath}/ca.crt\"\n\n# Configure the intermediary\nmkdir -p \"${certpath}/intermediate.db.certs\"\ntouch \"${certpath}/intermediate.db.index\"\necho 01 > \"${certpath}/intermediate.db.serial\"\n\ncat > \"${certpath}/intermediate.conf\" <<'EOF'\ndefault_ca = ca_default\n\n[ca_default]\ndir = REPLACE_WITH_CERTPATH\ncerts = $dir\nnew_certs_dir = $dir/intermediate.db.certs\ndatabase = $dir/intermediate.db.index\nserial = $dir/intermediate.db.serial\nRANDFILE = $dir/intermediate.db.rand\ncertificate = $dir/intermediate.crt\nprivate_key = $dir/intermediate.key\ndefault_days = 1\ndefault_crl_days = 1\ndefault_md = sha256\npreserve = no\npolicy = generic_policy\nx509_extensions = usr_cert\n\n[generic_policy]\ncountryName = optional\nstateOrProvinceName = optional\nlocalityName = optional\norganizationName = optional\norganizationalUnitName = optional\ncommonName = supplied\nemailAddress = optional\n\n[usr_cert]\nauthorityInfoAccess = OCSP;URI:http://localhost:8080\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\n\n[v3_ocsp]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = OCSPSigning\n\n[req]\ndistinguished_name = req_distinguished_name\n\n[req_distinguished_name]\n\nEOF\n\nsed -i \"s|REPLACE_WITH_CERTPATH|${certpath}|\" \"${certpath}/intermediate.conf\"\n\n# Generate & sign the intermediary\n\"${OPENSSL}\" genrsa -out \"${certpath}/intermediate.key\" 2048 > /dev/null 2>&1\n\"${OPENSSL}\" req -new -nodes -config \"${certpath}/ca.conf\" -key \"${certpath}/intermediate.key\" -out \"${certpath}/intermediate.csr\" -extensions v3_ocsp -subj \"/CN=intermediate.managedssh.amazonaws.com\" > /dev/null 2>&1\nyes | \"${OPENSSL}\" ca -config \"${certpath}/ca.conf\" -in \"${certpath}/intermediate.csr\" -cert \"${certpath}/ca.crt\" -keyfile \"${certpath}/ca.key\" -out \"${certpath}/intermediate.crt\" -extensions v3_ocsp -extensions v3_ca > /dev/null 2>&1\n\"${OPENSSL}\" x509 -in \"${certpath}/intermediate.crt\" -outform PEM -out \"${certpath}/intermediate.pem\"\n\n# Generate and sign the test cert\n\"${OPENSSL}\" genrsa -out \"${certpath}/unittest.key\" 2048 > /dev/null 2>&1\n\"${OPENSSL}\" req -new -nodes -config \"${certpath}/intermediate.conf\" -key \"${certpath}/unittest.key\" -out \"${certpath}/unittest.csr\" -subj \"/CN=unittest.managedssh.amazonaws.com\" > /dev/null 2>&1\nyes | \"${OPENSSL}\" ca -config \"${certpath}/intermediate.conf\" -in \"${certpath}/unittest.csr\" -cert \"${certpath}/intermediate.crt\" -keyfile \"${certpath}/intermediate.key\" -out \"${certpath}/unittest.crt\" > /dev/null 2>&1\n\"${OPENSSL}\" x509 -in \"${certpath}/unittest.crt\" -outform PEM -out \"${certpath}/unittest.pem\"\n", "num_lines": 163}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Unit test helper.  Takes a directory containing key blobs in files, signs the data in each, and consolidates into a final output.\n\nif [ -z \"${1}\" ] ; then\n    echo \"No openssl provided\"\n    exit 1\nfi\n\nif [ -z \"${2}\" ] ; then\n    echo \"Signing key not provided.\"\n    exit 2\nfi\n\nif [ -z \"${3}\" ] ; then\n    echo \"Input directory not provided.\"\n    exit 3\nfi\n\nif [ -z \"${4}\" ] ; then\n    echo \"Target file not provided.\"\n    exit 4\nfi\n\nOPENSSL=\"${1}\"\nprivate_key=\"${2}\"\ninput_dir=\"${3}\"\ntarget=\"${4}\"\n\nsigning_temp=$(mktemp -d /dev/shm/tmp-XXXXXXXX)\ntrap 'rm -rf \"${signing_temp}\"' EXIT\n\nfor file in \"${input_dir}\"/* ; do\n    # Generate the signature\n    \"${OPENSSL}\" dgst -sha256 -sigopt rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sign \"${private_key}\" -out \"${signing_temp}/signature\" \"${file}\"\n    # Base64 encode it\n    base64 \"${signing_temp}/signature\" > \"${signing_temp}/encoded\"\n    # Add the input file dump & its signature to the target\n    cat \"${file}\" \"${signing_temp}/encoded\" >> \"${target}\"\n    # Append a newline\n    echo >> \"${target}\"\ndone\n", "num_lines": 60}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Authorized keys command unit test script.  Takes the script to test, certificate, CA, input, and expected output.\n\n# TODO: Switch to named args/getopts\n\nif [ -z \"${1}\" ] ; then\n    echo \"No openssl provided\"\n    exit 1\nfi\n\nif [ -z \"${2}\" ] ; then\n    echo \"Script file not provided\"\n    exit 2\nfi\n\nif [ -z \"${3}\" ] ; then\n    echo \"No certificate file provided\"\n    exit 3\nfi\n\nif [ -z \"${4}\" ] ; then\n    echo \"No CA file provided\"\n    exit 4\nfi\n\nif [ -z \"${5}\" ] ; then\n    echo \"OCSP responses directory not provided\"\n    exit 5\nfi\n\nif [ -z \"${6}\" ] ; then\n    echo \"No input file provided\"\n    exit 6\nfi\n\nif [ -z \"${7}\" ] ; then\n    echo \"No expected output file provided\"\n    exit 7\nfi\n\nOPENSSL=$1\ncertificate=$(cat \"${3}\")\nfilename=\"${6##*/}\"\n\nexpected_output=$(cat \"${7}\")\nexpected_exit=0\nif [ -z \"${expected_output}\" ] ; then\n    # If expected output is empty then we expect the script not to exit success\n    expected_exit=255\nfi\n\ntestdir=$(mktemp -d /dev/shm/tmp-XXXXXXXX)\n\n# The key fingerprint is for a pre-generated ssh key used in several test inputs\n# Some test inputs contain other keys as well\n# The test outputs, however, *only* match this key - we expect the other keys to be rejected\ntest_output=$(${2} -x true -p \"${6}\" -o \"${OPENSSL}\" -d \"${testdir}\" -s \"${certificate}\" -i \"i-abcd1234\" -c \"unittest.managedssh.amazonaws.com\" -a \"${4}\" -v \"${5}\" -f \"SHA256:F3e4S8/QjcVquqrvmyq9AWAhOxIXfpbpnmDVFdA0sPU\")\ntest_status=$?\n\nexit_status=0\nif [[ $test_status -eq $expected_exit && \"${test_output}\" = \"${expected_output}\" ]] ; then\n    echo \"${filename} PASSED\"\nelse\n    echo \"${filename} FAILED\"\n    echo \"EXPECTED: exit ${expected_exit} with output\"\n    echo \"${expected_output}\"\n    echo \"ACTUAL: exit ${test_status} with output\"\n    echo \"${test_output}\"\n    exit_status=1\nfi\n\nrm -rf \"${testdir}\"\n\nexit \"${exit_status}\"\n", "num_lines": 93}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Test that package uninstall removes customizations and reinstall re-adds them\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"$( dirname \"${BASH_SOURCE[0]}\" )\" )\" && pwd)\")\n\nwhile getopts \":i:p:z:u:k:l:t:\" opt ; do\n    case \"${opt}\" in\n        i)\n            instance_id=\"${OPTARG}\"\n            ;;\n        p)\n            public_ip=\"${OPTARG}\"\n            ;;\n        z)\n            zone=\"${OPTARG}\"\n            ;;\n        u)\n            osuser=\"${OPTARG}\"\n            ;;\n        k)\n            private_key=\"${OPTARG}\"\n            ;;\n        l)\n            distro=\"${OPTARG}\"\n            ;;\n        t)\n            package_path=\"${OPTARG}\"\n            ;;\n        *)\n            ;;\n    esac\ndone\n\nsource \"${TOPDIR}/integration-test/config/${distro}\"\n\npackage_name=\"${package_path##*/}\"\n\n# Construct the test script\nscriptfile=$(mktemp /tmp/tmp-XXXXXXXX)\ntrap 'rm -f \"${scriptfile}\"'  EXIT\n\nif [ \"${SSHD_CONFIG_MODIFIED}\" -ne 0 ] ; then\n    config_check=\"\\\"\\$(sudo grep \\\"^AuthorizedKeysCommand[[:blank:]]/opt/aws/bin/eic_run_authorized_keys[[:blank:]]%u[[:blank:]]%f$\\\" /etc/ssh/sshd_config)\\\"\"\nelse\n    config_check=\"-f /lib/systemd/system/${SSHD_SERVICE}.service.d/ec2-instance-connect.conf\"\nfi\n\necho '#!/bin/bash' > \"${scriptfile}\"\necho \"set -e\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n\" \"echo \\\"Uninstalling package\\\"\" \"${REMOVE} ec2-instance-connect 2>&1\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n%s\\n%s\\n\" \"if [ ${config_check} ] ; then\" \"echo \\\"Package was not installed or deconfigured correctly\\\"\" \"exit 1\" \"fi\" >> \"${scriptfile}\"\n# We need an extra newline before the custom AKC due to some distros, eg RHEL, not having a newline at end of file\nprintf \"%s\\n%s\\n\" \"echo \\\"Adding override config to sshd_config\\\"\" \"printf \\\"\\n%s\\n\\\" \\\"AuthorizedKeysCommand exit\\\" | sudo tee -a /etc/ssh/sshd_config\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n\" \"echo \\\"Installing package\\\"\" \"${INSTALL} /tmp/${package_name} 2>&1\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n%s\\n%s\\n\" \"if [ ${config_check} ] ; then\" \"echo \\\"Package overwrote existing customizations!\\\"\" \"exit 1\" \"fi\" >> \"${scriptfile}\"\n\necho \"scping test script to instance\"\nscp -i \"${private_key}\" -o StrictHostKeyChecking=no \"${scriptfile}\" \"${osuser}@${public_ip}:/tmp/eic_custom_config_test.sh\" 2>&1\nscp_result=\"${?}\"\nif [ \"${scp_result}\" -ne 0 ] ; then\n    exit 1\nfi\n\necho \"Running test script\"\nfail=0\nssh -i \"${private_key}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" 'chmod +x /tmp/eic_custom_config_test.sh ; /tmp/eic_custom_config_test.sh' 2>&1\ntest_result=\"${?}\"\nif [ \"${test_result}\" -ne 0 ] ; then\n    fail=1\nfi\n\nif [ \"${fail}\" -eq 0 ] ; then\n    echo \"Invoking EIC end-to-end test for final validation\"\n    \"${TOPDIR}/integration-test/test/ssh_test.sh\" -i \"${instance_id}\" -p \"${public_ip}\" -z \"${zone}\" -u \"${osuser}\" -k \"${private_key}\" -l \"${distro}\" -t \"${package_path}\" 2>&1\n    ssh_result=\"${?}\"\n    if [ \"${ssh_result}\" -eq 0 ] ; then\n        echo \"ssh via EIC succeeded but should have failed!\"\n        fail=1\n    fi\nfi\n\n# Reset back to start-of-test conditions\nclean_cmd=\"${REMOVE} ec2-instance-connect  2>&1 ; sudo sed -i \\\"\\~^AuthorizedKeysCommand[[:blank:]]exit\\$~d\\\" /etc/ssh/sshd_config ; ${INSTALL} /tmp/${package_name} 2>&1\"\nssh -i \"${private_key}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" \"${clean_cmd}\"\n\nexit $fail\n", "num_lines": 105}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Basic EIC functionality test: push a key and ssh to the instance\n\nwhile getopts \":i:p:z:u:\" opt ; do\n    case \"${opt}\" in\n        i)\n            instance_id=\"${OPTARG}\"\n            ;;\n        p)\n            public_ip=\"${OPTARG}\"\n            ;;\n        z)\n            zone=\"${OPTARG}\"\n            ;;\n        u)\n            osuser=\"${OPTARG}\"\n            ;;\n        k)\n            private_key=\"${OPTARG}\"\n            ;;\n        l)\n            distro=\"${OPTARG}\"\n            ;;\n        t)\n            package_path=\"${OPTARG}\"\n            ;;\n        *)\n            ;;\n    esac\ndone\n\necho \"Testing EC2 Instance Connect end-to-end ssh functionality...\"\n\nkeydir=$(mktemp -d /tmp/tmp-XXXXXXXX)\ntrap 'rm -rf \"${keydir}\"' EXIT\n\nkeyfile=\"${keydir}/eic_test_key\"\nssh-keygen -t rsa -b 2048 -f \"${keyfile}\" -P \"\" -q\n\n# We will make 3 tries as certain elements (eg network calls) may cause transient failure\ntry=\"0\"\nsuccess=1\n\nwhile [ $try -lt 3 ] ; do\n    # Make 3 attempts to push a key\n    awstry=\"0\"\n    while [ $awstry -lt 3 ] ; do\n        aws ec2-instance-connect send-ssh-public-key --region us-west-2 --instance-id \"${instance_id}\" --availability-zone \"${zone}\" --instance-os-user \"${osuser}\" --ssh-public-key \"file://${keyfile}.pub\" 1>/dev/null\n        aws_code=$?\n        if [ $aws_code -ne 0 ] ; then\n            sleep 5\n            awstry=$((awstry+1))\n            echo \"${instance_id} EIC call ${awstry} failed\"\n        else\n            awstry=\"3\"\n        fi\n    done\n    sshtry=\"0\"\n    # Make 3 attempts to ssh\n    while [ $sshtry -lt 3 ] ; do\n        ssh -q -i \"${keyfile}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" exit 2>&1\n        success=$?\n        if [ $success -eq 0 ] ; then\n            echo \"${instance_id} ssh succeeded!\"\n            sshtry=\"3\"\n            try=\"3\"\n        else\n            sleep 5\n            sshtry=$((sshtry+1))\n            echo \"${instance_id} ssh call ${sshtry} failed\"\n        fi\n    done\n    if [ $success -ne 0 ] ; then\n        try=$((try+1))\n        echo \"${instance_id} EIC test attempt ${try} failed\"\n    fi\ndone\n\nif [ $success -eq 0 ] ; then\n    echo \"SUCCESS\"\nelse\n    echo \"FAILURE\"\nfi\n\nexit $success\n", "num_lines": 104}
{"repo_name": "aws-ec2-instance-connect-config", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Reads authorized keys blob $3 and prints verified, unexpired keys\n# Openssl to use provided as $1\n# Signer public key file path provided as $2\n\n# Test that package uninstall removes customizations and reinstall re-adds them\n\nTOPDIR=$(dirname \"$( cd \"$( dirname \"$( dirname \"${BASH_SOURCE[0]}\" )\" )\" && pwd)\")\n\nwhile getopts \":i:p:z:u:k:l:t:\" opt ; do\n    case \"${opt}\" in\n        i)\n            instance_id=\"${OPTARG}\"\n            ;;\n        p)\n            public_ip=\"${OPTARG}\"\n            ;;\n        z)\n            zone=\"${OPTARG}\"\n            ;;\n        u)\n            osuser=\"${OPTARG}\"\n            ;;\n        k)\n            private_key=\"${OPTARG}\"\n            ;;\n        l)\n            distro=\"${OPTARG}\"\n            ;;\n        t)\n            package_path=\"${OPTARG}\"\n            ;;\n        *)\n            ;;\n    esac\ndone\n\nsource \"${TOPDIR}/integration-test/config/${distro}\"\n\npackage_name=\"${package_path##*/}\"\n\n# Construct the test script\nscriptfile=$(mktemp /tmp/tmp-XXXXXXXX)\ntrap 'rm -f \"${scriptfile}\"'  EXIT\n\nif [ \"${SSHD_CONFIG_MODIFIED}\" -ne 0 ] ; then\n    config_check=\"grep -q \\\"^AuthorizedKeysCommand[[:blank:]]/opt/aws/bin/eic_run_authorized_keys[[:blank:]]%u[[:blank:]]%f$\\\" /etc/ssh/sshd_config\"\nelse\n    config_check=\"-f /lib/systemd/system/${SSHD_SERVICE}.service.d/ec2-instance-connect.conf\"\nfi\n\necho \"#!/bin/bash\" > \"${scriptfile}\"\necho \"set -e\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n\" \"echo \\\"Uninstalling package\\\"\" \"${REMOVE} ec2-instance-connect 2>&1\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n%s\\n%s\\n\" \"if [ ${config_check} ] ; then\" \"echo \\\"Package was not installed or deconfigured correctly\\\"\" \"exit 1\" \"fi\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n\" \"echo \\\"Reinstalling package\\\"\" \"${INSTALL} /tmp/${package_name} 2>&1\" >> \"${scriptfile}\"\nprintf \"%s\\n%s\\n%s\\n%s\\n\" \"if [ ! ${config_check} ] ; then\" \"echo \\\"Package not installed/configured correctly\\\"\" \"exit 1\" \"fi\" >> \"${scriptfile}\"\n\necho \"scping test script to instance\"\nscp -i \"${private_key}\" -o StrictHostKeyChecking=no \"${scriptfile}\" \"${osuser}@${public_ip}:/tmp/eic_uninstall_reinstall_test.sh\" 2>&1\nscp_result=\"${?}\"\nif [ \"${scp_result}\" -ne 0 ] ; then\n    exit 1\nfi\n\necho \"Running test script\"\nssh -i \"${private_key}\" -o StrictHostKeyChecking=no \"${osuser}@${public_ip}\" 'chmod +x /tmp/eic_uninstall_reinstall_test.sh ; /tmp/eic_uninstall_reinstall_test.sh' 2>&1\ntest_result=\"${?}\"\nif [ \"${test_result}\" -ne 0 ] ; then\n    exit 1\nfi\n\necho \"Invoking EIC end-to-end test for final validation\"\n\"${TOPDIR}/integration-test/test/ssh_test.sh\" -i \"${instance_id}\" -p \"${public_ip}\" -z \"${zone}\" -u \"${osuser}\" -k \"${private_key}\" -l \"${distro}\" -t \"${package_path}\" 2>&1\n\nexit \"${?}\"\n", "num_lines": 91}
{"repo_name": "aws-elastic-beanstalk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\nARTIFACTS_DIRECTORY=\"$HOME/awsebcli_artifacts\"\nGIT_COMMIT=`git rev-parse HEAD`\n\nif [[ ! $GIT_BRANCH ]]; then\n    GIT_BRANCH = `git rev-parse --abbrev-ref HEAD`\nfi\nPYTHON_INSTALLATION=$1\nPYTHON_VERSION=`${PYTHON_INSTALLATION} -c 'import sys; print(\".\".join(map(str, sys.version_info[:3])))'`\nVENV_ENV_NAME=\"$PYTHON_VERSION-$GIT_COMMIT\"\nUSAGE_TEXT=$(cat <<usage\nThis Bash script runs the unit tests of the current Git commit in an exclusive\nvirtualenv created from the Python installation described by the first argument\nto it. If the current branch is a `master` branch (irrespective of the `remote`),\nthe script generates an EBCLI artifact tar file available for consumers such as an\nend-to-end tests runner, and for the purposes of uploading to PyPi.\n\nUsage:\n\n    ./scripts/jenkins/runner.sh <PYTHON_EXECUTABLE>\n\ne.g., to test this project against Python 2.7 and Python 3.6, you would:\n\n    ./scripts/jenkins/runner.sh /usr/local/bin/python2.7\n\n        and\n\n    ./scripts/jenkins/runner.sh /usr/local/bin/python3.6\n\nusage\n)\nPYTHON_NOT_FOUND=\"\\\"$PYTHON_INSTALLATION --version\\\" did not work. Is \\\"$PYTHON_INSTALLATION\\\" really a Python binary?\"\nSTEP_NUMBER=1\nSUBSTEP_NUMBER=1\n\nerror_if_required_number_of_arguments_have_not_been_passed()\n{\n    if [ \"$#\" -ne 1 ] ; then\n        echo \"$USAGE_TEXT\"\n        exit 1\n    fi\n}\n\nexit_upon_failure()\n{\n    if [[ $? -ne 0 ]] ; then\n        echo \"Delete Python $PYTHON_VERSION virtualenv before premature exit\"\n        rm -rf $VENV_ENV_NAME\n\n        exit 1\n    fi\n    increment_step_number\n    echo \"\"\n}\n\nexit_upon_substep_failure()\n{\n    if [[ $? -ne 0 ]] ; then\n        echo \"Delete Python $PYTHON_VERSION virtualenv before premature exit\"\n        rm -rf $VENV_ENV_NAME\n\n        exit 1\n    fi\n    increment_substep_number\n    echo \"\"\n}\n\nprint_help_message_if_requested_and_exit()\n{\n    for i in $*\n    do\n        if [ \"$i\" == \"--help\" ] ; then\n            echo \"$USAGE_TEXT\"\n            exit 0\n        fi\n    done\n}\n\nvalidate_python_version_name()\n{\n    if [ \"$PYTHON_VERSION\" == '' ] ; then\n        echo \"$PYTHON_NOT_FOUND\"\n        exit 1\n    fi\n}\n\nstep_title()\n{\n    echo \"\"\n    echo \"******************************************************\"\n    echo \"$STEP_NUMBER. $1\"\n    echo \"******************************************************\"\n}\n\nsubstep_title()\n{\n    echo \"    $STEP_NUMBER.$SUBSTEP_NUMBER $1\"\n}\n\nincrement_step_number()\n{\n    STEP_NUMBER=$(($STEP_NUMBER + 1))\n}\n\nincrement_substep_number()\n{\n    SUBSTEP_NUMBER=$((SUBSTEP_NUMBER + 1))\n}\n\n\nprint_help_message_if_requested_and_exit $*\n\nstep_title \"Verifying required number of arguments have been passed\"\nerror_if_required_number_of_arguments_have_not_been_passed $*\nincrement_step_number\n\nstep_title \"Verifying Python binary path is valid\"\nvalidate_python_version_name\nincrement_step_number\n\ncreate_and_load_new_virtualenv()\n{\n    substep_title \"Creating new Python $PYTHON_VERSION virtualenv\"\n    virtualenv -p $PYTHON_INSTALLATION $VENV_ENV_NAME\n    exit_upon_substep_failure\n\n    substep_title \"Loading Python $PYTHON_VERSION virtualenv\"\n    source $VENV_ENV_NAME/bin/activate\n    exit_upon_substep_failure\n\n    substep_title \"Installing pip 21.1\"\n    pip install pip==\"21.1\"\n    exit_upon_substep_failure\n}\n\nstep_title \"Checking for CVEs\"\ncheck_for_cves()\n{\n    create_and_load_new_virtualenv\n\n    substep_title \"Installing AWSEBCLI and dependencies\"\n    pip install . --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Installing package, 'safety'\"\n    pip install safety --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Checking for known security vulnerabilities\"\n    safety check\n    exit_upon_substep_failure\n\n    substep_title \"Deleting Python $PYTHON_VERSION virtualenv\"\n    rm -rf $VENV_ENV_NAME\n    exit_upon_substep_failure\n    SUBSTEP_NUMBER=1\n}\ncheck_for_cves\nincrement_step_number\n\n\nstep_title \"Ensuring AWSEBCLI installs correctly after AWSCLI\"\nensure_awsebcli_installs_correctly_after_awscli()\n{\n    create_and_load_new_virtualenv\n\n    substep_title \"Installing AWSCLI and dependencies\"\n    pip install awscli --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Installing AWSEBCLI and dependencies\"\n    pip install . --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Checking for missing dependencies and dependency mismatches in the package set\"\n    python tests/test_dependencies_mismatch.py\n    exit_upon_substep_failure\n\n    substep_title \"Deleting Python $PYTHON_VERSION virtualenv\"\n    rm -rf $VENV_ENV_NAME\n    SUBSTEP_NUMBER=1\n}\nensure_awsebcli_installs_correctly_after_awscli\nincrement_step_number\n\nstep_title \"Ensuring AWSCLI installs correctly after AWSEBCLI\"\nensure_awscli_installs_correctly_after_awsebcli()\n{\n    create_and_load_new_virtualenv\n\n    substep_title \"Installing AWSEBCLI and dependencies\"\n    pip install . --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Checking for missing dependencies and dependency mismatches in the package set\"\n    python tests/test_dependencies_mismatch.py\n    exit_upon_substep_failure\n\n    substep_title \"Installing AWSEBCLI and dependencies\"\n    pip install awsebcli --no-cache-dir\n    exit_upon_substep_failure\n\n    substep_title \"Checking for missing dependencies and dependency mismatches in the package set\"\n    python tests/test_dependencies_mismatch.py\n    exit_upon_substep_failure\n\n    substep_title \"Deleting Python $PYTHON_VERSION virtualenv\"\n    rm -rf $VENV_ENV_NAME\n    SUBSTEP_NUMBER=1\n}\nensure_awscli_installs_correctly_after_awsebcli\nincrement_step_number\n\nstep_title \"Creating new Python $PYTHON_VERSION virtualenv\"\nvirtualenv -p $PYTHON_INSTALLATION $VENV_ENV_NAME\nexit_upon_failure\n\nstep_title \"Installing pip 21.1\"\npip install pip==\"21.1\"\nexit_upon_failure\n\nstep_title \"Loading Python $PYTHON_VERSION virtualenv\"\nsource $VENV_ENV_NAME/bin/activate\nexit_upon_failure\n\nstep_title \"(Re)Installing AWSEBCLI and dependencies using commit $GIT_BRANCH/$GIT_COMMIT\"\npython scripts/jenkins/install_dependencies\nexit_upon_failure\n\nstep_title \"Checking for missing dependencies and dependency mismatches in the package set\"\npython tests/test_dependencies_mismatch.py\nexit_upon_failure\n\nstep_title \"Executing unit tests\"\npython scripts/jenkins/run_unit_tests\nexit_upon_failure\n\nstep_title \"Checking whether branch is a 'master' branch\"\nif [[ $GIT_BRANCH =~ 'master' ]]; then\n    substep_title \"Ensuring $ARTIFACTS_DIRECTORY exists\"\n    if [ ! -d \"$ARTIFACTS_DIRECTORY\" ]; then\n        mkdir \"$ARTIFACTS_DIRECTORY\"\n    fi\n    increment_substep_number\n\n    substep_title \"Recreating $ARTIFACTS_DIRECTORY/$PYTHON_VERSION\"\n    if [ -d $ARTIFACTS_DIRECTORY/$PYTHON_VERSION ]; then\n        rm -rf $ARTIFACTS_DIRECTORY/$PYTHON_VERSION\n    fi\n    mkdir $ARTIFACTS_DIRECTORY/$PYTHON_VERSION\n    increment_substep_number\n\n    substep_title \"Packaging awsebcli to store in $ARTIFACTS_DIRECTORY/$PYTHON_VERSION\"\n    python setup.py sdist\n    mv dist/* $ARTIFACTS_DIRECTORY/$PYTHON_VERSION/\n    increment_substep_number\nelse\n    substep_title \"Branch is not a 'master' branch; skipping artifact generation\"\n    increment_substep_number\nfi\n\nstep_title \"Deleting Python $PYTHON_VERSION virtualenv\"\nrm -rf $VENV_ENV_NAME\n", "num_lines": 276}
{"repo_name": "aws-emr-best-practices", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#===============================================================================\n#!# script: hbase-snapshot-export\n#!# authors: ripani\n#!# version: v0.2\n#!#\n#!# Generate a snapshot of all the tables present in a specific hbase namespace.\n#!# The snapshots so created are then copied over an S3 bucket or HDFS path.\n#!# For legacy clusters, use the s3a:// schema and specify the AWS programmatic\n#!# keys.\n#!#\n#!# If you're transfering data between kerberized clusters, make sure the\n#!# clusters belong to the same Kerberos realm.\n#===============================================================================\n#?#\n#?# usage: ./hbase-snapshot-export.sh <HBASE_NS> <SNAPSHOT_PATH> [S3_ACCESS_KEY] [AWS_SECRET_KEY]\n#?#        ./hbase-snapshot-export.sh \"default\" \"hdfs://NN:8020/hbase\"\n#?#        ./hbase-snapshot-export.sh \"default\" \"s3://BUCKET/PREFIX\"\n#?#        ./hbase-snapshot-export.sh \"default\" \"s3a://BUCKET/PREFIX\" \"KEY\" \"SECRET\"\n#?#\n#?#   HBASE_NS                 HBase namespace to backup\n#?#   SNAPSHOT_PATH            HDFS or S3 path.\n#?#                            Example: s3://BUCKET or hdfs://NN:8020/user/hbase\n#?#   AWS_ACCESS_KEY           [Optional] AWS access key for s3a schema\n#?#   AWS_SECRET_KEY           [Optional] AWS secret key for s3a schema\n#?#\n#===============================================================================\n\n# Print the usage helper using the header as source\nfunction usage() {\n\t[ \"$*\" ] && echo \"$0: $*\"\n\tsed -n '/^#?#/,/^$/s/^#?# \\{0,1\\}//p' \"$0\"\n\texit -1\n}\n\n[[ $# -lt 2 ]] && echo \"error: wrong parameters\" && usage\n\n#===============================================================================\n# Configurations\n#===============================================================================\nHBASE_NS=\"$1\"\nSNAPSHOT_PATH=\"$2\"\nAWS_ACCESS_KEY=\"$3\"\nAWS_SECRET_KEY=\"$4\"\n\nif [[ -f \"/emr/instance-controller/lib/info/extraInstanceData.json\" ]]; then\n\tHBASE_CMD=\"sudo -u hbase hbase\"\nelse\n\tHBASE_CMD=\"hbase\"\nfi\n\n# Retrieve list tables for the namespace\nreadarray -t tables < <(echo \"list_namespace_tables '$HBASE_NS'\" | $HBASE_CMD shell 2> /dev/null | sed -e '1,/TABLE/d' -e '/seconds/,$d' | while IFS='' read -r line || [[ -n \"$line\" ]]; do echo \"$line\"; done)\n\n# Generate Snapshots\nlabel=\"$(date +\"%Y%m%d\")-$(date +%s)\"\nfor table in \"${tables[@]}\"; do\n\techo \"Creating snapshot for table $HBASE_NS:$table\"\n\t$HBASE_CMD snapshot create -n \"$label-$HBASE_NS-$table\" -t $HBASE_NS:$table\ndone\n\n# Copy Snapshots to S3\nsnapshots=$($HBASE_CMD snapshot info -list-snapshots | grep $label | awk '{print $1}')\nfor s in ${snapshots}; do\n\techo \"Transfer snapshot $s to $SNAPSHOT_PATH\"\n\tif [[ -z \"$AWS_ACCESS_KEY\" && -z \"$AWS_SECRET_KEY\" ]]; then\n\t\t$HBASE_CMD org.apache.hadoop.hbase.snapshot.ExportSnapshot -snapshot ${s} -copy-to $SNAPSHOT_PATH\n\telse\n\t\t$HBASE_CMD org.apache.hadoop.hbase.snapshot.ExportSnapshot -Dfs.s3a.access.key=$AWS_ACCESS_KEY -Dfs.s3a.secret.key=$AWS_SECRET_KEY -snapshot ${s} -copy-to $SNAPSHOT_PATH\n\tfi\ndone\n", "num_lines": 72}
{"repo_name": "aws-emr-best-practices", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#===============================================================================\n#!# script: hbase-snapshot-import\n#!# authors: ripani\n#!# version: v0.2\n#!#\n#!# Import and Restore HBase Snapshots using a label. Make sure all the required\n#!# HBase namespaces required by the tables already exist before launching the\n#!# script.\n#!#\n#!# If you're transfering data between kerberized clusters, make sure the\n#!# clusters belong to the same Kerberos realm.\n#===============================================================================\n#?#\n#?# usage: ./hbase-snapshot-import.sh <LABEL> <SNAPSHOT_PATH>\n#?#        ./hbase-snapshot-import.sh \"20220813-1660430\" \"hdfs://NN:8020/hbase\"\n#?#        ./hbase-snapshot-import.sh \"20220813-1660430\" \"s3://BUCKET/PREFIX\"\n#?#\n#?#   LABEL                    HBase namespace to backup\n#?#   SNAPSHOT_PATH            HDFS or S3 path.\n#?#                            Example: s3://BUCKET or hdfs://NN:8020/user/hbase\n#?#\n#===============================================================================\n\n# Print the usage helper using the header as source\nfunction usage() {\n    [ \"$*\" ] && echo \"$0: $*\"\n    sed -n '/^#?#/,/^$/s/^#?# \\{0,1\\}//p' \"$0\"\n    exit -1\n}\n\n[[ $# -lt 2 ]] && echo \"error: wrong parameters\" && usage\n\n#===============================================================================\n# Configurations\n#===============================================================================\nLABEL=\"$1\"\nSNAPSHOT_PATH=\"$2\"\n\nHBASE_CMD=\"sudo -u hbase hbase\"\nHBASE_CONF=\"/etc/hbase/conf/hbase-site.xml\"\nHBASE_ROOT=$(xmllint --xpath \"//configuration/property/*[text()='hbase.rootdir']/../value/text()\" $HBASE_CONF)\n\n#===============================================================================\n# Import Snapshots\n#===============================================================================\nsnapshots=$(\n    $HBASE_CMD snapshot info -list-snapshots \\\n        -remote-dir $SNAPSHOT_PATH | grep $LABEL | awk '{print $1}'\n)\nfor s in ${snapshots}; do\n    echo \"Import snapshot $s\"\n    $HBASE_CMD snapshot export -D hbase.rootdir=$SNAPSHOT_PATH \\\n        -snapshot $s \\\n        -copy-to $HBASE_ROOT\ndone\n\n#===============================================================================\n# Restore Snapshots\n#===============================================================================\nsnapshots=$(\n    $HBASE_CMD snapshot info -list-snapshots | grep $LABEL | awk '{print $1}'\n)\nfor s in ${snapshots}; do\n    echo \"Restore snapshot $s\"\n    echo \"restore_snapshot '$s'\" | $HBASE_CMD shell\ndone\n", "num_lines": 68}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# The command used to generate the clang-format config file is:\n#   clang-format --style=Google -dump-config\n\necho \"Checking version number\"\nif command -v clang-format-8; then\n    CLANG_FORMAT=clang-format-8\nelif command -v clang-format; then\n    CLANG_FORMAT=clang-format\nelse\n    echo \"clang-format-8 or clang-format not found\"\n    exit 1\nfi\nVER=$($CLANG_FORMAT --version | cut -f3 -d' ' | cut -f1 -d'.')\n\nif [ \"$VER\" -ge 8 ]; then\n    set -euxo pipefail\n    find . -name '*.h' -or -name '*.c' -or -name '*.cpp' | xargs \"$CLANG_FORMAT\" -i\nelse\n    echo \"clang-format version 8 or greater is needed to read the format file.\"\n    exit 1\nfi\n", "num_lines": 37}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nPATH=$PWD/build-tools/bin:$PATH\nROOT=$PWD\nNUM_CPU_THREADS=$(nproc)\n\n# End to end tests require valid credentials (instance role, etc..)\n# Disable for local runs.\nif [ -f \"/sys/hypervisor/uuid\" ]; then\n        ONEC2=$(grep -c ec2 /sys/hypervisor/uuid)\n        if [ \"${ONEC2}\" -gt 0 ]; then\n            E2E=\"ON\";\n        else\n            E2E=\"OFF\";\n        fi\nelif [ -n \"$CODEBUILD_BUILD_ARN\" ]; then\n    E2E=\"ON\";\nelse\n    E2E=\"OFF\";\nfi\n\ndebug() {\n# If the threading test does in fact fail, it does so by crashing.\n# Since this sort of bug might not be reproducible, make sure to dump\n# some useful information before failing.\n    ulimit -c unlimited\n    if ! \"$@\"; then\n        if [ -e core.* ]; then\n            gdb -x \"$ROOT/codebuild/gdb.commands\" \"$1\" core.* \n            exit 1\n        fi\n    fi\n}\n\nrun_test() {\n    PREFIX_PATH=\"$1\"\n    shift\n\n    rm -rf build\n    mkdir build\n    (cd build\n    #TODO: EC2 metadata service fails; fix an re-enable end2end tests.\n    cmake -DBUILD_AWS_ENC_SDK_CPP=ON -DAWS_ENC_SDK_END_TO_END_TESTS=${E2E} \\\n        -DAWS_ENC_SDK_KNOWN_GOOD_TESTS=ON \\\n        -DAWS_ENC_SDK_END_TO_END_EXAMPLES=${E2E} \\\n        -DCMAKE_C_FLAGS=\"$CFLAGS\" \\\n        -DCMAKE_CXX_FLAGS=\"$CXXFLAGS\" \\\n        -DCMAKE_SHARED_LINKER_FLAGS=\"$LDFLAGS\" \\\n        -DOPENSSL_ROOT_DIR=/deps/install \\\n        -DVALGRIND_OPTIONS=\"--gen-suppressions=all;--suppressions=$ROOT/valgrind.suppressions\" \\\n        -DCMAKE_PREFIX_PATH=\"$PREFIX_PATH\" \\\n        -DBUILD_SHARED_LIBS=\"$BUILD_SHARED_LIBS\" \\\n        -GNinja \\\n        .. \"$@\" 2>&1|head -n 1000)\n    cmake --build $ROOT/build -- -v\n    (cd build; ctest --output-on-failure -j${NUM_CPU_THREADS})\n    (cd build; debug ./tests/test_local_cache_threading) || exit 1\n    \"$ROOT/codebuild/bin/test-install.sh\" \"$PREFIX_PATH\" \"$PWD/build\"\n}\n\n# Print env variables for debug purposes\nenv\n\ncase \"$TEST_MODE\" in\n    dynamic)\n        # Run the full test suite without valgrind, and as a shared library\n        export BUILD_SHARED_LIBS=on\n        run_test '/deps/install;/deps/shared/install' -DCMAKE_BUILD_TYPE=RelWithDebInfo\n        ;;\n    static_debug)\n        # Also run the test suite as a debug build (probing for -DNDEBUG issues), and as a static library\n        export BUILD_SHARED_LIBS=off\n        run_test '/deps/install;/deps/static/install' -DCMAKE_BUILD_TYPE=Debug\n        ;;\n    static_valgrind)\n        # Run a lighter weight test suite under valgrind\n        export BUILD_SHARED_LIBS=off\n        run_test '/deps/install;/deps/static/install' \\\n            -DCMAKE_BUILD_TYPE=RelWithDebInfo -DREDUCE_TEST_ITERATIONS=TRUE -DVALGRIND_TEST_SUITE=ON\n        ;;\n    *)\n        echo \"unknown TEST_MODE: $TEST_MODE\"\n        exit 1\n        ;;\nesac\n\n", "num_lines": 102}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n./aws-encryption-sdk-specification/util/report.js \\\n    'include/**/*.h' \\\n    'source/**/*.c' \\\n    'tests/**/*.[ch]' \\\n    'aws-encryption-sdk-cpp/include/**/*.h' \\\n    'aws-encryption-sdk-cpp/source/**/*.cpp' \\\n    'aws-encryption-sdk-cpp/tests/**/*.h' \\\n    'aws-encryption-sdk-cpp/tests/**/*.cpp' \\\n    'compliance/*.txt'\n", "num_lines": 25}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script builds and installs AWS-originated dependencies. Since we want to test\n# building against both the static and shared variants, we build them twice, installing\n# the results under /deps/static/install and /deps/shared/install\n\n# This script uses the following environment variables:\n# CC, CXX, CFLAGS, CXXFLAGS, LDFLAGS - Compiler and flags configuration\n\nset -euxo pipefail\n\nbuild_pkg() {\n    INSTALL_DIR=$1\n    GIT_URL=$2\n    GIT_REF=$3\n\n    shift; shift; shift\n\n    SRC_DIR=/tmp/$(basename $GIT_URL .git)\n    BUILD_DIR=/tmp/build\n\n    if ! [ -e $SRC_DIR ]; then\n        mkdir -p \"$(dirname \"$SRC_DIR\")\"\n        git clone --depth 1 --branch $GIT_REF --recurse-submodules \"$GIT_URL\" \"$SRC_DIR\"\n    fi\n\n    mkdir -p $BUILD_DIR\n    (cd $BUILD_DIR &&\n     export LD_LIBRARY_PATH=/deps/install &&\n     cmake $SRC_DIR \"$@\" -DCMAKE_INSTALL_PREFIX=$root/install -DCMAKE_BUILD_TYPE=RelWithDebInfo -GNinja \\\n        -DCMAKE_PREFIX_PATH=/deps/install \\\n        -DCMAKE_C_FLAGS=\"$CFLAGS\" \\\n        -DCMAKE_CXX_FLAGS=\"$CXXFLAGS\" \\\n        -DCMAKE_SHARED_LINKER_FLAGS=\"$LDFLAGS\")\n    cmake --build $BUILD_DIR\n    cmake --build $BUILD_DIR --target install\n    rm -rf $BUILD_DIR\n}\n\nmkdir -p /deps\n\n# These must refer to git tags\nAWS_CRT_CPP_VERSION=\"v0.17.28\"\nAWS_SDK_CPP_VERSION=\"1.9.263\"\n\nfor libtype in shared static; do\n    root=/deps/$libtype\n\n    if [ $libtype == shared ]; then\n        CMAKE_ARGS=\"-DBUILD_SHARED_LIBS=ON\"\n        build_pkg $root/install https://github.com/awslabs/aws-crt-cpp.git $AWS_CRT_CPP_VERSION \\\n\t        $CMAKE_ARGS -DUSE_OPENSSL=ON\n    else\n        CMAKE_ARGS=\"-DBUILD_SHARED_LIBS=OFF\"\n    fi\n\n    build_pkg $root/install https://github.com/aws/aws-sdk-cpp.git $AWS_SDK_CPP_VERSION \\\n            $CMAKE_ARGS -DBUILD_ONLY=kms\ndone\n", "num_lines": 73}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script installs nodejs, which we use for running some tests.\n\nset -euxo pipefail\n\nVERSION=\"node_14.x\"\nDISTRO=\"$(awk -F'=' '/UBUNTU_CODENAME/ { print $2 }' /etc/os-release)\"\n\nwget --quiet -O - https://deb.nodesource.com/gpgkey/nodesource.gpg.key | apt-key add -\necho \"deb https://deb.nodesource.com/$VERSION $DISTRO main\" | tee /etc/apt/sources.list.d/nodesource.list\necho \"deb-src https://deb.nodesource.com/$VERSION $DISTRO main\" | tee -a /etc/apt/sources.list.d/nodesource.list\n\napt-get update\napt-get install nodejs\n", "num_lines": 29}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is similar to |install-shared-deps.sh| except below differences:\n# 1. OpenSSL is replaced with awslc.\n# 2. LibCurl version is updated to 7.74.\n# After this script, awslc(static and shared) and curl will be installed under /deps/install.\n\nset -euxo pipefail\n\nexport AWSLC_SRC_DIR=/tmp/awslc\nexport INSTALL_DIR=/deps/install\nexport LD_LIBRARY_PATH=${INSTALL_DIR}\nexport NUM_CPU_THREADS=$(nproc)\n\nfunction download_awslc() {\n    AWSLC_GIT_URL='https://github.com/awslabs/aws-lc.git'\n    AWSLC_TAG='main'\n    AWSLC_SHALLOW_SINCE=\"2023-04-07T00:00:01\"\n    rm -rf ${AWSLC_SRC_DIR}\n    mkdir -p ${AWSLC_SRC_DIR}\n    git clone --shallow-since ${AWSLC_SHALLOW_SINCE} --branch ${AWSLC_TAG} \"${AWSLC_GIT_URL}\" \"${AWSLC_SRC_DIR}\"\n}\n\nfunction build_awslc() {\n    BUILD_DIR=/tmp/build/awslc\n    rm -rf ${BUILD_DIR}\n    mkdir -p ${BUILD_DIR}\n    CMAKE_BUILD_COMMAND=\"cmake ${AWSLC_SRC_DIR} $@ \\\n        -GNinja \\\n        -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \\\n        -DCMAKE_BUILD_TYPE=RelWithDebInfo\"\n    if [[ -n \"${CFLAGS-}\" ]]; then\n        CMAKE_BUILD_COMMAND=\"${CMAKE_BUILD_COMMAND} -DCMAKE_C_FLAGS=${CFLAGS}\"\n    fi\n    if [[ -n \"${CXXFLAGS-}\" ]]; then\n        CMAKE_BUILD_COMMAND=\"${CMAKE_BUILD_COMMAND} -DCMAKE_CXX_FLAGS=${CXXFLAGS}\"\n    fi\n    (cd ${BUILD_DIR} && ${CMAKE_BUILD_COMMAND})\n    cmake --build ${BUILD_DIR}\n    cmake --build ${BUILD_DIR} --target install\n    rm -rf ${BUILD_DIR}\n}\n\nfunction install_libcurl() {\n    mkdir /deps/curl\n    cd /deps/curl\n    wget https://curl.haxx.se/download/curl-7.74.0.tar.gz\n    tar xzf curl-*.tar.gz\n    cd curl-*/\n    # awslc is forked from boringssl.\n    # |OPENSSL_IS_AWSLC| macro is equivalent to |OPENSSL_IS_BORINGSSL|.\n    # Replacing OPENSSL_IS_BORINGSSL with OPENSSL_IS_AWSLC.\n    #\n    # TODO: Remove the extra command below when curl has official support for AWS-LC.\n    find ./ -type f -exec sed -i -e 's/OPENSSL_IS_BORINGSSL/OPENSSL_IS_AWSLC/g' {} \\;\n    ./configure --with-ssl=/deps/install \\\n        --prefix=/deps/install \\\n        --disable-ldap \\\n        --without-libidn \\\n        --without-gnutls \\\n        --without-nss \\\n        --without-gssapi\n    make -j\"${NUM_CPU_THREADS}\"\n    make install\n    cd /\n    rm -rf /deps/curl\n}\n\nmkdir -p /deps\n\ndownload_awslc\n\nbuild_awslc '-DBUILD_SHARED_LIBS=ON'\nbuild_awslc '-DBUILD_SHARED_LIBS=OFF'\n\ninstall_libcurl\n", "num_lines": 80}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script installs non-AWS dependencies. Currently this is openssl and libcurl.\n\n# We install openssl primarily to control the version being used, but also to turn on\n# -DPURIFY to silence some valgrind warnings.\n\n# We install libcurl because we need a version that links against the version of openssl\n# in use, to avoid version conflicts.\n\n# env variables used:\n# $OPENSSL_PLATFORM: The openssl platform name (e.g. linux-generic32)\n# CC, CXX, CFLAGS, CXXFLAGS, LDFLAGS: The usual compiler flags (as used by the respective package\n#                                     configure scripts)\n# OPENSSL_TAG: The tag or branch of openssl to build\n\n\nset -euxo pipefail\n\nmkdir -p /deps\n\ngit clone --depth 1 --branch $OPENSSL_TAG https://github.com/openssl/openssl.git /deps/openssl_src\ncd /deps/openssl_src\n# -DPURIFY tries to avoid confusing valgrind (e.g. avoiding using uninitialized memory as entropy)\n./Configure --prefix=/deps/install shared -DPURIFY $OPENSSL_PLATFORM\nmake depend\nmake -j8\nmake install\ncd /\nrm -rf /deps/openssl_src\n\n# We need a libcurl compatible with our version of openssl as well\nmkdir /deps/curl\ncd /deps/curl\nwget https://curl.haxx.se/download/curl-7.61.1.tar.gz\ntar xzf curl-*.tar.gz\ncd curl-*/\n./configure --with-ssl=/deps/install --prefix=/deps/install \\\n    --without-gnutls --without-nss --without-gssapi\nmake -j8\nmake install\ncd /\nrm -rf /deps/curl\n", "num_lines": 57}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script builds and uploads all linux docker images.\n# The ECS_REGISTRY environment variable can be used to override which registry to upload to.\n\nset -euxo pipefail\n\nECS_SERVER=\"636124823696.dkr.ecr.us-west-2.amazonaws.com\"\nECS_REGISTRY=${ECS_REGISTRY:-${ECS_SERVER}/linux-docker-images}\n_AUTH_TOKEN=`aws ecr get-login-password --region us-west-2`\ndocker login --password ${_AUTH_TOKEN}  --username AWS ${ECS_SERVER}\n\nbuild_image() {\n    docker build -t $1 -f $1.Dockerfile .\n    docker tag $1:latest $ECS_REGISTRY:$1\n    docker push $ECS_REGISTRY:$1\n}\n\nbuild_image ubuntu-latest-x64\nbuild_image ubuntu-latest-x64-awslc\n", "num_lines": 34}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# When doing rapid iteration on dockerfiles, the apt package download step can take\n# significant time. This script attempts to use an apt-cacher-ng proxy on the host\n# to reduce this time. If such a proxy is not running, we'll fall back to directly\n# connecting to the distribution's apt repository.\n\nset -euxo pipefail\n\n# Find the host's IP\nHOST_IP=`route -n | grep '^0.0.0.0' | perl -pe 's/^\\S+\\s+(\\S+)\\s.*/$1/'`\n\n# Is a proxy running?\nif nc -e /bin/true $HOST_IP 3142 < /dev/null; then\n    echo \"=== Enabling apt proxy on http://$HOST_IP:3142\"\n    echo \"Acquire::http { Proxy \\\"http://$HOST_IP:3142\\\"; };\" > /etc/apt/apt.conf.d/99proxy\nfi\n", "num_lines": 31}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script installs dependencies from APT. If specific additional dependencies are needed,\n# the $EXTRA_PACKAGES environment variable can be set from the Dockerfile to avoid having to\n# `apt-get update' twice in the dockerfile.\n\nEXTRA_PACKAGES=${EXTRA_PACKAGES:-}\n\nset -euxo pipefail\n\napt-get -y update\nexport DEBIAN_FRONTEND=noninteractive\n\napt-get -y dist-upgrade\napt-get -y install xutils-dev wget build-essential cmake3 git zlib1g-dev awscli valgrind ninja-build libjson-c-dev $EXTRA_PACKAGES\nrm -rf /var/cache/apt/* /var/lib/apt/lists/*\n\n", "num_lines": 31}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script installs dependencies from APT. If specific additional dependencies are needed,\n# the $EXTRA_PACKAGES environment variable can be set from the Dockerfile to avoid having to\n# `apt-get update' twice in the dockerfile.\n\nEXTRA_PACKAGES=${EXTRA_PACKAGES:-}\n\nset -euxo pipefail\n\napt-get -y update\nexport DEBIAN_FRONTEND=noninteractive\n\napt-get -y dist-upgrade\napt-get -y install xutils-dev wget build-essential cmake git zlib1g-dev awscli valgrind ninja-build libjson-c-dev clang-format $EXTRA_PACKAGES\nrm -rf /var/cache/apt/* /var/lib/apt/lists/*\n\n", "num_lines": 31}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n./aws-encryption-sdk-specification/util/test_conditions \\\n    -s '-r include/ --include *.h' \\\n    -s 'source/*.c' \\\n    -t '-r tests/ --include *.[ch]' \\\n    -s '-r aws-encryption-sdk-cpp/include/ --include *.h' \\\n    -s '-r aws-encryption-sdk-cpp/source/ --include *.cpp' \\\n    -t '-r aws-encryption-sdk-cpp/tests/ --include *.h' \\\n    -t '-r aws-encryption-sdk-cpp/tests/ --include *.cpp' \\\n    -s 'compliance/*.txt'\n", "num_lines": 25}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nMY_PATH=\"$(dirname \"$0\")\"\nCODEBUILD_BASE=\"$MY_PATH/..\"\n\nPREFIX_PATH=\"$1\"\nBUILD_DIR=\"$2\"\nBUILD_SHARED_LIBS=${BUILD_SHARED_LIBS:-off}\n\nrm -rf /tmp/TEST_INSTALL\ncmake -DCMAKE_INSTALL_PREFIX=/tmp/TEST_INSTALL -DBUILD_SHARED_LIBS=\"$BUILD_SHARED_LIBS\" \"$BUILD_DIR\"\ncmake --build \"$BUILD_DIR\" --target install\n\nfor i in test-install-project test-install-project-cpp; do\n    PROJECT=\"$CODEBUILD_BASE/$i\"\n    PROJECT_BUILD=\"$PROJECT/build\"\n\n    rm -rf \"$PROJECT_BUILD\"\n    mkdir \"$PROJECT_BUILD\"\n    (cd \"$PROJECT_BUILD\"; cmake .. -DBUILD_SHARED_LIBS=\"$BUILD_SHARED_LIBS\" -DCMAKE_PREFIX_PATH=\"$1;/tmp/TEST_INSTALL\")\n    cmake --build \"$PROJECT_BUILD\"\n    \"$PROJECT_BUILD/testapp\"\ndone\n", "num_lines": 39}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nmkdir -p /deps\n\n# Ubuntu 14.04's version of cmake3 is too old for the AWS SDK for C++\n# (it fails when we try to use it from the encryption SDK's build scripts).\n# We'll use the distro version to bootstrap and build a newer version.\n\n# Note that we could skip the distro version and use the ./bootstrap script\n# in the cmake distribution ... but this takes way longer, as it'll end up\n# compiling a bootstrap cmake single-threaded, then recompile cmake again\n# after configuring itself.\nmkdir -p /deps/cmake\n(cd /deps/cmake;\n wget https://cmake.org/files/v3.12/cmake-3.12.2.tar.gz;\n tar xzvf cmake-*.tar.gz;\n cd cmake-*;\n mkdir build;\n cd build;\n cmake .. -GNinja -DCMAKE_INSTALL_PREFIX=/usr/local;\n ninja;\n ninja install)\nrm -rf /deps/cmake\n\n", "num_lines": 40}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset +ex\n\nOS=$(uname -s)\nAWS_SDK_CPP_VER=\"1.8.32\"  #github versioned branch\nBUILDROOT=\"/var/tmp/build-$(date +%s)\"\nOPENSSL_VER=\"openssl@1.1\" #note this is a brew label, not an exact version reference\nBUILDROOT=\"/var/tmp/build-$(date +%Y%m%d)\"\nAWS_ENCRYPTION_SDK_C_VER=\"master\"  # Build from master\n\ndeps(){\n  echo \"Installing dependencies\" \n  if [ $(which brew|grep -c 'brew') -lt 1 ]; then\n    echo \"Can't find brew, required to build\"\n    exit 1\n  fi\n  brew install ${OPENSSL_VER} cmake || true\n  mkdir ${BUILDROOT} || true\n  mkdir ${INSTALLROOT} || true\n}\n\nbuild_cpp(){\n    echo \"Building aws-sdk-cpp\"\n    cd ${BUILDROOT}\n    git clone -b ${AWS_SDK_CPP_VER} https://github.com/aws/aws-sdk-cpp.git\n    mkdir -p ${BUILDROOT}/build-aws-sdk-cpp ||true\n    mkdir -p ${BUILDROOT}/install || true \n    cd ${BUILDROOT}/build-aws-sdk-cpp\n    # See https://docs.aws.amazon.com/sdk-for-cpp/v1/developer-guide/cmake-params.html#cmake-target-arch\n    cmake -G Xcode -DTARGET_ARCH=\"APPLE\" -DBUILD_SHARED_LIBS=ON -DBUILD_ONLY=\"kms\" -DENABLE_UNITY_BUILD=ON ../aws-sdk-cpp \n    # This target runs the cpp tests, but doesn't appear to run the other dependancy tests.\n    xcodebuild -target ALL_BUILD \n    xcodebuild -target install\n}\n\nbuild_csdk(){\n    echo \"Building aws-encryption-sdk-c\"\n    cd ${BUILDROOT}\n    git clone -b ${AWS_ENCRYPTION_SDK_C_VER} https://github.com/aws/aws-encryption-sdk-c.git \n    mkdir -p ${BUILDROOT}/build-aws-encryption-sdk-c || true\n    cd $BUILDROOT/build-aws-encryption-sdk-c\n    cmake -G Xcode -DBUILD_SHARED_LIBS=ON -DOPENSSL_ROOT_DIR=\"/usr/local/opt/${OPENSSL_VER}\" ../aws-encryption-sdk-c \n    xcodebuild -target ALL_BUILD\n    xcodebuild -scheme RUN_TESTS\n}\n\n\nif [ \"$OS\" == 'Darwin' ]; then\n    deps\n    build_cpp\n    build_csdk\nelse\n\techo \"Expecting Mac OS; exiting\"\nfi\n", "num_lines": 70}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nrm -f hello_world.txt.encrypted\nrm -f hello_world.txt.decrypted\n", "num_lines": 20}
{"repo_name": "aws-encryption-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on an\n# \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eux\n\nif [ \"$#\" -eq 0 ]; then\n    echo \"Specify option -s to start jobs, -e to end jobs, and -c to cleanup bookkeeping\"\nfi\n\nwhile getopts \":sec\" opt; do\n    case $opt in\n        s ) # Start CBMC Batch Jobs\n            for job in proofs/*/; do\n                job=${job%/} #remove trailing slash\n                job=${job#*/} #job name\n                echo \"Starting job $job\"\n                cbmc-batch \\\n                    --no-report \\\n                    --no-coverage \\\n                    --wsdir proofs/$job \\\n                    --srcdir ../ \\\n                    --jobprefix $job-local \\\n                    --yaml proofs/$job/cbmc-batch.yaml\n            done\n            ;;\n        e ) # Check CBMC Batch Job Results\n            result=\"results.txt\"\n            if [ -f $result ]; then\n                rm $result\n            fi\n            for Makefile in Makefile-*-local-*; do\n                make -f $Makefile monitor\n                make -f $Makefile copy\n                dir=${Makefile#*-} # directory name from copy\n                job=${dir%-local-*-*} # original job name\n                check=\"$( ./check_result.py $dir proofs/$job/cbmc-batch.yaml )\"\n                echo \"$job: $check\" >> $result\n            done\n            ;;\n        c ) # Cleanup\n            for Makefile in Makefile-*-local-*; do\n                make -f $Makefile cleanup\n            done\n            ;;\n        \\?)\n            echo \"Specify option -s to start jobs, -e to end jobs, and -c to cleanup bookkeeping\"\n            exit 1\n    esac\ndone\n", "num_lines": 62}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to decrypt input from the command line\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: decrypt_command_line.sh $PLAINTEXT\n\necho \"$1\" | aws-encryption-cli --decrypt \\\n                               --suppress-metadata \\\n                               --input - \\\n                               --output - \\\n                               --decode \\\n                               --buffer \\\n                               --wrapping-keys discovery=true\n", "num_lines": 16}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to decrypt all files in a directory\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: decrypt_directory.sh $INPUT_DIRECTORY $CMK_ARN $OUTPUT_DIRECTORY\n\naws-encryption-cli --decrypt \\\n                   --input $1 --recursive \\\n                   --wrapping-keys key=$2 \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --encryption-context purpose=test \\\n                   --suppress-metadata \\\n                   --max-encrypted-data-keys 1 \\\n                   --buffer \\\n                   --output $3\n", "num_lines": 18}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to decrypt a file\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: decrypt_file.sh $INPUT_FILE $CMK_ARN $OUTPUT_DIRECTORY\n\naws-encryption-cli --decrypt \\\n                   --input $1 \\\n                   --wrapping-keys key=$2 \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --encryption-context purpose=test \\\n                   --suppress-metadata \\\n                   --max-encrypted-data-keys 1 \\\n                   --buffer \\\n                   --output $3\n", "num_lines": 18}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to decrypt a file that was encrypted with multiple\n# master keys\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: decrypt_file_multiple_keys.sh $INPUT_FILE $CMK_ARN_1 $CMK_ARN_2 $OUTPUT_DIRECTORY\n\naws-encryption-cli --decrypt \\\n                   --input $1 \\\n                   --wrapping-keys key=$2 key=$3 \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --encryption-context purpose=test \\\n                   --suppress-metadata \\\n                   --max-encrypted-data-keys 2 \\\n                   --buffer \\\n                   --output $4\n", "num_lines": 19}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to encrypt input from the command line\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: encrypt_command_line.sh $PLAINTEXT $CMK_ARN\n\necho \"$1\" | aws-encryption-cli --encrypt \\\n                               --suppress-metadata \\\n                               --input - \\\n                               --output - \\\n                               --encode \\\n                               --wrapping-keys key=$2\n", "num_lines": 15}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to encrypt all files in a directory\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: encrypt_directory.sh $INPUT_DIRECTORY $CMK_ARN $OUTPUT_DIRECTORY\n\naws-encryption-cli --encrypt \\\n                   --input $1 --recursive \\\n                   --wrapping-keys key=$2 \\\n                   --suppress-metadata \\\n                   --encryption-context purpose=test \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --output $3\n", "num_lines": 16}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to encrypt a file\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: encrypt_file.sh $INPUT_FILE $CMK_ARN $OUTPUT_DIRECTORY\n\naws-encryption-cli --encrypt \\\n                   --input $1 \\\n                   --wrapping-keys key=$2 \\\n                   --suppress-metadata \\\n                   --encryption-context purpose=test \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --output $3 \n", "num_lines": 16}
{"repo_name": "aws-encryption-sdk-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Basic example invocation of the AWS Encryption CLI to encrypt a file with multiple master keys\n# See full docs for more details:\n#  https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/crypto-cli-examples.html\n\n# Usage: encrypt_file_multiple_keys.sh $INPUT_FILE $CMK_ARN_1 $CMK_ARN_2 $OUTPUT_DIRECTORY\n\naws-encryption-cli --encrypt \\\n                   --input $1 \\\n                   --wrapping-keys key=$2 key=$3 \\\n                   --suppress-metadata \\\n                   --encryption-context purpose=test \\\n                   --commitment-policy require-encrypt-require-decrypt \\\n                   --output $4\n", "num_lines": 16}
{"repo_name": "aws-encryption-sdk-dafny", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nSPEC_ROOT=aws-encryption-sdk-specification\n\n# As we make the duvet framework more robust this logic around extracting and rebuilding\n# will probably change. For now, do something simple to unblock ourselves. \nREBUILD=false\n\nif [ ! -z $1 ] && [ $1 == \"rebuild\" ] ; then\n  echo \"Re-extracting spec because it was explicitly requested\"\n  REBUILD=true\nfi\n\nif [ ! -d $SPEC_ROOT/compliance ] ; then \n  echo \"Compliance directory missing, extracting spec\"\n  REBUILD=true\nfi\n\nif [ $REBUILD == \"true\" ] ; then\n  cd aws-encryption-sdk-specification\n  ./util/specification_extract.sh\n  cd ..\nfi\n\n$SPEC_ROOT/util/report.js \\\n  $(find src -name '*.dfy') \\\n  $(find test -name '*.dfy') \\\n  $(find aws-encryption-sdk-net/Source -name '*.cs') \\\n  $(find aws-encryption-sdk-net/Test -name '*.cs') \\\n  $(find compliance_exceptions -name '*.txt')\n", "num_lines": 31}
{"repo_name": "aws-encryption-sdk-java", "repo_creator": "aws", "programming_language": "Shell", "code": "## Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n## SPDX-License-Identifier: Apache-2.0\n\n#!bin/bash\n\nVERSION=$1\nCOUNTER=0\nSTATUS=1\n\necho \"Looking for version $VERSION\"\n\nwhile [  $STATUS -ne 0 ]; do\n    mvn org.apache.maven.plugins:maven-dependency-plugin:3.0.1:get \\\n        -Dartifact=com.amazonaws:aws-encryption-sdk-java:$VERSION:jar -U\n\n    STATUS=$?\n    if [ $STATUS -eq 0 ]; then\n        echo \"Found version $VERSION in Maven Central :)\"\n        break\n    fi\n\n    if [  $((COUNTER+=1)) -eq 15 ]; then\n        echo \"It has been an awfully long time, you should check Maven Central for issues\"\n        exit 1\n    fi\n\n    echo \"Could not find version $VERSION. Trying again.\"\n    sleep 60\ndone\n", "num_lines": 30}
{"repo_name": "aws-encryption-sdk-java", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n./aws-encryption-sdk-specification/util/report.js \\\n  'src/main/**/*.java' \\\n  'src/test/**/*.java' \\\n  'compliance_exceptions/*.java'\n", "num_lines": 10}
{"repo_name": "aws-encryption-sdk-java", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n./aws-encryption-sdk-specification/util/test_conditions \\\n  -s '-r src/main/ --include *.java' \\\n  -t '-r src/test/ --include *.java' \\\n  -s 'compliance_exceptions/*.java'\n", "num_lines": 10}
{"repo_name": "aws-encryption-sdk-python", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Minimal wrapper script for upstream requirements install and freeze.\n# We do this here rather than as tox commands because tox does not support output redirection.\nif [ -z ${1} ]; then\n    exit 1\nfi\n\npip install -r requirements.txt\npip install -r dev_requirements/test-requirements.txt\npip freeze > ${1}\n", "num_lines": 11}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "echo -n \"AWS for Fluent Bit Container Image Version \"\ncat /AWS_FOR_FLUENT_BIT_VERSION\nexec /fluent-bit/bin/fluent-bit -e /fluent-bit/firehose.so -e /fluent-bit/cloudwatch.so -e /fluent-bit/kinesis.so -c /fluent-bit/etc/fluent-bit.conf\n", "num_lines": 4}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "./init/fluent_bit_init_process\nsource /init/invoke_fluent_bit.sh\n", "num_lines": 3}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nexport AWS_REGION=\"us-west-2\"\nexport PROJECT_ROOT=\"$(pwd)\"\nexport VOLUME_MOUNT_CONTAINER=\"/out\"\nexport ARCHITECTURE=$(uname -m)\n# For arm, uname evaluates to 'aarch64' but everywhere else in the pipline\n# we use 'arm64'\nif [ \"$ARCHITECTURE\" = \"aarch64\" ]; then\n    ARCHITECTURE=\"arm64\"\nfi\n\nexport CW_INTEG_VALIDATOR_IMAGE=\"${CW_INTEG_VALIDATOR_IMAGE_BASE}:${ARCHITECTURE}\"\nexport S3_INTEG_VALIDATOR_IMAGE=\"${S3_INTEG_VALIDATOR_IMAGE_BASE}:${ARCHITECTURE}\"\n\ntest_cloudwatch() {\n\texport LOG_GROUP_NAME=\"fluent-bit-integ-test-${ARCHITECTURE}\"\n\t# Tag is used to name the log stream; each test run has a unique (random) log stream name\n\texport TAG=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 10)\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.test.yml build\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.test.yml up --abort-on-container-exit\n\tsleep 120\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/cloudwatch-test\n\n\t# Validate that log data is present in CW\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.validate.yml build\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.validate.yml up --abort-on-container-exit\n}\n\nclean_cloudwatch() {\n\texport LOG_GROUP_NAME=\"fluent-bit-integ-test-${ARCHITECTURE}\"\n\t# Clean up resources that were created in the test\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.clean.yml build\n\tdocker-compose --file ./integ/test_cloudwatch/docker-compose.clean.yml up --abort-on-container-exit\n}\n\nvalidate_or_clean_s3() {\n\t# Validate: validates that appropirate log data is present in the s3 bucket\n\t# Clean: deletes all the objects from s3 bucket that were created in the test\n\texport S3_ACTION=\"${1}\"\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.validate-and-clean-s3.yml build\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.validate-and-clean-s3.yml up --abort-on-container-exit\n}\n\ntest_kinesis() {\n\t# Generates log data which will be stored on the s3 bucket\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.test.yml build\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.test.yml up --abort-on-container-exit\n\n    # Giving a pause before running the validation test\n    # Firehose delivery stream has a buffer time which causes the delay to send the data\n\tsleep 120\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/kinesis-test\n\n\tvalidate_or_clean_s3 validate\n\n\tif [ -f ./integ/out/kinesis-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for kinesis stream.\"\n\t\texit 1\n\tfi\n}\n\ntest_kinesis_streams() {\n\t# Generates log data which will be stored on the s3 bucket\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.core.test.yml build\n\tdocker-compose --file ./integ/test_kinesis/docker-compose.core.test.yml up --abort-on-container-exit\n\n    # Giving a pause before running the validation test\n    # Firehose delivery stream has a buffer time which causes the delay to send the data\n\tsleep 120\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/kinesis-test\n\n\tvalidate_or_clean_s3 validate\n\n\tif [ -f ./integ/out/kinesis-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for kinesis stream.\"\n\t\texit 1\n\tfi\n}\n\ntest_firehose() {\n\t# Generates log data which will be stored on the s3 bucket\n\tdocker-compose --file ./integ/test_firehose/docker-compose.test.yml build\n\tdocker-compose --file ./integ/test_firehose/docker-compose.test.yml up --abort-on-container-exit\n\n    # Giving a pause before running the validation test\n    # Firehose delivery stream has a buffer time which causes the delay to send the data\n\tsleep 120\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/firehose-test\n\n\tvalidate_or_clean_s3 validate\n\n\tif [ -f ./integ/out/firehose-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for firehose.\"\n\t\texit 1\n\tfi\n}\n\ntest_kinesis_firehose() {\n\t# Generates log data which will be stored on the s3 bucket\n\tdocker-compose --file ./integ/test_firehose/docker-compose.core.test.yml build\n\tdocker-compose --file ./integ/test_firehose/docker-compose.core.test.yml up --abort-on-container-exit\n\n    # Giving a pause before running the validation test\n    # Firehose delivery stream has a buffer time which causes the delay to send the data\n\tsleep 120\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/firehose-test\n\n\tvalidate_or_clean_s3 validate\n\n\tif [ -f ./integ/out/firehose-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for firehose.\"\n\t\texit 1\n\tfi\n}\n\ntest_s3() {\n\t# different S3 prefix for each test\n\texport S3_PREFIX_PUT_OBJECT=\"logs/${ARCHITECTURE}/putobject\"\n\texport S3_PREFIX_MULTIPART=\"logs/${ARCHITECTURE}/multipart\"\n\t# Tag is used in the s3 keys; each test run has a unique (random) tag\n\texport TAG=$(head /dev/urandom | tr -dc A-Za-z0-9 | head -c 10)\n\t# Generates log data which will be stored on the s3 bucket\n\tdocker-compose --file ./integ/test_s3/docker-compose.test.yml build\n\tdocker-compose --file ./integ/test_s3/docker-compose.test.yml up --abort-on-container-exit\n\n    # Giving a pause before running the validation test\n\tsleep 20\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/s3-test\n\n\texport S3_ACTION=\"validate\"\n\tdocker-compose --file ./integ/test_s3/docker-compose.validate-s3-multipart.yml build\n\tdocker-compose --file ./integ/test_s3/docker-compose.validate-s3-multipart.yml up --abort-on-container-exit\n\n\tif [ -f ./integ/out/s3-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for S3.\"\n\t\texit 1\n\tfi\n\n\t# Creates a file as a flag for the validation failure\n\tmkdir -p ./integ/out\n\ttouch ./integ/out/s3-test\n\n\texport S3_ACTION=\"validate\"\n\tdocker-compose --file ./integ/test_s3/docker-compose.validate-s3-putobject.yml build\n\tdocker-compose --file ./integ/test_s3/docker-compose.validate-s3-putobject.yml up --abort-on-container-exit\n\n\tif [ -f ./integ/out/s3-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test failed for S3.\"\n\t\texit 1\n\tfi\n}\n\n\nclean_s3() {\n\tvalidate_or_clean_s3 clean\n}\nif [ \"${1}\" = \"cloudwatch\" ]; then\n\texport CW_PLUGIN_UNDER_TEST=\"cloudwatch\"\n\ttest_cloudwatch\n\tclean_cloudwatch\n\n\tif [ -f ./integ/out/cloudwatch-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test Failed for Cloudwatch.\"\n\t\texit 1\n\tfi\nfi\n\nif [ \"${1}\" = \"cloudwatch_logs\" ]; then\n\texport CW_PLUGIN_UNDER_TEST=\"cloudwatch_logs\"\n\ttest_cloudwatch\n\tclean_cloudwatch\n\n\tif [ -f ./integ/out/cloudwatch-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test Failed for Cloudwatch.\"\n\t\texit 1\n\tfi\nfi\n\nif [ \"${1}\" = \"clean-cloudwatch\" ]; then\n\tclean_cloudwatch\nfi\n\nif [ \"${1}\" = \"kinesis\" ]; then\n\texport S3_PREFIX=\"kinesis-test\"\n\texport TEST_FILE=\"kinesis-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_kinesis\nfi\n\nif [ \"${1}\" = \"kinesis_streams\" ]; then\n\texport S3_PREFIX=\"kinesis-test\"\n\texport TEST_FILE=\"kinesis-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_kinesis_streams\nfi\n\nif [ \"${1}\" = \"firehose\" ]; then\n\texport S3_PREFIX=\"firehose-test\"\n\texport TEST_FILE=\"firehose-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_firehose\nfi\n\nif [ \"${1}\" = \"kinesis_firehose\" ]; then\n\texport S3_PREFIX=\"firehose-test\"\n\texport TEST_FILE=\"firehose-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_kinesis_firehose\nfi\n\nif [ \"${1}\" = \"s3\" ]; then\n\texport S3_PREFIX=\"logs\"\n\texport TEST_FILE=\"s3-test\"\n\texport EXPECTED_EVENTS_LEN=\"7717\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_s3\nfi\n\nif [ \"${1}\" = \"clean-s3\" ]; then\n\tsource ./integ/resources/setup_test_environment.sh\n\tclean_s3\nfi\n\nif [ \"${1}\" = \"cicd\" ]; then\n\texport CW_PLUGIN_UNDER_TEST=\"cloudwatch\"\n\techo \"Running tests on Golang CW Plugin\"\n\ttest_cloudwatch && clean_cloudwatch\n\tif [ -f ./integ/out/cloudwatch-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test Failed for Cloudwatch (Golang).\"\n\t\texit 1\n\tfi\n\n\texport CW_PLUGIN_UNDER_TEST=\"cloudwatch_logs\"\n\techo \"Running tests on Core C CW Plugin\"\n\ttest_cloudwatch && clean_cloudwatch\n\tif [ -f ./integ/out/cloudwatch-test ]; then\n\t\t# if the file still exists, test failed\n\t\techo \"Test Failed for Cloudwatch (Core).\"\n\t\texit 1\n\tfi\n\n\tsource ./integ/resources/setup_test_environment.sh\n\n\t# golang kinesis plugin\n\texport S3_PREFIX=\"kinesis-test\"\n\texport TEST_FILE=\"kinesis-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tclean_s3 && test_kinesis\n\t\n\t# golang firehose plugin\n\texport S3_PREFIX=\"firehose-test\"\n\texport TEST_FILE=\"firehose-test\"\n\tclean_s3 && test_firehose\n\n\t# core kinesis plugin\n\texport S3_PREFIX=\"kinesis-test\"\n\texport TEST_FILE=\"kinesis-test\"\n\texport EXPECTED_EVENTS_LEN=\"1000\"\n\tclean_s3 && test_kinesis_streams\n\n\t# core firehose plugin\n\texport S3_PREFIX=\"firehose-test\"\n\texport TEST_FILE=\"firehose-test\"\n\tclean_s3 && test_kinesis_firehose\n\n\texport S3_PREFIX=\"logs\"\n\texport TEST_FILE=\"s3-test\"\n\texport EXPECTED_EVENTS_LEN=\"7717\"\n\tsource ./integ/resources/create_test_resources.sh\n\tsource ./integ/resources/setup_test_environment.sh\n\n\tclean_s3 && test_s3\nfi\n\nif [ \"${1}\" = \"delete\" ]; then\n\tsource ./integ/resources/delete_test_resources.sh\nfi", "num_lines": 318}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Deploys the CloudFormation template to create the stack and necessary resources- kinesis data stream, s3 bucket, and kinesis firehose delivery stream\n# Resource (stream, s3, delivery stream) names will start with the stack name followed by the corresponding architecture. \"integ-test-fluent-bit-architecture\"\nARCHITECTURE=$(uname -m | tr '_' '-')\n# For arm, uname evaluates to 'aarch64' but everywhere else in the pipline\n# we use 'arm64'\nif [ \"$ARCHITECTURE\" = \"aarch64\" ]; then\n    ARCHITECTURE=\"arm64\"\nfi\naws cloudformation deploy --template-file ./integ/resources/cfn-kinesis-s3-firehose.yml --stack-name integ-test-fluent-bit-${ARCHITECTURE} --region us-west-2 --capabilities CAPABILITY_NAMED_IAM", "num_lines": 11}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "# Delete the CloudFormation stack which created all the resources for running the integration test\nARCHITECTURE=$(uname -m | tr '_' '-')\n# For arm, uname evaluates to 'aarch64' but everywhere else in the pipline\n# we use 'arm64'\nif [ \"$ARCHITECTURE\" = \"aarch64\" ]; then\n    ARCHITECTURE=\"arm64\"\nfi\naws cloudformation delete-stack --stack-name integ-test-fluent-bit-${ARCHITECTURE}", "num_lines": 8}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Using CloudFormation describe-stacks extracts the output values for kinesis stream and s3 bucket name, and sets them as environment variables\nARCHITECTURE=$(uname -m | tr '_' '-')\n# For arm, uname evaluates to 'aarch64' but everywhere else in the pipline\n# we use 'arm64'\nif [ \"$ARCHITECTURE\" = \"aarch64\" ]; then\n    ARCHITECTURE=\"arm64\"\nfi\nstackOutputs=$(aws cloudformation describe-stacks --stack-name integ-test-fluent-bit-${ARCHITECTURE} --output text --query 'Stacks[0].Outputs[*].OutputValue')\nread -r -a outputArray <<< \"$stackOutputs\"\nexport FIREHOSE_STREAM=\"${outputArray[0]}\"\nexport KINESIS_STREAM=\"${outputArray[1]}\"\nexport S3_BUCKET_NAME=\"${outputArray[2]}\"\n", "num_lines": 15}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Use CloudFormation describe-stacks extracts the output values for cloudwatch log group name, s3 bucket name and ecs cluster name, and sets them as environment variables\nstackOutputs=$(aws cloudformation describe-stacks --stack-name ${TESTING_RESOURCES_STACK_NAME} --output text --query 'Stacks[0].Outputs[*].OutputValue')\nread -r -a outputArray <<< \"$stackOutputs\"\nif [ $PLATFORM == \"ECS\" ]\nthen\n    export ECS_CLUSTER_NAME=\"${outputArray[0]}\"\n    export CW_LOG_GROUP_NAME=\"${outputArray[1]}\"\nelse\n    export CW_LOG_GROUP_NAME=\"${outputArray[0]}\"\nfi\nstackOutputs=$(aws cloudformation describe-stacks --stack-name ${LOG_STORAGE_STACK_NAME} --output text --query 'Stacks[0].Outputs[*].OutputValue')\nread -r -a outputArray <<< \"$stackOutputs\"\nexport S3_BUCKET_NAME=\"${outputArray[0]}\"\n\nexport AWS_DEFAULT_REGION=${AWS_REGION}\n\n# Set necessary images as env vars\nexport FLUENT_BIT_IMAGE=\"${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:latest\"\nexport ECS_APP_IMAGE=\"906394416424.dkr.ecr.us-west-2.amazonaws.com/load-test-fluent-bit-ecs-app-image:latest\"\nexport EKS_APP_IMAGE=\"906394416424.dkr.ecr.us-west-2.amazonaws.com/load-test-fluent-bit-eks-app-image:latest\"\nexport ECS_APP_IMAGE_TCP=\"906394416424.dkr.ecr.us-west-2.amazonaws.com/load-test-fluent-bit-ecs-app-image-tcp:latest\"\n# Label EKS nodes\nif [ $PLATFORM == \"EKS\" ]\nthen\n    DestinationArray=(\"cloudwatch\" \"s3\" \"kinesis\" \"firehose\")\n    for i in \"${!DestinationArray[@]}\"; do \n        export NODE_NAME=$(kubectl get nodes -o json | jq -r \".items[$i].metadata.name\")\n        kubectl label --overwrite nodes ${NODE_NAME} destination=${DestinationArray[$i]}\n    done\nfi\n", "num_lines": 33}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "mvn clean   \nmvn compile\nmvn assembly:single\nmvn package\n", "num_lines": 5}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "mvn compile\nmvn assembly:single\nmvn package\n", "num_lines": 4}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "java -cp target/my-app-1.0-SNAPSHOT-jar-with-dependencies.jar com.mycompany.app.App", "num_lines": 1}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -euo pipefail\n\n# List of arguments the script can accept\nARGUMENT_LIST=(\n  \"KINESIS_PLUGIN_CLONE_URL\"\n  \"KINESIS_PLUGIN_TAG\"\n  \"KINESIS_PLUGIN_BRANCH\"\n  \"FIREHOSE_PLUGIN_CLONE_URL\"\n  \"FIREHOSE_PLUGIN_TAG\"\n  \"FIREHOSE_PLUGIN_BRANCH\"\n  \"CLOUDWATCH_PLUGIN_CLONE_URL\"\n  \"CLOUDWATCH_PLUGIN_TAG\"\n  \"CLOUDWATCH_PLUGIN_BRANCH\"\n  \"DOCKER_BUILD_FLAGS\"\n)\n\n# A variable to hold the build arguments for docker build\nPLUGIN_BUILD_ARGS=\"\"\n\n# windows or linux\n# set by env var in Makefile right now\n# setting this by env var ensures it works even on platforms where getopt and longoptions does not work\nOS_TYPE=\"${OS_TYPE}\"\nDOCKER_BUILD_FLAGS=\"${DOCKER_BUILD_FLAGS}\"\n\n# Go plugin versions can either be set by args to the script, or they will be sourced\n# from the windows.versions or linux.version file\nKINESIS_PLUGIN_TAG=\"\"\nFIREHOSE_PLUGIN_TAG=\"\"\nCLOUDWATCH_PLUGIN_TAG=\"\"\n\n\n# Method to display usage of the script\nusage() {\n  echo \"Usage: $0 [--KINESIS_PLUGIN_CLONE_URL <string>] [--KINESIS_PLUGIN_TAG <string>] [--KINESIS_PLUGIN_BRANCH <string>]\\\n  [--FIREHOSE_PLUGIN_CLONE_URL <string>] [--FIREHOSE_PLUGIN_TAG <string>] [--FIREHOSE_PLUGIN_BRANCH <string>]\\\n  [--CLOUDWATCH_PLUGIN_CLONE_URL <string>] [--CLOUDWATCH_PLUGIN_TAG <string>] [--CLOUDWATCH_PLUGIN_BRANCH <string>] \\\n  [--DOCKER_BUILD_FLAGS <string>]\" 1>&2;\n  exit 1;\n}\n\n# Read arguments\nopts=$(getopt \\\n  --longoptions \"$(printf \"%s:,\" \"${ARGUMENT_LIST[@]}\")\" \\\n  --name \"$(basename \"$0\")\" \\\n  --options \"\" \\\n  -- \"$@\"\n)\n\neval set -- \"$opts\"\n\n# Build plugin build arguments\n#TODO: this bash does not actually work on Developer Macs for some reason\nwhile [ $# -gt 0 ]\ndo\n  case \"$1\" in\n    --KINESIS_PLUGIN_CLONE_URL)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg KINESIS_PLUGIN_CLONE_URL=$2\";fi\n      shift 2;;\n    --KINESIS_PLUGIN_TAG)\n      if [ -n \"$2\" ];then\n        PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg KINESIS_PLUGIN_TAG=$2\"\n        KINESIS_PLUGIN_TAG=\"$2\"\n      fi\n      shift 2;;\n    --KINESIS_PLUGIN_BRANCH)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg KINESIS_PLUGIN_BRANCH=$2\";fi\n      shift 2;;\n    --FIREHOSE_PLUGIN_CLONE_URL)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg FIREHOSE_PLUGIN_CLONE_URL=$2\";fi\n      shift 2;;\n    --FIREHOSE_PLUGIN_TAG)\n      if [ -n \"$2\" ];then\n        PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg FIREHOSE_PLUGIN_TAG=$2\"\n        FIREHOSE_PLUGIN_TAG=\"$2\"\n      fi\n      shift 2;;\n    --FIREHOSE_PLUGIN_BRANCH)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg FIREHOSE_PLUGIN_BRANCH=$2\";fi\n      shift 2;;\n    --CLOUDWATCH_PLUGIN_CLONE_URL)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg CLOUDWATCH_PLUGIN_CLONE_URL=$2\";fi\n      shift 2;;\n    --CLOUDWATCH_PLUGIN_TAG)\n      if [ -n \"$2\" ];then\n        PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg CLOUDWATCH_PLUGIN_TAG=$2\"\n        CLOUDWATCH_PLUGIN_TAG=\"$2\"\n      fi\n      shift 2;;\n    --CLOUDWATCH_PLUGIN_BRANCH)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg CLOUDWATCH_PLUGIN_BRANCH=$2\";fi\n      shift 2;;\n    --DOCKER_BUILD_FLAGS)\n      if [ -n \"$2\" ];then PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS $2\";fi\n      shift 2;;\n    # End of arguments. End here and break.\n    --) shift; break ;;\n    # Any other argument is an invalid arg.\n    *) usage;;\n  esac\ndone\n\n# Change the directory to root of the repository\nscripts=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\ncd \"${scripts}/..\"\n\nif [ -z \"$OS_TYPE\" ];\nthen\n  echo \"OS_TYPE is required\"\n  exit 1\nfi\n\n# Retrieve the latest version based on the platform.\nif [ \"$OS_TYPE\" == \"windows\" ];\nthen\n  latest_version=$(cat windows.versions | jq -r '.windows[] | select(.latest==true)')\nelif [ \"$OS_TYPE\" == \"linux\" ];\nthen\n  latest_version=$(cat linux.version | jq -r '.linux')\nfi\n\n# For sanity checking, find the number of latest versions present.\nlatest_counts=$(echo $latest_version | jq -r '.version' | wc -l)\n\n# If latest version is not found or if multiple entries found, then throw an error.\nif [ -z \"$latest_version\" ]\nthen\n  echo \"latest version not found for ${OS_TYPE}\"\n  exit 1\nelif [ \"$latest_counts\" -ne 1 ]; then\n  echo \"more than 1 latest versions found for ${OS_TYPE}: ${latest_version}\"\n  exit 1\nfi\n\n# Source go plugin versions from latest version, if not set.\nif [ -z \"$KINESIS_PLUGIN_TAG\" ];\nthen\n  KINESIS_PLUGIN_TAG=$(echo \"$latest_version\" | jq -r '.\"kinesis-plugin\"')\n  PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg KINESIS_PLUGIN_TAG=$KINESIS_PLUGIN_TAG\"\nfi\nif [ -z \"$FIREHOSE_PLUGIN_TAG\" ];\nthen\n  FIREHOSE_PLUGIN_TAG=$(echo \"$latest_version\" | jq -r '.\"firehose-plugin\"')\n  PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg FIREHOSE_PLUGIN_TAG=$FIREHOSE_PLUGIN_TAG\"\nfi\nif [ -z \"$CLOUDWATCH_PLUGIN_TAG\" ];\nthen\n  CLOUDWATCH_PLUGIN_TAG=$(echo \"$latest_version\" | jq -r '.\"cloudwatch-plugin\"')\n  PLUGIN_BUILD_ARGS=\"$PLUGIN_BUILD_ARGS --build-arg CLOUDWATCH_PLUGIN_TAG=$CLOUDWATCH_PLUGIN_TAG\"\nfi\n\necho \"Plugin build arguments for ${OS_TYPE} are: $PLUGIN_BUILD_ARGS\"\necho \"Docker build flags are: $DOCKER_BUILD_FLAGS\"\n\n# Run platform specific build commands\nif [ \"$OS_TYPE\" == \"windows\" ];\nthen\n  # Create the build output folder\n  mkdir -p ./build/windows\n  echo \"Created build output folder\"\n\n  # Build plugin image and then copy the windows plugins\n  docker build $PLUGIN_BUILD_ARGS -t aws-fluent-bit-plugins:latest -f ./scripts/dockerfiles/Dockerfile.plugins-windows .\n  docker create -ti --name plugin-build-container aws-fluent-bit-plugins:latest bash\n  docker cp plugin-build-container:/plugins_windows.tar ./build/windows/plugins_windows.tar\n  docker rm -f plugin-build-container\n  echo \"Copied plugin archive to the build output folder\"\nfi\n\nif [ \"$OS_TYPE\" == \"linux\" ];\nthen\n  docker build $PLUGIN_BUILD_ARGS -t aws-fluent-bit-plugins:latest -f ./scripts/dockerfiles/Dockerfile.plugins .\nfi\n\n", "num_lines": 189}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -uo pipefail\n\n#############################################################################################################\n# Helper methods to set the required variables.\n#############################################################################################################\n# Constant\n# Number of presently supported OS versions.\nSUPPORTED_WINDOWS_OS_RELEASES_NUMBER=2\n\n# Sets ALL_AWS_FOR_FLUENT_BIT_VERSIONS variable with all the supported fluent-bit versions.\nset_all_supported_versions() {\n  ALL_AWS_FOR_FLUENT_BIT_VERSIONS=$(cat < ../windows.versions | jq -c -r '.windows[].version')\n}\n\n# Sets AWS_FOR_FLUENT_BIT_STABLE_VERSION variable with the stable version.\nset_stable_version() {\n  # Find the stable version.\n  AWS_FOR_FLUENT_BIT_STABLE_VERSION=$(cat < ../windows.versions | jq -r '.windows[] | select(.stable==true)| .version')\n  STABLE_VERSION_COUNT=$(echo \"$AWS_FOR_FLUENT_BIT_STABLE_VERSION\" | wc -l)\n\n  if [ \"$STABLE_VERSION_COUNT\" -ne 1 ]; then\n    echo \"Discrepancy in stable version: ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\"\n    exit 1\n  fi\n}\n\n# Sets AWS_FOR_FLUENT_BIT_LATEST_VERSION variable with the latest version.\nset_latest_version() {\n  # Find the latest version.\n  AWS_FOR_FLUENT_BIT_LATEST_VERSION=$(cat < ../windows.versions | jq -r '.windows[] | select(.latest==true)| .version')\n  LATEST_VERSION_COUNT=$(echo \"$AWS_FOR_FLUENT_BIT_LATEST_VERSION\" | wc -l)\n\n  if [ \"$LATEST_VERSION_COUNT\" -ne 1 ]; then\n    echo \"Discrepancy in latest version: ${AWS_FOR_FLUENT_BIT_LATEST_VERSION}\"\n    exit 1\n  fi\n}\n\n# Sets AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB variable with the latest version available in dockerhub.\nset_dockerhub_version() {\n  # Find the dockerhub version.\n  docker_hub_image_tags=$(curl -s -S 'https://registry.hub.docker.com/v2/repositories/amazon/aws-for-fluent-bit/tags/?page=1&page_size=250' | jq -r '.results[].name')\n  tag_array=(`echo ${docker_hub_image_tags}`)\n  AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB=$(./get_latest_dockerhub_version.py windows latest ${tag_array[@]})\n}\n\n# Returns the regional endpoint.\n# For Standard partition, it would be \"amazonaws.com\"\n# For China partition, it would be \"amazonaws.com.cn\"\nget_regional_image_endpoint() {\n  region=${1}\n  endpoint=\"amazonaws.com\"\n\n  if [ \"${region}\" = \"cn-north-1\" ] || [ \"${region}\" = \"cn-northwest-1\" ]; then\n  \t\tendpoint=\"${endpoint}.cn\"\n  fi\n  echo \"${endpoint}\"\n}\n\n#############################################################################################################\n# Functions to compare and validate image manifests\n#############################################################################################################\n\n# Checks if the image manifest for the provided image exists in the region.\ncheck_image_manifest_exists() {\n  manifest_image=${1}\n\n  # Inspect the manifest of the image.\n  # If the same doesn't exist, return 1.\n  image_manifest=$(docker manifest inspect \"${manifest_image}\" || echo \"1\")\n\n  if [ \"${image_manifest}\" = 1 ]; then\n    echo \"No manifest found for ${manifest_image}\"\n    exit 1\n  else\n    # If the image manifest exists, then ensure that the number of digests is equal to the supported Windows releases.\n    manifest_digests=$(echo \"${image_manifest}\" | jq -r '.manifests[].digest')\n    if [ $(echo \"${manifest_digests}\" | wc -l) != $SUPPORTED_WINDOWS_OS_RELEASES_NUMBER ]; then\n      echo \"Incomplete manifest found for ${manifest_image}\"\n      exit 1\n    fi\n    echo \"Manifest validation completed for ${manifest_image}\"\n  fi\n}\n\n# Compares image manifests of two images based on the image digests.\ncompare_image_manifests() {\n  first_manifest_image=${1}\n  second_manifest_image=${2}\n\n  # Retrieve the manifests of both the images. If the same is not found then return 1.\n  first_manifest=$(docker manifest inspect \"${first_manifest_image}\" || echo \"1\")\n  second_manifest=$(docker manifest inspect \"${second_manifest_image}\" || echo \"1\")\n\n  if [ \"${first_manifest}\" = 1 ]; then\n    echo \"No manifest found for ${first_manifest_image}\"\n    return 1\n  elif [ \"${second_manifest}\" = 1 ]; then\n    echo \"No manifest found for ${second_manifest_image}\"\n    return 1\n  fi\n\n  # Obtain the digest entries from the manifest.\n  first_manifest_digests=$(echo \"${first_manifest}\" | jq -r '.manifests[].digest' | sort)\n  second_manifest_digests=$(echo \"${second_manifest}\" | jq -r '.manifests[].digest' | sort)\n\n  # Compare the digest entries of both the manifests.\n  if [ $(echo \"$first_manifest_digests\" | wc -l) != $(echo \"$second_manifest_digests\" | wc -l) ]; then\n    echo \"Mismatch in manifests due to different number of manifest entries\"\n    return 1\n  elif ! diff <(echo \"${first_manifest_digests}\") <(echo \"${second_manifest_digests}\"); then\n    echo \"Mismatch in manifests: First: ${first_manifest_digests}, Second: ${second_manifest_digests}\"\n    return 1\n  else\n    echo \"Manifests are same\"\n  fi\n}\n\n# Set the required variables\nset_all_supported_versions\nset_latest_version\nset_dockerhub_version\nset_stable_version\n", "num_lines": 138}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n\n# This script uploads the following to the provided S3 bucket under S3_KEY_PREFIX\n#   <s3_key>_<date>_HOSTNAME_RANDOM.core.zip\n#   <s3_key>_<date>_HOSTNAME_RANDOM.executable\n#   <s3_key>_<date>_HOSTNAME_RANDOM.stacktrace\n#   <s3_key>_<date>_HOSTNAME_RANDOM.all.zip\n\nexport S3_BUCKET=$1\nexport S3_KEY_PREFIX=$2\nexport RUN_ID=$3\nexport CRASH_FOLDER=\"/cores-out\" # Add all crash files to a cores-out folder for staging,\n                                 # then copy over to the mounted volume /cores\n\n# Folder Structure\n# $CRASH_FOLDER: All the crash symbol information is combined and added to this folder.\n#    It is uploaded to s3 and added to the /cores folder\n# /cores: Files are sent to the cores folder\n\n# Process crash symbols\nexport CORE_FILENAME=`basename $S3_KEY_PREFIX`_`date +\"%FT%H%M%S\"`${HOSTNAME+_host-$HOSTNAME}_${RUN_ID}\n\n# Check if there is a corefile\nexport NO_CORE_STR=\"ls: cannot access $CRASH_FOLDER/core*: No such file or directory\"\nexport LS_CORE_STR=\"$(ls $CRASH_FOLDER/core* 2>&1 >/dev/null)\"\n\nif [ \"$NO_CORE_STR\" == \"$LS_CORE_STR\" ]; then\n\n    # No corefile\n    echo \"No core file to upload\"\nelse\n    # Zip and upload the core file first incase the other processes fail\n    mv `ls $CRASH_FOLDER/core*` ${CORE_FILENAME}.core\n    zip $CRASH_FOLDER/${CORE_FILENAME}.core.zip $CRASH_FOLDER/${CORE_FILENAME}.core\n\n    # $CRASH_FOLDER\n    #   - CORE_FILENAME.core.zip\n    #   - CORE_FILENAME.core\n\n    # Upload core zip\n    aws s3 cp $CRASH_FOLDER/${CORE_FILENAME}.core.zip s3://${S3_BUCKET}/${S3_KEY_PREFIX}/\n\n    # Remove corefile zip to root folder\n    mv $CRASH_FOLDER/${CORE_FILENAME}.core.zip /tmp/${CORE_FILENAME}.core.zip\n\n    # $CRASH_FOLDER\n    #   - CORE_FILENAME.core\n\n    # Process corefile, get stack trace and fluent bit executable. Add to zip.\n    cp /fluent-bit/bin/fluent-bit ./${CORE_FILENAME}.executable\n    gdb -batch -ex 'thread apply all bt full' -ex 'quit' '/fluent-bit/bin/fluent-bit' ${CORE_FILENAME}.core > $CRASH_FOLDER/${CORE_FILENAME}.stacktrace\n\n    # $CRASH_FOLDER\n    #   - CORE_FILENAME.core\n    #   - CORE_FILENAME.executable\n    #   - CORE_FILENAME.stacktrace\n\n    # Zip the crashfiles\n    zip -r $CRASH_FOLDER/${CORE_FILENAME}.all.zip $CRASH_FOLDER\n    rm $CRASH_FOLDER/${CORE_FILENAME}.core\n    mv /tmp/${CORE_FILENAME}.core.zip $CRASH_FOLDER/${CORE_FILENAME}.core.zip\n\n    # $CRASH_FOLDER\n    #   - CORE_FILENAME.core.zip\n    #   - CORE_FILENAME.executable\n    #   - CORE_FILENAME.stacktrace\n    #   - CORE_FILENAME.all.zip\n\n    # Send crash files to the /cores/ folder\n    cp $CRASH_FOLDER/* /cores/\n\n    # Send crash files to S3\n    aws s3 cp $CRASH_FOLDER s3://${S3_BUCKET}/${S3_KEY_PREFIX}/ --recursive\n\n    # Log stacktrace\n    echo \"Stacktrace - ${CORE_FILENAME}.stacktrace:\"\n    cat /cores/${CORE_FILENAME}.stacktrace\n\n    # Delay for 1 minute to allow for slow EFS uploads to complete if used\n    echo \"Waiting 1 minute for EFS core file transfers to complete\"\n    sleep 60\nfi\n", "num_lines": 95}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -uo pipefail\n\n#############################################################################################################\n# Start of the script\n#############################################################################################################\n\n# Source the common methods\nsource ./common_windows.sh\n# Get the regional endpoint variable\nimage_endpoint=$(get_regional_image_endpoint \"${AWS_REGION}\")\n\n# Declare constants\nexport DOCKER_CLI_EXPERIMENTAL=enabled\ndeclare -A os_releases=( [\"windows2019\"]=\"ltsc2019\" [\"windows2022\"]=\"ltsc2022\")\n\n#############################################################################################################\n# Login into regional ECR of the region where we want to push the manifest.\n# We also generate the Repository path here specific to regional ECR.\n#############################################################################################################\nif [[ $REGISTRY_TO_PUSH == \"private-ecr\" ]]; then\n  # Create Repository path specific for private ECR.\n  REGISTRY=\"${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.${image_endpoint}\"\n  REPOSITORY_PATH=\"${REGISTRY}/${REPOSITORY}\"\n\n  # Login into ECR of the region.\n  aws ecr get-login-password --region ${AWS_REGION}| docker login --username AWS --password-stdin ${REGISTRY}\n\n#############################################################################################################\n# Login into public ECR of the account where we want to push the manifest.\n# In order to do so, we assume a cross-account IAM role.\n# We also generate the Repository path here specific to public ECR.\n#############################################################################################################\nelif [[ $REGISTRY_TO_PUSH == \"public-ecr\" ]]; then\n  # Create Repository path specific for public ECR.\n  REGISTRY=\"public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}\"\n  REPOSITORY_PATH=\"${REGISTRY}/${REPOSITORY}\"\n\n  # Assume the publish role for public ecr.\n  CREDS=`aws sts assume-role --role-arn ${PUBLISH_ROLE_ARN_PUBLIC_ECR} --role-session-name publicECR`\n  export AWS_ACCESS_KEY_ID=`echo $CREDS | jq -r .Credentials.AccessKeyId`\n  export AWS_SECRET_ACCESS_KEY=`echo $CREDS | jq -r .Credentials.SecretAccessKey`\n  export AWS_SESSION_TOKEN=`echo $CREDS | jq -r .Credentials.SessionToken`\n\n  # Login into public ECR\n  aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${REGISTRY}\n\n#############################################################################################################\n# Login into dockerhub account where we want to push the manifest.\n# In order to do so, we get the credentials stored in Secrets Manager.\n# We also generate the Repository path here specific to dockerhub.\n#############################################################################################################\nelif [[ $REGISTRY_TO_PUSH == \"dockerhub\" ]]; then\n  # Create Repository path specific for Dockerhub.\n  REPOSITORY_PATH=\"${REPOSITORY}\"\n\n  # Login into dockerhub account\n  DOCKER_HUB_SECRET=\"com.amazonaws.dockerhub.aws-for-fluent-bit.credentials\"\n  docker login \\\n  -u \"$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.username')\" \\\n  --password \"$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.password')\"\n\n#############################################################################################################\n# Other registries are not supported.\n#############################################################################################################\nelse\n  echo \"Unsupported registry: ${REGISTRY_TO_PUSH}\"\n  exit 1\nfi\n\n#############################################################################################################\n# \"create-manifest\" action is used to create and push manifests for Windows in the target region and account.\n#############################################################################################################\nif [[ $ACTION == \"create-manifest\" ]]; then\n\n  # Create and push the image manifests for all the versions.\n  while read -r version; do\n    # Create image manifest.\n    docker manifest create ${REPOSITORY_PATH}:${version}-windowsservercore \\\n    ${REPOSITORY_PATH}:${version}-${os_releases[windows2019]} \\\n    ${REPOSITORY_PATH}:${version}-${os_releases[windows2022]}\n    if [ $? = 1 ]; then\n      echo \"Failed to create manifest for ${REPOSITORY_PATH}:${version}-windowsservercore\"\n      exit 1\n    fi\n\n    # Sanity check the manifest.\n    docker manifest inspect ${REPOSITORY_PATH}:${version}-windowsservercore\n\n    # Push manifest to ECR.\n    docker manifest push ${REPOSITORY_PATH}:${version}-windowsservercore\n    if [ $? = 1 ]; then\n      echo \"Failed to push manifest ${REPOSITORY_PATH}:${version}-windowsservercore\"\n      exit 1\n    fi\n  done <<< \"$(echo \"${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}\")\"\n\n  # Create manifest for latest image.\n  docker manifest create ${REPOSITORY_PATH}:windowsservercore-latest \\\n  ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-${os_releases[windows2019]} \\\n  ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-${os_releases[windows2022]}\n  if [ $? = 1 ]; then\n    echo \"Failed to create manifest for ${REPOSITORY_PATH}:windowsservercore-latest\"\n    exit 1\n  fi\n\n  # Push manifest for latest image.\n  docker manifest push ${REPOSITORY_PATH}:windowsservercore-latest\n  if [ $? = 1 ]; then\n    echo \"Failed to push manifest ${REPOSITORY_PATH}:windowsservercore-latest\"\n    exit 1\n  fi\n\n#############################################################################################################\n# \"sync-stable-image\" action is used to sync stable image in target repository/region/account.\n#############################################################################################################\nelif [[ $ACTION == \"sync-stable-image\" ]]; then\n  # Obtain the image URLs for expected and actual stable Windows image.\n  EXPECTED_IMAGE_FOR_STABLE=\"${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-windowsservercore\"\n  ACTUAL_IMAGE_FOR_STABLE=\"${REPOSITORY_PATH}:windowsservercore-stable\"\n\n  # If the image manifests are not same then create and push the latest one.\n  compare_image_manifests \"${EXPECTED_IMAGE_FOR_STABLE}\" \"${ACTUAL_IMAGE_FOR_STABLE}\"\n  if [ $? = 1 ]; then\n      # Create manifest for stable image.\n      docker manifest create ${REPOSITORY_PATH}:windowsservercore-stable \\\n      ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-${os_releases[windows2019]} \\\n      ${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-${os_releases[windows2022]}\n\n      # Push manifest for stable image.\n      docker manifest push ${REPOSITORY_PATH}:windowsservercore-stable\n      if [ $? = 1 ]; then\n        echo \"Failed to push manifest ${REPOSITORY_PATH}:windowsservercore-stable\"\n        exit 1\n      fi\n      echo \"Synced the latest version of stable image\"\n  else\n    echo \"Stable image is already in sync\"\n  fi\n#############################################################################################################\n# Any other action is not supported.\n#############################################################################################################\nelse\n  echo \"Unsupported action: ${ACTION}\"\n  exit 1\nfi\n", "num_lines": 160}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nVERSION=$1\nif [ -z \"$VERSION\" ]; then\n    echo \"Usage $0 <version>\"\n    echo \"Example: $0 2.31.11 \"\n    exit 1;\nfi\n\nimage_shas=$(aws ecr describe-images --registry-id 906394416424 --repository-name aws-for-fluent-bit --region us-west-2 --image-ids imageTag=${VERSION} imageTag=arm64-${VERSION} imageTag=amd64-${VERSION} imageTag=init-arm64-${VERSION} imageTag=init-amd64-${VERSION} imageTag=${VERSION}-windowsservercore imageTag=${VERSION}-ltsc2019 imageTag=${VERSION}-ltsc2022 | jq -r '.imageDetails[] | objects | .imageDigest')\n\nimage_sha_array=($image_shas)\n\necho \"Paste below query into Athena console and replace eventTime with desired data range\"\necho \"This can be used to obtain 'private' ECR download count\"\necho \"The query is for classic regions but can be used in other regions by changing the table name to 'cloudtrail_fluentbit'\"\necho \"-------\"\necho \"\"\necho \"\nSELECT COUNT(*) as call_count\nFROM cloudtrail_fluentbitimage\nWHERE\n    eventsource = 'ecr.amazonaws.com' AND\n    eventname in ('GetDownloadUrlForLayer', 'BatchGetImage') AND\n    eventTime > 'YYYY-MM-DDT00:00:00Z' AND\n    eventTime < 'YYYY-MM-DDT00:00:00Z' AND (\n      requestparameters like '%\"imageTag\":\"${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"amd64-${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"arm64-${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"init-${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"init-amd64-${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"init-arm64-${VERSION}\"%' OR\n      requestparameters like '%\"imageTag\":\"${VERSION}-windowsservercore\"%' OR\n      requestparameters like '%\"imageTag\":\"${VERSION}-ltsc2019\"%' OR\n      requestparameters like '%\"imageTag\":\"${VERSION}-ltsc2022\"%' OR\n      requestparameters like '%${image_sha_array[0]}%' OR\n      requestparameters like '%${image_sha_array[1]}%' OR\n      requestparameters like '%${image_sha_array[2]}%' OR\n      requestparameters like '%${image_sha_array[3]}%' OR\n      requestparameters like '%${image_sha_array[4]}%' OR\n      requestparameters like '%${image_sha_array[5]}%' OR\n      requestparameters like '%${image_sha_array[6]}%' OR\n      requestparameters like '%${image_sha_array[7]}%'\n    )\n\"\n\n", "num_lines": 47}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -xeuo pipefail\n\nscripts=$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\ncd \"${scripts}\"\n\nIMAGE_SHA_MATCHED=\"FALSE\"\nAWS_FOR_FLUENT_BIT_VERSION=$(cat ../AWS_FOR_FLUENT_BIT_VERSION)\nAWS_FOR_FLUENT_BIT_STABLE_VERSION=$(cat ../AWS_FOR_FLUENT_BIT_STABLE_VERSION)\n\nPUBLISH_LATEST=$(cat ../linux.version | jq -r '.linux.latest')\necho \"Publish Latest? ${PUBLISH_LATEST}\"\n\n# Problem: when we push a new version bump the version number in AWS_FOR_FLUENT_BIT_VERSION file changes\n# but that version is not published immediately. Thus, sync tasks normally\n# sync latest version found in DockerHub. But what if we want to release a non-latest version?\n# then sync tasks need to know this. So we use the script to check for an already published version\n# that's not latest\n\n# this code currenly works because DockerHub returns the only last 100 tags and as of March 2023 we only have 64\n# and it should keep working because dockerhub returns the latest tags first\ndocker_hub_image_tags=$(curl -s -S 'https://registry.hub.docker.com/v2/repositories/amazon/aws-for-fluent-bit/tags/?page=1&page_size=250' | jq -r '.results[].name')\ntag_array=(`echo ${docker_hub_image_tags}`)\nAWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB=$(./get_latest_dockerhub_version.py linux latest ${tag_array[@]})\n\n# If the AWS_FOR_FLUENT_BIT_VERSION is an older version which is already published to dockerhub\n# and latest is set to false in linux.version, then we sync an older non-latest version.\n# otherwise, normal behavior, sync latest version found in dockerhub\nif [ \"${PUBLISH_LATEST}\" = \"false\" ]; then\n\tPUBLISH_NON_LATEST=$(./get_latest_dockerhub_version.py linux ${AWS_FOR_FLUENT_BIT_VERSION} ${tag_array[@]})\n\tif [ \"${PUBLISH_NON_LATEST}\" = \"true\" ]; then\n\t\tAWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB=${AWS_FOR_FLUENT_BIT_VERSION}\n\tfi\nfi\n\n\n# Enforce STS regional endpoints\nAWS_STS_REGIONAL_ENDPOINTS=regional\n\n\nclassic_regions=\"\nus-east-1\neu-west-1\nus-west-1\nap-southeast-1\nap-northeast-1\nus-west-2\nsa-east-1\nap-southeast-2\neu-central-1\nap-northeast-2\nap-south-1\nus-east-2\nca-central-1\neu-west-2\neu-west-3\neu-north-1\nap-northeast-3\n\"\n\nclassic_regions_account_id=\"906394416424\"\n\ncn_regions=\"\ncn-north-1\ncn-northwest-1\n\"\n\ncn_regions_account_id=\"128054284489\"\n\ngov_regions=\"\nus-gov-east-1\nus-gov-west-1\n\"\n\ngov_regions_account_id=\"161423150738\"\n\nhongkong_region=\"ap-east-1\"\n\nhongkong_account_id=\"449074385750\"\n\nbahrain_region=\"me-south-1\"\n\nbahrain_account_id=\"741863432321\"\n\ncape_town_region=\"af-south-1\"\n\ncape_town_account_id=\"928143927712\"\n\nmilan_region=\"eu-south-1\"\n\nmilan_account_id=\"960320637246\"\n\njakarta_region=\"ap-southeast-3\"\n\njakarta_account_id=\"921575906885\"\n\nuae_region=\"me-central-1\"\n\nuae_account_id=\"358001906437\"\n\nspain_region=\"eu-south-2\"\n\nspain_account_id=\"146576467002\"\n\nzurich_region=\"eu-central-2\"\n\nzurich_account_id=\"269912160255\"\n\nhyderabad_region=\"ap-south-2\"\n\nhyderabad_account_id=\"378905956269\"\n\ngamma_region=\"us-west-2\"\n\ngamma_account_id=\"626332813196\"\n\nDOCKER_HUB_SECRET=\"com.amazonaws.dockerhub.aws-for-fluent-bit.credentials\"\n\nARCHITECTURES=(\"amd64\" \"arm64\")\n\n# This variable is used in the image tag\ninit=\"init\"\n\ndocker_hub_login() {\n\tusername=\"$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.username')\"\n\tpassword=\"$(aws secretsmanager get-secret-value --secret-id $DOCKER_HUB_SECRET --region us-west-2 | jq -r '.SecretString | fromjson.password')\"\n\n\t# Logout when the script exits\n\ttrap cleanup EXIT\n\tcleanup() {\n\t\tdocker logout\n\t}\n\n\t# login to DockerHub\n\tdocker login -u \"${username}\" --password \"${password}\"\n}\n\npublish_to_docker_hub() {\n\texport DOCKER_CLI_EXPERIMENTAL=enabled\n\n\tdocker_hub_login\n\n\tif [ $# -eq 2 ]; then\n\t\t# Get the image SHA's\n\t\tdocker pull ${1}:stable || echo \"0\"\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${1}:stable || echo \"0\")\n\t\tdocker pull ${1}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${1}:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})\n\n\t\tmatch_two_sha $sha1 $sha2\n\n\t\tif [ \"$IMAGE_SHA_MATCHED\" = \"FALSE\" ]; then\n\t\t\tcreate_manifest_list ${1} \"stable\" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tfi\n\telse\n\t\tfor arch in \"${ARCHITECTURES[@]}\"\n\t\tdo\n\t\t\tdocker tag ${1}:\"$arch\" ${1}:\"${arch}\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push ${1}:\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tdocker tag ${1}:\"$arch\"-\"debug\" ${1}:\"${arch}\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push ${1}:\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\t\n\t\t\tdocker tag ${1}:\"$init\"-\"$arch\" ${1}:\"$init\"-\"${arch}\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push ${1}:\"$init\"-\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tdocker tag ${1}:\"$init\"-\"$arch\"-\"debug\" ${1}:\"$init\"-\"${arch}\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push ${1}:\"$init\"-\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tdone\n\n\t\tcreate_manifest_list ${1} ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tcreate_manifest_list ${1} \"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tcreate_manifest_list_init ${1} \"$init\"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tcreate_manifest_list_init ${1} \"$init\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\t\tcreate_manifest_list ${1} \"latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tcreate_manifest_list ${1} \"debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tcreate_manifest_list_init ${1} \"init-latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tcreate_manifest_list_init ${1} \"init-debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tfi\n\tfi\n}\n\npublish_to_public_ecr() {\n\tif [ $# -eq 2 ]; then\n\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:stable || echo \"0\"\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:stable || echo \"0\")\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})\n\n\t\tmatch_two_sha $sha1 $sha2\n\n\t\tif [ \"$IMAGE_SHA_MATCHED\" = \"FALSE\" ]; then\n\t\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\t\tcreate_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit \"stable\" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tfi\n\telse\n\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\n\t\tfor arch in \"${ARCHITECTURES[@]}\"\n\t\tdo\n\t\t\tdocker tag ${1}:\"$arch\" public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tdocker tag ${1}:\"$arch\"-\"debug\" public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tdocker tag ${1}:\"$init\"-\"$arch\" public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tdocker tag ${1}:\"$init\"-\"$arch\"-\"debug\" public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\tdocker push public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tdone\n\n\t\tcreate_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\tcreate_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit \"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\n\t\tcreate_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit \"$init\"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\tcreate_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit \"$init\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\t\tcreate_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit \"latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\t\tcreate_manifest_list public.ecr.aws/aws-observability/aws-for-fluent-bit \"debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\t\tcreate_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit \"init-latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability\n\t\t\tcreate_manifest_list_init public.ecr.aws/aws-observability/aws-for-fluent-bit \"init-debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tfi\n\tfi\n}\n\npublish_ssm() {\n\t# This optional parameter indicates if we should publish stable (defaults to false)\n\tif [ ${4:-false} = true ]; then\n\t\taws ssm put-parameter --name /aws/service/aws-for-fluent-bit/stable --overwrite \\\n\t\t\t--description 'Regional Amazon ECR Image URI for the latest stable AWS for Fluent Bit Docker Image' \\\n\t\t\t--type String --region ${1} --value ${2}:${3}\n\telse\n\t\taws ssm put-parameter --name /aws/service/aws-for-fluent-bit/${3} --overwrite \\\n\t\t\t--description 'Regional Amazon ECR Image URI for the latest AWS for Fluent Bit Docker Image' \\\n\t\t\t--type String --region ${1} --value ${2}:${3}\n\n\t\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\t\taws ssm put-parameter --name /aws/service/aws-for-fluent-bit/latest --overwrite \\\n\t\t\t\t--description 'Regional Amazon ECR Image URI for the latest AWS for Fluent Bit Docker Image' \\\n\t\t\t\t--type String --region ${1} --value ${2}:latest\n\t\tfi\n\t\t\n\t\taws ssm put-parameter --name /aws/service/aws-for-fluent-bit/\"$init\"-${3} --overwrite \\\n\t\t\t--description 'Regional Amazon ECR Image URI for the \"$init\"-latest AWS for Fluent Bit Docker Image' \\\n\t\t\t--type String --region ${1} --value ${2}:\"$init\"-${3}\n\n\t\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\t\taws ssm put-parameter --name /aws/service/aws-for-fluent-bit/\"$init\"-latest --overwrite \\\n\t\t\t\t--description 'Regional Amazon ECR Image URI for the \"$init\"-latest AWS for Fluent Bit Docker Image' \\\n\t\t\t\t--type String --region ${1} --value ${2}:\"$init\"-latest\n\t\tfi\n\tfi\n}\n\nrollback_ssm() {\n\taws ssm delete-parameter --name /aws/service/aws-for-fluent-bit/${AWS_FOR_FLUENT_BIT_VERSION} --region ${1}\n\n\taws ssm delete-parameter --name /aws/service/aws-for-fluent-bit/\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION} --region ${1}\n}\n\ncheck_parameter() {\n\trepo_uri=$(aws ssm get-parameter --name /aws/service/aws-for-fluent-bit/${2} --region ${1} --query 'Parameter.Value')\n\tIFS='.' read -r -a array <<<\"$repo_uri\"\n\tregion=\"${array[3]}\"\n\tif [ \"${1}\" != \"${region}\" ]; then\n\t\techo \"${1}: Region found in repo URI does not match SSM Parameter region: ${repo_uri}\"\n\t\texit 1\n\tfi\n\t# remove leading and trailing quotes from repo_uri\n\trepo_uri=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$repo_uri\")\n\tdocker pull $repo_uri\n\n\tif [ \"${2}\" != \"stable\" ]; then \n\t\trepo_uri_init=$(aws ssm get-parameter --name /aws/service/aws-for-fluent-bit/\"$init\"-${2} --region ${1} --query 'Parameter.Value')\n\t\tIFS='.' read -r -a array <<<\"$repo_uri_init\"\n\t\tregion=\"${array[3]}\"\n\t\tif [ \"${1}\" != \"${region}\" ]; then\n\t\t\techo \"${1}: Region found in repo URI does not match SSM Parameter region: ${repo_uri}\"\n\t\t\texit 1\n\t\tfi\n\t\t# remove leading and trailing quotes from repo_uri\n\t\trepo_uri_init=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$repo_uri\")\n\t\tdocker pull $repo_uri_init\n\tfi\n}\n\nsync_public_and_repo() {\n\tregion=${1}\n\taccount_id=${2}\n\tendpoint=${3}\n\ttag=${4}\n\n\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag}\n\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag})\n\taws ecr get-login-password --region ${region}| docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.${endpoint}\n\trepoList=$(aws ecr describe-repositories --region ${region})\n\trepoName=$(echo $repoList | jq .repositories[0].repositoryName)\n\tif [ \"$repoName\" = '\"aws-for-fluent-bit\"' ]; then\n\t\ttagCount=$(aws ecr list-images  --repository-name aws-for-fluent-bit --region ${region} | jq -r '.imageIds[].imageTag' | grep -c ${tag} || echo \"0\")\n\t\tif [ \"$tagCount\" = '1' ]; then\n\t\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag}\n\t\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag})\n\t\telse\n\t\t\tsha2='repo_not_found'\n\t\tfi\n\telse\n\t\tsha2='repo_not_found'\n\tfi\n\n\tmatch_two_sha $sha1 $sha2\n\n\tif [ \"$IMAGE_SHA_MATCHED\" = \"FALSE\" ]; then\n\t\taws ecr create-repository --repository-name aws-for-fluent-bit --image-scanning-configuration scanOnPush=true --region ${region}  || true\n\t\tpush_image_ecr public.ecr.aws/aws-observability/aws-for-fluent-bit:${tag} \\\n\t\t\t${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${tag}\n\tfi\n}\n\nsync_ssm() {\n\tnamespace_path=${1}\n\tregion=${2}\n\trepo=${3}\n\ttag=${4}\n\n\t# Check the namespace_path looking for stable at the end, if the string were too short it would return an empty string\n\tis_stable=false\n\tif [ \"${namespace_path:(-6)}\" = \"stable\" ]; then\n\t\tis_stable=true\n\tfi\n\n\tinvalid_parameter=\n\tshould_prepare=false\n\t# Check to see if namespace is prepared, once a parameter is put into namespace requests should not fail\n\tif ! ssm_parameters=$(aws ssm get-parameters --names ${namespace_path} --region ${region}); then\n\t\tshould_prepare=true\n\telse\n\t\tinvalid_parameter=$(echo $ssm_parameters | jq .InvalidParameters[0])\n\tfi\n\n\tif [ $should_prepare = true ] || [ \"$invalid_parameter\" != 'null' ]; then\n\t\tpublish_ssm ${region} ${repo} ${tag} ${is_stable}\n\tfi\n}\n\nsync_image_version() {\n\tregion=${1}\n\taccount_id=${2}\n\n\tendpoint='amazonaws.com'\n\tif [ \"${1}\" = \"cn-north-1\" ] || [ \"${1}\" = \"cn-northwest-1\" ]; then\n\t\tendpoint=${endpoint}.cn\n\tfi\n\t\n\tfor arch in \"${ARCHITECTURES[@]}\"\n\tdo\n\t\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability || echo \"0\"\n\t\tsync_public_and_repo ${region} ${account_id} ${endpoint} \"${arch}-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\"\n\n\t\tsync_public_and_repo ${region} ${account_id} ${endpoint} \"${arch}-debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\"\n\n\t\tsync_public_and_repo ${region} ${account_id} ${endpoint} \"${init}-${arch}-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\"\n\n\t\tsync_public_and_repo ${region} ${account_id} ${endpoint} \"${init}-${arch}-debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\"\n\n\t\tsync_public_and_repo ${region} ${account_id} ${endpoint} \"${arch}-${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\"\n\tdone\n\n\tif [ \"${account_id}\" != \"${classic_regions_account_id}\" ]; then\n\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"debug\"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\n\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"$init\"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"$init\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB} debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"latest\" ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\n\t\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"init-latest\" ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"init-debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tfi\n\tfi\n\n\tif [ \"${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\" != \"${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\" ]; then\n\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\tfi\n\n\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit \"stable\" ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo \"0\"\n\n\tmake_repo_public ${region}\n\n\tsync_ssm \"/aws/service/aws-for-fluent-bit/${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\" ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tsync_ssm \"/aws/service/aws-for-fluent-bit/stable\" ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\n\tstable_uri=$(aws ssm get-parameters --names /aws/service/aws-for-fluent-bit/stable --region ${region} --query 'Parameters[0].Value')\n\tstable_uri=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$stable_uri\")\n\n\tif [ \"$stable_uri\" != \"${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\" ]; then\n\t\tpublish_ssm ${region} ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_STABLE_VERSION} true\n\tfi\n}\n\nverify_ssm() {\n\tis_sync_task=${2:-false}\n\n\tendpoint='amazonaws.com'\n\t\n\tif [ \"${1}\" = \"cn-north-1\" ] || [ \"${1}\" = \"cn-northwest-1\" ]; then\n\t\tendpoint=${endpoint}.cn\n\tfi\n\taws ecr get-login-password --region ${1} | docker login --username AWS --password-stdin ${3}.dkr.ecr.${1}.${endpoint}\n\n\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\tcheck_parameter ${1} latest\n\tfi\n\n\tif [ \"${is_sync_task}\" = \"true\" ]; then\n\t\tcheck_parameter ${1} ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tcheck_parameter ${1} stable\n\telse\n\t\tcheck_parameter ${1} ${AWS_FOR_FLUENT_BIT_VERSION}\n\tfi\n}\n\ncreate_manifest_list() {\n\n\texport DOCKER_CLI_EXPERIMENTAL=enabled\n\ttag=${2}\n\tversion=${3}\n\n\t# TODO: Add a way to automatically generate arch images in manifest\n\tdocker manifest create ${1}:${tag} ${1}:arm64-${version} ${1}:amd64-${version}\n\n\tfor arch in \"${ARCHITECTURES[@]}\"\n\tdo\n\t\tdocker manifest annotate --arch \"$arch\" ${1}:${tag} ${1}:\"$arch\"-${version}\n\tdone\n\n\t# sanity check on the debug log.\n \tdocker manifest inspect ${1}:${tag}\n\tdocker manifest push ${1}:${tag}\n}\n\ncreate_manifest_list_init() {\n\n\texport DOCKER_CLI_EXPERIMENTAL=enabled\n\ttag=${2}\n\tversion=${3}\n\n\t# TODO: Add a way to automatically generate arch images in manifest\n\tdocker manifest create ${1}:${tag} ${1}:\"$init\"-arm64-${version} ${1}:\"$init\"-amd64-${version}\n\n\tfor arch in \"${ARCHITECTURES[@]}\"\n\tdo\n\t\tdocker manifest annotate --arch \"$arch\" ${1}:${tag} ${1}:\"$init\"-\"$arch\"-${version}\n\tdone\n\n\t# sanity check on the debug log.\n \tdocker manifest inspect ${1}:${tag}\n\tdocker manifest push ${1}:${tag}\n}\n\npush_image_ecr() {\n\tdocker tag ${1} ${2}\n    \tdocker push ${2}\n}\n\nmake_repo_public() {\n\taws ecr set-repository-policy --repository-name aws-for-fluent-bit --policy-text file://public_repo_policy.json --region ${1}\n}\n\npublish_ecr() {\n\tregion=${1}\n\taccount_id=${2}\n\n\taws ecr get-login-password --region ${region}| docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.amazonaws.com\n\taws ecr create-repository --repository-name aws-for-fluent-bit --image-scanning-configuration scanOnPush=true --region ${region}  || true\n\n\tfor arch in \"${ARCHITECTURES[@]}\"\n\tdo\n\t\tpush_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:\"$arch\" \\\n\t\t\t${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tpush_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:\"$arch\"-\"debug\" \\\n\t\t\t${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tpush_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:\"$init\"-\"$arch\" \\\n\t\t\t${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:\"$init\"-\"$arch\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\t\tpush_image_ecr ${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazon/aws-for-fluent-bit-test:\"$init\"-\"$arch\"-\"debug\" \\\n\t\t\t${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit:\"$init\"-\"$arch\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\tdone\n\n\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"$init\"-${AWS_FOR_FLUENT_BIT_VERSION} ${AWS_FOR_FLUENT_BIT_VERSION}\n\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"$init\"-\"debug\"-${AWS_FOR_FLUENT_BIT_VERSION} debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\n\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tcreate_manifest_list ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"init-latest\" ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tcreate_manifest_list_init ${account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit \"init-debug-latest\" debug-${AWS_FOR_FLUENT_BIT_VERSION}\n\tfi \n\n\tmake_repo_public ${region}\n}\n\nverify_ecr() {\n\tregion=${1}\n\taccount_id=${2}\n\tis_sync_task=${3:-false}\n\n\tendpoint='amazonaws.com'\n\tif [ \"${1}\" = \"cn-north-1\" ] || [ \"${1}\" = \"cn-northwest-1\" ]; then\n\t\tendpoint=${endpoint}.cn\n\tfi\n\taws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account_id}.dkr.ecr.${region}.${endpoint}\n\n\tif [ \"${is_sync_task}\" = \"true\" ]; then\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:stable || echo \"0\"\n\t\tstableSha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:stable || echo \"0\")\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo \"0\"\n\t\tstableSha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION} || echo \"0\")\n\n\t\tverify_sha $stableSha1 $stableSha2\n\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})\n\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tsha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})\n\n\t\t# verify version number tag against public ECR\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})\n\n\t\tverify_sha $sha1 $sha2\n\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:init-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tsha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:init-${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB})\n\n\t\tverify_sha $sha1_init $sha2_init\n\telse\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})\n\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION})\n\tfi\n\n\t# in main pipeline when publishing a non-latest release\n\t# we can't verify the SHA against any other tag\n\t# only verification is the above steps to pull the image\n\tif [ \"${PUBLISH_LATEST}\" = \"true\" ]; then\n\t    # Also validate version number tag against latest tag\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:latest\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:latest)\n\n\t\tverify_sha $sha1 $sha2\n\n\t\tdocker pull ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-latest\n\t\tsha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' ${account_id}.dkr.ecr.${region}.${endpoint}/aws-for-fluent-bit:\"$init\"-latest)\n\t\t\n\t\tverify_sha $sha1_init $sha2_init\n\tfi \n}\n\ncheck_image_version() {\n\texport DOCKER_CLI_EXPERIMENTAL=enabled\n\tEXIT_CODE=0\n\n\tdocker_hub_login\n\t\n\t# check if we can get the image information in dockerhub; if yes, the exit status should be 0\n\tdocker manifest inspect public.ecr.aws/aws-observability/aws-for-fluent-bit:${1} > /dev/null || EXIT_CODE=$?\n\tif [ \"${EXIT_CODE}\" = \"0\" ]; then\n\t\techo \"Accidental release: current image version from github source file match a previous version from dockerhub.\"\n\t\texit 1\n\tfi\n\n\techo \"Approved release: release the image with a new version.\"\n}\n\nverify_ecr_image_scan() {\n\tregion=${1}\n\trepo_uri=${2}\n\ttag=${3}\n\n\ttagCount=$(aws ecr list-images  --repository-name ${repo_uri} --region ${region} | jq -r '.imageIds[].imageTag' | grep -c ${tag} || echo \"0\")\n\tif [ \"$tagCount\" = '1' ]; then\n\t\taws ecr start-image-scan --repository-name ${repo_uri} --image-id imageTag=${tag} --region ${region}\n\t\taws ecr wait image-scan-complete --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag}\n\t\thighVulnerabilityCount=$(aws ecr describe-image-scan-findings --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag} | jq '.imageScanFindings.findingSeverityCounts.HIGH')\n\t\tcriticalVulnerabilityCount=$(aws ecr describe-image-scan-findings --repository-name ${repo_uri} --region ${region} --image-id imageTag=${tag} | jq '.imageScanFindings.findingSeverityCounts.CRITICAL')\n\t\tif [ \"$highVulnerabilityCount\" != null ] || [ \"$criticalVulnerabilityCount\" != null ]; then\n\t\t\techo \"Uploaded image ${tag} has ${vulnerabilityCount} vulnerabilities.\"\n\t\t\texit 1\n\t\tfi\n\tfi\n}\n\nverify_dockerhub() {\n\tdocker_hub_login\n\t\n\t# Verify the image with stable tag\n\tif [ $# -eq 1 ] || [ \"${PUBLISH_LATEST}\" = \"false\" ]; then\n\t\t# Get the image SHA's\n\t\tdocker pull amazon/aws-for-fluent-bit:stable\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:stable)\n\t\tdocker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})\n\n\t\tverify_sha $sha1 $sha2\n\telse\n\t\t# Get the image SHA's\n\t\tdocker pull amazon/aws-for-fluent-bit:latest\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:latest)\n\t\tdocker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})\n\n\t\tverify_sha $sha1 $sha2\n\n\t\tdocker pull amazon/aws-for-fluent-bit:\"$init\"-latest\n\t\tsha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:\"$init\"-latest)\n\t\tdocker pull amazon/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' amazon/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION})\n\t\tverify_sha $sha1_init $sha2_init\n\tfi\n}\n\nverify_public_ecr() {\n\taws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/aws-observability || echo \"0\"\n\n\t# Verify the image with stable tag\n\tif [ $# -eq 1 ] || [ \"${PUBLISH_LATEST}\" = \"false\" ]; then\n\t\t# Get the image SHA's\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:stable\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:stable)\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION})\n\n\t\tverify_sha $sha1 $sha2\n\telse\n\t\t# Get the image SHA's\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:latest\n\t\tsha1=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:latest)\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha2=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION})\n\n\t\tverify_sha $sha1 $sha2\n\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-latest\n\t\tsha1_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-latest)\n\t\tdocker pull public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tsha2_init=$(docker inspect --format='{{index .RepoDigests 0}}' public.ecr.aws/aws-observability/aws-for-fluent-bit:\"$init\"-${AWS_FOR_FLUENT_BIT_VERSION})\n\n\t\tverify_sha $sha1_init $sha2_init\n\tfi\n}\n\nverify_sha() {\n\tsha1=${1}\n\tsha2=${2}\n\n\tmatch_two_sha $sha1 $sha2\n\n\tif [ \"$IMAGE_SHA_MATCHED\" = \"TRUE\" ]; then\n\t\techo '[Publish Verification] Successfull'\n\t\tIMAGE_SHA_MATCHED=\"FALSE\"\n\telse\n\t\techo '[Publish Verification] Failed'\n\t\texit 1\n\tfi\n}\n\nmatch_two_sha() {\n\tsha1=${1}\n\tsha2=${2}\n\n\t# Get the last 64 chars of the SHA string\n\tlast64_1=$(echo $sha1 | egrep -o '.{1,64}$')\n\tlast64_2=$(echo $sha2 | egrep -o '.{1,64}$')\n\n\tif [ \"$last64_1\" = \"$last64_2\" ]; then\n\t\tIMAGE_SHA_MATCHED=\"TRUE\"\n\telse\n\t\tIMAGE_SHA_MATCHED=\"FALSE\"\n\tfi\n}\n\n\nif [ \"${1}\" = \"publish\" ]; then\n\tif [ \"${2}\" = \"dockerhub\" ]; then\n\t\tpublish_to_docker_hub amazon/aws-for-fluent-bit\n\tfi\n\n\tif [ \"${2}\" = \"aws\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tpublish_ecr ${region} ${classic_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-cn\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tpublish_ecr ${region} ${cn_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-us-gov\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tpublish_ecr ${region} ${gov_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tpublish_ecr ${hongkong_region} ${hongkong_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tpublish_ecr ${bahrain_region} ${bahrain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tpublish_ecr ${cape_town_region} ${cape_town_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tpublish_ecr ${milan_region} ${milan_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tpublish_ecr ${jakarta_region} ${jakarta_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tpublish_ecr ${uae_region} ${uae_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tpublish_ecr ${spain_region} ${spain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tpublish_ecr ${zurich_region} ${zurich_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tpublish_ecr ${hyderabad_region} ${hyderabad_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"gamma\" ]; then\n\t\tpublish_ecr ${gamma_region} ${gamma_account_id}\n\tfi\nfi\n\nif [ \"${1}\" = \"verify\" ]; then\n\tif [ \"${2}\" = \"dockerhub\" ]; then\n\t\tdocker pull amazon/aws-for-fluent-bit:latest\n\t\tdocker pull amazon/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_VERSION}\n\tfi\n\tif [ \"${2}\" = \"aws\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tverify_ecr ${region} ${classic_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-cn\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tverify_ecr ${region} ${cn_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-us-gov\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tverify_ecr ${region} ${gov_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tverify_ecr ${hongkong_region} ${hongkong_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tverify_ecr ${bahrain_region} ${bahrain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tverify_ecr ${cape_town_region} ${cape_town_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tverify_ecr ${milan_region} ${milan_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tverify_ecr ${jakarta_region} ${jakarta_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tverify_ecr ${uae_region} ${uae_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tverify_ecr ${spain_region} ${spain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tverify_ecr ${zurich_region} ${zurich_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tverify_ecr ${hyderabad_region} ${hyderabad_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"gamma\" ]; then\n\t\tverify_ecr ${gamma_region} ${gamma_account_id}\n\tfi\nfi\n\nif [ \"${1}\" = \"publish-ssm\" ]; then\n\tif [ \"${2}\" = \"aws\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tpublish_ssm ${region} ${classic_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-cn\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tpublish_ssm ${region} ${cn_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-us-gov\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tpublish_ssm ${region} ${gov_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tpublish_ssm ${hongkong_region} ${hongkong_account_id}.dkr.ecr.${hongkong_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tpublish_ssm ${bahrain_region} ${bahrain_account_id}.dkr.ecr.${bahrain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tpublish_ssm ${cape_town_region} ${cape_town_account_id}.dkr.ecr.${cape_town_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tpublish_ssm ${milan_region} ${milan_account_id}.dkr.ecr.${milan_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tpublish_ssm ${jakarta_region} ${jakarta_account_id}.dkr.ecr.${jakarta_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tpublish_ssm ${uae_region} ${uae_account_id}.dkr.ecr.${uae_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tpublish_ssm ${spain_region} ${spain_account_id}.dkr.ecr.${spain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tpublish_ssm ${zurich_region} ${zurich_account_id}.dkr.ecr.${zurich_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\n\n\tif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tpublish_ssm ${hyderabad_region} ${hyderabad_account_id}.dkr.ecr.${hyderabad_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\tfi\nfi\n\nif [ \"${1}\" = \"verify-ssm\" ]; then\n\tif [ \"${2}\" = \"aws\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tverify_ssm ${region} false ${classic_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-cn\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tverify_ssm ${region} false ${cn_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-us-gov\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tverify_ssm ${region} false ${gov_regions_account_id}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tverify_ssm ${hongkong_region} false ${hongkong_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tverify_ssm ${bahrain_region} false ${bahrain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tverify_ssm ${cape_town_region} false ${cape_town_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tverify_ssm ${milan_region} false ${milan_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tverify_ssm ${jakarta_region} false ${jakarta_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tverify_ssm ${uae_region} false ${uae_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tverify_ssm ${spain_region} false ${spain_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tverify_ssm ${zurich_region} false ${zurich_account_id}\n\tfi\n\n\tif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tverify_ssm ${hyderabad_region} false ${hyderabad_account_id}\n\tfi\nfi\n\nif [ \"${1}\" = \"rollback-ssm\" ]; then\n\tif [ \"${2}\" = \"aws\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\trollback_ssm ${region}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-cn\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\trollback_ssm ${region}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"aws-us-gov\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\trollback_ssm ${region}\n\t\tdone\n\tfi\n\n\tif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\trollback_ssm ${hongkong_region}\n\tfi\n\n\tif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\trollback_ssm ${bahrain_region}\n\tfi\n\n\tif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\trollback_ssm ${cape_town_region}\n\tfi\n\n\tif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\trollback_ssm ${milan_region}\n\tfi\n\n\tif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\trollback_ssm ${jakarta_region}\n\tfi\n\n\tif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\trollback_ssm ${uae_region}\n\tfi\n\n\tif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\trollback_ssm ${spain_region}\n\tfi\n\n\tif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\trollback_ssm ${zurich_region}\n\tfi\n\n\tif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\trollback_ssm ${hyderabad_region}\n\tfi\nfi\n\n# Publish using CI/CD pipeline\n# Following scripts will be called only from the CI/CD pipeline\nif [ \"${1}\" = \"cicd-publish\" ]; then\n\tif [ \"${2}\" = \"dockerhub\" ]; then\n\t\tpublish_to_docker_hub amazon/aws-for-fluent-bit\n\telif [ \"${2}\" = \"public-ecr\" ]; then\n\t\tpublish_to_public_ecr amazon/aws-for-fluent-bit\n\telif [ \"${2}\" = \"us-gov-east-1\" ] || [ \"${2}\" = \"us-gov-west-1\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tsync_image_version ${region} ${gov_regions_account_id}\n\t\tdone\n\telif [ \"${2}\" = \"cn-north-1\" ] || [ \"${2}\" = \"cn-northwest-1\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tsync_image_version ${region} ${cn_regions_account_id}\n\t\tdone\n\telif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tsync_image_version ${bahrain_region} ${bahrain_account_id}\n\telif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tsync_image_version ${hongkong_region} ${hongkong_account_id}\n\telif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tsync_image_version ${cape_town_region} ${cape_town_account_id}\n\telif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tsync_image_version ${milan_region} ${milan_account_id}\n\telif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tsync_image_version ${jakarta_region} ${jakarta_account_id}\n\telif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tsync_image_version ${uae_region} ${uae_account_id}\n\telif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tsync_image_version ${spain_region} ${spain_account_id}\n\telif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tsync_image_version ${zurich_region} ${zurich_account_id}\n\telif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tsync_image_version ${hyderabad_region} ${hyderabad_account_id}\n\telif [ $# -eq 3 ] && [ \"${3}\" = \"stable\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tsync_image_version ${region} ${classic_regions_account_id}\n\t\tdone\n\telif [ $# -eq 3 ] && [ \"${2}\" = \"public-dockerhub-stable\" ]; then\n\t\tif [ \"${3}\" = \"us-west-2\" ]; then\n\t\t\tpublish_to_docker_hub amazon/aws-for-fluent-bit stable\n\t\tfi\n\telif [ $# -eq 3 ] && [ \"${2}\" = \"public-ecr-stable\" ]; then\n\t\tif [ \"${3}\" = \"us-west-2\" ]; then\n\t\t\tpublish_to_public_ecr amazon/aws-for-fluent-bit stable\n\t\tfi\n\telse\n\t\tpublish_ecr \"${2}\" ${classic_regions_account_id}\n\tfi\nfi\n\n# Verify using CI/CD pipeline\nif [ \"${1}\" = \"cicd-verify\" ]; then\n\tif [ \"${2}\" = \"dockerhub\" ]; then\n\t\tverify_dockerhub\n\telif [ \"${2}\" = \"public-ecr\" ]; then\n\t\tverify_public_ecr\n\telif [ \"${2}\" = \"us-gov-east-1\" ] || [ \"${2}\" = \"us-gov-west-1\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tverify_ecr ${region} ${gov_regions_account_id} true\n\t\tdone\n\telif [ \"${2}\" = \"cn-north-1\" ] || [ \"${2}\" = \"cn-northwest-1\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tverify_ecr ${region} ${cn_regions_account_id} true\n\t\tdone\n\telif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tverify_ecr ${bahrain_region} ${bahrain_account_id} true\n\telif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tverify_ecr ${hongkong_region} ${hongkong_account_id} true\n\telif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tverify_ecr ${cape_town_region} ${cape_town_account_id} true\n\telif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tverify_ecr ${milan_region} ${milan_account_id} true\n\telif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tverify_ecr ${jakarta_region} ${jakarta_account_id} true\n\telif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tverify_ecr ${uae_region} ${uae_account_id} true\n\telif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tverify_ecr ${spain_region} ${spain_account_id} true\n\telif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tverify_ecr ${zurich_region} ${zurich_account_id} true\n\telif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tverify_ecr ${hyderabad_region} ${hyderabad_account_id} true\n\telif [ $# -eq 3 ] && [ \"${3}\" = \"stable\" ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tverify_ecr ${region} ${classic_regions_account_id} true\n\t\tdone\n\telif [ \"${2}\" = \"stable\" ]; then\n\t\tif [ \"${3}\" = \"us-west-2\" ]; then\n\t\t\tverify_dockerhub stable\n\t\t\tverify_public_ecr stable\n\t\tfi\n\telse\n\t\tverify_ecr \"${2}\" ${classic_regions_account_id}\n\tfi\nfi\n\n# Publish SSM parameters\nif [ \"${1}\" = \"cicd-publish-ssm\" ]; then\n\tif [ \"${2}\" = \"us-gov-east-1\" ] || [ \"${2}\" = \"us-gov-west-1\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tpublish_ssm ${region} ${gov_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tdone\n\telif [ \"${2}\" = \"cn-north-1\" ] || [ \"${2}\" = \"cn-northwest-1\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tpublish_ssm ${region} ${cn_regions_account_id}.dkr.ecr.${region}.amazonaws.com.cn/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\t\tdone\n\telif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tpublish_ssm ${bahrain_region} ${bahrain_account_id}.dkr.ecr.${bahrain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tpublish_ssm ${hongkong_region} ${hongkong_account_id}.dkr.ecr.${hongkong_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tpublish_ssm ${cape_town_region} ${cape_town_account_id}.dkr.ecr.${cape_town_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tpublish_ssm ${milan_region} ${milan_account_id}.dkr.ecr.${milan_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tpublish_ssm ${jakarta_region} ${jakarta_account_id}.dkr.ecr.${jakarta_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tpublish_ssm ${uae_region} ${uae_account_id}.dkr.ecr.${uae_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tpublish_ssm ${spain_region} ${spain_account_id}.dkr.ecr.${spain_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tpublish_ssm ${zurich_region} ${zurich_account_id}.dkr.ecr.${zurich_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tpublish_ssm ${hyderabad_region} ${hyderabad_account_id}.dkr.ecr.${hyderabad_region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\n\telse\n\t\tfor region in ${classic_regions}; do\n\t\t\tpublish_ssm ${region} ${classic_regions_account_id}.dkr.ecr.${region}.amazonaws.com/aws-for-fluent-bit ${AWS_FOR_FLUENT_BIT_VERSION}\n\t\tdone\n\tfi\nfi\n\n# Verify SSM parameters\nif [ \"${1}\" = \"cicd-verify-ssm\" ]; then\n\tif [ \"${2}\" = \"us-gov-east-1\" ] || [ \"${2}\" = \"us-gov-west-1\" ]; then\n\t\tfor region in ${gov_regions}; do\n\t\t\tverify_ssm ${region} true ${gov_regions_account_id}\n\t\tdone\n\telif [ \"${2}\" = \"cn-north-1\" ] || [ \"${2}\" = \"cn-northwest-1\" ]; then\n\t\tfor region in ${cn_regions}; do\n\t\t\tverify_ssm ${region} true ${cn_regions_account_id}\n\t\tdone\n\telif [ \"${2}\" = \"${bahrain_region}\" ]; then\n\t\tverify_ssm ${bahrain_region} true ${bahrain_account_id}\n\telif [ \"${2}\" = \"${hongkong_region}\" ]; then\n\t\tverify_ssm ${hongkong_region} true ${hongkong_account_id}\n\telif [ \"${2}\" = \"${cape_town_region}\" ]; then\n\t\tverify_ssm ${cape_town_region} true ${cape_town_account_id}\n\telif [ \"${2}\" = \"${milan_region}\" ]; then\n\t\tverify_ssm ${milan_region} true ${milan_account_id}\n\telif [ \"${2}\" = \"${jakarta_region}\" ]; then\n\t\tverify_ssm ${jakarta_region} true ${jakarta_account_id}\n\telif [ \"${2}\" = \"${uae_region}\" ]; then\n\t\tverify_ssm ${uae_region} true ${uae_account_id}\n\telif [ \"${2}\" = \"${spain_region}\" ]; then\n\t\tverify_ssm ${spain_region} true ${spain_account_id}\n\telif [ \"${2}\" = \"${zurich_region}\" ]; then\n\t\tverify_ssm ${zurich_region} true ${zurich_account_id}\n\telif [ \"${2}\" = \"${hyderabad_region}\" ]; then\n\t\tverify_ssm ${hyderabad_region} true ${hyderabad_account_id}\n\telif [ $# -eq 3 ]; then\n\t\tfor region in ${classic_regions}; do\n\t\t\tverify_ssm ${region} true ${classic_regions_account_id}\n\t\tdone\n\telse\n\t\tfor region in ${classic_regions}; do\n\t\t\tverify_ssm ${region} false ${classic_regions_account_id}\n\t\tdone\n\tfi\nfi\n\nif [ \"${1}\" = \"cicd-verify-ecr-image-scan\" ]; then\n\tverify_ecr_image_scan ${2} ${3} ${4}\nfi\n\nif [ \"${1}\" = \"cicd-check-image-version\" ]; then\n\tcheck_image_version ${AWS_FOR_FLUENT_BIT_VERSION} \nfi", "num_lines": 1190}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -uo pipefail\n\n#############################################################################################################\n# This script would be executed from a codebuild project which would set the following environment variables-\n# ACTION -> Action to perform. Can be amongst \"publish-ssm-parameters\", or \"sync-ssm-parameter\"\n# SSM_PARAM_NAMESPACE -> The SSM Parameter namespace to be used.\n# ACCOUNT_ID -> Account ID where the images are present.\n# REGIONS_TO_PUBLISH -> A comma separated list of regions where we need to publish SSM parameter.\n# PUBLIC_REGISTRY_ALIAS -> Used when syncing the SSM params.\n# PUBLIC_REPOSITORY -> Public repository which is used for the image sync.\n#############################################################################################################\n\n#############################################################################################################\n# Helper methods to publish the SSM Parameter.\n#############################################################################################################\n\n# This method publishes the SSM parameter for a given tag if the same is not present or has old data.\npublish_ssm_param() {\n  local region param_name expected_param_value ssm_parameter old_param_value\n  region=${1}\n  param_name=${2}\n  expected_param_value=${3}\n\n  echo \"Publishing ${param_name} in ${region} region.\"\n  ssm_parameter=$(aws ssm get-parameter --name \"${param_name}\" --region \"${region}\" || echo \"1\")\n  # If SSM Parameter is present then find the old value.\n  if [ \"$ssm_parameter\" != 1 ]; then\n    old_param_value=$(echo \"$ssm_parameter\" | jq -r '.Parameter.Value')\n  fi\n\n  # If the expected parameter is not present, or has old data, then put the same in SSM store.\n  if [[ \"$ssm_parameter\" = 1 || \"$old_param_value\" != \"$expected_param_value\" ]]; then\n    # Verify that the image manifest actually exists and then publish the parameter.\n    check_image_manifest_exists \"${expected_param_value}\"\n\n    aws ssm put-parameter \\\n    --region \"${region}\" \\\n    --name \"${param_name}\" \\\n    --overwrite \\\n    --description 'Regional Amazon ECR Image URI for the AWS for Fluent Bit Windows Docker Image' \\\n    --type String \\\n    --value \"${expected_param_value}\"\n\n    echo \"Published SSM parameter ${param_name} = ${expected_param_value} in ${region} region\"\n  else\n    echo \"SSM Parameter ${param_name} is already latest. Skipping.\"\n  fi\n}\n\n# Publishes SSM Parameter for a given version.\npublish_ssm_param_for_version(){\n  local region version param_name param_value\n  region=${1}\n  version=${2}\n  # Get the regional endpoint variable\n  image_endpoint=$(get_regional_image_endpoint \"${region}\")\n\n  param_name=\"${SSM_PARAM_NAMESPACE}/${version}-windowsservercore\"\n  param_value=\"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${version}-windowsservercore\"\n\n  publish_ssm_param \"${region}\" \"${param_name}\" \"${param_value}\"\n}\n\n# Publishes SSM Parameter for the latest version.\npublish_ssm_param_for_latest(){\n  local region param_name expected_param_value\n  region=${1}\n  # Get the regional endpoint variable\n  image_endpoint=$(get_regional_image_endpoint \"${region}\")\n\n  param_name=\"${SSM_PARAM_NAMESPACE}/windowsservercore-latest\"\n  expected_param_value=\"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-windowsservercore\"\n\n  publish_ssm_param \"${region}\" \"${param_name}\" \"${expected_param_value}\"\n}\n\n# Publishes SSM Parameter for the stable version.\npublish_ssm_param_for_stable(){\n  local region param_name expected_param_value\n  region=${1}\n  # Get the regional endpoint variable\n  image_endpoint=$(get_regional_image_endpoint \"${region}\")\n\n  param_name=\"${SSM_PARAM_NAMESPACE}/windowsservercore-stable\"\n  expected_param_value=\"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${AWS_FOR_FLUENT_BIT_STABLE_VERSION}-windowsservercore\"\n\n  publish_ssm_param \"${region}\" \"${param_name}\" \"${expected_param_value}\"\n}\n\n# Publishes the SSM Parameter for all the supported versions in a given region.\npublish_to_region() {\n  local region\n  region=${1}\n\n  # For a given region, iterate over all supported versions and publish them if required.\n  while read -r version; do\n    publish_ssm_param_for_version \"${region}\" \"${version}\"\n  done <<< \"$(echo \"${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}\")\"\n\n  # Finally, publish the SSM param for latest as well as Dockerhub version.\n  publish_ssm_param_for_latest $region\n  publish_ssm_param_for_version \"${region}\" \"${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\"\n}\n\n#############################################################################################################\n# Helper methods for sync task\n#############################################################################################################\n\n# Compares if the image referenced by local SSM store and that in upstream repository are same.\ncompare_latest_ssm_param_image_with_public_ecr() {\n  local region repository param_name ssm_parameter regional_ecr_image upstream_image\n  region=${1}\n  repository=${2}\n  param_name=\"${SSM_PARAM_NAMESPACE}/windowsservercore-latest\"\n  upstream_image=\"${repository}:windowsservercore-latest\"\n\n  ssm_parameter=$(aws ssm get-parameter --name \"${param_name}\" --region \"${region}\" || echo \"1\")\n  if [ \"$ssm_parameter\" = 1 ]; then\n    return 1\n  else\n    regional_ecr_image=$(echo \"$ssm_parameter\" | jq -r '.Parameter.Value')\n  fi\n\n  compare_image_manifests \"${regional_ecr_image}\" \"${upstream_image}\"\n  return $?\n}\n\n#############################################################################################################\n# Start of the script\n#############################################################################################################\n\n# Source the common methods\nsource ./common_windows.sh\n\n#############################################################################################################\n# This action would be called in classic regions where we push the SSM parameters.\n# \"publish-ssm-parameters\" action would publish a new SSM Parameter if same is not present.\n#############################################################################################################\nif [[ $ACTION == \"publish-ssm-parameters\" ]]; then\n  echo \"Publishing the SSM parameter for Windows images in regions: ${REGIONS_TO_PUBLISH}\"\n\n  # Split the comma separated list of regions into an array\n  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\\n/g'`)\n  for region in \"${REGIONS[@]}\"\n  do\n    # Get the regional endpoint variable\n    image_endpoint=$(get_regional_image_endpoint \"${region}\")\n    # Authenticate to ECR so that regional image manifest can be inspected.\n    aws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}\"\n    publish_to_region \"${region}\"\n  done\n\n#############################################################################################################\n# This action would be invoked in opt-in regions as well as other partitions.\n# We will check if the images referenced in SSM param are same as those in public ECR.\n# If not, we will update the SSM parameters with latest.\n#############################################################################################################\nelif [[ $ACTION == \"sync-ssm-parameter\" ]]; then\n  # Split the comma separated list of regions into an array\n  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\\n/g'`)\n  for region in \"${REGIONS[@]}\"\n  do\n    # Get the regional endpoint\n    image_endpoint=$(get_regional_image_endpoint \"${region}\")\n    # Authenticate to ECR so that regional image manifest can be inspected.\n    aws ecr get-login-password --region \"${region}\" | docker login --username AWS --password-stdin \"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}\"\n\n    # Publish stable parameter if it has old data.\n    publish_ssm_param_for_stable \"${region}\"\n\n    # For a given region, find if the sync is need for all other parameters.\n    repository=\"public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}/${PUBLIC_REPOSITORY}\"\n    compare_latest_ssm_param_image_with_public_ecr \"${region}\" \"${repository}\"\n\n    # If return value is 1, then publish the SSM params in this region.\n    if [ $? = 1 ]; then\n      publish_to_region \"${region}\"\n    fi\n  done\n\n#############################################################################################################\n# Any action not matching above is unsupported.\n#############################################################################################################\nelse\n  echo \"Unsupported action: ${ACTION}\"\n  exit 1\nfi\n", "num_lines": 202}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -uo pipefail\n\n#############################################################################################################\n# Start of the script\n#############################################################################################################\n\n# Source the common methods\nsource ./common_windows.sh\n# Get the regional endpoint variable\nimage_endpoint=$(get_regional_image_endpoint \"${TARGET_AWS_REGION}\")\n\n# Declare the constants\nSOURCE_REPOSITORY_URL=\"public.ecr.aws/${SOURCE_REGISTRY_ALIAS}/${SOURCE_REPOSITORY}\"\nTARGET_REPOSITORY_URL=\"${TARGET_AWS_ACCOUNT}.dkr.ecr.${TARGET_AWS_REGION}.${image_endpoint}/${TARGET_REPOSITORY}\"\n\n# Authenticate to ECR of target repository.\n# Since out sync-task workflows would only target regional ECR, we are explicitly logging into the same.\naws ecr get-login-password --region \"${TARGET_AWS_REGION}\" | docker login --username AWS --password-stdin \"${TARGET_REPOSITORY_URL}\"\n\necho \"Verifying if the images need to be synced in: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}\"\n\n# Obtain the source image and expected image url.\nLATEST_IMAGE_URI_WITH_LATEST_TAG_IN_SOURCE=\"${SOURCE_REPOSITORY_URL}:windowsservercore-latest\"\nLATEST_IMAGE_URI_WITH_LATEST_TAG_IN_TARGET=\"${TARGET_REPOSITORY_URL}:windowsservercore-latest\"\n\n# Compare manifests for both and determine if sync is required.\ncompare_image_manifests \"${LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_SOURCE}\" \"${LATEST_IMAGE_URI_WITH_LATEST_TAG_IN_TARGET}\"\nif [ $? = 1 ]; then\n  echo \"true\" > SYNC_IMAGES\n  echo \"Images need to be synced in: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}\"\nelse\n  echo \"false\" > SYNC_IMAGES\n  echo \"Images are already in sync: ${TARGET_AWS_REGION}@${TARGET_AWS_ACCOUNT}\"\nfi\n", "num_lines": 49}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -euo pipefail\n\n#############################################################################################################\n# Start of the script\n#############################################################################################################\n\n# Source the common methods\nsource ./common_windows.sh\n# Get the regional endpoint variable\nimage_endpoint=$(get_regional_image_endpoint \"${AWS_REGION}\")\n\n#############################################################################################################\n# For regional ECR, we create the specific image URL here. Additionally, we also authenticate to regional ECR.\n#############################################################################################################\nif [[ $TARGET_REGISTRY == \"private-ecr\" ]]; then\n  # Create Repository url specific for regional ECR.\n  REGISTRY=\"${AWS_ACCOUNT}.dkr.ecr.${AWS_REGION}.${image_endpoint}\"\n  REPOSITORY_PATH=\"${REGISTRY}/${REPOSITORY}\"\n\n  # Authenticate to ECR.\n  aws ecr get-login-password --region \"${AWS_REGION}\" | docker login --username AWS --password-stdin \"${REGISTRY}\"\n\n#############################################################################################################\n# For public ECR, we create the specific image URL here.\n#############################################################################################################\nelif [[ $TARGET_REGISTRY == \"public-ecr\" ]]; then\n  REGISTRY=\"public.ecr.aws/${PUBLIC_REGISTRY_ALIAS}\"\n  REPOSITORY_PATH=\"${REGISTRY}/${REPOSITORY}\"\n\n#############################################################################################################\n# For dockerhub, we create the specific image URL here.\n#############################################################################################################\nelif [[ $TARGET_REGISTRY == \"dockerhub\" ]]; then\n  REPOSITORY_PATH=\"${REPOSITORY}\"\nfi\n\n#############################################################################################################\n# For \"verify-images\" action, we will verify that the image manifest exists for all the supported versions\n# in the target registry. We will also verify the latest image and compare the image digests for the same.\n#############################################################################################################\nif [[ $ACTION == \"verify-images\" ]]; then\n  # Validate that manifest exists for all the versions.\n  while read -r version; do\n    check_image_manifest_exists \"${REPOSITORY_PATH}:${version}-windowsservercore\"\n  done <<< \"$(echo \"${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}\")\"\n\n  # Validate that latest manifest is same as the required version.\n  LATEST_IMAGE_URI_WITH_VERSION_TAG=\"${REPOSITORY_PATH}:${AWS_FOR_FLUENT_BIT_LATEST_VERSION}-windowsservercore\"\n  LATEST_IMAGE_URI_WITH_LATEST_TAG=\"${REPOSITORY_PATH}:windowsservercore-latest\"\n  compare_image_manifests \"${LATEST_IMAGE_URI_WITH_LATEST_TAG}\" \"${LATEST_IMAGE_URI_WITH_VERSION_TAG}\"\n\n#############################################################################################################\n# Any action not matching above is unsupported.\n#############################################################################################################\nelse\n  echo \"Unsupported action: ${ACTION}\"\n  exit 1\nfi\n", "num_lines": 73}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n# \thttp://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -euo pipefail\n\n#############################################################################################################\n# This script would be executed from a codebuild project which would set the following environment variables-\n# ACTION -> Action to perform. Can be amongst \"verify-ssm-parameter\"\n# SSM_PARAM_NAMESPACE -> The SSM Parameter namespace to be used.\n# ACCOUNT_ID -> Account ID where the images are present.\n# REGIONS_TO_PUBLISH -> A comma separated list of regions where we need to publish SSM parameter.\n#############################################################################################################\n\n#############################################################################################################\n# Helper methods to verify the SSM Parameter.\n#############################################################################################################\n\n# Verifies that the given param tag has the expected image in the given region and account.\nverify_ssm_param(){\n  local ssm_parameter region version param_name\n  region=${1}\n  version=${2}\n  param_tag=${3}\n\n  # Get the regional endpoint variable\n  image_endpoint=$(get_regional_image_endpoint \"${region}\")\n\n  # Get the parameter name and the expected parameter value.\n  param_name=\"${SSM_PARAM_NAMESPACE}/${param_tag}\"\n  expected_param_value=\"${ACCOUNT_ID}.dkr.ecr.${region}.${image_endpoint}/aws-for-fluent-bit:${version}-windowsservercore\"\n\n  echo \"Verifying ${param_name} in ${region} region. Expected value: ${expected_param_value}\"\n  ssm_parameter=$(aws ssm get-parameter --name \"${param_name}\" --region \"${region}\" || echo \"1\")\n  # If SSM Parameter is present then find the old value.\n  if [ \"$ssm_parameter\" != 1 ]; then\n    current_param_value=$(echo $ssm_parameter | jq -r '.Parameter.Value')\n  fi\n\n  # If the latest parameter is not present, or is different then we exit with failure code.\n  if [[ \"$current_param_value\" == \"$expected_param_value\" ]]; then\n    echo \"SSM parameter ${param_name} in ${region} region matches the expected value\"\n  else\n    echo \"SSM parameter verification of ${param_name} in ${region} region failed. Actual: ${current_param_value} : Expected: ${expected_param_value}\"\n    exit 1\n  fi\n}\n\n#############################################################################################################\n# Start of the script\n#############################################################################################################\n\n# Source the common methods\nsource ./common_windows.sh\n\n#############################################################################################################\n# If action is \"verify-ssm-parameter\" then verify that SSM parameter for each supported version is present.\n#############################################################################################################\nif [[ $ACTION == \"verify-ssm-parameter\" ]]; then\n  echo \"Verifying the SSM parameter for Windows images in region: ${REGIONS_TO_PUBLISH}\"\n\n  # Split the comma separated list of regions into an array\n  REGIONS=(`echo $REGIONS_TO_PUBLISH | sed 's/,/\\n/g'`)\n  for region in \"${REGIONS[@]}\"\n  do\n    # For a given region, iterate over all supported versions and verify the SSM parameters.\n    while read -r version; do\n        verify_ssm_param \"${region}\" \"${version}\" \"${version}-windowsservercore\"\n    done <<< \"$(echo \"${ALL_AWS_FOR_FLUENT_BIT_VERSIONS}\")\"\n\n    # Finally, verify the SSM param for latest as well as Dockerhub version.\n    verify_ssm_param \"${region}\" \"${AWS_FOR_FLUENT_BIT_LATEST_VERSION}\" \"windowsservercore-latest\"\n    verify_ssm_param \"${region}\" \"${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}\" \"${AWS_FOR_FLUENT_BIT_VERSION_DOCKERHUB}-windowsservercore\"\n    verify_ssm_param \"${region}\" \"${AWS_FOR_FLUENT_BIT_LATEST_VERSION}\" \"windowsservercore-latest\"\n  done\n\n#############################################################################################################\n# Any action not matching above is unsupported.\n#############################################################################################################\nelse\n  echo \"Unsupported action: ${ACTION}\"\n  exit 1\nfi\n", "num_lines": 94}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Arguments:\n# $1 = number log lines to write at a time\n# $2 = sleep time between writes\n\nwhile [ true ]\ndo\n    /go/bin/flog -t stdout -f apache_common -n ${1}\n    sleep ${2}\ndone\n", "num_lines": 12}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "for i in `seq 1 100`;\ndo\n  echo \"2.1.0.1 - TheDoctor 000 [$(date)] \\\"POST /cestlavie\\\" 000 $i\"\n  sleep 1\ndone\n", "num_lines": 6}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "args=\"\"\n\nfor plugin in ./.vscode/external-plugins/*; do\n    for entry in \"$plugin\"/bin/*; do\n        [[ $entry == *.so ]] && args=\"${args} -e ${entry}\"\n    done\ndone\n\necho \"$args\"\n", "num_lines": 10}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Rebuild External Plugins (on Change)\n# For VSCode Fluent-Bit\n# The following detects changes to the following\n# watched directories and files, and will initiate a\n# rebuild on modification.\nwatch='*' # Watch all changes in the external plugin folder\n\ncd \"./.vscode/external-plugins\"\n\nfor plugin in */; do\n    # Step into plugin folder\n    cd $plugin;\n\n    # Keep a record of the latest update\n    # prior to the last build\n    mkdir -p bin/\n    memoryFile=\"./bin/.latestchange\"\n    [ -f $memoryFile ] || touch $memoryFile\n    lts1=`cat $memoryFile`\n    if uname | grep -q \"Darwin\"; then\n        lts2=`find $watch -type f -print0 | xargs -0 stat -f \"%m %N\" | sort -rn | head -1 | cut -f 1 -d \" \"`\n    else\n        lts2=`find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1`\n    fi\n    if [[ $lts1 != $lts2 ]] ; then\n        # Rebuild\n        make\n        # Make could modify files, so save a fresh timestamp\n        if uname | grep -q \"Darwin\"; then\n            echo `find $watch -type f -print0 | xargs -0 stat -f \"%m %N\" | sort -rn | head -1 | cut -f 1 -d \" \"` > $memoryFile\n        else\n            echo `find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1 | cut -f 1 -d \" \"` > $memoryFile\n        fi\n    fi\n    \n    # Step out of plugin folder\n    cd ..\ndone\n\ncd \"../../\"\n", "num_lines": 43}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Rebuild (on Change)\n# For VSCode Fluent-Bit\n# The following detects changes to the following\n# watched directories and files, and will initiate a\n# rebuild on modification.\nwatch='src/ plugins/'\n\n# Kill old fluent-bit processes (might not be the best place for this)\nkill -9 $(pgrep fluent-bit)\n\n# OpenSSL Key Export\n# export SSLKEYLOGFILE=/Users/falamatt/fluentbit-premaster\n# export LD_PRELOAD=.vscode/Scripts/libsslkeylog.so\nLD_PRELOAD=\"\"\n\n# Keep a record of the latest update\n# prior to the last build\nmemoryFile=\"./.vscode/Scripts/.latestchange\"\n[ -f $memoryFile ] || touch $memoryFile\nlts1=`cat $memoryFile`\nif uname | grep -q \"Darwin\"; then\n    lts2=`find $watch -type f -print0 | xargs -0 stat -f \"%m %N\" | sort -rn | head -1 | cut -f 1 -d \" \"`\nelse\n    lts2=`find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1`\nfi\n\nif [[ $lts1 != $lts2 ]] ; then\n    # Rebuild\n    cd build\n    cmake -DFLB_DEV=On ../\n    make\n    cd ..\n    # Make could modify files, so save a fresh timestamp\n    if uname | grep -q \"Darwin\"; then\n        echo `find $watch -type f -print0 | xargs -0 stat -f \"%m %N\" | sort -rn | head -1 | cut -f 1 -d \" \"` > $memoryFile\n    else\n        echo `find $watch -type f -print0 | xargs -0 stat -c %Y | sort -rn | head -1 | cut -f 1 -d \" \"` > $memoryFile\n    fi\nfi\n", "num_lines": 42}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Writes 500 log lines per second\n\nwhile :\ndo\n    for i in {0..${LOGGER_RATE}}\n    do\n        openssl rand -base64 ${LOG_SIZE}\n    done\n    sleep 1\ndone", "num_lines": 12}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "# Usage: Set the following env vars:\n#\n# STDOUT_LOGGER_RATE => logs per second to send to stdout\n# FILE1_LOGGER_RATE => logs per second to send to /tail/file1.log$(date \"+%Y-%m-%d-%H-%M-%S\")\n# TCP_LOGGER_RATE => logs per second to send to TCP_LOGGER_PORT\n# TCP_LOGGER_PORT => TCP port of TCP input in Fluent Bit, if used\n#\n# If you do not need one of these loggers, simply remove its entry from the loop\n#\n# you can easily configure additional loggers as needed\n# just add another entry in the while loop\n# and import the new file in the Dockerfile\n\n\nwhile true\ndo\n    for i in {1..$TCP_LOGGER_RATE}\n    do\n        cat /tcp.log | nc 127.0.0.1 $TCP_LOGGER_PORT\n    done\n    for i in {1..$STDOUT_LOGGER_RATE}\n    do\n        cat /stdout.log\n    done\n    for i in {1..$FILE1_LOGGER_RATE}\n    do\n        # this sets up automatic rotation of the active file based on the date\n        # automatic log file clean up is not currently in this image\n        cat /file1.log >>  /tail/file1.log$(date \"+%Y-%m-%d-%H\")\n    done\n    sleep 1\ndone", "num_lines": 32}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "while true\ndo\n   cat example.log >> app.log\n   sleep 1\ndone\n", "num_lines": 6}
{"repo_name": "aws-for-fluent-bit", "repo_creator": "aws", "programming_language": "Shell", "code": "read_line_by_line() {\n    while IFS= read -r line; do\n        echo \"$line\" | nc 127.0.0.1 $2\n        sleep 1\n    done < \"$1\"\n}\n\nwhile true\ndo\n    read_line_by_line $1 $2\n    sleep 1\ndone\n", "num_lines": 13}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\ndebug=0\n\n\nfunction usage {\n  echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]\"\n}\n\nfunction help {\n  info_msg \"$script_name\"\n  info_msg \" \"\n  info_msg \"Sets up the environment for AWS FPGA HDK tools.\"\n  info_msg \" \"\n  info_msg \"hdk_setup.sh script will:\"\n  info_msg \"  (1) Check if Xilinx Vivado is installed,\"\n  info_msg \"  (2) Set up key environment variables HDK_*, and\"\n  info_msg \"  (3) Download/update the HDK shell's checkpoint\"\n  info_msg \"  (4) Prepare DRAM controller and PCIe IP modules if they are not already available in your directory.\"\n  echo \" \"\n  usage\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n  arg=${args[$i]}\n  case $arg in\n    -d|-debug)\n      debug=1\n    ;;\n    -h|-help)\n      help\n      return 0\n    ;;\n    *)\n      err_msg \"Invalid option: $arg\\n\"\n      usage\n      return 1\n  esac\ndone\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\n\nhdk_shell_version=$(readlink $HDK_COMMON_DIR/shell_stable)\n\ndebug_msg \"Checking for Vivado install:\"\n\n# before going too far make sure Vivado is available\nif ! exists vivado; then\n    err_msg \"Please install/enable Vivado.\"\n    err_msg \"  If you are using the FPGA Developer AMI then please request support.\"\n    return 1\nfi\n\n# Install any patches as required\ninfo_msg \"Setting up Vivado patches if required.\"\nsetup_patches\n\n#Searching for Vivado version and comparing it with the list of supported versions\n\nexport VIVADO_VER=`vivado -version | grep Vivado | head -1`\n\ninfo_msg \"Using $VIVADO_VER\"\n\nif grep -Fxq \"$VIVADO_VER\" $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt\nthen\n    debug_msg \"$VIVADO_VER is supported by this HDK release.\"\nelse\n    err_msg \"$VIVADO_VER is not supported by this HDK release.\"\n    err_msg \"Supported versions are:\"\n    cat $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt\n    return 1\nfi\n\nVIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::'`\nexport VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:7}\necho \"VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION\"\n\ndebug_msg \"Vivado check succeeded\"\n\n# The CL_DIR is where the actual Custom Logic design resides. The developer is expected to override this.\n# export CL_DIR=$HDK_DIR/cl/developer_designs\n\ndebug_msg \"Done setting environment variables.\";\n\n# Download correct shell DCP\ninfo_msg \"Using HDK shell version $hdk_shell_version\"\ndebug_msg \"Checking HDK shell's checkpoint version\"\nhdk_resources_s3_bucket=aws-fpga-hdk-resources\n\n# Shell files to be downloaded\ndeclare -a s3_hdk_files=(\"SH_CL_BB_routed.dcp\"\n                         \"cl_hello_world.debug_probes.ltx\"\n                         \"cl_dram_dma.debug_probes.ltx\"\n                        )\n# Downloading the shell files\nfor shell_file in \"${s3_hdk_files[@]}\"\ndo\n  # Determine if shell or debug probe\n  if [ $shell_file == \"SH_CL_BB_routed.dcp\" ]; then\n    sub_dir=\"checkpoints\"\n  else\n    sub_dir=\"debug_probes\"\n  fi\n  hdk_shell_dir=$HDK_SHELL_DIR/build/$sub_dir/from_aws\n  hdk_file=$hdk_shell_dir/$shell_file\n  s3_shell_dir=hdk/$hdk_shell_version/build/$sub_dir/from_aws\n  # Download the sha256\n  if [ ! -e $hdk_shell_dir ]; then\n      mkdir -p $hdk_shell_dir || { err_msg \"Failed to create $hdk_shell_dir\"; return 2; }\n  fi\n  # Use curl instead of AWS CLI so that credentials aren't required.\n  debug_msg \"curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256\"\n  curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256 || { err_msg \"Failed to download HDK shell's $shell_file version from $s3_shell_dir/$shell_file.sha256 -o $hdk_file.sha256\"; return 2; }\n  if grep -q '<?xml version' $hdk_file.sha256; then\n    err_msg \"Failed to download HDK shell's $shell_file version from $s3_shell_dir/$shell_file.sha256\"\n    cat $hdk_file.sha256\n    return 2\n  fi\n  exp_sha256=$(cat $hdk_file.sha256)\n  debug_msg \"  $shell_file latest   version=$exp_sha256\"\n  # If shell file already downloaded check its sha256\n  if [ -e $hdk_file ]; then\n    act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )\n    debug_msg \"  $shell_file existing version=$act_sha256\"\n    if [[ $act_sha256 != $exp_sha256 ]]; then\n      info_msg \"HDK shell's $shell_file version is incorrect\"\n      info_msg \"  Saving old file to $hdk_file.back\"\n      mv $hdk_file $hdk_file.back\n    fi\n  else\n    info_msg \"HDK shell's $shell_file hasn't been downloaded yet.\"\n  fi\n  if [ ! -e $hdk_file ]; then\n    info_msg \"Downloading latest HDK shell $shell_file from $s3_shell_dir/$shell_file\"\n    # Use curl instead of AWS CLI so that credentials aren't required.\n    curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$s3_shell_dir/$shell_file -o $hdk_file || { err_msg \"HDK shell checkpoint download failed\"; return 2; }\n  fi\n\n  # Check sha256\n  act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )\n  if [[ $act_sha256 != $exp_sha256 ]]; then\n    err_msg \"Incorrect HDK shell checkpoint version:\"\n    err_msg \"  expected version=$exp_sha256\"\n    err_msg \"  actual   version=$act_sha256\"\n    err_msg \"  There may be an issue with the uploaded checkpoint or the download failed.\"\n    return 2\n  fi\n  info_msg \"HDK shell is up-to-date\"\ndone\n\n# Create DDR and PCIe IP models and patch PCIe\nmodels_dir=$HDK_COMMON_DIR/verif/models\nddr4_model_dir=$models_dir/ddr4_model\nif [ -f $ddr4_model_dir/arch_defines.v ]; then\n  # Models already built\n  # Check to make sure they were built with this version of vivado\n  if [[ -f $models_dir/.vivado_version ]]; then\n    models_vivado_version=$(cat $models_dir/.vivado_version)\n    info_msg \"DDR4 model files in $ddr4_model_dir/ were built with $models_vivado_version\"\n    if [[ $models_vivado_version != $VIVADO_VER ]]; then\n      info_msg \"  Wrong vivado version so rebuilding with $VIVADO_VER\"\n    fi\n  else\n    models_vivado_version=UNKNOWN\n    info_msg \"DDR4 model files in $ddr4_model_dir/ were built with UNKNOWN Vivado version so rebuilding.\"\n  fi\nelse\n  # Models haven't been built\n  models_vivado_version=NOT_BUILT\n  info_msg \"DDR4 model files in \"$ddr4_model_dir/\" do NOT exist. Running model creation step.\";\nfi\nif [[ $models_vivado_version != $VIVADO_VER ]] && [ ! -e $models_dir/build.lock ]; then\n  rm -rf $HDK_COMMON_DIR/verif/scripts/.done 2>&1 >/dev/null\nfi\nddr4_build_dir=$HDK_COMMON_DIR/verif/scripts/tmp\nif [ -d $ddr4_build_dir ] && [ ! -e $models_dir/build.lock ]; then rm -rf $ddr4_build_dir; fi\nif ! make -s -C $HDK_DIR/common/verif/scripts MODEL_DIR=$models_dir; then\n  err_msg \"  build dir=$ddr4_build_dir\"\n  return 2\nfi\n\nif [[ \":$CL_DIR\" == ':' ]]; then\n  info_msg \"attention: don't forget to set the CL_DIR variable for the directory of your custom logic.\";\nelse\n  info_msg \"CL_DIR is $CL_DIR\"\n  if [ ! -d $CL_DIR ]; then\n    err_msg \"CL_DIR doesn't exist. set CL_DIR to a valid directory.\"\n    unset CL_DIR\n  fi\nfi\n\ncd $current_dir\n\ninfo_msg \"AWS HDK setup PASSED.\";\n", "num_lines": 226}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n", "num_lines": 16}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n    echo \"ERROR: You must source this script\"\n    exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\n\n# Source sdk_setup.sh\ninfo_msg \"Sourcing sdk_setup.sh\"\nif ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then\n    return 1\nfi\n\nif [ -z \"$SDK_DIR\" ]; then\n    err_msg \"SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    return 1\nfi\n\ndebug=0\noverride=0\nfunction usage {\n    echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help] [-o|-override]\"\n}\n\nfunction help {\n    info_msg \"$script_name\"\n    info_msg \" \"\n    info_msg \"Checks & Sets up the runtime environment for AWS FPGA SDAccel Application usage.\"\n    info_msg \" \"\n    info_msg \"sdaccel_runtime_check.sh script will:\"\n    info_msg \"  (1) install FPGA Management Tools,\"\n    info_msg \"  (2) check if Xilinx Runtime (XRT) is installed\"\n    info_msg \"  (3) check if correct version of Xilinx Runtime (XRT) is installed,\"\n    info_msg \"  (4) check if the required XOCL driver is running \"\n    info_msg \"  (5) source runtime setup script \"\n    echo \" \"\n    usage\n}\n\nfunction xrt_install_instructions_2018_2 {\n    err_msg \"AWS recommended XRT version release: https://github.com/Xilinx/XRT/releases/tag/2018.2_XDF.RC5\"\n    err_msg \"refer to following link for instructions to install XRT\"\n    err_msg \"https://www.xilinx.com/html_docs/xilinx2018_2_xdf/sdaccel_doc/ejy1538090924727.html\"\n    err_msg \"use following command to download and install latest validated XRT rpms for centos distributions\"\n    err_msg \"curl -s https://s3.amazonaws.com/aws-fpga-developer-ami/1.5.0/Patches/XRT_2018_2_XDF_RC5/xrt_201802.2.1.0_7.5.1804-xrt.rpm -o xrt_201802.2.1.0_7.5.1804-xrt.rpm\"\n    err_msg \"curl -s https://s3.amazonaws.com/aws-fpga-developer-ami/1.5.0/Patches/XRT_2018_2_XDF_RC5/xrt_201802.2.1.0_7.5.1804-aws.rpm -o xrt_201802.2.1.0_7.5.1804-aws.rpm\"\n    err_msg \"sudo yum remove -y xrt-aws\"\n    err_msg \"sudo yum remove -y xrt\"\n    err_msg \"sudo yum install -y xrt_201802.2.1.0_7.5.1804-xrt.rpm\"\n    err_msg \"sudo yum install -y xrt_201802.2.1.0_7.5.1804-aws.rpm\"\n}\n\nfunction check_xdma_driver {\n       \n    if lsmod | grep -q 'xdma' ; then\n        err_msg \"Found XDMA Driver running. Please remove xdma driver using below command\"\n        err_msg \" rmmod xdma\"\n        return 1\n    fi\n}\n\nfunction check_edma_driver {\n       \n    if lsmod | grep -q 'edma' ; then\n        err_msg \"Found EDMA Driver running. Please remove edma driver using below command\"\n        err_msg \" rmmod edma\"\n        return 1\n    fi\n}\n\nfunction check_xocl_driver {\n    if lsmod | grep -q 'xocl' ; then\n        info_msg \"Found 'xocl Driver is installed and running. ' \"\n    else\n        err_msg \" XOCL Driver not installed. Please install xocl driver using below instructions\"\n        err_msg \" If using 2017.4 Vivado toolset please source $AWS_FPGA_REPO_DIR/sdaccel_setup.sh \"\n        err_msg \" if using 2018.2 Vivado toolset please reinstall rpm using instructions below \"\n        err_msg \"Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions\"\n        return 1\n    fi\n}\n\nfunction check_kernel_ver {\n\n      ins_ker_ver=$(uname -r)\n      info_msg \"Installed kernel version : $ins_ker_ver\"\n      if grep -Fxq \"$ins_ker_ver\" $AWS_FPGA_REPO_DIR/SDAccel/kernel_version.txt\n       then\n        info_msg \"kernel version $ins_ker_ver has been validated for this devkit.\"\n      else\n          warn_msg \"$ins_ker_ver does not match one of recommended kernel versions\"\n          cat $AWS_FPGA_REPO_DIR/SDAccel/kernel_version.txt\n          warn_msg \"Xilinx Runtime not validated against your installed kernel version.\"\n       fi\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n    arg=${args[$i]}\n    case $arg in\n        -d|-debug)\n            debug=1\n        ;;\n        -h|-help)\n            help\n            return 0\n        ;;\n        -o|-override)\n            override=1\n        ;;\n        *)\n            err_msg \"Invalid option: $arg\\n\"\n            usage\n            return 1\n    esac\ndone\n\n\nif ! exists vivado; then\n   if [[ -z \"${VIVADO_TOOL_VERSION}\" ]]; then\n      err_msg \" VIVADO_TOOL_VERSION ENV variable is not set.\"\n      err_msg \" ENV Variable VIVADO_TOOL_VERSION needs to be set for runtime usage. \"\n      err_msg \" If AFI was generated using V2019.1 tools use the command : export VIVADO_TOOL_VERSION=2019.1 \"\n      err_msg \" If AFI was generated using V2018.3 tools use the command : export VIVADO_TOOL_VERSION=2018.3 \"\n      err_msg \" If AFI was generated using V2018.2 tools use the command : export VIVADO_TOOL_VERSION=2018.2 \"\n      err_msg \" If AFI was generated using V2017.4 tools use the command : export VIVADO_TOOL_VERSION=2017.4 \"\n      err_msg \" Please set VIVADO_TOOL_VERSION to the correct value and re-run script.\"\n      return 1\n   else\n      info_msg \" VIVADO tools not found. Reading VIVADO_TOOL_VERSION ENV variable to determine runtime version... \"\n      VIVADO_TOOL_VERSION=\"${VIVADO_TOOL_VERSION}\"\n      export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}\n   fi\nelse\n    info_msg \"You are using instance with installed vivado tools. determining VIVADO version for runtime setup...\"\n    VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`\n    export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}\nfi\ninfo_msg \"VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION\"\n\n\ncheck_kernel_ver\ncheck_xdma_driver\ncheck_edma_driver\n\nif [[ \"$VIVADO_TOOL_VERSION\" =~ .*2018\\.2.* || \"$VIVADO_TOOL_VERSION\" =~ .*2018\\.3.* || \"$VIVADO_TOOL_VERSION\" =~ .*2019\\.1.* ]]; then\n    info_msg \"Xilinx Vivado version is $VIVADO_TOOL_VERSION\"\n    \n    if [ $override == 1 ]; then\n      info_msg \"XRT check overide selected.\"\n      source /opt/xilinx/xrt/setup.sh\n      return 0\n    fi\n\n    if [ -f \"/opt/xilinx/xrt/include/version.h\" ]; then\n       info_msg \"XRT installed. proceeding to check version compatibility\"\n       xrt_build_ver=$VIVADO_TOOL_VERSION\n       xrt_build_ver+=:\n       xrt_build_ver+=$(grep  'xrt_build_version_hash\\[\\]' /opt/xilinx/xrt/include/version.h | sed 's/\";//' | sed 's/^.*\"//')\n       info_msg \"Installed XRT version : $xrt_build_ver\"\n       if grep -Fxq \"$xrt_build_ver\" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n       then\n          info_msg \"XRT version $xrt_build_ver is supported.\"\n          info_msg \" Now checking XOCL driver...\"\n          check_xocl_driver\n          if [ -f \"/opt/xilinx/xrt/setup.sh\" ]; then \n             source /opt/xilinx/xrt/setup.sh\n          else\n             err_msg \" Cannot find /opt/xilinx/xrt/setup.sh\"\n             err_msg \" Please check XRT is installed correctly\"\n             err_msg \" Please Refer to $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions\"\n             return 1\n          fi\n          info_msg \" XRT Runtime setup Done\"\n       else\n          err_msg \"$xrt_build_ver does not match recommended versions\"\n          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n          err_msg \"Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions\"\n          return 1\n       fi\n    else\n       err_msg \"XRT not installed. Please install XRT\"\n       err_msg \"Please Refer $AWS_FPGA_REPO/SDAccel/doc/XRT_installation_instructions.md for XRT installation instructions\"\n       return 1\n    fi\nelse\n   info_msg \"Xilinx Vivado version is $VIVADO_TOOL_VERSION \"\n   info_msg \" Now checking XOCL driver...\"\n   check_xocl_driver\n   if [ -f \"/opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh\" ]; then\n      info_msg \" Sourcing /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh\"\n      source /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh\n      info_msg \"$VIVADO_TOOL_VERSION Runtime setup Done\"\n   else\n      err_msg \" /opt/Xilinx/SDx/${VIVADO_TOOL_VERSION}.rte.dyn/setup.sh  Not found. \"\n      err_msg \"$VIVADO_TOOL_VERSION runtime environment not installed. Please source $AWS_FPGA_REPO_DIR/sdaccel_setup.sh\"\n      return 1\n   fi\nfi\n\ninfo_msg \"SDAccel runtime check PASSED\"\n", "num_lines": 228}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n    echo \"ERROR: You must source this script\"\n    exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\nsource $SDACCEL_DIR/Runtime/xrt_common_functions.sh\n\n# Source sdk_setup.sh\ninfo_msg \"Sourcing sdk_setup.sh\"\nif ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then\n    return 1\nfi\n\nif [ -z \"$SDK_DIR\" ]; then\n    err_msg \"SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    return 1\nfi\n\ndebug=0\n\nfunction usage {\n    echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]\"\n}\n\nfunction help {\n    info_msg \"$script_name\"\n    info_msg \" \"\n    info_msg \"Sets up the environment for AWS FPGA SDAccel tools.\"\n    info_msg \" \"\n    info_msg \"sdaccel_setup.sh script will:\"\n    info_msg \"  (1) install FPGA Management Tools,\"\n    info_msg \"  (2) check if Xilinx tools are available,\"\n    info_msg \"  (3) check if required packages are installed,\"\n    info_msg \"  (4) Download lastest AWS Platform,\"\n    info_msg \"  (5) Install Runtime drivers \"\n    echo \" \"\n    usage\n}\n\nfunction check_set_xilinx_sdx {\n    if [[ \":$XILINX_SDX\" == ':' ]]; then\n        debug_msg \"XILINX_SDX is not set\"\n        which sdx\n        RET=$?\n        if [ $RET != 0 ]; then\n            debug_msg \"sdx not found in path.\"\n            err_msg \"XILINX_SDX variable not set and sdx not in the path\"\n            err_msg \"Please set XILINX_SDX variable to point to your location of your Xilinx installation or add location of sdx exectuable to your PATH variable\"\n            return $RET\n        else\n            export XILINX_SDX=`which sdx | sed 's:/bin/sdx::'`\n            info_msg \"Setting XILINX_SDX to $XILINX_SDX\"\n        fi\n    else\n        info_msg \"XILINX_SDX is already set to $XILINX_SDX\"\n    fi\n    # get sdaccel release version, i.e. \"2017.1\"\n    RELEASE_VER=$(basename $XILINX_SDX)\n    RELEASE_VER=${RELEASE_VER:0:6}\n    export RELEASE_VER=$RELEASE_VER\n    echo \"RELEASE_VER equals $RELEASE_VER\"\n}\n\nfunction check_install_packages_centos {\n#TODO: Check required packages are installed or install them\n#TODO: Check version of gcc is above 4.8.5 (4.6.3 does not work)\n  for pkg in `cat $SDACCEL_DIR/packages.txt`; do\n    if yum list installed \"$pkg\" >/dev/null 2>&1; then\n      true\n    else\n      warn_msg \" $pkg not installed - please run: sudo yum install $pkg \"\n    fi\n  done\n}\n\nfunction check_install_packages_ubuntu {\n  for pkg in `cat $SDACCEL_DIR/packages.txt`; do\n    if apt -qq list \"$pkg\" >/dev/null 2>&1; then\n      true\n    else\n      warn_msg \" $pkg not installed - please run: sudo apt-get install $pkg \"\n    fi\n  done\n}\n\nfunction check_internet {\n    curl --silent --head -m 30 http://www.amazon.com\n    RET=$?\n    if [ $RET != 0 ]; then\n        err_msg \"curl cannot connect to the internet using please check your internet connection or proxy settings\"\n        err_msg \"To check your connection run:   curl --silent --head -m 30 http://www.amazon.com \"\n        return $RET\n    else\n        info_msg \"Internet Access OK\"\n    fi\n}\n\nfunction check_icd {\n    info_msg \"Checking ICD is installed\"\n    if grep -q 'libxilinxopencl.so' /etc/OpenCL/vendors/xilinx.icd; then\n        info_msg \"Found 'libxilinxopencl.so\"\n    else\n        info_msg \"/etc/OpenCL/vendors/xilinx.icd does not exist or does not contain lbixilinxopencl.so creating and adding libxilinxopencl.so to it\"\n        sudo sh -c \"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\"\n        RET=$?\n    if [ $RET != 0 ]; then\n        err_msg \"/etc/OpenCL/vendors/xilinx.icd does not exist and cannot be created, sudo permissions needed to update it.\"\n        err_msg \"Run the following with sudo permissions: sudo sh -c \\\"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\\\" \"\n        return $RET\n    else\n        echo \"Done with ICD installation\"\n    fi\n    fi\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n    arg=${args[$i]}\n    case $arg in\n        -d|-debug)\n            debug=1\n        ;;\n        -h|-help)\n            help\n            return 0\n        ;;\n        *)\n            err_msg \"Invalid option: $arg\\n\"\n            usage\n            return 1\n    esac\ndone\n\n\nif [[ ! -z \"$XILINX_VITIS\" ]]; then\n    debug_msg \"XILINX_VITIS is set\"\n    err_msg \"XILINX_VITIS variable is set, but you are calling sdaccel_setup.sh. This likely means that you are calling source sdaccel_setup.sh with Xilinx Vitis installed. Xilinx has replaced SDAccel with Vitis from 2019.2 release onwards. Please checkout the Vitis README and flow instead.\"\n    return 1\nfi\n\n# Check XILINX_SDX is set\nif ! check_set_xilinx_sdx; then\n    return 1\nfi\n\n\ninfo_msg \" XILINX_SDX is set to $XILINX_SDX\"\n# Install patches as required.\ninfo_msg \" Checking & installing required patches\"\nsetup_patches\n\n\n# Update Xilinx SDAccel Examples from GitHub\ninfo_msg \"Using SDx $RELEASE_VER\"\nif [[ $RELEASE_VER =~ .*2017\\.4.* || $RELEASE_VER =~ .*2018\\.2.* || $RELEASE_VER =~ .*2018\\.3.* || $RELEASE_VER =~ .*2019\\.1.* ]]; then\n    info_msg \"Updating Xilinx SDAccel Examples $RELEASE_VER\"\n    git submodule update --init -- SDAccel/examples/xilinx_$RELEASE_VER\n    export VIVADO_TOOL_VER=$RELEASE_VER\n    if [ -e $SDACCEL_DIR/examples/xilinx ]; then\n        if [ ! -L $SDACCEL_DIR/examples/xilinx ]; then\n          err_msg \"ERROR:  SDAccel/examples/xilinx is not a symbolic link.  Backup any data and remove SDAccel/examples/xilinx directory.  The setup needs to create a symbolic link from SDAccel/examples/xilinx to SDAccel/examples/xilinx_$RELEASE_VER\"\n          return 1\n        fi\n    fi\n    ln -sf $SDACCEL_DIR/examples/xilinx_$RELEASE_VER $SDACCEL_DIR/examples/xilinx\nelse\n   echo \" $RELEASE_VER is not supported (2017.4, 2018.2, 2018.3 and 2019.1 are supported).\\n\"\n   return 2\nfi\n\n# settings64 removal - once we put this in the AMI, we will add a check\n#export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$XILINX_SDX/lib/lnx64.o\n\nexport LD_LIBRARY_PATH=`$XILINX_SDX/bin/ldlibpath.sh $XILINX_SDX/lib/lnx64.o`:$XILINX_SDX/runtime/lib/x86_64\nexport LD_LIBRARY_PATH=$XILINX_SDX/lnx64/tools/opencv/:$LD_LIBRARY_PATH\n\n# add variable to allow compilation using 2017.4 and 2018.2 on newer OSes\nexport XOCC_ADD_OPTIONS=\"--xp param:compiler.useHlsGpp=1 --xp param:compiler.minFrequencyLimit=80\"\n\n# Check if internet connection is available\nif ! check_internet; then\n    return 1\nfi\n\n# Check ICD is installed\nif ! check_icd; then\n    return 1\nfi\n\n# Check correct packages are installed\nif [ -f \"/etc/redhat-release\" ]; then\n    if ! check_install_packages_centos; then\n        return 1\n    fi\nelse\n    if ! check_install_packages_ubuntu; then\n        return 1\n    fi\nfi\n\nfunction setup_dsa {\n\n    if [ \"$#\" -ne 3 ]; then\n        err_msg \"Illegal number of parameters sent to the setup_dsa function!\"\n        return 1\n    fi\n\n    DSA=$1\n    DSA_S3_BASE_DIR=$2\n    PLATFORM_ENV_VAR_NAME=$3\n\n    dsa_dir=$SDACCEL_DIR/aws_platform/$DSA/hw/\n    sdk_dsa=$dsa_dir/$DSA.dsa\n    sdk_dsa_s3_bucket=aws-fpga-hdk-resources\n    s3_sdk_dsa=$sdk_dsa_s3_bucket/SDAccel/$DSA_S3_BASE_DIR/$DSA/$DSA.dsa\n\n    # set a variable to point to the platform for build and emulation runs\n    export \"$PLATFORM_ENV_VAR_NAME\"=$SDACCEL_DIR/aws_platform/$DSA/$DSA.xpfm\n\n    # Download the sha256\n    if [ ! -e $dsa_dir ]; then\n        mkdir -p $dsa_dir || { err_msg \"Failed to create $dsa_dir\"; return 2; }\n    fi\n\n    # Use curl instead of AWS CLI so that credentials aren't required.\n    curl -s https://s3.amazonaws.com/$s3_sdk_dsa.sha256 -o $sdk_dsa.sha256 || { err_msg \"Failed to download DSA checkpoint version from $s3_sdk_dsa.sha256 -o $sdk_dsa.sha256\"; return 2; }\n    if grep -q '<?xml version' $sdk_dsa.sha256; then\n        err_msg \"Failed to download SDK DSA checkpoint version from $s3_sdk_dsa.sha256\"\n        cat sdk_dsa.sha256\n        return 2\n    fi\n    exp_sha256=$(cat $sdk_dsa.sha256)\n    debug_msg \"  latest   version=$exp_sha256\"\n    # If DSA already downloaded check its sha256\n    if [ -e $sdk_dsa ]; then\n        act_sha256=$( sha256sum $sdk_dsa | awk '{ print $1 }' )\n        debug_msg \"  existing version=$act_sha256\"\n        if [[ $act_sha256 != $exp_sha256 ]]; then\n            info_msg \"SDK DSA checkpoint version is incorrect\"\n            info_msg \"  Saving old checkpoint to $sdk_dsa.back\"\n            mv $sdk_dsa $sdk_dsa.back\n        fi\n    else\n        info_msg \"SDK DSA hasn't been downloaded yet.\"\n    fi\n\n    if [ ! -e $sdk_dsa ]; then\n        info_msg \"Downloading latest SDK DSA checkpoint from $s3_sdk_dsa\"\n        # Use curl instead of AWS CLI so that credentials aren't required.\n        curl -s https://s3.amazonaws.com/$s3_sdk_dsa -o $sdk_dsa || { err_msg \"SDK dsa checkpoint download failed\"; return 2; }\n    fi\n    # Check sha256\n    act_sha256=$( sha256sum $sdk_dsa | awk '{ print $1 }' )\n    if [[ $act_sha256 != $exp_sha256 ]]; then\n        err_msg \"Incorrect SDK dsa checkpoint version:\"\n        err_msg \"  expected version=$exp_sha256\"\n        err_msg \"  actual   version=$act_sha256\"\n        err_msg \"  There may be an issue with the uploaded checkpoint or the download failed.\"\n        return 2\n    fi\n}\n\n    #-------------------Dynamic 5.0 Platform----------------------\n    setup_dsa xilinx_aws-vu9p-f1-04261818_dynamic_5_0 dsa_v062918_shell_v04261818 AWS_PLATFORM_DYNAMIC_5_0\n    info_msg \"AWS Platform: Dynamic 5.0 Platform is up-to-date\"\n    #-------------------Dynamic 5.0 Platform----------------------\n\n\n\n# Start of runtime xdma driver install\nsetup_runtime\n\nexport AWS_PLATFORM=$AWS_PLATFORM_DYNAMIC_5_0\ninfo_msg \"The default AWS Platform has been set to: \\\"AWS_PLATFORM=\\$AWS_PLATFORM_DYNAMIC_5_0\\\" \"\n\ninfo_msg \"SDAccel Setup PASSED\"\n", "num_lines": 304}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\n\nsudo rm -f /tmp/sdk_root_env.exp\ntypeset -f allow_non_root > /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP}\" >> /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_OTHERS=${AWS_FPGA_SDK_OTHERS}\" >> /tmp/sdk_root_env.exp\necho \"export SDK_NON_ROOT_USER=${SDK_NON_ROOT_USER}\" >> /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_OVERRIDE_GROUP=${AWS_FPGA_SDK_OVERRIDE_GROUP}\" >> /tmp/sdk_root_env.exp\nsudo chown root:root /tmp/sdk_root_env.exp\nsudo chmod 700 /tmp/sdk_root_env.exp\n\n#\n# Execute sdk_install.sh inside a subshell so the user's current\n# shell does not exit on errors from the install.\n#\ncd $script_dir\nif ! bash $SDK_DIR/sdk_install.sh; then\n    echo \"Error: AWS SDK install was unsuccessful, sdk_install.sh returned $?\"\n    return 1\nfi\n\ncd $current_dir\ninfo_msg \"$script_name PASSED\"\n", "num_lines": 54}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n    echo \"ERROR: You must source this script\"\n    exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\nsource $VITIS_DIR/Runtime/xrt_common_functions.sh\n\n# Source sdk_setup.sh\ninfo_msg \"Sourcing sdk_setup.sh\"\nif ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then\n    return 1\nfi\n\nif [ -z \"$SDK_DIR\" ]; then\n    err_msg \"SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    return 1\nfi\n\ndebug=0\noverride=0\nfunction usage {\n    echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help] [-o|-override]\"\n}\n\nfunction help {\n    info_msg \"$script_name\"\n    info_msg \" \"\n    info_msg \"Checks & Sets up the runtime environment for AWS FPGA Vitis Application usage.\"\n    info_msg \" \"\n    info_msg \"vitis_runtime_check.sh script will:\"\n    info_msg \"  (1) install FPGA Management Tools,\"\n    info_msg \"  (2) check if Xilinx Runtime (XRT) is installed\"\n    info_msg \"  (3) check if correct version of Xilinx Runtime (XRT) is installed,\"\n    info_msg \"  (4) check if the required XOCL driver is running \"\n    info_msg \"  (5) source runtime setup script \"\n    echo \" \"\n    usage\n}\n\nfunction check_xdma_driver {\n\n    if lsmod | grep -q 'xdma' ; then\n        err_msg \"Found XDMA Driver running. Please remove xdma driver using below command\"\n        err_msg \" rmmod xdma\"\n        return 1\n    fi\n}\n\nfunction check_xocl_driver {\n    if lsmod | grep -q 'xocl' ; then\n        info_msg \"Found 'xocl Driver is installed and running. ' \"\n    else\n        err_msg \"XOCL Driver not installed. Please install xocl driver using below instructions\"\n        err_msg \"If using Vitis, please source $AWS_FPGA_REPO_DIR/vitis_setup.sh \"\n        return 1\n    fi\n}\n\nfunction check_kernel_ver {\n\n      ins_ker_ver=$(uname -r)\n      info_msg \"Installed kernel version : $ins_ker_ver\"\n      if grep -Fxq \"$ins_ker_ver\" $AWS_FPGA_REPO_DIR/Vitis/kernel_version.txt\n       then\n        info_msg \"kernel version $ins_ker_ver has been validated for this devkit.\"\n      else\n          warn_msg \"$ins_ker_ver does not match one of recommended kernel versions\"\n          cat $AWS_FPGA_REPO_DIR/Vitis/kernel_version.txt\n          warn_msg \"Xilinx Runtime not validated against your installed kernel version.\"\n       fi\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n    arg=${args[$i]}\n    case $arg in\n        -d|-debug)\n            debug=1\n        ;;\n        -h|-help)\n            help\n            return 0\n        ;;\n        -o|-override)\n            override=1\n        ;;\n        *)\n            err_msg \"Invalid option: $arg\\n\"\n            usage\n            return 1\n    esac\ndone\n\n\nif ! exists vivado; then\n   if [[ -z \"${VIVADO_TOOL_VERSION}\" ]]; then\n      err_msg \" VIVADO_TOOL_VERSION ENV variable is not set.\"\n      err_msg \" ENV Variable VIVADO_TOOL_VERSION needs to be set for runtime usage. \"\n      err_msg \" If AFI was generated using V2019.2 tools use the command : export VIVADO_TOOL_VERSION=2019.2 \"\n      err_msg \" Please set VIVADO_TOOL_VERSION to the correct value and re-run script.\"\n      return 1\n   else\n      info_msg \" VIVADO tools not found. Reading VIVADO_TOOL_VERSION ENV variable to determine runtime version... \"\n      VIVADO_TOOL_VERSION=\"${VIVADO_TOOL_VERSION}\"\n      export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}\n   fi\nelse\n    info_msg \"You are using instance with installed vivado tools. determining VIVADO version for runtime setup...\"\n    VIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`\n    export VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}\nfi\ninfo_msg \"VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION\"\n\n\ncheck_kernel_ver\ncheck_xdma_driver\n\nif [[ \"$VIVADO_TOOL_VERSION\" =~ .*2019\\.2.*  || \"$VIVADO_TOOL_VERSION\" =~ .*2020\\.* || \"$VIVADO_TOOL_VERSION\" =~ .*2021\\.*  ]]; then\n    info_msg \"Xilinx Vivado version is $VIVADO_TOOL_VERSION\"\n\n    if [ $override == 1 ]; then\n      info_msg \"XRT check override selected.\"\n      source /opt/xilinx/xrt/setup.sh\n      return 0\n    fi\n\n    if [ -f \"/opt/xilinx/xrt/include/version.h\" ]; then\n       info_msg \"XRT installed. proceeding to check version compatibility\"\n       xrt_build_ver=$VIVADO_TOOL_VERSION\n       xrt_build_ver+=:\n       xrt_build_ver+=$(grep  'xrt_build_version_hash\\[\\]' /opt/xilinx/xrt/include/version.h | sed 's/\";//' | sed 's/^.*\"//')\n       info_msg \"Installed XRT version : $xrt_build_ver\"\n       if grep -Fxq \"$xrt_build_ver\" $AWS_FPGA_REPO_DIR/Vitis/vitis_xrt_version.txt\n       then\n          info_msg \"XRT version $xrt_build_ver is supported.\"\n          info_msg \" Now checking XOCL driver...\"\n          check_xocl_driver\n          if [ -f \"/opt/xilinx/xrt/setup.sh\" ]; then\n             source /opt/xilinx/xrt/setup.sh\n          else\n             err_msg \" Cannot find /opt/xilinx/xrt/setup.sh\"\n             err_msg \" Please check XRT is installed correctly\"\n             err_msg \" Please Refer to $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions\"\n             return 1\n          fi\n          info_msg \" XRT Runtime setup Done\"\n       else\n          err_msg \"$xrt_build_ver does not match recommended versions\"\n          cat $AWS_FPGA_REPO_DIR/Vitis/vitis_xrt_version.txt\n          err_msg \"Please Refer $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions\"\n          return 1\n       fi\n    else\n       err_msg \"XRT not installed. Please install XRT\"\n       err_msg \"Please Refer $AWS_FPGA_REPO/Vitis/doc/XRT_installation_instructions.md for XRT installation instructions\"\n       return 1\n    fi\nelse\n   err_msg \"Xilinx Vivado version is $VIVADO_TOOL_VERSION , only 2019.2, 2020.1, 2020.2, 2021.1 or 2021.2 are supported for Vitis \"\n   return 1\nfi\n\nsetup_runtime\n\ninfo_msg \"Starting MPD\"\nsystemctl is-active --quiet mpd || sudo systemctl start mpd\n\ninfo_msg \"Vitis runtime check PASSED\"\n", "num_lines": 196}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n    echo \"ERROR: You must source this script\"\n    exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\nsource $VITIS_DIR/Runtime/xrt_common_functions.sh\n\n# Source sdk_setup.sh\ninfo_msg \"Sourcing sdk_setup.sh\"\nif ! source $AWS_FPGA_REPO_DIR/sdk_setup.sh; then\n    return 1\nfi\n\nif [ -z \"$SDK_DIR\" ]; then\n    err_msg \"SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    return 1\nfi\n\ndebug=0\n\nfunction usage {\n    echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]\"\n}\n\nfunction help {\n    info_msg \"$script_name\"\n    info_msg \" \"\n    info_msg \"Sets up the environment for AWS FPGA Vitis tools.\"\n    info_msg \" \"\n    info_msg \"vitis_setup.sh script will:\"\n    info_msg \"  (1) install FPGA Management Tools,\"\n    info_msg \"  (2) check if Xilinx tools are available,\"\n    info_msg \"  (3) check if required packages are installed,\"\n    info_msg \"  (4) Download lastest AWS Platform,\"\n    info_msg \"  (5) Install Runtime drivers \"\n    echo \" \"\n    usage\n}\n\nfunction check_set_xilinx_vitis {\n    if [[ \":$XILINX_VITIS\" == ':' ]]; then\n        debug_msg \"XILINX_VITIS is not set\"\n        which vitis\n        RET=$?\n        if [ $RET != 0 ]; then\n            debug_msg \"vitis not found in path.\"\n            err_msg \"XILINX_VITIS variable not set and vitis not in the path\"\n            err_msg \"Please set XILINX_VITIS variable to point to your location of your Xilinx installation or add location of vitis exectuable to your PATH variable\"\n            return $RET\n        else\n            export XILINX_VITIS=`which vitis | sed 's:/bin/vitis::'`\n            info_msg \"Setting XILINX_VITIS to $XILINX_VITIS\"\n        fi\n    else\n        info_msg \"XILINX_VITIS is already set to $XILINX_VITIS\"\n    fi\n    # get Vitis release version, i.e. \"2019.2\"\n    RELEASE_VER=$(basename $XILINX_VITIS)\n    RELEASE_VER=${RELEASE_VER:0:6}\n    export RELEASE_VER=$RELEASE_VER\n    echo \"RELEASE_VER equals $RELEASE_VER\"\n}\n\nfunction check_install_packages_centos {\n#TODO: Check required packages are installed or install them\n#TODO: Check version of gcc is above 4.8.5 (4.6.3 does not work)\n  for pkg in `cat $VITIS_DIR/packages.txt`; do\n    if yum list installed \"$pkg\" >/dev/null 2>&1; then\n      true\n    else\n      warn_msg \" $pkg not installed - please run: sudo yum install $pkg \"\n    fi\n  done\n}\n\nfunction check_install_packages_ubuntu {\n  for pkg in `cat $VITIS_DIR/packages.txt`; do\n    if apt -qq list \"$pkg\" >/dev/null 2>&1; then\n      true\n    else\n      warn_msg \" $pkg not installed - please run: sudo apt-get install $pkg \"\n    fi\n  done\n}\n\nfunction check_internet {\n    curl --silent --head -m 30 http://www.amazon.com\n    RET=$?\n    if [ $RET != 0 ]; then\n        err_msg \"curl cannot connect to the internet using please check your internet connection or proxy settings\"\n        err_msg \"To check your connection run:   curl --silent --head -m 30 http://www.amazon.com \"\n        return $RET\n    else\n        info_msg \"Internet Access OK\"\n    fi\n}\n\nfunction check_icd {\n    info_msg \"Checking ICD is installed\"\n    if grep -q 'libxilinxopencl.so' /etc/OpenCL/vendors/xilinx.icd; then\n        info_msg \"Found 'libxilinxopencl.so\"\n    else\n        info_msg \"/etc/OpenCL/vendors/xilinx.icd does not exist or does not contain lbixilinxopencl.so creating and adding libxilinxopencl.so to it\"\n        sudo sh -c \"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\"\n        RET=$?\n    if [ $RET != 0 ]; then\n        err_msg \"/etc/OpenCL/vendors/xilinx.icd does not exist and cannot be created, sudo permissions needed to update it.\"\n        err_msg \"Run the following with sudo permissions: sudo sh -c \\\"echo libxilinxopencl.so > /etc/OpenCL/vendors/xilinx.icd\\\" \"\n        return $RET\n    else\n        echo \"Done with ICD installation\"\n    fi\n    fi\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n    arg=${args[$i]}\n    case $arg in\n        -d|-debug)\n            debug=1\n        ;;\n        -h|-help)\n            help\n            return 0\n        ;;\n        *)\n            err_msg \"Invalid option: $arg\\n\"\n            usage\n            return 1\n    esac\ndone\n\n# Check XILINX_VITIS is set\nif ! check_set_xilinx_vitis; then\n    return 1\nfi\n\ninfo_msg \" XILINX_VITIS is set to $XILINX_VITIS\"\n# Install patches as required.\ninfo_msg \"Setting up Vitis patches if required.\"\nsetup_patches\n\n\n# Update Xilinx Vitis Examples from GitHub\ninfo_msg \"Using Vitis $RELEASE_VER\"\nif [[ $RELEASE_VER =~ .*2019\\.2.*  ||  $RELEASE_VER =~ .*2020\\.* ||  $RELEASE_VER =~ .*2021\\.* ]]; then\n    info_msg \"Updating Xilinx Vitis Examples $RELEASE_VER\"\n    git submodule update --init -- Vitis/examples/xilinx_$RELEASE_VER\n    export VIVADO_TOOL_VER=$RELEASE_VER\n    if [ -e $VITIS_DIR/examples/xilinx ]; then\n        if [ ! -L $VITIS_DIR/examples/xilinx ]; then\n          err_msg \"ERROR:  Vitis/examples/xilinx is not a symbolic link.  Backup any data and remove Vitis/examples/xilinx directory.  The setup needs to create a symbolic link from Vitis/examples/xilinx to Vitis/examples/xilinx_$RELEASE_VER\"\n          return 1\n        fi\n    fi\n    ln -sf $VITIS_DIR/examples/xilinx_$RELEASE_VER $VITIS_DIR/examples/xilinx\nelse\n   echo \" $RELEASE_VER is not supported (2019.2, 2020.1, 2020.2, 2021.1 or 2021.2 are supported).\\n\"\n   return 2\nfi\n\n# Check if internet connection is available\nif ! check_internet; then\n    return 1\nfi\n\n# Check ICD is installed\nif ! check_icd; then\n    return 1\nfi\n\n# Check correct packages are installed\n\nif [[ $(lsb_release -si) == \"Centos\" ]]; then\n    if ! check_install_packages_centos; then\n        return 1\n    fi\nelif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n    if ! check_install_packages_ubuntu; then\n        return 1\n    fi\n#elif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n#    if ! check_install_packages_ubuntu; then\n#        return 1\n#    fi\nfi\n\nfunction setup_xsa {\n\n    if [ \"$#\" -ne 3 ]; then\n        err_msg \"Illegal number of parameters sent to the setup_xsa function!\"\n        return 1\n    fi\n\n    XSA=$1\n    XSA_S3_BASE_DIR=$2\n    PLATFORM_ENV_VAR_NAME=$3\n\n    xsa_dir=$VITIS_DIR/aws_platform/$XSA/hw/\n    vitis_xsa=$xsa_dir/$XSA.xsa\n    vitis_xsa_s3_bucket=aws-fpga-hdk-resources\n    s3_vitis_xsa=$vitis_xsa_s3_bucket/Vitis/$XSA_S3_BASE_DIR/$XSA/$XSA.xsa\n\n    # set a variable to point to the platform for build and emulation runs\n    export \"$PLATFORM_ENV_VAR_NAME\"=$VITIS_DIR/aws_platform/$XSA/$XSA.xpfm\n\n    # Download the sha256\n    if [ ! -e $xsa_dir ]; then\n        mkdir -p $xsa_dir || { err_msg \"Failed to create $xsa_dir\"; return 2; }\n    fi\n\n    # Use curl instead of AWS CLI so that credentials aren't required.\n    curl -s https://s3.amazonaws.com/$s3_vitis_xsa.sha256 -o $vitis_xsa.sha256 || { err_msg \"Failed to download XSA version from $s3_vitis_xsa.sha256 -o $vitis_xsa.sha256\"; return 2; }\n    if grep -q '<?xml version' $vitis_xsa.sha256; then\n        err_msg \"Failed to download VITIS XSA version from $s3_vitis_xsa.sha256\"\n        cat vitis_xsa.sha256\n        return 2\n    fi\n    exp_sha256=$(cat $vitis_xsa.sha256)\n    debug_msg \"  latest   version=$exp_sha256\"\n    # If XSA already downloaded check its sha256\n    if [ -e $vitis_xsa ]; then\n        act_sha256=$( sha256sum $vitis_xsa | awk '{ print $1 }' )\n        debug_msg \"  existing version=$act_sha256\"\n        if [[ $act_sha256 != $exp_sha256 ]]; then\n            info_msg \"VITIS XSA version is incorrect\"\n            info_msg \"  Saving old XSA to $vitis_xsa.back\"\n            mv $vitis_xsa $vitis_xsa.back\n        fi\n    else\n        info_msg \"VITIS XSA hasn't been downloaded yet.\"\n    fi\n\n    if [ ! -e $vitis_xsa ]; then\n        info_msg \"Downloading latest VITIS XSA from $s3_vitis_xsa\"\n        # Use curl instead of AWS CLI so that credentials aren't required.\n        curl -s https://s3.amazonaws.com/$s3_vitis_xsa -o $vitis_xsa || { err_msg \"VITIS XSA download failed\"; return 2; }\n    fi\n    # Check sha256\n    act_sha256=$( sha256sum $vitis_xsa | awk '{ print $1 }' )\n    if [[ $act_sha256 != $exp_sha256 ]]; then\n        err_msg \"Incorrect VITIS XSA version:\"\n        err_msg \"  expected version=$exp_sha256\"\n        err_msg \"  actual   version=$act_sha256\"\n        err_msg \"  There may be an issue with the uploaded XSA or the download failed.\"\n        return 2\n    fi\n}\n\n    #-------------------201920_3 Vitis Platform----------------------\n    setup_xsa xilinx_aws-vu9p-f1_shell-v04261818_201920_3 xsa_v121319_shell_v04261818 AWS_PLATFORM_201920_3\n    info_msg \"AWS Platform: 201920_3 Vitis Platform is up-to-date\"\n    #-------------------201920_3 Vitis Platform----------------------\n\n\n# Setup XRT as we need it for building\nsetup_runtime\n\nexport AWS_PLATFORM=$AWS_PLATFORM_201920_3\ninfo_msg \"The default AWS Platform has been set to: \\\"AWS_PLATFORM=\\$AWS_PLATFORM_201920_3\\\" \"\n\ninfo_msg \"Vitis Setup PASSED\"\n\ninfo_msg \"To run a runtime example, start the MPD service by calling: \\`systemctl is-active --quiet mpd || sudo systemctl start mpd\\`\"\n", "num_lines": 293}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# TODO\n# Check if /build and /design directories exist, abort\n# Check if $HDK_COMMON_DIR exist\n\ncp -rL $HDK_SHELL_DIR/new_cl_template/build .\ncp -r  $HDK_SHELL_DIR/new_cl_template/design .\n", "num_lines": 24}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Set env\nexport CLOCK_A_RECIPE=\"$(cut -d'A' -f2 <<<\"$clock_recipe_a\")\"\nexport CLOCK_B_RECIPE=\"$(cut -d'B' -f2 <<<\"$clock_recipe_b\")\"\nexport CLOCK_C_RECIPE=\"$(cut -d'C' -f2 <<<\"$clock_recipe_c\")\"\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 208}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Set env\nexport CLOCK_A_RECIPE=\"$(cut -d'A' -f2 <<<\"$clock_recipe_a\")\"\nexport CLOCK_B_RECIPE=\"$(cut -d'B' -f2 <<<\"$clock_recipe_b\")\"\nexport CLOCK_C_RECIPE=\"$(cut -d'C' -f2 <<<\"$clock_recipe_c\")\"\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 208}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 170}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 170}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 170}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 170}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nif ! [[ $CL_DIR ]]\nthen\n\terr_msg \"Environment variable CL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [[ $HDK_SHELL_DIR ]]\nthen\n\terr_msg \"Environment variable HDK_SHELL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/constraints ]\nthen\n\terr_msg \"Constraints directory is not found in $CL_DIR/build/ directory\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/reports ]\nthen\n\tinfo_msg \"Creating the reports directory\"\n\tmkdir $CL_DIR/build/reports\n\tif ! [ -d $CL_DIR/build/reports ]\n\tthen\t\n\t\terr_msg \"Failed to create reports directory, please check directory permissions\"\n\t\texit 1\t\n\tfi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints ] \nthen\n        info_msg \"Creating the checkpoints directory\"\n        mkdir $CL_DIR/build/checkpoints\n        if ! [ -d $CL_DIR/build/checkpoints ]\n        then\n                err_msg \"Failed to create checkpoints directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints/to_aws ]\nthen\n        info_msg \"Creating the checkpoints/to_aws directory\"\n        mkdir $CL_DIR/build/checkpoints/to_aws\n        if ! [ -d $CL_DIR/build/checkpoints/to_aws ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/src_post_encryption ]\nthen\n        info_msg \"Creating the src_port_encryption directory\"\n        mkdir $CL_DIR/build/src_post_encryption\n        if ! [ -d $CL_DIR/build/src_post_encryption ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n", "num_lines": 101}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 170}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-gui] [-foreground] [-notify] [-ignore_memory_requirement] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground.\"\n    echo \"This will open Vivado GUI, create a Block Design Hello World Example\"\n    echo \"and run Synthesis and Implementation.\"\n    echo \"The terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to access the GUI.\"\n    echo \"\"\n    echo \"The tar file used to generate the AFI image will be located in:\"\n    echo \"$CL_DIR/build/scripts/example_projects/<name_of_example_design>.runs/faas_1/build/checkpoints/to_aws\"\n}\n\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\ngui=0\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -gui )                  gui=1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Set env\nexport CLOCK_A_RECIPE=\"$(cut -d'A' -f2 <<<\"$clock_recipe_a\")\"\nexport CLOCK_B_RECIPE=\"$(cut -d'B' -f2 <<<\"$clock_recipe_b\")\"\nexport CLOCK_C_RECIPE=\"$(cut -d'C' -f2 <<<\"$clock_recipe_c\")\"\n\n# Run vivado\nif [[ $gui == 0 ]]\nthen\n  cmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nelse\n  foreground=1\n  cmd=\"vivado -nojournal -log $logname -source $vivado_script -tclargs $timestamp $notify $gui\"\nfi\n\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 208}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 259}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [[ \":$HDK_COMMON_DIR\" == \":\" ]]; then\n  echo \"ERROR: HDK_COMMON_DIR not set. Source hdk_setup.sh first.\"\n  exit 2\nfi\n\nif [[ \":$VIVADO_VER\" == \":\" ]]; then\n  echo \"ERROR: VIVADO_VER not set. Source hdk_setup.sh first.\"\n  exit 2\nfi\n\nmodels_dir=$1\nif [[ \":$models_dir\" == \":\" ]]; then\n  models_dir=$HDK_COMMON_DIR/verif/models\nfi\n\nif [ ! -e $models_dir ]; then\n  mkdir -p $models_dir\nfi\n\nlockfile_filename=$models_dir/build.lock\n\n# Prevent multiple users from building in the same directory.\n# Set the number of retries to 0 so that we will just fail\n# and let the other process complete the build.\nif [ -e $lockfile_filename ]; then\n  echo \"ERROR: $lockfile_filename exists\"\n  echo \"ERROR: Another process is already building the models.\"\n  exit 2\nelse\n  touch $lockfile_filename\nfi\n\necho \"$VIVADO_VER\" > $models_dir/.vivado_version\n\nif ! vivado -mode batch -source $HDK_COMMON_DIR/verif/scripts/init.tcl; then\n  rm -f $lockfile_filename\n  exit 2\nfi\n\nddr4_imports_dir=tmp/tmp_ddr_ex/ddr4_core_ex/imports\nddr4_model_dir=$models_dir/ddr4_model\nddr4_rdimm_model_dir=$models_dir/ddr4_rdimm_wrapper\nif [ ! -d $ddr4_model_dir ]; then mkdir -p $ddr4_model_dir; fi\nif [ ! -d $ddr4_rdimm_model_dir ]; then mkdir -p $ddr4_rdimm_model_dir; fi\necho \"Copying files to $ddr4_model_dir\"\ncp $ddr4_imports_dir/arch_defines.v              $ddr4_model_dir/\ncp $ddr4_imports_dir/arch_package.sv              $ddr4_model_dir/\ncp $ddr4_imports_dir/ddr4_model.sv               $ddr4_model_dir/\ncp $ddr4_imports_dir/ddr4_sdram_model_wrapper.sv $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm_interface.sv           $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm_subtest.vh             $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm.vh                     $ddr4_model_dir/\ncp $ddr4_imports_dir/interface.sv                $ddr4_model_dir/\ncp $ddr4_imports_dir/MemoryArray.sv              $ddr4_model_dir/\ncp $ddr4_imports_dir/proj_package.sv             $ddr4_model_dir/\ncp $ddr4_imports_dir/StateTableCore.sv           $ddr4_model_dir/\ncp $ddr4_imports_dir/StateTable.sv               $ddr4_model_dir/\n#cp $ddr4_imports_dir/subtest.vh                  $ddr4_model_dir/\ncp $ddr4_imports_dir/timing_tasks.sv             $ddr4_model_dir/\n\necho \"Copying files to $ddr4_rdimm_model_dir\"\ncp $ddr4_imports_dir/ddr4_bi_delay.sv            $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_db_delay_model.sv      $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_db_dly_dir.sv          $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_dimm.sv                $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_dir_detect.sv          $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rank.sv                $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rcd_model.sv           $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rdimm_wrapper.sv       $ddr4_rdimm_model_dir/\n\n\necho \"patching ddr4_rdimm_wrapper.sv file\"\nsed -i s/_4G/_8G/g  $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\nsed -i -e 's/\\/\\/\\LRDIMM/\\: LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\nsed -i -e 's/\\/\\/\\!LRDIMM/\\: NOT_LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\n\necho \"patching ddr4_sdram_model_wrapper.sv file\"\nsed -i '/`include \"arch_package.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"proj_package.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"interface.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"ddr4_model.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\n\necho \"\\`include \\\"arch_package.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"proj_package.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"interface.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"ddr4_model.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\n\necho \"patching interface.sv file\"\nsed -i '/`include \"ddr4_sdram_model_wrapper.sv\"/d' $ddr4_model_dir/interface.sv\nsed -i '2i`ifndef DDR4_INT_DEF' $ddr4_model_dir/interface.sv\nsed -i '3i  `define DDR4_INT_DEF' $ddr4_model_dir/interface.sv\nsed -i '$a`endif' $ddr4_model_dir/interface.sv\n\necho \"patching proj_package.sv file\"\nsed -i '/`include \"ddr4_sdram_model_wrapper.sv\"/d' $ddr4_model_dir/proj_package.sv\nsed -i '2i`ifndef DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv\nsed -i '3i  `define DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv\nsed -i '$a`endif' $ddr4_model_dir/proj_package.sv\n\necho \"patching ddr4_model.sv file\"\nsed -i '1i`ifndef DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv\nsed -i '2i `define DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv\nsed -i '$a`endif' $ddr4_model_dir/ddr4_model.sv\n\nrm -f $lockfile_filename\n", "num_lines": 123}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Exit on any error\nset -e\n# Process command line args\n\nwhile [[ $# -gt 1 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    --test-name)\n        test_name=\"$2\"\n        shift\n        shift\n        ;;\n    --test-dir)\n        test_dir=\"$2\"\n        shift\n        shift\n        ;;\n    --simulator)\n        simulator=\"$2\"\n        shift\n        shift\n        ;;\n    --batch)\n        batch=\"$2\"\n        shift\n        shift\n        ;;\n    --vivado-version)\n      vivado_version=\"$2\"\n        shift\n        shift\n        ;;\n    --test-type)\n        test_type=\"$2\"\n        shift\n        shift\n        ;;\n    *)\n        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n        exit 1\n        ;;\nesac\ndone\n\nvivado_version=${vivado_version//./_}\nif [ $batch == \"TRUE\" ]; then\n# COMMAND=\"batch_submit.py -q vcs-lo --jd Cad-centos7_2 --jn github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} --wait --echo -c make\"\n# COMMAND=\"sbatch -c 1 --mem 64GB -p regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net -W -o ${test_name}_${test_type}_${simulator}.stdout.sim.log -e ${test_name}_${test_type}_${simulator}.stderr.sim.log sbatch_wrap.sh make\"\nCOMMAND=\"srun -c 1 --mem 64GB --time 160 -p verif_regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net make\"\n\nelse\nCOMMAND=\"make\"\nfi\n\necho \"$COMMAND\"\n\n# Run the test\npushd $test_dir\ncase \"$simulator\" in\n\tvcs)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" VCS=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 VCS=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 VCS=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 VCS=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" VCS=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" VCS=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\ties)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" IES=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 IES=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 IES=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 IES=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" IES=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" IES=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\tquesta)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" QUESTA=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 QUESTA=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 QUESTA=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" QUESTA=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" QUESTA=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\t*)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\"\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\"\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\"\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\nesac\n# Exit out of the test dir\npopd\n", "num_lines": 246}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nsed 's/\\([0-9]\\)\\( \\{0,\\}[,}]\\)/\\1f\\2/g' twid_radix4_8.cl > tmp\nmv tmp twid_radix4_8.cl\n", "num_lines": 5}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# \n# Copyright (C) 2018 Xilinx, Inc\n# Xilinx XRT setup functions\n#\n# Author: ryan.radjabi@xilinx.com\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n# \n#     http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nXRT_PATH=\"${SDACCEL_DIR}/Runtime/XRT_${RELEASE_VER}\"\n\nfunction get_install_cmd {\n    xrt_inst_cmd=\"install\"\n    aws_inst_cmd=\"install\"\n    if [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        dpkg -s xrt\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            xrt_inst_cmd=\"install --reinstall\"\n        fi\n        dpkg -s xrt-aws\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            aws_inst_cmd=\"install --reinstall\"\n        fi\n    elif [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        rpm -q xrt\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            xrt_inst_cmd=\"reinstall\"\n        fi\n        rpm -q xrt-aws\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            aws_inst_cmd=\"reinstall\"\n        fi\n    fi\n}\n\nfunction build_xrt {\n    info_msg \"xrt-path: $XRT_PATH\"\n    if [ -z \"$(ls -A $XRT_PATH)\" ]; then\n        # XRT_PATH is empty, this is the first run, so call submodule update\n        git submodule update --init -- $XRT_PATH\n    else\n        # XRT_PATH is not empty, only call init, this allows local changes to exist in XRT \n        git submodule init -- $XRT_PATH\n    fi\n    info_msg \"XRT Developer Flow: Building SDAccel runtime XRT...\"\n    sudo sh -c \"cd $XRT_PATH;./src/runtime_src/tools/scripts/xrtdeps.sh;\"\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to install dependencies: xrtdeps.sh: {$?}\"\n        return $?\n    fi\n    if [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        scl enable devtoolset-6 \"cd ${XRT_PATH}/build/; ./build.sh;\"\n    elif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        sudo sh -c \"cd ${XRT_PATH}/build/; ./build.sh;\"\n    fi\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to build XRT: {$?}\"\n    fi\n\n    return $?\n}\n\n# takes the path to RPM/DEB package as argument\nfunction install_xrt_package {\n    get_install_cmd\n    if [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        sudo sh -c \"cd $1; yum ${xrt_inst_cmd} -y xrt_*-xrt.rpm; yum ${aws_inst_cmd} -y xrt_*-aws.rpm;\"\n    elif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        sudo sh -c \"cd $1; apt ${xrt_inst_cmd} ./xrt_*-xrt.deb; apt ${aws_inst_cmd} ./xrt_*-aws.deb;\"\n    fi\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to install XRT: {$?}\"\n    else\n        info_msg \"SDAccel runtime installed\"\n    fi\n    return $?\n}\n\nfunction setup_runtime {\n    if [ -e /opt/xilinx/xrt ]; then # Check if XRT is installed\n        info_msg \"XRT Install, non-dev\"\n        export XILINX_XRT=/opt/xilinx/xrt\n        export LD_LIBRARY_PATH=$XILINX_XRT/lib:$LD_LIBRARY_PATH\n        # copy libstdc++ from $XILINX_SDX/lib\n        if [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n            sudo cp $XILINX_SDX/lib/lnx64.o/Ubuntu/libstdc++.so* /opt/xilinx/xrt/lib/\n        elif [[ $(lsb_release -si) == \"CentOS\" ]]; then\n            sudo cp $XILINX_SDX/lib/lnx64.o/Default/libstdc++.so* /opt/xilinx/xrt/lib/\n        else\n            info_msg \"Unsupported OS.\"\n            return 1\n        fi\n    elif [[ $RELEASE_VER == \"2017.4\" ]]; then # Build 2017.4 Runtime\n        info_msg \"SDACCEL Install\"\n        cd $SDACCEL_DIR\n        info_msg \"Building SDAccel runtime v$RELEASE_VER\"\n        if ! make ec2=1 debug=1 RELEASE_VER=$RELEASE_VER; then\n            err_msg \"Build of SDAccel runtime v$RELEASE_VER FAILED\"\n            return 1\n        fi\n        info_msg \"Installing SDAccel runtime v$RELEASE_VER\"\n        export INSTALL_ROOT=/opt/Xilinx/SDx/${RELEASE_VER}.rte.dyn\n        if ! sudo make ec2=1 debug=1 INSTALL_ROOT=$INSTALL_ROOT SDK_DIR=$SDK_DIR XILINX_SDX=$XILINX_SDX SDACCEL_DIR=$SDACCEL_DIR RELEASE_VER=$RELEASE_VER DSA=xilinx_aws-vu9p-f1-04261818_dynamic_5_0 install ; then\n            err_msg \"Install of SDAccel runtime v$RELEASE_VER FAILED\"\n            return 1\n        fi\n        info_msg \"SDAccel runtime v$RELEASE_VER installed\"\n        cd $current_dir\n    else # No XRT available and not 2017.4\n        info_msg \"SDAccel runtime not installed - This is required if you are running on an F1 instance.\"\n        # Placeholder for code to download pre-compiled RPM/DEB package and remove above message\n        # install_xrt_package <Path to RPM/DEB>\n    fi\n}\n", "num_lines": 132}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash \n\n# Amazon FPGA Hardware Development Kit\n#                                     \n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#                                                                        \n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is  \n# located at                                                                 \n#                                                                            \n#    http://aws.amazon.com/asl/                                              \n#                                                                            \n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or  \n# implied. See the License for the specific language governing permissions and\n# limitations under the License.                                              \n\nset -e\n\nscript=${BASH_SOURCE[0]}\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\n\nsource $AWS_FPGA_REPO_DIR/shared/bin/set_common_functions.sh\nsource $AWS_FPGA_REPO_DIR/shared/bin/set_common_env_vars.sh\n\ndebug=0\n\nfunction usage {\n   info_msg \"USAGE: $script_name [-h|-help] [-s3_bucket=<bucket_name>] [-s3_dcp_key=<S3_folder_of_dcp>] [-s3_logs_key=<S3_folder_of_logs>] [-xclbin=<xclbin_filename>] [-o=<awsxclbin_filename>] [-awsprofile=<aws_profile_name>]\"                                                                                               \n}                                                                                                              \n\nfunction help {\n  info_msg \"$script_name\"\n  info_msg \" \"           \n  info_msg \"SDAccel AFI Creation\"\n  info_msg \" \"                   \n  info_msg \"create_sdaccel_afi.sh assumes you have:\"\n  info_msg \"  (*) Read the README on Github and understand the SDAccel workflow (SDAccel/README.md)\"\n  info_msg \"  (*) Generated an XCLBIN using the SDAccel Build flow\"                                 \n  info_msg \"  (*) Ready to create an AFI and test on F1.  Your kernel has been validated using SW/HW Emulation.\"                                                                                                              \n  info_msg \"create_sdaccel_afi.sh will:\"                                                                       \n  info_msg \"  (1) Split your XCLBIN into two parts:  DCP (.bit) and Metadata (.xml)\"                           \n  info_msg \"  (2) Generates a Manifest file for AFI creation that sets the clocks based on your achieved target freq from your build\"                                                                                         \n  info_msg \"  (3) Prepares tar file for AFI creation process\"                                                  \n  info_msg \"  (4) Calls aws ec2 create-fpga-image\"                                                             \n  info_msg \"  (5) Creates new XCLBIN (called AWSXCLBIN) that is composed of: Metadata and AGFI-ID\"             \n  echo \" \"                                                                                                     \n  usage                                                                                                        \n}                                                                                                              \n\nif [ \"$1\" == \"\" ]\nthen             \n    err_msg \"Invalid usage\"\n    usage                  \n    exit 1                 \nfi                         \n\nwhile [ \"$1\" != \"\" ]; do\n    PARAM=`echo $1 | awk -F= '{print $1}'`\n    VALUE=`echo $1 | awk -F= '{print $2}'`\n    case $PARAM in                        \n        -h | --help)                      \n            help                          \n            exit                          \n            ;;                            \n        -xclbin)                          \n            xclbin=$VALUE                 \n            ;;                            \n        -o)                               \n            awsxclbin=$VALUE              \n            ;;                            \n        -aws_profile_name)                \n            aws_profile_name=$VALUE       \n            ;;                            \n        -s3_bucket)                       \n            s3_bucket=$VALUE              \n            ;;                            \n        -s3_logs_key)                     \n            s3_logs=$VALUE                \n            ;;                            \n        -s3_dcp_key)                      \n            s3_dcps=$VALUE                \n            ;;                            \n        *)                                \n            err_msg \"Unknown parameter \\\"$PARAM\\\"\"\n            usage                                 \n            exit 1                                \n            ;;                                    \n    esac                                          \n    shift                                         \ndone                                              \n\nif [ \"$HDK_DIR\" == \"\" ]\nthen\n    err_msg \"Env HDK_DIR not set\"\n    exit 1\nfi\n\nif [ \"$RELEASE_VER\" == \"\" ]\nthen\n    err_msg \"Env variable RELEASE_VER not set, did you source sdaccel_setup.sh?\"\n    exit 1\nfi\n\nif [[ -e \"$xclbin\" ]]\nthen                 \n    info_msg \"Found xclbin '$xclbin'\"\nelse                                 \n    err_msg \"File '$xclbin' not found\"\n    exit 1                            \nfi                                    \n\nstripped_xclbin=$(basename $xclbin)\next_xclbin=${stripped_xclbin##*.}  \nstripped_xclbin=${stripped_xclbin%.*}\n\ninfo_msg \"$stripped_xclbin\"\n\nif [ \"$awsxclbin\" == \"\" ]\nthen                     \n    awsxclbin=$stripped_xclbin\nfi                            \n\n\nif [ \"$awsxclbin\" != \"$stripped_xclbin\" ]\nthen                                     \n    warn_msg \"$awsxclbin does not match $stripped_xclbin\"\n    warn_msg \"For github examples, -o <xclbin_filename> must be equal to $stripped_xclbin\"\nfi                                                                                        \n\nif [[ -e \"$awsxclbin\" ]]\nthen                    \n    err_msg \"File '$awsxclbin' already exists\"\n    exit 1                                    \nfi                                            \n\nif [ \":$s3_bucket\" == \":\" ]\nthen                       \n    err_msg \"Invalid s3_bucket\"\n    usage                      \n    exit 1                     \nfi                             \n\n# s3 logs is not required\n# s3 dcp key is required \nif [ \"$s3_dcps\" == \"\" ]  \nthen                     \n    err_msg \"Invalid s3_dcps key\"\n    usage                        \n    exit 1                       \nfi                               \n\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\")\n\n#Steps\n#1. Strip XCLBIN to get DCP for ingestion\n#2. Create Manifest file                 \n#3. Prepare ingestion tar file           \n#4. Call create-fpga-image               \n#5. Manipulate the AFI ID                \n#6. Create awsxclbin                     \n\n#STEP 1\n#Strip XCLBIN to get DCP for ingestion\nif [[ -e \"${XILINX_SDX}/runtime/bin/xclbinsplit\" ]]\nthen\n    $XILINX_SDX/runtime/bin/xclbinsplit -o ${timestamp} $xclbin\nelse\n    /opt/xilinx/xrt/bin/xclbinsplit -o ${timestamp} $xclbin\nfi\n\nif [[ -e \"${timestamp}-primary.bit\" ]]\nthen\n    info_msg \"Split DCP from xclbin: ${timestamp}-primary.bit\"\nelse                                                          \n    err_msg \"File ${timestamp}-primary.bit not found\"         \n    exit 1                                                    \nfi                                                            \nif [[ -e \"${timestamp}-xclbin.xml\" ]]                         \nthen                                                          \n    info_msg \"Split Metadata from xclbin: ${timestamp}-primary.bit\"\nelse                                                               \n    err_msg \"File ${timestamp}-xclbin.xml not found\"               \n    exit 1                                                         \nfi                                                                 \n\nif [[ -d \"to_aws\" ]]\nthen                \n    err_msg \"Directory to_aws already exists\"\n    exit 1                                   \nfi                                           \n\nmkdir to_aws\ncp ${timestamp}-primary.bit to_aws/${timestamp}_SH_CL_routed.dcp\n\n#STEP 2\n#Create Manifest file\nstrategy=DEFAULT     \nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\nshell_version=0x04261818\ntool_version=v$RELEASE_VER\ndevice_id=0xF010                                                                                         \nvendor_id=0x1D0F                                                                                         \nsubsystem_id=0x1D51                                                                                      \nsubsystem_vendor_id=0xFEDD                                                                               \nboard_id=$(echo 'cat //project/platform/@boardid' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d \\\");                                                                                    \nplat_name=$(echo 'cat //project/platform/@name' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d \\\");                                                                                           \nclock_main_a0=$(echo 'cat //project/platform/device/systemClocks/clock/@frequency' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d MHz\\\" | xargs printf \"%.0f\");                          \nclock_extra_b0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port=\"DATA_CLK\"]/@frequency' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d MHz\\\" | xargs printf \"%.0f\");                 \n\nif [ \"$plat_name\" == \"dynamic\" ]\nthen\nclock_extra_c0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port=\"KERNEL_CLK\"]/@frequency' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d MHz\\\" | xargs printf \"%.0f\");                 \nelse \nclock_extra_c0=$(echo 'cat //project/platform/device/core/kernelClocks/clock[@port=\"KERNEL_CLK2\"]/@frequency' | xmllint --shell \"${timestamp}-xclbin.xml\" | grep -v \">\" | cut -f 2 -d \"=\" | tr -d MHz\\\" | xargs printf \"%.0f\");                 \nfi\n\n#id0_version=$(grep 'CL_SH_ID0' $CL_DIR/design/cl_id_defines.vh | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')                                                                                                     \n#device_id=\"0x${id0_version:0:4}\";                                                                             \n#vendor_id=\"0x${id0_version:4:4}\";                                                                             \n#id1_version=$(grep 'CL_SH_ID1' $CL_DIR/design/cl_id_defines.vh | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')                                                                                                     \n#subsystem_id=\"0x${id1_version:0:4}\";                                                                          \n#subsystem_vendor_id=\"0x${id1_version:4:4}\";                                                                   \n\nif [[ \"$board_id\" != \"aws-vu9p-f1-04261818\" ]]\nthen                                 \n    err_msg \"Platform $board_id used to create xclbin is not correct, you should be using aws-vu9p-f1-04261818\"\n    exit                                                                                              \nfi                                                                                                    \n\n#Write Manifest File here\nhash=$( sha256sum  to_aws/${timestamp}_SH_CL_routed.dcp | awk '{ print $1 }' )\nmanifest_file=\"${timestamp}_manifest.txt\"                                     \nexec 3<>$manifest_file                                                        \necho \"manifest_format_version=2\" >&3                                          \necho \"pci_vendor_id=$vendor_id\" >&3                                           \necho \"pci_device_id=$device_id\" >&3                                           \necho \"pci_subsystem_id=$subsystem_id\" >&3                                     \necho \"pci_subsystem_vendor_id=$subsystem_vendor_id\" >&3                       \necho \"dcp_hash=$hash\" >&3                                                     \necho \"shell_version=$shell_version\" >&3                                       \necho \"dcp_file_name=${timestamp}_SH_CL_routed.dcp\" >&3                        \necho \"hdk_version=$hdk_version\" >&3                                           \necho \"tool_version=$tool_version\" >&3                                               \necho \"date=$timestamp\" >&3                                                    \necho \"clock_main_a0=$clock_main_a0\" >&3                                       \necho \"clock_extra_b0=$clock_extra_b0\" >&3                                     \necho \"clock_extra_c0=$clock_extra_c0\" >&3                                     \nexec 3>&-                                                                     \nexec 3>&-                                                                     \n\nif [[ -e \"$manifest_file\" ]]\nthen                        \n    info_msg \"Generated manifest file '$manifest_file'\"\nelse                                                   \n    err_msg \"File '$manifest_file' not found\"          \n    exit 1                                             \nfi                                                     \ncp $manifest_file to_aws/$manifest_file                \n\n\n#STEP 3\n#Prepare ingestion\ntar -cf ${timestamp}_Developer_SDAccel_Kernel.tar to_aws/${timestamp}_SH_CL_routed.dcp to_aws/${timestamp}_manifest.txt                                                                                                       \n\n\n#STEP 4\n#Call create-fpga-image\nprofile_text=\"\"        \nif [ \"$aws_profile_name\" != \"\" ]\nthen                            \n    profile_text=\"--profile ${aws_profile_name}\"\nfi                                              \n\nlog_storage_text=\"\"\nif [ \"${s3_logs}\" != \"\" ]\nthen\n    log_storage_text=\"--logs-storage-location Bucket=${s3_bucket},Key=${s3_logs}\"\nfi\n\naws s3 ${profile_text} cp ${timestamp}_Developer_SDAccel_Kernel.tar s3://${s3_bucket}/${s3_dcps}/\naws ec2 ${profile_text} create-fpga-image --name ${stripped_xclbin} --description ${stripped_xclbin} --input-storage-location Bucket=${s3_bucket},Key=${s3_dcps}/${timestamp}_Developer_SDAccel_Kernel.tar ${log_storage_text} > ${timestamp}_afi_id.txt\n\n\n#STEP 5\n#Manipulate the AFI ID\ntest=`grep agfi ${timestamp}_afi_id.txt | awk -F: '{print $2}' | sed 's/ \\\"//g' | sed 's/\\\".*//g' | sed ':a;N;$!ba;s/\\n/ /g'`\necho -n $test > ${timestamp}_agfi_id.txt\necho ${timestamp}_agfi_id.txt\n\n#STEP 6\n#Create .awsxclbin\nif [[ -e \"${XILINX_SDX}/runtime/bin/xclbincat\" ]]\nthen\n    xclbincat=${XILINX_SDX}/runtime/bin/xclbincat\nelse\n    xclbincat=/opt/xilinx/xrt/bin/xclbincat\nfi\n\ncommand=\"$xclbincat -b ${timestamp}_agfi_id.txt -m ${timestamp}-xclbin.xml -n header.bin -o ${awsxclbin}.awsxclbin\"\nif [ \"$plat_name\" == \"dynamic\" ]\nthen\n    command=\"$command -k mode:hw_pr -k featureRomTimestamp:0 -r runtime_data.rtd\"\nfi\ninfo_msg \"Calling $command\"\n$command\n\n", "num_lines": 309}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nscript=${BASH_SOURCE[0]}\nif [ $script != $0 ]; then\n  echo \"ERROR: You must execute this script instead of sourcing!\"\n  return\nfi\n\n\nif [ -z \"$SDK_DIR\" ]; then\n    echo \"Error: SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    exit 1\nfi\n\ngcc --version &> /dev/null\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: gcc is not installed.\"\n    echo \"    You can install gcc and other useful development tools by using: sudo yum groupinstall \\\"Development tools\\\"\"\n    exit $RET \nfi\n\nsudo -V &> /dev/null\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: sudo is not in path or not installed. Driver installations will fail \"\n    echo \"    To install drivers please add sudo to your path or install sudo by running \\\"yum install sudo\\\" as root \"\n    #exit $RET \nfi\n\n\nSDK_USERSPACE_DIR=$SDK_DIR/userspace\n\n# Build the Amazon FPGA Image (AFI) Management Tools\n(cd $SDK_USERSPACE_DIR && ./mkall_fpga_mgmt_tools.sh)\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: mkall_fpga_mgmt_tools.sh returned $RET\"\n    exit $RET\nfi\necho \"Build complete.\"\n\n# Install the Amazon FPGA Image (AFI) Management Tools\n$SDK_USERSPACE_DIR/install_fpga_mgmt_tools.sh\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: install_fpga_mgmt_tools.sh returned $RET\"\n    exit $RET\nfi\n# Add udev rules if asked for non root access\nif allow_non_root ; then\n\t  sudo $SDK_USERSPACE_DIR/add_udev_rules.sh\n\t  RET=$?\n\t  if [ $RET != 0 ]; then\n\t\t\t\t echo \"Error: $SDK_USERSPACE_DIR/add_udev_rules.sh returned $RET\"\n\t\t\t\t exit $RET\n\t  fi\nfi\n\necho \"Done with SDK install.\"\n", "num_lines": 75}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nSLOT=$1\nfpga-describe-local-image -S $SLOT\necho \"$WORKSPACE/hdk/cl/examples/cl_hello_world/software/runtime/test_hello_world --slot $SLOT\" > /tmp/run_non_root_cmd_as_new_group\nnewgrp fpgauser << ES\nchmod 755 /tmp/run_non_root_cmd_as_new_group\n/tmp/run_non_root_cmd_as_new_group\nES\n\n", "num_lines": 27}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\ncd $SDK_DIR/apps/byte_swapper\nflask run --host=0.0.0.0 > flask_server.log 2>&1 &\necho \"CHILDPID $!\"\ncat flask_server.log\n", "num_lines": 21}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/bash -ex\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\ncd $SDK_DIR/tests\nrm -rf fio_dma_tools_original\naws s3 cp s3://aws-fpga-jenkins-testing/fio_dma_tools/ fio_dma_tools_original/ --recursive\ncd fio_dma_tools_original\nrm -rf xdma_v2017_1/\ncd fio\nchmod +x configure\n./configure\nmake\nmv fio ../scripts\ncd ..\nrm -rf fio\ncd ..\naws s3 rm s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive\naws s3 cp fio_dma_tools_original/ s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive\nrm -rf fio_dma_tools_original/\n", "num_lines": 34}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nsource /tmp/sdk_root_env.exp\nset +x\nrm -f /tmp/sdk_root_env.exp\n\nmkdir -p /opt/aws/bin\n\nDBDFs=`lspci -Dn |  grep -Ew \"1d0f:1042|1d0f:1041\" | awk '{print $1}' | sed ':x;N;$!bx;s/\\n/ /g'`\n\n\nif [[ $AWS_FPGA_SDK_OTHERS ]]; then\n# Allow all users\n\n  # Make a script that will be run to change permissions everytime\n  # udev rule for the DBDF is matched\n  echo \"Installing permission fix script for udev\"\n  cat >/opt/aws/bin/change-fpga-perm.sh<<EF\n#!/bin/bash\nset -x\nsetperm () {\n  chmod g=u \\$1\n  chmod a=u \\$1\n}\nsetfpgaperm () {\n  for f in \\$1/*; do\n    setperm \\$f;\n  done\n}\n\ndevicePath=/sys/bus/pci/devices/\\$1\ngrep -q \"0x058000\" \\$devicePath/class && setfpgaperm \"\\$devicePath\"\nsetperm /sys/bus/pci/rescan all\nEF\n\necho \"Adding udev rule: 9999-presistent-fpga.rules\"\ncat >/etc/udev/rules.d/9999-presistent-fpga.rules<<EF\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1041\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1041\", ACTION==\"add\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1042\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1042\", ACTION==\"add\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nEF\n\nelse\n# Allow group only\n\n  echo \"Creating group ${AWS_FPGA_SDK_GROUP}\"\n  getent group ${AWS_FPGA_SDK_GROUP} >/dev/null 2>&1\n  if [[ $? -eq 0 ]] ; then\n    if [ -z ${AWS_FPGA_SDK_OVERRIDE_GROUP} ] ; then\n      echo \"Group ${AWS_FPGA_SDK_GROUP} already exists. Please export a non existent group name  to AWS_FPGA_SDK_GROUP or export AWS_FPGA_SDK_OVERRIDE_GROUP=y\"\n      exit 1\n    fi\n    echo \"${AWS_FPGA_SDK_GROUP} already exists, will grant FPGA resource access to this group\"\n  else\n    groupadd  ${AWS_FPGA_SDK_GROUP}\n    if [[ $? -ne 0 ]] ; then\n      echo \"Could not group ${AWS_FPGA_SDK_GROUP}\"\n      exit 1\n    fi\n  fi\n\n  echo \"Adding user ${SDK_NON_ROOT_USER} into group ${AWS_FPGA_SDK_GROUP}\"\n  getent group ${AWS_FPGA_SDK_GROUP} | grep -qw ${SDK_NON_ROOT_USER}\n  if [[ $? -eq 0 ]] ; then\n    echo \"${SDK_NON_ROOT_USER} is already in group ${AWS_FPGA_SDK_GROUP}\"\n  else\n    usermod -a -G ${AWS_FPGA_SDK_GROUP} ${SDK_NON_ROOT_USER}\n    if [[ $? -ne 0 ]] ; then\n      echo \"Could not add user ${SDK_NON_ROOT_USER} to group ${AWS_FPGA_SDK_GROUP}\"\n      exit 1\n    fi\n  fi\n\n  # Fail on any unsucessful command\n  set -e\n  # Make a script that will be run to change permissions everytime\n  # udev rule for the DBDF is matched\n  echo \"Installing permission fix script for udev\"\n  cat >/opt/aws/bin/change-fpga-perm.sh<<EF\n#!/bin/bash\nset -x\nsetperm () {\n  chmod g=u \\$1\n  if [[ x\\$2 != \"x\" ]] ; then\n    chmod a=u \\$1\n  fi\n}\nsetgrp() {\n  chown root:${AWS_FPGA_SDK_GROUP} \\$1\n}\nsetfpgaperm () {\n  for f in \\$1/*; do\n    setperm \\$f;\n    setgrp \\$f\n  done\n}\n\ndevicePath=/sys/bus/pci/devices/\\$1\ngrep -q \"0x058000\" \\$devicePath/class && setfpgaperm \"\\$devicePath\"\nsetperm /sys/bus/pci/rescan all\nEF\n\necho \"Adding udev rule: 9999-presistent-fpga.rules\"\n\n  rm -f /tmp/9999-presistent-fpga.rules\n  for d in $DBDFs ; do\n    echo \"KERNEL==\\\"*${d}*\\\", RUN+=\\\"/opt/aws/bin/change-fpga-perm.sh '${d}'\\\"\" >> /tmp/9999-presistent-fpga.rules\n  done\n  for d in $DBDFs ; do\n    echo \"KERNEL==\\\"*${d}*\\\", ACTION==\\\"add\\\", RUN+=\\\"/opt/aws/bin/change-fpga-perm.sh '${d}'\\\"\" >> /tmp/9999-presistent-fpga.rules\n  done\n  echo \"Adding udev rule: 9999-presistent-fpga.rules\"\n  cp /tmp/9999-presistent-fpga.rules /etc/udev/rules.d/9999-presistent-fpga.rules\nfi\n\nchmod 544 /opt/aws/bin/change-fpga-perm.sh\n\n## Test the rules for any issues\nfor d in  $DBDFs ; do\nudevadm test --action=\"add\" /sys/bus/pci/devices/${d} >/dev/null 2>&1\ndone\n#\n## Make udev daemon aware of rule changes\nudevadm control --reload\n#\n## Trigger the change for rules to avoid a reboot\nfor d in  $DBDFs ; do\nudevadm trigger --action=\"add\"  /sys/bus/pci/devices/${d}\ndone\n", "num_lines": 147}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\nif [ -z \"$SDK_DIR\" ]; then\n\techo \"Error: SDK_DIR environment variable is not set.  Please 'source sdk_setup.sh' from the aws-fpga directory first.\"\n\texit 1\nfi\n\nif [ $EUID != 0 ]; then\n\techo \"\"\n\techo \"Root privileges are required to install. You may be asked for your password...\"\n\tsudo -E \"$0\" \"$@\"\n\texit $?\nelse\n\techo \"Executing as root...\"\n\techo \"\"\nfi\n\nBASE_PATH=/usr/local\n\n# check to see if the /usr/local/bin is on the sudo PATH (is secure_path enabled?)\necho $PATH | grep \"$BASE_PATH\"\nret=$?\nif [ $ret -ne \"0\" ]; then\n\tBASE_PATH=/usr\nfi\n\nSDK_MGMT_DIR=$SDK_DIR/userspace\nAFI_MGMT_TOOLS_SRC_DIR=$SDK_MGMT_DIR/fpga_mgmt_tools/src\nAFI_MGMT_TOOLS_DST_DIR=$BASE_PATH/bin\nAFI_MGMT_TOOLS_LIB_DIR=$SDK_MGMT_DIR/lib/so\n\n# in order to accommodate different distributions, check several options for the user-libraries directory\nif [ -d \"/usr/local/lib64\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/local/lib64\nelif [ -d \"/usr/local/lib\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/local/lib\nelif [ -d \"/usr/lib64\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/lib64\nelif [ -d \"/usr/lib\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/lib\nelse\n\techo \"Error: No directory for installing libraries.\"\n\texit 1\nfi\n\nif [ ! -d \"$AFI_MGMT_TOOLS_DST_DIR\" ]; then\n\tmkdir -p $AFI_MGMT_TOOLS_DST_DIR\nfi\n\n# /usr/bin requires sudo permissions \necho \"AWS FPGA: Copying Amazon FPGA Image (AFI) Management Tools to $AFI_MGMT_TOOLS_DST_DIR\"\ncp -f $AFI_MGMT_TOOLS_SRC_DIR/fpga-* $AFI_MGMT_TOOLS_DST_DIR\ncp -f $AFI_MGMT_TOOLS_LIB_DIR/libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR\nln -sf libfpga_mgmt.so.1 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so\nln -sf libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so.1\n\nsource /tmp/sdk_root_env.exp\nif allow_non_root ; then\n  chmod u+s $AFI_MGMT_TOOLS_DST_DIR/fpga-local-cmd\nfi\n\necho \"AWS FPGA: Installing shared library to $AFI_MGMT_LIBS_DST_DIR\"\nld_conf_change=\"0\"\nwhile true; do\n\t# update the dynamic linker cache\n\tldconfig\n\n\t# confirm that the linker cache stored the library we want\n\tldconfig -p | grep \"libfpga_mgmt\\.so\\.1\"\n\tret=$?\n\tif [ $ret -ne \"0\" ]; then\n\t\tif [ \"$ld_conf_change\" -eq \"1\" ]; then\n\t\t\techo \"Error: Unable to automatically install the fpga_mgmt library.\"\n\t\t\texit 1\n\t\tfi\n\t\tld_conf_change=\"1\"\n\t\techo \"$AFI_MGMT_LIBS_DST_DIR\" > /etc/ld.so.conf.d/fpga_mgmt-x86_64.conf\n\telse\n\t\tbreak\n\tfi\ndone\necho \"AWS FPGA: Installing python bindings for FPGA management library\"\ncat>/tmp/mod_search_path<<EF\nrm -f /tmp/py_install_paths\nif [[ \\$? -ne 0 ]] ; then\n\techo \"Could not install python modules\"\n\texit 1\nfi\nfor i in 2 3 ; do\n\twhich python\\$i >/dev/null 2>&1 || continue\n\tpython\\$i -c \"import sys\nprint(sys.path)\n\" | tr , '\\n' | tr -d \"'[]\" | grep -E \"64.*site-packages$\" >> /tmp/py_install_paths\ndone\nEF\nbash /tmp/mod_search_path\nwhile read -t 2 site_package ; do\n\tPYMODULES=\"fpga_dma.py fpga_mgmt.py fpga_pci.py\"\n\tfor mod in $PYMODULES ; do\n\t\tsudo sed -e \"s,PY_BIND_AFI_MGMT_LIBS_DST_DIR,$AFI_MGMT_LIBS_DST_DIR,g\" $SDK_DIR/userspace/python_bindings/$mod > $site_package/$mod\n\t\tif [[ $? -ne 0 ]] ; then\n\t\t\techo \"Could not install $mod\"\n\t\t\texit 1\n\t\tfi\n\t\techo \"Installed $site_package/$mod\"\n\tdone\ndone < /tmp/py_install_paths\necho \"AWS FPGA: Done with Amazon FPGA Image (AFI) Management Tools install.\"\n", "num_lines": 125}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Build script for the Amazon FPGA Image Management Tools and libraries.\n\nTOP=`pwd` \n\nLOGLEVEL=$1\nif [ -z \"$LOGLEVEL\" ]; then\n\tCONFIG_LOGLEVEL=0\nelse\n\tCONFIG_LOGLEVEL=$LOGLEVEL\nfi\n\nif allow_non_root ; then\n       OPT=\"$OPT -DFPGA_ALLOW_NON_ROOT=1\"\nfi\n\n#\n# gcc optimizations\n#OPT=\"-O3 -fno-strict-aliasing\"\n\n#\n# The max number of FPGA BARs that may be attached,\n# e.g. (FPGA_SLOT_MAX * FPGA_PF_MAX * FPGA_BAR_PER_PF_MAX) is the upper bound.\n#\nFPGA_PCI_BARS_DFLT=64\nFPGA_PCI_BARS_MAX=$2\nif [ -z \"$FPGA_PCI_BARS_MAX\" ]; then\n\tFPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_DFLT\nelse\n\tFPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_MAX\nfi\n\n# get the HDK/SDK version number\nsource $TOP/../../hdk/hdk_version.txt\n\nfunction build_exec {\n\tcd $TOP/$BUILD_DIR \n\techo \"Entering $TOP/$BUILD_DIR\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"could not cd to $TOP/$BUILD_DIR\"\n\t\texit 1\n\tfi\n\tmake clean\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make clean failed\"\n\t\texit 1\n\tfi\n\tmake OPT=\"$OPT -DCONFIG_LOGLEVEL=\"$CONFIG_LOGLEVEL\" -DFPGA_PCI_BARS_MAX=\"$FPGA_PCI_BARS_MAX\" -DCLI_VERSION='\\\"$HDK_VERSION\\\"'\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make failed\"\n\t\texit 1\n\tfi\n\tcd $TOP\n}\n\n\nBUILD_DIR=\"utils\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_pci\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_dma\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_mgmt\"\nbuild_exec\n\nBUILD_DIR=\"fpga_mgmt_tools/src\"\nbuild_exec\n", "num_lines": 90}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Build script for the Amazon FPGA Image Management Tools and associated libraries. \n\nTOP=`pwd` \n\nLOGLEVEL=$1\nif [ -z \"$LOGLEVEL\" ]; then\n\tCONFIG_LOGLEVEL=3\nelse\n\tCONFIG_LOGLEVEL=$LOGLEVEL\nfi\n\nfunction build_exec {\n\tcd $TOP/$BUILD_DIR \n\techo \"Entering $TOP/$BUILD_DIR\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"could not cd to $TOP/$BUILD_DIR\"\n\t\texit 1\n\tfi\n\tmake clean\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make clean failed\"\n\t\texit 1\n\tfi\n\tcd $TOP\n}\n\n\nBUILD_DIR=\"utils\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_pci\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_mgmt\"\nbuild_exec\n\nBUILD_DIR=\"fpga_mgmt_tools/src\"\nbuild_exec\n", "num_lines": 58}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\ninfo_msg \"Setting up environment variables\"\n\n# Make sure that AWS_FPGA_REPO_DIR is set to the location of this script.\nif [[ \":$AWS_FPGA_REPO_DIR\" == ':' ]]; then\n  debug_msg \"AWS_FPGA_REPO_DIR not set so setting to $script_dir\"\n  export AWS_FPGA_REPO_DIR=$script_dir\nelif [[ $AWS_FPGA_REPO_DIR != $script_dir ]]; then\n  info_msg \"Changing AWS_FPGA_REPO_DIR from $AWS_FPGA_REPO_DIR to $script_dir\"\n  export AWS_FPGA_REPO_DIR=$script_dir\nelse\n  debug_msg \"AWS_FPGA_REPO_DIR=$AWS_FPGA_REPO_DIR\"\nfi\n\n# HDK\n# Clear environment variables\nunset HDK_DIR\nunset HDK_COMMON_DIR\nunset HDK_SHELL_DIR\nunset HDK_SHELL_DESIGN_DIR\n\nexport -f allow_non_root\nexport -f allow_others\n\nif  allow_non_root || allow_others ; then\n\texport AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP:-\"fpgauser\"}\n\texport SDK_NON_ROOT_USER=$(whoami)\n  info_msg \"Allowing group ${AWS_FPGA_SDK_GROUP} access to FPGA management tools and resources\"\nfi\n\n\nexport HDK_DIR=$AWS_FPGA_REPO_DIR/hdk\n\n# The next variable should not be modified and should always point to the /common directory under HDK_DIR\nexport HDK_COMMON_DIR=$HDK_DIR/common\n\n# Point to the latest version of AWS shell\nexport HDK_SHELL_DIR=$(readlink -f $HDK_COMMON_DIR/shell_stable)\n\n# Set the common shell design dir\nexport HDK_SHELL_DESIGN_DIR=$HDK_SHELL_DIR/design\n\n# SDK\nunset SDK_DIR\n\nexport SDK_DIR=$AWS_FPGA_REPO_DIR/sdk\n\n# SDACCEL\n# Setup Location of SDACCEL_DIR\nexport SDACCEL_DIR=$AWS_FPGA_REPO_DIR/SDAccel\n#  Vitis\n# Setup Location of VITIS_DIR\nexport VITIS_DIR=$AWS_FPGA_REPO_DIR/Vitis\n\n# PYTHONPATH\n# Update PYTHONPATH with libraries used for unit testing\npython_lib=$AWS_FPGA_REPO_DIR/shared/lib\nPYTHONPATH=$python_lib:$PYTHONPATH\nexport PYTHONPATH\n\n# PATH Changes\n\nexport PATH=$(echo $PATH | sed -e 's/\\(^\\|:\\)[^:]\\+\\/shared\\/bin\\/scripts\\(:\\|$\\)/:/g; s/^://; s/:$//')\nPATH=$AWS_FPGA_REPO_DIR/shared/bin/scripts:$PATH\n\n# Enable xilinx licensing\nexport XILINX_ENABLE_AWS_WHITELIST=095707098027\n", "num_lines": 82}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n    if [[ $debug == 0 ]]; then\n        return\n    fi\n    echo -e \"DEBUG: $1\"\n}\n\nfunction err_msg {\n    echo -e >&2 \"ERROR: $1\"\n}\n\nfunction warn_msg {\n    echo -e \"WARNING: $1\"\n}\n\nfunction is_myvivado_set {\n    if env | grep -q ^MYVIVADO=\n    then\n        true\n    else\n        false\n    fi\n}\n\nfunction is_xilinx_path_set {\n    if env | grep -q ^XILINX_PATH\n    then\n        true\n    else\n        false\n    fi\n}\n\n# Function to check whether a command exists.\nexists() {\n    if command -v $1 >/dev/null 2>&1\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction get_base_vivado_version {\n    local  __resultvar=$1\n\n    if is_myvivado_set\n    then\n\n        local MYVIVADO_ENV_VAR_BACKUP=$MYVIVADO\n\n        unset MYVIVADO\n        local __vivado_version=$(get_vivado_version)\n        export MYVIVADO=$MYVIVADO_ENV_VAR_BACKUP\n    elif is_xilinx_path_set\n    then\n        local XILINX_PATH_ENV_VAR_BACKUP=$XILINX_PATH\n        unset XILINX_PATH\n        local __vivado_version=$(get_vivado_version)\n        export XILINX_PATH=$XILINX_PATH_ENV_VAR_BACKUP\n    else\n        local __vivado_version=$(get_vivado_version)\n    fi\n\n    if [[ \"$__resultvar\" ]]; then\n        eval $__resultvar=\"'$__vivado_version'\"\n    else\n        echo \"$__vivado_version\"\n    fi\n\n}\n\nfunction munge_myvivado_var {\n    if [[ ! -z $1 ]]; then\n        if ! echo \"$MYVIVADO\" | /bin/grep -Eq \"(^|:)$1($|:)\" ; then\n            if [ \"$2\" = \"after\" ] ; then\n                MYVIVADO=\"$MYVIVADO:$1\"\n            else\n                MYVIVADO=\"$1:$MYVIVADO\"\n            fi\n        fi\n        export MYVIVADO\n    fi\n}\n\nfunction get_vivado_version {\n    local __resultvar=$1\n\n    local __vivado_version=`vivado -version | grep Vivado | head -1`\n\n    if [[ \"$__resultvar\" ]]; then\n        eval $__resultvar=\"'__$vivado_version'\"\n    else\n        echo \"$__vivado_version\"\n    fi\n}\n\nfunction setup_patches {\n    local caller_script=\"${BASH_SOURCE[1]}\"\n\n    info_msg \"Checking if patch AR71715 needs to be installed\"\n    patch_AR71715\n\n    info_msg \"Checking if patch AR73068 needs to be installed\"\n    patch_AR73068 \"$caller_script\"\n}\n\nfunction is_patch_applied {\n    local patch_name=\"$1\"\n    local long_vivado_version=$(get_vivado_version)\n\n    if [[ \"$long_vivado_version\" =~ .*\"$patch_name\".* ]]; then\n      true\n    else\n      false\n    fi\n}\n\nfunction patch_AR71715 {\n    local bucket=\"aws-fpga-developer-ami/1.5.0/Patches\"\n    local object=\"AR71715.zip\"\n    local patch_dirname=\"AR71715\"\n    local patch_root=\"$XILINX_SDX/patches\"\n    local tool_dir=\"$XILINX_SDX\"\n\n    declare -a valid_vivado_versions=( \"Vivado v2018.2_AR71275_op (64-bit)\"\n                                        \"Vivado v2018.2.op (64-bit)\"\n                                        \"Vivado v2018.2 (64-bit)\"\n                                     )\n\n    local base_vivado_version=$(get_base_vivado_version)\n    is_patch_valid=false\n    for vivado_version in \"${valid_vivado_versions[@]}\"\n    do\n        if [ \":$vivado_version\" == \":$base_vivado_version\" ]; then\n            is_patch_valid=true\n        fi\n    done\n\n    if [ \"$is_patch_valid\" == \"true\" ]; then\n\n        info_msg \"Patch AR71715 is valid for $base_vivado_version\"\n\n        if [ ! -d $patch_root/$patch_dirname ]; then\n\n            info_msg \"Downloading the $patch_dirname patch.\"\n\n            curl -s https://s3.amazonaws.com/$bucket/$object -o $object || { err_msg \"Failed to download Patch $object from $bucket/$object\"; return 2; }\n\n            sudo mkdir -p $patch_root || { err_msg \"Failed to create path $patch_root  you need to have root permissions to install this patch. If you dont have root permissions please contact your system administrator\";  return 2; }\n\n            info_msg \"Extracting the $patch_dirname patch.\"\n\n            sudo unzip $object -d $patch_root/$patch_dirname || { err_msg \"Failed to unzip $object into: $patch_root/$patch_dirname\"; return 2; }\n            sudo cp $tool_dir/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl.bkp\n            sudo cp -f $patch_root/$patch_dirname/sdx/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl\n\n            rm $object\n\n            chmod -R 755 $patch_root/$patch_dirname\n        fi\n    fi\n}\n\nfunction install_patch {\n    local patch_name=\"$1\"\n    local patch_bucket=\"$2\"\n    local patch_object=\"$3\"\n    local patch_dir_name=\"${patch_object%.*}\"\n\n    if is_patch_applied $patch_name\n    then\n        info_msg \"$patch_name is already applied. Skipping.\"\n    else\n        info_msg \"Applying $patch_name\"\n        info_msg \"in bucket $patch_bucket\"\n        info_msg \"object $patch_object\"\n\n        # Checking if the patches directory exists and making it if it doesn't\n        [ -d $script_dir/patches ] || mkdir -p $script_dir/patches\n\n        info_msg \"Downloading the $patch_name from $patch_bucket/$patch_object.\"\n        debug_msg \"curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object\"\n\n        curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object || { err_msg \"Failed to download Patch $object from $patch_bucket/$patch_object\"; return 2; }\n\n        info_msg \"Extracting the $patch_name to $script_dir/patches/$patch_dir_name.\"\n\n        unzip -q -o $script_dir/patches/$patch_object -d $script_dir/patches/$patch_dir_name  || { err_msg \"Failed to extract $script_dir/patches/$patch_object to $script_dir/patches/$patch_dir_name\"; return 2; }\n\n        # XILINX_PATH should not have AR73068 at this point.\n        info_msg \"Appending XILINX_PATH with $script_dir/patches/$patch_dir_name/vivado\"\n\n        export XILINX_PATH=$XILINX_PATH:$script_dir/patches/$patch_dir_name/vivado\n    fi\n}\n\nfunction fix_patch_vitis_AR73068_2019_2 {\n    local patch_object=\"$1\"\n    local patch_dir_name=\"${patch_object%.*}\"\n    pushd patches/$patch_dir_name\n\n    sed -i '/.*checksum.*/d' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml\n    sed -i 's/coreRevision>73068/coreRevision>8/' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml\n    popd\n}\n\nfunction patch_AR73068_2019_2 {\n    info_msg \"Patching Vivado/Vitis 2019.2 with Xilinx Patch AR73068\"\n    local fix_patch=\"$1\"\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.8.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2019_2_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n\n    if [[ \"$fix_patch\" == true ]]; then\n      info_msg \"Fixing Patch AR73068 for Vitis\"\n      fix_patch_vitis_AR73068_2019_2 \"$patch_object\"\n    fi\n}\n\nfunction patch_AR73068_2019_1 {\n    info_msg \"Patching Vivado 2019.1 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.7.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2019_1_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2018_3 {\n    info_msg \"Patching Vivado 2018.3 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.6.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2018_3_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2018_2 {\n    info_msg \"Patching Vivado 2018.2 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.5.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2018_2_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2017_4 {\n    info_msg \"Patching Vivado 2017.4 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.4.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2017_4_preliminary_rev2.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068 {\n    local base_vivado_version=$(get_base_vivado_version)\n    local caller_script=\"$1\"\n    local fix_patch=false\n\n    # Vitis specific changes\n    if [[ \"$caller_script\" =~ \"vitis_setup.sh\" ]]; then\n      info_msg \"Patching Vitis with AR73068\"\n      fix_patch=true\n    fi\n\n    if [[ \"${base_vivado_version}\" =~ \"Vivado v2019.2\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2019_2 \"$fix_patch\"\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2019.1\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2019_1\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2018.3\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2018_3\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2018.2\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2018_2\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2017.4\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2017_4\n    else\n      info_msg \"Patch AR73068 not applicable for Vivado ${base_vivado_version}.\"\n    fi\n}\n\nfunction allow_non_root {\n       [ ! -z ${AWS_FPGA_ALLOW_NON_ROOT} ]\n}\n\nfunction allow_others {\n       [ ! -z ${AWS_FPGA_SDK_OTHERS} ]\n}\n", "num_lines": 315}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nos_uname=`uname -r`\n\nscript=${BASH_SOURCE[0]}\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\npython_versions=(3.6 2.7)\n\n# First install python if it is not installed.\nfor python_version in ${python_versions[@]}; do\n    if [[ $os_uname =~ (amzn2) ]]; then\n        python_version = ${python_version:0:1}\n    fi\n\n    python=python$python_version\n    pip=pip$python_version\n    yum_python_package=${python/./}\n    if [ ! -e /usr/bin/$python ]; then\n        if ! sudo yum -y install $yum_python_package; then\n            echo \"Error: Install of $yum_python_package failed\"\n            exit 1\n        fi\n    fi\ndone\n\n# Python2 pip is common between OS's. We can use that to install other\nif [ ! -e /usr/bin/pip2 ]; then\n    if ! sudo yum -y install python2-pip; then\n        echo \"Error: Install of $yum_python_package failed\"\n        exit 1\n    fi\n    sudo pip install -U 'pip<21'\nfi\n\n# Install virtualenv\nif [ ! -e /usr/bin/virtualenv ]; then\n    if ! sudo pip install virtualenv; then\n        echo \"Error: Install of virtualenv failed\"\n        exit 1\n    fi\nfi\n\n# Install virtualenvwrapper\nif [ ! -e ~/.local/bin/virtualenvwrapper.sh ]; then\n    if ! pip install --user virtualenvwrapper; then\n        echo \"Error: Install of virtualenvwrapper failed\"\n        exit 1\n    fi\nfi\n\nsource ~/.local/bin/virtualenvwrapper.sh\n\n# Create virtualenv environments\nfor python_version in ${python_versions[@]}; do\n\n    if [[ $os_uname =~ (amzn2) ]]\n    then\n        site_packages=/usr/lib64/python$python_version/site-packages/\n\n        python=python${python_version:0:1}\n\n        mkvirtualenv -r $script_dir/requirements.txt  -p $(which $python) --system-site-packages python${python_version:0:1}\n\n        # Adding the python bindings site packages to path\n        add2virtualenv $site_packages\n    else\n        python=python$python_version\n        mkvirtualenv -r $script_dir/requirements.txt  -p $(which $python) python${python_version:0:1}\n    fi\ndone\n", "num_lines": 91}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\nif ! source $script_dir/setup_test_env.sh; then\n    return 1\nfi\n\nif ! source $WORKSPACE/sdaccel_setup.sh; then\n    return 1\nfi\n", "num_lines": 37}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\nif ! source $script_dir/setup_test_env.sh; then\n    return 1\nfi\n\nif ! source $WORKSPACE/vitis_setup.sh; then\n    return 1\nfi\n", "num_lines": 37}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\ninstance_id=`curl http://169.254.169.254/latest/meta-data/instance-id`\ninstance_type=`curl http://169.254.169.254/latest/meta-data/instance-type`\n\necho \"Test Running on INSTANCE ID: $instance_id INSTANCE TYPE: $instance_type\"\n\nif [ \":$WORKSPACE\" == \":\" ]; then\n    export WORKSPACE=$(git rev-parse --show-toplevel)\nfi\nexport WORKON_HOME=$WORKSPACE/.virtualenvs\n\n$script_dir/install_python_venv.sh\n\n# Setup default environment to work on\nsource $WORKSPACE/.virtualenvs/python2/bin/activate\n\nexport PYTHONPATH=$WORKSPACE/shared/lib:$PYTHONPATH\n\nexport AWS_DEFAULT_REGION=us-east-1\n", "num_lines": 48}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\nif ! source $script_dir/setup_test_env.sh; then\n    return 1\nfi\n\nif ! source $WORKSPACE/hdk_setup.sh; then\n    return 1\nfi\n", "num_lines": 37}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\nexport LD_LIBRARY_PATH=$XILINX_SDX/lnx64/tools/opencv/:$LD_LIBRARY_PATH\n\nif ! source $script_dir/setup_test_env.sh; then\n    return 1\nfi\n\nif ! source $script_dir/setup_test_xrtpatch.sh; then\n    return 1\nfi\n \nif ! source $WORKSPACE/sdaccel_setup.sh; then\n    return 1\nfi\n", "num_lines": 43}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\nexport LD_LIBRARY_PATH=$XILINX_VITIS/lnx64/tools/opencv/:$LD_LIBRARY_PATH\n\nif ! source $script_dir/setup_test_env.sh; then\n    return 1\nfi\n\nif ! source $script_dir/setup_test_xrtpatch.sh; then\n    return 1\nfi\n \nif ! source $WORKSPACE/vitis_setup.sh; then\n    return 1\nfi\n", "num_lines": 43}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\nsetup_test_env_script_dir=$script_dir\n\nif ! source $script_dir/setup_test_env.sh; then\n  return 1\nfi\n\nif ! source $WORKSPACE/sdk_setup.sh; then\n  return 1\nfi\n\nif [ x$1 == \"xpy_bindings\" ] ; then\n  source $WORKSPACE/.virtualenvs/python3/bin/activate\n  aws s3 cp s3://aws-fpga-jenkins-testing/python_bindings_dependencies/setup.sh .\n  chmod 755 ./setup.sh\n  ./setup.sh\n  export PYTHONPATH=$PYTHONPATH:$SDK_DIR/apps\n  source $WORKSPACE/.virtualenvs/python2/bin/activate\nfi", "num_lines": 46}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is\n# located at\n#\n#    http://aws.amazon.com/asl/\n#\n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or\n# implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\n\ns3_ami_bucket=aws-fpga-developer-ami\n\nVIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::' | sed 's:v::'`\nexport VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:6}\necho \"VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION\"\n\n\nif [[ \"$VIVADO_TOOL_VERSION\" =~ .*2018\\.2.* ]]; then\n    echo \"Xilinx Vivado version is 2018.2\"\n\n    s3_ami_version=1.5.0\n    xrt_release_version=XRT_2018_2_XDF_RC5\n    xrt_rpm_name=xrt_201802.2.1.0_7.5.1804-xrt.rpm\n    aws_xrt_rpm_name=xrt_201802.2.1.0_7.5.1804-aws.rpm\n\n    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name\n    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name\n\n    if [ -f \"/opt/xilinx/xrt/include/version.h\" ]; then\n       echo \"XRT installed. proceeding to check version compatibility\"\n       xrt_build_ver=$(grep  'xrt_build_version_hash\\[\\]' /opt/xilinx/xrt/include/version.h | sed 's/\";//' | sed 's/^.*\"//')\n       echo \"Installed XRT version hash : $xrt_build_ver\"\n       if grep -Fxq \"$xrt_build_ver\" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n       then\n          echo \"XRT version $xrt_build_ver is up-to-date.\"\n       else\n          echo \"$xrt_build_ver is stale. upgrading XRT to\"\n          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n          sudo yum reinstall -y $xrt_rpm_name\n          echo \" XRT patch rpm installed successfully\"\n          sudo yum install -y $aws_xrt_rpm_name\n          echo \" XRT patch aws rpm installed successfully\"\n       fi\n    else\n       echo \"XRT not installed. Please install XRT\"\n       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n       sudo yum reinstall -y $xrt_rpm_name\n       echo \" XRT patch rpm installed successfully\"\n       sudo yum install -y $aws_xrt_rpm_name\n       echo \" XRT patch aws rpm installed successfully\"\n    fi\nelif [[ \"$VIVADO_TOOL_VERSION\" =~ .*2018\\.3.* ]]; then\n    echo \"Xilinx Vivado version is 2018.3\"\n\n    s3_ami_version=1.6.0\n    xrt_release_version=XRT_2018_3_RC5\n    xrt_rpm_name=xrt_201830.2.1.0_7.6.1810-xrt.rpm\n    aws_xrt_rpm_name=xrt_201830.2.1.0_7.6.1810-aws.rpm\n\n    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name\n    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name\n\n    if [ -f \"/opt/xilinx/xrt/include/version.h\" ]; then\n       echo \"XRT installed. proceeding to check version compatibility\"\n       xrt_build_ver=$(grep  'xrt_build_version_hash\\[\\]' /opt/xilinx/xrt/include/version.h | sed 's/\";//' | sed 's/^.*\"//')\n       echo \"Installed XRT version hash : $xrt_build_ver\"\n       if grep -Fxq \"$xrt_build_ver\" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n       then\n          echo \"XRT version $xrt_build_ver is up-to-date.\"\n       else\n          echo \"$xrt_build_ver is stale. upgrading XRT to\"\n          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n          sudo yum reinstall -y $xrt_rpm_name\n          echo \" XRT patch rpm installed successfully\"\n          sudo yum reinstall -y $aws_xrt_rpm_name\n          echo \" XRT patch aws rpm installed successfully\"\n       fi\n    else\n       echo \"XRT not installed. Please install XRT\"\n       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n       sudo yum reinstall -y $xrt_rpm_name\n       echo \" XRT patch rpm installed successfully\"\n       sudo yum install -y $aws_xrt_rpm_name\n       echo \" XRT patch aws rpm installed successfully\"\n    fi\nelif [[ \"$VIVADO_TOOL_VERSION\" =~ .*2019\\.1.* ]]; then\n    echo \"Xilinx Vivado version is 2019.1\"\n\n    s3_ami_version=1.7.0\n    xrt_release_version=XRT_2019_1_0_3\n    xrt_rpm_name=xrt_201910.2.2.0_7.7.1908-xrt.rpm\n    aws_xrt_rpm_name=xrt_201910.2.2.0_7.7.1908-aws.rpm\n\n    xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$xrt_rpm_name\n    aws_xrt_rpm_path=$s3_ami_bucket/$s3_ami_version/Patches/$xrt_release_version/$aws_xrt_rpm_name\n\n    if [ -f \"/opt/xilinx/xrt/include/version.h\" ]; then\n       echo \"XRT installed. proceeding to check version compatibility\"\n       xrt_build_ver=$(grep  'xrt_build_version_hash\\[\\]' /opt/xilinx/xrt/include/version.h | sed 's/\";//' | sed 's/^.*\"//')\n       echo \"Installed XRT version hash : $xrt_build_ver\"\n       if grep -Fxq \"$xrt_build_ver\" $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n       then\n          echo \"XRT version $xrt_build_ver is up-to-date.\"\n       else\n          echo \"$xrt_build_ver is stale. upgrading XRT to\"\n          cat $AWS_FPGA_REPO_DIR/SDAccel/sdaccel_xrt_version.txt\n          curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n          curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n          sudo yum reinstall -y $xrt_rpm_name\n          echo \" XRT patch rpm installed successfully\"\n          sudo yum reinstall -y $aws_xrt_rpm_name\n          echo \" XRT patch aws rpm installed successfully\"\n       fi\n    else\n       echo \"XRT not installed. Please install XRT\"\n       curl -s https://s3.amazonaws.com/$xrt_rpm_path  -o $xrt_rpm_name || { echo \" Error: Failed to download xrt rpm from  $xrt_rpm_path\"; return 2; }\n       curl -s https://s3.amazonaws.com/$aws_xrt_rpm_path -o $aws_xrt_rpm_name || { echo \" Error: Failed to download aws xrt rpm from  $aws_xrt_rpm_path\"; return 2; }\n       sudo yum reinstall -y $xrt_rpm_name\n       echo \" XRT patch rpm installed successfully\"\n       sudo yum install -y $aws_xrt_rpm_name\n       echo \" XRT patch aws rpm installed successfully\"\n    fi\nelse\n   echo \"Xilinx Vivado version is $VIVADO_TOOL_VERSION . Proceeding with base runtime version \"\nfi\n", "num_lines": 151}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "# \n# Copyright (C) 2018 Xilinx, Inc\n# Xilinx XRT setup functions\n#\n# Author: ryan.radjabi@xilinx.com\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n# \n#     http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n#\n\nXRT_PATH=\"${VITIS_DIR}/Runtime/XRT_${RELEASE_VER}\"\n\nfunction get_install_cmd {\n    xrt_inst_cmd=\"install\"\n    aws_inst_cmd=\"install\"\n    if [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        dpkg -s xrt\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            xrt_inst_cmd=\"install --reinstall\"\n        fi\n        dpkg -s xrt-aws\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            aws_inst_cmd=\"install --reinstall\"\n        fi\n    elif [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        rpm -q xrt\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            xrt_inst_cmd=\"reinstall\"\n        fi\n        rpm -q xrt-aws\n        ret=$?\n        if [[ $ret == \"0\" ]]; then\n            aws_inst_cmd=\"reinstall\"\n        fi\n    fi\n}\n\nfunction build_xrt {\n    info_msg \"xrt-path: $XRT_PATH\"\n    if [ -z \"$(ls -A $XRT_PATH)\" ]; then\n        # XRT_PATH is empty, this is the first run, so call submodule update\n        git submodule update --init -- $XRT_PATH\n    else\n        # XRT_PATH is not empty, only call init, this allows local changes to exist in XRT \n        git submodule init -- $XRT_PATH\n    fi\n    info_msg \"XRT Developer Flow: Building Xilinx runtime XRT...\"\n    sudo sh -c \"cd $XRT_PATH;./src/runtime_src/tools/scripts/xrtdeps.sh;\"\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to install dependencies: xrtdeps.sh: {$?}\"\n        return $?\n    fi\n    if [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        scl enable devtoolset-6 \"cd ${XRT_PATH}/build/; ./build.sh;\"\n    elif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        sudo sh -c \"cd ${XRT_PATH}/build/; ./build.sh;\"\n    fi\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to build XRT: {$?}\"\n    fi\n\n    return $?\n}\n\n# takes the path to RPM/DEB package as argument\nfunction install_xrt_package {\n    get_install_cmd\n    if [[ $(lsb_release -si) == \"CentOS\" ]]; then\n        sudo sh -c \"cd $1; yum ${xrt_inst_cmd} -y xrt_*-xrt.rpm; yum ${aws_inst_cmd} -y xrt_*-aws.rpm;\"\n    elif [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n        sudo sh -c \"cd $1; apt ${xrt_inst_cmd} ./xrt_*-xrt.deb; apt ${aws_inst_cmd} ./xrt_*-aws.deb;\"\n    fi\n    ret=$?\n    if [[ $ret != 0 ]]; then\n        err_msg \"XRT Developer Flow: Failed to install XRT: {$?}\"\n    else\n        info_msg \"Xilinx runtime installed\"\n    fi\n    return $?\n}\n\nfunction setup_runtime {\n    if [ -e /opt/xilinx/xrt ]; then # Check if XRT is installed\n        info_msg \"XRT Install, non-dev\"\n        export XILINX_XRT=/opt/xilinx/xrt\n        export PATH=$PATH:/opt/xilinx/xrt/bin\n\n        export LD_LIBRARY_PATH=$XILINX_XRT/lib:$LD_LIBRARY_PATH\n\n        if [[ $RELEASE_VER =~ .*2019\\.2.* ]]; then\n\n          # copy libstdc++ from $XILINX_VITIS/lib\n          if [[ $(lsb_release -si) == \"Ubuntu\" ]]; then\n              sudo cp $XILINX_VITIS/lib/lnx64.o/Ubuntu/libstdc++.so* /opt/xilinx/xrt/lib/\n          elif [[ $(lsb_release -si) == \"CentOS\" ]]; then\n              sudo cp $XILINX_VITIS/lib/lnx64.o/Default/libstdc++.so* /opt/xilinx/xrt/lib/\n          elif [[ $(lsb_release -si) == \"Amazon\" ]]; then\n              sudo cp /lib64/libstdc++.so* /opt/xilinx/xrt/lib/\n          else\n              info_msg \"Unsupported OS.\"\n              return 1\n          fi\n        fi\n    else # No XRT available\n        err_msg \"Xilinx XRT runtime not installed - This is required if you are running on an F1 instance.\"\n    fi\n}\n", "num_lines": 122}
{"repo_name": "aws-fpga", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash \n\n# Amazon FPGA Hardware Development Kit\n#                                     \n# Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#                                                                        \n# Licensed under the Amazon Software License (the \"License\"). You may not use\n# this file except in compliance with the License. A copy of the License is  \n# located at                                                                 \n#                                                                            \n#    http://aws.amazon.com/asl/                                              \n#                                                                            \n# or in the \"license\" file accompanying this file. This file is distributed on\n# an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or  \n# implied. See the License for the specific language governing permissions and\n# limitations under the License.                                              \n\nset -e\n\nscript=${BASH_SOURCE[0]}\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\n\nsource $AWS_FPGA_REPO_DIR/shared/bin/set_common_functions.sh\nsource $AWS_FPGA_REPO_DIR/shared/bin/set_common_env_vars.sh\nscript_dir=$(dirname $full_script)\n\n\ndebug=0\n\nfunction usage {\n   info_msg \"USAGE: $script_name [-h|-help] [-s3_bucket=<bucket_name>] [-s3_dcp_key=<S3_folder_of_dcp>] [-s3_logs_key=<S3_folder_of_logs>] [-xclbin=<xclbin_filename>] [-o=<awsxclbin_filename>] [-awsprofile=<aws_profile_name>]\"                                                                                               \n}                                                                                                              \n\nfunction help {\n  info_msg \"$script_name\"\n  info_msg \" \"           \n  info_msg \"Vitis AFI Creation\"\n  info_msg \" \"                   \n  info_msg \"create_vitis_afi.sh assumes you have:\"\n  info_msg \"  (*) Read the README on Github and understand the Vitis workflow (Vitis/README.md)\"\n  info_msg \"  (*) Generated an XCLBIN using the Vitis Build flow\"                                 \n  info_msg \"  (*) Ready to create an AFI and test on F1.  Your kernel has been validated using SW/HW Emulation.\"                                                                                                              \n  info_msg \"create_vitis_afi.sh will:\"                                                                       \n  info_msg \"  (1) Extract three parts from your XCLBIN:  DCP (.dcp) , clocks data(.json) and build metadata (.json)\"                           \n  info_msg \"  (2) Generates a Manifest file for AFI creation that sets the clocks based on your achieved target freq from your build\"                                                                                         \n  info_msg \"  (3) Prepares tar file for AFI creation process\"                                                  \n  info_msg \"  (4) Calls aws ec2 create-fpga-image\"                                                             \n  info_msg \"  (5) Creates new XCLBIN (called AWSXCLBIN) that is composed of: Metadata and AGFI-ID\"             \n  echo \" \"                                                                                                     \n  usage                                                                                                        \n}                                                                                                              \n\nif [ \"$1\" == \"\" ]\nthen             \n    err_msg \"Invalid usage\"\n    usage                  \n    exit 1                 \nfi                         \n\nwhile [ \"$1\" != \"\" ]; do\n    PARAM=`echo $1 | awk -F= '{print $1}'`\n    VALUE=`echo $1 | awk -F= '{print $2}'`\n    case $PARAM in                        \n        -h | --help)                      \n            help                          \n            exit                          \n            ;;                            \n        -xclbin)                          \n            xclbin=$VALUE                 \n            ;;                            \n        -o)                               \n            awsxclbin=$VALUE              \n            ;;                            \n        -aws_profile_name)                \n            aws_profile_name=$VALUE       \n            ;;                            \n        -s3_bucket)                       \n            s3_bucket=$VALUE              \n            ;;                            \n        -s3_logs_key)                     \n            s3_logs=$VALUE                \n            ;;                            \n        -s3_dcp_key)                      \n            s3_dcps=$VALUE                \n            ;;                            \n        *)                                \n            err_msg \"Unknown parameter \\\"$PARAM\\\"\"\n            usage                                 \n            exit 1                                \n            ;;                                    \n    esac                                          \n    shift                                         \ndone                                              \n\nif [ \"$RELEASE_VER\" == \"\" ]\nthen\n    err_msg \"Env variable RELEASE_VER not set, did you source sdaccel_setup.sh?\"\n    exit 1\nfi\n\nif [[ -e \"$xclbin\" ]]\nthen                 \n    info_msg \"Found xclbin '$xclbin'\"\nelse                                 \n    err_msg \"File '$xclbin' not found\"\n    exit 1                            \nfi                                    \n\nstripped_xclbin=$(basename $xclbin)\next_xclbin=${stripped_xclbin##*.}  \nstripped_xclbin=${stripped_xclbin%.*}\n\ninfo_msg \"$stripped_xclbin\"\n\nif [ \"$awsxclbin\" == \"\" ]\nthen                     \n    awsxclbin=$stripped_xclbin\nfi                            \n\n\nif [ \"$awsxclbin\" != \"$stripped_xclbin\" ]\nthen                                     \n    warn_msg \"$awsxclbin does not match $stripped_xclbin\"\n    warn_msg \"For github examples, -o <xclbin_filename> must be equal to $stripped_xclbin\"\nfi                                                                                        \n\nif [[ -e \"$awsxclbin\" ]]\nthen                    \n    err_msg \"File '$awsxclbin' already exists\"\n    exit 1                                    \nfi                                            \n\nif [ \":$s3_bucket\" == \":\" ]\nthen                       \n    err_msg \"Invalid s3_bucket\"\n    usage                      \n    exit 1                     \nfi                             \n\n# s3 logs is not required\n# s3 dcp key is required \nif [ \"$s3_dcps\" == \"\" ]  \nthen                     \n    err_msg \"Invalid s3_dcps key\"\n    usage                        \n    exit 1                       \nfi                               \n\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\")\n\n#Steps\n#1. Strip XCLBIN to get DCP for ingestion\n#2. Create Manifest file                 \n#3. Prepare ingestion tar file           \n#4. Call create-fpga-image               \n#5. Manipulate the AFI ID                \n#6. Create awsxclbin                     \n\n#STEP 1\n#Strip XCLBIN to get DCP for ingestion\n#/opt/xilinx/xrt/bin/xclbinsplit -o ${timestamp} $xclbin\n/opt/xilinx/xrt/bin/xclbinutil --dump-section BUILD_METADATA:JSON:${timestamp}_build.json --dump-section CLOCK_FREQ_TOPOLOGY:JSON:${timestamp}_clocks.json --dump-section BITSTREAM:RAW:${timestamp}_SH_CL_routed.dcp -i $xclbin\nif [[ -e \"${timestamp}_SH_CL_routed.dcp\" ]]\nthen\n    info_msg \"Split DCP from xclbin: ${timestamp}_SH_CL_routed.dcp\"\nelse                                                          \n    err_msg \"File ${timestamp}_SH_CL_routed.dcp not found\"         \n    exit 1                                                    \nfi                                                            \nif [[ -e \"${timestamp}_build.json\" ]]                         \nthen                                                          \n    info_msg \"The build Metadata from xclbin: ${timestamp}_build.json\"\nelse                                                               \n    err_msg \"File ${timestamp}_build.json not found\"               \n    exit 1                                                         \nfi                                                                 \nif [[ -e \"${timestamp}_clocks.json\" ]]                         \nthen                                                          \n    info_msg \"The clocks Metadata from xclbin: ${timestamp}_clocks.json\"\nelse                                                               \n    err_msg \"File ${timestamp}_clocks.json not found\"               \n    exit 1                                                         \nfi                                                                 \n\nif [[ -d \"to_aws\" ]]\nthen                \n    err_msg \"Directory to_aws already exists\"\n    exit 1                                   \nfi                                           \n\nmkdir to_aws\ncp ${timestamp}_SH_CL_routed.dcp ./to_aws/\n\n#STEP 2\n#Create Manifest file\nstrategy=DEFAULT     \nhdk_version=$(grep 'HDK_VERSION' $script_dir/../../hdk/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\nshell_version=0x04261818\ntool_version=v$RELEASE_VER\ndevice_id=0xF010\nvendor_id=0x1D0F                                                                                         \nsubsystem_id=0x1D51                                                                                      \nsubsystem_vendor_id=0xFEDD                                                                               \n# Get XSA info from build metadata\nvendor=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep vendor | sed 's/.*: \"//g' | sed 's/\",//'`)\nboard_id=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep board_id | sed 's/.*: \"//g' | sed 's/\",//'`)\nplat_name=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep name | sed 's/.*: \"//g' | sed 's/\",//'`)\nmajor=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep major | sed 's/.*: \"//g' | sed 's/\",//'`)\nminor=$(echo `grep -A 6 dsa ./${timestamp}_build.json | grep minor | sed 's/.*: \"//g' | sed 's/\",//'`)\n# Get clock info from clock metadata\nclock_main_a0=$(echo `grep -B 1 SYSTEM ${timestamp}_clocks.json | grep -o -e '[0-9]*'`)\nclock_extra_b0=$(echo `grep -B 2 DATA_CLK ${timestamp}_clocks.json | grep freq | grep -o -e '[0-9]*'`)\nclock_extra_c0=$(echo `grep -B 2 KERNEL_CLK ${timestamp}_clocks.json | grep -o -e '[0-9]*'`)\n\nif [[ \"$vendor\" != \"xilinx\" && \"$board_id\" != \"aws-vu9p-f1\" && \"$plat_name\" != \"shell-v04261818\" && \"$major\" != \"201920\" && \"$minor\" != \"2\" ]]\nthen                                 \n    err_msg \"Platform ${vendor}_${board_id}_${plat_name}_${major}_${minor} used to create xclbin is not correct, you should be using xilinx_aws-vu9p-f1_shell-v04261818_201920_3\"\n    exit                                                                                              \nfi                                                                                                    \n\n#Write Manifest File here\nhash=$( sha256sum  to_aws/${timestamp}_SH_CL_routed.dcp | awk '{ print $1 }' )\nmanifest_file=\"${timestamp}_manifest.txt\"                                     \nexec 3<>$manifest_file                                                        \necho \"manifest_format_version=2\" >&3                                          \necho \"pci_vendor_id=$vendor_id\" >&3                                           \necho \"pci_device_id=$device_id\" >&3                                           \necho \"pci_subsystem_id=$subsystem_id\" >&3                                     \necho \"pci_subsystem_vendor_id=$subsystem_vendor_id\" >&3                       \necho \"dcp_hash=$hash\" >&3                                                     \necho \"shell_version=$shell_version\" >&3                                       \necho \"dcp_file_name=${timestamp}_SH_CL_routed.dcp\" >&3                        \necho \"hdk_version=$hdk_version\" >&3                                           \necho \"tool_version=$tool_version\" >&3                                               \necho \"date=$timestamp\" >&3                                                    \necho \"clock_main_a0=$clock_main_a0\" >&3                                       \necho \"clock_extra_b0=$clock_extra_b0\" >&3                                     \necho \"clock_extra_c0=$clock_extra_c0\" >&3                                     \nexec 3>&-                                                                     \nexec 3>&-                                                                     \n\nif [[ -e \"$manifest_file\" ]]\nthen                        \n    info_msg \"Generated manifest file '$manifest_file'\"\nelse                                                   \n    err_msg \"File '$manifest_file' not found\"          \n    exit 1                                             \nfi                                                     \ncp $manifest_file to_aws/$manifest_file                \n\n\n#STEP 3\n#Prepare ingestion\ntar -cf ${timestamp}_Developer_Vitis_Kernel.tar to_aws/${timestamp}_SH_CL_routed.dcp to_aws/${timestamp}_manifest.txt                                                                                                       \n#STEP 4\n#Call create-fpga-image\nprofile_text=\"\"        \nif [ \"$aws_profile_name\" != \"\" ]\nthen                            \n    profile_text=\"--profile ${aws_profile_name}\"\nfi                                              \n\nlog_storage_text=\"\"\nif [ \"${s3_logs}\" != \"\" ]\nthen\n    log_storage_text=\"--logs-storage-location Bucket=${s3_bucket},Key=${s3_logs}\"\nfi\n\naws s3 ${profile_text} cp ${timestamp}_Developer_Vitis_Kernel.tar s3://${s3_bucket}/${s3_dcps}/\naws ec2 ${profile_text} create-fpga-image --name ${stripped_xclbin} --description ${stripped_xclbin} --input-storage-location Bucket=${s3_bucket},Key=${s3_dcps}/${timestamp}_Developer_Vitis_Kernel.tar ${log_storage_text} > ${timestamp}_afi_id.txt\n\n\n#STEP 5\n#Manipulate the AFI ID\ntest=`grep agfi ${timestamp}_afi_id.txt | awk -F: '{print $2}' | sed 's/ \\\"//g' | sed 's/\\\".*//g' | sed ':a;N;$!ba;s/\\n/ /g'`\necho -n $test > ${timestamp}_agfi_id.txt\necho ${timestamp}_agfi_id.txt\n\n#STEP 6\n#Create .awsxclbin\n\n\nif [[ \"$RELEASE_VER\" == \"2020.2\" || \"$RELEASE_VER\" == \"2021.1\" || \"$RELEASE_VER\" == \"2021.2\" ]]\nthen\n\t/opt/xilinx/xrt/bin/xclbinutil -i $xclbin --remove-section PARTITION_METADATA --replace-section BITSTREAM:RAW:${timestamp}_agfi_id.txt -o ${awsxclbin}.awsxclbin\nelse\n\t/opt/xilinx/xrt/bin/xclbinutil -i $xclbin --remove-section PARTITION_METADATA --remove-section SYSTEM_METADATA --replace-section BITSTREAM:RAW:${timestamp}_agfi_id.txt -o ${awsxclbin}.awsxclbin\nfi                                              \n", "num_lines": 290}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\n\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\ndebug=0\n\n\nfunction usage {\n  echo -e \"USAGE: source [\\$AWS_FPGA_REPO_DIR/]$script_name [-d|-debug] [-h|-help]\"\n}\n\nfunction help {\n  info_msg \"$script_name\"\n  info_msg \" \"\n  info_msg \"Sets up the environment for AWS FPGA HDK tools.\"\n  info_msg \" \"\n  info_msg \"hdk_setup.sh script will:\"\n  info_msg \"  (1) Check if Xilinx Vivado is installed,\"\n  info_msg \"  (2) Set up key environment variables HDK_*, and\"\n  info_msg \"  (3) Download/update the HDK shell's checkpoint\"\n  info_msg \"  (4) Prepare DRAM controller and PCIe IP modules if they are not already available in your directory.\"\n  echo \" \"\n  usage\n}\n\n# Process command line args\nargs=( \"$@\" )\nfor (( i = 0; i < ${#args[@]}; i++ )); do\n  arg=${args[$i]}\n  case $arg in\n    -d|-debug)\n      debug=1\n    ;;\n    -h|-help)\n      help\n      return 0\n    ;;\n    *)\n      err_msg \"Invalid option: $arg\\n\"\n      usage\n      return 1\n  esac\ndone\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\n\nhdk_shell_version=$(readlink $HDK_COMMON_DIR/shell_stable)\n\ndebug_msg \"Checking for Vivado install:\"\n\n# before going too far make sure Vivado is available\nif ! exists vivado; then\n    err_msg \"Please install/enable Vivado.\"\n    err_msg \"  If you are using the FPGA Developer AMI then please request support.\"\n    return 1\nfi\n\n# Install any patches as required\ninfo_msg \"Setting up Vivado patches if required.\"\nsetup_patches\n\n#Searching for Vivado version and comparing it with the list of supported versions\n\nexport VIVADO_VER=`vivado -version | grep Vivado | head -1`\n\ninfo_msg \"Using $VIVADO_VER\"\n\nif grep -Fxq \"$VIVADO_VER\" $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt\nthen\n    debug_msg \"$VIVADO_VER is supported by this HDK release.\"\nelse\n    err_msg \"$VIVADO_VER is not supported by this HDK release.\"\n    err_msg \"Supported versions are:\"\n    cat $AWS_FPGA_REPO_DIR/supported_vivado_versions.txt\n    return 1\nfi\n\nVIVADO_TOOL_VERSION=`vivado -version | grep Vivado | head -1 | sed 's:Vivado *::' | sed 's: .*$::'`\nexport VIVADO_TOOL_VERSION=${VIVADO_TOOL_VERSION:0:7}\necho \"VIVADO_TOOL_VERSION is $VIVADO_TOOL_VERSION\"\n\ndebug_msg \"Vivado check succeeded\"\n\n# The CL_DIR is where the actual Custom Logic design resides. The developer is expected to override this.\n# export CL_DIR=$HDK_DIR/cl/developer_designs\n\ndebug_msg \"Done setting environment variables.\";\n\n# Download correct shell DCP\ninfo_msg \"Using HDK shell version $hdk_shell_version\"\ndebug_msg \"Checking HDK shell's checkpoint version\"\nhdk_resources_s3_bucket=aws-fpga-hdk-resources\n\n# Shell files to be downloaded\n#declare -a s3_hdk_files=(\"SH_CL_BB_routed.dcp\"\n#                         \"cl_hello_world.debug_probes.ltx\"\n#                         \"cl_dram_dma.debug_probes.ltx\"\n#                        )\n#\ndeclare -a s3_hdk_files=(\"SH_CL_BB_routed.dcp\"\n                        )\n#\n\n# Downloading the shell files\nfor shell_file in \"${s3_hdk_files[@]}\"\ndo\n  # Determine if shell or debug probe\n  if [ $shell_file == \"SH_CL_BB_routed.dcp\" ]; then\n    sub_dir=\"checkpoints\"\n  else\n    sub_dir=\"debug_probes\"\n  fi\n  hdk_shell_dir=$HDK_SHELL_DIR/build/$sub_dir/from_aws\n  hdk_file=$hdk_shell_dir/$shell_file\n  s3_shell_dir=hdk/$hdk_shell_version/build/$sub_dir/from_aws\n  aws_alveo_shell_dir=alveo/u200/$hdk_shell_version\n  # Download the sha256\n  if [ ! -e $hdk_shell_dir ]; then\n      mkdir -p $hdk_shell_dir || { err_msg \"Failed to create $hdk_shell_dir\"; return 2; }\n  fi\n  # Use curl instead of AWS CLI so that credentials aren't required.\n#  echo -n \"Do you agree to AWS_F1_Shell_License_Agreement [Y/N]: \"\n#  read x\n#  if [ \"$x\" != \"Y\" ]; then\n#    echo \"exiting hdk_setup\"\n#    return 2\n#  fi\n  debug_msg \"curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256\"\n  curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256 || { err_msg \"Failed to download HDK shell's $shell_file version from $aws_alveo_shell_dir/$shell_file.sha256 -o $hdk_file.sha256\"; return 2; }\n  if grep -q '<?xml version' $hdk_file.sha256; then\n     err_msg \"Failed to download HDK shell's $shell_file version from $aws_alveo_shell_dir/$shell_file.sha256\"\n     cat $hdk_file.sha256\n     return 2\n  fi\n  exp_sha256=$(cat $hdk_file.sha256)\n  debug_msg \"  $shell_file latest   version=$exp_sha256\"\n  # If shell file already downloaded check its sha256\n  if [ -e $hdk_file ]; then\n    act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )\n    debug_msg \"  $shell_file existing version=$act_sha256\"\n    if [[ $act_sha256 != $exp_sha256 ]]; then\n      info_msg \"HDK shell's $shell_file version is incorrect\"\n      info_msg \"  Saving old file to $hdk_file.back\"\n      mv $hdk_file $hdk_file.back\n    fi\n  else\n    info_msg \"HDK shell's $shell_file hasn't been downloaded yet.\"\n  fi\n  if [ ! -e $hdk_file ]; then\n    echo -n \"Do you agree to AWS_F1_Shell_License_Agreement [Y/N]: \"\n    read x\n    if [ \"$x\" != \"Y\" ]; then\n      echo \"exiting hdk_setup\"\n      return 2\n    fi\n    info_msg \"Downloading latest HDK shell $shell_file from $aws_alveo_shell_dir/$shell_file\"\n    # Use curl instead of AWS CLI so that credentials aren't required.\n    curl -s https://$hdk_resources_s3_bucket.s3.amazonaws.com/$aws_alveo_shell_dir/$shell_file -o $hdk_file || { err_msg \"HDK shell checkpoint download failed\"; return 2; }\n  fi\n\n  # Check sha256\n  act_sha256=$( sha256sum $hdk_file | awk '{ print $1 }' )\n  if [[ $act_sha256 != $exp_sha256 ]]; then\n    err_msg \"Incorrect HDK shell checkpoint version:\"\n    err_msg \"  expected version=$exp_sha256\"\n    err_msg \"  actual   version=$act_sha256\"\n    err_msg \"  There may be an issue with the uploaded checkpoint or the download failed.\"\n    return 2\n  fi\n  info_msg \"HDK shell is up-to-date\"\ndone\n\n# Create DDR and PCIe IP models and patch PCIe\nmodels_dir=$HDK_COMMON_DIR/verif/models\nddr4_model_dir=$models_dir/ddr4_model\nif [ -f $ddr4_model_dir/arch_defines.v ]; then\n  # Models already built\n  # Check to make sure they were built with this version of vivado\n  if [[ -f $models_dir/.vivado_version ]]; then\n    models_vivado_version=$(cat $models_dir/.vivado_version)\n    info_msg \"DDR4 model files in $ddr4_model_dir/ were built with $models_vivado_version\"\n    if [[ $models_vivado_version != $VIVADO_VER ]]; then\n      info_msg \"  Wrong vivado version so rebuilding with $VIVADO_VER\"\n    fi\n  else\n    models_vivado_version=UNKNOWN\n    info_msg \"DDR4 model files in $ddr4_model_dir/ were built with UNKNOWN Vivado version so rebuilding.\"\n  fi\nelse\n  # Models haven't been built\n  models_vivado_version=NOT_BUILT\n  info_msg \"DDR4 model files in \"$ddr4_model_dir/\" do NOT exist. Running model creation step.\";\nfi\nif [[ $models_vivado_version != $VIVADO_VER ]] && [ ! -e $models_dir/build.lock ]; then\n  rm -rf $HDK_COMMON_DIR/verif/scripts/.done 2>&1 >/dev/null\nfi\nddr4_build_dir=$HDK_COMMON_DIR/verif/scripts/tmp\nif [ -d $ddr4_build_dir ] && [ ! -e $models_dir/build.lock ]; then rm -rf $ddr4_build_dir; fi\nif ! make -s -C $HDK_DIR/common/verif/scripts MODEL_DIR=$models_dir; then\n  err_msg \"  build dir=$ddr4_build_dir\"\n  return 2\nfi\n\nif [[ \":$CL_DIR\" == ':' ]]; then\n  info_msg \"attention: don't forget to set the CL_DIR variable for the directory of your custom logic.\";\nelse\n  info_msg \"CL_DIR is $CL_DIR\"\n  if [ ! -d $CL_DIR ]; then\n    err_msg \"CL_DIR doesn't exist. set CL_DIR to a valid directory.\"\n    unset CL_DIR\n  fi\nfi\n\ncd $current_dir\n\ninfo_msg \"AWS HDK setup PASSED.\";\n", "num_lines": 234}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n", "num_lines": 6}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Script must be sourced from a bash shell or it will not work\n# When being sourced $0 will be the interactive shell and $BASH_SOURCE_ will contain the script being sourced\n# When being run $0 and $_ will be the same.\nscript=${BASH_SOURCE[0]}\nif [ $script == $0 ]; then\n  echo \"ERROR: You must source this script\"\n  exit 2\nfi\n\nfull_script=$(readlink -f $script)\nscript_name=$(basename $full_script)\nscript_dir=$(dirname $full_script)\ncurrent_dir=$(pwd)\n\nsource $script_dir/shared/bin/set_common_functions.sh\nsource $script_dir/shared/bin/set_common_env_vars.sh\n\nsudo rm -f /tmp/sdk_root_env.exp\ntypeset -f allow_non_root > /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP}\" >> /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_OTHERS=${AWS_FPGA_SDK_OTHERS}\" >> /tmp/sdk_root_env.exp\necho \"export SDK_NON_ROOT_USER=${SDK_NON_ROOT_USER}\" >> /tmp/sdk_root_env.exp\necho \"export AWS_FPGA_SDK_OVERRIDE_GROUP=${AWS_FPGA_SDK_OVERRIDE_GROUP}\" >> /tmp/sdk_root_env.exp\nsudo chown root:root /tmp/sdk_root_env.exp\nsudo chmod 700 /tmp/sdk_root_env.exp\n\n#\n# Execute sdk_install.sh inside a subshell so the user's current\n# shell does not exit on errors from the install.\n#\ncd $script_dir\nif ! bash $SDK_DIR/sdk_install.sh; then\n    echo \"Error: AWS SDK install was unsuccessful, sdk_install.sh returned $?\"\n    return 1\nfi\n\ncd $current_dir\ninfo_msg \"$script_name PASSED\"\n", "num_lines": 54}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# TODO\n# Check if /build and /design directories exist, abort\n# Check if $HDK_COMMON_DIR exist\n\ncp -rL $HDK_SHELL_DIR/new_cl_template/build .\ncp -r  $HDK_SHELL_DIR/new_cl_template/design .\n", "num_lines": 14}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nif ! [[ $CL_DIR ]]\nthen\n\terr_msg \"Environment variable CL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [[ $HDK_SHELL_DIR ]]\nthen\n\terr_msg \"Environment variable HDK_SHELL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/constraints ]\nthen\n\terr_msg \"Constraints directory is not found in $CL_DIR/build/ directory\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/reports ]\nthen\n\tinfo_msg \"Creating the reports directory\"\n\tmkdir $CL_DIR/build/reports\n\tif ! [ -d $CL_DIR/build/reports ]\n\tthen\n\t\terr_msg \"Failed to create reports directory, please check directory permissions\"\n\t\texit 1\n\tfi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints ]\nthen\n        info_msg \"Creating the checkpoints directory\"\n        mkdir $CL_DIR/build/checkpoints\n        if ! [ -d $CL_DIR/build/checkpoints ]\n        then\n                err_msg \"Failed to create checkpoints directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints/to_aws ]\nthen\n        info_msg \"Creating the checkpoints/to_aws directory\"\n        mkdir $CL_DIR/build/checkpoints/to_aws\n        if ! [ -d $CL_DIR/build/checkpoints/to_aws ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/src_post_encryption ]\nthen\n        info_msg \"Creating the src_port_encryption directory\"\n        mkdir $CL_DIR/build/src_post_encryption\n        if ! [ -d $CL_DIR/build/src_post_encryption ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/bitstreams ]\nthen\n        info_msg \"Creating the bitstreams directory\"\n        mkdir $CL_DIR/build/bitstreams\n        if ! [ -d $CL_DIR/build/bitstreams ]\n        then\n                err_msg \"Failed to create bitstreams directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n", "num_lines": 103}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_clock_converter_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_clock_converter_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_clock_converter_0/sim/axi_clock_converter_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_clock_converter_0 xil_defaultlib.glbl -o axi_clock_converter_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_clock_converter_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_clock_converter_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_clock_converter_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 243}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L fifo_generator_v13_2_5 -L axi_clock_converter_v2_1_21 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_clock_converter_0 xil_defaultlib.axi_clock_converter_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_clock_converter_0 -key {Behavioral:sim_1:Functional:axi_clock_converter_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_clock_converter_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_512 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_clock_converter_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_clock_converter_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_clock_converter_512/sim/axi_clock_converter_512.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_clock_converter_512 xil_defaultlib.glbl -o axi_clock_converter_512_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_clock_converter_512_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_clock_converter_512_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_clock_converter_512_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 252}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_512 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L fifo_generator_v13_2_5 -L axi_clock_converter_v2_1_21 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_clock_converter_512 xil_defaultlib.axi_clock_converter_512 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_clock_converter_512 -key {Behavioral:sim_1:Functional:axi_clock_converter_512} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_clock_converter_512.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_register_slice/sim/axi_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_register_slice xil_defaultlib.glbl -o axi_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_register_slice xil_defaultlib.axi_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_register_slice -key {Behavioral:sim_1:Functional:axi_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice_light \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_register_slice_light/sim/axi_register_slice_light.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_register_slice_light xil_defaultlib.glbl -o axi_register_slice_light_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_register_slice_light_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_register_slice_light_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_register_slice_light_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice_light \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_register_slice_light xil_defaultlib.axi_register_slice_light xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_register_slice_light -key {Behavioral:sim_1:Functional:axi_register_slice_light} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_register_slice_light.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work generic_baseblocks_v2_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/b752/hdl/generic_baseblocks_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/af2c/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_data_fifo_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/54c0/hdl/axi_data_fifo_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_crossbar_v2_1_23 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/bc0a/hdl/axi_crossbar_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_xbar_0/sim/cl_axi_interconnect_xbar_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_s00_regslice_0/sim/cl_axi_interconnect_s00_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_s01_regslice_0/sim/cl_axi_interconnect_s01_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m00_regslice_0/sim/cl_axi_interconnect_m00_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m01_regslice_0/sim/cl_axi_interconnect_m01_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m02_regslice_0/sim/cl_axi_interconnect_m02_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m03_regslice_0/sim/cl_axi_interconnect_m03_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/sim/cl_axi_interconnect.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_axi_interconnect xil_defaultlib.glbl -o cl_axi_interconnect_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_axi_interconnect_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_axi_interconnect_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_axi_interconnect_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 262}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L generic_baseblocks_v2_1_0 -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L fifo_generator_v13_2_5 -L axi_data_fifo_v2_1_21 -L axi_crossbar_v2_1_23 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_axi_interconnect xil_defaultlib.cl_axi_interconnect xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_axi_interconnect -key {Behavioral:sim_1:Functional:cl_axi_interconnect} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_axi_interconnect.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect_m00_regslice_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../ipstatic/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../ipstatic/ipshared/ec67/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../ipstatic/ipshared/af2c/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_axi_interconnect_m00_regslice_0/sim/cl_axi_interconnect_m00_regslice_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_axi_interconnect_m00_regslice_0 xil_defaultlib.glbl -o cl_axi_interconnect_m00_regslice_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_axi_interconnect_m00_regslice_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_axi_interconnect_m00_regslice_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_axi_interconnect_m00_regslice_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect_m00_regslice_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../ipstatic/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_axi_interconnect_m00_regslice_0 xil_defaultlib.cl_axi_interconnect_m00_regslice_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_axi_interconnect_m00_regslice_0 -key {Behavioral:sim_1:Functional:cl_axi_interconnect_m00_regslice_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_axi_interconnect_m00_regslice_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_debug_bridge \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 179}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xsdbm_v3_0_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../ipstatic/hdl/xsdbm_v3_0_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/sim/bd_a493_xsdbm_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work lut_buffer_v2_0_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../ipstatic/hdl/lut_buffer_v2_0_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_1/sim/bd_a493_lut_buffer_0.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/sim/bd_a493.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/sim/cl_debug_bridge.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_debug_bridge xil_defaultlib.glbl -o cl_debug_bridge_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_debug_bridge_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_debug_bridge_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_debug_bridge_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 237}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_debug_bridge \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 179}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xsdbm_v3_0_0 -L xil_defaultlib -L lut_buffer_v2_0_0 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_debug_bridge xil_defaultlib.cl_debug_bridge xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_debug_bridge -key {Behavioral:sim_1:Functional:cl_debug_bridge} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_debug_bridge.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/modelsim\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 168}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/questa\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 175}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/riviera\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 154}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_0/sim/bd_bf3f_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_1/sim/bd_bf3f_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_2/sim/bd_bf3f_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_3/sim/bd_bf3f_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_4/sim/bd_bf3f_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_5/sim/bd_bf3f_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_6/sim/bd_bf3f_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_7/sim/bd_bf3f_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_8/sim/bd_bf3f_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_9/sim/bd_bf3f_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_10/sim/bd_bf3f_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/sim/bd_bf3f.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_0/sim/ddr4_core_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_core_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/ip_top/ddr4_core_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_core_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core xil_defaultlib.glbl -o ddr4_core_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/vcs\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 384}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core xil_defaultlib.ddr4_core xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core -key {Behavioral:sim_1:Functional:ddr4_core} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_a \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_0/sim/bd_8120_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_1/sim/bd_8120_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_2/sim/bd_8120_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_3/sim/bd_8120_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_4/sim/bd_8120_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_5/sim/bd_8120_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_6/sim/bd_8120_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_7/sim/bd_8120_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_8/sim/bd_8120_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_9/sim/bd_8120_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_10/sim/bd_8120_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/sim/bd_8120.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_0/sim/ddr4_core_a_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_core_a_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/ip_top/ddr4_core_a_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_core_a_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_a xil_defaultlib.glbl -o ddr4_core_a_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_a_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_a_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_a_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_a \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_a xil_defaultlib.ddr4_core_a xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_a -key {Behavioral:sim_1:Functional:ddr4_core_a} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_a.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_b \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_0/sim/bd_b066_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_1/sim/bd_b066_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_2/sim/bd_b066_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_3/sim/bd_b066_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_4/sim/bd_b066_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_5/sim/bd_b066_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_6/sim/bd_b066_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_7/sim/bd_b066_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_8/sim/bd_b066_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_9/sim/bd_b066_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_10/sim/bd_b066_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/sim/bd_b066.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_0/sim/ddr4_core_b_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_core_b_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/ip_top/ddr4_core_b_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_core_b_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_b xil_defaultlib.glbl -o ddr4_core_b_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_b_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_b_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_b_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_b \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_b xil_defaultlib.ddr4_core_b xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_b -key {Behavioral:sim_1:Functional:ddr4_core_b} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_b.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_c \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_0/sim/bd_a0a4_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_1/sim/bd_a0a4_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_2/sim/bd_a0a4_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_3/sim/bd_a0a4_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_4/sim/bd_a0a4_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_5/sim/bd_a0a4_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_6/sim/bd_a0a4_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_7/sim/bd_a0a4_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_8/sim/bd_a0a4_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_9/sim/bd_a0a4_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_10/sim/bd_a0a4_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/sim/bd_a0a4.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_0/sim/ddr4_core_c_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_core_c_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/ip_top/ddr4_core_c_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_core_c_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_c xil_defaultlib.glbl -o ddr4_core_c_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_c_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_c_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_c_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_c \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_c xil_defaultlib.ddr4_core_c xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_c -key {Behavioral:sim_1:Functional:ddr4_core_c} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_c.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_d \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_0/sim/bd_d2ea_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_1/sim/bd_d2ea_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_2/sim/bd_d2ea_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_3/sim/bd_d2ea_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_4/sim/bd_d2ea_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_5/sim/bd_d2ea_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_6/sim/bd_d2ea_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_7/sim/bd_d2ea_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_8/sim/bd_d2ea_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_9/sim/bd_d2ea_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_10/sim/bd_d2ea_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/sim/bd_d2ea.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_0/sim/ddr4_core_d_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_core_d_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/ip_top/ddr4_core_d_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_core_d_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_d xil_defaultlib.glbl -o ddr4_core_d_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_d_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_d_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_d_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_d \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_d xil_defaultlib.ddr4_core_d xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_d -key {Behavioral:sim_1:Functional:ddr4_core_d} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_d.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.dest_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/dest_register_slice/sim/dest_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.dest_register_slice xil_defaultlib.glbl -o dest_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./dest_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key dest_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc dest_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.dest_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot dest_register_slice xil_defaultlib.dest_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim dest_register_slice -key {Behavioral:sim_1:Functional:dest_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb dest_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_0/sim/ila_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_0 xil_defaultlib.glbl -o ila_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_0 xil_defaultlib.ila_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_0 -key {Behavioral:sim_1:Functional:ila_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_1 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_1/sim/ila_1.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_1 xil_defaultlib.glbl -o ila_1_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_1_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_1_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_1_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_1 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_1 xil_defaultlib.ila_1 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_1 -key {Behavioral:sim_1:Functional:ila_1} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_1.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_vio_counter \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_vio_counter/sim/ila_vio_counter.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_vio_counter xil_defaultlib.glbl -o ila_vio_counter_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_vio_counter_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_vio_counter_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_vio_counter_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_vio_counter \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_vio_counter xil_defaultlib.ila_vio_counter xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_vio_counter -key {Behavioral:sim_1:Functional:ila_vio_counter} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_vio_counter.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.src_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/src_register_slice/sim/src_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.src_register_slice xil_defaultlib.glbl -o src_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./src_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key src_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc src_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.src_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot src_register_slice xil_defaultlib.src_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim src_register_slice -key {Behavioral:sim_1:Functional:src_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb src_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.vio_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/sim/vio_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.vio_0 xil_defaultlib.glbl -o vio_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./vio_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key vio_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc vio_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.vio_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot vio_0 xil_defaultlib.vio_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim vio_0 -key {Behavioral:sim_1:Functional:vio_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb vio_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_bit_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nif ! [[ $CL_DIR ]]\nthen\n\terr_msg \"Environment variable CL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [[ $HDK_SHELL_DIR ]]\nthen\n\terr_msg \"Environment variable HDK_SHELL_DIR is not defined\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/constraints ]\nthen\n\terr_msg \"Constraints directory is not found in $CL_DIR/build/ directory\"\n\texit 1\nfi\n\nif ! [ -d $CL_DIR/build/reports ]\nthen\n\tinfo_msg \"Creating the reports directory\"\n\tmkdir $CL_DIR/build/reports\n\tif ! [ -d $CL_DIR/build/reports ]\n\tthen\n\t\terr_msg \"Failed to create reports directory, please check directory permissions\"\n\t\texit 1\n\tfi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints ]\nthen\n        info_msg \"Creating the checkpoints directory\"\n        mkdir $CL_DIR/build/checkpoints\n        if ! [ -d $CL_DIR/build/checkpoints ]\n        then\n                err_msg \"Failed to create checkpoints directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/checkpoints/to_aws ]\nthen\n        info_msg \"Creating the checkpoints/to_aws directory\"\n        mkdir $CL_DIR/build/checkpoints/to_aws\n        if ! [ -d $CL_DIR/build/checkpoints/to_aws ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/src_post_encryption ]\nthen\n        info_msg \"Creating the src_port_encryption directory\"\n        mkdir $CL_DIR/build/src_post_encryption\n        if ! [ -d $CL_DIR/build/src_post_encryption ]\n        then\n                err_msg \"Failed to create directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n\n\nif ! [ -d $CL_DIR/build/bitstreams ]\nthen\n        info_msg \"Creating the bitstreams directory\"\n        mkdir $CL_DIR/build/bitstreams\n        if ! [ -d $CL_DIR/build/bitstreams ]\n        then\n                err_msg \"Failed to create bitstreams directory, please check directory permissions\"\n                exit 1\n        fi\nfi\n", "num_lines": 103}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_clock_converter_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_clock_converter_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_clock_converter_0/sim/axi_clock_converter_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_clock_converter_0 xil_defaultlib.glbl -o axi_clock_converter_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_clock_converter_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_clock_converter_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_clock_converter_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 243}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:44:13 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_0.sh [-help]\n# usage: axi_clock_converter_0.sh [-lib_map_path]\n# usage: axi_clock_converter_0.sh [-noclean_files]\n# usage: axi_clock_converter_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_clock_converter_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L fifo_generator_v13_2_5 -L axi_clock_converter_v2_1_21 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_clock_converter_0 xil_defaultlib.axi_clock_converter_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_clock_converter_0 -key {Behavioral:sim_1:Functional:axi_clock_converter_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_clock_converter_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_0.sh [-help]\\n\\\nUsage: axi_clock_converter_0.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_0.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_512 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_clock_converter_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_clock_converter_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_clock_converter_512/sim/axi_clock_converter_512.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_clock_converter_512 xil_defaultlib.glbl -o axi_clock_converter_512_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_clock_converter_512_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_clock_converter_512_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_clock_converter_512_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 252}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_clock_converter_512.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm axi_infrastructure_v1_1_0 fifo_generator_v13_2_5 axi_clock_converter_v2_1_21 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_clock_converter_512 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_clock_converter_512.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:57:49 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_clock_converter_512.sh [-help]\n# usage: axi_clock_converter_512.sh [-lib_map_path]\n# usage: axi_clock_converter_512.sh [-noclean_files]\n# usage: axi_clock_converter_512.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_clock_converter_512.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L fifo_generator_v13_2_5 -L axi_clock_converter_v2_1_21 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_clock_converter_512 xil_defaultlib.axi_clock_converter_512 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_clock_converter_512 -key {Behavioral:sim_1:Functional:axi_clock_converter_512} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_clock_converter_512.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_clock_converter_512.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_clock_converter_512.sh [-help]\\n\\\nUsage: axi_clock_converter_512.sh [-lib_map_path]\\n\\\nUsage: axi_clock_converter_512.sh [-reset_run]\\n\\\nUsage: axi_clock_converter_512.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_register_slice/sim/axi_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_register_slice xil_defaultlib.glbl -o axi_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:48:10 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice.sh [-help]\n# usage: axi_register_slice.sh [-lib_map_path]\n# usage: axi_register_slice.sh [-noclean_files]\n# usage: axi_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_register_slice xil_defaultlib.axi_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_register_slice -key {Behavioral:sim_1:Functional:axi_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice.sh [-help]\\n\\\nUsage: axi_register_slice.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice.sh [-reset_run]\\n\\\nUsage: axi_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice_light \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/axi_register_slice_light/sim/axi_register_slice_light.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.axi_register_slice_light xil_defaultlib.glbl -o axi_register_slice_light_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./axi_register_slice_light_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key axi_register_slice_light_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc axi_register_slice_light_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'axi_register_slice_light.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.axi_register_slice_light \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : axi_register_slice_light.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:50:29 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: axi_register_slice_light.sh [-help]\n# usage: axi_register_slice_light.sh [-lib_map_path]\n# usage: axi_register_slice_light.sh [-noclean_files]\n# usage: axi_register_slice_light.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"axi_register_slice_light.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot axi_register_slice_light xil_defaultlib.axi_register_slice_light xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim axi_register_slice_light -key {Behavioral:sim_1:Functional:axi_register_slice_light} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb axi_register_slice_light.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./axi_register_slice_light.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: axi_register_slice_light.sh [-help]\\n\\\nUsage: axi_register_slice_light.sh [-lib_map_path]\\n\\\nUsage: axi_register_slice_light.sh [-reset_run]\\n\\\nUsage: axi_register_slice_light.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work generic_baseblocks_v2_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/b752/hdl/generic_baseblocks_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/af2c/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/simulation/fifo_generator_vlog_beh.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work fifo_generator_v13_2_5 $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/hdl/fifo_generator_v13_2_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work fifo_generator_v13_2_5 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/276e/hdl/fifo_generator_v13_2_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_data_fifo_v2_1_21 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/54c0/hdl/axi_data_fifo_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_crossbar_v2_1_23 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/bc0a/hdl/axi_crossbar_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_xbar_0/sim/cl_axi_interconnect_xbar_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_s00_regslice_0/sim/cl_axi_interconnect_s00_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_s01_regslice_0/sim/cl_axi_interconnect_s01_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m00_regslice_0/sim/cl_axi_interconnect_m00_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m01_regslice_0/sim/cl_axi_interconnect_m01_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m02_regslice_0/sim/cl_axi_interconnect_m02_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/ip/cl_axi_interconnect_m03_regslice_0/sim/cl_axi_interconnect_m03_regslice_0.v\" \\\n    \"$ref_dir/../../../bd/cl_axi_interconnect/sim/cl_axi_interconnect.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_axi_interconnect xil_defaultlib.glbl -o cl_axi_interconnect_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_axi_interconnect_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_axi_interconnect_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_axi_interconnect_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 262}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(generic_baseblocks_v2_1_0 axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 fifo_generator_v13_2_5 axi_data_fifo_v2_1_21 axi_crossbar_v2_1_23 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../../ip.gen/sources_1/bd/cl_axi_interconnect/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Wed Dec 15 00:52:38 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect.sh [-help]\n# usage: cl_axi_interconnect.sh [-lib_map_path]\n# usage: cl_axi_interconnect.sh [-noclean_files]\n# usage: cl_axi_interconnect.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_axi_interconnect.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L generic_baseblocks_v2_1_0 -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L fifo_generator_v13_2_5 -L axi_data_fifo_v2_1_21 -L axi_crossbar_v2_1_23 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_axi_interconnect xil_defaultlib.cl_axi_interconnect xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_axi_interconnect -key {Behavioral:sim_1:Functional:cl_axi_interconnect} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_axi_interconnect.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect.sh [-help]\\n\\\nUsage: cl_axi_interconnect.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect_m00_regslice_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../ipstatic/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../ipstatic/ipshared/ec67/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../ipstatic/ipshared/af2c/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_axi_interconnect_m00_regslice_0/sim/cl_axi_interconnect_m00_regslice_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_axi_interconnect_m00_regslice_0 xil_defaultlib.glbl -o cl_axi_interconnect_m00_regslice_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_axi_interconnect_m00_regslice_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_axi_interconnect_m00_regslice_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_axi_interconnect_m00_regslice_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_axi_interconnect_m00_regslice_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_axi_interconnect_m00_regslice_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/ipshared/ec67/hdl\" \\\n       +incdir+\"../../../ipstatic/ipshared/ec67/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_axi_interconnect_m00_regslice_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:53:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\n# usage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_axi_interconnect_m00_regslice_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_axi_interconnect_m00_regslice_0 xil_defaultlib.cl_axi_interconnect_m00_regslice_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_axi_interconnect_m00_regslice_0 -key {Behavioral:sim_1:Functional:cl_axi_interconnect_m00_regslice_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_axi_interconnect_m00_regslice_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_axi_interconnect_m00_regslice_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_axi_interconnect_m00_regslice_0.sh [-help]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-lib_map_path]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-reset_run]\\n\\\nUsage: cl_axi_interconnect_m00_regslice_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_debug_bridge \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 179}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xsdbm_v3_0_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../ipstatic/hdl/xsdbm_v3_0_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/sim/bd_a493_xsdbm_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work lut_buffer_v2_0_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../ipstatic/hdl/lut_buffer_v2_0_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_1/sim/bd_a493_lut_buffer_0.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/sim/bd_a493.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/cl_debug_bridge/sim/cl_debug_bridge.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.cl_debug_bridge xil_defaultlib.glbl -o cl_debug_bridge_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./cl_debug_bridge_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key cl_debug_bridge_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc cl_debug_bridge_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 237}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'cl_debug_bridge.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xsdbm_v3_0_0 xil_defaultlib lut_buffer_v2_0_0)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.cl_debug_bridge \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../ipstatic/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/cl_debug_bridge/bd_0/ip/ip_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 179}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : cl_debug_bridge.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 17:59:08 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: cl_debug_bridge.sh [-help]\n# usage: cl_debug_bridge.sh [-lib_map_path]\n# usage: cl_debug_bridge.sh [-noclean_files]\n# usage: cl_debug_bridge.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"cl_debug_bridge.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xsdbm_v3_0_0 -L xil_defaultlib -L lut_buffer_v2_0_0 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot cl_debug_bridge xil_defaultlib.cl_debug_bridge xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim cl_debug_bridge -key {Behavioral:sim_1:Functional:cl_debug_bridge} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb cl_debug_bridge.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./cl_debug_bridge.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: cl_debug_bridge.sh [-help]\\n\\\nUsage: cl_debug_bridge.sh [-lib_map_path]\\n\\\nUsage: cl_debug_bridge.sh [-reset_run]\\n\\\nUsage: cl_debug_bridge.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/modelsim\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 168}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/questa\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 175}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/riviera\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 154}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_0/sim/bd_bf3f_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_1/sim/bd_bf3f_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_2/sim/bd_bf3f_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_3/sim/bd_bf3f_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_4/sim/bd_bf3f_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_5/sim/bd_bf3f_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_6/sim/bd_bf3f_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_7/sim/bd_bf3f_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_8/sim/bd_bf3f_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_9/sim/bd_bf3f_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/ip/ip_10/sim/bd_bf3f_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/bd_0/sim/bd_bf3f.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_0/sim/ddr4_core_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_core_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/ip_top/ddr4_core_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal/ddr4_core_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top/ddr4_core.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core xil_defaultlib.glbl -o ddr4_core_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  else\n    lib_map_path=\"/proj/chimera_work/zhcz/f1-alveo-staging/hdk/common/shell_v04261818/design/ip/ip.cache/compile_simlib/vcs\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 384}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Thu Dec 16 09:26:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core.sh [-help]\n# usage: ddr4_core.sh [-lib_map_path]\n# usage: ddr4_core.sh [-noclean_files]\n# usage: ddr4_core.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core xil_defaultlib.ddr4_core xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core -key {Behavioral:sim_1:Functional:ddr4_core} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -protoinst \"protoinst_files/cl_axi_interconnect.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core.sh [-help]\\n\\\nUsage: ddr4_core.sh [-lib_map_path]\\n\\\nUsage: ddr4_core.sh [-reset_run]\\n\\\nUsage: ddr4_core.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_a \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_0/sim/bd_8120_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_1/sim/bd_8120_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_2/sim/bd_8120_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_3/sim/bd_8120_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_4/sim/bd_8120_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_5/sim/bd_8120_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_6/sim/bd_8120_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_7/sim/bd_8120_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_8/sim/bd_8120_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_9/sim/bd_8120_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/ip/ip_10/sim/bd_8120_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/bd_0/sim/bd_8120.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_0/sim/ddr4_core_a_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_core_a_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/ip_top/ddr4_core_a_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal/ddr4_core_a_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top/ddr4_core_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_a xil_defaultlib.glbl -o ddr4_core_a_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_a_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_a_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_a_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_a.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_a \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_a/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_a.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:57 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_a.sh [-help]\n# usage: ddr4_core_a.sh [-lib_map_path]\n# usage: ddr4_core_a.sh [-noclean_files]\n# usage: ddr4_core_a.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_a.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_a xil_defaultlib.ddr4_core_a xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_a -key {Behavioral:sim_1:Functional:ddr4_core_a} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_a.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_a.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_a.sh [-help]\\n\\\nUsage: ddr4_core_a.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_a.sh [-reset_run]\\n\\\nUsage: ddr4_core_a.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_b \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_0/sim/bd_b066_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_1/sim/bd_b066_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_2/sim/bd_b066_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_3/sim/bd_b066_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_4/sim/bd_b066_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_5/sim/bd_b066_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_6/sim/bd_b066_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_7/sim/bd_b066_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_8/sim/bd_b066_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_9/sim/bd_b066_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/ip/ip_10/sim/bd_b066_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/bd_0/sim/bd_b066.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_0/sim/ddr4_core_b_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_core_b_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/ip_top/ddr4_core_b_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal/ddr4_core_b_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top/ddr4_core_b.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_b xil_defaultlib.glbl -o ddr4_core_b_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_b_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_b_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_b_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_b.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_b \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_b/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_b.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:40:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_b.sh [-help]\n# usage: ddr4_core_b.sh [-lib_map_path]\n# usage: ddr4_core_b.sh [-noclean_files]\n# usage: ddr4_core_b.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_b.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_b xil_defaultlib.ddr4_core_b xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_b -key {Behavioral:sim_1:Functional:ddr4_core_b} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_b.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_b.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_b.sh [-help]\\n\\\nUsage: ddr4_core_b.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_b.sh [-reset_run]\\n\\\nUsage: ddr4_core_b.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_c \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_0/sim/bd_a0a4_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_1/sim/bd_a0a4_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_2/sim/bd_a0a4_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_3/sim/bd_a0a4_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_4/sim/bd_a0a4_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_5/sim/bd_a0a4_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_6/sim/bd_a0a4_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_7/sim/bd_a0a4_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_8/sim/bd_a0a4_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_9/sim/bd_a0a4_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/ip/ip_10/sim/bd_a0a4_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/bd_0/sim/bd_a0a4.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_0/sim/ddr4_core_c_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_core_c_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/ip_top/ddr4_core_c_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal/ddr4_core_c_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top/ddr4_core_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_c xil_defaultlib.glbl -o ddr4_core_c_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_c_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_c_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_c_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_c.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_c \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_c/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_c.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:33:19 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_c.sh [-help]\n# usage: ddr4_core_c.sh [-lib_map_path]\n# usage: ddr4_core_c.sh [-noclean_files]\n# usage: ddr4_core_c.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_c.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_c xil_defaultlib.ddr4_core_c xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_c -key {Behavioral:sim_1:Functional:ddr4_core_c} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_c.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_c.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_c.sh [-help]\\n\\\nUsage: ddr4_core_c.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_c.sh [-reset_run]\\n\\\nUsage: ddr4_core_c.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_d \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xpm $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_cdc/hdl/xpm_cdc.sv\" \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_memory/hdl/xpm_memory.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xpm $vhdlan_opts \\\n    \"/tools/xilinx/Vivado/2020.2/data/ip/xpm/xpm_VCOMP.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work microblaze_v11_0_4 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/microblaze_v11_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_0/sim/bd_d2ea_microblaze_I_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lib_cdc_v1_0_2 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lib_cdc_v1_0_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work proc_sys_reset_v5_0_13 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/proc_sys_reset_v5_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_1/sim/bd_d2ea_rst_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_v10_v3_0_11 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_v10_v3_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_2/sim/bd_d2ea_ilmb_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_3/sim/bd_d2ea_dlmb_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work lmb_bram_if_cntlr_v4_0_19 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/lmb_bram_if_cntlr_v4_0_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_4/sim/bd_d2ea_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_5/sim/bd_d2ea_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work blk_mem_gen_v8_4_4 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../ipstatic/simulation/blk_mem_gen_v8_4.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_6/sim/bd_d2ea_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_7/sim/bd_d2ea_second_dlmb_cntlr_0.vhd\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_8/sim/bd_d2ea_second_ilmb_cntlr_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_9/sim/bd_d2ea_second_lmb_bram_I_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vhdlan -work iomodule_v3_1_6 $vhdlan_opts \\\n    \"$ref_dir/../../../ipstatic/hdl/iomodule_v3_1_vh_rfs.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vhdlan -work xil_defaultlib $vhdlan_opts \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/ip/ip_10/sim/bd_d2ea_iomodule_0_0.vhd\" \\\n  2>&1 | tee -a vhdlan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/bd_0/sim/bd_d2ea.v\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_0/sim/ddr4_core_d_microblaze_mcs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts -sverilog +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_core_d_phy_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy_behav.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/phy/ddr4_phy_v2_2_xiphy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/iob/ddr4_phy_v2_2_iob_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/iob/ddr4_phy_v2_2_iob.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/clocking/ddr4_phy_v2_2_pll.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_tristate_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_riuor_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_control_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_byte_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/xiphy_files/ddr4_phy_v2_2_xiphy_bitslice_wrapper.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/ip_top/ddr4_core_d_phy.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_wtr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ref.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_rd_wr.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_periodic.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_group.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_merge_enc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_gen.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_fi_xor.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_dec_fix.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc_buf.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ecc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_ctl.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_cmd_mux_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_cmd_mux_ap.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_mux_p.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_c.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_arb_a.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_act_timer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc_act_rank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/controller/ddr4_v2_2_mc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_wr_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_rd_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ui/ddr4_v2_2_ui.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_ar_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_aw_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_b_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_cmd_translator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_incr_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_r_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_w_channel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_wr_cmd_fsm.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_wrap_cmd.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_a_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axi_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_axic_register_slice.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_latch_and.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_latch_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_carry_or.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_command_fifo.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator_sel.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_comparator_sel_static.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_r_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi/ddr4_v2_2_w_upsizer.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg_bank.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_reg.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/axi_ctrl/ddr4_v2_2_axi_ctrl_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/clocking/ddr4_v2_2_infrastructure.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_xsdb_bram.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_write.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_wr_byte.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_wr_bit.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_sync.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_read.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_rd_en.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_pi.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_mc_odt.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_debug_microblaze.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_cplx_data.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_cplx.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_config_rom.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_addr_decode.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_top.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal_xsdb_arbiter.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_cal.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_chipscope_xsdb_slave.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_v2_2_dp_AB9.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d_ddr4.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d_ddr4_mem_intfc.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal/ddr4_core_d_ddr4_cal_riu.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top/ddr4_core_d.sv\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/tb/microblaze_mcs_0.sv\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ddr4_core_d xil_defaultlib.glbl -o ddr4_core_d_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ddr4_core_d_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ddr4_core_d_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ddr4_core_d_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 394}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ddr4_core_d.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xpm microblaze_v11_0_4 xil_defaultlib lib_cdc_v1_0_2 proc_sys_reset_v5_0_13 lmb_v10_v3_0_11 lmb_bram_if_cntlr_v4_0_19 blk_mem_gen_v8_4_4 iomodule_v3_1_6)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ddr4_core_d \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/ip_1/rtl/map\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/ip_top\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ddr4_core_d/rtl/cal\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 182}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ddr4_core_d.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 16:34:23 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ddr4_core_d.sh [-help]\n# usage: ddr4_core_d.sh [-lib_map_path]\n# usage: ddr4_core_d.sh [-noclean_files]\n# usage: ddr4_core_d.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\nxvhdl_opts=\"--relax\"\n\n\n# Script info\necho -e \"ddr4_core_d.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n  xvhdl $xvhdl_opts -prj vhdl.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L microblaze_v11_0_4 -L xil_defaultlib -L lib_cdc_v1_0_2 -L proc_sys_reset_v5_0_13 -L lmb_v10_v3_0_11 -L lmb_bram_if_cntlr_v4_0_19 -L blk_mem_gen_v8_4_4 -L iomodule_v3_1_6 -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ddr4_core_d xil_defaultlib.ddr4_core_d xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ddr4_core_d -key {Behavioral:sim_1:Functional:ddr4_core_d} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(lib_cdc_v1_0_2)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ddr4_core_d.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ddr4_core_d.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ddr4_core_d.sh [-help]\\n\\\nUsage: ddr4_core_d.sh [-lib_map_path]\\n\\\nUsage: ddr4_core_d.sh [-reset_run]\\n\\\nUsage: ddr4_core_d.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 215}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.dest_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/dest_register_slice/sim/dest_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.dest_register_slice xil_defaultlib.glbl -o dest_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./dest_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key dest_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc dest_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'dest_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.dest_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : dest_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:08:26 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: dest_register_slice.sh [-help]\n# usage: dest_register_slice.sh [-lib_map_path]\n# usage: dest_register_slice.sh [-noclean_files]\n# usage: dest_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"dest_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot dest_register_slice xil_defaultlib.dest_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim dest_register_slice -key {Behavioral:sim_1:Functional:dest_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib axi_infrastructure_v1_1_0)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb dest_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./dest_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: dest_register_slice.sh [-help]\\n\\\nUsage: dest_register_slice.sh [-lib_map_path]\\n\\\nUsage: dest_register_slice.sh [-reset_run]\\n\\\nUsage: dest_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_0/sim/ila_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_0 xil_defaultlib.glbl -o ila_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_0/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:12:52 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_0.sh [-help]\n# usage: ila_0.sh [-lib_map_path]\n# usage: ila_0.sh [-noclean_files]\n# usage: ila_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_0 xil_defaultlib.ila_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_0 -key {Behavioral:sim_1:Functional:ila_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_0.sh [-help]\\n\\\nUsage: ila_0.sh [-lib_map_path]\\n\\\nUsage: ila_0.sh [-reset_run]\\n\\\nUsage: ila_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_1 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_1/sim/ila_1.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_1 xil_defaultlib.glbl -o ila_1_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_1_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_1_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_1_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_1.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_1 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_1/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_1.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:18:21 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_1.sh [-help]\n# usage: ila_1.sh [-lib_map_path]\n# usage: ila_1.sh [-noclean_files]\n# usage: ila_1.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_1.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_1 xil_defaultlib.ila_1 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_1 -key {Behavioral:sim_1:Functional:ila_1} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_1.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_1.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_1.sh [-help]\\n\\\nUsage: ila_1.sh [-lib_map_path]\\n\\\nUsage: ila_1.sh [-reset_run]\\n\\\nUsage: ila_1.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_vio_counter \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/ila_vio_counter/sim/ila_vio_counter.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.ila_vio_counter xil_defaultlib.glbl -o ila_vio_counter_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./ila_vio_counter_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key ila_vio_counter_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc ila_vio_counter_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'ila_vio_counter.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.ila_vio_counter \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/ila_vio_counter/hdl/verilog\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 177}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : ila_vio_counter.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:32:01 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: ila_vio_counter.sh [-help]\n# usage: ila_vio_counter.sh [-lib_map_path]\n# usage: ila_vio_counter.sh [-noclean_files]\n# usage: ila_vio_counter.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"ila_vio_counter.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot ila_vio_counter xil_defaultlib.ila_vio_counter xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim ila_vio_counter -key {Behavioral:sim_1:Functional:ila_vio_counter} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb ila_vio_counter.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./ila_vio_counter.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: ila_vio_counter.sh [-help]\\n\\\nUsage: ila_vio_counter.sh [-lib_map_path]\\n\\\nUsage: ila_vio_counter.sh [-reset_run]\\n\\\nUsage: ila_vio_counter.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.src_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work axi_infrastructure_v1_1_0 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_infrastructure_v1_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work axi_register_slice_v2_1_22 $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../ipstatic/hdl/axi_register_slice_v2_1_vl_rfs.v\" \\\n  2>&1 | tee -a vlogan.log\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/src_register_slice/sim/src_register_slice.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.src_register_slice xil_defaultlib.glbl -o src_register_slice_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./src_register_slice_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key src_register_slice_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc src_register_slice_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 231}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'src_register_slice.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(axi_infrastructure_v1_1_0 axi_register_slice_v2_1_22 xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.src_register_slice \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"$ref_dir/../../../ipstatic/hdl\" \\\n       +incdir+\"../../../ipstatic/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : src_register_slice.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:33:41 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: src_register_slice.sh [-help]\n# usage: src_register_slice.sh [-lib_map_path]\n# usage: src_register_slice.sh [-noclean_files]\n# usage: src_register_slice.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"src_register_slice.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L axi_infrastructure_v1_1_0 -L axi_register_slice_v2_1_22 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot src_register_slice xil_defaultlib.src_register_slice xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim src_register_slice -key {Behavioral:sim_1:Functional:src_register_slice} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=(xil_defaultlib)\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb src_register_slice.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./src_register_slice.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: src_register_slice.sh [-help]\\n\\\nUsage: src_register_slice.sh [-lib_map_path]\\n\\\nUsage: src_register_slice.sh [-reset_run]\\n\\\nUsage: src_register_slice.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Aldec Active-HDL Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work activehdl)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 153}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Cadence Incisive Enterprise Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nirun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"ies_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  irun $irun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.vio_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ncsim.key irun.key irun.log waves.shm irun.history .simvision INCA_libs)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Mentor Graphics ModelSim Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"modelsim_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf modelsim_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 169}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Mentor Graphics Questa Advanced Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  source elaborate.do 2>&1 | tee -a elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  vsim -64 -c -do \"do {simulate.do}\" -l simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy modelsim.ini file\ncopy_setup_file()\n{\n  file=\"modelsim.ini\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    cp $src_file .\n  fi\n}\n\n# Create design library directory\ncreate_lib_dir()\n{\n  lib_dir=\"questa_lib\"\n  if [[ -e $lib_dir ]]; then\n    rm -rf $lib_dir\n  fi\n\n  mkdir $lib_dir\n\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaborate.log simulate.log vsim.wlf questa_lib)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 176}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Aldec Riviera-PRO Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  source compile.do 2>&1 | tee -a compile.log\n\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  runvsimsa -l simulate.log -do \"do {simulate.do}\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     map_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     map_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Map library.cfg file\nmap_setup_file()\n{\n  file=\"library.cfg\"\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      vmap -link $lib_map_path\n    fi\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(compile.log elaboration.log simulate.log dataset.asdb work riviera)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 155}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Synopsys Verilog Compiler Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Command line options\nvlogan_opts=\"-full64\"\nvhdlan_opts=\"-full64\"\nvcs_elab_opts=\"-full64 -debug_pp -t ps -licqueue -l elaborate.log\"\nvcs_sim_opts=\"-ucli -licqueue -l simulate.log\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"vcs_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  vlogan -work xil_defaultlib $vlogan_opts +v2k +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" +incdir+\"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/hdl\" \\\n    \"$ref_dir/../../../../ip.gen/sources_1/ip/vio_0/sim/vio_0.v\" \\\n  2>&1 | tee -a vlogan.log\n\n\n  vlogan -work xil_defaultlib $vlogan_opts +v2k \\\n    glbl.v \\\n  2>&1 | tee -a vlogan.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  vcs $vcs_elab_opts xil_defaultlib.vio_0 xil_defaultlib.glbl -o vio_0_simv\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  ./vio_0_simv $vcs_sim_opts -do simulate.do\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n      create_lib_mappings $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n      create_lib_mappings $2\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Define design library mappings\ncreate_lib_mappings()\n{\n  file=\"synopsys_sim.setup\"\n  if [[ -e $file ]]; then\n    if [[ ($1 == \"\") ]]; then\n      return\n    else\n      rm -rf $file\n    fi\n  fi\n\n  touch $file\n\n  lib_map_path=\"<SPECIFY_COMPILED_LIB_PATH>\"\n  if [[ ($1 != \"\" && -e $1) ]]; then\n    lib_map_path=\"$1\"\n  else\n    echo -e \"ERROR: Compiled simulation library directory path not specified or does not exist (type \"./top.sh -help\" for more information)\\n\"\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    mapping=\"$lib:$sim_lib_dir/$lib\"\n    echo $mapping >> $file\n  done\n\n  if [[ ($lib_map_path != \"\") ]]; then\n    incl_ref=\"OTHERS=$lib_map_path/synopsys_sim.setup\"\n    echo $incl_ref >> $file\n  fi\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(ucli.key vio_0_simv vlogan.log vhdlan.log compile.log elaborate.log simulate.log .vlogansetup.env .vlogansetup.args .vcs_lib_lock scirocco_command.log 64 AN.DB csrc vio_0_simv.daidir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 223}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Cadence Xcelium Parallel Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n# Prerequisite:- To compile and run simulation, you must compile the Xilinx simulation libraries using the\n# 'compile_simlib' TCL command. For more information about this command, run 'compile_simlib -help' in the\n# Vivado Tcl Shell. Once the libraries have been compiled successfully, specify the -lib_map_path switch\n# that points to these libraries and rerun export_simulation. For more information about this switch please\n# type 'export_simulation -help' in the Tcl shell.\n#\n# You can also point to the simulation libraries by either replacing the <SPECIFY_COMPILED_LIB_PATH> in this\n# script with the compiled library directory path or specify this path with the '-lib_map_path' switch when\n# executing this script. Please type 'vio_0.sh -help' for more information.\n#\n# Additional references - 'Xilinx Vivado Design Suite User Guide:Logic simulation (UG900)'\n#\n#*********************************************************************************************************\n\n# Directory path for design sources and include directories (if any) wrt this path\nref_dir=\".\"\n\n# Override directory with 'export_sim_ref_dir' env path value if set in the shell\nif [[ (! -z \"$export_sim_ref_dir\") && ($export_sim_ref_dir != \"\") ]]; then\n  ref_dir=\"$export_sim_ref_dir\"\nfi\n\n# Set the compiled library directory\nref_lib_dir=\".\"\n\n# Command line options\nxrun_opts=\"-64bit -v93 -relax -access +rwc -namemap_mixgen\"\n\n# Design libraries\ndesign_libs=(xil_defaultlib)\n\n# Simulation root library directory\nsim_lib_dir=\"xcelium_lib\"\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  execute\n}\n\n# RUN_STEP: <execute>\nexecute()\n{\n  xrun $xrun_opts \\\n       -reflib \"$ref_lib_dir/unisim:unisim\" \\\n       -reflib \"$ref_lib_dir/unisims_ver:unisims_ver\" \\\n       -reflib \"$ref_lib_dir/secureip:secureip\" \\\n       -reflib \"$ref_lib_dir/unimacro:unimacro\" \\\n       -reflib \"$ref_lib_dir/unimacro_ver:unimacro_ver\" \\\n       -top xil_defaultlib.vio_0 \\\n       -f run.f \\\n       -top glbl \\\n       glbl.v \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl/verilog\" \\\n       +incdir+\"../../../../ip.gen/sources_1/ip/vio_0/hdl\"\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      else\n        ref_lib_dir=$2\n      fi\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n  esac\n\n  create_lib_dir\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Create design library directory paths\ncreate_lib_dir()\n{\n  if [[ -e $sim_lib_dir ]]; then\n    rm -rf $sim_lib_dir\n  fi\n\n  for (( i=0; i<${#design_libs[*]}; i++ )); do\n    lib=\"${design_libs[i]}\"\n    lib_dir=\"$sim_lib_dir/$lib\"\n    if [[ ! -e $lib_dir ]]; then\n      mkdir -p $lib_dir\n    fi\n  done\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xmsim.key xrun.key xrun.log waves.shm xrun.history .simvision xcelium.d xcelium)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n\n  create_lib_dir\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 178}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -f\n#*********************************************************************************************************\n# Vivado (TM) v2020.2 (64-bit)\n#\n# Filename    : vio_0.sh\n# Simulator   : Xilinx Vivado Simulator\n# Description : Simulation script for compiling, elaborating and verifying the project source files.\n#               The script will automatically create the design libraries sub-directories in the run\n#               directory, add the library logical mappings in the simulator setup file, create default\n#               'do/prj' file, execute compilation, elaboration and simulation steps.\n#\n# Generated by Vivado on Tue Dec 14 18:37:42 CST 2021\n# SW Build 3064766 on Wed Nov 18 09:12:47 MST 2020\n#\n# Copyright 1986-2020 Xilinx, Inc. All Rights Reserved. \n#\n# usage: vio_0.sh [-help]\n# usage: vio_0.sh [-lib_map_path]\n# usage: vio_0.sh [-noclean_files]\n# usage: vio_0.sh [-reset_run]\n#\n#*********************************************************************************************************\n\n# Command line options\nxv_boost_lib_path=/tools/xilinx/Vivado/2020.2/tps/boost_1_64_0\nxvlog_opts=\"--relax\"\n\n\n# Script info\necho -e \"vio_0.sh - Script generated by export_simulation (Vivado v2020.2 (64-bit)-id)\\n\"\n\n# Main steps\nrun()\n{\n  check_args $# $1\n  setup $1 $2\n  compile\n  elaborate\n  simulate\n}\n\n# RUN_STEP: <compile>\ncompile()\n{\n  # Compile design files\n  xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log\n\n}\n\n# RUN_STEP: <elaborate>\nelaborate()\n{\n  xelab --relax --debug typical --mt auto -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot vio_0 xil_defaultlib.vio_0 xil_defaultlib.glbl -log elaborate.log\n}\n\n# RUN_STEP: <simulate>\nsimulate()\n{\n  xsim vio_0 -key {Behavioral:sim_1:Functional:vio_0} -tclbatch cmd.tcl -protoinst \"protoinst_files/bd_d2ea.protoinst\" -protoinst \"protoinst_files/bd_a0a4.protoinst\" -protoinst \"protoinst_files/bd_b066.protoinst\" -protoinst \"protoinst_files/bd_8120.protoinst\" -protoinst \"protoinst_files/bd_bf3f.protoinst\" -protoinst \"protoinst_files/bd_a493.protoinst\" -log simulate.log\n}\n\n# STEP: setup\nsetup()\n{\n  case $1 in\n    \"-lib_map_path\" )\n      if [[ ($2 == \"\") ]]; then\n        echo -e \"ERROR: Simulation library directory path not specified (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n        exit 1\n      fi\n     copy_setup_file $2\n    ;;\n    \"-reset_run\" )\n      reset_run\n      echo -e \"INFO: Simulation run files deleted.\\n\"\n      exit 0\n    ;;\n    \"-noclean_files\" )\n      # do not remove previous data\n    ;;\n    * )\n     copy_setup_file $2\n  esac\n\n  # Add any setup/initialization commands here:-\n\n  # <user specific commands>\n\n}\n\n# Copy xsim.ini file\ncopy_setup_file()\n{\n  file=\"xsim.ini\"\n  lib_map_path=\"/tools/xilinx/Vivado/2020.2/data/xsim\"\n  if [[ ($1 != \"\") ]]; then\n    lib_map_path=\"$1\"\n  fi\n  if [[ ($lib_map_path != \"\") ]]; then\n    src_file=\"$lib_map_path/$file\"\n    if [[ -e $src_file ]]; then\n      cp $src_file .\n    fi\n\n    # Map local design libraries to xsim.ini\n    map_local_libs\n\n  fi\n}\n\n# Map local design libraries\nmap_local_libs()\n{\n  updated_mappings=()\n  local_mappings=()\n\n  # Local design libraries\n  local_libs=()\n\n  if [[ 0 == ${#local_libs[@]} ]]; then\n    return\n  fi\n\n  file=\"xsim.ini\"\n  file_backup=\"xsim.ini.bak\"\n\n  if [[ -e $file ]]; then\n    rm -f $file_backup\n    # Create a backup copy of the xsim.ini file\n    cp $file $file_backup\n    # Read libraries from backup file and search in local library collection\n    while read -r line\n    do\n      IN=$line\n      # Split mapping entry with '=' delimiter to fetch library name and mapping\n      read lib_name mapping <<<$(IFS=\"=\"; echo $IN)\n      # If local library found, then construct the local mapping and add to local mapping collection\n      if `echo ${local_libs[@]} | grep -wq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        local_mappings+=(\"$lib_name\")\n      fi\n      # Add to updated library mapping collection\n      updated_mappings+=(\"$line\")\n    done < \"$file_backup\"\n    # Append local libraries not found originally from xsim.ini\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then\n        line=\"$lib_name=xsim.dir/$lib_name\"\n        updated_mappings+=(\"$line\")\n      fi\n    done\n    # Write updated mappings in xsim.ini\n    rm -f $file\n    for (( i=0; i<${#updated_mappings[*]}; i++ )); do\n      lib_name=\"${updated_mappings[i]}\"\n      echo $lib_name >> $file\n    done\n  else\n    for (( i=0; i<${#local_libs[*]}; i++ )); do\n      lib_name=\"${local_libs[i]}\"\n      mapping=\"$lib_name=xsim.dir/$lib_name\"\n      echo $mapping >> $file\n    done\n  fi\n}\n\n# Delete generated data from the previous run\nreset_run()\n{\n  files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb vio_0.wdb xsim.dir)\n  for (( i=0; i<${#files_to_remove[*]}; i++ )); do\n    file=\"${files_to_remove[i]}\"\n    if [[ -e $file ]]; then\n      rm -rf $file\n    fi\n  done\n}\n\n# Check command line arguments\ncheck_args()\n{\n  if [[ ($1 == 1 ) && ($2 != \"-lib_map_path\" && $2 != \"-noclean_files\" && $2 != \"-reset_run\" && $2 != \"-help\" && $2 != \"-h\") ]]; then\n    echo -e \"ERROR: Unknown option specified '$2' (type \\\"./vio_0.sh -help\\\" for more information)\\n\"\n    exit 1\n  fi\n\n  if [[ ($2 == \"-help\" || $2 == \"-h\") ]]; then\n    usage\n  fi\n}\n\n# Script usage\nusage()\n{\n  msg=\"Usage: vio_0.sh [-help]\\n\\\nUsage: vio_0.sh [-lib_map_path]\\n\\\nUsage: vio_0.sh [-reset_run]\\n\\\nUsage: vio_0.sh [-noclean_files]\\n\\n\\\n[-help] -- Print help information for this script\\n\\n\\\n[-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\\n\\\nusing the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\\n\\n\\\n[-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\\n\\\nfrom the previous run will be removed. If you don't want to remove the simulator generated files, use the\\n\\\n-noclean_files switch.\\n\\n\\\n[-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\\n\\n\"\n  echo -e $msg\n  exit 1\n}\n\n# Launch script\nrun $1 $2\n", "num_lines": 213}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Usage help\nfunction usage\n{\n    echo \"usage: aws_build_dcp_from_cl.sh [ [-script <vivado_script>] | [-strategy BASIC | DEFAULT | EXPLORE | TIMING | CONGESTION] [-clock_recipe_a A0 | A1 | A2] [-clock_recipe_b B0 | B1 | B2 | B3 | B4 | B5] [-clock_recipe_c C0 | C1 | C2 | C3] [-uram_option 2 | 3 | 4] [-vdefine macro1,macro2,macro3,.....,macrox] -foreground] [-notify] | [-h] | [-H] | [-help] ]\"\n    echo \" \"\n    echo \"By default the build is run in the background using nohup so that the\"\n    echo \"process will not be terminated if the terminal window is closed.\"\n    echo \"The window can be closed if it is running on your computer and the\"\n    echo \"network connection is lost. All build output will be redirected to a\"\n    echo \"log file called *.nohup.out.\"\n    echo \" \"\n    echo \"The -foreground option runs the build in the foreground. All output will\"\n    echo \"go to the terminal and the build may be terminated if the terminal\"\n    echo \"is closed. This option is useful if you want to wait for the build\"\n    echo \"to complete. This option is safe if the terminal is running on the\"\n    echo \"AWS instance, for example on a GUI desktop on the instance.\"\n}\n\n# Default arguments for script and strategy\nstrategy=DEFAULT\nclock_recipe_a=A0\nclock_recipe_b=B0\nclock_recipe_c=C0\nvivado_script=\"create_dcp_from_cl.tcl\"\nforeground=0\nnotify=0\nignore_memory_requirement=0\nexpected_memory_usage=30000000\nuram_option=2\nvdefine=\"\"\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n  if [[ $debug == 0 ]]; then\n    return\n  fi\n  echo -e \"DEBUG: $1\"\n}\n\nfunction warn_msg {\n  echo -e \"WARNING: $1\"\n}\n\nfunction err_msg {\n  echo -e >&2 \"ERROR: $1\"\n}\n\nfunction get_instance_memory {\n  local mem=$(awk -F\"[: ]+\" '/MemTotal/ {print $2;exit}' /proc/meminfo)\n  echo \"$mem\"\n}\n\n# Parse command-line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -script )               shift\n                                vivado_script=$1\n                                ;;\n        -strategy )             shift\n                                strategy=$1\n                                ;;\n        -clock_recipe_a )       shift\n                                clock_recipe_a=$1\n                                ;;\n        -clock_recipe_b )       shift\n                                clock_recipe_b=$1\n                                ;;\n        -clock_recipe_c )       shift\n                                clock_recipe_c=$1\n                                ;;\n        -uram_option )          shift\n                                uram_option=$1\n                                ;;\n        -vdefine )              shift\n                                vdefine=$1\n                                ;;\n        -foreground )           foreground=1\n                                ;;\n        -notify )               notify=1\n                                ;;\n        -ignore_memory_requirement) ignore_memory_requirement=1\n                                ;;\n        -h | -H | -help )       usage\n                                exit\n                                ;;\n        * )                     usage\n                                exit 1\n    esac\n    shift\ndone\n\n# Check that script exists\nif ! [ -f \"$vivado_script\" ]; then\n  err_msg \"$vivado_script doesn't exist.\"\n  exit 1\nfi\n\n# Check that strategy is valid\nshopt -s extglob\nif [[ $strategy != @(BASIC|DEFAULT|EXPLORE|TIMING|CONGESTION) ]]; then\n  err_msg \"$strategy isn't a valid strategy. Valid strategies are BASIC, DEFAULT, EXPLORE, TIMING and CONGESTION.\"\n  exit 1\nfi\n\n# Check that clock_recipe_a is valid\nshopt -s extglob\nif [[ $clock_recipe_a != @(A0|A1|A2) ]]; then\n  err_msg \"$clock_recipe_a isn't a valid Clock Group A recipe. Valid Clock Group A recipes are A0, A1, and A2.\"\n  exit 1\nfi\n\n# Check that clock_recipe_b is valid\nshopt -s extglob\nif [[ $clock_recipe_b != @(B0|B1|B2|B3|B4|B5) ]]; then\n  err_msg \"$clock_recipe_b isn't a valid Clock Group B recipe. Valid Clock Group B recipes are B0, B1, B2, B3, B4, and B5.\"\n  exit 1\nfi\n\n# Check that clock_recipe_c is valid\nshopt -s extglob\nif [[ $clock_recipe_c != @(C0|C1|C2|C3) ]]; then\n  err_msg \"$clock_recipe_c isn't a valid Clock Group C recipe. Valid Clock Group C recipes are C0, C1, C2, and C3.\"\n  exit 1\nfi\n\n# Check that uram_option is valid\nshopt -s extglob\nif [[ $uram_option != @(2|3|4) ]]; then\n  err_msg \"$uram_option isn't a valid URAM option. Valid URAM options are 2 (50%), 3 (75%), and 4 (100%).\"\n  exit 1\nfi\n# process vdefines\ninfo_msg \"VDEFINE is : $vdefine\"\nshopt -s extglob\nIFS=',' read -r -a vdefine_array <<< \"$vdefine\"\n\nopt_vdefine=\"\"\n\nfor index in \"${!vdefine_array[@]}\"\ndo \n echo \"$index ${vdefine_array[index]}\"\n opt_vdefine+=\" -verilog_define \"\n opt_vdefine+=${vdefine_array[index]}\ndone\necho \"$opt_vdefine\"\nif [ $expected_memory_usage -gt `get_instance_memory` ]; then\n\n    output_message=\"YOUR INSTANCE has less memory than is necessary for certain builds. This means that your builds will take longer than expected. \\nTo change to an instance type with more memory, please check our instance resize guide: http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-resize.html\"\n\n  if [[ $ignore_memory_requirement == 0 ]]; then\n      err_msg \"$output_message\"\n      err_msg \"To ignore this memory requirement, run this script again with -ignore_memory_requirement as an argument.\"\n      exit 1\n  else\n      warn_msg \"$output_message\"\n  fi\nfi\n\ninfo_msg \"Starting the design checkpoint build process\"\ninfo_msg \"Checking for proper environment variables and build directories\"\n\nif ! [ $HDK_SHELL_DIR ]\nthen\n\terr_msg \"HDK_SHELL_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ $CL_DIR ]\nthen\n\terr_msg \"CL_DIR environment variable is not set. Set CL_DIR to a valid directory.\"\n\texit 1\nfi\n\nif ! [ $HDK_DIR ]\nthen\n\terr_msg \"HDK_DIR environment variable is not set, try running hdk_setup.sh script from the root directory of AWS FPGA repository.\"\n\texit 1\nfi\n\nif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\nthen\n\tinfo_msg \"prepare_build_env.sh script is not eXecutable, trying to apply chmod +x\"\n\tchmod +x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\tif ! [ -x $HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh ]\n\tthen\n\t\terr_msg \"Failed to change prepare_build_environment.sh to eXecutable, aborting!\"\n\t\texit 1\n\tfi\nfi\n\n$HDK_SHELL_DIR/build/scripts/prepare_build_environment.sh\n\nif ! [[ $? -eq 0 ]]\nthen\n\terr_msg \"Missing environment variable or unable to create the needed build directories, aborting!\"\n\texit 1\nfi\n\n# Use timestamp for logs and output files\ntimestamp=$(date +\"%y_%m_%d-%H%M%S\") \nlogname=$timestamp.vivado.log\nln -s -f $logname last_log\n\ninfo_msg \"Environment variables and directories are present. Checking for Vivado installation.\"\n\n# Before going too far make sure Vivado is available\nvivado -version >/dev/null 2>&1 || { err_msg \"Please install/enable Vivado.\" ; return 1; }\n\n# Get the HDK Version\nhdk_version=$(grep 'HDK_VERSION' $HDK_DIR/hdk_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the Shell Version\nshell_version=$(grep 'SHELL_VERSION' $HDK_SHELL_DIR/shell_version.txt | sed 's/=/ /g' | awk '{print $2}')\n\n# Get the PCIe Device & Vendor ID from ID0\nid0_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID0' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\ndevice_id=\"0x${id0_version:0:4}\";\nvendor_id=\"0x${id0_version:4:4}\";\n\n# Get the PCIe Subsystem & Subsystem Vendor ID from ID1\nid1_version=$(grep -v '^\\//' $CL_DIR/design/cl_id_defines.vh | grep 'CL_SH_ID1' | grep 'define' | sed 's/_//g' | awk -F \"h\" '{print $2}')\nsubsystem_id=\"0x${id1_version:0:4}\";\nsubsystem_vendor_id=\"0x${id1_version:4:4}\";\n\n# Run vivado\ncmd=\"vivado -mode batch -nojournal -log $logname -source $vivado_script -tclargs $timestamp $strategy $hdk_version $shell_version $device_id $vendor_id $subsystem_id $subsystem_vendor_id $clock_recipe_a $clock_recipe_b $clock_recipe_c $uram_option $notify $opt_vdefine\"\nif [[ \"$foreground\" == \"0\" ]]; then\n  nohup $cmd > $timestamp.nohup.out 2>&1 &\n  \n  info_msg \"Build through Vivado is running as background process, this may take few hours.\"\n  info_msg \"Output is being redirected to $timestamp.nohup.out\"\n  info_msg \"If you have set your EMAIL environment variable and -notify is specified, you will receive a notification when complete.\"\n  info_msg \"  (See \\$HDK_DIR/cl/examples/README.md for details)\"\nelse\n  info_msg \"Build through Vivado is running in the foreground, this may take a few hours.\"\n  info_msg \"The build may be terminated if the network connection to this terminal window is lost.\"\n  $cmd\nfi\n", "num_lines": 249}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nif [[ \":$HDK_COMMON_DIR\" == \":\" ]]; then\n  echo \"ERROR: HDK_COMMON_DIR not set. Source hdk_setup.sh first.\"\n  exit 2\nfi\n\nif [[ \":$VIVADO_VER\" == \":\" ]]; then\n  echo \"ERROR: VIVADO_VER not set. Source hdk_setup.sh first.\"\n  exit 2\nfi\n\nmodels_dir=$1\nif [[ \":$models_dir\" == \":\" ]]; then\n  models_dir=$HDK_COMMON_DIR/verif/models\nfi\n\nif [ ! -e $models_dir ]; then\n  mkdir -p $models_dir\nfi\n\nlockfile_filename=$models_dir/build.lock\n\n# Prevent multiple users from building in the same directory.\n# Set the number of retries to 0 so that we will just fail\n# and let the other process complete the build.\nif [ -e $lockfile_filename ]; then\n  echo \"ERROR: $lockfile_filename exists\"\n  echo \"ERROR: Another process is already building the models.\"\n  exit 2\nelse\n  touch $lockfile_filename\nfi\n\necho \"$VIVADO_VER\" > $models_dir/.vivado_version\n\nif ! vivado -mode batch -source $HDK_COMMON_DIR/verif/scripts/init.tcl; then\n  rm -f $lockfile_filename\n  exit 2\nfi\n\nddr4_imports_dir=tmp/tmp_ddr_ex/ddr4_core_ex/imports\nddr4_model_dir=$models_dir/ddr4_model\nddr4_rdimm_model_dir=$models_dir/ddr4_rdimm_wrapper\nif [ ! -d $ddr4_model_dir ]; then mkdir -p $ddr4_model_dir; fi\nif [ ! -d $ddr4_rdimm_model_dir ]; then mkdir -p $ddr4_rdimm_model_dir; fi\necho \"Copying files to $ddr4_model_dir\"\ncp $ddr4_imports_dir/arch_defines.v              $ddr4_model_dir/\ncp $ddr4_imports_dir/arch_package.sv              $ddr4_model_dir/\ncp $ddr4_imports_dir/ddr4_model.sv               $ddr4_model_dir/\ncp $ddr4_imports_dir/ddr4_sdram_model_wrapper.sv $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm_interface.sv           $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm_subtest.vh             $ddr4_model_dir/\n#cp $ddr4_imports_dir/dimm.vh                     $ddr4_model_dir/\ncp $ddr4_imports_dir/interface.sv                $ddr4_model_dir/\ncp $ddr4_imports_dir/MemoryArray.sv              $ddr4_model_dir/\ncp $ddr4_imports_dir/proj_package.sv             $ddr4_model_dir/\ncp $ddr4_imports_dir/StateTableCore.sv           $ddr4_model_dir/\ncp $ddr4_imports_dir/StateTable.sv               $ddr4_model_dir/\n#cp $ddr4_imports_dir/subtest.vh                  $ddr4_model_dir/\ncp $ddr4_imports_dir/timing_tasks.sv             $ddr4_model_dir/\n\necho \"Copying files to $ddr4_rdimm_model_dir\"\ncp $ddr4_imports_dir/ddr4_bi_delay.sv            $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_db_delay_model.sv      $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_db_dly_dir.sv          $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_dimm.sv                $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_dir_detect.sv          $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rank.sv                $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rcd_model.sv           $ddr4_rdimm_model_dir/\ncp $ddr4_imports_dir/ddr4_rdimm_wrapper.sv       $ddr4_rdimm_model_dir/\n\n\necho \"patching ddr4_rdimm_wrapper.sv file\"\nsed -i s/_4G/_8G/g  $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\nsed -i -e 's/\\/\\/\\LRDIMM/\\: LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\nsed -i -e 's/\\/\\/\\!LRDIMM/\\: NOT_LRDIMM/g' $ddr4_rdimm_model_dir/ddr4_rdimm_wrapper.sv\n\necho \"patching ddr4_sdram_model_wrapper.sv file\"\nsed -i '/`include \"arch_package.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"proj_package.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"interface.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\nsed -i '/`include \"ddr4_model.sv\"/d' $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\n\necho \"\\`include \\\"arch_package.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"proj_package.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"interface.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\necho \"\\`include \\\"ddr4_model.sv\\\"\" >> $ddr4_model_dir/ddr4_sdram_model_wrapper.sv\n\necho \"patching interface.sv file\"\nsed -i '/`include \"ddr4_sdram_model_wrapper.sv\"/d' $ddr4_model_dir/interface.sv\nsed -i '2i`ifndef DDR4_INT_DEF' $ddr4_model_dir/interface.sv\nsed -i '3i  `define DDR4_INT_DEF' $ddr4_model_dir/interface.sv\nsed -i '$a`endif' $ddr4_model_dir/interface.sv\n\necho \"patching proj_package.sv file\"\nsed -i '/`include \"ddr4_sdram_model_wrapper.sv\"/d' $ddr4_model_dir/proj_package.sv\nsed -i '2i`ifndef DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv\nsed -i '3i  `define DDR4_PROJ_PKG' $ddr4_model_dir/proj_package.sv\nsed -i '$a`endif' $ddr4_model_dir/proj_package.sv\n\necho \"patching ddr4_model.sv file\"\nsed -i '1i`ifndef DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv\nsed -i '2i `define DDR4_MODEL_DEF' $ddr4_model_dir/ddr4_model.sv\nsed -i '$a`endif' $ddr4_model_dir/ddr4_model.sv\n\nrm -f $lockfile_filename\n", "num_lines": 113}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Exit on any error\nset -e\n# Process command line args\n\nwhile [[ $# -gt 1 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    --test-name)\n        test_name=\"$2\"\n        shift\n        shift\n        ;;\n    --test-dir)\n        test_dir=\"$2\"\n        shift\n        shift\n        ;;\n    --simulator)\n        simulator=\"$2\"\n        shift\n        shift\n        ;;\n    --batch)\n        batch=\"$2\"\n        shift\n        shift\n        ;;\n    --vivado-version)\n      vivado_version=\"$2\"\n        shift\n        shift\n        ;;\n    --test-type)\n        test_type=\"$2\"\n        shift\n        shift\n        ;;\n    *)\n        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n        exit 1\n        ;;\nesac\ndone\n\nvivado_version=${vivado_version//./_}\nif [ $batch == \"TRUE\" ]; then\n# COMMAND=\"batch_submit.py -q vcs-lo --jd Cad-centos7_2 --jn github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} --wait --echo -c make\"\n# COMMAND=\"sbatch -c 1 --mem 64GB -p regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net -W -o ${test_name}_${test_type}_${simulator}.stdout.sim.log -e ${test_name}_${test_type}_${simulator}.stderr.sim.log sbatch_wrap.sh make\"\nCOMMAND=\"srun -c 1 --mem 64GB --time 160 -p regress -J github_regress_${test_name}_${test_type}_${vivado_version}_${simulator} -L VCSMXRunTime_Net make\"\n\nelse\nCOMMAND=\"make\"\nfi\n\necho \"$COMMAND\"\n\n# Run the test\npushd $test_dir\ncase \"$simulator\" in\n\tvcs)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" VCS=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 VCS=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 VCS=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 VCS=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 VCS=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" VCS=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" VCS=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\ties)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" IES=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 IES=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 IES=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 IES=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 IES=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" IES=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" IES=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\tquesta)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\" QUESTA=1\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10 QUESTA=1\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0 QUESTA=1\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1 QUESTA=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\" QUESTA=1\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\" QUESTA=1\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\n\t*)\n\tcase \"$test_type\" in\n\t    sv)\n\t       $COMMAND TEST=\"$test_name\"\n\t       ;;\n\t    sv_fast)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1\n\t        ;;\n\t    sv_fast_ecc_direct)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_DIRECT=1 ECC_ADDR_HI=1000 ECC_ADDR_LO=0\n\t        ;;\n\t    sv_fast_ecc_rnd)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100\n\t        ;;\n\t    sv_fast_ecc_rnd_100)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=100\n\t        ;;\n\t    sv_fast_ecc_rnd_50)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=50\n\t        ;;\n\t    sv_fast_ecc_rnd_10)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=10\n\t        ;;\n\t    sv_fast_ecc_rnd_0)\n\t       $COMMAND TEST=\"$test_name\" AXI_MEMORY_MODEL=1 ECC_RAND=1 RND_ECC_WEIGHT=0\n\t        ;;\n\t    sv_ddr_bkdr)\n\t       $COMMAND TEST=\"$test_name\" DDR_BKDR=1\n\t        ;;\n\t    vhdl)\n\t       $COMMAND TEST=\"$test_name\"\n\t        ;;\n\t    c)\n\t       $COMMAND C_TEST=\"$test_name\"\n\t        ;;\n\t    *)\n\t        echo -e >&2 \"ERROR: Invalid option: $1\\n\"\n\t        exit 1\n\t        ;;\n\tesac\n\t;;\nesac\n# Exit out of the test dir\npopd\n", "num_lines": 236}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nscript=${BASH_SOURCE[0]}\nif [ $script != $0 ]; then\n  echo \"ERROR: You must execute this script instead of sourcing!\"\n  return\nfi\n\n\nif [ -z \"$SDK_DIR\" ]; then\n    echo \"Error: SDK_DIR environment variable is not set.  Please use 'source sdk_setup.sh' from the aws-fpga directory.\"\n    exit 1\nfi\n\ngcc --version &> /dev/null\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: gcc is not installed.\"\n    echo \"    You can install gcc and other useful development tools by using: sudo yum groupinstall \\\"Development tools\\\"\"\n    exit $RET \nfi\n\nsudo -V &> /dev/null\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: sudo is not in path or not installed. Driver installations will fail \"\n    echo \"    To install drivers please add sudo to your path or install sudo by running \\\"yum install sudo\\\" as root \"\n    #exit $RET \nfi\n\n\nSDK_USERSPACE_DIR=$SDK_DIR/userspace\n\n# Build the Amazon FPGA Image (AFI) Management Tools\n(cd $SDK_USERSPACE_DIR && ./mkall_fpga_mgmt_tools.sh)\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: mkall_fpga_mgmt_tools.sh returned $RET\"\n    exit $RET\nfi\necho \"Build complete.\"\n\n# Install the Amazon FPGA Image (AFI) Management Tools\n$SDK_USERSPACE_DIR/install_fpga_mgmt_tools.sh\nRET=$?\nif [ $RET != 0 ]; then\n    echo \"Error: install_fpga_mgmt_tools.sh returned $RET\"\n    exit $RET\nfi\n# Add udev rules if asked for non root access\nif allow_non_root ; then\n\t  sudo $SDK_USERSPACE_DIR/add_udev_rules.sh\n\t  RET=$?\n\t  if [ $RET != 0 ]; then\n\t\t\t\t echo \"Error: $SDK_USERSPACE_DIR/add_udev_rules.sh returned $RET\"\n\t\t\t\t exit $RET\n\t  fi\nfi\n\necho \"Done with SDK install.\"\n", "num_lines": 75}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\ncd $SDK_DIR/apps/byte_swapper\nflask run --host=0.0.0.0 > flask_server.log 2>&1 &\necho \"CHILDPID $!\"\ncat flask_server.log\n", "num_lines": 11}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/bash -ex\n\n# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\ncd $SDK_DIR/tests\nrm -rf fio_dma_tools_original\naws s3 cp s3://aws-fpga-jenkins-testing/fio_dma_tools/ fio_dma_tools_original/ --recursive\ncd fio_dma_tools_original\nrm -rf xdma_v2017_1/\ncd fio\nchmod +x configure\n./configure\nmake\nmv fio ../scripts\ncd ..\nrm -rf fio\ncd ..\naws s3 rm s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive\naws s3 cp fio_dma_tools_original/ s3://aws-fpga-jenkins-testing/fio_dma_tools_compiled --recursive\nrm -rf fio_dma_tools_original/\n", "num_lines": 24}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nsource /tmp/sdk_root_env.exp\nset +x\nrm -f /tmp/sdk_root_env.exp\n\nmkdir -p /opt/aws/bin\n\nDBDFs=`lspci -Dn |  grep -Ew \"1d0f:1042|1d0f:1041\" | awk '{print $1}' | sed ':x;N;$!bx;s/\\n/ /g'`\n\n\nif [[ $AWS_FPGA_SDK_OTHERS ]]; then\n# Allow all users\n\n  # Make a script that will be run to change permissions everytime\n  # udev rule for the DBDF is matched\n  echo \"Installing permission fix script for udev\"\n  cat >/opt/aws/bin/change-fpga-perm.sh<<EF\n#!/bin/bash\nset -x\nsetperm () {\n  chmod g=u \\$1\n  chmod a=u \\$1\n}\nsetfpgaperm () {\n  for f in \\$1/*; do\n    setperm \\$f;\n  done\n}\n\ndevicePath=/sys/bus/pci/devices/\\$1\ngrep -q \"0x058000\" \\$devicePath/class && setfpgaperm \"\\$devicePath\"\nsetperm /sys/bus/pci/rescan all\nEF\n\necho \"Adding udev rule: 9999-presistent-fpga.rules\"\ncat >/etc/udev/rules.d/9999-presistent-fpga.rules<<EF\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1041\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1041\", ACTION==\"add\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1042\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nATTR{vendor}==\"0x1d0f\", ATTR{device}==\"0x1042\", ACTION==\"add\", RUN+=\"/opt/aws/bin/change-fpga-perm.sh %k\"\nEF\n\nelse\n# Allow group only\n\n  echo \"Creating group ${AWS_FPGA_SDK_GROUP}\"\n  getent group ${AWS_FPGA_SDK_GROUP} >/dev/null 2>&1\n  if [[ $? -eq 0 ]] ; then\n    if [ -z ${AWS_FPGA_SDK_OVERRIDE_GROUP} ] ; then\n      echo \"Group ${AWS_FPGA_SDK_GROUP} already exists. Please export a non existent group name  to AWS_FPGA_SDK_GROUP or export AWS_FPGA_SDK_OVERRIDE_GROUP=y\"\n      exit 1\n    fi\n    echo \"${AWS_FPGA_SDK_GROUP} already exists, will grant FPGA resource access to this group\"\n  else\n    groupadd  ${AWS_FPGA_SDK_GROUP}\n    if [[ $? -ne 0 ]] ; then\n      echo \"Could not group ${AWS_FPGA_SDK_GROUP}\"\n      exit 1\n    fi\n  fi\n\n  echo \"Adding user ${SDK_NON_ROOT_USER} into group ${AWS_FPGA_SDK_GROUP}\"\n  getent group ${AWS_FPGA_SDK_GROUP} | grep -qw ${SDK_NON_ROOT_USER}\n  if [[ $? -eq 0 ]] ; then\n    echo \"${SDK_NON_ROOT_USER} is already in group ${AWS_FPGA_SDK_GROUP}\"\n  else\n    usermod -a -G ${AWS_FPGA_SDK_GROUP} ${SDK_NON_ROOT_USER}\n    if [[ $? -ne 0 ]] ; then\n      echo \"Could not add user ${SDK_NON_ROOT_USER} to group ${AWS_FPGA_SDK_GROUP}\"\n      exit 1\n    fi\n  fi\n\n  # Fail on any unsucessful command\n  set -e\n  # Make a script that will be run to change permissions everytime\n  # udev rule for the DBDF is matched\n  echo \"Installing permission fix script for udev\"\n  cat >/opt/aws/bin/change-fpga-perm.sh<<EF\n#!/bin/bash\nset -x\nsetperm () {\n  chmod g=u \\$1\n  if [[ x\\$2 != \"x\" ]] ; then\n    chmod a=u \\$1\n  fi\n}\nsetgrp() {\n  chown root:${AWS_FPGA_SDK_GROUP} \\$1\n}\nsetfpgaperm () {\n  for f in \\$1/*; do\n    setperm \\$f;\n    setgrp \\$f\n  done\n}\n\ndevicePath=/sys/bus/pci/devices/\\$1\ngrep -q \"0x058000\" \\$devicePath/class && setfpgaperm \"\\$devicePath\"\nsetperm /sys/bus/pci/rescan all\nEF\n\necho \"Adding udev rule: 9999-presistent-fpga.rules\"\n\n  rm -f /tmp/9999-presistent-fpga.rules\n  for d in $DBDFs ; do\n    echo \"KERNEL==\\\"*${d}*\\\", RUN+=\\\"/opt/aws/bin/change-fpga-perm.sh '${d}'\\\"\" >> /tmp/9999-presistent-fpga.rules\n  done\n  for d in $DBDFs ; do\n    echo \"KERNEL==\\\"*${d}*\\\", ACTION==\\\"add\\\", RUN+=\\\"/opt/aws/bin/change-fpga-perm.sh '${d}'\\\"\" >> /tmp/9999-presistent-fpga.rules\n  done\n  echo \"Adding udev rule: 9999-presistent-fpga.rules\"\n  cp /tmp/9999-presistent-fpga.rules /etc/udev/rules.d/9999-presistent-fpga.rules\nfi\n\nchmod 544 /opt/aws/bin/change-fpga-perm.sh\n\n## Test the rules for any issues\nfor d in  $DBDFs ; do\nudevadm test --action=\"add\" /sys/bus/pci/devices/${d} >/dev/null 2>&1\ndone\n#\n## Make udev daemon aware of rule changes\nudevadm control --reload\n#\n## Trigger the change for rules to avoid a reboot\nfor d in  $DBDFs ; do\nudevadm trigger --action=\"add\"  /sys/bus/pci/devices/${d}\ndone\n", "num_lines": 147}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\nif [ -z \"$SDK_DIR\" ]; then\n\techo \"Error: SDK_DIR environment variable is not set.  Please 'source sdk_setup.sh' from the aws-fpga directory first.\"\n\texit 1\nfi\n\nif [ $EUID != 0 ]; then\n\techo \"\"\n\techo \"Root privileges are required to install. You may be asked for your password...\"\n\tsudo -E \"$0\" \"$@\"\n\texit $?\nelse\n\techo \"Executing as root...\"\n\techo \"\"\nfi\n\nBASE_PATH=/usr/local\n\n# check to see if the /usr/local/bin is on the sudo PATH (is secure_path enabled?)\necho $PATH | grep \"$BASE_PATH\"\nret=$?\nif [ $ret -ne \"0\" ]; then\n\tBASE_PATH=/usr\nfi\n\nSDK_MGMT_DIR=$SDK_DIR/userspace\nAFI_MGMT_TOOLS_SRC_DIR=$SDK_MGMT_DIR/fpga_mgmt_tools/src\nAFI_MGMT_TOOLS_DST_DIR=$BASE_PATH/bin\nAFI_MGMT_TOOLS_LIB_DIR=$SDK_MGMT_DIR/lib/so\n\n# in order to accommodate different distributions, check several options for the user-libraries directory\nif [ -d \"/usr/local/lib64\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/local/lib64\nelif [ -d \"/usr/local/lib\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/local/lib\nelif [ -d \"/usr/lib64\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/lib64\nelif [ -d \"/usr/lib\" ]; then\n\tAFI_MGMT_LIBS_DST_DIR=/usr/lib\nelse\n\techo \"Error: No directory for installing libraries.\"\n\texit 1\nfi\n\nif [ ! -d \"$AFI_MGMT_TOOLS_DST_DIR\" ]; then\n\tmkdir -p $AFI_MGMT_TOOLS_DST_DIR\nfi\n\n# /usr/bin requires sudo permissions \necho \"AWS FPGA: Copying Amazon FPGA Image (AFI) Management Tools to $AFI_MGMT_TOOLS_DST_DIR\"\ncp -f $AFI_MGMT_TOOLS_SRC_DIR/fpga-* $AFI_MGMT_TOOLS_DST_DIR\ncp -f $AFI_MGMT_TOOLS_LIB_DIR/libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR\nln -sf libfpga_mgmt.so.1 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so\nln -sf libfpga_mgmt.so.1.0.0 $AFI_MGMT_LIBS_DST_DIR/libfpga_mgmt.so.1\n\nsource /tmp/sdk_root_env.exp\nif allow_non_root ; then\n  chmod u+s $AFI_MGMT_TOOLS_DST_DIR/fpga-local-cmd\nfi\n\necho \"AWS FPGA: Installing shared library to $AFI_MGMT_LIBS_DST_DIR\"\nld_conf_change=\"0\"\nwhile true; do\n\t# update the dynamic linker cache\n\tldconfig\n\n\t# confirm that the linker cache stored the library we want\n\tldconfig -p | grep \"libfpga_mgmt\\.so\\.1\"\n\tret=$?\n\tif [ $ret -ne \"0\" ]; then\n\t\tif [ \"$ld_conf_change\" -eq \"1\" ]; then\n\t\t\techo \"Error: Unable to automatically install the fpga_mgmt library.\"\n\t\t\texit 1\n\t\tfi\n\t\tld_conf_change=\"1\"\n\t\techo \"$AFI_MGMT_LIBS_DST_DIR\" > /etc/ld.so.conf.d/fpga_mgmt-x86_64.conf\n\telse\n\t\tbreak\n\tfi\ndone\necho \"AWS FPGA: Installing python bindings for FPGA management library\"\ncat>/tmp/mod_search_path<<EF\nrm -f /tmp/py_install_paths\nif [[ \\$? -ne 0 ]] ; then\n\techo \"Could not install python modules\"\n\texit 1\nfi\nfor i in 2 3 ; do\n\twhich python\\$i >/dev/null 2>&1 || continue\n\tpython\\$i -c \"import sys\nprint(sys.path)\n\" | tr , '\\n' | tr -d \"'[]\" | grep -E \"64.*site-packages$\" >> /tmp/py_install_paths\ndone\nEF\nbash /tmp/mod_search_path\nwhile read -t 2 site_package ; do\n\tPYMODULES=\"fpga_dma.py fpga_mgmt.py fpga_pci.py\"\n\tfor mod in $PYMODULES ; do\n\t\tsudo sed -e \"s,PY_BIND_AFI_MGMT_LIBS_DST_DIR,$AFI_MGMT_LIBS_DST_DIR,g\" $SDK_DIR/userspace/python_bindings/$mod > $site_package/$mod\n\t\tif [[ $? -ne 0 ]] ; then\n\t\t\techo \"Could not install $mod\"\n\t\t\texit 1\n\t\tfi\n\t\techo \"Installed $site_package/$mod\"\n\tdone\ndone < /tmp/py_install_paths\necho \"AWS FPGA: Done with Amazon FPGA Image (AFI) Management Tools install.\"\n", "num_lines": 125}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Build script for the Amazon FPGA Image Management Tools and libraries.\n\nTOP=`pwd` \n\nLOGLEVEL=$1\nif [ -z \"$LOGLEVEL\" ]; then\n\tCONFIG_LOGLEVEL=0\nelse\n\tCONFIG_LOGLEVEL=$LOGLEVEL\nfi\n\nif allow_non_root ; then\n       OPT=\"$OPT -DFPGA_ALLOW_NON_ROOT=1\"\nfi\n\n#\n# gcc optimizations\n#OPT=\"-O3 -fno-strict-aliasing\"\n\n#\n# The max number of FPGA BARs that may be attached,\n# e.g. (FPGA_SLOT_MAX * FPGA_PF_MAX * FPGA_BAR_PER_PF_MAX) is the upper bound.\n#\nFPGA_PCI_BARS_DFLT=64\nFPGA_PCI_BARS_MAX=$2\nif [ -z \"$FPGA_PCI_BARS_MAX\" ]; then\n\tFPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_DFLT\nelse\n\tFPGA_PCI_BARS_MAX=$FPGA_PCI_BARS_MAX\nfi\n\n# get the HDK/SDK version number\nsource $TOP/../../hdk/hdk_version.txt\n\nfunction build_exec {\n\tcd $TOP/$BUILD_DIR \n\techo \"Entering $TOP/$BUILD_DIR\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"could not cd to $TOP/$BUILD_DIR\"\n\t\texit 1\n\tfi\n\tmake clean\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make clean failed\"\n\t\texit 1\n\tfi\n\tmake OPT=\"$OPT -DCONFIG_LOGLEVEL=\"$CONFIG_LOGLEVEL\" -DFPGA_PCI_BARS_MAX=\"$FPGA_PCI_BARS_MAX\" -DCLI_VERSION='\\\"$HDK_VERSION\\\"'\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make failed\"\n\t\texit 1\n\tfi\n\tcd $TOP\n}\n\n\nBUILD_DIR=\"utils\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_pci\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_dma\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_mgmt\"\nbuild_exec\n\nBUILD_DIR=\"fpga_mgmt_tools/src\"\nbuild_exec\n", "num_lines": 90}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright 2015-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Build script for the Amazon FPGA Image Management Tools and associated libraries. \n\nTOP=`pwd` \n\nLOGLEVEL=$1\nif [ -z \"$LOGLEVEL\" ]; then\n\tCONFIG_LOGLEVEL=3\nelse\n\tCONFIG_LOGLEVEL=$LOGLEVEL\nfi\n\nfunction build_exec {\n\tcd $TOP/$BUILD_DIR \n\techo \"Entering $TOP/$BUILD_DIR\"\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"could not cd to $TOP/$BUILD_DIR\"\n\t\texit 1\n\tfi\n\tmake clean\n\tRET=$?\n\tif [ $RET -ne 0 ]; then\n\t\techo \"make clean failed\"\n\t\texit 1\n\tfi\n\tcd $TOP\n}\n\n\nBUILD_DIR=\"utils\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_pci\"\nbuild_exec\n\nBUILD_DIR=\"fpga_libs/fpga_mgmt\"\nbuild_exec\n\nBUILD_DIR=\"fpga_mgmt_tools/src\"\nbuild_exec\n", "num_lines": 58}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\ninfo_msg \"Setting up environment variables\"\n\n# Make sure that AWS_FPGA_REPO_DIR is set to the location of this script.\nif [[ \":$AWS_FPGA_REPO_DIR\" == ':' ]]; then\n  debug_msg \"AWS_FPGA_REPO_DIR not set so setting to $script_dir\"\n  export AWS_FPGA_REPO_DIR=$script_dir\nelif [[ $AWS_FPGA_REPO_DIR != $script_dir ]]; then\n  info_msg \"Changing AWS_FPGA_REPO_DIR from $AWS_FPGA_REPO_DIR to $script_dir\"\n  export AWS_FPGA_REPO_DIR=$script_dir\nelse\n  debug_msg \"AWS_FPGA_REPO_DIR=$AWS_FPGA_REPO_DIR\"\nfi\n\n# HDK\n# Clear environment variables\nunset HDK_DIR\nunset HDK_COMMON_DIR\nunset HDK_SHELL_DIR\nunset HDK_SHELL_DESIGN_DIR\n\nexport -f allow_non_root\nexport -f allow_others\n\nif  allow_non_root || allow_others ; then\n\texport AWS_FPGA_SDK_GROUP=${AWS_FPGA_SDK_GROUP:-\"fpgauser\"}\n\texport SDK_NON_ROOT_USER=$(whoami)\n  info_msg \"Allowing group ${AWS_FPGA_SDK_GROUP} access to FPGA management tools and resources\"\nfi\n\n\nexport HDK_DIR=$AWS_FPGA_REPO_DIR/hdk\n\n# The next variable should not be modified and should always point to the /common directory under HDK_DIR\nexport HDK_COMMON_DIR=$HDK_DIR/common\n\n# Point to the latest version of AWS shell\nexport HDK_SHELL_DIR=$(readlink -f $HDK_COMMON_DIR/shell_stable)\n\n# Set the common shell design dir\nexport HDK_SHELL_DESIGN_DIR=$HDK_SHELL_DIR/design\n\n# SDK\nunset SDK_DIR\n\nexport SDK_DIR=$AWS_FPGA_REPO_DIR/sdk\n\n# SDACCEL\n# Setup Location of SDACCEL_DIR\nexport SDACCEL_DIR=$AWS_FPGA_REPO_DIR/SDAccel\n#  Vitis\n# Setup Location of VITIS_DIR\nexport VITIS_DIR=$AWS_FPGA_REPO_DIR/Vitis\n\n# PYTHONPATH\n# Update PYTHONPATH with libraries used for unit testing\npython_lib=$AWS_FPGA_REPO_DIR/shared/lib\nPYTHONPATH=$python_lib:$PYTHONPATH\nexport PYTHONPATH\n\n# PATH Changes\n\nexport PATH=$(echo $PATH | sed -e 's/\\(^\\|:\\)[^:]\\+\\/shared\\/bin\\/scripts\\(:\\|$\\)/:/g; s/^://; s/:$//')\nPATH=$AWS_FPGA_REPO_DIR/shared/bin/scripts:$PATH\n\n# Enable xilinx licensing\nexport XILINX_ENABLE_AWS_WHITELIST=095707098027\n", "num_lines": 72}
{"repo_name": "aws-fpga-f1-u200", "repo_creator": "aws", "programming_language": "Shell", "code": "# Amazon FPGA Hardware Development Kit\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfunction info_msg {\n  echo -e \"INFO: $1\"\n}\n\nfunction debug_msg {\n    if [[ $debug == 0 ]]; then\n        return\n    fi\n    echo -e \"DEBUG: $1\"\n}\n\nfunction err_msg {\n    echo -e >&2 \"ERROR: $1\"\n}\n\nfunction warn_msg {\n    echo -e \"WARNING: $1\"\n}\n\nfunction is_myvivado_set {\n    if env | grep -q ^MYVIVADO=\n    then\n        true\n    else\n        false\n    fi\n}\n\nfunction is_xilinx_path_set {\n    if env | grep -q ^XILINX_PATH\n    then\n        true\n    else\n        false\n    fi\n}\n\n# Function to check whether a command exists.\nexists() {\n    if command -v $1 >/dev/null 2>&1\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction get_base_vivado_version {\n    local  __resultvar=$1\n\n    if is_myvivado_set\n    then\n\n        local MYVIVADO_ENV_VAR_BACKUP=$MYVIVADO\n\n        unset MYVIVADO\n        local __vivado_version=$(get_vivado_version)\n        export MYVIVADO=$MYVIVADO_ENV_VAR_BACKUP\n    elif is_xilinx_path_set\n    then\n        local XILINX_PATH_ENV_VAR_BACKUP=$XILINX_PATH\n        unset XILINX_PATH\n        local __vivado_version=$(get_vivado_version)\n        export XILINX_PATH=$XILINX_PATH_ENV_VAR_BACKUP\n    else\n        local __vivado_version=$(get_vivado_version)\n    fi\n\n    if [[ \"$__resultvar\" ]]; then\n        eval $__resultvar=\"'$__vivado_version'\"\n    else\n        echo \"$__vivado_version\"\n    fi\n\n}\n\nfunction munge_myvivado_var {\n    if [[ ! -z $1 ]]; then\n        if ! echo \"$MYVIVADO\" | /bin/grep -Eq \"(^|:)$1($|:)\" ; then\n            if [ \"$2\" = \"after\" ] ; then\n                MYVIVADO=\"$MYVIVADO:$1\"\n            else\n                MYVIVADO=\"$1:$MYVIVADO\"\n            fi\n        fi\n        export MYVIVADO\n    fi\n}\n\nfunction get_vivado_version {\n    local __resultvar=$1\n\n    local __vivado_version=`vivado -version | grep Vivado | head -1`\n\n    if [[ \"$__resultvar\" ]]; then\n        eval $__resultvar=\"'__$vivado_version'\"\n    else\n        echo \"$__vivado_version\"\n    fi\n}\n\nfunction setup_patches {\n    local caller_script=\"${BASH_SOURCE[1]}\"\n\n    info_msg \"Checking if patch AR71715 needs to be installed\"\n    patch_AR71715\n\n    info_msg \"Checking if patch AR73068 needs to be installed\"\n    patch_AR73068 \"$caller_script\"\n}\n\nfunction is_patch_applied {\n    local patch_name=\"$1\"\n    local long_vivado_version=$(get_vivado_version)\n\n    if [[ \"$long_vivado_version\" =~ .*\"$patch_name\".* ]]; then\n      true\n    else\n      false\n    fi\n}\n\nfunction patch_AR71715 {\n    local bucket=\"aws-fpga-developer-ami/1.5.0/Patches\"\n    local object=\"AR71715.zip\"\n    local patch_dirname=\"AR71715\"\n    local patch_root=\"$XILINX_SDX/patches\"\n    local tool_dir=\"$XILINX_SDX\"\n\n    declare -a valid_vivado_versions=( \"Vivado v2018.2_AR71275_op (64-bit)\"\n                                        \"Vivado v2018.2.op (64-bit)\"\n                                        \"Vivado v2018.2 (64-bit)\"\n                                     )\n\n    local base_vivado_version=$(get_base_vivado_version)\n    is_patch_valid=false\n    for vivado_version in \"${valid_vivado_versions[@]}\"\n    do\n        if [ \":$vivado_version\" == \":$base_vivado_version\" ]; then\n            is_patch_valid=true\n        fi\n    done\n\n    if [ \"$is_patch_valid\" == \"true\" ]; then\n\n        info_msg \"Patch AR71715 is valid for $base_vivado_version\"\n\n        if [ ! -d $patch_root/$patch_dirname ]; then\n\n            info_msg \"Downloading the $patch_dirname patch.\"\n\n            curl -s https://s3.amazonaws.com/$bucket/$object -o $object || { err_msg \"Failed to download Patch $object from $bucket/$object\"; return 2; }\n\n            sudo mkdir -p $patch_root || { err_msg \"Failed to create path $patch_root  you need to have root permissions to install this patch. If you dont have root permissions please contact your system administrator\";  return 2; }\n\n            info_msg \"Extracting the $patch_dirname patch.\"\n\n            sudo unzip $object -d $patch_root/$patch_dirname || { err_msg \"Failed to unzip $object into: $patch_root/$patch_dirname\"; return 2; }\n            sudo cp $tool_dir/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl.bkp\n            sudo cp -f $patch_root/$patch_dirname/sdx/scripts/ocl/ocl_util.tcl $tool_dir/scripts/ocl/ocl_util.tcl\n\n            rm $object\n\n            chmod -R 755 $patch_root/$patch_dirname\n        fi\n    fi\n}\n\nfunction install_patch {\n    local patch_name=\"$1\"\n    local patch_bucket=\"$2\"\n    local patch_object=\"$3\"\n    local patch_dir_name=\"${patch_object%.*}\"\n\n    if is_patch_applied $patch_name\n    then\n        info_msg \"$patch_name is already applied. Skipping.\"\n    else\n        info_msg \"Applying $patch_name\"\n        info_msg \"in bucket $patch_bucket\"\n        info_msg \"object $patch_object\"\n\n        # Checking if the patches directory exists and making it if it doesn't\n        [ -d $script_dir/patches ] || mkdir -p $script_dir/patches\n\n        info_msg \"Downloading the $patch_name from $patch_bucket/$patch_object.\"\n        debug_msg \"curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object\"\n\n        curl -s $patch_bucket/$patch_object -o $script_dir/patches/$patch_object || { err_msg \"Failed to download Patch $object from $patch_bucket/$patch_object\"; return 2; }\n\n        info_msg \"Extracting the $patch_name to $script_dir/patches/$patch_dir_name.\"\n\n        unzip -q -o $script_dir/patches/$patch_object -d $script_dir/patches/$patch_dir_name  || { err_msg \"Failed to extract $script_dir/patches/$patch_object to $script_dir/patches/$patch_dir_name\"; return 2; }\n\n        # XILINX_PATH should not have AR73068 at this point.\n        info_msg \"Appending XILINX_PATH with $script_dir/patches/$patch_dir_name/vivado\"\n\n        export XILINX_PATH=$XILINX_PATH:$script_dir/patches/$patch_dir_name/vivado\n    fi\n}\n\nfunction fix_patch_vitis_AR73068_2019_2 {\n    local patch_object=\"$1\"\n    local patch_dir_name=\"${patch_object%.*}\"\n    pushd patches/$patch_dir_name\n\n    sed -i '/.*checksum.*/d' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml\n    sed -i 's/coreRevision>73068/coreRevision>8/' ./vivado/data/ip/xilinx/ddr4_v2_2/component.xml\n    popd\n}\n\nfunction patch_AR73068_2019_2 {\n    info_msg \"Patching Vivado/Vitis 2019.2 with Xilinx Patch AR73068\"\n    local fix_patch=\"$1\"\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.8.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2019_2_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n\n    if [[ \"$fix_patch\" == true ]]; then\n      info_msg \"Fixing Patch AR73068 for Vitis\"\n      fix_patch_vitis_AR73068_2019_2 \"$patch_object\"\n    fi\n}\n\nfunction patch_AR73068_2019_1 {\n    info_msg \"Patching Vivado 2019.1 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.7.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2019_1_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2018_3 {\n    info_msg \"Patching Vivado 2018.3 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.6.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2018_3_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2018_2 {\n    info_msg \"Patching Vivado 2018.2 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.5.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2018_2_preliminary_rev1.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068_2017_4 {\n    info_msg \"Patching Vivado 2017.4 with Xilinx Patch AR73068\"\n\n    local patch_bucket=\"https://aws-fpga-developer-ami.s3.amazonaws.com/1.4.0/Patches/AR73068\"\n    local patch_object=\"AR73068_Vivado_2017_4_preliminary_rev2.zip\"\n\n    install_patch \"AR73068\" \"$patch_bucket\" \"$patch_object\"\n}\n\nfunction patch_AR73068 {\n    local base_vivado_version=$(get_base_vivado_version)\n    local caller_script=\"$1\"\n    local fix_patch=false\n\n    # Vitis specific changes\n    if [[ \"$caller_script\" =~ \"vitis_setup.sh\" ]]; then\n      info_msg \"Patching Vitis with AR73068\"\n      fix_patch=true\n    fi\n\n    if [[ \"${base_vivado_version}\" =~ \"Vivado v2019.2\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2019_2 \"$fix_patch\"\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2019.1\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2019_1\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2018.3\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2018_3\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2018.2\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2018_2\n    elif [[ \"${base_vivado_version}\" =~ \"Vivado v2017.4\" ]]; then\n      info_msg \"Patch $patch_name is valid for Vivado $base_vivado_version.\"\n      patch_AR73068_2017_4\n    else\n      info_msg \"Patch AR73068 not applicable for Vivado ${base_vivado_version}.\"\n    fi\n}\n\nfunction allow_non_root {\n       [ ! -z ${AWS_FPGA_ALLOW_NON_ROOT} ]\n}\n\nfunction allow_others {\n       [ ! -z ${AWS_FPGA_SDK_OTHERS} ]\n}\n", "num_lines": 305}
{"repo_name": "aws-gamekit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nif [[ $# -eq 0 ]] ; then\n    echo 'USAGE: ./regenerate_projects_ios.sh <AWSSDK_DIR> <BOOST_DIR> <yaml-cpp_DIR> <curl_DIR> <SOURCE_PATH> <Debug|Release>'\n    echo 'Example: ./regenerate_projects_ios.sh ~/development/AWSSDK_ios ~/development/boost_1_76_0 ~/development/yaml-cpp ~/development/Build-OpenSSL-cURL . Debug'\n    exit 1\nfi\n\ncmake -G \"Xcode\" -DCMAKE_BUILD_TYPE=$6 -DBUILD_SHARED_LIBS=OFF \\\n-Daws-c-http_DIR=$1/install/arm64/ios/$6/lib/aws-c-http/cmake \\\n-Daws-c-io_DIR=$1/install/arm64/ios/$6/lib/aws-c-io/cmake \\\n-Daws-c-common_DIR=$1/install/arm64/ios/$6/lib/aws-c-common/cmake \\\n-Daws-c-cal_DIR=$1/install/arm64/ios/$6/lib/aws-c-cal/cmake \\\n-Daws-c-compression_DIR=$1/install/arm64/ios/$6/lib/aws-c-compression/cmake \\\n-Daws-c-mqtt_DIR=$1/install/arm64/ios/$6/lib/aws-c-mqtt/cmake \\\n-Daws-c-auth_DIR=$1/install/arm64/ios/$6/lib/aws-c-auth/cmake \\\n-Daws-c-event-stream_DIR=$1/install/arm64/ios/$6/lib/aws-c-event-stream/cmake \\\n-Daws-checksums_DIR=$1/install/arm64/ios/$6/lib/aws-checksums/cmake \\\n-Daws-c-s3_DIR=$1/install/arm64/ios/$6/lib/aws-c-s3/cmake \\\n-DAWSSDK_DIR=$1/install/arm64/ios/$6/lib/cmake/AWSSDK \\\n-Daws-cpp-sdk-core_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-core \\\n-Daws-crt-cpp_DIR=$1/install/arm64/ios/$6/lib/aws-crt-cpp/cmake \\\n-Daws-cpp-sdk-cloudformation_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-cloudformation \\\n-Daws-cpp-sdk-cognito-idp_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-cognito-idp \\\n-Daws-cpp-sdk-sts_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-sts \\\n-Daws-cpp-sdk-secretsmanager_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-secretsmanager \\\n-Daws-cpp-sdk-ssm_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-ssm \\\n-Daws-cpp-sdk-s3_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-s3 \\\n-Daws-cpp-sdk-lambda_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-lambda \\\n-Daws-cpp-sdk-apigateway_DIR=$1/install/arm64/ios/$6/lib/cmake/aws-cpp-sdk-apigateway \\\n-Daws-c-sdkutils_DIR=$1/install/arm64/ios/$6/lib/aws-c-sdkutils/cmake -DBOOST_ROOT=$2 \\\n-DBOOST_LIBRARYDIR=$2/stage/lib -Dyaml-cpp_DIR=$3/build_ios/install/arm64/$6/share/cmake/yaml-cpp \\\n-DCURL_INCLUDE_DIR=$4/curl/include -DOPENSSL_INCLUDE_DIR=$4/openssl/IOS/include \\\n-DNGHTTP2_INCLUDE_DIR=$4/nghttp2/iOS/arm64/include -DCMAKE_XCODE_ATTRIBUTE_ARCHS=\"arm64\" \\\n-DCMAKE_INSTALL_PREFIX=$5/build_ios/install/arm64/$6 -DCMAKE_XCODE_ATTRIBUTE_IPHONEOS_DEPLOYMENT_TARGET=14.0 \\\n-DCMAKE_XCODE_ATTRIBUTE_SDK_NAME=iOS -DCMAKE_XCODE_ATTRIBUTE_SDKROOT=iphoneos \\\n-DENABLE_CUSTOM_HTTP_CLIENT_FACTORY=ON -DENABLE_CURL_CLIENT=ON -DENABLE_CURL_LOGGING=OFF \\\n$5\n", "num_lines": 41}
{"repo_name": "aws-glue-databrew-jupyter-extension", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nmy_region=$1\necho \"region is $my_region\"\nexport PATH=/home/ec2-user/anaconda3/bin:$PATH\ncurl -sL https://rpm.nodesource.com/setup_15.x | sudo bash -\nsudo yum install -y nodejs\npip install --upgrade jupyter\npip uninstall jupyterlab\npip install \"jupyterlab>=2.2.9,<3.0.0\"\npip install aws-jupyter-proxy\n\nnpm_version=`npm --version`\nnode_version=`node --version`\njupyter_version=`jupyter lab --version`\necho \"NODE VERISON : $node_version , NPM VERSION : $npm_version and JUPYTERLAB VERSION : $jupyter_version\"\n\n\nCERTIFICATE_DIR=\"/home/ec2-user/certificate\"\nJUPYTER_CONFIG_DIR=\"/home/ec2-user/.jupyter\"\n\nif [ ! -d \"$CERTIFICATE_DIR\" ]; then\n    mkdir $CERTIFICATE_DIR\n    openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout \"$CERTIFICATE_DIR/mykey.key\" -out \"$CERTIFICATE_DIR/mycert.pem\" -batch\n    chown -R ec2-user $CERTIFICATE_DIR\nfi\necho \"*********************Finished Writing Certificats******************\"\n\nif [ ! -d \"$JUPYTER_CONFIG_DIR\" ]; then\n    mkdir $JUPYTER_CONFIG_DIR\nfi\necho \"*********************Started Writing Config File******************\"\n    # append notebook server settings\n    cat <<EOF >> \"$JUPYTER_CONFIG_DIR/jupyter_notebook_config.py\"\n# Set options for certfile, ip, password, and toggle off browser auto-opening\nc.NotebookApp.certfile = u'$CERTIFICATE_DIR/mycert.pem'\nc.NotebookApp.keyfile = u'$CERTIFICATE_DIR/mykey.key'\n# Set ip to '*' to bind on all interfaces (ips) for the public server\nc.NotebookApp.ip = '*'\nfrom IPython.lib import passwd\npassword = passwd(\"databrew_demo\")\nc.NotebookApp.password = password\nc.NotebookApp.open_browser = False\n\n# It is a good idea to set a known, fixed port for server access\nc.NotebookApp.port = 8888\nEOF\n    chown -R ec2-user $JUPYTER_CONFIG_DIR\necho \"*********************Finished Writing Config File******************\"\njupyter labextension install aws_glue_databrew_jupyter\n\npip install --upgrade boto3\npip install --upgrade awscli\naws configure set region $my_region\nnohup jupyter notebook --config=$JUPYTER_CONFIG_DIR/jupyter_notebook_config.py &\ndf -h\n", "num_lines": 56}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Usage: ./compile-gromacs-acfl.sh <gromacs_version>(optional, default version is 2022.4)\n# the Gromacs releases can be found at https://manual.gromacs.org/\ngromacs_version=2022.4\nif [ ! -z \"$1\" ]\nthen\n  gromacs_version=$1\nfi\n\ncd /shared/tools\nwget -q http://ftp.gromacs.org/pub/gromacs/gromacs-${gromacs_version}.tar.gz\ntar xf gromacs-${gromacs_version}.tar.gz\nmkdir -p gromacs-${gromacs_version}/build_mpi-acfl && cd gromacs-${gromacs_version}/build_mpi-acfl\n\nexport ROOT=/shared\nCURDIR=${ROOT}/gromacs-${gromacs_version}-acfl\nexport PATH=/shared/openmpi-4.1.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=/shared/openmpi-4.1.4-acfl/lib:$LD_LIBRARY_PATH\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04\nmodule load armpl/23.04.0\n\nexport LDFLAGS=\"-lgfortran -lamath -lm -lastring\"\ncmake .. -DGMX_BUILD_OWN_FFTW=OFF \\\n      -DREGRESSIONTEST_DOWNLOAD=ON \\\n      -DCMAKE_C_FLAGS=\"-mcpu=neoverse-512tvb --param=aarch64-autovec-preference=4 -g\" \\\n      -DCMAKE_CXX_FLAGS=\"-mcpu=neoverse-512tvb --param=aarch64-autovec-preference=4 -g\" \\\n      -DCMAKE_C_COMPILER=$(which mpicc) \\\n      -DCMAKE_CXX_COMPILER=$(which mpicxx) \\\n      -DGMX_OMP=ON \\\n      -DGMX_MPI=ON \\\n      -DGMX_SIMD=ARM_SVE \\\n      -DGMX_BUILD_MDRUN_ONLY=OFF \\\n      -DGMX_DOUBLE=OFF \\\n      -DCMAKE_INSTALL_PREFIX=${CURDIR} \\\n      -DBUILD_SHARED_LIBS=OFF \\\n      -DGMX_FFT_LIBRARY=fftw3 \\\n      -DFFTWF_LIBRARY=${ARMPL_LIBRARIES}/libarmpl_lp64.so \\\n      -DFFTWF_INCLUDE_DIR=${ARMPL_INCLUDES} \\\n      \\\n      -DGMX_BLAS_USER=${ARMPL_LIBRARIES}/libarmpl_lp64.so \\\n      -DGMX_LAPACK_USER=${ARMPL_LIBRARIES}/libarmpl_lp64.so \\\n      \\\n      -DGMXAPI=OFF \\\n      -DGMX_GPU=OFF\n\nmake \nmake  install\ncd ..\n", "num_lines": 50}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --wait-all-nodes=1\n#SBATCH --ntasks-per-node=64\n#SBATCH --ntasks=64\n#SBATCH --cpus-per-task=1\n#SBATCH --ntasks-per-core=1\n#SBATCH --export=ALL\n#SBATCH --partition=compute\n#SBATCH --exclusive\n\nexport PATH=/shared/gromacs-2022.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=/shared/gromacs-2022.4-acfl/lib:$LD_LIBRARY_PATH\nexport PATH=/shared/openmpi-4.1.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=/shared/openmpi-4.1.4-acfl/lib:$LD_LIBRARY_PATH\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\n\n[ ! -d /shared/data-gromacs/benchRIB ] && mkdir -p /shared/data-gromacs/benchRIB\ncd /shared/data-gromacs/benchRIB\n\nbench=RIB\nif [ ! -f bench${bench} ]; then\n  wget https://www.mpinat.mpg.de/bench${bench}\n  unzip bench${bench}\nfi\n\nexport OMP_NUM_THREADS=${SLURM_CPUS_PER_TASK}\nexport FI_EFA_FORK_SAFE=1\necho 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope\n\nmpirun -np ${SLURM_NTASKS} --report-bindings gmx_mpi mdrun -v -maxh 0.25 -deffnm bench${bench} -ntomp ${OMP_NUM_THREADS} -resethway &>> bench${bench}.out\n", "num_lines": 32}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Usage: ./compile_openfoam-acfl.sh <openfoam_version>(optional, default version is v2112)\n# openFOAM releases can be found at https://www.openfoam.com/download/release-history\n\nopenfoam_version=v2112\nif [ ! -z \"$1\" ]\nthen\n  openfoam_version=$1\nfi\n\nmkdir -p /shared/tools/openfoam-root && cd /shared/tools/openfoam-root\nexport PATH=/shared/openmpi-4.1.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=/shared/openmpi-4.1.4-acfl/lib:$LD_LIBRARY_PATH\nmodule use /shared/arm/modulefiles \nmodule load acfl/23.04 armpl/23.04.0\n\n[ -d openfoam ] || git clone -b OpenFOAM-${openfoam_version} https://develop.openfoam.com/Development/openfoam.git\n[ -d ThirdParty-common ] || git clone -b ${openfoam_version} https://develop.openfoam.com/Development/ThirdParty-common.git\n\npushd ThirdParty-common\nscotch_version=\"6.1.0\"\ngit clone -b v${scotch_version} https://gitlab.inria.fr/scotch/scotch.git scotch_${scotch_version}\npopd\ncd openfoam\n\n# a patch required for ACfL or GCC-12 (https://develop.openfoam.com/Development/openfoam/-/commit/91198eaf6a0c11b57446374d97a079ca95cf1412)\nwget https://raw.githubusercontent.com/aws/aws-graviton-getting-started/graviton-hpc-guide/HPC/scripts-openfoam/openfoam-v2112-patch.diff\ngit apply openfoam-v2112-patch.diff\n\nsed -i -e \"s/WM_COMPILER=Gcc/WM_COMPILER=Arm/g\" etc/bashrc\nsource etc/bashrc || echo \"Non-zero exit of source etc/bashrc\"\n./Allwmake -j \n", "num_lines": 33}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --wait-all-nodes=1\n#SBATCH --ntasks-per-node=64\n#SBATCH --ntasks=64\n#SBATCH --cpus-per-task=1\n#SBATCH --ntasks-per-core=1\n#SBATCH --export=ALL\n#SBATCH --partition=compute\n#SBATCH --exclusive\n\n# load OpenFOAM environment settings\nexport FI_EFA_FORK_SAFE=1\nexport WM_PROJECT_DIR=/shared/tools/openfoam-root/openfoam\nsource $WM_PROJECT_DIR/bin/tools/RunFunctions\nsource $WM_PROJECT_DIR/etc/bashrc\nexport PATH=/shared/openmpi-4.1.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=/shared/openmpi-4.1.4-acfl/lib:$LD_LIBRARY_PATH\nmodule use /shared/arm/modulefiles \nmodule load acfl/23.04 armpl/23.04.0\n\nworkdir=/shared/data-openfoam/motorBike-70M\nmkdir -p $workdir && cd $workdir\ncp -rp ${WM_PROJECT_DIR}/tutorials/incompressible/pisoFoam/LES/motorBike/motorBike/ .\ncp -rp ${WM_PROJECT_DIR}/tutorials/incompressible/pisoFoam/LES/motorBike/lesFiles/ .\ncd motorBike\n\nmkdir constant/triSurface\ncp -f \\\n\"$FOAM_TUTORIALS\"/resources/geometry/motorBike.obj.gz \\\nconstant/triSurface/\nmkdir log\n\n# use 64 processes for the simulation and domain decomposition is 4 subdomains in x, y and z direction\nsed -i 's/numberOfSubdomains 8;/numberOfSubdomains 64;/' system/decomposeParDict\nsed -i 's/(4 2 1);/(4 4 4);/' system/decomposeParDict\nblockMesh > ./log/blockMesh.log\ndecomposePar -decomposeParDict system/decomposeParDict > log/decomposePar.log\n\nmkdir -p 0\nsed -i 's/mergeTolerance 1E-6/mergeTolerance 1E-5/' system/snappyHexMeshDict\nmpirun -np 64 snappyHexMesh -parallel -decomposeParDict system/decomposeParDict.ptscotch -profiling -overwrite > log/snappyHexMesh.log\nfind . -iname '*level*' -type f -delete\nrestore0Dir -processor\ncp 0.orig/* 0 -rp\n\nmpirun -np 64 renumberMesh -parallel -decomposeParDict system/decomposeParDict.ptscotch -overwrite -constant > ./log/renumberMesh.log\nmpirun -np 64 potentialFoam -parallel -decomposeParDict system/decomposeParDict.ptscotch -noFunctionObjects -initialiseUBCs > ./log/potentialFoam.log\nmpirun -np 64 simpleFoam -parallel -decomposeParDict system/decomposeParDict.ptscotch > ./log/simpleFoam.log\n\n", "num_lines": 50}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# download acfl for ubuntu 20.04 from arm website - https://developer.arm.com/downloads/-/arm-compiler-for-linux\n# install acfl will include armpl automatically\nmkdir -p /shared/tools\ncd /shared/tools\nwget -O arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar 'https://developer.arm.com/-/media/Files/downloads/hpc/arm-compiler-for-linux/23-04/arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar?rev=5f0c6e9758aa4409ab9e6a3891c791a4&revision=5f0c6e97-58aa-4409-ab9e-6a3891c791a4'\ntar xf arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar\n./arm-compiler-for-linux_23.04_Ubuntu-20.04/arm-compiler-for-linux_23.04_Ubuntu-20.04.sh \\\n-i /shared/arm -a --force\n", "num_lines": 11}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Find the download link to ArmPL (Ubuntu 20.04, GCC-12) on https://developer.arm.com/downloads/-/arm-performance-libraries\nmkdir -p /shared/tools && cd /shared/tools\nwget -O arm-performance-libraries_23.04_Ubuntu-20.04_gcc-10.2.tar 'https://developer.arm.com/-/media/Files/downloads/hpc/arm-performance-libraries/23-04/ubuntu-20/arm-performance-libraries_23.04_Ubuntu-20.04_gcc-12.2.tar?rev=defaf45ca17644dea20dc54a5a0327ed&revision=defaf45c-a176-44de-a20d-c54a5a0327ed'\ntar xf arm-performance-libraries_23.04_Ubuntu-20.04_gcc-10.2.tar\ncd arm-performance-libraries_23.04_Ubuntu-20.04/\n./arm-performance-libraries_23.04_Ubuntu-20.04.sh -i /shared/arm -a --force\n", "num_lines": 9}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# compile a copy of Open MPI with ACFL\nexport INSTALLDIR=/shared\nexport OPENMPI_VERSION=4.1.4\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nexport CFLAGS=\"-mcpu=neoverse-512tvb\"\ncd /shared/tools\nwget -N https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-4.1.4.tar.gz\ntar -xzvf openmpi-4.1.4.tar.gz\ncd openmpi-4.1.4\nmkdir build-acfl\ncd build-acfl\n../configure --prefix=${INSTALLDIR}/openmpi-${OPENMPI_VERSION}-acfl --enable-mpirun-prefix-by-default --with-sge --without-verbs --disable-man-pages --enable-builtin-atomics --with-libfabric=/opt/amazon/efa  --with-libfabric-libdir=/opt/amazon/efa/lib\nmake -j$(nproc) && make install\n\n", "num_lines": 21}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# download and compile Open MPI with GCC for customers who wants to use GCC\nexport INSTALLDIR=/shared\nexport OPENMPI_VERSION=4.1.4\nexport CC=gcc\nexport CXX=g++\nexport FC=gfortran\nexport CFLAGS=\"-march=native\"\ncd /shared/tools\nwget -N https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-4.1.4.tar.gz\ntar -xzvf openmpi-4.1.4.tar.gz\ncd openmpi-4.1.4\nmkdir build\ncd build\n../configure --prefix=${INSTALLDIR}/openmpi-${OPENMPI_VERSION} --enable-mpirun-prefix-by-default --with-sge --without-verbs --disable-man-pages --enable-builtin-atomics --with-libfabric=/opt/amazon/efa  --with-libfabric-libdir=/opt/amazon/efa/lib\nmake -j$(nproc) && make install\n\n", "num_lines": 19}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nsudo apt update -y\n\nsudo add-apt-repository -y ppa:ubuntu-toolchain-r/test\nsudo apt install -y gcc-11 g++-11 gfortran-11\nsudo update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100 --slave /usr/bin/g++ g++ /usr/bin/g++-11 --slave /usr/bin/gcov gcov /usr/bin/gcov-11 --slave /usr/bin/gfortran gfortran /usr/bin/gfortran-11\n\n", "num_lines": 10}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n# download acfl for ubuntu 20.04 from arm website - https://developer.arm.com/downloads/-/arm-compiler-for-linux\n# install acfl will include armpl automatically\nmkdir -p /shared/tools\ncd /shared/tools\nwget -O arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar 'https://developer.arm.com/-/media/Files/downloads/hpc/arm-compiler-for-linux/23-04/arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar?rev=5f0c6e9758aa4409ab9e6a3891c791a4&revision=5f0c6e97-58aa-4409-ab9e-6a3891c791a4'\ntar xf arm-compiler-for-linux_23.04_Ubuntu-20.04_aarch64.tar\n./arm-compiler-for-linux_23.04_Ubuntu-20.04/arm-compiler-for-linux_23.04_Ubuntu-20.04.sh \\\n-i /shared/arm -a --force\n\n# compile a copy of Open MPI with ACFL\nexport INSTALLDIR=/shared\nexport OPENMPI_VERSION=4.1.4\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nexport CFLAGS=\"-mcpu=neoverse-512tvb\"\ncd /shared/tools\nwget -N https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-4.1.4.tar.gz\ntar -xzvf openmpi-4.1.4.tar.gz\ncd openmpi-4.1.4\nmkdir build-acfl\ncd build-acfl\n../configure --prefix=${INSTALLDIR}/openmpi-${OPENMPI_VERSION}-acfl --enable-mpirun-prefix-by-default --with-sge --without-verbs --disable-man-pages --enable-builtin-atomics --with-libfabric=/opt/amazon/efa  --with-libfabric-libdir=/opt/amazon/efa/lib\nmake -j$(nproc) && make install\n\n# download and compile Open MPI with GCC for customers who wants to use GCC\nexport CC=gcc\nexport CXX=g++\nexport FC=gfortran\nexport CFLAGS=\"-march=native\"\ncd /shared/tools\ncd openmpi-4.1.4\nmkdir build\ncd build\n../configure --prefix=${INSTALLDIR}/openmpi-${OPENMPI_VERSION} --enable-mpirun-prefix-by-default --with-sge --without-verbs --disable-man-pages --enable-builtin-atomics --with-libfabric=/opt/amazon/efa  --with-libfabric-libdir=/opt/amazon/efa/lib\nmake -j$(nproc) && make install\n\n", "num_lines": 43}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nmkdir -p /shared/tools-acfl && cd /shared/tools-acfl\nwget -N http://zlib.net/zlib-1.2.13.tar.gz\ntar -xzvf zlib-1.2.13.tar.gz\ncd zlib-1.2.13\n./configure --prefix=${WRF_INSTALL}/zlib-acfl\nsed -i 's/DPIC/fPIC/g' Makefile\nmake check && make install\n", "num_lines": 17}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=mpicc\nexport CXX=mpic++\nexport FC=mpifort\nexport F90=mpifort\ncd /shared/tools-acfl\ncurl -o hdf5-1.12.0.tar.gz -J -L https://www.hdfgroup.org/package/hdf5-1-12-0-tar-gz/?wpdmdl=14582\ntar -xzvf hdf5-1.12.0.tar.gz \ncd hdf5-1.12.0\n./configure --prefix=${WRF_INSTALL}/hdf5-acfl --with-zlib=${WRF_INSTALL}/zlib --enable-parallel --enable-shared --enable-hl --enable-fortran --with-pic\nsed -i -e 's#wl=\"\"#wl=\"-Wl,\"#g' libtool\nsed -i -e 's#pic_flag=\"\"#pic_flag=\" -fPIC -DPIC\"#g' libtool\nmake -j$(nproc) && make install", "num_lines": 20}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nexport F77=armflang\nexport F90=armflang\nexport MPICC=mpicc\nexport MPIF77=mpifort\nexport MPIF90=mpifort\nexport MPICXX=mpicxx\nexport CFLAGS=\"-O3 -fPIC -DPIC\"\nexport CXXFLAGS=\"-O3 -fPIC -DPIC\"\nexport FFLAGS=\"-O3 -fPIC\"\nexport FCFLAGS=\"-O3 -fPIC\"\nexport FLDFLAGS=\"-fPIC\"\nexport F90LDFLAGS=\"-fPIC\"\nexport LDFLAGS=\"-fPIC\"\ncd /shared/tools-acfl\nwget -N https://parallel-netcdf.github.io/Release/pnetcdf-1.12.2.tar.gz\ntar -xzvf pnetcdf-1.12.2.tar.gz\ncd pnetcdf-1.12.2\n./configure --prefix=${WRF_INSTALL}/pnetcdf-acfl --enable-fortran --enable-large-file-test --enable-shared\nmake -j$(nproc) && make install\n", "num_lines": 31}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=mpicc\nexport CXX=mpicxx\nexport FC=mpif90\nexport F77=mpif90\nexport F90=mpif90\nHDF5=${WRF_INSTALL}/hdf5-acfl\nPNET=${WRF_INSTALL}/pnetcdf-acfl\nZLIB=${WRF_INSTALL}/zlib-acfl\nexport CPPFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport CFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport CXXFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport FCFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport FFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport LDFLAGS=\"-I$HDF5/include -I${PNET}/include -L$ZLIB/lib -L$HDF5/lib -L${PNET}/lib\"\ncd /shared/tools-acfl\nwget -N https://downloads.unidata.ucar.edu/netcdf-c/4.8.1/netcdf-c-4.8.1.tar.gz\ntar -xzvf netcdf-c-4.8.1.tar.gz\ncd netcdf-c-4.8.1\n./configure --prefix=${WRF_INSTALL}/netcdf-acfl CPPFLAGS=\"-I$HDF5/include -I$PNET/include\" CFLAGS=\"-DHAVE_STRDUP -O3 -march=armv8.2-a+crypto+fp16+rcpc+dotprod\" LDFLAGS=\"-L$HDF5/lib -L$PNET/lib\" --enable-pnetcdf --enable-large-file-tests --enable-largefile  --enable-parallel-tests --enable-shared --enable-netcdf-4  --with-pic --disable-doxygen --disable-dap\nmake -j$(nproc) && make install\n\n\n", "num_lines": 31}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=mpicc\nexport CXX=mpicxx\nexport FC=mpif90\nexport F77=mpif90\nexport F90=mpif90\nHDF5=${WRF_INSTALL}/hdf5-acfl\nNCDIR=${WRF_INSTALL}/netcdf-acfl\nexport LD_LIBRARY_PATH=${NCDIR}/lib:${LD_LIBRARY_PATH}\nexport CPPFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport CFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport CXXFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport FCFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport FFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport LDFLAGS=\"-L$HDF5/lib -L$NCDIR/lib\"\ncd /shared/tools-acfl\nwget -N https://downloads.unidata.ucar.edu/netcdf-fortran/4.5.4/netcdf-fortran-4.5.4.tar.gz\ntar -xzvf netcdf-fortran-4.5.4.tar.gz\ncd netcdf-fortran-4.5.4\n./configure --prefix=$NCDIR --disable-static --enable-shared --with-pic --enable-parallel-tests --enable-large-file-tests --enable-largefile\nsed -i -e 's#wl=\"\"#wl=\"-Wl,\"#g' libtool\nsed -i -e 's#pic_flag=\"\"#pic_flag=\" -fPIC -DPIC\"#g' libtool\nmake -j$(nproc) && make install\n", "num_lines": 31}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# WRF releases can be found at https://github.com/wrf-model/WRF/releases\n# this script will install v4.5 from source (github)\n\nexport WRF_INSTALL=/shared\nexport CURDIR=/shared/wrf-arm-v45-acfl\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=mpicc\nexport CXX=mpicxx\nexport FC=mpif90\nexport F77=mpif90\nexport F90=mpif90\nexport ZLIB=${WRF_INSTALL}/zlib-acfl\nexport HDF5=${WRF_INSTALL}/hdf5-acfl\nexport PHDF5=${WRF_INSTALL}/hdf5-acfl\nexport NETCDF=${WRF_INSTALL}/netcdf-acfl\nexport PNETCDF=${WRF_INSTALL}/pnetcdf-acfl\nexport PATH=${NETCDF}/bin:${PATH}\nexport PATH=${PNETCDF}/bin:${PATH}\nexport PATH=${HDF5}/hdf5-acfl/bin:${PATH}\nexport LD_LIBRARY_PATH=${ZLIB}/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=${NETCDF}/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=${PNETCDF}/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=${HDF5}/lib:$LD_LIBRARY_PATH\nexport WRFIO_NCD_LARGE_FILE_SUPPORT=1\nexport NETCDF_classic=1\n\nmkdir -p ${CURDIR} && cd ${CURDIR}\n# get WRF source v45\ngit clone https://github.com/wrf-model/WRF.git\ncd WRF && git checkout release-v4.5\n\n# apply a patch for ACFL compiler options\nwget https://raw.githubusercontent.com/aws/aws-graviton-getting-started/graviton-hpc-guide/HPC/scripts-wrf/WRF-v45-patch-acfl.diff\ngit apply WRF-v45-patch-acfl.diff\n\n# choose option '12. (dm+sm)   armclang (armflang/armclang): Aarch64' and '1=basic'\n./configure\nsed -i 's/(WRF_NMM_CORE)$/(WRF_NMM_CORE)  -Wno-error=implicit-function-declaration -Wno-error=implicit-int/g'  configure.wrf\n./compile -j 1 em_real 2>&1 | tee compile_wrf.out\n", "num_lines": 45}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nexport WRF_INSTALL=/shared\nmodule use /shared/arm/modulefiles\nmodule load acfl/23.04 armpl/23.04.0\nexport OPENMPI_VERSION=4.1.4\nexport PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${WRF_INSTALL}/openmpi-${OPENMPI_VERSION}-acfl/lib:$LD_LIBRARY_PATH\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nexport F77=armflang\nexport F90=armflang\nexport MPICC=mpicc\nexport MPIF77=mpifort\nexport MPIF90=mpifort\nexport MPICXX=mpicxx\n\n# zlib\nmkdir -p /shared/tools-acfl && cd /shared/tools-acfl\nwget -N http://zlib.net/zlib-1.2.13.tar.gz\ntar -xzvf zlib-1.2.13.tar.gz\ncd zlib-1.2.13\n./configure --prefix=${WRF_INSTALL}/zlib-acfl\nsed -i 's/DPIC/fPIC/g' Makefile\nmake check && make install\n\n# hdf5\nexport CC=mpicc\nexport CXX=mpic++\nexport FC=mpifort\nexport F90=mpifort\ncd /shared/tools-acfl\ncurl -o hdf5-1.12.0.tar.gz -J -L https://www.hdfgroup.org/package/hdf5-1-12-0-tar-gz/?wpdmdl=14582\ntar -xzvf hdf5-1.12.0.tar.gz \ncd hdf5-1.12.0\n./configure --prefix=${WRF_INSTALL}/hdf5-acfl --with-zlib=${WRF_INSTALL}/zlib --enable-parallel --enable-shared --enable-hl --enable-fortran --with-pic\nsed -i -e 's#wl=\"\"#wl=\"-Wl,\"#g' libtool\nsed -i -e 's#pic_flag=\"\"#pic_flag=\" -fPIC -DPIC\"#g' libtool\nmake -j$(nproc) && make install\n\n# pnetcdf\nexport CC=armclang\nexport CXX=armclang++\nexport FC=armflang\nexport F77=armflang\nexport F90=armflang\nexport MPICC=mpicc\nexport MPIF77=mpifort\nexport MPIF90=mpifort\nexport MPICXX=mpicxx\nexport CFLAGS=\"-O3 -fPIC -DPIC\"\nexport CXXFLAGS=\"-O3 -fPIC -DPIC\"\nexport FFLAGS=\"-O3 -fPIC\"\nexport FCFLAGS=\"-O3 -fPIC\"\nexport FLDFLAGS=\"-fPIC\"\nexport F90LDFLAGS=\"-fPIC\"\nexport LDFLAGS=\"-fPIC\"\ncd /shared/tools-acfl\nwget -N https://parallel-netcdf.github.io/Release/pnetcdf-1.12.2.tar.gz\ntar -xzvf pnetcdf-1.12.2.tar.gz\ncd pnetcdf-1.12.2\n./configure --prefix=${WRF_INSTALL}/pnetcdf-acfl --enable-fortran --enable-large-file-test --enable-shared\nmake -j$(nproc) && make install\n\n# netcdf-c\nexport CC=mpicc\nexport CXX=mpicxx\nexport FC=mpif90\nexport F77=mpif90\nexport F90=mpif90\nHDF5=${WRF_INSTALL}/hdf5-acfl\nPNET=${WRF_INSTALL}/pnetcdf-acfl\nZLIB=${WRF_INSTALL}/zlib-acfl\nexport CPPFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport CFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport CXXFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport FCFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport FFLAGS=\"-I$HDF5/include -I${PNET}/include\"\nexport LDFLAGS=\"-I$HDF5/include -I${PNET}/include -L$ZLIB/lib -L$HDF5/lib -L${PNET}/lib\"\ncd /shared/tools-acfl\nwget -N https://downloads.unidata.ucar.edu/netcdf-c/4.8.1/netcdf-c-4.8.1.tar.gz\ntar -xzvf netcdf-c-4.8.1.tar.gz\ncd netcdf-c-4.8.1\n./configure --prefix=${WRF_INSTALL}/netcdf-acfl CPPFLAGS=\"-I$HDF5/include -I$PNET/include\" CFLAGS=\"-DHAVE_STRDUP -O3 -march=armv8.2-a+crypto+fp16+rcpc+dotprod\" LDFLAGS=\"-L$HDF5/lib -L$PNET/lib\" --enable-pnetcdf --enable-large-file-tests --enable-largefile  --enable-parallel-tests --enable-shared --enable-netcdf-4  --with-pic --disable-doxygen --disable-dap\nmake -j$(nproc) && make install\n\n# netcdf-fortran\nNCDIR=${WRF_INSTALL}/netcdf-acfl\nexport LD_LIBRARY_PATH=${NCDIR}/lib:${LD_LIBRARY_PATH}\nexport CPPFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport CFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport CXXFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport FCFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport FFLAGS=\"-I$HDF5/include -I$NCDIR/include\"\nexport LDFLAGS=\"-L$HDF5/lib -L$NCDIR/lib\"\ncd /shared/tools-acfl\nwget -N https://downloads.unidata.ucar.edu/netcdf-fortran/4.5.4/netcdf-fortran-4.5.4.tar.gz\ntar -xzvf netcdf-fortran-4.5.4.tar.gz\ncd netcdf-fortran-4.5.4\n./configure --prefix=$NCDIR --disable-static --enable-shared --with-pic --enable-parallel-tests --enable-large-file-tests --enable-largefile\nsed -i -e 's#wl=\"\"#wl=\"-Wl,\"#g' libtool\nsed -i -e 's#pic_flag=\"\"#pic_flag=\" -fPIC -DPIC\"#g' libtool\nmake -j$(nproc) && make install\n", "num_lines": 106}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --wait-all-nodes=1\n#SBATCH --ntasks-per-node=8\n#SBATCH --cpus-per-task=1\n#SBATCH --nodes=1\n#SBATCH --ntasks-per-core=1\n#SBATCH --export=ALL\n#SBATCH --partition=compute\n#SBATCH --exclusive\n\n#ENV VARIABLES#\n\n#---------------------Run-time env-----------------------------------------\nulimit -s unlimited\n\nexport OMP_STACKSIZE=12G\nexport OMP_NUM_THREADS=8\nexport FI_EFA_FORK_SAFE=1\nwrf_root=/shared\nwrf_install=${wrf_root}\nmodule use /shared/arm/modulefiles\nmodule load armpl/23.04.0 acfl/23.04\n\nexport PATH=${wrf_install}/openmpi-4.1.4-acfl/bin:$PATH\nexport LD_LIBRARY_PATH=${wrf_install}/openmpi-4.1.4-acfl/lib:$LD_LIBRARY_PATH\n\nexport LD_LIBRARY_PATH=${wrf_install}/netcdf-acfl/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=${wrf_install}/pnetcdf-acfl/lib:$LD_LIBRARY_PATH\nexport LD_LIBRARY_PATH=${wrf_install}/hdf5-acfl/lib:$LD_LIBRARY_PATH\n\n#--------------------------------------------------------------------------\nmkdir -p /shared/data-wrf && cd /shared/data-wrf\nwget https://www2.mmm.ucar.edu/wrf/src/conus12km.tar.gz\ntar xf conus12km.tar.gz\ncd conus12km\ncp ${wrf_install}/wrf-arm-v45-acfl/WRF/run/*.TBL .\ncp ${wrf_install}/wrf-arm-v45-acfl/WRF/run/*.formatted .\ncp ${wrf_install}/wrf-arm-v45-acfl/WRF/run/RRTMG* .\ncp ${wrf_install}/wrf-arm-v45-acfl/WRF/run/CAMtr_volume_mixing_ratio* .\nln -s ${wrf_install}/wrf-arm-v45-acfl/WRF/main/wrf.exe wrf-v45-acfl.exe\n\necho \"Running WRF on $(date)\"\necho 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope\n\ndate -u +%Y-%m-%d_%H:%M:%S >> wrf.times\nmpirun --map-by socket:PE=8 --bind-to core ./wrf-v45-acfl.exe &>> wrf.out\necho nstasks=$SLURM_NTASKS\ndate -u +%Y-%m-%d_%H:%M:%S >> wrf.times\n", "num_lines": 49}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nlet capture_freq=99\n\n# search replace filter that will combine thread names like \n# GC-Thread-1 to GC-Thread- in perf-script sample header lines.\nsr_filter='s/^([a-zA-Z\\-]+)[0-9]*-?([a-zA-z]*) (.*?)$/\\1\\2 \\3/g'\n\nhelp_msg() {\n echo \"Requires perf to be installed and in your PATH\"\n echo \"usage: $0 oncpu|offcpu|<custom_event> [time seconds|default 300] --f|--frequency 99 -r|--regexfilter 's/hi/bye/g'\"\n echo \"custom_event is any event listed in perf-list\"\n}\n\nprocess_perf_data () {\n  perf inject -j -i perf.data -o perf.data.jit\n  perf script -f -i perf.data.jit > script.out\n  \n  if [[ ! -z \"${sr_filter}\" ]]; then\n    perl -pi -e \"${sr_filter}\" script.out\n  fi\n  ./FlameGraph/stackcollapse-perf.pl --kernel --jit script.out > folded.out\n  ./FlameGraph/flamegraph.pl --colors java folded.out > flamegraph_$1_$4_$3_$2.svg\n  rm perf.data perf.data.jit script.out folded.out\n}\n\ncapture_on_cpu () {\n  perf record -a -g -k 1 -F${capture_freq} -e cpu-clock:pppH -- sleep $1\n  process_perf_data \"oncpu\" $2 $3 $4\n}\n\ncapture_off_cpu () {\n  perf record -a -g -k 1 -F${capture_freq} -e sched:sched_switch -- sleep $1\n  process_perf_data \"offcpu\" $2 $3 $4\n}\n\ncapture_custom_event () {\n  perf record -a -g -k 1 -F${capture_freq} -e $1 -- sleep $2\n  process_perf_data $1 $3 $4 $5\n}\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must be run with sudo privileges\"\n  exit 1\nfi\n\n# Test perf exists\ntest_perf=$(perf list &> /dev/null)\nif [[ $? -ne 0 ]]; then\n  help_msg\n  exit 1\nfi\n\ndate=$(date \"+%Y-%m-%d_%H:%M:%S\")\n# Get meta-data using IMDSv2\ntoken=$(curl -s -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\")\ninstance_type=$(curl -s -H \"X-aws-ec2-metadata-token: $token\" http://169.254.169.254/latest/meta-data/instance-type)\ninstance_id=$(curl -s -H \"X-aws-ec2-metadata-token: $token\" http://169.254.169.254/latest/meta-data/instance-id)\n\nPOSITIONAL=()\nwhile [[ $# -gt 0 ]]\ndo\n  key=\"$1\"\n  case $key in\n    -f|--frequency)\n      let capture_freq=\"$2\"\n      shift; shift\n      ;;\n    -r|--regexfilter)\n      sr_filter=\"$2\"\n      shift; shift\n      ;;\n    -h|--help)\n      help_msg\n      exit 1\n      ;;\n    *)\n      POSITIONAL+=(\"$1\")\n      shift\n      ;;\n  esac\ndone\nset -- \"${POSITIONAL[@]}\"\n\nif [[ $# -lt 1 ]]; then\n  help_msg\n  exit 1\nfi\n\ncapture_time=300\nif [[ $# -gt 1 ]]; then\n  capture_time=$2\nfi\n\nif [[ \"$1\" == \"oncpu\" ]]; then\n  capture_on_cpu $capture_time $date $instance_type $instance_id\nelif [[ \"$1\" == \"offcpu\" ]]; then\n  capture_off_cpu $capture_time $date $instance_type $instance_id\nelse\n  capture_custom_event $1 $capture_time $date $instance_type $instance_id\nfi\n", "num_lines": 104}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ngrub_loc=/etc/default/grub\n#grub_loc=test\n\nhelp_msg() {\n  echo \"usage: $0 on|off\"\n}\n\nset -e\n\nenable_iommu() {\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"((.(?!iommu.strict=[01]))*)\"$/GRUB_CMDLINE_LINUX=\"\\1 iommu.strict=1\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"(.*?) iommu.strict=[01](.*?)\"$/GRUB_CMDLINE_LINUX=\"\\1\\2 iommu.strict=1\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"((.(?!iommu.passthrough=[01]))*)\"$/GRUB_CMDLINE_LINUX=\"\\1 iommu.passthrough=0\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"(.*?) iommu.passthrough=[01](.*?)\"$/GRUB_CMDLINE_LINUX=\"\\1\\2 iommu.passthrough=0\"/g' $grub_loc\n}\n\ndisable_iommu() {\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"((.(?!iommu.strict=[01]))*)\"$/GRUB_CMDLINE_LINUX=\"\\1 iommu.strict=0\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"(.*?) iommu.strict=[01](.*?)\"$/GRUB_CMDLINE_LINUX=\"\\1\\2 iommu.strict=0\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"((.(?!iommu.passthrough=[01]))*)\"$/GRUB_CMDLINE_LINUX=\"\\1 iommu.passthrough=1\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"(.*?) iommu.passthrough=[01](.*?)\"$/GRUB_CMDLINE_LINUX=\"\\1\\2 iommu.passthrough=1\"/g' $grub_loc\n}\n\nupdate_grub() {\n  if [[ -d /boot/grub2 ]]; then\n    grub2-mkconfig -o /boot/grub2/grub.cfg\n  else\n    grub2-mkconfig -o /boot/grub/grub.cfg\n  fi \n}\n\nif [[ $# -ne 1 ]]; then\n  help_msg\n  exit 1\nfi\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must be run with sudo privileges\"\n  exit 1\nfi\n\ncp $grub_loc ${grub_loc}.bak\ncase $1 in\n  on)\n    enable_iommu\n    update_grub\n    ;;\n  off)\n    disable_iommu\n    update_grub\n    ;;\n  *)\n    rm ${grub_loc}.bak\n    help_msg\n    exit 1\nesac\n\necho \"To make changes take effect run: %> sudo shutdown now -r\"\n", "num_lines": 61}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ngrub_loc=/etc/default/grub\n#grub_loc=test\n\nhelp_msg() {\n  echo \"usage: $0 <size in GB>\"\n}\n\nset -e\n\nconfig_mem () {\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"((.(?!mem=[0-9]+[KMG]))*)\"$/GRUB_CMDLINE_LINUX=\"\\1 mem='\"${1}\"'G\"/g' $grub_loc\n  perl -pi -e 's/GRUB_CMDLINE_LINUX=\"(.*?) mem=[0-9]+[KMG](.*?)\"$/GRUB_CMDLINE_LINUX=\"\\1\\2 mem='\"${1}\"'G\"/g' $grub_loc\n}\n\nupdate_grub() {\n  if [[ -d /boot/grub2 ]]; then\n    grub2-mkconfig -o /boot/grub2/grub.cfg\n  else\n    grub2-mkconfig -o /boot/grub/grub.cfg\n  fi \n}\n\nif [[ $# -ne 1 ]]; then\n  help_msg\n  exit 1\nfi\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must be run with sudo privileges\"\n  exit 1\nfi\n\ncp $grub_loc ${grub_loc}.bak\n\nconfig_mem $1\nupdate_grub\n\necho \"To make changes take effect run: %> sudo shutdown now -r\"\n", "num_lines": 41}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nhelp_msg() {\n  echo \"usage: $0 [cpus] [default=threads|cores]\"\n}\n\nif [[ $# -lt 1 ]]; then\n  help_msg\n  exit 1\nfi\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must be run with sudo privileges\"\n  exit 1\nfi\n\nif [[ \"$2\" == \"threads\" && $(uname -m) == \"aarch64\" ]]; then\n  echo \"Can only specify 'cores' for hotplugging cpus on Graviton\"\n  exit 1\nfi\n\n# Re-enable all CPUs then modify the list\nall_vcpus=$(lscpu -a -p=CPU | awk -F',' '$0 ~ /^[[:digit:]]+$/{print $1}')\nfor i in $all_vcpus; do\n  echo 1 > /sys/devices/system/cpu/cpu$i/online\ndone\n\n# Parse lscpu output to select the subset of cores/threads to hotplug in/out\ncase $2 in\n  threads)\n    let physical_cores=$1/2\n    vcpus_on=$(lscpu -p=CPU,CORE | awk -F',' 'BEGIN{j='\"${physical_cores}\"'}$0 ~ /^[[:digit:]]+,[[:digit:]]+$/{if ($2<j) {print $1}; i++}')\n    vcpus_off=$(lscpu -p=CPU,CORE | awk -F',' 'BEGIN{j='\"${physical_cores}\"'}$0 ~ /^[[:digit:]]+,[[:digit:]]+$/{if ($2>=j) {print $1}; i++}')\n    ;;\n  cores)\n    let physical_cores=$1\n    vcpus_on=$(lscpu -p=CPU,CORE | awk -F',' 'BEGIN{j='\"${physical_cores}\"'}$0 ~ /^[[:digit:]]+,[[:digit:]]+$/{if ($1<j) {print $1}; i++}')\n    vcpus_off=$(lscpu -p=CPU,CORE | awk -F',' 'BEGIN{j='\"${physical_cores}\"'}$0 ~ /^[[:digit:]]+,[[:digit:]]+$/{if ($1>=j) {print $1}; i++}')\n    ;;\n  *)\n    echo \"Do not recognize option: $2\"\n    exit 1\nesac\n\nfor i in $vcpus_on; do\n  echo 1 > /sys/devices/system/cpu/cpu$i/online\ndone\n\nfor i in $vcpus_off; do\n  echo 0 > /sys/devices/system/cpu/cpu$i/online\ndone\n\n# Update Docker cpusets to reflect cpus that are hotplugged in/out to allow\n# restarted containers so they see the proper number of CPUs\nFILE=/sys/fs/cgroup/cpuset/docker/cpuset.cpus\nif [ -f \"$FILE\" ]; then\n  cp /sys/fs/cgroup/cpuset/cpuset.cpus /sys/fs/cgroup/cpuset/docker/cpuset.cpus\nfi\n", "num_lines": 59}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must run with sudo privileges\"\n  exit 1\nfi\n\nset -e\n\ni=$(find / -name '*.jar' -type f -print)\ni=($i)\n\nmkdir -p /tmp/jar_dir\npushd /tmp/jar_dir\n\nfor jar in ${i[@]}; do\n  cp $jar .\n  jar_name=$(basename ${jar})\n  unzip -qq ${jar_name}\n  find . -name '*.so' -type f -print\n  rm -rf *\ndone\n\nrm -rf * /tmp/jar_dir\npopd\n", "num_lines": 26}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must run with sudo privileges\"\n  exit 1\nfi\n\npy_ver=$(python3 --version | awk '{print $2}' | awk -F'.' '{print $1\".\"$2}' | tr -d [:cntrl:])\nif [[ $# -ge 1 ]]; then\n  py_ver=$1\nfi\n  \n\ni=$(find / -wholename \"*python${py_ver}/site-packages\" -type d -print)\ni=($i)\n\ncwd=$(pwd)\n\nfor pylib in ${i[@]}; do\n  cd ${pylib}\n  find . -name '*.so' -type f -print\n  cd $cwd\ndone\n\ncd $cwd\n", "num_lines": 26}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must run with sudo privileges\"\n  exit 1\nfi\n\necho \"------ INSTALLING BCC PERFORAMANCE TOOLS ------\"\namazon-linux-extras enable BCC\nyum install -y -q perf kernel-devel-$(uname -r) bcc\n", "num_lines": 11}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ninstall_al2023_dependencies () {\n  echo \"------ INSTALLING UTILITIES ------\"\n  dnf install -y -q vim unzip git\n\n  echo \"------ INSTALLING HIGH LEVEL PERFORMANCE TOOLS ------\"\n  dnf install -y -q sysstat htop hwloc tcpdump\n\n  echo \"------ INSTALLING LOW LEVEL PERFORAMANCE TOOLS ------\"\n  dnf install -y -q perf kernel-devel-$(uname -r) bcc\n\n  echo \"------ INSTALL ANALYSIS TOOLS AND DEPENDENCIES ------\"\n  dnf install -y -q python3 python3-pip\n  python3 -m pip install --upgrade pip\n  python3 -m pip install pandas numpy scipy matplotlib sh seaborn plotext\n  git clone https://github.com/brendangregg/FlameGraph.git FlameGraph\n\n  echo \"------ DONE ------\"\n}\ninstall_al2_dependencies () {\n  echo \"------ INSTALLING UTILITIES ------\"\n  yum install -y -q vim unzip git\n\n  echo \"------ INSTALLING HIGH LEVEL PERFORMANCE TOOLS ------\"\n  yum install -y -q sysstat dstat htop hwloc tcpdump\n\n  echo \"------ INSTALLING LOW LEVEL PERFORAMANCE TOOLS ------\"\n  amazon-linux-extras enable BCC\n  yum install -y -q perf kernel-devel-$(uname -r) bcc\n\n  echo \"------ INSTALL ANALYSIS TOOLS AND DEPENDENCIES ------\"\n  yum install -y -q python3 python3-pip\n  python3 -m pip install --upgrade pip\n  python3 -m pip install pandas numpy scipy matplotlib sh seaborn plotext\n  git clone https://github.com/brendangregg/FlameGraph.git FlameGraph\n\n  echo \"------ DONE ------\"\n}\n\ninstall_ubuntu2004_dependencies () {\n  echo \"------ INSTALLING UTILITIES ------\"\n  apt-get update\n  apt-get install -y -q vim unzip git lsb-release grub2-common net-tools\n  ln -s /usr/sbin/grub-mkconfig /usr/sbin/grub2-mkconfig\n\n  echo \"------ INSTALLING HIGH LEVEL PERFORMANCE TOOLS ------\"\n  apt-get install -y -q sysstat htop hwloc tcpdump dstat\n\n  echo \"------ INSTALLING LOW LEVEL PERFORAMANCE TOOLS ------\"\n  apt-get install -y -q linux-tools-$(uname -r) linux-headers-$(uname -r) linux-modules-extra-$(uname -r) bpfcc-tools\n\n  echo \"------ INSTALL ANALYSIS TOOLS AND DEPENDENCIES ------\"\n  apt-get install -y -q python3-dev python3-pip\n  python3 -m pip install --upgrade pip\n  python3 -m pip install pandas numpy scipy matplotlib sh seaborn plotext\n  git clone https://github.com/brendangregg/FlameGraph.git FlameGraph\n\n  echo \"------ DONE ------\"\n}\n\nif [[ $(id -u) -ne 0 ]]; then\n  echo \"Must run with sudo privileges\"\n  exit 1\nfi\n\nos_name=$(cat /etc/os-release | grep \"PRETTY_NAME\" | awk -F\"=\" '{print $2}' | tr -d '[=\"=]' | tr -d [:cntrl:])\n\n\nif [[ \"$os_name\" == \"Amazon Linux 2023\" ]]; then\n  install_al2023_dependencies\nelif [[ \"$os_name\" == \"Amazon Linux 2\" ]]; then\n  install_al2_dependencies\nelif [[ \"$os_name\" =~ \"Ubuntu 20.04\" ]]; then\n  install_ubuntu2004_dependencies\nelif [[ \"$os_name\" =~ \"Ubuntu 22.04\" ]]; then\n  install_ubuntu2004_dependencies\nelse\n  echo \"$os_name not supported\"\n  exit 1\nfi\n\necho \"DEPENDENCIES SUCCESSFULLY INSTALLED! -- RUN UTILITIES FROM THIS DIRECTORY\"\n", "num_lines": 84}
{"repo_name": "aws-graviton-getting-started", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# Graviton2 Function Finder\n# Identify Lambda functions with Graviton2 compatible and not-compatible runtimes versions.  Looks in all regions where Graviton2 Lambda is currently available.\n# Lambda runtimes support for Graviton2 docs: https://docs.aws.amazon.com/lambda/latest/dg/lambda-runtimes.html\n\nsupported_regions=(us-east-1 us-east-2 us-west-2 eu-west-1 eu-west-2 eu-central-1 ap-southeast-1 ap-southeast-2 ap-northeast-1 ap-south-1)\nsupported_runtimes=(python3.8 python3.9 nodejs12.x nodejs14.x dotnetcore3.1 ruby2.7 java8.al2 java11 provided.al2)\nunsupported_runtimes=(python3.6 python3.7 python2.7 nodejs10.x dotnetcore2.1 ruby2.5 java8 go1.x provided)\n\necho \"Graviton2 Function Support Finder\"\n\nfor region in \"${supported_regions[@]}\"\n        do\n\techo \"  \"\n\techo \"Region: [${region}] - Functions WITH Graviton Compatible Runtimes\"\n\techo \"  \"\n\n\tfor runtime in \"${supported_runtimes[@]}\"\n        do\n\t\taws lambda list-functions --region \"${region}\" --output text --query \"Functions[?Runtime=='${runtime}'].{ARN:FunctionArn, Runtime:Runtime}\"\n\n\tdone\n\n        # include the container image functions\n\taws lambda list-functions --region \"${region}\" --output text --query \"Functions[?PackageType=='Image'].{ARN:FunctionArn, PackageType:'container-image'}\"\n\n\n\techo \"  \"\n\techo \"Region: [${region}] - Functions with Runtimes that are NOT Compatible with Graviton2. Require a Runtime version update.\"\n\techo \"  \"\n\n\tfor runtime in \"${unsupported_runtimes[@]}\"\n        do\n\t\taws lambda list-functions --region \"${region}\" --output text --query \"Functions[?Runtime=='${runtime}'].{ARN:FunctionArn, Runtime:Runtime}\"\n\tdone\ndone\necho \"finished\"", "num_lines": 38}
{"repo_name": "aws-health-tools", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Updates the Lambda functions that are too big to be inlined in the CloudFormation Template\n\nset -e\nAPPNAME=$1\nREGION=$2\nif [ $# -lt 2 ]; then\n  echo 1>&2 \"$0: not enough arguments.\"\n  echo 1>&2 \"Usage: $0 <CF_APPNAME> <REGION>\"\n  echo 1>&2 \"  CF_APPNAME: The name of the deployed CloudFormation template to update\"\n  echo 1>&2 \"  REGION: The region of the deployed CloudFormation template\"\n  exit 2\nfi\n\nAWS_VERSION=$(aws --version)\nAWS_COMMAND_FLAGS=\"\"\n\n# check if aws version is 2.x\n# we need to stop the command from waiting for user input\nif [[ $AWS_VERSION == *\"aws-cli/2\"* ]]; then\n  AWS_COMMAND_FLAGS=\"--no-cli-pager\"\nfi\n\ncreateOrUpdate () {\n    FUNC_NAME=$1\n    SOURCE=$2\n    cp \"$SOURCE\" index.py\n    zip \"$FUNC_NAME.zip\" index.py\n    aws lambda update-function-code --function-name \"$FUNC_NAME\" --zip-file \"fileb://$FUNC_NAME.zip\" --region \"$REGION\" $AWS_COMMAND_FLAGS\n    rm \"$FUNC_NAME.zip\"\n    rm index.py\n}\ncreateOrUpdate \"$APPNAME-Chat-Post\" \"Health-Event-Chat-Post-LambdaFn.py\"\ncreateOrUpdate \"$APPNAME-Poller\" \"Health-Event-Poller-LambdaFn.py\"\ncreateOrUpdate \"$APPNAME-Status\" \"Health-Event-Status-LambdaFn.py\"\ncreateOrUpdate \"$APPNAME-Iterator\" \"Health-Event-Iterator-LambdaFn.py\"\n", "num_lines": 37}
{"repo_name": "aws-imds-packet-analyzer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n#check if shell script is running as root => su permissions to edit /etc/systemd/system dir\nif [ \"$EUID\" -ne 0 ]; then\n  echo \"[ERROR] Please run as root (sudo)\"\n  exit 1\nfi\n\nbpf_trace_service=\"imds_tracer_tool.service\"\nbpf_trace_path=$(pwd)\nbpf_trace_systemd_path=\"/etc/systemd/system/$bpf_trace_service\"\n\necho \"--- removing old service file\"\nrm $bpf_trace_systemd_path\n\necho \"--- create new Unit file\"\ntouch $bpf_trace_systemd_path\n\necho \"--- add service details\"\necho \"[Unit]\" >> $bpf_trace_systemd_path\necho \"Description=ImdsPacketAnalyzer IMDS detection tooling from AWS\" >> $bpf_trace_systemd_path\necho \"Before=network-online.target\" >> $bpf_trace_systemd_path\necho \"After=multi-user.target\" >> $bpf_trace_systemd_path\necho \"\" >> $bpf_trace_systemd_path\n\necho \"[Service]\" >> $bpf_trace_systemd_path\necho \"Type=simple\" >> $bpf_trace_systemd_path\necho \"Restart=always\" >> $bpf_trace_systemd_path\necho \"WorkingDirectory=$bpf_trace_path\" >> $bpf_trace_systemd_path\necho \"ExecStart=$(command -v python3) $bpf_trace_path/src/imds_snoop.py\" >> $bpf_trace_systemd_path\n\necho \"\" >> $bpf_trace_systemd_path\necho \"[Install]\" >> $bpf_trace_systemd_path\necho \"WantedBy=multi-user.target\" >> $bpf_trace_systemd_path\n\necho \"--- Service details:\"\necho \"\"\ncat $bpf_trace_systemd_path\n\necho \"\"\necho \"--- reload daemon and enable the $bpf_trace_service service\"\nsystemctl daemon-reload\nsystemctl enable $bpf_trace_service\n\necho \"--- start the $bpf_trace_service service\"\n# For normal service we would start in activate, but we're starting here as we want to detect all IMDSv1 calls as early as possible\nsystemctl start $bpf_trace_service\n\necho \"--- done\"", "num_lines": 51}
{"repo_name": "aws-imds-packet-analyzer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n#check if shell script is running as root => su permissions to edit /etc/systemd/system dir\nif [ \"$EUID\" -ne 0 ]; then\n  echo \"[ERROR] Please run as root (sudo)\"\n  exit 1\nfi\n\nbpf_trace_service=\"imds_tracer_tool.service\"\nbpf_trace_systemd_path=\"/etc/systemd/system/$bpf_trace_service\"\n\necho \"--- stopping tracer service\"\nsystemctl stop imds_tracer_tool.service\n\necho \"--- removing service file (unit file)\"\nrm $bpf_trace_systemd_path\n\necho \"--- reload daemons\"\nsystemctl daemon-reload\n\necho \"\"\n\necho \"[INFO] Associated log files can be found in the /var/log/ directory\"\necho \"Run the following command to delete all log files: \"\necho \"sudo rm /var/log/imds-trace.*\"", "num_lines": 27}
{"repo_name": "aws-imds-packet-analyzer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nif [ \"$EUID\" -ne 0 ]; then\n  echo \"[ERROR] Please run as root (sudo)\"\n  exit 1\nfi\n\n# Check for supported operating systems\nif grep -q \"Amazon Linux 2023\" /etc/os-release; then\n    #amazon Linux 2023\n    dnf install -y bcc-tools\nelif grep -q \"Amazon Linux 2\" /etc/os-release  &&  grep -q 'VERSION=\"2\"' /etc/os-release ; then\n    #amazon linux 2\n    if [ ! -z \"${SUDO_USER}\" ]; then\n        echo  \"[INFO] Running with sudo..checking if SUDO_USER: '${SUDO_USER}' has home dir to support amazon-linux-extras cache...\"\n        homedir=$( getent passwd \"${SUDO_USER}\" | cut -d: -f6 )\n        if [ -d ${homedir} ]; then\n            echo \"[INFO] SUDO_USER: ${SUDO_USER} homedir '${homedir}' exists, moving forward with BCC installs\"\n        else\n            echo  \"[ERROR] SUDO_USER: ${SUDO_USER} homedir '${homedir}' does not exist, please create to support amazon-linux-extras cache\"\n            exit 1\n        fi\n    fi\n    # enable BCC extra\n    amazon-linux-extras enable BCC\n    # dependencies\n    yum -y install kernel-devel-$(uname -r) bcc-devel\nelif grep -q 'ID=debian' /etc/os-release  &&  grep -q 'VERSION_ID=\"11\"' /etc/os-release  ; then\n    #debian 11\n    #Avoid duplication of repo URL\n    if ! grep -xq 'deb http://cloudfront.debian.net/debian sid main' /etc/apt/sources.list ; then\n         echo deb http://cloudfront.debian.net/debian sid main | sudo tee -a /etc/apt/sources.list\n    else\n         echo \"[INFO] Debian Repo URL exists in /etc/apt/sources.list.\"\n    fi\n    apt-get update\n    #Set the environment variable DEBIAN_FRONTEND to 'noninteractive' to avoid the prompts and accept the default answers\n    export DEBIAN_FRONTEND=noninteractive\n    apt-get install -y bpfcc-tools libbpfcc libbpfcc-dev linux-headers-$(uname -r) bcc --no-install-recommends\nelif grep -q 'ID=debian' /etc/os-release  &&  grep -q 'VERSION_ID=\"10\"' /etc/os-release  ; then\n    #debian 10\n    #Avoid duplication of repo URL\n    if ! grep -xq 'deb http://cloudfront.debian.net/debian sid main' /etc/apt/sources.list ; then\n       echo deb http://cloudfront.debian.net/debian sid main | sudo tee -a /etc/apt/sources.list\n    else\n       echo \"[INFO] Debian Repo URL exists in /etc/apt/sources.list.\"\n    fi\n    apt-get update\n    #Set the environment variable DEBIAN_FRONTEND to 'noninteractive' to avoid the prompts and accept the default answers\n    export DEBIAN_FRONTEND=noninteractive\n    # \"|| true\" helps bash to ignore error and return success, prevents the script to stop if execution fails\n    apt-get install -y bpfcc-tools libbpfcc libbpfcc-dev linux-headers-$(uname -r) bcc --no-install-recommends || true\n    #Steps to fix the libcrypt1 error\n    cd /tmp/\n    apt -y download libcrypt1\n    dpkg-deb -x libcrypt1* .\n    cp -av lib/x86_64-linux-gnu/* /lib/x86_64-linux-gnu/\n    #Re-run the install command\n    apt-get install -y bpfcc-tools libbpfcc libbpfcc-dev linux-headers-$(uname -r) bcc --no-install-recommends || true\n    apt install -y --fix-broken || true\n    # Run the install command\n    apt-get install -y bpfcc-tools libbpfcc libbpfcc-dev linux-headers-$(uname -r) bcc  --no-install-recommends\nelif grep -q 'ID=ubuntu' /etc/os-release  &&  grep -q 'VERSION_ID=\"22.04\"' /etc/os-release  ; then\n    #Ubuntu 22.04\n    apt-get update\n    #Build bcc from the source\n    apt install -y bison build-essential cmake flex git libedit-dev libllvm14 llvm-14-dev libclang-14-dev python3 zlib1g-dev libelf-dev libfl-dev python3-distutils zip  --no-install-recommends\n    if [ -d \"/home/ubuntu/\" ] ; then\n        echo \"[INFO] Directory '/home/ubuntu/' exists, moving forward with BCC installs\"\n        cd /home/ubuntu/\n        #Handle error : destination path 'bcc' already exists during git clone.\n        if [ -d \"/home/ubuntu/bcc\" ]; then\n            rm -rf /home/ubuntu/bcc\n            git clone https://github.com/iovisor/bcc.git bcc\n        else\n            git clone https://github.com/iovisor/bcc.git bcc\n        fi\n        mkdir bcc/build; cd bcc/build\n        cmake ..\n        make\n        make install\n        cmake -DPYTHON_CMD=python3 .. # build python3 binding\n        pushd src/python/\n        make\n        sudo make install\n        popd\n        apt-get -y install linux-headers-$(uname -r)\n    else\n        echo  \"[ERROR] Directory '/home/ubuntu/' does not exist, please create to support BCC build\"\n        exit 1\n    fi\nelif grep -q 'ID=ubuntu' /etc/os-release  &&  grep -q 'VERSION_ID=\"20.04\"' /etc/os-release  ; then\n    #Ubuntu 20.04\n    apt-get update\n   #Build bcc from the source\n    apt install -y bison build-essential cmake flex git libedit-dev libllvm12 llvm-12-dev libclang-12-dev python zlib1g-dev libelf-dev libfl-dev python3-distutils zip  --no-install-recommends\n    if [ -d \"/home/ubuntu/\" ] ; then\n        echo \"[INFO] Directory '/home/ubuntu/' exists, moving forward with BCC installs\"\n        cd /home/ubuntu/\n        #Handle error : destination path 'bcc' already exists during git clone.\n        if [ -d \"/home/ubuntu/bcc\" ]; then\n            rm -rf /home/ubuntu/bcc\n            git clone https://github.com/iovisor/bcc.git bcc\n        else\n            git clone https://github.com/iovisor/bcc.git bcc\n        fi\n        mkdir bcc/build; cd bcc/build\n        cmake ..\n        make\n        make install\n        cmake -DPYTHON_CMD=python3 .. # build python3 binding\n        pushd src/python/\n        make\n        sudo make install\n        popd\n        apt-get -y install linux-headers-$(uname -r)\n    else\n        echo  \"[ERROR] Directory '/home/ubuntu/' does not exist, please create to support BCC build\"\n        exit 1\n    fi\nelif grep -q 'ID=\"rhel\"' /etc/os-release; then\n    #RHEL 8 and 9\n    yum -y install bcc-tools libbpf\nelif grep -q 'ID=\"sles\"' /etc/os-release  && grep -q 'VERSION_ID=\"15.[0-4]\"' /etc/os-release ; then\n    #SLES 15\n    zypper ref\n    zypper in -y  bcc-tools bcc-examples\n    zypper in -y --oldpackage kernel-default-devel-$(zypper se -s kernel-default-devel | awk '{split($0,a,\"|\"); print a[4]}' | grep $(uname -r | awk '{gsub(\"-default\", \"\");print}') | sed -e 's/^[ \\t]*//' | tail -n 1)\nelse\n    echo \"[ERROR] Unsupported operating system\"\n    exit 1\nfi", "num_lines": 134}
{"repo_name": "aws-imds-packet-analyzer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\npython3 -m pytest tests/ -v\nrm -r .pytest_cache\nrm -r src/__pycache__\nrm -r tests/__pycache__", "num_lines": 8}
{"repo_name": "aws-iot-device-sdk-arduino-yun", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# If input args not correct, echo usage\nif [ $# -ne 3 ]; then\n    echo \"usage: ./AWSIoTArduinoYunInstallAll.sh <Board IP> <UserName> <Board Password>\"\nelse\n# Welcoming prompt\n    echo \"This script will install all of the depencies and upload the codebase and credentials to the targeted Arduino Yun Board for the AWS IoT Arduino Yun SDK, which includes:\"\n    echo \"- Install dependencies\"\n    echo \"- Upload codebase\"\n    echo \"- Upload credentials\"\n    echo \"Please make sure you have included your credentials (private key, certificate and rootCA) in AWS-IoT-Python-Runtime/certs/\"\n# Load in params\n    yunBoardIP=$1\n    yunBoardUserName=$2\n    yunBoardPassword=$3\n    pyLibDir=\"./AWS-IoT-Python-Runtime\"\n    certsDir=\"$pyLibDir/certs\"\n# Check to see if AWS-IoT-Python-Runtime/certs/ is empty\n    if [ \"`ls -A $certsDir`\" = \"\" ]; then\n\techo -e \"\\nIt seems there are no credentials in $certsDir. Please generate your credentials and put them in that directory.\\n\"\n\texit\n    fi\n# Change permission of functional scripts\n    echo \"Changing permissions for functional scripts...\"\n    chmod 755 AWSIoTArduinoYunScp.sh\n    chmod 755 AWSIoTArduinoYunSetupEnvironment.sh\n    echo \"Done.\"\n# Now start uploading codebase and credentials\n    echo \"Uploading codebase and credentials...\"\n    ./AWSIoTArduinoYunScp.sh $yunBoardIP $yunBoardUserName $yunBoardPassword $pyLibDir /root/\n    echo \"Done.\"\n# Now start installing codebase on Arduino Yun Board\n    echo \"Installing dependencies on Arduino Yun...\"\n    ./AWSIoTArduinoYunSetupEnvironment.sh $yunBoardIP $yunBoardUserName $yunBoardPassword\n    echo \"Done.\"\n# End of this script\n    echo \"Execution completed!\"\nfi", "num_lines": 38}
{"repo_name": "aws-iot-device-sdk-arduino-yun", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect\n# This script helps to upload the targeted file/directory to remote Arduino Yun Board\n\n# Args check\nif {$argc!= 5} {\n    send_user \"usage: ./AWSIoTArduinoYunScp.sh <Board IP> <UserName> <Board Password> <File> <Destination>\\n\"\n    exit\n}\n\nset timeout 10\nset ArduinoYunIPAddress [lindex $argv 0]\nset ArduinoYunUserName [lindex $argv 1]\nset ArduinoYunPassword [lindex $argv 2]\nset TargetFile [lindex $argv 3]\nset Destination [lindex $argv 4]\nset RemoteEndpoint \"$ArduinoYunUserName@$ArduinoYunIPAddress:$Destination\"\n\nsend_user \"Arduino Yun IP is: $ArduinoYunIPAddress\\n\"\nsend_user \"Arduino Yun User Name is: $ArduinoYunUserName\\n\"\nsend_user \"\\nNow start transmitting $TargetFile to remote directory: $RemoteEndpoint ...\\n\"\n\n# scp automatically creates the missing directory\nspawn scp -r $TargetFile $RemoteEndpoint\nexpect {\n    # In case this is the first time\n    -re \".*yes/no.*\" {\n        send \"yes\\r\"; exp_continue\n\t-re \".*assword.*\" { send  \"$ArduinoYunPassword\\r\" }\n    }\n    -re \".*assword.*\" { send \"$ArduinoYunPassword\\r\" }\n}\nexpect {\n    eof {\n\tsend_user \"Completed!\\n\"\n    }\n}", "num_lines": 36}
{"repo_name": "aws-iot-device-sdk-arduino-yun", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect\n# This script helps to upload the targeted file/directory to remote Arduino Yun Board\n\n# Args check\nif {$argc!= 3} {\n    send_user \"usage: ./AWSIoTArduinoYunScp.sh <Board IP> <UserName> <Board Password>\\n\"\n    exit\n}\n\nset timeout -1\nset ArduinoYunIPAddress [lindex $argv 0]\nset ArduinoYunUserName [lindex $argv 1]\nset ArduinoYunPassword [lindex $argv 2]\nset RemoteEndpoint \"$ArduinoYunUserName@$ArduinoYunIPAddress\"\n\nsend_user \"Arduino Yun IP is: $ArduinoYunIPAddress\\n\"\nsend_user \"Arduino Yun User Name is: $ArduinoYunUserName\\n\"\nsend_user \"\\nThe following dependencies will be remotely installed on Arduino Yun:\\n\"\nsend_user \"distribute\\npython-openssl\\n\\n\"\nsend_user \"Please wait until the installation completes and the program exits.\\n\\n\"\n\n# ssh into Arduino Yun and automatically perform the installation\nspawn ssh $RemoteEndpoint\nexpect {\n    # In case this is the first time\n    -re \".*yes/no.*\" {\n        send \"yes\\r\"; exp_continue\n\t-re \".*assword.*\" { send  \"$ArduinoYunPassword\\r\" }\n    }\n    -re \".*assword.*\" { send \"$ArduinoYunPassword\\r\" }\n}\n# Install all dependencies\nexpect \"*~#\" { send \"opkg update\\r\" }\nexpect \"*~#\" { send \"opkg install distribute\\r\" }\nexpect \"*~#\" { send \"opkg install python-openssl\\r\" }\nexpect \"*~#\" { send \"easy_install pip\\r\" }\nexpect \"*~#\" { send \"pip install AWSIoTPythonSDK==1.0.0\\r\" }\nexpect \"*~#\" { send \"exit\\r\" }\n# End of installation\ninteract\n", "num_lines": 41}
{"repo_name": "aws-iot-device-sdk-arduino-yun", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/expect\n# This script helps to upload the targeted file/directory to remote Arduino Yun Board\n\n# Args check\nif {$argc!=5} {\n\tsend_user \"usage: ./AWSIoTArduinoYunWebsocketCredentialConfig.sh <Board IP> <UserName> <Board Password> <AWS_ACCESS_KEY_ID> <AWS_SECRET_ACCESS_KEY>\\n\"\n\texit\n}\n\nset timeout 10\nset ArduinoYunIPAddress [lindex $argv 0]\nset ArduinoYunUserName [lindex $argv 1]\nset ArduinoYunPassword [lindex $argv 2]\nset AWS_ACCESS_KEY_ID [lindex $argv 3]\nset AWS_SECRET_ACCESS_KEY [lindex $argv 4]\nset RemoteEndpoint \"$ArduinoYunUserName@$ArduinoYunIPAddress\"\nset profileFullPath \"/etc/profile\"\n\nsend_user \"Arduino Yun IP is: $ArduinoYunIPAddress\\n\"\nsend_user \"Arduino Yun User Name is: $ArduinoYunUserName\\n\"\nsend_user \"New environment variables will be added to Arduino Yun:\\n\"\nsend_user \"AWS_ACCESS_KEY_ID: $AWS_ACCESS_KEY_ID\\n\"\nsend_user \"AWS_SECRET_ACCESS_KEY: $AWS_SECRET_ACCESS_KEY\\n\"\nsend_user \"$profileFullPath will be modified.\\n\"\nsend_user \"Please wati until the program exits.\\n\\n\"\n\n# ssh into Arduino Yun and modify $profileFullPath\nspawn ssh $RemoteEndpoint\nexpect {\n    # In case this is the first time\n    -re \".*yes/no.*\" {\n        send \"yes\\r\"; exp_continue\n\t-re \".*assword.*\" { send  \"$ArduinoYunPassword\\r\" }\n    }\n    -re \".*assword.*\" { send \"$ArduinoYunPassword\\r\" }\n}\n# Insert new environment variables\nexpect \"*~#\" {\n\t# In case we need to update credentials\n\t# Remove the existing AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY\n\tsend \"sed -i '/^export AWS_ACCESS_KEY_ID=/'d /etc/profile\\r\"\n\tsend \"sed -i '/^export AWS_SECRET_ACCESS_KEY=/'d /etc/profile\\r\"\n\t# Append the new credentials to the end of the file\n\tsend \"echo export AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID >> /etc/profile\\r\"\n\tsend \"echo export AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY >> /etc/profile\\r\"\n\t# Enable the new profile\n\tsend \"source /etc/profile\\r\"\n}\nexpect \"*~#\" { send \"exit\\r\" }\n# Notification to the user to power-cycle the board\nsend_user \"Credentials added to Yun as environment variables. Now please power-cycle the board.\"\nsend_user \"Exiting...\"\n# End of the configuration\ninteract\n\n\n\n", "num_lines": 58}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ -z $CLANG_FORMAT ]] ; then\n    CLANG_FORMAT=clang-format\nfi\n\nif NOT type $CLANG_FORMAT 2> /dev/null ; then\n    echo \"No appropriate clang-format found.\"\n    exit 1\nfi\n\nFAIL=0\nSOURCE_FILES=`find deviceadvisor devicedefender discovery eventstream_rpc greengrass_ipc identity iotdevicecommon jobs shadow samples secure_tunneling -type f \\( -name '*.h' -o -name '*.cpp' \\)`\nfor i in $SOURCE_FILES\ndo\n    $CLANG_FORMAT -output-replacements-xml $i | grep -c \"<replacement \" > /dev/null\n    if [ $? -ne 1 ]\n    then\n        echo \"$i failed clang-format check.\"\n        FAIL=1\n    fi\ndone\n\nexit $FAIL\n", "num_lines": 25}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "set -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/secure_tunneling/tests\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\ntunnel_info=$(aws iotsecuretunneling open-tunnel --destination-config services=ssh,ssh2,ssh3 --timeout-config maxLifetimeTimeoutMinutes=10) && echo -e \"$tunnel_info\" > /tmp/tunnel_info.pem\n\nexport SECTUN_SOURCE_TOKEN=$(sed '4!d' /tmp/tunnel_info.pem | cut -d'\"' -f4)\nexport SECTUN_DESTINATION_TOKEN=$(sed '5!d' /tmp/tunnel_info.pem | cut -d'\"' -f4)\nexport SECTUN_ENDPOINT=\"data.tunneling.iot.us-east-1.amazonaws.com\"\n\necho \"Running Secure Tunnel Test\"\n./secure_tunnel_test\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/mqtt/basic_connect\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Basic Connect test\"\n./basic-connect --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem\n\npopd\n\npushd $CODEBUILD_SRC_DIR/samples/mqtt/websocket_connect\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\necho \"Websocket test\"\n./websocket-connect --endpoint $ENDPOINT --signing_region us-east-1\n\npopd\n", "num_lines": 32}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/mqtt/custom_authorizer_connect\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_NAME=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_PASSWORD=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Custom Authorizer Connnect Test\"\n./custom-authorizer-connect --endpoint $ENDPOINT --custom_auth_authorizer_name $AUTH_NAME --custom_auth_password $AUTH_PASSWORD\n\npopd\n", "num_lines": 22}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\npushd $CODEBUILD_SRC_DIR/samples/mqtt/pkcs11_connect\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\n# from hereon commands are echoed. don't leak secrets\nset -x\n\nsofthsm2-util --version\n\n# SoftHSM2's default tokendir path might be invalid on this machine\n# so set up a conf file that specifies a known good tokendir path\nmkdir -p /tmp/tokens\nexport SOFTHSM2_CONF=/tmp/softhsm2.conf\necho \"directories.tokendir = /tmp/tokens\" > /tmp/softhsm2.conf\n\n# create token\nsofthsm2-util --init-token --free --label my-token --pin 0000 --so-pin 0000\n\n# add private key to token (must be in PKCS#8 format)\nopenssl pkcs8 -topk8 -in /tmp/privatekey.pem -out /tmp/privatekey.p8.pem -nocrypt\nsofthsm2-util --import /tmp/privatekey.p8.pem --token my-token --label my-key --id BEEFCAFE --pin 0000\n\n# run sample\n./pkcs11-connect --endpoint $ENDPOINT --cert /tmp/certificate.pem --pkcs11_lib /usr/lib/softhsm/libsofthsm2.so --pin 0000 --token_label my-token --key_label my-key\n\npopd\n", "num_lines": 37}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/pub_sub/basic_pub_sub\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"PubSub test\"\n./basic-pub-sub --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem\n\npopd\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\n# build package\ncd $CODEBUILD_SRC_DIR\n\ngit submodule update --init --recursive\nmkdir build\ncd build\n\nmkdir -p /tmp/install\n\ncmake -DCMAKE_INSTALL_PREFIX=/tmp/install -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\nmake install\n\ncd ..\n\ncert=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/cert\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$cert\" > /tmp/certificate.pem\nkey=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/key\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key\" > /tmp/privatekey.pem\nkey_p8=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/keyp8\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key_p8\" > /tmp/privatekey_p8.pem\n", "num_lines": 25}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/shadow/shadow_sync\n\nmkdir _build\ncd _build\ncmake -DCMAKE_PREFIX_PATH=/tmp/install ..\nmake -j\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Shadow-Sync test\"\n./shadow-sync --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --thing_name CI_CodeBuild_Thing --is_ci true\n\npopd\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-cpp-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euxo pipefail\n\n# Redirect output to stderr.\nexec 1>&2\n\nRELEASE_TYPE=\"$1\"\nRELEASE_TITLE=\"$2\"\n\n# Make sure there are ONLY two arguments\nif [ \"$#\" != \"2\" ]; then\n    echo \"ERROR: Arguments passed is NOT equal to two!\"\n    exit 1\nfi\n\npushd $(dirname $0) > /dev/null\n\n# Get the current version\ngit checkout main\n\ngit_tags=$(git tag)\ncurrent_version=$(python3 ./update_semantic_version.py  --version \"${git_tags}\" --type MINOR --parse_latest_version true)\ncurrent_version_without_v=$(echo ${current_version} | cut -f2 -dv)\n\necho \"Current release version is ${current_version_without_v}\"\n\n# Validate that RELEASE_TYPE is what we expect and bump the version\nnew_version=$(python3 ./update_semantic_version.py --version \"${current_version_without_v}\" --type \"${RELEASE_TYPE}\")\nif [ \"$new_version\" == \"0.0.0\" ]; then\n    echo \"ERROR: Unknown release type! Exitting...\"\n    exit -1\nfi\necho \"New version is ${new_version}\"\n\n# Validate that the title is set\nif [ \"$RELEASE_TITLE\" == \"\" ]; then\n    echo \"ERROR: No title set! Cannot make release. Exitting...\"\n    exit -1\nfi\n\n# Setup Github credentials\ngit config --local user.email \"aws-sdk-common-runtime@amazon.com\"\ngit config --local user.name \"GitHub Actions\"\n\n# Update version-sensitive files\n# --==--\nnew_version_branch=AutoTag-v${new_version}\ngit checkout -b ${new_version_branch}\n\n# Update version file\necho \"${new_version}\" > ../VERSION\ngit add ../VERSION\n# Update the version in the README to show the latest\nsed -i -r \"s/.*Latest released version:.*/Latest released version: v${new_version}/\" ../README.md\ngit add ../README.md\n# Make the commit\ngit commit -m \"[v$new_version] $RELEASE_TITLE\"\n\n# push the commit and create a PR\ngit push -u \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-cpp-v2.git\" ${new_version_branch}\ngh pr create --title \"AutoTag PR for v${new_version}\" --body \"AutoTag PR for v${new_version}\" --head ${new_version_branch}\n\n# Merge the PR\ngh pr merge --admin --squash\n# --==--\n\n# Update local state with the merged pr (if one was made) and just generally make sure we're up to date\ngit fetch\ngit checkout main\ngit pull \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-cpp-v2.git\" main\n\n# Create new tag on latest commit (lightweight tag - we do NOT want an annotated tag)\ngit tag -f v${new_version}\n# Push new tag to github\ngit push \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-cpp-v2.git\" --tags\n\n# Determine if this is a pre-release or not based on the major version\nIS_PRE_RELEASE=\"false\"\nVERSION_STRING_DELIMITER=.\nVERSION_STRING_ARRAY=($(echo \"$new_version\" | tr $VERSION_STRING_DELIMITER '\\n'))\nif [ \"${VERSION_STRING_ARRAY[0]}\" == \"0\" ]; then\n    IS_PRE_RELEASE=\"true\"\nelse\n    IS_PRE_RELEASE=\"false\"\nfi\n\n# Create the release with auto-generated notes as the description\n# - NOTE: This will only add notes if there is at least one PR. If there is no PRs,\n# - then this will be blank and need manual input/changing after running.\nif [ $IS_PRE_RELEASE == \"true\" ]; then\n    gh release create \"v${new_version}\" -p --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nelse\n    gh release create \"v${new_version}\" --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nfi\n\npopd > /dev/null\n", "num_lines": 98}
{"repo_name": "aws-iot-device-sdk-java", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nset -x\n# force a failure if there's no tag\ngit describe --tags\n# now get the tag\nCURRENT_TAG=$(git describe --tags | cut -f2 -dv)\n# convert v0.2.12-2-g50254a9 to 0.2.12\nCURRENT_TAG_VERSION=$(git describe --tags | cut -f1 -d'-' | cut -f2 -dv)\n# if there's a hash on the tag, then this is not a release tagged commit\nif [ \"$CURRENT_TAG\" != \"$CURRENT_TAG_VERSION\" ]; then\n    echo \"Current tag version is not a release tag, cut a new release if you want to publish.\"\n    exit 1\nfi\n\nPUBLISHED_TAG_VERSION=$(curl -s \"https://repo.maven.apache.org/maven2/com/amazonaws/aws-iot-device-sdk-java/maven-metadata.xml\" | grep \"<latest>\" | cut -f2 -d \">\" | cut -f1 -d \"<\")\nif [ \"$PUBLISHED_TAG_VERSION\" == \"$CURRENT_TAG_VERSION\" ]; then\n    echo \"$CURRENT_TAG_VERSION is already in Sonatype, cut a new tag if you want to upload another version.\"\n    exit 1\nfi\n\necho \"$CURRENT_TAG_VERSION currently does not exist in Sonatype, allowing pipeline to continue.\"\nexit 0\n", "num_lines": 24}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\n# build java package\ncd $CODEBUILD_SRC_DIR\n\nulimit -c unlimited\nmvn compile\n", "num_lines": 12}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nVERSION_FILE_PATH=$1\nif [ ! readlink -e \"$VERSION_FILE_PATH\" ]; then\n    echo \"No VERSION file found! Cannot make release!\"\n    exit 1\nelse\n    echo \"VERSION file found...\"\nfi\nVERSION=$(cat $VERSION_FILE_PATH)\n\n# Make sure the version variable is populated\nif [ -z \"${VERSION}\" ]; then\n    echo \"VERSION file is empty!\"\n    exit 1\nelse\n    echo \"VERSION file contains: ${VERSION}\"\nfi\n\n# Make sure the version follows the correct format: major.minor.patch\nLENGTH_CHECK=\"${VERSION//[^.]}\"\nif [ ${#LENGTH_CHECK} != 2 ]; then\n    echo \"VERSION file contains invalid version (not in format major.minor.patch)\"\n    exit 1\nfi\n# Use RegX to ensure it only contains numbers and periods\nREGX_CHECK='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ $VERSION =~ $REGX_CHECK ]]; then\n    echo \"VERSION file contains valid version\"\nelse\n    echo \"VERSION file contains invalid version (RegX validator failed)\"\n    exit 1\nfi\n\n# Does Maven have the version? If so, do not allow it!\nPUBLISHED_TAG_VERSION=$(curl -s \"https://repo.maven.apache.org/maven2/software/amazon/awssdk/iotdevicesdk/aws-iot-device-sdk/maven-metadata.xml\" | grep \"<latest>\" | cut -f2 -d \">\" | cut -f1 -d \"<\")\nif [ \"$PUBLISHED_TAG_VERSION\" == \"$VERSION\" ]; then\n    echo \"$VERSION is already in Sonatype, cut a new tag if you want to upload another version.\"\n    exit 1\nfi\n\necho \"$VERSION currently does not exist in Sonatype, allowing pipeline to continue.\"\nexit 0\n", "num_lines": 44}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/CustomAuthorizerConnect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"unit-test/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nAUTH_NAME=$(aws secretsmanager get-secret-value --secret-id \"unit-test/authorizer-name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_PASSWORD=$(aws secretsmanager get-secret-value --secret-id \"unit-test/authorizer-password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Mqtt Connect with Custom Authorizer test\"\nmvn exec:java -Dexec.mainClass=\"customauthorizerconnect.CustomAuthorizerConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--custom_auth_authorizer_name,$AUTH_NAME,--custom_auth_password,$AUTH_PASSWORD\"\n\npopd\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/BasicConnect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Basic Mqtt (Direct) Connect test\"\nmvn exec:java -Dexec.mainClass=\"basicconnect.BasicConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey.pem,--cert,/tmp/certificate.pem\"\n\npopd\n\npushd $CODEBUILD_SRC_DIR/samples/WebsocketConnect\n\nmvn compile\n\necho \"Websocket Connect test\"\nmvn exec:java -Dexec.mainClass=\"websocketconnect.WebsocketConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--signing_region,us-east-1,--port,443\"\n\npopd\n", "num_lines": 27}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/CustomAuthorizerConnect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_NAME=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_PASSWORD=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Mqtt Connect with Custom Authorizer test\"\nmvn exec:java -Dexec.mainClass=\"customauthorizerconnect.CustomAuthorizerConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--custom_auth_authorizer_name,$AUTH_NAME,--custom_auth_password,$AUTH_PASSWORD\"\n\npopd\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/CustomKeyOpsConnect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Custom Key Ops test\"\nmvn exec:java -Dexec.mainClass=\"customkeyopsconnect.CustomKeyOpsConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey_p8.pem,--cert,/tmp/certificate.pem\"\n\npopd\n", "num_lines": 17}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/CustomKeyOpsConnect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"unit-test/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Custom Key Ops test\"\nmvn exec:java -Dexec.mainClass=\"customkeyopsconnect.CustomKeyOpsConnect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey_p8.pem,--cert,/tmp/certificate.pem\"\n\npopd\n", "num_lines": 17}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\npushd $CODEBUILD_SRC_DIR/samples/Pkcs11Connect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\n# from hereon commands are echoed. don't leak secrets\nset -x\n\nsofthsm2-util --version\n\n# SoftHSM2's default tokendir path might be invalid on this machine\n# so set up a conf file that specifies a known good tokendir path\nmkdir -p /tmp/tokens\nexport SOFTHSM2_CONF=/tmp/softhsm2.conf\necho \"directories.tokendir = /tmp/tokens\" > /tmp/softhsm2.conf\n\n# create token\nsofthsm2-util --init-token --free --label my-token --pin 0000 --so-pin 0000\n\n# add private key to token (must be in PKCS#8 format)\nopenssl pkcs8 -topk8 -in /tmp/privatekey.pem -out /tmp/privatekey.p8.pem -nocrypt\nsofthsm2-util --import /tmp/privatekey.p8.pem --token my-token --label my-key --id BEEFCAFE --pin 0000\n\n# run sample\nmvn exec:java -Dexec.mainClass=\"pkcs11connect.Pkcs11Connect\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--cert,/tmp/certificate.pem,--pkcs11_lib,/usr/lib/softhsm/libsofthsm2.so,--pin,0000,--token_label,my-token,--key_label,my-key\"\n\npopd\n", "num_lines": 32}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/BasicPubSub\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Basic PubSub test\"\nmvn exec:java -Dexec.mainClass=\"pubsub.PubSub\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey.pem,--cert,/tmp/certificate.pem\"\n\npopd\n", "num_lines": 18}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/Mqtt5/PubSub\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"MQTT5 PubSub test\"\nmvn exec:java -Dexec.mainClass=\"mqtt5.pubsub.PubSub\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey.pem,--cert,/tmp/certificate.pem\"\n\npopd\n", "num_lines": 18}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\n# build java package\ncd $CODEBUILD_SRC_DIR\n\nulimit -c unlimited\nmvn compile\nmvn install -DskipTests=true\n\ncert=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/cert\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$cert\" > /tmp/certificate.pem\nkey=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/key\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key\" > /tmp/privatekey.pem\nkey_p8=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/keyp8\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key_p8\" > /tmp/privatekey_p8.pem\n", "num_lines": 18}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/Shadow\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nmvn compile\n\necho \"Shadow test\"\nmvn exec:java -Dexec.mainClass=\"shadow.ShadowSample\" -Daws.crt.ci=\"True\" -Dexec.arguments=\"--endpoint,$ENDPOINT,--key,/tmp/privatekey.pem,--cert,/tmp/certificate.pem,--thing_name,CI_CodeBuild_Thing\"\n\npopd\n", "num_lines": 18}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get the S3 URL containing all of the MQTT5 testing environment variables passed in to the bash script\ntesting_env_bucket=$1\nregion=$2\n\n# Make sure we have something:\nif [ \"${testing_env_bucket}\" != \"\" ] && [ \"${region}\" != \"\" ]; then\n    echo \"S3 bucket for environment variables found and region\"\nelse\n    echo \"Could not get S3 bucket for environment variables and/or region.\"\n    echo \"You need to run this script and pass the S3 URL of the file containing\"\n    echo \"all of the environment variables to set, as well as the secrets for certificates and private keys\"\n    echo \"\"\n    echo \"Example: mqtt5_test_setup.sh s3://<bucket>/<file> <region>\"\n    echo \"\"\n    echo \"When finished, run 'cleanup' to remove the files downloaded:\"\n    echo \"\"\n    echo \"Example: mqtt5_test_setup.sh s3://<bucket>/<file> cleanup\"\n    echo \"\"\n    return 1\nfi\n\n# Is this just a request to clean up?\n# NOTE: This blindly assumes there is a environment_files.txt file\nif [ \"${region}\" != \"cleanup\" ]; then\n    sleep 0.1 # we have to do something to do an else...\nelse\n    echo \"Undoing environment variables\"\n    unset $(grep -v '^#' ${PWD}/environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    unset AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH\n    unset AWS_TEST_MQTT5_IOT_KEY_PATH\n\n    echo \"Cleaning up resources...\"\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    echo \"Success!\"\n    return 0\nfi\n\n# Get the file from S3\naws s3 cp ${testing_env_bucket} ${PWD}/environment_files.txt\ntesting_env_file=$( cat environment_files.txt )\n# Make sure we have data of some form\nif [ \"${testing_env_file}\" != \"\" ]; then\n    echo \"Environment variables secret found\"\nelse\n    echo \"Could not get environment variables from secrets!\"\n    return 1\nfi\n\n# Make all the variables in mqtt5_environment_variables.txt exported\n# so we can run MQTT5 tests\nexport $(grep -v '^#' environment_files.txt | xargs)\n\n# CRT/non-builder certificate and key processing\n# Get the certificate and key secrets (dumps straight to a file)\ncrt_cert_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_CERTIFICATE_FILE_SECRET}\" --query \"SecretString\" --region ${region} | cut -f2 -d\\\") && echo \"$crt_cert_file\" > ${PWD}/crt_certificate.pem\ncrt_key_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_KEY_FILE_SECRET}\" --query \"SecretString\" --region ${region} | cut -f2 -d\\\") && echo \"$crt_key_file\" > ${PWD}/crt_privatekey.pem\n# Does the certificate file have data? If not, then abort!\nif [ \"${crt_cert_file}\" != \"\" ]; then\n    echo \"CRT Certificate secret found\"\nelse\n    echo \"Could not get CRT certificate from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n\n    return 1\nfi\n# Does the private key file have data? If not, then abort!\nif [ \"${crt_key_file}\" != \"\" ]; then\n    echo \"CRT Private key secret found\"\nelse\n    echo \"Could not get CRT private key from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n\n    return 1\nfi\n# Set the certificate and key paths (absolute paths for best compatbility)\nexport AWS_TEST_MQTT5_CERTIFICATE_FILE=\"${PWD}/crt_certificate.pem\"\nexport AWS_TEST_MQTT5_KEY_FILE=\"${PWD}/crt_privatekey.pem\"\n\n\n# IoT/Builder certificate and key processing\n# Get the certificate and key secrets (dumps straight to a file)\niot_cert_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH_SECRET}\" --region ${region} --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$iot_cert_file\" > ${PWD}/iot_certificate.pem\niot_key_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_IOT_KEY_PATH_SECRET}\" --region ${region} --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$iot_key_file\" > ${PWD}/iot_privatekey.pem\n# Does the certificate file have data? If not, then abort!\nif [ \"${iot_cert_file}\" != \"\" ]; then\n    echo \"IoT Certificate secret found\"\nelse\n    echo \"Could not get IoT certificate from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    return 1\nfi\n# Does the private key file have data? If not, then abort!\nif [ \"${iot_key_file}\" != \"\" ]; then\n    echo \"IoT Private key secret found\"\nelse\n    echo \"Could not get IoT private key from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    return 1\nfi\n# Set IoT certificate and key paths\nexport AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH=\"${PWD}/iot_certificate.pem\"\nexport AWS_TEST_MQTT5_IOT_KEY_PATH=\"${PWD}/iot_privatekey.pem\"\n\n# Everything is set\necho \"Success: Environment variables set!\"\n", "num_lines": 145}
{"repo_name": "aws-iot-device-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euxo pipefail\n\n# Redirect output to stderr.\nexec 1>&2\n\nRELEASE_TYPE=\"$1\"\nRELEASE_TITLE=\"$2\"\n\n# Make sure there are ONLY two arguments\nif [ \"$#\" != \"2\" ]; then\n    echo \"ERROR: Arguments passed is NOT equal to two!\"\n    exit 1\nfi\n\npushd $(dirname $0) > /dev/null\n\n# Get the current version\ngit checkout main\n\ngit_tags=$(git tag)\ncurrent_version=$(python3 ./update_semantic_version.py  --version \"${git_tags}\" --type MINOR --parse_latest_version true)\ncurrent_version_without_v=$(echo ${current_version} | cut -f2 -dv)\n\necho \"Current release version is ${current_version_without_v}\"\n\n# Validate that RELEASE_TYPE is what we expect and bump the version\nnew_version=$(python3 ./update_semantic_version.py --version \"${current_version_without_v}\" --type \"${RELEASE_TYPE}\")\nif [ \"$new_version\" == \"0.0.0\" ]; then\n    echo \"ERROR: Unknown release type! Exitting...\"\n    exit -1\nfi\necho \"New version is ${new_version}\"\n\n# Validate that the title is set\nif [ \"$RELEASE_TITLE\" == \"\" ]; then\n    echo \"ERROR: No title set! Cannot make release. Exitting...\"\n    exit -1\nfi\n\n# Setup Github credentials\ngit config --local user.email \"aws-sdk-common-runtime@amazon.com\"\ngit config --local user.name \"GitHub Actions\"\n\n# Update version-sensitive files\n# --==--\nnew_version_branch=AutoTag-v${new_version}\ngit checkout -b ${new_version_branch}\n\n# Go from utils to the main folder\ncd ..\n# Update the SDK version text and the SDK version in samples\npython3 ./update-crt.py\npython3 ./update-crt.py ${new_version} --update_sdk_text\npython3 ./update-crt.py ${new_version} --update_samples\n# Update the version in the README to show the latest\nsed -i -r \"s/.*Latest released version:.*/Latest released version: v${new_version}/\" README.md\n# Not sure how to do this better, so just add each file individually\ngit add sdk/pom.xml\ngit add README.md\ngit add android/iotdevicesdk/build.gradle\n# Add all the sample pom files\nfind . -name \"pom.xml\" -maxdepth 3 -mindepth 3 -exec git add {} +\n# go back to the utils folder\ncd utils\n\n# Make the commit\ngit commit -m \"[v$new_version] $RELEASE_TITLE\"\n\n# push the commit and create a PR\ngit push -u \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-java-v2.git\" ${new_version_branch}\ngh pr create --title \"AutoTag PR for v${new_version}\" --body \"AutoTag PR for v${new_version}\" --head ${new_version_branch}\n\n# Merge the PR\ngh pr merge --admin --squash\n# --==--\n\n# Update local state with the merged pr (if one was made) and just generally make sure we're up to date\ngit fetch\ngit checkout main\ngit pull \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-java-v2.git\" main\n\n# Create new tag on latest commit (lightweight tag - we do NOT want an annotated tag)\ngit tag -f v${new_version}\n# Push new tag to github\ngit push \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-java-v2.git\" --tags\n\n# Determine if this is a pre-release or not based on the major version\nIS_PRE_RELEASE=\"false\"\nVERSION_STRING_DELIMITER=.\nVERSION_STRING_ARRAY=($(echo \"$new_version\" | tr $VERSION_STRING_DELIMITER '\\n'))\nif [ \"${VERSION_STRING_ARRAY[0]}\" == \"0\" ]; then\n    IS_PRE_RELEASE=\"true\"\nelse\n    IS_PRE_RELEASE=\"false\"\nfi\n\n# Create the release with auto-generated notes as the description\n# - NOTE: This will only add notes if there is at least one PR. If there is no PRs,\n# - then this will be blank and need manual input/changing after running.\nif [ $IS_PRE_RELEASE == \"true\" ]; then\n    gh release create \"v${new_version}\" -p --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nelse\n    gh release create \"v${new_version}\" --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nfi\n\npopd > /dev/null\n", "num_lines": 109}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# force a failure if there's no tag\ngit describe --tags\n# now get the tag\nCURRENT_TAG=$(git describe --tags | cut -f2 -dv)\n# convert v0.2.12-2-g50254a9 to 0.2.12\nCURRENT_TAG_VERSION=$(git describe --tags | cut -f1 -d'-' | cut -f2 -dv)\n# if there's a hash on the tag, then this is not a release tagged commit\nif [ \"$CURRENT_TAG\" != \"$CURRENT_TAG_VERSION\" ]; then\n    echo \"Current tag version is not a release tag, cut a new release if you want to publish.\"\n    exit 1\nfi\n\nPUBLISHED_TAG_VERSION=`npm show aws-iot-device-sdk version`\nif [ \"$PUBLISHED_TAG_VERSION\" == \"$CURRENT_TAG_VERSION\" ]; then\n    echo \"$CURRENT_TAG_VERSION is already in npm, cut a new tag if you want to upload another version.\"\n    exit 1\nfi\n\necho \"$CURRENT_TAG_VERSION currently does not exist in npm, allowing pipeline to continue.\"\nexit 0\n", "num_lines": 24}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# force a failure if there's no tag\ngit describe --tags\n# now get the tag\nCURRENT_TAG=$(git describe --tags | cut -f2 -dv)\n# convert v0.2.12-2-g50254a9 to 0.2.12\nCURRENT_TAG_VERSION=$(git describe --tags | cut -f1 -d'-' | cut -f2 -dv)\n# if there's a hash on the tag, then this is not a release tagged commit\nif [ \"$CURRENT_TAG\" != \"$CURRENT_TAG_VERSION\" ]; then\n    echo \"Current tag version is not a release tag, cut a new release if you want to publish.\"\n    exit 1\nfi\n\nsed --in-place -E \"s/\\\"version\\\": \\\".+\\\"/\\\"version\\\": \\\"${CURRENT_TAG_VERSION}\\\"/\" package.json\n\nexit 0\n", "num_lines": 19}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n\nINTEGRATION_TEST_PATH=./integration-tests\n\nTEST_COUNT=0\n#\n# Run each integration test; if it exits with a non-zero status,\n# stop testing and return that status to the parent process.\n#\nfor file in `ls $INTEGRATION_TEST_PATH`\ndo\n#\n# Only run executable files.\n#\n   if [ -x $INTEGRATION_TEST_PATH/$file ]\n   then\n#\n# If not running in parallel mode, execute each test runner in sequence.\n#\n      if [ $PARALLEL_EXECUTION\"\" = \"\" ]\n      then\n         echo \"###################################################################\"\n         echo ${0##*/}\": running \"${file##*/}\"...\"\n         echo \"###################################################################\"\n         $INTEGRATION_TEST_PATH/$file\n         statusValue=$?\n         echo \"###################################################################\"\n         echo ${0##*/}\": complete, status=\"$statusValue\n         echo \"###################################################################\"\n         if [ $statusValue\"\" != 0 ]\n         then\n            exit $statusValue\"\"\n         fi\n      else\n#\n# If running in parallel mode, execute all test runners simultaneously.\n#\n         echo \"###################################################################\"\n         echo ${0##*/}\": running \"${file##*/}\" (parallel mode)...\"\n         echo \"###################################################################\"\n         $INTEGRATION_TEST_PATH/$file &\n         PIDS[$TEST_COUNT]=$!\n         NAMES[$TEST_COUNT]=${file##*/}\n         TEST_COUNT=$((TEST_COUNT+1))\n      fi\n   fi\ndone\n\nif [ $PARALLEL_EXECUTION\"\" != \"\" ]\nthen\n   COMBINED_EXIT_CODE=0\n#\n# Wait on all test runner processes.\n#\n   TEST_COUNT=0\n   for PID in \"${PIDS[@]}\"\n   do\n      wait \"$PID\"\n      EXIT_CODE=$?\n      echo \"###################################################################\"\n      echo ${NAMES[$TEST_COUNT]}\" complete, status=\"$EXIT_CODE\n      echo \"###################################################################\"\n      TEST_COUNT=$((TEST_COUNT+1))\n      COMBINED_EXIT_CODE=$((EXIT_CODE | COMBINED_EXIT_CODE))\n   done\n   echo \"###################################################################\"\n   echo ${0##*/}\": all test runners complete, status=\"$COMBINED_EXIT_CODE\n   echo \"###################################################################\"\n   exit $COMBINED_EXIT_CODE\nelse\n#\n# All test runners have completed successfully, exit with status 0\n#\n   exit 0\nfi\n", "num_lines": 77}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Master integration test runner for the AWS IoT Node.js device SDK.\n#\n# USAGE\n#\n#     run-tests.sh <authentication-type>\n#\n# PARAMETERS\n#\n#                        <authentication-type> : [websocket|certificate|custom-auth]\n#\n# This program will first validate the given parameters, then attempt to\n# retrieve required secrets from AWS secrets manager; if both are successful, it\n# will execute all of the scripts under the 'integration-tests' directory\n# until either one of them exits with a non-zero status, or they have all\n# been executed.  If this program exits with a zero status, that indicates\n# that both the test setup and the test execution was successful.\n#\n# RETURNS\n#\n#     0 if successful, non-zero otherwise\n#\n# SECRET HANDLING\n#\n# This script handles retrieving secrets from AWS secrets manager; for\n# websocket authentication, it will place the appropriate values in the AWS_ACCESS_KEY_ID\n# and AWS_SECRET_ACCESS_KEY environment variables used by the SDK.  For\n# certificate authentication, the certificate and private key will be stored\n# in PEM-format temporary files, along with the root CA certificate;\n# the files are named according to the default naming convention\n# specified in the README.md, and the following environment variable points\n# to their location:\n#\n#    CERT_DIR\n#\n# Temporary certificate and private key files are deleted after running the\n# individual test runner scripts.\n#\n#\n\n#\n# Set a randomized directory name to isolate this test run from others\n# in the same environment and make it available to sub-scripts via export.\n#\nexport NPMTEST_DIR=\"/tmp/npmtest-\"$RANDOM\n\n#\n# Validate arguments\n#\nif [ $# -eq 1 ]\nthen\n   export AUTHENTICATION_TYPE=$1\n\n   if [ $AUTHENTICATION_TYPE\"\" != \"websocket\" ] && \\\n      [ $AUTHENTICATION_TYPE\"\" != \"certificate\" ] && \\\n      [ $AUTHENTICATION_TYPE\"\" != \"custom-auth\" ]\n   then\n       echo ${0##*/}\": authentication-type must be one of [websocket|certificate|custom-auth]\"\n       exit 2\n   fi\n   export LONG_RUNNING_TEST=\"\"\nelse\n   echo ${0##*/}\" <authentication-type>\"\n   exit 1\nfi\n\n#\n# Set node/npm paths\nNODE=`which node`\nif [ ! -x $NODE\"\" ]\nthen\n   echo ${0##*/}\": can't find node, exiting...\"\n   exit 1\nfi\n\nNPM=`which npm`\nif [ ! -x $NPM\"\" ]\nthen\n   echo ${0##*/}\": can't find npm, exiting...\"\n   exit 1\nfi\n\n#\n# node-gyp requires that $HOME be defined\n#\n#export HOME=$PWD\n\n#\n# This script will run all of the programs under the integration-tests directory until\n# either one executes with a non-zero status or they have all been run.\n#\nRUN_INTEGRATION_TESTS='./run-integration-tests.sh'\n\n#\n# Install the Node.js SDK under a new temporary directory.\n#\necho \"Running integration tests in ${NPMTEST_DIR}\"\nmkdir -p $NPMTEST_DIR\n(cp -r ../../aws-iot-device-sdk-js $NPMTEST_DIR; cd $NPMTEST_DIR)\nif [ $? != \"0\" ]\nthen\n   echo \"###################################################################\"\n   echo ${0##*/}\": unable to copy iot sdk to test directory!\"\n   echo \"###################################################################\"\n   exit 4\nfi\n\n#\n# Attempt an npm install of the AWS Node.js SDK for control plane access for creating test jobs\n#\n(cd $NPMTEST_DIR/aws-iot-device-sdk-js; $NPM install aws-sdk)\nif [ $? != \"0\" ]\nthen\n   echo \"###################################################################\"\n   echo ${0##*/}\": unable to npm install aws-sdk!\"\n   echo \"###################################################################\"\n   exit 4\nfi\n\n\n#\n# Attempt an npm install of the Node.js SDK\n#\n(cd $NPMTEST_DIR/aws-iot-device-sdk-js; $NPM install)\nif [ $? != \"0\" ]\nthen\n   echo \"###################################################################\"\n   echo ${0##*/}\": unable to npm install aws iot device sdk!\"\n   echo \"###################################################################\"\n   exit 4\nfi\n\n#\n# The SDK installed without errors; now, retrieve credentials\n#\necho \"###################################################################\"\necho ${0##*/}\": retrieving AWS credentials from AWS SecretsManager\"\necho \"###################################################################\"\n# fetch secret value and strip quotes with sed\nprincipal=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id V1IotSdkIntegrationTestWebsocketAccessKeyId --query SecretString | sed -n 's/^\"\\(.*\\)\"/\\1/p')\nif [ $? == \"0\" ]\nthen\n    echo ${0##*/}\": retrieved ws testing access key id\"\nelse\n    echo ${0##*/}\": couldn't retrieve ws testing access key id!\"\n    exit 5\nfi\n\n# fetch secret value and strip quotes with sed\ncredential=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id V1IotSdkIntegrationTestWebsocketSecretAccessKey --query SecretString | sed -n 's/^\"\\(.*\\)\"/\\1/p')\nif [ $? == \"0\" ]\nthen\n    echo ${0##*/}\": retrieved ws testing secret access key\"\nelse\n    echo ${0##*/}\": couldn't retrieve ws testing secret access key!\"\n    exit 6\nfi\n\ncase $AUTHENTICATION_TYPE\"\" in\n\n   websocket)\n       export AWS_ACCESS_KEY_ID=$principal\n       export AWS_SECRET_ACCESS_KEY=$credential\n\n       $RUN_INTEGRATION_TESTS\n       exit $?\n       ;;\n\n   custom-auth)\n       echo \"###################################################################\"\n       echo ${0##*/}\": setting custom-auth credentials\"\n       echo \"###################################################################\"\n\n       # We need the custom authorization headers to use custom authorization, but we will verify via username and password\n       export CUSTOM_AUTH_HEADERS=\"{}\"\n       export CUSTOM_AUTH_NAME=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id \"unit-test/authorizer-name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n       export CUSTOM_AUTH_PASSWORD=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id \"unit-test/authorizer-password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\n       $RUN_INTEGRATION_TESTS\n       exit $?\n       ;;\n\n   certificate)\n       export JOBS_AWS_ACCESS_KEY_ID=$principal\n       export JOBS_AWS_SECRET_ACCESS_KEY=$credential\n\n       export CERT_DIR=$NPMTEST_DIR/certs\n       mkdir -p $CERT_DIR\n       echo \"###################################################################\"\n       echo ${0##*/}\": retrieving certificate credentials from AWS Secrets Manager\"\n       echo \"###################################################################\"\n\n       # fetch secret value, strip quotes and replace \"\\n\" with an actual newline\n       aws --region us-east-1 secretsmanager get-secret-value --secret-id V1IotSdkIntegrationTestCertificate --query SecretString | sed -n 's/^\"\\(.*\\)\"/\\1/p' | sed 's/\\\\n/\\\n/g' > $CERT_DIR/certificate.pem.crt\n       if [ $? == \"0\" ]\n       then\n\t   echo ${0##*/}\": retrieved Certificate\"\n       else\n\t   echo ${0##*/}\": couldn't retrieve Certificate!\"\n\t   exit 5\n       fi\n\n       # fetch secret value, strip quotes and replace \"\\n\" with an actual newline\n       aws --region us-east-1 secretsmanager get-secret-value --secret-id V1IotSdkIntegrationTestPrivateKey --query SecretString | sed -n 's/^\"\\(.*\\)\"/\\1/p' | sed 's/\\\\n/\\\n/g' > $CERT_DIR/private.pem.key\n       if [ $? == \"0\" ]\n       then\n\t   echo ${0##*/}\": retrieved Private Key\"\n       else\n\t   echo ${0##*/}\": couldn't retrieve Private Key!\"\n\t   exit 6\n       fi\n\n       #\n       # Retrieve the root CA certificate\n       #\n       curl -s 'https://www.amazontrust.com/repository/AmazonRootCA1.pem' > $CERT_DIR/root-CA.crt\n       if [ $? == \"0\" ]\n       then\n\t   echo ${0##*/}\": retrieved root CA certificate\"\n       else\n\t   echo ${0##*/}\": couldn't retrieve root CA certificate!\"\n\t   exit 7\n       fi\n\n       $RUN_INTEGRATION_TESTS\n       exit $?\n       ;;\n\n   *)\n       echo ${0##*/}\": unsupported authentication type (\"$AUTHENTICATION_TYPE\")\"\n       ;;\nesac\n", "num_lines": 236}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run the device-mode integration test.\n#\n#\n# Check to make sure the top-level test directory is defined.\n#\nif [ $NPMTEST_DIR\"\" = \"\" ]\nthen\n   echo ${0##*/}\": NPMTEST_DIR must be defined!\"\n   exit 1\nfi\n#\n# Set the name of the node executable (it should be in our path)\n#\nNODE=node\n#\n# Set a randomized test tag to isolate this test run from others within\n# the AWS account associated with our Odin material set.  This ensures\n# that all topic names used are unique to this test run.\n#\nTEST_TAG=\"test-\"$RANDOM\n#\n# Capture the exit code of the first command which fails in a pipeline.\n#\nset -o pipefail\n#\n# The integration tests pass a number of updates between two partner\n# processes.  Because these are QoS 0, delivery isn't guaranteed, but\n# we should expect to receive most of them.  All tests use the same number\n# of updates (48).\n#\nRECEIVES_REQUIRED=46\nTRANSMITS_TOTAL=48\nexport HOSTNAME=\"ajje7lpljulm4-ats.iot.us-east-1.amazonaws.com\"\nexport CUSTOM_AUTH_HOST=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id \"unit-test/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n#\n# Process output will be captured in these files.\n#\nPROC1_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-1.out\nPROC2_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-2.out\n#\n# Move the test javascript program to the installed SDK\n# directory\n#\nINT_TEST_DIR=$NPMTEST_DIR/aws-iot-device-sdk-js/integration-test\nmkdir -p $INT_TEST_DIR\ncp ${0%/*}/device-integration-test.js $INT_TEST_DIR\n#\n# Start the two partner processes for the device-mode integration test and\n# save their PIDs.\n#\nif [ $AUTHENTICATION_TYPE\"\" == \"certificate\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running device integration test (certificate auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $HOSTNAME -f $CERT_DIR -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $HOSTNAME  -f $CERT_DIR -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\nelif [ $AUTHENTICATION_TYPE\"\" == \"custom-auth\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running device integration test (websocket/custom auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\nelse\n    echo \"###################################################################\"\n    echo ${0##*/}\": running device integration test (websocket/sigv4)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $HOSTNAME -P=wss -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\n    $NODE $INT_TEST_DIR/device-integration-test.js -H $HOSTNAME -P=wss -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\nfi\n#\n# Wait on the two partner processes and record their exit codes.\n#\nwait $PROC1_PID\nPROC1_EXIT_CODE=$?\nwait $PROC2_PID\nPROC2_EXIT_CODE=$?\n#\n# Combine the two exit codes; if either process exited abnormally, this\n# test is a failure.\n#\nCOMBINED_EXIT_CODE=$((PROC1_EXIT_CODE | PROC_2_EXIT_CODE))\nif [ $COMBINED_EXIT_CODE\"\" = \"0\" ]\nthen\n   numReceived=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $1}'`\n   receiveMask=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $4}'|sed -e 's/.*=//'`\n\n   echo $numReceived\" messages received, receive mask [\"$receiveMask\"]\"\n\n   if [ $numReceived\"\" -gt $RECEIVES_REQUIRED\"\" ]\n   then\n      echo \"########################################################\"\n      echo \"   TEST SUCCEEDED: RECEIVED \"$numReceived\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"########################################################\"\n   else\n      echo \"########################################################\"\n      echo \"   TEST FAILED: RECEIVED \"$numReceived\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"########################################################\"\n      exit 2\n   fi\nelse\n   echo ${0##*/}\": FAILED (\"$PROC1_EXIT_CODE\":\"$PROC2_EXIT_CODE\")\"\n   exit $COMBINED_EXIT_CODE\nfi\nrm $PROC1_OUTFILE $PROC2_OUTFILE\n", "num_lines": 115}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run the jobs-mode integration test.\n#\n#\n# Check to make sure the top-level test directory is defined.\n#\nif [ $NPMTEST_DIR\"\" = \"\" ] \nthen\n   echo ${0##*/}\": NPMTEST_DIR must be defined!\"\n   exit 1\nfi\n#\n# Set the name of the node executable (it should be in our path)\n#\nNODE=node\n#\n# Set a randomized test tag to isolate this test run from others within\n# the AWS account associated with our Odin material set.  This ensures\n# that all topic names used are unique to this test run.\n#\nTEST_TAG=\"test-\"$RANDOM\n#\n# Capture the exit code of the first command which fails in a pipeline.\n#\nset -o pipefail\n#\n# The integration tests pass a number of updates between two partner\n# processes.  Because these are QoS 0, delivery isn't guaranteed, but\n# we should expect to receive most of them.  All tests use the same number\n# of updates (48).\n#\nRECEIVES_REQUIRED=46\nTRANSMITS_TOTAL=48\nCOMPLETED_JOBS_REQUIRED=4\nCREATED_JOBS_TOTAL=5\nexport HOSTNAME=\"ajje7lpljulm4-ats.iot.us-east-1.amazonaws.com\"\n#\n# Process output will be captured in these files.\n#\nPROC1_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-1.out\nPROC2_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-2.out\n#\n# Move the test javascript program to the installed SDK\n# directory\n#\nINT_TEST_DIR=$NPMTEST_DIR/aws-iot-device-sdk-js/integration-test\nmkdir -p $INT_TEST_DIR\ncp ${0%/*}/jobs-integration-test.js $INT_TEST_DIR\n#\n# Start the two partner processes for the jobs-mode integration test and\n# save their PIDs.\n#\nif [ $CERT_DIR\"\" != \"\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running jobs integration test (certificate auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/jobs-integration-test.js -H $HOSTNAME -f $CERT_DIR -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\n    $NODE $INT_TEST_DIR/jobs-integration-test.js -H $HOSTNAME  -f $CERT_DIR -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\nelif [ $AUTHENTICATION_TYPE\"\" == \"websocket\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running jobs integration test (websocket/sigv4)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/jobs-integration-test.js -H $HOSTNAME -P=wss -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\n    $NODE $INT_TEST_DIR/jobs-integration-test.js -H $HOSTNAME -P=wss -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\nelse\n    echo \"###################################################################\"\n    echo ${0##*/}\": skipping jobs integration test (custom_auth)\"\n    echo \"###################################################################\"\n    exit 0\nfi\n#\n# Wait on the two partner processes and record their exit codes.\n#\nwait $PROC1_PID\nPROC1_EXIT_CODE=$?\nwait $PROC2_PID\nPROC2_EXIT_CODE=$?\n#\n# Combine the two exit codes; if either process exited abnormally, this\n# test is a failure.\n#\nCOMBINED_EXIT_CODE=$((PROC1_EXIT_CODE | PROC_2_EXIT_CODE))\nif [ $COMBINED_EXIT_CODE\"\" = \"0\" ]\nthen\n   jobsCompleted=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ jobs completed' |awk '{print $1}'`\n   numReceived=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $1}'`\n   receiveMask=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $4}'|sed -e 's/.*=//'`\n   \n   echo $numReceived\" messages received, receive mask [\"$receiveMask\"]\"\n   echo $jobsCompleted\" jobs completed\"\n\n   if !([ $numReceived\"\" -lt $RECEIVES_REQUIRED\"\" ] || [ $jobsCompleted -lt $COMPLETED_JOBS_REQUIRED ])\n   then\n      echo \"########################################################\"\n      echo \"   TEST SUCCEEDED: RECEIVED \"$numReceived\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\" \n      echo \"                   JOBS COMPLETED \"$jobsCompleted\"/\"$CREATED_JOBS_TOTAL\", \"$COMPLETED_JOBS_REQUIRED\" required\" \n      echo \"########################################################\"\n   else\n      echo \"########################################################\"\n      echo \"   TEST FAILED: RECEIVED \"$numReceived\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"                JOBS COMPLETED \"$jobsCompleted\"/\"$CREATED_JOBS_TOTAL\", \"$COMPLETED_JOBS_REQUIRED\" required\"\n      echo \"########################################################\"\n      exit 2\n   fi\nelse\n   echo ${0##*/}\": FAILED (\"$PROC1_EXIT_CODE\":\"$PROC2_EXIT_CODE\")\"\n   exit $COMBINED_EXIT_CODE\nfi\nrm $PROC1_OUTFILE $PROC2_OUTFILE\n", "num_lines": 117}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run the offline publishing integration test.\n#\n#\n# Check to make sure the top-level test directory is defined.\n#\nif [ $NPMTEST_DIR\"\" = \"\" ]\nthen\n   echo ${0##*/}\": NPMTEST_DIR must be defined!\"\n   exit 1\nfi\n#\n# Set the name of the node executable (it should be in our path)\n#\nNODE=node\n#\n# Set a randomized test tag to isolate this test run from others within\n# the AWS account associated with our Odin material set.  This ensures\n# that all topic names used are unique to this test run.\n#\nTEST_TAG=\"test-\"$RANDOM\nexport HOSTNAME=\"ajje7lpljulm4-ats.iot.us-east-1.amazonaws.com\"\nexport CUSTOM_AUTH_HOST=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id \"unit-test/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n#\n# Capture the exit code of the first command which fails in a pipeline.\n#\nset -o pipefail\n#\n# The integration tests pass a number of updates between two partner\n# processes.  Because these are QoS 0, delivery isn't guaranteed, but\n# we should expect to receive most of them.  In this test, the transmitting\n# process is subjected to simulated network failures; since offline\n# publish queueing is enabled, published messages are stored until it\n# reconnects and are then drained out.  The receiving process should\n# receive all of these if everything is working correctly.\n#\n# The transmitting process sends messages with a monotonically increasing\n# value, starting at 1.  The receiving process maintains a running sum of\n# these values, as well as a running sum of the message numbers received.\n# At the end of the test, the ratio of these sums is calculated; if no\n# messages are missing at the receiver, this ratio will be exactly 1.0.\n# Any messages which weren't received will cause this ratio to be less than\n# 1.0.  Since QoS 0 is used for the test, this is possible so a very small\n# error difference is allowed.\n#\nRECEIVES_REQUIRED=46\nTRANSMITS_TOTAL=48\n#\n# Process output will be captured in these files.\n#\nPROC1_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-1.out\nPROC2_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-2.out\n#\n# Move the test javascript programs to the installed SDK\n# directory\n#\nINT_TEST_DIR=$NPMTEST_DIR/aws-iot-device-sdk-js/integration-test\nmkdir -p $INT_TEST_DIR\ncp ${0%/*}/offline-publishing-test.js $INT_TEST_DIR\n#\n# Start the two partner processes for the offline publishing integration test and\n# save their PIDs.\n#\nif [ $AUTHENTICATION_TYPE\"\" == \"certificate\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running thing integration test (certificate auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $HOSTNAME -f $CERT_DIR -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    sleep 3       # wait 3 seconds prior to starting transmitting process\n    #\n    # transmit 4x/second\n    #\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $HOSTNAME -f $CERT_DIR -t2 --debug=true --delay-ms=250 -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nelif [ $AUTHENTICATION_TYPE\"\" == \"custom-auth\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running device integration test (websocket/custom auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    sleep 3       # wait 3 seconds prior to starting transmitting process\n    #\n    # transmit 4x/second\n    #\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t2 --debug=true --delay-ms=250 -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nelse\n    echo \"###################################################################\"\n    echo ${0##*/}\": running thing integration test (websocket/sigv4)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $HOSTNAME -P=wss -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    sleep 3       # wait 3 seconds prior to starting transmitting process\n    #\n    # transmit 4x/second\n    #\n    $NODE $INT_TEST_DIR/offline-publishing-test.js -H $HOSTNAME -P=wss -t2 --debug=true --delay-ms=250 -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nfi\n#\n# Wait on the two partner processes and record their exit codes.\n#\nwait $PROC1_PID\nPROC1_EXIT_CODE=$?\nwait $PROC2_PID\nPROC2_EXIT_CODE=$?\n#\n# Combine the two exit codes; if either process exited abnormally, this\n# test is a failure.\n#\nCOMBINED_EXIT_CODE=$((PROC1_EXIT_CODE | PROC_2_EXIT_CODE))\nif [ $COMBINED_EXIT_CODE\"\" = \"0\" ]\nthen\n   #\n   # Print out the received quality for debugging.\n   #\n   cat $PROC1_OUTFILE | grep -E '^quality' |awk '{print $NF}'\n   receiveQuality=`cat $PROC1_OUTFILE | grep -E '^quality' |awk '{print $NF}'`\n\n   #\n   # We should receive all of these; allow only a very small error margin.\n   #\n   minAcceptableQuality=0.99\n   qualityGtMinAcceptable=`echo $receiveQuality\"\" \\> $minAcceptableQuality\"\" | bc -l`\n   #\n   # The quality ratio should never exceed 1.0.\n   #\n   maxAcceptableQuality=1.00001\n   qualityLtMaxAcceptable=`echo $maxAcceptableQuality\"\" \\> $receiveQuality\"\" | bc -l`\n\n   if [ $qualityGtMinAcceptable\"\" -eq 1 ] && [ $qualityLtMaxAcceptable\"\" -eq 1 ]\n   then\n      echo \"########################################################\"\n      echo \"   TEST SUCCEEDED: PROC 1 QUALITY \"$receiveQuality\", \"$minAcceptableQuality\" required\"\n      echo \"########################################################\"\n   else\n      echo \"########################################################\"\n      echo \"   TEST FAILED: PROC 1 QUALITY \"$receiveQuality\", \"$minAcceptableQuality\" required\"\n      echo \"########################################################\"\n      exit 2\n   fi\nelse\n   echo ${0##*/}\": FAILED (\"$PROC1_EXIT_CODE\":\"$PROC2_EXIT_CODE\")\"\n   exit $COMBINED_EXIT_CODE\nfi\nrm $PROC1_OUTFILE $PROC2_OUTFILE\n", "num_lines": 151}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run the thing-mode integration test.\n#\n#\n# Check to make sure the top-level test directory is defined.\n#\nif [ $NPMTEST_DIR\"\" = \"\" ]\nthen\n   echo ${0##*/}\": NPMTEST_DIR must be defined!\"\n   exit 1\nfi\n#\n# Set the name of the node executable (it should be in our path)\n#\nNODE=node\n#\n# Set a randomized test tag to isolate this test run from others within\n# the AWS account associated with our Odin material set.  This ensures\n# that all topic names used are unique to this test run.\n#\nTEST_TAG=\"test-\"$RANDOM\nexport HOSTNAME=\"ajje7lpljulm4-ats.iot.us-east-1.amazonaws.com\"\nexport CUSTOM_AUTH_HOST=$(aws --region us-east-1 secretsmanager get-secret-value --secret-id \"unit-test/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n#\n# Capture the exit code of the first command which fails in a pipeline.\n#\nset -o pipefail\n#\n# The integration tests pass a number of updates between two partner\n# processes.  Because these are QoS 0, delivery isn't guaranteed, but\n# we should expect to receive most of them.  All tests use the same number\n# of updates (48).\n#\nRECEIVES_REQUIRED=46\nTRANSMITS_TOTAL=48\n#\n# Process output will be captured in these files.\n#\nPROC1_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-1.out\nPROC2_OUTFILE=$NPMTEST_DIR/${0##*/}-$RANDOM-$RANDOM-proc-2.out\n#\n# Move the test javascript programs to the installed SDK\n# directory\n#\nINT_TEST_DIR=$NPMTEST_DIR/aws-iot-device-sdk-js/integration-test\nmkdir -p $INT_TEST_DIR\ncp ${0%/*}/thing-integration-test.js $INT_TEST_DIR\n#\n# Start the two partner processes for the thing-mode integration test and\n# save their PIDs.\n#\nif [ $AUTHENTICATION_TYPE\"\" == \"certificate\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running thing integration test (certificate auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $HOSTNAME -f $CERT_DIR -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $HOSTNAME -f $CERT_DIR -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nelif [ $AUTHENTICATION_TYPE\"\" == \"custom-auth\" ]\nthen\n    echo \"###################################################################\"\n    echo ${0##*/}\": running device integration test (websocket/custom auth)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $CUSTOM_AUTH_HOST -P=wss-custom-auth -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nelse\n    echo \"###################################################################\"\n    echo ${0##*/}\": running thing integration test (websocket/sigv4)\"\n    echo \"###################################################################\"\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $HOSTNAME -P=wss -t1 --debug=true -T $TEST_TAG | tee $PROC1_OUTFILE &\n    PROC1_PID=$!\n    $NODE $INT_TEST_DIR/thing-integration-test.js -H $HOSTNAME -P=wss -t2 --debug=true -T $TEST_TAG | tee $PROC2_OUTFILE &\n    PROC2_PID=$!\nfi\n#\n# Wait on the two partner processes and record their exit codes.\n#\nwait $PROC1_PID\nPROC1_EXIT_CODE=$?\nwait $PROC2_PID\nPROC2_EXIT_CODE=$?\n#\n# Combine the two exit codes; if either process exited abnormally, this\n# test is a failure.\n#\nCOMBINED_EXIT_CODE=$((PROC1_EXIT_CODE | PROC_2_EXIT_CODE))\nif [ $COMBINED_EXIT_CODE\"\" = \"0\" ]\nthen\n   numReceived1=`cat $PROC1_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $1}'`\n   receiveMask1=`cat $PROC1_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $4}'|sed -e 's/.*=//'`\n   numReceived2=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $1}'`\n   receiveMask2=`cat $PROC2_OUTFILE | grep -E '^[0-9]+\\ messages received, accumulator=.*' |awk '{print $4}'|sed -e 's/.*=//'`\n\n   echo \"proc 1: \"$numReceived1\" messages received, receive mask [\"$receiveMask1\"]\"\n   echo \"proc 2: \"$numReceived2\" messages received, receive mask [\"$receiveMask2\"]\"\n\n   if [ $numReceived1\"\" -gt $RECEIVES_REQUIRED ] && [ $numReceived2\"\" -gt $RECEIVES_REQUIRED ]\n   then\n      echo \"########################################################\"\n      echo \"   TEST SUCCEEDED: PROC 1 RECEIVED \"$numReceived1\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"                   PROC 2 RECEIVED \"$numReceived2\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"########################################################\"\n   else\n      echo \"########################################################\"\n      echo \"   TEST FAILED: PROC 1 RECEIVED \"$numReceived1\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"                PROC 2 RECEIVED \"$numReceived2\"/\"$TRANSMITS_TOTAL\", \"$RECEIVES_REQUIRED\" required\"\n      echo \"########################################################\"\n      exit 2\n   fi\nelse\n   echo ${0##*/}\": FAILED (\"$PROC1_EXIT_CODE\":\"$PROC2_EXIT_CODE\")\"\n   exit $COMBINED_EXIT_CODE\nfi\nrm $PROC1_OUTFILE $PROC2_OUTFILE\n", "num_lines": 120}
{"repo_name": "aws-iot-device-sdk-js", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nset -e\n\nBROWSER_BUNDLE_DIR=browser\n\n#\n# Make sure that browserify is available.\n#\nBROWSERIFY=`which browserify`\nif [ $? -ne 0 ]; then\n    echo ${0##*/}\": browserify is not available, please install, e.g. npm install -g browserify\"\n    exit 1\nfi\n\n#\n# Make sure that npm is available.\n#\nNPM=`which npm`\nif [ $? -ne 0 ]; then\n    echo ${0##*/}\": npm is not available, please install\"\n    exit 2\nfi\n\n#\n# Verify that npm is at least version 3 (this script won't work with previous\n# versions).\n#\nNPM_MAJOR_VERSION=`npm -v | cut -d'.' -f1`\nif [ $NPM_MAJOR_VERSION\"\" -lt 3 ]; then\n    echo ${0##*/}\": npm must be at least version 3 (installed npm version:\"$NPM_MAJOR_VERSION\")\"\n    exit 3\nfi\n\n#\n# Make sure we are in the right directory by verifying the presence of a couple of files\n#\nif [ ! -f \"README.md\" ] || [ ! -f \"thing/index.js\" ] || [ ! -d $BROWSER_BUNDLE_DIR ]; then\n    echo ${0##*/}\": this script must be run in the package top-level directory\"\n    exit 4\nfi\n\n#\n# Check to see if the SDK browser bundle exists; if it does not, we'll create the browser\n# bundle to be used by other applications.\n#\nif [ ! -f $BROWSER_BUNDLE_DIR/aws-iot-sdk-browser-bundle.js ]; then\n#\n# Prepare the bundle by doing an npm install in the browser bundle directory.  Note\n# that we use this copy of the SDK files rather than pulling them from npm, so that\n# we can easily work with local changes, if necessary.\n#\n    (cd $BROWSER_BUNDLE_DIR; tar cvzf aws-iot-device-sdk.tgz --exclude ${PWD##*/} --exclude node_modules --exclude .git --exclude .github --exclude .coverdata --exclude debug --exclude examples --exclude reports --exclude test -C ../ .; mkdir -p node_modules/aws-iot-device-sdk; (cd node_modules/aws-iot-device-sdk; tar xvzf ../../aws-iot-device-sdk.tgz); npm install)\n#\n# Create the browser bundle and delete all working files/directories.  Allow\n# aws-iot-device-sdk and aws-sdk to be required by other browserify bundles.\n#\n    (cd $BROWSER_BUNDLE_DIR; rm -f bundle.js; $BROWSERIFY -r aws-iot-device-sdk -r aws-sdk -o aws-iot-sdk-browser-bundle.js; rm -rf node_modules; rm -f aws-iot-device-sdk.tgz)\n    echo ${0##*/}\": prepared browser bundle\"\nfi\n\n#\n# Check to see how many arguments are available; if one argument is available, we'll\n# browserify that file using external references to aws-sdk and aws-iot-device-sdk and\n# place the result in that directory under 'bundle.js'. If two arguments are available\n# we'll use the second argument as the bundle output file. Finally, we'll copy the browser\n# bundle into the application directory so that it's available for use.\n#\nif [ $# -eq 0 ]; then\n    exit 0\nelif [ $# -eq 1 ] || [ $# -eq 2 ]; then\n#\n# Browserify another app using external references to aws-sdk and aws-iot-device-sdk.\n#\n   if [ ! -f $1\"\" ]; then\n      echo ${0##*/}\": can't browserify (\"$1\") because it's not a file or does not exist\"\n      exit 5\n   fi\n\n   APP_PATH=${1%/*}\"\"\n   APP_NAME=${1##*/}\"\"\n   OUTPUT_FILE=bundle.js\n\n   if [ $# -eq 2 ] && [ $2\"\" != \"\" ]; then\n      OUTPUT_FILE=${2##*/}\n   fi\n\n   echo \"browserifying \"$1\" and placing result in \"$APP_PATH/$OUTPUT_FILE\"...\"\n   (cd $APP_PATH\"\"; $BROWSERIFY -x aws-sdk -x aws-iot-device-sdk $APP_NAME -o $OUTPUT_FILE)\n   cp $BROWSER_BUNDLE_DIR/aws-iot-sdk-browser-bundle.js $APP_PATH\nelse\n   echo \"Usage: \"${0##*/}\" [javascript application] [output file]\"\n   exit 6\nfi\n\nexit 0\n", "num_lines": 110}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ex\n\n# clean\nrm -rf docs/\n\n# grab local copy of aws-crt-nodejs so we can build its docs into our own\nif [ ! -d build/docs/aws-crt-nodejs ]; then\n    mkdir -p build/docs\n    git clone --single-branch https://github.com/awslabs/aws-crt-nodejs.git build/docs/aws-crt-nodejs\nfi\n\nCRT_VERSION=`npm view aws-crt version`\npushd build/docs/aws-crt-nodejs\ngit fetch\ngit checkout \"v$CRT_VERSION\"\n# typedoc need source to be compiled to generate the docs. Pull and install the crt dependency to make sure the lib compiled.\ngit submodule update --init --recursive\nnpm install .\npopd\n\n# build docs\nnpx typedoc --options docsrc/typedoc-node.json\nnpx typedoc --options docsrc/typedoc-browser.json\ncp documents/index.html docs/index.html\n", "num_lines": 27}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nVERSION_FILE_PATH=$1\nif [ ! readlink -e \"$VERSION_FILE_PATH\" ]; then\n    echo \"No VERSION file found! Cannot make release!\"\n    exit 1\nelse\n    echo \"VERSION file found...\"\nfi\nVERSION=$(cat $VERSION_FILE_PATH)\n\n# Make sure the version variable is populated\nif [ -z \"${VERSION}\" ]; then\n    echo \"VERSION file is empty!\"\n    exit 1\nelse\n    echo \"VERSION file contains: ${VERSION}\"\nfi\n\n# Make sure the version follows the correct format: major.minor.patch\nLENGTH_CHECK=\"${VERSION//[^.]}\"\nif [ ${#LENGTH_CHECK} != 2 ]; then\n    echo \"VERSION file contains invalid version (not in format major.minor.patch)\"\n    exit 1\nfi\n# Use RegX to ensure it only contains numbers and periods\nREGX_CHECK='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ $VERSION =~ $REGX_CHECK ]]; then\n    echo \"VERSION file contains valid version\"\nelse\n    echo \"VERSION file contains invalid version (RegX validator failed)\"\n    exit 1\nfi\n\nPUBLISHED_TAG_VERSION=`npm show aws-iot-device-sdk-v2 version`\nif [ \"$PUBLISHED_TAG_VERSION\" == \"$VERSION\" ]; then\n    echo \"$VERSION found in npm. Testing release...\"\n\n    # install the Typescript and the SDK\n    npm install -g typescript\n    npm install\n\n    # Move to the sample folder and get the endpoint\n    cd samples/node/pub_sub\n    ENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --region us-east-1 --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\n    # Run the sample!\n    npm install\n    node dist/index.js --endpoint $ENDPOINT --ca_file /tmp/AmazonRootCA1.pem --cert /tmp/certificate.pem --key /tmp/privatekey.pem\n\n    exit 0\n\nelse\n    echo \"$VERSION was not found in npm. Release failed!\"\nfi\n\nexit 1\n", "num_lines": 59}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nVERSION_FILE_PATH=$1\nif [ ! readlink -e \"$VERSION_FILE_PATH\" ]; then\n    echo \"No VERSION file found! Cannot make release!\"\n    exit 1\nelse\n    echo \"VERSION file found...\"\nfi\nVERSION=$(cat $VERSION_FILE_PATH)\n\n# Make sure the version variable is populated\nif [ -z \"${VERSION}\" ]; then\n    echo \"VERSION file is empty!\"\n    exit 1\nelse\n    echo \"VERSION file contains: ${VERSION}\"\nfi\n\n# Make sure the version follows the correct format: major.minor.patch\nLENGTH_CHECK=\"${VERSION//[^.]}\"\nif [ ${#LENGTH_CHECK} != 2 ]; then\n    echo \"VERSION file contains invalid version (not in format major.minor.patch)\"\n    exit 1\nfi\n# Use RegX to ensure it only contains numbers and periods\nREGX_CHECK='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ $VERSION =~ $REGX_CHECK ]]; then\n    echo \"VERSION file contains valid version\"\nelse\n    echo \"VERSION file contains invalid version (RegX validator failed)\"\n    exit 1\nfi\n\n# Does NPM have the version? If so, do not allow it!\nPUBLISHED_TAG_VERSION=`npm show aws-iot-device-sdk-v2 version`\nif [ \"$PUBLISHED_TAG_VERSION\" == \"$VERSION\" ]; then\n    echo \"$VERSION is already in npm, cut a new tag if you want to upload another version.\"\n    exit 1\nfi\n\necho \"$VERSION currently does not exist in npm, allowing pipeline to continue.\"\nexit 0\n", "num_lines": 45}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nVERSION_FILE_PATH=$1\nif [ ! readlink -e \"$VERSION_FILE_PATH\" ]; then\n    echo \"No VERSION file found! Cannot make release!\"\n    exit 1\nelse\n    echo \"VERSION file found...\"\nfi\nVERSION=$(cat $VERSION_FILE_PATH)\n\n# Make sure the version variable is populated\nif [ -z \"${VERSION}\" ]; then\n    echo \"VERSION file is empty!\"\n    exit 1\nelse\n    echo \"VERSION file contains: ${VERSION}\"\nfi\n\n# Make sure the version follows the correct format: major.minor.patch\nLENGTH_CHECK=\"${VERSION//[^.]}\"\nif [ ${#LENGTH_CHECK} != 2 ]; then\n    echo \"VERSION file contains invalid version (not in format major.minor.patch)\"\n    exit 1\nfi\n# Use RegX to ensure it only contains numbers and periods\nREGX_CHECK='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ $VERSION =~ $REGX_CHECK ]]; then\n    echo \"VERSION file contains valid version\"\nelse\n    echo \"VERSION file contains invalid version (RegX validator failed)\"\n    exit 1\nfi\n\nsed -i -E \"s/\\\"version\\\": \\\".+\\\"/\\\"version\\\": \\\"${VERSION}\\\"/\" package.json\n\nexit 0\n", "num_lines": 39}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/node/basic_connect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nnpm install --unsafe-perm\n\necho \"Connect Basic (Direct) test\"\nnode dist/index.js --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --is_ci true\n\npopd\n\npushd $CODEBUILD_SRC_DIR/samples/node/websocket_connect\n\nnpm install --unsafe-perm\n\necho \"Connect Websocket test\"\nnode dist/index.js --endpoint $ENDPOINT --signing_region us-east-1 --is_ci true\n\npopd\n", "num_lines": 27}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/node/custom_authorizer_connect\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_NAME=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_PASSWORD=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nnpm install --unsafe-perm\n\necho \"Mqtt Connect with Custom Authorizer test\"\nnode dist/index.js --endpoint $ENDPOINT --custom_auth_authorizer_name $AUTH_NAME --custom_auth_password $AUTH_PASSWORD --is_ci true\n\npopd\n", "num_lines": 20}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/node/pub_sub\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nnpm install --unsafe-perm\n\necho \"PubSub test\"\nnode dist/index.js --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --is_ci true\n\npopd\n\npushd $CODEBUILD_SRC_DIR/samples/node/pub_sub_js\n\nnpm install --unsafe-perm\n\necho \"PubSub JS test\"\nnode index.js --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --is_ci true\n\npopd\n", "num_lines": 27}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\n# build package\ncd $CODEBUILD_SRC_DIR\n\nulimit -c unlimited\nnpm install --unsafe-perm\n\ncert=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/cert\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$cert\" > /tmp/certificate.pem\nkey=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/key\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key\" > /tmp/privatekey.pem\n", "num_lines": 16}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/node/shadow\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\nnpm install --unsafe-perm\n\necho \"Shadow test - MQTT 311\"\nnode dist/index.js --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --thing_name CI_CodeBuild_Thing --is_ci true\n\necho \"Shadow test - MQTT 5\"\nnode dist/index.js --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --thing_name CI_CodeBuild_Thing --is_ci true --mqtt5 true\n\npopd\n", "num_lines": 21}
{"repo_name": "aws-iot-device-sdk-js-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euxo pipefail\n\n# Redirect output to stderr.\nexec 1>&2\n\nRELEASE_TYPE=\"$1\"\nRELEASE_TITLE=\"$2\"\n\n# Make sure there are ONLY two arguments\nif [ \"$#\" != \"2\" ]; then\n    echo \"ERROR: Arguments passed is NOT equal to two!\"\n    exit 1\nfi\n\npushd $(dirname $0) > /dev/null\n\n# Get the current version\ngit checkout main\n\ngit_tags=$(git tag)\ncurrent_version=$(python3 ./update_semantic_version.py  --version \"${git_tags}\" --type MINOR --parse_latest_version true)\ncurrent_version_without_v=$(echo ${current_version} | cut -f2 -dv)\necho \"Current release version is ${current_version_without_v}\"\n\n# Validate that RELEASE_TYPE is what we expect and bump the version\nnew_version=$(python3 ./update_semantic_version.py --version \"${current_version_without_v}\" --type \"${RELEASE_TYPE}\")\nif [ \"$new_version\" == \"0.0.0\" ]; then\n    echo \"ERROR: Unknown release type! Exitting...\"\n    exit -1\nfi\necho \"New version is ${new_version}\"\n\n# Validate that the title is set\nif [ \"$RELEASE_TITLE\" == \"\" ]; then\n    echo \"ERROR: No title set! Cannot make release. Exitting...\"\n    exit -1\nfi\n\n# Setup Github credentials\ngit config --local user.email \"aws-sdk-common-runtime@amazon.com\"\ngit config --local user.name \"GitHub Actions\"\n\n# --==--\nnew_version_branch=AutoTag-v${new_version}\ngit checkout -b ${new_version_branch}\n\n# Update the version in the README to show the latest\nsed -i -r \"s/.*Latest released version:.*/Latest released version: v${new_version}/\" ../README.md\ngit add ../README.md\n# Make the commit\ngit commit -m \"[v$new_version] $RELEASE_TITLE\"\n\n# # push the commit and create a PR\ngit push -u \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-js-v2.git\" ${new_version_branch}\ngh pr create --title \"AutoTag PR for v${new_version}\" --body \"AutoTag PR for v${new_version}\" --head ${new_version_branch}\n\n# # Merge the PR\ngh pr merge --admin --squash\n# --==--\n\n# Update local state with the merged pr (if one was made) and just generally make sure we're up to date\ngit fetch\ngit checkout main\ngit pull \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-js-v2.git\" main\n\n# Create new tag on latest commit (lightweight tag - we do NOT want an annotated tag)\ngit tag -f v${new_version}\n# Push new tag to github\ngit push \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-js-v2.git\" --tags\n\n# Determine if this is a pre-release or not based on the major version\nIS_PRE_RELEASE=\"false\"\nVERSION_STRING_DELIMITER=.\nVERSION_STRING_ARRAY=($(echo \"$new_version\" | tr $VERSION_STRING_DELIMITER '\\n'))\nif [ \"${VERSION_STRING_ARRAY[0]}\" == \"0\" ]; then\n    IS_PRE_RELEASE=\"true\"\nelse\n    IS_PRE_RELEASE=\"false\"\nfi\n\n# Create the release with auto-generated notes as the description\n# - NOTE: This will only add notes if there is at least one PR. If there is no PRs,\n# - then this will be blank and need manual input/changing after running.\nif [ $IS_PRE_RELEASE == \"true\" ]; then\n    gh release create \"v${new_version}\" -p --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nelse\n    gh release create \"v${new_version}\" --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nfi\n\npopd > /dev/null\n", "num_lines": 93}
{"repo_name": "aws-iot-device-sdk-python", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script manages the start of integration\n# tests for Python core in AWS IoT Arduino Yun\n# SDK. The tests should be able to run both in\n# Brazil and ToD Worker environment.\n# The script will perform the following tasks:\n# 1. Retrieve credentials as needed from AWS\n# 2. Obtain ZIP package and unzip it locally\n# 3. Start the integration tests and check results\n# 4. Report any status returned.\n# To start the tests as TodWorker:\n# > run.sh MutualAuth 1000 100 7\n# or\n# > run.sh Websocket 1000 100 7\n# or\n# > run.sh ALPN 1000 100 7\n#\n# To start the tests from desktop:\n# > run.sh MutualAuthT 1000 100 7\n# or\n# > run.sh WebsocketT 1000 100 7\n# or\n# > run.sh ALPNT 1000 100 7\n#\n# 1000 MQTT messages, 100 bytes of random string\n# in length and 7 rounds of network failure for \n# progressive backoff.\n# Test mode (MutualAuth/Websocket) must be\n# specified.\n# Scale number must also be specified (see usage)\n\n# Define const\nUSAGE=\"usage: run.sh <testMode> <NumberOfMQTTMessages> <LengthOfShadowRandomString> <NumberOfNetworkFailure>\"\n\nAWSMutualAuth_TodWorker_private_key=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestPrivateKey-vNUQU8\"\nAWSMutualAuth_TodWorker_certificate=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestCertificate-vTRwjE\"\nAWSMutualAuth_Desktop_private_key=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestDesktopPrivateKey-DdC7nv\"\nAWSMutualAuth_Desktop_certificate=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestDesktopCertificate-IA4xbj\"\n\nAWSGGDiscovery_TodWorker_private_key=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestGGDiscoveryPrivateKey-YHQI1F\"\nAWSGGDiscovery_TodWorker_certificate=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestGGDiscoveryCertificate-TwlAcS\"\n\nAWSSecretForWebsocket_TodWorker_KeyId=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestWebsocketAccessKeyId-1YdB9z\"\nAWSSecretForWebsocket_TodWorker_SecretKey=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestWebsocketSecretAccessKey-MKTSaV\"\nAWSSecretForWebsocket_Desktop_KeyId=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestWebsocketAccessKeyId-1YdB9z\"\nAWSSecretForWebsocket_Desktop_SecretKey=\"arn:aws:secretsmanager:us-east-1:123124136734:secret:V1IotSdkIntegrationTestWebsocketSecretAccessKey-MKTSaV\"\n\nSDKLocation=\"./AWSIoTPythonSDK\"\nRetrieveAWSKeys=\"./test-integration/Tools/retrieve-key.py\"\nCREDENTIAL_DIR=\"./test-integration/Credentials/\"\nTEST_DIR=\"./test-integration/IntegrationTests/\"\nCA_CERT_URL=\"https://www.amazontrust.com/repository/AmazonRootCA1.pem\"\nCA_CERT_PATH=${CREDENTIAL_DIR}rootCA.crt\n\n\n\n\n# If input args not correct, echo usage\nif [ $# -ne 4 ]; then\n    echo ${USAGE}\nelse\n# Description\n    echo \"[STEP] Start run.sh\"\n    echo \"***************************************************\"\n    echo \"About to start integration tests for IoTPySDK...\"\n    echo \"Test Mode: $1\"\n# Determine the Python versions need to test for this SDK\n    pythonExecutableArray=()\n    pythonExecutableArray[0]=\"3\"\n# Retrieve credentials as needed from AWS\n    TestMode=\"\"\n    echo \"[STEP] Retrieve credentials from AWS\"\n    echo \"***************************************************\"\n    if [ \"$1\"x == \"MutualAuth\"x -o \"$1\"x == \"MutualAuthT\"x ]; then\n        AWSSetName_privatekey=${AWSMutualAuth_TodWorker_private_key}\n    \tAWSSetName_certificate=${AWSMutualAuth_TodWorker_certificate}\n    \tAWSDRSName_privatekey=${AWSGGDiscovery_TodWorker_private_key}\n        AWSDRSName_certificate=${AWSGGDiscovery_TodWorker_certificate}\n        TestMode=\"MutualAuth\"\n        if [ \"$1\"x == \"MutualAuthT\"x ]; then\n            AWSSetName_privatekey=${AWSMutualAuth_Desktop_private_key}\n    \t    AWSSetName_certificate=${AWSMutualAuth_Desktop_certificate}\n        fi\n    \tpython ${RetrieveAWSKeys} ${AWSSetName_certificate} > ${CREDENTIAL_DIR}certificate.pem.crt\n    \tpython ${RetrieveAWSKeys} ${AWSSetName_privatekey} > ${CREDENTIAL_DIR}privateKey.pem.key\n        curl -s \"${CA_CERT_URL}\" > ${CA_CERT_PATH}\n        echo -e \"URL retrieved certificate data:\\n$(cat ${CA_CERT_PATH})\\n\"\n    \tpython ${RetrieveAWSKeys} ${AWSDRSName_certificate} > ${CREDENTIAL_DIR}certificate_drs.pem.crt\n    \tpython ${RetrieveAWSKeys} ${AWSDRSName_privatekey} > ${CREDENTIAL_DIR}privateKey_drs.pem.key\n    elif [ \"$1\"x == \"Websocket\"x -o \"$1\"x == \"WebsocketT\"x ]; then\n    \tACCESS_KEY_ID_ARN=$(python ${RetrieveAWSKeys} ${AWSSecretForWebsocket_TodWorker_KeyId})\n        ACCESS_SECRET_KEY_ARN=$(python ${RetrieveAWSKeys} ${AWSSecretForWebsocket_TodWorker_SecretKey})\n        TestMode=\"Websocket\"\n        if [ \"$1\"x == \"WebsocketT\"x ]; then\n            ACCESS_KEY_ID_ARN=$(python ${RetrieveAWSKeys} ${AWSSecretForWebsocket_Desktop_KeyId})\n            ACCESS_SECRET_KEY_ARN=$(python ${RetrieveAWSKeys} ${AWSSecretForWebsocket_Desktop_SecretKey})\n        fi\n        echo ${ACCESS_KEY_ID_ARN}\n        echo ${ACCESS_SECRET_KEY_ARN}\n        export AWS_ACCESS_KEY_ID=${ACCESS_KEY_ID_ARN}\n        export AWS_SECRET_ACCESS_KEY=${ACCESS_SECRET_KEY_ARN}\n        curl -s \"${CA_CERT_URL}\" > ${CA_CERT_PATH}\n        echo -e \"URL retrieved certificate data:\\n$(cat ${CA_CERT_PATH})\\n\"\n    elif [ \"$1\"x == \"ALPN\"x -o \"$1\"x == \"ALPNT\"x ]; then\n        AWSSetName_privatekey=${AWSMutualAuth_TodWorker_private_key}\n    \tAWSSetName_certificate=${AWSMutualAuth_TodWorker_certificate}\n    \tAWSDRSName_privatekey=${AWSGGDiscovery_TodWorker_private_key}\n        AWSDRSName_certificate=${AWSGGDiscovery_TodWorker_certificate}\n        TestMode=\"ALPN\"\n        if [ \"$1\"x == \"ALPNT\"x ]; then\n            AWSSetName_privatekey=${AWSMutualAuth_Desktop_private_key}\n    \t    AWSSetName_certificate=${AWSMutualAuth_Desktop_certificate}\n        fi\n        python ${RetrieveAWSKeys} ${AWSSetName_certificate} > ${CREDENTIAL_DIR}certificate.pem.crt\n    \tpython ${RetrieveAWSKeys} ${AWSSetName_privatekey} > ${CREDENTIAL_DIR}privateKey.pem.key\n        curl -s \"${CA_CERT_URL}\" > ${CA_CERT_PATH}\n        echo -e \"URL retrieved certificate data:\\n$(cat ${CA_CERT_PATH})\\n\"\n    \tpython ${RetrieveAWSKeys} ${AWSDRSName_certificate} > ${CREDENTIAL_DIR}certificate_drs.pem.crt\n    \tpython ${RetrieveAWSKeys} ${AWSDRSName_privatekey} > ${CREDENTIAL_DIR}privateKey_drs.pem.key\n    else\n    \techo \"Mode not supported\"\n    \texit 1\n    fi\n# Obtain ZIP package and unzip it locally\n    echo ${TestMode}\n    echo \"[STEP] Obtain ZIP package\"\n    echo \"***************************************************\"\n    cp -R ${SDKLocation} ./test-integration/IntegrationTests/TestToolLibrary/SDKPackage/\n# Obtain Python executable\n\n    echo \"***************************************************\"\n    for file in `ls ${TEST_DIR}`\n    do\n        # if [ ${file}x == \"IntegrationTestMQTTConnection.py\"x ]; then\n        if [ ${file##*.}x == \"py\"x ]; then\n            echo \"[SUB] Running test: ${file}...\"\n\n            Scale=10\n            case \"$file\" in\n                \"IntegrationTestMQTTConnection.py\") Scale=$2\n                ;;\n                \"IntegrationTestShadow.py\") Scale=$3\n                ;;\n                \"IntegrationTestAutoReconnectResubscribe.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestProgressiveBackoff.py\") Scale=$4\n                ;;\n                \"IntegrationTestConfigurablePublishMessageQueueing.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestDiscovery.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestAsyncAPIGeneralNotificationCallbacks.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestOfflineQueueingForSubscribeUnsubscribe.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestClientReusability.py\") Scale=\"\"\n                ;;\n                \"IntegrationTestJobsClient.py\") Scale=\"\"\n            esac\n\n            python ${TEST_DIR}${file} ${TestMode} ${Scale}\n            currentTestStatus=$?\n            echo \"[SUB] Test: ${file} completed. Exiting with status: ${currentTestStatus}\"\n            if [ ${currentTestStatus} -ne 0 ]; then\n                echo \"!!!!!!!!!!!!!Test: ${file} failed.!!!!!!!!!!!!!\"\n                exit ${currentTestStatus}\n            fi\n            echo \"\"\n        fi\n    done\n    echo \"All integration tests passed\"\nfi\n", "num_lines": 174}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nVERSION_FILE_PATH=$1\nif [ ! readlink -e \"$VERSION_FILE_PATH\" ]; then\n    echo \"No VERSION file found! Cannot make release!\"\n    exit 1\nelse\n    echo \"VERSION file found...\"\nfi\nVERSION=$(cat $VERSION_FILE_PATH)\n\n# Make sure the version variable is populated\nif [ -z \"${VERSION}\" ]; then\n    echo \"VERSION file is empty!\"\n    exit 1\nelse\n    echo \"VERSION file contains: ${VERSION}\"\nfi\n\n# Make sure the version follows the correct format: major.minor.patch\nLENGTH_CHECK=\"${VERSION//[^.]}\"\nif [ ${#LENGTH_CHECK} != 2 ]; then\n    echo \"VERSION file contains invalid version (not in format major.minor.patch)\"\n    exit 1\nfi\n# Use RegX to ensure it only contains numbers and periods\nREGX_CHECK='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ $VERSION =~ $REGX_CHECK ]]; then\n    echo \"VERSION file contains valid version\"\nelse\n    echo \"VERSION file contains invalid version (RegX validator failed)\"\n    exit 1\nfi\n\n# Does PyPi have the version? If so, do not allow it!\nif python3 -m pip install --no-cache-dir -vvv awsiotsdk==$VERSION; then\n    echo \"$VERSION is already in pypi, cut a new tag if you want to upload another version.\"\n    exit 1\nfi\n\necho \"$VERSION currently does not exist in pypi, allowing pipeline to continue.\"\nexit 0\n", "num_lines": 43}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Basic Connect test\"\npython3 basic_connect.py --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem\n\necho \"Websocket Connect test\"\npython3 websocket_connect.py --endpoint $ENDPOINT --signing_region us-east-1\n\npopd\n", "num_lines": 19}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_NAME=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/name\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\nAUTH_PASSWORD=$(aws secretsmanager get-secret-value --secret-id \"ci/CustomAuthorizer/password\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Custom Authorizer test\"\npython3 custom_authorizer_connect.py --endpoint $ENDPOINT --custom_auth_authorizer_name $AUTH_NAME --custom_auth_password $AUTH_PASSWORD --signing_region us-east-1\n\npopd\n", "num_lines": 18}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\n# from hereon commands are echoed. don't leak secrets\nset -x\n\nsofthsm2-util --version\n\n# SoftHSM2's default tokendir path might be invalid on this machine\n# so set up a conf file that specifies a known good tokendir path\nmkdir -p /tmp/tokens\nexport SOFTHSM2_CONF=/tmp/softhsm2.conf\necho \"directories.tokendir = /tmp/tokens\" > /tmp/softhsm2.conf\n\n# create token\nsofthsm2-util --init-token --free --label my-token --pin 0000 --so-pin 0000\n\n# add private key to token (must be in PKCS#8 format)\nopenssl pkcs8 -topk8 -in /tmp/privatekey.pem -out /tmp/privatekey.p8.pem -nocrypt\nsofthsm2-util --import /tmp/privatekey.p8.pem --token my-token --label my-key --id BEEFCAFE --pin 0000\n\n# run sample\npython3 pkcs11_connect.py --endpoint $ENDPOINT --cert /tmp/certificate.pem --pkcs11_lib /usr/lib/softhsm/libsofthsm2.so --pin 0000 --token_label my-token --key_label my-key\n\npopd\n", "num_lines": 32}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"PubSub test\"\npython3 pubsub.py --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --is_ci \"true\"\n\npopd\n", "num_lines": 16}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"MQTT5 PubSub test\"\npython3 mqtt5_pubsub.py --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --is_ci \"true\"\n\npopd\n", "num_lines": 16}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\n# build package\ncd $CODEBUILD_SRC_DIR\n\nulimit -c unlimited\npython3 -m pip install .\n\ncert=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/cert\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$cert\" > /tmp/certificate.pem\nkey=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/key\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key\" > /tmp/privatekey.pem\nkey_p8=$(aws secretsmanager get-secret-value --secret-id \"ci/CodeBuild/keyp8\" --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$key_p8\" > /tmp/privatekey_p8.pem\n", "num_lines": 17}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\nset -o pipefail\n\nenv\n\npushd $CODEBUILD_SRC_DIR/samples/\n\nENDPOINT=$(aws secretsmanager get-secret-value --secret-id \"ci/endpoint\" --query \"SecretString\" | cut -f2 -d\":\" | sed -e 's/[\\\\\\\"\\}]//g')\n\necho \"Shadow test\"\npython3 shadow.py --endpoint $ENDPOINT --key /tmp/privatekey.pem --cert /tmp/certificate.pem --thing_name CI_CodeBuild_Thing --is_ci true\n\npopd\n", "num_lines": 16}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get the S3 URL containing all of the MQTT5 testing environment variables passed in to the bash script\ntesting_env_bucket=$1\nregion=$2\n\n# Make sure we have something:\nif [ \"${testing_env_bucket}\" != \"\" ] && [ \"${region}\" != \"\" ]; then\n    echo \"S3 bucket for environment variables found and region\"\nelse\n    echo \"Could not get S3 bucket for environment variables and/or region.\"\n    echo \"You need to run this script and pass the S3 URL of the file containing\"\n    echo \"all of the environment variables to set, as well as the secrets for certificates and private keys\"\n    echo \"\"\n    echo \"Example: mqtt5_test_setup.sh s3://<bucket>/<file> <region>\"\n    echo \"\"\n    echo \"When finished, run 'cleanup' to remove the files downloaded:\"\n    echo \"\"\n    echo \"Example: mqtt5_test_setup.sh s3://<bucket>/<file> cleanup\"\n    echo \"\"\n    return 1\nfi\n\n# Is this just a request to clean up?\n# NOTE: This blindly assumes there is a environment_files.txt file\nif [ \"${region}\" != \"cleanup\" ]; then\n    sleep 0.1 # we have to do something to do an else...\nelse\n    echo \"Undoing environment variables\"\n    unset $(grep -v '^#' ${PWD}/environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    unset AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH\n    unset AWS_TEST_MQTT5_IOT_KEY_PATH\n\n    echo \"Cleaning up resources...\"\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    echo \"Success!\"\n    return 0\nfi\n\n# Get the file from S3\naws s3 cp ${testing_env_bucket} ${PWD}/environment_files.txt\ntesting_env_file=$( cat environment_files.txt )\n# Make sure we have data of some form\nif [ \"${testing_env_file}\" != \"\" ]; then\n    echo \"Environment variables secret found\"\nelse\n    echo \"Could not get environment variables from secrets!\"\n    return 1\nfi\n\n# Make all the variables in mqtt5_environment_variables.txt exported\n# so we can run MQTT5 tests\nexport $(grep -v '^#' environment_files.txt | xargs)\n\n# CRT/non-builder certificate and key processing\n# Get the certificate and key secrets (dumps straight to a file)\ncrt_cert_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_CERTIFICATE_FILE_SECRET}\" --query \"SecretString\" --region ${region} | cut -f2 -d\\\") && echo -e \"$crt_cert_file\" > ${PWD}/crt_certificate.pem\ncrt_key_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_KEY_FILE_SECRET}\" --query \"SecretString\" --region ${region} | cut -f2 -d\\\") && echo -e \"$crt_key_file\" > ${PWD}/crt_privatekey.pem\n# Does the certificate file have data? If not, then abort!\nif [ \"${crt_cert_file}\" != \"\" ]; then\n    echo \"CRT Certificate secret found\"\nelse\n    echo \"Could not get CRT certificate from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n\n    return 1\nfi\n# Does the private key file have data? If not, then abort!\nif [ \"${crt_key_file}\" != \"\" ]; then\n    echo \"CRT Private key secret found\"\nelse\n    echo \"Could not get CRT private key from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n\n    return 1\nfi\n# Set the certificate and key paths (absolute paths for best compatbility)\nexport AWS_TEST_MQTT5_CERTIFICATE_FILE=\"${PWD}/crt_certificate.pem\"\nexport AWS_TEST_MQTT5_KEY_FILE=\"${PWD}/crt_privatekey.pem\"\n\n\n# IoT/Builder certificate and key processing\n# Get the certificate and key secrets (dumps straight to a file)\niot_cert_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH_SECRET}\" --region ${region} --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$iot_cert_file\" > ${PWD}/iot_certificate.pem\niot_key_file=$(aws secretsmanager get-secret-value --secret-id \"${AWS_TEST_MQTT5_IOT_KEY_PATH_SECRET}\" --region ${region} --query \"SecretString\" | cut -f2 -d\":\" | cut -f2 -d\\\") && echo -e \"$iot_key_file\" > ${PWD}/iot_privatekey.pem\n# Does the certificate file have data? If not, then abort!\nif [ \"${iot_cert_file}\" != \"\" ]; then\n    echo \"IoT Certificate secret found\"\nelse\n    echo \"Could not get IoT certificate from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    return 1\nfi\n# Does the private key file have data? If not, then abort!\nif [ \"${iot_key_file}\" != \"\" ]; then\n    echo \"IoT Private key secret found\"\nelse\n    echo \"Could not get IoT private key from secrets!\"\n\n    # Clean up...\n    unset $(grep -v '^#' environment_files.txt | xargs | cut -d \"=\" -f 1)\n    unset AWS_TEST_MQTT5_CERTIFICATE_FILE\n    unset AWS_TEST_MQTT5_KEY_FILE\n    rm \"${PWD}/environment_files.txt\"\n    rm \"${PWD}/crt_certificate.pem\"\n    rm \"${PWD}/crt_privatekey.pem\"\n    rm \"${PWD}/iot_certificate.pem\"\n    rm \"${PWD}/iot_privatekey.pem\"\n\n    return 1\nfi\n# Set IoT certificate and key paths\nexport AWS_TEST_MQTT5_IOT_CERTIFICATE_PATH=\"${PWD}/iot_certificate.pem\"\nexport AWS_TEST_MQTT5_IOT_KEY_PATH=\"${PWD}/iot_privatekey.pem\"\n\n# Everything is set\necho \"Success: Environment variables set!\"", "num_lines": 144}
{"repo_name": "aws-iot-device-sdk-python-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euxo pipefail\n\n# Redirect output to stderr.\nexec 1>&2\n\nRELEASE_TYPE=\"$1\"\nRELEASE_TITLE=\"$2\"\n\n# Make sure there are ONLY two arguments\nif [ \"$#\" != \"2\" ]; then\n    echo \"ERROR: Arguments passed is NOT equal to two!\"\n    exit 1\nfi\n\npushd $(dirname $0) > /dev/null\n\n# Get the current version\ngit checkout main\n\ngit_tags=$(git tag)\ncurrent_version=$(python3 ./update_semantic_version.py  --version \"${git_tags}\" --type MINOR --parse_latest_version true)\ncurrent_version_without_v=$(echo ${current_version} | cut -f2 -dv)\n\necho \"Current release version is ${current_version_without_v}\"\n\n# Validate that RELEASE_TYPE is what we expect and bump the version\nnew_version=$(python3 ./update_semantic_version.py --version \"${current_version_without_v}\" --type \"${RELEASE_TYPE}\")\nif [ \"$new_version\" == \"0.0.0\" ]; then\n    echo \"ERROR: Unknown release type! Exitting...\"\n    exit -1\nfi\necho \"New version is ${new_version}\"\n\n# Validate that the title is set\nif [ \"$RELEASE_TITLE\" == \"\" ]; then\n    echo \"ERROR: No title set! Cannot make release. Exitting...\"\n    exit -1\nfi\n\n# Setup Github credentials\ngit config --local user.email \"aws-sdk-common-runtime@amazon.com\"\ngit config --local user.name \"GitHub Actions\"\n\n# --==--\nnew_version_branch=AutoTag-v${new_version}\ngit checkout -b ${new_version_branch}\n\n# Update the version in the README to show the latest\nsed -i -r \"s/.*Latest released version:.*/Latest released version: v${new_version}/\" ../README.md\ngit add ../README.md\n# Make the commit\ngit commit -m \"[v$new_version] $RELEASE_TITLE\"\n\n# # push the commit and create a PR\ngit push -u \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-python-v2.git\" ${new_version_branch}\ngh pr create --title \"AutoTag PR for v${new_version}\" --body \"AutoTag PR for v${new_version}\" --head ${new_version_branch}\n\n# # Merge the PR\ngh pr merge --admin --squash\n# --==--\n\n# Update local state with the merged pr (if one was made) and just generally make sure we're up to date\ngit fetch\ngit checkout main\ngit pull \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-python-v2.git\" main\n\n# Create new tag on latest commit (lightweight tag - we do NOT want an annotated tag)\ngit tag -f v${new_version}\n# Push new tag to github\ngit push \"https://${GITHUB_ACTOR}:${GITHUB_TOKEN}@github.com/aws/aws-iot-device-sdk-python-v2.git\" --tags\n\n# Determine if this is a pre-release or not based on the major version\nIS_PRE_RELEASE=\"false\"\nVERSION_STRING_DELIMITER=.\nVERSION_STRING_ARRAY=($(echo \"$new_version\" | tr $VERSION_STRING_DELIMITER '\\n'))\nif [ \"${VERSION_STRING_ARRAY[0]}\" == \"0\" ]; then\n    IS_PRE_RELEASE=\"true\"\nelse\n    IS_PRE_RELEASE=\"false\"\nfi\n\n# Create the release with auto-generated notes as the description\n# - NOTE: This will only add notes if there is at least one PR. If there is no PRs,\n# - then this will be blank and need manual input/changing after running.\nif [ $IS_PRE_RELEASE == \"true\" ]; then\n    gh release create \"v${new_version}\" -p --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nelse\n    gh release create \"v${new_version}\" --generate-notes --notes-start-tag \"$current_version\" --target main -t \"${RELEASE_TITLE}\"\nfi\n\npopd > /dev/null\n", "num_lines": 94}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nif (($#<1)); then\n    echo \"Error: Output files not provided\" >&2\n    exit -1\nfi\n\nrm -rf build/dist\nmkdir build/dist\ncd build/dist\n\nfor FILE in $@; do\n    SRC=`echo $FILE | cut -d ':' -f1`\n    DEST=`echo $FILE | cut -d ':' -f2`\n    mkdir -p $DEST\n    cp ../../$SRC $DEST\ndone\n\ncp -r ../../LICENSE \\\n    ../../THIRD-PARTY-LICENSES \\\n    ../../configuration \\\n    ../../tools \\\n    .\nrm -rf tools/android-app\n\ntar -zcf ../aws-iot-fleetwise-edge.tar.gz *\n", "num_lines": 31}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nSCRIPT_DIR=$(dirname $(realpath \"$0\"))\nsource ${SCRIPT_DIR}/install-deps-versions.sh\n\nNATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --native-prefix)\n            NATIVE_PREFIX=\"$2\"\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --native-prefix  Native install prefix, default ${NATIVE_PREFIX}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\nexport PATH=/usr/local/android_sdk/cmake/${VERSION_CMAKE}/bin:${NATIVE_PREFIX}/bin:${PATH}\nmkdir -p build && cd build\n\nbuild() {\n    TARGET_ARCH=\"$1\"\n    HOST_PLATFORM=\"$2\"\n\n    mkdir ${TARGET_ARCH} && cd ${TARGET_ARCH}\n    LDFLAGS=-L/usr/local/${HOST_PLATFORM}/lib cmake \\\n        -DFWE_STATIC_LINK=On \\\n        -DFWE_STRIP_SYMBOLS=On \\\n        -DFWE_FEATURE_CUSTOM_DATA_SOURCE=On \\\n        -DFWE_FEATURE_EXTERNAL_GPS=On \\\n        -DFWE_BUILD_EXECUTABLE=Off \\\n        -DFWE_BUILD_ANDROID_SHARED_LIBRARY=On \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_TESTING=Off \\\n        -DANDROID_ABI=${TARGET_ARCH} \\\n        -DANDROID_PLATFORM=android-${VERSION_ANDROID_API} \\\n        -DCMAKE_ANDROID_NDK=/usr/local/android_sdk/ndk/${VERSION_ANDROID_NDK} \\\n        -DCMAKE_TOOLCHAIN_FILE=/usr/local/android_sdk/ndk/${VERSION_ANDROID_NDK}/build/cmake/android.toolchain.cmake \\\n        -DANDROID_TOOLCHAIN=clang \\\n        -DCMAKE_FIND_ROOT_PATH=/usr/local/${HOST_PLATFORM} \\\n        ../..\n    make -j`nproc`\n    cd ..\n}\n\nbuild \"armeabi-v7a\" \"armv7a-linux-androideabi\"\nbuild \"arm64-v8a\" \"aarch64-linux-android\"\n", "num_lines": 61}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\nNATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nexport PATH=${NATIVE_PREFIX}/bin:${PATH}\nmkdir -p build && cd build\ncmake \\\n  -DFWE_STATIC_LINK=On \\\n  -DFWE_STRIP_SYMBOLS=On \\\n  -DFWE_SECURITY_COMPILE_FLAGS=On \\\n  -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n  -DBUILD_TESTING=Off \\\n  ..\nmake -j`nproc`\n", "num_lines": 18}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\nNATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nexport PATH=${NATIVE_PREFIX}/bin:${PATH}\nmkdir -p build && cd build\ncmake \\\n  -DFWE_STATIC_LINK=On \\\n  -DFWE_STRIP_SYMBOLS=On \\\n  -DFWE_SECURITY_COMPILE_FLAGS=On \\\n  -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n  -DBUILD_TESTING=Off \\\n  ..\nmake -j`nproc`\n", "num_lines": 18}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\nPREFIX=\"/usr/local/`gcc -dumpmachine`\"\nexport PATH=${PREFIX}/bin:${PATH}\nmkdir -p build && cd build\ncmake \\\n  -DFWE_STATIC_LINK=On \\\n  -DFWE_STRIP_SYMBOLS=On \\\n  -DFWE_SECURITY_COMPILE_FLAGS=On \\\n  -DFWE_TEST_FAKETIME=On \\\n  -DCMAKE_PREFIX_PATH=${PREFIX} \\\n  ..\nmake -j`nproc`\n", "num_lines": 18}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nif [ -z \"${INPUT_CONFIG_FILE+x}\" ]; then\n    INPUT_CONFIG_FILE=\"\"\nfi\nif [ -z \"${OUTPUT_CONFIG_FILE+x}\" ]; then\n    OUTPUT_CONFIG_FILE=\"\"\nfi\nif [ -z \"${CERTIFICATE+x}\" ]; then\n    CERTIFICATE=\"\"\nfi\nif [ -z \"${CERTIFICATE_FILE+x}\" ]; then\n    CERTIFICATE_FILE=\"/etc/aws-iot-fleetwise/certificate.pem\"\nfi\nif [ -z \"${PRIVATE_KEY+x}\" ]; then\n    PRIVATE_KEY=\"\"\nfi\nif [ -z \"${PRIVATE_KEY_FILE+x}\" ]; then\n    PRIVATE_KEY_FILE=\"/etc/aws-iot-fleetwise/private-key.key\"\nfi\nif [ -z \"${VEHICLE_NAME+x}\" ]; then\n    VEHICLE_NAME=\"\"\nfi\nif [ -z \"${ENDPOINT_URL+x}\" ]; then\n    ENDPOINT_URL=\"\"\nfi\nif [ -z \"${CAN_BUS0+x}\" ]; then\n    CAN_BUS0=\"vcan0\"\nfi\nif [ -z \"${LOG_LEVEL+x}\" ]; then\n    LOG_LEVEL=\"Info\"\nfi\nif [ -z \"${LOG_COLOR+x}\" ]; then\n    LOG_COLOR=\"Auto\"\nfi\nif [ -z \"${PERSISTENCY_PATH+x}\" ]; then\n    PERSISTENCY_PATH=\"/var/aws-iot-fleetwise/\"\nfi\nif [ -z \"${TOPIC_PREFIX+x}\" ]; then\n    TOPIC_PREFIX=\"\\$aws/iotfleetwise/\"\nfi\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --input-config-file)\n            INPUT_CONFIG_FILE=$2\n            shift\n            ;;\n        --output-config-file)\n            OUTPUT_CONFIG_FILE=$2\n            shift\n            ;;\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --certificate)\n            CERTIFICATE=$2\n            shift\n            ;;\n        --certificate-file)\n            CERTIFICATE_FILE=$2\n            shift\n            ;;\n        --private-key)\n            PRIVATE_KEY=$2\n            shift\n            ;;\n        --private-key-file)\n            PRIVATE_KEY_FILE=$2\n            shift\n            ;;\n        --can-bus0)\n            CAN_BUS0=$2\n            shift\n            ;;\n        --persistency-path)\n            PERSISTENCY_PATH=$2\n            shift\n            ;;\n        --topic-prefix)\n            TOPIC_PREFIX=$2\n            shift\n            ;;\n        --log-level)\n            LOG_LEVEL=$2\n            shift\n            ;;\n        --log-color)\n            LOG_COLOR=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --input-config-file <FILE>   Input JSON config file\"\n            echo \"  --output-config-file <FILE>  Output JSON config file\"\n            echo \"  --vehicle-name <NAME>        Vehicle name\"\n            echo \"  --endpoint-url <URL>         IoT Core MQTT endpoint URL\"\n            echo \"  --can-bus0 <BUS>             CAN bus 0, default: ${CAN_BUS0}\"\n            echo \"  --certificate <CERTIFICATE>  Certificate\"\n            echo \"  --certificate-file <FILE>    Certificate file, default: ${CERTIFICATE_FILE}\"\n            echo \"  --private-key <KEY>          Private key\"\n            echo \"  --private-key-file <FILE>    Private key file, default: ${PRIVATE_KEY_FILE}\"\n            echo \"  --persistency-path <PATH>    Persistency path, default: ${PERSISTENCY_PATH}\"\n            echo \"  --topic-prefix <PREFIX>      IoT MQTT topic prefix, default: ${TOPIC_PREFIX}\"\n            echo \"  --log-level <LEVEL>          Log level. Either: Off, Error, Warning, Info, Trace. Default: ${LOG_LEVEL}\"\n            echo \"  --log-color <COLOR_OPTION>   Whether logs should be colored. Either: Auto, Yes, No. Default: ${LOG_COLOR}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${INPUT_CONFIG_FILE}\" == \"\" ]; then\n        echo \"Error: No input config file specified\"\n        exit -1\n    fi\n    if [ \"${OUTPUT_CONFIG_FILE}\" == \"\" ]; then\n        echo \"Error: No output config file specified\"\n        exit -1\n    fi\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        echo \"Error: No Vehicle name specified\"\n        exit -1\n    fi\n    if [ \"${ENDPOINT_URL}\" == \"\" ]; then\n        echo \"Error: No endpoint URL specified\"\n        exit -1\n    fi\n}\n\nparse_args \"$@\"\n\nif [ \"`jq '.networkInterfaces[0].canInterface' ${INPUT_CONFIG_FILE}`\" == \"null\" ] \\\n    || [ \"`jq '.networkInterfaces[1].obdInterface' ${INPUT_CONFIG_FILE}`\" == \"null\" ]; then\n    echo \"Error: Unexpected format in input config file\"\n    exit -1\nfi\n\n# Create the config file:\njq \".staticConfig.mqttConnection.endpointUrl=\\\"${ENDPOINT_URL}\\\"\" ${INPUT_CONFIG_FILE} \\\n    | jq \".staticConfig.mqttConnection.clientId=\\\"${VEHICLE_NAME}\\\"\" \\\n    | jq \".staticConfig.mqttConnection.collectionSchemeListTopic=\\\"${TOPIC_PREFIX}vehicles/${VEHICLE_NAME}/collection_schemes\\\"\" \\\n    | jq \".staticConfig.mqttConnection.decoderManifestTopic=\\\"${TOPIC_PREFIX}vehicles/${VEHICLE_NAME}/decoder_manifests\\\"\" \\\n    | jq \".staticConfig.mqttConnection.canDataTopic=\\\"${TOPIC_PREFIX}vehicles/${VEHICLE_NAME}/signals\\\"\" \\\n    | jq \".staticConfig.mqttConnection.checkinTopic=\\\"${TOPIC_PREFIX}vehicles/${VEHICLE_NAME}/checkins\\\"\" \\\n    | if [[ $CERTIFICATE ]]; \\\n        then jq \"del(.staticConfig.mqttConnection.certificateFilename)\" | jq \".staticConfig.mqttConnection.certificate=\\\"${CERTIFICATE}\\\"\"; \\\n        else jq \".staticConfig.mqttConnection.certificateFilename=\\\"${CERTIFICATE_FILE}\\\"\"; \\\n        fi \\\n    | if [[ $PRIVATE_KEY ]]; \\\n        then jq \"del(.staticConfig.mqttConnection.privateKeyFilename)\" | jq \".staticConfig.mqttConnection.privateKey=\\\"${PRIVATE_KEY}\\\"\"; \\\n        else jq \".staticConfig.mqttConnection.privateKeyFilename=\\\"${PRIVATE_KEY_FILE}\\\"\"; \\\n        fi \\\n    | jq \".staticConfig.internalParameters.systemWideLogLevel=\\\"${LOG_LEVEL}\\\"\" \\\n    | jq \".staticConfig.internalParameters.logColor=\\\"${LOG_COLOR}\\\"\" \\\n    | jq \".staticConfig.persistency.persistencyPath=\\\"${PERSISTENCY_PATH}\\\"\" \\\n    | jq \".networkInterfaces[0].canInterface.interfaceName=\\\"${CAN_BUS0}\\\"\" \\\n    | jq \".networkInterfaces[1].obdInterface.interfaceName=\\\"${CAN_BUS0}\\\"\" \\\n    | jq \".networkInterfaces[1].obdInterface.pidRequestIntervalSeconds=5\" \\\n    | jq \".networkInterfaces[1].obdInterface.dtcRequestIntervalSeconds=5\" \\\n    | jq \".networkInterfaces[1].interfaceId=\\\"0\\\"\" \\\n    | jq \".staticConfig.publishToCloudParameters.collectionSchemeManagementCheckinIntervalMs=5000\" \\\n    > ${OUTPUT_CONFIG_FILE}\n", "num_lines": 174}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\nBUS_COUNT=1\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --bus-count)\n            BUS_COUNT=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --bus-count <NUM>  Number of CAN buses\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\n# Install Python 3 and pip\napt update && apt install -y python3 python3-pip\n\n# Install pip packages\npip3 install \\\n    wrapt==1.10.0 \\\n    cantools==36.4.0 \\\n    prompt_toolkit==3.0.21 \\\n    python-can==3.3.4 \\\n    can-isotp==1.7 \\\n    matplotlib==3.4.3\n\n# Install CAN Simulator\ncp -r tools/cansim /usr/share\ncp tools/cansim/cansim@.service /lib/systemd/system/\nsystemctl daemon-reload\nsystemctl enable `seq -f \"cansim@%.0f\" 0 $((BUS_COUNT-1))`\nsystemctl start `seq -f \"cansim@%.0f\" 0 $((BUS_COUNT-1))`\n", "num_lines": 46}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nSCRIPT_DIR=$(dirname $(realpath \"$0\"))\nsource ${SCRIPT_DIR}/install-deps-versions.sh\n\nUSE_CACHE=\"true\"\nSDK_PREFIX=\"/usr/local/android_sdk\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --native-prefix)\n            NATIVE_PREFIX=\"$2\"\n            USE_CACHE=\"false\"\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --native-prefix  Native install prefix\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\napt update\napt install -y \\\n    unzip \\\n    git \\\n    wget \\\n    curl \\\n    default-jre \\\n    build-essential \\\n    file\n\nif [ ! -d ${SDK_PREFIX} ]; then\n    curl -o cmdline-tools.zip https://dl.google.com/android/repository/commandlinetools-linux-${VERSION_ANDROID_CMDLINE_TOOLS}_latest.zip\n    unzip cmdline-tools.zip\n    rm cmdline-tools.zip\n    mkdir -p ${SDK_PREFIX}/cmdline-tools\n    mv cmdline-tools ${SDK_PREFIX}/cmdline-tools/latest\n    yes | ${SDK_PREFIX}/cmdline-tools/latest/bin/sdkmanager --licenses || true\n    ${SDK_PREFIX}/cmdline-tools/latest/bin/sdkmanager --install \\\n        \"ndk;${VERSION_ANDROID_NDK}\" \\\n        \"cmake;${VERSION_CMAKE}\" \\\n        \"platforms;android-${VERSION_ANDROID_SDK}\" \\\n        \"platform-tools\" \\\n        \"emulator\" \\\n        \"build-tools;${VERSION_ANDROID_BUILD_TOOLS}\"\nfi\nexport PATH=${SDK_PREFIX}/cmake/${VERSION_CMAKE}/bin/:${PATH}\n\nif [ -z \"${NATIVE_PREFIX+x}\" ]; then\n    NATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nfi\n\ninstall_deps() {\n    TARGET_ARCH=\"$1\"\n    HOST_PLATFORM=\"$2\"\n    SSL_TARGET=\"$3\"\n    INSTALL_PREFIX=\"/usr/local/${HOST_PLATFORM}\"\n\n    mkdir -p ${INSTALL_PREFIX}\n    mkdir -p ${NATIVE_PREFIX}\n    mkdir deps-cross-android && cd deps-cross-android\n\n    # Boost\n    git clone https://github.com/moritz-wundke/Boost-for-Android.git\n    cd Boost-for-Android\n    git checkout 53e6c16ea80c7dcb2683fd548e0c7a09ddffbfc1\n    ./build-android.sh \\\n        ${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        --boost=${VERSION_BOOST} \\\n        --with-libraries=system,thread,filesystem,chrono,date_time,atomic \\\n        --layout=system \\\n        --arch=${TARGET_ARCH} \\\n        --target-version=${VERSION_ANDROID_API} > /dev/null\n    mv build/out/${TARGET_ARCH}/lib ${INSTALL_PREFIX}\n    mv build/out/${TARGET_ARCH}/include ${INSTALL_PREFIX}\n    cd ..\n\n    # Snappy\n    git clone -b ${VERSION_SNAPPY} https://github.com/google/snappy.git\n    cd snappy\n    mkdir build && cd build\n    cmake \\\n        -DSNAPPY_BUILD_TESTS=OFF \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DSNAPPY_BUILD_BENCHMARKS=OFF \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DANDROID_ABI=${TARGET_ARCH} \\\n        -DANDROID_PLATFORM=android-${VERSION_ANDROID_API} \\\n        -DCMAKE_ANDROID_NDK=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        -DCMAKE_TOOLCHAIN_FILE=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK}/build/cmake/android.toolchain.cmake \\\n        -DANDROID_TOOLCHAIN=clang \\\n        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    # Protobuf\n    wget -q https://github.com/protocolbuffers/protobuf/releases/download/${VERSION_PROTOBUF_RELEASE}/protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    tar -zxf protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    cd protobuf-${VERSION_PROTOBUF}\n    if [ ! -f ${NATIVE_PREFIX}/bin/protoc ]; then\n        mkdir build_native && cd build_native\n        ../configure --prefix=${NATIVE_PREFIX}\n        make install -j`nproc`\n        cd ..\n    fi\n    mkdir build_target && cd build_target\n    NDK=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        TOOLCHAIN=${NDK}/toolchains/llvm/prebuilt/linux-x86_64 \\\n        TARGET=${HOST_PLATFORM} \\\n        API=${VERSION_ANDROID_API} \\\n        AR=${TOOLCHAIN}/bin/llvm-ar \\\n        CC=${TOOLCHAIN}/bin/${TARGET}${API}-clang \\\n        AS=${CC} \\\n        CXX=${TOOLCHAIN}/bin/${TARGET}${API}-clang++ \\\n        LD=${TOOLCHAIN}/bin/ld \\\n        RANLIB=${TOOLCHAIN}/bin/llvm-ranlib \\\n        STRIP=${TOOLCHAIN}/bin/llvm-strip \\\n        ../configure \\\n            --host=${HOST_PLATFORM} \\\n            --prefix=${INSTALL_PREFIX} \\\n            \"CFLAGS=-fPIC\" \"CXXFLAGS=-fPIC\"\n    make install -j`nproc`\n    cd ../..\n\n    # JsonCpp\n    git clone -b ${VERSION_JSON_CPP} https://github.com/open-source-parsers/jsoncpp.git\n    cd jsoncpp\n    mkdir build && cd build\n    cmake \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n        -DJSONCPP_WITH_TESTS=Off \\\n        -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off \\\n        -DANDROID_ABI=${TARGET_ARCH} \\\n        -DANDROID_PLATFORM=android-${VERSION_ANDROID_API} \\\n        -DCMAKE_ANDROID_NDK=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        -DCMAKE_TOOLCHAIN_FILE=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK}/build/cmake/android.toolchain.cmake \\\n        -DANDROID_TOOLCHAIN=clang \\\n        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    # OpenSSL\n    wget -q https://www.openssl.org/source/openssl-${VERSION_OPENSSL}.tar.gz\n    tar -zxf openssl-${VERSION_OPENSSL}.tar.gz\n    cd openssl-${VERSION_OPENSSL}\n    ANDROID_NDK_HOME=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        PATH=${ANDROID_NDK_HOME}/toolchains/llvm/prebuilt/linux-x86_64/bin:${PATH} \\\n        INSTALL_PREFIX=${INSTALL_PREFIX} SSL_TARGET=${SSL_TARGET} VERSION_ANDROID_API=${VERSION_ANDROID_API} \\\n        bash -c './Configure ${SSL_TARGET} -D__ANDROID_API__=${VERSION_ANDROID_API} --prefix=${INSTALL_PREFIX} no-shared \\\n            && make -j`nproc`'\n    make install > /dev/null\n    cd ..\n\n    # curl\n    wget -q https://github.com/curl/curl/releases/download/${VERSION_CURL_RELEASE}/curl-${VERSION_CURL}.tar.gz\n    tar -zxf curl-${VERSION_CURL}.tar.gz\n    cd curl-${VERSION_CURL}\n    NDK=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        TOOLCHAIN=${NDK}/toolchains/llvm/prebuilt/linux-x86_64 \\\n        TARGET=${HOST_PLATFORM} \\\n        API=${VERSION_ANDROID_API} \\\n        AR=${TOOLCHAIN}/bin/llvm-ar \\\n        CC=${TOOLCHAIN}/bin/${TARGET}${API}-clang \\\n        AS=${CC} \\\n        CXX=${TOOLCHAIN}/bin/${TARGET}${API}-clang++ \\\n        LD=${TOOLCHAIN}/bin/ld \\\n        RANLIB=${TOOLCHAIN}/bin/llvm-ranlib \\\n        STRIP=${TOOLCHAIN}/bin/llvm-strip \\\n        LDFLAGS=\"-static\" \\\n        PKG_CONFIG=\"pkg-config --static\" \\\n        ./configure \\\n            --disable-shared \\\n            --enable-static \\\n            --disable-ldap \\\n            --enable-ipv6 \\\n            --with-ssl=${INSTALL_PREFIX} \\\n            --disable-unix-sockets \\\n            --disable-rtsp \\\n            --host=${HOST_PLATFORM} \\\n            --prefix=${INSTALL_PREFIX}\n    make install -j`nproc` V=1 LDFLAGS=\"-static -L${INSTALL_PREFIX}/lib\"\n    cd ..\n\n    # AWS C++ SDK\n    git clone -b ${VERSION_AWS_SDK_CPP} --recursive https://github.com/aws/aws-sdk-cpp.git\n    cd aws-sdk-cpp\n    mkdir build && cd build\n    CFLAGS=-I${INSTALL_PREFIX}/include cmake \\\n        -DENABLE_TESTING=OFF \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_ONLY='s3-crt;iot' \\\n        -DAWS_CUSTOM_MEMORY_MANAGEMENT=ON \\\n        -DANDROID_ABI=${TARGET_ARCH} \\\n        -DANDROID_PLATFORM=android-${VERSION_ANDROID_API} \\\n        -DCMAKE_ANDROID_NDK=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK} \\\n        -DCMAKE_TOOLCHAIN_FILE=${SDK_PREFIX}/ndk/${VERSION_ANDROID_NDK}/build/cmake/android.toolchain.cmake \\\n        -DANDROID_TOOLCHAIN=clang \\\n        -DCURL_LIBRARY=${INSTALL_PREFIX}/lib/libcurl.a \\\n        -DCMAKE_FIND_ROOT_PATH=${INSTALL_PREFIX} \\\n        -DCMAKE_INSTALL_PREFIX=${INSTALL_PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n    # pthread is directly linked somewhere, so just create a dummy .a file\n    ar -rc ${INSTALL_PREFIX}/lib/libpthread.a\n\n    cd ..\n    rm -rf deps-cross-android\n}\n\nif ! ${USE_CACHE} || [ ! -d /usr/local/aarch64-linux-android ]  || [ ! -d /usr/local/armv7a-linux-androideabi ] || [ ! -d ${NATIVE_PREFIX} ]; then\n    install_deps \"armeabi-v7a\" \"armv7a-linux-androideabi\" \"android-arm\"\n    install_deps \"arm64-v8a\" \"aarch64-linux-android\" \"android-arm64\"\nfi\n", "num_lines": 230}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nSCRIPT_DIR=$(dirname $(realpath \"$0\"))\nsource ${SCRIPT_DIR}/install-deps-versions.sh\n\nWITH_CAMERA_SUPPORT=\"false\"\nUSE_CACHE=\"true\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --with-camera-support)\n            WITH_CAMERA_SUPPORT=\"true\"\n            ;;\n        --native-prefix)\n            NATIVE_PREFIX=\"$2\"\n            USE_CACHE=\"false\"\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --with-camera-support  Install dependencies for camera support\"\n            echo \"  --native-prefix        Native install prefix\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\nARCH=`dpkg --print-architecture`\nif [ \"${ARCH}\" == \"arm64\" ]; then\n    echo \"Error: Architecture is already ${ARCH}, use install-deps-native.sh\" >&2\n    exit -1\nfi\n\nsed -i \"s/deb http/deb [arch=${ARCH}] http/g\" /etc/apt/sources.list\ncp /etc/apt/sources.list /etc/apt/sources.list.d/arm64.list\nsed -i \"s/deb \\[arch=${ARCH}\\] http/deb [arch=arm64] http/g\" /etc/apt/sources.list.d/arm64.list\nsed -i \"s#archive.ubuntu.com/ubuntu#ports.ubuntu.com/ubuntu-ports#g\" /etc/apt/sources.list.d/arm64.list\ndpkg --add-architecture arm64\napt update\napt install -y \\\n    build-essential \\\n    cmake \\\n    crossbuild-essential-arm64 \\\n    curl \\\n    git \\\n    libboost-log-dev:arm64 \\\n    libboost-system-dev:arm64 \\\n    libboost-thread-dev:arm64 \\\n    libsnappy-dev:arm64 \\\n    libssl-dev:arm64 \\\n    unzip \\\n    wget \\\n    zlib1g-dev:arm64\n\nif ${WITH_CAMERA_SUPPORT}; then\n    apt install -y \\\n        default-jre \\\n        libasio-dev \\\n        qemu-user-binfmt\nfi\n\nif [ ! -f /usr/include/linux/can/isotp.h ]; then\n    git clone https://github.com/hartkopp/can-isotp.git\n    cd can-isotp\n    git checkout beb4650660179963a8ed5b5cbf2085cc1b34f608\n    cp include/uapi/linux/can/isotp.h /usr/include/linux/can\n    cd ..\n    rm -rf can-isotp\nfi\n\nif [ -z \"${NATIVE_PREFIX+x}\" ]; then\n    NATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nfi\n\nif ! ${USE_CACHE} || [ ! -d /usr/local/aarch64-linux-gnu ] || [ ! -d ${NATIVE_PREFIX} ]; then\n    mkdir -p /usr/local/aarch64-linux-gnu/lib/cmake/\n    mkdir -p ${NATIVE_PREFIX}\n    cp ${SCRIPT_DIR}/arm64-toolchain.cmake /usr/local/aarch64-linux-gnu/lib/cmake/\n    mkdir deps-cross-arm64 && cd deps-cross-arm64\n\n    git clone -b ${VERSION_JSON_CPP} https://github.com/open-source-parsers/jsoncpp.git\n    cd jsoncpp\n    mkdir build && cd build\n    cmake \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n        -DJSONCPP_WITH_TESTS=Off \\\n        -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off \\\n        -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n        -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/protocolbuffers/protobuf/releases/download/${VERSION_PROTOBUF_RELEASE}/protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    tar -zxf protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    cd protobuf-${VERSION_PROTOBUF}\n    mkdir build && cd build\n    ../configure --prefix=${NATIVE_PREFIX}\n    make install -j`nproc`\n    cd ..\n    mkdir build_arm64 && cd build_arm64\n    CC=aarch64-linux-gnu-gcc CXX=aarch64-linux-gnu-g++ \\\n        ../configure --host=aarch64-linux --prefix=/usr/local/aarch64-linux-gnu\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/curl/curl/releases/download/${VERSION_CURL_RELEASE}/curl-${VERSION_CURL}.tar.gz\n    tar -zxf curl-${VERSION_CURL}.tar.gz\n    cd curl-${VERSION_CURL}\n    mkdir build && cd build\n    LDFLAGS=\"-static\" PKG_CONFIG=\"pkg-config --static\" CC=aarch64-linux-gnu-gcc ../configure \\\n        --disable-shared --enable-static --disable-ldap --enable-ipv6 --with-ssl --disable-unix-sockets \\\n        --disable-rtsp --without-zstd --host=aarch64-linux --prefix=/usr/local/aarch64-linux-gnu\n    make install -j`nproc` V=1 LDFLAGS=\"-static\"\n    cd ../..\n\n    git clone -b ${VERSION_AWS_SDK_CPP} --recursive https://github.com/aws/aws-sdk-cpp.git\n    cd aws-sdk-cpp\n    mkdir build && cd build\n    cmake \\\n        -DENABLE_TESTING=OFF \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_ONLY='s3-crt;iot' \\\n        -DAWS_CUSTOM_MEMORY_MANAGEMENT=ON \\\n        -DZLIB_LIBRARY=/usr/lib/aarch64-linux-gnu/libz.a \\\n        -DCURL_LIBRARY=/usr/local/aarch64-linux-gnu/lib/libcurl.a \\\n        -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n        -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    # AWS IoT FleetWise Edge camera support requires Fast-DDS and its dependencies:\n    if ${WITH_CAMERA_SUPPORT}; then\n        git clone -b ${VERSION_TINYXML2} https://github.com/leethomason/tinyxml2.git\n        cd tinyxml2\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DBUILD_STATIC_LIBS=ON \\\n            -DBUILD_TESTS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FOONATHAN_MEMORY_VENDOR} https://github.com/eProsima/foonathan_memory_vendor.git\n        cd foonathan_memory_vendor\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -Dextra_cmake_args=\"-DCMAKE_CROSSCOMPILING_EMULATOR=qemu-aarch64\" \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_CDR} https://github.com/eProsima/Fast-CDR.git\n        cd Fast-CDR\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS} https://github.com/eProsima/Fast-DDS.git\n        cd Fast-DDS\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCOMPILE_TOOLS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_CXX_FLAGS=\"-DUSE_FOONATHAN_NODE_SIZES=1\" \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/aarch64-linux-gnu/lib/cmake/arm64-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/aarch64-linux-gnu \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS_GEN} --recursive https://github.com/eProsima/Fast-DDS-Gen.git\n        cd Fast-DDS-Gen\n        ./gradlew assemble\n        mkdir -p ${NATIVE_PREFIX}/share/fastddsgen/java\n        cp share/fastddsgen/java/fastddsgen.jar ${NATIVE_PREFIX}/share/fastddsgen/java\n        cp scripts/fastddsgen ${NATIVE_PREFIX}/bin\n        cd ..\n    fi\n\n    cd ..\n    rm -rf deps-cross-arm64\nfi\n", "num_lines": 215}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nSCRIPT_DIR=$(dirname $(realpath \"$0\"))\nsource ${SCRIPT_DIR}/install-deps-versions.sh\n\nWITH_CAMERA_SUPPORT=\"false\"\nUSE_CACHE=\"true\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --with-camera-support)\n            WITH_CAMERA_SUPPORT=\"true\"\n            ;;\n        --native-prefix)\n            NATIVE_PREFIX=\"$2\"\n            USE_CACHE=\"false\"\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --with-camera-support  Install dependencies for camera support\"\n            echo \"  --native-prefix        Native install prefix\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\nARCH=`dpkg --print-architecture`\nif [ \"${ARCH}\" == \"armhf\" ]; then\n    echo \"Error: Architecture is already ${ARCH}, use install-deps-native.sh\" >&2\n    exit -1\nfi\n\nsed -i \"s/deb http/deb [arch=${ARCH}] http/g\" /etc/apt/sources.list\ncp /etc/apt/sources.list /etc/apt/sources.list.d/armhf.list\nsed -i \"s/deb \\[arch=${ARCH}\\] http/deb [arch=armhf] http/g\" /etc/apt/sources.list.d/armhf.list\nsed -i \"s#archive.ubuntu.com/ubuntu#ports.ubuntu.com/ubuntu-ports#g\" /etc/apt/sources.list.d/armhf.list\ndpkg --add-architecture armhf\napt update\napt install -y \\\n    build-essential \\\n    cmake \\\n    crossbuild-essential-armhf \\\n    curl \\\n    git \\\n    libboost-log-dev:armhf \\\n    libboost-system-dev:armhf \\\n    libboost-thread-dev:armhf \\\n    libsnappy-dev:armhf \\\n    libssl-dev:armhf \\\n    unzip \\\n    wget \\\n    zlib1g-dev:armhf\n\nif ${WITH_CAMERA_SUPPORT}; then\n    apt install -y \\\n        default-jre \\\n        libasio-dev \\\n        qemu-user-binfmt\nfi\n\nif [ ! -f /usr/include/linux/can/isotp.h ]; then\n    git clone https://github.com/hartkopp/can-isotp.git\n    cd can-isotp\n    git checkout beb4650660179963a8ed5b5cbf2085cc1b34f608\n    cp include/uapi/linux/can/isotp.h /usr/include/linux/can\n    cd ..\n    rm -rf can-isotp\nfi\n\nif [ -z \"${NATIVE_PREFIX+x}\" ]; then\n    NATIVE_PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nfi\n\nif ! ${USE_CACHE} || [ ! -d /usr/local/arm-linux-gnueabihf ] || [ ! -d ${NATIVE_PREFIX} ]; then\n    mkdir -p /usr/local/arm-linux-gnueabihf/lib/cmake/\n    mkdir -p ${NATIVE_PREFIX}\n    cp ${SCRIPT_DIR}/armhf-toolchain.cmake /usr/local/arm-linux-gnueabihf/lib/cmake/\n    mkdir deps-cross-armhf && cd deps-cross-armhf\n\n    git clone -b ${VERSION_JSON_CPP} https://github.com/open-source-parsers/jsoncpp.git\n    cd jsoncpp\n    mkdir build && cd build\n    cmake \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n        -DJSONCPP_WITH_TESTS=Off \\\n        -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off \\\n        -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n        -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/protocolbuffers/protobuf/releases/download/${VERSION_PROTOBUF_RELEASE}/protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    tar -zxf protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    cd protobuf-${VERSION_PROTOBUF}\n    mkdir build && cd build\n    ../configure --prefix=${NATIVE_PREFIX}\n    make install -j`nproc`\n    cd ..\n    mkdir build_armhf && cd build_armhf\n    CC=arm-linux-gnueabihf-gcc CXX=arm-linux-gnueabihf-g++ \\\n        ../configure --host=arm-linux --prefix=/usr/local/arm-linux-gnueabihf\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/curl/curl/releases/download/${VERSION_CURL_RELEASE}/curl-${VERSION_CURL}.tar.gz\n    tar -zxf curl-${VERSION_CURL}.tar.gz\n    cd curl-${VERSION_CURL}\n    mkdir build && cd build\n    LDFLAGS=\"-static\" PKG_CONFIG=\"pkg-config --static\" CC=arm-linux-gnueabihf-gcc ../configure \\\n        --disable-shared --enable-static --disable-ldap --enable-ipv6 --with-ssl --disable-unix-sockets \\\n        --disable-rtsp --without-zstd --host=arm-linux --prefix=/usr/local/arm-linux-gnueabihf\n    make install -j`nproc` V=1 LDFLAGS=\"-static\"\n    cd ../..\n\n    git clone -b ${VERSION_AWS_SDK_CPP} --recursive https://github.com/aws/aws-sdk-cpp.git\n    cd aws-sdk-cpp\n    mkdir build && cd build\n    cmake \\\n        -DENABLE_TESTING=OFF \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_ONLY='s3-crt;iot' \\\n        -DAWS_CUSTOM_MEMORY_MANAGEMENT=ON \\\n        -DZLIB_LIBRARY=/usr/lib/arm-linux-gnueabihf/libz.a \\\n        -DCURL_LIBRARY=/usr/local/arm-linux-gnueabihf/lib/libcurl.a \\\n        -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n        -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    # AWS IoT FleetWise Edge camera support requires Fast-DDS and its dependencies:\n    if ${WITH_CAMERA_SUPPORT}; then\n        git clone -b ${VERSION_TINYXML2} https://github.com/leethomason/tinyxml2.git\n        cd tinyxml2\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DBUILD_STATIC_LIBS=ON \\\n            -DBUILD_TESTS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FOONATHAN_MEMORY_VENDOR} https://github.com/eProsima/foonathan_memory_vendor.git\n        cd foonathan_memory_vendor\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -Dextra_cmake_args=\"-DCMAKE_CROSSCOMPILING_EMULATOR=qemu-arm\" \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_CDR} https://github.com/eProsima/Fast-CDR.git\n        cd Fast-CDR\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS} https://github.com/eProsima/Fast-DDS.git\n        cd Fast-DDS\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCOMPILE_TOOLS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_CXX_FLAGS=\"-DUSE_FOONATHAN_NODE_SIZES=1\" \\\n            -DCMAKE_TOOLCHAIN_FILE=/usr/local/arm-linux-gnueabihf/lib/cmake/armhf-toolchain.cmake \\\n            -DCMAKE_INSTALL_PREFIX=/usr/local/arm-linux-gnueabihf \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS_GEN} --recursive https://github.com/eProsima/Fast-DDS-Gen.git\n        cd Fast-DDS-Gen\n        ./gradlew assemble\n        mkdir -p ${NATIVE_PREFIX}/share/fastddsgen/java\n        cp share/fastddsgen/java/fastddsgen.jar ${NATIVE_PREFIX}/share/fastddsgen/java\n        cp scripts/fastddsgen ${NATIVE_PREFIX}/bin\n        cd ..\n    fi\n\n    cd ..\n    rm -rf deps-cross-armhf\nfi\n", "num_lines": 215}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nSCRIPT_DIR=$(dirname $(realpath \"$0\"))\nsource ${SCRIPT_DIR}/install-deps-versions.sh\n\nWITH_CAMERA_SUPPORT=\"false\"\nUSE_CACHE=\"true\"\nINSTALL_BUILD_TIME_DEPS=\"true\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --with-camera-support)\n            WITH_CAMERA_SUPPORT=\"true\"\n            ;;\n        --prefix)\n            PREFIX=\"$2\"\n            USE_CACHE=\"false\"\n            shift\n            ;;\n        --runtime-only)\n            INSTALL_BUILD_TIME_DEPS=\"false\"\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --with-camera-support  Install dependencies for camera support\"\n            echo \"  --runtime-only         Install only runtime dependencies\"\n            echo \"  --prefix               Install prefix\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\nif ${INSTALL_BUILD_TIME_DEPS}; then\n    apt update\n    apt install -y \\\n        build-essential \\\n        clang-format-10 \\\n        clang-tidy-10 \\\n        cmake \\\n        doxygen \\\n        faketime \\\n        git \\\n        graphviz \\\n        libboost-log-dev \\\n        libboost-system-dev \\\n        libboost-thread-dev \\\n        libsnappy-dev \\\n        libssl-dev \\\n        unzip \\\n\t\twget \\\n        zlib1g-dev\n    update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-10 1000\n    update-alternatives --install /usr/bin/clang-tidy clang-tidy /usr/bin/clang-tidy-10 1000\nfi\n\nif ${INSTALL_BUILD_TIME_DEPS} && ${WITH_CAMERA_SUPPORT}; then\n    apt install -y \\\n        default-jre \\\n        libasio-dev\nfi\n\nif ${INSTALL_BUILD_TIME_DEPS} && [ ! -f /usr/include/linux/can/isotp.h ]; then\n    git clone https://github.com/hartkopp/can-isotp.git\n    cd can-isotp\n    git checkout beb4650660179963a8ed5b5cbf2085cc1b34f608\n    cp include/uapi/linux/can/isotp.h /usr/include/linux/can\n    cd ..\n    rm -rf can-isotp\nfi\n\nif [ -z \"${PREFIX+x}\" ]; then\n    PREFIX=\"/usr/local/`gcc -dumpmachine`\"\nfi\n\nif ${INSTALL_BUILD_TIME_DEPS} && ( ! ${USE_CACHE} || [ ! -d ${PREFIX} ] ); then\n    mkdir -p ${PREFIX}\n    mkdir deps-native && cd deps-native\n\n    git clone -b ${VERSION_JSON_CPP} https://github.com/open-source-parsers/jsoncpp.git\n    cd jsoncpp\n    mkdir build && cd build\n    cmake \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n        -DJSONCPP_WITH_TESTS=Off \\\n        -DJSONCPP_WITH_POST_BUILD_UNITTEST=Off \\\n        -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/protocolbuffers/protobuf/releases/download/${VERSION_PROTOBUF_RELEASE}/protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    tar -zxf protobuf-cpp-${VERSION_PROTOBUF}.tar.gz\n    cd protobuf-${VERSION_PROTOBUF}\n    mkdir build && cd build\n    ../configure --prefix=${PREFIX}\n    make install -j`nproc`\n    cd ../..\n\n    wget -q https://github.com/curl/curl/releases/download/${VERSION_CURL_RELEASE}/curl-${VERSION_CURL}.tar.gz\n    tar -zxf curl-${VERSION_CURL}.tar.gz\n    cd curl-${VERSION_CURL}\n    mkdir build && cd build\n    LDFLAGS=\"-static\" PKG_CONFIG=\"pkg-config --static\" ../configure --disable-shared --enable-static \\\n        --disable-ldap --enable-ipv6 --with-ssl --disable-unix-sockets --disable-rtsp --without-zstd --prefix=${PREFIX}\n    make install -j`nproc` V=1 LDFLAGS=\"-static\"\n    cd ../..\n\n    git clone -b ${VERSION_AWS_SDK_CPP} --recursive https://github.com/aws/aws-sdk-cpp.git\n    cd aws-sdk-cpp\n    mkdir build && cd build\n    cmake \\\n        -DENABLE_TESTING=OFF \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DBUILD_ONLY='s3-crt;iot' \\\n        -DAWS_CUSTOM_MEMORY_MANAGEMENT=ON \\\n        -DZLIB_LIBRARY=/usr/lib/$(gcc -dumpmachine)/libz.a \\\n        -DCURL_LIBRARY=${PREFIX}/lib/libcurl.a \\\n        -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    git clone -b ${VERSION_GOOGLE_TEST} https://github.com/google/googletest.git\n    cd googletest\n    mkdir build && cd build\n    cmake \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    git clone -b ${VERSION_GOOGLE_BENCHMARK} https://github.com/google/benchmark.git\n    cd benchmark\n    mkdir build && cd build\n    cmake \\\n        -DBUILD_SHARED_LIBS=OFF \\\n        -DBENCHMARK_DOWNLOAD_DEPENDENCIES=on \\\n        -DCMAKE_BUILD_TYPE=Release \\\n        -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n        ..\n    make install -j`nproc`\n    cd ../..\n\n    # AWS IoT FleetWise Edge camera support requires Fast-DDS and its dependencies:\n    if ${WITH_CAMERA_SUPPORT}; then\n        git clone -b ${VERSION_TINYXML2} https://github.com/leethomason/tinyxml2.git\n        cd tinyxml2\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DBUILD_STATIC_LIBS=ON \\\n            -DBUILD_TESTS=OFF \\\n            -DCMAKE_POSITION_INDEPENDENT_CODE=On \\\n            -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FOONATHAN_MEMORY_VENDOR} https://github.com/eProsima/foonathan_memory_vendor.git\n        cd foonathan_memory_vendor\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_CDR} https://github.com/eProsima/Fast-CDR.git\n        cd Fast-CDR\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS} https://github.com/eProsima/Fast-DDS.git\n        cd Fast-DDS\n        mkdir build && cd build\n        cmake \\\n            -DCMAKE_BUILD_TYPE=Release \\\n            -DBUILD_SHARED_LIBS=OFF \\\n            -DCOMPILE_TOOLS=OFF \\\n            -DCMAKE_CXX_FLAGS=\"-DUSE_FOONATHAN_NODE_SIZES=1\" \\\n            -DCMAKE_INSTALL_PREFIX=${PREFIX} \\\n            ..\n        make install -j`nproc`\n        cd ../..\n\n        git clone -b ${VERSION_FAST_DDS_GEN} --recursive https://github.com/eProsima/Fast-DDS-Gen.git\n        cd Fast-DDS-Gen\n        ./gradlew assemble\n        mkdir -p ${PREFIX}/share/fastddsgen/java\n        cp share/fastddsgen/java/fastddsgen.jar ${PREFIX}/share/fastddsgen/java\n        cp scripts/fastddsgen ${PREFIX}/bin\n        cd ..\n    fi\n\n    cd ..\n    rm -rf deps-native\nfi\n", "num_lines": 220}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nexport VERSION_JSON_CPP=\"1.9.5\"\nexport VERSION_PROTOBUF=\"3.21.12\"\nexport VERSION_PROTOBUF_RELEASE=\"v21.12\"\nexport VERSION_CURL=\"7.86.0\"\nexport VERSION_CURL_RELEASE=\"curl-7_86_0\"\nexport VERSION_AWS_SDK_CPP=\"1.11.94\"\nexport VERSION_TINYXML2=\"6.0.0\"\nexport VERSION_FOONATHAN_MEMORY_VENDOR=\"v1.1.0\"\nexport VERSION_FAST_CDR=\"v1.0.21\"\nexport VERSION_FAST_DDS=\"v2.3.4\"\nexport VERSION_FAST_DDS_GEN=\"v2.0.1\"\nexport VERSION_GOOGLE_TEST=\"release-1.10.0\"\nexport VERSION_GOOGLE_BENCHMARK=\"v1.6.1\"\nexport VERSION_ANDROID_CMDLINE_TOOLS=\"9123335\"\nexport VERSION_ANDROID_NDK=\"23.1.7779620\"\nexport VERSION_ANDROID_API=\"21\"\nexport VERSION_ANDROID_SDK=\"33\"\nexport VERSION_ANDROID_BUILD_TOOLS=\"30.0.3\"\nexport VERSION_CMAKE=\"3.22.1\" # Provided by Ubuntu 20.04, version here used for Android build\nexport VERSION_SNAPPY=\"1.1.8\" # Provided by Ubuntu 20.04, version here used for Android build\nexport VERSION_OPENSSL=\"1.1.1s\" # Provided by Ubuntu 20.04, version here used for Android build\nexport VERSION_BOOST=\"1.78.0\" # Provided by Ubuntu 20.04, version here used for Android build\n", "num_lines": 24}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nexport DEBIAN_FRONTEND=\"noninteractive\"\n\napt update\napt install -y \\\n    gawk wget git-core diffstat unzip texinfo \\\n    build-essential chrpath socat cpio python3 python3-pip python3-pexpect \\\n    xz-utils debianutils iputils-ping python3-git python3-jinja2 libegl1-mesa libsdl1.2-dev \\\n    pylint3 xterm curl dosfstools mtools parted syslinux-common tree zip python ca-certificates\n\nif [ `dpkg --print-architecture` == \"amd64\" ]; then\n    apt install -y gcc-multilib\nfi\n\n# Google 'repo' tool, see https://source.android.com/setup/develop/repo\ncurl https://storage.googleapis.com/git-repo-downloads/repo > /usr/local/bin/repo\nchmod +x /usr/local/bin/repo\n", "num_lines": 23}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -e\n\n./tools/deploy/stop-fwe.sh\n\nmkdir -p /var/aws-iot-fleetwise\n\ncp build/src/executionmanagement/aws-iot-fleetwise-edge /usr/bin/\ncp tools/deploy/run-fwe.sh                              /usr/bin/\ncp tools/deploy/fwe@.service                            /lib/systemd/system/\n\n./tools/deploy/start-and-enable-fwe.sh\n", "num_lines": 16}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nBUS_COUNT=1\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --bus-count)\n            BUS_COUNT=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --bus-count <NUM>  Number of CAN buses\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n}\n\nparse_args \"$@\"\n\nif ! command -v cansend > /dev/null; then\n    # Install packages\n    apt update && apt install -y can-utils\nfi\n\n# For EC2, the SocketCAN modules vcan and can-gw are included in a separate package:\nif uname -r | grep -q aws; then\n    apt update && apt install -y linux-modules-extra-aws\nfi\n\n# Install can-isotp kernel module if not installed\n# can-isotp module is part of the mainline Linux kernel since version 5.10\nMODULE=\"can_isotp\"\necho \"Installing kernel module: $MODULE\"\nif modinfo $MODULE &> /dev/null ; then\n    echo \"$MODULE is already in system. There is no need to install it.\"\nelse\n    apt update && apt install -y build-essential dkms git\n    git clone https://github.com/hartkopp/can-isotp.git\n    cd can-isotp\n    git checkout beb4650660179963a8ed5b5cbf2085cc1b34f608\n    cd ..\n    if [ -d /usr/src/can-isotp-1.0 ]; then\n        dkms remove can-isotp/1.0 --all\n        rm -rf /usr/src/can-isotp-1.0\n    fi\n    mv can-isotp /usr/src/can-isotp-1.0\n    sed -e s/else// -e s/shell\\ uname\\ \\-r/KERNELRELEASE/ -i /usr/src/can-isotp-1.0/Makefile\n    cat > /usr/src/can-isotp-1.0/dkms.conf <<EOT\nPACKAGE_NAME=\"can-isotp\"\nPACKAGE_VERSION=\"1.0\"\nMAKE[0]=\"make modules\"\nCLEAN=\"make clean\"\nBUILT_MODULE_NAME[0]=\"can-isotp\"\nDEST_MODULE_LOCATION[0]=\"/kernel/drivers/net/can\"\nBUILT_MODULE_LOCATION[0]=\"./net/can\"\nAUTOINSTALL=\"yes\"\nEOT\n    dkms add -m can-isotp -v 1.0\n    dkms build -m can-isotp -v 1.0\n    dkms install -m can-isotp -v 1.0\n    cp /usr/src/can-isotp-1.0/include/uapi/linux/can/isotp.h /usr/include/linux/can\nfi\n\n# Load CAN modules, also at startup:\nmodprobe -a can-isotp can-gw\nprintf \"can-isotp\\ncan-gw\\n\" > /etc/modules-load.d/can.conf\n\n# Install setup-socketcan\nfor ((i=0; i<${BUS_COUNT}; i++)); do\n    printf \"ip link add dev vcan${i} type vcan; ip link set up vcan${i}\\n\" \\\n        >> /usr/local/bin/setup-socketcan.sh\ndone\ncat > /lib/systemd/system/setup-socketcan.service <<EOT\n[Unit]\nDescription=Setup SocketCAN interfaces\nAfter=network.target\n[Service]\nType=oneshot\nRemainAfterExit=yes\nExecStart=/bin/sh /usr/local/bin/setup-socketcan.sh\n[Install]\nWantedBy=multi-user.target\nEOT\nsystemctl enable setup-socketcan\nsystemctl start setup-socketcan\n", "num_lines": 94}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nTIMESTAMP=`date +%s`\nDEFAULT_VEHICLE_NAME=\"fwdemo\"\nVEHICLE_NAME=\"\"\nCERT_OUT_FILE=\"certificate.pem\"\nPRIVATE_KEY_OUT_FILE=\"private-key.key\"\nENDPOINT_URL_OUT_FILE=\"\"\nVEHICLE_NAME_OUT_FILE=\"\"\nTHING_POLICY_OUT_FILE=\"\"\nONLY_CLEAN_UP=false\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --certificate-pem-outfile)\n            CERT_OUT_FILE=$2\n            shift\n            ;;\n        --private-key-outfile)\n            PRIVATE_KEY_OUT_FILE=$2\n            shift\n            ;;\n        --endpoint-url-outfile)\n            ENDPOINT_URL_OUT_FILE=$2\n            shift\n            ;;\n        --vehicle-name-outfile)\n            VEHICLE_NAME_OUT_FILE=$2\n            shift\n            ;;\n        --thing-policy-outfile)\n            THING_POLICY_OUT_FILE=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --only-clean-up)\n            ONLY_CLEAN_UP=true\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --vehicle-name <NAME>                 Vehicle name\"\n            echo \"  --certificate-pem-outfile <FILENAME>  Certificate output file, default: ${CERT_OUT_FILE}\"\n            echo \"  --private-key-outfile <FILENAME>      Private key output file, default: ${PRIVATE_KEY_OUT_FILE}\"\n            echo \"  --endpoint-url-outfile <FILENAME>     Endpoint URL for MQTT connections output file\"\n            echo \"  --vehicle-name-outfile <FILENAME>     Vehicle name output file\"\n            echo \"  --thing-policy-outfile <FILENAME>     Thing policy output file\"\n            echo \"  --endpoint-url <URL>                  The endpoint URL used for AWS CLI calls\"\n            echo \"  --region                              The region used for AWS CLI calls, default: ${REGION}\"\n            echo \"  --only-clean-up                       Clean up resources created by previous runs of this script\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n}\n\necho \"==============================\"\necho \"AWS IoT FleetWise Provisioning\"\necho \"==============================\"\n\nparse_args \"$@\"\n\nif [ \"${VEHICLE_NAME}\" == \"\" ]; then\n    echo -n \"Enter Vehicle name [${DEFAULT_VEHICLE_NAME}]: \"\n    read VEHICLE_NAME\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        VEHICLE_NAME=${DEFAULT_VEHICLE_NAME}\n    fi\nfi\n\nNAME=\"${VEHICLE_NAME}-${TIMESTAMP}\"\n\nif [ ${ONLY_CLEAN_UP} == true ]; then\n\n    PRINCIPAL_ARN=$(aws iot list-thing-principals --thing-name ${VEHICLE_NAME} --region ${REGION} | jq -r \".principals[0]\")\n    CERTIFICATE_ID=$(echo ${PRINCIPAL_ARN} | cut -d'/' -f2 )\n    POLICY_NAME=$(aws iot list-principal-policies --principal ${PRINCIPAL_ARN} --region ${REGION} | jq -r \".policies[0].policyName\")\n\n    RETRY_COUNTER=10\n    while ! aws iot delete-thing --thing-name ${VEHICLE_NAME} --region ${REGION}\n    do\n        # Delete depending resources\n        aws iot detach-thing-principal --thing-name ${VEHICLE_NAME} --principal ${PRINCIPAL_ARN} --region ${REGION} || true\n        aws iot detach-principal-policy --policy-name \"${POLICY_NAME}\" --principal ${PRINCIPAL_ARN} --region ${REGION} || true\n        aws iot delete-policy --policy-name \"${POLICY_NAME}\" --region ${REGION} || true\n        aws iot update-certificate --certificate-id ${CERTIFICATE_ID} --new-status INACTIVE --region ${REGION} || true\n        aws iot delete-certificate --certificate-id ${CERTIFICATE_ID} --region ${REGION} || true\n\n        echo \"Wait one second before next retry\"\n        sleep 1\n        if [ \"${RETRY_COUNTER}\" -eq \"0\" ]; then\n            echo \"Failed aws iot delete-thing\"\n            exit 1\n        fi\n        ((RETRY_COUNTER--))\n    done\n    echo \"Successfully deleted iot thing\"\n    exit 0\n\nfi\n\necho -n \"Date: \"\ndate --rfc-3339=seconds\n\necho \"Vehicle name: ${VEHICLE_NAME}\"\n\necho \"Getting AWS account ID...\"\nACCOUNT_ID=`aws sts get-caller-identity | jq -r .Account`\necho ${ACCOUNT_ID}\n\necho \"Creating IoT thing...\"\naws iot create-thing \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --thing-name ${VEHICLE_NAME} \\\n    | jq -r .thingArn\n\nIOT_POLICY=`cat <<EOF\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": [\n                \"iot:Connect\",\n                \"iot:Subscribe\",\n                \"iot:Publish\",\n                \"iot:Receive\"\n            ],\n            \"Resource\": [\n            ]\n        }\n    ]\n}\nEOF\n`\nIOT_POLICY=`echo \"${IOT_POLICY}\" \\\n    | jq \".Statement[0].Resource[0]=\\\"arn:aws:iot:${REGION}:${ACCOUNT_ID}:client/${VEHICLE_NAME}\\\"\" \\\n    | jq \".Statement[0].Resource[1]=\\\"arn:aws:iot:${REGION}:${ACCOUNT_ID}:topic/*\\\"\" \\\n    | jq \".Statement[0].Resource[2]=\\\"arn:aws:iot:${REGION}:${ACCOUNT_ID}:topicfilter/*\\\"\"`\n\necho \"Creating policy...\"\naws iot create-policy \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --policy-name \"${NAME}-IoT-Policy\" \\\n    --policy-document \"${IOT_POLICY}\" \\\n    | jq -r .policyArn\n\necho \"Creating keys and certificate...\"\nCERT_ARN=`aws iot create-keys-and-certificate \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --set-as-active \\\n    --certificate-pem-outfile \"${CERT_OUT_FILE}\" \\\n    --private-key-outfile \"${PRIVATE_KEY_OUT_FILE}\" \\\n    | jq -r .certificateArn`\necho ${CERT_ARN}\n\necho \"Attaching policy...\"\naws iot attach-policy \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --policy-name \"${NAME}-IoT-Policy\" \\\n    --target ${CERT_ARN}\n\necho \"Attaching thing principal...\"\naws iot attach-thing-principal \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --thing-name ${VEHICLE_NAME} \\\n    --principal ${CERT_ARN}\n\necho \"Getting endpoint...\"\nENDPOINT=`aws iot describe-endpoint \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --endpoint-type \"iot:Data-ATS\" \\\n    | jq -j .endpointAddress`\necho ${ENDPOINT}\n\nif [ \"${ENDPOINT_URL_OUT_FILE}\" != \"\" ]; then\n    echo ${ENDPOINT} > ${ENDPOINT_URL_OUT_FILE}\nfi\n\nif [ \"${VEHICLE_NAME_OUT_FILE}\" != \"\" ]; then\n    echo -n $VEHICLE_NAME > ${VEHICLE_NAME_OUT_FILE}\nfi\n\nif [ \"${THING_POLICY_OUT_FILE}\" != \"\" ]; then\n    echo -n ${NAME}-IoT-Policy > ${THING_POLICY_OUT_FILE}\nfi\n", "num_lines": 216}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\n# 'repo' requires that Git is configured, otherwise it interactively prompts for the configuration:\ngit config user.name > /dev/null || git config --global user.name \"ubuntu\"\ngit config user.email > /dev/null || git config --global user.email \"ubuntu@`hostname`\"\ngit config color.ui || git config --global color.ui false\n\nrepo init -b release/bsp35.0 -u https://github.com/nxp-auto-linux/auto_yocto_bsp.git\nrepo sync\n\nSCRIPTPATH=`dirname $0`\ncp -r ${SCRIPTPATH}/yocto/* .\n", "num_lines": 17}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nVEHICLE_NAME_FILENAME=\"config/vehicle-name.txt\"\nVEHICLE_NAME=\"\"\nTHING_POLICY_FILENAME=\"config/thing-policy.txt\"\nTHING_POLICY=\"\"\nSERVICE_ROLE_ARN_FILENAME=\"config/service-role-arn.txt\"\nSERVICE_ROLE_ARN=\"\"\nTIMESTAMP_FILENAME=\"config/timestamp.txt\"\nTIMESTAMP=\"\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --timestamp)\n            TIMESTAMP=$2\n            shift\n            ;;\n        --service-role-arn)\n            SERVICE_ROLE_ARN=$2\n            shift\n            ;;\n        --thing-policy)\n            THING_POLICY=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --vehicle-name <NAME>     Vehicle name, by default will be read from ${VEHICLE_NAME_FILENAME}\"\n            echo \"  --timestamp <TS>          Timestamp of setup-iotfleetwise.sh script, by default will be read from ${TIMESTAMP_FILENAME}\"\n            echo \"  --service-role-arn <ARN>  Service role ARN for accessing Timestream, by default will be read from ${SERVICE_ROLE_ARN_FILENAME}\"\n            echo \"  --thing-policy <NAME>     Name of IoT thing policy, by default will be read from ${THING_POLICY_FILENAME}\"\n            echo \"  --endpoint-url <URL>      The endpoint URL used for AWS CLI calls\"\n            echo \"  --region <REGION>         The region used for AWS CLI calls, default: ${REGION}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        if [ -f \"${VEHICLE_NAME_FILENAME}\" ]; then\n            VEHICLE_NAME=`cat ${VEHICLE_NAME_FILENAME}`\n        else\n            echo \"Error: vehicle name not provided\"\n            exit -1\n        fi\n    fi\n\n    if [ \"${TIMESTAMP}\" == \"\" ]; then\n        if [ -f \"${TIMESTAMP_FILENAME}\" ]; then\n            TIMESTAMP=`cat ${TIMESTAMP_FILENAME}`\n        fi\n    fi\n\n    if [ \"${SERVICE_ROLE_ARN}\" == \"\" ]; then\n        if [ -f \"${SERVICE_ROLE_ARN_FILENAME}\" ]; then\n            SERVICE_ROLE_ARN=`cat ${SERVICE_ROLE_ARN_FILENAME}`\n        fi\n    fi\n\n    if [ \"${THING_POLICY}\" == \"\" ]; then\n        if [ -f \"${THING_POLICY_FILENAME}\" ]; then\n            THING_POLICY=`cat ${THING_POLICY_FILENAME}`\n        fi\n    fi\n}\n\necho \"=========================================\"\necho \"AWS IoT FleetWise Android Clean-up Script\"\necho \"=========================================\"\n\nparse_args \"$@\"\n\necho \"Getting AWS account ID...\"\nACCOUNT_ID=`aws sts get-caller-identity --query \"Account\" --output text`\necho ${ACCOUNT_ID}\n\nif [ \"${TIMESTAMP}\" != \"\" ]; then\n    NAME=\"${VEHICLE_NAME}-${TIMESTAMP}\"\n\n    echo \"Suspending campaign...\"\n    aws iotfleetwise update-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-campaign \\\n        --action SUSPEND | jq -r .arn || true\n\n    echo \"Deleting campaign...\"\n    aws iotfleetwise delete-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-campaign | jq -r .arn || true\n\n    echo \"Disassociating vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise disassociate-vehicle-fleet \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --fleet-id ${NAME}-fleet \\\n        --vehicle-name \"${VEHICLE_NAME}\" || true\n\n    echo \"Deleting vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise delete-vehicle \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --vehicle-name \"${VEHICLE_NAME}\" | jq -r .arn || true\n\n    echo \"Deleting fleet...\"\n    aws iotfleetwise delete-fleet \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --fleet-id ${NAME}-fleet | jq -r .arn || true\n\n    echo \"Deleting decoder manifest...\"\n    aws iotfleetwise delete-decoder-manifest \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-decoder-manifest | jq -r .arn || true\n\n    echo \"Deleting model manifest...\"\n    aws iotfleetwise delete-model-manifest \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-model-manifest | jq -r .arn || true\n\n    rm -f ${TIMESTAMP_FILENAME}\nfi\n\nif [ \"${SERVICE_ROLE_ARN}\" != \"\" ]; then\n    SERVICE_ROLE=`echo \"${SERVICE_ROLE_ARN}\" | cut -d \"/\" -f 2`\n    SERVICE_ROLE_POLICY_ARN=\"arn:aws:iam::${ACCOUNT_ID}:policy/${SERVICE_ROLE}-policy\"\n    echo \"Detatching policy...\"\n    aws iam detach-role-policy --role-name ${SERVICE_ROLE} --policy-arn ${SERVICE_ROLE_POLICY_ARN} --region ${REGION} || true\n    echo \"Deleting policy...\"\n    aws iam delete-policy --policy-arn ${SERVICE_ROLE_POLICY_ARN} --region ${REGION} || true\n    echo \"Deleting role...\"\n    aws iam delete-role --role-name ${SERVICE_ROLE} --region ${REGION} || true\n\n    rm -f ${SERVICE_ROLE_ARN_FILENAME}\nfi\n\necho \"Listing thing principals...\"\nTHING_PRINCIPAL=`aws iot list-thing-principals --region ${REGION} --thing-name ${VEHICLE_NAME} | jq -r \".principals[0]\" || true`\necho \"Detaching thing principal...\"\naws iot detach-thing-principal --region ${REGION} --thing-name ${VEHICLE_NAME} --principal ${THING_PRINCIPAL} || true\necho \"Detaching thing policy...\"\naws iot detach-policy --region ${REGION} --policy-name ${THING_POLICY} --target ${THING_PRINCIPAL} || true\necho \"Deleting thing...\"\naws iot delete-thing --region ${REGION} --thing-name ${VEHICLE_NAME} || true\necho \"Deleting thing policy...\"\naws iot delete-policy --region ${REGION} --policy-name ${THING_POLICY} || true\nCERTIFICATE_ID=`echo \"${THING_PRINCIPAL}\" | cut -d \"/\" -f 2 || true`\necho \"Updating certificate as INACTIVE...\"\naws iot update-certificate --region ${REGION} --certificate-id ${CERTIFICATE_ID} --new-status INACTIVE || true\necho \"Deleting certificate...\"\naws iot delete-certificate --region ${REGION} --certificate-id ${CERTIFICATE_ID} --force-delete || true\n\nrm -f ${VEHICLE_NAME_FILENAME}\nrm -f ${THING_POLICY_FILENAME}\nrm -f config/certificate.pem\nrm -f config/private-key.key\nrm -f config/creds.json\nrm -f config/endpoint.txt\nrm -f config/provisioning-qr-code.png\n\necho \"=========\"\necho \"Finished!\"\necho \"=========\"\n", "num_lines": 185}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nS3_BUCKET=\"\"\nS3_KEY_PREFIX=\"\"\nS3_PRESIGNED_URL_EXPIRY=86400 # One day\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nTOPIC_PREFIX=\"\\$aws/iotfleetwise/\"\nTIMESTAMP=`date +%s`\nVEHICLE_NAME=\"fwdemo-android-${TIMESTAMP}\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --s3-bucket)\n            S3_BUCKET=$2\n            shift\n            ;;\n        --s3-key-prefix)\n            S3_KEY_PREFIX=$2\n            shift\n            ;;\n        --s3-presigned-url-expiry)\n            S3_PRESIGNED_URL_EXPIRY=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --topic-prefix)\n            TOPIC_PREFIX=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --s3-bucket <NAME>                   Existing S3 bucket name\"\n            echo \"  --s3-key-prefix <PREFIX>             S3 bucket prefix\"\n            echo \"  --s3-presigned-url-expiry <SECONDS>  S3 presigned URL expiry, default: ${S3_PRESIGNED_URL_EXPIRY}\"\n            echo \"  --endpoint-url <URL>                 The endpoint URL used for AWS CLI calls\"\n            echo \"  --region                             The region used for AWS CLI calls, default: ${REGION}\"\n            echo \"  --topic-prefix <PREFIX>              IoT MQTT topic prefix, default: ${TOPIC_PREFIX}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n}\n\nparse_args \"$@\"\n\nif [ \"${S3_BUCKET}\" == \"\" ]; then\n    echo -n \"Enter name of existing S3 bucket: \"\n    read S3_BUCKET\n    if [ \"${S3_BUCKET}\" == \"\" ]; then\n        echo \"Error: S3 bucket name required\"\n        exit -1\n    fi\nfi\n\necho \"Getting S3 bucket region...\"\nS3_BUCKET_REGION=`aws s3api get-bucket-location --bucket ${S3_BUCKET} | jq -r .LocationConstraint`\nif [ -z \"${S3_BUCKET_REGION}\" ] || [ \"${S3_BUCKET_REGION}\" == \"null\" ]; then\n    S3_BUCKET_REGION=\"us-east-1\"\nfi\necho ${S3_BUCKET_REGION}\n\nmkdir -p config\n../../provision.sh \\\n    --vehicle-name ${VEHICLE_NAME} \\\n    ${ENDPOINT_URL_OPTION} \\\n    --region ${REGION} \\\n    --certificate-pem-outfile config/certificate.pem \\\n    --private-key-outfile config/private-key.key \\\n    --endpoint-url-outfile config/endpoint.txt \\\n    --vehicle-name-outfile config/vehicle-name.txt \\\n    --thing-policy-outfile config/thing-policy.txt\n\nCERTIFICATE=`cat config/certificate.pem`\nPRIVATE_KEY=`cat config/private-key.key`\nMQTT_ENDPOINT_URL=`cat config/endpoint.txt`\necho {} | jq \".vehicle_name=\\\"${VEHICLE_NAME}\\\"\" \\\n    | jq \".endpoint_url=\\\"${MQTT_ENDPOINT_URL}\\\"\" \\\n    | jq \".certificate=\\\"${CERTIFICATE}\\\"\" \\\n    | jq \".private_key=\\\"${PRIVATE_KEY}\\\"\" \\\n    | jq \".mqtt_topic_prefix=\\\"${TOPIC_PREFIX}\\\"\" \\\n    > config/creds.json\n\nS3_URL=\"s3://${S3_BUCKET}/${S3_KEY_PREFIX}${VEHICLE_NAME}-creds.json\"\necho \"Uploading credentials to S3...\"\naws s3 cp --region ${REGION} config/creds.json ${S3_URL}\necho \"Creating S3 pre-signed URL...\"\nS3_PRESIGNED_URL=`aws s3 presign --region ${S3_BUCKET_REGION} --expires-in ${S3_PRESIGNED_URL_EXPIRY} ${S3_URL}`\nPROVISIONING_LINK=\"https://fleetwise-app.automotive.iot.aws.dev/config#url=`echo ${S3_PRESIGNED_URL} | jq -s -R -r @uri`\"\nQR_CODE_FILENAME=\"config/provisioning-qr-code.png\"\nsegno --scale 5 --output ${QR_CODE_FILENAME} \"${PROVISIONING_LINK}\"\n\necho\necho \"You can now download the provisioning QR code.\"\necho \"----------------------------------\"\necho \"| Provisioning QR code filename: |\"\necho \"----------------------------------\"\necho `realpath ${QR_CODE_FILENAME}`\n\necho\necho \"Optional: After you have downloaded and scanned the QR code, you can delete the credentials for security by running the following command: aws s3 rm ${S3_URL}\"\n", "num_lines": 120}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nTIMESTAMP_FILENAME=\"config/timestamp.txt\"\nTIMESTAMP=`date +%s`\nVEHICLE_NAME_FILENAME=\"config/vehicle-name.txt\"\nVEHICLE_NAME=\"\"\nSERVICE_ROLE=\"IoTFleetWiseServiceRole-${TIMESTAMP}\"\nDEFAULT_TIMESTREAM_DB_NAME=\"IoTFleetWiseDB-${TIMESTAMP}\"\nSERVICE_PRINCIPAL=\"iotfleetwise.amazonaws.com\"\nTIMESTREAM_DB_NAME_FILENAME=\"config/timestream-db-name.txt\"\nTIMESTREAM_DB_NAME=\"\"\nTIMESTREAM_TABLE_NAME=\"VehicleDataTable\"\nSERVICE_ROLE_ARN_FILENAME=\"config/service-role-arn.txt\"\nSERVICE_ROLE_ARN=\"\"\nCAMPAIGN_FILE=\"campaign-android.json\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --timestream-db-name)\n            TIMESTREAM_DB_NAME=$2\n            shift\n            ;;\n        --timestream-table-name)\n            TIMESTREAM_TABLE_NAME=$2\n            shift\n            ;;\n        --service-role-arn)\n            SERVICE_ROLE_ARN=$2\n            shift\n            ;;\n        --service-principal)\n            SERVICE_PRINCIPAL=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --vehicle-name <NAME>            Vehicle name, by default will be read from ${VEHICLE_NAME_FILENAME}\"\n            echo \"  --timestream-db-name <NAME>      Timestream database name, by default will be read from ${TIMESTREAM_DB_NAME_FILENAME}\"\n            echo \"  --timestream-table-name <NAME>   Timetream table name, default: ${TIMESTREAM_TABLE_NAME}\"\n            echo \"  --service-role-arn <ARN>         Service role ARN for accessing Timestream, by default will be read from ${SERVICE_ROLE_ARN_FILENAME}\"\n            echo \"  --endpoint-url <URL>             The endpoint URL used for AWS CLI calls\"\n            echo \"  --region <REGION>                The region used for AWS CLI calls, default: ${REGION}\"\n            echo \"  --service-principal <PRINCIPAL>  AWS service principal for policies, default: ${SERVICE_PRINCIPAL}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        if [ -f \"${VEHICLE_NAME_FILENAME}\" ]; then\n            VEHICLE_NAME=`cat ${VEHICLE_NAME_FILENAME}`\n        else\n            echo \"Error: provision.sh script not run\"\n            exit -1\n        fi\n    fi\n\n    if [ \"${TIMESTREAM_DB_NAME}\" == \"\" ]; then\n        if [ -f \"${TIMESTREAM_DB_NAME_FILENAME}\" ]; then\n            TIMESTREAM_DB_NAME=`cat ${TIMESTREAM_DB_NAME_FILENAME}`\n        fi\n    fi\n\n    if [ \"${SERVICE_ROLE_ARN}\" == \"\" ]; then\n        if [ -f \"${SERVICE_ROLE_ARN_FILENAME}\" ]; then\n            SERVICE_ROLE_ARN=`cat ${SERVICE_ROLE_ARN_FILENAME}`\n        fi\n    fi\n}\n\necho \"================================\"\necho \"AWS IoT FleetWise Android Script\"\necho \"================================\"\n\nmkdir -p config\nparse_args \"$@\"\n\necho \"Getting AWS account ID...\"\nACCOUNT_ID=`aws sts get-caller-identity --query \"Account\" --output text`\necho ${ACCOUNT_ID}\n\nif [ \"${TIMESTREAM_DB_NAME}\" != \"\" ] && [ \"${SERVICE_ROLE_ARN}\" != \"\" ]; then\n    TIMESTREAM_TABLE_ARN=\"arn:aws:timestream:${REGION}:${ACCOUNT_ID}:database/${TIMESTREAM_DB_NAME}/table/${TIMESTREAM_TABLE_NAME}\"\nelse\n    TIMESTREAM_DB_NAME=${DEFAULT_TIMESTREAM_DB_NAME}\n\n    echo \"Creating Timestream database...\"\n    aws timestream-write create-database \\\n        --region ${REGION} \\\n        --database-name ${TIMESTREAM_DB_NAME} | jq -r .Database.Arn\n\n    echo \"Creating Timestream table...\"\n    TIMESTREAM_TABLE_ARN=$( aws timestream-write create-table \\\n        --region ${REGION} \\\n        --database-name ${TIMESTREAM_DB_NAME} \\\n        --table-name ${TIMESTREAM_TABLE_NAME} \\\n        --retention-properties \"{\\\"MemoryStoreRetentionPeriodInHours\\\":2, \\\n            \\\"MagneticStoreRetentionPeriodInDays\\\":2}\" | jq -r .Table.Arn )\n\n    echo \"Creating service role...\"\n    SERVICE_ROLE_TRUST_POLICY=$(cat << EOF\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n        \"Effect\": \"Allow\",\n        \"Principal\": {\n            \"Service\": [\n                \"$SERVICE_PRINCIPAL\"\n            ]\n        },\n        \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}\nEOF\n)\n    SERVICE_ROLE_ARN=`aws iam create-role \\\n        --role-name \"${SERVICE_ROLE}\" \\\n        --assume-role-policy-document \"${SERVICE_ROLE_TRUST_POLICY}\" | jq -r .Role.Arn`\n    echo ${SERVICE_ROLE_ARN}\n\n    echo \"Waiting for role to be created...\"\n    aws iam wait role-exists \\\n        --role-name \"${SERVICE_ROLE}\"\n\n    echo \"Creating service role policy...\"\n    SERVICE_ROLE_POLICY=$(cat <<'EOF'\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Sid\": \"timestreamIngestion\",\n            \"Effect\": \"Allow\",\n            \"Action\": [\n                \"timestream:WriteRecords\",\n                \"timestream:Select\"\n            ]\n        },\n        {\n            \"Sid\": \"timestreamDescribeEndpoint\",\n            \"Effect\": \"Allow\",\n            \"Action\": [\n                \"timestream:DescribeEndpoints\"\n            ],\n            \"Resource\": \"*\"\n        }\n    ]\n}\nEOF\n)\n    SERVICE_ROLE_POLICY=`echo \"${SERVICE_ROLE_POLICY}\" \\\n        | jq \".Statement[0].Resource=\\\"arn:aws:timestream:${REGION}:${ACCOUNT_ID}:database/${TIMESTREAM_DB_NAME}/*\\\"\"`\n    SERVICE_ROLE_POLICY_ARN=`aws iam create-policy \\\n        --policy-name ${SERVICE_ROLE}-policy \\\n        --policy-document \"${SERVICE_ROLE_POLICY}\" | jq -r .Policy.Arn`\n    echo ${SERVICE_ROLE_POLICY_ARN}\n\n    echo \"Waiting for policy to be created...\"\n    aws iam wait policy-exists \\\n        --policy-arn \"${SERVICE_ROLE_POLICY_ARN}\"\n\n    echo \"Attaching policy to service role...\"\n    aws iam attach-role-policy \\\n        --policy-arn ${SERVICE_ROLE_POLICY_ARN} \\\n        --role-name \"${SERVICE_ROLE}\"\n\n    echo ${TIMESTREAM_DB_NAME} > ${TIMESTREAM_DB_NAME_FILENAME}\n    echo ${SERVICE_ROLE_ARN} > ${SERVICE_ROLE_ARN_FILENAME}\nfi\n\nNAME=\"${VEHICLE_NAME}-${TIMESTAMP}\"\necho ${TIMESTAMP} > ${TIMESTAMP_FILENAME}\n\necho \"Deleting vehicle ${VEHICLE_NAME} if it already exists...\"\naws iotfleetwise delete-vehicle \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --vehicle-name \"${VEHICLE_NAME}\" | jq -r .arn\n\nVEHICLE_NODE=`cat ../../cloud/vehicle-node.json`\nOBD_NODES=`cat ../../cloud/obd-nodes.json`\nDBC_NODES=`cat externalGpsNodes.json`\n\necho \"Checking for existing signal catalog...\"\nSIGNAL_CATALOG_LIST=`aws iotfleetwise list-signal-catalogs \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION}`\nSIGNAL_CATALOG_COUNT=`echo ${SIGNAL_CATALOG_LIST} | jq '.summaries|length'`\n# Currently only one signal catalog is supported by the service\nif [ ${SIGNAL_CATALOG_COUNT} == 0 ]; then\n    SIGNAL_CATALOG_NAME=\"${NAME}-signal-catalog\"\n    echo \"No existing signal catalog\"\n    echo \"Creating signal catalog with Vehicle node...\"\n    SIGNAL_CATALOG_ARN=`aws iotfleetwise create-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --nodes \"${VEHICLE_NODE}\" | jq -r .arn`\n    echo ${SIGNAL_CATALOG_ARN}\nelse\n    SIGNAL_CATALOG_NAME=`echo ${SIGNAL_CATALOG_LIST} | jq -r .summaries[0].name`\n    SIGNAL_CATALOG_ARN=`echo ${SIGNAL_CATALOG_LIST} | jq -r .summaries[0].arn`\n\n    echo \"Updating Vehicle node in signal catalog...\"\n    if UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --description \"Vehicle node\" \\\n        --nodes-to-update \"${VEHICLE_NODE}\" 2>&1`; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\n    elif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n        exit -1\n    else\n        echo \"Node exists and is in use, continuing\"\n    fi\nfi\n\necho \"Updating OBD signals in signal catalog...\"\nif UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${SIGNAL_CATALOG_NAME} \\\n    --description \"OBD signals\" \\\n    --nodes-to-update \"${OBD_NODES}\" 2>&1`; then\n    echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\nelif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n    echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n    exit -1\nelse\n    echo \"Signals exist and are in use, continuing\"\nfi\n\necho \"Updating DBC signals in signal catalog...\"\nif UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${SIGNAL_CATALOG_NAME} \\\n    --description \"DBC signals\" \\\n    --nodes-to-update \"${DBC_NODES}\" 2>&1`; then\n    echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\nelif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n    echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n    exit -1\nelse\n    echo \"Signals exist and are in use, continuing\"\nfi\n\necho \"Creating model manifest...\"\n# Make a list of all node names:\nNODE_LIST=`( echo ${DBC_NODES} | jq -r .[].sensor.fullyQualifiedName | grep Vehicle\\\\. ; \\\n             echo ${OBD_NODES} | jq -r .[].sensor.fullyQualifiedName | grep Vehicle\\\\. ) | jq -Rn [inputs]`\naws iotfleetwise create-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest \\\n    --signal-catalog-arn ${SIGNAL_CATALOG_ARN} \\\n    --nodes \"${NODE_LIST}\" | jq -r .arn\n\necho \"Activating model manifest...\"\nMODEL_MANIFEST_ARN=`aws iotfleetwise update-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest \\\n    --status ACTIVE | jq -r .arn`\necho ${MODEL_MANIFEST_ARN}\n\necho \"Creating decoder manifest with OBD signals...\"\nNETWORK_INTERFACES=`cat network-interfaces.json`\nOBD_SIGNAL_DECODERS=`cat ../../cloud/obd-decoders.json`\nDECODER_MANIFEST_ARN=`aws iotfleetwise create-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest \\\n    --model-manifest-arn ${MODEL_MANIFEST_ARN} \\\n    --network-interfaces \"${NETWORK_INTERFACES}\" \\\n    --signal-decoders \"${OBD_SIGNAL_DECODERS}\" | jq -r .arn`\necho ${DECODER_MANIFEST_ARN}\n\nSIGNAL_DECODERS=`cat externalGpsDecoders.json`\naws iotfleetwise update-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest \\\n    --signal-decoders-to-add \"${SIGNAL_DECODERS}\" | jq -r .arn\n\necho \"Activating decoder manifest...\"\naws iotfleetwise update-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest \\\n    --status ACTIVE | jq -r .arn\n\necho \"Creating vehicle ${VEHICLE_NAME}...\"\naws iotfleetwise create-vehicle \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --decoder-manifest-arn ${DECODER_MANIFEST_ARN} \\\n    --association-behavior ValidateIotThingExists \\\n    --model-manifest-arn ${MODEL_MANIFEST_ARN} \\\n    --vehicle-name \"${VEHICLE_NAME}\" | jq -r .arn\n\necho \"Creating fleet...\"\nFLEET_ARN=`aws iotfleetwise create-fleet \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --fleet-id ${NAME}-fleet \\\n    --description \"Description is required\" \\\n    --signal-catalog-arn ${SIGNAL_CATALOG_ARN} | jq -r .arn`\necho ${FLEET_ARN}\n\necho \"Associating vehicle ${VEHICLE_NAME}...\"\naws iotfleetwise associate-vehicle-fleet \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --fleet-id ${NAME}-fleet \\\n    --vehicle-name \"${VEHICLE_NAME}\"\n\necho \"Creating campaign from ${CAMPAIGN_FILE}...\"\nCAMPAIGN=`cat ${CAMPAIGN_FILE} \\\n    | jq .name=\\\"${NAME}-campaign\\\" \\\n    | jq .signalCatalogArn=\\\"${SIGNAL_CATALOG_ARN}\\\" \\\n    | jq .targetArn=\\\"${FLEET_ARN}\\\"`\naws iotfleetwise create-campaign \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --cli-input-json \"${CAMPAIGN}\" --data-destination-configs \"[{\\\"timestreamConfig\\\":{\\\"timestreamTableArn\\\":\\\"${TIMESTREAM_TABLE_ARN}\\\",\\\"executionRoleArn\\\":\\\"${SERVICE_ROLE_ARN}\\\"}}]\" | jq -r .arn\n\necho \"Waiting for campaign to become ready for approval...\"\nwhile true; do\n    sleep 5\n    CAMPAIGN_STATUS=`aws iotfleetwise get-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-campaign | jq -r .status`\n    if [ \"${CAMPAIGN_STATUS}\" == \"WAITING_FOR_APPROVAL\" ]; then\n        break\n    fi\ndone\n\necho \"Approving campaign...\"\naws iotfleetwise update-campaign \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-campaign \\\n    --action APPROVE | jq -r .arn\n\necho \"=========\"\necho \"Finished!\"\necho \"=========\"\n", "num_lines": 361}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nif (($#<1)); then\n    echo \"Error: Instance number not provided\" >&2\n    exit -1\nfi\n\n# In order to reduce the CAN simulation overhead for a large fleet of vehicles, generation of CAN\n# bus messages for CAN signals is only performed on vcan0, then frames are forwarded to all of the\n# other buses using `cangw`. Simulation of the OBD server is however performed on every channel.\n\n# If the instance number is greater than zero check whether the forwarding rule is already applied:\nif (($1>0)) && ! cangw -L | grep -q \"cangw -A -s vcan0 -d vcan$1 -e\"; then\n    # If not, add a forwarding rule from vcan0 to this bus, excluding diagnostic frames:\n    cangw -A -s \"vcan0\" -d \"vcan$1\" -e -f \"700~C0000700\"\nfi\n\n# Start the CAN simulator: for instance numbers greater than zero, only OBD is simulated\n/usr/bin/python3 /usr/share/cansim/cansim.py --interface \"vcan$1\" `(($1>0)) && echo \"--only-obd\"`\n", "num_lines": 24}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nVEHICLE_NAME=\"\"\nTIMESTAMP=\"\"\nACCOUNT_ID=`aws sts get-caller-identity --query \"Account\" --output text`\nSERVICE_ROLE=\"IoTFleetWiseServiceRole\"\nSERVICE_ROLE_POLICY_ARN=\"arn:aws:iam::${ACCOUNT_ID}:policy/\"\nFLEET_SIZE=1\nBATCH_SIZE=$((`nproc`*4))\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --fleet-size)\n            FLEET_SIZE=$2\n            shift\n            ;;\n        --timestamp)\n            TIMESTAMP=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --vehicle-name <NAME>  Vehicle name\"\n            echo \"  --fleet-size <SIZE>    Size of fleet, default: ${FLEET_SIZE}. When greater than 1,\"\n            echo \"                         the instance number will be appended to each\"\n            echo \"                         Vehicle name after a '-', e.g. fwdemo-42\"\n            echo \"  --timestamp <TS>       Timestamp of demo.sh script\"\n            echo \"  --endpoint-url <URL>   The endpoint URL used for AWS CLI calls\"\n            echo \"  --region <REGION>      The region used for AWS CLI calls, default: ${REGION}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        echo \"Error: Vehicle name not provided\"\n        exit -1\n    fi\n    if [ \"${TIMESTAMP}\" == \"\" ]; then\n        echo \"Error: Timestamp not provided\"\n        exit -1\n    fi\n}\n\necho \"=======================================\"\necho \"AWS IoT FleetWise Cloud Clean-up Script\"\necho \"=======================================\"\n\nparse_args \"$@\"\n\nNAME=\"${VEHICLE_NAME}-${TIMESTAMP}\"\nSERVICE_ROLE=\"${SERVICE_ROLE}-${REGION}-${TIMESTAMP}\"\nSERVICE_ROLE_POLICY_ARN=\"${SERVICE_ROLE_POLICY_ARN}${SERVICE_ROLE}-policy\"\n\necho -n \"Date: \"\ndate --rfc-3339=seconds\n\necho \"Timestamp: ${TIMESTAMP}\"\necho \"Vehicle name: ${VEHICLE_NAME}\"\necho \"Fleet size: ${FLEET_SIZE}\"\n\n# $1 is the campaign name\nsuspend_and_delete_campaign(){\n    echo \"Suspending campaign...\"\n    aws iotfleetwise update-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name $1 \\\n        --action SUSPEND 2> /dev/null | jq -r .arn || true\n\n    echo \"Deleting campaign...\"\n    aws iotfleetwise delete-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name $1 2> /dev/null | jq -r .arn || true\n}\n\nsuspend_and_delete_campaign ${NAME}-campaign\nsuspend_and_delete_campaign ${NAME}-campaign-s3-json\nsuspend_and_delete_campaign ${NAME}-campaign-s3-parquet\n\nif ((FLEET_SIZE==1)); then\n    echo \"Disassociating vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise disassociate-vehicle-fleet \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --fleet-id ${NAME}-fleet \\\n        --vehicle-name \"${VEHICLE_NAME}\" 2> /dev/null || true\nelse\n    echo \"Disassociating vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1))...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                aws iotfleetwise disassociate-vehicle-fleet \\\n                    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n                    --fleet-id ${NAME}-fleet \\\n                    --vehicle-name \"${VEHICLE_NAME}-$((i+j))\" 2> /dev/null || true \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\nif ((FLEET_SIZE==1)); then\n    echo \"Deleting vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise delete-vehicle \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --vehicle-name \"${VEHICLE_NAME}\" 2> /dev/null || true\nelse\n    echo \"Deleting vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1))...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                aws iotfleetwise delete-vehicle \\\n                    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n                    --vehicle-name \"${VEHICLE_NAME}-$((i+j))\" 2> /dev/null || true \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\necho \"Deleting fleet...\"\naws iotfleetwise delete-fleet \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --fleet-id ${NAME}-fleet 2> /dev/null || true\n\necho \"Deleting decoder manifest...\"\naws iotfleetwise delete-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest 2> /dev/null || true\n\necho \"Deleting model manifest...\"\naws iotfleetwise delete-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest 2> /dev/null || true\n\necho \"Deleting service role and policy...\"\naws iam detach-role-policy --role-name ${SERVICE_ROLE} --policy-arn ${SERVICE_ROLE_POLICY_ARN} --region ${REGION} || true\naws iam delete-policy --policy-arn ${SERVICE_ROLE_POLICY_ARN} --region ${REGION} || true\naws iam delete-role --role-name ${SERVICE_ROLE} --region ${REGION} || true\n\n# Note: As the service currently only supports one signal catalog, do not delete it\n# echo \"Deleting signal catalog...\"\n# aws iotfleetwise delete-signal-catalog \\\n#     ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n#     --name ${NAME}-signal-catalog 2> /dev/null || true\n", "num_lines": 175}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nENDPOINT_URL=\"\"\nENDPOINT_URL_OPTION=\"\"\nREGION=\"us-east-1\"\nTIMESTAMP=`date +%s`\nACCOUNT_ID=`aws sts get-caller-identity --query \"Account\" --output text`\nDEFAULT_VEHICLE_NAME=\"fwdemo\"\nVEHICLE_NAME=\"\"\nTIMESTREAM_DB_NAME=\"IoTFleetWiseDB-${TIMESTAMP}\"\nTIMESTREAM_TABLE_NAME=\"VehicleDataTable\"\nSERVICE_ROLE=\"IoTFleetWiseServiceRole\"\nSERVICE_ROLE_POLICY_ARN=\"\"\nSERVICE_PRINCIPAL=\"iotfleetwise.amazonaws.com\"\nRANDOM_HASH=\"$(cat /proc/sys/kernel/random/uuid)\"\nBUCKET_NAME=\"\"\nSKIP_S3_POLICY=true\nCAMPAIGN_FILE=\"\"\nDEFAULT_CAMPAIGN_FILE=\"campaign-brake-event.json\"\nDBC_FILE=\"\"\nDEFAULT_DBC_FILE=\"hscan.dbc\"\nCLEAN_UP=false\nS3_UPLOAD=false\nFLEET_SIZE=1\nBATCH_SIZE=$((`nproc`*4))\nHEALTH_CHECK_RETRIES=360 # About 30mins\nMAX_ATTEMPTS_ON_REGISTRATION_FAILURE=5\nFORCE_REGISTRATION=false\nMIN_CLI_VERSION=\"aws-cli/2.11.24\"\n\nparse_args() {\n    while [ \"$#\" -gt 0 ]; do\n        case $1 in\n        --vehicle-name)\n            VEHICLE_NAME=$2\n            shift\n            ;;\n        --fleet-size)\n            FLEET_SIZE=$2\n            shift\n            ;;\n        --clean-up)\n            CLEAN_UP=true\n            ;;\n        --enable-s3-upload)\n            S3_UPLOAD=true\n            ;;\n        --campaign-file)\n            CAMPAIGN_FILE=$2\n            shift\n            ;;\n        --dbc-file)\n            DBC_FILE=$2\n            shift\n            ;;\n        --bucket-name)\n            BUCKET_NAME=$2\n            shift\n            ;;\n        --service-principal)\n            SERVICE_PRINCIPAL=$2\n            shift\n            ;;\n        --endpoint-url)\n            ENDPOINT_URL=$2\n            shift\n            ;;\n        --region)\n            REGION=$2\n            shift\n            ;;\n        --help)\n            echo \"Usage: $0 [OPTION]\"\n            echo \"  --vehicle-name <NAME>   Vehicle name\"\n            echo \"  --fleet-size <SIZE>     Size of fleet, default: ${FLEET_SIZE}. When greater than 1,\"\n            echo \"                          the instance number will be appended to each\"\n            echo \"                          Vehicle name after a '-', e.g. ${DEFAULT_VEHICLE_NAME}-42\"\n            echo \"  --campaign-file <FILE>  Campaign JSON file, default: ${DEFAULT_CAMPAIGN_FILE}\"\n            echo \"  --dbc-file <FILE>       DBC file, default: ${DEFAULT_DBC_FILE}\"\n            echo \"  --bucket-name <NAME>    S3 bucket name, default: iot-fleetwise-demo-<RANDOM_HASH>\"\n            echo \"  --clean-up              Delete created resources\"\n            echo \"  --enable-s3-upload      Create campaigns to upload data to S3\"\n            echo \"  --endpoint-url <URL>    The endpoint URL used for AWS CLI calls\"\n            echo \"  --service-principal <PRINCIPAL>    AWS service principal for policies, default: ${SERVICE_PRINCIPAL}\"\n            echo \"  --region <REGION>       The region used for AWS CLI calls, default: ${REGION}\"\n            exit 0\n            ;;\n        esac\n        shift\n    done\n\n    if [ \"${ENDPOINT_URL}\" != \"\" ]; then\n        ENDPOINT_URL_OPTION=\"--endpoint-url ${ENDPOINT_URL}\"\n    fi\n    if ((FLEET_SIZE==0)); then\n        echo \"Error: Fleet size must be greater than zero\" >&2\n        exit -1\n    fi\n}\n\necho \"===================================\"\necho \"AWS IoT FleetWise Cloud Demo Script\"\necho \"===================================\"\n\nparse_args \"$@\"\n\nif [ \"${VEHICLE_NAME}\" == \"\" ]; then\n    echo -n \"Enter Vehicle name [${DEFAULT_VEHICLE_NAME}]: \"\n    read VEHICLE_NAME\n    if [ \"${VEHICLE_NAME}\" == \"\" ]; then\n        VEHICLE_NAME=${DEFAULT_VEHICLE_NAME}\n    fi\nfi\n\nif [ \"${DBC_FILE}\" != \"\" ] && [ \"${CAMPAIGN_FILE}\" == \"\" ]; then\n    echo -n \"Enter campaign file name: \"\n    read CAMPAIGN_FILE\n    if [ \"${CAMPAIGN_FILE}\" == \"\" ]; then\n        echo \"Error: Please provide campaign file name for custom DBC file\" >&2\n        exit -1\n    fi\nfi\n\nif [ \"${CAMPAIGN_FILE}\" == \"\" ]; then\n    CAMPAIGN_FILE=${DEFAULT_CAMPAIGN_FILE}\nfi\n\nif [ \"${BUCKET_NAME}\" == \"\" ]; then\n    BUCKET_NAME=\"iot-fleetwise-demo-${RANDOM_HASH}\"\n    SKIP_S3_POLICY=false\nfi\n\nNAME=\"${VEHICLE_NAME}-${TIMESTAMP}\"\nSERVICE_ROLE=\"${SERVICE_ROLE}-${REGION}-${TIMESTAMP}\"\n\necho -n \"Date: \"\ndate +%Y-%m-%dT%H:%M:%S%z\necho \"Timestamp: ${TIMESTAMP}\"\necho \"Vehicle name: ${VEHICLE_NAME}\"\necho \"Fleet Size: ${FLEET_SIZE}\"\n\n# AWS CLI v1.x has a double base64 encoding issue\necho \"Checking AWS CLI version...\"\nCLI_VERSION=`aws --version | grep -Eo \"aws-cli/[[:digit:]]+.[[:digit:]]+.[[:digit:]]+\"`\necho \"${CLI_VERSION}\"\n\nif [[ \"${CLI_VERSION}\" < \"${MIN_CLI_VERSION}\" ]]; then\n    echo \"Error: Please update AWS CLI to ${MIN_CLI_VERSION} or newer\" >&2\n    exit -1\nfi\n\nerror_handler() {\n    if [ ${CLEAN_UP} == true ]; then\n        ./clean-up.sh \\\n            --vehicle-name ${VEHICLE_NAME} \\\n            --fleet-size ${FLEET_SIZE} \\\n            --timestamp ${TIMESTAMP} \\\n            ${ENDPOINT_URL_OPTION} \\\n            --region ${REGION} \\\n            --service-role ${SERVICE_ROLE} \\\n            --service-role-policy-arn ${SERVICE_ROLE_POLICY_ARN}\n    fi\n}\n\nregister_account() {\n    echo \"Registering account...\"\n    aws iotfleetwise register-account \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} | jq -r .registerAccountStatus\n    echo \"Waiting for account to be registered...\"\n}\n\nget_account_status() {\n    aws iotfleetwise get-register-account-status ${ENDPOINT_URL_OPTION} --region ${REGION}\n}\n\n# $1 is the campaign name\napprove_campaign() {\n    echo \"Waiting for campaign to become ready for approval...\"\n    while true; do\n        sleep 5\n        SIGNAL_CATALOG_COUNT=`echo ${SIGNAL_CATALOG_LIST} | jq '.summaries|length'`\n        CAMPAIGN_STATUS=`aws iotfleetwise get-campaign \\\n            ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n            --name $1`\n        echo ${CAMPAIGN_STATUS} | jq -r .arn\n        if [ `echo ${CAMPAIGN_STATUS} | jq -r .status` == \"WAITING_FOR_APPROVAL\" ]; then\n            break\n        fi\n    done\n\n    echo \"Approving campaign...\"\n    aws iotfleetwise update-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name $1 \\\n        --action APPROVE | jq -r .arn\n}\n\ntrap error_handler ERR\n\necho \"Getting AWS account ID...\"\necho ${ACCOUNT_ID}\n\necho \"Getting account registration status...\"\nif REGISTER_ACCOUNT_STATUS=`get_account_status 2>&1`; then\n    ACCOUNT_STATUS=`echo \"${REGISTER_ACCOUNT_STATUS}\" | jq -r .accountStatus`\nelif ! echo ${REGISTER_ACCOUNT_STATUS} | grep -q \"ResourceNotFoundException\"; then\n    echo ${REGISTER_ACCOUNT_STATUS} >&2\n    exit -1\nelse\n    ACCOUNT_STATUS=\"NOT_REGISTERED\"\nfi\necho ${ACCOUNT_STATUS}\nif [ \"${ACCOUNT_STATUS}\" == \"REGISTRATION_SUCCESS\" ]; then\n    echo \"Account is already registered\"\nelif [ \"${ACCOUNT_STATUS}\" == \"REGISTRATION_PENDING\" ]; then\n    echo \"Waiting for account to be registered...\"\nelse\n    register_account\nfi\n\n# Due to IAM's eventual consistency, the registration may initially fail because the\n# recently created role and the attached policies take some time to propagate.\nREGISTRATION_ATTEMPTS=0\nwhile [ \"${ACCOUNT_STATUS}\" != \"REGISTRATION_SUCCESS\" ]; do\n    sleep 5\n    REGISTER_ACCOUNT_STATUS=`get_account_status`\n    ACCOUNT_STATUS=`echo \"${REGISTER_ACCOUNT_STATUS}\" | jq -r .accountStatus`\n    if [ \"${ACCOUNT_STATUS}\" == \"REGISTRATION_FAILURE\" ]; then\n        echo \"Error: Registration failed\" >&2\n        ((REGISTRATION_ATTEMPTS+=1))\n        if ((REGISTRATION_ATTEMPTS >= MAX_ATTEMPTS_ON_REGISTRATION_FAILURE)); then\n            echo \"${REGISTER_ACCOUNT_STATUS}\" >&2\n            echo \"All ${MAX_ATTEMPTS_ON_REGISTRATION_FAILURE} registration attempts failed\" >&2\n            exit -1\n        else\n            register_account\n        fi\n    fi\ndone\n\necho \"Creating Timestream database...\" >&2\naws timestream-write create-database \\\n    --region ${REGION} \\\n    --database-name ${TIMESTREAM_DB_NAME} | jq -r .Database.Arn\n\necho \"Creating Timestream table...\"\nTIMESTREAM_TABLE_ARN=$( aws timestream-write create-table \\\n    --region ${REGION} \\\n    --database-name ${TIMESTREAM_DB_NAME} \\\n    --table-name ${TIMESTREAM_TABLE_NAME} \\\n    --retention-properties \"{\\\"MemoryStoreRetentionPeriodInHours\\\":2, \\\n        \\\"MagneticStoreRetentionPeriodInDays\\\":2}\" | jq -r .Table.Arn )\n\necho \"Creating service role...\"\nSERVICE_ROLE_TRUST_POLICY=$(cat << EOF\n{\n  \"Version\": \"2012-10-17\",\n  \"Statement\": [\n    {\n      \"Effect\": \"Allow\",\n      \"Principal\": {\n        \"Service\": [\n            \"$SERVICE_PRINCIPAL\"\n        ]\n      },\n      \"Action\": \"sts:AssumeRole\"\n    }\n  ]\n}\nEOF\n)\nSERVICE_ROLE_ARN=`aws iam create-role \\\n    --role-name \"${SERVICE_ROLE}\" \\\n    --assume-role-policy-document \"${SERVICE_ROLE_TRUST_POLICY}\" | jq -r .Role.Arn`\necho ${SERVICE_ROLE_ARN}\n\necho \"Waiting for role to be created...\"\naws iam wait role-exists \\\n    --role-name \"${SERVICE_ROLE}\"\n\necho \"Creating service role policy...\"\nSERVICE_ROLE_POLICY=$(cat <<'EOF'\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Sid\": \"timestreamIngestion\",\n            \"Effect\": \"Allow\",\n            \"Action\": [\n                \"timestream:WriteRecords\",\n                \"timestream:Select\"\n            ]\n        },\n        {\n            \"Sid\": \"timestreamDescribeEndpoint\",\n            \"Effect\": \"Allow\",\n            \"Action\": [\n                \"timestream:DescribeEndpoints\"\n            ],\n            \"Resource\": \"*\"\n        }\n    ]\n}\nEOF\n)\nSERVICE_ROLE_POLICY=`echo \"${SERVICE_ROLE_POLICY}\" \\\n    | jq \".Statement[0].Resource=\\\"arn:aws:timestream:${REGION}:${ACCOUNT_ID}:database/${TIMESTREAM_DB_NAME}/*\\\"\"`\nSERVICE_ROLE_POLICY_ARN=`aws iam create-policy \\\n    --policy-name ${SERVICE_ROLE}-policy \\\n    --policy-document \"${SERVICE_ROLE_POLICY}\" | jq -r .Policy.Arn`\necho ${SERVICE_ROLE_POLICY_ARN}\n\necho \"Waiting for policy to be created...\"\naws iam wait policy-exists \\\n    --policy-arn \"${SERVICE_ROLE_POLICY_ARN}\"\n\necho \"Attaching policy to service role...\"\naws iam attach-role-policy \\\n    --policy-arn ${SERVICE_ROLE_POLICY_ARN} \\\n    --role-name \"${SERVICE_ROLE}\"\n\nif ((FLEET_SIZE==1)); then\n    echo \"Deleting vehicle ${VEHICLE_NAME} if it already exists...\"\n    aws iotfleetwise delete-vehicle \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --vehicle-name \"${VEHICLE_NAME}\"\nelse\n    echo \"Deleting vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1)) if it already exists...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                aws iotfleetwise delete-vehicle \\\n                    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n                    --vehicle-name \"${VEHICLE_NAME}-$((i+j))\" \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\nif [ ${S3_UPLOAD} == true ]; then\n    echo \"S3 upload is enabled\"\n    echo \"Checking if S3 bucket exists...\"\n\n    BUCKET_LIST=$( aws s3 ls )\n    if grep -q \"$BUCKET_NAME\" <<< \"$BUCKET_LIST\"; then\n        echo \"S3 bucket already exists\"\n    else\n        echo \"Creating S3 bucket...\"\n        aws s3 mb s3://$BUCKET_NAME --region $REGION\n    fi\n    if [ ${SKIP_S3_POLICY} == false ]; then\n        echo \"Adding S3 bucket policy...\"\n        cat << EOF > s3-bucket-policy.json\n{\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"${SERVICE_PRINCIPAL}\"\n            },\n            \"Action\": \"s3:ListBucket\",\n            \"Resource\": \"arn:aws:s3:::${BUCKET_NAME}\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"${SERVICE_PRINCIPAL}\"\n            },\n            \"Action\": [\"s3:GetObject\", \"s3:PutObject\"],\n            \"Resource\": \"arn:aws:s3:::${BUCKET_NAME}/*\"\n        }\n    ]\n}\nEOF\n        aws s3api put-bucket-policy --bucket $BUCKET_NAME --policy file://s3-bucket-policy.json\n    fi\nfi\n\nVEHICLE_NODE=`cat vehicle-node.json`\nOBD_NODES=`cat obd-nodes.json`\nif [ \"${DBC_FILE}\" == \"\" ]; then\n    DBC_NODES=`python3 dbc-to-nodes.py ${DEFAULT_DBC_FILE}`\nelse\n    DBC_NODES=`python3 dbc-to-nodes.py ${DBC_FILE}`\nfi\n\necho \"Checking for existing signal catalog...\"\nSIGNAL_CATALOG_LIST=`aws iotfleetwise list-signal-catalogs \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION}`\nSIGNAL_CATALOG_COUNT=`echo ${SIGNAL_CATALOG_LIST} | jq '.summaries|length'`\n# Currently only one signal catalog is supported by the service\nif [ ${SIGNAL_CATALOG_COUNT} == 0 ]; then\n    echo \"No existing signal catalog\"\n    echo \"Creating signal catalog with Vehicle node...\"\n    SIGNAL_CATALOG_ARN=`aws iotfleetwise create-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-signal-catalog \\\n        --nodes \"${VEHICLE_NODE}\" | jq -r .arn`\n    echo ${SIGNAL_CATALOG_ARN}\n\n    echo \"Adding OBD signals to signal catalog...\"\n    aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-signal-catalog \\\n        --description \"OBD signals\" \\\n        --nodes-to-add \"${OBD_NODES}\" | jq -r .arn\n\n    echo \"Adding DBC signals to signal catalog...\"\n    aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-signal-catalog \\\n        --description \"DBC signals\" \\\n        --nodes-to-add \"${DBC_NODES}\" | jq -r .arn\n\n    echo \"Add an attribute to signal catalog...\"\n    aws iotfleetwise update-signal-catalog \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-signal-catalog \\\n        --description \"DBC Attributes\" \\\n        --nodes-to-add '[{\n            \"attribute\": {\n                \"dataType\": \"STRING\",\n                \"description\": \"Color\",\n                \"fullyQualifiedName\": \"Vehicle.Color\",\n                \"defaultValue\":\"Red\"\n            }}\n        ]' | jq -r .arn\nelse\n    SIGNAL_CATALOG_NAME=`echo ${SIGNAL_CATALOG_LIST} | jq -r .summaries[0].name`\n    SIGNAL_CATALOG_ARN=`echo ${SIGNAL_CATALOG_LIST} | jq -r .summaries[0].arn`\n    echo ${SIGNAL_CATALOG_ARN}\n\n    echo \"Updating Vehicle node in signal catalog...\"\n    if UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --description \"Vehicle node\" \\\n        --nodes-to-update \"${VEHICLE_NODE}\" 2>&1`; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\n    elif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n        exit -1\n    else\n        echo \"Node exists and is in use, continuing\"\n    fi\n\n    echo \"Updating OBD signals in signal catalog...\"\n    if UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --description \"OBD signals\" \\\n        --nodes-to-update \"${OBD_NODES}\" 2>&1`; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\n    elif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n        exit -1\n    else\n        echo \"Signals exist and are in use, continuing\"\n    fi\n\n    echo \"Updating DBC signals in signal catalog...\"\n    if UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --description \"DBC signals\" \\\n        --nodes-to-update \"${DBC_NODES}\" 2>&1`; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\n    elif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n        exit -1\n    else\n        echo \"Signals exist and are in use, continuing\"\n    fi\n\n    echo \"Updating color attribute\"\n    if UPDATE_SIGNAL_CATALOG_STATUS=`aws iotfleetwise update-signal-catalog \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${SIGNAL_CATALOG_NAME} \\\n        --description \"DBC Attributes\" \\\n        --nodes-to-add '[{\n            \"attribute\": {\n                \"dataType\": \"STRING\",\n                \"description\": \"Color\",\n                \"fullyQualifiedName\": \"Vehicle.Color\",\n                \"defaultValue\":\"Red\"\n            }}\n        ]' 2>&1`; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} | jq -r .arn\n    elif ! echo ${UPDATE_SIGNAL_CATALOG_STATUS} | grep -q \"InvalidSignalsException\"; then\n        echo ${UPDATE_SIGNAL_CATALOG_STATUS} >&2\n        exit -1\n    else\n        echo \"Signals exist and are in use, continuing\"\n    fi\nfi\n\necho \"Creating model manifest...\"\n# Make a list of all node names:\nNODE_LIST=`( echo ${DBC_NODES} | jq -r .[].sensor.fullyQualifiedName | grep Vehicle\\\\. ; \\\n             echo ${OBD_NODES} | jq -r .[].sensor.fullyQualifiedName | grep Vehicle\\\\. ) | jq -Rn [inputs]`\naws iotfleetwise create-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest \\\n    --signal-catalog-arn ${SIGNAL_CATALOG_ARN} \\\n    --nodes \"${NODE_LIST}\" | jq -r .arn\n\necho \"Updating attribute in model manifest...\"\nMODEL_MANIFEST_ARN=`aws iotfleetwise update-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest \\\n    --nodes-to-add 'Vehicle.Color' | jq -r .arn`\necho ${MODEL_MANIFEST_ARN}\n\necho \"Activating model manifest...\"\nMODEL_MANIFEST_ARN=`aws iotfleetwise update-model-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-model-manifest \\\n    --status ACTIVE | jq -r .arn`\necho ${MODEL_MANIFEST_ARN}\n\necho \"Creating decoder manifest with OBD signals...\"\nNETWORK_INTERFACES=`cat network-interfaces.json`\nOBD_SIGNAL_DECODERS=`cat obd-decoders.json`\nDECODER_MANIFEST_ARN=`aws iotfleetwise create-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest \\\n    --model-manifest-arn ${MODEL_MANIFEST_ARN} \\\n    --network-interfaces \"${NETWORK_INTERFACES}\" \\\n    --signal-decoders \"${OBD_SIGNAL_DECODERS}\" | jq -r .arn`\necho ${DECODER_MANIFEST_ARN}\n\necho \"Adding DBC signals to decoder manifest...\"\nif [ \"${DBC_FILE}\" == \"\" ]; then\n    DBC=`cat ${DEFAULT_DBC_FILE} | base64 -w0`\n    # Make map of node name to DBC signal name, i.e. {\"Vehicle.SignalName\":\"SignalName\"...}\n    NODE_TO_DBC_MAP=`echo ${DBC_NODES} | jq '.[].sensor.fullyQualifiedName//\"\"|match(\"Vehicle\\\\\\\\.\\\\\\\\w+\\\\\\\\.(.+)\")|{(.captures[0].string):.string}'|jq -s add`\n    NETWORK_FILE_DEFINITIONS=`echo [] \\\n        | jq .[0].canDbc.signalsMap=\"${NODE_TO_DBC_MAP}\" \\\n        | jq .[0].canDbc.networkInterface=\"\\\"1\\\"\" \\\n        | jq .[0].canDbc.canDbcFiles[0]=\"\\\"${DBC}\\\"\"`\n    aws iotfleetwise import-decoder-manifest \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-decoder-manifest \\\n        --network-file-definitions \"${NETWORK_FILE_DEFINITIONS}\" | jq -r .arn\nelse\n    SIGNAL_DECODERS=`python3 dbc-to-json.py ${DBC_FILE}`\n    aws iotfleetwise update-decoder-manifest \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --name ${NAME}-decoder-manifest \\\n        --signal-decoders-to-add \"${SIGNAL_DECODERS}\" | jq -r .arn\nfi\n\necho \"Activating decoder manifest...\"\naws iotfleetwise update-decoder-manifest \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-decoder-manifest \\\n    --status ACTIVE | jq -r .arn\n\nif ((FLEET_SIZE==1)); then\n    echo \"Creating vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise create-vehicle \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --decoder-manifest-arn ${DECODER_MANIFEST_ARN} \\\n        --association-behavior ValidateIotThingExists \\\n        --model-manifest-arn ${MODEL_MANIFEST_ARN} \\\n        --attributes '{\"Vehicle.Color\":\"Red\"}' \\\n        --vehicle-name \"${VEHICLE_NAME}\" | jq -r .arn\nelse\n    echo \"Creating vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1))...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                aws iotfleetwise create-vehicle \\\n                    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n                    --decoder-manifest-arn ${DECODER_MANIFEST_ARN} \\\n                    --association-behavior ValidateIotThingExists \\\n                    --model-manifest-arn ${MODEL_MANIFEST_ARN} \\\n                    --attributes '{\"Vehicle.Color\":\"Red\"}' \\\n                    --vehicle-name \"${VEHICLE_NAME}-$((i+j))\" >/dev/null \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\necho \"Creating fleet...\"\nFLEET_ARN=`aws iotfleetwise create-fleet \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --fleet-id ${NAME}-fleet \\\n    --description \"Description is required\" \\\n    --signal-catalog-arn ${SIGNAL_CATALOG_ARN} | jq -r .arn`\necho ${FLEET_ARN}\n\nif ((FLEET_SIZE==1)); then\n    echo \"Associating vehicle ${VEHICLE_NAME}...\"\n    aws iotfleetwise associate-vehicle-fleet \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --fleet-id ${NAME}-fleet \\\n        --vehicle-name \"${VEHICLE_NAME}\"\nelse\n    echo \"Associating vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1))...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                aws iotfleetwise associate-vehicle-fleet \\\n                    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n                    --fleet-id ${NAME}-fleet \\\n                    --vehicle-name \"${VEHICLE_NAME}-$((i+j))\" \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\necho \"Creating campaign from ${CAMPAIGN_FILE}...\"\nCAMPAIGN=`cat ${CAMPAIGN_FILE} \\\n    | jq .name=\\\"${NAME}-campaign\\\" \\\n    | jq .signalCatalogArn=\\\"${SIGNAL_CATALOG_ARN}\\\" \\\n    | jq .targetArn=\\\"${FLEET_ARN}\\\"`\naws iotfleetwise create-campaign \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --cli-input-json \"${CAMPAIGN}\" --data-destination-configs \"[{\\\"timestreamConfig\\\":{\\\"timestreamTableArn\\\":\\\"${TIMESTREAM_TABLE_ARN}\\\",\\\"executionRoleArn\\\":\\\"${SERVICE_ROLE_ARN}\\\"}}]\"| jq -r .arn\n\napprove_campaign ${NAME}-campaign\n\nif [ ${S3_UPLOAD} == true ]; then\n    echo \"Creating campaign from ${CAMPAIGN_FILE} for S3...\"\n    CAMPAIGN=`cat ${CAMPAIGN_FILE} \\\n        | jq .name=\\\"${NAME}-campaign-s3-json\\\" \\\n        | jq .signalCatalogArn=\\\"${SIGNAL_CATALOG_ARN}\\\" \\\n        | jq .targetArn=\\\"${FLEET_ARN}\\\"`\n    aws iotfleetwise create-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --cli-input-json \"${CAMPAIGN}\" --data-destination-configs \"[{\\\"s3Config\\\":{\\\"bucketArn\\\":\\\"arn:aws:s3:::${BUCKET_NAME}\\\",\\\"prefix\\\":\\\"${NAME}-campaign-s3-${RANDOM_HASH}\\\",\\\"dataFormat\\\":\\\"JSON\\\",\\\"storageCompressionFormat\\\":\\\"NONE\\\"}}]\"| jq -r .arn\n\n    approve_campaign ${NAME}-campaign-s3-json\n\n    echo \"Creating campaign from ${CAMPAIGN_FILE} for S3...\"\n    CAMPAIGN=`cat ${CAMPAIGN_FILE} \\\n        | jq .name=\\\"${NAME}-campaign-s3-parquet\\\" \\\n        | jq .signalCatalogArn=\\\"${SIGNAL_CATALOG_ARN}\\\" \\\n        | jq .targetArn=\\\"${FLEET_ARN}\\\"`\n    aws iotfleetwise create-campaign \\\n        ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n        --cli-input-json \"${CAMPAIGN}\" --data-destination-configs \"[{\\\"s3Config\\\":{\\\"bucketArn\\\":\\\"arn:aws:s3:::${BUCKET_NAME}\\\",\\\"prefix\\\":\\\"${NAME}-campaign-s3-${RANDOM_HASH}\\\",\\\"dataFormat\\\":\\\"PARQUET\\\",\\\"storageCompressionFormat\\\":\\\"NONE\\\"}}]\"| jq -r .arn\n\n    approve_campaign ${NAME}-campaign-s3-parquet\nfi\n\n# The following two actions(Suspending, Resuming) are only for demo purpose, it won't affect the campaign status\nsleep 2\necho \"Suspending campaign...\"\naws iotfleetwise update-campaign \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-campaign \\\n    --action SUSPEND | jq -r .arn\n\nsleep 2\necho \"Resuming campaign...\"\naws iotfleetwise update-campaign \\\n    ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n    --name ${NAME}-campaign \\\n    --action RESUME | jq -r .arn\n\ncheck_vehicle_healthy() {\n    for ((k=0; k<${HEALTH_CHECK_RETRIES}; k++)); do\n        VEHICLE_STATUS=`aws iotfleetwise get-vehicle-status \\\n            ${ENDPOINT_URL_OPTION} --region ${REGION} \\\n            --vehicle-name \"$1\"`\n        for ((l=0; ; l++)); do\n            CAMPAIGN_NAME=`echo ${VEHICLE_STATUS} | jq -r .campaigns[${l}].campaignName`\n            CAMPAIGN_STATUS=`echo ${VEHICLE_STATUS} | jq -r .campaigns[${l}].status`\n            # If the campaign was not found (when the index is out-of-range jq will return 'null')\n            if [ \"${CAMPAIGN_NAME}\" == \"null\" ]; then\n                echo \"Error: Campaign not found in vehicle status for vehicle $1\" >&2\n                exit -1\n            # If the campaign was found \\\n            elif [ \"${CAMPAIGN_NAME}\" == \"${NAME}-campaign\" ]; then\n                if [ \"${CAMPAIGN_STATUS}\" == \"HEALTHY\" ]; then\n                    break 2\n                fi\n                break\n            fi\n        done\n        sleep 5\n    done\n    if ((k>=HEALTH_CHECK_RETRIES)); then\n        echo \"Error: Health check timeout for vehicle $1\" >&2\n        exit -1\n    fi\n}\n\nif ((FLEET_SIZE==1)); then\n    echo \"Waiting until status of vehicle ${VEHICLE_NAME} is healthy...\"\n    check_vehicle_healthy \"${VEHICLE_NAME}\"\nelse\n    echo \"Waiting until status of vehicle ${VEHICLE_NAME}-0..$((FLEET_SIZE-1)) is healthy...\"\n    for ((i=0; i<${FLEET_SIZE}; i+=${BATCH_SIZE})); do\n        for ((j=0; j<${BATCH_SIZE} && i+j<${FLEET_SIZE}; j++)); do\n            # This output group is run in a background process. Note that stderr is redirected to stream 3 and back,\n            # to print stderr from the output group, but not info about the background process.\n            { \\\n                check_vehicle_healthy \"${VEHICLE_NAME}-$((i+j))\" \\\n            2>&3 &} 3>&2 2>/dev/null\n        done\n        # Wait for all background processes to finish\n        wait\n    done\nfi\n\nDELAY=30\necho \"Waiting ${DELAY} seconds for data to be collected...\"\nsleep ${DELAY}\n\necho \"The DB Name is ${TIMESTREAM_DB_NAME}\"\necho \"The DB Table is ${TIMESTREAM_TABLE_NAME}\"\n\necho \"Querying Timestream...\"\naws timestream-query query \\\n    --region ${REGION} \\\n    --query-string \"SELECT * FROM \\\"${TIMESTREAM_DB_NAME}\\\".\\\"${TIMESTREAM_TABLE_NAME}\\\" \\\n        WHERE vehicleName = '${VEHICLE_NAME}`if ((FLEET_SIZE>1)); then echo \"-0\"; fi`' \\\n        AND time between ago(1m) and now() ORDER BY time ASC\" \\\n    > ${NAME}-timestream-result.json\n\nif [ \"${DBC_FILE}\" == \"\" ]; then\n    echo \"Converting to HTML...\"\n    OUTPUT_FILE_HTML=\"${NAME}.html\"\n    python3 timestream-to-html.py ${NAME}-timestream-result.json ${OUTPUT_FILE_HTML}\n\n    echo \"You can now view the collected data.\"\n    echo \"----------------------------------\"\n    echo \"| Collected data in HTML format: |\"\n    echo \"----------------------------------\"\n    echo `pwd`/${OUTPUT_FILE_HTML}\nfi\n\nif [ ${S3_UPLOAD} == true ]; then\n    DELAY=1200\n    echo \"Waiting 20 minutes for data to be collected and uploaded to S3...\"\n    sleep ${DELAY}\n\n    if [ \"${DBC_FILE}\" == \"\" ]; then\n        echo \"Converting data from S3 to HTML...\"\n        OUTPUT_FILE_HTML=\"${NAME}.html\"\n        python3 s3-to-html.py --bucket ${BUCKET_NAME} --prefix ${NAME}-campaign-s3-${RANDOM_HASH} --json-output-filename ${NAME}-s3-json-result.html --parquet-output-filename ${NAME}-s3-parquet-result.html\n\n        echo \"You can now view the collected data.\"\n        echo \"-------------------------------------\"\n        echo \"| Collected S3 data in HTML format: |\"\n        echo \"-------------------------------------\"\n        echo `pwd`/${NAME}-s3-json-result.html \"and\" `pwd`/${NAME}-s3-parquet-result.html\n    fi\nfi\n\nif [ ${CLEAN_UP} == true ]; then\n    ./clean-up.sh \\\n        --vehicle-name ${VEHICLE_NAME} \\\n        --fleet-size ${FLEET_SIZE} \\\n        --timestamp ${TIMESTAMP} \\\n        ${ENDPOINT_URL_OPTION} \\\n        --region ${REGION}\nfi\n", "num_lines": 778}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -eo pipefail\n\n# Install Python 3 and pip\napt update && apt install -y python3 python3-pip\n\n# Install pip packages\npip3 install \\\n    wrapt==1.10.0 \\\n    plotly==5.3.1 \\\n    pandas==1.5.0 \\\n    cantools==36.4.0 \\\n    boto3==1.18.60 \\\n    fastparquet==2023.4.0\n", "num_lines": 18}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nCONFIG_FILE=\"/etc/aws-iot-fleetwise/config-0.json\"\n\nmkdir -p `dirname ${CONFIG_FILE}`\n/usr/bin/configure-fwe.sh \\\n    --input-config-file /usr/share/aws-iot-fleetwise/static-config.json \\\n    --output-config-file ${CONFIG_FILE} \\\n    $@\nCAN_IF=`jq -r .networkInterfaces[0].canInterface.interfaceName ${CONFIG_FILE}`\nPERSISTENCY_PATH=`jq -r .staticConfig.persistency.persistencyPath ${CONFIG_FILE}`\n\nmkdir -p ${PERSISTENCY_PATH}\n\nfunction ifup {\n    typeset output\n    output=$(ip link show \"$1\" up) && [[ -n $output ]]\n}\n\nwhile true; do\n    if ifup ${CAN_IF}; then\n        break\n    fi\n    echo \"Waiting for $CAN_IF\"\n    sleep 3\ndone\n\n/usr/bin/aws-iot-fleetwise-edge ${CONFIG_FILE}\n", "num_lines": 33}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -e\n\nif [ $# -eq 0 ]; then\n    echo \"Instance number not provided\"\n    exit 1\nfi\n\nEXTRA_ARGS=\"\"\n\n/usr/bin/aws-iot-fleetwise-edge /etc/aws-iot-fleetwise/config-$1.json ${EXTRA_ARGS}\n", "num_lines": 15}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Start and enable the FWE service at startup:\nsystemctl daemon-reload\nFLEET_SIZE=`ls -1 /etc/aws-iot-fleetwise/*.json | wc -l`\nLAST_SERVICE=`expr ${FLEET_SIZE} - 1`\nSERVICES=\"\"\nfor i in `seq 0 ${LAST_SERVICE}`; do\n   SERVICES=\"${SERVICES} fwe@$i\"\ndone\necho \"Starting and enabling${SERVICES}\"\nsystemctl enable ${SERVICES}\nsystemctl start ${SERVICES}\n", "num_lines": 16}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nFLEET_SIZE=`ls -1 /etc/aws-iot-fleetwise/*.json | wc -l`\nLAST_SERVICE=`expr ${FLEET_SIZE} - 1`\nSERVICES=\"\"\nfor i in `seq 0 ${LAST_SERVICE}`; do\n   SERVICES=\"${SERVICES} fwe@$i\"\ndone\necho \"Stopping${SERVICES}\"\nsystemctl stop ${SERVICES} 2> /dev/null || true\n", "num_lines": 13}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nSCRIPT_DIR=$(cd `dirname $0` && pwd)\n#################################\n# Configuable parameter         #\n#################################\nDEVICE=spider\nUSERNAME=rcar\nHOSTNAME=${DEVICE}\n\nKERNEL_CONFIG_APPEND=\"\n# for USB3 support\nCONFIG_FW_LOADER=y\nCONFIG_FIRMWARE_IN_KERNEL=y\nCONFIG_EXTRA_FIRMWARE=\\\"r8a779x_usb3_v2.dlmem r8a779x_usb3_v3.dlmem\\\"\nCONFIG_EXTRA_FIRMWARE_DIR=\\\"firmware\\\"\n# Avoid waiting timeout for loading USB firmware\nCONFIG_FW_LOADER_USER_HELPER=n\nCONFIG_FW_LOADER_USER_HELPER_FALLBACK=n\n# For fleetwise\nCONFIG_CAN_ISOTP=m\nCONFIG_CAN_VCAN=m\n# For S4\nCONFIG_GPIO_SYSFS=y\nCONFIG_DMATEST=m\nCONFIG_PCI_ENDPOINT_TEST=y\nCONFIG_SPI_SH_MSIOF=y\nCONFIG_SPI_SPIDEV=y\n\"\n\n#####################################################\n# Setup                                             #\n#####################################################\nif [[ $# < 2 ]]; then\n    echo \"Usage: $0 <Ubuntu version> <device_name> (<gui_option>)\"\n    echo \"    Ubuntu version(required):\"\n    echo \"        18.04.3, 20.04.4, etc...\"\n    echo \"        Please visit http://cdimage.ubuntu.com/ubuntu-base/releases/ .\"\n    echo \"    Target device(required):\"\n    echo \"        spider, ccpf-sk, ulcb\"\n    echo \"    gui_option(optional):\"\n    echo \"        -g: install gnome desktop. But it may be slow because GPU is not active.\"\n    echo \"    SD card option(optional) For S4 Spider:\"\n    echo \"        -sd: use sdcard instead of eMMC.\"\n    echo \"Required package:\"\n    echo \"    sudo apt install debootstrap qemu-user-static binfmt-support gcc-aarch64-linux-gnu\"\n    echo \"    # Also required the software which is needed to build linux kernel.\"\n    echo \"memo:\"\n    echo \"    debootstrap is not needed, but dependencies are required.\"\n    exit\nfi\n\nNET_DEV=eth0\nif [[ \"$2\" == \"spider\" ]]; then\n    DEVICE=spider\n    NET_DEV=tsn0\nelif [[ \"$2\" == \"ccpf-sk\" ]]; then\n    DEVICE=ccpf-sk\nelif [[ \"$2\" == \"ulcb\" ]]; then\n    DEVICE=ulcb\nelse\n    echo error: Check target board\n    exit\nfi\n\nif [[ \"$(id -u)\" != \"0\" ]]; then\n    echo Please run as root!; exit 1\nfi\n\nif [[ \"`update-binfmts --display | grep aarch64`\" == \"\" ]]; then\n    echo \"qemu may not be installed.\"\n    echo \"Please install it by following command:\"\n    echo \"    sudo apt install qemu-user-static\"\n    exit\nfi\nif [[ \"`update-binfmts --display | grep aarch64 | grep enable`\" == \"\" ]]; then\n    echo \"qemu-aarch64 is not enabled.\"\n    echo \"Please enable it by following command:\"\n    echo \"    sudo update-binfmts --enable qemu-aarch64\"\n    exit\nfi\nif [[ ! -e \"`which flex`\" ]]; then\n    echo \"It seems that depencencies are not installed\"\n    echo \"sudo apt-get install libncurses-dev gawk flex bison openssl libssl-dev dkms libelf-dev libudev-dev libpci-dev libiberty-dev autoconf\"\nfi\n\nADDITIONAL_PACKAGE=\"\"\nROOTFS_APPEND=\"\"\n# Gnome option\nif [[ \"$(echo $@' '| grep ' -g ')\" != \"\" ]]; then\n    ADDITIONAL_PACKAGE=\" gnome libegl-mesa0\"\n    ROOTFS_APPEND=\"-gnome\"\nfi\n\nSDCARD_OPTION=\"\"\nif [[ \"$(echo $@' '| grep ' -sd ')\" != \"\" ]]; then\n    if [[ \"${DEVICE}\" == \"spider\" ]]; then\n        SDCARD_OPTION=\"True\"\n    fi\nfi\n\nDHCP_CONF=\"\n[Match]\nName=${NET_DEV}\n[Network]\nDHCP=ipv4\n\"\n\nNAMESERVER=$(cat /etc/resolv.conf | grep nameserver | head -n 1 | awk '{print $2}')\nUBUNTU_ROOTFS_NAME=ubuntu-base-$1-base-arm64.tar.gz\nUBUNTU_VER=$1\nUBUNTU_ROOTFS_URL=http://cdimage.ubuntu.com/ubuntu-base/releases/${UBUNTU_VER}/release/${UBUNTU_ROOTFS_NAME}\n\nROOTFS=${ROOTFS:-Ubuntu-${UBUNTU_VER}${ROOTFS_APPEND}-rootfs}\nSDCARD_IMAGE_NAME=${ROOTFS}-image-rcar-${DEVICE}.ext4\nif [[ \"${SDCARD_OPTION}\" == \"True\" ]]; then\n    SDCARD_IMAGE_NAME=${ROOTFS}-image-rcar-${DEVICE}-sdcard.ext4\nfi\n\n# Cleanup\nrm -rf ${SDCARD_IMAGE_NAME} ${SDCARD_IMAGE_NAME}.gz\nrm -rf ${ROOTFS}\n\n# Downlaod ubuntu base\nmkdir -p ${ROOTFS}\nwget ${UBUNTU_ROOTFS_URL} -O- | tar zx -C ${ROOTFS}\n\n#####################################################\n# Build linux-kernel                                #\n#####################################################\n# Prepare linux-kernel for R-Car\ncd ${SCRIPT_DIR}\nif [ ! -e linux-bsp-${DEVICE} ]; then\n    if [[ \"${DEVICE}\" == \"spider\" ]] ;then\n        BRANCH=v5.10.41/rcar-5.1.6.rc3\n        git clone --depth 1 https://github.com/renesas-rcar/linux-bsp -b ${BRANCH} linux-bsp-${DEVICE}\n    else\n        git clone --depth 1 https://github.com/renesas-rcar/linux-bsp/ -b v5.10.41/rcar-5.1.4 linux-bsp-${DEVICE}\n    fi\n    cd linux-bsp-${DEVICE}\n    if [[ \"${DEVICE}\" == \"ccpf-sk\" ]]; then\n        wget https://github.com/renesas-rcar/meta-renesas-ccpf/archive/refs/heads/dunfell.zip\n        unzip dunfell.zip\n        git am ./meta-renesas-ccpf-dunfell/meta-rcar-gen3/recipes-kernel/linux/linux-renesas/*.patch\n        rm -rf dunfell.zip ./meta-renesas-ccpf-dunfell\n    fi\nelse\n    cd linux-bsp-${DEVICE}\nfi\n\ngit reset --hard ; git clean -df\nif [[ \"${SDCARD_OPTION}\" == \"True\" ]]; then\n    sed -i 's/#ifdef S4_USE_SD/#define S4_USE_SD\\n&/' ./arch/arm64/boot/dts/renesas/r8a779f0-spider-cpu.dtsi\nfi\necho \"${KERNEL_CONFIG_APPEND}\" >> ./arch/arm64/configs/defconfig\nmkdir -p firmware && cd firmware\nwget https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/r8a779x_usb3_v2.dlmem\nwget https://git.kernel.org/pub/scm/linux/kernel/git/firmware/linux-firmware.git/plain/r8a779x_usb3_v3.dlmem\ncd ../\nmake ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- defconfig Image dtbs -j$(grep -c processor /proc/cpuinfo)\ncp -L arch/arm64/boot/Image -t ../../../${ROOTFS}/boot\nfind ./arch/arm64/boot/ -name \"*${DEVICE}.dtb\" | xargs sudo cp \\\n    -t ../../../${ROOTFS}/boot\nmake ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- modules -j$(grep -c processor /proc/cpuinfo)\nmake ARCH=arm64 CROSS_COMPILE=aarch64-linux-gnu- \\\n    INSTALL_MOD_PATH=../../../${ROOTFS}/ modules_install\ncd ../../..\n\n#####################################################\n# Setup rootfs with chroot                          #\n#####################################################\nQEMU_BIN_PATH=$(which qemu-aarch64-static)\ncp ${QEMU_BIN_PATH} ./${ROOTFS}/${QEMU_BIN_PATH}\n# Prepare rootfs\nchroot \"${ROOTFS}\" sh -c \" \\\n    export DEBIAN_FRONTEND=noninteractive \\\n    && echo nameserver ${NAMESERVER} >/etc/resolv.conf \\\n    && apt update \\\n    && apt upgrade -y \\\n    && apt install -y apt-utils perl-modules \\\n    && apt install -y ubuntu-standard \\\n    && apt install -y vim net-tools ssh sudo tzdata rsyslog udev iputils-ping \\\n    && apt install -y unzip curl kmod iproute2 git python3-pip nano \\\n    && echo \\\"${DHCP_CONF}\\\" > /etc/systemd/network/01-${NET_DEV}.network \\\n    && useradd -m -s /bin/bash -G sudo ${USERNAME} \\\n    && echo ${USERNAME}:${USERNAME} | chpasswd \\\n    && echo \\\"${USERNAME}   ALL=(ALL) NOPASSWD:ALL\\\" >> /etc/sudoers \\\n    && echo ${HOSTNAME} > /etc/hostname \\\n    && systemctl enable systemd-networkd \\\n    && cp /usr/share/systemd/tmp.mount /etc/systemd/system/tmp.mount \\\n    && systemctl enable tmp.mount \\\n    && systemctl enable systemd-resolved \\\n    && rm /etc/resolv.conf \\\n    && ln -s /run/systemd/resolve/resolv.conf /etc/resolv.conf \\\n    && echo 127.0.0.1 localhost > /etc/hosts \\\n    && echo 127.0.1.1 ${HOSTNAME} >> /etc/hosts \\\n    && depmod -a \\`ls /lib/modules\\` \\\n    && apt clean \\\n    && exit \\\n\"\n#####################################################\n# Create SD card image                              #\n#####################################################\n# Prepare sdcard image (+1GB free space)\nBSIZE_MEGA=$(( 1000 + $(sudo du -hsm ./${ROOTFS} | head -1 | cut -f1) ))\ndd of=image.img count=0 seek=1 bs=${BSIZE_MEGA}M\nLOOP_DEV=$(sudo losetup -f)\nlosetup ${LOOP_DEV} image.img\n# MBR=msdos, GPT=gpt\nparted ${LOOP_DEV} -s mklabel msdos -s mkpart primary ext4 4096s 100%\nmkfs.ext4 ${LOOP_DEV}p1\nmount ${LOOP_DEV}p1 /mnt\ncp -rp ./${ROOTFS}/* -t /mnt\nsync\numount /mnt\nlosetup -d ${LOOP_DEV}\n\n# Prepare to release\nmv -f image.img ${SDCARD_IMAGE_NAME}\ngzip -k ${SDCARD_IMAGE_NAME}\n", "num_lines": 223}
{"repo_name": "aws-iot-fleetwise-edge", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nip link add dev vcan0  type vcan; ip link set up vcan0\nip link add dev vcan1  type vcan; ip link set up vcan1\nip link set up can0 txqueuelen 1000 type can bitrate 500000 dbitrate 5000000 fd on restart-ms 100\nip link set up can1 txqueuelen 1000 type can bitrate 500000 dbitrate 5000000 fd on restart-ms 100\n", "num_lines": 6}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/build.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\nGIT_COMMIT=${GIT_COMMIT:-$(git rev-parse --short=12 HEAD || echo \"GitNotFound\")}\nRELEASE_VERSION=${RELEASE_VERSION:-v$(date -u '+%Y%m%d.%H%M%S')}\nBUILD_TIME=${BUILD_TIME:-$(date -u '+%Y-%m-%d_%H:%M:%S')}\necho \"GIT_COMMIT:\" ${GIT_COMMIT}\necho \"RELEASE_VERSION:\" ${RELEASE_VERSION}\necho \"BUILD_TIME:\" ${BUILD_TIME}\n\nDEFAULT_ARCHS='amd64 arm64'\nDEFAULT_TARGETS='linux darwin'\nDEFAULT_WHAT='aws-k8s-tester cw-utils ec2-utils ecr-utils eks-utils etcd-utils s3-utils sts-utils'\n\nARCHS=${ARCHS:-$DEFAULT_ARCHS}\nTARGETS=${TARGETS:-$DEFAULT_TARGETS}\nWHAT=${WHAT:-$DEFAULT_WHAT}\n\necho \"\"\necho \"Usage: \\`make TARGETS='linux' WHAT='aws-k8s-tester cw-utils'\\`\"\necho \"DEFAULT_ARCHS=$DEFAULT_ARCHS\"\necho \"DEFAULT_TARGETS=$DEFAULT_TARGETS\"\necho \"DEFAULT_WHAT=$DEFAULT_WHAT\"\necho \"\"\n\nmkdir -p ./bin\n\nPACKAGE_NAME='github.com/aws/aws-k8s-tester'\nfor arch in ${ARCHS}; do\n  for os in ${TARGETS}; do\n    for bin in ${WHAT}; do\n      echo \"=== Building arch=${arch}, os=${os}, target=${bin} ===\"\n      CGO_ENABLED=0 \\\n        GOARCH=${arch} \\\n        GOOS=${os} \\\n        go build \\\n        -mod=mod -v \\\n        -ldflags \"-s -w \\\n        -X ${PACKAGE_NAME}/version.GitCommit=${GIT_COMMIT} \\\n        -X ${PACKAGE_NAME}/version.ReleaseVersion=${RELEASE_VERSION} \\\n        -X ${PACKAGE_NAME}/version.BuildTime=${BUILD_TIME}\" \\\n        -o ./bin/${bin}-${RELEASE_VERSION}-${os}-${arch} \\\n        ./cmd/${bin}\n    done\n  done\ndone\n\nWHAT=\"k8s-tester\"\nPACKAGE_NAME='github.com/aws/aws-k8s-tester/k8s-tester'\npushd ./k8s-tester/cmd/k8s-tester\nfor arch in ${ARCHS}; do\n  for os in ${TARGETS}; do\n    for bin in ${WHAT}; do\n      echo \"=== Building arch=${arch}, os=${os}, target=${bin} ===\"\n      pwd\n      CGO_ENABLED=0 \\\n        GOARCH=${arch} \\\n        GOOS=${os} \\\n        go build \\\n        -v \\\n        -ldflags \"-s -w \\\n        -X ${PACKAGE_NAME}/version.GitCommit=${GIT_COMMIT} \\\n        -X ${PACKAGE_NAME}/version.ReleaseVersion=${RELEASE_VERSION} \\\n        -X ${PACKAGE_NAME}/version.BuildTime=${BUILD_TIME}\" \\\n        -o ../../../bin/${bin}-${RELEASE_VERSION}-${os}-${arch} \\\n        .\n    done\n  done\ndone\npopd\n\necho \"\"\necho \"Success! Your shiny new binaries are ready.\"\necho \"find ./bin -type f\"\n", "num_lines": 80}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/ec2config.gen.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\nrm -f ec2config/README.md\ngo run ec2config/gen/main.go\ncat ec2config/README.md\n\ngo install -v ./cmd/ec2-utils\nec2-utils create config --path ./ec2config/default.yaml\nrm -f ./ec2config/default.ssh.sh\n", "num_lines": 16}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/eksconfig.gen.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\nrm -f eksconfig/README.md\ngo run eksconfig/gen/main.go\ncat eksconfig/README.md\n\ngo install -v ./cmd/aws-k8s-tester\naws-k8s-tester eks create config --path ./eksconfig/default.yaml\nrm -f ./eksconfig/default.kubectl.sh\nrm -f ./eksconfig/default.ssh.sh\n", "num_lines": 17}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/fmt.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\ngoimports -w ./cmd\ngofmt -s -w ./cmd\n\ngoimports -w ./client\ngofmt -s -w ./client\n\ngoimports -w ./e2e\ngofmt -s -w ./e2e\n\ngoimports -w ./ec2\ngofmt -s -w ./ec2\n\ngoimports -w ./ec2config\ngofmt -s -w ./ec2config\n\ngoimports -w ./eks\ngofmt -s -w ./eks\n\ngoimports -w ./eksconfig\ngofmt -s -w ./eksconfig\n\ngoimports -w ./k8s-tester\ngofmt -s -w ./k8s-tester\n\ngoimports -w ./pkg\ngofmt -s -w ./pkg\n\ngoimports -w ./ssh\ngofmt -s -w ./ssh\n\ngoimports -w ./utils\ngofmt -s -w ./utils\n\ngoimports -w ./version\ngofmt -s -w ./version\n", "num_lines": 44}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/install.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\ngo install -v ./cmd/...\n", "num_lines": 10}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ hack/unit.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\nmake clean\n\necho \"Running fmt tests...\"\nIGNORE_PKGS=\"(vendor)\"\nFORMATTABLE=$(find . -name \\*.go | while read -r a; do echo \"$(dirname \"$a\")/*.go\"; done | sort | uniq | grep -vE \"$IGNORE_PKGS\" | sed \"s|\\./||g\")\nFMT=($FORMATTABLE)\n\nfunction gofmt_pass {\n\tfmtRes=$(gofmt -l -s -d \"${FMT[@]}\")\n\tif [ -n \"${fmtRes}\" ]; then\n\t\techo -e \"gofmt checking failed:\\\\n${fmtRes}\"\n\t\texit 255\n\tfi\n}\n\nfunction govet_pass {\n\tvetRes=$(go vet ./...)\n\tif [ -n \"${vetRes}\" ]; then\n\t\techo -e \"govet checking failed:\\\\n${vetRes}\"\n\t\texit 255\n\tfi\n}\n\ngofmt_pass\ngovet_pass\n\necho \"Running unit tests...\"\ngo test -v ./eksconfig/...\ngo test -v -race ./eksconfig/...\ngo test -v ./ec2config/...\ngo test -v -race ./ec2config/...\n", "num_lines": 40}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\nGO111MODULE=on go mod init\nCOMMENT\n\nif ! [[ \"$0\" =~ hack/updatedep.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\nGO111MODULE=on go mod tidy -v\nGO111MODULE=on go mod vendor -v\n", "num_lines": 15}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n# in case IDE/gopls doesn't work\n\ngoimports -w .\ngofmt -s -w .\n\ngoimports -w ./aqua\ngofmt -s -w ./aqua\n\ngoimports -w ./armory\ngofmt -s -w ./armory\n\ngoimports -w ./cloudwatch-agent\ngofmt -s -w ./cloudwatch-agent\n\ngoimports -w ./clusterloader\ngofmt -s -w ./clusterloader\n\ngoimports -w ./cmd/k8s-tester\ngofmt -s -w ./cmd/k8s-tester\n\ngoimports -w ./cmd/readme-gen\ngofmt -s -w ./cmd/readme-gen\n\ngoimports -w ./cni\ngofmt -s -w ./cni\n\ngoimports -w ./configmaps\ngofmt -s -w ./configmaps\n\ngoimports -w ./conformance\ngofmt -s -w ./conformance\n\ngoimports -w ./csi-efs\ngofmt -s -w ./csi-efs\n\ngoimports -w ./csi-ebs\ngofmt -s -w ./csi-ebs\n\ngoimports -w ./csrs\ngofmt -s -w ./csrs\n\ngoimports -w ./falco\ngofmt -s -w ./falco\n\ngoimports -w ./falcon\ngofmt -s -w ./falcon\n\ngoimports -w ./fluent-bit\ngofmt -s -w ./fluent-bit\n\ngoimports -w ./helm\ngofmt -s -w ./helm\n\ngoimports -w ./jobs-echo\ngofmt -s -w ./jobs-echo\n\ngoimports -w ./jobs-pi\ngofmt -s -w ./jobs-pi\n\ngoimports -w ./kubernetes-dashboard\ngofmt -s -w ./kubernetes-dashboard\n\ngoimports -w ./metrics-server\ngofmt -s -w ./metrics-server\n\ngoimports -w ./nlb-guestbook\ngofmt -s -w ./nlb-guestbook\n\ngoimports -w ./nlb-hello-world\ngofmt -s -w ./nlb-hello-world\n\ngoimports -w ./php-apache\ngofmt -s -w ./php-apache\n\ngoimports -w ./secrets\ngofmt -s -w ./secrets\n\ngoimports -w ./splunk\ngofmt -s -w ./splunk\n\ngoimports -w ./stress\ngofmt -s -w ./stress\n\ngoimports -w ./sysdig\ngofmt -s -w ./sysdig\n\ngoimports -w ./tester\ngofmt -s -w ./tester\n\ngoimports -w ./vault\ngofmt -s -w ./vault\n\ngoimports -w ./tester\ngofmt -s -w ./tester\n\ngoimports -w ./wordpress\ngofmt -s -w ./wordpress\n", "num_lines": 101}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ gen.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\npushd cmd/readme-gen\ngo run ./main.go\npopd\n", "num_lines": 12}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! [[ \"$0\" =~ instance-types.gen.sh ]]; then\n  echo \"must be run from repository root\"\n  exit 255\nfi\n\ngo run ./instance-types\n", "num_lines": 10}
{"repo_name": "aws-k8s-tester", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v\n", "num_lines": 11}
{"repo_name": "aws-lambda-dotnet", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is used to locate 2 files in the /var/task folder, where the end-user assembly is located\n# The 2 files are <assembly name>.deps.json and <assembly name>.runtimeconfig.json\n# These files are used to add the end-user assembly into context and make the code reachable to the dotnet process\n# Since the file names are not known in advance, we use this shell script to find the files and pass them to the dotnet process as parameters\n# You can improve cold-start performance by setting the LAMBDA_DOTNET_MAIN_ASSEMBLY environment variable and specifying the assembly name\n# LAMBDA_TASK_ROOT is inherited from the Lambda execution environment/base image as \"/var/task\", but can be overridden for use in custom images.\nif [ -z \"${LAMBDA_TASK_ROOT}\" ]; then\n  echo \"Error: Environment variable LAMBDA_TASK_ROOT needs to be defined in order for the Lambda Runtime to load the function handler to be executed.\" 1>&2\n  exit 101\nfi\n\nif [ ! -d \"${LAMBDA_TASK_ROOT}\" ] | [ -z \"$(ls -A ${LAMBDA_TASK_ROOT})\" ]; then\n  echo \"Error: .NET binaries for Lambda function are not correctly installed in the ${LAMBDA_TASK_ROOT} directory of the image when the image was built. The ${LAMBDA_TASK_ROOT} directory is missing.\" 1>&2\n  exit 102\nfi\n\n# Get version of Lambda .NET runtime if available\nexport \"$(grep LAMBDA_RUNTIME_NAME /var/runtime/runtime-release 2>/dev/null || echo LAMBDA_RUNTIME_NAME=dotnet_custom)\"\nexport AWS_EXECUTION_ENV=\"AWS_Lambda_${LAMBDA_RUNTIME_NAME}\"\n\nexport DOTNET_ROOT=\"/var/lang/bin\"\nDOTNET_BIN=\"${DOTNET_ROOT}/dotnet\"\nDOTNET_EXEC=\"exec\"\nDOTNET_ARGS=()\nEXECUTABLE_BINARY_EXIST=false\n\nLAMBDA_HANDLER=\"\"\n# Command-line parameter has precedence over \"_HANDLER\" environment variable\nif [ -n \"${1}\" ]; then\n  LAMBDA_HANDLER=\"${1}\"\nelif [ -n \"${_HANDLER}\" ]; then\n  LAMBDA_HANDLER=\"${_HANDLER}\"\nelse\n  echo \"Error: No Lambda Handler function was specified.\" 1>&2\n  exit 103\nfi\n\nHANDLER_COL_INDEX=$(expr index \"${LAMBDA_HANDLER}\" \":\")\n\nif [[ \"${HANDLER_COL_INDEX}\" == 0 ]]; then \n  EXECUTABLE_ASSEMBLY=\"${LAMBDA_TASK_ROOT}/${LAMBDA_HANDLER}\"\n  EXECUTABLE_BINARY=\"${LAMBDA_TASK_ROOT}/${LAMBDA_HANDLER}\"\n  if [[ \"${EXECUTABLE_ASSEMBLY}\" != *.dll ]]; then\n    EXECUTABLE_ASSEMBLY=\"${EXECUTABLE_ASSEMBLY}.dll\"\n  fi\n  if [[ -f \"${EXECUTABLE_ASSEMBLY}\" ]]; then\n    DOTNET_ARGS+=(\"${EXECUTABLE_ASSEMBLY}\")\n  elif [[ -f \"${EXECUTABLE_BINARY}\" ]]; then\n    EXECUTABLE_BINARY_EXIST=true\n  else\n    echo \"Error: executable assembly ${EXECUTABLE_ASSEMBLY} or binary ${EXECUTABLE_BINARY} not found.\" 1>&2\n    exit 104\n  fi\nelse\n  if [ -n \"${LAMBDA_DOTNET_MAIN_ASSEMBLY}\" ]; then\n    if [[ \"${LAMBDA_DOTNET_MAIN_ASSEMBLY}\" == *.dll ]]; then\n      ASSEMBLY_NAME=\"${LAMBDA_DOTNET_MAIN_ASSEMBLY::-4}\"\n    else\n      ASSEMBLY_NAME=\"${LAMBDA_DOTNET_MAIN_ASSEMBLY}\"\n    fi\n  else\n    ASSEMBLY_NAME=\"${LAMBDA_HANDLER::${HANDLER_COL_INDEX}-1}\"\n  fi\n\n  DEPS_FILE=\"${LAMBDA_TASK_ROOT}/${ASSEMBLY_NAME}.deps.json\"\n  if ! [ -f \"${DEPS_FILE}\" ]; then\n    DEPS_FILES=( \"${LAMBDA_TASK_ROOT}\"/*.deps.json )\n\n    # Check if there were any matches to the *.deps.json glob, and that the glob was resolved\n    # This makes the matching independent from the global `nullopt` shopt's value (https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html)\n    if [ \"${#DEPS_FILES[@]}\" -ne 1 ] || echo \"${DEPS_FILES[0]}\" | grep -q -F '*'; then\n      echo \"Error: .NET binaries for Lambda function are not correctly installed in the ${LAMBDA_TASK_ROOT} directory of the image when the image was built. The ${LAMBDA_TASK_ROOT} directory is missing the required .deps.json file.\" 1>&2\n      exit 105\n    fi\n    DEPS_FILE=\"${DEPS_FILES[0]}\"\n  fi\n\n  RUNTIMECONFIG_FILE=\"${LAMBDA_TASK_ROOT}/${ASSEMBLY_NAME}.runtimeconfig.json\"\n  if ! [ -f \"${RUNTIMECONFIG_FILE}\" ]; then\n    RUNTIMECONFIG_FILES=( \"${LAMBDA_TASK_ROOT}\"/*.runtimeconfig.json )\n\n    # Check if there were any matches to the *.runtimeconfig.json glob, and that the glob was resolved\n    # This makes the matching independent from the global `nullopt` shopt's value (https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html)\n    if [ \"${#RUNTIMECONFIG_FILES[@]}\" -ne 1 ] || echo \"${RUNTIMECONFIG_FILES[0]}\" | grep -q -F '*'; then\n      echo \"Error: .NET binaries for Lambda function are not correctly installed in the ${LAMBDA_TASK_ROOT} directory of the image when the image was built. The ${LAMBDA_TASK_ROOT} directory is missing the required .runtimeconfig.json file.\" 1>&2\n      exit 106\n    fi\n    RUNTIMECONFIG_FILE=\"${RUNTIMECONFIG_FILES[0]}\"\n  fi\n\n  DOTNET_ARGS+=(\"--depsfile\" \"${DEPS_FILE}\"\n                \"--runtimeconfig\" \"${RUNTIMECONFIG_FILE}\"\n                \"/var/runtime/Amazon.Lambda.RuntimeSupport.dll\" \"${LAMBDA_HANDLER}\")\nfi\n\n\n# To support runtime wrapper scripts\n# https://docs.aws.amazon.com/lambda/latest/dg/runtimes-modify.html#runtime-wrapper\nif [ -z \"${AWS_LAMBDA_EXEC_WRAPPER}\" ]; then\n  if [ ${EXECUTABLE_BINARY_EXIST} = true ]; then\n    exec \"${EXECUTABLE_BINARY}\"\n  else\n    exec \"${DOTNET_BIN}\" \"${DOTNET_EXEC}\" \"${DOTNET_ARGS[@]}\"\n  fi\nelse\n  if [ ! -f \"${AWS_LAMBDA_EXEC_WRAPPER}\" ]; then\n    echo \"${AWS_LAMBDA_EXEC_WRAPPER}: does not exist\"\n    exit 127\n  fi\n  if [ ! -x \"${AWS_LAMBDA_EXEC_WRAPPER}\" ]; then\n    echo \"${AWS_LAMBDA_EXEC_WRAPPER}: is not an executable\"\n    exit 126\n  fi\n  if [ ${EXECUTABLE_BINARY_EXIST} = true ]; then\n    exec -- \"${AWS_LAMBDA_EXEC_WRAPPER}\" \"${EXECUTABLE_BINARY}\"\n  else\n    exec -- \"${AWS_LAMBDA_EXEC_WRAPPER}\" \"${DOTNET_BIN}\" \"${DOTNET_EXEC}\" \"${DOTNET_ARGS[@]}\"\n  fi\nfi", "num_lines": 121}
{"repo_name": "aws-lambda-go", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\necho \"\\\"$(od -N $((512 * 1024)) /dev/random | base64)\\\"\" > data.json\necho \"data payload for tests is: $(du -h data.json)\"\n\ntrap \"docker kill rie-bench\" 1 2 3 6\nbench () {\n    local handler_exe=$1\n    local entrypoint=$2\n    local image=$3\n    echo \"-------------------------------------------------\"\n    echo $@\n    echo \"-------------------------------------------------\"\n    docker run --name rie-bench --rm -d -p 9001:8080 -v \"${handler_exe}:/var/task/bootstrap\" --entrypoint aws-lambda-rie ${image} ${entrypoint} bootstrap\n    sleep 2\n    echo \"ensuring healthy function before starting test\"\n    curl -s -XPOST http://localhost:9001/2015-03-31/functions/function/invocations -d '{\"hello\": \"world\"}' | jq\n    echo \"-------------------------------------------------\"\n    ab -p data.json -n 100 http://localhost:9001/2015-03-31/functions/function/invocations\n    docker kill rie-bench\n}\n\nGOOS=linux GOARCH=amd64 go build                    -o handler       echo_handler.go\nGOOS=linux GOARCH=amd64 go build -tags lambda.norpc -o handler_norpc echo_handler.go\nls -lah handler*\n\nbench \"$(pwd)/handler_norpc\" /var/task/bootstrap    public.ecr.aws/lambda/provided:alami \nbench \"$(pwd)/handler_norpc\" /var/runtime/bootstrap public.ecr.aws/lambda/go             \nbench \"$(pwd)/handler\"       /var/runtime/bootstrap public.ecr.aws/lambda/go             \n", "num_lines": 32}
{"repo_name": "aws-lambda-go", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nurl_id=\"${1}\" # should be the lambda function url domain prefix for an echo function\nregion=${AWS_REGION:-us-west-2}\nurl=\"https://${url_id}.lambda-url.${region}.on.aws\"\naccount_id=$(aws sts get-caller-identity --output text --query \"Account\")\n\nredact () {\n    #https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-unique-ids \n    sed \"s/${url_id}/lambda-url-id/g\" \\\n    | sed 's/A[A-Z][A-Z]A[A-Z1-9]*\\([\":]\\)/iam-unique-id\\1/g' \\\n    | sed \"s/${account_id}/aws-account-id/g\" \\\n    | jq '.headers |= (.[\"x-amz-security-token\"] = \"security-token\" )' \\\n    | jq '.headers |= (.[\"x-forwarded-for\"] = \"127.0.0.1\")' \\\n    | jq '.requestContext.authorizer |= (.[\"iam\"] = {})' \\\n    | jq '.requestContext.http |= (.[\"sourceIp\"] = \"127.0.0.1\")'\n}\n\nawscurl --service lambda --region $region \\\n    -X POST \\\n    -H 'Header1: h1' \\\n    -H 'Header2: h1,h2' \\\n    -H 'Header3: h3' \\\n    -H 'Cookie: foo=bar; hello=hello' \\\n    -H 'Content-Type: application/json' \\\n    -d '{\"hello\": \"world\"}' \\\n    \"$url/hello?hello=world&foo=bar\" \\\n    | redact \\\n    | tee function-url-request-with-headers-and-cookies-and-text-body.json \\\n    | jq\n\nawscurl --service lambda --region $region \\\n    -X POST \\\n    -d '<idk/>' \\\n    \"$url\" \\\n    | redact \\\n    | tee function-url-domain-only-request-with-base64-encoded-body.json \\\n    | jq\n\nawscurl --service lambda --region $region \\\n    -X GET \\\n    \"$url\" \\\n    | redact \\\n    | tee function-url-domain-only-get-request.json \\\n    | jq\n\nawscurl --service lambda --region $region \\\n    -X GET \\\n    \"$url/\" \\\n    | redact \\\n    | tee function-url-domain-only-get-request-trailing-slash.json \\\n    | jq\n\n", "num_lines": 55}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nprojectVersion=$(mvn help:evaluate -Dexpression=project.version -q -DforceStdout)\nif [[ -z ${ENABLE_SNAPSHOT} ]]; then\n  echo \"Skipping SNAPSHOT deployment, as ENABLE_SNAPSHOT environment variable is not defined\"\n  exit\nfi\n\necho \"Deploying SNAPSHOT artifact\"\nif [[ ${projectVersion} != *\"SNAPSHOT\"* ]]; then\n    snapshotProjectVersion=\"${projectVersion}-SNAPSHOT\"\n    echo \"projectVersion: ${projectVersion}\"\n    echo \"snapshotProjectVersion: ${snapshotProjectVersion}\"\n    mvn versions:set \"-DnewVersion=${snapshotProjectVersion}\"\nelse\n    echo \"Already -SNAPSHOT version\"\nfi\n\nmvn -P ci-repo deploy --settings ric-dev-environment/settings.xml\nmv pom.xml.versionsBackup pom.xml\n", "num_lines": 23}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nSRC_DIR=$(dirname \"$0\")\nDST_DIR=${1}\nMULTI_ARCH=${2}\nCURL_VERSION=7.83.1\n\n# Not using associative arrays to maintain bash 3 compatibility with building on MacOS\n# MacOS ships with bash 3 and associative arrays require bash 4+\n# Declaring a map as an array with the column character as a separator :\ndeclare -a ARCHITECTURES_TO_PLATFORM=(\n    \"x86_64:linux/amd64\"\n    \"aarch64:linux/arm64/v8\"\n)\n\ndeclare -a TARGETS=(\"glibc\" \"musl\")\n\nfor pair in \"${ARCHITECTURES_TO_PLATFORM[@]}\"; do\n    arch=${pair%%:*}\n    platform=${pair#*:}\n\n    if [[ \"${MULTI_ARCH}\" != \"true\" ]] && [[ \"$(arch)\" != \"${arch}\" ]]; then\n        echo \"multi arch build not requested and host arch is $(arch), so skipping ${arch}:${platform} ...\"\n        continue\n    fi\n\n    mkdir -p \"${DST_DIR}/classes/${arch}\"\n\n    for target in \"${TARGETS[@]}\"; do\n        echo \"Compiling the native library for target ${target} on architecture ${arch} using Docker platform ${platform}\"\n        artifact=\"${DST_DIR}/classes/${arch}/aws-lambda-runtime-interface-client.${target}.so\"\n\n        if [[ \"${MULTI_ARCH}\" == \"true\" ]]; then\n            docker build --platform=\"${platform}\" -f \"${SRC_DIR}/Dockerfile.${target}\" --build-arg CURL_VERSION=${CURL_VERSION} \"${SRC_DIR}\" -o - | tar -xOf - src/aws-lambda-runtime-interface-client.so > \"${artifact}\"\n        else\n            echo \"multi-arch not requestsed, assuming this is a workaround to goofyness when docker buildx is enabled on Linux CI environments.\"\n            echo \"enabling docker buildx often updates the docker api version, so assuming that docker cli is also too old to use --output type=tar, so doing alternative build-tag-run approach\"\n            docker build --platform=\"${platform}\" -t \"lambda-java-jni-lib-${target}-${arch}\" -f \"${SRC_DIR}/Dockerfile.${target}\" --build-arg CURL_VERSION=${CURL_VERSION} \"${SRC_DIR}\"\n            docker run --rm --entrypoint /bin/cat \"lambda-java-jni-lib-${target}-${arch}\" /src/aws-lambda-runtime-interface-client.so > \"${artifact}\"\n        fi\n\n        [ -f \"${artifact}\" ]\n        if ! file -b \"${artifact}\" | tr '-' '_' | tee /dev/stderr | grep -q \"${arch}\"; then\n            echo \"${artifact} did not appear to be the correct architecture, check that Docker buildx is enabled\"\n            exit 1\n        fi\n    done\ndone\n", "num_lines": 52}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\n# build the AWS C++ SDK\ncd /aws-sdk-cpp\ngit pull\nmkdir build\ncd build\ncmake .. -GNinja -DBUILD_ONLY=\"lambda\" \\\n    -DCMAKE_BUILD_TYPE=Release \\\n    -DENABLE_UNITY_BUILD=ON \\\n    -DBUILD_SHARED_LIBS=ON \\\n    -DENABLE_TESTING=OFF \\\n    -DCMAKE_INSTALL_PREFIX=/install $@\nninja\nninja install\n", "num_lines": 18}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\n# build the lambda-runtime\ncd $CODEBUILD_SRC_DIR\nmkdir build\ncd build\ncmake .. -GNinja -DBUILD_SHARED_LIBS=ON -DCMAKE_BUILD_TYPE=Debug -DCMAKE_INSTALL_PREFIX=/install $@\nninja\nninja install\n", "num_lines": 12}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nCLANG_FORMAT=clang-format\n\nif NOT type $CLANG_FORMAT > /dev/null 2>&1; then\n    echo \"No appropriate clang-format found.\"\n    exit 1\nfi\n\nFAIL=0\nSOURCE_FILES=$(find src include tests -type f -name \"*.h\" -o -name \"*.cpp\")\nfor i in $SOURCE_FILES\ndo\n    if [ $($CLANG_FORMAT -output-replacements-xml $i | grep -c \"<replacement \") -ne 0 ]\n    then\n        echo \"$i failed clang-format check.\"\n        FAIL=1\n    fi\ndone\n\nexit $FAIL\n\n", "num_lines": 25}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\ncd $CODEBUILD_SRC_DIR\ncd build\nrm -rf *.zip\nninja $1\naws s3 cp tests/resources/lambda-test-fun.zip s3://aws-lambda-cpp-tests/$2lambda-test-fun.zip\nctest --output-on-failure\n\n", "num_lines": 12}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\necho \"Cleaning up...\"\ndocker stop \"${OS_DISTRIBUTION}-app\" || true\ndocker rm --force \"${OS_DISTRIBUTION}-app\" || true\ndocker stop \"${OS_DISTRIBUTION}-tester\" || true\ndocker rm --force \"${OS_DISTRIBUTION}-tester\" || true\ndocker network rm \"${OS_DISTRIBUTION}-network\" || true\n", "num_lines": 12}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\necho \"Setting up multi-arch build environment\"\nARCHITECTURE=$(arch)\nif [[ \"$ARCHITECTURE\" == \"x86_64\" ]]; then\n\tTARGET_EMULATOR=\"arm64\"\nelif [[ \"$ARCHITECTURE\" == \"aarch64\" ]]; then\n\tTARGET_EMULATOR=\"amd64\"\nelse\n\techo \"Architecture $ARCHITECTURE is not currently supported.\"\n\texit 1\nfi\n\necho \"Installing ${TARGET_EMULATOR} emulator\"\ndocker pull public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v6.1.0\ndocker run --rm --privileged public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v6.1.0 --install ${TARGET_EMULATOR}\necho \"Setting docker build command to default to buildx\"\necho \"Docker buildx version: $(docker buildx version)\"\ndocker buildx install\n", "num_lines": 23}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\necho \"---------Container Logs: ${OS_DISTRIBUTION}-app----------\"\necho\ndocker logs \"${OS_DISTRIBUTION}-app\" || true\necho\necho \"---------------------------------------------------\"\necho \"--------Container Logs: ${OS_DISTRIBUTION}-tester--------\"\necho\ndocker logs \"${OS_DISTRIBUTION}-tester\" || true\necho\necho \"---------------------------------------------------\"\n", "num_lines": 16}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euxo pipefail\n\necho \"Running Image ${IMAGE_TAG}\"\ndocker network create \"${OS_DISTRIBUTION}-network\"\n\nfunction_jar=\"./HelloWorld-1.0.jar\"\nfunction_handler=\"helloworld.App\"\ndocker run \\\n  --detach \\\n  --name \"${OS_DISTRIBUTION}-app\" \\\n  --network \"${OS_DISTRIBUTION}-network\" \\\n  --entrypoint=\"\" \\\n  --platform=\"${PLATFORM}\" \\\n  \"${IMAGE_TAG}\" \\\n  sh -c \"/usr/bin/${RIE} ${JAVA_BINARY_LOCATION} -jar ${function_jar} ${function_handler}\"\nsleep 2\n\n# running on arm64 hosts with x86_64 being emulated takes significantly more time than any other combination\nif [[ \"$(arch)\" == \"aarch64\" ]] && [[ \"${PLATFORM}\" == \"linux/amd64\" ]]; then\n  declare -i time_out=150\nelse\n  declare -i time_out=10\nfi\n\ndocker run \\\n  --name \"${OS_DISTRIBUTION}-tester\" \\\n  --env \"TARGET=${OS_DISTRIBUTION}-app\" \\\n  --env \"MAX_TIME=${time_out}\" \\\n  --network \"${OS_DISTRIBUTION}-network\" \\\n  --entrypoint=\"\" \\\n  --platform=\"${PLATFORM}\" \\\n    \"${IMAGE_TAG}\" \\\n  sh -c 'curl -X POST \"http://${TARGET}:8080/2015-03-31/functions/function/invocations\" -d \"{}\" --max-time ${MAX_TIME}'\nactual=\"$(docker logs --tail 1 \"${OS_DISTRIBUTION}-tester\" | xargs)\"\nexpected='success'\necho \"Response: ${actual}\"\nif [[ \"${actual}\" != \"${expected}\" ]]; then\n  echo \"fail! runtime: ${RUNTIME} - expected output ${expected} - got ${actual}\"\n  exit 1\nfi\n", "num_lines": 44}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is copied from https://github.com/aws/aws-codebuild-docker-images/blob/282c6634e8c83c2a9841719b09aabfced3461981/local_builds/codebuild_build.sh\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -r        Used to specify a report output directory.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:r:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        r  ) report_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -n \"$report_dir\" ]\nthen\n    docker_command+=\" -e \\\"REPORTS=$(allOSRealPath \"$report_dir\")\\\"\"\nfi\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" $local_agent_image\"\nelse\n    docker_command+=\" public.ecr.aws/codebuild/local-builds:latest\"\nfi\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 207}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\nDRYRUN=\"${DRYRUN-0}\"\n\nfunction usage {\n    echo \"usage: test_all.sh buildspec_yml_dir\"\n    echo \"Runs all buildspec build-matrix combinations via test_one.sh.\"\n    echo \"Required:\"\n    echo \"  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file.\"\n}\n\ndo_one_yaml() {\n    local -r YML=\"$1\"\n\n    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\\s*(\\S+)' \"$YML\" | cut -d' ' -f2)\n    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' \"$YML\" | tr -d '\\-\" ')\n    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/PLATFORM/,$d' \"$YML\" | sed '/#.*$/d' |  tr -d '\\-\" ')\n    PLATFORMS=$(sed '1,/PLATFORM/d;/phases/,$d' \"$YML\" |  tr -d '\\-\" ')\n\n    for DISTRO_VERSION in $DISTRO_VERSIONS; do\n      for RUNTIME_VERSION in $RUNTIME_VERSIONS; do\n        for PLATFORM in $PLATFORMS; do\n          if (( DRYRUN == 1 )); then\n            echo DRYRUN test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \"$PLATFORM\"\n          else\n            test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \"$PLATFORM\"\n          fi\n        done\n      done\n    done\n}\n\ntest_one_combination() {\n    local -r YML=\"$1\"\n    local -r OS_DISTRIBUTION=\"$2\"\n    local -r DISTRO_VERSION=\"$3\"\n    local -r RUNTIME_VERSION=\"$4\"\n    local -r PLATFORM=\"$5\"\n    local -r PLATFORM_SANITIZED=$(echo \"$PLATFORM\" | tr \"/\" \".\")\n\n    echo Testing:\n    echo \"  BUILDSPEC\" \"$YML\"\n    echo \"  with\" \"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \"$PLATFORM\"\n\n    \"$(dirname \"$0\")\"/test_one.sh \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \"$PLATFORM\" \\\n        > >(sed \"s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION-$PLATFORM_SANITIZED: /\") 2> >(sed \"s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION:$PLATFORM_SANITIZED: /\" >&2)\n}\n\nmain() {\n    if (( $# != 1 && $# != 2)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n    BUILDSPEC_YML_DIR=\"$1\"\n    HAS_YML=0\n    for f in \"$BUILDSPEC_YML_DIR\"/*.yml ; do\n        [ -f \"$f\" ] || continue;\n        do_one_yaml \"$f\"\n        HAS_YML=1\n    done\n\n    if (( HAS_YML == 0 )); then\n        >&2 echo At least one buildspec is required.\n        exit 2\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 74}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\n\nfunction usage {\n    >&2 echo \"usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]\"\n    >&2 echo \"Runs one buildspec version combination from a build-matrix buildspec.\"\n    >&2 echo \"Required:\"\n    >&2 echo \"  buildspec_yml          Used to specify the CodeBuild buildspec template file.\"\n    >&2 echo \"  os_distribution        Used to specify the OS distribution to build.\"\n    >&2 echo \"  distro_version         Used to specify the distro version of <os_distribution>.\"\n    >&2 echo \"  runtime_version        Used to specify the runtime version to test on the selected <distro_version>.\"\n    >&2 echo \"  platform               Used to specify the architecture platform to test on the selected <distro_version>.\"\n    >&2 echo \"Optional:\"\n    >&2 echo \"  env                    Additional environment variables file.\"\n}\n\n# codebuild/local-builds images are not multi-architectural\nfunction get_local_agent_image() {\n    if [[ \"$(arch)\" == \"aarch64\" ]]; then\n        echo \"public.ecr.aws/codebuild/local-builds:aarch64\"\n    else\n        echo \"public.ecr.aws/codebuild/local-builds:latest\"\n    fi\n}\n\nmain() {\n    if (( $# != 5 && $# != 6)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML=\"$1\"\n    OS_DISTRIBUTION=\"$2\"\n    DISTRO_VERSION=\"$3\"\n    RUNTIME_VERSION=\"$4\"\n    PLATFORM=\"$5\"\n    PLATFORM_SANITIZED=$(echo \"$PLATFORM\" | tr \"/\" \".\")\n    EXTRA_ENV=\"${6-}\"\n\n    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild.\"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\"-\"$RUNTIME_VERSION\"-\"$PLATFORM_SANITIZED\".XXXXXXXXXX)\n    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT\n\n    # Create an env file for codebuild_build.\n    ENVFILE=\"$CODEBUILD_TEMP_DIR/.env\"\n    if [ -f \"$EXTRA_ENV\" ]; then\n        cat \"$EXTRA_ENV\" > \"$ENVFILE\"\n    fi\n    {\n        echo \"\"\n        echo \"OS_DISTRIBUTION=$OS_DISTRIBUTION\"\n        echo \"DISTRO_VERSION=$DISTRO_VERSION\"\n        echo \"RUNTIME_VERSION=$RUNTIME_VERSION\"\n        echo \"PLATFORM=$PLATFORM\"\n    }  >> \"$ENVFILE\"\n\n    ARTIFACTS_DIR=\"$CODEBUILD_TEMP_DIR/artifacts\"\n    mkdir -p \"$ARTIFACTS_DIR\"\n    # Run CodeBuild local agent.\n    \"$(dirname \"$0\")\"/codebuild_build.sh \\\n        -i \"$CODEBUILD_IMAGE_TAG\" \\\n        -a \"$ARTIFACTS_DIR\" \\\n        -e \"$ENVFILE\" \\\n        -b \"$BUILDSPEC_YML\" \\\n        -s \"$(dirname $PWD)\" \\\n        -l \"$(get_local_agent_image)\"\n}\n\nmain \"$@\"\n", "num_lines": 74}
{"repo_name": "aws-lambda-java-libs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n# This script runs after the aws-lambda-java-serialization package phase. It verifies that no unexpected transitive\n# dependencies were missed from the relocation of third party classes.\n\nset -euo pipefail\n\nARTIFACT_PATH=${1}\nRELOCATION_PREFIX=${2}\nSERIALIZATION_MODULE_PATTERN=${3}\n\necho 'Validating that serialization module classes were not relocated'\nOUTPUT=$(zipinfo ${ARTIFACT_PATH} | grep '.class' | grep ${RELOCATION_PREFIX//.//} | grep ${SERIALIZATION_MODULE_PATTERN//.//} || true)\nif [[ ! -z \"$OUTPUT\" ]]; then\n    echo \"Serialization module classes were unexpectedly relocated\"\n    echo ${OUTPUT}\n    exit 1\nfi\n\necho 'Validating that everything other than serialization module classes were relocated'\nOUTPUT=$(zipinfo ${ARTIFACT_PATH} | grep '.class' | grep -v ${SERIALIZATION_MODULE_PATTERN//.//} | grep -v 'META-INF' | grep -v ${RELOCATION_PREFIX//.//} || true)\nif [[ ! -z \"$OUTPUT\" ]]; then\n    echo \"Some classes were not relocated\"\n    echo ${OUTPUT}\n    exit 1\nfi\n\necho 'Validating that META-INF/services were relocated'\nOUTPUT=$(zipinfo ${ARTIFACT_PATH} | grep 'META-INF/services/.\\+' | grep -v ${RELOCATION_PREFIX} || true)\nif [[ ! -z \"$OUTPUT\" ]]; then\n    echo \"Some meta-inf services were not relocated\"\n    echo ${OUTPUT}\n    exit 1\nfi\n", "num_lines": 36}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nset -e\n\nif [ \"$(uname)\" = \"Darwin\" ]; then\n    echo \"aws-lambda-cpp does not build on OS X. Skipping the postinstall step.\"\nelse\n    npm run build:gyp\n    mkdir -p dist\n    cp build/Release/rapid-client.node dist/\nfi\n\n# If the path of this file ends in \"node_modules/aws-lambda-ric/scripts\"\n# the package is being installed as a dependency and we can clean the deps folder.\nrelative_path=\"`dirname \\\"$0\\\"`\"\ncurrent_path=\"`( cd \\\"$relative_path\\\" && pwd )`\"\nnode_modules_path=\"/node_modules/aws-lambda-ric/scripts\"\n\nif test \"${current_path#*$node_modules_path}\" != \"$current_path\" || [ \"$BUILD\" != 1 ]; then\n    echo \"Cleaning up source dependencies to save space\"\n\n    deps_path=\"$current_path/../deps\"\n    build_path=\"$current_path/../build\"\n\n    # Clean up source dependencies\n    rm -rf \"$deps_path\"/aws-lambda-cpp*[^gz]\n    rm -rf \"$deps_path\"/curl*[^gz]\n    rm -rf \"$deps_path\"/artifacts\n    rm -rf \"$build_path\"\nfi\n", "num_lines": 31}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nset -e\n\nARTIFACTS_DIR=$(pwd)/deps/artifacts\n\nif [ \"$(uname)\" = \"Darwin\" ]; then\n    echo \"aws-lambda-cpp does not build on OS X. Skipping the preinstall step.\"\nelse\n    if [ -x \"$(command -v cmake3)\" ]; then\n        CMAKE=cmake3\n    elif [ -x \"$(command -v cmake)\" ]; then\n        CMAKE=cmake\n    else\n        echo 'Error: cmake is not installed.' >&2\n        exit 1\n    fi\n\n    cd deps\n    . ./versions\n\n    # unpack dependencies\n    tar xzf ./curl-$CURL_VERSION.tar.gz --no-same-owner && \\\n    tar xzf ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz --no-same-owner\n\n    (\n        # Build Curl\n        cd curl-curl-$CURL_VERSION && \\\n            ./buildconf && \\\n            ./configure \\\n                --prefix \"$ARTIFACTS_DIR\" \\\n                --disable-alt-svc \\\n                --disable-ares \\\n                --disable-cookies \\\n                --disable-crypto-auth \\\n                --disable-dateparse \\\n                --disable-dict \\\n                --disable-dnsshuffle \\\n                --disable-doh \\\n                --disable-file \\\n                --disable-ftp \\\n                --disable-get-easy-options \\\n                --disable-gopher \\\n                --disable-hsts \\\n                --disable-http-auth \\\n                --disable-imap \\\n                --disable-ipv6 \\\n                --disable-ldap \\\n                --disable-ldaps \\\n                --disable-libcurl-option \\\n                --disable-manual \\\n                --disable-mime \\\n                --disable-mqtt \\\n                --disable-netrc \\\n                --disable-ntlm-wb \\\n                --disable-pop3 \\\n                --disable-progress-meter \\\n                --disable-proxy \\\n                --disable-pthreads \\\n                --disable-rtsp \\\n                --disable-shared \\\n                --disable-smtp \\\n                --disable-socketpair \\\n                --disable-sspi \\\n                --disable-telnet \\\n                --disable-tftp \\\n                --disable-threaded-resolver \\\n                --disable-unix-sockets \\\n                --disable-verbose \\\n                --disable-versioned-symbols \\\n                --disable-websockets \\\n                --with-pic \\\n                --without-brotli \\\n                --without-ca-bundle \\\n                --without-gssapi \\\n                --without-libidn2 \\\n                --without-libpsl \\\n                --without-librtmp \\\n                --without-libssh2 \\\n                --without-nghttp2 \\\n                --without-nghttp3 \\\n                --without-ngtcp2 \\\n                --without-ssl \\\n                --without-zlib \\\n                --without-zstd && \\\n            make && \\\n            make install\n    )\n\n    (\n        # Build aws-lambda-cpp\n        mkdir -p ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build && \\\n            cd ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build\n\n        $CMAKE .. \\\n                -DCMAKE_CXX_FLAGS=\"-fPIC\" \\\n                -DCMAKE_INSTALL_PREFIX=\"$ARTIFACTS_DIR\" \\\n                -DCMAKE_MODULE_PATH=\"$ARTIFACTS_DIR\"/lib/pkgconfig && \\\n            make && make install\n    )\nfi\n", "num_lines": 102}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nset -e\n\ncd deps\n\nsource versions\n\n# clean up old files\nrm -f aws-lambda-cpp-*.tar.gz && rm -f curl-*.tar.gz\n\n# Grab Curl\nwget -c https://github.com/curl/curl/archive/refs/tags/curl-$CURL_VERSION.tar.gz -O - | tar -xz\n\n# Apply patches\n(\n  cd curl-curl-$CURL_VERSION && \\\n    patch -p1 < ../patches/0001-curl-disable_wakeup.patch\n)\n\n# Pack again and remove the folder\ntar -czvf curl-$CURL_VERSION.tar.gz curl-curl-$CURL_VERSION && \\\n  rm -rf curl-curl-$CURL_VERSION\n\n# Grab aws-lambda-cpp\nwget -c https://github.com/awslabs/aws-lambda-cpp/archive/refs/tags/v$AWS_LAMBDA_CPP_RELEASE.tar.gz -O - | tar -xz\n\n# Apply patches\n(\n  cd aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE && \\\n    patch -p1 < ../patches/aws-lambda-cpp-add-xray-response.patch\n)\n\n# Pack again and remove the folder\ntar -czvf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE --no-same-owner && \\\n  rm -rf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE\n", "num_lines": 37}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is copied from https://github.com/aws/aws-codebuild-docker-images/blob/f0912e4b16e427da35351fc102f0f56f4ceb938a/local_builds/codebuild_build.sh\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\ndocker_command+=\" amazon/aws-codebuild-local:latest\"\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 195}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\nDISTRO=\"${DISTRO:=\"\"}\"\nDRYRUN=\"${DRYRUN-0}\"\n\nfunction usage {\n    echo \"usage: test_all.sh buildspec_yml_dir\"\n    echo \"Runs all buildspec build-matrix combinations via test_one.sh.\"\n    echo \"Required:\"\n    echo \"  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file.\"\n}\n\ndo_one_yaml() {\n    local -r YML=\"$1\"\n\n    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\\s*(\\S+)' \"$YML\" | cut -d' ' -f2)\n    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' \"$YML\" | tr -d '\\-\" ')\n    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/phases/,$d' \"$YML\" | sed '/#.*$/d' |  tr -d '\\-\" ')\n\n    for DISTRO_VERSION in $DISTRO_VERSIONS ; do\n        for RUNTIME_VERSION in $RUNTIME_VERSIONS ; do\n            if (( DRYRUN == 1 )) ; then\n                echo DRYRUN test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            else\n                test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            fi\n        done\n    done\n}\n\ntest_one_combination() {\n    local -r YML=\"$1\"\n    local -r OS_DISTRIBUTION=\"$2\"\n    local -r DISTRO_VERSION=\"$3\"\n    local -r RUNTIME_VERSION=\"$4\"\n  \n    echo Testing:\n    echo \"  BUILDSPEC\" \"$YML\"\n    echo \"  with\" \"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n\n    \"$(dirname \"$0\")\"/test_one.sh \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \\\n        > >(sed \"s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION: /\") 2> >(sed \"s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION: /\" >&2)\n}\n\nmain() {\n    if (( $# != 1 && $# != 2)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML_DIR=\"$1\"\n    HAS_YML=0\n    for f in \"$BUILDSPEC_YML_DIR\"/*\"$DISTRO\"*.yml ; do\n        [ -f \"$f\" ] || continue;\n        do_one_yaml \"$f\"\n        HAS_YML=1\n    done\n\n    if (( HAS_YML == 0 )); then\n        >&2 echo At least one buildspec is required.\n        exit 2\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 71}
{"repo_name": "aws-lambda-nodejs-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\n\nfunction usage {\n    >&2 echo \"usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]\"\n    >&2 echo \"Runs one buildspec version combination from a build-matrix buildspec.\"\n    >&2 echo \"Required:\"\n    >&2 echo \"  buildspec_yml          Used to specify the CodeBuild buildspec template file.\"\n    >&2 echo \"  os_distribution        Used to specify the OS distribution to build.\"\n    >&2 echo \"  distro_version         Used to specify the distro version of <os_distribution>.\"\n    >&2 echo \"  runtime_version        Used to specify the runtime version to test on the selected <distro_version>.\"\n    >&2 echo \"Optional:\"\n    >&2 echo \"  env                    Additional environment variables file.\"\n}\n\nmain() {\n    if (( $# != 3 && $# != 4)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML=\"$1\"\n    OS_DISTRIBUTION=\"$2\"\n    DISTRO_VERSION=\"$3\"\n    RUNTIME_VERSION=\"$4\"\n    EXTRA_ENV=\"${5-}\"\n\n    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild.\"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\"-\"$RUNTIME_VERSION\".XXXXXXXXXX)\n    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT\n\n    # Create an env file for codebuild_build.\n    ENVFILE=\"$CODEBUILD_TEMP_DIR/.env\"\n    if [ -f \"$EXTRA_ENV\" ]; then\n        cat \"$EXTRA_ENV\" > \"$ENVFILE\"\n    fi\n    {\n        echo \"\"\n        echo \"OS_DISTRIBUTION=$OS_DISTRIBUTION\"\n        echo \"DISTRO_VERSION=$DISTRO_VERSION\"\n        echo \"RUNTIME_VERSION=$RUNTIME_VERSION\"\n    }  >> \"$ENVFILE\"\n    \n    ARTIFACTS_DIR=\"$CODEBUILD_TEMP_DIR/artifacts\"\n    mkdir -p \"$ARTIFACTS_DIR\"\n\n    # Run CodeBuild local agent.\n    \"$(dirname \"$0\")\"/codebuild_build.sh \\\n        -i \"$CODEBUILD_IMAGE_TAG\" \\\n        -a \"$ARTIFACTS_DIR\" \\\n        -e \"$ENVFILE\" \\\n        -b \"$BUILDSPEC_YML\"\n}\n\nmain \"$@\"\n", "num_lines": 60}
{"repo_name": "aws-lambda-python-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nset -e\n\nARTIFACTS_DIR=$(pwd)/deps/artifacts\n\nif [ \"$(uname)\" = \"Darwin\" ]; then\n    echo \"aws-lambda-cpp does not build on OS X. Skipping the preinstall step.\"\nelse\n    if [ -x \"$(command -v cmake3)\" ]; then\n        CMAKE=cmake3\n    elif [ -x \"$(command -v cmake)\" ]; then\n        CMAKE=cmake\n    else\n        echo 'Error: cmake is not installed.' >&2\n        exit 1\n    fi\n\n    cd deps\n    . ./versions\n\n    CURL_VERSION=\"${CURL_MAJOR_VERSION}.${CURL_MINOR_VERSION}.${CURL_PATCH_VERSION}\"\n\n    rm -rf ./curl-$CURL_VERSION\n    rm -rf ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE\n\n    # unpack dependencies\n    tar xzf ./curl-$CURL_VERSION.tar.gz --no-same-owner && \\\n    tar xzf ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz --no-same-owner\n\n    (\n        # Build Curl\n        cd curl-$CURL_VERSION && \\\n            ./buildconf && \\\n            ./configure \\\n                --prefix \"$ARTIFACTS_DIR\" \\\n                --disable-shared \\\n                --without-ssl \\\n                --with-pic \\\n                --without-zlib && \\\n            make && \\\n            make install\n    )\n\n    (\n        # Build aws-lambda-cpp\n        mkdir -p ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build && \\\n            cd ./aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE/build\n\n        $CMAKE .. \\\n                -DCMAKE_CXX_FLAGS=\"-fPIC\" \\\n                -DCMAKE_INSTALL_PREFIX=\"$ARTIFACTS_DIR\" \\\n                -DENABLE_LTO=$ENABLE_LTO \\\n                -DCMAKE_MODULE_PATH=\"$ARTIFACTS_DIR\"/lib/pkgconfig && \\\n            make && make install\n    )\nfi", "num_lines": 57}
{"repo_name": "aws-lambda-python-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\nset -e\n\ncd deps\nsource versions\n\n# Clean up old files\nrm -f aws-lambda-cpp-*.tar.gz && rm -f curl-*.tar.gz\n\n# Grab Curl\nwget -c \"https://github.com/curl/curl/releases/download/curl-${CURL_MAJOR_VERSION}_${CURL_MINOR_VERSION}_${CURL_PATCH_VERSION}/curl-${CURL_MAJOR_VERSION}.${CURL_MINOR_VERSION}.${CURL_PATCH_VERSION}.tar.gz\"\n\n# Grab aws-lambda-cpp\nwget -c https://github.com/awslabs/aws-lambda-cpp/archive/v$AWS_LAMBDA_CPP_RELEASE.tar.gz -O - | tar -xz\n\n## Apply patches to aws-lambda-cpp\n(\n  cd aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE && \\\n    patch -p1 < ../patches/aws-lambda-cpp-add-xray-response.patch && \\\n    patch -p1 < ../patches/aws-lambda-cpp-posting-init-errors.patch && \\\n    patch -p1 < ../patches/aws-lambda-cpp-make-the-runtime-client-user-agent-overrideable.patch && \\\n    patch -p1 < ../patches/aws-lambda-cpp-make-lto-optional.patch && \\\n    patch -p1 < ../patches/aws-lambda-cpp-add-content-type.patch\n)\n\n## Pack again and remove the folder\ntar -czvf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE.tar.gz aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE --no-same-owner && \\\n  rm -rf aws-lambda-cpp-$AWS_LAMBDA_CPP_RELEASE\n", "num_lines": 30}
{"repo_name": "aws-lambda-python-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is copied from https://github.com/aws/aws-codebuild-docker-images/blob/f0912e4b16e427da35351fc102f0f56f4ceb938a/local_builds/codebuild_build.sh\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\ndocker_command+=\" amazon/aws-codebuild-local:latest\"\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 195}
{"repo_name": "aws-lambda-python-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\nDRYRUN=\"${DRYRUN-0}\"\n\nfunction usage {\n    echo \"usage: test_all.sh buildspec_yml_dir\"\n    echo \"Runs all buildspec build-matrix combinations via test_one.sh.\"\n    echo \"Required:\"\n    echo \"  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file.\"\n}\n\ndo_one_yaml() {\n    local -r YML=\"$1\"\n\n    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\\s*(\\S+)' \"$YML\" | cut -d' ' -f2)\n    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' \"$YML\" | tr -d '\\-\" ')\n    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/phases/,$d' \"$YML\" | sed '/#.*$/d' |  tr -d '\\-\" ')\n\n    for DISTRO_VERSION in $DISTRO_VERSIONS ; do\n        for RUNTIME_VERSION in $RUNTIME_VERSIONS ; do\n            if (( DRYRUN == 1 )) ; then\n                echo DRYRUN test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            else\n                test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            fi\n        done\n    done\n}\n\ntest_one_combination() {\n    local -r YML=\"$1\"\n    local -r OS_DISTRIBUTION=\"$2\"\n    local -r DISTRO_VERSION=\"$3\"\n    local -r RUNTIME_VERSION=\"$4\"\n  \n    echo Testing:\n    echo \"  BUILDSPEC\" \"$YML\"\n    echo \"  with\" \"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n\n    \"$(dirname \"$0\")\"/test_one.sh \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \\\n        > >(sed \"s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION: /\") 2> >(sed \"s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION: /\" >&2)\n}\n\nmain() {\n    if (( $# != 1 && $# != 2)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML_DIR=\"$1\"\n    HAS_YML=0\n    for f in \"$BUILDSPEC_YML_DIR\"/*.yml ; do\n        [ -f \"$f\" ] || continue;\n        do_one_yaml \"$f\"\n        HAS_YML=1\n    done\n\n    if (( HAS_YML == 0 )); then\n        >&2 echo At least one buildspec is required.\n        exit 2\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 70}
{"repo_name": "aws-lambda-python-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\n\nfunction usage {\n    >&2 echo \"usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]\"\n    >&2 echo \"Runs one buildspec version combination from a build-matrix buildspec.\"\n    >&2 echo \"Required:\"\n    >&2 echo \"  buildspec_yml          Used to specify the CodeBuild buildspec template file.\"\n    >&2 echo \"  os_distribution        Used to specify the OS distribution to build.\"\n    >&2 echo \"  distro_version         Used to specify the distro version of <os_distribution>.\"\n    >&2 echo \"  runtime_version        Used to specify the runtime version to test on the selected <distro_version>.\"\n    >&2 echo \"Optional:\"\n    >&2 echo \"  env                    Additional environment variables file.\"\n}\n\nmain() {\n    if (( $# != 3 && $# != 4)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    set -x\n    BUILDSPEC_YML=\"$1\"\n    OS_DISTRIBUTION=\"$2\"\n    DISTRO_VERSION=\"$3\"\n    RUNTIME_VERSION=\"$4\"\n    EXTRA_ENV=\"${5-}\"\n\n    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild.\"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\"-\"$RUNTIME_VERSION\".XXXXXXXXXX)\n    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT\n\n    # Create an env file for codebuild_build.\n    ENVFILE=\"$CODEBUILD_TEMP_DIR/.env\"\n    if [ -f \"$EXTRA_ENV\" ]; then\n        cat \"$EXTRA_ENV\" > \"$ENVFILE\"\n    fi\n    {\n        echo \"\"\n        echo \"OS_DISTRIBUTION=$OS_DISTRIBUTION\"\n        echo \"DISTRO_VERSION=$DISTRO_VERSION\"\n        echo \"RUNTIME_VERSION=$RUNTIME_VERSION\"\n    }  >> \"$ENVFILE\"\n    \n    ARTIFACTS_DIR=\"$CODEBUILD_TEMP_DIR/artifacts\"\n    mkdir -p \"$ARTIFACTS_DIR\"\n\n    # Run CodeBuild local agent.\n    \"$(dirname \"$0\")\"/codebuild_build.sh \\\n        -i \"$CODEBUILD_IMAGE_TAG\" \\\n        -a \"$ARTIFACTS_DIR\" \\\n        -e \"$ENVFILE\" \\\n        -b \"$BUILDSPEC_YML\"\n}\n\nmain \"$@\"\n", "num_lines": 61}
{"repo_name": "aws-lambda-ruby-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is copied from https://github.com/aws/aws-codebuild-docker-images/blob/f0912e4b16e427da35351fc102f0f56f4ceb938a/local_builds/codebuild_build.sh\n\nfunction allOSRealPath() {\n    if isOSWindows\n    then\n        path=\"\"\n        case $1 in\n            .* ) path=\"$PWD/${1#./}\" ;;\n            /* ) path=\"$1\" ;;\n            *  ) path=\"/$1\" ;;\n        esac\n\n        echo \"/$path\" | sed -e 's/\\\\/\\//g' -e 's/://' -e 's/./\\U&/3'\n    else\n        case $1 in\n            /* ) echo \"$1\"; exit;;\n            *  ) echo \"$PWD/${1#./}\"; exit;;\n        esac\n    fi\n}\n\nfunction isOSWindows() {\n    if [ $OSTYPE == \"msys\" ]\n    then\n        return 0\n    else\n        return 1\n    fi\n}\n\nfunction usage {\n    echo \"usage: codebuild_build.sh [-i image_name] [-a artifact_output_directory] [options]\"\n    echo \"Required:\"\n    echo \"  -i        Used to specify the customer build container image.\"\n    echo \"  -a        Used to specify an artifact output directory.\"\n    echo \"Options:\"\n    echo \"  -l IMAGE  Used to override the default local agent image.\"\n    echo \"  -s        Used to specify source information. Defaults to the current working directory for primary source.\"\n    echo \"               * First (-s) is for primary source\"\n    echo \"               * Use additional (-s) in <sourceIdentifier>:<sourceLocation> format for secondary source\"\n    echo \"               * For sourceIdentifier, use a value that is fewer than 128 characters and contains only alphanumeric characters and underscores\"\n    echo \"  -c        Use the AWS configuration and credentials from your local host. This includes ~/.aws and any AWS_* environment variables.\"\n    echo \"  -p        Used to specify the AWS CLI Profile.\"\n    echo \"  -b FILE   Used to specify a buildspec override file. Defaults to buildspec.yml in the source directory.\"\n    echo \"  -m        Used to mount the source directory to the customer build container directly.\"\n    echo \"  -d        Used to run the build container in docker privileged mode.\"\n    echo \"  -e FILE   Used to specify a file containing environment variables.\"\n    echo \"            (-e) File format expectations:\"\n    echo \"               * Each line is in VAR=VAL format\"\n    echo \"               * Lines beginning with # are processed as comments and ignored\"\n    echo \"               * Blank lines are ignored\"\n    echo \"               * File can be of type .env or .txt\"\n    echo \"               * There is no special handling of quotation marks, meaning they will be part of the VAL\"\n    exit 1\n}\n\nimage_flag=false\nartifact_flag=false\nawsconfig_flag=false\nmount_src_dir_flag=false\ndocker_privileged_mode_flag=false\n\nwhile getopts \"cmdi:a:s:b:e:l:p:h\" opt; do\n    case $opt in\n        i  ) image_flag=true; image_name=$OPTARG;;\n        a  ) artifact_flag=true; artifact_dir=$OPTARG;;\n        b  ) buildspec=$OPTARG;;\n        c  ) awsconfig_flag=true;;\n        m  ) mount_src_dir_flag=true;;\n        d  ) docker_privileged_mode_flag=true;;\n        s  ) source_dirs+=(\"$OPTARG\");;\n        e  ) environment_variable_file=$OPTARG;;\n        l  ) local_agent_image=$OPTARG;;\n        p  ) aws_profile=$OPTARG;;\n        h  ) usage; exit;;\n        \\? ) echo \"Unknown option: -$OPTARG\" >&2; exit 1;;\n        :  ) echo \"Missing option argument for -$OPTARG\" >&2; exit 1;;\n        *  ) echo \"Invalid option: -$OPTARG\" >&2; exit 1;;\n    esac\ndone\n\nif  ! $image_flag\nthen\n    echo \"The image name flag (-i) must be included for a build to run\" >&2\nfi\n\nif  ! $artifact_flag\nthen\n    echo \"The artifact directory (-a) must be included for a build to run\" >&2\nfi\n\nif  ! $image_flag ||  ! $artifact_flag\nthen\n    exit 1\nfi\n\ndocker_command=\"docker run \"\nif isOSWindows\nthen\n    docker_command+=\"-v //var/run/docker.sock:/var/run/docker.sock -e \"\nelse\n    docker_command+=\"-v /var/run/docker.sock:/var/run/docker.sock -e \"\nfi\n\ndocker_command+=\"\\\"IMAGE_NAME=$image_name\\\" -e \\\n    \\\"ARTIFACTS=$(allOSRealPath \"$artifact_dir\")\\\"\"\n\nif [ -z \"$source_dirs\" ]\nthen\n    docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"$PWD\")\\\"\"\nelse\n    for index in \"${!source_dirs[@]}\"; do\n        if [ $index -eq 0 ]\n        then\n            docker_command+=\" -e \\\"SOURCE=$(allOSRealPath \"${source_dirs[$index]}\")\\\"\"\n        else\n            identifier=${source_dirs[$index]%%:*}\n            src_dir=$(allOSRealPath \"${source_dirs[$index]#*:}\")\n\n            docker_command+=\" -e \\\"SECONDARY_SOURCE_$index=$identifier:$src_dir\\\"\"\n        fi\n    done\nfi\n\nif [ -n \"$buildspec\" ]\nthen\n    docker_command+=\" -e \\\"BUILDSPEC=$(allOSRealPath \"$buildspec\")\\\"\"\nfi\n\nif [ -n \"$environment_variable_file\" ]\nthen\n    environment_variable_file_path=$(allOSRealPath \"$environment_variable_file\")\n    environment_variable_file_dir=$(dirname \"$environment_variable_file_path\")\n    environment_variable_file_basename=$(basename \"$environment_variable_file\")\n    docker_command+=\" -v \\\"$environment_variable_file_dir:/LocalBuild/envFile/\\\" -e \\\"ENV_VAR_FILE=$environment_variable_file_basename\\\"\"\nfi\n\nif [ -n \"$local_agent_image\" ]\nthen\n    docker_command+=\" -e \\\"LOCAL_AGENT_IMAGE_NAME=$local_agent_image\\\"\"\nfi\n\nif $awsconfig_flag\nthen\n    if [ -d \"$HOME/.aws\" ]\n    then\n        configuration_file_path=$(allOSRealPath \"$HOME/.aws\")\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=$configuration_file_path\\\"\"\n    else\n        docker_command+=\" -e \\\"AWS_CONFIGURATION=NONE\\\"\"\n    fi\n\n    if [ -n \"$aws_profile\" ]\n    then\n        docker_command+=\" -e \\\"AWS_PROFILE=$aws_profile\\\"\"\n    fi\n\n    docker_command+=\"$(env | grep ^AWS_ | while read -r line; do echo \" -e \\\"$line\\\"\"; done )\"\nfi\n\nif $mount_src_dir_flag\nthen\n    docker_command+=\" -e \\\"MOUNT_SOURCE_DIRECTORY=TRUE\\\"\"\nfi\n\nif $docker_privileged_mode_flag\nthen\n    docker_command+=\" -e \\\"DOCKER_PRIVILEGED_MODE=TRUE\\\"\"\nfi\n\nif isOSWindows\nthen\n    docker_command+=\" -e \\\"INITIATOR=$USERNAME\\\"\"\nelse\n    docker_command+=\" -e \\\"INITIATOR=$USER\\\"\"\nfi\n\ndocker_command+=\" amazon/aws-codebuild-local:latest\"\n\n# Note we do not expose the AWS_SECRET_ACCESS_KEY or the AWS_SESSION_TOKEN\nexposed_command=$docker_command\nsecure_variables=( \"AWS_SECRET_ACCESS_KEY=\" \"AWS_SESSION_TOKEN=\")\nfor variable in \"${secure_variables[@]}\"\ndo\n    exposed_command=\"$(echo $exposed_command | sed \"s/\\($variable\\)[^ ]*/\\1********\\\"/\")\"\ndone\n\necho \"Build Command:\"\necho \"\"\necho $exposed_command\necho \"\"\n\neval $docker_command\n", "num_lines": 195}
{"repo_name": "aws-lambda-ruby-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\nDRYRUN=\"${DRYRUN-0}\"\n\nfunction usage {\n    echo \"usage: test_all.sh buildspec_yml_dir\"\n    echo \"Runs all buildspec build-matrix combinations via test_one.sh.\"\n    echo \"Required:\"\n    echo \"  buildspec_yml_dir      Used to specify the CodeBuild buildspec template file.\"\n}\n\ndo_one_yaml() {\n    local -r YML=\"$1\"\n\n    OS_DISTRIBUTION=$(grep -oE 'OS_DISTRIBUTION:\\s*(\\S+)' \"$YML\" | cut -d' ' -f2)\n    DISTRO_VERSIONS=$(sed '1,/DISTRO_VERSION/d;/RUNTIME_VERSION/,$d' \"$YML\" | tr -d '\\-\" ')\n    RUNTIME_VERSIONS=$(sed '1,/RUNTIME_VERSION/d;/phases/,$d' \"$YML\" | sed '/#.*$/d' |  tr -d '\\-\" ')\n\n    for DISTRO_VERSION in $DISTRO_VERSIONS ; do\n        for RUNTIME_VERSION in $RUNTIME_VERSIONS ; do\n            if (( DRYRUN == 1 )) ; then\n                echo DRYRUN test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            else\n                test_one_combination \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n            fi\n        done\n    done\n}\n\ntest_one_combination() {\n    local -r YML=\"$1\"\n    local -r OS_DISTRIBUTION=\"$2\"\n    local -r DISTRO_VERSION=\"$3\"\n    local -r RUNTIME_VERSION=\"$4\"\n  \n    echo Testing:\n    echo \"  BUILDSPEC\" \"$YML\"\n    echo \"  with\" \"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\" \"$RUNTIME_VERSION\"\n\n    \"$(dirname \"$0\")\"/test_one.sh \"$YML\" \"$OS_DISTRIBUTION\" \"$DISTRO_VERSION\" \"$RUNTIME_VERSION\" \\\n        > >(sed \"s/^/$OS_DISTRIBUTION$DISTRO_VERSION-$RUNTIME_VERSION: /\") 2> >(sed \"s/^/$OS_DISTRIBUTION-$DISTRO_VERSION:$RUNTIME_VERSION: /\" >&2)\n}\n\nmain() {\n    if (( $# != 1 && $# != 2)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML_DIR=\"$1\"\n    HAS_YML=0\n    for f in \"$BUILDSPEC_YML_DIR\"/*.yml ; do\n        [ -f \"$f\" ] || continue;\n        do_one_yaml \"$f\"\n        HAS_YML=1\n    done\n\n    if (( HAS_YML == 0 )); then\n        >&2 echo At least one buildspec is required.\n        exit 2\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 70}
{"repo_name": "aws-lambda-ruby-runtime-interface-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -euo pipefail\n\nCODEBUILD_IMAGE_TAG=\"${CODEBUILD_IMAGE_TAG:-al2/x86_64/standard/3.0}\"\n\nfunction usage {\n    >&2 echo \"usage: test_one.sh buildspec_yml os_distribution distro_version runtime_version [env]\"\n    >&2 echo \"Runs one buildspec version combination from a build-matrix buildspec.\"\n    >&2 echo \"Required:\"\n    >&2 echo \"  buildspec_yml          Used to specify the CodeBuild buildspec template file.\"\n    >&2 echo \"  os_distribution        Used to specify the OS distribution to build.\"\n    >&2 echo \"  distro_version         Used to specify the distro version of <os_distribution>.\"\n    >&2 echo \"  runtime_version        Used to specify the runtime version to test on the selected <distro_version>.\"\n    >&2 echo \"Optional:\"\n    >&2 echo \"  env                    Additional environment variables file.\"\n}\n\nmain() {\n    if (( $# != 3 && $# != 4)); then\n        >&2 echo \"Invalid number of parameters.\"\n        usage\n        exit 1\n    fi\n\n    BUILDSPEC_YML=\"$1\"\n    OS_DISTRIBUTION=\"$2\"\n    DISTRO_VERSION=\"$3\"\n    RUNTIME_VERSION=\"$4\"\n    EXTRA_ENV=\"${5-}\"\n\n    CODEBUILD_TEMP_DIR=$(mktemp -d codebuild.\"$OS_DISTRIBUTION\"-\"$DISTRO_VERSION\"-\"$RUNTIME_VERSION\".XXXXXXXXXX )\n    trap 'rm -rf $CODEBUILD_TEMP_DIR' EXIT\n\n    # Create an env file for codebuild_build.\n    ENVFILE=\"$CODEBUILD_TEMP_DIR/.env\"\n    if [ -f \"$EXTRA_ENV\" ]; then\n        cat \"$EXTRA_ENV\" > \"$ENVFILE\"\n    fi\n    {\n        echo \"\"\n        echo \"OS_DISTRIBUTION=$OS_DISTRIBUTION\"\n        echo \"DISTRO_VERSION=$DISTRO_VERSION\"\n        echo \"RUNTIME_VERSION=$RUNTIME_VERSION\"\n    }  >> \"$ENVFILE\"\n    \n    ARTIFACTS_DIR=\"$CODEBUILD_TEMP_DIR/artifacts\"\n    mkdir -p \"$ARTIFACTS_DIR\"\n\n    # Run CodeBuild local agent.\n    \"$(dirname \"$0\")\"/codebuild_build.sh \\\n        -i \"$CODEBUILD_IMAGE_TAG\" \\\n        -a \"$ARTIFACTS_DIR\" \\\n        -e \"$ENVFILE\" \\\n        -b \"$BUILDSPEC_YML\"\n}\n\nmain \"$@\"\n", "num_lines": 60}
{"repo_name": "aws-lambda-runtime-interface-emulator", "repo_creator": "aws", "programming_language": "Shell", "code": "function handler () {\n  EVENT_DATA=$1\n  echo \"$EVENT_DATA\" 1>&2;\n  RESPONSE=\"Echoing request: '$EVENT_DATA'\"\n\n  echo $RESPONSE\n}", "num_lines": 7}
{"repo_name": "aws-lambda-runtime-interface-emulator", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -euo pipefail\n\n# Initialization - load function handler\nsource $LAMBDA_TASK_ROOT/\"bash_function.sh\"\n\n# Processing\nwhile true\ndo\n  HEADERS=\"$(mktemp)\"\n  # Get an event\n  EVENT_DATA=$(curl -sS -LD \"$HEADERS\" -X GET \"http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/next\")\n  REQUEST_ID=$(grep -Fi Lambda-Runtime-Aws-Request-Id \"$HEADERS\" | tr -d '[:space:]' | cut -d: -f2)\n\n  # Execute the handler function from the script\n  FN_PATH=$LAMBDA_TASK_ROOT/\"bash_function.sh\"\n  RESPONSE=$($FN_PATH \"$EVENT_DATA\")\n\n  # Send the response\n  curl -X POST \"http://${AWS_LAMBDA_RUNTIME_API}/2018-06-01/runtime/invocation/$REQUEST_ID/response\"  -d \"response_from_runtime\"\ndone", "num_lines": 22}
{"repo_name": "aws-lambda-runtime-interface-emulator", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Spawn one child process recursively and spin\n# When parent process receives a SIGTERM, child process doesn't exit\n\nif [ -z \"$DONT_SPAWN\" ]\nthen\n    DONT_SPAWN=true ./$0 &\nfi\n\nwhile true\ndo\n  sleep 1\ndone", "num_lines": 14}
{"repo_name": "aws-lambda-runtime-interface-emulator", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n", "num_lines": 2}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -xe\n\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha1 > aes_128_cbc_sha1_tls_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -implicit-iv > aes_128_cbc_sha1_tls_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha256 > aes_128_cbc_sha256_tls_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -implicit-iv > aes_128_cbc_sha256_tls_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha1 > aes_256_cbc_sha1_tls_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -implicit-iv > aes_256_cbc_sha1_tls_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher 3des -mac sha1 > des_ede3_cbc_sha1_tls_tests.txt\ngo run make_legacy_aead_tests.go -cipher 3des -mac sha1 -implicit-iv > des_ede3_cbc_sha1_tls_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -stitch > aes_128_cbc_sha1_tls_stitch_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha1 -implicit-iv -stitch > aes_128_cbc_sha1_tls_stitch_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -stitch > aes_128_cbc_sha256_tls_stitch_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes128 -mac sha256 -implicit-iv -stitch > aes_128_cbc_sha256_tls_stitch_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -stitch > aes_256_cbc_sha1_tls_stitch_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha1 -implicit-iv -stitch > aes_256_cbc_sha1_tls_stitch_implicit_iv_tests.txt\n\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha256 -stitch > aes_256_cbc_sha256_tls_stitch_tests.txt\ngo run make_legacy_aead_tests.go -cipher aes256 -mac sha256 -implicit-iv -stitch > aes_256_cbc_sha256_tls_stitch_implicit_iv_tests.txt\n", "num_lines": 28}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2016, Google Inc.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nset -e\n\nbuildDir=../build\nif [ $# -gt 0 ]; then\n  buildDir=$1\nfi\n\nfor testSource in $(ls -1 *.cc); do\n  test=$(echo $testSource | sed -e 's/\\.cc$//')\n  if [ ! -x $buildDir/fuzz/$test ] ; then\n    echo \"Failed to find binary for $test\"\n    exit 1\n  fi\n  if [ ! -d ${test}_corpus ]; then\n    echo \"Failed to find corpus directory for $test\"\n    exit 1\n  fi\n  if [ -d ${test}_corpus_old ]; then\n    echo \"Old corpus directory for $test already exists\"\n    exit 1\n  fi\ndone\n\nfor testSource in $(ls -1 *.cc); do\n  test=$(echo $testSource | sed -e 's/\\.cc$//')\n  mv ${test}_corpus ${test}_corpus_old\n  mkdir ${test}_corpus\n  $buildDir/fuzz/$test -max_len=50000 -merge=1 ${test}_corpus ${test}_corpus_old\n  rm -Rf ${test}_corpus_old\ndone\n", "num_lines": 46}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2016, Google Inc.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nset -ex\n\nif [[ $# -ne 2 ]]; then\n  echo \"Usage: $0 fuzzer_mode_build_dir no_fuzzer_mode_build_dir\"\n  exit 1\nfi\n\nfuzzer_mode_build_dir=$1\nno_fuzzer_mode_build_dir=$2\n\n\n# Sanity-check the build directories.\n\nif ! grep -q '^FUZZ:' \"$fuzzer_mode_build_dir/CMakeCache.txt\"; then\n  echo \"$fuzzer_mode_build_dir was not built with -DFUZZ=1\"\n  exit 1\nfi\n\nif grep -q '^NO_FUZZER_MODE:' \"$fuzzer_mode_build_dir/CMakeCache.txt\"; then\n  echo \"$fuzzer_mode_build_dir was built with -DNO_FUZZER_MODE=1\"\n  exit 1\nfi\n\nif ! grep -q '^FUZZ:' \"$no_fuzzer_mode_build_dir/CMakeCache.txt\"; then\n  echo \"$no_fuzzer_mode_build_dir was not built with -DFUZZ=1\"\n  exit 1\nfi\n\nif ! grep -q '^NO_FUZZER_MODE:' \"$no_fuzzer_mode_build_dir/CMakeCache.txt\"; then\n  echo \"$no_fuzzer_mode_build_dir was not built with -DNO_FUZZER_MODE=1\"\n  exit 1\nfi\n\n\n# Sanity-check the current working directory.\n\nassert_directory() {\n  if [[ ! -d $1 ]]; then\n    echo \"$1 not found.\"\n    exit 1\n  fi\n}\n\nassert_directory client_corpus\nassert_directory client_corpus_no_fuzzer_mode\nassert_directory server_corpus\nassert_directory server_corpus_no_fuzzer_mode\nassert_directory dtls_client_corpus\nassert_directory dtls_server_corpus\n\n\n# Gather new transcripts. Ignore errors in running the tests.\n\nfuzzer_mode_shim=$(readlink -f \"$fuzzer_mode_build_dir/ssl/test/bssl_shim\")\nno_fuzzer_mode_shim=$(readlink -f \\\n    \"$no_fuzzer_mode_build_dir/ssl/test/bssl_shim\")\n\nfuzzer_mode_handshaker=$(readlink -f \\\n    \"$fuzzer_mode_build_dir/ssl/test/handshaker\")\nno_fuzzer_mode_handshaker=$(readlink -f \\\n    \"$no_fuzzer_mode_build_dir/ssl/test/handshaker\")\n\nfuzzer_mode_transcripts=$(mktemp -d '/tmp/boringssl-transcript-fuzzer-mode.XXXXXX')\nno_fuzzer_mode_transcripts=$(mktemp -d '/tmp/boringssl-transcript-no-fuzzer-mode.XXXXXX')\n\necho Recording fuzzer-mode transcripts\n(cd ../ssl/test/runner/ && go test \\\n    -shim-path \"$fuzzer_mode_shim\" \\\n    -handshaker-path \"$fuzzer_mode_handshaker\" \\\n    -transcript-dir \"$fuzzer_mode_transcripts\" \\\n    -fuzzer \\\n    -deterministic) || true\n\necho Recording non-fuzzer-mode transcripts\n(cd ../ssl/test/runner/ && go test \\\n    -shim-path \"$no_fuzzer_mode_shim\" \\\n    -handshaker-path \"$no_fuzzer_mode_handshaker\" \\\n    -transcript-dir \"$no_fuzzer_mode_transcripts\" \\\n    -deterministic)\n\n\n# Minimize the existing corpora.\n\nminimize_corpus() {\n  local fuzzer=\"$1\"\n  local corpus=\"$2\"\n\n  echo \"Minimizing ${corpus}\"\n  mv \"$corpus\" \"${corpus}_old\"\n  mkdir \"$corpus\"\n  \"$fuzzer\" -max_len=50000 -merge=1 \"$corpus\" \"${corpus}_old\"\n  rm -Rf \"${corpus}_old\"\n}\n\nminimize_corpus \"$fuzzer_mode_build_dir/fuzz/client\" client_corpus\nminimize_corpus \"$fuzzer_mode_build_dir/fuzz/server\" server_corpus\nminimize_corpus \"$no_fuzzer_mode_build_dir/fuzz/client\" client_corpus_no_fuzzer_mode\nminimize_corpus \"$no_fuzzer_mode_build_dir/fuzz/server\" server_corpus_no_fuzzer_mode\nminimize_corpus \"$fuzzer_mode_build_dir/fuzz/dtls_client\" dtls_client_corpus\nminimize_corpus \"$fuzzer_mode_build_dir/fuzz/dtls_server\" dtls_server_corpus\nminimize_corpus \"$fuzzer_mode_build_dir/fuzz/decode_client_hello_inner\" decode_client_hello_inner_corpus\n\n\n# Incorporate the new transcripts.\n\n\"$fuzzer_mode_build_dir/fuzz/client\" -max_len=50000 -merge=1 client_corpus \"${fuzzer_mode_transcripts}/tls/client\"\n\"$fuzzer_mode_build_dir/fuzz/server\" -max_len=50000 -merge=1 server_corpus \"${fuzzer_mode_transcripts}/tls/server\"\n\"$no_fuzzer_mode_build_dir/fuzz/client\" -max_len=50000 -merge=1 client_corpus_no_fuzzer_mode \"${no_fuzzer_mode_transcripts}/tls/client\"\n\"$no_fuzzer_mode_build_dir/fuzz/server\" -max_len=50000 -merge=1 server_corpus_no_fuzzer_mode \"${no_fuzzer_mode_transcripts}/tls/server\"\n\"$fuzzer_mode_build_dir/fuzz/dtls_client\" -max_len=50000 -merge=1 dtls_client_corpus \"${fuzzer_mode_transcripts}/dtls/client\"\n\"$fuzzer_mode_build_dir/fuzz/dtls_server\" -max_len=50000 -merge=1 dtls_server_corpus \"${fuzzer_mode_transcripts}/dtls/server\"\n\"$fuzzer_mode_build_dir/fuzz/decode_client_hello_inner\" -max_len=50000 -merge=1 decode_client_hello_inner_corpus \"${fuzzer_mode_transcripts}/decode_client_hello_inner\"\n", "num_lines": 128}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Take current contents of generated-src and move to another directory\nmv ./generated-src ./generated-src-bak\n\n# Regenerate contents of generated-src\npython3 ./util/generate_build_files.py\n\n# Check whether or not\nif [[ $(diff -qr ./generated-src ./generated-src-bak) ]]; then \n    echo \"Contents of generated-src are not up-to-date.\"\n    exit 1;\nfi\n\necho \"Contents of generated-src are up-to-date.\"\n", "num_lines": 18}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\necho \"Running objects.go to update files\"\npushd crypto/obj\ngo run objects.go\npopd\n\necho \"Adding all changed files to the git tree\"\ngit add -A\n\necho \"Checking for any changes\"\ngit diff --exit-code HEAD\n\necho \"Running make_errors.go to update files\"\ngo run ./util/make_errors.go ssl evp ocsp pem\n\necho \"Adding all changed files to the git tree\"\ngit add -A\n\necho \"Checking for any changes\"\ngit diff --exit-code HEAD\n", "num_lines": 24}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -x\n\n# set default value of directory name\nif [ -z \"${PR_FOLDER_NAME}\" ]; then export PR_FOLDER_NAME=aws-lc; fi\n\n# Get AWS_ACCOUNT_ID\nif [ -z \"${AWS_ACCOUNT_ID}\" ]; then AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text); fi\n\nAWSLC_PR_ROOT=$(pwd)\n\ncd ..\n\n# run this from the bm_framework root directory!\nAWSLC_PR_ROOT=$(pwd)/\"${PR_FOLDER_NAME}\"\nAWSLC_PROD_ROOT=$(pwd)/aws-lc-prod\n\nsource ${AWSLC_PR_ROOT}/tests/ci/common_posix_setup.sh\n\n# clone the various repositories we need (we already have aws-lc-pr since we need it to run this script)\ngit clone https://github.com/aws/aws-lc.git aws-lc-prod\n\n# build AWSLC pr\nmkdir -p \"${PR_FOLDER_NAME}\"/build\n${CMAKE_COMMAND} -B\"${PR_FOLDER_NAME}\"/build -H\"${PR_FOLDER_NAME}\" -GNinja -DCMAKE_BUILD_TYPE=Release \\\n  -DBUILD_TESTING=OFF\nninja -C \"${PR_FOLDER_NAME}\"/build\n\n# build FIPS compliant version of AWSLC pr\nmkdir -p \"${PR_FOLDER_NAME}\"/fips_build\n${CMAKE_COMMAND} -B\"${PR_FOLDER_NAME}\"/fips_build -H\"${PR_FOLDER_NAME}\" -GNinja -DFIPS=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=TRUE\nninja -C \"${PR_FOLDER_NAME}\"/fips_build\n\n# build AWSLC prod\nmkdir -p aws-lc-prod/build\n${CMAKE_COMMAND} -Baws-lc-prod/build -Haws-lc-prod -GNinja -DCMAKE_BUILD_TYPE=Release -DBUILD_TESTING=OFF\nninja -C aws-lc-prod/build\n\n#build FIPS compliant version of AWSLC prod\nmkdir -p aws-lc-prod/fips_build\n${CMAKE_COMMAND} -Baws-lc-prod/fips_build -Haws-lc-prod -GNinja -DFIPS=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=TRUE\nninja -C aws-lc-prod/fips_build\n\n./\"${PR_FOLDER_NAME}\"/build/tool/bssl speed -timeout 1 -json > aws-lc-pr_bm.json\n./\"${PR_FOLDER_NAME}\"/fips_build/tool/bssl speed -timeout 1 -json > aws-lc-pr_fips_bm.json\n\n./aws-lc-prod/build/tool/bssl speed -timeout 1 -json > aws-lc-prod_bm.json\n./aws-lc-prod/fips_build/tool/bssl speed -timeout 1 -json > aws-lc-prod_fips_bm.json\n\n\n./\"${PR_FOLDER_NAME}\"/build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-pr_tt_bm.json\n./\"${PR_FOLDER_NAME}\"/fips_build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-pr_tt_fips_bm.json\n./aws-lc-prod/build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-prod_tt_bm.json\n./aws-lc-prod/fips_build/tool/bssl speed -filter trusttoken -timeout 1 -json > aws-lc-prod_tt_fips_bm.json\n\n# convert results from .json to .csv\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_fips_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_fips_bm.json\n\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_tt_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-pr_tt_fips_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_tt_bm.json\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/convert_json_to_csv.py aws-lc-prod_tt_fips_bm.json\n\n# once we have csvs, we want to update the main benchmark results files with the sequential trusttoken results\n# files will be updated in place\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/update_results.py aws-lc-pr_bm.csv aws-lc-pr_tt_bm.csv python3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/update_results.py aws-lc-pr_fips_bm.csv aws-lc-pr_tt_fips_bm.csv python3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/update_results.py aws-lc-prod_bm.csv aws-lc-prod_tt_bm.csv python3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/update_results.py aws-lc-prod_fips_bm.csv aws-lc-prod_tt_fips_bm.csv\n\n# check for regressions!\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/compare_results.py aws-lc-prod_bm.csv aws-lc-pr_bm.csv prod_vs_pr.csv\nprod_vs_pr_code=\"$?\"\npython3 \"${PR_FOLDER_NAME}\"/tests/ci/benchmark_framework/compare_results.py aws-lc-prod_fips_bm.csv aws-lc-pr_fips_bm.csv prod_vs_pr_fips.csv\nprod_vs_pr_fips_code=\"$?\"\n\n# upload results to s3\naws s3 cp aws-lc-pr_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-pr_bm.csv\"\naws s3 cp aws-lc-pr_fips_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-pr_fips_bm.csv\"\naws s3 cp aws-lc-prod_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-prod_bm.csv\"\naws s3 cp aws-lc-prod_fips_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/${CODEBUILD_SOURCE_VERSION}/aws-lc-prod_fips_bm.csv\"\n\n# upload results to lastest folders in s3\naws s3 mv aws-lc-pr_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/aws-lc-pr_bm.csv\"\naws s3 mv aws-lc-pr_fips_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/aws-lc-pr_fips_bm.csv\"\naws s3 mv aws-lc-prod_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest/aws-lc-prod_bm.csv\"\naws s3 mv aws-lc-prod_fips_bm.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest/aws-lc-prod_fips_bm.csv\"\n\n# if any of the results gave an exit code of 5, there's a performance regression\n# we only want to actually fail the vote if we've detected a regression in the pr version of aws-lc and tip of main of aws-lc (for fips and non-fips)\nexit_fail=false\nif [ \"${prod_vs_pr_code}\" != 0 ]; then\n  aws s3 cp prod_vs_pr.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/prod_vs_pr.csv\"\n  aws s3 mv prod_vs_pr.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/prod_vs_pr.csv\"\n  exit_fail=true\nfi\nif [ \"${prod_vs_pr_fips_code}\" != 0 ]; then\n  aws s3 cp prod_vs_pr_fips.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/${CODEBUILD_SOURCE_VERSION}/prod_vs_pr_fips.csv\"\n  aws s3 mv prod_vs_pr_fips.csv s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}/prod_vs_pr_fips.csv\"\n  exit_fail=true\nfi\n\nif [ \"${exit_fail}\" = true ]; then\n  exit 1\nfi\n", "num_lines": 109}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\nif [ -v CODEBUILD_FUZZING_ROOT ]; then\n  CORPUS_ROOT=\"${CODEBUILD_FUZZING_ROOT}/fuzzing\"\nelse\n  CORPUS_ROOT=\"${BUILD_ROOT}/mock_efs/fuzzing\"\nfi\necho \"$CORPUS_ROOT\"\n\nif [ -v CODEBUILD_BUILD_ID ]; then\n  BUILD_ID=$CODEBUILD_BUILD_ID\nelse\n  # Generate a random string in bash https://unix.stackexchange.com/questions/230673/how-to-generate-a-random-string\n  BUILD_ID=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 13 ; echo '')\nfi\necho \"$BUILD_ID\"\n\nDATE_NOW=\"$(date +%Y-%m-%d)\"\nSHARED_FAILURE_ROOT=\"${CORPUS_ROOT}/runs/${DATE_NOW}/${BUILD_ID}\"\nLOCAL_RUN_ROOT=\"${BUILD_ROOT}/fuzz_run_root\"\nrm -rf \"$LOCAL_RUN_ROOT\"\n\nfunction put_metric_count {\n  put_metric --unit Count \"$@\"\n}\n\nfunction put_metric {\n  # This call to publish the metric could fail but we don't want to fail the build +e turns off exit on error\n  set +e\n  aws cloudwatch put-metric-data \\\n    --namespace AWS-LC-Fuzz \\\n    \"$@\" || echo \"Publishing metric failed, continuing with the rest of the build\"\n  # Turn it back on for the rest of the build\n  set -e\n}\n\nfunction run_fuzz_test {\n  SHARED_FUZZ_TEST_CORPUS=\"${CORPUS_ROOT}/shared_corpus/${FUZZ_NAME}/shared_corpus\"\n  LOCAL_FUZZ_TEST_ROOT=\"${LOCAL_RUN_ROOT}/${FUZZ_NAME}\"\n  LOCAL_SHARED_CORPUS=\"${LOCAL_FUZZ_TEST_ROOT}/local_shared_corpus\"\n  LOCAL_RUN_CORPUS=\"${LOCAL_FUZZ_TEST_ROOT}/run_corpus\"\n  LOCAL_ARTIFACTS_FOLDER=\"${LOCAL_FUZZ_TEST_ROOT}/artifacts\"\n  LOCAL_FUZZ_RUN_LOGS=\"${LOCAL_FUZZ_TEST_ROOT}/logs\"\n  SUMMARY_LOG=\"${LOCAL_FUZZ_RUN_LOGS}/summary.log\"\n  mkdir -p \"$SHARED_FUZZ_TEST_CORPUS\" \"$LOCAL_FUZZ_TEST_ROOT\" \"$LOCAL_RUN_CORPUS\" \"$LOCAL_ARTIFACTS_FOLDER\" \"$LOCAL_FUZZ_RUN_LOGS\"\n\n  # To avoid having each libfuzzer thread read from the shared corpus copy it to the local CodeBuild directory one time\n  cp -r \"$SHARED_FUZZ_TEST_CORPUS\" \"$LOCAL_SHARED_CORPUS\"\n\n  # Calculate starting metrics and post to CloudWatch, this counts the files in LOCAL_SHARED_CORPUS but publishes them\n  # as the SharedCorpusFileCount, which it basically everything in SHARED_FUZZ_TEST_CORPUS was just copied to\n  # LOCAL_SHARED_CORPUS\n  ORIGINAL_CORPUS_FILE_COUNT=$(find \"$LOCAL_SHARED_CORPUS\" -type f | wc -l)\n  put_metric_count --metric-name SharedCorpusFileCount --value \"$ORIGINAL_CORPUS_FILE_COUNT\" --dimensions \"FuzzTest=$FUZZ_NAME\"\n\n  # Perform the actual fuzzing!\n  # Step 1 run each fuzz test for the determined time. This will use the existing shared corpus copied from EFS to\n  # LOCAL_SHARED_CORPUS and any files checked into the GitHub SRC_CORPUS. This runs the fuzzer with three\n  # folders: the first folder is where new inputs will go (LOCAL_RUN_CORPUS), all other folders will be used as input\n  # for fuzzing (LOCAL_SHARED_CORPUS and SRC_CORPUS).\n  # https://llvm.org/docs/LibFuzzer.html#options\n  #\n  # Run with NUM_CPU_THREADS which will be physical cores on ARM and virtualized cores on x86 with hyper threading.\n  # Looking at the overall system fuzz rate running 1:1 with virtualized cores provides a noticeable speed up. This\n  # is slightly different than libfuzzer's recommendation of #cores/2.\n  # This could fail and we want to capture that so we can publish metrics and save logs (+e)\n  set +e\n  FUZZ_RUN_FAILURE=0\n  # 2048 is the default memory usage. https://llvm.org/docs/LibFuzzer.html\n  MEM_USAGE_LIMIT=2048\n  if [[ (\"${FUZZ_NAME}\" == *\"cryptofuzz\"*) && ((\"$(uname -p)\" == 'aarch64')) ]]; then\n    # On arm, libFuzzer: out-of-memory (used: 2063Mb; limit: 2048Mb)\n    # Below is set based on ARM BUILD_GENERAL1_LARGE(8vCPU, 16 GB memory).\n    # 2500MB x 6 / 1024 = 14.6GB\n    MEM_USAGE_LIMIT=2500\n    NUM_CPU_THREADS=6\n  fi\n  time \"${FUZZ_TEST_PATH}\" -rss_limit_mb=${MEM_USAGE_LIMIT} -print_final_stats=1 -timeout=\"$FUZZ_TEST_TIMEOUT\" -max_total_time=\"$TIME_FOR_EACH_FUZZ\" \\\n    -jobs=\"$NUM_CPU_THREADS\" -workers=\"$NUM_CPU_THREADS\" \\\n    -artifact_prefix=\"$LOCAL_ARTIFACTS_FOLDER/\" \\\n    \"$LOCAL_RUN_CORPUS\" \"$LOCAL_SHARED_CORPUS\" \"$SRC_CORPUS\" 2>&1 | tee \"$SUMMARY_LOG\"\n  # This gets the status of the fuzz run which determines if we want to fail the build or not, otherwise we'd get the results of tee\n  if [ \"${PIPESTATUS[0]}\" == 1 ]; then\n    FUZZ_RUN_FAILURE=1\n  fi\n\n  # The libfuzzer logs are written to the current working directory and need to be moved after the test is done\n  mv ./*.log  \"${LOCAL_FUZZ_RUN_LOGS}/.\"\n\n  if [ \"$FUZZ_RUN_FAILURE\" == 1 ]; then\n    FUZZ_TEST_FAILURE_ROOT=\"${SHARED_FAILURE_ROOT}/${FUZZ_NAME}\"\n    mkdir -p \"$FUZZ_TEST_FAILURE_ROOT\"\n\n    if [[ \"$FUZZ_NAME\" == \"cryptofuzz\" ]]; then\n      for ARTIFACT in \"$LOCAL_ARTIFACTS_FOLDER\"/*; do\n        base64 $ARTIFACT\n        ARTIFACT_NAME=$(basename \"$ARTIFACT\")\n        \"${FUZZ_TEST_PATH}\" --debug \"$ARTIFACT\" | tee \"${LOCAL_FUZZ_RUN_LOGS}/${ARTIFACT_NAME}.log\"\n      done\n    fi\n\n    cp -r \"$LOCAL_FUZZ_TEST_ROOT\" \"$SHARED_FAILURE_ROOT\"\n    cp \"$FUZZ_TEST_PATH\" \"${FUZZ_TEST_FAILURE_ROOT}/${FUZZ_NAME}\"\n\n    # If this fuzz run has failed the below metrics won't make a lot of sense, it could fail on the first input and\n    # publish a TestCount of 1 which makes all the metrics look weird\n    echo \"${FUZZ_NAME} failed, see the above output for details. For all the logs see ${SHARED_FAILURE_ROOT} in EFS\"\n    exit 1\n  else\n    echo \"Fuzz test ${FUZZ_NAME} finished successfully, not copying run logs and run corpus\"\n  fi\n\n  set -e\n\n  # Step 2 merge any new files from the run corpus and GitHub src corpus into the shared corpus, the first folder is\n  # where to merge the new corpus (SHARED_FUZZ_TEST_CORPUS), the second two are where to read new inputs from\n  # (LOCAL_RUN_CORPUS and SRC_CORPUS).\n  time \"${FUZZ_TEST_PATH}\" -merge=1 \"$SHARED_FUZZ_TEST_CORPUS\" \"$LOCAL_RUN_CORPUS\" \"$SRC_CORPUS\"\n\n  # Calculate interesting metrics and post results to CloudWatch, this checks the shared (EFS) corpus after the new test\n  # run corpus has been merged in\n  FINAL_SHARED_CORPUS_FILE_COUNT=$(find \"$SHARED_FUZZ_TEST_CORPUS\" -type f | wc -l)\n  put_metric_count --metric-name SharedCorpusFileCount --value \"$FINAL_SHARED_CORPUS_FILE_COUNT\" --dimensions \"FuzzTest=$FUZZ_NAME\"\n\n  RUN_CORPUS_FILE_COUNT=$(find \"$LOCAL_RUN_CORPUS\" -type f | wc -l)\n  put_metric_count --metric-name RunCorpusFileCount --value \"$RUN_CORPUS_FILE_COUNT\" --dimensions \"FuzzTest=$FUZZ_NAME,Platform=$PLATFORM\"\n\n  TEST_COUNT=$(grep -o \"stat::number_of_executed_units: [0-9]*\" \"$SUMMARY_LOG\" | awk '{test_count += $2} END {print test_count}')\n  put_metric_count --metric-name TestCount --value \"$TEST_COUNT\" --dimensions \"FuzzTest=$FUZZ_NAME,Platform=$PLATFORM\"\n\n  TESTS_PER_SECOND=$((TEST_COUNT/TIME_FOR_EACH_FUZZ))\n  put_metric --metric-name TestRate --value \"$TESTS_PER_SECOND\" --unit Count/Second --dimensions \"FuzzTest=$FUZZ_NAME,Platform=$PLATFORM\"\n\n  FEATURE_COVERAGE=$(grep -o \"ft: [0-9]*\" \"$SUMMARY_LOG\" | awk '{print $2}' | sort -n | tail -1)\n  put_metric_count --metric-name FeatureCoverage --value \"$FEATURE_COVERAGE\" --dimensions \"FuzzTest=$FUZZ_NAME,Platform=$PLATFORM\"\n\n  BLOCK_COVERAGE=$(grep -o \"cov: [0-9]*\" \"$SUMMARY_LOG\" | awk '{print $2}' | sort -n | tail -1)\n  put_metric_count --metric-name BlockCoverage --value \"$BLOCK_COVERAGE\" --dimensions \"FuzzTest=$FUZZ_NAME,Platform=$PLATFORM\"\n\n  echo \"${FUZZ_NAME} starting shared ${ORIGINAL_CORPUS_FILE_COUNT} final shared ${FINAL_SHARED_CORPUS_FILE_COUNT} new files ${RUN_CORPUS_FILE_COUNT} total test count ${TEST_COUNT} test rate ${TESTS_PER_SECOND} code coverage ${BLOCK_COVERAGE} feature coverage ${FEATURE_COVERAGE}\"\n}\n", "num_lines": 145}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nif [ -v CODEBUILD_SRC_DIR ]; then\n  SRC_ROOT=\"$CODEBUILD_SRC_DIR\"\nelse\n  SRC_ROOT=$(pwd)\nfi\necho \"$SRC_ROOT\"\n\ncd ../\nSYS_ROOT=$(pwd)\ncd $SRC_ROOT\n\nBUILD_ROOT=\"${SRC_ROOT}/test_build_dir\"\necho \"$BUILD_ROOT\"\n\nPLATFORM=$(uname -m)\n\nNUM_CPU_THREADS=''\nKERNEL_NAME=$(uname -s)\nif [[ \"${KERNEL_NAME}\" == \"Darwin\" ]]; then\n  # On MacOS, /proc/cpuinfo does not exist.\n  NUM_CPU_THREADS=$(sysctl -n hw.ncpu)\nelse\n  # Assume KERNEL_NAME is Linux.\n  NUM_CPU_THREADS=$(grep -c ^processor /proc/cpuinfo)\n  if [[ $PLATFORM == \"aarch64\" ]]; then\n    CPU_PART=$(grep -Po -m 1 'CPU part.*:\\s\\K.*' /proc/cpuinfo)\n    NUM_CPU_PART=$(grep -c $CPU_PART /proc/cpuinfo)\n    # Set capabilities via the static flags for valgrind tests.\n    # This is because valgrind reports the instruction\n    #   mrs %0, MIDR_EL1\n    # which fetches the CPU part number, as illegal.\n    # For some reason, valgrind also reports SHA512 instructions illegal,\n    # so the SHA512 capability is not included below.\n    VALGRIND_STATIC_CAP_FLAGS=\"-DOPENSSL_STATIC_ARMCAP -DOPENSSL_STATIC_ARMCAP_NEON\"\n    VALGRIND_STATIC_CAP_FLAGS+=\" -DOPENSSL_STATIC_ARMCAP_AES -DOPENSSL_STATIC_ARMCAP_PMULL \"\n    VALGRIND_STATIC_CAP_FLAGS+=\" -DOPENSSL_STATIC_ARMCAP_SHA1 -DOPENSSL_STATIC_ARMCAP_SHA256 \"\n    if [[ $NUM_CPU_PART == $NUM_CPU_THREADS ]] && [[ ${CPU_PART} =~ 0x[dD]40 ]]; then\n      VALGRIND_STATIC_CAP_FLAGS+=\" -DOPENSSL_STATIC_ARMCAP_SHA3 -DOPENSSL_STATIC_ARMCAP_NEOVERSE_V1\"\n    fi\n  fi\nfi\n\n# Pick cmake3 if possible. We don't know of any OS that installs a cmake3\n# executable that is not at least version 3.0.\nif [[ -x \"$(command -v cmake3)\" ]] ; then\n  CMAKE_COMMAND=\"cmake3\"\nelse\n  CMAKE_COMMAND=\"cmake\"\nfi\n\nfunction run_build {\n  local cflags=(\"$@\")\n  rm -rf \"$BUILD_ROOT\"\n  mkdir -p \"$BUILD_ROOT\"\n  cd \"$BUILD_ROOT\" || exit 1\n\n  if [[ \"${AWSLC_32BIT}\" == \"1\" ]]; then\n    cflags+=(\"-DCMAKE_TOOLCHAIN_FILE=${SRC_ROOT}/util/32-bit-toolchain.cmake\")\n  fi\n\n  if [[ -x \"$(command -v ninja)\" ]]; then\n    echo \"Using Ninja build system (ninja).\"\n    BUILD_COMMAND=\"ninja\"\n    cflags+=(-GNinja)\n  elif [[ -x \"$(command -v ninja-build)\" ]]; then\n    echo \"Using Ninja build system (ninja-build).\"\n    BUILD_COMMAND=\"ninja-build\"\n    cflags+=(-GNinja)\n  else\n    echo \"Using Make.\"\n    BUILD_COMMAND=\"make -j${NUM_CPU_THREADS}\"\n  fi\n\n  ${CMAKE_COMMAND} \"${cflags[@]}\" \"$SRC_ROOT\"\n  $BUILD_COMMAND\n  cd \"$SRC_ROOT\"\n}\n\nfunction run_cmake_custom_target {\n  $BUILD_COMMAND -C \"$BUILD_ROOT\" \"$@\"\n}\n\nfunction build_and_test {\n  run_build \"$@\"\n  run_cmake_custom_target 'run_tests'\n}\n\nfunction generate_symbols_file {\n  # read_symbols.go currently only support static libraries\n  if [ ! -f  \"$BUILD_ROOT\"/crypto/libcrypto.a ]; then\n    echo \"Static library not found: ${BUILD_ROOT}/crypto/libcrypto.a\"\n    exit 1\n  fi\n\n  go run \"$SRC_ROOT\"/util/read_symbols.go -out \"$BUILD_ROOT\"/symbols_crypto.txt \"$BUILD_ROOT\"/crypto/libcrypto.a\n  go run \"$SRC_ROOT\"/util/read_symbols.go -out \"$BUILD_ROOT\"/symbols_ssl.txt \"$BUILD_ROOT\"/ssl/libssl.a\n\n  # The $BUILD_ROOT gets deleted on each run. symbols.txt must be placed elsewhere.\n  cat \"$BUILD_ROOT\"/symbols_crypto.txt  \"$BUILD_ROOT\"/symbols_ssl.txt >  \"$SRC_ROOT\"/symbols.txt\n}\n\n\nfunction verify_symbols_prefixed {\n  go run \"$SRC_ROOT\"/util/read_symbols.go -out \"$BUILD_ROOT\"/symbols_final_crypto.txt \"$BUILD_ROOT\"/crypto/libcrypto.a\n  go run \"$SRC_ROOT\"/util/read_symbols.go -out \"$BUILD_ROOT\"/symbols_final_ssl.txt \"$BUILD_ROOT\"/ssl/libssl.a\n  # For grep's basic regular expression language the meta-characters (e.g. \"?\",\n  # \"|\", etc.) are interpreted as literal characters. To keep their\n  # meta-character semantics, they must be escaped with \"\\\".\n  # Deciphering the pattern \"^_\\?\\(bignum\\|curve25519_x25519\\)\":\n  #  * \"^\": anchor at start of line.\n  #  * \"_\\?\": might contain underscore.\n  #  * \"\\(bignum\\|curve25519_x25519\\)\": match string of either \"bignum\" or \"curve25519_x25519\".\n  # Recall that the option \"-v\" reverse the pattern matching. So, we are really\n  # filtering out lines that contain either \"bignum\" or \"curve25519_x25519\".\n  cat \"$BUILD_ROOT\"/symbols_final_crypto.txt  \"$BUILD_ROOT\"/symbols_final_ssl.txt | grep -v -e '^_\\?\\(bignum\\|curve25519_x25519\\)' >  \"$SRC_ROOT\"/symbols_final.txt\n  # Now filter out every line that has the unique prefix $CUSTOM_PREFIX. If we\n  # have any lines left, then some symbol(s) weren't prefixed, unexpectedly.\n  if [ $(grep -c -v ${CUSTOM_PREFIX}  \"$SRC_ROOT\"/symbols_final.txt) -ne 0 ]; then\n    echo \"Symbol(s) missing prefix!\"\n    exit 1\n  fi\n}\n\n\nfunction build_prefix_and_test {\n  CUSTOM_PREFIX=aws_lc_1_1_0\n  run_build \"$@\"\n  generate_symbols_file\n  run_build \"$@\" \"-DBORINGSSL_PREFIX=${CUSTOM_PREFIX}\" \"-DBORINGSSL_PREFIX_SYMBOLS=${SRC_ROOT}/symbols.txt\"\n  verify_symbols_prefixed\n  run_cmake_custom_target 'run_tests'\n}\n\nfunction fips_build_and_test {\n  run_build \"$@\" -DFIPS=1\n  # Upon completion of the build process. The module\u00e2\u20ac\u2122s status can be verified by 'tool/bssl isfips'.\n  # https://csrc.nist.gov/CSRC/media/projects/cryptographic-module-validation-program/documents/security-policies/140sp3678.pdf\n  # FIPS mode is enabled when 'defined(BORINGSSL_FIPS) && !defined(OPENSSL_ASAN)'.\n  # https://github.com/aws/aws-lc/blob/220e266d4e415cf0101388b89a2bd855e0e4e203/crypto/fipsmodule/is_fips.c#L22\n  expect_fips_mode=1\n  for build_flag in \"$@\"\n  do\n    if [[ \"${build_flag}\" == '-DASAN=1' ]]; then\n      expect_fips_mode=0\n      break\n    fi\n  done\n  module_status=$(\"${BUILD_ROOT}/tool/bssl\" isfips)\n  [[ \"${expect_fips_mode}\" == \"${module_status}\" ]] || { echo >&2 \"FIPS Mode validation failed.\"; exit 1; }\n  # Run tests.\n  run_cmake_custom_target 'run_tests'\n  \"${BUILD_ROOT}/util/fipstools/test_fips\"\n}\n\nfunction build_and_test_valgrind {\n  if [[ $PLATFORM == \"aarch64\" ]]; then\n    run_build \"$@\" -DCMAKE_C_FLAGS=\"$VALGRIND_STATIC_CAP_FLAGS\"\n    run_cmake_custom_target 'run_tests_valgrind'\n\n    # Disable all capabilities and run again\n    # (We don't use the env. variable OPENSSL_armcap because it is currently\n    #  restricted to the case of runtime discovery of capabilities\n    #  in cpu_aarch64_linux.c)\n    run_build \"$@\" -DCMAKE_C_FLAGS=\"-DOPENSSL_STATIC_ARMCAP\"\n    run_cmake_custom_target 'run_tests_valgrind'\n  else\n    run_build \"$@\"\n    run_cmake_custom_target 'run_tests_valgrind'\n  fi\n}\n\nfunction build_and_test_ssl_runner_valgrind {\n  export AWS_LC_GO_TEST_TIMEOUT=\"60m\"\n\n  if [[ $PLATFORM == \"aarch64\" ]]; then\n    run_build \"$@\" -DCMAKE_C_FLAGS=\"$VALGRIND_STATIC_CAP_FLAGS\"\n  else\n    run_build \"$@\"\n  fi\n    run_cmake_custom_target 'run_ssl_runner_tests_valgrind'\n}\n\nfunction build_and_test_with_sde {\n  run_build \"$@\"\n  run_cmake_custom_target 'run_tests_with_sde'\n}\n\nfunction build_and_run_minimal_test {\n  run_build \"$@\"\n  run_cmake_custom_target 'run_minimal_tests'\n}\n\n# Install local build of AWS-LC for integration testing.\nfunction aws_lc_build() {\n  AWS_LC_DIR=${1}\n  BUILD_FOLDER=${2}\n  INSTALL_FOLDER=${3}\n\n  echo \"Building AWS-LC to ${BUILD_FOLDER} and installing to ${INSTALL_FOLDER} with CFlags \"${@:4}\"\"\n  ${CMAKE_COMMAND} ${AWS_LC_DIR} -GNinja \"-B${BUILD_FOLDER}\" \"-DCMAKE_INSTALL_PREFIX=${INSTALL_FOLDER}\" \"${@:4}\"\n  ninja -C ${BUILD_FOLDER} install\n  ls -R ${INSTALL_FOLDER}\n  rm -rf ${BUILD_FOLDER:?}/*\n}\n\nfunction print_executable_information {\n  EXE_NAME=${1}\n  EXE_ARGUMENT=${2}\n  LABEL=${3}\n\n  echo \"\"\n  echo \"${LABEL}:\"\n  if command -v ${EXE_NAME} &> /dev/null\n  then\n    ${EXE_NAME} ${EXE_ARGUMENT}\n  else\n    echo \"${EXE_NAME} not found\"\n  fi\n}\n\nprint_executable_information \"cmake\" \"--version\" \"CMake version\"\nprint_executable_information \"cmake3\" \"--version\" \"CMake version (cmake3 executable)\"\nprint_executable_information \"go\" \"version\" \"Go version\"\nprint_executable_information \"perl\" \"--version\" \"Perl version\"\n# Ninja executable names are not uniform over operating systems\nprint_executable_information \"ninja-build\" \"--version\" \"Ninja version (ninja-build executable)\"\nprint_executable_information \"ninja\" \"--version\" \"Ninja version (ninja executable)\"\nprint_executable_information \"gcc\" \"--version\" \"gcc version\"\nprint_executable_information \"g++\" \"--version\" \"g++ version\"\nprint_executable_information \"clang\" \"--version\" \"clang version\"\nprint_executable_information \"clang++\" \"--version\" \"clang++ version\"\nprint_executable_information \"cc\" \"--version\" \"cc version\"\nprint_executable_information \"c++\" \"--version\" \"c++ version\"\nprint_executable_information \"make\" \"--version\" \"Make version\"\nprint_executable_information \"rustup\" \"show\" \"Rust toolchain\"\necho \"\"\necho \"Operating system information:\"\nuname -a\necho \"\"\necho \"Environment variables:\"\nenv\n", "num_lines": 245}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n#$1 is the prefix for the ssm document, echos the doc name so we can capture the output\ncreate_ssm_document() {\n  local doc_name\n  doc_name=\"$1\"_ssm_document_\"${CODEBUILD_SOURCE_VERSION}\"\n  aws ssm create-document --content file://tests/ci/cdk/cdk/ssm/\"$1\"_ssm_document.yaml \\\n    --name \"${doc_name}\" \\\n    --document-type Command \\\n    --document-format YAML >/dev/null\n  echo \"${doc_name}\"\n}\n\n#$1 is the document name, $2 is the instance ids, $3 is the cloudwatch log group name.\nfunction run_ssm_command() {\n  local command_id\n  command_id=\"$(aws ssm send-command --instance-ids \"${2}\" \\\n    --document-name \"${1}\" \\\n    --cloud-watch-output-config CloudWatchLogGroupName=\"${3}\",CloudWatchOutputEnabled=true \\\n    --query Command.CommandId --output text)\"\n  echo \"${command_id}\"\n}\n", "num_lines": 24}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -exuo pipefail\n\n# -e: Exit on any failure\n# -x: Print the command before running\n# -u: Any variable that is not set will cause an error if used\n# -o pipefail: Makes sure to exit a pipeline with a non-zero error code if any command in the pipeline exists with a\n#              non-zero error code.\n\n# Device Farm project to designate Device Farm runs. The two device pools defined below should also belong to this project.\nAWSLC_DEVICEFARM_PROJECT='arn:aws:devicefarm:us-west-2:620771051181:project:d1e78543-a776-49c5-9452-9a2b3448b728'\n# Device pool arn for FIPS.\nAWSLC_FIPS_DEVICEFARM_DEVICE_POOL='arn:aws:devicefarm:us-west-2:620771051181:devicepool:d1e78543-a776-49c5-9452-9a2b3448b728/4726586b-cdbc-4dc0-98a5-38e7448e3691'\n# Device pool arn for non-FIPS.\nAWSLC_NON_FIPS_DEVICEFARM_DEVICE_POOL='arn:aws:devicefarm:us-west-2:620771051181:devicepool:d1e78543-a776-49c5-9452-9a2b3448b728/4e72604c-86eb-41b6-9383-7797c04328b4'\n\n###########################\n# Main and related helper #\n###########################\n\nfunction script_helper() {\n  cat <<EOF\nThis script helps compile AWSLCAndroidTestRunner and kick off the device farm python script with the arguments needed.\n\nOptions:\n    --help                          Displays this help menu\n    --test-name\t\t\t\t\t\t          Name of current test.\n    --devicefarm-project-arn        The devicefarm project's arn. Default to team account's.\n    --devicefarm-device-pool-arn    The device pool's arn.\n    --fips                          If we're compiling for FIPS or not. Will always compile for the FIPS, shared, release build.\n    --release                       If we're compiling for Release or Debug.\n    --shared                        If we're compiling for Shared or Static.\n    --action                        Required. The value can be:\n\t                                   'start-job': kicks off a device farm job.\nEOF\n}\n\nfunction export_global_variables() {\n  # If these variables are not set or empty, defaults are exported, but the |main-apk| and |test-apk| must be set.\n  if [[ -z \"${ANDROID_TEST_NAME+x}\" || -z \"${ANDROID_TEST_NAME}\" ]]; then\n    export ANDROID_TEST_NAME='AWS-LC Android Test'\n  fi\n  if [[ -z \"${DEVICEFARM_PROJECT+x}\" || -z \"${DEVICEFARM_PROJECT}\" ]]; then\n    export DEVICEFARM_PROJECT=$AWSLC_DEVICEFARM_PROJECT\n  fi\n  if [[ -z \"${FIPS+x}\" || -z \"${FIPS}\" ]]; then\n    export FIPS=false\n  fi\n  if [[ -z \"${RELEASE+x}\" || -z \"${RELEASE}\" ]]; then\n    export RELEASE=false\n  fi\n  if [[ -z \"${SHARED+x}\" || -z \"${SHARED}\" ]]; then\n    export SHARED=false\n  fi\n  if [[ -z \"${DEVICEFARM_DEVICE_POOL+x}\" || -z \"${DEVICEFARM_DEVICE_POOL}\" ]]; then\n    if [[ \"${FIPS}\" = true ]]; then\n      # Device pool arn for FIPS.\n      export DEVICEFARM_DEVICE_POOL=$AWSLC_FIPS_DEVICEFARM_DEVICE_POOL\n    else\n      # Device pool arn for non-FIPS.\n      export DEVICEFARM_DEVICE_POOL=$AWSLC_NON_FIPS_DEVICEFARM_DEVICE_POOL\n    fi\n  fi\n  if [[ -z \"${AWS_REGION+x}\" || -z \"${AWS_REGION}\" ]]; then\n    export AWS_REGION='us-west-2'\n  fi\n}\n\nfunction compile_for_android() {\n  # |ANDROID_APK| and |ANDROID_TEST_APK| are apk names corresponding to the settings in the test runner gradle file.\n  # The working directory of this script should under `tests/ci`. \n  # AWSLCAndroidTestRunner should be at `tests/ci/android/AWSLCAndroidTestRunner`.\n  pushd android/AWSLCAndroidTestRunner\n  export ANDROID_APK_LOCATION='android/AWSLCAndroidTestRunner/app/build/outputs/apk'\n  if [[ \"${FIPS}\" = true ]]; then\n    if [[ \"${SHARED}\" = true ]]; then\n      # FIPS (Release Shared)\n      ./gradlew assembleDebug assembleAndroidTest -PFIPS -PShared --offline\n    else\n      # FIPS (Release Static), go dependencies need to be copied from AWS-LC.\n      mkdir app/src/main/cpp/util\n      cp -r ../../../../util/godeps.go app/src/main/cpp/util/godeps.go\n      cp -r ../../../../go.mod app/src/main/cpp/go.mod\n      cp -r ../../../../go.sum app/src/main/cpp/go.sum\n      ./gradlew assembleDebug assembleAndroidTest -PFIPS --offline\n    fi\n    export ANDROID_APK=\"${ANDROID_APK_LOCATION}/debug/awslc_fips.apk\"\n    export ANDROID_TEST_APK=\"${ANDROID_APK_LOCATION}/androidTest/debug/awslc_fips-androidTest.apk\"\n  else\n    if [[ \"${RELEASE}\" = true ]]; then\n      if [[ \"${SHARED}\" = true ]]; then\n        # Release Shared\n        ./gradlew assembleDebug assembleAndroidTest -PRelease -PShared --offline\n        export ANDROID_APK=\"${ANDROID_APK_LOCATION}/debug/awslc_shared_rel.apk\"\n        export ANDROID_TEST_APK=\"${ANDROID_APK_LOCATION}/androidTest/debug/awslc_shared_rel-androidTest.apk\"\n      else\n        # Release Static\n        ./gradlew assembleDebug assembleAndroidTest -PRelease --offline\n        export ANDROID_APK=\"${ANDROID_APK_LOCATION}/debug/awslc_static_rel.apk\"\n        export ANDROID_TEST_APK=\"${ANDROID_APK_LOCATION}/androidTest/debug/awslc_static_rel-androidTest.apk\"\n      fi\n    else\n      if [[ \"${SHARED}\" = true ]]; then\n        # Debug Shared\n        ./gradlew assembleDebug assembleAndroidTest -PShared --offline\n        export ANDROID_APK=\"${ANDROID_APK_LOCATION}/debug/awslc_shared_dbg.apk\"\n        export ANDROID_TEST_APK=\"${ANDROID_APK_LOCATION}/androidTest/debug/awslc_shared_dbg-androidTest.apk\"\n      else\n        # Debug Static\n        ./gradlew assembleDebug assembleAndroidTest --offline\n        export ANDROID_APK=\"${ANDROID_APK_LOCATION}/debug/awslc_static_dbg.apk\"\n        export ANDROID_TEST_APK=\"${ANDROID_APK_LOCATION}/androidTest/debug/awslc_static_dbg-androidTest.apk\"\n      fi\n    fi\n  fi\n  popd\n}\n\nfunction main() {\n  # parse arguments.\n  while [[ $# -gt 0 ]]; do\n    case ${1} in\n    --help)\n      script_helper\n      exit 0\n      ;;\n    --test-name)\n      export ANDROID_TEST_NAME=\"${2}\"\n      shift\n      ;;\n    --devicefarm-project-arn)\n      export DEVICEFARM_PROJECT=\"${2}\"\n      shift\n      ;;\n    --devicefarm-device-pool-arn)\n      export DEVICEFARM_DEVICE_POOL=\"${2}\"\n      shift\n      ;;\n    --fips)\n      export FIPS=\"${2}\"\n      shift\n      ;;\n    --release)\n      export RELEASE=\"${2}\"\n      shift\n      ;;\n    --shared)\n      export SHARED=\"${2}\"\n      shift\n      ;;\n    --action)\n      export ACTION=\"${2}\"\n      shift\n      ;;\n    *)\n      echo \"${1} is not supported.\"\n      exit 1\n      ;;\n    esac\n    # Check next option -- key/value.\n    shift\n  done\n\n  # Make sure action is set.\n  if [[ -z \"${ACTION+x}\" || -z \"${ACTION}\" ]]; then\n    echo \"${ACTION} is required input.\"\n    exit 1\n  fi\n\n  # Export global variables, which provides the contexts needed by ci setup/destroy.\n  export_global_variables\n\n  # Execute the action.\n  case ${ACTION} in\n  start-job)\n    compile_for_android\n    python3 -u ./devicefarm_job.py\n    ;;\n  *)\n    echo \"--action is required. Use '--help' to see allowed actions.\"\n    exit 1\n    ;;\n  esac\n}\n\n# Invoke main\nmain \"$@\"", "num_lines": 191}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\n# The build and test time is not meant to be scientific benchmark, just to get a rough sense of changes overtime.\n# In case there is a weird change over time this recorded additional information about the host to the logs.\nlscpu\n\nbranch=$(echo \"$CODEBUILD_WEBHOOK_TRIGGER\" | cut -d '/' -f2)\ncommon_dimensions=\"Branch=${branch}\"\n\ncommit_timestamp=$(git show -s --format=%ct)\n\nfunction put_metric {\n  # This call to publish the metric could fail but we don't want to fail the build +e turns off exit on error\n  set +e\n  aws cloudwatch put-metric-data \\\n    --timestamp \"$commit_timestamp\" \\\n    --namespace AWS-LC \\\n    \"$@\" || echo \"Publishing metric failed, continuing with the rest of the build\"\n  # Turn it back on for the rest of the build\n  set -e\n}\n\n# Return the size of an object or total for the folder (summarize)\nfunction size {\n  du --bytes --apparent-size --summarize \"$@\" | cut -f1\n}\n\nSOURCE_CODE_SIZE=$(size \"$SRC_ROOT\")\nput_metric --metric-name FolderSize --value \"$SOURCE_CODE_SIZE\" --unit Bytes --dimensions \"Folder=root,${common_dimensions}\"\n\nfor FOLDER_PATH in \"$SRC_ROOT\"/*/ ; do\n    FOLDER_SIZE=$(size \"$FOLDER_PATH\")\n    FOLDER=$(basename \"$FOLDER_PATH\")\n    put_metric --metric-name FolderSize --value \"$FOLDER_SIZE\" --unit Bytes --dimensions \"Folder=${FOLDER},${common_dimensions}\"\ndone\n\nfunction run_build_and_collect_metrics {\n  cmake_build_flags=(\"-DCMAKE_BUILD_TYPE=Release\")\n  if [[ \"$small\" == \"ON\" ]]; then\n    build_size=\"Small\"\n    cmake_build_flags+=(\"-DOPENSSL_SMALL=1\")\n  else\n    build_size=\"Large\"\n  fi\n  if [[ \"$no_assembly\" == \"ON\" ]]; then\n    assembly=\"NoAsm\"\n    cmake_build_flags+=(\"-DOPENSSL_NO_ASM=1\")\n  else\n    assembly=\"Asm\"\n  fi\n\n  cmake_build_flags+=(\"-DBUILD_SHARED_LIBS=${shared_library}\")\n  if [[ \"$shared_library\" == \"ON\" ]]; then\n    linking=\"Shared\"\n    lib_extension=\"so\"\n  else\n    linking=\"Static\"\n    lib_extension=\"a\"\n  fi\n  if [[ \"$fips\" == \"ON\" ]]; then\n    fips_mode=\"FIPS\"\n    cmake_build_flags+=(\"-DFIPS=1\")\n  else\n    fips_mode=\"NotFIPS\"\n  fi\n  size_common_dimensions=\"${common_dimensions},Optimization=Release,BuildSize=${build_size},Assembly=${assembly},CPU=${PLATFORM},Linking=${linking},FIPS=${fips_mode}\"\n\n  build_start=$(date +%s)\n  run_build \"${cmake_build_flags[@]}\"\n  build_end=$(date +%s)\n  build_time=$((build_end-build_start))\n  put_metric --metric-name BuildTime --value \"$build_time\" --unit Seconds --dimensions \"$size_common_dimensions\"\n\n  test_start=$(date +%s)\n  run_cmake_custom_target 'run_tests'\n  test_end=$(date +%s)\n  test_time=$((test_end-test_start))\n  put_metric --metric-name TestTime --value \"$test_time\" --unit Seconds --dimensions \"$size_common_dimensions\"\n\n  libcrypto_size=$(size \"${BUILD_ROOT}/crypto/libcrypto.${lib_extension}\")\n  libssl_size=$(size \"${BUILD_ROOT}/ssl/libssl.${lib_extension}\")\n  tool_size=$(size \"${BUILD_ROOT}/tool/bssl\")\n  put_metric --metric-name LibCryptoSize --value \"$libcrypto_size\" --unit Bytes --dimensions \"${size_common_dimensions}\"\n  put_metric --metric-name LibSSLSize --value \"$libssl_size\" --unit Bytes --dimensions \"${size_common_dimensions}\"\n  put_metric --metric-name ToolSize --value \"$tool_size\" --unit Bytes --dimensions \"${size_common_dimensions}\"\n\n  pushd .\n  cd \"$BUILD_ROOT\"\n  for file_path in $(find . -type f -name \"*.o\"); do\n    object_size=$(size \"${BUILD_ROOT}/${file_path}\")\n    # Cleanup the file names ./crypto/fipsmodule/CMakeFiles/fipsmodule.dir/bcm.c.o -> crypto/fipsmodule/bcm.c.o\n    # sed has there own regex format, [[:alpha:]] matches one Alphabetic character\n    file_name=$(sed -e \"s/CMakeFiles\\///g\" -e \"s/[[:alpha:]]*\\.dir\\///g\" <<< \"$file_path\" | cut -c 3-)\n    put_metric --metric-name ObjectSize --value \"$object_size\" --unit Bytes --dimensions \"File=${file_name},${size_common_dimensions}\"\n  done\n  popd\n}\n\nfips=OFF\nfor shared_library in ON OFF; do\n  for small in ON OFF; do\n    for no_assembly in ON OFF; do\n      run_build_and_collect_metrics\n    done\n  done\ndone\n\n# We only care about two FIPS dimensions\nshared_library=ON\nsmall=OFF\nno_assembly=OFF\nfips=ON\nrun_build_and_collect_metrics\n\n# The static FIPS build only works on Linux platforms.\nif [[ (\"$(uname -s)\" == 'Linux'*) && ((\"$(uname -p)\" == 'x86_64'*) || (\"$(uname -p)\" == 'aarch64'*)) ]]; then\n  shared_library=OFF\n  run_build_and_collect_metrics\nfi\n", "num_lines": 125}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\ninstall_dir=\"$(pwd)/../libcrypto_install_dir\"\nopenssl_url='https://github.com/openssl/openssl.git'\nopenssl_1_1_branch='OpenSSL_1_1_1-stable'\nopenssl_1_0_branch='OpenSSL_1_0_2-stable'\n# OpenSSL 3.0 branch still isn't stable yet, so we lock down\n# a tag to prevent build failures that they introduced from\n# failing our CI.\nopenssl_3_0_branch='openssl-3.0.5'\n\nfunction build_aws_lc_fips {\n  echo \"building aws-lc in FIPS mode\"\n  run_build \\\n      -DCMAKE_INSTALL_PREFIX=\"${install_dir}/aws-lc-fips\" \\\n      -DFIPS=1 \\\n      -DENABLE_DILITHIUM=ON \\\n      -DCMAKE_BUILD_TYPE=RelWithDebInfo\n  pushd \"$BUILD_ROOT\"\n  ninja install\n  popd\n}\n\nfunction build_openssl_1_0 {\n    echo \"building OpenSSL 1.0\"\n    git clone --depth 1 --branch \"${openssl_1_0_branch}\" \"${openssl_url}\" \"../openssl-1.0\"\n    pushd \"../openssl-1.0\"\n    mkdir -p \"${install_dir}/openssl-1.0\"\n    ./config --prefix=\"${install_dir}/openssl-1.0\" --openssldir=\"${install_dir}/openssl-1.0\" -d\n    make \"-j${NUM_CPU_THREADS}\" > /dev/null\n    make install_sw\n    popd\n    rm -rf \"../openssl-1.0\"\n}\n\nfunction build_openssl_1_1 {\n    echo \"building OpenSSL 1.1\"\n    git clone --depth 1 --branch \"${openssl_1_1_branch}\" \"${openssl_url}\" \"../openssl-1.1\"\n    pushd \"../openssl-1.1\"\n    mkdir -p \"${install_dir}/openssl-1.1\"\n    ./config --prefix=\"${install_dir}/openssl-1.1\" --openssldir=\"${install_dir}/openssl-1.1\" -d\n    make \"-j${NUM_CPU_THREADS}\" > /dev/null\n    make install_sw\n    popd\n    rm -rf \"../openssl-1.1\"\n}\n\nfunction build_openssl_3_0 {\n    echo \"building OpenSSL 3.0\"\n    git clone --depth 1 --branch \"${openssl_3_0_branch}\" \"${openssl_url}\" \"../openssl-3.0\"\n    pushd \"../openssl-3.0\"\n    mkdir -p \"${install_dir}/openssl-3.0\"\n    ./Configure --prefix=\"${install_dir}/openssl-3.0\" --openssldir=\"${install_dir}/openssl-3.0\" -d\n    make \"-j${NUM_CPU_THREADS}\" > /dev/null\n    make install_sw\n    popd\n    rm -rf \"../openssl-3.0\"\n}\n\n# We build each tool individually so we can have more insight into what is failing\n\n# Building AWS-LC always builds bssl (which includes the speed tool) with the \"local\" libcrypto. We\n# also support building speed.cc with an \"external\" aws-lc libcrypto (and openssl). This is useful\n# when we want to compare the performance of a particular FIPS release against mainline if mainline\n# has changes in speed.cc that could affect the comparison of the FIPS to non-FIPS, or if new\n# algorithms have been added to speed.cc\nbuild_aws_lc_fips\necho \"Testing awslc_bm with AWS-LC FIPS\"\nrun_build -DAWSLC_INSTALL_DIR=\"${install_dir}/aws-lc-fips\" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo\n\"${BUILD_ROOT}/tool/awslc_bm\"\n\n# Run the \"local\" benchmark that was built with the AWS-LC FIPS benchmark, only do this once because this tool\n# is always the same regardless of what additional external libcrypto is built\n\"${BUILD_ROOT}/tool/bssl\" speed\n\nbuild_openssl_1_0\necho \"Testing ossl_bm with OpenSSL 1.0\"\nrun_build -DOPENSSL_1_0_INSTALL_DIR=\"${install_dir}/openssl-1.0\" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo\n\"${BUILD_ROOT}/tool/ossl_1_0_bm\"\n\nbuild_openssl_1_1\necho \"Testing ossl_bm with OpenSSL 1.1\"\nrun_build -DOPENSSL_1_1_INSTALL_DIR=\"${install_dir}/openssl-1.1\" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo\n\"${BUILD_ROOT}/tool/ossl_1_1_bm\"\n\nbuild_openssl_3_0\necho \"Testing ossl_bm with OpenSSL 3.0\"\nrun_build -DOPENSSL_3_0_INSTALL_DIR=\"${install_dir}/openssl-3.0\" -DASAN=1 -DCMAKE_BUILD_TYPE=RelWithDebInfo\n\"${BUILD_ROOT}/tool/ossl_3_0_bm\"\n", "num_lines": 94}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Please run from project root folder!\n# You'll want to set the codebuild env variables set if running locally\nsource tests/ci/common_ssm_setup.sh\n\n# cleanup code\ncleanup() {\n  set +e\n  # kill ec2 instances after we're done w/ them\n  for id in ${instance_ids};do\n    aws ec2 terminate-instances --instance-ids \"${id}\"\n  done\n\n  # delete the various documents that we created\n  for name in ${ssm_document_names};do\n    aws ssm delete-document --name \"${name}\"\n  done\n}\n\n# we wanna run the cleanup code on exit\ntrap cleanup EXIT\n\n# print some information for reference\necho GitHub PR Number: \"${CODEBUILD_WEBHOOK_TRIGGER}\"\necho GitHub Commit Version: \"${CODEBUILD_SOURCE_VERSION}\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\necho AWS Account ID: \"${AWS_ACCOUNT_ID}\"\necho GitHub Repo Link: \"${CODEBUILD_SOURCE_REPO_URL}\"\n\n# get information for ec2 instances\nvpc_id=\"$(aws ec2 describe-vpcs --filter Name=tag:Name,Values=aws-lc-ci-bm-framework/aws-lc-ci-bm-framework-ec2-vpc --query Vpcs[*].VpcId --output text)\"\nsg_id=\"$(aws ec2 describe-security-groups --filter Name=vpc-id,Values=\"${vpc_id}\" --filter Name=group-name,Values=bm_framework_ec2_sg --query SecurityGroups[*].GroupId --output text)\"\nsubnet_id=\"$(aws ec2 describe-subnets --filter Name=vpc-id,Values=\"${vpc_id}\" --filter Name=state,Values=available --filter Name=tag:Name,Values=aws-lc-ci-bm-framework/aws-lc-ci-bm-framework-ec2-vpc/PrivateSubnet1 --query Subnets[*].SubnetId --output text)\"\n\n#$1 is nohw type, $2 is OPENSSL_ia32cap value\ngenerate_ssm_document_file() {\n  # use sed to replace placeholder values inside preexisting document\n  sed -e \"s,{AWS_ACCOUNT_ID},${AWS_ACCOUNT_ID},g\" \\\n    -e \"s,{PR_NUM},${CODEBUILD_WEBHOOK_TRIGGER},g\" \\\n    -e \"s,{COMMIT_ID},${CODEBUILD_SOURCE_VERSION},g\" \\\n    -e \"s,{GITHUB_REPO},${CODEBUILD_SOURCE_REPO_URL},g\" \\\n    -e \"s,{OPENSSL_ia32cap},$2,g\" \\\n    -e \"s,{NOHW_TYPE},$1,g\" \\\n    tests/ci/cdk/cdk/ssm/bm_framework_ssm_document.yaml \\\n    >tests/ci/cdk/cdk/ssm/bm_framework_\"$1\"_ssm_document.yaml\n}\n\n# create the ssm documents that will be used for the various ssm commands\ngenerate_ssm_document_file \"\" \"\"\ngenerate_ssm_document_file \"nosha\" \"~0x100000000\"\ngenerate_ssm_document_file \"noavx\" \"~0x1000000000000000:0xC0010020\"\n\n#$1 for ami, $2 for instance-type, echos the instance id so we can capture the output\ncreate_ec2_instances() {\n  local instance_id\n  instance_id=\"$(aws ec2 run-instances --image-id \"$1\" --count 1 \\\n    --instance-type \"$2\" --security-group-ids \"${sg_id}\" --subnet-id \"${subnet_id}\" \\\n    --block-device-mappings 'DeviceName=\"/dev/sda1\",Ebs={DeleteOnTermination=True,VolumeSize=200}' \\\n    --tag-specifications 'ResourceType=\"instance\",Tags=[{Key=\"aws-lc\",Value=\"aws-lc-ci-bm-framework-ec2-x86-instance\"}]' \\\n    --iam-instance-profile Name=aws-lc-ci-bm-framework-ec2-profile \\\n    --placement 'AvailabilityZone=us-west-2a' \\\n    --query Instances[*].InstanceId --output text)\"\n  echo \"${instance_id}\"\n}\n\n# create ec2 instances for x86 and arm\nx86_id=$(create_ec2_instances \"ami-01773ce53581acf22\" \"c5.metal\")\narm_id=$(create_ec2_instances \"ami-018e246d8c0f39ae5\" \"c6g.metal\")\nx86_nosha_id=$(create_ec2_instances \"ami-01773ce53581acf22\" \"m5.metal\")\nx86_noavx_id=$(create_ec2_instances \"ami-01773ce53581acf22\" \"c5.metal\")\ninstance_ids=\"${x86_id} ${arm_id} ${x86_nosha_id} ${x86_noavx_id}\"\n\n# if any of the ids are blank, ec2 creation failed\nif [[ -z \"${x86_id}\" ]] || [[ -z \"${arm_id}\" ]] || [[ -z \"${x86_nosha_id}\" ]] || [[ -z \"${x86_noavx_id}\" ]];  then\n  exit 1\nfi\n\n# Give a few minutes for the ec2 instances to be ready\nsleep 60\n\nfor i in {1..30}; do\n  ready=true\n  for id in ${instance_ids}; do\n    status=$(aws ssm describe-instance-information --filter Key=\"InstanceIds\",Values=\"${id}\" \\\n    --query InstanceInformationList[*].PingStatus --output text)\n    if [ \"${status}\" != Online ]; then\n      ready=false\n    fi\n  done\n  if [ \"${ready}\" = true ]; then\n    break\n  fi\n  echo \"Wait for instances to be able to run the SSM commands\"\n\n  # if we've hit the 30 minute mark and still aren't ready, then something has gone wrong\n  if [ \"${i}\" = 30 ]; then exit 1; fi\n  sleep 60\ndone\n\n# Create, and run ssm command for arm & x86\nssm_doc_name=$(create_ssm_document \"bm_framework_\")\nnosha_ssm_doc_name=$(create_ssm_document \"bm_framework_nosha\")\nnoavx_ssm_doc_name=$(create_ssm_document \"bm_framework_noavx\")\nssm_document_names=\"${ssm_doc_name} ${nosha_ssm_doc_name} ${noavx_ssm_doc_name}\"\n\n# delete contents of 'latest' folders before uploading anything new to them\naws s3 rm s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-pr-bucket/latest-${CODEBUILD_WEBHOOK_TRIGGER}\" --recursive\naws s3 rm s3://\"${AWS_ACCOUNT_ID}-aws-lc-ci-bm-framework-prod-bucket/latest\" --recursive\n\ncloudwatch_group_name=\"aws-lc-ci-bm-framework-cw-logs\"\nx86_ssm_command_id=$(run_ssm_command \"${ssm_doc_name}\" \"${x86_id}\" \"${cloudwatch_group_name}\")\narm_ssm_command_id=$(run_ssm_command \"${ssm_doc_name}\" \"${arm_id}\" \"${cloudwatch_group_name}\")\nnosha_ssm_command_id=$(run_ssm_command \"${nosha_ssm_doc_name}\" \"${x86_nosha_id}\" \"${cloudwatch_group_name}\")\nnoavx_ssm_command_id=$(run_ssm_command \"${noavx_ssm_doc_name}\" \"${x86_noavx_id}\" \"${cloudwatch_group_name}\")\nssm_command_ids=\"${x86_ssm_command_id} ${arm_ssm_command_id} ${nosha_ssm_command_id} ${noavx_ssm_command_id}\"\n\n# Give some time for the commands to run\nfor i in {1..30}; do\n  echo \"${i}: Continue to wait 3 min for SSM commands to finish.\"\n  sleep 180\n  done=true\n  success=true\n  # for each command, check its status\n  for id in ${ssm_command_ids}; do\n    ssm_command_status=\"$(aws ssm list-commands --command-id \"${id}\" --query Commands[*].Status --output text)\"\n    ssm_target_count=\"$(aws ssm list-commands --command-id \"${id}\" --query Commands[*].TargetCount --output text)\"\n    ssm_completed_count=\"$(aws ssm list-commands --command-id \"${id}\" --query Commands[*].CompletedCount --output text)\"\n    if [[ ${ssm_command_status} == 'Success' && ${ssm_completed_count} == \"${ssm_target_count}\" ]]; then\n      echo \"SSM command ${id} finished successfully.\"\n    elif [[ ${ssm_command_status} == 'Failed' && ${ssm_completed_count} == \"${ssm_target_count}\" ]]; then\n      echo \"SSM command ${id} failed.\"\n      success=false\n    else\n      done=false\n    fi\n  done\n\n  # if after the loop finish and done is still true, then we're done\n  if [ \"${done}\" = true ]; then\n    echo \"All SSM commands have finished.\"\n\n    # if success is still true here, then none of the commands failed\n    if [ \"${success}\" != true ]; then\n      echo \"An SSM command failed!\"\n      exit 1\n    fi\n    break\n  fi\ndone\n", "num_lines": 154}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Sourcing these files check for environment variables which may be unset so wait to enable -u\nsource tests/ci/common_fuzz.sh\nsource \"${FUZZ_ROOT}/fuzz_env.sh\"\n# After loading everything any undefined variables should fail the build\nset -u\n\nrm -rf \"$BUILD_ROOT\"\nmkdir -p \"$BUILD_ROOT\"\ncd \"$BUILD_ROOT\"\n\n# Build AWS-LC based on https://github.com/guidovranken/cryptofuzz/blob/master/docs/openssl.md\n${CMAKE_COMMAND} -DCMAKE_CXX_FLAGS=\"$CXXFLAGS\" -DCMAKE_C_FLAGS=\"$CFLAGS\" -DBORINGSSL_ALLOW_CXX_RUNTIME=1 \\\n  -GNinja -DBUILD_TESTING=OFF -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=RelWithDebInfo ../\nninja\ncd ../\n\n# CRYPTOFUZZ_AWSLC will enable AES_256_XTS in upstream code. See `V610453347`.\n# TODO: remove CRYPTOFUZZ_BORINGSSL when CRYPTOFUZZ_AWSLC is fully integrated.\nexport CXXFLAGS=\"$CXXFLAGS -DCRYPTOFUZZ_BORINGSSL -DCRYPTOFUZZ_AWSLC\"\nexport OPENSSL_INCLUDE_PATH=`realpath include/`\nexport OPENSSL_LIBCRYPTO_A_PATH=`realpath ${BUILD_ROOT}/crypto/libcrypto.a`\n\n# For cryptofuzz development only, override CRYPTOFUZZ_SRC with CUSTOM_CRYPTOFUZZ_REPO_DIR.\nCUSTOM_CRYPTOFUZZ_REPO_DIR=''\nif [[ -z \"${CUSTOM_CRYPTOFUZZ_REPO_DIR}\" ]]; then\n  echo \"CUSTOM_CRYPTOFUZZ_REPO_DIR is empty.\"\nelse\n  export CRYPTOFUZZ_SRC=\"${CUSTOM_CRYPTOFUZZ_REPO_DIR}\"\n  # Local development does not need differential fuzzing.\n  # Remove these libs related build flags.\n  export CXXFLAGS=\"${CXXFLAGS// -DCRYPTOFUZZ_BOTAN/}\"\n  export CXXFLAGS=\"${CXXFLAGS// -DCRYPTOFUZZ_CRYPTOPP/}\"\n  cd \"$CRYPTOFUZZ_SRC\"\n  # This step is to generate required header and cpp files.\n  python3 gen_repository.py\nfi\n\n# Build the common OpenSSL module with AWS-LC\ncd \"${CRYPTOFUZZ_SRC}/modules/openssl\"\nmake \"-j${NUM_CPU_THREADS}\"\n\nexport CFLAGS=\"${CFLAGS} -I $OPENSSL_INCLUDE_PATH\"\nexport CXXFLAGS=\"${CXXFLAGS} -I $OPENSSL_INCLUDE_PATH\"\nexport LIBFUZZER_LINK=\"-fsanitize=fuzzer\"\n\n# Build the overall cryptofuzz and generate_corpus binary\ncd \"$CRYPTOFUZZ_SRC\"\nrm -rf cryptofuzz\nrm -rf generate_corpus\nmake \"-j${NUM_CPU_THREADS}\" cryptofuzz generate_corpus\n\n# Common AWS-LC fuzzing setup, the cryptofuzz binary is in this folder so FUZZ_TEST_PATH=FUZZ_NAME\nFUZZ_NAME=\"cryptofuzz\"\nFUZZ_TEST_PATH=\"${CRYPTOFUZZ_SRC}/${FUZZ_NAME}\"\nSRC_CORPUS=\"$CRYPTOFUZZ_SEED_CORPUS\"\n\n# For cryptofuzz development only, uncomment below code to generate new corpus.\n# rm -rf \"$CRYPTOFUZZ_SEED_CORPUS\" && mkdir \"$CRYPTOFUZZ_SEED_CORPUS\"\n# ./generate_corpus \"$CRYPTOFUZZ_SEED_CORPUS\"\n\n# Perform the actual fuzzing. We want the total build time to be about 45 minutes:\n# 5 minutes for building AWS-LC and Cryptofuzz\n# 16 minutes (1000 seconds) of fuzzing\n# 24 minutes of cleanup and merging in new inputs\nTIME_FOR_EACH_FUZZ=1000\n\n# Some fuzz tests can take a while but still pass. This is a tradeoff: less false positive noise, but some inputs that take\n# a long time could lead to a denial of service avenue. We're mostly interested in correctness and memory safety at this\n# time so we're willing to take the fit on fuzz speed\nFUZZ_TEST_TIMEOUT=30\n\n# Call the common fuzzing logic\nrun_fuzz_test\n", "num_lines": 79}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC shared library in FIPS Release mode.\"\nfips_build_and_test -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1\n\n# Static FIPS build works only on Linux platforms.\nif [[ (\"$(uname -s)\" == 'Linux'*) && ((\"$(uname -p)\" == 'x86_64'*) || (\"$(uname -p)\" == 'aarch64'*)) ]]; then\n  echo \"Testing AWS-LC static library in FIPS Release mode.\"\n  fips_build_and_test -DCMAKE_BUILD_TYPE=Release\n\n  echo \"Testing AWS-LC static breakable build\"\n  run_build -DFIPS=1 -DCMAKE_C_FLAGS=\"-DBORINGSSL_FIPS_BREAK_TESTS\"\n  cd $SRC_ROOT\n  ./util/fipstools/test-break-kat.sh\n\n  # These build parameters may be needed by our aws-lc-fips-sys Rust package\n  run_build -DFIPS=1 -DBUILD_LIBSSL=OFF -DBUILD_TESTING=OFF\nfi\n\n# The AL2 version of Clang does not have all of the required artifacts for address sanitizer, see P45594051\nif [[ \"${AWSLC_NO_ASM_FIPS}\" == \"1\" ]]; then\n  if [[ (\"$(uname -p)\" == 'x86_64'*) ]]; then\n    echo \"Building with Clang and testing AWS-LC in FIPS Release mode with address sanitizer.\"\n    fips_build_and_test -DASAN=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1\n  else\n    # See the comment in run_posix_santizers.sh for more context. ASAN on Arm has a huge performance impact on ssl_test\n    # which causes it to take over 2 hours to complete.\n    echo \"Building with Clang and testing AWS-LC in FIPS Release mode with address sanitizer only running crypto_test\"\n    run_build -DFIPS=1 -DASAN=1 -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=1\n    go run util/all_tests.go -build-dir \"$BUILD_ROOT\"\n  fi\nfi\n\necho \"Testing shared AWS-LC in FIPS Debug mode in a different folder.\"\nBUILD_ROOT=$(mktemp -d)\nfips_build_and_test -DCMAKE_BUILD_TYPE=Debug -DBUILD_SHARED_LIBS=1\n", "num_lines": 41}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nAWS_LC_DIR=${PWD##*/}\ncd ../\nROOT=$(pwd)\n\nrm -rf aws-lc-verification-build\ngit clone --recurse-submodules https://github.com/awslabs/aws-lc-verification.git aws-lc-verification-build\ncd aws-lc-verification-build\n# aws-lc-verification has aws-lc as one submodule under 'src' dir.\n# Below is to copy code of **target** aws-lc to 'src' dir.\nrm -rf ./src/* && cp -r \"${ROOT}/${AWS_LC_DIR}/\"* ./src\n# execute the entry to saw scripts.\n./SAW/scripts/docker_entrypoint.sh\ncd ..\nrm -rf aws-lc-verification-build\n", "num_lines": 19}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Sourcing these files check for environment variables which may be unset so wait to enable -u\nsource tests/ci/common_fuzz.sh\n# Running the build also checks for unset variables\nrun_build -DCMAKE_BUILD_TYPE=RelWithDebInfo -DFUZZ=1 -DASAN=1 -DBUILD_TESTING=OFF\n# After loading everything any undefined variables should fail the build\nset -u\n# We want our CI to take about 45 minutes:\n# 2 minutes to build AWS-LC\n# 25 minutes (1500 seconds) for all fuzzing\n# 18 minutes for cleanup and merging files\nif [[ $PLATFORM == \"aarch64\" ]]; then\n  # Arm sanitizers are very slow which causes the clean up time to take longer per\n  # fuzz test, only run for 16 minutes\n  TOTAL_FUZZ_TEST_TIME=1000\nelse\n  TOTAL_FUZZ_TEST_TIME=1500\nfi\n\nFUZZ_TEST_TIMEOUT=5\n\nFUZZ_TESTS=$(find \"${BUILD_ROOT}/fuzz\" -type f -executable)\nNUM_FUZZ_TESTS=$(echo \"$FUZZ_TESTS\" | wc -l)\nTIME_FOR_EACH_FUZZ=$((TOTAL_FUZZ_TEST_TIME/NUM_FUZZ_TESTS))\n\nfor FUZZ_TEST_PATH in $FUZZ_TESTS;do\n  FUZZ_NAME=$(basename \"$FUZZ_TEST_PATH\")\n  SRC_CORPUS=\"${SRC_ROOT}/fuzz/${FUZZ_NAME}_corpus\"\n\n  run_fuzz_test\ndone\n", "num_lines": 36}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\nexport CMAKE_BUILD_PARALLEL_LEVEL=${NUM_CPU_THREADS}\n\n# Set up environment.\n\n# ROOT\n#  |\n#  - AWS_LC_DIR\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - BUILD_DIR\n#    - install-shared\n#    - install-static\n#    - install-both\n#    - MYAPP_SRC\n\n# Assumes script is executed from the root of aws-lc directory\nAWS_LC_DIR=$(pwd)\nROOT=$(realpath ${AWS_LC_DIR}/..)\n\nSCRATCH_DIR=${ROOT}/SCRATCH_AWSLC_INSTALL_SHARED_AND_STATIC\nmkdir -p ${SCRATCH_DIR}\nrm -rf ${SCRATCH_DIR}/*\n\nfunction fail() {\n    echo \"test failure: $1\"\n    exit 1\n}\n\nfunction install_aws_lc() {\n    local INSTALL_DIR=${SCRATCH_DIR}/$1\n    local BUILD_SHARED_LIBS=$2\n\n    local BUILD_DIR=${SCRATCH_DIR}/build\n    rm -rf ${BUILD_DIR}\n    ${CMAKE_COMMAND} -H${AWS_LC_DIR} -B${BUILD_DIR} -GNinja -DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} -DBUILD_TESTING=OFF -D${BUILD_SHARED_LIBS}\n    ${CMAKE_COMMAND} --build ${BUILD_DIR} --target install\n}\n\n# create installation with shared libssl.so/libcrypto.so\ninstall_aws_lc install-shared BUILD_SHARED_LIBS=ON\n\n# create installation with static libssl.a/libcrypto.a\ninstall_aws_lc install-static BUILD_SHARED_LIBS=OFF\n\n# create installation with both shared libssl.so/libcrypto.so and static libssl.a/libcrypto.a\ninstall_aws_lc install-both BUILD_SHARED_LIBS=OFF\ninstall_aws_lc install-both BUILD_SHARED_LIBS=ON\n\n# write out source of a small cmake project, containing:\n# - mylib: a library that uses AWS-LC\n# - myapp: executable that uses mylib\nMYAPP_SRC_DIR=${SCRATCH_DIR}/myapp-src\nrm -rf ${MYAPP_SRC_DIR}\nmkdir -p ${MYAPP_SRC_DIR}\n\ncat <<EOF > ${MYAPP_SRC_DIR}/mylib.c\n#include <openssl/ssl.h>\nvoid mylib_init(void) {\n    OPENSSL_init_ssl(0, NULL);\n}\nEOF\n\ncat <<EOF > ${MYAPP_SRC_DIR}/myapp.c\nextern void mylib_init(void);\nint main() {\n    mylib_init();\n}\nEOF\n\ncat <<EOF > ${MYAPP_SRC_DIR}/CMakeLists.txt\ncmake_minimum_required (VERSION 3.0)\nproject (myapp C)\nadd_library(mylib mylib.c)\nfind_package(ssl REQUIRED)\ntarget_link_libraries(mylib PRIVATE AWS::ssl)\nadd_executable(myapp myapp.c)\ntarget_link_libraries(myapp PRIVATE mylib)\nEOF\n\n# build myapp and mylib, confirm that expected type of libssl and libcrypto are used\nbuild_myapp() {\n    local BUILD_SHARED_LIBS=$1 # (\"BUILD_SHARED_LIBS=ON\" or \"BUILD_SHARED_LIBS=OFF\")\n    local AWS_LC_INSTALL_DIR=$2 # which install dir should be used\n    local EXPECT_USE_LIB_TYPE=$3 # (\".so\" or \".a\") which types of libssl and libcrypto are expected to be used\n\n    local BUILD_DIR=${SCRATCH_DIR}/build\n    rm -rf ${BUILD_DIR}\n\n    cmake -H${MYAPP_SRC_DIR} -B${BUILD_DIR} -GNinja -D${BUILD_SHARED_LIBS} -DCMAKE_PREFIX_PATH=${SCRATCH_DIR}/${AWS_LC_INSTALL_DIR}\n    cmake --build ${BUILD_DIR}\n    ldd ${BUILD_DIR}/myapp\n\n    test_lib_use ${BUILD_DIR}/myapp libssl ${EXPECT_USE_LIB_TYPE}\n    test_lib_use ${BUILD_DIR}/myapp libcrypto ${EXPECT_USE_LIB_TYPE}\n}\n\n# test that app is using expected library\ntest_lib_use() {\n    local APP=$1 # app to examine\n    local LIB_NAME=$2 # name of lib that app should be using, without file extension\n    local EXPECT_USE_LIB_TYPE=$3 # (\".so\" or \".a\") expected type of lib that app should be using\n\n    if ldd ${APP} | grep -q ${LIB_NAME}.so; then\n        local ACTUAL_USE_LIB_TYPE=.so\n    else\n        local ACTUAL_USE_LIB_TYPE=.a\n    fi\n\n    if [ ${ACTUAL_USE_LIB_TYPE} != ${EXPECT_USE_LIB_TYPE} ]; then\n        fail \"used ${LIB_NAME}${ACTUAL_USE_LIB_TYPE}, but expected to use ${LIB_NAME}${EXPECT_USE_LIB_TYPE}\"\n    fi\n}\n\n# if only shared libssl.so/libcrypto.so are available, that's what should get used\nbuild_myapp BUILD_SHARED_LIBS=ON install-shared .so\nbuild_myapp BUILD_SHARED_LIBS=OFF install-shared .so\n\n# if only static libssl.a/libcrypto.a are available, that's what should get used\nbuild_myapp BUILD_SHARED_LIBS=ON install-static .a\nbuild_myapp BUILD_SHARED_LIBS=OFF install-static .a\n\n# if both shared libssl.so/libcrypto.so and static libssl.a/libcrypto.a are available...\nbuild_myapp BUILD_SHARED_LIBS=ON install-both .so # myapp should use libssl.so/libcrypto.so\nbuild_myapp BUILD_SHARED_LIBS=OFF install-both .a # myapp should use libssl.a/libcrypto.a\n\n# ------------------------------------------------------- #\n#           Test for the static library constructor       #\n# ------------------------------------------------------- #\nrm -rf ${MYAPP_SRC_DIR}\nmkdir -p ${MYAPP_SRC_DIR}\n\ncat <<EOF > ${MYAPP_SRC_DIR}/static_constructor_test.c\n#include <stdint.h>\n#include \"openssl/bn.h\"\nextern uint8_t OPENSSL_cpucap_initialized;\nint main() {\n  BIGNUM *a = BN_new();\n  return (OPENSSL_cpucap_initialized == 1 ? 0 : 1);\n}\nEOF\n\n# create installation with static libcrypto.a\ninstall_aws_lc install-static BUILD_SHARED_LIBS=OFF\n\n# compile the test app with libcrypto.a\n${CC} ${MYAPP_SRC_DIR}/static_constructor_test.c ${SCRATCH_DIR}/install-static/lib/libcrypto.a -pthread -I${SCRATCH_DIR}/install-static/include -o ${MYAPP_SRC_DIR}/static_constructor_test\n\n# verify that the test app returns success\n${MYAPP_SRC_DIR}/static_constructor_test || fail \"static library constructor has not been executed\"\n", "num_lines": 158}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\n# gcc 4.1.3 is used in our CI because ubuntu 7.10's `gcc4.1.3` and\n# `GNU assembler 2.18` resembles rhel5's binutils the most. SSE4\n# assembly instructions are not supported in ubuntu 7.04, while rhel5\n# and ubuntu 7.10 do.\necho \"Testing gcc 4.1.2 / 4.1.3 support.\"\n\n# Go is disabled because go tries to fetch from the server when building,\n# but the certificates on the ancient ubuntu are expired and the ancient \n# tools are insufficient to update the certificates.\n# The build flags used are the same as our ancient internal build.\nrun_build  -DDISABLE_GO=ON -DBUILD_TESTING=OFF -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=Debug -DMY_ASSEMBLER_IS_TOO_OLD_FOR_AVX=ON -std=gnu99 -fgnu89-inline\n", "num_lines": 19}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Please run from project root folder!\n# You'll want to set the codebuild env variables set if running locally\nsource tests/ci/common_ssm_setup.sh\n\n# cleanup code\ncleanup() {\n  set +e\n  # delete the various documents that we created\n  for name in ${ssm_document_names};do\n    aws ssm delete-document --name \"${name}\"\n  done\n}\n\n# we wanna run the cleanup code on exit\ntrap cleanup EXIT\n\n# print some information for reference\necho GitHub PR Number: \"${CODEBUILD_WEBHOOK_TRIGGER}\"\necho GitHub Branch Name: \"${CODEBUILD_WEBHOOK_HEAD_REF}\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\necho AWS Account ID: \"${AWS_ACCOUNT_ID}\"\necho GitHub Repo Link: \"${CODEBUILD_SOURCE_REPO_URL}\"\nexport cloudwatch_group_name=\"aws-lc-ci-macos-arm-cw-logs\"\nexport s3_bucket_name=\"aws-lc-codebuild\"\n\n# get information for ec2 instances\nec2_instance=\"$(aws ec2 describe-instances --filter \"Name=tag:Name,Values=aws-lc-ci-macos-arm-ec2-instance\" \"Name=instance-state-name,Values=running\" --query Reservations[*].Instances[*].InstanceId --output text)\"\n\ngenerate_ssm_document_file() {\n  # use sed to replace placeholder values inside preexisting document\n  sed -e \"s,{AWS_ACCOUNT_ID},${AWS_ACCOUNT_ID},g\" \\\n    -e \"s,{PR_NUM},${CODEBUILD_WEBHOOK_TRIGGER//pr\\/},g\" \\\n    -e \"s,{SOURCE},${CODEBUILD_SOURCE_REPO_URL},g\" \\\n    -e \"s,{S3_BUCKET},${s3_bucket_name},g\" \\\n    tests/ci/cdk/cdk/ssm/m1_tests_ssm_document.yaml \\\n    >tests/ci/cdk/cdk/ssm/macos_arm_ssm_document.yaml\n}\n\n# create the ssm documents that will be used for the various ssm commands\ngenerate_ssm_document_file\n\n# Create, and run ssm command.\nssm_doc_name=$(create_ssm_document \"macos_arm\")\nssm_document_names=\"${ssm_doc_name}\"\n\nm1_ssm_command_id=$(run_ssm_command \"${ssm_doc_name}\" \"${ec2_instance}\" ${cloudwatch_group_name})\n\nrun_url=\"https://${AWS_REGION}.console.aws.amazon.com/cloudwatch/home?region=${AWS_REGION}\\\n#logsV2:log-groups/log-group/${cloudwatch_group_name}/log-events/\\\n${m1_ssm_command_id}\\$252F${ec2_instance}\\$252FrunShellScript\\$252Fstdout\"\n\necho \"Actual Run in EC2 can be observered at CloudWatch URL: ${run_url}\"\n\n# Give some time for the commands to run\ndone=false\nsuccess=false\nfor i in {1..45}; do\n  echo \"${i}: Continue to wait 2 min for SSM commands to finish.\"\n  sleep 120\n\n  ssm_command_status=\"$(aws ssm list-commands --command-id \"${m1_ssm_command_id}\" --query Commands[*].Status --output text)\"\n  ssm_target_count=\"$(aws ssm list-commands --command-id \"${m1_ssm_command_id}\" --query Commands[*].TargetCount --output text)\"\n  ssm_completed_count=\"$(aws ssm list-commands --command-id \"${m1_ssm_command_id}\" --query Commands[*].CompletedCount --output text)\"\n  if [[ ${ssm_command_status} == 'Success' && ${ssm_completed_count} == \"${ssm_target_count}\" ]]; then\n    echo \"SSM command ${m1_ssm_command_id} finished successfully.\"\n    success=true\n    done=true\n  elif [[ ${ssm_command_status} == 'Failed' && ${ssm_completed_count} == \"${ssm_target_count}\" ]]; then\n    echo \"SSM command ${m1_ssm_command_id} failed.\"\n    done=true\n  else\n    # Still running.\n    done=false\n  fi\n\n  # if after the loop finish and done is still true, then we're done\n  if [ \"${done}\" = true ]; then\n    echo \"M1 SSM command has finished.\"\n\n    # if success is still true here, then none of the commands failed\n    if [ \"${success}\" == true ]; then\n      echo \"M1 SSM command succeeded!\"\n      exit 0\n    else\n      echo \"M1 SSM command failed!\"\n      exit 1\n    fi\n    break\n  fi\ndone\nexit 1", "num_lines": 96}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC without Go in debug mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON\n\necho \"Testing AWS-LC without Go in release mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing shared lib AWS-LC without Go in release mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release\n\n# build AWS-LC without Perl/Go.\necho \"Testing AWS-LC without Perl/Go in debug mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON\n\necho \"Testing AWS-LC without Perl/Go in release mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing shared lib AWS-LC without Perl/Go in release mode.\"\nbuild_and_run_minimal_test -DDISABLE_GO=ON -DDISABLE_PERL=ON -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release\n", "num_lines": 25}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\nbuild_type=Release\ncflags=(\"-DCMAKE_BUILD_TYPE=${build_type}\")\nif [ $(uname -p) == \"aarch64\" ]; then\n  # BoringSSL provides two sets tests: the C/C++ tests and the blackbox tests.\n  # Details: https://github.com/google/boringssl/blob/master/BUILDING.md\n  # The blackbox tests (run `go test` under `ssl/test/runner`) take 30 minutes to complete on ARM when ASAN clang flag enabled.\n  # But the blackbox tests take less than 2 minutes to complete on other test dimensions -- X86 ASAN and ARM (when ASAN disabled).\n  # Instead of running the two sets tests, only the former test is executed here. ssl runner tests are covered by |run_ssl_asan_tests.sh|.\n  # https://github.com/google/sanitizers/issues/1331\n  echo \"Building AWS-LC in ${build_type} mode with address sanitizer, and running only non ssl test.\"\n  run_build -DASAN=1 \"${cflags[@]}\"\n  go run util/all_tests.go -build-dir \"$BUILD_ROOT\"\nelse\n  echo \"Testing AWS-LC in ${build_type} mode with address sanitizer.\"\n  build_and_test -DASAN=1 \"${cflags[@]}\"\nfi\n\necho \"Testing AWS-LC in ${build_type} mode with control flow integrity sanitizer.\"\nbuild_and_test -DCFI=1 \"${cflags[@]}\"\n\necho \"Testing AWS-LC in ${build_type} mode with undefined behavior sanitizer.\"\nexport UBSAN_OPTIONS=print_stacktrace=1\nbuild_and_test -DUBSAN=1 \"${cflags[@]}\"\nunset UBSAN_OPTIONS\n\nif [ $(uname -p) == \"aarch64\" ]; then\n  # ARM MSAN runs get stuck on PoolTest.Threads for over an hour https://github.com/aws/aws-lc/issues/13\n  echo \"Building AWS-LC in ${build_type} mode with memory sanitizer.\"\n  run_build -DMSAN=1 -DUSE_CUSTOM_LIBCXX=1 \"${cflags[@]}\"\nelse\n  echo \"Testing AWS-LC in ${build_type} mode with memory sanitizer.\"\n  build_and_test -DMSAN=1 -DUSE_CUSTOM_LIBCXX=1 \"${cflags[@]}\"\nfi\n\nif [ $(uname -p) == \"x86_64\" ]; then\n  # x86 TSAN runs get stuck on PoolTest.Threads for over an hour https://github.com/aws/aws-lc/issues/13\n  echo \"Building AWS-LC in ${build_type} mode with thread sanitizer.\"\n  run_build -DTSAN=1 -DUSE_CUSTOM_LIBCXX=1 \"${cflags[@]}\"\nelse\n  echo \"Testing AWS-LC in ${build_type} mode with thread sanitizer.\"\n  build_and_test -DTSAN=1 -DUSE_CUSTOM_LIBCXX=1 \"${cflags[@]}\"\nfi\n", "num_lines": 50}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC in debug mode.\"\nbuild_and_test\n\necho \"Testing AWS-LC in release mode.\"\nbuild_and_test -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing AWS-LC with Dilithium3 enabled.\"\nbuild_and_test -DENABLE_DILITHIUM=ON\n\necho \"Testing AWS-LC small compilation.\"\nbuild_and_test -DOPENSSL_SMALL=1 -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing AWS-LC with libssl off.\"\nbuild_and_test -DBUILD_LIBSSL=OFF -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing AWS-LC in no asm mode.\"\nbuild_and_test -DOPENSSL_NO_ASM=1 -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing building shared lib.\"\nbuild_and_test -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release\n\nif [[ \"${AWSLC_C99_TEST}\" == \"1\" ]]; then\n    echo \"Testing the C99 compatability of AWS-LC headers.\"\n    ./tests/coding_guidelines/c99_gcc_test.sh\nfi\n\nif [[ \"${AWSLC_CODING_GUIDELINES_TEST}\" == \"1\" ]]; then\n  echo \"Testing that AWS-LC is compliant with the coding guidelines.\"\n  source ./tests/coding_guidelines/coding_guidelines_test.sh\nfi\n\n# Lightly verify that uncommon build options does not break the build. Fist\n# define a list of typical build options to verify the special build option with\nbuild_options_to_test=(\"\" \"-DBUILD_SHARED_LIBS=1\" \"-DCMAKE_BUILD_TYPE=Release\" \"-DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release\")\n\n## Build option: MY_ASSEMBLER_IS_TOO_OLD_FOR_AVX\nfor build_option in \"${build_options_to_test[@]}\"; do\n  run_build ${build_option} -DMY_ASSEMBLER_IS_TOO_OLD_FOR_AVX=ON\ndone\n\n## Build option: MY_ASSEMBLER_IS_TOO_OLD_FOR_512AVX\nfor build_option in \"${build_options_to_test[@]}\"; do\n  run_build ${build_option} -DMY_ASSEMBLER_IS_TOO_OLD_FOR_512AVX=ON\ndone\n", "num_lines": 52}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing a prefix build of AWS-LC in debug mode.\"\nbuild_prefix_and_test\n\necho \"Testing a prefix build of AWS-LC in release mode.\"\nbuild_prefix_and_test -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing a prefix build of AWS-LC small compilation.\"\nbuild_prefix_and_test -DOPENSSL_SMALL=1 -DCMAKE_BUILD_TYPE=Release\n\necho \"Testing a prefix build of AWS-LC in no asm mode.\"\nbuild_prefix_and_test -DOPENSSL_NO_ASM=1 -DCMAKE_BUILD_TYPE=Release\n", "num_lines": 19}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# BoringSSL has 7k+ ssl runner tests, and the total number of the runner tests keep increasing.\n# When ASAN enabled, the tests take more than 1 hour to finish. The cause relates to https://github.com/google/sanitizers/issues/1331\n# To reduce the total time, these tests will be executed in diff CodeBuild dimensions.\n# Env var |AWS_LC_SSL_RUNNER_START_INDEX| and |AWS_LC_SSL_RUNNER_END_INDEX| will be used with this script to split runner tests.\nsource tests/ci/common_posix_setup.sh\n\nbuild_type=Release\ncflags=(\"-DCMAKE_BUILD_TYPE=${build_type}\")\n\nif [ $(uname -p) == \"aarch64\" ]; then\n  echo \"Executing AWS-LC SSL runner tests in ${build_type} mode with address sanitizer.\"\n  run_build -DASAN=1 \"${cflags[@]}\"\n  run_cmake_custom_target 'run_ssl_runner_tests'\nfi\n", "num_lines": 20}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC in debug mode under Valgrind.\"\nbuild_and_test_ssl_runner_valgrind\n", "num_lines": 9}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC in debug mode under Intel's SDE.\"\nbuild_and_test_with_sde\n\necho \"Testing AWS-LC in release mode under Intel's SDE.\"\nbuild_and_test_with_sde -DCMAKE_BUILD_TYPE=Release\n", "num_lines": 12}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\necho \"Testing AWS-LC in debug mode under Valgrind.\"\nbuild_and_test_valgrind\n", "num_lines": 9}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -xo\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nif ! [ -x \"$(command -v docker)\" ]; then\n  apt-get update\n  apt-get install -y apt-transport-https ca-certificates curl gnupg lsb-release\n  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | gpg --no-tty --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg\n  # need to change below depending on cpu type\n  echo \"deb [arch=${CPU_TYPE} signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" | tee /etc/apt/sources.list.d/docker.list >/dev/null\n  apt-get update\n  apt-get install -y docker-ce docker-ce-cli containerd.io\nfi\n", "num_lines": 16}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -exuo pipefail\n\n# -e: Exit on any failure\n# -x: Print the command before running\n# -u: Any variable that is not set will cause an error if used\n# -o pipefail: Makes sure to exit a pipeline with a non-zero error code if any command in the pipeline exists with a\n#              non-zero error code.\n\nfunction delete_s3_buckets() {\n  aws s3api list-buckets --query \"Buckets[].Name\" | jq '.[]' | while read -r i; do\n    bucket_name=$(echo \"${i}\" | tr -d '\"')\n    # Delete the bucket if its name uses AWS_LC_S3_BUCKET_PREFIX.\n    if [[ \"${bucket_name}\" == *\"${AWS_LC_S3_BUCKET_PREFIX}\"* ]]; then\n      aws s3 rm \"s3://${bucket_name}\" --recursive\n      aws s3api delete-bucket --bucket \"${bucket_name}\"\n    # Delete bm-framework buckets if we're not on the team account\n    elif [[ \"${CDK_DEPLOY_ACCOUNT}\" != \"620771051181\" ]] && [[ \"${bucket_name}\" == *\"${aws-lc-ci-bm-framework}\"* ]]; then\n      aws s3 rm \"s3://${bucket_name}\" --recursive\n      aws s3api delete-bucket --bucket \"${bucket_name}\"\n    fi\n  done\n}\n\nfunction delete_container_repositories() {\n  ecr_repos=$(aws ecr describe-repositories)\n  if [[ \"${ecr_repos}\" == *\"${ECR_LINUX_AARCH_REPO_NAME}\"* ]]; then\n    aws ecr delete-repository --repository-name \"${ECR_LINUX_AARCH_REPO_NAME}\" --force\n  fi\n  if [[ \"${ecr_repos}\" == *\"${ECR_LINUX_X86_REPO_NAME}\"* ]]; then\n    aws ecr delete-repository --repository-name \"${ECR_LINUX_X86_REPO_NAME}\" --force\n  fi\n  if [[ \"${ecr_repos}\" == *\"${ECR_WINDOWS_X86_REPO_NAME}\"* ]]; then\n    aws ecr delete-repository --repository-name \"${ECR_WINDOWS_X86_REPO_NAME}\" --force\n  fi\n}\n\nfunction destroy_ci() {\n  if [[ \"${CDK_DEPLOY_ACCOUNT}\" == \"620771051181\" ]]; then\n    echo \"destroy_ci should not be executed on team account.\"\n    exit 1\n  fi\n  cdk destroy aws-lc-* --force\n  # CDK stack destroy does not delete s3 bucket automatically.\n  delete_s3_buckets\n  # CDK stack destroy does not delete ecr automatically.\n  delete_container_repositories\n}\n\nfunction destroy_docker_img_build_stack() {\n  if [[ \"${IMG_BUILD_STATUS}\" == \"Failed\" ]]; then\n    echo \"Docker images build failed. AWS resources of building Docker images is kept for debug.\"\n    exit 1\n  fi\n  # Destroy all temporary resources created for all docker image build.\n  cdk destroy aws-lc-docker-image-build-* --force\n  # CDK stack destroy does not delete s3 bucket automatically.\n  delete_s3_buckets\n}\n\nfunction create_linux_docker_img_build_stack() {\n  # Clean up build stacks if exists.\n  destroy_docker_img_build_stack\n  # Deploy aws-lc ci stacks.\n  # When repeatedly deploy, error 'EIP failed Reason: Maximum number of addresses has been reached' can happen.\n  # https://forums.aws.amazon.com/thread.jspa?messageID=952368\n  # Workaround: go to AWS EIP console, release unused IP.\n  cdk deploy aws-lc-docker-image-build-linux --require-approval never\n}\n\nfunction create_win_docker_img_build_stack() {\n  # Clean up build stacks if exists.\n  destroy_docker_img_build_stack\n  # Deploy aws-lc ci stacks.\n  # When repeatedly deploy, error 'EIP failed Reason: Maximum number of addresses has been reached' can happen.\n  # https://forums.aws.amazon.com/thread.jspa?messageID=952368\n  # Workaround: go to AWS EIP console, release unused IP.\n  cdk deploy aws-lc-docker-image-build-windows --require-approval never\n}\n\nfunction create_github_ci_stack() {\n  cdk deploy aws-lc-ci-* --require-approval never\n}\n\nfunction run_linux_img_build() {\n  # https://awscli.amazonaws.com/v2/documentation/api/latest/reference/codebuild/start-build-batch.html\n  build_id=$(aws codebuild start-build-batch --project-name aws-lc-docker-image-build-linux | jq -r '.buildBatch.id')\n  export AWS_LC_LINUX_BUILD_BATCH_ID=\"${build_id}\"\n}\n\nfunction run_windows_img_build() {\n  # EC2 takes several minutes to be ready for running command.\n  echo \"Wait 3 min for EC2 ready for SSM command execution.\"\n  sleep 180\n\n  # Run commands on windows EC2 instance to build windows docker images.\n  for i in {1..60}; do\n    instance_id=$(aws ec2 describe-instances \\\n      --filters \"Name=tag:${WIN_EC2_TAG_KEY},Values=${WIN_EC2_TAG_VALUE}\" | jq -r '.Reservations[0].Instances[0].InstanceId')\n    if [[ \"${instance_id}\" == \"null\" ]]; then\n      sleep 60\n      continue\n    fi\n    instance_ping_status=$(aws ssm describe-instance-information \\\n      --filters \"Key=InstanceIds,Values=${instance_id}\" | jq -r '.InstanceInformationList[0].PingStatus')\n    if [[ \"${instance_ping_status}\" == \"Online\" ]]; then\n      # https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/send-command.html\n      command_id=$(aws ssm send-command \\\n        --instance-ids \"${instance_id}\" \\\n        --document-name \"${WIN_DOCKER_BUILD_SSM_DOCUMENT}\" \\\n        --output-s3-bucket-name \"${S3_FOR_WIN_DOCKER_IMG_BUILD}\" \\\n        --output-s3-key-prefix 'runcommand' | jq -r '.Command.CommandId')\n      # Export for checking command run status.\n      export WINDOWS_DOCKER_IMG_BUILD_COMMAND_ID=\"${command_id}\"\n      echo \"Windows ec2 is executing SSM command.\"\n      return\n    else\n      echo \"${i}: Current instance ping status: ${instance_ping_status}. Wait 1 minute to retry SSM command execution.\"\n      sleep 60\n    fi\n  done\n  echo \"After 30 minutes, Windows ec2 is still not ready for SSM commands execution. Exit.\"\n  exit 1\n}\n\nfunction linux_docker_img_build_status_check() {\n  export IMG_BUILD_STATUS='Failed'\n  # Every 5 min, this function checks if the linux docker image batch code build finished successfully.\n  # Normally, docker img build can take up to 1 hour. Here, we wait up to 30 * 5 min.\n  for i in {1..30}; do\n    # https://docs.aws.amazon.com/cli/latest/reference/codebuild/batch-get-build-batches.html\n    build_batch_status=$(aws codebuild batch-get-build-batches --ids \"${AWS_LC_LINUX_BUILD_BATCH_ID}\" | jq -r '.buildBatches[0].buildBatchStatus')\n    if [[ ${build_batch_status} == 'SUCCEEDED' ]]; then\n      export IMG_BUILD_STATUS='Success'\n      echo \"Code build ${AWS_LC_LINUX_BUILD_BATCH_ID} finished successfully.\"\n      return\n    elif [[ ${build_batch_status} == 'FAILED' ]]; then\n      echo \"Code build ${AWS_LC_LINUX_BUILD_BATCH_ID} failed.\"\n      exit 1\n    else\n      echo \"${i}: Wait 5 min for docker image build job finish.\"\n      sleep 300\n    fi\n  done\n  echo \"Code build ${AWS_LC_LINUX_BUILD_BATCH_ID} takes more time than expected.\"\n  exit 1\n}\n\nfunction win_docker_img_build_status_check() {\n  export IMG_BUILD_STATUS='Failed'\n  # Every 5 min, this function checks if the windows docker image build is finished successfully.\n  # Normally, docker img build can take up to 1 hour. Here, we wait up to 30 * 5 min.\n  for i in {1..30}; do\n    # https://awscli.amazonaws.com/v2/documentation/api/latest/reference/ssm/list-commands.html\n    command_run_status=$(aws ssm list-commands --command-id \"${WINDOWS_DOCKER_IMG_BUILD_COMMAND_ID}\" | jq -r '.Commands[0].Status')\n    if [[ ${command_run_status} == 'Success' ]]; then\n      export IMG_BUILD_STATUS='Success'\n      echo \"SSM command ${WINDOWS_DOCKER_IMG_BUILD_COMMAND_ID} finished successfully.\"\n      return\n    elif [[ ${command_run_status} == 'Failed' ]]; then\n      echo \"SSM command ${WINDOWS_DOCKER_IMG_BUILD_COMMAND_ID} failed.\"\n      exit 1\n    else\n      echo \"${i}: Wait 5 min for windows docker image build job finish.\"\n      sleep 300\n    fi\n  done\n  echo \"SSM command ${WINDOWS_DOCKER_IMG_BUILD_COMMAND_ID} takes more time than expected.\"\n  exit 1\n}\n\nfunction build_linux_docker_images() {\n  # Always destroy docker build stacks (which include EC2 instance) on EXIT.\n  trap destroy_docker_img_build_stack EXIT\n\n  # Create/update aws-ecr repo.\n  cdk deploy aws-lc-ecr-linux-* --require-approval never\n\n  # Create docker image build stack.\n  create_linux_docker_img_build_stack\n\n  echo \"Activating AWS CodeBuild to build Linux aarch & x86 docker images.\"\n  run_linux_img_build\n\n  echo \"Waiting for docker images creation. Building the docker images need to take 1 hour.\"\n  # TODO(CryptoAlg-624): These image build may fail due to the Docker Hub pull limits made on 2020-11-01.\n  linux_docker_img_build_status_check\n}\n\nfunction build_win_docker_images() {\n # Always destroy docker build stacks (which include EC2 instance) on EXIT.\n trap destroy_docker_img_build_stack EXIT\n\n # Create/update aws-ecr repo.\n cdk deploy aws-lc-ecr-windows-* --require-approval never\n\n # Create aws windows build stack\n create_win_docker_img_build_stack\n\n echo \"Executing AWS SSM commands to build Windows docker images.\"\n run_windows_img_build\n\n echo \"Waiting for docker images creation. Building the docker images need to take 1 hour.\"\n # TODO(CryptoAlg-624): These image build may fail due to the Docker Hub pull limits made on 2020-11-01.\n win_docker_img_build_status_check\n}\n\nfunction setup_ci() {\n  build_linux_docker_images\n  build_win_docker_images\n\n  create_github_ci_stack\n  create_android_resources\n}\n\nfunction create_android_resources() {\n  # Use aws cli to create Device Farm project and get project arn to create device pools.\n  # TODO: Move resource creation to aws cdk when cdk has support for device form resource constructs.\n  # Issue: https://github.com/aws/aws-cdk/issues/17893\n  DEVICEFARM_PROJECT=`aws devicefarm create-project --name aws-lc-android-ci | \\\n                             python -c 'import json,sys;obj=json.load(sys.stdin);print(obj[\"project\"][\"arn\"])'`\n\n  DEVICEFARM_DEVICE_POOL=`aws devicefarm create-device-pool --project-arn ${DEVICEFARM_PROJECT} \\\n    --name \"aws-lc-device-pool\" \\\n    --description \"AWS-LC Device Pool\" \\\n    --rules file://../android/devicepool_rules.json --max-devices 2 | \\\n    python -c 'import json,sys;obj=json.load(sys.stdin);print(obj[\"devicePool\"][\"arn\"])'`\n\n  DEVICEFARM_DEVICE_POOL_FIPS=`aws devicefarm create-device-pool --project-arn ${DEVICEFARM_PROJECT} \\\n    --name \"aws-lc-device-pool-fips\" \\\n    --description \"AWS-LC FIPS Device Pool\" \\\n    --rules file://../android/devicepool_rules_fips.json --max-devices 2 | \\\n    python -c 'import json,sys;obj=json.load(sys.stdin);print(obj[\"devicePool\"][\"arn\"])'`\n\n  cat <<EOF\n\nDEVICEFARM_PROJECT arn value: ${DEVICEFARM_PROJECT}\n\nDEVICEFARM_DEVICE_POOL arn value: ${DEVICEFARM_DEVICE_POOL}\n\nDEVICEFARM_DEVICE_POOL_FIPS arn value: ${DEVICEFARM_DEVICE_POOL_FIPS}\n\nTake the corresponding Device Farm arn values and update the arn values at tests/ci/kickoff_devicefarm_job.sh\n\nEOF\n}\n\n###########################\n# Main and related helper #\n###########################\n\nfunction script_helper() {\n  cat <<EOF\nThis script uses CDK to deploy/destroy AWS resources defined in the aws-lc cdk app.\n\nFor aws-lc continuous integration setup, this script uses aws cli to build some non-AWS resources(e.g. Docker image).\n\nOptions:\n    --help                       Displays this help\n    --aws-account                AWS account for CDK deploy/destroy. Default to '620771051181'.\n    --aws-region                 AWS region for AWS resources creation. Default to 'us-west-2'.\n    --github-repo-owner          GitHub repository owner. Default to 'aws'.\n    --github-source-version      GitHub source version. Default to 'main'.\n    --action                     Required. The value can be\n                                   'deploy-ci': deploys aws-lc ci. This includes AWS and Docker image resources creation.\n                                   'update-ci': update aws-lc ci. This only update AWS CodeBuild for GitHub CI.\n                                   'destroy-ci': destroys AWS and Docker image resources used by aws-lc ci.\n                                   'destroy-img-stack': destroys AWS resources created during built of Docker images.\n                                   'build-linux-img': builds Linux Docker image used by aws-lc ci.\n                                                After image build, AWS resources are cleaned up.\n                                   'build-win-img': builds Windows Docker image used by aws-lc ci.\n                                                After image build, AWS resources are cleaned up.\n                                   'diff': compares the specified stack with the deployed stack.\n                                   'synth': synthesizes and prints the CloudFormation template for the stacks.\n                                   'bootstrap': Bootstraps the CDK stack. This is needed before deployment or updating the CI.\nEOF\n}\n\nfunction export_global_variables() {\n  # If these variables are not set or empty, defaults are export.\n  if [[ -z \"${CDK_DEPLOY_ACCOUNT+x}\" || -z \"${CDK_DEPLOY_ACCOUNT}\" ]]; then\n    export CDK_DEPLOY_ACCOUNT='620771051181'\n  fi\n  if [[ -z \"${CDK_DEPLOY_REGION+x}\" || -z \"${CDK_DEPLOY_REGION}\" ]]; then\n    export CDK_DEPLOY_REGION='us-west-2'\n    export AWS_DEFAULT_REGION=\"${CDK_DEPLOY_REGION}\"\n  fi\n  if [[ -z \"${GITHUB_REPO_OWNER+x}\" || -z \"${GITHUB_REPO_OWNER}\" ]]; then\n    export GITHUB_REPO_OWNER='aws'\n  fi\n  if [[ -z \"${GITHUB_SOURCE_VERSION+x}\" || -z \"${GITHUB_SOURCE_VERSION}\" ]]; then\n    export GITHUB_SOURCE_VERSION='main'\n  fi\n  # Other variables for managing resources.\n  DATE_NOW=\"$(date +%Y-%m-%d-%H-%M)\"\n  export GITHUB_REPO='aws-lc'\n  export ECR_LINUX_AARCH_REPO_NAME='aws-lc-docker-images-linux-aarch'\n  export ECR_LINUX_X86_REPO_NAME='aws-lc-docker-images-linux-x86'\n  export ECR_WINDOWS_X86_REPO_NAME='aws-lc-docker-images-windows-x86'\n  export AWS_LC_S3_BUCKET_PREFIX='aws-lc-windows-docker-image-build-s3'\n  export S3_FOR_WIN_DOCKER_IMG_BUILD=\"${AWS_LC_S3_BUCKET_PREFIX}-${DATE_NOW}\"\n  export WIN_EC2_TAG_KEY='aws-lc'\n  export WIN_EC2_TAG_VALUE=\"aws-lc-windows-docker-image-build-${DATE_NOW}\"\n  export WIN_DOCKER_BUILD_SSM_DOCUMENT=\"windows-ssm-document-${DATE_NOW}\"\n  export IMG_BUILD_STATUS='unknown'\n  # 620771051181 is AWS-LC team AWS account.\n  if [[ \"${CDK_DEPLOY_ACCOUNT}\" != \"620771051181\" ]] && [[ \"${GITHUB_REPO_OWNER}\" == 'aws' ]]; then\n    echo \"Only team account is allowed to create CI stacks on aws repo.\"\n    exit 1\n  fi\n}\n\nfunction main() {\n  # parse arguments.\n  while [[ $# -gt 0 ]]; do\n    case ${1} in\n    --help)\n      script_helper\n      exit 0\n      ;;\n    --aws-account)\n      export CDK_DEPLOY_ACCOUNT=\"${2}\"\n      shift\n      ;;\n    --aws-region)\n      export CDK_DEPLOY_REGION=\"${2}\"\n      export AWS_DEFAULT_REGION=\"${CDK_DEPLOY_REGION}\"\n      shift\n      ;;\n    --github-repo-owner)\n      export GITHUB_REPO_OWNER=\"${2}\"\n      shift\n      ;;\n    --github-source-version)\n      export GITHUB_SOURCE_VERSION=\"${2}\"\n      shift\n      ;;\n    --action)\n      export ACTION=\"${2}\"\n      shift\n      ;;\n    *)\n      echo \"${1} is not supported.\"\n      exit 1\n      ;;\n    esac\n    # Check next option -- key/value.\n    shift\n  done\n\n  # Make sure action is set.\n  if [[ -z \"${ACTION+x}\" || -z \"${ACTION}\" ]]; then\n    echo \"${ACTION} is required input.\"\n    exit 1\n  fi\n\n  # Export global variables, which provides the contexts needed by ci setup/destroy.\n  export_global_variables\n\n  # Execute the action.\n  case ${ACTION} in\n  deploy-ci)\n    setup_ci\n    ;;\n  update-ci)\n    create_github_ci_stack\n    ;;\n  destroy-ci)\n    destroy_ci\n    ;;\n  update-android-resources)\n    create_android_resources\n    ;;\n  destroy-img-stack)\n    destroy_docker_img_build_stack\n    ;;\n  build-linux-img)\n    build_linux_docker_images\n    ;;\n  build-win-img)\n    build_win_docker_images\n    ;;\n  synth)\n    cdk synth aws-lc-ci-*\n    ;;\n  diff)\n    cdk diff aws-lc-ci-*\n    ;;\n  bootstrap)\n    cdk bootstrap\n    ;;\n  *)\n    echo \"--action is required. Use '--help' to see allowed actions.\"\n    exit 1\n    ;;\n  esac\n}\n\n# Invoke main\nmain \"$@\"\n", "num_lines": 405}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n\nfunction env {\n  export \"$1\"=\"$2\"\n  echo \"export ${1}=\\\"${2}\\\"\" >> \"${FUZZ_ROOT}/fuzz_env.sh\"\n}\n# Recommended flags from https://github.com/guidovranken/cryptofuzz/blob/master/docs/building.md\n# Remove-fsanitize=undefined which doesn't fail the build but creates additional noise in build output\nexport CFLAGS=\"-fsanitize=address,fuzzer-no-link -O2 -g -Wno-gnu-designator\"\nexport CXXFLAGS=\"-fsanitize=address,fuzzer-no-link -D_GLIBCXX_DEBUG -O2 -g\"\n\n# Setup base of Cryptofuzz\ncd \"$FUZZ_ROOT\"\nMODULES_ROOT=\"${FUZZ_ROOT}/modules\"\ngit clone --depth 1 https://github.com/guidovranken/cryptofuzz.git\ncd cryptofuzz\ngit rev-parse HEAD\nCRYPTOFUZZ_SRC=$(pwd)\npython3 gen_repository.py\n\nmkdir \"$MODULES_ROOT\"\ncd \"$MODULES_ROOT\"\n\n# Setup the other crypto libraries for differential fuzzing\n# Botan https://github.com/guidovranken/cryptofuzz/blob/master/docs/botan.md\ngit clone --depth 1 https://github.com/randombit/botan.git\ncd botan\ngit rev-parse HEAD\npython3 configure.py --cc-bin=$CXX --cc-abi-flags=\"$CXXFLAGS\" --disable-shared --disable-modules=locking_allocator,x509,tls --build-targets=static --without-documentation\nmake -j$(nproc)\nexport CXXFLAGS=\"$CXXFLAGS -DCRYPTOFUZZ_BOTAN\"\nenv LIBBOTAN_A_PATH `realpath libbotan-3.a`\nenv BOTAN_INCLUDE_PATH `realpath build/include`\ncd \"${CRYPTOFUZZ_SRC}/modules/botan/\"\nmake -j$(nproc)\n\n# Crypto++ https://github.com/guidovranken/cryptofuzz/blob/master/docs/cryptopp.md\ncd \"$MODULES_ROOT\"\ngit clone --depth 1 https://github.com/weidai11/cryptopp.git\ncd cryptopp/\ngit rev-parse HEAD\nmake libcryptopp.a -j$(nproc)\nexport CXXFLAGS=\"$CXXFLAGS -DCRYPTOFUZZ_CRYPTOPP\"\nenv LIBCRYPTOPP_A_PATH `realpath libcryptopp.a`\nenv CRYPTOPP_INCLUDE_PATH `realpath .`\ncd \"${CRYPTOFUZZ_SRC}/modules/cryptopp/\"\nmake -j$(nproc)\n\n# Extract the seed corpus, docker layers are already compressed so this won't use any more space and save time when running\ncd \"$FUZZ_ROOT\"\nunzip cryptofuzz_data.zip\nrm cryptofuzz_data.zip\nenv CRYPTOFUZZ_SEED_CORPUS `realpath cryptofuzz_seed_corpus`\nenv CRYPTOFUZZ_DICT `realpath cryptofuzz-dict.txt`\n\n# Save final common flags\nenv CFLAGS \"$CFLAGS\"\nenv CXXFLAGS \"$CXXFLAGS\"\nenv CRYPTOFUZZ_SRC \"$CRYPTOFUZZ_SRC\"\n\n# Cryptofuzz builds its modules into $CRYPTOFUZZ_SRC/modules that includes everything it needs, deleting the module source\n# code saves a substantial amount of space in the docker image\nrm -rf \"$MODULES_ROOT\"\n\n# Prebuild the required libcpu_features to save time\ncd \"$CRYPTOFUZZ_SRC\"\nmake third_party/cpu_features/build/libcpu_features.a\n", "num_lines": 69}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -exo pipefail\n\nPLATFORM=$(uname -m)\n\n# Install golang\nmkdir \"$GOROOT\"\nGO_VERSION=1.20.1\nif [[ \"$PLATFORM\" == *x86* ]]; then\n  GO_ARCHIVE=\"go${GO_VERSION}.linux-amd64.tar.gz\"\nelse\n  GO_ARCHIVE=\"go${GO_VERSION}.linux-arm64.tar.gz\"\nfi\nwget \"https://dl.google.com/go/${GO_ARCHIVE}\"\ntar -xvf $GO_ARCHIVE\nmv go/* \"$GOROOT\"\nrm $GO_ARCHIVE\n# Common Go configuration\ngo env -w GO111MODULE=on\ngo env -w GOFLAGS=-buildvcs=false", "num_lines": 20}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# Log Docker hub limit https://docs.docker.com/docker-hub/download-rate-limit/#how-can-i-check-my-current-rate\nTOKEN=$(curl \"https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull\" | jq -r .token)\ncurl --head -H \"Authorization: Bearer $TOKEN\" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest\n\n# Every \"base\" image needs to build with the dependencies directory as the context so it has access to the install\n# dependencies scripts\ndocker build -t amazonlinux-2-aarch:base -f amazonlinux-2_base/Dockerfile ../dependencies\ndocker build -t amazonlinux-2-aarch:gcc-7x amazonlinux-2_gcc-7x\ndocker build -t amazonlinux-2-aarch:clang-7x amazonlinux-2_clang-7x\ndocker build -t amazonlinux-2023-aarch:base -f amazonlinux-2023_base/Dockerfile ../dependencies\ndocker build -t amazonlinux-2023-aarch:gcc-11x amazonlinux-2023_gcc-11x\ndocker build -t amazonlinux-2023-aarch:clang-15x amazonlinux-2023_clang-15x\ndocker build -t amazonlinux-2023-aarch:clang-15x-sanitizer amazonlinux-2023_clang-15x_sanitizer\ndocker build -t amazonlinux-2023-aarch:cryptofuzz -f amazonlinux-2023_clang-15x_cryptofuzz/Dockerfile ../dependencies\ndocker build -t ubuntu-20.04-aarch:base -f ubuntu-20.04_base/Dockerfile ../dependencies\ndocker build -t ubuntu-20.04-aarch:gcc-7x ubuntu-20.04_gcc-7x\ndocker build -t ubuntu-20.04-aarch:gcc-8x ubuntu-20.04_gcc-8x\ndocker build -t ubuntu-20.04-aarch:clang-7x ubuntu-20.04_clang-7x\ndocker build -t ubuntu-20.04-aarch:clang-8x ubuntu-20.04_clang-8x\ndocker build -t ubuntu-20.04-aarch:clang-9x ubuntu-20.04_clang-9x\ndocker build -t ubuntu-20.04-aarch:clang-10x ubuntu-20.04_clang-10x\ndocker build -t ubuntu-20.04-aarch:clang-7x-bm-framework ubuntu-20.04_clang-7x-bm-framework\ndocker build -t ubuntu-22.04-aarch:base -f ubuntu-22.04_base/Dockerfile ../dependencies\ndocker build -t ubuntu-22.04-aarch:gcc-11x ubuntu-22.04_gcc-11x\ndocker build -t ubuntu-22.04-aarch:gcc-12x ubuntu-22.04_gcc-12x\n", "num_lines": 30}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nfunction validate_input() {\n  key=\"${1}\"\n  value=\"${2}\"\n  if [[ -z \"${value}\" ]]; then\n    echo \"The value of ${key} is empty.\"\n    exit 1\n  fi\n}\n\n# Tag images with date to help find old images, CodeBuild uses the latest tag and gets updated automatically.\nfunction tag_and_push_img() {\n  source=\"${1}\"\n  validate_input 'source' \"${source}\"\n  target=\"${2}\"\n  validate_input 'target' \"${target}\"\n  img_push_date=$(date +%Y-%m-%d)\n  docker_img_with_latest=\"${target}_latest\"\n  docker_img_with_date=\"${target}_${img_push_date}\"\n  docker tag \"${source}\" \"${docker_img_with_latest}\"\n  docker tag \"${source}\" \"${docker_img_with_date}\"\n  docker push \"${docker_img_with_latest}\"\n  docker push \"${docker_img_with_date}\"\n}\n", "num_lines": 28}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource ./common.sh\n\nif [ -z ${1+x} ]; then\n  ECS_REPO=\"620771051181.dkr.ecr.us-west-2.amazonaws.com/aws-lc-docker-images-linux-aarch\"\nelse\n  ECS_REPO=$1\nfi\n\necho \"Uploading docker images to ${ECS_REPO}.\"\n\n$(aws ecr get-login --no-include-email --region us-west-2)\n\n# Tag images with date to help find old images, CodeBuild uses the latest tag and gets updated automatically\ntag_and_push_img 'amazonlinux-2-aarch:gcc-7x' \"${ECS_REPO}:amazonlinux-2_gcc-7x\"\ntag_and_push_img 'amazonlinux-2-aarch:clang-7x' \"${ECS_REPO}:amazonlinux-2_clang-7x\"\ntag_and_push_img 'amazonlinux-2023-aarch:gcc-11x' \"${ECS_REPO}:amazonlinux-2023_gcc-11x\"\ntag_and_push_img 'amazonlinux-2023-aarch:clang-15x' \"${ECS_REPO}:amazonlinux-2023_clang-15x\"\ntag_and_push_img 'amazonlinux-2023-aarch:clang-15x-sanitizer' \"${ECS_REPO}:amazonlinux-2023_clang-15x_sanitizer\"\ntag_and_push_img 'amazonlinux-2023-aarch:cryptofuzz' \"${ECS_REPO}:amazonlinux-2023_clang-15x_cryptofuzz\"\ntag_and_push_img 'ubuntu-20.04-aarch:gcc-7x' \"${ECS_REPO}:ubuntu-20.04_gcc-7x\"\ntag_and_push_img 'ubuntu-20.04-aarch:gcc-8x' \"${ECS_REPO}:ubuntu-20.04_gcc-8x\"\ntag_and_push_img 'ubuntu-20.04-aarch:clang-7x' \"${ECS_REPO}:ubuntu-20.04_clang-7x\"\ntag_and_push_img 'ubuntu-20.04-aarch:clang-8x' \"${ECS_REPO}:ubuntu-20.04_clang-8x\"\ntag_and_push_img 'ubuntu-20.04-aarch:clang-9x' \"${ECS_REPO}:ubuntu-20.04_clang-9x\"\ntag_and_push_img 'ubuntu-20.04-aarch:clang-10x' \"${ECS_REPO}:ubuntu-20.04_clang-10x\"\ntag_and_push_img 'ubuntu-20.04-aarch:clang-7x-bm-framework' \"${ECS_REPO}:ubuntu-20.04_clang-7x-bm-framework\"\ntag_and_push_img 'ubuntu-22.04-aarch:gcc-11x' \"${ECS_REPO}:ubuntu-22.04_gcc-11x\"\ntag_and_push_img 'ubuntu-22.04-aarch:gcc-12x' \"${ECS_REPO}:ubuntu-22.04_gcc-12x\"\n", "num_lines": 33}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n########################################\n# Build images from AWS-LC GitHub repo #\n########################################\n\n# Log Docker hub limit https://docs.docker.com/docker-hub/download-rate-limit/#how-can-i-check-my-current-rate\nTOKEN=$(curl \"https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull\" | jq -r .token)\ncurl --head -H \"Authorization: Bearer $TOKEN\" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest\n\n# Every \"base\" image needs to build with the dependencies directory as the context so it has access to the install\n# dependencies scripts\ndocker build -t ubuntu-18.04:base -f ubuntu-18.04_base/Dockerfile ../dependencies\ndocker build -t ubuntu-18.04:gcc-7x ubuntu-18.04_gcc-7x\ndocker build -t ubuntu-18.04:clang-6x ubuntu-18.04_clang-6x\ndocker build -t ubuntu-20.04:base -f ubuntu-20.04_base/Dockerfile ../dependencies\ndocker build -t ubuntu-20.04:gcc-7x ubuntu-20.04_gcc-7x\ndocker build -t ubuntu-20.04:gcc-8x ubuntu-20.04_gcc-8x\ndocker build -t ubuntu-20.04:clang-7x ubuntu-20.04_clang-7x\ndocker build -t ubuntu-20.04:clang-8x ubuntu-20.04_clang-8x\ndocker build -t ubuntu-20.04:clang-9x ubuntu-20.04_clang-9x\ndocker build -t ubuntu-20.04:clang-10x ubuntu-20.04_clang-10x\ndocker build -t ubuntu-20.04:android -f ubuntu-20.04_android/Dockerfile ../\ndocker build -t ubuntu-20.04:clang-7x-bm-framework ubuntu-20.04_clang-7x-bm-framework\ndocker build -t ubuntu-22.04:base -f ubuntu-22.04_base/Dockerfile ../dependencies\ndocker build -t ubuntu-22.04:gcc-11x ubuntu-22.04_gcc-11x\ndocker build -t ubuntu-22.04:gcc-12x ubuntu-22.04_gcc-12x\ndocker build -t amazonlinux-2:base -f amazonlinux-2_base/Dockerfile ../dependencies\ndocker build -t amazonlinux-2:gcc-7x amazonlinux-2_gcc-7x\ndocker build -t amazonlinux-2:gcc-7x-intel-sde amazonlinux-2_gcc-7x-intel-sde\ndocker build -t amazonlinux-2:clang-7x amazonlinux-2_clang-7x\ndocker build -t amazonlinux-2023:base -f amazonlinux-2023_base/Dockerfile ../dependencies\ndocker build -t amazonlinux-2023:gcc-11x amazonlinux-2023_gcc-11x\ndocker build -t amazonlinux-2023:clang-15x amazonlinux-2023_clang-15x\ndocker build -t amazonlinux-2023:clang-15x-sanitizer amazonlinux-2023_clang-15x_sanitizer\ndocker build -t amazonlinux-2023:cryptofuzz -f amazonlinux-2023_clang-15x_cryptofuzz/Dockerfile ../dependencies\ndocker build -t ubuntu-16.04:gcc-5x -f ubuntu-16.04_gcc-5x/Dockerfile ../dependencies\ndocker build -t centos-7:gcc-4x -f centos-7_gcc-4x/Dockerfile ../dependencies\ndocker build -t centos-8:gcc-8x -f centos-8_gcc-8x/Dockerfile ../dependencies\ndocker build -t fedora-31:clang-9x -f fedora-31_clang-9x/Dockerfile ../dependencies\n###########################################################\n# Build images defined in aws-lc-verification GitHub repo #\n###########################################################\n\n./ubuntu-20.04_clang-10x_formal-verification/create_image.sh ubuntu-20.04:clang-10x_formal-verification\n\n###########################################################\n# Build older unofficial docker image that uses gcc 4.1.3 #\n###########################################################\n\n./build_legacy_image.sh ubuntu-10.04_gcc-4.1x\n", "num_lines": 54}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nif [ -n \"$1\" ]; then\n  docker_name=\"$1\"\nelse\n  docker_name='ubuntu-10.04_gcc-4.1x'\nfi\n\nmkdir -p ${docker_name}/dependencies\ncd ${docker_name}/dependencies\n\n# The wget version that comes with this docker image is too old to\n# download the cmake version from source, so we predownload the \n# dependencies outside of the image and pull it in the container.\nwget -O cmake-3.9.6.tar.gz https://cmake.org/files/v3.9/cmake-3.9.6.tar.gz\ncd ..\nsudo docker build -t ubuntu-10.04_gcc-4.1x .\n\nsudo rm -rf dependencies\ncd ..\n", "num_lines": 23}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nfunction validate_input() {\n  key=\"${1}\"\n  value=\"${2}\"\n  if [[ -z \"${value}\" ]]; then\n    echo \"The value of ${key} is empty.\"\n    exit 1\n  fi\n}\n\n# Tag images with date to help find old images, CodeBuild uses the latest tag and gets updated automatically.\nfunction tag_and_push_img() {\n  source=\"${1}\"\n  validate_input 'source' \"${source}\"\n  target=\"${2}\"\n  validate_input 'target' \"${target}\"\n  img_push_date=$(date +%Y-%m-%d)\n  docker_img_with_latest=\"${target}_latest\"\n  docker_img_with_date=\"${target}_${img_push_date}\"\n  docker tag \"${source}\" \"${docker_img_with_latest}\"\n  docker tag \"${source}\" \"${docker_img_with_date}\"\n  docker push \"${docker_img_with_latest}\"\n  docker push \"${docker_img_with_date}\"\n}\n", "num_lines": 28}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource ./common.sh\n\nif [ -z ${1+x} ]; then\n  ECS_REPO=\"620771051181.dkr.ecr.us-west-2.amazonaws.com/aws-lc-docker-images-linux-x86\"\nelse\n  ECS_REPO=$1\nfi\n\necho \"Uploading docker images to ${ECS_REPO}.\"\n\n$(aws ecr get-login --no-include-email)\n\n# Tag images with date to help find old images, CodeBuild uses the latest tag and gets updated automatically\ntag_and_push_img 'ubuntu-16.04:gcc-5x' \"${ECS_REPO}:ubuntu-16.04_gcc-5x\"\ntag_and_push_img 'ubuntu-18.04:gcc-7x' \"${ECS_REPO}:ubuntu-18.04_gcc-7x\"\ntag_and_push_img 'ubuntu-18.04:clang-6x' \"${ECS_REPO}:ubuntu-18.04_clang-6x\"\ntag_and_push_img 'ubuntu-20.04:clang-7x' \"${ECS_REPO}:ubuntu-20.04_clang-7x\"\ntag_and_push_img 'ubuntu-20.04:clang-8x' \"${ECS_REPO}:ubuntu-20.04_clang-8x\"\ntag_and_push_img 'ubuntu-20.04:clang-9x' \"${ECS_REPO}:ubuntu-20.04_clang-9x\"\ntag_and_push_img 'ubuntu-20.04:clang-10x' \"${ECS_REPO}:ubuntu-20.04_clang-10x\"\ntag_and_push_img 'ubuntu-20.04:android' \"${ECS_REPO}:ubuntu-20.04_android\"\ntag_and_push_img 'ubuntu-20.04:clang-7x-bm-framework' \"${ECS_REPO}:ubuntu-20.04_clang-7x-bm-framework\"\ntag_and_push_img 'ubuntu-20.04:clang-10x_formal-verification' \"${ECS_REPO}:ubuntu-20.04_clang-10x_formal-verification\"\ntag_and_push_img 'ubuntu-20.04:gcc-7x' \"${ECS_REPO}:ubuntu-20.04_gcc-7x\"\ntag_and_push_img 'ubuntu-20.04:gcc-8x' \"${ECS_REPO}:ubuntu-20.04_gcc-8x\"\ntag_and_push_img 'ubuntu-22.04:gcc-11x' \"${ECS_REPO}:ubuntu-22.04_gcc-11x\"\ntag_and_push_img 'ubuntu-22.04:gcc-12x' \"${ECS_REPO}:ubuntu-22.04_gcc-12x\"\ntag_and_push_img 'centos-7:gcc-4x' \"${ECS_REPO}:centos-7_gcc-4x\"\ntag_and_push_img 'centos-8:gcc-8x' \"${ECS_REPO}:centos-8_gcc-8x\"\ntag_and_push_img 'amazonlinux-2:gcc-7x' \"${ECS_REPO}:amazonlinux-2_gcc-7x\"\ntag_and_push_img 'amazonlinux-2:clang-7x' \"${ECS_REPO}:amazonlinux-2_clang-7x\"\ntag_and_push_img 'amazonlinux-2:gcc-7x-intel-sde' \"${ECS_REPO}:amazonlinux-2_gcc-7x_intel-sde\"\ntag_and_push_img 'amazonlinux-2023:gcc-11x' \"${ECS_REPO}:amazonlinux-2023_gcc-11x\"\ntag_and_push_img 'amazonlinux-2023:clang-15x' \"${ECS_REPO}:amazonlinux-2023_clang-15x\"\ntag_and_push_img 'amazonlinux-2023:clang-15x-sanitizer' \"${ECS_REPO}:amazonlinux-2023_clang-15x_sanitizer\"\ntag_and_push_img 'amazonlinux-2023:cryptofuzz' \"${ECS_REPO}:amazonlinux-2023_clang-15x_cryptofuzz\"\ntag_and_push_img 'fedora-31:clang-9x' \"${ECS_REPO}:fedora-31_clang-9x\"\ntag_and_push_img 'ubuntu-10.04_gcc-4.1x' \"${ECS_REPO}:ubuntu-10.04_gcc-4.1x\"\n", "num_lines": 43}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nif [ -n \"$1\" ]; then\n  docker_tag=\"$1\"\nelse\n  docker_tag='ubuntu-20.04:clang-10x_formal-verification'\nfi\nrm -rf aws-lc-verification\ngit clone https://github.com/awslabs/aws-lc-verification.git\ncd aws-lc-verification\ndocker build -t ${docker_tag} .\ncd ..\nrm -rf aws-lc-verification\n", "num_lines": 16}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\ntrap dump_log EXIT\n\n# Set up environment.\n\n# SYS_ROOT\n#  |\n#  - SRC_ROOT(aws-lc)\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - mariadb\n#    - AWS_LC_BUILD_FOLDER\n#    - AWS_LC_INSTALL_FOLDER\n#    - MARIADB_BUILD_FOLDER\n\n# The CFlags, skipped test list, and patches were taken from the internal CI pipeline of our customer.\n\n# Assumes script is executed from the root of aws-lc directory\nSCRATCH_FOLDER=${SYS_ROOT}/\"MARIADB_BUILD_ROOT\"\nMARIADB_SRC_FOLDER=\"${SCRATCH_FOLDER}/server\"\nMARIADB_BUILD_FOLDER=\"${SCRATCH_FOLDER}/server/mariadb-aws-lc\"\nMARIADB_PATCH_FOLDER=${SRC_ROOT}/\"tests/ci/integration/mariadb_patch\"\nAWS_LC_BUILD_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-build\"\nAWS_LC_INSTALL_FOLDER=\"${MARIADB_SRC_FOLDER}/aws-lc-install\"\n\nmkdir -p ${SCRATCH_FOLDER}\nrm -rf ${SCRATCH_FOLDER}/*\ncd ${SCRATCH_FOLDER}\n\nfunction mariadb_build() {\n  cmake ${MARIADB_SRC_FOLDER} -GNinja -DWITH_SSL=${AWS_LC_INSTALL_FOLDER} \"-B${MARIADB_BUILD_FOLDER}\" -DPLUGIN_COLUMNSTORE=NO -DPLUGIN_ROCKSDB=NO -DPLUGIN_S3=NO -DPLUGIN_MROONGA=NO -DPLUGIN_CONNECT=NO -DPLUGIN_SPHINX=NO -DPLUGIN_SPIDER=NO -DPLUGIN_TOKUDB=NO -DPLUGIN_PERFSCHEMA=NO -DWITH_WSREP=OFF\n  ninja -C ${MARIADB_BUILD_FOLDER}\n  ls -R ${MARIADB_BUILD_FOLDER}\n}\n\n# Used to access debugging logs.\nfunction dump_log() {\n  ls ${MARIADB_BUILD_FOLDER}/mysql-test/var/log\n  for logfile in $(find -L \"${MARIADB_BUILD_FOLDER}/mysql-test/var/log\" -type f -name '*.log'); do\n    echo \"Dumping out logs to observe:\"\n    cat $logfile\n  done\n}\n\nfunction mariadb_run_tests() {\n  pushd ${MARIADB_BUILD_FOLDER}/mysql-test\n  # More complicated integration tests. mtr expects to be launched in-place and with write access to it's own directories\n  #\n  # main.plugin_load passes, but is skipped over since it generates a warning when we run the script in Codebuild. Warnings will cause\n  # a failure in MariaDB's test runs, unless --nowarnings is turned on. The warning is not reproducable in Gitlab's CI or any local\n  # container runs. This test isn't relevant to AWS-LC integration so we skip over the Codebuild specific issue for now.\n  echo \"main.mysqldump : Field separator argument is not what is expected; check the manual when executing 'SELECT INTO OUTFILE'\nmain.flush_logs_not_windows : query 'flush logs' succeeded - should have failed with error ER_CANT_CREATE_FILE (1004)\nmain.mysql_upgrade_noengine : upgrade output order does not match the expected\nmain.plugin_load : This test generates a warning in Codebuild. Skip over since this isn't relevant to AWS-LC. \"> skiplist\n  ./mtr --suite=main --force --parallel=auto --skip-test-list=${MARIADB_BUILD_FOLDER}/mysql-test/skiplist --retry-failure=2\n  popd\n}\n\n# TODO: Remove this when we make an upstream contribution.\nfunction mariadb_patch() {\n  for patchfile in $(find -L \"${MARIADB_PATCH_FOLDER}\" -type f -name '*.patch'); do\n    echo \"Apply patch $patchfile...\"\n    patch -p1 --quiet -i \"$patchfile\"\n  done\n}\n\n# Get latest mariadb version, we can pin to a specific version if MariaDB's code changes break us too often.\ngit clone https://github.com/MariaDB/server.git ${MARIADB_SRC_FOLDER} --depth 1\nmkdir -p ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} ${MARIADB_BUILD_FOLDER}\nls\n\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER}\npushd ${MARIADB_SRC_FOLDER}\nmariadb_patch\nmariadb_build\nmariadb_run_tests\npopd\n\n", "num_lines": 86}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\nMYSQL_VERSION_TAG=\"mysql-8.0.33\"\n# This directory is specific to the docker image used. Use -DDOWNLOAD_BOOST=1 -DWITH_BOOST=<directory>\n# with mySQL to download a compatible boost version locally.\nBOOST_INSTALL_FOLDER=/home/dependencies/boost\n\n# Set up environment.\n\n# SYS_ROOT\n#  |\n#  - SRC_ROOT(aws-lc)\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - mysql\n#    - AWS_LC_BUILD_FOLDER\n#    - AWS_LC_INSTALL_FOLDER\n#    - MYSQL_BUILD_FOLDER\n\n# Assumes script is executed from the root of aws-lc directory\nSCRATCH_FOLDER=${SYS_ROOT}/\"MYSQL_BUILD_ROOT\"\nMYSQL_SRC_FOLDER=\"${SCRATCH_FOLDER}/mysql-server\"\nMYSQL_BUILD_FOLDER=\"${SCRATCH_FOLDER}/server/mysql-aws-lc\"\nAWS_LC_BUILD_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-build\"\nAWS_LC_INSTALL_FOLDER=\"${MYSQL_SRC_FOLDER}/aws-lc-install\"\n\nmkdir -p ${SCRATCH_FOLDER}\nrm -rf ${SCRATCH_FOLDER}/*\ncd ${SCRATCH_FOLDER}\n\nfunction mysql_patch_reminder() {\n  LATEST_MYSQL_VERSION_TAG=mysql-`curl https://api.github.com/repos/mysql/mysql-server/tags | jq '.[].name' |grep '\\-8.0' |sed -e 's/\"mysql-cluster-\\(.*\\)\"/\\1/' |sort | tail -n 1`\n  if [[ \"${LATEST_MYSQL_VERSION_TAG}\" != \"${MYSQL_VERSION_TAG}\" ]]; then\n    aws cloudwatch put-metric-data --namespace AWS-LC --metric-name MySQLVersionMismatch --value 1\n  else\n    aws cloudwatch put-metric-data --namespace AWS-LC --metric-name MySQLVersionMismatch --value 0\n  fi\n}\n\nfunction mysql_build() {\n  cmake ${MYSQL_SRC_FOLDER} -GNinja -DENABLED_PROFILING=OFF -DWITH_NDB_JAVA=OFF  -DWITH_BOOST=${BOOST_INSTALL_FOLDER} -DWITH_SSL=${AWS_LC_INSTALL_FOLDER} \"-B${MYSQL_BUILD_FOLDER}\"\n  ninja -C ${MYSQL_BUILD_FOLDER}\n  ls -R ${MYSQL_BUILD_FOLDER}\n}\n\nfunction mysql_run_tests() {\n  pushd ${MYSQL_BUILD_FOLDER}\n  ninja test\n  popd\n}\n\n# Get latest MySQL version. MySQL often updates with large changes depending on OpenSSL all at once, so we pin to a specific version.\nmysql_patch_reminder\ngit clone https://github.com/mysql/mysql-server.git ${MYSQL_SRC_FOLDER} -b ${MYSQL_VERSION_TAG} --depth 1\nmkdir -p ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} ${MYSQL_BUILD_FOLDER}\nls\n\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER}\npushd ${MYSQL_SRC_FOLDER}\nmysql_build\n# TODO: There are still pending test failures that need to be resolved. Turn this on once we resolve them.\n# mysql_run_tests\npopd\n", "num_lines": 69}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\n# Set up environment.\n\n# SYS_ROOT\n#  |\n#  - SRC_ROOT(aws-lc)\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - openssh-portable\n#    - AWS_LC_BUILD_FOLDER\n#    - AWS_LC_INSTALL_FOLDER\n#    - OPENSSH_INSTALL_FOLDER\n\n# Assumes script is executed from the root of aws-lc directory\nSCRATCH_FOLDER=\"${SYS_ROOT}/SCRATCH_AWSLC_OPENSSH_INTERN_TEST\"\nAWS_LC_BUILD_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-build\"\nAWS_LC_INSTALL_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-install\"\nOPENSSH_WORKSPACE_FOLDER=\"${SCRATCH_FOLDER}/openssh-portable\"\nOPENSSH_INSTALL_FOLDER=\"${SCRATCH_FOLDER}/openssh-install\"\n\nNINJA_COMMAND=ninja\nif ! ${NINJA_COMMAND} --version; then\n  NINJA_COMMAND=ninja-build\nfi\n\n# Make script execution idempotent.\nrm -rf \"${SCRATCH_FOLDER}\"\nmkdir -p \"${SCRATCH_FOLDER}\"\npushd \"${SCRATCH_FOLDER}\"\n\n# Test helper functions.\n\nfunction install_aws_lc() {\n  AWS_LC_LIB_FOLDER=$(readlink -f \"${AWS_LC_INSTALL_FOLDER}\"/lib*)\n  # This installs AWS-LC as the \"libcrypto\" for the system\n  echo \"${AWS_LC_LIB_FOLDER}\" > /etc/ld.so.conf.d/aws-lc.conf\n  rm -f /etc/ld.so.cache\n  ldconfig\n}\n\nfunction openssh_build() {\n  pushd \"${OPENSSH_WORKSPACE_FOLDER}\"\n  autoreconf\n  # The RSA_meth_XXX functions are not implemented by AWS-LC, and the implementation provided by OpenSSH also doesn't compile for us.\n  # Fortunately, these functions are only needed for pkcs11 support, which is disabled for our build.\n  # See: https://github.com/openssh/openssh-portable/pull/385\n  export CFLAGS=\"-DAWS_LC_INTERNAL_IGNORE_BN_SET_FLAGS=1 -DHAVE_RSA_METH_FREE=1 -DHAVE_RSA_METH_DUP=1 -DHAVE_RSA_METH_SET1_NAME=1 -DHAVE_RSA_METH_SET_PRIV_ENC=1 -DHAVE_RSA_METH_SET_PRIV_DEC=1\"\n  ./configure --with-ssl-dir=\"${AWS_LC_INSTALL_FOLDER}\" --prefix=\"${OPENSSH_INSTALL_FOLDER}\" --disable-pkcs11\n  make install\n  ls -R \"${OPENSSH_INSTALL_FOLDER}\"\n  popd\n}\n\nfunction checkout_openssh_branch() {\n  pushd \"${OPENSSH_WORKSPACE_FOLDER}\"\n  make clean\n  git clean -f -d\n  git checkout --track origin/\"$1\"\n  popd\n}\n\nfunction openssh_run_tests() {\n  pushd \"${OPENSSH_WORKSPACE_FOLDER}\"\n  if ! id -u sshd; then\n    useradd sshd\n  fi\n  export TEST_SSH_UNSAFE_PERMISSIONS=1\n  export SKIP_LTESTS=\"$@\"\n  make tests\n  popd\n}\n\nmkdir -p \"${AWS_LC_BUILD_FOLDER}\" \"${AWS_LC_INSTALL_FOLDER}\" \"${OPENSSH_INSTALL_FOLDER}\"\n\n# Get latest OpenSSH version.\ngit clone https://github.com/openssh/openssh-portable.git\nls\n\n# Buld AWS-LC as a shared library\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} -DBUILD_SHARED_LIBS=1\ninstall_aws_lc\n\nCODEBUILD_SKIPPED_TESTS=\"agent-subprocess forwarding multiplex forward-control agent-restrict connection-timeout\"\n\n# Using default branch. Build openssh and run tests.\nopenssh_build\nopenssh_run_tests \"${CODEBUILD_SKIPPED_TESTS}\"\n\n# Using branch V_8_9\ncheckout_openssh_branch V_8_9\nopenssh_build\n# In v8.9, the \"percent\" test requires the 'openssl' cli command\nopenssh_run_tests \"percent ${CODEBUILD_SKIPPED_TESTS}\"\n\npopd\n\n", "num_lines": 103}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\n# Set up environment.\n\n# SYS_ROOT\n#  |\n#  - SRC_ROOT(aws-lc)\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - postgres\n#    - AWS_LC_BUILD_FOLDER\n#    - AWS_LC_INSTALL_FOLDER\n#    - POSTGRES_BUILD_FOLDER\n\n# Assumes script is executed from the root of aws-lc directory\nSCRATCH_FOLDER=${SYS_ROOT}/\"POSTGRES_BUILD_ROOT\"\nPOSTGRES_SRC_FOLDER=\"${SCRATCH_FOLDER}/postgres\"\nPOSTGRES_BUILD_FOLDER=\"${SCRATCH_FOLDER}/postgres/build\"\nAWS_LC_BUILD_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-build\"\nAWS_LC_INSTALL_FOLDER=\"${POSTGRES_SRC_FOLDER}/aws-lc-install\"\n\nmkdir -p ${SCRATCH_FOLDER}\nrm -rf ${SCRATCH_FOLDER}/*\ncd ${SCRATCH_FOLDER}\n\nfunction postgres_build() {\n  ./configure --with-openssl --enable-tap-tests --with-includes=${AWS_LC_INSTALL_FOLDER}/include --with-libraries=${AWS_LC_INSTALL_FOLDER}/lib --prefix=$(pwd)/build\n  make -j ${NUM_CPU_THREADS}\n  # Build additional modules for postgres.\n  make -j ${NUM_CPU_THREADS} -C contrib all\n  ls -R build\n}\n\nfunction postgres_run_tests() {\n  make -j ${NUM_CPU_THREADS} check\n  # Run additional tests, particularly the \"SSL\" tests.\n  make -j ${NUM_CPU_THREADS} check-world PG_TEST_EXTRA='ssl'\n  cd ${SCRATCH_FOLDER}\n}\n\n# SSL tests expect the OpenSSL style of error messages. We patch this to expect AWS-LC's style.\n# TODO: Remove this when we make an upstream contribution.\nfunction postgres_patch() {\n  POSTGRES_ERROR_STRING=(\"certificate verify failed\" \"bad decrypt\" \"sslv3 alert certificate revoked\" \"tlsv1 alert unknown ca\")\n  AWS_LC_EXPECTED_ERROR_STRING=(\"CERTIFICATE_VERIFY_FAILED\" \"BAD_DECRYPT\" \"SSLV3_ALERT_CERTIFICATE_REVOKED\" \"TLSV1_ALERT_UNKNOWN_CA\")\n  for i in \"${!POSTGRES_ERROR_STRING[@]}\"; do\n    find ./ -type f -name \"001_ssltests.pl\" | xargs sed -i -e \"s|${POSTGRES_ERROR_STRING[$i]}|${AWS_LC_EXPECTED_ERROR_STRING[$i]}|g\"\n  done\n}\n\n# Get latest postgres version.\ngit clone https://github.com/postgres/postgres.git ${POSTGRES_SRC_FOLDER}\nmkdir -p ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} ${POSTGRES_BUILD_FOLDER}\nls\n\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER}\ncd ${POSTGRES_SRC_FOLDER}\npostgres_patch\npostgres_build\npostgres_run_tests\n\n", "num_lines": 67}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nsource tests/ci/common_posix_setup.sh\n\n# Set up environment.\n\n# SYS_ROOT\n#  |\n#  - SRC_ROOT(aws-lc)\n#  |\n#  - SCRATCH_FOLDER\n#    |\n#    - s2n-tls\n#    - AWS_LC_BUILD_FOLDER\n#    - AWS_LC_INSTALL_FOLDER\n#    - S2N_TLS_BUILD_FOLDER\n\n# Assumes script is executed from the root of aws-lc directory\nSCRATCH_FOLDER=${SYS_ROOT}/\"SCRATCH_AWSLC_S2N_INTERN_TEST\"\nAWS_LC_BUILD_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-build\"\nAWS_LC_INSTALL_FOLDER=\"${SCRATCH_FOLDER}/aws-lc-install\"\nS2N_TLS_BUILD_FOLDER=\"${SCRATCH_FOLDER}/s2n-tls-build\"\n\n# Make script execution idempotent.\nmkdir -p ${SCRATCH_FOLDER}\nrm -rf ${SCRATCH_FOLDER}/*\ncd ${SCRATCH_FOLDER}\n\n# Test helper functions.\n# Assumes OS where the Ninja executable is named \"ninja\". This is not true for\n# AL2 for example.\n\nfunction fail() {\n    echo \"test failure: $1\"\n    exit 1\n}\n\nfunction s2n_tls_build() {\n\t${CMAKE_COMMAND} s2n-tls -GNinja \"-B${S2N_TLS_BUILD_FOLDER}\" \"-DCMAKE_PREFIX_PATH=${AWS_LC_INSTALL_FOLDER}\" \"$@\"\n\tninja -C ${S2N_TLS_BUILD_FOLDER}\n\tls -R ${S2N_TLS_BUILD_FOLDER}\n}\n\nfunction s2n_tls_run_tests() {\n\tcd ${S2N_TLS_BUILD_FOLDER}\n\tctest -j ${NUM_CPU_THREADS} --output-on-failure\n\tcd ${SCRATCH_FOLDER}\n}\n\nfunction s2n_tls_prepare_new_build() {\n\trm -rf ${S2N_TLS_BUILD_FOLDER}/*\n}\n\n# Get latest s2n-tls version.\n\nmkdir -p ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} ${S2N_TLS_BUILD_FOLDER}\ngit clone https://github.com/aws/s2n-tls.git\nls\n\n# s2n-tls's FindLibCrypto.cmake expects to find both the static and shared\n# libcrypto objects. We can't use existing test helper functions\n# (e.g. run_build()) because they make implicit assumptions about e.g. build\n# folders.\n\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} -DBUILD_SHARED_LIBS=0\naws_lc_build ${SRC_ROOT} ${AWS_LC_BUILD_FOLDER} ${AWS_LC_INSTALL_FOLDER} -DBUILD_SHARED_LIBS=1\n\n# Build s2n-tls+aws-lc and run s2n-tls tests. First using static aws-lc\n# libcrypto and then shared aws-lc libcrypto.\n\ns2n_tls_build\ns2n_tls_run_tests\ns2n_tls_prepare_new_build\n\ns2n_tls_build -DBUILD_SHARED_LIBS=1\ns2n_tls_run_tests\ns2n_tls_prepare_new_build\n\n# Test interned s2n-tls+aws-lc against both static and shared aws-lc libcrypto.\n\ns2n_tls_build -DS2N_INTERN_LIBCRYPTO=1\ns2n_tls_run_tests\ns2n_tls_prepare_new_build\n\ns2n_tls_build -DBUILD_SHARED_LIBS=1 -DS2N_INTERN_LIBCRYPTO=1\n# Sanity check that libcrypto does not appear in the .dynamic ELF section.\nldd ${S2N_TLS_BUILD_FOLDER}/lib/libs2n.so | grep -q libcrypto && fail \"libs2n.so declares a dynamic dependency on libcrypto which should not happen with interned s2n-tls+aws-lc\"\ns2n_tls_run_tests\ns2n_tls_prepare_new_build\n", "num_lines": 92}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# This test is aimed to run with GCC 6 and above on x86-64 architectures.\n\nINCLUDE_DIR=\"./include\"\n\nINCLUDE_FILES=`ls $INCLUDE_DIR/openssl/*.h | grep -v $INCLUDE_DIR/openssl/arm_arch.h`\n\n# - This compilation line gets no source files as its input (it uses the -c flag).\n#   Instead it uses the force include flag (-include) to include all of headers\n#   except for arm_arch.h, which cannot run on x86-64 architectures.\n# - The -Wpedantic flag ensures that the compiler will fault if a non C99 line \n#   exists in the code.\n# - The -fsyntax-only tells the compiler to check the syntax without producing \n#   any outputs.\n#\n# This test has some known limitations:\n# \"Some users try to use -Wpedantic to check programs for strict ISO C\n# conformance. They soon find that it does not do quite what they want: it finds\n# some non-ISO practices, but not all \u00e2\u20ac\u201d only those for which ISO C requires a\n# diagnostic, and some others for which diagnostics have been added.\"\n# https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html\n\n${CC} -std=c99 -c -I${INCLUDE_DIR} -include ${INCLUDE_FILES} -Wpedantic -fsyntax-only -Werror\n\n# AWS C SDKs conforms to C99. They set `C_STANDARD 99` which will set the\n# flag `-std=gnu99`\n# https://github.com/awslabs/aws-c-common/blob/main/cmake/AwsCFlags.cmake\n# https://github.com/aws/aws-encryption-sdk-c/blob/master/cmake/AwsCryptosdkCFlags.cmake\n# https://cmake.org/cmake/help/latest/prop_tgt/C_STANDARD.html\n#\n# the c99 and gnu99 modes are different, so let's test both.\n\n${CC} -std=gnu99 -c -I${INCLUDE_DIR} -include ${INCLUDE_FILES} -Wpedantic -fsyntax-only -Werror\n", "num_lines": 37}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n./tests/coding_guidelines/style.sh\n./tests/coding_guidelines/c99_gcc_test.sh\n", "num_lines": 7}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\n# This test reports on common style mistakes.\n\n# Test 1: Check for headers without #pragma once\n# - Ignore third party libraries\n# - Ignore the file md32_common.h which is included several times in different\n#   contexts (TODO:Fix this)\n# - If the last grep did not match any file (success) it returns an error code\n#   that terminates the script. We avoid this by adding the final '|| true'\nHEADERS_WITHOUT_PRAGMA=`find . -type f -name \"*.h\" | grep -v third_party | \n\t                grep -v md32_common.h | xargs grep -L \"pragma once\" ||\n                        true`\nif [ ! -z \"$HEADERS_WITHOUT_PRAGMA\" ] ; then\n  echo \"The following headers do not contain the 'pragma once' guard:\n        $HEADERS_WITHOUT_PRAGMA\"\n  # TODO: re-enable \"#pragma once\" when CI is active.\n  # exit -1\nfi\n\n", "num_lines": 23}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (c) 2016, Google Inc.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\nset -xe\n\nSRC=$PWD\n\nBUILD=$(mktemp -d '/tmp/boringssl.XXXXXX')\nBUILD_SRC=$(mktemp -d '/tmp/boringssl-src.XXXXXX')\nLCOV=$(mktemp -d '/tmp/boringssl-lcov.XXXXXX')\n\nif [ -n \"$1\" ]; then\n  LCOV=$(readlink -f \"$1\")\n  mkdir -p \"$LCOV\"\nfi\n\ncd \"$BUILD\"\ncmake \"$SRC\" -GNinja -DGCOV=1\nninja\n\ncp -r \"$SRC/crypto\" \"$SRC/include\" \"$SRC/ssl\" \"$SRC/tool\" \\\n  \"$BUILD_SRC\"\ncp -r \"$BUILD\"/* \"$BUILD_SRC\"\nmkdir \"$BUILD/callgrind/\"\n\ncd \"$SRC\"\ngo run \"$SRC/util/all_tests.go\" -build-dir \"$BUILD\" -callgrind -num-workers 16\nutil/generate-asm-lcov.py \"$BUILD/callgrind\" \"$BUILD\" > \"$BUILD/asm.info\"\n\ngo run \"util/all_tests.go\" -build-dir \"$BUILD\"\n\ncd \"$SRC/ssl/test/runner\"\ngo test -shim-path \"$BUILD/ssl/test/bssl_shim\" -num-workers 1\n\ncd \"$LCOV\"\nlcov -c -d \"$BUILD\" -b \"$BUILD\" -o \"$BUILD/lcov.info\"\nlcov -r \"$BUILD/lcov.info\" -o \"$BUILD/filtered.info\" \"*_test.c\" \"*_test.cc\" \"*/third_party/googletest/*\"\ncat \"$BUILD/filtered.info\" \"$BUILD/asm.info\" > \"$BUILD/final.info\"\nsed -i \"s;$BUILD;$BUILD_SRC;g\" \"$BUILD/final.info\"\nsed -i \"s;$SRC;$BUILD_SRC;g\" \"$BUILD/final.info\"\ngenhtml -p \"$BUILD_SRC\" \"$BUILD/final.info\"\n\nrm -rf \"$BUILD\"\nrm -rf \"$BUILD_SRC\"\n\nxdg-open index.html\n", "num_lines": 59}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "#------------------------------------------------------------------------------------\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n#------------------------------------------------------------------------------------\n\nset -exo pipefail\n\nBENCH_DIR=${PWD}\nAWSLC_DIR=${BENCH_DIR}/../aws-lc\nOPENSSL_DIR=${BENCH_DIR}/../openssl\nPROJECT=benchmark_ec_p256\nOPENSSL102=0\n\n# Process input parameters and append them to the options string\noptions=''\nwhile [[ \"$#\" -gt 0 ]]; do\n    case $1 in\n        -t|--test)\n            options+=\" -t $2\";\n            shift ;;\n        -m|--msec)\n            options+=\" -m $2\";\n            shift ;;\n        --ossl102)\n            OPENSSL102=1;\n            OPENSSL102_DIR=${BENCH_DIR}/../openssl102/openssl;;\n        --counter)\n            CNTR_REG=1;;\n        *)\n            echo \"Unknown parameter passed: $1\" && \\\n            echo \"Possible options are: \" && \\\n            echo \" benchmark-build-run.sh [-t|--test <\\\"ecdhp256\\\"|\\\"ecdsap256\\\">]\" && \\\n            echo \"                        [-m|--msec <milliseconds>]\" && \\\n            echo \"                        [--ossl102]\" && \\\n            echo \"                        [--counter]\";\n            exit 1 ;;\n    esac\n    shift\ndone\n\n# Check that AWS-LC directory exists\nif [[ ! -d ${AWSLC_DIR} ]]\nthen\n    echo \"AWS-LC directory not found: ${AWSLC_DIR}\"; exit 1;\n## checkout AWS-LC if it doesn't exist already\n#     echo \"Checkout AWS-LC main tip\" && \\\n#         cd .. && \\\n#         git clone https://github.com/aws/aws-lc.git && \\\n#         cd ${BENCH_DIR}\nfi\n\n# build AWS-LC\necho \"Build AWS-LC\" && \\\n    cd ${AWSLC_DIR} && \\\n    mkdir -p build && \\\n    cd build && \\\n    cmake -DCMAKE_BUILD_TYPE=Release -GNinja .. && \\\n    ninja && \\\n    cd ${BENCH_DIR}\n\n# checkout OpenSSL if it doesn't exist already\nif [[ ! -d ${OPENSSL_DIR} ]]\nthen\n    echo \"Checkout tag OpenSSL_1_1_1h from OpenSSL\" && \\\n        cd .. && \\\n        git clone --branch OpenSSL_1_1_1h --single-branch https://github.com/openssl/openssl.git && \\\n        cd ${BENCH_DIR}\nfi\n\n# build OpenSSL if libcrypto.a doesn't exist\n[[ ! -f ${OPENSSL_DIR}/libcrypto.a ]] && \\\n    echo \"Build OpenSSL\" && \\\n    cd ${OPENSSL_DIR} && \\\n    ./config && \\\n    make && \\\n    cd ${BENCH_DIR}\n\n# checkout OpenSSL 1.0.2u (Dec 20, 2019) if specified\nif [[ \"${OPENSSL102}\" -eq 1 ]]\nthen\n    if [[ ! -d ${OPENSSL102_DIR} ]]\n    then\n        echo \"Checkout tag OpenSSL_1_0_2u from OpenSSL\" && \\\n            cd .. && \\\n            mkdir -p openssl102 && \\\n            cd openssl102 && \\\n            git clone --branch OpenSSL_1_0_2u --single-branch https://github.com/openssl/openssl.git && \\\n            cd ${BENCH_DIR}\n    fi\n    # build OpenSSL 1.0.2 if libcrypto.a doesn't exist\n    if [[ ! -f ${OPENSSL102_DIR}/libcrypto.a ]]\n    then\n        echo \"Build OpenSSL 1.0.2\" && \\\n            cd ${OPENSSL102_DIR}\n\n        if [[ \"${OSTYPE}\" == \"darwin\"* ]]\n        then\n            ./Configure darwin64-x86_64-cc && \\\n                make\n        else\n            ./config && \\\n                make\n        fi\n        cd ${BENCH_DIR}\n    fi\nfi\n\n\n# build benchmark binaries\necho \"Build benchmark binaries\" && \\\n    mkdir -p build && \\\n    cd build && \\\n    cmake -DOPENSSL102_LIB=\"${OPENSSL102}\" -DCOUNTER_REGISTER=\"${CNTR_REG}\" .. && \\\n    cmake --build . && \\\n    BUILD_SUCCESS=1\n\n# run benchmarks\nif [[ \"${BUILD_SUCCESS}\" -eq 1 ]]\nthen\n    echo\n    echo \"Run P-256 AWS-LC benchmarks\"\n    ./${PROJECT}_awslc ${options}\n\n    echo\n    echo \"Run P-256 OPENSSL benchmarks\"\n    if [[ \"${OSTYPE}\" == \"darwin\"* ]]\n    then\n        DYLD_LIBRARY_PATH=${OPENSSL_DIR} ./${PROJECT}_ossl ${options}\n    else\n        LD_LIBRARY_PATH=${OPENSSL_DIR} ./${PROJECT}_ossl ${options}\n    fi\n\n    if [[ \"${OPENSSL102}\" -eq 1 ]]\n    then\n        echo\n        echo \"Run P-256 OPENSSL 1.0.2 benchmarks\"\n        if [[ \"${OSTYPE}\" == \"darwin\"* ]]\n        then\n            DYLD_LIBRARY_PATH=${OPENSSL102_DIR} ./${PROJECT}_ossl102 ${options}\n        else\n            LD_LIBRARY_PATH=${OPENSSL102_DIR} ./${PROJECT}_ossl102 ${options}\n        fi\n    fi\nfi\n", "num_lines": 145}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright (c) 2022, Google Inc.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# This script runs test_fips repeatedly with different FIPS tests broken. It is\n# intended to be observed to demonstrate that the various tests are working and\n# thus pauses for a keystroke between tests.\n#\n# Runs in either device mode (on an attached Android device) or in a locally built\n# BoringSSL checkout.\n#\n# On Android static binaries are not built using FIPS mode, so in device mode each\n# test makes changes to libcrypto.so rather than the test binary, test_fips.\n\nset -e\n\ndie () {\n  echo \"ERROR: $@\"\n  exit 1\n}\n\nusage() {\n  echo \"USAGE: $0 [local|device]\"\n  exit 1\n}\n\ninferred_mode() {\n  # Try and infer local or device mode based on makefiles and artifacts.\n  if [ -f Android.bp -o -f external/boringssl/Android.bp ]; then\n    echo device\n  elif [ -f CMakeLists.txt -a -d build/crypto -a -d build/ssl ]; then\n    echo local\n  else\n    echo \"Unable to infer mode, please specify on the command line.\"\n    usage\n  fi\n}\n\n# Prefer mode from command line if present.\ncase \"$1\" in\n  local|device)\n    MODE=$1\n    ;;\n\n  \"\")\n    MODE=`inferred_mode`\n    ;;\n\n  *)\n    usage\n    ;;\nesac\n\ncheck_directory() {\n  test -d \"$1\" || die \"Directory $1 not found.\"\n}\n\ncheck_file() {\n  test -f \"$1\" || die \"File $1 not found.\"\n}\n\nrun_test_locally() {\n  eval \"$1\" || true\n}\n\nrun_test_on_device() {\n  EXECFILE=\"$1\"\n  LIBRARY=\"$2\"\n  adb shell rm -rf \"$DEVICE_TMP\"\n  adb shell mkdir -p \"$DEVICE_TMP\"\n  adb push \"$EXECFILE\" \"$DEVICE_TMP\" > /dev/null\n  EXECPATH=$(basename \"$EXECFILE\")\n  adb push \"$LIBRARY\" \"$DEVICE_TMP\" > /dev/null\n  adb shell \"LD_LIBRARY_PATH=$DEVICE_TMP\" \"$DEVICE_TMP/$EXECPATH\" || true\n}\n\ndevice_integrity_break_test() {\n  go run \"$BORINGSSL/util/fipstools/break-hash.go\" \"$LIBCRYPTO_BIN\" ./libcrypto.so\n  $RUN \"$TEST_FIPS_BIN\" ./libcrypto.so\n  rm ./libcrypto.so\n}\n\nlocal_integrity_break_test() {\n  go run $BORINGSSL/util/fipstools/break-hash.go \"$TEST_FIPS_BIN\" ./break-bin\n  chmod u+x ./break-bin\n  $RUN ./break-bin\n  rm ./break-bin\n}\n\nlocal_runtime_break_test() {\n  BORINGSSL_FIPS_BREAK_TEST=$1 \"$RUN\" \"$TEST_FIPS_BREAK_BIN\"\n}\n\n# TODO(prb): make break-hash and break-kat take similar arguments to save having\n# separate functions for each.\ndevice_kat_break_test() {\n  KAT=\"$1\"\n  go run \"$BORINGSSL/util/fipstools/break-kat.go\" \"$LIBCRYPTO_BREAK_BIN\" \"$KAT\" > ./libcrypto.so\n  $RUN \"$TEST_FIPS_BIN\" ./libcrypto.so\n  rm ./libcrypto.so\n}\n\nlocal_kat_break_test() {\n  KAT=\"$1\"\n  go run \"$BORINGSSL/util/fipstools/break-kat.go\" \"$TEST_FIPS_BREAK_BIN\" \"$KAT\" > ./break-bin\n  chmod u+x ./break-bin\n  $RUN ./break-bin\n  rm ./break-bin\n}\n\npause () {\n  echo -n \"Press <Enter> \"\n  read\n}\n\nif [ \"$MODE\" = \"local\" ]; then\n  TEST_FIPS_BIN=${TEST_FIPS_BIN:-build/util/fipstools/test_fips}\n  TEST_FIPS_BREAK_BIN=${TEST_FIPS_BREAK_BIN:-./test_fips_break}\n  check_file \"$TEST_FIPS_BIN\"\n  check_file \"$TEST_FIPS_BREAK_BIN\"\n\n  BORINGSSL=.\n  RUN=run_test_locally\n  BREAK_TEST=local_break_test\n  INTEGRITY_BREAK_TEST=local_integrity_break_test\n  KAT_BREAK_TEST=local_kat_break_test\n  RUNTIME_BREAK_TEST=local_runtime_break_test\n  if [ ! -f \"$TEST_FIPS_BIN\" ]; then\n    echo \"$TEST_FIPS_BIN is missing. Run this script from the top level of a\"\n    echo \"BoringSSL checkout and ensure that BoringSSL has been built in\"\n    echo \"build/ with -DFIPS_BREAK_TEST=TESTS passed to CMake.\"\n    exit 1\n  fi\nelse # Device mode\n  test \"$ANDROID_BUILD_TOP\" || die \"'lunch aosp_arm64-eng' first\"\n  check_directory \"$ANDROID_PRODUCT_OUT\"\n\n  TEST_FIPS_BIN=\"$ANDROID_PRODUCT_OUT/system/bin/test_fips\"\n  check_file \"$TEST_FIPS_BIN\"\n  LIBCRYPTO_BIN=\"$ANDROID_PRODUCT_OUT/system/lib64/libcrypto.so\"\n  LIBCRYPTO_BREAK_BIN=\"libcrypto.so\"\n  check_file \"$LIBCRYPTO_BIN\"\n  check_file \"$LIBCRYPTO_BREAK_BIN\"\n\n  test \"$ANDROID_SERIAL\" || die \"ANDROID_SERIAL not set\"\n  DEVICE_TMP=/data/local/tmp\n\n  BORINGSSL=\"$ANDROID_BUILD_TOP/external/boringssl/src\"\n  RUN=run_test_on_device\n  INTEGRITY_BREAK_TEST=device_integrity_break_test\n  KAT_BREAK_TEST=device_kat_break_test\nfi\n\n\nKATS=$(go run \"$BORINGSSL/util/fipstools/break-kat.go\" --list-tests)\n\necho -e '\\033[1mNormal output\\033[0m'\n$RUN \"$TEST_FIPS_BIN\" \"$LIBCRYPTO_BIN\"\npause\n\necho\necho -e '\\033[1mIntegrity test failure\\033[0m'\n$INTEGRITY_BREAK_TEST\npause\n\nfor kat in $KATS; do\n  echo\n  echo -e \"\\033[1mKAT failure ${kat}\\033[0m\"\n  $KAT_BREAK_TEST $kat\n  pause\ndone\n\nif [ \"$MODE\" = \"local\" ]; then\n  # TODO(prb): add support for Android devices.\n  for runtime_test in ECDSA_PWCT RSA_PWCT CRNG; do\n    echo\n    echo -e \"\\033[1m${runtime_test} failure\\033[0m\"\n    $RUNTIME_BREAK_TEST ${runtime_test}\n    pause\n  done\nfi\n", "num_lines": 192}
{"repo_name": "aws-lc", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright (c) 2022, Google Inc.\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY\n# SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION\n# OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN\n# CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n# This script attempts to break each of the known KATs and checks that doing so\n# seems to work and at least mentions the correct KAT in the output.\n\nset -x\nset -e\n\nTEST_FIPS_BIN=\"test_build_dir/util/fipstools/test_fips\"\n\nif [ ! -f $TEST_FIPS_BIN ]; then\n  echo \"$TEST_FIPS_BIN is missing. Run this script from the top level of a\"\n  echo \"BoringSSL checkout and ensure that ./build-fips-break-test-binaries.sh\"\n  echo \"has been run first.\"\n  exit 1\nfi\n\nKATS=$(go run util/fipstools/break-kat.go --list-tests)\n\nfor kat in $KATS; do\n  go run util/fipstools/break-kat.go $TEST_FIPS_BIN $kat > break-kat-bin\n  chmod u+x ./break-kat-bin\n  if ! (./break-kat-bin 2>&1 >/dev/null || true) | \\\n       egrep -q \"^$kat[^a-zA-Z0-9]\"; then\n    echo \"Failure for $kat did not mention that name in the output\"\n    exit 1\n  fi\n  rm ./break-kat-bin\ndone\necho \"All tests broken as expected\"\n", "num_lines": 43}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nROOT=$PWD\nRUSTLS_RING_STRING=\"^ring = \\\".*\\\"\"\nRUSTLS_OUR_STRING=\"ring = { path = \\\"${PWD}\\\", package = \\\"aws-lc-rs\\\"}\"\n\ngit clone https://github.com/rustls/rustls.git\ncd rustls\n\n# replace instances of ring with our crate\nif [[ \"$(uname)\" == \"Darwin\" ]]; then\n\tfind ./ -type f  -name \"Cargo.toml\" | xargs sed -i '' \"s|${RUSTLS_RING_STRING}|${RUSTLS_OUR_STRING}|g\"\nelse\n\tfind ./ -type f  -name \"Cargo.toml\" | xargs sed -i \"s|${RUSTLS_RING_STRING}|${RUSTLS_OUR_STRING}|g\"\nfi\ncargo test\n", "num_lines": 19}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -exu\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nROOT=$PWD\nQUIC_RING_STRING=\"^ring = { .* optional .* }\"\nQUIC_OUR_STRING=\"ring = { path = \\\"${PWD}\\\", optional = true, package = \\\"aws-lc-rs\\\"}\"\nQUIC_CRYPTO_RING_STRING=\"^ring = { .* }\"\nQUIC_CRYPTO_OUR_STRING=\"ring = { path = \\\"${PWD}\\\", package = \\\"aws-lc-rs\\\"}\"\n\ngit clone https://github.com/aws/s2n-quic.git\ncd s2n-quic\n\n# replace instances of ring with our crate\nif [[ \"$(uname)\" == \"Darwin\" ]]; then\n\tfind ./ -type f  -name \"Cargo.toml\" | xargs sed -i '' -e \"s|${QUIC_RING_STRING}|${QUIC_OUR_STRING}|g\" -e \"s|${QUIC_CRYPTO_RING_STRING}|${QUIC_CRYPTO_OUR_STRING}|g\"\nelse\n\tfind ./ -type f  -name \"Cargo.toml\" | xargs sed -i -e \"s|${QUIC_RING_STRING}|${QUIC_OUR_STRING}|g\" -e \"s|${QUIC_CRYPTO_RING_STRING}|${QUIC_CRYPTO_OUR_STRING}|g\"\nfi\ncargo test\n", "num_lines": 21}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -ex\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\n#############################################\n# Build images from aws-lc-rs GitHub repo #\n#############################################\n\n# Linux hosts might not have \"jq\" installed.\n\n# Ubuntu:\n# sudo apt-get install jq\n\n# Amazon Linux:\n# sudo yum install jq\n\n# Log Docker hub limit https://docs.docker.com/docker-hub/download-rate-limit/#how-can-i-check-my-current-rate\nTOKEN=$(curl \"https://auth.docker.io/token?service=registry.docker.io&scope=repository:ratelimitpreview/test:pull\" | jq -r .token)\ncurl --head -H \"Authorization: Bearer $TOKEN\" https://registry-1.docker.io/v2/ratelimitpreview/test/manifests/latest\n\npushd \"${REPO_ROOT}/docker\" &>/dev/null\ndocker build -t rust:linux-386 linux-386 --load\ndocker build -t rust:linux-arm64 linux-arm64 --load\ndocker build -t rust:linux-x86_64 linux-x86_64 --load\npopd &>/dev/null\n", "num_lines": 30}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nIGNORE_DIRTY=0\nIGNORE_BRANCH=0\nIGNORE_UPSTREAM=0\nSKIP_TEST=0\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\nsource \"${SCRIPT_DIR}\"/_generation_tools.sh\n\ngeneration_options \"$@\"\nshift $((OPTIND - 1))\n\nassert_docker_status\n\npushd \"${REPO_ROOT}\" &>/dev/null\n\ncheck_workspace $IGNORE_DIRTY\ncheck_branch $IGNORE_BRANCH $IGNORE_UPSTREAM\n\nvalidate_crate_version \"${REPO_ROOT}/aws-lc-fips-sys\"\n\nSCRIPT_ARGS=(-c aws-lc-fips-sys)\n\n\"${SCRIPT_DIR}\"/_run_supported_symbol_builds.sh -f \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_generate_prefix_headers.sh \"${SCRIPT_ARGS[@]}\"\n# TODO: Can we trigger this in docker and still get the confirmation prompt? -a STDIN does not work correctly here\n#docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${SCRIPT_DIR}/_verify_crate_api_diff.sh ${SCRIPT_ARGS[*]}\"\n\"${SCRIPT_DIR}\"/_verify_crate_api_diff.sh \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_generate_all_bindings_flavors.sh -f \"${SCRIPT_ARGS[@]}\"\ndocker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${SCRIPT_DIR}/_verify_crate_packaging.sh ${SCRIPT_ARGS[*]}\"\n\n# Crate testing.\nif [[ ${SKIP_TEST} -eq 1 ]]; then\n  echo Aborting. Crate generated but not tested.\n  exit 1\nfi\n\"${SCRIPT_DIR}\"/_test_supported_builds.sh \"${SCRIPT_ARGS[@]}\" -f\n\nsubmodule_commit_metadata aws-lc-fips-sys\n\npopd &>/dev/null # ${REPO_ROOT}\n\necho 'Generation Succeeded!'\n\n", "num_lines": 52}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nIGNORE_DIRTY=0\nIGNORE_BRANCH=0\nIGNORE_UPSTREAM=0\nIGNORE_MACOS=0\nSKIP_TEST=0\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\nsource \"${SCRIPT_DIR}\"/_generation_tools.sh\n\ngeneration_options \"$@\"\nshift $((OPTIND - 1))\n\nassert_docker_status\n\npushd \"${REPO_ROOT}\" &>/dev/null\n\ncheck_workspace $IGNORE_DIRTY\ncheck_branch $IGNORE_BRANCH $IGNORE_UPSTREAM\n\nIS_MACOS_HOST=$(check_running_on_macos [[ $IGNORE_MACOS -eq 0 ]])\nif [[ $IS_MACOS_HOST -ne 0 ]]; then\n  echo Script is not running on macOS!\nfi\n\nvalidate_crate_version \"${REPO_ROOT}/aws-lc-sys\"\n\nSCRIPT_ARGS=(-c aws-lc-sys)\nif [[ ${IGNORE_MACOS} -eq 1 ]]; then\n  SCRIPT_ARGS=(\"${SCRIPT_ARGS[@]}\" -m)\nfi\n\n\"${SCRIPT_DIR}\"/_run_supported_symbol_builds.sh \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_generate_prefix_headers.sh \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_verify_crate_api_diff.sh \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_generate_all_bindings_flavors.sh \"${SCRIPT_ARGS[@]}\"\n\"${SCRIPT_DIR}\"/_verify_crate_packaging.sh \"${SCRIPT_ARGS[@]}\"\n\n# Crate testing.\nif [[ ${SKIP_TEST} -eq 1 ]]; then\n  echo Aborting. Crate generated but not tested.\n  exit 1\nfi\n\"${SCRIPT_DIR}\"/_test_supported_builds.sh \"${SCRIPT_ARGS[@]}\"\n\nsubmodule_commit_metadata aws-lc-sys\n\npopd &>/dev/null # ${REPO_ROOT}\n\necho 'Generation Succeeded!'\n\n", "num_lines": 59}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n  echo \"-f fips build\"\n}\n\nfunction cmake_build_options() {\n  if [[ \"${GENERATE_FIPS}\" -eq 0 ]]; then\n    echo \"-DDISABLE_GO=ON -DDISABLE_PERL=ON -DBUILD_LIBSSL=ON\"\n  else\n    echo \"-DFIPS=1 -DBUILD_LIBSSL=ON\"\n  fi\n}\n\nfunction filter_symbols() {\n  if [[ \"${GENERATE_FIPS}\" -eq 0 ]]; then\n    grep -v \"^_\\?bignum_\" | grep -v \"_\\?curve25519_x25519\" | grep -v \"pqcrystals\"\n  else\n    grep -v \"^_\\?bignum_\" | grep -v \"_\\?curve25519_x25519\" | grep -v \"pqcrystals\" | grep -v \"OPENSSL_armcap_P\"\n  fi\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGENERATE_FIPS=0\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:f option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  f)\n    GENERATE_FIPS=1\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\nAWS_LC_DIR=\"${CRATE_DIR}/aws-lc\"\nTARGET_PLATFORM_ARCH=$(\"${REPO_ROOT}\"/scripts/tools/target-platform.rs)\nTARGET_PLATFORM=$(echo \"${TARGET_PLATFORM_ARCH}\" | cut -d ' ' -f 1)\nTARGET_ARCH=$(echo \"${TARGET_PLATFORM_ARCH}\" | cut -d ' ' -f 2)\nSYMBOLS_DIR=\"${CRATE_DIR}/symbols\"\nSYMBOLS_FILE=\"${SYMBOLS_DIR}/${TARGET_PLATFORM}_${TARGET_ARCH}.txt\"\n\nTEMP_BUILD_DIR=\"$(mktemp -d)\"\n\nif [[ ! -d ${CRATE_DIR} || ! -d ${TEMP_BUILD_DIR} || -z \"${TARGET_PLATFORM}\" || -z \"${TARGET_ARCH}\" ]]; then\n  echo \"$(basename \"$0\")\" Sanity Check Failed\n  exit 1\nfi\n\necho Building in: \"${TEMP_BUILD_DIR}\"\nmkdir -p \"${TEMP_BUILD_DIR}\"\npushd \"${TEMP_BUILD_DIR}\" &>/dev/null\n\nif [[ $(type -P \"cmake3\") ]]; then\n  CMAKE=cmake3\nelse\n  CMAKE=cmake\nfi\n\ngo env -w GOPROXY=direct\n${CMAKE} \"${AWS_LC_DIR}\" $(cmake_build_options)\n${CMAKE} --build . --target clean\n${CMAKE} --build . --target crypto ssl\n\npushd \"${AWS_LC_DIR}\" &>/dev/null\ngo run -mod readonly \"${AWS_LC_DIR}\"/util/read_symbols.go \"${TEMP_BUILD_DIR}/crypto/libcrypto.a\" \"${TEMP_BUILD_DIR}/ssl/libssl.a\" | filter_symbols >\"${SYMBOLS_FILE}\"\npopd &>/dev/null # ${AWS_LC_DIR}\n\npopd &>/dev/null # ${TEMP_BUILD_DIR}\n\nrm -rf \"${TEMP_BUILD_DIR}\"\n\necho DONE\n", "num_lines": 93}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:f option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must not be empty\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\nTEMP_TARGET_DIR=$(mktemp -d)\n\nif [[ ! -d ${TEMP_TARGET_DIR} || ! -d ${CRATE_DIR} ]]; then\n  echo \"$(basename \"${0}\")\" Sanity Check Failed\n  exit 1\nfi\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\nexport GOPROXY=direct\n\ncargo clean --target-dir \"${TEMP_TARGET_DIR}\"\ncargo test --target-dir \"${TEMP_TARGET_DIR}\" --release\ncargo test --target-dir \"${TEMP_TARGET_DIR}\" --release --features ssl\n\nrm -rf \"${TEMP_TARGET_DIR}\" &>/dev/null || true\n\npopd &>/dev/null\n", "num_lines": 53}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\nsource \"${SCRIPT_DIR}/_generation_tools.sh\"\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n  echo \"-f FIPS build\"\n  echo \"-m Ignore macOS\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGENERATE_FIPS=0\nIGNORE_MACOS=0\nRELATIVE_CRATE_PATH=\"\"\nGEN_BINDINGS_SCRIPT=\"${SCRIPT_DIR}/_generate_bindings.sh\"\n\nwhile getopts c:fm option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  f)\n    GENERATE_FIPS=1\n    ;;\n  m)\n    IGNORE_MACOS=1\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nassert_docker_status\n\npushd \"${REPO_ROOT}\" &>/dev/null\n\npids=\"\"\nif [[ \"${GENERATE_FIPS}\" -eq 0 ]]; then\n  ## macOS bindings\n  IS_MACOS_HOST=$(check_running_on_macos [[ $IGNORE_MACOS -eq 0 ]])\n  if [[ $IS_MACOS_HOST -eq 0 ]]; then\n    ${GEN_BINDINGS_SCRIPT} -c \"${RELATIVE_CRATE_PATH}\" &\n  else\n    echo Script is not running on macOS.\n    echo Bindings will not be generated for macOS!\n    echo\n  fi\n\n  ## TODO: Find a way to pre-generate bindings for macos-aarch64 on the fly.\n\n  ##\n  ## These docker image can be built from Dockerfiles under: <AWS-LC-DIR>/tests/ci/docker_images/rust\n  ##\n\n  ## 386 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/386 rust:linux-386 /bin/bash -c \"${GEN_BINDINGS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## linux x86_64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${GEN_BINDINGS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## linux aarch64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 rust:linux-arm64 /bin/bash -c \"${GEN_BINDINGS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n\nelse\n  ## linux x86_64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${GEN_BINDINGS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## linux aarch64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 rust:linux-arm64 /bin/bash -c \"${GEN_BINDINGS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n\nfi\n\necho \"Waiting for build completion\"\nfor pid in ${pids}; do\n  wait ${pid}\ndone\n\npopd &>/dev/null # ${REPO_ROOT}\n", "num_lines": 96}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:f option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must not be empty\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\nTEMP_TARGET_DIR=$(mktemp -d)\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\ngo env -w GOPROXY=direct\n\ncargo clean --target-dir \"${TEMP_TARGET_DIR}\"\n# Sets AWS_LC_RUST_INTERNAL_BINDGEN=1 which will cause the generation bindings for a specific platform. This feature\n# is only intended for internal use thus is not a cargo feature. Requires bindgen to be enabled. The internal_bindgen\n# config is enabled so that the final crates doesn't expect to find the dynamically generated bindings.rs\nenv AWS_LC_RUST_INTERNAL_BINDGEN=1 cargo build --target-dir \"${TEMP_TARGET_DIR}\" --features bindgen,ssl\ncargo clean --target-dir \"${TEMP_TARGET_DIR}\"\n\npopd &>/dev/null # ${CRATE_DIR}\n\nrm -rf \"${TEMP_TARGET_DIR}\" &>/dev/null || true\n", "num_lines": 51}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:fm option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\nAWS_LC_DIR=\"${CRATE_DIR}/aws-lc\"\nSYMBOLS_DIR=\"${CRATE_DIR}/symbols\"\nGEN_INCLUDE_DIR=\"${CRATE_DIR}/generated-include\"\n\npushd \"${AWS_LC_DIR}\" &>/dev/null\nTEMP_FILE=$(mktemp)\n\nfind \"${SYMBOLS_DIR}\" -type f -print0 | env LC_ALL=C xargs -0 sort | uniq >\"${TEMP_FILE}\"\ngo env -w GOPROXY=direct\ngo run -mod readonly \"${AWS_LC_DIR}\"/util/make_prefix_headers.go -out \"${GEN_INCLUDE_DIR}\" \"${TEMP_FILE}\"\nrm \"${TEMP_FILE}\" &>/dev/null || true\n\npopd &>/dev/null # ${AWS_LC_DIR}\n", "num_lines": 47}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nfunction usage {\n  echo\n  echo \"Usage: $(basename \"${0}\") [-d] [-b] [-u] [-m] [-s]\"\n  echo\n}\n\nfunction generation_options {\n  while getopts \"dbums\" option; do\n    case ${option} in\n    d)\n      IGNORE_DIRTY=1\n      ;;\n    b)\n      IGNORE_BRANCH=1\n      ;;\n    u)\n      IGNORE_UPSTREAM=1\n      ;;\n    m)\n      IGNORE_MACOS=1\n      ;;\n    s)\n      SKIP_TEST=1\n      ;;\n    *)\n      echo Invalid argument: -\"${?}\"\n      usage\n      exit 1\n      ;;\n    esac\n  done\n}\n\nfunction check_workspace {\n  local IGNORE_DIRTY=$1\n\n  if [[ $(git status --porcelain | wc -l) -gt 0 ]]; then\n    echo Workspace is dirty.\n    if [[ ${IGNORE_DIRTY} -eq 0 ]]; then\n      echo Aborting. Use '-d' to ignore.\n      echo\n      exit 1\n    else\n      echo Ignoring dirty workspace.\n      echo\n    fi\n  fi\n}\n\nfunction check_branch {\n  local IGNORE_BRANCH=$1\n  local IGNORE_UPSTREAM=$2\n  local CURRENT_BRANCH\n\n  CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)\n  if [ \"${CURRENT_BRANCH}\" != \"main\" ]; then\n    echo Branch is not main.\n    if [[ ${IGNORE_BRANCH} -eq 0 ]]; then\n      echo Aborting. Use '-b' to ignore.\n      echo\n      exit 1\n    else\n      echo Ignoring wrong branch.\n      echo\n    fi\n  fi\n\n  local UPSTREAM\n  UPSTREAM=$(git status -sb | head -n 1 | sed -e 's/^## \\(.*\\.\\.\\.\\)*\\(.*\\)$/\\2/')\n  if [ -z \"${UPSTREAM}\" ]; then\n    echo No upstream branch found.\n    if [[ ${IGNORE_UPSTREAM} -eq 0 ]]; then\n      echo Aborting. Use '-u' to ignore.\n      echo\n      exit 1\n    else\n      echo Ignoring missing upstream branch.\n      echo\n      return 0\n    fi\n  fi\n\n  local LOCAL_HASH\n  local UPSTREAM_HASH\n  git fetch\n  LOCAL_HASH=$(git rev-parse HEAD)\n  UPSTREAM_HASH=$(git rev-parse \"${UPSTREAM}\")\n\n  if [[ ! \"${LOCAL_HASH}\" == \"${UPSTREAM_HASH}\" ]]; then\n    echo \"${CURRENT_BRANCH}\" not up to date with upstream.\n    if [[ ${IGNORE_UPSTREAM} -eq 0 ]]; then\n      echo Aborting. Use '-u' to ignore.\n      echo\n      exit 1\n    else\n      echo Ignoring branch not up to date.\n      echo\n    fi\n  fi\n}\n\n# If host is macOS returns successfully (zero value return)\nfunction check_running_on_macos {\n  local FAIL_NON_MACOS=$1\n  if [[ \"$(uname)\" =~ [Dd]arwin ]]; then\n    return 0\n  fi\n  if [[ $FAIL_NON_MACOS -eq 1 ]]; then\n    echo Script is not running on macOS.\n    echo Aborting. Use '-m' to ignore.\n    echo\n    exit 1\n  fi\n  return 1\n}\n\nfunction assert_docker_status {\n  if ! docker stats --no-stream &>/dev/null; then\n    echo Please start the Docker daemon to continue.\n    exit 1\n  fi\n}\n\nfunction parse_version {\n  local VERSION=\"${1}\"\n  echo Version: \"${VERSION}\"\n  echo \"${VERSION}\" | egrep -q '^[0-9]+\\.[0-9]+\\.[0-9]+$'\n}\n\nfunction prompt_yes_no {\n  while true; do\n    read -p \"$1 (y/n): \" yn\n    case $yn in\n    [Yy]*) break ;;\n    [Nn]*) return 1 ;;\n    *) echo \"Please answer (y)es or (n)o.\" ;;\n    esac\n  done\n  return 0\n}\n\nfunction validate_crate_version {\n  local CRATE_DIR=$1\n  local REPO_ROOT\n  REPO_ROOT=$(git rev-parse --show-toplevel)\n\n  pushd \"${CRATE_DIR}\" &>/dev/null\n\n  local CRATE_NAME\n  CRATE_NAME=$(\"${REPO_ROOT}\"/scripts/tools/cargo-dig.rs -n)\n\n  local CRATE_VERSION\n  CRATE_VERSION=$(\"${REPO_ROOT}\"/scripts/tools/cargo-dig.rs -v)\n\n  PUBLISHED_CRATE_VERSION=$(cargo search \"${CRATE_NAME}\" | egrep \"^${CRATE_NAME} \" | sed -e 's/.*\"\\(.*\\)\".*/\\1/')\n\n  if ! parse_version \"${PUBLISHED_CRATE_VERSION}\"; then\n    echo Could not find current version of published crate.\n    exit 1\n  fi\n\n  echo\n  echo \"Current published version of ${CRATE_NAME}: ${PUBLISHED_CRATE_VERSION}\"\n  if parse_version \"${CRATE_VERSION}\"; then\n    if ! perl -e \"exit !(version->parse('${CRATE_VERSION}')>version->parse('${PUBLISHED_CRATE_VERSION}'))\"; then\n      echo \"New version must come after: ${PUBLISHED_CRATE_VERSION}\"\n      exit 1\n    fi\n  else\n    echo Could not parse version: \"${CRATE_VERSION}\"\n    exit 1\n  fi\n\n  popd &>/dev/null # \"${CRATE_DIR}\"\n\n  echo\n  echo \"Generating crate with version: ${CRATE_VERSION}\"\n}\n\nfunction submodule_commit_metadata {\n  local CRATE_DIR=$1\n  local REPO_ROOT\n  REPO_ROOT=$(git rev-parse --show-toplevel)\n\n  pushd \"${REPO_ROOT}\" &>/dev/null\n  COMMIT_HASH=$(git submodule status -- ${CRATE_DIR}/aws-lc | sed -e 's/.\\([0-9a-f]*\\).*/\\1/')\n  perl -pi -e \"s/commit-hash .*/commit-hash = \\\"${COMMIT_HASH}\\\"/\" ${CRATE_DIR}/Cargo.toml\n  popd &>/dev/null\n}\n", "num_lines": 193}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\nsource \"${SCRIPT_DIR}/_generation_tools.sh\"\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f] [-m]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n  echo \"-f fips build\"\n  echo \"-m ignore mac\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nCOLLECT_SYMBOLS_SCRIPT=\"${SCRIPT_DIR}/_collect_symbols_build.sh\"\nGENERATE_FIPS=0\nIGNORE_MACOS=0\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:fm option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  f)\n    GENERATE_FIPS=1\n    ;;\n  m)\n    IGNORE_MACOS=1\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nassert_docker_status\n\npushd \"${REPO_ROOT}\" &>/dev/null\n\n##\n## These docker image can be built from Dockerfiles under: <AWS-LC-DIR>/tests/ci/docker_images/rust\n##\npids=''\nif [[ \"${GENERATE_FIPS}\" -eq 0 ]]; then\n  ## macOS symbols\n  IS_MACOS_HOST=$(check_running_on_macos [[ $IGNORE_MACOS -eq 0 ]])\n  if [[ $IS_MACOS_HOST -eq 0 ]]; then\n    ${COLLECT_SYMBOLS_SCRIPT} -c \"${RELATIVE_CRATE_PATH}\" &\n  else\n    echo Script is not running on macOS.\n    echo Symbols will not be collected for macOS!\n    echo\n  fi\n\n  ## 386 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/386 -- rust:linux-386 /bin/bash -c \"${COLLECT_SYMBOLS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## x86_64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 -- rust:linux-x86_64 /bin/bash -c \"${COLLECT_SYMBOLS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## arm64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 -- rust:linux-arm64 /bin/bash -c \"${COLLECT_SYMBOLS_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n\nelse\n\n  ## x86_64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 -- rust:linux-x86_64 /bin/bash -c \"${COLLECT_SYMBOLS_SCRIPT} -c ${RELATIVE_CRATE_PATH} -f\" &\n  pids=\"$! ${pids}\"\n  ## arm64 build\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 -- rust:linux-arm64 /bin/bash -c \"${COLLECT_SYMBOLS_SCRIPT} -c ${RELATIVE_CRATE_PATH} -f\" &\n  pids=\"$! ${pids}\"\nfi\n\nfor pid in ${pids}; do\n  wait ${pid}\ndone\n\npopd &>/dev/null # ${REPO_ROOT}\n", "num_lines": 92}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nsource \"${SCRIPT_DIR}/_generation_tools.sh\"\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n  echo \"-f FIPS build\"\n  echo \"-m Ignore macOS\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nGENERATE_FIPS=0\nIGNORE_MACOS=0\nRELATIVE_CRATE_PATH=\"\"\nCRATE_TEST_SCRIPT=\"${SCRIPT_DIR}/_crate_test_build.sh\"\n\nwhile getopts c:f option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  f)\n    GENERATE_FIPS=1\n    ;;\n  m)\n    IGNORE_MACOS=1\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nassert_docker_status\n\npushd \"${REPO_ROOT}\" &>/dev/null\n\npids=''\nif [[ \"${GENERATE_FIPS}\" -eq 0 ]]; then\n  ### Test crate on Mac\n  IS_MACOS_HOST=$(check_running_on_macos [[ $IGNORE_MACOS -eq 0 ]])\n  if [[ $IS_MACOS_HOST -eq 0 ]]; then\n    ${CRATE_TEST_SCRIPT} -c \"${RELATIVE_CRATE_PATH}\" &\n  else\n    echo Script is not running on macOS.\n    echo Crate will not be tested on macOS!\n    echo\n  fi\n\n  ## 386 test\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/386 rust:linux-386 /bin/bash -c \"${CRATE_TEST_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## x86_64 test\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${CRATE_TEST_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## arm64 test\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 rust:linux-arm64 /bin/bash -c \"${CRATE_TEST_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\nelse\n  ## x86_64 test\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${CRATE_TEST_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\n  ## arm64 test\n  docker run -v \"$(pwd)\":\"$(pwd)\" -w \"$(pwd)\" --rm --platform linux/arm64 rust:linux-arm64 /bin/bash -c \"${CRATE_TEST_SCRIPT} -c ${RELATIVE_CRATE_PATH}\" &\n  pids=\"$! ${pids}\"\nfi\n\necho \"Waiting for tests to complete\"\nfor pid in ${pids}; do\n  wait ${pid}\ndone\n\npopd &>/dev/null # ${REPO_ROOT}\n", "num_lines": 87}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\nsource \"${SCRIPT_DIR}/_generation_tools.sh\"\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo \"Performs an API diff of the crate to the published version\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:fm option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\nCRATE_NAME=$(\"${REPO_ROOT}\"/scripts/tools/cargo-dig.rs -n)\nCRATE_VERSION=$(\"${REPO_ROOT}\"/scripts/tools/cargo-dig.rs -v)\n\nPUBLISHED_CRATE_VERSION=$(cargo search \"${CRATE_NAME}\" | egrep \"^${CRATE_NAME} \" | sed -e 's/.*\"\\(.*\\)\".*/\\1/')\n\nif ! parse_version \"${PUBLISHED_CRATE_VERSION}\"; then\n  echo Could not find current version of published crate.\n  exit 1\nfi\n\nTEMP_TARGET_DIR=$(mktemp -d)\n\ngo env -w GOPROXY=direct\n\nenv AWS_LC_RUST_INTERNAL_BINDGEN=1 cargo build --target-dir \"${TEMP_TARGET_DIR}\" --features bindgen\nif ! cargo +nightly-2023-01-04 public-api --target-dir \"${TEMP_TARGET_DIR}\" diff --deny changed --deny removed \"${PUBLISHED_CRATE_VERSION}\"; then\n  echo\n  echo \"Version changing from: ${PUBLISHED_CRATE_VERSION} to ${CRATE_VERSION}\"\n  if ! prompt_yes_no \"API changes found.  Continue with crate generation?\"; then\n    rm -rf \"${TEMP_TARGET_DIR}\"\n    popd &>/dev/null # ${CRATE_DIR}\n    exit 1\n  fi\nfi\n\nrm -rf \"${TEMP_TARGET_DIR}\"\n\npopd &>/dev/null # ${CRATE_DIR}\n", "num_lines": 70}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo \"Validates that the target crate can be packaged and built from the package\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:fm option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\ngo env -w GOPROXY=direct\n\nTEMP_TARGET_DIR=$(mktemp -d)\ncargo package --target-dir \"${TEMP_TARGET_DIR}\" --allow-dirty\nrm -rf \"${TEMP_TARGET_DIR}\"\n\npopd &>/dev/null # ${CRATE_DIR}\n", "num_lines": 45}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\nPUBLISH=0\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=aws-lc-fips-sys\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\nsource \"${SCRIPT_DIR}\"/_publish_tools.sh\n\npublish_options \"$@\"\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\ncat << HERE > ./aws-lc/go.mod\nmodule boringssl.googlesource.com/boringssl\n\ngo 1.13\nHERE\n\nrun_prepublish_checks -c \"${RELATIVE_CRATE_PATH}\"\npublish_crate \"${RELATIVE_CRATE_PATH}\" ${PUBLISH}\ngit --git-dir=\"${CRATE_DIR}/aws-lc/.git\" restore go.mod\npopd &>/dev/null\n", "num_lines": 29}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\nPUBLISH=0\nRELATIVE_CRATE_PATH=aws-lc-rs\n\nsource \"${SCRIPT_DIR}\"/_publish_tools.sh\n\npublish_options \"$@\"\n\npushd \"${CRATE_DIR}\" &>/dev/null\nrun_prepublish_checks -c \"${RELATIVE_CRATE_PATH}\"\npublish_crate \"${RELATIVE_CRATE_PATH}\" ${PUBLISH}\npopd &>/dev/null\n", "num_lines": 19}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nSCRIPT_DIR=$(cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\nPUBLISH=0\nREPO_ROOT=$(git rev-parse --show-toplevel)\nRELATIVE_CRATE_PATH=aws-lc-sys\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\nsource \"${SCRIPT_DIR}\"/_publish_tools.sh\n\npublish_options \"$@\"\n\npushd \"${CRATE_DIR}\" &>/dev/null\nrun_prepublish_checks -c \"${RELATIVE_CRATE_PATH}\"\npublish_crate \"${RELATIVE_CRATE_PATH}\" ${PUBLISH}\npopd &>/dev/null\n", "num_lines": 21}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nset -e\n\nfunction usage {\n  echo \"Usage: $(basename \"${0}\"): -c CRATE_PATH [-f]\"\n  echo\n  echo \"-c CRATE_PATH The relative crate path from the repository root\"\n}\n\nRELATIVE_CRATE_PATH=\"\"\n\nwhile getopts c:f option; do\n  case $option in\n  c)\n    RELATIVE_CRATE_PATH=\"${OPTARG}\"\n    ;;\n  ?)\n    usage\n    exit 1\n    ;;\n  esac\ndone\n\nif [[ -z \"${RELATIVE_CRATE_PATH}\" ]]; then\n  echo \"Relative crate path must be provided\"\n  exit 1\nfi\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nCRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\nTEMP_TARGET_DIR=$(mktemp -d)\n\npushd \"${CRATE_DIR}\" &>/dev/null\n\nexport GOPROXY=direct\n\ncargo clean --target-dir \"${TEMP_TARGET_DIR}\"\ncargo clippy --fix --allow-no-vcs\ncargo fmt\ncargo test --target-dir \"${TEMP_TARGET_DIR}\" # sanity check\ncargo package --target-dir \"${TEMP_TARGET_DIR}\" --allow-dirty # checks if published package will build.\ncargo clean --target-dir \"${TEMP_TARGET_DIR}\"\n\npopd &>/dev/null # \"${CRATE_DIR}\"\n\nrm -rf \"${TEMP_TARGET_DIR}\" &>/dev/null || true\n", "num_lines": 51}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0 OR ISC\n\nfunction usage {\n  echo\n  echo \"Usage: $(basename \"${0}\") [-p]\"\n  echo\n  echo \"-p Actually publish the crate (defaults to dry-run)\"\n  echo\n}\n\nfunction publish_options {\n  while getopts \"p\" option; do\n    case ${option} in\n    p)\n      PUBLISH=1\n      ;;\n    *)\n      echo Invalid argument: -\"${?}\"\n      usage\n      exit 1\n      ;;\n    esac\n  done\n}\n\nfunction run_prepublish_checks {\n  local SCRIPT_DIR\n  SCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n  \"${SCRIPT_DIR}\"/_prepublish_checks.sh \"$@\"\n}\n\n# FIPS static build is only supported on linux.\nfunction run_prepublish_checks_linux {\n  local SCRIPT_DIR\n  SCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n  local REPO_ROOT\n  REPO_ROOT=$(git rev-parse --show-toplevel)\n  docker run -v \"${REPO_ROOT}\":\"${REPO_ROOT}\" -w \"${REPO_ROOT}\" --rm --platform linux/amd64 rust:linux-x86_64 /bin/bash -c \"${SCRIPT_DIR}/_prepublish_checks.sh $*\"\n}\n\nfunction publish_crate {\n  local RELATIVE_CRATE_PATH=$1\n  local PUBLISH=$2\n  local REPO_ROOT\n  REPO_ROOT=$(git rev-parse --show-toplevel)\n  local CRATE_DIR=\"${REPO_ROOT}/${RELATIVE_CRATE_PATH}\"\n\n  pushd \"${CRATE_DIR}\" &>/dev/null\n\n  cargo publish --dry-run --allow-dirty\n\n  if [[ ${PUBLISH} -eq 1 ]]; then\n    cargo publish --allow-dirty\n  else\n    echo Not published. Use -p to publish.\n  fi\n\n  popd &>/dev/null # \"${CRATE_DIR}\"\n\n  return\n}\n", "num_lines": 63}
{"repo_name": "aws-lc-rs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\nset -e\n\nAWS_LC_RS_FILES=$(find \"$PWD\" -type f \\( -name \"*.rs\" -o -name \"*.sh\" \\) -not \\( -path \"*/aws-lc-fips-sys/aws-lc/*\" -o -path \"*/aws-lc-sys/aws-lc/*\" -o -path \"*/target/*\" \\))\n\nFAILED=0\n\nfor file in $AWS_LC_RS_FILES; do\n    # The word \"Copyright\" should appear at least once in the first 3 lines of every file\n    COUNT=`head -n 3 \"${file}\" | grep \"Copyright\" | wc -l`;\n    if [ \"${COUNT}\" -eq \"0\" ]; then\n        FAILED=1;\n        echo \"Copyright Check Failed: $file\";\n    fi\ndone\n\nif [ $FAILED == 1 ]; then\n    printf \"\\\\033[31;1mFAILED Copyright Check\\\\033[0m\\\\n\"\n    exit -1\nelse\n    printf \"\\\\033[32;1mPASSED Copyright Check\\\\033[0m\\\\n\"\nfi\n", "num_lines": 28}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -x\n\n# install adduser and add the airflow user\nyum update -y\nyum install -y shadow-utils\nadduser -s /bin/bash -d \"${AIRFLOW_USER_HOME}\" airflow\nyum install -y sudo\n\necho 'airflow ALL=(ALL)NOPASSWD:ALL' | sudo EDITOR='tee -a' visudo\n\nyum erase openssl-devel -y\nyum install openssl11 openssl11-devel libffi-devel bzip2-devel wget tar xz -y\n# Install python optional standard libary module dependencies \nyum install ncurses-devel gdbm-devel readline-devel xz-libs xz-devel uuid-devel libuuid-devel -y \nyum install glibc -y\n\n# install system dependency to enable the installation of most Airflow extras\nyum install -y gcc gcc-c++ cyrus-sasl-devel python3-devel python3-wheel make\n\n# install sqlite to avoid local-runner Airflow error messages\nyum install -y sqlite-devel\n\n# Python 3.10 install\nsudo mkdir python_install\npython_file=Python-$PYTHON_VERSION\npython_tar=$python_file.tar\npython_xz=$python_tar.xz\nsudo mkdir python_source\nwget \"https://www.python.org/ftp/python/$PYTHON_VERSION/$python_xz\" -P /python_source\ncp /python_source/$python_xz /python_install/$python_xz\nunxz ./python_install/$python_xz\ntar -xf ./python_install/$python_tar -C ./python_install\n\npushd /python_install/$python_file \n./configure --enable-optimizations --enable-loadable-sqlite-extensions --prefix=/usr ## Override the install at /usr/bin/python3\nmake install -j $(nproc) # use -j to set the cores for the build\npopd\n\n# Upgrade pip\npip3 install $PIP_OPTION --upgrade 'pip<23'\n\n# openjdk is required for JDBC to work with Airflow\nyum install -y java-1.8.0-openjdk\n\n# Installing mariadb-devel dependency for apache-airflow-providers-mysql.\n# The mariadb-devel provided by AL2 conflicts with openssl11 which is required Python 3.10\n# so a newer version of the dependency must be installed from source.\nsudo mkdir mariadb_rpm\nsudo chown airflow /mariadb_rpm\n\nif [[ $(uname -p) == \"aarch64\" ]]; then\n\twget https://dlm.mariadb.com/2592621/MariaDB/mariadb-10.8.6/yum/rhel7-aarch64/rpms/MariaDB-common-10.8.4-1.el7.centos.aarch64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2592615/MariaDB/mariadb-10.8.6/yum/rhel7-aarch64/rpms/MariaDB-compat-10.8.4-1.el7.centos.aarch64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2592630/MariaDB/mariadb-10.8.6/yum/rhel7-aarch64/rpms/MariaDB-shared-10.8.4-1.el7.centos.aarch64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2592622/MariaDB/mariadb-10.8.6/yum/rhel7-aarch64/rpms/MariaDB-devel-10.8.4-1.el7.centos.aarch64.rpm -P /mariadb_rpm\nelse\n\twget https://dlm.mariadb.com/2596575/MariaDB/mariadb-10.8.6/yum/rhel7-amd64/rpms/MariaDB-common-10.8.6-1.el7.centos.x86_64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2596577/MariaDB/mariadb-10.8.6/yum/rhel7-amd64/rpms/MariaDB-compat-10.8.6-1.el7.centos.x86_64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2596582/MariaDB/mariadb-10.8.6/yum/rhel7-amd64/rpms/MariaDB-shared-10.8.6-1.el7.centos.x86_64.rpm -P /mariadb_rpm\n\twget https://dlm.mariadb.com/2596593/MariaDB/mariadb-10.8.6/yum/rhel7-amd64/rpms/MariaDB-devel-10.8.6-1.el7.centos.x86_64.rpm -P /mariadb_rpm\nfi\n\n# install mariadb_devel and its dependencies\nsudo rpm -ivh /mariadb_rpm/*\n\n# install minimal Airflow packages\nsudo -u airflow pip3 install $PIP_OPTION --no-use-pep517 --constraint /constraints.txt poetry\nsudo -u airflow pip3 install $PIP_OPTION --constraint /constraints.txt cached-property\nsudo -u airflow pip3 install $PIP_OPTION --constraint /constraints.txt wheel \nsudo -u airflow pip3 install $PIP_OPTION --constraint /constraints.txt --use-deprecated legacy-resolver apache-airflow[celery,statsd\"${AIRFLOW_DEPS:+,}${AIRFLOW_DEPS}\"]==\"${AIRFLOW_VERSION}\"\n\n# install celery[sqs] and its dependencies\nyum install -y libcurl-devel \n# see https://stackoverflow.com/questions/49200056/pycurl-import-error-ssl-backend-mismatch\nexport PYCURL_SSL_LIBRARY=openssl11\nsudo -u airflow pip3 install $PIP_OPTION --compile pycurl\nsudo -u airflow pip3 install $PIP_OPTION celery[sqs]\n\n# install postgres Python driver and its dependencies\nyum install -y postgresql-devel\nsudo -u airflow pip3 install $PIP_OPTION psycopg2\n\n# install unixODBC-devel to support pyodbc\nyum install -y unixODBC-devel\n\n# install additional python dependencies\nif [ -n \"${PYTHON_DEPS}\" ]; then sudo -u airflow pip3 install $PIP_OPTION \"${PYTHON_DEPS}\"; fi\n\nMWAA_BASE_PROVIDERS_FILE=/mwaa-base-providers-requirements.txt\necho \"Installing providers supported for airflow version ${AIRFLOW_VERSION}\"\nsudo -u airflow pip3 install $PIP_OPTION -r $MWAA_BASE_PROVIDERS_FILE\n\n# jq is used to parse json\nyum install -y jq\n\n# nc is used to check DB connectivity\nyum install -y nc\n\n# install archiving packages\nyum install -y zip unzip bzip2 gzip # tar\n\n# install awscli v2\nzip_file=\"awscliv2.zip\"\ncd /tmp\ncurl \"https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip\" -o $zip_file\nunzip $zip_file\n./aws/install\nrm $zip_file\nrm -rf ./aws\ncd -  # Return to previous directory\n\nyum clean all\n", "num_lines": 116}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nTRY_LOOP=\"20\"\n\n# Global defaults\n: \"${AIRFLOW_HOME:=\"/usr/local/airflow\"}\"\n: \"${AIRFLOW__CORE__FERNET_KEY:=${FERNET_KEY:=$(cat /usr/local/etc/airflow_fernet_key)}}\"\n: \"${AIRFLOW__CORE__EXECUTOR:=${EXECUTOR:-Sequential}Executor}\"\n: \"${REQUIREMENTS_FILE:=\"requirements/requirements.txt\"}\"\n\n# Load DAGs examples (default: Yes)\nif [[ -z \"$AIRFLOW__CORE__LOAD_EXAMPLES\" && \"${LOAD_EX:=n}\" == n ]]; then\n  AIRFLOW__CORE__LOAD_EXAMPLES=False\nfi\n\nexport \\\n  AIRFLOW_HOME \\\n  AIRFLOW__CORE__EXECUTOR \\\n  AIRFLOW__CORE__FERNET_KEY \\\n  AIRFLOW__CORE__LOAD_EXAMPLES \\\n\n# Install custom python package if requirements.txt is present\ninstall_requirements() {\n    # Install custom python package if requirements.txt is present\n    if [[ -e \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\" ]]; then\n      if ! grep -- \"-c \" \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\"\n      then\n          if ! grep -- \"--constraint \" \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\"\n          then\n              echo \"WARNING: Constraints should be specified for requirements.txt. Please see https://docs.aws.amazon.com/mwaa/latest/userguide/working-dags-dependencies.html#working-dags-dependencies-test-create\"\n          fi\n      fi    \n        echo \"Installing requirements.txt\"\n        pip3 install --user -r \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\"\n    fi\n}\n\n# Download custom python WHL files and package as ZIP if requirements.txt is present\npackage_requirements() {\n    # Download custom python WHL files and package as ZIP if requirements.txt is present\n    if [[ -e \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\" ]]; then\n        echo \"Packaging requirements.txt into plugins\"\n        pip3 download -r \"$AIRFLOW_HOME/$REQUIREMENTS_FILE\" -d \"$AIRFLOW_HOME/plugins\"\n        cd \"$AIRFLOW_HOME/plugins\"\n        zip \"$AIRFLOW_HOME/requirements/plugins.zip\" *\n        printf '%s\\n%s\\n' \"--no-index\" \"$(cat $AIRFLOW_HOME/$REQUIREMENTS_FILE)\" > \"$AIRFLOW_HOME/requirements/packaged_requirements.txt\"\n        printf '%s\\n%s\\n' \"--find-links /usr/local/airflow/plugins\" \"$(cat $AIRFLOW_HOME/requirements/packaged_requirements.txt)\" > \"$AIRFLOW_HOME/requirements/packaged_requirements.txt\"\n    fi\n}\n\nwait_for_port() {\n  local name=\"$1\" host=\"$2\" port=\"$3\"\n  local j=0\n  while ! nc -z \"$host\" \"$port\" >/dev/null 2>&1 < /dev/null; do\n    j=$((j+1))\n    if [ $j -ge $TRY_LOOP ]; then\n      echo >&2 \"$(date) - $host:$port still not reachable, giving up\"\n      exit 1\n    fi\n    echo \"$(date) - waiting for $name... $j/$TRY_LOOP\"\n    sleep 5\n  done\n}\n\nexecute_startup_script() {\n  # Execute customer provided shell script\n  if [[ -e \"$AIRFLOW_HOME/startup/startup.sh\" ]]; then\n    bash /shell-launch-script.sh\n    source stored_env\n    export AIRFLOW_HOME=\"/usr/local/airflow\"\n    export AIRFLOW__CORE__LOAD_EXAMPLES=\"False\"\n    cd \"$AIRFLOW_HOME\"\n  else\n    echo \"No startup script found, skipping execution.\"\n  fi\n}\n\n# Other executors than SequentialExecutor drive the need for an SQL database, here PostgreSQL is used\nif [ \"$AIRFLOW__CORE__EXECUTOR\" != \"SequentialExecutor\" ]; then\n  # Check if the user has provided explicit Airflow configuration concerning the database\n  if [ -z \"$AIRFLOW__CORE__SQL_ALCHEMY_CONN\" ]; then\n    # Default values corresponding to the default compose files\n    : \"${POSTGRES_HOST:=\"postgres\"}\"\n    : \"${POSTGRES_PORT:=\"5432\"}\"\n    : \"${POSTGRES_USER:=\"airflow\"}\"\n    : \"${POSTGRES_PASSWORD:=\"airflow\"}\"\n    : \"${POSTGRES_DB:=\"airflow\"}\"\n    : \"${POSTGRES_EXTRAS:-\"\"}\"\n\n    AIRFLOW__CORE__SQL_ALCHEMY_CONN=\"postgresql+psycopg2://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_HOST}:${POSTGRES_PORT}/${POSTGRES_DB}${POSTGRES_EXTRAS}\"\n    export AIRFLOW__CORE__SQL_ALCHEMY_CONN\n  else\n    # Derive useful variables from the AIRFLOW__ variables provided explicitly by the user\n    POSTGRES_ENDPOINT=$(echo -n \"$AIRFLOW__CORE__SQL_ALCHEMY_CONN\" | cut -d '/' -f3 | sed -e 's,.*@,,')\n    POSTGRES_HOST=$(echo -n \"$POSTGRES_ENDPOINT\" | cut -d ':' -f1)\n    POSTGRES_PORT=$(echo -n \"$POSTGRES_ENDPOINT\" | cut -d ':' -f2)\n  fi\n\n  wait_for_port \"Postgres\" \"$POSTGRES_HOST\" \"$POSTGRES_PORT\"\nfi\n\n\ncase \"$1\" in\n  local-runner)\n    # if S3_PLUGINS_PATH\n    if [ -n \"$S3_PLUGINS_PATH\" ]; then\n      echo \"Downloading $S3_PLUGINS_PATH\"\n      mkdir -p $AIRFLOW_HOME/plugins\n      cd $AIRFLOW_HOME/plugins\n      aws s3 cp $S3_PLUGINS_PATH plugins.zip\n      unzip -o plugins.zip \n      rm plugins.zip\n    fi\n    # if S3_DAGS_PATH\n    if [ -n \"$S3_DAGS_PATH\" ]; then\n      echo \"Syncing $S3_DAGS_PATH\"   \n      mkdir -p $AIRFLOW_HOME/dags\n      cd $AIRFLOW_HOME/dags\n      aws s3 sync --exact-timestamp --delete $S3_DAGS_PATH .\n    fi    \n    # if S3_REQUIREMENTS_PATH\n    if [ -n \"$S3_REQUIREMENTS_PATH\" ]; then\n      echo \"Downloading $S3_REQUIREMENTS_PATH\"\n      mkdir -p $AIRFLOW_HOME/requirements\n      aws s3 cp $S3_REQUIREMENTS_PATH $AIRFLOW_HOME/$REQUIREMENTS_FILE\n    fi\n\n    execute_startup_script\n    source stored_env\n    export AIRFLOW_HOME=\"/usr/local/airflow\"\n    export AIRFLOW__CORE__LOAD_EXAMPLES=\"False\"\n\n    install_requirements\n    airflow db init\n    if [ \"$AIRFLOW__CORE__EXECUTOR\" = \"LocalExecutor\" ] || [ \"$AIRFLOW__CORE__EXECUTOR\" = \"SequentialExecutor\" ]; then\n      # With the \"Local\" and \"Sequential\" executors it should all run in one container.\n      airflow scheduler &\n      sleep 2\n    fi\n    airflow users create -r Admin -u admin -e admin@example.com -f admin -l user -p $DEFAULT_PASSWORD\n    exec airflow webserver\n    ;;\n  resetdb)\n    airflow db reset -y\n    sleep 2\n    airflow db init\n    ;;\n  test-requirements)\n    # if S3_REQUIREMENTS_PATH\n    if [ -n \"$S3_REQUIREMENTS_PATH\" ]; then\n      echo \"Downloading $S3_REQUIREMENTS_PATH\"\n      mkdir -p $AIRFLOW_HOME/requirements\n      aws s3 cp $S3_REQUIREMENTS_PATH $AIRFLOW_HOME/$REQUIREMENTS_FILE\n    fi      \n    install_requirements\n    ;;\n  package-requirements)\n    # if S3_REQUIREMENTS_PATH\n    if [ -n \"$S3_REQUIREMENTS_PATH\" ]; then\n      echo \"Downloading $S3_REQUIREMENTS_PATH\"\n      mkdir -p $AIRFLOW_HOME/requirements\n      aws s3 cp $S3_REQUIREMENTS_PATH $AIRFLOW_HOME/$REQUIREMENTS_FILE\n    fi      \n    package_requirements\n    ;;\n  test-startup-script)\n    execute_startup_script\n    ;;\n  *)\n    # The command is something like bash, not an airflow subcommand. Just run it in the right environment.\n    exec \"$@\"\n    ;;\nesac\n", "num_lines": 174}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Generate fernet key\nFERNET_KEY=\"$(python -c \"from cryptography.fernet import Fernet; FERNET_KEY = Fernet.generate_key().decode(); print(FERNET_KEY)\")\"\n\n# Store it in the image so that it can be used in entrypoint\necho \"$FERNET_KEY\" > /usr/local/etc/airflow_fernet_key\n", "num_lines": 8}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource \"$AIRFLOW_HOME/startup/startup.sh\"\ndeclare -p | grep -v '^declare \\-[aAilnrtux]*r ' > stored_env", "num_lines": 4}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ntimeout_seconds=300\nexec 3>&1 4>&2\ntime=$(TIMEFORMAT=\"%R\"; { time timeout \"${timeout_seconds}s\" bash /run-startup.sh 1>&3 2>&4; } 2>&1)\nexit_status=$?\nexec 3>&- 4>&-\nif [ $exit_status -eq 124 ]; then\n echo \"Startup script timed out after $timeout_seconds seconds.\"\nelse\n echo \"Finished running startup script. Execution time: ${time}s.\"\n source stored_env\nfi\necho \"Running verification\"\nbash /verification.sh\necho \"Verification completed\"", "num_lines": 16}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nyum update -y\n\n# install basic python environment\nyum install -y python37 gcc gcc-g++ python3-devel\n\n# JDBC and PyODBC dependencies\nyum install -y java-1.8.0-openjdk unixODBC-devel \n\n# Database clients\nyum install -y postgresql-devel\n\n# Archiving Libraries\nyum install -y zip unzip bzip2 gzip\n\n# Airflow extras\nyum install -y gcc-c++ cyrus-sasl-devel libcurl-devel openssl-devel shadow-utils\n\n#### Required Libraries for entrypoint.sh script\n\n# jq is used to parse ECS-injected AWSSecretsManager secrets\nyum install -y jq\n\n# nc is used to check DB connectivity\nyum install -y nc\n\n# Needed for generating fernet key for local runner\nyum install -y python2-cryptography\n\n# Install additional system library dependencies. Provided as a string of libraries separated by space\nif [ -n \"${SYSTEM_DEPS}\" ]; then yum install -y \"${SYSTEM_DEPS}\"; fi\n\nyum clean all", "num_lines": 35}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nEXPECTED_AIRFLOW_VERSION=\"2.5.1\"\nEXPECTED_WATCHTOWER_VERSION=\"2.0.1\"\n\nvalidate_version_with_pip() {\n  if [[ $(pip3 show \"$1\" | grep 'Version' | grep -o '[0-9].*') != \"$2\" ]]\n  then\n    echo \"Validation Error: $1 version $2 expected\"\n  fi\n}\n\nif ! python3 -c 'import sys; assert sys.version_info[:2] == (3,10)' > /dev/null;\nthen\n  echo \"Validation Error: Python version 3.10 expected\"\nfi\n\nvalidate_version_with_pip \"apache-airflow\" \"$EXPECTED_AIRFLOW_VERSION\"\n\nvalidate_version_with_pip \"watchtower\" \"$EXPECTED_WATCHTOWER_VERSION\"", "num_lines": 20}
{"repo_name": "aws-mwaa-local-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Running sample startup script.\"", "num_lines": 3}
{"repo_name": "aws-nitro-enclaves-acm", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -xe\n#\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Entry point script for the CI running on an EC2 instance.\n# It is responsible for:\n#    1. Publishing status updates to github.\n#    2. Running the tests.\n#    3. Publishing the test logs in an S3 bucket.\n\n# Set pipe fail option to capture return code after using pipe commands (e.g. tee)\nset -o pipefail\nSCRIPTDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\ncd \"${SCRIPTDIR}\"\n\n# S3 bucket where additional test dependencies reside\nACM_FOR_NE_REPO_S3=\"aws-ne-acm-deps\"\n\n# KMS Key Id associated with the account where the CodePipeline resides\nKMS_KEY_ID=\"0522fe28-9053-44bf-b7a5-5b74cf050ba1\"\n\n# Update Github status, see:\n#   https://developer.github.com/v3/repos/statuses/\nfunction status_update() {\n        curl -H \"Authorization: token ${ACCESS_TOKEN}\" \\\n                -X POST -d '{\"state\":\"'\"${STATE}\"'\",\"target_url\": \"'\"${LOGS_URL}\"'\",\"description\": \"Test runner updated\",\"context\": \"test_runner/ec2-instance\"}'\\\n                https://api.github.com/repos/aws/aws-nitro-enclaves-acm/statuses/${CODEBUILD_RESOLVED_SOURCE_VERSION}\n}\n\n# Perform the %post scriptlet steps of the RPM\nfunction install_ne_acm_files() {\n\tinstall -D -m0644 artifacts/p11ne.eif /usr/share/nitro_enclaves/p11ne/p11ne.eif\n\tinstall -D -m0644 artifacts/image-measurements.json /usr/share/nitro_enclaves/p11ne/image-measurements.json\n\tinstall -D -m0644 src/vtok_agent/service/acm.example.yaml /usr/share/nitro_enclaves/p11ne/acm.example.yaml\n\n\tinstall -D -m0755 build/target/release/p11ne-client /usr/bin/p11ne-client\n\tinstall -D -m0755 build/target/release/p11ne-agent /usr/bin/p11ne-agent\n\tinstall -D -m0644 src/vtok_agent/service/nitro-enclaves-acm.service /usr/lib/systemd/system/nitro-enclaves-acm.service\n\n\tinstall -D -m0644 src/vtok_agent/service/acm.example.yaml /etc/nitro_enclaves/acm.example.yaml\n\n\tinstall -D -m0644 THIRD-PARTY-LICENSES /usr/share/licenses/aws-nitro-enclaves-acm-1.0/THIRD-PARTY-LICENSES.txt\n\n\tsystemctl --system daemon-reload\n}\n\n# Cleanup what the corresponding `install` phase brought in\nfunction uninstall_ne_acm_files() {\n\trm -f /usr/share/nitro_enclaves/p11ne/p11ne.eif\n\trm -f /usr/share/nitro_enclaves/p11ne/image-measurements.json\n\trm -f /usr/share/nitro_enclaves/p11ne/acm.example.yaml\n\n\trm -f /usr/bin/p11ne-client\n\trm -f /usr/bin/p11ne-agent\n\trm -f /usr/lib/systemd/system/nitro-enclaves-acm.service\n\n\trm -f /etc/nitro_enclaves/acm.example.yaml\n\n\trm -f /usr/share/licenses/aws-nitro-enclaves-acm-1.0/THIRD-PARTY-LICENSES.txt\n}\n\npwd\nsource build_env.txt\n\nPR_NUMBER=$(echo \"$CODEBUILD_SOURCE_VERSION\" | cut -d\"/\" -f2)\nLOGS_PATH=\"tests_results/${PR_NUMBER}/ci_logs_${CODEBUILD_RESOLVED_SOURCE_VERSION}.txt\"\nLOGS_URL=\"https://console.aws.amazon.com/s3/object/aws-ne-acm-ci/${LOGS_PATH}\"\nACCESS_TOKEN=$(aws ssm get-parameter --name GITHUB_TOKEN --region us-east-1 | jq -r .Parameter.Value)\nif [[ $ACCESS_TOKEN == \"\" ]];\nthen\n        echo \"Invalid ACCESS_TOKEN\"\n        exit 1\nfi\n\nSTATE=\"pending\"\nstatus_update\n\ninstall_ne_acm_files\n\nset +e\n./run-nitro-enclaves-acm-tests \"$ACM_FOR_NE_REPO_S3\" \"$KMS_KEY_ID\" 2>&1 | tee test_logs.out\nTEST_RESULTS=$?\nset -e\n\nuninstall_ne_acm_files\n\naws s3 cp test_logs.out s3://aws-ne-acm-ci/${LOGS_PATH}\n\nSTATE=\"success\"\nif [[ \"${TEST_RESULTS}\" != \"0\" ]];then\n        STATE=\"failure\"\nfi\n\nstatus_update\n", "num_lines": 96}
{"repo_name": "aws-nitro-enclaves-acm", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nUSAGE=\"\n    p11ne installer for Amazon Linux 2 - install and set up p11ne and its dependencies\n\n    Usage: $0 --target <devctr|release>\n\n    This scripts expects:\n    - an Amazon Linux 2 environment, preferably a clean base AMI;\n    - <script dir>/install [optional]           A rootfs structure, holding any pre-built\n                                                binaries that should be installed.\n\n    Options:\n        --target <devctr|release>               The build target:\n                                                - devctr: set up the dev container;\n                                                - release: set up the release parent AMI;\n\"\n\nNITRO_ENCLAVES_GROUP=ne\nTHIS_DIR=\"$(cd \"$(dirname \"$0\")\" && pwd)\"\nOPT_TARGET=\n\nBUILD_DEPS=(\n    autoconf\n    automake\n    cmake\n    gcc\n    gettext-devel\n    git\n    libffi-devel\n    libtool\n    make\n    openssl-devel\n)\n\nsay_err() {\n    echo \"$*\" 1>&2\n}\n\ndie() {\n    [[ $# -gt 0 ]] && say_err \"$*\"\n    exit 1\n}\n\nok_or_die() {\n    [ $? -eq 0 ] || die \"$*\"\n}\n\np11ne_is_release_setup() {\n    [[ $OPT_TARGET = release ]]\n}\n\np11ne_setup_parent() {\n    # Install build deps that are currently missing. We will be removing these before\n    # the end, so we need to avoid removing any packages that we need, but were already\n    # installed.\n    MY_BUILD_DEPS=($(for dep in \"${BUILD_DEPS[@]}\"; do rpm -q $dep > /dev/null || echo $dep; done))\n    yum install -y \"${MY_BUILD_DEPS[@]}\" \\\n        && yum install -y gnutls-utils jq tar p11-kit\n    ok_or_die\n\n    amazon-linux-extras install -y docker aws-nitro-enclaves-cli nginx1 \\\n        && yum install -y aws-nitro-enclaves-cli-devel\n    ok_or_die\n\n    cd \"$THIS_DIR\"\n\n    if [[ -d install ]]; then\n        pushd install \\\n            && tar -c . | tar -xC / \\\n            && popd\n        ok_or_die \"Pre-built rootfs install failed.\"\n    fi\n\n    if p11ne_is_release_setup; then\n        systemctl enable docker\n        systemctl enable nitro-enclaves-allocator\n        ok_or_die \"Error setting up startup services\"\n\n        # Make sure ec2-user has access to nitro-cli resources\n        usermod -aG $NITRO_ENCLAVES_GROUP ec2-user \\\n            && usermod -aG docker ec2-user\n        ok_or_die \"Unable to grant Nitro Enclaves access to ec2-user.\"\n    fi\n\n    mkdir -p \"$THIS_DIR/src\" && cd \"$THIS_DIR/src\"\n\n    # TODO: update to a newer, untagged commit, if we need the pin-source feature.\n    # Install libp11 (openssl PKCS#11 engine) from sources\n    git clone https://github.com/OpenSC/libp11.git \\\n        && pushd libp11 \\\n        && git reset --hard libp11-0.4.10 \\\n        && ./bootstrap \\\n        && ./configure --prefix=/usr --with-pkcs11-module=/usr/lib64/p11-kit-proxy.so \\\n        && make -j $(nproc) \\\n        && make install\n    ok_or_die\n    popd\n\n    # Clean up\n    if p11ne_is_release_setup; then\n        # Remove build-time deps\n        yum remove -y \"${MY_BUILD_DEPS[@]}\"\n        yum autoremove -y\n    fi\n}\n\nmain() {\n    while [[ -n \"$1\" ]]; do\n        case \"$1\" in\n            --target)\n                [[ -n \"$2\" ]] || die \"Error: missing target. See --help.\"\n                [[ \"$2\" = devctr ]] || [[ \"$2\" = release ]] || die \"Invalid target: $2\".\n                OPT_TARGET=\"$2\"\n                shift\n                ;;\n            --help|-h|help)\n                die \"$USAGE\"\n                ;;\n        esac\n        shift\n    done\n\n    [[ -n \"$OPT_TARGET\" ]] || die \"Error: missing target. See --help.\"\n\n    p11ne_setup_parent\n}\n\nmain \"$@\"\n", "num_lines": 132}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -xe\n#\n# Copyright 2019-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Entry point script for the CI running on an EC2 instance.\n# It is responsible for:\n#    1. Publishing status updates to github.\n#    2. Running the tests.\n#    3. Publishing the test logs in an S3 bucket.\n\n# Set pipe fail option to capture return code after using pipe commands (e.g. tee)\nset -o pipefail\nSCRIPTDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\ncd \"${SCRIPTDIR}\"\n\n# Update Github status, see:\n#   https://developer.github.com/v3/repos/statuses/\nfunction status_update() {\n\tcurl -H \"Authorization: token ${ACCESS_TOKEN}\" \\\n\t\t-X POST -d '{\"state\":\"'\"${STATE}\"'\",\"target_url\": \"'\"${LOGS_URL}\"'\",\"description\": \"Test runner updated\",\"context\": \"Integration Testing ('\"${ARCH}\"')\"}'\\\n\t\thttps://api.github.com/repos/aws/aws-nitro-enclaves-cli/statuses/${CODEBUILD_RESOLVED_SOURCE_VERSION}\n}\n\n# Before running the CI suite, we prune the Docker environment and reboot. This is done because\n# successive CI runs and derived docker runs progressively increase disk usage, up to the point\n# where a CI run will eventually fail due to no space left.\n# We also clear the system caches in order to guarantee the maximum possible available memory.\ndocker system prune --force\necho 3 > /proc/sys/vm/drop_caches\n\npwd\nsource build_env.txt\n\nARCH=$(uname -m)\nPR_NUMBER=$(echo \"$CODEBUILD_SOURCE_VERSION\" | cut -d\"/\" -f2)\nLOGS_PATH=\"tests_results/${PR_NUMBER}/ci_logs_${CODEBUILD_RESOLVED_SOURCE_VERSION}_${ARCH}.txt\"\nLOGS_URL=\"https://console.aws.amazon.com/s3/object/aws-nitro-enclaves-cli/${LOGS_PATH}\"\nACCESS_TOKEN=$(aws ssm get-parameter --name GITHUB_TOKEN --region us-east-1 | jq -r .Parameter.Value)\nif [[ $ACCESS_TOKEN == \"\" ]];\nthen\n        echo \"Invalid ACCESS_TOKEN\"\n        exit 1\nfi\n\nSTATE=\"pending\"\nstatus_update\n\nset +e\n./run_tests.sh 2>&1 | tee test_logs.out\nTEST_RESULTS=$?\nset -e\n\naws s3 cp --content-type 'text/plain' test_logs.out s3://aws-nitro-enclaves-cli/${LOGS_PATH}\n\nSTATE=\"success\"\nif [[ \"${TEST_RESULTS}\" != \"0\" ]];then\n\tSTATE=\"failure\"\nfi\n\nstatus_update\n", "num_lines": 62}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e -u\n\n#The package names work for Ubuntu, AL2, RedHat 8 and CentOS 7\nPACKAGES=\"docker make gcc\"\nPREREQ_OPTIONS=\"-y\"\n\ninstall_prerequisites() {\n\tif grep -qni \"Amazon Linux\\|CentOS\\|RedHat\" /etc/os-release\n\tthen\n\t\tOPERATION=\"yum install\"\n\telif grep -qni \"Ubuntu\" /etc/os-release\n\tthen\n\t\tOPERATION=\"apt-get install\"\n\telse\n\t\t#Try to continue, just in case the user has done that themselves\n\t\techo \"Warning: prerequisite packages were not installed. Please manually install ${PACKAGES}.\"\n\t\treturn\n\tfi\n\t${OPERATION} ${PREREQ_OPTIONS} ${PACKAGES}\n}\n\nupdate_git() {\n\tif [ -d .git ] || git rev-parse --git-dir > /dev/null 2>&1\n\tthen\n\t\tgit pull\n\t\tgit checkout \"$2\"\n\telse\n\t\techo \"You're trying to install nitro-cli outside of the git repository.\"\n\t\texit\n\tfi\n}\n\ninstall_nitro_cli() {\n\tmake nitro-cli && make vsock-proxy && make install\n\tsource \"${NITRO_CLI_INSTALL_DIR}\"/etc/profile.d/nitro-cli-env.sh\n\techo \"Nitro CLI is now installed. We recommend adding ${NITRO_CLI_INSTALL_DIR}/etc/profile.d/nitro-cli-env.sh in your .bashrc file\"\n}\n\nshow_usage() {\n\techo \"Usage: $0 [--update <commit>] [--ask-for-confirmation] [--help]\"\n}\n\n#Parse parameters\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n\t-u|--update)\n\tupdate_git \"$2\" || show_usage\n\tshift 2\n\t;;\n\t-c|--ask-for-confirmation)\n\tPREREQ_OPTIONS=\"\"\n\tshift\n\t;;\n\t-h|--help)\n\tshow_usage\n\texit\nesac\ndone\n\ninstall_prerequisites\ninstall_nitro_cli\n", "num_lines": 67}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -x\n#\n# Copyright 2020-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script used for running all the tests we have on a EC2 instance that has\n# --enclave-options set to true\n#\nTEST_SUITES_FAILED=0\nTEST_SUITES_TOTAL=0\n\nSCRIPTDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nexport NITRO_CLI_BLOBS=\"${SCRIPTDIR}/blobs\"\nexport NITRO_CLI_ARTIFACTS=\"${SCRIPTDIR}/build\"\nARCH=\"$(uname -m)\"\n\nAWS_ACCOUNT_ID=667861386598\n\n# Indicate that the test suite has failed\nfunction register_test_fail() {\n\tTEST_SUITES_FAILED=$((TEST_SUITES_FAILED + 1))\n}\n\n# Clean up and exit with the current test suite's status\nfunction clean_up_and_exit() {\n\t[ \"$(lsmod | grep -cw nitro_enclaves)\" -eq 0 ] || rmmod nitro_enclaves || register_test_fail\n\tmake clean\n\trm -rf test_images\n\n\t# Cleanup pulled images during testing\n\tdocker rmi public.ecr.aws/aws-nitro-enclaves/hello:v1 2> /dev/null || true\n\tdocker rmi hello-world:latest 2> /dev/null || true\n\n\trm -rf examples/\"${ARCH}\"/hello-entrypoint\n\tdocker rmi hello-entrypoint-usage:latest 2> /dev/null || true\n\n\texit $TEST_SUITES_FAILED\n}\n\n# Force the test suite to end in failure\nfunction test_failed() {\n\tregister_test_fail\n\tclean_up_and_exit\n}\n\n# Remove the Nitro Enclaves driver\nfunction remove_ne_driver() {\n\t[ \"$(lsmod | grep -cw nitro_enclaves)\" -eq 0 ] || rmmod nitro_enclaves || test_failed\n}\n\n# Configure and insert the Nitro Enclaves driver\nfunction configure_ne_driver() {\n\tif [ \"$(lsmod | grep -cw nitro_enclaves)\" -eq 0 ]\n\tthen\n\t\t# Preallocate 2046 Mb, that should be enough for all the tests. We explicitly\n\t\t# pick this value to have both 1 GB and 2 MB pages if the system allows it.\n\t\tsource build/install/etc/profile.d/nitro-cli-env.sh || test_failed\n\t\t./build/install/etc/profile.d/nitro-cli-config -m 2046 -t 2 || test_failed\n\tfi\n}\n\n# First run the instalation test, before we change the environement\npytest-3 tests/integration/test_installation.py || test_failed\n\n# Clean up build artefacts\nmake clean\n\n# Setup the environement with everything needed to run the integration tests\nmake command-executer || test_failed\nmake nitro-tests || test_failed\nmake nitro_enclaves || test_failed\nmake nitro-cli || test_failed\nmake vsock-proxy || test_failed\nmake install || test_failed\n\n# Ensure the Nitro Enclaves driver is inserted at the beginning.\nconfigure_ne_driver\n\n# Create directories for enclave process sockets and logs\nmkdir -p /run/nitro_enclaves || test_failed\nmkdir -p /var/log/nitro_enclaves || test_failed\n\n# Build EIFS for testing\nmkdir -p test_images || test_failed\nexport HOME=\"/root\"\n\n# Simple EIF\nnitro-cli build-enclave --docker-uri public.ecr.aws/aws-nitro-enclaves/hello:v1 \\\n\t--output-file test_images/hello.eif || test_failed\n\n# Generate signing certificate\nopenssl ecparam -name secp384r1 -genkey -out test_images/key.pem || test_failed\nopenssl req -new -key test_images/key.pem -sha384 -nodes \\\n\t-subj \"/CN=AWS/C=US/ST=WA/L=Seattle/O=Amazon/OU=AWS\" -out test_images/csr.pem || test_failed\nopenssl x509 -req -days 20  -in test_images/csr.pem -out test_images/cert.pem \\\n\t-sha384 -signkey test_images/key.pem || test_failed\n# Signed EIF\nnitro-cli build-enclave --docker-uri public.ecr.aws/aws-nitro-enclaves/hello:v1 \\\n\t--output-file test_images/hello-signed.eif \\\n\t--private-key test_images/key.pem --signing-certificate test_images/cert.pem || test_failed\n\n\n# Build enclave image using Docker ENTRYPOINT instruction\nmkdir -p examples/\"${ARCH}\"/hello-entrypoint || test_failed\ncp -r examples/\"${ARCH}\"/hello/* examples/\"${ARCH}\"/hello-entrypoint || test_failed\n\nsed -i 's/CMD/ENTRYPOINT/g' examples/\"${ARCH}\"/hello-entrypoint/Dockerfile || test_failed\n\nnitro-cli build-enclave --docker-dir examples/\"${ARCH}\"/hello-entrypoint --docker-uri hello-entrypoint-usage \\\n\t--output-file test_images/hello-entrypoint-usage.eif || test_failed\n\n# Run all unit tests\nwhile IFS= read -r test_line\ndo\n\tTEST_SUITES_TOTAL=$((TEST_SUITES_TOTAL + 1))\n\ttest_module=\"$(echo ${test_line} | cut -d' ' -f2)\"\n\ttest_exec_name=\"$(basename $(echo ${test_line} | cut -d' ' -f1))\"\n\n\tconfigure_ne_driver\n\n\ttimeout 5m \\\n\t./build/nitro_cli/\"${ARCH}\"-unknown-linux-musl/release/deps/\"${test_exec_name}\" \\\n\t\t--test-threads=1 --nocapture || test_failed\ndone < <(grep -v '^ *#' < build/test_executables.txt)\n\n# Ensure the Nitro Enclaves driver is inserted for the remaining integration tests.\nconfigure_ne_driver\n\n# Run integration tests except the instalation test\npytest-3 tests/integration/ --ignore tests/integration/test_installation.py || test_failed\n\nclean_up_and_exit\n", "num_lines": 133}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nif [ -z ${NITRO_CLI_INSTALL_DIR} ];\nthen\n    echo \"INSTALLDIR variable not set, please set the variable to the location where nitro-cli is installed\"\n    return -1\nfi\n\nlsmod | grep -q nitro_enclaves || \\\n    sudo insmod ${NITRO_CLI_INSTALL_DIR}/lib/modules/extra/nitro_enclaves/nitro_enclaves.ko\n\nexport PATH=${PATH}:${NITRO_CLI_INSTALL_DIR}/usr/bin/:${NITRO_CLI_INSTALL_DIR}/etc/profile.d/\nexport NITRO_CLI_BLOBS=${NITRO_CLI_INSTALL_DIR}/usr/share/nitro_enclaves/blobs\n", "num_lines": 17}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\ncount=1\nwhile true; do\n    printf \"[%4d] $HELLO\\n\" $count\n    count=$((count+1))\n    sleep 5\ndone\n", "num_lines": 11}
{"repo_name": "aws-nitro-enclaves-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\ncount=1\nwhile true; do\n    printf \"[%4d] $HELLO\\n\" $count\n    count=$((count+1))\n    sleep 5\ndone\n", "num_lines": 11}
{"repo_name": "aws-nitro-enclaves-k8s-device-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nsource \"$(dirname $(realpath $0))/common.sh\"\n\ndocker build --target builder -t $BUILDER_IMAGE $TOP_DIR -f $TOP_DIR/container/Dockerfile\ndocker build --target device_plugin -t $IMAGE $TOP_DIR -f $TOP_DIR/container/Dockerfile\n", "num_lines": 9}
{"repo_name": "aws-nitro-enclaves-k8s-device-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nreadonly SUCCESS=0\nreadonly FAILURE=255\n\nreadonly SCRIPTS_DIR=$(dirname $(realpath $0))\nreadonly TOP_DIR=$(cd $SCRIPTS_DIR/.. && pwd)\nreadonly ECR_CONFIG_FILE_PATH=\"$SCRIPTS_DIR/.ecr.uri\"\nreadonly RELEASE_FILE=\"RELEASE\"\n\nreadonly BUILDER_IMAGE=ne-k8s-device-plugin-build:latest\nreadonly REPOSITORY_NAME=aws-nitro-enclaves-k8s-device-plugin\nreadonly RELEASE=$(cat $TOP_DIR/$RELEASE_FILE)\nreadonly TAG=$RELEASE-$(arch)\nreadonly IMAGE=$REPOSITORY_NAME:$TAG\n\nsay() {\n  echo \"$@\"\n}\n\ndie() {\n  say \"[ERROR] $@\"\n  exit $FAILURE\n}\n\n[[ -f $TOP_DIR/$RELEASE_FILE ]] || \\\n  die \"Cannot find $RELEASE_FILE file in $TOP_DIR directory.\"\n\n_set_config_item() {\n  local var=$1; shift\n  local prompt=\"$@\"\n\n  local value=\"\"\n  while [[ $value = \"\" ]];\n  do\n      printf \"$prompt\"\n      read value\n  done\n\n  echo \"$var=$value\" >> \"$ECR_CONFIG_FILE_PATH\"\n}\n\n_load_ecr_config() {\n  [[ -f $ECR_CONFIG_FILE_PATH ]] || {\n      printf \"No configuration found!\\n\"\n      _set_config_item ECR_URL \"Please enter an ECR URL:\"\n      _set_config_item ECR_REGION \"Please enter AWS region of the ECR repository:\"\n  }\n\n  source \"$ECR_CONFIG_FILE_PATH\"\n  [[ -z \"$ECR_URL\" || -z \"$ECR_REGION\" ]] && {\n      say \"$(basename $ECR_CONFIG_FILE_PATH) seems corrupted. Try using\" \\\n      \"'rm -f $ECR_CONFIG_FILE_PATH' to remove this configuration.\"\n      exit 1\n  }\n\n  return 0\n}\n\n_ecr_login() {\n  is_a_public_ecr_registry\n\n  if [[ $? -eq $SUCCESS ]]; then\n      aws ecr-public get-login-password --region \"$ECR_REGION\" | docker login --username AWS --password-stdin $ECR_URL\n  else\n      aws ecr get-login-password --region \"$ECR_REGION\" | docker login --username AWS --password-stdin $ECR_URL\n  fi\n}\n\n# Loads configuration and logs in to a registry.\n#\necr_login() {\n    _load_ecr_config || die \"Error while loading configuration file!\"\n    say \"Using ECR registry url: $ECR_URL. (region: $ECR_REGION).\"\n    _ecr_login || die \"Failed to log in to the ECR registry.\"\n}\n\n# Check if the current ECR URL is a public one or not.\n# \nis_a_public_ecr_registry() {\n  [[ \"$ECR_URL\" =~ ^public.ecr.aws* ]] && { return $SUCCESS; }\n  return $FAILURE\n}\n\n# Generic user confirmation function\n# \nconfirm() {\n  read -p \"$@ (yes/no)\" yn\n  case yn in\n    yes) ;;\n    *)\n      say \"Aborting...\"\n      exit $FAILURE\n      ;;\n  esac\n}\n", "num_lines": 99}
{"repo_name": "aws-nitro-enclaves-k8s-device-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nsource \"$(dirname $(realpath $0))/common.sh\"\n\nmain() {\n  ecr_login\n\n  docker manifest create --amend $ECR_URL/$REPOSITORY_NAME \\\n    $ECR_URL/$REPOSITORY_NAME:$RELEASE-x86_64 \\\n    $ECR_URL/$REPOSITORY_NAME:$RELEASE-aarch64 || \\\n    die \"Cannot create manifest for multiarch image.\" \\\n      \" Please ensure that both x86_64 and aarch64 images\" \\\n      \" already exist in the repository.\"\n\n  docker manifest inspect $ECR_URL/$IMAGE\n  \n  is_a_public_ecr_registry && {\n    confirm \"You are about to make changes on a\" \\\n      \" publicly available manifest. Are you sure want to continue? (yes/no)\"\n  }\n\n  docker manifest push $ECR_URL/$REPOSITORY_NAME:latest\n}\n\nmain\n", "num_lines": 28}
{"repo_name": "aws-nitro-enclaves-k8s-device-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nsource \"$(dirname $(realpath $0))/common.sh\"\n\nmain() {\n  ecr_login\n\n  aws ecr --region $ECR_REGION describe-repositories \\\n    --repository-names \"$REPOSITORY_NAME\" > /dev/null || \\\n    die \"There is no repository named $REPOSITORY_NAME in\" \\\n    \"$ECR_REGION region.\"\n\n  is_a_public_ecr_registry && {\n    confirm \"You are about to make changes on a public repository.\" \\\n            \" Are you sure want to continue?\"\n  }\n\n  docker tag $IMAGE $ECR_URL/$IMAGE\n  say \"Pushing $IMAGE to $ECR_URL...\"\n  docker push $ECR_URL/$IMAGE\n}\n\nmain\n", "num_lines": 26}
{"repo_name": "aws-nitro-enclaves-nsm-api", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nNUM_TESTS=2\ntests_passed=0\n\nset -u\nif [ $# -eq 1 ]; then\n\tif [ \"$1\" = \"CLI_CHECK\" ]; then\n\t\tdocker system prune --all --force\n\tfi\nfi\n\nmake run-nsm-test-cpp\ndocker run -a stdout -a stderr -t nsm-test-cpp '/command-executer run --cid 16 --port 5005 --command \"/nsm-test\"'\n\nRESULT=$?\nif [ $RESULT -eq 0 ]; then\n\techo \"The test-cpp test has PASSED\"\n\ttests_passed=$((tests_passed+1))\nelse\n\techo \"The test-cpp test has FAILED\"\nfi\n\nnitro-cli terminate-enclave --all\n\nmake run-nsm-check-eif\ndocker run -a stdout -a stderr nsm-check '/command-executer run --cid 16 --port 5005 --command \"/nsm-check\"'\n\nRESULT=$?\nif [ $RESULT -eq 0 ]; then\n\techo \"The nsm-check test has PASSED\"\n\ttests_passed=$((tests_passed+1))\nelse\n\techo \"The nsm-check test has FAILED\"\nfi\n\nnitro-cli terminate-enclave --all\n\necho \"$tests_passed/$NUM_TESTS tests passed\"\n", "num_lines": 40}
{"repo_name": "aws-nitro-enclaves-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ndocker build --target kmstool-enclave-cli -t kmstool-enclave-cli -f ../../containers/Dockerfile.al2 ../..\nCONTAINER_ID=$(docker create kmstool-enclave-cli)\ndocker cp $CONTAINER_ID:/kmstool_enclave_cli ./\ndocker cp $CONTAINER_ID:/usr/lib64/libnsm.so ./\ndocker rm $CONTAINER_ID\n", "num_lines": 10}
{"repo_name": "aws-nitro-enclaves-sdk-c", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script builds the current repo and runs a quick smoke test against KMS.\n# Prerequisites:\n# * aws-nitro-enclaves-cli and aws-nitro-enclaves-cli-devel packages installed\n# * a KMS Key configured for debug mode (all zeroes)\n# * docker\n# * vsock-proxy running\n# * nitro-enclaves-allocator with at least 1G RAM and 2 CPUs\n#\n# Usage:\n# KMS_KEY_ARN=arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab ./tests/integration/test_kms.sh\n\nset -eu\n\ncleanup() {\n    docker rmi kmstool-instance:$RAND_TAG &>/dev/null ||:\n    docker rmi kmstool-enclave:$RAND_TAG &>/dev/null ||:\n\n    rm -rf \"$TEMP_DIR\" &>/dev/null ||:\n\n    if [[ ! -z \"${ENCLAVE_ID+x}\" ]]; then\n        nitro-cli terminate-enclave --enclave-id \"$ENCLAVE_ID\" &>/dev/null ||:\n    fi\n}\n\nfail() {\n    echo \"$(tput bold)$(tput setaf 1) $1 $(tput sgr0)\"\n    echo \"TEST: FAILED\"\n    exit 1\n}\n\nnitro-cli --version || fail \"aws-nitro-enclaves-cli not installed\"\ntest -c /dev/nitro_enclaves || fail \"not running on an instance with Nitro Enclaves enabled\"\ntest ! -z \"${KMS_KEY_ARN+x}\" || fail \"KMS_KEY_ARN not set\"\n\nreadonly RAND_TAG=$(dd if=/dev/urandom bs=12 count=1 2>/dev/null | base64 | tr -cd \"[[:alnum:]]\")\nreadonly RAND_MSG=$(dd if=/dev/urandom bs=16 count=1 2>/dev/null | base64)\nreadonly TEMP_DIR=$(mktemp -d)\nreadonly KMS_KEY_REGION=${KMS_KEY_REGION:-us-east-1}\n\ntrap cleanup EXIT\n\ndocker build -f containers/Dockerfile.al2 --target kmstool-instance -t \"kmstool-instance:$RAND_TAG\" . || fail \"Unable to build kmstool-instance\"\ndocker build -f containers/Dockerfile.al2 --target kmstool-enclave -t \"kmstool-enclave:$RAND_TAG\" .  || fail \"Unable to build kmstool-enclave\"\n\nnitro-cli build-enclave --docker-uri kmstool-enclave:$RAND_TAG --output-file $TEMP_DIR/test.eif | jq . || fail \"Unable to build EIF\"\n\nENCLAVE_ID=$(nitro-cli run-enclave --eif-path $TEMP_DIR/test.eif --memory 1024 --cpu-count 2 --enclave-cid 7777 --debug-mode  | jq -r .EnclaveID) || fail \"Unable to start enclave\"\n\nMESSAGE=\"Test message: $RAND_MSG\"\nBASE64_MESSAGE=$(echo \"$MESSAGE\" | base64)\n\nENCRYPTED=$(aws kms encrypt --key-id \"$KMS_KEY_ARN\" --plaintext \"$BASE64_MESSAGE\" --query CiphertextBlob --output text)\ndocker run --network host -t kmstool-instance:$RAND_TAG bash -c \"/kmstool_instance --cid 7777 '$ENCRYPTED' 2>/dev/null | grep -q '$MESSAGE'\" || fail \"Message could not be decrypted\"\n\n\necho \"TEST: SUCCESS\"\n", "num_lines": 62}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nexport PATH=$PATH:$(dirname $(realpath $BASH_SOURCE))\n\n", "num_lines": 7}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nreadonly SUCCESS=0\nreadonly FAILURE=255\n\nreadonly BUILDER_INSTANCE_OUTPUT_PATH=/output\nreadonly BUILDER_INSTANCE_SOURCE_PATH=/source\nreadonly BUILDER_INSTANCE_ENCLAVE_MANIFEST=\"$BUILDER_INSTANCE_SOURCE_PATH/enclave_manifest.json\"\n\ndie() {\n  local code=1\n  [[ \"$1\" = \"-c\" ]] && {\n    code=\"$2\"\n    shift 2\n  }\n  say_err \"$@\"\n  exit $code\n}\n\nsay_err() {\n  [ -t 2 ] && [ -n \"$TERM\" ] \\\n    && echo \"$(tput setaf 1)[BUILDER] $*$(tput sgr0)\" 1>&2 \\\n    || echo \"[BUILDER] $*\" 1>&2\n}\n\nsay() {\n  [ -t 1 ] && [ -n \"$TERM\" ] \\\n    && echo \"$(tput setaf 2)[BUILDER]$(tput sgr0) $*\" \\\n    || echo \"[BUILDER] $*\"\n}\n\nbuild_eif() {\n  local image_name=$1\n  local tag=$2\n  local eif_name=$3\n\n  nitro-cli build-enclave --docker-uri $image_name:$tag --output-file /output/$eif_name\n}\n\nclone_repository() {\n  local repo_addr=$1\n  local directory=$2\n  local tag=$3\n\n  git clone --depth 1 $repo_addr -b $tag $directory\n}\n\nparse_required_items() {\n  local arch=$(uname -m)\n  local ctr=0\n\n  readonly items=(\n    .name\n    .repository\n    .tag\n    .eif.name\n    .eif.docker.image_name\n    .eif.docker.image_tag\n    .eif.docker.target\n    .eif.docker.$arch.file_name\n    .eif.docker.$arch.file_path\n    .eif.docker.$arch.build_path\n  )\n\n  jq -r --arg arch \"$arch\" \\\n    '.name, .repository, .tag,\n    .eif.name,\n    .eif.docker.image_name,\n    .eif.docker.image_tag,\n    .eif.docker.target,\n    .eif.docker.\"'\"$arch\"'\".file_name,\n    .eif.docker.\"'\"$arch\"'\".file_path,\n    .eif.docker.\"'\"$arch\"'\".build_path' \\\n    $BUILDER_INSTANCE_ENCLAVE_MANIFEST | \\\n    while IFS= read -r value ; \\\n      do\n        local item=${items[$ctr]:1}\n        [[ \"null\" = \"$value\" ]] && {\n          say_err \"Manifest file must include item: $item!\"\n          return $FAILURE\n        }\n        item=$(echo ${item/\".$arch\"/\"\"})\n        item=$(echo ${item/\".\"/\"_\"})\n        item=$(echo ${item/\".\"/\"_\"})\n        echo \"export MANIFEST_${item^^}=\\\"$value\\\"\" >> .config\n        let \"ctr=ctr+1\"\n      done\n}\n\nparse_instance_items() {\n  local arch=$(uname -m)\n  local ctr=0\n\n  readonly items=(\n    .instance.docker.image_name\n    .instance.docker.image_tag\n    .instance.docker.target\n    .instance.docker.$arch.file_name\n    .instance.docker.$arch.file_path\n    .instance.docker.$arch.build_path\n  )\n\n  jq -r --arg arch \"$arch\" \\\n   '.instance.docker.image_name,\n    .instance.docker.image_tag,\n    .instance.docker.target,\n    .instance.docker.\"'\"$arch\"'\".file_name,\n    .instance.docker.\"'\"$arch\"'\".file_path,\n    .instance.docker.\"'\"$arch\"'\".build_path' \\\n    $BUILDER_INSTANCE_ENCLAVE_MANIFEST | \\\n    while IFS= read -r value ; \\\n      do\n        local item=${items[$ctr]:1}\n        [[ \"null\" = \"$value\" ]] && {\n          say_err \"Missing instance application definition: $item!\"\n          return $FAILURE\n        }\n        item=$(echo ${item/\".$arch\"/\"\"})\n        item=$(echo ${item/\".\"/\"_\"})\n        item=$(echo ${item/\".\"/\"_\"})\n        echo \"export MANIFEST_${item^^}=\\\"$value\\\"\" >> .config\n        let \"ctr=ctr+1\"\n      done\n}\n\nparse_manifest_file() {\n  truncate -s 0 .config\n  parse_required_items || die \"Cannot parse manifest file!\"\n  local out=$(jq -r '.instance' $BUILDER_INSTANCE_ENCLAVE_MANIFEST)\n  [[ \"$out\" != \"null\" ]] && {\n    # Instance application-related fields are optional. However, once an instance\n    # JSON object is defined, it must include all items required for build.\n    parse_instance_items || \"Cannot parse manifest file!\"\n  }\n  return $SUCCESS\n}\n\nfunction all_exported_files_exist() {\n  # Get exported files list.\n  local exported_files=($(jq -r '[.instance.exports[]]|join(\" \")' \\\n    $BUILDER_INSTANCE_ENCLAVE_MANIFEST 2> /dev/null))\n\n  for exp_file in ${exported_files[@]}\n  do\n    [[ -f \"$BUILDER_INSTANCE_OUTPUT_PATH/$(basename $exp_file)\" ]] || return $FAILURE;\n  done\n\n  return $SUCCESS\n}\n\nmain() {\n  [[ -f $BUILDER_INSTANCE_ENCLAVE_MANIFEST ]] || {\n    die \"No enclave manifest file found!\" \\\n    \"Please make sure enclave_manifest.json\" \\\n    \"exists in the project directory.\"\n  }\n\n  parse_manifest_file || {\n    die \"Invalid enclave manifest file! Aborting...\"\n  }\n\n  source .config\n  say \"---- Using config: ----\"\n  cat .config\n  say \"-----------------------\"\n\n  all_exported_files_exist; local exp_files_exist=$?\n\n  [[ $exp_files_exist -eq 0 && -f \"$BUILDER_INSTANCE_OUTPUT_PATH/$MANIFEST_EIF_NAME\" ]] && {\n    say \"All enclave application already exist in the $BUILDER_INSTANCE_OUTPUT_PATH folder.\" \\\n        \"Skipping build...\"\n    return $SUCCESS\n  }\n\n  clone_repository $MANIFEST_REPOSITORY $MANIFEST_NAME $MANIFEST_TAG || {\n    die \"Error while cloning repository of $MANIFEST_NAME!\"\n  }\n\n  # Build EIF file if it doesn't exist in the bin folder.\n  [[ ! -f \"$BUILDER_INSTANCE_OUTPUT_PATH/$MANIFEST_EIF_NAME\" ]] && {\n    local target=\"\"\n    [[ \"$MANIFEST_EIF_DOCKER_TARGET\" != \"\" ]] && { target=\"--target $MANIFEST_EIF_DOCKER_TARGET\"; }\n\n    # Build EIF File\n    docker build -t $MANIFEST_EIF_DOCKER_IMAGE_NAME:$MANIFEST_EIF_DOCKER_IMAGE_TAG \\\n      $target \\\n      -f $MANIFEST_NAME/$MANIFEST_EIF_DOCKER_FILE_PATH/$MANIFEST_EIF_DOCKER_FILE_NAME \\\n      $MANIFEST_NAME/$MANIFEST_EIF_DOCKER_BUILD_PATH || {\n        die \"Cannot build docker image $MANIFEST_EIF_DOCKER_IMAGE_NAME!\"\n      }\n\n    build_eif $MANIFEST_EIF_DOCKER_IMAGE_NAME $MANIFEST_EIF_DOCKER_IMAGE_TAG \\\n      $MANIFEST_EIF_NAME || die \"Cannot build eif file!\"\n  }\n\n  # Build instance application if available\n  [[ $exp_files_exist -ne 0 && ! -z $MANIFEST_INSTANCE_DOCKER_IMAGE_NAME ]]  && {\n    target=\"\"\n    [[ \"$MANIFEST_INSTANCE_DOCKER_TARGET\" != \"\" ]] && { target=\"--target $MANIFEST_INSTANCE_DOCKER_TARGET\"; }\n\n    docker build -t $MANIFEST_INSTANCE_DOCKER_IMAGE_NAME:$MANIFEST_INSTANCE_DOCKER_IMAGE_TAG \\\n      $target \\\n      -f $MANIFEST_NAME/$MANIFEST_INSTANCE_DOCKER_FILE_PATH/$MANIFEST_INSTANCE_DOCKER_FILE_NAME \\\n      $MANIFEST_NAME/$MANIFEST_INSTANCE_DOCKER_BUILD_PATH || {\n        die \"Cannot build docker image $MANIFEST_INSTANCE_DOCKER_IMAGE_NAME!\"\n      }\n  }\n\n  return $SUCCESS\n}\n\nmain\n", "num_lines": 215}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Helper Functions\n####################################################\n\n_create_deployment_file() {\n  local filepath=$1\n  local container_name=$2\n  local repository_uri=$3\n\nreadonly file_content=$(cat<<EOF\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: hello-deployment\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: hello\n  template:\n    metadata:\n      labels:\n        app: hello\n    spec:\n      containers:\n      - name: $container_name\n        image: $repository_uri:latest\n        command: [\"/home/run.sh\"]\n        imagePullPolicy: Always\n        volumeMounts:\n        - mountPath: /hugepages-2Mi\n          name: hugepage-2mi\n          readOnly: false\n        # Enable if 1Gi pages are required\n        #- mountPath: /hugepages-1Gi\n        #  name: hugepage-1gi\n        #  readOnly: false\n        resources:\n          limits:\n            aws.ec2.nitro/nitro_enclaves: \"1\"\n            hugepages-2Mi: 512Mi\n            cpu: 250m\n          requests:\n            aws.ec2.nitro/nitro_enclaves: \"1\"\n            hugepages-2Mi: 512Mi\n      volumes:\n      - name: hugepage-2mi\n        emptyDir:\n          medium: HugePages-2Mi\n      - name: hugepage-1gi\n        emptyDir:\n          medium: HugePages-1Gi\n      tolerations:\n      - effect: NoSchedule\n        operator: Exists\n      - effect: NoExecute\n        operator: Exists\nEOF\n)\n  # Create deployment yaml file\n  #\n  reset_ifs\n  printf '%s\\n' $file_content > $filepath || return $FAILURE\n  restore_ifs\n\n  return $SUCCESS\n}\n\n####################################################\n# Events\n####################################################\n\non_run() {\n  return $SUCCESS\n}\n\non_file_requested() {\n  local filename=$1\n  local target_dir=$2\n  local retval=$SUCCESS\n\n  case $filename in\n  \"hello_deployment.yaml\")\n    local fullpath=$target_dir/$filename\n    local container_name=$3;\n    local repository_uri=$4;\n    _create_deployment_file \"$fullpath\" \"$container_name\" \"$repository_uri\"; retval=$?;\n    ;;\n  *)\n    say_err \"${FUNCNAME[0]}: Requested file $1 is unknown.\"\n    retval=$FAILURE\n    ;;\n  esac\n\n  return $retval\n}\n\non_stop() {\n  return $SUCCESS\n}\n", "num_lines": 105}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nreadonly EIF_PATH=\"/home/hello.eif\"\nreadonly ENCLAVE_CPU_COUNT=2\nreadonly ENCLAVE_MEMORY_SIZE=128\n\nmain() {\n    nitro-cli run-enclave --cpu-count $ENCLAVE_CPU_COUNT --memory $ENCLAVE_MEMORY_SIZE \\\n        --eif-path $EIF_PATH --debug-mode\n\n    local enclave_id=$(nitro-cli describe-enclaves | jq -r \".[0].EnclaveID\")\n    echo \"-------------------------------\"\n    echo \"Enclave ID is $enclave_id\"\n    echo \"-------------------------------\"\n\n    nitro-cli console --enclave-id $enclave_id # blocking call.\n}\n\nmain", "num_lines": 20}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Helper Functions\n####################################################\n\n_create_deployment_file() {\n  local filepath=$1\n  local container_name=$2\n  local repository_uri=$3\n\nreadonly file_content=$(cat<<EOF\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: kms-deployment\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: kms\n  template:\n    metadata:\n      labels:\n        app: kms\n    spec:\n      serviceAccountName: ne-service-account\n      containers:\n      - name: $container_name\n        image: $repository_uri:latest\n        command: [\"/home/run.sh\"]\n        imagePullPolicy: Always\n        volumeMounts:\n        - mountPath: /hugepages-2Mi\n          name: hugepage-2mi\n          readOnly: false\n        # Enable if 1Gi pages are required\n        #- mountPath: /hugepages-1Gi\n        #  name: hugepage-1gi\n        #  readOnly: false\n        resources:\n          limits:\n            aws.ec2.nitro/nitro_enclaves: \"1\"\n            hugepages-2Mi: 512Mi\n            cpu: 250m\n          requests:\n            aws.ec2.nitro/nitro_enclaves: \"1\"\n            hugepages-2Mi: 512Mi\n      volumes:\n      - name: hugepage-2mi\n        emptyDir:\n          medium: HugePages-2Mi\n      - name: hugepage-1gi\n        emptyDir:\n          medium: HugePages-1Gi\n      tolerations:\n      - effect: NoSchedule\n        operator: Exists\n      - effect: NoExecute\n        operator: Exists\nEOF\n)\n\n  # Create deployment yaml file\n  #\n  reset_ifs\n  printf '%s\\n' $file_content > $filepath || return $FAILURE\n  restore_ifs\n\n  return $SUCCESS\n}\n\n####################################################\n# Events\n####################################################\n\non_run() {\n  # Create service account\n  eksctl utils associate-iam-oidc-provider \\\n    --cluster $CONFIG_EKS_CLUSTER_NAME \\\n    --region $CONFIG_REGION \\\n    --approve || {\n        say_err \"Error while creating a service account!\"\n        return $FAILURE\n    }\n\n  local policy_arn=$(aws iam list-policies --query 'Policies[?PolicyName==`enclave_sa_policy`].Arn' --output text)\n\n  if [[ -z \"$policy_arn\" ]]\n  then\n    aws iam create-policy \\\n      --policy-name enclave_sa_policy \\\n      --policy-document file://$CONTAINER_DIR/kms/enclave_sa_policy.json || {\n        say_err \"Cannot create IAM policy for KMS!\"\n        return $FAILURE\n    }\n\n    policy_arn=$(aws iam list-policies --query 'Policies[?PolicyName==`enclave_sa_policy`].Arn' --output text)\n  fi\n\n  eksctl create iamserviceaccount \\\n    --name ne-service-account \\\n    --namespace default \\\n    --cluster $CONFIG_EKS_CLUSTER_NAME \\\n    --role-name \"kms-service-account\" \\\n    --attach-policy-arn $policy_arn \\\n    --region $CONFIG_REGION \\\n    --approve || {\n      say_err \"Failed to create service account!\"\n      return $FAILURE\n  }\n\n  return $SUCCESS\n}\n\non_file_requested() {\n  local filename=$1\n  local target_dir=$2\n  local retval=$SUCCESS\n\n  case $filename in\n  \"kms_deployment.yaml\")\n    local fullpath=$target_dir/$filename\n    local container_name=$3;\n    local repository_uri=$4;\n    _create_deployment_file \"$fullpath\" \"$container_name\" \"$repository_uri\"; retval=$?;\n    ;;\n  *)\n    say_err \"${FUNCNAME[0]}: Requested file $1 is unknown.\"\n    retval=$FAILURE\n    ;;\n  esac\n\n  return $retval\n}\n\non_stop() {\n  return $SUCCESS\n}\n", "num_lines": 142}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n#Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nreadonly MY_NAME=\"kms-example\"\n\nreadonly EIF_PATH=\"/home/kmstool.eif\"\nreadonly ENCLAVE_CPU_COUNT=2\nreadonly ENCLAVE_MEMORY_SIZE=128\n\nCIPHERTEXT=\"\"\n\nlog() {\n    echo -e \"[$MY_NAME] $*\" 1>&2\n}\n\ninit() {\n    # Load configuration\n    # - CMK_REGION\n    # - CONFIG_VERBOSE\n    source \"/home/.config\"\n\n    [[ -z \"$CMK_REGION\" ]] && {\n        log \"[ERROR]: AWS region cannot be empty!\"\n        exit 1\n    }\n\n    local account_id=$(aws sts get-caller-identity | jq -r .Account)\n    sed -i \"s/ACCOUNT_ID/${account_id}/g\" /home/test-enclave-policy.json\n\n    log \"Creating a KMS key...\"\n    local kms_key_arn=$(aws kms create-key --description \"Nitro Enclaves Test Key\" --policy file:///home/test-enclave-policy.json --query KeyMetadata.Arn --output text)\n    local message=\"Hello, KMS\\!\"\n\n    log \"Encrypting message...\"\n    CIPHERTEXT=$(aws kms encrypt --key-id \"$kms_key_arn\" --plaintext \"$message\" --query CiphertextBlob --output text --region \"$CMK_REGION\")\n\n    log \"******************************\"\n    log \"KMS Key ARN: $kms_key_arn\"\n    log \"Account ID: $account_id\"\n    log \"Unencrypted message: $message\"\n    log \"Ciphertext: $CIPHERTEXT\"\n    log \"******************************\"\n\n    nitro-cli run-enclave --cpu-count $ENCLAVE_CPU_COUNT --memory $ENCLAVE_MEMORY_SIZE \\\n        --eif-path $EIF_PATH --debug-mode 2>&1 > /dev/null\n\n    vsock-proxy 8000 kms.$CMK_REGION.amazonaws.com 443 &\n}\n\nuninit() {\n    local enclave_id=$1\n    nitro-cli terminate-enclave --enclave-id $enclave_id 2>&1 > /dev/null\n}\n\nmain() {\n    init\n\n    local desc=$(nitro-cli describe-enclaves)\n    local enclave_id=$(echo $desc | jq -r .[0].EnclaveID)\n    local enclave_cid=$(echo $desc | jq -r .[0].EnclaveCID)\n    local kms_command=\"kmstool_instance --cid $enclave_cid --region $CMK_REGION $CIPHERTEXT\"\n    [[ \"$CONFIG_VERBOSE\" != \"yes\" ]] && {\n        kms_command+=\" 2>&1 | grep \\\"Object = { \\\\\\\"Status\\\\\\\"\\\"\"\n    }\n\n    log \"Requesting from the enclave to decrypt message...\"\n\n    local kms_output=$(eval $kms_command)\n    log \"------------------------\"\n    log \"> Got response from the enclave!\"\n    log $kms_output\n    log \"------------------------\"\n    uninit $enclave_id\n\n    sleep infinity\n}\n\nmain\n", "num_lines": 79}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Launch Template: User Data\n####################################################\n\nreadonly lt_user_data=$(cat<<EOF\nMIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"==MYBOUNDARY==\"\n\n--==MYBOUNDARY==\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\n\n#!/bin/bash -e\nreadonly NE_ALLOCATOR_SPEC_PATH=\"/etc/nitro_enclaves/allocator.yaml\"\n# Node resources that will be allocated for Nitro Enclaves\nreadonly CPU_COUNT=$CONFIG_NODE_ENCLAVE_CPU_LIMIT\nreadonly MEMORY_MIB=$CONFIG_NODE_ENCLAVE_MEMORY_LIMIT_MIB\n\n# This step below is needed to install nitro-enclaves-allocator service.\namazon-linux-extras install aws-nitro-enclaves-cli -y\n# Update enclave's allocator specification: allocator.yaml\nsed -i \"s/cpu_count:.*/cpu_count: \\$CPU_COUNT/g\" \\$NE_ALLOCATOR_SPEC_PATH\nsed -i \"s/memory_mib:.*/memory_mib: \\$MEMORY_MIB/g\" \\$NE_ALLOCATOR_SPEC_PATH\n# Restart the nitro-enclaves-allocator service to take changes effect.\nsystemctl restart nitro-enclaves-allocator.service\necho \"NE user data script has finished successfully.\"\n--==MYBOUNDARY==\nEOF\n)\n\n####################################################\n# Base64 Encode User Data\n####################################################\n\nreset_ifs\nreadonly b64_lt_user_data=$(printf '%s\\n' $lt_user_data | base64 -w 0)\nrestore_ifs\n\n####################################################\n# Launch Template Data\n####################################################\n\nreadonly launch_template_data=$(cat <<EOF\n{\n  \"InstanceType\": \"$CONFIG_INSTANCE_TYPE\",\n  \"EnclaveOptions\": {\n    \"Enabled\": true\n  },\n  \"UserData\" : \"${b64_lt_user_data}\"\n}\nEOF\n)\n\n####################################################\n# Helper functions\n####################################################\n\nlaunch_template_exists() {\n  local name=$1\n  local out=$(awscli ec2 describe-launch-templates | grep $name)\n  ok_or_die \"Cannot get launch template info!\"\n  if [[ -z \"$out\" ]]; then\n    return 255 # Not exists.\n  fi\n}\n\ncreate_launch_template() {\n  local name=$1\n\n  awscli ec2 create-launch-template \\\n    --launch-template-name $name \\\n    --version-description  \"$lt_version_desc\" \\\n    --launch-template-data \"$launch_template_data\"\n}\n\n####################################################\n# Functions\n####################################################\n\nmain() {\n  local lt_name=\"lt_$CONFIG_SETUP_UUID\"\n\n  launch_template_exists $lt_name -eq 0 && {\n    say_warn \"A launch template with name $lt_name already exists.\"\n    return $SUCCESS\n  }\n\n  say \"Creating launch template with name: ${lt_name}\"\n\n  create_launch_template $lt_name || {\n    say_err \"Error while creating launch template! (Code: $?)\"\n    return $FAILURE\n  }\n\n  say \"Launch template has been created successfully in $CONFIG_REGION region.\"\n}\n", "num_lines": 100}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# EKSCTL ClusterConfig generation\n####################################################\n\nfunction generate_cluster_config() {\nlocal lt_id=$1\ncat<<EOF\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\n\nmetadata:\n  name: $CONFIG_EKS_CLUSTER_NAME\n  region: $CONFIG_REGION\n  version: \"$CONFIG_K8S_VERSION\"\n\nmanagedNodeGroups:\n  - name: $CONFIG_EKS_WORKER_NODE_NAME\n    launchTemplate:\n      id: $lt_id\n      version: \"1\"\n    desiredCapacity: $CONFIG_EKS_WORKER_NODE_CAPACITY\n\nEOF\n}\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  local lt_name=\"lt_$CONFIG_SETUP_UUID\"\n  local lt_id=$(get_launch_template_id $lt_name)\n\n  [[ \"$lt_id\" != \"\" ]] || die \"Cannot retrieve launch template id!\"\n  debug \"Launch template id: $lt_id\"\n\n  cluster_exists $CONFIG_EKS_CLUSTER_NAME -eq 0 && {\n    say_warn \"The EKS cluster with name $CONFIG_EKS_CLUSTER_NAME already exists.\"\n    return $SUCCESS\n  }\n\n  local cluster_config=$(generate_cluster_config $lt_id)\n\n  say_warn \"####################################################\"\n  say_warn \"Using $FILE_CLUSTER_CONFIG to create an EKS cluster.\"\n  say_warn \"Cluster creation will take some time.\"\n  say_warn \"####################################################\"\n\n  reset_ifs\n  printf '%s\\n' $cluster_config > $WORKING_DIR/$FILE_CLUSTER_CONFIG\n  restore_ifs\n\n  debug $cluster_config\n  eksctl create cluster -f $WORKING_DIR/$FILE_CLUSTER_CONFIG\n}\n", "num_lines": 60}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Constants\n####################################################\n\nreadonly DP_DAEMONSET_NAME=aws-nitro-enclaves-k8s-daemonset\nreadonly DP_PLUGIN_LABEL=aws-nitro-enclaves-k8s-dp\n\n####################################################\n# Misc Specification\n####################################################\nreadonly misc_specification=$(cat<<EOF\napiVersion: v1\nkind: Namespace\nmetadata:\n  name: nitro-enclaves\n  labels:\n    name: nitro-enclaves\n---\napiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: $DP_DAEMONSET_NAME\n  namespace: kube-system\n  labels:\n    name: $DP_PLUGIN_LABEL\n    role: agent\nspec:\n  selector:\n    matchLabels:\n      name: $DP_PLUGIN_LABEL\n  updateStrategy:\n    type: RollingUpdate\n  template:\n    metadata:\n      labels:\n        name: $DP_PLUGIN_LABEL\n      annotations:\n        node.kubernetes.io/bootstrap-checkpoint: \"true\"\n    spec:\n      nodeSelector:\n        $DP_PLUGIN_LABEL: enabled\n      priorityClassName: \"system-node-critical\"\n      hostname: $DP_PLUGIN_LABEL\n      containers:\n      - name: $DP_PLUGIN_LABEL\n        image: public.ecr.aws/aws-nitro-enclaves/aws-nitro-enclaves-k8s-device-plugin:latest\n        imagePullPolicy: Always\n        securityContext:\n          allowPrivilegeEscalation: false\n          capabilities:\n            drop: [\"ALL\"]\n        resources:\n          limits:\n            cpu: 100m\n            memory: 15Mi\n          requests:\n            cpu: 10m\n            memory: 15Mi\n        volumeMounts:\n          - name: device-plugin\n            mountPath: /var/lib/kubelet/device-plugins\n          - name: dev-dir\n            mountPath: /dev\n          - name: sys-dir\n            mountPath: /sys\n      volumes:\n        - name: device-plugin\n          hostPath:\n            path: /var/lib/kubelet/device-plugins\n        - name: dev-dir\n          hostPath:\n            path: /dev\n        - name: sys-dir\n          hostPath:\n            path: /sys\n      terminationGracePeriodSeconds: 30\nEOF\n)\n\n####################################################\n# Helper functions\n####################################################\n\nget_node_name() {\n  echo $(kubectl get nodes -o json | jq -r '.items[].metadata.name')\n}\n\ndevice_plugin_running() {\n  kubectl get pods -n kube-system --field-selector=status.phase=Running \\\n  | grep $DP_DAEMONSET_NAME 2>&1 > /dev/null\n}\n\nunlabel_node() {\n  local node_name=$1\n  local label=$2\n  kubectl label node $node_name $label-\n}\n\nlabel_node() {\n  local node_name=$1\n  local label=$2\n  local value=$3\n  kubectl label node $node_name $2=$3\n}\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  device_plugin_running -eq 0 && {\n    say_warn \"Device plugin is already enabled and running.\"\n    return $SUCCESS\n  }\n\n  reset_ifs\n  printf '%s\\n' $misc_specification > $FILE_K8S_DEVICE_PLUGIN_MANIFEST\n  restore_ifs\n\n  local node_name=$(get_node_name)\n  [ -z \"${node_name}\" ] && {\n    say_err \"Cannot get K8s node name. Device plugin installation has failed!\"\n    say_err \"Make sure cluster the cluster installation has completed successfully.\"\n    return $FAILURE\n  }\n\n  say \"Attempt to unlabel node $node_name...\"\n  unlabel_node $node_name $DP_PLUGIN_LABEL\n\n  say \"Enabling Nitro Enclaves K8s device plugin...\"\n  kubectl apply -f $FILE_K8S_DEVICE_PLUGIN_MANIFEST || {\n    say_err \"Error applying manifest. ($FILE_K8S_DEVICE_PLUGIN_MANIFEST)\"\n    return $FAILURE\n  }\n\n  say \"Labelling node $node_name...\"\n  label_node $node_name $DP_PLUGIN_LABEL enabled -eq 0 || {\n    say_err \"Error while labelling ${node_name}.\"\n    return $FAILURE\n  }\n}\n", "num_lines": 146}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Constants\n####################################################\n\nreadonly BUILDER_CONTAINER_DIR=$WORKING_DIR/container\nreadonly BUILDER_ARTIFACTS_DIR=$BUILDER_CONTAINER_DIR/bin\nreadonly BUILDER_DOCKERFILE=$BUILDER_CONTAINER_DIR/builder/Dockerfile.builder\nreadonly BUILDER_IMAGE=ne-example-builder:latest\n\n####################################################\n# Helper functions\n####################################################\n\n# Builds .eif file and other binary files defined by the\n# example's Dockerfile. If the build succeeds, the EIF\n# file is automatically exported to the artifacts folder.\nbuild_enclave_apps() {\n  local project_name=$1\n\n  docker run \\\n    -v /var/run/docker.sock:/var/run/docker.sock \\\n    -v $BUILDER_ARTIFACTS_DIR:/output \\\n    -v $BUILDER_CONTAINER_DIR/$project_name:/source \\\n    --env-file $FILE_CONFIGURATION \\\n    -it $BUILDER_IMAGE\n}\n\n# Exports additional files defined in the enclave manifest file\n# to the artifacts folder.\nexport_files() {\n  local enclave_manifest=$1\n  # Get the name:tag information of the image.\n  local apps_image=$(jq -r '.instance.docker | \"\\(.image_name):\\(.image_tag)\"' $enclave_manifest)\n  # Get exported files list.\n  local exported_files=($(jq -r '[.instance.exports[]]|join(\" \")' $enclave_manifest 2> /dev/null))\n\n  for exp_file in ${exported_files[@]}\n  do\n    say \"Exporting $exp_file...\"\n    [ -f \"$BUILDER_ARTIFACTS_DIR/$(basename $exp_file)\" ] && {\n      say_warn \"$(basename $exp_file) already exists in the bin/ directory.\"\n      continue;\n    }\n    copy_from_docker_image $apps_image $exp_file $BUILDER_ARTIFACTS_DIR\n  done\n}\n\n####################################################\n# Main\n####################################################\nmain() {\n  local project_name=$1\n\n  # Build image builder if it doesn't exist already.\n  # This container image has all dependencies installed\n  # that we need to build enclave images.\n  docker build -t $BUILDER_IMAGE -f $BUILDER_DOCKERFILE $BUILDER_CONTAINER_DIR\n  mkdir -p $BUILDER_ARTIFACTS_DIR\n\n  [[ ! -d $BUILDER_CONTAINER_DIR/$project_name ]] && {\n    say_err \"Cannot find $project_name under $BUILDER_CONTAINER_DIR directory.\"\n    return $FAILURE\n  }\n\n  local enclave_manifest=\"$BUILDER_CONTAINER_DIR/$project_name/enclave_manifest.json\"\n  local eif_file=($(jq -r '.eif_name' $enclave_manifest 2> /dev/null))\n  local skip_eif_build=false\n\n  [ -f \"$BUILDER_ARTIFACTS_DIR/$eif_file\" ] && {\n    say_warn \"$eif_file already exists. Existing EIF file will be reused.\"\n    skip_eif_build=true;\n  }\n\n  # Build enclave apps\n  [[ \"$skip_eif_build\" != true ]] && {\n    build_enclave_apps $project_name || {\n      say_err \"Enclave apps build failed with error. (Code: $?)\"\n      return $FAILURE\n    }\n  }\n\n  # .eif file has already been built and exported to $BUILDER_ARTIFACTS_DIR\n  # directory. Let's check if we have any other exports defined in the manifest file.\n  export_files $enclave_manifest || {\n    say_err \"Enclave apps build failed at export stage with error. (Code: $?)\"\n    return $FAILURE\n  }\n}\n", "num_lines": 93}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n###################################################\n# Main\n####################################################\n\nmain() {\n  local project_name=$1\n  local image=\"$project_name-$CONFIG_SETUP_UUID:latest\"\n  local build_path=$WORKING_DIR/container\n  local dockerfile_path=$build_path/$project_name/Dockerfile\n\n  docker image rm $image || true\n  docker build --target image \\\n    --build-arg config_region=$CONFIG_REGION \\\n    -t $image -f $dockerfile_path $build_path || {\n    say_err \"Error while building docker image! (Code: $?)\"\n    return $FAILURE\n  }\n}\n", "num_lines": 23}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n###################################################\n# Helper functions\n####################################################\n\nrepository_exists() {\n  local repo_name=$1\n  local result=$(aws ecr describe-repositories --region $CONFIG_REGION | \\\n              jq -r --arg rn \"$repo_name\" '.repositories[]|select(.repositoryName==$rn)| .repositoryName')\n  [[ \"$result\" != \"$repo_name\" ]] && return $FAILURE\n  return $SUCCESS\n}\n\ncreate_ecr_repository() {\n  local repo_name=$1\n  awscli ecr create-repository \\\n      --repository-name $repo_name \\\n      --image-tag-mutability MUTABLE\n}\n\n###################################################\n# Main\n####################################################\n\nmain() {\n  local project_name=$1\n  local repo_name=\"$project_name-$CONFIG_SETUP_UUID\"\n\n  repository_exists $repo_name || {\n    say_warn \"Creating an ECR repository: $repo_name.\"\n\n    create_ecr_repository $repo_name || {\n      say_err \"Cannot create repository with name $repo_name.\"\n      return $FAILURE\n    }\n  }\n\n  local image=\"$repo_name:latest\"\n  local repo_uri=$(get_repository_uri $repo_name)\n\n  docker tag $image $repo_uri || {\n    say_err \"Cannot tag image $image! Please ensure that you built the image!\"\n    return $FAILURE\n  }\n\n  [[ \"$repo_uri\" != \"null\" ]] || {\n    say_err \"Cannot get repository URI for $repo_name!\"\n    return $FAILURE\n  }\n \n  local registry_addr=${repo_uri/%\"/$repo_name\"}\n  \n  docker_login $registry_addr $CONFIG_REGION || {\n    say_error \"Cannot log in to ${registry_addr}!\"\n    return $FAILURE\n  }\n \n  docker push $repo_uri\n}\n", "num_lines": 63}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  local tool_image_name=$1\n  local image_name=\"$tool_image_name-$CONFIG_SETUP_UUID\"\n  local repository_uri=$(get_repository_uri $image_name)\n\n  [[ \"$repository_uri\" == \"null\" || \"$repository_uri\" == \"\" ]] && {\n    say_err \"Cannot get repository URI for $repository_name!\"\n    return $FAILURE\n  }\n\n  local deployment_file=\"${tool_image_name}_deployment.yaml\"\n\n  # Prepare necessary resources before running the app.\n  trigger_event $tool_image_name on_run\n  # Render a deployment file.\n  trigger_event $tool_image_name \\\n                on_file_requested \\\n                \"$deployment_file\" \\\n                \"$WORKING_DIR\" \\\n                \"$image_name\" \\\n                \"$repository_uri\"\n\n  say \"Generated deployment file: $deployment_file.\"\n  local prepare_only=$2\n  [[ \"$prepare_only\" != false ]] && { return $SUCCESS; }\n\n  kubectl apply -f \"$WORKING_DIR/$deployment_file\" || {\n    say_err \"Error while applying deployment file: $deployment_file\"\n    return $FAILURE\n  }\n}\n\n", "num_lines": 41}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  local tool_image_name=$1\n  local deployment_file=\"$WORKING_DIR/${tool_image_name}_deployment.yaml\"\n\n  kubectl delete -f $deployment_file || {\n    say_err \"Error while stopping application $tool_image_name!\"\n  }\n\n  trigger_event $tool_image_name on_stop\n}\n", "num_lines": 19}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n####################################################\n# Helper functions\n####################################################\n\ndelete_file() {\n say \"Deleting $1...\"\n rm -f $WORKING_DIR/$1\n}\n\nis_eksctl_installed() {\n  which eksctl 2>&1 > /dev/null\n}\n\ndelete_eks_resources() {\n  say \"Attempt to delete cluster node group: $CONFIG_EKS_WORKER_NODE_NAME\"\n\n  eksctl delete nodegroup --cluster=$CONFIG_EKS_CLUSTER_NAME --name=$CONFIG_EKS_WORKER_NODE_NAME \\\n    --region $CONFIG_REGION --wait || $force_cleanup || {\n      say_err \"Cluster node group cannot be deleted.\"\n      return $FAILURE\n    }\n\n  say \"Attempt to delete cluster: $CONFIG_EKS_WORKER_NODE_NAME\"\n\n  eksctl delete cluster --name $CONFIG_EKS_CLUSTER_NAME \\\n    --region $CONFIG_REGION --wait || $force_cleanup || {\n      say_err \"Cluster cannot be deleted.\"\n      return $FAILURE\n    }\n}\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  local force_cleanup=$1\n  #TODO: Delete the ECR repository\n  #TODO: Delete docker images\n\n  is_eksctl_installed && {\n    delete_eks_resources $force_cleanup\n  }\n\n  local lt_name=\"lt_$CONFIG_SETUP_UUID\"\n  local lt_id=$(get_launch_template_id $lt_name)\n\n  say \"Attempt to delete launch template: $lt_name\"\n\n  [[ \"$lt_id\" != \"\" ]] && {\n    awscli ec2 delete-launch-template --launch-template-id $lt_id || $force_cleanup || \\\n      --region $CONFIG_REGION || $force_cleanup || {\n        say_error \"Launch template cannot be deleted.\"\n        return $FAILURE\n      }\n  }\n\n  delete_file $FILE_CLUSTER_CONFIG\n  delete_file $FILE_CONFIGURATION\n  delete_file $FILE_SETUP_ID\n}\n", "num_lines": 66}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nreadonly DEBUG=false\n\nreadonly WORKING_DIR=$(cd $(dirname $(realpath ${BASH_SOURCE[0]}))/../ && pwd)\nreadonly SCRIPTS_DIR=$WORKING_DIR/scripts\nreadonly CONTAINER_DIR=$WORKING_DIR/container\n\nreadonly FILE_SETUP_ID=\".setup.ne.k8s.ctl\"\nreadonly FILE_CONFIGURATION=\".config.ne.k8s.ctl\"\nreadonly FILE_CLUSTER_CONFIG=\"cluster_config.yaml\"\nreadonly FILE_K8S_DEVICE_PLUGIN_MANIFEST=\"aws-nitro-enclaves-k8s-ds.yaml\"\n\nreadonly FILE_HOOKS=\"hooks.sh\"\n\nreadonly DIRECTORY_DEMO_BINARIES=\"$WORKING_DIR/container/bin\"\n", "num_lines": 19}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nsource \"$(dirname $(realpath ${BASH_SOURCE[0]}))/common.sh\"\nsource \"$WORKING_DIR/scripts/utils.sh\"\n\n####################################################\n# Constants\n####################################################\n\nreadonly MY_NAME=\"fetch-prebuilt\"\n\nreadonly DEMO_BIN_REGISTRY=709843417989.dkr.ecr.eu-west-1.amazonaws.com\nreadonly DEMO_BIN_REPOSITORY_NAME=ne-kms-demo-binaries\nreadonly DEMO_BIN_REPOSITORY_TAG=latest\nreadonly DEMO_BIN_REGION=\"eu-west-1\"\nreadonly DEMO_BIN_IMAGE=$DEMO_BIN_REGISTRY/$DEMO_BIN_REPOSITORY_NAME:$DEMO_BIN_REPOSITORY_TAG\n\nreadonly DEMO_BINARIES=(hello.eif kmstool_instance kmstool.eif libnsm.so)\n\n####################################################\n# Helper functions\n####################################################\n\ncheck_existing_binaries() {\n  for binary in ${DEMO_BINARIES[@]}\n  do\n    [ -f $DIRECTORY_DEMO_BINARIES/$binary ] && {\n      say_warn \"container/bin directory already contains some files.\" \\\n          \"This operation will overwrite existing files.\"\n      read -p \"Are you sure want to continue? (y/n)\" yn\n      case $yn in\n        [Yy]* ) break;;\n        * ) die \"Fetch operation has been cancelled!\";;\n      esac\n    }\n  done\n}\n\n# Extracts all demo binaries inside from container to the\n# containers/bin directory.\nextract_demo_binaries() {\n  for binary in ${DEMO_BINARIES[@]}\n  do\n    say \"Extracting $binary...\"\n    copy_from_docker_image $DEMO_BIN_IMAGE $binary $DIRECTORY_DEMO_BINARIES \\\n      || return $FAILURE\n  done\n}\n\n####################################################\n# Main\n####################################################\n\nmain() {\n  check_existing_binaries\n\n  #TODO: Remove after public repository becomes available.\n  docker_login $DEMO_BIN_REGISTRY $DEMO_BIN_REGION || {\n    say_warn \"Cannot log in to ${DEMO_BIN_REGISTRY}!\"\n    return $FAILURE\n  }\n\n  docker pull $DEMO_BIN_IMAGE || {\n    say_err \"Cannot fetch ${DEMO_BIN_REPOSITORY_NAME} from registry ${DEMO_BIN_REGISTRY}!\"\n    return $FAILURE\n  }\n\n  extract_demo_binaries || {\n    say_err \"Demo binaries cannot be extracted! Please make sure you have write access for the working directory.\"\n    return $FAILURE\n  }\n}\n\nmain", "num_lines": 76}
{"repo_name": "aws-nitro-enclaves-with-k8s", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Generic error codes\n#\nreadonly SUCCESS=0\nreadonly FAILURE=255\n\n####################################################\n# Utility functions\n####################################################\n\n_IFS=${_IFS-${IFS}}\n\nfunction reset_ifs {\n  IFS=\n}\n\nfunction restore_ifs {\n  IFS=$_IFS\n}\n\n# ######################################################\n\n# Send an error-decorated text message to stderr\n#\nsay_err() {\n  [ -t 2 ] && [ -n \"$TERM\" ] \\\n    && echo \"$(tput setaf 1)[$MY_NAME] $*$(tput sgr0)\" 1>&2 \\\n    || echo \"[$MY_NAME] $*\" 1>&2\n}\n\n# Send a warning-decorated text message to stderr\n#\nsay_warn() {\n  [ -t 2 ] && [ -n \"$TERM\" ] \\\n    && echo \"$(tput setaf 3)[$MY_NAME] $*$(tput sgr0)\" 1>&2 \\\n    || echo \"[$MY_NAME] $*\" 1>&2\n}\n\n# Send a decorated message to stdout, followed by a new line\n#\nsay() {\n  [ -t 1 ] && [ -n \"$TERM\" ] \\\n    && echo \"$(tput setaf 2)[$MY_NAME]$(tput sgr0) $*\" \\\n    || echo \"[$MY_NAME] $*\"\n}\n\n# Send a debug message to stdout, followed by a new line\n#\ndebug() {\n  [ \"$DEBUG\" == true ] && {\n    printf \"[DEBUG]\"\n    say $*\n  }\n}\n\n# Exit with an error message and (optional) code\n# Usage: die [-c <error code>] <error message>\n#\ndie() {\n  local code=1\n  [[ \"$1\" = \"-c\" ]] && {\n    code=\"$2\"\n    shift 2\n  }\n  say_err \"$@\"\n  exit $code\n}\n\n# Exit with an error message if the last exit code is not 0\n#\nok_or_die() {\n  local code=$?\n  [[ -f log.err ]] && cat log.err 1>&2 && rm -rf log.err\n  [[ $code -eq 0 ]] || die -c $code \"$@\"\n}\n\n# ######################################################\n\nfunction awscli {\n  debug \"aws \"$@\" -region $CONFIG_REGION\"\n  aws \"$@\" --region $CONFIG_REGION\n}\n\nget_launch_template_id() {\n  local lt_name=$1\n  local out=$(aws ec2 describe-launch-templates --region $CONFIG_REGION)\n  ok_or_die \"Cannot get launch template information!\"\n  echo $out | jq -r --arg lt_name \"$lt_name\" '.LaunchTemplates[] | select(.LaunchTemplateName == $lt_name).LaunchTemplateId'\n}\n\n# ######################################################\n\n# Checks if a cluster exists.\n#\ncluster_exists() {\n  local cluster_name=$1\n  out=$(aws eks list-clusters --region $CONFIG_REGION)\n  local match=$(echo $out | jq -r --arg cname $cluster_name '.clusters[]|select(. == $cname)')\n  [[ \"$match\" != \"$cluster_name\" ]] && return 255\n  debug \"[[ $match != $cluster_name ]]\"\n  return 0\n}\n\n# ######################################################\n\n# Copies a file inside from docker image to a host directory.\n#\ncopy_from_docker_image() {\n  local image=$1\n  local src_file=$2\n  local dst_path=$3\n\n  docker run \\\n    -v $dst_path:/output:rw \\\n    --rm --entrypoint \\\n    cp $image $src_file /output/\n}\n\n# Logs in to a private ECR\n#\ndocker_login() {\n  local registry_address=$1\n  local region=$2\n  aws ecr get-login-password --region $region | \\\n     docker login --username AWS --password-stdin $registry_address\n}\n\n# Get URI of the given repository name.\nget_repository_uri() {\n    local repo_name=$1\n    local result=$(aws ecr describe-repositories --region $CONFIG_REGION | \\\n                jq -r --arg rn \"$repo_name\" '.repositories[]|select(.repositoryName==$rn)| .repositoryUri')\n    echo \"$result\"\n}\n\n# ######################################################\n\ntrigger_event() {\n  local project_name=$1\n  local event_name=$2\n  local hooks_file=$CONTAINER_DIR/$project_name/$FILE_HOOKS\n\n  [[ -f $hooks_file ]] && {\n    debug \"Found hooks file for $1!\"\n    source $hooks_file\n    [[ \"$(declare -Ff \"$event_name\")\" ]] && {\n      debug \"Running $event_name.\"\n      shift 2\n      $event_name \"$@\" || die \"$event_name @ $hooks_file have failed!\"\n    }\n  }\n\n  return $SUCCESS\n}", "num_lines": 157}
{"repo_name": "aws-northstar", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Build script is to be run from the root directory of the aws-northstar package\n\nset -ev\n\nBUILD_FOLDER_LEGACY=${PWD}/packages/legacy/build/\nSTYLEGUIDE_FOLDER_LEGACY=${PWD}/packages/legacy/styleguide.out/\nSTYLEGUIDE_FOLDER_LEGACY_EXAMPLE=${STYLEGUIDE_FOLDER_LEGACY}examples/\nEXAMPLES_FOLDER=${PWD}/packages/examples/\n\nBUILD_FOLDER_UI=${PWD}/packages/ui/build/\nSTORYBOOK_FOLDER_UI=${PWD}/packages/ui/storybook.out/\nSTORYBOOK_FOLDER_UI_EXAMPLE=${STORYBOOK_FOLDER_UI}static/examples/\n\nyarn install --immutable\nyarn test:ci\nyarn styleguide:build\nyarn storybook:build\n\necho 'Remove build folder to make sure the npm package only includes clean built components'\nif [ -d ${BUILD_FOLDER_LEGACY} ]; then rm -rf ${BUILD_FOLDER_LEGACY}; fi \nif [ -d ${BUILD_FOLDER_UI} ]; then rm -rf ${BUILD_FOLDER_UI}; fi \n\nyarn build\n\necho 'Merge coverage reports'\nif ! [ -d .nyc_output/ ]; then mkdir .nyc_output/; fi \nfind ./packages -type f -name \"coverage-final.json\" -path \"*/coverage/*\" -not \\( -path \"*/node_modules/*\" -prune \\) \\\n| nl -bt -nln \\\n| sed -re 's!^([0-9]+) +\\t(.+)$!\\2 .nyc_output/coverage-final-\\1.json!' \\\n| xargs -L 1 -t cp \nnpx nyc report --reporter lcov\n\necho \"Package the example app for legacy\"\n./scripts/packageDemo.sh legacy ${PWD}/packages/examples/legacy ${STYLEGUIDE_FOLDER_LEGACY_EXAMPLE} ${PWD}/packages/legacy/build 4000000 1700000\n\necho \"Package the example app for ui\"\n\n./scripts/packageDemo.sh ui ${PWD}/packages/examples/ui ${STORYBOOK_FOLDER_UI_EXAMPLE} ${PWD}/packages/ui/build 1500000 1000000\n", "num_lines": 41}
{"repo_name": "aws-northstar", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Package demo app\n\nset -e\n\nDEMO_TYPE=$1\nDEMO_FOLDER=$2\nEXAMPLE_FOLDER=$3\nBUILD_FOLDER=$4\nBUNDLE_SIZE_THRESHOLD=$5\nMAIN_BUNDLE_SIZE_THRESHOLD=$6\nTAR_PATH=${EXAMPLE_FOLDER}create-react-app.tar.gz\nTMP_FOLDER=/tmp/northstar_demo_${DEMO_TYPE}_$(date +%s)\n\necho \"DEMO_TYPE=${DEMO_TYPE}\"\necho \"DEMO_FOLDER=${DEMO_FOLDER}\"\necho \"EXAMPLE_FOLDER=${EXAMPLE_FOLDER}\"\necho \"BUILD_FOLDER=${BUILD_FOLDER}\"\necho \"BUNDLE_SIZE_THRESHOLD=${BUNDLE_SIZE_THRESHOLD}\"\necho \"MAIN_BUNDLE_SIZE_THRESHOLD=${MAIN_BUNDLE_SIZE_THRESHOLD}\"\necho \"TAR_PATH=${TAR_PATH}\"\necho \"TMP_FOLDER=${TMP_FOLDER}\"\n\nif [ -d $TMP_FOLDER ]; then rm -rf $TMP_FOLDER; fi\nmkdir -p $TMP_FOLDER\n\npushd $TMP_FOLDER\nrsync  -rv --exclude=\"node_modules/\" --exclude=\"build/\" --include=\"*/\" $DEMO_FOLDER/ $TMP_FOLDER/\n\necho \"Creating example folder if not exist\"\nif [ ! -d ${EXAMPLE_FOLDER} ]; then mkdir -p ${EXAMPLE_FOLDER}; fi \n\necho \"Packing demo app\" \ntar -czvf $TAR_PATH .\n\npopd\n\nrm -rf $TMP_FOLDER\n\necho \"Running Sanity check\"\n./scripts/runDemoTest.sh ${TAR_PATH} ${BUILD_FOLDER} ${BUNDLE_SIZE_THRESHOLD} ${MAIN_BUNDLE_SIZE_THRESHOLD}\n", "num_lines": 43}
{"repo_name": "aws-northstar", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sending notification to slack workflow\"\n\nCONTENT=\"{\\\"version\\\": \\\"${RELEASED_VERSION}\\\", \\\"link\\\": \\\"https://github.com/aws/aws-northstar/releases/tag/v${RELEASED_VERSION}\\\"}\"\ncurl -X POST -H 'Content-type: application/json' --data \"${CONTENT}\" ${SLACK_WORKFLOW_WEBHOOK}\n", "num_lines": 7}
{"repo_name": "aws-northstar", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Test the example app\n\nset -e\n\nTEST_FOLDER=/tmp/northstar_test_$(date +%s)\nDEMO_ARCHIVE=$1\nBUILD_FOLDER=$2\n\nBUNDLE_SIZE_THRESHOLD=$3\nMAIN_BUNDLE_SIZE_THRESHOLD=$4\n\necho \"TEST_FOLDER=${TEST_FOLDER}\"\necho \"DEMO_ARCHIVE=${DEMO_ARCHIVE}\"\necho \"BUILD_FOLDER=${BUILD_FOLDER}\"\necho \"BUNDLE_SIZE_THRESHOLD=${BUNDLE_SIZE_THRESHOLD}\"\necho \"MAIN_BUNDLE_SIZE_THRESHOLD=${MAIN_BUNDLE_SIZE_THRESHOLD}\"\n\nif [ -d $TEST_FOLDER ]; then rm -rf $TEST_FOLDER; fi\nmkdir -p $TEST_FOLDER\n\ntar -zxf ${DEMO_ARCHIVE} --directory ${TEST_FOLDER}\n\npushd $TEST_FOLDER \n\necho \"Building the project\"\nyarn add file://$BUILD_FOLDER\nyarn\nyarn build\n\necho \"Creating source map\"\nnpx source-map-explorer build/static/js/*.js --json result.json\n\necho \"File bundle size:\"\ncat result.json | jq \".results[] | .bundleName,.totalBytes\" \n\nFAILED_FILE_COUNT=$(cat result.json | jq \".results[] | select(.totalBytes>${BUNDLE_SIZE_THRESHOLD}) | .bundleName\" -r | wc -l | awk '{$1=$1;print}')\n\nFAILED_MAIN_FILE_COUNT=$(cat result.json | jq \".results | .[] | select(.bundleName | contains(\\\"main\\\")) | select(.totalBytes>${MAIN_BUNDLE_SIZE_THRESHOLD}) | .bundleName\" -r | wc -l | awk '{$1=$1;print}')\n\npopd\n\necho \"FAILED_FILE_COUNT=${FAILED_FILE_COUNT}\"\n\nif [ ${FAILED_FILE_COUNT} -gt 0 ] ; then\n    echo \"FAILED: One or more file bundle size exceeds threshold ${BUNDLE_SIZE_THRESHOLD}\"\n    exit 1\nelse\n    echo \"PASS: All file bundle size are below threshold ${BUNDLE_SIZE_THRESHOLD}\"\nfi\n\necho \"FAILED_MAIN_FILE_COUNT=${FAILED_MAIN_FILE_COUNT}\"\n\nif [ ${FAILED_MAIN_FILE_COUNT} -gt 0 ] ; then\n    echo \"FAILED: The main file bundle size exceeds threshold ${MAIN_BUNDLE_SIZE_THRESHOLD}\"\n    exit 1\nelse\n    echo \"PASS: The main file bundle size is below threshold ${MAIN_BUNDLE_SIZE_THRESHOLD}\"\nfi\n\nrm -rf $TEST_FOLDER\n", "num_lines": 63}
{"repo_name": "aws-ofi-nccl", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# Copyright (c) 2018-2019, Amazon.com, Inc. or its affiliates. All rights reserved.\n#\n# See LICENSE.txt for license information\n#\n\n#! /bin/sh -x\n\nautoreconf -ivf\n", "num_lines": 10}
{"repo_name": "aws-panorama-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "pip3 install --upgrade panoramacli", "num_lines": 1}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -ex\n\ncp client/resources/sigv4_auth.py client/src/pcluster_client\npatch -u -N client/src/pcluster_client/api_client.py < client/resources/api_client.py.patch\npatch -u -N client/src/requirements.txt < client/resources/client-requirements.txt.patch\npatch -u -N client/src/setup.py < client/resources/setup.py.patch\npatch -u -N client/src/README.md < client/resources/readme.md.patch\n", "num_lines": 17}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/\n#\n# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl \"minor update\" \"gitlab.com\"\n\ngit_user_id=$1\ngit_repo_id=$2\nrelease_note=$3\ngit_host=$4\n\nif [ \"$git_host\" = \"\" ]; then\n    git_host=\"github.com\"\n    echo \"[INFO] No command line input provided. Set \\$git_host to $git_host\"\nfi\n\nif [ \"$git_user_id\" = \"\" ]; then\n    git_user_id=\"GIT_USER_ID\"\n    echo \"[INFO] No command line input provided. Set \\$git_user_id to $git_user_id\"\nfi\n\nif [ \"$git_repo_id\" = \"\" ]; then\n    git_repo_id=\"GIT_REPO_ID\"\n    echo \"[INFO] No command line input provided. Set \\$git_repo_id to $git_repo_id\"\nfi\n\nif [ \"$release_note\" = \"\" ]; then\n    release_note=\"Minor update\"\n    echo \"[INFO] No command line input provided. Set \\$release_note to $release_note\"\nfi\n\n# Initialize the local directory as a Git repository\ngit init\n\n# Adds the files in the local repository and stages them for commit.\ngit add .\n\n# Commits the tracked changes and prepares them to be pushed to a remote repository.\ngit commit -m \"$release_note\"\n\n# Sets the new remote\ngit_remote=$(git remote)\nif [ \"$git_remote\" = \"\" ]; then # git remote not defined\n\n    if [ \"$GIT_TOKEN\" = \"\" ]; then\n        echo \"[INFO] \\$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment.\"\n        git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git\n    else\n        git remote add origin https://${git_user_id}:\"${GIT_TOKEN}\"@${git_host}/${git_user_id}/${git_repo_id}.git\n    fi\n\nfi\n\ngit pull origin master\n\n# Pushes (Forces) the changes in the local repository up to the remote repository\necho \"Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git\"\ngit push origin master 2>&1 | grep -v 'To https'\n", "num_lines": 58}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\nROOT_DIR=\"${SCRIPT_DIR}/../../..\"\ndocker build \"$@\" -f \"${ROOT_DIR}/api/docker/awslambda/Dockerfile\" \"${ROOT_DIR}/cli\" -t pcluster-lambda\n\necho\necho \"Use the following to run a shell in the container\"\necho \"  docker run -it --entrypoint /bin/bash pcluster-lambda\"\necho\necho \"Use the following to run a local AWS Lambda endpoint hosting the API\"\necho \"  docker run -e POWERTOOLS_TRACE_DISABLED=1 -e AWS_REGION=eu-west-1 -p 9000:8080 pcluster-lambda\"\necho \"Then you can use the following to send requests to the local endpoint\"\necho \"  curl -XPOST \\\"http://localhost:9000/2015-03-31/functions/function/invocations\\\" -d @${SCRIPT_DIR}/test-events/event.json\"\necho\necho \"Use the following to run a local Flask development server hosting the API\"\necho \"  docker run -p 8080:8080 --entrypoint python pcluster-lambda -m pcluster.api.flask_app\"\necho \"Then you can navigate to the following url to test the API: http://0.0.0.0:8080/ui\"\necho \"Note that to enable swagger-ui you have to build the docker with '--build-arg PROFILE=dev'\"\necho\necho \"Use the following command to push the built image to a public ECR repository\"\necho \"  aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws/<alias>/<repository-name>\"\necho \"  docker tag pcluster-lambda:latest public.ecr.aws/<alias>/<repository-name>:latest\"\necho \"  docker push public.ecr.aws/<alias>/<repository-name>:latest\"\n", "num_lines": 26}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at http://aws.amazon.com/apache2.0/\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nusage=\"$(basename \"$0\") [-h] --s3-bucket bucket-name --region aws-region [--stack-name name] [--enable-iam-admin true|false] [--create-api-user true|false])\"\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\n\nS3_BUCKET=\nSTACK_NAME=\"ParallelClusterApi\"\nENABLE_IAM_ADMIN=\"true\"\nCREATE_API_USER=\"false\"\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    -h)\n    echo \"$usage\" >&2\n    exit 1\n    ;;\n    --s3-bucket)\n    S3_BUCKET=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --region)\n    export AWS_DEFAULT_REGION=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --stack-name)\n    export STACK_NAME=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --enable-iam-admin)\n    export ENABLE_IAM_ADMIN=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --create-api-user)\n    export CREATE_API_USER=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --enable-fsx-s3-access)\n    export ENABLE_FSX_S3_ACCESS=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --fsx-s3-buckets)\n    export FSX_S3_BUCKETS=$2\n    shift # past argument\n    shift # past value\n    ;;\n    *)    # unknown option\n    echo \"$usage\" >&2\n    exit 1\n    ;;\nesac\ndone\n\nif [ -z \"${S3_BUCKET}\" ] || [ -z \"${AWS_DEFAULT_REGION}\" ] ; then\n    echo \"$usage\" >&2\n    exit 1\nfi\n\nACCOUNT_ID=$(aws sts get-caller-identity --query \"Account\" --output text)\nS3_UPLOAD_URI=\"s3://${S3_BUCKET}/api/ParallelCluster.openapi.yaml\"\nPOLICIES_S3_URI=\"s3://${S3_BUCKET}/stacks/parallelcluster-policies.yaml\"\nPOLICIES_TEMPLATE_URI=\"http://${S3_BUCKET}.s3.${AWS_DEFAULT_REGION}.amazonaws.com/stacks/parallelcluster-policies.yaml\"\n\necho \"Publishing OpenAPI specs to S3\"\naws s3 cp \"${SCRIPT_DIR}/../spec/openapi/ParallelCluster.openapi.yaml\" \"${S3_UPLOAD_URI}\"\n\necho \"Publishing policies CloudFormation stack to S3\"\naws s3 cp \"${SCRIPT_DIR}/../../cloudformation/policies/parallelcluster-policies.yaml\" \"${POLICIES_S3_URI}\"\n\necho \"Deploying API template\"\naws cloudformation deploy \\\n    --stack-name \"${STACK_NAME}\" \\\n    --template-file \"${SCRIPT_DIR}/parallelcluster-api.yaml\" \\\n    --s3-bucket \"${S3_BUCKET}\" \\\n    --s3-prefix \"api/\" \\\n    --parameter-overrides ApiDefinitionS3Uri=\"${S3_UPLOAD_URI}\" \\\n                          PoliciesTemplateUri=\"${POLICIES_TEMPLATE_URI}\" \\\n                          EnableIamAdminAccess=\"${ENABLE_IAM_ADMIN}\" CreateApiUserRole=\"${CREATE_API_USER}\" \\\n    --capabilities CAPABILITY_NAMED_IAM\n", "num_lines": 95}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nif ! command -v yq &> /dev/null\nthen\n    echo \"Please install yq: https://mikefarah.gitbook.io/yq/\"\n    echo \"   GO111MODULE=on go get github.com/mikefarah/yq/v4; export PATH=\\$PATH:~/go/bin\"\n    exit 1\nfi\npushd smithy && ../../gradlew build && popd\nGENERATED_JSON_PATH=\"smithy/build/smithyprojections/smithy/source/openapi/ParallelCluster.openapi.json\"\n./spec_overrides.sh \"$GENERATED_JSON_PATH\"\n# Convert json into yaml\nyq eval -P $GENERATED_JSON_PATH -o yaml > openapi/ParallelCluster.openapi.yaml\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nif ! command -v redoc-cli &> /dev/null\nthen\n    echo \"Please install redoc-cli: npm install -g redoc-cli\"\n    exit\nfi\ncd openapi\nredoc-cli bundle ParallelCluster.openapi.yaml -o ParallelCluster.openapi.redoc.html\necho \"Generated redoc bundle: spec/openapi/ParallelCluster.openapi.redoc.html\"\n", "num_lines": 12}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\ndocker run -p 8080:8080 -e URL=docs/ParallelCluster.openapi.yaml --name pcluster-swagger-ui -v \"$(pwd)/openapi\":/usr/share/nginx/html/docs/ swaggerapi/swagger-ui\n", "num_lines": 5}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nYAML_PATH=$1\nexport INDEX=\"$(yq '.paths[\"/v3/clusters/{clusterName}/logstreams\"].get.parameters.[] | select(.name == \"filters\") | path | .[-1]' \"$YAML_PATH\")\"\nyq e -i '.paths[\"/v3/clusters/{clusterName}/logstreams\"].get.parameters[env(INDEX)].style = \"spaceDelimited\"' \"$YAML_PATH\"\n", "num_lines": 7}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -eu\n\nretry() {\n    local loop=1\n    local max_retries=3\n    local retry_delays=5\n\n    set +e\n    while true; do\n        \"$@\" && break || {\n            if [[ ${loop} -le ${max_retries} ]]; then\n                echo \"Command ($*) failed. Retrying...\"\n                loop=$((loop+1))\n                sleep ${retry_delays}\n            else\n                echo \"Command ($*) failed after ${max_retries} attempts.\"\n                exit 1\n            fi\n        }\n    done\n    set -e\n}\n\nbuild_docker_image() {\n    local image=$1\n    echo \"Building image ${image}\"\n    if [ ! -f \"${image}/Dockerfile\" ]; then\n        echo \"Dockerfile not found for image ${image}. Exiting...\"\n        exit 1\n    fi\n    retry docker build --build-arg AWS_REGION=\"${AWS_REGION}\" -f \"${image}/Dockerfile\" -t \"${IMAGE_REPO_NAME}:${image}\" .\n}\n\nif [ -z \"${IMAGE}\" ]; then\n    echo \"No image to build specified. Building all images...\"\n    for file in $(find `pwd` -type f -name Dockerfile); do\n        IMAGE_TAG=$(dirname \"${file}\" | xargs basename)\n        build_docker_image \"${IMAGE_TAG}\"\n    done\nelse\n    build_docker_image \"${IMAGE}\"\nfi\n", "num_lines": 44}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -eu\n\npush_docker_image() {\n    local image=$1\n    echo \"Uploading image ${image}\"\n    local aws_domain=\"amazonaws.com\"\n    if [[ ${AWS_REGION} == cn-* ]]; then\n        aws_domain=\"amazonaws.com.cn\"\n    elif [[ ${AWS_REGION} == us-iso-* ]]; then\n        aws_domain=\"c2s.ic.gov\"\n    elif [[ ${AWS_REGION} == us-isob-* ]]; then\n        aws_domain=\"sc2s.sgov.gov\"\n    fi\n    docker tag \"${IMAGE_REPO_NAME}:${image}\" \"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.${aws_domain}/${IMAGE_REPO_NAME}:${image}\"\n    docker push \"${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.${aws_domain}/${IMAGE_REPO_NAME}:${image}\"\n}\n\nif [ -z \"${IMAGE}\" ]; then\n    for file in $(find `pwd` -type f -name Dockerfile); do\n        IMAGE_TAG=$(dirname \"${file}\" | xargs basename)\n        push_docker_image \"${IMAGE_TAG}\"\n    done\nelse\n    push_docker_image \"${IMAGE}\"\nfi\n", "num_lines": 27}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Job id: ${AWS_BATCH_JOB_ID}\"\necho \"Initializing the environment...\"\n\n# Starting ssh agents\necho \"Starting ssh agents...\"\neval $(ssh-agent -s) && ssh-add ${SSHDIR}/id_rsa\n/usr/sbin/sshd -f /root/.ssh/sshd_config -h /root/.ssh/ssh_host_rsa_key\n\n# mount nfs\necho \"Mounting /home...\"\n/parallelcluster/bin/mount_nfs.sh \"${PCLUSTER_HEAD_NODE_IP}\" \"/home\"\n\n# create if not exists hidden pcluster folder\nPCLUSTER_HIDDEN_FOLDER=\"/home/.pcluster/\"\nif [ ! -d \"${PCLUSTER_HIDDEN_FOLDER}\" ]; then\n  echo \"Creating ${PCLUSTER_HIDDEN_FOLDER}\"\n  mkdir \"${PCLUSTER_HIDDEN_FOLDER}\"\nfi\n\necho \"Mounting shared file system...\"\nebs_shared_dirs=$(echo \"${PCLUSTER_SHARED_DIRS}\" | tr \",\" \" \")\n\nfor ebs_shared_dir in ${ebs_shared_dirs}\ndo\n  if [[ ${ebs_shared_dir} != \"NONE\" ]]; then\n    # mount nfs\n    /parallelcluster/bin/mount_nfs.sh \"${PCLUSTER_HEAD_NODE_IP}\" \"${ebs_shared_dir}\"\n  fi\ndone\n\nebs_arr=($ebs_shared_dirs)\n\n# mount EFS via nfs\nIFS=',' read -r -a efs_ids <<< \"${PCLUSTER_EFS_FS_IDS}\"\nIFS=',' read -r -a efs_shared_dirs <<< \"${PCLUSTER_EFS_SHARED_DIRS}\"\nfor i in \"${!efs_ids[@]}\"; do\n  /parallelcluster/bin/mount_efs.sh \"${efs_ids[i]}\" \"${PCLUSTER_AWS_REGION}\" \"${efs_shared_dirs[i]}\"\ndone\n\n# mount RAID via nfs\nif [[ ${PCLUSTER_RAID_SHARED_DIR} != \"NONE\" ]]; then\n  /parallelcluster/bin/mount_nfs.sh \"${PCLUSTER_HEAD_NODE_IP}\" \"${PCLUSTER_RAID_SHARED_DIR}\"\nfi\n\n# create hostfile if mnp job\nif [ -n \"${AWS_BATCH_JOB_NUM_NODES}\" ]; then\n  /parallelcluster/bin/generate_hostfile.sh \"${PCLUSTER_HIDDEN_FOLDER}\" \"${HOME}\"\nfi\n\n# run the user's script\necho \"Starting the job...\"\nexec \"$@\"\n", "num_lines": 56}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy\n# of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Usage:\n#   generate_hostfile.sh <shared_dir> <destination_dir>\n\nusage() {\n    cat <<ENDUSAGE\nThis script generates a hostfile which contains the ip addresses of the compute nodes\n\nUSAGE:\ngenerate_hostfile <shared_dir> <destination_dir>\nshared_dir: Shared directory on which compute and head instances have agreed upon for reading and writing the ip addresses. Directory needs to exist. A temporary directory is created inside this directory\ndestination_dir: Directory where hostfile should reside. Directory needs to exist\nENDUSAGE\n\n}\n\nerror_exit_usage() {\n    echo \"Error executing script: $1\"\n    usage\n    exit 1\n}\n\nerror_exit() {\n    echo \"Error executing script: $1\"\n    exit 1\n}\n\n# Check that the arguments are valid\ncheck_arguments_valid() {\n    if [ -z \"${shared_dir}\" ]; then\n        error_exit_usage \"Shared directory is a required argument\"\n    fi\n\n    if [ -z \"${destination_dir}\" ]; then\n        error_exit_usage \"Destination directory is a required argument\"\n    fi\n\n    if [ ! -d \"${shared_dir}\" ]; then\n        error_exit \"Shared directory ${shared_dir} does not exist\"\n    fi\n\n    if [ ! -d \"${destination_dir}\" ]; then\n        error_exit \"Destination directory ${destination_dir} does not exist\"\n    fi\n}\n\n# Check that the necessary batch variables exist, else exit\ncheck_batch_env_variables_exist() {\n    if [[ -z \"${AWS_BATCH_JOB_NODE_INDEX}\" ]]; then\n        error_exit \"AWS_BATCH_JOB_NODE_INDEX is expected to exist but does not exist.\"\n    fi\n\n    if [[ -z \"${AWS_BATCH_JOB_MAIN_NODE_INDEX}\" ]]; then\n        error_exit \"AWS_BATCH_JOB_MAIN_NODE_INDEX is expected to exist but does not exist.\"\n    fi\n\n    if [[ -z \"${AWS_BATCH_JOB_NUM_NODES}\" ]]; then\n        error_exit \"AWS_BATCH_JOB_NUM_NODES is expected to exist but does not exist.\"\n    fi\n\n    if [[ -z \"${AWS_BATCH_JOB_ID}\" ]]; then\n        error_exit \"AWS_BATCH_JOB_ID is expected to exist but does not exist.\"\n    fi\n\n    if [[ -z \"${AWS_BATCH_JOB_ATTEMPT}\" ]]; then\n        error_exit \"AWS_BATCH_JOB_ATTEMPT is expected to exist but does not exist.\"\n    fi\n}\n\n# On the head node populate the hostfile with the ip addresses and available cores of the compute nodes\nread_compute_address() {\n    if [[ ! -f \"${destination_dir}/hostfile\" ]]; then\n        touch \"${destination_dir}/hostfile\"\n    fi\n\n    compute_nodes_read=0\n\n    while [[ \"${AWS_BATCH_JOB_NUM_NODES}\" -gt ${compute_nodes_read} ]]; do\n        for fullfile in \"${shared_dir_temp}\"/* ; do\n            file=$(basename \"${fullfile}\")\n            if [[ ${file} = \"*\" ]]; then\n                # No files found in ${shared_dir_temp} yet\n                break\n            fi\n\n            if ! [[ ${file} =~ ^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]; then\n                error_exit \"Matched filename not in expected format on head node: ${file}\"\n            fi\n\n            cat \"${fullfile}\" >> \"${destination_dir}/hostfile\"\n            rm -rf \"${fullfile}\"\n            (( compute_nodes_read += 1 ))\n        done\n        echo \"Detected ${compute_nodes_read}/${AWS_BATCH_JOB_NUM_NODES} compute nodes. Waiting for all compute nodes to start.\"\n        sleep 15\n    done\n\n    if [[ \"$(ls -A \"${shared_dir_temp}\")\" ]]; then\n        error_exit \"head node failed to read some of the ip addresses while generating the hostfile. Shared temp directory is not empty\"\n    elif [[ $(wc -l < \"${destination_dir}/hostfile\") -ne ${AWS_BATCH_JOB_NUM_NODES} ]]; then\n        error_exit \"The number of entries in hostfile is not equal to the AWS_BATCH_JOB_NUM_NODES\"\n    else\n        rmdir \"${shared_dir_temp}\"\n    fi\n}\n\n# Write a file in the shared dir with container ip address and available cores.\nwrite_node_info() {\n  ip_address=$(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)\n  if ! [[ ${ip_address} =~ ^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]; then\n    error_exit \"Matched IP Address not in expected format on compute node: ${ip_address}\"\n  fi\n  available_cores=$(nproc --all)\n  echo \"${ip_address} slots=${available_cores}\" > \"${shared_dir_temp}/${ip_address}\"\n}\n\n\nmain() {\n\n    if [ $# -ne 2 ]; then\n        error_exit_usage \"Wrong number of arguments provided\"\n    fi\n\n    # This is the shared directory on which compute and head instances have agreed upon for reading and writing the ip addresses\n    shared_dir=\"${1}\"\n    if [[ \"${shared_dir:0:1}\" != '/' ]]; then\n      shared_dir=\"/${shared_dir}\"\n    fi\n    destination_dir=${2}\n\n    check_arguments_valid\n    check_batch_env_variables_exist\n\n    # AWS_BATCH_JOB_ID is in the format job_id#node_id. Stripping #node_id.\n    shared_dir_temp=\"${shared_dir}/${AWS_BATCH_JOB_ID%#*}-${AWS_BATCH_JOB_ATTEMPT}\"\n\n    mkdir -p \"${shared_dir_temp}\"\n\n    write_node_info\n    # If it is the head inspect the shared directory for the hostfile list\n    if [[ \"${AWS_BATCH_JOB_NODE_INDEX}\" -eq  \"${AWS_BATCH_JOB_MAIN_NODE_INDEX}\" ]]; then\n        read_compute_address\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 161}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy\n# of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Usage:\n#   modify_china_yum_vars.sh <region>\n\nusage() {\n    cat <<ENDUSAGE\nThis script modifies yum repo variables so that the Amazon Linux 2 repo points to the region-specific URLs for China and Isolated regions.\nThe modification is only made if the cluster is running in a China or Isolated region.\n\nUSAGE:\nmodify_yum_vars.sh <region>\nregion: Region which cluster is running in\nENDUSAGE\n\n}\n\nerror_exit_usage() {\n    echo \"Error executing script: $1\"\n    usage\n    exit 1\n}\n\nmain() {\n\n    if [ $# -ne 1 ]; then\n        error_exit_usage \"Wrong number of arguments provided\"\n    fi\n\n    # Modify yum repo variables if cluster is running in a region with non default AWS domain.\n    local REGION=\"${1}\"\n    local AWS_DOMAIN=\"amazonaws.com\"\n    if [[ ${REGION} == cn-* ]]; then\n        AWS_DOMAIN=\"amazonaws.com.cn\"\n    elif [[ ${REGION} == us-iso-* ]]; then\n        AWS_DOMAIN=\"c2s.ic.gov\"\n    elif [[ ${REGION} == us-isob-* ]]; then\n        AWS_DOMAIN=\"sc2s.sgov.gov\"\n    fi\n    if [[ ${AWS_DOMAIN} != \"amazonaws.com\" ]]; then\n        echo \"amazonlinux-2-repos-${REGION}.s3\" > /etc/yum/vars/amazonlinux\n        echo \"${AWS_DOMAIN}\" > /etc/yum/vars/awsdomain\n        echo \"https\" > /etc/yum/vars/awsproto\n        echo \"${REGION}\" > /etc/yum/vars/awsregion\n    else\n        echo \"Not running in China or Isolated region. Skipping modification of yum variables.\"\n    fi\n}\n\nmain \"$@\"\n", "num_lines": 64}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy\n# of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Usage: mount_filesystem.sh efs_fs_id aws_region shared_dir\n\nerror_exit_usage() {\n    echo \"Error executing script: $1\"\n    usage\n    exit 1\n}\n\nerror_exit() {\n    echo \"Error executing script: $1\"\n    exit 1\n}\n\nusage() {\n    cat <<ENDUSAGE\n    This script mounts EFS filesystem on shared dir on the nodes in the batch job.\n    The shared directory will be created if it does not exist.\n\n    USAGE:\n    mount_nfs <efs_fs_id> <aws_region> <shared_dir>\n    efs_fs_id: if of EFS file system\n    aws_region: AWS region of the stack\n    shared_dir: directory for EFS file system to be mounted on. If directory doesn't exist on compute, will be created\nENDUSAGE\n}\n\n# Check that the arguments are valid\ncheck_arguments_valid(){\n    if [ -z \"${efs_fs_id}\" ]; then\n        error_exit_usage \"EFS FS Id is a required argument\"\n    fi\n\n    if [ -z \"${aws_region}\" ]; then\n        error_exit_usage \"AWS region is a required argument\"\n    fi\n\n    if [ -z \"${shared_dir}\" ]; then\n        error_exit_usage \"The directory to be shared via nfs is a required argument\"\n    fi\n}\n\n# mount nfs\nmount_nfs() {\n\n    error_message=$(rpcinfo &> /dev/null || rpcbind 2>&1)\n    if [[ $? -ne 0 ]]; then\n        error_exit \"Failed to run rpcbind with error_message: ${error_message}\"\n    fi\n\n    mkdir -p ${shared_dir}\n    error_message=$(mount -t nfs4 -o nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev \"${efs_dir}\" \"${shared_dir}\" 2>&1)\n    if [[ $? -ne 0 ]]; then\n        error_exit \"Failed to mount nfs volume from ${efs_dir} with error_message: ${error_message}\"\n    fi\n\n    # Check that the filesystem is mounted as appropriate\n    mount_line=$(mount | grep \"${efs_dir}\")\n    if [[ -z \"${mount_line}\" ]]; then\n        error_exit \"mount succeeded but nfs volume from ${efs_dir} was not mounted as expected\"\n    fi\n}\n\n\n# main function\nmain() {\n    efs_fs_id=${1}\n    aws_region=${2}\n    aws_domain=\"amazonaws.com\"\n    if [[ ${aws_region} == cn-* ]]; then\n        aws_domain=\"amazonaws.com.cn\"\n    elif [[ ${aws_region} == us-iso-* ]]; then\n        aws_domain=\"c2s.ic.gov\"\n    elif [[ ${aws_region} == us-isob-* ]]; then\n        aws_domain=\"sc2s.sgov.gov\"\n    fi\n    efs_dir=\"${efs_fs_id}.efs.${aws_region}.${aws_domain}:/\"\n    shared_dir=\"/${3}\"\n\n    check_arguments_valid\n    mount_nfs\n}\n\nmain \"$@\"\n", "num_lines": 99}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy\n# of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n# Usage: mount_filesystem.sh head_node_ip shared_dir\n\nerror_exit_usage() {\n    echo \"Error executing script: $1\"\n    usage\n    exit 1\n}\n\nerror_exit() {\n    echo \"Error executing script: $1\"\n    exit 1\n}\n\nusage() {\n    cat <<ENDUSAGE\nThis script mounts the shared dir from head node instance on the nodes in the batch job.\nThe shared directory will be created if it does not exist.\n\nUSAGE:\nmount_nfs <head_node_ip> <shared_dir>\nhead_node_ip: ip address of the main node\nshared_dir: directory from head node to be shared. If directory doesn't exist on compute, will be created\nENDUSAGE\n}\n\n# Check that the arguments are valid\ncheck_arguments_valid(){\n    if [ -z \"${head_node_ip}\" ]; then\n        error_exit_usage \"Head Node IP is a required argument\"\n    fi\n\n    if [ -z \"${shared_dir}\" ]; then\n        error_exit_usage \"The directory to be shared via nfs is a required argument\"\n    fi\n}\n\n# mount nfs\nmount_nfs() {\n\n    error_message=$(rpcinfo &> /dev/null || rpcbind 2>&1)\n    if [[ $? -ne 0 ]]; then\n        error_exit \"Failed to run rpcbind with error_message: ${error_message}\"\n    fi\n\n    mkdir -p ${shared_dir}\n    error_message=$(mount -t nfs -o hard,intr,noatime,_netdev \"${head_node_ip}\":\"${shared_dir}\" \"${shared_dir}\" 2>&1)\n    if [[ $? -ne 0 ]]; then\n        error_exit \"Failed to mount nfs volume from ${head_node_ip}:${shared_dir} with error_message: ${error_message}\"\n    fi\n\n    # Check that the filesystem is mounted as appropriate\n    mount_line=$(mount | grep \"${head_node_ip}:${shared_dir}\")\n    if [[ -z \"${mount_line}\" ]]; then\n        error_exit \"mount succeeded but nfs volume from ${head_node_ip}:${shared_dir} was not mounted as expected\"\n    fi\n}\n\n\n# main function\nmain() {\n    head_node_ip=${1}\n    shared_dir=${2}\n    if [[ \"${shared_dir:0:1}\" != '/' ]]; then\n      shared_dir=\"/${shared_dir}\"\n    fi\n\n    check_arguments_valid\n    mount_nfs\n}\n\nmain \"$@\"\n", "num_lines": 87}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "Content-Type: multipart/mixed; boundary=\"==BOUNDARY==\"\nMIME-Version: 1.0\n\n--==BOUNDARY==\nContent-Type: text/cloud-boothook; charset=\"us-ascii\"\nMIME-Version: 1.0\n\n#!/bin/bash -x\n\nwhich dnf 2>/dev/null; dnf=$?\nwhich yum 2>/dev/null; yum=$?\n\nif [ \"${!dnf}\" == \"0\" ]; then\n  echo \"proxy=${DnfProxy}\" >> /etc/dnf/dnf.conf\nelif [ \"${!yum}\" == \"0\" ]; then\n  echo \"proxy=${YumProxy}\" >> /etc/yum.conf\nelse\n  echo \"Not yum system\"\nfi\n\nwhich apt-get && echo \"Acquire::http::Proxy \\\"${AptProxy}\\\";\" >> /etc/apt/apt.conf || echo \"Not apt system\"\n\nproxy=${ProxyServer}\nif [ \"${!proxy}\" != \"NONE\" ]; then\n  proxy_host=$(echo \"${!proxy}\" | awk -F/ '{print $3}' | cut -d: -f1)\n  proxy_port=$(echo \"${!proxy}\" | awk -F/ '{print $3}' | cut -d: -f2)\n  echo -e \"[Boto]\\nproxy = ${!proxy_host}\\nproxy_port = ${!proxy_port}\\n\" >/etc/boto.cfg\n  cat >> /etc/profile.d/proxy.sh <<PROXY\nexport http_proxy=\"${!proxy}\"\nexport https_proxy=\"${!proxy}\"\nexport no_proxy=\"localhost,127.0.0.1,169.254.169.254\"\nexport HTTP_PROXY=\"${!proxy}\"\nexport HTTPS_PROXY=\"${!proxy}\"\nexport NO_PROXY=\"localhost,127.0.0.1,169.254.169.254\"\nPROXY\nfi\n\n--==BOUNDARY==\nContent-Type: text/cloud-config; charset=us-ascii\nMIME-Version: 1.0\n\nbootcmd:\n  # Disable multithreading using logic from https://aws.amazon.com/blogs/compute/disabling-intel-hyper-threading-technology-on-amazon-linux/\n  # thread_siblings_list contains a comma (,) or dash (-) separated list of CPU hardware threads within the same core as cpu\n  # e.g. 0-1 or 0,1\n  # cat /sys/devices/system/cpu/cpu*/topology/thread_siblings_list\n  #     | tr '-' ','       # convert hyphen (-) to comma (,), to account that some kernels and CPU architectures use a hyphen instead of a comma\n  #     | cut -s -d, -f2-  # split over comma (,) and take the right part\n  #     | tr ',' '\\n'      # convert remaining comma (,) into new lines\n  #     | sort -un         # sort and unique\n  - if [ \"${DisableMultiThreadingManually}\" = \"true\" ]; then for cpunum in $(cat /sys/devices/system/cpu/cpu*/topology/thread_siblings_list | tr '-' ',' | cut -s -d, -f2- | tr ',' '\\n' | sort -un); do echo 0 > /sys/devices/system/cpu/cpu$cpunum/online; done; fi\n\npackage_update: false\npackage_upgrade: false\nrepo_upgrade: none\n\ndatasource_list: [ Ec2, None ]\noutput:\n  all: \"| tee -a /var/log/cloud-init-output.log | logger -t user-data -s 2>/dev/console\"\nwrite_files:\n  - path: /tmp/dna.json\n    permissions: '0644'\n    owner: root:root\n    content: |\n      {\n        \"cluster\": {\n          \"cluster_name\": \"${ClusterName}\",\n          \"stack_name\": \"${AWS::StackName}\",\n          \"stack_arn\": \"${AWS::StackId}\",\n          \"enable_efa\": \"${EnableEfa}\",\n          \"raid_shared_dir\": \"${RAIDSharedDir}\",\n          \"raid_type\": \"${RAIDType}\",\n          \"base_os\": \"${BaseOS}\",\n          \"region\": \"${AWS::Region}\",\n          \"efs_fs_ids\": \"${EFSIds}\",\n          \"efs_shared_dirs\": \"${EFSSharedDirs}\",\n          \"efs_encryption_in_transits\": \"${EFSEncryptionInTransits}\",\n          \"efs_iam_authorizations\": \"${EFSIamAuthorizations}\",\n          \"fsx_fs_ids\": \"${FSXIds}\",\n          \"fsx_mount_names\": \"${FSXMountNames}\",\n          \"fsx_dns_names\": \"${FSXDNSNames}\",\n          \"fsx_volume_junction_paths\": \"${FSXVolumeJunctionPaths}\",\n          \"fsx_fs_types\": \"${FSXFileSystemTypes}\",\n          \"fsx_shared_dirs\": \"${FSXSharedDirs}\",\n          \"scheduler\": \"${Scheduler}\",\n          \"ephemeral_dir\": \"${EphemeralDir}\",\n          \"ebs_shared_dirs\": \"${EbsSharedDirs}\",\n          \"proxy\": \"${ProxyServer}\",\n          \"slurm_ddb_table\": \"${SlurmDynamoDBTable}\",\n          \"log_group_name\": \"${LogGroupName}\",\n          \"dns_domain\": \"${ClusterDNSDomain}\",\n          \"hosted_zone\": \"${ClusterHostedZone}\",\n          \"node_type\": \"ComputeFleet\",\n          \"cluster_user\": \"${OSUser}\",\n          \"enable_intel_hpc_platform\": \"${IntelHPCPlatform}\",\n          \"cw_logging_enabled\": \"${CWLoggingEnabled}\",\n          \"log_rotation_enabled\": \"${LogRotationEnabled}\",\n          \"scheduler_queue_name\": \"${QueueName}\",\n          \"scheduler_compute_resource_name\": \"${ComputeResourceName}\",\n          \"enable_efa_gdr\": \"${EnableEfaGdr}\",\n          \"custom_node_package\": \"${CustomNodePackage}\",\n          \"custom_awsbatchcli_package\": \"${CustomAwsBatchCliPackage}\",\n          \"use_private_hostname\": \"${UsePrivateHostname}\",\n          \"head_node_private_ip\": \"${HeadNodePrivateIp}\",\n          \"directory_service\": {\n            \"enabled\": \"${DirectoryServiceEnabled}\"\n          }\n        }\n      }\n  - path: /etc/chef/client.rb\n    permissions: '0644'\n    owner: root:root\n    content: cookbook_path ['/etc/chef/cookbooks']\n  - path: /tmp/extra.json\n    permissions: '0644'\n    owner: root:root\n    content: |\n      ${ExtraJson}\n  - path: /tmp/bootstrap.sh\n    permissions: '0744'\n    owner: root:root\n    content: |\n      #!/bin/bash -x\n\n      function error_exit\n      {\n        echo \"Bootstrap failed with error: $1\"\n        # wait logs flush before signaling the failure\n        sleep 10\n        # TODO: add possibility to override this behavior and keep the instance for debugging\n        shutdown -h now\n        exit 1\n      }\n      function vendor_cookbook\n      {\n        mkdir /tmp/cookbooks\n        cd /tmp/cookbooks\n        tar -xzf /etc/chef/aws-parallelcluster-cookbook.tgz\n        HOME_BAK=\"${!HOME}\"\n        export HOME=\"/tmp\"\n        for d in `ls /tmp/cookbooks`; do\n          cd /tmp/cookbooks/$d\n          LANG=en_US.UTF-8 /opt/cinc/embedded/bin/berks vendor /etc/chef/cookbooks --delete || error_exit 'Vendoring cookbook failed.'\n        done;\n        export HOME=\"${!HOME_BAK}\"\n      }\n\n      function publish_startup_time\n      {\n        start_time=$1\n        end_time=$2\n        # Only put the startup time data if the scheduler is slurm\n        slurm_node_path=/etc/parallelcluster/slurm_plugin/slurm_node_spec.json\n        if test -f \"$slurm_node_path\"; then\n            INSTANCE_ID=$(cat $slurm_node_path | jq -r .instance_id)\n            INSTANCE_TYPE=$(cat $slurm_node_path | jq -r .'compute.\"instance-type\"')\n            aws cloudwatch put-metric-data --namespace \"ParallelCluster\" --metric-name \"StartupTime\" --value $(($end_time-$start_time)) --dimensions \"InstanceID=${!INSTANCE_ID},InstanceType=${!INSTANCE_TYPE},ClusterName=${ClusterName}\" --region \"${AWS::Region}\"\n        fi\n      }\n\n      [ -f /etc/profile.d/proxy.sh ] && . /etc/profile.d/proxy.sh\n\n      # Configure AWS CLI using the expected overrides, if any.\n      [ -f /etc/profile.d/aws-cli-default-config.sh ] && . /etc/profile.d/aws-cli-default-config.sh\n\n      custom_cookbook=${CustomChefCookbook}\n      export _region=${AWS::Region}\n\n      s3_url=${AWS::URLSuffix}\n      if [ \"${!custom_cookbook}\" != \"NONE\" ]; then\n        if [[ \"${!custom_cookbook}\" =~ ^s3://([^/]*)(.*) ]]; then\n          # Set the socket connection timeout to 15s. Emperically, it seems like the actual\n          # timeout is 8x(cli-connect-timeout). i.e. if cli-connection-timeout is set to\n          # 60s, the call will timeout the connect attempt at 8m. Setting it to 15s, causes\n          # each attempt to take 240s, so 2m * 3 attempts will result in a failure after 6\n          # minutes.\n          S3API_RESULT=$(AWS_RETRY_MODE=standard aws s3api get-bucket-location --cli-connect-timeout 15 --bucket ${!BASH_REMATCH[1]} --region ${AWS::Region} 2>&1) || error_exit \"${!S3API_RESULT}\"\n          bucket_region=$(echo \"${!S3API_RESULT}\" | jq -r '.LocationConstraint')\n          if [[ \"${!bucket_region}\" == null ]]; then\n            bucket_region=\"us-east-1\"\n          fi\n          cookbook_url=$(aws s3 presign \"${!custom_cookbook}\" --region \"${!bucket_region}\")\n        else\n          cookbook_url=${!custom_cookbook}\n        fi\n      fi\n      export PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin\n      export parallelcluster_version=aws-parallelcluster-${ParallelClusterVersion}\n      export cookbook_version=${CookbookVersion}\n      export chef_version=${ChefVersion}\n      export berkshelf_version=${BerkshelfVersion}\n      if [ -f /opt/parallelcluster/.bootstrapped ]; then\n        installed_version=$(cat /opt/parallelcluster/.bootstrapped)\n        if [ \"${!cookbook_version}\" != \"${!installed_version}\" ]; then\n          cookbook_version_number=$(echo ${!cookbook_version} | awk -F- '{print $NF}')\n          installed_version_number=$(echo ${!installed_version} | awk -F- '{print $NF}')\n          error_exit \"This AMI was created with ParallelCluster ${!installed_version_number}, but is trying to be used with ParallelCluster ${!cookbook_version_number}. Please either use an AMI created with ParallelCluster ${!cookbook_version_number} or change your ParallelCluster to ${!installed_version_number}\"\n        fi\n      else\n        error_exit \"This AMI was not baked by ParallelCluster. Please use pcluster build-image command to create an AMI by providing your AMI as parent image.\"\n      fi\n      if [ \"${!custom_cookbook}\" != \"NONE\" ]; then\n        curl --retry 3 -v -L -o /etc/chef/aws-parallelcluster-cookbook.tgz ${!cookbook_url}\n        vendor_cookbook\n      fi\n      cd /tmp\n\n      mkdir -p /etc/chef/ohai/hints\n      touch /etc/chef/ohai/hints/ec2.json\n\n      # measure start time\n      start=$(date +%s)\n\n      jq --argfile f1 /tmp/dna.json --argfile f2 /tmp/extra.json -n '$f1 * $f2' > /etc/chef/dna.json || ( echo \"jq not installed or invalid extra_json\"; cp /tmp/dna.json /etc/chef/dna.json)\n      {\n        pushd /etc/chef &&\n        cinc-client --local-mode --config /etc/chef/client.rb --log_level info --force-formatter --no-color --chef-zero-port 8889 --json-attributes /etc/chef/dna.json --override-runlist aws-parallelcluster-entrypoints::init &&\n        /opt/parallelcluster/scripts/fetch_and_run -preinstall &&\n        cinc-client --local-mode --config /etc/chef/client.rb --log_level info --force-formatter --no-color --chef-zero-port 8889 --json-attributes /etc/chef/dna.json --override-runlist aws-parallelcluster-entrypoints::config &&\n        /opt/parallelcluster/scripts/fetch_and_run -postinstall &&\n        cinc-client --local-mode --config /etc/chef/client.rb --log_level info --force-formatter --no-color --chef-zero-port 8889 --json-attributes /etc/chef/dna.json --override-runlist aws-parallelcluster-entrypoints::finalize &&\n        popd\n      } || error_exit 'Failed to run bootstrap recipes. If --norollback was specified, check /var/log/cfn-init.log and /var/log/cloud-init-output.log.'\n\n      if [ ! -f /opt/parallelcluster/.bootstrapped ]; then\n        echo ${!cookbook_version} | tee /opt/parallelcluster/.bootstrapped\n      fi\n\n      # measure end time\n      end=$(date +%s)\n\n      if [ \"${ComputeStartupTimeMetricEnabled}\" = \"True\" ]; then\n        publish_startup_time $start $end || echo \"[WARNING] failed to push the StartupTime metric to CloudWatch.\"\n      fi\n\n--==BOUNDARY==\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\nMIME-Version: 1.0\n\n#!/bin/bash -x\n\nfunction error_exit\n{\n  echo \"Timed-out when bootstrapping instance\"\n  sleep 10  # Allow logs to propagate\n  shutdown -h now\n  exit 1\n}\n\nif [ \"${Timeout}\" == \"NONE\" ]; then\n  /tmp/bootstrap.sh\nelse\n  timeout ${Timeout} /tmp/bootstrap.sh || error_exit\nfi\n\n# End of file\n--==BOUNDARY==\n", "num_lines": 258}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "Content-Type: multipart/mixed; boundary=\"==BOUNDARY==\"\nMIME-Version: 1.0\n\n--==BOUNDARY==\nContent-Type: text/cloud-boothook; charset=\"us-ascii\"\nMIME-Version: 1.0\n\n#!/bin/bash -x\n\nwhich dnf 2>/dev/null; dnf=$?\nwhich yum 2>/dev/null; yum=$?\n\nif [ \"${!dnf}\" == \"0\" ]; then\n  echo \"proxy=${DnfProxy}\" >> /etc/dnf/dnf.conf\nelif [ \"${!yum}\" == \"0\" ]; then\n  echo \"proxy=${YumProxy}\" >> /etc/yum.conf\nelse\n  echo \"Not yum system\"\nfi\n\nwhich apt-get && echo \"Acquire::http::Proxy \\\"${AptProxy}\\\";\" >> /etc/apt/apt.conf || echo \"Not apt system\"\n\nproxy=${ProxyServer}\nif [ \"${!proxy}\" != \"NONE\" ]; then\n  proxy_host=$(echo \"${!proxy}\" | awk -F/ '{print $3}' | cut -d: -f1)\n  proxy_port=$(echo \"${!proxy}\" | awk -F/ '{print $3}' | cut -d: -f2)\n  echo -e \"[Boto]\\nproxy = ${!proxy_host}\\nproxy_port = ${!proxy_port}\\n\" >/etc/boto.cfg\n  cat >> /etc/profile.d/proxy.sh <<PROXY\nexport http_proxy=\"${!proxy}\"\nexport https_proxy=\"${!proxy}\"\nexport no_proxy=\"localhost,127.0.0.1,169.254.169.254\"\nexport HTTP_PROXY=\"${!proxy}\"\nexport HTTPS_PROXY=\"${!proxy}\"\nexport NO_PROXY=\"localhost,127.0.0.1,169.254.169.254\"\nPROXY\nfi\n\n--==BOUNDARY==\nContent-Type: text/cloud-config; charset=us-ascii\nMIME-Version: 1.0\n\nbootcmd:\n  # Disable multithreading using logic from https://aws.amazon.com/blogs/compute/disabling-intel-hyper-threading-technology-on-amazon-linux/\n  # thread_siblings_list contains a comma (,) or dash (-) separated list of CPU hardware threads within the same core as cpu\n  # e.g. 0-1 or 0,1\n  # cat /sys/devices/system/cpu/cpu*/topology/thread_siblings_list\n  #     | tr '-' ','       # convert hyphen (-) to comma (,), to account that some kernels and CPU architectures use a hyphen instead of a comma\n  #     | cut -s -d, -f2-  # split over comma (,) and take the right part\n  #     | tr ',' '\\n'      # convert remaining comma (,) into new lines\n  #     | sort -un         # sort and unique\n  - if [ \"${DisableMultiThreadingManually}\" = \"true\" ]; then for cpunum in $(cat /sys/devices/system/cpu/cpu*/topology/thread_siblings_list | tr '-' ',' | cut -s -d, -f2- | tr ',' '\\n' | sort -un); do echo 0 > /sys/devices/system/cpu/cpu$cpunum/online; done; fi\n\npackage_update: false\npackage_upgrade: false\nrepo_upgrade: none\n\ndatasource_list: [ Ec2, None ]\n\n--==BOUNDARY==\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\nMIME-Version: 1.0\n\n#!/bin/bash -x\n\nfunction error_exit\n{\n  # wait logs flush before signaling the failure\n  sleep 10\n  # trim the error message because there is a size limit of 4096 bytes for cfn-signal\n  # https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cloudformation-limits.html\n  cutoff=$(expr 4096 - $(stat --printf=\"%s\" /tmp/wait_condition_handle.txt))\n  reason=$(head --bytes=${!cutoff} /var/log/parallelcluster/bootstrap_error_msg 2>/dev/null) || reason=\"$1\"\n  cfn-signal --exit-code=1 --reason=\"${!reason}\" \"${!wait_condition_handle_presigned_url}\" --region ${AWS::Region} --url ${CloudFormationUrl}\n  exit 1\n}\nfunction vendor_cookbook\n{\n  mkdir /tmp/cookbooks\n  cd /tmp/cookbooks\n  tar -xzf /etc/chef/aws-parallelcluster-cookbook.tgz\n  HOME_BAK=\"${!HOME}\"\n  export HOME=\"/tmp\"\n  for d in `ls /tmp/cookbooks`; do\n    cd /tmp/cookbooks/$d\n    LANG=en_US.UTF-8 /opt/cinc/embedded/bin/berks vendor /etc/chef/cookbooks --delete || error_exit 'Vendoring cookbook failed.'\n  done;\n  export HOME=\"${!HOME_BAK}\"\n}\n[ -f /etc/profile.d/proxy.sh ] && . /etc/profile.d/proxy.sh\n\n# Configure AWS CLI using the expected overrides, if any.\n[ -f /etc/profile.d/aws-cli-default-config.sh ] && . /etc/profile.d/aws-cli-default-config.sh\n\n# deploy config files\nexport PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/aws/bin\n# Load ParallelCluster environment variables\n[ -f /etc/profile.d/pcluster.sh ] && . /etc/profile.d/pcluster.sh\n\ncd /tmp\ncfn-init -s ${AWS::StackName} -v -c deployFiles -r HeadNodeLaunchTemplate --region ${AWS::Region} --url ${CloudFormationUrl}\nwait_condition_handle_presigned_url=$(cat /tmp/wait_condition_handle.txt)\n\ncustom_cookbook=${CustomChefCookbook}\nexport _region=${AWS::Region}\ns3_url=${AWS::URLSuffix}\nif [ \"${!custom_cookbook}\" != \"NONE\" ]; then\n  if [[ \"${!custom_cookbook}\" =~ ^s3://([^/]*)(.*) ]]; then\n    bucket_region=$(aws s3api get-bucket-location --bucket ${!BASH_REMATCH[1]} --region ${AWS::Region} | jq -r '.LocationConstraint')\n    if [[ \"${!bucket_region}\" == null ]]; then\n      bucket_region=\"us-east-1\"\n    fi\n    cookbook_url=$(aws s3 presign \"${!custom_cookbook}\" --region \"${!bucket_region}\")\n  else\n    cookbook_url=${!custom_cookbook}\n  fi\nfi\nexport parallelcluster_version=aws-parallelcluster-${ParallelClusterVersion}\nexport cookbook_version=${CookbookVersion}\nexport chef_version=${ChefVersion}\nexport berkshelf_version=${BerkshelfVersion}\nif [ -f /opt/parallelcluster/.bootstrapped ]; then\n  installed_version=$(cat /opt/parallelcluster/.bootstrapped)\n  if [ \"${!cookbook_version}\" != \"${!installed_version}\" ]; then\n    cookbook_version_number=$(echo ${!cookbook_version} | awk -F- '{print $NF}')\n    installed_version_number=$(echo ${!installed_version} | awk -F- '{print $NF}')\n    error_exit \"This AMI was created with ${!installed_version_number}, but is trying to be used with ${!cookbook_version_number}. Please either use an AMI created with ${!cookbook_version_number} or change your ParallelCluster to ${!installed_version_number}\"\n  fi\nelse\n  error_exit \"This AMI was not baked by ParallelCluster. Please use pcluster build-image command to create an AMI by providing your AMI as parent image.\"\nfi\nif [ \"${!custom_cookbook}\" != \"NONE\" ]; then\n  curl --retry 3 -v -L -o /etc/chef/aws-parallelcluster-cookbook.tgz ${!cookbook_url}\n  vendor_cookbook\nfi\n\n# Call CloudFormation\ncfn-init -s ${AWS::StackName} -v -c default -r HeadNodeLaunchTemplate --region ${AWS::Region} --url ${CloudFormationUrl} || error_exit 'Failed to bootstrap the head node. Please check /var/log/cfn-init.log or /var/log/chef-client.log in the head node, or check the cfn-init.log or chef-client.log in CloudWatch logs. Please refer to https://docs.aws.amazon.com/parallelcluster/latest/ug/troubleshooting-v3.html#troubleshooting-v3-get-logs for more details on ParallelCluster logs.'\ncfn-signal --exit-code=0 --reason=\"HeadNode setup complete\" \"${!wait_condition_handle_presigned_url}\" --region ${AWS::Region} --url ${CloudFormationUrl}\n# End of file\n--==BOUNDARY==\n", "num_lines": 141}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Very basic first tests\n\nset -ex\necho $PATH\nwhich pcluster\npip check\npcluster version\npcluster --help\n", "num_lines": 10}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# shellcheck source=/dev/null\nsource /etc/parallelcluster/cfnconfig\nCLUSTER_NAME=\"${stack_name:?}\"\nAWS_DEFAULT_REGION=\"${cfn_region:?}\"\n\nNUM_COMPUTE_NODES=$(/opt/slurm/bin/sinfo --Node --noheader | awk '{print $1,$4}' | grep -cEv '(~|#|%)$')\naws cloudwatch put-metric-data \\\n    --region \"$AWS_DEFAULT_REGION\" \\\n    --namespace 'ParallelCluster/AdIntegration' \\\n    --metric-name 'ComputeNodeCount' \\\n    --dimensions \"ClusterName=${CLUSTER_NAME}\" \\\n    --value \"$NUM_COMPUTE_NODES\"", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# TODO: add efs\nfor fspath in shared efs; do\n    # srun has to be used for whoami because slurm_nss plugin only send user information through srun\n    date '+%Y%m%d%H%M%S' > \"/$fspath/$(srun whoami)\"\ndone\n\nBENCHMARK_NAME=osu_barrier\nOSU_BENCHMARK_VERSION=5.7.1\n\nmodule load openmpi\n# Run collective benchmark. The collective operations are close to what a real application looks like.\n# NOTE: The test is sized for 4 compute nodes.\n# -np total number of processes to run (all CPUs * 4 nodes)\nmpirun \\\n    > /shared/\"$(date '+%Y%m%d%H%M%S')-$(srun whoami)-${BENCHMARK_NAME}\".out \\\n    /shared/openmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/collective/${BENCHMARK_NAME}\n", "num_lines": 20}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"post-install script has $# arguments\"\nfor arg in \"$@\"\ndo\n    echo \"arg: ${arg}\"\ndone\n\ncase $# in\n    3)\n        exit 0\n    ;;\n    *)\n        exit 1\nesac\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"pre-install script has $# arguments\"\nfor arg in \"$@\"\ndo\n    echo \"arg: ${arg}\"\ndone\n\ncase $# in\n    3)\n        exit 0\n    ;;\n    *)\n        exit 1\nesac\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nexit 1\n", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\n# add debug mode\nsed -i '$s/}/,\\n\"agent\":{\"debug\": true}}/' /opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/file_amazon-cloudwatch-agent.json\n# restart cw agent\n/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a fetch-config -m ec2 -s -c file:/opt/aws/amazon-cloudwatch-agent/etc/amazon-cloudwatch-agent.d/file_amazon-cloudwatch-agent.json\n", "num_lines": 17}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nexit 1\n", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the\n# License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Requirements: sudo, user be able to become root without password, ethtool, netstat\n\n# Script to generate a system information archive.\n# This script needs to be run by a user in sudoers and it takes an existing directory as argument\n\nfunction log() {\n  local LEVEL=\"INFO\"\n  if [ \"${2}\" != \"\" ]; then\n    LEVEL=\"${2}\"\n  fi\n  echo \"$(date) - system-analyzer - ${LEVEL} - ${1}\"\n}\n\nfunction body() {\n  # Function to print the header passed in pipe and execute the argument\n  # example: cat file_with_header.csv | body sort > file_with_header_but_sorted_body.csv\n  IFS= read -r HEADER\n  printf '%s\\n' \"${HEADER}\"\n  \"${@}\"\n}\n\nfunction _copy_if_exists() {\n  if [ -e \"${1}\" ]; then\n    cp -r \"${1}\" \"${2}\"\n  else\n    log \"${1} do not exists\" \"WARNING\"\n  fi\n}\n\nfunction signal_handler() {\n  # arg 1: return code\n  # arg 2: line number of the error\n  # arg 3: temporary directory to remove\n\n  if [ \"${1}\" != \"0\" ]; then\n    log \"Catching a signal\" \"ERROR\"\n    rm -fr \"${BASE_TEMP_DIR}\"\n    log \"Return code:${1} occurred on line ${2} - Deleted ${3}\" \"ERROR\"\n    exit \"${1}\"\n  fi\n}\n\nfunction _save_installed_services_timers() {\n  log \"Save installed services and timer\"\n  local OUT_DIR=${1}\n\n  # Save installed services\n  systemctl --all --type=service --state running,active | head -n -7 | body sort -du > \"${OUT_DIR}\"/services_active\n  systemctl list-unit-files --state enabled,generated | head -n -2 | body sort -du > \"${OUT_DIR}\"/services_enabled\n\n  # Save timers\n  systemctl list-timers | head -n -3 | body sort -du > \"${OUT_DIR}\"/timers\n}\n\nfunction _save_scheduled_commands() {\n  log \"Save scheduled commands\"\n  local OUT_DIR=${1}\n  local OS=${2}\n  local OS_VERSION=${3}\n\n  # Save scheduled commands and scripts\n  mkdir \"${OUT_DIR}\"/etc_cron\n  mkdir \"${OUT_DIR}\"/spool_cron\n\n\n  _copy_if_exists /etc/cron* \"${OUT_DIR}\"/etc_cron\n  _copy_if_exists /var/spool/cron \"${OUT_DIR}\"/spool_cron\n\n  _copy_if_exists /etc/anacrontab \"${OUT_DIR}\"/etc_cron\n  _copy_if_exists /var/spool/anacron \"${OUT_DIR}\"/spool_cron\n\n  _copy_if_exists /var/spool/at \"${OUT_DIR}\"/spool_cron\n\n}\n\nfunction _network_info() {\n  log \"Save network information\"\n  local OUT_DIR=\"${1}/network/\"\n\n  # Save meaningful network statistic\n  mkdir \"${OUT_DIR}\"\n  for network in $(ip link | egrep \"^[0-9]+\" | awk -F\\: '{print $2}' | tr -d \" \" | grep -v \"lo\"); do\n    ethtool -S \"${network}\" > \"${OUT_DIR}\"/eth0_stats\n  done\n  netstat -s > \"${OUT_DIR}\"/netstat_stats\n  ip address > \"${OUT_DIR}\"/address\n}\n\nfunction _save_avail_mpi() {\n  log \"Save mpi versions\"\n  local OUT_DIR=\"${1}/mpi/\"\n\n  # Save available mpi\n  mkdir \"${OUT_DIR}\"\n  MODULES=\"$(echo \"${MODULEPATH}\" | tr : '\\n')\"\n  set +e +o pipefail\n  MPI_MODULES=$(for MODULE in $MODULES; do\n    ls -1 \"${MODULE}\" 2>/dev/null | grep -i mpi;\n    done)\n  set -e -o pipefail\n  for MPI_MODULE in $MPI_MODULES\n  do\n    module load \"${MPI_MODULE}\" 2>&1 1>/dev/null\n    mpirun --version > \"${OUT_DIR}\"/\"${MPI_MODULE}\"\n    module unload \"${MPI_MODULE}\" 2>&1 1>/dev/null\n  done\n}\n\nfunction _save_imds_info() {\n  log \"Save IMDSv2 information\"\n  # Misc IMDS info\n  TOKEN=\"$(curl -s -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\")\"\n  curl -s -H \"X-aws-ec2-metadata-token: ${TOKEN}\" http://169.254.169.254/latest/meta-data/ami-id > \"${TEMP_DIR}\"/ami-id\n  curl -s -H \"X-aws-ec2-metadata-token: ${TOKEN}\" http://169.254.169.254/latest/meta-data/instance-type > \"${TEMP_DIR}\"/instance-type\n  curl -s -H \"X-aws-ec2-metadata-token: ${TOKEN}\" http://169.254.169.254/latest/user-data > \"${TEMP_DIR}\"/user-data\n}\n\nfunction _is_user_root() {\n  [ \"${EUID:-$(id -u)}\" -eq 0 ]\n}\n\nfunction main() {\n\n  # Set switch to catch errors\n  set -e -o pipefail\n\n  # Check number of arguments\n  if [ $# -ne 1 ]; then\n    echo \"usage: ${0} [directory]\"\n    echo \"es. ${0} /tmp/\"\n    exit 1\n  fi\n\n  # Become root if not and re-execute the script itself\n  if ! _is_user_root; then\n    log \"Running the script as root\"\n    sudo bash --login ${0} ${1}\n    exit $?\n  fi\n\n  # Check if path exist\n  if [ -d \"${1}\" ]; then\n    log \"Directory ${1} exists.\"\n  else\n    log \"Directory ${1} does not exist - exiting\"\n    exit 1\n  fi\n\n  local RESULT_ARCHIVE=\"${1}/system-information.tar.gz\"\n\n  # temporary directory\n  local BASE_TEMP_DIR=\"$(mktemp -d)\"\n  local TEMP_DIR=\"${BASE_TEMP_DIR}/system-information/\"\n\n  # Register signal handling to clean the temporary directory in case of kill, kill -9, ctrl+c, error in the script\n  trap 'signal_handler ${?} ${LINENO} ${BASE_TEMP_DIR}' SIGINT SIGTERM SIGHUP INT ERR EXIT\n\n  log \"Create temporary directory\"\n  mkdir \"${TEMP_DIR}\"\n\n  # Find os type and select package command\n  local PACKAGE_REPORT_CMD=\"\"\n  local OS=\"$(grep \"^ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\n\n  case ${OS} in\n    ubuntu)\n      PACKAGE_REPORT_CMD=\"dpkg-query -l\"\n      ;;\n    amzn | centos | rhel)\n      PACKAGE_REPORT_CMD=\"rpm -qa\"\n      ;;\n    *)\n      echo \"Unrecognized system. Found /etc/os-release ID content: ${OS}\"\n      exit 1\n      ;;\n  esac\n\n  local OS_VERSION=\"$(grep \"^VERSION_ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\n\n  log \"Save OS type and version\"\n  echo \"${OS}\" > \"${TEMP_DIR}/os\"\n  echo \"${OS_VERSION}\" > \"${TEMP_DIR}/os_version\"\n\n  # Save uname\n  log \"Save uname\"\n  uname -a > \"${TEMP_DIR}/uname\"\n\n  # Save installed packages on system\n  log \"Save installed packages on system\"\n  ${PACKAGE_REPORT_CMD} | sort -du > \"${TEMP_DIR}\"/packages\n\n  _save_installed_services_timers \"${TEMP_DIR}\"\n\n  _save_scheduled_commands \"${TEMP_DIR}\" \"${OS}\" \"${OS_VERSION}\"\n\n  _save_avail_mpi \"${TEMP_DIR}\"\n\n  _network_info \"${TEMP_DIR}\"\n\n  _save_imds_info \"${TEMP_DIR}\"\n\n  # Save users info\n  log \"Save /etc/passwd content\"\n  cp /etc/passwd \"${TEMP_DIR}/passwd\"\n\n  # Create the archive\n  log \"Create the archive\"\n  rm -fr \"${RESULT_ARCHIVE}\"\n  cd \"${TEMP_DIR}/..\"\n  tar -czf \"${RESULT_ARCHIVE}\" \"system-information/\" 1>/dev/null\n  cd \"/\"\n  rm -fr \"${BASE_TEMP_DIR}\"\n  log \"DONE\"\n}\n\nlog \"START\"\nmain \"${@}\"", "num_lines": 230}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nrm -f /shared/mpi.out\nmodule load openmpi\nmpirun --map-by ppr:1:node --timeout 20 \"ring\" >> /shared/mpi.out\n", "num_lines": 7}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nMPI_VERSION=${1}\n\nOSU_BENCHMARKS_VERSION={{ osu_benchmark_version }}\nOSU_BENCHMARKS_PACKAGE_NAME=\"osu-micro-benchmarks-${OSU_BENCHMARKS_VERSION}\"\nOSU_BENCHMARKS_INSTALLATION_DIR=\"/shared/${MPI_VERSION}/${OSU_BENCHMARKS_PACKAGE_NAME}/\"\n\n# If the compilation directory already exists, skip the compilation.\n[ -d \"${OSU_BENCHMARKS_INSTALLATION_DIR}\" ] && exit 0\n\nmodule load ${MPI_VERSION}\nmkdir -p /shared/${MPI_VERSION}\n\n#wget --no-check-certificate http://mvapich.cse.ohio-state.edu/download/mvapich/${OSU_BENCHMARKS_PACKAGE_NAME}.tgz\ncp \"./${OSU_BENCHMARKS_PACKAGE_NAME}.tgz\" /shared/${MPI_VERSION}\ncd /shared/${MPI_VERSION}\ntar zxvf \"./${OSU_BENCHMARKS_PACKAGE_NAME}.tgz\"\n\n# Update config.guess and config.sub files to support ARM architecture.\ncd\ncp \"./config.guess\" \"${OSU_BENCHMARKS_INSTALLATION_DIR}\"\ncp \"./config.sub\" \"${OSU_BENCHMARKS_INSTALLATION_DIR}\"\n\n# Compile OSU benchmarks\ncd \"${OSU_BENCHMARKS_INSTALLATION_DIR}\"\n./configure CC=$(which mpicc) CXX=$(which mpicxx)\nmake\n", "num_lines": 30}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nBENCHMARK_NAME={{ benchmark_name }}\nOSU_BENCHMARK_VERSION={{ osu_benchmark_version }}\nNUM_OF_PROCESSES={{ num_of_processes }}\n\nmodule load intelmpi\nexport I_MPI_DEBUG=10\n\nenv\n\n# Run collective benchmark. The collective operations are close to what a real application looks like.\n# -np total number of processes to run (all vCPUs * N compute nodes), divided by 2 if multithreading is disabled\nmpirun -bootstrap=slurm -np ${NUM_OF_PROCESSES} /shared/intelmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/collective/${BENCHMARK_NAME} > /shared/${BENCHMARK_NAME}.out\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nBENCHMARK_NAME={{ benchmark_name }}\nOSU_BENCHMARK_VERSION={{ osu_benchmark_version }}\nNUM_OF_PROCESSES={{ num_of_processes }}\n\nmodule load openmpi\n\nenv\n\n# Run collective benchmark. The collective operations are close to what a real application looks like.\n# -np total number of processes to run (all vCPUs * N compute nodes), divided by 2 if multithreading is disabled\nmpirun -np ${NUM_OF_PROCESSES} /shared/openmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/collective/${BENCHMARK_NAME}  > /shared/${BENCHMARK_NAME}.out\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nmodule load openmpi\n\nBENCHMARK_NAME={{ benchmark_name }}\nOSU_BENCHMARK_VERSION={{ osu_benchmark_version }}\n\nenv\n\n# Run multiple bandwidth/message rate benchmark\n# NOTE: The test is sized for two P4d compute nodes.\n# -N: number of processes per node (48, 1 for each CPU)\n# -n total number of processes to run (96, all CPUs from 2 nodes)\n# -x FI_EFA_USE_DEVICE_RDMA=1 Enables RDMA support\nmpirun --mca btl_tcp_if_exclude lo -n 96 -N 48 -x FI_EFA_USE_DEVICE_RDMA=1 /shared/openmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/pt2pt/${BENCHMARK_NAME} > /shared/${BENCHMARK_NAME}.out\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nBENCHMARK_NAME={{ benchmark_name }}\nOSU_BENCHMARK_VERSION={{ osu_benchmark_version }}\n\nmodule load intelmpi\nexport I_MPI_DEBUG=10\n\nenv\n\nmpirun -bootstrap=slurm  -np 2 --map-by ppr:1:node /shared/intelmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/pt2pt/${BENCHMARK_NAME} > /shared/${BENCHMARK_NAME}.out\n", "num_lines": 13}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nBENCHMARK_NAME={{ benchmark_name }}\nOSU_BENCHMARK_VERSION={{ osu_benchmark_version }}\n\nmodule load openmpi\n\nenv\n\nmpirun -np 2 --map-by ppr:1:node /shared/openmpi/osu-micro-benchmarks-${OSU_BENCHMARK_VERSION}/mpi/pt2pt/${BENCHMARK_NAME} > /shared/${BENCHMARK_NAME}.out\n", "num_lines": 12}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"Test head node bootstrap error caused by OnNodeStart Script.\"\nexit 1\n\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nyum -y install vim\n", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\napt update -y\napt-get install -y nodejs", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\nCRASHDIR=/var/crash\n\n# There are no crash files if the directory doesn't exist\n[ -d ${CRASHDIR} ] || exit 0\n\n# Exit nonzero if there are any files\ncrash_files=\"$(ls -A ${CRASHDIR})\"\nif [ -n \"${crash_files}\" ]; then\n  echo \"Found crash files in ${CRASHDIR}: ${crash_files}\"\n  exit 1\nfi\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\nCRASHDIR=/var/crash\n\n# There are no crash files if the directory doesn't exist\n[ -d ${CRASHDIR} ] || exit 0\n\n# Exit nonzero if there are any files\ncrash_files=\"$(ls -A ${CRASHDIR})\"\nif [ -n \"${crash_files}\" ]; then\n  echo \"Found crash files in ${CRASHDIR}: ${crash_files}\"\n  exit 1\nfi\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nrm -rf /shared/${1}\n\nmodule load ${1}\nNCCL_BENCHMARKS_VERSION='2.10.0'\nNCCL_VERSION='2.7.8-1'\nOFI_NCCL_VERSION='1.1.1'\nMPI_HOME=$(which mpirun | awk -F '/bin' '{print $1}')\nNVCC_GENCODE=\"-gencode=arch=compute_80,code=sm_80\" # Arch for NVIDIA A100\n\nmkdir -p /shared/${1}\n\n# Install and build nccl from sources\ncd /shared/${1}\nwget https://github.com/NVIDIA/nccl/archive/v${NCCL_VERSION}.tar.gz\ntar zxvf \"v${NCCL_VERSION}.tar.gz\"\ncd nccl-${NCCL_VERSION}\nmake -j src.build NVCC_GENCODE=\"${NVCC_GENCODE}\"\n\n# Build nccl-tests\ncd /shared/${1}\nwget https://github.com/NVIDIA/nccl-tests/archive/v${NCCL_BENCHMARKS_VERSION}.tar.gz\ntar zxvf \"v${NCCL_BENCHMARKS_VERSION}.tar.gz\"\ncd \"nccl-tests-${NCCL_BENCHMARKS_VERSION}/\"\nNVCC_GENCODE=\"${NVCC_GENCODE}\" make MPI=1 MPI_HOME=${MPI_HOME} NCCL_HOME=/shared/${1}/nccl-${NCCL_VERSION}/build/\n\nwget https://github.com/aws/aws-ofi-nccl/archive/v${OFI_NCCL_VERSION}.tar.gz\ntar xvfz v${OFI_NCCL_VERSION}.tar.gz\ncd aws-ofi-nccl-${OFI_NCCL_VERSION}\n./autogen.sh\n./configure --with-libfabric=/opt/amazon/efa --with-cuda=/usr/local/cuda/targets/x86_64-linux/ --with-nccl=/shared/openmpi/nccl-${NCCL_VERSION}/build/ --with-mpi=${MPI_HOME} --prefix /shared/openmpi/ofi-plugin\nmake\nmake install\n", "num_lines": 36}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --nodes=2\n#SBATCH --exclusive\n#SBATCH --ntasks-per-node=8\n\n\nmodule load openmpi\nNCCL_VERSION='2.7.8-1'\nmpirun \\\n-x FI_PROVIDER=\"efa\" \\\n-x FI_EFA_USE_DEVICE_RDMA=1 \\\n-x LD_LIBRARY_PATH=/shared/openmpi/nccl-${NCCL_VERSION}/build/lib/:/shared/openmpi/ofi-plugin/lib/:$LD_LIBRARY_PATH \\\n-x RDMAV_FORK_SAFE=1 \\\n-x NCCL_ALGO=ring \\\n-x NCCL_DEBUG=WARNING \\\n-x NCCL_PROTO=simple \\\n--mca pml ^cm --mca btl tcp,self --mca btl_tcp_if_exclude lo,docker0 --bind-to none \\\n/shared/openmpi/nccl-tests-2.10.0/build/all_reduce_perf -b 8 -e 1G -f 2 -g 1 -c 1 -n 100 > /shared/nccl_tests.out\n", "num_lines": 19}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Installs Fabtests suite from GitHub.\n# Usage: install-fabtests.sh [FABTESTS_DIR]\n# Example: install-fabtests.sh /shared/fabtests\n\nFABTESTS_DIR=\"$1\"\n\nFABTESTS_REPO=\"https://github.com/ofiwg/libfabric.git\"\n# TODO We should target the release 1.16.0 instead of a commit.\n# We must fix this once that version will be released.\nFABTESTS_COMMIT=\"840a4a93ccf576b950dfd15d979cbf5f06e9c64b\"\nFABTESTS_SOURCES_DIR=\"$FABTESTS_DIR/sources\"\nLIBFABRIC_DIR=\"/opt/amazon/efa\"\nCUDA_DIR=\"/usr/local/cuda\"\n\necho \"[INFO] Installing Fabtests in $FABTESTS_DIR\"\nrm -rf $FABTESTS_DIR\nmkdir -p $FABTESTS_SOURCES_DIR\ncd $FABTESTS_SOURCES_DIR\ngit clone $FABTESTS_REPO\ncd libfabric\ngit reset --hard $FABTESTS_COMMIT\ncd fabtests\n./autogen.sh\n./configure --with-libfabric=$LIBFABRIC_DIR --with-cuda=$CUDA_DIR --prefix=$FABTESTS_DIR && make -j 32 && make install\npython3 -m pip install -r $FABTESTS_SOURCES_DIR/libfabric/fabtests/pytest/requirements.txt\npython3 -m pip install pyyaml # TODO This is required but it is missing in the above requirements.txt\necho \"[INFO] Fabtests installed in $FABTESTS_DIR\"", "num_lines": 30}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Executes Fabtests suite.\n# Usage: run-fabtests.sh [FABTESTS_DIR] [PID_FILE] [LOG_FILE] [REPORT_FILE] [COMPUTE_NODE_1] [COMPUTE_NODE_2] [TEST_CASES] [TEST_OPTIONS]\n# Example:\n# run-fabtests.sh \\\n# /shared/fabtests \\\n# /shared/fabtests/outputs/fabtests.pid \\\n# /shared/fabtests/outputs/fabtests.log \\\n# /shared/fabtests/outputs/fabtests.report \\\n# q1-st-g4dn8xl-efa-1 q1-st-g4dn8xl-efa-2 \\\n# rdm_tagged_bw,rdm_tagged_pingpong,runt \\\n# enable-gdr\n\nFABTESTS_DIR=\"$1\"\nPID_FILE=\"$2\"\nLOG_FILE=\"$3\"\nREPORT_FILE=\"$4\"\nCOMPUTE_NODE_1=\"$5\"\nCOMPUTE_NODE_2=\"$6\"\nTEST_CASES=\"$7\"\nTEST_OPTIONS=\"$8\"\n\necho \"[INFO] Starting Fabtests ($FABTESTS_DIR) using compute nodes $COMPUTE_NODE_1 and $COMPUTE_NODE_2: $TEST_CASES\"\necho \"[INFO] Fabtests will use the following test environment options: $TEST_OPTIONS\"\necho \"[INFO] Fabtests pid will be stored in $PID_FILE\"\necho \"[INFO] Fabtests logs will be stored in $LOG_FILE\"\necho \"[INFO] Fabtests report will be stored in $REPORT_FILE\"\n\nFABTESTS_BIN_DIR=\"$FABTESTS_DIR/bin\"\nFABTESTS_RUNNER=\"$FABTESTS_BIN_DIR/runfabtests.py\"\nFABTESTS_TIMEOUT=\"300\" # Timeout for each test\nCOMPUTE_IP_1=$(host $COMPUTE_NODE_1 | cut -d ' ' -f 4)\nCOMPUTE_IP_2=$(host $COMPUTE_NODE_2 | cut -d ' ' -f 4)\nTEST_EXPRESSION=${TEST_CASES//,/ or }\nTEST_ENVIRONMENT_OPTION=\"\"\n[[ \"$TEST_OPTIONS\" == *\"enable-gdr\"* ]] && TEST_ENVIRONMENT_OPTION=\"-E \\\"FI_EFA_USE_DEVICE_RDMA=1\\\"\"\n\nmkdir -p $(dirname $PID_FILE)\nmkdir -p $(dirname $LOG_FILE)\nmkdir -p $(dirname $REPORT_FILE)\n\npython3 $FABTESTS_RUNNER \\\n  -b efa \\\n  -p \"$FABTESTS_BIN_DIR\" \\\n  --expression \"$TEST_EXPRESSION\" \\\n  --timeout $FABTESTS_TIMEOUT \\\n  --junit-xml $REPORT_FILE \\\n  -v $TEST_ENVIRONMENT_OPTION $COMPUTE_IP_1 $COMPUTE_IP_2 > $LOG_FILE 2>&1 &\n\necho $! > $PID_FILE\n\necho \"[INFO] Fabtests launched\"", "num_lines": 54}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p $HOME/mock_health_checks\nsudo tee $HOME/mock_health_checks/gpu_health_check.sh > /dev/null <<EOT\n#!/bin/bash\nexit 1\nEOT\nsudo chmod +x $HOME/mock_health_checks/gpu_health_check.sh\n\nsudo sed -i '/managed_health_check_dir =/ s|\\/opt\\/slurm\\/etc\\/pcluster\\/\\.slurm_plugin\\/scripts\\/health_checks|'$HOME'\\/mock_health_checks|' /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\necho \"Mocked failing GPU Health Check\"\ncat /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\n", "num_lines": 13}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir -p $HOME/mock_health_checks\nsudo tee $HOME/mock_health_checks/gpu_health_check.sh > /dev/null <<EOT\n#!/bin/bash\nexit 0\nEOT\nsudo chmod +x $HOME/mock_health_checks/gpu_health_check.sh\n\nsudo sed -i '/managed_health_check_dir =/ s|\\/opt\\/slurm\\/etc\\/pcluster\\/\\.slurm_plugin\\/scripts\\/health_checks|'$HOME'\\/mock_health_checks|' /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\necho \"Mocked successful GPU Health Check\"\ncat /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\n", "num_lines": 13}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo sed -i '/managed_health_check_dir =/ s|'$HOME'\\/mock_health_checks|\\/opt\\/slurm\\/etc\\/pcluster\\/\\.slurm_plugin\\/scripts\\/health_checks|' /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\n\necho \"Health check configuration restored\"\ncat /opt/slurm/etc/pcluster/.slurm_plugin/scripts/conf/health_check_manager.conf\n", "num_lines": 7}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# These installation instructions come from the following URL:\n# https://software.intel.com/content/www/us/en/develop/documentation/cluster-checker-user-guide/top/installation.html#YUMINSTALL\n# To see the latest available versions:\n# $ repoquery --repofrompath=reponame,https://yum.repos.intel.com/clck/2019 --repoid=reponame -a\nset -e\n\nsudo rpm --import https://yum.repos.intel.com/intel-gpg-keys/GPG-PUB-KEY-INTEL-SW-PRODUCTS-2019.PUB\nsudo yum-config-manager --add-repo https://yum.repos.intel.com/clck/2019/setup/intel-clck-2019.repo\nsudo yum-config-manager --add-repo https://yum.repos.intel.com/clck-ext/2019/setup/intel-clck-ext-2019.repo\nsudo yum -y install intel-clck-2019.9-056", "num_lines": 11}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nsource /opt/intel/clck/2019.9/bin/clckvars.sh\nclck -f nodefile -F intel_hpc_platform_compat-hpc-2018.0", "num_lines": 5}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"This script can't stop, won't stop.\" 1>&2\nexit 1\n", "num_lines": 4}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --ntasks=2 --nodes=2\n\nset -e\n\nmodule load intelmpi\nsrun --mpi=pmi2 /shared/intelmpi/osu-micro-benchmarks-{{ osu_benchmark_version }}/mpi/pt2pt/osu_latency\nmpirun /shared/intelmpi/osu-micro-benchmarks-{{ osu_benchmark_version }}/mpi/pt2pt/osu_latency", "num_lines": 8}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --ntasks=2 --nodes=2\n\nset -e\n\nmodule load openmpi\nsrun --mpi=pmix /shared/openmpi/osu-micro-benchmarks-{{ osu_benchmark_version }}/mpi/pt2pt/osu_latency\nmpirun /shared/openmpi/osu-micro-benchmarks-{{ osu_benchmark_version }}/mpi/pt2pt/osu_latency\n", "num_lines": 9}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Pre-Install\"\n", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"custom_action script has $# arguments\"\nfor arg in \"$@\"\ndo\n    echo \"executing ${arg}\"\n    \"${arg}\" || echo \"failed to execute ${arg}\"\ndone\n", "num_lines": 9}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"custom_action script has $# arguments\"\nfor arg in \"$@\"\ndo\n    echo \"executing ${arg}\"\n    \"${arg}\" || echo \"failed to execute ${arg}\"\ndone\n", "num_lines": 9}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"--- id: $(id)\"\necho \"--- whoami: $(whoami)\"\necho \"--- hostname: $(hostname)\"\necho \"--- pwd: $(pwd)\"\necho \"--- PATH: $(echo ${PATH})\"\necho \"--- HOME: $(echo ${HOME})\"\n", "num_lines": 9}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction _log () {\n  echo \"$(date +\"%Y-%m-%dT%H-%M-%S\") [$1] $2\"\n}\n\nfunction log () {\n  _log \"INFO\" \"$1\"\n}\n\nfunction log_error () {\n  _log \"ERROR\" \"$1\"\n}\n\nfunction fail () {\n  log_error \"$1\"\n  exit 1\n}\n\nfunction download_asset () {\n  local s3_uri=\"$1\"\n  local local_file=\"$2\"\n  local permissions=\"$3\"\n\n  mkdir -p $(dirname \"${local_file}\")\n  aws s3 cp \"${s3_uri}\" \"${local_file}\"\n  chmod ${permissions} \"${local_file}\"\n}\n\nfunction cron_script () {\n  local cron_expression=\"$1\"\n  local script=\"$2\"\n  local log=\"$3\"\n\n  echo \"${cron_expression} ${script} > ${log} 2>&1\" >> \"/var/spool/cron/$(whoami)\"\n}\n\nfunction timestamp_millis () {\n  date +\"%s%3N\"\n}\n\nfunction timestamp_datetime () {\n  date +\"%Y-%m-%dT%H-%M-%S\"\n}\n\nfunction millis_to_date_time () {\n  date -d @${1::-3} +\"%Y-%m-%dT%H-%M-%S\"\n}\n\nfunction date_time_to_millis () {\n  date -d ${1} +\"%Y-%m-%dT%H-%M-%S\"\n}\n\nfunction get_instance_id () {\n  # This function uses IMDS to retrieve the instance id, so it can be used:\n  # 1. in the head node only if the function is executed by a super user or if IMDS secured is disabled\n  # 2. in a compute node, always as there is no IMDS lockdown in there\n  local imds_endpoint=\"http://169.254.169.254/latest\"\n  local imds_token=$(curl -X PUT \"${imds_endpoint}/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\" 2>/dev/null)\n\n  curl -H \"aws-ec2-metadata-token: ${imds_token}\" \"${imds_endpoint}/meta-data/instance-id\" 2>/dev/null\n}\n\nfunction wait_job_completion () {\n  local job_ids=$1\n  local sleep_seconds=$2\n  local expected_jobs_in_queue=0\n\n  while true; do\n    local jobs_in_queue=$(/opt/slurm/bin/squeue -h -j${job_ids} | wc -l)\n    log \"Current jobs in queue: ${jobs_in_queue}. Expected jobs in queue: ${expected_jobs_in_queue}\"\n    [ ${jobs_in_queue} == ${expected_jobs_in_queue} ] && break\n    log \"Sleeping ${sleep_seconds} seconds\"\n    sleep ${sleep_seconds}\n  done\n}\n\nfunction get_compute_fleet_running_nodes () {\n  local cluster_name=$1\n  local region=$2\n\n  /usr/local/bin/pcluster describe-cluster-instances --region ${region} --cluster-name \"${cluster_name}\" --query 'instances[].nodeType'  | grep -o ComputeNode  | wc -l\n}\n\nfunction terminate_compute_fleet () {\n    local cluster_name=$1\n    local region=$2\n\n    /usr/local/bin/pcluster delete-cluster-instances --region ${region} --cluster-name \"${cluster_name}\" --force true\n}\n\nfunction wait_compute_fleet () {\n  local cluster_name=$1\n  local region=$2\n  local expected_compute_nodes=$3\n  local sleep_seconds=$4\n\n  while true; do\n    local compute_nodes=$(get_compute_fleet_running_nodes ${cluster_name} ${region})\n    log \"Current compute nodes ${compute_nodes}. Expected compute nodes ${expected_compute_nodes}.\"\n    [ ${compute_nodes} == ${expected_compute_nodes} ] && break\n    log \"Sleeping ${sleep_seconds} seconds\"\n    sleep ${sleep_seconds}\n  done\n}\n\nfunction add_to_json () {\n  local key=$1\n  local value=$2\n  local json_file=$3\n\n  [[ ! -f ${json_file} ]] && echo \"{}\" > ${json_file}\n  echo $(jq \".${key} = \\\"${value}\\\"\" ${json_file}) > ${json_file}\n}\n\nfunction merge_json () {\n  local json_file_1=$1\n  local json_file_2=$2\n  local json_file_3=$3\n\n  echo $(jq --argfile f1 \"${json_file_1}\" --argfile f2 \"${json_file_2}\" -n '$f1 * $f2') > \"${json_file_3}\"\n}\n\nfunction get_sample_from_json () {\n  local key=\"$1\"\n  local files=\"$2\"\n\n  jq -n \"[inputs.${key}]\" ${files} | jq -r -c 'map(select(length > 0)) | join(\",\")'\n}\n\nfunction get_json_with_minimum () {\n  local key=\"$1\"\n  local files=\"$2\"\n\n  jq -n \"[inputs] | sort_by(.${key}) | .[0]\" ${files}\n}\n\nfunction get_json_with_maximum () {\n  local key=\"$1\"\n  local files=\"$2\"\n\n  jq -n \"[inputs] | sort_by(.${key}) | .[-1]\" ${files}\n}\n\nfunction get_min () {\n  python3 -c \"print(min([${1}]))\"\n}\n\nfunction get_max () {\n  python3 -c \"print(max([${1}]))\"\n}\n\nfunction get_avg () {\n  python3 -c \"from statistics import mean;print(mean([${1}]))\"\n}\n\nfunction get_std () {\n  python3 -c \"from statistics import stdev;print(stdev([${1}]))\"\n}\n\nfunction get_med () {\n  python3 -c \"from statistics import median;print(median([${1}]))\"\n}\n\nfunction get_prc () {\n  python3 -c \"from numpy import percentile;print(percentile([${1}], ${2}))\"\n}\n\nfunction get_circular_array_element () {\n  local position=${1}\n  shift\n  local array=(\"$@\")\n  local array_size=${#array[@]}\n  local index=$(( ${position} % ${array_size} ))\n\n  echo \"${array[@]:${index}:1}\"\n}\n\nfunction join_array_by {\n  local d=${1-} a=${2-}\n\n  if shift 2; then\n    printf %s \"$a\" \"${@/#/$d}\"\n  fi\n}\n\nfunction put_metric() {\n  local region=\"$1\"\n  local namespace=\"$2\"\n  local dimensions=\"$3\"\n  local metric_name=\"$4\"\n  local value=\"$5\"\n\n  aws cloudwatch put-metric-data \\\n      --region \"${region}\" \\\n      --namespace \"${namespace}\" \\\n      --dimensions \"${dimensions}\" \\\n      --metric-name \"${metric_name}\" \\\n      --value \"${value}\"\n}\n", "num_lines": 201}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n# Cluster variables\nsource /etc/parallelcluster/cfnconfig\nSHARED_DIR=\"$(echo $cfn_ebs_shared_dirs | cut -d ',' -f 1)\"\nCLUSTER_NAME=\"${stack_name:?}\"\nAWS_DEFAULT_REGION=\"${cfn_region:?}\"\n\n# Load libraries\nsource \"${SHARED_DIR}/assets/lib/functions.sh\"\n\nCW_NAMESPACE=\"ParallelCluster/PerformanceTests\"\nCW_DIMENSIONS=\"ClusterName=${CLUSTER_NAME}\"\nPCLUSTER=\"/usr/local/bin/pcluster\"\nSQUEUE=\"/opt/slurm/bin/squeue\"\n\nfunction publish_metric () {\n  local metric_name=\"$1\"\n  local metric_value=\"$2\"\n\n  put_metric ${AWS_DEFAULT_REGION} ${CW_NAMESPACE} \"${CW_DIMENSIONS}\" \"${metric_name}\" \"${metric_value}\"\n}\n\nlog \"Publishing metrics for cluster ${CLUSTER_NAME} in region ${AWS_DEFAULT_REGION} to CloudWatch namespace ${CW_NAMESPACE}\"\n\nNUM_COMPUTE_NODES=$(${PCLUSTER} describe-cluster-instances --region ${AWS_DEFAULT_REGION} --cluster-name \"$CLUSTER_NAME\" --query 'instances[].nodeType'  | grep -o ComputeNode  | wc -l)\npublish_metric \"ComputeNodeCount\" \"${NUM_COMPUTE_NODES}\"\n\nNUM_JOBS_QUEUED=$(${SQUEUE} -h | wc -l)\npublish_metric \"JobsQueuedCount\" \"${NUM_JOBS_QUEUED}\"\n\nNUM_JOBS_PENDING=$(${SQUEUE} -h -t configuring,pending | wc -l)\npublish_metric \"JobsPendingCount\" \"${NUM_JOBS_PENDING}\"\n\nNUM_JOBS_RUNNING=$(${SQUEUE} -h -t running | wc -l)\npublish_metric \"JobsRunningCount\" \"${NUM_JOBS_RUNNING}\"\n\nNUM_JOBS_FAILED=$(${SQUEUE} -h -t failed | wc -l)\npublish_metric \"JobsFailedCount\" \"${NUM_JOBS_FAILED}\"\n\nlog \"Published metrics for cluster ${CLUSTER_NAME} in region ${AWS_DEFAULT_REGION} to CloudWatch namespace ${CW_NAMESPACE}\"\n", "num_lines": 43}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Cluster variables\nsource /etc/parallelcluster/cfnconfig\nSHARED_DIR=\"$(echo $cfn_ebs_shared_dirs | cut -d ',' -f 1)\"\n\n# Load libraries\nFUNCTIONS_SCRIPT=\"${SHARED_DIR}/assets/lib/functions.sh\"\nsource \"${FUNCTIONS_SCRIPT}\"\n\n# Instance Details\nINSTANCE_ID=$(get_instance_id)\n\n# Monitoring\nINSTANCE_METRICS_DIR=\"${SHARED_DIR}/metrics/compute-nodes\"\nINSTANCE_METRICS_FILE=\"${INSTANCE_METRICS_DIR}/instance-${INSTANCE_ID}.json\"\nINSTANCE_METRICS_PRE_FILE=\"/local/parallelcluster/monitoring/instance-metrics.json\"\nmkdir -m 777 -p ${INSTANCE_METRICS_DIR}\n\n# Monitoring - PreInstall Metrics\ncp ${INSTANCE_METRICS_PRE_FILE} ${INSTANCE_METRICS_FILE}\n\n# Monitoring - Start Time (milliseconds)\nINSTANCE_START_TIME=$(date +\"%s%3N\")\nadd_to_json \"instancePostInstallTimestamp\" ${INSTANCE_START_TIME} ${INSTANCE_METRICS_FILE}\n\n# Monitoring - Up Time (seconds)\nINSTANCE_UPTIME=$(cat /proc/uptime | cut -d ' ' -f 1 | cut -d '.' -f 1)\nadd_to_json \"instancePostInstallUpTime\" ${INSTANCE_UPTIME} ${INSTANCE_METRICS_FILE}\n\n# Monitoring - InstanceId\nadd_to_json \"instanceId\" ${INSTANCE_ID} ${INSTANCE_METRICS_FILE}\n\nchmod 666 ${INSTANCE_METRICS_FILE}\n", "num_lines": 36}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Cluster variables\nsource /etc/parallelcluster/cfnconfig\nSHARED_DIR=\"$(echo $cfn_ebs_shared_dirs | cut -d ',' -f 1)\"\nCLUSTER_NAME=\"${stack_name:?}\"\nAWS_DEFAULT_REGION=\"${cfn_region:?}\"\n\n# Inputs\nS3_BUCKET_URI=\"${1}\"\n\n# Check inputs\n[ -z ${S3_BUCKET_URI} ] && echo \"$(date +\"%Y-%m-%dT%H-%M-%S\") [ERROR] 1st argument S3_BUCKET_URI must not be empty\" && exit 1\n\n# Load libraries\nFUNCTIONS_SCRIPT_S3=\"${S3_BUCKET_URI}/functions.sh\"\nFUNCTIONS_SCRIPT=\"${SHARED_DIR}/assets/lib/functions.sh\"\nmkdir -p $(dirname \"${FUNCTIONS_SCRIPT}\")\naws s3 cp \"${FUNCTIONS_SCRIPT_S3}\" \"${FUNCTIONS_SCRIPT}\"\nchmod 755 \"${FUNCTIONS_SCRIPT}\"\nsource \"${FUNCTIONS_SCRIPT}\"\n\n# Download - Scale Test Runner\nSCALE_TEST_SCRIPT_S3=\"${S3_BUCKET_URI}/run-scale-test.sh\"\nSCALE_TEST_SCRIPT=\"${SHARED_DIR}/assets/workloads/scale-test/run-scale-test.sh\"\ndownload_asset \"${SCALE_TEST_SCRIPT_S3}\" \"${SCALE_TEST_SCRIPT}\" 755\n\n# Download - Scale Test Job Wrapper\nSCALE_TEST_JOB_WRAPPER_SCRIPT_S3=\"${S3_BUCKET_URI}/scale-test-job-wrapper.sh\"\nSCALE_TEST_JOB_WRAPPER_SCRIPT=\"${SHARED_DIR}/assets/workloads/scale-test/scale-test-job-wrapper.sh\"\ndownload_asset \"${SCALE_TEST_JOB_WRAPPER_SCRIPT_S3}\" \"${SCALE_TEST_JOB_WRAPPER_SCRIPT}\" 755\n\n# Download - Script Env Info\nENV_INFO_SCRIPT_S3=\"${S3_BUCKET_URI}/env-info.sh\"\nENV_INFO_SCRIPT=\"${SHARED_DIR}/assets/workloads/env-info.sh\"\ndownload_asset \"${ENV_INFO_SCRIPT_S3}\" \"${ENV_INFO_SCRIPT}\" 755\n\n# Install AWS ParallelCluster\nrm -rf aws-parallelcluster\npip3 uninstall -y aws-parallelcluster openapi-spec-validator pyrsistent\npip3 install pyrsistent==0.16.0\ngit clone https://github.com/aws/aws-parallelcluster.git\npip3 install aws-parallelcluster/cli/\n\n# Install Python libraries\npip3 install numpy\n\n# Dashboard improvements\nDASHBOARD_WIDGETS_JSON_S3=\"${S3_BUCKET_URI}/cloudwatch-dashboard-widgets.json\"\nDASHBOARD_WIDGETS_JSON=\"${SHARED_DIR}/assets/monitoring/cloudwatch-dashboard-widgets.json\"\ndownload_asset \"${DASHBOARD_WIDGETS_JSON_S3}\" \"${DASHBOARD_WIDGETS_JSON}\" 755\n\nTEMP_DIR=$(mktemp -d -t pcluster-post-head-XXXXXXXXXX)\n\nCURRENT_DASHBOARD_JSON=\"${TEMP_DIR}/current-dashboard.json\"\nCURRENT_DASHBOARD=$(aws cloudwatch get-dashboard --region ${AWS_DEFAULT_REGION} --dashboard-name \"${CLUSTER_NAME}-${AWS_DEFAULT_REGION}\")\necho ${CURRENT_DASHBOARD} > \"${CURRENT_DASHBOARD_JSON}\"\n\nNEW_DASHBOARD_WIDGETS_JSON=\"${TEMP_DIR}/new-dashboard-widgets.json\"\nNEW_DASHBOARD_WIDGETS=$(cat ${DASHBOARD_WIDGETS_JSON})\nNEW_DASHBOARD_WIDGETS=${NEW_DASHBOARD_WIDGETS//INSERT_CLUSTER_NAME_HERE/${CLUSTER_NAME}}\nNEW_DASHBOARD_WIDGETS=${NEW_DASHBOARD_WIDGETS//INSERT_AWS_REGION_HERE/${AWS_DEFAULT_REGION}}\necho ${NEW_DASHBOARD_WIDGETS} > ${NEW_DASHBOARD_WIDGETS_JSON}\n\nFINAL_DASHBOARD_BODY_JSON=\"${TEMP_DIR}/final-dashboard-body.json\"\necho $(cat ${CURRENT_DASHBOARD_JSON} | jq -r '.DashboardBody' | jq --argfile f2 ${NEW_DASHBOARD_WIDGETS_JSON} '.widgets |= . + $f2.widgets') > ${FINAL_DASHBOARD_BODY_JSON}\naws cloudwatch put-dashboard --region ${AWS_DEFAULT_REGION} --dashboard-name \"${CLUSTER_NAME}-${AWS_DEFAULT_REGION}\" --dashboard-body \"$(cat ${FINAL_DASHBOARD_BODY_JSON})\"\n\n\n# TODO must complete dashboard enrichment\n\n# Metrics publishing\nMETRICS_PUBLISHER_SCRIPT_S3=\"${S3_BUCKET_URI}/metrics-publisher.sh\"\nMETRICS_PUBLISHER_SCRIPT=\"${SHARED_DIR}/assets/monitoring/metrics-publisher.sh\"\ndownload_asset \"${METRICS_PUBLISHER_SCRIPT_S3}\" \"${METRICS_PUBLISHER_SCRIPT}\" 755\ncron_script \"* * * * *\" \"${METRICS_PUBLISHER_SCRIPT}\" \"${METRICS_PUBLISHER_SCRIPT}.log\"\n", "num_lines": 78}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Monitoring\nINSTANCE_METRICS_FILE=\"/local/parallelcluster/monitoring/instance-metrics.json\"\nmkdir -p $(dirname \"${INSTANCE_METRICS_FILE}\")\necho \"{}\" > ${INSTANCE_METRICS_FILE}\n\n# Monitoring - Start Time (milliseconds)\nINSTANCE_START_TIME=$(date +\"%s%3N\")\necho $(jq \".instancePreInstallTimestamp = \\\"${INSTANCE_START_TIME}\\\"\" ${INSTANCE_METRICS_FILE}) > ${INSTANCE_METRICS_FILE}\n\n# Monitoring - Up Time (seconds)\nINSTANCE_UPTIME=$(cat /proc/uptime | cut -d ' ' -f 1 | cut -d '.' -f 1)\necho $(jq \".instancePreInstallUpTime = \\\"${INSTANCE_UPTIME}\\\"\" ${INSTANCE_METRICS_FILE}) > ${INSTANCE_METRICS_FILE}\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n# Usage: /shared/assets/workloads/scale-test/run-scale-test.sh [ITERATIONS] [JOBS_PER_ITERATION] [NUM_PROCESSES_PER_JOB] [JOB_USERS] [JOB_COMMAND] [OUTPUT_DIR] [OUTPUT_S3_URI]\n# Usage: /shared/assets/workloads/scale-test/run-scale-test.sh 3 5 4 ec2-user \"/shared/assets/workloads/env-info.sh ; sleep 30\" /shared/scale-tests/scale-test-$(date +\"%Y-%m-%dT%H-%M-%S\") s3://aws-parallelcluster-mgiacomo/scale-test/out\n# Usage: /shared/assets/workloads/scale-test/run-scale-test.sh 5 5 4 ec2-user,PclusterUser1,PclusterUser2 \"sleep 120\" /shared/scale-tests/scale-test-$(date +\"%Y-%m-%dT%H-%M-%S\") s3://aws-parallelcluster-mgiacomo/scale-test/out\n\n# Cluster variables\nsource /etc/parallelcluster/cfnconfig\nCLUSTER_NAME=\"${stack_name}\"\nAWS_DEFAULT_REGION=\"${cfn_region}\"\nSHARED_DIR=\"$(echo $cfn_ebs_shared_dirs | cut -d ',' -f 1)\"\n\n# Load libraries\nFUNCTIONS_SCRIPT=\"${SHARED_DIR}/assets/lib/functions.sh\"\nsource \"${FUNCTIONS_SCRIPT}\"\n\n# Functions\nfunction launch_job () {\n  local job_user=$1\n  local num_processes=$2\n  local job_wrapper_script=$3\n  local output_dir=$4\n  local job_command=$5\n\n  local sbatch_result=$(sudo -iu ${job_user} sbatch -n ${num_processes} \"${job_wrapper_script}\" \"${output_dir}\" \"${job_command}\")\n  local submission_line=$(echo $sbatch_result | grep \"Submitted batch job\")\n\n  [ -z $submission_line ] && fail \"Job submission failed\"\n\n  local job_id=$(echo $submission_line | cut -d ' ' -f 4)\n  echo $job_id\n}\n\n# Input\nITERATIONS=${1:-3}\nJOBS_PER_ITERATION=${2:-1}\nNUM_PROCESSES_PER_JOB=${3:-1}\nJOB_USERS=($(echo ${4:-$(whoami)} | tr \",\" \" \"))\nJOB_COMMAND=\"${5:-\"sleep 60\"}\"\nOUTPUT_DIR=${6:-\"${SHARED_DIR}/scale-tests/${CLUSTER_NAME}-$(timestamp_datetime)\"}\nOUTPUT_S3=${7}\n\n# Job Details\nJOB_WRAPPER_SCRIPT=\"${SHARED_DIR}/assets/workloads/scale-test/scale-test-job-wrapper.sh\"\n\n# Print Info\necho \"# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\"\necho \"# SCALE TEST\"\necho \"# - Iterations: ${ITERATIONS}\"\necho \"# - Jobs / Iteration: ${JOBS_PER_ITERATION}\"\necho \"# - Processes / Job: ${NUM_PROCESSES_PER_JOB}\"\necho \"# - Job Users:\" \"${JOB_USERS[@]}\"\necho \"# - Job Wrapper Script: ${JOB_WRAPPER_SCRIPT}\"\necho \"# - Job Command: ${JOB_COMMAND}\"\necho \"# - Test Output: ${OUTPUT_DIR}\"\necho \"# - Test Output S3: ${OUTPUT_S3}\"\necho \"# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\"\n\n# Init\nfor iteration in $(seq 1 ${ITERATIONS}); do\n  log \"Executing iteration ${iteration}/${ITERATIONS}\"\n\n  log \"Terminating compute fleet\"\n  terminate_compute_fleet ${CLUSTER_NAME} ${AWS_DEFAULT_REGION}\n\n  log \"Waiting for compute fleet down to 0 nodes (can take up to the configured idle scale-down time, default 10 minutes)\"\n  wait_compute_fleet ${CLUSTER_NAME} ${AWS_DEFAULT_REGION} 0 120\n\n  # Job Launch\n  JOB_IDS=()\n  for j in $(seq 1 ${JOBS_PER_ITERATION}); do\n    JOB_USER=$(get_circular_array_element $(( ${j} - 1 )) \"${JOB_USERS[@]}\")\n    log \"Submitting job ${j}/${JOBS_PER_ITERATION} for iteration ${iteration}/${ITERATIONS} as user ${JOB_USER}\"\n    JOB_ID=$(launch_job \"${JOB_USER}\" \"${NUM_PROCESSES_PER_JOB}\" \"${JOB_WRAPPER_SCRIPT}\" \"${OUTPUT_DIR}\" \"${JOB_COMMAND}\")\n    JOB_SUBMISSION_TIME_MILLIS=$(timestamp_millis)\n    JOB_METRICS_FILE=\"${OUTPUT_DIR}/job.${JOB_ID}.sample.json\"\n    mkdir -m 777 -p $(dirname ${JOB_METRICS_FILE})\n    echo \"{}\" > ${JOB_METRICS_FILE}\n    chmod 666 ${JOB_METRICS_FILE}\n\n    log \"Job ${JOB_ID} submitted at $(millis_to_date_time ${JOB_SUBMISSION_TIME_MILLIS}); metrics will be collected in ${JOB_METRICS_FILE}\"\n    add_to_json \"jobId\" ${JOB_ID} ${JOB_METRICS_FILE}\n    add_to_json \"user\" ${JOB_USER} ${JOB_METRICS_FILE}\n    add_to_json \"jobSubmissionTimestamp\" ${JOB_SUBMISSION_TIME_MILLIS} ${JOB_METRICS_FILE}\n    JOB_IDS+=(${JOB_ID})\n  done\n\n  # Waiting Jobs Completion\n  log \"Waiting for jobs completion:\" \"${JOB_IDS[@]}\"\n  wait_job_completion $(join_array_by \",\" \"${JOB_IDS[@]}\") 120\n\n  # Metrics\n  COMPUTE_NODES_METRICS=(\"instancePreInstallUpTime\" \"instancePostInstallUpTime\")\n  COMPUTE_NODES_METRICS_WITH_TIMESTAMPS=(${COMPUTE_NODES_METRICS[@]} \"instancePreInstallTimestamp\" \"instancePostInstallTimestamp\")\n  COMPUTE_NODES_METRICS_WITH_TIMESTAMPS_AND_INSTANCE_ID=(${COMPUTE_NODES_METRICS_WITH_TIMESTAMPS[@]} \"instanceId\")\n  JOB_METRICS=(\"jobRunTime\" \"jobWaitingTime\" \"jobWarmupLeaderNodeTime\" \"jobWarmupFirstNodeTime\" \"jobWarmupLastNodeTime\")\n\n  # Compute Nodes Sample\n  # instancePreInstallTimestamp, instancePreInstallUpTime, instancePostInstallTimestamp, instancePostInstallUpTime\n  COMPUTE_NODES_SAMPLE_FILE=\"${OUTPUT_DIR}/compute-nodes.${iteration}.sample.json\"\n  COMPUTE_NODES_METRICS_DIR=\"${SHARED_DIR}/metrics/compute-nodes\"\n  COMPUTE_NODES_METRICS_FILES=$(find ${COMPUTE_NODES_METRICS_DIR} -type f -name \"instance-*.json\")\n  for metric in \"${COMPUTE_NODES_METRICS_WITH_TIMESTAMPS[@]}\"; do\n    add_to_json \"${metric}Sample\" $(get_sample_from_json \"${metric}\" \"${COMPUTE_NODES_METRICS_FILES}\") ${COMPUTE_NODES_SAMPLE_FILE}\n  done\n\n  for JOB_ID in \"${JOB_IDS[@]}\"; do\n    JOB_METRICS_FILE=\"${OUTPUT_DIR}/job.${JOB_ID}.sample.json\"\n    # Compute Nodes metrics\n    # firstComputeNode timings, i.e. time metrics from the first launched compute node\n    FIRST_COMPUTE_NODE_METRICS=$(get_json_with_minimum \"instancePreInstallTimestamp\" \"${COMPUTE_NODES_METRICS_FILES}\")\n    for metric in \"${COMPUTE_NODES_METRICS_WITH_TIMESTAMPS_AND_INSTANCE_ID[@]}\"; do\n      add_to_json \"firstComputeNode.${metric}\" \"$(echo ${FIRST_COMPUTE_NODE_METRICS} | jq -r \".${metric}\")\" ${JOB_METRICS_FILE}\n    done\n    # lastComputeNode timings, i.e. time metrics from the last launched compute node\n    LAST_COMPUTE_NODE_METRICS=$(get_json_with_maximum \"instancePreInstallTimestamp\" \"${COMPUTE_NODES_METRICS_FILES}\")\n    for metric in \"${COMPUTE_NODES_METRICS_WITH_TIMESTAMPS_AND_INSTANCE_ID[@]}\"; do\n      add_to_json \"lastComputeNode.${metric}\" \"$(echo ${LAST_COMPUTE_NODE_METRICS} | jq -r \".${metric}\")\" ${JOB_METRICS_FILE}\n    done\n\n    # Derived Metrics: jobRunTime = jobEndTimestamp - jobStartTimestamp\n    JOB_RUN_TIME_MILLIS=$(cat ${JOB_METRICS_FILE} | jq '(.jobEndTimestamp|tonumber) - (.jobStartTimestamp|tonumber)')\n    add_to_json \"jobRunTime\" ${JOB_RUN_TIME_MILLIS} ${JOB_METRICS_FILE}\n\n    # Derived Metrics: jobWaitingTime = jobStartTimestamp - jobSubmissionTimestamp\n    JOB_WAITING_TIME_MILLIS=$(cat ${JOB_METRICS_FILE} | jq '(.jobStartTimestamp|tonumber) - (.jobSubmissionTimestamp|tonumber)')\n    add_to_json \"jobWaitingTime\" ${JOB_WAITING_TIME_MILLIS} ${JOB_METRICS_FILE}\n\n    # Derived Metrics: jobWarmupLeaderNodeTime = jobStartTimestamp - leaderComputeNode.instancePreInstallTimestamp\n    JOB_WARMUP_LEADER_NODE_TIME_MILLIS=$(cat ${JOB_METRICS_FILE} | jq '(.jobStartTimestamp|tonumber) - (.leaderComputeNode.instancePreInstallTimestamp|tonumber)')\n    add_to_json \"jobWarmupLeaderNodeTime\" ${JOB_WARMUP_LEADER_NODE_TIME_MILLIS} ${JOB_METRICS_FILE}\n\n    # Derived Metrics: jobWarmupFirstNodeTime = jobStartTimestamp - firstComputeNode.instancePreInstallTimestamp\n    JOB_WARMUP_FIRST_NODE_TIME_MILLIS=$(cat ${JOB_METRICS_FILE} | jq '(.jobStartTimestamp|tonumber) - (.firstComputeNode.instancePreInstallTimestamp|tonumber)')\n    add_to_json \"jobWarmupFirstNodeTime\" ${JOB_WARMUP_FIRST_NODE_TIME_MILLIS} ${JOB_METRICS_FILE}\n\n    # Derived Metrics: jobWarmupLastNodeTime = jobStartTimestamp - lastComputeNode.instancePreInstallTimestamp\n    JOB_WARMUP_LAST_NODE_TIME_MILLIS=$(cat ${JOB_METRICS_FILE} | jq '(.jobStartTimestamp|tonumber) - (.lastComputeNode.instancePreInstallTimestamp|tonumber)')\n    add_to_json \"jobWarmupLastNodeTime\" ${JOB_WARMUP_LAST_NODE_TIME_MILLIS} ${JOB_METRICS_FILE}\n  done\n\n  # Cleanup\n  rm -rf ${COMPUTE_NODES_METRICS_FILES}\n\n  # Finalize\n  log \"Iteration ${iteration}/${ITERATIONS} completed: job metrics in ${JOB_METRICS_FILE}\"\n  log \"Waiting 60 seconds before the next iteration\"\n  sleep 60\n  log \"Terminating compute fleet\"\n  terminate_compute_fleet ${CLUSTER_NAME} ${AWS_DEFAULT_REGION}\ndone\n\n# Samples\nlog \"Generating samples\"\nSAMPLES_FILE=\"${OUTPUT_DIR}/samples.json\"\nJOBS_SAMPLE_FILES=$(find ${OUTPUT_DIR} -type f -name \"job.*.sample.json\")\nfor metric in \"${JOB_METRICS[@]}\"; do\n  add_to_json \"${metric}Sample\" $(get_sample_from_json \"${metric}\" \"${JOBS_SAMPLE_FILES}\") ${SAMPLES_FILE}\ndone\nCOMPUTE_NODES_SAMPLE_FILES=$(find ${OUTPUT_DIR} -type f -name \"compute-nodes.*.sample.json\")\nfor metric in \"${COMPUTE_NODES_METRICS[@]}\"; do\n  add_to_json \"${metric}Sample\" $(get_sample_from_json \"${metric}Sample\" \"${COMPUTE_NODES_SAMPLE_FILES}\") ${SAMPLES_FILE}\ndone\n\n# Statistics\nlog \"Generating statistics\"\nSTATISTICS_FILE=\"${OUTPUT_DIR}/statistics.json\"\nSTATISTICS_METRICS=(${JOB_METRICS[@]} ${COMPUTE_NODES_METRICS[@]})\nfor metric in \"${STATISTICS_METRICS[@]}\"; do\n  add_to_json \"${metric}.min\" $(get_min \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\") ${STATISTICS_FILE}\n  add_to_json \"${metric}.max\" $(get_max \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\") ${STATISTICS_FILE}\n  add_to_json \"${metric}.avg\" $(get_avg \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\") ${STATISTICS_FILE}\n  add_to_json \"${metric}.std\" $(get_std \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\") ${STATISTICS_FILE}\n  add_to_json \"${metric}.med\" $(get_med \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\") ${STATISTICS_FILE}\n  add_to_json \"${metric}.prc25\" $(get_prc \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\" 25) ${STATISTICS_FILE}\n  add_to_json \"${metric}.prc75\" $(get_prc \"$(cat ${SAMPLES_FILE} | jq -r \".${metric}Sample\")\" 75) ${STATISTICS_FILE}\ndone\n\n# End\nlog \"Scale test completed: samples in ${SAMPLES_FILE}, statistics in ${STATISTICS_FILE}\"\n\n# Upload samples and statistics on S3\nif [[ -z ${OUTPUT_S3} ]]; then\n  log \"Skipping upload on S3 as no OUTPUT_S3 has been specified\"\nelse\n  aws s3 cp --recursive ${OUTPUT_DIR} ${OUTPUT_S3}\n  log \"Results published to ${OUTPUT_S3}\"\nfi\n", "num_lines": 190}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# To submit this job, run:\n# sbatch -n 16 /shared/assets/workloads/scale-test/scale-test-job-wrapper.sh [OUTPUT_DIR] [JOB_COMMAND]\n# sbatch -n 16 /shared/assets/workloads/scale-test/scale-test-job-wrapper.sh /shared/scale-tests/scale-test-$(date +\"%Y-%m-%dT%H-%M-%S\") \"/shared/assets/workloads/env-info.sh ; sleep 60\"\n# sbatch -n 16 /shared/assets/workloads/scale-test/scale-test-job-wrapper.sh /shared/scale-tests/scale-test-$(date +\"%Y-%m-%dT%H-%M-%S\") \"sleep 120\"\n#\n# Note: 16 processes = 4 compute nodes c5.xlarge having 4 vCPUs each\n\n# Cluster variables\nsource /etc/parallelcluster/cfnconfig\nSHARED_DIR=\"$(echo $cfn_ebs_shared_dirs | cut -d ',' -f 1)\"\n\n# Load libraries\nFUNCTIONS_SCRIPT=\"${SHARED_DIR}/assets/lib/functions.sh\"\nsource \"${FUNCTIONS_SCRIPT}\"\n\n# Input\nOUTPUT_DIR=\"${1}\"\nJOB_COMMAND=\"${2:-\"sleep 60\"}\"\n\n# Scale Test - Directories and Files\nJOB_METRICS_FILE=\"${OUTPUT_DIR}/job.${SLURM_JOB_ID}.sample.json\"\nmkdir -m 777 -p $(dirname ${JOB_METRICS_FILE})\n\n# Scale Test - Instance Info\nINSTANCE_ID=$(get_instance_id)\nINSTANCE_METRICS_FILE=\"${SHARED_DIR}/metrics/compute-nodes/instance-${INSTANCE_ID}.json\"\nfor metric in \"instancePreInstallTimestamp\" \"instancePreInstallUpTime\" \"instancePostInstallTimestamp\" \"instancePostInstallUpTime\" \"instanceId\"; do\n  add_to_json \"leaderComputeNode.${metric}\" \"$(cat ${INSTANCE_METRICS_FILE} | jq -r \".${metric}\")\" ${JOB_METRICS_FILE}\ndone\n\n# Scale Test - Job Info\nadd_to_json \"processes\" ${SLURM_NPROCS} ${JOB_METRICS_FILE}\n\n# Scale Test - Job Start Time\nJOB_START_TIME_MILLIS=$(timestamp_millis)\nadd_to_json \"jobStartTimestamp\" ${JOB_START_TIME_MILLIS} ${JOB_METRICS_FILE}\n\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n# Job Command\nbash -c \"${JOB_COMMAND}\"\n# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #\n\n# Scale Test - Job End Time\nJOB_END_TIME_MILLIS=$(timestamp_millis)\nadd_to_json \"jobEndTimestamp\" ${JOB_END_TIME_MILLIS} ${JOB_METRICS_FILE}\n", "num_lines": 49}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\n. /etc/os-release\nrelease=\"${ID}${VERSION_ID:+.${VERSION_ID}}\"\n\nif [ `echo ${release} | grep '^centos\\.7'` ]; then\n  sudo yum remove -y epel-release\n\n  sudo yum repolist | grep epel\n\n  if [ $? -eq 0 ]; then\n      echo \"epel installed\"\n      exit 1\n  fi\nelif [ `echo \"${release}\" | grep '^centos\\.8'` ]; then\n  sudo dnf remove -y epel-release\n\n  sudo dnf repolist | grep epel\n\n  if [ $? -eq 0 ]; then\n      echo \"epel not removed\"\n      exit 1\n  fi\nfi", "num_lines": 25}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\n. /etc/os-release\nrelease=\"${ID}${VERSION_ID:+.${VERSION_ID}}\"\n\nif [ `echo ${release} | grep '^centos\\.7'` ]; then\n  sudo yum repolist | grep epel\n\n  if [ $? -ne 0 ]; then\n      echo \"epel not installed\"\n      exit 1\n  fi\nelif [ `echo \"${release}\" | grep '^centos\\.8'` ]; then\n  sudo dnf repolist | grep epel\n\n  if [ $? -ne 0 ]; then\n      echo \"epel not installed\"\n      exit 1\n  fi\nfi", "num_lines": 21}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n_openmpi_module=$1\n_remote_host=$2\n\nmodule load ${_openmpi_module}\n$(which mpirun) --host ${_remote_host} hostname\n", "num_lines": 9}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2018      Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy\n# of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n#\n#\n# Script executed on clusters from parallelcluster-release-check.py.  This\n# script attempts to submit two jobs which must complete in 10\n# minutes, one of which (hopefully) requires scaling.\n#\n\n# Usage:\n#   cluster-check.sh {submit | scaledown_check} <scheduler>\n#\nset -e\n\nslurm_get_slots() {\n    local -- ppn i=0\n    ppn=$(scontrol show nodes -o | head -n 1 | sed -n -e 's/^.* CPUTot=\\([0-9]\\+\\) .*$/\\1/p')\n    # wait 15 secs before giving up retrieving the slots per host\n    while [ -z \"${ppn}\" -a $i -lt 15 ]; do\n        sleep 1\n        i=$((i+1))\n        ppn=$(scontrol show nodes -o | head -n 1 | sed -n -e 's/^.* CPUTot=\\([0-9]\\+\\) .*$/\\1/p')\n    done\n\n    echo ${ppn}\n}\n\nsubmit_launch() {\n    # in case the scheduler goes nuts, wrap ourselves in a timeout so\n    # there's a bounded completion time\n    if test \"$CHECK_CLUSTER_SUBPROCESS\" = \"\"; then\n        export CHECK_CLUSTER_SUBPROCESS=1\n        timeout -s KILL 9m /bin/bash ./cluster-check.sh \"$@\"\n        exit $?\n    fi\n\n    scheduler=\"$2\"\n\n    echo \"--> scheduler: $scheduler\"\n\n    submit_init ${scheduler}\n\n    echo \"$(date +%s)\" > jobs_start_time\n\n    ${scheduler}_submit\n    echo \"Jobs submitted successfully\"\n}\n\nsubmit_init() {\n    # we submit 3 1-node jobs, each of which are a sleep.\n    # The whole thing has to run in 9 minutes (higher of the three sleep times + buffer),\n    # or the kill in submit_launch will fail the job, which means that the jobs must run at the same time.\n    # The initial cluster is 1 nodes, so we'll need to scale up 2 further nodes simultaneously\n    # and bootstrap in less than 7 minutes and run the job that needs 105 seconds\n    # in order for the test to succeed.\n\n    # job1: 7m45s\n    export _sleepjob1=465\n    # job2: 1m45s\n    export _sleepjob2=105\n    # job3: 1m45s\n    export _sleepjob3=105\n\n    scheduler=$1\n    export _ppn=$(${scheduler}_get_slots)\n    if [ -z \"${_ppn}\" ]; then\n        >&2 echo \"The number of slots per instance couldn't be retrieved, no compute nodes available in ${scheduler} cluster\"\n        exit 1\n    fi\n}\n\nslurm_submit() {\n    cat > job1.sh <<EOF\n#!/bin/bash\nsrun sleep ${_sleepjob1}\necho \"\\$(date +%s)\" > job1.done\nEOF\n    cat > job2.sh <<EOF\n#!/bin/bash\nsrun sleep ${_sleepjob2}\necho \"\\$(date +%s)\" > job2.done\nEOF\n\n    cat > job3.sh <<EOF\n#!/bin/bash\nsrun sleep ${_sleepjob3}\necho \"\\$(date +%s)\" > job3.done\nEOF\n\n    chmod +x job1.sh job2.sh job3.sh\n    rm -f job1.done job2.done job3.done\n\n    sbatch -N 1 -n ${_ppn} ./job1.sh\n    sbatch -N 1 -n ${_ppn} ./job2.sh\n    sbatch -N 1 -n ${_ppn} ./job3.sh\n}\n\nscaledown_check_launch() {\n    # bounded completion time\n    if test \"$CHECK_CLUSTER_SUBPROCESS\" = \"\"; then\n        export CHECK_CLUSTER_SUBPROCESS=1\n        timeout -s KILL 5m /bin/bash ./cluster-check.sh \"$@\"\n        exit $?\n    fi\n\n    scheduler=\"$2\"\n\n    echo \"--> scheduler: $scheduler\"\n\n    scaledown_complete=0\n    while test $scaledown_complete = 0 ; do\n        ${scheduler}_scaledown_check\n        sleep 10\n    done\n    echo \"Scaledown successful\"\n}\n\nhas_zero_active_instances(){\n    instances=$1\n    if [[ ${instances} ]]; then\n        echo \"instances have not scaled down yet\"\n        scaledown_complete=0\n    else\n        echo \"instances have scaled down; exiting\"\n        scaledown_complete=1\n    fi\n}\n\nslurm_scaledown_check() {\n    has_zero_active_instances $(sinfo --noheader | awk '$4 != \"0\"')\n}\n\nmain() {\n    case \"$1\" in\n        submit)\n            submit_launch \"$@\"\n            ;;\n        scaledown_check)\n            scaledown_check_launch \"$@\"\n            ;;\n        *)\n            echo \"!! Unknown command $1 !!\"\n            exit 1\n            ;;\n    esac\n}\n\nmain \"$@\"\n", "num_lines": 161}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"ip container: $(/sbin/ip -o -4 addr list eth0 | awk '{print $4}' | cut -d/ -f1)\"\nTOKEN=$(curl --retry 3 --retry-delay 0  --fail -s -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 300\")\necho \"ip host: $(curl --retry 3 --retry-delay 0  --fail -s -H \"X-aws-ec2-metadata-token: ${TOKEN}\" \"http://169.254.169.254/latest/meta-data/local-ipv4\")\"\n\n# get shared dir\nIFS=',' _shared_dirs=(${PCLUSTER_SHARED_DIRS})\n_shared_dir=${_shared_dirs[0]}\n_job_dir=\"${_shared_dir}/${AWS_BATCH_JOB_ID%#*}-${AWS_BATCH_JOB_ATTEMPT}\"\n_exit_code_file=\"${_job_dir}/batch-exit-code\"\n\nif [[ \"${AWS_BATCH_JOB_NODE_INDEX}\" -eq  \"${AWS_BATCH_JOB_MAIN_NODE_INDEX}\" ]]; then\n    echo \"Hello I'm the main node $(hostname)! I run the mpi job!\"\n\n    mkdir -p \"${_job_dir}\"\n\n    echo \"Writing mpi code...\"\n    cat > \"${_shared_dir}/mpi_hello_world.c\" << EOF\n// Copyright 2011 www.mpitutorial.com\n//\n// An intro MPI hello world program that uses MPI_Init, MPI_Comm_size,\n// MPI_Comm_rank, MPI_Finalize, and MPI_Get_processor_name.\n//\n#include <mpi.h>\n#include <stdio.h>\n#include <stddef.h>\n\nint main(int argc, char** argv) {\n  // Initialize the MPI environment. The two arguments to MPI Init are not\n  // currently used by MPI implementations, but are there in case future\n  // implementations might need the arguments.\n  MPI_Init(NULL, NULL);\n\n  // Get the number of processes\n  int world_size;\n  MPI_Comm_size(MPI_COMM_WORLD, &world_size);\n\n  // Get the rank of the process\n  int world_rank;\n  MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);\n\n  // Get the name of the processor\n  char processor_name[MPI_MAX_PROCESSOR_NAME];\n  int name_len;\n  MPI_Get_processor_name(processor_name, &name_len);\n\n  // Print off a hello world message\n  printf(\"Hello world from processor %s, rank %d out of %d processors\\n\",\n         processor_name, world_rank, world_size);\n\n  // Finalize the MPI environment. No more MPI calls can be made after this\n  MPI_Finalize();\n}\nEOF\n\n    echo \"Compiling...\"\n    /usr/lib64/openmpi/bin/mpicc -o \"${_job_dir}/mpi_hello_world\" \"${_shared_dir}/mpi_hello_world.c\"\n\n    echo \"Running...\"\n    /usr/lib64/openmpi/bin/mpirun --mca btl_tcp_if_include eth0 --allow-run-as-root --machinefile \"${HOME}/hostfile\" \"${_job_dir}/mpi_hello_world\"\n\n    # Write exit status code\n    echo \"0\" > \"${_exit_code_file}\"\n    # Waiting for compute nodes to terminate\n    sleep 30\nelse\n    echo \"Hello I'm a compute node $(hostname)! I let the main node orchestrate the mpi execution!\"\n    # Since mpi orchestration happens on the main node, we need to make sure the containers representing the compute\n    # nodes are not terminated. A simple trick is to wait for a file containing the status code to be created.\n    # All compute nodes are terminated by Batch if the main node exits abruptly.\n    while [ ! -f \"${_exit_code_file}\" ]; do\n        sleep 2\n    done\n    exit $(cat \"${_exit_code_file}\")\nfi\n", "num_lines": 78}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Executing Test Script\"\nenv | grep TEST=test\n", "num_lines": 6}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\necho \"Executing Test Script\"\nexit 0\n", "num_lines": 5}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\n\nPIDS=($(pgrep supervisord$))\nfor PID in \"${PIDS[@]}\"\ndo\n    CMD_LINE=($(ps -p ${PID} -o args --no-headers))\n    # CMD_LINE is in the form\n    # /opt/parallelcluster/shared/path/pyenv/versions/3.9.9/envs/some_virtualenv/bin/python3.9 /opt/parallelcluster/shared/some-path/pyenv/versions/3.9.9/envs/some_virtualenv/bin/supervisord -n -c /opt/parallelcluster/some-path/supervisord.conf\n    if ${CMD_LINE[0]} $(dirname ${CMD_LINE[1]})/supervisorctl -c ${CMD_LINE[4]} status clustermgtd &>/dev/null; then\n        ${CMD_LINE[0]} $(dirname ${CMD_LINE[1]})/supervisorctl -c ${CMD_LINE[4]} stop clustermgtd\n    fi\ndone\n", "num_lines": 24}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nslurmctld_proc_id=$(ps aux | grep \"slurm\" | grep \"sbin\" | awk '{print $2}') && kill -9 ${slurmctld_proc_id}\n", "num_lines": 14}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\n\nPIDS=($(pgrep supervisord$))\nfor PID in \"${PIDS[@]}\"\ndo\n    CMD_LINE=($(ps -p ${PID} -o args --no-headers))\n    # CMD_LINE is in the form\n    # /opt/parallelcluster/shared/path/pyenv/versions/3.9.9/envs/some_virtualenv/bin/python3.9 /opt/parallelcluster/shared/path/pyenv/versions/3.9.9/envs/some_virtualenv/bin/supervisord -n -c /opt/parallelcluster/some_path/supervisord.conf\n    if ${CMD_LINE[0]} $(dirname ${CMD_LINE[1]})/supervisorctl -c ${CMD_LINE[4]} status clustermgtd &>/dev/null; then\n        ${CMD_LINE[0]} $(dirname ${CMD_LINE[1]})/supervisorctl -c ${CMD_LINE[4]} start clustermgtd\n    fi\ndone\n", "num_lines": 24}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nsystemctl start slurmctld\n", "num_lines": 14}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nslurm_plugin_path=$(sudo find / -iname slurm_plugin -print0|grep -FzZ 'node_virtualenv')\ncat > $slurm_plugin_path/overrides.py << EOF\nfrom botocore.exceptions import ClientError\nimport boto3\nimport logging\n\nlogger = logging.getLogger(__name__)\n\ndef run_instances(region, boto3_config, **run_instances_kwargs):\n    if \"ice-compute-resource\" in run_instances_kwargs.get(\"LaunchTemplate\", {}).get(\"LaunchTemplateName\"):\n        # Forcing the Placement/tenancy override to host will trigger an InsufficientHostCapacity since we do not\n        # have a fleet of reserved hosts\n        run_instances_kwargs['Placement']= {'Tenancy': 'host'}\n        logger.info(\"Updated parameters for EC2 run_instances: %s\", run_instances_kwargs)\n    ec2_client = boto3.client(\"ec2\", region_name=region, config=boto3_config)\n    return ec2_client.run_instances(**run_instances_kwargs)\n\ndef update_lt_instance_overrides(overrides):\n    updated_overrides = []\n    for ov in overrides:\n        if 'InstanceType' in ov:\n            # mutate t2.large into t2-large to force an Error in CreateFleet request\n            mispelled_instance_type = ov['InstanceType'].replace(\".\", \"-\")\n            ov['InstanceType'] = mispelled_instance_type\n            updated_overrides.append(ov)\n        else:\n            updated_overrides.append(ov)\n\n    return updated_overrides\n\ndef create_fleet(region, boto3_config, **create_fleet_kwargs):\n    configs = create_fleet_kwargs.get(\"LaunchTemplateConfigs\", [])\n    if len(configs) >= 1 and configs[0]:\n        lt_config = configs[0]\n\n        if \"ice-cr-multiple\" in lt_config.get('LaunchTemplateSpecification').get(\"LaunchTemplateName\"):\n            # CreateFleet will return an Error and an empty list of instances\n            lt_config['Overrides'] = update_lt_instance_overrides(lt_config['Overrides'])\n            logger.info(\"Updated Instance Overrides for CreateFleet args: %s\", create_fleet_kwargs)\n        elif \"exception-cr-multiple\" in lt_config.get('LaunchTemplateSpecification').get(\"LaunchTemplateName\"):\n            # force CreateFleet to raise an exception since `inf*` instance types have Inferentia accelerators\n            # that are manufactured by AWS, and we are also requesting Manufacturer=nvidia\n            lt_config['Overrides'] = [{\n                        \"InstanceRequirements\": {\n                            \"VCpuCount\": { \"Min\": 2 },\n                            \"MemoryMiB\": { \"Min\": 2048 },\n                            \"AllowedInstanceTypes\": [  \"inf*\" ],\n                            \"AcceleratorManufacturers\": [ \"nvidia\" ]\n                        }\n                    }]\n            logger.info(\"Updated Instance Overrides for CreateFleet args: %s\", create_fleet_kwargs)\n\n        ec2_client = boto3.client(\"ec2\", region_name=region, config=boto3_config)\n        return ec2_client.create_fleet(**create_fleet_kwargs)\n    else:\n        raise Exception(\"Missing LaunchTemplateSpecification parameter in create_fleet request.\")\nEOF\n", "num_lines": 70}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script creates a dummy systemd service that sleeps for a given time, and\n# makes it a dependency for the slurmd service. This way it's possible to simulate\n# a longer rebooting time of the node via scontrol reboot.\n\n# TODO: consider disabling the network during the sleep in order to simulate the\n# non-responsiveness to the EC2 status checks of the rebooted node.\n#\n# It doesn't seem to be possible to add a `ifconfig eth0 down` and `ifconfig eth0 up`\n# in the following systemd service: the first command completely kills the instance\n# and the second command doesn't seem to reactivate the network interface.\n\nsudo mkdir /etc/systemd/system/slurmd.service.d\n\ncat <<DELAY_SERVICE | sudo tee /etc/systemd/system/slurmd_delay.service\n[Unit]\nDescription=Dummy Slurmd delay\nBefore=slurmd.service\nWants=network-online.target\n\n[Service]\nType=simple\nTimeoutSec=180s\nExecStartPre=sleep 120\nExecStart=sleep 1\n\n[Install]\nWantedBy=multi-user.target\nDELAY_SERVICE\n\ncat <<SLURMD_DROP_IN | sudo tee /etc/systemd/system/slurmd.service.d/add_delay.conf\n[Unit]\nAfter=slurmd_delay.service\nRequires=slurmd_delay.service\nSLURMD_DROP_IN\n\nsudo systemctl daemon-reload\n", "num_lines": 39}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Reset state of the daemons after running add_sleep_to_slurmd_service_compute.sh\n\nsudo rm /etc/systemd/system/slurmd_delay.service\nsudo rm /etc/systemd/system/slurmd.service.d/add_delay.conf\nsudo systemctl daemon-reload\n", "num_lines": 8}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#SBATCH --export=ALL\n#SBATCH --nodes=2\n#SBATCH --ntasks-per-node=3\n#SBATCH --job-name=imb2\n#SBATCH --output=runscript.out\n\nmodule load intelmpi\nmpirun -n 6 IMB-MPI1 Alltoall -npmin 2\n", "num_lines": 11}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\necho \"qsub executed successfully\"", "num_lines": 2}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n. \"/etc/parallelcluster/cfnconfig\"\n\n\nif [[ $cfn_node_type == \"HeadNode\" ]]; then\n    # Override create_fleet attributes\n    cat > /opt/slurm/etc/pcluster/create_fleet_overrides.json << 'EOF'\n{\n    \"fleet\": {\n        \"fleet-1\": {\n            \"TagSpecifications\": [\n                 {\n                    \"ResourceType\": \"instance\",\n                    \"Tags\": [\n                        {\n                            \"Key\": \"overridefleet\",\n                            \"Value\": \"overridefleet\"\n                        }\n                    ]\n                }\n            ]\n        }\n    }\n}\nEOF\n\n    # Override run_instances attributes\n    cat > /opt/slurm/etc/pcluster/run_instances_overrides.json << 'EOF'\n{\n    \"single\": {\n        \"single-1\": {\n            \"TagSpecifications\": [\n                 {\n                    \"ResourceType\": \"instance\",\n                    \"Tags\": [\n                        {\n                            \"Key\": \"overridesingle\",\n                            \"Value\": \"overridesingle\"\n                        }\n                    ]\n                }\n            ]\n        }\n    }\n}\nEOF\nfi\n", "num_lines": 49}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nfunction get_instance_type() {\n  token=$(curl -s -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 300\")\n  instance_type_url=\"http://169.254.169.254/latest/meta-data/instance-type\"\n  instance_type=$(curl --retry 3 --retry-delay 0 --silent --fail -H \"X-aws-ec2-metadata-token: ${token}\" \"${instance_type_url}\")\n}\nget_instance_type\nif [ \"${instance_type}\" == \"c5.large\" ]; then\n  echo \"Test Bootstrap error that causes instance to self terminate.\"\n  exit 1\nfi\n\n", "num_lines": 24}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nexit 1\n", "num_lines": 3}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\nssh $1 sudo pkill -f slurmd\n", "num_lines": 14}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nget_setting_value() {\n  local _file=$1\n  local _search=$2\n  local _pattern\n\n  _pattern=$(grep \"${_search}\" \"${_file}\")\n  echo \"${_pattern}\" | tr -d '\\n' | cut -d = -f 2 | xargs\n}\n\n# Get the root user (root is added to Slurm accounting by default during configuration)\ngetent passwd 0 | cut -d : -f 1\n# Get the configured cluster user name from the dna.json (added to the database during node configuration)\njq -r '.cluster.cluster_user' < \"/etc/chef/dna.json\"\n# Get the configured Slurm user from the slurm configuration (added to the database during node configuration)\nget_setting_value \"/opt/slurm/etc/slurm.conf\" \"^SlurmUser=\"\n", "num_lines": 17}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nCA_URL=$1\nCA_NAME=$2\nCA_PATH=\"/tmp/slurm\"\nCA_FILE_PATH=\"${CA_PATH}/${CA_NAME}\"\nSLURMDBD_CONFIG_FILE=\"/opt/slurm/etc/slurmdbd.conf\"\n\nwget ${CA_URL} -P ${CA_PATH}\n\necho \"Clearing previous CA Setting\"\nsed -i \"/^StorageParameters\\s*=/d\" \"${SLURMDBD_CONFIG_FILE}\"\n\necho \"Setting 'StorageParameters' SSL_CA=${CA_FILE_PATH}\"\necho \"StorageParameters=SSL_CA=${CA_FILE_PATH}\" >> \"${SLURMDBD_CONFIG_FILE}\"\n\necho \"Restarting slurmdbd service\"\nsystemctl restart slurmdbd\n", "num_lines": 21}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Test the basic functionality of the Neuron component installed in the ParallelCluster AMI\n\n# Print available Neuron packages\nOS=\"$(grep \"^ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\ncase ${OS} in\n  ubuntu)\n    apt list --installed | grep neuron\n    USER=ubuntu\n    ;;\n  amzn)\n    rpm -qa | grep neuron\n    USER=ec2-user\n    ;;\n  *)\n    echo \"Unsupported system. Found /etc/os-release ID content: ${OS}\"\n    exit 1\n    ;;\nesac\n\n# Create python scripts required for the tests\ncat <<EOF >allreduce_launch.py\nimport os\nimport torch_xla.core.xla_model as xm\nimport torch\nimport torch.distributed as dist\nfrom torch_xla.distributed import xla_backend\n\n#os.environ[\"NEURON_RT_LOG_LEVEL\"] = \"INFO\"\n#os.environ[\"NEURON_RT_LOG_LOCATION\"] = \"syslog\"\n#os.environ[\"NCCL_DEBUG\"] = \"ERROR\"\n#os.environ[\"NCCL_DEBUG_SUBSYS\"] = \"ALL\"\n\n\ndef _mp_fn():\n    dist.init_process_group('xla')\n    world_size = xm.xrt_world_size()\n    device = xm.xla_device()\n\n    if world_size > 0:\n        ones = torch.ones((2, 3))\n        xones = ones.to(device)\n        print(\"running all reduce\")\n        result = xm.all_reduce(xm.REDUCE_SUM, xones)\n        result_cpu = result.cpu()\n        expected = torch.ones((2,3))*world_size\n        assert expected.allclose(result_cpu)\n        print(result_cpu)\n        print('PASS')\n\n\nif __name__ == '__main__':\n    print(\n        'master_port:{}, master_addr:{}, rank:{}, local_rank:{}, size:{}'.format(\n            os.environ['MASTER_PORT'],\n            os.environ['MASTER_ADDR'],\n            os.environ['RANK'],\n            os.environ['LOCAL_RANK'],\n            os.environ['WORLD_SIZE'],\n        )\n    )\n\n    _mp_fn()\nEOF\n\n\ncat <<'EOF' >test_launch.py\nimport os\nimport subprocess\n\n\ndef test_local_launch_allreduce():\n    # This test launches a two phase launcher, spawns two processes which\n    # in turn launch more processes. This uses pytorch distributed.launch utility along with ptxrt bridge\n    cmd = \"torchrun --nproc_per_node=$PROC_PER_NODE --nnodes=1 allreduce_launch.py \"\n\n    new_env0 = os.environ.copy()\n    new_env0['PROC_PER_NODE'] = '2'\n\n    proc0 = subprocess.Popen(cmd, env=new_env0, shell=True)\n\n    return_code = proc0.wait()\n    assert return_code == 0\nEOF\n\n# Activate virtual environment created by neuron-installation.sh and run the test\n# We expect to find PASSED word at the end of the output\nsource /home/$USER/aws_neuron_venv_pytorch/bin/activate\npytest test_launch.py -vxs | tee output-allreduce.txt\n", "num_lines": 90}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Test the collective functionality of the Neuron component installed in the ParallelCluster AMI\n# This script can work if submitted through Slurm with the following command:\n# sbatch --nodes=2 --ntasks-per-node=1 --cpus-per-task=32 neuron-ccl.sh\n# or if submitted directly on a single node (SLURM_JOB_NODELIST not set)\n\ncat <<'EOF' >submission-script.sh\n#!/bin/bash\nset -x\n\n# FIXME remove this repo once packages are public available\nTEMPORARY_ARTIFACTS_BUCKET_PATH=s3://aws-parallelcluster-beta/neuron/\n\n# Print available Neuron packages\nOS=\"$(grep \"^ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\ncase ${OS} in\n  ubuntu)\n    apt list --installed | grep neuron\n    ;;\n  amzn)\n    rpm -qa | grep neuron\n    ;;\n  *)\n    echo \"Unsupported system. Found /etc/os-release ID content: ${OS}\"\n    exit 1\n    ;;\nesac\n\n# Identify node name to set the right START_RANK\nif [ \"${SLURM_NNODES:=1}\" == \"1\" ]; then\n  # SLURM_NNODES is not set (no slurm job) or script is executed in a single node\n  START_RANK=0\n  # retrieve first IP of the list\n  HOST_IP=$(hostname -I | cut -d ' ' -f1)\nelse\n  # SLURM_JOB_NODELIST is an array, find first and second node of the array and use number to identify first node.\n  NODE_NAME_PREFIX=${SLURM_JOB_NODELIST%-[*}\n  NODE1=$(echo $SLURM_JOB_NODELIST | cut -d'[' -f2 | cut -d'-' -f1)\n  NODE2=$(echo $SLURM_JOB_NODELIST | cut -d'[' -f2 | cut -d'-' -f2 | tr -d ']')\n  HOST_IP=$(scontrol show nodes $NODE_NAME_PREFIX-$NODE1 | grep -oe \"NodeAddr=[^ ]*\" | cut -d'=' -f2)\n\n  if [ \"$(hostname)\" == \"$NODE_NAME_PREFIX-$NODE1\" ]; then\n      START_RANK=0\n  else\n      START_RANK=32\n  fi\nfi\nTOTAL_RANK=$(($SLURM_NNODES*32))\n\n# Download file for simulation (64 in the file name corresponds to the number of ranks hardcoded into the file).\n# To use a different number of ranks you need to generate another one:\n# python3 inst-sweep/genneffs_nccl.py -n <total-number-of-ranks> --all --output <output-dir>\nNEFF_FILE=test_nccl_64r_50allg_int8_393216/0/file.neff\nif [[ ! -f $NEFF_FILE ]]; then\n  aws s3 cp ${TEMPORARY_ARTIFACTS_BUCKET_PATH}test_nccl_64r_50allg_int8_393216_0_file.neff $NEFF_FILE\nfi\n\n# Print eth0 ip\n/usr/sbin/ip -br addr show dev eth0 scope global\n\n# Export variables required for neuron-bench\nexport PATH=\"/opt/aws/neuron/bin:$PATH\"\n# Export variables required for EFA\nexport FI_EFA_USE_DEVICE_RDMA=1\nexport FI_PROVIDER=efa\n\nNCCL_DEBUG=trace NCCL_DEBUG_SUBSYS=all NCCL_DEBUG_FILE=$(pwd)/nccl_${SLURM_TASK_PID}.log \\\nNEURON_RT_EXEC_TIMEOUT=10 \\\nNEURON_RT_ROOT_COMM_ID=$HOST_IP:33666 \\\nLD_LIBRARY_PATH=/opt/aws/neuron/lib:/opt/amazon/efa/lib64 \\\nneuron-bench infer --fixed-instance-count 32 --enable-only-latency --work 1 \\\n  --run-as-cc-neff --minimal-tensor-io --verbose 4 --cc-skip-latencies 5\\\n  --cc-world-size $TOTAL_RANK --cc-rank-start $START_RANK \\\n  --summary-percentiles=1,50,99,100 \\\n  --warmup none $NEFF_FILE | tee output-ccl.txt\n\nEOF\n\n# srun is required to run neuron-bench process on the two nodes\nsrun bash submission-script.sh", "num_lines": 80}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Private Repository Access\n# I manually created a TrainiumPreviewRepository secret and TrainiumPreviewPolicy on 447714826191 account to permit access to Secret below\n# {\n#    \"Version\": \"2012-10-17\",\n#    \"Statement\": [\n#        {\n#            \"Effect\": \"Allow\",\n#            \"Action\": [\n#                \"secretsmanager:GetResourcePolicy\",\n#                \"secretsmanager:GetSecretValue\",\n#                \"secretsmanager:DescribeSecret\",\n#                \"secretsmanager:ListSecretVersionIds\"\n#            ],\n#            \"Resource\": [\n#                \"arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository-<RANDOM-STRING>\"\n#            ]\n#        },\n#        {\n#            \"Effect\": \"Allow\",\n#            \"Action\": \"secretsmanager:ListSecrets\",\n#            \"Resource\": \"*\"\n#        }\n#    ]\n#}\nREPO_USER=$(aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository --region us-east-1 --query 'SecretString' --output text | jq -r '.repository_user')\nREPO_SECRET=$(aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository --region us-east-1 --query 'SecretString' --output text | jq -r '.repository_password')\nREPO_SUFFIX=$(aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository --region us-east-1 --query 'SecretString' --output text | jq -r '.repository_suffix')\n\nTEMPORARY_ARTIFACTS_BUCKET_PATH=s3://aws-parallelcluster-beta/neuron/\n\n\n_ubuntu_installation() {\n  # Configure Linux for Neuron repository updates\n  sudo tee /etc/apt/sources.list.d/neuron-private.list > /dev/null <<EOF\ndeb https://${REPO_USER}:${REPO_SECRET}@apt.${REPO_SUFFIX} focal main\nEOF\n\n  sudo apt-get update -y\n  sudo apt-get install -y aws-neuronx-runtime-lib=2.* aws-neuronx-collectives=2.*\n\n  wget -qO - https://${REPO_USER}:${REPO_SECRET}@apt.${REPO_SUFFIX}/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB | sudo apt-key add -\n\n  # Install packages from S3 --> FIXME they should be installed from configured repository\n  DEBS=$(aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository --region us-east-1 --query 'SecretString' --output text | jq -r '.debs')\n  for DEB in $DEBS\n  do\n    sudo dpkg -i $DEB\n  done\n\n  # Install Python venv and activate Python virtual environment to install Neuron pip packages.\n  local OS_VERSION=\"$(grep \"^VERSION_ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\n  case ${OS_VERSION} in\n      20.04)\n        sudo apt-get install -y python3.8-venv g++\n        python3 -m venv /home/ubuntu/aws_neuron_venv_pytorch\n        ;;\n      18.04)\n        sudo apt-get install -y python3.7-venv g++\n        python3.7 -m venv /home/ubuntu/aws_neuron_venv_pytorch\n        ;;\n      *)\n        echo \"Unrecognized VERSION_ID. Found /etc/os-release version content: ${OS_VERSION}\"\n        exit 1\n        ;;\n    esac\n}\n\n_rhel_installation() {\n  sudo tee /etc/yum.repos.d/neuron-private.repo > /dev/null <<EOF\n[neuron-private]\nname=Neuron YUM Repository\nbaseurl=https://${REPO_USER}:${REPO_SECRET}@yum.${REPO_SUFFIX}\nenabled=1\nEOF\n  sudo yum install -y aws-neuronx-runtime-lib-2.* aws-neuronx-collectives-2.*\n\n  sudo rpm --import https://${REPO_USER}:${REPO_SECRET}@yum.${REPO_SUFFIX}/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB\n\n  # Install packages from S3 --> FIXME they should be installed from configured repository\n  RPMS=$(aws secretsmanager get-secret-value --secret-id arn:aws:secretsmanager:us-east-1:447714826191:secret:TrainiumPreviewRepository --region us-east-1 --query 'SecretString' --output text | jq -r '.rpms')\n  for RPM in $RPMS\n  do\n    sudo rpm -i $RPM\n  done\n\n  python3 -m venv /home/ec2-user/aws_neuron_venv_pytorch\n}\n\n\n_dkms_ubuntu_installation() {\n  sudo tee /etc/apt/sources.list.d/neuron.list > /dev/null <<EOF\ndeb https://apt.repos.neuron.amazonaws.com focal main\nEOF\n  wget -qO - https://apt.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB | sudo apt-key add -\n\n  sudo apt update\n  sudo apt-get install aws-neuronx-dkms -y\n}\n\n\n_dkms_rhel_installation() {\n  sudo tee /etc/yum.repos.d/neuron.repo > /dev/null <<EOF\n[neuron]\nname=Neuron YUM Repository\nbaseurl=https://yum.repos.neuron.amazonaws.com\nenabled=1\nEOF\n  sudo rpm --import https://yum.repos.neuron.amazonaws.com/GPG-PUB-KEY-AMAZON-AWS-NEURON.PUB\n\n  sudo yum install aws-neuronx-dkms -y\n}\n\n\nfunction main() {\n  # Download packages from S3 --> FIXME they should be installed from configured repository\n  aws s3 cp ${TEMPORARY_ARTIFACTS_BUCKET_PATH} . --recursive\n\n  local OS=\"$(grep \"^ID=\" /etc/os-release | cut -d\"=\" -f 2 | xargs)\"\n  case ${OS} in\n    ubuntu)\n      _dkms_ubuntu_installation\n      _ubuntu_installation\n      USER=ubuntu\n      ;;\n    amzn)\n      _dkms_rhel_installation\n      _rhel_installation\n      USER=ec2-user\n      ;;\n    *)\n      echo \"Unsupported system. Found /etc/os-release ID content: ${OS}\"\n      exit 1\n      ;;\n  esac\n\n  # Install Python venv and activate Python virtual environment to install Neuron pip packages.\n  source /home/$USER/aws_neuron_venv_pytorch/bin/activate\n  pip3 install -U pip\n  pip3 install pytest\n\n  python3 -m pip config set global.extra-index-url \"https://pip.repos.neuron.amazonaws.com\"\n  PIPS='torch-neuronx==1.11.0.1.* neuronx-cc==2.* transformers'\n  pip3 install ${PIPS}\n}\n\nmain \"${@}\"\n", "num_lines": 149}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Test the alignment of the Route 53 IP and the the host IP.\n\nOUTPUT_FILE=\"output-primary-ip.txt\"\n\n# Get DNS Server\nDNS_SERVER=\"\"\ngrep Ubuntu /etc/issue &>/dev/null && DNS_SERVER=$(systemd-resolve --status | grep \"DNS Servers\" | awk '{print $3}' | sort -r | head -1)\n\n# Determine expected entry in /etc/hosts\nIP=\"$(host $HOSTNAME $DNS_SERVER | tail -1 | awk '{print $4}')\"\nDOMAIN=$(jq .cluster.dns_domain /etc/chef/dna.json | tr -d \\\")\nEXPECTED=\"$IP $HOSTNAME.${DOMAIN::-1} $HOSTNAME\"\necho \"Expected entry in /etc/hosts: $EXPECTED\" | tee $OUTPUT_FILE\n\n# Retrieve actual entry in /etc/hosts\nACTUAL=\"$(grep \"$HOSTNAME\" /etc/hosts)\"\necho \"Actual entry in /etc/hosts: $ACTUAL\" | tee -a $OUTPUT_FILE\n\n# Check\nif [[ \"$ACTUAL\" == \"$EXPECTED\" ]]; then\n  echo \"PASSED\" | tee -a $OUTPUT_FILE\nelse\n  echo \"ERROR: Route53 IP does not match host IP\" | tee -a $OUTPUT_FILE\nfi\n", "num_lines": 26}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"starting failed_postupdate script\"\nexit 1\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"postinstall-$1\" > /tmp/postinstall_out.txt\necho \"postinstall run OK\"\n\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"starting postupdate script\"\necho \"postupdate-$1\" > /tmp/postupdate_out.txt\necho \"postupdate run OK\"\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"preinstall-$1\" > /tmp/preinstall_out.txt\necho \"preinstall run OK\"", "num_lines": 14}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\ndf -h | grep '/$' | awk '{{print $2}}' > /shared/$(hostname)_root_volume_size.txt\n", "num_lines": 14}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"updated_postinstall-$1\" > /tmp/updated_postinstall_out.txt\necho \"updated_postinstall run OK\"\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"starting updated_postupdate script\"\necho \"updated_postupdate-$1\" > /tmp/updated_postupdate_out.txt\necho \"updated_postupdate run OK\"\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\necho \"updated_preinstall-$1\" > /tmp/updated_preinstall_out.txt\necho \"updated_preinstall run OK\"\n", "num_lines": 15}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# On Mac OS, the default implementation of sed is BSD sed, but this script requires GNU sed.\nif [ \"$(uname)\" == \"Darwin\" ]; then\n  command -v gsed >/dev/null 2>&1 || { echo >&2 \"[ERROR] Mac OS detected: please install GNU sed with 'brew install gnu-sed'\"; exit 1; }\n  PATH=\"/usr/local/opt/gnu-sed/libexec/gnubin:$PATH\"\nfi\n\nif [ -z \"$1\" ]; then\n    echo \"New version not specified. Usage: bump-awsbatch-cli-version.sh NEW_VERSION\"\n    exit 1\nfi\n\nNEW_VERSION=$1\nCURRENT_VERSION=$(sed -ne \"s/^VERSION = \\\"\\(.*\\)\\\"/\\1/p\" awsbatch-cli/setup.py)\nsed -i \"s/VERSION = \\\"$CURRENT_VERSION\\\"/VERSION = \\\"$NEW_VERSION\\\"/g\" awsbatch-cli/setup.py\n", "num_lines": 19}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# On Mac OS, the default implementation of sed is BSD sed, but this script requires GNU sed.\nif [ \"$(uname)\" == \"Darwin\" ]; then\n  command -v gsed >/dev/null 2>&1 || { echo >&2 \"[ERROR] Mac OS detected: please install GNU sed with 'brew install gnu-sed'\"; exit 1; }\n  PATH=\"/usr/local/opt/gnu-sed/libexec/gnubin:$PATH\"\nfi\n\n_error_exit() {\n   echo \"$1\"\n   exit 1\n}\n\n_help() {\n    local -- _cmd=$(basename \"$0\")\n\n    cat <<EOF\n\n  Usage: ${_cmd} [OPTION]...\n\n  Bump ParallelCluster version.\n\n  --version <version>                                               ParallelCluster version\n  -h, --help                                                        Print this help message\nEOF\n}\n\nmain() {\n    # parse input options\n    while [ $# -gt 0 ] ; do\n        case \"$1\" in\n            --version)                            _version=\"$2\"; shift;;\n            --version=*)                          _version=\"${1#*=}\";;\n            -h|--help|help)                       _help; exit 0;;\n            *)                                    _help; _error_exit \"[error] Unrecognized option '$1'\";;\n        esac\n        shift\n    done\n\n    # verify required parameters\n    if [ -z \"${_version}\" ]; then\n        _error_exit \"--version parameter not specified\"\n        _help;\n    else\n        NEW_VERSION=$_version\n        NEW_VERSION_SHORT=$(echo ${NEW_VERSION} | grep -Eo \"[0-9]+\\.[0-9]+\\.[0-9]+\")\n        CURRENT_VERSION=$(sed -ne \"s/^VERSION = \\\"\\(.*\\)\\\"/\\1/p\" cli/setup.py)\n        CURRENT_VERSION_SHORT=$(echo ${CURRENT_VERSION} | grep -Eo \"[0-9]+\\.[0-9]+\\.[0-9]+\")\n        PC_SUPPORT_DIR=\"./pc_support\"\n        sed -i \"s/VERSION = \\\"$CURRENT_VERSION\\\"/VERSION = \\\"$NEW_VERSION\\\"/g\" cli/setup.py\n\n        sed -i \"s/\\\"parallelcluster\\\": \\\"$CURRENT_VERSION\\\"/\\\"parallelcluster\\\": \\\"$NEW_VERSION\\\"/g\" cli/src/pcluster/constants.py\n        sed -i \"s/aws-parallelcluster-cookbook-$CURRENT_VERSION/aws-parallelcluster-cookbook-$NEW_VERSION/g\" cli/src/pcluster/constants.py\n        sed -i \"s| version: $CURRENT_VERSION_SHORT| version: $NEW_VERSION_SHORT|g\" cli/src/pcluster/api/openapi/openapi.yaml\n\n        sed -i \"s|parallelcluster/$CURRENT_VERSION|parallelcluster/$NEW_VERSION|g\" api/infrastructure/parallelcluster-api.yaml\n        sed -i \"s| Version: $CURRENT_VERSION| Version: $NEW_VERSION|g\" api/infrastructure/parallelcluster-api.yaml\n        sed -i \"s| ShortVersion: $CURRENT_VERSION_SHORT| ShortVersion: $NEW_VERSION_SHORT|g\" api/infrastructure/parallelcluster-api.yaml\n        sed -i \"s| version: $CURRENT_VERSION_SHORT| version: $NEW_VERSION_SHORT|g\" api/spec/openapi/ParallelCluster.openapi.yaml\n        sed -i \"s| version: \\\"$CURRENT_VERSION_SHORT\\\"| version: \\\"$NEW_VERSION_SHORT\\\"|g\" api/spec/smithy/model/parallelcluster.smithy\n        sed -i \"s| Version: $CURRENT_VERSION| Version: $NEW_VERSION|g\" cloudformation/custom_resource/cluster.yaml\n        sed -i \"s| Version: $CURRENT_VERSION| Version: $NEW_VERSION|g\" cloudformation/custom_resource/cluster-1-click.yaml\n        cp \"$PC_SUPPORT_DIR/os_$CURRENT_VERSION.json\" \"$PC_SUPPORT_DIR/os_$NEW_VERSION.json\"\n        git add \"$PC_SUPPORT_DIR/os_$NEW_VERSION.json\"\n\n        pushd api && ./gradlew generatePythonClient && popd\n    fi\n}\n\nmain \"$@\"\n\n# vim:syntax=sh\n", "num_lines": 75}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e -o xtrace\n\n\nappend_package_details_to_final_license_file(){\n  # Function to Append Package Details to the THIRD-PARTY-LICENSES file\n  #Arguments ->  1- Package Name, 2- Package Version, 3- License Type , 4- URL for package, 5,6,7- URL for License\n  # Adding a header to final License file with Package Name, Package Version, License Type , URL for package\n  echo -e \"\\n\\n\\n$1 \\n$2 \\n$3 \\n$4\" >> $final_license_file\n  # Appending License\n  curl $5 >> $final_license_file\n  # Adding Dual Licenses if they exist \n  if [ $# -gt 5 ]\n    then\n      curl $6 >> $final_license_file\n      curl $7 >> $final_license_file\n  fi\n\n}\n\nfunction create_attribution_doc() {\n  ATTR_SCRIPT_DIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" >/dev/null 2>&1 && pwd)\"\n\n  # Install the python version if it doesnt exist\n  if test ! -d ${PYENV_ROOT}/versions/${PYTHON_VERSION};\n  then \n    env PYTHON_CONFIGURE_OPTS=\"--enable-shared\" pyenv install ${PYTHON_VERSION}\n  fi\n  \n  pyenv virtualenv ${PYTHON_VERSION} attribution-doc-env\n  # switch to a specific virtual env\n  source ${PYENV_ROOT}/versions/attribution-doc-env/bin/activate\n  \n  # Update Pip\n  pip3 install --upgrade pip\n  \n  # Installing PyInstaller\n  pip3 install pyinstaller\n  # Install pip-licenses\n  pip3 install pip-licenses\n  \n  # install pcluster via source\n  \n  pip3 install -e $(dirname $ATTR_SCRIPT_DIR )/cli\n  #pip3 install -r requirements.txt\n  \n  final_license_file=$(dirname $ATTR_SCRIPT_DIR )/THIRD-PARTY-LICENSES.txt\n  \n  # Create a list of aws cdk Sub-packages we want to ignore \n  aws_cdk_ignore_subpackages=$(pip list | grep cdk | awk '{print $1}') \n  aws_cdk_version=$(pip list | grep cdk | awk '{print $2}'| head -n 1)\n  \n  packaging_version=$(pip list | grep packaging | awk '{print $2}')\n  exception_group_version=$(pip list | grep exceptiongroup | awk '{print $2}')\n  idna_version=$(pip list | grep idna | awk '{print $2}')\n  typing_extentions_version=$(pip list | grep typing_extensions | awk '{print $2}')\n  # Create a pip License document\n  pip-licenses -i $aws_cdk_ignore_subpackages aws-parallelcluster pip-licenses packaging pyinstaller-hooks-contrib pyinstaller exceptiongroup idna typing_extensions certifi --format=plain-vertical --with-license-file --with-urls --no-license-path --with-authors --output-file=$final_license_file\n  \n  \n  #Getting python version\n  cpy_version=$(python -V |  grep -Eo '([0-9]+)(\\.?[0-9]+)' | head -1) \n\n  \n  # certifi \n  append_package_details_to_final_license_file \"certifi\" \"2022.12.07\" \"Mozilla Public License 2.0 (MPL 2.0)\" \"https://github.com/certifi/python-certifi/tree/2022.12.07\" \"https://raw.githubusercontent.com/certifi/python-certifi/2022.12.07/LICENSE\"\n  \n  # exception_group \n  append_package_details_to_final_license_file \"exceptiongroup\" $exception_group_version \"MIT License\" \"https://github.com/agronholm/exceptiongroup\" \"https://raw.githubusercontent.com/agronholm/exceptiongroup/main/LICENSE\"\n  \n  # idna \n  append_package_details_to_final_license_file \"idna\" $idna_version \"BSD License\" \"https://github.com/kjd/idna\" \"https://raw.githubusercontent.com/kjd/idna/master/LICENSE.md\"\n  \n  # typing_extentions\n  append_package_details_to_final_license_file \"typing_extensions\" $typing_extentions_version \"Python Software Foundation License\" \"https://github.com/python/typing_extensions\" \"https://raw.githubusercontent.com/python/typing_extensions/main/LICENSE\"\n  \n  # Packaging\n  append_package_details_to_final_license_file \"packaging\" $packaging_version \"Apache Software License; BSD License\" \"https://github.com/pypa/packaging\" \"https://raw.githubusercontent.com/pypa/packaging/main/LICENSE\" \"https://raw.githubusercontent.com/pypa/packaging/main/LICENSE.APACHE\" \"https://raw.githubusercontent.com/pypa/packaging/main/LICENSE.BSD\"\n  \n  # pyinstaller-hooks-contrib\n  append_package_details_to_final_license_file \"pyinstaller-hooks-contrib\" \"2022.15\" \"Apache License 2.0; GNU General Public License\" \"https://github.com/pyinstaller/pyinstaller-hooks-contrib/archive/refs/tags/2022.15.tar.gz.\" \"https://raw.githubusercontent.com/pyinstaller/pyinstaller-hooks-contrib/2022.15/LICENSE\" \"https://raw.githubusercontent.com/pyinstaller/pyinstaller-hooks-contrib/2022.15/LICENSE.APL.txt\" \"https://raw.githubusercontent.com/pyinstaller/pyinstaller-hooks-contrib/2022.15/LICENSE.GPL.txt\"\n  \n  # pyinstaller\n  append_package_details_to_final_license_file \"pyinstaller\" \"5.7.0\" \"GNU General Public License v2 (GPLv2)\" \"https://github.com/pyinstaller/pyinstaller/archive/refs/tags/v5.7.0.tar.gz.\" \"https://raw.githubusercontent.com/pyinstaller/pyinstaller/v5.7.0/COPYING.txt\"\n  \n  # aws-cdk \n  append_package_details_to_final_license_file \"aws-cdk\" $aws_cdk_version \"Apache License\" \"https://raw.githubusercontent.com/aws/aws-cdk/main/LICENSE\" \"https://raw.githubusercontent.com/aws/aws-cdk/main/LICENSE\"\n  \n  # Python\n  append_package_details_to_final_license_file \"Python\" $cpy_version \"PSF License Version 2; Zero-Clause BSD license\" \"https://raw.githubusercontent.com/python/cpython/$cpy_version/LICENSE\" \"https://raw.githubusercontent.com/python/cpython/$cpy_version/LICENSE\"\n  \n  \n  deactivate\n  pyenv virtualenv-delete -f attribution-doc-env\n\n}\n\n\n_error_exit() {\n   echo \"$1\"\n   exit 1\n}\n\n_help() {\n    local -- _cmd=$(basename \"$0\")\n\n    cat <<EOF\n  This script will create the THIRD_PARTY_LICENSE.txt file assuming you have already installed Pyenv\n  Usage: ${_cmd} [OPTION]...\n\n\n  --python-version <version>                                        Python version with which you want to create the attribution document.\n  -h, --help                                                        Print this help message\n  \n  Examples:\n  ${_cmd}\n  $_cmd --python-version 3.9.10\nEOF\n}\n\nfunction parse_options () {\n  \n   while [ $# -gt 0 ] ; do\n          case \"$1\" in\n              --python-version)                      PYTHON_VERSION=\"$2\"; shift;;\n              -h|--help|help)                       _help; exit 0;;\n              *)                                    _help; _error_exit \"[error] Unrecognized option '$1'\";;\n          esac\n          shift\n      done\n\n}\n\nfunction main() {\n  parse_options \"$@\"\n  create_attribution_doc\n}\n\nmain \"$@\"", "num_lines": 140}
{"repo_name": "aws-parallelcluster", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n_error_exit() {\n   echo \"$1\"\n   exit 1\n}\n\n_info() {\n  echo \"INFO: $1\"\n}\n\n_help() {\n    local -- _cmd=$(basename \"$0\")\n\n    cat <<EOF\n\n  Usage: ${_cmd} [OPTION]...\n\n  Copy the AWS ParallelCluster Package to an S3 bucket.\n\n  --bucket <bucket>             Bucket to upload the package to\n  --srcdir <src-dir>            Root folder of the pcluster project\n  --profile <aws-profile>       AWS profile name to use for the upload\n                                (optional, default is AWS_PROFILE env variable or \"default\").\n  --region <aws-region>         Region to use for AWSCli commands (optional, default is \"us-east-1\")\n  -h, --help                    Print this help message\nEOF\n}\n\nmain() {\n    # parse input options\n    while [ $# -gt 0 ] ; do\n        case \"$1\" in\n            --bucket)           _bucket=\"$2\"; shift;;\n            --bucket=*)         _bucket=\"${1#*=}\";;\n            --srcdir)           _srcdir=\"$2\"; shift;;\n            --srcdir=*)         _srcdir=\"${1#*=}\";;\n            --profile)          _profile=\"$2\"; shift;;\n            --profile=*)        _profile=\"${1#*=}\";;\n            --region)           _region=\"$2\"; shift;;\n            --region=*)         _region=\"${1#*=}\";;\n            -h|--help|help)     _help; exit 0;;\n            *)                  _help; echo \"[error] Unrecognized option '$1'\"; exit 1;;\n        esac\n        shift\n    done\n\n    # verify required parameters\n    if [ -z \"${_bucket}\" ]; then\n        _error_exit \"--bucket parameter not specified\"\n        _help;\n    fi\n    if [ -z \"${_srcdir}\" ]; then\n        _error_exit \"--srcdir parameter not specified\"\n        _help;\n    fi\n\n    # initialize optional parameters\n    if [ -z \"${AWS_PROFILE}\" ] && [ -z \"${_profile}\" ]; then\n        _info \"--profile parameter not specified, using 'default'\"\n    elif [ -n \"${_profile}\" ]; then\n        _profile=\"--profile ${_profile}\"\n    fi\n    if [ -z \"${_region}\" ]; then\n        _info \"--region parameter not specified, using 'us-east-1'\"\n        _region=\"us-east-1\"\n    fi\n\n    # check bucket or create it\n    aws ${_profile} s3api head-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n    if [ $? -ne 0 ]; then\n        _info \"Bucket ${_bucket} does not exist, trying to create it\"\n        aws ${_profile} s3api create-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n        if [ $? -ne 0 ]; then\n            _error_exit \"Unable to create bucket ${_bucket}\"\n        fi\n    fi\n\n    _pcluster_version=$(grep \"^VERSION = \\\"\" \"${_srcdir}/cli/setup.py\" |awk '{print $3}'| tr -d \\\")\n    if [ -z \"${_pcluster_version}\" ]; then\n        _error_exit \"Unable to detect ParallelCluster CLI version, are you in the right directory?\"\n    fi\n    _info \"Detected ParallelCluster CLI version ${_pcluster_version}\"\n\n    _version=$(grep \"^VERSION = \\\"\" \"${_srcdir}/awsbatch-cli/setup.py\" |awk '{print $3}'| tr -d \\\")\n    if [ -z \"${_version}\" ]; then\n        _error_exit \"Unable to detect ParallelCluster AWS Batch CLI version, are you in the right directory?\"\n    fi\n    _info \"Detected ParallelCluster AWS Batch CLI version ${_version}\"\n\n    # Create archive\n    _cwd=$(pwd)\n    pushd \"${_srcdir}\" > /dev/null\n    _stashName=$(git stash create)\n    git archive --format tar --prefix=\"aws-parallelcluster-${_pcluster_version}/\" \"${_stashName:-HEAD}\" | gzip > \"${_cwd}/aws-parallelcluster-${_pcluster_version}.tgz\"\n    popd > /dev/null\n\n    # upload package\n    _key_path=\"parallelcluster/${_pcluster_version}/cli\"\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-${_pcluster_version}.tgz s3://${_bucket}/${_key_path}/aws-parallelcluster-${_pcluster_version}.tgz || _error_exit 'Failed to push CLI to S3'\n\n    _bucket_region=$(aws ${_profile} s3api get-bucket-location --bucket ${_bucket} --output text)\n    if [ ${_bucket_region} == \"None\" ]; then\n        _bucket_region=\"\"\n     else\n         _bucket_region=\".${_bucket_region}\"\n     fi\n\n    echo \"Done. Add the following configuration to the pcluster create config file:\"\n    echo \"\"\n    echo \"DevSettings:\"\n    echo \"  AwsBatchCliPackage: s3://${_bucket}/${_key_path}/aws-parallelcluster-${_pcluster_version}.tgz\"\n}\n\nmain \"$@\"\n\n# vim:syntax=sh\n", "num_lines": 118}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource kitchen/kitchen.local-yml.sh\n\nTHIS_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\nexport KITCHEN_YAML=\"${THIS_DIR}/kitchen.docker.yml\"\nexport KITCHEN_GLOBAL_YAML=\"${THIS_DIR}/kitchen.global.yml\"\nexport KITCHEN_DRIVER=dokken\n\n# Export DOCKER_HOST variable when using Colima\nif [[ $(command -v colima) ]]; then\n  colima status || colima start\n  export DOCKER_HOST=unix://${HOME}/.colima/default/docker.sock\nfi\n\necho \"** KITCHEN_LOCAL_YAML: $KITCHEN_LOCAL_YAML\"\necho \"** KITCHEN_YAML: $KITCHEN_YAML\"\necho \"** KITCHEN_GLOBAL_YAML: $KITCHEN_GLOBAL_YAML\"\necho \"kitchen $*\"\n\nkitchen \"$@\"\n", "num_lines": 22}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables you can set in your local .kitchen.env.sh (not to be pushed)\n#\n# KITCHEN_AWS_REGION:         AWS region;\n#                             falls back to AWS_DEFAULT_REGION, then to eu-west-1\n#\n# KITCHEN_ARCHITECTURE:       [x86_64|arm64];\n#                             default x86_64\n#\n# KITCHEN_INSTANCE_TYPE:      instance type to use\n#                             default t2.micro\n#\n# KITCHEN_KEY_NAME:           KeyPair to use with EC2 instances\n#                             default kitchen\n#\n# KITCHEN_SUBNET_ID:          subnet to put EC2 instance into\n#                             if not set will use Subnet tagged with Kitchen=true\n#\n# KITCHEN_SECURITY_GROUP_ID:  security group to associate to the instance\n#                             if not set will use SG tagged with Kitchen=true\n#\n# KITCHEN_IAM_PROFILE:        IAM instance profile name\n#                             if not set no profile will be attached\n#\n# KITCHEN_USER_DATA_SCRIPT:   user-data script to launch on the instance\n#                             if not set no user-data script will be launched\n#\n# KITCHEN_SSH_KEY_PATH:       path to private key\n#                             default ~/.ssh/${key-name}-${region}.pem\n#\n# KITCHEN_PCLUSTER_VERSION:   ParallelCluster version to use\n#                             defaults to the latest one\n#\n# KITCHEN_ALINUX2_AMI:        specific AMI to use for alinux2\n#                             if not specified, will look for the latest suitable ParallelCluster AMI\n#\n# KITCHEN_RHEL8_AMI:        specific AMI to use for redhat8\n#                             if not specified, will look for the latest suitable ParallelCluster AMI\n#\n# KITCHEN_CENTOS7_AMI:        specific AMI to use for centos7\n#                             if not specified, will look for the latest suitable ParallelCluster AMI\n#\n# KITCHEN_UBUNTU2004_AMI:       specific AMI to use for ubuntu20.04\n#                             if not specified, will look for the latest suitable ParallelCluster AMI\n#\n# KITCHEN_UBUNTU2204_AMI:       specific AMI to use for ubuntu22.04\n#                             if not specified, will look for the latest suitable ParallelCluster AMI\n#\n\nsource kitchen/kitchen.local-yml.sh\n\nTHIS_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\nexport KITCHEN_YAML=\"${THIS_DIR}/kitchen.ec2.yml\"\nexport KITCHEN_GLOBAL_YAML=\"${THIS_DIR}/kitchen.global.yml\"\nexport KITCHEN_DRIVER=ec2\n\nif [ -e \"${THIS_DIR}/.kitchen.env.sh\" ]\nthen\n  echo \"*** Apply local environment\"\n  source \"${THIS_DIR}/.kitchen.env.sh\"\nfi\n\n: \"${KITCHEN_AWS_REGION:=${AWS_DEFAULT_REGION:-eu-west-1}}\"\n: \"${KITCHEN_KEY_NAME:=kitchen}\"\n: \"${KITCHEN_SSH_KEY_PATH:=\"~/.ssh/${KITCHEN_KEY_NAME}-${KITCHEN_AWS_REGION}.pem\"}\"\n: \"${KITCHEN_AVAILABILITY_ZONE:=a}\"\n: \"${KITCHEN_ARCHITECTURE:=x86_64}\"\n\nif [ \"$1\" == \"create\" ] || [ \"$1\" == \"converge\" ] || [ \"$1\" == \"verify\" ] || [ \"$1\" == \"destroy\" ] || [ \"$1\" == \"test\" ]; then\n  # Subnet\n  if [ -z \"${KITCHEN_SUBNET_ID}\" ]; then\n    echo \"** KITCHEN_SUBNET_ID not explicitly set: looking for subnet tagged Kitchen=true\"\n\n    KITCHEN_SUBNET_ID=$(aws ec2 describe-subnets --region \"${KITCHEN_AWS_REGION}\" \\\n        --filters \"Name=tag:Kitchen,Values=true\" \\\n                  \"Name=availability-zone,Values=${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --query 'Subnets[0].SubnetId' --output text)\n\n    echo \"** KITCHEN_SUBNET_ID: ${KITCHEN_SUBNET_ID}\"\n\n    if [ \"${KITCHEN_SUBNET_ID}\" = \"None\" ]; then\n      echo \"Subnet tagged Kitchen=true not found in AZ ${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\"\n      exit 1\n    fi\n  fi\n\n  # VPC\n  if [ -z \"${KITCHEN_VPC_ID}\" ]; then\n    echo \"** KITCHEN_VPC_ID not explicitly set: deriving from subnet\"\n\n    KITCHEN_VPC_ID=$(aws ec2 describe-subnets --region \"${KITCHEN_AWS_REGION}\" \\\n        --subnet-ids \"${KITCHEN_SUBNET_ID}\" \\\n        --query 'Subnets[0].VpcId' --output text)\n\n    echo \"** KITCHEN_VPC_ID: ${KITCHEN_VPC_ID}\"\n  fi\n\n  # Security Group\n  if [ -z \"${KITCHEN_SECURITY_GROUP_ID}\" ]; then\n    echo \"** KITCHEN_SECURITY_GROUP_ID not explicitly set\"\n\n    if [ -z \"${KITCHEN_SECURITY_GROUP_NAME}\" ]; then\n      echo \"** KITCHEN_SECURITY_GROUP_NAME not explicitly set, looking for tag Kitchen=true\"\n\n      KITCHEN_SECURITY_GROUP_ID=$(aws ec2 describe-security-groups --region \"${KITCHEN_AWS_REGION}\" \\\n                  --filters \"Name=tag:Kitchen,Values=true\" \"Name=vpc-id,Values=${KITCHEN_VPC_ID}\" \\\n                  --query 'SecurityGroups[0].GroupId' --output text)\n    else\n      echo \"** Looking for SG named ${KITCHEN_SECURITY_GROUP_NAME}\"\n\n      KITCHEN_SECURITY_GROUP_ID=$(aws ec2 describe-security-groups --region \"${KITCHEN_AWS_REGION}\" \\\n                  --filters \"Name=vpc-id,Values=${KITCHEN_VPC_ID}\" \"Name=group-name,Values=${KITCHEN_SECURITY_GROUP_NAME}\" \\\n                  --query 'SecurityGroups[0].GroupId' --output text)\n    fi\n\n    echo \"** KITCHEN_SECURITY_GROUP_ID: ${KITCHEN_SECURITY_GROUP_ID}\"\n\n  fi\nfi\n\nexport KITCHEN_AWS_REGION\nexport KITCHEN_KEY_NAME\nexport KITCHEN_SSH_KEY_PATH\nexport KITCHEN_AVAILABILITY_ZONE\nexport KITCHEN_ARCHITECTURE\nexport KITCHEN_INSTANCE_TYPE\nexport KITCHEN_SUBNET_ID\nexport KITCHEN_VPC_ID\nexport KITCHEN_SECURITY_GROUP_ID\n\necho \"** KITCHEN_AWS_REGION: ${KITCHEN_AWS_REGION}\"\necho \"** KITCHEN_KEY_NAME: ${KITCHEN_KEY_NAME}\"\necho \"** KITCHEN_SSH_KEY_PATH: ${KITCHEN_SSH_KEY_PATH}\"\necho \"** KITCHEN_AVAILABILITY_ZONE: ${KITCHEN_AVAILABILITY_ZONE}\"\necho \"** KITCHEN_ARCHITECTURE: ${KITCHEN_ARCHITECTURE}\"\necho \"** KITCHEN_INSTANCE_TYPE: ${KITCHEN_INSTANCE_TYPE}\"\necho \"** KITCHEN_SUBNET_ID: ${KITCHEN_SUBNET_ID}\"\necho \"** KITCHEN_VPC_ID: ${KITCHEN_VPC_ID}\"\necho \"** KITCHEN_SECURITY_GROUP_ID: ${KITCHEN_SECURITY_GROUP_ID}\"\necho \"** KITCHEN_IAM_PROFILE: ${KITCHEN_IAM_PROFILE}\"\necho \"** KITCHEN_LOCAL_YAML: ${KITCHEN_LOCAL_YAML}\"\necho \"** KITCHEN_YAML: $KITCHEN_YAML\"\necho \"** KITCHEN_GLOBAL_YAML: $KITCHEN_GLOBAL_YAML\"\necho \"kitchen $*\"\n\nkitchen \"$@\"\n", "num_lines": 149}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the\n# License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n. /etc/parallelcluster/cfnconfig\n\nLVM_VG_NAME=\"vg.01\"\nLVM_NAME=\"lv_ephemeral\"\nLVM_PATH=\"/dev/${LVM_VG_NAME}/${LVM_NAME}\"\nLVM_ACTIVE_STATE=\"a\"\nFS_TYPE=\"ext4\"\nMOUNT_OPTIONS=\"noatime,nodiratime\"\n# cfn_ephemeral_dir is set in the environment by cfnconfig sourcing\nINPUT_MOUNTPOINT=\"${cfn_ephemeral_dir}\"\n\nfunction log {\n  SCRIPT=$(basename \"$0\")\n  MESSAGE=\"$1\"\n  echo \"ParallelCluster - ${MESSAGE}\"\n}\n\nfunction error_exit {\n  log \"[ERROR] $1\"\n  exit 1\n}\n\nfunction exit_noop {\n  log \"[INFO] $1\"\n  exit 0\n}\n\nfunction parameter_check {\n  if [[ -z \"${INPUT_MOUNTPOINT}\" ]]; then\n    exit_noop \"Mount point not specified\"\n  fi\n}\n\nfunction set_imds_token {\n  if [[ -z \"${IMDS_TOKEN}\" ]];then\n    IMDS_TOKEN=$(curl --retry 3 --retry-delay 0 --fail -s -f -X PUT -H \"X-aws-ec2-metadata-token-ttl-seconds: 900\" http://169.254.169.254/latest/api/token)\n    if [[ \"$?\" -gt 0 ]] || [[ -z \"${IMDS_TOKEN}\" ]]; then\n      error_exit \"Could not get IMDSv2 token. Instance Metadata might have been disabled or this is not an EC2 instance\"\n    fi\n  fi\n}\n\nfunction get_metadata {\n    QUERY=$1\n    local IMDS_OUTPUT\n    IMDS_OUTPUT=$(curl --retry 3 --retry-delay 0 --fail -s -q -H \"X-aws-ec2-metadata-token:${IMDS_TOKEN}\" -f \"http://169.254.169.254/latest/${QUERY}\")\n    echo -n \"${IMDS_OUTPUT}\"\n}\n\nfunction print_block_device_mapping {\n  echo 'block-device-mapping: '\n  DEVICE_MAPPING_LIST=$(get_metadata meta-data/block-device-mapping/)\n  if [[ -n \"${DEVICE_MAPPING_LIST}\" ]]; then\n    for DEVICE_MAPPING in ${DEVICE_MAPPING_LIST}; do\n      echo -e '\\t' \"${DEVICE_MAPPING}: $(get_metadata meta-data/block-device-mapping/\"${DEVICE_MAPPING}\")\"\n    done\n  else\n    echo \"NOT AVAILABLE\"\n  fi\n}\n\nfunction check_instance_store {\n  if ls /dev/nvme* >& /dev/null; then\n    IS_NVME=1\n    MAPPINGS=$(realpath --relative-to=/dev/ -P /dev/disk/by-id/nvme*Instance_Storage* | grep -v \"*Instance_Storage*\" | uniq)\n  else\n    IS_NVME=0\n    set_imds_token\n    MAPPINGS=$(print_block_device_mapping | grep ephemeral | awk '{print $2}' | sed 's/sd/xvd/')\n  fi\n\n  NUM_DEVICES=0\n  for MAPPING in ${MAPPINGS}; do\n    umount \"/dev/${MAPPING}\" &>/dev/null\n    STAT_COMMAND=\"stat -t /dev/${MAPPING}\"\n    if ${STAT_COMMAND} &>/dev/null; then\n      DEVICES+=(\"/dev/${MAPPING}\")\n      NUM_DEVICES=$((NUM_DEVICES + 1))\n    fi\n  done\n\n  if [[ \"${NUM_DEVICES}\" -gt 0 ]]; then\n    log \"This instance type has (${NUM_DEVICES}) device(s) for instance store: (${DEVICES[*]})\"\n  else\n    exit_noop \"This instance type doesn't have instance store\"\n  fi\n\n  if [[ \"${IS_NVME}\" -eq 0 ]]; then\n    log \"This instance store may suffer first-write penalty unless initialized: please have a look at https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/disk-performance.html\"\n    # Initialization can take long time, even hours\n    # for DEVICE in \"${DEVICES[@]}\"; do\n    #  dd if=/dev/zero of=\"${DEVICE}\" bs=1M\n    # done\n  fi\n}\n\nfunction create_lvm {\n  log \"Creating LVM (${LVM_PATH})\"\n  pvcreate -y \"${DEVICES[@]}\"\n  vgcreate -y \"${LVM_VG_NAME}\" \"${DEVICES[@]}\"\n  LVM_CREATE_COMMAND=\"lvcreate -y -i ${NUM_DEVICES} -I 64 -l 100%FREE -n ${LVM_NAME} ${LVM_VG_NAME}\"\n  if ! ${LVM_CREATE_COMMAND}; then\n    error_exit \"Failed to create LVM\"\n  else\n    log \"LVM (${LVM_PATH}) created successfully\"\n  fi\n}\n\nfunction check_lvm_exist {\n  LVM_EXIST_COMMAND=\"lvs ${LVM_PATH} --nosuffix --noheadings -q\"\n\n  if ! ${LVM_EXIST_COMMAND} &>/dev/null; then\n    log \"LVM (${LVM_PATH}) does not exist\"\n    create_lvm\n  else\n    log \"LVM (${LVM_PATH}) already exists\"\n  fi\n}\n\nfunction activate_lvm {\n  LVM_STATE=$(lvs \"${LVM_PATH}\" --nosuffix --noheadings -o lv_attr | xargs | cut -c5)\n  log \"Found LVM (${LVM_PATH}) in state (${LVM_STATE})\"\n\n  if [[ \"${LVM_STATE}\" != \"${LVM_ACTIVE_STATE}\" ]]; then\n    log \"Activating LVM (${LVM_PATH})\"\n    LVM_ACTIVATE_COMMAND=\"lvchange -ay ${LVM_PATH}\"\n    if ! ${LVM_ACTIVATE_COMMAND}; then\n      error_exit \"Failed to activate LVM\"\n    else\n      log \"LVM (${LVM_PATH}) activated successfully\"\n    fi\n  fi\n}\n\nfunction format_lvm {\n  LVM_FS_TYPE=$(lsblk \"${LVM_PATH}\" --noheadings -o FSTYPE | xargs)\n  log \"Found LVM (${LVM_PATH}) FS type (${LVM_FS_TYPE})\"\n\n  if [[ \"${LVM_FS_TYPE}\" != \"${FS_TYPE}\" ]]; then\n    log \"Formatting LVM (${LVM_PATH}) with FS type (${FS_TYPE})\"\n    LVM_FORMAT_COMMAND=\"mkfs -t ${FS_TYPE} ${LVM_PATH}\"\n    if ! ${LVM_FORMAT_COMMAND}; then\n      error_exit \"Failed to format LVM\"\n    else\n      log \"LVM (${LVM_PATH}) formatted successfully\"\n    fi\n    sync\n    sleep 1\n  else\n    log \"LVM (${LVM_PATH}) already formatted with FS type (${LVM_FS_TYPE})\"\n  fi\n}\n\nfunction mount_lvm {\n  LVM_MOUNTPOINT=$(lsblk \"${LVM_PATH}\" -o MOUNTPOINT --noheadings | xargs)\n\n  if [[ -z ${LVM_MOUNTPOINT} ]]; then\n    log \"LVM (${LVM_PATH}) not mounted, mounting on (${INPUT_MOUNTPOINT})\"\n    # create mount\n    mkdir -p \"${INPUT_MOUNTPOINT}\"\n    LVM_MOUNT_COMMAND=\"mount -v -t ${FS_TYPE} -o ${MOUNT_OPTIONS} ${LVM_PATH} ${INPUT_MOUNTPOINT}\"\n    if ! ${LVM_MOUNT_COMMAND}; then\n      error_exit \"Failed to mount LVM\"\n    else\n      log \"LVM (${LVM_PATH}) mounted successfully\"\n    fi\n    # set mount permission\n    chmod 1777 \"${INPUT_MOUNTPOINT}\"\n  else\n    log \"LVM (${LVM_PATH}) already mounted on (${LVM_MOUNTPOINT})\"\n  fi\n}\n\nfunction main {\n  parameter_check\n  check_instance_store\n  check_lvm_exist\n  activate_lvm\n  format_lvm\n  mount_lvm\n}\n\nmain\n", "num_lines": 195}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Configure a specific Network Interface according to the OS\n# The configuration involves 3 aspects:\n# - Main configuration (IP address, protocol and gateway)\n# - A specific routing table, so that all traffic coming to a network interface leaves the instance using the same\n#   interface\n# - A routing rule to make the OS use the specific routing table for this network interface\n\nset -e\n\nif\n  [ -z \"${DEVICE_NAME}\" ] ||          # name of the device\n  [ -z \"${DEVICE_NUMBER}\" ] ||        # number of the device\n  [ -z \"${GW_IP_ADDRESS}\" ] ||        # gateway ip address\n  [ -z \"${DEVICE_IP_ADDRESS}\" ] ||    # ip address to assign to the interface\n  [ -z \"${CIDR_PREFIX_LENGTH}\" ] ||   # the prefix length of the device IP cidr block\n  [ -z \"${NETMASK}\" ]                 # netmask to apply to device ip address\nthen\n  echo 'One or more environment variables missing'\n  exit 1\nfi\n\nROUTE_TABLE=\"100${DEVICE_NUMBER}\"\n\necho \"Configuring ${DEVICE_NAME} with IP:${DEVICE_IP_ADDRESS} CIDR_PREFIX:${CIDR_PREFIX_LENGTH} NETMASK:${NETMASK} GW:${GW_IP_ADDRESS} ROUTING_TABLE:${ROUTE_TABLE}\"\n\n# config file\nFILE=\"/etc/sysconfig/network-scripts/ifcfg-${DEVICE_NAME}\"\nif [ ! -f \"$FILE\" ]; then\n/bin/cat <<EOF >${FILE}\nDEVICE=${DEVICE_NAME}\nTYPE=Ethernet\nONBOOT=yes\nBOOTPROTO=none\nIPADDR=${DEVICE_IP_ADDRESS}\nPREFIX=${CIDR_PREFIX_LENGTH}\nGATEWAY=${GW_IP_ADDRESS}\nMTU=\"9001\"\nIPV4_FAILURE_FATAL=yes\nNAME=\"System ${DEVICE_NAME}\"\nEOF\nfi\n\n# route file\nFILE=\"/etc/sysconfig/network-scripts/route-${DEVICE_NAME}\"\nif [ ! -f \"$FILE\" ]; then\n/bin/cat <<EOF >${FILE}\ndefault via ${GW_IP_ADDRESS} dev ${DEVICE_NAME} table ${ROUTE_TABLE}\ndefault via ${GW_IP_ADDRESS} dev ${DEVICE_NAME} metric ${ROUTE_TABLE}\n${DEVICE_IP_ADDRESS} dev ${DEVICE_NAME} table ${ROUTE_TABLE}\nEOF\nfi\n\n# rule file\nFILE=\"/etc/sysconfig/network-scripts/rule-${DEVICE_NAME}\"\nif [ ! -f \"$FILE\" ]; then\n/bin/cat <<EOF >${FILE}\nfrom ${DEVICE_IP_ADDRESS} lookup ${ROUTE_TABLE}\nEOF\nfi", "num_lines": 60}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n#\n# Manage the access to IMDS\n#\n# --allow <user1,...,userN>   List of users to allow access to IMDS\n# --deny  <user1,...,userN>   List of users to deny access to IMDS\n# --unset <user1,...,userN>   Remove iptables rules related to IMDS for the given list of users\n# --flush                     Restore default IMDS access\n# --help                      Print this help message\n\nfunction error() {\n  >&2 echo \"[ERROR] $1\"\n  exit 1\n}\n\nfunction info() {\n  echo \"[INFO] $1\"\n}\n\nfunction help() {\n  local -- cmd=$(basename \"$0\")\n  cat <<EOF\n\n  Usage: ${cmd} [OPTION]...\n\n  Manage the access to IMDS\n\n  --allow <user1,...,userN>   Allow IMDS access to the given list of users\n  --deny  <user1,...,userN>   Deny IMDS access to the given list of users\n  --unset <user1,...,userN>   Remove iptables rules related to IMDS for the given list of users\n  --flush                     Restore default IMDS access\n  --help                      Print this help message\nEOF\n}\n\nfunction iptables_delete() {\n  local iptables_command=$1\n  local chain=$2\n  local destination=$3\n  local jump=$4\n  local user=$5\n\n  # Build iptables delete command\n  if [[ -z $user ]]; then\n    rule_args=\"$chain --destination $destination -j $jump\"\n  else\n    rule_args=\"$chain --destination $destination -j $jump -m owner --uid-owner $user\"\n  fi\n\n  local iptables_delete_command=\"$iptables_command -D $rule_args\"\n\n  # Remove rules\n  local should_remove=true\n  while $should_remove; do\n    eval $iptables_delete_command 1>/dev/null 2>/dev/null || should_remove=false\n  done\n}\n\nfunction iptables_add() {\n  local iptables_command=$1\n  local chain=$2\n  local destination=$3\n  local jump=$4\n  local user=$5\n\n  # Remove duplicate rules\n  iptables_delete $iptables_command $chain $destination $jump $user\n\n  # Remove opposite rules\n  if [[ $jump == \"ACCEPT\" ]]; then\n    iptables_delete $iptables_command $destination \"REJECT\" $user\n  elif [[ $jump == \"REJECT\" ]]; then\n    iptables_delete $iptables_command $destination \"ACCEPT\" $user\n  fi\n\n  # Build iptables add command\n  if [[ -z $user ]]; then\n    rule_args=\"$chain --destination $destination -j $jump\"\n  else\n    rule_args=\"$chain --destination $destination -j $jump -m owner --uid-owner $user\"\n  fi\n\n  local iptables_add_command=\"$iptables_command -A $rule_args\"\n\n  # Add rule\n  eval $iptables_add_command\n  info \"Rule in chain $chain: $destination $jump $user\"\n}\n\nfunction setup_chain() {\n  local iptables_command=$1\n  local chain=$2\n  local source_chain=$3\n  local destination=$4\n\n  $iptables_command --new $chain 2>/dev/null && info \"ParallelCluster chain created: $chain\" \\\n  || info \"ParallelCluster chain exists: $chain\"\n\n  iptables_add $iptables_command $source_chain $destination $chain\n}\n\nmain() {\n  # Constants\n  PARALLELCLUSTER_CHAIN=\"PARALLELCLUSTER_IMDS\"\n  OUTPUT_CHAIN=\"OUTPUT\"\n  IMDS_IP=\"169.254.169.254\"\n  IMDS_IP6=\"fd00:ec2::254\"\n  IPTABLE_CMD=\"iptables\"\n  IPTABLE_CMD_V6=\"ip6tables\"\n\n  # Parse options\n  while [ $# -gt 0 ] ; do\n      case \"$1\" in\n          --allow)    allow_users=\"$2\"; shift;;\n          --deny)     deny_users=\"$2\"; shift;;\n          --unset)    unset_users=\"$2\"; shift;;\n          --flush)    flush=\"true\";;\n          --help)     help; exit 0;;\n          *)          help; error \"Unrecognized option '$1'\";;\n      esac\n      shift\n  done\n\n  IFS=\",\"\n  for ip_version_address in $IPTABLE_CMD,$IMDS_IP $IPTABLE_CMD_V6,$IMDS_IP6\n  do\n    set -- $ip_version_address\n    iptables_command=$1\n    ip=$2\n\n    # Check required commands\n    command -v $iptables_command >/dev/null || error \"Cannot find required command: $iptables_command\"\n\n    # Check arguments and options\n    if [[ -z $allow_users && -z $deny_users && -z $unset_users && -z $flush ]]; then\n      error \"Missing at least one mandatory option: '--allow', '--deny', '--unset', '--flush'\"\n    fi\n\n    # Setup ParallelCluster chain\n    setup_chain $iptables_command $PARALLELCLUSTER_CHAIN $OUTPUT_CHAIN $ip\n\n    # Flush ParallelCluster chain, if required\n    if [[ $flush == \"true\" ]]; then\n      $iptables_command --flush $PARALLELCLUSTER_CHAIN\n      info \"ParallelCluster chain flushed\"\n      exit 0\n    fi\n\n    # Delete rule: ACCEPT/REJECT user, for every user to unset\n    for user in $unset_users; do\n      info \"Deleting rules related to IMDS access for user: $user\"\n      iptables_delete $iptables_command $PARALLELCLUSTER_CHAIN $ip \"ACCEPT\" $user\n      iptables_delete $iptables_command $PARALLELCLUSTER_CHAIN $ip \"REJECT\" $user\n    done\n\n    # Add rule: ACCEPT user, for every allowed user\n    for user in $allow_users; do\n      info \"Allowing IMDS access for user: $user\"\n      iptables_add $iptables_command $PARALLELCLUSTER_CHAIN $ip \"ACCEPT\" $user\n    done\n\n    # Add rule: REJECT user, for every denied user\n    for user in $deny_users; do\n      info \"Denying IMDS access for user: $user\"\n      iptables_add $iptables_command $PARALLELCLUSTER_CHAIN $ip \"REJECT\" $user\n    done\n\n    # Add rule: REJECT not allowed users\n    info \"Denying IMDS access for not allowed users\"\n    iptables_add $iptables_command $PARALLELCLUSTER_CHAIN $ip \"REJECT\"\n  done\n}\n\nmain \"$@\"\n", "num_lines": 176}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Configure a specific Network Interface according to the OS\n# The configuration involves 3 aspects:\n# - Main configuration (IP address, protocol and gateway)\n# - A specific routing table, so that all traffic coming to a network interface leaves the instance using the same\n#   interface\n# - A routing rule to make the OS use the specific routing table for this network interface\n\n# RedHat 8 official documentation:\n# https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/8/html/configuring_and_managing_networking/configuring-policy-based-routing-to-define-alternative-routes_configuring-and-managing-networking\n\nset -e\n\nif\n  [ -z \"${DEVICE_NAME}\" ] ||          # name of the device\n  [ -z \"${DEVICE_NUMBER}\" ] ||        # number of the device\n  [ -z \"${GW_IP_ADDRESS}\" ] ||        # gateway ip address\n  [ -z \"${DEVICE_IP_ADDRESS}\" ] ||    # ip address to assign to the interface\n  [ -z \"${CIDR_PREFIX_LENGTH}\" ]      # the prefix length of the device IP cidr block\nthen\n  echo 'One or more environment variables missing'\n  exit 1\nfi\n\ncon_name=\"System ${DEVICE_NAME}\"\nroute_table=\"100${DEVICE_NUMBER}\"\npriority=\"100${DEVICE_NUMBER}\"\nmetric=\"100${DEVICE_NUMBER}\"\n\n# Rename connection\noriginal_con_name=`nmcli -t -f GENERAL.CONNECTION device show ${DEVICE_NAME} | cut -f2 -d':'`\nsudo nmcli connection modify \"${original_con_name}\" con-name \"${con_name}\" ifname ${DEVICE_NAME}\n\nconfigured_ip=`nmcli -t -f IP4.ADDRESS device show ${DEVICE_NAME} | cut -f2 -d':'`\nif [ -z \"${configured_ip}\" ]; then\n  # Setup connection method to \"manual\", configure ip address and gateway, only if not already configured.\n  sudo nmcli connection modify \"${con_name}\" ipv4.method manual ipv4.addresses ${DEVICE_IP_ADDRESS}/${CIDR_PREFIX_LENGTH} ipv4.gateway ${GW_IP_ADDRESS}\nfi\n\n# Setup routes\n# This command uses the ipv4.routes parameter to add a static route to the routing table with ID ${route_table}.\n# This static route for 0.0.0.0/0 uses the IP of the gateway as next hop.\nsudo nmcli connection modify \"${con_name}\" ipv4.routes \"0.0.0.0/0 ${GW_IP_ADDRESS} ${metric} table=${route_table}\"\n\n# Setup routing rules\n# The command uses the ipv4.routing-rules parameter to add a routing rule with priority ${priority} that routes\n# traffic from ${DEVICE_IP_ADDRESS} to table ${route_table}. Low values have a high priority.\n# The syntax in the ipv4.routing-rules parameter is the same as in an \"ip rule add\" command,\n# except that ipv4.routing-rules always requires specifying a priority.\nsudo nmcli connection modify \"${con_name}\" ipv4.routing-rules \"priority ${priority} from ${DEVICE_IP_ADDRESS} table ${route_table}\"\n\n# Reapply previous connection modification.\nsudo nmcli device reapply ${DEVICE_NAME}\n", "num_lines": 54}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Configure a specific Network Interface according to the OS\n# The configuration involves 3 aspects:\n# - Main configuration (IP address, protocol and gateway)\n# - A specific routing table, so that all traffic coming to a network interface leaves the instance using the same\n#   interface\n# - A routing rule to make the OS use the specific routing table for this network interface\n\nset -e\n\nif\n  [ -z \"${DEVICE_NAME}\" ] ||          # name of the device\n  [ -z \"${DEVICE_NUMBER}\" ] ||        # number of the device\n  [ -z \"${GW_IP_ADDRESS}\" ] ||        # gateway ip address\n  [ -z \"${DEVICE_IP_ADDRESS}\" ] ||    # ip address to assign to the interface\n  [ -z \"${CIDR_PREFIX_LENGTH}\" ] ||   # the prefix length of the device IP cidr block\n  [ -z \"${NETMASK}\" ] ||              # netmask to apply to device ip address\n  [ -z \"${CIDR_BLOCK}\" ]              # (full) subnet cidr block\nthen\n  echo 'One or more environment variables missing'\n  exit 1\nfi\n\nSTATIC_IP_CONFIG=$(cat<<END\n      addresses:\n       - ${DEVICE_IP_ADDRESS}/${CIDR_PREFIX_LENGTH}\n      dhcp4: no\nEND\n)\n\n# NOTE: In Ubuntu 20.04 all network interfaces are already configured in 50-cloud-init.yaml with dhcp4 enabled.\n# However, the specific configuration files created below (in the same way of Ubuntu 18) will override these initial\n# settings, as can be verified with the command `netplan get`\ngrep \"${DEVICE_NAME}:\" /etc/netplan/50-cloud-init.yaml 1>/dev/null && STATIC_IP_CONFIG=\"\"\nif [ \"${STATIC_IP_CONFIG}\" = \"\" ]\n  then\n    echo \"Device ${DEVICE_NAME} is dhcp managed in current platform\"\n  else\n    echo \"Device ${DEVICE_NAME} IP address will be set to ${DEVICE_IP_ADDRESS}\"\nfi\n\nFILE=\"/etc/netplan/${DEVICE_NAME}.yaml\"\nROUTE_TABLE=\"100${DEVICE_NUMBER}\"\n\necho \"Configuring ${DEVICE_NAME} with IP:${DEVICE_IP_ADDRESS} CIDR_PREFIX:${CIDR_PREFIX_LENGTH} NETMASK:${NETMASK} GW:${GW_IP_ADDRESS} ROUTING_TABLE:${ROUTE_TABLE}\"\n\n/bin/cat <<EOF >${FILE}\nnetwork:\n  version: 2\n  renderer: networkd\n  ethernets:\n    ${DEVICE_NAME}:\n$STATIC_IP_CONFIG\n      mtu: '9001'\n      routes:\n       - to: 0.0.0.0/0\n         via: ${GW_IP_ADDRESS} # Default gateway\n         table: ${ROUTE_TABLE}\n       - to: 0.0.0.0/0\n         via: ${GW_IP_ADDRESS} # Default gateway\n         metric: ${ROUTE_TABLE}\n       - to: ${DEVICE_IP_ADDRESS}\n         via: 0.0.0.0\n         scope: link\n         table: ${ROUTE_TABLE}\n      routing-policy:\n        - from: ${DEVICE_IP_ADDRESS}\n          table: ${ROUTE_TABLE}\nEOF\n\n# Hook to delete automatic routes to subnet automatically created from kernel.\n# This is needed in Ubuntu 18 because they are generated in the reverse order in which the network interfaces are\n# attached and this prevents the primary Network Interface from being selected to communicate in the subnet.\n# In Ubuntu 20 this hook is needed as well for a slightly different reason. Automatic routes here are\n# already present due to cloud-init initialization and we need to remove them to make sure that the primary Network\n# Interface is selected when opening connections to the subnet\nFILE=\"/etc/networkd-dispatcher/routable.d/cleanup-routes.sh\"\n\nif [ ! -f \"$FILE\" ]; then\n/bin/cat <<EOF >${FILE}\n#!/bin/sh\n\nlogger -t parallelcluster \"Removing Automatic route for Interface: \\${IFACE}\"\nip route del ${CIDR_BLOCK} dev \\${IFACE}\nlogger -t parallelcluster \"Automatic route removed for Interface: \\${IFACE}\"\nEOF\n\n# The hook script file must be executable and owned by root\nchmod 755 ${FILE}\nfi\n", "num_lines": 91}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** post_create\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n\nRESOURCE_NAME=ebs_mount-vol_array\n\necho \"** Creating EBS volume...\"\n\nKITCHEN_EBS_VOLUME_ID=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume created: ${KITCHEN_EBS_VOLUME_ID}\"\n\nsed -i.bak \"s#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => .*,#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => %w(${KITCHEN_EBS_VOLUME_ID}),#\" \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\"\n", "num_lines": 21}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** pre_destroy\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n[ -n \"${KITCHEN_INSTANCE_HOSTNAME}\" ] || exit 0\n\nRESOURCE_NAME=ebs_mount-vol_array\n\nKITCHEN_EBS_VOLUME_ID=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\)),/\\1/p\")\n[ -z \"${KITCHEN_EBS_VOLUME_ID}\" ] && echo \"Volume not available. Skipping pre_destroy hook.\" && exit 0\n\necho \"** Deleting EBS volume ${KITCHEN_EBS_VOLUME_ID}\"\n\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID} detached\"\n\naws ec2 wait volume-available --volume-ids ${KITCHEN_EBS_VOLUME_ID} --region \"${KITCHEN_AWS_REGION}\"\n\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volumes ${KITCHEN_EBS_VOLUME_ID} deleted\"\n", "num_lines": 22}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** post_create\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n\nRESOURCE_NAME=ebs_unmount-vol_array\n\necho \"** Creating EBS volume...\"\n\nKITCHEN_EBS_VOLUME_ID=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume created: ${KITCHEN_EBS_VOLUME_ID}\"\n\nsed -i.bak \"s#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => .*,#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => %w(${KITCHEN_EBS_VOLUME_ID}),#\" \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\"\n", "num_lines": 21}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** pre_destroy\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n[ -n \"${KITCHEN_INSTANCE_HOSTNAME}\" ] || exit 0\n\nRESOURCE_NAME=ebs_unmount-vol_array\n\nKITCHEN_EBS_VOLUME_ID=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\)),/\\1/p\")\n[ -z \"${KITCHEN_EBS_VOLUME_ID}\" ] && echo \"Volume not available. Skipping pre_destroy hook.\" && exit 0\n\necho \"** Deleting EBS volume ${KITCHEN_EBS_VOLUME_ID}\"\n\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID} detached\"\n\naws ec2 wait volume-available --volume-ids ${KITCHEN_EBS_VOLUME_ID} --region \"${KITCHEN_AWS_REGION}\"\n\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volumes ${KITCHEN_EBS_VOLUME_ID} deleted\"\n", "num_lines": 22}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** post_create\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || return\n\necho \"** Creating ENI...\"\n\nKITCHEN_ENI_ID=$(aws ec2 create-network-interface --region \"${KITCHEN_AWS_REGION}\" \\\n    --description \"Kitchen tests ENI for ${KITCHEN_SUITE_NAME} on ${KITCHEN_EC2_INSTANCE_ID}\" \\\n    --subnet-id \"${KITCHEN_SUBNET_ID}\" \\\n    --groups \"${KITCHEN_SECURITY_GROUP_ID}\" \\\n    --tag-specifications \"ResourceType=network-interface,Tags=[{Key=Kitchen, Value=true}]\" \\\n    --query \"NetworkInterface.NetworkInterfaceId\" --output text)\n\necho \"** ENI created: ${KITCHEN_ENI_ID}\"\n\naws ec2 attach-network-interface --region \"${KITCHEN_AWS_REGION}\" \\\n    --device-index 1 --instance-id \"${KITCHEN_EC2_INSTANCE_ID}\" \\\n    --network-interface-id \"${KITCHEN_ENI_ID}\" \\\n    --network-card-index 1\n", "num_lines": 22}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** pre_destroy\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || return\n[ -z \"${KITCHEN_EC2_INSTANCE_ID}\" ] && echo \"EC2 instance not available. Skipping pre_destroy hook.\" && exit 0\n\nread KITCHEN_ENI_ID KITCHEN_ATTACHMENT_ID <<< \"$(aws ec2 describe-instances --instance-ids \"${KITCHEN_EC2_INSTANCE_ID}\" \\\n    --query \"Reservations[0].Instances[0].NetworkInterfaces[?Attachment.DeviceIndex==\\`1\\`].[NetworkInterfaceId, Attachment.AttachmentId]\" \\\n    --region \"${KITCHEN_AWS_REGION}\" --output text)\"\n\nif [ -n \"${KITCHEN_ATTACHMENT_ID}\" ]; then\n  echo \"** Detaching ENI: ${KITCHEN_ATTACHMENT_ID}\"\n  aws ec2 detach-network-interface --attachment-id \"${KITCHEN_ATTACHMENT_ID}\" --region \"${KITCHEN_AWS_REGION}\"\nfi\n\nif [ -n \"${KITCHEN_ENI_ID}\" ]; then\n  echo \"** Waiting for ENI to be detached: ${KITCHEN_ENI_ID}\"\n  aws ec2 wait network-interface-available --network-interface-ids \"${KITCHEN_ENI_ID}\" --region \"${KITCHEN_AWS_REGION}\"\n\n  echo \"** Deleting ENI: ${KITCHEN_ENI_ID}\"\n  aws ec2 delete-network-interface --network-interface-id \"${KITCHEN_ENI_ID}\" --region \"${KITCHEN_AWS_REGION}\"\nfi\n", "num_lines": 24}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** post_create\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || return\n\nRESOURCE_NAME=raid_mount-raid_vol_array\n\necho \"** Creating 2 EBS volumes...\"\n\nKITCHEN_EBS_VOLUME_ID1=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume 1 created: ${KITCHEN_EBS_VOLUME_ID1}\"\n\nKITCHEN_EBS_VOLUME_ID2=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume 2 created: ${KITCHEN_EBS_VOLUME_ID2}\"\n\nsed -i.bak \"s#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => .*,#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => %w(${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2}),#\" \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\"\n", "num_lines": 30}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** pre_destroy\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n[ -n \"${KITCHEN_INSTANCE_HOSTNAME}\" ] || exit 0\n\nRESOURCE_NAME=raid_mount-raid_vol_array\n\nKITCHEN_EBS_VOLUME_ID1=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\) \\(.*\\)),/\\1/p\")\nKITCHEN_EBS_VOLUME_ID2=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\) \\(.*\\)),/\\2/p\")\n[ -z \"${KITCHEN_EBS_VOLUME_ID1}\" ] && [ -z \"${KITCHEN_EBS_VOLUME_ID2}\" ] && echo \"Volumes not available. Skipping pre_destroy hook.\" && exit 0\n\necho \"** Deleting EBS volumes ${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2}\"\n\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID1}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID1} detached\"\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID2}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID2} detached\"\n\naws ec2 wait volume-available --volume-ids ${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2} --region \"${KITCHEN_AWS_REGION}\"\n\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID1}\" --region \"${KITCHEN_AWS_REGION}\"\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID2}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volumes ${KITCHEN_EBS_VOLUME_ID1} and ${KITCHEN_EBS_VOLUME_ID2} deleted\"\n", "num_lines": 26}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** post_create\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || return\n\nRESOURCE_NAME=raid_unmount-raid_vol_array\n\necho \"** Creating 2 EBS volumes...\"\n\nKITCHEN_EBS_VOLUME_ID1=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume 1 created: ${KITCHEN_EBS_VOLUME_ID1}\"\n\nKITCHEN_EBS_VOLUME_ID2=$(aws ec2 create-volume \\\n        --region \"${KITCHEN_AWS_REGION}\" \\\n        --availability-zone \"${KITCHEN_AWS_REGION}${KITCHEN_AVAILABILITY_ZONE}\" \\\n        --size 1 \\\n        --tag-specifications \"ResourceType=volume,Tags=[{Key=Kitchen, Value=true},{Key=Platform, Value=${KITCHEN_PLATFORM_NAME}},{Key=ResourceName, Value=${RESOURCE_NAME}}]\" \\\n        --query \"VolumeId\" --output text)\n\necho \"** EBS volume 2 created: ${KITCHEN_EBS_VOLUME_ID2}\"\n\nsed -i.bak \"s#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => .*,#'${RESOURCE_NAME}/${KITCHEN_PLATFORM_NAME}' => %w(${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2}),#\" \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\"\n", "num_lines": 30}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"**** pre_destroy\"\n\n[[ \"${KITCHEN_DRIVER}\" = \"ec2\" ]] || exit 0\n[ -n \"${KITCHEN_INSTANCE_HOSTNAME}\" ] || exit 0\n\nRESOURCE_NAME=raid_unmount-raid_vol_array\n\nKITCHEN_EBS_VOLUME_ID1=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\) \\(.*\\)),/\\1/p\")\nKITCHEN_EBS_VOLUME_ID2=$(cat \"${KITCHEN_ROOT_DIR}/test/environments/kitchen.rb\" | sed -n -e \"s/.*'${RESOURCE_NAME}\\/${KITCHEN_PLATFORM_NAME}' => %w(\\(.*\\) \\(.*\\)),/\\2/p\")\n[ -z \"${KITCHEN_EBS_VOLUME_ID1}\" ] && [ -z \"${KITCHEN_EBS_VOLUME_ID2}\" ] && echo \"Volumes not available. Skipping pre_destroy hook.\" && exit 0\n\necho \"** Deleting EBS volumes ${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2}\"\n\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID1}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID1} detached\"\naws ec2 detach-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID2}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volume ${KITCHEN_EBS_VOLUME_ID2} detached\"\n\naws ec2 wait volume-available --volume-ids ${KITCHEN_EBS_VOLUME_ID1} ${KITCHEN_EBS_VOLUME_ID2} --region \"${KITCHEN_AWS_REGION}\"\n\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID1}\" --region \"${KITCHEN_AWS_REGION}\"\naws ec2 delete-volume --volume-id \"${KITCHEN_EBS_VOLUME_ID2}\" --region \"${KITCHEN_AWS_REGION}\"\necho \"** EBS volumes ${KITCHEN_EBS_VOLUME_ID1} and ${KITCHEN_EBS_VOLUME_ID2} deleted\"\n", "num_lines": 26}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# clean up cloud init artifacts https://cloudinit.readthedocs.io/en/latest/topics/cli.html#clean\ncloud-init clean -s\n\nrm -rf /var/tmp/* /tmp/*\nrm -rf /etc/ssh/ssh_host_*\nrm -f /etc/udev/rules.d/70-persistent-net.rules\ngrep -l \"Created by cloud-init on instance boot automatically\" /etc/sysconfig/network-scripts/ifcfg-* | xargs rm -f\nrm -rf /var/crash/*\n\n# https://bugs.centos.org/view.php?id=13836#c33128\nsource /etc/os-release\nif [ \"${ID}${VERSION_ID}\" == \"centos7\" ]; then\n    rm -f /etc/sysconfig/network-scripts/ifcfg-eth0\nfi\n\nfind /var/log -type f -exec /bin/rm -v {} \\;\ntouch /var/log/lastlog\n", "num_lines": 20}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file.\n# This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\n\n\n# Generate a 5 year self-signed certificate and a new RSA private key and copy in the given path.\n# The command must be executed as root.\n\n# Usage:\n# ./generate_certificate.sh \\\n#     \"/etc/parallelcluster/ext-auth-certificate.pem\" \\\n#     \"/etc/parallelcluster/ext-auth-private-key.pem\" \\\n#     dcv-ext-auth-user \\\n#     dcv-ext-auth-user-group\n\n_check_param() {\n    paramValue=\"$1\"\n    errorMessage=\"$2\"\n    if [[ -z \"${paramValue}\" ]]; then\n        >&2 echo \"${errorMessage}\"\n        exit 1\n    fi\n}\n\nmain() {\n    certificatePath=\"$1\"\n    privateKeyPath=\"$2\"\n    user=\"$3\"\n    group=\"$4\"\n\n    _check_param \"${certificatePath}\" \"Certificate file path required\"\n    _check_param \"${privateKeyPath}\" \"Private Key file path required\"\n    _check_param \"${user}\" \"User required\"\n    _check_param \"${group}\" \"Group required\"\n\n    # Generate a new certificate and a new RSA private key\n    openssl req -newkey rsa:2048 -sha256 -x509 -days 1825 -subj \"/CN=localhost\" -out \"${certificatePath}\" -nodes -keyout \"${privateKeyPath}\"\n    chmod 440 \"${certificatePath}\" \"${privateKeyPath}\"\n    chown \"${user}\":\"${group}\" \"${certificatePath}\" \"${privateKeyPath}\"\n}\n\nmain \"$@\"\n", "num_lines": 53}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Cookbook Name:: aws-parallelcluster\n#\n# Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance with the\n# License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script must be executed by the user who want to connect to DCV to obtain a Session Token.\n#\n# It performs the following steps:\n# 1. Asks the ParallelCluster DCV External Authenticator for a Request Token and the Access File name\n# 2. Creates the \"access file\" in the AUTHORIZATION_FILE_DIR folder (to confirm user identity)\n# 3. Asks the ParallelCluster DCV External Authenticator for a SessionToken (the real token to access to the DCV session)\n# 4. Returns DCV Session Id, DCV Server Port and the Session Token\n\n# Requirements:\n# jq, curl, awk, xargs, shuf, cat, grep, systemctl\n\n# Usage:\n# The script requires the ParallelCluster shared folder as input parameter\n# The ParallelCluster shared folder will be used as session storage folder for DCV.\n# It enables the clients to share files while connected to the session.\n# ./pcluster_dcv_connect.sh \"/shared\"\n\n\n# Returns the sessionid, the port and the tokenid (256 character long).\n# Example: mysession 8443 adfsaklcxzvsadkhfgsdkhjfag-__bafbdajshsdjfh\n\nAUTHORIZATION_FILE_DIR=\"/var/spool/parallelcluster/pcluster_dcv_authenticator\"\nDCV_SESSION_FOLDER=\"${HOME}/.parallelcluster/dcv\"\nLOG_FILE_PATH=\"/var/log/parallelcluster/pcluster_dcv_connect.log\"\nLOG_FILE_MAX_SIZE=5242880 # 5MB\n\n\n_fail() {\n  message=$1\n  >&2 echo \"ERROR: ${message}\"\n  exit 1\n}\n\n_validate_json() {\n  json_param=$1\n  message=$2\n\n  if [[ -z \"${json_param}\" ]]; then\n      _fail \"${message}. Empty JSON.\"\n  fi\n  if ! $(jq -e . >/dev/null 2>&1 <<<\"${json_param}\"); then\n      _fail \"${message}. Wrong JSON.\"\n  fi\n}\n\n_atomic_touch() {\n    file_path=\"$1\"\n\n    _umask=$(umask)\n    umask 0022 && touch \"${file_path}\"\n    umask ${_umask}\n\n    if [[ ! -f \"${file_path}\" ]]; then\n        _fail \"Unable to create the file in the $(dirname \"${file_path}\") folder. Exiting..\"\n    fi\n}\n\n_log() {\n    text=$1\n\n    [[ -f \"${LOG_FILE_PATH}\" ]] || _atomic_touch \"${LOG_FILE_PATH}\"\n\n    # create a backup of the file if the size exceeds the LOG_FILE_MAX_SIZE\n    file_size=$(du -b ${LOG_FILE_PATH} | awk '{print $1}')\n    if [[ ${file_size} -gt ${LOG_FILE_MAX_SIZE} ]]; then\n        mv \"${LOG_FILE_PATH}\" \"${LOG_FILE_PATH}.1\"\n    fi\n\n    # append log\n    log_time=$(date \"+%Y-%m-%d %H:%M:%S\")\n    echo \"[${log_time}]: ${text}\" >> \"${LOG_FILE_PATH}\"\n}\n\n_create_dcv_session() {\n    dcv_session_file=\"$1\"\n    shared_folder_path=\"$2\"\n\n    _log \"Creating a new NICE DCV session...\"\n    # Generate a random session id\n    sessionid=$(shuf -zer -n20  {A..Z} {a..z} {0..9})\n    echo \"${sessionid}\" > \"${dcv_session_file}\"\n    dcv create-session --type virtual --storage-root \"${shared_folder_path}\" \"${sessionid}\"\n    _log \"NICE DCV session created successfully.\"\n\n    echo \"${sessionid}\"\n}\n\nmain() {\n    _log \"--- Initializing NICE DCV authentication... ---\"\n\n    if [[ -z \"$1\" ]]; then\n        _fail \"The script requires the shared folder as input parameter.\"\n    fi\n\n    shared_folder_path=\"$1\"\n    user=$(whoami)\n    os=$(< /etc/chef/dna.json jq -r .cluster.base_os)\n    _log \"Input parameters: user: ${user}, OS: ${os}, shared_folder_path: ${shared_folder_path}.\"\n\n    if ! [[ \"${os}\" =~ ^(alinux2|ubuntu2004|centos[7-8]|rhel8)$ ]]; then\n        _fail \"OS not supported.\"\n    fi\n\n    if ! systemctl is-active --quiet dcvserver; then\n        _fail \"NICE DCV service is not active on the given instance.\"\n    fi\n\n    # Create a session with session storage enabled.\n    mkdir -p \"${DCV_SESSION_FOLDER}\"\n    dcv_session_file=\"${DCV_SESSION_FOLDER}/dcv_session\"\n    if [[ ! -e ${dcv_session_file} ]]; then\n        sessionid=$(_create_dcv_session \"${dcv_session_file}\" \"${shared_folder_path}\")\n    else\n        sessionid=$(cat \"${dcv_session_file}\")\n        _log \"Reusing existing NICE DCV session for the current user.\"\n\n        # number of session can either be 0 or 1\n        number_of_sessions=$(dcv list-sessions |& grep \"${user}\" | grep -c \"${sessionid}\")\n        if (( number_of_sessions == 0 )); then\n            # There is no running session (e.g. the system has been rebooted)\n            _log \"There are no running sessions for the current user, creating a new one..\"\n            sessionid=$(_create_dcv_session \"${dcv_session_file}\" \"${shared_folder_path}\")\n        fi\n    fi\n\n    # xargs to remove eventual whitespaces\n    dcv_server_port=$(grep web-port= /etc/dcv/dcv.conf| awk -F'=' '{ print $2 }' | xargs)\n    ext_auth_port=$((dcv_server_port + 1))\n\n    # Retrieve Request Token and Access File name\n    _log \"Retrieving Request Token and Access File name..\"\n    user_token_request=$(curl --retry 3 --max-time 5 -s -k -X GET -G \"https://localhost:${ext_auth_port}\" -d action=requestToken -d authUser=\"${user}\" -d sessionID=\"${sessionid}\")\n    _validate_json \"${user_token_request}\" \"Unable to obtain the Request Token from the NICE DCV external authenticator.\"\n    request_token=$(echo \"${user_token_request}\" | jq -r .requestToken)\n    access_file=$(echo \"${user_token_request}\" | jq -r .accessFile)\n    _log \"Request Token and Access File name obtained successfully.\"\n\n    # Create the access file in the AUTHORIZATION_FILE_DIR with 644 permissions\n    # This is used by the external authenticator to verify the user declares himself as who he really is\n    _log \"Creating access file..\"\n    _atomic_touch \"${AUTHORIZATION_FILE_DIR}/${access_file}\"\n    _log \"Access file created successfully.\"\n\n\n    # Retrieve Session Token\n    _log \"Retrieving Session Token..\"\n    session_token_request=$(curl --retry 3 --max-time 5 -s -k -X GET -G \"https://localhost:${ext_auth_port}\" -d action=sessionToken -d requestToken=\"${request_token}\")\n    _validate_json \"${session_token_request}\" \"Unable to obtain the Session Token from the NICE DCV external authenticator.\"\n    session_token=$(echo \"${session_token_request}\" | jq -r .sessionToken)\n    _log \"Session Token obtained successfully.\"\n\n    if [[ -z \"${dcv_server_port}\" ]]; then\n      dcv_server_port=8443\n    fi\n\n    _log \"--- NICE DCV authentication performed successfully. ---\"\n    echo \"PclusterDcvServerPort=${dcv_server_port} PclusterDcvSessionId=${sessionid} PclusterDcvSessionToken=${session_token}\"\n}\n\nmain \"$@\"\n", "num_lines": 176}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the\n# License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# GPU Health Check\n# Check GPU healthiness by executing NVIDIA DCGM diagnostic tool\n# If GPU_DEVICE_ORDINAL is set, the diagnostic check targets the GPU listed in the variable\n# Prerequisite for the diagnostic check are:\n#   * node has NVIDIA GPU\n#   * DCGM service is running\n#   * fabric manager service is running (if node is NVSwitch enabled)\n#   * persistent mode is enabled for the target GPU\n\n## DCGMI run level\n# 1 - Quick (System Validation)\n# 2 - Medium (Extended System Validation)\n# 3 - Long (System HW Diagnostics)\n# 4 - Extended (Longer-running System HW Diagnostics)\nDCGMI_LEVEL=2\n\nfunction main() {\n\n  ## Identify full path of lspci command\n  lspci_fullpath=$(PATH=$PATH:/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/sbin:/bin command -v lspci)\n\n  ## Check if the instance has an NVIDIA acceleration\n  is_nvidia\n  fast_success_exit \"$?\" \"The GPU Health Check is running in an instance without a supported GPU: skipping its execution.\"\n\n  ## Check if the nvidia-smi command is available\n  command -v nvidia-smi &>/dev/null\n  fast_success_exit \"$?\" \"The GPU Health Check has been executed but the nvidia-smi tool is not available in this system or is located in a different file path. Please consider using an official ParallelCluster AMI.\"\n\n  ## Check if the DCGM Diagnostic tool is available\n  command -v dcgmi  &>/dev/null\n  fast_success_exit \"$?\" \"The GPU Health Check has been executed but the NVIDIA DCGM Diagnostic tool is not available in this system or is located in a different file path. Please consider using an official ParallelCluster AMI.\"\n\n  ## Check if the NVIDIA GPU is supported by DCGM tool\n  nvidia_smi_output=$(nvidia-smi -L)\n  fast_success_exit \"$?\" \"The nvidia-smi tool failed its execution.\"\n  log_info \"GPU list is '${nvidia_smi_output//$'\\n'/, }'\"\n  is_dcgm_supported\n  fast_success_exit \"$?\" \"The GPU Health Check is running in a NVIDIA GPU not supported by DCGM Diagnostic tool: skipping its execution.\"\n\n  ## Check if there are GPU associated to the job\n  if [ -z \"$GPU_DEVICE_ORDINAL\" ]; then\n    # The \"nvidia-smi -L\" return the list of GPUs available on the node:\n    # $nvidia-smi -L\n    # GPU 0: NVIDIA A100-SXM4-80GB (UUID: GPU-e57350fc-1789-b69a-0637-18a3025b1da2)\n    # GPU 1: NVIDIA A100-SXM4-80GB (UUID: GPU-c4798aff-efab-68a7-1a52-107a0d6775fd)\n    # ...\n    # for each line in the output the ID is removing all characters after the colon symbol and the \"GPU \" string\n    # $nvidia-smi -L | while IFS= read -r gpu ; do echo $gpu | cut -d ':' -f1 | sed s/\"GPU \"//; done\n    # 0\n    # 1\n    # Then the newline is replaced by a comma\n    # $nvidia-smi -L | while IFS= read -r gpu ; do echo $gpu | cut -d ':' -f1 | sed s/\"GPU \"//; done | tr '\\n' ','\n    # 0,1,\n    # and then we remove the last char\n    # $nvidia-smi -L | while IFS= read -r gpu ; do echo $gpu | cut -d ':' -f1 | sed s/\"GPU \"//; done | tr '\\n' ',' | sed 's/.$//'\n    # 0,1\n    GPU_DEVICE_ORDINAL=$(echo \"$nvidia_smi_output\" | while IFS= read -r gpu ; do echo $gpu | cut -d ':' -f1 | sed s/\"GPU \"//; done | tr '\\n' ',' | sed 's/.$//')\n    log_info \"The variable GPU_DEVICE_ORDINAL has been initialized using information provided by nvidia-smi\"\n  fi\n  log_info \"The value of GPU_DEVICE_ORDINAL is '${GPU_DEVICE_ORDINAL}'\"\n\n  ## Services Initialization\n  local dcgm_service_started\n  initialize_dcgm\n  fast_success_exit \"$?\" \"Skipping execution of the GPU Health Check\"\n\n  local nvidia_fabricmanager_service_started\n  initialize_nvidia_fabricmanager\n  fast_success_exit \"$?\" \"Skipping execution of the GPU Health Check\"\n\n  ## Retrieve gpus information and enable them to run the health check\n  local gpus_list\n  gpus_list=${GPU_DEVICE_ORDINAL//,/$'\\n'}\n  for gpu_id in $gpus_list\n  do\n    # Retrieve gpu information. This check will exit in following cases:\n    # - the nvidia-smi command is not available\n    # - the nvidia-smi command is available but it fails its execution\n    nvidia_smi_out=$(nvidia-smi -q -i $gpu_id)\n    fast_success_exit \"$?\" \"The nvidia-smi tool failed its execution.\"\n\n    ## Enable persistence mode in target GPU, required by the DCGM Diagnostic tool\n    local persistence_mode_enabled_$gpu_id\n    persistence_mode=$(echo \"$nvidia_smi_out\" | grep \"Persistence Mode\")\n    if [[ ! ${persistence_mode} == *\"Enabled\"* ]]; then\n      nvidia-smi -i $gpu_id -pm 1 >/dev/null\n      log_info \"Persistence mode has been enabled by the GPU Health Check in target GPU '${gpu_id}'\"\n      declare persistence_mode_enabled_$gpu_id=true\n    else\n      log_info \"Persistence mode already enabled for target GPU '${gpu_id}'\"\n    fi\n\n    ## Log useful GPU information\n    gpu_identifier=$(echo \"$nvidia_smi_out\" | grep \"^GPU \" | xargs)\n    gpu_uuid=$(echo \"$nvidia_smi_out\" | grep \"GPU UUID\" | xargs)\n    gpu_serial_number=$(echo \"$nvidia_smi_out\" | grep \"Serial Number\" | xargs)\n    # This command logs the GPU information in the format\n    # Details for GPU '0'. 'GPU 00000000:00:1E.0', 'GPU UUID : GPU-931c0765-01f6-f7af-00df-fb4202cec8b9', 'Serial Number : 0322817127524'\n    log_info \"Details for GPU '${gpu_id}': '${gpu_identifier}', '${gpu_uuid}', '${gpu_serial_number}'\"\n  done\n\n  ## Run GPUs Health Check test\n  log_info \"Running GPU Health Check with DCGMI level $DCGMI_LEVEL\"\n  dcgmi diag -i $GPU_DEVICE_ORDINAL -r $DCGMI_LEVEL\n  dcgmi_exit_code=$?\n\n  if [ $dcgmi_exit_code -ne 0 ]; then\n    log_error \"The GPU Health Check failed\"\n  else\n    log_info \"The GPU Health Check succeeded\"\n  fi\n  tear_down\n  return $dcgmi_exit_code\n}\n\nfunction _log() {\n  echo \"$(date +\"%Y-%m-%d %H:%M:%S,%3N\") - [${0##*/}] - $1 - JobID $SLURM_JOB_ID - ${*:2}\"\n}\n\nfunction log_info() {\n  _log \"INFO\" \"$@\"\n}\n\nfunction log_error() {\n  _log \"ERROR\" \"$@\"\n}\n\nfunction fast_success_exit() {\n  if [ $1 -ne 0 ]; then\n    log_info \"$2\"\n    tear_down\n    exit 0\n  fi\n}\n\nfunction is_nvidia() {\n  $lspci_fullpath | grep -i -o 'NVIDIA' &>/dev/null\n  return $?\n}\n\nfunction is_dcgm_supported() {\n  echo $nvidia_smi_output | grep -v -i -o ' K520 ' &>/dev/null\n  return $?\n}\n\nfunction start_service() {\n  systemctl start $1\n  if [ $? -ne 0 ]; then\n    log_info \"Unable to start service $1\"\n    return 1\n  fi\n}\n\nfunction initialize_dcgm() {\n  systemctl show nvidia-dcgm.service -p ActiveState | grep \"=active\"\n  if [ $? -ne 0 ]; then\n    log_info \"Starting nvidia-dcgm service since it is not running\"\n    start_service nvidia-dcgm\n    if [ $? -ne 0 ]; then\n      return 1\n    fi\n    dcgm_service_started=true\n  else\n    log_info \"nvidia-dcgm service if already running\"\n  fi\n}\n\nfunction initialize_nvidia_fabricmanager() {\n  log_info \"Verifying if the check is running on a NVSwitch enabled system\"\n  nvswitch_check=$($lspci_fullpath -d 10de:1af1 | wc -l)\n  if [ \"${nvswitch_check}\" -gt 1 ]; then\n    systemctl show nvidia-fabricmanager.service -p ActiveState | grep \"=active\"\n    if [ $? -ne 0 ]; then\n      log_info \"Starting nvidia-fabricmanager since it is not running\"\n      start_service nvidia-fabricmanager\n      if [ $? -ne 0 ]; then\n        return 1\n      fi\n      nvidia_fabricmanager_service_started=true\n    else\n      log_info \"nvidia-fabricmanager is already running\"\n    fi\n  fi\n}\n\nfunction tear_down() {\n  log_info \"Restoring previous configurations\"\n\n  ## Restore previous persistence mode\n  for gpu_id in $gpus_list\n  do\n      persistence_mode_variable=persistence_mode_enabled_$gpu_id\n      if [ \"${!persistence_mode_variable}\" = true ] ; then\n        log_info \"Disabling persistence mode on GPU '$gpu_id'\"\n        nvidia-smi -i $gpu_id -pm 0 >/dev/null\n      fi\n  done\n\n  if [ \"$nvidia_fabricmanager_service_started\" = true ] ; then\n    log_info \"Stopping nvidia-fabricmanager service\"\n    systemctl stop nvidia-fabricmanager\n  fi\n\n  if [ \"$dcgm_service_started\" = true ] ; then\n    log_info \"Stopping nvidia-dcgm service\"\n    systemctl stop nvidia-dcgm\n  fi\n}\n\nmain \"$@\"\n", "num_lines": 225}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "# Prefer a user pyenv over a system-wide install\nif [ -s \"${HOME}/.pyenv/bin\" ]; then\n    pyenv_root=\"${HOME}/.pyenv\"\n    pyenv_init=\"pyenv init -\"\nelif [ -s \"<%= @global_prefix %>\" ]; then\n    pyenv_root=\"<%= @global_prefix %>\"\n    export PYENV_ROOT=${pyenv_root}\n    # Rehashing will fail in a system install\n    pyenv_init=\"pyenv init - --no-rehash\"\nfi\n\nif [ -n \"$pyenv_root\" ]; then\n    export PATH=\"${pyenv_root}/bin:$PATH\"\n    eval \"$($pyenv_init)\"\nfi\n", "num_lines": 16}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"*** Fix relative paths in dependent cookbooks\"\nrm -rf /tmp/cookbooks\nmkdir -p /tmp/cookbooks/aws-parallelcluster-awsbatch\nmkdir -p /tmp/cookbooks/aws-parallelcluster-platform\nmkdir -p /tmp/cookbooks/aws-parallelcluster-environment\nmkdir -p /tmp/cookbooks/aws-parallelcluster-computefleet\nmkdir -p /tmp/cookbooks/aws-parallelcluster-shared/test\nmkdir -p /tmp/cookbooks/aws-parallelcluster-slurm/test\ncp -r cookbooks/aws-parallelcluster-awsbatch/test /tmp/cookbooks/aws-parallelcluster-awsbatch\ncp -r cookbooks/aws-parallelcluster-platform/test /tmp/cookbooks/aws-parallelcluster-platform\ncp -r cookbooks/aws-parallelcluster-environment/test /tmp/cookbooks/aws-parallelcluster-environment\ncp -r cookbooks/aws-parallelcluster-computefleet/test /tmp/cookbooks/aws-parallelcluster-computefleet\ncp -r cookbooks/aws-parallelcluster-shared/test /tmp/cookbooks/aws-parallelcluster-shared\ncp -r cookbooks/aws-parallelcluster-slurm/test /tmp/cookbooks/aws-parallelcluster-slurm\nsed -i.bak \"s#path: ../aws-parallelcluster#path: /tmp/cookbooks/aws-parallelcluster#g\" /tmp/cookbooks/aws-parallelcluster-*/test/inspec.yml\n", "num_lines": 17}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nKITCHEN_SCOPE=$1; shift;\nKITCHEN_SUBJECT=$(echo $KITCHEN_SCOPE | awk -F- '{print $1}')\nKITCHEN_PHASE=$(echo $KITCHEN_SCOPE | awk -F- '{print $2}')\n\n# ./kitchen.$driver.sh platform-install ... will run kitchen in aws-parallelcluster-cookbook/cookbooks/aws-parallelcluster-platform dir\nexport KITCHEN_COOKBOOK_PATH=\"cookbooks/aws-parallelcluster-${KITCHEN_SUBJECT}\"\n\nexport KITCHEN_LOCAL_YAML=\"${KITCHEN_COOKBOOK_PATH}/kitchen.${KITCHEN_SCOPE}.yml\"\nexport KITCHEN_PHASE\n", "num_lines": 12}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport KITCHEN_HOOK=$1\nKITCHEN_ROOT_DIR=$(readlink -f $2)\nexport KITCHEN_ROOT_DIR\nTHIS_DIR=$(dirname \"$0\")\n\n# Run OS specific hooks from kitchen/hooks folder\nSCRIPT=\"${THIS_DIR}/hooks/${KITCHEN_PLATFORM_NAME}/${KITCHEN_HOOK}.sh\"\nif [ -e \"${SCRIPT}\" ]; then\n\n  echo \"*** Run ${KITCHEN_HOOK} on host ${KITCHEN_INSTANCE_HOSTNAME}\"\n  echo \"**** Script: ${SCRIPT}\"\n  # shellcheck disable=SC1090\n  source \"${SCRIPT}\"\nfi\n\n# Run test specific hooks from cookbooks/aws-parallelcluster-*/test/hooks folder\nSCRIPT=\"${THIS_DIR}/../${KITCHEN_COOKBOOK_PATH}/test/hooks/${KITCHEN_PHASE}/${KITCHEN_SUITE_NAME}/${KITCHEN_HOOK}.sh\"\nif [ -e \"${SCRIPT}\" ]; then\n  echo \"*** Run ${KITCHEN_HOOK} for cookbook ${KITCHEN_COOKBOOK_PATH} suite ${KITCHEN_SUITE_NAME} on host ${KITCHEN_INSTANCE_HOSTNAME}\"\n  echo \"**** Script: ${SCRIPT}\"\n\n  if [ \"${KITCHEN_DRIVER}\" = \"ec2\" ]; then\n\n    if [ -n \"${KITCHEN_INSTANCE_HOSTNAME}\" ]; then\n      case ${KITCHEN_PLATFORM_NAME} in\n        alinux*|redhat* ) export KITCHEN_EC2_USER='ec2-user';;\n        centos*         ) export KITCHEN_EC2_USER='centos';;\n        ubuntu*         ) export KITCHEN_EC2_USER='ubuntu';;\n      esac\n      echo \"Retrieve EC2 instance id using key ${KITCHEN_SSH_KEY_PATH}\"\n\n      KITCHEN_EC2_INSTANCE_ID=$(ssh -o StrictHostKeyChecking=no -i \"${KITCHEN_SSH_KEY_PATH}\" \\\n        \"${KITCHEN_EC2_USER}@${KITCHEN_INSTANCE_HOSTNAME}\" '\n        TOKEN=$(curl -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\") \\\n        && curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/meta-data/instance-id\n      ')\n\n      [ -n \"${KITCHEN_EC2_INSTANCE_ID}\" ] && echo \"EC2 instance id: ${KITCHEN_EC2_INSTANCE_ID}\" || echo \"Unable to retrieve instance id.\"\n      export KITCHEN_EC2_INSTANCE_ID\n    fi\n  fi\n\n  # shellcheck disable=SC1090\n  source \"${SCRIPT}\"\n\nelse\n  echo \"*** Hook ${KITCHEN_HOOK} undefined for ${KITCHEN_SUITE_NAME}\"\nfi\n", "num_lines": 51}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# do some check\n>&2 echo \"err to stderr\"\necho \"output to stdout\"\nexit 125\n", "num_lines": 6}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# non executable\nexit 1\n", "num_lines": 4}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# do some check\n>&2 echo \"err to stderr\"\necho \"output to stdout\"\nexit 0\n", "num_lines": 6}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# On Mac OS, the default implementation of sed is BSD sed, but this script requires GNU sed.\nif [ \"$(uname)\" == \"Darwin\" ]; then\n  command -v gsed >/dev/null 2>&1 || { echo >&2 \"[ERROR] Mac OS detected: please install GNU sed with 'brew install gnu-sed'\"; exit 1; }\n  PATH=\"/usr/local/opt/gnu-sed/libexec/gnubin:$PATH\"\nfi\n\nif [ -z \"$1\" -o -z \"$2\" ]; then\n    echo \"New version not specified. Usage: bump-version.sh NEW_PCLUSTER_VERSION NEW_AWSBATCH_CLI_VERSION\"\n    exit 1\nfi\n\nNEW_PCLUSTER_VERSION=$1\nNEW_AWSBATCH_CLI_VERSION=$2\nVERSIONS_FILE=\"cookbooks/aws-parallelcluster-shared/attributes/versions.rb\"\n\nCURRENT_PCLUSTER_VERSION=$(sed -ne \"s/default\\['cluster'\\]\\['parallelcluster-version'\\] = '\\(.*\\)'/\\1/p\" ${VERSIONS_FILE})\n\nNEW_PCLUSTER_VERSION_SHORT=$(echo ${NEW_PCLUSTER_VERSION} | grep -Eo \"[0-9]+\\.[0-9]+\\.[0-9]+\")\nCURRENT_PCLUSTER_VERSION_SHORT=$(echo ${CURRENT_PCLUSTER_VERSION} | grep -Eo \"[0-9]+\\.[0-9]+\\.[0-9]+\")\n\nsed -i \"s/default\\['cluster'\\]\\['parallelcluster-version'\\] = '${CURRENT_PCLUSTER_VERSION}'/default['cluster']['parallelcluster-version'] = '${NEW_PCLUSTER_VERSION}'/g\" ${VERSIONS_FILE}\nsed -i \"s/default\\['cluster'\\]\\['parallelcluster-cookbook-version'\\] = '$CURRENT_PCLUSTER_VERSION'/default['cluster']['parallelcluster-cookbook-version'] = '${NEW_PCLUSTER_VERSION}'/g\" ${VERSIONS_FILE}\nsed -i \"s/default\\['cluster'\\]\\['parallelcluster-node-version'\\] = '${CURRENT_PCLUSTER_VERSION}'/default['cluster']['parallelcluster-node-version'] = '${NEW_PCLUSTER_VERSION}'/g\" ${VERSIONS_FILE}\nsed -i \"s/version '${CURRENT_PCLUSTER_VERSION_SHORT}'/version '${NEW_PCLUSTER_VERSION_SHORT}'/g\" metadata.rb\n\nsed -i \"s/ENV\\['KITCHEN_PCLUSTER_VERSION'\\] || '${CURRENT_PCLUSTER_VERSION}'/ENV\\['KITCHEN_PCLUSTER_VERSION'\\] || '${NEW_PCLUSTER_VERSION}'/g\" kitchen.ec2.yml\n\nCOOKBOOKS=(\"aws-parallelcluster-awsbatch\" \"aws-parallelcluster-entrypoints\" \"aws-parallelcluster-slurm\" \"aws-parallelcluster-platform\" \"aws-parallelcluster-environment\" \"aws-parallelcluster-computefleet\" \"aws-parallelcluster-shared\" \"aws-parallelcluster-slurm\" \"aws-parallelcluster-tests\")\nfor cookbook in \"${COOKBOOKS[@]}\"; do\n  METADATA_FILES+=(\"cookbooks/${cookbook}/metadata.rb\")\ndone\n\n# Update version in specific cookbook metadata\nsed -i \"s/version '${CURRENT_PCLUSTER_VERSION_SHORT}'/version '${NEW_PCLUSTER_VERSION_SHORT}'/g\" ${METADATA_FILES[*]}\n\nfor COOKBOOK in ${COOKBOOKS[*]}; do\n  # Update dependencies version in main cookbook metadata\n  sed -i \"s/depends '${COOKBOOK}', '~> ${CURRENT_PCLUSTER_VERSION_SHORT}'/depends '${COOKBOOK}', '~> ${NEW_PCLUSTER_VERSION_SHORT}'/g\" metadata.rb\n  # Update dependencies version in specific cookbook metadata\n  sed -i \"s/depends '${COOKBOOK}', '~> ${CURRENT_PCLUSTER_VERSION_SHORT}'/depends '${COOKBOOK}', '~> ${NEW_PCLUSTER_VERSION_SHORT}'/g\" ${METADATA_FILES[*]}\ndone\n\n# Update AWS Batch CLI version\nCURRENT_AWSBATCH_CLI_VERSION=$(sed -ne \"s/^default\\['cluster'\\]\\['parallelcluster-awsbatch-cli-version'\\] = '\\(.*\\)'/\\1/p\" ${VERSIONS_FILE})\nsed -i \"s/default\\['cluster'\\]\\['parallelcluster-awsbatch-cli-version'\\] = '${CURRENT_AWSBATCH_CLI_VERSION}'/default['cluster']['parallelcluster-awsbatch-cli-version'] = '${NEW_AWSBATCH_CLI_VERSION}'/g\" ${VERSIONS_FILE}\n", "num_lines": 50}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# WARNING: REQUIRES /bin/bash\n#\n# - cinc-install.sh v1.1.0\n#\n# - must run on /bin/sh on solaris 9\n# - must run on /bin/sh on AIX 6.x\n#\n# Copyright:: Copyright (c) 2010-2018 Chef Software, Inc.\n# License:: Apache License, Version 2.0\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# helpers.sh\n############\n# This section has some helper functions to make life easier.\n#\n# Outputs:\n# $tmp_dir: secure-ish temp directory that can be used during installation.\n############\n\n# Check whether a command exists - returns 0 if it does, 1 if it does not\nexists() {\n  if command -v $1 >/dev/null 2>&1\n  then\n    return 0\n  else\n    return 1\n  fi\n}\n\n# Output the instructions to report bug about this script\nreport_bug() {\n  echo \"Version: $version\"\n  echo \"\"\n  echo \"Please file a Bug Report at https://gitlab.com/cinc-project/mixlib-install/issues\"\n  echo \"Alternatively, feel free to open a Support Ticket at https://gitlab.com/groups/cinc-project/-/issues\"\n  echo \"More Cinc support resources can be found at https://www.cinc.sh/support\"\n  echo \"\"\n  echo \"Please include as many details about the problem as possible i.e., how to reproduce\"\n  echo \"the problem (if possible), type of the Operating System and its version, etc.,\"\n  echo \"and any other relevant details that might help us with troubleshooting.\"\n  echo \"\"\n}\n\nchecksum_mismatch() {\n  echo \"Package checksum mismatch!\"\n  report_bug\n  exit 1\n}\n\nunable_to_retrieve_package() {\n  echo \"Unable to retrieve a valid package!\"\n  report_bug\n  echo \"Metadata URL: $metadata_url\"\n  if test \"x$download_url\" != \"x\"; then\n    echo \"Download URL: $download_url\"\n  fi\n  if test \"x$stderr_results\" != \"x\"; then\n    echo \"\\nDEBUG OUTPUT FOLLOWS:\\n$stderr_results\"\n  fi\n  exit 1\n}\n\nhttp_404_error() {\n  echo \"Omnitruck artifact does not exist for version $version on platform $platform\"\n  echo \"\"\n  echo \"Either this means:\"\n  echo \"   - We do not support $platform\"\n  echo \"   - We do not have an artifact for $version\"\n  echo \"\"\n  echo \"This is often the latter case due to running a prerelease or RC version of Cinc\"\n  echo \"or a gem version which was only pushed to rubygems and not omnitruck.\"\n  echo \"\"\n  echo \"You may be able to set your knife[:bootstrap_version] to the most recent stable\"\n  echo \"release of Cinc to fix this problem (or the most recent stable major version number).\"\n  echo \"\"\n  echo \"In order to test the version parameter, adventurous users may take the Metadata URL\"\n  echo \"below and modify the '&v=<number>' parameter until you successfully get a URL that\"\n  echo \"does not 404 (e.g. via curl or wget).  You should be able to use '&v=11' or '&v=12'\"\n  echo \"succesfully.\"\n  echo \"\"\n  echo \"If you cannot fix this problem by setting the bootstrap_version, it probably means\"\n  echo \"that $platform is not supported.\"\n  echo \"\"\n  # deliberately do not call report_bug to suppress bug report noise.\n  echo \"Metadata URL: $metadata_url\"\n  if test \"x$download_url\" != \"x\"; then\n    echo \"Download URL: $download_url\"\n  fi\n  if test \"x$stderr_results\" != \"x\"; then\n    echo \"\\nDEBUG OUTPUT FOLLOWS:\\n$stderr_results\"\n  fi\n  exit 1\n}\n\ncapture_tmp_stderr() {\n  # spool up /tmp/stderr from all the commands we called\n  if test -f \"$tmp_dir/stderr\"; then\n    output=`cat $tmp_dir/stderr`\n    stderr_results=\"${stderr_results}\\nSTDERR from $1:\\n\\n$output\\n\"\n    rm $tmp_dir/stderr\n  fi\n}\n\n# do_wget URL FILENAME\ndo_wget() {\n  echo \"trying wget...\"\n  wget --user-agent=\"User-Agent: mixlib-install/3.11.27\" -O \"$2\" \"$1\" 2>$tmp_dir/stderr\n  rc=$?\n  # check for 404\n  grep \"ERROR 404\" $tmp_dir/stderr 2>&1 >/dev/null\n  if test $? -eq 0; then\n    echo \"ERROR 404\"\n    http_404_error\n  fi\n\n  # check for bad return status or empty output\n  if test $rc -ne 0 || test ! -s \"$2\"; then\n    capture_tmp_stderr \"wget\"\n    return 1\n  fi\n\n  return 0\n}\n\n# do_curl URL FILENAME\ndo_curl() {\n  echo \"trying curl...\"\n  curl -A \"User-Agent: mixlib-install/3.11.27\" --retry 5 -sL -D $tmp_dir/stderr \"$1\" > \"$2\"\n  rc=$?\n  # check for 404\n  grep \"404 Not Found\" $tmp_dir/stderr 2>&1 >/dev/null\n  if test $? -eq 0; then\n    echo \"ERROR 404\"\n    http_404_error\n  fi\n\n  # check for bad return status or empty output\n  if test $rc -ne 0 || test ! -s \"$2\"; then\n    capture_tmp_stderr \"curl\"\n    return 1\n  fi\n\n  return 0\n}\n\n# do_fetch URL FILENAME\ndo_fetch() {\n  echo \"trying fetch...\"\n  fetch --user-agent=\"User-Agent: mixlib-install/3.11.27\" -o \"$2\" \"$1\" 2>$tmp_dir/stderr\n  # check for bad return status\n  test $? -ne 0 && return 1\n  return 0\n}\n\n# do_perl URL FILENAME\ndo_perl() {\n  echo \"trying perl...\"\n  perl -e 'use LWP::Simple; getprint($ARGV[0]);' \"$1\" > \"$2\" 2>$tmp_dir/stderr\n  rc=$?\n  # check for 404\n  grep \"404 Not Found\" $tmp_dir/stderr 2>&1 >/dev/null\n  if test $? -eq 0; then\n    echo \"ERROR 404\"\n    http_404_error\n  fi\n\n  # check for bad return status or empty output\n  if test $rc -ne 0 || test ! -s \"$2\"; then\n    capture_tmp_stderr \"perl\"\n    return 1\n  fi\n\n  return 0\n}\n\n# do_python URL FILENAME\ndo_python() {\n  echo \"trying python...\"\n  python -c \"import sys,urllib2; sys.stdout.write(urllib2.urlopen(urllib2.Request(sys.argv[1], headers={ 'User-Agent': 'mixlib-install/3.11.27' })).read())\" \"$1\" > \"$2\" 2>$tmp_dir/stderr\n  rc=$?\n  # check for 404\n  grep \"HTTP Error 404\" $tmp_dir/stderr 2>&1 >/dev/null\n  if test $? -eq 0; then\n    echo \"ERROR 404\"\n    http_404_error\n  fi\n\n  # check for bad return status or empty output\n  if test $rc -ne 0 || test ! -s \"$2\"; then\n    capture_tmp_stderr \"python\"\n    return 1\n  fi\n  return 0\n}\n\n# returns 0 if checksums match\ndo_checksum() {\n  if exists sha256sum; then\n    echo \"Comparing checksum with sha256sum...\"\n    checksum=`sha256sum $1 | awk '{ print $1 }'`\n    return `test \"x$checksum\" = \"x$2\"`\n  elif exists shasum; then\n    echo \"Comparing checksum with shasum...\"\n    checksum=`shasum -a 256 $1 | awk '{ print $1 }'`\n    return `test \"x$checksum\" = \"x$2\"`\n  else\n    echo \"WARNING: could not find a valid checksum program, pre-install shasum or sha256sum in your O/S image to get valdation...\"\n    return 0\n  fi\n}\n\n# do_download URL FILENAME\ndo_download() {\n  echo \"downloading $1\"\n  echo \"  to file $2\"\n\n  url=`echo $1`\n  if test \"x$platform\" = \"xsolaris2\"; then\n    if test \"x$platform_version\" = \"x5.9\" -o \"x$platform_version\" = \"x5.10\"; then\n      # solaris 9 lacks openssl, solaris 10 lacks recent enough credentials - your base O/S is completely insecure, please upgrade\n      url=`echo $url | sed -e 's/https/http/'`\n    fi\n  fi\n\n  # we try all of these until we get success.\n  # perl, in particular may be present but LWP::Simple may not be installed\n\n  if exists wget; then\n    do_wget $url $2 && return 0\n  fi\n\n  if exists curl; then\n    do_curl $url $2 && return 0\n  fi\n\n  if exists fetch; then\n    do_fetch $url $2 && return 0\n  fi\n\n  if exists perl; then\n    do_perl $url $2 && return 0\n  fi\n\n  if exists python; then\n    do_python $url $2 && return 0\n  fi\n\n  unable_to_retrieve_package\n}\n\n# get_region INSTANCE_METADATA_FILE\n# get region from metadata\nget_region() {\n  if exists curl; then\n    echo \"Trying curl to get region with IMDSv2 ...\"\n    token=$(curl -s --connect-timeout 5 --max-time 5 --retry 3 -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 300\")\n    region=$(curl -s -H \"X-aws-ec2-metadata-token: ${token}\" http://169.254.169.254/latest/dynamic/instance-identity/document|grep region|awk -F\\\" '{print $4}')\n  elif exists python; then\n    echo \"Trying python to get region with IMDSv2 ...\"\n    token=$(python -c \"import sys,requests; sys.stdout.write(requests.put('http://169.254.169.254/latest/api/token', headers={'X-aws-ec2-metadata-token-ttl-seconds': '300', 'User-Agent': 'mixlib-install/3.11.27'}).content)\")\n    region=$(python -c \"import sys,requests,json; sys.stdout.write(json.loads(requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document', headers={ 'X-aws-ec2-metadata-token': '${token}', 'User-Agent': 'mixlib-install/3.11.27' }).content.decode())['region'])\")\n  fi\n\n  if test \"x$region\" = \"x\"; then\n    echo \"Unable to get region with IMDSv2, trying with IMDSv1 ...\"\n    do_download \"http://169.254.169.254/latest/dynamic/instance-identity/document\" $1\n    region=$(cat $1 | awk '$1 ==\"\\\"region\\\"\" {print $3}' | sed 's/\"//g; s/,//g')\n  fi\n}\n\n# install_file TYPE FILENAME\n# TYPE is \"rpm\", \"deb\", \"solaris\", \"sh\", etc.\ninstall_file() {\n  echo \"Installing $project $version\"\n  case \"$1\" in\n    \"rpm\")\n      if test \"x$platform\" = \"xnexus\" || test \"x$platform\" = \"xios_xr\"; then\n        echo \"installing with yum...\"\n        yum install -yv \"$2\"\n      else\n        echo \"installing with rpm...\"\n        rpm -Uvh --oldpackage --replacepkgs \"$2\"\n      fi\n      ;;\n    \"deb\")\n      echo \"installing with dpkg...\"\n      flock $(apt-config shell StateDir Dir::State/d | sed -r \"s/.*'(.*)'$/\\1/\")daily_lock dpkg -i \"$2\"\n      ;;\n    \"bff\")\n      echo \"installing with installp...\"\n      installp -aXYgd \"$2\" all\n      ;;\n    \"solaris\")\n      echo \"installing with pkgadd...\"\n      echo \"conflict=nocheck\" > $tmp_dir/nocheck\n      echo \"action=nocheck\" >> $tmp_dir/nocheck\n      echo \"mail=\" >> $tmp_dir/nocheck\n      pkgrm -a $tmp_dir/nocheck -n $project >/dev/null 2>&1 || true\n      pkgadd -G -n -d \"$2\" -a $tmp_dir/nocheck $project\n      ;;\n    \"pkg\")\n      echo \"installing with installer...\"\n      cd / && /usr/sbin/installer -pkg \"$2\" -target /\n      ;;\n    \"dmg\")\n      echo \"installing dmg file...\"\n      hdiutil detach \"/Volumes/cinc_project\" >/dev/null 2>&1 || true\n      hdiutil attach \"$2\" -mountpoint \"/Volumes/cinc_project\"\n      cd / && /usr/sbin/installer -pkg `find \"/Volumes/cinc_project\" -name \\*.pkg` -target /\n      hdiutil detach \"/Volumes/cinc_project\"\n      ;;\n    \"sh\" )\n      echo \"installing with sh...\"\n      sh \"$2\"\n      ;;\n    \"p5p\" )\n      echo \"installing p5p package...\"\n      pkg install -g \"$2\" $project\n      ;;\n    *)\n      echo \"Unknown filetype: $1\"\n      report_bug\n      exit 1\n      ;;\n  esac\n  if test $? -ne 0; then\n    echo \"Installation failed\"\n    report_bug\n    exit 1\n  fi\n}\n\nif test \"x$TMPDIR\" = \"x\"; then\n  tmp=\"/tmp\"\nelse\n  tmp=$TMPDIR\nfi\n# secure-ish temp dir creation without having mktemp available (DDoS-able but not exploitable)\ntmp_dir=\"$tmp/install.sh.$$\"\n(umask 077 && mkdir $tmp_dir) || exit 1\n\n############\n# end of helpers.sh\n############\n\n\n# script_cli_parameters.sh\n############\n# This section reads the CLI parameters for the install script and translates\n#   them to the local parameters to be used later by the script.\n#\n# Outputs:\n# $version: Requested version to be installed.\n# $channel: Channel to install the product from\n# $project: Project to be installed\n# $cmdline_filename: Name of the package downloaded on local disk.\n# $cmdline_dl_dir: Name of the directory downloaded package will be saved to on local disk.\n# $install_strategy: Method of package installations. default strategy is to always install upon exec. Set to \"once\" to skip if project is installed\n# $download_url_override: Install package downloaded from a direct URL.\n# $checksum: SHA256 for download_url_override file (optional)\n############\n\n# Defaults\nchannel=\"stable\"\nproject=\"cinc\"\n\nwhile getopts pnv:b:c:f:P:d:s:l:a opt\ndo\n  case \"$opt\" in\n\n    v)  version=\"$OPTARG\";;\n    b)  bucket=\"$OPTARG\";; # bucket name to overide default bucket for downloading CINC client\n    c)  channel=\"$OPTARG\";;\n    p)  channel=\"current\";; # compat for prerelease option\n    n)  channel=\"current\";; # compat for nightlies option\n    f)  cmdline_filename=\"$OPTARG\";;\n    P)  project=\"$OPTARG\";;\n    d)  cmdline_dl_dir=\"$OPTARG\";;\n    s)  install_strategy=\"$OPTARG\";;\n    l)  download_url_override=\"$OPTARG\";;\n    a)  checksum=\"$OPTARG\";;\n    \\?)   # unknown flag\n      echo >&2 \\\n      \"usage: $0 [-P project] [-c release_channel] [-v version] [-f filename | -d download_dir] [-s install_strategy] [-l download_url_override] [-a checksum] [-b bucket]\"\n      exit 1;;\n  esac\ndone\n\nshift `expr $OPTIND - 1`\n\n\nif test -d \"/opt/$project\" && test \"x$install_strategy\" = \"xonce\"; then\n  echo \"$project installation detected\"\n  echo \"install_strategy set to 'once'\"\n  echo \"Nothing to install\"\n  exit\nfi\n\n\n# platform_detection.sh\n############\n# This section makes platform detection compatible with omnitruck on the system\n#   it runs.\n#\n# Outputs:\n# $platform: Name of the platform.\n# $platform_version: Version of the platform.\n# $machine: System's architecture.\n############\n\n#\n# Platform and Platform Version detection\n#\n# NOTE: This logic should match ohai platform and platform_version matching.\n# do not invent new platform and platform_version schemas, just make this behave\n# like what ohai returns as platform and platform_version for the system.\n#\n# ALSO NOTE: Do not mangle platform or platform_version here.  It is less error\n# prone and more future-proof to do that in the server, and then all omnitruck clients\n# will 'inherit' the changes (install.sh is not the only client of the omnitruck\n# endpoint out there).\n#\n\nmachine=`uname -m`\nos=`uname -s`\n\nif test -f \"/etc/lsb-release\" && grep DISTRIB_ID /etc/lsb-release >/dev/null && ! grep wrlinux /etc/lsb-release >/dev/null; then\n  platform=`grep DISTRIB_ID /etc/lsb-release | cut -d \"=\" -f 2 | tr '[A-Z]' '[a-z]'`\n  platform_version=`grep DISTRIB_RELEASE /etc/lsb-release | cut -d \"=\" -f 2`\n\n  if test \"$platform\" = \"\\\"cumulus linux\\\"\"; then\n    platform=\"cumulus_linux\"\n  elif test \"$platform\" = \"\\\"cumulus networks\\\"\"; then\n    platform=\"cumulus_networks\"\n  fi\n\nelif test -f \"/etc/debian_version\"; then\n  platform=\"debian\"\n  platform_version=`cat /etc/debian_version`\nelif test -f \"/etc/Eos-release\"; then\n  # EOS may also contain /etc/redhat-release so this check must come first.\n  platform=arista_eos\n  platform_version=`awk '{print $4}' /etc/Eos-release`\n  machine=\"i386\"\nelif test -f \"/etc/redhat-release\"; then\n  platform=`sed 's/^\\(.\\+\\) release.*/\\1/' /etc/redhat-release | tr '[A-Z]' '[a-z]'`\n  platform_version=`sed 's/^.\\+ release \\([.0-9]\\+\\).*/\\1/' /etc/redhat-release`\n\n  if test \"$platform\" = \"xenserver\"; then\n    # Current XenServer 6.2 is based on CentOS 5, platform is not reset to \"el\" server should hanlde response\n    platform=\"xenserver\"\n  else\n    # FIXME: use \"redhat\"\n    platform=\"el\"\n  fi\n\nelif test -f \"/etc/system-release\"; then\n  platform=`sed 's/^\\(.\\+\\) release.\\+/\\1/' /etc/system-release | tr '[A-Z]' '[a-z]'`\n  platform_version=`sed 's/^.\\+ release \\([.0-9]\\+\\).*/\\1/' /etc/system-release | tr '[A-Z]' '[a-z]'`\n  case $platform in amazon*) # sh compat method of checking for a substring\n    platform=\"el\"\n\n    . /etc/os-release\n    platform_version=$VERSION_ID\n    if test \"$platform_version\" = \"2\"; then\n      platform_version=\"7\"\n    else\n      # VERSION_ID will match YYYY.MM for Amazon Linux AMIs\n      platform_version=\"6\"\n    fi\n  esac\n\n# Apple OS X\nelif test -f \"/usr/bin/sw_vers\"; then\n  platform=\"mac_os_x\"\n  # Matching the tab-space with sed is error-prone\n  platform_version=`sw_vers | awk '/^ProductVersion:/ { print $2 }' | cut -d. -f1,2`\n\n  # x86_64 Apple hardware often runs 32-bit kernels (see OHAI-63)\n  x86_64=`sysctl -n hw.optional.x86_64`\n  if test $x86_64 -eq 1; then\n    machine=\"x86_64\"\n  fi\nelif test -f \"/etc/release\"; then\n  machine=`/usr/bin/uname -p`\n  if grep SmartOS /etc/release >/dev/null; then\n    platform=\"smartos\"\n    platform_version=`grep ^Image /etc/product | awk '{ print $3 }'`\n  else\n    platform=\"solaris2\"\n    platform_version=`/usr/bin/uname -r`\n  fi\nelif test -f \"/etc/SuSE-release\"; then\n  if grep 'Enterprise' /etc/SuSE-release >/dev/null;\n  then\n      platform=\"sles\"\n      platform_version=`awk '/^VERSION/ {V = $3}; /^PATCHLEVEL/ {P = $3}; END {print V \".\" P}' /etc/SuSE-release`\n  else\n      platform=\"opensuseleap\"\n      platform_version=`awk '/^VERSION =/ { print $3 }' /etc/SuSE-release`\n  fi\nelif test \"x$os\" = \"xFreeBSD\"; then\n  platform=\"freebsd\"\n  platform_version=`uname -r | sed 's/-.*//'`\nelif test \"x$os\" = \"xAIX\"; then\n  platform=\"aix\"\n  platform_version=\"`uname -v`.`uname -r`\"\n  machine=\"powerpc\"\nelif test -f \"/etc/os-release\"; then\n  . /etc/os-release\n  if test \"x$CISCO_RELEASE_INFO\" != \"x\"; then\n    . $CISCO_RELEASE_INFO\n  fi\n\n  platform=$ID\n  platform_version=$VERSION\nfi\n\nif test \"x$platform\" = \"x\"; then\n  echo \"Unable to determine platform version!\"\n  report_bug\n  exit 1\nfi\n\n#\n# NOTE: platform mangling in the install.sh is DEPRECATED\n#\n# - install.sh should be true to ohai and should not remap\n#   platform or platform versions.\n#\n# - remapping platform and mangling platform version numbers is\n#   now the complete responsibility of the server-side endpoints\n#\n\nmajor_version=`echo $platform_version | cut -d. -f1`\ncase $platform in\n  # FIXME: should remove this case statement completely\n  \"el\")\n    # FIXME:  \"el\" is deprecated, should use \"redhat\"\n    platform_version=$major_version\n    ;;\n  \"debian\")\n    if test \"x$major_version\" = \"x5\"; then\n      # This is here for potential back-compat.\n      # We do not have 5 in versions we publish for anymore but we\n      # might have it for earlier versions.\n      platform_version=\"6\"\n    else\n      platform_version=$major_version\n    fi\n    ;;\n  \"freebsd\")\n    platform_version=$major_version\n    ;;\n  \"sles\")\n    platform_version=$major_version\n    ;;\n  \"opensuseleap\")\n    platform_version=$major_version\n    ;;\nesac\n\n# normalize the architecture we detected\ncase $machine in\n  \"x86_64\"|\"amd64\"|\"x64\")\n    machine=\"x86_64\"\n    ;;\n  \"i386\"|\"i86pc\"|\"x86\"|\"i686\")\n    machine=\"i386\"\n    ;;\n  \"sparc\"|\"sun4u\"|\"sun4v\")\n    machine=\"sparc\"\n    ;;\nesac\n\nif test \"$platform\" = \"ubuntu\"; then\n  case $machine in\n    \"arm64\"|\"aarch64\")\n      machine=\"arm64\"\n      ;;\n    \"x86_64\"|\"amd64\"|\"x64\")\n      machine=\"amd64\"\n      ;;\n    \"i386\"|\"i86pc\"|\"x86\"|\"i686\")\n      machine=\"i386\"\n      ;;\n  esac\nfi\n\nif test \"x$platform_version\" = \"x\"; then\n  echo \"Unable to determine platform version!\"\n  report_bug\n  exit 1\nfi\n\nif test \"x$platform\" = \"xsolaris2\"; then\n  # hack up the path on Solaris to find wget, pkgadd\n  PATH=/usr/sfw/bin:/usr/sbin:$PATH\n  export PATH\nfi\n\n# Region detection\ninstance_metadata_file=$tmp_dir/instance_metadata\nget_region instance_metadata_file\n\n# Download domain detection\nif [[ ${region} == cn-* ]]; then\n  download_domain=\"amazonaws.com.cn\"\nelif [[ ${region} == us-iso-* ]]; then\n  download_domain=\"c2s.ic.gov\"\nelif [[ ${region} == us-isob-* ]]; then\n  download_domain=\"sc2s.sgov.gov\"\nelse\n  download_domain=\"amazonaws.com\"\nfi\n\necho \"${platform} ${platform_version} ${machine} ${region}\"\n\n############\n# end of platform_detection.sh\n############\n\n\n# All of the download utilities in this script load common proxy env vars.\n# If variables are set they will override any existing env vars.\n# Otherwise, default proxy env vars will be loaded by the respective\n# download utility.\n\nif test \"x$https_proxy\" != \"x\"; then\n  echo \"setting https_proxy: $https_proxy\"\n  HTTPS_PROXY=$https_proxy\n  https_proxy=$https_proxy\n  export HTTPS_PROXY\n  export https_proxy\nfi\n\nif test \"x$http_proxy\" != \"x\"; then\n  echo \"setting http_proxy: $http_proxy\"\n  HTTP_PROXY=$http_proxy\n  http_proxy=$http_proxy\n  export HTTP_PROXY\n  export http_proxy\nfi\n\nif test \"x$ftp_proxy\" != \"x\"; then\n  echo \"setting ftp_proxy: $ftp_proxy\"\n  FTP_PROXY=$ftp_proxy\n  ftp_proxy=$ftp_proxy\n  export FTP_PROXY\n  export ftp_proxy\nfi\n\nif test \"x$no_proxy\" != \"x\"; then\n  echo \"setting no_proxy: $no_proxy\"\n  NO_PROXY=$no_proxy\n  no_proxy=$no_proxy\n  export NO_PROXY\n  export no_proxy\nfi\n\n\n# create_download_url.sh\n############\n# This section creates the url of the package to download.\n#\n# Inputs:\n# $channel:\n# $project:\n# $version:\n# $platform:\n# $platform_version:\n# $machine:\n# $tmp_dir:\n#\n# Outputs:\n# $download_url:\n# $sha256:\n############\n\nif test \"x$bucket\" = \"x\"; then\n  # Use official bucket if not specified\n  bucket=\"${region}-aws-parallelcluster\"\nfi\n\nbucket_url=\"https://${bucket}.s3.${region}.${download_domain}/archives/${project}/${platform}/${platform_version}/\"\n\nif test \"x$build\" = \"x\"; then\n  # Build version set to 1 by default if not specified\n  build=1\nfi\n\nif test \"x$download_url_override\" = \"x\"; then\n  case \"$platform\" in\n  \"debian\"|\"ubuntu\")\n    package_file=\"${project}_${version}-${build}_${machine}.deb\"\n    ;;\n  *)\n    package_file=\"${project}-${version}-${build}.${platform}${platform_version}.${machine}.rpm\"\n    ;;\n  esac\n\n  download_url=${bucket_url}${package_file}\n  checksum_url=\"${download_url}.sha256\"\n\n  # Extracting sha256 checksum\n  checksum_file=${tmp_dir}/${package_file}.sha256\n  do_download \"${checksum_url}\" ${checksum_file}\n  sha256=$(awk '{print $1}' ${checksum_file})\nelse\n  download_url=$download_url_override\n  # Set sha256 to empty string if checksum not set\n  sha256=${checksum=\"\"}\nfi\n\n############\n# end of create_download_url.sh\n############\n\n\n# fetch_package.sh\n############\n# This section fetches a package from $download_url and verifies its metadata.\n#\n# Inputs:\n# $download_url:\n# $tmp_dir:\n# Optional Inputs:\n# $cmdline_filename: Name of the package downloaded on local disk.\n# $cmdline_dl_dir: Name of the directory downloaded package will be saved to on local disk.\n#\n# Outputs:\n# $download_filename: Name of the downloaded file on local disk.\n# $filetype: Type of the file downloaded.\n############\n\nfilename=`echo $download_url | sed -e 's/^.*\\///'`\nfiletype=`echo $filename | sed -e 's/^.*\\.//'`\n\n# use either $tmp_dir, the provided directory (-d) or the provided filename (-f)\nif test \"x$cmdline_filename\" != \"x\"; then\n  download_filename=\"$cmdline_filename\"\nelif test \"x$cmdline_dl_dir\" != \"x\"; then\n  download_filename=\"$cmdline_dl_dir/$filename\"\nelse\n  download_filename=\"$tmp_dir/$filename\"\nfi\n\n# ensure the parent directory where we download the installer always exists\ndownload_dir=`dirname $download_filename`\n(umask 077 && mkdir -p $download_dir) || exit 1\n\n# check if we have that file locally available and if so verify the checksum\n# Use cases\n# 1) metadata - new download\n# 2) metadata - cached download when cmdline_dl_dir set\n# 3) url override - no checksum new download\n# 4) url override - with checksum new download\n# 5) url override - with checksum cached download when cmdline_dl_dir set\n\ncached_file_available=\"false\"\nverify_checksum=\"true\"\n\nif test -f $download_filename; then\n  echo \"$download_filename exists\"\n  cached_file_available=\"true\"\nfi\n\nif test \"x$download_url_override\" != \"x\"; then\n  echo \"Download URL override specified\"\n  if test \"x$cached_file_available\" = \"xtrue\"; then\n    echo \"Verifying local file\"\n    if test \"x$sha256\" = \"x\"; then\n      echo \"Checksum not specified, ignoring existing file\"\n      cached_file_available=\"false\" # download new file\n      verify_checksum=\"false\" # no checksum to compare after download\n    elif do_checksum \"$download_filename\" \"$sha256\"; then\n      echo \"Checksum match, using existing file\"\n      cached_file_available=\"true\" # don't need to download file\n      verify_checksum=\"false\" # don't need to checksum again\n    else\n      echo \"Checksum mismatch, ignoring existing file\"\n      cached_file_available=\"false\" # download new file\n      verify_checksum=\"true\" # checksum new downloaded file\n    fi\n  else\n    echo \"$download_filename not found\"\n    cached_file_available=\"false\" # download new file\n    if test \"x$sha256\" = \"x\"; then\n      verify_checksum=\"false\" # no checksum to compare after download\n    else\n      verify_checksum=\"true\" # checksum new downloaded file\n    fi\n  fi\nfi\n\nif test \"x$cached_file_available\" != \"xtrue\"; then\n  do_download \"$download_url\" \"$download_filename\"\nfi\n\nif test \"x$verify_checksum\" = \"xtrue\"; then\n  do_checksum \"$download_filename\" \"$sha256\" || checksum_mismatch\nfi\n\n############\n# end of fetch_package.sh\n############\n\n\n# install_package.sh\n############\n# Installs a package and removed the temp directory.\n#\n# Inputs:\n# $download_filename: Name of the file to be installed.\n# $filetype: Type of the file to be installed.\n# $version: The version requested. Used only for warning user if not set.\n############\n\nif test \"x$version\" = \"x\" -a \"x$CI\" != \"xtrue\"; then\n  echo\n  echo \"WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\"\n  echo\n  echo \"You are installing a package without a version pin.  If you are installing\"\n  echo \"on production servers via an automated process this is DANGEROUS and you will\"\n  echo \"be upgraded without warning on new releases, even to new major releases.\"\n  echo \"Letting the version float is only appropriate in desktop, test, development or\"\n  echo \"CI/CD environments.\"\n  echo\n  echo \"WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING\"\n  echo\nfi\n\ninstall_file $filetype \"$download_filename\"\n\nif test \"x$tmp_dir\" != \"x\"; then\n  rm -r \"$tmp_dir\"\nfi\n\n############\n# end of install_package.sh\n############\n", "num_lines": 855}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This script simplifies run of kitchen tests for a given OS.\n# It must be executed from the root folder of the cookbook repo:\n# bash util/test-os.sh ec2 rhel8\n#\n# It searches for all the test suites defined in the functional cookbook and runs them sequentially.\n# The output will be saved into a `/tmp/kitchen-<os>-<date>` folder.\n# To run config tests is required to set a KITCHEN_${os}_AMI environment variable (e.g. KITCHEN_RHEL8_AMI)\n# or have a ParallelCluster AMI in the account.\n\n[ -z \"$1\" ] && echo \"Missing driver parameter, should be ec2 or docker\" && exit 1\n[ -z \"$2\" ] && echo \"Missing OS parameter\" && exit 1\ndriver=$1\nos=$2\n\nthis_dir=$( cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\ndate=$(date +\"%Y%m%dT%H%M\")\ntest_output=\"/tmp/kitchen-${os}-${date}\"\nmkdir -p \"${test_output}\"\n\nfor dir in \"${this_dir}/../cookbooks/aws-parallelcluster-\"*/; do\n  config_files=$(ls \"${dir}\"*.yml)\n  if [[ -n ${config_files} ]]; then\n    for config_file in ${config_files}; do\n      filename=$(basename \"${config_file}\")\n      cookbook=$(basename \"$(dirname ${config_file})\")\n      kitchen_config=$(echo \"${filename}\" | sed \"s/kitchen\\.\\(.*\\)\\.yml/\\1/\")\n      echo \"*** Executing tests in the ${kitchen_config} file\"\n\n      ami_env_var=$(echo \"KITCHEN_${os}_AMI\" | tr '[:lower:]' '[:upper:]')\n      if [[ \"${kitchen_config}\" == *\"-config\" ]] && [[ -z ${!ami_env_var} ]]; then\n        echo \"Environment variable ${ami_env_var} not set, skipping ${kitchen_config} test. Look at image_search on kitchen.ec2.yml for more details.\"\n        continue\n      fi\n\n      suites=$(yq e '.suites[].name' \"${this_dir}/../cookbooks/${cookbook}/kitchen.${kitchen_config}.yml\")\n      for suite in ${suites}; do\n          test=\"${suite//_/-}-${os}\"\n          echo \"* Executing ${test}\"\n          bash \"${this_dir}/../kitchen.${driver}.sh\" \"${kitchen_config}\" test \"${test}\" | tee \"${test_output}/kitchen-test-${driver}-${kitchen_config}-${test}.txt\"\n      done\n    done\n  fi\ndone\n", "num_lines": 45}
{"repo_name": "aws-parallelcluster-cookbook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n_error_exit() {\n  echo \"ERROR: $1\"\n  exit 1\n}\n\n_info() {\n  echo \"INFO: $1\"\n}\n\n_help() {\n    local -- _cmd=$(basename \"$0\")\n\n    cat <<EOF\n\n  Usage: ${_cmd} [OPTION]...\n\n  Copy the AWS ParallelCluster Cookbook in an S3 bucket.\n\n  --bucket <bucket>             Bucket where upload the cookbook\n  --srcdir <src-dir>            Root folder of the cookbook project\n  --profile <aws-profile>       AWS profile name to use for the upload\n                                (optional, default is AWS_PROFILE env variable or \"default\")\n  --region <aws-region>         Region to use for AWSCli commands (optional, default is \"us-east-1\")\n  -h, --help                    Print this help message\nEOF\n}\n\nmain() {\n    # parse input options\n    while [ $# -gt 0 ] ; do\n        case \"$1\" in\n            --bucket)           _bucket=\"$2\"; shift;;\n            --bucket=*)         _bucket=\"${1#*=}\";;\n            --srcdir)           _srcdir=\"$2\"; shift;;\n            --srcdir=*)         _srcdir=\"${1#*=}\";;\n            --profile)          _profile=\"$2\"; shift;;\n            --profile=*)        _profile=\"${1#*=}\";;\n            --region)           _region=\"$2\"; shift;;\n            --region=*)         _region=\"${1#*=}\";;\n            -h|--help|help)     _help; exit 0;;\n            *)                  _help; echo \"[error] Unrecognized option '$1'\"; exit 1;;\n        esac\n        shift\n    done\n\n    # verify required parameters\n    if [ -z \"${_bucket}\" ]; then\n        _error_exit \"--bucket parameter not specified\"\n        _help;\n    fi\n    if [ -z \"${_srcdir}\" ]; then\n        _error_exit \"--srcdir parameter not specified\"\n        _help;\n    fi\n\n    # initialize optional parameters\n    if [ -z \"${AWS_PROFILE}\" ] && [ -z \"${_profile}\" ]; then\n        _info \"--profile parameter not specified, using 'default'\"\n    elif [ -n \"${_profile}\" ]; then\n        _profile=\"--profile ${_profile}\"\n    fi\n    if [ -z \"${_region}\" ]; then\n        _info \"--region parameter not specified, using 'us-east-1'\"\n        _region=\"us-east-1\"\n    fi\n\n    # check bucket or create it\n    aws ${_profile} s3api head-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n    if [ $? -ne 0 ]; then\n        _info \"Bucket ${_bucket} do not exist, trying to create it\"\n        aws ${_profile} s3api create-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n        if [ $? -ne 0 ]; then\n            _error_exit \"Unable to create bucket ${_bucket}\"\n        fi\n    fi\n\n    _version=$(grep \"^version\" \"${_srcdir}/metadata.rb\" | awk '{print $2}'| tr -d \\')\n    if [ -z \"${_version}\" ]; then\n        _error_exit \"Unable to detect cookbook version, are you in the right directory?\"\n    fi\n    _info \"Detected version ${_version}\"\n\n    # Create archive and md5\n    _cwd=$(pwd)\n    pushd \"${_srcdir}\" > /dev/null\n    _stashName=$(git stash create)\n    git archive --format tar --prefix=\"aws-parallelcluster-cookbook-${_version}/\" \"${_stashName:-HEAD}\" | gzip > \"${_cwd}/aws-parallelcluster-cookbook-${_version}.tgz\"\n    #tar zcvf \"${_cwd}/aws-parallelcluster-cookbook-${_version}.tgz\" --transform \"s,^aws-parallelcluster-cookbook/,aws-parallelcluster-cookbook-${_version}/,\" ../aws-parallelcluster-cookbook\n    popd > /dev/null\n    md5sum aws-parallelcluster-cookbook-${_version}.tgz > aws-parallelcluster-cookbook-${_version}.md5\n\n    # upload packages\n    _key_path=\"parallelcluster/${_version}/cookbooks\"\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-cookbook-${_version}.tgz s3://${_bucket}/${_key_path}/aws-parallelcluster-cookbook-${_version}.tgz || _error_exit 'Failed to push cookbook to S3'\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-cookbook-${_version}.md5 s3://${_bucket}/${_key_path}/aws-parallelcluster-cookbook-${_version}.md5 || _error_exit 'Failed to push cookbook md5 to S3'\n    aws ${_profile} --region \"${_region}\" s3api head-object --bucket ${_bucket} --key ${_key_path}/aws-parallelcluster-cookbook-${_version}.tgz --output text --query LastModified > aws-parallelcluster-cookbook-${_version}.tgz.date || _error_exit 'Failed to fetch LastModified date'\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-cookbook-${_version}.tgz.date s3://${_bucket}/${_key_path}/aws-parallelcluster-cookbook-${_version}.tgz.date || _error_exit 'Failed to push cookbook date'\n\n    _bucket_region=$(aws ${_profile} s3api get-bucket-location --bucket ${_bucket} --output text)\n    if [ ${_bucket_region} = \"None\" ]; then\n        _bucket_region=\"\"\n    else\n        _bucket_region=\".${_bucket_region}\"\n    fi\n\n    echo \"\"\n    echo \"Done. Add the following configuration to the pcluster create config file:\"\n    echo \"\"\n    echo \"DevSettings:\"\n    echo \"  Cookbook:\"\n    echo \"    ChefCookbook: s3://${_bucket}/${_key_path}/aws-parallelcluster-cookbook-${_version}.tgz\"\n}\n\nmain \"$@\"\n\n# vim:syntax=sh\n", "num_lines": 119}
{"repo_name": "aws-parallelcluster-node", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\n# On Mac OS, the default implementation of sed is BSD sed, but this script requires GNU sed.\nif [ \"$(uname)\" == \"Darwin\" ]; then\n  command -v gsed >/dev/null 2>&1 || { echo >&2 \"[ERROR] Mac OS detected: please install GNU sed with 'brew install gnu-sed'\"; exit 1; }\n  PATH=\"/usr/local/opt/gnu-sed/libexec/gnubin:$PATH\"\nfi\n\nif [ -z \"$1\" ]; then\n    echo \"New version not specified. Usage: bump-version.sh NEW_VERSION\"\n    exit 1\nfi\n\nNEW_VERSION=$1\nCURRENT_VERSION=$(sed -ne \"s/^version = \\\"\\(.*\\)\\\"/\\1/p\" setup.py)\n\nsed -i \"s/version = \\\"$CURRENT_VERSION\\\"/version = \\\"$NEW_VERSION\\\"/g\" setup.py\n", "num_lines": 20}
{"repo_name": "aws-parallelcluster-node", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n_error_exit() {\n   echo \"$1\"\n   exit 1\n}\n\n_info() {\n  echo \"INFO: $1\"\n}\n\n_help() {\n    local -- _cmd=$(basename \"$0\")\n\n    cat <<EOF\n\n  Usage: ${_cmd} [OPTION]...\n\n  Copy the AWS ParallelCluster Node in an S3 bucket.\n\n  --bucket <bucket>             Bucket where upload the package\n  --srcdir <src-dir>            Root folder of the node package\n  --profile <aws-profile>       AWS profile name to use for the upload\n                                (optional, default is AWS_PROFILE env variable or \"default\")\n  --region <aws-region>         Region to use for AWSCli commands (optional, default is \"us-east-1\")\n  -h, --help                    Print this help message\nEOF\n}\n\nmain() {\n    # parse input options\n    while [ $# -gt 0 ] ; do\n        case \"$1\" in\n            --bucket)           _bucket=\"$2\"; shift;;\n            --bucket=*)         _bucket=\"${1#*=}\";;\n            --srcdir)           _srcdir=\"$2\"; shift;;\n            --srcdir=*)         _srcdir=\"${1#*=}\";;\n            --profile)          _profile=\"$2\"; shift;;\n            --profile=*)        _profile=\"${1#*=}\";;\n            --region)           _region=\"$2\"; shift;;\n            --region=*)         _region=\"${1#*=}\";;\n            -h|--help|help)     _help; exit 0;;\n            *)                  _help; echo \"[error] Unrecognized option '$1'\"; exit 1;;\n        esac\n        shift\n    done\n\n    # verify required parameters\n    if [ -z \"${_bucket}\" ]; then\n        _error_exit \"--bucket parameter not specified\"\n        _help;\n    fi\n    if [ -z \"${_srcdir}\" ]; then\n        _error_exit \"--srcdir parameter not specified\"\n        _help;\n    fi\n\n    # initialize optional parameters\n    if [ -z \"${AWS_PROFILE}\" ] && [ -z \"${_profile}\" ]; then\n        _info \"--profile parameter not specified, using 'default'\"\n    elif [ -n \"${_profile}\" ]; then\n        _profile=\"--profile ${_profile}\"\n    fi\n    if [ -z \"${_region}\" ]; then\n        _info \"--region parameter not specified, using 'us-east-1'\"\n        _region=\"us-east-1\"\n    fi\n\n    # check bucket or create it\n    aws ${_profile} s3api head-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n    if [ $? -ne 0 ]; then\n        _info \"Bucket ${_bucket} do not exist, trying to create it\"\n        aws ${_profile} s3api create-bucket --bucket \"${_bucket}\" --region \"${_region}\"\n        if [ $? -ne 0 ]; then\n            _error_exit \"Unable to create bucket ${_bucket}\"\n        fi\n    fi\n\n    _version=$(grep \"version = \\\"\" \"${_srcdir}/setup.py\" |awk '{print $3}' | tr -d \\\")\n    if [ -z \"${_version}\" ]; then\n        _error_exit \"Unable to detect node version, are you in the right directory?\"\n    fi\n    _info \"Detected version ${_version}\"\n\n    # Create archive\n    _cwd=$(pwd)\n    pushd \"${_srcdir}\" > /dev/null\n    _stashName=$(git stash create)\n    git archive --format tar --prefix=\"aws-parallelcluster-node-${_version}/\" \"${_stashName:-HEAD}\" | gzip > \"${_cwd}/aws-parallelcluster-node-${_version}.tgz\"\n    #tar zcvf \"${_cwd}/aws-parallelcluster-node-${_version}.tgz\" --transform \"s,^aws-parallelcluster-node/,aws-parallelcluster-node-${_version}/,\" ../aws-parallelcluster-node\n    popd > /dev/null\n    md5sum aws-parallelcluster-node-${_version}.tgz > aws-parallelcluster-node-${_version}.md5\n\n    # upload package\n    _key_path=\"parallelcluster/${_version}/node\"\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-node-${_version}.tgz s3://${_bucket}/${_key_path}/aws-parallelcluster-node-${_version}.tgz || _error_exit 'Failed to push node to S3'\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-node-${_version}.md5 s3://${_bucket}/${_key_path}/aws-parallelcluster-node-${_version}.md5 || _error_exit 'Failed to push node md5 to S3'\n    aws ${_profile} --region \"${_region}\" s3api head-object --bucket ${_bucket} --key ${_key_path}/aws-parallelcluster-node-${_version}.tgz --output text --query LastModified > aws-parallelcluster-node-${_version}.tgz.date || _error_exit 'Failed to fetch LastModified date'\n    aws ${_profile} --region \"${_region}\" s3 cp aws-parallelcluster-node-${_version}.tgz.date s3://${_bucket}/${_key_path}/aws-parallelcluster-node-${_version}.tgz.date || _error_exit 'Failed to push node date'\n\n    _bucket_region=$(aws ${_profile} s3api get-bucket-location --bucket ${_bucket} --output text)\n    if [ ${_bucket_region} = \"None\" ]; then\n        _bucket_region=\"\"\n    else\n        _bucket_region=\".${_bucket_region}\"\n    fi\n\n    echo \"\"\n    echo \"Done. Add the following configuration to the pcluster create config file:\"\n    echo \"\"\n    echo \"DevSettings:\"\n    echo \"  NodePackage: s3://${_bucket}/${_key_path}/aws-parallelcluster-node-${_version}.tgz\"\n}\n\nmain \"$@\"\n\n# vim:syntax=sh\n", "num_lines": 118}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# The following script checks if git-secrets is installed on a local machine.\n# If not, it prints an error message pointing to the official awslabs git-secrets repository.\n# If yes, it executes the 'git-secrets' command with the argument(s) passed to the script.\n#\n# Usage: \n#   get-secrets-command.sh [COMMAND]\n#\n# Examples:\n#   $ get-secrets-command.sh '--register-aws > /dev/null'\n#   $ get-secrets-command.sh '--pre_commit_hook -- \"$@\"'\n#\n\nif [ -z \"${CI}\" ] || [ \"${CI}\" != true ]; then\n  if ! command -v git-secrets >/dev/null 2>&1; then\n      echo \"git-secrets is not installed. Please visit https://github.com/awslabs/git-secrets#installing-git-secrets\"\n      exit 1\n  fi\n  \n  _command=\"git-secrets $@\"\n  eval \"$_command\"\nfi\n", "num_lines": 24}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nREGULAR_BUCKET=parallelcluster-ui-release-artifacts-us-east-1\nALTERNATIVE_BUCKET=parallelcluster-ui-release-artifacts-eu-west-1\nREGULAR_REGION_FOR_TEMPLATES=\"us-east-1\"\nALTERNATIVE_REGION_FOR_TEMPLATES=\"eu-west-1\"\n\nBUCKETS=(\"$REGULAR_BUCKET\" \"$ALTERNATIVE_BUCKET\")\nREGIONS=(\"$REGULAR_REGION_FOR_TEMPLATES\" \"$ALTERNATIVE_REGION_FOR_TEMPLATES\")", "num_lines": 19}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nerror(){\n echo \"An error has occurred while releasing the infrastructure files.\"\n}\n\n", "num_lines": 17}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\n\nsource ${SCRIPT_DIR}/common.sh\nsource ${SCRIPT_DIR}/bucket_configuration.sh\ntrap 'error' ERR\n\necho \"Uploading the main templates\"\n\"${SCRIPT_DIR}\"/upload.sh \"$SCRIPT_DIR\"\necho \"Uploading accounting template\"\n\"${SCRIPT_DIR}\"/slurm-accounting/upload.sh \"$SCRIPT_DIR\"", "num_lines": 23}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to update the infrastructure of a given PCM environment.\n# An environment is composed of a list of variables with the entrypoints of the environment\n# and a CloudFormation request file where the stack update can be customized,\n# for example by changing the parameters provided to the previous version of the stack\n#\n# Usage: ./infrastructure/update-environment-infra.sh [ENVIRONMENT]\n# Example: ./infrastructure/update-environment-infra.sh demo\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\nFILES=(parallelcluster-ui-cognito.yaml parallelcluster-ui.yaml)\nENVIRONMENT=$1\n. \"${SCRIPT_DIR}/environments/${ENVIRONMENT}-variables.sh\"\n\nBUCKET=$(aws cloudformation describe-stack-resources \\\n  --stack-name \"${INFRA_BUCKET_STACK_NAME}\" \\\n  --logical-resource-id InfrastructureBucket \\\n  --output json \\\n  --query 'StackResources[0].PhysicalResourceId'\\\n  | tr -d '\"' )\n\n# The yaml files describing the infrastructure are uploaded to a private S3 bucket\n# and then used to update the CloudFormation stack, where the same bucket is passed as parameters.\n# This is done to make sure that we deploy all the changes to the infrastructure, and not only the changes\n# made to parallelcluster-ui.yaml (the parent stack)\necho Uploading to: \"${BUCKET}\"\nfor FILE in \"${FILES[@]}\"\ndo\n  aws s3 cp \"${SCRIPT_DIR}/${FILE}\" \"s3://${BUCKET}/${FILE}\"\ndone\n\nBUCKET_URL=\"https://${BUCKET}.s3.${REGION}.amazonaws.com\"\nCLI_INPUT_YAML=$(sed \"s#BUCKET_URL_PLACEHOLDER#${BUCKET_URL}#g\" \"${SCRIPT_DIR}/environments/${ENVIRONMENT}-cfn-update-args.yaml\")\n\n# Launches a new CFN update: the script hangs until the stack is updated\nAWS_PAGER=\"cat\" aws cloudformation update-stack \\\n  --cli-input-yaml \"${CLI_INPUT_YAML}\" \\\n  --stack-name \"${STACK_NAME}\" \\\n  --region \"${REGION}\"\n\naws cloudformation wait stack-update-complete \\\n  --stack-name \"${STACK_NAME}\" \\\n  --region \"${REGION}\"\n", "num_lines": 55}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is just an internal utility script to change all the 1-click links when the bucket changes\n\nsource common.sh\ntrap 'error' ERR\n\nREGIONS=( $(aws ec2 describe-regions --query \"Regions[*].RegionName\" --output text) )\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\n\nfor REGION in \"${REGIONS[@]}\"\ndo\n    if [ \"$REGION\" != \"ap-southeast-3\" ] && [ \"$REGION\" != \"me-central-1\" ];\n    then\n      #FIXME For other partitions we should also parametrize the partition in the URL\n      while IFS= read -r -d '' file\n      do\n        if [[ \"$file\" != *\"node_modules\"* ]]; then\n          # The commented one is for regions not yet on the new name (gov-cloud for example)\n          #sed -i.bak -E \"s/templateURL=.*${REGION}\\.s3\\.${REGION}\\.amazonaws\\.com\\/(.*)yaml(.*)templateURL=.*${REGION}\\.s3\\.${REGION}\\.amazonaws\\.com\\/(.*)yaml/templateURL=https:\\/\\/${REGULAR_BUCKET}\\.s3\\.${REGULAR_REGION_FOR_TEMPLATES}\\.amazonaws\\.com\\/\\1yaml\\2templateURL=https:\\/\\/${ALTERNATIVE_BUCKET}\\.s3\\.${ALTERNATIVE_REGION_FOR_TEMPLATES}\\.amazonaws\\.com\\/\\3yaml/\" \"${file}\" && rm \"${file}.bak\"\n          sed -i.bak -E \"s/templateURL=.*${REGULAR_BUCKET}\\.s3\\.${REGION}\\.amazonaws\\.com\\/(.*)yaml(.*)templateURL=.*${REGULAR_BUCKET}\\.s3\\.${REGION}\\.amazonaws\\.com\\/(.*)yaml/templateURL=https:\\/\\/${REGULAR_BUCKET}\\.s3\\.${REGULAR_REGION_FOR_TEMPLATES}\\.amazonaws\\.com\\/\\1yaml\\2templateURL=https:\\/\\/${ALTERNATIVE_BUCKET}\\.s3\\.${ALTERNATIVE_REGION_FOR_TEMPLATES}\\.amazonaws\\.com\\/\\3yaml/\" \"${file}\" && rm \"${file}.bak\"\n        fi\n      done <   <(find \"$SCRIPT_DIR/..\" -name \"*.md\" -type f -print0)\n    fi\ndone\n\n\n\n\n", "num_lines": 40}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nSCRIPT_DIR=$1\n\nsource ${SCRIPT_DIR}/common.sh\nsource ${SCRIPT_DIR}/bucket_configuration.sh\ntrap 'error' ERR\n\n\nif [ -z \"$SCRIPT_DIR\" ];\nthen\n  echo \"SCRIPT_DIR=$SCRIPT_DIR must be initialized and not empty\"\n  exit 1;\nfi\n\nFILES=(parallelcluster-ui-cognito.yaml parallelcluster-ui.yaml)\n\nfor INDEX in \"${!BUCKETS[@]}\"\ndo\n  echo Uploading to: \"${BUCKETS[INDEX]}\"\n  #FIXME For other partitions we should also parametrize the partition in the URL\n  TEMPLATE_URL=\"https:\\/\\/${BUCKETS[INDEX]}\\.s3\\.${REGIONS[INDEX]}\\.amazonaws\\.com\"\n  sed -i \"s/PLACEHOLDER/${TEMPLATE_URL}/g\" \"${SCRIPT_DIR}/parallelcluster-ui.yaml\"\n  for FILE in \"${FILES[@]}\"\n  do\n      aws s3 cp \"${SCRIPT_DIR}/${FILE}\" \"s3://${BUCKETS[INDEX]}/${FILE}\"\n  done\ndone\n", "num_lines": 40}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "REGION=eu-west-1\nSTACK_NAME=parallelcluster-ui-demo\nINFRA_BUCKET_STACK_NAME=pcluster-manager-github", "num_lines": 3}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may not use this file except in compliance\n# with the License. A copy of the License is located at\n#\n# http://aws.amazon.com/apache2.0/\n#\n# or in the \"LICENSE.txt\" file accompanying this file. This file is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES\n# OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions and\n# limitations under the License.\n\nsource $1/common.sh\nsource $1/bucket_configuration.sh\ntrap 'error' ERR\n\nACCOUNTING_SCRIPT_DIR=\"$1/slurm-accounting\"\n\nif [ ! -d \"$ACCOUNTING_SCRIPT_DIR\" ] || [ ! -r \"$ACCOUNTING_SCRIPT_DIR\" ];\nthen\n  echo \"ACCOUNTING_SCRIPT_DIR=$ACCOUNTING_SCRIPT_DIR must be a readable directory\"\n  exit 1;\nfi\n\nFILES=(accounting-cluster-template.yaml)\n\nfor INDEX in \"${!BUCKETS[@]}\"\ndo\n  echo Uploading to: \"${BUCKETS[INDEX]}\"\n  for FILE in \"${FILES[@]}\"\n  do\n    aws s3 cp \"${ACCOUNTING_SCRIPT_DIR}/${FILE}\" \"s3://${BUCKETS[INDEX]}/slurm-accounting/${FILE}\"\n  done\ndone\n", "num_lines": 36}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nUSAGE=\"$(basename \"$0\") [-h] --tag YYYY.MM.REVISION [--ecr-region REGION, defaults to 'us-east-1'] [--ecr-endpoint PUBLIC_ECR ENDPOINT, defaults to 'public.ecr.aws/pcm']\"\n\nprint_usage() {\n  echo \"$USAGE\" 1>&2\n}\n\nECR_REPO=\"parallelcluster-ui\"\nECR_REGION=\"us-east-1\"\nECR_ENDPOINT=\"public.ecr.aws/pcm\"\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    -h)\n    print_usage\n    exit 1\n    ;;\n    --tag)\n    TAG=$2\n    shift\n    shift\n    ;;\n    --ecr-endpoint)\n    ECR_ENDPOINT=$2\n    shift\n    shift\n    ;;\n    --ecr-region)\n    ECR_REGION=$2\n    shift\n    shift\n    ;;\n    *)\n    print_usage\n    exit 1\n    ;;\nesac\ndone\n\n\nif [ -z $TAG ]; then\n  echo 'No `--tag` parameter specified, exiting' 1>&2\n  exit 1\nelif ! [[ $TAG =~ [0-9]{4}\\.(0[1-9]|1[0-2])\\.[0-9]+ ]]; then\n  echo '`--tag` parameter must be a valid year, month and revision number combo of the following format `YYYY.MM.REVISION`, exiting' 1>&2\n  exit 1\nfi\n\naws ecr-public get-login-password --region \"$ECR_REGION\" | docker login --username AWS --password-stdin \"${ECR_ENDPOINT}\"\n\npushd frontend\nif [ ! -d node_modules ]; then\n  npm install\nfi\ndocker build --build-arg PUBLIC_URL=/ -t frontend-awslambda .\npopd\ndocker build -f Dockerfile.awslambda -t ${ECR_REPO} .\n\nECR_IMAGE_VERSION_TAGGED=${ECR_ENDPOINT}/${ECR_REPO}:${TAG}\nECR_IMAGE_LATEST_TAGGED=${ECR_ENDPOINT}/${ECR_REPO}:latest\n\ndocker tag ${ECR_REPO} ${ECR_IMAGE_VERSION_TAGGED}\ndocker push ${ECR_IMAGE_VERSION_TAGGED}\n\ndocker tag ${ECR_REPO} ${ECR_IMAGE_LATEST_TAGGED}\ndocker push ${ECR_IMAGE_LATEST_TAGGED}\n\necho \"Uploaded: ${ECR_IMAGE_VERSION_TAGGED}, ${ECR_IMAGE_LATEST_TAGGED}\"", "num_lines": 73}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nTAG=latest\n\nUSAGE=\"$(basename \"$0\") [-h] [--stack-name STACKNAME] [--region REGION] [--tag TAG]\"\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    -h)\n    echo \"$USAGE\" >&2\n    exit 1\n    ;;\n    --stack-name)\n    STACKNAME=\"$2\"\n    shift # past argument\n    shift # past value\n    ;;\n    --region)\n    REGION=$2\n    shift # past argument\n    shift # past value\n    ;;\n    --tag)\n    TAG=$2\n    shift # past argument\n    shift # past value\n    ;;\n    *)    # unknown option\n    echo \"$usage\" >&2\n    exit 1\n    ;;\nesac\ndone\n\nif [ -z $REGION ]; then\n    echo \"Error: no region was specified, please provide one using --region REGION, exiting.\"\n    exit 1\nfi\n\nif [ -z $STACKNAME ]; then\n    echo \"Error: no stack name parameter defined, exiting.\"\n    exit 1\nfi\n\n\nfunction resource_id_from_cf_output {\n  echo \"$1\" | grep \"$2\" | cut -d \" \" -f 2\n}\n\nCF_QUERY=\"StackResources[?LogicalResourceId == 'PrivateEcrRepository' || LogicalResourceId == 'ParallelClusterUIFunction'].{ LogicalResourceId: LogicalResourceId, PhysicalResourceId: PhysicalResourceId }\"\nCF_OUTPUT=`aws cloudformation describe-stack-resources --stack-name \"$STACKNAME\" --region \"$REGION\" --query \"$CF_QUERY\" --output text | tr '\\t' ' '`\n\nLAMBDA_NAME=\"$(resource_id_from_cf_output \"$CF_OUTPUT\" \"ParallelClusterUIFunction\")\"\nLAMBDA_ARN=$(aws lambda --region ${REGION} list-functions --query \"Functions[?contains(FunctionName, '$LAMBDA_NAME')] | [0].FunctionArn\" | xargs echo)\n\nACCOUNT_ID=$(aws sts get-caller-identity --query \"Account\" --output text)\nECR_ENDPOINT=\"${ACCOUNT_ID}.dkr.ecr.${REGION}.amazonaws.com\"\nPRIVATE_ECR_REPO=\"$(resource_id_from_cf_output \"$CF_OUTPUT\" \"PrivateEcrRepository\")\"\nIMAGE=${ECR_ENDPOINT}/${PRIVATE_ECR_REPO}:latest\n\npushd frontend\nif [ ! -d node_modules ]; then\n  npm install\nfi\ndocker build --build-arg PUBLIC_URL=/ -t frontend-awslambda .\npopd\ndocker build -f Dockerfile.awslambda -t ${IMAGE} .\n\necho \"Logging in to private repo...\"\naws ecr get-login-password --region ${REGION} | docker login --username AWS --password-stdin \"${ECR_ENDPOINT}\"\necho \"Pushing private docker container...\"\ndocker push ${IMAGE}\necho \"Updating lambda...\"\naws lambda --region ${REGION} update-function-code --function-name ${LAMBDA_ARN} --image-uri ${IMAGE} --publish >/dev/null\n", "num_lines": 78}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nREPO=\"parallelcluster-ui\"\nDIGEST=$(aws ecr describe-images --repository-name \"${REPO}\" \\\n--query 'sort_by(imageDetails,& imagePushedAt)[-2].[imageDigest][0]')\nMANIFEST=$(aws ecr batch-get-image --repository-name \"${REPO}\" --image-ids imageDigest=\"${DIGEST}\" | jq --raw-output --join-output '.images[0].imageManifest')\naws ecr put-image --repository-name \"${REPO}\" --image-tag latest --image-manifest \"${MANIFEST}\"", "num_lines": 6}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nREPO=\"parallelcluster-ui\"\nDIGEST=$(aws ecr describe-images --repository-name \"${REPO}\" \\\n--query 'sort_by(imageDetails,& imagePushedAt)[-1].[imageDigest][0]')\nMANIFEST=$(aws ecr batch-get-image --repository-name \"${REPO}\" --image-ids imageDigest=\"${DIGEST}\" | jq --raw-output --join-output '.images[0].imageManifest')\naws ecr put-image --repository-name \"${REPO}\" --image-tag latest --image-manifest \"${MANIFEST}\"", "num_lines": 6}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "FLASK_RUN_PORT=5001 FLASK_APP=app:run flask run\n", "num_lines": 2}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "RED='\\033[0;31m'\nNC='\\033[0m'\n\ncheck_region() {\n  if [ -z $REGION ]; then\n    echo -e \"${RED}Region is not set. Exiting${NC}\" 1>&2\n    exit 1\n  fi\n}\n\nget_user_pool_id() {\n  aws cognito-idp list-user-pools --region \"$REGION\" --max-results 1 --query 'UserPools[0].Id' --output text\n}\n\ncheck_user_pool_id() {\n  if [ -z $USER_POOL_ID ]; then\n    echo -e \"${RED}Cognito user pool id is NOT set, using first user pool returned by the query${NC}\" 1>&2\n    USER_POOL_ID=`get_user_pool_id`\n    echo -e \"${RED}Chosen Cognito user pool id is ${USER_POOL_ID}${NC}\" 1>&2\n  fi\n}\n", "num_lines": 22}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n\nfunction print_help() {\n  echo \"Usage $0 --region REGION [--user-pool-id USER_POOL_ID]\"\n}\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    -h)\n    print_help  >&2\n    exit 1\n    ;;\n\n    --user-pool-id)\n    USER_POOL_ID=\"$2\"\n    shift\n    shift\n    ;;\n\n    --region)\n    REGION=$2\n    shift\n    shift\n    ;;\n\n    *)    # unknown option\n    print_help  >&2\n    exit 1\n    ;;\nesac\ndone\n\n\n. common.sh\n\ncheck_region\ncheck_user_pool_id\n\naws cognito-idp list-users --region \"$REGION\" --user-pool-id $USER_POOL_ID --query \"Users[].{email: Attributes[?Name == 'email'].Value | [0]}\" --output text | while read USERNAME\ndo\n  USER_GROUPS=$(aws cognito-idp admin-list-groups-for-user --username \"$USERNAME\" --user-pool-id \"$USER_POOL_ID\" --region \"$REGION\" --query 'Groups[*].GroupName' --output text | tr -s '\\t' ',')\n  echo \"$USERNAME|$USER_GROUPS\"\ndone\n", "num_lines": 48}
{"repo_name": "aws-parallelcluster-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nfunction print_help() {\n  echo \"Usage $0 --region REGION --users-export-file PATH [--user-pool-id USER_POOL_ID --temp-pwd TEMP_PASSWORD --no-email]\"\n}\n\nTEMP_PWD='P@ssw0rd'\nSEND_EMAIL=true\n\nwhile [[ $# -gt 0 ]]\ndo\nkey=\"$1\"\n\ncase $key in\n    -h)\n    print_help 1>&2\n    exit 1\n    ;;\n\n    --user-pool-id)\n    USER_POOL_ID=\"$2\"\n    shift\n    shift\n    ;;\n\n    --region)\n    REGION=$2\n    shift\n    shift\n    ;;\n\n    --temp-pwd)\n    TEMP_PWD=$2\n    shift\n    shift\n    ;;\n\n    --no-email)\n    SEND_EMAIL=false\n    shift\n    ;;\n\n    --users-export-file)\n    FILE=$2\n    shift\n    shift\n    ;;\n\n    *)    # unknown option\n    print_help  >&2\n    exit 1\n    ;;\nesac\ndone\n\n. common.sh\n\ncheck_region\ncheck_user_pool_id\n\nif [ -z \"$FILE\" ]; then\n  echo \"Users export file is required. Exiting\" 1>&2\n  exit 1\nfi\n\ncat \"$FILE\" | while read LINE; do\n  EMAIL=\"$(echo \"$LINE\" | cut -d '|' -f 1)\"\n  USER_GROUPS=\"$(echo \"$LINE\" | cut -d '|' -f 2)\"\n\n  echo \"Creating user $EMAIL with groups $USER_GROUPS\"\n\n  suppress_string='--message-action SUPPRESS'\n    if [ $SEND_EMAIL = true ]; then\n      suppress_string=''\n    fi\n  aws cognito-idp admin-create-user --region \"$REGION\" --user-pool-id \"$USER_POOL_ID\" --username \"$EMAIL\" --temporary-password \"$TEMP_PWD\" --user-attributes Name=email,Value=\"$EMAIL\" Name=email_verified,Value=true $suppress_string > /dev/null\n  echo $USER_GROUPS | tr ',' '\\n' | while read USER_GROUP\n\n  do\n    aws cognito-idp admin-add-user-to-group --region \"$REGION\" --user-pool-id \"$USER_POOL_ID\" --username \"$EMAIL\" --group-name $USER_GROUP\n  done\ndone\n\n\necho \"All done\"\n", "num_lines": 86}
{"repo_name": "aws-prototyping-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n##\n# log debug messages if OPEN_API_GATEWAY_DEBUG env var set to 1\n# this is a helper function for debugging our scripts\nlog() {\n  if [ \"$OPEN_API_GATEWAY_DEBUG\" == 1 ]; then\n    echo \"$@\"\n  fi\n}\n\n# Determine which package manager we're using\n# Use pnpm if available, otherwise fall back to npm (it's present if you have node)\n\n# NOTES: removed `yarn` option: yarn v2+ has no backwards compatibility and will\n# fail to run some of the commands because peer dependencies not found;\n# yarn v1 has no significant performance difference from npm/npx\npkg_manager=pnpm\nif ! $pkg_manager -v &> /dev/null; then\n  pkg_manager=npm\nfi\n\nlog \"package manager :: $pkg_manager\"\n\n##\n# installs the passed packages with the package manager in use\ninstall_packages() {\n  log \"installing packages :: $@\"\n\n  if [ \"$pkg_manager\" == \"pnpm\" ]; then\n    reporter=silent\n    if [ \"$OPEN_API_GATEWAY_DEBUG\" == 1 ]; then\n      reporter=default\n    fi\n    $pkg_manager install --reporter=$reporter \"$@\"\n  else\n    silent_switch=\"--silent\"\n    if [ \"$OPEN_API_GATEWAY_DEBUG\" == 1 ]; then\n      silent_switch=\"\"\n    fi\n    $pkg_manager install $silent_switch \"$@\"\n  fi\n}\n\n##\n# runs the passed command with the package manager's proper syntax\nrun_command() {\n  cmd=\"$@\"\n\n  if [ \"$pkg_manager\" == \"pnpm\" ]; then\n    # pnpx cli was deprecated in v6 --> use pnpm dlx\n    runner=\"pnpm dlx\"\n  else\n    runner=\"npx\"\n  fi\n\n  log \"running command $runner $cmd\"\n\n  $runner $cmd >/dev/null 2>&1\n}\n", "num_lines": 63}
{"repo_name": "aws-prototyping-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n##\n# log messages\nlog() {\n  echo \"$@\"\n}\n\n# Determine which package manager we're using\n# Use pnpm if available, otherwise fall back to npm (it's present if you have node)\n\n# NOTES: removed `yarn` option: yarn v2+ has no backwards compatibility and will\n# fail to run some of the commands because peer dependencies not found;\n# yarn v1 has no significant performance difference from npm/npx\npkg_manager=pnpm\nif ! $pkg_manager -v &> /dev/null; then\n  pkg_manager=npm\nfi\n\nlog \"package manager :: $pkg_manager\"\n\n##\n# installs the passed packages with the package manager in use\ninstall_packages() {\n  log \"installing packages :: $@\"\n\n  if [ \"$pkg_manager\" == \"pnpm\" ]; then\n    $pkg_manager install --reporter=default \"$@\"\n  else\n    $pkg_manager install \"$@\"\n  fi\n}\n\n##\n# runs the passed command with the package manager's proper syntax\nrun_command() {\n  cmd=\"$@\"\n\n  if [ \"$pkg_manager\" == \"pnpm\" ]; then\n    runner=\"pnpm exec\"\n  else\n    runner=\"npx\"\n  fi\n\n  log \"running command $runner $cmd\"\n\n  $runner $cmd\n}\n", "num_lines": 51}
{"repo_name": "aws-prototyping-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nmkdir -p .tools\n[[ ! -d .tools/git-secrets ]] && {\n    echo \"=============================================================================================\"\n    echo \"Downloading git-secrets...\"\n    (cd .tools && git clone --depth 1 https://github.com/awslabs/git-secrets.git)\n}\n\n# As the name implies, git-secrets heavily depends on git:\n#\n# a) the config is stored and fetched using 'git config'.\n# b) the search is performed using 'git grep' (other search methods don't work\n#    properly, see https://github.com/awslabs/git-secrets/issues/66)\n#\n# When we run in a CodeBuild build, we don't have a git repo, unfortunately. So\n# when that's the case, 'git init' one on the spot, add all files to it (which\n# because of the .gitignore will exclude dependencies and generated files) and\n# then call 'git-secrets' as usual.\ngit rev-parse --git-dir > /dev/null 2>&1 || {\n    git init --quiet\n    git add -A .\n}\n\n# AWS config needs to be added to this repository's config\n.tools/git-secrets/git-secrets --register-aws\n\n.tools/git-secrets/git-secrets --scan\necho \"git-secrets scan ok\"", "num_lines": 30}
{"repo_name": "aws-prototyping-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nYELLOW='\\033[0;33m'\nCYAN='\\033[0;36m'\nGREEN='\\033[0;32m'\nNO_COLOUR='\\033[0m'\n\nTOTAL_NPM_COUNT=0;\nTOTAL_PYPI_COUNT=0;\nprintf \"`echo $YELLOW`Monthly downloads by Package\\n-----------------------------------------------------------\\n\\n\";\n\nfor NPM_PKG in `npx lerna list`;\ndo\n  PKG_DIR=`npx lerna list --scope $NPM_PKG -l | awk '{ print $3 }'`;\n  PYTHON_PKG=`cat $PKG_DIR/package.json | jq -r .jsii.targets.python.distName`;\n\n  NPM_COUNT=`curl -s https://api.npmjs.org/downloads/range/last-month/$NPM_PKG | jq '[.downloads[].downloads | tonumber] | add'`;\n  PYPI_COUNT=`curl -s https://pypistats.org/api/packages/$PYTHON_PKG/recent | jq '.data.last_month'`;\n\n  [[ \"$PYTHON_PKG\" == \"null\" ]] && PYPI_COUNT=0;\n\n  TOTAL_NPM_COUNT=$(($TOTAL_NPM_COUNT + $NPM_COUNT));\n  TOTAL_PYPI_COUNT=$(($TOTAL_PYPI_COUNT + $PYPI_COUNT));\n\n  printf \"$CYAN$NPM_PKG: $NO_COLOUR$NPM_COUNT (NPM), $PYPI_COUNT (PYPI)\\n\";\ndone\n\nprintf \"$GREEN\\nTOTAL: $NO_COLOUR$TOTAL_NPM_COUNT (NPM), $TOTAL_PYPI_COUNT (PYPI) \\n\";", "num_lines": 27}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------------\n#\n# This script is intended to be used to bump the version of the RFDK modules, update package.json,\n# package-lock.json, and create a commit.\n#\n# to start a version bump, run:\n#     bump.sh <version | version Type>\n#\n# If a version is not provided, the 'minor' version will be bumped.\n# The version can be an explicit version _or_ one of:\n# 'major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', or 'prerelease'.\n#\n# This script utilizes the \"lerna version\" feature as well as the \"standard-version\" node package\n#   https://github.com/lerna/lerna/tree/master/commands/version\n#   https://www.npmjs.com/package/standard-version\n#\n# --------------------------------------------------------------------------------------------------\n\nset -euxo pipefail\ncurrent_version=$(node -p \"require('./package.json').version\")\nif test \"${current_version}\" = \"0.42.0\"; then\n  # The version after 0.42.0 will be 1.0.0\n  version=${1:-major}\nelse\n  version=${1:-minor}\nfi\n\ncd \"$(dirname \"$0\")\"\n\necho \"Starting $version version bump\"\n\nexport NODE_OPTIONS=\"--max-old-space-size=4096 ${NODE_OPTIONS:-}\"\n\n/bin/bash ./install.sh\n\nnpx lerna version $version --yes --exact --no-git-tag-version --no-push\n\n# Another round of install to fix package-lock.jsons\n/bin/bash ./install.sh\n\n# align \"peerDependencies\" to actual dependencies after bump\n# this is technically only required for major version bumps, but in the meantime we shall do it in every bump\n/bin/bash ./scripts/fix-peer-deps.sh\n\n# Generate CHANGELOG and create a commit\nnpx standard-version --skip.tag=true --commit-all\n\n# Get the new version number to do some manual find and replaces\nnew_version=$(node -p \"require('./package.json').version\")\n\n# Update the version of RFDK used in the python examples\nfor exampleSetupPy in $(find ./examples/ -name 'setup.py')\ndo\n  sed -i \"s/\\\"aws-rfdk==[0-9]*\\.[0-9]*\\.[0-9]*\\\"/\\\"aws-rfdk==$new_version\\\"/\" \"$exampleSetupPy\"\ndone\n\n# When standard-version adds a patch release to the changelog, it makes it a smaller header size. This undoes that.\nif [[ $version == \"patch\" ]]; then\n  version_header=\"#\\(## \\[$new_version](.*) (.*)\\)\"\n  sed -i \"s|$version_header|\\1|\" ./CHANGELOG.md\nfi\n\nversion_header=\"# \\[$new_version](.*) (.*)\"\n\n# Add a section to the changelog that states the supported Deadline versions\nDEADLINE_RELEASE_NOTE_URL=\"https://docs.thinkboxsoftware.com/products/deadline/10.2/1_User%20Manual/manual/release-notes.html\"\nDEADLINE_SUPPORTED_VERSIONS=$(node ./scripts/getSupportedDeadlineVersions.ts)\nMIN_DEADLINE_VERSION=$(echo \"$DEADLINE_SUPPORTED_VERSIONS\" | grep 'Min' | cut -f 2 -d ' ')\nMAX_DEADLINE_VERSION=$(echo \"$DEADLINE_SUPPORTED_VERSIONS\" | grep 'Max' | cut -f 2 -d ' ')\ndeadline_version_section=\"\\n\\n\\n### Officially Supported Deadline Versions\\n\\n* [${MIN_DEADLINE_VERSION} to ${MAX_DEADLINE_VERSION}](${DEADLINE_RELEASE_NOTE_URL})\"\nsed -i \"s|\\($version_header\\)|\\1$deadline_version_section|\" ./CHANGELOG.md\n\n# Add a section to the changelog that state the version of CDK being used\ncdk_version=$(node -p \"require('./package.json').devDependencies['aws-cdk-lib']\")\ncdk_version_section=\"\\n\\n\\n### Supported CDK Version\\n\\n* [$cdk_version](https://github.com/aws/aws-cdk/releases/tag/v$cdk_version)\"\nsed -i \"s|\\($version_header\\)|\\1$cdk_version_section|\" ./CHANGELOG.md\n\ngit add .\ngit commit --amend --no-edit\n", "num_lines": 81}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\necho \"Cleaning base directory and tools...\"\n\n# Installation directories\nrm -rf ./node_modules/\nrm -rf ./tools/pkglint/node_modules/\n\n# Build files\nif [ -f .BUILD_COMPLETED ]; then\n    rm .BUILD_COMPLETED\nfi\n\n# Packaging directory\nrm -rf ./dist\n\necho \"Done\"\n", "num_lines": 19}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\nmkdir -p .tools\n[[ ! -d .tools/git-secrets ]] && {\n    echo \"=============================================================================================\"\n    echo \"Downloading git-secrets...\"\n    (cd .tools && git clone --depth 1 https://github.com/awslabs/git-secrets.git)\n}\n\n# As the name implies, git-secrets heavily depends on git:\n#\n# a) the config is stored and fetched using 'git config'.\n# b) the search is performed using 'git grep' (other search methods don't work\n#    properly, see https://github.com/awslabs/git-secrets/issues/66)\n#\n# When we run in a CodeBuild build, we don't have a git repo, unfortunately. So\n# when that's the case, 'git init' one on the spot, add all files to it (which\n# because of the .gitignore will exclude dependencies and generated files) and\n# then call 'git-secrets' as usual.\ngit rev-parse --git-dir > /dev/null 2>&1 || {\n    git init --quiet\n    git add -A .\n\n    # AWS config needs to be added to this fresh repository's config\n    .tools/git-secrets/git-secrets --register-aws\n}\n\n.tools/git-secrets/git-secrets --scan\necho \"git-secrets scan ok\"\n", "num_lines": 31}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\nexec npx yarn install --frozen-lockfile\n", "num_lines": 4}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# creates symlinks under node_modules for all packages in this repo\n# can be used to work against this code base.\nset -euo pipefail\nroot=\"$(cd $(dirname $0) && pwd)\"\n\nmkdir -p node_modules node_modules/.bin\n\nmodules=\"$(find ${root}/packages -name package.json | grep -v node_modules | grep -v init-templates | xargs -n1 dirname)\"\nfor module in ${modules}; do\n  if [[ $(basename $(dirname $module)) == @* ]]; then\n    # This is a @scope/based package\n    scope=$(basename $(dirname $module))\n    link_dir=node_modules/$(basename $(dirname $module))\n    mkdir -p $link_dir\n  else\n    link_dir=node_modules\n  fi\n\n  module_dir=${link_dir}/$(basename $module)\n  echo \"${module} => ${module_dir}\"\n  rm -fr ${module_dir}\n  ln -fs ${module} ${link_dir}\n\n  # Symlink executable scripts into place as well. This is not completely\n  # according to spec (we look in the bin/ directory instead of the { \"scripts\"\n  # } entry in package.json but it's quite a bit easier.\n  if [[ -d $module/bin ]]; then\n    for script in $(find $module/bin -perm /111); do\n      echo \"${script} => node_modules/.bin/$(basename $script)\"\n      ln -fs ${script} node_modules/.bin\n    done\n  fi\ndone\n", "num_lines": 35}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Runs \"npm package\" in all modules. This will produce a \"dist/\" directory in each module.\n# Then, runs rsync to put all the packages in a \"dist/\" directory in the root folder.\n\nset -eu\nexport PATH=$PWD/node_modules/.bin:$PATH\nexport NODE_OPTIONS=\"--max-old-space-size=4096 ${NODE_OPTIONS:-}\"\nroot=$PWD\n\nTMPDIR=${TMPDIR:-$(dirname $(mktemp -u))}\ndistdir=\"$PWD/dist\"\nrm -fr ${distdir}\nmkdir -p ${distdir}\n\n# Split out jsii and non-jsii packages. Jsii packages will be built all at once.\n# Non-jsii packages will be run individually.\necho \"Collecting package list...\" >&2\nscripts/list-packages $TMPDIR/jsii.txt $TMPDIR/nonjsii.txt\n\n# Return lerna scopes from a package list\nfunction lerna_scopes() {\n  while [[ \"${1:-}\" != \"\" ]]; do\n    echo \"--scope $1 \"\n    shift\n  done\n}\n\necho \"Packaging jsii modules\" >&2\n\n# Jsii packaging (all at once using jsii-pacmak)\njsii-pacmak \\\n  --verbose \\\n  --outdir $distdir/ \\\n  $(cat $TMPDIR/jsii.txt)\n\n# Non-jsii packaging, which means running 'package' in every individual\n# module and rsync'ing the result to the shared dist directory.\necho \"Packaging non-jsii modules\" >&2\nlerna run $(lerna_scopes $(cat $TMPDIR/nonjsii.txt)) --sort --concurrency=1 --stream package\n\nfor dir in $(find packages -name dist | grep -v node_modules | grep -v run-wrappers); do\n  echo \"Merging ${dir} into ${distdir}\"\n  rsync -av $dir/ ${distdir}/\ndone\n\n# Remove a JSII aggregate POM that may have snuck past\nrm -rf dist/java/software/amazon/jsii\n\n# Get version from lerna\nversion=\"$(cat ${root}/lerna.json | grep version | cut -d '\"' -f4)\"\n\n# Get commit from CodePipeline (or git, if we are in CodeBuild)\n# If CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local\n# build or CodePipeline build), use the HEAD commit hash).\ncommit=\"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\"\nif [ -z \"${commit}\" ]; then\n  commit=\"$(git rev-parse --verify HEAD)\"\nfi\n\ncat > ${distdir}/build.json <<HERE\n{\n  \"name\": \"aws-rfdk\",\n  \"version\": \"${version}\",\n  \"commit\": \"${commit}\"\n}\nHERE\n\ncp CHANGELOG.md ${distdir}/\n\n# for posterity, print all files in dist\necho \"==============================================================================================\"\necho \" dist contents\"\necho \"==============================================================================================\"\nfind dist/\n", "num_lines": 75}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# This script is only here to illustrate how to add custom user data when using our WorkerInstanceFleet and WorkerInstanceConfiguration constructs\nmkdir test_dir \n", "num_lines": 5}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nrm -rf node_modules/ cdk.out/ cdk.context.json stage/\n", "num_lines": 6}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nrm -rf node_modules/ cdk.out/ cdk.context.json stage/\n", "num_lines": 6}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nrm -rf node_modules/ cdk.out/ cdk.context.json stage/\n", "num_lines": 6}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nrm -rf node_modules/ cdk.out/ cdk.context.json stage/\n", "num_lines": 6}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Accept SSPL license to install MongoDB\n#   - If not set to `true` here, the Repository test component will fail immediately on execution\nexport USER_ACCEPTS_SSPL_FOR_RFDK_TESTS=false\n\n# Version of Deadline to install on farm resources.\n#   -  If not set here, will default to the latest\nexport DEADLINE_VERSION\n\n# Qualified path to staged Deadline assets.\n#   - If not set here, assets will stage automatically to `aws-rfdk/integ/stage`\n#   - If set here, the version found in `manifest.json` at this path will override any value supplied for DEADLINE_VERSION\nexport DEADLINE_STAGING_PATH\n\n# Override for Deadline Docker images that will be used over the images that can be built via the staged Deadline Docker recipes\n#   - If set, it must be a JSON string like:\n#     {\n#       \"repositoryArn\": <string>, (The ECR repository ARN)\n#       \"imageOverrides\": {\n#         <string>: <string>, (key = Deadline Docker recipe name (see ThinkboxManagedDeadlineDockerRecipes in aws-rfdk); value = tag of Docker image to use)\n#         ...\n#       }\n#     }\nexport RFDK_DOCKER_IMAGE_OVERRIDES\n\n# The ARN of the Secret containing a zip file with the UBL certificates to use.\n#   - If unspecified, a secret will be created that contains dummy certificates.\n#   - If this is specified, UBL_LICENSE_MAP must be specified as well.\n#   - For more info, please see https://docs.thinkboxsoftware.com/products/deadline/10.2/1_User%20Manual/manual/licensing-usage-based.html#third-party-usage-based-licensing\nexport UBL_CERTIFICATE_BUNDLE_SECRET_ARN\n\n# Map of UBL licenses and the limits for them.\n#   - This must be specified if UBL_CERTIFICATE_BUNDLE_SECRET_ARN is specified, otherwise this is ignored.\n#   - Expected format is a JSON object where the keys are the name of a product in PascalCase,\n#     and the values are numbers that represent the UBL limit. A limit of 0 is treated as unlimited UBL.\n#   - To see all supported licenses, see the static `for...()` methods in the UsageBasedLicense class in RFDK.\n#\n# Example:\n# {\n#   \"Maya\": 10,\n#   \"Cinema4D\": 0,\n#   // ...\n# }\nexport UBL_LICENSE_MAP\n\n\n# EC2 AMIs to use for Deadline workers\n#   - If not set here, the appropriate basic worker AMI for the version of Deadline and region will be pulled from the public directory\nexport LINUX_DEADLINE_AMI_ID\nexport WINDOWS_DEADLINE_AMI_ID\n\n# Configure test suites to include in end-to-end test\nexport SKIP_deadline_01_repository_TEST\nexport SKIP_deadline_02_renderQueue_TEST\nexport SKIP_deadline_03_workerFleetHttp_TEST\nexport SKIP_deadline_04_workerFleetHttps_TEST\nexport SKIP_deadline_05_secretsManagement_TEST\n\n# All test suites will be run in parallel\nexport RUN_TESTS_IN_PARALLEL=false\n", "num_lines": 65}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -uo pipefail\n\n# Disable exit on error. Errors are manually handled by the script\nset +e\n\nCOMPONENT_NAME=${1:-undefined}\nOPTION=${2:-undefined}\n\nSCRIPT_EXIT_CODE=0\n\nif [[ $(basename $(pwd)) != $COMPONENT_NAME ]]; then\n  echo \"ERROR: Script must be run from top directory of test component\"\n  exit 1\nfi\n\nSKIP_TEST_CHECK=\\$SKIP_${COMPONENT_NAME}_TEST\nSKIP_TEST_CHECK=$(eval \"echo $SKIP_TEST_CHECK\" 2> /dev/null) || SKIP_TEST_CHECK=false\nif [[ ! \"${SKIP_TEST_CHECK}\" = \"true\" ]]; then\n  # Load utility functions\n  source \"../common/scripts/bash/deploy-utils.sh\"\n\n  ensure_component_artifact_dir \"${COMPONENT_NAME}\"\n\n  if [[ $OPTION != '--destroy-only' ]]; then\n\n    deploy_component_stacks $COMPONENT_NAME\n    DEPLOY_EXIT_CODE=$?\n\n    if [[ $DEPLOY_EXIT_CODE -eq 0 ]]\n    then\n      echo \"$(timestamp) [${COMPONENT_NAME}] running test suite started\"\n\n      execute_component_test $COMPONENT_NAME\n      SCRIPT_EXIT_CODE=$?\n\n      echo \"$(timestamp) [${COMPONENT_NAME}] running test suite complete\"\n\n      test_report_path=\"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\"\n      if [[ -f \"${test_report_path}\" ]]\n      then\n        if [[ $(node -pe \"require('${test_report_path}').numFailedTests\") -eq 0 ]]\n        then\n          echo \"$(timestamp) [${COMPONENT_NAME}] test suite passed\"\n        else\n          echo \"$(timestamp) [${COMPONENT_NAME}] test suite failed\"\n        fi\n      fi\n    else\n      SCRIPT_EXIT_CODE=$DEPLOY_EXIT_CODE\n    fi\n\n  fi\n  if [[ $OPTION != '--deploy-and-test-only' ]]; then\n    destroy_component_stacks $COMPONENT_NAME\n    DESTROY_EXIT_CODE=$?\n\n    # We want the exit-code to reflect the deploy and test portion if\n    # non-zero. Otherwise, destroy exit code should be used\n    if [[ $SCRIPT_EXIT_CODE -eq 0 ]]\n    then\n      SCRIPT_EXIT_CODE=$DESTROY_EXIT_CODE\n    fi\n  fi\nfi\n\nexit $SCRIPT_EXIT_CODE\n", "num_lines": 72}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Handle errors manually\nset +e\n# Fail on unset variables\nset -u\n\nCOMPONENT_ROOT=\"$1\"\nCOMPONENT_NAME=$(basename \"$COMPONENT_ROOT\")\nSTART_TIME=$SECONDS\n\nCOMPONENT_E2E_ARG=\"\"\nif [[ \"${DEV_MODE:-false}\" == \"true\" ]]; then\n  COMPONENT_E2E_ARG=\"--deploy-and-test-only\"\nfi\n\n# Before changing directories, we determine the\n# asbolute path of INTEG_TEMP_DIR, since it is a relative\n# path\nexport INTEG_TEMP_DIR=$(readlink -fm \"${INTEG_TEMP_DIR}\")\n\ncd \"$INTEG_ROOT/$COMPONENT_ROOT\"\n\n# Ensure the component's artifact subdir exists\nsource \"../common/scripts/bash/deploy-utils.sh\"\nensure_component_artifact_dir \"${COMPONENT_NAME}\"\n\n(\n    set +e\n    ../common/scripts/bash/component_e2e.sh \"$COMPONENT_NAME\" \"$COMPONENT_E2E_ARG\"\n    exit_code=$?\n    echo $exit_code > \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/exitcode\"\n    exit $exit_code\n)\ntest_exit_code=$?\n\nFINISH_TIME=$SECONDS\ncat > \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/timings.sh\" <<EOF\n${COMPONENT_NAME}_START_TIME=${START_TIME}\n${COMPONENT_NAME}_FINISH_TIME=${FINISH_TIME}\nEOF\n\nexit $test_exit_code\n", "num_lines": 47}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfunction ensure_component_artifact_dir () {\n  component_name=$1\n  # Ensure component artifact sub-directory exists\n  mkdir -p \"${INTEG_TEMP_DIR}/${component_name}\"\n}\n\nfunction deploy_component_stacks () {\n  COMPONENT_NAME=$1\n\n  echo \"$(timestamp) [${COMPONENT_NAME}] app deployment started\"\n\n  ensure_component_artifact_dir \"${COMPONENT_NAME}\"\n\n  # Generate the cdk.out directory which includes a manifest.json file\n  # this can be used to determine the deployment ordering\n  echo \"$(timestamp) [${COMPONENT_NAME}] synthesizing started\"\n  # Synthesis requires AWS API calls for the context methods\n  # (https://docs.aws.amazon.com/cdk/latest/guide/context.html#context_methods)\n  # in our case this is for stack.availabilityZones\n\n  npx cdk synth &> \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/synth.log\"\n  SYNTH_EXIT_CODE=$?\n  echo $SYNTH_EXIT_CODE > \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/synth-exit-code\"\n  if [[ $SYNTH_EXIT_CODE -ne 0 ]]\n  then\n    echo \"$(timestamp) [${COMPONENT_NAME}] synthesizing failed\"\n    echo \"$(timestamp) [${COMPONENT_NAME}] app deployment failed\"\n    return $SYNTH_EXIT_CODE\n  fi\n  echo \"$(timestamp) [${COMPONENT_NAME}] synthesizing complete\"\n\n  echo \"$(timestamp) [${COMPONENT_NAME}] app deployment started\"\n\n  # Empty the deploy log file in case it was non-empty\n  deploy_log_path=\"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/deploy.txt\"\n  cp /dev/null \"${deploy_log_path}\"\n\n  for stack in $(cdk_stack_deploy_order); do\n    echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack deployment started\"\n    npx cdk deploy --app cdk.out --require-approval=never -e \"${stack}\" &>> \"${deploy_log_path}\"\n    STACK_DEPLOY_EXIT_CODE=$?\n    if [[ $STACK_DEPLOY_EXIT_CODE -ne 0 ]]\n    then\n      # Save exit code\n      echo $STACK_DEPLOY_EXIT_CODE > \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/deploy-exit-code\"\n\n      echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack deployment failed\"\n      echo \"$(timestamp) [${COMPONENT_NAME}] app deployment failed\"\n      return $STACK_DEPLOY_EXIT_CODE\n    fi\n    echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack deployment complete\"\n  done\n\n  echo 0 > \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/deploy-exit-code\"\n\n  echo \"$(timestamp) [${COMPONENT_NAME}] app deployment complete\"\n}\n\nfunction cdk_stack_deploy_order () {\n  # Outputs the stacks in topological deploy order\n  \"${INTEG_ROOT}/scripts/node/stack-order\"\n}\n\nfunction cdk_stack_destroy_order () {\n  # Outputs the stacks in topological destroy order\n  \"${INTEG_ROOT}/scripts/node/stack-order\" -r\n}\n\nfunction execute_component_test () {\n  COMPONENT_NAME=$1\n\n  test_report_path=\"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\"\n  test_output_path=\"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-output.txt\"\n\n  ensure_component_artifact_dir \"${COMPONENT_NAME}\"\n  yarn run test \"$COMPONENT_NAME.test\" --json --outputFile=\"${test_report_path}\" &> \"${test_output_path}\"\n}\n\nfunction destroy_component_stacks () {\n  COMPONENT_NAME=$1\n\n  ensure_component_artifact_dir \"${COMPONENT_NAME}\"\n\n  echo \"$(timestamp) [${COMPONENT_NAME}] app destroy started\"\n\n  destroy_log_path=\"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/destroy.txt\"\n  # Empty the destroy log file in case it was non-empty\n  cp /dev/null \"${destroy_log_path}\"\n  for stack in $(cdk_stack_destroy_order); do\n    echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack destroy started\"\n    npx cdk destroy --app cdk.out -e -f \"${stack}\" &>> \"${destroy_log_path}\"\n    STACK_DESTROY_EXIT_CODE=$?\n    if [[ $STACK_DESTROY_EXIT_CODE -ne 0 ]]\n    then\n      echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack destroy failed\"\n      echo \"$(timestamp) [${COMPONENT_NAME}] app destroy failed\"\n      return $STACK_DESTROY_EXIT_CODE\n    fi\n    echo \"$(timestamp) [${COMPONENT_NAME}] -> [${stack}] stack destroy complete\"\n  done\n\n  echo \"$(timestamp) [${COMPONENT_NAME}] app destroy complete\"\n}\n\nfunction timestamp() {\n  date \"+%Y-%m-%dT%H:%M:%S\"\n}\n", "num_lines": 113}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to install jq module for extracting info from JSON files.\n# The script will check whether jq is installed already. If it is, then it will do\n# nothing.\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n\nset -eou pipefail\n\nSCRIPT_LOC=\"$(dirname \"$0\")\"\n\n# Only install jq if it is not already on the system\nif ! which jq\nthen\n    sudo yum install -y jq\nfi\n\nexit 0\n", "num_lines": 26}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Removes renderqueue certification file made by `fetch-cert.sh` between test runs\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n\nrm -rf \"./cert\"\n\nexit 0\n", "num_lines": 16}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to configure a Deadline installation to connect to the render queue and repository at a specified endpoint\n#\n# Input:\n#   ENDPOINT: Endpoint destination for the render queue being queried\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nENDPOINT=$1\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\nCERT=\"$(pwd)/cert\"\n\n# If a user-created CERT file is present, set up certificate for authenticating TLS\nif [ -d \"$CERT\" ]; then\n\n  # Set up client connection settings for TLS by altering ini file with deadlinecommand\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ProxyUseSSL True\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ConnectionType Remote\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ProxySSLCA \"$CERT/ca-cert.crt\"\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ClientSSLAuthentication NotRequired\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ProxyRoot $ENDPOINT\n\nelse\n  # Non-TLS connections can connect to the repository directly\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ProxyUseSSL False\n  sudo $DEADLINE/deadlinecommand SetIniFileSetting ProxySSLCA \"\"\n  sudo $DEADLINE/deadlinecommand ChangeRepository Remote $ENDPOINT >/dev/null\nfi\n\nexit 0\n", "num_lines": 37}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to retrieve the authentication certificate for a render queue from a provided Secret\n#\n# Input:\n#   AWS_REGION: Region where stacks are deployed, taken from AWS.config\n#   SECRET_ARN: ARN for the Secret that has the value of the X.509 certificate needed to authenticate\n#     the RCS TLS. If present, indicates that the render queue is secured by HTTPS and the ARN is used\n#     to extract the key value of the cert.\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nAWS_REGION=$1\nSECRET_ARN=$2\nmkdir -p cert\n\n# Extract the value of the Secret\nexport SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id=$SECRET_ARN --region=$AWS_REGION)\n# Use jq to extract the SecretString (i.e. the key)\nSECRET_STRING=$(jq '.SecretString' <<< \"$SECRET_VALUE\")\n# Format away quotations/escape characters so the key will format correctly, then save it to a temporary file\nSECRET_STRING=${SECRET_STRING#\"\\\"\"}\nSECRET_STRING=${SECRET_STRING%\"\\\"\"}\necho -e $SECRET_STRING > \"./cert/ca-cert.crt\"\n\nexit 0\n", "num_lines": 32}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to query a Deadline repository to confirm the farm's database has been initialized\n#\n# Input:\n#   AWS_REGION: Region where stacks are deployed, taken from AWS.config\n#   DB_SECRET_ARN: Id for the Secret containing username/password information for accessing the database\n# Output:\n#   { \"databases\" : [ { \"name\" : \"deadline10db\" } ], \"ok\" : 1 } \nset -euo pipefail\n\nAWS_REGION=$1\nDB_SECRET_ARN=$2\nCERT=\"$(pwd)/cert\"\n\n# Retrieve login information for the database from its Secret\nDB_SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id=$DB_SECRET_ARN --region=$AWS_REGION)\nDB_SECRET_STRING=$(jq -r '.SecretString' <<< \"$DB_SECRET_VALUE\")\nDB_USERNAME=$(jq -r '.username' <<< \"$DB_SECRET_STRING\")\nDB_PASS=$(jq -r '.password' <<< \"$DB_SECRET_STRING\")\n\nif [ -d \"$CERT\" ]; then\n  # MongoDB instances require retrieving the value of the .pem key created for the database\n  CERT_CA=\"$CERT/ca-cert.crt\"\n\n  # The domain zone for the mongo instance used is hard-coded during setup\n  DB_ADDRESS=\"mongo.renderfarm.local:27017\"\nelse\n  CERT_CA=\"./testScripts/rds-combined-ca-bundle.pem\"\n\n  # DocDB contains the endpoint address to use in its secret\n  ENDPOINT=$(jq -r '.host' <<< \"$DB_SECRET_STRING\")\n  PORT=$(jq -r '.port' <<< \"$DB_SECRET_STRING\")\n  DB_ADDRESS=$ENDPOINT:$PORT\n\nfi\n\n# Mongo command to query for \"deadline10db\" database\nmongo --quiet --ssl --host=\"$DB_ADDRESS\" --sslCAFile=\"$CERT_CA\" --username=\"$DB_USERNAME\" --password=\"$DB_PASS\" --eval='printjson( db.adminCommand( { listDatabases: 1, nameOnly: true, filter: { \"name\": \"deadline10db\" } } ) )'\n\nexit 0\n", "num_lines": 45}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to query an EFS file sytem to retrieve the settings file for the Deadline repository\n#\n# Input:\n#   MOUNT_ID: The test case id, which corresponds to the mount path for the EFS\n# Output:\n#   Non-zero exit code on failure\nset -euo pipefail\n\nMOUNT_ID=$1\n\ncat \"/mnt/efs/fsdl${MOUNT_ID}/DeadlineRepository/settings/repository.ini\"\n\nexit 0\n", "num_lines": 19}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to fetch the repository.ini file from the repository at the RQ endpoint\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Fetch repository.ini from the Deadline repo\n$DEADLINE/deadlinecommand -GetRepositoryFilePath \"settings/repository.ini\"\n\nexit 0\n", "num_lines": 21}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to contact the render queue endpoint to test that it can accept requests\n#\n# Input:\n#   ENDPOINT: Endpoint destination for the render queue being queried\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nENDPOINT=$1\nCERT=\"$(pwd)/cert\"\n\n# If a user-created CERT file is present, set up certificate for authenticating TLS\nif [ -d \"$CERT\" ]; then\n  # Adding https to the endpoint is necessary to use curl\n  ENDPOINT=\"https://\"${ENDPOINT}\n  CURL_ARGS=\"$ENDPOINT -s --cacert ./cert/ca-cert.crt\"\nelse\n  CURL_ARGS=\"$ENDPOINT -s\"\nfi\n\n# Make contact with the render queue endpoint\ncurl $CURL_ARGS\n\nexit 0\n", "num_lines": 31}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to return the username for the process running the RCS as reported by Deadline\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n#   Outputs the username of the process that the Deadline RCS is running as\n\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Fetch repository.ini from the Deadline repo\n$DEADLINE/deadlinecommand -json GetProxyServerInfos | jq -e -r '.result[]|select(.Stat == 1 and .Type == \"Remote\")|.User'\n", "num_lines": 21}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to submit a sample job to the render farm\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Send job to Deadline\n$DEADLINE/deadlinecommand SubmitCommandLineJob -executable \"/usr/bin/sleep\" -arguments \"10\" -frames \"1-10\" -name \"sleeptest\"\n\nexit 0\n", "num_lines": 21}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to send a sample Deadline command to test connection to the render queue\n#\n# Input:\n#   None\n# Output:\n#   Non-zero return code on failure.\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Perform basic command on render queue\n$DEADLINE/deadlinecommand Users\n\nexit 0\n", "num_lines": 21}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to pull the names of workers from a render farm and output the pools, groups, and region the workers are assigned to\n#\n# Input:\n#   None\n# Output:\n#   \"testpool testgroup testregion\"\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# List workers associated with renderqueue\nWORKERS=$($DEADLINE/deadlinecommand GetSlaveNames)\nPOOL_WORKER=$($DEADLINE/deadlinecommand GetSlaveNamesInPool testpool)\nGROUP_WORKER=$($DEADLINE/deadlinecommand GetSlaveNamesInGroup testgroup)\n\n# The list of workers for a region is not easily accessible; this deduces the worker assigned\n# to the region by eliminating the two already assigned to the group and pool\nfor WORKER in $WORKERS; do\n  # Converts the worker name to all lower-case; the Windows workers are created with their names in all-caps\n  WORKER=$(sed -e 's/\\(.*\\)/\\L\\1/' <<< \"$WORKER\")\n  if [ $WORKER != $POOL_WORKER ]; then\n    if [ $WORKER != $GROUP_WORKER ]; then\n      REGION_WORKER=$WORKER\n    fi\n  fi\ndone\n\n$DEADLINE/deadlinecommand GetSlaveSetting $POOL_WORKER Pools\n$DEADLINE/deadlinecommand GetSlaveSetting $GROUP_WORKER Groups\n$DEADLINE/deadlinecommand GetSlaveInfo $REGION_WORKER Region\n\nexit 0\n", "num_lines": 39}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to fetch names of workers associated with the configured render queue\n#\n# Input:\n#   None\n# Output:\n#   A list of names of the workers attached to the render farm\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# List workers associated with renderqueue\nWORKERS=$($DEADLINE/deadlinecommand Slaves)\nWORKERS=$(sed -e 's/\\(.*\\)/\\L\\1/' <<< \"$WORKERS\")\necho $WORKERS\n\nexit 0\n", "num_lines": 23}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to submit test Deadline jobs to be picked up by worker nodes based on their assigned group or pool\n#\n# Input:\n#   JOB_NAME: Name for the test config/job submitted to Deadline. Will be either \"group\" or \"pool\"\n#   ARG: Command line arg added to `deadlinecommand` to submit the job to only the specific group/pool for the test case\n# Output:\n#   A count of the number of entries in the output for `deadlinecommand GetSlavesRenderingJob` for the test job\n\nset -euo pipefail\n\nJOB_NAME=$1\nARG=$2\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Send a sleep command to the render queue; based on the arg passed in, this job will be assigned to the test group or pool\nJOB_ID=$($DEADLINE/deadlinecommand --prettyjson SubmitCommandLineJob -executable \"/usr/bin/sleep\" -arguments \"10\" -frames \"1-10\" -name $JOB_NAME $ARG)\n# We then pull the jobId from the output of `SubmitCommandLineJob`\nJOB_ID=$(jq -r '.result' <<< \"$JOB_ID\")\n\n# Rest to allow time for the worker to pull the job from the render queue\nsleep 7s\n\n# List workers for each job\nASSIGNED_WORKERS=$($DEADLINE/deadlinecommand GetSlavesRenderingJob $JOB_ID)\n\n# Occasionally the above request is made while the worker is between frames, so if the previous\n# operation returns a blank string, this loop will retry every second up to five times\nRETRY_COUNT=0\nwhile [ \"$ASSIGNED_WORKERS\" = \"\" ]; do\n  sleep 1s\n  ASSIGNED_WORKERS=$($DEADLINE/deadlinecommand GetSlavesRenderingJob $JOB_ID)\n  RETRY_COUNT=$(( $RETRY_COUNT + 1 ))\n  if [[ $RETRY_COUNT -eq 5 ]]; then\n    exit 1\n  fi\ndone\n\n# Count the number of workers reported to be assigned to the job\nWORKER_COUNT=0\nfor WORKER in $ASSIGNED_WORKERS; do\n  WORKER_COUNT=$(( $WORKER_COUNT + 1 ))\ndone\n\necho $WORKER_COUNT\n\n# Delete the job when finished\n$DEADLINE/deadlinecommand DeleteJob $JOB_ID >/dev/null\n\nexit 0\n", "num_lines": 55}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to pull the names of workers from a render farm and output the pools, groups, and region the workers are assigned to\n#\n# Input:\n#   None\n# Output:\n#   \"testpool testgroup testregion\"\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# List workers associated with renderqueue\nWORKERS=$($DEADLINE/deadlinecommand GetSlaveNames)\nPOOL_WORKER=$($DEADLINE/deadlinecommand GetSlaveNamesInPool testpool)\nGROUP_WORKER=$($DEADLINE/deadlinecommand GetSlaveNamesInGroup testgroup)\n\n# The list of workers for a region is not easily accessible; this deduces the worker assigned\n# to the region by eliminating the two already assigned to the group and pool\nfor WORKER in $WORKERS; do\n  # Converts the worker name to all lower-case; the Windows workers are created with their names in all-caps\n  WORKER=$(sed -e 's/\\(.*\\)/\\L\\1/' <<< \"$WORKER\")\n  if [ $WORKER != $POOL_WORKER ]; then\n    if [ $WORKER != $GROUP_WORKER ]; then\n      REGION_WORKER=$WORKER\n    fi\n  fi\ndone\n\n$DEADLINE/deadlinecommand GetSlaveSetting $POOL_WORKER Pools\n$DEADLINE/deadlinecommand GetSlaveSetting $GROUP_WORKER Groups\n$DEADLINE/deadlinecommand GetSlaveInfo $REGION_WORKER Region\n\nexit 0\n", "num_lines": 39}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to fetch names of workers associated with the configured render queue\n#\n# Input:\n#   None\n# Output:\n#   A list of names of the workers attached to the render farm\n\nset -euo pipefail\n\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# List workers associated with renderqueue\nWORKERS=$($DEADLINE/deadlinecommand Slaves)\nWORKERS=$(sed -e 's/\\(.*\\)/\\L\\1/' <<< \"$WORKERS\")\necho $WORKERS\n\nexit 0\n", "num_lines": 23}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to submit test Deadline jobs to be picked up by worker nodes based on their assigned group or pool\n#\n# Input:\n#   JOB_NAME: Name for the test config/job submitted to Deadline. Will be either \"group\" or \"pool\"\n#   ARG: Command line arg added to `deadlinecommand` to submit the job to only the specific group/pool for the test case\n# Output:\n#   A count of the number of entries in the output for `deadlinecommand GetSlavesRenderingJob` for the test job\n\nset -euo pipefail\n\nJOB_NAME=$1\nARG=$2\nDEADLINE=\"/opt/Thinkbox/Deadline10/bin\"\n\n# Send a sleep command to the render queue; based on the arg passed in, this job will be assigned to the test group or pool\nJOB_ID=$($DEADLINE/deadlinecommand --prettyjson SubmitCommandLineJob -executable \"/usr/bin/sleep\" -arguments \"10\" -frames \"1-10\" -name $JOB_NAME $ARG)\n# We then pull the jobId from the output of `SubmitCommandLineJob`\nJOB_ID=$(jq -r '.result' <<< \"$JOB_ID\")\n\n# Rest to allow time for the worker to pull the job from the render queue\nsleep 7s\n\n# List workers for each job\nASSIGNED_WORKERS=$($DEADLINE/deadlinecommand GetSlavesRenderingJob $JOB_ID)\n\n# Occasionally the above request is made while the worker is between frames, so if the previous\n# operation returns a blank string, this loop will retry every second up to five times\nRETRY_COUNT=0\nwhile [ \"$ASSIGNED_WORKERS\" = \"\" ]; do\n  sleep 1s\n  ASSIGNED_WORKERS=$($DEADLINE/deadlinecommand GetSlavesRenderingJob $JOB_ID)\n  RETRY_COUNT=$(( $RETRY_COUNT + 1 ))\n  if [[ $RETRY_COUNT -eq 5 ]]; then\n    exit 1\n  fi\ndone\n\n# Count the number of workers reported to be assigned to the job\nWORKER_COUNT=0\nfor WORKER in $ASSIGNED_WORKERS; do\n  WORKER_COUNT=$(( $WORKER_COUNT + 1 ))\ndone\n\necho $WORKER_COUNT\n\n# Delete the job when finished\n$DEADLINE/deadlinecommand DeleteJob $JOB_ID >/dev/null\n\nexit 0\n", "num_lines": 55}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# Script to run a Deadline Secrets Management command.\n#\n# Input:\n#   AWS_REGION: Region where stacks are deployed, taken from AWS.config\n#   SM_CREDENTIALS_ARN: ID for the Secret containing username/password information for accessing Deadline Secrets Management\n#   COMMAND: The Deadline Secrets Management command to run.\n#   ARGS: (Optional Array) Arguments for the Deadline Secrets Management command.\n# Output:\n#   The output of the given Deadline Secrets Management command.\nset -feuo pipefail\n\nARGS=($@)\n\nAWS_REGION=$1\nSM_CREDENTIALS_ARN=$2\nCOMMAND=$3\nSM_CMD_ARGS=(${ARGS[@]:3})\n\nDEADLINE_PATH=\"/opt/Thinkbox/Deadline10/bin\"\n\nSM_SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id=$SM_CREDENTIALS_ARN --region=$AWS_REGION)\nSM_SECRET_STRING=$(jq -r '.SecretString' <<< \"$SM_SECRET_VALUE\")\nSM_USERNAME=$(jq -r '.username' <<< \"$SM_SECRET_STRING\")\nexport SM_PASSWORD=$(jq -r '.password' <<< \"$SM_SECRET_STRING\")\n\n# The syntax ${array[@]+\"${array[@]}\"} is a way to get around the expansion of an empty array raising an unbound variable error since this script\n# sets the \"u\" shell option above. This is a use of the ${parameter+word} shell expansion. If the value of \"parameter\" is unset, nothing will be\n# substituted in its place. If \"parameter\" is set, then the value of \"word\" is used, which is the expansion of the populated array.\n# Since bash treats the expansion of an empty array as an unset variable, we can use this pattern expand the array only if it is populated.\n\"$DEADLINE_PATH/deadlinecommand\" --json secrets $COMMAND \"$SM_USERNAME\" --password env:SM_PASSWORD ${SM_CMD_ARGS[@]+\"${SM_CMD_ARGS[@]}\"}\n\nunset SM_PASSWORD\n", "num_lines": 38}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to clear up extra files between deployments of the integration test framework\n# The script searches for test components configured in the framework and removes the cdk.context.json file and the cdk.out directory from each one where they exist\n# Then, it deletes the integ/node_modules directory so they can be reinstalled\n\nset -euo pipefail\nshopt -s globstar\n\nINTEG_ROOT=\"$(pwd)\"\n\nfor COMPONENT in **/cdk.json; do\n    # In case the yarn install was done inside this integ package, there are some example cdk.json files in the aws-cdk\n    # package we want to avoid.\n    if [[ $COMPONENT == *\"node_modules\"* ]]; then\n        continue\n    fi\n\n    COMPONENT_ROOT=\"$(dirname \"$COMPONENT\")\"\n    rm -f \"${COMPONENT_ROOT}/cdk.context.json\"\n    rm -rf \"${COMPONENT_ROOT}/cdk.out\"\ndone\n\nrm -rf \"$INTEG_ROOT/node_modules\"\n", "num_lines": 28}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to deploy stacks in default configuration for inspection by user\n\nset -euo pipefail\nshopt -s globstar\n\nexport INTEG_ROOT=\"$(pwd)\"\n\n# Create temp directory\nexport INTEG_TEMP_DIR=\"$INTEG_ROOT/.e2etemp\"\nrm -rf $INTEG_TEMP_DIR\nmkdir -p $INTEG_TEMP_DIR\n\nBASH_SCRIPTS=\"$INTEG_ROOT/scripts/bash\"\nINFRASTRUCTURE_APP=\"$INTEG_ROOT/components/_infrastructure\"\n\n# Load environment variables from config file\nif [ ! \"${SKIP_TEST_CONFIG-}\" = true ]; then\n  # Load variables from config file\n  echo \"Loading config...\"\n  source \"$INTEG_ROOT/test-config.sh\"\nfi\n\n# Set variables from script\nsource $BASH_SCRIPTS/set-test-variables.sh\n\nif [ -z ${INTEG_STACK_TAG+x} ]; then\n    # Create a unique tag to add to stack names and some resources\n    export INTEG_STACK_TAG=\"$(date +%s%N)\"\nfi\n\n# Deploy the infrastructure app, a cdk app containing only a VPC to be supplied to the following tests\ncd \"$INFRASTRUCTURE_APP\"\nnpx cdk deploy \"*\" --require-approval=never\n\ncd \"$INTEG_ROOT\"\n\nfor COMPONENT in **/cdk.json; do\n    COMPONENT_ROOT=\"$(dirname \"$COMPONENT\")\"\n    COMPONENT_NAME=$(basename \"$COMPONENT_ROOT\")\n    # Use a pattern match to exclude the infrastructure app from the results\n    if [[ \"$(basename \"$COMPONENT_ROOT\")\" != _* ]]; then\n        # Excecute the e2e test in the component's scripts directory\n        cd \"$INTEG_ROOT/$COMPONENT_ROOT\" && ../common/scripts/bash/component_e2e.sh \"$COMPONENT_NAME\" --deploy-and-test-only || true\n    fi\ndone\n\nexit 0\n", "num_lines": 53}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\nshopt -s globstar\n\n# Deploy the infrastructure app, a cdk app containing only a VPC to be supplied to the following tests\nINFRASTRUCTURE_APP=\"$INTEG_ROOT/components/_infrastructure\"\ncd \"$INFRASTRUCTURE_APP\"\nmkdir -p \"${INTEG_TEMP_DIR}/infrastructure\"\necho \"$(date \"+%Y-%m-%dT%H:%M:%S\") [infrastructure] deployment started\"\n\n# Handle errors manually\nset +e\n\n# Hide the deploy log unless something goes wrong (save the scrollback buffer)\nnpx cdk deploy \"*\" --require-approval=never &> \"${INTEG_TEMP_DIR}/infrastructure/deploy.txt\"\ndeploy_exit_code=$?\n\n# If an exit code was returned from the deployment, output the deploy log\nif [[ $deploy_exit_code -ne 0 ]]\nthen\n    echo \"$(date \"+%Y-%m-%dT%H:%M:%S\") [infrastructure] deployment failed\"\n    cat \"${INTEG_TEMP_DIR}/infrastructure/deploy.txt\"\nelse\n    echo \"$(date \"+%Y-%m-%dT%H:%M:%S\") [infrastructure] deployment complete\"\nfi\n\ncd \"$INTEG_ROOT\"\n\nexit $deploy_exit_code\n", "num_lines": 34}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\n# Only pull AMI ids if one of these variables is not already set\nif [ -z ${LINUX_DEADLINE_AMI_ID+x} ] || [ -z ${WINDOWS_DEADLINE_AMI_ID+x} ]; then\n    DEADLINE_RELEASE=$(sed 's/\\(.*\\..*\\..*\\)\\..*/\\1/' <<< $DEADLINE_VERSION)\n    curl https://awsportal.s3.amazonaws.com/$DEADLINE_RELEASE/Release/amis.json --silent -o \"$INTEG_TEMP_DIR/amis.json\"\n    if [ -z ${LINUX_DEADLINE_AMI_ID+x} ]; then\n        export LINUX_DEADLINE_AMI_ID=$(node -e $'const json = require(\\'./.e2etemp/amis.json\\'); console.log(json[process.argv[1]].worker[\"ami-id\"])' \"$AWS_REGION\")\n    fi\n    if [ -z ${WINDOWS_DEADLINE_AMI_ID+x} ]; then\n        export WINDOWS_DEADLINE_AMI_ID=$(node -e $'const json = require(\\'./.e2etemp/amis.json\\'); console.log(json[process.argv[1]].windowsWorker[\"ami-id\"])' \"$AWS_REGION\")\n    fi\nfi\n", "num_lines": 19}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\nshopt -s globstar\n\nPRETEST_TIME=$(( $PRETEST_FINISH_TIME - $TEST_START_TIME ))\necho \"Pretest setup runtime: $((($PRETEST_TIME / 60) % 60))m $(($PRETEST_TIME % 60))s\"\n\nINFRASTRUCTURE_DEPLOY_TIME=$(( $INFRASTRUCTURE_DEPLOY_FINISH_TIME - $PRETEST_FINISH_TIME ))\necho \"Infrastructure stack deploy runtime: $((($INFRASTRUCTURE_DEPLOY_TIME / 60) % 60))m $(($INFRASTRUCTURE_DEPLOY_TIME % 60))s\"\n\nINFRASTRUCTURE_DESTROY_TIME=$(( $INFRASTRUCTURE_DESTROY_FINISH_TIME - $INFRASTRUCTURE_DESTROY_START_TIME ))\necho \"Infrastructure stack cleanup runtime: $((($INFRASTRUCTURE_DESTROY_TIME / 60) % 60))m $(($INFRASTRUCTURE_DESTROY_TIME % 60))s\"\n\nread_exit_code() {\n    EXIT_CODE_FILENAME=$1\n\n    # Read the test run exit code from the file\n    if [[ -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/${EXIT_CODE_FILENAME}\" ]]\n    then\n        COMPONENT_EXIT_CODE=$(cat \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/${EXIT_CODE_FILENAME}\")\n        echo $COMPONENT_EXIT_CODE\n    else\n        echo -1\n    fi\n}\n\n# Function pulls test results from test output file and calculates time spent on each stage of the test\nreport_results () {\n    COMPONENT_NAME=$1\n\n    echo\n    echo \"============================================================\"\n    echo \"[${COMPONENT_NAME}]: TEST REPORT\"\n    echo \"============================================================\"\n    echo\n\n    # Read the test run exit code from the file\n    COMPONENT_EXIT_CODE=$(read_exit_code exitcode)\n    if [[ $COMPONENT_EXIT_CODE -ge 0 ]]\n    then\n        echo \"Exit code: ${COMPONENT_EXIT_CODE}\"\n    else\n        echo \"Exit code: (unknown)\"\n    fi\n    echo\n\n    # If the component failed, output the deploy and destroy logs for debugging\n    if [[ $COMPONENT_EXIT_CODE -ne 0 ]]\n    then\n        SYNTH_EXIT_CODE=$(read_exit_code synth-exit-code)\n        echo\n\n        if [[ $SYNTH_EXIT_CODE -ne 0 && -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/synth.log\" ]]\n        then\n            echo \"----------------------------------------------\"\n            echo \"[${COMPONENT_NAME}]: Synth Log\"\n            echo \"----------------------------------------------\"\n            echo\n\n            cat \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/synth.log\"\n\n            echo\n        fi\n\n        DEPLOY_EXIT_CODE=$(read_exit_code deploy-exit-code)\n        if [[ $DEPLOY_EXIT_CODE -ne 0 && -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/deploy.txt\" ]]\n        then\n            echo \"----------------------------------------------\"\n            echo \"[${COMPONENT_NAME}]: Deployment Log\"\n            echo \"----------------------------------------------\"\n            echo\n\n            cat \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/deploy.txt\"\n\n            echo\n        fi\n\n        if [[ -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/destroy.txt\" ]]\n        then\n            echo \"----------------------------------------------\"\n            echo \"[${COMPONENT_NAME}]: Destroy log\"\n            echo \"----------------------------------------------\"\n            echo\n\n            cat \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/destroy.txt\"\n\n            echo\n        fi\n    fi\n\n    if [[ -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-output.txt\" ]]\n    then\n        echo \"----------------------------------------------\"\n        echo \"[${COMPONENT_NAME}]: Test output\"\n        echo \"----------------------------------------------\"\n        echo\n\n        cat \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-output.txt\"\n\n        echo\n    fi\n    \n\n    if [[ -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\" ]]\n    then\n        # Get test numbers from jest output\n        TESTS_RAN=$(node -e $'const json = require(process.argv[1]); console.log(json.numTotalTests)' \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\")\n        TESTS_PASSED=$(node -e $'const json = require(process.argv[1]); console.log(json.numPassedTests)' \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\")\n        TESTS_FAILED=$(node -e $'const json = require(process.argv[1]); console.log(json.numFailedTests)' \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\")\n\n        echo \"Results for test component ${COMPONENT_NAME}: \"\n        echo \"  -Tests ran:     ${TESTS_RAN}\"\n        echo \"  -Tests passed:  ${TESTS_PASSED}\"\n        echo \"  -Tests failed:  ${TESTS_FAILED}\"\n\n        if [[ -f \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/timings.sh\" ]]\n        then\n            # File contains bash variable declaration syntax for:\n            #     ${COMPONENT_NAME}_START_TIME\n            #     ${COMPONENT_NAME}_FINISH_TIME\n            source \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/timings.sh\"\n\n            DEPLOY_START_TIME=${COMPONENT_NAME}_START_TIME\n            DEPLOY_FINISH_TIME=$(node -e $'const json = require(process.argv[1]); console.log(json.startTime)' \"${INTEG_TEMP_DIR}/${COMPONENT_NAME}/test-report.json\")\n            DEPLOY_FINISH_TIME=\"${DEPLOY_FINISH_TIME:0:10}\"\n            DESTROY_START_TIME=$(node -e $'const json = require(process.argv[1]); console.log(json.testResults[0].endTime)' \"$INTEG_TEMP_DIR/${COMPONENT_NAME}/test-report.json\")\n            DESTROY_START_TIME=\"${DESTROY_START_TIME:0:10}\"\n            DESTROY_FINISH_TIME=${COMPONENT_NAME}_FINISH_TIME\n\n            # Calculate seconds from when deploy began to when test began\n            DEPLOY_TIME=$(( $DEPLOY_FINISH_TIME - $DEPLOY_START_TIME ))\n            # Calculate seconds from when deploy ended to when teardown began\n            TEST_TIME=$(( $DESTROY_START_TIME - $DEPLOY_FINISH_TIME ))\n            # Calculate seconds from when test ended to when teardown finished\n            DESTROY_TIME=$(( $DESTROY_FINISH_TIME - $DESTROY_START_TIME ))\n\n            echo \"  -Deploy runtime:     $((($DEPLOY_TIME / 60) % 60))m $(($DEPLOY_TIME % 60))s\"\n            echo \"  -Test suite runtime: $((($TEST_TIME / 60) % 60))m $(($TEST_TIME % 60))s\"\n            echo \"  -Cleanup runtime:    $((($DESTROY_TIME / 60) % 60))m $(($DESTROY_TIME % 60))s\"\n        fi\n    fi\n}\n\n# Report test results for each test component\nfor COMPONENT in **/cdk.json; do\n    COMPONENT_ROOT=\"$(dirname \"$COMPONENT\")\"\n    COMPONENT_NAME=$(basename \"$COMPONENT_ROOT\")\n    # Use a pattern match to exclude the infrastructure app from the results\n    if [[ \"$COMPONENT_NAME\" != _* ]]; then\n        report_results $COMPONENT_NAME\n    fi\n    export ${COMPONENT_NAME}_FINISH_TIME=$SECONDS\ndone\n\nexit 0\n", "num_lines": 160}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to run end to end test for configured RFDK components\n# Configuration information for each test is drawn from integ/test-config.sh\n# Script handles stack deployment, execution of the necessary tests, and teardown\n\nset -euo pipefail\nshopt -s globstar\n\nUSAGE=\"Usage: ./$0 [-d]\n\nRuns the RFDK integration tests.\n\nOptions:\n  -d Runs in development mode. CloudFormation stacks will not be torn down and temporary script output will not be deleted.\n  -h Displays this help text.\n\"\n\nexport DEV_MODE=${DEV_MODE:-false}\n\nwhile getopts \"hd\" opt; do\n  case $opt in\n    h)\n        echo \"${USAGE}\"\n        exit 1\n    ;;\n    d)\n      export DEV_MODE=true\n      echo \"Running in development mode...\"\n    ;;\n    \\?)\n        echo -e \"\\n${USAGE}\" >&2\n        exit 1\n    ;;\n  esac\ndone\n\nSCRIPT_EXIT_CODE=0\n\necho \"RFDK end-to-end integration tests started $(date)\"\n\n# Mark test start time\nexport TEST_START_TIME=\"$(date +%s)\"\nSECONDS=$TEST_START_TIME\n\nexport INTEG_ROOT=\"$(pwd)\"\nBASH_SCRIPTS=\"$INTEG_ROOT/scripts/bash\"\n\n# Load environment variables from config file\nif [ ! \"${SKIP_TEST_CONFIG-}\" = true ]; then\n  # Load variables from config file\n  echo \"Loading config...\"\n  source \"$INTEG_ROOT/test-config.sh\"\nfi\n\n# Set variables from script\nsource $BASH_SCRIPTS/set-test-variables.sh\n\n# Make sure SSPL license has been accepted if running repository test\nif [ ! \"${SKIP_deadline_01_repository_TEST-}\" = true ]; then\n    if [ $USER_ACCEPTS_SSPL_FOR_RFDK_TESTS != true ]; then\n        echo \"Error: SSPL license has not been accepted for repository test; test will not run. See README.md for details\"\n        exit 1\n    fi\nfi\n\n# Create temp directory\nexport INTEG_TEMP_DIR=\"$INTEG_ROOT/.e2etemp\"\nrm -rf $INTEG_TEMP_DIR\nmkdir -p $INTEG_TEMP_DIR\n\n# Stage deadline from script\nif [ ! -d \"${DEADLINE_STAGING_PATH}\" ]\nthen\n  $BASH_SCRIPTS/stage-deadline.sh\nfi\n\n# Extract the Deadline version to use for Deadline installations on the farm.\n# Tests allow not specifying or specifying a partial version string such as \"10.1.12\". After staging, we\n# obtain the fully resolved version (e.g. \"10.1.12.1\") which is required to determine\n# the matching AWS Portal AMI IDs\nexport DEADLINE_VERSION=$(node -e $'const json = require(process.argv[1] + \\'/manifest.json\\'); console.log(json.version)' \"$DEADLINE_STAGING_PATH\")\n\n# Find Deadline AMIs based on supplied version\nsource $BASH_SCRIPTS/fetch-worker-amis.sh\n\n# Create a unique tag to add to stack names and some resources\nif [ -z ${INTEG_STACK_TAG+x} ]; then\n    export INTEG_STACK_TAG=\"$(date +%s%N)\"\nfi\n\n# Mark pretest finish time\nexport PRETEST_FINISH_TIME=$SECONDS\n\n# Define cleanup function for deployment failure\ncleanup_on_failure () {\n  if [[ \"$DEV_MODE\" == \"true\" ]]; then\n    echo \"Running in development mode, skipping cleanup...\"\n  else\n    echo \"Performing best-effort full cleanup...\"\n    yarn run tear-down\n  fi\n}\n\nget_component_dirs () {\n  # Find all \"cdk.json\" files (indicates parent dir is a CDK app)\n  find . -name \"cdk.json\"           | \\\n  # Filter out node_modules\n  grep -v node_modules              | \\\n  # Extract the directory name\n  xargs -n1 dirname                 | \\\n  # Filter out apps whose driectories begin with an underscore (_) as this\n  # convention indicates the app is not a test\n  grep -v \"/_\"                      | \\\n  # Sort\n  sort\n}\n\n# Deploy the infrastructure app, a cdk app containing only a VPC to be supplied to the following tests\n$BASH_SCRIPTS/deploy-infrastructure.sh || (\n  echo \"$(date \"+%Y-%m-%dT%H:%M:%S\") [infrastructure] Error deploying infrastructure\"\n  cleanup_on_failure\n  false\n)\n\n# Mark infrastructure deploy finish time\nexport INFRASTRUCTURE_DEPLOY_FINISH_TIME=$SECONDS\n\nXARGS_ARGS=\"-n 1\"\nif [[ \"${RUN_TESTS_IN_PARALLEL-}\" = true ]]\nthen\n  # Instruct xargs to run all the commands in parallel and block until they complete execution\n  XARGS_ARGS=\"${XARGS_ARGS} -P 0\"\nfi\n\n# At this point in processing, we don't want failures to abort the script\n# All statements below this must execute\nset +e\n\n# Run the component tests (potentially in parallel).\nget_component_dirs | xargs ${XARGS_ARGS} components/deadline/common/scripts/bash/component_e2e_driver.sh\n# Capture the exit code for returning later from this process\nSCRIPT_EXIT_CODE=$?\n\n# Destroy the infrastructure stack on completion. \nexport INFRASTRUCTURE_DESTROY_START_TIME=$SECONDS     # Mark infrastructure destroy start time\nif [[ \"$DEV_MODE\" == \"true\" ]]; then\n  echo \"Running in development mode, keeping infrastructure up...\"\nelse\n  $BASH_SCRIPTS/teardown-infrastructure.sh || (\n    echo '$(date \"+%Y-%m-%dT%H:%M:%S\") [infrastructure] Error destroying infrastructure'\n    # This is a best-effort since we always want to report the test results if possible.\n    cleanup_on_failure || true\n  )\nfi\nexport INFRASTRUCTURE_DESTROY_FINISH_TIME=$SECONDS    # Mark infrastructure destroy finish time\n\necho \"Complete!\"\n\n# Report results\n$BASH_SCRIPTS/report-test-results.sh\n\nif [[ \"$DEV_MODE\" == \"true\" ]]; then\n  echo \"Running in development mode, skipping folder cleanup...\"\nelse\n  echo \"Cleaning up folders...\"\n  yarn run clean\nfi\n\necho \"Exiting...\"\n\nexit $SCRIPT_EXIT_CODE\n", "num_lines": 176}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Used as the entry point to run the tests in an automated way. This expects the following env vars to be set:\n# USER_ACCEPTS_SSPL_FOR_RFDK_TESTS - Needs to be 'true' to use these tests\n#\n# Each of these env vars must be set to assume an IAM role in a separate account.\n# If at least one is not set, an IAM role will not be assumed.\n# ROLE_ARN - The role that will be assumed to deploy the integ tests\n# ROLE_SESSION_NAME - A name for the assume role session\n# ROLE_EXTERNAL_ID - The external ID matching the assume role\n# DEADLINE_VERSION - Optional, will default to the latest Deadline version if not set, otherwise the specified version will be used.\n\nset -euo pipefail\n\nif [ ! -z ${ROLE_ARN+x} ] && \\\n   [ ! -z ${ROLE_SESSION_NAME+x} ] && \\\n   [ ! -z ${ROLE_EXTERNAL_ID+x} ]; then\n\n  unset AWS_ACCESS_KEY_ID\n  unset AWS_SECRET_ACCESS_KEY\n  unset AWS_SESSION_TOKEN\n\n  TEST_PROFILE_NAME=integtestrunner\n  # Set up the default profile to dynamically assume-role to the given ROLE_ARN whenever the credentials\n  # need to be refreshed.\n  # Reference: https://docs.aws.amazon.com/cli/latest/topic/config-vars.html#using-aws-iam-roles\n  aws configure --profile ${TEST_PROFILE_NAME} set role_arn ${ROLE_ARN}\n  aws configure --profile ${TEST_PROFILE_NAME} set external_id ${ROLE_EXTERNAL_ID}\n  aws configure --profile ${TEST_PROFILE_NAME} set role_session_name ${ROLE_SESSION_NAME}\n\n  if [ ! -z ${CODEBUILD_BUILD_NUMBER} ]\n  then\n    # Running in a CodeBuild container.\n    # ref: https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html\n    echo \"Running in ECS\"\n    aws configure --profile ${TEST_PROFILE_NAME} set credential_source EcsContainer\n  elif curl -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 5\" 2> /dev/null >& /dev/null\n  then\n    # Running on an EC2 instance\n    echo \"Running on EC2\"\n    aws configure --profile ${TEST_PROFILE_NAME} set credential_source Ec2InstanceMetadata\n  else\n    # Not a container or EC2 instance. Use the AWS_PROFILE profile for the source credentials\n    # for the assume-role; default to the 'default' profile is there is no AWS_PROFILE defined.\n    echo \"Non-AWS local run environment\"\n    aws configure --profile ${TEST_PROFILE_NAME} set source_profile ${AWS_PROFILE:-default}\n  fi\n\n  # Work around a CDK bug: https://github.com/aws/aws-cdk/issues/3396#issuecomment-990609132\n  touch ~/.aws/credentials\n\n  # Must be the last thing that we do in this code path.\n  export AWS_PROFILE=${TEST_PROFILE_NAME}\n  export AWS_STS_REGIONAL_ENDPOINTS=regional\nfi\n\n# Basic integ test configuration\nexport SKIP_TEST_CONFIG=true\n\n./scripts/bash/rfdk-integ-e2e.sh\n\nunset AWS_ACCESS_KEY_ID\nunset AWS_SECRET_ACCESS_KEY\nunset AWS_SESSION_TOKEN\nunset AWS_PROFILE\n", "num_lines": 69}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\necho \"Setting test variables...\"\n\n# Get region from CDK_DEFAULT_REGION; assume us-west-2 if it's not set\nif [ -z ${CDK_DEFAULT_REGION+x} ]; then\n    export AWS_REGION=\"us-west-2\"\nelse\n    export AWS_REGION=$CDK_DEFAULT_REGION\nfi\n\nif [ -z ${USER_ACCEPTS_SSPL_FOR_RFDK_TESTS+x} ]; then\n    export USER_ACCEPTS_SSPL_FOR_RFDK_TESTS=false\nfi\n\n\n# Set staging path to default if not overridden\nif [ -z ${DEADLINE_STAGING_PATH+x} ]; then\n    export DEADLINE_STAGING_PATH=\"$INTEG_ROOT/stage\"\nelif [ $(ls \"$DEADLINE_STAGING_PATH/manifest.json\" 2> /dev/null) ]; then\n    #If path is set, extract the Deadline version to use for Deadline installations on the farm. This will override any other Deadline version provided.\n    export DEADLINE_VERSION=$(node -e $'const json = require(process.argv[1] + \\'/manifest.json\\'); console.log(json.version)' \"$DEADLINE_STAGING_PATH\")\nfi\n", "num_lines": 27}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\n# Check if Deadline assets are staged at configured path\nif [ ! $(ls \"$DEADLINE_STAGING_PATH/manifest.json\" 2> /dev/null) ]; then\n    # If DEADLINE_VERSION is not defined set empty value to get the latest version\n    if [ -z ${DEADLINE_VERSION+x} ]; then\n        export DEADLINE_VERSION=\"\"\n    fi\n    # Stage Deadline assets\n    npx stage-deadline --output \"$DEADLINE_STAGING_PATH\" $DEADLINE_VERSION\nfi\n\nexit 0\n", "num_lines": 19}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to remove all stacks deployed by the framework\n# Searches for configured test components and runs cdk destroy on the app within\n# User must set INTEG_STACK_TAG manually so that the program can find the randomized stack names\n\nset -euo pipefail\nshopt -s globstar\n\nINTEG_ROOT=\"$(pwd)\"\nBASH_SCRIPTS=\"$INTEG_ROOT/scripts/bash\"\nINFRASTRUCTURE_APP=\"$INTEG_ROOT/components/_infrastructure\"\nsource \"$INTEG_ROOT/components/deadline/common/scripts/bash/deploy-utils.sh\"\n\nif [ -z ${INTEG_STACK_TAG+x} ]; then\n    echo \"INTEG_STACK_TAG must be set, exiting...\"\n    exit 1\nfi\n\n# Load environment variables from config file\nif [ ! \"${SKIP_TEST_CONFIG-}\" = true ]; then\n  # Load variables from config file\n  echo \"Loading config...\"\n  source \"$INTEG_ROOT/test-config.sh\"\nfi\n\n# Set variables from script\nsource $BASH_SCRIPTS/set-test-variables.sh\n\n# This is a best-effort. If any component fails to destroy, we proceed and try\n# the others. Disable the exit on error option\nset +e\n\nfor COMPONENT in **/cdk.json; do\n    # In case the yarn install was done inside this integ package, there are some example cdk.json files in the aws-cdk\n    # package we want to avoid.\n    if [[ $COMPONENT == *\"node_modules\"* ]]; then\n        continue\n    fi\n    COMPONENT_ROOT=\"$(dirname \"$COMPONENT\")\"\n    COMPONENT_NAME=$(basename \"$COMPONENT_ROOT\")\n    # Use a pattern match to exclude the infrastructure app from the results\n    if [[ \"$(basename \"$COMPONENT_ROOT\")\" != _* ]]; then\n        # Excecute the e2e test in the component's scripts directory\n        cd \"$INTEG_ROOT/$COMPONENT_ROOT\" && ../common/scripts/bash/component_e2e.sh \"$COMPONENT_NAME\" --destroy-only\n    fi\ndone\n\ncd \"$INFRASTRUCTURE_APP\" && npx cdk destroy \"*\" -f\n\ncd \"$INTEG_ROOT\" && yarn run clean\n\nexit 0\n", "num_lines": 57}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -euo pipefail\n\nsource \"$INTEG_ROOT/components/deadline/common/scripts/bash/deploy-utils.sh\"\n\necho \"$(timestamp) [infrastructure] destroy started\"\nINFRASTRUCTURE_APP=\"$INTEG_ROOT/components/_infrastructure\"\ncd \"$INFRASTRUCTURE_APP\"\n\nmkdir -p \"${INTEG_TEMP_DIR}/infrastructure\"\n\n# Hide the destroy log unless something goes wrong (save the scrollback buffer)\nnpx cdk destroy \"*\" -f &> \"${INTEG_TEMP_DIR}/infrastructure/destroy.txt\"\ndestroy_exit_code=$?\n\n# If an exit code was returned from the destroy, output the destroy log\nif [[ $destroy_exit_code -ne 0 ]]\nthen\n    echo \"$(timestamp) [infrastructure] destroy failed\"\n    cat \"${INTEG_TEMP_DIR}/infrastructure/destroy.txt\"\nelse\n    echo \"$(timestamp) [infrastructure] destroy complete\"\nfi\n\nexit $destroy_exit_code\n", "num_lines": 30}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is meant to build a Lambda Layer using Docker. Its usage is:\n#   build_layer.sh <layer_name>\n# The layer_name should map to a directory under the layers directory. Full instructions on how to build and publish\n# a Lambda Layer can be found in the README.\n\nset -euo pipefail\n\nif test $# -lt 1\nthen\n    echo \"Usage: $0 <directory>\"\n    echo \"  Builds the layer located in <directory>\"\n    exit 1\nfi\n\nSCRIPT_DIR=$(dirname $0)\nSCRIPT_NAME=$(basename $0)\nif ! test -f ${PWD}/${SCRIPT_NAME}\nthen\n    echo \"Must be run from the directory containing ${SCRIPT_NAME}\"\n    exit 1\nfi\n\nLAYER_NAME=$(basename $1)\nLAYER_DIR=\"${PWD}/../layers/${LAYER_NAME}\"\nif ! test -d \"${LAYER_DIR}\"\nthen\n    echo \"${LAYER_NAME} directory must a subdirectory of ${PWD}/../layers/\"\n    exit 1\nfi\n\nfor file in layer.zip description.txt license.txt runtimes.txt\ndo\n    test -f \"${LAYER_DIR}/${file}\" && rm -f \"${LAYER_DIR}/${file}\"\ndone\n\ndocker build -t \"${LAYER_NAME}\" \"${LAYER_DIR}/\"\n\n# Run the docker container as the current user.\n# For this to work we need to mount this machine's credentials files\n# inside of the container as read-only.\n\nUSER_OPT=\"-u $(id -u):$(id -g)\"\nUSERFILE_MOUNTS=\"-v /etc/passwd:/etc/passwd:ro -v /etc/shadow:/etc/shadow:ro -v /etc/group:/etc/group:ro\"\ndocker run --rm \\\n    -v \"${LAYER_DIR}\":/tmp/layer ${USERFILE_MOUNTS} \\\n    ${USER_OPT} \\\n    \"${LAYER_NAME}\"\n", "num_lines": 53}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "set -euo pipefail\n\necho \"Cleaning aws-rfdk...\"\n\nrm -rf ./node_modules/\n\n if [ -f ./.jsii ]; then\n     rm ./.jsii\n fi\n if [ -f ./tsconfig.json ]; then\n     rm ./tsconfig.json\n fi\n\necho \"Done aws-rfdk\"\n", "num_lines": 15}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\necho \"Running python tests\"\n\npython3 -m unittest discover -s \"$PWD/lib/deadline/scripts/python\" -b\n\nexit 0\n", "num_lines": 10}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script downloads, installs and configures the cloudwatch agent. Must be run as sudo capable user.\n\nusage() {\n  echo \"This script downloads, installs and configures the CloudWatch agent. Must be run as sudo capable user.\nArguments:\n  -i: [Flag] Attempts to install the CloudWatch agent. If this isn't set we skip right to configuring it.\n  -s: [Flag] Skips the verification of the CloudWatch agent installer. Only relevent if we are trying to install the agent.\n  \\$1: region\n  \\$2: SSM parameter name\n\nNote: Flags must appear before positional parameters\"\n  exit 1\n}\n\n# Don't exit if commands fail\nset -x\n\nfunction install_agent {\n  region=\"$1\"\n  # Check if amazon-cloudwatch-agent is already installed\n  if rpm -qa | grep amazon-cloudwatch-agent\n  then\n    return\n  fi\n\n  TMPDIR=$(mktemp -d)\n  pushd $TMPDIR 2>&1 > /dev/null\n\n  # Download CloudWatch agent installer\n  aws s3api get-object --region $region --bucket amazoncloudwatch-agent-$region --key amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm amazon-cloudwatch-agent.rpm\n\n  if [ \"$SKIP_VERIFICATION\" = false ]\n  then\n    aws s3api get-object --region $region --bucket amazoncloudwatch-agent-$region --key assets/amazon-cloudwatch-agent.gpg amazon-cloudwatch-agent.gpg\n    GPG_IMPORT_OUT=$(gpg --no-default-keyring --keyring ./keyring.gpg --import amazon-cloudwatch-agent.gpg 2>&1)\n    GPG_KEY=$(echo \"${GPG_IMPORT_OUT}\" | grep -Eow 'key [0-9A-F]+' | awk '{print $2}')\n    GPG_FINGERPRINT_OUT=$(gpg --no-default-keyring --keyring ./keyring.gpg --fingerprint ${GPG_KEY} 2>&1)\n    GPG_FINGERPRINT=$(echo \"${GPG_FINGERPRINT_OUT}\" | tr -d '[:blank:]' | grep -Eo 'fingerprint=[0-9A-F]{40}')\n    if test \"${GPG_FINGERPRINT}\" != \"fingerprint=937616F3450B7D806CBD9725D58167303B789C72\"\n    then\n        # Key failed to verify. Alert AWS!!\n        echo \"ERROR: Key failed to verify.\"\n        popd\n        rm -rf ${TMPDIR}\n        return\n    fi\n\n    aws s3api get-object --region $region --bucket amazoncloudwatch-agent-$region --key amazon_linux/amd64/latest/amazon-cloudwatch-agent.rpm.sig amazon-cloudwatch-agent.rpm.sig\n    if ! gpg --no-default-keyring --keyring ./keyring.gpg --verify amazon-cloudwatch-agent.rpm.sig amazon-cloudwatch-agent.rpm 2>&1\n    then\n        # CloudWatch agent installer failed to verify. Alert AWS!!\n        echo \"ERROR: Agent installer failed to verify\"\n        popd\n        rm -rf ${TMPDIR}\n        return\n    fi\n  fi\n\n  # Run the CloudWatch agent installer\n  sudo rpm -U ./amazon-cloudwatch-agent.rpm\n\n  popd\n  rm -rf ${TMPDIR}\n}\n\necho \"Starting CloudWatch installation and configuration script.\"\n\n# Parse options\nSKIP_VERIFICATION=false\nINSTALL_AGENT=false\nOPTIND=1 # Reset index for getopts in case of previous invocations\nwhile getopts \"is\" opt; do\n  case $opt in\n  i) INSTALL_AGENT=true ;;\n  s) SKIP_VERIFICATION=true ;;\n  \\?) echo \"ERROR: Unknown option specified\"; usage ;;\n  esac\ndone\nshift $((OPTIND - 1))\n\n# Parse positional arguments\nif (($# != 2))\nthen\n  echo \"ERROR: Invalid arguments\"\n  usage\nfi\nREGION=\"$1\"\nSSM_PARAMETER_NAME=\"$2\"\n\n# Check if we want to attempt to install the agent\nif $INSTALL_AGENT\nthen\n  install_agent $REGION\nelse\n  echo \"Skipped installation of CloudWatch agent\"\nfi\n\n# starts the agent\n/opt/aws/amazon-cloudwatch-agent/bin/amazon-cloudwatch-agent-ctl -a append-config -m ec2 -c ssm:$SSM_PARAMETER_NAME -s\n\necho \"Script completed successfully.\"\n", "num_lines": 107}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script downloads and installs the Lustre client.\n# See https://docs.aws.amazon.com/fsx/latest/LustreGuide/install-lustre-client.html\n\nset -xeu\nshopt -s extglob\n\ntrap exit_trap EXIT\nfunction exit_trap() {\n  if [[ $? -ne 0 ]]; then\n    echo \"ERROR: An error occurred while attempting to install the Lustre client on your device. \\\n    Please refer to the FSx for Lustre documentation: https://docs.aws.amazon.com/fsx/latest/LustreGuide/install-lustre-client.html\"\n  fi\n}\n\nfunction is_kernel_version_lower() {\n  local IFS='.-'\n  read -r -a lhs_array <<< \"$1\"\n  read -r -a rhs_array <<< \"$2\"\n\n  # Calculate minimum length betweeen the two arrays\n  [[ ${#lhs_array[@]} -lt ${#rhs_array[@]} ]] && n=${#lhs_array[@]} || n=${#rhs_array[@]}\n\n  unset IFS\n  for i in $( seq 0 $((n-1)) ); do\n    local lhs=\"${lhs_array[$i]}\"\n    local rhs=\"${rhs_array[$i]}\"\n    if [[ $lhs =~ ^[0-9]+$ && $rhs =~ ^[0-9]+$ && $lhs -lt $rhs ]]; then\n      return 0\n    fi\n  done\n  return 1\n}\n\nfunction install_on_al2() {\n  architecture=$(uname -m)\n  case $architecture in\n    x86_64)   min_version=\"4.14.104-95.84.amzn2.x86_64\";;\n    aarch64)  min_version=\"4.14.181-142.260.amzn2.aarch64\";;\n    *) echo \"ERROR: Unrecognized Amazon Linux 2 kernel version: $kernel_version\"; exit 1;;\n  esac\n\n  kernel_version=$(uname -r)\n  if is_kernel_version_lower \"$kernel_version\" \"$min_version\"; then\n    echo \"ERROR: Kernel version ($kernel_version) is lower than the minimum required version: $min_version\"\n    exit 1\n  fi\n\n  sudo amazon-linux-extras install -y lustre2.10\n}\n\nfunction install_on_al1() {\n  min_version=\"4.14.104-78.84.amzn1.x86_64\"\n\n  kernel_version=$(uname -r)\n  if is_kernel_version_lower \"$kernel_version\" \"$min_version\"; then\n    echo \"ERROR: Kernel version ($kernel_version) is lower than the minimum required version: $min_version\"\n    exit 1\n  fi\n\n  sudo yum install -y lustre-client\n}\n\nfunction verify_lustre_kmod() {\n  if ! sudo modprobe -v --first-time lustre; then\n    echo \"ERROR: Lustre client kernel modules were not installed successfully. See above logs for more information.\"\n    exit 1\n  fi\n\n  sudo lustre_rmmod\n}\n\nfunction install_on_rhel() {\n  # Note: In addition to installing the lustre client packages, an additional \"kmod-lustre-client\" package also needs to be\n  # installed. This package contains kernel-specific modules used by the lustre client.\n\n  # Create map of RHEL release to kernel version shell patterns. See https://access.redhat.com/articles/3078\n  # This mapping is needed to determine which version of the Lustre client to install based on the instructions at\n  # https://docs.aws.amazon.com/fsx/latest/LustreGuide/install-lustre-client.html#lustre-client-rhel\n  declare -A rhel_kernel_versions\n  rhel_kernel_versions=(\n    [7.5]='3.10.0-862.*'\n    [7.6]='3.10.0-957.*'\n    [7.7]='3.10.0-1062.*'\n    [7.8]='3.10.0-1127.*'\n    [7.9]='3.10.0-1160.*'\n    [8.1]='4.18.0-147.*'\n    [8.2]='4.18.0-193.*'\n    [8.3]='4.18.0-240.*'\n    [8.4]='4.18.0-305.*'\n  )\n\n  kernel_version=$(uname -r)\n\n  id=$(grep ^ID= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\n  if [[ $id = \"centos\" ]]; then\n    # Map CentOS release to the RHEL release it was based on\n    # This information can be found by referring to the CentOS release announcements\n    # For example, see announcement for CentOS 7 (1804): https://lists.centos.org/pipermail/centos-announce/2018-May/022829.html\n    #\n    # The major and minor versions of CentOS releases match that of RHEL,\n    # so we can just extract those bits and treat them as the RHEL version\n    rhel_version=$(awk '{print $4}' /etc/centos-release | awk -F \".\" '{print $1\".\"$2}')\n  else\n    rhel_version=$(grep ^VERSION_ID= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\n  fi\n\n  case $rhel_version in\n    # RHEL 7.5 and 7.6\n    # ----------------\n    7.5|7.6)\n      case $kernel_version in\n        ${rhel_kernel_versions[7.5]}) lustre_version=\"2.10.5\";;\n        ${rhel_kernel_versions[7.6]}) lustre_version=\"2.10.8\";;\n        *) echo \"ERROR: Unsupported kernel version $kernel_version for RHEL $rhel_version\"; exit 1;;\n      esac\n      sudo yum -y install \"https://downloads.whamcloud.com/public/lustre/lustre-${lustre_version}/el7/client/RPMS/x86_64/kmod-lustre-client-${lustre_version}-1.el7.x86_64.rpm\"\n      sudo yum -y install \"https://downloads.whamcloud.com/public/lustre/lustre-${lustre_version}/el7/client/RPMS/x86_64/lustre-client-${lustre_version}-1.el7.x86_64.rpm\"\n\n      verify_lustre_kmod\n    ;;\n\n    # RHEL 7.7, 7.8, and 7.9\n    # ----------------------\n    7.7|7.8|7.9)\n      architecture=$(uname -m)\n      case $architecture in\n        x86_64)\n          distro_name=\"el\"\n          case $kernel_version in\n            ${rhel_kernel_versions[7.7]}) replace_ver=\"7.7\";;\n            ${rhel_kernel_versions[7.8]}) replace_ver=\"7.8\";;\n            ${rhel_kernel_versions[7.9]});; # Do nothing\n            *) echo \"ERROR: Unsupported kernel version $kernel_version for RHEL $rhel_version\"; exit 1;;\n          esac\n        ;;\n        aarch64)\n          distro_name=\"centos\"\n          case $kernel_version in\n            # RHEL 7.8 for ARM-based AWS-Graviton powered instances have the 8.1 kernel version (see AWS docs)\n            ${rhel_kernel_versions[8.1]}) replace_ver=\"7.8\";;\n            ${rhel_kernel_versions[8.2]});; # Do nothing\n            *) echo \"ERROR: Unsupported kernel version $kernel_version for RHEL $rhel_version\"; exit 1;;\n          esac\n        ;;\n        *) echo \"ERROR: Unrecognized architecture: $architecture\"; exit 1;;\n      esac\n\n      curl https://fsx-lustre-client-repo-public-keys.s3.amazonaws.com/fsx-rpm-public-key.asc -o /tmp/fsx-rpm-public-key.asc\n      sudo rpm --import /tmp/fsx-rpm-public-key.asc\n      sudo curl \"https://fsx-lustre-client-repo.s3.amazonaws.com/${distro_name}/7/fsx-lustre-client.repo\" -o /etc/yum.repos.d/aws-fsx.repo\n      if [[ -n \"${replace_ver+x}\" ]]; then\n        sudo sed -i \"s#7#${replace_ver}#\" /etc/yum.repos.d/aws-fsx.repo\n      fi\n\n      sudo yum clean all\n      sudo yum install -y kmod-lustre-client lustre-client\n\n      verify_lustre_kmod\n    ;;\n\n    # RHEL 8.2 or newer\n    # -----------------\n    8.[2-9]|8.[1-9]+([0-9]))\n      case $kernel_version in\n        ${rhel_kernel_versions[8.2]}) replace_ver=\"8.2\";;\n        ${rhel_kernel_versions[8.3]}) replace_ver=\"8.3\";;\n        *)\n          if is_kernel_version_lower \"$kernel_version\" \"${rhel_kernel_versions[8.2]}\"; then\n            echo \"ERROR: Kernel version ($kernel_version) is lower than the minimum required version: ${rhel_kernel_versions[8.2]}\"\n            exit 1\n          fi\n        ;;\n      esac\n\n      curl https://fsx-lustre-client-repo-public-keys.s3.amazonaws.com/fsx-rpm-public-key.asc -o /tmp/fsx-rpm-public-key.asc\n      sudo rpm --import /tmp/fsx-rpm-public-key.asc\n      sudo curl https://fsx-lustre-client-repo.s3.amazonaws.com/el/8/fsx-lustre-client.repo -o /etc/yum.repos.d/aws-fsx.repo\n      if [[ -n \"${replace_ver+x}\" ]]; then\n        # Change the baseurl referenced in aws-fsx.repo so we pull the correct version of the lustre client for this kernel\n        sudo sed -i \"s#8#${replace_ver}#\" /etc/yum.repos.d/aws-fsx.repo\n      fi\n\n      sudo yum clean all\n      sudo yum install -y kmod-lustre-client lustre-client\n\n      verify_lustre_kmod\n    ;;\n    *) echo \"ERROR: Unsupported CentOS/RHEL version: $rhel_version\"; exit 1;;\n  esac\n}\n\nfunction install_on_ubuntu() {\n  ubuntu_version=$(grep ^VERSION_ID= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\n  kernel_version=$(uname -r)\n  architecture=$(uname -m)\n\n  case $ubuntu_version in\n    16.04)\n      code_name=\"xenial\"\n      min_version=\"4.4.0-1092-aws\"\n    ;;\n    18.04)\n      code_name=\"bionic\"\n      case $architecture in\n        x86_64)   min_version=\"4.15.0-1054-aws\";;\n        aarch64)  min_version=\"5.3.0-1023-aws\";;\n        *) echo \"ERROR: Unrecognized architecture: $architecture\"; exit 1;;\n      esac\n    ;;\n    20.04)\n      code_name=\"focal\"\n      case $architecture in\n        x86_64)   min_version=\"5.4.0-1011-aws\";;\n        aarch64)  min_version=\"5.4.0-1015-aws\";;\n        *) echo \"ERROR: Unrecognized architecture: $architecture\"; exit 1;;\n      esac\n    ;;\n    *) echo \"ERROR: Unsupported Ubuntu version: $ubuntu_version\"; exit 1;;\n  esac\n\n  wget -O - https://fsx-lustre-client-repo-public-keys.s3.amazonaws.com/fsx-ubuntu-public-key.asc | sudo apt-key add -\n  sudo bash -c \"echo \\\"deb https://fsx-lustre-client-repo.s3.amazonaws.com/ubuntu $code_name main\\\" > /etc/apt/sources.list.d/fsxlustreclientrepo.list && apt-get update\"\n\n  if is_kernel_version_lower \"$kernel_version\" \"$min_version\"; then\n    echo \"ERROR: Kernel version ($kernel_version) is lower than the minimum required version: $min_version\"\n    exit 1\n  fi\n\n  sudo apt install -y \"lustre-client-modules-${kernel_version}\"\n}\n\nfunction install_on_suse() {\n  sudo wget https://fsx-lustre-client-repo-public-keys.s3.amazonaws.com/fsx-sles-public-key.asc\n  sudo rpm --import fsx-sles-public-key.asc\n  sudo wget https://fsx-lustre-client-repo.s3.amazonaws.com/suse/sles-12/SLES-12/fsx-lustre-client.repo\n\n  sudo zypper -n ar --gpgcheck-strict fsx-lustre-client.repo\n  \n  suse_version=$(grep ^VERSION_ID= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\n  case $suse_version in\n    12.3) sudo sed -i 's#SLES-12#SP3#' /etc/zypp/repos.d/aws-fsx.repo;;\n    12.4) sudo sed -i 's#SLES-12#SP4#' /etc/zypp/repos.d/aws-fsx.repo;;\n    12.5);; # Do nothing\n    *)\n      echo \"ERROR: Unsupported SUSE Linux version: $suse_version\"\n      exit 1\n    ;;\n  esac\n\n  sudo zypper -n refresh\n  sudo zypper -n install lustre-client\n}\n\nif lustre_version=$(lfs --version); then\n  echo \"Lustre client already installed: $lustre_version\"\n  exit 0\nfi\n\necho \"Installing Lustre client...\"\n\nos_id=$(grep ^ID= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\ncase $os_id in\n  rhel|centos)   install_on_rhel;;\n  ubuntu) install_on_ubuntu;;\n  sles)   install_on_suse;;\n  amzn)\n    amzn_version=$(uname -r | awk -F \".\" '{print $5}')\n    case $amzn_version in\n      amzn1)        install_on_al1;;\n      amzn2?(int))  install_on_al2;;\n      *)\n        echo \"WARNING: Unrecognized Amazon Linux version: $amzn_version. Assuming Amazon Linux 2...\"\n        install_on_al2\n      ;;\n    esac\n  ;;\n  *)\n    pretty_name=$(grep ^PRETTY_NAME= /etc/os-release | awk -F \"=\" '{print $2}' | sed s/\\\"//g)\n    echo \"ERROR: Unsupported operating system: $os_id ($pretty_name)\"\n    exit 1\n  ;;\nesac\n", "num_lines": 288}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# A collection of shell functions for using the EC2 Metadata Service Version 2 to fetch information about the EC2 instance\n# that a script is running on.\n# Note that using some of the functions in this script require that the system already has the following applications\n# installed:\n#   * grep\n#   * tr\n#   * curl\n#   * awk\n\nfunction get_metadata_token() {\n    curl -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 30\" 2> /dev/null\n}\n\nfunction authenticate_identity_document() {\n    # Cryptographically verify that the instance identity document is authentic by\n    # using the instructions here: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/verify-pkcs7.html\n    \n    if ! which openssl > /dev/null 2>&1\n    then\n        if ! sudo yum install -y openssl || sudo apt-get install -y openssl\n        then\n            echo \"ERROR -- Authenticating the instance identity document requires openssl\"\n            return 1\n        fi\n    fi\n\n    SCRIPT_DIRECTORY=$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\n    TOKEN=$(get_metadata_token)\n\n    CERT_FILE=$(mktemp)\n    echo \"-----BEGIN PKCS7-----\" > \"${CERT_FILE}\"\n    curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/pkcs7 2> /dev/null >> \"${CERT_FILE}\"\n    echo \"\" >> \"${CERT_FILE}\"\n    echo \"-----END PKCS7-----\" >> \"${CERT_FILE}\"\n\n    DOCUMENT_FILE=$(mktemp)\n    curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document 2> /dev/null > \"${DOCUMENT_FILE}\"\n\n    echo \"Verifying identity document authenticity\"\n    openssl smime -verify -in \"${CERT_FILE}\" -inform PEM -content \"${DOCUMENT_FILE}\" -certfile ${SCRIPT_DIRECTORY}/ec2-certificates.crt -noverify 1> /dev/null\n}\n\nfunction get_identity_document() {\n    # Usage: $0 <token>\n    TOKEN=$1\n    curl -s -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/dynamic/instance-identity/document 2> /dev/null\n}\n\nfunction get_instance_id() {\n    # Get the ec2 instance id of this instance (ex: i-1234567890)\n    # Usage: $0 <token>\n    TOKEN=$1\n    curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/meta-data/instance-id 2> /dev/null\n}\n\nfunction get_region() {\n    # Get the region that this instance is running within (ex: us-west-2)\n    # Usage: $0 <token>\n    TOKEN=$1\n    IDENTITY_DOC=$(get_identity_document ${TOKEN})\n    # The identity doc is a json document, find the 'region' key-value to get the current region.\n    # Convert a line like:   \"region\" : \"us-west-2\",\n    #  into: us-west-2\n    echo $IDENTITY_DOC | tr ',' '\\n' | tr -d '[\",{}]' | grep 'region' | awk '{print $3}'\n}\n\nfunction get_availability_zone() {\n    # Get the availability zone that this instance is running within (ex: us-west-2b)\n    # Usage: $0 <token>\n    TOKEN=$1\n    curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v 'http://169.254.169.254/latest/meta-data/placement/availability-zone' 2> /dev/null\n}\n", "num_lines": 78}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script that will mount a given EBS volume for use.\n# This script will:\n#   1) Attach the volume to this instance if it is not already attached.\n#   2) Format the block volume to the filesystem format that's passed as an\n#      argument to this script. But **ONLY IF** the filesystem has no current format.\n#   3) Mount the volume to the given mount point with the given mount options.\n#   4) Resize the filesystem on the volume if the volume is larger than the formatted\n#      filesystem size.\n#\n# Note: This does **NOT** support multiple partitions on the EBS Volume. \n#       It's expected that we are using the root parition as the filesystem.\n#\n# Script arguments:\n#  $1 -- EBS Volume Identifier (ex: vol-00000000000)\n#  $2 -- Filesystem format.\n#  $3 -- Mount path; directory that we mount the EFS to.\n#        By default, we automatically search for an available one and use the first we find.\n#  $4 -- Mount options for the filesystem; passed to the mount command.\n#  $5 -- (optional) The device name to attach the EBS Volume to. If empty/blank, then this\n#        script will automatically find an unused device to attach the volume to.\n\nset -xefu\n\nif test $# -lt 4\nthen\n    echo \"Usage: $0 <ebs volume id> <filesystem format> <mount path> <mount options> [<device attachment>]\"\n    echo \" <filesystem format> must be one of: xfs  (that is all, for now)\"\n    exit 1\nfi\n\nSCRIPT_LOC=$(dirname $0)\n\nsource \"${SCRIPT_LOC}/metadataUtilities.sh\"\n\nfunction get_attached_device() {\n    # If the given EBS volume is attached, then return the device name it's attached under.\n    # Usage:\n    #   get_attached_device <EBS volume id>\n    # ex:\n    #   get_attached_device vol-1234ba726\n\n    EBS_VOL_ID=$1\n    METADATA_TOKEN=$(get_metadata_token)\n    INSTANCE_ID=$(get_instance_id \"${METADATA_TOKEN}\")\n    AWS_REGION=$(get_region \"${METADATA_TOKEN}\")\n\n    # Example output:\n    #  aws --region us-west-2 ec2 describe-volumes --filters Name=volume-id,Values=vol-0755e90763c1948ad Name=attachment.instance-id,Values=i-0241efb9b8268eff8  --query 'Volumes[].Attachments[].Device'\n    # [\n    #    \"/dev/xvdz\"\n    # ]\n    # If not attached, then the output is:\n    # []\n    DESCRIBE_OUT=$(aws --region ${AWS_REGION} ec2 describe-volumes \\\n                    --filters Name=volume-id,Values=${EBS_VOL_ID} Name=attachment.instance-id,Values=${INSTANCE_ID} \\\n                    --query 'Volumes[].Attachments[].Device' )\n    if echo ${DESCRIBE_OUT} | grep 'dev' 2>&1 > /dev/null\n    then\n        echo $DESCRIBE_OUT | tr -d '][\"[:space:]'\n    else\n        echo \"\"\n    fi\n}\n\nfunction find_available_device_name() {\n    # To attach an EBS volume to this instance we need to attach it to a specific device name\n    # This function finds an unused device name for us to attach the EBS volume to.\n    \n    for suffix in $(echo {z..b})\n    do\n        DEVICE=\"/dev/xvd${suffix}\"\n        if ! test -e ${DEVICE}\n        then\n            echo ${DEVICE}\n            return 0\n        fi\n    done\n    return 1\n}\n\nfunction attach_ebs_volume() {\n    # Attaches the given EBS Volume to this instance, and waits until it has\n    # successfully attached.\n    # Usage:\n    #  attach_ebs_volume <ebs volume id> <device name of EBS volume>\n    # ex:\n    #  attach_ebs_volume vol-134fb8343 /dev/xvdz\n\n    EBS_VOL_ID=$1\n    TARGET_DEV=$2\n    METADATA_TOKEN=$(get_metadata_token)\n    INSTANCE_ID=$(get_instance_id \"${METADATA_TOKEN}\")\n    AWS_REGION=$(get_region \"${METADATA_TOKEN}\")\n\n    # Attach the EBS\n    aws --region \"${AWS_REGION}\" ec2 attach-volume --volume-id \"${EBS_VOL_ID}\" --instance-id \"${INSTANCE_ID}\" --device \"${TARGET_DEV}\"\n    # Wait until the volume has attached\n    while ! test -e \"${TARGET_DEV}\"\n    do \n        sleep 1\n    done\n}\n\nfunction is_partition_table() {\n    # Determine whether or not the given device is a partition table.\n    # Usage:\n    #  is_paritition_table <device name>\n    #  <device name> must be a regular file (no symlinks!)\n    # ex:\n    #  is_paritition_table /dev/nvme1n1\n\n    # Use blkid to determine whether it's a partition table. If it is, then there will be a PTUUID in the blkid output.\n    # ex:\n    # $ blkid -o full /dev/nvme0n1\n    # /dev/nvme0n1: PTUUID=\"24f84068-53be-4ae2-a53d-cbac5515b1af\" PTTYPE=\"gpt\"\n\n    DEVICE_NAME=$1\n\n    sudo blkid -o full \"${DEVICE_NAME}\" | grep 'PTUUID=' > /dev/null\n}\n\nfunction identify_volume() {\n    # Determine the UUID of the filesystem on the given device.\n    # Requires: The device has a filesystem.\n    # Usage:\n    #  identify_filesystem <device name>\n    #  <device name> must be a regular file (no symlinks!)\n    # ex:\n    #  identify_filesystem /dev/nvme0n1\n\n    # Example 'blkid -o export' output:\n    # DEVNAME=/dev/nvme1n1\n    # UUID=a7786831-dd21-40b5-abc5-0c9a9f7929a4\n    # TYPE=xfs\n\n    DEVICE_NAME=$1\n\n    sudo blkid -o export ${DEVICE_NAME} | grep '^UUID=' | cut -s -d '=' -f 2\n}\n\nfunction identify_filesystem() {\n    # Determine what type of filesystem, if any, is present on the given device.\n    # Usage:\n    #  identify_filesystem <device name>\n    #  <device name> must be a regular file (no symlinks!)\n    # ex:\n    #  identify_filesystem /dev/nvme0n1\n\n    # Example 'blkid -o export' output:\n    # DEVNAME=/dev/nvme1n1\n    # UUID=a7786831-dd21-40b5-abc5-0c9a9f7929a4\n    # TYPE=xfs\n\n    # Some TYPE fields:\n    # TYPE=xfs\n    # TYPE=ext2\n    # TYPE=ext3\n    # TYPE=ext4\n    # TYPE=vfat\n\n    DEVICE_NAME=$1\n\n    if BLKID_OUT=$( sudo blkid -o export ${DEVICE_NAME} | grep '^TYPE=' )\n    then\n        echo ${BLKID_OUT} | cut -s -d '=' -f 2\n    else\n        echo \"UNFORMATTED\"\n    fi\n}\n\nfunction format_volume() {\n    # When first attached the EBS volume will not have a filesystem on it\n    # This function is intended to be used to format such a blank volume.\n    # It *can* also be used to wipe a device and give it a new format, as well,\n    # so *be careful*.\n    #\n    # Usage:\n    #  format_volume <device name> <format type>\n    #  <device name> must be a regular file (no symlinks!)\n    #  <format type> must be a valid value for the -t option of mkfs\n    # ex:\n    #  format_volume /dev/nvme0n1\n\n    DEVICE_NAME=$1\n    FORMAT=$2\n\n    RESERVE_BLOCK_OPTION=\"\"\n    if test \"${FORMAT:0:3}\" == \"ext\"\n    then\n        # The -m option for ext filesystems:\n        #  Specify the percentage of the filesystem blocks reserved for the super-user. Default is 5%.\n        # Set this to 0%. This volume will not be a root volume.\n        RESERVE_BLOCK_OPTION=\"-m 0\"\n    fi\n    sudo mkfs -t \"${FORMAT}\" ${RESERVE_BLOCK_OPTION} \"${DEVICE_NAME}\"\n    # Be paranoid. Make sure the drive formatted\n    if ! test \"$(identify_filesystem ${DEVICE_NAME})\" == \"${FORMAT}\"\n    then\n        echo \"ERROR: Device ${DEVICE_NAME} failed to format\"\n        exit 1\n    fi\n}\n\nfunction mount_volume() {\n    # Mount the given device to a specified mount point, and set up /etc/fstab so that it is\n    # remounted on reboot.\n    # Usage:\n    #  mount_volume <device name> <mount point> [<extra mount options>]\n    #  <device name> must be a regular file (no symlinks!)\n    #  <mount point> will be created if it does not already exist.\n    # ex:\n    #  mount_volume /dev/nvme0n1 /var/lib/mongo ro\n\n    DEVICE_NAME=$1\n    MOUNT_POINT=$2\n    EXTRA_MOUNT_OPTIONS=${3:-rw}\n    test -d \"${MOUNT_POINT}\" || sudo mkdir -p \"${MOUNT_POINT}\"\n\n    VOL_UUID=$(identify_volume ${DEVICE_NAME})\n    VOL_TYPE=$(identify_filesystem ${DEVICE_NAME})\n\n    # fstab may be missing a newline at end of file.\n    if test $(tail -c 1 /etc/fstab | wc -l) -eq 0\n    then\n        # Newline was missing, so add one.\n        echo \"\" | sudo tee -a /etc/fstab\n    fi\n\n    echo \"UUID=${VOL_UUID} ${MOUNT_POINT} ${VOL_TYPE} defaults,nofail,${EXTRA_MOUNT_OPTIONS} 0 2\" | sudo tee -a /etc/fstab\n    sudo mount \"${MOUNT_POINT}\"\n}\n\nfunction resize_volume_partition_if_needed() {\n    # If the EBS volume is larger than the formatted disk space, then we need\n    # to resize the filesystem to grow to the EBS volume size.\n    # Usage:\n    #  $0 <device name>\n    #  <device name> must be a regular file (no symlinks!)\n    # ex:\n    #  resize_volume_partition_if_needed /dev/nvme1n1\n\n    # Reference: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/recognize-expanded-volume-linux.html\n\n    DEVICE_NAME=$1\n\n    FS_TYPE=$(identify_filesystem ${DEVICE_NAME})\n    case \"${FS_TYPE}\" in\n    xfs)\n        # xfs_growfs handles checking whether a resize needs to happen or not automatically.\n        # ex:\n        # meta-data=/dev/nvme1n1           isize=512    agcount=5, agsize=655360 blks\n        #          =                       sectsz=512   attr=2, projid32bit=1\n        #          =                       crc=1        finobt=1 spinodes=0\n        # data     =                       bsize=4096   blocks=2883584, imaxpct=25\n        #          =                       sunit=0      swidth=0 blks\n        # naming   =version 2              bsize=4096   ascii-ci=0 ftype=1\n        # log      =internal               bsize=4096   blocks=2560, version=2\n        #          =                       sectsz=512   sunit=0 blks, lazy-count=1\n        # realtime =none                   extsz=4096   blocks=0, rtextents=0\n        # data size unchanged, skipping\n        sudo xfs_growfs -d \"${DEVICE_NAME}\"\n        ;;\n    ext*)\n        # resize2fs handles checking whether a resize needs to happen or not automatically\n        # ex:\n        #  resize2fs 1.42.9 (28-Dec-2013)\n        #  The filesystem is already 2621440 blocks long.  Nothing to do!\n        sudo resize2fs ${DEVICE_NAME}\n        ;;\n    *)\n        echo \"ERROR -- Cannot resize unknown filesystem type '${FS_TYPE}'\"\n        exit 1\n    esac\n}\n\nVOL_ID=$1\nif ! echo $VOL_ID | grep -E 'vol-[A-Fa-f0-9]+' 2>&1 > /dev/null\nthen\n    echo \"ERROR: $VOL_ID does not look like an the id for an EBS volume\"\n    exit 1\nfi\n\nFILESYSTEM_FORMAT=$2\nMOUNT_PATH=$3\nMOUNT_OPTIONS=$4\nGIVEN_TARGET_DEVICE=${5:-}\n\n# Make sure that the EC2 instance identity document is authentic before we use it to fetch\n# information about the instance we're running on.\nauthenticate_identity_document\n\n# If the EBS volume is already attached, then get the device \n# name it's attached as.\nTARGET_DEVICE=$(get_attached_device ${VOL_ID})\n\n# If not set, fall back to $GIVEN_TARGET_DEVICE or finding a device if that's not set either.\nif test \"${TARGET_DEVICE}\" == \"\"\nthen\n    TARGET_DEVICE=${TARGET_DEVICE:-${GIVEN_TARGET_DEVICE:-$(find_available_device_name)}}\n    attach_ebs_volume $VOL_ID $TARGET_DEVICE\nfi\n\nif ! test -e \"${TARGET_DEVICE}\"\nthen\n    echo \"ERROR -- Could not find device ${TARGET_DEVICE}\"\n    exit 1\nfi\n\n# Look through symlinks to the true device file.\nDEVICE_NAME=$(readlink -f \"${TARGET_DEVICE}\")\n\nis_partition_table \"${DEVICE_NAME}\" && echo \"ERROR -- '${DEVICE_NAME}' is a partition table.\" && exit 1\n\nif test \"$(identify_filesystem ${DEVICE_NAME})\" == \"UNFORMATTED\"\nthen\n    format_volume \"${DEVICE_NAME}\" \"${FILESYSTEM_FORMAT}\"\nfi\n\nmount_volume \"${DEVICE_NAME}\" \"${MOUNT_PATH}\" \"${MOUNT_OPTIONS}\"\n\nresize_volume_partition_if_needed $DEVICE_NAME\n", "num_lines": 327}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script will mount an Amazon Elastic File System (EFS) to a specified mount directory on this instance,\n# and set up /etc/fstab so that the EFS is re-mounted on a system reboot.\n#\n# Note: This script uses get_metadata_token and get_region from ./metadataUtilities.sh\n#  Thus, the system must have applications pre-installed as outlined in that file.\n#\n# Script arguments:\n#  $1 -- EFS Identifier (ex: efs-00000000000)\n#  $2 -- Mount path; directory that we mount the EFS to.\n#  $3 -- whether to obtain the EFS mount target's IP address using the EFS API and persist this to\n#        the /etc/hosts file on the system. This allows the script to work when the mounting instance cannot resolve the\n#        mount target using DNS. A value of \"true\" (case sensitive) will  enable this feature. Any other value will\n#        is treated as being disabled.\n#  $4 -- (optional) NFSv4 mount options for the EFS. \n\nset -xeu\n\nif test $# -lt 3\nthen\n  echo \"Usage: $0 FILE_SYSTEM_ID MOUNT_PATH RESOLVE_MOUNT_POINT_USING_API [MOUNT_OPTIONS]\"\n  exit 1\nfi\n\nSCRIPT_DIR=$(dirname $0)\nsource \"${SCRIPT_DIR}/metadataUtilities.sh\"\n\n# Make sure that the EC2 instance identity document is authentic before we use it to fetch\n# information about the instance we're running on.\nauthenticate_identity_document\n\nMETADATA_TOKEN=$(get_metadata_token)\nAWS_REGION=$(get_region \"${METADATA_TOKEN}\")\nAVAILABILITY_ZONE_NAME=$(get_availability_zone \"${METADATA_TOKEN}\")\n\nFILESYSTEM_ID=$1\nMOUNT_PATH=$2\nRESOLVE_MOUNTPOINT_IP_VIA_API=$3\nMOUNT_OPTIONS=\"${4:-}\"\n\nmkdir -p \"${MOUNT_PATH}\"\n\nAMAZON_EFS_PACKAGE=\"amazon-efs-utils\"\nif which yum\nthen\n  PACKAGE_MANAGER=\"yum\"\n  NFS_UTILS_PACAKGE=\"nfs-utils\"\nelse\n  PACKAGE_MANAGER=\"apt-get\"\n  NFS_UTILS_PACKAGE=\"nfs-common\"\nfi\n\nfunction use_amazon_efs_mount() {\n  test -f \"/sbin/mount.efs\" || \"${PACKAGE_MANAGER}\" install -y \"${AMAZON_EFS_PACKAGE}\"\n  return $?\n}\n\nfunction use_nfs_mount() {\n  test -f \"/sbin/mount.nfs4\" || \"${PACKAGE_MANAGER}\" install -y \"${NFS_UTILS_PACKAGE}\"\n  return $?\n}\n\nfunction resolve_mount_target_ip_via_api() {\n  local EFS_FS_ID=$1\n  local MNT_TARGET_RESOURCE_ID=$2\n  local AVAILABILITY_ZONE_NAME=$3\n  local AWS_REGION=$4\n  local MOUNT_POINT_IP=\"\"\n\n  local FILTER_ARGUMENT=\"\"\n  if [[ $MNT_TARGET_RESOURCE_ID == fs-* ]]\n  then\n    # Mounting without an access point\n    FILTER_ARGUMENT=\"--file-system-id ${MNT_TARGET_RESOURCE_ID}\"\n  elif [[ $MNT_TARGET_RESOURCE_ID == fsap-* ]]\n  then\n    # Mounting with an access point\n    FILTER_ARGUMENT=\"--access-point-id ${MNT_TARGET_RESOURCE_ID}\"\n  else\n    echo \"Unsupported mount target resource: ${MNT_TARGET_RESOURCE_ID}\"\n    return 1\n  fi\n\n  # We prioritize the mount target in the same availability zone as the mounting instance\n  # jq sorts with false first then true (https://stedolan.github.io/jq/manual/#sort,sort_by(path_expression), so we\n  # negate the condition in the sort_by(...) expression\n  MOUNT_POINT_JSON=$(aws efs describe-mount-targets \\\n    --region \"${AWS_REGION}\"                      \\\n    ${FILTER_ARGUMENT}                            \\\n    | jq \".MountTargets | sort_by( .AvailabilityZoneName != \\\"${AVAILABILITY_ZONE_NAME}\\\" ) | .[0]\"\n  )\n\n  if [[ -z \"${MOUNT_POINT_JSON}\" ]]\n  then\n    echo \"Could not find mount target for ${MNT_TARGET_RESOURCE_ID}\"\n    return 1\n  fi\n\n  MOUNT_POINT_IP=$(echo \"${MOUNT_POINT_JSON}\" | jq -r .IpAddress)\n  MOUNT_POINT_AZ=$(echo \"${MOUNT_POINT_JSON}\" | jq -r .AvailabilityZoneName )\n\n  if [[ \"${MOUNT_POINT_AZ}\" != \"${AVAILABILITY_ZONE_NAME}\" ]]\n  then\n    set +x\n    echo \"------------------------------------------ WARNING ------------------------------------------\"\n    echo \"Could not find mount target for ${MNT_TARGET_RESOURCE_ID} matching the current availability\"\n    echo \"zone (${AVAILABILITY_ZONE_NAME}). Cross-AZ data charges will be applied. To reduce costs,\"\n    echo \"add a mount target for ${MNT_TARGET_RESOURCE_ID} in ${AVAILABILITY_ZONE_NAME}.\"\n    echo \"------------------------------------------ WARNING ------------------------------------------\"\n    set -x\n  fi\n\n  DNS_NAME=\"${EFS_FS_ID}.efs.${AWS_REGION}.amazonaws.com\"\n\n  # Backup the old hosts file\n  cp /etc/hosts \"/etc/hosts.rfdk-backup-$(date +%Y-%m-%dT%H:%M:%S)\"\n  # Remove any existing entries for the target DNS name\n  sed -i -e \"/${DNS_NAME}/d\" /etc/hosts\n  # Write the resolved entry for the target DNS name\n  cat >> /etc/hosts <<EOF\n\n${MOUNT_POINT_IP} ${DNS_NAME} # Added by RFDK\nEOF\n}\n\n# Optionally resolve DNS using the EFS API\nif [[ $RESOLVE_MOUNTPOINT_IP_VIA_API == \"true\"  ]]\nthen\n  # jq is used to query the JSON API response\n  if ! where jq > /dev/null 2>&1\n  then\n    \"${PACKAGE_MANAGER}\" install -y jq\n  fi\n\n  # Get access point ID if available, otherwise file system ID\n  MNT_TARGET_RESOURCE_ID=$FILESYSTEM_ID\n  # The access point is supplied as in the MOUNT_OPTIONS argument, which is a list of comma-separated fstab options.\n  # Here is a sample opts string containing an access point:\n  #\n  #   rw,iam,accesspoint=fsap-1234567890,fsc\n  #\n  # See https://docs.aws.amazon.com/efs/latest/ug/efs-mount-helper.html#mounting-access-points\n  #\n  # We extract that value from MOUNT_OPTIONS here:\n  ACCESS_POINT_MOUNT_OPT=$(echo \"${MOUNT_OPTIONS}\" | sed -e 's#,#\\n#g' | grep 'accesspoint=') || true\n  if [[ ! -z \"${ACCESS_POINT_MOUNT_OPT}\" ]]; then\n    ACCESS_POINT_ID=$(echo \"${ACCESS_POINT_MOUNT_OPT}\" | cut -d= -f2)\n    MNT_TARGET_RESOURCE_ID=\"${ACCESS_POINT_ID}\"\n  fi\n\n  # This feature is treated as a best-effort first choice but falls-back to a regular DNS lookup with a warning emitted\n  resolve_mount_target_ip_via_api \\\n      \"${FILESYSTEM_ID}\"          \\\n      \"${MNT_TARGET_RESOURCE_ID}\" \\\n      \"${AVAILABILITY_ZONE_NAME}\" \\\n      \"${AWS_REGION}\"             \\\n    || echo \"WARNING: Couldn't resolve EFS IP address using the EFS service API endpoint\"\nfi\n\n# Attempt to mount the EFS file system\n\n# fstab may be missing a newline at end of file.\nif test $(tail -c 1 /etc/fstab | wc -l) -eq 0\nthen\n  # Newline was missing, so add one.\n  echo \"\" | tee -a /etc/fstab\nfi\n\nif use_amazon_efs_mount\nthen\n  echo \"${FILESYSTEM_ID}:/ ${MOUNT_PATH} efs defaults,tls,_netdev,${MOUNT_OPTIONS}\" | tee -a /etc/fstab\n  MOUNT_TYPE=efs\nelif use_nfs_mount\nthen\n  echo \"${FILESYSTEM_ID}.efs.${AWS_REGION}.amazonaws.com:/ ${MOUNT_PATH} nfs4 nfsvers=4.1,rsize=1048576,wsize=1048576,hard,timeo=600,retrans=2,noresvport,_netdev,${MOUNT_OPTIONS} 0 0\" | tee -a /etc/fstab\n  MOUNT_TYPE=nfs4\nelse\n  echo \"Could not find suitable mount helper to mount the Elastic File System: ${FILESYSTEM_ID}\"\n  exit 1\nfi\n\n# We can sometimes fail to mount the EFS with a \"Connection reset by host\" error, or similar. \n# To counteract this, as best we can, we try to mount the EFS a handful of times and fail-out\n# only if unable to mount it after that.\nTRIES=0\nMAX_TRIES=20\nwhile test ${TRIES} -lt ${MAX_TRIES} && ! mount -a -t ${MOUNT_TYPE}\ndo\n  let TRIES=TRIES+1\n  sleep 2\ndone\n\n# Check whether the drive as been mounted. Fail if not.\ncat /proc/mounts | grep \"${MOUNT_PATH}\"\nexit $?\n", "num_lines": 200}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script will mount an Amazon FSx for Lustre File System to a specified mount directory on this instance,\n# and set up /etc/fstab so that the file system is re-mounted on a system reboot.\n#\n# This script requires the Lustre client to be already installed on the instance.\n# See https://docs.aws.amazon.com/fsx/latest/LustreGuide/install-lustre-client.html\n#\n# Note: This script uses get_metadata_token and get_region from ./metadataUtilities.sh\n#  Thus, the system must have applications pre-installed as outlined in that file.\n#\n# Script arguments:\n#  $1 -- file system Identifier (ex: fs-00000000000)\n#  $2 -- Mount path; directory that we mount the file system to.\n#  $3 -- Mount name\n#  $4 -- (optional) Lustre mount options for the file system.\n\nset -xeu\n\nif test $# -lt 3\nthen\n  echo \"Usage: $0 <file system ID> <mount path> <mount name> [<mount options>]\"\n  exit 1\nfi\n\nSCRIPT_DIR=$(dirname $0)\nsource \"${SCRIPT_DIR}/metadataUtilities.sh\"\n\n# Make sure that the EC2 instance identity document is authentic before we use it to fetch\n# information about the instance we're running on.\nauthenticate_identity_document\n\nMETADATA_TOKEN=$(get_metadata_token)\nAWS_REGION=$(get_region \"${METADATA_TOKEN}\")\n\nFILESYSTEM_ID=$1\nMOUNT_PATH=$2\nMOUNT_NAME=$3\nMOUNT_OPTIONS=\"${4:-}\"\n\nFILESYSTEM_DNS_NAME=\"${FILESYSTEM_ID}.fsx.${AWS_REGION}.amazonaws.com\"\nMOUNT_OPTIONS=\"defaults,noatime,flock,_netdev,${MOUNT_OPTIONS}\"\n\nsudo mkdir -p \"${MOUNT_PATH}\"\n\n# Attempt to mount the FSx file system\n\n# fstab may be missing a newline at end of file.\nif test $(tail -c 1 /etc/fstab | wc -l) -eq 0\nthen\n  # Newline was missing, so add one.\n  echo \"\" | sudo tee -a /etc/fstab\nfi\n\n# See https://docs.aws.amazon.com/fsx/latest/LustreGuide/mount-fs-auto-mount-onreboot.html\nMOUNT_TYPE=lustre\necho \"${FILESYSTEM_DNS_NAME}@tcp:/${MOUNT_NAME} ${MOUNT_PATH} ${MOUNT_TYPE} ${MOUNT_OPTIONS} 0 0\" | sudo tee -a /etc/fstab\n\n# We can sometimes fail to mount the file system with a \"Connection reset by host\" error, or similar. \n# To counteract this, as best we can, we try to mount the file system a handful of times and fail-out\n# only if unable to mount it after that.\nTRIES=0\nMAX_TRIES=20\nwhile test ${TRIES} -lt ${MAX_TRIES} && ! sudo mount -a -t ${MOUNT_TYPE}\ndo\n  let TRIES=TRIES+1\n  sleep 2\ndone\n\n# Check whether the drive as been mounted. Fail if not.\ncat /proc/mounts | grep \"${MOUNT_PATH}\"\nexit $?\n", "num_lines": 76}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to install MongoDB Community Edition v3.6 from the Mongo.org yum repository.\n#\n# Developer note: For legal reasons we absolutely cannot distribute MongoDB in any way.\n#  This includes distributing the installers, or images with MongoDB pre-installed.\n#  We *can* distribute scripting like this that facilitates the installation of \n#  MongoDB from the official MongoDB repository.\n\nset -xefuo pipefail\n\n# Installation instructions: https://docs.mongodb.com/v3.6/tutorial/install-mongodb-on-red-hat/\n# Note: There are no instructions for Amazon Linux 2, but the RedHat 7 binaries are compatible.\n\nREPO_FILENAME=mongodb-org-3.6.repo\nYUM_REPOS_DIR=/etc/yum.repos.d\n\ncat > \"/tmp/${REPO_FILENAME}\" << EOF\n[mongodb-org-3.6]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64\ngpgcheck=1\nenabled=1\ngpgkey=https://www.mongodb.org/static/pgp/server-3.6.asc\nEOF\n\nsudo mv \"/tmp/${REPO_FILENAME}\" \"${YUM_REPOS_DIR}\"\n# Be paranoid. Make sure the repo file is locked down to root.\nsudo chown root.root \"${YUM_REPOS_DIR}/${REPO_FILENAME}\"\nsudo chmod 600 \"${YUM_REPOS_DIR}/${REPO_FILENAME}\"\n\n# Do the install\nsudo yum install -y mongodb-org\n", "num_lines": 37}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nfunction get_secret_string() {\n  SECRET_ID=$1\n  AWS_REGION=$(echo ${SECRET_ID} | cut -d: -f4)\n  PYTHON_SCRIPT=\"import json,sys; d=json.load(sys.stdin); print d[\\\"SecretString\\\"];\"\n  set +x\n  export RET_VALUE=$(aws --region ${AWS_REGION} secretsmanager get-secret-value --secret-id \"${SECRET_ID}\" | python -c \"${PYTHON_SCRIPT}\" )\n  set -x\n}\n", "num_lines": 14}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# A script for fetching an X.509 certificate for the server from the Secrets\n# that are created by the RFDK's X509CertificatePem\n\n# Command-line arguments\n#  $1 -- Certificate secret ARN\n#  $2 -- Trust chain secret ARN\n#  $3 -- Private key secret ARN\n#  $4 -- Private key passphrase secret ARN\n\nset -xeufo pipefail\n\nif test $# -lt 4\nthen\n  echo \"ERROR -- Incorrect number of options for script. See script header for usage.\"\n  exit 1\nfi\n\nif ! ( which aws && which openssl )\nthen\n  echo \"ERROR -- Need the AWS CLI and openssl to be able to run.\"\n  exit 1\nfi\n\nSCRIPT_DIR=$(dirname $0)\nsource \"${SCRIPT_DIR}/secretsFunction.sh\"\n\nCERT_ID=$1\nCHAIN_ID=$2\nKEY_ID=$3\nKEY_PW_ID=$4\n\nget_secret_string \"${CERT_ID}\" \nprintenv RET_VALUE > ./key.crt\nget_secret_string \"${CHAIN_ID}\" \nprintenv RET_VALUE > ./ca.crt\nget_secret_string \"${KEY_ID}\" \nprintenv RET_VALUE > ./encrypted_key.pem\n\n# Note: We must get the private key passphrase **LAST**. We use the returned\n# environment variable to securely invoke openssl to decrypt the private key.\nget_secret_string \"${KEY_PW_ID}\"\n\n# Decrypt the private key.\nopenssl rsa -in ./encrypted_key.pem -passin env:RET_VALUE -out ./decrypted_key.pem\nunset RET_VALUE\n\ncat key.crt decrypted_key.pem > key.pem\n\n# Validate the certificate and key are valid.\necho \"Validating server key\"\n\nset +x # Do not print out key modulus; it's a secret\nKEY_MODULUS=$(openssl rsa -modulus -noout -in ./decrypted_key.pem | openssl md5)\nCA_MODULUS=$(openssl x509 -modulus -noout -in ./key.crt | openssl md5)\n\ntest \"${KEY_MODULUS}\" == \"${CA_MODULUS}\" || exit 1\nset -x\n\necho \"Success - valid key\"\n", "num_lines": 65}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Command-line arguments:\n#  $1 -- ARN of the Secret containing the admin credentials.\n\nset -xeufo pipefail\n\nif test $# -lt 1\nthen\n  echo \"ERROR -- Incorrect number of options for script. See script header for usage.\"\n  exit 1\nfi\n\nfunction cleanup() {\n  RC=$?\n  # Clean up any secrets\n  if test -f ./adminCredentials.js\n  then\n    rm -f ./adminCredentials.js\n  fi\n  exit ${RC}\n}\n\ntrap cleanup EXIT ERR SIGQUIT SIGKILL SIGTERM SIGPIPE\n\nSCRIPT_DIR=$(dirname $0)\nsource \"${SCRIPT_DIR}/secretsFunction.sh\"\n\nADMIN_CREDENTIALS_ARN=$1\n\necho 'var adminCredentials = JSON.parse(\"' > ./temp.js\nget_secret_string \"${ADMIN_CREDENTIALS_ARN}\"\nprintenv RET_VALUE | sed 's/\"/\\\\\"/g' >> ./temp.js\necho '\");' >> ./temp.js\ncat temp.js | tr -d '\\n' > ./adminCredentials.js\nrm -f ./temp.js\n\nmongo --port 27017 --host localhost ./createAdminUser.js --quiet\nrm -f ./adminCredentials.js\n", "num_lines": 43}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Set up the live/secure configuration for mongo in preparation for starting the\n# service for real.\n\nset -xeufo pipefail\n\ncat /etc/mongod.conf | python ./setupMongodLiveConfig.py > ./mongod.conf.new\nsudo mv ./mongod.conf.new /etc/mongod.conf\n# Make sure mongod user can read the config file\nsudo chmod 640 /etc/mongod.conf\nsudo chown root.mongod /etc/mongod.conf \n", "num_lines": 16}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Set the open files limit to 200k so we don't have dropped/refused connections.\n# Per mongo, the process limit should be 50% of the open file limit too.\nSERVICE_FILE=\"/lib/systemd/system/mongod.service\"\nif test -e \"${SERVICE_FILE}\"\nthen\n    if grep 'LimitNOFILE' \"${SERVICE_FILE}\"\n    then\n        # Note: Only change if the values are their defaults from the MongoDB rpm install.\n        #  Customer might have created a custom AMI with their own limits.\n        sudo sed --in-place=.bak -e 's/^LimitNOFILE=64000$/LimitNOFILE=200000/' -e 's/^LimitNPROC=64000$/LimitNPROC=100000/' \"${SERVICE_FILE}\"\n    else\n        echo \"LimitNOFILE=200000\" | sudo tee -a \"${SERVICE_FILE}\"\n        echo \"LimitNPROC=100000\" | sudo tee -a \"${SERVICE_FILE}\"\n    fi\nelse\n    echo \"ERROR: Could not find systemd configuration file for mongod\"\n    exit 1\nfi\n\n# We changed a systemd file. Need to reload it.\nsudo systemctl daemon-reload\n", "num_lines": 27}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\ncat /etc/mongod.conf | python ./setupMongodNoAuth.py > ./mongod.conf.new\nsudo mv ./mongod.conf.new /etc/mongod.conf\n# Make sure mongod user can read the config file\nsudo chmod 640 /etc/mongod.conf\nsudo chown root.mongod /etc/mongod.conf \n", "num_lines": 11}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Command-line arguments:\n#  $1 -- Storage path of the MongoDB data.\n\nset -xeufo pipefail\n\nif test $# -lt 1\nthen\n  echo \"ERROR -- Incorrect number of options for script. See script header for usage.\"\n  exit 1\nfi\n\nSTORAGE_PATH=$1\n\ncat /etc/mongod.conf | python ./setupMongodStorage.py \"${STORAGE_PATH}\" > ./mongod.conf.new\nsudo mv ./mongod.conf.new /etc/mongod.conf\n# Make sure mongod user can read the config file\nsudo chmod 640 /etc/mongod.conf\nsudo chown root.mongod /etc/mongod.conf \n", "num_lines": 24}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script configures any settings in the deadline.ini file for the rcs then restarts it to ensure they take effect.\n#\n# Arguments:\n# $@ Alternating pairs of Deadline ini file setting names and values.\n\nset -euxo pipefail\n\nargs=(\"$@\")\n\n# Function to check if the RCS is running and listening\nfunction is-rcs-ready() {\n    local rcs_pids=\"$(pgrep deadlinercs)\"\n\n    if [ -z \"$rcs_pids\" ]; then\n        echo \"RCS is not running\"\n        return 1\n    fi\n\n    # Replace newlines with commas as expected by the -p argument of lsof\n    rcs_pids=$(echo \"$rcs_pids\" | paste -s -d ,)\n\n    # Check if the RCS process has any TCP listening sockets\n    lsof -iTCP -sTCP:LISTEN -p \"$rcs_pids\" > /dev/null\n}\n\n# Cloud-init does not load system environment variables. Cherry-pick the\n# environment variable installed by the Deadline Client installer.\nif [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n    source \"/etc/profile.d/deadlineclient.sh\"\nfi\n\n# Find Deadline\nif [ -z \"$DEADLINE_PATH\" ]; then\n    echo \"ERROR: DEADLINE_PATH environment variable not set\"\n    exit 1\nfi\n\n# Find Deadline Command\ndeadlinecommand=\"$DEADLINE_PATH/deadlinecommand\"\nif [ ! -f \"$deadlinecommand\" ]; then\n    echo \"ERROR: deadlinecommand not found\"\n    exit 1\nfi\n\nsudo -u ec2-user \"$deadlinecommand\" -SetIniFileSetting LaunchRemoteConnectionServerAtStartup True\n\nfor (( i=0; i<${#args[@]}; i=i+2 ))\n  do\n    sudo -u ec2-user \"$deadlinecommand\" -SetIniFileSetting \"${args[i]}\" \"${args[i+1]}\"\n  done\n\n# Configure the Launcher to start the RCS and restart it\n/etc/init.d/deadline10launcher restart\n\n# Wait until the RCS is up and running\necho \"Waiting for RCS to be ready\"\nwhile ! is-rcs-ready; do\n    sleep 1\ndone\necho \"RCS is ready\"\n", "num_lines": 66}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script fetches the Document DB cluster credentials and persists them in\n# the local credential store for the current user.\n#\n# Arguments:\n# $1: Path where deadline repository is installed.\n\nset -xeo pipefail +o history\n\nrepo_path=\"$1\"\n\n# Cloud-init does not load system environment variables. Cherry-pick the\n# environment variable installed by the Deadline Client installer.\nif [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n    source \"/etc/profile.d/deadlineclient.sh\"\nfi\n\n# Find Deadline\nif [ -z \"$DEADLINE_PATH\" ]; then\n    echo \"ERROR: DEADLINE_PATH environment variable not set\"\n    exit 1\nfi\n\n# Find Deadline Command\ndeadlinecommand=\"$DEADLINE_PATH/deadlinecommand\"\nif [ ! -f \"$deadlinecommand\" ]; then\n    echo \"ERROR: deadlinecommand not found\"\n    exit 1\nfi\n\n# Disable outputting commands so the secret is not exposed\nset +x\n\nexport DB_CERT_FILE=\"\"\nexport DB_CERT_PASSWORD=\"\"\n# Set the DB credentials. These are scoped to the user that runs the command, so we\nconfigure_deadline_database \"$deadlinecommand\"\n\n# Resume outputting commands\nset -x\n\n# Configure location to Deadline Repository\nprintenv DB_CERT_PASSWORD | sudo -u ec2-user \"$deadlinecommand\" -ChangeRepository Direct \"$repo_path\" \"${DB_CERT_FILE}\"\nunset DB_CERT_FILE\nunset DB_CERT_PASSWORD\n\necho \"Script completed successfully\"\n", "num_lines": 52}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script configures the deadline.ini file with the Remote Server endpoints and restart the launcher service\n# Arguments:\n# $1: comma separated groups\n# $2: comma separated pools\n# $3: region\n# $4: minimum supported deadline version\n# $5: worker listening port\n# $6: worker listening port configuration script\n\n# exit when any command fails\nset -xeuo pipefail\n\nWORKER_GROUPS=(${1//,/ })\nWORKER_POOLS=(${2//,/ })\nWORKER_REGION=\"$3\"\nMINIMUM_SUPPORTED_DEADLINE_VERSION=$4\nWORKER_LISTENING_PORT=$5\nWORKER_LISTENING_PORT_CONFIG_SCRIPT=$6\n\n# Cloud-init does not load system environment variables. Cherry-pick the\n# environment variable installed by the Deadline Client installer.\nif [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n    source \"/etc/profile.d/deadlineclient.sh\"\nfi\n\n# Find Deadline\nif [ -z \"$DEADLINE_PATH\" ]; then\n    echo \"ERROR: DEADLINE_PATH environment variable not set\"\n    exit 1\nfi\n\nDEADLINE_COMMAND=\"$DEADLINE_PATH/deadlinecommand\"\nif [ ! -f \"$DEADLINE_COMMAND\" ]; then\n    echo \"ERROR: $DEADLINE_COMMAND not found!\"\n    exit 1\nfi\n\nisVersionLessThan() {\n    python -c \"import sys;sys.exit(0 if tuple(map(int, sys.argv[-2].split('.'))) < tuple(map(int, sys.argv[-1].split('.'))) else 1)\" \"$1\" \"$2\"\n}\n\nDEADLINE_VERSION=$(\"$DEADLINE_COMMAND\" -Version | grep -oP '[v]\\K\\d+\\.\\d+\\.\\d+\\.\\d+\\b')\nif [ -z \"$DEADLINE_VERSION\" ]; then\n    echo \"ERROR: Unable to identify the version of installed Deadline Client. Exiting...\"\n    exit 1\nfi\n\nif isVersionLessThan $DEADLINE_VERSION $MINIMUM_SUPPORTED_DEADLINE_VERSION; then\n    echo \"ERROR: Installed Deadline Version ($DEADLINE_VERSION) is less than the minimum supported version ($MINIMUM_SUPPORTED_DEADLINE_VERSION). Exiting...\"\n    exit 1\nfi\n\n# launch worker at launcher startup\n\"$DEADLINE_COMMAND\" -SetIniFileSetting LaunchSlaveAtStartup True\n# keep worker running\n\"$DEADLINE_COMMAND\" -SetIniFileSetting KeepWorkerRunning True\n# restart stalled worker\n\"$DEADLINE_COMMAND\" -SetIniFileSetting RestartStalledSlave True\n# auto update\n\"$DEADLINE_COMMAND\" -SetIniFileSetting AutoUpdateOverride False\n# Disable S3Backed Cache\n\"$DEADLINE_COMMAND\" -SetIniFileSetting UseS3BackedCache False\n# Blank the S3BackedCache Url\n\"$DEADLINE_COMMAND\" -SetIniFileSetting S3BackedCacheUrl \"\"\n\n# setting the group, pool and region for this worker\n\nif [ -z \"$WORKER_REGION\" ]; then\n    echo \"INFO: WORKER_REGION not provided\"\nelse\n    \"$DEADLINE_COMMAND\" -SetIniFileSetting Region $WORKER_REGION\nfi\n\nWORKER_NAME_PREFIX=`hostname -s`\n\n# Fetching all workers in this node\nWORKER_NAMES=()\nshopt -s dotglob\nfor file in /var/lib/Thinkbox/Deadline10/slaves/*\ndo\n  file=\"${file##*/}\"\n  workerSuffix=\"${file%%.*}\"\n  if [[ -z \"$workerSuffix\" || \"$workerSuffix\" = \"*\" ]]; then\n    WORKER_NAMES+=( \"$WORKER_NAME_PREFIX\" )\n  else\n    WORKER_NAMES+=( \"$WORKER_NAME_PREFIX\"-$workerSuffix )\n  fi\ndone\nshopt -u dotglob\n\n# Setting Groups for all workers in this node\nif [ ${#WORKER_GROUPS[@]} -gt 0 ]; then\n  for group in \"${WORKER_GROUPS[@]}\"\n  do\n    existingGroups=( $(\"$DEADLINE_COMMAND\" -GetGroupNames) )\n    if [[ ! \" ${existingGroups[@]} \" =~ \" ${group} \" ]]; then\n        \"$DEADLINE_COMMAND\" -AddGroup $group\n    fi\n  done\n  \"$DEADLINE_COMMAND\" -SetGroupsForSlave $(IFS=, ; echo \"${WORKER_NAMES[*]}\") $(IFS=, ; echo \"${WORKER_GROUPS[*]}\")\nfi\n\n# Setting Pools for all workers in this node\nif [ ${#WORKER_POOLS[@]} -gt 0 ]; then\n  for pool in \"${WORKER_POOLS[@]}\"\n  do\n    existingPools=( $(\"$DEADLINE_COMMAND\" -GetPoolNames) )\n    if [[ ! \" ${existingPools[@]} \" =~ \" ${pool} \" ]]; then\n        \"$DEADLINE_COMMAND\" -AddPool $pool\n    fi\n  done\n  \"$DEADLINE_COMMAND\" -SetPoolsForSlave $(IFS=, ; echo \"${WORKER_NAMES[*]}\") $(IFS=, ; echo \"${WORKER_POOLS[*]}\")\nfi\n\n# Setting listening port for the workers on this node (we cannot have multiple workers listening on the same port)\nport_offset=0\nfor worker_name in \"${WORKER_NAMES[@]}\"; do\n  \"$DEADLINE_COMMAND\" -ExecuteScriptNoGui \"$WORKER_LISTENING_PORT_CONFIG_SCRIPT\" -n $worker_name -p $(($WORKER_LISTENING_PORT+$port_offset))\n  port_offset=$((port_offset+1))\ndone\n\n# Restart service, if it exists, else restart application\nif service --status-all | grep -q 'Deadline 10 Launcher'; then\n  service deadline10launcher stop\n  sudo killall -w deadlineworker || true\n  service deadline10launcher start\nelse\n  DEADLINE_LAUNCHER=\"$DEADLINE_PATH/deadlinelauncher\"\n  \"$DEADLINE_LAUNCHER\" -shutdownall\n  sudo killall -w deadlineworker || true\n  \"$DEADLINE_LAUNCHER\" -nogui\nfi\n\necho \"Script completed successfully.\"\n", "num_lines": 140}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script configures the deadline.ini file with the settings for the HealthMonitor\n# Arguments:\n# $1: healthCheckPort\n# $2: minimum supported deadline version\n\n# exit when any command fails\nset -xeuo pipefail\n\nHEALTH_CHECK_PORT=\"$1\"\nMINIMUM_SUPPORTED_DEADLINE_VERSION=$2\n\n# Cloud-init does not load system environment variables. Cherry-pick the\n# environment variable installed by the Deadline Client installer.\nif [ -f \"/etc/profile.d/deadlineclient.sh\" ]; then\n    source \"/etc/profile.d/deadlineclient.sh\"\nfi\n\n# Find Deadline\nif [ -z \"$DEADLINE_PATH\" ]; then\n    echo \"ERROR: DEADLINE_PATH environment variable not set\"\n    exit 1\nfi\n\nDEADLINE_COMMAND=\"$DEADLINE_PATH/deadlinecommand\"\nif [ ! -f \"$DEADLINE_COMMAND\" ]; then\n    echo \"ERROR: $DEADLINE_COMMAND not found!\"\n    exit 1\nfi\n\nisVersionLessThan() {\n    python -c \"import sys;sys.exit(0 if tuple(map(int, sys.argv[-2].split('.'))) < tuple(map(int, sys.argv[-1].split('.'))) else 1)\" \"$1\" \"$2\"\n}\n\nDEADLINE_VERSION=$(\"$DEADLINE_COMMAND\" -Version | grep -oP '[v]\\K\\d+\\.\\d+\\.\\d+\\.\\d+\\b')\nif [ -z \"$DEADLINE_VERSION\" ]; then\n    echo \"ERROR: Unable to identify the version of installed Deadline Client. Exiting...\"\n    exit 1\nfi\n\nif isVersionLessThan $DEADLINE_VERSION $MINIMUM_SUPPORTED_DEADLINE_VERSION; then\n    echo \"ERROR: Installed Deadline Version ($DEADLINE_VERSION) is less than the minimum supported version ($MINIMUM_SUPPORTED_DEADLINE_VERSION). Exiting...\"\n    exit 1\nfi\n\n# enabling the health check port\n\"$DEADLINE_COMMAND\" -SetIniFileSetting ResourceTrackerVersion V2\n# health check port\n\"$DEADLINE_COMMAND\" -SetIniFileSetting LauncherHealthCheckPort $HEALTH_CHECK_PORT\n\necho \"Script completed successfully.\"\n", "num_lines": 56}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Script to install and configure cachefilesd onto a Linux host.\n# This script is presently narrowly written for use on the ECS container host\n# instance(s) that are running the Deadline RCS containers in the RenderQueue construct.\n\nset -xeu\n\nif ! test -f /sbin/cachefilesd\nthen\n  # The yum install can fail if there is no route to the yum repository.\n  # Since this is an AL2 instance, that is equivalent to requiring a route to\n  # the regional S3 endpoint on port 80.\n  sudo yum install -y cachefilesd || echo 'ERROR -- Failed to install cachefilesd' && exit 0\n\n  cat << EOF | sudo tee -a /etc/cachefilesd.conf\n# Allow 16k cull table entries\nculltable 14\nEOF\n\nfi\n\n# Make sure cachefilesd is running\nsudo systemctl enable cachefilesd\nsudo systemctl start cachefilesd\n", "num_lines": 26}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# Script to download the contents of a Secret from AWS SecretsManager, and save\n# the contents to a file\n#\n# Arguments:\n#   $1 -- The ARN of the secret to fetch\n#   $2 -- The filename to save the contents as.\n\nset -xefuo pipefail\n\nif test $# -lt 2\nthen\n    echo \"Usage: $0 <secret arn> <filename>\"\n    exit 1\nfi\n\nSECRET_ARN=$1\nOUTPUT_FILENAME=$2\nAWS_REGION=$(echo ${SECRET_ARN} | cut -d: -f 4)\n\nOUTPUT_DIR=$(dirname \"${OUTPUT_FILENAME}\")\n[ -d \"${OUTPUT_DIR}\" ] || sudo mkdir -p \"${OUTPUT_DIR}\"\n\nPY_SCRIPT=\"from __future__ import print_function; import json, sys; d=json.load(sys.stdin); print(d[sys.argv[1]])\"\n\nset +x\nexport SECRET_JSON=$(aws --region ${AWS_REGION} secretsmanager get-secret-value --secret-id ${SECRET_ARN})\nset -x\nif printenv SECRET_JSON | grep 'SecretString' 2>&1 > /dev/null\nthen\n    # Secret was plain test. Just copy the contents of the SecretString into the output file\n    printenv SECRET_JSON | python -c \"${PY_SCRIPT}\" SecretString > \"${OUTPUT_FILENAME}\"\nelse\n    # Secret value is binary. The contents of SecretBinary will be the base64 encoding of the secret\n    printenv SECRET_JSON | python -c \"${PY_SCRIPT}\" SecretBinary | base64 -w0 -i -d > \"${OUTPUT_FILENAME}\"\nfi\nunset SECRET_JSON\n", "num_lines": 42}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# exit when any command fails\nset -xeuo pipefail\n\nMIN_DEADLINE_VERSION_REPO_NO_ROOT=\"10.1.18\"\nUSAGE=\"Usage: $0 -i <installer-s3-path> -p <local-installer-path> -v <deadline-version>\n\nThis script downloads the deadline repository installer and executes it.\n\nRequired arguments:\n  -i s3 path for the deadline repository installer.\n  -p Path where deadline repository needs to be installed.\n  -v Deadline Repository Version being installed.\n\nOptional arguments\n  -s Deadline Repository settings file to import.\n  -o The UID[:GID] that this script will chown the Repository files for. If GID is not specified, it defults to be the same as UID.\n  -c Secrets management admin credentials ARN. If this parameter is specified, secrets management will be enabled.\n  -r Region where stacks are deployed. Required to get secret management credentials.\"\n\nwhile getopts \"i:p:v:s:o:c:r:\" opt; do\n  case $opt in\n    i) S3PATH=\"$OPTARG\"\n    ;;\n    p) PREFIX=\"$OPTARG\" \n    ;;\n    v) DEADLINE_REPOSITORY_VERSION=\"$OPTARG\"\n    ;;\n    s) DEADLINE_REPOSITORY_SETTINGS_FILE=\"$OPTARG\"\n    ;;\n    o) DEADLINE_REPOSITORY_OWNER=\"$OPTARG\"\n    ;;\n    c) SECRET_MANAGEMENT_ARN=\"$OPTARG\"\n    ;;\n    r) AWS_REGION=\"$OPTARG\"\n    ;;\n    /?)\n      echo \"$USAGE\"\n      exit 1\n    ;;\n  esac\ndone\n\nif [ -z \"${S3PATH+x}\" ] || \\\n   [ -z \"${PREFIX+x}\" ] || \\\n   [ -z \"${DEADLINE_REPOSITORY_VERSION+x}\" ]; then\n  echo \"ERROR: Required arguments are missing.\"\n  echo \"$USAGE\"\n  exit 1\nfi\n\n# check if repository is already installed at the given path\nREPOSITORY_FILE_PATH=\"$PREFIX/settings/repository.ini\"\nCONNECTION_FILE_PATH=\"$PREFIX/settings/connection.ini\"\n\n# Run the Function that the Database Connection created to set up the installer arguments.\ndeclare -A INSTALLER_DB_ARGS\nconfigure_database_installation_args\n\nif test -f \"$REPOSITORY_FILE_PATH\"; then\n    echo \"File $REPOSITORY_FILE_PATH exists. Validating Database Connection\"\n    # File Exists\n\n    INSTALLER_DB_HOSTNAME=${INSTALLER_DB_ARGS[\"--dbhost\"]}\n    INSTALLER_DB_PORT=${INSTALLER_DB_ARGS[\"--dbport\"]}\n\n    # Additionally, vadlidate the DB endpoint.\n    source $CONNECTION_FILE_PATH > /dev/null 2>&1 || true\n    if [ \"$Hostname\" != \"$INSTALLER_DB_HOSTNAME\" ] || [ \"$Port\" != \"$INSTALLER_DB_PORT\" ]; then\n        echo \"ERROR: Repository pre-exists but configured database endpoint($Hostname:$Port) does not match with provided database endpoint($INSTALLER_DB_HOSTNAME:$INSTALLER_DB_PORT).\"\n        exit 1\n    fi\n    echo \"Database Connection is valid.  Validating Deadline Version.\"\n    \n    # Following runs the .ini file as a script while suppressing all the errors. This creates bash variables with\n    # the key's name and sets its value to the value specified in .ini file.\n    # This is a quick way to read the .ini values but is not a full-proof way. Since we dont have common keys in\n    # multiple sections of the config files, this approach will work correctly.\n    # The proper way to achieve this is to use a ini config manager tool to get the value of required key.\n    source $REPOSITORY_FILE_PATH > /dev/null 2>&1 || true\n    if [[ \"$Version\" = \"$DEADLINE_REPOSITORY_VERSION\" ]]; then\n        echo \"Repository version $DEADLINE_REPOSITORY_VERSION already exists at path $REPOSITORY_FILE_PATH.\"\n    else\n        SplitVersion=(${Version//./ })\n        SplitRepoVersion=(${DEADLINE_REPOSITORY_VERSION//./ })\n\n        if [[ ${SplitVersion[0]} != ${SplitRepoVersion[0]} ]]; then\n            echo \"ERROR: Repository pre-exists but configured Repository Version (${Version}) has a different Major Version than the provided installer (${DEADLINE_REPOSITORY_VERSION}).\"\n            exit 1\n        fi\n    fi\nfi\n\nREPO_INSTALLER=/tmp/repo_installer.run\n\naws s3 cp $S3PATH $REPO_INSTALLER\nchmod +x $REPO_INSTALLER\n\nset +x\n\nREPO_ARGS=()\n\nfor key in \"${!INSTALLER_DB_ARGS[@]}\"; do\n  REPO_ARGS+=(\"${key}\" \"${INSTALLER_DB_ARGS[$key]}\")\ndone\n\nif [ ! -z \"${DEADLINE_REPOSITORY_SETTINGS_FILE+x}\" ]; then\n  if [ ! -f \"$DEADLINE_REPOSITORY_SETTINGS_FILE\" ]; then\n    echo \"ERROR: Repository settings file was specified but is not a file: $DEADLINE_REPOSITORY_SETTINGS_FILE.\"\n    exit 1\n  else\n    REPO_ARGS+=(\"--importrepositorysettings\" \"true\" \"--repositorysettingsimportoperation\" \"append\" \"--repositorysettingsimportfile\" \"$DEADLINE_REPOSITORY_SETTINGS_FILE\")\n  fi\nfi\n\nif [ ! -z \"${SECRET_MANAGEMENT_ARN+x}\" ]; then\n  sudo yum install -y jq\n  SM_SECRET_VALUE=$(aws secretsmanager get-secret-value --secret-id=$SECRET_MANAGEMENT_ARN --region=$AWS_REGION)\n  SM_SECRET_STRING=$(jq -r '.SecretString' <<< \"$SM_SECRET_VALUE\")\n  SECRET_MANAGEMENT_USER=$(jq -r '.username' <<< \"$SM_SECRET_STRING\")\n  SECRET_MANAGEMENT_PASSWORD=$(jq -r '.password' <<< \"$SM_SECRET_STRING\")\n  if !([[ ${#SECRET_MANAGEMENT_PASSWORD} -ge 8 ]] && \n    echo $SECRET_MANAGEMENT_PASSWORD | grep -q [0-9] &&\n    echo $SECRET_MANAGEMENT_PASSWORD | grep -q [a-z] &&\n    echo $SECRET_MANAGEMENT_PASSWORD | grep -q [A-Z] &&\n    echo $SECRET_MANAGEMENT_PASSWORD | grep -q [^[:alnum:]])\n  then\n    echo \"ERROR: Admin password is too weak. It must be at least 8 characters long and contain at least one lowercase letter, one uppercase letter, one symbol and one digit.\"\n    exit 1\n  fi\n  echo \"Secrets management is enabled. Credentials are stored in secret: $SECRET_MANAGEMENT_ARN\"\n  REPO_ARGS+=(\"--installSecretsManagement\" \"true\" \"--secretsAdminName\" \"$SECRET_MANAGEMENT_USER\" \"--secretsAdminPassword\" \"$SECRET_MANAGEMENT_PASSWORD\")\nelse\n  echo \"Secrets management is not enabled.\"\nfi\n\nINSTALL_AS_NON_ROOT_CMD=\"\"\nif [[ -n \"${DEADLINE_REPOSITORY_OWNER+x}\" ]]; then\n  if [[ ! \"$DEADLINE_REPOSITORY_OWNER\" =~ ^[0-9]+(:[0-9]+)?$ ]]; then\n    echo \"ERROR: Deadline Repository owner is invalid: ${DEADLINE_REPOSITORY_OWNER}\"\n    exit 1\n  fi\n  REPOSITORY_OWNER_UID=\"${DEADLINE_REPOSITORY_OWNER%:*}\"\n  REPOSITORY_OWNER_GID=\"${DEADLINE_REPOSITORY_OWNER#*:}\"\n\n  if [[ -z $REPOSITORY_OWNER_GID ]]; then\n    echo \"Repository owner GID not specified. Defaulting to UID $REPOSITORY_OWNER_UID\"\n    REPOSITORY_OWNER_GID=$REPOSITORY_OWNER_UID\n  fi\n\n  EXISTING_GROUP=$(id -g $REPOSITORY_OWNER_UID)\n  if [[ $? -eq 0 ]]; then\n    # UID already taken, make sure the GID matches\n    if [[ ! $EXISTING_GROUP -eq $REPOSITORY_OWNER_GID ]]; then\n      echo \"ERROR: Deadline Repository owner UID $REPOSITORY_OWNER_UID is already in use and has incorrect GID. Got GID $EXISTING_GROUP, expected $REPOSITORY_OWNER_GID\"\n      exit 1\n    fi\n  else\n    # Create the group\n    groupadd deadline-rcs-user -g $REPOSITORY_OWNER_GID\n\n    # Create the user\n    useradd deadline-rcs-user -u $REPOSITORY_OWNER_UID -g $REPOSITORY_OWNER_GID\n  fi\n\n  # Determine whether we can run the installer as the user that will own the repository\n  VERSION_COMPONENTS=(${DEADLINE_REPOSITORY_VERSION//./ })\n  MIN_VERSION_COMPONENTS=(${MIN_DEADLINE_VERSION_REPO_NO_ROOT//./ })\n  if !([[ ${VERSION_COMPONENTS[0]} -lt ${MIN_VERSION_COMPONENTS[0]} ]] || \\\n       [[ ${VERSION_COMPONENTS[1]} -lt ${MIN_VERSION_COMPONENTS[1]} ]] || \\\n       [[ ${VERSION_COMPONENTS[2]} -lt ${MIN_VERSION_COMPONENTS[2]} ]])\n  then\n    echo \"Deadline Repository installer will be run as UID=$REPOSITORY_OWNER_UID\"\n    INSTALL_AS_NON_ROOT_CMD=\"sudo -u #$REPOSITORY_OWNER_UID\"\n  fi\nfi\n\n# The syntax ${array[@]+\"${array[@]}\"} is a way to get around the expansion of an empty array raising an unbound variable error since this script\n# sets the \"u\" shell option above. This is a use of the ${parameter+word} shell expansion. If the value of \"parameter\" is unset, nothing will be\n# substituted in its place. If \"parameter\" is set, then the value of \"word\" is used, which is the expansion of the populated array.\n# Since bash treats the expansion of an empty array as an unset variable, we can use this pattern expand the array only if it is populated.\n$INSTALL_AS_NON_ROOT_CMD $REPO_INSTALLER --mode unattended --setpermissions false --prefix \"$PREFIX\" --installmongodb false --backuprepo false ${REPO_ARGS[@]+\"${REPO_ARGS[@]}\"}\n\nif [[ -z \"$INSTALL_AS_NON_ROOT_CMD\" ]] && [[ -n \"${REPOSITORY_OWNER_UID+x}\" ]]; then\n  echo \"Changing ownership of Deadline Repository files to UID=$REPOSITORY_OWNER_UID GID=$REPOSITORY_OWNER_GID\"\n  sudo chown -R \"$REPOSITORY_OWNER_UID:$REPOSITORY_OWNER_GID\" \"$PREFIX\"\nfi\n\nset -x\n\necho \"Script completed successfully.\"\n", "num_lines": 196}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nnode_modules/.bin/tsc -b \"$@\"\n", "num_lines": 3}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Script to clean stale .js and .d.ts files (that don't have a corresponding .ts\n# file).\n\nfor filename in $(find . \\\n     -not \\( -name node_modules -prune \\) \\\n     -not \\( -name coverage -prune \\) \\\n     -type f \\\n     -name \\*.js -o -name \\*.d.ts | git check-ignore --stdin); do\n\n    if [[ $filename == *.d.ts ]]; then\n        source=${filename%.d.ts}.ts\n    else\n        source=${filename%.*}.ts\n    fi\n\n    if [[ ! -f $source ]]; then\n        rm $filename\n        echo Removed $filename\n    fi\ndone\n", "num_lines": 22}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\n\nif [ ! -f lerna.json ]; then\n  echo \"This script should be run from the root of the repo.\"\n  exit 1\nfi\n\n# first, we need to make sure that all existing peer dependencies are aligned to the \"dependency\" version\nfind . -name package.json | grep -v node_modules | xargs node scripts/sync-peer-deps.js\n\n# must build first so .jsii is aligned\n/bin/bash ./build.sh --skip-tests\n\n# now, run jsii-fix-peers to add all missing peers based on the jsii spec\nnpx lerna exec \"$PWD/tools/cdk-build-tools/node_modules/.bin/jsii-fix-peers 2>/dev/null || true\"\n", "num_lines": 17}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------------\n#\n# this wonderful tool allows you to execute a command for all modules in this repo\n# in topological order, but has the incredible property of being stateful.\n# this means that if a command fails, you can fix the issue and resume from where\n# you left off.\n#\n# to start a session, run:\n#     foreach.sh COMMAND\n#\n# this will execute \"COMMAND\" for each module in the repo (cwd will be the directory of the module).\n# if a task fails, it will stop, and then to resume, simply run `foreach.sh` again (with or without the same command).\n#\n# to reset the session (either when all tasks finished or if you wish to run a different session), run:\n#     foreach.sh --reset\n#\n# to run the command only against the current module and its dependencies:\n#     foreach.sh --up COMMAND\n#\n# --------------------------------------------------------------------------------------------------\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\nstatedir=\"${scriptdir}\"\nstatefile=\"${statedir}/.foreach.state\"\ncommandfile=\"${statedir}/.foreach.command\"\nbase=$PWD\n\nfunction heading {\n  printf \"\\e[38;5;81m$@\\e[0m\\n\"\n}\n\nfunction error {\n  printf \"\\e[91;5;81m$@\\e[0m\\n\"\n}\n\nfunction success {\n  printf \"\\e[32;5;81m$@\\e[0m\\n\"\n}\n\nif [[ \"${1:-}\" == \"--reset\" ]]; then\n    rm -f \"${statedir}/.foreach.\"*\n    success \"state cleared. you are free to start a new command.\"\n    exit 0\nfi\n\nup=\"\"\nup_desc=\"\"\nif [[ \"${1:-}\" == \"--up\" ]]; then\n    if [ ! -f package.json ]; then\n      echo \"--up can only be executed from within a module directory (looking for package.json)\"\n      exit 1\n    fi\n\n    scope=$(node -p \"require('./package.json').name\")\n    up=\" --scope ${scope} --include-dependencies\"\n    up_desc=\"('${scope}' and its dependencies)\"\n    shift\nfi\n\ncommand_arg=\"${@:-}\"\n\nif [ -f \"${statefile}\" ] && [ -f \"${commandfile}\" ]; then\n  command=\"$(cat ${commandfile})\"\n  if [ ! -z \"${command_arg}\" ] && [ \"${command}\" != \"${command_arg}\" ]; then\n    error \"error: there is still an active session for: \\\"${command}\\\". to reset:\"\n    error \"   $0 --reset\"\n    exit 1\n  fi\nfi\n\nif [ ! -f \"${statefile}\" ] && [ ! -f \"${commandfile}\" ]; then\n  if [ ! -z \"${command_arg}\" ]; then\n    command=\"${command_arg}\"\n    success \"starting new session ${up_desc}\"\n    ${scriptdir}/../node_modules/.bin/lerna ls --all ${up} --toposort -p > ${statefile}\n    echo \"${command}\" > ${commandfile}\n  else\n    error \"no active session, use \\\"$(basename $0) COMMAND\\\" to start a new session\"\n    exit 0\n  fi\nfi\n\nnext=\"$(head -n1 ${statefile})\"\nif [ -z \"${next}\" ]; then\n  success \"done (queue is empty). to reset:\"\n  success \"   $0 --reset\"\n  exit 0\nfi\n\nremaining=$(cat ${statefile} | wc -l | xargs -n1)\n\nheading \"---------------------------------------------------------------------------------\"\nheading \"${next}: ${command} (${remaining} remaining)\"\n\n(\n  cd ${next}\n\n  # special-case \"npm run\" or \"yarn run\" - skip any modules that simply don't have\n  # that script (similar to how \"lerna run\" behaves)\n  if [[ \"${command}\" == \"npm run \"* ]] || [[ \"${command}\" == \"yarn run \"* ]]; then\n    script=\"$(echo ${command} | cut -d\" \" -f3)\"\n    exists=$(node -pe \"(require('./package.json').scripts && require('./package.json').scripts['${script}']) || ''\")\n    if [ -z \"${exists}\" ]; then\n      echo \"skipping (no \"${script}\" script in package.json)\"\n      exit 0\n    fi\n  fi\n\n  sh -c \"${command}\" &> /tmp/foreach.stdio || {\n    cd ${base}\n    cat /tmp/foreach.stdio | ${scriptdir}/path-prefix ${next}\n    error \"error: last command failed. fix problem and resume by executing: $0\"\n    error \"directory:    ${next}\"\n    exit 1\n  }\n)\n\ntail -n +2 \"${statefile}\" > \"${statefile}.tmp\"\ncp \"${statefile}.tmp\" \"${statefile}\"\nexec $0\n", "num_lines": 122}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Generate an aggregate tsconfig.json with references to all projects in the\n# repository.\nprefix=\"$(pwd)/\"\n\necho '{'\necho '    \"__comment__\": \"This file is necessary to make transitive Project References in TypeScript work\",'\necho '    \"files\": [],'\necho '    \"references\": ['\n\n# set the comma to nothing at first.\n# if we have more than one package,\n# we set $comma to an actual comma\ncomma='  '\nfor package in $(node_modules/.bin/lerna ls -ap --ignore 'all-in-farm**'); do\n    relpath=${package#\"$prefix\"}\n    echo '  '\"$comma\"'{ \"path\": \"'\"$relpath\"'\" }'\n    comma=', '\ndone\necho '    ]'\necho '}'\n", "num_lines": 22}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is meant to perform the steps necessary to prepare a merge request for a release.\n# - Enable the docker Daemon\n# - Build and Publish all Lambda Layers\n# - Run the Bump script\n#\n# This script is meant to be run by the RFDK team on their internal pipeline\n\nset -euxo pipefail\n\nSCRIPT_DIR=$(dirname \"$0\")\nSCRIPT_DIR=$(readlink -f \"$SCRIPT_DIR\")\nROOT_DIR=$(readlink -f \"${SCRIPT_DIR}/..\")\nTESTS_DIR=$(readlink -f \"$ROOT_DIR/integ\")\n\n# Determine the ECR region we want to use\nset +e\n# First attempt to use the AWS_REGION environment variable which is set by CodeBuild\n# Source: https://docs.aws.amazon.com/codebuild/latest/userguide/build-env-ref-env-vars.html\nif [ -z ${AWS_REGION+x} ]; then\n    # Not running on CodeBuild, so fallback to getting the region from AWS CLI configuration\n    echo \"could not get region from AWS_REGION environment variable. Attempting AWS configuration...\"\n    ECR_REGION=\"$(aws configure get region)\"\n    if [ \"$?\" -ne 0 ] || [ -z \"${ECR_REGION}\" ]; then\n        echo \"ERROR: Could not determine region\"\n        exit 1\n    fi\nelse\n    ECR_REGION=\"${AWS_REGION}\"\nfi\nset -e\necho \"ECR_REGION=${ECR_REGION}\"\n\n# Ensure that the docker daemon is running in the background\n# These commands are currently being done here instead of in buildspec due to the following issue: https://github.com/awslabs/aws-delivlib/issues/448\n# These commands come from the Codebuild sample for running docker on a custom image: https://docs.aws.amazon.com/codebuild/latest/userguide/sample-docker-custom-image.html#sample-docker-custom-image-files\ndocker info || nohup /usr/bin/dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 --storage-driver=overlay2 &\ntimeout 15 sh -c \"until docker info; do echo .; sleep 1; done\"\n\n# Pull amazonlinux image locally from ECR. This is done to avoid pulling from DockerHub both for egress and rate\n# limiting.\nPULL_AL_FROM_ECR_ARGS=(\n    # Region of ECR repo\n    \"${ECR_REGION}\"\n    # Image versions to pull\n    \"latest\" # required for building and publishing lambda layers\n    \"2\"      # required for building Deadline docker images for running integration tests\n)\n/bin/bash ${SCRIPT_DIR}/pull_amazonlinux_from_ecr.sh \"${PULL_AL_FROM_ECR_ARGS[@]}\"\n\n# Run integ tests\n/bin/bash ${ROOT_DIR}/build.sh\npushd $TESTS_DIR\nyarn run e2e-automated\npopd\n\n# Build and publish lambda layers\n/bin/bash ${SCRIPT_DIR}/publish-all-lambda-layers.sh\n\n# Perform the bump\n/bin/bash ${ROOT_DIR}/bump.sh\n", "num_lines": 66}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is meant to build and publish all Lambda Layers using Docker. Its usage is:\n#   publish-all-lambda-layers.sh\n\nset -euo pipefail\n\n\nSCRIPT_DIR=$(dirname $0)\n\n# Switch to the lambda layers directory\ncd \"$SCRIPT_DIR/../lambda-layers\"\n\n# install and build node packages\nyarn\nyarn build\n\n# Find all layers\nLAYER_NAMES=$(find ./layers -mindepth 1 -maxdepth 1 -printf \"%f\\n\" -type d)\n\n# Switch to the bin directory\ncd bin\nfor LAYER in \"${LAYER_NAMES[@]}\"\ndo\n    ./build-layer.sh \"${LAYER}\"\ndone\n\nfor LAYER in \"${LAYER_NAMES[@]}\"\ndo\n    node ./publish.js \"${LAYER}\"\ndone\n\nnode ./write-ts.js \"${LAYER_NAMES[@]}\"\n", "num_lines": 37}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Fetches the amazonlinux Docker image from the official regional ECR and tags\n# it as-if it were fetched from DockerHub. This avoids any egress to the\n# internet when pulling images from AWS and also can be used to avoid DockerHub\n# rate limits.\n#\n# This assumes that the AWS CLI is configured to use AWS credentials with\n# sufficient access to query and pull images from the amazon linux ECR.\n#\n# For more information, see:\n# https://docs.aws.amazon.com/AmazonECR/latest/userguide/amazon_linux_container_image.html\n# https://docs.aws.amazon.com/IAM/latest/UserGuide/list_amazonelasticcontainerregistry.html\n#\n# USAGE\n#\n#   pull_amazonlinux_from_ecr.sh REGION [VERSION ...]\n#\n# ARGUMENTS\n#\n#   REGION\n#     The AWS region of the ECR repository to pull from\n#\n#   VERSION\n#     One or more Docker version tags to pull. If not specified, the \"latest\"\n#     tag will be pulled\n#\n# EXAMPLES\n#\n#   # Pulls the \"latest\" version from the us-east-1 ECR repo\n#   pull_amazonlinux_from_ecr.sh us-east-1\n#\n#   # Pulls the \"amazonlinux:2\" from the us-west-2 ECR repo\n#   pull_amazonlinux_from_ecr.sh us-west-2 2\n\n\nset -euo pipefail\n\n# The AWS account that contains the regional amazonlinux ECRs\nAWS_AL_ACCOUNT_ID=137112412989\n\nif [ \"$#\" -lt 1 ]; then\n    echo \"ERROR: No region specified\"\n    exit 1\nfi\n\n# Extract the AWS region from the first argument\nAWS_REGION=\"$1\"; shift\n\n# Remaining arguments are the image version tags. If not specified, \"latest\" is\n# used.\nif [ \"$#\" -gt 0 ]; then\n    TAG_VERSIONS=( \"$@\" )\nelse\n    TAG_VERSIONS=( \"latest\" )\nfi\n\n# Compute the ECR URI for the specified region\nAWS_AL_URI=\"${AWS_AL_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/amazonlinux\"\naws ecr get-login-password --region \"${AWS_REGION}\" | docker login --username AWS --password-stdin \"${AWS_AL_URI}\"\n\nfor TAG_VERSION in \"${TAG_VERSIONS[@]}\"; do\n    echo \"Pulling amazonlinux:${TAG_VERSION}...\"\n    docker pull \"${AWS_AL_URI}:${TAG_VERSION}\"\n    echo \"Tagging amazonlinux:${TAG_VERSION}...\"\n    docker tag \"${AWS_AL_URI}:${TAG_VERSION}\" \"amazonlinux:${TAG_VERSION}\"\n    echo \"done\"\ndone\n", "num_lines": 69}
{"repo_name": "aws-rfdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# This is a helper script for entering a docker build environment suitable for\n# building the RFDK. To use: Run this script from the root directory of the RFDK\n# repository.\n\n# Make sure we're running from the root of the CDK repo\nif ! test -f package.json || ! grep '\"name\": \"aws-rfdk\",' package.json > /dev/null || ! grep '\"private\": true,' package.json > /dev/null\nthen\n    echo \"Usage: Run from the root of the RFDK repository\"\n    exit 1\nfi\n\necho \"Entering jsii/superchain docker container so you can interactively build/test RFDK.\"\n\nUSER_OPT=\"-u $(id -u):$(id -g)\"\nUSERFILE_MOUNTS=\"-v /etc/passwd:/etc/passwd:ro -v /etc/shadow:/etc/shadow:ro -v /etc/group:/etc/group:ro\"\n\n# Share the config directories for language tools in the container.\nOTHER_MOUNTS=\"\"\nfor dir in \"${HOME}/.npm\" \"${HOME}/.dotnet\" \"${HOME}/.templateengine\" \"${HOME}/.yarn\" \"${HOME}/.jsii-cache\"\ndo\n  test -d ${dir} || mkdir ${dir}\n  OTHER_MOUNTS=\"${OTHER_MOUNTS} -v ${dir}:${dir}:rw\"\ndone\nfor file in \"${HOME}/.yarnrc\"\ndo\n  test -f ${file} || touch ${file}\n  OTHER_MOUNTS=\"${OTHER_MOUNTS} -v ${file}:${file}:rw\"\ndone\n\n# Add the user's ~/.gitconfig if there is one.\ntest -f \"${HOME}/.gitconfig\" && OTHER_MOUNTS=\"${OTHER_MOUNTS} -v ${HOME}/.gitconfig:${HOME}/.gitconfig:ro\"\n\ndocker run --rm \\\n    ${USERFILE_MOUNTS} \\\n    ${OTHER_MOUNTS} \\\n    -v ${PWD}:${PWD} -w ${PWD} \\\n    ${USER_OPT} \\\n    --net=host -it \\\n    --env DOTNET_CLI_TELEMETRY_OPTOUT=1 \\\n    jsii/superchain:1-buster-slim-node14\n\n", "num_lines": 47}
{"repo_name": "aws-sagemaker-edge-quick-device-setup", "repo_creator": "aws", "programming_language": "Shell", "code": "VERSION=0.0.4\n\n\nbuild () {\n    GOOS=$1 GOARCH=$2 go build -ldflags \"-X aws-sagemaker-edge-quick-device-setup/distinfo.OS=$1 -X aws-sagemaker-edge-quick-device-setup/distinfo.ARCH=$2 -X aws-sagemaker-edge-quick-device-setup/distinfo.VERSION=$VERSION\" -o ./bin/aws-sagemaker-edge-quick-device-setup-$1-$2 main.go\n}\n\nif [ $1-$2 != \"linux-amd64\" -a $1-$2 != \"linux-arm64\" ]; then\n    echo \"USAGE: bash build.sh OS ARCH\"\n    echo \"Supported operating system and architecture combinations\"\n    echo \"- linux amd64\"\n    echo \"- linux arm64\"\n    exit 1\nfi\n\n\nbuild $1 $2\nfor algo in sha1sum sha224sum sha256sum sha384sum sha512sum; do\n    ${algo} ./bin/aws-sagemaker-edge-quick-device-setup-$1-$2 > ./bin/aws-sagemaker-edge-quick-device-setup-$1-$2.${algo}\ndone \n", "num_lines": 21}
{"repo_name": "aws-sam-build-images", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n# You can use this to build any changes you make to Docker build images to your local machine.\n# Of course, you can also run a single one of these commands manually.\n# If you use this script, ensure that you run with --skip-pull-image, else the remote image may be used.\n\nif [ -z ${SAM_CLI_VERSION+x} ];\nthen\n    echo \"Must set SAM_CLI_VERSION to run this script.\"\n    exit -1;\nelse\n    echo \"SAM CLI VERSION: $SAM_CLI_VERSION\";\nfi\n\n# Disable DOCKER_CONTENT_TRUST for pulling from public ECR\nexport DOCKER_CONTENT_TRUST=0\nexport DOCKER_CLI_EXPERIMENTAL=enabled\n\n# Single arch images\ndocker build -f Dockerfile-java8 -t amazon/aws-sam-cli-build-image-java8:x86_64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION . &\ndocker build -f Dockerfile-provided -t amazon/aws-sam-cli-build-image-provided:x86_64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION . &\ndocker build -f Dockerfile-python37 -t amazon/aws-sam-cli-build-image-python3.7:x86_64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION . &\ndocker build -f Dockerfile-go1x -t amazon/aws-sam-cli-build-image-go1.x:x86_64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION . &\nwait\n\n# Multi arch images\n# First build all x86docker build -f Dockerfile-dotnet6 -t amazon/aws-sam-cli-build-image-dotnet6:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-dotnet7 -t amazon/aws-sam-cli-build-image-dotnet7:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-java8_al2 -t amazon/aws-sam-cli-build-image-java8.al2:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-java11 -t amazon/aws-sam-cli-build-image-java11:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-java17 -t amazon/aws-sam-cli-build-image-java17:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-nodejs12x -t amazon/aws-sam-cli-build-image-nodejs12.x:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-nodejs14x -t amazon/aws-sam-cli-build-image-nodejs14.x:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-nodejs16x -t amazon/aws-sam-cli-build-image-nodejs16.x:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-nodejs18x -t amazon/aws-sam-cli-build-image-nodejs18.x:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-provided_al2 -t amazon/aws-sam-cli-build-image-provided.al2:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-python38 -t amazon/aws-sam-cli-build-image-python3.8:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-python39 -t amazon/aws-sam-cli-build-image-python3.9:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-python310 -t amazon/aws-sam-cli-build-image-python3.10:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-ruby27 -t amazon/aws-sam-cli-build-image-ruby2.7:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\ndocker build -f Dockerfile-ruby32 -t amazon/aws-sam-cli-build-image-ruby3.2:x86_64 --platform linux/amd64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=x86_64 --build-arg IMAGE_ARCH=x86_64 . &\nwait\n\n# Build arm64 images\ndocker run --rm --privileged multiarch/qemu-user-static --reset -p yes\ndocker build -f Dockerfile-dotnet6 -t amazon/aws-sam-cli-build-image-dotnet6:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-dotnet7 -t amazon/aws-sam-cli-build-image-dotnet7:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-java8_al2 -t amazon/aws-sam-cli-build-image-java8.al2:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-java11 -t amazon/aws-sam-cli-build-image-java11:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-java17 -t amazon/aws-sam-cli-build-image-java17:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-nodejs12x -t amazon/aws-sam-cli-build-image-nodejs12.x:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-nodejs14x -t amazon/aws-sam-cli-build-image-nodejs14.x:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-nodejs16x -t amazon/aws-sam-cli-build-image-nodejs16.x:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-nodejs18x -t amazon/aws-sam-cli-build-image-nodejs18.x:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-provided_al2 -t amazon/aws-sam-cli-build-image-provided.al2:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-python38 -t amazon/aws-sam-cli-build-image-python3.8:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-python39 -t amazon/aws-sam-cli-build-image-python3.9:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-python310 -t amazon/aws-sam-cli-build-image-python3.10:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-ruby27 -t amazon/aws-sam-cli-build-image-ruby2.7:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\ndocker build -f Dockerfile-ruby32 -t amazon/aws-sam-cli-build-image-ruby3.2:arm64 --platform linux/arm64 --build-arg SAM_CLI_VERSION=$SAM_CLI_VERSION --build-arg AWS_CLI_ARCH=aarch64 --build-arg IMAGE_ARCH=arm64 . &\nwait\n", "num_lines": 62}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nbinary_zip_filename=$1\npython_library_zip_filename=$2\nbuild_binary_name=$3\nbuild_folder=$4\npython_version=$5\n\nif [ \"$python_library_zip_filename\" = \"\" ]; then\n    python_library_zip_filename=\"python-libraries.zip\";\nfi\n\nif [ \"$python_version\" = \"\" ]; then\n    python_version=\"3.11.3\";\nfi\n\nif [ \"$CI_OVERRIDE\" = \"1\" ]; then\n  build_folder=\"aws-sam-cli-beta\"\n  build_binary_name=\"sam-beta\"\nfi\n\nif ! [ \"$build_binary_name\" = \"\" ]; then\n    echo \"Building native installer with nightly/beta build\"\n    is_nightly=\"true\"\nelse\n    echo \"Building native installer with normal build\"\n    is_nightly=\"false\"\nfi\n\nset -eu\n\nyum install -y zlib-devel libffi-devel bzip2-devel\n\necho \"Making Folders\"\nmkdir -p .build/src\nmkdir -p .build/output/aws-sam-cli-src\nmkdir -p .build/output/python-libraries\nmkdir -p .build/output/pyinstaller-output\nmkdir -p .build/output/openssl\ncd .build/output/openssl\n\ncurl \"https://www.openssl.org/source/openssl-1.1.1t.tar.gz\" --output openssl-1.1.1.tar.gz\ntar xzf openssl-1.1.1.tar.gz\ncd openssl-1.1.1t\n./config --prefix=/opt/openssl && make && make install\ncd ../../..\n\necho \"Copying Source\"\ncp -r ../[!.]* ./src\ncp -r ./src/* ./output/aws-sam-cli-src\n\necho \"Removing CI Scripts and other files/direcories not needed\"\nrm -vf ./output/aws-sam-cli-src/appveyor*.yml\nrm -rf ./output/aws-sam-cli-src/tests\nrm -rf ./output/aws-sam-cli-src/designs\nrm -rf ./output/aws-sam-cli-src/docs\nrm -rf ./output/aws-sam-cli-src/media\nrm -rf ./output/aws-sam-cli-src/Make.ps1\nrm -rf ./output/aws-sam-cli-src/CODEOWNERS\nrm -rf ./output/aws-sam-cli-src/CODE_OF_CONDUCT.md\nrm -rf ./output/aws-sam-cli-src/CONTRIBUTING.md\nrm -rf ./output/aws-sam-cli-src/DESIGN.md\nrm -rf ./output/aws-sam-cli-src/Makefile\nrm -rf ./output/aws-sam-cli-src/mypy.ini\nrm -rf ./output/aws-sam-cli-src/pytest.ini\n\necho \"Installing Python\"\ncurl \"https://www.python.org/ftp/python/${python_version}/Python-${python_version}.tgz\" --output python.tgz\ntar -xzf python.tgz\ncd Python-$python_version\n./configure --enable-shared --with-openssl=/opt/openssl --with-openssl-rpath=auto \nmake -j8\nmake install\nldconfig\ncd ..\n\necho \"Installing Python Libraries\"\npython3 -m venv venv\n./venv/bin/pip install --upgrade pip\n./venv/bin/pip install -r src/requirements/reproducible-linux.txt\n\necho \"Copying All Python Libraries\"\ncp -r ./venv/lib/python*/site-packages/* ./output/python-libraries\n\necho \"Installing PyInstaller\"\n./venv/bin/pip install -r src/requirements/pyinstaller-build.txt\n\necho \"Building Binary\"\ncd src\nif [ \"$is_nightly\" = \"true\" ]; then\n    echo \"Updating samcli.spec with nightly/beta build\"\n    sed -i.bak \"s/'sam'/'$build_binary_name'/g\" installer/pyinstaller/samcli.spec\n    rm installer/pyinstaller/samcli.spec.bak\nfi\necho \"samcli.spec content is:\"\ncat installer/pyinstaller/samcli.spec\n# --onedir/--onefile options not allowed when spec file provided for\n# updated pyinstaller version.\n../venv/bin/python -m PyInstaller --clean installer/pyinstaller/samcli.spec\n\n\nmkdir pyinstaller-output\ndist_folder=\"sam\"\nif [ \"$is_nightly\" = \"true\" ]; then\n    echo \"using dist_folder with nightly/beta build\"\n    dist_folder=$build_binary_name\nfi\necho \"dist_folder=$dist_folder\"\nmv \"dist/$dist_folder\" pyinstaller-output/dist\ncp installer/assets/* pyinstaller-output\nchmod 755 pyinstaller-output/install\nif [ \"$is_nightly\" = \"true\" ]; then\n    echo \"Updating install script with nightly/beta build\"\n    sed -i.bak \"s/\\/usr\\/local\\/aws-sam-cli/\\/usr\\/local\\/$build_folder/g\" pyinstaller-output/install\n    sed -i.bak 's/EXE_NAME=\\\"sam\\\"/EXE_NAME=\\\"'$build_binary_name'\\\"/g' pyinstaller-output/install\n    rm pyinstaller-output/install.bak\nfi\necho \"install script content is:\"\ncat pyinstaller-output/install\necho \"Copying Binary\"\ncd ..\ncp -r src/pyinstaller-output/* output/pyinstaller-output\n\necho \"Packaging Binary\"\nyum install -y zip\ncd output/pyinstaller-output/\nzip -r ../\"$binary_zip_filename\" ./*\ncd ..\nzip -r \"$binary_zip_filename\" aws-sam-cli-src\n\necho \"Packaging Python Libraries\"\ncd python-libraries\nrm -rf ./*.dist-info\nrm -rf ./*.egg-info\nrm -rf ./__pycache__\nrm -rf ./pip\nrm -rf ./easy_install.py\nrm -rf ./pkg_resources\nrm -rf ./setuptools\n\nrm -rf ./*.so\nzip -r ../$python_library_zip_filename ./*\ncd ..\nzip -r $python_library_zip_filename aws-sam-cli-src\n", "num_lines": 144}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nbinary_zip_filename=${1:-}\npython_library_zip_filename=${2:-}\npython_version=${3:-}\nbuild_binary_name=${4:-}\nbuild_folder=${5:-}\nopenssl_version=${6:-}\nmac_arch=\"$(uname -m)\"\nopenssl_config_arch=\"\"\n\n# Set architecture to install openssl\nif [ \"$mac_arch\" = \"arm64\" ]; then\n    openssl_config_arch=\"darwin64-arm64-cc\"\n    export PATH=/usr/local/bin:\"$PATH\"\nelif [ \"$mac_arch\" = \"x86_64\" ]; then\n    openssl_config_arch=\"darwin64-x86_64-cc\"\nelse\n    echo \"Invalid architecture found\"\n    exit 1\nfi\n\nif [ \"$CI_OVERRIDE\" = \"1\" ]; then\n  build_folder=\"aws-sam-cli-beta\"\n  build_binary_name=\"sam-beta\"\nfi\n\nif [ \"$python_library_zip_filename\" = \"\" ]; then\n    python_library_zip_filename=\"python-libraries.zip\";\nfi\n\nif [ \"$openssl_version\" = \"\" ]; then\n    openssl_version=\"1.1.1o\";\nfi\n\nif [ \"$python_version\" = \"\" ]; then\n    python_version=\"3.8.13\";\nfi\n\nif ! [ \"$build_binary_name\" = \"\" ]; then\n    echo \"Building native installer with nightly/beta build\"\n    is_nightly=\"true\"\nelse\n    echo \"Building native installer with normal build\"\n    is_nightly=\"false\"\nfi\n\nset -eu\n\necho \"Making Folders\"\nmkdir -p .build/src\nmkdir -p .build/output/aws-sam-cli-src\nmkdir -p .build/output/python-libraries\nmkdir -p .build/output/pyinstaller-output\ncd .build\n\n# Installing Openssl to allow pip configured in the TLS/SSL location to install python libraries\necho \"Installing Openssl\"\ncurl -LO https://www.openssl.org/source/openssl-\"${openssl_version}\".tar.gz\ntar -xzf openssl-\"${openssl_version}\".tar.gz\ncd openssl-\"$openssl_version\"\n# Openssl configure https://wiki.openssl.org/index.php/Compilation_and_Installation\n./Configure --prefix=/usr/local --openssldir=/usr/local/openssl no-ssl3 no-ssl3-method no-zlib ${openssl_config_arch} enable-ec_nistp_64_gcc_128\n\nmake\nsudo make install\ncd ..\n\n# Copying aws-sam-cli source code\necho \"Copying Source\"\ncp -r ../[!.]* ./src\ncp -r ./src/* ./output/aws-sam-cli-src\n\necho \"Removing CI Scripts\"\nrm -vf ./output/aws-sam-cli-src/appveyor*.yml\n\necho \"Installing Python\"\ncurl \"https://www.python.org/ftp/python/${python_version}/Python-${python_version}.tgz\" --output python.tgz\ntar -xzf python.tgz\ncd Python-\"$python_version\"\n./configure --enable-shared\nmake -j8\nsudo make install\ncd ..\n\necho \"Installing Python Libraries\"\n/usr/local/bin/python3.8 -m venv venv\n./venv/bin/pip install --upgrade pip\n./venv/bin/pip install -r src/requirements/reproducible-mac.txt\n\necho \"Copying All Python Libraries\"\ncp -r ./venv/lib/python*/site-packages/* ./output/python-libraries\n\necho \"Installing PyInstaller\"\n./venv/bin/pip install -r src/requirements/pyinstaller-build.txt\n\n# Building the binary using pyinstaller\necho \"Building Binary\"\ncd src\nif [ \"$is_nightly\" = \"true\" ]; then\n    # If nightly build, replace the exe_name in spec file with build_binary_name\n    echo \"Updating samcli-mac.spec with nightly/beta build\"\n    sed -i.bak \"s/'sam'/'$build_binary_name'/g\" installer/pyinstaller/samcli-mac.spec\n    rm installer/pyinstaller/samcli-mac.spec.bak\nfi\necho \"samcli-mac.spec content is:\"\ncat installer/pyinstaller/samcli-mac.spec\n# Note: onefile/onedir options are not valid when spec file is used on mac\n../venv/bin/python -m PyInstaller --clean installer/pyinstaller/samcli-mac.spec\n\n# Organizing the pyinstaller-output folder\nmkdir pyinstaller-output\ndist_folder=\"sam\"\nif [ \"$is_nightly\" = \"true\" ]; then\n    echo \"using dist_folder with nightly/beta build\"\n    dist_folder=$build_binary_name\nfi\necho \"dist_folder=$dist_folder\"\nmv \"dist/$dist_folder\" pyinstaller-output/dist\ncp installer/assets/* pyinstaller-output\nchmod 755 pyinstaller-output/install\nif [ \"$is_nightly\" = \"true\" ]; then\n    echo \"Updating install script with nightly/beta build\"\n    # If nightly build, replace the build folder and build_binary_name in the install script\n    sed -i.bak \"s/\\/usr\\/local\\/aws-sam-cli/\\/usr\\/local\\/$build_folder/g\" pyinstaller-output/install\n    sed -i.bak 's/EXE_NAME=\\\"sam\\\"/EXE_NAME=\\\"'\"$build_binary_name\"'\\\"/g' pyinstaller-output/install\n    rm pyinstaller-output/install.bak\nfi\necho \"install script content is:\"\ncat pyinstaller-output/install\necho \"Copying Binary\"\ncd ..\ncp -r src/pyinstaller-output/* output/pyinstaller-output\n\necho \"Packaging Binary\"\ncd output\ncd pyinstaller-output\ncd dist\ncd ..\nzip -r ../\"$binary_zip_filename\" ./*\ncd ..\nzip -r \"$binary_zip_filename\" aws-sam-cli-src\n\n# Remove unwanted files and zip the python libraries\necho \"Packaging Python Libraries\"\ncd python-libraries\nrm -rf ./*.dist-info\nrm -rf ./*.egg-info\nrm -rf ./__pycache__\nrm -rf ./pip\nrm -rf ./easy_install.py\nrm -rf ./pkg_resources\nrm -rf ./setuptools\n\nrm -rf ./*.so\nzip -r ../\"$python_library_zip_filename\" ./*\ncd ..\nzip -r \"$python_library_zip_filename\" aws-sam-cli-src\n", "num_lines": 159}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -xeo pipefail\n\nexport SAM_CLI_TELEMETRY=\"${SAM_CLI_TELEMETRY:-0}\"\n\nif [ \"$CI_OVERRIDE\" = \"1\" ]; then\n    sam_binary=\"sam-beta\"\nelif [ \"$IS_NIGHTLY\" = \"1\" ]; then\n    sam_binary=\"sam-nightly\"\nelif [ \"$SAM_CLI_DEV\" = \"1\" ]; then\n    sam_binary=\"samdev\"\nelse\n    sam_binary=\"sam\"\nfi\n\nif ! command -v \"$sam_binary\" &> /dev/null; then\n    echo \"$sam_binary not found. Please check if it is in PATH\"\n    exit 1\nfi\n\necho \"Using ${sam_binary} as SAM CLI binary name\" \n\nif [ \"$sam_binary\" = \"sam\" ]; then\n    SAMCLI_INSTALLED_VERSION=$($sam_binary --version | cut -d \" \" -f 4)\n\n    # Get latest SAM CLI version from GH main branch\n    SAMCLI_LATEST_VERSION=$(curl -L https://raw.githubusercontent.com/aws/aws-sam-cli/master/samcli/__init__.py | tail -n 1 | cut -d '\"' -f 2)\n\n    # Check version\n    if [[ \"$SAMCLI_INSTALLED_VERSION\" != \"$SAMCLI_LATEST_VERSION\" ]]; then\n        echo \"expected: $SAMCLI_LATEST_VERSION; got: $SAMCLI_INSTALLED_VERSION\"\n        exit 1\n    fi\n\n    echo \"Version check succeeded\"\nfi\n\necho \"Starting testing sam binary\"\nrm -rf sam-app-testing\n\"$sam_binary\" init --no-interactive -n sam-app-testing --dependency-manager mod --runtime go1.x --app-template hello-world --package-type Zip --architecture x86_64\ncd sam-app-testing\nGOFLAGS=\"-buildvcs=false\" \"$sam_binary\" build\n\"$sam_binary\" validate\n\necho \"sam init, sam build, and sam validate commands Succeeded\"\n", "num_lines": 46}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nsrc_code=$1\nbuild_path=$2\noutput_name=$3\nresource_type=$4\necho \"building ${resource_type} ${src_code} into ${build_path}\"\n\ntemp_path=${build_path}/tmp_building/${output_name}\nif [[ \"${resource_type}\" == \"Layer\" ]]; then\n  temp_path=${build_path}/tmp_building/${output_name}/python\n  echo \"new path ${temp_path}\"\nfi\n\nmkdir -p ${build_path}\nmkdir -p ${build_path}/tmp_building\nmkdir -p ${build_path}/tmp_building/${output_name}\nmkdir -p ${temp_path}\nrm -rf ${temp_path}/*\n\ncp -r $src_code/* ${temp_path}\npip install -r ${temp_path}/requirements.txt -t ${temp_path}/.\ncurrent=$(pwd)\ncd ${build_path}/tmp_building/${output_name}\nzip -r ${output_name} .\ncd ${current}\nmv \"${build_path}/tmp_building/${output_name}/${output_name}\" \"${build_path}/$output_name\"\nrm -rf ${build_path}/tmp_building/${output_name}\nrm -rf ${build_path}/tmp_building\n", "num_lines": 29}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nsrc_code=$1\nbuild_path=$2\noutput_name=$3\nresource_type=$4\necho \"building ${resource_type} ${src_code} into ${build_path}\"\n\ntemp_path=${build_path}/tmp_building/${output_name}\nif [[ \"${resource_type}\" == \"Layer\" ]]; then\n  temp_path=${build_path}/tmp_building/${output_name}/python\n  echo \"new path ${temp_path}\"\nfi\n\nmkdir -p ${build_path}\nmkdir -p ${build_path}/tmp_building\nmkdir -p ${build_path}/tmp_building/${output_name}\nmkdir -p ${temp_path}\nrm -rf ${temp_path}/*\n\ncp -r $src_code/* ${temp_path}\npip install -r ${temp_path}/requirements.txt -t ${temp_path}/.\ncurrent=$(pwd)\ncd ${build_path}/tmp_building/${output_name}\nzip -r ${output_name} .\ncd ${current}\nmv \"${build_path}/tmp_building/${output_name}/${output_name}\" \"${build_path}/$output_name\"\nrm -rf ${build_path}/tmp_building/${output_name}\nrm -rf ${build_path}/tmp_building\n", "num_lines": 29}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nsrc_code=$1\nbuild_path=$2\noutput_name=$3\nresource_type=$4\necho \"building ${resource_type} ${src_code} into ${build_path}\"\n\ntemp_path=${build_path}/tmp_building/${output_name}\nif [[ \"${resource_type}\" == \"Layer\" ]]; then\n  temp_path=${build_path}/tmp_building/${output_name}/python\n  echo \"new path ${temp_path}\"\nfi\n\nmkdir -p ${build_path}\nmkdir -p ${build_path}/tmp_building\nmkdir -p ${build_path}/tmp_building/${output_name}\nmkdir -p ${temp_path}\nrm -rf ${temp_path}/*\n\ncp -r $src_code/* ${temp_path}\npip install -r ${temp_path}/requirements.txt -t ${temp_path}/.\ncurrent=$(pwd)\ncd ${build_path}/tmp_building/${output_name}\nzip -r ${output_name} .\ncd ${current}\nmv \"${build_path}/tmp_building/${output_name}/${output_name}\" \"${build_path}/$output_name\"\nrm -rf ${build_path}/tmp_building/${output_name}\nrm -rf ${build_path}/tmp_building\n", "num_lines": 29}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nsrc_code=$1\nbuild_path=$2\noutput_name=$3\nresource_type=$4\necho \"building ${resource_type} ${src_code} into ${build_path}\"\n\ntemp_path=${build_path}/tmp_building/${output_name}\nif [[ \"${resource_type}\" == \"Layer\" ]]; then\n  temp_path=${build_path}/tmp_building/${output_name}/python\n  echo \"new path ${temp_path}\"\nfi\n\nmkdir -p ${build_path}\nmkdir -p ${build_path}/tmp_building\nmkdir -p ${build_path}/tmp_building/${output_name}\nmkdir -p ${temp_path}\nrm -rf ${temp_path}/*\n\ncp -r $src_code/* ${temp_path}\npip install -r ${temp_path}/requirements.txt -t ${temp_path}/.\ncurrent=$(pwd)\ncd ${build_path}/tmp_building/${output_name}\nzip -r ${output_name} .\ncd ${current}\nmv \"${build_path}/tmp_building/${output_name}/${output_name}\" \"${build_path}/$output_name\"\nrm -rf ${build_path}/tmp_building/${output_name}\nrm -rf ${build_path}/tmp_building\n", "num_lines": 29}
{"repo_name": "aws-sam-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nsrc_code=$1\nbuild_path=$2\noutput_name=$3\nresource_type=$4\necho \"building ${resource_type} ${src_code} into ${build_path}\"\n\ntemp_path=${build_path}/tmp_building/${output_name}\nif [[ \"${resource_type}\" == \"Layer\" ]]; then\n  temp_path=${build_path}/tmp_building/${output_name}/python\n  echo \"new path ${temp_path}\"\nfi\n\nmkdir -p ${build_path}\nmkdir -p ${build_path}/tmp_building\nmkdir -p ${build_path}/tmp_building/${output_name}\nmkdir -p ${temp_path}\nrm -rf ${temp_path}/*\n\ncp -r $src_code/* ${temp_path}\npip install -r ${temp_path}/requirements.txt -t ${temp_path}/.\ncurrent=$(pwd)\ncd ${build_path}/tmp_building/${output_name}\nzip -r ${output_name} .\ncd ${current}\nmv \"${build_path}/tmp_building/${output_name}/${output_name}\" \"${build_path}/$output_name\"\nrm -rf ${build_path}/tmp_building/${output_name}\nrm -rf ${build_path}/tmp_building\n", "num_lines": 29}
{"repo_name": "aws-sam-cli-app-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\ndocker build -t al2-graalvm:gradle .\n", "num_lines": 5}
{"repo_name": "aws-sam-cli-app-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\ndocker build -t al2-graalvm:maven .", "num_lines": 4}
{"repo_name": "aws-sam-cli-app-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\ndocker build -t al2-graalvm:gradle .", "num_lines": 4}
{"repo_name": "aws-sam-cli-app-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n\ndocker build -t al2-graalvm:maven .", "num_lines": 4}
{"repo_name": "aws-sam-cli-app-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get user input for stack name\nread -p \"Enter the name of the CloudFormation stack: \" stack_name\n\n# Get the API Gateway URL from the stack\napi_gateway_endpoint=$(aws cloudformation describe-stacks --stack-name \"$stack_name\" --query \"Stacks[0].Outputs[?OutputKey=='APIGatewayEndpoint'].OutputValue\" --output text)\n\n# Get the CloudFront Distribution ID from the stack\ncloudfront_distribution_id=$(aws cloudformation describe-stacks --stack-name \"$stack_name\" --query \"Stacks[0].Outputs[?OutputKey=='CloudFrontDistributionId'].OutputValue\" --output text)\n\n# Get the S3 Bucket Name from the stack\ns3_bucket_name=$(aws cloudformation describe-stacks --stack-name \"$stack_name\" --query \"Stacks[0].Outputs[?OutputKey=='WebS3BucketName'].OutputValue\" --output text)\n\n# Output the results\necho \"API Gateway URL: $api_gateway_endpoint\"\necho \"CloudFront Distribution ID: $cloudfront_distribution_id\"\necho \"S3 Bucket Name: $s3_bucket_name\"\n\n# Move to frontend and install\ncd frontend/ && npm install\n\n# Create .env file for building distribtuion with API Gateway Endpoint defined\ntouch .env\n\n# Add the API Gateway endpoint to the .env file\necho \"VUE_APP_API_ENDPOINT=$api_gateway_endpoint\" >> .env\n\n# Confirm that the endpoint has been added to the .env file\necho \"The API Gateway endpoint has been added to the .env file:\"\ncat .env\n\n# Create distribution for deployment\nnpm run build && cd dist/\n\n# Sync distribution with S3\naws s3 sync . s3://$s3_bucket_name/\n\n# Create cloudfront invalidation and capture id for next step\ninvalidation_output=$(aws cloudfront create-invalidation --distribution-id $cloudfront_distribution_id --paths \"/*\")\ninvalidation_id=$(echo \"$invalidation_output\" | grep -oP '(?<=\"Id\": \")[^\"]+')\n\n# Wait for cloudfront invalidation to complete\naws cloudfront wait invalidation-completed --distribution-id $cloudfront_distribution_id --id $invalidation_id\n\n# Get cloudfront domain name and validate\ncloudfront_domain_name=$(aws cloudfront list-distributions --query \"DistributionList.Items[?Id=='$cloudfront_distribution_id'].DomainName\" --output text)\n\necho \"The invalidation is now complete - please visit your cloudfront URL to test: $cloudfront_domain_name\"\n", "num_lines": 50}
{"repo_name": "aws-sam-cli-pipeline-init-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nROLE=$1\nSESSION_NAME=$2\n\n# Unset AWS credentials stored in env so that every time this script runs,\n# it will use the AWS CodeBuild service role to assume the target IAM roles.\nunset AWS_SESSION_TOKEN\nunset AWS_ACCESS_KEY_ID\nunset AWS_SECRET_ACCESS_KEY\n\ncred=$(aws sts assume-role --role-arn \"$ROLE\" \\\n                           --role-session-name \"$SESSION_NAME\" \\\n                           --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                           --output text)\n\nACCESS_KEY_ID=$(echo \"$cred\" | awk '{ print $1 }')\nexport AWS_ACCESS_KEY_ID=$ACCESS_KEY_ID\n\nSECRET_ACCESS_KEY=$(echo \"$cred\" | awk '{ print $2 }')\nexport AWS_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY\n\nSESSION_TOKEN=$(echo \"$cred\" | awk '{ print $3 }')\nexport AWS_SESSION_TOKEN=$SESSION_TOKEN\n", "num_lines": 26}
{"repo_name": "aws-sam-cli-pipeline-init-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nROLE=$1\nSESSION_NAME=$2\n\n# Unset AWS credentials stored in env so that every time this script runs,\n# it will use the AWS CodeBuild service role to assume the target IAM roles.\nunset AWS_SESSION_TOKEN\nunset AWS_ACCESS_KEY_ID\nunset AWS_SECRET_ACCESS_KEY\n\ncred=$(aws sts assume-role --role-arn \"$ROLE\" \\\n                           --role-session-name \"$SESSION_NAME\" \\\n                           --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                           --output text)\n\nACCESS_KEY_ID=$(echo \"$cred\" | awk '{ print $1 }')\nexport AWS_ACCESS_KEY_ID=$ACCESS_KEY_ID\n\nSECRET_ACCESS_KEY=$(echo \"$cred\" | awk '{ print $2 }')\nexport AWS_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY\n\nSESSION_TOKEN=$(echo \"$cred\" | awk '{ print $3 }')\nexport AWS_SESSION_TOKEN=$SESSION_TOKEN\n", "num_lines": 24}
{"repo_name": "aws-sam-cli-pipeline-init-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nROLE=$1\nSESSION_NAME=$2\nPROFILE_NAME=$3\nPERMISSIONS_PROVIDER=$4\nTOKEN=$5\n\nunset AWS_SESSION_TOKEN\n\nif [ \"$PERMISSIONS_PROVIDER\" = \"AWS IAM\" ]\nthen\n    aws configure --profile sam-pipeline-user set aws_access_key_id \"$PIPELINE_USER_ACCESS_KEY_ID\"\n    aws configure --profile sam-pipeline-user set aws_secret_access_key \"$PIPELINE_USER_SECRET_ACCESS_KEY\"\n\n    cred=$(aws sts assume-role --profile sam-pipeline-user \\\n                            --role-arn \"$ROLE\" \\\n                            --role-session-name \"$SESSION_NAME\" \\\n                            --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                            --output text)\nelse\n    # Use assume-role-with-web-identity instead of assume-role\n    cred=$(aws sts assume-role-with-web-identity --role-arn \"$ROLE\" \\\n                            --role-session-name \"$SESSION_NAME\" \\\n                            --web-identity-token \"$TOKEN\" \\\n                            --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                            --output text)\nfi\n\nACCESS_KEY_ID=$(echo \"$cred\" | awk '{ print $1 }')\naws configure --profile \"$PROFILE_NAME\" set aws_access_key_id \"$ACCESS_KEY_ID\"\n\nSECRET_ACCESS_KEY=$(echo \"$cred\" | awk '{ print $2 }')\naws configure --profile \"$PROFILE_NAME\" set aws_secret_access_key \"$SECRET_ACCESS_KEY\"\n\nSESSION_TOKEN=$(echo \"$cred\" | awk '{ print $3 }')\naws configure --profile \"$PROFILE_NAME\" set aws_session_token \"$SESSION_TOKEN\"\n", "num_lines": 37}
{"repo_name": "aws-sam-cli-pipeline-init-templates", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nROLE=$1\nSESSION_NAME=$2\nPERMISSIONS_PROVIDER=$3\n\nunset AWS_SESSION_TOKEN\nexport AWS_ACCESS_KEY_ID=$PIPELINE_USER_ACCESS_KEY_ID\nexport AWS_SECRET_ACCESS_KEY=$PIPELINE_USER_SECRET_ACCESS_KEY\n\nif [ \"$PERMISSIONS_PROVIDER\" = \"OpenID Connect (OIDC)\" ]\nthen\n    # Use assume-role-with-web-identity instead of assume-role\n    cred=$(aws sts assume-role-with-web-identity --role-arn \"$ROLE\" \\\n                            --role-session-name \"$SESSION_NAME\" \\\n                            --web-identity-token \"$CI_JOB_JWT_V2\" \\\n                            --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                            --output text)\n\nelse\n    cred=$(aws sts assume-role --role-arn \"$ROLE\" \\\n                        --role-session-name \"$SESSION_NAME\" \\\n                        --query '[Credentials.AccessKeyId,Credentials.SecretAccessKey,Credentials.SessionToken]' \\\n                        --output text)\nfi\nACCESS_KEY_ID=$(echo \"$cred\" | awk '{ print $1 }')\nexport AWS_ACCESS_KEY_ID=$ACCESS_KEY_ID\n\nSECRET_ACCESS_KEY=$(echo \"$cred\" | awk '{ print $2 }')\nexport AWS_SECRET_ACCESS_KEY=$SECRET_ACCESS_KEY\n\nSESSION_TOKEN=$(echo \"$cred\" | awk '{ print $3 }')\nexport AWS_SESSION_TOKEN=$SESSION_TOKEN\n\n", "num_lines": 34}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\nCRT_URI_PREFIX=https://codeload.github.com/awslabs\nCRT_URI=${CRT_URI_PREFIX}/aws-crt-cpp/zip/cb474daeeaf5c025bd3408103adf61b97b74e600  # v0.19.9\n\nAWS_C_AUTH_URI=${CRT_URI_PREFIX}/aws-c-auth/zip/54f8d804120daab9e0d75a56a113a222b334d0f9  # v0.6.26\nAWS_C_CAL_URI=${CRT_URI_PREFIX}/aws-c-cal/zip/de2f0f2e86a7e7b85b28cc027b8cf620945d8825  # v0.5.21\nAWS_C_COMMON_URI=${CRT_URI_PREFIX}/aws-c-common/zip/21d478b14465bfa52608d4040d9084e955180fa7  # v0.8.15\nAWS_C_COMPRESSION_URI=${CRT_URI_PREFIX}/aws-c-compression/zip/b517b7decd0dac30be2162f5186c250221c53aff  # v0.2.16\nAWS_C_EVENT_STREAM_URI=${CRT_URI_PREFIX}/aws-c-event-stream/zip/0f6eee87aee2860598084e814e0eedc0b3b9122d  # v0.2.20\nAWS_C_HTTP_URI=${CRT_URI_PREFIX}/aws-c-http/zip/c7350090b8712d9a6fd66a7d5d45056c87879f26  # v0.7.7\nAWS_C_IO_URI=${CRT_URI_PREFIX}/aws-c-io/zip/2c4475f60d9103d90a30fc4bc38940c0477d63d9  # v0.13.21\nAWS_C_MQTT_URI=${CRT_URI_PREFIX}/aws-c-mqtt/zip/815fc9731b77c7a21308a1be9ac11378c053b515  # v0.8.10\nAWS_C_S3_URI=${CRT_URI_PREFIX}/aws-c-s3/zip/ae6c6cc7dd301044dd6d81d24b005d2463a23de9  # v0.2.8\nAWS_C_SDKUTILS_URI=${CRT_URI_PREFIX}/aws-c-sdkutils/zip/9de59230f025df2745b098feda3611f9667e5a35  # v0.1.8\nAWS_CHECKSUMS_URI=${CRT_URI_PREFIX}/aws-checksums/zip/ad53be196a25bbefa3700a01187fdce573a7d2d0  # v0.1.14\nAWS_LC_URI=${CRT_URI_PREFIX}/aws-lc/zip/161e747063dcb16e71d299190f072a26c0a56294  # v1.5.0\nS2N_URI=${CRT_URI_PREFIX}/s2n/zip/274f3213eca8b535bf43aa203711902d98e534dd  # v1.3.38\n\n\necho \"Removing CRT\"\nrm -rf crt\n\necho \"Downloading and expanding CRT CPP\"\nmkdir -p crt/tmp\ncurl ${CRT_URI} --output crt/tmp/crt.zip\nunzip crt/tmp/crt -d crt\nCRT_DIR_TMP=`ls -d crt/aws-crt-cpp*`\nmv ${CRT_DIR_TMP} crt/aws-crt-cpp\n\necho \"Downloading and expanding CRT dependencies\"\ncurl ${AWS_C_AUTH_URI} --output crt/tmp/1.zip\ncurl ${AWS_C_CAL_URI} --output crt/tmp/2.zip\ncurl ${AWS_C_COMMON_URI} --output crt/tmp/3.zip\ncurl ${AWS_C_COMPRESSION_URI} --output crt/tmp/4.zip\ncurl ${AWS_C_EVENT_STREAM_URI} --output crt/tmp/5.zip\ncurl ${AWS_C_HTTP_URI} --output crt/tmp/6.zip\ncurl ${AWS_C_IO_URI} --output crt/tmp/7.zip\ncurl ${AWS_C_MQTT_URI} --output crt/tmp/8.zip\ncurl ${AWS_C_S3_URI} --output crt/tmp/9.zip\ncurl ${AWS_C_SDKUTILS_URI} --output crt/tmp/10.zip\ncurl ${AWS_CHECKSUMS_URI} --output crt/tmp/11.zip\ncurl ${AWS_LC_URI} --output crt/tmp/12.zip\ncurl ${S2N_URI} --output crt/tmp/13.zip\n\n\nfor a in `seq 1 13`; do\n    unzip crt/tmp/${a} -d crt/tmp\ndone\n\nrm -rf crt/aws-crt-cpp/crt\nmkdir crt/aws-crt-cpp/crt\n\nfor a in `ls crt/tmp |grep -v '.zip$' |grep -v aws-crt-cpp`; do\n    mv crt/tmp/$a \"crt/aws-crt-cpp/crt/\"`echo $a | sed 's/-[0-9a-f]\\{40\\}$//'`\ndone\n\necho \"Adjust S2N location\"\nmv crt/aws-crt-cpp/crt/s2n-tls crt/aws-crt-cpp/crt/s2n\n\necho \"To complete setup run cmake -Bbuild; cmake --build build; cmake --build --target install\"\n", "num_lines": 64}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eu\n\nif [[ $# -lt 1 ]]; then\n    echo -e \"error: missing location paramter.\\n\"\n    echo -e \"USAGE: BuildMyCode [OPTIONS]\\n\"\n    echo \"OPTIONS:\"\n    echo \"-b|--branch       The name of the git branch. Default is the current branch.\"\n    echo \"-c|--cmake-flags  Any additional CMake flags to pass to the build jobs.\"\n    echo \"-l|--location     The name of key in S3 under which to save the BuildSpec.zip file.\"\n\n    exit 1\nfi\n\nbranch=\"\"\ncmakeFlags=\"\"\n# default to the current branch\nif [[ -z $branch ]]; then\n    branch=$(git rev-parse --abbrev-ref HEAD)\nfi\n\nPOSITIONAL=()\nwhile [[ $# -gt 0 ]]\ndo\n    key=\"$1\"\n    case $key in\n        -b|--branch)\n            branch=$2\n            shift # past argument\n            ;;\n        -c|--cmake-flags)\n            cmakeFlags=$2\n            shift # past argument\n            ;;\n        -l|--location) # where to put the buildspec.zip file\n            buildspecLocation=$2\n            shift # past argument\n            ;;\n        *)    # unknown option\n            POSITIONAL+=(\"$1\") # save it in an array for later\n            shift # past argument\n            ;;\n    esac\ndone\nset -- \"${POSITIONAL[@]}\" # restore positional parameters\n\n\njson='{ \"branch\": \"'$branch'\", \"cmakeFlags\": \"'$cmakeFlags' \"}'\necho \"$json\" >BuildSpec.json\nzip -r BuildSpec.zip BuildSpec.json\naws s3 cp BuildSpec.zip s3://aws-sdk-cpp-dev-pipeline/\"${buildspecLocation}\"/BuildSpec.zip\nS3VERSION=$(aws s3api head-object --bucket aws-sdk-cpp-dev-pipeline --key \"${buildspecLocation}\"/BuildSpec.zip | awk '/VersionId/{gsub(/[\",]/, \"\"); print $2}')\necho -e \"\\033[30;42mYour build version ID is ${S3VERSION}\\033[0m\"\necho \"Remember that the code that is going to be build and tested is the one in the remote branch $branch. If you didn't push your changes, you are building an old version.\"\n", "num_lines": 56}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nbranch =$(python aws-sdk-cpp/CI/ExtractBuildArgs.py branch)\ngit clone git@github.com:awslabs/aws-sdk-cpp-staging.git aws-sdk-cpp\ncd aws-sdk-cpp\ngit reset --hard HEAD\ngit checkout master\ngit pull\ngit checkout $branch\n", "num_lines": 10}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This script validates that every files in the install manifest generated by cmake is in an expected location\n# We expect to use this script as a validation step in CI for Linux x86_64 platforms.\n# This acts also as a driver to make thes list of locations more compact, expect reductions here in the future.\n\nset -e\nMANIFEST=install_manifest.txt\nTOTAL_FILES=$(wc -l $MANIFEST)\nUNEXPECTED_FILES=$( cat $MANIFEST \\\n                  | grep -v '^/usr/local/include/aws' \\\n                  | grep -v '^/usr/local/include/s2n.h' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/cmake' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/libaws-' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/pkgconfig/aws-cpp-sdk-' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/aws-crt-cpp' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/aws-c' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/s2n' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/libs2n' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/libtesting-resources' \\\n                  | grep -v '^/usr/local/lib\\(64\\)\\?/pkgconfig/testing-resources.pc' ) \\\n            || [[ $? == 1 ]] # 1 is grep error code for empty result\nif [[ !  -z  $UNEXPECTED_FILES  ]]\nthen\n    TOTAL_UNEXPECTED_FILES=$( echo $UNEXPECTED_FILES | wc -l)\n        echo $TOTAL_UNEXPECTED_FILES ' / ' $TOTAL_FILES ' are unexpected to be installed from manifest'\n    echo $UNEXPECTED_FILES\n    exit 1\nfi\n", "num_lines": 29}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how to build the SDK on Debug build-type using clang with c++20 standard flagbuild-al2-debug-clang-cxx20.sh\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/al2-build\"\nmkdir \"${PREFIX_DIR}/al2-install\"\ncd \"${PREFIX_DIR}/al2-build\"\ncmake -GNinja ../aws-sdk-cpp -DCMAKE_BUILD_TYPE=Debug -DCMAKE_TOOLCHAIN_FILE=../aws-sdk-cpp/toolchains/clang-c++20.cmake -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/al2-install\"\nninja-build -j $(grep -c ^processor /proc/cpuinfo)\nninja-build install\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how to build the SDK on Debug build-type with minimize on and address sanitizers\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/al2-build\"\nmkdir \"${PREFIX_DIR}/al2-install\"\ncd \"${PREFIX_DIR}/al2-build\"\ncmake -GNinja ../aws-sdk-cpp -DCMAKE_BUILD_TYPE=Debug -DCMAKE_CXX_FLAGS=\"-ggdb -fsanitize=address\" -DMINIMIZE_SIZE=ON -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/al2-install\"\nninja-build -j $(grep -c ^processor /proc/cpuinfo)\nninja-build install\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how to build the SDK on Debug build-type using gcc10 with c++20 standard flag\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/al2-build\"\nmkdir \"${PREFIX_DIR}/al2-install\"\ncd \"${PREFIX_DIR}/al2-build\"\ncmake -GNinja ../aws-sdk-cpp -DCMAKE_BUILD_TYPE=Debug -DCMAKE_TOOLCHAIN_FILE=../aws-sdk-cpp/toolchains/gcc10-c++20.cmake -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/al2-install\"\nninja-build -j $(grep -c ^processor /proc/cpuinfo)\nninja-build install\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how to build the SDK on Debug build-type with unity build disabled\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/al2-build\"\nmkdir \"${PREFIX_DIR}/al2-install\"\ncd \"${PREFIX_DIR}/al2-build\"\ncmake -GNinja ../aws-sdk-cpp -DCMAKE_BUILD_TYPE=Debug -DENABLE_UNITY_BUILD=OFF -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/al2-install\"\nninja-build -j $(grep -c ^processor /proc/cpuinfo)\nninja-build install\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how the simplest build of the SDK using all default parameters\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/al2-build\"\nmkdir \"${PREFIX_DIR}/al2-install\"\ncd \"${PREFIX_DIR}/al2-build\"\ncmake -GNinja ../aws-sdk-cpp -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/al2-install\"\ncmake --build . --parallel $(grep -c ^processor /proc/cpuinfo)\ncmake --build . --target install\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how to build the SDK on Debug build-type with minimize on and address sanitizers\n# Directories created and files are prefixed with PREFIX_DIR argument\n# SDK installation is expected to be in ${PREFIX_DIR}/al2-install and a clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# OUTPUT_DIR is relative to the PREFIX_DIR\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"Usage: ${0} PREFIX_DIR OUTPUT_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\nOUTPUT_DIR=\"${PREFIX_DIR}/$2\"\nSRC_DIR=\"${PREFIX_DIR}/aws-sdk-cpp\"\n\nexport VERSION_NUM=$(grep AWS_SDK_VERSION_STRING \"${SRC_DIR}/src/aws-cpp-sdk-core/include/aws/core/VersionConfig.h\" | cut -d '\"' -f2)\necho \"AWS_SDK_VERSION: ${VERSION_NUM}\"\n\necho \"Running doc generation\"\ncd \"${SRC_DIR}\"\n# curl https://raw.githubusercontent.com/jothepro/doxygen-awesome-css/main/doxygen-awesome.css -o \"${SRC_DIR}/docs/doxygen/static/doxygen-awesome.css\"\npython3 \"${SRC_DIR}/docs/doxygen/run_docs_generation.py\" --sdk_root \"${SRC_DIR}\" --sdk_version \"${VERSION_NUM}\" --output_dir \"${OUTPUT_DIR}/${VERSION_NUM}\"\n\necho \"Creating Cross Links\"\npython3 \"${SRC_DIR}/docs/doxygen/generate_cross_link_data.py\" \\\n  --apiDefinitionsPath \"${SRC_DIR}/tools/code-generation/api-descriptions/\" \\\n  --templatePath \"${SRC_DIR}/docs/doxygen/static/crosslink_redirect.html\" \\\n  --outputPath \"${OUTPUT_DIR}/crosslink_redirect.html\"\n\necho \"Staging static files\"\nmkdir -p \"${OUTPUT_DIR}/root/html\"\ncp \"${SRC_DIR}/LICENSE\" \"${OUTPUT_DIR}/root/html\"\nmkdir -p \"${OUTPUT_DIR}/LATEST\"\nrsync -av \"${OUTPUT_DIR}\"/\"${VERSION_NUM}\"/* \"${OUTPUT_DIR}/LATEST\"\n\ncp \"${SRC_DIR}/docs/doxygen/static/index.html\" -p \"${OUTPUT_DIR}/\"\ncp \"${SRC_DIR}/docs/doxygen/static/index.html\" \"${OUTPUT_DIR}/LATEST/index.html\"\ncp \"${SRC_DIR}/docs/doxygen/static/index.html\" \"${OUTPUT_DIR}/${VERSION_NUM}/index.html\"\n", "num_lines": 44}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script builds a sample app\n# Directories created and files are prefixed with PREFIX_DIR argument\n# SDK installation is expected to be in ${PREFIX_DIR}/al2-install and a clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# A AWS_ACCOUNT with proper role setup is required to run the built app, if passed argument, app is tried to run after build\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -eq 1 ]; then\n  AUTORUN=0\nelif [ \"$#\" -eq 3 ]; then\n  AUTORUN=1\n  AWS_ACCOUNT=\"$2\"\n  AWS_ROLE_SESSION_NAME=\"$3\"\nelse\n  echo \"Usage: ${0} PREFIX_DIR AWS_ACCOUNT ROLE_SESSION_NAME\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\necho \"Building the Sample App\"\n\nmkdir \"${PREFIX_DIR}/sample-build\"\nmkdir \"${PREFIX_DIR}/sample-install\"\ncd \"${PREFIX_DIR}/sample-build\"\ncmake ../aws-sdk-cpp/tools/CI/install-test -G Ninja -DCMAKE_CXX_FLAGS=\"-ggdb -fsanitize=address\" -DCMAKE_PREFIX_PATH=\"${PREFIX_DIR}/al2-install\" -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/sample_install\"\ncmake --build .\ncmake --build . --target install\n\nif [ \"${AUTORUN}\" -eq 0 ]; then\n  # Only continue if there is a scheduled autorun\n  exit 0\nfi\n\necho \"Setting the run environment\"\nexport TEST_ASSUME_ROLE_ARN=arn:aws:iam::${AWS_ACCOUNT}:role/IntegrationTest\nexport sts=$(aws sts assume-role --role-arn \"$TEST_ASSUME_ROLE_ARN\" --role-session-name \"${AWS_ROLE_SESSION_NAME}\" --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]')\nexport profile=sdk-integ-test\naws configure set aws_access_key_id $(echo \"$sts\" | jq -r '.[0]') --profile \"$profile\"\naws configure set aws_secret_access_key $(echo \"$sts\" | jq -r '.[1]') --profile \"$profile\"\naws configure set aws_session_token $(echo \"$sts\" | jq -r '.[2]') --profile \"$profile\"\naws configure list --profile \"$profile\"\nexport AWS_PROFILE=$profile\nexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:${PREFIX_DIR}/al2-install/lib64/\"\necho \"Running the app\"\ncd \"${PREFIX_DIR}/sample_install/bin\"\n./app\n", "num_lines": 52}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script is an example of how the simplest build of the SDK using all default parameters\n# Directories created and files are prefixed with PREFIX_DIR argument\n# A clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# Platform: MacOS\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: ${0} PREFIX_DIR\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\nmkdir \"${PREFIX_DIR}/mac-build\"\nmkdir \"${PREFIX_DIR}/mac-install\"\ncd \"${PREFIX_DIR}/mac-build\"\ncmake ../aws-sdk-cpp -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/mac-install\"\ncmake --build . --parallel $(sysctl -n hw.ncpu)\ncmake --install .\n", "num_lines": 24}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script builds a sample app\n# Directories created and files are prefixed with PREFIX_DIR argument\n# SDK installation is expected to be in ${PREFIX_DIR}/mac-install and a clone of aws-sdk-cpp is expected to be in ${PREFIX_DIR}/aws-sdk-cpp\n# A AWS_ACCOUNT with proper role setup is required to run the built app, if passed argument, app is tried to run after build\n# Platform: MacOS\n\nset -e\n\nif [ \"$#\" -eq 1 ]; then\n  AUTORUN=0\nelif [ \"$#\" -eq 3 ]; then\n  AUTORUN=1\n  AWS_ACCOUNT=\"$2\"\n  AWS_ROLE_SESSION_NAME=\"$3\"\nelse\n  echo \"Usage: ${0} PREFIX_DIR AWS_ACCOUNT ROLE_SESSION_NAME\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\n\necho \"Building the Sample App\"\n\ncd aws-sdk-cpp/tools/CI/install-test\nmkdir \"${PREFIX_DIR}/sample-build\"\nmkdir \"${PREFIX_DIR}/sample-install\"\ncd \"${PREFIX_DIR}/sample-build\"\ncmake ../aws-sdk-cpp/tools/CI/install-test -DCMAKE_CXX_FLAGS=\"-ggdb -fsanitize=address\" -DCMAKE_PREFIX_PATH=\"${PREFIX_DIR}/mac-install\" -DCMAKE_INSTALL_PREFIX=\"${PREFIX_DIR}/sample_install\"\ncmake --build .\ncmake --install .\n\nif [ \"${AUTORUN}\" -eq 0 ]; then\n  # Only continue if there is a scheduled autorun\n  exit 0\nfi\n\necho \"Setting the run environment\"\nexport TEST_ASSUME_ROLE_ARN=arn:aws:iam::${AWS_ACCOUNT}:role/IntegrationTest\nexport TEST_LAMBDA_CODE_PATH=${PREFIX_DIR}/aws-sdk-cpp/tests/aws-cpp-sdk-lambda-integration-tests/resources\nexport sts=$(aws sts assume-role --role-arn \"$TEST_ASSUME_ROLE_ARN\" --role-session-name \"${AWS_ROLE_SESSION_NAME}\" --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]')\nexport profile=sdk-integ-test\naws configure set aws_access_key_id $(echo \"$sts\" | jq -r '.[0]') --profile \"$profile\"\naws configure set aws_secret_access_key $(echo \"$sts\" | jq -r '.[1]') --profile \"$profile\"\naws configure set aws_session_token $(echo \"$sts\" | jq -r '.[2]') --profile \"$profile\"\naws configure list --profile \"$profile\"\nexport AWS_PROFILE=$profile\nexport DYLD_LIBRARY_PATH=$CATAPULT_WORKSPACE_DIR/mac-install/lib\necho \"Running the app\"\ncd \"${PREFIX_DIR}/sample_install/bin\"\n./app\n", "num_lines": 54}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script runs integration tests previously build\n# Directories created and files are prefixed with PREFIX_DIR argument\n# SDK build to tests is expected to be in ${PREFIX_DIR}/al2-build, the source project in ${PREFIX_DIR}/aws-sdk-cpp,\n# and an installed build to test in ${PREFIX_DIR}/al2-install\n# A AWS_ACCOUNT with proper role setup is required to run the tests\n# Platform: Amazon Linux 2\n\nset -e\n\nif [ \"$#\" -ne 3 ]; then\n  echo \"Usage: ${0} PREFIX_DIR AWS_ACCOUNT ROLE_SESSION_NAME\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\nAWS_ACCOUNT=\"$2\"\nAWS_ROLE_SESSION_NAME=\"$3\"\n\necho \"Setting the run environment\"\nexport TEST_ASSUME_ROLE_ARN=arn:aws:iam::${AWS_ACCOUNT}:role/IntegrationTest\nexport TEST_LAMBDA_CODE_PATH=${PREFIX_DIR}/aws-sdk-cpp/tools/aws-cpp-sdk-lambda-integration-tests/resources\nexport sts=$(aws sts assume-role --role-arn \"$TEST_ASSUME_ROLE_ARN\" --role-session-name \"${AWS_ROLE_SESSION_NAME}\" --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]')\nexport profile=sdk-integ-test\naws configure set aws_access_key_id $(echo \"$sts\" | jq -r '.[0]') --profile \"$profile\"\naws configure set aws_secret_access_key $(echo \"$sts\" | jq -r '.[1]') --profile \"$profile\"\naws configure set aws_session_token $(echo \"$sts\" | jq -r '.[2]') --profile \"$profile\"\naws configure list --profile \"$profile\"\nexport AWS_PROFILE=$profile\nexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:${PREFIX_DIR}/al2-install/lib64/\"\ncd \"${PREFIX_DIR}/al2-build\"\nif [ -f \"${PREFIX_DIR}/aws-sdk-cpp/tools/scripts/suppressions.txt\" ]; then export LSAN_OPTIONS=suppressions=\"${PREFIX_DIR}/aws-sdk-cpp/tools/scripts/suppressions.txt\"; fi\npython ../aws-sdk-cpp/tools/scripts/run_integration_tests.py --testDir ./tests\n", "num_lines": 36}
{"repo_name": "aws-sdk-cpp", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0.\n\n# This script runs integration tests previously build\n# Directories created and files are prefixed with PREFIX_DIR argument\n# SDK build to tests is expected to be in ${PREFIX_DIR}/mac-build, the source project in ${PREFIX_DIR}/aws-sdk-cpp,\n# and an installed build to test in ${PREFIX_DIR}/mac-install\n# A AWS_ACCOUNT with proper role setup is required to run the tests\n# Platform: MacOS\n\nset -e\n\nif [ \"$#\" -ne 3 ]; then\n  echo \"Usage: ${0} PREFIX_DIR AWS_ACCOUNT ROLE_SESSION_NAME\"\n  exit 1\nfi\nPREFIX_DIR=\"$1\"\nAWS_ACCOUNT=\"$2\"\nAWS_ROLE_SESSION_NAME=\"$3\"\n\necho \"Setting the run environment\"\nexport TEST_ASSUME_ROLE_ARN=arn:aws:iam::${AWS_ACCOUNT}:role/IntegrationTest\nexport TEST_LAMBDA_CODE_PATH=${PREFIX_DIR}/aws-sdk-cpp/tests/aws-cpp-sdk-lambda-integration-tests/resources\nexport sts=$(aws sts assume-role --role-arn \"$TEST_ASSUME_ROLE_ARN\" --role-session-name \"${AWS_ROLE_SESSION_NAME}\" --query 'Credentials.[AccessKeyId,SecretAccessKey,SessionToken]')\nexport profile=sdk-integ-test\naws configure set aws_access_key_id $(echo \"$sts\" | jq -r '.[0]') --profile \"$profile\"\naws configure set aws_secret_access_key $(echo \"$sts\" | jq -r '.[1]') --profile \"$profile\"\naws configure set aws_session_token $(echo \"$sts\" | jq -r '.[2]') --profile \"$profile\"\naws configure list --profile \"$profile\"\nexport AWS_PROFILE=$profile\nexport DYLD_LIBRARY_PATH=$CATAPULT_WORKSPACE_DIR/mac-install/lib\ncd \"${PREFIX_DIR}/mac-build\"\nif [ -f \"${PREFIX_DIR}/aws-sdk-cpp/tools/scripts/suppressions.txt\" ]; then export LSAN_OPTIONS=suppressions=\"${PREFIX_DIR}/aws-sdk-cpp/tools/scripts/suppressions.txt\"; fi\npython ../aws-sdk-cpp/tools/scripts/run_integration_tests.py --testDir ./tests\n", "num_lines": 36}
{"repo_name": "aws-sdk-go-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nPROJECT_DIR=\"\"\nSDK_SOURCE_DIR=$(cd `dirname $0` && pwd)\n\nusage() {\n  echo \"Usage: $0 [-s SDK_SOURCE_DIR] [-d PROJECT_DIR]\" 1>&2\n  exit 1\n}\n\nwhile getopts \"hs:d:\" options; do\n  case \"${options}\" in\n  s)\n    SDK_SOURCE_DIR=${OPTARG}\n    if [ \"$SDK_SOURCE_DIR\" == \"\" ]; then\n      echo \"path to SDK source directory is required\" || exit\n      usage\n    fi\n    ;;\n  d)\n    PROJECT_DIR=${OPTARG}\n    ;;\n  h)\n    usage\n    ;;\n  *)\n    usage\n    ;;\n  esac\ndone\n\nif [ \"$PROJECT_DIR\" != \"\" ]; then\n  cd \"$PROJECT_DIR\" || exit\nfi\n\ngo mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep \"github.com/aws/aws-sdk-go-v2\" | while read x; do\n  repPath=${x/github.com\\/aws\\/aws-sdk-go-v2/${SDK_SOURCE_DIR}}\n  echo -replace $x=$repPath\ndone | xargs go mod edit\n", "num_lines": 40}
{"repo_name": "aws-sdk-go-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -xe\n\nSDK_ROOT=$1\nCODEGEN_ROOT=$2\n\nREPOTOOLS_VERSION=\"${REPOTOOLS_VERSION:-latest}\"\n\ncd \"$1\"\ngo run github.com/awslabs/aws-go-multi-module-repository-tools/cmd/gomodgen@${REPOTOOLS_VERSION} -build \"$CODEGEN_ROOT\"\n", "num_lines": 12}
{"repo_name": "aws-sdk-java", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho '{';\necho '\"Version\": 1,';\necho \"\\\"AccessKeyId\\\": \\\"$1\\\",\";\necho \"\\\"SecretAccessKey\\\": \\\"$2\\\"\";\nif [[ $# -ge 3 ]]; then\n    echo ','\n    echo \"\\\"SessionToken\\\": \\\"$3\\\"\";\nfi;\nif [[ $# -ge 4 ]]; then\n    echo ','\n    echo \"\\\"Expiration\\\": \\\"$4\\\"\";\nfi;\necho '}';", "num_lines": 14}
{"repo_name": "aws-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Some error case\" 1>&2\nexit 125", "num_lines": 3}
{"repo_name": "aws-sdk-java-v2", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho '{';\necho '\"Version\": 1,';\necho \"\\\"AccessKeyId\\\": \\\"$1\\\",\";\necho \"\\\"SecretAccessKey\\\": \\\"$2\\\"\";\nif [[ $# -ge 3 ]]; then\n    echo ',';\n    if [[ \"$3\" = \"RANDOM_TOKEN\" ]]; then\n        echo \"\\\"SessionToken\\\": \\\"$RANDOM\\\"\"\n    else\n        echo \"\\\"SessionToken\\\": \\\"$3\\\"\"\n    fi;\nfi;\nif [[ $# -ge 4 ]]; then\n    echo ','\n    echo \"\\\"Expiration\\\": \\\"$4\\\"\";\nfi;\necho '}';", "num_lines": 18}
{"repo_name": "aws-sdk-js-v3", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Set a command line alias to make running the dispatcher easier.\n\nalias b=\"node ./scripts/cli-dispatcher/index.js\"", "num_lines": 5}
{"repo_name": "aws-sdk-net", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho '{';\necho '\"Version\": 1,';\necho '\"AccessKeyId\": \"AccessKey\",';\necho '\"SecretAccessKey\": \"SecretKey\"';\nif [ $1 == 'Session' ]; then\n    echo ','\n    echo '\"SessionToken\": \"sessionToken\",';\n    echo '\"Expiration\": \"2018-12-11T17:46:28Z\"';\nfi;\necho '}';", "num_lines": 11}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nblack .\nruff --fix --select \"I001\" --select \"I002\" awswrangler", "num_lines": 5}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nversions=${1:-ALL}\nposargs=${2:-32}\nSECONDS=0\n\nset -e\n\nmkdir -p test-reports\ntox -e ${versions} -- ${posargs}\nif [ $versions = \"ALL\" ]; then\n    coverage html --directory coverage\n    rm -rf .coverage* Running 2> /dev/null\nfi\n\nduration=$SECONDS\necho \"$(($duration / 60)) minutes and $(($duration % 60)) seconds elapsed.\"\n", "num_lines": 17}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nblack --check .\nruff . --ignore \"PL\" --ignore \"D\"\nruff awswrangler\nmypy --install-types --non-interactive awswrangler\npylint -j 0 --disable=all --enable=R0911,R0912,R0913,R0915 awswrangler\ndoc8 --ignore-path docs/source/stubs --max-line-length 120 docs/source\npoetry lock --check\n", "num_lines": 11}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\npushd ..\nrm -rf docs/build docs/source/stubs\nmake -C docs/ html\ndoc8 --max-line-length 120 docs/source\n", "num_lines": 8}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nVERSION=$(poetry version --short)\nDIR_NAME=$(dirname \"$PWD\")\n\nARCH=$(arch)\n[ \"${ARCH}\" = \"aarch64\" ] && ARCH_SUFFIX=\"-arm64\" # AWS Lambda, the name arm64 is used instead of aarch64\n\necho \"Building Lambda Layers for AWS SDK for pandas ${VERSION}\"\n\npushd lambda\n\n# Building all related docker images\n./build-docker-images.sh\n\n# Python 3.8\ndocker run \\\n  --volume \"$DIR_NAME\":/aws-sdk-pandas/ \\\n  --workdir /aws-sdk-pandas/building/lambda \\\n  --rm \\\n  awswrangler-build-py38 \\\n  build-lambda-layer.sh \"${VERSION}-py3.8${ARCH_SUFFIX}\" \"ninja-build\"\n\n# Python 3.9\ndocker run \\\n  --volume \"$DIR_NAME\":/aws-sdk-pandas/ \\\n  --workdir /aws-sdk-pandas/building/lambda \\\n  --rm \\\n  awswrangler-build-py39 \\\n  build-lambda-layer.sh \"${VERSION}-py3.9${ARCH_SUFFIX}\" \"ninja-build\"\n\n# Python 3.10\ndocker run \\\n  --volume \"$DIR_NAME\":/aws-sdk-pandas/ \\\n  --workdir /aws-sdk-pandas/building/lambda \\\n  --rm \\\n  awswrangler-build-py310 \\\n  build-lambda-layer.sh \"${VERSION}-py3.10${ARCH_SUFFIX}\" \"ninja-build\"\n", "num_lines": 40}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\npushd ..\nrm -rf dist/*.whl\npoetry build -f wheel\n", "num_lines": 7}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\npushd ..\nrm -fr dist\npoetry publish --build\nrm -fr dist\n", "num_lines": 8}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\npushd ..\nrm -fr awswrangler.zip\n\n# Zip the library\ngit archive HEAD:awswrangler --format zip --prefix awswrangler/awswrangler/ --output awswrangler.zip\n\n# Upload the Zip file\ns3_location=$(aws cloudformation describe-stacks --stack-name aws-sdk-pandas-glueray --query \"Stacks[0].Outputs[?OutputKey=='AWSSDKforpandasZIPLocation'].OutputValue\" --output text)\naws s3 cp awswrangler.zip $s3_location\n\nrm -fr awswrangler.zip\n", "num_lines": 15}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\ncp ../../pyproject.toml .\ncp ../../poetry.lock .\n\nexport DOCKER_BUILDKIT=1\n\n# Python 3.8\ndocker build \\\n  --pull \\\n  --tag awswrangler-build-py38 \\\n  --build-arg base_image=public.ecr.aws/lambda/python:3.8 \\\n  .\n\n# Python 3.9\ndocker build \\\n  --pull \\\n  --tag awswrangler-build-py39 \\\n  --build-arg base_image=public.ecr.aws/lambda/python:3.9 \\\n  .\n\n# Python 3.10\ndocker build \\\n  --pull \\\n  --tag awswrangler-build-py310 \\\n  --build-arg base_image=public.ecr.aws/lambda/python:3.10 \\\n  .\n\nrm -rf pyproject.toml poetry.lock\n", "num_lines": 31}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\nFILENAME=\"awswrangler-layer-${1}.zip\"\nNINJA=${2}\n\npushd /aws-sdk-pandas\nrm -rf python dist/pyarrow_files \"dist/${FILENAME}\" \"${FILENAME}\"\npopd\n\nrm -rf dist arrow\n\nexport ARROW_HOME=$(pwd)/dist\nexport LD_LIBRARY_PATH=$(pwd)/dist/lib:$LD_LIBRARY_PATH\n\ngit clone \\\n  --depth 1 \\\n  --branch apache-arrow-10.0.0 \\\n  --single-branch \\\n  https://github.com/apache/arrow.git\n\nmkdir $ARROW_HOME\nmkdir arrow/cpp/build\npushd arrow/cpp/build\n\ncmake \\\n    -DCMAKE_INSTALL_PREFIX=$ARROW_HOME \\\n    -DCMAKE_INSTALL_LIBDIR=lib \\\n    -DARROW_PYTHON=ON \\\n    -DARROW_PARQUET=ON \\\n    -DARROW_DATASET=ON \\\n    -DARROW_WITH_SNAPPY=ON \\\n    -DARROW_WITH_ZLIB=ON \\\n    -DARROW_FLIGHT=OFF \\\n    -DARROW_GANDIVA=OFF \\\n    -DARROW_ORC=OFF \\\n    -DARROW_CSV=ON \\\n    -DARROW_JSON=ON \\\n    -DARROW_COMPUTE=ON \\\n    -DARROW_FILESYSTEM=ON \\\n    -DARROW_PLASMA=OFF \\\n    -DARROW_WITH_BZ2=OFF \\\n    -DARROW_WITH_ZSTD=OFF \\\n    -DARROW_WITH_LZ4=OFF \\\n    -DARROW_WITH_BROTLI=OFF \\\n    -DARROW_BUILD_TESTS=OFF \\\n    -GNinja \\\n    ..\n\neval $NINJA\neval \"${NINJA} install\"\n\npopd\n\npushd arrow/python\n\nexport CMAKE_PREFIX_PATH=${ARROW_HOME}${CMAKE_PREFIX_PATH:+:${CMAKE_PREFIX_PATH}}\nexport ARROW_PRE_0_15_IPC_FORMAT=0\nexport PYARROW_WITH_HDFS=0\nexport PYARROW_WITH_FLIGHT=0\nexport PYARROW_WITH_GANDIVA=0\nexport PYARROW_WITH_ORC=0\nexport PYARROW_WITH_CUDA=0\nexport PYARROW_WITH_PLASMA=0\nexport PYARROW_WITH_PARQUET=1\nexport PYARROW_WITH_DATASET=1\nexport PYARROW_WITH_FILESYSTEM=1\nexport PYARROW_WITH_CSV=1\nexport PYARROW_WITH_JSON=1\nexport PYARROW_WITH_COMPUTE=1\n\npython3 setup.py build_ext \\\n  --build-type=release \\\n  --bundle-arrow-cpp \\\n  bdist_wheel\n\npip3 install dist/pyarrow-*.whl -t /aws-sdk-pandas/dist/pyarrow_files\n\npopd\n\npushd /aws-sdk-pandas\n\npip3 install . -t ./python \".[redshift,mysql,postgres,gremlin,opensearch,openpyxl]\"\n\nrm -rf python/pyarrow*\nrm -rf python/boto*\n\nrm -f /aws-sdk-pandas/dist/pyarrow_files/pyarrow/libarrow.so\nrm -f /aws-sdk-pandas/dist/pyarrow_files/pyarrow/libparquet.so\nrm -f /aws-sdk-pandas/dist/pyarrow_files/pyarrow/libarrow_python.so\n\ncp -r /aws-sdk-pandas/dist/pyarrow_files/pyarrow* python/\n\n# Removing nonessential files\nfind python -name '*.so' -type f -exec strip \"{}\" \\;\nfind python -wholename \"*/tests/*\" -type f -delete\nfind python -regex '^.*\\(__pycache__\\|\\.py[co]\\)$' -delete\n\nzip -r9 \"${FILENAME}\" ./python\nmv \"${FILENAME}\" dist/\n\nrm -rf python dist/pyarrow_files \"${FILENAME}\"\n\npopd\n\nrm -rf dist arrow\n", "num_lines": 107}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nSTACK=${1}\n\npushd ..\ncdk destroy aws-sdk-pandas-${STACK}\npopd", "num_lines": 7}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nSTACK=${1}\n\npushd ..\ncdk bootstrap\ncdk deploy aws-sdk-pandas-${STACK}\npopd", "num_lines": 8}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n# Get my current IP address\nLOCALIP=`host myip.opendns.com resolver1.opendns.com | grep myip | awk '{print $4}'`\n\n# Get security group ID\nSGID=`aws cloudformation  describe-stacks --stack-name aws-sdk-pandas-databases --query \"Stacks[0].Outputs[?OutputKey=='DatabaseSecurityGroupId'].OutputValue\" --output text`\n\n# Update Security Group with local ip\naws ec2 authorize-security-group-ingress \\\n  --group-id ${SGID} \\\n  --protocol all \\\n  --port -1 \\\n  --cidr ${LOCALIP}/32\n", "num_lines": 16}
{"repo_name": "aws-sdk-pandas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n# Get security group ID\nSGID=`aws cloudformation  describe-stacks --stack-name aws-sdk-pandas-databases --query \"Stacks[0].Outputs[?OutputKey=='DatabaseSecurityGroupId'].OutputValue\" --output text`\n\n# Check to see current setting\naws ec2 describe-security-groups --group-id ${SGID}\n", "num_lines": 9}
{"repo_name": "aws-toolkit-azure-devops", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nDELETED_FIELDS=(\n    'metrics'\n    '_links'\n    'authoredBy'\n    'retentionRules'\n    'queue'\n    'triggers'\n    'tags'\n    'properties'\n    'url'\n    'uri'\n    'createdDate'\n    'project.id'\n    'project.url'\n    'project.revision'\n    'project.visability'\n    'repository.url'\n    'variables.bundleBucket'\n    'variables.bucketName'\n    'variables.bundleBucketName'\n    'variables.topicArn'\n    'variables.queueUrl'\n)\n\nwhich jq || ( echo \"jq is not installed, on OSX you can get this from 'brew install jq'\" && exit 1 )\n\necho \"This script cleans up exported tasks to remove undesirable fields\"\necho\necho \"it will be run on the following files:\"\nfor file in *.json;\ndo \n    echo ${file}\ndone\necho\n\nread -p \"Look over the list then press enter to continue, this will modify every .json file listed above!\"\nread -p \"Are you really sure?\"\n\nfor file in *.json;\ndo \n    echo \"fixing up file ${file}\"\n    OUTPUT=$(jq -M . $file)\n    for field in \"${DELETED_FIELDS[@]}\";\n    do \n        OUTPUT=$(jq -M \"del(.${field})\" <<< \"$OUTPUT\")\n    done\n    OUTPUT=$(jq . -M <<< \"$OUTPUT\")\n    echo $OUTPUT > $file\ndone\n\necho \"done\"\n", "num_lines": 54}
{"repo_name": "aws-toolkit-eclipse", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n## Install third-party dependencies to your local maven repository\nmvn -Pinstall-third-party-bundles clean install\n\n## Build development environment to be used as the target platform\nmvn -Pbuild-eclipse-devide package\n", "num_lines": 8}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: $0 </path/to/build.txt>\" >&2\n  exit 1\nfi\n\ncat \"$1\" | cut -d\"-\" -f2 | cut -d\".\" -f1\n", "num_lines": 9}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -eq 0 ] || [ \"$#\" -gt 2 ]; then\n  echo \"Usage: $0 <git repo> [git branch]\" >&2\n  exit 1\nfi\n\nset -x\ncd /projects\nPROJECT_DIR=$(basename $1 .git)\nif [ -d $PROJECT_DIR ]; then\n  cd $PROJECT_DIR\n  if [ ! -d \".git\" ]; then\n    git init && git remote add origin \"$1\" && git fetch origin && git remote set-head origin --auto\n    # use provided branch if available, else infer from remote\n    DEFAULT_BRANCH=${2:-$(basename $(git rev-parse --abbrev-ref origin/HEAD))}\n    git checkout -b \"$DEFAULT_BRANCH\" --track && git reset 'origin/'\"$DEFAULT_BRANCH\"\n  else\n    echo 'Skipping git clone since \"'$PROJECT_DIR'/.git\" already exists'\n  fi\nelse\n  # if branch was provided, pass along to clone command\n  git clone \"$1\" -v ${2:+--branch \"$2\"};\nfi\n", "num_lines": 25}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nname_value=''\nemail_value=''\n\nprint_usage() {\n  echo \"Usage: $0 [-n <name>] [-e <email>]\" >&2\n}\n\nwhile getopts ':n:e:' flag; do\n  case \"${flag}\" in\n    n) name_value=${OPTARG};;\n    e) email_value=${OPTARG};;\n    *) print_usage\n       exit 1 ;;\n  esac\ndone\n\nset -x\n\nif [ -n \"$name_value\" ]; then\n    git config --global 'user.name' \"$name_value\"\nfi\n\nif [ -n \"$email_value\" ]; then\n    git config --global 'user.email' \"$email_value\"\nfi\n", "num_lines": 28}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"Usage: $0 <id-runtime-dir> <plugin-url>\" >&2\n  exit 1\nfi\n\nset -x\npluginFile=\"$(mktemp -d)/plugin.zip\"\nmkdir -p \"$1\" && curl  -SL -o \"$pluginFile\" \"$2\" && unzip -oq \"$pluginFile\" -d \"$1/plugins\" && rm \"$pluginFile\"\n", "num_lines": 11}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: $0 <ssh-target>\" >&2\n  exit 1\nfi\n\nset -x\nmkdir -p ~/.ssh && (ssh-keygen -F \"$1\" || (ssh-keyscan \"$1\" >> \"$HOME\"/.ssh/known_hosts))\n", "num_lines": 10}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -ne 2 ]; then\n  echo \"Usage: $0 </path/to/remote-dev-server.sh> <project root>\" >&2\n  exit 1\nfi\n\nset -x\nset -o pipefail\n\nprojectRoot=$2\n\nif [ ! -d \"$projectRoot\" ]; then\n    echo \"$projectRoot does not exist, falling back to /projects\"\n    projectRoot='/projects'\nfi\n\n# retry if the backend exits under the threshold\nsecondsThreshold=20\nendTime=$(( $(date +%s) + secondsThreshold ))\nlastExit=0\n# date +%s is technically not POSIX, but the alternative is an obscure trick with awk that uses the fact that srand() is seeded with the epoch by default\nwhile [ \"$(date +%s)\" -lt \"$endTime\" ]\ndo\n  case \"$lastExit\" in\n    # 2: backend already open\n    # 7: backend expired\n    # 127: provided backend path was invalid\n    2|7|127) exit \"$lastExit\"\n  esac\n\n  echo \"Backend not available yet. Attempting to start\"\n  endTime=$(( $(date +%s) + secondsThreshold ))\n  nohup \"$1\" run \"$projectRoot\" | tee $HOME/start.log &\n  wait $!\n  lastExit=$?\n  sleep 3\ndone\n", "num_lines": 39}
{"repo_name": "aws-toolkit-jetbrains", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nwhile [ ! -f /proc/pid/$2 ] ;\ndo\n      sleep 2\ndone\n", "num_lines": 9}
{"repo_name": "aws-toolkit-vscode", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/env bash\n\n# By default, this script gets the latest VSIX from:\n#     https://github.com/aws/aws-toolkit-vscode/releases/\n# else the first argument must be a URL or file pointing to a toolkit VSIX or\n# ZIP (containing a VSIX).\n#\n# USAGE:\n#     cloud9-toolkit-install.sh [URL|FILE]\n#     curl -LO https://raw.githubusercontent.com/aws/aws-toolkit-vscode/master/cloud9-toolkit-install.sh && bash cloud9-toolkit-install.sh\n# EXAMPLES:\n#     cloud9-toolkit-install.sh https://github.com/aws/aws-toolkit-vscode/releases/download/v1.24.0/aws-toolkit-vscode-1.24.0.vsix\n#     cloud9-toolkit-install.sh toolkit.zip\n\nset -eu\n\n# Script currently depends on $HOME so running as root is not supported.\nif [ \"$(whoami)\" = root ]; then\n    echo \"cannot run as root\"\n    exit 1\nfi\n\n_log() {\n    echo >&2 \"$@\"\n}\n\n# Runs whatever is passed.\n#\n# On failure:\n#   - prints the command output\n#   - exits the script\n_run() {\n    local out\n    if ! out=\"$(\"$@\" 2>&1)\"; then\n        _log \"Command failed (output below): '${*}'\"\n        echo \"$out\" | sed 's/^/    /'\n        _log \"Command failed (output above): '${*}'\"\n        exit 1\n    fi\n}\n\n# Gets the first existing directory, or exits if none are found.\n_any_dir() {\n    for d in \"$@\"; do\n        if test -d \"$d\"; then\n            echo \"$d\"\n            return\n        fi\n    done\n\n    _log \"error: None of the expected dirs exist:\"\n    for d in \"$@\"; do\n        _log \"    $d\"\n    done\n    exit 1\n}\n\n_setglobals() {\n    # Example:\n    #     https://github.com/aws/aws-toolkit-vscode/releases/tag/v1.24.0\n    TOOLKIT_LATEST_RELEASE_URL=\"$(curl -Ls -o /dev/null -w '%{url_effective}' 'https://github.com/aws/aws-toolkit-vscode/releases/latest')\"\n    # Example:\n    #     1.24.0\n    TOOLKIT_LATEST_VERSION=\"$(echo \"$TOOLKIT_LATEST_RELEASE_URL\" | grep -oh '[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+$')\"\n    # Example:\n    #     https://github.com/aws/aws-toolkit-vscode/releases/download/v1.24.0/aws-toolkit-vscode-1.24.0.vsix\n    TOOLKIT_LATEST_ARTIFACT_URL=\"https://github.com/aws/aws-toolkit-vscode/releases/download/v${TOOLKIT_LATEST_VERSION}/aws-toolkit-vscode-${TOOLKIT_LATEST_VERSION}.vsix\"\n    # URL or local filepath pointing to toolkit VSIX or ZIP (containing a VSIX).\n    TOOLKIT_FILE=${1:-}\n    TOOLKIT_INSTALL_PARENT=\"$(_any_dir \"/projects/.c9/aws-toolkit-vscode\" \"$HOME/.c9/dependencies/aws-toolkit-vscode\" \"$HOME/environment/.c9/extensions\" \"$HOME/.c9/aws-toolkit-vscode\")\"\n    # Hash name is 128 chars long.\n    TOOLKIT_INSTALL_DIR=\"$(_any_dir \"$(realpath ${TOOLKIT_INSTALL_PARENT}/????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????)\" \"$(realpath ${TOOLKIT_INSTALL_PARENT}/extension)\")\"\n    SCRIPT_WORKDIR=\"$HOME/toolkit\"\n}\n\n_main() {\n    (\n        if test -f \"$TOOLKIT_FILE\"; then\n            # Ensure full path (before `cd` below).\n            TOOLKIT_FILE=\"$(readlink -f \"$TOOLKIT_FILE\")\"\n        fi\n\n        echo \"Script will DELETE these directories:\"\n        echo \"    ${TOOLKIT_INSTALL_DIR}\"\n        echo \"    ${SCRIPT_WORKDIR}\"\n        read -n1 -r -p \"ENTER to continue, CTRL-c to cancel\"\n        rm -rf \"${TOOLKIT_INSTALL_DIR}.old\"\n        mv \"$TOOLKIT_INSTALL_DIR\" \"${TOOLKIT_INSTALL_DIR}.old\"\n        rm -rf \"$SCRIPT_WORKDIR\"\n\n        cd \"$HOME/\"\n        mkdir -p \"$SCRIPT_WORKDIR\"\n        mkdir -p \"$TOOLKIT_INSTALL_PARENT\"\n        cd \"${SCRIPT_WORKDIR}\"\n\n        # Set default URL if no argument was provided.\n        if test -z \"$TOOLKIT_FILE\"; then\n            _log \"Latest release:\"\n            _log \"    URL    : $TOOLKIT_LATEST_RELEASE_URL\"\n            _log \"    version: $TOOLKIT_LATEST_VERSION\"\n            _log \"    VSIX   : $TOOLKIT_LATEST_ARTIFACT_URL\"\n            TOOLKIT_FILE=\"$TOOLKIT_LATEST_ARTIFACT_URL\"\n        fi\n\n        TOOLKIT_FILE_EXTENSION=\"${TOOLKIT_FILE: -4}\"\n        if test -f \"$TOOLKIT_FILE\"; then\n            _log \"Local file (not URL): ${TOOLKIT_FILE}\"\n            if [ \"$TOOLKIT_FILE_EXTENSION\" = \".zip\" ] || [ \"$TOOLKIT_FILE_EXTENSION\" = \".ZIP\" ]; then\n                _log 'File is a .zip file'\n                _run unzip -- \"$TOOLKIT_FILE\"\n                _run unzip -- *.vsix\n            else\n                _log 'File is not .zip file, assuming .vsix'\n                _run unzip -- \"$TOOLKIT_FILE\"\n            fi\n        else\n            _log \"URL: ${TOOLKIT_FILE}\"\n            _log 'Deleting toolkit.zip'\n            rm -rf toolkit.zip\n            _log 'Downloading...'\n            curl -o toolkit.zip -L \"$TOOLKIT_FILE\"\n            if [ \"$TOOLKIT_FILE_EXTENSION\" = \".zip\" ] || [ \"$TOOLKIT_FILE_EXTENSION\" = \".ZIP\" ]; then\n                _log 'File is a .zip file'\n                _run unzip -- toolkit.zip\n                _run unzip -- *.vsix\n            else\n                _log 'File is not .zip file, assuming .vsix'\n                _run unzip -- toolkit.zip\n            fi\n        fi\n\n        mv extension \"$TOOLKIT_INSTALL_DIR\"\n        _log \"Toolkit installed to: $TOOLKIT_INSTALL_DIR\"\n        _log \"Refresh Cloud9 to load it\"\n    )\n}\n\n_setglobals \"$@\"\n_main\n", "num_lines": 140}
{"repo_name": "aws-toolkit-vscode", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/env bash\n\nset -e\n\ntest -n \"$GITHUB_READONLY_TOKEN\" || { echo 'missing $GITHUB_READONLY_TOKEN'; exit 1; }\n\n# Authenticate all \"git\" (and \"curl --netrc\") github calls, to avoid rate-limiting.\n# NOTE: the \"login\" value is arbitrary.\nprintf \"machine github.com         login oauth password ${GITHUB_READONLY_TOKEN:-unknown}\\n\" >> \"$HOME/.netrc\"\nprintf \"machine api.github.com     login oauth password ${GITHUB_READONLY_TOKEN:-unknown}\\n\" >> \"$HOME/.netrc\"\nprintf \"machine uploads.github.com login oauth password ${GITHUB_READONLY_TOKEN:-unknown}\\n\" >> \"$HOME/.netrc\"\n# Print ratelimit info.\n2>/dev/null curl --netrc -L -I https://api.github.com/ | grep x-ratelimit | sed 's/\\(.*\\)/    \\1/'\n# Validate ratelimit.\n2>/dev/null curl --netrc -L -I https://api.github.com/ | >/dev/null grep 'x-ratelimit-limit: *[0-9][0-9][0-9][0-9]\\+' || { echo 'invalid github token, or rate limit too low (expected 5000+)'; exit 1; }\n", "num_lines": 16}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "START_TIME=$(date +%s)\nHEX_TIME=$(printf '%x\\n' $START_TIME)\nGUID=$(dd if=/dev/random bs=12 count=1 2>/dev/null | od -An -tx1 | tr -d ' \\t\\n')\nTRACE_ID=\"1-$HEX_TIME-$GUID\"\nSEGMENT_ID=$(dd if=/dev/random bs=8 count=1 2>/dev/null | od -An -tx1 | tr -d ' \\t\\n')\nSEGMENT_DOC=\"{\\\"trace_id\\\": \\\"$TRACE_ID\\\", \\\"id\\\": \\\"$SEGMENT_ID\\\", \\\"start_time\\\": $START_TIME, \\\"in_progress\\\": true, \\\"name\\\": \\\"XRay-Daemon-Test\\\"}\"\nHEADER='{\"format\": \"json\", \"version\": 1}'\nTRACE_DATA=\"$HEADER\\n$SEGMENT_DOC\"\necho \"$HEADER\" > trace_document.txt\necho \"$SEGMENT_DOC\" >> trace_document.txt\n\necho \"TRACE_ID=$TRACE_ID\" >> $GITHUB_ENV\n", "num_lines": 13}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nBUILD_FOLDER=${TARGETPLATFORM/\\//-}\n\necho \"Building for platform ${TARGETPLATFORM}\"\n\nif [[ -d \"/workspace/build/xray-${BUILD_FOLDER}\" ]]; then\n  echo \"Copying prebuilt binary\"\n  cp /workspace/build/xray-${BUILD_FOLDER}/xray /workspace/\nelse\n  echo \"Building from source\"\n  CGO_ENABLED=0 GOOS=linux GOARCH=$(echo $TARGETPLATFORM | cut -d'/' -f2) go build -a -ldflags '-extldflags \"-static\"' -o /workspace/xray /workspace/cmd/tracing\nfi\n", "num_lines": 14}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\necho \"****************************************\"\necho \"Creating legacy artifacts for 3.x with older names\"\necho \"****************************************\"\n\ncd ${BGO_SPACE}/build/dist\n\necho \"Building and packaging legacy artifacts for Linux\"\ncp ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-amd64-${VERSION}.zip ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-3.x.zip\ncp ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-amd64-${VERSION}.rpm ${BGO_SPACE}/build/dist/aws-xray-daemon-3.x.rpm\ncp ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-amd64-${VERSION}.deb ${BGO_SPACE}/build/dist/aws-xray-daemon-3.x.deb\ncp ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-arm64-${VERSION}.rpm ${BGO_SPACE}/build/dist/aws-xray-daemon-arm64-3.x.rpm\ncp ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-arm64-${VERSION}.deb ${BGO_SPACE}/build/dist/aws-xray-daemon-arm64-3.x.deb\n\necho \"Building and packaging legacy artifacts for MacOS\"\nunzip -q -o aws-xray-daemon-macos-amd64-${VERSION}.zip\nmv xray xray_mac\nzip aws-xray-daemon-macos-3.x.zip xray_mac cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray_mac\n\necho \"Building and packaging legacy artifacts for Windows\"\nunzip -q -o aws-xray-daemon-windows-amd64-service-${VERSION}.zip\nmv xray_service.exe xray.exe\nzip aws-xray-daemon-windows-service-3.x.zip xray.exe cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray.exe\n\nunzip -q -o aws-xray-daemon-windows-amd64-${VERSION}.zip\nmv xray.exe xray_windows.exe\nzip aws-xray-daemon-windows-process-3.x.zip xray_windows.exe cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray_windows.exe\n\nrm cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\n", "num_lines": 36}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nVERSION=$1\n\necho \"****************************************\"\necho \"Creating major version packages for VERSION=${VERSION}\"\necho \"****************************************\"\n\n# Git SHA-1 hash for commits is 40 char long\nif [[ ${#VERSION} -eq 40 ]]\nthen\n  echo \"Since the version is a commit hash, the major version will be \\\"latest\\\".\"\n  MAJOR_VERSION=latest\nelse\n  IFS='.' read -ra PARTS <<< \"$VERSION\"\n  MAJOR_VERSION=${PARTS[0]}.x\n  echo \"This is a release version. Will create binaries with \\\"$MAJOR_VERSION\\\" suffix.\"\nfi\n\ncd ${BGO_SPACE}/build/dist\n\nfor filename in *; do\n  newFilename=\"${filename/$VERSION/$MAJOR_VERSION}\"\n  if [[ $newFilename != $filename ]]\n  then\n    cp $filename $newFilename\n  fi\ndone", "num_lines": 30}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"****************************************\"\necho \"GPG signing for daemon assets\"\necho \"****************************************\"\n\necho \"Starting gpg signing for zip files\"\nfor filename in build/dist/*; do\n  ext=\"${filename##*.}\"\n  if [ $ext == \"zip\" ]; then\n    gpg --output $filename.sig --detach-sig $filename\n  fi\ndone\necho \"Finished gpg signing for zip files\"\n\n\necho \"Starting GPG signing for rpm files\"\nrpm -qa gpg-pubkey\n\necho \"Create rpmmacros file\"\nrm ~/.rpmmacros\necho -e \"%_signature gpg\\n%_gpg_path ~/.gnupg\\n%_gpg_name AWS X-Ray\\n%_gpgbin /usr/bin/gpg\" >> ~/.rpmmacros\ncat ~/.rpmmacros\n\nfor filename in build/dist/*; do\n  ext=\"${filename##*.}\"\n  if [ $ext == \"rpm\" ]; then\n    rpmsign --addsign $filename\n  fi\ndone\necho \"Finished GPG signing for rpm files\"\n\necho \"Starting GPG signing for deb files\"\nfor filename in build/dist/*; do\n  ext=\"${filename##*.}\"\n  if [ $ext == \"deb\" ]; then\n    ar x $filename\n    cat debian-binary control.tar.gz data.tar.gz > /tmp/combined-contents\n    gpg -abs -o _gpgorigin /tmp/combined-contents\n    ar rc $filename _gpgorigin debian-binary control.tar.gz data.tar.gz\n    rm /tmp/combined-contents\n    rm control.tar.gz\n    rm data.tar.gz\n    rm debian-binary\n    rm _gpgorigin\n  fi\ndone\necho \"Finished GPG signing for deb files\"\n", "num_lines": 49}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nARCH=$1\n\necho \"****************************************\"\necho \"Creating deb file for Ubuntu Linux ${ARCH}\"\necho \"****************************************\"\n\necho \"Creating debian folders\"\n\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/etc/init/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/xray/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/var/lib/amazon/xray/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/lib/systemd/system/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/lintian/overrides/\nmkdir -p ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/\n\necho \"Copying application files\"\n\ncp ${BGO_SPACE}/build/xray-linux-${ARCH}/xray ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/bin/\ncp ${BGO_SPACE}/build/dist/cfg.yaml ${BGO_SPACE}/bin/debian_${ARCH}/debian/etc/amazon/xray/cfg.yaml\ncp ${BGO_SPACE}/Tool/src/packaging/debian/xray.conf ${BGO_SPACE}/bin/debian_${ARCH}/debian/etc/init/xray.conf\ncp ${BGO_SPACE}/Tool/src/packaging/debian/xray.service ${BGO_SPACE}/bin/debian_${ARCH}/debian/lib/systemd/system/xray.service\n\necho \"Copying debian package config files\"\n\ncp ${BGO_SPACE}/Tool/src/packaging/debian/conffiles ${BGO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${BGO_SPACE}/Tool/src/packaging/debian/preinst ${BGO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${BGO_SPACE}/Tool/src/packaging/debian/postinst ${BGO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${BGO_SPACE}/Tool/src/packaging/debian/prerm ${BGO_SPACE}/bin/debian_${ARCH}/debian/\ncp ${BGO_SPACE}/Tool/src/packaging/debian/lintian-overrides ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/lintian/overrides/xray\n\necho \"Constructing the control file\"\n\necho \"Package: xray\" > ${BGO_SPACE}/bin/debian_${ARCH}/debian/control\necho \"Architecture: ${ARCH}\" >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/control\necho -n \"Version: \" >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/control\necho $VERSION >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/control\ncat ${BGO_SPACE}/Tool/src/packaging/debian/control >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/control\n\necho \"Constructing the copyright file\"\ncat ${BGO_SPACE}/LICENSE >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/copyright\necho \"\\n ======================== \\n\" >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/copyright\ncat ${BGO_SPACE}/THIRD-PARTY-LICENSES.txt >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/copyright\n\necho \"Constructing the changelog file\"\n\necho -n \"xray (\" > ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog\necho $VERSION >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog\necho \"-1) precise-proposed; urgency=low\" >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog\ncat ${BGO_SPACE}/Tool/src/packaging/debian/changelog >> ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog\n\ncp ${BGO_SPACE}/Tool/src/packaging/debian/changelog.Debian ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/\ncp ${BGO_SPACE}/Tool/src/packaging/debian/debian-binary ${BGO_SPACE}/bin/debian_${ARCH}/debian/\n\necho \"Setting permissioning as required by debian\"\n\ncd ${BGO_SPACE}/bin/debian_${ARCH}/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog\"\n\ncd ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\ncd ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/; export GZIP=-9; tar cvzf changelog.Debian.gz changelog.Debian --owner=0 --group=0; cd ~-\n\nrm ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog\nrm ${BGO_SPACE}/bin/debian_${ARCH}/debian/usr/share/doc/xray/changelog.Debian\n\necho \"Creating tar\"\n# the below permission is required by debian\ncd ${BGO_SPACE}/bin/debian_${ARCH}/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${BGO_SPACE}/bin/debian_${ARCH}/debian/; tar czf control.tar.gz control conffiles preinst postinst prerm copyright --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package\"\nar r ${BGO_SPACE}/bin/xray.deb ${BGO_SPACE}/bin/debian_${ARCH}/debian/debian-binary\nar r ${BGO_SPACE}/bin/xray.deb ${BGO_SPACE}/bin/debian_${ARCH}/debian/control.tar.gz\nar r ${BGO_SPACE}/bin/xray.deb ${BGO_SPACE}/bin/debian_${ARCH}/debian/data.tar.gz\ncp ${BGO_SPACE}/bin/xray.deb ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-${ARCH}-${VERSION}.deb\n", "num_lines": 79}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nARCH=$1\nif [[ $ARCH == \"amd64\" ]]\nthen\n    BUILD_ARCH=x86_64\nelif [[ $ARCH == \"arm64\" ]]\nthen\n    BUILD_ARCH=aarch64\nelse\n    echo \"Invalid architecture input. Exiting\"\n    exit 1\nfi\n\necho \"*************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL ${ARCH}\"\necho \"*************************************************\"\n\nrm -rf ${BGO_SPACE}/bin/linux_${ARCH}/linux\n\necho \"Creating rpmbuild workspace\"\nmkdir -p ${BGO_SPACE}/bin/linux_${ARCH}/linux/rpmbuild/{RPMS,SRPMS,BUILD,COORD_SOURCES,SPECS,DATA_SOURCES}\nmkdir -p ${BGO_SPACE}/bin/linux_${ARCH}/linux/usr/bin/\nmkdir -p ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/amazon/xray/\nmkdir -p ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/init/\nmkdir -p ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/systemd/system/\n\necho \"Copying application files\"\ncp ${BGO_SPACE}/build/xray-linux-${ARCH}/xray ${BGO_SPACE}/bin/linux_${ARCH}/linux/usr/bin/\ncp ${BGO_SPACE}/pkg/cfg.yaml ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/amazon/xray/cfg.yaml\ncp ${BGO_SPACE}/Tool/src/packaging/linux/xray.conf ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/init/\ncp ${BGO_SPACE}/Tool/src/packaging/linux/xray.service ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/systemd/system/\ncp ${BGO_SPACE}/LICENSE ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/amazon/xray/\ncp ${BGO_SPACE}/THIRD-PARTY-LICENSES.txt ${BGO_SPACE}/bin/linux_${ARCH}/linux/etc/amazon/xray/\n\necho \"Creating the rpm package\"\nSPEC_FILE=\"${BGO_SPACE}/Tool/src/packaging/linux/xray.spec\"\nBUILD_ROOT=\"${BGO_SPACE}/bin/linux_${ARCH}/linux\"\nrpmbuild --target ${BUILD_ARCH}-linux --define \"rpmversion ${VERSION}\" --define \"_topdir bin/linux_${ARCH}/linux/rpmbuild\" -bb --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\ncp ${BGO_SPACE}/bin/linux_${ARCH}/linux/rpmbuild/RPMS/${BUILD_ARCH}/*.rpm ${BGO_SPACE}/build/dist/aws-xray-daemon-linux-${ARCH}-${VERSION}.rpm\n", "num_lines": 45}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Linux amd64 and arm64\"\necho \"****************************************\"\n\nDIST_FOLDER=${BGO_SPACE}/build/dist/\ncd $DIST_FOLDER\n\ncp ../xray-linux-amd64/xray xray\nzip aws-xray-daemon-linux-amd64-${VERSION}.zip xray cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray\n\ncp ../xray-linux-arm64/xray xray\nzip aws-xray-daemon-linux-arm64-${VERSION}.zip xray cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray", "num_lines": 15}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for OS-X amd64\"\necho \"****************************************\"\n\nDIST_FOLDER=${BGO_SPACE}/build/dist/\ncd $DIST_FOLDER\n\ncp ../xray-mac-amd64/xray xray\nzip aws-xray-daemon-macos-amd64-${VERSION}.zip xray cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray\n\ncp ../xray-mac-arm64/xray xray\nzip aws-xray-daemon-macos-arm64-${VERSION}.zip xray cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray\n", "num_lines": 16}
{"repo_name": "aws-xray-daemon", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows amd64\"\necho \"****************************************\"\n\nDIST_FOLDER=${BGO_SPACE}/build/dist/\ncd $DIST_FOLDER\n\ncp ../xray-windows-amd64/xray_service.exe xray_service.exe\nzip aws-xray-daemon-windows-amd64-service-${VERSION}.zip xray_service.exe cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray_service.exe\n\ncp ../xray-windows-amd64/xray.exe xray.exe\nzip aws-xray-daemon-windows-amd64-${VERSION}.zip xray.exe cfg.yaml LICENSE THIRD-PARTY-LICENSES.txt\nrm xray.exe\n", "num_lines": 16}
{"repo_name": "aws-xray-java-agent", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ \"$1\" = \"\" ]; then\n  echo \"Must provide a version number argument, e.g. 2.7.x\"\n  exit 0\nfi\n\necho \"**************************************\"\necho \"Starting Baseline Benchmarks\"\necho \"**************************************\"\n\n./gradlew clean jmh --stacktrace\n\necho \"**************************************\"\necho \"Starting SDK Benchmarks\"\necho \"**************************************\"\n\n./gradlew jmh -Psdk --stacktrace\n\necho \"**************************************\"\necho \"Starting SDK Benchmarks\"\necho \"**************************************\"\n\n./gradlew jmh -Pagent -x test --stacktrace  # We don't care about agent integ tests here\n\necho \"**************************************\"\necho \"Finished all benchmarks\"\necho \"**************************************\"\n\nmkdir -p \"aws-xray-agent-benchmark/results/$1\"\ncp -Rf aws-xray-agent-benchmark/build/reports/jmh/ \"aws-xray-agent-benchmark/results/$1\"\ngit add aws-xray-agent-benchmark/results\n\necho \"Inspect the results in aws-xray-agent-benchmark/results/$1 then commit!\"\n", "num_lines": 35}
{"repo_name": "aws-xray-sdk-node", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n## This script copies a file provided as the first parameter into the destination directory\n## provided by the second parameter, while maintaining the directory structure of the source\n## file. It is similar to 'cp --parents' on Linux, but usable cross-platform\nsrc=(${*: 1})\ndest=${*: -1:1}\nfor filename in $src; do\n  [ -e \"$filename\" ] || continue\n  dirPath=$(dirname \"${filename}\")\n  mkdir -p $dest/$dirPath\n  cp -a $filename $dest/$dirPath\ndone\n", "num_lines": 14}
{"repo_name": "c3r", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nif [ \"$#\" -ne 1 ]; then\n    echo \"Expected a top-level directory name for unsigned artifacts.\"\n    exit 1\nfi\n\nif [[ -z \"$C3R_ALL_Y_TEST_COLLABORATION\" ]]; then\n    echo \"Expected env var C3R_ALL_Y_TEST_COLLABORATION to be set\"\n    echo \"to a collaboration ID where all cryptographic parameters\"\n    echo \"are set to 'Yes'.\"\n    exit 1\nfi\n\nif [[ -z \"$C3R_ALL_N_TEST_COLLABORATION\" ]]; then\n    echo \"Expected env var C3R_ALL_N_TEST_COLLABORATION to be set\"\n    echo \"to a collaboration ID where all cryptographic parameters\"\n    echo \"are set to 'No'.\"\n    exit 1\nfi\n\nARTIFACT_DIR=$1\n\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\npushd $SCRIPT_DIR/.. > /dev/null\n\nC3R_CLI_DIR=c3r-cli/build/libs\nC3R_CLI_SPARK_DIR=c3r-cli-spark/build/libs\n\n# Build everything\n./gradlew build -x checkFileUtilTest --parallel\n\n# Get the version from the CLI\nC3R_VERSION=$(java -jar $C3R_CLI_DIR/c3r-cli-all.jar --version)\necho \"JAR version found: $C3R_VERSION\"\n\n# Test CLI JAR\npython3 c3r-cli/src/integration-test/integration_tests.py \\\n  --id-y $C3R_ALL_Y_TEST_COLLABORATION \\\n  --id-n $C3R_ALL_N_TEST_COLLABORATION \\\n  $C3R_CLI_DIR/c3r-cli-all.jar\n\n# Test CLI Spark JAR\npython3 c3r-cli-spark/src/integration-test/spark_integration_tests.py \\\n  --id-y $C3R_ALL_Y_TEST_COLLABORATION \\\n  --id-n $C3R_ALL_N_TEST_COLLABORATION \\\n  $C3R_CLI_SPARK_DIR/c3r-cli-spark-all.jar\n\n\nmkdir -p $ARTIFACT_DIR\n\n# Move CLI jar to the artifact directory\nmv $C3R_CLI_DIR/c3r-cli-all.jar $ARTIFACT_DIR/c3r-cli-$C3R_VERSION.jar\nmv $C3R_CLI_SPARK_DIR/c3r-cli-spark-all.jar $ARTIFACT_DIR/c3r-cli-spark-$C3R_VERSION.jar\n\n# Given an SDK project name, collect it's JAR, javadocs JAR, and sources JAR\n# and move them to the artifact directory with a version number applied\nfunction move_sdk_jars() {\n    local sdk_name=$1\n    local sdk_jar_dir=$sdk_name/build/libs\n    # Move sdk JARs to the artifact directory\n    mv $sdk_jar_dir/$sdk_name.jar $ARTIFACT_DIR/$sdk_name-$C3R_VERSION.jar\n    mv $sdk_jar_dir/$sdk_name-javadoc.jar $ARTIFACT_DIR/$sdk_name-javadoc-$C3R_VERSION.jar\n    mv $sdk_jar_dir/$sdk_name-sources.jar $ARTIFACT_DIR/$sdk_name-sources-$C3R_VERSION.jar\n}\n\n# Move sdk JARs to the artifact directory\nmove_sdk_jars c3r-sdk-core\nmove_sdk_jars c3r-sdk-parquet\n\necho \"JAR files tagged with version $C3R_VERSION and placed in $ARTIFACT_DIR/\"\n\npopd > /dev/null # $SCRIPT_DIR/..\n", "num_lines": 77}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_adc_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_adc_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ ! -z $1 ]; then\n    #Set dac output voltage\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_adc_rp3.py $1\"\nfi\n", "num_lines": 43}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\n# This is a shell script to secure copy the GPIO_RP3 to RP3\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_gpio_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_gpio_rp3.py ${LOGINID}@${IP}:/home/pi/Tests/\nelif [ \"$1\" == \"-w\" ]; then\n\n    #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to read the GPIO pin status\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_gpio_rp3.py -i $2 > /home/pi/Tests/gpio_rpi_res.txt\"\n\n    #Copy the GPIO pin status to host for validation\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/gpio_rpi_res.txt ${DIR}\n\nelif [ \"$1\" == \"-r\" ]; then\n    #Open a SSH connection to RP3 and run the test_iot_gpio_rp3.py to set the GPIO pin output\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_gpio_rp3.py -o $2\"\n\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/gpio_rpi_res.txt\"\nfi\n\nexit 0\n", "num_lines": 57}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_adc_rp3.py from Host to RP3\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"mkdir -p /home/pi/Tests\"\n    sshpass -p \"$PASSWD\" scp ${DIR}/test_iot_i2c_master_rp3.py \"$LOGINID\"@\"$IP\":/home/pi/Tests\nelif [ \"$1\" == \"-s\" ]; then\n    #Run demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'\n    sleep .1\n    #Run rpi script\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"python /home/pi/Tests/test_iot_i2c_master_rp3.py\"\n    #Kill demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"sudo killall pigpiod\"\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p \"$PASSWD\" ssh \"$LOGINID\"@\"$IP\" \"rm /home/pi/Tests/i2c_master_res.txt\"\nfi", "num_lines": 49}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_read_PWM.py and test_iot_wave_PWM.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_pwm_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    #Delete the result file on rpi\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/pwm_rpi_res.txt\"\nelse\n    #Run demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo pigpiod -s 1 -b 200'\n    #Run two pwm scripts at same time\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'python /home/pi/Tests/test_iot_pwm_rp3.py > /home/pi/Tests/pwm_rpi_res.txt'\n    #Kill demon\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} 'sudo killall pigpiod'\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/pwm_rpi_res.txt ${DIR}\nfi\n", "num_lines": 54}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nif [ \"$1\" == \"-t\" ]; then\n  for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do\n      (\n          syspath=\"${sysdevpath%/dev}\"\n          devname=\"$(udevadm info -q name -p $syspath)\"\n          [[ \"$devname\" == \"bus/\"* ]] && continue\n          eval \"$(udevadm info -q property --export -p $syspath)\"\n          [[ (-z \"$ID_SERIAL\") || (\"$ID_SERIAL\" != *\"MicroPython\"*)]] && continue\n          echo \"/dev/$devname\"\n          break\n      )\n  done\nfi\n", "num_lines": 41}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of\n# this software and associated documentation files (the \"Software\"), to deal in\n# the Software without restriction, including without limitation the rights to\n# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so,\n# subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy test script from Host ubuntu to RP3\n    sshpass -p \"${PASSWD}\" ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p \"${PASSWD}\" scp ${DIR}/test_iot_tsensor_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    #Delete the result file on rpi\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/tsensor_rpi_res.txt\"\nelse\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python /home/pi/Tests/test_iot_tsensor_rp3.py > /home/pi/Tests/tsensor_rpi_res.txt\"\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/tsensor_rpi_res.txt ${DIR}\nfi\n", "num_lines": 47}
{"repo_name": "common-io-basic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# FreeRTOS Common IO V0.1.2\n# Copyright (C) 2020 Amazon.com, Inc. or its affiliates.  All Rights Reserved.\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# http://aws.amazon.com/freertos\n# http://www.FreeRTOS.org\n\n\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\nIP=$1\nshift\nLOGINID=$1\nshift\nPASSWD=$1\nshift\n\nif [ \"$1\" == \"-p\" ]; then\n    #Secure copy the test_iot_uart_rp3.py from Host to RP3\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"mkdir -p /home/pi/Tests\"\n    sshpass -p ${PASSWD} scp ${DIR}/test_iot_uart_rp3.py ${LOGINID}@${IP}:/home/pi/Tests\nelif [ \"$1\" == \"-c\" ]; then\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"rm /home/pi/Tests/uart_res.txt\"\nelse\n    sshpass -p ${PASSWD} ssh ${LOGINID}@${IP} \"python3 /home/pi/Tests/test_iot_uart_rp3.py $1 > /home/pi/Tests/uart_res.txt\"\n    #Copy back result\n    sshpass -p ${PASSWD} scp ${LOGINID}@${IP}:/home/pi/Tests/uart_res.txt ${DIR}\nfi\n", "num_lines": 46}
{"repo_name": "constructs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# verifies that the package does not introduce breaking changes to APIs\n# against the currently published version.\nset -euo pipefail\nscript_dir=\"$(cd $(dirname $0) && pwd)\"\npackage_name=$(node -p \"require('./package.json').name\")\nexec npx jsii-diff --keys npm:${package_name}\n", "num_lines": 8}
{"repo_name": "constructs", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Creates a symlink under node_modules of a package consuming this library\n# that replaces the version from NPM with this local version.\n# Helpful when developing a project that depends on this library\n# (like the AWS CDK),\n# and needing to do some changes in this package -\n# you can test your changes on a real consumer of this library.\n#\n# Usage:\n#   cd my/project/that/uses/constructs/library\n#   /path/to/source/of/constructs/scripts/link.sh\n\nset -euo pipefail\n\n# we are in scripts/, so the root is one level up\nroot=\"$(cd $(dirname $0)/.. && pwd)\"\nmkdir -p node_modules # -p makes mkdir not fail if the directory already exists\ndest=node_modules/constructs\n\necho \"Linking: '${root}' to '${dest}'\"\nrm -fr ${dest}\n# since root is a directory, node_modules needs to be the destination\nln -fs ${root} node_modules\n", "num_lines": 25}
{"repo_name": "containers-roadmap", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\n\nusage() {\n    cat <<EOF\nGenerate certificate suitable for use with an sidecar-injector webhook service.\n\nThis script uses k8s' CertificateSigningRequest API to a generate a\ncertificate signed by k8s CA suitable for use with sidecar-injector webhook\nservices. This requires permissions to create and approve CSR. See\nhttps://kubernetes.io/docs/tasks/tls/managing-tls-in-a-cluster for\ndetailed explantion and additional instructions.\n\nThe server key/cert k8s CA cert are stored in a k8s secret.\n\nusage: ${0} [OPTIONS]\n\nThe following flags are required.\n\n       --service          Service name of webhook.\n       --namespace        Namespace where webhook service and secret reside.\n       --secret           Secret name for CA certificate and server certificate/key pair.\nEOF\n    exit 1\n}\n\nwhile [[ $# -gt 0 ]]; do\n    case ${1} in\n        --service)\n            service=\"$2\"\n            shift\n            ;;\n        --secret)\n            secret=\"$2\"\n            shift\n            ;;\n        --namespace)\n            namespace=\"$2\"\n            shift\n            ;;\n        *)\n            usage\n            ;;\n    esac\n    shift\ndone\n\n[ -z ${service} ] && service=vpc-admission-webhook-svc\n[ -z ${secret} ] && secret=vpc-admission-webhook-certs\n[ -z ${namespace} ] && namespace=default\n\nif [ ! -x \"$(command -v openssl)\" ]; then\n    echo \"openssl not found\"\n    exit 1\nfi\n\ncsrName=${service}.${namespace}\ntmpdir=$(mktemp -d)\necho \"creating certs in tmpdir ${tmpdir} \"\n\ncat <<EOF >> ${tmpdir}/csr.conf\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nDNS.1 = ${service}\nDNS.2 = ${service}.${namespace}\nDNS.3 = ${service}.${namespace}.svc\nEOF\n\nopenssl genrsa -out ${tmpdir}/server-key.pem 2048\nopenssl req -new -key ${tmpdir}/server-key.pem -subj \"/CN=${service}.${namespace}.svc\" -out ${tmpdir}/server.csr -config ${tmpdir}/csr.conf\n\n# clean-up any previously created CSR for our service. Ignore errors if not present.\nkubectl delete csr ${csrName} 2>/dev/null || true\n\n# create  server cert/key CSR and  send to k8s API\ncat <<EOF | kubectl create -f -\napiVersion: certificates.k8s.io/v1beta1\nkind: CertificateSigningRequest\nmetadata:\n  name: ${csrName}\nspec:\n  groups:\n  - system:authenticated\n  request: $(cat ${tmpdir}/server.csr | base64 | tr -d '\\n')\n  usages:\n  - digital signature\n  - key encipherment\n  - server auth\nEOF\n\n# verify CSR has been created\nwhile true; do\n    kubectl get csr ${csrName}\n    if [ \"$?\" -eq 0 ]; then\n        break\n    fi\ndone\n\n# approve and fetch the signed certificate\nkubectl certificate approve ${csrName}\n# verify certificate has been signed\nfor x in $(seq 10); do\n    serverCert=$(kubectl get csr ${csrName} -o jsonpath='{.status.certificate}')\n    if [[ ${serverCert} != '' ]]; then\n        break\n    fi\n    sleep 1\ndone\nif [[ ${serverCert} == '' ]]; then\n    echo \"ERROR: After approving csr ${csrName}, the signed certificate did not appear on the resource. Giving up after 10 attempts.\" >&2\n    exit 1\nfi\necho ${serverCert} | openssl base64 -d -A -out ${tmpdir}/server-cert.pem\n\n\n# create the secret with CA cert and server cert/key\nkubectl create secret generic ${secret} \\\n        --from-file=key.pem=${tmpdir}/server-key.pem \\\n        --from-file=cert.pem=${tmpdir}/server-cert.pem \\\n        --dry-run -o yaml |\n    kubectl -n ${namespace} apply -f -\n", "num_lines": 144}
{"repo_name": "containers-roadmap", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You may\n# not use this file except in compliance with the License. A copy of the\n# License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nROOT=$(cd $(dirname $0)/../../; pwd)\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nexport CA_BUNDLE=$(kubectl config view --raw -o json --minify | jq -r '.clusters[0].cluster.\"certificate-authority-data\"' | tr -d '\"')\n\nif command -v envsubst >/dev/null 2>&1; then\n    envsubst\nelse\n    sed -e \"s|\\${CA_BUNDLE}|${CA_BUNDLE}|g\"\nfi\n", "num_lines": 29}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n# Start dockerd\n/usr/local/bin/dockerd \\\n\t--host=unix:///var/run/docker.sock \\\n\t--host=tcp://127.0.0.1:2375 \\\n\t--storage-driver=overlay2 &>/var/log/docker.log &\n\n# Wait until dockerd is spun up\ntries=0\nd_timeout=60\nuntil docker info >/dev/null 2>&1\ndo\n\tif [ \"$tries\" -gt \"$d_timeout\" ]; then\n                cat /var/log/docker.log\n\t\techo 'Timed out trying to connect to internal docker host.' >&2\n\t\texit 1\n\tfi\n        tries=$(( $tries + 1 ))\n\tsleep 1\ndone\n\necho $DOCKERHUB_TOKEN | docker login --password-stdin -u $DOCKERHUB_USERNAME\n\n#Run all the e2e tests\ncd /github.com/aws/copilot-cli/e2e/$TEST_SUITE && /go/bin/ginkgo -v -r --timeout=1h30m --fail-fast", "num_lines": 26}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\necho \"e2e success: job running\"\ncurl http://front-end.$COPILOT_SERVICE_DISCOVERY_ENDPOINT/job-setter/\n", "num_lines": 5}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env sh\nset -eu\n\nenvsubst '${NGINX_PORT}' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf\n\nexec \"$@\"", "num_lines": 6}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/sh\n\n[ -z \"$STATUS\" ] && STATUS=\"NOT OVERRIDDEN\"\n\nsleep 20\n\nfor i in 1 2 3 4 5 6 7 8; do\n    echo \"e2e environment variables: $STATUS\"\n    sleep 3\ndone\n", "num_lines": 11}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\necho \"e2e success: job running\"\ncurl http://front-end.$COPILOT_SERVICE_DISCOVERY_ENDPOINT/job-setter/\n", "num_lines": 5}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\necho \"e2e success: job running\"\ncurl http://front-end.$COPILOT_SERVICE_DISCOVERY_ENDPOINT/oraoraora-setter/\n", "num_lines": 5}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /usr/bin/env python3\nimport subprocess\nimport sys\n\ncmd = subprocess.run(['aws', 'configure', 'list-profiles'], stdout=subprocess.PIPE)\nprofiles = cmd.stdout.decode('utf-8').split('\\n')\n\nif len(sys.argv) < 2:\n  sys.exit('no arg passed to script, must be one of: \"e2e\" or \"regression\"')\n\nif sys.argv[1] == \"e2e\":\n  requiredProfiles = ['e2etestenv', 'e2eprodenv']\nelif sys.argv[1] == \"regression\":\n  requiredProfiles = ['regression']\nelse:\n  sys.exit('invalid arg passed to script, must be one of: \"e2e\" or \"regression\"')\n\nfor profile in requiredProfiles:\n  if profile in profiles:\n    continue\n  print(f'Profile [{profile}] is required but does not exist. Copying your [default] access key id and secret key...')\n  cmd = subprocess.run(['aws', 'configure', 'get', 'default.region'], stdout=subprocess.PIPE)\n  region = cmd.stdout.decode('utf-8').strip()\n  cmd = subprocess.run(['aws', 'configure', 'get', 'default.aws_access_key_id'], stdout=subprocess.PIPE)\n  access_key = cmd.stdout.decode('utf-8').strip()\n  cmd = subprocess.run(['aws', 'configure', 'get', 'default.aws_secret_access_key'], stdout=subprocess.PIPE)\n  secret = cmd.stdout.decode('utf-8').strip()\n  subprocess.run(['aws', 'configure', 'set', 'region', region, '--profile', profile])\n  subprocess.run(['aws', 'configure', 'set', 'aws_access_key_id', access_key, '--profile', profile])\n  subprocess.run(['aws', 'configure', 'set', 'aws_secret_access_key', secret, '--profile', profile])", "num_lines": 30}
{"repo_name": "copilot-cli", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n# license.sh checks that all Go files in the given correct-looking license header.\n\ncheck_header() {\n    got=$1\n    want=$(cat <<EOF\n// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\nEOF\n    )\n    if [[ \"$got\" = *\"$want\"* ]]; then\n        return 0\n    fi\n    return 1\n}\n\nif [ $# != 1 ]; then\n    echo \"Usage: $0 rootdir\" >&2\n    exit 1\nfi\n\nfail=0\nfor file in $(find $1 -regextype 'posix-extended' -regex '.*\\.(go|js)'); do\n    case $file in\n        $1/*/mocks/*)\n            # Skip mocks packages.\n        ;;\n        $1/*/mock_*.go)\n            # Skip mock files.\n        ;;\n        $1/*/node_modules/*)\n            # Skip node modules for js files.\n        ;;\n        $1/site/*)\n            # Skip website content\n        ;;\n        *)\n            header=\"$(head -10 $file)\"\n            if ! check_header \"$header\"; then\n                fail=1\n                echo \"${file#$1/} doesn't have the right copyright header:\"\n                echo \"$header\" | sed -e 's/^/    /g'\n            fi\n            ;;\n    esac\ndone\n\nif [ $fail -ne 0 ]; then\n    exit 1\nfi\n", "num_lines": 54}
{"repo_name": "credentials-fetcher", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\nfor((i=1; i <= 3 ; i++))\ndo   \n     service_account_name=\"WebApp${i}\"\n     domain_name=\"contoso\"\n\n     add_krb_msg=\"#######  Adding kerberos lease #######\"\n     echo ${add_krb_msg}\n\n     add_kerberos_lease=$(grpc_cli call unix:/var/credentials-fetcher/socket/credentials_fetcher.sock AddKerberosLease \"credspec_contents: '{\\\"CmsPlugins\\\":[\\\"ActiveDirectory\\\"],\\\"DomainJoinConfig\\\":{\\\"Sid\\\":\\\"S-1-5-21-4217655605-3681839426-3493040985\\\",\\\"MachineAccountName\\\":\\\"${service_account_name}\\\",\\\"Guid\\\":\\\"af602f85-d754-4eea-9fa8-fd76810485f1\\\",\\\"DnsTreeName\\\":\\\"${domain_name}.com\\\",\\\"DnsName\\\":\\\"${domain_name}.com\\\",\\\"NetBiosName\\\":\\\"${domain_name}\\\"},\\\"ActiveDirectoryConfig\\\":{\\\"GroupManagedServiceAccounts\\\":[{\\\"Name\\\":\\\"${service_account_name}\\\",\\\"Scope\\\":\\\"${domain_name}.com\\\"},{\\\"Name\\\":\\\"${service_account_name}\\\",\\\"Scope\\\":\\\"${domain_name}\\\"}]}}'\")\n\n   echo \"Add kerberos lease response: ${add_kerberos_lease}\"  \n   add_kerberos_lease_id=$(echo \"${add_kerberos_lease}\" | grep  'lease_id' | cut -f2 -d: | tr -d ' ' | tr -d '\\n')\n\n   echo \"Added kerberos ticket for lease_id: ${add_kerberos_lease_id}\"\n\n   delete_krb_msg=\"#######  Deleting kerberos lease #######\"\n   echo ${delete_krb_msg}\n   delete_kerberos_lease=$(grpc_cli call unix:/var/credentials-fetcher/socket/credentials_fetcher.sock DeleteKerberosLease \"lease_id: '${add_kerberos_lease_id}'\")\n\n   echo \"Delete kerberos tickets corresponding to lease: ${delete_kerberos_lease}\"\n\ndone\n", "num_lines": 26}
{"repo_name": "credentials-fetcher", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Thanks to https://github.com/dotnet/sdk/issues/8742#issuecomment-890559867\n\nDOTNET_CLI_TELEMETRY_OPTOUT=1\nexport DOTNET_CLI_TELEMETRY_OPTOUT\n\nsdkver=$(LC_ALL=C dotnet --version)\nfwkver=$(LC_ALL=C dotnet --list-runtimes | \\\n    LC_ALL=C sed --posix -n '/^Microsoft.NETCore.App \\([^ ]*\\) .*$/{s//\\1/p;q;}')\n\n# dotnet-sdk-5.0 installed via .deb package\ndotnethome=/usr/lib64/dotnet\ndotnetlib=$dotnethome/shared/Microsoft.NETCore.App/$fwkver\ndotnet_cscdll=$dotnethome/sdk/$sdkver/Roslyn/bincore/csc.dll\ndotnet_csclib='-r:netstandard.dll -r:Microsoft.CSharp.dll -r:System.dll'\nfor x in \"$dotnetlib\"/System.*.dll; do\n\tdotnet_csclib=\"$dotnet_csclib -r:${x##*/}\"\ndone\n# add if needed\n#dotnet_csclib=\"$dotnet_csclib -r:Microsoft.Win32.Primitives.dll\"\n\nexec dotnet \"$dotnet_cscdll\" \"-lib:$dotnetlib\" $dotnet_csclib \"$@\"\n\n#!/bin/sh\n\nDOTNET_CLI_TELEMETRY_OPTOUT=1\nexport DOTNET_CLI_TELEMETRY_OPTOUT\n\nsdkver=$(LC_ALL=C dotnet --version)\nfwkver=$(LC_ALL=C dotnet --list-runtimes | \\\n    LC_ALL=C sed --posix -n '/^Microsoft.NETCore.App \\([^ ]*\\) .*$/{s//\\1/p;q;}')\n\nexename=$1\ncase $exename in\n(*.exe|*.EXE) ;;\n(*)\n\techo >&2 \"E: $exename is not a .exe file\"\n\texit 1\n\t;;\nesac\n\njsonname=${exename%.*}.runtimeconfig.json\nprintf '%s\"%s\"%s\\n' \\\n    '{\"runtimeOptions\":{\"framework\":{\"name\":\"Microsoft.NETCore.App\",\"version\":' \\\n    \"$fwkver\" '}}}' >\"$jsonname\"\n", "num_lines": 47}
{"repo_name": "crypto-tools", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Verify that tests can be successfully run from the source build.\n#\n# NOTE: Humans should not run this file directly. If you want to run this check, run \"tox -e sourcebuildcheck\".\n\nWORKINGDIR=${1}\nDISTDIR=${2}\n\necho \"Performing source build check\"\necho \"Using working directory ${WORKINGDIR}\"\necho \"Using dist directory ${DISTDIR}\"\n\necho \"Locating the source build and copying it into the working directory.\"\nDISTFILE=`ls $DISTDIR/{{cookiecutter.pypi_name}}-*.tar.gz | tail -1`\necho \"Found source build at ${DISTFILE}\"\ncp ${DISTFILE} ${WORKINGDIR}\n\necho \"Extracting the source build.\"\ncd ${WORKINGDIR}\nNEWDISTFILE=$(ls {{cookiecutter.pypi_name}}-*.tar.gz | tail -1)\necho \"Using distfile ${NEWDISTFILE}\"\ntar xzvf ${NEWDISTFILE}\nrm ${NEWDISTFILE}\nEXTRACTEDDIR=$(ls | tail -1)\ncd ${EXTRACTEDDIR}\n\necho \"Installing requirements from extracted source build.\"\npip install -r test/requirements.txt\npip install -e .\n\necho \"Running tests from extracted source build.\"\npytest --cov {{cookiecutter.module_name}} -m local\n", "num_lines": 33}
{"repo_name": "dcv-color-primitives", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify,\n# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nwhile [[ \"$#\" -gt 0 ]]\ndo case $1 in\n    -c|--use-cycles) use_cycles=\"$2\"\n    shift;;\n    -f|--filter) filter=\"$2\"\nesac\nshift\ndone\n\nEXEC=`cargo bench --no-run 2>&1 | grep -oP benches-[0-9a-f]+`\nDIR=`pwd`\n\n# Drop file system cache\necho 3 | sudo tee /proc/sys/vm/drop_caches\nsudo sync\n\n# Disable address space randomization\necho 0 | sudo tee /proc/sys/kernel/randomize_va_space\n\nsudo rm -Rf ${DIR}/target/criterion\n\nsudo DCP_USE_CYCLES=${use_cycles} nice -n -5 taskset -c 0 ${DIR}/target/release/deps/${EXEC} --bench -n ${filter} | grep -i \"time:\\|thrpt:\"\n", "num_lines": 41}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EKS_CLUSTER_MANAGER_ROLE=<ARN-of-IAM-role>\n#/ export EKS_TEST_ROLE=<ARN-of-IAM-role>\n#/ ./add_iam_identity.sh eks_cluster_name\n\nset -ex\n\n# Function to add cluster manager IAM role to EKS cluster\nfunction add_cluster_manager_identity() {\n\n  eksctl create iamidentitymapping \\\n    --cluster ${1} \\\n    --arn ${2} \\\n    --group system:masters \\\n    --username cluster_manager\n\n  eksctl get iamidentitymapping \\\n    --cluster ${1}\n}\n\n# Function to add test IAM role to EKS cluster\nfunction add_test_build_role() {\n\n  eksctl create iamidentitymapping \\\n    --cluster ${1} \\\n    --arn ${2} \\\n    --username test-role\n\n  eksctl get iamidentitymapping \\\n    --cluster ${1}\n}\n\n# Function to create rbac rules for test role in EKS cluster\nfunction create_rbac_rules() {\n  kubectl create -f rbac.yaml\n}\n\n# Check for input arguments\nif [ $# -lt 1 ]; then\n  echo \"usage: ./${0} eks_cluster_name\"\n  exit 1\nfi\n\nCLUSTER=${1}\n\n# Check for IAM role environment variables\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ]; then\n  add_cluster_manager_identity ${CLUSTER} ${EKS_CLUSTER_MANAGER_ROLE}\nfi\n\n# Check for IAM role environment variables\nif [ -n \"${EKS_TEST_ROLE}\" ]; then\n  add_test_build_role ${CLUSTER} ${EKS_TEST_ROLE}\nfi\n\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ] && [ -n \"${EKS_TEST_ROLE}\" ]; then\n  create_rbac_rules\nfi\n", "num_lines": 61}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage: ./build.sh\n\nset -ex\n\n# Create operation function\n#\n# Invokes create_cluster.sh script to create EKS cluster nodegroups and namespaces.\n# Invokes add_iam_identity.sh script to create RBAC rules for test IAM role. Add cluster manager IAM role\n# and test IAM role authentication to the cluster.\n# Invokes install_cluster_components.sh script to install cluster autoscalar and kubeflow components in the cluster.\nfunction create_cluster() {\n\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n\n      if ! check_cluster_status $CLUSTER_NAME; then\n        ./create_cluster.sh $CLUSTER_NAME $EKS_VERSION\n        ./add_iam_identity.sh $CLUSTER_NAME\n        ./install_cluster_components.sh $CLUSTER_NAME $CLUSTER_AUTOSCALAR_IMAGE_VERSION\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: already exists. Skipping create operation.\"\n      fi\n    done\n  done\n}\n\n# Upgrade cluster operation function\n#\n# Invokes upgrade_operation.sh script to upgrade the EKS cluster in the following order\n# 1. Scale cluster autoscalar to 0 to prevent unwanted scaling\n# 2. Upgrade EKS control plane\n# 3. Upgrade EKS nodegroups:\n#    i) Delete Exisiting nodegroups\n#    ii) Create nodegroups with updated configuration\n# 4. Upgrade core k8s components\n# 5. Scale cluster autoscalar back to 1\nfunction upgrade_cluster() {\n  TARGET=\"CLUSTER\"\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n      if check_cluster_status $CLUSTER_NAME; then\n        ./upgrade_operation.sh $TARGET $CLUSTER_NAME $EKS_VERSION $CLUSTER_AUTOSCALAR_IMAGE_VERSION\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: does not exists. Skipping upgrade operation.\"\n      fi\n    done\n  done\n\n}\n\n# Upgrade nodegroup operation function\n#\n# Invokes upgrade_operation.sh script to upgrade the EKS nodegroup for a cluster\nfunction upgrade_nodegroup() {\n  TARGET=\"NODEGROUP\"\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n      if check_cluster_status $CLUSTER_NAME; then\n        ./upgrade_operation.sh $TARGET $CLUSTER_NAME $EKS_VERSION\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: does not exists. Skipping upgrade operation.\"\n      fi\n    done\n  done\n\n}\n\n# Upgrade kubeflow version\n#\n# Invokes upgrade_kubeflow script to upgrade kubeflow manifests on each EKS cluster\nfunction upgrade_kubeflow(){\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n      if check_cluster_status $CLUSTER_NAME; then\n        ./upgrade_kubeflow.sh $CLUSTER_NAME\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: does not exists. Skipping upgrade operation.\"\n      fi\n    done\n  done\n}\n\n# Delete operation function\n#\n# Invokes delete_cluster.sh script to delete EKS cluster, nodegroups and other related components\nfunction delete_cluster() {\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n      if check_cluster_status $CLUSTER_NAME; then\n        ./delete_cluster.sh $CLUSTER_NAME\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: does not exists. Skipping delete operation.\"\n      fi\n    done\n  done\n\n}\n\n# new operation function to perform one time operation on the cluster\n# Once deployed, the contents of the new_operation.sh should be moved to a dedicated script\n# to allow upcoming features to be configured in the new_operation.sh script\n# Invokes new_operation.sh script to add graviton nodegroup on the EKS cluster\nfunction new_operation() {\n\n  for CONTEXT in \"${CONTEXTS[@]}\"; do\n    for CLUSTER in \"${EKS_CLUSTERS[@]}\"; do\n      CLUSTER_NAME=${CLUSTER}-${CONTEXT}\n      if check_cluster_status $CLUSTER_NAME; then\n        ./new_operation.sh $CLUSTER_NAME $EKS_VERSION\n      else\n        echo \"EKS Cluster :: ${CLUSTER_NAME} :: does not exists. Skipping delete operation.\"\n      fi\n    done\n  done\n\n}\n\nfunction check_cluster_status() {\n  aws eks describe-cluster --name ${1} --region ${AWS_REGION} --query cluster.status --out text | grep -q ACTIVE\n}\n\n# Check for input arguments\nif [ -z \"$1\" ]; then\n  EKS_CLUSTERS=($(jq -r '.eks_clusters[]' build_param.json))\nelse\n  EKS_CLUSTERS=${1}-`date +%s`\nfi\n\nif [ -z \"$2\" ]; then\n  CONTEXTS=($(jq -r '.contexts[]' build_param.json))\nelse\n  CONTEXTS=${2}\nfi\n\n\n# Parse parameters from build_param.json config file\nOPERATION=$(jq -r '.operation' build_param.json)\nEKS_VERSION=$(jq -r '.eks_version' build_param.json)\nCLUSTER_AUTOSCALAR_IMAGE_VERSION=$(jq -r '.cluster_autoscalar_image_version' build_param.json)\n\n# Create a cluster if the context is predeploy and operation is other than create\nif [ \"${CONTEXTS}\" = \"BETA\" ] && [ \"${OPERATION}\" != \"create\" ]; then\n  echo \"Create a cluster inorder to perform operations other than creating cluster\"\n  create_cluster\nfi\n\n\ncase ${OPERATION} in\n\ncreate)\n  create_cluster\n  ;;\n\nupgrade_cluster)\n  upgrade_cluster\n  ;;\n\nupgrade_nodegroup)\n  upgrade_nodegroup\n  ;;\n  \nupgrade_kubeflow)\n  upgrade_kubeflow\n  ;;\n\ndelete)\n  delete_cluster\n  ;;\n\nnew_operation)\n  new_operation\n  ;;\n*)\n  echo \"Specify valid operation\"\n  ;;\nesac\n\n# Cleanup the EKS cluster if the context is BETA\nif [ \"${CONTEXT}\" = \"BETA\" ]; then\n  echo \"Delete the pre-deploy cluster\"\n  delete_cluster\nfi", "num_lines": 188}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EC2_KEY_PAIR_NAME=<EC2-Key-Pair-Name>\n#/ ./create_cluster.sh eks_cluster_name eks_version\n\nset -ex\n\n# Function to create EC2 key pair\nfunction create_ec2_key_pair() {\n  aws ec2 create-key-pair \\\n    --key-name ${1} \\\n    --query 'KeyMaterial' \\\n    --output text >./${1}.pem\n}\n\n# Function to create EKS cluster using eksctl.\n# The cluster name follows the dlc-{framework}-{build_context} convention\nfunction create_eks_cluster() {\n\n  if [ \"${3}\" = \"us-east-1\" ]; then\n    ZONE_LIST=(a b d)\n  else\n    ZONE_LIST=(a b c)\n  fi\n\n  eksctl create cluster \\\n    --name ${1} \\\n    --version ${2} \\\n    --zones=${3}${ZONE_LIST[0]},${3}${ZONE_LIST[1]},${3}${ZONE_LIST[2]} \\\n    --without-nodegroup\n}\n\n# Function to create static and dynamic nodegroups in EKS cluster\nfunction create_node_group() {\n\n  STATIC_NODEGROUP_INSTANCE_TYPE=\"m5.large\"\n  GPU_NODEGROUP_INSTANCE_TYPE=\"p3.16xlarge\"\n  INF_NODEGROUP_INSTANCE_TYPE=\"inf1.xlarge\"\n\n  # static nodegroup\n  eksctl create nodegroup \\\n    --name ${1}-static-nodegroup-${2/./-} \\\n    --cluster ${1} \\\n    --node-type ${STATIC_NODEGROUP_INSTANCE_TYPE} \\\n    --nodes 1 \\\n    --node-labels \"static=true\" \\\n    --tags \"k8s.io/cluster-autoscaler/node-template/label/static=true\" \\\n    --asg-access \\\n    --ssh-access \\\n    --ssh-public-key \"${3}\"\n\n  # dynamic gpu nodegroup\n  eksctl create nodegroup \\\n    --name ${1}-gpu-nodegroup-${2/./-} \\\n    --cluster ${1} \\\n    --node-type ${GPU_NODEGROUP_INSTANCE_TYPE} \\\n    --nodes-min 0 \\\n    --nodes-max 100 \\\n    --node-volume-size 80 \\\n    --node-labels \"test_type=gpu\" \\\n    --tags \"k8s.io/cluster-autoscaler/node-template/label/test_type=gpu\" \\\n    --asg-access \\\n    --ssh-access \\\n    --ssh-public-key \"${3}\"\n\n  # dynamic inf nodegroup\n  eksctl create nodegroup \\\n    --name ${1}-inf-nodegroup-${2/./-} \\\n    --cluster ${1} \\\n    --node-type ${INF_NODEGROUP_INSTANCE_TYPE} \\\n    --nodes-min 0 \\\n    --nodes-max 100 \\\n    --node-volume-size 500 \\\n    --node-labels \"test_type=inf\" \\\n    --tags \"k8s.io/cluster-autoscaler/node-template/label/test_type=inf,k8s.io/cluster-autoscaler/node-template/resources/aws.amazon.com/neuron=1,k8s.io/cluster-autoscaler/node-template/resources/hugepages-2Mi=256Mi\" \\\n    --asg-access \\\n    --ssh-access \\\n    --ssh-public-key \"${3}\"\n\n}\n\n# Attach IAM policy to nodegroup IAM role\nfunction add_iam_policy() {\n  NODE_GROUP_NAME=${1}\n  CLUSTER_NAME=${2}\n  REGION=${3}\n\n  ROLE_ARN=$(aws eks describe-nodegroup --nodegroup-name ${NODE_GROUP_NAME} --cluster-name ${CLUSTER_NAME} --region ${REGION} | jq -r '.nodegroup.nodeRole')\n  ROLE_NAME=$(echo ${ROLE_ARN} | grep -oP 'arn:aws:iam::\\d+:role/\\K\\S+')\n\n  declare -a POLICY_ARN=(\"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess\")\n\n  for policy in ${POLICY_ARN[@]}; do\n    aws iam attach-role-policy \\\n      --role-name $ROLE_NAME \\\n      --policy-arn $policy \\\n      --region ${REGION}\n  done\n\n}\n\n# Function to create namespaces in EKS cluster\nfunction create_namespaces() {\n  kubectl create -f namespace.yaml\n}\n\nfunction add_iam_permissions_nodegroup() {\n  CLUSTER_NAME=${1}\n  REGION=${2}\n  LIST_NODE_GROUPS=$(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region ${REGION} -o json | jq -r '.[].Name')\n\n  if [ -n \"${LIST_NODE_GROUPS}\" ]; then\n    for NODEGROUP in ${LIST_NODE_GROUPS}; do\n      add_iam_policy ${NODEGROUP} ${CLUSTER_NAME} ${REGION}\n    done\n  else\n    echo \"No Nodegroups present in the EKS cluster ${CLUSTER_NAME}\"\n  fi\n}\n\n#/ Tags added to the nodegroup do not propogate to the underlying Auto Scaling Group.\n#/ Hence adding the tags explicitly as it is required for cluster autoscalar functionality\n#/ See https://github.com/aws/containers-roadmap/issues/608\nfunction add_tags_asg() {\n\n  CLUSTER_NAME=${1}\n  REGION=${2}\n\n  for details in $(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region ${REGION} -o json | jq -c '.[]'); do\n    nodegroup_name=$(echo $details | jq -r '.Name')\n    asg_name=$(echo $details | jq -r '.AutoScalingGroupName')\n\n    if [[ ${nodegroup_name} == *\"gpu\"* ]]; then\n      aws autoscaling create-or-update-tags \\\n        --tags ResourceId=${asg_name},ResourceType=auto-scaling-group,Key=k8s.io/cluster-autoscaler/node-template/label/test_type,Value=gpu,PropagateAtLaunch=true\n    fi\n\n    if [[ ${nodegroup_name} == *\"inf\"* ]]; then\n      aws autoscaling create-or-update-tags \\\n        --tags ResourceId=${asg_name},ResourceType=auto-scaling-group,Key=k8s.io/cluster-autoscaler/node-template/label/test_type,Value=inf,PropagateAtLaunch=true \\\n        ResourceId=${asg_name},ResourceType=auto-scaling-group,Key=k8s.io/cluster-autoscaler/node-template/resources/aws.amazon.com/neuron,Value=1,PropagateAtLaunch=true \\\n        ResourceId=${asg_name},ResourceType=auto-scaling-group,Key=k8s.io/cluster-autoscaler/node-template/resources/hugepages-2Mi,Value=256Mi,PropagateAtLaunch=true\n    fi\n\n  done\n\n}\n\n# Check for input arguments\nif [ $# -ne 2 ]; then\n  echo \"usage: ./${0} eks_cluster_name eks_version\"\n  exit 1\nfi\n\n# Check for IAM role environment variables\nif [ -z \"${AWS_REGION}\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\nCLUSTER=${1}\nEKS_VERSION=${2}\n\n# Check for EC2 keypair environment variable. If empty, create a new key pair.\nif [ -z \"${EC2_KEY_PAIR_NAME}\" ]; then\n  KEY_NAME=${CLUSTER}-KeyPair\n  echo \"No EC2 key pair name configured. Creating keypair ${KEY_NAME}\"\n  create_ec2_key_pair ${KEY_NAME}\n  EC2_KEY_PAIR_NAME=${KEY_NAME}\nelse\n  exist=$(aws ec2 describe-key-pairs --key-name ${EC2_KEY_PAIR_NAME} --region ${AWS_REGION} | grep KeyName | wc -l)\n  if [ ${exist} -eq 0 ]; then\n    echo \"EC2 key pair ${EC2_KEY_PAIR_NAME} does not exist in ${AWS_REGION} region\"\n    exit 1\n  fi\nfi\n\ncreate_eks_cluster ${CLUSTER} ${EKS_VERSION} ${AWS_REGION}\ncreate_node_group ${CLUSTER} ${EKS_VERSION} ${EC2_KEY_PAIR_NAME}\nadd_tags_asg ${CLUSTER} ${AWS_REGION}\nadd_iam_permissions_nodegroup ${CLUSTER} ${AWS_REGION}\ncreate_namespaces", "num_lines": 183}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EKS_CLUSTER_MANAGER_ROLE=<ARN-of-IAM-role>\n#/ ./delete_cluster.sh eks_cluster_name\n\nset -ex\n\n# Function to delete EKS cluster\nfunction delete_cluster() {\n  eksctl delete cluster \\\n    --name ${1} \\\n    --region ${2}\n}\n\n# Function to update kubeconfig at ~/.kube/config\nfunction update_kubeconfig() {\n\n  eksctl utils write-kubeconfig \\\n    --cluster ${1} \\\n    --authenticator-role-arn ${2} \\\n    --region ${3}\n\n  kubectl config get-contexts\n}\n\n# Detach IAM policy from nodegroup IAM role\nfunction remove_iam_policy() {\n\n  NODE_GROUP_NAME=${1}\n  CLUSTER_NAME=${2}\n  REGION=${3}\n\n  ROLE_ARN=$(aws eks describe-nodegroup --nodegroup-name ${NODE_GROUP_NAME} --cluster-name ${CLUSTER_NAME} --region ${REGION} | jq -r '.nodegroup.nodeRole')\n  ROLE_NAME=$(echo ${ROLE_ARN} | grep -oP 'arn:aws:iam::\\d+:role/\\K\\S+')\n\n  declare -a POLICY_ARN=(\"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess\")\n\n  for policy in ${POLICY_ARN[@]}; do\n    aws iam detach-role-policy \\\n      --role-name $ROLE_NAME \\\n      --policy-arn $policy \\\n      --region ${REGION}\n  done\n\n}\n\nfunction remove_iam_permissions_nodegroup() {\n  CLUSTER_NAME=${1}\n  REGION=${2}\n  LIST_NODE_GROUPS=$(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region ${REGION} -o json | jq -r '.[].Name')\n\n  if [ -n \"${LIST_NODE_GROUPS}\" ]; then\n    for NODEGROUP in ${LIST_NODE_GROUPS}; do\n      remove_iam_policy ${NODEGROUP} ${CLUSTER_NAME} ${REGION}\n    done\n  else\n    echo \"No Nodegroups present in the EKS cluster ${CLUSTER_NAME}\"\n  fi\n}\n\n# Function to delete OIDC provider\nfunction delete_oidc_provider() {\n  CLUSTER_NAME=${1}\n\n  account_id=$(aws sts get-caller-identity | jq -r '.Account')\n  oidc_issuer=$(aws eks describe-cluster --name ${CLUSTER_NAME} | jq -r '.cluster.identity.oidc.issuer')\n  oidc_url=$(echo $oidc_issuer | grep -oP 'https://\\K\\S+')\n  oidc_provider_arn=\"arn:aws:iam::${account_id}:oidc-provider/${oidc_url}\"\n\n  if [ -n \"${oidc_provider_arn}\" ]; then\n    echo \"Deleting OICD provider ${oidc_provider_arn} attached to EKS cluster ${CLUSTER_NAME}\"\n    aws iam delete-open-id-connect-provider --open-id-connect-provider-arn ${oidc_provider_arn}\n  fi\n\n}\n\n# Function to delete IAM roles related to OIDC\nfunction delete_oidc_iam_roles() {\n  CLUSTER_NAME=${1}\n\n  declare -a OIDC_ROLE_LIST=(\"kf-admin-${CLUSTER_NAME}\"\n    \"kf-user-${CLUSTER_NAME}\"\n  )\n\n  for role in ${OIDC_ROLE_LIST[@]}; do\n    role_policies=$(aws iam list-role-policies --role-name ${role} | jq -r '.PolicyNames[]')\n    for policy in ${role_policies[@]}; do\n      aws iam delete-role-policy --role-name ${role} --policy-name ${policy}\n    done\n    aws iam delete-role --role-name ${role}\n  done\n\n}\n# Check for input arguments\nif [ $# -ne 1 ]; then\n  echo \"usage: ./${0} eks_cluster_name\"\n  exit 1\nfi\n\n# Check for environment variables\nif [ -z \"${AWS_REGION}\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\nCLUSTER=${1}\n\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ]; then\n  update_kubeconfig ${CLUSTER} ${EKS_CLUSTER_MANAGER_ROLE} ${AWS_REGION}\nfi\n\nremove_iam_permissions_nodegroup ${CLUSTER} ${AWS_REGION}\n# delete_oidc_provider ${CLUSTER}\n# delete_oidc_iam_roles ${CLUSTER}\ndelete_cluster ${CLUSTER} ${AWS_REGION}\n", "num_lines": 118}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage: ./env_setup.sh\n\nset -ex\n\n# The below url/version is based on EKS v1.25.6. The same needs to be updated for EKS version upgrade.\nKUBECTL_CLIENT=\"https://s3.us-west-2.amazonaws.com/amazon-eks/1.25.6/2023-01-30/bin/linux/amd64/kubectl\"\nEKSCTL_CLIENT=\"https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_$(uname -s)_amd64.tar.gz\"\nAWS_IAM_AUTHENTICATOR=\"https://github.com/kubernetes-sigs/aws-iam-authenticator/releases/download/v0.6.2/aws-iam-authenticator_0.6.2_linux_amd64\"\n\nLATEST_KUBECTL_CLIENT_VERSION=1.25\n\nfunction install_kubectl_client() {\n    curl --silent --location ${KUBECTL_CLIENT} -o /usr/local/bin/kubectl\n    chmod +x /usr/local/bin/kubectl\n}\n# aws caller identity\naws sts get-caller-identity\n\n# install aws-iam-authenticator\ncurl --silent --location ${AWS_IAM_AUTHENTICATOR} -o /usr/local/bin/aws-iam-authenticator\nchmod +x /usr/local/bin/aws-iam-authenticator\n\n#aws-iam-authenticator version\naws-iam-authenticator version\n\n# install kubectl\nif ! [ -x \"$(command -v kubectl)\" ]; then\n    install_kubectl_client\nelse\n    # check if the kubectl client version is less than 1.20\n    KUBECTL_VERSION=$(kubectl version --client -o json)\n    CURRENT_KUBECTL_CLIENT_VERSION=$(echo \"$KUBECTL_VERSION\" | jq -r '.clientVersion.major').$(echo \"$KUBECTL_VERSION\" | jq -r '.clientVersion.minor' | sed 's/+$//g')\n\n    if (($(echo \"$CURRENT_KUBECTL_CLIENT_VERSION < $LATEST_KUBECTL_CLIENT_VERSION\" | bc -l))); then\n        install_kubectl_client\n    fi\nfi\n\n#kubectl version\nkubectl version --short --client\n\n# install eksctl\nif ! [ -x \"$(command -v eksctl)\" ]; then\n    curl --silent --location ${EKSCTL_CLIENT} | tar xz -C /tmp\n    mv /tmp/eksctl /usr/local/bin\nfi\n\n# eksctl version\neksctl version\n", "num_lines": 51}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ ./install_cluster_components.sh eks_cluster_name cluster_autoscalar_image_version\n\nset -ex\n\n# Function to install cluster autoscalar\nfunction install_cluster_autoscalar() {\n  kubectl create -f cluster-autoscalar-autodiscover.yaml\n  kubectl -n kube-system annotate deployment.apps/cluster-autoscaler cluster-autoscaler.kubernetes.io/safe-to-evict=\"false\"\n  sed -e 's/<CLUSTER_NAME>/'\"${1}\"'/g;s/<VERSION>/'\"${2}\"'/g' cluster-autoscalar-autodiscover.yaml >/tmp/cluster-autoscalar-autodiscover-${1}.yaml &&\n    kubectl replace -f /tmp/cluster-autoscalar-autodiscover-${1}.yaml\n\n}\n\n# Check for input arguments\nif [ $# -ne 2 ]; then\n  echo \"usage: ./${0} eks_cluster_name cluster_autoscalar_image_version\"\n  exit 1\nfi\n\n# Check for environment variables\nif [ -z \"$AWS_REGION\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\nCLUSTER_NAME=${1}\nCLUSTER_AUTOSCALAR_IMAGE_VERSION=${2}\n\ninstall_cluster_autoscalar ${CLUSTER_NAME} ${CLUSTER_AUTOSCALAR_IMAGE_VERSION}\n\n# install kubeflow\n../test/dlc_tests/eks/eks_manifest_templates/kubeflow/install_kubeflow.sh ${CLUSTER_NAME}\n", "num_lines": 37}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EKS_CLUSTER_MANAGER_ROLE=<ARN-of-IAM-role>\n#/ ./new_operation.sh eks_cluster_name eks_version\nset -ex\n\n# Function to create EC2 key pair\nfunction create_ec2_key_pair() {\n  aws ec2 create-key-pair \\\n    --key-name ${1} \\\n    --query 'KeyMaterial' \\\n    --output text >./${1}.pem\n}\n\n# Function to update kubeconfig at ~/.kube/config\nfunction update_kubeconfig() {\n\n  eksctl utils write-kubeconfig \\\n    --cluster ${1} \\\n    --authenticator-role-arn ${2} \\\n    --region ${3}\n\n  kubectl config get-contexts\n}\n\n# Attach IAM policy to nodegroup IAM role\nfunction add_iam_policy() {\n  NODE_GROUP_NAME=${1}\n  CLUSTER_NAME=${2}\n  REGION=${3}\n\n  ROLE_ARN=$(aws eks describe-nodegroup --nodegroup-name ${NODE_GROUP_NAME} --cluster-name ${CLUSTER_NAME} --region ${REGION} | jq -r '.nodegroup.nodeRole')\n  ROLE_NAME=$(echo ${ROLE_ARN} | grep -oP 'arn:aws:iam::\\d+:role/\\K\\S+')\n\n  declare -a POLICY_ARN=(\"arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess\")\n\n  for policy in ${POLICY_ARN[@]}; do\n    aws iam attach-role-policy \\\n      --role-name $ROLE_NAME \\\n      --policy-arn $policy \\\n      --region ${REGION}\n  done\n\n}\n\nfunction add_iam_permissions_nodegroup() {\n  CLUSTER_NAME=${1}\n  REGION=${2}\n  LIST_NODE_GROUPS=$(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region ${REGION} -o json | jq -r '.[].Name')\n\n  if [ -n \"${LIST_NODE_GROUPS}\" ]; then\n    for NODEGROUP in ${LIST_NODE_GROUPS}; do\n      if [[ ${NODEGROUP} == *\"graviton\"* ]]; then\n        add_iam_policy ${NODEGROUP} ${CLUSTER_NAME} ${REGION}\n      fi\n    done\n  else\n    echo \"No Nodegroups present in the EKS cluster ${CLUSTER_NAME}\"\n  fi\n}\n\n#/ Tags added to the nodegroup do not propogate to the underlying Auto Scaling Group.\n#/ Hence adding the tags explicitly as it is required for cluster autoscalar functionality\n#/ See https://github.com/aws/containers-roadmap/issues/608\nfunction add_tags_asg() {\n\n  CLUSTER_NAME=${1}\n  REGION=${2}\n\n  for details in $(eksctl get nodegroup --cluster ${CLUSTER_NAME} --region ${REGION} -o json | jq -c '.[]'); do\n    nodegroup_name=$(echo $details | jq -r '.Name')\n    asg_name=$(echo $details | jq -r '.AutoScalingGroupName')\n\n    if [[ ${nodegroup_name} == *\"graviton\"* ]]; then\n      aws autoscaling create-or-update-tags \\\n        --tags ResourceId=${asg_name},ResourceType=auto-scaling-group,Key=k8s.io/cluster-autoscaler/node-template/label/test_type,Value=graviton,PropagateAtLaunch=true\n    fi\n\n  done\n\n}\n\n# Function to create graviton nodegroup in EKS cluster\nfunction create_graviton_node_group() {\n\n  GRAVITON_NODEGROUP_INSTANCE_TYPE=\"c6g.4xlarge\"\n\n  # dynamic graviton nodegroup\n  eksctl create nodegroup \\\n    --name ${1}-graviton-nodegroup-${2/./-} \\\n    --cluster ${1} \\\n    --node-type ${GRAVITON_NODEGROUP_INSTANCE_TYPE} \\\n    --nodes-min 0 \\\n    --nodes-max 100 \\\n    --node-volume-size 80 \\\n    --node-labels \"test_type=graviton\" \\\n    --tags \"k8s.io/cluster-autoscaler/node-template/label/test_type=graviton\" \\\n    --asg-access \\\n    --managed=true \\\n    --ssh-access \\\n    --ssh-public-key \"${3}\"\n}\n\n\n#Function to upgrade core k8s components\nfunction update_eksctl_utils() {\n  eksctl utils update-kube-proxy \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n\n  eksctl utils update-aws-node \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n\n  eksctl utils update-coredns \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n}\n\nif [ $# -ne 2 ]; then\n  echo \"usage: ./${0} eks_cluster_name eks_version\"\n  exit 1\nfi\n\nif [ -z \"${AWS_REGION}\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\n# Check for EC2 keypair environment variable. If empty, create a new key pair.\nif [ -z \"${EC2_KEY_PAIR_NAME}\" ]; then\n  KEY_NAME=${CLUSTER}-KeyPair\n  echo \"No EC2 key pair name configured. Creating keypair ${KEY_NAME}\"\n  create_ec2_key_pair ${KEY_NAME}\n  EC2_KEY_PAIR_NAME=${KEY_NAME}\nelse\n  exist=$(aws ec2 describe-key-pairs --key-name ${EC2_KEY_PAIR_NAME} --region ${AWS_REGION} | grep KeyName | wc -l)\n  if [ ${exist} -eq 0 ]; then\n    echo \"EC2 key pair ${EC2_KEY_PAIR_NAME} does not exist in ${AWS_REGION} region\"\n    exit 1\n  fi\nfi\n\nCLUSTER=${1}\nEKS_VERSION=${2}\n\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ]; then\n  update_kubeconfig ${CLUSTER} ${EKS_CLUSTER_MANAGER_ROLE} ${AWS_REGION}\nfi\n\nupdate_eksctl_utils ${CLUSTER} ${AWS_REGION}\ncreate_graviton_node_group ${CLUSTER} ${EKS_VERSION} ${EC2_KEY_PAIR_NAME}\nadd_tags_asg ${CLUSTER} ${AWS_REGION}\nadd_iam_permissions_nodegroup ${CLUSTER} ${AWS_REGION}", "num_lines": 158}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EKS_CLUSTER_MANAGER_ROLE=<ARN-of-IAM-role>\n#/ ./upgrade_kubeflow.sh eks_cluster_name\n\nset -ex\n\n# Function to update kubeconfig at ~/.kube/config\nfunction update_kubeconfig() {\n\n  eksctl utils write-kubeconfig \\\n    --cluster ${1} \\\n    --authenticator-role-arn ${2} \\\n    --region ${3}\n\n  kubectl config get-contexts\n}\n\n# Check for eks cluster name\nif [ $# -ne 1 ]; then\n  echo \"usage: ./${0} eks_cluster_name\"\n  exit 1\nfi\n\n# Check for environment variables\nif [ -z \"$AWS_REGION\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\nCLUSTER_NAME=${1}\n\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ]; then\n  update_kubeconfig ${CLUSTER_NAME} ${EKS_CLUSTER_MANAGER_ROLE} ${AWS_REGION}\nfi\n\n# install kubeflow\nOPERATION=\"UPGRADE\"\n../test/dlc_tests/eks/eks_manifest_templates/kubeflow/install_kubeflow.sh ${CLUSTER_NAME} ${OPERATION}\n", "num_lines": 42}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage:\n#/ export AWS_REGION=<AWS-Region>\n#/ export EKS_CLUSTER_MANAGER_ROLE=<ARN-of-IAM-role>\n#/ target can be one of [ cluster | nodegroup ]\n#/ cluster_autoscalar_image_version option is not required for [nodegroup] target\n#/ ./upgrade_operation.sh <target> eks_cluster_name eks_version cluster_autoscalar_image_version\nset -ex\n\n# Function to update kubeconfig at ~/.kube/config\nfunction update_kubeconfig() {\n\n  eksctl utils write-kubeconfig \\\n    --cluster ${1} \\\n    --authenticator-role-arn ${2} \\\n    --region ${3}\n\n  kubectl config get-contexts\n}\n\n# Function to upgrade eks control plane\nfunction upgrade_eks_control_plane() {\n\n  eksctl upgrade cluster \\\n    --name ${1} \\\n    --version ${2} \\\n    --timeout 180m \\\n    --approve\n}\n\n# Function to control scaling of cluster autoscalar\nfunction scale_cluster_autoscalar() {\n  kubectl scale deployments/cluster-autoscaler \\\n    --replicas=${1} \\\n    -n kube-system\n}\n# Function to upgrade autoscalar image\nfunction upgrade_autoscalar_image() {\n  kubectl -n kube-system \\\n    set image deployment.apps/cluster-autoscaler cluster-autoscaler=k8s.gcr.io/autoscaling/cluster-autoscaler:${1}\n}\n\n# Function to upgrade nodegroups\nfunction upgrade_nodegroups() {\n  CLUSTER=${1}\n  EKS_VERSION=${2}\n  REGION=${3}\n\n  LIST_NODE_GROUPS=$(eksctl get nodegroup --cluster ${CLUSTER} -o json | jq -r '.[].Name')\n\n  if [ -n \"${LIST_NODE_GROUPS}\" ]; then\n\n    for NODEGROUP in ${LIST_NODE_GROUPS}; do\n      eksctl upgrade nodegroup \\\n        --name ${NODEGROUP} \\\n        --cluster ${CLUSTER} \\\n        --kubernetes-version ${EKS_VERSION} \\\n        --timeout 90m \\\n        --region ${REGION}\n    done\n  else\n    echo \"No Nodegroups present in the EKS cluster ${1}\"\n  fi\n}\n\n#Function to upgrade core k8s components\nfunction update_eksctl_utils() {\n  eksctl utils update-kube-proxy \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n\n  eksctl utils update-aws-node \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n\n  eksctl utils update-coredns \\\n    --cluster ${1} \\\n    --region ${2} \\\n    --approve\n}\n\nif [ $# -lt 3 ]; then\n  echo \"usage: ${0} target eks_cluster_name eks_version cluster_autoscalar_image_version\"\n  exit 1\nfi\n\nif [ -z \"${AWS_REGION}\" ]; then\n  echo \"AWS region not configured\"\n  exit 1\nfi\n\nTARGET=${1}\nCLUSTER=${2}\nEKS_VERSION=${3}\nCLUSTER_AUTOSCALAR_IMAGE_VERSION=${4}\n\nif [ -n \"${EKS_CLUSTER_MANAGER_ROLE}\" ]; then\n  update_kubeconfig ${CLUSTER} ${EKS_CLUSTER_MANAGER_ROLE} ${AWS_REGION}\nfi\n\nif [ \"${TARGET}\" = \"CLUSTER\" ]; then\n  #scale to 0 to avoid unwanted scaling\n  scale_cluster_autoscalar 0\n  upgrade_autoscalar_image ${CLUSTER_AUTOSCALAR_IMAGE_VERSION}\n  upgrade_eks_control_plane ${CLUSTER} ${EKS_VERSION}\n  upgrade_nodegroups ${CLUSTER} ${EKS_VERSION} ${AWS_REGION}\n  update_eksctl_utils ${CLUSTER} ${AWS_REGION}\n  #scale back to 1\n  scale_cluster_autoscalar 1\nelif [ \"${TARGET}\" = \"NODEGROUP\" ]; then\n  upgrade_nodegroups ${CLUSTER} ${EKS_VERSION} ${AWS_REGION}\nfi\n", "num_lines": 115}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ \"$1\" = \"train\" ]]; then\n     CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n     sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n     gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n     gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n     LD_PRELOAD=/libchangehostname.so train\nelse\n     eval \"$@\"\nfi\n", "num_lines": 12}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nneuron_monitor_running=0\nif [[ ! -z \"${NEURON_MONITOR_CW_REGION}\" ]]; then\n  # Start neuron monitor. If namespace/region variable is set then use it.\n  if [[ ! -z \"${NEURON_MONITOR_CONFIG_FILE}\" ]]; then\n    config=\"--config-file ${NEURON_MONITOR_CONFIG_FILE:+ $NEURON_MONITOR_CONFIG_FILE}\"\n  fi\n  if [[ ! -z \"${NEURON_MONITOR_CW_NAMESPACE}\" ]]; then\n    mnnamespace=\"--namespace ${NEURON_MONITOR_CW_NAMESPACE:+ $NEURON_MONITOR_CW_NAMESPACE}\"\n  fi\n  region=\"--region ${NEURON_MONITOR_CW_REGION:+ $NEURON_MONITOR_CW_REGION}\"\n  /opt/aws/neuron/bin/neuron-monitor ${config:+ $config} | /opt/aws/neuron/bin/neuron-monitor-cloudwatch.py ${mnnamespace:+ $mnnamespace} ${region:+$region} >> /tmp/nm.log 2>&1 &\n  nm_pid=$!\n  echo \"Neuron Monitor Started\"\n  neuron_monitor_running=1\nfi ", "num_lines": 17}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ \"$1\" = \"train\" ]]; then\n     CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n     sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n     gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n     gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n     LD_PRELOAD=/libchangehostname.so train\nelse\n     eval \"$@\"\nfi\n", "num_lines": 12}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODEL_STORE=/opt/ml/model\nMMS_CONFIG=/home/model-server/config.properties\nMODEL_PATH=\"\"\n\nwhile getopts \":m:t:\" opt; do\n  case $opt in\n    m) MODEL_PATH=\"$OPTARG\"\n    ;;\n    t) MMS_CONFIG=\"$OPTARG\"\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\nprintf \"Model path: %s\\n\" \"$MODEL_PATH\"\nprintf \"MMS_CONFIG: %s\\n\" \"$TS_CONFIG\"\n# Start the Model Server\nif [[ -z \"$MODEL_PATH\" ]]; then\n  multi-model-server --start --mms-config /home/model-server/config.properties --model-store /opt/ml/model &\nelse\n  multi-model-server --start --mms-config $MMS_CONFIG --models $MODEL_PATH &\nfi\nstatus=$?\nif [ $status -ne 0 ]; then\n  echo \"Failed to start MMS Model Server: $status\"\n  exit $status\nfi", "num_lines": 30}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nneuron_monitor_running=0\nif [[ ! -z \"${NEURON_MONITOR_CW_REGION}\" ]]; then\n  # Start neuron monitor. If namespace/region variable is set then use it.\n  if [[ ! -z \"${NEURON_MONITOR_CONFIG_FILE}\" ]]; then\n    config=\"--config-file ${NEURON_MONITOR_CONFIG_FILE:+ $NEURON_MONITOR_CONFIG_FILE}\"\n  fi\n  if [[ ! -z \"${NEURON_MONITOR_CW_NAMESPACE}\" ]]; then\n    mnnamespace=\"--namespace ${NEURON_MONITOR_CW_NAMESPACE:+ $NEURON_MONITOR_CW_NAMESPACE}\"\n  fi\n  region=\"--region ${NEURON_MONITOR_CW_REGION:+ $NEURON_MONITOR_CW_REGION}\"\n  /opt/aws/neuron/bin/neuron-monitor ${config:+ $config} | /opt/aws/neuron/bin/neuron-monitor-cloudwatch.py ${mnnamespace:+ $mnnamespace} ${region:+$region} >> /tmp/nm.log 2>&1 &\n  nm_pid=$!\n  echo \"Neuron Monitor Started\"\n  neuron_monitor_running=1\nfi", "num_lines": 17}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nneuron_monitor_running=0\nif [[ ! -z \"${NEURON_MONITOR_CW_REGION}\" ]]; then\n  # Start neuron monitor. If namespace/region variable is set then use it.\n  if [[ ! -z \"${NEURON_MONITOR_CONFIG_FILE}\" ]]; then\n    config=\"--config-file ${NEURON_MONITOR_CONFIG_FILE:+ $NEURON_MONITOR_CONFIG_FILE}\"\n  fi\n  if [[ ! -z \"${NEURON_MONITOR_CW_NAMESPACE}\" ]]; then\n    mnnamespace=\"--namespace ${NEURON_MONITOR_CW_NAMESPACE:+ $NEURON_MONITOR_CW_NAMESPACE}\"\n  fi\n  region=\"--region ${NEURON_MONITOR_CW_REGION:+ $NEURON_MONITOR_CW_REGION}\"\n  /opt/aws/neuron/bin/neuron-monitor ${config:+ $config} | /opt/aws/neuron/bin/neuron-monitor-cloudwatch.py ${mnnamespace:+ $mnnamespace} ${region:+$region} >> /tmp/nm.log 2>&1 &\n  nm_pid=$!\n  echo \"Neuron Monitor Started\"\n  neuron_monitor_running=1\nfi", "num_lines": 17}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n\n    gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n    gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so train\nelse\n    serve\nfi\n", "num_lines": 16}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODEL_STORE=/opt/ml/model\nTS_CONFIG=/home/model-server/config.properties\nMODEL_PATH=\"\"\n\nwhile getopts \":m:t:\" opt; do\n  case $opt in\n    m) MODEL_PATH=\"$OPTARG\"\n    ;;\n    t) TS_CONFIG=\"$OPTARG\"\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\nprintf \"Model path: %s\\n\" \"$MODEL_PATH\"\nprintf \"TS_CONFIG: %s\\n\" \"$TS_CONFIG\"\n# Start the Model Server\nif [[ -z \"$MODEL_PATH\" ]]; then\n  torchserve --start --ts-config /home/model-server/config.properties --model-store /opt/ml/model &\nelse\n  torchserve --start --ts-config $TS_CONFIG --models $MODEL_PATH &\nfi\nstatus=$?\nif [ $status -ne 0 ]; then\n  echo \"Failed to start TF Model Server: $status\"\n  exit $status\nfi", "num_lines": 30}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ \"$1\" = \"train\" ]]; then\n     CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n     sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n     gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n     gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n     LD_PRELOAD=/libchangehostname.so train\nelse\n     eval \"$@\"\nfi\n", "num_lines": 12}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "FRAMEWORK=$1\n\nset -x\n\ncd ${FRAMEWORK}\npwd\n\nif [ \"$FRAMEWORK\" = \"tensorflow\"  ]; then\n    cd ../inference\n    chmod +x ./scripts/*.sh\n    chmod +x ./docker/build_artifacts/sagemaker/serve\nfi\n\ncd ../../\n", "num_lines": 15}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nneuron_monitor_running=0\nif [[ ! -z \"${NEURON_MONITOR_CW_REGION}\" ]]; then\n  # Start neuron monitor. If namespace/region variable is set then use it.\n  if [[ ! -z \"${NEURON_MONITOR_CONFIG_FILE}\" ]]; then\n    config=\"--config-file ${NEURON_MONITOR_CONFIG_FILE:+ $NEURON_MONITOR_CONFIG_FILE}\"\n  fi\n  if [[ ! -z \"${NEURON_MONITOR_CW_NAMESPACE}\" ]]; then\n    mnnamespace=\"--namespace ${NEURON_MONITOR_CW_NAMESPACE:+ $NEURON_MONITOR_CW_NAMESPACE}\"\n  fi\n  region=\"--region ${NEURON_MONITOR_CW_REGION:+ $NEURON_MONITOR_CW_REGION}\"\n  /opt/aws/neuron/bin/neuron-monitor ${config:+ $config} | /opt/aws/neuron/bin/neuron-monitor-cloudwatch.py ${mnnamespace:+ $mnnamespace} ${region:+$region} >> /tmp/nm.log 2>&1 &\n  nm_pid=$!\n  echo \"Neuron Monitor Started\"\n  neuron_monitor_running=1\nfi", "num_lines": 17}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# PreRequisities\n# Install mxnet >=1.3b and gluoncv on each machine\n# Ensure you have Horovod, OpenMPI installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n# Training\n# num-epochs is configurable.\n# Ideally user can specify num-epochs of their choice or rely on default value=90\n# CodeBuild timeout is currently 90mins.\n# When num-epochs = 40 and warmup-epochs = 10, training completes within 90min timeout\n# Hence, for purpose of the PR num-epochs has been set to 40\n\npython mxnet_imagenet_resnet50.py --num-epochs \"40\"\n", "num_lines": 20}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\naws configure set region \"us-west-2\"\naws cloudwatch put-metric-data --metric-name \"test2\" --namespace \"PyTorch/SM/Benchmarks/TorchDynamo/Inductor\" --value 5\nPYTHON_VERSION=$(python -c 'import sys; print(sys.version_info[0])' | tr -d \"'\")\nif [ \"$PYTHON_VERSION\" -eq 2 ]\nthen\n  exit 0\nfi\nHOME_DIR=/opt/ml/output/data/test/benchmark\nBIN_DIR=${HOME_DIR}/bin\nLOG_DIR=${HOME_DIR}/logs\n\nmkdir -p ${HOME_DIR}\nmkdir -p ${BIN_DIR}\nmkdir -p ${LOG_DIR}\n\npython -c \"import sys;\nassert sys.version_info < (3, 7);\"\nPYTHON_VERSION_CHECK=`echo $?`\n\nset -e\ncd $BIN_DIR\n# tmp fix for numpy deprecations, PR raised: https://github.com/HewlettPackard/dlcookbook-dlbs/pull/19\ngit clone --quiet --single-branch --depth 1 --branch v2.0.0 https://github.com/pytorch/pytorch.git pytorch\n\ncd pytorch\n\npip install -U numpy\npip install deepspeed==0.8.2\npip install gitpython\npip install tabulate==0.9.0\n\nTRAINING_LOG=${LOG_DIR}/pytorch_inductor_huggingface_benchmark.log\n\npython benchmarks/dynamo/runner.py --suites=huggingface --training --dtypes=amp --compilers=inductor --output-dir=huggingface_logs --extra-args='--output-directory=./' > $TRAINING_LOG 2>&1\n\nRETURN_VAL=`echo $?`\nset -e\n\nif [ ${RETURN_VAL} -eq 0 ]; then\n    echo \"Training Huggingface Benchmark Test Complete using PyTorch Inductor.\"\nelse\n    echo \"Training Huggingface Benchmark Test Failed using PyTorch Inductor.\"\n    cat $TRAINING_LOG\n    exit 1\nfi\n\nexit 0\n", "num_lines": 49}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nPYTHON_VERSION=$(python -c 'import sys; print(sys.version_info[0])' | tr -d \"'\")\nif [ \"$PYTHON_VERSION\" -eq 2 ]\nthen\n  exit 0\nfi\nHOME_DIR=/opt/ml/output/data/test/benchmark\nBIN_DIR=${HOME_DIR}/bin\nLOG_DIR=${HOME_DIR}/logs\n\nmkdir -p ${HOME_DIR}\nmkdir -p ${BIN_DIR}\nmkdir -p ${LOG_DIR}\n\npython -c \"import sys;\nassert sys.version_info < (3, 7);\"\nPYTHON_VERSION_CHECK=`echo $?`\n\nset -e\ncd $BIN_DIR\n# tmp fix for numpy deprecations, PR raised: https://github.com/HewlettPackard/dlcookbook-dlbs/pull/19\ngit clone --quiet --single-branch --depth 1 --branch v2.0.0 https://github.com/pytorch/pytorch.git pytorch\n\ncd pytorch\n\npip install -U numpy\npip install deepspeed==0.8.2\npip install gitpython\npip install tabulate==0.9.0\n\nTRAINING_LOG=${LOG_DIR}/pytorch_inductor_timm_benchmark.log\n\npython benchmarks/dynamo/runner.py --suites=timm_models --training --dtypes=amp --compilers=inductor --output-dir=timm_logs --extra-args='--output-directory=./' > $TRAINING_LOG 2>&1 \n\nRETURN_VAL=`echo $?`\nset -e\n\nif [ ${RETURN_VAL} -eq 0 ]; then\n    echo \"Training Timm Complete using PyTorch Inductor.\"\nelse\n    echo \"Training Timm Failed using PyTorch Inductor.\"\n    cat $TRAINING_LOG\n    exit 1\nfi\n\nexit 0\n", "num_lines": 48}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nPYTHON_VERSION=$(python -c 'import sys; print(sys.version_info[0])' | tr -d \"'\")\nif [ \"$PYTHON_VERSION\" -eq 2 ]\nthen\n  exit 0\nfi\nHOME_DIR=/opt/ml/output/data/test/benchmark\nBIN_DIR=${HOME_DIR}/bin\nLOG_DIR=${HOME_DIR}/logs\n\nmkdir -p ${HOME_DIR}\nmkdir -p ${BIN_DIR}\nmkdir -p ${LOG_DIR}\n\npython -c \"import sys;\nassert sys.version_info < (3, 7);\"\nPYTHON_VERSION_CHECK=`echo $?`\n\nset -e\ncd $BIN_DIR\n# tmp fix for numpy deprecations, PR raised: https://github.com/HewlettPackard/dlcookbook-dlbs/pull/19\ngit clone --quiet --single-branch --depth 1 --branch v2.0.0 https://github.com/pytorch/pytorch.git pytorch\n\ncd pytorch\n\npip install -U numpy\npip install deepspeed==0.8.2\npip install gitpython\npip install tabulate==0.9.0\n\n# install torchdata and torchtext before installing torchbench\ngit clone --branch v0.6.0 https://github.com/pytorch/data.git \ncd data\npip install .\n\ncd ..\ngit clone --branch v0.15.1 https://github.com/pytorch/text torchtext\ncd torchtext\ngit submodule update --init --recursive\nFORCE_CUDA=1 python setup.py clean install\n\ncd ../..\ngit clone --quiet --single-branch --depth 1 https://github.com/pytorch/benchmark.git\ncd benchmark\npython install.py\n\ncd ../pytorch\n\nTRAINING_LOG=${LOG_DIR}/pytorch_inductor_torchbench_benchmark.log\npython benchmarks/dynamo/runner.py --suites=torchbench --training --dtypes=amp --compilers=inductor --output-dir=torchbench_logs --extra-args='--output-directory=./' > $TRAINING_LOG 2>&1 \n\nRETURN_VAL=`echo $?`\nset -e\n\nif [ ${RETURN_VAL} -eq 0 ]; then\n    echo \"Training Torchbench Complete using PyTorch Inductor.\"\nelse\n    echo \"Training Torchbench Failed using PyTorch Inductor.\"\n    cat $TRAINING_LOG\n    exit 1\nfi\n\nexit 0\n", "num_lines": 65}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# Ensure you have Horovod, OpenMPI, and Tensorflow installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n\n# Training\n\nexport TENSORFLOW_INTER_OP_PARALLELISM=2\n# For an EC2 c5.18xlarge instance, number of logical cores = 72\nexport TENSORFLOW_INTRA_OP_PARALLELISM=72\n# For an EC2 c5.18xlarge instance, number of physical cores = 36\nexport OMP_NUM_THREADS=36\nexport KMP_AFFINITY='granularity=fine,verbose,compact,1,0'\n# For an EC2 c5.18xlarge instance, number of physical cores / 4 = 36 /4 = 9\nexport TENSORFLOW_SESSION_PARALLELISM=9\nexport KMP_BLOCKTIME=1\nexport KMP_SETTINGS=0\n\npython -W ignore horovod/examples/tensorflow_synthetic_benchmark.py --no-cuda --num-warmup-batche 10 --num-iters 10 \\\n--model ResNet50\n", "num_lines": 26}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "\n#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# Ensure you have Horovod, OpenMPI, and Tensorflow installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n# p3 instances have larger GPU memory, so a higher batch size can be used\nGPU_MEM=`nvidia-smi --query-gpu=memory.total --format=csv,noheader -i 0 | awk '{print $1}'`\nif [ $GPU_MEM -gt 15000 ] ; then BATCH_SIZE=256; else BATCH_SIZE=128; fi\n\n# Training\n\npython -W ignore deep-learning-models/models/resnet/tensorflow/train_imagenet_resnet_hvd.py \\\n--data_dir $SM_CHANNEL_TRAIN --num_epochs 90 -b $BATCH_SIZE \\\n--lr_decay_mode poly --warmup_epochs 10 --clear_log\n", "num_lines": 20}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# Ensure you have Horovod, OpenMPI, and Tensorflow installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n\n# Training\n\nexport TENSORFLOW_INTER_OP_PARALLELISM=2\n# For an EC2 c5.18xlarge instance, number of logical cores = 72\nexport TENSORFLOW_INTRA_OP_PARALLELISM=72\n# For an EC2 c5.18xlarge instance, number of physical cores = 36\nexport OMP_NUM_THREADS=36\nexport KMP_AFFINITY='granularity=fine,verbose,compact,1,0'\n# For an EC2 c5.18xlarge instance, number of physical cores / 4 = 36 /4 = 9\nexport TENSORFLOW_SESSION_PARALLELISM=9\nexport KMP_BLOCKTIME=1\nexport KMP_SETTINGS=0\n\npython -W ignore horovod/examples/tensorflow2_synthetic_benchmark.py --no-cuda --num-warmup-batches 10 --num-iters 10 \\\n--model ResNet50\n", "num_lines": 26}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# Ensure you have Horovod, OpenMPI, and Tensorflow installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n# p3 instances have larger GPU memory, so a higher batch size can be used\nGPU_MEM=`nvidia-smi --query-gpu=memory.total --format=csv,noheader -i 0 | awk '{print $1}'`\nif [ $GPU_MEM -gt 15000 ] ; then BATCH_SIZE=256; else BATCH_SIZE=128; fi\n\n# Training\n\npython -W ignore deep-learning-models/models/resnet/tensorflow2/train_tf2_resnet.py \\\n--data_dir $SM_CHANNEL_TRAIN --synthetic --batch_size 128 --num_batches 1000 --clear_log 2\n", "num_lines": 18}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\n# Ensure you have Horovod, OpenMPI, and Tensorflow installed on each machine\n# Specify hosts in the file `hosts`\n\nset -ex\n\n# p3 instances have larger GPU memory, so a higher batch size can be used\nGPU_MEM=`nvidia-smi --query-gpu=memory.total --format=csv,noheader -i 0 | awk '{print $1}'`\nif [ $GPU_MEM -gt 15000 ] ; then BATCH_SIZE=256; else BATCH_SIZE=128; fi\n\n# Training\n\npython -W ignore deep-learning-models/models/resnet/tensorflow2/train_tf2_resnet.py \\\n--data_dir $SM_CHANNEL_TRAIN --synthetic --batch_size 128 --num_batches 1000 --clear_log 2 --xla-off\n", "num_lines": 18}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# For dockerfiles of PyTorch >= 2.0, CUDA_HOME is already set as an env, and is configured as /opt/conda\npython -c \"import torch; from packaging.version import Version; assert Version(torch.__version__) >= Version('2.0')\"\nTORCH_VERSION_2x=$?\nif [ $TORCH_VERSION_2x -ne 0 ]; then\n  CUDA_HOME=/usr/local/cuda\nfi\n\nset -e\n\necho \"Building all_reduce_perf from nccl-tests\"\ncd /tmp/\nrm -rf nccl-tests/\ngit clone https://github.com/NVIDIA/nccl-tests.git\ncd nccl-tests/\nmake MPI=1 MPI_HOME=/opt/amazon/openmpi NCCL_HOME=/usr/local CUDA_HOME=${CUDA_HOME}\ncp build/all_reduce_perf /all_reduce_perf\ncd /tmp/\nrm -rf nccl-tests/\n", "num_lines": 21}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\nset -ex\n\n# Script to run fi_pingpong locally over EFA to test connectivity.\n\nif ! command -v fi_info >/dev/null 2>&1 || ! command -v fi_pingpong >/dev/null 2>&1; then\n        echo \"Error: required libfabric binaries not found.\"\n        exit 1\nfi\n\nif ! fi_info -p efa >/dev/null 2>&1; then\n        echo \"Error: EFA libfabric provider not detected.\" >&2\n        exit 1\nfi\n\necho \"Starting server...\"\nFI_EFA_ENABLE_SHM_TRANSFER=0 fi_pingpong -e rdm -p efa >/dev/null 2>&1 &\nsleep 0.5\n\necho \"Starting client...\"\nFI_EFA_ENABLE_SHM_TRANSFER=0 timeout 8 fi_pingpong -e rdm -p efa localhost\nret=$?\nif [ $ret -ne 0 ]; then\n        if [ $ret -eq 124 ]; then\n                echo \"Error: fi_pingpong test timed out.\" >&2\n        else\n                echo \"Error: fi_pingpong test returned $ret.\" >&2\n        fi\nfi\nkill %1\nexit $ret\n", "num_lines": 34}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#!/usr/bin/env bash\nsanity | grep 'Failures: 0, Errors: 0' &> /dev/null\nif [ $? != 0 ]; then\n    echo \"GDRCopy Sanity check failed!\"\n    exit 1\nfi\necho \"GDRCopy Sanity check succeed!\"\n", "num_lines": 21}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#/ Usage: \n#/ cluster name is required. operation is optional\n#/ ./install_kubeflow.sh eks_cluster_name [operation]\n\nset -ex\n\n# Function to install kustomize\ninstall_kustomize(){\n    KUSTOMIZE_VERSION=\"v4.5.7\"\n    KUSTOMIZE_URL=\"https://github.com/kubernetes-sigs/kustomize/releases/download/kustomize%2F${KUSTOMIZE_VERSION}/kustomize_${KUSTOMIZE_VERSION}_linux_amd64.tar.gz\"\n\n    if ! command -v kustomize &> /dev/null\n    then\n        wget -O /tmp/kustomize_${KUSTOMIZE_VERSION}_linux.tar.gz ${KUSTOMIZE_URL}\n        tar -xvf /tmp/kustomize_${KUSTOMIZE_VERSION}_linux.tar.gz -C /tmp/\n        if ! [ -x \"$command -v sudo\" ]; then\n            mv /tmp/kustomize /usr/local/bin\n        else\n            sudo mv /tmp/kustomize /usr/local/bin\n        fi\n    fi\n}\n\n# Function to install kubeflow in EKS cluster using kustomize\ninstall_kubeflow(){\n\n    echo \"> Installing kubeflow namespace\"\n    kustomize build manifests/common/kubeflow-namespace/base | kubectl apply -f -\n\n    echo \"> Installing training operators\"\n    kustomize build manifests/apps/training-operator/upstream/overlays/kubeflow | kubectl apply -f -\n}\n\n# Function to remove kubeflow training operators in EKS cluster using kustomize\nuninstall_kubeflow(){\n\n    echo \"> Uninstalling training operators\"\n    while ! kustomize build manifests/apps/training-operator/upstream/overlays/kubeflow | kubectl delete -f -; do echo \"Retrying to delete training operator resources\"; sleep 10; done\n\n}\n\n# Function to create directory and download kubeflow components\nsetup_kubeflow(){\n    KUBEFLOW_VERSION=\"v1.7.0\"\n    local EKS_CLUSTER_NAME=$1\n    DIRECTORY=\"${HOME}/${EKS_CLUSTER_NAME}\"\n\n    if [ -d \"${DIRECTORY}\" ]; then\n        rm -rf ${DIRECTORY};\n    fi\n        \n    mkdir ${DIRECTORY} \n    cd ${DIRECTORY}\n    \n    # clones manifests from kubeflow github into a folder named manifests\n    git clone -b ${KUBEFLOW_VERSION} --single-branch https://github.com/kubeflow/manifests.git\n}\n\n\n\n# Check for input arguments\nif [ $# ge 1 ]; then\n    echo \"usage: ./${0} eks_cluster_name [operation]\"\n    exit 1\nfi\n\nEKS_CLUSTER_NAME=${1}\nOPERATION=${2}\n\necho \"> Installing kustomize\"\ninstall_kustomize\n\necho \"> Setup installation directory\"\nsetup_kubeflow ${EKS_CLUSTER_NAME}\n\n# uninstall the manifest if operation is to upgrade kubeflow\nif [ \"${OPERATION}\" = \"UPGRADE\" ]; then\n    echo \"> Uninstalling kubeflow manifest\"\n    uninstall_kubeflow\nfi\n\necho \"> Setting up kubeflow\"\ninstall_kubeflow\n\necho \"> Installation complete\"\n", "num_lines": 87}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#!/usr/bin/env bash\n\n/opt/amazon/efa/bin/fi_info -p efa | grep 'efa' &> /dev/null\nif [ $? == 1 ]; then\n    echo \"EFA not picked on instance\"\n    exit 1\nfi\necho \"EFA picked on instance\"\n", "num_lines": 22}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright 2018-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#!/usr/bin/env bash\nsanity | grep 'Failures: 0, Errors: 0' &> /dev/null\nif [ $? != 0 ]; then\n    echo \"GDRCopy Sanity check failed!\"\n    exit 1\nfi\necho \"GDRCopy Sanity check succeed!\"\n", "num_lines": 21}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\npython smdataparallel_mnist.py\n", "num_lines": 8}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nif [[ $(python -c \"import torch; from packaging.version import Version; is_less_than_pt10 = Version(torch.__version__) < Version('1.10'); print(is_less_than_pt10)\") == 'True' ]]\nthen\n    smddpsinglenode python smdataparallel_mnist.py\nelse\n    smddp_singlenode_dev python smdataparallel_mnist.py\nfi\n\nbash smmodelparallel_mnist_script_mode.sh\n", "num_lines": 15}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "set -ex\n\nexport SM_HP_MP_PARAMETERS=\\{\\\"ddp\\\":true,\\\"microbatches\\\":4,\\\"partitions\\\":2,\\\"pipeline\\\":\\\"interleaved\\\"\\}\nmpirun -mca btl_vader_single_copy_mechanism none --allow-run-as-root -np 8 python smmodelparallel_pt_mnist.py --assert-losses 1 --data-dir data/training", "num_lines": 4}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nab -k -n 10000 -c 16 -p test/resources/inputs/test.json -T 'application/json' http://localhost:8080/tfs/v1/models/half_plus_three:predict\nab -k -n 10000 -c 16 -p test/resources/inputs/test.json -T 'application/json' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test.jsons -T 'application/json' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test.csv -T 'text/csv' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test-cifar.json -T 'application/json'     -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=cifar' http://localhost:8080/invocations\n\n# Larger payloads are generated and removed when this script exits.\nTEMPFILE='/tmp/perftest_data'\ntrap 'rm -f $TEMPFILE' EXIT\n\necho \"Generating data\"\n# Creates a 10MB file with 10000 columns per line.\npython test/perf/data_generator.py -c 'text/csv' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'text/csv' http://localhost:8080/invocations\n\npython test/perf/data_generator.py -c 'application/json' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'application/json' http://localhost:8080/invocations\n\npython test/perf/data_generator.py -c 'application/jsonlines' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'application/jsonlines' http://localhost:8080/invocations\n", "num_lines": 23}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ninstance_type=\"${1:-c5.xlarge}\"\nif [[ \"$instance_type\" == p* ]]; then\n    arch='gpu'\nelse\n    arch='cpu'\nfi\n\nendpoint_name=$(echo \"sagemaker-tensorflow-serving-$instance_type\" | tr . -)\n\naws sagemaker create-endpoint-config \\\n    --endpoint-config-name $endpoint_name \\\n    --production-variants '[{\n        \"VariantName\": \"variant-name-1\",\n        \"ModelName\": \"sagemaker-tensorflow-serving-model-'$arch'\",\n        \"InitialInstanceCount\": 1,\n        \"InstanceType\": \"ml.'$instance_type'\"\n    }]'\n\naws sagemaker create-endpoint --endpoint-name $endpoint_name --endpoint-config-name $endpoint_name\n", "num_lines": 22}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\narch=${1:-'cpu'}\naws_region=$(aws configure get region)\naws_account=$(aws --region $aws_region sts --endpoint-url https://sts.$aws_region.amazonaws.com get-caller-identity --query 'Account' --output text)\n\n# change this to match SageMaker execution role in your account\nsagemaker_role=\"arn:aws:iam::$aws_account:role/service-role/AmazonSageMaker-ExecutionRole-20180510T114550\"\n\ntar -C test/resources/models -czf /tmp/sagemaker-tensorflow-serving-model.tar.gz .\naws s3 mb s3://sagemaker-$aws_region-$aws_account || true\naws s3 cp /tmp/sagemaker-tensorflow-serving-model.tar.gz s3://sagemaker-$aws_region-$aws_account/sagemaker-tensorflow-serving/test-models/sagemaker-tensorflow-serving-model.tar.gz\nrm /tmp/sagemaker-tensorflow-serving-model.tar.gz\n\n\naws sagemaker create-model \\\n    --model-name sagemaker-tensorflow-serving-model-$arch \\\n    --primary-container '{\n        \"Image\": \"'$aws_account'.dkr.ecr.'$aws_region'.amazonaws.com/sagemaker-tensorflow-serving:1.11.1-'$arch'\",\n        \"ModelDataUrl\": \"s3://sagemaker-'$aws_region'-'$aws_account'/sagemaker-tensorflow-serving/test-models/sagemaker-tensorflow-serving-model.tar.gz\",\n        \"Environment\": {\n            \"SAGEMAKER_TFS_DEFAULT_MODEL_NAME\": \"half_plus_three\"\n        }\n    }' \\\n    --execution-role-arn \"$sagemaker_role\"\n", "num_lines": 28}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nendpoint=${1-'sagemaker-tensorflow-serving-cpu-c5-xlarge'}\naws sagemaker delete-endpoint --endpoint-name $endpoint\naws sagemaker delete-endpoint-config --endpoint-config-name $endpoint", "num_lines": 5}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model sm-c518xl >> sm-perftest.log; done\n\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 128 --model tfs-c518xl >> tfs-perftest.log; done\n\n\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 128 --model tfs-p316xl >> tfs-perftest.log; done\n", "num_lines": 36}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\npython smdataparallel_mnist.py\n", "num_lines": 8}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nmpirun --allow-run-as-root -np 2 python send_receive_checkpoint.py\n\n\n", "num_lines": 10}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nsmddp_singlenode_dev python smdataparallel_mnist.py\n\nmpirun --allow-run-as-root -np 2 python tf2_conv.py\n", "num_lines": 10}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nmpirun --allow-run-as-root -np 4 python smmodelparallel_hvd2_conv.py\n\n\n", "num_lines": 10}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nmpirun --allow-run-as-root -np 2 python tf2_conv.py\nmpirun --allow-run-as-root -np 2 python tf2_conv.py xla\n\n\n", "num_lines": 11}
{"repo_name": "deep-learning-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: MIT-0\n\nset -ex\n\nmpirun --allow-run-as-root -np 2 python tf2_checkpoint_test.py\n\n", "num_lines": 9}
{"repo_name": "ec2-macos-init", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nlog() { echo \"> $*\" >&2; }\n\nif ! hash lipo 2>/dev/null; then\n    log \"Unable to build universal binary without 'lipo' (macOS only).\"\n    exit 1\nfi\n\nlog \"Building EC2 macOS Init...\"\n\n# Get commit date and version tag\nCOMMITDATE=\"$(git show -s --format=%ci HEAD)\"\nVERSION=\"$(git describe --always --tags)\"\n\nlog \"Commit date: ${COMMITDATE}\"\nlog \"Version: ${VERSION}\"\n\nfor arch in amd64 arm64; do\n    log \"Building for darwin/$arch\"\n    GOOS=darwin GOARCH=\"$arch\" CGO_ENABLED=0 \\\n        go build -trimpath \\\n        -ldflags=\"-s -w -X 'main.CommitDate=${COMMITDATE}' -X 'main.Version=${VERSION}'\" \\\n        -o \"ec2-macos-init_$arch\"\ndone\n\nlipo -create -output ec2-macos-init \\\n    ec2-macos-init_amd64 ec2-macos-init_arm64\n\nlog \"Build complete\"\n", "num_lines": 32}
{"repo_name": "efs-utils", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n#\n# Copyright 2017-2018 Amazon.com, Inc. and its affiliates. All Rights Reserved.\n#\n# Licensed under the MIT License. See the LICENSE accompanying this file\n# for the specific language governing permissions and limitations under\n# the License.\n#\n\nset -ex\n\nBASE_DIR=$(pwd)\nBUILD_ROOT=${BASE_DIR}/build/debbuild\nVERSION=1.35.0\nRELEASE=1\nDEB_SYSTEM_RELEASE_PATH=/etc/os-release\n\necho 'Cleaning deb build workspace'\nrm -rf ${BUILD_ROOT}\nmkdir -p ${BUILD_ROOT}\n\necho 'Creating application directories'\nmkdir -p ${BUILD_ROOT}/etc/amazon/efs\nmkdir -p ${BUILD_ROOT}/etc/init/\nmkdir -p ${BUILD_ROOT}/etc/systemd/system\nmkdir -p ${BUILD_ROOT}/sbin\nmkdir -p ${BUILD_ROOT}/usr/bin\nmkdir -p ${BUILD_ROOT}/var/log/amazon/efs\nmkdir -p ${BUILD_ROOT}/usr/share/man/man8\n\necho 'Copying application files'\ninstall -p -m 644 dist/amazon-efs-mount-watchdog.conf ${BUILD_ROOT}/etc/init\ninstall -p -m 644 dist/amazon-efs-mount-watchdog.service ${BUILD_ROOT}/etc/systemd/system\ninstall -p -m 444 dist/efs-utils.crt ${BUILD_ROOT}/etc/amazon/efs\ninstall -p -m 644 dist/efs-utils.conf ${BUILD_ROOT}/etc/amazon/efs\ninstall -p -m 755 src/mount_efs/__init__.py ${BUILD_ROOT}/sbin/mount.efs\ninstall -p -m 755 src/watchdog/__init__.py ${BUILD_ROOT}/usr/bin/amazon-efs-mount-watchdog\n\necho 'Copying install scripts'\ninstall -p -m 755 dist/scriptlets/after-install-upgrade ${BUILD_ROOT}/postinst\ninstall -p -m 755 dist/scriptlets/before-remove ${BUILD_ROOT}/prerm\ninstall -p -m 755 dist/scriptlets/after-remove ${BUILD_ROOT}/postrm\n\necho 'Copying control file'\ninstall -p -m 644 dist/amazon-efs-utils.control ${BUILD_ROOT}/control\n\necho 'Copying conffiles'\ninstall -p -m 644 dist/amazon-efs-utils.conffiles ${BUILD_ROOT}/conffiles\n\necho 'Copying manpages'\ninstall -p -m 644 man/mount.efs.8 ${BUILD_ROOT}/usr/share/man/man8/mount.efs.8\n\necho 'Creating deb binary file'\necho '2.0'> ${BUILD_ROOT}/debian-binary\n\necho 'Setting permissions'\nfind ${BUILD_ROOT} -type d | xargs chmod 755;\n\necho 'Creating tar'\ncd ${BUILD_ROOT}\ntar czf control.tar.gz control conffiles postinst prerm postrm --owner=0 --group=0\ntar czf data.tar.gz etc sbin usr var --owner=0 --group=0\ncd ${BASE_DIR}\n\necho 'Building deb'\nDEB=${BUILD_ROOT}/amazon-efs-utils-${VERSION}-${RELEASE}_all.deb\nar r ${DEB} ${BUILD_ROOT}/debian-binary\nar r ${DEB} ${BUILD_ROOT}/control.tar.gz\nar r ${DEB} ${BUILD_ROOT}/data.tar.gz\n\necho 'Copying deb to output directory'\ncp ${BUILD_ROOT}/amazon-efs-utils*deb build/\n", "num_lines": 73}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nBUILD_LIB_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/\" && pwd -P)\"\n\nif [ -f \"/buildkit.sh\" ] && ! buildctl debug workers > /dev/null 2>&1; then\n    # on the builder base this helper file exists to run buildkitd\n    # in prow buildkitd is run as a separate container so it will be running already\n    # in codebuild its run directly on the instance so we want to use this helper\n    /buildkit.sh \"$@\"\nelse\n    buildctl \"$@\"\nfi\n", "num_lines": 26}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfunction buildkit_ready() {\n  for i in {1..24}\n  do\n    if [ ! -S \"/run/buildkit/buildkitd.sock\" ]\n    then\n      echo \"Buildkit daemon is not running. Retrying.\"\n      sleep 5s\n    else\n      exit 0\n    fi\n  done\n  echo \"Buildkit daemon is not available\"\n  exit 1\n}\n\nbuildkit_ready\n", "num_lines": 32}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This is a diff impl than what it is eks-anywhere-build-tooling\n# we can rely on the git_tag file existing in this repo\n# instead we pull it from eks-anywhere-build-tooling git\nfunction build::common::get_latest_eksa_asset_url() {\n  local -r artifact_bucket=$1\n  local -r project=$2\n  local -r arch=${3-amd64}\n  local -r latesttag=${4-latest}\n\n  local branch=main\n  if [[ \"$latesttag\" != \"latest\" ]]; then\n    branch=$latesttag\n  fi\n\n  local -r git_tag=$(curl -sL https:/raw.githubusercontent.com/aws/eks-anywhere-build-tooling/$branch/projects/$project/GIT_TAG)\n  local -r url=\"https://$(basename $artifact_bucket).s3-us-west-2.amazonaws.com/projects/$project/$latesttag/$(basename $project)-linux-$arch-${git_tag}.tar.gz\"\n\n  local -r http_code=$(curl -I -L -s -o /dev/null -w \"%{http_code}\" $url)\n  if [[ \"$http_code\" == \"200\" ]]; then \n    echo \"$url\"\n  else\n    echo \"https://$(basename $artifact_bucket).s3-us-west-2.amazonaws.com/projects/$project/latest/$(basename $project)-linux-$arch-${git_tag}.tar.gz\"\n  fi\n}\n", "num_lines": 40}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nBINARY_DEPS_DIR=\"$1\" \nDEP=\"$2\"\nARTIFACTS_BUCKET=\"$3\"\nLATEST_TAG=\"$4\"\n#RELEASE_BRANCH=\"${5-$(build::eksd_releases::get_release_branch)}\"\n\nDEP=${DEP#\"$BINARY_DEPS_DIR\"}\nOS_ARCH=\"$(cut -d '/' -f1 <<< ${DEP})\"\nPRODUCT=$(cut -d '/' -f2 <<< ${DEP})\nREPO_OWNER=$(cut -d '/' -f3 <<< ${DEP})\nREPO=$(cut -d '/' -f4 <<< ${DEP})\n\nARCH=\"$(cut -d '-' -f2 <<< ${OS_ARCH})\"\n\nOUTPUT_DIR_FILE=$BINARY_DEPS_DIR/linux-$ARCH/$PRODUCT/$REPO_OWNER/$REPO\nif [[ $REPO == *.tar.gz ]]; then\n    mkdir -p $(dirname $OUTPUT_DIR_FILE)\nelse\n    mkdir -p $OUTPUT_DIR_FILE\nfi\n\nif [[ $PRODUCT = 'eksd' ]]; then\n    if [[ $REPO_OWNER = 'kubernetes' ]]; then\n        TARBALL=\"kubernetes-$REPO-linux-$ARCH.tar.gz\"\n        URL=$(build::eksd_releases::get_eksd_kubernetes_asset_url $TARBALL $RELEASE_BRANCH $ARCH)\n        # these tarballs will extra with the kubernetes/{client,server} folders\n        OUTPUT_DIR_FILE=$BINARY_DEPS_DIR/linux-$ARCH/$PRODUCT\n    else\n        URL=$(build::eksd_releases::get_eksd_component_url $REPO_OWNER $RELEASE_BRANCH $ARCH)\n    fi\nelse\n    TARBALL=\"$REPO-linux-$ARCH.tar.gz\"\n    URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET $REPO_OWNER/$REPO $ARCH $LATEST_TAG)\nfi\n\nif [[ $REPO == *.tar.gz ]]; then\n    curl -sSL $URL -o $OUTPUT_DIR_FILE\nelse\n    curl -sSL $URL | tar xz -C $OUTPUT_DIR_FILE\nfi\n", "num_lines": 65}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBINARY_DEPS_DIR=\"$1\"\nARCH=\"$2\"\n\nOUTPUT_DIR=\"${BINARY_DEPS_DIR}/linux-$ARCH\"\nEKS_A_TOOL_BINARY_DIR=\"${OUTPUT_DIR}/eks-a-tools/binary\"\nEKS_A_TOOL_LICENSE_DIR=\"${OUTPUT_DIR}/eks-a-tools/licenses\"\n\nmkdir -p $EKS_A_TOOL_BINARY_DIR\nmkdir -p $EKS_A_TOOL_LICENSE_DIR\n\ndeclare -A project_bin_licenses=([\"eksa/vmware/govmomi\"]=\"govc GOVMOMI\"\n                                 [\"eksa/helm/helm\"]=\"helm HELM\"\n                                 [\"eksa/apache/cloudstack-cloudmonkey\"]=\"cmk CMK\")\n\nfor project in \"${!project_bin_licenses[@]}\"\ndo\n  bin_license_map=(${project_bin_licenses[$project]})\n  binary=${bin_license_map[0]}\n  license_prefix=${bin_license_map[1]}\n  cp $OUTPUT_DIR/$project/$binary $EKS_A_TOOL_BINARY_DIR/$(basename $binary)\n  cp $OUTPUT_DIR/$project/ATTRIBUTION.txt $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_ATTRIBUTION.txt\n  cp -r $OUTPUT_DIR/$project/LICENSES $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_LICENSES\ndone\n", "num_lines": 45}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\nset -o pipefail\n\ncat << EOF > ${INTEGRATION_TEST_INFRA_CONFIG}\n---\n\nec2:\n  amiId: ${INTEGRATION_TEST_AL2_AMI_ID}\n  subnetId: ${INTEGRATION_TEST_SUBNET_ID}\n\nvSphere:\n  url: ${TEST_RUNNER_GOVC_URL}\n  insecure: True\n  library: ${TEST_RUNNER_GOVC_LIBRARY}\n  template: ${TEST_RUNNER_GOVC_TEMPLATE}\n  datacenter: ${TEST_RUNNER_GOVC_DATACENTER}\n  datastore: ${TEST_RUNNER_GOVC_DATASTORE}\n  resourcePool: ${TEST_RUNNER_GOVC_RESOURCE_POOL}\n  network: ${TEST_RUNNER_GOVC_NETWORK}\n  folder: ${TEST_RUNNER_GOVC_FOLDER}\nEOF\n", "num_lines": 38}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\nset -o pipefail\n\nif [ \"$TEST_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty TEST_ROLE_ARN, this script is used in CodeBuild to set profile to assume an IAM role\"\n    exit 1\nfi\n\nexport AWS_SDK_LOAD_CONFIG=1\nexport AWS_CONFIG_FILE=$(pwd)/awscliconfig\nexport AWS_PROFILE=e2e-test-account\n\ncat << EOF > ${AWS_CONFIG_FILE}\n[profile ${AWS_PROFILE}]\nrole_arn=${TEST_ROLE_ARN}\nregion=us-west-2\ncredential_source=EcsContainer\nEOF\n", "num_lines": 35}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\nset -o pipefail\n\nsource /docker.sh\nstart::dockerd\nwait::for::dockerd\n", "num_lines": 23}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nARTIFACTS_BUCKET=\"${1?Specify first argument - artifacts bucket}\"\nREPO_ROOT=\"${2?Specify second argument - repo root directory}\"\nPROJECT_PATH=\"${3? Specify third argument - project path}\"\nBUILD_IDENTIFIER=\"${4? Specify fourth argument - build identifier}\"\nGIT_HASH=\"${5?Specify fifth argument - git hash of the tar builds}\"\nOS_LIST_CSV=\"${6?Specify sixth argument - comma-separated list of operating systems for CLI build}\"\nARCH_LIST_CSV=\"${7?Specify seventh argument - comma-separated list of architectures for CLI build}\"\nBRANCH_NAME=\"${8?Specify eighth argument - branch name that CLI was built from}\"\nDRY_RUN=\"${9?Specify ninth argument - Dry run upload}\"\n\nREPO=\"eksctl-anywhere\"\nBINARY_PATH=\"bin\"\nTAR_PATH=\"${REPO_ROOT}/${PROJECT_PATH}/${BUILD_IDENTIFIER}-${GIT_HASH}/artifacts\"\nLATEST=latest\nif [[ $BRANCH_NAME != \"main\" ]]; then\n  LATEST=$BRANCH_NAME\nfi\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\n\nfunction build::cli::move_artifacts() {\n  local -r os=$1\n  local -r arch=$2\n  local -r cli_artifacts_path=$3\n\n  mv ${BINARY_PATH}/${os}/${arch}/eksctl-anywhere ${cli_artifacts_path}\n  cp ATTRIBUTION.txt ${cli_artifacts_path}\n}\n\nfunction build::cli::create_tarball() {\n  local -r os=$1\n  local -r arch=$2\n  local -r tar_file=$3\n  local -r tar_path=$4\n  local -r cli_artifacts_path=$5\n\n  build::ensure_tar\n\n  \"${TAR}\" czf \"${tar_path}/${os}/${arch}/${tar_file}\" -C ${cli_artifacts_path} . --owner=0 --group=0\n}\n\nfunction build::cli::generate_shasum() {\n  local -r tar_path=$1\n  local -r os=$2\n  local -r arch=$3\n\n  echo \"Writing artifact hashes to shasum files...\"\n\n  if [ ! -d \"$tar_path\" ]; then\n    echo \"  Unable to find tar directory $tar_path\"\n    exit 1\n  fi\n\n  cd $tar_path/$os/$arch\n  for file in $(find . -name '*.tar.gz'); do\n    filepath=$(basename $file)\n    sha256sum \"$filepath\" > \"$file.sha256\"\n    sha512sum \"$filepath\" > \"$file.sha512\"\n  done\n  cd -\n}\n\nfunction build::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  elif which gnutar &>/dev/null; then\n      TAR=gnutar\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\nfunction build::cli::upload() {\n  local -r artifactspath=$1\n  local -r artifactsbucket=$2\n  local -r projectpath=$3\n  local -r buildidentifier=$4\n  local -r githash=$5\n  local -r latesttag=$6\n  local -r dry_run=$7\n\n  upload_path=\"$artifactsbucket\"/\"$projectpath\"/\"$buildidentifier\"-\"$githash\"/artifacts\n  latest_upload_path=\"$artifactsbucket\"/\"$projectpath\"/\"$latesttag\"\n  if [ \"$CODEBUILD_CI\" = \"true\" ]; then\n    if [[ \"$CODEBUILD_BUILD_ID\" =~ \"aws-staging-eks-a-build\" ]]; then\n      upload_path=\"$upload_path\"/staging\n      latest_upload_path=\"$artifactsbucket\"/\"$projectpath\"/staging/\"$latesttag\"\n    fi\n  fi\n  echo \"$githash\" >> \"$artifactspath\"/githash\n\n  if [ \"$dry_run\" = \"true\" ]; then\n    aws s3 cp \"$artifactspath\" \"$upload_path\" --recursive --dryrun\n    aws s3 cp \"$artifactspath\" \"$latest_upload_path\" --dryrun\n  else\n    # Upload artifacts to s3\n    # 1. To proper path on s3 with buildId-githash\n    # 2. Latest path to indicate the latest build, with --delete option to delete stale files in the dest path\n    aws s3 sync \"$artifactspath\" \"$upload_path\" --acl public-read\n    aws s3 sync \"$artifactspath\" \"$latest_upload_path\" --delete --acl public-read\n  fi\n}\n\nOS_LIST=($(echo $OS_LIST_CSV | tr \",\" \"\\n\"))\nARCH_LIST=($(echo $ARCH_LIST_CSV | tr \",\" \"\\n\"))\n\nfor OS in \"${OS_LIST[@]}\"; do\n  for ARCH in \"${ARCH_LIST[@]}\"; do\n    TAR_FILE=\"${REPO}-${OS}-${ARCH}.tar.gz\"\n    CLI_ARTIFACTS_PATH=\"cli-artifacts/${OS}/${ARCH}\"\n    mkdir -p $TAR_PATH/$OS/$ARCH\n    mkdir -p $CLI_ARTIFACTS_PATH\n\n    build::cli::move_artifacts $OS $ARCH $CLI_ARTIFACTS_PATH\n    build::cli::create_tarball $OS $ARCH $TAR_FILE $TAR_PATH $CLI_ARTIFACTS_PATH\n    build::cli::generate_shasum $TAR_PATH $OS $ARCH\n  done\ndone\nbuild::cli::upload ${TAR_PATH} ${ARTIFACTS_BUCKET} ${PROJECT_PATH} ${BUILD_IDENTIFIER} ${GIT_HASH} ${LATEST} ${DRY_RUN}\n", "num_lines": 135}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSA_K8S_VERSION=\"${1?First argument is EKS-A k8s version}\"\nCONFORMANCE_VERSION=\"${2?Second argument is conformance test version}\"\nTARGET_DIR=\"${3?Third argument is target directory}\"\n\nTARGET=${TARGET_DIR}/README.md\n\ncat template/README.md.begin >${TARGET}\nsed -e 's/^/   /' -e \"s/kubernetesVersion: .*$/kubernetesVersion: \\\"${EKSA_K8S_VERSION}\\\"/\" <template/example.yaml >>${TARGET}\ncat template/README.md.end >>${TARGET}\nsed -i \"\" -e \"s/{{eksa_k8s_version}}/${EKSA_K8S_VERSION}/\" -e \"s/{{conformance_version}}/${CONFORMANCE_VERSION}/\" ${TARGET_DIR}/README.md\n", "num_lines": 30}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTARGET_DIR=\"${1?First argument is target directory}\"\n\nRESULTS_DIR=$(mktemp -d results.XXXXXX)\nRESULTS=$(./sonobuoy retrieve ${RESULTS_DIR})\ntar xzf $RESULTS -C ${RESULTS_DIR}\nmv ${RESULTS_DIR}/plugins/e2e/results/global/* ${TARGET_DIR}\n./sonobuoy results ${RESULTS}\nrm -rf ${RESULTS_DIR}\n", "num_lines": 29}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# To deploy to a development environment make sure you have\n# ${AWS_PROFILE} set to your account\n# ${AMPLIFY_APP_ID} (optional) set to your Amplify app or a stack named eks-anywhere-docs-devstack\n# ${AMPLIFY_APP_BRANCH} (optional) set to Amplify branch you want to deploy to [default: main]\n\nset -euo pipefail\n\n# if $AWS_PROFILE is not set we should assume we're in a deployment pipeline\nif [ -z \"${AWS_PROFILE}\" ]; then\n\n\t# set up AWS credentials file\n\tcat << EOF > config\n[default]\noutput = json\nregion = us-west-2\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n[profile release-prod]\nrole_arn = arn:aws:iam::153288728732:role/DocsDeploymentRole\nregion = us-east-1\nsource_profile=default\nEOF\n\n\tAWS_CONFIG_FILE=$(pwd)/config\n\tAWS_DEFAULT_PROFILE=release-prod\nfi\n\n# Use this function if the script is cancelled (ctrl+c) or times out\ncancel_job() {\n\taws amplify stop-job --app-id $APP --branch $BRANCH --job-id $JOB_ID\n}\n\n# vars for deployment\nGIT_COMMIT=$(git rev-parse --short HEAD)\nFILE=${1:-public.zip}\nAPP=${AMPLIFY_APP_ID:-$(aws cloudformation describe-stacks \\\n    --stack-name eks-anywhere-docs-devstack \\\n    --query 'Stacks[].Outputs[?OutputKey==`EksAnywhereDocsappId`].OutputValue' \\\n    --output text)}\nBRANCH=${AMPLIFY_APP_BRANCH:-main}\n\n# Check if we're on a tag commit\nGIT_TAG=$(git tag --points-at ${GIT_COMMIT})\n\n# If we're on a git tag we should create a branch so documentation versions work\n# Branches are configured in config.toml\nif [ -n \"${GIT_TAG}\" ]; then\n\t# replaces tag text like v0.2.0 with v0-2\n\tBRANCH=\"$(echo ${GIT_TAG%.*} | tr '.' '-')\"\n\t# create an amplify app branch for the tag\n\taws amplify create-branch --app-id $APP --branch-name $BRANCH --no-cli-pager\nfi\n\n# Create a deployment and save the job id and upload url\nread -r JOB_ID URL < <(aws amplify create-deployment --app-id  $APP --branch $BRANCH --output text)\n\n# cancel the amplify job if we exit or are inturrupted\ntrap cancel_job INT EXIT\n# upload our zip\ncurl --silent --show-error --fail --upload-file $FILE \"${URL}\"\n\naws amplify start-deployment --app-id $APP --branch $BRANCH --job-id $JOB_ID\n\n# get job status and wait for it to finish\nSTATUS=$(aws amplify get-job --app-id $APP --branch $BRANCH --job-id $JOB_ID --output text --query 'job.summary.status')\n# Don't trap for exits after this point\ntrap - EXIT\n# Total timeout will be 20+19+18...\nTIMEOUT=20\nwhile [ $TIMEOUT -gt 0 ]; do\nif [ \"${STATUS}\" = 'SUCCEED' ]; then\n\techo \"Successfully deployed $BRANCH\"\n\texit 0\nelif [ \"${STATUS}\" = 'FAILED' ]; then\n\techo \"Applify job $JOB_ID failed\"\n\taws amplify get-job --app-id $APP --branch $BRANCH --job-id $JOB_ID\n\texit 1\nelse\n\techo \"Waiting for amplify job $JOB_ID on app $APP\"\n\tSTATUS=$(aws amplify get-job --app-id $APP --branch $BRANCH --job-id $JOB_ID --output text --query 'job.summary.status')\nfi\nsleep $(( TIMEOUT-- ))\ndone\n# If we timeout waiting for the job this will run\ncancel_job\n", "num_lines": 101}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "\n* vCenter endpoint (must be accessible to EKS Anywhere clusters)\n* public.ecr.aws\n* anywhere-assets.eks.amazonaws.com (to download the EKS Anywhere binaries, manifests and OVAs)\n* distro.eks.amazonaws.com (to download EKS Distro binaries and manifests)\n* d2glxqk2uabbnd.cloudfront.net (for EKS Anywhere and EKS Distro ECR container images)\n* api.ecr.us-west-2.amazonaws.com (for EKS Anywhere package authentication matching your region)\n* d5l0dvt14r5h8.cloudfront.net (for EKS Anywhere package ECR container images)\n* api.github.com (only if GitOps is enabled)\n", "num_lines": 10}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n# - https://github.com/kubernetes/kubernetes/blob/master/hack/cherry_pick_pull.sh\n# Modifications Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. Licensed under the Apache2 License\n\n# Modifications:\n# - changed instructions link to doc in this repo instead of upstream\n# - harcoded MAIN_REPO_ORG and MAIN_REPO_NAME to avoid difference with awk on mac vs linux\n\n# Usage Instructions: https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md\n\n# Checkout a PR from GitHub. (Yes, this is sitting in a Git tree. How\n# meta.) Assumes you care about pulls from remote \"upstream\" and\n# checks them out to a branch named:\n#  automated-cherry-pick-of-<pr>-<target branch>-<timestamp>\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel)\"\ndeclare -r REPO_ROOT\ncd \"${REPO_ROOT}\"\n\nSTARTINGBRANCH=$(git symbolic-ref --short HEAD)\ndeclare -r STARTINGBRANCH\ndeclare -r REBASEMAGIC=\"${REPO_ROOT}/.git/rebase-apply\"\nDRY_RUN=${DRY_RUN:-\"\"}\nREGENERATE_DOCS=${REGENERATE_DOCS:-\"\"}\nUPSTREAM_REMOTE=${UPSTREAM_REMOTE:-upstream}\nFORK_REMOTE=${FORK_REMOTE:-origin}\nMAIN_REPO_ORG=aws # ${MAIN_REPO_ORG:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $3}')}\nMAIN_REPO_NAME=eks-anywhere # ${MAIN_REPO_NAME:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $4}')}\n\nif [[ -z ${GITHUB_USER:-} ]]; then\n  echo \"Please export GITHUB_USER=<your-user> (or GH organization, if that's where your fork lives)\"\n  exit 1\nfi\n\nif ! command -v gh > /dev/null; then\n  echo \"Can't find 'gh' tool in PATH, please install from https://github.com/cli/cli\"\n  exit 1\nfi\n\nif [[ \"$#\" -lt 2 ]]; then\n  echo \"${0} <remote branch> <pr-number>...: cherry pick one or more <pr> onto <remote branch> and leave instructions for proposing pull request\"\n  echo\n  echo \"  Checks out <remote branch> and handles the cherry-pick of <pr> (possibly multiple) for you.\"\n  echo \"  Examples:\"\n  echo \"    $0 upstream/release-3.14 12345        # Cherry-picks PR 12345 onto upstream/release-3.14 and proposes that as a PR.\"\n  echo \"    $0 upstream/release-3.14 12345 56789  # Cherry-picks PR 12345, then 56789 and proposes the combination as a single PR.\"\n  echo\n  echo \"  Set the DRY_RUN environment var to skip git push and creating PR.\"\n  echo \"  This is useful for creating patches to a release branch without making a PR.\"\n  echo \"  When DRY_RUN is set the script will leave you in a branch containing the commits you cherry-picked.\"\n  echo\n  echo \"  Set the REGENERATE_DOCS environment var to regenerate documentation for the target branch after picking the specified commits.\"\n  echo \"  This is useful when picking commits containing changes to API documentation.\"\n  echo\n  echo \"  Set UPSTREAM_REMOTE (default: upstream) and FORK_REMOTE (default: origin)\"\n  echo \"  to override the default remote names to what you have locally.\"\n  echo\n  echo \"  For merge process info, see https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md\"\n  exit 2\nfi\n\n# Checks if you are logged in. Will error/bail if you are not.\ngh auth status\n\nif git_status=$(git status --porcelain --untracked=no 2>/dev/null) && [[ -n \"${git_status}\" ]]; then\n  echo \"!!! Dirty tree. Clean up and try again.\"\n  exit 1\nfi\n\nif [[ -e \"${REBASEMAGIC}\" ]]; then\n  echo \"!!! 'git rebase' or 'git am' in progress. Clean up and try again.\"\n  exit 1\nfi\n\ndeclare -r BRANCH=\"$1\"\nshift 1\ndeclare -r PULLS=( \"$@\" )\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\nPULLDASH=$(join - \"${PULLS[@]/#/#}\") # Generates something like \"#12345-#56789\"\ndeclare -r PULLDASH\nPULLSUBJ=$(join \" \" \"${PULLS[@]/#/#}\") # Generates something like \"#12345 #56789\"\ndeclare -r PULLSUBJ\n\necho \"+++ Updating remotes...\"\ngit remote update \"${UPSTREAM_REMOTE}\" \"${FORK_REMOTE}\"\n\nif ! git log -n1 --format=%H \"${BRANCH}\" >/dev/null 2>&1; then\n  echo \"!!! '${BRANCH}' not found. The second argument should be something like ${UPSTREAM_REMOTE}/release-0.21.\"\n  echo \"    (In particular, it needs to be a valid, existing remote branch that I can 'git checkout'.)\"\n  exit 1\nfi\n\nNEWBRANCHREQ=\"automated-cherry-pick-of-${PULLDASH}\" # \"Required\" portion for tools.\ndeclare -r NEWBRANCHREQ\nNEWBRANCH=\"$(echo \"${NEWBRANCHREQ}-${BRANCH}\" | sed 's/\\//-/g')\"\ndeclare -r NEWBRANCH\nNEWBRANCHUNIQ=\"${NEWBRANCH}-$(date +%s)\"\ndeclare -r NEWBRANCHUNIQ\necho \"+++ Creating local branch ${NEWBRANCHUNIQ}\"\n\ncleanbranch=\"\"\ngitamcleanup=false\nfunction return_to_kansas {\n  if [[ \"${gitamcleanup}\" == \"true\" ]]; then\n    echo\n    echo \"+++ Aborting in-progress git am.\"\n    git am --abort >/dev/null 2>&1 || true\n  fi\n\n  # return to the starting branch and delete the PR text file\n  if [[ -z \"${DRY_RUN}\" ]]; then\n    echo\n    echo \"+++ Returning you to the ${STARTINGBRANCH} branch and cleaning up.\"\n    git checkout -f \"${STARTINGBRANCH}\" >/dev/null 2>&1 || true\n    if [[ -n \"${cleanbranch}\" ]]; then\n      git branch -D \"${cleanbranch}\" >/dev/null 2>&1 || true\n    fi\n  fi\n}\ntrap return_to_kansas EXIT\n\nSUBJECTS=()\nfunction make-a-pr() {\n  local rel\n  rel=\"$(basename \"${BRANCH}\")\"\n  echo\n  echo \"+++ Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}\"\n\n  local numandtitle\n  numandtitle=$(printf '%s\\n' \"${SUBJECTS[@]}\")\n  prtext=$(cat <<EOF\nCherry pick of ${PULLSUBJ} on ${rel}.\n\n${numandtitle}\n\nFor details on the cherry pick process, see the [cherry pick requests](https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md) page.\n\n\\`\\`\\`release-note\n\n\\`\\`\\`\nEOF\n)\n\n  gh pr create --title=\"Automated cherry pick of ${numandtitle}\" --body=\"${prtext}\" --head \"${GITHUB_USER}:${NEWBRANCH}\" --base \"${rel}\" --repo=\"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}\"\n}\n\ngit checkout -b \"${NEWBRANCHUNIQ}\" \"${BRANCH}\"\ncleanbranch=\"${NEWBRANCHUNIQ}\"\n\ngitamcleanup=true\nfor pull in \"${PULLS[@]}\"; do\n  echo \"+++ Downloading patch to /tmp/${pull}.patch (in case you need to do this again)\"\n\n  curl -o \"/tmp/${pull}.patch\" -sSL \"https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch\"\n  echo\n  echo \"+++ About to attempt cherry pick of PR. To reattempt:\"\n  echo \"  $ git am -3 /tmp/${pull}.patch\"\n  echo\n  git am -3 \"/tmp/${pull}.patch\" || {\n    conflicts=false\n    while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \\\n      || [[ -e \"${REBASEMAGIC}\" ]]; do\n      conflicts=true # <-- We should have detected conflicts once\n      echo\n      echo \"+++ Conflicts detected:\"\n      echo\n      (git status --porcelain | grep ^U) || echo \"!!! None. Did you git am --continue?\"\n      echo\n      echo \"+++ Please resolve the conflicts in another window (and remember to 'git add / git am --continue')\"\n      read -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\n      echo\n      if ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n        echo \"Aborting.\" >&2\n        exit 1\n      fi\n    done\n\n    if [[ \"${conflicts}\" != \"true\" ]]; then\n      echo \"!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'\"\n      exit 1\n    fi\n  }\n\n  # set the subject\n  subject=$(grep -m 1 \"^Subject\" \"/tmp/${pull}.patch\" | sed -e 's/Subject: \\[PATCH//g' | sed 's/.*] //')\n  SUBJECTS+=(\"#${pull}: ${subject}\")\n\n  # remove the patch file from /tmp\n  rm -f \"/tmp/${pull}.patch\"\ndone\ngitamcleanup=false\n\n# Re-generate docs (if needed)\nif [[ -n \"${REGENERATE_DOCS}\" ]]; then\n  echo\n  echo \"Regenerating docs...\"\n  if ! hack/generate-docs.sh; then\n    echo\n    echo \"hack/generate-docs.sh FAILED to complete.\"\n    exit 1\n  fi\nfi\n\nif [[ -n \"${DRY_RUN}\" ]]; then\n  echo \"!!! Skipping git push and PR creation because you set DRY_RUN.\"\n  echo \"To return to the branch you were in when you invoked this script:\"\n  echo\n  echo \"  git checkout ${STARTINGBRANCH}\"\n  echo\n  echo \"To delete this branch:\"\n  echo\n  echo \"  git branch -D ${NEWBRANCHUNIQ}\"\n  exit 0\nfi\n\nif git remote -v | grep ^\"${FORK_REMOTE}\" | grep \"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"; then\n  echo \"!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"\n  echo \"This isn't normal. Leaving you with push instructions:\"\n  echo\n  echo \"+++ First manually push the branch this script created:\"\n  echo\n  echo \"  git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\n  echo\n  echo \"where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.).\"\n  echo \"OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values.\"\n  echo\n  make-a-pr\n  cleanbranch=\"\"\n  exit 0\nfi\n\necho\necho \"+++ I'm about to do the following to push to GitHub (and I'm assuming ${FORK_REMOTE} is your personal fork):\"\necho\necho \"  git push ${FORK_REMOTE} ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\necho\nread -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\nif ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n  echo \"Aborting.\" >&2\n  exit 1\nfi\n\ngit push \"${FORK_REMOTE}\" -f \"${NEWBRANCHUNIQ}:${NEWBRANCH}\"\nmake-a-pr\n", "num_lines": 252}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nTEMP_FOLDER=tmp-kubebuilder-project\nPATH_TO_KUBEBUILDER=hack/tools/bin/kubebuilder\n\nsetupFakeKubebuilderEnv() {\n\tmkdir -p $TEMP_FOLDER/hack\n\tln -s $(pwd)/pkg/api $TEMP_FOLDER/api\n\tln -s $(pwd)/controllers $TEMP_FOLDER/controllers\n\tln -s $(pwd)/manager/main.go $TEMP_FOLDER/main.go\n\tln -s $(pwd)/hack/boilerplate.go.txt $TEMP_FOLDER/hack/boilerplate.go.txt\n\tln -s $(pwd)/PROJECT $TEMP_FOLDER/PROJECT\n\tcp hack/fake-Makefile $TEMP_FOLDER/Makefile\n}\n\nrestoreKubebuilderEnv() {\n\trm -rf $TEMP_FOLDER\n}\n\nif [ ! -f $PATH_TO_KUBEBUILDER ]; then\n\techo \"Kubebuilder is not installed. Run 'make hack/tools/bin/kubebuilder'\"\n\texit 1\nfi\n\nsetupFakeKubebuilderEnv\n(cd $TEMP_FOLDER && ./../$PATH_TO_KUBEBUILDER \"$@\")\nrestoreKubebuilderEnv\n", "num_lines": 28}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nversion::get_version_vars() {\n    # shellcheck disable=SC1083\n    GIT_COMMIT=\"$(git rev-parse HEAD^{commit})\"\n\n    if git_status=$(git status --porcelain 2>/dev/null) && [[ -z ${git_status} ]]; then\n        GIT_TREE_STATE=\"clean\"\n    else\n        GIT_TREE_STATE=\"dirty\"\n    fi\n\n    # stolen from k8s.io/hack/lib/version.sh\n    # Use git describe to find the version based on tags.\n    if GIT_VERSION=$(git describe --tags --abbrev=14 2>/dev/null); then\n        # This translates the \"git describe\" to an actual semver.org\n        # compatible semantic version that looks something like this:\n        #   v1.1.0-alpha.0.6+84c76d1142ea4d\n        #\n        # TODO: We continue calling this \"git version\" because so many\n        # downstream consumers are expecting it there.\n        # shellcheck disable=SC2001\n        DASHES_IN_VERSION=$(echo \"${GIT_VERSION}\" | sed \"s/[^-]//g\")\n        if [[ \"${DASHES_IN_VERSION}\" == \"---\" ]] ; then\n            # We have distance to subversion (v1.1.0-subversion-1-gCommitHash)\n            # shellcheck disable=SC2001\n            GIT_VERSION=$(echo \"${GIT_VERSION}\" | sed \"s/-\\([0-9]\\{1,\\}\\)-g\\([0-9a-f]\\{14\\}\\)$/.\\1\\-\\2/\")\n        elif [[ \"${DASHES_IN_VERSION}\" == \"--\" ]] ; then\n            # We have distance to base tag (v1.1.0-1-gCommitHash)\n            # shellcheck disable=SC2001\n            GIT_VERSION=$(echo \"${GIT_VERSION}\" | sed \"s/-g\\([0-9a-f]\\{14\\}\\)$/-\\1/\")\n        fi\n        if [[ \"${GIT_TREE_STATE}\" == \"dirty\" ]]; then\n            # git describe --dirty only considers changes to existing files, but\n            # that is problematic since new untracked .go files affect the build,\n            # so use our idea of \"dirty\" from git status instead.\n            GIT_VERSION+=\"-dirty\"\n        fi\n\n\n        # Try to match the \"git describe\" output to a regex to try to extract\n        # the \"major\" and \"minor\" versions and whether this is the exact tagged\n        # version or whether the tree is between two tagged versions.\n        if [[ \"${GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?([-].*)?([+].*)?$ ]]; then\n            GIT_MAJOR=${BASH_REMATCH[1]}\n            GIT_MINOR=${BASH_REMATCH[2]}\n        fi\n\n        # If GIT_VERSION is not a valid Semantic Version, then refuse to build.\n        if ! [[ \"${GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$ ]]; then\n            echo \"GIT_VERSION should be a valid Semantic Version. Current value: ${GIT_VERSION}\"\n            echo \"Please see more details here: https://semver.org\"\n            exit 1\n        fi\n    fi\n\n    GIT_RELEASE_TAG=$(git describe --abbrev=0 --tags)\n    GIT_RELEASE_COMMIT=$(git rev-list -n 1  \"${GIT_RELEASE_TAG}\")\n}\n\n# stolen from k8s.io/hack/lib/version.sh and modified\n# Prints the value that needs to be passed to the -ldflags parameter of go build\nversion::ldflags() {\n    version::get_version_vars\n\n    local -a ldflags\n    function add_ldflag() {\n        local key=${1}\n        local val=${2}\n        ldflags+=(\n            \"-X 'sigs.k8s.io/cluster-api/version.${key}=${val}'\"\n        )\n    }\n\n    add_ldflag \"buildDate\" \"$(date ${SOURCE_DATE_EPOCH:+\"--date=@${SOURCE_DATE_EPOCH}\"} -u +'%Y-%m-%dT%H:%M:%SZ')\"\n    add_ldflag \"gitCommit\" \"${GIT_COMMIT}\"\n    add_ldflag \"gitTreeState\" \"${GIT_TREE_STATE}\"\n    add_ldflag \"gitMajor\" \"${GIT_MAJOR}\"\n    add_ldflag \"gitMinor\" \"${GIT_MINOR}\"\n    add_ldflag \"gitVersion\" \"${GIT_VERSION}\"\n    add_ldflag \"gitReleaseCommit\" \"${GIT_RELEASE_COMMIT}\"\n\n    # The -ldflags parameter takes a single string, so join the output.\n    echo \"${ldflags[*]-}\"\n}\n\nversion::ldflags", "num_lines": 104}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBINARY_NAME=\"${1?Specify first argument - binary name}\"\nTAG=\"${2?Specify second argument - git version tag}\"\nTAR_PATH=\"${3?Specify third argument - tarball output path}\"\nBIN_ROOT=\"_output/bin\"\nLICENSES_PATH=\"_output/LICENSES\"\nMANIFESTS_PATH=\"_output/manifests\"\n\nREPO_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nsource \"$REPO_ROOT/scripts/common.sh\"\n\nfunction build::eks-anywhere-cluster-controller::create_tarball() {\n  platform=${1}\n  OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n  ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n  TAR_FILE=\"${BINARY_NAME}-${OS}-${ARCH}-${TAG}.tar.gz\"\n\n  cp -rf $LICENSES_PATH $BIN_ROOT/$BINARY_NAME/${OS}-${ARCH}/\n  cp ATTRIBUTION.txt $BIN_ROOT/$BINARY_NAME/${OS}-${ARCH}/\n  build::common::create_tarball ${TAR_PATH}/${TAR_FILE} $BIN_ROOT/$BINARY_NAME/${OS}-${ARCH} .\n  cp -rf $MANIFESTS_PATH/ ${TAR_PATH}\n}\n\nfunction build::eks-anywhere-cluster-controller::tarball() {\n  build::common::ensure_tar\n  mkdir -p \"$TAR_PATH\"\n  build::eks-anywhere-cluster-controller::create_tarball \"linux/amd64\"\n  rm -rf $BIN_ROOT\n  rm -rf $LICENSES_PATH\n}\n\nbuild::eks-anywhere-cluster-controller::tarball\n\nbuild::common::generate_shasum \"${TAR_PATH}\"\n", "num_lines": 55}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSRC_TAR_PATH=\"${1?Specify first argument - source tar path}\"\nARTIFACTS_BUCKET=\"${2?Specify second argument - artifacts buckets}\"\nPROJECT_PATH=\"${3? Specify third argument - project path}\"\nBUILD_IDENTIFIER=\"${4? Specify fourth argument - build identifier}\"\nGIT_HASH=\"${5?Specify fifth argument - git hash of the tar builds}\"\nLATEST_PATH=\"${6?Specify sixth argument - latest S3 folder path for artifacts}\"\n\nREPO_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nsource \"$REPO_ROOT/scripts/common.sh\"\n\nbuild::common::upload_artifacts $SRC_TAR_PATH $ARTIFACTS_BUCKET $PROJECT_PATH $BUILD_IDENTIFIER $GIT_HASH $LATEST_PATH\n", "num_lines": 32}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "export VSPHERE_USERNAME=\"cloudadmin@vmc.local\"\nexport VSPHERE_PASSWORD=\"bogus\"\nexport VSPHERE_SERVER=\"vsphere_server\"\nexport VSPHERE_DATACENTER=\"SDDC-Datacenter\"\nexport VSPHERE_DATASTORE=\"/SDDC-Datacenter/datastore/WorkloadDatastore\"\nexport VSPHERE_NETWORK=\"/SDDC-Datacenter/network/sddc-cgw-network-1\"\nexport VSPHERE_RESOURCE_POOL=\"*/Resources\"\nexport VSPHERE_FOLDER=\"/SDDC-Datacenter/vm\"\nexport VSPHERE_TEMPLATE=\"/SDDC-Datacenter/vm/Templates/ubuntu-1804-kube-v1.19.6\"\nexport CONTROL_PLANE_ENDPOINT_IP=\"1.2.3.4\"\nexport VSPHERE_TLS_THUMBPRINT=\"ABCDEFG\"\nexport VSPHERE_SSH_AUTHORIZED_KEY=\"ssh-rsa\"\nexport EXP_CLUSTER_RESOURCE_SET=\"true\"\nexport VSPHERE_STORAGE_POLICY=\"\"\nkind get clusters | grep tlhowe\nif [ $? -eq 1 ]\nthen\n    set -e\n    kind create cluster --name tlhowe\n    clusterctl init --infrastructure vsphere:v0.7.8\nfi\nclusterctl config cluster default --kubernetes-version v1.19.6 >out2\n", "num_lines": 23}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource ${SCRIPT_ROOT}/setup-aws-config.sh\nset_aws_config \"production\"\n\nEKSA_RELEASE_MANIFEST_URL=\"${1?Specify first argument - EKS-A release manifest URL}\"\n\nLATEST_EKSA_VERSION=$(curl $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.latestVersion')\nLATEST_EKSA_RELEASE_NUMBER=$(curl $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.releases[] | select(.version == '\\\"$LATEST_EKSA_VERSION\\\"') | .number')\nLATEST_BUNDLE_RELEASE_MANIFEST_URI=$(curl $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.releases[] | select(.version == '\\\"$LATEST_EKSA_VERSION\\\"') | .bundleManifestUrl')\nLATEST_EKSA_ADMIN_AMI_URI=\"https://anywhere-assets.eks.amazonaws.com/releases/eks-a/$LATEST_EKSA_RELEASE_NUMBER/artifacts/eks-a-admin-ami/$LATEST_EKSA_VERSION/eks-anywhere-admin-ami-$LATEST_EKSA_VERSION-eks-a-$LATEST_EKSA_RELEASE_NUMBER.raw\"\n\nNOTIFICATION_SUBJECT=\"New release of EKS Anywhere - version $LATEST_EKSA_VERSION\"\nNOTIFICATION_BODY=\"Amazon EKS Anywhere version $LATEST_EKSA_VERSION has been released. You can get the latest EKS-A CLI tarballs from GitHub releases. The bundle release manifest corresponding to this version of EKS-A is $LATEST_BUNDLE_RELEASE_MANIFEST_URI. This release includes a new build of the EKS-A Admin AMI image which is available at $LATEST_EKSA_ADMIN_AMI_URI\"\n\necho \"\nSending SNS message with the following details:\n    - Topic ARN: $EKSA_RELEASE_SNS_TOPIC_ARN\n    - Subject: $NOTIFICATION_SUBJECT\n    - Body: $NOTIFICATION_BODY\"\n\nSNS_MESSAGE_ID=$(\n    aws sns publish \\\n        --topic-arn \"$EKSA_RELEASE_SNS_TOPIC_ARN\" \\\n        --subject \"$NOTIFICATION_SUBJECT\" \\\n        --message \"$NOTIFICATION_BODY\" \\\n        --query \"MessageId\" \\\n        --output text\n)\n\nif [ \"$SNS_MESSAGE_ID\" ]; then\n  echo -e \"\\nRelease notification published with SNS MessageId $SNS_MESSAGE_ID\"\nelse\n  echo \"Received unexpected response while publishing to release SNS topic. An error may have occurred, and the \\\nnotification may not have not have been published\"\n  exit 1\nfi\n", "num_lines": 57}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource ${SCRIPT_ROOT}/setup-aws-config.sh\n\nARTIFACTS_DIR=\"${1?Specify first argument - artifacts path}\"\nSOURCE_BUCKET=\"${2?Specify second argument - source bucket}\"\nRELEASE_BUCKET=\"${3?Specify third argument - release bucket}\"\nCDN=\"${4?Specify fourth argument - cdn}\"\nBUNDLE_NUMBER=\"${5?Specify fifth argument - Bundle number}\"\nCLI_MIN_VERSION=\"${6?Specify sixth argument - CLI min version}\"\nCLI_MAX_VERSION=\"${7?Specify seventh argument - CLI max version}\"\nSOURCE_CONTAINER_REGISTRY=\"${8?Specify eighth argument - source container registry}\"\nRELEASE_CONTAINER_REGISTRY=\"${9?Specify ninth argument - release container registry}\"\nRELEASE_ENVIRONMENT=\"${10?Specify tenth argument - Release environment}\"\nBUILD_REPO_BRANCH_NAME=\"${11?Specify eleventh argument - Build repo branch name}\"\nCLI_REPO_BRANCH_NAME=\"${12?Specify twelfth argument - CLI repo branch name}\"\nBUILD_REPO_URL=\"${13?Specify thirteenth argument - Build repo URL}\"\nCLI_REPO_URL=\"${14?Specify fourteenth argument - CLI repo URL}\"\n\nset_aws_config \"$RELEASE_ENVIRONMENT\"\n\nmkdir -p \"${ARTIFACTS_DIR}\"\n\n${BASE_DIRECTORY}/release/bin/eks-anywhere-release release \\\n    --bundle-number \"${BUNDLE_NUMBER}\" \\\n    --min-version \"${CLI_MIN_VERSION}\" \\\n    --max-version \"${CLI_MAX_VERSION}\" \\\n    --build-repo-branch-name \"${BUILD_REPO_BRANCH_NAME}\" \\\n    --cli-repo-branch-name \"${CLI_REPO_BRANCH_NAME}\" \\\n    --artifact-dir \"${ARTIFACTS_DIR}\" \\\n    --source-bucket \"${SOURCE_BUCKET}\" \\\n    --source-container-registry \"${SOURCE_CONTAINER_REGISTRY}\" \\\n    --cdn \"${CDN}\" \\\n    --release-bucket \"${RELEASE_BUCKET}\" \\\n    --release-container-registry \"${RELEASE_CONTAINER_REGISTRY}\" \\\n    --release-environment ${RELEASE_ENVIRONMENT} \\\n    --dev-release=false \\\n    --bundle-release=true \\\n    --build-repo-url \"${BUILD_REPO_URL}\" \\\n    --cli-repo-url \"${CLI_REPO_URL}\"\n", "num_lines": 61}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource ${SCRIPT_ROOT}/setup-aws-config.sh\n\nRELEASE_VERSION=\"${1?Specify first argument - latest version}\"\nARTIFACTS_DIR=\"${2?Specify second argument - artifacts path}\"\nSOURCE_BUCKET=\"${3?Specify third argument - source bucket}\"\nRELEASE_BUCKET=\"${4?Specify fourth argument - release bucket}\"\nCDN=\"${5?Specify fifth argument - cdn}\"\nBUNDLE_NUMBER=\"${6?Specify sixth argument - Bundle number}\"\nRELEASE_NUMBER=\"${7?Specify seventh argument - Release number}\"\nRELEASE_ENVIRONMENT=\"${8?Specify eighth argument - Release environment}\"\nCLI_REPO_BRANCH_NAME=\"${9?Specify ninth argument - Branch name}\"\nBUILD_REPO_URL=\"${10?Specify tenth argument - Build repo URL}\"\nCLI_REPO_URL=\"${11?Specify eleventh argument - CLI repo URL}\"\n\nset_aws_config \"$RELEASE_ENVIRONMENT\"\n\nmkdir -p \"${ARTIFACTS_DIR}\"\n\n${BASE_DIRECTORY}/release/bin/eks-anywhere-release release \\\n    --release-version \"${RELEASE_VERSION}\" \\\n    --bundle-number \"${BUNDLE_NUMBER}\" \\\n    --release-number \"${RELEASE_NUMBER}\" \\\n    --cli-repo-branch-name \"${CLI_REPO_BRANCH_NAME}\" \\\n    --artifact-dir \"${ARTIFACTS_DIR}\" \\\n    --source-bucket \"${SOURCE_BUCKET}\" \\\n    --cdn \"${CDN}\" \\\n    --release-bucket \"${RELEASE_BUCKET}\" \\\n    --release-environment ${RELEASE_ENVIRONMENT} \\\n    --dev-release=false \\\n    --bundle-release=false \\\n    --build-repo-url \"${BUILD_REPO_URL}\" \\\n    --cli-repo-url \"${CLI_REPO_URL}\"\n", "num_lines": 55}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nARTIFACTS_DIR=\"${1?Specify first argument - artifacts path}\"\nWEEKLY_RELEASES_URL_PREFIX=\"${2?Specify second argument - weekly releases URL prefix}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nRELEASE_NOTES_PATH=\"$SCRIPT_ROOT/github-bundle-release-notes\"\nexport DATE_YYYYMMDD=\"${DATE_YYYYMMDD:-$(date \"+%F\")}\"\nRELEASE_TAG=\"weekly.$DATE_YYYYMMDD\"\n\n# Filling in values for the GitHub Release notes template\nenvsubst '$DATE_YYYYMMDD:$BUILD_REPO_HEAD:$CLI_REPO_HEAD' \\\n    < \"$RELEASE_NOTES_PATH.tmpl\" \\\n    > \"$RELEASE_NOTES_PATH\"\n\n# Downloading the weekly bundle release manifest\nmkdir -p $ARTIFACTS_DIR\nfor releasetype in bundle eks-a; do\n    wget $WEEKLY_RELEASES_URL_PREFIX/$DATE_YYYYMMDD/$releasetype-release.yaml -O $ARTIFACTS_DIR/$DATE_YYYYMMDD-$releasetype-release.yaml\ndone\n\nfor os in darwin linux; do\n    for arch in amd64 arm64; do\n        EKSA_CLI_URI=$(yq e \".spec.releases[0].eksACLI.$os.$arch.uri\" $ARTIFACTS_DIR/$DATE_YYYYMMDD-eks-a-release.yaml)\n        wget $EKSA_CLI_URI -O $ARTIFACTS_DIR/$(basename $EKSA_CLI_URI)\n    done\ndone\n\nIMAGE_BUILDER_CLI_URI=$(yq e \".spec.versionsBundles[0].eksD.imagebuilder.uri\" $ARTIFACTS_DIR/$DATE_YYYYMMDD-bundle-release.yaml)\nwget $IMAGE_BUILDER_CLI_URI -O $ARTIFACTS_DIR/$(basename $IMAGE_BUILDER_CLI_URI)\n\n# Publish the asset as a Github pre-release on main branch with a new dated tag\ngh release create $RELEASE_TAG $ARTIFACTS_DIR/* --notes-file \"$RELEASE_NOTES_PATH\" --prerelease --repo \"github.com/aws/eks-anywhere\" --title \"Weekly Release $DATE_YYYYMMDD\" --target \"main\"\n", "num_lines": 52}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nexport LANG=C.UTF-8\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\n\nARTIFACTS_DIR=\"${1?Specify first argument - artifacts path}\"\nSOURCE_BUCKET=\"${2?Specify second argument - source bucket}\"\nRELEASE_BUCKET=\"${3?Specify third argument - release bucket}\"\nCDN=\"${4?Specify fourth argument - cdn}\"\nSOURCE_CONTAINER_REGISTRY=\"${5?Specify fifth argument - source container registry}\"\nRELEASE_CONTAINER_REGISTRY=\"${6?Specify sixth argument - release container registry}\"\nBUILD_REPO_URL=\"${7?Specify seventh argument - Build repo URL}\"\nCLI_REPO_URL=\"${8?Specify eighth argument - CLI repo URL}\"\nBUILD_REPO_BRANCH_NAME=\"${9?Specify ninth argument - Build repo branch name}\"\nCLI_REPO_BRANCH_NAME=\"${10?Specify tenth argument - CLI repo branch name}\"\nDRY_RUN=\"${11?Specify eleventh argument - Dry run}\"\nWEEKLY=\"${12?Specify twelfth argument - Weekly release}\"\n\nmkdir -p \"${ARTIFACTS_DIR}\"\n\n${BASE_DIRECTORY}/release/bin/eks-anywhere-release release \\\n    --artifact-dir \"${ARTIFACTS_DIR}\" \\\n    --build-repo-url \"${BUILD_REPO_URL}\" \\\n    --cli-repo-url \"${CLI_REPO_URL}\" \\\n    --build-repo-branch-name \"${BUILD_REPO_BRANCH_NAME}\" \\\n    --cli-repo-branch-name \"${CLI_REPO_BRANCH_NAME}\" \\\n    --source-bucket \"${SOURCE_BUCKET}\" \\\n    --source-container-registry \"${SOURCE_CONTAINER_REGISTRY}\" \\\n    --cdn \"${CDN}\" \\\n    --release-bucket \"${RELEASE_BUCKET}\" \\\n    --release-container-registry \"${RELEASE_CONTAINER_REGISTRY}\" \\\n    --dev-release=true \\\n    --dry-run=${DRY_RUN} \\\n    --weekly=${WEEKLY}\n", "num_lines": 54}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nfunction set_aws_config() {\n    release_environment=\"$1\"\n    if [ \"$STAGING_ARTIFACT_DEPLOYMENT_ROLE\" = \"\" ]; then\n        echo \"Empty STAGING_ARTIFACT_DEPLOYMENT_ROLE\"\n        exit 1\n    fi\n    cat << EOF > awscliconfig\n[profile artifacts-staging]\nrole_arn=$STAGING_ARTIFACT_DEPLOYMENT_ROLE\nregion=us-east-1\ncredential_source=EcsContainer\n\nEOF\n\n    if [ \"$release_environment\" = \"production\" ]; then\n        if [ \"$PROD_ARTIFACT_DEPLOYMENT_ROLE\" = \"\" ]; then\n            echo \"Empty PROD_ARTIFACT_DEPLOYMENT_ROLE\"\n            exit 1\n        fi\n        cat << EOF >> awscliconfig\n[profile artifacts-production]\nrole_arn=$PROD_ARTIFACT_DEPLOYMENT_ROLE\nregion=us-east-1\ncredential_source=EcsContainer\nEOF\n    fi\n\n    export AWS_CONFIG_FILE=$(pwd)/awscliconfig\n}\n", "num_lines": 50}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o pipefail\n\nif [ ! -d \"/root/.docker\" ]; then\n    mkdir -p /root/.docker\nfi\nif [ ! -d \"/root/.config/containers\" ]; then\n    mkdir -p /root/.config/containers\nfi\nmv release/scripts/docker-ecr-config.json /root/.docker/config.json\nmv release/scripts/policy.json /root/.config/containers/policy.json\ngit config --global credential.helper '!aws codecommit credential-helper $@'\ngit config --global credential.UseHttpPath true\n", "num_lines": 30}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n# The generate-attribution script requires a GIT_TAG file in the project\n# root. The CLI repo doesn't have such a file, so just generating a temporary\n# one from the head commit hash\nfunction build::create_git_tag(){\n    git rev-parse HEAD > GIT_TAG\n}\n\n# The api/v1alpha1 package of the release submodule in the CLI repo does not have \n# a license file. Hence we need to copy it into the vendor directory for go-licenses\n# to pick up\nfunction build::fix_licenses(){\n    cp LICENSE ./vendor/github.com/aws/eks-anywhere/release/api/v1alpha1/LICENSE\n}\n\n# We only need to include dependencies outside of this repo\nfunction build::exclude_own(){\n    sed -i '/^github.com\\/aws\\/eks-anywhere/d' _output/attribution/go-license.csv\n}\n", "num_lines": 35}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nREPO=\"homebrew-tap\"\nORIGIN_ORG=\"eks-anywhere-brew-pr-bot\"\nUPSTREAM_ORG=\"aws\"\n\nPR_BODY=$(cat <<EOF\nIssue #, if available:\n\nDescription of changes:\nUpdate EKS Anywhere formula to point at our latest release.\n\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\nEOF\n)\n\ncd ${SCRIPT_ROOT}/\ncd ../../\ngh auth login --with-token < /secrets/github-secrets/token\n\ncd ${SCRIPT_ROOT}\nBREW_UPDATE_SCRIPT=\"brew_formula_update.sh\"\nif [ ! -f \"$BREW_UPDATE_SCRIPT\" ]\nthen\n  echo \"The script to update the brew formula does not exist in this folder, exiting..\"\n  exit 1\nfi\n\nLATEST_VERSION=$(echo $(/home/prow/go/src/github.com/aws/eks-anywhere/scripts/$BREW_UPDATE_SCRIPT))\n\ncd ${SCRIPT_ROOT}/../../../${ORIGIN_ORG}/${REPO}\ngit config --global push.default current\ngit config user.name \"EKS Anywhere Brew Update PR Bot\"\ngit config user.email \"aws-model-rocket-bots+eksbrewprbot@amazon.com\"\ngit remote -v\n\ngit remote add origin git@github.com:${ORIGIN_ORG}/${REPO}.git\ngit remote add upstream git@github.com:${UPSTREAM_ORG}/${REPO}.git\n\nPR_TITLE=\"chore: update eks-anywhere formula for ${LATEST_VERSION}\"\nCOMMIT_MESSAGE=\"[PR BOT] Update eks-anywhere brew formula for ${LATEST_VERSION}\"\nPR_BRANCH=\"eks-anywhere-formula-update\"\n\ngit checkout -b $PR_BRANCH\n\ngit diff\ngit add Formula/eks-anywhere.rb\n# If some other files get modified, the changes should be ignored\ngit restore .\nFILES_ADDED=$(git diff --staged --name-only)\nif [ \"$FILES_ADDED\" = \"\" ]; then\n    exit 0\nfi\n\ngit commit -m \"$COMMIT_MESSAGE\"\nssh-agent bash -c 'ssh-add /secrets/ssh-secrets/ssh-privatekey; ssh -o StrictHostKeyChecking=no git@github.com; git fetch upstream; git rebase -Xtheirs upstream/master; git push -u origin $PR_BRANCH -f'\n\necho \"Added ssh private key\\n\"\n\nPR_EXISTS=$(gh pr list | grep -c \"${PR_BRANCH}\" || true)\nif [ $PR_EXISTS -eq 0 ]; then\n  gh pr create --title \"$PR_TITLE\" --body \"$PR_BODY\" --repo \"${UPSTREAM_ORG}/${REPO}\"\nfi\n\n", "num_lines": 83}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nREPO=\"homebrew-tap\"\nORIGIN_ORG=\"eks-anywhere-brew-pr-bot\"\nUPSTREAM_ORG=\"aws\"\nYQ_LATEST_RELEASE_URL=\"https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64\"\n\nif ! command -v yq &> /dev/null\nthen\n  wget -qO /usr/local/bin/yq $YQ_LATEST_RELEASE_URL\n  chmod a+x /usr/local/bin/yq\nfi\n\ncurl --silent 'https://anywhere-assets.eks.amazonaws.com/releases/eks-a/manifest.yaml' -o release.yaml\n\nlatest_release_version=$(cat release.yaml | yq e '.spec.latestVersion')\n\nlatest_release=$(cat release.yaml | yq e '.spec.releases[] | select(.version == \"'$latest_release_version'\")' >> latest_release.yaml)\n\nfor os in darwin linux\ndo\n  KEY_URL=\"${os}_url\"\n  KEY_SHA=\"${os}_sha256\"\n  export $KEY_URL=$(cat latest_release.yaml | yq e \".eksABinary.${os}.uri\")\n  export $KEY_SHA=$(cat latest_release.yaml | yq e \".eksABinary.${os}.sha256\")\ndone\n\n# removes the char v from string like => v1.0.1\nlatest_release_version=\"${latest_release_version:1}\"\nexport VERSION=$latest_release_version\n\nEKSA_TEMPLATE=\"eks-anywhere.rb.tmpl\"\nEKSA_FORMULA=\"${SCRIPT_ROOT}/../../../${ORIGIN_ORG}/${REPO}/Formula/eks-anywhere.rb\"\n\nif [ ! -f \"$EKSA_TEMPLATE\" ]\nthen\n  echo \"Template file ${EKSA_TEMPLATE} does not exist in this working folder, exiting..\"\n  exit 1\nfi\n\nif [ ! -f \"$EKSA_FORMULA\" ]\nthen\n  echo \"Can not find the ${EKSA_FORMULA} file, exiting..\"\n  exit 1\nfi\n\nenvsubst '$VERSION:$darwin_url:$darwin_sha256:$linux_url:$linux_sha256' \\\n < \"${EKSA_TEMPLATE}\" \\\n > \"${EKSA_FORMULA}\"\n\necho \"v${VERSION}\"\n\nrm release.yaml\nrm latest_release.yaml\n", "num_lines": 68}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction build::common::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  elif which gnutar &>/dev/null; then\n      TAR=gnutar\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\n# Build a release tarball.  $1 is the output tar name.  $2 is the base directory\n# of the files to be packaged.  This assumes that ${2}/kubernetes is what is\n# being packaged.\nfunction build::common::create_tarball() {\n  build::common::ensure_tar\n\n  local -r tarfile=$1\n  local -r stagingdir=$2\n  local -r repository=$3\n\n  \"${TAR}\" czf \"${tarfile}\" -C \"${stagingdir}\" $repository --owner=0 --group=0\n}\n\n# Generate shasum of tarballs. $1 is the directory of the tarballs.\nfunction build::common::generate_shasum() {\n\n  local -r tarpath=$1\n\n  echo \"Writing artifact hashes to shasum files...\"\n\n  if [ ! -d \"$tarpath\" ]; then\n    echo \"  Unable to find tar directory $tarpath\"\n    exit 1\n  fi\n\n  cd $tarpath\n  for file in $(find . -name '*.tar.gz'); do\n    filepath=$(basename $file)\n    sha256sum \"$filepath\" > \"$file.sha256\"\n    sha512sum \"$filepath\" > \"$file.sha512\"\n  done\n  cd -\n}\n\nfunction build::common::upload_artifacts() {\n  local -r artifactspath=$1\n  local -r artifactsbucket=$2\n  local -r projectpath=$3\n  local -r buildidentifier=$4\n  local -r githash=$5\n  local -r latestpath=$6\n\n  echo \"$githash\" >> \"$artifactspath\"/githash\n\n  # Upload artifacts to s3\n  # 1. To proper path on s3 with buildId-githash\n  # 2. Latest path to indicate the latest build, with --delete option to delete stale files in the dest path\n  aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$buildidentifier\"-\"$githash\"/artifacts --acl public-read\n  aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$latestpath\" --delete --acl public-read\n}\n\nfunction build::gather_licenses() {\n  # force 1.16 since thats the version used to install go-licenses in builder-base\n  build::common::use_go_version 1.18\n  if ! command -v go-licenses &> /dev/null\n  then\n    echo \" go-licenses not found.  If you need license or attribtuion file handling\"\n    echo \" please refer to the doc in docs/development/attribution-files.md\"\n    exit\n  fi\n\n  local -r outputdir=$1\n  local -r patterns=$2\n\n\n  # Force deps to only be pulled form vendor directories\n  # this is important in a couple cases where license files\n  # have to be manually created\n  export GOFLAGS=-mod=vendor\n  # force platform to be linux to ensure all deps are picked up\n  export GOOS=linux\n  export GOARCH=amd64\n\n  mkdir -p \"${outputdir}/attribution\"\n  # attribution file generated uses the output go-deps and go-license to gather the neccessary\n  # data about each dependency to generate the amazon approved attribution.txt files\n  # go-deps is needed for module versions\n  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns\n  go list -deps=true -json ./... | jq -s ''  > \"${outputdir}/attribution/go-deps.json\"\n\n  go-licenses save --force $patterns --save_path=\"${outputdir}/LICENSES\"\n\n  # go-licenses can be a bit noisy with its output and lot of it can be confusing\n  # the following messags are safe to ignore since we do not need the license url for our process\n  NOISY_MESSAGES=\"cannot determine URL for|Error discovering URL|unsupported package host\"\n  go-licenses csv $patterns > \"${outputdir}/attribution/go-license.csv\" 2>  >(grep -vE \"$NOISY_MESSAGES\" >&2)\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -q \"^vendor\\/golang.org\\/x\"; then\n      echo \" go-licenses created a file with a std golang package (golang.org/x/*)\"\n      echo \" prefixed with vendor/.  This most likely will result in an error\"\n      echo \" when generating the attribution file and is probably due to\"\n      echo \" to a version mismatch between the current version of go \"\n      echo \" and the version of go that was used to build go-licenses\"\n      exit 1\n  fi\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n  fi\n\n\n  # go-license is pretty eager to copy src for certain license types\n  # when it does, it applies strange permissions to the copied files\n  # which makes deleting them later awkward\n  # this behavior may change in the future with the following PR\n  # https://github.com/google/go-licenses/pull/28\n  chmod -R 777 \"${outputdir}/LICENSES\"\n\n  # most of the packages show up the go-license.csv file as the module name\n  # from the go.mod file, storing that away since the source dirs usually get deleted\n  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')\n  echo $MODULE_NAME > ${outputdir}/attribution/root-module.txt\n}\n\nfunction build::generate_attribution(){\n  local -r golang_verson=$1\n  local -r output_directory=${2:-\"_output\"}\n  local -r attribution_file=${3:-\"ATTRIBUTION.txt\"}\n\n  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)\n  local -r go_path=$(build::common::get_go_path $golang_verson)\n  local -r golang_version_tag=$($go_path/go version | grep -o \"go[0-9].* \")\n\n  if cat \"${output_directory}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  generate-attribution $root_module_name \"./\" $golang_version_tag $output_directory\n  cp -f \"${output_directory}/attribution/ATTRIBUTION.txt\" $attribution_file\n}\n\nfunction build::common::remove_go_path() {\n  # This is the path where the specific go binary versions reside in our builder-base image\n  export PATH=$(echo \"$PATH\" | sed -e \"s/^\\/go\\/go[0-9\\.]*\\/bin://\")\n\n  # This is the path that will most likely be correct if running locally\n  local -r quoted_go_path=$(build::common::re_quote $GOPATH)\n  export PATH=$(echo \"$PATH\" | sed -e \"s/^$quoted_go_path\\/go[0-9\\.]*\\/bin://\")\n}\n\nfunction build::common::get_go_path() {\n  local -r version=$1\n\n  # This is the path where the specific go binary versions reside in our builder-base image\n  local -r gorootbinarypath=\"/go/go${version}/bin\"\n  # This is the path that will most likely be correct if running locally\n  local -r gopathbinarypath=\"$GOPATH/go${version}/bin\"\n  if [ -d \"$gorootbinarypath\" ]; then\n    echo $gorootbinarypath\n  elif [ -d \"$gopathbinarypath\" ]; then\n    echo $gopathbinarypath\n  else\n    # not in builder-base, probably running in dev environment\n    # return default go installation\n    local -r which_go=$(which go)\n    echo \"$(dirname $which_go)\"\n  fi\n}\n\nfunction build::common::use_go_version() {\n  local -r version=$1\n\n  local -r gobinarypath=$(build::common::get_go_path $version)\n  echo \"Adding $gobinarypath to PATH\"\n  # Adding to the beginning of PATH to allow for builds on specific version if it exists\n  export PATH=${gobinarypath}:$PATH\n}\n\nfunction build::common::re_quote() {\n    local -r to_escape=$1\n    sed 's/[][()\\.^$\\/?*+]/\\\\&/g' <<< \"$to_escape\"\n}\n", "num_lines": 212}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nREPO=\"eks-anywhere\"\nORIGIN_ORG=\"eks-distro-pr-bot\"\nUPSTREAM_ORG=\"aws\"\n\nPR_TITLE=\"Update ATTRIBUTION.txt file\"\nCOMMIT_MESSAGE=\"[PR BOT] Update ATTRIBUTION.txt file\"\n\nPR_BODY=$(cat <<EOF\nThis PR updates the ATTRIBUTION.txt file if there have been changes.\n\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\nEOF\n)\n\nPR_BRANCH=\"attribution-files-update\"\n\ncd ${SCRIPT_ROOT}/..\ngit config --global push.default current\ngit config user.name \"EKS Distro PR Bot\"\ngit config user.email \"aws-model-rocket-bots+eksdistroprbot@amazon.com\"\ngit remote add origin git@github.com:${ORIGIN_ORG}/${REPO}.git\ngit remote add upstream git@github.com:${UPSTREAM_ORG}/${REPO}.git\ngit checkout -b $PR_BRANCH\n\ngit diff\ngit add ATTRIBUTION.txt\n# If some other files get modified, the changes should be ignored\ngit restore .\nFILES_ADDED=$(git diff --staged --name-only)\nif [ \"$FILES_ADDED\" = \"\" ]; then\n    exit 0\nfi\n\ngit commit -m \"$COMMIT_MESSAGE\"\nssh-agent bash -c 'ssh-add /secrets/ssh-secrets/ssh-privatekey; ssh -o StrictHostKeyChecking=no git@github.com; git fetch upstream; git rebase -Xtheirs upstream/main; git push -u origin $PR_BRANCH -f'\n\ngh auth login --with-token < /secrets/github-secrets/token\n\nPR_EXISTS=$(gh pr list | grep -c \"${PR_BRANCH}\" || true)\nif [ $PR_EXISTS -eq 0 ]; then\n  gh pr create --title \"$PR_TITLE\" --body \"$PR_BODY\"\nfi\n", "num_lines": 63}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nif [ \"$TEST_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty TEST_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\n\ncat << EOF > config_file\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n[profile e2e-cleanup]\nrole_arn=$TEST_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nsource_profile=default\nEOF\nexport AWS_SDK_LOAD_CONFIG=true\nexport AWS_CONFIG_FILE=$(pwd)/config_file\nexport AWS_PROFILE=e2e-cleanup\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n$REPO_ROOT/bin/test e2e cleanup aws \\\n   -s ${INTEGRATION_TEST_STORAGE_BUCKET} \\\n   -a ${INTEGRATION_TEST_MAX_INSTANCE_AGE} \\\n   -t ${INTEGRATION_TEST_INSTANCE_TAG} \\\n   -v 4", "num_lines": 47}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\ndelete_cluster_controller_image() {\n    aws ecr-public batch-delete-image --repository-name eks-anywhere-cluster-controller --image-ids=imageTag=${PULL_PULL_SHA}.${PULL_BASE_REF} --region us-east-1\n}\n\ntrap 'unset AWS_PROFILE; delete_cluster_controller_image' EXIT\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nif [ \"$TEST_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty TEST_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nBIN_FOLDER=$REPO_ROOT/bin\nTEST_REGEX=\"${1:-TestDockerKubernetes121SimpleFlow}\"\nBRANCH_NAME=\"${2:-main}\"\n\ncat << EOF > config_file\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n[profile e2e-docker-test]\nrole_arn=$TEST_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nsource_profile=default\nEOF\n\nINTEGRATION_TEST_INFRA_CONFIG=\"/tmp/test-infra.yml\"\nexport T_TINKERBELL_S3_INVENTORY_CSV_KEY=\"inventory/den80/den80-hardware.csv\"\n\ncat << EOF > ${INTEGRATION_TEST_INFRA_CONFIG}\n---\n\nec2:\n  amiId: ${INTEGRATION_TEST_AL2_AMI_ID}\n  subnetId:\n\nEOF\n\nexport AWS_SDK_LOAD_CONFIG=true\nexport AWS_CONFIG_FILE=$(pwd)/config_file\nexport AWS_PROFILE=e2e-docker-test\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n\nBUNDLES_OVERRIDE=false\nif [ -f \"$BIN_FOLDER/local-bundle-release.yaml\" ]; then\n    BUNDLES_OVERRIDE=true\nfi\n\n# In order to be uploaded from the sidecar and used by the junit lens\n# the junit reports need to be in /logs/*/junit*.xml\nTEST_REPORT_FOLDER=/logs/artifacts\n\n$BIN_FOLDER/test e2e run \\\n    -c ${INTEGRATION_TEST_INFRA_CONFIG} \\\n    -s ${INTEGRATION_TEST_STORAGE_BUCKET} \\\n    -j ${JOB_ID} \\\n    -i ${INTEGRATION_TEST_INSTANCE_PROFILE} \\\n    -r ${TEST_REGEX} \\\n    --bundles-override=${BUNDLES_OVERRIDE} \\\n    --test-report-folder=${TEST_REPORT_FOLDER} \\\n    -v4\n\n# Faking cross-platform versioned folders for dry-run\nmkdir -p $BIN_FOLDER/linux/amd64\ncp $BIN_FOLDER/eksctl-anywhere $BIN_FOLDER/linux/amd64/eksctl-anywhere\n\n$REPO_ROOT/cmd/integration_test/build/script/upload_artifacts.sh \\\n    \"s3://artifacts-bucket\" \\\n    $REPO_ROOT \\\n    \"eks-a-cli\" \\\n    $PROW_JOB_ID \\\n    $PULL_PULL_SHA \\\n    \"linux\" \\\n    \"amd64\" \\\n    $BRANCH_NAME \\\n    true\n", "num_lines": 104}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\nset -o nounset\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nBUNDLE_MANIFEST_URL=\"$1\"\nCLUSTER_CONTROLLER_OVERRIDE_IMAGE=\"$2\"\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\nif ! yq --version; then\n    echo \"Cannot find yq executable. Build on Linux\"\n    echo \"or install yq on Mac (brew install yq).\"\n    exit 1\nfi\n\nmkdir -p $REPO_ROOT/bin\nmake release-manifests RELEASE_DIR=$REPO_ROOT/bin RELEASE_MANIFEST_TARGET=local-eksa-components.yaml\ncurl $BUNDLE_MANIFEST_URL -o $REPO_ROOT/bin/local-bundle-release.yaml\n$SED -i \"s,public.ecr.aws/.*/eks-anywhere-cluster-controller:.*,${CLUSTER_CONTROLLER_OVERRIDE_IMAGE},\" $REPO_ROOT/bin/local-eksa-components.yaml\nyq e -i '.spec.versionsBundles[].eksa.components.uri |= \"bin/local-eksa-components.yaml\"' $REPO_ROOT/bin/local-bundle-release.yaml\n", "num_lines": 41}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nSHASUM_FILES=\"shasums-eksctl-anywhere\"\n\n#Clean up any existing old folders for shasum files\nif [ -d \"$SHASUM_FILES\" ]; then rm -Rf $SHASUM_FILES; fi\n\nYQ_LATEST_RELEASE_URL=\"https://github.com/mikefarah/yq/releases/latest\"\n\nif ! command -v yq &> /dev/null\nthen\n    echo \"Please install YQ from $YQ_LATEST_RELEASE_URL and rerun this script.\"\n    exit\nfi\n\necho \"YQ is installed, continuing..\"\n\nFILE_PREFIX=\"eksctl-anywhere\"\n\nTAR=\"amd64.tar.gz\"\n\n\nCURRENT_YQ_VERSION=$(yq -V | awk '{print $NF}')\n\nversionSplit=($(echo $CURRENT_YQ_VERSION | tr \".\" \"\\n\"))\nCURRENT_YQ_MAJOR_VERSION=${versionSplit[0]}\nCURRENT_YQ_MINOR_VERSION=${versionSplit[1]}\nEXPECTED_YQ_MAJOR_VERSION=4\nEXPECTED_YQ_MINOR_VERSION=18\n\nif [ $CURRENT_YQ_MAJOR_VERSION -lt $EXPECTED_YQ_MAJOR_VERSION ]; then\n    echo \"ERROR: Current yq major version v$CURRENT_YQ_MAJOR_VERSION.x is older than expected v$EXPECTED_YQ_MAJOR_VERSION.x\"\n    echo \"Please install the latest version of yq from $YQ_LATEST_RELEASE_URL\"\n    exit 1\nfi\n\nif [ $CURRENT_YQ_MAJOR_VERSION == $EXPECTED_YQ_MAJOR_VERSION ] && [ $CURRENT_YQ_MINOR_VERSION -lt $EXPECTED_YQ_MINOR_VERSION ]; then\n    echo \"ERROR: Current yq minor version v$CURRENT_YQ_MAJOR_VERSION.$CURRENT_YQ_MINOR_VERSION.x is older than expected v$EXPECTED_YQ_MAJOR_VERSION.$EXPECTED_YQ_MINOR_VERSION.x\"\n    echo \"Please install the latest version of yq from $YQ_LATEST_RELEASE_URL\"\n    exit 1\nfi\n\nmkdir -p $SHASUM_FILES\ncd $SHASUM_FILES\ncurl --silent 'https://anywhere-assets.eks.amazonaws.com/releases/eks-a/manifest.yaml' -o release.yaml\n\nlatest_release_version=$(cat release.yaml | yq e '.spec.latestVersion')\n\nlatest_release=$(cat release.yaml | yq e '.spec.releases[] | select(.version == \"'$latest_release_version'\")' >> latest_release.yaml)\n\nfor sha in 256 512\ndo\n  for os in linux darwin\n  do\n    SHA_VALUE=$(cat latest_release.yaml | yq e \".eksABinary.${os}.sha${sha}\")\n    echo \"${SHA_VALUE}  ${FILE_PREFIX}-${latest_release_version}-${os}-${TAR}\" >> \"${FILE_PREFIX}-${latest_release_version}-sha${sha}sums.txt\"\n  done\ndone\n\necho \"Generated the check sum files inside the ${SHASUM_FILES} folder at the directory where you ran this script from.\"\n\nrm release.yaml\nrm latest_release.yaml\n", "num_lines": 76}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\nset -o pipefail\n\nbundle_number=$(cat \"${CODEBUILD_SRC_DIR}/release/triggers/bundle-release/development/BUNDLE_NUMBER\")\nbundle_url=\"https://beta-assets.eks-anywhere.model-rocket.aws.dev/releases/bundles/${bundle_number}/manifest.yaml\"\nwget -O \"${CODEBUILD_SRC_DIR}/bin/local-bundle-release.yaml\" \"${bundle_url}\"\n", "num_lines": 23}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Echo the names of go packages modified in the differences between the\n# working tree and the AWS main branch in github.\n\n# This is useful for limiting testing runs.\n\nset -euo pipefail\n\nfunction awsRemote () {\n    git remote -v \\\n\t| grep \"github.com[:/]aws/eks-anywhere.git\" \\\n\t| head -n 1 \\\n\t| awk '{print $1}' \\\n\t| tr -d '\\n'\n}\n\nref=\"$(awsRemote)/main\"\n\n{\n    set +e\n    git diff --stat --name-only \"$ref...HEAD\"\n    git status --untracked-files=normal --short | awk '{ print $NF }'\n} | grep .\\.go\\$ \\\n    | xargs -r -n1 dirname \\\n    | sort \\\n    | uniq \\\n    | sed -e 's,^,./,' \\\n    | tr '\\n' ' '\n\necho\n\n", "num_lines": 33}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nREPO=\"eks-anywhere\"\nORIGIN_ORG=\"eks-distro-pr-bot\"\nUPSTREAM_ORG=\"aws\"\n\nPR_TITLE=\"Generate release testdata files\"\nCOMMIT_MESSAGE=\"[PR BOT] Generate release testdata files\"\n\nPR_BODY=$(cat <<EOF\nGenerate release testdata files.\n\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\nEOF\n)\n\nPR_BRANCH=\"update-release-test-file\"\n\ncd ${SCRIPT_ROOT}/..\ngit config --global push.default current\ngit config user.name \"EKS Distro PR Bot\"\ngit config user.email \"aws-model-rocket-bots+eksdistroprbot@amazon.com\"\ngit remote add origin git@github.com:${ORIGIN_ORG}/${REPO}.git\ngit remote add upstream git@github.com:${UPSTREAM_ORG}/${REPO}.git\ngit checkout -b $PR_BRANCH\n\ngit diff\ngit add release/pkg/test/testdata/*.yaml\n# If some other files get modified, the changes should be ignored\ngit restore .\nFILES_ADDED=$(git diff --staged --name-only)\nif [ \"$FILES_ADDED\" = \"\" ]; then\n    exit 0\nfi\n\ngit commit -m \"$COMMIT_MESSAGE\"\nssh-agent bash -c 'ssh-add /secrets/ssh-secrets/ssh-privatekey; ssh -o StrictHostKeyChecking=no git@github.com; git fetch upstream; git rebase -Xtheirs upstream/main; git push -u origin $PR_BRANCH -f'\n\ngh auth login --with-token < /secrets/github-secrets/token\n\nPR_EXISTS=$(gh pr list | grep -c \"${PR_BRANCH}\" || true)\nif [ $PR_EXISTS -eq 0 ]; then\n  gh pr create --title \"$PR_TITLE\" --body \"$PR_BODY\"\nfi\n", "num_lines": 63}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\nset -o errexit\nset -o pipefail\n\nGOLANG_VERSION=\"$1\"\nREPO_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../\" && pwd -P)\"\nif [ \"$CI\" = \"true\" ]; then\n    # Prow clone process does not add remote so we have to explicitly add\n    # it. Setting it to HTTPS URL for go-licenses \n    git remote add origin https://github.com/$REPO_OWNER/eks-anywhere.git\nelse\n    # go-licenses supports only HTTPS URLs so if the CLI repo is cloned locally \n    # with SSH URL, we need to temporarily override the remote URL for go-licenses\n    # to work as expected\n    ORIGIN_URL=$(git remote get-url origin)\n    if [[ \"$ORIGIN_URL\" =~ \"git@github.com\" ]]; then\n        CLONE_METHOD=\"ssh\"\n        REPO_OWNER=\"$(dirname $ORIGIN_URL | cut -d':' -f2)\"\n        git remote set-url origin https://github.com/${REPO_OWNER}/eks-anywhere.git\n    else\n        CLONE_METHOD=\"https\"\n    fi\nfi\n\nsource \"$REPO_ROOT/scripts/common.sh\"\nsource \"$REPO_ROOT/scripts/attribution_helpers.sh\"\n\nfunction build::attribution::generate(){\n    cd $REPO_ROOT\n    $(build::common::get_go_path \"$GOLANG_VERSION\")/go mod vendor\n    build::create_git_tag\n    build::fix_licenses\n    build::gather_licenses _output \"./cmd/eksctl-anywhere ./controllers\"\n    build::exclude_own\n    build::generate_attribution $GOLANG_VERSION\n    # Removing temporary override by resetting remote origin URL to original SSH url \n    if [ \"$CI\" != \"true\" ] && [ \"$CLONE_METHOD\" = \"ssh\" ]; then\n        git remote set-url origin $ORIGIN_URL\n    elif [ \"$CI\" = \"true\" ] && [ \"$JOB_TYPE\" = \"periodic\" ]; then\n        git remote remove origin\n    fi\n    rm -rf _output bin vendor GIT_TAG\n}\n\nbuild::attribution::generate\n", "num_lines": 62}
{"repo_name": "eks-anywhere", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -e\nset -o pipefail\n\nif [ ! -d \"/root/.docker\" ]; then\n    mkdir -p /root/.docker\nfi\nmv manager/config/docker-ecr-config.json /root/.docker/config.json\ngit config --global credential.helper '!aws codecommit credential-helper $@'\ngit config --global credential.UseHttpPath true\n", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBASE_DIRECTORY=\"${1?Specify first argument - Base directory of build-tooling repo}\"\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\n# Iterating over orgs under projects folder\nfor org_path in projects/*; do\n    org=$(basename \"$org_path\")\n    for repo_path in projects/$org/*; do\n        repo=$(basename \"$repo_path\")\n        # couple odd ball non-builds in this repo\n        if [[ -f $repo_path/DO_NOT_BUILD ]]; then\n            continue\n        fi\n        echo -n \"${org}_${repo} \"\n    done\ndone\n\necho\n", "num_lines": 39}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBUILD_LIB_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/\" && pwd -P)\"\n\nCMD=\"buildctl\"\nif [ -f \"/buildkit.sh\" ] && ! buildctl debug workers >/dev/null 2>&1; then\n    # on the builder base this helper file exists to run buildkitd\n    # in prow buildkitd is run as a seperate container so it will be running already\n    # in codebuild its run directly on the instance so we want to use this helper\n    CMD=\"/buildkit.sh\"\n\nfi\n# From time to time we see random failures when creating/pushing images that fix on reruning the job\n# this is an attempt to avoid failing key jobs, like the release job, with a flaky failure\n# If running in builder base, most likely we are running in prow/codebuild, us retry logic\n# if not in builder base, probably running locally so skip the retry\nif [ -f \"/buildkit.sh\" ]; then\n    for i in $(seq 1 5); do\n        [ $i -gt 1 ] && sleep 15\n        $CMD \"$@\" && s=0 && break || s=$?\n    done\n\n    # space is limited on presubmit nodes, after each image build clear the build cache\n    if [ \"${JOB_TYPE:-}\" == \"presubmit\" ] && [ \"${PRUNE_BUILDCTL:-false}\" == \"true\" ]; then\n        $CMD prune --all\n    fi\n\n    (exit $s)\nelse\n    # skip retry when running locally\n    log_file=$(mktemp)\n    trap \"rm -f $log_file\" EXIT\n    if ! $CMD \"$@\" 2>&1 | tee $log_file; then        \n        if grep -q \"blobs/uploads/\\\": EOF\" $log_file ; then\n            echo \"******************************************************\"\n            echo \"Ensure container registry and repository exists!!\"\n            echo \"Try running make create-ecr-repos to create ecr repositories in your aws account.\"\n            echo \"******************************************************\"\n        fi\n        exit 1\n    fi\nfi\n", "num_lines": 60}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfunction buildkit_ready() {\n  for i in {1..24}\n  do\n    if [ ! -S \"/run/buildkit/buildkitd.sock\" ]\n    then\n      echo \"Buildkit daemon is not running. Retrying.\"\n      sleep 5s\n    else\n      exit 0\n    fi\n  done\n  echo \"Buildkit daemon is not available\"\n  exit 1\n}\n\nbuildkit_ready", "num_lines": 31}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2015 The Kubernetes Authors.\n# - https://github.com/kubernetes/kubernetes/blob/master/hack/cherry_pick_pull.sh\n# Modifications Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. Licensed under the Apache2 License\n\n# Modifications:\n# - changed instructions link to doc in this repo instead of upstream\n# - harcoded MAIN_REPO_ORG and MAIN_REPO_NAME to avoid difference with awk on mac vs linux\n\n# Usage Instructions: https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md\n\n# Checkout a PR from GitHub. (Yes, this is sitting in a Git tree. How\n# meta.) Assumes you care about pulls from remote \"upstream\" and\n# checks them out to a branch named:\n#  automated-cherry-pick-of-<pr>-<target branch>-<timestamp>\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO_ROOT=\"$(git rev-parse --show-toplevel)\"\ndeclare -r REPO_ROOT\ncd \"${REPO_ROOT}\"\n\nSTARTINGBRANCH=$(git symbolic-ref --short HEAD)\ndeclare -r STARTINGBRANCH\ndeclare -r REBASEMAGIC=\"${REPO_ROOT}/.git/rebase-apply\"\nDRY_RUN=${DRY_RUN:-\"\"}\nREGENERATE_DOCS=${REGENERATE_DOCS:-\"\"}\nUPSTREAM_REMOTE=${UPSTREAM_REMOTE:-upstream}\nFORK_REMOTE=${FORK_REMOTE:-origin}\nMAIN_REPO_ORG=aws # ${MAIN_REPO_ORG:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $3}')}\nMAIN_REPO_NAME=eks-anywhere-build-tooling # ${MAIN_REPO_NAME:-$(git remote get-url \"$UPSTREAM_REMOTE\" | awk '{gsub(/http[s]:\\/\\/|git@/,\"\")}1' | awk -F'[@:./]' 'NR==1{print $4}')}\n\nif [[ -z ${GITHUB_USER:-} ]]; then\n  echo \"Please export GITHUB_USER=<your-user> (or GH organization, if that's where your fork lives)\"\n  exit 1\nfi\n\nif ! command -v gh > /dev/null; then\n  echo \"Can't find 'gh' tool in PATH, please install from https://github.com/cli/cli\"\n  exit 1\nfi\n\nif [[ \"$#\" -lt 2 ]]; then\n  echo \"${0} <remote branch> <pr-number>...: cherry pick one or more <pr> onto <remote branch> and leave instructions for proposing pull request\"\n  echo\n  echo \"  Checks out <remote branch> and handles the cherry-pick of <pr> (possibly multiple) for you.\"\n  echo \"  Examples:\"\n  echo \"    $0 upstream/release-3.14 12345        # Cherry-picks PR 12345 onto upstream/release-3.14 and proposes that as a PR.\"\n  echo \"    $0 upstream/release-3.14 12345 56789  # Cherry-picks PR 12345, then 56789 and proposes the combination as a single PR.\"\n  echo\n  echo \"  Set the DRY_RUN environment var to skip git push and creating PR.\"\n  echo \"  This is useful for creating patches to a release branch without making a PR.\"\n  echo \"  When DRY_RUN is set the script will leave you in a branch containing the commits you cherry-picked.\"\n  echo\n  echo \"  Set the REGENERATE_DOCS environment var to regenerate documentation for the target branch after picking the specified commits.\"\n  echo \"  This is useful when picking commits containing changes to API documentation.\"\n  echo\n  echo \"  Set UPSTREAM_REMOTE (default: upstream) and FORK_REMOTE (default: origin)\"\n  echo \"  to override the default remote names to what you have locally.\"\n  echo\n  echo \"  For merge process info, see https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md\"\n  exit 2\nfi\n\n# Checks if you are logged in. Will error/bail if you are not.\ngh auth status\n\nif git_status=$(git status --porcelain --untracked=no 2>/dev/null) && [[ -n \"${git_status}\" ]]; then\n  echo \"!!! Dirty tree. Clean up and try again.\"\n  exit 1\nfi\n\nif [[ -e \"${REBASEMAGIC}\" ]]; then\n  echo \"!!! 'git rebase' or 'git am' in progress. Clean up and try again.\"\n  exit 1\nfi\n\ndeclare -r BRANCH=\"$1\"\nshift 1\ndeclare -r PULLS=( \"$@\" )\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\nPULLDASH=$(join - \"${PULLS[@]/#/#}\") # Generates something like \"#12345-#56789\"\ndeclare -r PULLDASH\nPULLSUBJ=$(join \" \" \"${PULLS[@]/#/#}\") # Generates something like \"#12345 #56789\"\ndeclare -r PULLSUBJ\n\necho \"+++ Updating remotes...\"\ngit remote update \"${UPSTREAM_REMOTE}\" \"${FORK_REMOTE}\"\n\nif ! git log -n1 --format=%H \"${BRANCH}\" >/dev/null 2>&1; then\n  echo \"!!! '${BRANCH}' not found. The second argument should be something like ${UPSTREAM_REMOTE}/release-0.21.\"\n  echo \"    (In particular, it needs to be a valid, existing remote branch that I can 'git checkout'.)\"\n  exit 1\nfi\n\nNEWBRANCHREQ=\"automated-cherry-pick-of-${PULLDASH}\" # \"Required\" portion for tools.\ndeclare -r NEWBRANCHREQ\nNEWBRANCH=\"$(echo \"${NEWBRANCHREQ}-${BRANCH}\" | sed 's/\\//-/g')\"\ndeclare -r NEWBRANCH\nNEWBRANCHUNIQ=\"${NEWBRANCH}-$(date +%s)\"\ndeclare -r NEWBRANCHUNIQ\necho \"+++ Creating local branch ${NEWBRANCHUNIQ}\"\n\ncleanbranch=\"\"\ngitamcleanup=false\nfunction return_to_kansas {\n  if [[ \"${gitamcleanup}\" == \"true\" ]]; then\n    echo\n    echo \"+++ Aborting in-progress git am.\"\n    git am --abort >/dev/null 2>&1 || true\n  fi\n\n  # return to the starting branch and delete the PR text file\n  if [[ -z \"${DRY_RUN}\" ]]; then\n    echo\n    echo \"+++ Returning you to the ${STARTINGBRANCH} branch and cleaning up.\"\n    git checkout -f \"${STARTINGBRANCH}\" >/dev/null 2>&1 || true\n    if [[ -n \"${cleanbranch}\" ]]; then\n      git branch -D \"${cleanbranch}\" >/dev/null 2>&1 || true\n    fi\n  fi\n}\ntrap return_to_kansas EXIT\n\nSUBJECTS=()\nfunction make-a-pr() {\n  local rel\n  rel=\"$(basename \"${BRANCH}\")\"\n  echo\n  echo \"+++ Creating a pull request on GitHub at ${GITHUB_USER}:${NEWBRANCH}\"\n\n  local numandtitle\n  numandtitle=$(printf '%s\\n' \"${SUBJECTS[@]}\")\n  prtext=$(cat <<EOF\nCherry pick of ${PULLSUBJ} on ${rel}.\n\n${numandtitle}\n\nFor details on the cherry pick process, see the [cherry pick requests](https://github.com/aws/eks-anywhere-build-tooling/tree/main/docs/development/cherry-picks.md) page.\n\n\\`\\`\\`release-note\n\n\\`\\`\\`\nEOF\n)\n\n  gh pr create --title=\"Automated cherry pick of ${numandtitle}\" --body=\"${prtext}\" --head \"${GITHUB_USER}:${NEWBRANCH}\" --base \"${rel}\" --repo=\"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}\"\n}\n\ngit checkout -b \"${NEWBRANCHUNIQ}\" \"${BRANCH}\"\ncleanbranch=\"${NEWBRANCHUNIQ}\"\n\ngitamcleanup=true\nfor pull in \"${PULLS[@]}\"; do\n  echo \"+++ Downloading patch to /tmp/${pull}.patch (in case you need to do this again)\"\n\n  curl -o \"/tmp/${pull}.patch\" -sSL \"https://github.com/${MAIN_REPO_ORG}/${MAIN_REPO_NAME}/pull/${pull}.patch\"\n  echo\n  echo \"+++ About to attempt cherry pick of PR. To reattempt:\"\n  echo \"  $ git am -3 /tmp/${pull}.patch\"\n  echo\n  git am -3 \"/tmp/${pull}.patch\" || {\n    conflicts=false\n    while unmerged=$(git status --porcelain | grep ^U) && [[ -n ${unmerged} ]] \\\n      || [[ -e \"${REBASEMAGIC}\" ]]; do\n      conflicts=true # <-- We should have detected conflicts once\n      echo\n      echo \"+++ Conflicts detected:\"\n      echo\n      (git status --porcelain | grep ^U) || echo \"!!! None. Did you git am --continue?\"\n      echo\n      echo \"+++ Please resolve the conflicts in another window (and remember to 'git add / git am --continue')\"\n      read -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\n      echo\n      if ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n        echo \"Aborting.\" >&2\n        exit 1\n      fi\n    done\n\n    if [[ \"${conflicts}\" != \"true\" ]]; then\n      echo \"!!! git am failed, likely because of an in-progress 'git am' or 'git rebase'\"\n      exit 1\n    fi\n  }\n\n  # set the subject\n  subject=$(grep -m 1 \"^Subject\" \"/tmp/${pull}.patch\" | sed -e 's/Subject: \\[PATCH//g' | sed 's/.*] //')\n  SUBJECTS+=(\"#${pull}: ${subject}\")\n\n  # remove the patch file from /tmp\n  rm -f \"/tmp/${pull}.patch\"\ndone\ngitamcleanup=false\n\n# Re-generate docs (if needed)\nif [[ -n \"${REGENERATE_DOCS}\" ]]; then\n  echo\n  echo \"Regenerating docs...\"\n  if ! hack/generate-docs.sh; then\n    echo\n    echo \"hack/generate-docs.sh FAILED to complete.\"\n    exit 1\n  fi\nfi\n\nif [[ -n \"${DRY_RUN}\" ]]; then\n  echo \"!!! Skipping git push and PR creation because you set DRY_RUN.\"\n  echo \"To return to the branch you were in when you invoked this script:\"\n  echo\n  echo \"  git checkout ${STARTINGBRANCH}\"\n  echo\n  echo \"To delete this branch:\"\n  echo\n  echo \"  git branch -D ${NEWBRANCHUNIQ}\"\n  exit 0\nfi\n\nif git remote -v | grep ^\"${FORK_REMOTE}\" | grep \"${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"; then\n  echo \"!!! You have ${FORK_REMOTE} configured as your ${MAIN_REPO_ORG}/${MAIN_REPO_NAME}.git\"\n  echo \"This isn't normal. Leaving you with push instructions:\"\n  echo\n  echo \"+++ First manually push the branch this script created:\"\n  echo\n  echo \"  git push REMOTE ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\n  echo\n  echo \"where REMOTE is your personal fork (maybe ${UPSTREAM_REMOTE}? Consider swapping those.).\"\n  echo \"OR consider setting UPSTREAM_REMOTE and FORK_REMOTE to different values.\"\n  echo\n  make-a-pr\n  cleanbranch=\"\"\n  exit 0\nfi\n\necho\necho \"+++ I'm about to do the following to push to GitHub (and I'm assuming ${FORK_REMOTE} is your personal fork):\"\necho\necho \"  git push ${FORK_REMOTE} ${NEWBRANCHUNIQ}:${NEWBRANCH}\"\necho\nread -p \"+++ Proceed (anything but 'y' aborts the cherry-pick)? [y/n] \" -r\nif ! [[ \"${REPLY}\" =~ ^[yY]$ ]]; then\n  echo \"Aborting.\" >&2\n  exit 1\nfi\n\ngit push \"${FORK_REMOTE}\" -f \"${NEWBRANCHUNIQ}:${NEWBRANCH}\"\nmake-a-pr\n", "num_lines": 252}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nBUILD_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/\" && pwd -P)\"\nsource \"${BUILD_ROOT}/eksd_releases.sh\"\n\nif [ -n \"${OUTPUT_DEBUG_LOG:-}\" ]; then\n    set -x\nfi\n\n\nfunction build::common::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  elif which gnutar &>/dev/null; then\n      TAR=gnutar\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\n# Build a release tarball.  $1 is the output tar name.  $2 is the base directory\n# of the files to be packaged.  This assumes that ${2}/kubernetes is what is\n# being packaged.\nfunction build::common::create_tarball() {\n  build::common::ensure_tar\n\n  local -r tarfile=$1\n  local -r stagingdir=$2\n  local -r repository=$3\n\n  build::common::echo_and_run \"${TAR}\" czf \"${tarfile}\" -C \"${stagingdir}\" $repository --owner=0 --group=0\n}\n\n# Generate shasum of tarballs. $1 is the directory of the tarballs.\nfunction build::common::generate_shasum() {\n\n  local -r tarpath=$1\n\n  echo \"Writing artifact hashes to shasum files...\"\n\n  if [ ! -d \"$tarpath\" ]; then\n    echo \"  Unable to find tar directory $tarpath\"\n    exit 1\n  fi\n\n  cd $tarpath\n  for file in $(find . -name '*.tar.gz'); do\n    filepath=$(basename $file)\n    sha256sum \"$filepath\" > \"$file.sha256\"\n    sha512sum \"$filepath\" > \"$file.sha512\"\n  done\n  cd -\n}\n\nfunction build::common::upload_artifacts() {\n  local -r artifactspath=$1\n  local -r artifactsbucket=$2\n  local -r projectpath=$3\n  local -r buildidentifier=$4\n  local -r githash=$5\n  local -r latesttag=$6\n  local -r dry_run=$7\n  local -r do_not_delete=$8\n  \n  if [ \"$dry_run\" = \"true\" ]; then\n    build::common::echo_and_run aws s3 cp \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$buildidentifier\"-\"$githash\"/artifacts --recursive --dryrun\n    build::common::echo_and_run aws s3 cp \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$latesttag\" --recursive --dryrun\n  else\n    # Upload artifacts to s3 \n    # 1. To proper path on s3 with buildId-githash\n    # 2. Latest path to indicate the latest build, with --delete option to delete stale files in the dest path\n    build::common::echo_and_run aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$buildidentifier\"-\"$githash\"/artifacts --acl public-read\n\n    if [ \"$do_not_delete\" = \"true\" ]; then\n      build::common::echo_and_run aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$latesttag\" --acl public-read\n    else\n      build::common::echo_and_run aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$latesttag\" --delete --acl public-read\n    fi\n  fi\n}\n\nfunction build::gather_licenses() {\n  local -r outputdir=$1\n  local -r patterns=$2\n  local -r golang_version=$3\n  local -r threshold=$4\n  \n  # Force deps to only be pulled form vendor directories\n  # this is important in a couple cases where license files\n  # have to be manually created\n  export GOFLAGS=-mod=vendor\n  # force platform to be linux to ensure all deps are picked up\n  export GOOS=linux \n  export GOARCH=amd64 \n\n  build::common::use_go_version \"$golang_version\"\n\n  if ! command -v go-licenses &> /dev/null\n  then\n    echo \" go-licenses not found.  If you need license or attribution file handling\"\n    echo \" please refer to the doc in docs/development/attribution-files.md\"\n    exit\n  fi\n\n  mkdir -p \"${outputdir}/attribution\"\n  # attribution file generated uses the output go-deps and go-license to gather the necessary\n  # data about each dependency to generate the amazon approved attribution.txt files\n  # go-deps is needed for module versions\n  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns\n  build::common::echo_and_run go list -deps=true -json ./... | jq -s ''  > \"${outputdir}/attribution/go-deps.json\"\n\n  # go-licenses can be a bit noisy with its output and lot of it can be confusing \n  # the following messages are safe to ignore since we do not need the license url for our process\n  NOISY_MESSAGES=\"cannot determine URL for|Error discovering license URL|unsupported package host|contains non-Go code|has empty version|vendor.*\\.(h|s)$\"\n \n  build::common::echo_and_run go-licenses save --confidence_threshold $threshold --force $patterns --save_path \"${outputdir}/LICENSES\" 2> >(grep -vE \"$NOISY_MESSAGES\")\n  \n  build::common::echo_and_run go-licenses csv --confidence_threshold $threshold $patterns 2> >(grep -vE \"$NOISY_MESSAGES\") > \"${outputdir}/attribution/go-license.csv\"  \n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -q \"^vendor\\/golang.org\\/x\"; then\n      echo \" go-licenses created a file with a std golang package (golang.org/x/*)\"\n      echo \" prefixed with vendor/.  This most likely will result in an error\"\n      echo \" when generating the attribution file and is probably due to\"\n      echo \" to a version mismatch between the current version of go \"\n      echo \" and the version of go that was used to build go-licenses\"\n      exit 1\n  fi\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  # go-license is pretty eager to copy src for certain license types\n  # when it does, it applies strange permissions to the copied files\n  # which makes deleting them later awkward\n  # this behavior may change in the future with the following PR\n  # https://github.com/google/go-licenses/pull/28\n  # We can delete these additional files because we are running go mod vendor\n  # prior to this call so we know the source is the same as upstream\n  # go-licenses is copying this code because it doesnt know if its be modified or not\n  chmod -R 777 \"${outputdir}/LICENSES\"\n  find \"${outputdir}/LICENSES\" -type f \\( -name '*.yml' -o -name '*.go' -o -name '*.mod' -o -name '*.sum' -o -name '*gitignore' \\) -delete\n\n  # most of the packages show up the go-license.csv file as the module name\n  # from the go.mod file, storing that away since the source dirs usually get deleted\n  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')\n  if [ ! -f ${outputdir}/attribution/root-module.txt ]; then\n  \techo $MODULE_NAME > ${outputdir}/attribution/root-module.txt\n  fi\n}\n\nfunction build::non-golang::gather_licenses(){\n  local -r project=\"$1\"\n  local -r git_tag=\"$2\"\n  local -r output_dir=\"$3\"\n  project_org=\"$(cut -d '/' -f1 <<< ${project})\"\n  project_name=\"$(cut -d '/' -f2 <<< ${project})\"\n  git clone https://github.com/${project_org}/${project_name}\n  cd $project_name\n  git checkout $git_tag\n  cd ..\n  build::non-golang::copy_licenses $project_name $output_dir/LICENSES/github.com/${project_org}/${project_name}\n  rm -rf $project_name\n}\n\nfunction build::non-golang::copy_licenses(){\n  local -r source_dir=\"$1\"\n  local -r destination_dir=\"$2\"\n  (cd $source_dir; find . \\( -name \"*COPYING*\" -o -name \"*COPYRIGHT*\" -o -name \"*LICEN[C|S]E*\" -o -name \"*NOTICE*\" \\)) |\n  while read file\n  do\n    license_dest=$destination_dir/$(dirname $file)\n    mkdir -p $license_dest\n    cp -r \"${source_dir}/${file}\" $license_dest/$(basename $file)\n  done\n}\n\nfunction build::generate_attribution(){\n  local -r project_root=$1\n  local -r golang_version=$2\n  local -r output_directory=${3:-\"${project_root}/_output\"}\n  local -r attribution_file=${4:-\"${project_root}/ATTRIBUTION.txt\"}\n\n  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)\n  local -r go_path=$(build::common::get_go_path $golang_version)\n  local -r golang_version_tag=$($go_path/go version | grep -o \"go[0-9].* \")\n\n  if cat \"${output_directory}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  build::common::echo_and_run generate-attribution $root_module_name $project_root $golang_version_tag $output_directory \n  cp -f \"${output_directory}/attribution/ATTRIBUTION.txt\" $attribution_file\n}\n\nfunction build::common::get_go_path() {\n  local -r version=$1\n\n  # This is the path where the specific go binary versions reside in our builder-base image\n  local -r gorootbinarypath=\"/go/go${version}/bin\"\n  # This is the path that will most likely be correct if running locally\n  local -r gopathbinarypath=\"$GOPATH/go${version}/bin\"\n  if [ -d \"$gorootbinarypath\" ]; then\n    echo $gorootbinarypath\n  elif [ -d \"$gopathbinarypath\" ]; then\n    echo $gopathbinarypath\n  else\n    # not in builder-base, probably running in dev environment\n    # return default go installation\n    local -r which_go=$(which go)\n    echo \"$(dirname $which_go)\"\n  fi\n}\n\nfunction build::common::use_go_version() {\n  local -r version=$1\n\n  if (( \"${version#*.}\" < 16 )); then\n    echo \"Building with GO version $version is no longer supported!  Please update the build to use a newer version.\"\n    exit 1\n  fi\n\n  local -r gobinarypath=$(build::common::get_go_path $version)\n  echo \"Adding $gobinarypath to PATH\"\n  # Adding to the beginning of PATH to allow for builds on specific version if it exists\n  export PATH=${gobinarypath}:$PATH\n  export GOCACHE=$(go env GOCACHE)/$version\n}\n\n# Use a seperate build cache for each project/version to ensure there are no\n# shared bits which can mess up the final checksum calculation\n# this is mostly needed for create checksums locally since in the builds\n# different versions of the same project are not built in the same container\nfunction build::common::set_go_cache() {\n  local -r project=$1\n  local -r git_tag=$2\n  export GOCACHE=$(go env GOCACHE)/$project/$git_tag\n}\n\nfunction build::common::re_quote() {\n    local -r to_escape=$1\n    sed 's/[][()\\.^$\\/?*+]/\\\\&/g' <<< \"$to_escape\"\n}\n\nfunction build::common::get_latest_eksa_asset_url() {\n  local -r artifact_bucket=$1\n  local -r project=$2\n  local -r arch=${3-amd64}\n  local -r s3downloadpath=${4-latest}\n  local -r releasebranch=${5-}\n\n  s3artifactfolder=$s3downloadpath\n\n  projectwithreleasebranch=$project\n  # If not able to find git_tag w/o specifying a branch, update projectwithreleasebranch and git_tag to use a branch.\n  git_tag=$(cat $BUILD_ROOT/../../projects/${projectwithreleasebranch}/GIT_TAG || echo \"invalid\")\n  if [ \"$git_tag\" = \"invalid\" ]; then\n    projectwithreleasebranch=$project/$releasebranch\n    git_tag=$(cat $BUILD_ROOT/../../projects/${projectwithreleasebranch}/GIT_TAG)\n  fi  \n\n  local -r tar_file_prefix=$(MAKEFLAGS= make --no-print-directory -C $BUILD_ROOT/../../projects/${project} var-value-TAR_FILE_PREFIX)\n \n  local -r url=\"https://$(basename $artifact_bucket).s3-us-west-2.amazonaws.com/projects/$projectwithreleasebranch/$s3artifactfolder/$tar_file_prefix-linux-$arch-${git_tag}.tar.gz\"\n\n  local -r http_code=$(curl -I -L -s -o /dev/null -w \"%{http_code}\" $url)\n  if [[ \"$http_code\" == \"200\" ]]; then \n    echo \"$url\"\n  else\n    echo \"https://$(basename $artifact_bucket).s3-us-west-2.amazonaws.com/projects/$projectwithreleasebranch/latest/$tar_file_prefix-linux-$arch-${git_tag}.tar.gz\"\n  fi\n}\n\nfunction build::common::wait_for_tag() {\n  local -r tag=$1\n  sleep_interval=20\n  for i in {1..60}; do\n    echo \"Checking for tag ${tag}...\"\n    git rev-parse --verify --quiet \"${tag}\" && echo \"Tag ${tag} exists!\" && break\n    git fetch --tags > /dev/null 2>&1\n    echo \"Tag ${tag} does not exist!\"\n    echo \"Waiting for tag ${tag}...\"\n    sleep $sleep_interval\n    if [ \"$i\" = \"60\" ]; then\n      exit 1\n    fi\n  done\n}\n\nfunction build::common::wait_for_tarball() {\n  local -r tarball_url=$1\n  sleep_interval=20\n  for i in {1..60}; do\n    echo \"Checking for URL ${tarball_url}...\"\n    local http_code=$(curl -I -L -s -o /dev/null -w \"%{http_code}\" $tarball_url)\n    if [[ \"$http_code\" == \"200\" ]]; then \n      echo \"Tarball exists!\" && break\n    fi\n    echo \"Tarball does not exist!\"\n    echo \"Waiting for tarball to be uploaded to ${tarball_url}\"\n    sleep $sleep_interval\n    if [ \"$i\" = \"60\" ]; then\n      exit 1\n    fi\n  done\n}\n\nfunction build::common::get_clone_url() {\n  local -r org=$1\n  local -r repo=$2\n  local -r aws_region=$3\n  local -r codebuild_ci=$4\n\n  if [ \"$codebuild_ci\" = \"true\" ]; then\n    echo \"https://git-codecommit.${aws_region}.amazonaws.com/v1/repos/${org}.${repo}\"\n  else\n    echo \"https://github.com/${org}/${repo}.git\"\n  fi\n}\n\nfunction retry() {\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        >&2 echo \"Command failed. Attempt $n/$max:\"\n        sleep $delay;\n      else\n        fail \"The command has failed after $n attempts.\"\n      fi\n    }\n  done\n}\n\n# $1 - timeout value, should include unit (s/m/h/etc) ex: 10m\nfunction retry_with_timeout() {\n  TIMEOUT=$1\n  shift\n\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    timeout $TIMEOUT \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        # multiple the numeric part of the timeout by 1.5 and suffix with the last char which is the unit\n        TIMEOUT=$((${TIMEOUT:0:-1} * 3/2))${TIMEOUT: -1}\n        echo \"Command failed. Attempt $n/$max with timeout ${TIMEOUT}:\"\n        sleep $delay;\n      else\n        fail \"The command has failed after $n attempts.\"\n      fi\n    }\n  done\n}\n\nfunction build::docker::retry_pull() {\n  retry docker pull \"$@\"\n}\n\nfunction build::common::echo_and_run() {\n  >&2 echo \"($(pwd)) \\$ $*\"\n  \"$@\"\n}\n\nfunction build::bottlerocket::check_release_availablilty() {\n  local release_file=$1\n  local release_channel=$2\n  local format=$3\n  retval=0\n  release_version=$(yq e \".${release_channel}.${format}-release-version\" $release_file)\n  if [ $release_version == \"null\" ]; then\n    retval=1\n  fi\n  echo $retval\n}\n\nfunction build::jq::update_in_place() {\n  local json_file=$1\n  local jq_query=$2\n\n  cat $json_file | jq -S ''\"$jq_query\"'' > $json_file.tmp && mv $json_file.tmp $json_file\n}\n", "num_lines": 416}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nPROJECT_ROOT=\"$1\"\nGOLANG_VERSION=\"$2\"\nOUTPUT_DIR=\"$3\"\nOUTPUT_FILENAME=\"$4\"\nRELEASE_BRANCH=\"${5:-}\"\n\nif [[ -n \"$RELEASE_BRANCH\" ]] && [ -d \"$PROJECT_ROOT/$RELEASE_BRANCH\" ]; then\n\tPROJECT_ROOT=$PROJECT_ROOT/$RELEASE_BRANCH\nfi\n\nbuild::generate_attribution $PROJECT_ROOT $GOLANG_VERSION $OUTPUT_DIR $PROJECT_ROOT/$OUTPUT_FILENAME\n", "num_lines": 34}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nASSET_ROOT=\"$1\"\n\nFIND=find\nif which gfind &>/dev/null; then\n    FIND=gfind\nelif which gnudate &>/dev/null; then\n    FIND=gnufind\nfi\n\nREALPATH=realpath\nif which grealpath &>/dev/null; then\n    REALPATH=grealpath\nfi\n\nSHA256SUM=$(dirname ${ASSET_ROOT})/SHA256SUM\nSHA512SUM=$(dirname ${ASSET_ROOT})/SHA512SUM\nrm -f $SHA256SUM\nrm -f $SHA512SUM\necho \"Writing artifact hashes to SHA256SUM/SHA512SUM files...\"\ncd $ASSET_ROOT\nfor file in $(find ${ASSET_ROOT} -type f -not -path '*\\.sha[25][51][62]' -not -path '*\\.docker_*' \\\n     \\( -path '*bin/linux*' -o -path '*bin/windows*' -o -path '*bin/darwin*' -o -name '*\\.gz' -o -name '*\\.ova' -o -name '*\\.qcow2' \\) ); do\n    filepath=$($REALPATH --relative-base=${ASSET_ROOT} $file )\n    sha256sum \"$filepath\" | tee -a $SHA256SUM > \"$file.sha256\" || return 1\n    sha512sum \"$filepath\" | tee -a $SHA512SUM > \"$file.sha512\" || return 1\ndone\n\nif [ -f $SHA256SUM ]; then\n    mv $SHA256SUM $SHA512SUM \"$ASSET_ROOT\"\n    sha256sum SHA256SUM > \"SHA256SUM.sha256\" || return 1\n    sha512sum SHA256SUM > \"SHA256SUM.sha512\" || return 1\n    sha256sum SHA512SUM > \"SHA512SUM.sha256\" || return 1\n    sha512sum SHA512SUM > \"SHA512SUM.sha512\" || return 1\n\n    cat SHA256SUM\nfi\ncd -\n", "num_lines": 57}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Key for bundles manifest is environment/latest\n# example key = \"dev/release-1.20\"\ndeclare -A BUNDLE_MANIFEST=()\n\nfunction build::eksa_releases::load_bundle_manifest() {\n  local -r dev_release=${1-false}\n  local -r latest=${2-latest}\n  local -r echo=${3-true}\n  oldopt=$-\n  set +o nounset\n  set +x\n\n  local -r bundle_manifest_key=$(build::eksa_releases::get_bundle_manifest_key $dev_release $latest)\n  if [ ! ${BUNDLE_MANIFEST[$bundle_manifest_key]+1} ]; then\n    local -r release_manifest_url=$(build::eksa_releases::get_eksa_release_manifest_url $dev_release $latest)\n    local -r release_manifest=$(curl -s --retry 5 $release_manifest_url)\n\n    local -r latest_version=$(echo \"$release_manifest\" | yq e \".spec.latestVersion\" -)\n    local -r bundle_manifest_url=$(echo \"$release_manifest\" | yq e \".spec.releases[] | select(.version == \\\"$latest_version\\\") .bundleManifestUrl\" -)\n    BUNDLE_MANIFEST[$bundle_manifest_key]=$(curl -s --retry 5 \"$bundle_manifest_url\" | yq)\n  fi\n  if $echo; then\n    echo \"${BUNDLE_MANIFEST[$bundle_manifest_key]}\"\n  fi\n  set -$oldopt\n}\n\nfunction build::eksa_releases::get_eksa_component_asset_url() {\n  local -r component=$1\n  local -r asset=$2\n  local -r release_branch=$3\n  local -r dev_release=${4-false}\n  local -r latest=${5-main}\n\n  build::eksa_releases::get_eksa_component_asset_path $release_branch \".$component.$asset.uri\" $dev_release $latest\n}\n\nfunction build::eksa_releases::get_eksa_component_asset_artifact_checksum() {\n  local -r component=$1\n  local -r asset=$2\n  local -r type=$3\n  local -r release_branch=$4\n  local -r dev_release=${5-false}\n  local -r latest=${6-main}\n\n  if [[ $type != \"sha256\" ]] && [[ $type != \"sha512\" ]]; then\n    echo \"Invalid shasum type. Allowed types are sha256 and sha512\"\n  fi\n\n  build::eksa_releases::get_eksa_component_asset_path $release_branch \".$component.$asset.$type\" $dev_release $latest\n}\n\nfunction build::eksa_releases::get_eksa_component_asset_path() {\n  local -r release_branch=$1\n  local -r path=$2\n  local -r dev_release=${3-false}\n  local -r latest=${4-main}\n\n  oldopt=$-\n  set +x\n\n  # Get latest bundle manifest url\n  local bundle_manifest=$(build::eksa_releases::load_bundle_manifest $dev_release $latest)\n  local kube_version=$(echo $release_branch | sed 's/\\-/\\./g')\n\n  local query=\".spec.versionsBundles[] | select(.kubeVersion == \\\"$kube_version\\\") $path\"\n\n  echo \"$bundle_manifest\" | yq e \"$query\" -\n\n  set -$oldopt\n}\n\nfunction build::eksa_releases::get_eksa_release_manifest_url() {\n  local -r dev_release=${1-false}\n  local -r latest=${2-latest}\n\n  if [[ $dev_release == false ]]; then\n    echo \"https://anywhere-assets.eks.amazonaws.com/releases/eks-a/manifest.yaml\"\n  elif [[ $latest == \"latest\" ]]; then\n    echo \"https://dev-release-assets.eks-anywhere.model-rocket.aws.dev/eks-a-release.yaml\"\n  else\n    echo \"https://dev-release-assets.eks-anywhere.model-rocket.aws.dev/$latest/eks-a-release.yaml\"\n  fi\n}\n\nfunction build::eksa_releases::get_bundle_manifest_key() {\n  local -r dev_release=${1-false}\n  local -r latest=${2-latest}\n\n  local environment=\"prod\"\n  if [ $dev_release == true ]; then\n    environment=\"dev\"\n  fi\n\n  echo \"$environment/$latest\"\n}\n", "num_lines": 112}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nREPO_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../../\" && pwd -P)\"\nLATEST_RELEASE_BRANCH=''\nPROD_DOMAIN=\"distro.eks.amazonaws.com\"\nDEV_DOMAIN=\"eks-d-postsubmit-artifacts.s3.us-west-2.amazonaws.com\"\ndeclare -A RELEASE_YAML=()\n\nfunction build::eksd_releases::load_release_yaml() {\n    local -r release_branch=$1\n    local -r echo=${2-true}\n    oldopt=$-\n    set +o nounset\n    set +x\n\n    # if key exists, 1 is returned which would resolve to true\n    if [ ! ${RELEASE_YAML[$release_branch]+1} ]; then\n        local -r yaml_url=$(build::eksd_releases::get_release_yaml_url ${release_branch})\n        RELEASE_YAML[$release_branch]=$(curl -s --retry 5 $yaml_url)\n    fi\n    if $echo; then\n        echo \"${RELEASE_YAML[$release_branch]}\"\n    fi\n    set -$(echo $oldopt | sed 's/c//') # remove -c from options for when this is invoked with bash -c\n}\n\nfunction build::eksd_releases::get_release_yaml_url() {\n    local -r release_branch=$1\n    local -r release_number=$(yq e \".releases[] | select(.branch==\\\"${release_branch}\\\").number\" ${REPO_ROOT}/EKSD_LATEST_RELEASES)\n    local -r dev=$(yq e \".releases[] | select(.branch==\\\"${release_branch}\\\").dev\" ${REPO_ROOT}/EKSD_LATEST_RELEASES)\n    local -r yaml_path=\"kubernetes-${release_branch}/kubernetes-${release_branch}-eks-${release_number}.yaml\"\n    local yaml_url=\"https://$PROD_DOMAIN/$yaml_path\"\n    if [[ $dev == \"true\" ]]; then\n      yaml_url=\"https://$DEV_DOMAIN/$yaml_path\"\n    fi\n    echo \"$yaml_url\"\n}\n\nfunction build::eksd_releases::get_release_branch() {\n    if [ -z $LATEST_RELEASE_BRANCH ]; then\n        LATEST_RELEASE_BRANCH=$(yq e \".latest\" ${REPO_ROOT}/EKSD_LATEST_RELEASES)\n    fi\n    echo $LATEST_RELEASE_BRANCH\n}\n\nfunction build::eksd_releases::get_eksd_release_number() {\n    local -r release_branch=$1\n    \n    oldopt=$-\n    set +x\n    \n    local -r yaml=$(build::eksd_releases::load_release_yaml $release_branch)\n\n    echo \"$yaml\" |  yq e \".spec.number\" -\n    \n    set -$oldopt\n}\n\nfunction build::eksd_releases::get_eksd_release_name() {\n    local -r release_branch=$1\n    \n    oldopt=$-\n    set +x\n    \n    local -r yaml=$(build::eksd_releases::load_release_yaml $release_branch)\n\n    echo \"$yaml\" |  yq e \".metadata.name\" -\n    \n    set -$oldopt\n}\n\nfunction build::eksd_releases::get_eksd_component_version() {\n    local -r component=$1\n    local -r release_branch=$2\n    \n    oldopt=$-\n    set +x\n    \n    local -r yaml=$(build::eksd_releases::load_release_yaml $release_branch)\n\n    echo \"$yaml\" | yq e \".status.components[] | select(.name == \\\"$component\\\") .gitTag\" -\n    \n    set -$oldopt\n}\n\nfunction build::eksd_releases::get_eksd_component_asset_path() {\n    local -r component=$1\n    local -r release_branch=$2\n    local -r path=$3\n    local -r arch=$4\n    local -r asset=${5-}\n    \n    oldopt=$-\n    set +x\n    \n    local -r yaml=$(build::eksd_releases::load_release_yaml $release_branch)\n\n    local query=\".status.components[] | select(.name == \\\"$component\\\") .assets[]\"\n\n    if [[ $path == \".archive.uri\" ]] || [[ $path == \".archive.sha256\" ]]; then\n        query+=\" | select(.type == \\\"Archive\\\")\"\n    fi\n\n    if [ -z $asset ]; then\n        query+=\" | select(.arch[0] == \\\"$arch\\\") $path\"  \n    else\n        query+=\" | select(.name == \\\"$asset\\\") | select(.arch[0] == \\\"$arch\\\") $path\"\n    fi\n\n    echo \"$yaml\" | yq e \"$query\" -\n    \n    set -$(echo $oldopt | sed 's/c//') # remove -c from options for when this is invoked with bash -c\n}\n\nfunction build::eksd_releases::get_eksd_component_asset_url() {\n    local -r component=$1\n    local -r asset=$2\n    local -r release_branch=${3-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${4-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path $component $release_branch \".archive.uri\" $arch $asset \n}\n\nfunction build::eksd_releases::get_eksd_component_asset_sha() {\n    local -r component=$1\n    local -r asset=$2\n    local -r release_branch=${3-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${4-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path $component $release_branch \".archive.sha256\" $arch $asset\n}\n\n\nfunction build::eksd_releases::get_eksd_kubernetes_asset_url() {\n    local -r asset=$1\n    local -r release_branch=${2-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${3-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_url \"kubernetes\" $asset $release_branch $arch\n}\n\nfunction build::eksd_releases::get_eksd_kubernetes_image_url() {\n    local -r asset=$1\n    local -r release_branch=${2-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${3-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path \"kubernetes\" $release_branch \".image.uri\" $arch $asset \n}\n\nfunction build::eksd_releases::get_eksd_component_asset_image_tag() {\n    local -r component=$1\n    local -r asset=$2\n    local -r release_branch=$3\n    local -r arch=${4-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path $component $release_branch \".image.uri\" $arch $asset | awk -F: '{print $2}'\n}\n\nfunction build::eksd_releases::get_eksd_component_url() {\n    local -r component=$1\n    local -r release_branch=${2-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${3-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path $component $release_branch \".archive.uri\" $arch\n}\n\n\nfunction build::eksd_releases::get_eksd_component_sha() {\n    local -r component=$1\n    local -r release_branch=${2-$(build::eksd_releases::get_release_branch)}\n    local -r arch=${3-amd64}\n\n    build::eksd_releases::get_eksd_component_asset_path $component $release_branch \".archive.sha256\" $arch\n}\n\nfunction build::eksd_releases::get_eksd_image_repo() {\n    local -r release_branch=${1-$(build::eksd_releases::get_release_branch)}\n    \n    build::eksd_releases::get_eksd_kubernetes_image_url \"kube-apiserver-image\" $release_branch | sed -E 's,/kubernetes/kube-apiserver.*,,'\n}\n\nfunction build::eksd_releases::get_eksd_kubernetes_asset_base_url() {\n    local -r release_branch=${1-$(build::eksd_releases::get_release_branch)}\n    \n    local -r kube_version=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $release_branch)\n    local -r apiserver=\"bin/linux/amd64/kube-apiserver\"\n    build::eksd_releases::get_eksd_kubernetes_asset_url $apiserver $release_branch | sed -E \"s,/$kube_version/$apiserver.*,,\"\n}\n\nfunction build::eksd_releases::get_eksd_cni_asset_base_url() {\n    local -r release_branch=${1-$(build::eksd_releases::get_release_branch)}\n    \n    local -r cni_plugins_version=$(build::eksd_releases::get_eksd_component_version \"cni-plugins\" $release_branch)\n    build::eksd_releases::get_eksd_component_url \"cni-plugins\" $release_branch | sed -E \"s,/$cni_plugins_version/cni-plugins.*,,\"\n}\n", "num_lines": 209}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nBINARY_DEPS_DIR=\"$1\" \nDEP=\"$2\"\nARTIFACTS_BUCKET=\"$3\"\nLATEST_TAG=\"$4\"\nRELEASE_BRANCH=\"${5-$(build::eksd_releases::get_release_branch)}\"\n\nDEP=${DEP#\"$BINARY_DEPS_DIR\"}\nOS_ARCH=\"$(cut -d '/' -f1 <<< ${DEP})\"\nPRODUCT=$(cut -d '/' -f2 <<< ${DEP})\nREPO_OWNER=$(cut -d '/' -f3 <<< ${DEP})\nREPO=$(cut -d '/' -f4 <<< ${DEP})\n\nRELEASE_BRANCH_OVERRIDE=$(cut -d '/' -f5 <<< ${DEP})\nRELEASE_BRANCH=${RELEASE_BRANCH_OVERRIDE:-$RELEASE_BRANCH}\n\nARCH=\"$(cut -d '-' -f2 <<< ${OS_ARCH})\"\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\n\nOUTPUT_DIR_FILE=$BINARY_DEPS_DIR/linux-$ARCH/$PRODUCT/$REPO_OWNER/$REPO\n\nif [[ -n \"$RELEASE_BRANCH_OVERRIDE\" ]]; then\n    OUTPUT_DIR_FILE+=/$RELEASE_BRANCH_OVERRIDE\nfi\n\nif [[ $REPO == *.tar.gz ]]; then\n    mkdir -p $(dirname $OUTPUT_DIR_FILE)\nelse\n    mkdir -p $OUTPUT_DIR_FILE\nfi\n\nif [[ $PRODUCT = 'eksd' ]]; then\n    if [[ $REPO_OWNER = 'kubernetes' ]]; then\n        TARBALL=\"kubernetes-$REPO-linux-$ARCH.tar.gz\"\n        URL=$(build::eksd_releases::get_eksd_kubernetes_asset_url $TARBALL $RELEASE_BRANCH $ARCH)\n        # these tarballs will extra with the kubernetes/{client,server} folders\n        OUTPUT_DIR_FILE=$BINARY_DEPS_DIR/linux-$ARCH/$PRODUCT\n    else\n        URL=$(build::eksd_releases::get_eksd_component_url $REPO_OWNER $RELEASE_BRANCH $ARCH)\n    fi\nelse\n    URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET $REPO_OWNER/$REPO $ARCH $LATEST_TAG $RELEASE_BRANCH)\nfi\n\nif [ \"$CODEBUILD_CI\" = \"true\" ]; then\n    build::common::echo_and_run build::common::wait_for_tarball $URL\nfi\n\nDOWNLOAD_DIR=$(mktemp -d)\ntrap \"rm -rf $DOWNLOAD_DIR\" EXIT\n\nbuild::common::echo_and_run wget -q --retry-connrefused $URL $URL.sha256 -P $DOWNLOAD_DIR\n(cd $DOWNLOAD_DIR && sha256sum -c *.sha256)\n\nif [[ $REPO == *.tar.gz ]]; then\n    build::common::echo_and_run mv $DOWNLOAD_DIR/*.tar.gz $OUTPUT_DIR_FILE\nelse\n    build::common::echo_and_run tar xzf $DOWNLOAD_DIR/*.tar.gz -C $OUTPUT_DIR_FILE\nfi\n", "num_lines": 81}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nPACKAGE_FILTER=\"$3\"\nREPO_SUBPATH=\"${4:-}\"\nGOLANG_VERSION=\"${5:-}\"\nLICENSE_THRESHOLD=\"${6:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\ncd $REPO/$REPO_SUBPATH\nbuild::gather_licenses $OUTPUT_DIR \"$PACKAGE_FILTER\" \"$GOLANG_VERSION\" \"$LICENSE_THRESHOLD\"\n", "num_lines": 32}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT=\"$1\"\nGIT_TAG=\"$2\"\nOUTPUT_DIR=\"$3\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nbuild::non-golang::gather_licenses $PROJECT $GIT_TAG $OUTPUT_DIR\n", "num_lines": 28}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nBINARY_TARGET_FILES=\"$2\"\nBINARY_PLATFORMS=\"$3\"\nBINARY_TARGETS=\"$4\"\nREPO=\"$5\"\nHAS_PATCHES=\"$6\"\nLOCAL_IMAGE_TARGETS=\"$7\"\nIMAGE_TARGETS=\"$8\"\nBUILD_TARGETS=\"$9\"\nRELEASE_TARGETS=\"${10}\"\nHAS_S3_ARTIFACTS=\"${11}\"\nHAS_LICENSES=\"${12}\"\nREPO_NO_CLONE=\"${13}\"\nFETCH_BINARIES_TARGETS=\"${14}\"\nHAS_HELM_CHART=\"${15}\"\nIN_DOCKER_TARGETS=\"${16}\"\n\nNL=$'\\n'\nHEADER=\"########### DO NOT EDIT #############################\"\nFOOTER=\"########### END GENERATED ###########################\"\n\nMAKEFILE=$PROJECT_ROOT/Makefile\nHELPFILE=$PROJECT_ROOT/Help.mk\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $MAKEFILE\n# remove trailing newlines\nprintf %s \"$(< $MAKEFILE)\" > $MAKEFILE\n\ntouch $HELPFILE\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $HELPFILE\n# remove trailing newlines\nprintf %s \"$(< $HELPFILE)\" > $HELPFILE\n\n# Generate help items from Common.mk\nEXTRA_HELP=\"$(make help-list --no-print-directory)\"\nBINARY_TARGETS_HELP=\"\"\nCHECKSUMS_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$BINARY_TARGETS\" | xargs)\" ]; then\n    BINARY_TARGETS_HELP+=\"${NL}${NL}##@ Binary Targets\"\n    BINARY_TARGETS_HELP+=\"${NL}binaries: ## Build all binaries: \\`${BINARY_TARGET_FILES}\\` for \\`${BINARY_PLATFORMS}\\`\"\n    TARGETS=(${BINARY_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        BINARY_TARGETS_HELP+=\"${NL}${target}: ## Build \\`${target}\\`\"\n    done\n\n    CHECKSUMS_TARGETS_HELP+=\"${NL}${NL}##@ Checksum Targets\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}checksums: ## Update checksums file based on currently built binaries.\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}validate-checksums: # Validate checksums of currently built binaries against checksums file.\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}all-checksums: ## Update checksums files for all RELEASE_BRANCHes.\"\nfi\n\nGIT_TARGETS_HELP=\"\"\nif [[ \"$REPO_NO_CLONE\" != \"true\" ]]; then\n    GIT_TARGETS_HELP+=\"${NL}${NL}##@ GIT/Repo Targets\"\n    GIT_TARGETS_HELP+=\"${NL}clone-repo:  ## Clone upstream \\`${REPO}\\`\"\n    GIT_TARGETS_HELP+=\"${NL}checkout-repo: ## Checkout upstream tag based on value in GIT_TAG file\"\nfi\n\nPATCHES_TARGET=\"\"\nif [[ \"$HAS_PATCHES\" == \"true\" ]]; then\n    PATCHES_TARGET+=\"${NL}patch-repo: ## Patch upstream repo with patches in patches directory\"\nfi\n\nIMAGE_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$LOCAL_IMAGE_TARGETS\" | xargs)\" ]; then\n    IMAGE_TARGETS_HELP+=\"${NL}${NL}##@ Image Targets\"\n    IMAGE_TARGETS_HELP+=\"${NL}local-images: ## Builds \\`$(echo ${LOCAL_IMAGE_TARGETS} | xargs)\\` as oci tars for presumbit validation\"\n    IMAGE_TARGETS_HELP+=\"${NL}images: ## Pushes \\`$(echo ${IMAGE_TARGETS} | xargs)\\` to IMAGE_REPO\"\n    \n    ALL_IMAGES=()\n    TARGETS=(${LOCAL_IMAGE_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        ALL_IMAGES+=(\"$target\")\n    done\n    TARGETS=(${IMAGE_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        if [[ ! \" ${ALL_IMAGES[*]} \" =~ \" ${target} \" ]]; then\n            ALL_IMAGES+=(\"$target\")\n        fi\n    done\n    for image in \"${ALL_IMAGES[@]}\"; do\n        IMAGE_TARGETS_HELP+=\"${NL}$image: ## Builds/pushes \\`${image}\\`\"\n    done\n\nfi\n\nARTIFACTS_TARGETS=\"\"\nif [[ \"$HAS_S3_ARTIFACTS\" == \"true\" ]]; then\n    ARTIFACTS_TARGETS+=\"${NL}${NL}##@ Artifact Targets\" \n    ARTIFACTS_TARGETS+=\"${NL}tarballs: ## Create tarballs by calling build/lib/simple_create_tarballs.sh unless SIMPLE_CREATE_TARBALLS=false, then tarballs must be defined in project Makefile\"\n    ARTIFACTS_TARGETS+=\"${NL}s3-artifacts: # Prepare ARTIFACTS_PATH folder structure with tarballs/manifests/other items to be uploaded to s3\"\n    ARTIFACTS_TARGETS+=\"${NL}upload-artifacts: # Upload tarballs and other artifacts from ARTIFACTS_PATH to S3\"\nfi\n\nLICENSES_TARGETS=\"\"\nif [[ \"$HAS_LICENSES\" == \"true\" ]]; then\n    LICENSES_TARGETS+=\"${NL}${NL}##@ License Targets\" \n    LICENSES_TARGETS+=\"${NL}gather-licenses: ## Helper to call \\$(GATHER_LICENSES_TARGETS) which gathers all licenses\"\n    LICENSES_TARGETS+=\"${NL}attribution: ## Generates attribution from licenses gathered during \\`gather-licenses\\`.\"\n    LICENSES_TARGETS+=\"${NL}attribution-pr: ## Generates PR to update attribution files for projects\"\n    LICENSES_TARGETS+=\"${NL}attribution-checksums: ## Update attribution and checksums files.\"\n    LICENSES_TARGETS+=\"${NL}all-attributions: ## Update attribution files for all RELEASE_BRANCHes.\"\n    LICENSES_TARGETS+=\"${NL}all-attributions-checksums: ## Update attribution and checksums files for all RELEASE_BRANCHes.\"\nfi\n\nCLEAN_TARGETS=\"${NL}${NL}##@ Clean Targets\"\nCLEAN_TARGETS+=\"${NL}clean: ## Removes source and _output directory\"\nif [[ \"$REPO_NO_CLONE\" != \"true\" ]]; then\n    CLEAN_TARGETS+=\"${NL}clean-repo: ## Removes source directory\"\nfi\n\nFETCH_BINARY_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$FETCH_BINARIES_TARGETS\" | xargs)\" ]; then\n    FETCH_BINARY_TARGETS_HELP+=\"${NL}${NL}##@ Fetch Binary Targets\"\n    TARGETS=(${FETCH_BINARIES_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        FETCH_BINARY_TARGETS_HELP+=\"${NL}${target}: ## Fetch \\`${target}\\`\"\n    done\nfi\n\nHELM_TARGETS=\"\"\nif [[ \"$HAS_HELM_CHART\" == \"true\" ]]; then\n    HELM_TARGETS+=\"${NL}${NL}##@ Helm Targets\"\n    HELM_TARGETS+=\"${NL}helm/build: ## Build helm chart\"\n    HELM_TARGETS+=\"${NL}helm/push: ## Build helm chart and push to registry defined in IMAGE_REPO.\"\nfi\n\nTARGETS=(${IN_DOCKER_TARGETS// / })\nDOCKER_TARGETS=\"${NL}${NL}##@ Run in Docker Targets\"\nfor target in \"${TARGETS[@]}\"; do\n    DOCKER_TARGETS+=\"${NL}run-${target}-in-docker: ## Run \\`${target}\\` in docker builder container\"\ndone\n\ncat >> $HELPFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n${GIT_TARGETS_HELP}${PATCHES_TARGET}${BINARY_TARGETS_HELP}${IMAGE_TARGETS_HELP}${HELM_TARGETS}${FETCH_BINARY_TARGETS_HELP}${CHECKSUMS_TARGETS_HELP}${DOCKER_TARGETS}${ARTIFACTS_TARGETS}${LICENSES_TARGETS}${CLEAN_TARGETS}\n${EXTRA_HELP}\n\n##@ Build Targets\nbuild: ## Called via prow presubmit, calls \\`${BUILD_TARGETS//$PROJECT_ROOT\\//\"\"}\\`\nrelease: ## Called via prow postsubmit + release jobs, calls \\`${RELEASE_TARGETS}\\`\n${FOOTER}\nEOF\n\ncat >> $MAKEFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n# Run make help for a formatted help block with all targets\ninclude Help.mk\n${FOOTER}\nEOF\n\n", "num_lines": 181}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o pipefail\n\nBASE_DIRECTORY=\"${1?Specify first argument - Base directory of build-tooling repo}\"\nUPSTREAM_PROJECTS_FILE=\"$BASE_DIRECTORY/UPSTREAM_PROJECTS.yaml\"\n\nYQ_LATEST_RELEASE_URL=\"https://github.com/mikefarah/yq/releases/latest\"\nCURRENT_YQ_VERSION=$(yq -V | awk '{print $NF}')\nCURRENT_YQ_MAJOR_VERSION=${CURRENT_YQ_VERSION:1:1}\nLATEST_YQ_VERSION=$(curl --retry 5 -fIsS $YQ_LATEST_RELEASE_URL | grep \"location:\" | awk -F/ '{print $NF}')\nLATEST_YQ_MAJOR_VERSION=${LATEST_YQ_VERSION:1:1}\nif [ $CURRENT_YQ_MAJOR_VERSION -lt $LATEST_YQ_MAJOR_VERSION ]; then\n    echo \"Current yq major version v$CURRENT_YQ_MAJOR_VERSION.x is older than the latest (v$LATEST_YQ_MAJOR_VERSION.x).\"\n    echo \"Please install the latest version of yq from $YQ_LATEST_RELEASE_URL\"\n    exit 1\nfi\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\ndeclare -i org_count=0 # Counter variable for each org\n\nyq eval --null-input \".projects = []\" > $UPSTREAM_PROJECTS_FILE # Creates an empty YAML array\n\n# Iterating over orgs under projects folder\nfor org_path in projects/*; do\n    repos=() # Empty array for repos in the org\n    org=$(cut -d/ -f2 <<< $org_path)\n    declare -i repo_count=0\n    for repo_path in projects/$org/*; do\n        repo=\"$(cut -d/ -f3 <<< $repo_path)\"\n        if [ \"$org\" = \"aws\" ] & [[ $repo =~ \"eks-anywhere\" ]]; then # Ignore self-referential repos\n            continue\n        fi\n        if [ \"$org\" = \"kubernetes-sigs\" ] & [[ \"$repo\" =~ \"metrics-server\" ]]; then # Ignore helm builds backed by eks-d images to reduce toil\n            continue\n        fi\n        if curl --retry 5 -fIsS https://github.com/$org/$repo &> /dev/null; then # Check if org/repo combination is a Github repo\n            repos+=(\"$repo\")\n        fi\n    done\n    if [ ${#repos[@]} -gt 0 ]; then\n        yq eval -i -P \".projects += [{\\\"org\\\": \\\"$org\\\", \\\"repos\\\": []}]\" $UPSTREAM_PROJECTS_FILE # Add an entry for this org in the projects array\n        for repo in \"${repos[@]}\"; do\n            yq eval -i -P \".projects[$org_count].repos += [{\\\"name\\\": \\\"$repo\\\", \\\"versions\\\": []}]\" $UPSTREAM_PROJECTS_FILE # Add each repo to the repos array\n            git_tags=$(find projects/$org/$repo -type f -name \"GIT_TAG\" | sort)\n            for file in $git_tags; do\n                tag=$(cat $file)\n                if [ $repo = \"cilium\" ]; then\n                    yq eval -i -P \".projects[$org_count].repos[$repo_count].versions += [{\\\"tag\\\": \\\"$tag\\\"}]\" $UPSTREAM_PROJECTS_FILE\n                else\n                    if [ \"$(git ls-remote --tags https://github.com/$org/$repo | awk '{print $2}' | grep $tag || true)\" ]; then\n                        yq eval -i -P \".projects[$org_count].repos[$repo_count].versions += [{\\\"tag\\\": \\\"$tag\\\"}]\" $UPSTREAM_PROJECTS_FILE\n                    else\n                        yq eval -i -P \".projects[$org_count].repos[$repo_count].versions += [{\\\"commit\\\": \\\"$tag\\\"}]\" $UPSTREAM_PROJECTS_FILE\n                    fi\n                fi\n            done\n            repo_count+=1\n        done\n        org_count+=1\n    fi\ndone\n\nHEAD_COMMENT=$(cat $BASE_DIRECTORY/hack/boilerplate.yq.txt)\nyq eval -i \". headComment=\\\"$HEAD_COMMENT\\\"\" $UPSTREAM_PROJECTS_FILE # Add a header comment with license verbiage and no-edit warning\n", "num_lines": 83}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBASE_DIRECTORY=\"${1?Specify first argument - Base directory of build-tooling repo}\"\nALL_PROJECTS=\"${2?Specify second argument - All projects in repo}\"\nSTAGING_BUILDSPEC_FILE=\"${3}\"\nSKIP_DEPEND_ON=\"${4:-false}\"\nEXCLUDE_VAR=\"${5:-EXCLUDE_FROM_STAGING_BUILDSPEC}\"\nBUILDSPECS_VAR=\"${6:-BUILDSPECS}\"\nFAST_FAIL=\"${7:-true}\"\nADD_FINAL_STAGE=\"${8:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nYQ_LATEST_RELEASE_URL=\"https://github.com/mikefarah/yq/releases/latest\"\nCURRENT_YQ_VERSION=$(yq -V | awk '{print $NF}')\nCURRENT_YQ_MAJOR_VERSION=${CURRENT_YQ_VERSION:1:1}\nLATEST_YQ_VERSION=$(curl -fIsS $YQ_LATEST_RELEASE_URL | grep \"location:\" | awk -F/ '{print $NF}')\nLATEST_YQ_MAJOR_VERSION=${LATEST_YQ_VERSION:1:1}\nif [ $CURRENT_YQ_MAJOR_VERSION -lt $LATEST_YQ_MAJOR_VERSION ]; then\n    echo \"Current yq major version v$CURRENT_YQ_MAJOR_VERSION.x is older than the latest (v$LATEST_YQ_MAJOR_VERSION.x).\"\n    echo \"Please install the latest version of yq from $YQ_LATEST_RELEASE_URL\"\n    exit 1\nfi\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\nmkdir -p $(dirname $STAGING_BUILDSPEC_FILE)\nyq eval --null-input \".batch={\\\"fast-fail\\\":$FAST_FAIL,\\\"build-graph\\\":[]}\" > $STAGING_BUILDSPEC_FILE # Creates an empty YAML array\n\n# TODO: refactor use of release_branch to get git_tag and golang_version in makefile, we should be able to push this to common.mk and avoid needing to pass it here\nRELEASE_BRANCH=$(build::eksd_releases::get_release_branch)\n\nfunction make_var() {\n    make --no-print-directory -C $1 \"$(echo \"$2\" | sed 's/[^ ]* */var-value-&/g')\" CODEBUILD_CI=true 2>/dev/null\n}\n\nPROJECTS=(${ALL_PROJECTS// / })\nALL_PROJECT_IDS=\"\"\nfor project in \"${PROJECTS[@]}\"; do\n    org=$(cut -d_ -f1 <<< $project)\n    repo=$(cut -d_ -f2- <<< $project)\n\n    PROJECT_PATH=$MAKE_ROOT/projects/$org/$repo\n\n    if [[ \"true\" == \"$(make_var $PROJECT_PATH $EXCLUDE_VAR)\" ]]; then\n        continue\n    fi\n\n    CLONE_URL=\"\"\n    if [[ \"true\" != \"$(make_var $PROJECT_PATH REPO_NO_CLONE)\" ]]; then\n        REPO=$(make_var $PROJECT_PATH CLONE_URL AWS_REGION=us-west-2)\n        CLONE_URL=\",\\\"CLONE_URL\\\":\\\"$REPO\\\"\"\n    fi\n\n    BUILDSPECS=$(make_var $PROJECT_PATH $BUILDSPECS_VAR)\n    SPECS=(${BUILDSPECS// / })\n    for (( i=0; i < ${#SPECS[@]}; i++ )); do\n        IDENTIFIER=\"${org//-/_}_${repo//-/_}\"\n\n        buildspec=${SPECS[$i]}\n\n        DEPEND_ON=\"\"\n        # something other than empty string since some overrides are empty strings\n        PROJECT_DEPENDENCIES=\"false\"\n        for var in \"BUILDSPEC_$((( $i + 1 )))_DEPENDS_ON_OVERRIDE\" \"BUILDSPEC_DEPENDS_ON_OVERRIDE\"; do\n            BUILDSPEC_DEPENDS_ON=\"$(make_var $PROJECT_PATH $var)\"\n            HARDCODED_DEP=\"false\"\n            if [[ \"none\" = \"$BUILDSPEC_DEPENDS_ON\" ]]; then\n                PROJECT_DEPENDENCIES=\"\"\n                break\n            elif [[ -n \"$BUILDSPEC_DEPENDS_ON\" ]]; then\n                HARDCODED_DEP=\"true\"\n                PROJECT_DEPENDENCIES=$BUILDSPEC_DEPENDS_ON\n                break\n            fi\n        done\n\n        BUILDSPEC_IDENTIFIER_OVERRIDE=\"$(make_var $PROJECT_PATH BUILDSPEC_$((( $i + 1 )))_IDENTIFIER_OVERRIDE)\"\n        if [[ -n \"$BUILDSPEC_IDENTIFIER_OVERRIDE\" ]]; then\n            IDENTIFIER=\"$BUILDSPEC_IDENTIFIER_OVERRIDE\"\n        fi   \n       \n        echo \"Adding: $IDENTIFIER\"\n\n        if [ \"$PROJECT_DEPENDENCIES\" = \"false\" ]; then\n            PROJECT_DEPENDENCIES=$(make_var $PROJECT_PATH PROJECT_DEPENDENCIES)\n        fi\n\n        if [ -n \"$PROJECT_DEPENDENCIES\" ] && [ \"$SKIP_DEPEND_ON\" != \"true\" ]; then\n            DEPS=(${PROJECT_DEPENDENCIES// / })\n            for dep in \"${DEPS[@]}\"; do\n                if [ \"$HARDCODED_DEP\" = \"true\" ]; then\n                    DEPEND_ON+=\"\\\"$dep\\\",\"\n                    continue\n                fi\n\n                DEP_PRODUCT=\"$(cut -d/ -f1 <<< $dep)\"\n                if [[ \"$DEP_PRODUCT\" == \"eksd\" ]]; then\n                    continue\n                fi\n                DEP_ORG=\"$(cut -d/ -f2 <<< $dep)\"\n                DEP_REPO=\"$(cut -d/ -f3 <<< $dep)\"\n                DEPEND_ON+=\"\\\"${DEP_ORG//-/_}_${DEP_REPO//-/_}\\\",\"\n\n                if [ ! -d $MAKE_ROOT/projects/$DEP_ORG/$DEP_REPO ]; then\n                    echo \"Non-existent project dependency: $dep!!!\"\n                    exit 1\n                fi\n            done\n        fi\n\n        if [ -n \"$DEPEND_ON\" ]; then\n            DEPEND_ON=\"\\\"depend-on\\\":[${DEPEND_ON%?}],\"\n        fi\n        BUILDSPEC_VARS_KEYS=$(make_var $PROJECT_PATH BUILDSPEC_VARS_KEYS)\n        if [[ -z \"$BUILDSPEC_VARS_KEYS\" ]]; then\n            BUILDSPEC_VARS_KEYS=$(make_var $PROJECT_PATH BUILDSPEC_$((( $i + 1 )))_VARS_KEYS)\n        fi\n        \n        BUILDSPEC_PLATFORM=$(make_var $PROJECT_PATH BUILDSPEC_$((( $i + 1 )))_PLATFORM)\n        if [[ -z \"$BUILDSPEC_PLATFORM\" ]]; then\n            BUILDSPEC_PLATFORM=$(make_var $PROJECT_PATH BUILDSPEC_PLATFORM)\n        fi\n\n        BUILDSPEC_COMPUTE_TYPE=$(make_var $PROJECT_PATH BUILDSPEC_$((( $i + 1 )))_COMPUTE_TYPE)\n        if [[ -z \"$BUILDSPEC_COMPUTE_TYPE\" ]]; then\n            BUILDSPEC_COMPUTE_TYPE=$(make_var $PROJECT_PATH BUILDSPEC_COMPUTE_TYPE)\n        fi\n\n        ARCH_TYPE=\"\\\"type\\\":\\\"$BUILDSPEC_PLATFORM\\\",\\\"compute-type\\\":\\\"$BUILDSPEC_COMPUTE_TYPE\\\",\"\n    \n        if [[ \"$BUILDSPECS_VAR\" == \"CHECKSUMS_BUILDSPECS\" ]] && [[ \"$BUILDSPEC_VARS_KEYS\" == \"RELEASE_BRANCH\" ]] && [[ \"false\" == \"$(make_var $PROJECT_PATH BINARIES_ARE_RELEASE_BRANCHED)\" ]]; then\n            BUILDSPEC_VARS_KEYS=\"\"\n        fi\n\n        if [[ -n \"$BUILDSPEC_VARS_KEYS\" ]]; then\n            KEYS=(${BUILDSPEC_VARS_KEYS// / })\n\n            BUILDSPEC_VARS_VALUES=$(make_var $PROJECT_PATH BUILDSPEC_VARS_VALUES)\n            if [[ -z \"$BUILDSPEC_VARS_VALUES\" ]]; then\n                BUILDSPEC_VARS_VALUES=$(make_var $PROJECT_PATH BUILDSPEC_$((( $i + 1 )))_VARS_VALUES)\n            fi\n            VARS=(${BUILDSPEC_VARS_VALUES// / })\n            \n            # Note: only support 1 or 2 vars for now since that is all we need for kind + image-builder \n            if [ ${#VARS[@]} -eq 1 ]; then\n                VALUES_1=$(make_var $PROJECT_PATH ${VARS[0]})\n                ARR_1=(${VALUES_1// / })\n                \n                for val1 in \"${ARR_1[@]}\"; do                \n                    BUILDSPEC_NAME=$(basename $buildspec .yml)\n                    IDENTIFIER=${org//-/_}_${repo//-/_}_${val1//[-\\/]/_}\n                    \n                    # If building on one binary platform assume we want to run on a specific arch instance\n                    ARCH_TYPE=\"\\\"type\\\":\\\"$BUILDSPEC_PLATFORM\\\",\\\"compute-type\\\":\\\"$BUILDSPEC_COMPUTE_TYPE\\\",\"\n                    if [ \"${KEYS[0]}\" = \"BINARY_PLATFORMS\" ]; then\n                        if [ \"${val1}\" = \"linux/amd64\" ]; then\n                            ARCH_TYPE=\"\\\"type\\\":\\\"LINUX_CONTAINER\\\",\\\"compute-type\\\":\\\"BUILD_GENERAL1_SMALL\\\",\"\n                        else\n                            ARCH_TYPE=\"\\\"type\\\":\\\"ARM_CONTAINER\\\",\\\"compute-type\\\":\\\"BUILD_GENERAL1_SMALL\\\",\"\n                        fi\n                    fi\n\n                    ALL_PROJECT_IDS+=\"\\\"$IDENTIFIER\\\",\"\n                    yq eval -i -P \\\n                        \".batch.build-graph += [{\\\"identifier\\\":\\\"$IDENTIFIER\\\",\\\"buildspec\\\":\\\"$buildspec\\\",$DEPEND_ON\\\"env\\\":{$ARCH_TYPE\\\"variables\\\":{\\\"PROJECT_PATH\\\": \\\"projects/$org/$repo\\\"$CLONE_URL,\\\"${KEYS[0]}\\\":\\\"$val1\\\"}}}]\" \\\n                        $STAGING_BUILDSPEC_FILE\n                done\n            else\n                VALUES_1=$(make_var $PROJECT_PATH ${VARS[0]})\n                VALUES_2=$(make_var $PROJECT_PATH ${VARS[1]})\n\n                ARR_1=(${VALUES_1// / })\n                ARR_2=(${VALUES_2// / })\n                for val1 in \"${ARR_1[@]}\"; do\n                    for val2 in \"${ARR_2[@]}\"; do\n                        BUILDSPEC_NAME=$(basename $buildspec .yml)\n                        IDENTIFIER=${org//-/_}_${repo//-/_}_${val1//-/_}_${val2//-/_}_${BUILDSPEC_NAME//-/_}\n                        ALL_PROJECT_IDS+=\"\\\"$IDENTIFIER\\\",\"\n                        yq eval -i -P \\\n                            \".batch.build-graph += [{\\\"identifier\\\":\\\"$IDENTIFIER\\\",\\\"buildspec\\\":\\\"$buildspec\\\",$DEPEND_ON\\\"env\\\":{$ARCH_TYPE\\\"variables\\\":{\\\"PROJECT_PATH\\\": \\\"projects/$org/$repo\\\"$CLONE_URL,\\\"${KEYS[0]}\\\":\\\"$val1\\\",\\\"${KEYS[1]}\\\":\\\"$val2\\\"}}}]\" \\\n                            $STAGING_BUILDSPEC_FILE \n                    done\n                done\n            fi\n        else\n            ALL_PROJECT_IDS+=\"\\\"$IDENTIFIER\\\",\"\n            yq eval -i -P \\\n                \".batch.build-graph += [{\\\"identifier\\\":\\\"$IDENTIFIER\\\",\\\"buildspec\\\":\\\"$buildspec\\\",$DEPEND_ON\\\"env\\\":{$ARCH_TYPE\\\"variables\\\":{\\\"PROJECT_PATH\\\": \\\"projects/$org/$repo\\\"$CLONE_URL}}}]\" \\\n                $STAGING_BUILDSPEC_FILE \n        fi\n        \n    done\ndone\n\nif [ -n \"${ADD_FINAL_STAGE}\" ]; then\n    ARCH_TYPE=\"\\\"type\\\":\\\"ARM_CONTAINER\\\",\\\"compute-type\\\":\\\"BUILD_GENERAL1_SMALL\\\"\"\n    yq eval -i -P \\\n        \".batch.build-graph += [{\\\"identifier\\\":\\\"final_stage\\\",\\\"buildspec\\\":\\\"$ADD_FINAL_STAGE\\\",\\\"env\\\":{$ARCH_TYPE},\\\"depend-on\\\":[${ALL_PROJECT_IDS%?}]}]\" \\\n        $STAGING_BUILDSPEC_FILE \nfi\n\nHEAD_COMMENT=$(cat $BASE_DIRECTORY/hack/boilerplate.yq.txt)\nyq eval -i \". headComment=\\\"$HEAD_COMMENT\\\"\" $STAGING_BUILDSPEC_FILE # Add a header comment with license verbiage and no-edit warning\n\nif [[ \"${#PROJECTS[@]}\" = \"1\" ]]; then\n    # if there is only one project we do not want project_path and clone_url to be set since it will be set at the codebuild level\n    yq -i 'del(.batch.build-graph.[].env.variables.PROJECT_PATH)' $STAGING_BUILDSPEC_FILE\n    yq -i 'del(.batch.build-graph.[].env.variables.CLONE_URL)' $STAGING_BUILDSPEC_FILE\n    yq -i 'del(.. | select(tag == \"!!map\" and length == 0))' $STAGING_BUILDSPEC_FILE\n    yq -i 'del(.. | select(tag == \"!!map\" and length == 0))' $STAGING_BUILDSPEC_FILE\nfi\n", "num_lines": 233}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nREPO=\"$2\"\nTAG=\"$3\"\nGOLANG_VERSION=\"$4\"\nREPO_SUBPATH=\"${5:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\ncd $REPO/$REPO_SUBPATH\n\nCACHE_KEY=$(echo $PROJECT_ROOT | sed 's/\\(.*\\)\\//\\1-/' | xargs basename)\nbuild::common::use_go_version $GOLANG_VERSION\nbuild::common::set_go_cache $CACHE_KEY $TAG\nbuild::common::echo_and_run go mod vendor\n", "num_lines": 35}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nOUTPUT_DIR=\"${1?First arguement is output directory}\"\nHELM_DESTINATION_REPOSITORY=\"${2?Second argument is helm destination repository}\"\nCHART_NAME=$(basename ${HELM_DESTINATION_REPOSITORY})\n\n#\n# Build\n#\ncd ${OUTPUT_DIR}/helm\nhelm package \"${CHART_NAME}\"\n", "num_lines": 30}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nHELM_SOURCE_REPOSITORY=\"${1?First argument is helm source repository}\"\nHELM_DESTINATION_REPOSITORY=\"${2?Second argument is helm destination repository}\"\nHELM_DIRECTORY=\"${3?Third argument is helm directory}\"\nOUTPUT_DIR=\"${4?Fouth arguement is output directory}\"\n\nCHART_NAME=$(basename ${HELM_DESTINATION_REPOSITORY})\nDEST_DIR=${OUTPUT_DIR}/helm/${CHART_NAME}\nSOURCE_DIR=$(basename ${HELM_SOURCE_REPOSITORY})/${HELM_DIRECTORY}/.\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\n#\n# Copy\n#\nmkdir -p ${DEST_DIR}\nrsync -a --exclude .git \"${SOURCE_DIR}\" \"${DEST_DIR}\"\nbuild::non-golang::copy_licenses ${HELM_SOURCE_REPOSITORY} $DEST_DIR/LICENSES/github.com/${HELM_SOURCE_REPOSITORY}\n", "num_lines": 39}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\nIMAGE_REGISTRY=\"${1?First argument is image registry}\"\nHELM_REPO_URL=\"${2?Second arguement is update repo url}\"\nHELM_PULL_NAME=\"${3?Third argument is name of helm chart}\"\nREPO=\"${4?Fourth argument is helm source repository}\"\nHELM_DIRECTORY=\"${5?Fifth argument is helm directory name}\"\nCHART_VERSION=\"${6?Sixth argument is the version of helm chart we need to pull}\"\nCOPY_CRDS=\"${7?Seventh argument is whether we need add crds to the helm chart}\"\n\nfunction cleanup() {\n  if [ -d \"$HELM_PULL_NAME\" ]; then\n    rm -rf \"${HELM_PULL_NAME}\"\n  fi\n}\n\nfunction cleanup-chart() {\n  if [ -d \"${REPO}/${HELM_DIRECTORY}\" ]; then\n    rm -rf \"${REPO}/${HELM_DIRECTORY}\"\n  fi\n}\n\nfunction copy-crds() {\n  if [ -d \"${COPY_CRDS}\" ]; then\n    rm -rf  ${REPO}/${HELM_DIRECTORY}/crds/*\n    mkdir ${REPO}/${HELM_DIRECTORY}/crds || true\n    cp ${COPY_CRDS}/* ${REPO}/${HELM_DIRECTORY}/crds\n  fi\n}\n\ntrap cleanup err\n\nhelm repo add ${IMAGE_REGISTRY} ${HELM_REPO_URL}\nhelm repo update\nhelm pull ${IMAGE_REGISTRY}/${HELM_PULL_NAME} --version ${CHART_VERSION} --untar\n\ncleanup-chart\n\nmv ${HELM_PULL_NAME} ${REPO}/${HELM_DIRECTORY}\n\ncopy-crds\n\ncleanup\n", "num_lines": 67}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\nIMAGE_REGISTRY=\"${1?First argument is image registry}\"\nHELM_DESTINATION_REPOSITORY=\"${2?Second argument is helm repository}\"\nHELM_TAG=\"${3?Third argument is helm tag}\"\nGIT_TAG=\"${4?Fourth arguement is the Git Tag}\"\nOUTPUT_DIR=\"${5?Fifth arguement is output directory}\"\nLATEST_TAG=\"${6?Sixth arguement is latest tag}\"\nSEMVER_GIT_TAG=\"${GIT_TAG#[^0-9:main]}\"\n\nSEMVER=\"${HELM_TAG#[^0-9]}\" # remove any leading non-digits\nSEMVER_REGEX='^([0-9]+\\.){0,2}(\\*|[0-9]+)$'\nif [[ ! $SEMVER_GIT_TAG =~ $SEMVER_REGEX ]]; then\n  # if not a valid semver, fallback to helm tag semver\n  SEMVER_GIT_TAG=$SEMVER\nfi\n\nHELM_DESTINATION_OWNER=$(dirname ${HELM_DESTINATION_REPOSITORY})\nCHART_NAME=$(basename ${HELM_DESTINATION_REPOSITORY})\nCHART_FILE=\"${OUTPUT_DIR}/helm/${CHART_NAME}-${SEMVER}.tgz\"\n\nDOCKER_CONFIG=${DOCKER_CONFIG:-~/.docker}\nexport HELM_REGISTRY_CONFIG=\"${DOCKER_CONFIG}/config.json\"\nexport HELM_EXPERIMENTAL_OCI=1\nTMPFILE=$(mktemp /tmp/helm-output.XXXXXX)\nfunction cleanup() {\n  if [[ \"${IMAGE_REGISTRY}\" == *\"public.ecr.aws\"* ]]; then\n    echo \"If authentication failed: aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws\"\n  else\n    echo \"If authentication failed: aws ecr get-login-password --region \\${AWS_REGION} | docker login --username AWS --password-stdin ${IMAGE_REGISTRY}\"\n  fi\n  rm -f \"${TMPFILE}\"\n}\n\ntrap cleanup err\ntrap \"rm -f $TMPFILE\" exit\nhelm push ${CHART_FILE} oci://${IMAGE_REGISTRY}/${HELM_DESTINATION_OWNER} | tee ${TMPFILE}\n\n# Adds a 2nd tag to the helm chart for the bundle-release jobs.\nif [[ \"${IMAGE_REGISTRY}\" != *\"public.ecr.aws\"* ]]; then\n  MANIFEST=$(aws ecr batch-get-image --repository-name \"$HELM_DESTINATION_REPOSITORY\" --image-ids imageTag=${SEMVER} --query \"images[].imageManifest\" --output text)\n  export AWS_PAGER=\"\"\n  aws ecr put-image --repository-name ${HELM_DESTINATION_REPOSITORY} --image-tag ${SEMVER_GIT_TAG}-${LATEST_TAG}-helm --image-manifest \"$MANIFEST\" --image-manifest-media-type \"application/vnd.oci.image.manifest.v1+json\"\nfi\n\nDIGEST=$(grep Digest $TMPFILE | $SED -e 's/Digest: //')\n{\n    set +x\n    echo\n    echo\n    echo \"helm install ${CHART_NAME} oci://${IMAGE_REGISTRY}/${HELM_DESTINATION_REPOSITORY} --version ${SEMVER} --set sourceRegistry=${IMAGE_REGISTRY}\"\n}\n", "num_lines": 76}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\nHELM_DESTINATION_REPOSITORY=\"${1?First argument is helm destination repository}\"\nOUTPUT_DIR=\"${2?Second arguement is output directory}\"\n\nCHART_NAME=$(basename ${HELM_DESTINATION_REPOSITORY})\nDEST_DIR=${OUTPUT_DIR}/helm/${CHART_NAME}\n\n#\n# Search and replace\n#\nTEMPLATE_DIR=helm/templates\nSEDFILE=${OUTPUT_DIR}/helm/sedfile\nfor file in Chart.yaml values.yaml\ndo\n  $SED -f ${SEDFILE} -i ${DEST_DIR}/${file}\ndone\n\nif [ -d ${OUTPUT_DIR}/helm/${CHART_NAME}/crds ]; then\n  for file in crds/*.yaml \n  do\n    $SED -f ${SEDFILE} -i ${DEST_DIR}/${file}\n  done\nfi", "num_lines": 47}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o errexit\nset -o nounset\nset -o pipefail\n\nIMAGE_REGISTRY=\"${1?First argument is registry}\"\nHELM_DESTINATION_REPOSITORY=\"${2?Second argument is helm destination repository}\"\nOUTPUT_DIR=\"${3?Third argument is output directory}\"\nIMAGE_TAG=\"${4?Fourth argument is image tag}\"\nHELM_TAG=\"${5?Fifth argument is helm tag}\"\nPROJECT_ROOT=\"${6?Sixth argument is project root}\"\nLATEST=\"${7?Seventh argument is latest tag}\"\nHELM_USE_UPSTREAM_IMAGE=\"${8?Eigth argument is bool determining whether to use cached upstream images}\"\nHELM_IMAGE_LIST=\"${@:9}\"\n\nCHART_NAME=$(basename ${HELM_DESTINATION_REPOSITORY})\nDEST_DIR=${OUTPUT_DIR}/helm/${CHART_NAME}\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nPACKAGE_DEPENDENCIES=${PACKAGE_DEPENDENCIES:=\"\"}\nFORCE_JSON_SCHEMA_FILE=${FORCE_JSON_SCHEMA_FILE:=\"\"}\n\n#\n# Image tags\n#\nREQUIRES_FILE=${DEST_DIR}/requires.yaml\ncat >${REQUIRES_FILE} <<!\n---\nkind: EksaPackageRequires\nmetadata:\n  name: ${HELM_DESTINATION_REPOSITORY}-${HELM_TAG/v}\n  namespace: eksa-packages\nspec:\n  images:\n!\nJSON_SCHEMA_FILE=$PROJECT_ROOT/helm/schema.json\nSEDFILE=${OUTPUT_DIR}/helm/sedfile\nexport IMAGE_TAG\nexport HELM_TAG\nexport HELM_REGISTRY=$(aws ecr-public describe-registries --region us-east-1  --output text --query 'registries[*].registryUri')\nenvsubst <$PROJECT_ROOT/helm/sedfile.template >${SEDFILE}\n# Semver requires that our version begin with a digit, so strip the v.\necho \"s,version: v,version: ,g\" >>${SEDFILE}\nfor IMAGE in ${HELM_IMAGE_LIST:-}\ndo\n  if [ \"${IMAGE}\" == \"${HELM_DESTINATION_REPOSITORY}\" ] || [ \"${IMAGE_TAG}\" != \"${HELM_TAG}\" ]\n  then\n    TAG=\"${IMAGE_TAG}\"\n  else\n    TAG=\"${LATEST}\"\n  fi\n  IMAGE_SHASUM=$(${SCRIPT_ROOT}/image_shasum.sh ${HELM_REGISTRY} ${IMAGE} ${TAG}) ||\n  IMAGE_SHASUM=$(${SCRIPT_ROOT}/image_shasum.sh ${IMAGE_REGISTRY} ${IMAGE} ${TAG})\n  echo \"s,{{${IMAGE}}},${IMAGE_SHASUM},g\" >>${SEDFILE}\n  if [ \"${TAG}\" == \"latest\" ]\n  then\n    USE_TAG=$(aws --region us-east-1 ecr-public describe-images --repository-name ${IMAGE} --image-ids imageTag=latest --query 'imageDetails[0].imageTags' --output yaml | grep -v latest | head -1| sed -e 's/- //') ||\n    USE_TAG=$(aws ecr describe-images --repository-name ${IMAGE} --image-id imageTag=latest --query 'imageDetails[0].imageTags' --output yaml | grep -v latest | head -1| sed -e 's/- //') ||\n    USE_TAG=\"latest\"\n  else\n    USE_TAG=$TAG\n  fi\n  # If HELM_USE_UPSTREAM_IMAGE is true, we are using images from upstream.\n  # Though we pull images directly from upstream for build tooling checks (i.e.\n  # get images shasums), we will use cached images in the helm charts. Cached\n  # images follow the convention of ${PROJECT_NAME}/${UPSTREAM_IMAGE_NAME}.\n  if [ \"${HELM_USE_UPSTREAM_IMAGE}\" == true ]\n  then\n    PROJECT_NAME=$(echo \"$HELM_DESTINATION_REPOSITORY\" | awk -F \"/\" '{print $1}')\n    IMAGE_REPO=\"${PROJECT_NAME}/${IMAGE}\"\n  else\n    IMAGE_REPO=\"${IMAGE}\"\n  fi\n  cat >>${REQUIRES_FILE} <<!\n  - repository: ${IMAGE_REPO}\n    tag: ${USE_TAG}\n    digest: ${IMAGE_SHASUM}\n!\ndone\n\nif [ -n \"${FORCE_JSON_SCHEMA_FILE}\" ]\nthen \n  JSON_SCHEMA_FILE=${FORCE_JSON_SCHEMA_FILE}\nfi\n\nif [ -f ${JSON_SCHEMA_FILE} ]\nthen\n  JSON_SCHEMA=$(cat ${JSON_SCHEMA_FILE} | gzip | base64 | tr -d '\\n')\n  cat >>${REQUIRES_FILE} <<!\n  schema: ${JSON_SCHEMA}\n!\nfi\n\nif [ -n \"${PACKAGE_DEPENDENCIES}\" ]; then\n  echo \"  dependencies:\" >> ${REQUIRES_FILE}\n  echo ${PACKAGE_DEPENDENCIES} | tr ',' '\\n'  | while read dep; do\n      echo \"  - ${dep}\"\n  done >> ${REQUIRES_FILE}\nfi\n", "num_lines": 115}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREGISTRY=\"${1?First argument is registry}\"\nREPOSITORY=\"${2?Second argument is repository}\"\nIMAGE_TAG=\"${3?Third argument is image tag}\"\n\nif [ \"${JOB_TYPE:-}\" == \"presubmit\" ]\nthen\n  echo latest\n  exit 0\nfi\nTMPFILE=$(mktemp)\ntrap \"rm -f $TMPFILE\" exit\nTARGET=${REGISTRY}/${REPOSITORY}:${IMAGE_TAG}\nskopeo inspect -n --raw docker://${TARGET} >${TMPFILE}\nskopeo manifest-digest ${TMPFILE}\n", "num_lines": 35}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Taken from https://github.com/aws/eks-distro-build-tooling/blob/main/builder-base/install.sh\n# TODO: introduce a shared scripts repo to better share things like this\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nsetupgo() {\n    local -r version=$1\n    go install golang.org/dl/go${version}@latest\n    go${version} download\n    # Removing the patch number as we only care about the minor version of golang\n    local -r majorversion=$(cut -d. -f\"1,2\" <<< $version)\n    mkdir -p ${GOPATH}/go${majorversion}/bin\n    ln -sf ${GOPATH}/bin/go${version} ${GOPATH}/go${majorversion}/bin/go\n    ln -sf ${HOME}/sdk/go${version}/bin/gofmt ${GOPATH}/go${majorversion}/bin/gofmt\n}\n\nsetupgo \"${GOLANG116_VERSION:-1.16.15}\"\nsetupgo \"${GOLANG117_VERSION:-1.17.13}\"\nsetupgo \"${GOLANG118_VERSION:-1.18.10}\"\nsetupgo \"${GOLANG119_VERSION:-1.19.10}\"\nsetupgo \"${GOLANG120_VERSION:-1.20.5}\"\n\nbuild::common::use_go_version \"1.16\"\nGOBIN=${GOPATH}/go1.16/bin go install github.com/jaxesn/go-licenses@4497a2a38565e4e6ad095ea8117c25ecd622d0cc\n\nbuild::common::use_go_version \"1.17\"\nGOBIN=${GOPATH}/go1.17/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48\n\nbuild::common::use_go_version \"1.18\"\nGOBIN=${GOPATH}/go1.18/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48\n\nbuild::common::use_go_version \"1.19\"\nGOBIN=${GOPATH}/go1.19/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48\n\nbuild::common::use_go_version \"1.20\"\nGOBIN=${GOPATH}/go1.20/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48\n\n# 1.18 is the default so symlink it to /go/bin\nln -sf ${GOPATH}/go1.18/bin/go-licenses ${GOPATH}/bin\n", "num_lines": 60}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nfunction registry_ready() {\n  for i in {1..24}\n  do\n    if ! curl http://$IMAGE_REPO/ > /dev/null 2>&1;\n    then\n      echo \"Local registry at ${IMAGE_REPO} is not running. Retrying.\"\n      sleep 5\n    else\n      exit 0\n    fi\n  done\n  echo \"Local registry at ${IMAGE_REPO} is not available\"\n  exit 1\n}\n\nregistry_ready", "num_lines": 35}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#set -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nRETURN=0\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\nfor GIT_TAG_FILE in projects/*/*/GIT_TAG\ndo\n    VERSION=\"$(cat $GIT_TAG_FILE | $SED \"s,-,--,g\")\"\n    README=\"$(dirname $GIT_TAG_FILE)/README.md\"\n    if [ ! -f $README ]\n    then\n        echo \"Missing file $README\"\n        continue\n    fi\n    EXPECTED_VERSION=\"img.shields.io/badge/version-$VERSION\"\n    if grep -l \"$EXPECTED_VERSION\" ${README} >/dev/null\n    then\n        continue\n    fi\n    if ! grep \"img.shields.io/badge/version\" ${README} >/dev/null\n    then\n        echo \"Did not find version $README\"\n        continue\n    fi\n    RETURN=-1\n    ACTUAL_VERSION=$(grep \"img.shields.io/badge/version\" ${README} | $SED -e 's,.*img.shields.io/badge/version-,,' -e 's/-blue).*$//')\n    echo \"Version mismatch $README expected $VERSION actual $ACTUAL_VERSION\"\n    $SED -i -e \"s/$ACTUAL_VERSION/$VERSION/\" $README\ndone\n", "num_lines": 51}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT=\"$1\"\nTARGET=\"$2\"\nIMAGE_REPO=\"${3:-}\"\nRELEASE_BRANCH=\"${4:-}\"\nARTIFACTS_BUCKET=\"${5:-$ARTIFACTS_BUCKET}\"\nBASE_DIRECTORY=\"${6:-}\"\nGO_MOD_CACHE=\"${7:-}\"\nREMOVE=\"${8:-false}\"\nPLATFORM=\"${9:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nsource \"${SCRIPT_ROOT}/common.sh\"\n\n# Since we may actually be running docker in docker here for cgo builds\n# we need to have the host path base_dir and go_mod_cache and netrc\nDOCKER_RUN_BASE_DIRECTORY=\"${DOCKER_RUN_BASE_DIRECTORY:-$BASE_DIRECTORY}\"\nDOCKER_RUN_GO_MOD_CACHE=\"${DOCKER_RUN_GO_MOD_CACHE:-$GO_MOD_CACHE}\"\n\nMAKE_VARS=\"IMAGE_REPO=$IMAGE_REPO ARTIFACTS_BUCKET=$ARTIFACTS_BUCKET\"\n\nfunction remove_container()\n{\n\tdocker rm -vf $CONTAINER_ID\n}\n\nSKIP_RUN=\"false\"\nNAME=\"\"\nif [[ \"$REMOVE\" == \"false\" ]]; then\n\techo \"****************************************************************\"\n\techo \"A docker container with the name eks-a-builder will be launched.\"\n\techo \"It will be left running to support running consecutive runs.\"\n\techo \"Run 'make stop-docker-builder' when you are done to stop it.\"\n\techo \"****************************************************************\"\n\n\tNAME=\"--name eks-a-builder\"\n\n\tif docker ps -f name=eks-a-builder | grep -w eks-a-builder; then\n\t\tSKIP_RUN=\"true\"\n\t\tCONTAINER_ID=\"eks-a-builder\"\n\tfi\nelse\n\ttrap \"remove_container\" EXIT\nfi\n\nIMAGE=\"public.ecr.aws/eks-distro-build-tooling/builder-base:latest\"\nPLATFORM_ARG=\"\"\n\nif [[ -n \"$PLATFORM\" ]]; then\n\tDIGEST=$(docker buildx imagetools inspect --raw public.ecr.aws/eks-distro-build-tooling/builder-base:latest | jq -r \".manifests[] | select(.platform.architecture == \\\"${PLATFORM#linux/}\\\") | .digest\")\n\tIMAGE=\"public.ecr.aws/eks-distro-build-tooling/builder-base@$DIGEST\"\n\tPLATFORM_ARG=\"--platform $PLATFORM\"\n\tMAKE_VARS=\" BINARY_PLATFORMS=$PLATFORM\"\nfi\n\nif [[ \"$SKIP_RUN\" == \"false\" ]]; then\n\tbuild::docker::retry_pull $IMAGE\n\n\tNETRC=\"\"\n\tif [ -f $HOME/.netrc ]; then\n\t\tDOCKER_RUN_NETRC=\"${DOCKER_RUN_NETRC:-$HOME/.netrc}\"\n\t\tNETRC=\"--mount type=bind,source=$DOCKER_RUN_NETRC,target=/root/.netrc\"\n\telse\n\t\tDOCKER_RUN_NETRC=\"\"\n\tfi\n\n\tmkdir -p $DOCKER_RUN_GO_MOD_CACHE\n\tCONTAINER_ID=$(build::common::echo_and_run docker run -d $NAME --privileged $NETRC $PLATFORM_ARG \\\n\t\t--mount type=bind,source=$DOCKER_RUN_BASE_DIRECTORY,target=/eks-anywhere-build-tooling \\\n\t\t--mount type=bind,source=$DOCKER_RUN_GO_MOD_CACHE,target=/mod-cache \\\n\t\t-v /var/run/docker.sock:/var/run/docker.sock \\\n\t\t-e GOPROXY=${GOPROXY:-} -e GOMODCACHE=/mod-cache -e DOCKER_RUN_BASE_DIRECTORY=$DOCKER_RUN_BASE_DIRECTORY -e DOCKER_RUN_GO_MOD_CACHE=$DOCKER_RUN_GO_MOD_CACHE -e DOCKER_RUN_NETRC=$DOCKER_RUN_NETRC \\\n\t\t--entrypoint sleep $IMAGE infinity)\n\n\tdocker exec -it $CONTAINER_ID git config --global --add safe.directory /eks-anywhere-build-tooling\nfi\n\n\nbuild::common::echo_and_run docker exec -e RELEASE_BRANCH=$RELEASE_BRANCH -it $CONTAINER_ID \\\n\tmake $TARGET -C /eks-anywhere-build-tooling/projects/$PROJECT $MAKE_VARS\n", "num_lines": 100}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nsource /docker.sh \n\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\nGIT_CONFIG_SCOPE=\"--global\"\nif [[ \"$CODEBUILD_CI\" = \"true\" ]] && [[ \"$CODEBUILD_BUILD_ID\" =~ \"aws-staging-bundle-build\" ]]; then\n    GIT_CONFIG_SCOPE=\"--system\"\nfi\n\nif [ ! -d \"/root/.docker\" ]; then\n    mkdir -p /root/.docker\nfi\n\ncp config/docker-ecr-config.json /root/.docker/config.json\ngit config ${GIT_CONFIG_SCOPE} credential.helper '!aws codecommit credential-helper $@'\ngit config ${GIT_CONFIG_SCOPE} credential.UseHttpPath true\n\nstart::dockerd\nwait::for::dockerd\n\nbuild::docker::retry_pull public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v7.0.0\n\ndocker run --privileged --rm public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v7.0.0 --install aarch64,amd64\n", "num_lines": 32}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nTARGET_FILE=\"$2\"\nREPO=\"$3\"\nGOLANG_VERSION=\"$4\"\nBINARY_PLATFORMS=\"$5\"\nSOURCE_PATTERN=\"$6\"\nGOBUILD_COMMAND=\"$7\" \nEXTRA_GOBUILD_FLAGS=\"$8\"\nGO_LDFLAGS=\"$9\"\nCGO_ENABLED=\"${10}\"\nCGO_LDFLAGS=\"${11}\"\nREPO_SUBPATH=\"${12:-}\"\nALL_TARGET_FILES=\"${13:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nfunction build::simple::print_go_env(){\n  for var in \"GOOS\" \"GOARCH\" \"CGO_ENABLED\" \"GOCACHE\" \"GOFLAGS\"; do\n    if [ -n \"${!var:-}\" ]; then\n      echo \"$var: ${!var:-}\"\n    fi\n    if [ \"$var\" = \"CGO_ENABLED\" ] && [ \"${!var:-}\" = \"1\" ]; then\n      for other in \"CGO_LDFLAGS\" \"CGO_CFLAGS\" \"LD_LIBRARY_PATH\" \"PKG_CONFIG_PATH\"; do echo \"$other: ${!other:-}\"; done\n    fi\n  done\n}\n\nfunction build::simple::binaries(){\n  mkdir -p $(dirname $TARGET_FILE)\n  cd \"$PROJECT_ROOT/$REPO/$REPO_SUBPATH\"\n  build::common::use_go_version $GOLANG_VERSION\n  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })\n  for platform in \"${SUPPORTED_PLATFORMS[@]}\"; do\n    OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n    ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n    if [ $CGO_ENABLED = 1 ]; then\n      export CGO_LDFLAGS=\"$CGO_LDFLAGS,-L$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64\"\n      export CGO_CFLAGS=\"-I$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/include\"\n      export LD_LIBRARY_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64:${LD_LIBRARY_PATH-}\n      export PKG_CONFIG_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64/pkgconfig:${PKG_CONFIG_PATH-}\n    fi\n\n    # target file is meant to be treated as a folder since multiple binaries will written out\n    if [[ \"$TARGET_FILE\" == */ ]]; then\n      mkdir -p $TARGET_FILE\n    fi\n\n    echo \"Building binary(s): $ALL_TARGET_FILES\"\n    export CGO_ENABLED=$CGO_ENABLED GOOS=$OS GOARCH=$ARCH \n    \n    build::simple::print_go_env\n    \n    build::common::echo_and_run go $GOBUILD_COMMAND -trimpath -a -ldflags \"$GO_LDFLAGS\" $EXTRA_GOBUILD_FLAGS -o $TARGET_FILE $SOURCE_PATTERN\n\n    if [[ \"$TARGET_FILE\" == */ ]]; then\n      # in the case of outputing to a directory, the files will be named by the basename of the source pattern\n      # these need to be renamed to match the configured name from ALL_TARGET_FILES\n      TARGET_FILES=(${ALL_TARGET_FILES// / })\n      index=0\n      for source in $SOURCE_PATTERN; do\n        if [ \"$(basename $source)\" != \"${TARGET_FILES[$index]}\" ] && [ -f $TARGET_FILE$(basename $source) ]; then\n          # in the case of multiple target files but the first is a ., we cant move . but it should already be named correctly\n          build::common::echo_and_run mv $TARGET_FILE$(basename $source) $TARGET_FILE${TARGET_FILES[$index]}\n        fi\n        ((index=index+1))\n      done\n    fi\n  done\n}\n\nbuild::simple::binaries\n", "num_lines": 92}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAR_FILE_PREFIX=\"$1\"\nOUTPUT_DIR=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\nTAG=\"$4\"\nBINARY_PLATFORMS=\"$5\"\nTAR_PATH=\"$6\"\nGIT_HASH=\"$7\"\n\nLICENSE_PATHS=($(find $OUTPUT_DIR -type d -name \"LICENSES\"))\nATTRIBUTION_PATHS=($(find $OUTPUT_DIR -type f -name \"*ATTRIBUTION.txt\"))\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nfunction build::simple::tarball() {\n  build::common::ensure_tar\n  mkdir -p \"$TAR_PATH\"\n  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })\n  for platform in \"${SUPPORTED_PLATFORMS[@]}\"; do\n    OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n    ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n    TAR_FILE=\"${TAR_FILE_PREFIX}-${OS}-${ARCH}-${TAG}.tar.gz\"\n\n    for path in \"${LICENSE_PATHS[@]}\"; do\n      build::common::echo_and_run cp -rf $path ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/\n    done\n    for path in \"${ATTRIBUTION_PATHS[@]}\"; do\n      build::common::echo_and_run cp $path ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/\n    done\n    build::common::create_tarball ${TAR_PATH}/${TAR_FILE} ${OUTPUT_BIN_DIR}/${OS}-${ARCH} .\n  done\n  echo $GIT_HASH > $TAR_PATH/githash\n}\n\nbuild::simple::tarball\n", "num_lines": 55}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$1\"\nPROJECT_ROOT=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\n\n\nif [ ! -d ${OUTPUT_BIN_DIR} ] ;  then\n    echo \"${OUTPUT_BIN_DIR} not present! Run 'make binaries'\"\n    exit 1\nfi\n\nCHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS\n\nrm -f $CHECKSUMS_FILE\nfor file in $(find ${OUTPUT_BIN_DIR} -type f | sort); do\n    filepath=$(realpath --relative-base=$MAKE_ROOT $file)\n    sha256sum $filepath >> $CHECKSUMS_FILE\ndone\n\necho \"*************** CHECKSUMS ***************\"\ncat $CHECKSUMS_FILE\necho \"*****************************************\"\n", "num_lines": 41}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nif [[ -z \"${JOB_TYPE:-}\" ]] && [[ -z \"${CODEBUILD_CI:-}\" ]]; then\n    exit 0\nfi\n\nGOPATH=$GOPATH\nif [ -d \"/go\" ]; then\n    GOPATH=\"/go\"\nfi\n\nfor go in $GOPATH/go*/bin/go; do\n    VERSION=$($go version | grep -o \"go[0-9].* \" | grep -o \"[0-9\\.]*\")\n    NOPATCH=$(cut -d. -f\"1,2\" <<< $VERSION)\n    sed -i \"s,\\${GOLANG${NOPATCH//./}_VERSION:-.*},\\${GOLANG${NOPATCH//./}_VERSION:-$VERSION},\" ./build/lib/install_go_versions.sh \ndone\n", "num_lines": 38}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSRC_TAR_PATH=\"${1?Specify first argument - source tar path}\"\nARTIFACTS_BUCKET=\"${2?Specify second argument - artifacts buckets}\"\nPROJECT_PATH=\"${3? Specify third argument - project path}\"\nBUILD_IDENTIFIER=\"${4? Specify fourth argument - build identifier}\"\nGIT_HASH=\"${5?Specify fifth argument - git hash of the tar builds}\"\nLATEST_TAG=\"${6?Specify sixth argument - folder name corresponding to latest build}\"\nUPLOAD_DRY_RUN=\"${7?Specify seventh argument - Dry run upload}\"\nUPLOAD_DO_NOT_DELETE=\"${8?Specify eighth argument - Do not delete extra files in s3 bucket on upload}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nbuild::common::upload_artifacts $SRC_TAR_PATH $ARTIFACTS_BUCKET $PROJECT_PATH $BUILD_IDENTIFIER $GIT_HASH $LATEST_TAG $UPLOAD_DRY_RUN $UPLOAD_DO_NOT_DELETE", "num_lines": 33}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nPROJECT_ROOT=\"$1\"\nARTIFACTS_FOLDER=\"$2\"\nGIT_TAG=\"$3\"\nFAKE_ARM_ARTIFACTS_FOR_VALIDATION=\"$4\"\nFAKE_AMD_BINARIES_FOR_VALIDATION=\"$5\"\nIMAGE_FORMAT=\"${6:-}\"\nIMAGE_OS=\"${7:-}\"\n\nEXPECTED_FILES_PATH=$PROJECT_ROOT/expected_artifacts\nif [ -n \"$IMAGE_FORMAT\" ]; then\n  if [ \"$IMAGE_OS\" = \"bottlerocket\" ]; then\n    EXPECTED_FILES_PATH=${PROJECT_ROOT}/expected-artifacts/expected_artifacts_${IMAGE_FORMAT}_bottlerocket\n  else\n    EXPECTED_FILES_PATH=${PROJECT_ROOT}/expected-artifacts/expected_artifacts_${IMAGE_FORMAT}\n  fi\nfi\n\nREALPATH=realpath\nif which grealpath &>/dev/null; then\n    REALPATH=grealpath\nfi\n\nACTUAL_FILES=$(mktemp)\nfind \"$ARTIFACTS_FOLDER\" \\\n     -type f \\\n     -exec $REALPATH --relative-base=\"$ARTIFACTS_FOLDER\" {} \\; \\\n     > \"$ACTUAL_FILES\"\n\nEXPECTED_FILES=$(mktemp)\nbuild::common::echo_and_run export GIT_TAG=$GIT_TAG\nbuild::common::echo_and_run export IMAGE_OS=$IMAGE_OS\nenvsubst \"\\$GIT_TAG:\\$IMAGE_OS\" \\\n         < \"$EXPECTED_FILES_PATH\" \\\n         > \"$EXPECTED_FILES\"\n\nif $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then\n    echo \"Faking arm64 artifacts\"\n    sed -i '/arm64/d' \"$EXPECTED_FILES\"\nfi\n\nif $FAKE_AMD_BINARIES_FOR_VALIDATION; then\n    echo \"Faking amd64 artifacts\"\n    sed -i '/amd64/d' \"$EXPECTED_FILES\"\nfi\n\n# The versions of sort found on macOS and Linux can behave\n# differently. That's why we sort each file here and now, to ensure\n# that whatever version is in use, it's consistent.\necho \"diffing $EXPECTED_FILES $ACTUAL_FILES\"\nif ! diff -q <(sort \"$EXPECTED_FILES\") <(sort \"$ACTUAL_FILES\"); then\n    echo \"Artifacts directory does not matched expected!\"\n    diff -y <(sort \"$EXPECTED_FILES\") <(sort \"$ACTUAL_FILES\")\n    exit 1\nfi\n", "num_lines": 77}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$1\"\nPROJECT_ROOT=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\nFAKE_ARM_ARTIFACTS_FOR_VALIDATION=\"$4\"\nFAKE_AMD_BINARIES_FOR_VALIDATION=\"$5\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\nCHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS\n\nif $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then\n\tTEMP_FILE=$(mktemp)\n\tgrep -v 'arm64' $CHECKSUMS_FILE > $TEMP_FILE\n\tCHECKSUMS_FILE=$TEMP_FILE\nfi\n\nif $FAKE_AMD_BINARIES_FOR_VALIDATION; then\n\tTEMP_FILE=$(mktemp)\n\tgrep -v 'amd64' $CHECKSUMS_FILE > $TEMP_FILE\n\tCHECKSUMS_FILE=$TEMP_FILE\nfi\n\nif ! sha256sum -c $CHECKSUMS_FILE; then\n\techo \"Checksums do not match!\"\n\techo \"The correct checksums are printed below\"\n\techo \"Please only update if changing GIT_TAG or build flags.\"\n\t$SCRIPT_ROOT/update_checksums.sh $MAKE_ROOT $PROJECT_ROOT $OUTPUT_BIN_DIR\n\texit 1\nfi\n", "num_lines": 51}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nsource \"${SCRIPT_ROOT}/eksd_releases.sh\"\n\nFAILED=0\nfor release_branch in $(cat $SCRIPT_ROOT/../../release/SUPPORTED_RELEASE_BRANCHES); do\n    YAML_URL=$(build::eksd_releases::get_release_yaml_url $release_branch)\n    HTTP_CODE=$(curl -I -L -s -o /dev/null -w \"%{http_code}\" $YAML_URL)\n    if [[ \"$HTTP_CODE\" != \"200\" ]]; then\n        echo \"EKS-D manifest does not exist: $YAML_URL\"\n        FAILED=1\n        continue\n    fi   \n\n    build::eksd_releases::load_release_yaml $release_branch > /dev/null\n    COMPONENT_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $release_branch)\n    COMPONENT_VERSION_FROM_YAML=$(yq e \".releases[] | select(.branch==\\\"${release_branch}\\\").kubeVersion\" $SCRIPT_ROOT/../../EKSD_LATEST_RELEASES)\n\n    if [[ \"$COMPONENT_VERSION\" != \"$COMPONENT_VERSION_FROM_YAML\" ]]; then\n        echo \"kubeVersion: $COMPONENT_VERSION_FROM_YAML does not match version from EKS-D release manifest: $COMPONENT_VERSION\"\n        FAILED=1\n    fi\ndone\n\nif [[ \"$FAILED\" == \"0\" ]]; then\n    echo \"All EKS-D versions validated!\"\nfi\nexit $FAILED\n", "num_lines": 49}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2014 The Kubernetes Authors.\n# - https://github.com/kubernetes/kubernetes/blob/master/hack/lib/version.sh\n# Copyright 2020 The Kubernetes Authors.\n# - https://github.com/kubernetes-sigs/cluster-api/blob/main/hack/version.sh\n# Modifications Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. Licensed under the Apache2 License\n\n# Modifications:\n# Adapted upsteam code from kubernetes/kubernetes and CAPI to support the CAPI use case, but also be generic for other\n# projects built in this repo\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nversion::get_version_vars() {\n    local -r repo=$1\n    GIT_RELEASE_TAG=$(git -C $repo describe --match 'v[0-9]*.[0-9]*.[0-9]**' --abbrev=0 --tags)\n    GIT_RELEASE_COMMIT=$(git -C $repo rev-list -n 1  \"${GIT_RELEASE_TAG}\")\n\n    GIT_COMMIT=$GIT_RELEASE_COMMIT\n\n    # from k8s.io/hack/lib/version.sh\n    # Use git describe to find the version based on tags.\n    if GIT_VERSION=$GIT_RELEASE_TAG; then\n        # Try to match the \"git describe\" output to a regex to try to extract\n        # the \"major\" and \"minor\" versions and whether this is the exact tagged\n        # version or whether the tree is between two tagged versions.\n        if [[ \"${GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?([-].*)?([+].*)?$ ]]; then\n            GIT_MAJOR=${BASH_REMATCH[1]}\n            GIT_MINOR=${BASH_REMATCH[2]}\n        fi\n\n        # If GIT_VERSION is not a valid Semantic Version, then refuse to build.\n        if ! [[ \"${GIT_VERSION}\" =~ ^v([0-9]+)\\.([0-9]+)(\\.[0-9]+)?(-[0-9A-Za-z.-]+)?(\\+[0-9A-Za-z.-]+)?$ ]]; then\n            echo \"GIT_VERSION should be a valid Semantic Version. Current value: ${GIT_VERSION}\"\n            echo \"Please see more details here: https://semver.org\"\n            exit 1\n        fi\n    fi\n\n\n}\n\n# Prints the value that needs to be passed to the -ldflags parameter of go build\nversion::ldflags() {\n    local -r repo=$1\n    local -r package_prefix=$2\n    version::get_version_vars $repo\n\n    # from k8s.io/hack/lib/version.sh\n    local -a ldflags\n    function add_ldflag() {\n        local key=${1}\n        local val=${2}\n        ldflags+=(\n            \"-X '${package_prefix}.${key}=${val}'\"\n        )\n    }\n    DATE=date\n    if which gdate &>/dev/null; then\n        DATE=gdate\n    elif which gnudate &>/dev/null; then\n        DATE=gnudate\n    fi\n    \n    # buildDate is not actual buildDate to avoid it breaking reproducible checksums\n    # instead it is the date of the last commit, either the upstream TAG commit or the latest patch applied\n    SOURCE_DATE_EPOCH=$(git -C $repo log -1 --format=%at)\n    add_ldflag \"buildDate\" \"$(${DATE} --date=@${SOURCE_DATE_EPOCH} -u +'%Y-%m-%dT%H:%M:%SZ')\"\n    add_ldflag \"gitCommit\" \"${GIT_COMMIT}\"\n    add_ldflag \"gitTreeState\" \"clean\"\n    add_ldflag \"gitMajor\" \"${GIT_MAJOR}\"\n    add_ldflag \"gitMinor\" \"${GIT_MINOR}\"\n    add_ldflag \"gitVersion\" \"${GIT_VERSION}\"\n    add_ldflag \"gitReleaseCommit\" \"${GIT_RELEASE_COMMIT}\"\n\n    # The -ldflags parameter takes a single string, so join the output.\n    echo \"${ldflags[*]-}\"\n}\n\nversion::ldflags $1 $2\n", "num_lines": 84}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAG=\"$1\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nbuild::common::wait_for_tag $TAG\n", "num_lines": 27}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nif [[ -z \"${JOB_TYPE:-}\" ]] && [[ -z \"${CODEBUILD_CI:-}\" ]]; then\n    exit 0\nfi\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nsource $SCRIPT_ROOT/../lib/common.sh\n\nSKIP_PR=\"${1:-false}\"\n\nORIGIN_ORG=\"eks-distro-pr-bot\"\nUPSTREAM_ORG=\"aws\"\nREPO=\"eks-anywhere-build-tooling\"\n\nMAIN_BRANCH=\"main\"\n\nif [[ -n \"${CODEBUILD_SOURCE_VERSION:-}\" ]]; then\n    MAIN_BRANCH=\"$CODEBUILD_SOURCE_VERSION\"\nfi\n\nif [[ -n \"${PULL_BASE_REF:-}\" ]]; then\n    MAIN_BRANCH=\"$PULL_BASE_REF\"\nfi\n\nfunction pr::github::should_auth()\n{\n    [[ \"${JOB_TYPE:-}\" == \"periodic\" ]] || [[ -n \"${CODEBUILD_CI:-}\" ]]\n}\n\nfunction commit_push()\n{\n    local -r pr_branch=\"$1\"\n    local force_push=\"$2\"\n\n    if [[ \"$force_push\" = \"true\" ]]; then\n        force_push=\"-f\"\n    else\n        force_push=\"\"\n    fi\n\n    if build::common::echo_and_run git push $force_push -u bot $pr_branch; then\n        echo \"Commit pushed\"\n        return\n    fi\n\n    # Other jobs could be running and updating the same branch, which is expected\n    # attempt to rebase and retry\n    build::common::echo_and_run git fetch -q bot\n    build::common::echo_and_run git branch --set-upstream-to=bot/$pr_branch $pr_branch\n    \n    # rebase succeeded, return 1 to retry the push\n    if build::common::echo_and_run git rebase bot/$pr_branch; then\n        echo \"Rebased local branch, retrying\"\n        return 1\n    fi\n\n    git status\n    git diff HEAD -- $(git diff --name-only --diff-filter=U)\n\n    # rebase failed with conflict, exit with error\n    exit 1\n}\n\nfunction pr::commit::push()\n{\n    local -r commit_message=\"$1\"\n    local -r pr_branch=\"$2\"\n    local -r force_push=\"${3:-true}\"\n\n    build::common::echo_and_run git checkout -B $pr_branch\n\n    git diff --staged\n    local -r files_added=$(git diff --staged --name-only)\n    if [ \"$files_added\" = \"\" ]; then\n        echo \"No files changed to commit\"\n        return 1\n    fi\n    \n    build::common::echo_and_run git status\n    build::common::echo_and_run git commit -m \"$commit_message\" || true\n\n    if ! pr::github::should_auth; then\n        echo \"Skipping commit push due to missing correct job type\"\n        return 1\n    fi\n\n    if pr::github::auth; then\n        retry commit_push \"$pr_branch\" \"$force_push\"\n    fi\n}\n\nfunction pr::create()\n{\n    local -r pr_title=\"$1\"\n    local -r pr_branch=\"$2\"\n    local -r pr_body=\"$3\"\n\n    if ! pr::github::should_auth; then\n        echo \"Skipping PR creation due to missing correct job type\"\n        return\n    fi\n\n    if [[ \"${SKIP_PR}\" == \"true\" ]]; then\n        echo \"Skipping PR creation\"\n        return\n    fi\n\n    if ! pr::github::auth; then\n        echo \"Skipping PR creation due to missing Github auth creds\"\n        return\n    fi\n\n    if ! git ls-remote --exit-code bot $pr_branch; then\n        echo \"Skipping PR creation due to missing upstream branch: $pr_branch\"\n        return\n    fi\n\n    local pr_exists=$(GH_PAGER='' gh pr list --json number -H \"$pr_branch\")\n    if [ \"$pr_exists\" != \"[]\" ]; then\n        # already exists\n        echo \"PR already exists.\"\n        return\n    fi    \n\n    build::common::echo_and_run gh pr create --title \"$pr_title\" --body \"$pr_body\" --base $MAIN_BRANCH --head $ORIGIN_ORG:$pr_branch\n}\n\nfunction pr::github::auth()\n{\n    if [[ -z \"${GITHUB_TOKEN:-}\" ]] && [[ ! -f /secrets/github-secrets/token ]]; then\n        echo \"Missing GITHUB_TOKEN or /secrets/github-secrets/token, cannot authenticate\"\n        return 1\n    fi\n\n    if [ -f /secrets/github-secrets/token ]; then\n        gh auth login --with-token < /secrets/github-secrets/token\n    fi\n\n    gh auth setup-git\n    gh api rate_limit\n    \n    gh repo set-default \"${UPSTREAM_ORG}/${REPO}\"\n}\n\nfunction pr::create::pr_body(){\n    pr_body=\"\"\n    case $1 in\n    attribution)\n        pr_body=$(cat <<'EOF'\nThis PR updates the ATTRIBUTION.txt files across all dependency projects if there have been changes.\n\nThese files should only be changing due to project GIT_TAG bumps or Golang version upgrades. If changes are for any other reason, please review carefully before merging!\nEOF\n)\n        ;;\n    checksums)\n        pr_body=$(cat <<EOF\nThis PR updates the CHECKSUMS files across all dependency projects if there have been changes.\n\nThese files should only be changing due to project GIT_TAG bumps or Golang version upgrades. If changes are for any other reason, please review carefully before merging!\n\nThese files were generated using $CODEBUILD_BUILD_IMAGE\nEOF\n)\n        ;;\n    makehelp)\n        pr_body=$(cat <<'EOF'\nThis PR updates the Help.mk files across all dependency projects if there have been changes.\nEOF\n)\n        ;;\n    go-mod)\n        pr_body=$(cat <<'EOF'\nThis PR updates the checked in go.mod and go.sum files across all dependency projects to support automated vulnerability scanning.\nEOF\n)\n        ;;\n    *)\n        echo \"Invalid argument: $1\"\n        exit 1\n        ;;\n    esac\n    PROW_BUCKET_NAME=$(echo $JOB_SPEC | jq -r \".decoration_config.gcs_configuration.bucket\" | awk -F// '{print $NF}')\n    full_pr_body=$(printf \"%s\\n\\n/hold\\n\\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\" \"$pr_body\")\n\n    printf \"$full_pr_body\"\n}\n\nfunction pr::create::attribution() {\n    local -r pr_title=\"Update ATTRIBUTION.txt files\"\n    local commit_message=\"[PR BOT] Update ATTRIBUTION.txt files\"\n    local pr_branch=\"attribution-files-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"attribution\")\n    \n    local force_push=\"true\"\n    if [ -n \"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\" ]; then\n        pr_branch+=\"-$CODEBUILD_RESOLVED_SOURCE_VERSION\"\n        force_push=\"false\"\n\n        local -r changed_files=$(git diff --staged --name-only | grep \"^projects\" | cut -d '/' -f2- | uniq | tr  '\\n' ' ')\n        commit_message=\"[PR BOT] Update $changed_files\"\n    fi\n\n    # always try to create pr if running in codebuild\n    if pr::commit::push \"$commit_message\" \"$pr_branch\" \"$force_push\" || [ -n \"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\" ]; then\n        pr::create \"$pr_title\" \"$pr_branch\" \"$pr_body\"\n    fi\n}\n\nfunction pr::create::checksums() {\n    local -r pr_title=\"Update CHECKSUMS files\"\n    local pr_branch=\"checksums-files-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"checksums\")\n\n    local force_push=\"true\"\n    if [ -n \"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\" ]; then\n        pr_branch+=\"-$CODEBUILD_RESOLVED_SOURCE_VERSION\"\n        force_push=\"false\"\n    fi\n\n    # This file is being added as it may have been updated by the last lines of ./build/lib/update_go_versions.sh,\n    # which replaces the go version in this script with the go version(s) in the builder base if they are newer \n    # when running `make update-checksum-files`\n    build::common::echo_and_run git add ./build/lib/install_go_versions.sh\n\n    # stash checksums and attribution and help.mk files\n    build::common::echo_and_run git stash --keep-index\n    \n    # ignore return since we always want to try and create_pr\n    pr::commit::push \"[PR BOT] Update install_go_versions.sh\" \"$pr_branch\" \"$force_push\" || true\n\n    pr::stash::pop\n\n    # Add checksum files\n    for FILE in $(find . -type f -name CHECKSUMS); do\n        if [[ \"0 1\" == \"$(git diff --numstat $FILE | awk -F ' ' '{print $1,$2}')\" ]]; then\n            echo \"Ignoring changes to $FILE since only changes are deletions\"\n            git diff $FILE\n            git checkout -- $FILE\n            continue\n        fi\n        pr::file:add $FILE\n    done\n\n    # stash attribution and help.mk files\n    build::common::echo_and_run git stash --keep-index\n\n    local -r changed_files=$(git diff --staged --name-only | grep \"^projects\" | cut -d '/' -f2- | uniq | tr  '\\n' ' ')\n    local -r commit_message=\"[PR BOT] Update $changed_files\"\n \n    # always try to create pr if running in codebuild\n    if pr::commit::push \"$commit_message\" \"$pr_branch\" \"$force_push\" || [ -n \"${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\" ]; then\n        pr::create \"$pr_title\" \"$pr_branch\" \"$pr_body\"\n    fi\n}\n\nfunction pr::create::help() {\n    local -r pr_title=\"Update Makefile generated help\"\n    local -r commit_message=\"[PR BOT] Update Help.mk files\"\n    local -r pr_branch=\"help-makefiles-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"makehelp\")\n\n    if pr::commit::push \"$commit_message\" \"$pr_branch\"; then\n        pr::create \"$pr_title\" \"$pr_branch\" \"$pr_body\"\n    fi\n}\n\nfunction pr::create::go-mod() {\n    local -r pr_title=\"Update go.mod files\"\n    local -r commit_message=\"[PR BOT] Update go.mod files\"\n    local -r pr_branch=\"go-mod-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"go-mod\")\n\n    if pr::commit::push \"$commit_message\" \"$pr_branch\"; then\n        pr::create \"$pr_title\" \"$pr_branch\" \"$pr_body\"\n    fi\n}\n\nfunction pr::file:add() {\n    local -r file=\"$1\"\n\n    if git check-ignore -q $FILE; then\n        return\n    fi\n\n    local -r diff=\"$(git diff --ignore-blank-lines --ignore-all-space $FILE)\"\n    if [[ -z $diff ]]; then\n        return\n    fi\n\n    git add $file\n}\n\nfunction pr::stash::pop() {\n    if [ \"$(git stash list)\" != \"\" ]; then\n        build::common::echo_and_run git stash pop\n    fi\n}\n\ncd ${SCRIPT_ROOT}/../../\ngit config --global push.default current\ngit config user.name \"EKS Distro PR Bot\"\ngit config user.email \"aws-model-rocket-bots+eksdistroprbot@amazon.com\"\ngit config remote.upstream.url >&- || git remote add upstream https://github.com/${UPSTREAM_ORG}/${REPO}.git\ngit config remote.bot.url >&- || git remote add bot https://github.com/${ORIGIN_ORG}/${REPO}.git\n\n# Files have already changed, stash to perform rebase\nbuild::common::echo_and_run git stash\n\nbuild::common::echo_and_run git checkout $MAIN_BRANCH\n\n# avoid hitting github limits in presubmits\nif pr::github::should_auth; then\n    build::common::echo_and_run retry git fetch -q upstream\n\n    # there will be conflicts before we are on the bots fork at this point\n    # -Xtheirs instructs git to favor the changes from the current branch\n    build::common::echo_and_run git rebase -Xtheirs upstream/$MAIN_BRANCH\nfi\n\npr::stash::pop\n\necho -e \"\\n-------------------------- Adding Checksum files ---------------------------\\n\"\n\npr::create::checksums\n\necho -e \"\\n----------------------------------------------------------------------------\\n\"\n\nbuild::common::echo_and_run git checkout $MAIN_BRANCH\n\npr::stash::pop\n\necho -e \"\\n-------------------------- Adding ATTRIBUTION files ------------------------\\n\"\n\n# Add attribution files\nfor FILE in $(find . -type f \\( -name \"*ATTRIBUTION.txt\" ! -path \"*/_output/*\" \\)); do\n    pr::file:add $FILE\ndone\n\n# stash help.mk files\ngit stash --keep-index\n\npr::create::attribution\n\necho -e \"\\n----------------------------------------------------------------------------\\n\"\n\nbuild::common::echo_and_run git checkout $MAIN_BRANCH\n\npr::stash::pop\n\necho -e \"\\n-------------------------- Adding Help.mk files -----------------------------\\n\"\n\n# Add help.mk/Makefile files\nfor FILE in $(find . -type f \\( -name Help.mk -o -name Makefile \\)); do\n    pr::file:add $FILE\ndone\n\npr::create::help\n\necho -e \"\\n----------------------------------------------------------------------------\\n\"\n", "num_lines": 379}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o errexit\nset -o nounset\nset -o pipefail\nshopt -s globstar\n\nPROJECT=\"$1\"\nTARGET=\"$2\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nPROJECT_ROOT=$MAKE_ROOT/$PROJECT\n\nOUTPUT_DIR=$MAKE_ROOT/_output\nmkdir -p $OUTPUT_DIR\ntouch $OUTPUT_DIR/total_summary.txt\n\nfunction build::attribution::generate(){\n    make -C $PROJECT_ROOT $TARGET\n\n    if ls $PROJECT_ROOT/_output/**/summary.txt 1> /dev/null 2>&1; then\n        for summary in $PROJECT_ROOT/_output/**/summary.txt; do\n            sed -i \"s/+.*=/ =/g\" $summary\n            awk -F\" => \" '{ count[$1]+=$2} END { for (item in count) printf(\"%s => %d\\n\", item, count[item]) }' \\\n                $summary $OUTPUT_DIR/total_summary.txt | sort > $OUTPUT_DIR/total_summary.tmp && mv $OUTPUT_DIR/total_summary.tmp $OUTPUT_DIR/total_summary.txt\n        done\n    fi\n}\n\n\n# Some projects have specific folders for different kubernetes release\n# dynamically find all versions to avoid having to update with every release\nRELEASE_FOLDER=$(find $PROJECT_ROOT -type d -maxdepth 1 -name \"1-*\")\nSUPPORTED_RELEASE_BRANCHES=$(cat $MAKE_ROOT/release/SUPPORTED_RELEASE_BRANCHES)\n\nif [ -z \"${RELEASE_FOLDER}\" ]; then\n    build::attribution::generate\nelse\n    LAST_GIT_TAG=\"\"\n    LAST_RELEASE_BRANCH=\"\"\n    for release_folder in $PROJECT_ROOT/1-*/ ; do\n        release=$(basename $release_folder)\n\n        # if release is no longer a supported release branch, skip it\n        if [[ ! \"$SUPPORTED_RELEASE_BRANCHES\" == *\"$release\"* ]]; then\n            echo \"Skipping $release, no longer supported\"\n            continue\n        fi\n\n        # some projects have release folders but no git_tag since they do not build binaries\n        if [ ! -f $PROJECT_ROOT/$release/GIT_TAG ]; then\n            continue\n        fi\n\n        export RELEASE_BRANCH=\"$release\"\n\n        GIT_TAG=\"$(cat $PROJECT_ROOT/$release/GIT_TAG)\"\n        if [ \"$GIT_TAG\" != \"$LAST_GIT_TAG\" ] || [ $TARGET == \"update-go-mods\" ]; then\n            # clean before regenerating to ensure there are no intermediate files left around\n            make -C $PROJECT_ROOT clean clean-go-cache\n            build::attribution::generate $release\n        else\n            # if the git_tags match across release branches, save the output state to avoid\n            # rebuilding/regenerating\n            if [[ $TARGET == *\"checksums\"* ]]; then\n                echo \"Copying $LAST_RELEASE_BRANCH CHECKSUMS to $release\"\n                mkdir -p $PROJECT_ROOT/_output/$release\n                sed \"s/$LAST_RELEASE_BRANCH/$release/\" $PROJECT_ROOT/$LAST_RELEASE_BRANCH/CHECKSUMS > $PROJECT_ROOT/$release/CHECKSUMS\n            fi\n\n            if [[ $TARGET == *\"attribution\"* ]]; then\n                echo \"Copying $LAST_RELEASE_BRANCH ATTRIBUTION to $release\"\n                mkdir -p $PROJECT_ROOT/_output/$release\n                cp -rf $PROJECT_ROOT/$LAST_RELEASE_BRANCH/*TTRIBUTION.txt $PROJECT_ROOT/$release\n            fi            \n        fi\n        LAST_GIT_TAG=\"$GIT_TAG\"\n        LAST_RELEASE_BRANCH=\"$release\"\n    done\nfi\n\nmake -C $PROJECT_ROOT clean clean-go-cache\n", "num_lines": 97}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nmkdir -p $ARTIFACTS_PATH\n\n# TODO: once cloning snow provider source run standard make targert\nmkdir -p $ARTIFACTS_PATH/manifests/infrastructure-snow/$TAG\ncp -rf manifests/* $ARTIFACTS_PATH/manifests/infrastructure-snow/$TAG\n", "num_lines": 36}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\nAMI_MANIFEST_OUTPUT=\"${1?Specify first argument - AMI manifest output file from packer}\"\nIMAGE_FORMAT=\"${2?Specify second argument - Format for exported image \\(vmdk\\|raw\\|vhd\\)}\"\nS3_DST_EXPORT_PATH=\"${3?Specify third argument - Destination S3 path}\"\nREPLICAS=\"${4?Specify fourth argument - Comma separated list of s3 destinations for exported image copies}\"\n\nARTIFACT_ID=$(cat $AMI_MANIFEST_OUTPUT | jq -r '.builds[0].artifact_id')\nARTIFACT_ID_SPLIT=(${ARTIFACT_ID//:/ })\nAMI_ID=${ARTIFACT_ID_SPLIT[1]}\n\nREPLICAS_SPLIT=(${REPLICAS//,/ })\n\nDST_BUCKET_PATH=${S3_DST_EXPORT_PATH#\"s3://\"}\nDST_BUCKET_NAME=${DST_BUCKET_PATH%%/*}\nDST_PATH=${DST_BUCKET_PATH#\"$DST_BUCKET_NAME/\"}\n\nEXPORTED_IMAGE_PREFIX=\"$DST_PATH\"\n\nEXPORT_RESPONSE=$(aws ec2 export-image --disk-image-format $IMAGE_FORMAT --s3-export-location S3Bucket=$DST_BUCKET_NAME,S3Prefix=$EXPORTED_IMAGE_PREFIX --image-id $AMI_ID)\necho $EXPORT_RESPONSE\n\nEXPORT_TASK_ID=$(echo $EXPORT_RESPONSE | jq -r '.ExportImageTaskId')\nEXPORTED_IMAGE_KEY=\"${EXPORTED_IMAGE_PREFIX}${EXPORT_TASK_ID}.${IMAGE_FORMAT}\"\nEXPORTED_IMAGE_LOCATION=\"s3://${DST_BUCKET_NAME}/${EXPORTED_IMAGE_KEY}\"\nEXPORTED_IMAGE_URL=\"https://${DST_BUCKET_NAME}.s3.amazonaws.com/${EXPORTED_IMAGE_KEY}\"\n\nFINAL_STATUSES=(completed deleted)\nSTATUS=$(echo $EXPORT_RESPONSE | jq -r '.Status')\nSTATUS_MESSAGE=$(echo $EXPORT_RESPONSE | jq -r '.StatusMessage')\nPROGRESS=$(echo $EXPORT_RESPONSE | jq -r '.Progress')\n\nuntil [[ \"${FINAL_STATUSES[*]}\" =~ \"${STATUS}\" ]]; do\n  echo \"Image import is $STATUS: $STATUS_MESSAGE $PROGRESS%\"\n  sleep 30\n\n  DESCRIBE_RESPONSE=$(aws ec2 describe-export-image-tasks --export-image-task-ids $EXPORT_TASK_ID)\n  STATUS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Status')\n  STATUS_MESSAGE=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].StatusMessage')\n  PROGRESS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Progress')\ndone\n\nif [[ \"$STATUS\" != \"completed\" ]]; then\n    echo \"Image import failed: $STATUS - $STATUS_MESSAGE\"\n    exit 1\nfi\n\necho \"Image import for ami $AMI_ID succeeded\"\n\naws s3api put-object-acl --bucket $DST_BUCKET_NAME --key $EXPORTED_IMAGE_KEY --acl public-read\nEXPORTED_IMAGE_SHA256=$(curl -s $EXPORTED_IMAGE_URL | sha256sum | cut -d\" \" -f1)\nfor dst in \"${REPLICAS_SPLIT[@]}\"\ndo\n  echo \"Copying exported image to $dst\"\n  aws s3 cp --no-progress --acl public-read $EXPORTED_IMAGE_LOCATION $dst\n  echo -n \"$EXPORTED_IMAGE_SHA256  $(basename $dst)\" > $(basename $dst).sha256\n  aws s3 cp --no-progress --acl public-read $(basename $dst).sha256 $dst.sha256\ndone\n", "num_lines": 77}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\nBUCKET=\"${1?Specify second argument - s3 bucket}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../../../..\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/build/lib/common.sh\"\n\nOS=linux\nREPO=client\nARCH=amd64\nNAME=\"kubernetes-sigs/kind\"\nRELEASE_BRANCH=$(build::eksd_releases::get_release_branch)\n\necho $(build::common::get_latest_eksa_asset_url $BUCKET $NAME $ARCH $RELEASE_BRANCH)", "num_lines": 20}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../../../..\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/build/lib/common.sh\"\n\nOS=linux\nREPO=client\nARCH=amd64\nNAME=\"bin/$OS/$ARCH/kubectl\"\nRELEASE_BRANCH=$(build::eksd_releases::get_release_branch)\n\necho $(build::eksd_releases::get_eksd_kubernetes_asset_url $NAME $RELEASE_BRANCH $ARCH)", "num_lines": 17}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nRELEASES_MANIFEST=$(curl --silent -L $EKSA_RELEASE_MANIFEST_URL)\n\nnewest_release_date=0\nnewest_release_version=\"\"\n\nwhile IFS=$'\\t' read -r date version _; do\n    # date is something like '2022-05-05 13:05:34.038243612 +0000 UTC'\n    # I can't get `date` to parse this format, so deleting the extra timezone first\n    parsed_date=$(date -d \"$(echo $date | awk '{print $1,$2,$3}')\" +\"%s\")\n\n    if [ $parsed_date -gt $newest_release_date ];\n    then\n        newest_release_date=$parsed_date\n        newest_release_version=$version\n    fi  \ndone < <(echo \"$RELEASES_MANIFEST\" | yq e '.spec.releases[] | [.date, .version] | @tsv' -)\n\nif [ -z \"${newest_release_version}\" ]; then\n    echo \"Not valid release found\"\n    exit 1\nfi\n\necho -n \"$newest_release_version\"", "num_lines": 30}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nLATEST_EKSA_RELEASE_NUMBER=$(curl $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.releases[] | select(.version == '\\\"$EKSA_VERSION\\\"') | .number')\nPROD_RELEASE_ADMIN_AMI_DESTINATION=\"s3://$EKSA_PRODUCTION_ARTIFACTS_BUCKET/releases/eks-a/$LATEST_EKSA_RELEASE_NUMBER/artifacts/eks-a-admin-ami/$EKSA_VERSION/eks-anywhere-admin-ami-$EKSA_VERSION-eks-a-$LATEST_EKSA_RELEASE_NUMBER.raw\"\n\necho $PROD_RELEASE_ADMIN_AMI_DESTINATION\n", "num_lines": 12}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSA_RELEASE_MANIFEST_S3_URL=\"${1?Specify first argument - Canonical S3 URL for the EKS-A releases manifest}\"\nEKSA_RELEASE_MANIFEST_CDN_URL=\"${2?Specify second argument - CloudFront URL for the EKS-A releases manifest}\"\n\nn=0\nmax_attempts=120\ndelay=30\nwhile true; do\n    LATEST_EKSA_VERSION_S3=$(curl $EKSA_RELEASE_MANIFEST_S3_URL | yq e '.spec.latestVersion' -)\n    LATEST_EKSA_VERSION_CLOUDFRONT=$(curl $EKSA_RELEASE_MANIFEST_CDN_URL | yq e '.spec.latestVersion' -)\n    [[ \"$LATEST_EKSA_VERSION_S3\" == \"$LATEST_EKSA_VERSION_CLOUDFRONT\" ]] && break || {\n        if [[ $n -lt $max_attempts ]]; then\n            ((n++))\n            echo \"Older version of release manifest is cached in CloudFront, waiting for cache to be updated - Attempt $n/$max\"\n            sleep $delay;\n        else\n            echo \"Timeout occured after $n attempts waiting for CloudFront cache to be updated\"\n            exit 1\n        fi\n    }\ndone\n", "num_lines": 28}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nsudo bash -c 'cat <<'EOF' >> /etc/docker/daemon.json\n{\n  \"log-driver\": \"journald\",\n  \"log-level\": \"debug\"\n}\nEOF'\n\nsudo systemctl restart docker --no-block", "num_lines": 15}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSA_MANIFESTS_PATH=\"${EKSA_MANIFESTS_PATH:-/usr/lib/eks-a/manifests}\" # The full path where eks-a manifests will be downloaded\nEKSA_ARTIFACTS_TAR_PATH=\"${EKSA_ARTIFACTS_TAR_PATH:-/usr/lib/eks-a/artifacts/artifacts.tar.gz}\" # The path where the tar containing all eks-a container artifacts will be stored\n\nsudo mkdir -p $EKSA_MANIFESTS_PATH\nsudo -E env \"PATH=$PATH\" eksctl anywhere download artifacts --retain-dir --download-dir $EKSA_MANIFESTS_PATH -v4\nsudo chmod -R a+r $EKSA_MANIFESTS_PATH\n\nARTIFACTS_NAME_DIR=$(dirname $EKSA_ARTIFACTS_TAR_PATH)\nsudo mkdir -p $ARTIFACTS_NAME_DIR\nsudo -E env \"PATH=$PATH\" eksctl anywhere download images -o $EKSA_ARTIFACTS_TAR_PATH -v4\nsudo chmod -R a+r $ARTIFACTS_NAME_DIR\n\n# The download images command pulls down all the images in the bundle\n# but after the images get saved to a tar archive, the images are still\n# in the local Docker runtime, that bloats the final admin image. This can\n# cause downstream resource heavy operations to fail due to lack of disk\n# space. To mitigate this, we prune all the dangling and unused images and\n# volumes to increase the free disk space on the admin image.\nsudo docker system prune --all --volumes --force\n", "num_lines": 27}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Install packages\nsudo apt-get update -y\nsudo apt-get install -y python python3 python3-pip\nsudo apt-get install -y awscli\nsudo snap install jq", "num_lines": 12}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho $EKSA_VERSION\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSCTL_VERSION=\"${EKSCTL_VERSION:-latest}\" # The eksctl version to install (example v0.0.0)\nEKSA_RELEASE_MANIFEST_URL=\"${EKSA_RELEASE_MANIFEST_URL:-https://anywhere-assets.eks.amazonaws.com/releases/eks-a/manifest.yaml}\" # The url pointing to the eks-a releases manifest\nEKSA_VERSION=\"${EKSA_VERSION:-latest}\" # The eks-a version to install (example v0.0.0)\n\n# Install eksctl\nmkdir eksctl_tmp\nif [[ \"$EKSCTL_VERSION\" == \"latest\" ]]; then\n\tEKSCTL_URL=\"https://github.com/weaveworks/eksctl/releases/latest/download/eksctl_linux_amd64.tar.gz\"\nelse\n\tEKSCTL_URL=\"https://github.com/weaveworks/eksctl/releases/download/${EKSCTL_VERSION}/eksctl_linux_amd64.tar.gz\"\nfi\ncurl -L --silent $EKSCTL_URL | tar xz -C ./eksctl_tmp\n\nsudo mv eksctl_tmp/eksctl /usr/local/bin/\nrm -rf eksctl_tmp\n\n# Install eksctl-anywhere\nmkdir eksa_tmp\nif [[ \"$EKSA_VERSION\" == \"latest\" || \"$EKSA_VERSION\" == \"v0.0.0\" ]]; then\n\tEKSA_VERSION=$(curl -L --silent $EKSA_RELEASE_MANIFEST_URL |  yq e '.spec.latestVersion' -)\nfi\nEKSA_TAR_URL=$(curl -L --silent $EKSA_RELEASE_MANIFEST_URL | yq e '.spec.releases[] | select(.version == \"'$EKSA_VERSION'\") | .eksABinary.linux.uri')\ncurl -L --silent $EKSA_TAR_URL | tar xz -C ./eksa_tmp\n\nsudo mv eksa_tmp/eksctl-anywhere /usr/local/bin/\nrm -rf eksa_tmp\n", "num_lines": 36}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ \"$GO_VERSION\" == \"latest\" ]]; then\n    GO_VERSION=\"$(curl --silent https://go.dev/VERSION?m=text)\";\n    GO_URL=\"https://go.dev/dl/${GO_VERSION}.linux-amd64.tar.gz\"\nelse\n    GO_URL=\"https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz\"\nfi\n\nsudo apt-get install -y tar\nsudo apt-get install -y git\n\ncurl -L --silent $GO_URL | sudo tar xz -C /usr/local\n\nexport GOROOT=/usr/local/go\nexport GOPATH=/usr/local/go/packages\nexport GOPROXY=direct\n\nsudo sh -c \"echo 'PATH=\\$PATH:$GOROOT/bin:$GOPATH/bin' >> /etc/profile.d/golang.sh\"\n\nsource /etc/profile.d/golang.sh\n\nGO=/usr/local/go/bin/go\n\n$GO version\n\n# required for e2e tests\nsudo GOPROXY=direct GOPATH=/usr/local/go/packages $GO install gotest.tools/gotestsum@latest\nsudo cp $GOPATH/bin/gotestsum /usr/local/bin/gotestsum\n\nsudo env GOOS=linux GOARCH=amd64 CGO_ENABLED=0 $GO build -o test2json -ldflags=\"-s -w\" cmd/test2json\nsudo mv test2json /usr/local/bin/test2json", "num_lines": 37}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Install packages\nsudo apt-get update -y\nsudo apt-get install -y ipmitool", "num_lines": 10}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# KIND_URL needs to be provided to the script as envvar\n\nsudo apt-get install -y tar\n\nmkdir kind_tmp\n\ncurl --silent -L $KIND_URL  | tar xz -C ./kind_tmp\nchmod +x kind_tmp/kind\nsudo mv kind_tmp/kind /usr/local/bin/kind\nrm -rf kind_tmp", "num_lines": 17}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# KUBECTL_URL needs to be provided to the script\n\ncurl --silent -L $KUBECTL_URL --output kubectl\nchmod +x kubectl\nsudo mv kubectl /usr/local/bin/kubectl\n", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nsudo apt-get install -y python python3 python3-pip\nsudo snap install amazon-ssm-agent --classic\nsudo systemctl stop snap.amazon-ssm-agent.amazon-ssm-agent.service\n\nSSM_ACTIVATION_DIR=/etc/amazon/ssm\n\nsudo mkdir -p $SSM_ACTIVATION_DIR\nchmod +x /home/$USER/activate_ssm.sh\nsudo mv /home/$USER/activate_ssm.sh $SSM_ACTIVATION_DIR\n\nsudo sh -c \"echo '@reboot root /etc/amazon/ssm/activate_ssm.sh' >> /etc/crontab\"\n", "num_lines": 19}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Enabling docker\nsudo systemctl start docker\nsudo systemctl enable docker\n\nUSER=\"${USER:-ubuntu}\"\n# Setting permisions to avoid sudo\nsudo usermod -a -G docker $USER\n\n# Rebooting to get permissions\nsudo reboot\n", "num_lines": 18}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Package cleanup and reset cloud-init\nsudo yum clean all\nsudo cloud-init clean\n\n# Remove ssh keys and hosts\nsudo rm -rf /home/ec2-user/.ssh\nsudo rm -rf /root/.ssh\nsudo rm -f /etc/ssh/ssh_host_*\n\n# Clean tmp\nsudo rm -rf /tmp/*\nsudo rm -rf /var/tmp/*\n\n# Clean cache\nsudo rm -rf /var/cache/*\n\n# Truncate audit logs\nsudo touch /var/log/wtmp\nsudo touch /var/log/lastlog\n\n# Truncate other logs\nsudo journalctl --flush\nsudo journalctl -m --vacuum-time=1s\nsudo find /var/log -type f -iname '*.log' | sudo xargs truncate -s 0\nsudo find /var/log -type f -name '*.gz' -exec rm {} +\n\n# Remove bash history\ncat /dev/null > ~/.bash_history && sudo rm -f /root/.bash_history && history -c\n", "num_lines": 36}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Install prerequisites\nsudo yum update -y\nsudo amazon-linux-extras enable docker\nsudo yum install -y docker tar\n\n# Install yq\nwget \\\n    --progress dot:giga \\\n    $YQ_URL\nsudo mv yq_linux_amd64 /usr/local/bin/yq\nchmod +x /usr/local/bin/yq\n", "num_lines": 19}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nsudo amazon-linux-extras install kernel-5.15 -y\nsudo yum clean all\nsudo yum update -y\nsudo yum upgrade -y\n\nsudo reboot\n", "num_lines": 14}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\ngetprops_from_ovfxml() {\n/usr/bin/python - <<EOS\nfrom xml.dom.minidom import parseString\novfEnv = open(\"$1\", \"r\").read()\ndom = parseString(ovfEnv)\nsection = dom.getElementsByTagName(\"PropertySection\")[0]\nfor property in section.getElementsByTagName(\"Property\"):\n  key = property.getAttribute(\"oe:key\").replace('.','_')\n  value = property.getAttribute(\"oe:value\")\n  print \"{0}='{1}'\".format(key,value)\ndom.unlink()\nEOS\n}\n\n[ -x /usr/bin/vmtoolsd ] || {\n  echo \"ERROR: VMware Tools are not installed. Exiting ...\"\n  exit 1\n}\n\n/usr/bin/vmtoolsd --cmd='info-get guestinfo.ovfEnv' >/tmp/ovf.xml 2>/dev/null\n\n[ -s /tmp/ovf.xml ] || {\n  echo \"ERROR: Cannot get OVF parameters through VMware Tools. Exiting ...\"\n  exit 1\n}\n\neval `getprops_from_ovfxml /tmp/ovf.xml`\n\nSSM_ACTIVATION_DIR=/etc/amazon/ssm\n\nmkdir -p $SSM_ACTIVATION_DIR\n\nSSM_ACTIVATION_FILE=$SSM_ACTIVATION_DIR/.activated\n\nif test -f \"$SSM_ACTIVATION_FILE\"; then\n\techo \"SSM is already activated.\"\nelse\n\techo \"Activating SSM Agent...\"\n    /snap/amazon-ssm-agent/current/amazon-ssm-agent -register -code \"$ssm_activation_code\" -id \"$ssm_activation_id\" -region \"$ssm_activation_region\"\n    systemctl enable snap.amazon-ssm-agent.amazon-ssm-agent.service\n    systemctl start snap.amazon-ssm-agent.amazon-ssm-agent.service\n    touch $SSM_ACTIVATION_FILE\nfi\n", "num_lines": 51}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSA_MANIFESTS_PATH=\"${EKSA_MANIFESTS_PATH:-/usr/lib/eks-a/manifests}\"\nEKSA_ARTIFACTS_TAR_PATH=\"${EKSA_ARTIFACTS_TAR_PATH:-/usr/lib/eks-a/artifacts/artifacts.tar.gz}\"\n\nif test -d $EKSA_MANIFESTS_PATH; then\n\techo \"Manifests dir exists. Pass.\"\nelse\n\techo \"Manifests dir does not exist. Failing.\"\n\texit 1\nfi\n\nif test -f $EKSA_ARTIFACTS_TAR_PATH; then\n\techo \"Artifacts tarball exists. Pass\"\nelse\n\techo \"Artifacts tarball does not exist. Failing.\"\n\texit 1\nfi\n", "num_lines": 23}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif type -p jq &>/dev/null; then\n\techo \"jq command exists. Pass.\"\nelse\n\techo \"jq command does not exist. Failing.\"\n\texit 1\nfi\n\nif type -p python3 &>/dev/null; then\n\techo \"python3 command exists. Pass.\"\nelse\n\techo \"python3 command does not exist. Failing.\"\n\texit 1\nfi\n\nif type -p aws &>/dev/null; then\n\techo \"aws command exists. Pass.\"\nelse\n\techo \"aws command does not exist. Failing.\"\n\texit 1\nfi", "num_lines": 26}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nCUR_STATE=$(systemctl is-active docker)\nif [[ $CUR_STATE == \"active\" ]]; then\n\techo \"Docker service is active. Pass\"\nelse\n\techo \"Docker service is not active. State '$CUR_STATE'. Failing.\"\n\texit 1\nfi\n\nif type -P docker &>/dev/null; then\n\techo \"Docker command exists. Pass.\"\nelse\n\techo \"Docker command does not exist. Failing.\"\n\texit 1\nfi\n\nGROUP='docker'\nif groups $USER | grep &>/dev/null \"$GROUP\"; then\n\techo \"The '$USER' is a member of the '$GROUP' group. Pass.\"\nelse\n\techo \"The '$USER' is not a member of the '$GROUP' group. Failing.\"\n\texit 1\nfi\n", "num_lines": 29}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n if type -p eksctl &>/dev/null; then\n\techo \"eksctl command exists. Pass.\"\nelse\n\techo \"eksctl command does not exist. Failing.\"\n\texit 1\nfi\n\n\nif type -p eksctl-anywhere &>/dev/null; then\n\techo \"eksctl-anywhere binary exists. Pass.\"\nelse\n\techo \"eksctl-anywhere binary does not exist. Failing.\"\n\texit 1\nfi\n\n\nif eksctl anywhere version &>/dev/null; then\n\techo \"eksctl anywhere command works. Pass.\"\nelse\n\techo \"eksctl anywhere command does not work. Failing.\"\n\texit 1\nfi\n ", "num_lines": 29}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nsource /etc/profile.d/golang.sh\n\nif type -p go &>/dev/null; then\n\techo \"go command exists. Pass.\"\nelse\n\techo \"go command does not exist. Failing.\"\n\texit 1\nfi\n\nif type -p git &>/dev/null; then\n\techo \"git command exists. Pass.\"\nelse\n\techo \"git command does not exist. Failing.\"\n\texit 1\nfi", "num_lines": 21}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif type -p kind &>/dev/null; then\n\techo \"kind command exists. Pass.\"\nelse\n\techo \"kind command does not exist. Failing.\"\n\texit 1\nfi\n", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif type -p kubectl &>/dev/null; then\n\techo \"kubectl command exists. Pass.\"\nelse\n\techo \"kubectl command does not exist. Failing.\"\n\texit 1\nfi\n", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSSM_SERVICE_FILE=/etc/systemd/system/snap.amazon-ssm-agent.amazon-ssm-agent.service\nif test -f \"$SSM_SERVICE_FILE\"; then\n\techo \"Amazon SSM Agent service is installed. Pass\"\nelse\n\techo \"Amazon SSM Agent service is not installed.\"\n\texit 1\nfi", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Package cleanup and reset cloud-init\nsudo apt-get -y autoremove\nsudo apt-get -y clean\nsudo cloud-init clean\n\n# Remove ssh keys and hosts\nsudo rm -rf /home/ubuntu/.ssh\nsudo rm -rf /root/.ssh\nsudo rm -f /etc/ssh/ssh_host_*\n\n# Clean tmp\nsudo rm -rf /tmp/*\nsudo rm -rf /var/tmp/*\n\n# Truncate audit logs\nsudo touch /var/log/wtmp\nsudo touch /var/log/lastlog\n\n# Truncate other logs\nsudo find /var/log -type f -iname '*.log' | sudo xargs truncate -s 0\nsudo find /var/log -type f -name '*.gz' -exec rm {} +\nsudo journalctl --rotate\nsudo journalctl -m --vacuum-time=1s\n\n# Remove bash history\ncat /dev/null > ~/.bash_history && sudo rm -f /root/.bash_history && history -c\n", "num_lines": 34}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# Install prerequisites\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common tar\n\n# Install docker gpg key\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n\n# Adding docker repo\nLSB_RELEASE=$(lsb_release -cs)\nARCH=$(dpkg --print-architecture)\nSOURCE=\"deb [arch=$ARCH] https://download.docker.com/linux/ubuntu $LSB_RELEASE stable\"\nsudo add-apt-repository \"$SOURCE\"\n\n# Install docker and containerd\nsudo apt-get update\nsudo apt-get install -y docker-ce docker-ce-cli containerd.io\n\n# Install yq\nsudo snap install yq\n", "num_lines": 27}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nsudo apt-get clean\nsudo apt-get update\nsudo apt-get upgrade -y\n\nsudo reboot\n", "num_lines": 13}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nARCH=\"$1\"\n\nOUTPUT_DIR=\"${MAKE_ROOT}/_output/dependencies/linux-$ARCH\"\nEKS_A_TOOL_BINARY_DIR=\"${OUTPUT_DIR}/eks-a-tools/binary\"\nEKS_A_TOOL_LICENSE_DIR=\"${OUTPUT_DIR}/eks-a-tools/licenses\"\n\nmkdir -p $EKS_A_TOOL_BINARY_DIR\nmkdir -p $EKS_A_TOOL_LICENSE_DIR\n\ndeclare -A project_bin_licenses=([\"eksa/fluxcd/flux2\"]=\"flux FLUX2\"\n                                 [\"eksa/kubernetes-sigs/cluster-api\"]=\"clusterctl CAPI\"\n                                 [\"eksa/kubernetes-sigs/kind\"]=\"kind KIND\"\n                                 [\"eksd/kubernetes\"]=\"client/bin/kubectl KUBERNETES\"\n                                 [\"eksa/replicatedhq/troubleshoot\"]=\"support-bundle TROUBLESHOOT\"\n                                 [\"eksa/vmware/govmomi\"]=\"govc GOVMOMI\"\n                                 ['eksa/helm/helm']=\"helm HELM\"\n                                 ['eksa/apache/cloudstack-cloudmonkey']=\"cmk CLOUDMONKEY\")\n\nfor project in \"${!project_bin_licenses[@]}\"\ndo\n  bin_license_map=(${project_bin_licenses[$project]})\n  binary=${bin_license_map[0]}\n  license_prefix=${bin_license_map[1]}\n  cp $OUTPUT_DIR/$project/$binary $EKS_A_TOOL_BINARY_DIR/$(basename $binary)\n  cp $OUTPUT_DIR/$project/ATTRIBUTION.txt $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_ATTRIBUTION.txt\n  cp -r $OUTPUT_DIR/$project/LICENSES $EKS_A_TOOL_LICENSE_DIR/${license_prefix}_LICENSES\ndone\n", "num_lines": 52}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\ncd $REPO\n\nMANIFEST_IMAGE_OVERRIDE=\"${IMAGE_REPO}/aws/etcdadm-bootstrap-provider:${IMAGE_TAG}\"\n\nsed -i \"s,\\${ETCDADM_BOOTSTRAP_IMAGE},${MANIFEST_IMAGE_OVERRIDE},\" ./config/manager/manager.yaml\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" config/manager/manager.yaml\n\nmkdir -p $OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${TAG}\nkustomize build config/default > bootstrap-components.yaml\ncp bootstrap-components.yaml \"$OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${TAG}\"\ncp ../manifests/metadata.yaml \"$OUTPUT_DIR/manifests/bootstrap-etcdadm-bootstrap/${TAG}\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 43}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\ncd $REPO\n\nMANIFEST_IMAGE_OVERRIDE=\"${IMAGE_REPO}/aws/etcdadm-controller:${IMAGE_TAG}\"\n\nsed -i \"s,\\${ETCDADM_CONTROLLER_IMAGE},${MANIFEST_IMAGE_OVERRIDE},\" ./config/manager/manager.yaml\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" config/manager/manager.yaml\n\nmkdir -p $OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${TAG}\nkustomize build config/default > bootstrap-components.yaml\n\ncp bootstrap-components.yaml \"$OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${TAG}\"\ncp ../manifests/metadata.yaml \"$OUTPUT_DIR/manifests/bootstrap-etcdadm-controller/${TAG}\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 44}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o pipefail\n\nARTIFACTS_PATH=\"$1\"\nBASE_DIRECTORY=\"$2\"\nTAG=\"$3\"\n\n# TODO: use cert-manager make target to generate the cert-manager.yaml file when we upgrade cert-manager version (v1.7.0-alpha.0)\n#\n# The following commits would need to be added as patches:\n# https://github.com/cert-manager/cert-manager/commit/6734e9b7469288b51848eb209597a1920e4801ea\n# https://github.com/cert-manager/cert-manager/commit/32d716654a1091e99e80c10a2798cd839a705713\n#\n# Then would need to run the make target as follows (can specify -jN, like `-j8`, to run whatever targets that can in parallel):\n# make -f make/Makefile bin/yaml/cert-manager.yaml\nmkdir -p $ARTIFACTS_PATH/manifests/$TAG\ncp $BASE_DIRECTORY/projects/cert-manager/cert-manager/manifests/cert-manager.yaml $ARTIFACTS_PATH/manifests/$TAG\n", "num_lines": 34}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nTAG=\"${1?Specify first argument - git version tag}\"\nARTIFACTS_PATH=\"${2?Specify second argument - artifacts path}\"\nREGISTRY=\"${3?Specify third argument - image registry}\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nHELM_BIN=\"${MAKE_ROOT}/_output/helm-bin\"\n\nmkdir -p $ARTIFACTS_PATH\n\nfunction build::install::helm(){\n  mkdir -p $HELM_BIN\n  export PATH=$HELM_BIN:$PATH\n  curl -s https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | HELM_INSTALL_DIR=$HELM_BIN bash\n}\n\nfunction build::cilium::manifests(){\n  export HELM_EXPERIMENTAL_OCI=1\n  mkdir -p _output/manifests/cilium/$TAG\n  helm template cilium oci://$REGISTRY/cilium --version ${TAG#\"v\"} --namespace kube-system -f manifests/cilium-eksa.yaml \\\n    --set operator.image.tag=$TAG --set image.tag=$TAG --set image.repository=\"$REGISTRY/cilium\" --set operator.image.repository=\"$REGISTRY/operator\" > _output/manifests/cilium/${TAG}/cilium.yaml\n}\n\nbuild::install::helm\nbuild::cilium::manifests\n\ncp -rf _output/manifests $ARTIFACTS_PATH\n", "num_lines": 47}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nIMAGE_REGISTRY=\"${1?Specify first argument - image registry}\"\nIMAGE_NAME=\"${2?Specify second argument - image name}\"\nIMAGE_TAG=\"${3? Specify third argument - image tag}\"\nDIGEST_DST=\"${4? Specify fourth argument - destination file for image digest}\"\n\nIMAGE=$IMAGE_REGISTRY/$IMAGE_NAME:$IMAGE_TAG\n\nSHA256=$(skopeo inspect --raw docker://$IMAGE | sha256sum | awk '{print $1;}')\nDIGEST=\"sha256:$SHA256\"\n\necho -n $DIGEST > $DIGEST_DST\n", "num_lines": 32}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAR_FILE_PREFIX=\"$1\"\nOUTPUT_DIR=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\nTAG=\"$4\"\nBINARY_PLATFORMS=\"$5\"\nTAR_PATH=\"$6\"\nGIT_HASH=\"$7\"\nBINARY_DEPS_DIR=\"$8\"\n\nLICENSES_PATH=\"$OUTPUT_DIR/LICENSES\"\nATTRIBUTION_PATH=\"$OUTPUT_DIR/ATTRIBUTION.txt\"\nREPO_PATH=\"containerd\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nfunction build::simple::tarball() {\n  build::common::ensure_tar\n  mkdir -p \"$TAR_PATH\"\n  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })\n  for platform in \"${SUPPORTED_PLATFORMS[@]}\"; do\n    OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n    ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n    TAR_FILE=\"${TAR_FILE_PREFIX}-${OS}-${ARCH}-${TAG}.tar.gz\"\n    TAR_STAGING_DIR=\"${OUTPUT_BIN_DIR}/${OS}-${ARCH}/tar-staging\"\n\n    build::common::echo_and_run mkdir -p ${TAR_STAGING_DIR}/usr/local/{bin,sbin} ${TAR_STAGING_DIR}/etc/systemd/system\n\t\tbuild::common::echo_and_run find ${OUTPUT_BIN_DIR}/${OS}-${ARCH} -not -type d -execdir cp \"{}\" ${TAR_STAGING_DIR}/usr/local/bin \";\"\n    build::common::echo_and_run cp $ATTRIBUTION_PATH ${TAR_STAGING_DIR}/usr/local/bin/CONTAINERD_ATTRIBUTION.txt\n    build::common::echo_and_run cp ${BINARY_DEPS_DIR}/${OS}-${ARCH}/eksa/opencontainers/runc/runc ${TAR_STAGING_DIR}/usr/local/sbin\n    build::common::echo_and_run cp ${BINARY_DEPS_DIR}/${OS}-${ARCH}/eksa/opencontainers/runc/ATTRIBUTION.txt ${TAR_STAGING_DIR}/usr/local/sbin/RUNC_ATTRIBUTION.txt\n    build::common::echo_and_run cp ${REPO_PATH}/containerd.service ${TAR_STAGING_DIR}/etc/systemd/system\n\n    build::common::create_tarball ${TAR_PATH}/${TAR_FILE} ${TAR_STAGING_DIR} .\n\n    rm -rf ${TAR_STAGING_DIR}\n  done\n  echo $GIT_HASH > $TAR_PATH/githash\n}\n\nbuild::simple::tarball\n", "num_lines": 61}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\ncd $REPO\n\nCAPI_REGISTRY_PREFIX=\"${IMAGE_REPO}/kubernetes-sigs/cluster-api\"\nKUBE_RBAC_PROXY_LATEST_TAG=latest\n\nmake set-manifest-image \\\n    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/cluster-api-controller MANIFEST_TAG=$IMAGE_TAG \\\n    TARGET_RESOURCE=\"./config/default/manager_image_patch.yaml\"\n\n# Set the kubeadm bootstrap image to the production bucket.\nmake set-manifest-image \\\n    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/kubeadm-bootstrap-controller MANIFEST_TAG=$IMAGE_TAG \\\n    TARGET_RESOURCE=\"./bootstrap/kubeadm/config/default/manager_image_patch.yaml\"\n\n# Set the kubeadm control plane image to the production bucket.\nmake set-manifest-image \\\n    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/kubeadm-control-plane-controller MANIFEST_TAG=$IMAGE_TAG  \\\n    TARGET_RESOURCE=\"./controlplane/kubeadm/config/default/manager_image_patch.yaml\"\n\nmake set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE=\"./config/default/manager_pull_policy.yaml\"\nmake set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE=\"./bootstrap/kubeadm/config/default/manager_pull_policy.yaml\"\nmake set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE=\"./controlplane/kubeadm/config/default/manager_pull_policy.yaml\"\n\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" config/manager/manager.yaml\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" bootstrap/kubeadm/config/manager/manager.yaml\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" controlplane/kubeadm/config/manager/manager.yaml\n\n## Build the manifests\nmake release-manifests\n\n## Build the development manifests\nmake set-manifest-image \\\n    MANIFEST_IMG=$CAPI_REGISTRY_PREFIX/capd-manager MANIFEST_TAG=$IMAGE_TAG \\\n    TARGET_RESOURCE=\"./test/infrastructure/docker/config/default/manager_image_patch.yaml\"\nmake set-manifest-pull-policy PULL_POLICY=IfNotPresent TARGET_RESOURCE=\"./test/infrastructure/docker/config/default/manager_pull_policy.yaml\"\nmake release-manifests-dev\n\nmkdir -p $OUTPUT_DIR/manifests/{bootstrap-kubeadm,cluster-api,control-plane-kubeadm,infrastructure-docker}/$TAG\ncp out/bootstrap-components.yaml \"$OUTPUT_DIR/manifests/bootstrap-kubeadm/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/bootstrap-kubeadm/$TAG\"\n\ncp out/control-plane-components.yaml \"$OUTPUT_DIR/manifests/control-plane-kubeadm/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/control-plane-kubeadm/$TAG\"\n\ncp out/core-components.yaml \"$OUTPUT_DIR/manifests/cluster-api/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/cluster-api/$TAG\"\n\ncp out/infrastructure-components-development.yaml \"$OUTPUT_DIR/manifests/infrastructure-docker/$TAG/infrastructure-components-development.yaml\"\ncp test/infrastructure/docker/templates/cluster-template-development.yaml \"$OUTPUT_DIR/manifests/infrastructure-docker/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/infrastructure-docker/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 82}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\nGOLANG_VERSION=\"$7\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nbuild::common::use_go_version ${GOLANG_VERSION}\n\ncd $REPO\n\nKUBE_RBAC_PROXY_IMAGE_OVERRIDE=${IMAGE_REPO}/brancz/kube-rbac-proxy:latest\nsed -i 's,image: .*,image: '\"${KUBE_RBAC_PROXY_IMAGE_OVERRIDE}\"',' ./config/default-with-metrics-port/manager_auth_proxy_patch.yaml\n\nmake release-manifests-metrics-port \\\n  RELEASE_DIR=\"out\" \\\n  IMG=\"${IMAGE_REPO}/kubernetes-sigs/cluster-api-provider-cloudstack/release/manager:$IMAGE_TAG\"\n\nmkdir -p $OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG\ncp templates/cluster-template.yaml \"$OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG\"\ncp out/infrastructure-components.yaml \"$OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/infrastructure-cloudstack/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 49}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\nGOLANG_VERSION=\"$7\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nbuild::common::use_go_version $GOLANG_VERSION\n\ncd $REPO\n\nyq eval -i -P \".spec.template.spec.containers[0].args += [\\\"--namespace=eksa-system\\\"]\" config/manager/manager.yaml\n\nmake manifests STAGE=\"release\" \\\n  MANIFEST_DIR=\"out\" \\\n  PULL_POLICY=\"IfNotPresent\" \\\n  IMAGE=\"${IMAGE_REPO}/kubernetes-sigs/cluster-api-provider-vsphere/release/manager:$IMAGE_TAG\"\n\nmkdir -p $OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG\ncp out/cluster-template.yaml \"$OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG\"\ncp out/infrastructure-components.yaml \"$OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG\"\ncp metadata.yaml \"$OUTPUT_DIR/manifests/infrastructure-vsphere/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 49}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -xe\nset -o errexit\nset -o nounset\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/build/setup_image_builder_cli.sh\"\n\nimage_os=\"${1?Specify the first argument - image os}\"\nimage_os_version=\"${2?Specify the second argument - image os version}\"\nrelease_channel=\"${3?Specify the third argument - release channel}\"\nimage_format=\"${4?Specify the fourth argument - image format}\"\nartifacts_bucket=${5-$ARTIFACTS_BUCKET}\nlatest=${6-latest}\n\n# Download and setup latest image-builder cli\nimage_build::common::download_latest_dev_image_builder_cli \"${HOME}\" $artifacts_bucket 'amd64' 'jackson-test-build' # $latest\n\nimage_os_version_arg=\"\"\nif [[ \"$image_os\" == \"ubuntu\" ]]; then\n  image_os_version_arg=\"--os-version ${image_os_version:0:2}.${image_os_version:2:2}\"\nelif [[ \"$image_os\" == \"redhat\" ]]; then\n  image_os_version_arg=\"--os-version $image_os_version\"\nfi\n\nimage_builder_config_file=\"${HOME}/image_builder_config_file\"\nredhat_config_file=\"${HOME}/redhat_config_file\"\nif [[ $image_os == \"redhat\" ]]; then\n  jq --null-input \\\n    --arg rhel_username $RHSM_USERNAME \\\n    --arg rhel_password $RHSM_PASSWORD \\\n    --arg iso_url \"https://redhat-iso-pdx.s3.us-west-2.amazonaws.com/8.4/rhel-8.4-x86_64-dvd.iso\" \\\n    --arg iso_checksum_type \"sha256\" \\\n    --arg iso_checksum \"ea5f349d492fed819e5086d351de47261c470fc794f7124805d176d69ddf1fcd\" \\\n    '{\"rhel_username\": $rhel_username, \"rhel_password\": $rhel_password, \"iso_url\": $iso_url, \"iso_checksum_type\": $iso_checksum_type, \"iso_checksum\": $iso_checksum}' > $redhat_config_file\nfi\n\nif [[ $image_format == \"ova\" ]]; then\n  # Setup vsphere config\n  vsphere_config_file=\"${HOME}/vsphere_config_file\"\n  echo \"${VSPHERE_CONNECTION_DATA}\" > $vsphere_config_file\n\n  # Run image-builder cli\n  if [[ $image_os == \"redhat\" ]]; then\n    jq -s add $vsphere_config_file $redhat_config_file > $image_builder_config_file\n  else\n    image_builder_config_file=$vsphere_config_file\n  fi\n\n  \"${HOME}\"/image-builder build --hypervisor vsphere --os $image_os $image_os_version_arg --vsphere-config $image_builder_config_file --release-channel $release_channel\nelif [[ $image_format == \"raw\" ]]; then\n  # Run image-builder cli\n  if [[ $image_os == \"ubuntu\" ]]; then\n    \"${HOME}\"/image-builder build --hypervisor baremetal --os $image_os $image_os_version_arg --release-channel $release_channel\n    echo \"done with image builder\"\n  elif [[ $image_os == \"redhat\" ]]; then\n    echo \"Creating baremetal config\"\n    echo \"$(jq --arg extra_rpms \"https://redhat-iso-pdx.s3.us-west-2.amazonaws.com/8.4/rpms/kmod-megaraid_sas-07.719.06.00_el8.4-1.x86_64.rpm\" \\\n      '. += {\"extra_rpms\": $extra_rpms}' $redhat_config_file)\" > $image_builder_config_file\n\n    \"${HOME}\"/image-builder build --hypervisor baremetal --os $image_os $image_os_version_arg --release-channel $release_channel --baremetal-config $image_builder_config_file\n  fi\nelif [[ $image_format == \"cloudstack\" ]]; then\n  if [[ $image_os != \"redhat\" ]]; then\n    echo \"Cloudstack builds do not support any non-redhat OS\"\n    exit 1\n  fi\n\n  echo \"Creating cloudstack config\"\n  image_builder_config_file=$redhat_config_file\n  \"${HOME}\"/image-builder build --hypervisor cloudstack --os $image_os $image_os_version_arg --release-channel $release_channel --cloudstack-config $image_builder_config_file\nelif [[ $image_format == \"ami\" ]]; then\n  if [[ $image_os != \"ubuntu\" ]]; then\n    echo \"AMI builds do not support any non-ubuntu os\"\n    exit 1\n  fi\n\n  echo \"Creating AMI config\"\n  jq --null-input \\\n    --arg ami_filter_owners \"099720109477\" \\\n    --arg custom_role_names \"$MAKE_ROOT/ansible/roles/load_additional_files\" \\\n    --arg ansible_extra_vars \"@$MAKE_ROOT/packer/ami/ansible_extra_vars.yaml\" \\\n    --arg manifest_output \"$MANIFEST_OUTPUT\" \\\n    '{\"ami_filter_owners\": $ami_filter_owners, \"custom_role_names\": $custom_role_names, \"ansible_extra_vars\": $ansible_extra_vars, \"manifest_output\": $manifest_output}' > $image_builder_config_file\n  \"${HOME}\"/image-builder build --hypervisor ami --os $image_os $image_os_version_arg --release-channel $release_channel --ami-config $image_builder_config_file\nfi\n", "num_lines": 101}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO_ROOT=\"${1?Specify first argument - repo root}\"\nPROJECT_PATH=\"${2?Specify second argument - Project path}\"\nRELEASE_BRANCH=\"${3?Specify third argument - Release branch}\"\nAMI_ID=\"${4?Specify fourth argument - AMI ID to create instance}\"\nINSTANCE_TYPE=\"${5?Specify fifth argument - Instance type to create}\"\nKEY_NAME=\"${6?Specify sixth argument - Key name to associate with instance}\"\nIMAGE_OS=\"${7?Specify seventh argument - Raw build target name}\"\nIMAGE_OS_VERSION=\"${8?Specify eight argument - Raw build target name}\"\nIMAGE_FORMAT=\"${9?Specify ninth argument - Image format}\"\nLATEST=\"${10?Specify the tenth argument - Latest tag}\"\nARTIFACTS_PATH=\"${11?Specify the eleventh argument - Artifacts path}\"\nBRANCH_NAME=\"${12?Specify the twelveth argument - Branch Name}\"\n\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\nCI=\"${CI:-false}\"\n\nif [ \"$CODEBUILD_CI\" = \"true\" ]; then\n    KEY_NAME=\"$KEY_NAME-$CODEBUILD_BUILD_ID\"\n    CREATOR=$CODEBUILD_BUILD_ID\nelif [ \"$CI\" = \"true\" ]; then\n    KEY_NAME=\"$KEY_NAME-$PROW_JOB_ID\"\n    CREATOR=$PROW_JOB_ID\nfi\n\nif [ \"$IMAGE_FORMAT\" != \"raw\" ] && [ \"$IMAGE_FORMAT\" != \"cloudstack\" ]; then\n  echo \"Unsupported image format. This script only supports building raw and cloudstack builds\"\n  exit 1\nfi\n\nREPO_NAME=$(basename $REPO_ROOT)\nKEY_LOCATION=$REPO_ROOT/$PROJECT_PATH/$KEY_NAME.pem\nREMOTE_HOME_DIR=\"/home/ubuntu\"\nREMOTE_PROJECT_PATH=$REMOTE_HOME_DIR/$REPO_NAME/$PROJECT_PATH\nREMOTE_ARTIFACTS_PATH=$REMOTE_HOME_DIR/$PROJECT_PATH/artifacts\nSSH_OPTS=\"-i $KEY_LOCATION -o StrictHostKeyChecking=no -o ConnectTimeout=120\"\n\nterminate_instance() {\n    aws ec2 terminate-instances --instance-ids $1\n}\ndelete_key_pair() {\n    aws ec2 delete-key-pair --key-name $1\n}\n\n# Delete keypair and instance when exiting script. This will prevent\n# lingering instances by deleting the EC2 instance regardless of success\n# or failure of build\ntrap 'if [ -n \"$INSTANCE_ID\" ]; then terminate_instance $INSTANCE_ID; fi; delete_key_pair $KEY_NAME' EXIT\n\n# Check if key of that name already exists, else create keypair\n# Query and save the key contents into a local file for\n# communicating to EC2 instance via SSH\nif ! aws ec2 wait key-pair-exists --key-names=$KEY_NAME 2>/dev/null ; then\n    aws ec2 create-key-pair --key-name $KEY_NAME --tag-specifications \"ResourceType=key-pair,Tags=[{Key=Creator,Value=$CREATOR}]\" --query \"KeyMaterial\" --output text > $KEY_LOCATION\nfi\nchmod 600 $KEY_LOCATION\n\nRUN_INSTANCE_EXTRA_ARGS=\"\"\nif [ \"$CODEBUILD_CI\" = \"true\" ]; then\n    # Select a random subnet from Codebuild project's private subnet list\n    SUBNET_ID_LIST=$RAW_IMAGE_BUILD_SUBNET_ID\n    SUBNET_COUNT=$(echo $SUBNET_ID_LIST | awk -F\\, '{print NF}')\n    INDEX=$((($RANDOM % $SUBNET_COUNT) + 1))\n    SUBNET_ID=$(cut -d',' -f${INDEX} <<< $SUBNET_ID_LIST)\n\n    # Query the availability zone that this subnet exists in\n    SUBNET_AZ=$(aws ec2 describe-subnets --subnet-ids $SUBNET_ID --query \"Subnets[].AvailabilityZone\" --output text)\n\n    # Define extra args to run the instance in the same subnet and use\n    # the same security group as Codebuild\n    RUN_INSTANCE_EXTRA_ARGS=\"--subnet-id $SUBNET_ID --placement AvailabilityZone=$SUBNET_AZ --security-group-ids $RAW_IMAGE_BUILD_SECURITY_GROUP --associate-public-ip-address --iam-instance-profile Name=eksa-imagebuilder-instance-profile\"\nfi\n\nMAX_RETRIES=20\nfor i in $(seq 1 $MAX_RETRIES); do\n    echo \"Attempt $(($i)) of instance launch\"\n\n    # Create a single EC2 instance with provided instance type and AMI\n    # Query the instance ID for use in future commands\n    INSTANCE_ID=$(aws ec2 run-instances --count 1 --image-id=$AMI_ID --instance-type $INSTANCE_TYPE --key-name $KEY_NAME $RUN_INSTANCE_EXTRA_ARGS --tag-specifications \"ResourceType=instance,Tags=[{Key=Creator,Value=$CREATOR}]\" --query \"Instances[0].InstanceId\" --output text --metadata-options \"HttpEndpoint=enabled,HttpTokens=required,HttpPutResponseHopLimit=2\") && break\n\n    if [ \"$i\" = \"$MAX_RETRIES\" ]; then\n        exit 1\n    fi\n    sleep 30\ndone\n\n# Wait in loop until instance is running\naws ec2 wait instance-running --instance-ids $INSTANCE_ID\n\n# Get the public DNS of the instance to use as SSH hostname\nPUBLIC_DNS_NAME=$(aws ec2 describe-instances --instance-ids $INSTANCE_ID --query \"Reservations[].Instances[].PublicDnsName\" --output text)\nREMOTE_HOST=ubuntu@$PUBLIC_DNS_NAME\n\n# rsync might sometimes fail with flaky connection issues, so\n# implementing retry logic will make it more robust to flakes\nfor i in $(seq 1 $MAX_RETRIES); do\n    echo \"Attempt $(($i))\"\n\n    # Transfer the repo contents from the CI environment to the EC2 instance\n    rsync -azh -e \"ssh $SSH_OPTS\" $REPO_ROOT $REMOTE_HOST:~/ && echo \"Files transferred!\" && break\n\n    if [ \"$i\" = \"$MAX_RETRIES\" ]; then\n        exit 1\n    fi\n    sleep 10\ndone\n\n# If not running on Codebuild, exit gracefully\nif [ \"$CODEBUILD_CI\" = \"false\" ]; then\n    exit 0\nfi\n\nSSH_COMMANDS=\"sudo usermod -a -G kvm ubuntu; sudo chmod 666 /dev/kvm; sudo chown root:kvm /dev/kvm; export IMAGE_OS=$IMAGE_OS IMAGE_OS_VERSION=$IMAGE_OS_VERSION IMAGE_FORMAT=$IMAGE_FORMAT; CODEBUILD_CI=true CODEBUILD_SRC_DIR=/home/ubuntu/$REPO_NAME BRANCH_NAME=$BRANCH_NAME ARTIFACTS_PATH=$REMOTE_ARTIFACTS_PATH $REMOTE_PROJECT_PATH/build/build_image.sh $IMAGE_OS $IMAGE_OS_VERSION $RELEASE_BRANCH $IMAGE_FORMAT $ARTIFACTS_BUCKET $LATEST\"\nif [[ \"$IMAGE_OS\" == \"redhat\" ]]; then\n  SSH_COMMANDS=\"export RHSM_USERNAME='$RHSM_USERNAME' RHSM_PASSWORD='$RHSM_PASSWORD'; $SSH_COMMANDS\"\nfi\n\nssh $SSH_OPTS $REMOTE_HOST $SSH_COMMANDS\necho \"done with ssh command\"\n# Copy built raw image from the instance back into the CI build environment\nOUTPUT_IMAGE_BLOB=\"*.gz\"\nOUTPUT_IMAGE_FORMAT=$IMAGE_FORMAT\nif [[ \"$IMAGE_FORMAT\" == \"cloudstack\" ]]; then\n  OUTPUT_IMAGE_BLOB=\"*.qcow2\"\nfi\nmkdir -p $ARTIFACTS_PATH\nscp $SSH_OPTS $REMOTE_HOST:$REMOTE_HOME_DIR/$OUTPUT_IMAGE_BLOB $REPO_ROOT/$PROJECT_PATH/\nscp $SSH_OPTS $REMOTE_HOST:$REMOTE_ARTIFACTS_PATH/$RELEASE_BRANCH/$IMAGE_OS/$IMAGE_OS_VERSION/$OUTPUT_IMAGE_FORMAT/{EKSD_MANIFEST_URL,KUBERNETES_VERSION,packer.log} $ARTIFACTS_PATH\n", "num_lines": 150}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\nEKSD_RELEASE_BRANCH=\"${1?Specify first argument - EKS-D release branch}\"\nAMI_MANIFEST_OUTPUT=\"${2?Specify second argument - AMI manifest output file from packer}\"\nIMAGE_FORMAT=\"${3?Specify third argument - Format for exported image \\(vmdk\\|raw\\|vhd\\)}\"\nS3_DST_EXPORT_PATH=\"${4?Specify fourth argument - Destination S3 path}\"\nREPLICAS=\"${5?Specify fourth argument - Comma separated list of s3 destinations for exported image copies}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../../../..\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/build/lib/common.sh\"\n\nARTIFACT_ID=$(cat $AMI_MANIFEST_OUTPUT | jq -r '.builds[0].artifact_id')\nARTIFACT_ID_SPLIT=(${ARTIFACT_ID//:/ })\nAMI_ID=${ARTIFACT_ID_SPLIT[1]}\n\nREPLICAS_SPLIT=(${REPLICAS//,/ })\n\nDST_BUCKET_PATH=${S3_DST_EXPORT_PATH#\"s3://\"}\nDST_BUCKET_NAME=${DST_BUCKET_PATH%%/*}\nDST_PATH=${DST_BUCKET_PATH#\"$DST_BUCKET_NAME/\"}\n\nEKSD_RELEASE=$(build::eksd_releases::get_eksd_release_name $EKSD_RELEASE_BRANCH)\nEXPORTED_IMAGE_PREFIX=\"$DST_PATH/$EKSD_RELEASE-\"\n\nEXPORT_RESPONSE=$(aws ec2 export-image --disk-image-format $IMAGE_FORMAT --s3-export-location S3Bucket=$DST_BUCKET_NAME,S3Prefix=$EXPORTED_IMAGE_PREFIX --image-id $AMI_ID)\necho $EXPORT_RESPONSE\n\nEXPORT_TASK_ID=$(echo $EXPORT_RESPONSE | jq -r '.ExportImageTaskId')\nEXPORTED_IMAGE_LOCATION=\"s3://${DST_BUCKET_NAME}/${EXPORTED_IMAGE_PREFIX}${EXPORT_TASK_ID}.${IMAGE_FORMAT}\"\n\nFINAL_STATUSES=(completed deleted)\nSTATUS=$(echo $EXPORT_RESPONSE | jq -r '.Status')\nSTATUS_MESSAGE=$(echo $EXPORT_RESPONSE | jq -r '.StatusMessage')\nPROGRESS=$(echo $EXPORT_RESPONSE | jq -r '.Progress')\n\nuntil [[ \"${FINAL_STATUSES[*]}\" =~ \"${STATUS}\" ]]; do\n  echo \"Image import is $STATUS: $STATUS_MESSAGE $PROGRESS%\"\n  sleep 30\n\n  DESCRIBE_RESPONSE=$(aws ec2 describe-export-image-tasks --export-image-task-ids $EXPORT_TASK_ID)\n  STATUS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Status')\n  STATUS_MESSAGE=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].StatusMessage')\n  PROGRESS=$(echo $DESCRIBE_RESPONSE | jq -r '.ExportImageTasks[0].Progress')\ndone\n\nif [[ \"$STATUS\" != \"completed\" ]]; then\n    echo \"Image import failed: $STATUS - $STATUS_MESSAGE\"\n    exit 1\nfi\n\necho \"Image import for ami $AMI_ID succeeded\"\n\nfor dst in \"${REPLICAS_SPLIT[@]}\"\ndo\n  echo \"Copying exported image to $dst\"\n  aws s3 cp --no-progress --acl public-read $EXPORTED_IMAGE_LOCATION $dst \ndone\n", "num_lines": 76}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nRELEASE_CHANNEL=\"${1?Specify first argument - EKS-D release channel}\"\nFORMAT=\"${2?Specify second argument - Image format}\"\nBOTTLEROCKET_DOWNLOAD_PATH=\"${3?Specify third argument - Download path for Bottlerocket-related files}\"\nPROJECT_PATH=\"${4?Specify fourth argument - Project path}\"\nLATEST_TAG=\"${5?Specify fifth argument - S3 destination folder for latest artifact upload}\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\n\n# Setting version and URL parameters for downloading the OVA\nOS_DOWNLOAD_PATH=\nKUBEVERSION=$(echo $RELEASE_CHANNEL | tr '-' '.')\nBOTTLEROCKET_RELEASE_VERSION=$(yq e \".${RELEASE_CHANNEL}.${FORMAT}-release-version\" $MAKE_ROOT/BOTTLEROCKET_RELEASES)\nif [[ $BOTTLEROCKET_RELEASE_VERSION == \"null\" ]] ; then\n  echo \"Bottlerocket build for ${RELEASE_CHANNEL} is not enabled. Terminating silently.\"\n  exit 0\nfi\ncase $FORMAT in\nami)\n  VARIANT=\"aws\"\n  TARGET=\"bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.img.lz4\"\n  ;;\nraw)\n  VARIANT=\"metal\"\n  TARGET=\"bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.img.lz4\"\n  ;;\nova)\n  VARIANT=\"vmware\"\n  TARGET=\"bottlerocket-${VARIANT}-k8s-${KUBEVERSION}-x86_64-${BOTTLEROCKET_RELEASE_VERSION}.ova\"\n  ;;\n*)\n  echo \"Invalid image format: $FORMAT\"\n  exit 1\n  ;;\nesac\n\nBOTTLEROCKET_METADATA_URL=\"https://updates.bottlerocket.aws/2020-07-07/${VARIANT}-k8s-${KUBEVERSION}/x86_64/\"\nBOTTLEROCKET_TARGETS_URL=\"https://updates.bottlerocket.aws/targets/\"\nOS_DOWNLOAD_PATH=${BOTTLEROCKET_DOWNLOAD_PATH}/${FORMAT}\nrm -rf $OS_DOWNLOAD_PATH\n\n# Downloading the TARGET from the Bottlerocket target location using Tuftool\nbuild::common::echo_and_run tuftool download \"${OS_DOWNLOAD_PATH}\" \\\n    --target-name \"${TARGET}\" \\\n    --root \"${BOTTLEROCKET_DOWNLOAD_PATH}/root.json\" \\\n    --metadata-url \"${BOTTLEROCKET_METADATA_URL}\" \\\n    --targets-url \"${BOTTLEROCKET_TARGETS_URL}\"\n\n# Post processing for aws and metal variants\nif [[ $VARIANT == \"aws\" ]] || [[ $VARIANT == \"metal\" ]]; then\n  BOTTLEROCKET_IMG=\"${TARGET%.lz4}\"\n  build::common::echo_and_run lz4 --decompress ${OS_DOWNLOAD_PATH}/${TARGET} ${OS_DOWNLOAD_PATH}/${BOTTLEROCKET_IMG}\n  build::common::echo_and_run gzip ${OS_DOWNLOAD_PATH}/${BOTTLEROCKET_IMG}\n  rm -f ${OS_DOWNLOAD_PATH}/${TARGET}\nfi\n", "num_lines": 78}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nfunction image_build::common::download_latest_dev_image_builder_cli() {\n  local -r download_location=${1-/usr/bin}\n  local -r artifacts_bucket=${2-$ARTIFACTS_BUCKET}\n  local -r arch=${3-amd64}\n  local -r latest=${4-latest}\n\n  local -r latest_tar_url=$(build::common::get_latest_eksa_asset_url $artifacts_bucket 'aws/image-builder' $arch $latest)\n\n  # Download the tar ball and decompress\n  local -r http_code=$(curl -s -w \"%{http_code}\" $latest_tar_url -o image-builder.tar.gz)\n  if [[ \"$http_code\" != \"200\" ]]; then\n    echo \"Error downloading latest image builder cli\"\n    exit 1\n  fi\n  tar -xvf image-builder.tar.gz --directory $download_location/ ./image-builder\n  rm -rf image-builder.tar.gz\n}\n", "num_lines": 36}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nRELEASE_BRANCH=\"${1?Specify first argument - release branch}\"\nIMAGE_FORMAT=\"${2?Specify second argument - image format}\"\nIMAGE_OS=\"${3?Specify third argument - image OS}\"\nARTIFACTS_BUCKET=\"${4?Specify fourth argument - artifact bucket}\"\nOVA_PATH=\"${5? Specify fifth argument - ova output path}\"\nADDITIONAL_PAUSE_IMAGE_FROM=\"${6? Specify sixth argument - additional pause image}\"\nLATEST_TAG=\"${7? Specify seventh argument - latest tag}\"\nIMAGE_BUILDER_DIR=\"${8? Specify eighth argument - image-builder directory}\"\nIMAGE_OS_DIR=\"${9? Specify ninth argument - image-os-dir}\"\nIMAGE_OS_VERSION=\"${10? Specify tenth argument - image-os-version}\"\n\nCI=\"${CI:-false}\"\nCODEBUILD_CI=\"${CODEBUILD_CI:-false}\"\nDEV_RELEASE=false\nif [[ $CI == true || $CODEBUILD_CI == true ]]; then\n  DEV_RELEASE=true\nfi\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\nsource \"${MAKE_ROOT}/../../../build/lib/eksa_releases.sh\"\n\nfunction env_and_envsubst()\n{\n    echo -e \"\\nRunning envsubst with input file $2 saving to $3 with ENV: \"\n    local -r env_vars=(${1//:/ })\n    for var in \"${env_vars[@]}\"; do\n        local var_name=${var:1}\n        echo \"$var_name: ${!var_name:-}\"\n    done\n    envsubst \"$1\" < \"$2\" > \"$3\"\n}\n\n# Preload release yaml\necho \"Loading EKSD manifest from: $(build::eksd_releases::get_release_yaml_url $RELEASE_BRANCH)\"\nbuild::eksd_releases::load_release_yaml $RELEASE_BRANCH > /dev/null\n\necho \"Loading EKSA manifest from: $(build::eksa_releases::get_eksa_release_manifest_url $DEV_RELEASE $LATEST_TAG)\"\nbuild::eksa_releases::load_bundle_manifest $DEV_RELEASE $LATEST_TAG > /dev/null\n\nOUTPUT_CONFIGS=\"$MAKE_ROOT/_output/$RELEASE_BRANCH/$IMAGE_FORMAT/$IMAGE_OS_DIR/config\"\nmkdir -p $OUTPUT_CONFIGS\n\nexport CNI_SHA=\"sha256:$(build::eksd_releases::get_eksd_component_sha 'cni-plugins' $RELEASE_BRANCH)\"\nexport PLUGINS_ASSET_BASE_URL=$(build::eksd_releases::get_eksd_cni_asset_base_url $RELEASE_BRANCH)\nexport CNI_VERSION=$(build::eksd_releases::get_eksd_component_version 'cni-plugins' $RELEASE_BRANCH)\n\n# Get CNI sha256 to validate cni plugins in image are from eks-d\n# Use sha from manfiest to validate tar and then generate sha from specific binary\necho \"Downloading cni plugins to get shasum of host-device plugin for validation during image building\"\nTMP_CNI=\"$HOME/tmp/eks-image-builder-cni\"\nmkdir -p $TMP_CNI\ncurl -o $TMP_CNI/cni-plugins.tar.gz \"$PLUGINS_ASSET_BASE_URL/$CNI_VERSION/cni-plugins-linux-amd64-$CNI_VERSION.tar.gz\"\necho \"$(echo $CNI_SHA | sed -E 's/.*sha256:(.*)$/\\1/') $TMP_CNI/cni-plugins.tar.gz\" > $TMP_CNI/cni.sha256\nsha256sum -c $TMP_CNI/cni.sha256\ntar -zxvf $TMP_CNI/cni-plugins.tar.gz -C $TMP_CNI ./host-device \nexport CNI_HOST_DEVICE_SHA256=\"$(sha256sum $TMP_CNI/host-device | awk -F ' ' '{print $1}')\"\nrm -rf $TMP_CNI\n\nenv_and_envsubst '$CNI_SHA:$PLUGINS_ASSET_BASE_URL:$CNI_VERSION:$CNI_HOST_DEVICE_SHA256' \\\n    \"$MAKE_ROOT/packer/config/cni.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/cni.json\"\n\nexport PAUSE_IMAGE=$(build::eksd_releases::get_eksd_kubernetes_image_url 'pause-image' $RELEASE_BRANCH)\nenv_and_envsubst '$PAUSE_IMAGE:$HTTP_PROXY:$HTTPS_PROXY:$NO_PROXY' \\\n    \"$MAKE_ROOT/packer/config/common.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/common.json\"\n\nexport IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $RELEASE_BRANCH)\nexport KUBERNETES_ASSET_BASE_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $RELEASE_BRANCH)\nexport KUBERNETES_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $RELEASE_BRANCH)\nexport KUBERNETES_SERIES=\"v${RELEASE_BRANCH/-/.}\"\nexport EKSD_NAME=$(build::eksd_releases::get_eksd_release_name $RELEASE_BRANCH)\nEKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $RELEASE_BRANCH)\nexport KUBERNETES_FULL_VERSION=\"$KUBERNETES_VERSION-eks-$RELEASE_BRANCH-$EKSD_RELEASE\"\nexport ETCD_HTTP_SOURCE=$(build::eksd_releases::get_eksd_component_url \"etcd\" $RELEASE_BRANCH)\nexport ETCD_VERSION=$(build::eksd_releases::get_eksd_component_version \"etcd\" $RELEASE_BRANCH)\nexport ETCD_SHA256=$(build::eksd_releases::get_eksd_component_sha \"etcd\" $RELEASE_BRANCH)\nexport ETCDADM_HTTP_SOURCE=${ETCDADM_HTTP_SOURCE:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'etcdadm' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}\nexport ETCDADM_VERSION='v0.1.5'\nexport CRICTL_URL=${CRICTL_URL:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'crictl' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}\nexport CRICTL_SHA256=\"${CRICTL_SHA256:-$(build::eksa_releases::get_eksa_component_asset_artifact_checksum 'eksD' 'crictl' 'sha256' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}\"\n\nexport CONTAINERD_URL=${CONTAINERD_URL:-$(build::eksa_releases::get_eksa_component_asset_url 'eksD' 'containerd' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}\nexport CONTAINERD_SHA256=\"${CONTAINERD_SHA256:-$(build::eksa_releases::get_eksa_component_asset_artifact_checksum 'eksD' 'containerd' 'sha256' $RELEASE_BRANCH $DEV_RELEASE $LATEST_TAG)}\"\n# TEMP - workaround released image-builders using the main branch\n# remove this before next release and after patch image builder to use specific release tag instead of main\nif [[ \"$CONTAINERD_URL\" == \"null\" ]]; then\n    export CONTAINERD_URL=\"https://github.com/containerd/containerd/releases/download/v1.6.19/cri-containerd-cni-1.6.19-linux-amd64.tar.gz\"\n    export CONTAINERD_SHA256=\"0457907ec410c2172829f6d1808f43fd2b83395a242bcb677cfe26320df13d5d\"\nfi\n\nenv_and_envsubst '$IMAGE_REPO:$KUBERNETES_ASSET_BASE_URL:$KUBERNETES_VERSION:$KUBERNETES_SERIES:$CRICTL_URL:$CRICTL_SHA256:$CONTAINERD_URL:$CONTAINERD_SHA256:$ETCD_HTTP_SOURCE:$ETCD_VERSION:$ETCDADM_HTTP_SOURCE:$ETCD_SHA256:$ETCDADM_VERSION:$KUBERNETES_FULL_VERSION' \\\n    \"$MAKE_ROOT/packer/config/kubernetes.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/kubernetes.json\"\n\nADDITIONAL_PAUSE_IMAGE_VERSION_BASE_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $ADDITIONAL_PAUSE_IMAGE_FROM)\nADDITIONAL_PAUSE_KUBERNETES_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $ADDITIONAL_PAUSE_IMAGE_FROM)\nexport ADDITIONAL_PAUSE_IMAGE=$ADDITIONAL_PAUSE_IMAGE_VERSION_BASE_URL/$ADDITIONAL_PAUSE_KUBERNETES_VERSION/bin/linux/amd64/pause.tar\nenv_and_envsubst '$ADDITIONAL_PAUSE_IMAGE' \\\n    \"$MAKE_ROOT/packer/config/additional_components.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/additional_components.json\"\n\n# Write kubernetes version and the eksd manifest url consumed to output directory\nmkdir -p $OVA_PATH\necho \"$KUBERNETES_VERSION\" > \"$OVA_PATH\"/KUBERNETES_VERSION\nexport EKSD_MANIFEST_URL=$(build::eksd_releases::get_release_yaml_url $RELEASE_BRANCH)\necho \"$EKSD_MANIFEST_URL\" > \"$OVA_PATH\"/EKSD_MANIFEST_URL\n\nenv_and_envsubst '$CNI_VERSION:$ETCD_VERSION:$ETCD_SHA256:$ETCDADM_VERSION:$PAUSE_IMAGE:$CNI_HOST_DEVICE_SHA256' \\\n    \"$MAKE_ROOT/packer/config/validate_goss_inline_vars.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/validate_goss_inline_vars.json\"\n\nenv_and_envsubst '$EKSD_NAME' \\\n    \"$MAKE_ROOT/packer/config/ovf_custom_properties.json.tmpl\" \\\n    \"$OUTPUT_CONFIGS/ovf_custom_properties.json\"\n\n# This is the IP address that Packer will create the server on to host the local\n# directory containing the kickstart config\nif [ \"$IMAGE_FORMAT\" = \"ova\" ] && \\\n    ( [ \"$IMAGE_OS\" = \"redhat\" ] || ( [ \"$IMAGE_OS\" = \"ubuntu\" ] && [ \"$IMAGE_OS_VERSION\" != \"2004\" ] )  ); then\n    echo \"Finding correct interface for packer temporary http server\"\n    ACTIVE_INTERFACE=\"\"\n    if [ \"$(uname -s)\" = \"Linux\" ]; then\n        INTERFACES=($(ls /sys/class/net))\n        for interface in \"${INTERFACES[@]}\"; do\n            if [ \"$interface\" = \"eth0\" ] || [ \"$interface\" = \"en0\" ] || [ \"$interface\" = \"eno1\" ]; then\n                ACTIVE_INTERFACE=$interface\n                echo \"Found interface: $interface\"\n                break\n            fi\n        done\n        HTTP_SERVER_IP=$(ip a l $ACTIVE_INTERFACE | awk '/inet / {print $2}' | cut -d/ -f1)\n    elif [ \"$(uname -s)\" = \"Darwin\" ]; then\n        ACTIVE_INTERFACE=\"en0\"\n        HTTP_SERVER_IP=$(ifconfig $ACTIVE_INTERFACE | awk '/inet / {print $2}' | cut -d/ -f1)\n    fi\n    \n    if [ -z $ACTIVE_INTERFACE ]; then\n        echo \"ACTIVE_INTERFACE cannot be an empty string. Please check your network configuration\n        and set an appropriate value for ACTIVE_INTERFACE\"\n        exit 1\n    fi\n\n    PACKER_HTTP_SERVER_IP=${PACKER_HTTP_SERVER_IP:-$HTTP_SERVER_IP}\n    if [ -z $PACKER_HTTP_SERVER_IP ]; then\n        echo \"PACKER_HTTP_SERVER_IP cannot be automatically determined.  Please export PACKER_HTTP_SERVER_IP=<Current Host's IP>\"\n        exit 1\n    fi\n\n    SED=sed\n    if [ \"$(uname -s)\" = \"Darwin\" ]; then\n      SED=gsed\n    fi\n    find ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ova -type f -name '*.json' | xargs $SED -i \"s/{{ .HTTPIP }}/$PACKER_HTTP_SERVER_IP/g\"\nfi\n\n# If the image format is AMI and our Packer config specifies a non-gp3 volume, then\n# remove the throughput field in the upstream Packer config since only gp3 supports\n# specifying throughput\nif [ \"$IMAGE_FORMAT\" = \"ami\" ]; then\n    volume_type=\"$(cat $MAKE_ROOT/packer/ami/ami.json | jq -r '.volume_type')\"\n    if [[ $volume_type != \"null\" && $volume_type != \"gp3\" ]]; then\n        build::jq::update_in_place ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ami/packer.json \"del(.builders[0].launch_block_device_mappings[].throughput)\"\n    else\n        build::jq::update_in_place ${MAKE_ROOT}/${IMAGE_BUILDER_DIR}/packer/ami/packer.json '.builders[0].launch_block_device_mappings[].throughput = \"{{ user `throughput` }}\"'\n    fi\nfi\n\n", "num_lines": 189}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\nRELEASE_CHANNEL=\"${1?Specify first argument - EKS-D release channel}\"\nFORMAT=\"${2?Specify second argument - Image format}\"\nARTIFACTS_PATH=\"${3?Specify third argument - Artifacts path}\"\nARTIFACTS_UPLOAD_PATH=\"${4?Specify fourth argument - Artifacts upload path}\"\nIMAGE_OS_VERSION=\"${5?Specify fifth argument - OS version}\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nrelease_availability=$(build::bottlerocket::check_release_availablilty $MAKE_ROOT/BOTTLEROCKET_RELEASES $RELEASE_CHANNEL $FORMAT)\nif [ $release_availability -ne 0 ]; then\n  echo \"No Bottlerocket release found for release branch. Terminating silently...\"\n  exit 0\nfi\n\nbuild::common::echo_and_run make -C $MAKE_ROOT s3-artifacts-${FORMAT}-bottlerocket-${IMAGE_OS_VERSION} IMAGE_OS=bottlerocket\nbuild::common::echo_and_run make -C $MAKE_ROOT upload-artifacts ARTIFACTS_PATH=$ARTIFACTS_PATH ARTIFACTS_UPLOAD_PATH=$ARTIFACTS_UPLOAD_PATH IMAGE_FORMAT=$FORMAT IMAGE_OS=bottlerocket IMAGE_OS_VERSION=$IMAGE_OS_VERSION\n", "num_lines": 38}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nsource /etc/eks/logging.sh\n\nset -uxo pipefail\n\nSCRIPT_LOG=/var/log/eks-bootstrap.log\ntouch $SCRIPT_LOG\n\n# save stdout and stderr to file descriptors 3 and 4,\n# then redirect them to \"$SCRIPT_LOG\"\n# restore stdout and stderr at bottom of script\nexec 3>&1 4>&2 >>$SCRIPT_LOG 2>&1\n\necho \"127.0.0.1   $(hostname)\" >>/etc/hosts\n\nNETWORK_CONFIG_PATH=/tmp/network.yaml\nNETPLAN_CONFIG_PATH=/etc/netplan/config.yaml\n\n# dynamically get default network interface name using mac address\nTOKEN=`curl -X PUT \"http://169.254.169.254/latest/api/token\" -H \"X-aws-ec2-metadata-token-ttl-seconds: 21600\"`\nDEFAULT_MAC=$(curl -H \"X-aws-ec2-metadata-token: $TOKEN\" -v http://169.254.169.254/latest/meta-data/mac)\nDEFAULT_NETWORK=$(ip -br link | grep $DEFAULT_MAC | awk '{print $1}')\n\n# configure DNI\nDNI_COUNT=$(grep -E \"dniCount\" $NETWORK_CONFIG_PATH | awk '{print $2}')\nDNI_LIST=$(ip -br link | grep -Ev \"$DEFAULT_NETWORK|lo\" | awk '{print $1}')\nwhile [ -z \"$DNI_LIST\" ] || [[ $(echo \"$DNI_LIST\" | wc -l) != \"$DNI_COUNT\" ]]\ndo\n  # creating DNI is a separate api call, which has some delays\n  log::info \"DNI is not ready, retrying\"\n  sleep 5\n  DNI_LIST=$(ip -br link | grep -Ev \"$DEFAULT_NETWORK|lo\" | awk '{print $1}')\ndone\nlog::info \"Using DNI: $DNI_LIST\"\n\nDEFAULT_GATEWAY=$(ip r | grep default | awk '{print $3}')\nlog::info \"Using default gateway: $DEFAULT_GATEWAY\"\n\n# route imds traffic to private nic\ncat<<EOF >\"$NETPLAN_CONFIG_PATH\"\nnetwork:\n    version: 2\n    renderer: networkd\n    ethernets:\n        $DEFAULT_NETWORK:\n            routes:\n                - to: 169.254.169.254\n                  via: $DEFAULT_GATEWAY\nEOF\n\nMETRIC=0\nINDEX=1\nfor DNI in $DNI_LIST\ndo\nMAC=$(ip -br link | grep -E \"$DNI\" |  awk '{print $3}')\nif ! grep -q \"static\" \"$NETWORK_CONFIG_PATH\"\nthen\necho \"Configuring DHCP\"\ncat<<EOF >>\"$NETPLAN_CONFIG_PATH\"\n        $DNI:\n            set-name: $DNI\n            dhcp4: true\n            dhcp-identifier: mac\n            dhcp4-overrides:\n                route-metric: $METRIC\n                send-hostname: true\n                hostname: $(hostname)\n            match:\n                macaddress: $MAC\nEOF\nelse\necho \"Configuring static ips: $(cat $NETWORK_CONFIG_PATH)\"\nSTATIC_IP=$(awk -v j=\"$INDEX\" '/address/{i++}i==j{print;exit}' $NETWORK_CONFIG_PATH | awk '{print $3}')\nGATEWAY=$(awk -v j=\"$INDEX\" '/gateway/{i++}i==j{print;exit}' $NETWORK_CONFIG_PATH | awk '{print $2}')\nif grep -A 2 \"$STATIC_IP\" \"$NETWORK_CONFIG_PATH\" | grep -q \"primary\"\nthen\nMETRIC=0\nelse\nMETRIC=50\nfi\ncat<<EOF >>\"$NETPLAN_CONFIG_PATH\"\n        $DNI:\n            set-name: $DNI\n            addresses:\n                - $STATIC_IP\n            routes:\n                - to: default\n                  via: $GATEWAY\n                  metric: $METRIC\n            match:\n                macaddress: $MAC\nEOF\nfi\nMETRIC=50\n((INDEX=INDEX+1))\ndone\n\nnetplan --debug apply\n\nsleep 5\nDNI_IP_LIST=$(ip route show | grep -Ev \"$DEFAULT_NETWORK|default|lo\"  | awk '{print $9}' | sort | uniq)\nwhile [ -z \"$DNI_IP_LIST\" ] || [[ $(echo \"$DNI_IP_LIST\" | wc -l) != \"$DNI_COUNT\" ]]\ndo\n    # if ip is not ready in 5 s, need to retry netplan apply\n    log::info \"IP is not ready, retrying\"\n    netplan --debug apply\n    sleep 5\n    DNI_IP_LIST=$(ip route show | grep -Ev \"$DEFAULT_NETWORK|default|lo\" | awk '{print $9}' | sort | uniq)\ndone\nlog::info \"IP leased: $DNI_IP_LIST\"\n\nlog::info \"network configuration finished\"\n\n# mount container data volume if exists\nDEVICE=$(lsblk | grep -E vd | awk '{print $1}')\nif [ -n \"$DEVICE\" ]; then\n    log::info \"found new device /dev/$DEVICE\"\n\n    # stop containerd and kubelet\n    systemctl stop containerd\n    systemctl stop kubelet\n\n    MOUNT_POINT=/var/lib/containerd\n    BACKUP_DIR=/var/lib/containerd_backup\n\n    # backup containerd data\n    mv \"$MOUNT_POINT\" \"$BACKUP_DIR\"\n\n    # recreate dir\n    mkdir \"$MOUNT_POINT\"\n\n    # format disk\n    mkfs -t ext4 /dev/\"$DEVICE\"\n\n    # mount new device\n    echo \"/dev/$DEVICE $MOUNT_POINT     ext4    defaults        0 0\" >>/etc/fstab\n    mount -a\n\n    # move containerd data back\n    mv \"$BACKUP_DIR\"/* \"$MOUNT_POINT\"/\n    rm -rf \"$BACKUP_DIR\"\n\n    # restart containerd and kubelet\n    systemctl restart containerd\n    systemctl restart kubelet\n\n    log::info \"successfully mounted new device /dev/$DEVICE\"\nelse\n    log::info \"no new device found, skipping volume mount process\"\nfi\n\n# restore stdout and stderr\nexec 1>&3 2>&4\n", "num_lines": 154}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -uxo pipefail\n\nlog::error() {\n  local message=\"${1}\"\n  timestamp=$(date --iso-8601=seconds)\n  echo \"!!! [${timestamp}] ${1}\" >&2\n}\n\n# Print a status line. Formatted to show up in a stream of output.\nlog::info() {\n  timestamp=$(date --iso-8601=seconds)\n  echo \"+++ [${timestamp}] ${1}\"\n}\n", "num_lines": 16}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nINLINE_VARS_FILE=\"${1?Specify first argument - inline vars file for goss}\"\n\nTEST_VM_NAME=vendor-validation-testing\nSSH_KEY=$(cat ${HOME}/.ssh/id_rsa.pub)\nUSERNAME=tester\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\n\nGOSS_DIR=$MAKE_ROOT/image-builder/images/capi/packer/goss\nREMOTE_GOSS_DIR=/home/$USERNAME\n\n# Clone the template to a vm\ngovc vm.clone -on=false -vm $TEMPLATE -net=sddc-cgw-network-1 $TEST_VM_NAME\n\n# Set the meta data to the clonned vm\ngovc vm.change -vm $TEST_VM_NAME \\\n\t-e guestinfo.metadata=\"$(MACADDRESS=$(govc device.info -vm $TEST_VM_NAME -json ethernet-0 | jq \".Devices[0].MacAddress\") TEST_VM_NAME=$TEST_VM_NAME envsubst < $MAKE_ROOT/validate/metadata.yaml | base64)\" \\\n\t-e guestinfo.metadata.encoding=\"base64\"\n\n# Set the user data to the clonned vm to add users\ngovc vm.change -vm $TEST_VM_NAME \\\n\t-e guestinfo.userdata=\"$(SSH_KEY=$SSH_KEY USERNAME=$USERNAME envsubst < $MAKE_ROOT/validate/cloudconfig.yaml | base64)\" \\\n\t-e guestinfo.userdata.encoding=\"base64\"\n\ngovc vm.power -on $TEST_VM_NAME\n\n# Wait for the vm to get an ip\necho \"Waiting for vm\"\ngovc vm.info -waitip $TEST_VM_NAME\n\nREMOTE_IP=$(govc vm.ip $TEST_VM_NAME)\necho \"Remote vm ip address is\" $REMOTE_IP\n\n# Run all the pre-reqs commands\ndeclare -a cmds=(\"sudo apt install git -y\"\n\t\t\t\t \"sudo curl -L https://github.com/aelsabbahy/goss/releases/latest/download/goss-linux-amd64 -o /usr/local/bin/goss\"\n\t\t\t\t \"sudo chmod +rx /usr/local/bin/goss\"\n)\n\nfor cmd in \"${cmds[@]}\"\ndo\n\tssh -o StrictHostKeyChecking=no $USERNAME@$REMOTE_IP \"$cmd\"\ndone\n\n# Copy over all the goss scripts\nscp -o StrictHostKeyChecking=no -r $GOSS_DIR/* $USERNAME@$REMOTE_IP:$REMOTE_GOSS_DIR\n\n# Run the goss scripts\nINLINE_VARS=$(cat $INLINE_VARS_FILE)\nssh -o StrictHostKeyChecking=no $USERNAME@$REMOTE_IP \"sudo goss -g goss.yaml --vars goss-vars.yaml --vars-inline '$INLINE_VARS' validate --retry-timeout 0s --sleep 1s -f json -o pretty\"\n\nif [ $? -ne 0 ]; then\n\techo \"Goss validation failed\"\n\techo \"The vm is left on, please access with $USERNAME@$REMOTE_IP\"\n\texit 1\nelse\n\techo \"Goss validation passed\"\nfi\n\n# Deleting and removing the vm\ngovc vm.destroy $TEST_VM_NAME\nexit 0", "num_lines": 83}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nEKSD_RELEASE_BRANCH=\"$1\"\nARTIFACTS_BUCKET=\"$2\"\nOUTPUT_FILE=\"$3\"\nLATEST_TAG=\"$4\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nBUILD_LIB=\"${MAKE_ROOT}/../../../build/lib\"\nsource \"${BUILD_LIB}/common.sh\"\n\n# Preload release yaml\nbuild::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH false\n\nKUBE_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $EKSD_RELEASE_BRANCH)\nEKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)\nEKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)\nEKSD_VERSION_SUFFIX=\"eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE\"\nEKSD_KUBE_VERSION=\"$KUBE_VERSION-$EKSD_VERSION_SUFFIX\"\nCOREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version \"coredns\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\nETCD_VERSION=$(build::eksd_releases::get_eksd_component_version \"etcd\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\n\nCNI_PLUGINS_AMD64_URL=$(build::eksd_releases::get_eksd_component_url \"cni-plugins\" $EKSD_RELEASE_BRANCH amd64)\nCNI_PLUGINS_ARM64_URL=$(build::eksd_releases::get_eksd_component_url \"cni-plugins\" $EKSD_RELEASE_BRANCH arm64)\nCNI_PLUGINS_AMD64_SHA256SUM=$(build::eksd_releases::get_eksd_component_sha \"cni-plugins\" $EKSD_RELEASE_BRANCH amd64)\nCNI_PLUGINS_ARM64_SHA256SUM=$(build::eksd_releases::get_eksd_component_sha \"cni-plugins\" $EKSD_RELEASE_BRANCH arm64)\n\nCRICTL_AMD64_URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET 'kubernetes-sigs/cri-tools' amd64 $LATEST_TAG)\nCRICTL_ARM64_URL=$(build::common::get_latest_eksa_asset_url $ARTIFACTS_BUCKET 'kubernetes-sigs/cri-tools' arm64 $LATEST_TAG)\nCRICTL_AMD64_SHA256SUM_URL=$CRICTL_AMD64_URL.sha256\nCRICTL_ARM64_SHA256SUM_URL=$CRICTL_ARM64_URL.sha256\n\nmkdir -p $(dirname $OUTPUT_FILE)\ncat <<EOF >> $OUTPUT_FILE\nEKSD_KUBE_VERSION=$EKSD_KUBE_VERSION\nEKSD_IMAGE_REPO=$EKSD_IMAGE_REPO\nCOREDNS_VERSION=$COREDNS_VERSION\nETCD_VERSION=$ETCD_VERSION\nCNI_PLUGINS_AMD64_URL=$CNI_PLUGINS_AMD64_URL\nCNI_PLUGINS_ARM64_URL=$CNI_PLUGINS_ARM64_URL\nCNI_PLUGINS_AMD64_SHA256SUM=$CNI_PLUGINS_AMD64_SHA256SUM\nCNI_PLUGINS_ARM64_SHA256SUM=$CNI_PLUGINS_ARM64_SHA256SUM\nCRICTL_AMD64_SHA256SUM_URL=$CRICTL_AMD64_SHA256SUM_URL\nCRICTL_ARM64_SHA256SUM_URL=$CRICTL_ARM64_SHA256SUM_URL\nCRICTL_AMD64_URL=$CRICTL_AMD64_URL\nCRICTL_ARM64_URL=$CRICTL_ARM64_URL\nEOF\n", "num_lines": 65}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o pipefail\n\nEKSD_RELEASE_BRANCH=\"${1?Specify first argument - release branch}\"\nINTERMEDIATE_BASE_IMAGE=\"${2?Specify second argument - kind base tag}\"\nARCH=\"${3?Specify third argument - Targetarch}\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\n# Include common constants and other vars needed when building image\nsource \"${MAKE_ROOT}/_output/$EKSD_RELEASE_BRANCH/kind-node-image-build-args\"\n\nINTERMEDIATE_NODE_IMAGE=\"kind/build/node-image:$KUBE_VERSION-$EKSD_RELEASE_BRANCH\"\n\n# Uses kind cli to build node-image, usually the fake kubernetes src\n# to download the eks-d release artifacts instead of building from src\n# ouput image: $INTERMEDIATE_NODE_IMAGE\nfunction build::kind::build_node_image(){\n    export KUBE_VERSION=$KUBE_VERSION\n    export EKSD_RELEASE_BRANCH=$EKSD_RELEASE_BRANCH\n    export EKSD_RELEASE=$EKSD_RELEASE\n    export EKSD_IMAGE_REPO=$EKSD_IMAGE_REPO\n    export EKSD_ASSET_URL=$EKSD_ASSET_URL\n    export KUBE_ARCH=$ARCH\n\n    KIND_PATH=\"$MAKE_ROOT/_output/bin/kind/$(uname | tr '[:upper:]' '[:lower:]')-$(go env GOHOSTARCH)/kind\"\n    $KIND_PATH build node-image $MAKE_ROOT/images/k8s.io/kubernetes \\\n        --base-image $INTERMEDIATE_BASE_IMAGE --image $INTERMEDIATE_NODE_IMAGE --arch $ARCH      \n}\n\nfunction build::kind::validate_versions(){\n    local -r container_id=$1\n    local -r eksd_tag=\"$KUBE_VERSION-eks-\" # there is a commit hash at the end\n    # We expect certain versions to be in the kind base/node images since we end up replacing them\n    # validate they haven't changed\n    if ! docker exec -i $container_id grep \"image: $KINDNETD_IMAGE_TAG\"  /kind/manifests/default-cni.yaml > /dev/null 2>&1; then\n        echo \"Did not find expected version of kindnetd: $KINDNETD_IMAGE_TAG\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id grep \"$LOCAL_PATH_HELPER_IMAGE_TAG\"  /kind/manifests/default-storage.yaml > /dev/null 2>&1; then\n        echo \"Did not find expected version of debian base: $LOCAL_PATH_HELPER_IMAGE_TAG\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id grep \"image: $LOCAL_PATH_PROVISONER_IMAGE_TAG\"  /kind/manifests/default-storage.yaml > /dev/null 2>&1; then\n        echo \"Did not find expected version of local path provisoner: $LOCAL_PATH_PROVISONER_IMAGE_TAG\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id grep \"$PAUSE_IMAGE_TAG\"  /etc/containerd/config.toml > /dev/null 2>&1; then\n        echo \"Did not find expected version of pause image: $PAUSE_IMAGE_TAG\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id /usr/bin/kubeadm version -oshort | grep \"$eksd_tag\" > /dev/null 2>&1; then\n        echo \"Did not find expected version of kubeadm: $eksd_tag\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id kubectl version --short --client=true | grep \"$eksd_tag\" > /dev/null 2>&1; then\n        echo \"Did not find expected version of kubectl: $eksd_tag\"\n        exit 1\n    fi\n    if ! docker exec -i $container_id kubelet --version | grep \"$eksd_tag\" > /dev/null 2>&1; then\n        echo \"Did not find expected version of kubelet: $eksd_tag\"\n        exit 1\n    fi\n}\n\n# This whole process of creating a container from the image, loading images\n# and commit it back is a recreation of what the kind build node-image does\n# the reason being is this is the easiest way to convert a docker/oci image\n# into an on disk containerd format\n# output image: $INTERMEDIATE_NODE_IMAGE\nfunction build::kind::load_images(){\n    CONTAINER_ID=$(docker run --platform linux/$ARCH --entrypoint sleep -d -i $INTERMEDIATE_NODE_IMAGE infinity)\n\n    build::kind::validate_versions $CONTAINER_ID\n\n    docker exec --privileged -i $CONTAINER_ID bash -c \"nohup containerd > /dev/null 2>&1 & sleep 5\"\n    docker exec --privileged -i $CONTAINER_ID crictl images\n\n    # pull local-path-provisioner + al2 helper image\n    IMAGES_FOLDER=$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/images\n    mkdir -p $IMAGES_FOLDER\n    IMAGES=(\"$AL2_HELPER_IMAGE\" \"$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE\" \"$PAUSE_IMAGE_TAG_OVERRIDE\" \"$KIND_KINDNETD_IMAGE_OVERRIDE\" \"$ETCD_IMAGE_TAG\" \"$COREDNS_IMAGE_TAG\")\n\n    declare -A release_image_overrides\n    release_image_overrides[\"$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE\"]=$LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE\n    release_image_overrides[\"$KIND_KINDNETD_IMAGE_OVERRIDE\"]=$KIND_KINDNETD_RELEASE_OVERRIDE\n\n    for image in \"${IMAGES[@]}\"; do\n        # docker pull when passing a platform will pull the image for the given platform\n        # and that new image id will \"take over\" the tag which we can use to trigger the save\n        build::docker::retry_pull --platform linux/$ARCH $image\n        image_id=$(docker images $image --format \"{{.ID}}\")\n\n        if [ ! -f $IMAGES_FOLDER/$image_id.tar ]; then\n            if [[ $image =~ local-path-provisioner ]] || [[ $image =~ kindnetd ]]; then\n                docker tag $image_id ${release_image_overrides[$image]}\n                docker save ${release_image_overrides[$image]} -o $IMAGES_FOLDER/$image_id.tar\n            else\n                docker save $image -o $IMAGES_FOLDER/$image_id.tar\n            fi\n        fi\n        docker exec --privileged -i $CONTAINER_ID \\\n            ctr --namespace=k8s.io images import --all-platforms --no-unpack - < $IMAGES_FOLDER/$image_id.tar\n    done\n\n    docker exec --privileged -i $CONTAINER_ID crictl images\n    \n    # Validate all images in the image are from public.ecr\n    EXPECTED_FINAL_IMAGES=(\"amazonlinux/amazonlinux\" \"kind/kindnetd\" \"rancher/local-path-provisioner\" \\\n        \"kubernetes/kube-apiserver\" \"kubernetes/kube-controller-manager\" \"kubernetes/kube-proxy\" \\\n        \"kubernetes/kube-scheduler\" \"kubernetes/pause\" \"coredns/coredns\" \"etcd-io/etcd\")\n    declare -a FOUND_EXPECTED_IMAGES\n    FINAL_IMAGES=$(docker exec -i $CONTAINER_ID crictl images -o json | jq \".images[].repoTags[]\" -r) \n    mapfile -t FINAL_IMAGES <<< \"$FINAL_IMAGES\"\n    declare -p FINAL_IMAGES\n    for image in \"${FINAL_IMAGES[@]}\"; do\n        if [[ ! $image =~ ^public\\.ecr\\.aws\\/ ]]; then\n            echo \"$image is not from public.ecr.aws!\"\n            exit 1\n        fi\n        EXPECTED_IMAGE=false\n        for expected in \"${EXPECTED_FINAL_IMAGES[@]}\"; do\n            if [[ $image =~ $expected ]]; then\n                FOUND_EXPECTED_IMAGES+=( \"$expected}\" )\n                EXPECTED_IMAGE=true\n                break\n            fi\n        done\n        if ! $EXPECTED_IMAGE; then\n            echo \"$image is not expected to be included in final image!\"\n            exit 1\n        fi\n        if [[ $ARCH != $(docker exec --privileged -i $CONTAINER_ID \\\n                crictl inspecti -o go-template --template={{.info.imageSpec.architecture}} $image) ]]; then\n            echo \"saved image: $image is not the correct arch: $ARCH!\"\n            exit 1\n        fi\n    done\n\n    if [[ \"${#FOUND_EXPECTED_IMAGES[@]}\" != \"${#EXPECTED_FINAL_IMAGES[@]}\" ]]; then\n        echo \"${EXPECTED_FINAL_IMAGES[*]} are expected to be included in the final image but only ${FOUND_EXPECTED_IMAGES[*]} exist!\"\n        exit 1\n    fi\n\n    if [[ $(docker exec --privileged -i $CONTAINER_ID ctr -n k8s.io snapshots ls | wc -l) -gt 1 ]]; then\n        echo \"Snapshots exists, all images should have been loaded but not unpacked!\"\n        exit 1\n    fi\n\n    docker exec --privileged -i $CONTAINER_ID pkill containerd\n\n    docker commit --change 'ENTRYPOINT [ \"/usr/local/bin/entrypoint\", \"/sbin/init\" ]' $CONTAINER_ID | sed -E 's/.*sha256:(.*)$/\\1/'\n\n    docker kill $CONTAINER_ID\n\n    # Copy files created by the node build process and ctr import out to be used in next build\n    FILES_DIR=$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/linux-$ARCH/files\n    ROOT_FS=$FILES_DIR/rootfs\n    mkdir -p $ROOT_FS/var/lib/containerd $ROOT_FS/etc/containerd\n    docker cp $CONTAINER_ID:/etc/containerd/config.toml $ROOT_FS/etc/containerd\n    docker cp $CONTAINER_ID:/kind $ROOT_FS\n    docker cp $CONTAINER_ID:/var/lib/containerd/io.containerd.content.v1.content $ROOT_FS/var/lib/containerd\n\n    mkdir -p $ROOT_FS/usr/bin\n    for binary in kubeadm kubelet kubectl; do\n        docker cp $CONTAINER_ID:/usr/bin/$binary $ROOT_FS/usr/bin\n    done\n    \n    # meta.db is the databse for containerd and its not reproducible since dates are included\n    # moving out of file directly to support reusing buildkit cache as much as possible\n    docker cp $CONTAINER_ID:/var/lib/containerd/io.containerd.metadata.v1.bolt $FILES_DIR\n\n    # update kind default manifests to use overridden images\n\tsed -i \"s,image: $LOCAL_PATH_PROVISONER_IMAGE_TAG,image: $LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE,\" $ROOT_FS/kind/manifests/default-storage.yaml\n\tsed -i \"s,$LOCAL_PATH_HELPER_IMAGE_TAG,$AL2_HELPER_IMAGE,\" $ROOT_FS/kind/manifests/default-storage.yaml\n\tsed -i \"s,image: $KINDNETD_IMAGE_TAG,image: $KIND_KINDNETD_RELEASE_OVERRIDE,\" $ROOT_FS/kind/manifests/default-cni.yaml\n\t# Update containerd config to have eks-d pause image tag\n\tsed -i \"s,$PAUSE_IMAGE_TAG,$PAUSE_IMAGE_TAG_OVERRIDE,\" $ROOT_FS/etc/containerd/config.toml\n}\n\nif command -v docker &> /dev/null && docker info > /dev/null 2>&1 ; then\n    build::kind::build_node_image\n    build::kind::load_images\nfi\n", "num_lines": 201}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nIMAGE=\"$1\"\nARCH=\"$2\"\nEKSD_RELEASE_BRANCH=\"$3\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nBUILD_LIB=\"${MAKE_ROOT}/../../../build/lib\"\nsource \"${BUILD_LIB}/common.sh\"\n\n# Preload release yaml\nbuild::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH false\n\nKUBE_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $EKSD_RELEASE_BRANCH)\nEKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)\nEKSD_VERSION_SUFFIX=\"eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE\"\nEKSD_KUBE_VERSION=\"$KUBE_VERSION-$EKSD_VERSION_SUFFIX\"\nCOREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version \"coredns\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\nETCD_VERSION=$(build::eksd_releases::get_eksd_component_version \"etcd\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\nEKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)\n\n# Make sure the correct arch image is pulled and tagged\nbuild::docker::retry_pull --platform linux/$ARCH $IMAGE\n\nKIND_PATH=\"$MAKE_ROOT/_output/bin/kind/$(uname | tr '[:upper:]' '[:lower:]')-$(go env GOHOSTARCH)/kind\"\ncat << EOF \\\n  | $KIND_PATH create cluster \\\n    --name \"eks-a-kind-test-$ARCH\" \\\n    --image=\"$IMAGE\" \\\n    --wait=\"5m\" -v9 --retain \\\n    --config=/dev/stdin \\\n    || true\napiVersion: kind.x-k8s.io/v1alpha4\nkind: Cluster\nkubeadmConfigPatches:\n- |\n    kind: ClusterConfiguration\n    dns:\n        type: CoreDNS\n        imageRepository: $EKSD_IMAGE_REPO/coredns\n        imageTag: $COREDNS_VERSION\n    etcd:\n        local:\n            imageRepository: $EKSD_IMAGE_REPO/etcd-io\n            imageTag: $ETCD_VERSION\n    imageRepository: $EKSD_IMAGE_REPO/kubernetes\n    kubernetesVersion: $EKSD_KUBE_VERSION\nEOF\n", "num_lines": 66}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o pipefail\n\nEKSD_RELEASE_BRANCH=\"$1\"\nKINDNETD_IMAGE_COMPONENT=\"$2\"\nIMAGE_REPO=\"$3\"\nARTIFACTS_BUCKET=\"$4\"\nIMAGE_TAG=\"$5\"\nLATEST=\"$6\"\nOUTPUT_FILE=\"$7\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nBUILD_LIB=\"${MAKE_ROOT}/../../../build/lib\"\nsource \"${BUILD_LIB}/common.sh\"\n\n# This is used by the local-path-provisioner within the kind node\nAL2_HELPER_IMAGE=\"public.ecr.aws/amazonlinux/amazonlinux:2\"\nLOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE=\"$IMAGE_REPO/rancher/local-path-provisioner:$LATEST\"\nLOCAL_PATH_PROVISONER_RELEASE_OVERRIDE=\"public.ecr.aws/eks-anywhere/rancher/local-path-provisioner:$(cat $MAKE_ROOT/../../rancher/local-path-provisioner/GIT_TAG)\"\nKIND_KINDNETD_RELEASE_OVERRIDE=\"public.ecr.aws/eks-anywhere/kubernetes-sigs/kind/kindnetd:$(cat $MAKE_ROOT/GIT_TAG)\"\nKIND_KINDNETD_IMAGE_OVERRIDE=\"$IMAGE_REPO/$KINDNETD_IMAGE_COMPONENT:$LATEST\"\n\n# Preload release yaml\nbuild::eksd_releases::load_release_yaml $EKSD_RELEASE_BRANCH\n\nKUBE_VERSION=$(build::eksd_releases::get_eksd_component_version \"kubernetes\" $EKSD_RELEASE_BRANCH)\nEKSD_RELEASE=$(build::eksd_releases::get_eksd_release_number $EKSD_RELEASE_BRANCH)\nEKSD_KUBE_VERSION=\"$KUBE_VERSION-eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE\"\nPAUSE_IMAGE_TAG_OVERRIDE=$(build::eksd_releases::get_eksd_kubernetes_image_url \"pause-image\" $EKSD_RELEASE_BRANCH)\nEKSD_IMAGE_REPO=$(build::eksd_releases::get_eksd_image_repo $EKSD_RELEASE_BRANCH)\nEKSD_ASSET_URL=$(build::eksd_releases::get_eksd_kubernetes_asset_base_url $EKSD_RELEASE_BRANCH)/$KUBE_VERSION\n\nEKSD_VERSION_SUFFIX=\"eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE\"\nCOREDNS_VERSION=$(build::eksd_releases::get_eksd_component_version \"coredns\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\nETCD_VERSION=$(build::eksd_releases::get_eksd_component_version \"etcd\" $EKSD_RELEASE_BRANCH)-$EKSD_VERSION_SUFFIX\n\n# Expected versions provided by kind which are replaced in the docker build with our versions\n# when updating kind check the following, they may need to be updated\n# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_cni.go#L23\nKINDNETD_IMAGE_TAG=\"docker.io/kindest/kindnetd:v20230330-48f316cd@sha256:c19d6362a6a928139820761475a38c24c0cf84d507b9ddf414a078cf627497af\"\n# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_storage.go#L28\nLOCAL_PATH_PROVISONER_IMAGE_TAG=\"docker.io/kindest/local-path-provisioner:v0.0.23-kind.0@sha256:f2d0a02831ff3a03cf51343226670d5060623b43a4cfc4808bd0875b2c4b9501\"\n# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/pkg/build/nodeimage/const_storage.go#L29\nLOCAL_PATH_HELPER_IMAGE_TAG=\"docker.io/kindest/local-path-helper:v20230330-48f316cd@sha256:135203f2441f916fb13dad1561d27f60a6f11f50ec288b01a7d2ee9947c36270\"\n# https://github.com/kubernetes-sigs/kind/blob/v0.18.0/images/base/files/etc/containerd/config.toml#L37\nPAUSE_IMAGE_TAG=\"registry.k8s.io/pause:3.7\"\n\nmkdir -p $(dirname $OUTPUT_FILE)\ncat <<EOF >> $OUTPUT_FILE\nAL2_HELPER_IMAGE=$AL2_HELPER_IMAGE\nLOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE=$LOCAL_PATH_PROVISONER_IMAGE_TAG_OVERRIDE\nLOCAL_PATH_PROVISONER_RELEASE_OVERRIDE=$LOCAL_PATH_PROVISONER_RELEASE_OVERRIDE\nKIND_KINDNETD_RELEASE_OVERRIDE=$KIND_KINDNETD_RELEASE_OVERRIDE\nKIND_KINDNETD_IMAGE_OVERRIDE=$KIND_KINDNETD_IMAGE_OVERRIDE\nKUBE_VERSION=$KUBE_VERSION\nEKSD_RELEASE=$EKSD_RELEASE\nEKSD_KUBE_VERSION=$EKSD_KUBE_VERSION\nPAUSE_IMAGE_TAG_OVERRIDE=$PAUSE_IMAGE_TAG_OVERRIDE\nEKSD_IMAGE_REPO=$EKSD_IMAGE_REPO\nEKSD_ASSET_URL=$EKSD_ASSET_URL\nKINDNETD_IMAGE_TAG=$KINDNETD_IMAGE_TAG\nLOCAL_PATH_HELPER_IMAGE_TAG=$LOCAL_PATH_HELPER_IMAGE_TAG\nLOCAL_PATH_PROVISONER_IMAGE_TAG=$LOCAL_PATH_PROVISONER_IMAGE_TAG\nPAUSE_IMAGE_TAG=$PAUSE_IMAGE_TAG\nNODE_IMAGE_TAG=$EKSD_KUBE_VERSION-$IMAGE_TAG\nNODE_IMAGE_LATEST_TAG=$EKSD_KUBE_VERSION-$LATEST\nETCD_IMAGE_TAG=$EKSD_IMAGE_REPO/etcd-io/etcd:$ETCD_VERSION\nCOREDNS_IMAGE_TAG=$EKSD_IMAGE_REPO/coredns/coredns:$COREDNS_VERSION\nEOF\n", "num_lines": 85}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nEKSD_RELEASE_BRANCH=\"${1?Specify first argument - release branch}\"\nARCH=\"${2?Specify second argument - Targetarch}\"\n\nDEP_FOLDER=\"$MAKE_ROOT/_output/$EKSD_RELEASE_BRANCH/dependencies/linux-$ARCH\"\nOUTPUT_FOLDER=\"$DEP_FOLDER/files/rootfs\"\nmkdir -p $OUTPUT_FOLDER/LICENSES\n\nfor FOLDER in eksd/kubernetes eksa/kubernetes-sigs/etcdadm eksd/cni-plugins eksa/kubernetes-sigs/cri-tools; do\n    cp -rf $DEP_FOLDER/$FOLDER/LICENSES \"$OUTPUT_FOLDER/LICENSES/$(echo $(basename $FOLDER) | tr a-z A-Z  | tr -d '-'  )_LICENSES\"\n    cp $DEP_FOLDER/$FOLDER/ATTRIBUTION.txt \"$OUTPUT_FOLDER/LICENSES/$(echo $(basename $FOLDER) | tr a-z A-Z  | tr -d '-'  )_ATTRIBUTION.txt\"\ndone\n\nmkdir -p $OUTPUT_FOLDER/usr/bin/\ncp $DEP_FOLDER/eksa/kubernetes-sigs/etcdadm/etcdadm $OUTPUT_FOLDER/usr/bin/\n\n# Place etcd tarball etcdadm cache directory to avoid downloading at runtime   \nETCD_VERSION=$(build::eksd_releases::get_eksd_component_version \"etcd\" $EKSD_RELEASE_BRANCH $ARCH)\nFOLDER=\"$OUTPUT_FOLDER/var/cache/etcdadm/etcd/$ETCD_VERSION\"\nmkdir -p $FOLDER\ncp $DEP_FOLDER/eksd/etcd/etcd.tar.gz $FOLDER/etcd-$ETCD_VERSION-linux-$ARCH.tar.gz\n", "num_lines": 42}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n/usr/bin/kubeadm --config /etc/kubeadm.config \"$@\"\n", "num_lines": 17}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# the upstream version of this script builds the image\n# download them from eks-distro public.ecr\n# and pulls the binaries from the eks-d release bucket\n\n# since kind is calling this directly, cannot require args\n# instead the following env vars are required\nif [[ -z \"${KUBE_VERSION}\" ]]; then\n    echo \"KUBE_VERSION env var not set\"\n    exit 1\nfi\n\nif [[ -z \"${EKSD_RELEASE_BRANCH}\" ]]; then\n    echo \"EKSD_RELEASE_BRANCH env var not set\"\n    exit 1\nfi\n\nif [[ -z \"${EKSD_RELEASE}\" ]]; then\n    echo \"EKSD_RELEASE env var not set\"\n    exit 1\nfi\n\nif [[ -z \"${EKSD_IMAGE_REPO}\" ]]; then\n    echo \"EKSD_IMAGE_REPO env var not set\"\n    exit 1\nfi\nif [[ -z \"${EKSD_ASSET_URL}\" ]]; then\n    echo \"EKSD_ASSET_URL env var not set\"\n    exit 1\nfi\n\nif [[ -z \"${KUBE_ARCH}\" ]]; then\n    echo \"KUBE_ARCH env var not set\"\n    exit 1\nfi\n\nSOURCE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\n\n# symlink to project root _output to make sure files are properly cleaned up\n# when running make clean\nPROJECT_ROOT=\"$(cd \"$SOURCE_ROOT/../../..\" && pwd -P)\"\n\nsource \"${PROJECT_ROOT}/../../../build/lib/common.sh\"\n\n\nrm -f $SOURCE_ROOT/_output\nln -s $PROJECT_ROOT/_output/$EKSD_RELEASE_BRANCH $SOURCE_ROOT/_output\n\n# Download binaries\nmkdir -p $SOURCE_ROOT/_output/dockerized/bin/linux/$KUBE_ARCH \n\nfor binary in \"kubeadm\" \"kubelet\" \"kubectl\"; do\n    FILE=\"$SOURCE_ROOT/_output/dockerized/bin/linux/$KUBE_ARCH/$binary \"\n    if [ ! -f $FILE ]; then\n        curl $EKSD_ASSET_URL/bin/linux/$KUBE_ARCH/$binary -o $FILE\n    fi\ndone\n\n# Download container images\nEKSD_TAG=\"$KUBE_VERSION-eks-$EKSD_RELEASE_BRANCH-$EKSD_RELEASE\"\n\nmkdir -p $SOURCE_ROOT/_output/release-images/$KUBE_ARCH/   \n\nfor container in \"kube-apiserver\" \"kube-controller-manager\" \"kube-scheduler\" \"kube-proxy\"; do\n    IMAGE_TAG=\"$EKSD_IMAGE_REPO/kubernetes/$container:$EKSD_TAG\"\n    FILE=\"$SOURCE_ROOT/_output/release-images/$KUBE_ARCH/$container.tar\"\n    if [ ! -f $FILE ]; then\n        build::docker::retry_pull --platform linux/$KUBE_ARCH $IMAGE_TAG\n        docker save $IMAGE_TAG -o $FILE\n    fi\ndone\n", "num_lines": 91}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# kind calls this scripts to build the binaries\n# for versions < 1.21. for other versions it relies\n# on the download-images script to also build the binaries\n# this script will be a noop only to support < 1.21 builds\n", "num_lines": 25}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# the upstream verison of this scripts a number of\n# version related information, but all kind is checking for\n# is gitVersion\n\n# since kind is calling this directly, cannot require args\n# instead the following env vars are required\n# KUBE_VERSION\n\nif [[ -z \"${KUBE_VERSION}\" ]]; then\n    echo \"KUBE_VERSION env var not set\"\n    exit 1\nfi\n\necho \"gitVersion $KUBE_VERSION\"\n", "num_lines": 34}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\nGOLANG_VERSION=\"$7\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nbuild::common::use_go_version $GOLANG_VERSION\n\ncd $REPO\n\nsed -i'' -e 's@newName: .*@newName: '\"${IMAGE_REPO}/nutanix-cloud-native/cluster-api-provider-nutanix\"'@' config/manager/kustomization.yaml\nsed -i'' -e 's@newTag: .*@newTag: '\"${IMAGE_TAG}\"'@' config/manager/kustomization.yaml\nsed -i'' -e 's@image: .*@image: '\"${IMAGE_REPO}/brancz/kube-rbac-proxy:latest\"'@' config/default/manager_auth_proxy_patch.yaml\n\nmake release-manifests \\\n  RELEASE_DIR=\"out\" \\\n  IMG=\"${IMAGE_REPO}:${IMAGE_TAG}\"\n\nmkdir -p $OUTPUT_DIR/manifests/infrastructure-nutanix/$TAG\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/infrastructure-nutanix/$TAG\"\ncp out/cluster-template.yaml \"$OUTPUT_DIR/manifests/infrastructure-nutanix/$TAG\"\ncp out/infrastructure-components.yaml \"$OUTPUT_DIR/manifests/infrastructure-nutanix/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 50}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# compress static assets\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\ncd prometheus/web/ui\ncp embed.go.tmpl embed.go\n\n# We run gzip with the following flags:\n# -f overwrite of output file and compress links;\n# -k keeps input files;\n# -n drops the original name and timestamp so that the embeded assets\n# generate deterministic checksums.\nGZIP_OPTS=\"-fkn\"\n# gzip option '-k' may not always exist in the latest gzip available on different distros.\nif ! gzip -k -h &>/dev/null; then GZIP_OPTS=\"-fn\"; fi\n\nfind static -type f -name '*.gz' -delete\nfind static -type f -exec gzip $GZIP_OPTS '{}' \\; -print0 | xargs -0 -I % echo %.gz | xargs echo //go:embed >> embed.go\necho var EmbedFS embed.FS >> embed.go\n", "num_lines": 37}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAR=tar\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    TAR=gtar\nfi\n\nrm -f \"prometheus/npm_licenses.tar.bz2\"\nfind prometheus/web/ui/node_modules -iname \"license*\" | $TAR cfj \"prometheus/npm_licenses.tar.bz2\" --transform 's/^/npm_licenses\\//' --files-from=-\n", "num_lines": 27}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nIMAGE_REPO=\"$5\"\nIMAGE_TAG=\"$6\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\ncd $REPO\n\nmake release \\\n  RELEASE_DIR=\"out\" \\\n  REGISTRY=${IMAGE_REPO} \\\n  TAG=${IMAGE_TAG}\n\nmkdir -p $OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG\ncp out/cluster-template.yaml \"$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG\"\ncp out/infrastructure-components.yaml \"$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG\"\ncp out/metadata.yaml \"$OUTPUT_DIR/manifests/infrastructure-tinkerbell/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 44}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nARTIFACTS_PATH=\"$3\"\nTAG=\"$4\"\nGOLANG_VERSION=\"$5\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nbuild::common::use_go_version ${GOLANG_VERSION}\n\ncd $REPO\n\nmake release-manifests \\\n  RELEASE_DIR=\"out\" \\\n\nmkdir -p $OUTPUT_DIR/manifests/infrastructure-rufio/$TAG\ncp out/manifest.yaml \"$OUTPUT_DIR/manifests/infrastructure-rufio/$TAG\"\n\ncp -rf $OUTPUT_DIR/manifests $ARTIFACTS_PATH\n", "num_lines": 41}
{"repo_name": "eks-anywhere-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o pipefail\n\nREPO=\"$1\"\nARTIFACTS_PATH=\"$2\"\nIMAGE_REPO=\"$3\"\nTINK_SERVER_IMAGE_COMPONENT=\"$4\"\nTINK_CONTROLLER_IMAGE_COMPONENT=\"$5\"\nIMAGE_TAG=\"$6\"\nGOLANG_VERSION=\"$7\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nbuild::common::use_go_version ${GOLANG_VERSION}\n\ncd $REPO\n\nnpm install prettier --global\n\nmake release-manifests \\\n  TINK_SERVER_IMAGE=${IMAGE_REPO}/${TINK_SERVER_IMAGE_COMPONENT} \\\n  TINK_CONTROLLER_IMAGE=${IMAGE_REPO}/${TINK_CONTROLLER_IMAGE_COMPONENT} \\\n  TINK_SERVER_TAG=${IMAGE_TAG} \\\n  TINK_CONTROLLER_TAG=${IMAGE_TAG}\n\ncp out/release/tink.yaml $ARTIFACTS_PATH\n", "num_lines": 45}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\n<<COMMENT\ngo mod init\ngo mod vendor -v\nCOMMENT\n\ngo mod init || true\ngo mod tidy -v", "num_lines": 10}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Common functions used by various build scripts. To use these\n# functions, source this file, e.g.:\n#    . <path-to-this-file>/common.sh\n\n# awsAuth echoes an AWS ECR password\nfunction awsAuth () {\n    local repo=${1?:no repo specified}\n    local awsCmd=\"ecr\"\n    local region=\"--region=us-west-2\"\n\n    if [[ $repo =~ \"public.ecr.aws\" ]]; then\n        awsCmd=\"ecr-public\"\n        region=\"--region=us-east-1\"\n    fi\n\n    aws \"$awsCmd\" \"$region\" \"--profile=${PROFILE:-}\" get-login-password\n}\n\nfunction generate () {\n    local version=$1\n    local stage=$2\n    local kms_key=signingPackagesKey\n\n    cd \"${BASE_DIRECTORY}/generatebundlefile\"\n    ./bin/generatebundlefile --input \"./data/bundles_${stage}/${version}.yaml\" \\\n                 --key alias/${kms_key} \\\n                 --output \"output-${version}\"\n}\n\nfunction regionCheck () {\n    local version=$1\n    cd \"${BASE_DIRECTORY}/generatebundlefile\"\n    ./bin/generatebundlefile --bundle \"output-${version}/bundle.yaml\" \\\n                --region-check true || true\n}\n\nfunction push () {\n    local version=${1?:no version specified}\n    cd \"${BASE_DIRECTORY}/generatebundlefile/output-${version}\"\n    awsAuth \"$REPO\" | \"$ORAS_BIN\" login \"$REPO\" --username AWS --password-stdin\n    removeBundleMetadata bundle.yaml\n    if \"$ORAS_BIN\" pull \"${REPO}:v${version}-latest\" -o ${version}; then\n        removeBundleMetadata ${version}/bundle.yaml\n    else\n        mkdir -p ${version} && touch ${version}/bundle.yaml.stripped\n    fi\n\n    if (git diff --no-index --quiet -- ${version}/bundle.yaml.stripped bundle.yaml.stripped) then\n        echo \"bundle contents are identical skipping bundle push for ${version}\"\n    else\n        \"$ORAS_BIN\" push \"${REPO}:v${version}-${CODEBUILD_BUILD_NUMBER}\" bundle.yaml\n        \"$ORAS_BIN\" push \"${REPO}:v${version}-latest\" bundle.yaml\n    fi\n}\n\nfunction removeBundleMetadata () {\n    local bundle=${1?:no bundle specified}\n    yq 'del(.metadata.name)' ${bundle} > ${bundle}.strippedname\n    yq 'del(.metadata.annotations)' ${bundle}.strippedname > ${bundle}.stripped\n}\n", "num_lines": 77}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Generate bundle files for supported kubernetes versions.\n\nset -euxo pipefail\n\nexport LANG=C.UTF-8\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\n. \"${BASE_DIRECTORY}/generatebundlefile/hack/common.sh\"\nECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries \\\n                 --query 'registries[*].registryUri' --output text)\nREPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles\nORAS_BIN=${BASE_DIRECTORY}/bin/oras\n\nif [ ! -x \"${ORAS_BIN}\" ]; then\n    make oras-install\nfi\n\nmake build\nchmod +x ${BASE_DIRECTORY}/generatebundlefile/bin\n\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    generate ${version} \"dev\"\n    push ${version}\ndone\n", "num_lines": 41}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nexport LANG=C.UTF-8\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nHELM_REPO=${HELM_REPO}\necho ${HELM_REPO}\n\nmake build\nchmod +x ${BASE_DIRECTORY}/generatebundlefile/bin\n\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\naws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\ncd \"${BASE_DIRECTORY}/generatebundlefile\"\n\nif [[ -n \"${PROMOTE_FILE}\" ]]; then\n    if [[ \"${HELM_REPO}\" == \"eks-anywhere-packages\" ]]; then\n        # We need to copy the images for the packages helm chart, but no other packages.\n        ./bin/generatebundlefile  \\\n            --promote ${HELM_REPO} --input ${PROMOTE_FILE} --copy-images\n    else\n        ./bin/generatebundlefile  \\\n            --promote ${HELM_REPO} --input ${PROMOTE_FILE}\n    fi\nelse\n    ./bin/generatebundlefile  \\\n        --promote ${HELM_REPO}\nfi\n", "num_lines": 49}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n#!/usr/bin/env bash\n\n\n###################\n\n# This file is NOT meant to be run as a script, or in CI. It's for useful commands when developing/testing generatebundle.\n\n####################\n\nset -e\n\nexport local_ecr_public=\"public.ecr.aws/f5b7k4z5\"\n\nfunction repoExists () {\n    aws ecr-public describe-repositories \\\n        | jq -r \".repositories[].repositoryName\" \\\n        | grep -q \"^$1\\$\"\n}\n\nREPO_1=hello-eks-anywhere\nREPO_2=eks-anywhere-packages\nif ! repoExists ${REPO_1}; then\n      aws ecr-public  create-repository --repository-name ${REPO_1}\nfi\n\nif ! repoExists ${REPO_2}; then\n      aws ecr-public create-repository --repository-name ${REPO_2}\nfi\n\n#############\n### ECR Logins\n#############\n\nexport HELM_EXPERIMENTAL_OCI=1\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\naws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin 646717423341.dkr.ecr.us-west-2.amazonaws.com\n\n################################################\n# Populate Test cases for generateBundle\n# TODO replace version this with an upstream version from the dev Account once it's published.\n#################################################\n\nhelm pull oci://646717423341.dkr.ecr.us-west-2.amazonaws.com/hello-eks-anywhere --version 0.1.0+c4e25cb42e9bb88d2b8c2abfbde9f10ade39b214\nhelm push hello-eks-anywhere-0.1.0+c4e25cb42e9bb88d2b8c2abfbde9f10ade39b214.tgz \"oci://$local_ecr_public\"\n\n########################\n# Oras examples\n#########################\n\n# Manually push a local bundle\ncd output/\noras push public.ecr.aws/f5b7k4z5/eks-anywhere-packages-bundles:v1.0.0-bundle bundle-1.20.yaml\n\n# Pull latest bundle\noras pull public.ecr.aws/f5b7k4z5/eks-anywhere-packages-bundles:v1\n\n########################\n# Hack to Simulate Codebuild jobs locally, Run Builder-base test of promo/signing flags\n########################\n\ngo mod vendor\ndocker run -d -v ${HOME}/.aws/credentials:/root/.aws/credentials:ro -v ${HOME}/go/src/github.com/modelrocket/eks-anywhere-packages:/go/src/github.com/aws/modelrocket/eks-anywhere-packages public.ecr.aws/eks-distro-build-tooling/builder-base:latest  tail -f /dev/null\ndocker ps\ndocker exec -it <CONTAINER_ID> /bin/bash\ncd eks-anywhere-packages/\n./generatebundlefile/hack/setup.sh\n\n# Change the `make build` command to use vendor\n\nbuild: ## Build release binary.\n\tmkdir -p $(REPO_ROOT)/generatebundlefile/bin\n\t$(GO) build -mod vendor -o $(REPO_ROOT)/generatebundlefile/bin/generatebundlefile *.go\n\n", "num_lines": 89}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nexport LANG=C.UTF-8\n\nBASE_AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\n\ncat << EOF > configfile\n[default]\nregion=us-west-2\naccount=$BASE_AWS_ACCOUNT_ID\noutput=json\n\n[profile packages]\nrole_arn=$PACKAGES_ARTIFACT_DEPLOYMENT_ROLE\nregion=us-west-2\ncredential_source=EcsContainer\nEOF\n\n# Release Package Images to Packages Artifact account\nexport CODEBUILD_BUILD_NUMBER=$(($CODEBUILD_BUILD_NUMBER+110))\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile\nexport PROFILE=packages\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\n. \"${BASE_DIRECTORY}/generatebundlefile/hack/common.sh\"\nORAS_BIN=${BASE_DIRECTORY}/bin/oras\n\nmake build\nchmod +x ${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile\n\naws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\n${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \\\n    --input ${BASE_DIRECTORY}/generatebundlefile/data/prod_artifact_move.yaml \\\n    --private-profile ${PROFILE}\n\n# Release Helm Chart, and bundle to Production account\ncat << EOF > prodconfigfile\n[default]\nregion=us-west-2\naccount=$BASE_AWS_ACCOUNT_ID\noutput=json\n\n[profile prod]\nrole_arn=$ARTIFACT_DEPLOYMENT_ROLE\nregion=us-east-1\ncredential_source=EcsContainer\nEOF\n\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/prodconfigfile\nexport PROFILE=prod\n. \"${BASE_DIRECTORY}/generatebundlefile/hack/common.sh\"\nECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries --profile ${PROFILE} --query 'registries[*].registryUri' --output text)\nREPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles\n\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\n# Move Helm charts within the bundle to another account\n${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \\\n    --input ${BASE_DIRECTORY}/generatebundlefile/data/prod_artifact_move.yaml \\\n    --public-profile ${PROFILE}\n\nif [ ! -x \"${ORAS_BIN}\" ]; then\n    make oras-install\nfi\n\nexport AWS_PROFILE=prod\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/prodconfigfile\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    generate ${version} \"prod\"\ndone\n\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    push ${version}\ndone\n", "num_lines": 97}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -x\nset -o pipefail\n\nexport LANG=C.UTF-8\n\nBASE_AWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\n\ncat << EOF > configfile\n[default]\nregion=us-west-2\naccount=$BASE_AWS_ACCOUNT_ID\noutput=json\n\n[profile packages]\nrole_arn=$PACKAGES_ARTIFACT_DEPLOYMENT_ROLE\nregion=us-west-2\ncredential_source=EcsContainer\nEOF\n\n# Release Package Images to Packages Artifact account\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile\nexport PROFILE=packages\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\n. \"${BASE_DIRECTORY}/generatebundlefile/hack/common.sh\"\nORAS_BIN=${BASE_DIRECTORY}/bin/oras\n\nmake build\nchmod +x ${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile\n\naws ecr get-login-password --region us-west-2 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin ${AWS_ACCOUNT_ID}.dkr.ecr.us-west-2.amazonaws.com\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\n# Move Helm Images within the bundle to Private ECR\n${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \\\n    --input ${BASE_DIRECTORY}/generatebundlefile/data/staging_artifact_move.yaml \\\n    --private-profile ${PROFILE}\n\n# Release Helm Chart, and bundle to Staging account\ncat << EOF > stagingconfigfile\n[default]\nregion=us-west-2\naccount=$BASE_AWS_ACCOUNT_ID\noutput=json\n\n[profile staging]\nrole_arn=$ARTIFACT_DEPLOYMENT_ROLE\nregion=us-east-1\ncredential_source=EcsContainer\nEOF\n\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/stagingconfigfile\nexport PROFILE=staging\n. \"${BASE_DIRECTORY}/generatebundlefile/hack/common.sh\"\nECR_PUBLIC=$(aws ecr-public --region us-east-1 describe-registries --profile ${PROFILE} --query 'registries[*].registryUri' --output text)\nREPO=${ECR_PUBLIC}/eks-anywhere-packages-bundles\n\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\n\n# Move Helm charts within the bundle to Public ECR\n${BASE_DIRECTORY}/generatebundlefile/bin/generatebundlefile  \\\n    --input ${BASE_DIRECTORY}/generatebundlefile/data/staging_artifact_move.yaml \\\n    --public-profile ${PROFILE}\n\nif [ ! -x \"${ORAS_BIN}\" ]; then\n    make oras-install\nfi\n\n# Generate Bundles from Public ECR\nexport AWS_PROFILE=staging\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/stagingconfigfile\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    generate ${version} \"staging\"\ndone\n\n# Push Bundles to Public ECR\naws ecr-public get-login-password --region us-east-1 | HELM_EXPERIMENTAL_OCI=1 helm registry login --username AWS --password-stdin public.ecr.aws\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    push ${version}\ndone\n\n# Check images from Bundle in Private ECR\nexport AWS_CONFIG_FILE=${BASE_DIRECTORY}/generatebundlefile/configfile\nexport AWS_PROFILE=packages\nfor version in 1-22 1-23 1-24 1-25 1-26 1-27; do\n    regionCheck ${version}\ndone\n", "num_lines": 105}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o pipefail\n\n# More Information about the Docker Cred Helper https://github.com/docker/docker-credential-helpers\n# ECR credential helper automatically uses the same credentials as the AWS CLI and the AWS SDKs \n# to first retrieve an ECR authentication token for each account for secure access to repositories,\n# then lets the Docker daemon use this token when familiar Docker commands such as docker push or docker pull\nif [ ! -d \"/root/.docker\" ]; then\n    mkdir -p /root/.docker\nfi\n\nif [ ! -d \"/root/.config/containers\" ]; then\n    mkdir -p /root/.config/containers\nfi\n\nmv generatebundlefile/hack/policy.json /root/.config/containers/policy.json\nmv generatebundlefile/hack/docker-ecr-config.json /root/.docker/config.json\ngit config --global credential.helper '!aws codecommit credential-helper $@'\ngit config --global credential.UseHttpPath true", "num_lines": 35}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nROOT_DIR=\"$(git rev-parse --show-toplevel)\"\n\ncd ${ROOT_DIR}\n./bin/kustomize build config/crd > charts/eks-anywhere-packages/crds/crd.yaml\n./bin/kustomize build config/crd > charts/eks-anywhere-packages-crds/templates/crd.yaml\n\ncd charts\nhelm lint eks-anywhere-packages\nOUTDIR=_output\nrm -rf $OUTDIR\nmkdir $OUTDIR\ncp -r eks-anywhere-packages $OUTDIR\nEKS_ANYWHERE_PACKAGES_TAG=$(cat image-tags/eks-anywhere-packages)\nsed \\\n        -e \"s,{{eks-anywhere-packages}},${EKS_ANYWHERE_PACKAGES_TAG},\" \\\n        eks-anywhere-packages/values.yaml >${OUTDIR}/eks-anywhere-packages/values.yaml\ncd $OUTDIR\nRESULT=$(helm package eks-anywhere-packages| sed -e 's/Successfully packaged chart and saved it to: //g')\necho \"helm install eks-anywhere-packages ${RESULT}\"\n", "num_lines": 40}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nyq () {\n  local file=$1\n  local query=$2\n  local params=$3\n  docker run --rm -i --entrypoint yq linuxserver/yq ${params} -rc \"${query}\" <${file}\n}\nfile=$1 \ntmpfile=$(mktemp ${file}.digest.XXXXXX)\nalwaysexcludes='.metadata.annotations.\"eksa.aws.com/signature\"'\nhas_excludes=$(yq \"${file}\" '.metadata.annotations.\"eksa.aws.com/excludes\"')\n\nexcludes=\"\"\nif [ \"${has_excludes}\" != \"null\" ]; then\n    excludes=$(yq \"${file}\" '.metadata.annotations.\"eksa.aws.com/excludes\"' | base64 -d | cat <(echo ${alwaysexcludes}) - | paste -sd \",\" -) \nfi\nyq ${file} \"del(${alwaysexcludes}$([ ! -z ${excludes} ] && echo , ${excludes})) | walk( if type == \\\"object\\\" then with_entries(select(.value != \\\"\\\" and .value != null and .value != [])) else . end)\" \"--indentless-lists -Y -S\" | openssl dgst -sha256 -binary >${tmpfile}\nsignature=$(openssl pkeyutl -inkey pkg/signature/testdata/private.ec.key -sign -in ${tmpfile} | base64 | tr -d '\\n')\nyq \"${file}\" \".metadata.annotations.\\\"eksa.aws.com/signature\\\" = \\\"${signature}\\\"\" -Y > \"${file}.signed\"\ncat ${tmpfile} | base64 | tr -d '\\n' > ${file}.digest\nrm -f ${tmpfile}\n", "num_lines": 22}
{"repo_name": "eks-anywhere-packages", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction build::common::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  elif which gnutar &>/dev/null; then\n      TAR=gnutar\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\n# Build a release tarball.  $1 is the output tar name.  $2 is the base directory\n# of the files to be packaged.  This assumes that ${2}/kubernetes is what is\n# being packaged.\nfunction build::common::create_tarball() {\n  build::common::ensure_tar\n\n  local -r tarfile=$1\n  local -r stagingdir=$2\n  local -r repository=$3\n\n  \"${TAR}\" czf \"${tarfile}\" -C \"${stagingdir}\" $repository --owner=0 --group=0\n}\n\n# Generate shasum of tarballs. $1 is the directory of the tarballs.\nfunction build::common::generate_shasum() {\n\n  local -r tarpath=$1\n\n  echo \"Writing artifact hashes to shasum files...\"\n\n  if [ ! -d \"$tarpath\" ]; then\n    echo \"  Unable to find tar directory $tarpath\"\n    exit 1\n  fi\n\n  cd $tarpath\n  for file in $(find . -name '*.tar.gz'); do\n    filepath=$(basename $file)\n    sha256sum \"$filepath\" > \"$file.sha256\"\n    sha512sum \"$filepath\" > \"$file.sha512\"\n  done\n  cd -\n}\n\nfunction build::common::upload_artifacts() {\n  local -r artifactspath=$1\n  local -r artifactsbucket=$2\n  local -r projectpath=$3\n  local -r buildidentifier=$4\n  local -r githash=$5\n  local -r latestpath=$6\n\n  echo \"$githash\" >> \"$artifactspath\"/githash\n\n  # Upload artifacts to s3\n  # 1. To proper path on s3 with buildId-githash\n  # 2. Latest path to indicate the latest build, with --delete option to delete stale files in the dest path\n  aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$buildidentifier\"-\"$githash\"/artifacts --acl public-read\n  aws s3 sync \"$artifactspath\" \"$artifactsbucket\"/\"$projectpath\"/\"$latestpath\" --delete --acl public-read\n}\n\nfunction build::gather_licenses() {\n  # force 1.18 since thats the version used to install go-licenses in builder-base\n  build::common::use_go_version 1.18\n  if ! command -v go-licenses &> /dev/null\n  then\n    echo \" go-licenses not found.  If you need license or attribtuion file handling\"\n    echo \" please refer to the doc in docs/development/attribution-files.md\"\n    exit\n  fi\n\n  local -r outputdir=$1\n  local -r patterns=$2\n\n\n  # Force deps to only be pulled form vendor directories\n  # this is important in a couple cases where license files\n  # have to be manually created\n  export GOFLAGS=-mod=vendor\n  # force platform to be linux to ensure all deps are picked up\n  export GOOS=linux\n  export GOARCH=amd64\n\n  mkdir -p \"${outputdir}/attribution\"\n  # attribution file generated uses the output go-deps and go-license to gather the neccessary\n  # data about each dependency to generate the amazon approved attribution.txt files\n  # go-deps is needed for module versions\n  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns\n  go list -deps=true -json ./... | jq -s ''  > \"${outputdir}/attribution/go-deps.json\"\n\n  go-licenses save --force $patterns --save_path=\"${outputdir}/LICENSES\"\n\n  # go-licenses can be a bit noisy with its output and lot of it can be confusing\n  # the following messags are safe to ignore since we do not need the license url for our process\n  NOISY_MESSAGES=\"cannot determine URL for|Error discovering URL|unsupported package host\"\n  go-licenses csv $patterns > \"${outputdir}/attribution/go-license.csv\" 2>  >(grep -vE \"$NOISY_MESSAGES\" >&2)\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -q \"^vendor\\/golang.org\\/x\"; then\n      echo \" go-licenses created a file with a std golang package (golang.org/x/*)\"\n      echo \" prefixed with vendor/.  This most likely will result in an error\"\n      echo \" when generating the attribution file and is probably due to\"\n      echo \" to a version mismatch between the current version of go \"\n      echo \" and the version of go that was used to build go-licenses\"\n      exit 1\n  fi\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n  fi\n\n\n  # go-license is pretty eager to copy src for certain license types\n  # when it does, it applies strange permissions to the copied files\n  # which makes deleting them later awkward\n  # this behavior may change in the future with the following PR\n  # https://github.com/google/go-licenses/pull/28\n  chmod -R 777 \"${outputdir}/LICENSES\"\n\n  # most of the packages show up the go-license.csv file as the module name\n  # from the go.mod file, storing that away since the source dirs usually get deleted\n  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')\n  echo $MODULE_NAME > ${outputdir}/attribution/root-module.txt\n}\n\nfunction build::generate_attribution(){\n  local -r golang_verson=$1\n  local -r output_directory=${2:-\"_output\"}\n  local -r attribution_file=${3:-\"ATTRIBUTION.txt\"}\n\n  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)\n  local -r go_path=$(build::common::get_go_path $golang_verson)\n  local -r golang_version_tag=$($go_path/go version | grep -o \"go[0-9].* \")\n\n  if cat \"${output_directory}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  generate-attribution $root_module_name \"./\" $golang_version_tag $output_directory\n  cp -f \"${output_directory}/attribution/ATTRIBUTION.txt\" $attribution_file\n}\n\nfunction build::common::remove_go_path() {\n  # This is the path where the specific go binary versions reside in our builder-base image\n  export PATH=$(echo \"$PATH\" | sed -e \"s/^\\/go\\/go[0-9\\.]*\\/bin://\")\n\n  # This is the path that will most likely be correct if running locally\n  local -r quoted_go_path=$(build::common::re_quote $GOPATH)\n  export PATH=$(echo \"$PATH\" | sed -e \"s/^$quoted_go_path\\/go[0-9\\.]*\\/bin://\")\n}\n\nfunction build::common::get_go_path() {\n  local -r version=$1\n\n  # This is the path where the specific go binary versions reside in our builder-base image\n  local -r gorootbinarypath=\"/go/go${version}/bin\"\n  # This is the path that will most likely be correct if running locally\n  local -r gopathbinarypath=\"$GOPATH/go${version}/bin\"\n  if [ -d \"$gorootbinarypath\" ]; then\n    echo $gorootbinarypath\n  elif [ -d \"$gopathbinarypath\" ]; then\n    echo $gopathbinarypath\n  else\n    # not in builder-base, probably running in dev environment\n    # return default go installation\n    local -r which_go=$(which go)\n    echo \"$(dirname $which_go)\"\n  fi\n}\n\nfunction build::common::use_go_version() {\n  local -r version=$1\n\n  local -r gobinarypath=$(build::common::get_go_path $version)\n  echo \"Adding $gobinarypath to PATH\"\n  # Adding to the beginning of PATH to allow for builds on specific version if it exists\n  export PATH=${gobinarypath}:$PATH\n}\n\nfunction build::common::re_quote() {\n    local -r to_escape=$1\n    sed 's/[][()\\.^$\\/?*+]/\\\\&/g' <<< \"$to_escape\"\n}\n", "num_lines": 212}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nGIT_REPO_ROOT=$(git rev-parse --show-toplevel)\nBUILD_DIR=\"${GIT_REPO_ROOT}/build\"\nTOOLS_DIR=\"${BUILD_DIR}/tools\"\nSTABLE=\"${GIT_REPO_ROOT}/stable\"\nexport PATH=\"${TOOLS_DIR}:${PATH}\"\n\nRELEASE_NOTES=\"${BUILD_DIR}/release-notes.md\"\ntouch \"${RELEASE_NOTES}\"\n\nfunction get_chart_version() {\n    chart=\"$(basename ${1})\"\n    grep 'version: [0-9]\\+\\.[0-9]\\+\\.[0-9]\\+' \"${GIT_REPO_ROOT}/stable/${chart}/Chart.yaml\" | cut -d':' -f2 | tr -d '[:space:]'\n}\n\nfunction get_app_version() {\n    chart=\"$(basename ${1})\"\n    grep 'appVersion:[ ]*v\\?[0-9]\\+\\.[0-9]\\+\\.[0-9]\\+' \"${GIT_REPO_ROOT}/stable/${chart}/Chart.yaml\" | cut -d':' -f2 | tr -d '[:space:]'\n}\n\n>&2 git fetch --all --tags\n\nif $(git describe HEAD --tags | grep -Eq \"^v[0-9]+(\\.[0-9]+)*(-[a-z0-9]+)?$\"); then\n    LAST_RELEASE_HASH=$(git rev-list --tags --max-count=1 --skip=1 --no-walk)\nelse \n    TAG=$(git describe HEAD --tags | grep -Eo \"^v[0-9]+(\\.[0-9]+)*\")\n    LAST_RELEASE_HASH=$(git rev-list -1 $TAG)\nfi\nLAST_RELEASE_TAG=$(git describe $LAST_RELEASE_HASH --tags)\n\nCHANGED_CHARTS=()\n\ncd ${STABLE}\necho \"## Charts\" | tee \"${RELEASE_NOTES}\"\nfor chart in */; do\n    chart=\"$(basename $chart)\"\n    LAST_COMMIT_HASH=$(git --no-pager log --pretty=tformat:\"%H\" -- \"${chart}\" | awk 'FNR <= 1')\n    ## If LAST_RELEASE_HASH does not include the chart, then it's a new chart so we'll add it to the notes\n    if [[ -z $(git ls-tree -d $LAST_RELEASE_HASH \"${chart}\") ]]; then\n        echo \"- ${chart} (chart $(get_chart_version ${chart}), image $(get_app_version ${chart}))\"  | tee -a \"${RELEASE_NOTES}\"\n        CHANGED_CHARTS+=(\"${chart}\")\n        continue\n    fi\n    ## If LAST_RELEASE_HASH is NOT an ancestor of LAST_COMMIT_HASH then it has not been modified \n    if [[ ! -z $LAST_COMMIT_HASH && -z $(git rev-list $LAST_COMMIT_HASH | grep $LAST_RELEASE_HASH) || $LAST_COMMIT_HASH == $LAST_RELEASE_HASH ]]; then\n        continue\n    fi\n    ## The chart was modified since the last release\n    echo \"- ${chart} (chart $(get_chart_version ${chart}), image $(get_app_version ${chart}))\"  | tee -a \"${RELEASE_NOTES}\"\n    CHANGED_CHARTS+=(\"${chart}\")\ndone\n\necho \"## Changes\"  | tee -a \"${RELEASE_NOTES}\"\nfor chart in \"${CHANGED_CHARTS[@]}\"; do\n    echo \"- [${chart}]\" | tee -a \"${RELEASE_NOTES}\"\n    for change in $(git rev-list $LAST_RELEASE_HASH..HEAD ${chart}); do\n        one_line_msg=$(git --no-pager log --pretty='%s (thanks to %an)'  \"${change}\" -n1 |  sed 's/^\\[.*\\]//' | xargs)\n        echo \"  - ${one_line_msg}\" | tee -a \"${RELEASE_NOTES}\"\n    done\ndone\n\n>&2 echo -e \"\\n\\nRelease notes file: ${RELEASE_NOTES}\"\n", "num_lines": 65}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nPLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')\nARCH=$([[ $(uname -m) = \"x86_64\" ]] && echo 'amd64' || echo 'arm64')\nGIT_REPO_ROOT=$(git rev-parse --show-toplevel)\nBUILD_DIR=\"${GIT_REPO_ROOT}/build\"\nTMP_DIR=\"${BUILD_DIR}/tmp\"\nTOOLS_DIR=\"${BUILD_DIR}/tools\"\nmkdir -p \"${TOOLS_DIR}\"\nexport PATH=\"${TOOLS_DIR}:${PATH}\"\n\nHELMV2_VERSION=\"v2.17.0\"\nHELMV3_VERSION=\"v3.6.3\"\nKUBECTL_VERSION=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)\nKIND_VERSION=v0.11.1\nBATS_VERSION=1.1.0\n\n## Install kubectl\ncurl -sSL \"https://storage.googleapis.com/kubernetes-release/release/${KUBECTL_VERSION}/bin/${PLATFORM}/${ARCH}/kubectl\" -o \"${TOOLS_DIR}/kubectl\"\nchmod +x \"${TOOLS_DIR}/kubectl\"\n\n## Install kubeval\nmkdir -p \"${TMP_DIR}/kubeval\"\ncurl -sSL https://github.com/instrumenta/kubeval/releases/latest/download/kubeval-${PLATFORM}-${ARCH}.tar.gz | tar xz -C \"${TMP_DIR}/kubeval\"\nmv \"${TMP_DIR}/kubeval/kubeval\" \"${TOOLS_DIR}/kubeval\"\n\n## Install helm v2\nmkdir -p \"${TMP_DIR}/helmv2\"\ncurl -sSL  https://get.helm.sh/helm-${HELMV2_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C \"${TMP_DIR}/helmv2\"\nmv \"${TMP_DIR}/helmv2/${PLATFORM}-${ARCH}/helm\" \"${TOOLS_DIR}/helmv2\"\nrm -rf \"${PLATFORM}-${ARCH}\"\n\n## Install helm v3\nmkdir -p \"${TMP_DIR}/helmv3\"\ncurl -sSL https://get.helm.sh/helm-${HELMV3_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C \"${TMP_DIR}/helmv3\"\nmv \"${TMP_DIR}/helmv3/${PLATFORM}-${ARCH}/helm\" \"${TOOLS_DIR}/helmv3\"\nrm -rf \"${PLATFORM}-${ARCH}\"\n\n## Install Bats\ncurl -sSL https://github.com/bats-core/bats-core/archive/v${BATS_VERSION}.tar.gz | tar xz -C \"${TOOLS_DIR}\"\nln -s ${TOOLS_DIR}/bats-core-${BATS_VERSION}/bin/bats ${TOOLS_DIR}/bats\n\n## Initialize helm\n\nhelmv2 init --stable-repo-url https://charts.helm.sh/stable --client-only --kubeconfig=\"${BUILD_DIR}/.kube/kubeconfig\"\n\n\n## Install kind\ncurl -sSL \"https://github.com/kubernetes-sigs/kind/releases/download/${KIND_VERSION}/kind-${PLATFORM}-${ARCH}\" -o \"${TOOLS_DIR}/kind\"\nchmod +x \"${TOOLS_DIR}/kind\"\n\nrm -rf ${TMP_DIR}\n", "num_lines": 54}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nGIT_REPO_ROOT=$(git rev-parse --show-toplevel)\nBUILD_DIR=\"${GIT_REPO_ROOT}/build\"\nTOOLS_DIR=\"${BUILD_DIR}/tools\"\nSTABLE=\"${GIT_REPO_ROOT}/stable\"\nexport PATH=\"${TOOLS_DIR}:${PATH}\"\n\nPACKAGE_DIR=\"${GIT_REPO_ROOT}/build\"\nmkdir -p \"${PACKAGE_DIR}\"\n\nhelmv3 package \"${STABLE}/\"* --destination \"${PACKAGE_DIR}/stable\" --dependency-update\n", "num_lines": 14}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nGIT_REPO_ROOT=$(git rev-parse --show-toplevel)\nBUILD_DIR=\"${GIT_REPO_ROOT}/build\"\nTOOLS_DIR=\"${BUILD_DIR}/tools\"\nSTABLE=\"${GIT_REPO_ROOT}/stable\"\nPACKAGE_DIR=\"${GIT_REPO_ROOT}/build\"\nexport PATH=\"${TOOLS_DIR}:${PATH}\"\nVERSION=\"$(git describe --tags --always)\"\n\nif echo \"${VERSION}\" | grep -Eq \"^v[0-9]+(\\.[0-9]+){2}$\"; then\n    git fetch --all\n    git config user.email eks-bot@users.noreply.github.com\n    git config user.name eks-bot\n    git remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPO}\n    git config pull.rebase false\n    git checkout gh-pages\n    mv -n $PACKAGE_DIR/stable/*.tgz .\n    helmv3 repo index . --url https://aws.github.io/eks-charts\n    git add .\n    git commit -m \"Publish stable charts ${VERSION}\"\n    git push origin gh-pages\n    echo \"\u00e2\u0153\u2026 Published charts\"\nelse\n    echo \"Not a valid semver release tag! Skip charts publish\"\n    exit 1\nfi\n\n", "num_lines": 30}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ncheck_kube_connection() {\n\n\tkube_err=$(kubectl cluster-info 2>&1 >/dev/null)\n    if [[ -z $kube_err ]]; then\n        echo \"kubectl context check: PASSED!\"\n        return 0\n    else\n        echo \"kubectl context check: FAILED -- context or permissions issue for kubectl\"\n        echo $kube_err\n        return 1\n    fi\n\n}\n\ncheck_kube_installation() {\n\n    kube_err=$(kubectl version --client 2>&1 >/dev/null)\n    if [[ -z $kube_err ]]; then\n        echo \"kubectl installation check: PASSED!\"\n        return 0\n    else\n        echo \"kubectl installation check: FAILED -- kubectl not installed\"\n        return 1\n    fi\n\n}\n\ncheck_jq_installation() {\n\n    jq_err=$(jq --version 2>&1 >/dev/null)\n    if [[ -z $jq_err ]]; then\n        echo \"jq installation check: PASSED!\"\n        return 0\n    else\n        echo \"jq installation check: FAILED -- jq not installed\"\n        return 1\n    fi\n\n}\n\ncheck_old_crds() {\n\n    vs=$(kubectl get crd virtualservices.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n    vn=$(kubectl get crd virtualnodes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n    ms=$(kubectl get crd meshes.appmesh.k8s.aws --ignore-not-found -o json | jq -r '.spec.versions[]? | select(.? | .name == \"v1beta1\")')\n\n    if [[ -z $vs && -z $vn && -z $ms  ]]; then\n        echo \"App Mesh CRD check: PASSED!\"\n        return 0\n    else\n       echo \"App Mesh CRD check: FAILED -- v1beta1 CRDs are still installed\"\n       return 1\n    fi\n\n}\n\ncheck_controller_version() {\n    currentver=$(kubectl get deployment -n appmesh-system appmesh-controller --ignore-not-found -o json | jq -r \".spec.template.spec.containers[].image\" | cut -f2 -d ':')\n    requiredver=\"v1.0.0\"\n\n    if [[ \"$(printf '%s\\n' \"$requiredver\" \"$currentver\" | sort -V | head -n1)\" = \"$requiredver\" || -z \"$currentver\" ]]; then\n        echo \"Controller version check: PASSED!\"\n        return 0\n    else\n        echo \"Controller version check: FAILED -- old appmesh-controller ($currentver) is still running\"\n        return 1\n    \n    fi\n}\n\ncheck_injector() {\n    status=0\n    for ns in \"appmesh-inject\" \"appmesh-system\"; do\n\n        injector=$(kubectl get deployment -n ${ns} appmesh-inject --ignore-not-found -o json | jq -r .kind)\n\n        if [ -z $injector ]; then\n            echo \"Injector check for namespace ${ns}: PASSED!\"\n        else\n           echo \"Injector check: FAILED -- appmesh-inject is still running in namespace ${ns}\"\n           return 1\n        fi\n\n    done\n    return 0\n}\n\nmain() {\n\n    exitcode=0\n    check_kube_installation || exitcode=1\n    check_jq_installation || exitcode=1\n    check_kube_connection || exitcode=1\n    if [ ${exitcode} = 0 ]; then\n        check_old_crds || exitcode=1\n        check_controller_version || exitcode=1\n        check_injector || exitcode=1\n    fi\n\n    if [ ${exitcode} = 0 ]; then\n        echo -e \"\\nYour cluster is ready for upgrade. Please proceed to the installation instructions\"\n    else\n        echo -e \"\\nYour cluster is NOT ready for upgrade to v1.0.0. Please install/uninstall all the identified items before proceeding\"\n    fi\n\n}\n\nmain", "num_lines": 110}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Run e2e tests\n\nset -o errexit\n\nexport REPO_ROOT=$(git rev-parse --show-toplevel)\nexport PATH=\"$REPO_ROOT/build/tools:$PATH\"\n\ncd \"${REPO_ROOT}/test/e2e/\"\nbats -t .\n", "num_lines": 12}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Helm charts testing helpers\n\nset -o errexit\n\nexport REPO_ROOT=$(git rev-parse --show-toplevel)\n\nfunction infof() {\n    echo -e \"\\e[32m${1}\\e[0m\" >&3\n}\n\nfunction errorf() {\n    echo -e \"\\e[31m${1}\\e[0m\" >&3\n    exit 1\n}\n\nfunction installChart() {\n  chartName=$(basename $1)\n  testValues=\"$1/ci/values.yaml\"\n\n  infof \"Installing chart $chartName\"\n  if test -f \"$testValues\"; then\n    helm upgrade -i $chartName $1 --namespace $2 -f $testValues\n  else\n    helm upgrade -i $chartName $1 --namespace $2\n  fi\n  infof \"\u00e2\u0153\u201d $chartName chart install test passed\"\n}\n\nfunction waitForDeployment() {\n  chartName=$(basename $1)\n  infof \"Waiting for deployment $chartName\"\n  retries=10\n  count=0\n  ok=false\n  until $ok; do\n    kubectl -n $2 get deployment/$chartName && ok=true || ok=false\n    sleep 6\n    count=$(($count + 1))\n    if [[ $count -eq $retries ]]; then\n      errorf \"No more retries left\"\n    fi\n  done\n\n  kubectl -n $2 rollout status deployment/$chartName --timeout=1m >&3\n  infof \"\u00e2\u0153\u201d deployment/$chartName test passed\"\n}\n\nfunction waitForService() {\n  chartName=$(basename $1)\n  infof \"Waiting for service $chartName\"\n  retries=10\n  count=0\n  ok=false\n  until $ok; do\n    kubectl -n $2 get svc/$chartName && ok=true || ok=false\n    sleep 6\n    count=$(($count + 1))\n    if [[ $count -eq $retries ]]; then\n      errorf \"No more retries left\"\n    fi\n  done\n    infof \"\u00e2\u0153\u201d service/$chartName test passed\"\n}\n", "num_lines": 66}
{"repo_name": "eks-charts", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Create Kubernetes cluster with Kind\n\nset -o errexit\n\nREPO_ROOT=$(git rev-parse --show-toplevel)\nTOOLS_DIR=\"$REPO_ROOT/build/tools\"\nexport PATH=\"$TOOLS_DIR:$PATH\"\nHELM_MODE=\"${HELM_MODE:-v2}\"\n\nkind create cluster --wait 5m\n\nfunction installHelm() {\n\n  if [[ \"${1}\" == \"v2\" ]]; then\n    kubectl --namespace kube-system create sa tiller\n\n    kubectl create clusterrolebinding tiller-cluster-rule \\\n      --clusterrole=cluster-admin --serviceaccount=kube-system:tiller\n\n    cp -f $TOOLS_DIR/helmv2 $TOOLS_DIR/helm\n\n    helm init --stable-repo-url https://charts.helm.sh/stable --service-account tiller --upgrade --wait\n  else\n    cp -f $TOOLS_DIR/helmv3 $TOOLS_DIR/helm\n  fi\n}\n\nexport KUBECONFIG=\"$(kind get kubeconfig > $REPO_ROOT/build/kind-kubeconfig)\"\n\ninstallHelm $HELM_MODE\n\nkubectl get pods --all-namespaces\n", "num_lines": 35}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBASE_DIRECTORY=\"${1?Specify first argument - Base directory of build-tooling repo}\"\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\n# Iterating over orgs under projects folder\nfor org_path in projects/*; do\n    org=$(basename \"$org_path\")\n    for repo_path in projects/$org/*; do\n        repo=$(basename \"$repo_path\")\n        # couple odd ball non-builds in this repo\n        if [[ -f $repo_path/DO_NOT_BUILD ]]; then\n            continue\n        fi\n        echo -n \"${org}_${repo} \"\n    done\ndone\n\necho\n", "num_lines": 39}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBUILD_LIB_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/\" && pwd -P)\"\n\nCMD=\"buildctl\"\nif [ -f \"/buildkit.sh\" ] && ! buildctl debug workers >/dev/null 2>&1; then\n    # on the builder base this helper file exists to run buildkitd\n    # in prow buildkitd is run as a seperate container so it will be running already\n    # in codebuild its run directly on the instance so we want to use this helper\n    CMD=\"/buildkit.sh\"\n\nfi\n# From time to time we see random failures when creating/pushing images that fix on reruning the job\n# this is an attempt to avoid failing key jobs, like the release job, with a flaky failure\n# If running in builder base, most likely we are running in prow/codebuild, us retry logic\n# if not in builder base, probably running locally so skip the retry\nif [ -f \"/buildkit.sh\" ]; then\n    for i in $(seq 1 5); do\n        [ $i -gt 1 ] && sleep 15\n        $CMD \"$@\" && s=0 && break || s=$?\n    done\n\n    # space is limited on presubmit nodes, after each image build clear the build cache\n    if [ \"${JOB_TYPE:-}\" == \"presubmit\" ] && [ \"${PRUNE_BUILDCTL:-false}\" == \"true\" ]; then\n        $CMD prune --all\n    fi\n\n    (exit $s)\nelse\n    # skip retry when running locally\n    log_file=$(mktemp)\n    trap \"rm -f $log_file\" EXIT\n    if ! $CMD \"$@\" 2>&1 | tee $log_file; then        \n        if grep -q \"blobs/uploads/\\\": EOF\" $log_file ; then\n            echo \"******************************************************\"\n            echo \"Ensure container registry and repository exists!!\"\n            echo \"Try running make create-ecr-repos to create ecr repositories in your aws account.\"\n            echo \"******************************************************\"\n        fi\n        exit 1\n    fi\nfi\n", "num_lines": 60}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfunction buildkit_ready() {\n  for i in {1..24}\n  do\n    if [ ! -S \"/run/buildkit/buildkitd.sock\" ]\n    then\n      echo \"Buildkit daemon is not running. Retrying.\"\n      sleep 5s\n    else\n      exit 0\n    fi\n  done\n  echo \"Buildkit daemon is not available\"\n  exit 1\n}\n\nbuildkit_ready", "num_lines": 31}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nif [ -n \"${OUTPUT_DEBUG_LOG:-}\" ]; then\n    set -x\nfi\n\n\nfunction build::common::ensure_tar() {\n  if [[ -n \"${TAR:-}\" ]]; then\n    return\n  fi\n\n  # Find gnu tar if it is available, bomb out if not.\n  TAR=tar\n  if which gtar &>/dev/null; then\n      TAR=gtar\n  elif which gnutar &>/dev/null; then\n      TAR=gnutar\n  fi\n  if ! \"${TAR}\" --version | grep -q GNU; then\n    echo \"  !!! Cannot find GNU tar. Build on Linux or install GNU tar\"\n    echo \"      on Mac OS X (brew install gnu-tar).\"\n    return 1\n  fi\n}\n\n# Build a release tarball.  $1 is the output tar name.  $2 is the base directory\n# of the files to be packaged.  This assumes that ${2}/kubernetes is what is\n# being packaged.\nfunction build::common::create_tarball() {\n  build::common::ensure_tar\n\n  local -r tarfile=$1\n  local -r stagingdir=$2\n  local -r repository=$3\n\n  build::common::echo_and_run \"${TAR}\" czf \"${tarfile}\" -C \"${stagingdir}\" $repository --owner=0 --group=0\n}\n\n# Generate shasum of tarballs. $1 is the directory of the tarballs.\nfunction build::common::generate_shasum() {\n\n  local -r tarpath=$1\n\n  echo \"Writing artifact hashes to shasum files...\"\n\n  if [ ! -d \"$tarpath\" ]; then\n    echo \"  Unable to find tar directory $tarpath\"\n    exit 1\n  fi\n\n  cd $tarpath\n  for file in $(find . -name '*.tar.gz'); do\n    filepath=$(basename $file)\n    sha256sum \"$filepath\" > \"$file.sha256\"\n    sha512sum \"$filepath\" > \"$file.sha512\"\n  done\n  cd -\n}\n\n\nfunction build::gather_licenses() {\n  local -r outputdir=$1\n  local -r patterns=$2\n  local -r golang_version=$3\n\n  # Force deps to only be pulled form vendor directories\n  # this is important in a couple cases where license files\n  # have to be manually created\n  export GOFLAGS=-mod=vendor\n  # force platform to be linux to ensure all deps are picked up\n  export GOOS=linux \n  export GOARCH=amd64 \n\n  # the version of go used here must be the version go-licenses was installed with corresponding go versions\n  build::common::use_go_version $golang_version\n\n  if ! command -v go-licenses &> /dev/null\n  then\n    echo \" go-licenses not found.  If you need license or attribution file handling\"\n    echo \" please refer to the doc in docs/development/attribution-files.md\"\n    exit\n  fi\n\n  mkdir -p \"${outputdir}/attribution\"\n  # attribution file generated uses the output go-deps and go-license to gather the necessary\n  # data about each dependency to generate the amazon approved attribution.txt files\n  # go-deps is needed for module versions\n  # go-licenses are all the dependencies found from the module(s) that were passed in via patterns\n  build::common::echo_and_run go list -deps=true -json ./... | jq -s ''  > \"${outputdir}/attribution/go-deps.json\"\n\n  # go-licenses can be a bit noisy with its output and lot of it can be confusing \n  # the following messages are safe to ignore since we do not need the license url for our process\n  NOISY_MESSAGES=\"cannot determine URL for|Error discovering license URL|unsupported package host|contains non-Go code|has empty version|vendor.*\\.s$\"\n\n  build::common::echo_and_run go-licenses save --force $patterns --save_path \"${outputdir}/LICENSES\" 2> >(grep -vE \"$NOISY_MESSAGES\")\n  \n  build::common::echo_and_run go-licenses csv $patterns 2> >(grep -vE \"$NOISY_MESSAGES\") > \"${outputdir}/attribution/go-license.csv\"  \n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -q \"^vendor\\/golang.org\\/x\"; then\n      echo \" go-licenses created a file with a std golang package (golang.org/x/*)\"\n      echo \" prefixed with vendor/.  This most likely will result in an error\"\n      echo \" when generating the attribution file and is probably due to\"\n      echo \" to a version mismatch between the current version of go \"\n      echo \" and the version of go that was used to build go-licenses\"\n      exit 1\n  fi\n\n  if cat \"${outputdir}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  # go-license is pretty eager to copy src for certain license types\n  # when it does, it applies strange permissions to the copied files\n  # which makes deleting them later awkward\n  # this behavior may change in the future with the following PR\n  # https://github.com/google/go-licenses/pull/28\n  # We can delete these additional files because we are running go mod vendor\n  # prior to this call so we know the source is the same as upstream\n  # go-licenses is copying this code because it doesnt know if its be modified or not\n  chmod -R 777 \"${outputdir}/LICENSES\"\n  find \"${outputdir}/LICENSES\" -type f \\( -name '*.yml' -o -name '*.go' -o -name '*.mod' -o -name '*.sum' -o -name '*gitignore' \\) -delete\n\n  # most of the packages show up the go-license.csv file as the module name\n  # from the go.mod file, storing that away since the source dirs usually get deleted\n  MODULE_NAME=$(go mod edit -json | jq -r '.Module.Path')\n  if [ ! -f ${outputdir}/attribution/root-module.txt ]; then\n  \techo $MODULE_NAME > ${outputdir}/attribution/root-module.txt\n  fi\n}\n\nfunction build::non-golang::gather_licenses(){\n  local -r project=\"$1\"\n  local -r git_tag=\"$2\"\n  local -r output_dir=\"$3\"\n  project_org=\"$(cut -d '/' -f1 <<< ${project})\"\n  project_name=\"$(cut -d '/' -f2 <<< ${project})\"\n  git clone https://github.com/${project_org}/${project_name}\n  cd $project_name\n  git checkout $git_tag\n  cd ..\n  build::non-golang::copy_licenses $project_name $output_dir/LICENSES/github.com/${project_org}/${project_name}\n  rm -rf $project_name\n}\n\nfunction build::non-golang::copy_licenses(){\n  local -r source_dir=\"$1\"\n  local -r destination_dir=\"$2\"\n  (cd $source_dir; find . \\( -name \"*COPYING*\" -o -name \"*COPYRIGHT*\" -o -name \"*LICEN[C|S]E*\" -o -name \"*NOTICE*\" \\)) |\n  while read file\n  do\n    license_dest=$destination_dir/$(dirname $file)\n    mkdir -p $license_dest\n    cp -r \"${source_dir}/${file}\" $license_dest/$(basename $file)\n  done\n}\n\nfunction build::generate_attribution(){\n  local -r project_root=$1\n  local -r golang_version=$2\n  local -r output_directory=${3:-\"${project_root}/_output\"}\n  local -r attribution_file=${4:-\"${project_root}/ATTRIBUTION.txt\"}\n\n  local -r root_module_name=$(cat ${output_directory}/attribution/root-module.txt)\n  local -r go_path=$(build::common::get_go_path $golang_version)\n  local -r golang_version_tag=$($go_path/go version | grep -o \"go[0-9].* \")\n\n  if cat \"${output_directory}/attribution/go-license.csv\" | grep -e \",LGPL-\" -e \",GPL-\"; then\n    echo \" one of the dependencies is licensed as LGPL or GPL\"\n    echo \" which is prohibited at Amazon\"\n    echo \" please look into removing the dependency\"\n    exit 1\n  fi\n\n  build::common::echo_and_run generate-attribution $root_module_name $project_root $golang_version_tag $output_directory \n  cp -f \"${output_directory}/attribution/ATTRIBUTION.txt\" $attribution_file\n}\n\nfunction build::common::get_go_path() {\n  local -r version=$1\n\n  # This is the path where the specific go binary versions reside in our builder-base image\n  local -r gorootbinarypath=\"/go/go${version}/bin\"\n  # This is the path that will most likely be correct if running locally\n  local -r gopathbinarypath=\"$GOPATH/go${version}/bin\"\n  if [ -d \"$gorootbinarypath\" ]; then\n    echo $gorootbinarypath\n  elif [ -d \"$gopathbinarypath\" ]; then\n    echo $gopathbinarypath\n  else\n    # not in builder-base, probably running in dev environment\n    # return default go installation\n    local -r which_go=$(which go)\n    echo \"$(dirname $which_go)\"\n  fi\n}\n\nfunction build::common::use_go_version() {\n  local -r version=$1\n\n  if (( \"${version#*.}\" < 16 )); then\n    echo \"Building with GO version $version is no longer supported!  Please update the build to use a newer version.\"\n    exit 1\n  fi\n\n  local -r gobinarypath=$(build::common::get_go_path $version)\n  echo \"Adding $gobinarypath to PATH\"\n  # Adding to the beginning of PATH to allow for builds on specific version if it exists\n  export PATH=${gobinarypath}:$PATH\n  export GOCACHE=$(go env GOCACHE)/$version\n}\n\n# Use a seperate build cache for each project/version to ensure there are no\n# shared bits which can mess up the final checksum calculation\n# this is mostly needed for create checksums locally since in the builds\n# different versions of the same project are not built in the same container\nfunction build::common::set_go_cache() {\n  local -r project=$1\n  local -r git_tag=$2\n  export GOCACHE=$(go env GOCACHE)/$project/$git_tag\n}\n\nfunction build::common::re_quote() {\n    local -r to_escape=$1\n    sed 's/[][()\\.^$\\/?*+]/\\\\&/g' <<< \"$to_escape\"\n}\nfunction build::common::wait_for_tag() {\n  local -r tag=$1\n  sleep_interval=20\n  for i in {1..60}; do\n    echo \"Checking for tag ${tag}...\"\n    git rev-parse --verify --quiet \"${tag}\" && echo \"Tag ${tag} exists!\" && break\n    git fetch --tags > /dev/null 2>&1\n    echo \"Tag ${tag} does not exist!\"\n    echo \"Waiting for tag ${tag}...\"\n    sleep $sleep_interval\n    if [ \"$i\" = \"60\" ]; then\n      exit 1\n    fi\n  done\n}\n\nfunction build::common::wait_for_tarball() {\n  local -r tarball_url=$1\n  sleep_interval=20\n  for i in {1..60}; do\n    echo \"Checking for URL ${tarball_url}...\"\n    local -r http_code=$(curl -I -L -s -o /dev/null -w \"%{http_code}\" $tarball_url)\n    if [[ \"$http_code\" == \"200\" ]]; then \n      echo \"Tarball exists!\" && break\n    fi\n    echo \"Tarball does not exist!\"\n    echo \"Waiting for tarball to be uploaded to ${tarball_url}\"\n    sleep $sleep_interval\n    if [ \"$i\" = \"60\" ]; then\n      exit 1\n    fi\n  done\n}\n\nfunction build::common::get_clone_url() {\n  local -r org=$1\n  local -r repo=$2\n  local -r aws_region=$3\n\n  echo \"https://github.com/${org}/${repo}.git\"\n}\n\nfunction retry() {\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        >&2 echo \"Command failed. Attempt $n/$max:\"\n        sleep $delay;\n      else\n        fail \"The command has failed after $n attempts.\"\n      fi\n    }\n  done\n}\n\nfunction build::docker::retry_pull() {\n  retry docker pull \"$@\"\n}\n\nfunction build::common::echo_and_run() {\n  >&2 echo \"($(pwd)) \\$ $*\"\n  \"$@\"\n}", "num_lines": 310}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nPROJECT_ROOT=\"$1\"\nGOLANG_VERSION=\"$2\"\nOUTPUT_DIR=\"$3\"\nOUTPUT_FILENAME=\"$4\"\nRELEASE_BRANCH=\"${5:-}\"\n\nif [[ -n \"$RELEASE_BRANCH\" ]] && [ -d \"$PROJECT_ROOT/$RELEASE_BRANCH\" ]; then\n\tPROJECT_ROOT=$PROJECT_ROOT/$RELEASE_BRANCH\nfi\n\nbuild::generate_attribution $PROJECT_ROOT $GOLANG_VERSION $OUTPUT_DIR $PROJECT_ROOT/$OUTPUT_FILENAME\n", "num_lines": 34}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nIMAGE_NAME=\"$1\"\nIMAGE=\"$2\"\nLATEST_IMAGE=\"$3\"\nWINDOWS_IMAGE_VERSIONS=\"$4\"\n\necho \"Creating windows manifest for $IMAGE_NAME\"\n\n# this metadate file contains the linux/amd+arm images\nif [ ! -f /tmp/$IMAGE_NAME-metadata.json ]; then\n    echo \"No metadata file for image: /tmp/$IMAGE_NAME-metadata.json!\"\n    exit 1\nfi\n\n# need to remove mediaType from descri since buildx segfaults when it is set\njq -r '.\"containerimage.descriptor\"  | {size, digest}' /tmp/$IMAGE_NAME-metadata.json > /tmp/$IMAGE_NAME-descr-final.json\n\nCREATE_ARGS=\"-f /tmp/$IMAGE_NAME-descr-final.json \"\nVERSIONS=(${WINDOWS_IMAGE_VERSIONS// / })\nfor version in \"${VERSIONS[@]}\"; do\n    if [ ! -f /tmp/$IMAGE_NAME-$version-metadata.json ]; then\n        echo \"No metadata file for image: /tmp/$IMAGE_NAME-$version-metadata.json!\"\n        exit 1\n    fi\n\n    BASE_IMAGE=$(jq -r '.\"containerimage.buildinfo\".attrs.\"build-arg:BASE_IMAGE\"' /tmp/$IMAGE_NAME-$version-metadata.json)\n\n    # need to remove mediaType from descri since buildx segfaults when it is set\n    jq -r '.\"containerimage.descriptor\"  | {size, digest}' /tmp/$IMAGE_NAME-$version-metadata.json > /tmp/$IMAGE_NAME-$version-descr.json\n    build::common::echo_and_run retry docker buildx imagetools inspect --raw $BASE_IMAGE | jq '.manifests[0] | {platform}' | jq add -s - /tmp/$IMAGE_NAME-$version-descr.json > /tmp/$IMAGE_NAME-$version-descr-final.json\n    cat /tmp/$IMAGE_NAME-$version-descr-final.json\n    CREATE_ARGS+=\"-f /tmp/$IMAGE_NAME-$version-descr-final.json \"\ndone\n\n\nbuild::common::echo_and_run retry docker buildx imagetools create --dry-run $CREATE_ARGS -t $IMAGE -t $LATEST_IMAGE > /tmp/$IMAGE_NAME-manfiest-final.json\n\ncat  /tmp/$IMAGE_NAME-manfiest-final.json\n\nif [ \"$(jq '.manifests[].platform.os' /tmp/$IMAGE_NAME-manfiest-final.json |  grep -w -c windows)\" != \"${#VERSIONS[@]}\" ]; then\n    echo \"image manifest does not contain correct number of windows images!\"\n    exit 1\nfi\n\nif [ \"$(jq '.manifests[].platform.os' /tmp/$IMAGE_NAME-manfiest-final.json |  grep -w -c linux)\" != \"2\" ]; then\n    echo \"image manifest does not contain correct number of linux images!\"\n    exit 1\nfi\n\nif [ \"$(jq '.manifests[].platform | select( has(\"os.version\") == true ) | .\"os.version\"' /tmp/$IMAGE_NAME-manfiest-final.json | wc -l | xargs)\" != \"${#VERSIONS[@]}\" ]; then\n    echo \"windows images do not have os.version set!\"\n    exit 1\nfi\n\nbuild::common::echo_and_run retry docker buildx imagetools create $CREATE_ARGS -t $IMAGE -t $LATEST_IMAGE\n\nbuild::common::echo_and_run retry docker buildx imagetools inspect $IMAGE\n\n# Public ecr's tagging appears to have some delay when retagging existing tags, like latest\n# retry the diff to give it time to make sure the latest manifest has been updated to new verion\nfunction validate_latest() {\n    if ! diff <(retry docker buildx imagetools inspect $IMAGE --raw) <(retry docker buildx imagetools inspect $LATEST_IMAGE --raw); then\n        echo \"image manifest and latest manifest do not match!\"\n        return 1\n    fi\n}\n\nretry validate_latest\n\nrm -rf /tmp/$IMAGE_NAME-*.json\n", "num_lines": 92}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nPACKAGE_FILTER=\"$3\"\nREPO_SUBPATH=\"${4:-}\"\nGOLANG_VERSION=\"${5:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\ncd $REPO/$REPO_SUBPATH\nbuild::gather_licenses $OUTPUT_DIR \"$PACKAGE_FILTER\" \"$GOLANG_VERSION\"\n", "num_lines": 31}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nBINARY_TARGET_FILES=\"$2\"\nBINARY_PLATFORMS=\"$3\"\nBINARY_TARGETS=\"$4\"\nREPO=\"$5\"\nHAS_PATCHES=\"$6\"\nLOCAL_IMAGE_TARGETS=\"$7\"\nIMAGE_TARGETS=\"$8\"\nBUILD_TARGETS=\"$9\"\nRELEASE_TARGETS=\"${10}\"\nHAS_S3_ARTIFACTS=\"${11}\"\nHAS_LICENSES=\"${12}\"\nREPO_NO_CLONE=\"${13}\"\nFETCH_BINARIES_TARGETS=\"${14}\"\nHAS_HELM_CHART=\"${15}\"\nIN_DOCKER_TARGETS=\"${16}\"\n\nNL=$'\\n'\nHEADER=\"########### DO NOT EDIT #############################\"\nFOOTER=\"########### END GENERATED ###########################\"\n\nMAKEFILE=$PROJECT_ROOT/Makefile\nHELPFILE=$PROJECT_ROOT/Help.mk\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $MAKEFILE\n# remove trailing newlines\nprintf %s \"$(< $MAKEFILE)\" > $MAKEFILE\n\ntouch $HELPFILE\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $HELPFILE\n# remove trailing newlines\nprintf %s \"$(< $HELPFILE)\" > $HELPFILE\n\n# Generate help items from Common.mk\nEXTRA_HELP=\"$(make help-list --no-print-directory)\"\nBINARY_TARGETS_HELP=\"\"\nCHECKSUMS_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$BINARY_TARGETS\" | xargs)\" ]; then\n    BINARY_TARGETS_HELP+=\"${NL}${NL}##@ Binary Targets\"\n    BINARY_TARGETS_HELP+=\"${NL}binaries: ## Build all binaries: \\`${BINARY_TARGET_FILES}\\` for \\`${BINARY_PLATFORMS}\\`\"\n    TARGETS=(${BINARY_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        BINARY_TARGETS_HELP+=\"${NL}${target}: ## Build \\`${target}\\`\"\n    done\n\n    CHECKSUMS_TARGETS_HELP+=\"${NL}${NL}##@ Checksum Targets\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}checksums: ## Update checksums file based on currently built binaries.\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}validate-checksums: # Validate checksums of currently built binaries against checksums file.\"\n    CHECKSUMS_TARGETS_HELP+=\"${NL}all-checksums: ## Update checksums files for all RELEASE_BRANCHes.\"\nfi\n\nGIT_TARGETS_HELP=\"\"\nif [[ \"$REPO_NO_CLONE\" != \"true\" ]]; then\n    GIT_TARGETS_HELP+=\"${NL}${NL}##@ GIT/Repo Targets\"\n    GIT_TARGETS_HELP+=\"${NL}clone-repo:  ## Clone upstream \\`${REPO}\\`\"\n    GIT_TARGETS_HELP+=\"${NL}checkout-repo: ## Checkout upstream tag based on value in GIT_TAG file\"\nfi\n\nPATCHES_TARGET=\"\"\nif [[ \"$HAS_PATCHES\" == \"true\" ]]; then\n    PATCHES_TARGET+=\"${NL}patch-repo: ## Patch upstream repo with patches in patches directory\"\nfi\n\nIMAGE_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$LOCAL_IMAGE_TARGETS\" | xargs)\" ]; then\n    IMAGE_TARGETS_HELP+=\"${NL}${NL}##@ Image Targets\"\n    IMAGE_TARGETS_HELP+=\"${NL}local-images: ## Builds \\`$(echo ${LOCAL_IMAGE_TARGETS} | xargs)\\` as oci tars for presumbit validation\"\n    IMAGE_TARGETS_HELP+=\"${NL}images: ## Pushes \\`$(echo ${IMAGE_TARGETS} | xargs)\\` to IMAGE_REPO\"\n    \n    ALL_IMAGES=()\n    TARGETS=(${LOCAL_IMAGE_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        ALL_IMAGES+=(\"$target\")\n    done\n    TARGETS=(${IMAGE_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        if [[ ! \" ${ALL_IMAGES[*]} \" =~ \" ${target} \" ]]; then\n            ALL_IMAGES+=(\"$target\")\n        fi\n    done\n    for image in \"${ALL_IMAGES[@]}\"; do\n        IMAGE_TARGETS_HELP+=\"${NL}$image: ## Builds/pushes \\`${image}\\`\"\n    done\n\nfi\n\nARTIFACTS_TARGETS=\"\"\nif [[ \"$HAS_S3_ARTIFACTS\" == \"true\" ]]; then\n    ARTIFACTS_TARGETS+=\"${NL}${NL}##@ Artifact Targets\" \n    ARTIFACTS_TARGETS+=\"${NL}tarballs: ## Create tarballs by calling build/lib/simple_create_tarballs.sh unless SIMPLE_CREATE_TARBALLS=false, then tarballs must be defined in project Makefile\"\n    ARTIFACTS_TARGETS+=\"${NL}s3-artifacts: # Prepare ARTIFACTS_PATH folder structure with tarballs/manifests/other items to be uploaded to s3\"\n    ARTIFACTS_TARGETS+=\"${NL}upload-artifacts: # Upload tarballs and other artifacts from ARTIFACTS_PATH to S3\"\nfi\n\nLICENSES_TARGETS=\"\"\nif [[ \"$HAS_LICENSES\" == \"true\" ]]; then\n    LICENSES_TARGETS+=\"${NL}${NL}##@ License Targets\" \n    LICENSES_TARGETS+=\"${NL}gather-licenses: ## Helper to call \\$(GATHER_LICENSES_TARGETS) which gathers all licenses\"\n    LICENSES_TARGETS+=\"${NL}attribution: ## Generates attribution from licenses gathered during \\`gather-licenses\\`.\"\n    LICENSES_TARGETS+=\"${NL}attribution-pr: ## Generates PR to update attribution files for projects\"\n    LICENSES_TARGETS+=\"${NL}attribution-checksums: ## Update attribution and checksums files.\"\n    LICENSES_TARGETS+=\"${NL}all-attributions: ## Update attribution files for all RELEASE_BRANCHes.\"\n    LICENSES_TARGETS+=\"${NL}all-attributions-checksums: ## Update attribution and checksums files for all RELEASE_BRANCHes.\"\nfi\n\nCLEAN_TARGETS=\"${NL}${NL}##@ Clean Targets\"\nCLEAN_TARGETS+=\"${NL}clean: ## Removes source and _output directory\"\nif [[ \"$REPO_NO_CLONE\" != \"true\" ]]; then\n    CLEAN_TARGETS+=\"${NL}clean-repo: ## Removes source directory\"\nfi\n\nFETCH_BINARY_TARGETS_HELP=\"\"\nif [ ! -z \"$(echo \"$FETCH_BINARIES_TARGETS\" | xargs)\" ]; then\n    FETCH_BINARY_TARGETS_HELP+=\"${NL}${NL}##@ Fetch Binary Targets\"\n    TARGETS=(${FETCH_BINARIES_TARGETS// / })\n    for target in \"${TARGETS[@]}\"; do\n        FETCH_BINARY_TARGETS_HELP+=\"${NL}${target}: ## Fetch \\`${target}\\`\"\n    done\nfi\n\nHELM_TARGETS=\"\"\nif [[ \"$HAS_HELM_CHART\" == \"true\" ]]; then\n    HELM_TARGETS+=\"${NL}${NL}##@ Helm Targets\"\n    HELM_TARGETS+=\"${NL}helm/build: ## Build helm chart\"\n    HELM_TARGETS+=\"${NL}helm/push: ## Build helm chart and push to registry defined in IMAGE_REPO.\"\nfi\n\nTARGETS=(${IN_DOCKER_TARGETS// / })\nDOCKER_TARGETS=\"${NL}${NL}##@ Run in Docker Targets\"\nfor target in \"${TARGETS[@]}\"; do\n    DOCKER_TARGETS+=\"${NL}run-${target}-in-docker: ## Run \\`${target}\\` in docker builder container\"\ndone\n\ncat >> $HELPFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n${GIT_TARGETS_HELP}${PATCHES_TARGET}${BINARY_TARGETS_HELP}${IMAGE_TARGETS_HELP}${HELM_TARGETS}${FETCH_BINARY_TARGETS_HELP}${CHECKSUMS_TARGETS_HELP}${DOCKER_TARGETS}${ARTIFACTS_TARGETS}${LICENSES_TARGETS}${CLEAN_TARGETS}\n${EXTRA_HELP}\n\n##@ Build Targets\nbuild: ## Called via prow presubmit, calls \\`${BUILD_TARGETS//$PROJECT_ROOT\\//\"\"}\\`\nrelease: ## Called via prow postsubmit + release jobs, calls \\`${RELEASE_TARGETS}\\`\n${FOOTER}\nEOF\n\ncat >> $MAKEFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n# Run make help for a formatted help block with all targets\ninclude Help.mk\n${FOOTER}\nEOF\n\n", "num_lines": 181}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nREPO=\"$2\"\nTAG=\"$3\"\nGOLANG_VERSION=\"$4\"\nREPO_SUBPATH=\"${5:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\ncd $REPO/$REPO_SUBPATH\n\nCACHE_KEY=$(echo $PROJECT_ROOT | sed 's/\\(.*\\)\\//\\1-/' | xargs basename)\nbuild::common::use_go_version $GOLANG_VERSION\nbuild::common::set_go_cache $CACHE_KEY $TAG\nbuild::common::echo_and_run go mod vendor\n", "num_lines": 35}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Taken from https://github.com/aws/eks-distro-build-tooling/blob/main/builder-base/install.sh\n# TODO: introduce a shared scripts repo to better share things like this\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nsetupgo() {\n    local -r version=$1\n    go install golang.org/dl/go${version}@latest\n    go${version} download\n    # Removing the patch number as we only care about the minor version of golang\n    local -r majorversion=$(cut -d. -f\"1,2\" <<< $version)\n    mkdir -p ${GOPATH}/go${majorversion}/bin\n    ln -sf ${GOPATH}/bin/go${version} ${GOPATH}/go${majorversion}/bin/go\n    ln -sf ${HOME}/sdk/go${version}/bin/gofmt ${GOPATH}/go${majorversion}/bin/gofmt\n}\n\nsetupgo \"${GOLANG117_VERSION:-1.17.13}\"\nsetupgo \"${GOLANG118_VERSION:-1.18.10}\"\nsetupgo \"${GOLANG119_VERSION:-1.19.10}\"\nsetupgo \"${GOLANG120_VERSION:-1.20.5}\"\n\n# use 1.17 when installing and running go-licenses\n# go-licenses needs to be installed by the same version of go that is being used\n# to generate the deps list during the attribution generation process\nbuild::common::use_go_version \"1.17\"\nGOBIN=${GOPATH}/go1.17/bin go install github.com/google/go-licenses@v1.2.1\n\nbuild::common::use_go_version \"1.18\"\nGOBIN=${GOPATH}/go1.18/bin go install github.com/google/go-licenses@v1.2.1\n\nbuild::common::use_go_version \"1.19\"\nGOBIN=${GOPATH}/go1.19/bin go install github.com/google/go-licenses@v1.2.1\n\nbuild::common::use_go_version \"1.20\"\nGOBIN=${GOPATH}/go1.20/bin go install github.com/google/go-licenses@v1.2.1\n\n# 1.17 is the default so symlink it to /go/bin\nln -sf ${GOPATH}/go1.17/bin/go-licenses ${GOPATH}/bin\n", "num_lines": 59}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nfunction registry_ready() {\n  for i in {1..24}\n  do\n    if ! curl http://$IMAGE_REPO/ > /dev/null 2>&1;\n    then\n      echo \"Local registry at ${IMAGE_REPO} is not running. Retrying.\"\n      sleep 5\n    else\n      exit 0\n    fi\n  done\n  echo \"Local registry at ${IMAGE_REPO} is not available\"\n  exit 1\n}\n\nregistry_ready", "num_lines": 35}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nGIT_TAG=\"$2\"\nPATCHES_DIR=\"${3:-../patches}\"\n\nmkdir -p $PATCHES_DIR\n\ncd $REPO\n\nCOMMIT=$(git rev-parse HEAD)\nLATEST_PATCH_NUMBER=$(ls -f $PATCHES_DIR | cut -d- -f1 | sort | tail -1)\n\nif [[ ! $LATEST_PATCH_NUMBER =~ ^[0-9] ]]; then\n    LATEST_PATCH_NUMBER=1\nfi\n\ngit add go.mod go.sum\n\n# if the upstream project vends their deps, lets update them in the patch\nif [ $(git cat-file -t $GIT_TAG:vendor 2>/dev/null) ]; then\n    git add ./vendor\nfi\n\ngit commit\ngit format-patch --signoff --start-number $((LATEST_PATCH_NUMBER + 1)) -o $PATCHES_DIR $COMMIT --\n\n# Copy into project folder to check in for dependabot\ncp -f go.{mod,sum} $(dirname $PATCHES_DIR)\n", "num_lines": 47}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT=\"$1\"\nTARGET=\"$2\"\nIMAGE_REPO=\"${3:-}\"\nRELEASE_BRANCH=\"${4:-}\"\nARTIFACTS_BUCKET=\"${5:-$ARTIFACTS_BUCKET}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\nsource \"${SCRIPT_ROOT}/common.sh\"\n\necho \"****************************************************************\"\necho \"A docker container with the name eks-d-builder will be launched.\"\necho \"It will be left running to support running consecutive runs.\"\necho \"Run 'make stop-docker-builder' when you are done to stop it.\"\necho \"****************************************************************\"\n\nif ! docker ps -f name=eks-d-builder | grep -w eks-d-builder; then\n\tbuild::docker::retry_pull public.ecr.aws/eks-distro-build-tooling/builder-base:latest\n\n\tNETRC=\"\"\n\tif [ -f $HOME/.netrc ]; then\n\t\tNETRC=\"--mount type=bind,source=$HOME/.netrc,target=/root/.netrc\"\n\tfi\n\n\t# on a linux host, the uid needs to match the host user otherwise\n\t# git will complain about user permissions on the repo, when go\n\t# goes to figure out the vcs information\n\tUSER_ID=\"\"\n\tif [ \"$(uname -s)\" = \"Linux\" ] && [ -n \"${USER:-}\" ]; then\n\t\tUSER_ID=\"-u $(id -u ${USER}):$(id -g ${USER})\"\n\tfi\n\n\tdocker run -d --name eks-d-builder --privileged $NETRC $USER_ID \\\n\t\t--mount type=bind,source=$MAKE_ROOT,target=/eks-distro \\\n\t\t-e GOPROXY=${GOPROXY:-} --entrypoint sleep \\\n\t\tpublic.ecr.aws/eks-distro-build-tooling/builder-base:latest infinity\nfi\n\ndocker exec -e RELEASE_BRANCH=$RELEASE_BRANCH -it eks-d-builder make $TARGET -C /eks-distro/projects/$PROJECT IMAGE_REPO=$IMAGE_REPO ARTIFACTS_BUCKET=$ARTIFACTS_BUCKET", "num_lines": 59}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nTARGET_FILE=\"$2\"\nREPO=\"$3\"\nGOLANG_VERSION=\"$4\"\nBINARY_PLATFORMS=\"$5\"\nSOURCE_PATTERN=\"$6\"\nGOBUILD_COMMAND=\"$7\" \nEXTRA_GOBUILD_FLAGS=\"$8\"\nGO_LDFLAGS=\"$9\"\nCGO_ENABLED=\"${10}\"\nCGO_LDFLAGS=\"${11}\"\nREPO_SUBPATH=\"${12:-}\"\nALL_TARGET_FILES=\"${13:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nfunction build::simple::print_go_env(){\n  for var in \"GOOS\" \"GOARCH\" \"CGO_ENABLED\" \"GOCACHE\" \"GOFLAGS\"; do\n    if [ -n \"${!var:-}\" ]; then\n      echo \"$var: ${!var:-}\"\n    fi\n    if [ \"$var\" = \"CGO_ENABLED\" ] && [ \"${!var:-}\" = \"1\" ]; then\n      for other in \"CGO_LDFLAGS\" \"CGO_CFLAGS\" \"LD_LIBRARY_PATH\" \"PKG_CONFIG_PATH\"; do echo \"$other: ${!other:-}\"; done\n    fi\n  done\n}\n\nfunction build::simple::binaries(){\n  mkdir -p $(dirname $TARGET_FILE)\n  cd \"$PROJECT_ROOT/$REPO/$REPO_SUBPATH\"\n  build::common::use_go_version $GOLANG_VERSION\n  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })\n  for platform in \"${SUPPORTED_PLATFORMS[@]}\"; do\n    OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n    ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n    if [ $CGO_ENABLED = 1 ]; then\n      export CGO_LDFLAGS=\"$CGO_LDFLAGS,-L$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64\"\n      export CGO_CFLAGS=\"-I$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/include\"\n      export LD_LIBRARY_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64:${LD_LIBRARY_PATH-}\n      export PKG_CONFIG_PATH=$PROJECT_ROOT/_output/source/$OS-$ARCH/usr/lib64/pkgconfig:${PKG_CONFIG_PATH-}\n    fi\n\n    # target file is meant to be treated as a folder since multiple binaries will written out\n    if [[ \"$TARGET_FILE\" == */ ]]; then\n      mkdir -p $TARGET_FILE      \n    fi\n\n    echo \"Building binary(s): $ALL_TARGET_FILES\"\n    export CGO_ENABLED=$CGO_ENABLED GOOS=$OS GOARCH=$ARCH \n    \n    build::simple::print_go_env\n    \n    build::common::echo_and_run go $GOBUILD_COMMAND -trimpath -a -ldflags \"$GO_LDFLAGS\" $EXTRA_GOBUILD_FLAGS -o $TARGET_FILE $SOURCE_PATTERN\n\n    if [[ \"$TARGET_FILE\" == */ ]]; then\n      # in the case of outputing to a directory, the files will be named by the basename of the source pattern\n      # these need to be renamed to match the configured name from ALL_TARGET_FILES\n      TARGET_FILES=(${ALL_TARGET_FILES// / })\n      index=0\n      for source in $SOURCE_PATTERN; do\n        if [ \"$(basename $source)\" != \"${TARGET_FILES[$index]}\" ] && [ -f $TARGET_FILE$(basename $source) ]; then\n          # in the case of multiple target files but the first is a ., we cant move . but it should already be named correctly          \n          build::common::echo_and_run mv $TARGET_FILE$(basename $source) $TARGET_FILE${TARGET_FILES[$index]}\n        fi\n        ((index=index+1))\n      done\n    fi\n  done\n}\n\nbuild::simple::binaries\n", "num_lines": 92}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAR_FILE_PREFIX=\"$1\"\nOUTPUT_DIR=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\nTAG=\"$4\"\nBINARY_PLATFORMS=\"$5\"\nTAR_PATH=\"$6\"\n\nLICENSES_PATH=$(find $OUTPUT_DIR -maxdepth 3 -name LICENSES)\nATTRIBUTION_PATH=$(find $OUTPUT_DIR -maxdepth 1 -name \"*ATTRIBUTION.txt\")\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nfunction build::simple::tarball() {\n  build::common::ensure_tar\n  mkdir -p \"$TAR_PATH\"\n  SUPPORTED_PLATFORMS=(${BINARY_PLATFORMS// / })\n  for platform in \"${SUPPORTED_PLATFORMS[@]}\"; do\n    OS=\"$(cut -d '/' -f1 <<< ${platform})\"\n    ARCH=\"$(cut -d '/' -f2 <<< ${platform})\"\n    TAR_FILE=\"${TAR_FILE_PREFIX}-${OS}-${ARCH}-${TAG}.tar.gz\"\n\n    build::common::echo_and_run cp -rf $LICENSES_PATH ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/ \n    build::common::echo_and_run cp $ATTRIBUTION_PATH ${OUTPUT_BIN_DIR}/${OS}-${ARCH}/ \n    build::common::create_tarball ${TAR_PATH}/${TAR_FILE} ${OUTPUT_BIN_DIR}/${OS}-${ARCH} .\n  done\n}\n\nbuild::simple::tarball\n", "num_lines": 49}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$1\"\nPROJECT_ROOT=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\n\n\nif [ ! -d ${OUTPUT_BIN_DIR} ] ;  then\n    echo \"${OUTPUT_BIN_DIR} not present! Run 'make binaries'\"\n    exit 1\nfi\n\nCHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS\n\nrm -f $CHECKSUMS_FILE\nfor file in $(find ${OUTPUT_BIN_DIR} -type f | sort); do\n    filepath=$(realpath --relative-base=$MAKE_ROOT $file)\n    sha256sum $filepath >> $CHECKSUMS_FILE\ndone\n\necho \"*************** CHECKSUMS ***************\"\ncat $CHECKSUMS_FILE\necho \"*****************************************\"\n", "num_lines": 41}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nif [[ -z \"$JOB_TYPE\" ]]; then\n    exit 0\nfi\n\nGOPATH=$GOPATH\nif [ -d \"/go\" ]; then\n    GOPATH=\"/go\"\nfi\n\nfor go in $GOPATH/go*/bin/go; do\n    VERSION=$($go version | grep -o \"go[0-9].* \" | grep -o \"[0-9\\.]*\")\n    NOPATCH=$(cut -d. -f\"1,2\" <<< $VERSION)\n    sed -i \"s,\\${GOLANG${NOPATCH//./}_VERSION:-.*},\\${GOLANG${NOPATCH//./}_VERSION:-$VERSION},\" ./build/lib/install_go_versions.sh \ndone\n", "num_lines": 38}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nREPO=\"$2\"\nTAG=\"$3\"\nGOLANG_VERSION=\"$4\"\nCUSTOM_VENDOR_UPDATE_SCRIPT=\"${5:-}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\ncd $REPO\n\nCACHE_KEY=$(echo $PROJECT_ROOT | sed 's/\\(.*\\)\\//\\1-/' | xargs basename)\nbuild::common::use_go_version $GOLANG_VERSION\nbuild::common::set_go_cache $CACHE_KEY $TAG\n\n# force a full download of deps to properly clean up the go.sum\nrm -rf go.sum vendor\n\nif [ ! -f \"$CUSTOM_VENDOR_UPDATE_SCRIPT\" ]; then\n    go mod vendor\n    go mod tidy\nelse\n    exec $CUSTOM_VENDOR_UPDATE_SCRIPT\nfi\n", "num_lines": 44}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=\"$1\"\nARTIFACTS_FOLDER=\"$2\"\nGIT_TAG=\"$3\"\nFAKE_ARM_ARTIFACTS_FOR_VALIDATION=\"$4\"\n\nEXPECTED_FILES_PATH=$PROJECT_ROOT/expected_artifacts\nif [[ $ARTIFACTS_FOLDER == *images ]]; then\n\tEXPECTED_FILES_PATH=$PROJECT_ROOT/expected_images\nfi\n\nACTUAL_FILES=$(mktemp)\n\nfor file in $(find ${ARTIFACTS_FOLDER} -type f | sort); do\n    filepath=$(realpath --relative-base=$ARTIFACTS_FOLDER $file)\n\techo $filepath >> $ACTUAL_FILES\ndone\n\nEXPECTED_FILES=$(mktemp)\nexport GIT_TAG=$GIT_TAG\nenvsubst '$GIT_TAG' \\\n\t< $EXPECTED_FILES_PATH \\\n\t> $EXPECTED_FILES\n\nif $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then\n\tsed -i '/arm64/d' $EXPECTED_FILES\nfi\n\nif ! diff $EXPECTED_FILES $ACTUAL_FILES; then\n\techo \"Artifacts directory does not matched expected!\"\n\techo \"******************* Actual ******************\"\n\tcat $ACTUAL_FILES\n\techo \"*********************************************\"\n\texit 1\nfi\n\n", "num_lines": 55}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$1\"\nPROJECT_ROOT=\"$2\"\nOUTPUT_BIN_DIR=\"$3\"\nFAKE_ARM_ARTIFACTS_FOR_VALIDATION=\"$4\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\ncd $MAKE_ROOT\n\nCHECKSUMS_FILE=$PROJECT_ROOT/CHECKSUMS\n\nif $FAKE_ARM_ARTIFACTS_FOR_VALIDATION; then\n\tTEMP_FILE=$(mktemp)\n\tgrep -v 'arm64' $CHECKSUMS_FILE > $TEMP_FILE\n\tCHECKSUMS_FILE=$TEMP_FILE\nfi\n\nif ! sha256sum -c $CHECKSUMS_FILE; then\n\techo \"Checksums do not match!\"\n\techo \"The correct checksums are printed below\"\n\techo \"Please only update if changing GIT_TAG or build flags.\"\n\t$SCRIPT_ROOT/update_checksums.sh $MAKE_ROOT $PROJECT_ROOT $OUTPUT_BIN_DIR\n\texit 1\nfi\n", "num_lines": 44}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAG=\"$1\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nbuild::common::wait_for_tag $TAG\n", "num_lines": 27}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nif [[ -z \"$JOB_TYPE\" ]]; then\n    exit 0\nfi\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nsource $SCRIPT_ROOT/../lib/common.sh\n\nORIGIN_ORG=\"eks-distro-pr-bot\"\nUPSTREAM_ORG=\"aws\"\n\nMAIN_BRANCH=\"${PULL_BASE_REF:-main}\"\n\ncd ${SCRIPT_ROOT}/../../\ngit config --global push.default current\ngit config user.name \"EKS Distro PR Bot\"\ngit config user.email \"aws-model-rocket-bots+eksdistroprbot@amazon.com\"\ngit config remote.origin.url >&- || git remote add origin git@github.com:${ORIGIN_ORG}/eks-distro.git\ngit config remote.upstream.url >&- || git remote add upstream https://github.com/${UPSTREAM_ORG}/eks-distro.git\n\nbuild::common::echo_and_run git status\n\n# Files have already changed, stash to perform rebase\nbuild::common::echo_and_run git stash\nbuild::common::echo_and_run retry git fetch upstream\n\nbuild::common::echo_and_run git checkout $MAIN_BRANCH\n# there will be conflicts before we are on the bots fork at this point\n# -Xtheirs instructs git to favor the changes from the current branch\nbuild::common::echo_and_run git rebase -Xtheirs upstream/$MAIN_BRANCH\n\nif [ \"$(git stash list)\" != \"\" ]; then\n    build::common::echo_and_run git stash pop\n    build::common::echo_and_run git status\nfi\n\nfunction pr:create()\n{\n    local -r pr_title=\"$1\"\n    local -r commit_message=\"$2\"\n    local -r pr_branch=\"$3\"\n    local -r pr_body=\"$4\"\n\n    git diff --staged\n    local -r files_added=$(git diff --staged --name-only)\n    if [ \"$files_added\" = \"\" ]; then\n        return 0\n    fi\n\n    git checkout -B $pr_branch\n    git commit -m \"$commit_message\" || true\n\n    if [ \"$JOB_TYPE\" != \"periodic\" ]; then\n        return 0\n    fi\n\n    ssh-agent bash -c 'ssh-add /secrets/ssh-secrets/ssh-key; ssh -o StrictHostKeyChecking=no git@github.com; git push -u origin $pr_branch -f'\n\n    gh auth login --with-token < /secrets/github-secrets/token\n    local -r pr_exists=$(gh pr list | grep -c \"$pr_branch\" || true)\n    if [ $pr_exists -eq 0 ]; then\n        echo \"Creating PR $pr_title\"\n        gh pr create --title \"$pr_title\" --body \"$pr_body\" --base $MAIN_BRANCH\n    fi\n}\n\nfunction pr::create::pr_body(){\n    pr_body=\"\"\n    case $1 in\n    attribution)\n        pr_body=$(cat <<'EOF'\nThis PR updates the ATTRIBUTION.txt files across all dependency projects if there have been changes.\n\nThese files should only be changing due to project GIT_TAG bumps or Golang version upgrades. If changes are for any other reason, please review carefully before merging!\nEOF\n)\n        ;;\n    checksums)\n        pr_body=$(cat <<'EOF'\nThis PR updates the CHECKSUMS files across all dependency projects if there have been changes.\n\nThese files should only be changing due to project GIT_TAG bumps or Golang version upgrades. If changes are for any other reason, please review carefully before merging!\nEOF\n)\n        ;;\n    makehelp)\n        pr_body=$(cat <<'EOF'\nThis PR updates the Help.mk files across all dependency projects if there have been changes.\nEOF\n)\n        ;;\n    go-mod)\n        pr_body=$(cat <<'EOF'\nThis PR updates the checked in go.mod and go.sum files across all dependency projects to support automated vulnerability scanning.\nEOF\n)\n        ;;\n    *)\n        echo \"Invalid argument: $1\"\n        exit 1\n        ;;\n    esac\n    PROW_BUCKET_NAME=$(echo $JOB_SPEC | jq -r \".decoration_config.gcs_configuration.bucket\" | awk -F// '{print $NF}')\n    full_pr_body=$(printf \"%s\\nClick [here](https://prow.eks.amazonaws.com/view/s3/$PROW_BUCKET_NAME/logs/$JOB_NAME/$BUILD_ID) to view job logs.\\n\\n/hold\\n\\nBy submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\" \"$pr_body\")\n\n    printf \"$full_pr_body\"\n}\n\nfunction pr::create::attribution() {\n    local -r pr_title=\"Update ATTRIBUTION.txt files\"\n    local -r commit_message=\"[PR BOT] Update ATTRIBUTION.txt files\"\n    local -r pr_branch=\"attribution-files-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"attribution\")\n\n    pr:create \"$pr_title\" \"$commit_message\" \"$pr_branch\" \"$pr_body\"\n}\n\nfunction pr::create::checksums() {\n    local -r pr_title=\"Update CHECKSUMS files\"\n    local -r commit_message=\"[PR BOT] Update CHECKSUMS files\"\n    local -r pr_branch=\"checksums-files-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"checksums\")\n\n    pr:create \"$pr_title\" \"$commit_message\" \"$pr_branch\" \"$pr_body\"\n}\n\nfunction pr::create::help() {\n    local -r pr_title=\"Update Makefile generated help\"\n    local -r commit_message=\"[PR BOT] Update Help.mk files\"\n    local -r pr_branch=\"help-makefiles-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"makehelp\")\n\n    pr:create \"$pr_title\" \"$commit_message\" \"$pr_branch\" \"$pr_body\"\n}\n\nfunction pr::create::go-mod() {\n    local -r pr_title=\"Update go.mod files\"\n    local -r commit_message=\"[PR BOT] Update go.mod files\"\n    local -r pr_branch=\"go-mod-update-$MAIN_BRANCH\"\n    local -r pr_body=$(pr::create::pr_body \"go-mod\")\n\n    pr:create \"$pr_title\" \"$commit_message\" \"$pr_branch\" \"$pr_body\"\n}\n\nfunction pr::file:add() {\n    local -r file=\"$1\"\n\n    if git check-ignore -q $FILE; then\n        continue\n    fi\n\n    local -r diff=\"$(git diff --ignore-blank-lines --ignore-all-space $FILE)\"\n    if [[ -z $diff ]]; then\n        continue\n    fi\n\n    git add $file\n}\n\necho \"Adding Checksum files\"\n# Add checksum files\nfor FILE in $(find . -type f -name CHECKSUMS); do\n    pr::file:add $FILE\ndone\n\n# This file is being added as it may have been updated by the last lines of ./build/lib/update_go_versions.sh,\n# which replaces the go version in this script with the go version(s) in the builder base if they are newer \n# when running `make update-checksum-files`\ngit add ./build/lib/install_go_versions.sh\n\n# stash attribution and help.mk files\ngit stash --keep-index\n\npr::create::checksums\n\ngit checkout $MAIN_BRANCH\n\nif [ \"$(git stash list)\" != \"\" ]; then\n    build::common::echo_and_run git stash pop\n    build::common::echo_and_run git status\nfi\n\necho \"Adding ATTRIBUTION files\"\n# Add attribution files\nfor FILE in $(find . -type f \\( -name \"*ATTRIBUTION.txt\" ! -path \"*/_output/*\" \\)); do\n    pr::file:add $FILE\ndone\n\n# stash help.mk files\ngit stash --keep-index\n\npr::create::attribution\n\ngit checkout $MAIN_BRANCH\n\nif [ \"$(git stash list)\" != \"\" ]; then\n    build::common::echo_and_run git stash pop\n    build::common::echo_and_run git status\nfi\n\necho \"Adding Help.mk files\"\n\n# Add help.mk/Makefile files\nfor FILE in $(find . -type f \\( -name Help.mk -o -name Makefile \\)); do\n    pr::file:add $FILE\ndone\n\n# stash go.sum files\ngit stash --keep-index\n\npr::create::help\n\ngit checkout $MAIN_BRANCH\n\nif [ \"$(git stash list)\" != \"\" ]; then\n    build::common::echo_and_run git stash pop\n    build::common::echo_and_run git status\nfi\n\necho \"Adding go.mod and go.sum files\"\n# Add go.mod files\nfor FILE in $(find . -type f \\( -name go.sum -o -name go.mod \\)); do    \n    git check-ignore -q $FILE || git add $FILE\ndone\n\npr::create::go-mod\n", "num_lines": 245}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2020 Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o errexit\nset -o nounset\nset -o pipefail\nshopt -s globstar\n\nPROJECT=\"$1\"\nTARGET=\"$2\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\nPROJECT_ROOT=$MAKE_ROOT/$PROJECT\n\nOUTPUT_DIR=$MAKE_ROOT/_output\nmkdir -p $OUTPUT_DIR\ntouch $OUTPUT_DIR/total_summary.txt\n\nfunction build::attribution::generate(){\n    make -C $PROJECT_ROOT $TARGET\n\n    if ls $PROJECT_ROOT/_output/**/summary.txt 1> /dev/null 2>&1; then\n        for summary in $PROJECT_ROOT/_output/**/summary.txt; do\n            sed -i \"s/+.*=/ =/g\" $summary\n            awk -F\" => \" '{ count[$1]+=$2} END { for (item in count) printf(\"%s => %d\\n\", item, count[item]) }' \\\n                $summary $OUTPUT_DIR/total_summary.txt | sort > $OUTPUT_DIR/total_summary.tmp && mv $OUTPUT_DIR/total_summary.tmp $OUTPUT_DIR/total_summary.txt\n        done\n    fi\n}\n\n\n# Some projects have specific folders for different kubernetes release\n# dynamically find all versions to avoid having to update with every release\nRELEASE_FOLDER=$(find $PROJECT_ROOT -type d -name \"1-*\")\n\nif [ -z \"${RELEASE_FOLDER}\" ]; then\n    build::attribution::generate\nelse\n    LAST_GIT_TAG=\"\"\n    LAST_RELEASE_BRANCH=\"\"\n    for release in $(cat $MAKE_ROOT/release/SUPPORTED_RELEASE_BRANCHES) ; do\n        export RELEASE_BRANCH=\"$release\"\n\n        GIT_TAG=\"$(cat $PROJECT_ROOT/$release/GIT_TAG)\"\n        if [ \"$GIT_TAG\" != \"$LAST_GIT_TAG\" ] || [ $TARGET == \"update-go-mods\" ]; then\n            # clean before regenerating to ensure there are no intermediate files left around\n            make -C $PROJECT_ROOT clean clean-go-cache\n            build::attribution::generate $release\n        else\n            # if the git_tags match across release branches, save the output state to avoid\n            # rebuilding/regenerating\n            if [[ $TARGET == *\"checksums\"* ]]; then\n                echo \"Copying $LAST_RELEASE_BRANCH CHECKSUMS to $release\"\n                mkdir -p $PROJECT_ROOT/_output/$release\n                sed \"s/$LAST_RELEASE_BRANCH/$release/\" $PROJECT_ROOT/$LAST_RELEASE_BRANCH/CHECKSUMS > $PROJECT_ROOT/$release/CHECKSUMS\n            fi\n\n            if [[ $TARGET == *\"attribution\"* ]]; then\n                echo \"Copying $LAST_RELEASE_BRANCH ATTRIBUTION to $release\"\n                mkdir -p $PROJECT_ROOT/_output/$release\n                cp -rf $PROJECT_ROOT/$LAST_RELEASE_BRANCH/*TTRIBUTION.txt $PROJECT_ROOT/$release\n            fi            \n        fi\n        LAST_GIT_TAG=\"$GIT_TAG\"\n        LAST_RELEASE_BRANCH=\"$release\"\n    done\nfi\n\nmake -C $PROJECT_ROOT clean clean-go-cache\n", "num_lines": 83}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Generates release on GitHub.\n# IMPORTANT!! GIT_TAG for release must already exist.\nset -e\nset -o pipefail\nset -x\n\nGIT_TAG=\"${1?...}\"\nCHANGELOG_FILEPATH=\"${2?...}\"\nINDEX_FILEPATH=\"${3?...}\"\n\n# Removes the first three lines to get rid of H1 headers and an empty line and the\n# changelog highlights from the changelog and first four lines from the index.md\n# including the additional information and the empty line for the github release\n# docs\n# The H1 headers are larger than the release titles on GitHub, and it\n# looks confusing with them.\nreleaseNotes=\"$(sed '1,3d' \"$CHANGELOG_FILEPATH\")\n\n$(sed '1,4d' \"$INDEX_FILEPATH\")\"\n\ngh release create \"$GIT_TAG\" --title \"EKS Distro $GIT_TAG Release\" --notes \"$releaseNotes\" --repo \"aws/eks-distro\"\n", "num_lines": 37}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nPR_BRANCH=\"${1?...}\"\nPR_TITLE=\"${2?...}\"\n\necho \"pushing...\"\ngit push origin \"${PR_BRANCH}\"\necho \"pushed!\"\n\nPR_REPO=\"eks-distro\"\n\nGITHUB_USERNAME_REGEX=\"s/(https:\\/\\/|git@)github\\.com(\\/|:)(.*)\\/${PR_REPO}.git/\\3/p\"\nGITHUB_USERNAME=$(git remote get-url origin | sed -n -E \"$GITHUB_USERNAME_REGEX\")\nif [ -z \"$GITHUB_USERNAME\" ]\nthen\necho \"Failed to parse Github username! Ensure you have a remote 'origin' set.\" && return 1\nfi\n\npr_arguments=(\n  --head \"${GITHUB_USERNAME}:${PR_BRANCH}\"\n  --repo \"aws/${PR_REPO}\"\n  --title \"${PR_TITLE}\"\n  --web\n  --body \"By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.\"\n)\n\ngh pr create \"${pr_arguments[@]}\"\n", "num_lines": 45}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nRELEASE_BRANCH=$(cat \"${BASE_DIRECTORY}\"/release/DEFAULT_RELEASE_BRANCH)\nRELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-production}\nRELEASE=$(cat \"${BASE_DIRECTORY}\"/release/\"${RELEASE_BRANCH}\"/\"${RELEASE_ENVIRONMENT}\"/RELEASE)\nRELEASE_TAG=\"eks-${RELEASE_BRANCH}-${RELEASE}\"\n\nRELEASE_CRD=\"https://distro.eks.amazonaws.com/kubernetes-${RELEASE_BRANCH}/kubernetes-${RELEASE_BRANCH}-eks-${RELEASE}.yaml\"\nECR_BASE=\"public.ecr.aws/eks-distro\"\n\nRELEASE_GIT_TAG=$(cat \"${BASE_DIRECTORY}\"/projects/kubernetes/release/${RELEASE_BRANCH}/GIT_TAG)\n\nwhile read -r image_uri; do\n  docker pull \"$image_uri\"\ndone < <(curl \"${RELEASE_CRD}\" | sed -n -e \"s|^.*uri: \\\\($ECR_BASE\\\\)|\\1|p\")\n\n# These are not in the CRD\ndocker pull \"${ECR_BASE}/kubernetes/kube-proxy-base:${RELEASE_GIT_TAG}-${RELEASE_TAG}\"\ndocker pull \"${ECR_BASE}/kubernetes/go-runner:${RELEASE_GIT_TAG}-${RELEASE_TAG}\"\n", "num_lines": 37}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\nBASEDIR=$(dirname \"$0\")\ncd ${BASEDIR}\n\nfunction install_ecr_public {\n    if [ ! -f ~/.aws/models/ecr-public/2020-10-30/service-2.json ]\n    then\n        echo \"Installing ECR Public plugin\"\n        aws configure add-model \\\n          --service-model file://ecr-public-2020-10-30.api.json \\\n          --service-name ecr-public\n    fi\n}\n\nfunction create_ecr_public_policy {\n    POLICY_NAME=ECRPublicAccess\n    if aws iam list-policies \\\n         --query \"Policies[?PolicyName=='${POLICY_NAME}'].[PolicyName]\" \\\n         --output text | grep \"${POLICY_NAME}\" >/dev/null\n    then\n        return\n    fi\n    echo \"Creating ECR Public policy\"\n    aws iam create-policy \\\n      --policy-name ${POLICY_NAME} \\\n      --policy-document \\\n      file://ecr-public-policy.json\n}\n\nfunction login_ecr_public {\n    # Token expires after 12 hours\n    TOKEN=$(aws --region us-east-1 ecr-public get-authorization-token \\\n        --output=text \\\n        --query 'authorizationData.authorizationToken')\n\n    DOCKER_CONFIG=${DOCKER_CONFIG:-\"~/.docker\"}\n    if command -v docker &> /dev/null && docker info > /dev/null 2>&1; then\n        echo $TOKEN | \\\n            base64 --decode | \\\n            cut -d: -f2 | \\\n            docker login -u AWS --password-stdin https://public.ecr.aws\n    else\n        mkdir -p $DOCKER_CONFIG\n        if [ ! -f $DOCKER_CONFIG/config.json ]; then\n            echo '{}' > $DOCKER_CONFIG/config.json\n        fi\n        # Gross, abominable hack until ecr-credential-helper supports public ECR\n        # See https://github.com/awslabs/amazon-ecr-credential-helper/issues/248\n        cat $DOCKER_CONFIG/config.json | \\\n            jq --arg TOKEN $TOKEN '.auths.\"public.ecr.aws\".auth = $TOKEN' > $DOCKER_CONFIG/config.json.new\n        cp $DOCKER_CONFIG/config.json.new $DOCKER_CONFIG/config.json\n    fi\n}\n\nfunction create_private_repository {\n    local -r repository_name=\"${1?First argument is repository name}\"\n    aws ecr describe-repositories \\\n      --query \"repositories[*].repositoryName\" \\\n      --output text \\\n      --repository-name $repository_name 2>/dev/null ||\n    aws ecr create-repository \\\n      --repository-name $repository_name \\\n      --image-scanning-configuration scanOnPush=true\n}\n\nfunction create_public_repository {\n    local -r repository_name=\"${1?First argument should be repository name}\"\n    local -r file_prefix=\"$(echo $repository_name | awk -F/ '{print $(NF)}')\"\n    local -r input=\"create-public-repo-input.json\"\n    # Yes, they put a _space_ in \"ARM 64\"\n    cat << EOF > $input\n{\n    \"repositoryName\": \"$repository_name\",\n    \"catalogData\": {\n        \"description\": \"Development $(cat image-docs/${file_prefix}-description)\",\n        \"architectures\": [\n            \"x86-64\",\n            \"ARM 64\"\n        ],\n        \"operatingSystems\": [\n            \"linux\"\n        ],\n\t\"aboutText\": \"Development $(awk '{printf \"%s\\\\n\", $0}' image-docs/${file_prefix}-about.md)\",\n\t\"usageText\": \"$(awk '{printf \"%s\\\\n\", $0}' image-docs/${file_prefix}-usage.md)\"\n    }\n}\nEOF\n    aws ecr-public describe-repositories \\\n      --query \"repositories[*].repositoryName\" \\\n      --output text \\\n      --repository-name $repository_name 2>/dev/null ||\n    aws ecr-public create-repository \\\n      --repository-name $repository_name \\\n      --cli-input-json file://$input\n    rm -f $input\n}\n\nfunction create_all_private_repositories {\n    create_private_repository \"coredns/coredns\"\n    create_private_repository \"etcd-io/etcd\"\n    create_private_repository \"kubernetes-csi/external-attacher\"\n    create_private_repository \"kubernetes-csi/external-provisioner\"\n    create_private_repository \"kubernetes-csi/external-resizer\"\n    create_private_repository \"kubernetes-csi/external-snapshotter/csi-snapshotter\"\n    create_private_repository \"kubernetes-csi/external-snapshotter/snapshot-controller\"\n    create_private_repository \"kubernetes-csi/external-snapshotter/snapshot-validation-webhook\"\n    create_private_repository \"kubernetes-csi/livenessprobe\"\n    create_private_repository \"kubernetes-csi/node-driver-registrar\"\n    create_private_repository \"kubernetes-sigs/aws-iam-authenticator\"\n    create_private_repository \"kubernetes-sigs/metrics-server\"\n    create_private_repository \"kubernetes/go-runner\"\n    create_private_repository \"kubernetes/kube-apiserver\"\n    create_private_repository \"kubernetes/kube-controller-manager\"\n    create_private_repository \"kubernetes/kube-proxy\"\n    create_private_repository \"kubernetes/kube-proxy-base\"\n    create_private_repository \"kubernetes/kube-scheduler\"\n    create_private_repository \"kubernetes/pause\"\n}\n\nfunction create_all_public_repositories {\n    create_public_repository \"coredns/coredns\"\n    create_public_repository \"etcd-io/etcd\"\n    create_public_repository \"kubernetes-csi/external-attacher\"\n    create_public_repository \"kubernetes-csi/external-provisioner\"\n    create_public_repository \"kubernetes-csi/external-resizer\"\n    create_public_repository \"kubernetes-csi/external-snapshotter/csi-snapshotter\"\n    create_public_repository \"kubernetes-csi/external-snapshotter/snapshot-controller\"\n    create_public_repository \"kubernetes-csi/external-snapshotter/snapshot-validation-webhook\"\n    create_public_repository \"kubernetes-csi/livenessprobe\"\n    create_public_repository \"kubernetes-csi/node-driver-registrar\"\n    create_public_repository \"kubernetes-sigs/aws-iam-authenticator\"\n    create_public_repository \"kubernetes-sigs/metrics-server\"\n    create_public_repository \"kubernetes/go-runner\"\n    create_public_repository \"kubernetes/kube-apiserver\"\n    create_public_repository \"kubernetes/kube-controller-manager\"\n    create_public_repository \"kubernetes/kube-proxy\"\n    create_public_repository \"kubernetes/kube-proxy-base\"\n    create_public_repository \"kubernetes/kube-scheduler\"\n    create_public_repository \"kubernetes/pause\"\n}\n\nfunction update_public_repository {\n    local -r repository_name=\"${1?First argument is repository_name}\"\n    local -r file_prefix=\"$(echo $repository_name | awk -F/ '{print $(NF)}')\"\n    # requires CLI v2\n    aws ecr-public put-repository-catalog-data \\\n        --repository-name $repository_name \\\n        --catalog-data operatingSystems=Linux,logoImageBlob=$(cat eks-distro-img-large.png |base64)\n    local -r input=\"update-public-repo-input.json\"\n    cat << EOF > base-$input\n{\n    \"repositoryName\": \"$repository_name\",\n    \"catalogData\": {\n        \"architectures\": [\n            \"x86-64\",\n            \"ARM 64\"\n        ],\n        \"operatingSystems\": [\n            \"Linux\"\n        ]\n    }\n}\nEOF\n    jq --arg about \"$(<image-docs/${file_prefix}-about.md)\" '.catalogData.aboutText=$about' base-${input} > about-$input\n    jq --arg usage \"$(<image-docs/${file_prefix}-usage.md)\" '.catalogData.usageText=$usage' about-${input} > $input\n    aws ecr-public put-repository-catalog-data \\\n      --cli-input-json file://$input\n    rm base-$input about-${input} ${input}\n}\n\nfunction delete_public_repository {\n    local -r repository_name=\"${1?First argument is repository name}\"\n    if ! aws ecr-public describe-repositories \\\n           --query \"repositories[*].repositoryName\" \\\n           --repository-name $repository_name 2>/dev/null\n    then\n        return\n    fi\n    REGISTRY_ID=$(aws ecr-public describe-registries --query registries[0].registryId --output text)\n    for digest in $(aws ecr-public describe-images --registry-id  $REGISTRY_ID --repository-name $repository_name --query imageDetails[*].imageDigest --output text); do\n        aws ecr-public batch-delete-image --registry-id  $REGISTRY_ID --repository-name $repository_name --image-ids imageDigest=$digest\n    done\n    aws ecr-public delete-repository --registry-id  $REGISTRY_ID --repository-name $repository_name\n}\n\nfunction retag_private_image {\n    local -r repository_name=\"${1?First argument is repository name}\"\n    local -r image_tag=\"${2?Second argument is image tag}\"\n    local -r new_tag=\"${3?Third argument is new tag}\"\n    MANIFEST=$(aws ecr batch-get-image --repository-name ${repository_name} --image-ids imageTag=${image_tag} --query 'images[].imageManifest' --output text)\n    aws ecr put-image --repository-name ${repository_name} --image-tag ${new_tag} --image-manifest \"$MANIFEST\"\n}\n\nCOMMAND=\"${1}\"\nshift\ncase \"${COMMAND}\" in\ninstall-ecr-public)\n  install_ecr_public\n  ;;\ncreate-ecr-public-policy)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  create_ecr_public_policy\n  ;;\nlogin-ecr-public)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  login_ecr_public\n  ;;\ncreate-public-repository)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  create_public_repository ${1}\n  ;;\ncreate-all-private-repositories)\n  create_all_private_repositories\n  ;;\ncreate-all-public-repositories)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  create_all_public_repositories\n  ;;\ncreate-private-repository)\n  create_private_repository ${*}\n  ;;\nupdate-public-metadata)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  update_public_repository ${*}\n  ;;\ndelete-public-repository)\n  export AWS_DEFAULT_REGION=us-east-1\n  export AWS_REGION=us-east-1\n  delete_public_repository ${*}\n  ;;\nretag-private-image)\n  retag_private_image ${*}\n  ;;\n*)\n  echo \"Please specify a supported command\"\n  exit 1\n  ;;\nesac\n", "num_lines": 259}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\n\nreadonly ECR_REPOS=(\n    coredns/coredns\n    etcd-io/etcd\n    kubernetes-csi/external-attacher\n    kubernetes-csi/external-provisioner\n    kubernetes-csi/external-resizer\n    kubernetes-csi/external-snapshotter/csi-snapshotter\n    kubernetes-csi/external-snapshotter/snapshot-controller\n    kubernetes-csi/external-snapshotter/snapshot-validation-webhook\n    kubernetes-csi/livenessprobe\n    kubernetes-csi/node-driver-registrar\n    kubernetes-sigs/aws-iam-authenticator\n    kubernetes-sigs/metrics-server\n    kubernetes/go-runner\n    kubernetes/kube-apiserver\n    kubernetes/kube-controller-manager\n    kubernetes/kube-proxy\n    kubernetes/kube-proxy-base\n    kubernetes/kube-scheduler\n    kubernetes/pause\n)\nfor image in \"${ECR_REPOS[@]}\"; do\n    aws ecr describe-repositories --repository-name $image 2>/dev/null ||\n    aws ecr create-repository \\\n        --repository-name $image \\\n        --image-scanning-configuration  scanOnPush=true || true\ndone\n", "num_lines": 46}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash -xe\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n./ecr-command.sh install-ecr-public\n./ecr-command.sh create-ecr-public-policy\n./ecr-command.sh login-ecr-public\n\n./ecr-command.sh delete-public-repository test-repository\n./ecr-command.sh create-public-repository test-repository\n./ecr-command.sh update-public-metadata test-repository\n./ecr-command.sh delete-public-repository test-repository\n\n./ecr-command.sh create-private-repository test-repository\n#./ecr-command.sh retag-private-image test-repository scratch 1.0 2.0\n", "num_lines": 27}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\n\nfunction retry {\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n/$max:\"\n        sleep $delay;\n      else\n        fail \"The command has failed after $n attempts.\"\n      fi\n    }\n  done\n}\n\nfunction k {\n    retry kubectl --context $KOPS_CLUSTER_NAME \"$@\"\n}\n\n# Add IAM configmap\necho 'Waiting for cluster to come up...'\nk apply -f ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml\n\n# kops installs an older metrics server\n# than we ship with EKS-D, along with an older clusterrole def. The 0.6 version\n# of metrics requires a slightly different rbac setup.\nk apply -f metrics-server-0.6-clusterrole.yaml\n\n# kops doesnt support setting these cilium values\n# session affinity for conformance tess\n# kube-proxy disabled to make sure we are validating our kube-proxy\nk -n kube-system patch cm/cilium-config --type merge -p '{\"data\":{\"enable-session-affinity\":\"true\"}}'\nk -n kube-system rollout restart deployment/cilium-operator\nk -n kube-system rollout status deployment/cilium-operator --timeout=30s\nk -n kube-system delete pods -lk8s-app=cilium\n\nset -x\n${KOPS} validate cluster --wait 15m\n\n# --set ipam.mode=\"kubernetes\" \n", "num_lines": 65}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\nif [ \"$TEST_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty TEST_ROLE_ARN, this script must be run in a codebuild job with a test role arn provided\"\n    exit 1\nfi\n\nBASEDIR=$(dirname \"$0\")\n\ncat << EOF > config\n[profile conformance-test]\nrole_arn=$TEST_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\ncredential_source=EcsContainer\nEOF\n\nexport AWS_CONFIG_FILE=$(pwd)/config\nexport AWS_PROFILE=conformance-test\nDEFAULT_KOPS_ZONE_NAME=\"prod-build-pdx.kops-ci.model-rocket.aws.dev\"\nKOPS_ZONE_NAME=${KOPS_ZONE_NAME:-\"${DEFAULT_KOPS_ZONE_NAME}\"}\nexport NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}\nexport KOPS_CLUSTER_NAME=${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-$(git rev-parse --short HEAD).$(echo $RANDOM | md5sum | head -c 4).${KOPS_ZONE_NAME}\n${BASEDIR}/run_all.sh\n", "num_lines": 42}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nADDITIONAL_ARGS=\"\"\nif [ -n \"$NODE_INSTANCE_PROFILE\" ]; then\n    ADDITIONAL_ARGS=\"--lifecycle-overrides IAMRole=ExistsAndWarnIfChanges,IAMRolePolicy=ExistsAndWarnIfChanges,IAMInstanceProfileRole=ExistsAndWarnIfChanges\"\nfi\n\n${KOPS} update cluster --admin --name ${KOPS_CLUSTER_NAME} --yes $ADDITIONAL_ARGS\n", "num_lines": 28}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\n# Create the bucket if it doesn't exist\n_bucket_name=$(aws s3api list-buckets  --query \"Buckets[?Name=='$BUCKET_NAME'].Name | [0]\" --out text)\nif [ $_bucket_name == \"None\" ]; then\n    echo \"Creating kOps state store: $KOPS_STATE_STORE\"\n    if [ \"$AWS_DEFAULT_REGION\" == \"us-east-1\" ]; then\n        aws s3api create-bucket --bucket $BUCKET_NAME\n    else\n        aws s3api create-bucket --bucket $BUCKET_NAME --create-bucket-configuration LocationConstraint=$AWS_DEFAULT_REGION\n    fi\nelse\n    echo \"Using kOps state store: $KOPS_STATE_STORE\"\nfi\n\nmkdir -p ./${KOPS_CLUSTER_NAME}\necho \"Creating ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml\"\ncat << EOF > ./${KOPS_CLUSTER_NAME}/aws-iam-authenticator.yaml\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: aws-iam-authenticator\n  namespace: kube-system\n  labels:\n    k8s-app: aws-iam-authenticator\ndata:\n  config.yaml: |\n    clusterID: $KOPS_CLUSTER_NAME\nEOF\n\necho \"Creating ${KOPS_CLUSTER_NAME}.yaml\"\n${KOPS} toolbox template --template ${BASEDIR}/eks-d.tpl --values ./${KOPS_CLUSTER_NAME}/values.yaml > \"./${KOPS_CLUSTER_NAME}/${KOPS_CLUSTER_NAME}.yaml\"\n\necho \"Creating cluster configuration\"\n${KOPS} create -f \"./${KOPS_CLUSTER_NAME}/${KOPS_CLUSTER_NAME}.yaml\"\n\necho \"Creating cluster ssh key\"\nSSH_FILE=${SSH_KEY_PATH:-$HOME/.ssh/id_rsa}\nif [ ! -f \"$SSH_FILE\" ]\nthen\n  ssh-keygen -t rsa -b 4096 -f \"$SSH_FILE\"\nfi\nexport SSH_KEY_PATH=\"$SSH_FILE\"\n${KOPS} create secret --name $KOPS_CLUSTER_NAME sshpublickey admin -i \"${SSH_KEY_PATH}.pub\"\necho\necho \"# Creating ./${KOPS_CLUSTER_NAME}/env.sh\"\necho \"export AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION\" | tee ./${KOPS_CLUSTER_NAME}/env.sh\necho \"export AWS_REGION=$AWS_DEFAULT_REGION\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\necho \"export KOPS_CLUSTER_NAME=$KOPS_CLUSTER_NAME\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\necho \"export KOPS_STATE_STORE=$KOPS_STATE_STORE\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\necho \"export KOPS_BASE_URL=$KOPS_BASE_URL\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nif [ -n \"$CONTROL_PLANE_INSTANCE_PROFILE\" ]; then\n    echo \"export CONTROL_PLANE_INSTANCE_PROFILE=$CONTROL_PLANE_INSTANCE_PROFILE\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\nif [ -n \"$NODE_INSTANCE_PROFILE\" ]; then\n    echo \"export NODE_INSTANCE_PROFILE=$NODE_INSTANCE_PROFILE\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\nif [ -n \"$NODE_INSTANCE_TYPE\" ]; then\n    echo \"export NODE_INSTANCE_TYPE=$NODE_INSTANCE_TYPE\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\nif [ -n \"$NODE_ARCHITECTURE\" ]; then\n    echo \"export NODE_ARCHITECTURE=$NODE_ARCHITECTURE\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\nif [ -n \"$ARTIFACT_BUCKET\" ]; then\n    echo \"export ARTIFACT_BUCKET=$ARTIFACT_BUCKET\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\nif [ -n \"$IMAGE_REPO\" ]; then\n    echo \"export IMAGE_REPO=$IMAGE_REPO\" | tee -a ./${KOPS_CLUSTER_NAME}/env.sh\nfi\n", "num_lines": 89}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Create a unique s3 bucket name\nexport KOPS_STATE_STORE=${KOPS_STATE_STORE:-s3://kops-state-store-$(cat /dev/urandom | LC_ALL=C tr -dc \"[:alpha:]\" | tr '[:upper:]' '[:lower:]' | head -c 32)}\necho export KOPS_STATE_STORE=\"${KOPS_STATE_STORE}\"\n", "num_lines": 19}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nmkdir -p \"./${KOPS_CLUSTER_NAME}\"\nif [ -f \"./${KOPS_CLUSTER_NAME}/values.yaml\" ]; then\n    echo -e \"Error the ./${KOPS_CLUSTER_NAME}/values.yaml file already exists.\"\n    echo -e \"Delete the cluster and cluster store before creating a new cluster\"\n    exit 1\nfi\n\nfunction get_container_yaml() {\n    REPOSITORY_NAME=\"${1}\"\n    RELEASE=\"${2}\"\n    VERSION=\"$(get_project_version $REPOSITORY_NAME)\"\n\n    if  [[ $REPOSITORY_NAME == \"kubernetes-csi/external-snapshotter\" ]] \n    then\n        REPOSITORY_NAME=\"kubernetes-csi/external-snapshotter/csi-snapshotter\"\n    fi\n\n    if  [[ $REPOSITORY_NAME == \"kubernetes/cloud-provider-aws\" ]] \n    then\n        REPOSITORY_NAME=\"kubernetes/cloud-provider-aws/cloud-controller-manager\"\n    fi\n    \n    echo \"    repository: ${IMAGE_REPO}/${REPOSITORY_NAME}\n    tag: ${VERSION}-eks-${RELEASE_BRANCH}-${RELEASE}\"\n}\n\nfunction get_project_version(){\n    REPOSITORY_NAME=\"${1}\"\n    if  [[ $REPOSITORY_NAME == kubernetes/* ]] && [[ $REPOSITORY_NAME != \"kubernetes/cloud-provider-aws\" ]] \n    then\n        REPOSITORY_NAME=\"kubernetes/kubernetes\"\n    fi\n    \n    TAG_FILE=${BASEDIR}/../../projects/${REPOSITORY_NAME}/GIT_TAG\n    if [ -f \"$TAG_FILE\" ]; then\n        VERSION=$(cat ${BASEDIR}/../../projects/${REPOSITORY_NAME}/GIT_TAG)\n    else\n        VERSION=$(cat ${BASEDIR}/../../projects/${REPOSITORY_NAME}/${RELEASE_BRANCH}/GIT_TAG)\n    fi\n    \n    echo $VERSION\n}\n\n# Get latest ubuntu ami based on desired release and arch\nUBUNTU_AMI=$(aws ec2 describe-images --owners 099720109477 --filters \"Name=name,Values=ubuntu/images/hvm-ssd/ubuntu-$UBUNTU_RELEASE-$NODE_ARCHITECTURE-server-*\" --query 'sort_by(Images, &CreationDate)[-1].[Name]' --output text)\n\necho \"Creating ./${KOPS_CLUSTER_NAME}/values.yaml\"\ncat << EOF > ./${KOPS_CLUSTER_NAME}/values.yaml\nkubernetesVersion: ${ARTIFACT_URL}/kubernetes/${KUBERNETES_VERSION}\nclusterName: $KOPS_CLUSTER_NAME\nconfigBase: $KOPS_STATE_STORE/$KOPS_CLUSTER_NAME\nawsRegion: $AWS_DEFAULT_REGION\ncontrolPlaneInstanceProfileArn: $CONTROL_PLANE_INSTANCE_PROFILE\nnodeInstanceProfileArn: $NODE_INSTANCE_PROFILE\ninstanceType: $NODE_INSTANCE_TYPE\narchitecture: $NODE_ARCHITECTURE\nubuntuAmi: $UBUNTU_AMI\nipv6: $IPV6\npause:\n$(get_container_yaml kubernetes/pause $RELEASE)\nkube_apiserver:\n$(get_container_yaml kubernetes/kube-apiserver $RELEASE)\nkube_controller_manager:\n$(get_container_yaml kubernetes/kube-controller-manager $RELEASE)\nkube_scheduler:\n$(get_container_yaml kubernetes/kube-scheduler $RELEASE)\nkube_proxy:\n$(get_container_yaml kubernetes/kube-proxy $RELEASE)\nmetrics_server:\n$(get_container_yaml kubernetes-sigs/metrics-server $RELEASE)\nawsiamauth:\n$(get_container_yaml kubernetes-sigs/aws-iam-authenticator $RELEASE)\ncoredns:\n$(get_container_yaml coredns/coredns $RELEASE)\nnode_driver_registrar:\n$(get_container_yaml kubernetes-csi/node-driver-registrar $RELEASE)\ncsi_resizer:\n$(get_container_yaml kubernetes-csi/external-resizer $RELEASE)\ncsi_attacher:\n$(get_container_yaml kubernetes-csi/external-attacher $RELEASE)\ncsi_snapshotter:\n$(get_container_yaml kubernetes-csi/external-snapshotter $RELEASE)\ncsi_provisioner:\n$(get_container_yaml kubernetes-csi/external-provisioner $RELEASE)\ncsi_livenessprobe:\n$(get_container_yaml kubernetes-csi/livenessprobe $RELEASE)\netcd:\n$(get_container_yaml etcd-io/etcd $RELEASE)\ncloud_controller_manager:\n$(get_container_yaml kubernetes/cloud-provider-aws $RELEASE)\nEOF\n", "num_lines": 113}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\necho \"Deleting cluster $KOPS_STATE_STORE ${KOPS_CLUSTER_NAME}\"\nset -x\n${KOPS} delete cluster --state \"${KOPS_STATE_STORE}\" --name \"${KOPS_CLUSTER_NAME}\" --yes\nset +x\n", "num_lines": 26}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\necho \"Deleting kops store $KOPS_STATE_STORE\"\nset -x\naws s3 rm --recursive \"${KOPS_STATE_STORE}/${KOPS_CLUSTER_NAME}\" || true\nif [ -n \"${KOPS_CLUSTER_NAME}\" ]\nthen\n  rm -rf \"./${KOPS_CLUSTER_NAME}\"\nfi\n", "num_lines": 29}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nexport LOG_DUMP_SAVE_SERVICES=\"kops-configuration containerd protokube\"\nexport KUBERNETES_PROVIDER=\"none\" # the script from upstream doesnt seem to handle aws exactly right\nexport LOG_DUMP_SSH_KEY=\"~/.ssh/id_rsa\"\nexport LOG_DUMP_SSH_USER=\"ubuntu\"\nexport LOG_DUMP_EXTRA_FILES=\"cloud-init-output.log cloud-init.log kube-proxy.log containers/*\"\nexport LOG_DUMP_SYSTEMD_JOURNAL=true\nARTIFACTS=${ARTIFACTS:-\"./_artifacts\"}\n\nfunction log_dump_custom_get_instances() {\n    local -r type=$1\n    local filter=''\n    if [ $type == \"control_plane\" ]; then\n        filter=\"Name=tag:k8s.io/role/master,Values=1\"\n    else\n        filter=\"Name=tag:k8s.io/role/node,Values=1\"\n    fi\n    nodes=$(aws ec2 describe-instances \\\n        --filters \"Name=tag:KubernetesCluster,Values=${KOPS_CLUSTER_NAME}\" \"$filter\" \\\n        --query \"Reservations[*].Instances[*].PublicDnsName\" --output text)\n\n    # Container logs are symlinks and need a slightly different chmod\n    # log-dump-ssh comes the upstream log-dump.sh script\n    for node in $nodes ; do log-dump-ssh $node \"sudo chmod a+r /var/log/containers/*\" || true ; done\n\n    echo \"$nodes\"\n}\nexport -f log_dump_custom_get_instances\n\n# fix protocol error: filename does not match request\n# this seems to happen for the symlink'd files\nfunction scp() {\n    command scp -T \"$@\"\n}\nexport -f scp\n\nsource ./log-dump/log-dump.sh $ARTIFACTS\n", "num_lines": 58}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\nREPOSITORY_NAME=\"${1}\"\nQUERY='[.imageDetails[] | select(.imageTags != null)] | sort_by(.imagePushedAt)|reverse|first|.imageTags[0]'\nTAG=$(aws --region us-east-1 ecr-public  describe-images \\\n          --repository-name \"${REPOSITORY_NAME}\" | \\\n          jq -r \"${QUERY}\")\necho ${TAG}\n", "num_lines": 24}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#            http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n# Ignoring preflight check failures since we only need the env vars set\n\nif [ \"$(uname)\" == \"Darwin\" ]\nthen\n    OS=\"darwin\"\n    ARCH=\"amd64\"\nelse\n    OS=\"linux\"\n    ARCH=\"amd64\"\nfi\n\nmkdir -p ${BASEDIR}/bin\n\nif [ ! -x ${KOPS} ]\nthen\n    echo \"Determine kops version\"\n    echo \"Download kops\"\n    KOPS_URL=\"https://eks-d-postsubmit-artifacts.s3.us-west-2.amazonaws.com/kops/${KOPS_VERSION}/${OS}/${ARCH}/kops\"\n    set -x\n    curl -L -o ${KOPS} \"${KOPS_URL}\"\n    chmod 755 ${KOPS}\n    set +x\nfi\n\nif ! command -v kubectl &> /dev/null\nthen\n    echo \"kubectl could not be found. Downloading...\"\n    KUBECTL_VERSION=$(cat ${BASEDIR}/../../projects/kubernetes/kubernetes/${RELEASE_BRANCH}/GIT_TAG)\n    KUBECTL_PATH=${BASEDIR}/bin/kubectl\n    COUNT=0\n    while [ ! \"$(${KUBECTL_PATH} version)\" ]; do\n        sleep 5\n        COUNT=$(expr $COUNT + 1)\n        if [ $COUNT -gt 120 ]\n        then\n            echo \"Failed to download kubectl\"\n            exit 1\n        fi\n        set -x\n        curl -sSL \"${ARTIFACT_URL}/kubernetes/${KUBECTL_VERSION}/bin/${OS}/${ARCH}/kubectl\" -o ${KUBECTL_PATH}\n        chmod +x ${KUBECTL_PATH}\n        set +x\n    done\nfi\n\nif ! command -v helm &> /dev/null\nthen\n    curl -s https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | HELM_INSTALL_DIR=${BASEDIR}/bin bash\nfi\n\nif ! command -v sonobuoy &> /dev/null\nthen\n    echo \"Download sonobuoy\"\n    SONOBUOY=https://github.com/vmware-tanzu/sonobuoy/releases/download/v0.56.2/sonobuoy_0.56.2_${OS}_${ARCH}.tar.gz\n    wget -qO- ${SONOBUOY} |tar -xz sonobuoy\n    chmod 755 sonobuoy\n    mv sonobuoy ./bin\nfi\n\necho \"$(which kops): $(kops version)\"\necho \"$(which kubectl): $(kubectl version --client=true --short)\"\necho \"$(which helm): $(helm version --short)\"\necho \"$(which sonobuoy): $(sonobuoy version --short)\"\n\nexit 0\n", "num_lines": 85}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nif [ \"$TEST_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nBASEDIR=$(dirname \"$0\")\n\ncat << EOF > config\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile conformance-test]\nrole_arn=$TEST_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nsource_profile=default\nEOF\nexport AWS_CONFIG_FILE=$(pwd)/config\nexport AWS_PROFILE=conformance-test\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\nDEFAULT_KOPS_ZONE_NAME=\"prod-build-pdx.kops-ci.model-rocket.aws.dev\"\nKOPS_ZONE_NAME=${KOPS_ZONE_NAME:-\"${DEFAULT_KOPS_ZONE_NAME}\"}\nexport NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}\nexport KOPS_CLUSTER_NAME=${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-$(git rev-parse --short HEAD).$(echo $RANDOM | md5sum | head -c 4).${KOPS_ZONE_NAME}\n${BASEDIR}/run_all.sh\n", "num_lines": 48}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -exo pipefail\nBASEDIR=$(dirname \"$0\")\ncd ${BASEDIR}\n\nfunction cleanup()\n{\n  echo 'Deleting...'\n  ./gather_logs.sh || true\n  ./delete_cluster.sh\n  ./delete_store.sh\n}\n\nfunction cleanup_and_error()\n{\n  cleanup\n  exit 255;\n}\n\necho \"This script will create a cluster, run tests and tear it down\"\nsource ./set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n./install_requirements.sh\nif [[ \"${KOPS_STATE_STORE}\" != \"\" ]]; then\n  for cluster_name in $(aws s3 ls ${KOPS_STATE_STORE}); do\n    if [[ \"${cluster_name}\" == \"${RELEASE_BRANCH}-${NODE_ARCHITECTURE}-\"* ]]; then\n      # Only delete if older than a day, get timestamp from config file in s3\n      cluster_fqdn=\"$(echo ${cluster_name}|tr -d \"/\")\"\n      config=$(aws s3 ls ${KOPS_STATE_STORE}/${cluster_fqdn}/config)\n      createDate=$(echo $config | awk {'print $1\" \"$2'})\n      createDate=$(date -d\"$createDate\" +%s)\n      olderThan=$(date --date \"1 day ago\" +%s)\n      if [[ $createDate -lt $olderThan ]]; then\n        echo \"Deleting cluster ${cluster_fqdn}\"\n        ${KOPS} delete cluster --state \"${KOPS_STATE_STORE}\" --name ${cluster_fqdn} --yes\n        aws s3 rm --recursive \"${KOPS_STATE_STORE}/${cluster_name}\"\n      fi\n    fi\n  done\nfi\ntrap cleanup_and_error SIGINT SIGTERM ERR\n./create_values_yaml.sh\n./create_configuration.sh\n./create_cluster.sh\n./set_nodeport_access.sh\n./cluster_wait.sh\n./validate_dns.sh\n./run_tests.sh\n./validate_eks.sh\n./run_sonobuoy.sh\n\n# avoid trying to clean up twice\ntrap '' SIGINT SIGTERM ERR\n\ncleanup\n", "num_lines": 70}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\nBASEDIR=$(dirname \"$0\")\necho \"This script will create a cluster\"\ncd \"$BASEDIR\"\nsource ./set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n./install_requirements.sh\n./create_values_yaml.sh\n./create_configuration.sh\n./create_cluster.sh\necho\necho \"Run ./cluster_wait.sh\"\n", "num_lines": 28}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nCONFORMANCE_IMAGE=registry.k8s.io/conformance:${KUBERNETES_VERSION}\necho \"Testing cluster ${KOPS_CLUSTER_NAME}\"\n\nCOUNT=0\nwhile ! sonobuoy --context ${KOPS_CLUSTER_NAME} run --mode=certified-conformance --wait --kube-conformance-image ${CONFORMANCE_IMAGE}\ndo\n  sonobuoy --context ${KOPS_CLUSTER_NAME} delete --all --wait||true\n  sleep 5\n  COUNT=$(expr $COUNT + 1)\n  if [ $COUNT -gt 3 ]\n  then\n    echo \"Failed to run sonobuoy\"\n    exit 1\n  fi\n  echo 'Waiting for the cluster to be ready...'\ndone\n\nresults=''\nfunction save_results() {\n  local run=$1\n  \n  results=$(sonobuoy --context ${KOPS_CLUSTER_NAME} retrieve)\n  mv $results \"./${KOPS_CLUSTER_NAME}/$results\"\n  results=\"./${KOPS_CLUSTER_NAME}/$results\"\n  mkdir -p ./${KOPS_CLUSTER_NAME}/results\n  tar xzf $results -C ./${KOPS_CLUSTER_NAME}/results\n  if [ -w /logs/artifacts ]\n  then\n    mkdir -p /logs/artifacts/$NODE_ARCHITECTURE-$run\n    cp ./${KOPS_CLUSTER_NAME}/results/plugins/e2e/results/global/* /logs/artifacts/$NODE_ARCHITECTURE-$run\n  fi\n\n  sonobuoy results --plugin e2e ${results}\n  if sonobuoy results --plugin e2e ${results} | grep 'Status: passed'; then\n    return 0\n  else\n    return 1\n  fi\n}\n\nCOUNT=1\nwhile ! save_results $COUNT; do\n  # retry failed conformance tests up to 3 times\n  echo \"Rerunning failed conformace tests\"\n  COUNT=$(expr $COUNT + 1)\n  if [ $COUNT -gt 4 ]; then\n    echo \"Conformance test still failing after reruns\"\n    exit 1\n  fi\n  sonobuoy --context ${KOPS_CLUSTER_NAME} delete --all --wait\n  sonobuoy --context ${KOPS_CLUSTER_NAME} run --rerun-failed ${results} --wait --kube-conformance-image ${CONFORMANCE_IMAGE}  \ndone\n", "num_lines": 74}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nfunction fail {\n  echo $1 >&2\n  exit 1\n}\n\nfunction retry {\n  local n=1\n  local max=5\n  local delay=1\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n/$max:\"\n        sleep $delay;\n      else\n        fail \"The command has failed after $n attempts.\"\n      fi\n    }\n  done\n}\n\nfunction k {\n    retry kubectl --context ${KOPS_CLUSTER_NAME} \"$@\"\n}\n\nfunction node_driver_registrar_expect {\n    echo \"node_driver_registrar_expect\"\n    k logs --selector app=csi-mockplugin --container node-driver-registrar  | \\\n        grep \"Registration Server started at: /registration/io.kubernetes.storage.mock-reg.sock\"\n}\n\nfunction liveness_probe_expect {\n    echo \"liveness_probe_expect\"\n    k logs --selector app=csi-mockplugin --container liveness-probe | \\\n        grep \"io.kubernetes.storage.mock\"\n}\n\nfunction provisioning_expect {\n    echo \"provisioning_expect\"\n    [ $(k get events --field-selector involvedObject.name=example-pvc,reason=ProvisioningSucceeded | wc -l) -ge 1 ]\n}\n\nfunction attach_expect {\n    echo \"attach_expect\"\n    k logs --selector app=csi-mockplugin --container csi-attacher | \\\n        grep \"Fully attached\"\n}\n\nfunction resize_expect {\n    echo \"resize_expect\"\n    [ $(k get events --field-selector involvedObject.name=example-pvc,reason=VolumeResizeSuccessful | wc -l) -ge 1 ]    \n}\n\nfunction validate_csi {\n    # Launch mock csi driver and validate all sidecars launch and trigger specific\n    # events and/or log messages\n    # Not a full suite but at least verifies all containers launch and \n    # executes some of the flows\n\n    ${KOPS} toolbox template --template ${BASEDIR}/tests/csi/deploy/csi-mock-driver-deployment.yaml.tpl \\\n        --values ./${KOPS_CLUSTER_NAME}/values.yaml > \"./${KOPS_CLUSTER_NAME}/csi-mock-driver-deployment.yaml\"\n\n    k apply -f ${BASEDIR}/tests/csi/deploy/csi-mock-driver-rbac.yaml\n\n    k apply -f \"./${KOPS_CLUSTER_NAME}/csi-mock-driver-deployment.yaml\"\n\n    k wait deploy/csi-mockplugin --for condition=available --timeout=5m\n    \n    retry node_driver_registrar_expect\n    retry liveness_probe_expect\n\n    k apply -f \"tests/csi/pvc-test.yaml\"\n    retry provisioning_expect\n    \n    k apply -f tests/csi/pod-test.yaml \n    k wait pod/web-server --for condition=ready --timeout=5m\n    retry attach_expect\n\n    k patch pvc example-pvc -p '{\"spec\":{\"resources\":{\"requests\":{\"storage\": \"2Mi\"}}}}'  \n    retry resize_expect\n\n}\n\nfunction etcd_expect {\n    echo \"etcd_expect\"\n    [ $(k exec etcd0  -- etcdctl --endpoints=http://etcd0:2379 member list | wc -l) = 3 ]\n}\n\nfunction validate_etcd {\n    # Not a full suite\n    # Launch a 3 node etcd cluster using etcd images to validate they launch correctly\n    \n    ${KOPS} toolbox template --template ${BASEDIR}/tests/etcd/deploy/etcd.yaml.tpl \\\n        --values ./${KOPS_CLUSTER_NAME}/values.yaml > \"./${KOPS_CLUSTER_NAME}/etcd.yaml\"\n    \n    k apply -f \"./${KOPS_CLUSTER_NAME}/etcd.yaml\"\n    k wait pod/etcd0 --for condition=ready --timeout=5m\n    k wait pod/etcd1 --for condition=ready --timeout=5m\n    k wait pod/etcd2 --for condition=ready --timeout=5m\n    retry etcd_expect\n\n}\n\nvalidate_csi\nvalidate_etcd\n", "num_lines": 128}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nexport DEFAULT_RELEASE_BRANCH=$(cat ${BASE_DIRECTORY}/release/DEFAULT_RELEASE_BRANCH)\nexport RELEASE_BRANCH=${RELEASE_BRANCH:-\"${DEFAULT_RELEASE_BRANCH}\"}\nRELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-development}\nexport DEFAULT_RELEASE=$(cat ${BASE_DIRECTORY}/release/${RELEASE_BRANCH}/${RELEASE_ENVIRONMENT}/RELEASE)\nexport RELEASE=${RELEASE:-${DEFAULT_RELEASE}}\nexport ARTIFACT_BASE_URL=\"https://distro.eks.amazonaws.com\"\nexport NODE_INSTANCE_TYPE=${NODE_INSTANCE_TYPE:-t3.medium}\nexport NODE_ARCHITECTURE=${NODE_ARCHITECTURE:-amd64}\nexport UBUNTU_RELEASE=${UBUNTU_RELEASE:-focal-20.04}\nexport IPV6=${IPV6:-false}\nexport KOPS_VERSION=\"1.26.3\"\n\nif [ -n \"$ARTIFACT_BUCKET\" ]; then\n    export ARTIFACT_BASE_URL=\"https://$ARTIFACT_BUCKET.s3.amazonaws.com\"\nfi\n\nif [ \"${PREFLIGHT_CHECK_PASSED:-false}\" != \"true\" ]\nthen\n    PREFLIGHT_CHECK_PASSED=true\n    GOOD=\"\\xE2\\x9C\\x94\"\n    BAD=\"\\xE2\\x9D\\x8C\"\n    export AWS_DEFAULT_REGION=${AWS_DEFAULT_REGION:-${AWS_REGION}}\n    export AWS_REGION=\"${AWS_DEFAULT_REGION}\"\n    if [ -z \"$AWS_DEFAULT_REGION\" ]; then\n        PREFLIGHT_CHECK_PASSED=false\n        echo -e \"${BAD} AWS_REGION must be set and exported\"\n    else\n        echo -e \"${GOOD} AWS_REGION=${AWS_REGION}\"\n    fi\n\n    if ! aws sts get-caller-identity --query Account --output text >/dev/null 2>/dev/null\n    then\n        PREFLIGHT_CHECK_PASSED=false\n        echo -e \"${BAD} AWS CLI failed to authenticate\"\n    else\n        echo -e \"${GOOD} AWS CLI authenticated\"\n    fi\n\n    if [ -z \"$KOPS_STATE_STORE\" ]; then\n        PREFLIGHT_CHECK_PASSED=false\n        echo -e \"${BAD} KOPS_STATE_STORE must be set and exported\"\n    else\n        echo -e \"${GOOD} KOPS_STATE_STORE=${KOPS_STATE_STORE}\"\n    fi\n    if [[ \"${KOPS_STATE_STORE}\" != s3://* ]]\n    then\n        export KOPS_STATE_STORE=\"s3://${KOPS_STATE_STORE}\"\n    fi\n    export BUCKET_NAME=${KOPS_STATE_STORE#\"s3://\"}\n\n    if [ -z \"$KOPS_CLUSTER_NAME\" ]; then\n        PREFLIGHT_CHECK_PASSED=false\n        echo -e \"${BAD} KOPS_CLUSTER_NAME must be set and exported\"\n    else\n        echo -e \"${GOOD} KOPS_CLUSTER_NAME=${KOPS_CLUSTER_NAME}\"\n    fi\nfi\nexport PREFLIGHT_CHECK_PASSED\n\nexport KUBERNETES_VERSION=$(cat ../../projects/kubernetes/kubernetes/${RELEASE_BRANCH}/GIT_TAG)\nexport IMAGE_REPO=${IMAGE_REPO:-public.ecr.aws/eks-distro}\nexport ARTIFACT_URL=${ARTIFACT_URL:-$ARTIFACT_BASE_URL/kubernetes-${RELEASE_BRANCH}/releases/${RELEASE}/artifacts}\nexport CNI_VERSION=$(cat ../../projects/containernetworking/plugins/${RELEASE_BRANCH}/GIT_TAG)\nexport CNI_VERSION_URL=${ARTIFACT_URL}/plugins/${CNI_VERSION}/cni-plugins-linux-${NODE_ARCHITECTURE}-${CNI_VERSION}.tar.gz\nexport CNI_ASSET_HASH_STRING=${CNI_ASSET_HASH_STRING:-sha256:$(curl -s ${CNI_VERSION_URL}.sha256 | cut -f1 -d' ')}\nexport KOPS_BASE_URL=https://eks-d-postsubmit-artifacts.s3.amazonaws.com/kops/$KOPS_VERSION\nexport KOPS=bin/kops\nmkdir -p bin\nexport PATH=`pwd`/bin:${PATH}\n", "num_lines": 86}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\nBASEDIR=$(dirname \"$0\")\nsource ${BASEDIR}/set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\n#\n# NodePort setting\n#\nexport KOPS_FEATURE_FLAGS=SpecOverrideFlag\n${KOPS} edit cluster --name \"${KOPS_CLUSTER_NAME}\" --set 'cluster.spec.nodePortAccess=0.0.0.0/0'\n\n\nADDITIONAL_ARGS=\"\"\nif [ -n \"$NODE_INSTANCE_PROFILE\" ]; then\n    ADDITIONAL_ARGS=\"--lifecycle-overrides IAMRole=ExistsAndWarnIfChanges,IAMRolePolicy=ExistsAndWarnIfChanges,IAMInstanceProfileRole=ExistsAndWarnIfChanges\"\nfi\n\n${KOPS} update cluster --yes $ADDITIONAL_ARGS\n", "num_lines": 35}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# In prow we have occasional dns issues after a cluster has been created\n# Wait for 60 seconds giving both dns pods a chance to get the latest\n# ip for the api server.  Printing out the results to potentially\n# make debugging easier\n\nset -eo pipefail\nBASEDIR=$(dirname \"$0\")\ncd \"$BASEDIR\"\nsource ./set_environment.sh\n$PREFLIGHT_CHECK_PASSED || exit 1\n\nAPISERVER=\"api.$KOPS_CLUSTER_NAME\"\nSUCCESS_COUNT=0\nwhile [ $SUCCESS_COUNT -lt 8 ]\ndo\n  API_SERVER_IP=$(dig +short $APISERVER)\n  if [ -z \"$API_SERVER_IP\" ]; then\n    echo \"$APISERVER did not resolve!\"\n    SUCCESS_COUNT=0\n  else\n    echo \"$APISERVER resolves to $API_SERVER_IP\"\n    SUCCESS_COUNT=$((SUCCESS_COUNT+1))\n  fi\n  \n  sleep 5s\ndone\n\nkubectl --context ${KOPS_CLUSTER_NAME} config set-cluster ${KOPS_CLUSTER_NAME} \\\n    --insecure-skip-tls-verify=true --server=https://${API_SERVER_IP}\n", "num_lines": 45}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nkubectl --context $KOPS_CLUSTER_NAME get po --all-namespaces -o json | jq -r '.items[].spec.containers[].image' | sort -u\n", "num_lines": 17}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Call this to dump all control_plane and node logs into the folder specified in $1\n# (defaults to _artifacts). Only works if the provider supports SSH.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nreadonly local_report_dir=\"${1:-_artifacts}\"\nreport_dir=\"\"\nreadonly gcs_artifacts_dir=\"${2:-}\"\nreadonly logexporter_namespace=\"${3:-logexporter}\"\n\n# In order to more trivially extend log-dump for custom deployments,\n# check for a function named log_dump_custom_get_instances. If it's\n# defined, we assume the function can me called with one argument, the\n# role, which is either \"control_plane\" or \"node\".\necho 'Checking for custom logdump instances, if any'\nif [[ $(type -t log_dump_custom_get_instances) == \"function\" ]]; then\n  readonly use_custom_instance_list=yes\nelse\n  readonly use_custom_instance_list=\nfi\n\nreadonly control_plane_ssh_supported_providers=\"gce aws\"\nreadonly node_ssh_supported_providers=\"gce gke aws\"\nreadonly gcloud_supported_providers=\"gce gke\"\n\nreadonly control_plane_logfiles=\"kube-apiserver.log kube-apiserver-audit.log kube-scheduler.log kube-controller-manager.log etcd.log etcd-events.log glbc.log cluster-autoscaler.log kube-addon-manager.log konnectivity-server.log fluentd.log kubelet.cov\"\nreadonly node_logfiles=\"kube-proxy.log fluentd.log node-problem-detector.log kubelet.cov\"\nreadonly node_systemd_services=\"node-problem-detector\"\nreadonly hollow_node_logfiles=\"kubelet-hollow-node-*.log kubeproxy-hollow-node-*.log npd-hollow-node-*.log\"\nreadonly aws_logfiles=\"cloud-init-output.log\"\nreadonly gce_logfiles=\"startupscript.log\"\nreadonly kern_logfile=\"kern.log\"\nreadonly initd_logfiles=\"docker/log\"\nreadonly supervisord_logfiles=\"kubelet.log supervisor/supervisord.log supervisor/kubelet-stdout.log supervisor/kubelet-stderr.log supervisor/docker-stdout.log supervisor/docker-stderr.log\"\nreadonly systemd_services=\"kubelet kubelet-monitor kube-container-runtime-monitor ${LOG_DUMP_SYSTEMD_SERVICES:-docker}\"\nreadonly extra_log_files=\"${LOG_DUMP_EXTRA_FILES:-}\"\nreadonly extra_systemd_services=\"${LOG_DUMP_SAVE_SERVICES:-}\"\nreadonly dump_systemd_journal=\"${LOG_DUMP_SYSTEMD_JOURNAL:-false}\"\n\n# Root directory for Kubernetes files on Windows nodes.\nWINDOWS_K8S_DIR=\"C:\\\\etc\\\\kubernetes\"\n# Directory where Kubernetes log files will be stored on Windows nodes.\nexport WINDOWS_LOGS_DIR=\"${WINDOWS_K8S_DIR}\\\\logs\"\n# Log files found in WINDOWS_LOGS_DIR on Windows nodes:\nreadonly windows_node_logfiles=\"kubelet.log kube-proxy.log docker.log docker_images.log csi-proxy.log\"\n# Log files found in other directories on Windows nodes:\nreadonly windows_node_otherfiles=\"C:\\\\Windows\\\\MEMORY.dmp\"\n\n# Limit the number of concurrent node connections so that we don't run out of\n# file descriptors for large clusters.\nreadonly max_dump_processes=25\n\n# Indicator variable whether we experienced a significant failure during\n# logexporter creation or execution.\nlogexporter_failed=0\n\n# Percentage of nodes that must be logexported successfully (otherwise the\n# process will exit with a non-zero exit code).\nreadonly log_dump_expected_success_percentage=\"${LOG_DUMP_EXPECTED_SUCCESS_PERCENTAGE:-0}\"\n\n# Example:  kube::util::trap_add 'echo \"in trap DEBUG\"' DEBUG\n# See: http://stackoverflow.com/questions/3338030/multiple-bash-traps-for-the-same-signal\nkube::util::trap_add() {\n  local trap_add_cmd\n  trap_add_cmd=$1\n  shift\n\n  for trap_add_name in \"$@\"; do\n    local existing_cmd\n    local new_cmd\n\n    # Grab the currently defined trap commands for this trap\n    existing_cmd=$(trap -p \"${trap_add_name}\" |  awk -F\"'\" '{print $2}')\n\n    if [[ -z \"${existing_cmd}\" ]]; then\n      new_cmd=\"${trap_add_cmd}\"\n    else\n      new_cmd=\"${trap_add_cmd};${existing_cmd}\"\n    fi\n\n    # Assign the test. Disable the shellcheck warning telling that trap\n    # commands should be single quoted to avoid evaluating them at this\n    # point instead evaluating them at run time. The logic of adding new\n    # commands to a single trap requires them to be evaluated right away.\n    # shellcheck disable=SC2064\n    trap \"${new_cmd}\" \"${trap_add_name}\"\n  done\n}\n\n# Opposite of kube::util::ensure-temp-dir()\nkube::util::cleanup-temp-dir() {\n  rm -rf \"${KUBE_TEMP}\"\n}\n\n# Create a temp dir that'll be deleted at the end of this bash session.\n#\n# Vars set:\n#   KUBE_TEMP\nkube::util::ensure-temp-dir() {\n  if [[ -z ${KUBE_TEMP-} ]]; then\n    KUBE_TEMP=$(mktemp -d 2>/dev/null || mktemp -d -t kubernetes.XXXXXX)\n    kube::util::trap_add kube::util::cleanup-temp-dir EXIT\n  fi\n}\n\n# Use the gcloud defaults to find the project.  If it is already set in the\n# environment then go with that.\n#\n# Vars set:\n#   PROJECT\n#   NETWORK_PROJECT\n#   PROJECT_REPORTED\nfunction detect-project() {\n  if [[ -z \"${PROJECT-}\" ]]; then\n    PROJECT=$(gcloud config list project --format 'value(core.project)')\n  fi\n\n  NETWORK_PROJECT=${NETWORK_PROJECT:-${PROJECT}}\n\n  if [[ -z \"${PROJECT-}\" ]]; then\n    echo \"Could not detect Google Cloud Platform project.  Set the default project using \" >&2\n    echo \"'gcloud config set project <PROJECT>'\" >&2\n    exit 1\n  fi\n  if [[ -z \"${PROJECT_REPORTED-}\" ]]; then\n    echo \"Project: ${PROJECT}\" >&2\n    echo \"Network Project: ${NETWORK_PROJECT}\" >&2\n    echo \"Zone: ${ZONE}\" >&2\n    PROJECT_REPORTED=true\n  fi\n}\n\n# Detect Linux and Windows nodes created in the instance group.\n#\n# Vars set:\n#   NODE_NAMES\n#   INSTANCE_GROUPS\n#   WINDOWS_NODE_NAMES\n#   WINDOWS_INSTANCE_GROUPS\nfunction detect-node-names() {\n  # These prefixes must not be prefixes of each other, so that they can be used to\n  # detect mutually exclusive sets of nodes.\n  local -r NODE_INSTANCE_PREFIX=${NODE_INSTANCE_PREFIX:-\"${INSTANCE_PREFIX}-minion\"}\n  local -r WINDOWS_NODE_INSTANCE_PREFIX=${WINDOWS_NODE_INSTANCE_PREFIX:-\"${INSTANCE_PREFIX}-windows-node\"}\n  detect-project\n  INSTANCE_GROUPS=()\n  INSTANCE_GROUPS+=($(gcloud compute instance-groups managed list \\\n    --project \"${PROJECT}\" \\\n    --filter \"name ~ '${NODE_INSTANCE_PREFIX}-.+' AND zone:(${ZONE})\" \\\n    --format='value(name)' || true))\n  WINDOWS_INSTANCE_GROUPS=()\n  WINDOWS_INSTANCE_GROUPS+=($(gcloud compute instance-groups managed list \\\n    --project \"${PROJECT}\" \\\n    --filter \"name ~ '${WINDOWS_NODE_INSTANCE_PREFIX}-.+' AND zone:(${ZONE})\" \\\n    --format='value(name)' || true))\n\n  NODE_NAMES=()\n  if [[ -n \"${INSTANCE_GROUPS[@]:-}\" ]]; then\n    for group in \"${INSTANCE_GROUPS[@]}\"; do\n      NODE_NAMES+=($(gcloud compute instance-groups managed list-instances \\\n        \"${group}\" --zone \"${ZONE}\" --project \"${PROJECT}\" \\\n        --format='value(instance)'))\n    done\n  fi\n  # Add heapster node name to the list too (if it exists).\n  if [[ -n \"${HEAPSTER_MACHINE_TYPE:-}\" ]]; then\n    NODE_NAMES+=(\"${NODE_INSTANCE_PREFIX}-heapster\")\n  fi\n  WINDOWS_NODE_NAMES=()\n  if [[ -n \"${WINDOWS_INSTANCE_GROUPS[@]:-}\" ]]; then\n    for group in \"${WINDOWS_INSTANCE_GROUPS[@]}\"; do\n      WINDOWS_NODE_NAMES+=($(gcloud compute instance-groups managed \\\n        list-instances \"${group}\" --zone \"${ZONE}\" --project \"${PROJECT}\" \\\n        --format='value(instance)'))\n    done\n  fi\n\n  echo \"INSTANCE_GROUPS=${INSTANCE_GROUPS[*]:-}\" >&2\n  echo \"NODE_NAMES=${NODE_NAMES[*]:-}\" >&2\n}\n\n# Detect the IP for the control_plane\n#\n# Assumed vars:\n#   CONTROL_PLANE_NAME\n#   ZONE\n#   REGION\n# Vars set:\n#   KUBE_CONTROL_PLANE\n#   KUBE_CONTROL_PLANE_IP\nfunction detect-control_plane() {\n  detect-project\n  KUBE_CONTROL_PLANE=${CONTROL_PLANE_NAME}\n  echo \"Trying to find control_plane named '${CONTROL_PLANE_NAME}'\" >&2\n  if [[ -z \"${KUBE_CONTROL_PLANE_IP-}\" ]]; then\n    local control_plane_address_name=\"${CONTROL_PLANE_NAME}-ip\"\n    echo \"Looking for address '${control_plane_address_name}'\" >&2\n    if ! KUBE_CONTROL_PLANE_IP=$(gcloud compute addresses describe \"${control_plane_address_name}\" \\\n      --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)') || \\\n      [[ -z \"${KUBE_CONTROL_PLANE_IP-}\" ]]; then\n      echo \"Could not detect Kubernetes control_plane node.  Make sure you've launched a cluster with 'kube-up.sh'\" >&2\n      exit 1\n    fi\n  fi\n  if [[ -z \"${KUBE_CONTROL_PLANE_INTERNAL_IP-}\" ]] && [[ ${GCE_PRIVATE_CLUSTER:-} == \"true\" ]]; then\n      local control_plane_address_name=\"${CONTROL_PLANE_NAME}-internal-ip\"\n      echo \"Looking for address '${control_plane_address_name}'\" >&2\n      if ! KUBE_CONTROL_PLANE_INTERNAL_IP=$(gcloud compute addresses describe \"${control_plane_address_name}\" \\\n        --project \"${PROJECT}\" --region \"${REGION}\" -q --format='value(address)') || \\\n        [[ -z \"${KUBE_CONTROL_PLANE_INTERNAL_IP-}\" ]]; then\n        echo \"Could not detect Kubernetes control_plane node.  Make sure you've launched a cluster with 'kube-up.sh'\" >&2\n        exit 1\n      fi\n  fi\n  echo \"Using control_plane: $KUBE_CONTROL_PLANE (external IP: $KUBE_CONTROL_PLANE_IP; internal IP: ${KUBE_CONTROL_PLANE_INTERNAL_IP:-(not set)})\" >&2\n}\n\n# SSH to a node by name ($1) and run a command ($2).\nfunction setup() {\n  if [[ -z \"${use_custom_instance_list}\" ]]; then\n    echo \"Using gce provider, skipping check for LOG_DUMP_SSH_KEY and LOG_DUMP_SSH_USER\"\n    ZONE=\"${KUBE_GCE_ZONE:-us-central1-b}\"\n    REGION=\"${ZONE%-*}\"\n    INSTANCE_PREFIX=\"${KUBE_GCE_INSTANCE_PREFIX:-kubernetes}\"\n    CLUSTER_NAME=\"${CLUSTER_NAME:-${INSTANCE_PREFIX}}\"\n    CONTROL_PLANE_NAME=\"${INSTANCE_PREFIX}-control_plane\"\n    GCE_PRIVATE_CLUSTER=\"${KUBE_GCE_PRIVATE_CLUSTER:-false}\"\n    detect-project 2>&1\n  elif [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then\n    NUM_NODES=${NUM_NODES:-3}\n    echo \"Using 'use_custom_instance_list' with gke, skipping check for LOG_DUMP_SSH_KEY and LOG_DUMP_SSH_USER\"\n  elif [[ -z \"${LOG_DUMP_SSH_KEY:-}\" ]]; then\n    echo 'LOG_DUMP_SSH_KEY not set, but required when using log_dump_custom_get_instances'\n    exit 1\n  elif [[ -z \"${LOG_DUMP_SSH_USER:-}\" ]]; then\n    echo 'LOG_DUMP_SSH_USER not set, but required when using log_dump_custom_get_instances'\n    exit 1\n  fi\n}\n\nfunction log-dump-ssh() {\n  local host=\"$1\"\n  local cmd=\"$2\"\n\n  if [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    for (( i=0; i<5; i++)); do\n      if gcloud compute ssh --ssh-flag=\"-o LogLevel=quiet\" --ssh-flag=\"-o ConnectTimeout=30\" --project \"${PROJECT}\" --zone=\"${ZONE}\" \"${host}\" --command \"echo test > /dev/null\"; then\n        break\n      fi\n      sleep 5\n    done\n    # Then actually try the command.\n    gcloud compute ssh --ssh-flag=\"-o LogLevel=quiet\" --ssh-flag=\"-o ConnectTimeout=30\" --project \"${PROJECT}\" --zone=\"${ZONE}\" \"${host}\" --command \"${cmd}\"\n    return\n  fi\n\n  ssh -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${LOG_DUMP_SSH_KEY}\" \"${LOG_DUMP_SSH_USER}@${host}\" \"${cmd}\"\n}\n\n# Copy all files /var/log/{$3}.log on node $1 into local dir $2.\n# $3 should be a string array of file names.\n# This function shouldn't ever trigger errexit, but doesn't block stderr.\nfunction copy-logs-from-node() {\n    local -r node=\"${1}\"\n    local -r dir=\"${2}\"\n    shift\n    shift\n    local files=(\"$@\")\n    # Append \"*\"\n    # The * at the end is needed to also copy rotated logs (which happens\n    # in large clusters and long runs).\n    files=( \"${files[@]/%/*}\" )\n    # Prepend \"/var/log/\"\n    files=( \"${files[@]/#/\\/var\\/log\\/}\" )\n    # Comma delimit (even the singleton, or scp does the wrong thing), surround by braces.\n    local -r scp_files=\"{$(printf \"%s,\" \"${files[@]}\")}\"\n\n    if [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n      # get-serial-port-output lets you ask for ports 1-4, but currently (11/21/2016) only port 1 contains useful information\n      gcloud compute instances get-serial-port-output --project \"${PROJECT}\" --zone \"${ZONE}\" --port 1 \"${node}\" > \"${dir}/serial-1.log\" || true\n      gcloud compute scp --recurse --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}:${scp_files}\" \"${dir}\" > /dev/null || true\n    elif  [[ \"${KUBERNETES_PROVIDER}\" == \"aws\" ]]; then\n      local ip\n      ip=$(get_ssh_hostname \"${node}\")\n      scp -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${AWS_SSH_KEY}\" \"${SSH_USER}@${ip}:${scp_files}\" \"${dir}\" > /dev/null || true\n    elif  [[ -n \"${use_custom_instance_list}\" ]]; then\n      scp -oLogLevel=quiet -oConnectTimeout=30 -oStrictHostKeyChecking=no -i \"${LOG_DUMP_SSH_KEY}\" \"${LOG_DUMP_SSH_USER}@${node}:${scp_files}\" \"${dir}\" > /dev/null || true\n    else\n      echo \"Unknown cloud-provider '${KUBERNETES_PROVIDER}' and use_custom_instance_list is unset too - skipping logdump for '${node}'\"\n    fi\n}\n\n# Save logs for node $1 into directory $2. Pass in any non-common files in $3.\n# Pass in any non-common systemd services in $4.\n# $3 and $4 should be a space-separated list of files.\n# Set $5 to true to indicate it is on control_plane. Default to false.\n# This function shouldn't ever trigger errexit\nfunction save-logs() {\n    local -r node_name=\"${1}\"\n    local -r dir=\"${2}\"\n    local files=()\n    IFS=' ' read -r -a files <<< \"$3\"\n    local opt_systemd_services=\"${4:-\"\"}\"\n    local on_control_plane=\"${5:-\"false\"}\"\n\n    local extra=()\n    IFS=' ' read -r -a extra <<< \"$extra_log_files\"\n    files+=(\"${extra[@]}\")\n    if [[ -n \"${use_custom_instance_list}\" ]]; then\n      if [[ -n \"${LOG_DUMP_SAVE_LOGS:-}\" ]]; then\n        local dump=()\n        IFS=' ' read -r -a dump <<< \"${LOG_DUMP_SAVE_LOGS:-}\"\n        files+=(\"${dump[@]}\")\n      fi\n    else\n      local providerlogs=()\n      case \"${KUBERNETES_PROVIDER}\" in\n        gce|gke)\n          IFS=' ' read -r -a providerlogs <<< \"${gce_logfiles}\"\n          ;;\n        aws)\n          IFS=' ' read -r -a providerlogs <<< \"${aws_logfiles}\"\n          ;;\n      esac\n      files+=(\"${providerlogs[@]}\")\n    fi\n    local services\n    read -r -a services <<< \"${systemd_services} ${opt_systemd_services} ${extra_systemd_services}\"\n\n    if log-dump-ssh \"${node_name}\" \"command -v journalctl\" &> /dev/null; then\n        if [[ \"${on_control_plane}\" == \"true\" ]]; then\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-control_plane-installation.service\" > \"${dir}/kube-control_plane-installation.log\" || true\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-control_plane-configuration.service\" > \"${dir}/kube-control_plane-configuration.log\" || true\n        else\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-node-installation.service\" > \"${dir}/kube-node-installation.log\" || true\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -u kube-node-configuration.service\" > \"${dir}/kube-node-configuration.log\" || true\n        fi\n        log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise -k\" > \"${dir}/kern.log\" || true\n\n        for svc in \"${services[@]}\"; do\n            log-dump-ssh \"${node_name}\" \"sudo journalctl --output=cat -u ${svc}.service\" > \"${dir}/${svc}.log\" || true\n        done\n\n        if [[ \"$dump_systemd_journal\" == \"true\" ]]; then\n          log-dump-ssh \"${node_name}\" \"sudo journalctl --output=short-precise\" > \"${dir}/systemd.log\" || true\n        fi\n    else\n        local tmpfiles=()\n        for f in \"${kern_logfile}\" \"${initd_logfiles}\" \"${supervisord_logfiles}\"; do\n            IFS=' ' read -r -a tmpfiles <<< \"$f\"\n            files+=(\"${tmpfiles[@]}\")\n        done\n    fi\n\n    # Try dumping coverage profiles, if it looks like coverage is enabled in the first place.\n    if log-dump-ssh \"${node_name}\" \"stat /var/log/kubelet.cov\" &> /dev/null; then\n      if log-dump-ssh \"${node_name}\" \"command -v docker\" &> /dev/null; then\n        if [[ \"${on_control_plane}\" == \"true\" ]]; then\n          run-in-docker-container \"${node_name}\" \"kube-apiserver\" \"cat /tmp/k8s-kube-apiserver.cov\" > \"${dir}/kube-apiserver.cov\" || true\n          run-in-docker-container \"${node_name}\" \"kube-scheduler\" \"cat /tmp/k8s-kube-scheduler.cov\" > \"${dir}/kube-scheduler.cov\" || true\n          run-in-docker-container \"${node_name}\" \"kube-controller-manager\" \"cat /tmp/k8s-kube-controller-manager.cov\" > \"${dir}/kube-controller-manager.cov\" || true\n        else\n          run-in-docker-container \"${node_name}\" \"kube-proxy\" \"cat /tmp/k8s-kube-proxy.cov\" > \"${dir}/kube-proxy.cov\" || true\n        fi\n      else\n        echo 'Coverage profiles seem to exist, but cannot be retrieved from inside containers.'\n      fi\n    fi\n\n    echo 'Changing logfiles to be world-readable for download'\n    log-dump-ssh \"${node_name}\" \"sudo chmod -R a+r /var/log\" || true\n\n    echo \"Copying '${files[*]}' from ${node_name}\"\n    copy-logs-from-node \"${node_name}\" \"${dir}\" \"${files[@]}\"\n}\n\n# Saves a copy of the Windows Docker event log to ${WINDOWS_LOGS_DIR}\\docker.log\n# on node $1.\nfunction export-windows-docker-event-log() {\n    local -r node=\"${1}\"\n\n    local -r powershell_cmd=\"powershell.exe -Command \\\"\\$logs=\\$(Get-EventLog -LogName Application -Source Docker | Format-Table -Property TimeGenerated, EntryType, Message -Wrap); \\$logs | Out-File -FilePath '${WINDOWS_LOGS_DIR}\\\\docker.log'\\\"\"\n\n    # Retry up to 3 times to allow ssh keys to be properly propagated and\n    # stored.\n    for retry in {1..3}; do\n      if gcloud compute ssh --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}\" \\\n        --command \"$powershell_cmd\"; then\n        break\n      else\n        sleep 10\n      fi\n    done\n}\n\n# Saves prepulled Windows Docker images list to ${WINDOWS_LOGS_DIR}\\docker_images.log\n# on node $1.\nfunction export-windows-docker-images-list() {\n    local -r node=\"${1}\"\n\n    local -r powershell_cmd=\"powershell.exe -Command \\\"\\$logs=\\$(docker image list); \\$logs | Out-File -FilePath '${WINDOWS_LOGS_DIR}\\\\docker_images.log'\\\"\"\n\n    # Retry up to 3 times to allow ssh keys to be properly propagated and\n    # stored.\n    for retry in {1..3}; do\n      if gcloud compute ssh --project \"${PROJECT}\" --zone \"${ZONE}\" \"${node}\" \\\n        --command \"$powershell_cmd\"; then\n        break\n      else\n        sleep 10\n      fi\n    done\n}\n\n# Saves log files from diagnostics tool.(https://github.com/GoogleCloudPlatform/compute-image-tools/tree/control_plane/cli_tools/diagnostics)\nfunction save-windows-logs-via-diagnostics-tool() {\n    local node=\"${1}\"\n    local dest_dir=\"${2}\"\n\n    gcloud compute instances add-metadata \"${node}\" --metadata enable-diagnostics=true --project=\"${PROJECT}\" --zone=\"${ZONE}\"\n    local logs_archive_in_gcs\n    logs_archive_in_gcs=$(gcloud alpha compute diagnose export-logs \"${node}\" \"--zone=${ZONE}\" \"--project=${PROJECT}\" | tail -n 1)\n    local temp_local_path=\"${node}.zip\"\n    for retry in {1..20}; do\n      if gsutil mv \"${logs_archive_in_gcs}\" \"${temp_local_path}\"  > /dev/null 2>&1; then\n        echo \"Downloaded diagnostics log from ${logs_archive_in_gcs}\"\n        break\n      else\n        sleep 10\n      fi\n    done\n\n    if [[ -f \"${temp_local_path}\" ]]; then\n      unzip \"${temp_local_path}\" -d \"${dest_dir}\" > /dev/null\n      rm -f \"${temp_local_path}\"\n    fi\n}\n\n# Saves log files from SSH\nfunction save-windows-logs-via-ssh() {\n    local node=\"${1}\"\n    local dest_dir=\"${2}\"\n\n    export-windows-docker-event-log \"${node}\"\n    export-windows-docker-images-list \"${node}\"\n\n    local remote_files=()\n    for file in \"${windows_node_logfiles[@]}\"; do\n      remote_files+=( \"${WINDOWS_LOGS_DIR}\\\\${file}\" )\n    done\n    remote_files+=( \"${windows_node_otherfiles[@]}\" )\n\n    # TODO(pjh, yujuhong): handle rotated logs and copying multiple files at the\n    # same time.\n    for remote_file in \"${remote_files[@]}\"; do\n      # Retry up to 3 times to allow ssh keys to be properly propagated and\n      # stored.\n      for retry in {1..3}; do\n        if gcloud compute scp --recurse --project \"${PROJECT}\" \\\n          --zone \"${ZONE}\" \"${node}:${remote_file}\" \"${dest_dir}\" \\\n          > /dev/null; then\n          break\n        else\n          sleep 10\n        fi\n      done\n    done\n}\n\n# Save log files and serial console output from Windows node $1 into local\n# directory $2.\n# This function shouldn't ever trigger errexit.\nfunction save-logs-windows() {\n    local -r node=\"${1}\"\n    local -r dest_dir=\"${2}\"\n\n    if [[ ! \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n      echo \"Not saving logs for ${node}, Windows log dumping requires gcloud support\"\n      return\n    fi\n\n    if [[ \"${KUBERNETES_PROVIDER}\" == \"gke\" ]]; then\n      save-windows-logs-via-diagnostics-tool \"${node}\" \"${dest_dir}\"\n    else\n      save-windows-logs-via-ssh \"${node}\" \"${dest_dir}\"\n    fi\n\n    # Serial port 1 contains the Windows console output.\n    gcloud compute instances get-serial-port-output --project \"${PROJECT}\" \\\n      --zone \"${ZONE}\" --port 1 \"${node}\" > \"${dest_dir}/serial-1.log\" || true\n}\n\n# Execute a command in container $2 on node $1.\n# Uses docker because the container may not ordinarily permit direct execution.\nfunction run-in-docker-container() {\n  local node_name=\"$1\"\n  local container=\"$2\"\n  shift 2\n  log-dump-ssh \"${node_name}\" \"docker exec \\\"\\$(docker ps -f label=io.kubernetes.container.name=${container} --format \\\"{{.ID}}\\\")\\\" $*\"\n}\n\nfunction dump_control_planes() {\n  local control_plane_names=()\n  if [[ -n \"${use_custom_instance_list}\" ]]; then\n    while IFS='' read -r line; do control_plane_names+=(\"$line\"); done < <(log_dump_custom_get_instances control_plane)\n  elif [[ ! \"${control_plane_ssh_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    echo \"Control_Plane SSH not supported for ${KUBERNETES_PROVIDER}\"\n    return\n  elif [[ -n \"${KUBEMARK_CONTROL_PLANE_NAME:-}\" ]]; then\n    control_plane_names=( \"${KUBEMARK_CONTROL_PLANE_NAME}\" )\n  else\n    if ! (detect-control_plane); then\n      echo 'Control_Plane not detected. Is the cluster up?'\n      return\n    fi\n    control_plane_names=( \"${CONTROL_PLANE_NAME}\" )\n  fi\n\n  if [[ \"${#control_plane_names[@]}\" == 0 ]]; then\n    echo 'No control_planes found?'\n    return\n  fi\n\n  proc=${max_dump_processes}\n  for control_plane_name in \"${control_plane_names[@]}\"; do\n    control_plane_dir=\"${report_dir}/${control_plane_name}\"\n    mkdir -p \"${control_plane_dir}\"\n    save-logs \"${control_plane_name}\" \"${control_plane_dir}\" \"${control_plane_logfiles}\" \"\" \"true\" &\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n    fi\n  done\n  # Wait for any remaining processes.\n  if [[ proc -gt 0 && proc -lt ${max_dump_processes} ]]; then\n    wait\n  fi\n}\n\n# Dumps logs from nodes in the cluster. Linux nodes to dump logs from can be\n# specified via $1 or $use_custom_instance_list. If not specified then the nodes\n# to dump logs for will be detected using detect-node-names(); if Windows nodes\n# are present then they will be detected and their logs will be dumped too.\nfunction dump_nodes() {\n  local node_names=()\n  local windows_node_names=()\n  if [[ -n \"${1:-}\" ]]; then\n    echo 'Dumping logs for nodes provided as args to dump_nodes() function'\n    node_names=( \"$@\" )\n  elif [[ -n \"${use_custom_instance_list}\" ]]; then\n    echo 'Dumping logs for nodes provided by log_dump_custom_get_instances() function'\n    while IFS='' read -r line; do node_names+=(\"$line\"); done < <(log_dump_custom_get_instances node)\n  elif [[ ! \"${node_ssh_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    echo \"Node SSH not supported for ${KUBERNETES_PROVIDER}\"\n    return\n  else\n    echo 'Detecting nodes in the cluster'\n    detect-node-names &> /dev/null\n    if [[ -n \"${NODE_NAMES:-}\" ]]; then\n      node_names=( \"${NODE_NAMES[@]}\" )\n    fi\n    if [[ -n \"${WINDOWS_NODE_NAMES:-}\" ]]; then\n      windows_node_names=( \"${WINDOWS_NODE_NAMES[@]}\" )\n    fi\n  fi\n\n  if [[ \"${#node_names[@]}\" == 0 && \"${#windows_node_names[@]}\" == 0 ]]; then\n    echo 'No nodes found!'\n    return\n  fi\n\n  node_logfiles_all=\"${node_logfiles}\"\n  if [[ \"${ENABLE_HOLLOW_NODE_LOGS:-}\" == \"true\" ]]; then\n    node_logfiles_all=\"${node_logfiles_all} ${hollow_node_logfiles}\"\n  fi\n\n  linux_nodes_selected_for_logs=()\n  if [[ -n \"${LOGDUMP_ONLY_N_RANDOM_NODES:-}\" ]]; then\n    # We randomly choose 'LOGDUMP_ONLY_N_RANDOM_NODES' many nodes for fetching logs.\n    for index in $(shuf -i 0-$(( ${#node_names[*]} - 1 )) -n \"${LOGDUMP_ONLY_N_RANDOM_NODES}\")\n    do\n      linux_nodes_selected_for_logs+=(\"${node_names[$index]}\")\n    done\n  else\n    linux_nodes_selected_for_logs=( \"${node_names[@]}\" )\n  fi\n  all_selected_nodes=( \"${linux_nodes_selected_for_logs[@]}\" )\n  \n\n  proc=${max_dump_processes}\n  start=\"$(date +%s)\"\n  # log_dump_ssh_timeout is the maximal number of seconds the log dumping over\n  # SSH operation can take. Please note that the logic enforcing the timeout\n  # is only a best effort. The actual time of the operation may be longer\n  # due to waiting for all the child processes below.\n  log_dump_ssh_timeout_seconds=\"${LOG_DUMP_SSH_TIMEOUT_SECONDS:-}\"\n  for i in \"${!all_selected_nodes[@]}\"; do\n    node_name=\"${all_selected_nodes[$i]}\"\n    node_dir=\"${report_dir}/${node_name}\"\n    mkdir -p \"${node_dir}\"\n    if [[ \"${i}\" -lt \"${#linux_nodes_selected_for_logs[@]}\" ]]; then\n      # Save logs in the background. This speeds up things when there are\n      # many nodes.\n      save-logs \"${node_name}\" \"${node_dir}\" \"${node_logfiles_all}\" \"${node_systemd_services}\" &\n    else\n      save-logs-windows \"${node_name}\" \"${node_dir}\" &\n    fi\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n      now=\"$(date +%s)\"\n      if [[ -n \"${log_dump_ssh_timeout_seconds}\" && $((now - start)) -gt ${log_dump_ssh_timeout_seconds} ]]; then\n        echo \"WARNING: Hit timeout after ${log_dump_ssh_timeout_seconds} seconds, finishing log dumping over SSH shortly\"\n        break\n      fi\n    fi\n  done\n  # Wait for any remaining processes.\n  if [[ proc -gt 0 && proc -lt ${max_dump_processes} ]]; then\n    wait\n  fi\n}\n\n# Collect names of nodes which didn't run logexporter successfully.\n# This function examines NODE_NAMES but not WINDOWS_NODE_NAMES since logexporter\n# does not run on Windows nodes.\n#\n# Note: This step is O(#nodes^2) as we check if each node is present in the list of succeeded nodes.\n# Making it linear would add code complexity without much benefit (as it just takes ~1s for 5k nodes).\n# Assumes:\n#   NODE_NAMES\n# Sets:\n#   NON_LOGEXPORTED_NODES\nfunction find_non_logexported_nodes() {\n  local file=\"${gcs_artifacts_dir}/logexported-nodes-registry\"\n  echo \"Listing marker files ($file) for successful nodes...\"\n  succeeded_nodes=$(gsutil ls \"${file}\") || return 1\n  echo 'Successfully listed marker files for successful nodes'\n  NON_LOGEXPORTED_NODES=()\n  for node in \"${NODE_NAMES[@]}\"; do\n    if [[ ! \"${succeeded_nodes}\" =~ ${node} ]]; then\n      NON_LOGEXPORTED_NODES+=(\"${node}\")\n    fi\n  done\n}\n\n# This function examines NODE_NAMES but not WINDOWS_NODE_NAMES since logexporter\n# does not run on Windows nodes.\nfunction dump_nodes_with_logexporter() {\n  if [[ -n \"${use_custom_instance_list}\" ]]; then\n    echo 'Dumping logs for nodes provided by log_dump_custom_get_instances() function'\n    NODE_NAMES=()\n    while IFS='' read -r line; do NODE_NAMES+=(\"$line\"); done < <(log_dump_custom_get_instances node)\n  else\n    echo 'Detecting nodes in the cluster'\n    detect-node-names &> /dev/null\n  fi\n\n  if [[ -z \"${NODE_NAMES:-}\" ]]; then\n    echo 'No nodes found!'\n    return\n  fi\n\n  # Obtain parameters required by logexporter.\n  local -r service_account_credentials=\"$(base64 \"${GOOGLE_APPLICATION_CREDENTIALS}\" | tr -d '\\n')\"\n  local -r cloud_provider=\"${KUBERNETES_PROVIDER}\"\n  local -r enable_hollow_node_logs=\"${ENABLE_HOLLOW_NODE_LOGS:-false}\"\n  local -r logexport_sleep_seconds=\"$(( 90 + NUM_NODES / 3 ))\"\n  if [[ -z \"${ZONE_NODE_SELECTOR_DISABLED:-}\" ]]; then\n    local -r node_selector=\"${ZONE_NODE_SELECTOR_LABEL:-topology.kubernetes.io/zone}: ${ZONE}\"\n  fi\n\n  # Fill in the parameters in the logexporter daemonset template.\n  local -r tmp=\"${KUBE_TEMP}/logexporter\"\n  local -r manifest_yaml=\"${tmp}/logexporter-daemonset.yaml\"\n  mkdir -p \"${tmp}\"\n  local -r cwd=$(dirname \"${BASH_SOURCE[0]}\")\n  cp \"${cwd}/logexporter-daemonset.yaml\" \"${manifest_yaml}\"\n\n  sed -i'' -e \"s@{{.NodeSelector}}@${node_selector:-}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.LogexporterNamespace}}@${logexporter_namespace}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ServiceAccountCredentials}}@${service_account_credentials}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.CloudProvider}}@${cloud_provider}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.GCSPath}}@${gcs_artifacts_dir}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.EnableHollowNodeLogs}}@${enable_hollow_node_logs}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.DumpSystemdJournal}}@${dump_systemd_journal}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ExtraLogFiles}}@${extra_log_files}@g\" \"${manifest_yaml}\"\n  sed -i'' -e \"s@{{.ExtraSystemdServices}}@${extra_systemd_services}@g\" \"${manifest_yaml}\"\n\n  # Create the logexporter namespace, service-account secret and the logexporter daemonset within that namespace.\n  if ! kubectl create -f \"${manifest_yaml}\"; then\n    echo 'Failed to create logexporter daemonset.. falling back to logdump through SSH'\n    kubectl delete namespace \"${logexporter_namespace}\" || true\n    dump_nodes \"${NODE_NAMES[@]}\"\n    logexporter_failed=1\n    return\n  fi\n\n  # Periodically fetch list of already logexported nodes to verify\n  # if we aren't already done.\n  start=\"$(date +%s)\"\n  while true; do\n    now=\"$(date +%s)\"\n    if [[ $((now - start)) -gt ${logexport_sleep_seconds} ]]; then\n      echo 'Waiting for all nodes to be logexported timed out.'\n      break\n    fi\n    if find_non_logexported_nodes; then\n      if [[ -z \"${NON_LOGEXPORTED_NODES:-}\" ]]; then\n        break\n      fi\n    fi\n    sleep 15\n  done\n\n  # Store logs from logexporter pods to allow debugging log exporting process\n  # itself.\n  proc=${max_dump_processes}\n  kubectl get pods -n \"${logexporter_namespace}\" -o jsonpath='{range .items[*]}{.metadata.name}{\"\\t\"}{.spec.nodeName}{\"\\n\"}{end}' | (while read -r pod node; do\n    echo \"Fetching logs from ${pod} running on ${node}\"\n    mkdir -p \"${report_dir}/${node}\"\n    kubectl logs -n \"${logexporter_namespace}\" \"${pod}\" > \"${report_dir}/${node}/${pod}.log\" &\n\n    # We don't want to run more than ${max_dump_processes} at a time, so\n    # wait once we hit that many nodes. This isn't ideal, since one might\n    # take much longer than the others, but it should help.\n    proc=$((proc - 1))\n    if [[ proc -eq 0 ]]; then\n      proc=${max_dump_processes}\n      wait\n    fi\n  # Wait for any remaining processes.\n  done; wait)\n\n  # List registry of marker files (of nodes whose logexporter succeeded) from GCS.\n  for retry in {1..10}; do\n    if find_non_logexported_nodes; then\n      break\n    else\n      echo \"Attempt ${retry} failed to list marker files for successful nodes\"\n      if [[ \"${retry}\" == 10 ]]; then\n        echo 'Final attempt to list marker files failed.. falling back to logdump through SSH'\n        kubectl delete namespace \"${logexporter_namespace}\" || true\n        dump_nodes \"${NODE_NAMES[@]}\"\n        logexporter_failed=1\n        return\n      fi\n      sleep 2\n    fi\n  done\n\n  failed_nodes=()\n  # The following if is needed, because defaulting for empty arrays\n  # seems to treat them as non-empty with single empty string.\n  if [[ -n \"${NON_LOGEXPORTED_NODES:-}\" ]]; then\n    for node in \"${NON_LOGEXPORTED_NODES[@]:-}\"; do\n      echo \"Logexporter didn't succeed on node ${node}. Queuing it for logdump through SSH.\"\n      failed_nodes+=(\"${node}\")\n    done\n  fi\n\n  # If less than a certain ratio of the nodes got logexported, report an error.\n  if [[ $(((${#NODE_NAMES[@]} - ${#failed_nodes[@]}) * 100)) -lt $((${#NODE_NAMES[@]} * log_dump_expected_success_percentage )) ]]; then\n    logexporter_failed=1\n  fi\n\n  # Delete the logexporter resources and dump logs for the failed nodes (if any) through SSH.\n  kubectl get pods --namespace \"${logexporter_namespace}\" || true\n  kubectl delete namespace \"${logexporter_namespace}\" || true\n  if [[ \"${#failed_nodes[@]}\" != 0 ]]; then\n    echo -e \"Dumping logs through SSH for the following nodes:\\n${failed_nodes[*]}\"\n    dump_nodes \"${failed_nodes[@]}\"\n  fi\n}\n\nfunction detect_node_failures() {\n  if ! [[ \"${gcloud_supported_providers}\" =~ ${KUBERNETES_PROVIDER} ]]; then\n    return\n  fi\n\n  detect-node-names\n  if [[ \"${KUBERNETES_PROVIDER}\" == \"gce\" ]]; then\n    local all_instance_groups=(\"${INSTANCE_GROUPS[@]}\" \"${WINDOWS_INSTANCE_GROUPS[@]}\")\n  else\n    local all_instance_groups=(\"${INSTANCE_GROUPS[@]}\")\n  fi\n\n  if [ -z \"${all_instance_groups:-}\" ]; then\n    return\n  fi\n  for group in \"${all_instance_groups[@]}\"; do\n    local creation_timestamp\n    creation_timestamp=$(gcloud compute instance-groups managed describe \\\n                         \"${group}\" \\\n                         --project \"${PROJECT}\" \\\n                         --zone \"${ZONE}\" \\\n                         --format='value(creationTimestamp)')\n    echo \"Failures for ${group} (if any):\"\n    gcloud logging read --order=asc \\\n          --format='table(timestamp,jsonPayload.resource.name,jsonPayload.event_subtype)' \\\n          --project \"${PROJECT}\" \\\n          \"resource.type=\\\"gce_instance\\\"\n           logName=\\\"projects/${PROJECT}/logs/compute.googleapis.com%2Factivity_log\\\"\n           (jsonPayload.event_subtype=\\\"compute.instances.hostError\\\" OR jsonPayload.event_subtype=\\\"compute.instances.automaticRestart\\\")\n           jsonPayload.resource.name:\\\"${group}\\\"\n           timestamp >= \\\"${creation_timestamp}\\\"\"\n  done\n}\n\nfunction dump_logs() {\n  # Copy control_plane logs to artifacts dir locally (through SSH).\n  echo \"Dumping logs from control_plane locally to '${report_dir}'\"\n  dump_control_planes\n  if [[ \"${DUMP_ONLY_CONTROL_PLANE_LOGS:-}\" == \"true\" ]]; then\n    echo 'Skipping dumping of node logs'\n    return\n  fi\n\n  # Copy logs from nodes to GCS directly or to artifacts dir locally (through SSH).\n  if [[ -n \"${gcs_artifacts_dir}\" ]]; then\n    echo \"Dumping logs from nodes to GCS directly at '${gcs_artifacts_dir}' using logexporter\"\n    dump_nodes_with_logexporter\n  else\n    echo \"Dumping logs from nodes locally to '${report_dir}'\"\n    dump_nodes\n  fi\n}\n\n# Without ${DUMP_TO_GCS_ONLY} == true:\n# * only logs exported by logexporter will be uploaded to\n#   ${gcs_artifacts_dir}\n# * other logs (control_plane logs, nodes where logexporter failed) will be\n#   fetched locally to ${report_dir}.\n# If $DUMP_TO_GCS_ONLY == 'true', all logs will be uploaded directly to\n# ${gcs_artifacts_dir}.\nfunction main() {\n  setup\n  kube::util::ensure-temp-dir\n  if [[ \"${DUMP_TO_GCS_ONLY:-}\" == \"true\" ]] && [[ -n \"${gcs_artifacts_dir}\" ]]; then\n    report_dir=\"${KUBE_TEMP}/logs\"\n    mkdir -p \"${report_dir}\"\n    echo \"${gcs_artifacts_dir}\" > \"${local_report_dir}/control_plane-and-node-logs.link.txt\"\n    echo \"Dumping logs temporarily to '${report_dir}'. Will upload to '${gcs_artifacts_dir}' later.\"\n  else\n    report_dir=\"${local_report_dir}\"\n  fi\n\n  dump_logs\n\n  if [[ \"${DUMP_TO_GCS_ONLY:-}\" == \"true\" ]] && [[ -n \"${gcs_artifacts_dir}\" ]]; then\n    if [[ \"$(ls -A ${report_dir})\" ]]; then\n      echo \"Uploading '${report_dir}' to '${gcs_artifacts_dir}'\"\n\n      if gsutil ls \"${gcs_artifacts_dir}\" > /dev/null; then\n        # If \"${gcs_artifacts_dir}\" exists, the simple call:\n        # `gsutil cp -r /tmp/dir/logs ${gcs_artifacts_dir}` will\n        #  create subdirectory 'logs' in ${gcs_artifacts_dir}\n        #\n        # If \"${gcs_artifacts_dir}\" exists, we want to merge its content\n        # with local logs. To do that we do the following trick:\n        # * Let's say that ${gcs_artifacts_dir} == 'gs://a/b/c'.\n        # * We rename 'logs' to 'c'\n        # * Call `gsutil cp -r /tmp/dir/c gs://a/b/`\n        #\n        # Similar pattern is used in bootstrap.py#L409-L416.\n        # It is a known issue that gsutil cp behavior is that complex.\n        # For more information on this, see:\n        # https://cloud.google.com/storage/docs/gsutil/commands/cp#how-names-are-constructed\n        remote_dir=$(dirname ${gcs_artifacts_dir})\n        remote_basename=$(basename ${gcs_artifacts_dir})\n        mv ${report_dir} \"${KUBE_TEMP}/${remote_basename}\"\n        gsutil -m cp -r -c -z log,txt,xml \"${KUBE_TEMP}/${remote_basename}\" \"${remote_dir}\"\n        rm -rf \"${KUBE_TEMP}/${remote_basename}\"\n      else  # ${gcs_artifacts_dir} doesn't exist.\n        gsutil -m cp -r -c -z log,txt,xml \"${report_dir}\" \"${gcs_artifacts_dir}\"\n        rm -rf \"${report_dir}\"\n      fi\n    else\n      echo \"Skipping upload of '${report_dir}' as it's empty.\"\n    fi\n  fi\n\n  detect_node_failures\n  if [[ ${logexporter_failed} -ne 0 && ${log_dump_expected_success_percentage} -gt 0 ]]; then\n    return 1\n  fi\n}\n\nmain", "num_lines": 917}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\ncat << EOF > config\n[default]\noutput = json\nregion = us-west-2\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile release-prod]\nrole_arn = arn:aws:iam::379412251201:role/DocsDeploymentRole\nregion = us-east-1\nsource_profile=default\nEOF\n\nBUCKET_NAME=artifactsstack-379412251201-docsbucketecea003f-bhslmuf2xe3m\nDISTRIBUTION_ID=${DISTRIBUTION_ID:-\"E1G9R70424D2RN\"}\n\nexport AWS_CONFIG_FILE=$(pwd)/config\nexport AWS_DEFAULT_PROFILE=release-prod\n\naws s3 sync --acl public-read ./site s3://${BUCKET_NAME}\naws cloudfront create-invalidation --distribution-id $DISTRIBUTION_ID --paths \"/404.html\" \"/assets/\" \"/community/\" \"/index.html\" \"/search/\" \"/sitemap.xml\" \"/sitemap.xml.gz\" \"/users/\"\n", "num_lines": 42}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAG=\"$1\"\nBIN_PATH=\"$2\"\nOS=\"$3\"\nARCH=\"$4\"\n\nCGO_ENABLED=0 GOOS=$OS GOARCH=$ARCH \\\n\tsh build_linux.sh -trimpath \\\n\t-ldflags \"-s -w -buildid='' -extldflags -static -X github.com/containernetworking/plugins/pkg/utils/buildversion.BuildVersion=${TAG}\"\n \n mv bin/* $BIN_PATH\n rm -rf gopath\n \n", "num_lines": 34}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_FILE=\"$2\"\n\nfunction build::plugins::patterns(){\n  cd $REPO\n  # Pull licenses for the plugins we are building, similiar logic exist in build_linux.sh called above\n  # https://github.com/containernetworking/plugins/blob/master/build_linux.sh#L14\n  PLUGINS=\"plugins/meta/* plugins/main/* plugins/ipam/*\"\n  ALL_PLUGINS=\"\"\n  FILES=\"\"\n  for d in $PLUGINS; do\n    if [ -d \"$d\" ]; then\n      plugin=\"$(basename \"$d\")\"\n      if [ \"${plugin}\" != \"windows\" ]; then\n        ALL_PLUGINS+=\"./$d \"\n        FILES+=\"$plugin \"\n      fi\n    fi\n  done\n  mkdir -p $(dirname $OUTPUT_FILE)\n  echo \"SOURCE_PATTERNS=$ALL_PLUGINS\" > $OUTPUT_FILE\n  echo \"BINARY_TARGET_FILES=$FILES\" >> $OUTPUT_FILE\n}\n\nbuild::plugins::patterns\n", "num_lines": 47}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\n\nREPO=\"$1\"\nGOLANG_VERSION=\"$2\"\nGIT_TAG=\"$3\"\nRELEASE_BRANCH=\"$4\"\n\nsource \"${MAKE_ROOT}/build/lib/init.sh\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nOUTPUT_DIR=${MAKE_ROOT}/_output/${RELEASE_BRANCH}\nKUBE_GIT_VERSION_FILE=${MAKE_ROOT}/${RELEASE_BRANCH}/KUBE_GIT_VERSION_FILE\n\nbuild::common::use_go_version $GOLANG_VERSION\nbuild::common::set_go_cache kubernetes $GIT_TAG\nbuild::binaries::kube_bins \"$SOURCE_DIR\" $RELEASE_BRANCH $GIT_TAG $KUBE_GIT_VERSION_FILE\n\nmkdir -p ${OUTPUT_DIR}/bin\nrsync --remove-source-files -a --include '*/' --include 'kube-*' --include 'kubelet*' \\\n\t--include 'kubeadm*' --include 'kubectl*' --exclude '*' ${SOURCE_DIR}/_output/local/bin ${OUTPUT_DIR}\n\n# In presubmit builds space is very limited\nrm -rf ${SOURCE_DIR}/_output\n", "num_lines": 44}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nGIT_TAG=\"$2\"\nRELEASE_BRANCH=\"$3\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nGIT_TAG=\"$(cat ${MAKE_ROOT}/${RELEASE_BRANCH}/GIT_TAG)\"\n\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\nsource \"${MAKE_ROOT}/build/lib/init.sh\"\nsource \"${MAKE_ROOT}/build/lib/tarballs.sh\"\n\nif [ ! -d ${OUTPUT_DIR}/${RELEASE_BRANCH} ]; then\n    echo \"${OUTPUT_DIR}/${RELEASE_BRANCH} not present!\"\n    exit 1\nfi\n\nOUTPUT_RELEASE_DIR=\"${OUTPUT_DIR}/${RELEASE_BRANCH}\"\nBIN=\"${OUTPUT_RELEASE_DIR}/bin\" \nTAR_OUTPUT_DIR=${OUTPUT_DIR}/tar/${RELEASE_BRANCH}\n\nmkdir -p $TAR_OUTPUT_DIR\nbuild::common::ensure_tar\nbuild::tarballs::create_tarballs $BIN $OUTPUT_RELEASE_DIR $TAR_OUTPUT_DIR\n\n# exclude helper files used for make targets\necho \"eks-distro-checkout-$GIT_TAG export-ignore\" >> $SOURCE_DIR/.git/info/attributes\necho \"eks-distro-patched export-ignore\" >> $SOURCE_DIR/.git/info/attributes\n\n# Tag current HEAD of repo which includes the patches so that when the archive is created\n# the proper tag will be written into the hack/lib/version.sh file for anyone building from \n# this source tarball. Load version file to avoid recreating git version\nsource \"${MAKE_ROOT}/${RELEASE_BRANCH}/KUBE_GIT_VERSION_FILE\"\ngit -C $SOURCE_DIR tag -f $KUBE_GIT_VERSION\n\ngit \\\n    -C $SOURCE_DIR \\\n    archive \\\n    --format=tar.gz \\\n    --output=${TAR_OUTPUT_DIR}/kubernetes-src.tar.gz \\\n    HEAD\n", "num_lines": 61}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nTAG=$1\nRELEASE_BRANCH=$2\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/build/lib/init.sh\"\n\nVERSION_FILE=\"${MAKE_ROOT}/${RELEASE_BRANCH}/KUBE_GIT_VERSION_FILE\"\nrm -f $VERSION_FILE\ntouch $VERSION_FILE\nbuild::version::create_env_file \"$TAG\" \"$VERSION_FILE\" \"kubernetes\"\n", "num_lines": 31}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nREPO=\"$1\"\nOUTPUT_DIR=\"$2\"\nRELEASE_BRANCH=\"$3\"\n\n# The heketi/heketi dependency is dual licensed between Apache 2.0 or LGPLv3+\n# this was done at the request of the kubernetes project since the original license\n# was not one that allowed redistro.  The pieces used by the kubernetes project follow under\n# the apache2 license.\n# https://github.com/heketi/heketi/pull/1419\n# https://github.com/kubernetes/kubernetes/pull/70828\n# Copy the apache2 license into place in the vendor directory\n#\n# For Kubernetes 1.26+, heketi was removed https://github.com/kubernetes/kubernetes/pull/112015\n# This block should be removed once 1-25 is no longer supported.\nMINOR_VERSION=${RELEASE_BRANCH: -2}\nif [[ $MINOR_VERSION -le 25 ]]; then\n  cp $REPO/vendor/github.com/heketi/heketi/LICENSE-APACHE2 $REPO/vendor/github.com/heketi/heketi/LICENSE\n  rm -f $REPO/vendor/github.com/heketi/heketi/COPYING-*\nfi\n\n# a number of k8s.io dependencies which come from the main repo show\n# up in the list and since they are in the repo they have no version\n# set the rootmodule name to k8s.io to force all projects with that \n# prefix and no version to use the k8s git_tag version\nmkdir -p ${OUTPUT_DIR}/attribution\necho \"k8s.io\" > ${OUTPUT_DIR}/attribution/root-module.txt\n", "num_lines": 46}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nsource \"${MAKE_ROOT}/build/lib/init.sh\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nRELEASE_BRANCH=\"$1\"\nGOLANG_VERSION=\"$2\"\n\nexport ARTIFACTS=${ARTIFACTS:-\"./_artifacts\"}\nexport KUBE_JUNIT_REPORT_DIR=\"${ARTIFACTS}\"\nexport KUBE_KEEP_VERBOSE_TEST_OUTPUT=y\nexport LOG_LEVEL=4\nexport KUBE_TIMEOUT=${KUBE_TIMEOUT:-\"--timeout=600s\"}\n\nbuild::common::use_go_version $GOLANG_VERSION\n\n# Beginning with Go 1.17, using `go get` to install executables was deprecated\n# in favor of `go install`. See https://go.dev/doc/go-get-install-deprecation\nawk -v short_golang_version=\"${GOLANG_VERSION:0:4}\" \\\n    -v go_install_min_version=\"1.17\" \\\n  'BEGIN {\n    if (short_golang_version<go_install_min_version)\n      system(\"go get gotest.tools/gotestsum\")\n    else\n      system(\"go install gotest.tools/gotestsum\")\n    fi\n  };'\n\ncd $MAKE_ROOT/kubernetes\n\n# Install etcd for tests\n./hack/install-etcd.sh\n\nexport PATH=\"${GOPATH}/bin:${MAKE_ROOT}/kubernetes/third_party/etcd:${PATH}\"\n\n# kube build scripts set GOCACHE and GOMODCACHE to be in the ./_output/local/go/cache directory\n# relative to the kubernetes source folder instead\n# unsetting these two which we set in our common script to allow kube to fully manage these locations\n# and keep the directories we need to clean consistent through versions\nunset GOCACHE GOMODCACHE\n\nMAX_RETRIES=5\n# There are flakes in upstream tests, the process also caches passing results\n# so on rerun it only runs the tests which failed\nfor i in $(seq 1 $MAX_RETRIES);\ndo\n  [ $i -gt 1 ] && sleep 5\n  make test && ret=0 && break || ret=$?;\ndone\n\nif [ $ret -ne 0 ]; then\n  echo \"Tests failed after $MAX_RETRIES runs, checking if failures are known flakes\"\n\n  latest_log=$(ls -td $ARTIFACTS/junit*.stdout | head -1)\n  gotestsum --jsonfile $ARTIFACTS/out.json --raw-command cat \"$latest_log\"\n  jq -r 'select(.Action==\"fail\" and .Test) | [.Package, .Test]  | join(\"/\")' $ARTIFACTS/out.json > $ARTIFACTS/failed_tests\n  non_flakes=$(grep -Fxv -f $MAKE_ROOT/top_flakes $ARTIFACTS/failed_tests || true)\n\n  if [ ! \"$non_flakes\" ]\n  then\n        echo \"Failures are confirmed flakes.  Tests considered passing\"\n        ret=0\n  else\n    echo \"\nThe following tests failed after $MAX_RETRIES runs and are not listed in top_flakes\nCheck upstream if failing test is a common flake and add it to the top_flakes file:\n  https://github.com/kubernetes/community/blob/master/contributors/devel/sig-testing/flaky-tests.md\n\n$non_flakes\n\"\n  fi\nfi\n\nexit $ret\n", "num_lines": 93}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfunction build::binaries::kube_bins() {\n  local -r repository=\"$1\"\n  local -r release_branch=\"$2\"\n  local -r git_tag=\"$3\"\n  local -r kube_git_version_file=\"$4\"\n\n  export KUBE_GIT_VERSION_FILE=$kube_git_version_file\n\n  cd $repository\n  \n  \n  # kube build scripts set GOCACHE and GOMODCACHE to be in the ./_output/local/go/cache directory\n  # relative to the kubernetes source folder instead\n  # unsetting these two which we set in our common script to allow kube to fully manage these locations\n  # and keep the directories we need to clean consistent through versions\n  unset GOCACHE GOMODCACHE\n\n  # Ideally, to avoid checksum differences due to modules being downloaded by go mod download vs\n  # vendored in the vendor directly, which really only comes into play when build locally vs in a clean\n  # builder-base, we would run `./hack/update-vendor.sh` to redownload all the modules avoiding this difference\n  # We do this for all projects, however, with kubernetes we actually patch some files in vendor\n  # so if we ran this it would overwrite our patched changes\n  # TODO: potentially look at ways to run this but reset back to patches after downloads?\n  # or once we are using go 1.15, using the seperate cache dirs like we do could help?\n  # ./hack/update-vendor.sh\n  \n  # Build all core components for linux arm64 and amd64\n  # GOLDFLASGS\n  # * strip symbol, debug, and DWARF tables\n  # * set an empty build id for reproducibility\n  # * build static binaries\n  # Run in two steps to support passing -trimpath\n  export CGO_ENABLED=0\n  export GOLDFLAGS='-s -w -buildid=\"\"'\n  export KUBE_STATIC_OVERRIDES=\"cmd/kubelet \\\n      cmd/kube-proxy \\\n      cmd/kubeadm \\\n      cmd/kubectl \\\n      cmd/kube-apiserver \\\n      cmd/kube-controller-manager \\\n      cmd/kube-scheduler\"\n\n  # For Kubernetes 1.23 and older, removing `make generated_files` results in this error:\n  # cmd/kube-apiserver/app/server.go:401:80: undefined: \"k8s.io/kubernetes/pkg/generated/openapi\".GetOpenAPIDefinitions\n  #\n  # This block should be removes when 1.23 is no longer supported.\n  local -r minor_version=${release_branch: -2}\n  if [[ $minor_version -le 23 ]]; then\n    make generated_files\n  fi\n\n  # Linux\n  for arch in linux/amd64 linux/arm64; do\n    export KUBE_BUILD_PLATFORMS=\"$arch\"\n    hack/make-rules/build.sh -trimpath cmd/kubelet \\\n          cmd/kube-proxy \\\n          cmd/kubeadm \\\n          cmd/kubectl \\\n          cmd/kube-apiserver \\\n          cmd/kube-controller-manager \\\n          cmd/kube-scheduler\n\n    # In presubmit builds space is very limited\n    rm -rf ./_output/local/go/cache\n  done\n  \n  # Windows\n  export KUBE_BUILD_PLATFORMS=\"windows/amd64\"\n  hack/make-rules/build.sh -trimpath cmd/kubelet \\\n    cmd/kube-proxy \\\n      cmd/kubeadm \\\n      cmd/kubectl\n\n  # Darwin\n  export KUBE_BUILD_PLATFORMS=\"darwin/amd64\" \n  hack/make-rules/build.sh -trimpath cmd/kubectl\n\n  # In presubmit builds space is very limited\n  rm -rf ./_output/local/go/cache\n\n  cd ..\n}\n", "num_lines": 98}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/../..\" && pwd -P)\"\n\nREPOSITORY=\"kubernetes\"\nSOURCE_DIR=${MAKE_ROOT}/${REPOSITORY}\n\nOUTPUT_DIR=\"${MAKE_ROOT}/_output\"\n\nsource \"${MAKE_ROOT}/build/lib/binaries.sh\"\nsource \"${MAKE_ROOT}/build/lib/version.sh\"\n", "num_lines": 26}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\nreadonly KUBE_SUPPORTED_SERVER_PLATFORMS=(\n  linux/amd64\n  linux/arm64\n)\n\nreadonly KUBE_SUPPORTED_NODE_PLATFORMS=(\n  linux/amd64\n  linux/arm64\n  windows/amd64\n)\n\nreadonly KUBE_SUPPORTED_CLIENT_PLATFORMS=(\n  linux/amd64\n  linux/arm64\n  darwin/amd64\n  windows/amd64\n)\n\n### server binaries\nfunction build::tarballs::server_targets() {\n  local targets=(\n    cmd/kube-proxy\n    cmd/kube-apiserver\n    cmd/kube-controller-manager\n    cmd/kubelet\n    cmd/kubeadm\n    cmd/kube-scheduler\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_SERVER_TARGETS <<< \"$(build::tarballs::server_targets)\"\nreadonly KUBE_SERVER_TARGETS\nreadonly KUBE_SERVER_BINARIES=(\"${KUBE_SERVER_TARGETS[@]##*/}\")\n\n### node binaries\nfunction build::tarballs::node_targets() {\n  local targets=(\n    cmd/kube-proxy\n    cmd/kubeadm\n    cmd/kubelet\n  )\n  echo \"${targets[@]}\"\n}\n\nIFS=\" \" read -ra KUBE_NODE_TARGETS <<< \"$(build::tarballs::node_targets)\"\nreadonly KUBE_NODE_TARGETS\nreadonly KUBE_NODE_BINARIES=(\"${KUBE_NODE_TARGETS[@]##*/}\")\nreadonly KUBE_NODE_BINARIES_WIN=(\"${KUBE_NODE_BINARIES[@]/%/.exe}\")\n\n### client binaries\nreadonly KUBE_CLIENT_TARGETS=(\n  cmd/kubectl\n)\nreadonly KUBE_CLIENT_BINARIES=(\"${KUBE_CLIENT_TARGETS[@]##*/}\")\nreadonly KUBE_CLIENT_BINARIES_WIN=(\"${KUBE_CLIENT_BINARIES[@]/%/.exe}\")\n\nfunction build::tarballs::create_tarballs(){\n    local -r bin_root=\"$1\"\n    local -r output_dir=\"$2\"\n    local -r tar_output_dir=\"$3\"\n\n    for platform in \"${KUBE_SUPPORTED_SERVER_PLATFORMS[@]}\"; do\n        # The substitution on platform_src below will replace all slashes with\n        # dashes.  It'll transform darwin/amd64 -> darwin-amd64.\n        local platform_src=\"${platform//\\//-}\"\n\n        tarball=$tar_output_dir/kubernetes-server-$platform_src.tar.gz\n        local ch_dir=\"${output_dir}/${platform}\"\n        local bin_dir=\"${output_dir}/${platform}/kubernetes/server/bin\"\n        mkdir -p $bin_dir\n        for bin in ${KUBE_SERVER_BINARIES[@]}; do\n            cp ${bin_root}/${platform}/${bin} $bin_dir\n        done\n        cp -rf $output_dir/LICENSES $ch_dir/kubernetes\n        cp $output_dir/ATTRIBUTION.txt $ch_dir/kubernetes\n        build::common::create_tarball $tarball $ch_dir kubernetes\n        rm -rf $ch_dir\n        rmdir $(dirname $ch_dir)\n    done\n\n    for platform in \"${KUBE_SUPPORTED_NODE_PLATFORMS[@]}\"; do\n        # The substitution on platform_src below will replace all slashes with\n        # dashes.  It'll transform darwin/amd64 -> darwin-amd64.\n        local platform_src=\"${platform//\\//-}\"\n        tarball=$tar_output_dir/kubernetes-node-$platform_src.tar.gz\n        local ch_dir=\"${output_dir}/${platform}\"\n        local bin_dir=\"${output_dir}/${platform}/kubernetes/node/bin\"\n        mkdir -p $bin_dir\n        if [ \"$platform\" == \"windows/amd64\" ]; then\n            for bin in ${KUBE_NODE_BINARIES_WIN[@]}; do\n                cp ${bin_root}/${platform}/${bin} $bin_dir\n            done\n        else\n            for bin in ${KUBE_NODE_BINARIES[@]}; do\n                cp ${bin_root}/${platform}/${bin} $bin_dir\n            done\n        fi\n        cp -rf $output_dir/LICENSES $ch_dir/kubernetes\n        cp $output_dir/ATTRIBUTION.txt $ch_dir/kubernetes\n        build::common::create_tarball $tarball $ch_dir kubernetes\n        rm -rf $ch_dir\n        rmdir $(dirname $ch_dir)\n    done\n\n    for platform in \"${KUBE_SUPPORTED_CLIENT_PLATFORMS[@]}\"; do\n        # The substitution on platform_src below will replace all slashes with\n        # dashes.  It'll transform darwin/amd64 -> darwin-amd64.\n        local platform_src=\"${platform//\\//-}\"\n        tarball=$tar_output_dir/kubernetes-client-$platform_src.tar.gz\n        local ch_dir=\"${output_dir}/${platform}\"\n        local bin_dir=\"${output_dir}/${platform}/kubernetes/client/bin\"\n        mkdir -p $bin_dir\n        if [ \"$platform\" == \"windows/amd64\" ]; then\n            for bin in ${KUBE_CLIENT_BINARIES_WIN[@]}; do\n                cp ${bin_root}/${platform}/${bin} $bin_dir\n            done\n        else\n            for bin in ${KUBE_CLIENT_BINARIES[@]}; do\n                cp ${bin_root}/${platform}/${bin} $bin_dir\n            done\n        fi\n        cp -rf $output_dir/LICENSES $ch_dir/kubernetes\n        cp $output_dir/ATTRIBUTION.txt $ch_dir/kubernetes\n        build::common::create_tarball $tarball $ch_dir kubernetes\n        rm -rf $ch_dir\n        rmdir $(dirname $ch_dir)\n    done\n}\n", "num_lines": 148}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nfunction build::version::create_env_file() {\n    local -r tag=\"$1\"\n    local -r version_file=\"$2\"\n    local -r repository=\"$3\"\n\n    local -r source_date_epoch=$(git -C $repository show -s --format=format:%ct $tag^{commit})    \n    local -r kube_git_version=$tag-eks-$(git -C $repository rev-parse --short=7 HEAD)\n\n    export KUBE_GIT_VERSION=$tag\n    export KUBE_GIT_TREE_STATE=clean\n\n    cd $repository\n\n    source \"${MAKE_ROOT}/$repository/hack/lib/init.sh\"\n    source \"${MAKE_ROOT}/$repository/hack/lib/version.sh\"\n    kube::version::get_version_vars\n    kube::version::save_version_vars $version_file\n    cd -\n\n    local -r version_file_cleaned=$version_file.tmp\n\n    cat $version_file | sed -e \"s/${tag}/${kube_git_version}/g\"| grep -v \"KUBE_GIT_TREE_STATE\" > $version_file_cleaned\n\n    cat << EOF >> $version_file_cleaned\nSOURCE_DATE_EPOCH='${source_date_epoch}'\nKUBE_GIT_TREE_STATE='archive'\nEOF\n    mv $version_file_cleaned $version_file\n}\n", "num_lines": 46}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nOUTPUT_DIR=\"$1\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nATTRIBUTION_DIR=\"${OUTPUT_DIR}/attribution\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\n\n# go-licenses calls the main module command-line-arguments in the csv output\nMODULE_NAME=$(cat \"${ATTRIBUTION_DIR}/root-module.txt\")\nSEARCH='command-line-arguments'\nREPLACE=$(build::common::re_quote $MODULE_NAME)\nsed -i.bak \"s/^$SEARCH/$REPLACE/\" \"${ATTRIBUTION_DIR}/go-license.csv\"\n", "num_lines": 32}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nRELEASE_BRANCH=\"$1\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nOUTPUT_DIR=\"${MAKE_ROOT}/_output/${RELEASE_BRANCH}\"\nATTRIBUTION_DIR=\"${OUTPUT_DIR}/attribution\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\n\n# go-licenses calls adds an additional cmd/livenessprobe\n# to the main module name in the csv output\nMODULE_NAME=$(cat \"${ATTRIBUTION_DIR}/root-module.txt\")\nSEARCH=$(build::common::re_quote \"$MODULE_NAME/cmd/livenessprobe\")\nREPLACE=$(build::common::re_quote $MODULE_NAME)\nsed -i.bak \"s/^$SEARCH/$REPLACE/\" \"${ATTRIBUTION_DIR}/go-license.csv\"\n", "num_lines": 34}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nRELEASE_BRANCH=\"$1\"\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nOUTPUT_DIR=\"${MAKE_ROOT}/_output/${RELEASE_BRANCH}\"\nATTRIBUTION_DIR=\"${OUTPUT_DIR}/attribution\"\nsource \"${MAKE_ROOT}/../../../build/lib/common.sh\"\n\n\n# go-licenses calls adds an additonal cmd/csi-node-driver-registrar \n# to the main module name in the csv output\nMODULE_NAME=$(cat \"${ATTRIBUTION_DIR}/root-module.txt\")\nSEARCH=$(build::common::re_quote \"$MODULE_NAME/cmd/csi-node-driver-registrar\")\nREPLACE=$(build::common::re_quote $MODULE_NAME)\nsed -i.bak \"s/^$SEARCH/$REPLACE/\" \"${ATTRIBUTION_DIR}/go-license.csv\"\n", "num_lines": 34}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nBASE_DIRECTORY=\"$(cd \"${SCRIPT_ROOT}/..\" && pwd -P)\"\nsource ${BASE_DIRECTORY}/build/lib/common.sh\n\nPROJECT=\"${1?First required argument is project}\"\nSOURCE_ARTIFACT_DIR=\"${2?Second required argument is source artifact directory}\"\nRELEASE_BRANCH=\"${3?Third required argument is release branch for example 1-18}\"\nRELEASE=\"${4?Fourth required argument is release for example 1}\"\nGIT_TAG=\"${5:-}\"\n\nDEST_DIR=${BASE_DIRECTORY}/kubernetes-${RELEASE_BRANCH}/releases/${RELEASE}/artifacts\n\n# For when calling from projects other than kubernetes\nif [ $PROJECT = \"kubernetes\" ]; then\n  GIT_TAG=$(cat ${BASE_DIRECTORY}/projects/kubernetes/kubernetes/${RELEASE_BRANCH}/GIT_TAG)\nfi\n\nARTIFACT_DIR=${DEST_DIR}/${PROJECT}/${GIT_TAG}\nmkdir -p $ARTIFACT_DIR\nbuild::common::echo_and_run cp -r $SOURCE_ARTIFACT_DIR/* $ARTIFACT_DIR\n\n# create checksums in source output since we validate artifacts from that folder\nbuild::common::echo_and_run $SCRIPT_ROOT/create_release_checksums.sh $SOURCE_ARTIFACT_DIR\nbuild::common::echo_and_run $SCRIPT_ROOT/create_release_checksums.sh $ARTIFACT_DIR\n", "num_lines": 44}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nBASE_DIRECTORY=\"$(cd \"${SCRIPT_ROOT}/..\" && pwd -P)\"\nsource ${BASE_DIRECTORY}/build/lib/common.sh\n\nASSET_ROOT=\"$1\"\n\nFIND=find\nif which gfind &>/dev/null; then\n    FIND=gfind\nelif which gnudate &>/dev/null; then\n    FIND=gnufind\nfi\n\nSHA256SUM=$(dirname ${ASSET_ROOT})/SHA256SUM\nSHA512SUM=$(dirname ${ASSET_ROOT})/SHA512SUM\nrm -f $SHA256SUM\nrm -f $SHA512SUM\necho \"Writing artifact hashes to SHA256SUM/SHA512SUM files in folder: $ASSET_ROOT\"\ncd $ASSET_ROOT\nfor file in $(find ${ASSET_ROOT} -type f -not -path '*\\.sha[25][51][62]' -not -path '*\\.docker_*' \\( -path '*bin/linux*' -o -path '*bin/windows*' -o -path '*bin/darwin*' -o -name '*tar\\.gz' \\) ); do\n    filepath=$(realpath --relative-base=${ASSET_ROOT} $file )\n    sha256sum \"$filepath\" | tee -a $SHA256SUM > \"$file.sha256\" || return 1\n    sha512sum \"$filepath\" | tee -a $SHA512SUM > \"$file.sha512\" || return 1\ndone\n\nmv $SHA256SUM $SHA512SUM \"$ASSET_ROOT\"\nsha256sum SHA256SUM > \"SHA256SUM.sha256\" || return 1\nsha512sum SHA256SUM > \"SHA256SUM.sha512\" || return 1\nsha256sum SHA512SUM > \"SHA512SUM.sha256\" || return 1\nsha512sum SHA512SUM > \"SHA512SUM.sha512\" || return 1\n\ncat SHA256SUM\ncd -\n", "num_lines": 53}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nARTIFACT_BUCKET=\"${1?First required argument should be bucket to create}\"\n\n# Create the bucket if it doesn't exist\n_bucket_name=$(aws s3api list-buckets  --query \"Buckets[?Name=='$ARTIFACT_BUCKET'].Name | [0]\" --out text)\nif [ $_bucket_name == \"None\" ]; then\n    echo \"Creating artifact bucket: s3://$ARTIFACT_BUCKET\"\n    if [ \"$AWS_DEFAULT_REGION\" == \"us-east-1\" ]; then\n        aws s3api create-bucket --bucket $ARTIFACT_BUCKET\n    else\n        aws s3api create-bucket --bucket $ARTIFACT_BUCKET --create-bucket-configuration LocationConstraint=$AWS_DEFAULT_REGION\n    fi\nelse\n    echo \"Using existing artifact bucket: s3://$ARTIFACT_BUCKET\"\nfi\n", "num_lines": 32}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nRELEASE_BRANCH=\"${1?First required argument is release branch for example 1-18}\"\nRELEASE=\"${2?Second required argument is release for example 1}\"\nIMAGE_REPO=\"${3?Third required argument is image repository}\"\nREPO_OWNER=${REPO_OWNER:-aws}\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY}\n\nDEV_RELEASE=true\nif [[ \"$JOB_NAME\" =~ \"prod-release\" ]]; then\n    DEV_RELEASE=false\nfi\n\nREPOSITORY=\"https://github.com/${REPO_OWNER}/eks-distro-build-tooling.git\"\nrm -rf ./eks-distro-build-tooling\ngit clone ${REPOSITORY}\nmake -C eks-distro-build-tooling/release\nDESTINATION=\"./kubernetes-${RELEASE_BRANCH}/kubernetes-${RELEASE_BRANCH}-eks-${RELEASE}.yaml\"\n./eks-distro-build-tooling/release/bin/eks-distro-release release \\\n    --image-repository ${IMAGE_REPO} \\\n    --release-branch ${RELEASE_BRANCH} \\\n    --release-number ${RELEASE} \\\n    --dev-release=${DEV_RELEASE} | tee ${DESTINATION}\nmkdir -p releasechannels\ngrep -v '^#.*' eks-distro-build-tooling/release/config/${RELEASE_BRANCH}/${RELEASE_BRANCH}.yaml \\\n    | sed \"s/latestRelease: .*/latestRelease: ${RELEASE}/\" >releasechannels/${RELEASE_BRANCH}.yaml\nmkdir -p crds\ngrep -v '^#.*' eks-distro-build-tooling/release/config/crds/releasechannels.distro.eks.amazonaws.com-v1alpha1.yaml \\\n    >crds/releasechannels.distro.eks.amazonaws.com-v1alpha1.yaml\ngrep -v '^#.*' eks-distro-build-tooling/release/config/crds/releases.distro.eks.amazonaws.com-v1alpha1.yaml \\\n    >crds/releases.distro.eks.amazonaws.com-v1alpha1.yaml\n", "num_lines": 49}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nAWS_ROLE_ARN=\"${AWS_ROLE_ARN?The AWS_ROLE_ARN must be set}\"\nARTIFACT_DEPLOYMENT_ROLE_ARN=\"${ARTIFACT_DEPLOYMENT_ROLE_ARN?The ARTIFACT_DEPLOYMENT_ROLE_ARN must be set}\"\nSNS_TOPIC_ARN=\"${SNS_TOPIC_ARN?The SNS_TOPIC_ARN must be set}\"\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY}\n\ncat << EOF > awscliconfig\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile release-account]\nrole_arn=$ARTIFACT_DEPLOYMENT_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}\nsource_profile=default\nEOF\nexport AWS_CONFIG_FILE=$(pwd)/awscliconfig\nexport AWS_PROFILE=release-account\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n\ngit -C . diff --name-only HEAD^ HEAD |\ngrep '^docs/contents/releases' |\ngrep release-announcement.txt |\nwhile read ANNOUNCEMENT\ndo\n    ${BASE_DIRECTORY}/release/sns_notification.sh ${ANNOUNCEMENT} ${SNS_TOPIC_ARN}\ndone\n", "num_lines": 46}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN\"\n    exit 1\nfi\n\nif [ \"$ARTIFACT_DEPLOYMENT_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty ARTIFACT_DEPLOYMENT_ROLE_ARN\"\n    exit 1\nfi\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY}\nRELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-development}\n\nexport RELEASE=$(cat ${BASE_DIRECTORY}/release/${RELEASE_BRANCH}/${RELEASE_ENVIRONMENT}/RELEASE)\n\nif [ \"${RELEASE}\" == \"0\" ]\nthen\n    echo \"No production release zero\"\n    exit 0\nfi\n\ncat << EOF > awscliconfig\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile release-account]\nrole_arn=$ARTIFACT_DEPLOYMENT_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}\nsource_profile=default\nEOF\nexport AWS_CONFIG_FILE=$(pwd)/awscliconfig\nexport AWS_PROFILE=release-account\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n\ncp -r /$HOME/.docker ${BASE_DIRECTORY}\nexport DOCKER_CONFIG=${BASE_DIRECTORY}/.docker\n${BASE_DIRECTORY}/development/ecr/ecr-command.sh install-ecr-public\n${BASE_DIRECTORY}/development/ecr/ecr-command.sh login-ecr-public\nmake release ${*}\n", "num_lines": 59}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN\"\n    exit 1\nfi\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY}\nRELEASE_ENVIRONMENT=${RELEASE_ENVIRONMENT:-development}\n\nexport RELEASE=$(cat ${BASE_DIRECTORY}/release/${RELEASE_BRANCH}/${RELEASE_ENVIRONMENT}/RELEASE)\n\nif [ \"${RELEASE}\" == \"0\" ]\nthen\n    echo \"No dev release zero\"\n    exit 0\nfi\n\ncp -r /$HOME/.docker ${BASE_DIRECTORY}\nexport DOCKER_CONFIG=${BASE_DIRECTORY}/.docker\n${BASE_DIRECTORY}/development/ecr/ecr-command.sh install-ecr-public\n${BASE_DIRECTORY}/development/ecr/ecr-command.sh login-ecr-public\nmake release ${*}\n", "num_lines": 37}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euxo pipefail\n\nRELEASE_BRANCH=\"${1?First required argument is release branch for example 1-18}\"\nRELEASE=\"${2?Second required argument is release for example 1}\"\nARTIFACT_BUCKET=\"${3?Third required argument is artifact bucket name}\"\nCRDS=\"${4:-false}\"\nDRY_RUN=\"${5:-false}\"\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\n\nPUBLIC_READ='--acl public-read'\n\ncd ${BASE_DIRECTORY}\nPREFIX_DIR=kubernetes-${RELEASE_BRANCH}\nDEST_DIR=${PREFIX_DIR}/releases/${RELEASE}/artifacts\n\nif [ \"$DRY_RUN\" = \"true\" ]; then\n  aws s3 cp $DEST_DIR s3://${ARTIFACT_BUCKET}/${DEST_DIR} ${PUBLIC_READ} --recursive --dryrun\nelse\n  aws s3 sync $DEST_DIR s3://${ARTIFACT_BUCKET}/${DEST_DIR} ${PUBLIC_READ}\nfi\n\n\nif [ \"$CRDS\" != \"true\" ]\nthen\n  exit 0\nfi\nif [ \"$DRY_RUN\" = \"true\" ]; then\n  echo \"dry run not supported for crd uploads!\"\n  exit 1\nfi\n\ncd ${PREFIX_DIR}\n\nfor CRD\nin *yaml\ndo\n  aws s3 ls s3://${ARTIFACT_BUCKET}/${PREFIX_DIR}/${CRD} || aws s3 cp ${CRD} s3://${ARTIFACT_BUCKET}/${PREFIX_DIR}/${CRD} ${PUBLIC_READ}\ndone\ncd ${BASE_DIRECTORY}\nif [ -d crds ]\nthen\n  for CRD\n  in crds/*yaml\n  do\n    aws s3 ls s3://${ARTIFACT_BUCKET}/${CRD} || aws s3 cp ${CRD} s3://${ARTIFACT_BUCKET}/${CRD} ${PUBLIC_READ}\n  done\nfi\nif [ -d releasechannels ]\nthen\n  for CHANNEL\n  in releasechannels/*yaml\n  do\n    aws s3 cp ${CHANNEL} s3://${ARTIFACT_BUCKET}/${CHANNEL} ${PUBLIC_READ}\n  done\nfi\n", "num_lines": 72}
{"repo_name": "eks-distro", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nANNOUNCEMENT_FILE=\"${1?First required argument is file path (from base directory) for announcement message}\"\nSNS_TOPIC_ARN=\"${2?Second required argument is SNS topic ARN}\"\n\n# Get release notification subject\nRELEASE_NUMBER=$(echo \"${ANNOUNCEMENT_FILE}\" | grep -o -E \"[[:digit:]]{1}\\-[[:digit:]]{2}\") # e.g. 1-19\nif [ -z \"$RELEASE_NUMBER\" ]; then\n  echo \"Failed to publish release notification: Unable to generate release number for notification subject\"\n  exit 1\nfi\nNOTIFICATION_SUBJECT=\"New Release of EKS-D v$RELEASE_NUMBER\"\n\n# Get release notification body\nif ! [ -s \"$ANNOUNCEMENT_FILE\" ]; then\n  echo \"Failed to publish release notification: Non-empty text for notification body expected at ${ANNOUNCEMENT_FILE}\"\n  exit 1\nfi\nNOTIFICATION_BODY=$(<\"${ANNOUNCEMENT_FILE}\")\n\n# Publish release notification\necho \"\nSending SNS message with the following details:\n    - Topic ARN: $SNS_TOPIC_ARN\n    - Subject: $NOTIFICATION_SUBJECT\n    - Body: $NOTIFICATION_BODY\"\n\nSNS_MESSAGE_ID=$(\n  aws sns publish \\\n    --topic-arn \"$SNS_TOPIC_ARN\" \\\n    --subject \"$NOTIFICATION_SUBJECT\" \\\n    --message \"$NOTIFICATION_BODY\" \\\n    --query \"MessageId\" --output text\n)\n\nif [ \"$SNS_MESSAGE_ID\" ]; then\n  echo -e \"\\nRelease notification published with SNS MessageId $SNS_MESSAGE_ID\"\nelse\n  echo \"Received unexpected response while publishing to release SNS topic. An error may have occurred, and the \\\nnotification may not have not have been published\"\n  exit 1\nfi\n", "num_lines": 56}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nNEW_TAG=\"$1\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\n${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh eks-distro-prow-jobs\n${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-distro-prow-jobs 'builder-base:(.+)-.*' 'builder-base:'\"\\1-$NEW_TAG\" '*.yaml'\n${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-distro-prow-jobs '(.+)-.*' \"\\1-$NEW_TAG\" BUILDER_BASE_TAG_FILE\n${SCRIPT_ROOT}/../pr-scripts/create_pr.sh eks-distro-prow-jobs '*.yaml'\n\n${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh eks-anywhere-prow-jobs\n${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-anywhere-prow-jobs 'builder-base:(.+)-.*' 'builder-base:'\"\\1-$NEW_TAG\" '*.yaml'\n${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-anywhere-prow-jobs '(.+)-.*' \"\\1-$NEW_TAG\" BUILDER_BASE_TAG_FILE\n${SCRIPT_ROOT}/../pr-scripts/create_pr.sh eks-anywhere-prow-jobs '*.yaml'\n", "num_lines": 34}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to perform buildkit builds in daemonless mode\n\nset -e\nset -o pipefail\nset -x\n\ntmp=$(mktemp -d /tmp/buildctl-daemonless.XXXXXX)\ntrap \"kill \\$(cat $tmp/pid); rm -rf $tmp\" EXIT\n\nstart::buildkitd() {\n    buildkitd --addr=unix:///run/buildkit/buildkitd.sock --oci-worker-platform=linux/amd64 --oci-worker-platform=linux/arm64 >$tmp/log 2>&1 &\n    pid=$!\n    echo $pid >$tmp/pid\n}\n\nwait::for::buildkitd() {\n    try=0\n    max_retries=10\n    until buildctl --addr=unix:///run/buildkit/buildkitd.sock debug workers >/dev/null 2>&1; do\n        if [ $try -gt $max_retries ]; then\n            echo >&2 \"could not connect to Buildkit socket after $max_retries trials\"\n            echo >&2 \"========== log ==========\"\n            cat >&2 $tmp/log\n            exit 1\n        fi\n        sleep $(awk \"BEGIN{print (100 + $try * 20) * 0.001}\")\n        try=$(expr $try + 1)\n    done\n}\n\nstart::buildkitd\nwait::for::buildkitd\n\nbuildctl --addr=unix:///run/buildkit/buildkitd.sock \"$@\"", "num_lines": 49}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nTARGETARCH=${TARGETARCH:-amd64}\nUSR=${USR:-${NEWROOT}/usr}\nUSR_LOCAL=${USR_LOCAL:-${USR}/local}\nUSR_BIN=${USR}/bin\nUSR_LOCAL_BIN=${USR_LOCAL}/bin\n\nBASE_DIR=\"\"\n\nIS_AL23=false\nif [ -f /etc/yum.repos.d/amazonlinux.repo ] && grep -q \"2023\" /etc/yum.repos.d/amazonlinux.repo; then \n    IS_AL23=true\nfi\n\n[ ${SKIP_INSTALL:-false} != false ] || mkdir -p $USR_BIN $USR_LOCAL_BIN\n", "num_lines": 33}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Script to perform docker builds in daemonless mode\n\nset -e\nset -o pipefail\nset -x\n\nstart::dockerd() {\n    dockerd --host=unix:///var/run/docker.sock --host=tcp://127.0.0.1:2375 &>/var/log/docker.log &\n}\n\nwait::for::dockerd() {\n    try=0\n    max_retries=10\n    until docker info >/dev/null 2>&1; do\n        if [ $try -gt $max_retries ]; then\n            echo >&2 \"could not connect to Docker socket after $max_retries trials\"\n            echo >&2 \"========== log ==========\"\n            cat /var/log/docker.log\n            exit 1\n        fi\n        sleep $(awk \"BEGIN{print (100 + $try * 20) * 0.001}\")\n        try=$(expr $try + 1)\n    done\n}\n", "num_lines": 40}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nVERSION=\"$1\"\nOUTPUT_DIR=\"$2\"\n\nRELEASE_NUMBER=\"$(echo $VERSION | cut -d'-' -f 2)\"\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nfunction build::go::download(){\n    # Set up specific go version by using go get, additional versions apart from default can be installed by calling\n    # the function again with the specific parameter.\n    local version=${1%-*}\n    local outputDir=${2}\n    local arch=${3}\n\n    for artifact in golang golang-bin; do\n        local filename=\"$outputDir/$arch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.$arch.rpm\"\n        if [ ! -f $filename ]; then\n            curl -sSL --retry 5 https://distro.eks.amazonaws.com/golang-go$version/releases/$RELEASE_NUMBER/$arch/RPMS/$arch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.$arch.rpm -o $filename --create-dirs\n            curl -sSL --retry 5 https://distro.eks.amazonaws.com/golang-go$version/releases/$RELEASE_NUMBER/$arch/RPMS/$arch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.$arch.rpm.sha256 -o $filename.sha256\n\n            if [[ $(sha256sum ${filename} | cut -d' ' -f1) != $(cut -d' ' -f1 \"${filename}.sha256\") ]] ; then \n                echo \"Checksum doesn't match!\"\n                exit 1\n            fi\n        fi\n    done\n\n    for artifact in golang-docs golang-misc golang-tests golang-src; do\n        local filename=\"$outputDir/$arch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.noarch.rpm\"\n        if [ ! -f $filename ]; then\n            curl -sSL --retry 5 https://distro.eks.amazonaws.com/golang-go$version/releases/$RELEASE_NUMBER/$arch/RPMS/noarch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.noarch.rpm -o $filename --create-dirs\n            curl -sSL --retry 5 https://distro.eks.amazonaws.com/golang-go$version/releases/$RELEASE_NUMBER/$arch/RPMS/noarch/$artifact-$version-$RELEASE_NUMBER.amzn2.eks.noarch.rpm.sha256 -o $filename.sha256\n\n            if [[ $(sha256sum ${filename} | cut -d' ' -f1) != $(cut -d' ' -f1 \"${filename}.sha256\") ]] ; then \n                echo \"Checksum doesn't match!\"\n                exit 1\n            fi\n        fi\n    done\n}\n\nbuild::go::download \"${VERSION}\" \"$OUTPUT_DIR\" \"x86_64\"\nbuild::go::download \"${VERSION}\" \"$OUTPUT_DIR\" \"aarch64\"\n", "num_lines": 65}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/ansible\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nfunction instal_ansible() {\n    local -r deps=\"python3-pip\"\n    yum install -y $deps\n\n    #################### IMAGE BUILDER ####################\n    # Install image-builder build dependencies - pip, Ansible, Packer\n    # Post upgrade, pip3 got renamed to pip and moved locations. It works completely with python3\n    # Symlinking pip3 to pip, to have pip3 commands work successfully\n    if [ \"$IS_AL23\" = \"false\" ]; then \n        pip3 install --no-cache-dir -U pip setuptools\n        ln -sf $USR_LOCAL_BIN/pip $USR_BIN/pip3\n    fi\n\n    ANSIBLE_VERSION=\"$ANSIBLE_VERSION\"\n    pip3 install --user --no-cache-dir \"ansible-core==$ANSIBLE_VERSION\"\n\n    PYWINRM_VERSION=\"$PYWINRM_VERSION\"\n    pip3 install --user --no-cache-dir \"pywinrm==$PYWINRM_VERSION\"\n    \n    rm -rf ${NEWROOT}/usr/*\n    mv /root/.local/* ${NEWROOT}/usr\n\n    rm -rf /root/.cache\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || instal_ansible\n", "num_lines": 51}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/aws-cli\n\nsource $SCRIPT_ROOT/common_vars.sh\n\n\nfunction install_aws_cli() {\n    if [ $TARGETARCH == 'amd64' ]; then \n        ARCH='x86_64'\n    else \n        ARCH='aarch64'\n    fi\n\n    wget \\\n        --progress dot:giga \\\n        https://awscli.amazonaws.com/awscli-exe-linux-$ARCH.zip\n    unzip -qq awscli-exe-linux-$ARCH.zip\n    ./aws/install \n    aws --version\n\n    # install symlinks so we cant install directly to our overridden usr/local\n    if [ \"$USR_LOCAL\" != \"/usr/local\" ]; then\n        mv /usr/local/aws-cli $USR_LOCAL\n        mv /usr/local/bin/{aws,aws_completer} $USR_LOCAL_BIN\n    fi\n    \n    rm awscli-exe-linux-$ARCH.zip\n    rm -rf aws\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_aws_cli\n", "num_lines": 51}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/common_vars.sh\n\n# since we are using the minimal-base-builder\n# policycoreutils is only half installed and the rpm db\n# is technically in an invalid state\n# removing it to avoid issues in future rpm transactions\nyum remove -y policycoreutils > /dev/null 2>&1\n\n# keep rpms around since we use them in every stage\nif [ \"$IS_AL23\" = \"true\" ]; then\n    echo \"keepcache=1\" >> /etc/dnf/dnf.conf\n    rm -rf /var/cache/dnf\n    ln -s yum /var/cache/dnf\n    rm -f /var/lib/dnf/history.*\nelse\n    sed -i 's/keepcache=0/keepcache=1/g' /etc/yum.conf\n    yum history new\nfi\n\nyum install --setopt=install_weak_deps=False -y \\\n    gzip \\\n    tar \\\n    unzip \\\n    wget\n\nchmod -R 777 /newroot\nrm -rf /newroot\n", "num_lines": 47}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to install the necessary dependencies on the pod\n# building the builder-base as well as into the builder-base itself\n# Note: since we run the build in fargate we do not have access to an overlayfs\n# so we use a single script from the dockerfile instead of layers to avoid\n# layer duplicate and running out of disk space\n# This does make local builds painful.  Its recommended to add new additions\n# in their own script/layer while testing and then when you are done add\n# to here\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/bash\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nBASH_DOWNLOAD_URL=\"http://ftp.gnu.org/gnu/bash/bash-$OVERRIDE_BASH_VERSION.tar.gz\"\n\nfunction install_bash() {\n    # al23 already ships with 5.1\n    if [ \"$IS_AL23\" != \"false\" ]; then\n        return\n    fi\n\n    # Bash 4.3 is required to run kubernetes make test\n    wget --progress dot:giga $BASH_DOWNLOAD_URL\n    tar -xf bash-$OVERRIDE_BASH_VERSION.tar.gz\n    sha256sum -c $BASE_DIR/bash-checksum\n    cd bash-$OVERRIDE_BASH_VERSION\n    ./configure --prefix=${NEWROOT}/usr --without-bash-malloc\n    make\n    make install\n\n    cd ..\n    rm -rf bash-$OVERRIDE_BASH_VERSION.tar.gz bash-$OVERRIDE_BASH_VERSION\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_bash\n", "num_lines": 56}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# This script is used to install the necessary dependencies on the pod\n# building the builder-base as well as into the builder-base itself\n# Note: since we run the build in fargate we do not have access to an overlayfs\n# so we use a single script from the dockerfile instead of layers to avoid\n# layer duplicate and running out of disk space\n# This does make local builds painful.  Its recommended to add new additions\n# in their own script/layer while testing and then when you are done add\n# to here\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/buildkit\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nBUILDKIT_DOWNLOAD_URL=\"https://github.com/moby/buildkit/releases/download/$BUILDKIT_VERSION/buildkit-$BUILDKIT_VERSION.linux-$TARGETARCH.tar.gz\"\n\n\nfunction install_buildkit() {\n    wget \\\n        --progress dot:giga \\\n        $BUILDKIT_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/buildkit-$TARGETARCH-checksum\n    tar -C $USR -xzf buildkit-$BUILDKIT_VERSION.linux-$TARGETARCH.tar.gz\n    rm -rf buildkit-$BUILDKIT_VERSION.linux-$TARGETARCH.tar.gz\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_buildkit\n", "num_lines": 47}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/docker_buildx\n\nsource $SCRIPT_ROOT/common_vars.sh\n\n\nDOCKER_BUILDX_URL=\"https://github.com/docker/buildx/releases/download/$DOCKER_BUILDX_VERSION/buildx-$DOCKER_BUILDX_VERSION.linux-$TARGETARCH\"\nDOCKER_BUILDX_CHECKSUM_URL=\"https://github.com/docker/buildx/releases/download/$DOCKER_BUILDX_VERSION/checksums.txt\"\n\n\nfunction install_docker_buildx() {\n    wget \\\n        --progress dot:giga \\\n        $DOCKER_BUILDX_URL\n    sha256sum -c $BASE_DIR/docker-buildx-$TARGETARCH-checksum\n    mkdir -p ${NEWROOT}/usr/local/lib/docker/cli-plugins\n    mv buildx-$DOCKER_BUILDX_VERSION.linux-$TARGETARCH ${NEWROOT}/usr/local/lib/docker/cli-plugins/docker-buildx\n    chmod a+x ${NEWROOT}/usr/local/lib/docker/cli-plugins/docker-buildx\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_docker_buildx\n", "num_lines": 41}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/ecr-cred-helper\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nAMAZON_ECR_CRED_HELPER_DOWNLOAD_URL=\"https://amazon-ecr-credential-helper-releases.s3.us-east-2.amazonaws.com/${AMAZON_ECR_CRED_HELPER_VERSION}/linux-$TARGETARCH/docker-credential-ecr-login\"\nAMAZON_ECR_CRED_HELPER_CHECKSUM_URL=\"${AMAZON_ECR_CRED_HELPER_DOWNLOAD_URL}.sha256\"\n\nfunction install_docker_cred() {\n    wget \\\n        --progress dot:giga \\\n        $AMAZON_ECR_CRED_HELPER_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/amazon-ecr-cred-helper-$TARGETARCH-checksum\n    mv docker-credential-ecr-login $USR_BIN/\n    chmod +x $USR_BIN/docker-credential-ecr-login\n\n    ls -al $USR_BIN\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_docker_cred\n", "num_lines": 40}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/common_vars.sh\n\n# The base image is the kind-minimal image with a /etc/passwd file\n# based from the minimal base, which is setup manually.  The root\n# user's shell is configured as /sbin/nologin\n# This doesnt work for the builder-base usage in Codebuild which runs \n# certain commands specifically as root.  We need the shell to be bash.\nusermod --shell /bin/bash root\n\n# user for goss/imagebuilder\n# to make sure the home dir is created correctly, tmp move the goss plugin\n# on arm goss does not exist\nif [ -f /home/imagebuilder/.packer.d/plugins/packer-provisioner-goss ]; then\n    mv /home/imagebuilder/.packer.d/plugins/packer-provisioner-goss /tmp\nfi\n\nrm -rf /home/imagebuilder\nuseradd -ms /bin/bash -u 1100 imagebuilder\n\nif [ -f /tmp/packer-provisioner-goss ]; then\n    mkdir -p /home/imagebuilder/.packer.d/plugins/\n    mv /tmp/packer-provisioner-goss /home/imagebuilder/.packer.d/plugins/\nfi\n\n# directory setup\nmkdir -p /go/src/github.com/aws/eks-distro\n\nyum install -y \\\n    bc \\\n    bind-utils \\\n    bzip2 \\\n    cpio \\\n    curl \\\n    docker \\\n    gettext \\\n    git-core \\\n    jq \\\n    less \\\n    make \\\n    openssh-clients \\\n    openssl \\\n    patch \\\n    procps-ng \\\n    rsync \\\n    tar \\\n    unzip \\\n    vim \\\n    wget \\\n    which \\\n    yum-utils\n\n# We see issues in fargate when installing on top of these images\n# including this plugin appears to fix it\n# ref: https://unix.stackexchange.com/questions/348941/rpmdb-checksum-is-invalid-trying-to-install-gcc-in-a-centos-7-2-docker-image    \nif [ \"$IS_AL23\" = \"false\" ]; then \n    yum install -y yum-plugin-ovl\nfi\n\nif [ \"${FINAL_STAGE_BASE}\" = \"full-copy-stage\" ]; then\n    yum install -y \\\n        gcc \\\n        openssl-devel \\\n        pkgconfig \\\n        python3-pip\n\n    # for building containerd\n    yum install -y \\\n        glibc-static \\\n        libseccomp-static\n\n    # headers for btrfs do not exist in al23. well need to address this in the future\n    # if we want to build containerd with btrfs support on al23\n    if [ \"$IS_AL23\" = \"false\" ]; then \n        yum install -y btrfs-progs-devel\n    fi  \nfi\n\n#################### CLEANUP ####################\n# truncate logs\nfind /var/log -type f | while read file; do echo -ne '' > $file; done\n\n# Removing doc and man files\n# to get all symlinks run twice\nfor i in {1..2}; do\n    find /usr/share/{doc,man} \\( -xtype l -o -type f \\) \\\n        ! \\( -iname '*lice*' -o -iname '*copy*' -o -iname '*gpl*' -o -iname '*not*' -o -iname \"*credits*\" \\) \\\n        -delete\ndone\nfind /usr/share/{doc,man} -type d -empty -delete\n\nrm -rf /root/.cache\n", "num_lines": 111}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/common_vars.sh\n\n$SCRIPT_ROOT/install_base_yum_packages.sh\n\nyum install --setopt=install_weak_deps=False -y \\\n    gcc \\\n    git-core \\\n    make \\\n    pkgconfig\n\n", "num_lines": 30}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/gh-cli\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nGITHUB_CLI_DOWNLOAD_URL=\"https://github.com/cli/cli/releases/download/v${GITHUB_CLI_VERSION}/gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz\"\nGITHUB_CLI_CHECKSUM_URL=\"https://github.com/cli/cli/releases/download/v${GITHUB_CLI_VERSION}/gh_${GITHUB_CLI_VERSION}_checksums.txt\"\n\nfunction install_gh_cli() {\n    wget --progress dot:giga $GITHUB_CLI_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/github-cli-$TARGETARCH-checksum\n    tar -xzf gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz\n    mv gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH/bin/gh $USR_BIN\n    rm -rf gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_gh_cli\n", "num_lines": 37}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nVERSION=\"$1\"\n\nGOLANG_MAJOR_VERSION=$(if [[ $(echo \"$VERSION\"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${VERSION%.*}; else echo ${VERSION%-*}; fi)\n\nNEWROOT=/golang-${GOLANG_MAJOR_VERSION}\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nmkdir -p /go/src /go/bin /go/pkg\n\nfunction build::go::symlink() {\n    local -r version=$1\n\n    # Removing the last number as we only care about the major version of golang\n    local -r majorversion=$(if [[ $(echo \"$version\"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${version%.*}; else echo ${version%-*}; fi)\n    mkdir -p ${GOPATH}/go${majorversion}/bin\n    \n    for binary in go gofmt; do\n        ln -s /root/sdk/go${version}/bin/${binary} ${GOPATH}/go${majorversion}/bin/${binary}\n    done\n    \n    if [ \"$version\" != \"$majorversion\" ]; then\n        ln -s ${GOPATH}/bin/go${version} ${GOPATH}/bin/go${majorversion}\n    fi\n}\n\nfunction build::go::install(){\n    # Set up specific go version by using go get, additional versions apart from default can be installed by calling\n    # the function again with the specific parameter.\n    local version=${1%-*}\n    build::go::extract $version\n    build::go::symlink $version\n}\n\nfunction build::go::extract() {\n    local version=$1\n\n    if [ $TARGETARCH == 'amd64' ]; then\n        local arch='x86_64'\n    else\n        local arch='aarch64'\n    fi\n\n    mkdir -p /tmp/go-extracted\n    for rpm in /tmp/$arch/golang-*.noarch.rpm /tmp/$arch/golang-*.$arch.rpm ; do $(cd /tmp/go-extracted && rpm2cpio $rpm | cpio -idm && rm -f $rpm); done\n\n    local -r golang_version=$(/tmp/go-extracted/usr/lib/golang/bin/go version | grep -o \"go[0-9].* \" | xargs)\n\n    mkdir -p /root/sdk/$golang_version\n    mv /tmp/go-extracted/usr/lib/golang/* /root/sdk/$golang_version\n\n    for license_dir in \"/usr/share/licenses/golang\" \"/usr/share/doc/golang-$VERSION\"; do\n        if [ -d /tmp/go-extracted/$license_dir ]; then\n            mv /tmp/go-extracted/$license_dir/* /root/sdk/$golang_version\n        fi\n    done\n\n    version=$(echo \"$golang_version\" | grep -o \"[0-9].*\")\n    ln -s /root/sdk/go${version}/bin/go ${GOPATH}/bin/$golang_version\n\n    rm -rf /tmp/go-extracted /tmp/golang-*.rpm\n}\n\n\nbuild::go::install \"${VERSION}\"\n\n# symlink default golang install to newroot bin\nfor binary in go gofmt; do\n    ln -s ${GOPATH}/go${GOLANG_MAJOR_VERSION}/bin/${binary} ${USR_BIN}/${binary}\ndone\n\nmkdir -p ${NEWROOT}/root\nmv /root/sdk ${NEWROOT}/root\nmv ${GOPATH} ${NEWROOT}/${GOPATH}\n", "num_lines": 96}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/goss\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nGOSS_DOWNLOAD_URL=\"https://github.com/YaleUniversity/packer-provisioner-goss/releases/download/v${GOSS_VERSION}/packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz\"\nGOSS_CHECKSUM_URL=\"https://github.com/YaleUniversity/packer-provisioner-goss/releases/download/v${GOSS_VERSION}/packer-provisioner-goss_v${GOSS_VERSION}_SHA256SUMS\"\n\nfunction install_goss() {\n    mkdir -p /goss/home/imagebuilder/.packer.d/plugins\n\n    # Installing Goss for imagebuilder validation    \n    wget \\\n        --progress dot:giga \\\n        $GOSS_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/goss-$TARGETARCH-checksum\n    tar -C ${NEWROOT}/home/imagebuilder/.packer.d/plugins -xzf packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz\n    rm -rf packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_goss\n", "num_lines": 41}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/govc\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nif [ $TARGETARCH == 'amd64' ]; then \n    ARCH='x86_64'\nelse \n    ARCH='arm64'\nfi\n\nGOVC_FILENAME=\"govc_Linux_$ARCH.tar.gz\"\nGOVC_DOWNLOAD_URL=\"https://github.com/vmware/govmomi/releases/download/v${GOVC_VERSION}/${GOVC_FILENAME}\"\nGOVC_CHECKSUM_URL=\"https://github.com/vmware/govmomi/releases/download/v${GOVC_VERSION}/checksums.txt\"\n\nfunction install_govc() {\n    # Installing govc CLI\n    wget \\\n        --progress dot:giga \\\n        $GOVC_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/govc-$TARGETARCH-checksum\n    tar -xf govc_Linux_$ARCH.tar.gz\n    mv govc $USR_BIN/govc\n    chmod +x $USR_BIN/govc\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_govc\n", "num_lines": 47}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nVERSION=$(go version | grep -o \"go[0-9].* \")\nGOLANG_MAJOR_VERSION=$(if [[ $(echo \"$VERSION\"|awk -F'.' '{print NF}') -ge 3 ]]; then echo ${VERSION%.*}; else echo ${VERSION%-*}; fi)\n\nNEWROOT=/go-licenses-${GOLANG_MAJOR_VERSION#go}\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nfunction install_go_licenses() {\n\n    # installing go-licenses has to happen after we have set the main go\n    # to symlink to the one in /root/sdk to ensure go-licenses gets built\n    # with GOROOT pointed to /root/sdk/go... instead of /usr/local/go so it\n    # is able to properly packages from the standard Go library\n    # We currently  use 1.19, 1.17 or 1.16, so installing for all\n    if [ \"${GOLANG_MAJOR_VERSION}\" = \"go1.16\" ]; then\n        GO111MODULE=on GOBIN=${NEWROOT}/${GOPATH}/${GOLANG_MAJOR_VERSION}/bin go install github.com/jaxesn/go-licenses@4497a2a38565e4e6ad095ea8117c25ecd622d0cc\n    else\n        GO111MODULE=on GOBIN=${NEWROOT}/${GOPATH}/${GOLANG_MAJOR_VERSION}/bin go install github.com/jaxesn/go-licenses@6800d77c11d0ef8628e7eda908b1d1149383ca48\n    fi\n\n    # symlink to go/bin and depending on which go-licenses vs is added last to\n    # the final image, will take precedent and be the default\n    # similiar to the strategy with golang\n    mkdir -p ${NEWROOT}/${GOPATH}/bin\n    ln -s ${GOPATH}/${GOLANG_MAJOR_VERSION}/bin/go-licenses ${NEWROOT}/${GOPATH}/bin/go-licenses\n    \n    rm -rf ${GOPATH}\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_go_licenses\n", "num_lines": 51}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/helm\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nHELM_DOWNLOAD_URL=\"https://get.helm.sh/helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz\"\nHELM_CHECKSUM_URL=\"$HELM_DOWNLOAD_URL.sha256\"\n\n\nfunction install_helm() {\n    # Installing Helm\n    wget \\\n        --progress dot:giga \\\n        $HELM_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/helm-$TARGETARCH-checksum\n    tar -xzvf helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz linux-$TARGETARCH/helm\n    mv linux-$TARGETARCH/helm $USR_BIN/helm\n    chmod +x $USR_BIN/helm\n    rm -f helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_helm\n", "num_lines": 42}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/hugo\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nif [ $TARGETARCH == 'amd64' ]; then \n    HUGO_FILENAME=\"hugo_extended_${HUGO_VERSION}_Linux-64bit.tar.gz\"\nelse\n    HUGO_FILENAME=\"nhugo_extended_${HUGO_VERSION}_Linux-ARM64.tar.gz\"\nfi\nHUGO_DOWNLOAD_URL=\"https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/$HUGO_FILENAME\"\nHUGO_CHECKSUM_URL=\"https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_checksums.txt\"\n\n\nfunction install_hugo() {\n    if [ $TARGETARCH == 'amd64' ]; then \n        ARCH='64bit'\n    else \n        ARCH='ARM64'\n        # there is no extended build for arm\n        return\n    fi\n\n    # Installing Hugo for docs\n    wget --progress dot:giga $HUGO_DOWNLOAD_URL\n    sha256sum -c ${BASE_DIR}/hugo-$TARGETARCH-checksum\n    tar -xf hugo_extended_${HUGO_VERSION}_Linux-${ARCH}.tar.gz\n    mv hugo $USR_BIN/hugo\n    rm -rf hugo_extended_${HUGO_VERSION}_Linux-${ARCH}.tar.gz LICENSE README.md\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_hugo\n", "num_lines": 52}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/linuxkit\n\nsource $SCRIPT_ROOT/common_vars.sh\n\n\nfunction install_linuxkit() {\n    # linuxkit is used by tinkerbell/hook for building an operating system installation environment (osie)\n    # We need a higher version of linuxkit hence we do go install of a particular commit\n    GO111MODULE=on GOBIN=${GOPATH}/go1.19/bin ${GOPATH}/go1.19/bin/go install github.com/linuxkit/linuxkit/src/cmd/linuxkit@$LINUXKIT_VERSION\n\n    mv ${GOPATH}/go1.19/bin/linuxkit ${USR_BIN}/linuxkit\n\n    rm -rf ${GOPATH}\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_linuxkit\n", "num_lines": 37}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/nodejs\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nif [ $TARGETARCH == 'amd64' ]; then \n    NODEJS_FILENAME=\"node-$NODEJS_VERSION-linux-x64.tar.gz\"\n    NODEJS_FOLDER=\"node-$NODEJS_VERSION-linux-x64\"\nelse\n    NODEJS_FILENAME=\"node-$NODEJS_VERSION-linux-arm64.tar.gz\"\n    NODEJS_FOLDER=\"node-$NODEJS_VERSION-linux-arm64\"\nfi\nNODEJS_DOWNLOAD_URL=\"https://nodejs.org/dist/$NODEJS_VERSION/$NODEJS_FILENAME\"\nNODEJS_CHECKSUM_URL=\"https://nodejs.org/dist/$NODEJS_VERSION/SHASUMS256.txt.asc\"\n\n\nfunction install_nodejs() {\n    # Installing NodeJS to run attribution generation script\n    wget --progress dot:giga $NODEJS_DOWNLOAD_URL\n    sha256sum -c ${BASE_DIR}/nodejs-$TARGETARCH-checksum\n    tar -C $USR --strip-components=1 -xzf $NODEJS_FILENAME $NODEJS_FOLDER\n    rm -rf $NODEJS_FILENAME\n}\n\nfunction install_generate_attribution() {\n    # Installing attribution generation script\n    mkdir ${NEWROOT}/generate-attribution-file\n    mv /package*.json /generate-attribution /generate-attribution-file.js /LICENSE-2.0.txt ${NEWROOT}/generate-attribution-file\n    \n    cd ${NEWROOT}/generate-attribution-file\n    ln -s /generate-attribution-file/generate-attribution $USR_BIN/generate-attribution\n\n    ln -s /$USR_BIN/node /usr/bin/node\n    $USR_BIN/npm install\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || (install_nodejs && install_generate_attribution)\n", "num_lines": 57}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/packer\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nPACKER_DOWNLOAD_URL=\"https://releases.hashicorp.com/packer/$PACKER_VERSION/packer_${PACKER_VERSION}_linux_$TARGETARCH.zip\"\nPACKER_CHECKSUM_URL=\"https://releases.hashicorp.com/packer/$PACKER_VERSION/packer_${PACKER_VERSION}_SHA256SUMS\"\n\nfunction install_packer() {\n    # put packer in /usr/local/bin so it takes precedent\n    # over the /usr/sbin/packer which is supplied by the cracklib package\n    wget \\\n        --progress dot:giga \\\n        $PACKER_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/packer-$TARGETARCH-checksum\n    unzip -o packer_${PACKER_VERSION}_linux_$TARGETARCH.zip -d $USR_LOCAL_BIN\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_packer\n", "num_lines": 39}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/skopeo\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nfunction install_skopeo() {\n    local -r deps=\"device-mapper-devel libassuan-devel gpgme-devel\"\n    yum install -y $deps\n\n    # Installing Skopeo\n    git clone https://github.com/containers/skopeo\n    cd skopeo\n    git checkout $SKOPEO_VERSION\n    make bin/skopeo\n    mv bin/skopeo $USR_BIN/skopeo\n\n    cd ..\n    rm -rf ${GOPATH} skopeo\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_skopeo\n", "num_lines": 41}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/tuftool\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nRUSTUP_DOWNLOAD_URL=\"https://sh.rustup.rs\"\n\n\nfunction install_tuftool() {\n    local -r deps=\"openssl openssl-devel\"\n    yum install -y $deps\n\n    # Installing Tuftool for Bottlerocket downloads\n    curl -fsS $RUSTUP_DOWNLOAD_URL | CARGO_HOME=$CARGO_HOME RUSTUP_HOME=$RUSTUP_HOME sh -s -- -y\n    find $CARGO_HOME/bin -type f -not -name \"cargo\" -not -name \"rustc\" -not -name \"rustup\" -delete\n    $CARGO_HOME/bin/rustup default stable\n    CARGO_NET_GIT_FETCH_WITH_CLI=true $CARGO_HOME/bin/cargo install --force -v --root $CARGO_HOME tuftool \n    cp $CARGO_HOME/bin/tuftool $USR_BIN/tuftool\n\n    rm -rf $RUSTUP_HOME $CARGO_HOME\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_tuftool\n", "num_lines": 43}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNEWROOT=/yq\n\nsource $SCRIPT_ROOT/common_vars.sh\n\nYQ_DOWNLOAD_URL=\"https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/yq_linux_$TARGETARCH.tar.gz\"\nYQ_CHECKSUM_URL=\"https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/checksums\"\nYQ_CHECKSUM_ORDER_URL=\"https://github.com/mikefarah/yq/releases/download/${YQ_VERSION}/checksums_hashes_order\"\n\n\nfunction install_yq() {\n    # needed to parse eks-d release yaml to get latest artifacts\n    wget \\\n        --progress dot:giga \\\n        $YQ_DOWNLOAD_URL\n    sha256sum -c $BASE_DIR/yq-$TARGETARCH-checksum\n    tar -C $USR_BIN -xzf yq_linux_$TARGETARCH.tar.gz\n    mv $USR_BIN/yq_linux_$TARGETARCH $USR_BIN/yq\n}\n\n[ ${SKIP_INSTALL:-false} != false ] || install_yq\n", "num_lines": 41}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nyum history | awk -F '|' 'NR>2{print $1}' | awk 'NF{print $1}' | grep -o '[0-9]\\+' | while read id; do yum history undo --skip-broken --setopt=protected_packages=False -y $id; done\n", "num_lines": 20}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nCHECKSUMS_ROOT=\"$SCRIPT_ROOT/..\"\n\neval $(yq  e 'to_entries | .[] | [.key,.value] | join(\"=\") ' versions.yaml)\n\nfor TARGETARCH in arm64 amd64; do\n    source $SCRIPT_ROOT/versions.sh\n\n    # YQ\n    yq_checksum_order=($(curl -sSL --retry 5 $YQ_CHECKSUM_ORDER_URL))\n    yq_checksums=$(curl -sSL --retry 5 -v --silent $YQ_CHECKSUM_URL)\n    yq_checksums=$(echo \"$yq_checksums\" | grep yq_linux_$TARGETARCH.tar.gz | cut -d \":\" -f 2)\n    IFS=' ' read -r -a yq_checksums_ar <<< \"$yq_checksums\"\n    \n    yq_checksum_index=-1\n    for i in \"${!yq_checksum_order[@]}\"; do\n        if [[ \"${yq_checksum_order[$i]}\" = \"SHA-256\" ]]; then\n            yq_checksum_index=$(($i+1))\n        fi\n    done\n    echo $yq_checksum_index\n    echo \"${yq_checksums_ar[*]}\"\n    sha256=\"${yq_checksums_ar[$yq_checksum_index]}\"\n    echo \"$sha256  yq_linux_$TARGETARCH.tar.gz\" > $CHECKSUMS_ROOT/checksums/yq-$TARGETARCH-checksum\n\n    # AMAZON_ECR_CRED_HELPER\n    curl -sSL --retry 5 $AMAZON_ECR_CRED_HELPER_CHECKSUM_URL -o $CHECKSUMS_ROOT/checksums/amazon-ecr-cred-helper-$TARGETARCH-checksum\n\n    # BUILDKIT\n    sha256=$(curl -sSL --retry 5 $BUILDKIT_DOWNLOAD_URL | sha256sum | awk '{print $1}')\n    echo \"$sha256  buildkit-$BUILDKIT_VERSION.linux-$TARGETARCH.tar.gz\" > $CHECKSUMS_ROOT/checksums/buildkit-$TARGETARCH-checksum\n\n    # DOCKER_BUILDX\n    echo \"$(curl -sSL --retry 5 -v --silent $DOCKER_BUILDX_CHECKSUM_URL 2>&1 | grep buildx-${DOCKER_BUILDX_VERSION}.linux-$TARGETARCH | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/docker-buildx-$TARGETARCH-checksum\n\n    # GITHUB CLI\n    echo \"$(curl -sSL --retry 5 -v --silent $GITHUB_CLI_CHECKSUM_URL 2>&1 | grep  gh_${GITHUB_CLI_VERSION}_linux_$TARGETARCH.tar.gz | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/github-cli-$TARGETARCH-checksum\n\n    # PACKER\n    echo \"$(curl -sSL --retry 5 -v --silent $PACKER_CHECKSUM_URL 2>&1 | grep packer_${PACKER_VERSION}_linux_$TARGETARCH.zip | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/packer-$TARGETARCH-checksum\n\n    # NODEJS\n    echo \"$(curl -sSL --retry 5 -v --silent $NODEJS_CHECKSUM_URL 2>&1 | grep $NODEJS_FILENAME | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/nodejs-$TARGETARCH-checksum\n\n    # HELM\n    sha256=$(curl -sSL --retry 5 $HELM_CHECKSUM_URL)\n    echo \"$sha256  helm-v${HELM_VERSION}-linux-$TARGETARCH.tar.gz\" > $CHECKSUMS_ROOT/checksums/helm-$TARGETARCH-checksum\n\n    # GOVC\n    echo \"$(curl -sSL --retry 5 -v  $GOVC_CHECKSUM_URL 2>&1 | grep $GOVC_FILENAME | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/govc-$TARGETARCH-checksum\n\n    # GOSS\n    echo \"$(curl -sSL --retry 5 -v --silent $GOSS_CHECKSUM_URL 2>&1 | grep packer-provisioner-goss-v${GOSS_VERSION}-linux-$TARGETARCH.tar.gz | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/goss-$TARGETARCH-checksum\ndone\n\n# HUGO\necho \"$(curl -sSL --retry 5 -v --silent $HUGO_CHECKSUM_URL 2>&1 | grep $HUGO_FILENAME | cut -d \":\" -f 2)\" > $CHECKSUMS_ROOT/checksums/hugo-$TARGETARCH-checksum\n\n# BASH\nsha256=$(curl -sSL --retry 5 $BASH_DOWNLOAD_URL | sha256sum | awk '{print $1}')\necho \"$sha256  bash-$OVERRIDE_BASH_VERSION.tar.gz\" > $CHECKSUMS_ROOT/checksums/bash-checksum\n", "num_lines": 80}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/common_vars.sh\n\nuname -a\n\ndocker-credential-ecr-login -v\nyq --version\ngh --version\ngovc version\nhelm version\n/usr/local/lib/docker/cli-plugins/docker-buildx version\nbuildctl --version\naws --version\nbash --version\n\n\nif [ $TARGETARCH == 'amd64' ]; then \n    hugo version\n    # goss\nfi\n\ntuftool --help\nskopeo --version\n\n# node + go + gcc are only included in the standard image\nif [ \"${FINAL_STAGE_BASE}\" = \"full-copy-stage\" ]; then\n    packer --version\n    ansible --version\n\n    node --version\n\n    # validate default symlinks are correctly setup\n    go version\n    go-licenses --help\n    \n    /go/bin/go1.16 version\n    /go/go1.16/bin/go-licenses --help\n    linuxkit version\n    /go/bin/go1.17 version\n    /go/go1.17/bin/go-licenses --help\n    /go/bin/go1.18 version\n    /go/go1.18/bin/go-licenses --help\n    /go/bin/go1.19 version\n    /go/go1.19/bin/go-licenses --help\n\n    gcc --version\nfi\n", "num_lines": 66}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nexport SKIP_INSTALL=\"true\"\n\nsource $SCRIPT_ROOT/install_aws_cli.sh\nsource $SCRIPT_ROOT/install_buildkit.sh\nsource $SCRIPT_ROOT/install_docker_buildx.sh\nsource $SCRIPT_ROOT/install_ecr_cred_helper.sh\nsource $SCRIPT_ROOT/install_gh_cli.sh\nsource $SCRIPT_ROOT/install_yq.sh\nsource $SCRIPT_ROOT/install_packer.sh\nsource $SCRIPT_ROOT/install_nodejs.sh\nsource $SCRIPT_ROOT/install_helm.sh\nsource $SCRIPT_ROOT/install_goss.sh\nsource $SCRIPT_ROOT/install_govc.sh\nsource $SCRIPT_ROOT/install_hugo.sh\nsource $SCRIPT_ROOT/install_bash.sh\n", "num_lines": 33}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nIMAGE_NAME=\"$1\"\nAL_TAG=\"$2\"\nNAME_FOR_TAG_FILE=\"$3\"\n\nif [[ $IMAGE_NAME == *-builder ]]; then\n    # ignore checking builder images\n    exit 0\nfi\n\nBASE_IMAGE_TAG=\"$(yq e \".al$AL_TAG.\\\"$NAME_FOR_TAG_FILE\\\"\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\"\nBASE_IMAGE=public.ecr.aws/eks-distro-build-tooling/$IMAGE_NAME:$BASE_IMAGE_TAG\nmkdir -p check-update\n\ncat << EOF > check-update/Dockerfile\nFROM $BASE_IMAGE AS base_image\n\nFROM public.ecr.aws/amazonlinux/amazonlinux:$AL_TAG as builder\n\nRUN rm -rf /var/lib/rpm\nCOPY --from=base_image /var/lib/rpm /var/lib/rpm\nCOPY --from=base_image /etc/yum.repos.d /etc/yum.repos.d\n\nRUN set -x && \\\n    if grep -q \"2023\" \"/etc/os-release\"; then \\\n        yum check-update --security --releasever=latest  > ./check_update_output; echo \\$? > ./return_value; \\\n    else \\\n        yum check-update --security  > ./check_update_output; echo \\$? > ./return_value; \\    \n    fi && \\\n    cat ./check_update_output | awk '/^$/,0' | awk '{print \\$1}' > ./update_packages\n\nFROM scratch\n\nCOPY --from=builder ./return_value ./return_value\nCOPY --from=builder ./update_packages ./update_packages\nEOF\n\n$SCRIPT_ROOT/../scripts/buildkit.sh build --frontend dockerfile.v0 \\\n         --opt platform=linux/amd64 \\\n         --opt filename=./check-update/Dockerfile \\\n         --local context=. \\\n         --progress plain \\\n         --output type=local,dest=/tmp/${IMAGE_NAME} \\\n    || {\n            mkdir -p /tmp/${IMAGE_NAME}\n            echo \"100\" > /tmp/${IMAGE_NAME}/return_value\n            echo \"\" > /tmp/${IMAGE_NAME}/update_packages\n        }\n\nRETURN_STATUS=$(cat /tmp/${IMAGE_NAME}/return_value)\n\nif [ \"$JOB_TYPE\" != \"periodic\" ]; then\n    echo \"none\" > ./check-update/${NAME_FOR_TAG_FILE}\n    exit 0\nfi\n\nif [ $RETURN_STATUS -eq 100 ]; then\n    cat /tmp/${IMAGE_NAME}/update_packages > ${SCRIPT_ROOT}/../eks-distro-base-updates/${AL_TAG}/update_packages-${NAME_FOR_TAG_FILE}\n    echo \"updates\" > ./check-update/${NAME_FOR_TAG_FILE}\nelif [ $RETURN_STATUS -eq 0 ]; then\n    echo \"none\" > ./check-update/${NAME_FOR_TAG_FILE}\nelif [ $RETURN_STATUS -eq 1 ]; then\n    echo \"error\" > ./check-update/${NAME_FOR_TAG_FILE}\nfi\n", "num_lines": 86}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nIMAGE_NAME=\"$1\"\nAL_TAG=\"$2\"\nNAME_FOR_TAG_FILE=\"$3\"\n\nfunction retry() {\n    local n=1\n    local max=120\n    local delay=5\n    while true; do\n        \"$@\" && break || {\n            if [[ $n -lt $max ]]; then\n            ((n++))\n            >&2 echo \"Command failed. Attempt $n/$max:\"\n            sleep $delay;\n            else\n            fail \"The command has failed after $n attempts.\"\n            fi\n        }\n    done\n}\n\n\nBASE_IMAGE_TAG=\"$(yq e \".windows.\\\"$NAME_FOR_TAG_FILE\\\"\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\"\n\nmkdir -p check-update\n\nif [ \"$BASE_IMAGE_TAG\" = \"null\" ]; then\n    echo \"updates\" > ./check-update/${NAME_FOR_TAG_FILE} \n    exit 0\nfi\n\nBASE_IMAGE=public.ecr.aws/eks-distro-build-tooling/$IMAGE_NAME\n\n# Pull the buildinfo from the last published image which will contain the sha of the two windows images\n# used to build that image. Compare these sha with the current shas tagged upstream for this given\n# windows version. If the current tag points to a different sha, the image needs updating\nBUILDINFO=$(retry skopeo inspect --config --override-os windows --override-arch amd64 docker://$BASE_IMAGE:$BASE_IMAGE_TAG --raw   | jq -r '.\"moby.buildkit.buildinfo.v1\"' | base64 -d)\n\nfor variant in \"nanoserver\" \"servercore\"; do\n    SOURCE_IMAGE_REF=$(jq -r \".sources | .[] | select(.ref | contains(\\\"$variant\\\")) | .ref\" <<< \"$BUILDINFO\")\n    SOURCE_IMAGE_PIN=$(jq -r \".sources | .[] | select(.ref | contains(\\\"$variant\\\")) | .pin\" <<< \"$BUILDINFO\")\n    \n    if [ \"$(retry docker buildx imagetools inspect --raw $SOURCE_IMAGE_REF@$SOURCE_IMAGE_PIN)\" != \"$(retry docker buildx imagetools inspect --raw $SOURCE_IMAGE_REF)\" ]; then\n        echo \"updates\" > ./check-update/${NAME_FOR_TAG_FILE}\n        exit 0\n    fi\ndone\n\necho \"none\" > ./check-update/${NAME_FOR_TAG_FILE}\n", "num_lines": 70}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nIMAGE_NAME=\"$1\"\nIMAGE=\"$2\"\nLATEST_IMAGE=\"$3\"\nWINDOWS_IMAGE_VERSION=\"$4\"\nWINDOWS_IMAGE_REGISTRY=\"$5\"\nWINDOWS_BASE_IMAGE_NAME=\"$6\"\n\nfunction retry() {\n    local n=1\n    local max=120\n    local delay=5\n    while true; do\n        \"$@\" && break || {\n            if [[ $n -lt $max ]]; then\n            ((n++))\n            >&2 echo \"Command failed. Attempt $n/$max:\"\n            sleep $delay;\n            else\n            fail \"The command has failed after $n attempts.\"\n            fi\n        }\n    done\n}\n\nif [ ! -f /tmp/$IMAGE_NAME-metadata.json ]; then\n    echo \"No metadata file for image: /tmp/$IMAGE_NAME-metadata.json!\"\n    exit 1\nfi\n\n# need to remove mediaType from descri since buildx segfaults when it is set\njq -r '.\"containerimage.descriptor\"  | {size, digest}' /tmp/$IMAGE_NAME-metadata.json > /tmp/$IMAGE_NAME-descr.json\n\nretry docker buildx imagetools inspect --raw $WINDOWS_IMAGE_REGISTRY/$WINDOWS_BASE_IMAGE_NAME:$WINDOWS_IMAGE_VERSION \\\n    | jq '.manifests[0] | {platform}' \\\n    | jq add -s - /tmp/$IMAGE_NAME-descr.json > /tmp/$IMAGE_NAME-descr-final.json\n\n\nretry docker buildx imagetools create --dry-run -f /tmp/$IMAGE_NAME-descr-final.json -t $IMAGE -t $LATEST_IMAGE > /tmp/$IMAGE_NAME-manfiest-final.json\n\ncat  /tmp/$IMAGE_NAME-manfiest-final.json\n\nif [ \"$(jq '.manifests[].platform | select( has(\"os.version\") == true ) | .\"os.version\"' /tmp/$IMAGE_NAME-manfiest-final.json | wc -l | xargs)\" != \"1\" ]; then\n    echo \"windows images do not have os.version set!\"\n    exit 1\nfi\n\nretry docker buildx imagetools create -f /tmp/$IMAGE_NAME-descr-final.json -t $IMAGE -t $LATEST_IMAGE\n\nretry docker buildx imagetools inspect $IMAGE\n\n# Public ecr's tagging appears to have some delay when retagging existing tags, like latest\n# retry the diff to give it time to make sure the latest manifest has been updated to new verion\nfunction validate_latest() {\n    if ! diff <(retry docker buildx imagetools inspect $IMAGE --raw) <(retry docker buildx imagetools inspect $LATEST_IMAGE --raw); then\n        echo \"image manifest and latest manifest do not match!\"\n        return 1\n    fi\n}\n\nretry validate_latest\n\nrm -rf /tmp/$IMAGE_NAME-*.json\n", "num_lines": 82}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMAKE_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nNL=$'\\n'\nHEADER=\"########### DO NOT EDIT #############################\"\nFOOTER=\"########### END GENERATED ###########################\"\n\nMAKEFILE=$MAKE_ROOT/Makefile\nHELPFILE=$MAKE_ROOT/Help.mk\n\nSED=sed\nif [ \"$(uname -s)\" = \"Darwin\" ]; then\n    SED=gsed\nfi\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $MAKEFILE\n# remove trailing newlines\nprintf %s \"$(< $MAKEFILE)\" > $MAKEFILE\n\ntouch $HELPFILE\n\n$SED -i \"/$HEADER/,/$FOOTER/d\" $HELPFILE\n# remove trailing newlines\nprintf %s \"$(< $HELPFILE)\" > $HELPFILE\n\n\nVARIANTS=$(make --no-print-directory -C $MAKE_ROOT var-value-MINIMAL_VARIANTS)\nVARIANTS=(${VARIANTS// / })\n\nMAIN_MINIMAL_TARGETS=\"${NL}${NL}##@ Main Minimal Targets\"\nEXPORT_MINIMAL_TARGETS=\"${NL}${NL}##@ Package Export Minimal Targets\"\nVALIDATE_MINIMAL_TARGETS=\"${NL}${NL}##@ Validate Minimal Targets\"\nTEST_MINIMAL_TARGETS=\"${NL}${NL}##@ Test Minimal Targets\"\nUPDATE_MINIMAL_TARGETS=\"${NL}${NL}##@ Update Minimal Targets\"\nCREATE_PR_MINIMAL_TARGETS=\"${NL}${NL}##@ Create PR Minimal Targets\"\n\nfor variant in \"${VARIANTS[@]}\"; do\n    MAIN_MINIMAL_TARGETS+=\"${NL}minimal-images-${variant}: ## Build, export packages, validate and run tests for minimal variant \\`${variant}\\`\"\n    EXPORT_MINIMAL_TARGETS+=\"${NL}packages-export-minimal-images-${variant}: ## Export packages for minimal variant \\`${variant}\\`\"\n    VALIDATE_MINIMAL_TARGETS+=\"${NL}validate-minimal-images-${variant}: ## Validate for minimal variant \\`${variant}\\`\"\n    TEST_MINIMAL_TARGETS+=\"${NL}test-minimal-images-${variant}: ## Run tests for minimal variant \\`${variant}\\`\"\n    UPDATE_MINIMAL_TARGETS+=\"${NL}minimal-update-${variant}: ## Run update logic for minimal variant \\`${variant}\\`\"\n    CREATE_PR_MINIMAL_TARGETS+=\"${NL}minimal-create-pr-${variant}: ## Run create pr logic for minimal variant \\`${variant}\\`\"\ndone\n\nCOMPILERS_TARGETS=\"${NL}${NL}##@ Compiler Images Targets\"\nCOMPILERS=$(make --no-print-directory -C $MAKE_ROOT var-value-COMPILERS)\nCOMPILERS=(${COMPILERS// / })\nfor compiler in \"${COMPILERS[@]}\"; do\n    COMPILERS_TARGETS+=\"${NL}${compiler}-compiler-images: ## Build compiler images for all versions of ${compiler}\"\n    VERSIONS=$(make --no-print-directory -C $MAKE_ROOT var-value-BASE_${compiler^^}_VARIANT_VERSIONS)\n    VERSIONS=(${VERSIONS// / })\n    for version in \"${VERSIONS[@]}\"; do\n        COMPILERS_TARGETS+=\"${NL}${compiler}-${version}-compiler-images: ## Build compiler images for ${compiler}-${version}\"\n    done\ndone\n\ncat >> $HELPFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n${MAIN_MINIMAL_TARGETS}${EXPORT_MINIMAL_TARGETS}${VALIDATE_MINIMAL_TARGETS}${TEST_MINIMAL_TARGETS}${UPDATE_MINIMAL_TARGETS}${CREATE_PR_MINIMAL_TARGETS}${COMPILERS_TARGETS}\n\n${FOOTER}\nEOF\n\ncat >> $MAKEFILE << EOF\n${NL}${NL}${NL}${HEADER}\n# To update call: make add-generated-help-block\n# This is added to help document dynamic targets and support shell autocompletion\n# Run make help for a formatted help block with all targets\ninclude Help.mk\n${FOOTER}\nEOF\n", "num_lines": 93}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nMIRROR=$(curl -s http://amazonlinux.default.amazonaws.com/2/core/latest/debuginfo/x86_64/mirror.list)\nVERSION=$(curl -s $MIRROR/repodata/primary.xml.gz | gunzip | sed -rn 's/^.*python3-debuginfo-(.*)\\-[0-9].amzn.*$/\\1/p' | sed '/-/!{s/$/_/}' | sort -V | sed 's/_$//' | tail -1)\n\nif [ -f /etc/os-release ] && grep \"Amazon Linux 2\" /etc/os-release; then\n    if [ \"$(yum info python3  | grep \"^Version\" | cut -d: -f2 | xargs)\" != \"$VERSION\" ]; then\n        echo \"Yum version does not match curl'd!\"\n        exit 1\n    fi\nfi\n\necho $VERSION\n", "num_lines": 32}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nIMAGE_TAG=$1\nIMAGE_NAME=$2\nAL_TAG=$3\nPR_BRANCH=\"$4\"\n\nif [ \"$AL_TAG\" != \"windows\" ]; then\n    AL_TAG=\"al$AL_TAG\"\nfi\n\nOLD_TAG=\"$(yq e \".al$AL_TAG.\\\"$IMAGE_NAME\\\"\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\"\nBASE_IMAGE_TAG_FILE=\"$(echo ${IMAGE_NAME^^} | sed 's/[\\.-]/_/g')_TAG_FILE\"\n\n${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh eks-distro-build-tooling $PR_BRANCH\n${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh eks-distro-build-tooling $OLD_TAG \".$AL_TAG.\\\"$IMAGE_NAME\\\" |= \\\"$IMAGE_TAG\\\"\" \"EKS_DISTRO_TAG_FILE.yaml\" true\n", "num_lines": 36}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nOTHER_CLONE_ROOT=${OTHER_CLONE_ROOT:-${SCRIPT_ROOT}/../../..}\nif [ $REPO_OWNER = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\nfi\n\nEXTRA_PR_BODY=\"\"\n\nREPOS=(eks-distro eks-anywhere-build-tooling eks-anywhere)\nfor repo in \"${REPOS[@]}\"; do\n    ${SCRIPT_ROOT}/../pr-scripts/update_local_branch.sh \"$repo\"    \ndone\nwhile IFS=, read -r key\ndo\n    key=${key:2} # strip leading - space\n    while IFS=, read -r image\n    do\n        image=${image:2} # strip leading - space\n        BASE_IMAGE_TAG_FILE=\"$(echo ${image^^} | tr '-' '_')_TAG_FILE\"\n\n        if [[ \"$key\" == \"al2023\" ]]; then\n            BASE_IMAGE_TAG_FILE=\"$(echo ${image^^} | tr '-' '_')_AL2023_TAG_FILE\"\n        fi\n\n        IMAGE_TAG=$(yq e \".$key.\\\"$image\\\"\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\n        # we will set the tag to null to trigger new builds. we dont want PRs being open setting\n        # tag file values to null\n        if [[ \"${IMAGE_TAG}\" = \"null\" ]]; then\n            continue\n        fi\n        for repo in \"${REPOS[@]}\"; do\n            ${SCRIPT_ROOT}/../pr-scripts/update_image_tag.sh \"$repo\" '.*' $IMAGE_TAG $BASE_IMAGE_TAG_FILE\n\n            if [ \"$(git -C ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${repo} status --porcelain -- $BASE_IMAGE_TAG_FILE | wc -l)\" -gt 0 ]; then\n                UPDATE_PACKAGES=\"$(cat ${SCRIPT_ROOT}/../eks-distro-base-updates/${key#al}/update_packages-${image})\"\n                if [ \"$UPDATE_PACKAGES\" != \"\" ]; then\n                    EXTRA_PR_BODY+=\"\\n${BASE_IMAGE_TAG_FILE}\\nThe following yum packages were updated:\\n\\`\\`\\`bash\\n${UPDATE_PACKAGES}\\n\\`\\`\\`\\n\"\n                fi\n            fi\n        done\n    done < <(yq e \".$key | keys\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\ndone < <(yq e \"keys\" $SCRIPT_ROOT/../EKS_DISTRO_TAG_FILE.yaml)\n\nfor repo in \"${REPOS[@]}\"; do\n   ${SCRIPT_ROOT}/../pr-scripts/create_pr.sh \"$repo\" 'EKS_DISTRO*_TAG_FILE' \"image-tag-update\" \"$EXTRA_PR_BODY\"\ndone\n", "num_lines": 70}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2020 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nif [[ -n \"${DEBUG:-}\" ]]; then\n    set -x\nfi\n\nbuild_arg=\"\"\nbuild_fail=0\nnft_fail=0\n\nwhile [[ $# -gt 1 ]]; do\n    case \"$1\" in\n\t--build-arg=*)\n\t    build_arg=\"${1#--build_arg=}\"\n\t    ;;\n\t--build-arg)\n\t    shift\n\t    build_arg=\"$1\"\n\t    ;;\n\t--build-fail)\n\t    build_fail=1\n\t    ;;\n\t--nft-fail)\n\t    nft_fail=1\n\t    ;;\n\t*)\n\t    echo \"Unrecognized flag '$1'\" 1>&2\n\t    exit 1\n\t    ;;\n    esac\n    shift\ndone\ntag=\"$1\"\n\nif podman -h &> /dev/null; then\n    docker_binary=podman\nelif docker -h &> /dev/null; then\n    if docker version &> /dev/null; then\n\tdocker_binary=docker\n    else\n\tdocker_binary=\"sudo docker\"\n\t# Get the password prompting out of the way now\n\tsudo docker version > /dev/null\n    fi\nelse\n    echo \"Could not find podman or docker\" 1>&2\n    exit 1\nfi\n\nfunction docker() {\n    if [[ -n \"${DEBUG:-}\" ]]; then\n\tcommand ${docker_binary} \"$@\"\n    else\n\tif [[ \"$1\" == \"build\" ]]; then\n\t    echo \"    docker $*\"\n\tfi\n\t# Redirect stdout to /dev/null and indent stderr\n\tcommand ${docker_binary} \"$@\" 2>&1 > /dev/null | \\\n\t    sed -e '/debconf: delaying package configuration/ d' \\\n\t\t-e 's/^/    /'\n    fi\n}\n\nfunction build() {\n\tif [[ -z \"${DEBUG:-}\" ]]; then\n\t\tquiet=\"-q\"\n\tfi\n\n\tif [[ -z \"${CACHE_BUILDS:-}\" ]]; then\n\t\tno_cache=\"--no-cache\"\n\tfi\n\n    build_tag=iptables-wrapper-test-$1\n    dockerfile=Dockerfile.test-${1%%-*}\n    shift\n\n    docker build ${no_cache:-} ${quiet:-} -t ${build_tag} -f test/${dockerfile} \"$@\" .\n}\n\nfunction PASS() {\n    printf \"\\033[1;92mPASS: $@\\033[0m\\n\\n\"\n    exit 0\n}\n\nfunction FAIL() {\n    printf \"\\033[1;31mFAIL: $@\\033[0m\\n\" 1>&2\n    exit 1\n}\n\nif ! build \"${tag}\" ${build_arg}; then\n    if [[ \"${build_fail}\" = 1 ]]; then\n\tPASS \"build failed as expected\"\n    fi\n    FAIL \"build failed unexpectedly\"\nfi\n\nif ! docker run --privileged \"iptables-wrapper-test-${tag}\" /tests -test.v -test.run \"^TestIPTablesWrapperLegacy$\" ; then\n    FAIL \"failed legacy iptables\"\nfi\nif ! docker run --privileged \"iptables-wrapper-test-${tag}\" /tests -test.v -test.run \"^TestIPTablesWrapperNFT$\" ; then\n    FAIL \"failed nft iptables\"\nfi\n\nif ! docker run --privileged \"iptables-wrapper-test-${tag}\" /tests -test.v -test.run \"^TestIP6TablesWrapperLegacy$\" ; then\n    FAIL \"failed legacy ip6tables\"\nfi\nif ! docker run --privileged \"iptables-wrapper-test-${tag}\" /tests -test.v -test.run \"^TestIP6TablesWrapperNFT$\" ; then\n    FAIL \"failed nft ip6tables\"\nfi\n\nPASS \"success\"\n", "num_lines": 130}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright 2022 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# USAGE: clean-distroless.sh\n\n# Modified version of https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/clean-distroless.sh\n\nREMOVE=\"/usr/share/base-files\n/usr/share/man\n/usr/lib/*-linux-gnu/gconv/\n/usr/bin/c_rehash\n/usr/bin/openssl\n/bin/mv\n/bin/chmod\n/bin/grep\n/bin/ln\n/bin/sleep\n/usr/bin/wc\n/iptables-wrapper-installer.sh\n/bin/sh\n/bin/dash\n/clean-distroless.sh\n/bin/rm\"\n\nIFS=\"\n\"\n\nfor item in ${REMOVE}; do\n    rm -rf \"${item}\"\ndone\n", "num_lines": 44}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/package-utils.sh\n\n# Copyright 2022 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# file_to_package identifies the debian package that provided the file $1\nfile_to_package() {\n    # `dpkg-query --search $file-pattern` outputs lines with the format: \"$package: $file-path\"\n    # where $file-path belongs to $package\n    # https://manpages.debian.org/jessie/dpkg/dpkg-query.1.en.html\n    dpkg-query --search \"$(realpath \"${1}\")\" | cut -d':' -f1\n}\n\n# package_to_copyright gives the path to the copyright file for the package $1\npackage_to_copyright() {\n    echo \"/usr/share/doc/${1}/copyright\"\n}\n\n# stage_file stages the filepath $1 to $2, following symlinks\n# and staging copyrights\nstage_file() {\n    cp -a --parents \"${1}\" \"${2}\"\n    # recursively follow symlinks\n    if [[ -L \"${1}\" ]]; then\n        stage_file \"$(cd \"$(dirname \"${1}\")\" || exit; realpath -s \"$(readlink \"${1}\")\")\" \"${2}\"\n    fi\n    # get the package so we can stage package metadata as well\n    package=\"$(file_to_package \"${1}\")\"\n    # stage the copyright for the file\n    cp -a --parents \"$(package_to_copyright \"${package}\")\" \"${2}\"\n    # stage the package status mimicking bazel\n    # https://github.com/bazelbuild/rules_docker/commit/f5432b813e0a11491cf2bf83ff1a923706b36420\n    # instead of parsing the control file, we can just get the actual package status with dpkg\n    dpkg -s \"${package}\" > \"${2}/var/lib/dpkg/status.d/${package}\"\n}\n", "num_lines": 49}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/stage-binaries-from-package.sh\n\n# Copyright 2022 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# USAGE: stage-binaries-from-package.sh /opt/stage package1 package2\n#\n# Stages all the packages and its dependencies (+ libraries and copyrights) to $1\n#\n# This is intended to be used in a multi-stage docker build with a distroless/base\n# or distroless/cc image.\nset -e\n\n. package-utils.sh\n\nstage_file_list() {\n    IFS=\"\n    \"\n    REQUIRED_FILES=\"$(dpkg -L \"${1}\" | grep -vE '(/\\.|/s?bin/|/usr/share/(man|doc|.*-completion))' | sed 's/\\n/ /g')\"\n    for file in $REQUIRED_FILES; do \n        if [ -f \"$file\" ]; then\n            stage_file \"${file}\" \"${STAGE_DIR}\"\n        fi\n    done\n\n    BIN_LIST=\"$(dpkg -L \"${1}\" | grep -E '/s?bin/' |sed 's/\\n/ /g')\"\n    for binary in $BIN_LIST; do\n        /stage-binary-and-deps.sh \"${2}\" \"${binary}\"\n    done\n}\n\nget_dependent_packages() {\n    apt-cache depends \"${1}\" |grep Depends|awk -F '.*Depends:[[:space:]]?' '{print $2}'\n}\n\nmain() {\n    STAGE_DIR=\"${1}/\"\n    mkdir -p \"${STAGE_DIR}\"/var/lib/dpkg/status.d/\n    apt -y update\n    shift\n    while (( \"$#\" )); do        # While there are arguments still to be shifted\n        PACKAGE=\"${1}\"\n        apt -y install \"${PACKAGE}\"\n        stage_file_list \"${PACKAGE}\" \"$STAGE_DIR\"\n        while IFS= read -r c_dep; do\n            stage_file_list \"${c_dep}\" \"${STAGE_DIR}\"\n        done < <(get_dependent_packages \"${PACKAGE}\")\n        shift\n    done\n}\n\nmain \"$@\"\n", "num_lines": 66}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copied from https://github.com/kubernetes/release/blob/master/images/build/distroless-iptables/distroless/stage-binary-and-deps.sh\n\n# Copyright 2021 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# USAGE: stage-binary-and-deps.sh haproxy /opt/stage\n#\n# Stages $1 and its dependencies + their copyright files to $2\n#\n# This is intended to be used in a multi-stage docker build with a distroless/base\n# or distroless/cc image.\n# This script was originally created by KinD maintainers and can be found at:\n#   https://github.com/kubernetes-sigs/kind/blob/v0.14.0/images/haproxy/stage-binary-and-deps.sh\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n\n. package-utils.sh\n\n# binary_to_libraries identifies the library files needed by the binary $1 with ldd\nbinary_to_libraries() {\n    # see: https://man7.org/linux/man-pages/man1/ldd.1.html\n    ldd \"${1}\" \\\n    `# strip the leading '${name} => ' if any so only '/lib-foo.so (0xf00)' remains` \\\n    | sed -E 's#.* => /#/#' \\\n    `# we want only the path remaining, not the (0x${LOCATION})` \\\n    | awk '{print $1}' \\\n    `# linux-vdso.so.1 is a special virtual shared object from the kernel` \\\n    `# see: http://man7.org/linux/man-pages/man7/vdso.7.html` \\\n    | grep -v 'linux-vdso.so.1'\n}\n\n# main script logic\nmain(){\n    local STAGE_DIR=\"${1}/\"\n    shift\n    while (( \"$#\" )); do\n        BINARY=\"${1}\"\n        # locate the path to the binary\n        local binary_path\n        binary_path=\"$(which \"${BINARY}\")\"\n    \n        # ensure package metadata dir\n        mkdir -p \"${STAGE_DIR}\"/var/lib/dpkg/status.d/\n    \n        # stage the binary itself\n        stage_file \"${binary_path}\" \"${STAGE_DIR}\"\n    \n        # stage the dependencies of the binary\n        while IFS= read -r c_dep; do\n            stage_file \"${c_dep}\" \"${STAGE_DIR}\"\n        done < <(binary_to_libraries \"${binary_path}\")\n        shift\n    done\n}\n\nmain \"$@\"\n", "num_lines": 73}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nIMAGE_REPO=$1\nIMAGE_TAG=$2\nAL_TAG=$3\nPLATFORMS=\"$4\"\nTEST=$5\nLOCAL_REGISTRY=$6\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nif [ \"$AL_TAG\" = \"2023\" ]; then\n    AL_TAG=\"23\"\nfi\n\nfunction retry() {\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        sleep $delay;\n      fi\n    }\n  done\n}\n\nfunction build::docker::retry_pull() {\n  retry docker pull \"$@\"\n}\n\nfunction check_base() {\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --progress plain \\\n        --opt target=check-base \\\n        --local dockerfile=./ \\\n\t\t--local context=./tests \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest\\\",push=true\n\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest\n        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:base-latest; then\n            echo \"base issue!\"\n            exit 1\n        fi\n    done\n}\n\nfunction check_base-nonroot() {\n    echo \"not impl\"\n}\n\nfunction check_base-glibc() {\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-glibc:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --progress plain \\\n        --opt target=check-cgo \\\n        --local dockerfile=./ \\\n\t\t--local context=./tests \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest\\\",push=true\n\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:glibc-latest | grep -v 'Printed from unsafe C code'; then\n            echo \"glibc issue!\"\n            exit 1\n        fi\n    done\n}\n\nfunction cleanup-iptable-rules() {\n    local mode\n    local ip\n    for mode in legacy nft; do\n        # ensure they do not already exist\n        for ip in iptables ip6tables; do\n            docker run --privileged --rm --net host --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-$mode-latest $ip -t mangle -X KUBE-IPTABLES-HINT &> /dev/null || true            \n        done\n    done\n}\n\nfunction check_base-iptables() {\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --progress plain \\\n        --opt target=check-iptables-legacy \\\n        --local dockerfile=./ \\\n\t\t--local context=./tests \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest\\\",push=true\n\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --progress plain \\\n        --opt target=check-iptables-nft \\\n        --local dockerfile=./ \\\n\t\t--local context=./tests \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest\\\",push=true\n\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-iptables:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --progress plain \\\n        --opt target=check-iptables-wrapper \\\n        --local dockerfile=./ \\\n\t\t--local context=$SCRIPT_ROOT/../ \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest\\\",push=true\n\n    local platform\n    local mode\n    local ip\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest\n\n        # ensure defatult is set to legacy which was set in dockerfile\n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest update-alternatives --list | grep 'iptables' | xargs)\" != \"iptables manual /usr/sbin/iptables-legacy\" ]]; then\n            echo \"iptables legacy alternative issue!\"\n            exit 1\n        fi\n        \n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest update-alternatives --list | grep 'ip6tables' | xargs)\" != \"ip6tables manual /usr/sbin/ip6tables-legacy\" ]]; then\n            echo \"ip6tables legacy alternative issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest iptables --version | grep -v 'legacy'; then\n            echo \"iptables legacy issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest ip6tables --version | grep -v 'legacy'; then\n            echo \"ip6tables legacy issue!\"\n            exit 1\n        fi\n        \n        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest iptables-save; then\n            echo \"iptables-save legacy issue!\"\n            exit 1\n        fi\n        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-legacy-latest ip6tables-save; then\n            echo \"ip6tables-save legacy issue!\"\n            exit 1\n        fi\n\n        # nft mode will fail when running on a host that does not match the arch, both arch have been confirmed to work on their respective\n        # arch based instances\n        if [[ ! \"$platform\" = \"linux/$(go env GOHOSTARCH)\" ]]; then\n            continue\n        fi\n        \n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest\n\n        # ensure defatult is set to nft which was set in dockerfile\n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest update-alternatives --list | grep 'iptables' | xargs)\" != \"iptables manual /usr/sbin/iptables-nft\" ]]; then\n            echo \"iptables nft alternative issue!\"\n            exit 1\n        fi\n        \n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest update-alternatives --list | grep 'ip6tables' | xargs)\" != \"ip6tables manual /usr/sbin/ip6tables-nft\" ]]; then\n            echo \"ip6tables nft alternative issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest iptables --version | grep -v 'nf_tables'; then\n            echo \"iptables nft issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest ip6tables --version | grep -v 'nf_tables'; then\n            echo \"ip6tables nft issue!\"\n            exit 1\n        fi\n\n        # these are included to match upstream, but default to nft and are not explictly set anywhere accross eks-d/a\n        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest ebtables --version; then\n            echo \"ebtables nft issue!\"\n            exit 1\n        fi\n\n        if ! docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-nft-latest arptables --version; then\n            echo \"arptables nft issue!\"\n            exit 1\n        fi\n\n\n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest\n\n        # ensure defatult is set to wrapper which was set in dockerfile\n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest update-alternatives --list | grep '^iptables' | xargs)\" != \"iptables manual /usr/sbin/iptables-wrapper\" ]]; then\n            echo \"iptables wrapper alternative issue!\"\n            exit 1\n        fi\n        \n        if [[ \"$(docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest update-alternatives --list | grep 'ip6tables' | xargs)\" != \"ip6tables manual /usr/sbin/iptables-wrapper\" ]]; then\n            echo \"ip6tables wrapper alternative issue!\"\n            exit 1\n        fi\n        \n        # iptables-wrapper defaults to nft mode when none of the kubelet hint rules are set\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest iptables --version | grep -v 'nf_tables'; then\n            echo \"iptables wrapper issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest ip6tables --version | grep -v 'nf_tables'; then\n            echo \"ip6tables wrapper issue!\"\n            exit 1\n        fi\n        \n        # create KUBE-IPTABLES-HINT and test that wrapper sets the correct mode        \n        for mode in nft legacy; do\n            local expected=\"$mode\"\n            if [[ \"$mode\" == \"nft\" ]]; then\n                expected=\"nf_tables\"\n            fi\n\n            # no matter which version of a given iptables mode is used to add the hint, it should trigger the wrapper to use that mode for both\n            # depending on how the hint rule is set, the resulting mode should be set\n            for ip in iptables ip6tables; do\n                cleanup-iptable-rules\n\n                docker run --privileged --rm --net host --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-$mode-latest $ip -t mangle -N KUBE-IPTABLES-HINT\n\n                if docker run --privileged --net host --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest iptables --version | grep -v \"$expected\"; then\n                    echo \"iptables wrapper issue!\"\n                    exit 1\n                fi\n                \n                if docker run --privileged --net host --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest ip6tables --version | grep -v \"$expected\"; then\n                    echo \"iptables wrapper issue!\"\n                    exit 1\n                fi\n            done\n        done\n        \n        cleanup-iptable-rules\n\n        # run upstream test binaries which tests a number of similiar cases as above\n        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run \"^TestIPTablesWrapperLegacy$\"; then\n            echo \"iptables wrapper legacy issue!\"\n            exit 1\n        fi\n        \n        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run \"^TestIPTablesWrapperNFT$\"; then\n            echo \"iptables wrapper nft issue!\"\n            exit 1\n        fi\n\n        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run \"^TestIP6TablesWrapperLegacy$\"; then\n            echo \"iptables wrapper ipv6 legacy issue!\"\n            exit 1\n        fi\n\n        if ! docker run --privileged --rm --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:iptables-wrapper-latest /tests -test.v -test.run \"^TestIP6TablesWrapperNFT$\"; then\n            echo \"ip6tables wrapper ipv6 nft issue!\"\n            exit 1\n        fi\n    done\n}\n\nfunction check_base-csi() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi:$IMAGE_TAG\n        if docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi:$IMAGE_TAG xfs_info -V | grep -v 'xfs_info version'; then\n            echo \"csi xfs issue!\"\n            exit 1\n        fi\n    done\n }\n\n function check_base-csi-ebs() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi-ebs:$IMAGE_TAG\n        if docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-csi-ebs:$IMAGE_TAG mount --version | grep -v 'mount'; then\n            echo \"csi xfs issue!\"\n            exit 1\n        fi\n    done\n }\n\n function check_base-git() {\n    if [[ -z \"$PRIVATE_REPO\" ]]; then\n        echo \"Error: Please set PRIVATE_REPO to a private github repo in your github account\"\n        echo \"example: PRIVATE_REPO=git@github.com:jaxesn/test-private.git\"\n        exit 1\n    fi\n\n    if [[ -z \"$SSH_KEY_FOLDER\" ]]; then\n        echo \"Error: Please set SSH_KEY_FOLDER to the local folder which contains your github private/public key\"\n        echo \"example: SSH_KEY_FOLDER=/Users/jgw/.ssh \"\n        exit 1\n    fi\n\n    local netrc=\"\"\n    if [ -f $HOME/.netrc ]; then\n        netrc=\"--secret id=netrc,src=$HOME/.netrc\"\n    fi\n\n    $SCRIPT_ROOT/../../scripts/buildkit.sh  \\\n        build \\\n        --frontend dockerfile.v0 \\\n        --opt filename=./tests/Dockerfile \\\n\t\t--opt platform=$PLATFORMS \\\n        --opt build-arg:BASE_IMAGE=$IMAGE_REPO/eks-distro-minimal-base-git:$IMAGE_TAG \\\n        --opt build-arg:AL_TAG=$AL_TAG \\\n        --opt build-arg:GOPROXY=${GOPROXY:-direct} \\\n        --progress plain \\\n        --opt target=check-git \\\n        --local dockerfile=./ \\\n\t\t--local context=./tests $netrc \\\n        --export-cache type=inline \\\n        --import-cache type=registry,ref=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest \\\n        --output type=image,oci-mediatypes=true,\\\"name=$LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest\\\",push=true\n\n    for platform in ${PLATFORMS//,/ }; do\n        # use git cli to clone private and public repo\n        build::docker::retry_pull --platform=$platform $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest\n        docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \\\n            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \\\n            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \\\n            $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest git clone $PRIVATE_REPO\n\n        docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \\\n            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \\\n            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \\\n            $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest git clone https://github.com/aws/eks-distro.git\n\n        # use lib git to clone private and public repo\n        if docker run --rm --platform=$platform -v $SSH_KEY_FOLDER/id_rsa:/root/.ssh/id_rsa \\\n            -v $SSH_KEY_FOLDER/id_rsa.pub:/root/.ssh/id_rsa.pub \\\n            -v $SSH_KEY_FOLDER/known_hosts:/root/.ssh/known_hosts \\\n            -e PRIVATE_REPO=$PRIVATE_REPO $LOCAL_REGISTRY/eks-distro-minimal-images-base-test:git-latest check-git | grep -v 'Successfully cloned!'; then\n            echo \"git issue!\"\n            exit 1\n        fi\n    done\n\n }\n\n check_base-docker-client() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-docker-client:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform -v /var/run/docker.sock:/var/run/docker.sock $IMAGE_REPO/eks-distro-minimal-base-docker-client:$IMAGE_TAG docker info; then\n            echo \"docker client issue!\"\n            exit 1\n        fi\n    done\n }\n\n check_base-haproxy() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-haproxy:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-haproxy:$IMAGE_TAG haproxy -v; then\n            echo \"haproxy issue!\"\n            exit 1\n        fi\n    done\n }\n\n check_base-nginx() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nginx:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nginx:$IMAGE_TAG nginx -v; then\n            echo \"nginx issue!\"\n            exit 1\n        fi\n    done\n }\n\n check_base-kind() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-kind:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-kind:$IMAGE_TAG ctr -v; then\n            echo \"kind issue!\"\n            exit 1\n        fi\n    done\n }\n\n check_base-nsenter() {\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/eks-distro-minimal-base-nsenter:$IMAGE_TAG\n\n        if docker run --rm --platform=$platform  $IMAGE_REPO/eks-distro-minimal-base-nsenter:$IMAGE_TAG nsenter --version | grep -v 'nsenter from util-linux'; then\n            echo \"nsenter issue!\"\n            exit 1\n        fi\n    done\n  }\n\n\n check_base-python3() {\n    local -r version=\"$1\"\n    local -r image_component=\"${2:-eks-distro-minimal-base-python}\"\n    # Cases based on distroless's test cases\n    # https://github.com/GoogleContainerTools/distroless/blob/main/experimental/python3/testdata/python3.yaml\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG\n\n        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"print('Hello World')\" | grep -v 'Hello World'; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n    \n        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"import subprocess, sys; subprocess.check_call(sys.executable + ' --version', shell=True)\" | grep -v 'Python 3'; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"import ctypes.util; ctypes.CDLL(ctypes.util.find_library('rt')).timer_create\"; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"import distutils.dist\"; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"open(u'h\\\\xe9llo', 'w'); import sys; print(sys.getfilesystemencoding())\" | grep -v 'utf-8'; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n\n        if docker run --rm --platform=$platform -v $SCRIPT_ROOT/python3-test.py:/eks-d-python-validate.py $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 /eks-d-python-validate.py | grep -v 'FINISHED ENTIRE SCRIPT'; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG /usr/bin/python3 -c \"import ssl; print(ssl.OPENSSL_VERSION)\"; then\n            echo \"python3 issue!\"\n            exit 1\n        fi\n    done\n  }\n\ncheck_base-python-3.7() {\n    check_base-python3 3.7\n    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-python:$IMAGE_TAG pip3 --version >/dev/null 2>&1; then\n        echo \"pip should not exist!\"\n        exit 1\n    fi\n}\n\ncheck_base-python-3.9() {\n    check_base-python3 3.9\n    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-python:$IMAGE_TAG pip3 --version >/dev/null 2>&1; then\n        echo \"pip should not exist!\"\n        exit 1\n    fi\n}\n\ncheck_base-python-compiler() {\n    local -r version=\"$1\"\n    local -r variant=\"$2\"\n\n    check_base-compiler-$2 python\n    check_base-python3 \"$1\" python\n\n    for platform in ${PLATFORMS//,/ }; do\n        if ! docker run --rm --platform=$platform --pull=always $IMAGE_REPO/python:$IMAGE_TAG pip3 --version; then\n            echo \"python issue!\"\n            exit 1\n        fi\n    done\n}\n\ncheck_base-python-compiler-3.7-base() {\n    check_base-python-compiler 3.7 base\n}\n\ncheck_base-python-compiler-3.7-yum() {\n    check_base-python-compiler 3.7 yum\n}\n\ncheck_base-python-compiler-3.7-gcc() {\n    check_base-python-compiler 3.7 gcc\n}\n\ncheck_base-python-compiler-3.9-base() {\n    check_base-python-compiler 3.9 base\n}\n\ncheck_base-python-compiler-3.9-yum() {\n    check_base-python-compiler 3.9 yum\n}\n\ncheck_base-python-compiler-3.9-gcc() {\n    check_base-python-compiler 3.9 gcc\n}\n\ncheck_base-nodejs() {\n    local -r version=\"$1\"\n    local -r image_component=\"${2:-eks-distro-minimal-base-nodejs}\"\n    for platform in ${PLATFORMS//,/ }; do\n        if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/$image_component:$IMAGE_TAG node --version | grep -v $version; then\n            echo \"nodejs issue!\"\n            exit 1\n        fi\n\n        if ! docker run --rm --platform=$platform --pull=always $IMAGE_REPO/$image_component:$IMAGE_TAG env node; then\n            echo \"nodejs issue!\"\n            exit 1\n        fi\n\n    done\n}\n\ncheck_base-nodejs-16() {\n    check_base-nodejs 16\n\n    if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/eks-distro-minimal-base-nodejs:$IMAGE_TAG npm --version > /dev/null 2>&1; then\n        echo \"npm should not exist!\"\n        exit 1\n    fi\n}\n\ncheck_base-nodejs-compiler() {\n    local -r version=\"$1\"\n    local -r variant=\"$2\"\n\n    check_base-compiler-$2 nodejs\n    check_base-nodejs \"$1\" nodejs\n\n    for platform in ${PLATFORMS//,/ }; do\n        if docker run --rm --platform=$platform --pull=always $IMAGE_REPO/nodejs:$IMAGE_TAG npm --version | grep -v '8'; then\n            echo \"npm issue!\"\n            exit 1\n        fi\n    done\n}\n\n\ncheck_base-nodejs-compiler-16-base() {\n    check_base-nodejs-compiler 16 base\n}\n\ncheck_base-nodejs-compiler-16-yum() {\n    check_base-nodejs-compiler 16 yum\n}\n\ncheck_base-nodejs-compiler-16-gcc() {\n    check_base-nodejs-compiler 16 gcc\n}\n\n\ncheck_base-compiler-base() {\n    local -r image_component=\"${1:-compiler-base}\"\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG curl --version; then\n            echo \"compiler-base issue!\"\n            exit 1\n        fi\n    done\n}\n\ncheck_base-compiler-yum() {\n    local -r image_component=\"${1:-compiler-base}\"\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG yum --version; then\n            echo \"compiler-base issue!\"\n            exit 1\n        fi\n    done\n}\n\ncheck_base-compiler-gcc() {\n    local -r image_component=\"${1:-compiler-base}\"\n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG\n\n        if ! docker run --rm --platform=$platform $IMAGE_REPO/$image_component:$IMAGE_TAG gcc --version; then\n            echo \"compiler-base issue!\"\n            exit 1\n        fi\n    done\n}\n\ncheck_base-golang-compiler() {\n    local -r version=\"$1\"\n    local -r variant=\"$2\"\n\n    check_base-compiler-$2 golang\n    \n    for platform in ${PLATFORMS//,/ }; do\n        build::docker::retry_pull --platform=$platform $IMAGE_REPO/golang:$IMAGE_TAG\n\n        if docker run --rm --platform=$platform $IMAGE_REPO/golang:$IMAGE_TAG go version | grep -v $version; then\n            echo \"golang issue!\"\n            exit 1\n        fi\n    done\n}\n\ncheck_base-golang-compiler-1.18-base() {\n    check_base-golang-compiler 1.18 base\n}\n\ncheck_base-golang-compiler-1.18-yum() {\n    check_base-golang-compiler 1.18 yum\n}\n\ncheck_base-golang-compiler-1.18-gcc() {\n    check_base-golang-compiler 1.18 gcc\n}\n\ncheck_base-golang-compiler-1.19-base() {\n    check_base-golang-compiler 1.19 base\n}\n\ncheck_base-golang-compiler-1.19-yum() {\n    check_base-golang-compiler 1.19 yum\n}\n\ncheck_base-golang-compiler-1.19-gcc() {\n    check_base-golang-compiler 1.19 gcc\n}\n\ncheck_base-golang-compiler-1.20-base() {\n    check_base-golang-compiler 1.20 base\n}\n\ncheck_base-golang-compiler-1.20-yum() {\n    check_base-golang-compiler 1.20 yum\n}\n\ncheck_base-golang-compiler-1.20-gcc() {\n    check_base-golang-compiler 1.20 gcc\n}\n\n\n$TEST\n", "num_lines": 695}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -x\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSRC_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\n\ndeclare -A cases[\"coredns/coredns\"]='github.com/coredns/coredns' \n    cases['containernetworking/plugins']='github.com/containernetworking/plugins'\n    cases['etcd-io/etcd']='go.etcd.io/etcd'\n    cases['fluxcd/source-controller']='github.com/fluxcd/source-controller'\n    cases['kubernetes/release']='k8s.io/release/images/build/go-runner'\n    cases['kubernetes-csi/external-attacher']='github.com/kubernetes-csi/external-attacher'\n    cases['kubernetes-csi/external-provisioner']='github.com/kubernetes-csi/external-provisioner'\n    cases['kubernetes-csi/external-resizer']='github.com/kubernetes-csi/external-resizer'\n    cases['kubernetes-csi/external-snapshotter']='github.com/kubernetes-csi/external-snapshotter/v3'\n    cases['kubernetes-csi/livenessprobe']='github.com/kubernetes-csi/livenessprobe'\n    cases['kubernetes-csi/node-driver-registrar']='github.com/kubernetes-csi/node-driver-registrar'\n    cases['kubernetes-sigs/aws-iam-authenticator']='sigs.k8s.io/aws-iam-authenticator'\n    cases['kubernetes-sigs/cri-tools']='github.com/kubernetes-sigs/cri-tools'\n    cases['kubernetes-sigs/metrics-server']='sigs.k8s.io/metrics-server'\n    cases['kubernetes/kubernetes-1-19']='k8s.io/'\n\nfor i in \"${!cases[@]}\"\ndo\n  rm -f \"$SRC_ROOT/tests/cases/$i/_output/ATTRIBUTION.txt\"\n  (cd \"$SRC_ROOT/tests/cases/$i\" &&  node $SRC_ROOT/generate-attribution-file.js ${cases[$i]} ./ go1.15.6 ./_output)\n  (cd \"$SRC_ROOT/tests/cases/$i\" && diff ./_output/attribution/ATTRIBUTION.txt ATTRIBUTION.txt)\ndone\n", "num_lines": 44}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/lib.sh\n\nPLATFORM=$(uname -s | tr '[:upper:]' '[:lower:]')\nARCH=$([[ $(uname -m) = \"x86_64\" ]] && echo 'amd64' || echo 'arm64')\nTMP_DIR=\"${BUILD_DIR}/tmp\"\nmkdir -p \"${TOOLS_DIR}\"\n\nHELM_VERSION=v3.7.1\nKUBECTL_VERSION=v1.22.6\nKIND_VERSION=v0.11.1\nRELEASE_BRANCH=1-22\nRELEASE=3\n\n## Install kubectl\nif ! command -v kubectl &> /dev/null; then\n    echo \"kubectl could not be found. Downloading...\"\n    curl -sSL \"https://distro.eks.amazonaws.com/kubernetes-${RELEASE_BRANCH}/releases/${RELEASE}/artifacts/kubernetes/${KUBECTL_VERSION}/bin/linux/amd64/kubectl\" -o \"${TOOLS_DIR}/kubectl\"\n    chmod +x \"${TOOLS_DIR}/kubectl\"\nfi\n\n## Install kubeval\nif ! command -v kubeval &> /dev/null; then\n    echo \"kubeval could not be found. Downloading...\"\n    mkdir -p \"${TMP_DIR}/kubeval\"\n    curl -sSL https://github.com/instrumenta/kubeval/releases/latest/download/kubeval-${PLATFORM}-${ARCH}.tar.gz | tar xz -C \"${TMP_DIR}/kubeval\"\n    mv \"${TMP_DIR}/kubeval/kubeval\" \"${TOOLS_DIR}/kubeval\"\nfi\n\n## Install helm\nif ! command -v helm &> /dev/null; then\n    echo \"helm could not be found. Downloading...\"\n    mkdir -p \"${TMP_DIR}/helm\"\n    curl -sSL https://get.helm.sh/helm-${HELM_VERSION}-${PLATFORM}-${ARCH}.tar.gz | tar xz -C \"${TMP_DIR}/helm\"\n    mv \"${TMP_DIR}/helm/${PLATFORM}-${ARCH}/helm\" \"${TOOLS_DIR}/helm\"\n    rm -rf \"${PLATFORM}-${ARCH}\"\nfi\n\n## Install kind\nif ! command -v kind &> /dev/null; then\n    echo \"kind could not be found. Downloading...\"\n    curl -sSL \"https://github.com/kubernetes-sigs/kind/releases/download/${KIND_VERSION}/kind-${PLATFORM}-${ARCH}\" -o \"${TOOLS_DIR}/kind\"\n    chmod +x \"${TOOLS_DIR}/kind\"\nfi\n\nrm -rf ${TMP_DIR}\n\necho \"Tools installed successfully\"\n", "num_lines": 66}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nCHART_BUCKET=\"prowdataclusterstack-316-prowchartsbucket2e50b8d9-8b0f36hrcee8\"\nREPO_URL=\"https://${CHART_BUCKET}.s3.amazonaws.com\"\n\nCHART_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/..\" && pwd -P)\"\nSTABLE=\"${CHART_ROOT}/stable\"\nBUILD_DIR=\"${CHART_ROOT}/build\"\nTOOLS_DIR=\"${BUILD_DIR}/tools\"\nexport PATH=\"${TOOLS_DIR}:${PATH}\"\n", "num_lines": 25}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -euo pipefail\n\nerr_report() {\n    echo \"Exited with error on line $1\"\n}\ntrap 'err_report $LINENO' ERR\n\nCHARTS_DIR=$1\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource $SCRIPT_ROOT/lib.sh\n\nmkdir -p \"${BUILD_DIR}\"\n\nif [ -e \"${CHARTS_DIR}/Chart.yaml\" ]\nthen\n\thelm package \"${CHARTS_DIR}/\" --destination \"${BUILD_DIR}/stable\"\nelse\n\thelm package \"${CHARTS_DIR}/\"* --destination \"${BUILD_DIR}/stable\"\nfi\n\nset +e # Should have exit code 18\nRETURN_CODE=\"$(curl --write-out '%{http_code}' --silent --output /dev/null -X HEAD ${REPO_URL}/index.yaml)\"\nCURL_EXIT_CODE=$?\nset -e\n\nif [ \"$CURL_EXIT_CODE\" != \"18\" ] && [ \"$CURL_EXIT_CODE\" != \"0\" ]; then\n    echo \"Error! Got exit code $CURL_EXIT_CODE from curl\"\n    exit 1\nfi\n\nMERGE_ARG=\"\"\n# When initially creating the repo, we need to skip adding the merge argument\nif [ \"$RETURN_CODE\" == \"200\" ]; then\n    MERGE_ARG=\"--merge index.yaml\"\n    curl -o index.yaml --silent \"${REPO_URL}/index.yaml\"\nfi\nhelm repo index $BUILD_DIR/stable --url $REPO_URL $MERGE_ARG\naws s3 cp --recursive --acl public-read ${BUILD_DIR}/stable  \"s3://${CHART_BUCKET}\"\necho \"\u00e2\u0153\u2026 Published charts\"\n", "num_lines": 57}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\necho \"Running install.sh in $(pwd)\"\n\nyum install -y jq\n\nKUBECTL_VERSION=v1.22.6\nEKS_D_RELEASE_BRANCH=1-22\nEKS_D_RELEASE_NUMBER=3\ncurl -sSL \"https://distro.eks.amazonaws.com/kubernetes-${EKS_D_RELEASE_BRANCH}/releases/${EKS_D_RELEASE_NUMBER}/artifacts/kubernetes/${KUBECTL_VERSION}/bin/linux/amd64/kubectl\" -o /bin/kubectl\nchmod +x /bin/kubectl\n\nCA_BUNDLE=$(cat /var/run/secrets/kubernetes.io/serviceaccount/ca.crt | base64 -w 0)\ncat /config/mutatingwebhook.yaml | sed -e \"s|\\${CA_BUNDLE}|${CA_BUNDLE}|g\" | sed -e \"s|\\${WEBHOOK_NAME}|${WEBHOOK_NAME}|g\" | sed -e \"s|\\${NAMESPACE}|${NAMESPACE}|g\" | sed -e \"s|\\${MWC_NAME}|${MWC_NAME}|g\" > mutatingwebhook.yaml\nkubectl apply -f mutatingwebhook.yaml\n\n# Loop for a total of 50 seconds to give time for webhook to create CertificateSigningRequest\n# The default hook timeout is 300, but for fargate there is a sleep container before this is run, and with the boot time of fargate containers, we get closer to the timeout if we increase the loop count\nfor i in {1..10}; do\n    # Make sure to have the NAMESPACE and WEBHOOK_NAME env var defined\n    for c in $(kubectl get csr -o json | jq -r \".items[] | select(.spec.username==\\\"system:serviceaccount:$NAMESPACE:$WEBHOOK_NAME\\\" and .status=={}).metadata.name\"); do\n        kubectl certificate approve $c\n    done\n    sleep 5\ndone\n", "num_lines": 42}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\necho \"Running uninstall.sh in $(pwd)\"\n\nKUBECTL_VERSION=v1.20.7\nEKS_D_RELEASE_BRANCH=1-20\nEKS_D_RELEASE_NUMBER=8\ncurl -sSL \"https://distro.eks.amazonaws.com/kubernetes-${EKS_D_RELEASE_BRANCH}/releases/${EKS_D_RELEASE_NUMBER}/artifacts/kubernetes/${KUBECTL_VERSION}/bin/linux/amd64/kubectl\" -o /bin/kubectl\nchmod +x /bin/kubectl\n\nkubectl delete mutatingwebhookconfiguration $MWC_NAME\nkubectl delete secret -n $NAMESPACE $WEBHOOK_NAME\n", "num_lines": 29}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nREPO=\"$1\"\nFILEPATH=\"$2\"\nPR_BRANCH=\"${3:-image-tag-update}\"\nEXTRA_PR_BODY=\"${4:-}\"\n\nSED=sed\nif [[ \"$(uname -s)\" == \"Darwin\" ]]; then\n    SED=gsed\nfi\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nOTHER_CLONE_ROOT=${OTHER_CLONE_ROOT:-${SCRIPT_ROOT}/../../..}\n\nCHANGED_FILE=\"tag file(s)\"\nCHANGED_COMPONENT=\"base image\"\nif [[ $REPO =~ \"prow-jobs\" ]]; then\n    CHANGED_FILE=\"Prowjobs\"\n    CHANGED_COMPONENT=\"builder-base image tag\"\nfi\nif [[ $JOB_NAME =~ \"prow-deck-tooling\" ]]; then\n    CHANGED_FILE=\"Prow controlplane Helm chart\"\n    CHANGED_COMPONENT=\"Prow component images\"\nfi\n\nif [ $REPO_OWNER = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\nfi\n\nPR_TITLE=\"Update ${CHANGED_COMPONENT} in ${CHANGED_FILE}\"\nCOMMIT_MESSAGE=\"[PR BOT] ${PR_TITLE}\"\n\nif [[ $REPO =~ \"prow-jobs\" ]]; then\n    PR_BODY_FILE=${SCRIPT_ROOT}/../pr-scripts/builder_base_pr_body\nelse\n    if [[ $JOB_NAME =~ \"prow-deck-tooling\" ]]; then\n        PR_BODY_FILE=${SCRIPT_ROOT}/../pr-scripts/prow_cp_pr_body\n    else\n        PR_BODY_FILE=${SCRIPT_ROOT}/../pr-scripts/eks_distro_base_other_repo_pr_body\n        if [ $REPO = \"eks-distro-build-tooling\" ]; then\n            PR_BODY_FILE=${SCRIPT_ROOT}/../pr-scripts/eks_distro_base_pr_body\n        fi\n        cp $PR_BODY_FILE ${SCRIPT_ROOT}/../pr-scripts/${REPO}_pr_body\n        PR_BODY_FILE=${SCRIPT_ROOT}/../pr-scripts/${REPO}_pr_body\n        $SED -i \"s,in .* with,in ${CHANGED_FILE} with,\" $PR_BODY_FILE\n    fi\nfi\n\nif [ -n \"${EXTRA_PR_BODY}\" ]; then\n    PR_BODY+=\"${EXTRA_PR_BODY}\"\nfi\n\n# Adding this here to include the \"do-not-merge/hold\" label. Trying to use the gh client with the --label arg will not succeed\n# as the bot doesn't have permission to add labels. Doing it this way our Prow chatops will pick it up and add it.\nprintf \"\\n/hold\\n\" >> $PR_BODY_FILE\n\nPROW_BUCKET_NAME=$(echo $JOB_SPEC | jq -r \".decoration_config.gcs_configuration.bucket\" | awk -F// '{print $NF}')\nprintf \"\\nClick [here](https://prow.eks.amazonaws.com/view/s3/$PROW_BUCKET_NAME/logs/$JOB_NAME/$BUILD_ID) to view job logs.\n\\nBy submitting this pull request,\\\nI confirm that you can use, modify, copy,\\\nand redistribute this contribution,\\\nunder the terms of your choice.\" >> $PR_BODY_FILE\nPR_BODY=$(cat $PR_BODY_FILE)\n\n\ncd ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO}\n\nif [[ \"$(basename \"$FILEPATH\")\" != \"$FILEPATH\" ]]; then\n    cd $(dirname $FILEPATH)\n    FILEPATH=\"$(basename $FILEPATH)\"\nfi\n\nfor FILE in $(find ./ -type f -name \"$FILEPATH\" ); do\n    git add $FILE\ndone\n\ncd ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO}\nif [ $REPO = \"eks-distro-build-tooling\" ]; then\n    git add ./eks-distro-base-minimal-packages/. ./eks-distro-base-updates/.\nfi\nif [[ $REPO =~ \"prow-jobs\" ]]; then\n    git add ./BUILDER_BASE_TAG_FILE\nfi\n\nFILES_ADDED=$(git diff --staged --name-only)\nif [ \"$FILES_ADDED\" = \"\" ]; then\n    exit 0\nfi\n\nif [ \"$JOB_TYPE\" = \"presubmit\" ]; then\n    git diff --staged\n    exit 0\nfi\n\ngit commit -m \"$COMMIT_MESSAGE\"\n\nssh-agent bash -c 'ssh-add /secrets/ssh-secrets/ssh-key; ssh -o StrictHostKeyChecking=no git@github.com; git push -u origin $PR_BRANCH -f'\n\ngh auth login --with-token < /secrets/github-secrets/token\n\nPR_EXISTS=$(GH_PAGER='' gh pr list --json number -H \"${PR_BRANCH}\")\nif [ \"$PR_EXISTS\" = \"[]\" ]; then\n  gh pr create --title \"$PR_TITLE\" --body \"$PR_BODY\"\nfi\n", "num_lines": 127}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nREPO=\"$1\"\nPR_BRANCH=\"${2:-image-tag-update}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nif [ \"$JOB_TYPE\" != \"periodic\" ]; then\n    exit 0\nfi\n\nif [ $REPO_OWNER = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\nfi\n\ncd ${SCRIPT_ROOT}/../../../${ORIGIN_ORG}/${REPO}\n\ngh auth login --with-token < /secrets/github-secrets/token\n\nPR_EXISTS=$(GH_PAGER='' gh pr list --json number -H \"${PR_BRANCH}\")\nif [ \"$PR_EXISTS\" != \"[]\" ]; then\n    echo \"There is an existing PR already open, please merge/close before building new images!\"\n    exit 1\nfi\n", "num_lines": 45}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nREPO=\"$1\"\nOLD_TAG=\"$2\"\nNEW_TAG=\"$3\"\nFILEPATH=\"$4\"\nUSE_YQ=\"$5\"\n\nSED=sed\nif [[ \"$(uname -s)\" == \"Darwin\" ]]; then\n    SED=gsed\nfi\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nOTHER_CLONE_ROOT=${OTHER_CLONE_ROOT:-${SCRIPT_ROOT}/../../..}\n\nif [ $REPO_OWNER = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\nfi\n\nREPO_PATH=${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO}\ncp -rf ${SCRIPT_ROOT}/../eks-distro-base-minimal-packages $REPO_PATH\ncp -rf ${SCRIPT_ROOT}/../eks-distro-base-updates $REPO_PATH\ncd $REPO_PATH\npwd\n\nif [ \"$USE_YQ\" = \"true\" ]; then\n    yq -i e \"$NEW_TAG\" EKS_DISTRO_TAG_FILE.yaml   \nelse\n    for FILE in $(find ./ -type f -name \"$FILEPATH\"); do\n        $SED -i -E \"s,${OLD_TAG},${NEW_TAG},\" $FILE\n    done\nfi\n", "num_lines": 55}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nREPO=\"$1\"\nPR_BRANCH=\"${2:-image-tag-update}\"\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nOTHER_CLONE_ROOT=${OTHER_CLONE_ROOT:-${SCRIPT_ROOT}/../../..}\nif [ \"$REPO_OWNER\" = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\n    UPSTREAM_ORG=\"aws\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\n    UPSTREAM_ORG=$REPO_OWNER\nfi\n\nif [ \"$JOB_TYPE\" = \"presubmit\" ]; then\n    PR_BRANCH=\"image-update-branch\"\nfi\n\nif [ ! -d ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO} ]; then\n    git clone https://github.com/${ORIGIN_ORG}/${REPO}.git ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO}\nfi\n\ncd ${OTHER_CLONE_ROOT}/${ORIGIN_ORG}/${REPO}\nif [ $(git branch --show-current) != $PR_BRANCH ]; then\n    git config --global push.default current\n    git config user.name \"EKS Distro PR Bot\"\n    git config user.email \"aws-model-rocket-bots+eksdistroprbot@amazon.com\"\n    git config remote.origin.url >&- || git remote add origin git@github.com:${ORIGIN_ORG}/${REPO}.git\n    git config remote.upstream.url >&- || git remote add upstream https://github.com/${UPSTREAM_ORG}/${REPO}.git\n    if [ \"$REPO\" = \"eks-distro-build-tooling\" ] && [ \"$JOB_TYPE\" = \"presubmit\" ]; then\n        git fetch upstream pull/$PULL_NUMBER/head:image-update-branch\n        git checkout $PR_BRANCH\n    else\n        git fetch upstream\n        git checkout upstream/main -b $PR_BRANCH\n    fi\nfi", "num_lines": 57}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nif [ \"$1\" == \"\" ]; then\n    echo \"Please specify a Go Minor Version to set up for EKS Go\"\n    exit 1\nfi\nGOLANG_MINOR_VERSION=$1\n\nif [ \"$2\" == \"\" ]; then\n    echo \"Please specify a Go Git Tag to use for the given Go Minor Version\"\n    exit 1\nfi\nGOLANG_GIT_TAG=$2\n\n\nBASE_DIRECTORY=\"$(git rev-parse --show-toplevel)\"\nPROJECT_DIRECTORY=\"$BASE_DIRECTORY/projects/golang/go/\"\nVERSION_DIRECTORY=\"${PROJECT_DIRECTORY}${GOLANG_MINOR_VERSION}\"\n\nif [ -d \"$VERSION_DIRECTORY\" ]; then\n    echo \"$VERSION_DIRECTORY already exists; existing so as not to over-write an existing project structure\"\n    exit 1\nfi\n\nmkdir \"$VERSION_DIRECTORY\"\n\nmkdir ${VERSION_DIRECTORY}/patches\nmkdir ${VERSION_DIRECTORY}/rpmbuild\nmkdir ${VERSION_DIRECTORY}/rpmbuild/SOURCES\nmkdir ${VERSION_DIRECTORY}/rpmbuild/SPECS\n\ntouch ${VERSION_DIRECTORY}/GIT_TAG\necho \"$GOLANG_GIT_TAG\" >> ${VERSION_DIRECTORY}/GIT_TAG\n\ntouch ${VERSION_DIRECTORY}/RELEASE\necho \"0\" >> ${VERSION_DIRECTORY}/RELEASE\n\n( ${BASE_DIRECTORY}/projects/golang/go/development/scripts/setup_golang_version_readme.sh $GOLANG_MINOR_VERSION $GOLANG_GIT_TAG)", "num_lines": 55}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nif [ \"$1\" == \"\" ]; then\n  echo \"Please specify an EKS Go Minor Version to configure the readme for\"\n  exit 1\nfi\nGOLANG_MINOR_VERSION=$1\n\nBASE_DIRECTORY=\"$(git rev-parse --show-toplevel)\"\nPROJECT_DIRECTORY=\"$BASE_DIRECTORY/projects/golang/go/\"\nVERSION_DIRECTORY=\"${PROJECT_DIRECTORY}${GOLANG_MINOR_VERSION}\"\n\nGOLANG_GIT_TAG=$(cat $VERSION_DIRECTORY/GIT_TAG)\nGOLANG_RELEASE=$(cat $VERSION_DIRECTORY/RELEASE)\n\ntouch ${VERSION_DIRECTORY}/README.md\n\ncat >${VERSION_DIRECTORY}/README.md <<EOF\n# EKS Golang ${GOLANG_MINOR_VERSION}\n\nCurrent Release: \\`${GOLANG_RELEASE}\\`\n\nTracking Tag: \\`${GOLANG_GIT_TAG}\\`\n\nArtifacts: https://distro.eks.amazonaws.com/golang-go${GOLANG_MINOR_VERSION}/releases/${GOLANG_RELEASE}/RPMS\n\n### ARM64 Builds\n[![Build status](https://prow.eks.amazonaws.com/badge.svg?jobs=golang-${GOLANG_MINOR_VERSION}-ARM64-PROD-tooling-postsubmit)](https://prow.eks.amazonaws.com/?repo=aws%2Feks-distro-build-tooling&type=postsubmit)\n\n### AMD64 Builds\n[![Build status](https://prow.eks.amazonaws.com/badge.svg?jobs=golang-${GOLANG_MINOR_VERSION}-tooling-postsubmit)](https://prow.eks.amazonaws.com/?repo=aws%2Feks-distro-build-tooling&type=postsubmit)\n\n### Patches\nThe patches in \\`./patches\\` include relevant utility fixes for go \\`${GOLANG_MINOR_VERSION}\\`.\n\n### Spec\nThe RPM spec file in \\`./rpmbuild/SPECS\\` is sourced from the go ${GOLANG_MINOR_VERSION} SRPM available on Fedora, and modified to include the relevant patches and build the \\`${GOLANG_GIT_TAG}\\` source.\n\nEOF\n", "num_lines": 57}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nPATCHING_TOOLS=\"$(git rev-parse --show-toplevel)/projects/golang/go/development/scripts/patches/lib/patch.sh\"\nsource \"$PATCHING_TOOLS\"\n\n# * VERSION_DIR:  absolute path to the Golang minor version directory under this repo's projects/golang/go,\n#                 e.g. ~/go/eks-distro-build-tooling/projects/golang/go/1.16\n#\n# * GOLANG_DIR:   the absolute path to the root directory of the Golang repo, which must be cloned locally,\n#                 must be up-to-date with upstream, and must not be \"dirty\".\n#\n# * APPLY_CVE_PATCHES:  \"true\" if CVE patches should be applied. All other values are interpreted as \"false\".\n#                        Minor versions supported by upstream are not presumed to have any CVE patches. CVE\n#                        patch files must start with ####-go-1.XX.YY-eks-..., with 1.XX.YY the Go version.\n#\n# * APPLY_OTHER_PATCHES:  \"true\" if non-CVE patches should be applied. All other values are interpreted as\n#                         \"false\". Other patch files must NOT include the Golang version at the start.\nVERSION_DIR=$(realpath \"$1\")\nGOLANG_DIR=$(realpath \"$2\")\nAPPLY_CVE_PATCHES=\"${3:-true}\"\nAPPLY_OTHER_PATCHES=\"${4:-true}\"\n\nclone_golang \"$GOLANG_DIR\"\ncheckout_golang_at_git_tag \"$VERSION_DIR\" \"$GOLANG_DIR\"\n\nif [ \"$APPLY_CVE_PATCHES\" = \"true\" ]; then\n  apply_cve_patches \"$VERSION_DIR\" \"$GOLANG_DIR\"\nfi\n\nif [ \"$APPLY_OTHER_PATCHES\" = \"true\" ]; then\n  apply_other_patches \"$VERSION_DIR\" \"$GOLANG_DIR\"\nfi\n", "num_lines": 50}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nGOLANG_GIT_URL=\"https://github.com/golang/go.git\"\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n# Arg 2:  absolute path to the root directory of the locally cloned Golang repo\nfunction apply_cve_patches {\n  local version_dir=$1\n  local golang_dir=$2\n\n  echo \"Applying *CVE* patches in $version_dir to $golang_dir...\"\n  if apply_patches \"$version_dir\" \"$golang_dir\" \"true\"; then\n    echo \"All *CVE* patches succeeded!\"\n    echo \"HEAD is at the last successful *CVE* patch.\"\n    return 0\n  fi\n  echo \"A *CVE* patch failed to apply\"\n  echo \"HEAD is at the last successful *CVE* patch.\"\n  return 1\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n# Arg 2:  absolute path to the root directory of the locally cloned Golang repo\nfunction apply_other_patches {\n  local version_dir=$1\n  local golang_dir=$2\n\n  echo \"Assuming CVE patches, if they exist, are already applied in $golang_dir\"\n\n  echo \"Applying *other* patches in $version_dir to $golang_dir...\"\n  if apply_patches \"$version_dir\" \"$golang_dir\" \"false\"; then\n    echo \"All *other* patches succeeded!\"\n    echo \"HEAD is at the last successful *other* patch.\"\n    return 0\n  fi\n\n  echo \"An *other* patch failed to apply\"\n  echo \"HEAD is at the last successful *other* patch.\"\n  return 1\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n# Arg 2:  absolute path to the root directory of the locally cloned Golang repo\n# Arg 3:  must be \"true\" if the applied patches are CVE patches. All other values indicate that the\n#         patches are not CVE patches.\nfunction apply_patches {\n  local version_dir=$1\n  local golang_dir=$2\n  local is_apply_for_cve_patches=$3\n\n  local patches\n\n  pushd \"$golang_dir\"\n\n  if [[ -n \"$(ls \"$version_dir\")\" ]]; then\n    patches=$(_get_patches \"${version_dir}\" \"${is_apply_for_cve_patches}\")\n    echo \"Patches to apply: ${patches}\"\n    for file in ${patches}; do\n      if git am <\"$file\"; then\n        echo \"Applying succeeded: $file\"\n      else\n        echo \"Applying failed: $file\"\n        git am --skip\n        popd\n        return 1\n      fi\n    done\n  else\n    echo \"Nothing to apply in $version_dir\"\n  fi\n\n  popd\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n# Arg 2:  should be \"true\" if the applied patches are CVE patches. All other values indicate that\n#         the patches are not CVE patches.\n#\n# Returns:  names of patch files\nfunction _get_patches {\n  local version_dir=$1\n  local is_apply_for_cve_patches_string=$2\n\n  local is_apply_for_cve_patches=false\n  if [ \"$is_apply_for_cve_patches_string\" = \"true\" ]; then\n    is_apply_for_cve_patches=true\n  fi\n\n  local file_name_regex\n  file_name_regex=\"^.*[0-9]{4}-$(get_eks_go_git_tag \"$version_dir\")-.*\\.patch$\"\n  local is_match\n\n  declare -a patches\n\n  for file in \"${version_dir}\"/patches/*.patch; do\n    is_match=false\n    if [[ $file =~ $file_name_regex ]]; then\n      is_match=true\n    fi\n\n    if [ $is_match = $is_apply_for_cve_patches ]; then\n      patches+=(\"$file\")\n    fi\n  done\n  echo \"${patches[@]}\"\n}\n\n# Arg 1:  absolute path to the root directory of where the Golang repo is locally cloned or will be\n#         locally cloned if it is not already\nfunction clone_golang {\n  local golang_dir=$1\n  if [ ! \"$(ls -A \"$golang_dir\")\" ]; then\n    echo \"Golang repo expected at $golang_dir but was not found. Cloning...\"\n    git clone \"$GOLANG_GIT_URL\" \"$golang_dir\" --origin upstream\n  fi\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n# Arg 2:  absolute path to the root directory of the locally cloned Golang repo\nfunction checkout_golang_at_git_tag {\n  local version_dir=$1\n  local golang_dir=$2\n\n  pushd \"$golang_dir\"\n  if ! git diff-index --quiet HEAD --; then\n    echo \"Local $golang_dir repository is in a dirty state. Stash, commit, or reset in-progress work.\"\n    popd\n    return 1\n  fi\n\n  if ! git config remote.upstream.url >/dev/null; then\n    git remote add upstream \"$GOLANG_GIT_URL\"\n  fi\n  git fetch upstream --tags -f\n\n  local git_tag\n  git_tag=\"$(get_golang_git_tag \"${version_dir}\")\"\n\n  echo \"Checking out $git_tag in $golang_dir\"\n  git checkout tags/\"$git_tag\"\n  echo \"$git_tag checked out!\"\n  popd\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n#\n# Returns:  EKS Go git tag, e.g. go-1.17.13-eks\nfunction get_eks_go_git_tag {\n  local version_dir=$1\n\n  local golang_git_tag\n  golang_git_tag=$(get_golang_git_tag \"$version_dir\")\n  echo \"${golang_git_tag//go/go-}-eks\"\n}\n\n# Arg 1:  absolute path to the Golang minor version directory under this repo's projects/golang/go\n#\n# Returns:  EKS Go git tag, e.g. go1.17.13\nfunction get_golang_git_tag {\n  local version_dir=$1\n\n  local version\n\n  pushd \"$version_dir\" >/dev/null\n  version=\"$(cat GIT_TAG)\"\n  popd >/dev/null\n  echo \"$version\"\n}", "num_lines": 185}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -x\n\nBASE_DIRECTORY=\"$(git rev-parse --show-toplevel)\"\nPROJECT_DIRECTORY=\"$BASE_DIRECTORY/projects/golang/go/\"\nGO_REPO_URL=\"https://github.com/golang/go.git\"\n\nGO_REPO=\"$(dirname \"$BASE_DIRECTORY\")/go\"\n\nGO_VERSIONS=('1.18.10' '1.19.10' '1.20.5')\n\nfunction build::go::clone() {\n\tif [[ ! -e $GO_REPO ]]; then\n\t\tgit clone \"$GO_REPO_URL\" $GO_REPO\n\tfi\n}\n\nfunction build::go::create_eks_branches() {\n\tcd $GO_REPO\n\tfor ver in \"${GO_VERSIONS[@]}\"; do\n\t\tgit checkout \"release-branch.go${ver:0:4}\"\n\t\tgit checkout -B \"go-$ver-eks\"\n\t\tgit am $PROJECT_DIRECTORY/${ver:0:4}/patches/*.patch\n\tdone\t\n}\n\nfunction build::cherry_pick_commit() {\n\tgit cherry-pick $1 || echo \"Failed to cherry-pick apply manually for $2\"\n}\n\nfunction patch::create() {\n\tgit format-patch -1\n}\n\nfunction build::cleanup() {\n\trm -rv \"$GO_REPO\"\n}\n\nif [ -v 2 ]; then\n  GO_VERSIONS=(\"$2\")\nfi\nbuild::go::clone\nbuild::go::create_eks_branches\nfor ver in \"${GO_VERSIONS[@]}\"; do\n\tbuild::cherry_pick_commit $1 $ver\ndone\n\n#TODO if cherry-pick is success create patch\n#TODO add option to erase golang/go repo\n", "num_lines": 52}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN\"\n    exit 1\nfi\n\nif [ \"$ARTIFACT_DEPLOYMENT_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty ARTIFACT_DEPLOYMENT_ROLE_ARN\"\n    exit 1\nfi\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY} || exit\n\ncat << EOF > awscliconfig\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile artifacts-push]\nrole_arn=$ARTIFACT_DEPLOYMENT_ROLE_ARN\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-east-1}}\nsource_profile=default\n\n[profile ecr-public-push]\nrole_arn=$ECR_PUBLIC_PUSH_ROLE_ARN\nregion=us-east-1\nsource_profile=default\nEOF\nexport AWS_CONFIG_FILE=$(pwd)/awscliconfig\nexport AWS_PROFILE=artifacts-push\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n\nmake -C ${BASE_DIRECTORY}/projects/golang/go prod-release", "num_lines": 50}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nif [ \"$ARCHITECTURE\" == \"ARM64\" ]; then\n    echo \"Won't perform image release for ARM64 arch\"\n    exit 0\nfi\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN\"\n    exit 1\nfi\n\nif [ \"$ECR_PUBLIC_PUSH_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty ECR_PUBLIC_PUSH_ROLE_ARN\"\n    exit 1\nfi\n\nBASE_DIRECTORY=$(git rev-parse --show-toplevel)\ncd ${BASE_DIRECTORY} || exit\n\ncat << EOF > awscliconfig\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile ecr-public-push]\nrole_arn=$ECR_PUBLIC_PUSH_ROLE_ARN\nregion=us-east-1\nsource_profile=default\nEOF\nexport AWS_CONFIG_FILE=$(pwd)/awscliconfig\nexport AWS_PROFILE=ecr-public-push\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n\nmake -C ${BASE_DIRECTORY}/projects/golang/go prod-release-images", "num_lines": 50}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -x\n\nif [ -z \"$1\" ]; then\n    echo \"you must specify a codebuild project name\"\n    exit 1\nfi\nCODEBUILD_PROJECT_NAME=$1\n\nif [ -z \"$2\" ]; then\n    echo \"you must specify an image name\"\n    exit 1\nfi\nIMAGE_NAME=$2\n\nif [ -z \"$3\" ]; then\n    echo \"you must specify an image tag\"\n    exit 1\nfi\nIMAGE_TAG=$3\n\nif [ -z \"$4\" ]; then\n    echo \"you must specify an AWS region\"\n    exit 1\nfi\nAWS_REGION=$4\n\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\n\nIMAGE_URL=\"$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$IMAGE_NAME:$IMAGE_TAG\"\n\naws codebuild update-project \\\n    --name $CODEBUILD_PROJECT_NAME \\\n    --environment \"{\\\"image\\\": \\\"$IMAGE_URL\\\", \\\"type\\\": \\\"LINUX_CONTAINER\\\", \\\"computeType\\\": \\\"BUILD_GENERAL1_LARGE\\\", \\\"privilegedMode\\\": true, \\\"environmentVariables\\\": [{\\\"name\\\": \\\"GOPROXY\\\", \\\"value\\\": \\\"athens-proxy:endpoint\\\", \\\"type\\\": \\\"SECRETS_MANAGER\\\"}]}\"\n\n", "num_lines": 51}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -euo pipefail\n\nerr_report() {\n    echo \"Exited with error on line $1\"\n}\ntrap 'err_report $LINENO' ERR\n\nATHENS_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${ATHENS_ROOT}/../../../helm-charts/scripts/lib.sh\"\nBUILD_DIR=\"$ATHENS_ROOT/build\"\nREPO=${1}\nGIT_TAG=${2}\nCHART_VERSION=${3} \nCHART_BUCKET_NAME=${4}\nBASE_IMAGE=${5}\nIMAGE=${6}\nUPLOAD=${7}\nBUCKET_URL=\"https://${CHART_BUCKET_NAME}.s3.amazonaws.com\"\nsh \"${ATHENS_ROOT}/../../../helm-charts/scripts/install-toolchain.sh\"\nmkdir -p $BUILD_DIR\ncd $BUILD_DIR\n\ngit clone $REPO\ncd athens\ngit checkout ${GIT_TAG}\ngit config user.email prow@amazonaws.com\ngit config user.name \"Prow Bot\"\ngit am ${ATHENS_ROOT}/patches/*\nOUTPUT=\"dest=/tmp/athens.tar\"\nTYPE=\"type=oci\"\nif [[ $UPLOAD == \"true\" ]]; then\n    OUTPUT=\"push=true\"\n    TYPE=\"type=image\"\nfi\n\nbuildctl build \\\n  --frontend dockerfile.v0 \\\n  --opt platform=linux/amd64 \\\n  --opt build-arg:BASE_IMAGE=${BASE_IMAGE} \\\n  --local dockerfile=cmd/proxy/ \\\n  --local context=. \\\n  --output $TYPE,oci-mediatypes=true,name=${IMAGE},$OUTPUT\n\nyq eval -i \".version = \\\"${CHART_VERSION}\\\"\" charts/athens-proxy/Chart.yaml\n${CHART_ROOT}/scripts/lint-charts.sh $(pwd)/charts\nhelm package charts/* --destination stable\n\nif [[ $UPLOAD == \"true\" ]]\nthen\n    set +e\n    RETURN_CODE=\"$(curl --write-out '%{http_code}' --silent --output /dev/null -X HEAD ${BUCKET_URL}/index.yaml)\"\n    CURL_EXIT_CODE=$?\n    set -e\n    if [ \"$CURL_EXIT_CODE\" != \"18\" ] && [ \"$CURL_EXIT_CODE\" != \"0\" ]; then\n        echo \"Error! Got exit code $CURL_EXIT_CODE from curl\"\n        exit 1\n    fi\n    MERGE_ARG=\"\"\n    # When initially creating the repo, we need to skip adding the merge argument\n    if [ \"$RETURN_CODE\" == \"200\" ]; then\n        MERGE_ARG=\"--merge index.yaml\"\n        curl -o index.yaml --silent \"${BUCKET_URL}/index.yaml\"\n    fi\n    helm repo index stable --url ${BUCKET_URL} $MERGE_ARG\n    aws s3 cp --recursive --acl public-read stable  \"s3://${CHART_BUCKET_NAME}\"\nfi\ncd ..\nrm -rf athens\n\ncd $ATHENS_ROOT\nrm -rf $BUILD_DIR\n", "num_lines": 88}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nBASE_DIRECTORY=\"$(git rev-parse --show-toplevel)\"\nPROJECT_DIRECTORY=\"$BASE_DIRECTORY/projects/kubernetes/kops\"\n\nOUTPUT_DIR=\"$PROJECT_DIRECTORY/output/kops\"\n\nKOPS_VERSION_TAG=\"$(sed 's/v//' \"$PROJECT_DIRECTORY/GIT_TAG\")\"\n\nKOPS_BINARIES_BASE_URL=\"https://artifacts.k8s.io/binaries/kops\"\nCHANNELS_BINARY=\"channels\"\nPROTOKUBE_BINARY=\"protokube\"\nKOPS_BINARIES=(\"$CHANNELS_BINARY\" \"$PROTOKUBE_BINARY\")\n\nDNS_CONTROLLER=\"dns-controller\"\nKOPS_CONTROLLER=\"kops-controller\"\nKUBE_APISERVER_HEALTHCHECK=\"kube-apiserver-healthcheck\"\nKOPS_IMAGES=(\"$DNS_CONTROLLER\" \"$KOPS_CONTROLLER\" \"$KUBE_APISERVER_HEALTHCHECK\")\n\nSUPPORTED_ARCHS=(\"arm64\" \"amd64\")\nSUPPORTED_PLATFORMS=(\"linux\")\n\nSHA_SUFFIX=\".sha256\"\nTARBALL_SUFFIX=\".tar.gz\"\n\nfetch_kops_binaries() {\n  for BINARY in \"${KOPS_BINARIES[@]}\"\n  do\n    for ARCH in \"${SUPPORTED_ARCHS[@]}\"\n    do\n      for PLATFORM in \"${SUPPORTED_PLATFORMS[@]}\"\n      do\n          local kops_artifacts_output_dir=\"$OUTPUT_DIR/$KOPS_VERSION_TAG/$PLATFORM/$ARCH\"\n          local release_artifact_url=\"$KOPS_BINARIES_BASE_URL/$KOPS_VERSION_TAG/$PLATFORM/$ARCH/$BINARY\"\n          local release_artifact_checksum_url=\"${release_artifact_url}${SHA_SUFFIX}\"\n          curl -L --create-dirs -o \"$kops_artifacts_output_dir/$BINARY\" \"$release_artifact_url\"\n          curl -L --create-dirs -o \"$kops_artifacts_output_dir/${BINARY}${SHA_SUFFIX}\" \"$release_artifact_checksum_url\"\n      done\n    done\n  done\n}\n\nfetch_kops_images() {\n  for IMAGE in \"${KOPS_IMAGES[@]}\"\n  do\n      for ARCH in \"${SUPPORTED_ARCHS[@]}\"\n      do\n        local image_name=\"$IMAGE-${ARCH}${TARBALL_SUFFIX}\"\n        local image_output_dir=\"$OUTPUT_DIR/$KOPS_VERSION_TAG/images\"\n        local image_url=\"$KOPS_BINARIES_BASE_URL/$KOPS_VERSION_TAG/images/$image_name\"\n        local image_checksum_url=\"${image_url}${SHA_SUFFIX}\"\n        curl -L --create-dirs -o \"$image_output_dir/$image_name\" \"$image_url\"\n        curl -L --create-dirs -o \"$image_output_dir/${image_name}${SHA_SUFFIX}\" \"$image_checksum_url\"\n      done\n  done\n}\n\nmove_nodeup_binaries() {\n  for ARCH in \"${SUPPORTED_ARCHS[@]}\"\n  do\n    for PLATFORM in \"${SUPPORTED_PLATFORMS[@]}\"\n    do\n      local binary_path=\"$PROJECT_DIRECTORY/kops/.build/dist/$PLATFORM/$ARCH/nodeup\"\n      local binary_upload_path=\"$OUTPUT_DIR/$KOPS_VERSION_TAG/$PLATFORM/$ARCH/nodeup\"\n      cp \"$binary_path\" \"$binary_upload_path\"\n      # While we're in here, we generate the checksums for the nodeup binaries and output them to the output dir\n      sha256sum \"$binary_path\" | cut -d \" \" -f 1 >> \"${binary_upload_path}${SHA_SUFFIX}\"\n    done\n  done\n}\n\nmove_kops_binaries() {\n  for ARCH in \"${SUPPORTED_ARCHS[@]}\"\n  do\n    for PLATFORM in \"${SUPPORTED_PLATFORMS[@]}\"\n    do\n      local binary_path=\"$PROJECT_DIRECTORY/kops/.build/dist/$PLATFORM/$ARCH/kops\"\n      local binary_upload_path=\"$OUTPUT_DIR/$KOPS_VERSION_TAG/$PLATFORM/$ARCH/kops\"\n      cp \"$binary_path\" \"$binary_upload_path\"\n      # While we're in here, we generate the checksums for the kops binaries and output them to the output dir\n      sha256sum \"$binary_path\" | cut -d \" \" -f 1 >> \"${binary_upload_path}${SHA_SUFFIX}\"\n    done\n  done\n}\n\nsync_artifacts_to_s3() {\n  local artifact_bucket=$1\n  local src_dir=$2\n  local dest_dir=$3\n  local public_read=$4\n  local dry_run=$5\n\n  if [ $# -le 3 ] ; then\n    echo \"not enough parameters supplied!\"\n  fi\n\n  if [ -z \"$1\" ] ; then\n    echo \"first parameter, target artifacts s3 bucket, is required!\" && exit 1;\n  fi\n\n  if [ -z \"$2\" ] ; then\n    echo \"second parameter source directory is required!\" && exit 1;\n  fi\n\n  if [ -z \"$3\" ] ; then\n    echo \"third parameter destination directory is required!\" && exit 1;\n  fi\n\n  if [ -z \"$4\" ] ; then\n    echo \"fourth parameter, public read for s3, is required\" && exit 1;\n  fi\n\n  if [ -z \"$5\" ] ; then\n    echo \"this is not a dry run!\"\n  fi\n\n  public_acl_argument=\"\"\n  if [ \"$public_read\" = \"true\" ]; then\n    public_acl_argument=\"--acl public-read\"\n  fi\n\n  if [ \"$dry_run\" = \"true\" ]; then\n  aws s3 cp $src_dir s3://${artifact_bucket}/${dest_dir} --recursive --dryrun ${public_acl_argument}\n    else\n  aws s3 sync $src_dir s3://${artifact_bucket}/${dest_dir} ${public_acl_argument}\nfi\n}\n", "num_lines": 145}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nPATCH=patch\nif [[ \"$(uname -s)\" == \"Darwin\" ]]; then\n    PATCH=gpatch\nfi\n\n# Workaround to YQ aggressively removing blank lines from YAMLs.\n# Generates an updated values YAML on the fly, and generates a diff\n# ignoring blank lines, then patches the original YAML file with the diff\nfunction patch::yaml::with::readability(){\n    charts_dir=$1\n    filename=$2\n    yq_eval_command=$3\n    TMPDIR=$(mktemp -d)\n    yq eval \"$yq_eval_command\" $charts_dir/$filename > $TMPDIR/updated-$filename\n    (diff -U0 -w -b --ignore-blank-lines $charts_dir/$filename $TMPDIR/updated-$filename || true) > $TMPDIR/$filename.diff\n    $PATCH $charts_dir/$filename < $TMPDIR/$filename.diff\n}\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nIMAGE=\"$1\"\nVALUES_PATH=\"$2\"\nUPDATE_CHART=\"$3\"\n\nif [ $REPO_OWNER = \"aws\" ]; then\n    ORIGIN_ORG=\"eks-distro-pr-bot\"\nelse\n    ORIGIN_ORG=$REPO_OWNER\nfi\n\nREPO_PATH=${SCRIPT_ROOT}/../../../../../${ORIGIN_ORG}/eks-distro-build-tooling\ncd $REPO_PATH\n\nCONTROLPLANE_CHARTS_DIR=$REPO_PATH/helm-charts/stable/prow-control-plane\nHELM_VALUES_FILE=$CONTROLPLANE_CHARTS_DIR/values.yaml\nHELM_CHART_FILE=$CONTROLPLANE_CHARTS_DIR/Chart.yaml\n\npatch::yaml::with::readability $CONTROLPLANE_CHARTS_DIR \"values.yaml\" \".$VALUES_PATH = \\\"$IMAGE\\\"\"\n\n# Updating Prow controlplane chart version to the next patch release\nif [ $UPDATE_CHART -eq 1 ]; then\n    chart_version=$(yq eval \".version\" $HELM_CHART_FILE)\n    IFS=. read -r major minor patch <<<\"$chart_version\"\n    ((patch++))\n    printf -v updated_chart_version '%d.%d.%d' \"$major\" \"$minor\" \"$((patch))\"\n    patch::yaml::with::readability $CONTROLPLANE_CHARTS_DIR \"Chart.yaml\" \".version = \\\"$updated_chart_version\\\"\"\nfi\n", "num_lines": 68}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\n\nIMAGES=${1?Specify first argument - Images to be replaced in Helm values}\nVALUE_PATHS=${2?Specify second argument - Path to var in values.yaml to update, ex: deck.image}\n\nIMAGES=(${IMAGES// / })\nVALUE_PATHS=(${VALUE_PATHS// / })\n\n${SCRIPT_ROOT}/../../../pr-scripts/update_local_branch.sh eks-distro-build-tooling\n\t\nfor (( i=0; i<${#IMAGES[*]}; ++i)); do \\\n    ${SCRIPT_ROOT}/update_helm_chart.sh \"${IMAGES[$i]}\" \"${VALUE_PATHS[$i]}\" $(( $i==${#IMAGES[*]} - 1 )); \\\ndone\n\n${SCRIPT_ROOT}/../../../pr-scripts/create_pr.sh eks-distro-build-tooling 'helm-charts/stable/prow-control-plane/*.yaml'\n", "num_lines": 36}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nBUILD_LIB_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")/\" && pwd -P)\"\n\nif [ \"${USE_BUILDX:-}\" == \"true\" ]; then\n    printf \"\\nBuilding with with docker buildx\\n\" >&2\n\n    CMD=\"docker buildx\"\n    ARGS=\"\"\n    while test $# -gt 0; do\n        case \"$1\" in\n            --frontend)\n                shift\n                shift\n                ;;\n            --opt)\n                shift\n                if [[ $1 = filename* ]]; then\n                    ARGS+=\"--${1/filename/file} \"\n                elif [[ $1 = \"no-cache\"* ]]; then\n                    ARGS+=\"--${1/no-cache/no-cache-filter} \"\n                else\n                    ARGS+=\"--${1/:/ } \"\n                fi\n                shift\n                ;;\n            --local)\n                shift\n                if [[ $1 = context* ]]; then\n                    ARGS+=\"${1/context=/} \"        \n                fi\n                shift\n                ;;\n            --export-cache)\n                shift\n                ARGS+=\"--cache-to $1 \"\n                shift\n                ;;\n            --import-cache)\n                shift\n                ARGS+=\"--cache-from $1 \"\n                shift\n                ;;\n            *)\n                ARGS+=\"$1 \"\n                shift\n                ;;\n        esac\n    done\nelse\n    printf \"\\nBuilding with buildctl\\n\" >&2\n\n    CMD=\"buildctl\"\n    ARGS=\"$@\"\nfi\n\nif [ -f \"/buildkit.sh\" ] && ! buildctl debug workers >/dev/null 2>&1; then\n    # on the builder base this helper file exists to run buildkitd\n    # in prow buildkitd is run as a seperate container so it will be running already\n    # in codebuild its run directly on the instance so we want to use this helper\n    CMD=\"/buildkit.sh\"\nfi\n\n# From time to time we see random failures when creating/pushing images that fix on reruning the job\n# this is an attempt to avoid failing key jobs, like the release job, with a flaky failure\n# If running in builder base, most likely we are running in prow/codebuild, us retry logic\n# if not in builder base, probably running locally so skip the retry\nif [ -f \"/buildkit.sh\" ]; then\n    for i in $(seq 1 5); do\n        [ $i -gt 1 ] && sleep 15\n        $CMD $ARGS && s=0 && break || s=$?\n    done\n\n    # space is limited on presubmit nodes, after each image build clear the build cache\n    if [ \"${JOB_TYPE:-}\" == \"presubmit\" ] && [ \"${PRUNE_BUILDCTL:-false}\" == \"true\" ]; then\n        buildctl prune --all >&2\n    fi\n\n    (exit $s)\nelse\n    # skip retry when running locally\n    log_file=$(mktemp)\n    trap \"rm -f $log_file\" EXIT\n    if ! $CMD $ARGS 2>&1 | tee $log_file; then        \n        if grep -q \"blobs/uploads/\\\": EOF\" $log_file ; then\n            echo \"******************************************************\"\n            echo \"Ensure container registry and repository exists!!\"\n            echo \"Try running make create-ecr-repos to create ecr repositories in your aws account.\"\n            echo \"******************************************************\"\n        fi\n        exit 1\n    fi\nfi\n", "num_lines": 111}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nfunction buildkit_ready() {\n  for i in {1..24}\n  do\n    if ! buildctl debug workers > /dev/null 2>&1;\n    then\n      echo \"Buildkit daemon is not running. Retrying.\"\n      sleep 5\n    else\n      exit 0\n    fi\n  done\n  echo \"Buildkit daemon is not available\"\n  exit 1\n}\n\nbuildkit_ready\n", "num_lines": 36}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nfunction retry() {\n  local n=1\n  local max=120\n  local delay=5\n  while true; do\n    \"$@\" && break || {\n      if [[ $n -lt $max ]]; then\n        ((n++))\n        sleep $delay;\n      fi\n    }\n  done\n}\n\nfunction build::docker::retry_pull() {\n  retry docker pull \"$@\"\n}", "num_lines": 36}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nfunction registry_ready() {\n  for i in {1..24}\n  do\n    if ! curl http://$IMAGE_REPO/ > /dev/null 2>&1;\n    then\n      echo \"Local registry at ${IMAGE_REPO} is not running. Retrying.\"\n      sleep 5\n    else\n      exit 0\n    fi\n  done\n  echo \"Local registry at ${IMAGE_REPO} is not available\"\n  exit 1\n}\n\nregistry_ready\n", "num_lines": 36}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\n\nBUILDER_NAME=\"eks-d-builders\"\n\nfunction install_kubectl() {\n    local -r kubectl_version=v1.23.12\n    local -r eks_d_release_branch=1-23\n    local -r eks_d_release_number=6\n    curl -sSL \"https://distro.eks.amazonaws.com/kubernetes-${eks_d_release_branch}/releases/${eks_d_release_number}/artifacts/kubernetes/${kubectl_version}/bin/linux/amd64/kubectl\" -o /bin/kubectl\n    chmod +x /bin/kubectl\n}\n\nfunction setup_kubeconfig_in_pod() {\n    install_kubectl\n    \n    for f in \"token\" \"ca.crt\"; do\n        if [ ! -f \"/var/run/secrets/kubernetes.io/serviceaccount/${f}\" ]; then\n            echo \"/var/run/secrets/kubernetes.io/serviceaccount/${f} missing!\"\n            exit 1\n        fi\n    done\n\n    kubectl config set-cluster cfc --server=https://kubernetes.default --certificate-authority=/var/run/secrets/kubernetes.io/serviceaccount/ca.crt\n    kubectl config set-context cfc --cluster=cfc\n    kubectl config set-credentials user --token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)\n    kubectl config set-context cfc --user=user\n    kubectl config use-context cfc\n}\n\ndocker buildx version\n\nif ! docker buildx ls | grep $BUILDER_NAME > /dev/null 2>&1; then\n    # in postsubmit we create builders for both amd and arm since buildx doesnt support\n    # different types of drivers within the same group\n    if [ ${CREATE_BUILDER_PODS:-false} = \"true\" ]; then\n        if ! kubectl config current-context > /dev/null 2>&1; then\n            if [ ! -f /var/run/secrets/kubernetes.io/serviceaccount/token ]; then\n                echo \"No kubeconfig or service account!\"\n                exit 1\n            fi\n            setup_kubeconfig_in_pod\n        fi\n\n        kubectl get pods -n buildkit-orchestration\n        kubectl get deployments -n buildkit-orchestration\n\n        # created buildkit are destroyed in a trap at the end of the prow job\n        # in the case where jobs are evicted or otherwise crash where the trap does\n        # not fire, they can be left around. cleanup any instances older than 1 day\n        # https://stackoverflow.com/a/53989428 - match the 5 column which is the age against a nuber folloed by \"d\"\n        DEPLOYMENTS=$(kubectl get deployments -n buildkit-orchestration | awk 'match($5,/[0-9]+d/) {printf $1\" \"}')\n        if [ -n \"$DEPLOYMENTS\" ]; then\n            kubectl delete deployments -n buildkit-orchestration $DEPLOYMENTS\n        fi\n\n        docker buildx create \\\n            --bootstrap \\\n            --name=$BUILDER_NAME \\\n            --driver=kubernetes \\\n            --platform=linux/amd64 \\\n            --node=builder-amd64-${PROW_JOB_ID:-1} \\\n            --driver-opt=namespace=buildkit-orchestration,nodeselector=\"arch=AMD64\",rootless=true,image=${BUILDKITD_IMAGE:-moby/buildkit:v0.10.5-rootless}\n\n        docker buildx create \\\n            --bootstrap \\\n            --append \\\n            --name=$BUILDER_NAME \\\n            --driver=kubernetes \\\n            --platform=linux/arm64 \\\n            --node=builder-arm64-${PROW_JOB_ID:-1} \\\n            --driver-opt=namespace=buildkit-orchestration,nodeselector=\"arch=ARM64\",rootless=true,image=${BUILDKITD_IMAGE:-moby/buildkit:v0.10.5-rootless}\n\n        kubectl get pods -n buildkit-orchestration\n        kubectl get deployments -n buildkit-orchestration\n\n    else\n        if [ -n \"${BUILDKIT_HOST_AMD64}\" ] && [ -n \"${BUILDKIT_HOST_ARM64}\" ]; then\n            docker buildx create --name $BUILDER_NAME --platform=linux/amd64 --driver remote ${BUILDKIT_HOST_AMD64}\n            docker buildx create --append --name $BUILDER_NAME --platform=linux/arm64 --driver remote ${BUILDKIT_HOST_ARM64}\n        else\n            # in presubmit we just attach to the sidecar container\n            docker buildx create --name $BUILDER_NAME --driver remote ${BUILDKIT_HOST:-unix:///run/buildkit/buildkitd.sock}\n        fi\n    fi\nfi\n\ndocker buildx inspect $BUILDER_NAME\ndocker buildx use $BUILDER_NAME\n", "num_lines": 106}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\nset -e\nset -o pipefail\n\nif [ ! -d \"/root/.docker\" ]; then\n    mkdir -p /root/.docker\nfi\n\nmv docker-config/docker-ecr-config.json /root/.docker/config.json\n", "num_lines": 12}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\nset -e\nset -o pipefail\nset -x\n\nif [ \"$AWS_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty AWS_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\nif [ \"$ECR_PUBLIC_PUSH_ROLE_ARN\" == \"\" ]; then\n    echo \"Empty ECR_PUBLIC_PUSH_ROLE_ARN, this script must be run in a postsubmit pod with IAM Roles for Service Accounts\"\n    exit 1\nfi\n\n# Creating a config file on the fly to configure assume-role and push to ECR public\ncat << EOF > config\n[default]\noutput=json\nregion=${AWS_REGION:-${AWS_DEFAULT_REGION:-us-west-2}}\nrole_arn=$AWS_ROLE_ARN\nweb_identity_token_file=/var/run/secrets/eks.amazonaws.com/serviceaccount/token\n\n[profile ecr-public-push]\nrole_arn=$ECR_PUBLIC_PUSH_ROLE_ARN\nregion=us-east-1\nsource_profile=default\nEOF\n\nexport AWS_CONFIG_FILE=$(pwd)/config\nexport AWS_PROFILE=ecr-public-push\nexport AWS_DEFAULT_PROFILE=$AWS_PROFILE\n\nunset AWS_ROLE_ARN AWS_WEB_IDENTITY_TOKEN_FILE\n", "num_lines": 50}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -x\nset -e\nset -o pipefail\n\nSCRIPT_ROOT=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd -P)\"\nsource \"${SCRIPT_ROOT}/common.sh\"\n\nsource /docker.sh\n\nstart::dockerd\nwait::for::dockerd\n\nbuild::docker::retry_pull public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v7.0.0\n\ndocker run --privileged --rm public.ecr.aws/eks-distro-build-tooling/binfmt-misc:qemu-v7.0.0 --install aarch64\n", "num_lines": 31}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nsync_artifacts_to_s3() {\n  local artifact_bucket=$1\n  local src_dir=$2\n  local dest_dir=$3\n  local public_read=$4\n  local dry_run=$5\n\n  if [ $# -le 3 ] ; then\n    echo \"not enough parameters supplied!\"\n  fi\n\n  if [ -z \"$1\" ] ; then\n    echo \"first parameter, target artifacts s3 bucket, is required!\" && exit 1;\n  fi\n\n  if [ -z \"$2\" ] ; then\n    echo \"second parameter source directory is required!\" && exit 1;\n  fi\n\n  if [ -z \"$3\" ] ; then\n    echo \"third parameter destination directory is required!\" && exit 1;\n  fi\n\n  if [ -z \"$4\" ] ; then\n    echo \"fourth parameter, public read for s3, is required\" && exit 1;\n  fi\n\n  if [ -z \"$5\" ] ; then\n    echo \"this is not a dry run!\"\n  fi\n\n  public_acl_argument=\"\"\n  if [ \"$public_read\" = \"true\" ]; then\n    public_acl_argument=\"--acl public-read\"\n  fi\n\n  if [ \"$dry_run\" = \"true\" ]; then\n  aws s3 cp $src_dir s3://${artifact_bucket}/${dest_dir} --recursive --dryrun ${public_acl_argument}\n    else\n  aws s3 sync $src_dir s3://${artifact_bucket}/${dest_dir} ${public_acl_argument}\nfi\n}\n", "num_lines": 62}
{"repo_name": "eks-distro-build-tooling", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\nset -o pipefail\nset -x\n\nif [ -z $1 ]; then\n    echo \"You must provide a working directory in which to execute the git synchronization\"\n    exit 0\nfi\n\nif [ -z $2 ]; then\n    echo \"You must provide a remote url to synchronize against\"\n    exit 1\nfi\n\nif [ -z $3 ]; then\n    echo \"No target branch specified; defaulting to 'main'\"\n    BRANCH=main\nelse\n    BRANCH=$3\nfi\n\ngit -C $1 init\ngit -C $1 remote add origin $2\ngit -C $1 fetch origin\ngit -C $1 reset --hard origin/$BRANCH\n", "num_lines": 41}
{"repo_name": "eks-distro-prow-jobs", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run buildkitd in background mode to be able to poll\n# for the done status file and kill process after\n\n# if running on the postsubmit cluster allow more cache space\nKEEP_STORAGE=20000\nif [ -n \"${FARGATE_PROFILE_NAME}\" ]; then\n\tKEEP_STORAGE=5000\nfi\n\nrootlesskit \\\n\tbuildkitd \\\n\t--addr=unix:///run/buildkit/buildkitd.sock \\\n\t--oci-worker-no-process-sandbox \\\n\t--oci-worker-platform=linux/amd64 \\\n\t--oci-worker-platform=linux/arm64 \\\n\t--oci-worker-gc \\\n\t--oci-worker-gc-keepstorage $KEEP_STORAGE \\\n\t&\npid=$!\nwhile [ ! -f /status/done ]\ndo\n  sleep 5\ndone\nkill $pid\n\n", "num_lines": 40}
{"repo_name": "eks-distro-prow-jobs", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run registry in background mode to be able to poll\n# for the done status file and kill process after\n\n\nwhile [ ! -f /status/done ]; do\n    echo -e \"-------------------------------------------------------------------------------------------------\"\n    \n    for folder in \"/root/.cache/go-build\" \"/home/prow/go/pkg/mod\" \"/home/user/.local/share/buildkit\" \"/var/lib/registry\" \"/tmp\"; do\n        if [ -d $folder ]; then\n            du -sh $folder 2> /dev/null\n        fi\n    done\n\n    for folder in \"/home/prow/go/src/github.com/aws\"; do\n        if [ -d $folder ]; then\n            echo -e \"\\n--------------- $folder -------------------\"\n            du -Sh $folder 2> /dev/null | sort -rh | head -10 \n            du -sh $folder 2> /dev/null\n            echo -e \"--------------- $folder -------------------\\n\"\n        fi\n    done\n\n    df -h\n    echo -e \"-------------------------------------------------------------------------------------------------\\n\"\n    \n    sleep 20\ndone\n", "num_lines": 42}
{"repo_name": "eks-distro-prow-jobs", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Run registry in background mode to be able to poll\n# for the done status file and kill process after\n\nregistry serve /etc/docker/registry/config.yml & \npid=$!\nwhile [ ! -f /status/done ]\ndo\n  sleep 5\ndone\nkill $pid\n", "num_lines": 25}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "#  Usage: Check results of firelens release stability tests\n#\n#  $1 = region\n#  $2 = cluster name\n#  $3 = Execution ID\n# \n# output order is the same as in our result table template\n# output is number of running tasks first, then number of cores\n\n\nfamilys_golden=\"\necs-firelens-stability-tests-golden-path-no-onepod-low-throughput\necs-firelens-stability-tests-golden-path-onepod-low-throughput\necs-firelens-stability-tests-golden-path-onepod-low-throughput-real\necs-firelens-stability-tests-golden-path-no-onepod-high-throughput\necs-firelens-stability-tests-golden-path-onepod-high-throughput\n\"\n\nfamilys_s3_stability=\"\necs-firelens-stability-tests-s3-stability-s3-throughput-1mbps\necs-firelens-stability-tests-s3-stability-s3-throughput-30mbps\n\"\n\nfamilys_s3_sensitivity=\"\necs-firelens-stability-tests-s3-sensitivity-s3-control\necs-firelens-stability-tests-s3-sensitivity-s3-outputPluginCount-10\necs-firelens-stability-tests-s3-sensitivity-s3-s3_compression-gzip\necs-firelens-stability-tests-s3-sensitivity-s3-s3_key_format-advanced\necs-firelens-stability-tests-s3-sensitivity-s3-throughput-10mbps\necs-firelens-stability-tests-s3-sensitivity-s3-total_file_size-1M\necs-firelens-stability-tests-s3-sensitivity-s3-upload_timeout-1m\necs-firelens-stability-tests-s3-sensitivity-s3-use_put_object-on\n\"\n\nif [ -z \"${1}\" ]\nthen\n    echo \"Usage: check_results.sh {region} {cluster} {execution ID}\"\n    exit 1\nfi\nif [ -z \"${2}\" ]\nthen\n    echo \"Usage: check_results.sh {region} {cluster} {execution ID}\"\n    exit 1\nfi\nif [ -z \"${3}\" ]\nthen\n    echo \"Usage: check_results.sh {region} {cluster} {execution ID}\"\n    exit 1\nfi\n\necho \"Cluster: ${2} ${1}\"\necho \"Execution: ${3}\"\necho \"____Task Counts____\"\necho \"\"\n\necho \"____GOLDEN PATH Task Counts____\" \nfor task_def in $familys_golden; do\n    running_count=$(aws ecs list-tasks --cluster $2 --region $1  --family $task_def | jq '.taskArns | length')\n    echo \"${task_def}: ${running_count}\"\ndone\n\n\necho \"____S3 stability Task Counts____\"\nfor task_def in $familys_s3_stability; do\n    running_count=$(aws ecs list-tasks --cluster $2 --region $1  --family $task_def | jq '.taskArns | length')\n    echo \"${task_def}: ${running_count}\"\ndone\n\n\necho \"____S3 sensitivity Task Counts____\"\nfor task_def in $familys_s3_sensitivity; do\n    running_count=$(aws ecs list-tasks --cluster $2 --region $1  --family $task_def | jq '.taskArns | length')\n    echo \"${task_def}: ${running_count}\"\ndone\n\n\necho \"____Core Counts____\"\ntotal_cores=$(aws s3 ls s3://stability-output/${3} --recursive | grep \"stacktrace\" | wc -l)\necho \"Total Cores: ${3}: ${total_cores}\"\necho \"\"\n\necho \"____GOLDEN PATH Core Counts____\" \nfor task_def in $familys_golden; do\n    cores=$(aws s3 ls s3://stability-output/${3}/${task_def} --recursive | grep \"stacktrace\" | wc -l)\n    echo \"${task_def}: ${cores}\"\ndone\n\n\necho \"____S3 stability Core Counts____\"\nfor task_def in $familys_s3_stability; do\n    cores=$(aws s3 ls s3://stability-output/${3}/${task_def} --recursive | grep \"stacktrace\" | wc -l)\n    echo \"${task_def}: ${cores}\"\ndone\n\n\necho \"____S3 sensitivity Core Counts____\"\nfor task_def in $familys_s3_sensitivity; do\n    cores=$(aws s3 ls s3://stability-output/${3}/${task_def} --recursive | grep \"stacktrace\" | wc -l)\n    echo \"${task_def}: ${cores}\"\ndone\n", "num_lines": 101}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource=$1\ndestination=$2\ndelay=$3\n\nmkdir -p $destination\n\necho \"o----------------------o\"\necho \"|                      |\"\necho \"|                      |\"\necho \"|                      |\"\necho \"|                      |\"\necho \"|   ~ Magic Mirror ~   |\"\necho \"|                      |\"\necho \"|         v1.0         |\"\necho \"|                      |\"\necho \"|                      |\"\necho \"|                      |\"\necho \"|                      |\"\necho \"o----------------------o\"\n\n\n\n# Wipe all files and directories from destination (Reconsider)\n# rm -r \"$destination\"/*\n\n# Copy all files from source to destination\ncp -alr \"$source\"/* \"$destination\"/\n\n# Keep track of the last MOVED_FROM event\nold_file=\"\"\n\ninotifywait -m -r --format %e\\;%w%f $source -e CREATE -e DELETE  -e MOVED_FROM -e MOVED_TO | while read -r line; do\n  # Split events into an array\n  IFS=';' read -r -a event_array <<< \"$line\"\n\n  echo \"EVENT: $line\"\n\n  # Check if create event\n  if [[ \"${event_array[0]}\" =~ CREATE.* ]]; then\n    file=\"${event_array[1]}\"\n    if [ -d \"$file\" ]; then\n      # If directory, create it in destination\n      mkdir -p \"$destination/${file#$source/}\"\n    else\n      # If file, create hard link in destination\n      ln \"$file\" \"$destination/${file#$source/}\"\n    fi\n  fi\n\n  # Check if delete event\n  if [[ \"${event_array[0]}\" =~ DELETE.* ]]; then\n    file=\"${destination}/${event_array[1]#$source/}\"\n    if [ -d \"$file\" ]; then\n      # If directory, wait $delay seconds before deleting it in destination\n      (sleep $delay && rm -rf \"$file\") &\n    else\n      # If file, wait $delay seconds before deleting it in destination\n      (sleep $delay && rm -f \"$file\") &\n    fi\n  fi\n\n  # Check if move event (MOVED_FROM)\n  if [[ \"${event_array[0]}\" =~ MOVED_FROM.* ]]; then\n    old_file=\"${destination}/${event_array[1]#$source/}\"\n  fi\n\n  # Check if move event (MOVED_TO)\n  if [[ \"${event_array[0]}\" =~ MOVED_TO.* ]]; then\n    file=\"${destination}/${event_array[1]#$source/}\"\n    new_file=\"$old_file\"\n    old_file=\"\"\n    mv \"$new_file\" \"$file\"\n  fi\ndone\n", "num_lines": 77}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "\necho \"Mountebank API Mocker with S3 Client v0.0.1\"\n\n# Retrieve S3 Test Configuration\naws s3 cp s3://${CLIENT_S3_BUCKET}/${CLIENT_S3_FILE} ./mountebank.json\n\n# Launch Mountebank\nmb&\nchild=$!\n\nsleep 5\n\n# Load Configuration\nconfig=`cat /mountebank.json`\necho $config\ncurl -i -X POST -H 'Content-Type: application/json' http://localhost:2525/imposters --data \"$config\"\n\n# Wait for Mountebank\nwait \"$child\"\n", "num_lines": 20}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "SCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\n_term() { \n  echo \"Caught SIGTERM signal!\" \n  kill -TERM \"$child\" 2>/dev/null\n}\n\ntrap _term SIGTERM\n\n# Start the mock API\ndocker pull bbyars/mountebank:2.8.2\ndocker run --rm --privileged -p 4430:4430 -p 2525:2525 -p 4545:4545 -p 5555:5555 bbyars/mountebank:2.8.2 start &\n\n# docker run --privileged --network host --rm -p 2525:2525 -p 4545:4545 -p 5555:5555 bbyars/mountebank:2.8.2 start &\nchild=$!\n\nsleep 1\n\nconfig=`cat $SCRIPT_DIR/mountebank.json`\necho $config\ncurl -i -X POST -H 'Content-Type: application/json' http://localhost:2525/imposters --data \"$config\"\n\nwait \"$child\"\n", "num_lines": 24}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "\necho \"Mountebank API Mocker with S3 Client v0.0.1\"\n\n# Retrieve S3 Test Configuration\naws s3 cp s3://${CLIENT_S3_BUCKET}/${CLIENT_S3_FILE} ./mountebank.json\n\n# Launch Mountebank\nmb&\nchild=$!\n\nsleep 5\n\n# Load Configuration\nconfig=`cat /mountebank.json`\necho $config\ncurl -i -X POST -H 'Content-Type: application/json' http://localhost:2525/imposters --data \"$config\"\n\n# Wait for Mountebank\nwait \"$child\"\n", "num_lines": 20}
{"repo_name": "firelens-datajet", "repo_creator": "aws", "programming_language": "Shell", "code": "SCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\n_term() { \n  echo \"Caught SIGTERM signal!\" \n  kill -TERM \"$child\" 2>/dev/null\n}\n\ntrap _term SIGTERM\n\n# Start the mock API\ndocker pull bbyars/mountebank:2.8.2\ndocker run --rm --privileged -p 4430:4430 -p 2525:2525 -p 4545:4545 -p 5555:5555 bbyars/mountebank:2.8.2 start &\n\n# docker run --privileged --network host --rm -p 2525:2525 -p 4545:4545 -p 5555:5555 bbyars/mountebank:2.8.2 start &\nchild=$!\n\nsleep 1\n\nconfig=`cat $SCRIPT_DIR/mountebank.json`\necho $config\ncurl -i -X POST -H 'Content-Type: application/json' http://localhost:2525/imposters --data \"$config\"\n\nwait \"$child\"\n", "num_lines": 24}
{"repo_name": "go-kafka-event-source", "repo_creator": "aws", "programming_language": "Shell", "code": "BASEDIR=$(dirname \"$0\")\n\nrm -rf ${BASEDIR}/data", "num_lines": 3}
{"repo_name": "go-kafka-event-source", "repo_creator": "aws", "programming_language": "Shell", "code": "KAFKA_BIN_VERSION=\"2.13\"\nKAFKA_VERSION=\"3.2.1\"\n\necho \"kafka install: ${KAFKA_INSTALL}\"\nif [ -z $KAFKA_INSTALL ]\nthen\n    if [ ! -d $1 ]\n    then\n        curl https://dlcdn.apache.org/kafka/${KAFKA_VERSION}/kafka_${KAFKA_BIN_VERSION}-${KAFKA_VERSION}.tgz -o kafka.tgz\n        tar -xzvf kafka.tgz\n        mv kafka_${KAFKA_BIN_VERSION}-${KAFKA_VERSION} $1\n        rm kafka.tgz\n    fi\nfi", "num_lines": 14}
{"repo_name": "go-kafka-event-source", "repo_creator": "aws", "programming_language": "Shell", "code": "BASEDIR=$(dirname \"$0\")\nSTART_DIR=$(pwd)\nif [ -z $KAFKA_INSTALL ]\nthen\n    KAFKA_INSTALL=$1\nfi\n\nPROGRAM=$2\nCOMMAND=$3\n\ncd ${KAFKA_INSTALL}\nABS_KAFKA_INSTALL=$(pwd)\ncd ${START_DIR}/${BASEDIR}\n${ABS_KAFKA_INSTALL}/bin/${PROGRAM}-server-${COMMAND}.sh ./${PROGRAM}.properties > ./${PROGRAM}.log\n", "num_lines": 15}
{"repo_name": "graph-explorer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ $(grep -e 'GRAPH_EXP_HTTPS_CONNECTION' ./packages/graph-explorer/.env | cut -d \"=\" -f 2) ]; then\n\n    if [ $HOST ]; then\n        echo \"Generating new self-signed SSL cert using $HOST...\"\n        cd /graph-explorer/packages/graph-explorer-proxy-server/cert-info/\n        sed -i \"21s/$/ $HOST:*/\" csr.conf\n        sed -i \"8s/$/ $HOST:*/\" cert.conf\n        openssl req -x509 -sha256 -days 356 -nodes -newkey rsa:2048 -subj \"/CN=Graph Explorer/C=US/L=Seattle\" -keyout rootCA.key -out rootCA.crt\n        openssl genrsa -out ./server.key 2048\n        openssl req -new -key ./server.key -out ./server.csr -config ./csr.conf\n        openssl x509 -req -in ./server.csr -CA ./rootCA.crt -CAkey ./rootCA.key -CAcreateserial -out ./server.crt -days 365 -sha256 -extfile ./cert.conf\nelse\n        echo \"No HOST environment variable specified.\"\n        if [ -f \"./rootCA.key\" ] && [ -f \"./rootCA.crt\" ] && [ -f \"./rootCA.crt\" ] && [ -f \"./server.csr\"] && [ -f \"./server.crt\"]; then\n            echo \"Found existing self-signed SSL certificate. Re-using existing cert.\"\n    else\n            echo \"No existing self-signed SSL certificate found. Please specify --env HOST=<hostname> during docker run command to create SSL cert.\"\n            exit 1\n        fi\n    fi\n\nelse\n    echo \"SSL disabled. Skipping self-signed certificate generation.\"\n    exit 1\nfi\necho \"Starting graph explorer...\"\npnpm -w start:proxy-server\n", "num_lines": 30}
{"repo_name": "graph-explorer", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\npnpm pm2 start \"node node-server.js\"\npnpm pm2 start \"serve dist\"\n\nexec sh", "num_lines": 5}
{"repo_name": "graph-notebook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -u ec2-user -i <<'EOF'\n\necho \"export GRAPH_NOTEBOOK_AUTH_MODE=DEFAULT\" >> ~/.bashrc  # set to IAM instead of DEFAULT if cluster is IAM enabled\necho \"export GRAPH_NOTEBOOK_HOST=CHANGE-ME\" >> ~/.bashrc\necho \"export GRAPH_NOTEBOOK_PORT=8182\" >> ~/.bashrc\necho \"export NEPTUNE_LOAD_FROM_S3_ROLE_ARN=\" >> ~/.bashrc\necho \"export AWS_REGION=cn-northwest-1\" >> ~/.bashrc  # modify region if needed\n\nVERSION=\"\"\nfor i in \"$@\"\ndo\ncase $i in\n    -v=*|--version=*)\n    VERSION=\"${i#*=}\"\n    echo \"set notebook version to ${VERSION}\"\n    shift\n    ;;\nesac\ndone\n\nsource activate JupyterSystemEnv\n\necho \"installing Python 3 kernel\"\npython3 -m ipykernel install --sys-prefix --name python3 --display-name \"Python 3\"\n\necho \"installing python dependencies...\"\npip uninstall NeptuneGraphNotebook -y # legacy uninstall when we used to install from source in s3\n\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"ipython==7.16.1\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"jupyter-console<=6.4.0\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"jupyter-client<=6.1.12\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"ipywidgets<=7.7.1\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"notebook==6.4.12\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"nbclient<=0.7.0\"\npip install -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn \"awswrangler\"\n\nif [[ ${VERSION} == \"\" ]]; then\n  pip install --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn graph-notebook\nelse\n  pip install --upgrade -i https://pypi.tuna.tsinghua.edu.cn/simple --trusted-host pypi.tuna.tsinghua.edu.cn graph-notebook==${VERSION}\nfi\n\necho \"installing nbextensions...\"\npython -m graph_notebook.nbextensions.install\n\necho \"installing static resources...\"\npython -m graph_notebook.static_resources.install\n\necho \"enabling visualization...\"\nif [[ ${VERSION//./} < 330 ]] && [[ ${VERSION} != \"\" ]]; then\n  jupyter nbextension install --py --sys-prefix graph_notebook.widgets\nfi\njupyter nbextension enable  --py --sys-prefix graph_notebook.widgets\n\nmkdir -p ~/SageMaker/Neptune\ncd ~/SageMaker/Neptune || exit\npython -m graph_notebook.notebooks.install\nchmod -R a+rw ~/SageMaker/Neptune/*\n\nsource ~/.bashrc || exit\nHOST=${GRAPH_NOTEBOOK_HOST}\nPORT=${GRAPH_NOTEBOOK_PORT}\nAUTH_MODE=${GRAPH_NOTEBOOK_AUTH_MODE}\nSSL=${GRAPH_NOTEBOOK_SSL}\nLOAD_FROM_S3_ARN=${NEPTUNE_LOAD_FROM_S3_ROLE_ARN}\n\nif [[ ${SSL} -eq \"\" ]]; then\n  SSL=\"True\"\nfi\n\necho \"Creating config with\nHOST:                       ${HOST}\nPORT:                       ${PORT}\nAUTH_MODE:                  ${AUTH_MODE}\nSSL:                        ${SSL}\nAWS_REGION:                 ${AWS_REGION}\"\n\n/home/ec2-user/anaconda3/envs/JupyterSystemEnv/bin/python -m graph_notebook.configuration.generate_config \\\n  --host \"${HOST}\" \\\n  --port \"${PORT}\" \\\n  --auth_mode \"${AUTH_MODE}\" \\\n  --ssl \"${SSL}\" \\\n  --load_from_s3_arn \"${LOAD_FROM_S3_ARN}\" \\\n  --aws_region \"${AWS_REGION}\"\n\necho \"Adding graph_notebook.magics to ipython config...\"\nif [[ ${VERSION//./} > 341 ]] || [[ ${VERSION} == \"\" ]]; then\n  /home/ec2-user/anaconda3/envs/JupyterSystemEnv/bin/python -m graph_notebook.ipython_profile.configure_ipython_profile\nelse\n  echo \"Skipping, unsupported on graph-notebook<=3.4.1\"\nfi\n\nconda /home/ec2-user/anaconda3/bin/deactivate\necho \"done.\"\n\nEOF\n", "num_lines": 99}
{"repo_name": "graph-notebook", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo -u ec2-user -i <<'EOF'\n\necho \"export GRAPH_NOTEBOOK_AUTH_MODE=DEFAULT\" >> ~/.bashrc  # set to IAM instead of DEFAULT if cluster is IAM enabled\necho \"export GRAPH_NOTEBOOK_HOST=CHANGE-ME\" >> ~/.bashrc\necho \"export GRAPH_NOTEBOOK_PORT=8182\" >> ~/.bashrc\necho \"export NEPTUNE_LOAD_FROM_S3_ROLE_ARN=\" >> ~/.bashrc\necho \"export AWS_REGION=us-west-2\" >> ~/.bashrc  # modify region if needed\n\nVERSION=\"\"\nfor i in \"$@\"\ndo\ncase $i in\n    -v=*|--version=*)\n    VERSION=\"${i#*=}\"\n    echo \"set notebook version to ${VERSION}\"\n    shift\n    ;;\nesac\ndone\n\nsource activate JupyterSystemEnv\n\necho \"installing Python 3 kernel\"\npython3 -m ipykernel install --sys-prefix --name python3 --display-name \"Python 3\"\n\necho \"installing python dependencies...\"\npip uninstall NeptuneGraphNotebook -y # legacy uninstall when we used to install from source in s3\n\npip install \"ipython==7.16.1\"\npip install \"jupyter-console<=6.4.0\"\npip install \"jupyter-client<=6.1.12\"\npip install \"ipywidgets<=7.7.1\"\npip install \"notebook==6.4.12\"\npip install \"nbclient<=0.7.0\"\npip install awswrangler\n\nif [[ ${VERSION} == \"\" ]]; then\n  pip install --upgrade graph-notebook\nelse\n   pip install --upgrade graph-notebook==${VERSION}\nfi\n\necho \"installing nbextensions...\"\npython -m graph_notebook.nbextensions.install\n\necho \"installing static resources...\"\npython -m graph_notebook.static_resources.install\n\necho \"enabling visualization...\"\nif [[ ${VERSION//./} < 330 ]] && [[ ${VERSION} != \"\" ]]; then\n  jupyter nbextension install --py --sys-prefix graph_notebook.widgets\nfi\njupyter nbextension enable  --py --sys-prefix graph_notebook.widgets\n\nmkdir -p ~/SageMaker/Neptune\ncd ~/SageMaker/Neptune || exit\npython -m graph_notebook.notebooks.install\nchmod -R a+rw ~/SageMaker/Neptune/*\n\nsource ~/.bashrc || exit\nHOST=${GRAPH_NOTEBOOK_HOST}\nPORT=${GRAPH_NOTEBOOK_PORT}\nAUTH_MODE=${GRAPH_NOTEBOOK_AUTH_MODE}\nSSL=${GRAPH_NOTEBOOK_SSL}\nLOAD_FROM_S3_ARN=${NEPTUNE_LOAD_FROM_S3_ROLE_ARN}\n\nif [[ ${SSL} -eq \"\" ]]; then\n  SSL=\"True\"\nfi\n\necho \"Creating config with\nHOST:                       ${HOST}\nPORT:                       ${PORT}\nAUTH_MODE:                  ${AUTH_MODE}\nSSL:                        ${SSL}\nAWS_REGION:                 ${AWS_REGION}\"\n\n/home/ec2-user/anaconda3/envs/JupyterSystemEnv/bin/python -m graph_notebook.configuration.generate_config \\\n  --host \"${HOST}\" \\\n  --port \"${PORT}\" \\\n  --auth_mode \"${AUTH_MODE}\" \\\n  --ssl \"${SSL}\" \\\n  --load_from_s3_arn \"${LOAD_FROM_S3_ARN}\" \\\n  --aws_region \"${AWS_REGION}\"\n\necho \"Adding graph_notebook.magics to ipython config...\"\nif [[ ${VERSION//./} > 341 ]] || [[ ${VERSION} == \"\" ]]; then\n  /home/ec2-user/anaconda3/envs/JupyterSystemEnv/bin/python -m graph_notebook.ipython_profile.configure_ipython_profile\nelse\n  echo \"Skipping, unsupported on graph-notebook<=3.4.1\"\nfi\n\nconda /home/ec2-user/anaconda3/bin/deactivate\necho \"done.\"\n\nEOF\n", "num_lines": 99}
{"repo_name": "graph-notebook", "repo_creator": "aws", "programming_language": "Shell", "code": "source /tmp/venv/bin/activate\ncd \"${WORKING_DIR}\"\nif [ ${GRAPH_NOTEBOOK_SSL} = \"\" ]; then\n    GRAPH_NOTEBOOK_SSL=\"True\"\nfi\n\nif [ ${PROVIDE_EXAMPLES} -eq 1 ]; then\n    python3 -m graph_notebook.notebooks.install --destination \"${EXAMPLE_NOTEBOOK_DIR}\"\nfi\n\npython3 -m graph_notebook.configuration.generate_config \\\n    --host \"${GRAPH_NOTEBOOK_HOST}\" \\\n    --port \"${GRAPH_NOTEBOOK_PORT}\" \\\n    --proxy_host \"${GRAPH_NOTEBOOK_HOST}\" \\\n    --proxy_port \"${GRAPH_NOTEBOOK_PORT}\" \\\n    --auth_mode \"${GRAPH_NOTEBOOK_AUTH_MODE}\" \\\n    --ssl \"${GRAPH_NOTEBOOK_SSL}\" \\\n    --iam_credentials_provider \"${GRAPH_NOTEBOOK_IAM_PROVIDER}\" \\\n    --load_from_s3_arn \"${NEPTUNE_LOAD_FROM_S3_ROLE_ARN}\" \\\n    --aws_region \"${AWS_REGION}\" \\\n\n\n\n##### Running The Notebook Service #####\nmkdir ~/.jupyter\nif [ ! ${NOTEBOOK_PASSWORD} ];\n    then\n        echo \"c.NotebookApp.password='$(python -c \"from notebook.auth import passwd; print(passwd('`curl -s 169.254.169.254/latest/meta-data/instance-id`'))\")'\" >> ~/.jupyter/jupyter_notebook_config.py\nelse\n    echo \"c.NotebookApp.password='$(python -c \"from notebook.auth import passwd; print(passwd('${NOTEBOOK_PASSWORD}'))\")'\" >> ~/.jupyter/jupyter_notebook_config.py\nfi\necho \"c.NotebookApp.allow_remote_access = True\" >> ~/.jupyter/jupyter_notebook_config.py\necho \"c.InteractiveShellApp.extensions = ['graph_notebook.magics']\" >> ~/.jupyter/jupyter_notebook_config.py\n\nnohup jupyter notebook --ip='*' --port ${NOTEBOOK_PORT} \"${WORKING_DIR}/notebooks\" --allow-root > jupyterserver.log &\nnohup jupyter lab --ip='*' --port ${LAB_PORT} \"${WORKING_DIR}/notebooks\" --allow-root > jupyterlab.log &\ntail -f /dev/null", "num_lines": 37}
{"repo_name": "homebrew-tap", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\n# Replace local tap with contents of this repo\n\n# Local tap folder name is the full repo name\n# instead of what the tap command uses.\n# Ex: brew tap aws/tap -> aws/homebrew-tap\nTAP_NAME=\"aws/homebrew-tap\"\nTAP_LOCATION=\"\"\n\n# Find tap path depending on the OS\nif [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n    TAP_LOCATION=\"/home/linuxbrew/.linuxbrew/Homebrew/Library/Taps/\"\nelif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n    TAP_LOCATION=\"/usr/local/Homebrew/Library/Taps/\"\nelse\n    echo \"Unsupported OS: $OSTYPE\"\n    exit 2\nfi\n\nTAP_LOCATION+=\"${TAP_NAME}\"\n\n# Replace tap with files in this repo\nrm -rf \"${TAP_LOCATION}\"\ncp -a . \"${TAP_LOCATION}\"\n", "num_lines": 27}
{"repo_name": "iot-atlas", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This script is used for both local testing and automated build process (CodeBuild)\nset -e\n\n# Local name of docker image to build and use\nexport IMAGE_NAME=temporary/hugo-ubuntu:latest\n\nfunction usage {\n    cat <<HELP_USAGE\n    usage: $0 [-hd] [-s bucket]\n    -d --develop      Run Hugo in interactive development mode\n                      (asciidoc images will show broken)\n    -s --sync=bucket  S3 bucket name to sync generate content\n    -v --validate     Run validation on content\n    -h --help         display help\nHELP_USAGE\n}\n\nfunction build_docker_image {\n    if ! [[ $(docker images -q $IMAGE_NAME) ]]; then\n        echo \"********** Building container image for Hugo and dependencies\"\n        docker build -t $IMAGE_NAME --build-arg GOPROXY=$(go env GOPROXY) .\n    fi\n}\n\nfunction hugo_build {\n    echo \"********** Building site content\"\n\n    # Empty public folder completely\n    shopt -s dotglob\n    rm -rf hugo/public/*\n    shopt -u dotglob\n\n    build_docker_image\n\n    # Generate full content\n    docker run --rm -v \"$PWD/hugo:/hugo-project\" $IMAGE_NAME hugo\n}\n\nfunction hugo_validate {\n    echo \"********** Validating content\"\n    # Test HTML local and external links\n    # Start hugo locally, reference //host.docker.internal for other containers to use\n    docker run -d --name hugo_checker --rm -p 1313:1313 -v \"$PWD/hugo:/hugo-project\" temporary/hugo-ubuntu:latest hugo server --bind 0.0.0.0 -b http://localhost:1313/ 1>/dev/null\n\n    # Wait until the web server is up\n    while [ \"`docker inspect -f {{.State.Health.Status}} hugo_checker`\" != \"healthy\" ]; do sleep 0.5; done\n\n    # Check all links\n    # unset shell exit to stop the container above before exiting\n    set +e\n    # The validation muffet is only in Dockerhub - set credentials for CI/CD\n    if ! [[ -z $DOCKERHUB_USERNAME || -z $DOCKERHUB_PASSWORD ]]; then\n    echo \"********** Docker credentials found, authenticating to hub.docker.com\"\n        echo $DOCKERHUB_PASSWORD | docker login -u $DOCKERHUB_USERNAME --password-stdin\n    fi\n    # Run for every translated language\n    if ! uri_path_validate \"en\" ||\n       ! uri_path_validate \"zh\" ||\n       ! uri_path_validate \"fr\"; then\n        echo \"********** Validation errors, stopping local Hugo instance\"\n        docker stop hugo_checker 1>/dev/null\n        echo \"Link checks failed, exiting\"\n        exit 1\n    fi\n    set -e\n    echo \"********** Validation completed successfully, stopping local Hugo instance\"\n    docker stop hugo_checker 1>/dev/null\n}\n\nfunction uri_path_validate {\n    # Run link checker for specific URI\n    # Note - run the container on the host network to access Hugo running in a separate container\n    #      - Exclude on github.com/aws in case of editURL changes. Will catch during automation\n    echo \"********** Running link checks on language: $1\"\n    if ! docker run --rm --net=\"host\" raviqqe/muffet \\\n            --exclude=\"https://github.com/aws/\" \\\n            --buffer-size=\"8192\"  \\\n            --header=\"User-Agent: IotAtlasBot/1.0 (+http://iotatlas.net/en/bot/)\" \\\n            --max-connections=512 --max-connections-per-host=2 --rate-limit=16 \\\n            http://localhost:1313/$1/; then\n        echo \"********** $1: Invalid links (see above)\"\n        return 1   # 1 = failure\n    fi\n    echo \"********** $1: All links are valid\"\n}\n\nfunction sync_s3 {\n    echo \"********** Synching content to S3 bucket: $BUCKET\"\n    aws s3 rm s3://$BUCKET --recursive\n    aws s3 sync hugo/public s3://$BUCKET\n}\n\nfunction hugo_develop {\n    build_docker_image\n    echo \"********** Starting Hugo for local development\"\n    docker run --rm -p 1313:1313 -v \"$PWD/hugo:/hugo-project\" $IMAGE_NAME\n    exit 0\n}\n\n# Process arguments\n\nfor i in \"$@\"\ndo\ncase $i in\n    -d|--develop)\n    hugo_develop\n    # Function exits - when in develop, not other tasks\n    ;;\n    -s=*|--sync=*)\n    BUCKET=\"${i#*=}\"\n    shift # past arg=param\n    ;;\n    -v|--validate)\n    VALIDATE=YES\n    shift\n    ;;\n    -h|--help)\n    usage\n    exit\n    ;;\n    *)\n    usage\n    exit 1\n    ;;\nesac\ndone\n\n# Build and optionally validate and sync\nhugo_build\n\nif [[ $VALIDATE ]]; then\n    hugo_validate\nfi\n\nif [[ $BUCKET ]]; then\n    sync_s3\nfi\n", "num_lines": 139}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n###\n# Starts a local server for the documentation website, for easy iteration.\n##\n\nif [ ! -d .venv ]; then\n  python3 -m venv --system-site-packages .venv\nfi\nsource .venv/bin/activate\n\npython3 -m pip install -r requirements-dev.txt --upgrade\n\npython3 -m mkdocs serve\n", "num_lines": 15}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nsrc=\"./src\"\n\n# Generate metadata files based on package.json.\n/usr/bin/env node ./Directory.Build.props.t.js > ${src}/Directory.Build.props\n/usr/bin/env node ./NuGet.Metadata.props.t.js > ${src}/NuGet.Metadata.props\n\n# Embed @jsii/runtime as a resource\nbundle_dir=\"src/Amazon.JSII.Runtime/jsii-runtime\"\nmkdir -p ${bundle_dir}\nrsync -av $(node -p 'require(\"path\").dirname(require.resolve(\"@jsii/runtime/package.json\"))')/webpack/ ${bundle_dir}\n\n\n# Generate Source\n/usr/bin/env node ./JsiiRuntimeProvider.t.js > ${src}/Amazon.JSII.Runtime/Services/JsiiRuntimeProvider.cs\n", "num_lines": 17}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\ndotnet build --force -c Release ./test/Amazon.JSII.Runtime.IntegrationTests\n", "num_lines": 5}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\ntest=\"./test\"\ngenRoot=\"${test}/generated\"\n\n# Clean up before we start working\nrm -rf ${genRoot}\n\n# Generate .NET projects for jsii-calc and its dependencies.\njsii-pacmak -t dotnet --code-only --recurse -o ${genRoot} ../../jsii-calc\n\n# Hack around project references to de-duplicate Amazon.JSII.Runtime in generated code.\nfor csproj in ${genRoot}/dotnet/*/*.csproj\ndo\n  dotnet remove ${csproj} package Amazon.JSII.Runtime\n  dotnet add    ${csproj} reference ../dotnet-runtime/src/Amazon.JSII.Runtime/Amazon.JSII.Runtime.csproj\ndone\n\n# Generate Directory.Build.props\n/usr/bin/env node ./Directory.Build.props.t.js > ${test}/Directory.Build.props\n", "num_lines": 21}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n# Run integration tests\necho \"Running integration tests\"\ndotnet test -c Release ./test/Amazon.JSII.Runtime.IntegrationTests/Amazon.JSII.Runtime.IntegrationTests.csproj\n", "num_lines": 7}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\ncd ${scriptdir}/..\n\nrm -fr dist\nmkdir -p dist/go\nrsync -av jsii-runtime-go/* dist/go/\n\n# create a \"version\" file which is needed by jsii-release\nversion=$(node -p \"require('./package.json').version\")\necho ${version} > dist/go/version\n", "num_lines": 13}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nproject=\"./project\"\n\nmkdir -p conf\n\n# generate pom.xml and JsiiVersion.java with version from package.json\n/usr/bin/env node ./pom.xml.t.js > ${project}/pom.xml\n/usr/bin/env node ./user.xml.t.js > ${project}/user.xml\n/usr/bin/env node ./JsiiVersion.t.js > ${project}/src/main/java/software/amazon/jsii/JsiiVersion.java\n\n# embed @jsii/runtime as a resource\nmkdir -p ${project}/src/main/resources/software/amazon/jsii\nrsync -av $(node -p 'require(\"path\").dirname(require.resolve(\"@jsii/runtime/package.json\"))')/webpack/ ${project}/src/main/resources/software/amazon/jsii\n\n/usr/bin/env node ./BundledRuntime.t.js > ${project}/src/main/java/software/amazon/jsii/BundledRuntime.java\n", "num_lines": 17}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n# consumed by user.xml.t.js\nstaging=\"maven-repo\"\nrm -fr ${staging} && mkdir -p ${staging}\n\n# Remove local artifacts from local maven repository\nrm -fr project/.m2/software/amazon/jsii\n\n# generate user.xml & pom.xml\nnode ./user.xml.t.js > ./project/user.xml\nnode ./pom.xml.t.js > ./project/pom.xml\n\n# build jsii-calc and all dep and output to MAVEN_REPO\njsii-pacmak ../../jsii-calc --outdir ${staging} -t java --recurse --verbose $@\n", "num_lines": 17}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n{\n    # Input\n    INPUT_FILE='lib/assembly.d.ts'\n\n    # Output\n    OUTPUT_DIR='schema'\n    OUTPUT_FILE=\"${OUTPUT_DIR}/jsii-spec.schema.json\"\n\n    mkdir -p ${OUTPUT_DIR}\n\n    echo \"Generating JSON schema into ${OUTPUT_FILE}\"\n    typescript-json-schema                   \\\n        ${INPUT_FILE}      'Assembly'        \\\n        --out              ${OUTPUT_FILE}    \\\n        --refs             true              \\\n        --required         true              \\\n        --strictNullChecks true              \\\n        --topRef           true\n}\n\n{\n    # Input\n    INPUT_FILE='lib/redirect.d.ts'\n\n    # Output\n    OUTPUT_DIR='schema'\n    OUTPUT_FILE=\"${OUTPUT_DIR}/assembly-redirect.schema.json\"\n\n    mkdir -p ${OUTPUT_DIR}\n\n    echo \"Generating JSON schema into ${OUTPUT_FILE}\"\n    typescript-json-schema                   \\\n        ${INPUT_FILE}      'AssemblyRedirect'\\\n        --out              ${OUTPUT_FILE}    \\\n        --refs             true              \\\n        --required         true              \\\n        --strictNullChecks true              \\\n        --topRef           true\n}\n", "num_lines": 43}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\ncommit=${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\n# CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local build or CodePipeline build),\n# use the HEAD commit hash\nif [ -z \"${commit}\" ]; then\n  commit=\"$(git rev-parse --verify HEAD)\"\n  suffix=\"@dev\"\nfi\n\nVERSION=$(node -p \"require('./package.json').version.replace(/\\\\+[0-9a-f]+\\$/, '')\")\n\ncat > lib/version.ts <<HERE\n// Generated at $(date -u +\"%Y-%m-%dT%H:%M:%SZ\") by generate.sh\n\n/** The short version number for this JSII compiler (e.g: \\`X.Y.Z\\`) */\nexport const SHORT_VERSION = '${VERSION}';\n\n/** The qualified version number for this JSII compiler (e.g: \\`X.Y.Z (build #######)\\`) */\nexport const VERSION = '${VERSION} (build ${commit:0:7}${suffix:-})';\nHERE\n", "num_lines": 23}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\ncd ${scriptdir}\n\nmodules=\"\\\n  ../@scope/jsii-calc-base-of-base \\\n  ../@scope/jsii-calc-base \\\n  ../@scope/jsii-calc-lib \\\n  ./\"\n\nfor mod in $modules; do\n  node -p \"require('./package.json').name\"\n  (\n    cd $mod\n    yarn build\n    yarn test:update\n  )\ndone\n\n", "num_lines": 21}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\ncommit=${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\n# CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local build or CodePipeline build),\n# use the HEAD commit hash\nif [ -z \"${commit}\" ]; then\n  commit=\"$(git rev-parse --verify HEAD)\"\nfi\n\nVERSION=$(node -p \"require('./package.json').version.replace(/\\\\+[0-9a-f]+\\$/, '')\")\n\ncat > lib/version.ts <<HERE\n// Generated at $(date -u +\"%Y-%m-%dT%H:%M:%SZ\") by generate.sh\n\n/** The qualified version number for this JSII compiler. */\nexport const VERSION = '${VERSION} (build ${commit:0:7})';\nHERE\n", "num_lines": 19}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\ncommit=${CODEBUILD_RESOLVED_SOURCE_VERSION:-}\n# CODEBUILD_RESOLVED_SOURCE_VERSION is not defined (i.e. local build or CodePipeline build),\n# use the HEAD commit hash\nif [ -z \"${commit}\" ]; then\n  commit=\"$(git rev-parse --verify HEAD)\"\n  suffix=\"@dev\"\nfi\n\nVERSION=$(node -p \"require('./package.json').version.replace(/\\\\+[0-9a-f]+\\$/, '')\")\n\ncat > lib/version.ts <<HERE\n// Generated at $(date -u +\"%Y-%m-%dT%H:%M:%SZ\") by generate.sh\n\n/** The short version number for this jsii-pacmak release (e.g: \\`X.Y.Z\\`) */\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const VERSION: string = '${VERSION}';\n\n/** The qualified version number for this jsii-pacmak release (e.g: \\`X.Y.Z (build #######)\\`) */\nexport const VERSION_DESC = '${VERSION} (build ${commit:0:7}${suffix:-})';\nHERE\n", "num_lines": 24}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\ncd $(dirname $0)\n\n# Test various build modes for jsii-pacmak (these are all ways in\n# which users can decide to run jsii-pacmak)\n#\n# The following list of packages must be toposorted, like a monorepo\n# manager would order the individual builds.\npacmak=${PWD}/../bin/jsii-pacmak\npackagedirs=\"\\\n    ${PWD}/../../@scope/jsii-calc-base-of-base \\\n    ${PWD}/../../@scope/jsii-calc-base \\\n    ${PWD}/../../@scope/jsii-calc-lib \\\n    ${PWD}/../../jsii-calc \\\n    \"\nclean_dists() {\n    for dir in $packagedirs; do rm -rf $dir/dist; done\n}\n\noutdir=$(mktemp -d)\nfinal_cleanup() {\n    rm -rf ${outdir}\n}\ntrap final_cleanup EXIT\n\n# Prepare Python venv to avoid depending on system stuff\ncase \"${OSTYPE}\" in\n\"msys\" | \"cygwin\" | \"win32\")\n    # On Windows, there is usually no python3.exe (the GitHub action workers will have a python3\n    # shim, but using this actually results in a WinError with Python 3.7 and 3.8 where venv will\n    # fail to copy the python binary if it's not invoked as python.exe). More on this particular\n    # issue can be read here: https://bugs.python.org/issue43749\n    PYTHON='python'\n    ;;\n*)\n    PYTHON='python3'\n    ;;\nesac\n\nvenv=\"${outdir}/.env\"\n${PYTHON} -m venv ${venv}\nif [ -f ${venv}/bin/activate ]; then\n    . ${venv}/bin/activate\nelse\n    # Hello Windows!\n    . ${venv}/Scripts/activate\nfi\n${PYTHON} -m pip install --upgrade pip~=22.1 twine~=4.0\n\n# Provision a specific NuGet package cache\nNUGET_CACHE=${outdir}/.nuget/packages\nOPTS=\"--dotnet-nuget-global-packages-folder=${NUGET_CACHE}\"\n\n# Single target, recursive build to a certain location\nclean_dists\necho \"Testing SINGLE TARGET, RECURSIVE build.\"\n(\n    # Run from the ${outdir} and use a relative --outdir value...\n    calcdir=${PWD}/../../jsii-calc\n    cd ${outdir}\n    ${pacmak} ${OPTS} -v -o dist --recurse ${calcdir}\n)\nfor tgt in dotnet go java python; do\n    # Ensure the target artifacts have been created as expected...\n    if [ ! -d \"${outdir}/dist/${tgt}\" ]; then\n        echo \"Assertion Failure: Expected a ${tgt} directory to exist in ${outdir}, but none found...\"\n        exit 1\n    fi\ndone\nrm -rf \"${outdir}/dist\"\n\n# Multiple targets, build one-by-one into own directory\nclean_dists\necho \"Testing ONE-BY-ONE build.\"\nfor dir in $packagedirs; do\n    ${pacmak} ${OPTS} -v $dir\ndone\n\n# Multiple targets, build all at once into own directory\nclean_dists\necho \"Testing ALL-AT-ONCE build.\"\n${pacmak} ${OPTS} -v --no-parallel $packagedirs\n\n# Test custom pack command\nclean_dists\necho \"Testing yarn custom pack command.\"\n${pacmak} ${OPTS} -v --pack-command='yarn pack -f custom.tgz -s && echo custom.tgz' ${PWD}/../../@scope/jsii-calc-base-of-base\n\n# Test custom mvn settings command\nclean_dists\necho \"Testing custom mvn parameters.\"\n${pacmak} ${OPTS} -v --mvn-builder=singlethreaded --mvn-threads=4 $packagedirs\n", "num_lines": 94}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#------------------------------------------------------------------------\n# updates all package.json files to the version defined in lerna.json\n# this is called when building inside our ci/cd system\n#------------------------------------------------------------------------\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\n\n# go to repo root\ncd ${scriptdir}/..\n\nfiles=\"$(find . -name package.json | grep -v node_modules | xargs)\"\n${scriptdir}/align-version.js ${files}\n\n# validation\nmarker=$(node -p \"require('./scripts/get-version-marker')\")\nif find . -name package.json | grep -v node_modules | xargs grep \"[^0-9]${marker}\"; then\n  echo \"ERROR: unexpected version marker ${marker} in a package.json file\"\n  exit 1\nfi\n", "num_lines": 21}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Build only the JavaScript packages\nset -euo pipefail\nscope=\"\"\nfor package in $(node_modules/.bin/lerna ls); do\n    scope=\"$scope --scope $package\"\ndone\nnode_modules/.bin/lerna $scope run build\nnode_modules/.bin/lerna $scope run test\n", "num_lines": 10}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------------\n#\n# This script is intended to be used to bump the version of the CDK modules, update package.json,\n# package-lock.json, and create a commit.\n#\n# to start a version bump, run:\n#     bump.sh <version | version Type>\n#\n# If a version is not provided, the 'minor' version will be bumped.\n# The version can be an explicit version _or_ one of:\n# 'major', 'minor', 'patch', 'premajor', 'preminor', 'prepatch', or 'prerelease'.\n#\n# --------------------------------------------------------------------------------------------------\nset -euo pipefail\nversion=${1:-minor}\n\necho \"Starting ${version} version bump\"\n\n# /bin/bash ./install.sh\n\n# Generate CHANGELOG and create a commit (see .versionrc.json)\nnpx standard-version --release-as ${version}\n", "num_lines": 24}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------------\n#\n# this wonderful tool allows you to execute a command for all modules in this repo\n# in topological order, but has the incredible property of being stateful.\n# this means that if a command fails, you can fix the issue and resume from where\n# you left off.\n#\n# to start a session, run:\n#     foreach.sh COMMAND\n#\n# this will execute \"COMMAND\" for each module in the repo (cwd will be the directory of the module).\n# if a task fails, it will stop, and then to resume, simply run `foreach.sh` again (with or without the same command).\n#\n# to reset the session (either when all tasks finished or if you wish to run a different session), run:\n#     rm -f ~/.foreach.*\n#\n# this will effectively delete the state files.\n#\n# --------------------------------------------------------------------------------------------------\nset -euo pipefail\nscriptdir=$(cd $(dirname $0) && pwd)\nstatefile=\"${HOME}/.foreach.state\"\ncommandfile=\"${HOME}/.foreach.command\"\ncommand_arg=\"${@:-}\"\nbase=$PWD\n\nfunction heading {\n  printf \"\\e[38;5;81m$@\\e[0m\\n\"\n}\n\nfunction error {\n  printf \"\\e[91;5;81m$@\\e[0m\\n\"\n}\n\nfunction success {\n  printf \"\\e[32;5;81m$@\\e[0m\\n\"\n}\n\nif [[ \"${1:-}\" == \"--reset\" ]]; then\n    rm -f ~/.foreach.*\n    success \"state cleared. you are free to start a new command.\"\n    exit 0\nfi\n\n\nif [ -f \"${statefile}\" ] && [ -f \"${commandfile}\" ]; then\n  command=\"$(cat ${commandfile})\"\n  if [ ! -z \"${command_arg}\" ] && [ \"${command}\" != \"${command_arg}\" ]; then\n    error \"error: there is still an active session for: \\\"${command}\\\". to reset:\"\n    error \"   $0 --reset\"\n    exit 1\n  fi\nfi\n\nif [ ! -f \"${statefile}\" ] && [ ! -f \"${commandfile}\" ]; then\n  if [ ! -z \"${command_arg}\" ]; then\n    command=\"${command_arg}\"\n    success \"starting new session\"\n    node_modules/.bin/lerna ls --all --toposort -p > ${statefile}\n    echo \"${command}\" > ${commandfile}\n  else\n    error \"no active session, use \\\"$(basename $0) COMMAND\\\" to start a new session\"\n    exit 0\n  fi\nfi\n\nnext=\"$(head -n1 ${statefile})\"\nif [ -z \"${next}\" ]; then\n  success \"done (queue is empty). to reset:\"\n  success \"   $0 --reset\"\n  exit 0\nfi\n\nremaining=$(cat ${statefile} | wc -l | xargs -n1)\n\nheading \"---------------------------------------------------------------------------------\"\nheading \"${next}: ${command} (${remaining} remaining)\"\n\n(\n  cd ${next}\n\n  # special-case \"npm run\" - skip any modules that simply don't have\n  # that script (similar to how \"lerna run\" behaves)\n  if [[ \"${command}\" == \"npm run\"* ]]; then\n    script=\"$(echo ${command} | cut -d\" \" -f3)\"\n    exists=$(node -pe \"(require('./package.json').scripts || {}).${script} || ''\")\n    if [ -z \"${exists}\" ]; then\n      echo \"skipping (no \"${script}\" script in package.json)\"\n      exit 0\n    fi\n  fi\n\n  sh -c \"${command}\" &> /tmp/foreach.stdio || {\n    cd ${base}\n    cat /tmp/foreach.stdio | ${scriptdir}/path-prefix ${next}\n    error \"error: last command failed. fix problem and resume by executing: $0\"\n    error \"directory:    ${next}\"\n    exit 1\n  }\n)\n\ntail -n +2 \"${statefile}\" > \"${statefile}.tmp\"\ncp \"${statefile}.tmp\" \"${statefile}\"\nexec $0\n", "num_lines": 106}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# creates symlinks under node_modules for all packages in this repo\n# can be used to work against this code base.\nset -euo pipefail\n\n# we need the '..' here, as this script is in the scripts/ subdirectory of the repo\nroot=\"$(cd $(dirname $0)/.. && pwd)\"\n\nmkdir -p node_modules node_modules/.bin\n\nmodules=\"$(find ${root}/packages -name package.json | grep -v node_modules | grep -v init-templates | xargs -n1 dirname)\"\nfor module in ${modules}; do\n  if [[ $(basename $(dirname $module)) == @* ]]; then\n    # This is a @scope/based package\n    scope=$(basename $(dirname $module))\n    link_dir=node_modules/$(basename $(dirname $module))\n    mkdir -p $link_dir\n  else\n    link_dir=node_modules\n  fi\n\n  module_dir=${link_dir}/$(basename $module)\n  echo \"${module} => ${module_dir}\"\n  rm -fr ${module_dir}\n  ln -fs ${module} $link_dir\n\n  # Symlink executable scripts into place as well. This is not completely\n  # according to spec (we look in the bin/ directory instead of the { \"scripts\"\n  # } entry in package.json but it's quite a bit easier.\n  [[ -d $module/bin ]] && for script in $(find $module/bin -perm +111); do\n    echo \"${script} => node_modules/.bin/$(basename $script)\"\n    ln -fs ${script} node_modules/.bin\n  done\ndone\n", "num_lines": 35}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# The purpose of this script is to prepare a \"dist\" directory\n# according to the conventions of the Buildable pipeline, so\n# that artifacts can be published to the various package managers\nset -e\nexport PATH=$PWD/node_modules/.bin:$PATH\n\ndistdir=\"$PWD/dist\"\nrm -fr ${distdir}\nmkdir -p ${distdir}\n\n# run \"npm run package\" in all modules (which support it)\n# this should emit a publishable to the \"dist\" directory of each module\nlerna run package --stream\n\n# collect all \"dist\" directories into \"pack\"\nfor dist in $(lerna exec --ignore=jsii-calc --ignore=@scope/\\* \"[ -d ./dist ] && echo \\${PWD}/dist || true\"); do\n  echo \"collecting ${dist}...\"\n  rsync -av ${dist}/ ${distdir}/\ndone\n\n# create a build.json file with build metadata\n# commit is obtained from CODEBUILD_RESOLVED_SOURCE_VERSION.\n# if not defined (i.e. local build or CodePipeline build), use the HEAD commit hash\nversion=\"$(node -e \"console.log(require('./lerna.json').version)\")\"\ncommit=\"${CODEBUILD_RESOLVED_SOURCE_VERSION:-\"$(git rev-parse --verify HEAD)\"}\"\n\ncat > ${distdir}/build.json <<HERE\n{\n  \"name\": \"jsii\",\n  \"version\": \"${version}\",\n  \"commit\": \"${commit}\"\n}\nHERE\n\n# copy CHANGELOG.md to dist/ for github releases\ncp CHANGELOG.md ${distdir}/\n\n# for posterity, print all files in dist\nfind dist/\n", "num_lines": 41}
{"repo_name": "jsii", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n###\n# This script can be used to build a jsii/superchain:local image from a locally\n# checked out version of the Dockerfile. It is made to build an image as similar\n# as possible to what would be built in the CI/CD infrastructure (in that it'll\n# include similar labels).\n###\n\n# Obtain the currently checked out commit ID\nCOMMIT_ID=$(git rev-parse HEAD)\n\nif [[ ! -z $(git status --short) ]]; then\n  # IF there are changes or untracked file, note the tree is dirty\n  COMMIT_ID=${COMMIT_ID}+dirty\nelse\n  # Otherwise, note that this was built locally\n  COMMIT_ID=${COMMIT_ID}+local\nfi\n\n# Now on to building the image\ndocker build                                                                    \\\n  --target superchain                                                           \\\n  --build-arg BUILDPLATFORM=linux/amd64                                         \\\n  --build-arg TARGETPLATFORM=linux/amd64                                        \\\n  --build-arg BUILD_TIMESTAMP=$(date -u +'%Y-%m-%dT%H:%M:%SZ')                  \\\n  --build-arg REGISTRY=\"docker.io/library\"                                      \\\n  --build-arg COMMIT_ID=${COMMIT_ID}                                            \\\n  -t \"public.ecr.aws/jsii/superchain:local\"                                     \\\n  -f ${PWD}/Dockerfile                                                          \\\n  ..\n", "num_lines": 33}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -eu -o pipefail\n\nfor i in $(\n  find ./tools ./cmd ./pkg ./test ./hack -name \"*.go\"\n); do\n  if ! grep -q \"Apache License\" $i; then\n    cat hack/boilerplate.go.txt $i >$i.new && mv $i.new $i\n  fi\ndone\n", "num_lines": 11}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nif [ -z ${ENABLE_GIT_PUSH+x} ]; then\n  ENABLE_GIT_PUSH=false\nfi\n\necho \"codegen running ENABLE_GIT_PUSH: ${ENABLE_GIT_PUSH}\"\n\nbandwidth() {\n  GENERATED_FILE=\"pkg/providers/instancetype/zz_generated.bandwidth.go\"\n  NO_UPDATE=''\n  SUBJECT=\"Bandwidth\"\n\n  go run hack/code/bandwidth_gen.go -- \"${GENERATED_FILE}\"\n\n  GIT_DIFF=$(git diff --stat \"${GENERATED_FILE}\")\n  checkForUpdates \"${GIT_DIFF}\" \"${NO_UPDATE}\" \"${SUBJECT}\" \"${GENERATED_FILE}\"\n}\n\npricing() {\n  GENERATED_FILE=\"pkg/providers/pricing/zz_generated.pricing.go\"\n  NO_UPDATE=$' pkg/providers/pricing/zz_generated.pricing.go | 4 ++--\\n 1 file changed, 2 insertions(+), 2 deletions(-)'\n  SUBJECT=\"Pricing\"\n\n  go run hack/code/prices_gen.go -- \"${GENERATED_FILE}\"\n\n  GIT_DIFF=$(git diff --stat \"${GENERATED_FILE}\")\n  checkForUpdates \"${GIT_DIFF}\" \"${NO_UPDATE}\" \"${SUBJECT} beside timestamps since last update\" \"${GENERATED_FILE}\"\n}\n\nvpcLimits() {\n  GENERATED_FILE=\"pkg/providers/instancetype/zz_generated.vpclimits.go\"\n  NO_UPDATE=''\n  SUBJECT=\"VPC Limits\"\n\n  go run hack/code/vpc_limits_gen.go -- \\\n    --url=https://raw.githubusercontent.com/aws/amazon-vpc-resource-controller-k8s/master/pkg/aws/vpc/limits.go \\\n    --output=\"${GENERATED_FILE}\"\n\n  GIT_DIFF=$(git diff --stat \"${GENERATED_FILE}\")\n  checkForUpdates \"${GIT_DIFF}\" \"${NO_UPDATE}\" \"${SUBJECT}\" \"${GENERATED_FILE}\"\n}\n\ninstanceTypeTestData() {\n  GENERATED_FILE=\"pkg/fake/zz_generated.describe_instance_types.go\"\n  NO_UPDATE=''\n  SUBJECT=\"Instance Type Test Data\"\n\n  go run hack/code/instancetype_testdata_gen.go --out-file ${GENERATED_FILE} \\\n    --instance-types t3.large,m5.large,m5.xlarge,p3.8xlarge,g4dn.8xlarge,c6g.large,inf1.2xlarge,inf1.6xlarge,trn1.2xlarge,m5.metal,dl1.24xlarge,m6idn.32xlarge,t4g.small,t4g.xlarge,t4g.medium\n\n  GIT_DIFF=$(git diff --stat \"${GENERATED_FILE}\")\n  checkForUpdates \"${GIT_DIFF}\" \"${NO_UPDATE}\" \"${SUBJECT}\" \"${GENERATED_FILE}\"\n}\n\ncheckForUpdates() {\n  GIT_DIFF=$1\n  NO_UPDATE=$2\n  SUBJECT=$3\n  GENERATED_FILE=$4\n\n  echo \"Checking git diff for updates. ${GIT_DIFF}, ${NO_UPDATE}\"\n  if [[ \"${GIT_DIFF}\" == \"${NO_UPDATE}\" ]]; then\n    noUpdates \"${SUBJECT}\"\n    git checkout \"${GENERATED_FILE}\"\n  else\n    echo \"true\" >/tmp/codegen-updates\n    git add \"${GENERATED_FILE}\"\n    if [[ $ENABLE_GIT_PUSH == true ]]; then\n      gitCommitAndPush \"${SUBJECT}\"\n    fi\n  fi\n}\n\ngitOpenAndPullBranch() {\n  git fetch origin\n  git checkout codegen || git checkout -b codegen || true\n}\n\ngitCommitAndPush() {\n  UPDATE_SUBJECT=$1\n  git commit -m \"CodeGen updates from AWS API for ${UPDATE_SUBJECT}\"\n  git push --set-upstream origin codegen\n}\n\nnoUpdates() {\n  UPDATE_SUBJECT=$1\n  echo \"No updates from AWS API for ${UPDATE_SUBJECT}\"\n}\n\nif [[ $ENABLE_GIT_PUSH == true ]]; then\n  gitOpenAndPullBranch\nfi\n\nbandwidth\npricing\nvpcLimits\ninstanceTypeTestData\n", "num_lines": 100}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nK8S_VERSION=\"${K8S_VERSION:=\"1.27.x\"}\"\nKUBEBUILDER_ASSETS=\"${KUBEBUILDER_ASSETS:=\"${HOME}/.kubebuilder/bin\"}\"\n\nmain() {\n    tools\n    kubebuilder\n}\n\ntools() {\n    go install github.com/google/go-licenses@latest\n    go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest\n    go install github.com/google/ko@latest\n    go install github.com/mikefarah/yq/v4@latest\n    go install github.com/norwoodj/helm-docs/cmd/helm-docs@latest\n    go install sigs.k8s.io/controller-runtime/tools/setup-envtest@latest\n    go install sigs.k8s.io/controller-tools/cmd/controller-gen@latest\n    go install github.com/sigstore/cosign/cmd/cosign@latest\n    go install -tags extended github.com/gohugoio/hugo@v0.110.0\n    go install golang.org/x/vuln/cmd/govulncheck@latest\n    go install github.com/onsi/ginkgo/v2/ginkgo@latest\n\n    if ! echo \"$PATH\" | grep -q \"${GOPATH:-undefined}/bin\\|$HOME/go/bin\"; then\n        echo \"Go workspace's \\\"bin\\\" directory is not in PATH. Run 'export PATH=\\\"\\$PATH:\\${GOPATH:-\\$HOME/go}/bin\\\"'.\"\n    fi\n}\n\nkubebuilder() {\n    mkdir -p $KUBEBUILDER_ASSETS\n    arch=$(go env GOARCH)\n    ## Kubebuilder does not support darwin/arm64, so use amd64 through Rosetta instead\n    if [[ $(go env GOOS) == \"darwin\" ]] && [[ $(go env GOARCH) == \"arm64\" ]]; then\n        arch=\"amd64\"\n    fi\n    ln -sf $(setup-envtest use -p path \"${K8S_VERSION}\" --arch=\"${arch}\" --bin-dir=\"${KUBEBUILDER_ASSETS}\")/* ${KUBEBUILDER_ASSETS}\n    find $KUBEBUILDER_ASSETS\n}\n\nmain \"$@\"\n", "num_lines": 42}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nUSAGE='Usage: '.$0.' [<previous release> <latest release>]'\nTOKEN=$(gh auth token)\n\nif [ ! $# -gt 0 ]; then\n    RELEASES=$(\n        curl -s \\\n            -H \"Accept: application/vnd.github+json\" \\\n            -H \"Authorization: token $TOKEN\" \\\n            https://api.github.com/repos/aws/karpenter/releases\n    )\n    LATEST=$(echo $RELEASES | jq -r \".[0].tag_name\")\n    PREVIOUS=$(echo $RELEASES | jq -r \".[1].tag_name\")\nelif [ $# -eq 2 ]; then\n    PREVIOUS=$1\n    LATEST=$2\nelse\n    echo $USAGE\n    exit\nfi\n\nCOMMITS_PER_PAGE=500\nRESPONSE=$(\n    gh api \\\n        -H \"Accept: application/vnd.github+json\" \\\n        /repos/aws/karpenter/compare/$PREVIOUS...$LATEST?per_page=$COMMITS_PER_PAGE\n)\nTOTAL_COMMITS=$(echo $RESPONSE | jq -r \".total_commits\")\nPAGES=$(echo $((($TOTAL_COMMITS + $COMMITS_PER_PAGE - 1) / $COMMITS_PER_PAGE)))\n\nCOMMITS=\"\"\nfor i in $(seq 1 $PAGES); do\n    NEXT=$(\n        gh api \\\n            -H \"Accept: application/vnd.github+json\" \\\n            /repos/aws/karpenter/compare/$PREVIOUS...$LATEST?per_page=$COMMITS_PER_PAGE\\&page=$i | jq -r \".commits\"\n    )\n    COMMITS=$(jq -s 'add' <(echo \"$COMMITS\") <(echo \"$NEXT\"))\ndone\n\nCONTRIBUTIONS=$(\n    echo $COMMITS | jq -r '\n    sort_by(.commit.author.date)\n    | .[].commit\n    | {author: .author.name, message: (.message | split(\"\\n\")[0])}\n' | jq -s\n)\nNUM_CONTRIBUTIONS=$(echo $CONTRIBUTIONS | jq length)\n\nCOMMUNITY_CONTRIBUTIONS=$(\n    echo $CONTRIBUTIONS | jq -r '\n    .[]\n    | select(\n        .author != \"Ellis Tarn\" and\n        .author != \"Suket Sharma\" and\n        .author != \"Todd Neal\" and\n        .author != \"Todd\" and\n        .author != \"Nick Tran\" and\n        .author != \"Jason Deal\" and\n        .author != \"Ryan Maleki\" and\n        .author != \"Jonathan Innis\" and\n        .author != \"Amanuel Engeda\" and\n        .author != \"Brandon Wagner\" and\n        .author != \"Brandon\" and\n        .author != \"Chris Negus\" and\n        .author != \"Jim DeWaard\" and\n        .author != \"Felix Zhe Huang\" and\n        .author != \"Raghav Tripathi\" and\n        .author != \"Justin Garrison\" and\n        .author != \"Alex Kestner\" and\n        .author != \"Geoffrey Cline\" and\n        .author != \"Bill Rayburn\" and\n        .author != \"Elton\" and\n        .author != \"Prateek Gogia\" and\n        .author != \"njtran\" and\n        .author != \"dewjam\" and\n        .author != \"suket22\" and\n        .author != \"StableRelease\" and\n        .author != \"dependabot[bot]\" and\n        .author != \"github-actions[bot]\"\n    )\n' | jq -s\n)\n\nNUM_COMMUNITY_CONTRIBUTIONS=$(echo $COMMUNITY_CONTRIBUTIONS | jq length)\n\necho \"Comparing $PREVIOUS and $LATEST\"\necho $COMMUNITY_CONTRIBUTIONS | jq\necho \"Community members contributed $NUM_COMMUNITY_CONTRIBUTIONS/$NUM_CONTRIBUTIONS ($(awk \"BEGIN {print (100*$NUM_COMMUNITY_CONTRIBUTIONS/$NUM_CONTRIBUTIONS)}\")%) commits\"\n", "num_lines": 92}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nconfig(){\n  GITHUB_ACCOUNT=\"aws\"\n  AWS_ACCOUNT_ID=\"071440425669\"\n  ECR_GALLERY_NAME=\"karpenter\"\n  RELEASE_REPO_ECR=${RELEASE_REPO_ECR:-public.ecr.aws/${ECR_GALLERY_NAME}/}\n  RELEASE_REPO_GH=${RELEASE_REPO_GH:-ghcr.io/${GITHUB_ACCOUNT}/karpenter}\n\n  MAIN_GITHUB_ACCOUNT=\"aws\"\n  PRIVATE_PULL_THROUGH_HOST=\"${AWS_ACCOUNT_ID}.dkr.ecr.us-east-1.amazonaws.com\"\n  SNS_TOPIC_ARN=\"arn:aws:sns:us-east-1:${AWS_ACCOUNT_ID}:KarpenterReleases\"\n  CURRENT_MAJOR_VERSION=\"0\"\n  RELEASE_PLATFORM=\"--platform=linux/amd64,linux/arm64\"\n\n  RELEASE_TYPE_STABLE=\"stable\"\n  RELEASE_TYPE_SNAPSHOT=\"snapshot\"\n}\n\n# versionData sets all the version properties for the passed release version. It sets the values\n# RELEASE_VERSION_MAJOR, RELEASE_VERSION_MINOR, and RELEASE_VERSION_PATCH to be used by other scripts\nversionData(){\n  local VERSION=\"$1\"\n  local VERSION=\"${VERSION#[vV]}\"\n  RELEASE_VERSION_MAJOR=\"${VERSION%%\\.*}\"\n  RELEASE_VERSION_MINOR=\"${VERSION#*.}\"\n  RELEASE_VERSION_MINOR=\"${RELEASE_VERSION_MINOR%.*}\"\n  RELEASE_VERSION_PATCH=\"${VERSION##*.}\"\n  RELEASE_MINOR_VERSION=\"v${RELEASE_VERSION_MAJOR}.${RELEASE_VERSION_MINOR}\"\n}\n\nrelease() {\n  RELEASE_VERSION=$1\n  echo \"Release Type: $(releaseType \"${RELEASE_VERSION}\")\nRelease Version: ${RELEASE_VERSION}\nCommit: $(git rev-parse HEAD)\nHelm Chart Version $(helmChartVersion $RELEASE_VERSION)\"\n\n  PR_NUMBER=${GH_PR_NUMBER:-}\n  if [ \"${GH_PR_NUMBER+defined}\" != defined ]; then\n   PR_NUMBER=\"none\"\n  fi\n\n  authenticate\n  buildImages\n  cosignImages\n  publishHelmChart \"karpenter\" \"${RELEASE_VERSION}\" \"${RELEASE_REPO_ECR}\"\n  publishHelmChart \"karpenter-crd\" \"${RELEASE_VERSION}\" \"${RELEASE_REPO_ECR}\"\n  pullPrivateReplica \"$RELEASE_VERSION\"\n}\n\nauthenticate() {\n  aws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin \"${RELEASE_REPO_ECR}\"\n}\n\nauthenticatePrivateRepo() {\n  aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin ${PRIVATE_PULL_THROUGH_HOST}\n}\n\nbuildImages() {\n    CONTROLLER_IMG=$(GOFLAGS=${GOFLAGS} KO_DOCKER_REPO=${RELEASE_REPO_ECR} ko publish -B -t \"${RELEASE_VERSION}\" \"${RELEASE_PLATFORM}\" ./cmd/controller)\n    HELM_CHART_VERSION=$(helmChartVersion \"$RELEASE_VERSION\")\n    IMG_REPOSITORY=$(echo \"$CONTROLLER_IMG\" | cut -d \"@\" -f 1 | cut -d \":\" -f 1)\n    IMG_TAG=$(echo \"$CONTROLLER_IMG\" | cut -d \"@\" -f 1 | cut -d \":\" -f 2 -s)\n    IMG_DIGEST=$(echo \"$CONTROLLER_IMG\" | cut -d \"@\" -f 2)\n    yq e -i \".controller.image.repository = \\\"${IMG_REPOSITORY}\\\"\" charts/karpenter/values.yaml\n    yq e -i \".controller.image.tag = \\\"${IMG_TAG}\\\"\" charts/karpenter/values.yaml\n    yq e -i \".controller.image.digest = \\\"${IMG_DIGEST}\\\"\" charts/karpenter/values.yaml\n    yq e -i \".appVersion = \\\"${RELEASE_VERSION#v}\\\"\" charts/karpenter/Chart.yaml\n    yq e -i \".version = \\\"${HELM_CHART_VERSION#v}\\\"\" charts/karpenter/Chart.yaml\n    yq e -i \".appVersion = \\\"${RELEASE_VERSION#v}\\\"\" charts/karpenter-crd/Chart.yaml\n    yq e -i \".version = \\\"${HELM_CHART_VERSION#v}\\\"\" charts/karpenter-crd/Chart.yaml\n}\n\nreleaseType(){\n  RELEASE_VERSION=$1\n\n  if [[ \"${RELEASE_VERSION}\" == v* ]]; then\n    echo $RELEASE_TYPE_STABLE\n  else\n    echo $RELEASE_TYPE_SNAPSHOT\n  fi\n}\n\nhelmChartVersion(){\n    RELEASE_VERSION=$1\n    if [[ $(releaseType $RELEASE_VERSION) == $RELEASE_TYPE_STABLE ]]; then\n      echo $RELEASE_VERSION\n    fi\n\n    if [[ $(releaseType $RELEASE_VERSION) == $RELEASE_TYPE_SNAPSHOT ]]; then\n      echo \"v${CURRENT_MAJOR_VERSION}-${RELEASE_VERSION}\"\n    fi\n}\n\nbuildDate(){\n    # TODO restore https://reproducible-builds.org/docs/source-date-epoch/\n    DATE_FMT=\"+%Y-%m-%dT%H:%M:%SZ\"\n    if [ -z \"${SOURCE_DATE_EPOCH-}\" ]; then\n        echo $(date -u ${DATE_FMT})\n    else\n        echo$(date -u -d \"${SOURCE_DATE_EPOCH}\" \"${DATE_FMT}\" 2>/dev/null || date -u -r \"${SOURCE_DATE_EPOCH}\" \"$(DATE_FMT)\" 2>/dev/null || date -u \"$(DATE_FMT)\")\n    fi\n}\n\ncosignImages() {\n    COSIGN_EXPERIMENTAL=1 cosign sign \\\n        -a GIT_HASH=\"$(git rev-parse HEAD)\" \\\n        -a GIT_VERSION=\"${RELEASE_VERSION}\" \\\n        -a BUILD_DATE=\"$(buildDate)\" \\\n        \"${CONTROLLER_IMG}\"\n}\n\npullPrivateReplica(){\n  authenticatePrivateRepo\n  RELEASE_IDENTIFIER=$1\n  PULL_THROUGH_CACHE_PATH=\"${PRIVATE_PULL_THROUGH_HOST}/ecr-public/${ECR_GALLERY_NAME}/\"\n  HELM_CHART_VERSION=$(helmChartVersion \"$RELEASE_VERSION\")\n  docker pull \"${PULL_THROUGH_CACHE_PATH}controller:${RELEASE_IDENTIFIER}\"\n  helm pull \"oci://${PULL_THROUGH_CACHE_PATH}karpenter\" --version \"${HELM_CHART_VERSION}\"\n  helm pull \"oci://${PULL_THROUGH_CACHE_PATH}karpenter-crd\" --version \"${HELM_CHART_VERSION}\"\n}\n\npublishHelmChart() {\n    CHART_NAME=$1\n    RELEASE_VERSION=$2\n    RELEASE_REPO=$3\n    HELM_CHART_VERSION=$(helmChartVersion $RELEASE_VERSION)\n    HELM_CHART_FILE_NAME=\"${CHART_NAME}-${HELM_CHART_VERSION}.tgz\"\n\n    cd charts\n    helm dependency update \"${CHART_NAME}\"\n    helm lint \"${CHART_NAME}\"\n    helm package \"${CHART_NAME}\" --version $HELM_CHART_VERSION\n    helm push \"${HELM_CHART_FILE_NAME}\" \"oci://${RELEASE_REPO}\"\n    rm \"${HELM_CHART_FILE_NAME}\"\n    cd ..\n}\n\ncreateNewWebsiteDirectory() {\n    RELEASE_VERSION=$1\n    versionData \"${RELEASE_VERSION}\"\n    \n    mkdir -p \"website/content/en/${RELEASE_MINOR_VERSION}\"\n    cp -r website/content/en/preview/* website/content/en/${RELEASE_MINOR_VERSION}/\n    find \"website/content/en/${RELEASE_MINOR_VERSION}/\" -type f | xargs perl -i -p -e \"s/{{< param \\\"latest_release_version\\\" >}}/${RELEASE_VERSION}/g;\"\n    find website/content/en/${RELEASE_MINOR_VERSION}/*/*/*.yaml -type f | xargs perl -i -p -e \"s/preview/${RELEASE_VERSION}/g;\"\n    find \"website/content/en/${RELEASE_MINOR_VERSION}/\" -type f | xargs perl -i -p -e \"s/{{< githubRelRef >}}/\\/${RELEASE_VERSION}\\//g;\"\n\n    rm -rf website/content/en/docs\n    mkdir -p website/content/en/docs\n    cp -r website/content/en/${RELEASE_MINOR_VERSION}/* website/content/en/docs/\n}\n\nremoveOldWebsiteDirectories() {\n  local n=5\n  # Get all the directories except the last n directories sorted from earliest to latest version\n  last_n_versions=$(find website/content/en/* -type d -name \"*\" -maxdepth 0 | grep -v \"preview\\|docs\" | sort | tail -n \"$n\")\n  last_n_versions+=$(echo -e \"\\nwebsite/content/en/preview\")\n  last_n_versions+=$(echo -e \"\\nwebsite/content/en/docs\")\n  all=$(find website/content/en/* -type d -name \"*\" -maxdepth 0)\n  ## symmetric difference\n  comm -3 <(sort <<< $last_n_versions) <(sort <<< $all) | tr -d '\\t' | xargs -r -n 1 rm -r\n}\n\neditWebsiteConfig() {\n  RELEASE_VERSION=$1\n  yq -i \".params.latest_release_version = \\\"${RELEASE_VERSION}\\\"\" website/config.yaml\n}\n\n# editWebsiteVersionsMenu sets relevant releases in the version dropdown menu of the website\n# without increasing the size of the set.\n# TODO: We need to maintain a list of latest minors here only. This is not currently\n# easy to achieve, however when we have a major release and we decide to maintain\n# a selected minor releases we can maintain that list in the repo and use it in here\neditWebsiteVersionsMenu() {\n  RELEASE_VERSION=$1\n  versionData \"${RELEASE_VERSION}\"\n  VERSIONS=(${RELEASE_MINOR_VERSION})\n  while IFS= read -r LINE; do\n    SANITIZED_VERSION=$(echo \"${LINE}\" | sed -e 's/[\"-]//g' -e 's/ *//g')\n    VERSIONS+=(\"${SANITIZED_VERSION}\")\n  done < <(yq '.params.versions' website/config.yaml)\n  unset VERSIONS[${#VERSIONS[@]}-2]\n\n  yq -i '.params.versions = []' website/config.yaml\n\n  for VERSION in \"${VERSIONS[@]}\"; do\n    yq -i \".params.versions += \\\"${VERSION}\\\"\" website/config.yaml\n  done\n}\n", "num_lines": 193}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nsource \"${SCRIPT_DIR}/common.sh\"\n\nconfig\n\nGIT_TAG=${GIT_TAG:-$(git describe --exact-match --tags || echo \"none\")}\nif [[ $(releaseType \"$GIT_TAG\") != $RELEASE_TYPE_STABLE ]]; then\n  echo \"Not a stable release. Missing required git tag.\"\n  exit 1\nfi\necho \"RenderingPrep website files for ${GIT_TAG}\"\n\ncreateNewWebsiteDirectory \"$GIT_TAG\"\nremoveOldWebsiteDirectories\neditWebsiteConfig \"$GIT_TAG\"\neditWebsiteVersionsMenu \"$GIT_TAG\"\n", "num_lines": 20}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nHEAD_HASH=$(git rev-parse HEAD)\nGIT_TAG=$(git describe --exact-match --tags || echo \"no tag\")\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nsource \"${SCRIPT_DIR}/common.sh\"\n\nconfig\npublishHelmChart \"karpenter-crd\" \"${HEAD_HASH}\" \"${RELEASE_REPO_GH}\"\n\nif [[ $(releaseType $GIT_TAG) == $RELEASE_TYPE_STABLE ]]; then\n  publishHelmChart \"karpenter-crd\" \"${GIT_TAG}\" \"${RELEASE_REPO_GH}\"\nfi\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nGIT_TAG=$(git describe --exact-match --tags || echo \"no tag\")\nHEAD_HASH=$(git rev-parse HEAD)\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nsource \"${SCRIPT_DIR}/common.sh\"\n\nconfig\nrelease $HEAD_HASH #release a snapshot version\n## Reset changes if it's a snapshot since we don't need to track these changes\n## and results in a -dirty commit hash for a stable release\ngit reset --hard\n\nif [[ $(releaseType $GIT_TAG) == $RELEASE_TYPE_STABLE ]]; then\n  release $GIT_TAG\nfi\n\n", "num_lines": 20}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\n# updateKarpenterCoreGoMod bumps the karpenter-core go.mod to the release version so that the\n# karpenter and karpenter-core release versions match\nupdateKarpenterCoreGoMod(){\n  RELEASE_VERSION=$1\n  if [[ $GITHUB_ACCOUNT != $MAIN_GITHUB_ACCOUNT ]]; then\n    echo \"not updating go mod for a repo other than the main repo\"\n    return\n  fi\n  go get -u \"github.com/aws/karpenter-core@${RELEASE_VERSION}\"\n  cd test\n  go get -u \"github.com/aws/karpenter-core@${RELEASE_VERSION}\"\n  cd ..\n  make tidy\n}\n\n# updateTektonPreUpgradeVersion updates the version that we use for the pre-upgrade E2E test suite\n# so that we are constantly testing against the last minor version of Karpenter\nupdateTektonPreUpgradeVersion(){\n  LAST_MINOR_VERSION=$(git tag --sort=committerdate | grep -v \"v${RELEASE_VERSION_MAJOR}.${RELEASE_VERSION_MINOR}\" | tail -1)\n  TEKTON_RELEASE_LISTENER_PATH=\"tools/release-notification-listener/listener/tekton.go\"\n  GITHUB_ACTION_E2E_MATRIX_PATH=\".github/workflows/e2e-matrix.yaml\"\n\n  # This command goes into the tekton release-listener file and replaces the preUpgradeVersion with the last minor version\n  sed -i \"s/preUpgradeVersion = \\\".*\\\"/preUpgradeVersion = \\\"$LAST_MINOR_VERSION\\\"/\" \"$TEKTON_RELEASE_LISTENER_PATH\"\n  sed -i \"s/from_git_ref:.*/from_git_ref: $LAST_MINOR_VERSION/\" \"$GITHUB_ACTION_E2E_MATRIX_PATH\"\n}\n\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\nsource \"${SCRIPT_DIR}/common.sh\"\n\nconfig\n\nGIT_TAG=$(git describe --exact-match --tags || echo \"none\")\nif [[ $(releaseType $GIT_TAG) != $RELEASE_TYPE_STABLE ]]; then\n  echo \"Not a stable release. Missing required git tag.\"\n  exit 1\nfi\n\nversionData \"$GIT_TAG\"\nupdateKarpenterCoreGoMod \"$GIT_TAG\"\nupdateTektonPreUpgradeVersion\n\ngit config user.name \"StableRelease\"\ngit config user.email \"StableRelease@users.noreply.github.com\"\ngit remote set-url origin https://x-access-token:${GITHUB_TOKEN}@github.com/${GITHUB_REPO}\ngit config pull.rebase false\n\nBRANCH_NAME=\"release-${GIT_TAG}\"\ngit checkout -b \"${BRANCH_NAME}\"\ngit add go.mod\ngit add go.sum\ngit add test/go.mod\ngit add test/go.sum\ngit add website\ngit add charts/karpenter-crd/Chart.yaml\ngit add charts/karpenter/Chart.yaml\ngit add charts/karpenter/Chart.lock\ngit add charts/karpenter/values.yaml\ngit add charts/karpenter/README.md\ngit commit -m \"Stable Release updates Release ${GIT_TAG}.\"\ngit push --set-upstream origin \"${BRANCH_NAME}\"", "num_lines": 64}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\naws ecr-public get-login-password --region us-east-1 | docker login --username AWS --password-stdin public.ecr.aws\ndocker build . --progress plain -t public.ecr.aws/karpenter/tools:latest\ndocker push public.ecr.aws/karpenter/tools:latest\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Running custom user data script\"\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"BOUNDARY\"\n\n--BOUNDARY\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\n\n#!/bin/bash\necho \"Running custom user data script\"\n\n--BOUNDARY--\n", "num_lines": 11}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"BOUNDARY\"\n\n--BOUNDARY\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\n\n#!/bin/bash\ncd\nsudo amazon-linux-extras install epel -y\nsudo yum update -y\n\n# Create a script to install the AMD Radeon GPU\ncat << EOF > /tmp/amd-install.sh\n#!/bin/bash\nexport echo PATH=/usr/local/bin:$PATH\naws s3 cp --recursive s3://ec2-amd-linux-drivers/latest/ . --no-sign-request\ntar -xf amdgpu-pro-*rhel*.tar.xz\ncd amdgpu-pro-20.20-1184451-rhel-7.8\n./amdgpu-pro-install -y --opencl=pal,legacy\nsystemctl disable amd-install.service\nreboot\nEOF\nsudo chmod +x /tmp/amd-install.sh\n\n# Create a service that will run on system reboot\ncat << EOF > /etc/systemd/system/amd-install.service\n[Unit]\nDescription=install amd drivers\n\n[Service]\nExecStart=/bin/bash /tmp/amd-install.sh\n\n[Install]\nWantedBy=multi-user.target\nEOF\nsudo systemctl enable amd-install.service\n\n# Run the EKS bootstrap script and then reboot\nexec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1\n/etc/eks/bootstrap.sh '%s' --apiserver-endpoint '%s' --b64-cluster-ca '%s' \\\n--use-max-pods false \\\n--container-runtime containerd \\\n--kubelet-extra-args '--node-labels=karpenter.sh/provisioner-name=%s,testing.karpenter.sh/test-id=unspecified'\n\nreboot\n--BOUNDARY-- ", "num_lines": 46}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "[settings.kubernetes]\nkube-api-qps = 30\n[settings.kubernetes.node-taints]\n\"node.cilium.io/agent-not-ready\" = [\"true:NoExecute\"]\n", "num_lines": 5}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"BOUNDARY\"\n\n--BOUNDARY\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\n\n#!/bin/bash\nexec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1\n/etc/eks/bootstrap.sh '%s' --apiserver-endpoint '%s' --b64-cluster-ca '%s' \\\n--use-max-pods false \\\n--container-runtime containerd \\\n--kubelet-extra-args '--node-labels=testing.karpenter.sh/test-id=unspecified,custom-label=custom-value,custom-label2=custom-value2'\n\n--BOUNDARY--\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "MIME-Version: 1.0\nContent-Type: multipart/mixed; boundary=\"BOUNDARY\"\n\n--BOUNDARY\nContent-Type: text/x-shellscript; charset=\"us-ascii\"\n\n#!/bin/bash\nexec > >(tee /var/log/user-data.log|logger -t user-data -s 2>/dev/console) 2>&1\n/etc/eks/bootstrap.sh '%s' --apiserver-endpoint '%s' --b64-cluster-ca '%s' \\\n--use-max-pods false \\\n--container-runtime containerd \\\n--kubelet-extra-args '--node-labels=karpenter.sh/provisioner-name=%s,testing.karpenter.sh/test-id=unspecified'\n\n--BOUNDARY--\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: add-monitoring.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step09-add-prometheus-grafana.sh\n  step10-add-grafana-port-forward.sh\n  step11-grafana-get-password.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\ndeclare -a steps=(\n  step01-config.sh\n  step12-add-provisioner.sh\n  step13-automatic-node-provisioning.sh\n  step14-automatic-node-termination.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: setup-roles.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\ndeclare -a steps=(\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source \"$SCRIPT_DIR/$step\"\ndone\n", "num_lines": 24}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndeclare -a steps=(\n  step01-config.sh\n  step16-cleanup.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: install.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step02-create-cluster.sh\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n  step08-apply-helm-chart.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "export AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nexport CLUSTER_NAME=\"${USER}-karpenter-demo\"\nexport AWS_DEFAULT_REGION=\"us-west-2\"\nexport AWS_ACCOUNT_ID=\"$(aws sts get-caller-identity --query Account --output text)\"\nexport TEMPOUT=$(mktemp)\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create cluster -f - << EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nfargateProfiles:\n  - name: karpenter\n    selectors:\n    - namespace: karpenter\niam:\n  withOIDC: true\nEOF\n", "num_lines": 18}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "curl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n\neksctl create cluster -f - <<EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n\niam:\n  withOIDC: true\n  serviceAccounts:\n  - metadata:\n      name: karpenter\n      namespace: karpenter\n    roleName: ${CLUSTER_NAME}-karpenter\n    attachPolicyARNs:\n    - arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\n    roleOnly: true\n\niamIdentityMappings:\n- arn: \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\"\n  username: system:node:{{EC2PrivateDNSName}}\n  groups:\n  - system:bootstrappers\n  - system:nodes\n\nmanagedNodeGroups:\n- instanceType: m5.large\n  amiFamily: AmazonLinux2\n  name: ${CLUSTER_NAME}-ng\n  desiredCapacity: 2\n  minSize: 1\n  maxSize: 10\n\n## Optionally run on fargate\n# fargateProfiles:\n# - name: karpenter\n#  selectors:\n#  - namespace: karpenter\nEOF\n\nexport CLUSTER_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} --query \"cluster.endpoint\" --output text)\"\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n\necho $CLUSTER_ENDPOINT $KARPENTER_IAM_ROLE_ARN\n", "num_lines": 56}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "TEMPOUT=$(mktemp)\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamidentitymapping \\\n  --username system:node:{{EC2PrivateDNSName}} \\\n  --cluster \"${CLUSTER_NAME}\" \\\n  --arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\" \\\n  --group system:bootstrappers \\\n  --group system:nodes\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamserviceaccount \\\n  --cluster \"${CLUSTER_NAME}\" --name karpenter --namespace karpenter \\\n  --role-name \"${CLUSTER_NAME}-karpenter\" \\\n  --attach-policy-arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\" \\\n  --role-only \\\n  --approve\n\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "# Logout of helm registry to perform an unauthenticated pull against the public ECR\nhelm registry logout public.ecr.aws\n\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --set controller.resources.requests.cpu=1 \\\n  --set controller.resources.requests.memory=1Gi \\\n  --set controller.resources.limits.cpu=1 \\\n  --set controller.resources.limits.memory=1Gi \\\n  --wait\n", "num_lines": 14}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm repo add grafana-charts https://grafana.github.io/helm-charts\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\n\nkubectl create namespace monitoring\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/prometheus-values.yaml | tee prometheus-values.yaml\nhelm install --namespace monitoring prometheus prometheus-community/prometheus --values prometheus-values.yaml\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/grafana-values.yaml | tee grafana-values.yaml\nhelm install --namespace monitoring grafana grafana-charts/grafana --values grafana-values.yaml\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl port-forward --namespace monitoring svc/grafana 3000:80\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl get secret --namespace monitoring grafana -o jsonpath=\"{.data.admin-password}\" | base64 --decode\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.sh/capacity-type\n      operator: In\n      values: [\"spot\"]\n  limits:\n    resources:\n      cpu: 1000\n  providerRef:\n    name: default\n  consolidation: \n    enabled: true\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n  securityGroupSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nEOF\n", "num_lines": 29}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inflate\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: inflate\n  template:\n    metadata:\n      labels:\n        app: inflate\n    spec:\n      terminationGracePeriodSeconds: 0\n      containers:\n        - name: inflate\n          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7\n          resources:\n            requests:\n              cpu: 1\nEOF\nkubectl scale deployment inflate --replicas 5\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete deployment inflate\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete node $NODE_NAME\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm uninstall karpenter --namespace karpenter\naws cloudformation delete-stack --stack-name \"Karpenter-${CLUSTER_NAME}\"\naws ec2 describe-launch-templates --filters Name=tag:karpenter.k8s.aws/cluster,Values=${CLUSTER_NAME} |\n    jq -r \".LaunchTemplates[].LaunchTemplateName\" |\n    xargs -I{} aws ec2 delete-launch-template --launch-template-name {}\neksctl delete cluster --name \"${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nAWS_REGION=\"$(aws configure list | grep region | tr -s \" \" | cut -d\" \" -f3)\"\nOIDC_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} \\\n    --query \"cluster.identity.oidc.issuer\" --output text)\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' \\\n    --output text)\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "echo '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"ec2.amazonaws.com\"\n            },\n            \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}' > node-trust-policy.json\n\naws iam create-role --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --assume-role-policy-document file://node-trust-policy.json\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKSWorkerNodePolicy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKS_CNI_Policy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonSSMManagedInstanceCore\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\"\n\naws iam add-role-to-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\" \\\n    --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat << EOF > controller-trust-policy.json\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Federated\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_ENDPOINT#*//}\"\n            },\n            \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n            \"Condition\": {\n                \"StringEquals\": {\n                    \"${OIDC_ENDPOINT#*//}:aud\": \"sts.amazonaws.com\",\n                    \"${OIDC_ENDPOINT#*//}:sub\": \"system:serviceaccount:karpenter:karpenter\"\n                }\n            }\n        }\n    ]\n}\nEOF\n\naws iam create-role --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --assume-role-policy-document file://controller-trust-policy.json\n\ncat << EOF > controller-policy.json\n{\n    \"Statement\": [\n        {\n            \"Action\": [\n                \"ssm:GetParameter\",\n                \"ec2:DescribeImages\",\n                \"ec2:RunInstances\",\n                \"ec2:DescribeSubnets\",\n                \"ec2:DescribeSecurityGroups\",\n                \"ec2:DescribeLaunchTemplates\",\n                \"ec2:DescribeInstances\",\n                \"ec2:DescribeInstanceTypes\",\n                \"ec2:DescribeInstanceTypeOfferings\",\n                \"ec2:DescribeAvailabilityZones\",\n                \"ec2:DeleteLaunchTemplate\",\n                \"ec2:CreateTags\",\n                \"ec2:CreateLaunchTemplate\",\n                \"ec2:CreateFleet\",\n                \"ec2:DescribeSpotPriceHistory\",\n                \"pricing:GetProducts\"\n            ],\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"Karpenter\"\n        },\n        {\n            \"Action\": \"ec2:TerminateInstances\",\n            \"Condition\": {\n                \"StringLike\": {\n                    \"ec2:ResourceTag/karpenter.sh/provisioner-name\": \"*\"\n                }\n            },\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"ConditionalEC2Termination\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"iam:PassRole\",\n            \"Resource\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\",\n            \"Sid\": \"PassNodeIAMRole\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"eks:DescribeCluster\",\n            \"Resource\": \"arn:${AWS_PARTITION}:eks:${AWS_REGION}:${AWS_ACCOUNT_ID}:cluster/${CLUSTER_NAME}\",\n            \"Sid\": \"EKSClusterEndpointLookup\"\n        }\n    ],\n    \"Version\": \"2012-10-17\"\n}\nEOF\n\naws iam put-role-policy --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --policy-name KarpenterControllerPolicy-${CLUSTER_NAME} \\\n    --policy-document file://controller-policy.json\n", "num_lines": 82}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws ec2 create-tags \\\n        --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n        --resources $(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n        --nodegroup-name $NODEGROUP --query 'nodegroup.subnets' --output text )\ndone\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "NODEGROUP=$(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups[0]' --output text)\n\nLAUNCH_TEMPLATE=$(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} --query 'nodegroup.launchTemplate.{id:id,version:version}' \\\n    --output text | tr -s \"\\t\" \",\")\n\n# If your EKS setup is configured to use only Cluster security group, then please execute -\n\nSECURITY_GROUPS=$(aws eks describe-cluster \\\n    --name ${CLUSTER_NAME} --query \"cluster.resourcesVpcConfig.clusterSecurityGroupId\" --output text)\n\n# If your setup uses the security groups in the Launch template of a managed node group, then :\n\nSECURITY_GROUPS=$(aws ec2 describe-launch-template-versions \\\n    --launch-template-id ${LAUNCH_TEMPLATE%,*} --versions ${LAUNCH_TEMPLATE#*,} \\\n    --query 'LaunchTemplateVersions[0].LaunchTemplateData.[NetworkInterfaces[0].Groups||SecurityGroupIds]' \\\n    --output text)\n\naws ec2 create-tags \\\n    --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n    --resources ${SECURITY_GROUPS}\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl edit configmap aws-auth -n kube-system\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm template karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter \\\n    --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n    --set settings.aws.clusterName=${CLUSTER_NAME} \\\n    --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterControllerRole-${CLUSTER_NAME}\" \\\n    --set controller.resources.requests.cpu=1 \\\n    --set controller.resources.requests.memory=1Gi \\\n    --set controller.resources.limits.cpu=1 \\\n    --set controller.resources.limits.memory=1Gi > karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl create namespace karpenter\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_provisioners.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.k8s.aws_awsnodetemplates.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_machines.yaml\nkubectl apply -f karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.k8s.aws/instance-category\n      operator: In\n      values: [c, m, r]\n    - key: karpenter.k8s.aws/instance-generation\n      operator: Gt\n      values: [\"2\"]\n  providerRef:\n    name: default\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\n  securityGroupSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\nEOF\n", "num_lines": 27}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl scale deploy/cluster-autoscaler -n kube-system --replicas=0\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=1,maxSize=1,desiredSize=1\"\ndone\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=2,maxSize=2,desiredSize=2\"\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: add-monitoring.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step09-add-prometheus-grafana.sh\n  step10-add-grafana-port-forward.sh\n  step11-grafana-get-password.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\ndeclare -a steps=(\n  step01-config.sh\n  step12-add-provisioner.sh\n  step13-automatic-node-provisioning.sh\n  step14-automatic-node-termination.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: setup-roles.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\ndeclare -a steps=(\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source \"$SCRIPT_DIR/$step\"\ndone\n", "num_lines": 24}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndeclare -a steps=(\n  step01-config.sh\n  step16-cleanup.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: install.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step02-create-cluster.sh\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n  step08-apply-helm-chart.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "export AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nexport CLUSTER_NAME=\"${USER}-karpenter-demo\"\nexport AWS_DEFAULT_REGION=\"us-west-2\"\nexport AWS_ACCOUNT_ID=\"$(aws sts get-caller-identity --query Account --output text)\"\nexport TEMPOUT=$(mktemp)\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create cluster -f - << EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nfargateProfiles:\n  - name: karpenter\n    selectors:\n    - namespace: karpenter\niam:\n  withOIDC: true\nEOF\n", "num_lines": 18}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "curl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n\neksctl create cluster -f - <<EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n\niam:\n  withOIDC: true\n  serviceAccounts:\n  - metadata:\n      name: karpenter\n      namespace: karpenter\n    roleName: ${CLUSTER_NAME}-karpenter\n    attachPolicyARNs:\n    - arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\n    roleOnly: true\n\niamIdentityMappings:\n- arn: \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\"\n  username: system:node:{{EC2PrivateDNSName}}\n  groups:\n  - system:bootstrappers\n  - system:nodes\n\nmanagedNodeGroups:\n- instanceType: m5.large\n  amiFamily: AmazonLinux2\n  name: ${CLUSTER_NAME}-ng\n  desiredCapacity: 2\n  minSize: 1\n  maxSize: 10\n\n## Optionally run on fargate\n# fargateProfiles:\n# - name: karpenter\n#  selectors:\n#  - namespace: karpenter\nEOF\n\nexport CLUSTER_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} --query \"cluster.endpoint\" --output text)\"\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n\necho $CLUSTER_ENDPOINT $KARPENTER_IAM_ROLE_ARN\n", "num_lines": 56}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "TEMPOUT=$(mktemp)\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamidentitymapping \\\n  --username system:node:{{EC2PrivateDNSName}} \\\n  --cluster \"${CLUSTER_NAME}\" \\\n  --arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\" \\\n  --group system:bootstrappers \\\n  --group system:nodes\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamserviceaccount \\\n  --cluster \"${CLUSTER_NAME}\" --name karpenter --namespace karpenter \\\n  --role-name \"${CLUSTER_NAME}-karpenter\" \\\n  --attach-policy-arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\" \\\n  --role-only \\\n  --approve\n\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "# Logout of helm registry to perform an unauthenticated pull against the public ECR\nhelm registry logout public.ecr.aws\n\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --set controller.resources.requests.cpu=1 \\\n  --set controller.resources.requests.memory=1Gi \\\n  --set controller.resources.limits.cpu=1 \\\n  --set controller.resources.limits.memory=1Gi \\\n  --wait\n", "num_lines": 14}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm repo add grafana-charts https://grafana.github.io/helm-charts\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\n\nkubectl create namespace monitoring\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/prometheus-values.yaml | tee prometheus-values.yaml\nhelm install --namespace monitoring prometheus prometheus-community/prometheus --values prometheus-values.yaml\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/grafana-values.yaml | tee grafana-values.yaml\nhelm install --namespace monitoring grafana grafana-charts/grafana --values grafana-values.yaml\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl port-forward --namespace monitoring svc/grafana 3000:80\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl get secret --namespace monitoring grafana -o jsonpath=\"{.data.admin-password}\" | base64 --decode\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.sh/capacity-type\n      operator: In\n      values: [\"spot\"]\n  limits:\n    resources:\n      cpu: 1000\n  providerRef:\n    name: default\n  consolidation: \n    enabled: true\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n  securityGroupSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nEOF\n", "num_lines": 29}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inflate\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: inflate\n  template:\n    metadata:\n      labels:\n        app: inflate\n    spec:\n      terminationGracePeriodSeconds: 0\n      containers:\n        - name: inflate\n          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7\n          resources:\n            requests:\n              cpu: 1\nEOF\nkubectl scale deployment inflate --replicas 5\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete deployment inflate\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete node $NODE_NAME\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm uninstall karpenter --namespace karpenter\naws cloudformation delete-stack --stack-name \"Karpenter-${CLUSTER_NAME}\"\naws ec2 describe-launch-templates --filters Name=tag:karpenter.k8s.aws/cluster,Values=${CLUSTER_NAME} |\n    jq -r \".LaunchTemplates[].LaunchTemplateName\" |\n    xargs -I{} aws ec2 delete-launch-template --launch-template-name {}\neksctl delete cluster --name \"${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nAWS_REGION=\"$(aws configure list | grep region | tr -s \" \" | cut -d\" \" -f3)\"\nOIDC_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} \\\n    --query \"cluster.identity.oidc.issuer\" --output text)\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' \\\n    --output text)\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "echo '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"ec2.amazonaws.com\"\n            },\n            \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}' > node-trust-policy.json\n\naws iam create-role --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --assume-role-policy-document file://node-trust-policy.json\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKSWorkerNodePolicy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKS_CNI_Policy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonSSMManagedInstanceCore\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\"\n\naws iam add-role-to-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\" \\\n    --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat << EOF > controller-trust-policy.json\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Federated\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_ENDPOINT#*//}\"\n            },\n            \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n            \"Condition\": {\n                \"StringEquals\": {\n                    \"${OIDC_ENDPOINT#*//}:aud\": \"sts.amazonaws.com\",\n                    \"${OIDC_ENDPOINT#*//}:sub\": \"system:serviceaccount:karpenter:karpenter\"\n                }\n            }\n        }\n    ]\n}\nEOF\n\naws iam create-role --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --assume-role-policy-document file://controller-trust-policy.json\n\ncat << EOF > controller-policy.json\n{\n    \"Statement\": [\n        {\n            \"Action\": [\n                \"ssm:GetParameter\",\n                \"ec2:DescribeImages\",\n                \"ec2:RunInstances\",\n                \"ec2:DescribeSubnets\",\n                \"ec2:DescribeSecurityGroups\",\n                \"ec2:DescribeLaunchTemplates\",\n                \"ec2:DescribeInstances\",\n                \"ec2:DescribeInstanceTypes\",\n                \"ec2:DescribeInstanceTypeOfferings\",\n                \"ec2:DescribeAvailabilityZones\",\n                \"ec2:DeleteLaunchTemplate\",\n                \"ec2:CreateTags\",\n                \"ec2:CreateLaunchTemplate\",\n                \"ec2:CreateFleet\",\n                \"ec2:DescribeSpotPriceHistory\",\n                \"pricing:GetProducts\"\n            ],\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"Karpenter\"\n        },\n        {\n            \"Action\": \"ec2:TerminateInstances\",\n            \"Condition\": {\n                \"StringLike\": {\n                    \"ec2:ResourceTag/karpenter.sh/provisioner-name\": \"*\"\n                }\n            },\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"ConditionalEC2Termination\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"iam:PassRole\",\n            \"Resource\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\",\n            \"Sid\": \"PassNodeIAMRole\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"eks:DescribeCluster\",\n            \"Resource\": \"arn:${AWS_PARTITION}:eks:${AWS_REGION}:${AWS_ACCOUNT_ID}:cluster/${CLUSTER_NAME}\",\n            \"Sid\": \"EKSClusterEndpointLookup\"\n        }\n    ],\n    \"Version\": \"2012-10-17\"\n}\nEOF\n\naws iam put-role-policy --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --policy-name KarpenterControllerPolicy-${CLUSTER_NAME} \\\n    --policy-document file://controller-policy.json\n", "num_lines": 82}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws ec2 create-tags \\\n        --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n        --resources $(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n        --nodegroup-name $NODEGROUP --query 'nodegroup.subnets' --output text )\ndone\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "NODEGROUP=$(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups[0]' --output text)\n\nLAUNCH_TEMPLATE=$(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} --query 'nodegroup.launchTemplate.{id:id,version:version}' \\\n    --output text | tr -s \"\\t\" \",\")\n\n# If your EKS setup is configured to use only Cluster security group, then please execute -\n\nSECURITY_GROUPS=$(aws eks describe-cluster \\\n    --name ${CLUSTER_NAME} --query \"cluster.resourcesVpcConfig.clusterSecurityGroupId\" --output text)\n\n# If your setup uses the security groups in the Launch template of a managed node group, then :\n\nSECURITY_GROUPS=$(aws ec2 describe-launch-template-versions \\\n    --launch-template-id ${LAUNCH_TEMPLATE%,*} --versions ${LAUNCH_TEMPLATE#*,} \\\n    --query 'LaunchTemplateVersions[0].LaunchTemplateData.[NetworkInterfaces[0].Groups||SecurityGroupIds]' \\\n    --output text)\n\naws ec2 create-tags \\\n    --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n    --resources ${SECURITY_GROUPS}\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl edit configmap aws-auth -n kube-system\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm template karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter \\\n    --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n    --set settings.aws.clusterName=${CLUSTER_NAME} \\\n    --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterControllerRole-${CLUSTER_NAME}\" \\\n    --set controller.resources.requests.cpu=1 \\\n    --set controller.resources.requests.memory=1Gi \\\n    --set controller.resources.limits.cpu=1 \\\n    --set controller.resources.limits.memory=1Gi > karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl create namespace karpenter\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_provisioners.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.k8s.aws_awsnodetemplates.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_machines.yaml\nkubectl apply -f karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.k8s.aws/instance-category\n      operator: In\n      values: [c, m, r]\n    - key: karpenter.k8s.aws/instance-generation\n      operator: Gt\n      values: [\"2\"]\n  providerRef:\n    name: default\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\n  securityGroupSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\nEOF\n", "num_lines": 27}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl scale deploy/cluster-autoscaler -n kube-system --replicas=0\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=1,maxSize=1,desiredSize=1\"\ndone\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=2,maxSize=2,desiredSize=2\"\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: add-monitoring.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step09-add-prometheus-grafana.sh\n  step10-add-grafana-port-forward.sh\n  step11-grafana-get-password.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\ndeclare -a steps=(\n  step01-config.sh\n  step12-add-provisioner.sh\n  step13-automatic-node-provisioning.sh\n  step14-automatic-node-termination.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: setup-roles.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\ndeclare -a steps=(\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source \"$SCRIPT_DIR/$step\"\ndone\n", "num_lines": 24}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndeclare -a steps=(\n  step01-config.sh\n  step16-cleanup.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: install.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step02-create-cluster.sh\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n  step08-apply-helm-chart.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "export CLUSTER_NAME=\"${USER}-karpenter-demo\"\nexport AWS_DEFAULT_REGION=\"us-west-2\"\nexport AWS_ACCOUNT_ID=\"$(aws sts get-caller-identity --query Account --output text)\"\nexport TEMPOUT=$(mktemp)\n", "num_lines": 5}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create cluster -f - << EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nfargateProfiles:\n  - name: karpenter\n    selectors:\n    - namespace: karpenter\niam:\n  withOIDC: true\nEOF\n", "num_lines": 18}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "curl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n\neksctl create cluster -f - <<EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n\niam:\n  withOIDC: true\n  serviceAccounts:\n  - metadata:\n      name: karpenter\n      namespace: karpenter\n    roleName: ${CLUSTER_NAME}-karpenter\n    attachPolicyARNs:\n    - arn:aws:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\n    roleOnly: true\n\niamIdentityMappings:\n- arn: \"arn:aws:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\"\n  username: system:node:{{EC2PrivateDNSName}}\n  groups:\n  - system:bootstrappers\n  - system:nodes\n\nmanagedNodeGroups:\n- instanceType: m5.large\n  amiFamily: AmazonLinux2\n  name: ${CLUSTER_NAME}-ng\n  desiredCapacity: 2\n  minSize: 1\n  maxSize: 10\n\n## Optionally run on fargate\n# fargateProfiles:\n# - name: karpenter\n#  selectors:\n#  - namespace: karpenter\nEOF\n\nexport CLUSTER_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} --query \"cluster.endpoint\" --output text)\"\nexport KARPENTER_IAM_ROLE_ARN=\"arn:aws:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n\necho $CLUSTER_ENDPOINT $KARPENTER_IAM_ROLE_ARN\n\naws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n\ndocker logout public.ecr.aws\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --wait\n", "num_lines": 68}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "TEMPOUT=$(mktemp)\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamidentitymapping \\\n  --username system:node:{{EC2PrivateDNSName}} \\\n  --cluster \"${CLUSTER_NAME}\" \\\n  --arn \"arn:aws:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\" \\\n  --group system:bootstrappers \\\n  --group system:nodes\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamserviceaccount \\\n  --cluster \"${CLUSTER_NAME}\" --name karpenter --namespace karpenter \\\n  --role-name \"${CLUSTER_NAME}-karpenter\" \\\n  --attach-policy-arn \"arn:aws:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\" \\\n  --role-only \\\n  --approve\n\nexport KARPENTER_IAM_ROLE_ARN=\"arn:aws:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "docker logout public.ecr.aws\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --set controller.resources.requests.cpu=1 \\\n  --set controller.resources.requests.memory=1Gi \\\n  --set controller.resources.limits.cpu=1 \\\n  --set controller.resources.limits.memory=1Gi \\\n  --wait\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm repo add grafana-charts https://grafana.github.io/helm-charts\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\n\nkubectl create namespace monitoring\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/prometheus-values.yaml | tee prometheus-values.yaml\nhelm install --namespace monitoring prometheus prometheus-community/prometheus --values prometheus-values.yaml\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/grafana-values.yaml | tee grafana-values.yaml\nhelm install --namespace monitoring grafana grafana-charts/grafana --values grafana-values.yaml\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl port-forward --namespace monitoring svc/grafana 3000:80\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl get secret --namespace monitoring grafana -o jsonpath=\"{.data.admin-password}\" | base64 --decode\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.sh/capacity-type\n      operator: In\n      values: [\"spot\"]\n  limits:\n    resources:\n      cpu: 1000\n  providerRef:\n    name: default\n  ttlSecondsAfterEmpty: 30\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n  securityGroupSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nEOF\n", "num_lines": 28}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inflate\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: inflate\n  template:\n    metadata:\n      labels:\n        app: inflate\n    spec:\n      terminationGracePeriodSeconds: 0\n      containers:\n        - name: inflate\n          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7\n          resources:\n            requests:\n              cpu: 1\nEOF\nkubectl scale deployment inflate --replicas 5\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete deployment inflate\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete node $NODE_NAME\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm uninstall karpenter --namespace karpenter\naws cloudformation delete-stack --stack-name \"Karpenter-${CLUSTER_NAME}\"\naws ec2 describe-launch-templates \\\n    | jq -r \".LaunchTemplates[].LaunchTemplateName\" \\\n    | grep -i \"Karpenter-${CLUSTER_NAME}\" \\\n    | xargs -I{} aws ec2 delete-launch-template --launch-template-name {}\neksctl delete cluster --name \"${CLUSTER_NAME}\"\n", "num_lines": 8}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nAWS_REGION=\"$(aws configure list | grep region | tr -s \" \" | cut -d\" \" -f3)\"\nOIDC_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} \\\n    --query \"cluster.identity.oidc.issuer\" --output text)\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' \\\n    --output text)\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "echo '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"ec2.amazonaws.com\"\n            },\n            \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}' > node-trust-policy.json\n\naws iam create-role --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --assume-role-policy-document file://node-trust-policy.json\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${ClusterName}\"\n\naws iam add-role-to-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${ClusterName}\" \\\n    --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat << EOF > controller-trust-policy.json\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Federated\": \"arn:aws:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_ENDPOINT#*//}\"\n            },\n            \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n            \"Condition\": {\n                \"StringEquals\": {\n                    \"${OIDC_ENDPOINT#*//}:aud\": \"sts.amazonaws.com\",\n                    \"${OIDC_ENDPOINT#*//}:sub\": \"system:serviceaccount:karpenter:karpenter\"\n                }\n            }\n        }\n    ]\n}\nEOF\n\naws iam create-role --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --assume-role-policy-document file://controller-trust-policy.json\n\ncat << EOF > controller-policy.json\n{\n    \"Statement\": [\n        {\n            \"Action\": [\n                \"ssm:GetParameter\",\n                \"ec2:DescribeImages\",\n                \"ec2:RunInstances\",\n                \"ec2:DescribeSubnets\",\n                \"ec2:DescribeSecurityGroups\",\n                \"ec2:DescribeLaunchTemplates\",\n                \"ec2:DescribeInstances\",\n                \"ec2:DescribeInstanceTypes\",\n                \"ec2:DescribeInstanceTypeOfferings\",\n                \"ec2:DescribeAvailabilityZones\",\n                \"ec2:DeleteLaunchTemplate\",\n                \"ec2:CreateTags\",\n                \"ec2:CreateLaunchTemplate\",\n                \"ec2:CreateFleet\",\n                \"ec2:DescribeSpotPriceHistory\",\n                \"pricing:GetProducts\"\n            ],\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"Karpenter\"\n        },\n        {\n            \"Action\": \"ec2:TerminateInstances\",\n            \"Condition\": {\n                \"StringLike\": {\n                    \"ec2:ResourceTag/Name\": \"*karpenter*\"\n                }\n            },\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"ConditionalEC2Termination\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"iam:PassRole\",\n            \"Resource\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\",\n            \"Sid\": \"PassNodeIAMRole\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"eks:DescribeCluster\",\n            \"Resource\": \"arn:${AWS_PARTITION}:eks:${AWS_REGION}:${AWS_ACCOUNT_ID}:cluster/${CLUSTER_NAME}\",\n            \"Sid\": \"EKSClusterEndpointLookup\"\n        }\n    ],\n    \"Version\": \"2012-10-17\"\n}\nEOF\n\naws iam put-role-policy --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --policy-name KarpenterControllerPolicy-${CLUSTER_NAME} \\\n    --policy-document file://controller-policy.json\n", "num_lines": 82}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws ec2 create-tags \\\n        --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n        --resources $(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n        --nodegroup-name $NODEGROUP --query 'nodegroup.subnets' --output text )\ndone\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "NODEGROUP=$(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups[0]' --output text)\n\nLAUNCH_TEMPLATE=$(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} --query 'nodegroup.launchTemplate.{id:id,version:version}' \\\n    --output text | tr -s \"\\t\" \",\")\n\n# If your EKS setup is configured to use only Cluster security group, then please execute -\n\nSECURITY_GROUPS=$(aws eks describe-cluster \\\n    --name ${CLUSTER_NAME} --query \"cluster.resourcesVpcConfig.clusterSecurityGroupId\" --output text)\n\n# If your setup uses the security groups in the Launch template of a managed node group, then :\n\nSECURITY_GROUPS=$(aws ec2 describe-launch-template-versions \\\n    --launch-template-id ${LAUNCH_TEMPLATE%,*} --versions ${LAUNCH_TEMPLATE#*,} \\\n    --query 'LaunchTemplateVersions[0].LaunchTemplateData.[NetworkInterfaces[0].Groups||SecurityGroupIds]' \\\n    --output text)\n\naws ec2 create-tags \\\n    --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n    --resources ${SECURITY_GROUPS}\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl edit configmap aws-auth -n kube-system\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm template karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter \\\n    --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${ClusterName} \\\n    --set settings.aws.clusterName=${CLUSTER_NAME} \\\n    --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterControllerRole-${CLUSTER_NAME}\" \\\n    --set controller.resources.requests.cpu=1 \\\n    --set controller.resources.requests.memory=1Gi \\\n    --set controller.resources.limits.cpu=1 \\\n    --set controller.resources.limits.memory=1Gi > karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl create namespace karpenter\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_provisioners.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.k8s.aws_awsnodetemplates.yaml\nkubectl apply -f karpenter.yaml\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.k8s.aws/instance-category\n      operator: In\n      values: [c, m, r]\n    - key: karpenter.k8s.aws/instance-generation\n      operator: Gt\n      values: [\"2\"]\n  providerRef:\n    name: default\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\n  securityGroupSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\nEOF\n", "num_lines": 27}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl scale deploy/cluster-autoscaler -n kube-system --replicas=0\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=1,maxSize=1,desiredSize=1\"\ndone\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=2,maxSize=2,desiredSize=2\"\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: add-monitoring.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step09-add-prometheus-grafana.sh\n  step10-add-grafana-port-forward.sh\n  step11-grafana-get-password.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\ndeclare -a steps=(\n  step01-config.sh\n  step12-add-provisioner.sh\n  step13-automatic-node-provisioning.sh\n  step14-automatic-node-termination.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: setup-roles.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\ndeclare -a steps=(\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source \"$SCRIPT_DIR/$step\"\ndone\n", "num_lines": 24}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndeclare -a steps=(\n  step01-config.sh\n  step16-cleanup.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: install.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step02-create-cluster.sh\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n  step08-apply-helm-chart.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "export CLUSTER_NAME=\"${USER}-karpenter-demo\"\nexport AWS_DEFAULT_REGION=\"us-west-2\"\nexport AWS_ACCOUNT_ID=\"$(aws sts get-caller-identity --query Account --output text)\"\nexport TEMPOUT=$(mktemp)\n", "num_lines": 5}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create cluster -f - << EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nfargateProfiles:\n  - name: karpenter\n    selectors:\n    - namespace: karpenter\niam:\n  withOIDC: true\nEOF\n", "num_lines": 18}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "curl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n\neksctl create cluster -f - <<EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n\niam:\n  withOIDC: true\n  serviceAccounts:\n  - metadata:\n      name: karpenter\n      namespace: karpenter\n    roleName: ${CLUSTER_NAME}-karpenter\n    attachPolicyARNs:\n    - arn:aws:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\n    roleOnly: true\n\niamIdentityMappings:\n- arn: \"arn:aws:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\"\n  username: system:node:{{EC2PrivateDNSName}}\n  groups:\n  - system:bootstrappers\n  - system:nodes\n\nmanagedNodeGroups:\n- instanceType: m5.large\n  amiFamily: AmazonLinux2\n  name: ${CLUSTER_NAME}-ng\n  desiredCapacity: 2\n  minSize: 1\n  maxSize: 10\n\n## Optionally run on fargate\n# fargateProfiles:\n# - name: karpenter\n#  selectors:\n#  - namespace: karpenter\nEOF\n\nexport CLUSTER_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} --query \"cluster.endpoint\" --output text)\"\nexport KARPENTER_IAM_ROLE_ARN=\"arn:aws:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n\necho $CLUSTER_ENDPOINT $KARPENTER_IAM_ROLE_ARN\n", "num_lines": 56}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "TEMPOUT=$(mktemp)\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamidentitymapping \\\n  --username system:node:{{EC2PrivateDNSName}} \\\n  --cluster \"${CLUSTER_NAME}\" \\\n  --arn \"arn:aws:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\" \\\n  --group system:bootstrappers \\\n  --group system:nodes\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamserviceaccount \\\n  --cluster \"${CLUSTER_NAME}\" --name karpenter --namespace karpenter \\\n  --role-name \"${CLUSTER_NAME}-karpenter\" \\\n  --attach-policy-arn \"arn:aws:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\" \\\n  --role-only \\\n  --approve\n\nexport KARPENTER_IAM_ROLE_ARN=\"arn:aws:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "# Logout of docker to perform an unauthenticated pull against the public ECR\ndocker logout public.ecr.aws\n\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --set controller.resources.requests.cpu=1 \\\n  --set controller.resources.requests.memory=1Gi \\\n  --set controller.resources.limits.cpu=1 \\\n  --set controller.resources.limits.memory=1Gi \\\n  --wait\n", "num_lines": 14}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm repo add grafana-charts https://grafana.github.io/helm-charts\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\n\nkubectl create namespace monitoring\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/prometheus-values.yaml | tee prometheus-values.yaml\nhelm install --namespace monitoring prometheus prometheus-community/prometheus --values prometheus-values.yaml\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/grafana-values.yaml | tee grafana-values.yaml\nhelm install --namespace monitoring grafana grafana-charts/grafana --values grafana-values.yaml\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl port-forward --namespace monitoring svc/grafana 3000:80\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl get secret --namespace monitoring grafana -o jsonpath=\"{.data.admin-password}\" | base64 --decode\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.sh/capacity-type\n      operator: In\n      values: [\"spot\"]\n  limits:\n    resources:\n      cpu: 1000\n  providerRef:\n    name: default\n  ttlSecondsAfterEmpty: 30\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n  securityGroupSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nEOF\n", "num_lines": 28}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inflate\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: inflate\n  template:\n    metadata:\n      labels:\n        app: inflate\n    spec:\n      terminationGracePeriodSeconds: 0\n      containers:\n        - name: inflate\n          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7\n          resources:\n            requests:\n              cpu: 1\nEOF\nkubectl scale deployment inflate --replicas 5\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete deployment inflate\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete node $NODE_NAME\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm uninstall karpenter --namespace karpenter\naws cloudformation delete-stack --stack-name \"Karpenter-${CLUSTER_NAME}\"\naws ec2 describe-launch-templates --filters Name=tag:karpenter.k8s.aws/cluster,Values=${CLUSTER_NAME} |\n    jq -r \".LaunchTemplates[].LaunchTemplateName\" |\n    xargs -I{} aws ec2 delete-launch-template --launch-template-name {}\neksctl delete cluster --name \"${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nAWS_REGION=\"$(aws configure list | grep region | tr -s \" \" | cut -d\" \" -f3)\"\nOIDC_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} \\\n    --query \"cluster.identity.oidc.issuer\" --output text)\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' \\\n    --output text)\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "echo '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"ec2.amazonaws.com\"\n            },\n            \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}' > node-trust-policy.json\n\naws iam create-role --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --assume-role-policy-document file://node-trust-policy.json\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKSWorkerNodePolicy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEKS_CNI_Policy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\"\n\naws iam add-role-to-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\" \\\n    --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat << EOF > controller-trust-policy.json\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Federated\": \"arn:aws:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_ENDPOINT#*//}\"\n            },\n            \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n            \"Condition\": {\n                \"StringEquals\": {\n                    \"${OIDC_ENDPOINT#*//}:aud\": \"sts.amazonaws.com\",\n                    \"${OIDC_ENDPOINT#*//}:sub\": \"system:serviceaccount:karpenter:karpenter\"\n                }\n            }\n        }\n    ]\n}\nEOF\n\naws iam create-role --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --assume-role-policy-document file://controller-trust-policy.json\n\ncat << EOF > controller-policy.json\n{\n    \"Statement\": [\n        {\n            \"Action\": [\n                \"ssm:GetParameter\",\n                \"ec2:DescribeImages\",\n                \"ec2:RunInstances\",\n                \"ec2:DescribeSubnets\",\n                \"ec2:DescribeSecurityGroups\",\n                \"ec2:DescribeLaunchTemplates\",\n                \"ec2:DescribeInstances\",\n                \"ec2:DescribeInstanceTypes\",\n                \"ec2:DescribeInstanceTypeOfferings\",\n                \"ec2:DescribeAvailabilityZones\",\n                \"ec2:DeleteLaunchTemplate\",\n                \"ec2:CreateTags\",\n                \"ec2:CreateLaunchTemplate\",\n                \"ec2:CreateFleet\",\n                \"ec2:DescribeSpotPriceHistory\",\n                \"pricing:GetProducts\"\n            ],\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"Karpenter\"\n        },\n        {\n            \"Action\": \"ec2:TerminateInstances\",\n            \"Condition\": {\n                \"StringLike\": {\n                    \"ec2:ResourceTag/karpenter.sh/provisioner-name\": \"*\"\n                }\n            },\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"ConditionalEC2Termination\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"iam:PassRole\",\n            \"Resource\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\",\n            \"Sid\": \"PassNodeIAMRole\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"eks:DescribeCluster\",\n            \"Resource\": \"arn:${AWS_PARTITION}:eks:${AWS_REGION}:${AWS_ACCOUNT_ID}:cluster/${CLUSTER_NAME}\",\n            \"Sid\": \"EKSClusterEndpointLookup\"\n        }\n    ],\n    \"Version\": \"2012-10-17\"\n}\nEOF\n\naws iam put-role-policy --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --policy-name KarpenterControllerPolicy-${CLUSTER_NAME} \\\n    --policy-document file://controller-policy.json\n", "num_lines": 82}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws ec2 create-tags \\\n        --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n        --resources $(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n        --nodegroup-name $NODEGROUP --query 'nodegroup.subnets' --output text )\ndone\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "NODEGROUP=$(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups[0]' --output text)\n\nLAUNCH_TEMPLATE=$(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} --query 'nodegroup.launchTemplate.{id:id,version:version}' \\\n    --output text | tr -s \"\\t\" \",\")\n\n# If your EKS setup is configured to use only Cluster security group, then please execute -\n\nSECURITY_GROUPS=$(aws eks describe-cluster \\\n    --name ${CLUSTER_NAME} --query \"cluster.resourcesVpcConfig.clusterSecurityGroupId\" --output text)\n\n# If your setup uses the security groups in the Launch template of a managed node group, then :\n\nSECURITY_GROUPS=$(aws ec2 describe-launch-template-versions \\\n    --launch-template-id ${LAUNCH_TEMPLATE%,*} --versions ${LAUNCH_TEMPLATE#*,} \\\n    --query 'LaunchTemplateVersions[0].LaunchTemplateData.[NetworkInterfaces[0].Groups||SecurityGroupIds]' \\\n    --output text)\n\naws ec2 create-tags \\\n    --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n    --resources ${SECURITY_GROUPS}\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl edit configmap aws-auth -n kube-system\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm template karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter \\\n    --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n    --set settings.aws.clusterName=${CLUSTER_NAME} \\\n    --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterControllerRole-${CLUSTER_NAME}\" \\\n    --set controller.resources.requests.cpu=1 \\\n    --set controller.resources.requests.memory=1Gi \\\n    --set controller.resources.limits.cpu=1 \\\n    --set controller.resources.limits.memory=1Gi > karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl create namespace karpenter\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_provisioners.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.k8s.aws_awsnodetemplates.yaml\nkubectl apply -f karpenter.yaml\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.k8s.aws/instance-category\n      operator: In\n      values: [c, m, r]\n    - key: karpenter.k8s.aws/instance-generation\n      operator: Gt\n      values: [\"2\"]\n  providerRef:\n    name: default\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\n  securityGroupSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\nEOF\n", "num_lines": 27}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl scale deploy/cluster-autoscaler -n kube-system --replicas=0\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=1,maxSize=1,desiredSize=1\"\ndone\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=2,maxSize=2,desiredSize=2\"\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: add-monitoring.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step09-add-prometheus-grafana.sh\n  step10-add-grafana-port-forward.sh\n  step11-grafana-get-password.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\ndeclare -a steps=(\n  step01-config.sh\n  step12-add-provisioner.sh\n  step13-automatic-node-provisioning.sh\n  step14-automatic-node-termination.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 15}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: setup-roles.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\nSCRIPT_DIR=$(cd -- \"$(dirname -- \"${BASH_SOURCE[0]}\")\" &>/dev/null && pwd)\n\ndeclare -a steps=(\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source \"$SCRIPT_DIR/$step\"\ndone\n", "num_lines": 24}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndeclare -a steps=(\n  step01-config.sh\n  step16-cleanup.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail #fail if one step fails\n\nif [ \"$#\" -ne 1 ]\nthen\n  echo \"Missing required Karpenter version. Usage: install.sh v0.0.1\"\n  exit 1\nfi\n\nexport KARPENTER_VERSION=$1\n\ndeclare -a steps=(\n  step01-config.sh\n  step02-create-cluster.sh\n  step03-iam-cloud-formation.sh\n  step04-grant-access.sh\n  step05-controller-iam.sh\n  step06-add-spot-role.sh\n  step08-apply-helm-chart.sh\n)\n\nfor step in \"${steps[@]}\"; do\n  echo \"$step\"\n  source $step\ndone\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "export AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nexport CLUSTER_NAME=\"${USER}-karpenter-demo\"\nexport AWS_DEFAULT_REGION=\"us-west-2\"\nexport AWS_ACCOUNT_ID=\"$(aws sts get-caller-identity --query Account --output text)\"\nexport TEMPOUT=$(mktemp)\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create cluster -f - << EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nfargateProfiles:\n  - name: karpenter\n    selectors:\n    - namespace: karpenter\niam:\n  withOIDC: true\nEOF\n", "num_lines": 18}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "curl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n\neksctl create cluster -f - <<EOF\n---\napiVersion: eksctl.io/v1alpha5\nkind: ClusterConfig\nmetadata:\n  name: ${CLUSTER_NAME}\n  region: ${AWS_DEFAULT_REGION}\n  version: \"1.24\"\n  tags:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n\niam:\n  withOIDC: true\n  serviceAccounts:\n  - metadata:\n      name: karpenter\n      namespace: karpenter\n    roleName: ${CLUSTER_NAME}-karpenter\n    attachPolicyARNs:\n    - arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\n    roleOnly: true\n\niamIdentityMappings:\n- arn: \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\"\n  username: system:node:{{EC2PrivateDNSName}}\n  groups:\n  - system:bootstrappers\n  - system:nodes\n\nmanagedNodeGroups:\n- instanceType: m5.large\n  amiFamily: AmazonLinux2\n  name: ${CLUSTER_NAME}-ng\n  desiredCapacity: 2\n  minSize: 1\n  maxSize: 10\n\n## Optionally run on fargate\n# fargateProfiles:\n# - name: karpenter\n#  selectors:\n#  - namespace: karpenter\nEOF\n\nexport CLUSTER_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} --query \"cluster.endpoint\" --output text)\"\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n\necho $CLUSTER_ENDPOINT $KARPENTER_IAM_ROLE_ARN\n", "num_lines": 56}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "TEMPOUT=$(mktemp)\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/cloudformation.yaml  > $TEMPOUT \\\n&& aws cloudformation deploy \\\n  --stack-name \"Karpenter-${CLUSTER_NAME}\" \\\n  --template-file \"${TEMPOUT}\" \\\n  --capabilities CAPABILITY_NAMED_IAM \\\n  --parameter-overrides \"ClusterName=${CLUSTER_NAME}\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamidentitymapping \\\n  --username system:node:{{EC2PrivateDNSName}} \\\n  --cluster \"${CLUSTER_NAME}\" \\\n  --arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\" \\\n  --group system:bootstrappers \\\n  --group system:nodes\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "eksctl create iamserviceaccount \\\n  --cluster \"${CLUSTER_NAME}\" --name karpenter --namespace karpenter \\\n  --role-name \"${CLUSTER_NAME}-karpenter\" \\\n  --attach-policy-arn \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:policy/KarpenterControllerPolicy-${CLUSTER_NAME}\" \\\n  --role-only \\\n  --approve\n\nexport KARPENTER_IAM_ROLE_ARN=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/${CLUSTER_NAME}-karpenter\"\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-service-linked-role --aws-service-name spot.amazonaws.com || true\n# If the role has already been successfully created, you will see:\n# An error occurred (InvalidInput) when calling the CreateServiceLinkedRole operation: Service role name AWSServiceRoleForEC2Spot has been taken in this account, please try a different suffix.\n", "num_lines": 4}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "# Logout of helm registry to perform an unauthenticated pull against the public ECR\nhelm registry logout public.ecr.aws\n\nhelm upgrade --install karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter --create-namespace \\\n  --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=${KARPENTER_IAM_ROLE_ARN} \\\n  --set settings.aws.clusterName=${CLUSTER_NAME} \\\n  --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n  --set settings.aws.interruptionQueueName=${CLUSTER_NAME} \\\n  --set controller.resources.requests.cpu=1 \\\n  --set controller.resources.requests.memory=1Gi \\\n  --set controller.resources.limits.cpu=1 \\\n  --set controller.resources.limits.memory=1Gi \\\n  --wait\n", "num_lines": 14}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm repo add grafana-charts https://grafana.github.io/helm-charts\nhelm repo add prometheus-community https://prometheus-community.github.io/helm-charts\nhelm repo update\n\nkubectl create namespace monitoring\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/prometheus-values.yaml | tee prometheus-values.yaml\nhelm install --namespace monitoring prometheus prometheus-community/prometheus --values prometheus-values.yaml\n\ncurl -fsSL https://raw.githubusercontent.com/aws/karpenter/\"${KARPENTER_VERSION}\"/website/content/en/preview/getting-started/getting-started-with-karpenter/grafana-values.yaml | tee grafana-values.yaml\nhelm install --namespace monitoring grafana grafana-charts/grafana --values grafana-values.yaml\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl port-forward --namespace monitoring svc/grafana 3000:80\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl get secret --namespace monitoring grafana -o jsonpath=\"{.data.admin-password}\" | base64 --decode\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.sh/capacity-type\n      operator: In\n      values: [\"spot\"]\n  limits:\n    resources:\n      cpu: 1000\n  providerRef:\n    name: default\n  consolidation: \n    enabled: true\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\n  securityGroupSelector:\n    karpenter.sh/discovery: ${CLUSTER_NAME}\nEOF\n", "num_lines": 29}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: inflate\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: inflate\n  template:\n    metadata:\n      labels:\n        app: inflate\n    spec:\n      terminationGracePeriodSeconds: 0\n      containers:\n        - name: inflate\n          image: public.ecr.aws/eks-distro/kubernetes/pause:3.7\n          resources:\n            requests:\n              cpu: 1\nEOF\nkubectl scale deployment inflate --replicas 5\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 26}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete deployment inflate\nkubectl logs -f -n karpenter -l app.kubernetes.io/name=karpenter -c controller\n", "num_lines": 3}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl delete node $NODE_NAME\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm uninstall karpenter --namespace karpenter\naws cloudformation delete-stack --stack-name \"Karpenter-${CLUSTER_NAME}\"\naws ec2 describe-launch-templates --filters Name=tag:karpenter.k8s.aws/cluster,Values=${CLUSTER_NAME} |\n    jq -r \".LaunchTemplates[].LaunchTemplateName\" |\n    xargs -I{} aws ec2 delete-launch-template --launch-template-name {}\neksctl delete cluster --name \"${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "AWS_PARTITION=\"aws\" # if you are not using standard partitions, you may need to configure to aws-cn / aws-us-gov\nAWS_REGION=\"$(aws configure list | grep region | tr -s \" \" | cut -d\" \" -f3)\"\nOIDC_ENDPOINT=\"$(aws eks describe-cluster --name ${CLUSTER_NAME} \\\n    --query \"cluster.identity.oidc.issuer\" --output text)\"\nAWS_ACCOUNT_ID=$(aws sts get-caller-identity --query 'Account' \\\n    --output text)\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "echo '{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Service\": \"ec2.amazonaws.com\"\n            },\n            \"Action\": \"sts:AssumeRole\"\n        }\n    ]\n}' > node-trust-policy.json\n\naws iam create-role --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --assume-role-policy-document file://node-trust-policy.json\n", "num_lines": 16}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKSWorkerNodePolicy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEKS_CNI_Policy\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly\n\naws iam attach-role-policy --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\" \\\n    --policy-arn arn:${AWS_PARTITION}:iam::aws:policy/AmazonSSMManagedInstanceCore\n", "num_lines": 12}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws iam create-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\"\n\naws iam add-role-to-instance-profile \\\n    --instance-profile-name \"KarpenterNodeInstanceProfile-${CLUSTER_NAME}\" \\\n    --role-name \"KarpenterNodeRole-${CLUSTER_NAME}\"\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat << EOF > controller-trust-policy.json\n{\n    \"Version\": \"2012-10-17\",\n    \"Statement\": [\n        {\n            \"Effect\": \"Allow\",\n            \"Principal\": {\n                \"Federated\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:oidc-provider/${OIDC_ENDPOINT#*//}\"\n            },\n            \"Action\": \"sts:AssumeRoleWithWebIdentity\",\n            \"Condition\": {\n                \"StringEquals\": {\n                    \"${OIDC_ENDPOINT#*//}:aud\": \"sts.amazonaws.com\",\n                    \"${OIDC_ENDPOINT#*//}:sub\": \"system:serviceaccount:karpenter:karpenter\"\n                }\n            }\n        }\n    ]\n}\nEOF\n\naws iam create-role --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --assume-role-policy-document file://controller-trust-policy.json\n\ncat << EOF > controller-policy.json\n{\n    \"Statement\": [\n        {\n            \"Action\": [\n                \"ssm:GetParameter\",\n                \"ec2:DescribeImages\",\n                \"ec2:RunInstances\",\n                \"ec2:DescribeSubnets\",\n                \"ec2:DescribeSecurityGroups\",\n                \"ec2:DescribeLaunchTemplates\",\n                \"ec2:DescribeInstances\",\n                \"ec2:DescribeInstanceTypes\",\n                \"ec2:DescribeInstanceTypeOfferings\",\n                \"ec2:DescribeAvailabilityZones\",\n                \"ec2:DeleteLaunchTemplate\",\n                \"ec2:CreateTags\",\n                \"ec2:CreateLaunchTemplate\",\n                \"ec2:CreateFleet\",\n                \"ec2:DescribeSpotPriceHistory\",\n                \"pricing:GetProducts\"\n            ],\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"Karpenter\"\n        },\n        {\n            \"Action\": \"ec2:TerminateInstances\",\n            \"Condition\": {\n                \"StringLike\": {\n                    \"ec2:ResourceTag/karpenter.sh/provisioner-name\": \"*\"\n                }\n            },\n            \"Effect\": \"Allow\",\n            \"Resource\": \"*\",\n            \"Sid\": \"ConditionalEC2Termination\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"iam:PassRole\",\n            \"Resource\": \"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterNodeRole-${CLUSTER_NAME}\",\n            \"Sid\": \"PassNodeIAMRole\"\n        },\n        {\n            \"Effect\": \"Allow\",\n            \"Action\": \"eks:DescribeCluster\",\n            \"Resource\": \"arn:${AWS_PARTITION}:eks:${AWS_REGION}:${AWS_ACCOUNT_ID}:cluster/${CLUSTER_NAME}\",\n            \"Sid\": \"EKSClusterEndpointLookup\"\n        }\n    ],\n    \"Version\": \"2012-10-17\"\n}\nEOF\n\naws iam put-role-policy --role-name KarpenterControllerRole-${CLUSTER_NAME} \\\n    --policy-name KarpenterControllerPolicy-${CLUSTER_NAME} \\\n    --policy-document file://controller-policy.json\n", "num_lines": 82}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws ec2 create-tags \\\n        --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n        --resources $(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n        --nodegroup-name $NODEGROUP --query 'nodegroup.subnets' --output text )\ndone\n", "num_lines": 7}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "NODEGROUP=$(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups[0]' --output text)\n\nLAUNCH_TEMPLATE=$(aws eks describe-nodegroup --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} --query 'nodegroup.launchTemplate.{id:id,version:version}' \\\n    --output text | tr -s \"\\t\" \",\")\n\n# If your EKS setup is configured to use only Cluster security group, then please execute -\n\nSECURITY_GROUPS=$(aws eks describe-cluster \\\n    --name ${CLUSTER_NAME} --query \"cluster.resourcesVpcConfig.clusterSecurityGroupId\" --output text)\n\n# If your setup uses the security groups in the Launch template of a managed node group, then :\n\nSECURITY_GROUPS=$(aws ec2 describe-launch-template-versions \\\n    --launch-template-id ${LAUNCH_TEMPLATE%,*} --versions ${LAUNCH_TEMPLATE#*,} \\\n    --query 'LaunchTemplateVersions[0].LaunchTemplateData.[NetworkInterfaces[0].Groups||SecurityGroupIds]' \\\n    --output text)\n\naws ec2 create-tags \\\n    --tags \"Key=karpenter.sh/discovery,Value=${CLUSTER_NAME}\" \\\n    --resources ${SECURITY_GROUPS}\n", "num_lines": 23}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl edit configmap aws-auth -n kube-system\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "helm template karpenter oci://public.ecr.aws/karpenter/karpenter --version ${KARPENTER_VERSION} --namespace karpenter \\\n    --set settings.aws.defaultInstanceProfile=KarpenterNodeInstanceProfile-${CLUSTER_NAME} \\\n    --set settings.aws.clusterName=${CLUSTER_NAME} \\\n    --set serviceAccount.annotations.\"eks\\.amazonaws\\.com/role-arn\"=\"arn:${AWS_PARTITION}:iam::${AWS_ACCOUNT_ID}:role/KarpenterControllerRole-${CLUSTER_NAME}\" \\\n    --set controller.resources.requests.cpu=1 \\\n    --set controller.resources.requests.memory=1Gi \\\n    --set controller.resources.limits.cpu=1 \\\n    --set controller.resources.limits.memory=1Gi > karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl create namespace karpenter\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_provisioners.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.k8s.aws_awsnodetemplates.yaml\nkubectl create -f \\\n    https://raw.githubusercontent.com/aws/karpenter/${KARPENTER_VERSION}/pkg/apis/crds/karpenter.sh_machines.yaml\nkubectl apply -f karpenter.yaml\n", "num_lines": 9}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "cat <<EOF | kubectl apply -f -\napiVersion: karpenter.sh/v1alpha5\nkind: Provisioner\nmetadata:\n  name: default\nspec:\n  requirements:\n    - key: karpenter.k8s.aws/instance-category\n      operator: In\n      values: [c, m, r]\n    - key: karpenter.k8s.aws/instance-generation\n      operator: Gt\n      values: [\"2\"]\n  providerRef:\n    name: default\n---\napiVersion: karpenter.k8s.aws/v1alpha1\nkind: AWSNodeTemplate\nmetadata:\n  name: default\nspec:\n  subnetSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\n  securityGroupSelector:\n    karpenter.sh/discovery: \"${CLUSTER_NAME}\"\nEOF\n", "num_lines": 27}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "kubectl scale deploy/cluster-autoscaler -n kube-system --replicas=0\n", "num_lines": 2}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "for NODEGROUP in $(aws eks list-nodegroups --cluster-name ${CLUSTER_NAME} \\\n    --query 'nodegroups' --output text); do aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=1,maxSize=1,desiredSize=1\"\ndone\n", "num_lines": 6}
{"repo_name": "karpenter", "repo_creator": "aws", "programming_language": "Shell", "code": "aws eks update-nodegroup-config --cluster-name ${CLUSTER_NAME} \\\n    --nodegroup-name ${NODEGROUP} \\\n    --scaling-config \"minSize=2,maxSize=2,desiredSize=2\"\n", "num_lines": 4}
{"repo_name": "karpenter-core", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -eu -o pipefail\n\nfor i in $(\n  find ./ -name \"*.go\"\n); do\n  if ! grep -q \"Apache License\" $i; then\n    cat hack/boilerplate.go.txt $i >$i.new && mv $i.new $i\n  fi\ndone\n", "num_lines": 11}
{"repo_name": "karpenter-core", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nK8S_VERSION=\"${K8S_VERSION:=\"1.24.x\"}\"\nKUBEBUILDER_ASSETS=\"${KUBEBUILDER_ASSETS:=\"${HOME}/.kubebuilder/bin\"}\"\n\nmain() {\n    tools\n    kubebuilder\n}\n\ntools() {\n    go install github.com/google/go-licenses@v1.2.0\n    go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.1\n    go install github.com/google/ko@v0.11.2\n    go install github.com/mikefarah/yq/v4@v4.24.5\n    go install github.com/norwoodj/helm-docs/cmd/helm-docs@v1.8.1\n    go install sigs.k8s.io/controller-runtime/tools/setup-envtest@v0.0.0-20220421205612-c162794a9b12\n    go install sigs.k8s.io/controller-tools/cmd/controller-gen@v0.11.3\n    go install github.com/sigstore/cosign/cmd/cosign@v1.10.0\n    go install github.com/gohugoio/hugo@v0.97.3+extended\n    go install golang.org/x/vuln/cmd/govulncheck@v0.0.0-20230215172424-8fb696828224\n    go install github.com/onsi/ginkgo/v2/ginkgo@latest\n\n    if ! echo \"$PATH\" | grep -q \"${GOPATH:-undefined}/bin\\|$HOME/go/bin\"; then\n        echo \"Go workspace's \\\"bin\\\" directory is not in PATH. Run 'export PATH=\\\"\\$PATH:\\${GOPATH:-\\$HOME/go}/bin\\\"'.\"\n    fi\n}\n\nkubebuilder() {\n    mkdir -p $KUBEBUILDER_ASSETS\n    arch=$(go env GOARCH)\n    ## Kubebuilder does not support darwin/arm64, so use amd64 through Rosetta instead\n    if [[ $(go env GOOS) == \"darwin\" ]] && [[ $(go env GOARCH) == \"arm64\" ]]; then\n        arch=\"amd64\"\n    fi\n    ln -sf $(setup-envtest use -p path \"${K8S_VERSION}\" --arch=\"${arch}\" --bin-dir=\"${KUBEBUILDER_ASSETS}\")/* ${KUBEBUILDER_ASSETS}\n    find $KUBEBUILDER_ASSETS\n}\n\nmain \"$@\"\n", "num_lines": 42}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/sh\n\nif test ! -d .git && test ! -f src/fabric.c; then\n    echo You really need to run this script in the top-level libfabric directory\n    exit 1\nfi\n\nset -x\n\nautoreconf -ivf\n", "num_lines": 11}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2016-2017   Cisco Systems, Inc.  All rights reserved.\n# Copyright (c) 2019    Cray Inc.  All rights reserved.\n#\n# This software is available to you under a choice of one of two\n# licenses.  You may choose to be licensed under the terms of the GNU\n# General Public License (GPL) Version 2, available from the file\n# COPYING in the main directory of this source tree, or the\n# BSD license below:\n#\n#     Redistribution and use in source and binary forms, with or\n#     without modification, are permitted provided that the following\n#     conditions are met:\n#\n#      - Redistributions of source code must retain the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer.\n#\n#      - Redistributions in binary form must reproduce the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer in the documentation and/or other materials\n#        provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n####################################################################\n#                                                                  #\n#                  Libfabric RPM build script                      #\n#                                                                  #\n####################################################################\n\n####################\n# initialized values\n####################\nspecfile=\"libfabric.spec\"\nrpmbuilddir=\"$PWD/rpmbuild\"\ndefault_prefix=\"/usr\"\ndefault_opt_prefix=\"/usr/opt\"\nprefix=\"\"\nnoop=\"\"\ninstall_in_opt=\"\"\ncreate_modulefile=\"\"\nunpack_spec=\"\"\nverbose=\"\"\nverboseoption=\"\"\nst=\"\"\nversion=\"\"\nmodulepath=\"\"\n\n##################################\n# If you need custom configure and\n# rpmbuild options, put them here\n# or use \"-c\" and \"-r\" parameters\n##################################\nconfigure_options=\"\"\nrpmbuild_options=\"\"\n\n###########\n# functions\n###########\nverbose()\n{\n  if [[ -n \"$verbose\" ]]; then\n    echo \"$0: --> $*\"\n  fi\n}\n\nruncmd()\n{\n  if [[ -z \"$noop\" ]]; then\n    verbose \"Executing: $*\"\n  else\n    verbose \"Would have executed: $*\"\n  fi\n\n  if [[ -z \"$noop\" ]]; then\n    eval \"$*\"\n    st=$?\n    if [[ $st -ne 0 ]]; then\n      echo \"$0: FATAL: command failed with status $st: $*\" 1>&2\n      exit 1\n    fi\n  fi\n}\n\nerror()\n{\n  st=$1\n  shift\n  echo \"$0: FATAL: $*\" 1>&2\n  if [[ -z \"$noop\" ]]; then\n    exit $st\n  fi\n}\n\n###################\n# usage information\n###################\nusage=\"Usage: $0 [-i provider_name] [-e provider_name]\n       [-n] [-o] [-m] [-d] [-s] [-c] [-r] [-v] [-h] tarball\n\n Provider options:\n\n  -i    provider_name\n             include 'provider_name' provider support to the build\n\n  -e    provider_name\n             exclude 'provider_name' provider support from the build\n\n General options:\n  -n         no op, do nothing (useful with -v option)\n\n  -o         install under /opt/libfabric/_VERSION_\n               {default: install under /usr/ }\n\n  -m         install modulefile\n              {default: don't install modulefile}\n\n  -d         build with Debugging support\n              {default: without debugging support}\n\n  -s         try to unpack libfabric.spec file from tarball\n               {default: look for libfabric.spec file in current directory}\n\n  -c    parameter\n             add custom configure parameter\n\n  -r    parameter\n             add custom RPM build parameter\n\n  -D         install default version file (i.e., \\\".version\\\") for the modulefile\n              {default: do not install version file}\n\n  -P    prefix\n             install RPM under prefix as installation prefix\n\n  -M    prefix\n             install a modulefile at the specified prefix\n              {default: /usr/share/Modules/modulefiles}\n\n  -V    version\n             Use the specified version as the RPM version\n\n  -v         be verbose\n\n  -h         print this message and exit\n\n  tarball    path to Libfabric source tarball\n  \"\n\n############\n# parse args\n############\nexport arguments=\"$@\"\nwhile getopts DP:M:V:nomi:e:dc:r:svh flag; do\n    case \"$flag\" in\n      n) noop=\"true\"\n         ;;\n      o) install_in_opt=\"true\"\n         ;;\n      m) create_modulefile=\"true\"\n         rpmbuild_options=\"$rpmbuild_options --define 'install_modulefile 1'\"\n         ;;\n      i) configure_options=\"$configure_options --enable-$OPTARG\"\n         ;;\n      e) configure_options=\"$configure_options --disable-$OPTARG\"\n         ;;\n      d) configure_options=\"$configure_options --enable-debug\"\n         ;;\n      c) configure_options=\"$configure_options $OPTARG\"\n         ;;\n      r) rpmbuild_options=\"$rpmbuild_options $OPTARG\"\n         ;;\n      P) prefix=$OPTARG\n         ;;\n      M) modulepath=$OPTARG\n         ;;\n      D) rpmbuild_options=\"$rpmbuild_options --define 'install_default_module_version 1'\"\n         ;;\n      V) version=$OPTARG\n         ;;\n      s) unpack_spec=\"true\"\n         ;;\n      v) verbose=\"true\"\n         ;;\n      h) echo \"$usage\"\n         exit 0\n         ;;\n    esac\ndone\nshift $(( OPTIND - 1 ));\n\nif [[ -n \"$verbose\" ]]; then\n  verboseoption=\"-v\"\nfi\n\n########################################\n# Check if there is at least 1 parameter\n# specified (tarball is mandatory)\n########################################\nif [[ $# -lt 1 ]]; then\n  echo \"$usage\" 1>&2\n  exit 1\nfi\n\n#############\n# Print hello\n#############\nif [[ -n \"$verbose\" ]]; then\ncat <<EOF\n\n------------------------------------------------------------------------------\n====              Welcome to the Libfabric RPM build script               ====\n------------------------------------------------------------------------------\nYou have specified these options:\n $arguments\n------------------------------------------------------------------------------\n\nEOF\n  if [[ -n \"$noop\" ]]; then\n    echo \"$0: --> Option -n was specified. I won't do anything.\"\n  fi\nfi\n\n################################\n# Check if tarball was specified\n################################\ntarball=\"$1\"\n\nif [[ ! -r \"$tarball\" ]]; then\n  error 2 \"Can't find $tarball\"\nfi\nverbose \"Found tarball: $tarball\"\n\n##############################\n# Get tarball name and version\n##############################\ntardirname=$(basename \"$tarball\" | awk '{print substr ($0, 0, index($0, \".tar\")-1)}')\nif [[ -z \"$tardirname\" ]]; then\n  error 3 \"Cannot determine name from $tarball\"\nfi\nverbose \"Name of package: $tardirname\"\n\nif [[ -z \"$version\" ]] ; then\n  version=$(basename \"$tardirname\" | cut -d- -f2)\n  if [[ -z \"$version\" ]]; then\n    error 4 \"Cannot determine version from $tarball\"\n  fi\nfi\nverbose \"Version: $version\"\n\nif [[ -n \"$install_in_opt\" ]]; then\n  if [[ -z \"$prefix\" ]] ; then\n    prefix=$default_opt_prefix\n  fi\n  prefix=\"$prefix/libfabric/$version\"\n\n  if [[ -n \"$modulepath\" ]] ; then\n    verbose \"Setting RPM module path to: $modulepath\"\n    rpmbuild_options=\"$rpmbuild_options --define 'modulefile_path $modulepath'\"\n  fi\nelse\n  if [[ -z \"$prefix\" ]] ; then\n    prefix=\"$default_prefix/libfabric\"\n  fi\nfi\n\nif [[ \"$prefix\" != \"$default_prefix\" ]] ; then\n  verbose \"Setting RPM install path to: $prefix\"\n  rpmbuild_options=\"$rpmbuild_options --define '_prefix $prefix'\"\nfi\n\n######################################\n# Try to unpack spec file from tarball\n######################################\nif [[ -n \"$unpack_spec\" ]]; then\n  if [[ -f \"$specfile\" ]]; then\n    verbose \"WARNING: $specfile already exists and will be overwritten\" 1>&2\n  fi\n  verbose \"Extracting tarball\"\n  runcmd \"tar $verboseoption -xf \\\"$tarball\\\"\"\n  verbose \"Copying specfile\"\n  runcmd \"cp -fp $verboseoption \\\"$tardirname/$specfile\\\" .\"\n  verbose \"Cleanup after extraction\"\n  runcmd \"rm -rf $verboseoption \\\"$tardirname\\\"\"\nfi\n\n##############################\n# Check if specfile is present\n##############################\nif [[ ! -r $specfile ]]; then\n  if [[ -z \"$noop\" ]]; then\n    error 5 \"Cannot find $specfile\"\n  else\n    verbose \"WARNING: Cannot find $specfile\" 1>&2\n  fi\nelse\n  verbose \"Found specfile: $specfile\"\nfi\n\n#############################\n# Prepare directory for build\n#############################\nverbose \"Cleanup old rpmbuild directory\"\nruncmd \"rm -rf $verboseoption \\\"$rpmbuilddir\\\"\"\nverbose \"Create rpmbuild SOURCES directory\"\nruncmd \"mkdir -p $verboseoption \\\"$rpmbuilddir/SOURCES/\\\"\"\nverbose \"Copy tarball to rpmbuild directory\"\nruncmd \"cp -fp $verboseoption \\\"$tarball\\\" \\\"$rpmbuilddir/SOURCES/\\\"\"\n\n###########\n# Build RPM\n###########\ncmd=\"\"\nbuild_opt=\"\"\n\nif [[ -z \"$verbose\" ]]; then\n  build_opt=\"--quiet\"\nelse\n  build_opt=\"-v\"\nfi\ncmd=\"rpmbuild $build_opt -bb $specfile $rpmbuild_options \\\n  --define '_topdir $rpmbuilddir' \\\n  --define '_sourcedir $rpmbuilddir/SOURCES' \\\n  --define '_rpmdir $rpmbuilddir/RPMS' \\\n  --define '_specdir $rpmbuilddir/SPECS' \\\n  --define '_tmppath $rpmbuilddir/tmp'\"\n\nif [[ -n \"$configure_options\" ]]; then\n  cmd=\"$cmd --define 'configopts $configure_options'\"\nfi\n\nverbose \"Build command used:\"\nverbose \"$cmd\"\nverbose \"RPM build will start\"\nruncmd \"$cmd\"\nverbose \"Done building the RPM\"\n\n##############\n# Print result\n##############\nif [[ -n \"$verbose\" ]]; then\n  cat <<EOF\n\n------------------------------------------------------------------------------\n====                FINISHED BUILDING Libfabric RPM                       ====\n------------------------------------------------------------------------------\nA copy of the tarball is located in: $rpmbuilddir/SOURCES/\nThe completed RPMs are located in:   $rpmbuilddir/RPMS/\n------------------------------------------------------------------------------\n\nEOF\nfi\n", "num_lines": 362}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# DIR is expected to be defined by files that include these common variables\nBUILD_VERSION=$(cat $DIR/../share/version)\nROOT_INSTALL_PATH=$LIBFABRIC_BUILD_PATH/virtualenv/\nPREREQ_INSTALL_PATH=$ROOT_INSTALL_PATH/prerequisites\nVIRTUALENV_INSTALL_PATH=$ROOT_INSTALL_PATH/venv-${BUILD_VERSION}\n\n", "num_lines": 9}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ -z ${FABTEST_PATH} ]] ; then\n\texport FABTEST_PATH=/scratch/jenkins/builds/fabtests/stable\nfi\n\nexport PATH=${FABTEST_PATH}/bin:$PATH\n\nif [[ -z ${FABTEST_PROVIDER} ]] ; then\n    FABTEST_PROVIDER='verbs;ofi_rxm'\nfi\n\nif [[ -z ${SLURMD_NODENAME} ]] ; then\n    echo SLURM is the only supported WLM at this point for testing\n    exit 1\nfi\n\nSERVER=$(scontrol show hostname ${SLURM_NODELIST} | head -n1)\nCLIENT=$(scontrol show hostname ${SLURM_NODELIST} | tail -n1)\n\nSERVER_ADDR=$(getent hosts ${SERVER} | awk '{print $1}')\nCLIENT_ADDR=$(getent hosts ${CLIENT} | awk '{print $1}')\n\nif [[ \"${SLURMD_NODENAME}\" == \"$SERVER\" ]] ; then\n    runfabtests.sh \\\n        $@ \\\n        \"${FABTEST_PROVIDER}\" \\\n        ${SERVER_ADDR} \\\n        ${CLIENT_ADDR}\nfi\n", "num_lines": 31}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null && pwd )\"\n\nsource $DIR/common.sh\n\nsource $VIRTUALENV_INSTALL_PATH/bin/activate\npython $DIR/../python/parse_results.py $@\n", "num_lines": 17}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null && pwd )\"\n\nsource $DIR/common.sh\n\nif [[ -z \"$(which pip)\" ]] ; then\n    echo failed to find pip\n    false\nfi\n\nif [[ -z \"$(which python)\" ]] ; then\n    echo failed to find python\n    false\nfi\n\nfunction cleanup {\n    echo failed to setup environment\n}\n\ntrap cleanup ERR\n\nif [[ -z \"$(which virtualenv)\" ]] ; then\n    pip --isolated install --root $PREREQ_INSTALL_PATH virtualenv\n    export PYTHONPATH=$PREREQ_INSTALL_PATH/usr/lib/python2.7/site-packages:$PYTHONPATH\n    export PATH=$PREREQ_INSTALL_PATH/bin:$PATH\nfi\n\nif [[ ! -f $VIRTUALENV_INSTALL_PATH/bin/activate ]] ; then\n    virtualenv $VIRTUALENV_INSTALL_PATH\nfi\n\nsource $VIRTUALENV_INSTALL_PATH/bin/activate\npip install -r $DIR/../share/requirements.txt\n\n", "num_lines": 44}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nfunction check_executable {\n    if [[ ! -x $1 ]] ; then\n        echo could not find executable: $1\n        exit 1\n    fi\n}\n\nfunction check_directory {\n    if [[ ! -d $1 ]] ; then\n        echo could not find directory: $1\n        exit 1\n    fi\n}\n\nfunction check_environment {\n    var=$1\n    val=$(eval \"echo \\$$var\")\n    if [[ -z \"$val\" ]] ; then\n        echo could not find environment variable: $var\n        exit 1\n    fi\n}\n\nfunction find_executable {\n    if [[ -z \"$(which $1)\" ]] ; then\n        echo could not find executable: $1\n        exit 1\n    fi\n}\n\n# check prerequisite environment variables\ncheck_environment ROOT_BUILD_PATH\ncheck_environment FABTEST_PATH\ncheck_environment LIBFABRIC_BUILD_PATH\ncheck_environment OMB_BUILD_PATH\ncheck_environment MPICH_PATH\n\n# check directories\ncheck_directory $ROOT_BUILD_PATH\ncheck_directory $OMB_BUILD_PATH\ncheck_directory $MPICH_PATH\ncheck_directory $SFT_INSTALL_PATH\ncheck_directory $BATS_INSTALL_PATH\n\n##### check prerequisite installed software packages\n# SLURM     https://slurm.schedmd.com/\nfind_executable srun\n# OMB       http://mvapich.cse.ohio-state.edu/benchmarks/\ncheck_executable $OMB_BUILD_PATH/pt2pt/osu_bw\n# Cray Proprietary\ncheck_executable $SFT_INSTALL_PATH/bin/ci-all.sh\n# BATS      https://github.com/bats-core/bats-core\ncheck_executable $BATS_INSTALL_PATH/bats\n\nexit 0\n", "num_lines": 60}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2017 Intel Corp.  All rights reserved.\n#\n# This software is available to you under a choice of one of two\n# licenses.  You may choose to be licensed under the terms of the GNU\n# General Public License (GPL) Version 2, available from the file\n# COPYING in the main directory of this source tree, or the\n# BSD license below:\n#\n#     Redistribution and use in source and binary forms, with or\n#     without modification, are permitted provided that the following\n#     conditions are met:\n#\n#      - Redistributions of source code must retain the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer.\n#\n#      - Redistributions in binary form must reproduce the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer in the documentation and/or other materials\n#        provided with the distribution.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#\n# MAN 2 PDF -- Simple script to convert the libfabric manpages into a PDF\n#\n# Requires libfabric manpages to be installed and available in MANPATH.\n# Uses man and ps2pdf to convert each manpage, followed by Mac join.py or\n# pdfjoin to generate final PDF\n#\n\n# Generate list of manpages, but exclude manpages that are symlinks to other manpages\nMANPAGES=( `echo fabric && man -a -w fi_* | xargs basename | sort | uniq | cut -d . -f 1` )\n\nPDFMANPAGES=( \"${MANPAGES[@]/%/.pdf}\" )\nWORKDIR=`mktemp -d /tmp/libfabric-manpages.XXXXXX || exit 1`\nOUTFILE=\"libfabric-manpages-`date \\\"+%Y-%m-%d\\\"`.pdf\"\nEXITDIR=\"$PWD\"\n\nif [ -e $OUTFILE ]; then\n    echo \"Error: $OUTFILE already exists\"\n    exit 1\nfi\n\necho Entering work directory: $WORKDIR\ncd $WORKDIR || exit 1\n\nfor manpage in \"${MANPAGES[@]}\"; do\n    echo \"  - Converting $manpage\"\n    man -t $manpage | ps2pdf - $WORKDIR/${manpage}.pdf || exit 1\ndone\n\necho \"  + Merging manpages\"\n\nif [ -x /System/Library/Automator/Combine\\ PDF\\ Pages.action/Contents/Resources/join.py ]; then\n    /System/Library/Automator/Combine\\ PDF\\ Pages.action/Contents/Resources/join.py -o $OUTFILE \"${PDFMANPAGES[@]}\" || exit 1\nelif hash pdfjoin 2>/dev/null; then\n    pdfjoin --quiet -o $OUTFILE \"${PDFMANPAGES[@]}\" || exit 1\nelse\n    echo \"Error: could not join PDFs (check installation of pdfjoin)\"\nfi\n\necho \"  + Cleaning up\"\n\nrm -f \"${PDFMANPAGES[@]}\"\ncd $EXITDIR\nif [ -e $WORKDIR/$OUTFILE ]; then\n    mv $WORKDIR/$OUTFILE .\n    echo \"Done: $OUTFILE\"\nelse\n    echo \"PDF generation failed\"\nfi\n\nrmdir $WORKDIR\n\n", "num_lines": 85}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/sh\n\nif test ! -d .git && test ! -f common/shared.c; then\n    echo You really need to run this script in the top-level fabtests directory\n    exit 1\nfi\n\nset -x\n\nif test ! -d config; then\n    mkdir config\nfi\n\nautoreconf -ivf\n", "num_lines": 15}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#\n# Copyright (c) 2017-2019, Intel Corporation.  All rights reserved.\n# Copyright (c) 2016-2018, Cisco Systems, Inc. All rights reserved.\n# Copyright (c) 2016, Cray, Inc. All rights reserved.\n# Copyright (c) 2019 Amazon.com, Inc. or its affiliates. All rights reserved.\n#\n# This software is available to you under a choice of one of two\n# licenses.  You may choose to be licensed under the terms of the GNU\n# General Public License (GPL) Version 2, available from the file\n# COPYING in the main directory of this source tree, or the\n# BSD license below:\n#\n#     Redistribution and use in source and binary forms, with or\n#     without modification, are permitted provided that the following\n#     conditions are met:\n#\n#      - Redistributions of source code must retain the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer.\n#\n#      - Redistributions in binary form must reproduce the above\n#        copyright notice, this list of conditions and the following\n#        disclaimer in the documentation and/or other materials\n#        provided with the distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n#\n\ntrap cleanup_and_exit SIGINT\n\n#\n# Default behavior with no args will use sockets provider with loopback\n#\ndeclare BIN_PATH\ndeclare PROV=\"\"\ndeclare CORE=\"\"\ndeclare UTIL=\"\"\ndeclare TEST_TYPE=\"quick\"\ndeclare SERVER=\"127.0.0.1\"\ndeclare CLIENT=\"127.0.0.1\"\ndeclare GOOD_ADDR=\"\"\ndeclare -i VERBOSE=0\ndeclare -i SKIP_NEG=0\ndeclare COMPLEX_CFG\ndeclare TIMEOUT_VAL=\"120\"\ndeclare STRICT_MODE=0\ndeclare FORK=0\ndeclare OOB=0\ndeclare C_ARGS=\"\"\ndeclare S_ARGS=\"\"\n\ndeclare cur_excludes=\"\"\ndeclare file_excludes=\"\"\ndeclare input_excludes=\"\"\n\ndeclare -r c_outp=$(mktemp fabtests.c_outp.XXXXXX)\ndeclare -r s_outp=$(mktemp fabtests.s_outp.XXXXXX)\n\ndeclare -i skip_count=0\ndeclare -i pass_count=0\ndeclare -i fail_count=0\ndeclare -i total_failures=0\n\nif [[ \"$(uname)\" == \"FreeBSD\" ]]; then\n    declare -ri FI_ENODATA=$(python -c 'import errno; print(errno.ENOMSG)')\nelse\n    declare -ri FI_ENODATA=$(python -c 'import errno; print(errno.ENODATA)')\nfi\ndeclare -ri FI_ENOSYS=$(python -c 'import errno; print(errno.ENOSYS)')\n\nneg_unit_tests=(\n\t\"fi_dgram g00n13s\"\n\t\"fi_rdm g00n13s\"\n\t\"fi_msg g00n13s\"\n)\n\nfunctional_tests=(\n\t\"fi_av_xfer -e rdm\"\n\t\"fi_av_xfer -e dgram\"\n\t\"fi_cm_data\"\n\t\"fi_cq_data -e msg\"\n\t\"fi_cq_data -e rdm\"\n\t\"fi_cq_data -e dgram\"\n\t\"fi_dgram\"\n\t\"fi_dgram_waitset\"\n\t\"fi_msg\"\n\t\"fi_msg_epoll\"\n\t\"fi_msg_sockets\"\n\t\"fi_poll -t queue\"\n\t\"fi_poll -t counter\"\n\t\"fi_rdm\"\n\t\"fi_rdm_rma_simple\"\n\t\"fi_rdm_rma_trigger\"\n\t\"fi_shared_ctx\"\n\t\"fi_shared_ctx --no-tx-shared-ctx\"\n\t\"fi_shared_ctx --no-rx-shared-ctx\"\n\t\"fi_shared_ctx -e msg\"\n\t\"fi_shared_ctx -e msg --no-tx-shared-ctx\"\n\t\"fi_shared_ctx -e msg --no-rx-shared-ctx\"\n\t\"fi_shared_ctx -e dgram\"\n\t\"fi_shared_ctx -e dgram --no-tx-shared-ctx\"\n\t\"fi_shared_ctx -e dgram --no-rx-shared-ctx\"\n\t\"fi_rdm_tagged_peek\"\n\t\"fi_scalable_ep\"\n\t\"fi_rdm_shared_av\"\n\t\"fi_multi_mr -e msg -V\"\n\t\"fi_multi_mr -e rdm -V\"\n\t\"fi_recv_cancel -e rdm -V\"\n\t\"fi_unexpected_msg -e msg -i 10\"\n\t\"fi_unexpected_msg -e rdm -i 10\"\n\t\"fi_unexpected_msg -e msg -S -i 10\"\n\t\"fi_unexpected_msg -e rdm -S -i 10\"\n\t\"fi_inj_complete -e msg\"\n\t\"fi_inj_complete -e rdm\"\n\t\"fi_inj_complete -e dgram\"\n\t\"fi_inj_complete -e msg -SR\"\n\t\"fi_inj_complete -e rdm -SR\"\n\t\"fi_inj_complete -e dgram -SR\"\n\t\"fi_bw -e rdm -v -T 1\"\n\t\"fi_bw -e msg -v -T 1\"\n)\n\nshort_tests=(\n\t\"fi_msg_pingpong -I 5\"\n\t\"fi_msg_pingpong -I 5 -v\"\n\t\"fi_msg_bw -I 5\"\n\t\"fi_msg_bw -I 5 -v\"\n\t\"fi_rma_bw -e msg -o write -I 5\"\n\t\"fi_rma_bw -e msg -o read -I 5\"\n\t\"fi_rma_bw -e msg -o writedata -I 5\"\n\t\"fi_rma_bw -e rdm -o write -I 5\"\n\t\"fi_rma_bw -e rdm -o read -I 5\"\n\t\"fi_rma_bw -e rdm -o writedata -I 5\"\n\t\"fi_rdm_atomic -I 5 -o all\"\n\t\"fi_rdm_cntr_pingpong -I 5\"\n\t\"fi_multi_recv -e rdm -I 5\"\n\t\"fi_multi_recv -e msg -I 5\"\n\t\"fi_rdm_pingpong -I 5\"\n\t\"fi_rdm_pingpong -I 5 -v\"\n\t\"fi_rdm_tagged_pingpong -I 5\"\n\t\"fi_rdm_tagged_pingpong -I 5 -v\"\n\t\"fi_rdm_tagged_bw -I 5\"\n\t\"fi_rdm_tagged_bw -I 5 -v\"\n\t\"fi_dgram_pingpong -I 5\"\n)\n\nstandard_tests=(\n\t\"fi_msg_pingpong\"\n\t\"fi_msg_pingpong -v\"\n\t\"fi_msg_pingpong -k\"\n\t\"fi_msg_pingpong -k -v\"\n\t\"fi_msg_bw\"\n\t\"fi_msg_bw -v\"\n\t\"fi_rma_bw -e msg -o write\"\n\t\"fi_rma_bw -e msg -o read\"\n\t\"fi_rma_bw -e msg -o writedata\"\n\t\"fi_rma_bw -e rdm -o write\"\n\t\"fi_rma_bw -e rdm -o read\"\n\t\"fi_rma_bw -e rdm -o writedata\"\n\t\"fi_rdm_atomic -o all -I 1000\"\n\t\"fi_rdm_cntr_pingpong\"\n\t\"fi_multi_recv -e rdm\"\n\t\"fi_multi_recv -e msg\"\n\t\"fi_rdm_pingpong\"\n\t\"fi_rdm_pingpong -v\"\n\t\"fi_rdm_pingpong -k\"\n\t\"fi_rdm_pingpong -k -v\"\n\t\"fi_rdm_tagged_pingpong\"\n\t\"fi_rdm_tagged_pingpong -v\"\n\t\"fi_rdm_tagged_bw\"\n\t\"fi_rdm_tagged_bw -v\"\n\t\"fi_dgram_pingpong\"\n\t\"fi_dgram_pingpong -k\"\n)\n\nunit_tests=(\n\t\"fi_getinfo_test -s SERVER_ADDR GOOD_ADDR\"\n\t\"fi_av_test -g GOOD_ADDR -n 1 -s SERVER_ADDR\"\n\t\"fi_dom_test -n 2\"\n\t\"fi_eq_test\"\n\t\"fi_cq_test\"\n\t\"fi_mr_test\"\n\t\"fi_cntr_test\"\n)\n\ncomplex_tests=(\n\t\"fi_ubertest\"\n)\n\nmultinode_tests=(\n\t\"fi_multinode -C msg\"\n\t\"fi_multinode -C rma\"\n\t\"fi_multinode_coll\"\n)\n\nfunction errcho {\n\t>&2 echo $*\n}\n\nfunction print_border {\n\tprintf \"# \"\n\tprintf \"%.0s-\" {1..78}\n\tprintf \"\\n\"\n}\n\nfunction print_results {\n\tlocal test_name=$1\n\tlocal test_result=$2\n\tlocal test_time=$3\n\tlocal server_out_file=$4\n\tlocal server_cmd=$5\n\tlocal client_out_file=$6\n\tlocal client_cmd=$7\n\n\tif [ $VERBOSE -eq 0 ] ; then\n\t\t# print a simple, single-line format that is still valid YAML\n\t\tprintf \"%-70s%10s\\n\" \"$test_exe:\" \"$test_result\"\n\telse\n\t\t# Print a more detailed YAML format that is not a superset of\n\t\t# the non-verbose output.  See ofiwg/fabtests#259 for a\n\t\t# rationale.\n\t\temit_stdout=0\n\t\tcase $test_result in\n\t\t\tPass*)\n\t\t\t\t[ $VERBOSE -ge 3 ] && emit_stdout=1\n\t\t\t\t;;\n\t\t\tNotrun|Excluded)\n\t\t\t\t[ $VERBOSE -ge 2 ] && emit_stdout=1\n\t\t\t\t;;\n\t\t\tFail*)\n\t\t\t\t[ $VERBOSE -ge 1 ] && emit_stdout=1\n\t\t\t\t;;\n\t\tesac\n\n\t\tprintf -- \"- name:   %s\\n\" \"$test_exe\"\n\t\tprintf -- \"  result: %s\\n\" \"$test_result\"\n\t\tprintf -- \"  time:   %s\\n\" \"$test_time\"\n\t\tif [ $emit_stdout -eq 1 -a \"$server_out_file\" != \"\" ] ; then\n\t\t\tif [ \"$server_cmd\" != \"\" ] ; then\n\t\t\t\tprintf -- \"  server_cmd: %s\\n\" \"$server_cmd\"\n\t\t\tfi\n\t\t\tprintf -- \"  server_stdout: |\\n\"\n\t\t\tsed -e 's/^/    /' < $server_out_file\n\t\tfi\n\t\tif [ $emit_stdout -eq 1 -a \"$client_out_file\" != \"\" ] ; then\n\t\t\tif [ \"$client_cmd\" != \"\" ] ; then\n\t\t\t\tprintf -- \"  client_cmd: %s\\n\" \"$client_cmd\"\n\t\t\tfi\n\t\t\tprintf -- \"  client_stdout: |\\n\"\n\t\t\tsed -e 's/^/    /' < $client_out_file\n\t\tfi\n\tfi\n}\n\nfunction cleanup {\n\t${CLIENT_CMD} \"ps -eo comm,pid | grep '^fi_' | awk '{print \\$2}' | xargs kill -9\" >& /dev/null\n\t${SERVER_CMD} \"ps -eo comm,pid | grep '^fi_' | awk '{print \\$2}' | xargs kill -9\" >& /dev/null\n\trm -f $c_outp $s_outp\n}\n\nfunction cleanup_and_exit {\n\tcleanup\n\texit 1\n}\n\n# compute the duration in seconds between two integer values\n# measured since the start of the UNIX epoch and print the result to stdout\nfunction compute_duration {\n\tlocal -i s=$1\n\tlocal -i e=$2\n\techo $(( $2 - $1))\n}\n\nfunction read_exclude_file {\n\tlocal excl_file=$1\n\n\tif [ ! -f $excl_file ]; then\n\t\techo \"Given exclusion file does not exist!\"\n\t\texit 1\n\tfi\n\n\twhile read -r pattern || [[ -n \"$pattern\" ]]; do\n\t\t# Ignore patterns that are comments or just whitespaces\n\t\tignore_pattern=\"#.*|^[\\t ]*$\"\n\t\tif [[ ! \"$pattern\" =~ $ignore_pattern ]]; then\n\t\t\tif [ -z \"$file_excludes\" ]; then\n\t\t\t\tfile_excludes=\"$pattern\"\n\t\t\telse\n\t\t\t\tfile_excludes=\"${file_excludes},$pattern\"\n\t\t\tfi\n\t\tfi\n\tdone < \"$excl_file\"\n}\n\nfunction auto_exclude {\n\tlocal excl_file\n\tlocal name=$UTIL\n\n\tif [ -z $UTIL ]; then\n\t\tname=$CORE\n\tfi\n\n\texcl_file=\"./fabtests/test_configs/${name}/${name}.exclude\"\n\tif [[ ! -f \"$excl_file\" ]]; then\n\t\texcl_file=\"./test_configs/${name}/${name}.exclude\"\n\t\tif [[ ! -f \"$excl_file\" ]]; then\n\t\t\texcl_file=\"../test_configs/${name}/${name}.exclude\"\n\t\t\tif [[ ! -f \"$excl_file\" ]]; then\n\t\t\t\treturn\n\t\t\tfi\n\t\tfi\n\tfi\n\n\tread_exclude_file ${excl_file}\n\tcur_excludes=${file_excludes}\n\tfile_excludes=\"\"\n}\n\nfunction set_excludes {\n\tif [[ -n \"$input_excludes\" ]]; then\n\t\tcur_excludes=${input_excludes}\n\tfi\n\n\tif [[ -n \"$file_excludes\" ]]; then\n\t\t[[ -z \"$cur_excludes\" ]] && cur_excludes=${file_excludes} || \\\n\t\t\tcur_excludes=\"${cur_excludes},${file_excludes}\"\n\tfi\n\n\tif [[ -n \"$cur_excludes\" ]]; then\n\t\treturn\n\tfi\n\n\tauto_exclude\n}\n\nfunction is_excluded {\n\ttest_name=$1\n\n\t[[ -z \"$cur_excludes\" ]] && return 1\n\n\tIFS=\",\" read -ra exclude_array <<< \"$cur_excludes\"\n\tfor pattern in \"${exclude_array[@]}\"; do\n\t\tif [[ \"$test_name\" =~ $pattern ]]; then\n\t\t\tprint_results \"$test_exe\" \"Excluded\" \"0\" \"\" \"\"\n\t\t\tskip_count+=1\n\t\t\treturn 0\n\t\tfi\n\tdone\n\treturn 1\n}\n\nfunction unit_test {\n\tlocal test=$1\n\tlocal is_neg=$2\n\tlocal ret1=0\n\tlocal s_interface=$(eval \"if [ $OOB -eq 1 ]; \\\n\t\tthen echo $GOOD_ADDR; \\\n\t\telse echo $S_INTERFACE; \\\n\t\tfi\")\n\tlocal test_exe=$(echo \"${test} -p \\\"$PROV\\\"\" | \\\n\t    sed -e \"s/GOOD_ADDR/$GOOD_ADDR/g\" -e \"s/SERVER_ADDR/$s_interface/g\")\n\tlocal start_time\n\tlocal end_time\n\tlocal test_time\n\n\tis_excluded \"$test\" && return\n\n\tstart_time=$(date '+%s')\n\n\tcmd=\"${BIN_PATH}${test_exe}\"\n\t${SERVER_CMD} \"${EXPORT_ENV} $cmd\" &> $s_outp &\n\tp1=$!\n\n\twait $p1\n\tret=$?\n\n\tend_time=$(date '+%s')\n\ttest_time=$(compute_duration \"$start_time\" \"$end_time\")\n\n\tif [ $is_neg -eq 1 -a $ret -eq $FI_ENODATA ]; then\n\t\t# negative test passed\n\t\tret=0\n\telif [ $is_neg -eq 1 ]; then\n\t\t# negative test failed\n\t\tret=1\n\tfi\n\tif [[ $STRICT_MODE -eq 0 && $ret -eq $FI_ENODATA || $ret -eq $FI_ENOSYS ]]; then\n\t\tprint_results \"$test_exe\" \"Notrun\" \"$test_time\" \"$s_outp\" \"$cmd\"\n\t\tskip_count+=1\n\telif [ $ret -ne 0 ]; then\n\t\tprint_results \"$test_exe\" \"Fail\" \"$test_time\" \"$s_outp\" \"$cmd\"\n\t\tif [ $ret -eq 124 ]; then\n\t\t\tcleanup\n\t\tfi\n\t\tfail_count+=1\n\telse\n\t\tprint_results \"$test_exe\" \"Pass\" \"$test_time\" \"$s_outp\" \"$cmd\"\n\t\tpass_count+=1\n\tfi\n}\n\nfunction cs_test {\n\tlocal test=$1\n\tlocal s_ret=0\n\tlocal c_ret=0\n\tlocal test_exe=\"${test} -p \\\"${PROV}\\\"\"\n\tlocal start_time\n\tlocal end_time\n\tlocal test_time\n\n\tis_excluded \"$test\" && return\n\n\tstart_time=$(date '+%s')\n\n\tif [[ $OOB -eq 1 ]]; then\n\t\ts_arg=\"-E\"\n\telse\n\t\ts_arg=\"-s $S_INTERFACE\"\n\tfi\n\ts_cmd=\"${BIN_PATH}${test_exe} ${S_ARGS} $s_arg\"\n\t${SERVER_CMD} \"${EXPORT_ENV} $s_cmd\" &> $s_outp &\n\ts_pid=$!\n\tsleep 1\n\n\tif [[ $OOB -eq 1 ]]; then\n\t\tc_arg=\"-E $S_INTERFACE\"\n\telse\n\t\tc_arg=\"-s $C_INTERFACE $S_INTERFACE\"\n\tfi\n\tc_cmd=\"${BIN_PATH}${test_exe} ${C_ARGS} $c_arg\"\n\t${CLIENT_CMD} \"${EXPORT_ENV} $c_cmd\" &> $c_outp &\n\tc_pid=$!\n\n\twait $c_pid\n\tc_ret=$?\n\n\t[[ c_ret -ne 0 ]] && kill -9 $s_pid 2> /dev/null\n\n\twait $s_pid\n\ts_ret=$?\n\n\tend_time=$(date '+%s')\n\ttest_time=$(compute_duration \"$start_time\" \"$end_time\")\n\n\tif [[ $STRICT_MODE -eq 0 && $s_ret -eq $FI_ENODATA && $c_ret -eq $FI_ENODATA ]] ||\n\t   [[ $STRICT_MODE -eq 0 && $s_ret -eq $FI_ENOSYS && $c_ret -eq $FI_ENOSYS ]]; then\n\t\tprint_results \"$test_exe\" \"Notrun\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\tskip_count+=1\n\telif [ $s_ret -ne 0 -o $c_ret -ne 0 ]; then\n\t\tprint_results \"$test_exe\" \"Fail\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\tif [ $s_ret -eq 124 -o $c_ret -eq 124 ]; then\n\t\t\tcleanup\n\t\tfi\n\t\tfail_count+=1\n\telse\n\t\tprint_results \"$test_exe\" \"Pass\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\tpass_count+=1\n\tfi\n}\n\nfunction set_cfg_file {\n\tlocal cfg_file\n\tlocal parent=$UTIL\n\tlocal name=$CORE\n\n\tif [ -z $UTIL ]; then\n\t\tparent=$CORE\n\t\tname=$1\n\tfi\n\n\tcfg_file=\"${PWD}/fabtests/test_configs/${parent}/${name}.test\"\n\tif [[ ! -f \"$cfg_file\" ]]; then\n\t\tcfg_file=\"${PWD}/test_configs/${parent}/${name}.test\"\n\t\tif [[ ! -f \"$cfg_file\" ]]; then\n\t\t\treturn\n\t\tfi\n\tfi\n\n\tCOMPLEX_CFG=${cfg_file}\n}\n\nfunction complex_test {\n\tlocal test=$1\n\tlocal config=$2\n\tlocal path=${PROV/;/\\/}\n\tlocal test_exe=\"${test}\"\n\tlocal s_ret=0\n\tlocal c_ret=0\n\tlocal start_time\n\tlocal end_time\n\tlocal test_time\n\n\tis_excluded \"$test\" && return\n\tif [[ -z \"$COMPLEX_CFG\" ]]; then\n\t\tset_cfg_file $config\n\tfi\n\n\tstart_time=$(date '+%s')\n\n\tif [[ $FORK -eq 1 ]]; then\n\t\topts=\"-f\"\n\telse\n\t\topts=\"\"\n\tfi\n\n\tif [[ $OOB -eq 1 ]]; then\n\t\topts+=\" -E\"\n\tfi\n\n\ts_cmd=\"${BIN_PATH}${test_exe} -x $opts\"\n\tFI_LOG_LEVEL=error ${SERVER_CMD} \"${EXPORT_ENV} $s_cmd\" &> $s_outp &\n\ts_pid=$!\n\tsleep 1\n\n\tc_cmd=\"${BIN_PATH}${test_exe} -u \"${COMPLEX_CFG}\" $S_INTERFACE $opts\"\n\tFI_LOG_LEVEL=error ${CLIENT_CMD} \"${EXPORT_ENV} $c_cmd\" &> $c_outp &\n\tc_pid=$!\n\n\twait $c_pid\n\tc_ret=$?\n\n\t[[ c_ret -ne 0 ]] && kill -9 $s_pid\n\n\twait $s_pid\n\ts_ret=$?\n\n\tend_time=$(date '+%s')\n\ttest_time=$(compute_duration \"$start_time\" \"$end_time\")\n\n\t# case: config file doesn't exist or invalid option provided\n\tif [ $s_ret -eq 1 -o $c_ret -eq 1 ]; then\n\t\tprint_results \"$test_exe\" \"Notrun\" \"0\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\tcleanup\n\t\tskip_count+=1\n\t\treturn\n\t# case: test didn't run becasue some error occured\n\telif [ $s_ret -ne 0 -o $c_ret -ne 0 ]; then\n\t\tprintf \"%-50s%s\\n\" \"$test_exe:\" \"Server returns $s_ret, client returns $c_ret\"\n\t\tprint_results \"$test_exe\" \"Fail [$f_cnt/$total]\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n                cleanup\n                fail_count+=1\n\telse\n\t\tlocal f_cnt=$(cat $c_outp | awk -F': ' '/ENOSYS|ERROR/ {total += $2} END {print total}')\n\t\tlocal s_cnt=$(cat $c_outp | awk -F': ' '/Success/ {total += $2} END {print total}')\n\t\tlocal total=$(cat $c_outp | awk -F': ' '/Success|ENODATA|ENOSYS|ERROR/ {total += $2} END {print total}')\n\t\tif [ $f_cnt -eq 0 ]; then\n\t\t\tprint_results \"$test_exe\" \"Pass [$s_cnt/$total]\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\t\tpass_count+=1\n\t\telse\n\t\t\tprint_results \"$test_exe\" \"Fail [$f_cnt/$total]\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"$c_outp\" \"$c_cmd\"\n\t\t\tcleanup\n\t\t\tfail_count+=1\n\t\tfi\n\tfi\n}\n\nfunction multinode_test {\n\tlocal test=\"$1\"\n\tlocal s_ret=0\n\tlocal c_ret=0\n\tlocal c_out_arr=()\n\tlocal num_procs=$2\n\tlocal test_exe=\"${test} -n $num_procs -p \\\"${PROV}\\\"\" \t\n\tlocal c_out\n\tlocal start_time\n\tlocal end_time\n\tlocal test_time\n\n\tis_excluded \"$test\" && return\n\n\tstart_time=$(date '+%s')\n\t\n\ts_cmd=\"${BIN_PATH}${test_exe} ${S_ARGS} -s ${S_INTERFACE}\"\n\t${SERVER_CMD} \"${EXPORT_ENV} $s_cmd\" &> $s_outp &\n\ts_pid=$!\n\tsleep 1\n\t\n\tc_pid_arr=()\t\n\tfor ((i=1; i<num_procs; i++))\n\tdo\n\t\tlocal c_out=$(mktemp fabtests.c_outp${i}.XXXXXX)\n\t\tc_cmd=\"${BIN_PATH}${test_exe} ${S_ARGS} -s ${S_INTERFACE}\"\n\t\t${CLIENT_CMD} \"${EXPORT_ENV} $c_cmd\" &> $c_out & \n\t\tc_pid_arr+=($!)\n\t\tc_out_arr+=($c_out)\n\tdone\n\n\tfor pid in ${c_pid_arr[*]}; do\n\t\twait $pid\n\t\tc_ret=($?)||$c_ret\n\tdone\n\t\n\t[[ c_ret -ne 0 ]] && kill -9 $s_pid 2> /dev/null\n\n\twait $s_pid\n\ts_ret=$?\n\techo \"server finished\"\n\t\n\tend_time=$(date '+%s')\n\ttest_time=$(compute_duration \"$start_time\" \"$end_time\")\n\t\n\tpe=1\n\tif [[ $STRICT_MODE -eq 0 && $s_ret -eq $FI_ENODATA && $c_ret -eq $FI_ENODATA ]] ||\n\t   [[ $STRICT_MODE -eq 0 && $s_ret -eq $FI_ENOSYS && $c_ret -eq $FI_ENOSYS ]]; then\n\t\tprint_results \"$test_exe\" \"Notrun\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"\" \"$c_cmd\"\n\t\tfor c_out in \"${c_out_arr[@]}\" \n\t\tdo\n\t\t\tprintf -- \"  client_stdout $pe: |\\n\"\n\t\t\tsed -e 's/^/    /' < $c_out\n\t\t\tpe=$((pe+1))\n\t\tdone\n\t\tskip_count+=1\n\telif [ $s_ret -ne 0 -o $c_ret -ne 0 ]; then\n\t\tprint_results \"$test_exe\" \"Fail\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"\" \"$c_cmd\"\n\t\tfor c_out in \"${c_out_arr[@]}\" \n\t\tdo\n\t\t\tprintf -- \"  client_stdout $pe: |\\n\"\n\t\t\tsed -e 's/^/    /' < $c_out\n\t\t\tpe=$((pe+1))\n\t\tdone\n\t\tif [ $s_ret -eq 124 -o $c_ret -eq 124 ]; then\n\t\t\tcleanup\n\t\tfi\n\t\tfail_count+=1\n\telse\n\t\tprint_results \"$test_exe\" \"Pass\" \"$test_time\" \"$s_outp\" \"$s_cmd\" \"\" \"$c_cmd\"\n\t\tfor c_out in \"${c_out_arr[@]}\" \n\t\tdo\n\t\t\tprintf -- \"  client_stdout $pe: |\\n\"\n\t\t\tsed -e 's/^/    /' < $c_out\n\t\t\tpe=$((pe+1))\n\t\tdone\n\t\tpass_count+=1\n\tfi\n}\n\nfunction set_core_util {\n\tprov_arr=$(echo $PROV | tr \";\" \" \")\n\tCORE=\"\"\n\tUTIL=\"\"\n\tfor p in $prov_arr; do\n\t\tif [[ -z $CORE ]]; then\n\t\t\tCORE=$p\n\t\telse\n\t\t\tUTIL=$p\n\t\tfi\n\tdone\n}\n\nfunction main {\n\tskip_count=0\n\tpass_count=0\n\tfail_count=0\n\tlocal complex_type=\"quick\"\n\n\tset_core_util\n\tset_excludes\n\t\n\n\tif [[ $1 == \"quick\" ]]; then\n\t\tlocal -r tests=\"unit functional short\"\n\telif [[ $1 == \"verify\" ]]; then\n\t\tlocal -r tests=\"complex\"\n\t\tcomplex_type=$1\n\telse\n\t\tlocal -r tests=$(echo $1 | sed 's/all/unit,functional,standard,complex,multinode/g' | tr ',' ' ')\n\t\tif [[ $1 == \"all\" || $1 == \"complex\" ]]; then\n\t\t\tcomplex_type=\"all\"\n\t\tfi\n\tfi\n\n\tif [ $VERBOSE -eq 0 ] ; then\n\t\tprintf \"# %-68s%10s\\n\" \"Test\" \"Result\"\n\t\tprint_border\n\tfi\n\n\tfor ts in ${tests}; do\n\tcase ${ts} in\n\t\tunit)\n\t\t\tfor test in \"${unit_tests[@]}\"; do\n\t\t\t\tunit_test \"$test\" \"0\"\n\t\t\tdone\n\n\t\t\tif [ $SKIP_NEG -eq 0 ] ; then\n\t\t\t\tfor test in \"${neg_unit_tests[@]}\"; do\n\t\t\t\t\tunit_test \"$test\" \"1\"\n\t\t\t\tdone\n\t\t\tfi\n\t\t;;\n\t\tfunctional)\n\t\t\tfor test in \"${functional_tests[@]}\"; do\n\t\t\t\tcs_test \"$test\"\n\t\t\tdone\n\t\t;;\n\t\tshort)\n\t\t\tfor test in \"${short_tests[@]}\"; do\n\t\t\t\tcs_test \"$test\"\n\t\t\tdone\n\t\t;;\n\t\tstandard)\n\t\t\tfor test in \"${standard_tests[@]}\"; do\n\t\t\t\tcs_test \"$test\"\n\t\t\tdone\n\t\t;;\n\t\tcomplex)\n\t\t\tfor test in \"${complex_tests[@]}\"; do\n\t\t\t\tcomplex_test $test $complex_type\n\t\t\tdone\n\t\t;;\n\t\tmultinode)\n\t\t\tfor test in \"${multinode_tests[@]}\"; do\n\t\t\t\t\tmultinode_test \"$test\" 3\n\t\t\tdone\n\t\t;;\n\t\t*)\n\t\t\terrcho \"Unknown test set: ${ts}\"\n\t\t\texit 1\n\t\t;;\n\tesac\n\tdone\n\n\ttotal=$(( $pass_count + $fail_count ))\n\n\tprint_border\n\n\tprintf \"# %-50s%10d\\n\" \"Total Pass\" $pass_count\n\tprintf \"# %-50s%10d\\n\" \"Total Notrun/Excluded\" $skip_count\n\tprintf \"# %-50s%10d\\n\" \"Total Fail\" $fail_count\n\n\tif [[ \"$total\" > \"0\" ]]; then\n\t\tprintf \"# %-50s%10d\\n\" \"Percentage of Pass\" $(( $pass_count * 100 / $total ))\n\tfi\n\n\tprint_border\n\n\tcleanup\n\ttotal_failures+=$fail_count\n}\n\nfunction usage {\n\terrcho \"Usage:\"\n\terrcho \"  $0 [OPTIONS] [provider] [host] [client]\"\n\terrcho\n\terrcho \"Run fabtests using provider between host and client (default\"\n\terrcho \"'sockets' provider in loopback-mode).  Report pass/fail/notrun status.\"\n\terrcho\n\terrcho \"Options:\"\n\terrcho -e \" -g\\tgood IP address from <host>'s perspective (default $GOOD_ADDR)\"\n\terrcho -e \" -v\\tprint output of failing\"\n\terrcho -e \" -vv\\tprint output of failing/notrun\"\n\terrcho -e \" -vvv\\tprint output of failing/notrun/passing\"\n\terrcho -e \" -t\\ttest set(s): all,quick,unit,functional,standard,short,complex (default quick)\"\n\terrcho -e \" -e\\texclude tests: comma delimited list of test names /\n\t\t\t regex patterns e.g. \\\"dgram,rma.*write\\\"\"\n\terrcho -e \" -E\\texport provided variable name and value to ssh client and server processes.\n\t\t\t options must of of the form '-E var=value'\"\n\terrcho -e \" -f\\texclude tests file: File containing list of test names /\n\t\t\t regex patterns to exclude (one per line)\"\n\terrcho -e \" -N\\tskip negative unit tests\"\n\terrcho -e \" -p\\tpath to test bins (default PATH)\"\n\terrcho -e \" -c\\tclient interface\"\n\terrcho -e \" -s\\tserver/host interface\"\n\terrcho -e \" -u\\tconfigure option for complex tests\"\n\terrcho -e \" -T\\ttimeout value in seconds\"\n\terrcho -e \" -S\\tStrict mode: -FI_ENODATA, -FI_ENOSYS errors would be treated as failures instead of skipped/notrun\"\n\terrcho -e \" -C\\tAdditional client test arguments: Parameters to pass to client fabtests\"\n\terrcho -e \" -L\\tAdditional server test arguments: Parameters to pass to server fabtests\"\n\terrcho -e \" -b\\tenable out-of-band address exchange over the default port\"\n\texit 1\n}\n\nwhile getopts \":vt:p:g:e:f:c:s:u:T:C:L:NRSbkE:\" opt; do\ncase ${opt} in\n\tt) TEST_TYPE=$OPTARG\n\t;;\n\tv) VERBOSE+=1\n\t;;\n\tp) BIN_PATH=\"${OPTARG}/\"\n\t;;\n\tg) GOOD_ADDR=${OPTARG}\n\t;;\n\tf) read_exclude_file ${OPTARG}\n\t;;\n\te) [[ -z \"$input_excludes\" ]] && input_excludes=${OPTARG} || \\\n\t\tinput_excludes=\"${input_excludes},${OPTARG}\"\n\t;;\n\tc) C_INTERFACE=${OPTARG}\n\t;;\n\ts) S_INTERFACE=${OPTARG}\n\t;;\n\tu) COMPLEX_CFG=${OPTARG}\n\t;;\n\tT) TIMEOUT_VAL=${OPTARG}\n\t;;\n\tN) SKIP_NEG+=1\n\t;;\n\tR)\n\t;;\n\tS) STRICT_MODE=1\n\t;;\n\tb) OOB=1\n\t;;\n\tk) FORK=1\n\t;;\n\tC) C_ARGS=\"${OPTARG}\"\n\t;;\n\tL) S_ARGS=\"${OPTARG}\"\n\t;;\n\tE)\n\tdelimiter=\"=\"\n\tvalue=${OPTARG#*$delimiter}\n\tvar=${OPTARG:0:$(( ${#OPTARG} - ${#value} - ${#delimiter} ))}\n\tEXPORT_STRING=\"export $var=\\\"$value\\\"\"\n\tif [[ -z $EXPORT_ENV ]] ; then\n\t\tEXPORT_ENV=\"$EXPORT_STRING ;\"\n\telse\n\t\tEXPORT_ENV=\"$EXPORT_ENV $EXPORT_STRING ;\"\n\tfi\n\t;;\n\t:|\\?) usage\n\t;;\nesac\n\ndone\n\n# base ssh command\ndeclare bssh=\"ssh -n -o StrictHostKeyChecking=no -o ConnectTimeout=2 -o BatchMode=yes\"\nif [ -z \"$(which timeout 2> /dev/null)\" ]; then\n\t# forego timeout\n\tdeclare SERVER_CMD=\"eval\"\n\tdeclare CLIENT_CMD=\"eval\"\nelse\n\tdeclare SERVER_CMD=\"eval timeout ${TIMEOUT_VAL}\"\n\tdeclare CLIENT_CMD=\"eval timeout ${TIMEOUT_VAL}\"\n\tbssh=\"timeout ${TIMEOUT_VAL} ${bssh}\"\nfi\n\n# shift past options\nshift $((OPTIND-1))\n\nif [[ $# -ge 4 ]]; then\n\tusage\nfi\n\nif [[ $# -ge 1 ]]; then\n\tPROV=$1\nfi\n\nif [[ $# -ge 2 ]]; then\n\tSERVER=$2\n\tSERVER_CMD=\"${bssh} ${SERVER}\"\nfi\n\nif [[ $# -ge 3 ]]; then\n\tCLIENT=$3\n\tCLIENT_CMD=\"${bssh} ${CLIENT}\"\nfi\n\n[ -z $C_INTERFACE ] && C_INTERFACE=$CLIENT\n[ -z $S_INTERFACE ] && S_INTERFACE=$SERVER\n[ -z $GOOD_ADDR ] && GOOD_ADDR=$S_INTERFACE\n\nif [[ -z $PROV ]]; then\n\tPROV=\"tcp\"\n\tmain ${TEST_TYPE}\n\tPROV=\"udp\"\n\tmain ${TEST_TYPE}\nelse\n\tmain ${TEST_TYPE}\nfi\n\nexit $total_failures\n", "num_lines": 886}
{"repo_name": "libfabric", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n########################################################################\n# This is a sample script for building the psm2 provider with three\n# different options:\n#\n# lib:  Link against external libpsm2.so;\n# src:  With PSM2 library source compiled in;\n# lto:  With PSM2 library source compiled in and with link-time\n#       optimization enabled.\n#\n# Please run the script from the top level directory of the source repo.\n#\n# The \"psm\", \"usnic\", and \"verbs\" providers are disabled to reduce the\n# building time. They can be enabled as needed.\n#\n# Please check that the following variables are either set to appropriate\n# values or can use the default values.\n#\n# PREFIX     Destination for installation\n# STAGE\t     Name for sub-directory used for building\n# PSM2_HOME  Location for PSM2 header and libraries (for \"lib\" build)\n# PSM2_SRC   Location for PSM2 source code (for \"src\" and \"lto\" builds)\n########################################################################\n\nif [ $# -eq 0 ]; then\n\techo Usage: $0 '[lib|src|lto]'\n\texit 1\nfi\n\ncase $1 in\n  lib)\toptions=\"\"\n\tcflags=\"\"\n\tldflags=\"\"\n\t;;\n  src)\toptions=\"--with-psm2-src=${PSM2_SRC:-$HOME/scm/opa-psm2}\"\n\tcflags='CFLAGS=\"-O3\"'\n\tldflags=\"\"\n\t;;\n  lto)\toptions=\"--with-psm2-src=${PSM2_SRC:-$HOME/scm/opa-psm2}\"\n\tcflags='CFLAGS=\"-O3 -flto -ffat-lto-objects -msse4.2\"'\n\tldflags='LDFLAGS=\"-fuse-linker-plugin -flto-partition=none\"'\n\t;;\n*)\techo Invalid option: \"$1\"\n\texit 1\n\t;;\nesac\n\nif [ ! -f ./autogen.sh ]; then\n\techo Please run the script from the top level directory.\n\texit 1\nfi\n\n./autogen.sh && \\\ncd ${STAGE:-stage} && \\\neval ../configure \\\n\t$cflags $ldflags $options \\\n\t--prefix=${PREFIX:-$HOME/install/ofi} \\\n\t--enable-psm2=${PSM2_HOME:-yes} \\\n\t--disable-psm \\\n\t--disable-usnic \\\n\t--disable-verbs && \\\nmake && make install\n\n", "num_lines": 64}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n#\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n#\n\nif [ -z \"$3\" ]; then\n    echo \"Missing one or more required params. Usage:\\nlmbr_pak_shaders.sh gameProjectName GLES3|METAL es3|ios|osx_gl [source shader list path]\"\n    exit 1\nfi\n\n# Extract an optional external engine path if present, otherwise use the cwd as the engine dir\nEXTERNAL_ENGINE_PATH=`cat engine.json | grep \"ExternalEnginePath\" | awk -F\":\" '{ print $2 }' | sed \"s/,//g\" | sed \"s/\\\"//g\" | xargs echo -n`\nif [ -z $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$(dirname \"$0\")\nelif [ -d $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$EXTERNAL_ENGINE_PATH\nelse\n    echo External Path in engine.json \"$EXTERNAL_ENGINE_PATH\" does not exist\n    exit 1\nfi\n\nBIN_FOLDER=`cat _WAF_/user_settings.options | grep \"out_folder_mac64\" | awk -F\"=\" '{ print $2 }' | sed \"s/^[ \\t]*//g\" | sed \"s/\\\"//g\" | xargs echo -n`\nif [ -z \"$BIN_FOLDER\" ]; then\n    echo Unable to find Mac64 bin output folder in _WAF/user_settings.options. Defaulting to BinMac64.\n    BIN_FOLDER=\"BinMac64\"\nfi\n\npy=\"$ENGINE_DIR/Tools/Python/python3.sh\"\ngame=\"$1\"\nshader_type=\"$2\"\nasset_platform=\"$3\"\nsource_shader_list=\"$4\"\n\ngen_args=\"$game $asset_platform $shader_type -b $BIN_FOLDER -e $ENGINE_DIR\"\nif [ ! -z $source_shader_list ]; then\n    gen_args=$gen_args -s $source_shader_list\nfi\n\nenv $py \"$ENGINE_DIR/Tools/PakShaders/gen_shaders.py\" $gen_args\n\nif [ $? -ne 0 ]; then\n    echo Failed to generate shaders.\n    exit 1\nfi\n\nsource=\"Cache/$game/$asset_platform/user/cache/shaders/cache\"\noutput=\"Build/$asset_platform/$game\"\n\nenv $py \"$ENGINE_DIR/Tools/PakShaders/pak_shaders.py\" $output -r $source -s $shader_type\n\nif [ $? -ne 0 ]; then\n    echo Failed to pack shaders.\n    exit 1\nfi\n\n", "num_lines": 65}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n#\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n#\n\n# Extract an optional external engine path if present, otherwise use the cwd as the engine dir\nEXTERNAL_ENGINE_PATH=`cat engine.json | grep \"ExternalEnginePath\" | awk -F\":\" '{ print $2 }' | sed \"s/,//g\" | sed \"s/\\\"//g\" | xargs echo -n`\nif [ -z $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$(dirname \"$0\")\nelif [ -d $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$EXTERNAL_ENGINE_PATH\nelse\n    echo External Path in engine.json \"$EXTERNAL_ENGINE_PATH\" does not exist\n    exit 1\nfi\n\nPYP=$ENGINE_DIR/Code/Tools/AzTestScanner\nenv PYTHONPATH=$PYP $ENGINE_DIR/Tools/Python/python3.sh -m aztest $*\n", "num_lines": 28}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# Original file Copyright Crytek GMBH or its affiliates, used under license.\n#\npushd_silent()\n{\n    pushd \"$@\" > /dev/null\n}\n\npopd_silent()\n{\n    popd \"$@\" > /dev/null\n}\n\nTIME=\"`date +%Y%m%d%H%M%S`\"\nexport COMMAND_ID=\"$COMPUTERNAME-$TIME\"\nif [ -n \"$BUILD_TAG\" ]; then\n    if [ -n \"$P4_CHANGELIST\" ]; then\n        export COMMAND_ID=\"$BUILD_TAG.$P4_CHANGELIST-$TIME\"\n    fi\nfi\n\npushd_silent $(dirname \"$0\")\n\n# Extract an optional external engine path if present, otherwise use the cwd as the engine dir\nEXTERNAL_ENGINE_PATH=`cat engine.json | grep \"ExternalEnginePath\" | awk -F\":\" '{ print $2 }' | sed \"s/,//g\" | sed \"s/\\\"//g\" | xargs echo -n`\nif [ -z $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$(dirname \"$0\")\nelif [ -d $EXTERNAL_ENGINE_PATH ]; then\n    ENGINE_DIR=$EXTERNAL_ENGINE_PATH\nelse\n    echo External Path in engine.json \"$EXTERNAL_ENGINE_PATH\" does not exist\n    exit 1\nfi\n\necho [WAF] Engine Root: $ENGINE_DIR\n\nPYTHON_PATH=\"$ENGINE_DIR/Tools/Python\"\n\nPYTHON_EXECUTABLE=$PYTHON_PATH/python3.sh\n\nbash $PYTHON_EXECUTABLE \"$ENGINE_DIR/Tools/build/waf-1.7.13/lmbr_waf\" \"$@\"\n\nRESULT=$?\n\npushd_silent $ENGINE_DIR\n\nif [ -f \"Tools/build/waf-1.7.13/build_metrics/build_metrics_overrides.py\" ]; then\n    if [ $RESULT -eq 0 ]; then\n        bash $PYTHON_EXECUTABLE Tools/build/waf-1.7.13/build_metrics/write_build_metric.py WafBuildResult 1 Unitless $*\n        if [ -f \"build_metrics.txt\" ]; then\n            env sed -i -e 's/#BUILD_RESULT#/True/g' build_metrics.txt\n        fi\n    else\n        if [ -f \"build_metrics.txt\" ]; then\n            bash $PYTHON_EXECUTABLE Tools/build/waf-1.7.13/build_metrics/write_build_metric.py WafBuildResult 0 Unitless $*\n            env sed -i -e 's/#BUILD_RESULT#/False/g' build_metrics.txt\n        fi\n    fi\nfi\n\npopd_silent\npopd_silent\nexit $RESULT", "num_lines": 74}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n#\n#!/bin/sh\n\necho \"=====================================================\"\necho \"This is a sample script to create a GameLift package.\"\necho \"You may need to adapt it for your own use.\"\necho \"=====================================================\"\necho \"\"\n\nif [ -d GameLiftPackageLinux ]\nthen\n    echo \"Cleaning directory GameLiftPackageLinux\"\n    rm -rf GameLiftPackageLinux\nfi\n\necho \"Creating directory GameLiftPackageLinux\"\nmkdir -p GameLiftPackageLinux\n\necho \"Copying required assets\"\nif [ -d MultiplayerSample_pc_Paks_Dedicated ]\nthen\n    cp -a MultiplayerSample_pc_Paks_Dedicated/* GameLiftPackageLinux/.\nelif [ -d multiplayersample_pc_paks ]\nthen\n    cp -a multiplayersample_pc_paks/* GameLiftPackageLinux/.\nelse\n    echo \"Failed to find required assets.\"\n    exit 1\nfi\n\necho \"Copying Server binaries\"\ncopied_game_binaries=false\n\necho \".... Looking for binaries in BinLinux64.Release.Dedicated\"\nif [ -d BinLinux64.Release.Dedicated ];\nthen\n    cp -a BinLinux64.Release.Dedicated/* GameLiftPackageLinux/.\n    copied_game_binaries=true\nfi\n\nif [ \"$copied_game_binaries\" == false ]; \nthen\n    echo \".... Looking for binaries in BinLinux64.Performance.Dedicated\"\n    if [ -d BinLinux64.Performance.Dedicated ]\n    then\n       cp -a BinLinux64.Performance.Dedicated/* GameLiftPackageLinux/.\n       copied_game_binaries=true\n    fi\nfi\n\nif [ \"$copied_game_binaries\" = false ]; \nthen\n    echo \".... Looking for binaries in BinLinux64.Dedicated\"\n    if [ -d BinLinux64.Dedicated ]\n    then\n        cp -a BinLinux64.Dedicated/* GameLiftPackageLinux/.\n        copied_game_binaries=true\n    fi\nfi\n\nif [ \"$copied_game_binaries\" == false ]; \nthen\n    echo \"Failed to find game binaries\"\n    exit 2\nelse \n    echo \".... Server binaries copied\"\nfi\n\necho \"Copying libc++ and libc++abi libs\"\nif [ -f /usr/lib/x86_64-linux-gnu/libc++.a ]\nthen\n    mkdir -p GameLiftPackageLinux/lib64\n    cp -a /usr/lib/x86_64-linux-gnu/libc++* GameLiftPackageLinux/lib64/.\nelse\n    echo \"Failed to find libc++ and lib++abi libs\"\n    exit 3\nfi \n\necho \"Copying ca-certificates.crt\"\nif [ -f /etc/ssl/certs/ca-certificates.crt ]\nthen\n    cp -a /etc/ssl/certs/ca-certificates.crt GameLiftPackageLinux/.\nelse\n    echo \"Failed to find and copy /etc/ssl/certs/ca-certificates.crt\"\n    echo \"Without a valid root certificate, your server may not be able to validate and access AWS endpoints. If you see Curl error code 77 in your server logs, this is a likely cause.\"\nfi \n\necho \"Creating install.sh\"\necho \"#!/bin/sh\" >> GameLiftPackageLinux/install.sh\necho \"\" >> GameLiftPackageLinux/install.sh\necho \"sudo cp -a ./lib64/* /lib64/.\" >> GameLiftPackageLinux/install.sh\n\n# the following line is optional so we ignore the copy command error code \necho \"sudo cp ./ca-certificates.crt /etc/ssl/certs/ca-certificates.crt || :\" >> GameLiftPackageLinux/install.sh\n\n\n# Extra Setup for GameLift Amazon Linux 2 instace building on Ubuntu 18.04. AL2 has glibc-2.26 by default. Ubuntu 18.04 uses glibc-2.27 by default.\n# Compiling and Installing glibc-2.27. Development tools installs dependencies required to install glibc.\n\n\n. /etc/os-release\nif [[ $VERSION == *\"18.04\"* ]]\nthen\n    echo \"if cat /etc/system-release | grep -qFe 'Amazon Linux release 2'\" >> GameLiftPackageLinux/install.sh\n    echo \"then\" >> GameLiftPackageLinux/install.sh\n    echo \" echo 'Installing missing libs for AL2'\" >> GameLiftPackageLinux/install.sh\n    echo \" sudo yum groupinstall 'Development Tools' -y\" >> GameLiftPackageLinux/install.sh\n    echo \" mkdir glibc && cd glibc\" >> GameLiftPackageLinux/install.sh\n    echo \" wget http://mirror.rit.edu/gnu/libc/glibc-2.27.tar.gz\" >> GameLiftPackageLinux/install.sh\n    echo \" tar zxvf glibc-2.27.tar.gz\" >> GameLiftPackageLinux/install.sh\n    echo \" mkdir glibc-2.27-build glibc-2.27-install\" >> GameLiftPackageLinux/install.sh\n    echo \" cd glibc-2.27-build\" >> GameLiftPackageLinux/install.sh\n    echo \" /local/game/glibc/glibc-2.27/configure --prefix='/local/game/glibc/glibc-2.27-install'\" >> GameLiftPackageLinux/install.sh\n    echo \" make -j 8\" >> GameLiftPackageLinux/install.sh\n    echo \" make -j 8 install\" >> GameLiftPackageLinux/install.sh\n    echo \" sudo ln -sf /local/game/glibc/glibc-2.27-install/lib/libm.so.6 /local/game/libm.so.6\" >> GameLiftPackageLinux/install.sh\n    echo \"cd /local/game/\" >> GameLiftPackageLinux/install.sh\n    echo \"fi\" >> GameLiftPackageLinux/install.sh\nfi\n\n\necho \"echo 'Install Success'\" >> GameLiftPackageLinux/install.sh\n\nchmod +x GameLiftPackageLinux/install.sh\nchmod 775 -R GameLiftPackageLinux/*\n\necho \"GameLift package created successfully: GameLiftPackageLinux\"\n\n", "num_lines": 139}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Executes the samples and tests for the Google Test Framework.\n\n# Help the dynamic linker find the path to the libraries.\nexport DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR\nexport DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR\n\n# Create some executables.\ntest_executables=$@\n\n# Now execute each one in turn keeping track of how many succeeded and failed.\nsucceeded=0\nfailed=0\nfailed_list=()\nfor test in ${test_executables[*]}; do\n  \"$test\"\n  result=$?\n  if [ $result -eq 0 ]; then\n    succeeded=$(( $succeeded + 1 ))\n  else\n    failed=$(( failed + 1 ))\n    failed_list=\"$failed_list $test\"\n  fi\ndone\n\n# Report the successes and failures to the console.\necho \"Tests complete with $succeeded successes and $failed failures.\"\nif [ $failed -ne 0 ]; then\n  echo \"The following tests failed:\"\n  echo $failed_list\nfi\nexit $failed\n", "num_lines": 63}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2008, Google Inc.\n# All rights reserved.\n#\n# Redistribution and use in source and binary forms, with or without\n# modification, are permitted provided that the following conditions are\n# met:\n#\n#     * Redistributions of source code must retain the above copyright\n# notice, this list of conditions and the following disclaimer.\n#     * Redistributions in binary form must reproduce the above\n# copyright notice, this list of conditions and the following disclaimer\n# in the documentation and/or other materials provided with the\n# distribution.\n#     * Neither the name of Google Inc. nor the names of its\n# contributors may be used to endorse or promote products derived from\n# this software without specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n# Executes the samples and tests for the Google Test Framework.\n\n# Help the dynamic linker find the path to the libraries.\nexport DYLD_FRAMEWORK_PATH=$BUILT_PRODUCTS_DIR\nexport DYLD_LIBRARY_PATH=$BUILT_PRODUCTS_DIR\n\n# Create some executables.\ntest_executables=(\"$BUILT_PRODUCTS_DIR/gtest_unittest-framework\"\n                  \"$BUILT_PRODUCTS_DIR/gtest_unittest\"\n                  \"$BUILT_PRODUCTS_DIR/sample1_unittest-framework\"\n                  \"$BUILT_PRODUCTS_DIR/sample1_unittest-static\")\n\n# Now execute each one in turn keeping track of how many succeeded and failed. \nsucceeded=0\nfailed=0\nfailed_list=()\nfor test in ${test_executables[*]}; do\n  \"$test\"\n  result=$?\n  if [ $result -eq 0 ]; then\n    succeeded=$(( $succeeded + 1 ))\n  else\n    failed=$(( failed + 1 ))\n    failed_list=\"$failed_list $test\"\n  fi\ndone\n\n# Report the successes and failures to the console.\necho \"Tests complete with $succeeded successes and $failed failures.\"\nif [ $failed -ne 0 ]; then\n  echo \"The following tests failed:\"\n  echo $failed_list\nfi\nexit $failed\n", "num_lines": 66}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Written and maintained by the.arul@gmail.com (2014)\n#\n\nBUILD_DIR=\"./lib/iOS\"\n\n###################################\n# \t\t SDK Version\n###################################\nIOS_SDK_VERSION=$(xcodebuild -version -sdk iphoneos | grep SDKVersion | cut -f2 -d ':' | tr -d '[[:space:]]')\n###################################\n\n###################################\n# \t\t BUILD Configuration\n###################################\n\nBUILD_SHARED_LIBS=OFF\nBUILD_TYPE=Release\n\n################################################\n# \t\t Minimum iOS deployment target version\n################################################\nMIN_IOS_VERSION=\"6.0\"\n\nIOS_SDK_TARGET=$MIN_IOS_VERSION\nXCODE_ROOT_DIR=$(xcode-select  --print-path)\nTOOLCHAIN=$XCODE_ROOT_DIR/Toolchains/XcodeDefault.xctoolchain\n\nCMAKE_C_COMPILER=$(xcrun -find cc)\nCMAKE_CXX_COMPILER=$(xcrun -find c++)\n\nBUILD_ARCHS_DEVICE=\"arm64e arm64 armv7s armv7\"\nBUILD_ARCHS_SIMULATOR=\"x86_64 i386\"\nBUILD_ARCHS_ALL=($BUILD_ARCHS_DEVICE $BUILD_ARCHS_SIMULATOR)\n\nCPP_DEV_TARGET_LIST=(miphoneos-version-min mios-simulator-version-min)\nCPP_DEV_TARGET=\nCPP_STD_LIB_LIST=(libc++ libstdc++)\nCPP_STD_LIB=\nCPP_STD_LIST=(c++11 c++14)\nCPP_STD=c++11\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\n\nbuild_arch()\n{\n    IOS_SDK_DEVICE=iPhoneOS\n    CPP_DEV_TARGET=${CPP_DEV_TARGET_LIST[0]}\n\n    if [[ \"$BUILD_ARCHS_SIMULATOR\" =~ \"$1\" ]]\n    then\n        echo '[!] Target SDK set to SIMULATOR.'\n        IOS_SDK_DEVICE=iPhoneSimulator\n        CPP_DEV_TARGET=${CPP_DEV_TARGET_LIST[1]}\n    else\n        echo '[!] Target SDK set to DEVICE.'\n    fi\n\n    unset DEVROOT SDKROOT CFLAGS LDFLAGS CPPFLAGS CXXFLAGS CMAKE_CLI_INPUT\n           \n\t#export CC=\"$(xcrun -sdk iphoneos -find clang)\"\n    #export CPP=\"$CC -E\"\n    export DEVROOT=$XCODE_ROOT_DIR/Platforms/$IOS_SDK_DEVICE.platform/Developer\n    export SDKROOT=$DEVROOT/SDKs/$IOS_SDK_DEVICE$IOS_SDK_VERSION.sdk\n    export CFLAGS=\"-arch $1 -pipe -no-cpp-precomp -stdlib=$CPP_STD_LIB -isysroot $SDKROOT -I$SDKROOT/usr/include/ -miphoneos-version-min=$IOS_SDK_TARGET\"\n     if [[ \"$BUILD_TYPE\" =~ \"Debug\" ]]; then\n      export CFLAGS=\"$CFLAGS -Og\"\n     else\n\t     export CFLAGS=\"$CFLAGS -O3\"\n     fi\n    export LDFLAGS=\"-arch $1 -isysroot $SDKROOT -L$SDKROOT/usr/lib/\"\n    export CPPFLAGS=\"$CFLAGS\"\n    export CXXFLAGS=\"$CFLAGS -std=$CPP_STD\"\n\n    rm CMakeCache.txt\n    \n    CMAKE_CLI_INPUT=\"-DCMAKE_C_COMPILER=$CMAKE_C_COMPILER -DCMAKE_CXX_COMPILER=$CMAKE_CXX_COMPILER -DCMAKE_TOOLCHAIN_FILE=./port/iOS/IPHONEOS_$(echo $1 | tr '[:lower:]' '[:upper:]')_TOOLCHAIN.cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE -DENABLE_BOOST_WORKAROUND=ON -DBUILD_SHARED_LIBS=$BUILD_SHARED_LIBS\"\n    \n    echo \"[!] Running CMake with -G 'Unix Makefiles' $CMAKE_CLI_INPUT\"\n    \n    cmake -G 'Unix Makefiles' ${CMAKE_CLI_INPUT}\n\n    echo \"[!] Building $1 library\"\n\n    xcrun -run make clean\n    xcrun -run make assimp -j 8 -l    \n    \n    if [[ \"$BUILD_SHARED_LIBS\" =~ \"ON\" ]]; then\n    \techo \"[!] Moving built dynamic libraries into: $BUILD_DIR/$1/\"\n    \tmv ./lib/*.dylib  $BUILD_DIR/$1/\n    fi\n    \n    echo \"[!] Moving built static libraries into: $BUILD_DIR/$1/\"\n    mv ./lib/*.a $BUILD_DIR/$1/\t   \n}\n\necho \"[!] $0 - assimp iOS build script\"\n\nCPP_STD_LIB=${CPP_STD_LIB_LIST[0]}\nCPP_STD=${CPP_STD_LIST[0]}\nDEPLOY_ARCHS=${BUILD_ARCHS_ALL[*]}\nDEPLOY_FAT=1\n\nfor i in \"$@\"; do\n    case $i in\n    -s=*|--std=*)\n        CPP_STD=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`\n        echo \"[!] Selecting c++ standard: $CPP_STD\"\n    ;;\n    -l=*|--stdlib=*)\n        CPP_STD_LIB=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`\n        echo \"[!] Selecting c++ std lib: $CPP_STD_LIB\"\n    ;;\n    -a=*|--archs=*)\n        DEPLOY_ARCHS=`echo $i | sed 's/[-a-zA-Z0-9]*=//'`\n        echo \"[!] Selecting architectures: $DEPLOY_ARCHS\"\n    ;;\n    --debug)\n    \tBUILD_TYPE=Debug        \n        echo \"[!] Selecting build type: Debug\"\n    ;;\n    --shared-lib)\n    \tBUILD_SHARED_LIBS=ON        \n        echo \"[!] Will generate dynamic libraries\"\n    ;;\n    -n|--no-fat)\n        DEPLOY_FAT=0\n        echo \"[!] Fat binary will not be created.\"\n    ;;\n    -h|--help)\n        echo \" - don't build fat library (--no-fat).\"\n        echo \" - Include debug information and symbols, no compiler optimizations (--debug).\"\n        echo \" - generate dynamic libraries rather than static ones (--shared-lib).\"\n        echo \" - supported architectures (--archs):  $(echo $(join , ${BUILD_ARCHS_ALL[*]}) | sed 's/,/, /g')\"\n        echo \" - supported C++ STD libs (--stdlib): $(echo $(join , ${CPP_STD_LIB_LIST[*]}) | sed 's/,/, /g')\"\n        echo \" - supported C++ standards (--std): $(echo $(join , ${CPP_STD_LIST[*]}) | sed 's/,/, /g')\"\n        exit\n    ;;\n    *)\n    ;;\n    esac\ndone\n\ncd ../../\nrm -rf $BUILD_DIR\n\nfor ARCH_TARGET in $DEPLOY_ARCHS; do\n\techo \"Creating folder: $BUILD_DIR/$ARCH_TARGET\"\n    mkdir -p $BUILD_DIR/$ARCH_TARGET\n    echo \"Building for arc: $ARCH_TARGET\" \n    build_arch $ARCH_TARGET\n    #rm ./lib/libassimp.a\ndone\n\n\nmake_fat_static_or_shared_binary()\n{\n\tLIB_NAME=$1\n\tLIPO_ARGS=''\n    for ARCH_TARGET in $DEPLOY_ARCHS; do\n        if [[ \"$BUILD_SHARED_LIBS\" =~ \"ON\" ]]; then\n            LIPO_ARGS=\"$LIPO_ARGS-arch $ARCH_TARGET $BUILD_DIR/$ARCH_TARGET/$LIB_NAME.dylib \"\n        else\n            LIPO_ARGS=\"$LIPO_ARGS-arch $ARCH_TARGET $BUILD_DIR/$ARCH_TARGET/$LIB_NAME.a \"\n        fi\n    done\n    if [[ \"$BUILD_SHARED_LIBS\" =~ \"ON\" ]]; then\n    \tLIPO_ARGS=\"$LIPO_ARGS -create -output $BUILD_DIR/$LIB_NAME-fat.dylib\"\n    else\n    \tLIPO_ARGS=\"$LIPO_ARGS -create -output $BUILD_DIR/$LIB_NAME-fat.a\"\n    fi\n    lipo $LIPO_ARGS\n}\n\nmake_fat_static_binary()\n{\n\tLIB_NAME=$1\n\tLIPO_ARGS=''\n    for ARCH_TARGET in $DEPLOY_ARCHS; do\n        LIPO_ARGS=\"$LIPO_ARGS-arch $ARCH_TARGET $BUILD_DIR/$ARCH_TARGET/$LIB_NAME.a \"\n    done\n    LIPO_ARGS=\"$LIPO_ARGS -create -output $BUILD_DIR/$LIB_NAME-fat.a\"\n    lipo $LIPO_ARGS\n}\n\nif [[ \"$DEPLOY_FAT\" -eq 1 ]]; then\n    echo '[+] Creating fat binaries ...'\n    \n    if [[ \"$BUILD_TYPE\" =~ \"Debug\" ]]; then\n    \tmake_fat_static_or_shared_binary 'libassimpd'\n\t    make_fat_static_binary 'libIrrXMLd'\n\t    make_fat_static_binary 'libzlibstaticd'\n\telse\n\t\tmake_fat_static_or_shared_binary 'libassimp'\n\t    make_fat_static_binary 'libIrrXML'\n\t    make_fat_static_binary 'libzlibstatic'\n\tfi\n    \n    echo \"[!] Done! The fat binaries can be found at $BUILD_DIR\"\nfi\n\n\n\n", "num_lines": 206}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\ngcc -shared -fPIC -g3 -I../../../include/ -lassimp -olibassimp_wrap.so assimp_wrap.cxx\n", "num_lines": 3}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nrm -rf assimp/\nmkdir assimp\nswig -c++ -d -outcurrentdir -I../../../include -splitproxy -package assimp $@ ../assimp.i\n", "num_lines": 5}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "declare -a headers=(\"fast_atof.h\"\n  \"qnan.h\"\n  \"BaseImporter.h\"\n  \"Hash.h\"\n  \"MemoryIOWrapper.h\"\n  \"ParsingUtils.h\"\n  \"StreamReader.h\"\n  \"StreamWriter.h\"\n  \"StringComparison.h\"\n  \"StringUtils.h\"\n  \"SGSpatialSort.h\"\n  \"GenericProperty.h\"\n  \"SpatialSort.h\"\n  \"SkeletonMeshBuilder.h\"\n  \"SmoothingGroups.h\"\n  \"StandardShapes.h\"\n  \"RemoveComments.h\"\n  \"Subdivision.h\"\n  \"Vertex.h\"\n  \"LineSplitter.h\"\n  \"TinyFormatter.h\"\n  \"Profiler.h\"\n  \"LogAux.h\"\n  \"Bitmap.h\"\n  \"XMLTools.h\"\n  \"IOStreamBuffer.h\"\n  \"CreateAnimMesh.h\"\n  \"irrXMLWrapper.h\"\n  \"BlobIOSystem.h\"\n  \"MathFunctions.h\"\n  \"Macros.h\"\n  \"Exceptional.h\"\n  \"ByteSwapper.h\")\n\nfor i in \"${headers[@]}\"\ndo\n  find . -type f -exec sed -i \"s,<../code/$i>,<assimp/$i>,g\" {} \\;\ndone\n", "num_lines": 39}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\ncd ../../code\ngrep -E 'Ifc([A-Z][a-z]*)+' -o IFCLoader.cpp IFCGeometry.cpp IFCCurve.cpp IFCProfile.cpp IFCMaterial.cpp | uniq | sed s/.*:// > ../scripts/IFCImporter/output.txt\n", "num_lines": 4}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -x\n\nopenssl version | tee openssl_version.txt\n\n# Private key\nopenssl ecparam -name prime256v1 -genkey -noout -conv_form uncompressed -out ecc_p256_private.pem\nopenssl ec -in ecc_p256_private.pem -outform DER -out ecc_p256_private.der\nopenssl pkcs8 -in ecc_p256_private.der -inform DER -out ecc_p256_private_p8_clear.der -outform DER -nocrypt -topk8\nopenssl pkcs8 -in ecc_p256_private.der -inform DER -out ecc_p256_private_p8_clear.pem -outform PEM -nocrypt -topk8\nopenssl ec -in ecc_p256_private.pem -text -out ecc_p256.txt\n\n# Encrypted private key\nopenssl pkcs8 -in ecc_p256_private.der -inform DER -passout 'pass:secret' -out ecc_p256_private_p8.der -outform DER -topk8\nopenssl pkcs8 -in ecc_p256_private.der -inform DER -passout 'pass:secret' -out ecc_p256_private_p8.pem -outform PEM -topk8\nopenssl ec -in ecc_p256_private.pem -des3 -out ecc_p256_private_enc_des3.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p256_private.pem -aes128 -out ecc_p256_private_enc_aes128.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p256_private.pem -aes192 -out ecc_p256_private_enc_aes192.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p256_private.pem -aes256 -out ecc_p256_private_enc_aes256.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p256_private.pem -aes-256-gcm -out ecc_p256_private_enc_aes256_gcm.pem -passout 'pass:secret' -outform PEM\n\n# Public key\nopenssl ec -in ecc_p256_private.pem -pubout -out ecc_p256_public.pem\nopenssl ec -pubin -in ecc_p256_public.pem -outform DER -out ecc_p256_public.der\nopenssl ec -pubin -in ecc_p256_public.pem -outform DER -conv_form compressed -out ecc_p256_public_compressed.der\nopenssl ec -pubin -in ecc_p256_public.pem -outform PEM -conv_form compressed -out ecc_p256_public_compressed.pem\n\n# X.509 cert\nopenssl req -new -key ecc_p256_private.pem -days 365 -x509 -out ecc_p256_x509.pem -subj '/C=GB/CN=example.com'\nopenssl x509 -in ecc_p256_x509.pem -out ecc_p256_x509.der -outform DER\n\n# OpenSSH\nchmod 600 ecc_p256_private.pem\nssh-keygen -f ecc_p256_private.pem -y > ecc_p256_public_openssh.txt\n\nssh-keygen -t ecdsa -b 256 -f ecc_p256_private_openssh.pem -P \"\"\ncp -fa ecc_p256_private_openssh.pem ecc_p256_private_openssh_old.pem\nssh-keygen -p -f ecc_p256_private_openssh_old.pem -m PEM -N \"\"\n\nssh-keygen -t ecdsa -b 256 -f ecc_p256_private_openssh_pwd.pem -P \"password\"\ncp -fa ecc_p256_private_openssh_pwd.pem ecc_p256_private_openssh_pwd_old.pem\nssh-keygen -p -f ecc_p256_private_openssh_pwd_old.pem -m PEM -N \"\" -P \"password\"\n\n# Legacy OpenSSL format with ECPARAMs\nopenssl ecparam -name prime256v1 -genkey -out ecc_p256_private_ecparams.pem\n", "num_lines": 48}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -x\n\nopenssl version | tee openssl_version_p384.txt\n\n# Private key\nopenssl ecparam -name secp384r1 -genkey -noout -conv_form uncompressed -out ecc_p384_private.pem\nopenssl ec -in ecc_p384_private.pem -outform DER -out ecc_p384_private.der\nopenssl pkcs8 -in ecc_p384_private.der -inform DER -out ecc_p384_private_p8_clear.der -outform DER -nocrypt -topk8\nopenssl pkcs8 -in ecc_p384_private.der -inform DER -out ecc_p384_private_p8_clear.pem -outform PEM -nocrypt -topk8\nopenssl ec -in ecc_p384_private.pem -text -out ecc_p384.txt\n\n# Encrypted private key\nopenssl pkcs8 -in ecc_p384_private.der -inform DER -passout 'pass:secret' -out ecc_p384_private_p8.der -outform DER -topk8\nopenssl pkcs8 -in ecc_p384_private.der -inform DER -passout 'pass:secret' -out ecc_p384_private_p8.pem -outform PEM -topk8\nopenssl ec -in ecc_p384_private.pem -des3 -out ecc_p384_private_enc_des3.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p384_private.pem -aes128 -out ecc_p384_private_enc_aes128.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p384_private.pem -aes192 -out ecc_p384_private_enc_aes192.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p384_private.pem -aes256 -out ecc_p384_private_enc_aes256.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p384_private.pem -aes-256-gcm -out ecc_p384_private_enc_aes256_gcm.pem -passout 'pass:secret' -outform PEM\n\n# Public key\nopenssl ec -in ecc_p384_private.pem -pubout -out ecc_p384_public.pem\nopenssl ec -pubin -in ecc_p384_public.pem -outform DER -out ecc_p384_public.der\nopenssl ec -pubin -in ecc_p384_public.pem -outform DER -conv_form compressed -out ecc_p384_public_compressed.der\nopenssl ec -pubin -in ecc_p384_public.pem -outform PEM -conv_form compressed -out ecc_p384_public_compressed.pem\n\n# X.509 cert\nopenssl req -new -key ecc_p384_private.pem -days 365 -x509 -out ecc_p384_x509.pem -subj '/C=GB/CN=example.com'\nopenssl x509 -in ecc_p384_x509.pem -out ecc_p384_x509.der -outform DER\n\n# OpenSSH\nchmod 600 ecc_p384_private.pem\nssh-keygen -f ecc_p384_private.pem -y > ecc_p384_public_openssh.txt\n\nssh-keygen -t ecdsa -b 384 -f ecc_p384_private_openssh.pem -P \"\"\ncp -fa ecc_p384_private_openssh.pem ecc_p384_private_openssh_old.pem\nssh-keygen -p -f ecc_p384_private_openssh_old.pem -m PEM -N \"\"\n\nssh-keygen -t ecdsa -b 384 -f ecc_p384_private_openssh_pwd.pem -P \"password\"\ncp -fa ecc_p384_private_openssh_pwd.pem ecc_p384_private_openssh_pwd_old.pem\nssh-keygen -p -f ecc_p384_private_openssh_pwd_old.pem -m PEM -N \"\" -P \"password\"\n", "num_lines": 45}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -x\n\nopenssl version | tee openssl_version_p521.txt\n\n# Private key\nopenssl ecparam -name secp521r1 -genkey -noout -conv_form uncompressed -out ecc_p521_private.pem\nopenssl ec -in ecc_p521_private.pem -outform DER -out ecc_p521_private.der\nopenssl pkcs8 -in ecc_p521_private.der -inform DER -out ecc_p521_private_p8_clear.der -outform DER -nocrypt -topk8\nopenssl pkcs8 -in ecc_p521_private.der -inform DER -out ecc_p521_private_p8_clear.pem -outform PEM -nocrypt -topk8\nopenssl ec -in ecc_p521_private.pem -text -out ecc_p521.txt\n\n# Encrypted private key\nopenssl pkcs8 -in ecc_p521_private.der -inform DER -passout 'pass:secret' -out ecc_p521_private_p8.der -outform DER -topk8\nopenssl pkcs8 -in ecc_p521_private.der -inform DER -passout 'pass:secret' -out ecc_p521_private_p8.pem -outform PEM -topk8\nopenssl ec -in ecc_p521_private.pem -des3 -out ecc_p521_private_enc_des3.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p521_private.pem -aes128 -out ecc_p521_private_enc_aes128.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p521_private.pem -aes192 -out ecc_p521_private_enc_aes192.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p521_private.pem -aes256 -out ecc_p521_private_enc_aes256.pem -passout 'pass:secret' -outform PEM\nopenssl ec -in ecc_p521_private.pem -aes-256-gcm -out ecc_p521_private_enc_aes256_gcm.pem -passout 'pass:secret' -outform PEM\n\n# Public key\nopenssl ec -in ecc_p521_private.pem -pubout -out ecc_p521_public.pem\nopenssl ec -pubin -in ecc_p521_public.pem -outform DER -out ecc_p521_public.der\nopenssl ec -pubin -in ecc_p521_public.pem -outform DER -conv_form compressed -out ecc_p521_public_compressed.der\nopenssl ec -pubin -in ecc_p521_public.pem -outform PEM -conv_form compressed -out ecc_p521_public_compressed.pem\n\n# X.509 cert\nopenssl req -new -key ecc_p521_private.pem -days 365 -x509 -out ecc_p521_x509.pem -subj '/C=GB/CN=example.com'\nopenssl x509 -in ecc_p521_x509.pem -out ecc_p521_x509.der -outform DER\n\n# OpenSSH\nchmod 600 ecc_p521_private.pem\nssh-keygen -f ecc_p521_private.pem -y > ecc_p521_public_openssh.txt\n\nssh-keygen -t ecdsa -b 521 -f ecc_p521_private_openssh.pem -P \"\"\ncp -fa ecc_p521_private_openssh.pem ecc_p521_private_openssh_old.pem\nssh-keygen -p -f ecc_p521_private_openssh_old.pem -m PEM -N \"\"\n\nssh-keygen -t ecdsa -b 521 -f ecc_p521_private_openssh_pwd.pem -P \"password\"\ncp -fa ecc_p521_private_openssh_pwd.pem ecc_p521_private_openssh_pwd_old.pem\nssh-keygen -p -f ecc_p521_private_openssh_pwd_old.pem -m PEM -N \"\" -P \"password\"\n", "num_lines": 45}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nset -x\n\nopenssl version | tee openssl_version.txt\n\n# Private key\nopenssl genrsa -out rsa2048_private.pem 2048\n\n# OpenSSH\nchmod 600 rsa2048_private.pem\nssh-keygen -f rsa2048_private.pem -y > rsa2048_public_openssh.txt\n\nssh-keygen -t rsa -b 2048 -f rsa2048_private_openssh.pem -P \"\"\ncp -fa rsa2048_private_openssh.pem rsa2048_private_openssh_old.pem\nssh-keygen -p -f rsa2048_private_openssh_old.pem -m PEM -N \"\"\n\nssh-keygen -t rsa -b 2048 -f rsa2048_private_openssh_pwd.pem -P \"password\"\ncp -fa rsa2048_private_openssh_pwd.pem rsa2048_private_openssh_pwd_old.pem\nssh-keygen -p -f rsa2048_private_openssh_pwd_old.pem -m PEM -N \"\" -P \"password\"\n", "num_lines": 22}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to check include/test code for common pybind11 code style errors.\n#\n# This script currently checks for\n#\n# 1. use of tabs instead of spaces\n# 2. MSDOS-style CRLF endings\n# 3. trailing spaces\n# 4. missing space between keyword and parenthesis, e.g.: for(, if(, while(\n# 5. Missing space between right parenthesis and brace, e.g. 'for (...){'\n# 6. opening brace on its own line. It should always be on the same line as the\n#    if/while/for/do statement.\n#\n# Invoke as: tools/check-style.sh\n#\n\ncheck_style_errors=0\nIFS=$'\\n'\n\nfound=\"$( GREP_COLORS='mt=41' GREP_COLOR='41' grep $'\\t' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )\"\nif [ -n \"$found\" ]; then\n    # The mt=41 sets a red background for matched tabs:\n    echo -e '\\033[31;01mError: found tab characters in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\n\nfound=\"$( grep -IUlr $'\\r' include tests/*.{cpp,py,h} docs/*.rst --color=always )\"\nif [ -n \"$found\" ]; then\n    echo -e '\\033[31;01mError: found CRLF characters in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(GREP_COLORS='mt=41' GREP_COLOR='41' grep '[[:blank:]]\\+$' include tests/*.{cpp,py,h} docs/*.rst -rn --color=always )\"\nif [ -n \"$found\" ]; then\n    # The mt=41 sets a red background for matched trailing spaces\n    echo -e '\\033[31;01mError: found trailing spaces in the following files:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(grep '\\<\\(if\\|for\\|while\\|catch\\)(\\|){' include tests/*.{cpp,h} -rn --color=always)\"\nif [ -n \"$found\" ]; then\n    echo -e '\\033[31;01mError: found the following coding style problems:\\033[0m'\n    check_style_errors=1\n    echo \"$found\" | sed -e 's/^/    /'\nfi\n\nfound=\"$(awk '\nfunction prefix(filename, lineno) {\n    return \"    \\033[35m\" filename \"\\033[36m:\\033[32m\" lineno \"\\033[36m:\\033[0m\"\n}\nfunction mark(pattern, string) { sub(pattern, \"\\033[01;31m&\\033[0m\", string); return string }\nlast && /^\\s*{/ {\n    print prefix(FILENAME, FNR-1) mark(\"\\\\)\\\\s*$\", last)\n    print prefix(FILENAME, FNR)   mark(\"^\\\\s*{\", $0)\n    last=\"\"\n}\n{ last = /(if|for|while|catch|switch)\\s*\\(.*\\)\\s*$/ ? $0 : \"\" }\n' $(find include -type f) tests/*.{cpp,h} docs/*.rst)\"\nif [ -n \"$found\" ]; then\n    check_style_errors=1\n    echo -e '\\033[31;01mError: braces should occur on the same line as the if/while/.. statement. Found issues in the following files:\\033[0m'\n    echo \"$found\"\nfi\n\nexit $check_style_errors\n", "num_lines": 71}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#------------------------------------------------------------------------------\n\n\n# generate_iterator( TargetType, n_elements, has_element_status )\nfunction generate_iterator\n{\n    NonConstIter=$1\"IterT\"\n    ConstIter=\"Const\"$NonConstIter\n    TargetType=\"typename Mesh::\"$1\n    TargetHandle=\"typename Mesh::\"$1\"Handle\"\n\n\n    cat iterators_template.hh \\\n    | sed -e \"s/IteratorT/$NonConstIter/; s/IteratorT/$NonConstIter/;\n\t      s/NonConstIterT/$NonConstIter/;\n\t      s/ConstIterT/$ConstIter/;\n              s/TargetType/$TargetType/;\n\t      s/TargetHandle/$TargetHandle/;\n\t      s/IsConst/0/;\n\t      s/n_elements/$2/;\n\t      s/has_element_status/$3/;\"\n\n\n    cat iterators_template.hh \\\n    | sed -e \"s/IteratorT/$ConstIter/; s/IteratorT/$ConstIter/;\n\t      s/NonConstIterT/$NonConstIter/;\n\t      s/ConstIterT/$ConstIter/;\n              s/TargetType/$TargetType/;\n\t      s/TargetHandle/$TargetHandle/;\n\t      s/IsConst/1/;\n\t      s/n_elements/$2/;\n\t      s/has_element_status/$3/;\"\n}\n\n\n#------------------------------------------------------------------------------\n\n\n# generate_circulator( NonConstName, SourceType, TargetType, \n#                      post_init,\n#                      increment, decrement,\n#                      get_handle,\n#                      [Name] )\nfunction generate_circulator\n{\n    NonConstCirc=$1\n    ConstCirc=\"Const\"$NonConstCirc\n    SourceHandle=\"typename Mesh::\"$2\"Handle\"\n    TargetHandle=\"typename Mesh::\"$3\"Handle\"\n    TargetType=\"typename Mesh::\"$3\n\n\n    cat circulators_template.hh \\\n    | sed -e \"s/CirculatorT/$NonConstCirc/; s/CirculatorT/$NonConstCirc/;\n\t      s/NonConstCircT/$NonConstCirc/;\n\t      s/ConstCircT/$ConstCirc/;\n\t      s/SourceHandle/$SourceHandle/;\n\t      s/TargetHandle/$TargetHandle/;\n              s/TargetType/$TargetType/;\n\t      s/IsConst/0/;\n              s/post_init/$4/;\n              s/increment/$5/;\n              s/decrement/$6/;\n\t      s/get_handle/$7/;\"\n\n\n    cat circulators_template.hh \\\n    | sed -e \"s/CirculatorT/$ConstCirc/; s/CirculatorT/$ConstCirc/;\n\t      s/NonConstCircT/$NonConstCirc/;\n\t      s/ConstCircT/$ConstCirc/;\n\t      s/SourceHandle/$SourceHandle/;\n\t      s/TargetHandle/$TargetHandle/;\n              s/TargetType/$TargetType/;\n\t      s/IsConst/1/;\n              s/post_init/$4/;\n              s/increment/$5/;\n              s/decrement/$6/;\n\t      s/get_handle/$7/;\"\n}\n\n\n#------------------------------------------------------------------------------\n\n\n### Generate IteratorsT.hh\n\ncat iterators_header.hh > IteratorsT.hh\n\ngenerate_iterator Vertex   n_vertices   has_vertex_status    >> IteratorsT.hh\ngenerate_iterator Halfedge n_halfedges  has_halfedge_status  >> IteratorsT.hh\ngenerate_iterator Edge     n_edges      has_edge_status      >> IteratorsT.hh\ngenerate_iterator Face     n_faces      has_face_status      >> IteratorsT.hh\n\ncat footer.hh >> IteratorsT.hh\n\n\n#------------------------------------------------------------------------------\n\n\n### Generate CirculatorsT.hh\n\ncat circulators_header.hh > CirculatorsT.hh\n\n\ngenerate_circulator VertexVertexIterT Vertex Vertex \\\n    \" \" \\\n    \"heh_=mesh_->cw_rotated_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->ccw_rotated_halfedge_handle(heh_);\" \\\n    \"mesh_->to_vertex_handle(heh_);\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator VertexOHalfedgeIterT Vertex Halfedge \\\n    \" \" \\\n    \"heh_=mesh_->cw_rotated_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->ccw_rotated_halfedge_handle(heh_);\" \\\n    \"heh_\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator VertexIHalfedgeIterT Vertex Halfedge \\\n    \" \" \\\n    \"heh_=mesh_->cw_rotated_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->ccw_rotated_halfedge_handle(heh_);\" \\\n    \"mesh_->opposite_halfedge_handle(heh_)\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator VertexEdgeIterT Vertex Edge \\\n    \" \" \\\n    \"heh_=mesh_->cw_rotated_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->ccw_rotated_halfedge_handle(heh_);\" \\\n    \"mesh_->edge_handle(heh_)\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator VertexFaceIterT Vertex Face \\\n    \"if (heh_.is_valid() \\&\\& !handle().is_valid()) operator++();\" \\\n    \"do heh_=mesh_->cw_rotated_halfedge_handle(heh_);  while ((*this) \\&\\& (!handle().is_valid()));\" \\\n    \"do\theh_=mesh_->ccw_rotated_halfedge_handle(heh_); while ((*this) \\&\\& (!handle().is_valid()));\" \\\n    \"mesh_->face_handle(heh_)\" \\\n    >> CirculatorsT.hh\n\n\ngenerate_circulator FaceVertexIterT Face Vertex \\\n    \" \" \\\n    \"heh_=mesh_->next_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->prev_halfedge_handle(heh_);\" \\\n    \"mesh_->to_vertex_handle(heh_)\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator FaceHalfedgeIterT Face Halfedge \\\n    \" \" \\\n    \"heh_=mesh_->next_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->prev_halfedge_handle(heh_);\" \\\n    \"heh_\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator FaceEdgeIterT Face Edge \\\n    \" \" \\\n    \"heh_=mesh_->next_halfedge_handle(heh_);\" \\\n    \"heh_=mesh_->prev_halfedge_handle(heh_);\" \\\n    \"mesh_->edge_handle(heh_)\" \\\n    >> CirculatorsT.hh\n\ngenerate_circulator FaceFaceIterT Face Face \\\n    \"if (heh_.is_valid() \\&\\& !handle().is_valid()) operator++();\" \\\n    \"do heh_=mesh_->next_halfedge_handle(heh_); while ((*this) \\&\\& (!handle().is_valid()));\" \\\n    \"do heh_=mesh_->prev_halfedge_handle(heh_); while ((*this) \\&\\& (!handle().is_valid()));\" \\\n    \"mesh_->face_handle(mesh_->opposite_halfedge_handle(heh_))\" \\\n    >> CirculatorsT.hh\n\n\ncat footer.hh >> CirculatorsT.hh\n\n\n#------------------------------------------------------------------------------\n", "num_lines": 176}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n#!/bin/sh\n\n\n# Install updates\napt-get update -y\n\n# Add Mozilla Security repo (needed to install binutils-2.26)\nadd-apt-repository -y ppa:ubuntu-mozilla-security/ppa\napt-get update -y\napt-get upgrade -y\n\n# Install software\napt-get install -y\napt-get install -y gcc # Internal Developers Only\napt-get install -y binutils-2.26\napt-get install -y libc++-dev # required for clang to work\napt-get install -y libc++abi-dev\napt-get install -y clang\napt-get install -y uuid-dev\napt-get install -y python-tk\n# apt-get install -y qt-sdk\napt-get install -y openjdk-7-jre\napt-get install -y libncurses5-dev\napt-get install -y helix-cli\napt-get install -y libcurl3\napt-get install -y libcurl4-openssl-dev\napt-get install -y python-pip\napt-get install -y zlib1g-dev # required for AZCG\napt-get install -y libjpeg-dev\napt-get install -y libjbig-dev\napt-get install -y libsdl2-dev # Needed for WWise\napt-get install -y libcurl3-nss # required by libaws-cpp-sdk-core.so\npip install awscli\n\n# Graphics packages\napt-get install -y libx11-dev\napt-get install -y mesa-common-dev\n\n# Qt 5.12 dependencies\napt-get install -y libopus-dev\napt-get install -y libwebpmux3\napt-get install -y libwebpdemux2\napt-get install -y libwebp-dev\n\n# Create a symlink to libGL and libEGL so we can link with them.\nln -s /usr/lib/x86_64-linux-gnu/libGL.so.1 /usr/lib/libGL.so\nln -s /usr/lib/x86_64-linux-gnu/libEGL.so.1 /usr/lib/libEGL.so\n\n# Configuration\n# mv /usr/bin/ld /usr/bin/ld.bak\n# mv /usr/bin/ld-2.26 /usr/bin/ld\nln -s /usr/bin/clang-3.8 /usr/bin/clang\nln -s /usr/bin/clang++-3.8 /usr/bin/clang++\n# cp -v /usr/include/libcxxabi/* /usr/include/c++/v1/\n# hash -r # This needs to be run from the parent shell and not part of this script.\n\necho\necho\necho \"=============================|======================|============================\"\necho \"Name                         | Expected Version     | Installed Version          \"\necho \"                             |    (or Higher)       |                            \"\necho \"=============================|======================|============================\"\necho \"binutils                     | 2.26.1               | `dpkg -l binutils | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"clang-3.8                    | 3.8                  | `dpkg -l clang-3.8 | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"g++                          | 5.3.1                | `dpkg -l g++ | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"gcc                          | 5.3.1                | `dpkg -l gcc | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libc++-dev                   | 3.7.0                | `dpkg -l libc++-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libc++abi-dev                | 3.7.0                | `dpkg -l libc++abi-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libcurl4-openssl-dev         | 7.47.0               | `dpkg -l libcurl4-openssl-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libncurses5-dev              | 6.0                  | `dpkg -l libncurses5-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"python-pip                   | 8.1.1                | `dpkg -l python-pip | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"python-tk                    | 2.7.11               | `dpkg -l python-tk | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"ubuntu-release-upgrader-core | 16.04.22             | `dpkg -l ubuntu-release-upgrader-core | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"uuid-dev                     | 2.27.1               | `dpkg -l uuid-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libopus-dev                  | 1.1.2-1ubuntu1       | `dpkg -l libopus-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libwebpmux3                  | 0.6.1-2              | `dpkg -l libwebpmux3 | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libwebpdemux2                | 0.6.1-2              | `dpkg -l libwebpdemux2 | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"libwebp-dev                  | 0.6.1-2              | `dpkg -l libwebp-dev | grep -E \"^ii\" | tr -s ' ' | cut -d' ' -f3`\"\necho \"=============================|======================|============================\"\necho\necho\n", "num_lines": 92}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# Original file Copyright Crytek GMBH or its affiliates, used under license.\n#\npushd $(dirname \"$0\")\nexport PYTHON_DIR=../../Tools/Python\n\nif [ -e $PYTHON_DIR ]\nthen\n    PYTHON=$PYTHON_DIR/python3.sh\n    if [ -e $PYTHON ]\n    then\n        LMBR_AWS_DIR=../../Tools/lmbr_aws\n        $PYTHON $LMBR_AWS_DIR/cleanup.py $*\n    else\n        echo Could not find python3.sh in $PYTHON_DIR\n    fi\nelse\n    echo Could not find Python3 in $PYTHON_DIR\nfi\n\npopd\nexit 0\n", "num_lines": 31}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# Original file Copyright Crytek GMBH or its affiliates, used under license.\n#\n\npushd $(dirname \"$0\")\n./python3.sh -m pip \"$@\"\nPIP_EXIT=$?\n\npopd\nexit $PIP_EXIT\n", "num_lines": 21}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or\n# its licensors.\n#\n# For complete copyright and license terms please see the LICENSE at the root of this\n# distribution (the \"License\"). All use of this software is governed by the License,\n# or, if provided, by the license below or the license accompanying this file. Do not\n# remove or modify any license notices. This file is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n#\n# Original file Copyright Crytek GMBH or its affiliates, used under license.\n\n\nSOURCE=\"${BASH_SOURCE[0]}\"\n# While $SOURCE is a symlink, resolve it\nwhile [ -h \"$SOURCE\" ]; do\n    DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n    SOURCE=\"$( readlink \"$SOURCE\" )\"\n    # If $SOURCE was a relative symlink (so no \"/\" as prefix, need to resolve it relative to the symlink base directory\n    [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\"\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n\nif [[ \"$OSTYPE\" = *\"darwin\"* ]];\nthen\n    export DYLD_FALLBACK_LIBRARY_PATH=$DIR/3.7.10/mac/Python.framework/Versions/3.7/lib/lib-dynload\n    PYTHON=$DIR/3.7.10/mac/Python.framework/Versions/3.7/bin/python3\n    PATH_SCRIPT=$DIR/3.7.10/extend_pythonpath.py\nelse\n    PYTHON=$DIR/3.7.10/linux_x64/bin/python3.7\n    PATH_SCRIPT=$DIR/3.7.10/extend_pythonpath.py\nfi\n\nif [ -e \"$PYTHON\" ]\nthen\n    export PYTHONPATH=\"$($PYTHON $PATH_SCRIPT)\"\n    \"$PYTHON\" \"$@\"\n    exit $?\nelse\n    echo \"Could not find python in $PYTHON\"\n    exit 1\nfi\n\nexit 1\n", "num_lines": 46}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tclConfig.sh --\n#\n# This shell script (for sh) is generated automatically by Tcl's\n# configure script.  It will create shell variables for most of\n# the configuration options discovered by the configure script.\n# This script is intended to be included by the configure scripts\n# for Tcl extensions so that they don't have to figure this all\n# out for themselves.\n#\n# The information in this file is specific to a single platform.\n\n# Tcl's version number.\nTCL_VERSION='8.6'\nTCL_MAJOR_VERSION='8'\nTCL_MINOR_VERSION='6'\nTCL_PATCH_LEVEL='.8'\n\n# C compiler to use for compilation.\nTCL_CC='gcc'\n\n# -D flags for use with the C compiler.\nTCL_DEFS='-DPACKAGE_NAME=\\\"tcl\\\" -DPACKAGE_TARNAME=\\\"tcl\\\" -DPACKAGE_VERSION=\\\"8.6\\\" -DPACKAGE_STRING=\\\"tcl\\ 8.6\\\" -DPACKAGE_BUGREPORT=\\\"\\\" -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DNO_VALUES_H=1 -DHAVE_SYS_PARAM_H=1 -DUSE_THREAD_ALLOC=1 -D_REENTRANT=1 -D_THREAD_SAFE=1 -DHAVE_PTHREAD_ATTR_SETSTACKSIZE=1 -DHAVE_PTHREAD_ATFORK=1 -DTCL_THREADS=1 -DTCL_CFGVAL_ENCODING=\\\"iso8859-1\\\" -DHAVE_ZLIB=1 -DMODULE_SCOPE=extern\\ __attribute__\\(\\(__visibility__\\(\\\"hidden\\\"\\)\\)\\) -DHAVE_HIDDEN=1 -DMAC_OSX_TCL=1 -DHAVE_COREFOUNDATION=1 -DHAVE_CAST_TO_UNION=1 -DTCL_SHLIB_EXT=\\\".dylib\\\" -DNDEBUG=1 -DTCL_CFG_OPTIMIZED=1 -DTCL_TOMMATH=1 -DMP_PREC=4 -DTCL_WIDE_INT_IS_LONG=1 -DHAVE_GETCWD=1 -DHAVE_MKSTEMP=1 -DHAVE_OPENDIR=1 -DHAVE_STRTOL=1 -DHAVE_WAITPID=1 -DHAVE_GETNAMEINFO=1 -DHAVE_GETADDRINFO=1 -DHAVE_FREEADDRINFO=1 -DHAVE_GAI_STRERROR=1 -DHAVE_STRUCT_ADDRINFO=1 -DHAVE_STRUCT_IN6_ADDR=1 -DHAVE_STRUCT_SOCKADDR_IN6=1 -DHAVE_STRUCT_SOCKADDR_STORAGE=1 -DHAVE_GETPWUID_R_5=1 -DHAVE_GETPWUID_R=1 -DHAVE_GETPWNAM_R_5=1 -DHAVE_GETPWNAM_R=1 -DHAVE_GETGRGID_R_5=1 -DHAVE_GETGRGID_R=1 -DHAVE_GETGRNAM_R_5=1 -DHAVE_GETGRNAM_R=1 -DHAVE_MTSAFE_GETHOSTBYNAME=1 -DHAVE_MTSAFE_GETHOSTBYADDR=1 -DHAVE_TERMIOS_H=1 -DHAVE_SYS_IOCTL_H=1 -DHAVE_SYS_TIME_H=1 -DTIME_WITH_SYS_TIME=1 -DHAVE_GMTIME_R=1 -DHAVE_LOCALTIME_R=1 -DHAVE_MKTIME=1 -DHAVE_TM_GMTOFF=1 -DHAVE_STRUCT_STAT_ST_BLOCKS=1 -DHAVE_STRUCT_STAT_ST_BLKSIZE=1 -DHAVE_BLKCNT_T=1 -DHAVE_INTPTR_T=1 -DHAVE_UINTPTR_T=1 -DHAVE_SIGNED_CHAR=1 -DHAVE_PUTENV_THAT_COPIES=1 -DHAVE_LANGINFO=1 -DHAVE_CHFLAGS=1 -DHAVE_MKSTEMPS=1 -DHAVE_GETATTRLIST=1 -DHAVE_COPYFILE_H=1 -DHAVE_COPYFILE=1 -DHAVE_LIBKERN_OSATOMIC_H=1 -DHAVE_OSSPINLOCKLOCK=1 -DUSE_VFORK=1 -DTCL_DEFAULT_ENCODING=\\\"utf-8\\\" -DTCL_LOAD_FROM_MEMORY=1 -DTCL_WIDE_CLICKS=1 -DHAVE_AVAILABILITYMACROS_H=1 -DHAVE_WEAK_IMPORT=1 -D_DARWIN_C_SOURCE=1 -DHAVE_FTS=1 -DHAVE_SYS_IOCTL_H=1 -DHAVE_SYS_FILIO_H=1 -DTCL_UNLOAD_DLLS=1 -DHAVE_CPUID=1 '\n\n# TCL_DBGX used to be used to distinguish debug vs. non-debug builds.\n# This was a righteous pain so the core doesn't do that any more.\nTCL_DBGX=\n\n# Default flags used in an optimized and debuggable build, respectively.\nTCL_CFLAGS_DEBUG='-g'\nTCL_CFLAGS_OPTIMIZE='-Os'\n\n# Default linker flags used in an optimized and debuggable build, respectively.\nTCL_LDFLAGS_DEBUG=''\nTCL_LDFLAGS_OPTIMIZE=''\n\n# Flag, 1: we built a shared lib, 0 we didn't\nTCL_SHARED_BUILD=1\n\n# The name of the Tcl library (may be either a .a file or a shared library):\nTCL_LIB_FILE='libtcl8.6.dylib'\n\n# Additional libraries to use when linking Tcl.\nTCL_LIBS=' -lz  -lpthread -framework CoreFoundation '\n\n# Top-level directory in which Tcl's platform-independent files are\n# installed.\nTCL_PREFIX='/usr/local'\n\n# Top-level directory in which Tcl's platform-specific files (e.g.\n# executables) are installed.\nTCL_EXEC_PREFIX='/usr/local'\n\n# Flags to pass to cc when compiling the components of a shared library:\nTCL_SHLIB_CFLAGS='-fno-common'\n\n# Flags to pass to cc to get warning messages\nTCL_CFLAGS_WARNING='-Wall'\n\n# Extra flags to pass to cc:\nTCL_EXTRA_CFLAGS='-arch x86_64 -I/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/libraries/usr/local/include -pipe   -mmacosx-version-min=10.9 '\n\n# Base command to use for combining object files into a shared library:\nTCL_SHLIB_LD='${CC} -dynamiclib ${CFLAGS} ${LDFLAGS} -Wl,-single_module'\n\n# Base command to use for combining object files into a static library:\nTCL_STLIB_LD='${AR} cr'\n\n# Either '$LIBS' (if dependent libraries should be included when linking\n# shared libraries) or an empty string.  See Tcl's configure.in for more\n# explanation.\nTCL_SHLIB_LD_LIBS='${LIBS}'\n\n# Suffix to use for the name of a shared library.\nTCL_SHLIB_SUFFIX='.dylib'\n\n# Library file(s) to include in tclsh and other base applications\n# in order to provide facilities needed by DLOBJ above.\nTCL_DL_LIBS=''\n\n# Flags to pass to the compiler when linking object files into\n# an executable tclsh or tcltest binary.\nTCL_LD_FLAGS=' -headerpad_max_install_names -Wl,-search_paths_first '\n\n# Flags to pass to cc/ld, such as \"-R /usr/local/tcl/lib\", that tell the\n# run-time dynamic linker where to look for shared libraries such as\n# libtcl.so.  Used when linking applications.  Only works if there\n# is a variable \"LIB_RUNTIME_DIR\" defined in the Makefile.\nTCL_CC_SEARCH_FLAGS=''\nTCL_LD_SEARCH_FLAGS=''\n\n# Additional object files linked with Tcl to provide compatibility\n# with standard facilities from ANSI C or POSIX.\nTCL_COMPAT_OBJS=' strstr.o strtoul.o strtod.o'\n\n# Name of the ranlib program to use.\nTCL_RANLIB='ranlib'\n\n# -l flag to pass to the linker to pick up the Tcl library\nTCL_LIB_FLAG='-ltcl8.6'\n\n# String to pass to linker to pick up the Tcl library from its\n# build directory.\nTCL_BUILD_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix -ltcl8.6'\n\n# String to pass to linker to pick up the Tcl library from its\n# installed directory.\nTCL_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib -ltcl8.6'\n\n# String to pass to the compiler so that an extension can\n# find installed Tcl headers.\nTCL_INCLUDE_SPEC='-I/usr/local/include'\n\n# Indicates whether a version numbers should be used in -l switches\n# (\"ok\" means it's safe to use switches like -ltcl7.5;  \"nodots\" means\n# use switches like -ltcl75).  SunOS and FreeBSD require \"nodots\", for\n# example.\nTCL_LIB_VERSIONS_OK='ok'\n\n# String that can be evaluated to generate the part of a shared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variables\n# VERSION and SHLIB_SUFFIX.  On most UNIX systems this is\n# ${VERSION}${SHLIB_SUFFIX}.\nTCL_SHARED_LIB_SUFFIX='${VERSION}.dylib'\n\n# String that can be evaluated to generate the part of an unshared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variable\n# VERSION.  On most UNIX systems this is ${VERSION}.a.\nTCL_UNSHARED_LIB_SUFFIX='${VERSION}.a'\n\n# Location of the top-level source directory from which Tcl was built.\n# This is the directory that contains a README file as well as\n# subdirectories such as generic, unix, etc.  If Tcl was compiled in a\n# different place than the directory containing the source files, this\n# points to the location of the sources, not the location where Tcl was\n# compiled.\nTCL_SRC_DIR='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8'\n\n# List of standard directories in which to look for packages during\n# \"package require\" commands.  Contains the \"prefix\" directory plus also\n# the \"exec_prefix\" directory, if it is different.\nTCL_PACKAGE_PATH='/Library/Frameworks/Python.framework/Versions/3.7/lib /usr/local/lib '\n\n# Tcl supports stub.\nTCL_SUPPORTS_STUBS=1\n\n# The name of the Tcl stub library (.a):\nTCL_STUB_LIB_FILE='libtclstub8.6.a'\n\n# -l flag to pass to the linker to pick up the Tcl stub library\nTCL_STUB_LIB_FLAG='-ltclstub8.6'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# build directory.\nTCL_BUILD_STUB_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix -ltclstub8.6'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# installed directory.\nTCL_STUB_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib -ltclstub8.6'\n\n# Path to the Tcl stub library in the build directory.\nTCL_BUILD_STUB_LIB_PATH='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/libtclstub8.6.a'\n\n# Path to the Tcl stub library in the install directory.\nTCL_STUB_LIB_PATH='/Library/Frameworks/Python.framework/Versions/3.7/lib/libtclstub8.6.a'\n\n# Flag, 1: we built Tcl with threads enabled, 0 we didn't\nTCL_THREADS=1\n", "num_lines": 170}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tclooConfig.sh --\n#\n# This shell script (for sh) is generated automatically by TclOO's configure\n# script, or would be except it has no values that we substitute. It will\n# create shell variables for most of the configuration options discovered by\n# the configure script. This script is intended to be included by TEA-based\n# configure scripts for TclOO extensions so that they don't have to figure\n# this all out for themselves.\n#\n# The information in this file is specific to a single platform.\n\n# These are mostly empty because no special steps are ever needed from Tcl 8.6\n# onwards; all libraries and include files are just part of Tcl.\nTCLOO_LIB_SPEC=\"\"\nTCLOO_STUB_LIB_SPEC=\"\"\nTCLOO_INCLUDE_SPEC=\"\"\nTCLOO_PRIVATE_INCLUDE_SPEC=\"\"\nTCLOO_CFLAGS=\"\"\nTCLOO_VERSION=1.1.0\n", "num_lines": 20}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tkConfig.sh --\n#\n# This shell script (for sh) is generated automatically by Tk's\n# configure script.  It will create shell variables for most of\n# the configuration options discovered by the configure script.\n# This script is intended to be included by the configure scripts\n# for Tk extensions so that they don't have to figure this all\n# out for themselves.  This file does not duplicate information\n# already provided by tclConfig.sh, so you may need to use that\n# file in addition to this one.\n#\n# The information in this file is specific to a single platform.\n\n# Tk's version number.\nTK_VERSION='8.6'\nTK_MAJOR_VERSION='8'\nTK_MINOR_VERSION='6'\nTK_PATCH_LEVEL='.8'\n\n# -D flags for use with the C compiler.\nTK_DEFS='-DPACKAGE_NAME=\\\"tk\\\" -DPACKAGE_TARNAME=\\\"tk\\\" -DPACKAGE_VERSION=\\\"8.6\\\" -DPACKAGE_STRING=\\\"tk\\ 8.6\\\" -DPACKAGE_BUGREPORT=\\\"\\\" -DHAVE_SYS_TYPES_H=1 -DHAVE_SYS_STAT_H=1 -DHAVE_STDLIB_H=1 -DHAVE_STRING_H=1 -DHAVE_MEMORY_H=1 -DHAVE_STRINGS_H=1 -DHAVE_INTTYPES_H=1 -DHAVE_STDINT_H=1 -DHAVE_UNISTD_H=1 -DUSE_THREAD_ALLOC=1 -D_REENTRANT=1 -D_THREAD_SAFE=1 -DHAVE_PTHREAD_ATTR_SETSTACKSIZE=1 -DHAVE_PTHREAD_ATFORK=1 -DTCL_THREADS=1 -DMODULE_SCOPE=extern\\ __attribute__\\(\\(__visibility__\\(\\\"hidden\\\"\\)\\)\\) -DHAVE_HIDDEN=1 -DMAC_OSX_TCL=1 -DHAVE_COREFOUNDATION=1 -DHAVE_CAST_TO_UNION=1 -DTCL_SHLIB_EXT=\\\".dylib\\\" -DNDEBUG=1 -DTCL_CFG_OPTIMIZED=1 -DTCL_WIDE_INT_IS_LONG=1 -DHAVE_SYS_TIME_H=1 -DTIME_WITH_SYS_TIME=1 -DHAVE_INTPTR_T=1 -DHAVE_UINTPTR_T=1 -DHAVE_PW_GECOS=1 -DHAVE_AVAILABILITYMACROS_H=1 -DHAVE_WEAK_IMPORT=1 -D_DARWIN_C_SOURCE=1 -DMAC_OSX_TK=1 '\n\n# Flag, 1: we built a shared lib, 0 we didn't\nTK_SHARED_BUILD=1\n\n\n# TK_DBGX used to be used to distinguish debug vs. non-debug builds.\n# This was a righteous pain so the core doesn't do that any more.\nTK_DBGX=\n\n# The name of the Tk library (may be either a .a file or a shared library):\nTK_LIB_FILE='libtk8.6.dylib'\n\n# Additional libraries to use when linking Tk.\nTK_LIBS='   -lpthread -framework CoreFoundation -framework Cocoa -framework Carbon -framework IOKit  -lz  -lpthread -framework CoreFoundation '\n\n# Top-level directory in which Tk's platform-independent files are\n# installed.\nTK_PREFIX='/usr/local'\n\n# Top-level directory in which Tk's platform-specific files (e.g.\n# executables) are installed.\nTK_EXEC_PREFIX='/usr/local'\n\n# -I switch(es) to use to make all of the X11 include files accessible:\nTK_XINCLUDES=''\n\n# Linker switch(es) to use to link with the X11 library archive.\nTK_XLIBSW=''\n\n# -l flag to pass to the linker to pick up the Tk library\nTK_LIB_FLAG='-ltk8.6'\n\n# String to pass to linker to pick up the Tk library from its\n# build directory.\nTK_BUILD_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tk8.6.8/unix -ltk8.6'\n\n# String to pass to linker to pick up the Tk library from its\n# installed directory.\nTK_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib -ltk8.6'\n\n# String to pass to the compiler so that an extension can\n# find installed Tk headers.\nTK_INCLUDE_SPEC='-I/usr/local/include'\n\n# Location of the top-level source directory from which Tk was built.\n# This is the directory that contains a README file as well as\n# subdirectories such as generic, unix, etc.  If Tk was compiled in a\n# different place than the directory containing the source files, this\n# points to the location of the sources, not the location where Tk was\n# compiled.\nTK_SRC_DIR='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tk8.6.8'\n\n# Needed if you want to make a 'fat' shared library library\n# containing tk objects or link a different wish.\nTK_CC_SEARCH_FLAGS=''\nTK_LD_SEARCH_FLAGS=''\n\n# The name of the Tk stub library (.a):\nTK_STUB_LIB_FILE='libtkstub8.6.a'\n\n# -l flag to pass to the linker to pick up the Tk stub library\nTK_STUB_LIB_FLAG='-ltkstub8.6'\n\n# String to pass to linker to pick up the Tk stub library from its\n# build directory.\nTK_BUILD_STUB_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tk8.6.8/unix -ltkstub8.6'\n\n# String to pass to linker to pick up the Tk stub library from its\n# installed directory.\nTK_STUB_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib -ltkstub8.6'\n\n# Path to the Tk stub library in the build directory.\nTK_BUILD_STUB_LIB_PATH='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tk8.6.8/unix/libtkstub8.6.a'\n\n# Path to the Tk stub library in the install directory.\nTK_STUB_LIB_PATH='/Library/Frameworks/Python.framework/Versions/3.7/lib/libtkstub8.6.a'\n", "num_lines": 98}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# itclConfig.sh --\n# \n# This shell script (for sh) is generated automatically by Itcl's\n# configure script.  It will create shell variables for most of\n# the configuration options discovered by the configure script.\n# This script is intended to be included by the configure scripts\n# for Itcl extensions so that they don't have to figure this all\n# out for themselves.  This file does not duplicate information\n# already provided by tclConfig.sh, so you may need to use that\n# file in addition to this one.\n#\n# The information in this file is specific to a single platform.\n\n# Itcl's version number.\nitcl_VERSION='4.1.1'\nITCL_VERSION='4.1.1'\n\n# The name of the Itcl library (may be either a .a file or a shared library):\nitcl_LIB_FILE=libitcl4.1.1.dylib\nITCL_LIB_FILE=libitcl4.1.1.dylib\n\n# String to pass to linker to pick up the Itcl library from its\n# build directory.\nitcl_BUILD_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1 -litcl4.1.1'\nITCL_BUILD_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1 -litcl4.1.1'\n\n# String to pass to linker to pick up the Itcl library from its\n# installed directory.\nitcl_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1 -litcl4.1.1'\nITCL_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1 -litcl4.1.1'\n\n# The name of the Itcl stub library (a .a file):\nitcl_STUB_LIB_FILE=libitclstub4.1.1.a\nITCL_STUB_LIB_FILE=libitclstub4.1.1.a\n\n# String to pass to linker to pick up the Itcl stub library from its\n# build directory.\nitcl_BUILD_STUB_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1 -litclstub4.1.1'\nITCL_BUILD_STUB_LIB_SPEC='-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1 -litclstub4.1.1'\n\n# String to pass to linker to pick up the Itcl stub library from its\n# installed directory.\nitcl_STUB_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1 -litclstub4.1.1'\nITCL_STUB_LIB_SPEC='-L/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1 -litclstub4.1.1'\n\n# String to pass to linker to pick up the Itcl stub library from its\n# build directory.\nitcl_BUILD_STUB_LIB_PATH='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1/libitclstub4.1.1.a'\nITCL_BUILD_STUB_LIB_PATH='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/itcl4.1.1/libitclstub4.1.1.a'\n\n# String to pass to linker to pick up the Itcl stub library from its\n# installed directory.\nitcl_STUB_LIB_PATH='/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1/libitclstub4.1.1.a'\nITCL_STUB_LIB_PATH='/Library/Frameworks/Python.framework/Versions/3.7/lib/itcl4.1.1/libitclstub4.1.1.a'\n\n# Location of the top-level source directories from which [incr Tcl]\n# was built.  This is the directory that contains generic, unix, etc.\n# If [incr Tcl] was compiled in a different place than the directory\n# containing the source files, this points to the location of the sources,\n# not the location where [incr Tcl] was compiled.\nitcl_SRC_DIR='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/itcl4.1.1'\nITCL_SRC_DIR='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/itcl4.1.1'\n\n# String to pass to the compiler so that an extension can\n# find installed Itcl headers.\nitcl_INCLUDE_SPEC='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/itcl4.1.1/generic'\nITCL_INCLUDE_SPEC='/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/itcl4.1.1/generic'\n", "num_lines": 68}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tdbcConfig.sh --\n#\n# This shell script (for sh) is generated automatically by TDBC's configure\n# script. It will create shell variables for most of the configuration options\n# discovered by the configure script. This script is intended to be included\n# by the configure scripts for TDBC extensions so that they don't have to\n# figure this all out for themselves.\n#\n# The information in this file is specific to a single platform.\n#\n# RCS: @(#) $Id$\n\n# TDBC's version number\ntdbc_VERSION=1.0.6\nTDBC_VERSION=1.0.6\n\n# Name of the TDBC library - may be either a static or shared library\ntdbc_LIB_FILE=libtdbc1.0.6.dylib\nTDBC_LIB_FILE=libtdbc1.0.6.dylib\n\n# String to pass to the linker to pick up the TDBC library from its build dir\ntdbc_BUILD_LIB_SPEC=\"-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6 -ltdbc1.0.6\"\nTDBC_BUILD_LIB_SPEC=\"-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6 -ltdbc1.0.6\"\n\n# String to pass to the linker to pick up the TDBC library from its installed\n# dir.\ntdbc_LIB_SPEC=\"-L/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6 -ltdbc1.0.6\"\nTDBC_LIB_SPEC=\"-L/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6 -ltdbc1.0.6\"\n\n# Name of the TBDC stub library\ntdbc_STUB_LIB_FILE=\"libtdbcstub1.0.6.a\"\nTDBC_STUB_LIB_FILE=\"libtdbcstub1.0.6.a\"\n\n# String to pass to the linker to pick up the TDBC stub library from its\n# build directory\ntdbc_BUILD_STUB_LIB_SPEC=\"-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6 -ltdbcstub1.0.6\"\nTDBC_BUILD_STUB_LIB_SPEC=\"-L/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6 -ltdbcstub1.0.6\"\n\n# String to pass to the linker to pick up the TDBC stub library from its\n# installed directory\ntdbc_STUB_LIB_SPEC=\"-L/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6 -ltdbcstub1.0.6\"\nTDBC_STUB_LIB_SPEC=\"-L/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6 -ltdbcstub1.0.6\"\n\n# Path name of the TDBC stub library in its build directory\ntdbc_BUILD_STUB_LIB_PATH=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6/libtdbcstub1.0.6.a\"\nTDBC_BUILD_STUB_LIB_PATH=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/unix/pkgs/tdbc1.0.6/libtdbcstub1.0.6.a\"\n\n# Path name of the TDBC stub library in its installed directory\ntdbc_STUB_LIB_PATH=\"/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6/libtdbcstub1.0.6.a\"\nTDBC_STUB_LIB_PATH=\"/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6/libtdbcstub1.0.6.a\"\n\n# Location of the top-level source directories from which TDBC was built.\n# This is the directory that contains doc/, generic/ and so on.  If TDBC\n# was compiled in a directory other than the source directory, this still\n# points to the location of the sources, not the location where TDBC was\n# compiled.\ntdbc_SRC_DIR=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6\"\nTDBC_SRC_DIR=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6\"\n\n# String to pass to the compiler so that an extension can find installed TDBC\n# headers\ntdbc_INCLUDE_SPEC=\"-I/usr/local/include\"\nTDBC_INCLUDE_SPEC=\"-I/usr/local/include\"\n\n# String to pass to the compiler so that an extension can find TDBC headers\n# in the source directory\ntdbc_BUILD_INCLUDE_SPEC=\"-I/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6/generic\"\nTDBC_BUILD_INCLUDE_SPEC=\"-I/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6/generic\"\n\n# Path name where .tcl files in the tdbc package appear at run time.\ntdbc_LIBRARY_PATH=\"/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6\"\nTDBC_LIBRARY_PATH=\"/Library/Frameworks/Python.framework/Versions/3.7/lib/tdbc1.0.6\"\n\n# Path name where .tcl files in the tdbc package appear at build time.\ntdbc_BUILD_LIBRARY_PATH=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6/library\"\nTDBC_BUILD_LIBRARY_PATH=\"/Volumes/Lumberyard/lumberyard_p4/lyengine/3rdPartySource/python/darwin_x64/temp/python_build/_bld/tcl8.6.8/pkgs/tdbc1.0.6/library\"\n\n# Additional flags that must be passed to the C compiler to use tdbc\ntdbc_CFLAGS=\nTDBC_CFLAGS=\n\n", "num_lines": 82}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tclConfig.sh --\n#\n# This shell script (for sh) is generated automatically by Tcl's\n# configure script.  It will create shell variables for most of\n# the configuration options discovered by the configure script.\n# This script is intended to be included by the configure scripts\n# for Tcl extensions so that they don't have to figure this all\n# out for themselves.\n#\n# The information in this file is specific to a single platform.\n\nTCL_DLL_FILE=\"tcl86t.dll\"\n\n# Tcl's version number.\nTCL_VERSION='8.6'\nTCL_MAJOR_VERSION='8'\nTCL_MINOR_VERSION='6'\nTCL_PATCH_LEVEL='8.6.9'\n\n# C compiler to use for compilation.\nTCL_CC='cl'\n\n# -D flags for use with the C compiler.\nTCL_DEFS='-nologo -c /D_ATL_XP_TARGETING /DUNICODE /D_UNICODE  -W3 -wd4311 -wd4312 -wd4311 -wd4312 -FpC:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\  -fp:strict -O2 -GS -GL -MD -I\"C:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\..\\win\" -I\"C:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\..\\generic\"  -I\"C:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\..\\libtommath\"  -DTCL_TOMMATH -DMP_PREC=4 -Dinline=__inline -DHAVE_ZLIB=1 -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE -DTCL_CFGVAL_ENCODING=\\\"cp1252\\\" -DSTDC_HEADERS -DTCL_THREADS=1 -DUSE_THREAD_ALLOC=1 -DNDEBUG -DTCL_CFG_OPTIMIZED -DTCL_CFG_DO64BIT   -DBUILD_tcl'\n\n# If TCL was built with debugging symbols, generated libraries contain\n# this string at the end of the library name (before the extension).\nTCL_DBGX=t\n\n# Default flags used in an optimized and debuggable build, respectively.\nTCL_CFLAGS_DEBUG='-nologo -c -W3 -YX -FpC:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\ -MDd'\nTCL_CFLAGS_OPTIMIZE='-nologo -c -W3 -YX -FpC:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\ -MD'\n\n# Default linker flags used in an optimized and debuggable build, respectively.\nTCL_LDFLAGS_DEBUG='-nologo -machine:AMD64 -debug -debugtype:cv'\nTCL_LDFLAGS_OPTIMIZE='-nologo -machine:AMD64 -release -opt:ref -opt:icf,3'\n\n# Flag, 1: we built a shared lib, 0 we didn't\nTCL_SHARED_BUILD=1\n\n# The name of the Tcl library (may be either a .a file or a shared library):\nTCL_LIB_FILE='tcl86t.lib'\n\n# Flag to indicate whether shared libraries need export files.\nTCL_NEEDS_EXP_FILE=\n\n# String that can be evaluated to generate the part of the export file\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variables\n# VERSION.  On most UNIX systems this is ${VERSION}.exp.\nTCL_EXPORT_FILE_SUFFIX='86t.lib'\n\n# Additional libraries to use when linking Tcl.\nTCL_LIBS='kernel32.lib advapi32.lib netapi32.lib user32.lib userenv.lib ws2_32.lib ucrt.lib netapi32.lib user32.lib userenv.lib ws2_32.lib'\n\n# Top-level directory in which Tcl's platform-independent files are\n# installed.\nTCL_PREFIX='C:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64'\n\n# Top-level directory in which Tcl's platform-specific files (e.g.\n# executables) are installed.\nTCL_EXEC_PREFIX='C:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64\\bin'\n\n# Flags to pass to cc when compiling the components of a shared library:\nTCL_SHLIB_CFLAGS=''\n\n# Flags to pass to cc to get warning messages\nTCL_CFLAGS_WARNING='-W3'\n\n# Extra flags to pass to cc:\nTCL_EXTRA_CFLAGS='-YX'\n\n# Base command to use for combining object files into a shared library:\nTCL_SHLIB_LD='link -nologo -machine:AMD64  -ltcg -release -opt:ref -opt:icf,3 -nodefaultlib:libucrt.lib -dll'\n\n# Base command to use for combining object files into a static library:\nTCL_STLIB_LD='lib -nologo'\n\n# Either '$LIBS' (if dependent libraries should be included when linking\n# shared libraries) or an empty string.  See Tcl's configure.in for more\n# explanation.\nTCL_SHLIB_LD_LIBS='kernel32.lib advapi32.lib netapi32.lib user32.lib userenv.lib ws2_32.lib ucrt.lib netapi32.lib user32.lib userenv.lib ws2_32.lib'\n\n# Suffix to use for the name of a shared library.\nTCL_SHLIB_SUFFIX='.dll'\n\n# Library file(s) to include in tclsh and other base applications\n# in order to provide facilities needed by DLOBJ above.\nTCL_DL_LIBS=''\n\n# Flags to pass to the compiler when linking object files into\n# an executable tclsh or tcltest binary.\nTCL_LD_FLAGS=''\n\n# Flags to pass to cc/ld, such as \"-R /usr/local/tcl/lib\", that tell the\n# run-time dynamic linker where to look for shared libraries such as\n# libtcl.so.  Used when linking applications.  Only works if there\n# is a variable \"LIB_RUNTIME_DIR\" defined in the Makefile.\nTCL_CC_SEARCH_FLAGS=''\nTCL_LD_SEARCH_FLAGS=''\n\n# Additional object files linked with Tcl to provide compatibility\n# with standard facilities from ANSI C or POSIX.\nTCL_COMPAT_OBJS=''\n\n# Name of the ranlib program to use.\nTCL_RANLIB=''\n\n# -l flag to pass to the linker to pick up the Tcl library\nTCL_LIB_FLAG=''\n\n# String to pass to linker to pick up the Tcl library from its\n# build directory.\nTCL_BUILD_LIB_SPEC=''\n\n# String to pass to linker to pick up the Tcl library from its\n# installed directory.\nTCL_LIB_SPEC='C:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64\\lib\\tcl86t.lib'\n\n# String to pass to the compiler so that an extension can\n# find installed Tcl headers.\nTCL_INCLUDE_SPEC='-IC:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64\\include'\n\n# Indicates whether a version numbers should be used in -l switches\n# (\"ok\" means it's safe to use switches like -ltcl7.5;  \"nodots\" means\n# use switches like -ltcl75).  SunOS and FreeBSD require \"nodots\", for\n# example.\nTCL_LIB_VERSIONS_OK=''\n\n# String that can be evaluated to generate the part of a shared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variables\n# VERSION and SHLIB_SUFFIX.  On most UNIX systems this is\n# ${VERSION}${SHLIB_SUFFIX}.\nTCL_SHARED_LIB_SUFFIX='86t.dll'\n\n# String that can be evaluated to generate the part of an unshared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variable\n# VERSION.  On most UNIX systems this is ${VERSION}.a.\nTCL_UNSHARED_LIB_SUFFIX='86t.lib'\n\n# Location of the top-level source directory from which Tcl was built.\n# This is the directory that contains a README file as well as\n# subdirectories such as generic, unix, etc.  If Tcl was compiled in a\n# different place than the directory containing the source files, this\n# points to the location of the sources, not the location where Tcl was\n# compiled.\nTCL_SRC_DIR='C:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\..'\n\n# List of standard directories in which to look for packages during\n# \"package require\" commands.  Contains the \"prefix\" directory plus also\n# the \"exec_prefix\" directory, if it is different.\nTCL_PACKAGE_PATH=''\n\n# Tcl supports stub.\nTCL_SUPPORTS_STUBS=1\n\n# The name of the Tcl stub library (.a):\nTCL_STUB_LIB_FILE='tclstub86.lib'\n\n# -l flag to pass to the linker to pick up the Tcl stub library\nTCL_STUB_LIB_FLAG='tclstub86.lib'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# build directory.\nTCL_BUILD_STUB_LIB_SPEC='-LC:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\Release_AMD64_VC13 tclstub86.lib'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# installed directory.\nTCL_STUB_LIB_SPEC='-LC:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64\\lib tclstub86.lib'\n\n# Path to the Tcl stub library in the build directory.\nTCL_BUILD_STUB_LIB_PATH='C:\\_work\\11\\b\\tcl-core-8.6.9.0\\win\\Release_AMD64_VC13\\tclstub86.lib'\n\n# Path to the Tcl stub library in the install directory.\nTCL_STUB_LIB_PATH='C:\\_work\\11\\b\\tcltk-8.6.9.0\\amd64\\lib\\tclstub86.lib'\n\n# Flag, 1: we built Tcl with threads enabled, 0 we didn't\nTCL_THREADS=1\n\n", "num_lines": 182}
{"repo_name": "lumberyard", "repo_creator": "aws", "programming_language": "Shell", "code": "# tclooConfig.sh --\n#\n# This shell script (for sh) is generated automatically by TclOO's configure\n# script, or would be except it has no values that we substitute. It will\n# create shell variables for most of the configuration options discovered by\n# the configure script. This script is intended to be included by TEA-based\n# configure scripts for TclOO extensions so that they don't have to figure\n# this all out for themselves.\n#\n# The information in this file is specific to a single platform.\n\n# These are mostly empty because no special steps are ever needed from Tcl 8.6\n# onwards; all libraries and include files are just part of Tcl.\nTCLOO_LIB_SPEC=\"\"\nTCLOO_STUB_LIB_SPEC=\"\"\nTCLOO_INCLUDE_SPEC=\"\"\nTCLOO_PRIVATE_INCLUDE_SPEC=\"\"\nTCLOO_CFLAGS=\"\"\nTCLOO_VERSION=1.1.0\n", "num_lines": 20}
{"repo_name": "neptune-export", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\n\njar=$(find . -name neptune-export-*-all.jar -print -quit)\njava -jar ${jar} \"$@\"\n", "num_lines": 5}
{"repo_name": "opsworks-cookbooks", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nFD_FILE='/proc/sys/fs/file-nr'\nSOCKET_FILE='/proc/net/sockstat'\n\nSOCKET=`cat $SOCKET_FILE | grep sockets | awk '{print $3}'`\nFD=`cat $FD_FILE | awk '{print $1}'`\n\necho -e \"file descriptors - $FD\\nsockets - $SOCKET\\n\"\n\ngmetric -tuint8 -x180 -n\"file_descriptors\" -v$FD\ngmetric -tuint8 -x180 -n\"sockets_in_use\" -v$SOCKET", "num_lines": 12}
{"repo_name": "pg_tle", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nDEBUG=0\nPROGRAM_NAME=$(basename $0)\nPROGRAM_VERSION=\"1.1\"\n\nPGCLI=$(which psql)\nPGFLAGS_DML=\"--quiet --no-align --tuples-only\"\nPGFLAGS_QRY=\"--quiet\"\n\nversion() {\n  cat <<VERSION_EOF\n\n${PROGRAM_NAME} ${PROGRAM_VERSION}\n\nVERSION_EOF\n}\n\nusage() {\n  cat <<USAGE_EOF\n\n${PROGRAM_NAME} ${PROGRAM_VERSION}\nManage local extension in PostgreSQL using pg_tle\n\nUSAGE:\n\n  Install:\n    ${PROGRAM_NAME} \\\\\n      --action install \\\\\n      --connection \"postgresql://postgres@localhost:5432/postgres?sslmode=prefer\" \\\\\n      --name <ExtensionName> \\\\\n      --extpath <ExtensionPath>\n\n  Remove:\n    ${PROGRAM_NAME} \\\\\n      --action uninstall \\\\\n      --connection \"postgresql://postgres@localhost:5432/postgres?sslmode=prefer\" \\\\\n      --name <ExtensionName>\n\n  List:\n    ${PROGRAM_NAME} \\\\\n      --action list \\\\\n      --connection \"postgresql://postgres@localhost:5432/postgres?sslmode=prefer\"\n\n  List Versions along wtih Extensions:\n    ${PROGRAM_NAME} \\\\\n      --action list-versions \\\\\n      --connection \"postgresql://postgres@localhost:5432/postgres?sslmode=prefer\"\n\nOPTIONS:\n\n    -a, --action <action name>\n          A required parameter.\n          install - install extension\n          update - update extension\n          uninstall - uninstall extension\n          list - list extension\n          list-versions - list extension along with available versions\n\n    -c, --connection <PG Connection>\n          A required parameter.\n          PostgreSQL connection string (URI or \"Name=Value Name1=V1\" format)\n\n    -n, --name <Extension Name>\n          A required parameter for install and uninstall actions.\n          Name of the extension\n\n    -p, --extpath <Extension Path>\n          A required parameter for install action.\n          Local path of the extension\n\n    -h, --help\n          Print help information\n\n    -V, --version\n          Print version information\n\n    -m, --runmake\n          Run make to generate SQL file \n\n    -s, --sqldir <subdir where SQL is present>\n          set subdir where extension SQL files are\n\nEXIT_CODES:\n  1 - PostgreSQL command line tool psql is missing\n  2 - Missing argument or Invalid arguments value\n  3 - Extension source code folder (--extpath) not found\n  4 - Error running conencting to PostgreSQL or error executiong SQL query\n  9 - Unsupported OS\n\n* Long Options are not supported on MACOS\n\nUSAGE_EOF\n}\n\nRUN_PGSQL(){\n  if [[ \"$1\" = \"\" ]]; then\n    PG_OUTPUT=$(psql ${pgConn} ${PGFLAGS} --command=\"${SQL_QUERY}\" 2>&1)\n  else\n    PG_OUTPUT=$(psql ${pgConn} ${PGFLAGS} -f \"${1}\" 2>&1)\n  fi\n  PG_EXIT=$?\n}\nOS_TYPE=$(uname)\nif [ \"${OS_TYPE}\" = \"Linux\" ]; then\n  SUPPORTED_ARGS=$(getopt -o c:a:p:n:s:mhvd --long connection:,action:,extpath:,name:,sqldir:,runmake,help,version,debug -- \"$@\")\n  EX=$?\nelif [ \"${OS_TYPE}\" = \"Darwin\" ]; then\n  SUPPORTED_ARGS=$(getopt c:a:p:n:s:mhvd $*)\n  EX=$?\nelse\n  echo \"Unsupport OS\"\n  exit 9\nfi\nif [ $EX -gt 0 ]; then\n  printf \"\\nError parsing argument(s)\\n\" >&2\n  if [ \"${OS_TYPE}\" = \"Darwin\" ]; then\n    printf \"\\nLong arguments are not supported on MACOS\\n\" >&2\n  fi\n  usage >&2\n  exit 2\nfi\n\nRUNMAKE=0\nSQLDir=\"\"\neval set -- \"$SUPPORTED_ARGS\"\nwhile true; do\n  case \"$1\" in\n    -c | --connection)\n        pgConn=$2\n        shift 2\n        continue\n        ;;\n    -n | --name)\n        ExtName=$2\n        shift 2\n        continue\n        ;;\n    -p | --extpath)\n        ExtPath=$2\n        shift 2\n        continue\n        ;;\n    -a | --action)\n        Action=$2\n        shift 2\n        continue\n        ;;\n    -m | --runmake)\n        RUNMAKE=1\n        shift 1\n        continue\n        ;;\n    -s | --sqldir)\n        SQLDir=$2\n        shift 2\n        continue\n        ;;\n    -d | --debug)\n        DEBUG=1\n        shift 1\n        continue\n        ;;\n    -h | --help)\n        usage\n        exit 0\n        ;;\n    -v | --version)\n        version\n        exit 0\n        ;;\n    --) shift;\n        break\n        ;;\n  esac\ndone\n\nif [ $# -gt 0 ]; then\n  printf \"\\nExtra argument(s) passed, %s\\n\" \"$@\" >&2\n  usage >&2\n  exit 2\nfi\n\nif [ -z \"${PGCLI}\" ] ; then\n  printf \"\\nPostgreSQL command line client 'psql' not found in PATH\\n\" >&2\n  exit 1\nfi\n\nif [ -z \"${Action}\" ] ; then\n  printf \"\\nMissing argument(s) --action is required\\n\" >&2\n  usage >&2\n  exit 2\nfi\n\nif [ -z \"${pgConn}\" ] ; then\n  printf \"\\nMissing argument(s) --connection is required\\n\" >&2\n  usage >&2\n  exit 2\nfi\n\ncase \"$Action\" in\n  install|update)\n    if [ -z \"${ExtName}\" ] || [ -z \"${ExtPath}\" ] ; then\n      printf \"\\nMissing argument(s) --name --extpath are required for install\\n\" >&2\n      usage >&2\n      exit 2\n    fi\n    if [ ! -d ${ExtPath} ] ; then\n      printf \"\\nFATAL: Extension path %s is missing.\\n\" ${ExtPath} >&2\n      exit 3\n    fi\n    if [ ${RUNMAKE} -gt 0 ]; then\n      pushd ${ExtPath}\n      make\n      popd\n    fi\n    ExtControl=\"${ExtPath}/${ExtName}.control\"\n    ExtSQL_Template=\"${ExtPath}/${SQLDir}/${ExtName}--%s.sql\"\n    if [ ! -f \"${ExtControl}\" ] ; then\n      printf \"\\nFATAL: Extension control file %s is missing.\\n\" ${ExtControl} >&2\n      exit 3\n    fi\n    ExtensionsList=\"\"\n    printf -v ExtSQL \"${ExtSQL_Template}\" \"*\"\n    for file in ${ExtSQL}\n    do\n      if [ \"${file}\" = \"${ExtSQL}\" ]; then\n        break\n      fi\n      parsed=$(sed -e \"s:.*${ExtName}--::g;s:.sql::g;s:--:,:g; s:$:,${file}:g\" <<< ${file} )\n      ExtensionsList=\"${ExtensionsList} ${parsed}\"\n    done\n    if [ -z \"${ExtensionsList}\" ] ; then\n      printf \"\\nFATAL: Extension SQL files %s are missing.\\n\" ${ExtSQL} >&2\n      exit 3\n    fi\n    if [ ${Action} == \"update\" ]; then\n      printf \"\\nUpdating ${ExtName} from ${ExtPath} in ${pgConn}\\n\"\n    else\n      printf \"\\nInstalling ${ExtName} from ${ExtPath} in ${pgConn}\\n\"\n    fi\n    PGFLAGS=${PGFLAGS_DML}\n    DefaultRev=\"$(sed -ne \"s/ //g;s/^default_version=\\(.*\\)/\\1/p\" < ${ExtControl})\"\n    if [ -z \"${DefaultRev}\" ]; then\n      printf \"\\nFATAL: default_version not defined in %s.\\n\" ${ExtControl} >&2\n      exit 3\n    fi\n    printf -v DefaultSQL \"${ExtSQL_Template}\" ${DefaultRev//\\'/}\n    [ ${DEBUG} -gt 0 ] && echo \"\\$DefaultSQL is ${DefaultSQL}\"\n    for revs in $ExtensionsList\n    do\n      [ ${DEBUG} -gt 0 ] && echo \"Working on ${revs}\"\n      IFS=, read -r v1 v2 v3 <<< \"${revs}\"\n      if [ -z \"${v3}\" ]; then\n        if [ \"${DefaultSQL}\" != \"${v2}\" ]; then\n          [ \"${DEBUG}\" -gt 0 ] && echo \"Skip loading: ${v2}\"\n          continue\n        fi\n        SUFLAG=\"$(sed -ne \"s/ //g;s/^trusted=\\(.*\\)/\\1/p\" < ${ExtControl})\"\n        SUFLAG=${SUFLAG:-false}\n        if [ ${Action} == \"update\" ]; then\n          SQL_WHERE=\" WHERE NOT EXISTS (SELECT pg_proc.proname FROM pg_catalog.pg_proc WHERE pg_proc.proname LIKE '${ExtName}.control'::pg_catalog.name AND pg_proc.pronamespace OPERATOR(pg_catalog.=) 'pgtle'::regnamespace::oid)\"\n        else\n          SQL_WHERE=\"\"\n        fi\n        SQL_QUERY=\"SELECT FROM pgtle.install_extension('${ExtName}', '${v1}', '\"$(sed -ne \"s/^comment.*=.*'\\(.*\\)'/\\1/p\" < ${ExtControl})\"', \\$_PG_TLE_SQL_\\$$(cat ${v2})\\$_PG_TLE_SQL_\\$) ${SQL_WHERE};\"\n      else\n        if [ ${Action} == \"update\" ]; then\n          SQL_WHERE=\" WHERE NOT EXISTS (SELECT pg_proc.proname FROM pg_catalog.pg_proc WHERE pg_proc.proname LIKE '${ExtName}--${v1}--${v2}.sql'::pg_catalog.name AND pg_proc.pronamespace OPERATOR(pg_catalog.=) 'pgtle'::regnamespace::oid)\"\n        else\n          SQL_WHERE=\"\"\n        fi\n        SQL_QUERY=\"SELECT FROM pgtle.install_update_path('${ExtName}', '${v1}', '${v2}', \\$_PG_TLE_SQL_\\$$(cat ${v3})\\$_PG_TLE_SQL_\\$) ${SQL_WHERE};\"\n      fi\n      SQL_FILE=$(mktemp .$$.XXXXXXXXXXXXXXXXXXX.sql)\n      (echo \"\\\\set ON_ERROR_STOP true\";echo \"${SQL_QUERY}\") >${SQL_FILE}\n      RUN_PGSQL ${SQL_FILE}\n      [ ${DEBUG} -eq 0 ] && rm -f ${SQL_FILE}\n      if [ ${PG_EXIT} -gt 0 ]; then\n        echo \"Failed to run SQL from ${SQL_FILE}\"\n        break\n      fi\n    done\n    if [ ${PG_EXIT} -eq 0 ]; then\n      SQL_QUERY=\"SELECT FROM pgtle.set_default_version('${ExtName}', ${DefaultRev}::text);\"\n      RUN_PGSQL\n    fi\n    ;;\n  uninstall)\n    if [ -z \"${ExtName}\" ] ; then\n      printf \"\\nMissing argument(s) --name is required for uninstall\\n\" >&2\n      usage >&2\n      exit 2\n    fi\n    printf \"\\nRemoving ${ExtName} from ${pgConn}\\n\"\n    PGFLAGS=${PGFLAGS_DML}\n    SQL_QUERY=\"SELECT FROM pgtle.uninstall_extension('${ExtName}');\"\n    RUN_PGSQL\n    ;;\n  list|list-versions)\n    printf \"\\nList pg_tle installed extension(s) from ${pgConn}\\n\"\n    PGFLAGS=${PGFLAGS_QRY}\n    if [ $Action = \"list\" ] ; then\n      SQL_QUERY='SELECT * FROM pgtle.available_extensions();'\n    else\n      SQL_QUERY='SELECT * FROM pgtle.available_extension_versions();'\n    fi\n    RUN_PGSQL\n    ;;\n  *)\n    printf \"\\nInvalid Action requested, %s\\n\" \"${Action}\" >&2\n    usage >&2\n    exit 2\n    ;;\nesac\nif [ \"${PG_EXIT}\" -eq 0 ] ; then\n  if [ $Action == \"list\" ] || [ $Action == \"list-versions\" ] ; then\n    if [[ \"${PG_OUTPUT}\" == *\"(0 rows)\"* ]] ; then\n      printf \"\\nNo pg_tle managed extension(s) available in ${pgConn}\\n\"\n    else\n      printf \"\\n${PG_OUTPUT}\\n\"\n    fi\n  else\n    printf \"\\n$Action completed successfully.\\n\"\n  fi\n  exit 0\nelse\n  printf \"\\nExecution Failed\\nExit code (psql): ${PG_EXIT}\\nError (psql): ${PG_OUTPUT}\\n\" >&2\n  exit 4\nfi\n\n", "num_lines": 347}
{"repo_name": "porting-advisor-for-graviton", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource ./test-helpers.sh\n\n# This script tests container image build and runs a couple of\n# tests against the generated image.\n\nif [ -d \".venv\" ]; then\n    mv .venv .venv_temp\nfi\n\ndocker build -t porting-advisor .\nif [ $? -ne 0 ]; then\n    echo \"**ERROR**: building container image\" && exit 1\nfi\n\necho \"Running container on samples to console\"\ndocker run --rm -v $(pwd)/sample-projects:/source porting-advisor /source > console_test.txt\ntest_report 'console' 'console_test.txt' \"${lines_to_find[@]}\"\nif [ $? -ne 0 ]; then\n    echo \"**ERROR**: running container to console\" && exit 1\nfi\nrm console_test.txt\n\necho \"Running container on samples to HTML report\"\ndocker run --rm -v $(pwd):/source porting-advisor /source/sample-projects --output /source/test.html \ntest_report 'html' 'test.html' \"${lines_to_find[@]}\"\nif [ $? -ne 0 ]; then\n    echo \"**ERROR**: running container to html report\" && exit 1\nfi\nrm -f test.html\n\nif [ -d \".venv_temp\" ]; then\n    mv .venv_temp .venv\nfi\n\nexit 0\n", "num_lines": 38}
{"repo_name": "porting-advisor-for-graviton", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# get binary name\nOS_SUFFIX=\"Other\"\ncase \"$(uname -s)\" in\n    Darwin)\n        OS_SUFFIX=\"macosx\"\n        ;;\n\n    Linux)\n        OS_SUFFIX=\"linux\"\n        ;;\nesac\n\nif [ $OS_SUFFIX = \"Other\" ]\nthen\n    echo \"**ERROR**: Unsupported platform\" && exit 1\nfi\n\nPROCESSOR_SUFFIX=`uname -m`\nFILE_NAME=\"porting-advisor-$OS_SUFFIX-$PROCESSOR_SUFFIX\"\necho $FILE_NAME", "num_lines": 22}
{"repo_name": "porting-advisor-for-graviton", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource ./test-helpers.sh\n\nFILE_NAME=`./getBinaryName.sh`\nchmod +x ./dist/$FILE_NAME\n\necho \"Running samples to console\"\n./dist/$FILE_NAME ./sample-projects/ > console_test.txt\ntest_report 'console' 'console_test.txt' \"${lines_to_find[@]}\"\nrm console_test.txt\n\n\necho \"Running samples to HTML report\"\n./dist/$FILE_NAME ./sample-projects/ --output test.html\ntest_report 'html' 'test.html' \"${lines_to_find[@]}\"\nrm test.html\n\n\necho \"Running samples to Dependency Report\"\ndeclare -a dependencies=(\"<si><t>component</t></si><si><t>version</t></si><si><t>origin</t></si><si><t>filename</t></si>\"\n                        \"<si><t>junit</t></si><si><t>4.8.2</t></si>\"\n                        \"<si><t>zstd-jni</t></si><si><t>1.1.0</t></si>\"\n                        \"<si><t>snappy-java</t></si><si><t>1.1.3</t></si>\"\n                        \"<si><t>lz4-java</t></si><si><t>1.4.0</t></si>\"\n                        \"<si><t>hadoop-lzo</t></si><si><t>0.4.17</t></si>\"\n                        \"<si><t>leveldbjni-all</t></si><si><t>1.8</t></si>\"\n                        \"<si><t>CommandLineParser</t></si><si><t>2.8.0</t></si>\"\n                        \"<si><t>Microsoft.Build.Utilities.Core</t></si><si><t>17.1.0</t></si>\"\n                        \"<si><t>Microsoft.Extensions.Logging.Console</t></si><si><t>6.0.0</t></si>\"\n                        \"<si><t>Microsoft.NET.Test.Sdk</t></si><si><t>16.5.0</t></si>\"\n                        \"<si><t>Microsoft.VisualStudio.Setup.Configuration.Interop</t></si><si><t>3.1.2196</t></si>\"\n                        \"<si><t>System.Linq.Async</t></si><si><t>6.0.1</t></si>\"\n                        \"<si><t>xunit</t></si><si><t>2.4.1</t></si>\"\n                        \"<si><t>coverlet.collector</t></si><si><t>1.2.0</t></si>\"\n                        \"<si><t>SciPy</t></si>\"\n                        \"<si><t>NumPy</t></si>\"\n                        \"<si><t>FakeDependency</t></si><si><t>1.2.3</t></si>\"\n                        \"<si><t>cors</t></si><si><t>2.8.5</t></si>\"\n                        \"<si><t>express</t></si><si><t>4.18.1</t></si>\"\n                        \"<si><t>rxjs</t></si><si><t>7.5.6</t></si>\"\n                        \"<si><t>socket.io</t></si><si><t>4.5.1</t></si>\"\n                        \"<si><t>@codechecks/client</t></si><si><t>0.1.12</t></si>\"\n                        \"<si><t>@commitlint/cli</t></si><si><t>17.0.3</t></si>\"\n                        \"<si><t>eslint</t></si><si><t>7.32.0</t></si>\"\n                        \"<si><t>typescript</t></si><si><t>4.7.4</t></si>\"\n                        \"<si><t>github.com/aws/aws-sdk-go</t></si>\"\n                        \"<si><t>github.com/golang/snappy</t></si>\"\n                        \"<si><t>rails</t></si><si><t>6.1.6.1</t></si>\"\n                        \"<si><t>rake</t></si><si><t>11.1</t></si>\"\n                        \"<si><t>actionpack</t></si>\"\n                        \"<si><t>bcrypt</t></si><si><t>3.1</t></si>\"\n                        \"<si><t>cucumber</t></si><si><t>4.1</t></si>\"\n                        \"<si><t>gc_tracer</t></si>\"\n                        \"<si><t>gssapi</t></si>\"\n                        \"<si><t>mail</t></si>\"\n                        \"<si><t>turbo-rails</t></si>\"\n                        \"<si><t>httpclient</t></si>\"\n                        \"<si><t>jruby-openssl</t></si>\"\n                    )\n./dist/$FILE_NAME ./sample-projects/ --output test.xlsx --output-format dependencies\n# xlsx files are compressed files, so we need to unzip them and then compare them\nmkdir ./temp\nunzip -q ./test.xlsx -d ./temp\ntest_report 'dependencies' './temp/xl/sharedStrings.xml' \"${dependencies[@]}\"\nrm test.xlsx\nrm -rf ./temp\n\n\necho \"--- Running negative tests ---\"\n\necho \"Running missing arguments test\"\n./dist/$FILE_NAME 2>&1 | tee missing_arguments_test.txt\nif diff \"./tests-baseline/missing_arguments_test.txt\" \"missing_arguments_test.txt\"; then\n    echo \"**PASSED** missing arguments test\"\nelse\n    echo \"**FAILED**: missing arguments test\" && exit 1 \nfi\nrm missing_arguments_test.txt\n\n\necho \"Running directory not found test\"\n./dist/$FILE_NAME unexisting_directory 2>&1 | tee directory_not_found_test.txt\nif diff \"./tests-baseline/directory_not_found_test.txt\" \"directory_not_found_test.txt\"; then\n    echo \"**PASSED** directory not found test\"\nelse\n    echo \"**FAILED**: directory not found test\" && exit 1 \nfi\nrm directory_not_found_test.txt\n", "num_lines": 90}
{"repo_name": "porting-advisor-for-graviton", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nFILE_NAME=`./getBinaryName.sh`\nchmod +x ./dist/$FILE_NAME\n\ngit clone https://github.com/pytorch/pytorch.git\ntime ./dist/$FILE_NAME pytorch\nrm -rf pytorch", "num_lines": 8}
{"repo_name": "porting-advisor-for-graviton", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction test_line() {\n    reportType=$1\n    result_filename=$2\n    pattern=$3\n    if grep --quiet \"$3\" \"$result_filename\"\n    then\n        echo \"**PASS** $reportType report has: $pattern\"\n    else\n        echo \"**FAILED** $reportType report is missing: $pattern\" && exit 1\n    fi\n}\n\nfunction test_report() {\n    report_type=$1\n    shift\n    result_filename=$1\n    shift\n    patterns=(\"$@\")\n    for line in \"${patterns[@]}\";\n    do\n        test_line $report_type $result_filename \"${line[@]}\"\n    done\n}\n\ndeclare -a lines_to_find=(\"detected java code. we recommend using Corretto\"\n    \"detected python code. min version 3.7.5 is required\"\n    \"detected python code. if you need pip, version 19.3 or above is recommended\"\n    \"dependency library numpy is present. min version 1.19.0 is required\"\n    \"detected java code. min version 8 is required. version 11 or above is recommended\"\n    \"using dependency library snappy-java version 1.1.3. upgrade to at least version 1.1.4\"\n    \"using dependency library hadoop-lzo. this library requires a manual build\"\n    \"dependency library: leveldbjni-all is not supported on Graviton\"\n    \"detected go code. min version 1.16 is required. version 1.18 or above is recommended\"\n    \"using dependency library github.com/golang/snappy version 0.0.1. upgrade to at least version 0.0.2\"\n)\n", "num_lines": 38}
{"repo_name": "porting-assistant-dotnet-client", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh -e\nrm -rf ./commit-hook-tests\ndotnet test --settings scripts/coverlet.runsettings tests/PortingAssistant.Client.UnitTests/PortingAssistant.Client.UnitTests.csproj -r ./commit-hook-tests\nfor f in ./commit-hook-tests/**/*.xml\ndo\n  echo \"\"\n  echo \"Code Coverage Check: $f\"\n\n  coverage=`cat $f | grep \"<coverage\" | cut -d\" \" -f 2 | cut -d\"=\" -f 2 | cut -d\"\\\"\" -f 2`\n  if [[ (($coverage < 0.20)) ]]\n  then\n    echo \"Code coverage requirement not met. Expected: > 0.20, Actual: $coverage\"\n    exit 1\n  fi\n  echo \"Code coverage: $coverage\"\ndone", "num_lines": 16}
{"repo_name": "porting-assistant-dotnet-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\nrm -rf ./netcore_build/\nmkdir ./netcore_build/\n(dotnet publish ../csharp/PortingAssistant/PortingAssistant.Api/PortingAssistant.Api.csproj -c Release -f net6.0 -o ./netcore_build/)\n(dotnet publish ../csharp/PortingAssistant/PortingAssistant.Telemetry/PortingAssistant.Telemetry.csproj -c Release -f net6.0 -o ./netcore_build/)", "num_lines": 5}
{"repo_name": "porting-assistant-dotnet-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e\nrm -rf react_build\nmkdir react_build\nrsync -r --copy-links node_modules/@porting-assistant/react/build/* react_build/\n", "num_lines": 5}
{"repo_name": "porting-assistant-dotnet-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "set -xe\n\necho 'Executing custom build script'\n\ncurrent_package_name=$(brazil-path pkg.name)\npackage_build_dir=$(brazil-path package-build-root)\n\n\n\n# copy assets to app folder\n# rsync -avz --exclude 'app' --exclude 'brazil*' --exclude 'private' $package_build_dir/. $package_build_dir/app\n\necho 'Contents of Build folder'\nls -lhtr $package_build_dir\n\n\nrm -Rf dist && mkdir -p dist\n\ncp -R $package_build_dir/. dist/\n\ncd dist && rm -Rf brazil* && rm -Rf private\n\ncd ../ && mkdir -p $package_build_dir/app && cp -R dist/. $package_build_dir/app/\n\n", "num_lines": 25}
{"repo_name": "porting-assistant-dotnet-ui", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash -e -x\ntsc\naws s3 cp s3://portingAssistant-test-solutions/test-solutions.zip .\nunzip -o test-solutions.zip\nmkdir ../electron/test_store", "num_lines": 5}
{"repo_name": "redshift-test-drive", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\necho \"bucket_name: $BUCKET_NAME\"\necho \"simple_replay_extract_overwrite_s3_path: $SIMPLE_REPLAY_EXTRACT_OVERWRITE_S3_PATH\"\necho \"simple_replay_log_location: $SIMPLE_REPLAY_LOG_LOCATION\"\necho \"redshift_user_name: $REDSHIFT_USER_NAME\"\necho \"what_if_timestamp: $WHAT_IF_TIMESTAMP\"\necho \"simple_replay_extract_start_time: $SIMPLE_REPLAY_EXTRACT_START_TIME\"\necho \"simple_replay_extract_end_time: $SIMPLE_REPLAY_EXTRACT_END_TIME\"\necho \"extract_prefix: $EXTRACT_PREFIX\"\necho \"script_prefix: $SCRIPT_PREFIX\"\n\nyum update -y\nyum -y install git\nyum -y install python3\nyum -y install python3-pip\nyum -y install aws-cfn-bootstrap\nyum -y install gcc gcc-c++ python3 python3-devel unixODBC unixODBC-devel\nmkdir amazonutils\ncd amazonutils\ngit clone https://github.com/aws/redshift-test-drive.git\ncd redshift-test-drive\nmake setup\nif [[ \"$SIMPLE_REPLAY_EXTRACT_OVERWRITE_S3_PATH\" != \"N/A\" ]]; then\n  aws s3 cp $SIMPLE_REPLAY_EXTRACT_OVERWRITE_S3_PATH config/replay.yaml\nfi\nWORKLOAD_LOCATION=\"s3://${BUCKET_NAME}/${EXTRACT_PREFIX}/${WHAT_IF_TIMESTAMP}\"\nsed -i \"s#master_username: \\\".*\\\"#master_username: \\\"$REDSHIFT_USER_NAME\\\"#g\" config/extract.yaml\nsed -i \"s#log_location: \\\".*\\\"#log_location: \\\"$SIMPLE_REPLAY_LOG_LOCATION\\\"#g\" config/extract.yaml\nsed -i \"s#workload_location: \\\".*\\\"#workload_location: \\\"$WORKLOAD_LOCATION\\\"#g\" config/extract.yaml\nsed -i \"s#start_time: \\\".*\\\"#start_time: \\\"$SIMPLE_REPLAY_EXTRACT_START_TIME\\\"#g\" config/extract.yaml\nsed -i \"s#end_time: \\\".*\\\"#end_time: \\\"$SIMPLE_REPLAY_EXTRACT_END_TIME\\\"#g\" config/extract.yaml\naws s3 cp config/extract.yaml s3://$BUCKET_NAME/$SCRIPT_PREFIX/\nmake extract", "num_lines": 34}
{"repo_name": "redshift-test-drive", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# This script bootstraps a base amazonlinux image to run the Redshift\n# Node Config concurrency test.\n# 1. Install the AWS CLI, Python3, and necessary Python libraries.\n# 2. Copy Python program source for concurrency test\n# 3. Execute that Python program\n# We expect all configuration to be defined as environment variables\n# for the Batch job.\n\nset -eu\n\nyum install -y awscli python3\npip3 install boto3 psycopg2-binary pandas sqlalchemy\n\naws s3 cp \"$PYTHON_SCRIPT\" ./script.py\n\n# This Python program requires these environment variables to be set:\n# `$SQL_SCRIPT_S3_PATH`, `$REDSHIFT_CLUSTER_ENDPOINT`,\n# `$REDSHIFT_IAM_ROLE`, `$BUCKET_NAME`, `$REDSHIFT_USER_NAME`\npython3 ./script.py\n", "num_lines": 21}
{"repo_name": "redshift-test-drive", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\necho \"bucket_name: $BUCKET_NAME\"\necho \"simple_replay_overwrite_s3_path: $SIMPLE_REPLAY_OVERWRITE_S3_PATH\"\necho \"redshift_user_name: $REDSHIFT_USER_NAME\"\necho \"what_if_timestamp: $WHAT_IF_TIMESTAMP\"\necho \"extract_prefix: $EXTRACT_PREFIX\"\necho \"replay_prefix: $REPLAY_PREFIX\"\necho \"script_prefix: $SCRIPT_PREFIX\"\necho \"redshift_iam_role: $REDSHIFT_IAM_ROLE\"\necho \"workload_location: $WORKLOAD_LOCATION\"\necho \"cluster_endpoint: $CLUSTER_ENDPOINT\"\necho \"cluster_identifier: $CLUSTER_IDENTIFIER\"\necho \"execute_unload_statements: $SIMPLE_REPLAY_UNLOAD_STATEMENTS\"\necho \"snapshot_account_id: $SNAPSHOT_ACCOUNT_ID\"\naccount_id=`aws sts get-caller-identity --query Account --output text`\necho \"account_id: $account_id\"\necho \"endpoint_type: $ENDPOINT_TYPE\"\nTARGET_CLUSTER_REGION=$(echo $CLUSTER_ENDPOINT | cut -f3 -d'.')\n##region = os.environ['AWS_REGION']\nyum update -y\nyum -y install git\nyum -y install python3\nyum -y install python3-pip\nyum -y install aws-cfn-bootstrap\nyum -y install gcc gcc-c++ python3 python3-devel unixODBC unixODBC-devel\nmkdir amazonutils\ncd amazonutils\ngit clone https://github.com/aws/redshift-test-drive.git\ncd redshift-test-drive\nmake setup\nif [[ \"$SIMPLE_REPLAY_OVERWRITE_S3_PATH\" != \"N/A\" ]]; then\n  aws s3 cp $SIMPLE_REPLAY_OVERWRITE_S3_PATH replay.yaml\nfi\n\nsed -i \"s#master_username: \\\".*\\\"#master_username: \\\"$REDSHIFT_USER_NAME\\\"#g\" config/replay.yaml\nsed -i \"s#unload_iam_role: \\\".*\\\"#unload_iam_role: \\\"$REDSHIFT_IAM_ROLE\\\"#g\" config/replay.yaml\nsed -i \"s#workload_location: \\\".*\\\"#workload_location: \\\"$WORKLOAD_LOCATION\\\"#g\" config/replay.yaml\nsed -i \"s#target_cluster_endpoint: \\\".*\\\"#target_cluster_endpoint: \\\"$CLUSTER_ENDPOINT\\\"#g\" config/replay.yaml\nsed -i \"s#target_cluster_region: \\\".*\\\"#target_cluster_region: \\\"$TARGET_CLUSTER_REGION\\\"#g\" config/replay.yaml\nsed -i \"s#analysis_iam_role: \\\".*\\\"#analysis_iam_role: \\\"$REDSHIFT_IAM_ROLE\\\"#g\" config/replay.yaml\nsed -i \"s#analysis_output: \\\".*\\\"#analysis_output: \\\"$WORKLOAD_LOCATION\\\"#g\" config/replay.yaml\n\nif [ \"$SIMPLE_REPLAY_UNLOAD_STATEMENTS\" == \"true\" ]; then\n    sed -i \"s#unload_iam_role: \\\".*\\\"#unload_iam_role: \\\"$REDSHIFT_IAM_ROLE\\\"#g\" config/replay.yaml\n    sed -i \"s#replay_output: \\\".*\\\"#replay_output: \\\"s3://$BUCKET_NAME/$REPLAY_PREFIX/$WHAT_IF_TIMESTAMP/$CLUSTER_IDENTIFIER\\\"#g\" config/replay.yaml\nfi\n\n\nif [[ \"$account_id\" == \"$SNAPSHOT_ACCOUNT_ID\" ]]; then\n   sed -i \"s#execute_copy_statements: \\\"false\\\"#execute_copy_statements: \\\"true\\\"#g\" config/replay.yaml\n   aws s3 cp $WORKLOAD_LOCATION/copy_replacements.csv . || true\n   sed -z -i \"s#,,\\n#,,$REDSHIFT_IAM_ROLE\\n#g\" copy_replacements.csv || true\n   aws s3 cp copy_replacements.csv $WORKLOAD_LOCATION/copy_replacements.csv || true\nfi\naws s3 cp config/replay.yaml s3://$BUCKET_NAME/$SCRIPT_PREFIX/replay_$CLUSTER_IDENTIFIER.yaml\nmake replay\nif [[ $ENDPOINT_TYPE == 'SERVERLESS' ]]; then\n  aws s3 cp s3://$BUCKET_NAME/$SCRIPT_PREFIX/system_config.json .\n  aws s3 cp s3://$BUCKET_NAME/$SCRIPT_PREFIX/create_external_schema.py .\n  python3 tools/NodeConfigCompare/python_scripts/create_external_schema.py\nfi\n", "num_lines": 63}
{"repo_name": "rolesanywhere-credential-helper", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Simple script to generate key/digest permutations for testing\n# keys are shared across certificates with the same algorithm,\n# but different digests\n\nec_digests=\"sha1 sha256 sha384 sha512\"\nec_curves=\"prime256v1 secp384r1\"\n\nrsa_digests=\"md5 sha1 sha256 sha384 sha512\"\nrsa_key_lengths=\"1024 2048 4096\"\n\nscript=$(readlink -f \"$0\")\nbasedir=$(dirname \"$script\")\n\nfor c in $ec_curves; do\n\tkey_file=\"${basedir}/tst/certs/ec-${c}-key.pem\"\n\topenssl ecparam -name $c -genkey -out $key_file\n\tfor d in $ec_digests; do\n\t\tcert_file=\"${basedir}/tst/certs/ec-${c}-${d}-cert.pem\"\n\t\topenssl req -x509 -new \\\n\t\t\t-key $key_file \\\n\t\t\t-out $cert_file \\\n\t\t\t-days 365 \\\n\t\t\t-subj \"/CN=roles-anywhere-${c}-${d}\" \\\n\t\t\t-${d}\n        openssl pkcs8 -topk8 -inform PEM -outform PEM \\\n            -in ${basedir}/tst/certs/ec-${c}-key.pem \\\n            -out ${basedir}/tst/certs/ec-${c}-key-pkcs8.pem \\\n            -nocrypt\n\tdone;\ndone;\n\nfor l in $rsa_key_lengths; do\n\tkey_file=\"${basedir}/tst/certs/rsa-${l}-key.pem\"\n\topenssl genrsa -out $key_file $l\n\tfor d in $rsa_digests; do\n\t\tcert_file=\"${basedir}/tst/certs/rsa-${l}-${d}-cert.pem\"\n\t\topenssl req -x509 -new \\\n\t\t\t-key $key_file \\\n\t\t\t-out $cert_file \\\n\t\t\t-days 365 \\\n\t\t\t-subj \"/CN=roles-anywhere-rsa-${l}\"\n        openssl pkcs8 -topk8 -inform PEM -outform PEM \\\n            -in ${basedir}/tst/certs/rsa-${l}-key.pem \\\n            -out ${basedir}/tst/certs/rsa-${l}-key-pkcs8.pem \\\n            -nocrypt\n\tdone;\ndone;\n\n# Create certificate bundle\ncp ${basedir}/tst/certs/rsa-2048-sha256-cert.pem ${basedir}/tst/certs/cert-bundle.pem\ncat ${basedir}/tst/certs/ec-prime256v1-sha256-cert.pem >> ${basedir}/tst/certs/cert-bundle.pem\n", "num_lines": 54}
{"repo_name": "rolesanywhere-credential-helper", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Simple script to generate a CA certificate/private key\n# and end-entity certificate/private key for use with \n# Roles Anywhere\n\nset -exuo pipefail\n\nscript=$(readlink -f \"$0\")\nbasedir=$(dirname \"$script\")\ndata_folder=${basedir}/credential-process-data\n\n# Create root CA config file\ncat > ${data_folder}/root.conf << EOF\n[ req ]\ndistinguished_name = req_distinguished_name\nprompt = no\n\n[ req_distinguished_name ]\nCN = TEST ROOT\n\n[ v3 ]\nbasicConstraints = critical,CA:TRUE,pathlen:1\nsubjectKeyIdentifier = hash\nkeyUsage = critical, cRLSign, digitalSignature, keyCertSign\nauthorityKeyIdentifier = keyid:always,issuer:always\nEOF\n\n# Create root CA certificate and RSA private key\nopenssl req -config ${data_folder}/root.conf -days 365 -extensions v3 -keyout ${data_folder}/root-key.pem -newkey rsa:2048 -nodes -out ${data_folder}/root-cert.pem -set_serial 1 -sha256 -x509\n\n# Create client certificate config file\ncat > ${data_folder}/client.conf <<EOF\n[ req ]\ndistinguished_name = req_distinguished_name\nprompt = no\ndefault_bits = 2048\ndefault_md = sha256\n\n[ req_distinguished_name ]\nCN = TEST CLIENT\n\n[ v3 ]\nauthorityKeyIdentifier=keyid,issuer\nbasicConstraints=CA:FALSE\nkeyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment\nEOF\n\n# Create client certificate and RSA private key\nopenssl req -nodes -new -keyout ${data_folder}/client-key.pem -out ${data_folder}/client-csr.pem -config ${data_folder}/client.conf\nopenssl x509 -req -in ${data_folder}/client-csr.pem -CA ${data_folder}/root-cert.pem -CAkey ${data_folder}/root-key.pem -set_serial 2 -out ${data_folder}/client-cert.pem -days 365 -sha256 -extfile ${data_folder}/client.conf -extensions v3\n", "num_lines": 52}
{"repo_name": "s2n-quic", "repo_creator": "aws", "programming_language": "Shell", "code": "# immediately bail if any command fails\nset -e\n\necho \"generating CA private key and certificate\"\nopenssl req -nodes -new -x509 -keyout ca-key.pem -out ca-cert.pem -days 65536 -config config/ca.cnf\n\n# secp384r1 is an arbitrarily chosen curve that is supported by the default\n# security policy in s2n-tls.\n# https://github.com/aws/s2n-tls/blob/main/docs/USAGE-GUIDE.md#chart-security-policy-version-to-supported-curvesgroups\necho \"generating server private key and CSR\"\nopenssl req  -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout server-key.pem -out server.csr -config config/server.cnf\n\necho \"generating client private key and CSR\"\nopenssl req  -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout client-key.pem -out client.csr -config config/client.cnf\n\necho \"generating server certificate and signing it\"\nopenssl x509 -days 65536 -req -in server.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extensions req_ext -extfile config/server.cnf\n\necho \"generating client certificate and signing it\"\nopenssl x509 -days 65536 -req -in client.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -extensions req_ext -extfile config/client.cnf\n\necho \"verifying generated certificates\"\nopenssl verify -CAfile ca-cert.pem server-cert.pem\nopenssl verify -CAfile ca-cert.pem client-cert.pem\n\necho \"cleaning up temporary files\"\nrm server.csr\nrm client.csr\nrm ca-key.pem\n", "num_lines": 30}
{"repo_name": "s2n-quic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\n# immediately exit if an error occurs.\nset -e\n\nARTIFACT_FOLDER=\"target/release\"\nNETBENCH_ARTIFACT_FOLDER=\"target/netbench\"\n\n# the run_trial function will run the request-response scenario\n# with the driver passed in as the first argument\nrun_trial() {\n    # e.g. request-response\n    SCENARIO=$1\n    # e.g. s2n-quic\n    DRIVER=$2\n    echo \"running the $SCENARIO scenario with $DRIVER\"\n\n    # make a directory to hold the collected statistics\n    mkdir -p $NETBENCH_ARTIFACT_FOLDER/results/$SCENARIO/$DRIVER\n\n    # run the server while collecting metrics.\n    echo \"  running the server\"\n    ./$ARTIFACT_FOLDER/netbench-collector \\\n    ./$ARTIFACT_FOLDER/netbench-driver-$DRIVER-server \\\n    --scenario ./$NETBENCH_ARTIFACT_FOLDER/$SCENARIO.json \\\n    > $NETBENCH_ARTIFACT_FOLDER/results/$SCENARIO/$DRIVER/server.json &\n    # store the server process PID. $! is the most recently spawned child pid\n    SERVER_PID=$!\n\n    # sleep for a small amount of time to allow the server to startup before the\n    # client\n    sleep 1\n\n    # run the client. Port 4433 is the default for the server.\n    echo \"  running the client\"\n    SERVER_0=localhost:4433 ./$ARTIFACT_FOLDER/netbench-collector \\\n     ./$ARTIFACT_FOLDER/netbench-driver-$DRIVER-client \\\n     --scenario ./$NETBENCH_ARTIFACT_FOLDER/$SCENARIO.json \\\n     > $NETBENCH_ARTIFACT_FOLDER/results/$SCENARIO/$DRIVER/client.json\n\n    # cleanup server processes. The collector PID (which is the parent) is stored in\n    # SERVER_PID. The collector forks the driver process. The following incantation\n    # kills the child processes as well.\n    echo \"  killing the server\"\n    kill $(ps -o pid= --ppid $SERVER_PID)\n}\n\n# build all tools in the netbench workspace\ncargo build --release\n\n# generate the scenario files. This will generate .json files that can be found\n# in the netbench/target/netbench directory. Config for all scenarios is done\n# through this binary.\n./$ARTIFACT_FOLDER/netbench-scenarios --request_response.response_size=8GiB --connect.connections 42\n\nrun_trial request_response s2n-quic\nrun_trial request_response s2n-tls\n\nrun_trial connect s2n-quic\nrun_trial connect s2n-tls\n\necho \"generating the report\"\n./$ARTIFACT_FOLDER/netbench-cli report-tree $NETBENCH_ARTIFACT_FOLDER/results $NETBENCH_ARTIFACT_FOLDER/report\n", "num_lines": 68}
{"repo_name": "s2n-quic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\nset -e\nset -o pipefail\n\n# Set up the routing needed for the simulation\n/setup.sh\n\n# The following variables are available for use:\n# - ROLE contains the role of this execution context, client or server\n# - SERVER_PARAMS contains user-supplied command line parameters\n# - CLIENT_PARAMS contains user-supplied command line parameters\n\nLOG_DIR=/logs\nLOG=$LOG_DIR/logs.txt\n\nQNS_BIN=\"perf_client\"\n\nCERT_ARGS=\"\"\n\nif [ -d \"/certs\" ]; then\n    CERT_ARGS=\"--private-key /certs/priv.key --certificate /certs/cert.pem\"\nfi\n\n# Wait for the simulator to start up.\n/wait-for-it.sh sim:57832 -s -t 30\n$QNS_BIN  \\\n  --download-size \"$DOWNLOAD_B\" \\\n  --upload-size \"$UPLOAD_B\" \\\n  --duration \"$DURATION\" \\\n  --json \"$LOG_DIR/perf_client.json\" \\\n  server4:443  2>&1 | tee $LOG\n", "num_lines": 37}
{"repo_name": "s2n-quic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\n./setup.sh\n./wait-for-it.sh sim:57832 -s -t 10\n\nif [ \"$ROLE\" == \"server\" ]; then\n  iperf3 -s\nelse\n   ./wait-for-it.sh $SERVER:5201 -s -t 10\n  iperf3 -c $SERVER -t $DURATION -i 1 -R -C $IPERF_CONGESTION --json > /logs/iperf.json\nfi", "num_lines": 16}
{"repo_name": "s2n-quic", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n#\n\nset -e\nset -o pipefail\n\nexport RUST_LOG=\"debug\"\nexport RUST_BACKTRACE=\"1\"\n\n# Set up the routing needed for the simulation\n/setup.sh\n\n# The following variables are available for use:\n# - ROLE contains the role of this execution context, client or server\n# - SERVER_PARAMS contains user-supplied command line parameters\n# - CLIENT_PARAMS contains user-supplied command line parameters\n\nLOG_DIR=/logs\nLOG=$LOG_DIR/logs.txt\n\nQNS_BIN=\"s2n-quic-qns\"\nQNS_MODE=${QNS_MODE:-interop}\nTLS=${TLS:-s2n-tls}\n\n# Disable GSO as it does not work with Docker\nSERVER_PARAMS+=\" --disable-gso\"\nCLIENT_PARAMS+=\" --disable-gso\"\n\nARCH=$(uname -m)\necho $ARCH\nif [ \"$ARCH\" == \"aarch64\" ] || [ \"$ARCH\" == \"arm64\" ]; then\n  # x86 images running on ARM hardware may produce incorrect\n  # UDP checksums. These commands will force the UDP checksum to\n  # be recalculated.\n  tc qdisc add dev eth0 handle ffff: ingress\n  tc filter add dev eth0 parent ffff: matchall action csum udp\nfi\n\nif [ \"$QNS_MODE\" == \"interop\" ]; then\n    if [ \"$ROLE\" == \"server\" ]; then\n        SERVER_PARAMS+=\" --www-dir /www\"\n    elif [ \"$ROLE\" == \"client\" ]; then\n        CLIENT_PARAMS+=\" --download-dir /downloads\"\n    fi\n\n    if [ \"$TESTCASE\" == \"http3\" ]; then\n        SERVER_PARAMS+=\" --application-protocols h3\"\n        CLIENT_PARAMS+=\" --application-protocols h3\"\n    fi\nfi\n\nif [ \"$QNS_MODE\" == \"interop\" ]; then\n    SERVER_PARAMS+=\" --tls $TLS\"\n    CLIENT_PARAMS+=\" --tls $TLS\"\nfi\n\nif [ \"$TEST_TYPE\" == \"MEASUREMENT\" ] && [ -x \"$(command -v s2n-quic-qns-release)\" ]; then\n    echo \"using optimized build\"\n    QNS_BIN=\"s2n-quic-qns-release\"\n    unset RUST_LOG\nfi\n\n# https://github.com/marten-seemann/quic-interop-runner/blob/1dedeab03da41716bdc3ab84243328ac2409f9fe/README.md#building-a-quic-endpoint\n# The Interop Runner generates a key and a certificate chain and mounts it into /certs.\n# The server needs to load its private key from priv.key, and the certificate chain from cert.pem.\nif [ -d \"/certs\" ]; then\n    if [ \"$ROLE\" == \"server\" ]; then\n        SERVER_PARAMS+=\" --private-key /certs/priv.key --certificate /certs/cert.pem\"\n    elif [ \"$ROLE\" == \"client\" ]; then\n        CLIENT_PARAMS+=\" --ca /certs/ca.pem\"\n    fi\nfi\n\nif [ \"$ROLE\" == \"client\" ]; then\n    # Wait for the simulator to start up.\n    /wait-for-it.sh sim:57832 -s -t 30\n    $QNS_BIN $QNS_MODE client \\\n        $CLIENT_PARAMS \\\n        $REQUESTS > $LOG\nelif [ \"$ROLE\" == \"server\" ]; then\n    $QNS_BIN $QNS_MODE server \\\n        $SERVER_PARAMS > $LOG\nfi\n\n", "num_lines": 88}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\nset -e\n\n# cd into the script directory so it can be executed from anywhere\npushd \"$(dirname \"${BASH_SOURCE[0]}\")\"\n\n# delete the existing copy in case we have extra files\nrm -rf s2n-tls-sys/lib\nmkdir -p s2n-tls-sys/lib\nmkdir -p s2n-tls-sys/lib/tests\nmkdir -p s2n-tls-sys/src/features\n\n# we copy the C sources into the `lib` directory so they get published in the\n# actual crate artifact.\ncp -r \\\n  ../../api \\\n  ../../crypto \\\n  ../../error \\\n  ../../pq-crypto \\\n  ../../stuffer \\\n  ../../tls \\\n  ../../utils \\\n  s2n-tls-sys/lib/\n\ncp -r \\\n  ../../tests/features \\\n  s2n-tls-sys/lib/tests/\n\ncp -r \\\n  ../../CMakeLists.txt \\\n  ../../cmake \\\n  s2n-tls-sys/lib/\n\n# generate the bindings modules from the copied sources\npushd generate\ncargo run -- ../s2n-tls-sys\npopd\n\n# make sure everything builds and passes sanity checks\npushd s2n-tls-sys\ncargo test\ncargo test --all-features\ncargo test --release\ncargo publish --dry-run --allow-dirty\ncargo publish --dry-run --allow-dirty --all-features\npopd\n\npushd integration\ncargo run\npopd\n\npopd\n", "num_lines": 56}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "# immediately bail if any command fails\nset -e\n\npushd \"$(dirname \"$0\")\"\n\necho \"generating CA private key and certificate\"\nopenssl req -nodes -new -x509 -keyout ca-key.pem -out ca-cert.pem -days 65536 -config config/ca.cnf\n\n# secp384r1 is an arbitrarily chosen curve that is supported by the default\n# security policy in s2n-tls.\n# https://github.com/aws/s2n-tls/blob/main/docs/USAGE-GUIDE.md#chart-security-policy-version-to-supported-curvesgroups\necho \"generating server private key and CSR\"\nopenssl req  -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout server-key.pem -out server.csr -config config/server.cnf\n\necho \"generating client private key and CSR\"\nopenssl req  -new -nodes -newkey ec -pkeyopt ec_paramgen_curve:secp384r1 -keyout client-key.pem -out client.csr -config config/client.cnf\n\necho \"generating server certificate and signing it\"\nopenssl x509 -days 65536 -req -in server.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out server-cert.pem -extensions req_ext -extfile config/server.cnf\n\necho \"generating client certificate and signing it\"\nopenssl x509 -days 65536 -req -in client.csr -CA ca-cert.pem -CAkey ca-key.pem -CAcreateserial -out client-cert.pem -extensions req_ext -extfile config/client.cnf\n\necho \"verifying generated certificates\"\nopenssl verify -CAfile ca-cert.pem server-cert.pem\nopenssl verify -CAfile ca-cert.pem client-cert.pem\n\ncat server-cert.pem ca-cert.pem > fullchain.pem\n\necho \"cleaning up temporary files\"\nrm server.csr\nrm client.csr\nrm ca-key.pem\n\npopd\n", "num_lines": 36}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n# SPDX-License-Identifier: Apache-2.0\n\n# this script will generate all of the certs used for the tokio examples and\n# tests.\n\n# used for TLS 1.2 connections\necho \"generating rsa key and cert\"\nopenssl req -x509 -newkey rsa:4096 -keyout key_rsa.pem -out cert_rsa.pem -sha256 -days 36500 -nodes -subj \"/C=US/ST=AZ/L=Tempe/O=Maas/OU=BioComputing/CN=localhost\"\n\n\n# used for TLS 1.3 connections\necho \"generating ec key and cert\"\nopenssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -keyout key.pem -out cert.pem -sha256 -days 36500 -nodes -subj \"/C=US/ST=AZ/L=Tempe/O=Amazon/OU=AmazonWebServices/CN=localhost\"\n", "num_lines": 15}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"build_aws_crt_cpp.sh build_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nsource codebuild/bin/s2n_setup_env.sh\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\n\nmkdir -p \"$BUILD_DIR/s2n\"\n# In case $BUILD_DIR is a subdirectory of current directory\nfor file in *;do test \"$file\" != \"$BUILD_DIR\" && cp -r \"$file\" \"$BUILD_DIR/s2n\";done\ncd \"$BUILD_DIR\"\ngit clone --depth 1 --shallow-submodules --recurse-submodules https://github.com/awslabs/aws-crt-cpp.git\n# Replace S2N\nrm -r aws-crt-cpp/crt/s2n\nmv s2n aws-crt-cpp/crt/\n\ncmake ./aws-crt-cpp -Bbuild -GNinja -DBUILD_DEPS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=\"${INSTALL_DIR}\"\nninja -C ./build install\nCTEST_OUTPUT_ON_FAILURE=1 CTEST_PARALLEL_LEVEL=$(nproc) ninja -C ./build test\n\npopd\n\nexit 0\n", "num_lines": 49}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# Get a list of changed files\nchanged_files=$(git diff origin/main --name-only )\n\n# Run clang-format on each changed file\nfor file in $changed_files\ndo\n    if [[ $file == *.c || $file == *.h ]]; then # Only run on .c and .h files\n        echo \"clang formatting ${file}\"\n        clang-format -i $file\n    fi\ndone\n", "num_lines": 26}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nS2N_FILES=$(find \"$PWD\" -type f -name \"s2n_*.[ch]\")\nS2N_FILES+=\" \"\nS2N_FILES+=$(find \"$PWD\"/codebuild/ -type f -name \"*.sh\")\nS2N_FILES+=\" \"\nS2N_FILES+=$(find \"$PWD\"/tests/ -type f -name \"*.sh\")\n\nFAILED=0\n\nfor file in $S2N_FILES; do\n    # The word \"Copyright\" should appear at least once in the first 3 lines of every file\n    COUNT=`head -3 $file | grep \"Copyright\" | wc -l`;\n    if [ \"$COUNT\" == \"0\" ];\n    then\n        FAILED=1;\n        echo \"Copyright Check Failed: $file\";\n    fi\ndone\n\nif [ $FAILED == 1 ];\nthen\n    printf \"\\\\033[31;1mFAILED Copyright Check\\\\033[0m\\\\n\"\n    exit -1\nelse\n    printf \"\\\\033[32;1mPASSED Copyright Check\\\\033[0m\\\\n\"\nfi\n", "num_lines": 43}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\n\nsource codebuild/bin/s2n_setup_env.sh\n\n# LLVM complains about corrupt coverage information\n# for static targets, so compile to a shared lib\n# instead.\ncmake . -Bbuild \\\n    -DCOVERAGE=ON \\\n    -DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT \\\n    -DBUILD_SHARED_LIBS=ON\n\ncmake --build ./build -- -j $(nproc)\n\necho \"done with the build\"\n", "num_lines": 30}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\n\n# merge profiling data\nllvm-profdata merge -failure-mode=all -sparse tests/unit/ut_*.profraw -o merged.profdata\n\n# generate file-level summary\nllvm-cov report build/lib/libs2n.so \\\n    -instr-profile=merged.profdata \\\n    > coverage_summary.txt\n\n# convert llvm information to lcov format for genhtml\nllvm-cov export build/lib/libs2n.so \\\n    -instr-profile=merged.profdata \\\n    -format=lcov \\\n    > unit_test_coverage.info\n\n# generate html report with annotated source files\ngenhtml unit_test_coverage.info \\\n    --branch-coverage \\\n    -o coverage_report\n", "num_lines": 35}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\necho \"The codebuild source version is ${CODEBUILD_SOURCE_VERSION}\"\n\nCLOUDFRONT_DISTRIBUTION=\"https://dx1inn44oyl7n.cloudfront.net\"\n\naws s3 sync coverage_report      s3://s2n-tls-public-coverage-artifacts/${CODEBUILD_SOURCE_VERSION}/report\naws s3 cp   coverage_summary.txt s3://s2n-tls-public-coverage-artifacts/${CODEBUILD_SOURCE_VERSION}/summary.txt\n\necho \"report : is at ${CLOUDFRONT_DISTRIBUTION}/${CODEBUILD_SOURCE_VERSION}/report/index.html\"\necho \"summary: is at ${CLOUDFRONT_DISTRIBUTION}/${CODEBUILD_SOURCE_VERSION}/summary.txt\"\n", "num_lines": 26}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nS2N_FILES=$(find \"$PWD\" -type f -name \"s2n*.[ch]\")\n\nFAILED=0\n\nfor file in $S2N_FILES; do\n    # There should be no c++ style comments: //\n    RESULT=`grep -rnv '\\*' $file | grep '\\B\\/\\/.*$' | grep -v '\\\".*\\\"'`;\n    if [ \"${#RESULT}\" != \"0\" ];\n    then\n        FAILED=1;\n        printf \"\\e[1;34mC++ Comments Check Failed in $file:\\e[0m\\n$RESULT\\n\\n\";\n    fi\ndone\n\nif [ $FAILED == 1 ];\nthen\n    printf \"\\\\033[31;1mFAILED C++ Comments Check\\\\033[0m\\\\n\"\n    exit -1\nelse\n    printf \"\\\\033[32;1mPASSED C++ Comments Check\\\\033[0m\\\\n\"\nfi", "num_lines": 36}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -eu\nsource codebuild/bin/s2n_setup_env.sh\nsource codebuild/bin/utils.sh\n\n# Disable PQ\nexport S2N_NO_PQ=1\n# Limit the number of child processes in the test run\nexport XDIST_WORKERS=2\nexport RUST_BACKTRACE=1\nexport TOX_TEST_NAME=\"$INTEGV2_TEST\"\n\n# There can be only one artifact config per batch job,\n# so we're scipting the baseline upload steps here.\nupload_artifacts(){\n  cd tests/integrationv2/target/criterion\n  echo \"Creating zip ${AWS_S3_PATH}\"\n  zip -r \"${AWS_S3_PATH}\" ./*\n  aws s3 cp \"${AWS_S3_PATH}\" \"${AWS_S3_URL}\"\n  echo \"S3 upload complete\"\n}\n\nif [ -d \"third-party-src\" ]; then\n  echo \"Not running against c.a.c.\"\n  return 0\nfi\n\n# setting LOCAL_TESTING disables a check for an existing baseline.\nif [ -z \"${LOCAL_TESTING:-}\" ]; then\n  # Fetch creds and the latest release number.\n  gh_login s2n_codebuild_PRs\n  LATEST_RELEASE_VER=$(get_latest_release)\n  # Build a specific filename for this release\n  AWS_S3_PATH=\"integv2criterion_${INTEGV2_TEST}_${LATEST_RELEASE_VER}.zip\"\n  zip_count=$(aws s3 ls \"${AWS_S3_URL}${AWS_S3_PATH}\"|wc -l||true)\n\n  # Only do the baseline if an artifact for the current release doesn't exist.\n  if [ \"$zip_count\" -eq 0 ]; then\n    echo \"File ${AWS_S3_URL}${AWS_S3_PATH} not found\"\n    criterion_install_deps\n    ORIGINAL_COMMIT=$(git rev-parse HEAD)\n    git fetch --tags\n    git checkout \"$LATEST_RELEASE_VER\"\n    S2N_USE_CRITERION=baseline make -C tests/integrationv2 \"$INTEGV2_TEST\"\n    upload_artifacts\n    git reset --hard  ${ORIGINAL_COMMIT}\n  else\n    echo \"Found existing artifact for ${LATEST_RELEASE_VER}, not rebuilding.\"\n    exit 0\n  fi\nelse\n  echo \"Local testing enabled; baselining without checking s3\"\n  criterion_install_deps\n  S2N_USE_CRITERION=baseline make -C tests/integrationv2 \"$INTEGV2_TEST\"\nfi\n\n", "num_lines": 70}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\nset -eu\nsource ./codebuild/bin/utils.sh\n# Disable PQ\nexport S2N_NO_PQ=1\nexport AWS_S3_BUCKET=\"s3://s2n-tls-logs/\"\n# Limit the number of child processes in the test run\nexport XDIST_WORKERS=4\nexport RUST_BACKTRACE=1\n\nexport GIT_COMMIT=$(git log -n 1 --format=\"%h\")\nexport AWS_S3_REPORT_PATH=\"reports/${INTEGV2_TEST}/$(date +%Y%m%d_%H%M_${GIT_COMMIT})\"\n\n# CodeBuild artifacts are too limited;\n# scipting the baseline download steps here.\ndownload_artifacts(){\n  mkdir -p ./tests/integrationv2/target/criterion || true\n  echo \"Downloading ${AWS_S3_BUCKET}${1}/${2}\"\n  pushd  ./tests/integrationv2/target/criterion/\n  aws s3 cp \"${AWS_S3_BUCKET}${1}/${2}\" .\n  unzip -o \"${2}\"\n  echo \"S3 download complete\"\n  popd\n}\n\nupload_report(){\n  cd tests/integrationv2/target/criterion\n  echo \"Uploading report to ${AWS_S3_BUCKET}/${AWS_S3_REPORT_PATH}\"\n  aws s3 sync . \"${AWS_S3_BUCKET}${AWS_S3_REPORT_PATH}\"\n  echo \"S3 upload complete\"\n}\n\n# Fetch creds and the latest release number.\ngh_login s2n_codebuild_PRs\nLATEST_RELEASE_VER=$(get_latest_release)\nAWS_ZIPFILE=\"integv2criterion_${INTEGV2_TEST}_${LATEST_RELEASE_VER}.zip\"\nAWS_S3_BASE_PATH=\"release\"\ncriterion_install_deps\ndownload_artifacts ${AWS_S3_BASE_PATH} ${AWS_ZIPFILE}\n\necho \"Current dir: $(pwd)\"\nS2N_USE_CRITERION=delta make -C tests/integrationv2 \"$INTEGV2_TEST\"\nupload_report\n\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\nCLANG_NINE=$(which clang-format-9)\nCLANG_VER=${CLANG_NINE:-clang-format}\nfor i in $(find . -not -path \"./test-deps/*\" -name '*.h' -or -name '*.c' -or -name '*.cpp'); do\n        $CLANG_VER --verbose -i \"$i\" ;\ndone\n\nif [[ `git status --porcelain` ]]; then\n        echo \"clang-format updated files, throwing an error\"\n        exit 255\nelse\n        echo \"No files touched\"\nfi\n", "num_lines": 28}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nFAILED=0\n\n#############################################\n# Grep for any instances of raw memcpy() function. s2n code should instead be\n# using one of the *_ENSURE_MEMCPY macros.\n#############################################\nS2N_FILES_ASSERT_NOT_USING_MEMCPY=$(find \"$PWD\" -type f -name \"s2n*.[ch]\" -not -path \"*/tests/*\"  -not -path \"*/pq-crypto/*\")\nfor file in $S2N_FILES_ASSERT_NOT_USING_MEMCPY; do\n  RESULT_NUM_LINES=`grep 'memcpy(' $file | wc -l`\n  if [ \"${RESULT_NUM_LINES}\" != 0 ]; then\n    echo \"Found ${RESULT_NUM_LINES} raw 'memcpy' calls in $file\"\n    FAILED=1\n  fi\ndone\n\n#############################################\n# Grep for any instances of raw memcmp() function. s2n code should instead be\n# using s2n_constant_time_equals()\n#\n# KNOWN_MEMCMP_USAGE is used to capture all known uses of memcmp and acts as a\n# safeguard against any new uses of memcmp.\n#############################################\nS2N_FILES_ASSERT_NOT_USING_MEMCMP=$(find \"$PWD\" -type f -name \"s2n*.[ch]\" -not -path \"*/tests/*\" -not -path \"*/bindings/*\")\ndeclare -A KNOWN_MEMCMP_USAGE\nKNOWN_MEMCMP_USAGE[\"$PWD/crypto/s2n_rsa.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_early_data.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_kem.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_cipher_suites.c\"]=3\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_server_hello.c\"]=3\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_security_policies.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_psk.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_config.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_resume.c\"]=2\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_connection.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/tls/s2n_protocol_preferences.c\"]=1\nKNOWN_MEMCMP_USAGE[\"$PWD/utils/s2n_map.c\"]=3\nKNOWN_MEMCMP_USAGE[\"$PWD/stuffer/s2n_stuffer_text.c\"]=1\n\nfor file in $S2N_FILES_ASSERT_NOT_USING_MEMCMP; do\n  # NOTE: this matches on 'memcmp', which will also match comments. However, there\n  # are no uses of 'memcmp' in comments so we opt for this stricter check.\n  RESULT_NUM_LINES=`grep -n 'memcmp' $file | wc -l`\n\n  # set default KNOWN_MEMCMP_USAGE value\n  [ -z \"${KNOWN_MEMCMP_USAGE[\"$file\"]}\" ] && KNOWN_MEMCMP_USAGE[\"$file\"]=\"0\"\n\n  # check if memcmp usage is 0 or a known value\n  if [ \"${RESULT_NUM_LINES}\" != \"${KNOWN_MEMCMP_USAGE[\"$file\"]}\" ]; then\n    echo \"Expected: ${KNOWN_MEMCMP_USAGE[\"$file\"]} Found: ${RESULT_NUM_LINES} usage of 'memcmp' in $file\"\n    FAILED=1\n  fi\ndone\n\n#############################################\n# Assert that functions do not return -1 or S2N_ERR* codes directly.\n# To indicate failure, functions should use the S2N_ERROR* macros defined\n# in s2n_errno.h.\n#############################################\nS2N_FILES_ASSERT_RETURN=$(find \"$PWD\" -type f -name \"s2n*.c\" -not -path \"*/tests/*\" -not -path \"*/docs/examples/*\")\nfor file in $S2N_FILES_ASSERT_RETURN; do\n  RESULT_NEGATIVE_ONE=`grep -rn 'return -1;' $file`\n  RESULT_S2N_ERR=`grep -rn 'return S2N_ERR*' $file`\n  RESULT_S2N_FAIL=`grep -rn 'return S2N_FAIL*' $file`\n\n  if [ \"${#RESULT_NEGATIVE_ONE}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mGrep for 'return -1;' check failed in $file:\\e[0m\\n$RESULT_NEGATIVE_ONE\\n\\n\"\n  fi\n  if [ \"${#RESULT_S2N_ERR}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mGrep for 'return S2N_ERR*' check failed in $file:\\e[0m\\n$RESULT_S2N_ERR\\n\\n\"\n  fi\n  if [ \"${#RESULT_S2N_FAIL}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mGrep for 'return S2N_FAIL*' check failed in $file:\\e[0m\\n$RESULT_S2N_FAIL\\n\\n\"\n  fi\ndone\n\n#############################################\n# Detect any array size calculations that are not using the s2n_array_len() function.\n#############################################\nS2N_FILES_ARRAY_SIZING_RETURN=$(find \"$PWD\" -type f -name \"s2n*.c\" -path \"*\")\nfor file in $S2N_FILES_ARRAY_SIZING_RETURN; do\n  RESULT_ARR_DIV=`grep -Ern 'sizeof\\((.*)\\) \\/ sizeof\\(\\1\\[0\\]\\)' $file`\n\n  if [ \"${#RESULT_ARR_DIV}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mUsage of 'sizeof(array) / sizeof(array[0])' check failed. Use s2n_array_len(array) instead in $file:\\e[0m\\n$RESULT_ARR_DIV\\n\\n\"\n  fi\ndone\n\n#############################################\n# Assert that all assignments from s2n_stuffer_raw_read() have a\n# notnull_check (or similar manual null check) on the same, or next, line.\n# The assertion is shallow; this doesn't guarantee that we're doing the\n# *correct* null check, just that we are doing *some* null check.\n#############################################\nS2N_FILES_ASSERT_NOTNULL_CHECK=$(find \"$PWD\" -type f -name \"s2n*.[ch]\" -not -path \"*/tests/*\")\nfor file in $S2N_FILES_ASSERT_NOTNULL_CHECK; do\n  while read -r line_one; do\n    # When called with the -A option, grep uses lines of \"--\" as delimiters. We ignore them.\n    if [[ $line_one == \"--\" ]]; then\n      continue\n    fi\n\n    read -r line_two\n\n    # $line_one definitely contains an assignment from s2n_stuffer_raw_read(),\n    # because that's what we grepped for. So verify that either $line_one or\n    # $line_two contains a null check.\n    null_check_regex=\"(.*(if|ENSURE).*=\\ NULL)|(ENSURE_REF)\"\n    if [[ $line_one =~ $null_check_regex ]] || [[ $line_two =~ $null_check_regex ]]; then\n      # Found a notnull_check\n      continue\n    else\n      FAILED=1\n      printf \"\\e[1;34mFound a call to s2n_stuffer_raw_read without an ENSURE_REF in $file:\\e[0m\\n$line_one\\n\\n\"\n    fi\n  done < <(grep -rnE -A 1 \"=\\ss2n_stuffer_raw_read\\(.*\\)\" $file)\ndone\n\n#############################################\n# Assert that \"index\" is not a variable name. An \"index\" function exists in strings.h, and older compilers (<GCC 4.8) \n# warn if any local variables called \"index\" are used because they are considered to shadow that declaration. \n#############################################\nS2N_FILES_ASSERT_VARIABLE_NAME_INDEX=$(find \"$PWD\" -type f -name \"s2n*.[ch]\")\nfor file in $S2N_FILES_ASSERT_VARIABLE_NAME_INDEX; do\n  RESULT_VARIABLE_NAME_INDEX=`gcc -fpreprocessed -dD -E -w $file | grep -v '\"' | grep '[\\*|,|;|[:space:]]index[;|,|\\)|[:space:]]'`\n  if [ \"${#RESULT_VARIABLE_NAME_INDEX}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mGrep for variable name 'index' check failed in $file:\\e[0m\\n$RESULT_VARIABLE_NAME_INDEX\\n\\n\"\n  fi\ndone\n\n#############################################\n# Assert that we didn't accidentally add an extra semicolon when ending a line.\n# This also errors when there is whitespace in-between semicolons, as that is an empty\n# statement and usually not purposeful.\n#############################################\nS2N_FILES_ASSERT_DOUBLE_SEMICOLON=$(find \"$PWD\" -type f -name \"s2n*.[ch]\" -not -path \"*/bindings/*\")\nfor file in $S2N_FILES_ASSERT_DOUBLE_SEMICOLON; do\n  RESULT_DOUBLE_SEMICOLON=`grep -Ern ';[[:space:]]*;' $file`\n  if [ \"${#RESULT_DOUBLE_SEMICOLON}\" != \"0\" ]; then\n    FAILED=1\n    printf \"\\e[1;34mFound a double semicolon in $file:\\e[0m\\n$RESULT_DOUBLE_SEMICOLON\\n\\n\"\n  fi\ndone\n\n#############################################\n## Assert that there are no new uses of S2N_ERROR_IF\n# TODO add crypto, tls (see https://github.com/aws/s2n-tls/issues/2635)\n#############################################\nS2N_ERROR_IF_FREE=\"bin error pq-crypto scram stuffer utils tests\"\nfor dir in $S2N_ERROR_IF_FREE; do\n  files=$(find \"$dir\" -type f -name \"*.c\" -path \"*\")\n  for file in $files; do\n    result=`grep -Ern 'S2N_ERROR_IF' $file`\n    if [ \"${#result}\" != \"0\" ]; then\n      FAILED=1\n      printf \"\\e[1;34mUsage of 'S2N_ERROR_IF' check failed. Use 'POSIX_ENSURE' instead in $file:\\e[0m\\n$result\\n\\n\"\n    fi\n  done\ndone\n\n#############################################\n## Assert all \".[c|h]\" source files have the correct file mode.\n#############################################\nS2N_FILES_WITH_WRONG_MODE=$(find \"$PWD\" \\( -name '*.c' -o -name '*.h' \\) -a \\! -perm 644)\nif [[ -n $S2N_FILES_WITH_WRONG_MODE ]]; then\n  for file in $S2N_FILES_WITH_WRONG_MODE; do\n    FAILED=1\n    printf \"\\\\033[31;1mFile mode of %s is not 644.\\\\033[0m\\\\n\" \"$file\"\n  done\n  printf \"\\\\033[31;1mPlease run \\`find s2n-tls/ -name '*.c' -o -name '*.h' -exec chmod 644 {} \\\\;\\` to fix all file modes.\\\\033[0m\\\\n\"\nfi\n\n#############################################\n## Assert \"extern\" is not added to function declarations unnecessarily.\n#############################################\nS2N_UNNECESSARY_EXTERNS=$(find \"$PWD\" -type f -name \"s2n*.[h]\" \\! -path \"*/api/*\" \\! -path \"*/bindings/*\" \\\n  -exec grep -RE \"extern (.*?) (.*?)\\(\" {} +)\nif [[ -n $S2N_UNNECESSARY_EXTERNS ]]; then\n  FAILED=1\n  printf \"\\e[1;34mFound unnecessary 'extern' in function declaration:\\e[0m\\n\"\n  printf \"$S2N_UNNECESSARY_EXTERNS\\n\\n\"\nfi\n\n#############################################\n# Assert ENSURE/GUARD have a valid error code\n#############################################\nS2N_ENSURE_WITH_INVALID_ERROR_CODE=$(find \"$PWD\" -type f -name \"s2n*.c\" -path \"*\" \\! -path \"*/tests/*\" \\\n    -exec grep -RE \"(ENSURE|GUARD_OSSL)\\(.*?, .*?);\" {} + | grep -v \"S2N_ERR_\")\nif [[ -n $S2N_ENSURE_WITH_INVALID_ERROR_CODE ]]; then\n  FAILED=1\n  printf \"\\e[1;34mENSURE and GUARD_OSSL require a valid error code from errors/s2n_errno.h:\\e[0m\\n\"\n  printf \"$S2N_ENSURE_WITH_INVALID_ERROR_CODE\\n\\n\"\nfi\n\n#############################################\n# REPORT FINAL RESULTS\n#############################################\nif [ $FAILED == 1 ]; then\n  printf \"\\\\033[31;1mFAILED Grep For Simple Mistakes check\\\\033[0m\\\\n\"\n  exit -1\nelse\n  printf \"\\\\033[32;1mPASSED Grep For Simple Mistakes check\\\\033[0m\\\\n\"\nfi\n", "num_lines": 222}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\nsource ./codebuild/bin/s2n_setup_env.sh\n\nif [[ ${DISTRO} != \"amazon linux\" ]]; then\n    echo \"Target AL2, but running on $DISTRO: Nothing to do.\"\n    exit 0\nfi\n\nbase_packages() {\n    # Latest AL2 image had dependency issues related to NodeJS.\n    # We don't use NodeJS, so just remove it.\n    yum erase -y nodejs || true\n    yum update -y\n    # The default openssl-devel on AL2 is openssl-1.0.\n    # We replace it with openssl-1.1 later in the build process.\n    yum erase -y openssl-devel || true\n    yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm || true\n    yum install amazon-linux-extras\n\n    # Who owns this package? It needs updating to not install modules under python2.7\n    PYTHON=$(which python2) amazon-linux-extras install -y ruby2.6 rust1 python3.8\n    PYTHON=$(which python2) amazon-linux-extras enable epel\n    PYTHON=$(which python2) amazon-linux-extras enable corretto8\n    yum install -y openssh-clients\n}\n\nmono() {\n    rpm --import https://download.mono-project.com/repo/xamarin.gpg\n    curl https://download.mono-project.com/repo/centos7-stable.repo | tee /etc/yum.repos.d/mono-centos7-stable.repo\n}\n\nsymlink_all_the_things() {\n    # Package owners should be doing this.\n    # Note the version number at the end allows for upgrades to supersede these.\n    update-alternatives --install /usr/bin/pip pip3 /usr/bin/pip3 300\n    update-alternatives --install /usr/bin/ninja ninja /usr/bin/ninja-build 170\n    update-alternatives --install /usr/bin/cmake cmake /usr/bin/cmake3 313\n    update-alternatives --install /usr/bin/gcc-7 gcc /usr/bin/gcc 700\n    update-alternatives --install /usr/bin/g++-7 g++ /usr/bin/g++ 700\n    update-alternatives --install /usr/bin/g++-7 g++ /usr/bin/g++ 700\n}\n\n\nbase_packages\nmono\nyum groupinstall -y \"Development tools\"\nyum install -y clang cmake3 iproute net-tools nettle-devel nettle openssl11-static openssl11-libs openssl11-devel which sudo psmisc python3-pip  tcpdump unzip zlib-devel libtool ninja-build valgrind  wget which\nsymlink_all_the_things\n", "num_lines": 64}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\nsource codebuild/bin/s2n_setup_env.sh\n\nusage() {\n    echo \"install_apache2.sh config_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nAPACHE2_CONFIG_DIR=\"$1\"\nAPACHE2_INSTALL_DIR=\"$2\"\n\napache_enable() {\n    item_type=\"$1\"\n    item=\"$2\"\n    required=\"$3\"\n\n    source_path=\"/etc/apache2/${item_type}-available/${item}\"\n    dest_path=\"${APACHE2_INSTALL_DIR}/${item_type}-enabled/${item}\"\n\n    if [ ! -f \"${source_path}\" ]; then\n        if [ \"$required\" = true ]; then\n            echo \"apache item not found: ${source_path}\"\n            exit 1\n        fi\n\n        return\n    fi\n\n    ln -s \"$source_path\" \"$dest_path\"\n}\n\nmod_enable() {\n    mod=\"$1\"\n    apache_enable \"mods\" \"${mod}.load\" true\n    apache_enable \"mods\" \"${mod}.conf\" false\n}\n\nconf_enable() {\n    conf=\"$1\"\n    apache_enable \"conf\" \"${conf}.conf\" true\n}\n\ncp -r \"${APACHE2_CONFIG_DIR}\" \"${APACHE2_INSTALL_DIR}\"\nmkdir \"${APACHE2_INSTALL_DIR}/mods-enabled\"\nmkdir \"${APACHE2_INSTALL_DIR}/conf-enabled\"\nmkdir \"${APACHE2_INSTALL_DIR}/run\"\nmkdir \"${APACHE2_INSTALL_DIR}/lock\"\nmkdir \"${APACHE2_INSTALL_DIR}/log\"\n\n# Enable default mods\nDEFAULT_MODS=(\"access_compat\" \"alias\" \"auth_basic\" \"authn_core\" \"authn_file\" \"authz_core\" \"authz_host\" \"authz_user\"\n              \"autoindex\" \"deflate\" \"dir\" \"env\" \"filter\" \"mime\" \"mpm_event\" \"negotiation\" \"reqtimeout\" \"setenvif\"\n              \"socache_shmcb\" \"status\" \"ssl\")\nfor mod in \"${DEFAULT_MODS[@]}\"; do\n    mod_enable \"$mod\"\ndone\n\n# Enable default configuration\nDEFAULT_CONF=(\"charset\" \"localized-error-pages\" \"other-vhosts-access-log\" \"security\" \"serve-cgi-bin\")\nfor conf in \"${DEFAULT_CONF[@]}\"; do\n    conf_enable \"$conf\"\ndone\n", "num_lines": 83}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_awslc.sh build_dir install_dir is_fips\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nIS_FIPS=$3\n\nsource codebuild/bin/jobs.sh\n\n# These tags represents the latest versions that S2N is compatible\n# with. It prevents our build system from breaking when AWS-LC\n# is updated, last done on 2023-02-22.\nif [ \"$IS_FIPS\" == \"1\" ]; then\n  AWSLC_VERSION=AWS-LC-FIPS-1.0.3\nelse\n  AWSLC_VERSION=v1.8.0\nfi\nmkdir -p \"$BUILD_DIR\"||true\ncd \"$BUILD_DIR\"\necho \"Checking out tag=$AWSLC_VERSION\"\n# --branch can also take tags and detaches the HEAD at that commit in the resulting repository\n# --depth 1 Create a shallow clone with a history truncated to 1 commit\ngit clone https://github.com/awslabs/aws-lc.git --branch \"$AWSLC_VERSION\" --depth 1\n\ninstall_awslc() {\n\techo \"Building with shared library=$1\"\n\tcmake ./aws-lc -Bbuild -GNinja -DBUILD_SHARED_LIBS=$1 -DCMAKE_BUILD_TYPE=relwithdebinfo -DCMAKE_INSTALL_PREFIX=\"${INSTALL_DIR}\" -DFIPS=\"${IS_FIPS}\"\n\tninja -j \"${JOBS}\" -C build install\n\tninja -C build clean\n}\n\nif [ \"$IS_FIPS\" != \"1\" ]; then\n  install_awslc 0\nfi\n\ninstall_awslc 1\n\nexit 0\n", "num_lines": 62}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -e\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_awslc_fips_2022.sh build_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\n\nsource codebuild/bin/jobs.sh\n\n# There are currently no AWSLC release tags for the 2022 FIPS branch. The\n# following is the latest commit in this branch as of 4/5/23:\n# https://github.com/aws/aws-lc/commits/fips-2022-11-02\nAWSLC_VERSION=03ea7816359a3e1babdf9f2cd0e694977c36ebbc\n\nmkdir -p \"$BUILD_DIR\" || true\ncd \"$BUILD_DIR\"\ngit clone https://github.com/aws/aws-lc.git\ncd aws-lc\ngit checkout \"${AWSLC_VERSION}\"\n\nbuild() {\n    shared=$1\n    cmake . -Bbuild -GNinja -DBUILD_SHARED_LIBS=\"${shared}\" -DCMAKE_BUILD_TYPE=relwithdebinfo -DCMAKE_INSTALL_PREFIX=\"${INSTALL_DIR}\" -DFIPS=1\n    ninja -j \"${JOBS}\" -C build install\n    ninja -C build clean\n}\n\nbuild 0\nbuild 1\n\nexit 0\n", "num_lines": 54}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_boringssl.sh build_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nsource codebuild/bin/jobs.sh\ncd \"$BUILD_DIR\"\n\n# Disable go proxy.  see https://github.com/golang/go/issues/33985\ngo env GOPRIVATE=*\n\n# BoringSSL doesn't have tags or versions in the Github repo.\n# This commit represents the latest version that S2N is compatible\n# with. It prevents our build system from breaking when BoringSSL\n# is updated, last done on 2022-12-30.\nBSSL_VERSION=31bad2514d21f6207f3925ba56754611c462a873\nmkdir boringssl\ncd boringssl\ngit init\ngit remote add origin https://github.com/google/boringssl.git\ngit fetch origin --depth=1 $BSSL_VERSION\ngit reset --hard FETCH_HEAD\n\ngit checkout $BSSL_VERSION\nmkdir ../build\ncd ../build\n\ncmake ../boringssl -DBUILD_SHARED_LIBS=1 -DCMAKE_BUILD_TYPE=Release\nmake -j $JOBS\n\n# BoringSSL does not define any install configuration in their CMake config, copy the stuff we know we need\nmkdir -p \"${INSTALL_DIR}/lib\"\nmkdir -p \"${INSTALL_DIR}/bin\"\ncp crypto/libcrypto.so \"${INSTALL_DIR}/lib/libcrypto.so\"\ncp tool/bssl \"${INSTALL_DIR}/bin/bssl\"\ncp -r ../boringssl/include \"$INSTALL_DIR\"\n\npopd\n\nexit 0\n", "num_lines": 64}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n\techo \"install_clang.sh download_dir install_dir os_name\"\n\texit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n\tusage\nfi\n\nCLANG_DOWNLOAD_DIR=$1\nCLANG_INSTALL_DIR=$2\nPLATFORM=$3\n\nmkdir -p \"$CLANG_DOWNLOAD_DIR\"\ncd \"$CLANG_DOWNLOAD_DIR\"\n\nif [ \"$PLATFORM\" == \"linux\" ]; then\n\t# The Certificate used by chromium.googlesource.com is not in the default CA\n\t# list supported by git/curl on Ubuntu, but the certificate is in the\n\t# ca-certificates.crt file in Ubuntu, so set this env variable so that it is\n\t# picked up by git.\n\texport SSL_CERT_FILE=/usr/lib/ssl/certs/ca-certificates.crt\nfi\n\nexport GIT_CURL_VERBOSE=1\necho \"Downloading Clang...\"\ngit clone https://chromium.googlesource.com/chromium/src/tools/clang\n\necho \"Updating Clang...\"\npython3 \"$CLANG_DOWNLOAD_DIR\"/clang/scripts/update.py\n\n# \"third_party\" directory is created above $CLANG_DOWNLOAD_DIR after running\n# update, move it into $CLANG_DOWNLOAD_DIR once update is complete.\nmv ../third_party \"$CLANG_DOWNLOAD_DIR\"\n\necho \"Installed Clang Version: \"\n\"$CLANG_DOWNLOAD_DIR\"/third_party/llvm-build/Release+Asserts/bin/clang --version\n\n# Install matching LLVM if FUZZ_COVERAGE is enabled\nif [[ \"$FUZZ_COVERAGE\" == \"true\" ]]; then\n\tLLVM_INSTALL_DIR=\"$CLANG_INSTALL_DIR\"/../llvm\n\tmkdir -p \"$LLVM_INSTALL_DIR\"\n\tpython3 \"$CLANG_DOWNLOAD_DIR\"/clang/scripts/update.py --package=\"coverage_tools\" --output-dir=\"$LLVM_INSTALL_DIR\"\n\tln -sf $LLVM_INSTALL_DIR/bin/llvm-cov /usr/bin/llvm-cov\n\tln -sf $LLVM_INSTALL_DIR/bin/llvm-profdata /usr/bin/llvm-profdata\nfi\n\nmkdir -p \"$CLANG_INSTALL_DIR\" && cp -rf \"$CLANG_DOWNLOAD_DIR\"/third_party/llvm-build/Release+Asserts/* \"$CLANG_INSTALL_DIR\"\n\n", "num_lines": 67}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"install_cppcheck.sh install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nINSTALL_DIR=$1\nsource codebuild/bin/jobs.sh\n\nmkdir -p $INSTALL_DIR||true\ncd \"$INSTALL_DIR\"\ngit clone --branch 2.3 --depth 1 https://github.com/danmar/cppcheck.git cppcheck-src\ncd cppcheck-src\n\nmake -j $JOBS\n\nmv cppcheck ..\nmv cfg ..\ncd ..\nrm -rf cppcheck-src\n", "num_lines": 41}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"install_ctverif.sh install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nINSTALL_DIR=$1\n\ncd \"$INSTALL_DIR\"\n\n#install smack\ngit clone https://github.com/smackers/smack.git -b develop\ncd smack/bin\ngit checkout 45e1fc5\n./build.sh\n\n# Disabling ShellCheck using https://github.com/koalaman/shellcheck/wiki/Directive\n# Turn of Warning in one line as https://github.com/koalaman/shellcheck/wiki/SC1090\n# shellcheck disable=SC1090\nsource \"$INSTALL_DIR\"/smack.environment\n\n#install ctverif\ncd \"$INSTALL_DIR\"\ngit clone --depth 1 https://github.com/imdea-software/verifying-constant-time.git -b test-automation\n\n", "num_lines": 46}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\nsource codebuild/bin/s2n_setup_env.sh\n\n\n # Install latest version of clang, clang++, and llvm-symbolizer. Needed for fuzzing.\nif [[ \"$TESTS\" == \"fuzz\" || \"$TESTS\" == \"ALL\" || \"$LATEST_CLANG\" == \"true\" ]]; then\n    mkdir -p \"$LATEST_CLANG_INSTALL_DIR\"||true\n    codebuild/bin/install_clang.sh \"$(mktemp -d)\" \"$LATEST_CLANG_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\nfi\n\n# Download and Install LibFuzzer with latest clang\nif [[ \"$TESTS\" == \"fuzz\" || \"$TESTS\" == \"ALL\" ]]; then\n    mkdir -p \"$LIBFUZZER_INSTALL_DIR\" || true\n    PATH=$LATEST_CLANG_INSTALL_DIR/bin:$PATH codebuild/bin/install_libFuzzer.sh \"$(mktemp -d)\" \"$LIBFUZZER_INSTALL_DIR\" \"$OS_NAME\" ;\nfi\n\n# Download and Install Openssl 1.1.1\nif [[ (\"$S2N_LIBCRYPTO\" == \"openssl-1.1.1\") || ( \"$TESTS\" == \"integrationv2\" || \"$TESTS\" == \"ALL\" ) ]]; then\n    if [[ ! -x \"$OPENSSL_1_1_1_INSTALL_DIR/bin/openssl\" ]]; then\n      mkdir -p \"$OPENSSL_1_1_1_INSTALL_DIR\"||true\n      codebuild/bin/install_openssl_1_1_1.sh \"$(mktemp -d)\" \"$OPENSSL_1_1_1_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\n    fi\nfi\n\n# Download and Install Openssl 3.0\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-3.0\" && ! -d \"$OPENSSL_3_0_INSTALL_DIR\" ]]; then\n    mkdir -p \"$OPENSSL_3_0_INSTALL_DIR\"\n    codebuild/bin/install_openssl_3_0.sh \"$(mktemp -d)\" \"$OPENSSL_3_0_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\nfi\n\n# Download and Install Openssl 1.0.2\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.0.2\" && ! -d \"$OPENSSL_1_0_2_INSTALL_DIR\" ]]; then\n    mkdir -p \"$OPENSSL_1_0_2_INSTALL_DIR\"||true\n    codebuild/bin/install_openssl_1_0_2.sh \"$(mktemp -d)\" \"$OPENSSL_1_0_2_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\nfi\n\n# Download and Install the Openssl FIPS module and Openssl 1.0.2-fips\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.0.2-fips\" ]] && [[ ! -d \"$OPENSSL_1_0_2_FIPS_INSTALL_DIR\" ]]; then\n    codebuild/bin/install_openssl_1_0_2_fips.sh \"$(mktemp -d)\" \"$OPENSSL_1_0_2_FIPS_INSTALL_DIR\" \"$OS_NAME\" ; fi\n\n# Download and Install LibreSSL\nif [[ \"$S2N_LIBCRYPTO\" == \"libressl\" && ! -d \"$LIBRESSL_INSTALL_DIR\" ]]; then\n    mkdir -p \"$LIBRESSL_INSTALL_DIR\"||true\n    codebuild/bin/install_libressl.sh \"$(mktemp -d)\" \"$LIBRESSL_INSTALL_DIR\" > /dev/null ;\nfi\n\n# Download and Install BoringSSL\nif [[ \"$S2N_LIBCRYPTO\" == \"boringssl\" && ! -d \"$BORINGSSL_INSTALL_DIR\" ]]; then\n    codebuild/bin/install_boringssl.sh \"$(mktemp -d)\" \"$BORINGSSL_INSTALL_DIR\" > /dev/null ;\nfi\n\n# Download and Install AWS-LC\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc\" && ! -d \"$AWSLC_INSTALL_DIR\" ]]; then\n    codebuild/bin/install_awslc.sh \"$(mktemp -d)\" \"$AWSLC_INSTALL_DIR\" \"0\" > /dev/null ;\nfi\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc-fips\" && ! -d \"$AWSLC_FIPS_INSTALL_DIR\" ]]; then\n    codebuild/bin/install_awslc.sh \"$(mktemp -d)\" \"$AWSLC_FIPS_INSTALL_DIR\" \"1\" > /dev/null ;\nfi\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc-fips-2022\" && ! -d \"$AWSLC_FIPS_2022_INSTALL_DIR\" ]]; then\n    codebuild/bin/install_awslc_fips_2022.sh \"$(mktemp -d)\" \"$AWSLC_FIPS_2022_INSTALL_DIR\" > /dev/null ;\nfi\n\nif [[ \"$TESTS\" == \"integrationv2\" || \"$TESTS\" == \"ALL\" ]]; then\n    # Install tox\n    if [[ \"$DISTRO\" == \"ubuntu\" ]]; then\n        if [[ ! -x `python3.9 -m tox --version` ]]; then\n            python3.9 -m pip install tox\n        fi\n    else\n        if [[ ! -x `which tox` ]]; then\n            case \"$DISTRO\" in\n            \"amazon linux\")\n                yum install -y python3-pip\n                python3 -m pip install --user tox ;;\n            \"apple\")\n                brew install python@3\n                python3 -m pip install --user tox ;;\n            *)\n                echo \"Unkown platform $DISTRO trying to install tox on $OS_NAME $ARCH\"\n                exit 1\n                ;;\n            esac\n        fi\n    fi\n\n    if [[ ! -x \"$OPENSSL_0_9_8_INSTALL_DIR/bin/openssl\" ]]; then\n      # Download and Install Openssl 0.9.8\n      mkdir -p \"$OPENSSL_0_9_8_INSTALL_DIR\"||true\n      codebuild/bin/install_openssl_0_9_8.sh \"$(mktemp -d)\" \"$OPENSSL_0_9_8_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\n    fi\n\n    if [[ ! -x \"$GNUTLS_INSTALL_DIR/bin/gnutls-cli\" ]]; then\n      # Download and Install GnuTLS for integration tests\n      mkdir -p \"$GNUTLS_INSTALL_DIR\"||true\n      codebuild/bin/install_gnutls.sh \"$(mktemp -d)\" \"$GNUTLS_INSTALL_DIR\" > /dev/null ;\n    fi\n\n    if [[ ! -x \"$GNUTLS37_INSTALL_DIR/bin/gnutls-cli\" ]]; then\n      # Download and Install GnuTLS for integration tests\n      mkdir -p \"$GNUTLS37_INSTALL_DIR\"||true\n      codebuild/bin/install_gnutls37.sh \"$(mktemp -d)\" \"$GNUTLS37_INSTALL_DIR\" > /dev/null ;\n    fi\n\n    if [[ ! -x \"$OQS_OPENSSL_1_1_1_INSTALL_DIR/bin/openssl\" ]]; then\n      # Download and Install OQS OpenSSL for integration tests\n      mkdir -p \"$OQS_OPENSSL_1_1_1_INSTALL_DIR\" ||true\n      codebuild/bin/install_oqs_openssl_1_1_1.sh \"$(mktemp -d)\" \"$OQS_OPENSSL_1_1_1_INSTALL_DIR\" \"$OS_NAME\" | head -50\n    fi\n\n    if [[ \"$DISTRO\" == \"ubuntu\" ]]; then\n        # Install SSLyze for all Integration Tests on Ubuntu.\n        # There is a nassl dependancy issue preventing this from working on on AL2 ARM (others?).\n        if [[ \"$S2N_NO_SSLYZE\" != \"true\" ]]; then\n            codebuild/bin/install_sslyze.sh\n        fi\n\n        if [[ ! -x \"$APACHE2_INSTALL_DIR/apache2.conf\" ]]; then\n            codebuild/bin/install_apache2.sh codebuild/bin/apache2 \"$APACHE2_INSTALL_DIR\"\n        fi\n    fi\nfi\n\n# Install SAW, Z3, and Yices for formal verification\nif [[ \"$SAW\" == \"true\" || \"$TESTS\" == \"ALL\" ]]; then\n    mkdir -p \"$SAW_INSTALL_DIR\"||true\n    codebuild/bin/install_saw.sh \"$(mktemp -d)\" \"$SAW_INSTALL_DIR\" > /dev/null ;\n\n    mkdir -p \"$Z3_INSTALL_DIR\"||true\n    codebuild/bin/install_z3_yices.sh \"$(mktemp -d)\" \"$Z3_INSTALL_DIR\" > /dev/null ;\nfi\n\nif [[ ! -x `which cmake` ]]; then\n    case \"$DISTRO\" in\n    \"ubuntu\")\n        apt-get -y install cmake\n        ;;\n    \"amazon linux\")\n        yum install -y cmake3\n        update-alternatives --install /usr/bin/cmake cmake /usr/bin/cmake3 30\n        ;;\n    \"apple\")\n        brew install cmake\n        ;;\n    *)\n        echo \"Unknown platform for cmake.\"\n        ;;\n    esac\nfi\n\nif [[ \"$TESTS\" == \"benchmark\" || \"$TESTS\" == \"ALL\" ]]; then\n    if [[ ! -x \"$GB_INSTALL_DIR/lib/libbenchmark.a\" ]]; then\n        mkdir -p \"$GB_INSTALL_DIR\"||true\n        codebuild/bin/install_googlebenchmark.sh \"$(mktemp -d)\" \"$GB_INSTALL_DIR\" \"$OS_NAME\" > /dev/null ;\n    fi\nfi\n\n", "num_lines": 172}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\nsource codebuild/bin/s2n_setup_env.sh\n\nusage() {\n    echo \"install_gnutls.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nGNUTLS_BUILD_DIR=$1\nGNUTLS_INSTALL_DIR=$2\n\nsource codebuild/bin/jobs.sh\n\n# libgmp is needed for libnettle\ncase \"$DISTRO\" in\n  \"ubuntu\")\n    sudo apt-get -qq install libgmp3-dev -y\n    ;;\n  \"amazon linux\")\n    sudo yum install -y gmp-devel\n    ;;\n\"darwin\" )\n    # Installing an existing package is a \"failure\" in brew\n    brew install gmp || true \n    ;;\n*)\n    echo \"Invalid platform! $OS_NAME\"\n    usage\n    ;;\nesac\n\ncd \"$GNUTLS_BUILD_DIR\"\n\n# libnettle is a dependency of GnuTLS\n# Originally from: https://ftp.gnu.org/gnu/nettle/nettle-3.3.tar.gz\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2017-08-29_nettle-3.3.tar.gz --output nettle-3.3.tar.gz\ntar -xzf nettle-3.3.tar.gz\ncd nettle-3.3\n./configure --prefix=\"$GNUTLS_INSTALL_DIR\"/nettle\nmake -j $JOBS\nmake -j $JOBS install\ncd ..\n\n# Install GnuTLS\n# Originally from: ftp://ftp.gnutls.org/gcrypt/gnutls/v3.5/gnutls-3.5.5.tar.xz\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2017-08-29_gnutls-3.5.5.tar.xz --output gnutls-3.5.5.tar.xz\ntar -xJf gnutls-3.5.5.tar.xz\ncd gnutls-3.5.5\n./configure LD_FLAGS=\"-R$GNUTLS_INSTALL_DIR/nettle/lib -L$GNUTLS_INSTALL_DIR/nettle/lib -lnettle -lhogweed\" \\\n            NETTLE_LIBS=\"-R$GNUTLS_INSTALL_DIR/nettle/lib -L$GNUTLS_INSTALL_DIR/nettle/lib -lnettle\" \\\n            NETTLE_CFLAGS=\"-I$GNUTLS_INSTALL_DIR/nettle/include\" \\\n            HOGWEED_LIBS=\"-R$GNUTLS_INSTALL_DIR/nettle/lib -L$GNUTLS_INSTALL_DIR/nettle/lib -lhogweed\" \\\n            HOGWEED_CFLAGS=\"-I$GNUTLS_INSTALL_DIR/nettle/include\" \\\n            --without-p11-kit \\\n            --with-included-libtasn1 \\\n            --prefix=\"$GNUTLS_INSTALL_DIR\"\nmake -j $JOBS\nmake -j $JOBS install\n", "num_lines": 79}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\nsource codebuild/bin/s2n_setup_env.sh\n\nusage() {\n    echo \"install_gnutls37.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nGNUTLS_BUILD_DIR=$1\nGNUTLS_INSTALL_DIR=$2\n\nsource codebuild/bin/jobs.sh\n\n# libgmp is needed for libnettle\ncase \"$DISTRO\" in\n  \"ubuntu\")\n    sudo apt-get -qq install libgmp3-dev -y\n    ;;\n  \"amazon linux\")\n    sudo yum install -y gmp-devel\n    ;;\n\"darwin\" )\n    # Installing an existing package is a \"failure\" in brew\n    brew install gmp || true\n    ;;\n*)\n    echo \"Invalid platform! $OS_NAME\"\n    usage\n    ;;\nesac\n\ncd \"$GNUTLS_BUILD_DIR\"\n\n# Originally from: https://ftp.gnu.org/gnu/nettle/\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2021-01-04_nettle-3.7.tar.gz --output nettle-3.7.tar.gz\ntar -xzf nettle-3.7.tar.gz\ncd nettle-3.7\n./configure --prefix=\"$GNUTLS_INSTALL_DIR\"/nettle \\\n            --disable-openssl \\\n            --enable-shared\nmake -j $JOBS\nmake -j $JOBS install\ncd ..\n\n# Install GnuTLS\n# Originally from: https://www.gnupg.org/ftp/gcrypt/gnutls/v3.7/\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2022-01-18_gnutls-3.7.3.tar.xz --output gnutls-3.7.3.tar.xz\ntar -xJf gnutls-3.7.3.tar.xz\ncd gnutls-3.7.3\nPKG_CONFIG_PATH=\"$GNUTLS_INSTALL_DIR\"/nettle/lib/pkgconfig:$PKG_CONFIG_PATH \\\n  ./configure --prefix=\"$GNUTLS_INSTALL_DIR\" \\\n              --without-p11-kit \\\n              --with-included-libtasn1 \\\n              --with-included-unistring\nmake -j $JOBS\nmake -j $JOBS install\n", "num_lines": 77}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n\techo \"install_googlebenchmark.sh download_dir install_dir os_name\"\n\texit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n\tusage\nfi\n\nGB_DOWNLOAD_DIR=$1\nGB_INSTALL_DIR=$2\nPLATFORM=$3\n\nmkdir -p \"$GB_DOWNLOAD_DIR\"\ncd \"$GB_DOWNLOAD_DIR\"\n\nexport GIT_CURL_VERBOSE=1\necho \"Downloading Google Benchmark...\"\ngit clone https://github.com/google/benchmark.git\ngit clone https://github.com/google/googletest.git benchmark/googletest\ncd benchmark\nmkdir build && cd build\ncmake ../ -DCMAKE_BUILD_TYPE=Release\nmake\n\nmkdir -p \"$GB_INSTALL_DIR\"/include && cp -rf \"$GB_DOWNLOAD_DIR\"/benchmark/include/benchmark \"$GB_INSTALL_DIR\"/include/\nmkdir -p \"$GB_INSTALL_DIR\"/lib && cp -rf \"$GB_DOWNLOAD_DIR\"/benchmark/build/src/*.a \"$GB_INSTALL_DIR\"/lib/\n\n\n\n", "num_lines": 48}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nset -ex\n\nusage() {\n\techo \"install_libFuzzer.sh download_dir install_dir os_name\"\n\texit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n\tusage\nfi\n\nLIBFUZZER_DOWNLOAD_DIR=$1\nLIBFUZZER_INSTALL_DIR=$2\nexport PLATFORM=$3\n\nmkdir -p \"$LIBFUZZER_DOWNLOAD_DIR\"\ncd \"$LIBFUZZER_DOWNLOAD_DIR\"\n\ngit clone https://chromium.googlesource.com/chromium/llvm-project/llvm/lib/Fuzzer\ncd Fuzzer\ngit checkout 651ead\ncd ..\n\necho \"Compiling LibFuzzer...\"\nclang++ -c -g -v -O2 -lstdc++ -std=c++11 Fuzzer/*.cpp -IFuzzer\nar ruv libFuzzer.a Fuzzer*.o\n\necho \"Copying libFuzzer.a to $LIBFUZZER_INSTALL_DIR\"\nmkdir -p \"$LIBFUZZER_INSTALL_DIR\"/lib && cp libFuzzer.a \"$LIBFUZZER_INSTALL_DIR\"/lib\n\n# Run AFL instead of libfuzzer if AFL_FUZZ is set. Not compatible with fuzz coverage.\nif [[ \"$AFL_FUZZ\" == \"true\" && \"$FUZZ_COVERAGE\" != \"true\" ]]; then\n\t# Clusterfuzz's bash script changed from AFL to AFL++ on April 1, 2021; this\n\t# commit (ac5ac9e4604ea03cfd643185ad1e3800e952ea44) pins the script to an older version\n\t# of Clusterfuzz until we support AFL++.\n\tmkdir -p \"$LIBFUZZER_INSTALL_DIR\" && curl https://raw.githubusercontent.com/google/clusterfuzz/ac5ac9e4604ea03cfd643185ad1e3800e952ea44/docs/setting-up-fuzzing/build_afl.bash > \"$LIBFUZZER_INSTALL_DIR\"/build_afl.bash\n\tchmod +x \"$LIBFUZZER_INSTALL_DIR\"/build_afl.bash\n\tcd \"$LIBFUZZER_INSTALL_DIR\"\n\t\"$LIBFUZZER_INSTALL_DIR\"/build_afl.bash\n\tcd -\nfi\n", "num_lines": 56}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"install_libressl.sh build_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nsource codebuild/bin/jobs.sh\n\ncd \"$BUILD_DIR\"\n# Originally from https://ftp.openbsd.org/pub/OpenBSD/LibreSSL/libressl-3.4.3.tar.gz\ncurl https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2022-12-01_libressl-3.6.1.tar.gz > libressl-3.6.1.tar.gz\ntar -xzvf libressl-3.6.1.tar.gz\ncd libressl-3.6.1\n./configure --prefix=\"$INSTALL_DIR\"\nmake -j $JOBS CFLAGS=-fPIC install\n", "num_lines": 38}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_openssl_0_9_8.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nPLATFORM=$3\n\ncd \"$BUILD_DIR\"\nwget https://www.openssl.org/source/old/0.9.x/openssl-0.9.8zh.tar.gz\ntar xzvf openssl-0.9.8zh.tar.gz\ncd openssl-0.9.8zh\n\nif [ \"$PLATFORM\" == \"linux\" ]; then\n    CONFIGURE=\"./config -d\"\nelif [ \"$PLATFORM\" == \"osx\" ]; then\n    CONFIGURE=\"./Configure darwin64-x86_64-cc\"\nelse\n    echo \"Invalid platform! $PLATFORM\"\n    usage\nfi\n\n$CONFIGURE --prefix=\"$INSTALL_DIR\"\n\nmake depend\nmake -j8\nmake install\n\npopd\n\nexit 0\n\n", "num_lines": 56}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_openssl_1_0_2.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nOS_NAME=$3\nsource codebuild/bin/jobs.sh\n\nmkdir -p $BUILD_DIR\ncd \"$BUILD_DIR\"\ncurl --retry 3 -L https://github.com/openssl/openssl/archive/OpenSSL_1_0_2-stable.zip --output openssl-OpenSSL_1_0_2-stable.zip\nunzip openssl-OpenSSL_1_0_2-stable.zip\ncd openssl-OpenSSL_1_0_2-stable\n\nif [ \"$OS_NAME\" == \"linux\" ]; then\n    CONFIGURE=\"./config -d\"\nelif [ \"$OS_NAME\" == \"osx\" ]; then\n    CONFIGURE=\"./Configure darwin64-x86_64-cc\"\nelse\n    echo \"Invalid platform! $OS_NAME\"\n    usage\nfi\n\nmkdir -p $INSTALL_DIR\n$CONFIGURE shared -g3 -fPIC no-libunbound no-gmp no-jpake no-krb5 no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace \\\n         no-store no-zlib no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia no-bf no-ripemd \\\n         no-dsa no-ssl2 no-capieng -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS \\\n         --prefix=\"$INSTALL_DIR\"\n\nmake -j $JOBS depend\nmake -j $JOBS\nmake -j $JOBS install_sw\n\npopd\n\nexit 0\n\n", "num_lines": 62}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_openssl_1_0_2_fips.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nOS_NAME=$3\n\nif [ \"$OS_NAME\" == \"linux\" ]; then\n    CONFIGURE=\"./config -d\"\nelif [ \"$OS_NAME\" == \"osx\" ]; then\n    echo \"WARNING: FIPS and MacOS is not officially supported. This build should only be used for local debugging.\"\n    echo \"See: http://openssl.6102.n7.nabble.com/Openssl-Fips-build-for-Mac-OSX-64-bit-td44716.html\"\n    CONFIGURE=\"./Configure darwin64-x86_64-cc\"\nelse\n    echo \"Invalid platform! $OS_NAME\"\n    usage\nfi\n\n# Install the FIPS object module in accordance with OpenSSL FIPS 140-2 Security Policy Annex A.\n#     https://www.openssl.org/docs/fips/SecurityPolicy-2.0.pdf\n# This installation is not FIPS compliant as we do not own the build system architecture.\n# It may only be used for testing purposes.\n#\n# There is no 'latest' download URL for the FIPS object modules\ncd \"$BUILD_DIR\"\n# Originally from: http://www.openssl.org/source/openssl-fips-2.0.13.tar.gz\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2017-08-31_openssl-fips-2.0.13.tar.gz --output openssl-fips-2.0.13.tar.gz\ngunzip -c openssl-fips-2.0.13.tar.gz | tar xf -\nrm openssl-fips-2.0.13.tar.gz\ncd openssl-fips-2.0.13\nmkdir ../OpensslFipsModule\nFIPSDIR=\"$(pwd)/../OpensslFipsModule\"\nexport FIPSDIR\nchmod +x ./Configure\n$CONFIGURE\nmake\nmake install\n\ncd \"$BUILD_DIR\"\ncurl --retry 3 -L https://github.com/openssl/openssl/archive/OpenSSL_1_0_2-stable.zip --output openssl-OpenSSL_1_0_2-stable.zip\nunzip openssl-OpenSSL_1_0_2-stable.zip\ncd openssl-OpenSSL_1_0_2-stable\n\nFIPS_OPTIONS=\"fips --with-fipsdir=$FIPSDIR shared\"\n\n$CONFIGURE $FIPS_OPTIONS -g3 -fPIC no-libunbound no-gmp no-jpake no-krb5 no-md2 no-rc5 \\\n         no-rfc3779 no-sctp no-ssl-trace no-store no-zlib no-hw no-mdc2 no-seed no-idea \\\n         enable-ec_nistp_64_gcc_128 no-camellia no-bf no-ripemd no-dsa no-ssl2 no-capieng -DSSL_FORBID_ENULL \\\n         -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS --prefix=\"$INSTALL_DIR\"\n\nmake depend\nmake\nmake install_sw\n\npopd\n\nexit 0\n\n", "num_lines": 83}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_openssl_1_1_1.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nOS_NAME=$3\nsource codebuild/bin/jobs.sh\nRELEASE=1_1_1-stable\n\nmkdir -p $BUILD_DIR\ncd \"$BUILD_DIR\"\ncurl --retry 3 -L https://github.com/openssl/openssl/archive/OpenSSL_${RELEASE}.zip --output OpenSSL_${RELEASE}.zip\nunzip OpenSSL_${RELEASE}.zip\ncd openssl-OpenSSL_${RELEASE}\n\nif [ \"$OS_NAME\" == \"linux\" ]; then\n    CONFIGURE=\"./config -d\"\nelif [[ \"$OS_NAME\" == \"osx\" || \"$OS_NAME\" == \"darwin\" ]]; then\n    CONFIGURE=\"./Configure darwin64-x86_64-cc\"\nelse\n    echo \"Invalid platform! $OS_NAME\"\n    usage\nfi\n\nmkdir -p $INSTALL_DIR\n# Use g3 to get debug symbols in libcrypto to chase memory leaks\n$CONFIGURE shared -g3 -fPIC              \\\n         no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib     \\\n         no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia\\\n         no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng                  \\\n         -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS      \\\n         --prefix=\"$INSTALL_DIR\"\n\nmake -j $JOBS depend\nmake -j $JOBS\nmake -j $JOBS install_sw\n\npopd\n\nexit 0\n", "num_lines": 65}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_openssl_3_0.sh build_dir install_dir os_name\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nOS_NAME=$3\nsource codebuild/bin/jobs.sh\nRELEASE=3.0.7\n\nmkdir -p $BUILD_DIR\ncd \"$BUILD_DIR\"\ncurl --retry 3 -L https://github.com/openssl/openssl/archive/refs/tags/openssl-${RELEASE}.zip --output OpenSSL_${RELEASE}.zip\nunzip OpenSSL_${RELEASE}.zip\ncd openssl-openssl-${RELEASE}\n\nCONFIGURE=\"./Configure \"\n\nmkdir -p $INSTALL_DIR\n# Use g3 to get debug symbols in libcrypto to chase memory leaks\n$CONFIGURE shared -g3 -fPIC              \\\n         no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib     \\\n         no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia\\\n         no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng no-dtls          \\\n         -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS      \\\n         --prefix=\"$INSTALL_DIR\"\n\nmake -j $JOBS\nmake -j $JOBS test\nmake -j $JOBS install\n\npopd\n\n# sym-link lib -> lib64 since codebuild assumes /lib path\npushd $INSTALL_DIR\nln -s lib64 lib\npopd\n\nexit 0\n", "num_lines": 63}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\n\nusage() {\n    echo \"install_oqs_openssl_1_1_1.sh build_dir install_dir platform\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"3\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nPLATFORM=$3\n\ncd \"$BUILD_DIR\"\n\n# Download OQS OpenSSL Source code\ngit clone --branch OQS-OpenSSL_1_1_1-stable https://github.com/open-quantum-safe/openssl.git\n\n\n# Download and Build OQS library, and copy \"lib\" and \"include\" artifacts into OQS OpenSSL directory\ngit clone https://github.com/open-quantum-safe/liboqs.git\ncd liboqs\n\n# Use commit that supports Kyber round 3; hybrid draft spec version 5\ngit checkout cf6d8a059e446d24e2af06949d83605ae0f4f414\n\nmkdir build && cd build\ncmake -GNinja -DCMAKE_INSTALL_PREFIX=${BUILD_DIR}/openssl/oqs ..\nninja\nninja install\n\n\n# Complete the OpenSSL Build\ncd \"$BUILD_DIR\"/openssl\n\n# Pin to OQS-OpenSSL commit that is compatible with Kyber round 3; hybrid draft spec version 5 LibOQS implementation\ngit checkout 613d1bea7afa23dc11f340e75990cb47d77711e9\n\nif [ \"$PLATFORM\" == \"linux\" ]; then\n    CONFIGURE=\"./config -d\"\nelif [ \"$PLATFORM\" == \"osx\" ]; then\n    CONFIGURE=\"./Configure darwin64-x86_64-cc\"\nelse\n    echo \"Invalid platform! $PLATFORM\"\n    usage\nfi\n\n# Use g3 to get debug symbols in libcrypto to chase memory leaks\n$CONFIGURE -g3 -fPIC              \\\n         no-md2 no-rc5 no-rfc3779 no-sctp no-ssl-trace no-zlib     \\\n         no-hw no-mdc2 no-seed no-idea enable-ec_nistp_64_gcc_128 no-camellia \\\n         no-bf no-ripemd no-dsa no-ssl2 no-ssl3 no-capieng                  \\\n         -DSSL_FORBID_ENULL -DOPENSSL_NO_DTLS1 -DOPENSSL_NO_HEARTBEATS      \\\n         --prefix=\"$INSTALL_DIR\"\n\nmake depend\nmake -j\nmake install_sw\n\nexit 0", "num_lines": 77}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\nset -e\n\nusage() {\n    echo \"install_prlimit.sh download_dir install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nINSTALL_DIR=$2\nsource codebuild/bin/jobs.sh\n\nsudo apt-get install -y libncurses5-dev\n\ncd \"$BUILD_DIR\"\n# Originally from: https://www.kernel.org/pub/linux/utils/util-linux/v2.25/util-linux-2.25.2.tar.gz\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2017-08-29_util-linux-2.25.2.tar.gz --output util-linux-2.25.2.tar.gz\ntar -xzvf util-linux-2.25.2.tar.gz\ncd util-linux-2.25.2\n./configure ADJTIME_PATH=/var/lib/hwclock/adjtime \\\n    --disable-chfn-chsh \\\n    --disable-login \\\n    --disable-nologin \\\n    --disable-su \\\n    --disable-setpriv \\\n    --disable-runuser \\\n    --disable-pylibmount \\\n    --disable-static \\\n    --without-python \\\n    --without-systemd \\\n    --disable-makeinstall-chown \\\n    --without-systemdsystemunitdir \\\n    --without-ncurses \\\n    --prefix=\"$INSTALL_DIR\" || cat config.log\n\nmake -j $JOBS > /dev/null\nmake -j $JOBS install > /dev/null\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n#!/bin/bash\n\nset -e\n\nif [ \"$#\" -ne 3 ]; then\n    echo \"install_python.sh libcrypto_root build_dir install_dir\"\n    exit 1\nfi\n\nLIBCRYPTO_ROOT=$1\nBUILD_DIR=$2\nINSTALL_DIR=$3\nsource codebuild/bin/jobs.sh\n\ncd \"$BUILD_DIR\"\n# Originally from: https://www.python.org/ftp/python/3.6.0/Python-3.6.0.tgz\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/2017-08-29_Python-3.6.0.tgz --output Python-3.6.0.tgz\ntar xzf Python-3.6.0.tgz\ncd Python-3.6.0\n CPPFLAGS=\"-I$LIBCRYPTO_ROOT/include\" LDFLAGS=\"-Wl,-rpath,$LIBCRYPTO_ROOT/lib -L$LIBCRYPTO_ROOT/lib\" ./configure --prefix=\"$INSTALL_DIR\"\nmake -j $JOBS\nmake -j $JOBS install\n", "num_lines": 37}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\nset -ex\npushd \"$(pwd)\"\n\nusage() {\n    echo \"install_s2n_head.sh build_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nBUILD_DIR=$1\nsource codebuild/bin/jobs.sh\ncd \"$BUILD_DIR\"\n\n# Clone the most recent s2n commit\ngit clone --depth=1 https://github.com/aws/s2n-tls s2n_head\ncmake ./s2n_head -Bbuild -DCMAKE_PREFIX_PATH=\"$LIBCRYPTO_ROOT\" -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on\ncmake --build ./build -- -j $JOBS\n\n# Copy new executables to bin directory\ncp -f \"$BUILD_DIR\"/build/bin/s2nc \"$BASE_S2N_DIR\"/bin/s2nc_head\ncp -f \"$BUILD_DIR\"/build/bin/s2nd \"$BASE_S2N_DIR\"/bin/s2nd_head\n\npopd\n\nexit 0\n", "num_lines": 43}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\nset -xe\n\nusage() {\n\techo \"install_saw.sh download_dir install_dir\"\n\texit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n\tusage\nfi\n\nDOWNLOAD_DIR=$1\nINSTALL_DIR=$2\n\nif [ -x \"$INSTALL_DIR/bin/saw\" ]; then\n\techo \"Saw already installed at $INSTALL_DIR/bin/saw\";\n\texit 0;\nfi\n\nmkdir -p \"$DOWNLOAD_DIR\"\ncd \"$DOWNLOAD_DIR\"\n\n#download saw binaries\ncurl --retry 3 https://s2n-public-test-dependencies.s3.us-west-2.amazonaws.com/saw-0.9.0.99-Linux-x86_64.tar.gz --output saw.tar.gz\n\nmkdir -p saw && tar -xzf saw.tar.gz --strip-components=1 -C saw\nmkdir -p \"$INSTALL_DIR\" && mv saw/* \"$INSTALL_DIR\"\n\n\"$INSTALL_DIR\"/bin/saw --version\n", "num_lines": 46}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\nsource codebuild/bin/s2n_setup_env.sh\n\nusage() {\n    echo \"install_shellcheck.sh\"\n    exit 1\n}\n\ninstall_shellcheck() {\n   wget \"https://github.com/koalaman/shellcheck/releases/download/v0.7.1/shellcheck-v0.7.1.linux.$ARCH.tar.xz\" -O /tmp/shellcheck.tar.xz\n   tar -Jxf /tmp/shellcheck.tar.xz -C /tmp\n   mv /tmp/shellcheck-v*/shellcheck /usr/local/bin/\n   chmod 755 /usr/local/bin/shellcheck\n}\n\nif [ \"$#\" -ne \"0\" ]; then\n    usage\nfi\n\ncase \"$OS_NAME\" in\n  \"amazon linux\"|\"linux\")\n    which shellcheck || install_shellcheck\n    ;;\n  \"darwin\" )\n    brew install shellcheck || true ;\n    ;;\n  *)\n    echo \"Unknown platform\"\n    exit 255\n    ;;\nesac\n", "num_lines": 48}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\nset -x\n\nusage() {\n    echo \"install_sidetrail.sh install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nINSTALL_DIR=$1\n\ncd \"$INSTALL_DIR\"\n\n#install smack\ngit clone https://github.com/danielsn/smack.git -b sidewinder-debug\ncd smack/bin\n\nclang --version\nwhich clang\n\n./build.sh\n\n# Disabling ShellCheck using https://github.com/koalaman/shellcheck/wiki/Directive\n# Turn of Warning in one line as https://github.com/koalaman/shellcheck/wiki/SC1090\n# shellcheck disable=SC1090\nsource \"$INSTALL_DIR\"/smack.environment\n\n#install ctverif\ncd \"$INSTALL_DIR\"\ngit clone --depth 1 https://github.com/imdea-software/verifying-constant-time.git -b test-automation\n\n", "num_lines": 50}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\nset -x\n\n#Figlet is required for ctverif printing\nsudo apt-get install -y figlet\n\n#Install boogieman\ngem install bam-bam-boogieman\nwhich bam\n\n#Install the apt-get dependencies from the smack build script: this way they will still be there\n#when we get things from cache\nDEPENDENCIES=\"git cmake python-yaml python-psutil unzip wget python3-yaml\"\nDEPENDENCIES+=\" mono-complete libz-dev libedit-dev\"\nDEPENDENCIES+=\" clang-3.9 llvm-3.9 llvm-3.9-dev\"\n\n# Adding MONO repository\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF\necho \"deb http://download.mono-project.com/repo/ubuntu trusty main\" | sudo tee /etc/apt/sources.list.d/mono-official.list\n\nsudo apt-get update -o Acquire::CompressionTypes::Order::=gz\nsudo apt-get install -y ${DEPENDENCIES}\npip install pyyaml\n\nLLVM_SHORT_VERSION=3.9\n\nsudo update-alternatives --install /usr/bin/clang clang /usr/bin/clang-${LLVM_SHORT_VERSION} 30\nsudo update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-${LLVM_SHORT_VERSION} 30\nsudo update-alternatives --install /usr/bin/llvm-config llvm-config /usr/bin/llvm-config-${LLVM_SHORT_VERSION} 30\nsudo update-alternatives --install /usr/bin/llvm-link llvm-link /usr/bin/llvm-link-${LLVM_SHORT_VERSION} 30\nsudo update-alternatives --install /usr/bin/llvm-dis llvm-dis /usr/bin/llvm-dis-${LLVM_SHORT_VERSION} 30\n\nwhich clang\nclang --version\nclang-3.9 --version\n\nmkdir -p ~/override_clang\nln -s /usr/bin/clang          ~/override_clang/clang\nln -s /usr/bin/clang++        ~/override_clang/clang++\nln -s /usr/bin/llvm-config   ~/override_clang/llvm-config\nln -s /usr/bin/llvm-link      ~/override_clang/llvm-link\nln -s /usr/bin/llvm-dis       ~/override_clang/llvm-dis\nsudo chmod +x ~/override_clang/*\n\nexport PATH=\"$HOME/override_clang/:${PATH}\"\nwhich clang\nclang --version\nclang-3.9 --version\n\nwhich python\npython --version\npip install psutil\n", "num_lines": 68}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n. codebuild/bin/s2n_setup_env.sh\n\naarch64_install() {\n        echo \"sslyze has a dependency on nassl, which will not build on ARM.\"\n}\n\ncase \"$ARCH\" in\n  \"aarch64\")\n        aarch64_install\n        exit 1\n        ;;\n  *)\n        python3 -m pip install --user --upgrade pip setuptools\n        # Version 3.0.0 introduces backwards incompatible changes in the JSON we parse.\n        # TODO: unpin the sslyze version and update the json parsing sslyze output.\n        python3 -m pip install --user \"sslyze<3.0.0\"\n        sudo ln -s /root/.local/bin/sslyze /usr/bin/sslyze || true\n        which sslyze\n        sslyze --version\n        ;;\nesac\n", "num_lines": 38}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Shim code to get local docker/ec2 instances bootstraped like a CodeBuild instance.\n# Not actually used by CodeBuild.\n\nsource codebuild/bin/s2n_setup_env.sh\n\nset -e\n\ngithub_apt(){\n  curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | gpg --dearmor -o /usr/share/keyrings/githubcli-archive-keyring.gpg\n  echo \"deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main\" | tee /etc/apt/sources.list.d/github-cli.list\n  apt update -y\n  apt install -y gh\n}\nget_rust() {\n  apt install -y clang-10 sudo\n  curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y\n  source $HOME/.cargo/env\n  rustup default nightly\n}\n\nbase_packages() {\n  echo \"Installing repositories and base packages\"\n  apt update -y\n  apt install -y software-properties-common\n  add-apt-repository ppa:ubuntu-toolchain-r/test -y\n  add-apt-repository ppa:longsleep/golang-backports -y\n  apt-get update -o Acquire::CompressionTypes::Order::=gz\n\n  DEPENDENCIES=\"unzip make indent iproute2 kwstyle libssl-dev net-tools tcpdump valgrind lcov m4 nettle-dev nettle-bin pkg-config psmisc gcc g++ zlibc zlib1g-dev python3-pip python3-testresources llvm curl shellcheck git tox cmake libtool ninja-build golang-go quilt jq apache2\"\n  if [[ -n \"${GCC_VERSION:-}\" ]] && [[ \"${GCC_VERSION:-}\" != \"NONE\" ]]; then\n    DEPENDENCIES+=\" gcc-$GCC_VERSION g++-$GCC_VERSION\";\n  fi\n  if ! command -v python3.9 &> /dev/null; then\n    add-apt-repository ppa:deadsnakes/ppa -y\n    DEPENDENCIES+=\" python3.9 python3.9-distutils\";\n  fi\n\n  apt-get -y install --no-install-recommends ${DEPENDENCIES}\n}\n\n\nbase_packages\ngithub_apt\nget_rust\n\n# If prlimit is not on our current PATH, download and compile prlimit manually. s2n needs prlimit to memlock pages\nif ! type prlimit > /dev/null && [[ ! -d \"$PRLIMIT_INSTALL_DIR\" ]]; then\n    mkdir -p \"$PRLIMIT_INSTALL_DIR\";\n    codebuild/bin/install_prlimit.sh \"$(mktemp -d)\" \"$PRLIMIT_INSTALL_DIR\";\nfi\n\nif [[ \"$TESTS\" == \"ctverif\" || \"$TESTS\" == \"ALL\" ]] && [[ ! -d \"$CTVERIF_INSTALL_DIR\" ]]; then\n    mkdir -p \"$CTVERIF_INSTALL_DIR\" && codebuild/bin/install_ctverif.sh \"$CTVERIF_INSTALL_DIR\" > /dev/null ; fi\n\nif [[ \"$TESTS\" == \"sidetrail\" || \"$TESTS\" == \"ALL\" ]] ; then\n    codebuild/bin/install_sidetrail_dependencies.sh ; fi\n\nif [[ \"$TESTS\" == \"sidetrail\" || \"$TESTS\" == \"ALL\" ]] && [[ ! -d \"$SIDETRAIL_INSTALL_DIR\" ]]; then\n    mkdir -p \"$SIDETRAIL_INSTALL_DIR\" && codebuild/bin/install_sidetrail.sh \"$SIDETRAIL_INSTALL_DIR\" > /dev/null ; fi\n", "num_lines": 75}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n\techo \"install_z3_yices.sh download_dir install_dir\"\n\texit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n\tusage\nfi\n\nDOWNLOAD_DIR=$1\nINSTALL_DIR=$2\n\nmkdir -p \"$DOWNLOAD_DIR\"\ncd \"$DOWNLOAD_DIR\"\n\n#download z3 and yices\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/yices-2.6.1-x86_64-pc-linux-gnu-static-gmp.tar.gz --output yices.tar.gz\ntar -xf yices.tar.gz\n\ncurl --retry 3 https://s3-us-west-2.amazonaws.com/s2n-public-test-dependencies/z3-4.8.8-x64-ubuntu-16.04.zip --output z3.zip\nunzip z3.zip\n\nmkdir -p \"$INSTALL_DIR\"/bin\nmv z3-4.8.8-x64-ubuntu-16.04/bin/* \"$INSTALL_DIR\"/bin\nmv yices-2.6.1/bin/* \"$INSTALL_DIR\"/bin\nchmod +x  \"$INSTALL_DIR\"/bin/*\n\n\"$INSTALL_DIR\"/bin/yices-smt2 --version\n\"$INSTALL_DIR\"/bin/yices --version\n\"$INSTALL_DIR\"/bin/z3 --version\n", "num_lines": 48}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Find if the environment has more than 8 cores\nJOBS=8\nif [[ -x \"$(command -v nproc)\" ]]; then\n    UNITS=$(nproc);\n    if [[ $UNITS -gt $JOBS ]]; then\n        JOBS=$UNITS;\n    fi\nfi\n", "num_lines": 24}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"run_cppcheck.sh install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nINSTALL_DIR=$1\n\nCPPCHECK_EXECUTABLE=${INSTALL_DIR}/cppcheck\n\nFAILED=0\n$CPPCHECK_EXECUTABLE --version\n$CPPCHECK_EXECUTABLE --std=c99 --error-exitcode=-1 --quiet --force -j 8 --enable=all --template='[{file}:{line}]: ({severity}:{id}) {message}' --inline-suppr --suppressions-list=codebuild/bin/cppcheck_suppressions.txt -I . -I ./tests api bin crypto error stuffer ./tests/unit tls utils || FAILED=1\nif [ $FAILED == 1 ];\nthen\n\tprintf \"\\\\033[31;1mFAILED cppcheck\\\\033[0m\\\\n\"\n\texit -1\nelse\n\tprintf \"\\\\033[32;1mPASSED cppcheck\\\\033[0m\\\\n\"\nfi\n", "num_lines": 41}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"run_ctverif.sh install_dir\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"1\" ]; then\n    usage\nfi\n\nINSTALL_DIR=$1\nexport CTVERIF_DIR=\"${1}/verifying-constant-time\"\nSMACK_DIR=\"${1}/smack\"\n\n#Put the dependencies are on the path\n\n# Disabling ShellCheck using https://github.com/koalaman/shellcheck/wiki/Directive\n# Turn of Warning in one line as https://github.com/koalaman/shellcheck/wiki/SC1090\n# shellcheck disable=SC1090\nsource \"${INSTALL_DIR}/smack.environment\"\nexport PATH=\"${SMACK_DIR}/bin:${SMACK_DIR}/build:${PATH}\"\n#Test that they are really there\nwhich smack || echo \"can't find smack\"\nwhich boogie || echo \"can't find z3\"\nwhich llvm2bpl || echo \"can't find llvm2bpl\"\n\n#copy the current version of the file to the test\ncd \"${BASE_S2N_DIR}/tests/ctverif\"\ncp \"${BASE_S2N_DIR}/utils/s2n_safety.c\" .\nmake clean\n\n#run the test.  We expect both to pass, and none to fail\nFAILED=0\nEXPECTED_PASS=2\nEXPECTED_FAIL=0\nmake 2>&1 | ./count_success.pl $EXPECTED_PASS $EXPECTED_FAIL || FAILED=1\n\nif [ $FAILED == 1 ];\nthen\n\tprintf \"\\\\033[31;1mFAILED ctverif\\\\033[0m\\\\n\"\n\texit -1\nelse\n\tprintf \"\\\\033[32;1mPASSED ctverif\\\\033[0m\\\\n\"\nfi\n", "num_lines": 61}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\n\nwhich KWStyle\n\nS2N_FILES=$(find \"$PWD\" -type f -name \"s2n_*.[ch]\" | grep -v \"test\")\nFAILED=0\n\nfor file in $S2N_FILES; do\n    set +e\n    ERROR_LIST=$(KWStyle -gcc -v -xml codebuild/bin/KWStyle.xml \"$file\")\n    set -e\n    if [ \"$ERROR_LIST\" != \"\" ] ;\n    then\n        echo \"$ERROR_LIST\"\n        FAILED=1\n    fi\ndone\n\nif [ $FAILED == 1 ];\nthen\n    printf \"\\\\033[31;1mFAILED kwstyle\\\\033[0m\\\\n\"\n    exit -1\nelse\n    printf \"\\\\033[32;1mPASSED kwstyle\\\\033[0m\\\\n\"\nfi\n", "num_lines": 41}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -ex\n\nusage() {\n    echo \"run_sidetrail.sh install_dir s2n_dir\"\n    exit 1\n}\n\nrunSingleTest() {\n    cd \"${BASE_S2N_DIR}/tests/sidetrail/working/${1}\"\n    ./copy_as_needed.sh\n    make clean\n    make 2>&1 | tee out.txt\n\n    ../../count_success.pl 1 0 out.txt\n}\n\nrunNegativeTest() {\n    cd \"${BASE_S2N_DIR}/tests/sidetrail/working/${1}\"\n    ./copy_as_needed.sh\n    make clean\n    make 2>&1 | tee out.txt\n\n    ../../count_success.pl 0 1 out.txt\n}\n\nif [[ \"$#\" -ne \"2\" ]]; then\n    usage\nfi\n\nINSTALL_DIR=$1\nSMACK_DIR=\"${1}/smack\"\nBASE_S2N_DIR=$2\n\n#Put the dependencies on the path\n\n# Disabling ShellCheck using https://github.com/koalaman/shellcheck/wiki/Directive\n# Turn of Warning in one line as https://github.com/koalaman/shellcheck/wiki/SC1090\n# shellcheck disable=SC1090\nsource \"${INSTALL_DIR}/smack.environment\"\nexport PATH=\"${SMACK_DIR}/bin:${SMACK_DIR}/build:${PATH}\"\n#Test that they are really there\nwhich smack || echo \"can't find smack\"\nwhich boogie || echo \"can't find z3\"\nwhich llvm2bpl || echo \"can't find llvm2bpl\"\nwhich clang\nclang --version\necho $BOOGIE\necho $CORRAL\n\nrunNegativeTest \"s2n-record-read-cbc-negative-test\"\nrunSingleTest \"s2n-cbc\" # Takes 6m 30s\nrunSingleTest \"s2n-record-read-aead\"\nrunSingleTest \"s2n-record-read-cbc\"\nrunSingleTest \"s2n-record-read-composite\"\nrunSingleTest \"s2n-record-read-stream\"\n\n", "num_lines": 72}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\n\napache2_config() {\n    cert_dir=\"$1\"\n    command=\"$2\"\n    echo \"apache2: ${command}\"\n\n    APACHE_SERVER_ROOT=\"$APACHE2_INSTALL_DIR\" \\\n    APACHE_RUN_USER=www-data \\\n    APACHE_RUN_GROUP=www-data \\\n    APACHE_PID_FILE=\"${APACHE2_INSTALL_DIR}/run/apache2.pid\" \\\n    APACHE_RUN_DIR=\"${APACHE2_INSTALL_DIR}/run\" \\\n    APACHE_LOCK_DIR=\"${APACHE2_INSTALL_DIR}/lock\" \\\n    APACHE_LOG_DIR=\"${APACHE2_INSTALL_DIR}/log\" \\\n    APACHE_CERT_DIR=\"${cert_dir}\" \\\n    apache2 -k \"${command}\" -f \"${APACHE2_INSTALL_DIR}/apache2.conf\"\n}\n\napache2_stop() {\n    cert_dir=\"$1\"\n    apache2_config \"${cert_dir}\" stop\n}\n\napache2_start() {\n    if [[ ! -f \"$APACHE2_INSTALL_DIR/apache2.conf\" ]]; then\n        echo \"apache2 not installed\"\n        exit 1\n    fi\n\n    cert_dir=\"$1\"\n    apache2_config \"${cert_dir}\" start\n\n    # Stop the apache server after tests finish, even if an error occurs\n    trap 'apache2_stop \"${cert_dir}\"' ERR EXIT\n}\n", "num_lines": 51}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nsource codebuild/bin/s2n_setup_env.sh\n\n# Use prlimit to set the memlock limit to unlimited for linux. OSX is unlimited by default\n# Codebuild Containers aren't allowing prlimit changes (and aren't being caught with the usual cgroup check)\nif [[ \"$OS_NAME\" == \"linux\" && -n \"$CODEBUILD_BUILD_ARN\" ]]; then\n    PRLIMIT_LOCATION=`which prlimit`\n    sudo -E ${PRLIMIT_LOCATION} --pid \"$$\" --memlock=unlimited:unlimited;\nfi\n\n# Set the version of GCC as Default if it's required\nif [[ -n \"$GCC_VERSION\" ]] && [[ \"$GCC_VERSION\" != \"NONE\" ]]; then\n    alias gcc=$(which gcc-$GCC_VERSION);\nfi\n\n# Find if the environment has more than 8 cores\nJOBS=8\nif [[ -x \"$(command -v nproc)\" ]]; then\n    UNITS=$(nproc);\n    if [[ $UNITS -gt $JOBS ]]; then\n        JOBS=$UNITS;\n    fi\nfi\n\nmake clean;\n\necho \"Using $JOBS jobs for make..\";\necho \"running with libcrypto: ${S2N_LIBCRYPTO}, gcc_version: ${GCC_VERSION}\"\n\nif [[ \"$OS_NAME\" == \"linux\" && \"$TESTS\" == \"valgrind\" ]]; then\n    # For linux make a build with debug symbols and run valgrind\n    # We have to output something every 9 minutes, as some test may run longer than 10 minutes\n    # and will not produce any output\n    while sleep 9m; do echo \"=====[ $SECONDS seconds still running ]=====\"; done &\n\n    if [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.1.1\" || \"$S2N_LIBCRYPTO\" == \"awslc\" ]]; then\n        # https://github.com/aws/s2n-tls/issues/3758\n        # Run valgrind in pedantic mode (--errors-for-leak-kinds=all)\n        echo \"running task pedantic_valgrind\"\n        S2N_DEBUG=true make -j $JOBS pedantic_valgrind\n    else\n        S2N_DEBUG=true make -j $JOBS valgrind\n    fi\n\n    kill %1\nfi\n\nCMAKE_PQ_OPTION=\"S2N_NO_PQ=False\"\nif [[ -n \"$S2N_NO_PQ\" ]]; then\n    CMAKE_PQ_OPTION=\"S2N_NO_PQ=True\"\nfi\n\ntest_linked_libcrypto() {\n    s2n_executable=\"$1\"\n    so_path=\"${LIBCRYPTO_ROOT}/lib/libcrypto.so\"\n    echo \"Testing for linked libcrypto: ${so_path}\"\n    echo \"ldd:\"\n    ldd \"${s2n_executable}\"\n    ldd \"${s2n_executable}\" | grep \"${so_path}\" || \\\n        { echo \"Linked libcrypto is incorrect.\"; exit 1; }\n    echo \"Test succeeded!\"\n}\n\nsetup_apache_server() {\n    # Start the apache server if the list of tests isn't defined, meaning all tests\n    # are to be run, or if the renegotiate test is included in the list of tests.\n    if [[ -z $TOX_TEST_NAME ]] || [[ \"${TOX_TEST_NAME}\" == *\"test_renegotiate_apache\"* ]]; then\n        source codebuild/bin/s2n_apache2.sh\n        APACHE_CERT_DIR=\"$(pwd)/tests/pems\"\n\n        apache2_start \"${APACHE_CERT_DIR}\"\n    fi\n}\n\nrun_integration_v2_tests() {\n    setup_apache_server\n    \"$CB_BIN_DIR/install_s2n_head.sh\" \"$(mktemp -d)\"\n    cmake . -Bbuild \\\n            -DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT \\\n            -D${CMAKE_PQ_OPTION} \\\n            -DS2N_BLOCK_NONPORTABLE_OPTIMIZATIONS=True \\\n            -DBUILD_SHARED_LIBS=on \\\n            -DS2N_INTEG_TESTS=on \\\n            -DPython3_EXECUTABLE=$(which python3)\n    cmake --build ./build --clean-first -- -j $(nproc)\n    test_linked_libcrypto ./build/bin/s2nc\n    test_linked_libcrypto ./build/bin/s2nd\n    cp -f ./build/bin/s2nc \"$BASE_S2N_DIR\"/bin/s2nc\n    cp -f ./build/bin/s2nd \"$BASE_S2N_DIR\"/bin/s2nd\n    cd ./build/\n    for test_name in $TOX_TEST_NAME; do\n      test=\"${test_name//test_/}\"\n      echo \"Running... ctest --no-tests=error --output-on-failure --verbose -R ^integrationv2_${test}$\"\n      ctest --no-tests=error --output-on-failure --verbose -R ^integrationv2_${test}$\n    done\n}\n\nrun_unit_tests() {\n    cmake . -Bbuild \\\n            -DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT \\\n            -D${CMAKE_PQ_OPTION} \\\n            -DS2N_BLOCK_NONPORTABLE_OPTIMIZATIONS=True \\\n            -DBUILD_SHARED_LIBS=on \\\n            -DEXPERIMENTAL_TREAT_WARNINGS_AS_ERRORS=on\n    cmake --build ./build -- -j $(nproc)\n    test_linked_libcrypto ./build/bin/s2nc\n    cmake --build build/ --target test -- ARGS=\"-L unit --output-on-failure -j $(nproc)\"\n}\n\n# Run Multiple tests on one flag.\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"sawHMACPlus\" ]] && [[ \"$OS_NAME\" == \"linux\" ]]; then make -C tests/saw tmp/verify_HMAC.log tmp/verify_drbg.log failure-tests; fi\n\n# Run Individual tests\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"unit\" ]]; then run_unit_tests; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"interning\" ]]; then ./codebuild/bin/test_libcrypto_interning.sh; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"exec_leak\" ]]; then ./codebuild/bin/test_exec_leak.sh; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"asan\" ]]; then make clean; S2N_ADDRESS_SANITIZER=1 make -j $JOBS ; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"integrationv2\" ]]; then run_integration_v2_tests; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"crt\" ]]; then ./codebuild/bin/build_aws_crt_cpp.sh $(mktemp -d) $(mktemp -d); fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"sharedandstatic\" ]]; then ./codebuild/bin/test_install_shared_and_static.sh $(mktemp -d); fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"dynamicload\" ]]; then ./codebuild/bin/test_dynamic_load.sh $(mktemp -d); fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"fuzz\" ]]; then (make clean && make fuzz) ; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"benchmark\" ]]; then (make clean && make benchmark) ; fi\nif [[ \"$TESTS\" == \"sawHMAC\" ]] && [[ \"$OS_NAME\" == \"linux\" ]]; then make -C tests/saw/ tmp/verify_HMAC.log ; fi\nif [[ \"$TESTS\" == \"sawDRBG\" ]]; then make -C tests/saw tmp/verify_drbg.log ; fi\nif [[ \"$TESTS\" == \"ALL\" || \"$TESTS\" == \"tls\" ]]; then make -C tests/saw tmp/verify_handshake.log ; fi\nif [[ \"$TESTS\" == \"sawHMACFailure\" ]]; then make -C tests/saw failure-tests ; fi\n", "num_lines": 144}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nsource codebuild/bin/s2n_setup_env.sh\n# Use prlimit to set the memlock limit to unlimited for linux. OSX is unlimited by default\n# Codebuild Containers aren't allowing prlimit changes (and aren't being caught with the usual cgroup check)\nif [[ \"$OS_NAME\" == \"linux\" && -n \"$CODEBUILD_BUILD_ARN\" ]]; then\n    PRLIMIT_LOCATION=`which prlimit`\n    sudo -E ${PRLIMIT_LOCATION} --pid \"$$\" --memlock=unlimited:unlimited;\nfi\n\nCMAKE_PQ_OPTION=\"S2N_NO_PQ=False\"\nif [[ -n \"$S2N_NO_PQ\" ]]; then\n    CMAKE_PQ_OPTION=\"S2N_NO_PQ=True\"\nfi\n\n# Linker flags are a workaround for openssl\ncase \"$TESTS\" in\n  \"unit\") cmake . -Bbuild -DCMAKE_EXE_LINKER_FLAGS=\"-lcrypto -lz\" -DCMAKE_EXPORT_COMPILE_COMMANDS=ON -D${CMAKE_PQ_OPTION} -DS2N_BLOCK_NONPORTABLE_OPTIMIZATIONS=True\n          cmake --build ./build -j $(nproc)\n          cmake --build ./build --target test -- ARGS=\"-L unit --output-on-failure\"\n\t  ;;\n  *) echo \"Unknown test\"\n     exit 1;;\nesac\n\n", "num_lines": 41}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\nset -ex\n\nsource codebuild/bin/s2n_setup_env.sh\n\n# Install missing test dependencies. If the install directory already exists, cached artifacts will be used\n# for that dependency.\n\nif [[ ! -d test-deps ]]; then\n    mkdir test-deps ;\nfi\n\n#Install & Run shell check before installing dependencies\necho \"Installing ShellCheck...\"\ncodebuild/bin/install_shellcheck.sh\necho \"Running ShellCheck...\"\nfind ./codebuild -type f -name '*.sh' -exec shellcheck -Cnever -s bash {} \\;\n\nif [[ \"$OS_NAME\" == \"linux\" ]]; then\n    codebuild/bin/install_ubuntu_dependencies.sh;\nfi\n\nif [[ \"$OS_NAME\" == \"darwin\" ]]; then\n    codebuild/bin/install_osx_dependencies.sh;\nfi\n\ncodebuild/bin/install_default_dependencies.sh\n\necho \"Success\"\n", "num_lines": 45}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nset -ex\n\n# Add all of our test dependencies to the PATH. Use Openssl 1.1.1 so the latest openssl is used for s_client\n# integration tests.\nexport PATH=$PYTHON_INSTALL_DIR/bin:$OPENSSL_1_1_1_INSTALL_DIR/bin:$GNUTLS_INSTALL_DIR/bin:$SAW_INSTALL_DIR/bin:$Z3_INSTALL_DIR/bin:$SCAN_BUILD_INSTALL_DIR/bin:$PRLIMIT_INSTALL_DIR/bin:$LATEST_CLANG_INSTALL_DIR/bin:`pwd`/codebuild/bin:~/.local/bin:$PATH\nexport LD_LIBRARY_PATH=$OPENSSL_1_1_1_INSTALL_DIR/lib:$LD_LIBRARY_PATH; \nexport DYLD_LIBRARY_PATH=$OPENSSL_1_1_1_INSTALL_DIR/lib:$LD_LIBRARY_PATH;", "num_lines": 21}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# TODO: Flag user if they didn't source this, values won't stick.\n\nsource codebuild/bin/s2n_set_build_preset.sh\n\n# Setup Default Build Config\n: \"${S2N_LIBCRYPTO:=openssl-1.1.1}\"\n: \"${BUILD_S2N:=false}\"\n: \"${GCC_VERSION:=NONE}\"\n: \"${LATEST_CLANG:=false}\"\n: \"${TESTS:=unit}\"\n: \"${S2N_COVERAGE:=false}\"\n: \"${LD_LIBRARY_PATH:=NONE}\"\n\n# Setup the cache directory paths.\n# Set Env Variables with defaults if they aren't already set\n: \"${BASE_S2N_DIR:=$(pwd)}\"\n: \"${TEST_DEPS_DIR:=$BASE_S2N_DIR/test-deps}\"\n: \"${PYTHON_INSTALL_DIR:=$TEST_DEPS_DIR/python}\"\n: \"${GNUTLS_INSTALL_DIR:=$TEST_DEPS_DIR/gnutls}\"\n: \"${GNUTLS37_INSTALL_DIR:=$TEST_DEPS_DIR/gnutls37}\"\n: \"${PRLIMIT_INSTALL_DIR:=$TEST_DEPS_DIR/prlimit}\"\n: \"${SAW_INSTALL_DIR:=$TEST_DEPS_DIR/saw}\"\n: \"${Z3_INSTALL_DIR:=$TEST_DEPS_DIR/z3}\"\n: \"${LIBFUZZER_INSTALL_DIR:=$TEST_DEPS_DIR/libfuzzer}\"\n: \"${LATEST_CLANG_INSTALL_DIR:=$TEST_DEPS_DIR/clang}\"\n: \"${SCAN_BUILD_INSTALL_DIR:=$TEST_DEPS_DIR/scan-build}\"\n: \"${OPENSSL_0_9_8_INSTALL_DIR:=$TEST_DEPS_DIR/openssl-0.9.8}\"\n: \"${OPENSSL_1_1_1_INSTALL_DIR:=$TEST_DEPS_DIR/openssl-1.1.1}\"\n: \"${OPENSSL_3_0_INSTALL_DIR:=$TEST_DEPS_DIR/openssl-3.0}\"\n: \"${OPENSSL_1_0_2_INSTALL_DIR:=$TEST_DEPS_DIR/openssl-1.0.2}\"\n: \"${OQS_OPENSSL_1_1_1_INSTALL_DIR:=$TEST_DEPS_DIR/oqs_openssl-1.1.1}\"\n: \"${OPENSSL_1_0_2_FIPS_INSTALL_DIR:=$TEST_DEPS_DIR/openssl-1.0.2-fips}\"\n: \"${BORINGSSL_INSTALL_DIR:=$TEST_DEPS_DIR/boringssl}\"\n: \"${AWSLC_INSTALL_DIR:=$TEST_DEPS_DIR/awslc}\"\n: \"${AWSLC_FIPS_INSTALL_DIR:=$TEST_DEPS_DIR/awslc-fips}\"\n: \"${AWSLC_FIPS_2022_INSTALL_DIR:=$TEST_DEPS_DIR/awslc-fips-2022}\"\n: \"${LIBRESSL_INSTALL_DIR:=$TEST_DEPS_DIR/libressl}\"\n: \"${CPPCHECK_INSTALL_DIR:=$TEST_DEPS_DIR/cppcheck}\"\n: \"${CTVERIF_INSTALL_DIR:=$TEST_DEPS_DIR/ctverif}\"\n: \"${SIDETRAIL_INSTALL_DIR:=$TEST_DEPS_DIR/sidetrail}\"\n: \"${GB_INSTALL_DIR:=$TEST_DEPS_DIR/gb}\"\n: \"${APACHE2_INSTALL_DIR:=$TEST_DEPS_DIR/apache2}\"\n: \"${FUZZ_TIMEOUT_SEC:=10}\"\n\n# Set some environment vars for OS, Distro and architecture.\n# Standardized as part of systemd http://0pointer.de/blog/projects/os-release\n# Samples:\n#  OS_NAME = \"linux\"\n#  DISTRO=\"ubuntu\"\n#  VERSION_ID = \"18.04\"\n#  VERSION_CODENAME = \"bionic\"\nif [[ -f \"/etc/os-release\" ]]; then\n  # AL2 doesn't provide a codename.\n  . /etc/os-release\n  export DISTRO=$(echo \"$NAME\"|tr \"[:upper:]\" \"[:lower:]\")\n  export VERSION_ID=${VERSION_ID:-\"unknown\"}\n  export VERSION_CODENAME=${VERSION_CODENAME:-\"unknown\"}\nelif [[ -x \"/usr/bin/sw_vers\" ]]; then\n  export DISTRO=\"apple\"\n  export VERSION_ID=$(sw_vers -productVersion|sed 's/:[[:space:]]*/=/g')\n  export VERSION_CODENAME=\"unknown\"  # not queriable via CLI\nelse\n  export DISTRO=\"unknown\"\n  export VERSION_ID=\"unknown\"\n  export VERSION_CODENAME=\"unknown\"\nfi\nexport OS_NAME=$(uname -s|tr \"[:upper:]\" \"[:lower:]\")\nexport ARCH=$(uname -m)\n\n# Export all Env Variables\nexport S2N_LIBCRYPTO\nexport BUILD_S2N\nexport GCC_VERSION\nexport LATEST_CLANG\nexport TESTS\nexport BASE_S2N_DIR\nexport TEST_DEPS_DIR\nexport PYTHON_INSTALL_DIR\nexport GNUTLS_INSTALL_DIR\nexport GNUTLS37_INSTALL_DIR\nexport PRLIMIT_INSTALL_DIR\nexport SAW_INSTALL_DIR\nexport Z3_INSTALL_DIR\nexport LIBFUZZER_INSTALL_DIR\nexport LATEST_CLANG_INSTALL_DIR\nexport SCAN_BUILD_INSTALL_DIR\nexport OPENSSL_0_9_8_INSTALL_DIR\nexport OPENSSL_1_1_1_INSTALL_DIR\nexport OPENSSL_3_0_INSTALL_DIR\nexport OPENSSL_1_0_2_INSTALL_DIR\nexport OPENSSL_1_0_2_FIPS_INSTALL_DIR\nexport OQS_OPENSSL_1_1_1_INSTALL_DIR\nexport BORINGSSL_INSTALL_DIR\nexport AWSLC_INSTALL_DIR\nexport AWSLC_FIPS_INSTALL_DIR\nexport AWSLC_FIPS_2022_INSTALL_DIR\nexport LIBRESSL_INSTALL_DIR\nexport CPPCHECK_INSTALL_DIR\nexport CTVERIF_INSTALL_DIR\nexport SIDETRAIL_INSTALL_DIR\nexport OPENSSL_1_1_X_MASTER_INSTALL_DIR\nexport FUZZ_TIMEOUT_SEC\nexport GB_INSTALL_DIR\nexport OS_NAME\nexport S2N_CORKED_IO\nexport S2N_NO_PQ\n# For use by criterion/ci run reports\nexport AWS_S3_URL=\"s3://s2n-tls-logs/release/\"\n\n# S2N_COVERAGE should not be used with fuzz tests, use FUZZ_COVERAGE instead\nif [[ \"$S2N_COVERAGE\" == \"true\" && \"$TESTS\" == \"fuzz\" ]]; then\n    export S2N_COVERAGE=\"false\"\n    export FUZZ_COVERAGE=\"true\"\nfi\n\n# Select the libcrypto to build s2n against. If this is unset, default to the latest stable version(Openssl 1.1.1)\nif [[ -z $S2N_LIBCRYPTO ]]; then export LIBCRYPTO_ROOT=$OPENSSL_1_1_1_INSTALL_DIR ; fi\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.1.1\" ]]; then export LIBCRYPTO_ROOT=$OPENSSL_1_1_1_INSTALL_DIR ; fi\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-3.0\" ]]; then export LIBCRYPTO_ROOT=$OPENSSL_3_0_INSTALL_DIR ; fi\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.0.2\" ]]; then export LIBCRYPTO_ROOT=$OPENSSL_1_0_2_INSTALL_DIR ; fi\nif [[ \"$S2N_LIBCRYPTO\" == \"openssl-1.0.2-fips\" ]]; then\n    export LIBCRYPTO_ROOT=$OPENSSL_1_0_2_FIPS_INSTALL_DIR ;\n    export S2N_TEST_IN_FIPS_MODE=1 ;\nfi\nif [[ \"$S2N_LIBCRYPTO\" == \"boringssl\" ]]; then export LIBCRYPTO_ROOT=$BORINGSSL_INSTALL_DIR ; fi\n\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc\" ]]; then export LIBCRYPTO_ROOT=$AWSLC_INSTALL_DIR ; fi\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc-fips\" ]]; then\n  export LIBCRYPTO_ROOT=$AWSLC_FIPS_INSTALL_DIR ;\n  export S2N_TEST_IN_FIPS_MODE=1 ;\nfi\nif [[ \"$S2N_LIBCRYPTO\" == \"awslc-fips-2022\" ]]; then\n  export LIBCRYPTO_ROOT=$AWSLC_FIPS_2022_INSTALL_DIR\n  export S2N_TEST_IN_FIPS_MODE=1\nfi\n\nif [[ \"$S2N_LIBCRYPTO\" == \"libressl\" ]]; then export LIBCRYPTO_ROOT=$LIBRESSL_INSTALL_DIR ; fi\n\n# Create a link to the selected libcrypto. This shouldn't be needed when LIBCRYPTO_ROOT is set, but some tests\n# have the \"libcrypto-root\" directory path hardcoded.\nrm -rf libcrypto-root && ln -s \"$LIBCRYPTO_ROOT\" libcrypto-root\n\n# Set the libfuzzer to use for fuzz tests\nexport LIBFUZZER_ROOT=$LIBFUZZER_INSTALL_DIR\n\n#check if the path contains test dep X, if not and X exists, add to path\npath_overrides=\"$PYTHON_INSTALL_DIR/bin\n$OPENSSL_1_1_1_INSTALL_DIR/bin\n$GNUTLS_INSTALL_DIR/bin\n$SAW_INSTALL_DIR/bin\n$Z3_INSTALL_DIR/bin\n$SCAN_BUILD_INSTALL_DIR/bin\n$PRLIMIT_INSTALL_DIR/bin\n$LATEST_CLANG_INSTALL_DIR/bin\n`pwd`/codebuild/bin\n~/.local/bin\"\n\ntestdeps_path(){\n    echo -ne \"checking $1 is in the path...\"\n    if [[ ! \"$PATH\" =~ \"$1\" ]]; then\n        if [[ -d \"$1\" ]]; then\n            export PATH=\"$1:$PATH\"\n            echo -e \"added\"\n        else\n            echo -e \"doesn't exist\"\n        fi\n    else\n        echo -e \"already in path\"\n    fi\n}\n\nfor i in $path_overrides; do testdeps_path \"$i\" ;done\n\n# Just recording in the output for debugging.\nif [ -f \"/etc/lsb-release\" ]; then\n  cat /etc/lsb-release\nfi\n\n# Translate our custom variables into full paths to the compiler.\nset_cc(){\n  if [ -z ${GCC_VERSION:-} -o ${GCC_VERSION} = \"NONE\" ]; then\n    echo \"No GCC_VERSION set\"\n    if [ ${LATEST_CLANG:-} = \"true\" ]; then\n      echo \"LATEST_CLANG is ${LATEST_CLANG}\"\n      if [ -d ${LATEST_CLANG_INSTALL_DIR:-} ]; then\n        export CC=${LATEST_CLANG_INSTALL_DIR}/bin/clang\n        export CXX=${LATEST_CLANG_INSTALL_DIR}/bin/clang++\n        echo \"CC set to ${CC}\"\n        echo \"CXX set to ${CXX}\"\n      else\n        echo \"Could not find a clang installation $LATEST_CLANG_INSTALL_DIR\"\n      fi\n    fi\n  else\n    echo \"GCC_VERSION is ${GCC_VERSION}\"\n    export CC=$(which gcc-${GCC_VERSION})\n    export CXX=$(which g++-${GCC_VERSION})\n    echo \"CC set to ${CC}\"\n    echo \"CXX set to ${CXX}\"\n  fi\n}\nset_cc\n\necho \"UID=$UID\"\necho \"OS_NAME=$OS_NAME\"\necho \"S2N_LIBCRYPTO=$S2N_LIBCRYPTO\"\necho \"LIBCRYPTO_ROOT=$LIBCRYPTO_ROOT\"\necho \"BUILD_S2N=$BUILD_S2N\"\necho \"GCC_VERSION=$GCC_VERSION\"\necho \"LATEST_CLANG=$LATEST_CLANG\"\necho \"TESTS=$TESTS\"\necho \"PATH=$PATH\"\necho \"LD_LIBRARY_PATH=$LD_LIBRARY_PATH\"\n\n", "num_lines": 230}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\ncase \"${S2N_BUILD_PRESET-default}\" in\n    \"awslc_gcc4-8\")\n        : \"${S2N_LIBCRYPTO:=awslc}\"\n        : \"${GCC_VERSION:=4.8}\"\n        ;;\n    \"awslc_gcc9\")\n        : \"${S2N_LIBCRYPTO:=awslc}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\n    \"awslc-fips_gcc4-8\")\n        : \"${S2N_LIBCRYPTO:=awslc-fips}\"\n        : \"${GCC_VERSION:=4.8}\"\n        ;;\n    \"awslc-fips_gcc9\")\n        : \"${S2N_LIBCRYPTO:=awslc-fips}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\n    \"awslc-fips-2022_gcc6\")\n        : \"${S2N_LIBCRYPTO:=awslc-fips-2022}\"\n        : \"${GCC_VERSION:=6}\"\n        ;;\n    \"libressl_gcc6\")\n        : \"${S2N_LIBCRYPTO:=libressl}\"\n        : \"${GCC_VERSION:=6}\"\n        ;;\n    \"libressl_gcc9\")\n        : \"${S2N_LIBCRYPTO:=libressl}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\n    \"boringssl\")\n        : \"${S2N_LIBCRYPTO:=boringssl}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\n    \"openssl-1.0.2\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.0.2}\"\n        : \"${GCC_VERSION:=6}\"\n        ;;\n    \"openssl-1.0.2-fips\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.0.2-fips}\"\n        : \"${GCC_VERSION:=6}\"\n        ;;\n    \"openssl-1.1.1_gcc4-8\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.1.1}\"\n        : \"${GCC_VERSION:=4.8}\"\n        ;;\n    \"openssl-1.1.1_gcc6\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.1.1}\"\n        : \"${GCC_VERSION:=6}\"\n        : \"${S2N_CORKED_IO:=true}\"\n        ;;\n    \"openssl-1.1.1_gcc6_softcrypto\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.1.1}\"\n        : \"${GCC_VERSION:=6}\"\n        : \"${OPENSSL_ia32cap:=~0x200000200000000}\"\n        ;;\n    \"openssl-1.1.1_gcc9\")\n        : \"${S2N_LIBCRYPTO:=openssl-1.1.1}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\n    \"openssl-3.0\")\n        : \"${S2N_LIBCRYPTO:=openssl-3.0}\"\n        : \"${GCC_VERSION:=9}\"\n        ;;\nesac\n\n", "num_lines": 80}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# This script compiles s2n-tls as a shared library and compiles a test \n# without linking to the library. This enables us to test behavior when \n# s2n-tls is dynamically loaded.\n\nWORK_DIR=$1\n\nif [ ! -z \"$NIX_STORE\" ]; then\n    OPENSSL=$(which openssl)\n    LIBCRYPTO_ROOT=$(nix-store --query $OPENSSL)\nelse\n    source codebuild/bin/s2n_setup_env.sh\nfi\n\nS2N_BUILD_ARGS=(-H. -DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT -DBUILD_TESTING=OFF)\n\n# create installation dir with libs2n.so\nif [ ! -d $WORK_DIR/s2n-install-shared ]; then\n    (set -x; cmake -B$WORK_DIR/s2n-build-shared -DCMAKE_INSTALL_PREFIX=$WORK_DIR/s2n-install-shared -DBUILD_SHARED_LIBS=ON ${S2N_BUILD_ARGS[@]})\n    (set -x; cmake --build $WORK_DIR/s2n-build-shared --target install -- -j $(nproc))\nfi\n\n# Compile the test file\n$CC -Wl,-rpath $LIBCRYPTO_ROOT -o s2n_dynamic_load_test codebuild/bin/s2n_dynamic_load_test.c -ldl -lpthread\n\nLDD_OUTPUT=$(ldd s2n_dynamic_load_test)\n\n# Confirm executable doesn't have libs2n.so loaded\nif echo \"$LDD_OUTPUT\" | grep -q libs2n; then\n    echo \"test failure: libs2n should not appear in ldd output\"\n    exit 1\nfi\n\n# Run the test with the path to libs2n\necho \"Running s2n_dynamic_load_test\"\nLD_LIBRARY_PATH=$LIBCRYPTO_ROOT/lib ./s2n_dynamic_load_test $WORK_DIR/s2n-install-shared/lib/libs2n.so\nreturncode=$?\nif [ $returncode -ne 0 ]; then\n    echo \"test failure: s2n_dynamic_load_test did not succeed\"\n    exit 1\nfi\necho \"Passed s2n_dynamic_load_test\"\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\n# Test that all file descriptors are properly cleaned up when `exec`ing from\n# from an initialized s2n-tls process.\n\nsource codebuild/bin/s2n_setup_env.sh\nsource codebuild/bin/jobs.sh\n\nfunction build() {\n  echo \"=== BUILDING $1 ===\"\n  cmake . -B$1 -DCMAKE_PREFIX_PATH=$TARGET_LIBCRYPTO_PATH ${@:2}\n  cmake --build $1 -- -j $JOBS\n}\n\nfunction fail() {\n    echo \"test failure: $1\"\n    exit 1\n}\n\nfunction write_exec_app() {\ncat <<EOF > build/detect_exec_leak.c\n#include <s2n.h>\n#include \"unistd.h\"\n\nint main() {\n    s2n_init();\n    execl(\"build/bin/detect_exec_leak_finish\", \"\", NULL);\n    return 0;\n}\nEOF\n}\n\nfunction write_exec_finish_app() {\ncat <<EOF > build/detect_exec_leak_finish.c\n#include <s2n.h>\n\nint main() {\n    s2n_init();\n    s2n_cleanup();\n\n    /* close std* file descriptors so valgrind output is less noisy */\n    fclose(stdin);\n    fclose(stdout);\n    fclose(stderr);\n    return 0;\n}\nEOF\n}\n\n# download libcrypto if its not available\nTARGET_LIBCRYPTO=\"${S2N_LIBCRYPTO//[-.]/_}\"\nTARGET_LIBCRYPTO_PATH=\"${TEST_DEPS_DIR}/${S2N_LIBCRYPTO}\"\nif [ ! -f $TARGET_LIBCRYPTO_PATH/lib/libcrypto.a ]; then\n    ./codebuild/bin/install_${TARGET_LIBCRYPTO}.sh $TARGET_LIBCRYPTO_PATH/src $TARGET_LIBCRYPTO_PATH linux\nfi\n\n# build s2n-tls\nbuild build -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on\n\n# compile the test app for exec leak test\nmkdir -p build/valgrind_log_dir\nwrite_exec_app\nwrite_exec_finish_app\ncc -Iapi build/detect_exec_leak.c build/lib/libs2n.so -o build/bin/detect_exec_leak\ncc -Iapi build/detect_exec_leak_finish.c build/lib/libs2n.so -o build/bin/detect_exec_leak_finish\n\n# run valgrind with track-fds enabled\nvalgrind_log_dir=valgrind_log_dir\nfor test_file in detect_exec_leak detect_exec_leak_finish; do\n    LD_LIBRARY_PATH=\"build/lib:$TARGET_LIBCRYPTO_PATH/lib:$LD_LIBRARY_PATH\" S2N_VALGRIND=1 \\\n        valgrind --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all \\\n        --run-libc-freeres=yes -q --gen-suppressions=all --track-fds=yes \\\n        --leak-resolution=high --undef-value-errors=no --trace-children=yes \\\n        --suppressions=tests/unit/valgrind.suppressions --log-file=\"build/$valgrind_log_dir/$test_file\" \\\n    \t  build/bin/$test_file\n\n    # search for all leaked file descriptors, excluding the valgrind_log_dir file\n    cat build/$valgrind_log_dir/$test_file | \\\n        grep \"Open file descriptor\" | \\\n        grep --invert-match $valgrind_log_dir \\\n        && fail \"file leak detected while running $test_file\"\ndone\n\necho pass\n", "num_lines": 100}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nset -eo pipefail\n\nusage() {\n    echo \"test_install_shared_and_static.sh build_dir\"\n    echo \"Checks that installed s2n-config.cmake chooses appropriately between shared and static.\"\n    echo \"Note that you MUST build against the version of libcrypto that's actually installed on the system,\"\n    echo \"because installing libs2n.so forces it to use the system's libcrypto.so.\"\n    exit 1\n}\n\nif [ \"$#\" -ne 1 ]; then\n    usage\nfi\n\nWORK_DIR=$1\n\nsource codebuild/bin/s2n_setup_env.sh\nsource codebuild/bin/jobs.sh\n\nCOMMON_S2N_BUILD_ARGS=(-H. -DCMAKE_PREFIX_PATH=$LIBCRYPTO_ROOT -DBUILD_TESTING=OFF)\n\n# create installation dir with libs2n.so\nif [ ! -d $WORK_DIR/s2n-install-shared ]; then\n    (set -x; cmake -B$WORK_DIR/s2n-build-shared -DCMAKE_INSTALL_PREFIX=$WORK_DIR/s2n-install-shared -DBUILD_SHARED_LIBS=ON ${COMMON_S2N_BUILD_ARGS[@]})\n    (set -x; cmake --build $WORK_DIR/s2n-build-shared --target install -- -j $JOBS)\nfi\n\n# create installation dir with libs2n.a\nif [ ! -d $WORK_DIR/s2n-install-static ]; then\n    (set -x; cmake -B$WORK_DIR/s2n-build-static -DCMAKE_INSTALL_PREFIX=$WORK_DIR/s2n-install-static -DBUILD_SHARED_LIBS=OFF ${COMMON_S2N_BUILD_ARGS[@]})\n    (set -x; cmake --build $WORK_DIR/s2n-build-static --target install -- -j $JOBS)\nfi\n\n# create installation dir with both libs2n.so and libs2n.a\nif [ ! -d $WORK_DIR/s2n-install-both ]; then\n    (set -x; cmake -B$WORK_DIR/s2n-build-shared-both -DCMAKE_INSTALL_PREFIX=$WORK_DIR/s2n-install-both -DBUILD_SHARED_LIBS=ON ${COMMON_S2N_BUILD_ARGS[@]})\n    (set -x; cmake --build $WORK_DIR/s2n-build-shared-both --target install -- -j $JOBS)\n\n    (set -x; cmake -B$WORK_DIR/s2n-build-static-both -DCMAKE_INSTALL_PREFIX=$WORK_DIR/s2n-install-both -DBUILD_SHARED_LIBS=OFF  ${COMMON_S2N_BUILD_ARGS[@]})\n    (set -x; cmake --build $WORK_DIR/s2n-build-static-both --target install -- -j $JOBS)\nfi\n\n# write out source of a small cmake project, containing:\n# - mylib: a library that uses s2n\n# - myapp: executable that uses mylib\nrm -rf $WORK_DIR/myapp-src\nmkdir -p $WORK_DIR/myapp-src\n\ncat <<EOF > $WORK_DIR/myapp-src/mylib.c\nextern int s2n_init(void);\n\nvoid mylib_init(void) {\n    s2n_init();\n}\nEOF\n\ncat <<EOF > $WORK_DIR/myapp-src/myapp.c\nextern void mylib_init(void);\n\nint main() {\n    mylib_init();\n}\nEOF\n\ncat <<EOF > $WORK_DIR/myapp-src/CMakeLists.txt\ncmake_minimum_required (VERSION 3.0)\nproject (myapp C)\n\nadd_library(mylib mylib.c)\nfind_package(s2n REQUIRED)\ntarget_link_libraries(mylib PRIVATE AWS::s2n)\n\nadd_executable(myapp myapp.c)\ntarget_link_libraries(myapp PRIVATE mylib)\nEOF\n\n# build myapp and mylib, confirm that expected type of libs2n is used\nbuild_myapp() {\n    local BUILD_SHARED_LIBS=$1 # (\"BUILD_SHARED_LIBS=ON\" or \"BUILD_SHARED_LIBS=OFF\")\n    local S2N_INSTALL_DIR=$2 # which s2n-install dir should be used\n    local LIBS2N_EXPECTED=$3 # (\"libs2n.so\" or \"libs2n.a\") which type of libs2n is expected to be used\n\n    echo \"---------------------------------------------------------------------\"\n    echo \"building myapp with $BUILD_SHARED_LIBS looking-in:$S2N_INSTALL_DIR should-use:$LIBS2N_EXPECTED\"\n\n    local MYAPP_BUILD_DIR=$WORK_DIR/myapp-build\n    rm -rf $MYAPP_BUILD_DIR/\n\n    local S2N_INSTALL_PATH=$(realpath $WORK_DIR/$S2N_INSTALL_DIR)\n\n    (set -x; cmake -H$WORK_DIR/myapp-src -B$MYAPP_BUILD_DIR -D$BUILD_SHARED_LIBS \"-DCMAKE_PREFIX_PATH=$S2N_INSTALL_PATH;$LIBCRYPTO_ROOT\")\n    (set -x; cmake --build $MYAPP_BUILD_DIR)\n\n    LDD_OUTPUT=$(ldd $MYAPP_BUILD_DIR/myapp)\n    echo \"$LDD_OUTPUT\"\n\n    if echo \"$LDD_OUTPUT\" | grep -q libs2n.so; then\n        local LIBS2N_ACTUAL=libs2n.so\n    else\n        local LIBS2N_ACTUAL=libs2n.a\n    fi\n\n    if [ $LIBS2N_ACTUAL != $LIBS2N_EXPECTED ]; then\n        echo \"test failure: used $LIBS2N_ACTUAL, but expected to use $LIBS2N_EXPECTED\"\n        exit 1\n    fi\n}\n\n# if only shared libs2n.so is available, that's what should get used\nbuild_myapp BUILD_SHARED_LIBS=ON s2n-install-shared libs2n.so\nbuild_myapp BUILD_SHARED_LIBS=OFF s2n-install-shared libs2n.so\n\n# if only static libs2n.a is available, that's what should get used\nbuild_myapp BUILD_SHARED_LIBS=ON s2n-install-static libs2n.a\nbuild_myapp BUILD_SHARED_LIBS=OFF s2n-install-static libs2n.a\n\n# if both libs2n.so and libs2n.a are available...\nbuild_myapp BUILD_SHARED_LIBS=ON s2n-install-both libs2n.so # should choose libs2n.so\nbuild_myapp BUILD_SHARED_LIBS=OFF s2n-install-both libs2n.a # should choose libs2n.a\n", "num_lines": 134}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nsource codebuild/bin/s2n_setup_env.sh\nsource codebuild/bin/jobs.sh\n\n# build 2 different version of libcrypto to make it easy to break the application if\n# interning doesn't work as expected\nWHICH_LIBCRYPTO=$(echo \"${S2N_LIBCRYPTO:-\"openssl-1.1.1\"}\")\nTARGET_LIBCRYPTO=\"${WHICH_LIBCRYPTO//[-.]/_}\"\nTARGET_LIBCRYPTO_PATH=\"${TEST_DEPS_DIR}/${WHICH_LIBCRYPTO}\"\nOPENSSL_1_0=\"$OPENSSL_1_0_2_INSTALL_DIR\"\nif [ ! -f $OPENSSL_1_0/lib/libcrypto.a ]; then\n  ./codebuild/bin/install_openssl_1_0_2.sh $OPENSSL_1_0/src $OPENSSL_1_0 linux\nfi\nif [ ! -f $TARGET_LIBCRYPTO_PATH/lib/libcrypto.a ]; then\n  if [ \"$TARGET_LIBCRYPTO\" == \"awslc\" ]; then\n    ./codebuild/bin/install_${TARGET_LIBCRYPTO}.sh $TARGET_LIBCRYPTO_PATH/src $TARGET_LIBCRYPTO_PATH 0\n  else\n    ./codebuild/bin/install_${TARGET_LIBCRYPTO}.sh $TARGET_LIBCRYPTO_PATH/src $TARGET_LIBCRYPTO_PATH linux\n  fi\nfi\n\nCOMMON_FLAGS=\"-DCMAKE_PREFIX_PATH=$TARGET_LIBCRYPTO_PATH -DCMAKE_BUILD_TYPE=RelWithDebInfo\"\nLTO_FLAGS=\"-DS2N_LTO=on\"\n\n# use LTO-aware commands if possible\nif [ -x \"$(command -v gcc-ar)\" ]; then\n  LTO_FLAGS+=\" -DCMAKE_AR=$(which gcc-ar) -DCMAKE_NM=$(which gcc-nm) -DCMAKE_RANLIB=$(which gcc-ranlib)\"\nfi\n\nfunction fail() {\n    echo \"test failure: $1\"\n    exit 1\n}\n\nfunction write_app() {\ncat <<EOF > $1\n#include <s2n.h>\n#include <openssl/bn.h>\n\nint main() {\n    s2n_init();\n    BN_CTX_new();\n    return 0;\n}\nEOF\n}\n\nfunction build() {\n  echo \"=== BUILDING $1 ===\"\n  cmake . -B$1 $COMMON_FLAGS ${@:2}\n  cmake --build $1 -- -j $JOBS\n}\n\nfunction tests() {\n  echo \"=== TESTING $1 ===\"\n  make -C $1 test ARGS=\"-j $JOBS -L unit\"\n}\n\n##################\n# Dynamic builds #\n##################\n\n# build a default version to test what happens without interning\nbuild build/shared-default -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on\nldd ./build/shared-default/lib/libs2n.so | grep -q libcrypto || fail \"shared-default: libcrypto was not linked\"\n\n# ensure libcrypto interning works with shared libs and no testing\nbuild build/shared -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=off -DS2N_INTERN_LIBCRYPTO=on\n# s2n should not publicly depend on libcrypto\nldd ./build/shared/lib/libs2n.so | grep -q libcrypto && fail \"shared: libcrypto was not interned\"\n\n# ensure libcrypto interning works with shared libs, LTO and no testing\n# NOTE: interning+LTO+testing doesn't currently work\nbuild build/shared-lto -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=off -DS2N_INTERN_LIBCRYPTO=on $LTO_FLAGS\n# s2n should not publicly depend on libcrypto\nldd ./build/shared-lto/lib/libs2n.so | grep -q libcrypto && fail \"shared-lto: libcrypto was not interned\"\n\n# ensure libcrypto interning works with shared libs and testing\nbuild build/shared-testing -DBUILD_SHARED_LIBS=on -DBUILD_TESTING=on -DS2N_INTERN_LIBCRYPTO=on\n# s2n should not publicly depend on libcrypto\nldd ./build/shared-testing/lib/libs2n.so | grep -q libcrypto && fail \"shared-testing: libcrypto was not interned\"\n# run the tests and make sure they all pass with the prefixed version\ntests build/shared-testing\n# load the wrong version of libcrypto and the tests should still pass\nLD_PRELOAD=$OPENSSL_1_0/lib/libcrypto.so tests build/shared-testing\n\n# ensure the small app will compile with both versions of openssl without any linking issues\nfor build in shared shared-lto; do\n  # create a small app that links against both s2n and libcrypto\n  write_app build/$build/app.c\n\n  for target in $OPENSSL_1_0 $TARGET_LIBCRYPTO_PATH; do\n    echo \"testing $build linking with $target\"\n    mkdir -p $target/bin\n    cc -fPIE -Iapi -I$target/include build/$build/app.c build/$build/lib/libs2n.so $target/lib/libcrypto.a -lpthread -ldl -o $target/bin/test-app\n    # make sure the app doesn't crash\n    LD_LIBRARY_PATH=\"build/$build/lib:$target/lib:$LD_LIBRARY_PATH\" $target/bin/test-app\n  done\ndone\n\n##################\n# Static builds  #\n##################\n\n# ensure libcrypto interning works with static libs\n# NOTE: static builds don't vary based on testing being enabled\nbuild build/static -DBUILD_SHARED_LIBS=off -DBUILD_TESTING=on -DS2N_INTERN_LIBCRYPTO=on\ntests build/static\n\n# TODO figure out how to get static-lto+interning builds working\n\n# ensure the small app will compile with both versions of openssl without any linking issues\nfor build in static; do\n  # create a small app that links against both s2n and libcrypto\n  write_app build/$build/app.c\n\n  for target in $OPENSSL_1_0 $TARGET_LIBCRYPTO_PATH; do\n    echo \"testing $build linking with $target\"\n    mkdir -p $target/bin\n    cc -fPIE -Iapi -I$target/include build/$build/app.c build/$build/lib/libs2n.a $target/lib/libcrypto.a -lpthread -ldl -o $target/bin/test-app\n    nm $target/bin/test-app | grep -q 'T s2n$BN_CTX_new' || fail \"$target: libcrypto symbols were not prefixed\"\n    nm $target/bin/test-app | grep -q 'T BN_CTX_new' || fail \"$target: libcrypto was not linked in application\"\n    # make sure the app doesn't crash\n    $target/bin/test-app\n  done\ndone\n\n##################\n# Runtime tests  #\n##################\n\nrun_connection_test() {\n    local TARGET=\"$1\"\n    LD_PRELOAD=$OPENSSL_1_0/lib/libcrypto.so ./build/$TARGET/bin/s2nd -c default_tls13 localhost 4433 &> /dev/null &\n    local SERVER_PID=$!\n    LD_PRELOAD=$OPENSSL_1_0/lib/libcrypto.so ./build/$TARGET/bin/s2nc -i -c default_tls13 localhost 4433 | tee build/client.log\n    kill $SERVER_PID &> /dev/null || true\n\n    # ensure a TLS 1.3 session was negotiated\n    echo \"checking for TLS 1.3\"\n    grep -q \"Actual protocol version: 34\" build/client.log\n}\n\n# without interning, the connection should fail when linking the wrong version of libcrypto\necho \"running pair: TLS 1.3 failure expected\"\nrun_connection_test shared-default && fail \"TLS 1.3 handshake was expected to fail\"\n\n# with interning, the connection should succeed even though we've linked the wrong version of libcrypto\necho \"running pair: TLS 1.3 success expected\"\nrun_connection_test shared-testing || fail \"TLS 1.3 handshake was expected to succeed\"\n\necho \"SUCCESS!\"\n", "num_lines": 169}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\nset -e\n\n# Utility functions\nget_latest_release(){\n    local LATEST_RELEASE_URL=$(gh api /repos/aws/s2n-tls/releases/latest|jq -r '.tarball_url')\n    local LATEST_RELEASE_VER=$(echo \"${LATEST_RELEASE_URL}\" | sed 's|.*/||')\n    echo \"${LATEST_RELEASE_VER}\"\n}\n\ngh_login(){\n    # Takes secrets manager key as an argument\n    # This GH personal access token must have 'repo' permissions to work.\n    gh auth status || aws secretsmanager get-secret-value --secret-id \"$1\" --query 'SecretString' --output text |jq -r '.secret_key'| gh auth login --with-token\n\n    #gh auth status\n}\n\ncriterion_install_deps(){\n    make install\n    source \"$HOME\"/.cargo/env\n    make -C bindings/rust\n}\n\n\nusage(){\n    echo -e \"Usage:\\n\\tget_latest_release: returns just the latest v.N.N.N version\"\n    echo -e \"\\tgh_login <Secret Name> : retrieves a GitHub PAT from secrest manager and logs into GitHub.\\n\"\n}\n\nif [[ \"${BASH_SOURCE[0]}\" == \"${0}\"  ]]; then\n    case \"${1:-}\" in\n        \"gh_login\")\n            gh_login \"${2:-}\";;\n        \"get_latest_release\")\n            get_latest_release\n            echo \"$LATEST_RELEASE_VER\";;\n        *)  usage;\n    esac\nfi\n", "num_lines": 54}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#/usr/bin/env bash\n\nset -e\n\nTOPLEVEL=$(git rev-parse --show-toplevel)\n\nBLOB=${1:-main}\n\npushd $TOPLEVEL > /dev/null\n\nduvet \\\n  report \\\n  --spec-pattern 'compliance/specs/**/*.toml' \\\n  --source-pattern '(*=,*#)api/**/*.[ch]' \\\n  --source-pattern '(*=,*#)bin/**/*.[ch]' \\\n  --source-pattern '(*=,*#)crypto/**/*.[ch]' \\\n  --source-pattern '(*=,*#)error/**/*.[ch]' \\\n  --source-pattern '(*=,*#)pq-crypto/**/*.[ch]' \\\n  --source-pattern '(*=,*#)stuffer/**/*.[ch]' \\\n  --source-pattern '(*=,*#)tests/**/*.[ch]' \\\n  --source-pattern '(*=,*#)tls/**/*.[ch]' \\\n  --source-pattern '(*=,*#)utils/**/*.[ch]' \\\n  --require-tests false \\\n  --blob-link \"https://github.com/aws/s2n/blob/$BLOB\" \\\n  --issue-link 'https://github.com/aws/s2n/issues' \\\n  --no-cargo \\\n  --html compliance/report.html\n  \necho \"report available in compliance/report.html\"\n\npopd > /dev/null\n\n", "num_lines": 33}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#/usr/bin/env bash\n\nduvet extract https://tools.ietf.org/rfc/rfc5869 # HMAC-based Extract-and-Expand Key Derivation Function (HKDF)\nduvet extract https://tools.ietf.org/rfc/rfc8446 # The Transport Layer Security (TLS) Protocol Version 1.3\nduvet extract https://tools.ietf.org/rfc/rfc8448 # Example Handshake Traces for TLS 1.3\nduvet extract https://tools.ietf.org/rfc/rfc7627 # Transport Layer Security (TLS) Session Hash and Extended Master Secret Extension\nduvet extract https://tools.ietf.org/rfc/rfc5746 # Transport Layer Security (TLS) Renegotiation Indication Extension\nduvet extract https://tools.ietf.org/rfc/rfc4492 # Elliptic Curve Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)\n\n", "num_lines": 10}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "echo nix/shell.sh: Entering a devShell\nexport SRC_ROOT=$(pwd)\nexport PATH=$SRC_ROOT/build/bin:$PATH\n\nbanner()\n{\n    echo \"+---------------------------------------------------------+\"\n    printf \"| %-55s |\\n\" \"$1\"\n    echo \"+---------------------------------------------------------+\"\n}\n\n\nfunction clean {\n    banner \"Cleanup up ./build\"\n    rm -rf ./build\n}\n\nfunction configure {\n    banner \"Configuring with cmake\"\n    cmake -S . -B./build \\\n          -DBUILD_TESTING=ON \\\n          -DS2N_INTEG_TESTS=ON \\\n          -DS2N_INSTALL_S2NC_S2ND=ON \\\n          -DS2N_INTEG_NIX=ON \\\n          -DBUILD_SHARED_LIBS=ON \\\n          -DCMAKE_BUILD_TYPE=RelWithDebInfo\n}\n\nfunction build {\n    banner \"Running Build\"\n    javac tests/integrationv2/bin/SSLSocketClient.java\n    cmake --build ./build -j $(nproc)\n}\n\nfunction unit {\n    if [[ -z \"$1\" ]]; then\n        (cd $SRC_ROOT/build; ctest -L unit -j $(nproc) --verbose)\n    else\n        (cd $SRC_ROOT/build; ctest -L unit -R $1 -j $(nproc) --verbose)\n    fi\n}\n\nfunction integ {\n    if [ \"$1\" == \"help\" ]; then\n        echo \"The following tests are not supported:\"\n        echo \" - cross_compatibility\"\n        echo \"    This test depends on s2nc_head and s2nd_head. To run\"\n        echo \"    the test build s2n-tls from the main branch on github.\"\n        echo \"    Change the names of s2n[cd] to s2n[cd]_head and add those\"\n        echo \"    binaries to \\$PATH.\"\n        echo \"- renegotiate_apache\"\n        echo \"   This test requires apache to be running. See codebuild/bin/s2n_apache.sh\"\n        echo \"    for more info.\"\n        return\n    fi\n    if [[ -z \"$1\" ]]; then\n        banner \"Running all integ tests except cross_compatibility, renegotiate_apache.\"\n        (cd $SRC_ROOT/build; ctest -L integrationv2 -E \"(integrationv2_cross_compatibility|integrationv2_renegotiate_apache)\" --verbose)\n    else\n        banner \"Warning: cross_compatibility & renegotiate_apache are not supported in nix for various reasons integ help for more info.\"\n        for test in $@; do\n            ctest --test-dir ./build -L integrationv2 --no-tests=error --output-on-failure -R \"$test\" --verbose\n            if [ \"$?\" -ne 0 ]; then\n               echo \"Test failed, stopping execution\"\n               exit 1\n            fi\n        done\n    fi\n}\n\nfunction check-clang-format {\n    banner \"Dry run of clang-format\"\n    (cd $SRC_ROOT;\n    include_regex=\".*\\.(c|h)$\";\n    src_files=`find ./api -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./bin -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./crypto -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./stuffer -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./error -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tls -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./utils -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tests/unit -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tests/testlib -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    echo $src_files | xargs -n 1 -P $(nproc) clang-format --dry-run -style=file)\n}\nfunction do-clang-format {\n    banner \"In place clang-format\"\n    (cd $SRC_ROOT;\n    include_regex=\".*\\.(c|h)$\";\n    src_files=`find ./api -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./bin -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./crypto -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./stuffer -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./error -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tls -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./utils -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tests/unit -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    src_files+=\" \";\n    src_files+=`find ./tests/testlib -name .git -prune -o -regextype posix-egrep -regex \"$include_regex\" -print`;\n    echo $src_files | xargs -n 1 -P $(nproc) clang-format -style=file -i)\n}\n\nfunction test_toolchain_counts {\n    # This is a starting point for a unit test of the devShell.\n    # The choosen S2N_LIBCRYPTO should be 2, and the others should be zero.\n    banner \"Checking the CMAKE_INCLUDE_PATH for libcrypto counts\"\n    echo $CMAKE_INCLUDE_PATH|gawk 'BEGIN{RS=\":\"; o10=0; o11=0; o3=0;awslc=0;libre=0}\n      /openssl-3.0/{o3++}\n      /openssl-1.1/{o11++}\n      /openssl-1.0/{o10++}\n      /aws-lc/{awslc++}\n      /libressl/{libre++}\n      END{print \"\\nOpenssl3:\\t\",o3,\"\\nOpenssl1.1:\\t\",o11,\"\\nOpenssl1.0.2:\\t\",o10,\"\\nAwlc:\\t\\t\",awslc,\"\\nLibreSSL:\\t\", libre}'\n    banner \"Checking tooling counts (these should all be 1)\"\n    echo -e \"\\nOpenssl integ:\\t $(openssl version|grep -c '1.1.1')\"\n    echo -e \"Corretto 17:\\t $(java -version 2>&1|grep -ce 'Runtime.*Corretto-17')\"\n    echo -e \"gnutls-cli:\\t $(gnutls-cli --version |grep -c 'gnutls-cli 3.7')\"\n    echo -e \"gnutls-serv:\\t $(gnutls-serv --version |grep -c 'gnutls-serv 3.7')\"\n    echo -e \"Nix Python:\\t $(which python|grep -c '/nix/store')\"\n    echo -e \"Nix pytest:\\t $(which pytest|grep -c '/nix/store')\"\n    echo -e \"Nix sslyze:\\t $(which sslyze|grep -c '/nix/store')\"\n    echo -e \"python nassl:\\t $(pip freeze|grep -c 'nassl')\"\n}\n\nfunction test_nonstandard_compilation {\n    # Any script that needs to compile s2n in a non-standard way can run here\n    ./codebuild/bin/test_dynamic_load.sh $(mktemp -d)\n}\n\n", "num_lines": 145}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get install python3 \nsudo apt-get install python3-pip\n\npip3 install --user cryptography\npip3 install --user pycryptodome\npip3 install --user pycryptodomex\n\npython3 aes_scram.py\n\n", "num_lines": 12}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Idempotently applies a codemod script to update safety macro calls to include the\n# context in which they're used.\n\nset -e\n\nSCRIPT_DIR=scripts/s2n_safety_explicit_context\n\nif [ ! -d $SCRIPT_DIR/.venv ]; then\n  python3 -m venv $SCRIPT_DIR/.venv\nfi\n\nsource $SCRIPT_DIR/.venv/bin/activate\npip install -r $SCRIPT_DIR/requirements.txt\n\nset -x\n\nfunction join { local IFS=\",\"; echo \"$*\"; }\n\nIGNORES=$(\n    join \\\n        api \\\n        cmake \\\n        codebuild \\\n        coverage \\\n        docker-images \\\n        docs \\\n        error \\\n        lib \\\n        libcrypto-build \\\n        libcrypto-root \\\n        scram \\\n        scripts \\\n        utils/s2n_safety.h \\\n        utils/s2n_safety_macros.h \\\n)\n\nfunction mod {\n  codemod \\\n    --exclude-paths $IGNORES \\\n    --extensions c,h,patch \\\n    \"$1\" \"$2\"\n}\n\nfunction map {\n  mod \"( +)$1 *\\(\" \"\\1$2(\"\n  mod \"^$1 *\\(\" \"$2(\"\n}\n\n# PTR\nmap BAIL_PTR               PTR_BAIL\nmap S2N_ERROR_PTR          PTR_BAIL\nmap ENSURE_PTR             PTR_ENSURE\nmap ENSURE_REF_PTR         PTR_ENSURE_REF\nmap ENSURE_MUT_PTR         PTR_ENSURE_MUT\nmap GUARD_PTR              PTR_GUARD_POSIX\nmap GUARD_POSIX_PTR        PTR_GUARD_POSIX\nmap GUARD_NONNULL_PTR      PTR_GUARD_NONNULL\nmap GUARD_RESULT_PTR       PTR_GUARD_RESULT\nmap notnull_check_ptr      PTR_ENSURE_REF\n\n# POSIX\nmap BAIL_POSIX             POSIX_BAIL\nmap S2N_ERROR              POSIX_BAIL\nmap ENSURE_POSIX           POSIX_ENSURE\nmap ENSURE_POSIX_REF       POSIX_ENSURE_REF\nmap ENSURE_POSIX_MUT       POSIX_ENSURE_MUT\nmap notnull_check          POSIX_ENSURE_REF\nmap PRECONDITION_POSIX     POSIX_PRECONDITION\nmap POSTCONDITION_POSIX    POSIX_POSTCONDITION\nmap GUARD                  POSIX_GUARD\nmap GUARD_NONNULL          POSIX_GUARD_PTR\nmap GUARD_POSIX_NONNULL    POSIX_GUARD_PTR\nmap GUARD_OSSL             POSIX_GUARD_OSSL\nmap GUARD_POSIX_OSSL       POSIX_GUARD_OSSL\nmap GUARD_AS_POSIX         POSIX_GUARD_RESULT\nmap GUARD_POSIX            POSIX_GUARD\nmap GUARD_POSIX_STRICT     POSIX_GUARD_STRICT\nmap gte_check              POSIX_ENSURE_GTE\nmap lte_check              POSIX_ENSURE_LTE\nmap gt_check               POSIX_ENSURE_GT\nmap lt_check               POSIX_ENSURE_LT\nmap eq_check               POSIX_ENSURE_EQ\nmap ne_check               POSIX_ENSURE_NE\nmap inclusive_range_check  POSIX_ENSURE_INCLUSIVE_RANGE\nmap exclusive_range_check  POSIX_ENSURE_EXCLUSIVE_RANGE\nmap memcpy_check           POSIX_CHECKED_MEMCPY\nmap memset_check           POSIX_CHECKED_MEMSET\n\n# GOTO\nmap GUARD_GOTO             GOTO_GUARD_POSIX\nmap GUARD_POSIX_GOTO       GOTO_GUARD_POSIX\nmap GUARD_NONNULL_GOTO     GOTO_GUARD_PTR\nmap GUARD_RESULT_GOTO      GOTO_GUARD_RESULT\n\n# s2n_result\nmap GUARD_RESULT           RESULT_GUARD\nmap GUARD_AS_RESULT        RESULT_GUARD_POSIX\nmap GUARD_RESULT_PTR       RESULT_GUARD_PTR\nmap GUARD_RESULT_OSSL      RESULT_GUARD_OSSL\nmap ENSURE                 RESULT_ENSURE\nmap ENSURE_REF             RESULT_ENSURE_REF\nmap ENSURE_MUT             RESULT_ENSURE_MUT\nmap ENSURE_GTE             RESULT_ENSURE_GTE\nmap ENSURE_LTE             RESULT_ENSURE_LTE\nmap ENSURE_GT              RESULT_ENSURE_GT\nmap ENSURE_LT              RESULT_ENSURE_LT\nmap ENSURE_NE              RESULT_ENSURE_NE\nmap ENSURE_EQ              RESULT_ENSURE_EQ\nmap ENSURE_OK              RESULT_ENSURE_OK\nmap DEBUG_ENSURE           RESULT_DEBUG_ENSURE\nmap BAIL                   RESULT_BAIL\nmap CHECKED_MEMCPY         RESULT_CHECKED_MEMCPY\nmap CHECKED_MEMSET         RESULT_CHECKED_MEMSET\n\n", "num_lines": 117}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -e\n\nusage() {\n    echo \"Usage: calcTotalCov.sh\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"0\" ]; then\n    usage\nfi\n\nif [[ -z \"$S2N_ROOT\" ]]; then\n    S2N_ROOT=../..\nfi\n\nFUZZCOV_SOURCES=\"${S2N_ROOT}/api ${S2N_ROOT}/bin ${S2N_ROOT}/crypto ${S2N_ROOT}/error ${S2N_ROOT}/pq-crypto ${S2N_ROOT}/stuffer ${S2N_ROOT}/tls ${S2N_ROOT}/utils\"\n\n\n# Outputs fuzz coverage results if the FUZZ_COVERAGE environment variable is set\n# Total coverage is overlayed on source code in s2n_cov.html and coverage statistics are available in s2n_cov.txt\n# If using LLVM version 9 or greater, coverage is output in LCOV format instead of HTML\n# All files are stored in the s2n coverage directory\nif [[ \"$FUZZ_COVERAGE\" == \"true\" ]]; then\n\n    printf \"Calculating total s2n coverage... \"\n\n    # The llvm-profdata merge command warns that the profraws were created from different binaries (which is true) but\n    # works fine for what we care about (the s2n library). Therefore, for user clarity all output is suppressed.\n    llvm-profdata merge -sparse ./profiles/*/*.profdata -o ./profiles/s2n_cov.profdata > /dev/null 2>&1\n    llvm-cov report -instr-profile=./profiles/s2n_cov.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} > ${COVERAGE_DIR}/fuzz/s2n_cov.txt\n\n    # Use LCOV format instead of HTML if the LLVM version we're using supports it\n    if [[ $(grep -Eo \"[0-9]*\" <<< `llvm-cov --version` | head -1) > 8 ]]; then\n        llvm-cov export -instr-profile=./profiles/s2n_cov.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} -format=lcov > ${COVERAGE_DIR}/fuzz/s2n_cov.info\n        genhtml -q -o ${COVERAGE_DIR}/html/overall_fuzz_coverage ${COVERAGE_DIR}/fuzz/s2n_cov.info\n    else\n        llvm-cov show -instr-profile=./profiles/s2n_cov.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} -use-color -format=html > ${COVERAGE_DIR}/fuzz/s2n_cov.html\n    fi\n    # Generate coverage report compatible with codecov.io\n    llvm-cov show -instr-profile=./profiles/s2n_cov.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} > ${COVERAGE_DIR}/fuzz/codecov.txt\n\n    S2N_COV=`grep -Eo '[0-9]*\\.[0-9]*\\%' ${COVERAGE_DIR}/fuzz/s2n_cov.txt | tail -1`\n    printf \"total s2n coverage from fuzz tests: %s\\n\" $S2N_COV\nfi\n", "num_lines": 60}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# The timeout command sends a TERM and under normal circumstances returns\n# exit code 124. We'll undo this later. \nset -e\n\nusage() {\n    echo \"Usage: runFuzzTest.sh TEST_NAME FUZZ_TIMEOUT_SEC\"\n    exit 1\n}\n\nif [ \"$#\" -ne \"2\" ]; then\n    usage\nfi\n\nTEST_NAME=$1\nFUZZ_TIMEOUT_SEC=$2\nMIN_TEST_PER_SEC=\"1000\"\nMIN_FEATURES_COVERED=\"100\"\n\n# Failures for negative tests on AFL can be ignored.\nif [[ $TEST_NAME == *_negative_test && \"$AFL_FUZZ\" != \"true\" ]];\nthen\n    EXPECTED_TEST_FAILURE=1\nelse\n    EXPECTED_TEST_FAILURE=0\nfi\n\nASAN_OPTIONS+=\"symbolize=1\"\nLSAN_OPTIONS+=\"log_threads=1\"\nUBSAN_OPTIONS+=\"print_stacktrace=1\"\nNUM_CPU_THREADS=$(nproc)\nLIBFUZZER_ARGS+=\"-timeout=5 -max_len=4096 -print_final_stats=1 -jobs=${NUM_CPU_THREADS} -workers=${NUM_CPU_THREADS} -max_total_time=${FUZZ_TIMEOUT_SEC}\"\n\nTEST_SPECIFIC_OVERRIDES=\"${PWD}/LD_PRELOAD/${TEST_NAME}_overrides.so\"\nGLOBAL_OVERRIDES=\"${PWD}/LD_PRELOAD/global_overrides.so\"\n\nFUZZCOV_SOURCES=\"${S2N_ROOT}/api ${S2N_ROOT}/bin ${S2N_ROOT}/crypto ${S2N_ROOT}/error ${S2N_ROOT}/pq-crypto ${S2N_ROOT}/stuffer ${S2N_ROOT}/tls ${S2N_ROOT}/utils\"\n\nif [ -e $TEST_SPECIFIC_OVERRIDES ];\nthen\n    export LD_PRELOAD=\"$TEST_SPECIFIC_OVERRIDES $GLOBAL_OVERRIDES\"\nelse\n    export LD_PRELOAD=\"$GLOBAL_OVERRIDES\"\nfi\n\nFIPS_TEST_MSG=\"\"\nif [ -n \"${S2N_TEST_IN_FIPS_MODE}\" ];\nthen\n    FIPS_TEST_MSG=\" FIPS test\"\nfi\n\nif [ ! -d \"./corpus/${TEST_NAME}\" ];\nthen\n  printf \"\\033[33;1mWARNING!\\033[0m ./corpus/${TEST_NAME} directory does not exist, feature coverage may be below minimum.\\n\\n\"\nfi\n\n# Make directory if it doesn't exist\nmkdir -p \"./corpus/${TEST_NAME}\"\n\nACTUAL_TEST_FAILURE=0\n\n# Copy existing Corpus to a temp directory so that new inputs from fuzz tests runs will add new inputs to the temp directory.\n# This allows us to minimize new inputs before merging to the original corpus directory.\nTEMP_CORPUS_DIR=\"$(mktemp -d)\"\ncp -r ./corpus/${TEST_NAME}/. \"${TEMP_CORPUS_DIR}\"\n\n# Run AFL instead of libfuzzer if AFL_FUZZ is set. Not compatible with fuzz coverage.\nif [[ ${AFL_FUZZ} == \"true\" && ${FUZZ_COVERAGE} != \"true\" ]]; then\n    unset LD_PRELOAD\n    # See https://aflplus.plus/docs/env_variables/\n    export AFL_NO_UI=true\n    export AFL_HARDEN=true\n    printf \"Running AFL %-s %-40s for %5d sec... \" \"${FIPS_TEST_MSG}\" ${TEST_NAME} ${FUZZ_TIMEOUT_SEC}\n    mkdir -p results/${TEST_NAME}\n    set +e\n    timeout ${FUZZ_TIMEOUT_SEC} ${LIBFUZZER_INSTALL_DIR}/afl-fuzz -i corpus/${TEST_NAME} -o results/${TEST_NAME} -m none ./${TEST_NAME}  2>&1> ./results/${TEST_NAME}/console_output.log\n    returncode=$?\n    # See the timeout man page for specifics\n    if [[ ${returncode} -ne 124 ]]; then\n        printf \"\\033[33;1mWARNING!\\033[0m AFL exited with an unexpected return value: %8d\" ${returncode}\n    fi\n    set -e\n    CRASH_COUNT=$(sed -n -e 's/^unique_crashes *: //p' ./results/${TEST_NAME}/fuzzer_stats)\n    TEST_COUNT=$(sed -n -e 's/^execs_done *: //p' ./results/${TEST_NAME}/fuzzer_stats)\n    FLOAT_TESTS_PER_SEC=$(sed -n -e 's/^execs_per_sec *: //p' ./results/${TEST_NAME}/fuzzer_stats)\n    TESTS_PER_SEC=$(echo \"($FLOAT_TESTS_PER_SEC+.5)/1\"|bc)\n\n    if [[ ${TESTS_PER_SEC} -lt 10 ]]; then\n        printf \"\\033[33;1mWARNING!\\033[0m %10d tests, only %6d tests per second; test is too slow.\\n\" ${TEST_COUNT} ${TESTS_PER_SEC}\n    fi\n    if [[ ${CRASH_COUNT} -gt 0 ]]; then\n        ACTUAL_TEST_FAILURE=1\n    fi\n    if [[ ${ACTUAL_TEST_FAILURE} == ${EXPECTED_TEST_FAILURE} ]]; then\n        printf \"\\033[32;1mPASSED\\033[0m %8d tests, %.1f test/sec\\n\" ${TEST_COUNT} ${TESTS_PER_SEC}\n        exit 0\n    else\n        printf \"\\033[31;1mFAILED\\033[0m %10d tests, %6d unique crashes\\n\" ${TEST_COUNT} ${CRASH_COUNT}\n        exit -1\n    fi\nelse\n    printf \"Running %-s %-40s for %5d sec with %2d threads... \" \"${FIPS_TEST_MSG}\" ${TEST_NAME} ${FUZZ_TIMEOUT_SEC} ${NUM_CPU_THREADS}\nfi\n\n# Setup and clean profile structure if FUZZ_COVERAGE is enabled, otherwise run as normal\nif [[ \"$FUZZ_COVERAGE\" == \"true\" ]]; then\n    mkdir -p \"./profiles/${TEST_NAME}\"\n    rm -f ./profiles/${TEST_NAME}/*.profraw\n    LLVM_PROFILE_FILE=\"./profiles/${TEST_NAME}/${TEST_NAME}.%p.profraw\" ./${TEST_NAME} ${LIBFUZZER_ARGS} ${TEMP_CORPUS_DIR} > ${TEST_NAME}_output.txt 2>&1 || ACTUAL_TEST_FAILURE=1\nelse\n    ./${TEST_NAME} ${LIBFUZZER_ARGS} ${TEMP_CORPUS_DIR} > ${TEST_NAME}_output.txt 2>&1 || ACTUAL_TEST_FAILURE=1\nfi\n\nTEST_INFO=$(\n    grep -o \"stat::number_of_executed_units: [0-9]*\" ${TEST_NAME}_output.txt | \\\n    awk -v timeout=$FUZZ_TIMEOUT_SEC '{count += int($2); rate = int(count / timeout)} END {print count, \"tests, \" rate \" test/sec\"}' \\\n)\nTESTS_PER_SEC=$(echo \"$TEST_INFO\" | cut -d ' ' -f 3)\nFEATURE_COVERAGE=`grep -o \"ft: [0-9]*\" ${TEST_NAME}_output.txt | awk '{print $2}' | sort | tail -1`\nTARGET_FUNCS=''\ndeclare -i TARGET_TOTAL=0\ndeclare -i TARGET_COV=0\n\n# Outputs fuzz coverage results if the FUZZ_COVERAGE environment variable is set\n# Coverage is overlayed on source code in ${TEST_NAME}_cov.html, and coverage statistics are available in ${TEST_NAME}_cov.txt\n# If using LLVM version 9 or greater, coverage is output in LCOV format instead of HTML\n# All files are stored in the s2n coverage directory\nif [[ \"$FUZZ_COVERAGE\" == \"true\" ]]; then\n    mkdir -p ${COVERAGE_DIR}/fuzz\n    llvm-profdata merge -sparse ./profiles/${TEST_NAME}/*.profraw -o ./profiles/${TEST_NAME}/${TEST_NAME}.profdata\n    llvm-cov report -instr-profile=./profiles/${TEST_NAME}/${TEST_NAME}.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} -show-functions > ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.txt\n\n    # Use LCOV format instead of HTML if the LLVM version we're using supports it\n    if [[ $(grep -Eo \"[0-9]*\" <<< `llvm-cov --version` | head -1) -gt 8 ]]; then\n        llvm-cov export -instr-profile=./profiles/${TEST_NAME}/${TEST_NAME}.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} -format=lcov > ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.info\n        genhtml -q -o ${COVERAGE_DIR}/html/${TEST_NAME} ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.info\n    else\n        llvm-cov show -instr-profile=./profiles/${TEST_NAME}/${TEST_NAME}.profdata ${S2N_ROOT}/lib/libs2n.so ${FUZZCOV_SOURCES} -use-color -format=html > ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.html\n    fi\n\n    # Extract target functions from test source\n    TARGET_FUNCS=`grep -Pzo \"(?<=/\\* Target Functions: )[\\w\\s]*\" ${TEST_NAME}.c | tr -d \"\\0\"`\n\n    # Find line coverage statistics for target functions\n    if [[ ! -z \"$TARGET_FUNCS\" ]];\n    then\n        for TARGET in ${TARGET_FUNCS}\n        do\n            TARGET_TOTAL+=`sed -n \"s/^.*${TARGET} .*% *\\([0-9]*\\) .*$/\\1/p\" ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.txt`\n            TARGET_COV+=`sed -n \"s/^.*${TARGET} .*% *[0-9]* *\\([0-9]*\\) .*$/\\1/p\" ${COVERAGE_DIR}/fuzz/${TEST_NAME}_cov.txt`\n        done\n    fi\nfi\n\nif [ $ACTUAL_TEST_FAILURE == $EXPECTED_TEST_FAILURE ];\nthen\n    printf \"\\033[32;1mPASSED\\033[0m %s\" \"$TEST_INFO\"\n\n    # Output target function coverage percentage if target functions are defined and fuzzing coverage is enabled\n    # Otherwise, print number of features covered\n    if [[ \"$FUZZ_COVERAGE\" == \"true\" && ! -z \"$TARGET_FUNCS\" && \"$EXPECTED_TEST_FAILURE\" != 1 && \"$TARGET_TOTAL\" != 0 ]];\n    then\n        printf \", %6.2f%% target coverage\" \"$(( 10000 * ($TARGET_TOTAL - $TARGET_COV) / $TARGET_TOTAL ))e-2\"\n    else\n        printf \", %5d features covered\" $FEATURE_COVERAGE\n    fi\n\n    if [ $EXPECTED_TEST_FAILURE == 1 ];\n    then\n        # Clean up LibFuzzer corpus files if the test is negative.\n        printf \"\\n\"\n        rm -f leak-* crash-*\n    else\n        # TEMP_CORPUS_DIR may contain many new inputs that only covers a small set of new branches. \n        # Instead of copying all new inputs to the corpus directory,  only copy back minimum number of new inputs that reach new branches.\n        ./${TEST_NAME} -merge=1 \"./corpus/${TEST_NAME}\" \"${TEMP_CORPUS_DIR}\" > ${TEST_NAME}_results.txt 2>&1\n\n        # Print number of new files and branches found in new Inputs (if any)\n        RESULTS=`grep -Eo \"[0-9]+ new files .*$\" ${TEST_NAME}_results.txt | tail -1`\n        printf \", ${RESULTS}\\n\"\n\n        if [ \"$TESTS_PER_SEC\" -lt $MIN_TEST_PER_SEC ]; then\n            printf \"\\033[33;1mWARNING!\\033[0m ${TEST_NAME} is only ${TESTS_PER_SEC} tests/sec, which is below ${MIN_TEST_PER_SEC}/sec! Fuzz tests are more effective at higher rates.\\n\\n\"\n        fi\n\n        if [ \"$FEATURE_COVERAGE\" -lt $MIN_FEATURES_COVERED ]; then\n            printf \"\\033[31;1mERROR!\\033[0m ${TEST_NAME} only covers ${FEATURE_COVERAGE} features, which is below ${MIN_FEATURES_COVERED}! This may be due to missing corpus files or a bug.\\n\"\n            exit -1;\n        fi\n    fi\n\nelse\n    cat ${TEST_NAME}_output.txt\n    printf \"\\033[31;1mFAILED\\033[0m %s, %6d features covered\\n\" \"$TEST_INFO\" $FEATURE_COVERAGE\n    exit -1\nfi\n", "num_lines": 211}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\n\nusage() {\n    echo \"gen_self_signed_cert.sh [OPTION]\n\nOptions:\n--user-type Server or client depending on intended usage of the cert\n--hash-alg The type of hash algorithm to use to sign the cert in openssl format, ex; sha256\n--dns A DNS type subject alternative name to add to the cert. Can be repeated.\n--ip An IP type subject alternative name to add to the cert. Can be repeated.\n--uri A URI type subject alternative name to add to the cert. Can be repeated.\n--cn  The CN to add to the cert\n--key-type The type of key for the generated certificate to have. Either rsa or ecdsa.\n--rsa-key-size Size of rsa key for generated certificate.\n--curve-name name of the ECC curve to use for the generated ECDSA certificate.\n--prefix Prefix for the output certificate and private key file name. Defaults to the CN value.\n\"\n    exit 0;\n}\n\nGETOPT=\"getopt\"\n\n# use gnu-getopt on macos\nif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n    GETOPT=\"/usr/local/opt/gnu-getopt/bin/getopt\"\n\n    if ! [ -x \"$(command -v $GETOPT)\" ]; then\n      echo 'Error: getopt is not installed. Install with `brew install gnu-getopt`' >&2\n      exit 1\n    fi\nfi\n\n# This only works with gnu getopt.\nPARSED_OPTS=`$GETOPT -o vdn: --long help,user-type:,rsa-key-size:,curve-name:,hash-alg:,ip:,uri:,dns:,cn:,key-type:,prefix: -n 'parse-options' -- \"$@\"`\neval set -- \"$PARSED_OPTS\"\n\nUSER_TYPE=\"server\"\nKEY_TYPE=\"rsa\"\nRSA_KEY_SIZE=\"2048\"\nCURVE_NAME=\"prime256v1\"\nHASH_ALG=\"sha256\"\nSANS=\nCN=\"s2nTestCert\"\nPREFIX=\n\nwhile true; do\n  case \"$1\" in\n    --help ) usage ;;\n    --cn ) CN=\"$2\" ; shift 2 ;;\n    --dns ) SANS=\"$SANS\"\"DNS:$2,\"  ; shift 2 ;;\n    --ip ) SANS=\"$SANS\"\"IP:$2,\"  ; shift 2 ;;\n    --uri ) SANS=\"$SANS\"\"URI:$2,\"  ; shift 2 ;;\n    --hash-alg )    HASH_ALG=\"$2\" ; shift 2 ;;\n    --key-type ) KEY_TYPE=\"$2\" ; shift 2 ;;\n    --rsa-key-size ) RSA_KEY_SIZE=\"$2\" ; shift 2 ;;\n    --curve-name ) CURVE_NAME=\"$2\" ; shift 2 ;;\n    --user-type ) USER_TYPE=\"$2\" ; shift 2 ;;\n    --prefix ) PREFIX=\"$2\" ; shift 2 ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\n# Trim the railing comma, openssl x509 config expects the last SAN value to have no comma.\nSANS=`echo $SANS | sed 's/,*$//g'`\nif [ -z \"$PREFIX\" ]; then\n    PREFIX=$CN\nfi\n\n# Picked up by cert_config.cfg. It might have been simpler to just generate all certs with both\n# serverAuth and clientAuth KeyUsage.\nKEY_USAGE=\nif [ \"$USER_TYPE\" == \"server\" ]\nthen\n    KEY_USAGE=\"serverAuth\";\nelif [ \"$USER_TYPE\" == \"client\" ]\nthen\n    KEY_USAGE=\"clientAuth\";\nelif [ \"$USER_TYPE\" == \"both\" ]\nthen\n    KEY_USAGE=\"serverAuth, clientAuth\";\nelse\n    echo \"Incorrect user-type: $USER_TYPE\" \n    usage ;\nfi\n\nconfig=\"\"\"\n[req]\ndistinguished_name = req_distinguished_name\nx509_extensions = v3_req\nprompt = no\n[req_distinguished_name]\nC = US\nST = WA\nL = Seattle\nO = Amazon\nOU = s2n\n\"\"\"\n\nif [[ ! -z \"$CN\" ]]; then\n    config+=\"CN = $CN\"\nfi\n\nconfig+=\"\"\"\n\n[v3_req]\nkeyUsage = keyEncipherment, dataEncipherment, digitalSignature\nextendedKeyUsage = $KEY_USAGE\n\"\"\"\n\nif [[ ! -z \"$SANS\" ]]; then\n    config+=\"subjectAltName = $SANS\"\nfi\n\ncert_conf_path=$(mktemp)\necho \"$config\" > $cert_conf_path\n\n# append an underscore if there's a prefix\nif [[ ! -z \"$PREFIX\" ]]; then\n  PREFIX=\"${PREFIX}_\"\nfi\n\nif [ \"$KEY_TYPE\" == \"rsa\" ]; then\n    openssl req -x509 -config \"$cert_conf_path\" -newkey rsa:${RSA_KEY_SIZE} -${HASH_ALG} -nodes -keyout ${PREFIX}rsa_key.pem -out ${PREFIX}rsa_cert.pem -days 36500\nelif [ \"$KEY_TYPE\" == \"ecdsa\" ]; then\n    openssl ecparam -out \"${PREFIX}ecdsa_key.pem\" -name \"$CURVE_NAME\" -genkey\n    openssl req -new -config \"$cert_conf_path\" -days 36500 -nodes -x509 -key \"${PREFIX}ecdsa_key.pem\" -out \"${PREFIX}ecdsa_cert.pem\"\nelse\n    echo \"Incorrect key-type: $KEY_TYPE\"\n    usage ;\nfi\n\nrm $cert_conf_path\n\n", "num_lines": 150}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\ninstall_dir=\"$(pwd)\"\nopenssl_conf_path=\"$(pwd)/openssl.conf\"\n\nget_subj() {\n  common_name=\"$1\"\n  echo \"/C=US/ST=Massachusetts/L=Boston/O=Amazon/OU=s2n/CN=${common_name}\"\n}\n\ninit_ca_dir() {\n  ca_dir=\"$1\"\n  mkdir -p \"${ca_dir}\"\n  touch \"${ca_dir}/index.txt\"\n  echo 01 > \"${ca_dir}/serial\"\n  echo 01 > \"${ca_dir}/crlnumber\"\n}\n\ngenerate_key_cert() {\n  path=\"$1\"\n  type=\"$2\"\n\n  common_name=$(basename \"${path}\")\n  out=\"csr.pem\"\n  opts=()\n\n  case \"${type}\" in\n    ca)\n      opts=(\"-x509\" \"-days\" \"36500\" \"-extensions\" \"v3_ca\")\n      out=\"cert.pem\"\n      ;;\n    intermediate)\n      ;;\n    leaf)\n      # Common name must be localhost for s2n-tls default verify host callback\n      common_name=\"localhost\"\n      ;;\n    *)\n      echo \"invalid type\"\n      exit\n  esac\n\n  pushd \"${path}\" || exit\n\n  openssl genrsa -out key.pem 4096 || exit\n  chmod 400 key.pem\n\n  ca_dir=\".\" \\\n  openssl req -config \"${openssl_conf_path}\" \\\n      -key key.pem \\\n      -new -sha256 \\\n      \"${opts[@]}\" \\\n      -out \"${out}\" \\\n      -subj \"$(get_subj ${common_name})\" \\\n      || exit\n\n  # Create a chain with just the root certificate for validating child certificates\n  if [ \"${type}\" = \"ca\" ]; then\n    cp cert.pem chain.pem\n  fi\n\n  popd || exit\n}\n\nverify_cert() {\n  ca_file_path=\"$1\"\n  cert_file_path=\"$2\"\n  crl_file_path=\"$3\"\n\n  opts=()\n  if [ -n \"${crl_file_path}\" ]; then\n      is_revoked=$4\n      if [ -z \"${is_revoked}\" ]; then\n        exit\n      fi\n\n      opts=(\"-CRLfile\" \"${crl_file_path}\" \"-crl_check\")\n  fi\n\n  verify_stderr=$(\n    openssl verify \\\n        -CAfile \"${ca_file_path}\" \\\n        \"${opts[@]}\" \\\n        \"${cert_file_path}\" \\\n        2>&1\n  )\n  verify_ret=$?\n\n  if [ -n \"${crl_file_path}\" ] && [ ${is_revoked} -eq 1 ]; then\n    # Ensure openssl verify failed due to certificate revocation\n    if ! [[ \"${verify_stderr}\" =~ .*\"certificate revoked\".* ]]; then\n      exit\n    fi\n  else\n    # Ensure openssl verify succeeded\n    if [ ${verify_ret} -ne 0 ]; then\n      exit\n    fi\n  fi\n}\n\nsign_cert() {\n  signer_path=\"$1\"\n  to_sign_path=\"$2\"\n  signer_type=\"$3\"\n\n  opts=()\n  case \"${signer_type}\" in\n    ca)\n      opts=(\"-extensions\" \"v3_intermediate_ca\")\n      ;;\n    intermediate)\n      opts=(\"-extensions\" \"usr_cert\")\n      ;;\n    *)\n      echo \"invalid type\"\n      exit\n  esac\n\n  ca_dir=\"${signer_path}\" \\\n  openssl ca -config \"${openssl_conf_path}\" -batch \\\n      -days 36500 -notext -md sha256 \\\n      \"${opts[@]}\" \\\n      -in \"${to_sign_path}/csr.pem\" \\\n      -out \"${to_sign_path}/cert.pem\" \\\n      || exit\n\n  # Ensure openssl can validate the signed certificate\n  verify_cert \"${signer_path}/chain.pem\" \"${to_sign_path}/cert.pem\"\n\n  # Create a chain that includes the newly signed certificate and all parent certificates\n  # for validating future child certificates\n  if [ \"${signer_type}\" = \"ca\" ]; then\n    cat \"${to_sign_path}/cert.pem\" \"${signer_path}/chain.pem\" > \"${to_sign_path}/chain.pem\"\n  fi\n}\n\ngenerate_crl() {\n  path=\"$1\"\n\n  pushd \"${path}\" || exit\n  ca_dir=\".\" \\\n  openssl ca -config \"${openssl_conf_path}\" -gencrl \\\n    -out crl.pem \\\n      || exit\n  popd || exit\n}\n\nrevoke_cert() {\n  ca_path=\"$1\"\n  cert_path=\"$2\"\n\n  ca_dir=\"${ca_path}\" \\\n  openssl ca -config \"${openssl_conf_path}\" \\\n      -revoke \"${cert_path}/cert.pem\" \\\n      || exit\n  generate_crl \"${ca_path}\"\n}\n\nbase_dir=$(mktemp -d)\npushd \"${base_dir}\" || exit\n\n#\n# Generate certificate chains of valid and revoked certificates with 1 intermediate CA.\n#\n# root -> valid intermediate   -> valid leaf\n#                              -> revoked leaf\n#      -> revoked intermediate -> valid leaf\n#                              -> revoked leaf\n#\n\n# Generate root certificate\ninit_ca_dir root\ngenerate_key_cert root ca\n\n# Generate intermediate certificates\ninit_ca_dir root/intermediate\ngenerate_key_cert root/intermediate intermediate\nsign_cert root root/intermediate ca\n\ninit_ca_dir root/intermediate_revoked\ngenerate_key_cert root/intermediate_revoked intermediate\nsign_cert root root/intermediate_revoked ca\n\n# Generate leaf certificates\nmkdir root/intermediate/leaf\ngenerate_key_cert root/intermediate/leaf leaf\nsign_cert root/intermediate root/intermediate/leaf intermediate\n\nmkdir root/intermediate/leaf_revoked\ngenerate_key_cert root/intermediate/leaf_revoked leaf\nsign_cert root/intermediate root/intermediate/leaf_revoked intermediate\n\nmkdir root/intermediate_revoked/leaf\ngenerate_key_cert root/intermediate_revoked/leaf leaf\nsign_cert root/intermediate_revoked root/intermediate_revoked/leaf intermediate\n\nmkdir root/intermediate_revoked/leaf_revoked\ngenerate_key_cert root/intermediate_revoked/leaf_revoked leaf\nsign_cert root/intermediate_revoked root/intermediate_revoked/leaf_revoked intermediate\n\n# Generate CRLs and revoke the revoked certificates\ngenerate_crl root\nrevoke_cert root root/intermediate_revoked\n\ngenerate_crl root/intermediate\nrevoke_cert root/intermediate root/intermediate/leaf_revoked\n\ngenerate_crl root/intermediate_revoked\nrevoke_cert root/intermediate_revoked root/intermediate/leaf_revoked\n\n# Ensure openssl verify reads generated CRLs and properly rejects certificates\nverify_cert root/chain.pem root/intermediate/cert.pem root/crl.pem 0\nverify_cert root/chain.pem root/intermediate_revoked/cert.pem root/crl.pem 1\n\nverify_cert root/intermediate/chain.pem root/intermediate/leaf/cert.pem root/intermediate/crl.pem 0\nverify_cert root/intermediate/chain.pem root/intermediate/leaf_revoked/cert.pem root/intermediate/crl.pem 1\n\nverify_cert root/intermediate_revoked/chain.pem root/intermediate_revoked/leaf/cert.pem root/intermediate_revoked/crl.pem 0\nverify_cert root/intermediate_revoked/chain.pem root/intermediate_revoked/leaf_revoked/cert.pem root/intermediate_revoked/crl.pem 1\n\n# Generate CRLs with invalid timestamps. Requires Openssl 3.0.\nca_dir=\"root/intermediate\" \\\nopenssl ca -config \"${openssl_conf_path}\" -gencrl \\\n    -crl_lastupdate 21220101000000Z \\\n    -out \"${install_dir}/intermediate_invalid_this_update_crl.pem\" \\\n    || exit\n\nca_dir=\"root/intermediate\" \\\nopenssl ca -config \"${openssl_conf_path}\" -gencrl \\\n    -crl_nextupdate 500101000000Z \\\n    -out \"${install_dir}/intermediate_invalid_next_update_crl.pem\" \\\n    || exit\n\n#\n# Create certificate chain pems and copy CRLs and keys\n#\n\ncp root/cert.pem \"${install_dir}/root_cert.pem\"\n\ncat root/intermediate/leaf/cert.pem \\\n    root/intermediate/cert.pem \\\n    > \"${install_dir}/none_revoked_cert_chain.pem\"\ncp root/intermediate/leaf/key.pem \"${install_dir}/none_revoked_key.pem\"\n\ncat root/intermediate/leaf_revoked/cert.pem \\\n    root/intermediate/cert.pem \\\n    > \"${install_dir}/leaf_revoked_cert_chain.pem\"\ncp root/intermediate/leaf_revoked/key.pem \"${install_dir}/leaf_revoked_key.pem\"\n\ncat root/intermediate_revoked/leaf/cert.pem \\\n    root/intermediate_revoked/cert.pem \\\n    > \"${install_dir}/intermediate_revoked_cert_chain.pem\"\ncp root/intermediate_revoked/leaf/key.pem \"${install_dir}/intermediate_revoked_key.pem\"\n\ncat root/intermediate_revoked/leaf_revoked/cert.pem \\\n    root/intermediate_revoked/cert.pem \\\n    > \"${install_dir}/all_revoked_cert_chain.pem\"\ncp root/intermediate_revoked/leaf_revoked/key.pem \"${install_dir}/all_revoked_key.pem\"\n\ncp root/crl.pem \"${install_dir}/root_crl.pem\"\ncp root/intermediate/crl.pem \"${install_dir}/intermediate_crl.pem\"\ncp root/intermediate_revoked/crl.pem \"${install_dir}/intermediate_revoked_crl.pem\"\n\npopd || exit\n\n# Cleanup\nrm -rf \"${base_dir}\"\n\n# Ensure that s2nc accepts all generated certificates\n./test_s2nc.sh || exit\n\necho \"Generation successful.\"\n", "num_lines": 287}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n# Ensure that s2nc accepts all generated certificates\n\ns2nc_path=\"../../../bin/s2nc\"\ns2nd_path=\"../../../bin/s2nd\"\n\ncert_chains=(\"none_revoked\" \"leaf_revoked\" \"intermediate_revoked\" \"all_revoked\")\n\nfor cert_chain in \"${cert_chains[@]}\"; do\n  \"${s2nd_path}\" \\\n      --self-service-blinding \\\n      --negotiate \\\n      --cert \"${cert_chain}_cert_chain.pem\" \\\n      --key \"${cert_chain}_key.pem\" \\\n      localhost 8888 &\n  s2nd_pid=$!\n\n  \"${s2nc_path}\" \\\n      --ca-file \"root_cert.pem\" \\\n      localhost 8888\n  s2nc_success=$?\n\n  kill ${s2nd_pid}\n\n  if [ ${s2nc_success} -ne 0 ]; then\n    exit 1\n  fi\ndone\n", "num_lines": 43}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n\n# immediately bail if any command fails\nset -e\n\n# This script assumes the existence of\n# ca_key.pem\n# ca_cert.pem\n# server_key.pem - the private key for early expiry cert being generated\n# config/ca.cnf\n# config/server_early_expiry.cnf\n\necho \"generating serial file\"\ntouch config/serial\n# the openssl ca command will read this file to figure out the serial number,\n# increment it for each certificate that is signed. This is the serial number in\n# hex notation.\necho \"1024\" > config/serial\n\necho \"generating server early expiry CSR\"\nopenssl req  -new -nodes -key server_key.pem -out server_early_expire.csr -config config/server_early_expire.cnf\n\necho \"creating empty CA database\"\n# it's mandatory for this to exist, although it is initially empty\n# this data base will be updated during the ca command\ntouch certs_early_expire_index.txt\n\necho \"generating server certificate and signing it\"\n# this directory holds the duplicate certs that the CA command generates\n# https://security.stackexchange.com/questions/111448/how-to-avoid-writing-pem-while-signing-a-csr\nmkdir -p to_nuke\n\n# use the \"batch\" option to disable prompting\n# the enddate argument is in YYYYMMDDHHMMSS format\n# use the \"notext\" option because s2n can't parse .pem certificates with the\n# text information inside of them\nopenssl ca -batch \\\n    -in server_early_expire.csr  \\\n    -out server_cert_early_expire.pem \\\n    -config config/ca.cnf \\\n    -outdir to_nuke \\\n    -enddate 20370101010101Z \\\n    -extfile config/server_early_expire.cnf \\\n    -extensions req_ext \\\n    -notext\n\necho \"verifying generated certificates\"\nopenssl verify -CAfile ca_cert.pem server_cert_early_expire.pem\n\necho \"generating ocsp response\"\n# This is the target next_update date for the OCSP response. This date needs to\n# be before 2038 so that next_update field can be tested on 32 bit platforms.\ntarget_date=\"2036-01-01\"\ncurrent_date=$(date +%Y-%m-%d)\nexpiration_days=$(( ($(date -d \"$target_date\" +%s) - $(date -d \"$current_date\" +%s)) / 86400 ))\n\n# The & launches the server in the background\nopenssl ocsp -port 8889 -text -CA ca_cert.pem \\\n      -index certs_early_expire_index.txt \\\n      -rkey ocsp_key.pem \\\n      -rsigner ocsp_cert.pem \\\n      -nrequest 1 \\\n      -ndays $expiration_days \\\n      &\n\nopenssl ocsp -CAfile ca_cert.pem \\\n      -url http://127.0.0.1:8889 \\\n      -issuer ca_cert.pem \\\n      -verify_other ocsp_cert.pem \\\n      -cert server_cert_early_expire.pem -respout ocsp_response_early_expire.der\n\necho \"removing temporary files\"\nrm server_early_expire.csr\n# openssl generates <file>, <file>.attr, <file>.old, and <file>.attr.old\n# delete all of them\nrm certs_early_expire_index* -f\nrm to_nuke -rf\nrm config/serial\nrm config/serial.old\n\n", "num_lines": 93}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -eu\n\ncd $(dirname $0)\n\n../gen_self_signed_cert.sh --cn '' --prefix 'without_cn'\n../gen_self_signed_cert.sh --ip '::1' --prefix 'ip_v6_lo'\n\n", "num_lines": 23}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r stuffer\nrm -r tls\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\n\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp stubs/s2n_hash.c crypto/\ncp stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp $S2N_BASE/tls/s2n_cbc.c tls/\npatch -p5 < ../patches/cbc.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\npatch -p1 < ../patches/safety.patch\n\ncp ../stubs/s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\n", "num_lines": 51}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r tls\nrm -r stuffer\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp ../stubs/s2n_hash.c crypto/\ncp ../stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p stuffer\ncp $S2N_BASE/stuffer/s2n_stuffer.c stuffer/\ncp $S2N_BASE/stuffer/s2n_stuffer_network_order.c stuffer/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp $S2N_BASE/tls/s2n_aead.c tls/\ncp $S2N_BASE/tls/s2n_cbc.c tls/\ncp $S2N_BASE/tls/s2n_record_read_aead.c tls/\npatch -p5 < ../patches/cbc.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_blob.c utils/\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_result.h utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\ncp $S2N_BASE/utils/s2n_safety.h utils/\npatch -p1 < ../patches/safety.patch\n\ncp s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\ncp ../stubs/s2n_mem.c utils/\n", "num_lines": 60}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r tls\nrm -r stuffer\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\n\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp ../stubs/s2n_hash.c crypto/\ncp ../stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p stuffer\ncp $S2N_BASE/stuffer/s2n_stuffer.c stuffer/\ncp $S2N_BASE/stuffer/s2n_stuffer_network_order.c stuffer/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp stubs/s2n_cbc.c tls/\ncp $S2N_BASE/tls/s2n_record_read_cbc.c tls/\npatch -p1 < record_read_cbc.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\npatch -p1 < ../patches/safety.patch\n\ncp ../stubs/s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\ncp ../stubs/s2n_mem.c utils/\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r tls\nrm -r stuffer\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\n\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp ../stubs/s2n_hash.c crypto/\ncp ../stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p stuffer\ncp $S2N_BASE/stuffer/s2n_stuffer.c stuffer/\ncp $S2N_BASE/stuffer/s2n_stuffer_network_order.c stuffer/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp stubs/s2n_cbc.c tls/\ncp $S2N_BASE/tls/s2n_record_read_cbc.c tls/\npatch -p1 < record_read_cbc.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\npatch -p1 < ../patches/safety.patch\n\ncp ../stubs/s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\ncp ../stubs/s2n_mem.c utils/\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r tls\nrm -r stuffer\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\n\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp ../stubs/s2n_hash.c crypto/\ncp ../stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p stuffer\ncp $S2N_BASE/stuffer/s2n_stuffer.c stuffer/\ncp $S2N_BASE/stuffer/s2n_stuffer_network_order.c stuffer/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp $S2N_BASE/tls/s2n_cbc.c tls/\ncp $S2N_BASE/tls/s2n_record_read_composite.c tls/\npatch -p5 < ../patches/cbc.patch\npatch -p1 < record_read.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\npatch -p1 < ../patches/safety.patch\n\ncp ../stubs/s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\ncp ../stubs/s2n_mem.c utils/\n", "num_lines": 58}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nmake clean\nrm -r crypto\nrm -r error\nrm -r tls\nrm -r stuffer\nrm -r utils\n", "num_lines": 22}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\nset -x\nset -e\n\nBASEDIR=$(pwd)\necho $BASEDIR\nS2N_BASE=\"$BASEDIR/../../../..\"\necho $S2N_BASE\n\ncd $BASEDIR\nmkdir -p crypto\n#The hmac should be based off the old hmac, so just apply the patches to add the invarients\ncp $S2N_BASE/crypto/s2n_hmac.c crypto/\ncp $S2N_BASE/crypto/s2n_hmac.h crypto/\npatch -p5 < ../patches/hmac.patch\n\n#the hash uses my stubs for now, so replace the file\ncp ../stubs/s2n_hash.c crypto/\ncp ../stubs/s2n_hash.h crypto/\n\nmkdir -p error\ncp ../stubs/s2n_errno.c error/\n\nmkdir -p stuffer\ncp $S2N_BASE/stuffer/s2n_stuffer.c stuffer/\ncp $S2N_BASE/stuffer/s2n_stuffer_network_order.c stuffer/\n\nmkdir -p tls\n#add invariants etc needed for the proof to the s2n_cbc code\ncp $S2N_BASE/tls/s2n_cbc.c tls/\ncp $S2N_BASE/tls/s2n_record_read_stream.c tls/\npatch -p5 < ../patches/cbc.patch\n\nmkdir -p utils\ncp $S2N_BASE/utils/s2n_result.c utils/\ncp $S2N_BASE/utils/s2n_safety.c utils/\npatch -p1 < ../patches/safety.patch\n\ncp ../stubs/s2n_annotations.h utils/\ncp ../stubs/s2n_ensure.h utils/\ncp ../stubs/s2n_ensure.c utils/\ncp ../stubs/s2n_mem.c utils/\n", "num_lines": 57}
{"repo_name": "s2n-tls", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\").\n# You may not use this file except in compliance with the License.\n# A copy of the License is located at\n#\n#  http://aws.amazon.com/apache2.0\n#\n# or in the \"license\" file accompanying this file. This file is distributed\n# on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n# express or implied. See the License for the specific language governing\n# permissions and limitations under the License.\n#\n\n\n./copy_as_needed.sh\nmake clean\ntime make\n", "num_lines": 20}
{"repo_name": "sagemaker-chainer-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsed -ie \"s/PLACEHOLDER_HOSTNAME/$1/g\" changehostname.c\n\ngcc -o changehostname.o -c -fPIC -Wall changehostname.c\ngcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n", "num_lines": 7}
{"repo_name": "sagemaker-containers", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License'). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the 'license' file accompanying this file. This file is\n# distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -ex\npython script.py\n", "num_lines": 17}
{"repo_name": "sagemaker-distribution", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# We need to checkout the version of boto3 that is installed in the mamba environment.\n\nboto3_version=$(micromamba list | grep boto3 | tr -s ' ' | cut -d ' ' -f 3)\n# Checkout the corresponding boto3 version\ngit checkout tags/$boto3_version\n\n# Run the unit and functional tests\npytest tests/unit tests/functional || exit $?\n", "num_lines": 11}
{"repo_name": "sagemaker-distribution", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Ref: https://keras.io/guides/, https://github.com/keras-team/keras-io/tree/master\n\nfor file in *.py; do\n    if [ \"$file\" != \"transfer_learning.py\" ]; then\n        # skipping transfer_learning.py because it has 20 epochs and it takes a very long time to execute\n        # https://github.com/keras-team/keras-io/blob/master/guides/transfer_learning.py#L562\n        python \"$file\" || exit $?\n    fi\ndone\n", "num_lines": 12}
{"repo_name": "sagemaker-distribution", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Run all the tutorials\nfor file in *.py; do\n     python \"$file\" || exit $?\ndone\n\n\n", "num_lines": 8}
{"repo_name": "sagemaker-distribution", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Create an empty notebook file for papermill's output\ntouch nb_output.ipynb\n\n# List of all referenced notebook files in Basics, Core, and In Depth sections of Tensorflow docs, excluding experimentals.\n# https://www.tensorflow.org/guide\nexample_notebooks=('basics.ipynb'\n    'tensor.ipynb'\n    'variable.ipynb'\n    'autodiff.ipynb'\n    'intro_to_graphs.ipynb'\n    'intro_to_modules.ipynb'\n    'basic_training_loops.ipynb'\n    'core/quickstart_core.ipynb'\n    'core/logistic_regression_core.ipynb'\n    'core/mlp_core.ipynb'\n    'core/matrix_core.ipynb'\n    'core/optimizers_core.ipynb'\n    'tensor_slicing.ipynb'\n    'advanced_autodiff.ipynb'\n    'ragged_tensor.ipynb'\n    'sparse_tensor.ipynb'\n    'random_numbers.ipynb'\n)\n\nfor nb in ${example_notebooks[@]}; do\n     papermill $nb 'nb_output.ipynb'\ndone\n", "num_lines": 30}
{"repo_name": "sagemaker-example-notebooks-testing", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\npushd python >/dev/null\npython3 setup.py sdist\npopd >/dev/null\n\ndocker build -t sagemaker-codebuild:cpu -f Dockerfile .\n", "num_lines": 8}
{"repo_name": "sagemaker-example-notebooks-testing", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction get_default_region() {\n    if [ -n \"$AWS_DEFAULT_REGION\" ]; then\n        echo \"$AWS_DEFAULT_REGION\"\n    else\n        aws configure get region\n    fi\n}\n\nfunction get_aws_account() {\n    aws --endpoint-url 'https://sts.us-west-2.amazonaws.com' --region 'us-west-2' sts get-caller-identity --query 'Account' --output text\n}\n\naws_region=$(get_default_region)\naws_account=$(get_aws_account)\necr_password=$(aws ecr get-login-password --region $aws_region)\ndocker login --username AWS --password $ecr_password $aws_account.dkr.ecr.$aws_region.amazonaws.com\n\ndocker tag sagemaker-codebuild:cpu $aws_account.dkr.ecr.$aws_region.amazonaws.com/sagemaker-codebuild:cpu\ndocker push $aws_account.dkr.ecr.$aws_region.amazonaws.com/sagemaker-codebuild:cpu\n\ndocker logout https://$aws_account.dkr.ecr.$aws_region.amazonaws.com\n", "num_lines": 24}
{"repo_name": "sagemaker-example-notebooks-testing", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# The argument to this script is the image name. This will be used as the image on the local\n# machine and combined with the account and region to form the repository name for ECR.\n\nprog=$0\ndefault_image=\"python:3.7-slim-buster\"\n\nfunction usage {\n    echo \"Usage: $1 [--base <base-image>] <image>\"\n    echo \"       base:  the image to use to build from [default: ${default_image}]\"\n    echo \"       image: the image to build to. Will be pushed to the matching ECR repo in your account\"\n}\n\nif [ \"$1\" == \"--base\" ]\nthen\n    base=$2\n    if [ \"${base}\" == \"\" ]\n    then\n       usage ${prog}\n       exit 1\n    fi\n    shift 2\nelse\n    base=${default_image}\nfi\n\nimage=$1\n\nif [ \"${image}\" == \"\" ]\nthen\n    usage ${prog}\n    exit 1\nfi\n\necho \"Source image ${base}\"\necho \"Final image ${image}\"\n\n# Get the account number associated with the current IAM credentials\naccount=$(aws sts get-caller-identity --query Account --output text)\n\nif [ $? -ne 0 ]\nthen\n    exit 255\nfi\n\n\n# Get the region defined in the current configuration (default to us-west-2 if none defined)\nregion=$(aws configure get region)\nregion=${region:-us-west-2}\necho \"Region ${region}\"\n\n\nfullname=\"${account}.dkr.ecr.${region}.amazonaws.com/${image}:latest\"\n\n# If the repository doesn't exist in ECR, create it.\n\naws ecr describe-repositories --repository-names \"${image}\" > /dev/null 2>&1\n\nif [ $? -ne 0 ]\nthen\n    aws ecr create-repository --repository-name \"${image}\" > /dev/null\n    if [ $? -ne 0 ]\n    then\n        exit 255\n    fi\nfi\n\n# Docker login has changed in aws-cli version 2. We support both flavors.\nAWS_CLI_MAJOR_VERSION=$(aws --version | sed 's%^aws-cli/\\([0-9]*\\)\\..*$%\\1%')\nif [ \"${AWS_CLI_MAJOR_VERSION}\" == \"1\" ]\nthen\n  # Get the login command from ECR and execute it directly\n  $(aws ecr get-login --region ${region} --no-include-email)\nelse\n  aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${account}.dkr.ecr.${region}.amazonaws.com\nfi\n\n# Build the docker image locally with the image name and then push it to ECR\n# with the full name.\n\ndocker build -t ${image} --build-arg BASE_IMAGE=${base} .\n\ndocker tag ${image} ${fullname}\n\ndocker push ${fullname}\n", "num_lines": 87}
{"repo_name": "sagemaker-example-notebooks-testing", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"No custom init script provided\"", "num_lines": 3}
{"repo_name": "sagemaker-example-notebooks-testing", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Use the container locally to run a Jupyter notebook against a container\n\nimage=$1\nnotebook=$2\noutdir=${3:-$(pwd)}\n\nnotebook_dir=$(dirname ${notebook})\nnotebook_file=$(basename ${notebook})\n\nnotebook_ext=\"${notebook_file##*.}\"\nnotebook_base=\"${notebook_file%.*}\"\n\ndocker run --rm \\\n       -v ${notebook_dir}:/opt/ml/processing/input \\\n       -v ${outdir}:/opt/ml/processing/output \\\n       -e PAPERMILL_INPUT=/opt/ml/processing/input/${notebook_file} \\\n       -e PAPERMILL_OUTPUT=/opt/ml/processing/output/${notebook_base}-$(date +%Y-%m-%d-%H-%M-%S).${notebook_ext} \\\n       -e PAPERMILL_PARAMS=\"{}\" \\\n       ${image} run_notebook\n", "num_lines": 22}
{"repo_name": "sagemaker-mxnet-inference-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -e\n\nif [[ \"$1\" = \"serve\" ]]; then\n    shift 1\n    mxnet-model-server --start --mms-config config.properties\nelse\n    eval \"$@\"\nfi\n\n# prevent docker exit\ntail -f /dev/null\n", "num_lines": 27}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -euo pipefail\n\necho =================== $1 execution time ===================\n\nstart_time=$2\nend_time=`date +%s`\ntotal_time=$(expr $end_time - $start_time + 1)\nhours=$((total_time/60/60%24))\nminutes=$((total_time/60%60))\nsecs=$((total_time%60))\n\n(( $hours > 0 )) && printf '%d hours ' $hours\n(( $minutes > 0 )) && printf '%d minutes ' $minutes\n(( $hours > 0 || $minutes > 0 )) && printf 'and '\nprintf '%d seconds\\n\\n' $secs\n", "num_lines": 30}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env python\n# add_no_index2.py\nimport fileinput\nimport sys\n\nfor line in fileinput.input(inplace=True):\n    if '.. class::' in line or '.. function::' in line or '.. data::' in line or '.. _' in line:\n        sys.stdout.write(line + '   :noindex:\\n')\n    else:\n        sys.stdout.write(line)\n", "num_lines": 11}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\npython benchmarks/scripts/tf_cnn_benchmarks/tf_cnn_benchmarks.py --num_batches=500 --model vgg16 --variable_update horovod --horovod_device gpu --use_fp16 --summary_verbosity 1 --save_summaries_steps 10 --train_dir /opt/ml/model --eval_dir /opt/ml/model --batch_size 32\n", "num_lines": 4}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"This is emr test script...\"\nsleep 15\n", "num_lines": 3}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n#\n# Mounting EFS and FSx for Lustre file systems for integration Tests\nFILE_SYSTEM_EFS_ID=$1\nFILE_SYSTEM_FSX_ID=$2\nREGION=$3\nEFS_MOUNT_DIRECTORY=$4\nFSX_MOUNT_DIRECTORY=$5\n\necho \"Mounting EFS File Systems\"\nsudo yum install -y amazon-efs-utils\nif [ ! -d $EFS_MOUNT_DIRECTORY ]\nthen\n    echo \"$EFS_MOUNT_DIRECTORY does not exist. Creating..\"\n    sudo mkdir \"$EFS_MOUNT_DIRECTORY\"\nfi\n\nif grep -qs $EFS_MOUNT_DIRECTORY /proc/mounts\nthen\n    echo \"$EFS_MOUNT_DIRECTORY already mounted.\"\nelse\n    sudo mount -t efs \"$FILE_SYSTEM_EFS_ID\":/ efs\n    if [ $? -eq 0 ]\n    then\n        echo \"Successfully mounted $FILE_SYSTEM_EFS_ID to $EFS_MOUNT_DIRECTORY.\"\n    else\n        echo \"Something went wrong. Could not mount $FILE_SYSTEM_EFS_ID to $EFS_MOUNT_DIRECTORY.\"\n        exit -1\n    fi\nfi\n\necho \"Creating subfolders for training data from EFS\"\nif [ ! -d $EFS_MOUNT_DIRECTORY/tensorflow ]\nthen\n    echo \"$EFS_MOUNT_DIRECTORY/tensorflow does not exist. Creating..\"\n    sudo mkdir $EFS_MOUNT_DIRECTORY/tensorflow\nfi\n\nif [ ! -d $EFS_MOUNT_DIRECTORY/one_p_mnist ]\nthen\n    echo \"$EFS_MOUNT_DIRECTORY/one_p_mnist does not exist. Creating..\"\n    sudo mkdir $EFS_MOUNT_DIRECTORY/one_p_mnist\nfi\n\necho \"Mounting FSx for Lustre File System\"\nsudo yum install -y lustre-client\nif [ ! -d $FSX_MOUNT_DIRECTORY ]\nthen\n    echo \"$FSX_MOUNT_DIRECTORY does not exist. Creating..\"\n    sudo mkdir -p $FSX_MOUNT_DIRECTORY\nfi\n\nif grep -qs $FSX_MOUNT_DIRECTORY /proc/mounts;\nthen\n    echo \"$FSX_MOUNT_DIRECTORY already mounted.\"\nelse\n    sudo mount -t lustre -o noatime,flock \"$FILE_SYSTEM_FSX_ID\".fsx.\"$REGION\".amazonaws.com@tcp:/fsx $FSX_MOUNT_DIRECTORY\n    if [ $? -eq 0 ]\n    then\n        echo \"Successfully mounted $FILE_SYSTEM_FSX_ID to $FSX_MOUNT_DIRECTORY.\"\n    else\n        echo \"Something went wrong. Could not mount $FILE_SYSTEM_FSX_ID to $FSX_MOUNT_DIRECTORY.\"\n        exit -1\n    fi\nfi\n\necho \"Creating subfolders for training data from Lustre file systems\"\nif [ ! -d $FSX_MOUNT_DIRECTORY/tensorflow ]\nthen\n    echo \"$FSX_MOUNT_DIRECTORY/tensorflow does not exist. Creating..\"\n    sudo mkdir $FSX_MOUNT_DIRECTORY/tensorflow\nfi\n\nif [ ! -d $FSX_MOUNT_DIRECTORY/one_p_mnist ]\nthen\n    echo \"$FSX_MOUNT_DIRECTORY/one_p_mnist does not exist. Creating..\"\n    sudo mkdir $FSX_MOUNT_DIRECTORY/one_p_mnist\nfi\n\necho \"Copying files to the mounted folders\"\nsudo cp temp_tf/* efs/tensorflow\nsudo cp temp_tf/* /mnt/fsx/tensorflow\nsudo cp temp_one_p/* efs/one_p_mnist/\nsudo cp temp_one_p/* /mnt/fsx/one_p_mnist\n", "num_lines": 98}
{"repo_name": "sagemaker-python-sdk", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Run a test against a SageMaker notebook\n# Only runs within the SDK's CI/CD environment\n\nfunction CreateLifeCycleConfig ()\n{\n\necho \"Creating life cycle config....\"\nLIFECYCLE_CONFIG_NAME=$1\nLIFECYCLE_CONFIG_CONTENT=$2\naws sagemaker create-notebook-instance-lifecycle-config --notebook-instance-lifecycle-config-name \"$LIFECYCLE_CONFIG_NAME\" --on-create Content=\"$LIFECYCLE_CONFIG_CONTENT\"\n\n}\n\nfunction DeleteLifeCycleConfig ()\n{\n\necho \"Deleting the existing life cycle config....\"\nLIFECYCLE_CONFIG_NAME=$1\naws sagemaker delete-notebook-instance-lifecycle-config --notebook-instance-lifecycle-config-name  \"$LIFECYCLE_CONFIG_NAME\"\n\n}\n\n\nfunction CreateLifeCycleConfigContent ()\n{\nACCOUNT_ID=$1\nCOMMIT_ID=$2\n\nTARBALL_DIRECTORY=/tmp/sdk-tarballs\nLIFECYCLE_CONFIG_1=$(cat << 'EOF'\n#!/bin/bash\n\nset -e\nset -x\n\nmkdir \"$HOME/.dlami\"\ntouch \"$HOME/.dlami/dlami_build_in_progress\"\nTARBALL_DIRECTORY=/tmp/sdk-tarballs\nmkdir -p \"$TARBALL_DIRECTORY\"\n\nEOF\n)\n\nLIFECYCLE_CONFIG_2=$(cat << EOF\n\naws s3 --region us-west-2 cp \"s3://sagemaker-python-sdk-$ACCOUNT_ID/notebook_test/sagemaker-$COMMIT_ID.tar.gz\" \"$TARBALL_DIRECTORY/sagemaker.tar.gz\"\n\nEOF\n)\n\nLIFECYCLE_CONFIG_3=$(cat << 'EOF'\n\n# Include \"base\" separately since it's not a subdirectory.\nfor env in base /home/ec2-user/anaconda3/envs/*; do\n    echo \"Updating SageMaker vended software in $env from pre-release SDKs...\"\n\n    sudo -u ec2-user -E sh -c 'source /home/ec2-user/anaconda3/bin/activate \"$env\"'\n\n    echo \"Updating SageMaker Python SDK...\"\n    pip install --upgrade pip\n    pip install \"$TARBALL_DIRECTORY/sagemaker.tar.gz\"\n\n    sudo -u ec2-user -E sh -c 'source /home/ec2-user/anaconda3/bin/deactivate'\n\n    echo \"Update of $env is complete.\"\ndone\n\nsudo rm -rf \"$MODELS_SOURCE_DIRECTORY\"\nsudo rm -rf \"$TARBALL_DIRECTORY\"\nrm -rf \"$HOME/.dlami\"\n\nEOF\n)\n\nLIFECYCLE_CONFIG_CONTENT=$((echo \"$LIFECYCLE_CONFIG_1$LIFECYCLE_CONFIG_2$LIFECYCLE_CONFIG_3\"|| echo \"\")| base64)\n\necho \"$LIFECYCLE_CONFIG_CONTENT\"\n\n}\n\nset -euo pipefail\n\n# git doesn't work in codepipeline, use CODEBUILD_RESOLVED_SOURCE_VERSION to get commit id\ncodebuild_initiator=\"${CODEBUILD_INITIATOR:-0}\"\nif [ \"${codebuild_initiator:0:12}\" == \"codepipeline\" ]; then\n    COMMIT_ID=\"${CODEBUILD_RESOLVED_SOURCE_VERSION}\"\nelse\n    COMMIT_ID=$(git rev-parse --short HEAD)\nfi\n\nACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)\nLIFECYCLE_CONFIG_NAME=\"install-python-sdk-$COMMIT_ID\"\n\npython setup.py sdist\n\naws s3 --region us-west-2 cp ./dist/sagemaker-*.tar.gz s3://sagemaker-python-sdk-$ACCOUNT_ID/notebook_test/sagemaker-$COMMIT_ID.tar.gz\naws s3 cp s3://sagemaker-python-sdk-cli-$ACCOUNT_ID/mead-nb-test.tar.gz mead-nb-test.tar.gz\ntar -xzf mead-nb-test.tar.gz\n\n\nLIFECYCLE_CONFIG_CONTENT=$(CreateLifeCycleConfigContent \"$ACCOUNT_ID\" \"$COMMIT_ID\" )\n\nif !(CreateLifeCycleConfig \"$LIFECYCLE_CONFIG_NAME\" \"$LIFECYCLE_CONFIG_CONTENT\")  ; then\n(DeleteLifeCycleConfig \"$LIFECYCLE_CONFIG_NAME\")\n(CreateLifeCycleConfig \"$LIFECYCLE_CONFIG_NAME\" \"$LIFECYCLE_CONFIG_CONTENT\")\nfi\n\nif [ -d amazon-sagemaker-examples ]; then rm -Rf amazon-sagemaker-examples; fi\ngit clone --depth 1 https://github.com/aws/amazon-sagemaker-examples.git\n\nexport JAVA_HOME=$(get-java-home)\necho \"set JAVA_HOME=$JAVA_HOME\"\nexport SAGEMAKER_ROLE_ARN=$(aws iam list-roles --output text --query \"Roles[?RoleName == 'SageMakerRole'].Arn\")\necho \"set SAGEMAKER_ROLE_ARN=$SAGEMAKER_ROLE_ARN\"\n\n./runtime/bin/mead-run-nb-test \\\n--instance-type ml.c4.8xlarge \\\n--region us-west-2 \\\n--lifecycle-config-name $LIFECYCLE_CONFIG_NAME \\\n--notebook-instance-role-arn $SAGEMAKER_ROLE_ARN \\\n--platformIdentifier notebook-al2-v2 \\\n--consider-skips-failures \\\n./amazon-sagemaker-examples/sagemaker_processing/spark_distributed_data_processing/sagemaker-spark-processing.ipynb \\\n./amazon-sagemaker-examples/advanced_functionality/kmeans_bring_your_own_model/kmeans_bring_your_own_model.ipynb \\\n./amazon-sagemaker-examples/advanced_functionality/tensorflow_iris_byom/tensorflow_BYOM_iris.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/1P_kmeans_highlevel/kmeans_mnist.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/1P_kmeans_lowlevel/kmeans_mnist_lowlevel.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/mxnet_gluon_sentiment/mxnet_sentiment_analysis_with_gluon.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/mxnet_onnx_export/mxnet_onnx_export.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/scikit_learn_randomforest/Sklearn_on_SageMaker_end2end.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/tensorflow_moving_from_framework_mode_to_script_mode/tensorflow_moving_from_framework_mode_to_script_mode.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/tensorflow_script_mode_pipe_mode/tensorflow_script_mode_pipe_mode.ipynb \\\n./amazon-sagemaker-examples/sagemaker-python-sdk/tensorflow_serving_using_elastic_inference_with_your_own_model/tensorflow_serving_pretrained_model_elastic_inference.ipynb \\\n\n(DeleteLifeCycleConfig \"$LIFECYCLE_CONFIG_NAME\")\n", "num_lines": 138}
{"repo_name": "sagemaker-pytorch-inference-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n\n    gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n    gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so train\nelse\n    serve\nfi\n", "num_lines": 16}
{"repo_name": "sagemaker-pytorch-inference-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n\n    gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n    gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so train\nelse\n    serve\nfi\n", "num_lines": 16}
{"repo_name": "sagemaker-pytorch-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ \"$1\" = \"train\" ]]; then\n     CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n     sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n     gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n     gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n     LD_PRELOAD=/libchangehostname.so train\nelse\n     eval \"$@\"\nfi\n", "num_lines": 12}
{"repo_name": "sagemaker-pytorch-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ \"$1\" = \"train\" ]]; then\n     CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n     sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" changehostname.c\n     gcc -o changehostname.o -c -fPIC -Wall changehostname.c\n     gcc -o libchangehostname.so -shared -export-dynamic changehostname.o -ldl\n     LD_PRELOAD=/libchangehostname.so train\nelse\n     eval \"$@\"\nfi\n", "num_lines": 12}
{"repo_name": "sagemaker-rl-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ $1 == 'train' ]\nthen\n    # Remove all nvidia gl libraries if they exists to run training in SageMaker.\n    rm -rf /usr/local/nvidia/lib/libGL*\n    rm -rf /usr/local/nvidia/lib/libEGL*\n    rm -rf /usr/local/nvidia/lib/libOpenGL*\n    rm -rf /usr/local/nvidia/lib64/libGL*\n    rm -rf /usr/local/nvidia/lib64/libEGL*\n    rm -rf /usr/local/nvidia/lib64/libOpenGL*\n\n    CURRENT_HOST=$(jq .current_host  /opt/ml/input/config/resourceconfig.json)\n\n    sed -ie \"s/PLACEHOLDER_HOSTNAME/$CURRENT_HOST/g\" /changehostname.c\n\n    gcc -o /changehostname.o -c -fPIC -Wall /changehostname.c\n    gcc -o /libchangehostname.so -shared -export-dynamic /changehostname.o -ldl\n\n    LD_PRELOAD=/libchangehostname.so xvfb-run --auto-servernum -s \"-screen 0 1400x900x24\" train\nelif [ $1 == 'serve' ]\nthen\n    serve\nfi\n", "num_lines": 25}
{"repo_name": "sagemaker-rl-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Build the docker images.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_build_std_args \"$@\"\n\necho \"pulling previous_image: $base_image_ecr_repo for layer cache... \"\n$(aws ecr get-login --no-include-email --registry-id $base_image_account_id) &>/dev/null || echo 'warning: ecr login failed'\ndocker pull $base_image_ecr_repo &>/dev/null || echo 'warning: base image pull failed'\ndocker logout https://$base_image_account_id.dkr.ecr.$aws_region.amazonaws.com &>/dev/null\n\necho \"building image with version_number: $version_number, and tagging as $local_image_tag ... \"\ndocker build \\\n    --cache-from $base_image_ecr_repo \\\n    -f vw/docker/$version_number/Dockerfile \\\n    -t $local_image_tag .\n\n", "num_lines": 22}
{"repo_name": "sagemaker-rl-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Pushes a locally tagged image to ECR repo.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_publish_std_args \"$@\"\n\necho \"logging into ECR.\"\n$(aws ecr get-login --no-include-email --registry-id $aws_account) &>/dev/null || echo 'warning: ecr login failed'\ndocker tag $local_image_tag $new_ecr_image_tag\n\necho \"pushing local_image: $local_image_tag to ecr_repo: $new_ecr_image_tag \"\ndocker push $new_ecr_image_tag\n\ndocker logout https://$aws_account.dkr.ecr.$aws_region.amazonaws.com &>/dev/null\n\n", "num_lines": 20}
{"repo_name": "sagemaker-rl-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Utility functions for build/test scripts.\n\nfunction error() {\n    >&2 echo $1\n    >&2 echo \"build usage: $0 [--version-number <major-version>] [--local-image-tag <tag-for-new-image>] [--base-image-ecr-repo <base ecr repo to cache from>] [--region <aws-region>]\"\n    >&2 echo \"publish usage: $0 [--local-image-tag <local image tag to push>] [--new-ecr-image-repo <ecr repo to push to>] [--region <aws-region>]\"\n    exit 1\n}\n\nfunction get_default_region() {\n    if [ -n \"${AWS_DEFAULT_REGION:-}\" ]; then\n        echo \"$AWS_DEFAULT_REGION\"\n    else\n        aws configure get region\n    fi\n}\n\nfunction get_aws_account() {\n    aws sts get-caller-identity --query 'Account' --output text\n}\n\nfunction parse_build_std_args() {\n    # defaults\n    aws_region=$(get_default_region)\n\n    while [[ $# -gt 0 ]]; do\n    key=\"$1\"\n\n    case $key in\n        -b|--base-image-account-id)\n        base_image_account_id=\"$2\"\n        shift\n        shift\n        ;;\n        -v|--version-number)\n        version_number=\"$2\"\n        shift\n        shift\n        ;;\n        -r|--region)\n        aws_region=\"$2\"\n        shift\n        shift\n        ;;\n        -l|--local-image-tag)\n        local_image_tag=\"$2\"\n        shift\n        shift\n        ;;\n        -b|--base-image-ecr-repo)\n        base_image_ecr_repo=\"$2\"\n        shift\n        shift\n        ;;\n        *) # unknown option\n        error \"unknown option: $1\"\n        shift\n        ;;\n    esac\n    done\n\n    [[ -z \"${base_image_account_id// }\" ]] && error 'missing base-image-account-id'\n    [[ -z \"${version_number// }\" ]] && error 'missing version-number'\n    [[ -z \"${aws_region// }\" ]] && error 'missing aws region'\n    [[ -z \"${local_image_tag// }\" ]] && error 'missing local tag name for the built image'\n    [[ -z \"${base_image_ecr_repo// }\" ]] && error 'missing base image to build from'\n\n    true\n}\n\nfunction parse_publish_std_args() {\n    # defaults\n    aws_region=$(get_default_region)\n    aws_account=$(get_aws_account)\n\n    while [[ $# -gt 0 ]]; do\n    key=\"$1\"\n\n    case $key in\n        -l|--local-image-tag)\n        local_image_tag=\"$2\"\n        shift\n        shift\n        ;;\n        -r|--region)\n        aws_region=\"$2\"\n        shift\n        shift\n        ;;\n        -n|--new-ecr-image-tag)\n        new_ecr_image_tag=\"$2\"\n        shift\n        shift\n        ;;\n        *) # unknown option\n        error \"unknown option: $1\"\n        shift\n        ;;\n    esac\n    done\n    \n    [[ -z \"${aws_account// }\" ]] && error 'missing aws aws_account'\n    [[ -z \"${aws_region// }\" ]] && error 'missing aws region'\n    [[ -z \"${local_image_tag// }\" ]] && error 'missing local tag name for the built image'\n    [[ -z \"${new_ecr_image_tag// }\" ]] && error 'missing base image to build from'\n\n    true\n}\n\n", "num_lines": 112}
{"repo_name": "sagemaker-rl-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\npip install gym[atari] gym[box2d] box2d-py>=2.3.5\npython gym_envs.py \"$@\"\n", "num_lines": 5}
{"repo_name": "sagemaker-scikit-learn-extension", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -euo pipefail\n\necho =================== $1 execution time ===================\n\nstart_time=$2\nend_time=`date +%s`\ntotal_time=$(expr $end_time - $start_time + 1)\nhours=$((total_time/60/60%24))\nminutes=$((total_time/60%60))\nsecs=$((total_time%60))\n\n(( $hours > 0 )) && printf '%d hours ' $hours\n(( $minutes > 0 )) && printf '%d minutes ' $minutes\n(( $hours > 0 || $minutes > 0 )) && printf 'and '\nprintf '%d seconds\\n\\n' $secs", "num_lines": 29}
{"repo_name": "sagemaker-spark", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\n\ncurl -LO https://github.com/apache/spark/archive/branch-2.2.zip\nunzip -o branch-2.2.zip \"spark-branch-2.2/python/pyspark/*\"\ncp -r spark-branch-2.2/python/pyspark ../src/\n", "num_lines": 7}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#\n# Build the docker images.\n#\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\naws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin 137112412989.dkr.ecr.us-west-2.amazonaws.com\n\necho \"building image ${version} ... \"\necho \"building image under ${build_context}/docker/${framework_version} ... \"\ndocker build \\\n    -f ${build_context}/docker/${framework_version}/Dockerfile.${processor} \\\n    -t ${repository}:${version} \\\n    --build-arg REGION=${REGION} \\\n    -t sagemaker-spark:latest \\\n    ${build_context}\n\ndocker logout https://137112412989.dkr.ecr.us-west-2.amazonaws.com\n", "num_lines": 37}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#\n# Calls EC2 describe-instance-types to form a json file used by the Spark container for choosing Spark config.\n# This will fetch more instance types than needed, but that's OK.\n#\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\ndest_path=${build_context}/aws-config\nmkdir -p ${dest_path}\ndest_path=${dest_path}/ec2-instance-type-info.json\n\necho \"Fetching EC2 instance type info to ${dest_path} ...\"\naws ec2 describe-instance-types --region ${aws_region} | \\\n  jq -c '[.InstanceTypes[] |\n  {\n    InstanceType: .InstanceType,\n    VCpuInfo: .VCpuInfo,\n    MemoryInfo: .MemoryInfo,\n    GpuInfo: .GpuInfo\n  }] |\n  sort_by(.InstanceType)' > ${dest_path}\n", "num_lines": 40}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n#\n# Publish images to your ECR account.\n#\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\n$(aws ecr get-login --no-include-email --region ${aws_region} --registry-id ${aws_account})\ndocker tag ${repository}:${version} ${aws_account}.dkr.ecr.${aws_region}.amazonaws.com/${repository}:${version}\ndocker push ${aws_account}.dkr.ecr.${aws_region}.amazonaws.com/${repository}:${version}\ndocker logout https://${aws_account}.dkr.ecr.${aws_region}.amazonaws.com\n", "num_lines": 29}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Utility functions for build/test scripts.\n\nfunction error() {\n    >&2 echo $1\n    >&2 echo \"usage: $0 [--region <aws-region>] [--spark-version <spark MAJOR.MINOR version>] [--processor <cpu|gpu>]\\\n     [--use-case <processing|training>] [--framework-version <py3|py37>] [--sm-version <sagemaker MAJOR.MINOR version?]\"\n    exit 1\n}\n\nfunction get_aws_account() {\n    aws --region $1 sts --endpoint-url https://sts.$1.amazonaws.com get-caller-identity --query 'Account' --output text\n}\n\nfunction parse_std_args() {\n    while [[ $# -gt 0 ]]; do\n    key=\"$1\"\n\n    case $key in\n        -r|--region)\n        aws_region=\"$2\"\n        shift\n        shift\n        ;;\n        --spark-version)\n        spark_version=\"$2\"\n        shift\n        shift\n        ;;\n        --processor)\n        processor=\"$2\"\n        shift\n        shift\n        ;;\n        --use-case)\n        use_case=\"$2\"\n        shift\n        shift\n        ;;\n        --framework-version)\n        framework_version=\"$2\"\n        shift\n        shift\n        ;;\n        --sm-version)\n        sm_version=\"$2\"\n        shift\n        shift\n        ;;\n        *) # unknown option\n        error \"unknown option: $1\"\n        shift\n        ;;\n    esac\n    done\n\n    [[ -z \"${aws_region// }\" ]] && error 'missing aws region'\n    [[ -z \"${spark_version// }\" ]] && error 'missing spark minor version'\n    [[ -z \"${processor// }\" ]] && processor='cpu'\n    [[ -z \"${use_case// }\" ]] && use_case='processing'\n    [[ -z \"${framework_version// }\" ]] && framework_version='py3'\n    [[ -z \"${sm_version// }\" ]] && sm_version='0.1'\n\n    [[ -z \"${DEST_REPO}\" ]] && repository=sagemaker-spark-$use_case || repository=\"${DEST_REPO}\"\n    [[ -z \"${REGION}\" ]] && aws_region='us-west-2' || aws_region=\"${REGION}\"\n\n\n    build_context=./spark/${use_case}/${spark_version}/${framework_version:0:3}\n    aws_account=$(get_aws_account $aws_region)\n    # spark tagging scheme :\n    # sagemaker-spark-[processing|training]:[spark_version]-[processor]-[python/scala version]-v[sm_major].[sm_minor]\n    version=${spark_version}-${processor}-${framework_version}-v${sm_version}\n    true\n}\n\nfunction error_build_context() {\n    >&2 echo $1\n    >&2 echo \"usage: $0 [--build-context <Docker build context>]\"\n    exit 1\n}\n\nfunction parse_build_context() {\n    # Docker build context\n    if [[ $1 == \"--build-context\" ]]\n    then\n        build_context=\"$2\"\n    fi\n\n    [[ -z \"${build_context// }\" ]] && error_build_context \"missing path to docker build context\"\n\n    true\n}", "num_lines": 93}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"Not implemented\"", "num_lines": 1}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#EMPTY FILE AVOID OVERRIDDING ENV VARS\n# Specifically, without copying the empty file, SPARK_HISTORY_OPTS will be overriden, \n# spark.history.ui.port defaults to 18082, and spark.eventLog.dir defaults to local fs\n", "num_lines": 4}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"Not implemented\"", "num_lines": 1}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#EMPTY FILE AVOID OVERRIDDING ENV VARS\n# Specifically, without copying the empty file, SPARK_HISTORY_OPTS will be overriden, \n# spark.history.ui.port defaults to 18082, and spark.eventLog.dir defaults to local fs\n", "num_lines": 4}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"Not implemented\"", "num_lines": 1}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#EMPTY FILE AVOID OVERRIDDING ENV VARS\n# Specifically, without copying the empty file, SPARK_HISTORY_OPTS will be overriden, \n# spark.history.ui.port defaults to 18082, and spark.eventLog.dir defaults to local fs\n", "num_lines": 4}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"Not implemented\"", "num_lines": 1}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#EMPTY FILE AVOID OVERRIDDING ENV VARS\n# Specifically, without copying the empty file, SPARK_HISTORY_OPTS will be overriden, \n# spark.history.ui.port defaults to 18082, and spark.eventLog.dir defaults to local fs\n", "num_lines": 4}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "echo \"Not implemented\"", "num_lines": 1}
{"repo_name": "sagemaker-spark-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#EMPTY FILE AVOID OVERRIDDING ENV VARS\n# Specifically, without copying the empty file, SPARK_HISTORY_OPTS will be overriden, \n# spark.history.ui.port defaults to 18082, and spark.eventLog.dir defaults to local fs\n", "num_lines": 4}
{"repo_name": "sagemaker-sparkml-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This is needed to make sure Java correctly detects CPU/Memory set by the container limits\njava -XX:+UnlockExperimentalVMOptions -XX:+UseCGroupMemoryLimitForHeap -jar /usr/local/lib/sparkml-serving-3.3.jar", "num_lines": 3}
{"repo_name": "sagemaker-tensorflow-extensions", "repo_creator": "aws", "programming_language": "Shell", "code": "find . -name \\*.hpp -or -name \\*.cpp \\\n\t| xargs cpplint --linelength=120 --filter=-build/c++11 2>&1 \\\n\t| grep -v \"Done processing \"\n", "num_lines": 4}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Build all the docker images.\n\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\n${DIR}/build.sh --version 1.14.0 --arch eia\n${DIR}/build.sh --version 1.15.0 --arch cpu\n${DIR}/build.sh --version 1.15.0 --arch gpu\n${DIR}/build.sh --version 2.1.0 --arch cpu\n${DIR}/build.sh --version 2.1.0 --arch gpu\n", "num_lines": 14}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Build the docker images.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\nget_ei_executable\n\necho \"pulling previous image for layer cache... \"\naws ecr get-login-password --region ${aws_region} \\\n    | docker login \\\n        --password-stdin \\\n        --username AWS \\\n        \"${aws_account}.dkr.ecr.${aws_region}.amazonaws.com/${repository}\" &>/dev/null || echo 'warning: ecr login failed'\ndocker pull $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$full_version-$device &>/dev/null || echo 'warning: pull failed'\ndocker logout https://$aws_account.dkr.ecr.$aws_region.amazonaws.com &>/dev/null\n\necho \"building image... \"\ncp -r docker/build_artifacts/* docker/$short_version/\ndocker build \\\n    --cache-from $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$full_version-$device \\\n    --build-arg TFS_VERSION=$full_version \\\n    --build-arg TFS_SHORT_VERSION=$short_version \\\n    -f docker/$short_version/Dockerfile.$arch \\\n    -t $repository:$full_version-$device \\\n    -t $repository:$short_version-$device \\\n    docker/$short_version/\n\nremove_ei_executable\n", "num_lines": 34}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Some example curl requests to try on local docker containers.\n\ncurl -X POST --data-binary @test/resources/inputs/test.json -H 'Content-Type: application/json' -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=half_plus_three' http://localhost:8080/invocations\ncurl -X POST --data-binary @test/resources/inputs/test-gcloud.jsons -H 'Content-Type: application/json' -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=half_plus_three' http://localhost:8080/invocations\ncurl -X POST --data-binary @test/resources/inputs/test-generic.json -H 'Content-Type: application/json' -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=half_plus_three' http://localhost:8080/invocations\ncurl -X POST --data-binary @test/resources/inputs/test.csv -H 'Content-Type: text/csv' -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=half_plus_three' http://localhost:8080/invocations\ncurl -X POST --data-binary @test/resources/inputs/test-cifar.json -H 'Content-Type: application/json' -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=cifar' http://localhost:8080/invocations", "num_lines": 9}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Publish all images to your ECR account.\n\nset -euo pipefail\n\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\n${DIR}/publish.sh --version 1.14.0 --arch eia\n${DIR}/publish.sh --version 1.15.0 --arch cpu\n${DIR}/publish.sh --version 1.15.0 --arch gpu\n${DIR}/publish.sh --version 2.1.0 --arch cpu\n${DIR}/publish.sh --version 2.1.0 --arch gpu\n", "num_lines": 14}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Publish images to your ECR account.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\naws ecr get-login-password --region ${aws_region} \\\n    | docker login \\\n        --password-stdin \\\n        --username AWS \\\n        \"${aws_account}.dkr.ecr.${aws_region}.amazonaws.com/${repository}\"\ndocker tag $repository:$full_version-$device $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$full_version-$device\ndocker tag $repository:$full_version-$device $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$short_version-$device\ndocker push $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$full_version-$device\ndocker push $aws_account.dkr.ecr.$aws_region.amazonaws.com/$repository:$short_version-$device\ndocker logout https://$aws_account.dkr.ecr.$aws_region.amazonaws.com\n", "num_lines": 21}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Utility functions for build/test scripts.\n\nfunction error() {\n    >&2 echo $1\n    >&2 echo \"usage: $0 [--version <major-version>] [--arch (cpu*|gpu|eia)] [--region <aws-region>]\"\n    exit 1\n}\n\nfunction get_default_region() {\n    if [ -n \"${AWS_DEFAULT_REGION:-}\" ]; then\n        echo \"$AWS_DEFAULT_REGION\"\n    else\n        aws configure get region\n    fi\n}\n\nfunction get_full_version() {\n    echo $1 | sed 's#^\\([0-9][0-9]*\\.[0-9][0-9]*\\)$#\\1.0#'\n}\n\nfunction get_short_version() {\n    echo $1 | sed 's#\\([0-9][0-9]*\\.[0-9][0-9]*\\)\\.[0-9][0-9]*#\\1#'\n}\n\nfunction get_aws_account() {\n    aws --region $AWS_DEFAULT_REGION sts --endpoint-url https://sts.$AWS_DEFAULT_REGION.amazonaws.com get-caller-identity --query 'Account' --output text\n}\n\nfunction get_ei_executable() {\n    [[ $arch != 'eia' ]] && return\n\n    if [[ -z $(aws s3 ls 's3://amazonei-tensorflow/tensorflow-serving/v'${short_version}'/ubuntu/latest/') ]]; then\n        echo 'ERROR: cannot find this version in S3 bucket.'\n        exit 1\n    fi\n\n    tmpdir=$(mktemp -d)\n    tar_file=$(aws s3 ls \"s3://amazonei-tensorflow/tensorflow-serving/v${short_version}/ubuntu/latest/\" | awk '{print $4}')\n    aws s3 cp \"s3://amazonei-tensorflow/tensorflow-serving/v${short_version}/ubuntu/latest/${tar_file}\" \"$tmpdir/$tar_file\"\n\n    tar -C \"$tmpdir\" -xf \"$tmpdir/$tar_file\"\n\n    find \"$tmpdir\" -name amazonei_tensorflow_model_server -exec mv {} docker/build_artifacts/ \\;\n    rm -rf \"$tmpdir\"\n}\n\nfunction remove_ei_executable() {\n    [[ $arch != 'eia' ]] && return\n\n    rm docker/build_artifacts/amazonei_tensorflow_model_server\n}\n\nfunction get_device_type() {\n    if [[ $1 = 'eia' ]]; then\n        echo 'cpu'\n    else\n        echo $1\n    fi\n}\n\nfunction parse_std_args() {\n    # defaults\n    arch='cpu'\n    version='1.13.0'\n    repository='sagemaker-tensorflow-serving'\n\n    aws_region=$(get_default_region)\n    aws_account=$(get_aws_account)\n\n    while [[ $# -gt 0 ]]; do\n    key=\"$1\"\n\n    case $key in\n        -v|--version)\n        version=\"$2\"\n        shift\n        shift\n        ;;\n        -a|--arch)\n        arch=\"$2\"\n        shift\n        shift\n        ;;\n        -r|--region)\n        aws_region=\"$2\"\n        shift\n        shift\n        ;;\n        -p|--repository)\n        repository=\"$2\"\n        shift\n        shift\n        ;;\n        *) # unknown option\n        error \"unknown option: $1\"\n        shift\n        ;;\n    esac\n    done\n\n    [[ -z \"${version// }\" ]] && error 'missing version'\n    [[ \"$arch\" =~ ^(cpu|gpu|eia)$ ]] || error \"invalid arch: $arch\"\n    [[ -z \"${aws_region// }\" ]] && error 'missing aws region'\n\n    [[ \"$arch\" = eia ]] && repository=$repository'-'$arch\n\n    full_version=$(get_full_version $version)\n    short_version=$(get_short_version $version)\n    device=$(get_device_type $arch)\n\n    true\n}\n", "num_lines": 115}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Start a local docker container.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\nif [ \"$arch\" == 'gpu' ]; then\n    docker_command='nvidia-docker'\nelse\n    docker_command='docker'\nfi\n\n\nMODEL_DIR=\"$(cd \"test/resources/models\" > /dev/null && pwd)\"\n$docker_command run \\\n    -v \"$MODEL_DIR\":/opt/ml/model:ro \\\n    -p 8080:8080 \\\n    -e \"SAGEMAKER_TFS_NGINX_LOGLEVEL=error\" \\\n    -e \"SAGEMAKER_BIND_TO_PORT=8080\" \\\n    -e \"SAGEMAKER_SAFE_PORT_RANGE=9000-9999\" \\\n    $repository:$full_version-$device serve > log.txt 2>&1 &\n", "num_lines": 26}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Stop a local docker container.\n\nset -euo pipefail\n\nsource scripts/shared.sh\n\nparse_std_args \"$@\"\n\ndocker kill $(docker ps -q --filter ancestor=$repository:$full_version-$device)\n", "num_lines": 12}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nab -k -n 10000 -c 16 -p test/resources/inputs/test.json -T 'application/json' http://localhost:8080/tfs/v1/models/half_plus_three:predict\nab -k -n 10000 -c 16 -p test/resources/inputs/test.json -T 'application/json' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test.jsons -T 'application/json' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test.csv -T 'text/csv' http://localhost:8080/invocations\nab -k -n 10000 -c 16 -p test/resources/inputs/test-cifar.json -T 'application/json'     -H 'X-Amzn-SageMaker-Custom-Attributes: tfs-model-name=cifar' http://localhost:8080/invocations\n\n# Larger payloads are generated and removed when this script exits.\nTEMPFILE='/tmp/perftest_data'\ntrap 'rm -f $TEMPFILE' EXIT\n\necho \"Generating data\"\n# Creates a 10MB file with 10000 columns per line.\npython test/perf/data_generator.py -c 'text/csv' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'text/csv' http://localhost:8080/invocations\n\npython test/perf/data_generator.py -c 'application/json' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'application/json' http://localhost:8080/invocations\n\npython test/perf/data_generator.py -c 'application/jsonlines' -s 10000 -p 10 -u MB > $TEMPFILE || exit $?\nab -k -n 10 -c 1 -p \"$TEMPFILE\" -T 'application/jsonlines' http://localhost:8080/invocations\n", "num_lines": 23}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ninstance_type=\"${1:-c5.xlarge}\"\nif [[ \"$instance_type\" == p* ]]; then\n    arch='gpu'\nelse\n    arch='cpu'\nfi\n\nendpoint_name=$(echo \"sagemaker-tensorflow-serving-$instance_type\" | tr . -)\n\naws sagemaker create-endpoint-config \\\n    --endpoint-config-name $endpoint_name \\\n    --production-variants '[{\n        \"VariantName\": \"variant-name-1\",\n        \"ModelName\": \"sagemaker-tensorflow-serving-model-'$arch'\",\n        \"InitialInstanceCount\": 1,\n        \"InstanceType\": \"ml.'$instance_type'\"\n    }]'\n\naws sagemaker create-endpoint --endpoint-name $endpoint_name --endpoint-config-name $endpoint_name\n", "num_lines": 22}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\narch=${1:-'cpu'}\naws_region=$(aws configure get region)\naws_account=$(aws --region $aws_region sts --endpoint-url https://sts.$aws_region.amazonaws.com get-caller-identity --query 'Account' --output text)\n\n# change this to match SageMaker execution role in your account\nsagemaker_role=\"arn:aws:iam::$aws_account:role/service-role/AmazonSageMaker-ExecutionRole-20180510T114550\"\n\ntar -C test/resources/models -czf /tmp/sagemaker-tensorflow-serving-model.tar.gz .\naws s3 mb s3://sagemaker-$aws_region-$aws_account || true\naws s3 cp /tmp/sagemaker-tensorflow-serving-model.tar.gz s3://sagemaker-$aws_region-$aws_account/sagemaker-tensorflow-serving/test-models/sagemaker-tensorflow-serving-model.tar.gz\nrm /tmp/sagemaker-tensorflow-serving-model.tar.gz\n\n\naws sagemaker create-model \\\n    --model-name sagemaker-tensorflow-serving-model-$arch \\\n    --primary-container '{\n        \"Image\": \"'$aws_account'.dkr.ecr.'$aws_region'.amazonaws.com/sagemaker-tensorflow-serving:1.11.1-'$arch'\",\n        \"ModelDataUrl\": \"s3://sagemaker-'$aws_region'-'$aws_account'/sagemaker-tensorflow-serving/test-models/sagemaker-tensorflow-serving-model.tar.gz\",\n        \"Environment\": {\n            \"SAGEMAKER_TFS_DEFAULT_MODEL_NAME\": \"half_plus_three\"\n        }\n    }' \\\n    --execution-role-arn \"$sagemaker_role\"\n", "num_lines": 28}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nendpoint=${1-'sagemaker-tensorflow-serving-cpu-c5-xlarge'}\naws sagemaker delete-endpoint --endpoint-name $endpoint\naws sagemaker delete-endpoint-config --endpoint-config-name $endpoint", "num_lines": 5}
{"repo_name": "sagemaker-tensorflow-serving-container", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model sm-c5xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model sm-c518xl >> sm-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model sm-c518xl >> sm-perftest.log; done\n\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-c5xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-c518xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python perftest_endpoint.py --count 5000 --warmup 100 --workers 128 --model tfs-c518xl >> tfs-perftest.log; done\n\n\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-p2xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 4 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 8 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 16 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 32 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 64 --model tfs-p316xl >> tfs-perftest.log; done\nfor i in $(seq 1 5); do python test/perf/perftest_endpoint.py --count 5000 --warmup 100 --workers 128 --model tfs-p316xl >> tfs-perftest.log; done\n", "num_lines": 36}
{"repo_name": "sagemaker-tensorflow-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\n./execute_tensorflow_training.py train \\\n--framework-version  1.12 \\\n--device gpu \\\n\\\n--instance-types ml.p3.16xlarge \\\n\\\n--instance-counts 1 \\\n--instance-counts 2 \\\n--instance-counts 4 \\\n--instance-counts 8 \\\n--instance-counts 16 \\\n\\\n--py-versions py3 \\\n\\\n--subnets # add subnet id here  \\\n\\\n--security-groups # add security-group id here\n", "num_lines": 32}
{"repo_name": "sagemaker-tensorflow-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the \"license\" file accompanying this file. This file is\n# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -ex\n\necho \"Launching training job using $SM_NUM_GPUS GPUs\"\n\n# p3 instances have larger GPU memory, so a higher batch size can be used\nGPU_MEM=`nvidia-smi --query-gpu=memory.total --format=csv,noheader -i 0 | awk '{print $1}'`\nif [ $GPU_MEM -gt 15000 ] ; then BATCH_SIZE=256; else BATCH_SIZE=128; fi\n\n# Training\npython -W ignore train_imagenet_resnet_hvd.py --num_epochs 90 --synthetic -b $BATCH_SIZE \\\n\t--lr_decay_mode poly --warmup_epochs 10 --clear_log\n", "num_lines": 26}
{"repo_name": "sagemaker-tensorflow-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexecute_tensorflow_training.py train \\\n--framework-version  1.12 \\\n--device gpu \\\n\\\n--instance-types ml.p3.16xlarge \\\n\\\n--instance-counts 1 \\\n--instance-counts 2 \\\n--instance-counts 4 \\\n\\\n--py-versions py3 \\\n\\\n--subnets subnet-125fb674  \\\n\\\n--security-groups sg-ce5dd1b4  \\\n\\\n--batch-sizes 64 \\\n\\\n-- --num_batches=1000 --model vgg16 \\\n    --variable_update horovod --horovod_device gpu --use_fp16 --summary_verbosity 1 --save_summaries_steps 10", "num_lines": 22}
{"repo_name": "sagemaker-training-toolkit", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License'). You\n# may not use this file except in compliance with the License. A copy of\n# the License is located at\n#\n#     http://aws.amazon.com/apache2.0/\n#\n# or in the 'license' file accompanying this file. This file is\n# distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES OR CONDITIONS OF\n# ANY KIND, either express or implied. See the License for the specific\n# language governing permissions and limitations under the License.\n\nset -ex\npython script.py\n", "num_lines": 17}
{"repo_name": "selective-search-with-mutual-information-cotraining", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\ndataset_name=example\ntrain_folder_path=../data/${dataset_name}_train_csv/\ntest_folder_path=../data/${dataset_name}_test_csv/\n\nbatch_size=64\nbatch_size_test=512\nselected_layer_idx=-1\npooling_strategy=CLS_TOKEN\nmax_length=64\nlr=2e-4\nlr_bert=5e-6\nentropy_weight=5\nnum_warmup_steps=1000\nseed=1\n\nmodel_path=../results/${dataset_name}_pair_BERT-finetune_layer${selected_layer_idx}\\\n_${pooling_strategy}\\\n_maxlen${max_length}\\\n_bs${batch_size}\\\n_lr-bert${lr_bert}\\\n_lr${lr}\\\n_warmup${num_warmup_steps}\\\n_entropy${entropy_weight}\\\n_seed${seed}/\n\npython -u ../../main.py \\\n    --model_path=${model_path} \\\n    --train_folder_path=${train_folder_path} \\\n    --test_folder_path=${test_folder_path} \\\n    --is_csv_header \\\n    --dim_input=768 \\\n    --number_clusters=64 \\\n    --dim_hidden=8 \\\n    --num_layers_posterior=0 \\\n    --batch_size=${batch_size} \\\n    --batch_size_test=${batch_size_test} \\\n    --lr=${lr} \\\n    --num_warmup_steps=${num_warmup_steps} \\\n    --lr_prior=0.1 \\\n    --num_steps_prior=1 \\\n    --init=0.0 \\\n    --clip=1.0 \\\n    --epochs=1 \\\n    --log_interval=10 \\\n    --check_val_test_interval=10000 \\\n    --save_per_num_epoch=100 \\\n    --num_bad_epochs=10 \\\n    --seed=${seed} \\\n    --entropy_weight=${entropy_weight} \\\n    --num_workers=0 \\\n    --cuda \\\n    --lr_bert=${lr_bert} \\\n    --max_length=${max_length} \\\n    --pooling_strategy=${pooling_strategy} \\\n    --selected_layer_idx=${selected_layer_idx} \n", "num_lines": 58}
{"repo_name": "serverless-application-model", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\nset -eux\n\nVENV=.venv_cfn_lint\n\n# Install to separate venv to avoid circular dependency; cfn-lint depends on samtranslator\n# See https://github.com/aws/serverless-application-model/issues/1042\nif [ ! -d \"${VENV}\" ]; then\n    python3 -m venv \"${VENV}\"\nfi\n\n\"${VENV}/bin/python\" -m pip install cfn-lint==0.75.0 --upgrade --quiet\n\"${VENV}/bin/cfn-lint\" --format parseable\n", "num_lines": 14}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Run checkstyle script\"\n\n# run gofmt\necho \"Run 'gofmt'\"\nunformatted=$(gofmt -l `pwd`/src/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by gofmt\"\n\tfor fi in $unformatted; do\n\t\techo >&2 $fi\n\tdone\n\techo \"Please run 'gofmt -w' for files listed.\"\n\texit 1\nfi\n\n# run goimports\necho \"Try update 'goimports'\"\nGOPATH=`pwd`/Tools go get golang.org/x/tools/cmd/goimports\n\necho \"Run 'goimports'\"\nunformatted=$(Tools/bin/goimports -l `pwd`/src/)\nif [[ -n $unformatted ]]; then\n\techo >&2 \"Error: Found files not formatted by goimports\"\n\tfor f in $unformatted; do\n\t\techo >&2 $f\n\tdone\n\techo \"Please run 'goimports -w' for files listed.\"\n\texit 1\nfi\n\necho \"Run 'go vet'\"\nln -s `pwd` `pwd`/vendor/src/github.com/aws/session-manager-plugin\ngo vet ./src/...\n", "num_lines": 34}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"**********************************************\"\necho \"Creating bundle zip file Mac OS X amd64 Plugin\"\necho \"**********************************************\"\n\nrm -rf ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle\n\necho \"Creating bundle workspace\"\n\nmkdir -p ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/bin\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/NOTICE\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/THIRD-PARTY\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/RELEASENOTES.md\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/VERSION\ncp ${GO_SPACE}/bin/darwin_amd64_plugin/session-manager-plugin ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/bin/session-manager-plugin\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/seelog.xml.template\n\necho \"Copying install script\"\n\ncp ${GO_SPACE}/Tools/src/darwin/install ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/install\nchmod 755 ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/install;\n\ncd ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle/bin/; strip session-manager-plugin; cd ~-\n\necho \"Creating the bundle zip file\"\n\nif [ -f ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle.zip ]\nthen\n    rm ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle.zip\nfi\n\ncd ${GO_SPACE}/bin/darwin_amd64_plugin;\nzip -r ${GO_SPACE}/bin/darwin_amd64_plugin/sessionmanager-bundle.zip ./sessionmanager-bundle\n", "num_lines": 39}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"**********************************************\"\necho \"Creating bundle zip file Mac OS X arm64 Plugin\"\necho \"**********************************************\"\n\nrm -rf ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle\n\necho \"Creating bundle workspace\"\n\nmkdir -p ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/bin\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/NOTICE\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/THIRD-PARTY\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/RELEASENOTES.md\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/VERSION\ncp ${GO_SPACE}/bin/darwin_arm64_plugin/session-manager-plugin ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/bin/session-manager-plugin\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/seelog.xml.template\n\necho \"Copying install script\"\n\ncp ${GO_SPACE}/Tools/src/darwin/install ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/install\nchmod 755 ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/install;\n\ncd ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle/bin/; strip session-manager-plugin; cd ~-\n\necho \"Creating the bundle zip file\"\n\nif [ -f ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle.zip ]\nthen\n    rm ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle.zip\nfi\n\ncd ${GO_SPACE}/bin/darwin_arm64_plugin;\nzip -r ${GO_SPACE}/bin/darwin_arm64_plugin/sessionmanager-bundle.zip ./sessionmanager-bundle\n", "num_lines": 39}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"*********************************************\"\necho \"Creating deb file for Ubuntu Linux 386 Plugin\"\necho \"*********************************************\"\n\nrm -rf ${GO_SPACE}/bin/debian_386/debian\n\necho \"Creating debian folders\"\n\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/etc/init/\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/usr/share/lintian/overrides/\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/var/lib/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_386/debian/lib/systemd/system/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_386_plugin/session-manager-plugin ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/bin/\ncd ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/debian_386/debian/etc/init/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.service ${GO_SPACE}/bin/debian_386/debian/lib/systemd/system/\n\necho \"Copying debian package config files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/debian_386/debian/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/packaging/ubuntu_plugin/conffiles ${GO_SPACE}/bin/debian_386/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/preinst ${GO_SPACE}/bin/debian_386/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postinst ${GO_SPACE}/bin/debian_386/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/prerm ${GO_SPACE}/bin/debian_386/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postrm ${GO_SPACE}/bin/debian_386/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/lintian-overrides ${GO_SPACE}/bin/debian_386/debian/usr/share/lintian/overrides/sessionmanagerplugin\n\necho \"Constructing the control file\"\n\necho 'Package: session-manager-plugin' > ${GO_SPACE}/bin/debian_386/debian/control\necho 'Architecture: i386' >> ${GO_SPACE}/bin/debian_386/debian/control\necho -n 'Version: ' >> ${GO_SPACE}/bin/debian_386/debian/control\ncat ${GO_SPACE}/VERSION | tr -d \"\\n\" >> ${GO_SPACE}/bin/debian_386/debian/control\necho '-1' >> ${GO_SPACE}/bin/debian_386/debian/control\ncat ${GO_SPACE}/packaging/ubuntu_plugin/control >> ${GO_SPACE}/bin/debian_386/debian/control\n\necho \"Constructing the changelog file\"\n\necho -n 'session-manager-plugin (' > ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat VERSION | tr -d \"\\n\"  >> ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/changelog\necho '-1) unstable; urgency=low' >> ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat ${GO_SPACE}/packaging/ubuntu_plugin/changelog >> ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/changelog\n\ncp ${GO_SPACE}/packaging/ubuntu_plugin/debian-binary ${GO_SPACE}/bin/debian_386/debian/\n\necho \"Setting permissions as required by debian\"\n\ncd ${GO_SPACE}/bin/debian_386/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog\"\n\ncd ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\n\nrm ${GO_SPACE}/bin/debian_386/debian/usr/share/doc/sessionmanagerplugin/changelog\n\necho \"Creating tar\"\n\n# the below permissioning is required by debian\ncd ${GO_SPACE}/bin/debian_386/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_386/debian/; tar czf control.tar.gz control conffiles preinst postinst prerm postrm --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package\"\n\nar r ${GO_SPACE}/bin/debian_386/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_386/debian/debian-binary\nar r ${GO_SPACE}/bin/debian_386/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_386/debian/control.tar.gz\nar r ${GO_SPACE}/bin/debian_386/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_386/debian/data.tar.gz\ncp ${GO_SPACE}/bin/debian_386/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_386/session-manager-plugin.deb\nmv ${GO_SPACE}/bin/debian_386/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/.\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_386/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_386/\n\nchmod 755 ${GO_SPACE}/bin/debian_386/install.sh ${GO_SPACE}/bin/debian_386/uninstall.sh\n\necho \"Zip deb, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-ubuntu-386.tar.gz  -C ${GO_SPACE}/bin/debian_386/ session-manager-plugin.deb install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/debian_386/install.sh\nrm ${GO_SPACE}/bin/debian_386/uninstall.sh\n", "num_lines": 95}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"***********************************************\"\necho \"Creating deb file for Ubuntu Linux amd64 Plugin\"\necho \"***********************************************\"\n\nrm -rf ${GO_SPACE}/bin/debian_amd64/debian\n\necho \"Creating debian folders\"\n\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/etc/init/\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/usr/share/lintian/overrides/\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/var/lib/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_amd64/debian/lib/systemd/system/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_amd64_plugin/session-manager-plugin ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/bin/\ncd ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/debian_amd64/debian/etc/init/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.service ${GO_SPACE}/bin/debian_amd64/debian/lib/systemd/system/\n\necho \"Copying debian package config files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/debian_amd64/debian/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/packaging/ubuntu_plugin/conffiles ${GO_SPACE}/bin/debian_amd64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/preinst ${GO_SPACE}/bin/debian_amd64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postinst ${GO_SPACE}/bin/debian_amd64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/prerm ${GO_SPACE}/bin/debian_amd64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postrm ${GO_SPACE}/bin/debian_amd64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/lintian-overrides ${GO_SPACE}/bin/debian_amd64/debian/usr/share/lintian/overrides/sessionmanagerplugin\n\necho \"Constructing the control file\"\n\necho 'Package: session-manager-plugin' > ${GO_SPACE}/bin/debian_amd64/debian/control\necho 'Architecture: amd64' >> ${GO_SPACE}/bin/debian_amd64/debian/control\necho -n 'Version: ' >> ${GO_SPACE}/bin/debian_amd64/debian/control\ncat ${GO_SPACE}/VERSION | tr -d \"\\n\" >> ${GO_SPACE}/bin/debian_amd64/debian/control\necho '-1' >> ${GO_SPACE}/bin/debian_amd64/debian/control\ncat ${GO_SPACE}/packaging/ubuntu_plugin/control >> ${GO_SPACE}/bin/debian_amd64/debian/control\n\necho \"Constructing the changelog file\"\n\necho -n 'session-manager-plugin (' > ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat VERSION | tr -d \"\\n\"  >> ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/changelog\necho '-1) unstable; urgency=low' >> ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat ${GO_SPACE}/packaging/ubuntu_plugin/changelog >> ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/changelog\n\ncp ${GO_SPACE}/packaging/ubuntu_plugin/debian-binary ${GO_SPACE}/bin/debian_amd64/debian/\n\necho \"Setting permissions as required by debian\"\n\ncd ${GO_SPACE}/bin/debian_amd64/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog\"\n\ncd ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\n\nrm ${GO_SPACE}/bin/debian_amd64/debian/usr/share/doc/sessionmanagerplugin/changelog\n\necho \"Creating tar\"\n\n# the below permissioning is required by debian\ncd ${GO_SPACE}/bin/debian_amd64/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_amd64/debian/; tar czf control.tar.gz control conffiles preinst postinst prerm postrm --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package\"\n\nar r ${GO_SPACE}/bin/debian_amd64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_amd64/debian/debian-binary\nar r ${GO_SPACE}/bin/debian_amd64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_amd64/debian/control.tar.gz\nar r ${GO_SPACE}/bin/debian_amd64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_amd64/debian/data.tar.gz\ncp ${GO_SPACE}/bin/debian_amd64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_amd64/session-manager-plugin.deb\nmv ${GO_SPACE}/bin/debian_amd64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/.\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_amd64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_amd64/\n\nchmod 755 ${GO_SPACE}/bin/debian_amd64/install.sh ${GO_SPACE}/bin/debian_amd64/uninstall.sh\n\necho \"Zip deb, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-ubuntu-amd64.tar.gz  -C ${GO_SPACE}/bin/debian_amd64/ session-manager-plugin.deb install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/debian_amd64/install.sh\nrm ${GO_SPACE}/bin/debian_amd64/uninstall.sh\n", "num_lines": 95}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"***********************************************\"\necho \"Creating deb file for Ubuntu Linux arm64 Plugin\"\necho \"***********************************************\"\n\nrm -rf ${GO_SPACE}/bin/debian_arm64/debian\n\necho \"Creating debian folders\"\n\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/etc/init/\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/usr/share/lintian/overrides/\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/var/lib/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_arm64/debian/lib/systemd/system/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_arm64_plugin/session-manager-plugin ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/bin/\ncd ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/debian_arm64/debian/etc/init/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.service ${GO_SPACE}/bin/debian_arm64/debian/lib/systemd/system/\n\necho \"Copying debian package config files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/debian_arm64/debian/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/packaging/ubuntu_plugin/conffiles ${GO_SPACE}/bin/debian_arm64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/preinst ${GO_SPACE}/bin/debian_arm64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postinst ${GO_SPACE}/bin/debian_arm64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/prerm ${GO_SPACE}/bin/debian_arm64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postrm ${GO_SPACE}/bin/debian_arm64/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/lintian-overrides ${GO_SPACE}/bin/debian_arm64/debian/usr/share/lintian/overrides/sessionmanagerplugin\n\necho \"Constructing the control file\"\n\necho 'Package: session-manager-plugin' > ${GO_SPACE}/bin/debian_arm64/debian/control\necho 'Architecture: arm64' >> ${GO_SPACE}/bin/debian_arm64/debian/control\necho -n 'Version: ' >> ${GO_SPACE}/bin/debian_arm64/debian/control\ncat ${GO_SPACE}/VERSION | tr -d \"\\n\" >> ${GO_SPACE}/bin/debian_arm64/debian/control\necho '-1' >> ${GO_SPACE}/bin/debian_arm64/debian/control\ncat ${GO_SPACE}/packaging/ubuntu_plugin/control >> ${GO_SPACE}/bin/debian_arm64/debian/control\n\necho \"Constructing the changelog file\"\n\necho -n 'session-manager-plugin (' > ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat VERSION | tr -d \"\\n\"  >> ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/changelog\necho '-1) unstable; urgency=low' >> ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat ${GO_SPACE}/packaging/ubuntu_plugin/changelog >> ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/changelog\n\ncp ${GO_SPACE}/packaging/ubuntu_plugin/debian-binary ${GO_SPACE}/bin/debian_arm64/debian/\n\necho \"Setting permissions as required by debian\"\n\ncd ${GO_SPACE}/bin/debian_arm64/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog\"\n\ncd ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\n\nrm ${GO_SPACE}/bin/debian_arm64/debian/usr/share/doc/sessionmanagerplugin/changelog\n\necho \"Creating tar\"\n\n# the below permissioning is required by debian\ncd ${GO_SPACE}/bin/debian_arm64/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_arm64/debian/; tar czf control.tar.gz control conffiles preinst postinst prerm postrm --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package\"\n\nar r ${GO_SPACE}/bin/debian_arm64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm64/debian/debian-binary\nar r ${GO_SPACE}/bin/debian_arm64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm64/debian/control.tar.gz\nar r ${GO_SPACE}/bin/debian_arm64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm64/debian/data.tar.gz\ncp ${GO_SPACE}/bin/debian_arm64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm64/session-manager-plugin.deb\nmv ${GO_SPACE}/bin/debian_arm64/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/.\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_arm64/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_arm64/\n\nchmod 755 ${GO_SPACE}/bin/debian_arm64/install.sh ${GO_SPACE}/bin/debian_arm64/uninstall.sh\n\necho \"Zip deb, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-ubuntu-arm64.tar.gz  -C ${GO_SPACE}/bin/debian_arm64/ session-manager-plugin.deb install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/debian_arm64/install.sh\nrm ${GO_SPACE}/bin/debian_arm64/uninstall.sh\n", "num_lines": 95}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"*********************************************\"\necho \"Creating deb file for Ubuntu Linux arm Plugin\"\necho \"*********************************************\"\n\nrm -rf ${GO_SPACE}/bin/debian_arm/debian\n\necho \"Creating debian folders\"\n\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/etc/init/\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/usr/share/lintian/overrides/\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/var/lib/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/debian_arm/debian/lib/systemd/system/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_arm_plugin/session-manager-plugin ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/bin/\ncd ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/debian_arm/debian/etc/init/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/session-manager-plugin.service ${GO_SPACE}/bin/debian_arm/debian/lib/systemd/system/\n\necho \"Copying debian package config files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/debian_arm/debian/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/packaging/ubuntu_plugin/conffiles ${GO_SPACE}/bin/debian_arm/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/preinst ${GO_SPACE}/bin/debian_arm/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postinst ${GO_SPACE}/bin/debian_arm/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/prerm ${GO_SPACE}/bin/debian_arm/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/postrm ${GO_SPACE}/bin/debian_arm/debian/\ncp ${GO_SPACE}/packaging/ubuntu_plugin/lintian-overrides ${GO_SPACE}/bin/debian_arm/debian/usr/share/lintian/overrides/sessionmanagerplugin\n\necho \"Constructing the control file\"\n\necho 'Package: session-manager-plugin' > ${GO_SPACE}/bin/debian_arm/debian/control\necho 'Architecture: armhf' >> ${GO_SPACE}/bin/debian_arm/debian/control\necho -n 'Version: ' >> ${GO_SPACE}/bin/debian_arm/debian/control\ncat ${GO_SPACE}/VERSION | tr -d \"\\n\" >> ${GO_SPACE}/bin/debian_arm/debian/control\necho '-1' >> ${GO_SPACE}/bin/debian_arm/debian/control\ncat ${GO_SPACE}/packaging/ubuntu_plugin/control >> ${GO_SPACE}/bin/debian_arm/debian/control\n\necho \"Constructing the changelog file\"\n\necho -n 'session-manager-plugin (' > ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat VERSION | tr -d \"\\n\"  >> ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/changelog\necho '-1) unstable; urgency=low' >> ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/changelog\ncat ${GO_SPACE}/packaging/ubuntu_plugin/changelog >> ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/changelog\n\ncp ${GO_SPACE}/packaging/ubuntu_plugin/debian-binary ${GO_SPACE}/bin/debian_arm/debian/\n\necho \"Setting permissions as required by debian\"\n\ncd ${GO_SPACE}/bin/debian_arm/; find ./debian -type d | xargs chmod 755; cd ~-\n\necho \"Compressing changelog\"\n\ncd ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/; export GZIP=-9; tar cvzf changelog.gz changelog --owner=0 --group=0 ; cd ~-\n\nrm ${GO_SPACE}/bin/debian_arm/debian/usr/share/doc/sessionmanagerplugin/changelog\n\necho \"Creating tar\"\n\n# the below permissioning is required by debian\ncd ${GO_SPACE}/bin/debian_arm/debian/; tar czf data.tar.gz usr etc lib --owner=0 --group=0 ; cd ~-\ncd ${GO_SPACE}/bin/debian_arm/debian/; tar czf control.tar.gz control conffiles preinst postinst prerm postrm --owner=0 --group=0 ; cd ~-\n\necho \"Constructing the deb package\"\n\nar r ${GO_SPACE}/bin/debian_arm/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm/debian/debian-binary\nar r ${GO_SPACE}/bin/debian_arm/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm/debian/control.tar.gz\nar r ${GO_SPACE}/bin/debian_arm/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm/debian/data.tar.gz\ncp ${GO_SPACE}/bin/debian_arm/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/debian_arm/session-manager-plugin.deb\nmv ${GO_SPACE}/bin/debian_arm/session-manager-plugin-`cat ${GO_SPACE}/VERSION`-1.deb ${GO_SPACE}/bin/.\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/ubuntu/install.sh ${GO_SPACE}/bin/debian_arm/\ncp ${GO_SPACE}/Tools/src/update/ubuntu/uninstall.sh ${GO_SPACE}/bin/debian_arm/\n\nchmod 755 ${GO_SPACE}/bin/debian_arm/install.sh ${GO_SPACE}/bin/debian_arm/uninstall.sh\n\necho \"Zip deb, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-ubuntu-arm.tar.gz  -C ${GO_SPACE}/bin/debian_arm/ session-manager-plugin.deb install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/debian_arm/install.sh\nrm ${GO_SPACE}/bin/debian_arm/uninstall.sh\n", "num_lines": 95}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"***********************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL 386\"\necho \"***********************************************\"\n\nrm -rf ${GO_SPACE}/bin/linux_386/linux\n\necho \"Creating rpmbuild workspace\"\n\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/usr/bin/\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/etc/amazon/ssmcli/\nmkdir -p ${GO_SPACE}/bin/linux_386/linux/var/lib/amazon/ssmcli/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_386/ssmcli ${GO_SPACE}/bin/linux_386/linux/usr/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/linux_386/linux/etc/amazon/ssmcli/seelog.xml.template\ncp ${GO_SPACE}/packaging/linux/ssmcli.conf ${GO_SPACE}/bin/linux_386/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux/ssmcli.service ${GO_SPACE}/bin/linux_386/linux/etc/systemd/system/\ncd ${GO_SPACE}/bin/linux_386/linux/usr/bin/; strip --strip-unneeded ssmcli; cd ~-\n\necho \"Creating the rpm package\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux/ssmcli.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/linux_386/linux\"\n\nsetarch i386 rpmbuild --target i386 -bb --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/linux_386/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\n\ncp ${GO_SPACE}/bin/linux_386/linux/rpmbuild/RPMS/i386/*.rpm ${GO_SPACE}/bin/\ncp ${GO_SPACE}/bin/linux_386/linux/rpmbuild/RPMS/i386/*.rpm ${GO_SPACE}/bin/linux_386/ssmcli.rpm\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_386/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_386/\n\nchmod 755 ${GO_SPACE}/bin/linux_386/install.sh ${GO_SPACE}/bin/linux_386/uninstall.sh\n\necho \"Zip rpm, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/ssmcli/`cat ${GO_SPACE}/VERSION`/ssmcli-linux-386.tar.gz  -C ${GO_SPACE}/bin/linux_386/ ssmcli.rpm install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/linux_386/install.sh\nrm ${GO_SPACE}/bin/linux_386/uninstall.sh", "num_lines": 54}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"******************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL 386 Plugin\"\necho \"******************************************************\"\n\nrm -rf ${GO_SPACE}/bin/linux_386_plugin/linux\n\necho \"Creating rpmbuild workspace\"\n\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/bin/\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/etc/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/linux_386_plugin/linux/var/lib/amazon/sessionmanagerplugin/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/bin/linux_386_plugin/session-manager-plugin ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/linux_386_plugin/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.service ${GO_SPACE}/bin/linux_386_plugin/linux/etc/systemd/system/\ncd ${GO_SPACE}/bin/linux_386_plugin/linux/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\n\necho \"Creating the rpm package\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/linux_386_plugin/linux\"\n\nsetarch x86_64 rpmbuild -bb --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/linux_386_plugin/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\n\ncp ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/\ncp ${GO_SPACE}/bin/linux_386_plugin/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/linux_386_plugin/session-manager-plugin.rpm\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_386_plugin/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_386_plugin/\n\nchmod 755 ${GO_SPACE}/bin/linux_386_plugin/install.sh ${GO_SPACE}/bin/linux_386_plugin/uninstall.sh\n\necho \"Zip rpm, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-linux-386.tar.gz  -C ${GO_SPACE}/bin/linux_386_plugin/ session-manager-plugin.rpm install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/linux_386_plugin/install.sh\nrm ${GO_SPACE}/bin/linux_386_plugin/uninstall.sh", "num_lines": 61}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"*************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL amd64\"\necho \"*************************************************\"\n\nrm -rf ${GO_SPACE}/bin/linux_amd64/linux\n\necho \"Creating rpmbuild workspace\"\n\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/usr/bin/\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/etc/amazon/ssmcli/\nmkdir -p ${GO_SPACE}/bin/linux_amd64/linux/var/lib/amazon/ssmcli/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/bin/linux_amd64/ssmcli ${GO_SPACE}/bin/linux_amd64/linux/usr/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/linux_amd64/linux/etc/amazon/ssmcli/seelog.xml.template\ncp ${GO_SPACE}/packaging/linux/ssmcli.conf ${GO_SPACE}/bin/linux_amd64/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux/ssmcli.service ${GO_SPACE}/bin/linux_amd64/linux/etc/systemd/system/\ncd ${GO_SPACE}/bin/linux_amd64/linux/usr/bin/; strip --strip-unneeded ssmcli; cd ~-\n\necho \"Creating the rpm package\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux/ssmcli.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/linux_amd64/linux\"\n\nsetarch x86_64 rpmbuild -bb --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/linux_amd64/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\n\ncp ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/\ncp ${GO_SPACE}/bin/linux_amd64/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/linux_amd64/ssmcli.rpm\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_amd64/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_amd64/\n\nchmod 755 ${GO_SPACE}/bin/linux_amd64/install.sh ${GO_SPACE}/bin/linux_amd64/uninstall.sh\n\necho \"Zip rpm, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/ssmcli/`cat ${GO_SPACE}/VERSION`/ssmcli-linux-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64/ ssmcli.rpm install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/linux_amd64/install.sh\nrm ${GO_SPACE}/bin/linux_amd64/uninstall.sh", "num_lines": 54}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"********************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL amd64 Plugin\"\necho \"********************************************************\"\n\nrm -rf ${GO_SPACE}/bin/linux_amd64_plugin/linux\n\necho \"Creating rpmbuild workspace\"\n\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/bin/\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/etc/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/linux_amd64_plugin/linux/var/lib/amazon/sessionmanagerplugin/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/bin/linux_amd64_plugin/session-manager-plugin ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/linux_amd64_plugin/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.service ${GO_SPACE}/bin/linux_amd64_plugin/linux/etc/systemd/system/\ncd ${GO_SPACE}/bin/linux_amd64_plugin/linux/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\n\necho \"Creating the rpm package\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/linux_amd64_plugin/linux\"\n\nsetarch x86_64 rpmbuild -bb --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/linux_amd64_plugin/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\n\ncp ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/\ncp ${GO_SPACE}/bin/linux_amd64_plugin/linux/rpmbuild/RPMS/x86_64/*.rpm ${GO_SPACE}/bin/linux_amd64_plugin/session-manager-plugin.rpm\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_amd64_plugin/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_amd64_plugin/\n\nchmod 755 ${GO_SPACE}/bin/linux_amd64_plugin/install.sh ${GO_SPACE}/bin/linux_amd64_plugin/uninstall.sh\n\necho \"Zip rpm, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-linux-amd64.tar.gz  -C ${GO_SPACE}/bin/linux_amd64_plugin/ session-manager-plugin.rpm install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/linux_amd64_plugin/install.sh\nrm ${GO_SPACE}/bin/linux_amd64_plugin/uninstall.sh", "num_lines": 61}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"********************************************************\"\necho \"Creating rpm file for Amazon Linux and RHEL arm64 Plugin\"\necho \"********************************************************\"\n\nrm -rf ${GO_SPACE}/bin/linux_arm64_plugin/linux\n\necho \"Creating rpmbuild workspace\"\n\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/SPECS\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/COORD_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/DATA_SOURCES\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/BUILD\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/RPMS\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/SRPMS\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/bin/\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/bin/\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/etc/init/\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/etc/systemd/system/\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/etc/amazon/sessionmanagerplugin/\nmkdir -p ${GO_SPACE}/bin/linux_arm64_plugin/linux/var/lib/amazon/sessionmanagerplugin/\n\necho \"Copying application files\"\n\ncp ${GO_SPACE}/LICENSE ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/LICENSE\ncp ${GO_SPACE}/NOTICE ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/NOTICE\ncp ${GO_SPACE}/README.md ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/THIRD-PARTY\ncp ${GO_SPACE}/VERSION ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/VERSION\ncp ${GO_SPACE}/bin/linux_arm64_plugin/session-manager-plugin ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/bin/\ncp ${GO_SPACE}/seelog_unix.xml ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/seelog.xml.template\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.conf ${GO_SPACE}/bin/linux_arm64_plugin/linux/etc/init/\ncp ${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.service ${GO_SPACE}/bin/linux_arm64_plugin/linux/etc/systemd/system/\ncd ${GO_SPACE}/bin/linux_arm64_plugin/linux/usr/local/sessionmanagerplugin/bin/; strip --strip-unneeded session-manager-plugin; cd ~-\n\necho \"Creating the rpm package\"\n\nSPEC_FILE=\"${GO_SPACE}/packaging/linux_plugin/session-manager-plugin.spec\"\nBUILD_ROOT=\"${GO_SPACE}/bin/linux_arm64_plugin/linux\"\n\nrpmbuild -bb --target aarch64 --define \"rpmversion `cat ${GO_SPACE}/VERSION`\" --define \"_topdir bin/linux_arm64_plugin/linux/rpmbuild\" --buildroot ${BUILD_ROOT} ${SPEC_FILE}\n\necho \"Copying rpm files to bin\"\n\ncp ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/RPMS/aarch64/*.rpm ${GO_SPACE}/bin/\ncp ${GO_SPACE}/bin/linux_arm64_plugin/linux/rpmbuild/RPMS/aarch64/*.rpm ${GO_SPACE}/bin/linux_arm64_plugin/session-manager-plugin.rpm\n\necho \"Copying install and uninstall script to bin\"\n\ncp ${GO_SPACE}/Tools/src/update/linux/install.sh ${GO_SPACE}/bin/linux_arm64_plugin/\ncp ${GO_SPACE}/Tools/src/update/linux/uninstall.sh ${GO_SPACE}/bin/linux_arm64_plugin/\n\nchmod 755 ${GO_SPACE}/bin/linux_arm64_plugin/install.sh ${GO_SPACE}/bin/linux_arm64_plugin/uninstall.sh\n\necho \"Zip rpm, install and uninstall files\"\n\ntar -zcvf ${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-linux-arm64.tar.gz  -C ${GO_SPACE}/bin/linux_arm64_plugin/ session-manager-plugin.rpm install.sh uninstall.sh\n\nrm ${GO_SPACE}/bin/linux_arm64_plugin/install.sh\nrm ${GO_SPACE}/bin/linux_arm64_plugin/uninstall.sh", "num_lines": 61}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows 386 Plugin\"\necho \"****************************************\"\n\nBIN_FOLDER=${GO_SPACE}/bin\nBUILD_FOLDER=${BIN_FOLDER}/windows_386_plugin\nPACKAGE_FOLDER=${BUILD_FOLDER}/windows\n\nrm -rf ${PACKAGE_FOLDER}\n\necho \"Creating windows folders\"\n\nmkdir -p ${PACKAGE_FOLDER}\n\necho \"Copying application files\"\n\nmkdir -p ${PACKAGE_FOLDER}/bin\ncp ${BUILD_FOLDER}/session-manager-plugin.exe ${PACKAGE_FOLDER}/bin/session-manager-plugin.exe\ncp ${GO_SPACE}/seelog_windows.xml.template ${PACKAGE_FOLDER}/seelog.xml.template\n\necho \"Copying windows package config files\"\n\ncp ${GO_SPACE}/LICENSE ${PACKAGE_FOLDER}/LICENSE\ncp ${GO_SPACE}/NOTICE ${PACKAGE_FOLDER}/NOTICE\ncp ${GO_SPACE}/README.md ${PACKAGE_FOLDER}/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${PACKAGE_FOLDER}/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${PACKAGE_FOLDER}/THIRD-PARTY\n\necho \"Constructing the zip package\"\n\nif [ -f ${PACKAGE_FOLDER}/session-manager-plugin.zip ]\nthen\n    rm ${PACKAGE_FOLDER}/session-manager-plugin.zip\nfi\ncd ${PACKAGE_FOLDER}\nzip -r package *\n\ncp ${GO_SPACE}/Tools/src/update/windows/install.bat ${PACKAGE_FOLDER}/\ncp ${GO_SPACE}/Tools/src/update/windows/uninstall.bat ${PACKAGE_FOLDER}/\n\nWINDOWS_386_ZIP=${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-windows-386.zip\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_FOLDER}/package.zip\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_FOLDER}/install.bat\nzip -j ${WINDOWS_386_ZIP} ${PACKAGE_FOLDER}/uninstall.bat\n\ncp ${WINDOWS_386_ZIP} ${BUILD_FOLDER}\nrm -rf ${PACKAGE_FOLDER}", "num_lines": 48}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"****************************************\"\necho \"Creating zip file for Windows amd64 plugin\"\necho \"****************************************\"\n\nBIN_FOLDER=${GO_SPACE}/bin\nBUILD_FOLDER=${BIN_FOLDER}/windows_amd64_plugin\nPACKAGE_FOLDER=${BUILD_FOLDER}/windows\n\nrm -rf ${PACKAGE_FOLDER}\n\necho \"Creating windows folders\"\n\nmkdir -p ${PACKAGE_FOLDER}\n\necho \"Copying application files\"\n\nmkdir -p ${PACKAGE_FOLDER}/bin\ncp ${BUILD_FOLDER}/session-manager-plugin.exe ${PACKAGE_FOLDER}/bin/session-manager-plugin.exe\ncp ${GO_SPACE}/seelog_windows.xml.template ${PACKAGE_FOLDER}/seelog.xml.template\n\necho \"Copying windows package config files\"\n\ncp ${GO_SPACE}/LICENSE ${PACKAGE_FOLDER}/LICENSE\ncp ${GO_SPACE}/NOTICE ${PACKAGE_FOLDER}/NOTICE\ncp ${GO_SPACE}/README.md ${PACKAGE_FOLDER}/README.md\ncp ${GO_SPACE}/RELEASENOTES.md ${PACKAGE_FOLDER}/RELEASENOTES.md\ncp ${GO_SPACE}/THIRD-PARTY ${PACKAGE_FOLDER}/THIRD-PARTY\n\necho \"Constructing the zip package\"\n\nif [ -f ${PACKAGE_FOLDER}/session-manager-plugin.zip ]\nthen\n    rm ${PACKAGE_FOLDER}/session-manager-plugin.zip\nfi\ncd ${PACKAGE_FOLDER}\nzip -r package *\n\ncp ${GO_SPACE}/Tools/src/update/windows/install.bat ${PACKAGE_FOLDER}/\ncp ${GO_SPACE}/Tools/src/update/windows/uninstall.bat ${PACKAGE_FOLDER}/\n\nWINDOWS_AMD64_ZIP=${GO_SPACE}/bin/updates/sessionmanagerplugin/`cat ${GO_SPACE}/VERSION`/session-manager-plugin-windows-amd64.zip\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_FOLDER}/package.zip\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_FOLDER}/install.bat\nzip -j ${WINDOWS_AMD64_ZIP} ${PACKAGE_FOLDER}/uninstall.bat\n\ncp ${WINDOWS_AMD64_ZIP} ${BUILD_FOLDER}\nrm -rf ${PACKAGE_FOLDER}", "num_lines": 48}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ $(/sbin/init --version 2> /dev/null) =~ upstart ]]; then\n\techo \"upstart detected\"\n\techo \"Installing ssmcli\" \n\trpm -U ssmcli.rpm\n\tssmcliVersion=$(rpm -q --qf '%{VERSION}\\n' ssmcli)\n\techo \"Installed version: $ssmcliVersion\"\n\techo \"starting ssmcli\"\n\t/sbin/start ssmcli\n\techo \"$(status ssmcli)\"\nelif [[ $(systemctl 2> /dev/null) =~ -\\.mount ]]; then\n\tif [[ \"$(systemctl is-active ssmcli)\" == \"active\" ]]; then\n\t\techo \"-> ssmcli is running\"\n\t\techo \"Stopping the ssmcli\"\n\t\techo \"$(systemctl stop ssmcli)\"\n\t\techo \"ssmcli stopped\"\n\t\techo \"$(systemctl daemon-reload)\"\n\t\techo \"Reload daemon\"\t\n\telse\n\t\techo \"-> ssmcli is not running on the machine\"\n\tfi\n\t\t\n\techo \"Installing ssmcli\" \n\techo \"$(rpm -U ssmcli.rpm)\"\n\n\techo \"Starting ssmcli\"\n\t$(systemctl daemon-reload)\n\t$(systemctl start ssmcli)\n\techo \"$(systemctl status ssmcli)\"\nelse\n\techo \"ssmcli is not installed on this machine\"\nfi\n", "num_lines": 34}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Uninstalling ssmcli\"\n\nif [[ $(/sbin/init --version 2> /dev/null) =~ upstart ]]; then\n\techo \"Checking if the ssmcli is installed\" \n\tif [ \"$(rpm -q ssmcli)\" != \"package ssmcli is not installed\" ]; then\n\t\techo \"-> ssmcli is installed on this machine\"\n\t\techo \"Uninstalling the ssmcli\" \t\n\t\trpm --erase ssmcli\n\t\tsleep 1\n\telse\n\t\techo \"-> ssmcli is not installed on this machine\"\n\tfi\nelif [[ $(systemctl 2> /dev/null) =~ -\\.mount ]]; then\n\techo \"Checking if the ssmcli is installed\" \n\tif [[ \"$(systemctl status ssmcli)\" != *\"Loaded: not-found\"* ]]; then\n\t\techo \"-> ssmcli is installed on this machine\"\n\t\techo \"Uninstalling the ssmcli\" \t\n\t\trpm --erase ssmcli\n\t\tsleep 1\n\telse\n\t\techo \"-> ssmcli is not installed on this machine\"\n\tfi\nelse\n\techo \"ssmcli is not installed on this machine\"\nfi", "num_lines": 27}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Installing ubuntu pkg\"\n\nif [[ \"$(cat /proc/1/comm)\" == \"init\" ]]; then\n    if [ \"$(dpkg -s ssmcli | grep 'Status:')\" == \"Status: install ok installed\" ]; then\n\t    # echo \"-> ssmcli is installed in this instance\"\n\t    # stop the ssmcli if it is running\n\t    # echo \"Checking if the ssmcli is running\"\n\t    if [ \"$(status ssmcli)\" != \"ssmcli stop/waiting\" ]; then\n\t\t    # echo \"-> ssmcli is running in the instance\"\n  \t\t    # echo \"Stopping the ssmcli\"\n  \t\t    /sbin/stop ssmcli\n  \t\t    sleep 1\n\t    fi\n    fi\n\n    # echo \"Installing ssmcli\"\n    dpkg -i ssmcli.deb\n\n\n    # echo \"Starting ssmcli\"\n    /sbin/start ssmcli\n    # echo \"Status\"\n    status ssmcli\n\nelif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n\tif [[ \"$(systemctl is-active ssmcli)\" == \"active\" ]]; then\n\t\t# echo \"-> ssmcli is running in the instance\"\n\t\tsystemctl stop ssmcli\n\t\t# echo \"ssmcli stopped\"\n\t\tsystemctl daemon-reload\n\t\t# echo \"Reload daemon\"\n\telse\n\t\techo \"-> ssmcli is not running in the instance\"\n\tfi\n\n\t# echo \"Installing ssmcli\"\n\tdpkg -i ssmcli.deb\n\n\t# echo \"Starting ssmcli\"\n\tsystemctl daemon-reload\n\tsystemctl start ssmcli\n\tsystemctl status ssmcli\nelse\n\n    echo \"ssmcli is not installed on this machine\"\nfi", "num_lines": 48}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!bin/bash\n\necho \"Uninstalling deb pkg\"\n\n# echo \"Checking if the ssmcli is installed\"\n# uninstall the ssmcli if it is present\nif [[ \"$(cat /proc/1/comm)\" == \"init\" ]]; then\n    if [ \"$(dpkg -s ssmcli | grep 'Status:')\" == \"Status: install ok installed\" ]; then\n        # echo \"-> ssmcli is installed in this instance\"\n        # stop the ssmcli if it is running\n        # echo \"Checking if the ssmcli is running\"\n        if [ \"$(status ssmcli)\" != \"ssmcli stop/waiting\" ]; then\n            # echo \"-> ssmcli is running in the instance\"\n            # echo \"Stopping the ssmcli\"\n            /sbin/stop ssmcli\n            sleep 1\n        else\n            echo \"-> ssmcli is not running\"\n        fi\n        # echo \"Uninstalling the ssmcli\"\n        dpkg -r ssmcli\n        sleep 1\n    else\n        echo \"-> ssmcli is not installed on this machine\"\n    fi\nelif [[ \"$(cat /proc/1/comm)\" == \"systemd\" ]]; then\n\tif [[ \"$(systemctl is-active ssmcli)\" == \"active\" ]]; then\n\t\t# echo \"-> ssmcli is running in the instance\"\n\t\t# echo \"Stopping the ssmcli\"\n\t\tsystemctl stop ssmcli\n\t\t# echo \"ssmcli stopped\"\n\t\tsystemctl daemon-reload\n\t\t# echo \"Reload daemon\"\n\telse\n\t\techo \"-> ssmcli is not running in the instance\"\n\tfi\n\n\t# echo \"Uninstalling ssmcli\"\n\tdpkg -r ssmcli\n\nelse\n    echo \"ssmcli is not installed on this machine\"\nfi", "num_lines": 43}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"./mksyscall.pl -l32 -plan9\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 139}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\t# Use then new build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd -arm\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd -arm\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 189}
{"repo_name": "session-manager-plugin", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\tif [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\t\techo 1>&2 \"In the new build system, mkerrors should not be called directly.\"\n\t\techo 1>&2 \"See README.md\"\n\t\texit 1\n\tfi\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capability.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/keyctl.h>\n#include <linux/magic.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/stat.h>\n#include <linux/watchdog.h>\n#include <linux/hdreg.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 ~ /^[A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 604}
{"repo_name": "smithy-go", "repo_creator": "aws", "programming_language": "Shell", "code": "#1/usr/bin/env bash\n\nPROJECT_DIR=\"\"\nSMITHY_SOURCE_DIR=$(cd `dirname $0` && pwd)\n\nusage() {\n  echo \"Usage: $0 [-s SMITHY_SOURCE_DIR] [-d PROJECT_DIR]\" 1>&2\n  exit 1\n}\n\nwhile getopts \"hs:d:\" options; do\n  case \"${options}\" in\n  s)\n    SMITHY_SOURCE_DIR=${OPTARG}\n    if [ \"$SMITHY_SOURCE_DIR\" == \"\" ]; then\n      echo \"path to smithy-go source directory is required\" || exit\n      usage\n    fi\n    ;;\n  d)\n    PROJECT_DIR=${OPTARG}\n    ;;\n  h)\n    usage\n    ;;\n  *)\n    usage\n    ;;\n  esac\ndone\n\nif [ \"$PROJECT_DIR\" != \"\" ]; then\n  cd $PROJECT_DIR || exit\nfi\n\ngo mod graph | awk '{print $1}' | cut -d '@' -f 1 | sort | uniq | grep \"github.com/aws/smithy-go\" | while read x; do\n  repPath=${x/github.com\\/aws\\/smithy-go/${SMITHY_SOURCE_DIR}}\n  echo -replace $x=$repPath\ndone | xargs go mod edit\n", "num_lines": 40}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nPKGS=\"cpu disk docker host load mem net process\"\n\nGOOS=$(go env GOOS)\nGOARCH=$(go env GOARCH)\nGOARCH=$(go env GOARCH)\n\nfor DIR in . v3\ndo\n        (cd \"$DIR\" || exit\n        for PKG in $PKGS\n        do\n                if [ -e \"${PKG}/types_${GOOS}.go\" ]; then\n                        (echo \"// +build $GOOS\"\n                        echo \"// +build $GOARCH\"\n                        go tool cgo -godefs \"${PKG}/types_${GOOS}.go\") | gofmt > \"${PKG}/${PKG}_${GOOS}_${GOARCH}.go\"\n                fi\n        done)\ndone\n", "num_lines": 21}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eu\n\n# this scripts is used when migrating v2 to v3.\n# usage: cd ${GOPATH}/src/github.com/shirou/gopsutil && bash tools/v3migration/v3migration.sh\n\n\n\nDIR=\"$(cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd)\"\nROOT=$(cd \"${DIR}\"/../.. && pwd)\n\n\n## 1. refresh\ncd \"${ROOT}\"\n\n/bin/rm -rf v3\n\n## 2. copy directories\n# docker is removed, #464 will be fixed\nmkdir -p v3\ncp -rp cpu disk docker host internal load mem net process winservices v3\ncp Makefile v3\n\n# build migartion tool\ngo build -o v3/v3migration \"${DIR}\"/v3migration.go\n\n\nV3DIR=$(cd \"${ROOT}\"/v3 && pwd)\ncd \"${V3DIR}\"\n\n## 3. mod\ngo mod init\n\n###  change import path\nfind . -name \"*.go\" -print0 | xargs -0 -I@ sed -i 's|\"github.com/shirou/gopsutil/|\"github.com/shirou/gopsutil/v3/|g' @\n\n############ Issues\n\n# #429 process.NetIOCounters is pointless on Linux\n./v3migration \"$(pwd)\" 429\nsed -i '/NetIOCounters/d' process/process.go\nsed -i \"/github.com\\/shirou\\/gopsutil\\/v3\\/net/d\" process/process_bsd.go\n\n\n# #464 CgroupMem : fix typo and wrong file names\nsed -i 's|memoryLimitInBbytes|memoryLimitInBytes|g' docker/docker.go\nsed -i 's|memoryLimitInBbytes|memory.limit_in_bytes|g' docker/docker_linux.go\nsed -i 's|memoryFailcnt|memory.failcnt|g' docker/docker_linux.go\n\n\n# fix #346\nsed -i 's/Soft     int32/Soft     uint64/' process/process.go\nsed -i 's/Hard     int32/Hard     uint64/' process/process.go\nsed -i 's| //TODO too small. needs to be uint64||' process/process.go\nsed -i 's|limitToInt(val string) (int32, error)|limitToUint(val string) (uint64, error)|' process/process_*.go\nsed -i 's|limitToInt|limitToUint|' process/process_*.go\nsed -i 's|return int32(res), nil|return uint64(res), nil|' process/process_*.go\nsed -i 's|math.MaxInt32|math.MaxUint64|' process/process_*.go\n\n# fix #545\n# variable names\nsed -i 's|WritebackTmp|WriteBackTmp|g' mem/*.go\nsed -i 's|Writeback|WriteBack|g' mem/*.go\nsed -i 's|SReclaimable|Sreclaimable|g' mem/*.go\nsed -i 's|SUnreclaim|Sunreclaim|g' mem/*.go\nsed -i 's|VMallocTotal|VmallocTotal|g' mem/*.go\nsed -i 's|VMallocUsed|VmallocUsed|g' mem/*.go\nsed -i 's|VMallocChunk|VmallocChunk|g' mem/*.go\n\n# json field name\nsed -i 's|hostid|hostId|g' host/host.go\nsed -i 's|hostid|hostId|g' host/host_test.go\nsed -i 's|sensorTemperature|temperature|g' host/host.go\nsed -i 's|sensorTemperature|temperature|g' host/host_test.go\n\nsed -i 's|writeback|writeBack|g' mem/*.go\nsed -i 's|writeBacktmp|writeBackTmp|g' mem/*.go\nsed -i 's|pagetables|pageTables|g' mem/*.go\nsed -i 's|swapcached|swapCached|g' mem/*.go\nsed -i 's|commitlimit|commitLimit|g' mem/*.go\nsed -i 's|committedas|committedAS|g' mem/*.go\nsed -i 's|hightotal|highTotal|g' mem/*.go\nsed -i 's|highfree|highFree|g' mem/*.go\nsed -i 's|lowtotal|lowTotal|g' mem/*.go\nsed -i 's|lowfree|lowFree|g' mem/*.go\nsed -i 's|swaptotal|swapTotal|g' mem/*.go\nsed -i 's|swapfree|swapFree|g' mem/*.go\nsed -i 's|vmalloctotal|vmallocTotal|g' mem/*.go\nsed -i 's|vmallocused|vmallocUsed|g' mem/*.go\nsed -i 's|vmallocchunk|vmallocChunk|g' mem/*.go\nsed -i 's|hugepagestotal|hugePagesTotal|g' mem/*.go\nsed -i 's|hugepagesfree|hugePagesFree|g' mem/*.go\nsed -i 's|hugepagesize|hugePageSize|g' mem/*.go\nsed -i 's|pgin|pgIn|g' mem/*.go\nsed -i 's|pgout|pgOut|g' mem/*.go\nsed -i 's|pgfault|pgFault|g' mem/*.go\nsed -i 's|pgmajfault|pgMajFault|g' mem/*.go\n\nsed -i 's|hardwareaddr|hardwareAddr|g' net/*.go\nsed -i 's|conntrackCount|connTrackCount|g' net/*.go\nsed -i 's|conntrackMax|connTrackMax|g' net/*.go\nsed -i 's|delete_list|deleteList|g' net/*.go\nsed -i 's|insert_failed|insertFailed|g' net/*.go\nsed -i 's|early_drop|earlyDrop|g' net/*.go\nsed -i 's|expect_create|expectCreate|g' net/*.go\nsed -i 's|expect_delete|expectDelete|g' net/*.go\nsed -i 's|search_restart|searchRestart|g' net/*.go\nsed -i 's|icmp_error|icmpError|g' net/*.go\nsed -i 's|expect_new|expectNew|g' net/*.go\n\n\n\n# fix no more public API/types/constants defined only for some platforms\n\nsed -i 's|CTLKern|ctlKern|g' cpu/*.go\nsed -i 's|CPNice|cpNice|g' cpu/*.go\nsed -i 's|CPSys|cpSys|g' cpu/*.go\nsed -i 's|CPIntr|cpIntr|g' cpu/*.go\nsed -i 's|CPIdle|cpIdle|g' cpu/*.go\nsed -i 's|CPUStates|cpUStates|g' cpu/*.go\nsed -i 's|CTLKern|ctlKern|g' cpu/cpu_openbsd.go\nsed -i 's|CTLHw|ctlHw|g' cpu/cpu_openbsd.go\nsed -i 's|SMT|sMT|g' cpu/cpu_openbsd.go\nsed -i 's|KernCptime|kernCptime|g' cpu/cpu_openbsd.go\nsed -i 's|KernCptime2|kernCptime2|g' cpu/cpu_openbsd.go\nsed -i 's|Win32_Processor|win32Processor|g' cpu/cpu_windows.go\n\nsed -i 's|DEVSTAT_NO_DATA|devstat_NO_DATA|g' disk/*.go\nsed -i 's|DEVSTAT_READ|devstat_READ|g' disk/*.go\nsed -i 's|DEVSTAT_WRITE|devstat_WRITE|g' disk/*.go\nsed -i 's|DEVSTAT_FREE|devstat_FREE|g' disk/*.go\nsed -i 's|Devstat|devstat|g' disk/*.go\nsed -i 's|Bintime|bintime|g' disk/*.go\nsed -i 's|SectorSize|sectorSize|g' disk/disk_linux.go\nsed -i 's|FileFileCompression|fileFileCompression|g' disk/disk_windows.go\nsed -i 's|FileReadOnlyVolume|fileReadOnlyVolume|g' disk/disk_windows.go\n\nsed -i 's|USER_PROCESS|user_PROCESS|g' host/host_*.go\nsed -i 's|LSB|lsbStruct|g' host/host_linux*\n\nsed -i 's| BcacheStats | bcacheStats |g' mem/*.go\n\nsed -i 's|TCPStatuses|tcpStatuses|g' net/*.go\nsed -i 's|CT_ENTRIES|ctENTRIES|g' net/net_linux.go\nsed -i 's|CT_SEARCHED|ctSEARCHED|g' net/net_linux.go\nsed -i 's|CT_FOUND|ctFOUND|g' net/net_linux.go\nsed -i 's|CT_NEW|ctNEW|g' net/net_linux.go\nsed -i 's|CT_INVALID|ctINVALID|g' net/net_linux.go\nsed -i 's|CT_IGNORE|ctIGNORE|g' net/net_linux.go\nsed -i 's|CT_DELETE|ctDELETE|g' net/net_linux.go\nsed -i 's|CT_DELETE_LIST|ctDELETE_LIST|g' net/net_linux.go\nsed -i 's|CT_INSERT|ctINSERT|g' net/net_linux.go\nsed -i 's|CT_INSERT_FAILED|ctINSERT_FAILED|g' net/net_linux.go\nsed -i 's|CT_DROP|ctDROP|g' net/net_linux.go\nsed -i 's|CT_EARLY_DROP|ctEARLY_DROP|g' net/net_linux.go\nsed -i 's|CT_ICMP_ERROR|ctICMP_ERROR|g' net/net_linux.go\nsed -i 's|CT_EXPECT_NEW|ctEXPECT_NEW|g' net/net_linux.go\nsed -i 's|CT_EXPECT_CREATE|ctEXPECT_CREATE|g' net/net_linux.go\nsed -i 's|CT_EXPECT_DELETE|ctEXPECT_DELETE|g' net/net_linux.go\nsed -i 's|CT_SEARCH_RESTART|ctSEARCH_RESTART|g' net/net_linux.go\n\nsed -i 's|PageSize|pageSize|g' process/process_*.go\nsed -i 's|PrioProcess|prioProcess|g' process/process_*.go\nsed -i 's|ClockTicks|clockTicks|g' process/process_*.go\n\n\n./v3migration \"$(pwd)\" issueRemoveUnusedValue\n\n\n############ SHOULD BE FIXED BY HAND\n", "num_lines": 172}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\n## Example in bash using STDIN signaling\n\ncounter=0\n\nwhile read LINE; do\n    echo \"counter_bash count=${counter}\"\n    counter=$((counter+1))\ndone\n\ntrap \"echo terminate 1>&2\" EXIT", "num_lines": 12}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "docker build -t local_telegraf -f scripts/alpine.docker .\n\ndocker-compose -f plugins/inputs/kibana/test_environment/docker-compose.yml up\n", "num_lines": 4}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "# Usage: sh file.sh output_filename.ext\n# reads from stdin and writes out to a file named on the command line.\nwhile read line; do\n  echo \"$line\" >> $1\ndone < /dev/stdin\n", "num_lines": 6}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# no auth\nmongod --dbpath data/noauth --fork --logpath /var/log/mongodb_noauth/mongod.log --bind_ip 0.0.0.0 --port 27017\n\n# scram auth\nmongod --dbpath data/scram --fork --logpath /var/log/mongodb_scram/mongod.log --bind_ip 0.0.0.0 --port 27018\nmongo localhost:27018/admin --eval \"db.createUser({user:\\\"root\\\", pwd:\\\"changeme\\\", roles:[{role:\\\"root\\\",db:\\\"admin\\\"}]})\"\nmongo localhost:27018/admin --eval \"db.shutdownServer()\"\nmongod --dbpath data/scram --fork --logpath /var/log/mongodb_scram/mongod.log --auth --setParameter authenticationMechanisms=SCRAM-SHA-256 --bind_ip 0.0.0.0 --port 27018\n\n# get client certificate subject for creating x509 authenticating user\ndn=$(openssl x509 -in ./private/client.pem -noout -subject -nameopt RFC2253 | sed 's/subject=//g')\n\n# x509 auth\nmongod --dbpath data/x509 --fork --logpath /var/log/mongodb_x509/mongod.log --bind_ip 0.0.0.0 --port 27019\nmongo localhost:27019/admin --eval \"db.getSiblingDB(\\\"\\$external\\\").runCommand({createUser:\\\"$dn\\\",roles:[{role:\\\"root\\\",db:\\\"admin\\\"}]})\"\nmongo localhost:27019/admin --eval \"db.shutdownServer()\"\nmongod --dbpath data/x509 --fork --logpath /var/log/mongodb_x509/mongod.log --auth --setParameter authenticationMechanisms=MONGODB-X509 --tlsMode preferTLS --tlsCAFile certs/cacert.pem --tlsCertificateKeyFile private/server.pem --bind_ip 0.0.0.0 --port 27019\n\n# x509 auth short expirey\n# mongodb will not start with an expired certificate. service must be started before certificate expires. tests should be run after certificate expiry\nmongod --dbpath data/x509_expire --fork --logpath /var/log/mongodb_x509_expire/mongod.log --bind_ip 0.0.0.0 --port 27020\nmongo localhost:27020/admin --eval \"db.getSiblingDB(\\\"\\$external\\\").runCommand({createUser:\\\"$dn\\\",roles:[{role:\\\"root\\\",db:\\\"admin\\\"}]})\"\nmongo localhost:27020/admin --eval \"db.shutdownServer()\"\nmongod --dbpath data/x509_expire --fork --logpath /var/log/mongodb_x509_expire/mongod.log --auth --setParameter authenticationMechanisms=MONGODB-X509 --tlsMode preferTLS --tlsCAFile certs/cacert.pem --tlsCertificateKeyFile private/serverexp.pem --bind_ip 0.0.0.0 --port 27020\n\n# note about key size and mongodb\n# x509 must be 2048 bytes or stronger in order for mongodb to start. otherwise you will receive similar error below\n# {\"keyFile\":\"/opt/private/server.pem\",\"error\":\"error:140AB18F:SSL routines:SSL_CTX_use_certificate:ee key too small\"}\n\n# copy key files to /opt/export. docker volume should point /opt/export to outputs/mongodb/dev in order to run non short x509 tests\ncp /opt/certs/cacert.pem /opt/private/client.pem /opt/private/clientenc.pem /opt/export\n\nwhile true; do sleep 1; done # leave container running.\n", "num_lines": 35}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\ntmpdir=\"$(mktemp -d)\"\n\ncleanup() {\n\trm -rf \"$tmpdir\"\n}\ntrap cleanup EXIT\n\ntargets=\"$(go tool dist list)\"\n\nfor target in ${targets}; do\n\t# only check platforms we build for\n\tcase \"${target}\" in\n\t\tlinux/*) ;;\n\t\twindows/*) ;;\n\t\tfreebsd/*) ;;\n\t\tdarwin/*) ;;\n\t\t*) continue;;\n\tesac\n\n\tGOOS=${target%%/*} GOARCH=${target##*/} \\\n\t\tgo list -deps -f '{{with .Module}}{{.Path}}{{end}}' ./cmd/telegraf/ >> \"${tmpdir}/golist\"\ndone\n\nfor dep in $(LC_ALL=C sort -u \"${tmpdir}/golist\"); do\n\tcase \"${dep}\" in\n\t\t# ignore ourselves\n\t\tgithub.com/influxdata/telegraf) continue;;\n\n\t\t# dependency is replaced in go.mod\n\t\tgithub.com/satori/go.uuid) continue;;\n\n\t\t# go-autorest has a single license for all sub modules\n\t\tgithub.com/Azure/go-autorest/autorest)\n\t\t\tdep=github.com/Azure/go-autorest;;\n\t\tgithub.com/Azure/go-autorest/*)\n\t\t\tcontinue;;\n\n\t\t# single license for all sub modules\n\t\tcloud.google.com/go/*)\n\t\t\tcontinue;;\n\tesac\n\n\t# Remove single and double digit version from path; these are generally not\n\t# actual parts of the path and instead indicate a branch or tag.\n\t#   example: github.com/influxdata/go-syslog/v2 -> github.com/influxdata/go-syslog\n\tdep=\"${dep%%/v[0-9]}\"\n\tdep=\"${dep%%/v[0-9][0-9]}\"\n\n\techo \"${dep}\" >> \"${tmpdir}/HEAD\"\ndone\n\n# If there are two versions of a library that have the same base (like\n# github.com/foo/bar github.com/foo/bar/v3) there will be a duplicate\n# in the list.  Remove duplicates again.\nmv \"${tmpdir}/HEAD\" \"${tmpdir}/HEAD-dup\"\nuniq \"${tmpdir}/HEAD-dup\" > \"${tmpdir}/HEAD\"\n\ngrep '^-' docs/LICENSE_OF_DEPENDENCIES.md | grep -v github.com/DataDog/datadog-agent | cut -f 2 -d' ' > \"${tmpdir}/LICENSE_OF_DEPENDENCIES.md\"\n\ndiff -U0 \"${tmpdir}/LICENSE_OF_DEPENDENCIES.md\" \"${tmpdir}/HEAD\" || {\ncat - <<EOF\n\n\nThe docs/LICENSE_OF_DEPENDENCIES.md file does not contain the expected entries.\n\nLines prefixed with '+' should be added to LICENSE_OF_DEPENDENCIES.md and '-'\nlines should be removed.\n\nInclude a link to the appropriate licenses for any additions.\nEOF\nexit 1\n}\n", "num_lines": 75}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\nIFS=$'\\n\\t'\n\nusage () {\n    echo \"Check that no dynamic symbols provided by glibc are newer than a given version\"\n    echo \"Usage:\"\n    echo \"   $0 program version\"\n    echo \"where program is the elf binary to check and version is a dotted version string like 2.3.4\"\n    exit 1\n}\n\n#validate input and display help\n[[ $# = 2 ]] || usage\nprog=$1\nmax=$2\n\n#make sure dependencies are installed\nhave_deps=true\nfor i in objdump grep sort uniq sed; do\n    if ! command -v \"$i\" > /dev/null; then\n\techo \"$i not in path\"\n\thave_deps=false\n    fi\ndone\nif [[ $have_deps = false ]]; then\n    exit 1\nfi\n\n#compare dotted versions\n#see https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash\nvercomp () {\n    if [[ $1 == $2 ]]\n    then\n        return 0\n    fi\n    local IFS=.\n    local i ver1=($1) ver2=($2)\n    # fill empty fields in ver1 with zeros\n    for ((i=${#ver1[@]}; i<${#ver2[@]}; i++))\n    do\n        ver1[i]=0\n    done\n    for ((i=0; i<${#ver1[@]}; i++))\n    do\n        if [[ -z ${ver2[i]} ]]\n        then\n            # fill empty fields in ver2 with zeros\n            ver2[i]=0\n        fi\n        if ((10#${ver1[i]} > 10#${ver2[i]}))\n        then\n            return 1\n        fi\n        if ((10#${ver1[i]} < 10#${ver2[i]}))\n        then\n            return 2\n        fi\n    done\n    return 0\n}\n\nif ! objdump -p \"$prog\" | grep -q NEEDED; then\n    echo \"$prog doesn't have dynamic library dependencies\"\n    exit 0\nfi\n\nobjdump -T \"$prog\" | # get the dynamic symbol table\n    sed -n \"s/.* GLIBC_\\([0-9.]\\+\\).*/\\1/p\" | # find the entries for glibc and grab the version\n    sort | uniq | # remove duplicates\n    while read v; do\n        set +e\n        vercomp \"$v\" \"$max\" # fail if any version is newer than our max\n        comp=$?\n        set -e\n        if [[ $comp -eq 1 ]]; then\n            echo \"$v is newer than $max\"\n            exit 1\n        fi\n    done\n\nexit 0\n", "num_lines": 83}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# CIRCLE-CI SCRIPT: This file is used exclusively for CI\n# To prevent the tests/builds to run for only a doc change, this script checks what files have changed in a pull request.\n\nBRANCH=\"$(git rev-parse --abbrev-ref HEAD)\"\necho $BRANCH\nif [[ ${CIRCLE_PULL_REQUEST##*/} != \"\" ]]; then # Only skip if their is an associated pull request with this job\n    # Ask git for all the differences between this branch and master\n    # Then use grep to look for changes in the .circleci/ directory, anything named *.go or *.mod or *.sum or *.sh or Makefile\n    # If no match is found, then circleci step halt will stop the CI job but mark it successful\n    git diff master --name-only --no-color | egrep -e \"^(\\.circleci\\/.*)$|^(.*\\.(go|mod|sum|sh))$|^Makefile$\" || circleci step halt;\nfi\n", "num_lines": 13}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n# This script is responsible for generating the Telegraf config found under the `etc` directory.\n# This script is meant to be only ran in within the Circle CI pipeline so that the Tiger Bot can update them automatically.\n# It supports Windows and Linux because the configs are different depending on the OS.\n\n\nos=$1 # windows or linux\nexe_path=\"/build/extracted\" # Path will contain telegraf binary\nconfig_name=\"telegraf.conf\"\n\nif [ \"$os\" = \"windows\" ]; then\n    zip=$(/bin/find ./build/dist -maxdepth 1 -name \"*windows_amd64.zip\" -print)\n    exe_path=\"$PWD/build/extracted\"\n    unzip \"$zip\" -d \"$exe_path\"\n    config_name=\"telegraf_windows.conf\"\n    exe_path=$(/bin/find \"$exe_path\" -name telegraf.exe -type f -print)\nelse\n    tar_path=$(find /build/dist -maxdepth 1 -name \"*linux_amd64.tar.gz\" -print | grep -v \".*static.*\")\n    mkdir \"$exe_path\"\n    tar --extract --file=\"$tar_path\" --directory \"$exe_path\"\n    exe_path=$(find \"$exe_path\" -name telegraf -type f -print | grep \".*usr/bin/.*\")\nfi\n\n$exe_path config > $config_name\n\nmkdir ./new-config\nmv $config_name ./new-config\n", "num_lines": 28}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\n# chkconfig: 2345 99 01\n# description: Telegraf daemon\n\n### BEGIN INIT INFO\n# Provides:          telegraf\n# Required-Start:    $all\n# Required-Stop:     $remote_fs $syslog\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# Short-Description: Start telegraf at boot time\n### END INIT INFO\n\n# this init script supports three different variations:\n#  1. New lsb that define start-stop-daemon\n#  2. Old lsb that don't have start-stop-daemon but define, log, pidofproc and killproc\n#  3. Centos installations without lsb-core installed\n#\n# In the third case we have to define our own functions which are very dumb\n# and expect the args to be positioned correctly.\n\n# Command-line options that can be set in /etc/default/telegraf.  These will override\n# any config file values.\nTELEGRAF_OPTS=\n\nUSER=telegraf\nGROUP=telegraf\n\nif [ -r /lib/lsb/init-functions ]; then\n    source /lib/lsb/init-functions\nfi\n\nDEFAULT=/etc/default/telegraf\n\nif [ -r $DEFAULT ]; then\n    set -o allexport\n    source $DEFAULT\n    set +o allexport\nfi\n\nif [ -z \"$STDOUT\" ]; then\n    STDOUT=/dev/null\nfi\nif [ ! -f \"$STDOUT\" ]; then\n    mkdir -p `dirname $STDOUT`\nfi\n\nif [ -z \"$STDERR\" ]; then\n    STDERR=/var/log/telegraf/telegraf.log\nfi\nif [ ! -f \"$STDERR\" ]; then\n    mkdir -p `dirname $STDERR`\nfi\n\nOPEN_FILE_LIMIT=65536\n\nfunction pidofproc() {\n    if [ $# -ne 3 ]; then\n        echo \"Expected three arguments, e.g. $0 -p pidfile daemon-name\"\n    fi\n\n    if [ ! -f \"$2\" ]; then\n        return 1\n    fi\n\n    local pidfile=`cat $2`\n\n    if [ \"x$pidfile\" == \"x\" ]; then\n        return 1\n    fi\n\n    if ps --pid \"$pidfile\" | grep -q $(basename $3); then\n        return 0\n    fi\n\n    return 1\n}\n\nfunction killproc() {\n    if [ $# -ne 3 ]; then\n        echo \"Expected three arguments, e.g. $0 -p pidfile signal\"\n    fi\n\n    pid=`cat $2`\n\n    kill -s $3 $pid\n}\n\nfunction log_failure_msg() {\n    echo \"$@\" \"[ FAILED ]\"\n}\n\nfunction log_success_msg() {\n    echo \"$@\" \"[ OK ]\"\n}\n\n# Process name ( For display )\nname=telegraf\n\n# Daemon name, where is the actual executable\ndaemon=/usr/bin/telegraf\n\n# pid file for the daemon\npidfile=/var/run/telegraf/telegraf.pid\npiddir=`dirname $pidfile`\n\nif [ ! -d \"$piddir\" ]; then\n    mkdir -p $piddir\n    chown $USER:$GROUP $piddir\nfi\n\n# Configuration file\nconfig=/etc/telegraf/telegraf.conf\nconfdir=/etc/telegraf/telegraf.d\n\n# If the daemon is not there, then exit.\n[ -x $daemon ] || exit 5\n\ncase $1 in\n    start)\n        # Checked the PID file exists and check the actual status of process\n        if [ -e \"$pidfile\" ]; then\n            if pidofproc -p $pidfile $daemon > /dev/null; then\n                log_failure_msg \"$name process is running\"\n\t    else\n                log_failure_msg \"$name pidfile has no corresponding process; ensure $name is stopped and remove $pidfile\"\n            fi\n            exit 0\n        fi\n\n        # Bump the file limits, before launching the daemon. These will carry over to\n        # launched processes.\n        ulimit -n $OPEN_FILE_LIMIT\n        if [ $? -ne 0 ]; then\n            log_failure_msg \"set open file limit to $OPEN_FILE_LIMIT\"\n        fi\n\n        log_success_msg \"Starting the process\" \"$name\"\n        if command -v startproc >/dev/null; then\n            startproc -u \"$USER\" -g \"$GROUP\" -p \"$pidfile\" -q -- \"$daemon\" -pidfile \"$pidfile\" -config \"$config\" -config-directory \"$confdir\" $TELEGRAF_OPTS\n        elif which start-stop-daemon > /dev/null 2>&1; then\n            start-stop-daemon --chuid $USER:$GROUP --start --quiet --pidfile $pidfile --exec $daemon -- -pidfile $pidfile -config $config -config-directory $confdir $TELEGRAF_OPTS >>$STDOUT 2>>$STDERR &\n        else\n            su -s /bin/sh -c \"nohup $daemon -pidfile $pidfile -config $config -config-directory $confdir $TELEGRAF_OPTS >>$STDOUT 2>>$STDERR &\" $USER\n        fi\n        log_success_msg \"$name process was started\"\n        ;;\n\n    stop)\n        # Stop the daemon.\n        if [ -e $pidfile ]; then\n            if pidofproc -p $pidfile $daemon > /dev/null; then\n                # periodically signal until process exists\n                while true; do\n                        if ! pidofproc -p $pidfile $daemon > /dev/null; then\n                                break\n                        fi\n                        killproc -p $pidfile SIGTERM 2>&1 >/dev/null\n                        sleep 2\n                done\n\n                log_success_msg \"$name process was stopped\"\n                rm -f $pidfile\n            fi\n        else\n            log_failure_msg \"$name process is not running\"\n        fi\n        ;;\n\n    reload)\n        # Reload the daemon.\n        if [ -e $pidfile ]; then\n            if pidofproc -p $pidfile $daemon > /dev/null; then\n                if killproc -p $pidfile SIGHUP; then\n                    log_success_msg \"$name process was reloaded\"\n                else\n                    log_failure_msg \"$name failed to reload service\"\n                fi\n            fi\n        else\n            log_failure_msg \"$name process is not running\"\n        fi\n        ;;\n\n    restart)\n        # Restart the daemon.\n        $0 stop && sleep 2 && $0 start\n        ;;\n\n    status)\n        # Check the status of the process.\n        if [ -e $pidfile ]; then\n            if pidofproc -p $pidfile $daemon > /dev/null; then\n                log_success_msg \"$name Process is running\"\n                exit 0\n            else\n                log_failure_msg \"$name Process is not running\"\n                exit 1\n            fi\n        else\n            log_failure_msg \"$name Process is not running\"\n            exit 3\n        fi\n        ;;\n\n    version)\n        $daemon version\n        ;;\n\n    *)\n        # For invalid arguments, print the usage message.\n        echo \"Usage: $0 {start|stop|restart|status|version}\"\n        exit 2\n        ;;\nesac\n", "num_lines": 217}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -eux\n\nARCH=$(uname -m)\nGO_VERSION=\"1.17.7\"\nif [ \"$ARCH\" = 'arm64' ]; then\n    GO_ARCH=\"darwin-arm64\"\n    GO_VERSION_SHA=\"e141bd85577b875cc771cfcc18604989c861e93bbef377ba6c80d29e18f9a338\" # from https://golang.org/dl\nelif [ \"$ARCH\" = 'x86_64' ]; then\n    GO_ARCH=\"darwin-amd64\"\n    GO_VERSION_SHA=\"7c3d9cc70ee592515d92a44385c0cba5503fd0a9950f78d76a4587916c67a84d\" # from https://golang.org/dl\nfi\n\n# This path is cachable. (Saving in /usr/local/ would cause issues restoring the cache.)\npath=\"/usr/local/Cellar\"\nsudo mkdir -p ${path}\n\n# Download Go and verify Go tarball. (Note: we aren't using brew because\n# it is slow to update and we can't pull specific minor versions.)\nsetup_go () {\n    echo \"installing go\"\n    curl -L https://golang.org/dl/go${GO_VERSION}.${GO_ARCH}.tar.gz --output go${GO_VERSION}.${GO_ARCH}.tar.gz\n    if ! echo \"${GO_VERSION_SHA}  go${GO_VERSION}.${GO_ARCH}.tar.gz\" | shasum --algorithm 256 --check -; then\n        echo \"Checksum failed\" >&2\n        exit 1\n    fi\n\n    sudo rm -rf ${path}/go\n    sudo tar -C $path -xzf go${GO_VERSION}.${GO_ARCH}.tar.gz\n    sudo mkdir -p /usr/local/bin\n    sudo ln -sf ${path}/go/bin/go /usr/local/bin/go\n    sudo ln -sf ${path}/go/bin/gofmt /usr/local/bin/gofmt\n}\n\nif command -v go >/dev/null 2>&1; then\n    echo \"Go is already installed\"\n    v=$(go version | { read -r _ _ v _; echo \"${v#go}\"; })\n    echo \"$v is installed, required version is ${GO_VERSION}\"\n    if [ \"$v\" != ${GO_VERSION} ]; then\n        setup_go\n        go version\n    fi\nelse\n    setup_go\nfi\n", "num_lines": 47}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -eux\n\nGO_VERSION=\"1.17.7\"\n\nsetup_go () {\n    choco upgrade golang --allow-downgrade --version=${GO_VERSION}\n    choco install make\n    git config --system core.longpaths true\n    rm -rf /c/Go\n    cp -r /c/Program\\ Files/Go /c/\n}\n\nif command -v go >/dev/null 2>&1; then\n    echo \"Go is already installed\"\n    v=$(go version | { read -r _ _ v _; echo \"${v#go}\"; })\n    echo \"$v is installed, required version is ${GO_VERSION}\"\n    if [ \"$v\" != ${GO_VERSION} ]; then\n        setup_go\n        go version\n    fi\nelse\n    setup_go\nfi\n", "num_lines": 26}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -eux\n\nOS=$1\nEXE=$2\nVERSION=\"1.7.0\"\n\nWINDOWS_SHA=\"7ae12ddb171375f0c14d6a09dd27a5c1d1fc72edeea674e3d6e7489a533b40c1\"\nDARWIN_SHA=\"a8e2351604882af1a67601cbeeacdcfa9b17fc2f6fbac291cf5d434efdf2d85b\"\nLINUX_SHA=\"b5c98cc408c75e76a097354d9487dca114996e821b3af29a0442aa6c9159bd40\"\n\nsetup_gotestsum () {\n    echo \"installing gotestsum\"\n    curl -L \"https://github.com/gotestyourself/gotestsum/releases/download/v${VERSION}/gotestsum_${VERSION}_${OS}_amd64.tar.gz\" --output gotestsum.tar.gz\n\n    if [ \"$OS\" = \"windows\" ]; then\n        SHA=$WINDOWS_SHA\n        SHATOOL=\"sha256sum\"\n    elif [ \"$OS\" = \"darwin\" ]; then\n        SHA=$DARWIN_SHA\n        SHATOOL=\"shasum --algorithm 256\"\n    elif [ \"$OS\" = \"linux\" ]; then\n        SHA=$LINUX_SHA\n        SHATOOL=\"sha256sum\"\n    fi\n\n    if ! echo \"${SHA}  gotestsum.tar.gz\" | ${SHATOOL} --check -; then\n        echo \"Checksum failed\" >&2\n        exit 1\n    fi\n\n    tar --extract --file=gotestsum.tar.gz \"${EXE}\"\n}\n\nif test -f \"${EXE}\"; then\n    echo \"gotestsum is already installed\"\n    v=$(./\"${EXE}\" --version)\n    echo \"$v is installed, required version is ${VERSION}\"\n    if [ \"$v\" != \"gotestsum version ${VERSION}\" ]; then\n        setup_gotestsum\n        ${EXE} --version\n    fi\nelse\n    setup_gotestsum\nfi\n", "num_lines": 47}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\njobName=$1\n\ncircleci config process .circleci/config.yml > process.yml\ncircleci local execute -c process.yml --job $jobName\n", "num_lines": 7}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction cleanup () {\n  echo \"Cleaning up any existing Telegraf or Telegraf.app\"\n  printf \"\\n\"\n  rm -rf Telegraf\n  rm -rf Telegraf.app\n}\n\n# Acquire the necessary certificates.\n# MacCertificate, MacCertificatePassword, AppleSigningAuthorityCertificate are environment variables, to follow convention they should have been all caps.\n# shellcheck disable=SC2154\nbase64 -D -o MacCertificate.p12 <<< \"$MacCertificate\"\n# shellcheck disable=SC2154\nsudo security import MacCertificate.p12 -k /Library/Keychains/System.keychain -P \"$MacCertificatePassword\" -A\n# shellcheck disable=SC2154\nbase64 -D -o AppleSigningAuthorityCertificate.cer <<< \"$AppleSigningAuthorityCertificate\"\nsudo security import AppleSigningAuthorityCertificate.cer -k '/Library/Keychains/System.keychain' -A\n\namdFile=$(find \"$HOME/project/dist\" -name \"*darwin_amd64.tar*\")\narmFile=$(find \"$HOME/project/dist\" -name \"*darwin_arm64.tar*\")\nmacFiles=(\"${amdFile}\" \"${armFile}\")\n\nfor tarFile in \"${macFiles[@]}\";\ndo\n  cleanup\n\n  # Create the .app bundle directory structure\n  RootAppDir=\"Telegraf.app/Contents\"\n  mkdir -p \"$RootAppDir\"\n  mkdir -p \"$RootAppDir/MacOS\"\n  mkdir -p \"$RootAppDir/Resources\"\n\n  DeveloperID=\"Developer ID Application: InfluxData Inc. (M7DN9H35QT)\"\n\n  # Sign telegraf binary and the telegraf_entry_mac script\n  echo \"Extract $tarFile to $RootAppDir/Resources\"\n  tar -xzvf \"$tarFile\" --strip-components=2 -C \"$RootAppDir/Resources\"\n  printf \"\\n\"\n  TelegrafBinPath=\"$RootAppDir/Resources/usr/bin/telegraf\"\n  codesign --force -s \"$DeveloperID\" --timestamp --options=runtime \"$TelegrafBinPath\"\n  echo \"Verify if $TelegrafBinPath was signed\"\n  codesign -dvv \"$TelegrafBinPath\"\n\n  printf \"\\n\"\n\n  cp ~/project/scripts/telegraf_entry_mac \"$RootAppDir\"/MacOS\n  EntryMacPath=\"$RootAppDir/MacOS/telegraf_entry_mac\"\n  codesign -s \"$DeveloperID\" --timestamp --options=runtime \"$EntryMacPath\"\n  echo \"Verify if $EntryMacPath was signed\"\n  codesign -dvv \"$EntryMacPath\"\n\n  printf \"\\n\"\n\n  cp ~/project/info.plist \"$RootAppDir\"\n  cp  ~/project/assets/icon.icns \"$RootAppDir/Resources\"\n\n  chmod +x \"$RootAppDir/MacOS/telegraf_entry_mac\"\n\n  # Sign the entire .app bundle, and wrap it in a DMG.\n  codesign -s \"$DeveloperID\" --timestamp --options=runtime --deep --force Telegraf.app\n  baseName=$(basename \"$tarFile\" .tar.gz)\n  echo \"$baseName\"\n  hdiutil create -size 500m -volname Telegraf -srcfolder Telegraf.app \"$baseName\".dmg\n  codesign -s \"$DeveloperID\" --timestamp --options=runtime \"$baseName\".dmg\n\n  # Send the DMG to be notarized.\n  # AppleUsername and ApplePassword are environment variables, to follow convention they should have been all caps.\n  # shellcheck disable=SC2154\n  uuid=$(xcrun altool --notarize-app --primary-bundle-id \"com.influxdata.telegraf\" --username \"$AppleUsername\" --password \"$ApplePassword\" --file \"$baseName\".dmg | awk '/RequestUUID/ { print $NF; }')\n  echo \"UUID: $uuid\"\n  if [[ $uuid == \"\" ]]; then\n    echo \"Could not upload for notarization.\"\n    exit 1\n  fi\n\n  printf \"\\n\"\n\n  # Wait until the status returns something other than 'in progress'.\n  request_status=\"in progress\"\n  while [[ \"$request_status\" == \"in progress\" ]]; do\n    sleep 10\n    request_response=$(xcrun altool --notarization-info \"$uuid\" --username \"$AppleUsername\" --password \"$ApplePassword\" 2>&1)\n    request_status=$(echo \"$request_response\" | awk -F ': ' '/Status:/ { print $2; }' )\n  done\n\n  if [[ $request_status != \"success\" ]]; then\n    echo \"Failed to notarize.\"\n    echo \"$request_response\"\n    cleanup\n    exit 1\n  fi\n\n  # Attach the notarization to the DMG.\n  xcrun stapler staple \"$baseName\".dmg\n  cleanup\n\n  mkdir -p ~/project/build/dist\n  mv \"$baseName\".dmg ~/project/build/dist\n\n  echo \"$baseName.dmg signed and notarized!\"\ndone\n", "num_lines": 103}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIN_DIR=/usr/bin\nLOG_DIR=/var/log/telegraf\nSCRIPT_DIR=/usr/lib/telegraf/scripts\nLOGROTATE_DIR=/etc/logrotate.d\n\nfunction install_init {\n    cp -f $SCRIPT_DIR/init.sh /etc/init.d/telegraf\n    chmod +x /etc/init.d/telegraf\n}\n\nfunction install_systemd {\n    cp -f $SCRIPT_DIR/telegraf.service $1\n    systemctl enable telegraf || true\n    systemctl daemon-reload || true\n}\n\nfunction install_update_rcd {\n    update-rc.d telegraf defaults\n}\n\nfunction install_chkconfig {\n    chkconfig --add telegraf\n}\n\n# Remove legacy symlink, if it exists\nif [[ -L /etc/init.d/telegraf ]]; then\n    rm -f /etc/init.d/telegraf\nfi\n# Remove legacy symlink, if it exists\nif [[ -L /etc/systemd/system/telegraf.service ]]; then\n    rm -f /etc/systemd/system/telegraf.service\nfi\n\n# Add defaults file, if it doesn't exist\nif [[ ! -f /etc/default/telegraf ]]; then\n    touch /etc/default/telegraf\nfi\n\n# Add .d configuration directory\nif [[ ! -d /etc/telegraf/telegraf.d ]]; then\n    mkdir -p /etc/telegraf/telegraf.d\nfi\n\n# If 'telegraf.conf' is not present use package's sample (fresh install)\nif [[ ! -f /etc/telegraf/telegraf.conf ]] && [[ -f /etc/telegraf/telegraf.conf.sample ]]; then\n   cp /etc/telegraf/telegraf.conf.sample /etc/telegraf/telegraf.conf\nfi\n\ntest -d $LOG_DIR || mkdir -p $LOG_DIR\nchown -R -L telegraf:telegraf $LOG_DIR\nchmod 755 $LOG_DIR\n\nif [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n\tinstall_systemd /lib/systemd/system/telegraf.service\n\tdeb-systemd-invoke restart telegraf.service || echo \"WARNING: systemd not running.\"\nelse\n\t# Assuming SysVinit\n\tinstall_init\n\t# Run update-rc.d or fallback to chkconfig if not available\n\tif which update-rc.d &>/dev/null; then\n\t\tinstall_update_rcd\n\telse\n\t\tinstall_chkconfig\n\tfi\n\tinvoke-rc.d telegraf restart\nfi\n", "num_lines": 69}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction disable_systemd {\n    systemctl disable telegraf\n    rm -f $1\n}\n\nfunction disable_update_rcd {\n    update-rc.d -f telegraf remove\n    rm -f /etc/init.d/telegraf\n}\n\nfunction disable_chkconfig {\n    chkconfig --del telegraf\n    rm -f /etc/init.d/telegraf\n}\n\nif [ \"$1\" == \"remove\" -o \"$1\" == \"purge\" ]; then\n\t# Remove/purge\n\trm -f /etc/default/telegraf\n\n\tif [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n\t\tdisable_systemd /lib/systemd/system/telegraf.service\n\telse\n\t\t# Assuming sysv\n\t\t# Run update-rc.d or fallback to chkconfig if not available\n\t\tif which update-rc.d &>/dev/null; then\n\t\t\tdisable_update_rcd\n\t\telse\n\t\t\tdisable_chkconfig\n\t\tfi\n\tfi\nfi\n", "num_lines": 34}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif ! grep \"^telegraf:\" /etc/group &>/dev/null; then\n    groupadd -r telegraf\nfi\n\nif ! id telegraf &>/dev/null; then\n    useradd -r -M telegraf -s /bin/false -d /etc/telegraf -g telegraf\nfi\n\nif [[ -d /etc/opt/telegraf ]]; then\n    # Legacy configuration found\n    if [[ ! -d /etc/telegraf ]]; then\n        # New configuration does not exist, move legacy configuration to new location\n        echo -e \"Please note, Telegraf's configuration is now located at '/etc/telegraf' (previously '/etc/opt/telegraf').\"\n        mv -vn /etc/opt/telegraf /etc/telegraf\n\n        if [[ -f /etc/telegraf/telegraf.conf ]]; then\n            backup_name=\"telegraf.conf.$(date +%s).backup\"\n            echo \"A backup of your current configuration can be found at: /etc/telegraf/${backup_name}\"\n            cp -a \"/etc/telegraf/telegraf.conf\" \"/etc/telegraf/${backup_name}\"\n        fi\n    fi\nfi\n", "num_lines": 25}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIN_DIR=/usr/bin\n\nif [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n\tdeb-systemd-invoke stop telegraf.service\nelse\n\t# Assuming sysv\n\tinvoke-rc.d telegraf stop\nfi\n", "num_lines": 11}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nBIN_DIR=/usr/bin\nLOG_DIR=/var/log/telegraf\nSCRIPT_DIR=/usr/lib/telegraf/scripts\nLOGROTATE_DIR=/etc/logrotate.d\n\nfunction install_init {\n    cp -f $SCRIPT_DIR/init.sh /etc/init.d/telegraf\n    chmod +x /etc/init.d/telegraf\n}\n\nfunction install_systemd {\n    cp -f $SCRIPT_DIR/telegraf.service $1\n    systemctl enable telegraf || true\n    systemctl daemon-reload || true\n}\n\nfunction install_update_rcd {\n    update-rc.d telegraf defaults\n}\n\nfunction install_chkconfig {\n    chkconfig --add telegraf\n}\n\n# Remove legacy symlink, if it exists\nif [[ -L /etc/init.d/telegraf ]]; then\n    rm -f /etc/init.d/telegraf\nfi\n# Remove legacy symlink, if it exists\nif [[ -L /etc/systemd/system/telegraf.service ]]; then\n    rm -f /etc/systemd/system/telegraf.service\nfi\n\n# Add defaults file, if it doesn't exist\nif [[ ! -f /etc/default/telegraf ]]; then\n    touch /etc/default/telegraf\nfi\n\n# Add .d configuration directory\nif [[ ! -d /etc/telegraf/telegraf.d ]]; then\n    mkdir -p /etc/telegraf/telegraf.d\nfi\n\n# If 'telegraf.conf' is not present use package's sample (fresh install)\nif [[ ! -f /etc/telegraf/telegraf.conf ]] && [[ -f /etc/telegraf/telegraf.conf.sample ]]; then\n   cp /etc/telegraf/telegraf.conf.sample /etc/telegraf/telegraf.conf\nfi\n\ntest -d $LOG_DIR || mkdir -p $LOG_DIR\nchown -R -L telegraf:telegraf $LOG_DIR\nchmod 755 $LOG_DIR\n\n# Distribution-specific logic\nif [[ -f /etc/redhat-release ]] || [[ -f /etc/SuSE-release ]]; then\n    # RHEL-variant logic\n    if [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n        install_systemd /usr/lib/systemd/system/telegraf.service\n    else\n        # Assuming SysVinit\n        install_init\n        # Run update-rc.d or fallback to chkconfig if not available\n        if which update-rc.d &>/dev/null; then\n            install_update_rcd\n        else\n            install_chkconfig\n        fi\n    fi\nelif [[ -f /etc/os-release ]]; then\n    source /etc/os-release\n    if [[ \"$NAME\" = \"Amazon Linux\" ]]; then\n        # Amazon Linux 2+ logic\n        install_systemd /usr/lib/systemd/system/telegraf.service\n    elif [[ \"$NAME\" = \"Amazon Linux AMI\" ]]; then\n        # Amazon Linux logic\n        install_init\n        # Run update-rc.d or fallback to chkconfig if not available\n        if which update-rc.d &>/dev/null; then\n            install_update_rcd\n        else\n            install_chkconfig\n        fi\n    elif [[ \"$NAME\" = \"Solus\" ]]; then\n        # Solus logic\n        install_systemd /usr/lib/systemd/system/telegraf.service\n    fi\nfi\n", "num_lines": 89}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction disable_systemd {\n    systemctl disable telegraf\n    rm -f $1\n}\n\nfunction disable_update_rcd {\n    update-rc.d -f telegraf remove\n    rm -f /etc/init.d/telegraf\n}\n\nfunction disable_chkconfig {\n    chkconfig --del telegraf\n    rm -f /etc/init.d/telegraf\n}\n\nif [[ -f /etc/redhat-release ]] || [[ -f /etc/SuSE-release ]]; then\n    # RHEL-variant logic\n    if [[ \"$1\" = \"0\" ]]; then\n        # InfluxDB is no longer installed, remove from init system\n        rm -f /etc/default/telegraf\n\n        if [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n            disable_systemd /usr/lib/systemd/system/telegraf.service\n        else\n            # Assuming sysv\n            disable_chkconfig\n        fi\n    fi\n    if [[ $1 -ge 1 ]]; then\n        # Package upgrade, not uninstall\n\n        if [[ \"$(readlink /proc/1/exe)\" == */systemd ]]; then\n            systemctl try-restart telegraf.service >/dev/null 2>&1 || :\n        fi\n    fi\nelif [[ -f /etc/os-release ]]; then\n    source /etc/os-release\n    if [[ \"$ID\" = \"amzn\" ]] && [[ \"$1\" = \"0\" ]]; then\n        # InfluxDB is no longer installed, remove from init system\n        rm -f /etc/default/telegraf\n\n        if [[ \"$NAME\" = \"Amazon Linux\" ]]; then\n            # Amazon Linux 2+ logic\n            disable_systemd /usr/lib/systemd/system/telegraf.service\n        elif [[ \"$NAME\" = \"Amazon Linux AMI\" ]]; then\n            # Amazon Linux logic\n            disable_chkconfig\n        fi\n    elif [[ \"$NAME\" = \"Solus\" ]]; then\n        rm -f /etc/default/telegraf\n        disable_systemd /usr/lib/systemd/system/telegraf.service\n    fi\nfi\n", "num_lines": 56}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/bash\n\nif ! grep \"^telegraf:\" /etc/group &>/dev/null; then\n    groupadd -r telegraf\nfi\n\nif ! id telegraf &>/dev/null; then\n    useradd -r -M telegraf -s /bin/false -d /etc/telegraf -g telegraf\nfi\n\nif [[ -d /etc/opt/telegraf ]]; then\n    # Legacy configuration found\n    if [[ ! -d /etc/telegraf ]]; then\n        # New configuration does not exist, move legacy configuration to new location\n        echo -e \"Please note, Telegraf's configuration is now located at '/etc/telegraf' (previously '/etc/opt/telegraf').\"\n        mv -vn /etc/opt/telegraf /etc/telegraf\n\n        if [[ -f /etc/telegraf/telegraf.conf ]]; then\n            backup_name=\"telegraf.conf.$(date +%s).backup\"\n            echo \"A backup of your current configuration can be found at: /etc/telegraf/${backup_name}\"\n            cp -a \"/etc/telegraf/telegraf.conf\" \"/etc/telegraf/${backup_name}\"\n        fi\n    fi\nfi\n", "num_lines": 25}
{"repo_name": "telegraf", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/bin/sh\n\nmkdir certs certs_by_serial private &&\nchmod 700 private &&\necho 01 > ./serial &&\ntouch ./index.txt &&\necho 'unique_subject = no' > index.txt.attr\ncat >./openssl.conf <<EOF\n[ ca ]\ndefault_ca = telegraf_ca\n\n[ telegraf_ca ]\ncertificate = ./certs/cacert.pem\ndatabase = ./index.txt\nnew_certs_dir = ./certs_by_serial\nprivate_key = ./private/cakey.pem\nserial = ./serial\n\ndefault_crl_days = 3650\ndefault_days = 3650\ndefault_md = sha256\n\npolicy = telegraf_ca_policy\nx509_extensions = certificate_extensions\n\n[ telegraf_ca_policy ]\ncommonName = supplied\n\n[ certificate_extensions ]\nbasicConstraints = CA:false\n\n[ req ]\ndefault_bits = 1024\ndefault_keyfile = ./private/cakey.pem\ndefault_md = sha256\nprompt = yes\ndistinguished_name = root_ca_distinguished_name\nx509_extensions = root_ca_extensions\n\n[ root_ca_distinguished_name ]\ncommonName = hostname\n\n[ root_ca_extensions ]\nbasicConstraints = CA:true\nkeyUsage = keyCertSign, cRLSign\n\n[ client_ca_extensions ]\nbasicConstraints = CA:false\nkeyUsage = digitalSignature\nsubjectAltName = @client_alt_names\nextendedKeyUsage = 1.3.6.1.5.5.7.3.2\n\n[ client_alt_names ]\nDNS.1 = localhost\nIP.1 = 127.0.0.1\n\n[ server_ca_extensions ]\nbasicConstraints = CA:false\nsubjectAltName = @server_alt_names\nkeyUsage = keyEncipherment, digitalSignature\nextendedKeyUsage = 1.3.6.1.5.5.7.3.1\n\n[ server_alt_names ]\nDNS.1 = localhost\nIP.1 = 127.0.0.1\nEOF\nopenssl req -x509 -config ./openssl.conf -days 3650 -newkey rsa:2048 -out ./certs/cacert.pem -keyout ./private/cakey.pem -subj \"/CN=Telegraf Test CA/\" -nodes &&\n\n# Create server and soon to expire keypair\nopenssl genrsa -out ./private/serverkey.pem 2048 &&\nopenssl req -new -key ./private/serverkey.pem -out ./certs/servercsr.pem -outform PEM -subj \"/CN=$(cat /proc/sys/kernel/hostname)/O=server/\" &&\nopenssl ca -config ./openssl.conf -in ./certs/servercsr.pem -out ./certs/servercert.pem -notext -batch -extensions server_ca_extensions &&\nopenssl ca -config ./openssl.conf -in ./certs/servercsr.pem -out ./certs/servercertexp.pem -startdate $(date +%y%m%d%H%M00 --date='-5 minutes')'Z' -enddate $(date +%y%m%d%H%M00 --date='5 minutes')'Z' -notext -batch -extensions server_ca_extensions &&\n\n# Create client and client encrypted keypair\nopenssl genrsa -out ./private/clientkey.pem 2048 &&\nopenssl req -new -key ./private/clientkey.pem -out ./certs/clientcsr.pem -outform PEM -subj \"/CN=$(cat /proc/sys/kernel/hostname)/O=client/\" &&\nopenssl ca -config ./openssl.conf -in ./certs/clientcsr.pem -out ./certs/clientcert.pem -notext -batch -extensions client_ca_extensions &&\ncp ./private/clientkey.pem ./private/clientkeyenc.pem &&\nssh-keygen -p -f ./private/clientkeyenc.pem -m PEM -N 'changeme'\n\n# Combine crt and key to create pem formatted keyfile\ncat ./certs/clientcert.pem ./private/clientkey.pem > ./private/client.pem &&\ncat ./certs/clientcert.pem ./private/clientkeyenc.pem > ./private/clientenc.pem &&\ncat ./certs/servercert.pem ./private/serverkey.pem > ./private/server.pem &&\ncat ./certs/servercertexp.pem ./private/serverkey.pem > ./private/serverexp.pem\n", "num_lines": 87}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nENDPOINT_FILE=$(mktemp)\nTOKEN_FILE=$(mktemp)\n\n[[ -z \"$DOMAIN\" ]] && echo \"No DOMAIN provided!\" && exit 1\n[[ -z \"$DOMAIN_OWNER\" ]] && echo \"No DOMAIN_OWNER provided!\" && exit 1\n[[ -z \"$REPOSITORY\" ]] && echo \"No REPOSITORY provided!\" && exit 1\n\naws codeartifact get-repository-endpoint --region us-west-2 --domain $DOMAIN --domain-owner $DOMAIN_OWNER --repository $REPOSITORY --format npm --output text | sed 's/https:\\/\\///' > $ENDPOINT_FILE\n\naws codeartifact get-authorization-token --region us-west-2 --domain $DOMAIN  --domain-owner $DOMAIN_OWNER --query authorizationToken --output text > $TOKEN_FILE\n\nDOCKER_BUILDKIT=1 docker build -t universal-test-runner . \\\n  --secret id=universal_test_runner_registry,src=$ENDPOINT_FILE \\\n  --secret id=universal_test_runner_auth_token,src=$TOKEN_FILE\n\nrm $ENDPOINT_FILE\nrm $TOKEN_FILE\n", "num_lines": 22}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n[[ -z \"$ECR_REGISTRY\" ]] && echo \"No ECR_REGISTRY provided!\" && exit 1\n\naws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin $ECR_REGISTRY\n\ndocker tag universal-test-runner:latest $ECR_REGISTRY:latest\ndocker push $ECR_REGISTRY:latest\n", "num_lines": 11}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Can't use `set -e` here when running in buildpack-deps docker image,\n# possibly related to https://github.com/nvm-sh/nvm/issues/1985\n# set -e\n\n# Used to install the right Node.js (and NPM) version when running in some CI\n# environments When installing Node.js in your local dev env, use the\n# instructions in the NVM README:\n# https://github.com/nvm-sh/nvm#installing-and-updating\n\necho \"Installing nvm...\"\n\ncurl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.1/install.sh | PROFILE=/dev/null bash\n\necho \"Initializing nvm...\"\n\nexport NVM_DIR=\"$HOME/.nvm\"\n[ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" --no-use  # This loads nvm\n\necho \"Installing Node.js...\"\n\nnvm install\n\necho \"Done.\"\n", "num_lines": 26}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n[[ -z \"$PRERELEASE_VERSION\" ]] && echo \"PRERELEASE_VERSION must be specified!\" && exit 1\n\necho \"Bumping all packages to version $PRERELEASE_VERSION\"\n\nnpm version $PRERELEASE_VERSION --workspaces --no-workspaces-update --include-workspace-root --no-git-tag-version\n\nnpx ts-node ./scripts/update-dependency-versions\n\nFILES_WITH_AWS_SCOPE=$(grep -l -R @aws --exclude=\"*node_modules*\" --exclude=\"*dist*\" ./packages)\n\necho \"Found the following files with @aws scope: $FILES_WITH_AWS_SCOPE\"\n\n# Replace all usage of aws scope with sentinel-internal in order to publish\n# prereleases to internal CodeArtifact registry for testing purposes.\nnpx ts-node ./scripts/replace-aws-scope.ts $FILES_WITH_AWS_SCOPE\n\necho \"Done.\"\n", "num_lines": 22}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n[[ -n \"$(git status --porcelain)\" ]] && echo \"Cannot run version bump when there are uncommitted changes!\" && exit 1\n\n[[ -z \"$WHAT_BUMP\" ]] && echo \"WHAT_BUMP must be specified! (e.g. major, minor, patch)\" && exit 1\n\necho \"Bumping all packages with increment $WHAT_BUMP...\"\n\nnpm version $WHAT_BUMP --workspaces --include-workspace-root --no-git-tag-version\n\nnpx ts-node ./scripts/update-dependency-versions\n\n# Make sure to update the package-lock after all the package versions changed\nnpm install --userconfig=/dev/null\n# Have to run it twice because npm is whack and will update the package-lock\n# to contain the old versions of the packages from the registry.\n# Another install fixes that \u00c2\u00af\\_(\u00e3\u0192\u201e)_/\u00c2\u00af\nnpm install --userconfig=/dev/null\n\nNEW_VERSION=$(node -e \"console.log(require('./package.json').version)\")\n\necho \"Committing all version updates..\"\ngit commit -a --no-verify -m \"$NEW_VERSION\"\n\necho \"Creating git tag for version $NEW_VERSION...\"\ngit tag -a -m \"$NEW_VERSION\" $NEW_VERSION\n\necho \"Done.\"\n", "num_lines": 31}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n[[ -n \"$(git status --porcelain)\" ]] && echo \"Cannot publish with uncommitted changes!\" && exit 1\n\n[[ \"$(git branch --show-current)\" != \"main\" ]] && echo \"Must be on main branch to publish!\" && exit 1\n\ngit fetch --tags origin\n\n[[ \"$(git rev-parse main)\" != \"$(git rev-parse origin/main)\" ]] \\\n  && echo \"Current main branch commit does not match origin/main! Run 'git pull origin main' to update.\" && exit 1\n\n# TODO: verify that last build on GitHub succeeded\n\nnpm run clean\nnpm run compile\nnpm run bump:release\n\nnpm login\n\n# You may have to enter an OTP for every single publish here\nnpm publish --workspaces --access public\n\ngit push --tags origin main\n", "num_lines": 26}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\neval \"$RUN_TESTS dotnet\"\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ndotnet build\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n# Make sure gradle will run the tests even if they're \"up-to-date\"\ngradle cleanTest\n\neval \"$RUN_TESTS gradle\"\n", "num_lines": 9}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\ngradle compileTestJava\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\neval \"$RUN_TESTS jest\"\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nnpm install\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\neval \"$RUN_TESTS maven\"\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nmvn compile\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n. ./venv/bin/activate\n\neval \"$RUN_TESTS pytest\"\n", "num_lines": 8}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n. ./script/bootstrap.sh\n", "num_lines": 6}
{"repo_name": "universal-test-runner", "repo_creator": "aws", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nVENV=\"venv\"\n\ntest -d $VENV || python3 -m venv $VENV || return\n$VENV/bin/pip install -r requirements.txt\n\n. $VENV/bin/activate\n", "num_lines": 11}
{"repo_name": "aad-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho -------------------------------------------------------------------------\necho\necho '                  _    _  _              __  __   ____'\necho '                 | |  | |(_)            |  \\/  | / __ \\ '\necho '                 | |__| | _ __   __ ___ | \\  / || |  | |'\necho '                 |  __  || |\\ \\ / // _ \\| |\\/| || |  | |'\necho '                 | |  | || | \\ V /|  __/| |  | || |__| |'\necho '                 |_|  |_||_|  \\_/  \\___||_|  |_| \\___\\_\\'\necho\necho \"-------------------------------------------------------------------------\"\necho \"\"\necho \"  HiveMQ Start Script for Linux/Unix v1.13\"\necho \"\"\necho \"                 DIAGNOSTIC MODE \"\necho \"\"\n\nechoerr() { printf \"%s\\n\" \"$*\" >&2; }\n\nif hash java 2>/dev/null; then\n\n    java_version=$(java -version 2>&1 | awk -F '\"' '/version/ {print $2}' | sed 's/\\..*//')\n\n    if [[ \"$((java_version))\" -lt 11 ]]; then\n        echoerr \"HiveMQ requires at least Java version 11\"\n        exit 1\n    fi\n\n    ############## VARIABLES\n    JAVA_OPTS=\"$JAVA_OPTS -Djava.net.preferIPv4Stack=true\"\n    JAVA_OPTS=\"$JAVA_OPTS -noverify\"\n\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.lang=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.nio=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/sun.nio.ch=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-exports java.base/jdk.internal.misc=ALL-UNNAMED\"\n\n    if [ -c \"/dev/urandom\" ]; then\n        # Use /dev/urandom as standard source for secure randomness if it exists\n        JAVA_OPTS=\"$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom\"\n    fi\n\n    # JMX Monitoring\n    JAVA_OPTS=\"$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false\"\n\n    JAVA_OPTS=\"$JAVA_OPTS -DdiagnosticMode=true\"\n\n    if [ -z \"$HIVEMQ_HOME\" ]; then\n        HIVEMQ_FOLDER=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/../\" && pwd )\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    else\n        HIVEMQ_FOLDER=\"$HIVEMQ_HOME\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    fi\n\n    if [ -z \"$HIVEMQ_HEAPDUMP_FOLDER\" ]; then\n        HEAPDUMP_PATH=\"$HIVEMQ_FOLDER\"\n    else\n        HEAPDUMP_PATH=\"$HIVEMQ_HEAPDUMP_FOLDER\"\n    fi\n\n    if [ ! -d \"$HIVEMQ_FOLDER\" ]; then\n        echoerr \"ERROR! HiveMQ Home Folder not found.\"\n    else\n\n        if [ ! -w \"$HIVEMQ_FOLDER\" ]; then\n            echoerr \"ERROR! HiveMQ Home Folder Permissions not correct.\"\n        else\n\n            if [ ! -f \"$HIVEMQ_FOLDER/bin/hivemq.jar\" ]; then\n                echoerr \"ERROR! HiveMQ JAR not found.\"\n                echoerr \"$HIVEMQ_FOLDER\";\n            else\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+CrashOnOutOfMemoryError\"\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError\"\n                HEAPDUMP_PATH_OPT=\"-XX:HeapDumpPath=$HEAPDUMP_PATH/heap-dump.hprof\"\n                ERROR_FILE_PATH_OPT=\"-XX:ErrorFile=$HEAPDUMP_PATH/hs_err_pid%p.log\"\n\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                echo \"  HIVEMQ_HOME: $HIVEMQ_FOLDER\"\n                echo \"\"\n                echo \"  JAVA_OPTS: $JAVA_OPTS\"\n                echo \"\"\n                echo \"  JAVA_VERSION: $java_version\"\n                echo \"\"\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                # Run HiveMQ\n                JAR_PATH=\"$HIVEMQ_FOLDER/bin/hivemq.jar\"\n                exec \"java\" \"${HOME_OPT}\" \"${HEAPDUMP_PATH_OPT}\" \"${ERROR_FILE_PATH_OPT}\" ${JAVA_OPTS} -jar \"${JAR_PATH}\"\n            fi\n        fi\n    fi\n\nelse\n    echoerr \"ERROR! You do not have the Java Runtime Environment installed, please install Java JRE from https://adoptium.net/?variant=openjdk11 and try again.\"\nfi\n", "num_lines": 100}
{"repo_name": "aad-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho -------------------------------------------------------------------------\necho\necho '                  _    _  _              __  __   ____'\necho '                 | |  | |(_)            |  \\/  | / __ \\ '\necho '                 | |__| | _ __   __ ___ | \\  / || |  | |'\necho '                 |  __  || |\\ \\ / // _ \\| |\\/| || |  | |'\necho '                 | |  | || | \\ V /|  __/| |  | || |__| |'\necho '                 |_|  |_||_|  \\_/  \\___||_|  |_| \\___\\_\\'\necho\necho \"-------------------------------------------------------------------------\"\necho \"\"\necho \"  HiveMQ Start Script for Linux/Unix v1.13\"\necho \"\"\n\nechoerr() { printf \"%s\\n\" \"$*\" >&2; }\n\nif hash java 2>/dev/null; then\n\n    java_version=$(java -version 2>&1 | awk -F '\"' '/version/ {print $2}' | sed 's/\\..*//')\n\n    if [[ \"$((java_version))\" -lt 11 ]]; then\n        echoerr \"HiveMQ 4 requires at least Java version 11\"\n        exit 1\n    fi\n\n    ############## VARIABLES\n    JAVA_OPTS=\"$JAVA_OPTS -Djava.net.preferIPv4Stack=true\"\n    JAVA_OPTS=\"$JAVA_OPTS -noverify\"\n\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.lang=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.nio=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/sun.nio.ch=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-exports java.base/jdk.internal.misc=ALL-UNNAMED\"\n\n    if [ -c \"/dev/urandom\" ]; then\n        # Use /dev/urandom as standard source for secure randomness if it exists\n        JAVA_OPTS=\"$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom\"\n    fi\n\n    # JMX Monitoring\n    JAVA_OPTS=\"$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false\"\n\n    # Recovery\n    JAVA_OPTS=\"$JAVA_OPTS -DstatefulCluster=true\"\n\n    # Uncomment for enabling Diagnostic Mode\n    #JAVA_OPTS=\"$JAVA_OPTS -DdiagnosticMode=true\"\n\n\n    if [ -z \"$HIVEMQ_HOME\" ]; then\n        HIVEMQ_FOLDER=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/../\" && pwd )\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    else\n        HIVEMQ_FOLDER=\"$HIVEMQ_HOME\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    fi\n\n    if [ -z \"$HIVEMQ_HEAPDUMP_FOLDER\" ]; then\n        HEAPDUMP_PATH=\"$HIVEMQ_FOLDER\"\n    else\n        HEAPDUMP_PATH=\"$HIVEMQ_HEAPDUMP_FOLDER\"\n    fi\n\n    if [ ! -d \"$HIVEMQ_FOLDER\" ]; then\n        echoerr \"ERROR! HiveMQ Home Folder not found.\"\n    else\n\n        if [ ! -w \"$HIVEMQ_FOLDER\" ]; then\n            echoerr \"ERROR! HiveMQ Home Folder Permissions not correct.\"\n        else\n\n            if [ ! -f \"$HIVEMQ_FOLDER/bin/hivemq.jar\" ]; then\n                echoerr \"ERROR! HiveMQ JAR not found.\"\n                echoerr \"$HIVEMQ_FOLDER\";\n            else\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+CrashOnOutOfMemoryError\"\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError\"\n                HEAPDUMP_PATH_OPT=\"-XX:HeapDumpPath=$HEAPDUMP_PATH/heap-dump.hprof\"\n                ERROR_FILE_PATH_OPT=\"-XX:ErrorFile=$HEAPDUMP_PATH/hs_err_pid%p.log\"\n\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                echo \"  HIVEMQ_HOME: $HIVEMQ_FOLDER\"\n                echo \"\"\n                echo \"  JAVA_OPTS: $JAVA_OPTS\"\n                echo \"\"\n                echo \"  JAVA_VERSION: $java_version\"\n                echo \"\"\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                # Run HiveMQ\n                JAR_PATH=\"$HIVEMQ_FOLDER/bin/hivemq.jar\"\n                exec \"java\" \"${HOME_OPT}\" \"${HEAPDUMP_PATH_OPT}\" \"${ERROR_FILE_PATH_OPT}\" ${JAVA_OPTS} -jar \"${JAR_PATH}\"\n            fi\n        fi\n    fi\n\nelse\n    echoerr \"ERROR! You do not have the Java Runtime Environment installed, please install Java JRE from https://adoptium.net/?variant=openjdk11 and try again.\"\nfi\n", "num_lines": 103}
{"repo_name": "aad-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho -------------------------------------------------------------------------\necho\necho '                  _    _  _              __  __   ____'\necho '                 | |  | |(_)            |  \\/  | / __ \\ '\necho '                 | |__| | _ __   __ ___ | \\  / || |  | |'\necho '                 |  __  || |\\ \\ / // _ \\| |\\/| || |  | |'\necho '                 | |  | || | \\ V /|  __/| |  | || |__| |'\necho '                 |_|  |_||_|  \\_/  \\___||_|  |_| \\___\\_\\'\necho\necho \"-------------------------------------------------------------------------\"\necho \"\"\necho \"  HiveMQ Start Script for Linux/Unix v1.13\"\necho \"\"\n\nechoerr() { printf \"%s\\n\" \"$*\" >&2; }\n\nif hash java 2>/dev/null; then\n\n    java_version=$(java -version 2>&1 | awk -F '\"' '/version/ {print $2}' | sed 's/\\..*//')\n\n    if [[ \"$((java_version))\" -lt 11 ]]; then\n        echoerr \"HiveMQ 4 requires at least Java version 11\"\n        exit 1\n    fi\n\n    ############## VARIABLES\n    JAVA_OPTS=\"$JAVA_OPTS -Djava.net.preferIPv4Stack=true\"\n    JAVA_OPTS=\"$JAVA_OPTS -noverify\"\n\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.lang=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/java.nio=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens java.base/sun.nio.ch=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-opens jdk.management/com.sun.management.internal=ALL-UNNAMED\"\n    JAVA_OPTS=\"$JAVA_OPTS --add-exports java.base/jdk.internal.misc=ALL-UNNAMED\"\n\n    if [ -c \"/dev/urandom\" ]; then\n        # Use /dev/urandom as standard source for secure randomness if it exists\n        JAVA_OPTS=\"$JAVA_OPTS -Djava.security.egd=file:/dev/./urandom\"\n    fi\n\n    # JMX Monitoring\n    JAVA_OPTS=\"$JAVA_OPTS -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=9010 -Dcom.sun.management.jmxremote.local.only=false -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false\"\n\n    # Uncomment for enabling Diagnostic Mode\n    #JAVA_OPTS=\"$JAVA_OPTS -DdiagnosticMode=true\"\n\n    if [ -z \"$HIVEMQ_HOME\" ]; then\n        HIVEMQ_FOLDER=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )/../\" && pwd )\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    else\n        HIVEMQ_FOLDER=\"$HIVEMQ_HOME\"\n        HOME_OPT=\"-Dhivemq.home=$HIVEMQ_FOLDER\"\n    fi\n\n    if [ -z \"$HIVEMQ_HEAPDUMP_FOLDER\" ]; then\n        HEAPDUMP_PATH=\"$HIVEMQ_FOLDER\"\n    else\n        HEAPDUMP_PATH=\"$HIVEMQ_HEAPDUMP_FOLDER\"\n    fi\n\n    if [ ! -d \"$HIVEMQ_FOLDER\" ]; then\n        echoerr \"ERROR! HiveMQ Home Folder not found.\"\n    else\n\n        if [ ! -w \"$HIVEMQ_FOLDER\" ]; then\n            echoerr \"ERROR! HiveMQ Home Folder Permissions not correct.\"\n        else\n\n            if [ ! -f \"$HIVEMQ_FOLDER/bin/hivemq.jar\" ]; then\n                echoerr \"ERROR! HiveMQ JAR not found.\"\n                echoerr \"$HIVEMQ_FOLDER\";\n            else\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+CrashOnOutOfMemoryError\"\n                JAVA_OPTS=\"$JAVA_OPTS -XX:+HeapDumpOnOutOfMemoryError\"\n                HEAPDUMP_PATH_OPT=\"-XX:HeapDumpPath=$HEAPDUMP_PATH/heap-dump.hprof\"\n                ERROR_FILE_PATH_OPT=\"-XX:ErrorFile=$HEAPDUMP_PATH/hs_err_pid%p.log\"\n\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                echo \"  HIVEMQ_HOME: $HIVEMQ_FOLDER\"\n                echo \"\"\n                echo \"  JAVA_OPTS: $JAVA_OPTS\"\n                echo \"\"\n                echo \"  JAVA_VERSION: $java_version\"\n                echo \"\"\n                echo \"-------------------------------------------------------------------------\"\n                echo \"\"\n                # Run HiveMQ\n                JAR_PATH=\"$HIVEMQ_FOLDER/bin/hivemq.jar\"\n                exec \"java\" \"${HOME_OPT}\" \"${HEAPDUMP_PATH_OPT}\" \"${ERROR_FILE_PATH_OPT}\" ${JAVA_OPTS} -jar \"${JAR_PATH}\"\n            fi\n        fi\n    fi\n\nelse\n    echoerr \"ERROR! You do not have the Java Runtime Environment installed, please install Java JRE from https://adoptium.net/?variant=openjdk11 and try again.\"\n    exit 1\nfi\n", "num_lines": 100}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Hello ${RESOURCE}\"\n\ni=0\nwhile true\ndo\n    echo \"Iteration $i\"\n\n    jwt=$(curl -sS http://169.254.169.254/metadata/identity/oauth2/token/?resource=$RESOURCE)\n    echo \"Full token:  $jwt\"\n    token=$(echo $jwt | jq -r '.access_token')\n    echo \"Access token:  $token\"\n    curl -v -H 'Accept: application/json' -H \"Authorization: Bearer ${token}\" $SERVICE_URL\n\n    i=$((i+1))\n    sleep 1\ndone", "num_lines": 18}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n[[ ! -z \"${SUBSCRIPTION_ID:-}\" ]] || (echo 'Must specify SUBSCRIPTION_ID' && exit 1)\n[[ ! -z \"${RESOURCE_GROUP:-}\" ]] || (echo 'Must specify RESOURCE_GROUP' && exit 1)\n[[ ! -z \"${CLUSTER_NAME:-}\" ]] || (echo 'Must specify CLUSTER_NAME' && exit 1)\n\nif ! az account set -s \"${SUBSCRIPTION_ID}\"; then\n  echo \"az login as a user and set the appropriate subscription ID\"\n  az login\n  az account set -s \"${SUBSCRIPTION_ID}\"\nfi\n\nif [[ -z \"${NODE_RESOURCE_GROUP:-}\" ]]; then\n  echo \"Retrieving your node resource group\"\n  NODE_RESOURCE_GROUP=\"$(az aks show -g ${RESOURCE_GROUP} -n ${CLUSTER_NAME} --query nodeResourceGroup -otsv)\"\nfi\n\necho \"Retrieving your cluster identity ID, which will be used for role assignment\"\nID=\"$(az aks show -g ${RESOURCE_GROUP} -n ${CLUSTER_NAME} --query servicePrincipalProfile.clientId -otsv)\"\n\necho \"Checking if the aks cluster is using managed identity\"\nif [[ \"${ID:-}\" == \"msi\" ]]; then\n  ID=\"$(az aks show -g ${RESOURCE_GROUP} -n ${CLUSTER_NAME} --query identityProfile.kubeletidentity.clientId -otsv)\"\nfi\n\necho \"Assigning 'Managed Identity Operator' role to ${ID}\"\naz role assignment create --role \"Managed Identity Operator\" --assignee \"${ID}\" --scope \"/subscriptions/${SUBSCRIPTION_ID}/resourcegroups/${NODE_RESOURCE_GROUP}\"\n\necho \"Assigning 'Virtual Machine Contributor' role to ${ID}\"\naz role assignment create --role \"Virtual Machine Contributor\" --assignee \"${ID}\" --scope \"/subscriptions/${SUBSCRIPTION_ID}/resourcegroups/${NODE_RESOURCE_GROUP}\"\n\n# your resource group that is used to store your user-assigned identities\n# assuming it is within the same subscription as your AKS node resource group\nif [[ -n \"${IDENTITY_RESOURCE_GROUP:-}\" ]]; then\n  echo \"Assigning 'Managed Identity Operator' role to ${ID} with ${IDENTITY_RESOURCE_GROUP} resource group scope\"\n  az role assignment create --role \"Managed Identity Operator\" --assignee \"${ID}\" --scope \"/subscriptions/${SUBSCRIPTION_ID}/resourcegroups/${IDENTITY_RESOURCE_GROUP}\"\nfi\n", "num_lines": 42}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n\nset -e\n\nabort() {\n\techo \"$@\"\n\treturn 1\n}\n\nif [ -z \"${CHECK_VERSION}\" ]; then\n\tabort \"Version must not be empty\"\nfi\nif [ \"${CHECK_VERSION}\" = \"${DEFAULT_VERSION}\" ]; then\n\tabort \"Version must not match default version: ${DEFAULT_VERSION}\"\nfi\n\n", "num_lines": 17}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\n# Check pre-requisites\n[[ ! -z \"${SUBSCRIPTION_ID:-}\" ]]         || (echo 'Must specify SUBSCRIPTION_ID' && exit -1)\n[[ ! -z \"${RESOURCE_GROUP:-}\" ]]          || (echo 'Must specify RESOURCE_GROUP' && exit -1)\n[[ ! -z \"${KEYVAULT_NAME:-}\" ]]           || (echo 'Must specify KEYVAULT_NAME' && exit -1)\n[[ ! -z \"${KEYVAULT_SECRET_NAME:-}\" ]]    || (echo 'Must specify KEYVAULT_SECRET_NAME' && exit -1)\n[[ -z \"$(hash az)\" ]]                     || (echo 'Azure CLI not found' && exit -1)\n[[ -z \"$(hash kubectl)\" ]]                || (echo 'kubectl not found' && exit -1)\n\nretry_cmd() {\n    set +e\n    local retval=0\n    for i in {0..10}; do\n        out=$(eval $1 2>&1)\n        retval=$?\n        [[ \"${out}\" == *\"already exists\"* ]] && retval=0\n        [ ${retval} -eq 0 ] && break\n        sleep 6\n    done\n    set -e\n    if [ ${retval} -ne  0 ]; then\n      >&2 echo $2\n      return 1\n    fi\n}\n\n# TODO: Handle multiple pools.\n# TODO: Handle system msi and VMA clusters.\nif [ ! -z ${SYSTEM_MSI_CLUSTER:-} ]; then\n  if \"${SYSTEM_MSI_CLUSTER}\" == \"true\" ]; then\n    echo \"System MSI cluster flag enabled\"\n    full_resourceid=$(az group show -n ${RESOURCE_GROUP} -o json | jq '.id' | sed 's/\"//g')\n    echo \"Resource id for the group: ${full_resourceid}\"\n    vmss_name=$(az vmss list -g ${RESOURCE_GROUP} -o json | jq '.[0].name' | sed 's/\"//g')\n    if [ \"${vmss_name}\" == \"\" ]; then\n      echo \"Could not find VMSS node pool. Currently e2e support is only for single VMSS pool + System MSI\"\n      exit 1\n    fi\n    echo \"Found VMSS: \" ${vmss_name}\n    vmss_sys_id=$(az vmss identity show -g ${RESOURCE_GROUP} -n ${vmss_name} -o json | jq '.principalId' | sed 's/\"//g')\n    echo \"System MSI principal id: \" ${vmss_sys_id}\n    echo \"Assigning system assigned MSI 'Contributor' role to the resource group ${RESOURCE_GROUP} for MIC assignments\"\n    az role assignment create --role \"Contributor\" --assignee ${vmss_sys_id} --scope ${full_resourceid}\n    # set the AZURE_CLIENT_ID to be the system assigned identity of the vmss pool\n    unset AZURE_CLIENT_ID\n    echo \"Setting the ${vmss_sys_id} as the AZURE_CLIENT_ID\"\n    AZURE_CLIENT_ID=${vmss_sys_id}\n  fi\nfi\n\n[[ ! -z \"${AZURE_CLIENT_ID:-}\" ]] || (echo 'Must specify AZURE_CLIENT_ID' && exit -1)\n\n# Create a keyvault\necho \"Creating a test keyvault...\"\naz keyvault create -g \"${RESOURCE_GROUP}\" -n \"${KEYVAULT_NAME}\"\n\necho \"Creating a test secret in ${KEYVAULT_NAME}\"\naz keyvault secret set --vault-name \"${KEYVAULT_NAME}\" -n \"${KEYVAULT_SECRET_NAME}\" --value test-value\n\nidentities=(\n    \"cluster-identity\"\n    \"keyvault-identity\"\n    \"keyvault-identity-0\"\n    \"keyvault-identity-1\"\n    \"keyvault-identity-2\"\n    \"keyvault-identity-3\"\n    \"keyvault-identity-4\"\n    \"keyvault-identity-5\"\n    \"immutable-identity\"\n)\n\nfor identity in \"${identities[@]}\"; do\n    echo \"Creating ${identity} and assign appropriate roles...\"\n    az identity create -g \"${RESOURCE_GROUP}\" -n \"${identity}\"\n    IDENTITY_CLIENT_ID=$(az identity show -g \"${RESOURCE_GROUP}\" -n \"${identity}\" --query 'clientId' -otsv)\n    IDENTITY_PRINCIPAL_ID=$(az identity show -g \"${RESOURCE_GROUP}\" -n \"${identity}\" --query 'principalId' -otsv)\n    az role assignment create --role 'Managed Identity Operator' --assignee \"${AZURE_CLIENT_ID}\" --scope \"/subscriptions/${SUBSCRIPTION_ID}/resourcegroups/${RESOURCE_GROUP}/providers/Microsoft.ManagedIdentity/userAssignedIdentities/${identity}\" || true\n    if [[ \"${identity}\" == \"keyvault-identity-5\" ]]; then\n        # Create identity with not enough permissions to test failure path\n        retry_cmd \"az keyvault set-policy -n ${KEYVAULT_NAME} --secret-permissions list --spn ${IDENTITY_CLIENT_ID}\" \"set policy failed\"\n    elif [[ \"${identity}\" == \"cluster-identity\" ]]; then\n        retry_cmd \"az role assignment create --role Reader --assignee ${IDENTITY_PRINCIPAL_ID} -g ${RESOURCE_GROUP}\" \"role assignment failed\"\n        continue\n    else\n        retry_cmd \"az keyvault set-policy -n ${KEYVAULT_NAME} --secret-permissions get list --spn ${IDENTITY_CLIENT_ID}\" \"set policy failed\"\n    fi\n\n    # The following command might need a couple of retries to succeed\n    retry_cmd \"az role assignment create --role Reader --assignee ${IDENTITY_PRINCIPAL_ID} --scope /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.KeyVault/vaults/${KEYVAULT_NAME}\" \"role assignment failed\"\ndone\n\necho \"Creating keyvault-sp and assign appropriate roles...\"\nSERVICE_PRINCIPAL_CLIENT_SECRET=$(az ad sp create-for-rbac --role \"Reader\" --scope \"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}\" --name http://keyvault-sp --query 'password' -otsv)\nSERVICE_PRINCIPAL_CLIENT_ID=$(az ad sp show --id http://keyvault-sp --query 'appId' -otsv)\nretry_cmd \"az keyvault set-policy -n ${KEYVAULT_NAME} --secret-permissions get list --spn ${SERVICE_PRINCIPAL_CLIENT_ID}\" \"set policy failed\"\n", "num_lines": 99}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e # stop on errors\nset -x # print commands when they are executed\n\n\n# this scripts sets up your azure subscription to enable AKS\n\naz provider register -n Microsoft.Network\naz provider register -n Microsoft.Storage\naz provider register -n Microsoft.Compute\naz provider register -n Microsoft.ContainerService\n", "num_lines": 13}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e # stop on errors\n\nif [ -z \"$RG\" ]\nthen\n      echo \"Resource Group Name Not Set. Set the env variable with the following command:\"\n      echo \"export RG = \\\"rg-name\\\" \"\n      return 1\nelse\n     echo \"Creating $RG resource group for this project\"\nfi\n\n\nset -x # print commands when they are executed\n\naz group create --name $RG --location eastus\n", "num_lines": 18}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nif [ -z \"$RG\" ]\nthen\n      echo \"Resource Group Name Not Set. Set the env variable with the following command:\"\n      echo \"export RG=\\\"rg-name\\\" \"\n      return 1\nfi\n\nif [ -z \"$K8S_NAME\" ]\nthen\n      echo \"Kubernetes Cluster Name Not Set. Set the env variable with the following command:\"\n      echo \"export K8S_NAME=\\\"K8S_NAME\\\" \"\n      return 1\nfi\n\necho \"Creating AKS cluster named $K8S_NAME with 1 node. This may take a while...\"\nset -x\n\naz aks create --resource-group $RG --name $K8S_NAME --node-count 1 --generate-ssh-keys\n", "num_lines": 23}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nif [ -z \"$RG\" ]\nthen\n      echo \"Resource Group Name Not Set. Set the env variable with the following command:\"\n      echo \"export RG = \\\"rg-name\\\" \"\n      return 1\nfi\n\nif [ -z \"$K8S_NAME\" ]\nthen\n      echo \"K8S Name Not Set. Set the env variable with the following command:\"\n      echo \"export K8S_NAME = \\\"k8s-name\\\" \"\n      return 1\nfi\n\n\nset -x\n\naz aks get-credentials --resource-group $RG --name $K8S_NAME\n\nset +x\n\necho \"kubectl is now configured. Run the following command to see your 1 node\"\necho \"kubectl get nodes\"\n", "num_lines": 28}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd \"${0%/*}\"\n\nset -e\nset -x\n\nkubectl apply -f ../../../../crd/azureAssignedIdentityCrd.yaml\nkubectl apply -f ../../../../crd/azureIdentityBindingCrd.yaml\nkubectl apply -f ../../../../crd/azureIdentityCrd.yaml", "num_lines": 10}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd \"${0%/*}\"\n\nset -e\nset -x\n\nkubectl apply -f ../../../../deploy/infra/deployment.yaml", "num_lines": 8}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nset -x\n\n# had to create the identity in the generated RG\n# https://github.com/Azure/aad-pod-identity/issues/38\n# you will need to replace the resource group below with the correct name\n# you may need to look in the Azure Portal to find the correct name\n# or you can use the CLI with something like \n# $az group list | grep 'k8s'\n\nif [ -z \"$MC_RG\" ]\nthen\n      echo \"K8S Resource Group Name Not Set. Set the env variable with the following command:\"\n      echo \"export MC_RG=\\\"resource-group-name\\\" \"\n      return 1\nfi\n\nif [ -z \"$SUB_ID\" ]\nthen\n      SUB_ID=$(az account show | jq -r .id)\n      echo \"Subscription ${SUB_ID} detected from environment\"\nfi\n\nexport principalid=$(az identity create --name demo-aad1 --resource-group $MC_RG --query 'principalId' -o tsv)\naz role assignment create --role Reader --assignee $principalid --scope /subscriptions/$SUB_ID/resourcegroups/$MC_RG\n", "num_lines": 29}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd \"${0%/*}\"\n\nfile=\"../../../../deploy/demo/deployment.yaml\"\n\nset -e\necho \"To deploy the demo app, update the /deploy/demo.deployment.yaml arguments with \\\nyour subscription, clientID and resource group. \\\nMake sure your identity with the client ID has reader permission to the resource group provided in the input.\"\n\nread -p \"Press enter to continue\"\n\nclient_id=$(az identity show -n demo-aad1 -g ${MC_RG} | jq -r .clientId)\nsubscription_id=$(az account show | jq -r .id)\n\nperl -pi -e \"s/CLIENT_ID/${client_id}/\" ${file}\nperl -pi -e \"s/SUBSCRIPTION_ID/${subscription_id}/\" ${file}\nperl -pi -e \"s/RESOURCE_GROUP/${MC_RG}/\" ${file}\n\n\n\n# aad-pod-identity/deploy/demo/deployment.yaml is the original file \nset -x\n\nkubectl apply -f ${file} \n", "num_lines": 27}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd \"${0%/*}\"\n\nfile=\"../../../../deploy/demo/aadpodidentity.yaml\"\n\nset -e\n\necho \"To give the Azure Id to the cluster, update the deploy/aadpodidentity.yaml spec with \\\nyour subscription, clientID, resource group, and type (0=Azure Id, 1=Service Principal). \"\n\nread -p \"Press enter to continue\"\n\nset -x\n\nclient_id=$(az identity show -n demo-aad1 -g ${MC_RG} | jq -r .clientId)\nresource_id=$(az identity show -n demo-aad1 -g ${MC_RG} | jq -r .id)\n\nperl -pi -e \"s/CLIENT_ID/${client_id}/\" ${file}\nperl -pi -e \"s/RESOURCE_ID/${resource_id//\\//\\\\/}/\" ${file}\n\nkubectl apply -f ${file}\n", "num_lines": 23}
{"repo_name": "aad-pod-identity", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd \"${0%/*}\"\n\nset -e\n\necho \"To give the Azure Id to the cluster, update the deploy/aadpodidentitybinding.yaml spec with \\\nyour binding name from step 3's AzureIdentity, and a pod selector to assign tge Id\"\n\nread -p \"Press enter to continue\"\n\nset -x\n\nkubectl apply -f ../../../../deploy/demo/aadpodidentitybinding.yaml\n", "num_lines": 15}
{"repo_name": "aaz-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nTAG=$(python -c 'from version import VERSION; print(\"v\" + VERSION)')\n\nread -p \"Creating new release for $TAG. Do you want to continue? [Y/n] \" prompt\n\nif [[ $prompt == \"y\" || $prompt == \"Y\" || $prompt == \"yes\" || $prompt == \"Yes\" ]]; then\n    git add -A\n    git commit -m \"Bump version to $TAG for release\" || true && git push\n    echo \"Creating new git tag $TAG\"\n    git tag \"$TAG\" -m \"$TAG\"\n    git push --tags\nelse\n    echo \"Cancelled\"\n    exit 1\nfi\n", "num_lines": 19}
{"repo_name": "abfs-backport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script to patch legacy Hadoop with new ABFS driver (hadoop-azure.*.jar) that has been specifically backported\n# for the targeted Hadoop distro and version.\n# To fully patch a cluster, this script must be run on EVERY node to update the local filesystem. On ONE NODE ONLY\n# the -a switch must be specified to patch the HDFS contents.\n\n# Parameters\nAPPLY_HDFS_PATCH=0\nHDFS_USER=hdfs\nDIR_PREFIX=/usr/hdp/\nHDFS_DIR_PREFIX=/hdp/apps/\nROLLBACK=0\nTARGET_RELEASE=\"HDP-2.5.2\"\n\n# Constants\nexport MATCHED_JAR_FILE_NAME=hadoop-azure\nGITHUB_API_ROOT_URI=https://api.github.com/repos/Azure/abfs-backport\nCURR_TIME=$(date \"+%Y-%m-%d-%H-%M-%S\")\nBACKUP_SUFFIX=\".original_${CURR_TIME}\"\nJAR_EXTENSION=\".jar\"\nJAR_FIND_SUFFIX=\"\"\n\ncheckstatus() {\n    \n     if [ $? -ne 0 ]; then\n        echo \"DEBUG... $1 failed\"\n    else\n        echo \"DEBUG... $1 success\"\n    fi\n}\n\nwhich jq > /dev/null\nif [ $? -ne 0 ]; then\n\n    echo \"This script requires jq to run. Please install using preferred package manager\"\n    exit 1\nfi\n\nwhile getopts \":a?hu:p:P:R:\" options\ndo\n    case \"${options}\" in\n        a)\n            APPLY_HDFS_PATCH=1\n            ;;\n        u)\n            HDFS_USER=${OPTARG}\n            ;;\n        t)\n            TARGET_RELEASE=${OPTARG}\n            ;;\n        p)\n            DIR_PREFIX=${OPTARG}\n            ;;\n        P)\n            HDFS_DIR_PREFIX=${OPTARG}\n            ;;\n        R)\n            ROLLBACK=1\n            ROLLBACK_VERSION=${OPTARG}\n            if [ -z ${ROLLBACK_VERSION} ]; then\n                echo \"Exiting; Backup version parameter is required for rollback\"\n                exit 4\n            fi\n            BACKUP_SUFFIX=\".original_${ROLLBACK_VERSION}\"\n            ;;\n        *|?|h)\n            echo \"Usage: $0 [-a] [-u HDFS_USER] [-t TARGET_VERSION] [-p DIRECTORY_PREFIX] [-P HDFS_DIRECTORY_PREFIX] [-R] [-?]\"\n            echo \"\"\n            echo \"Where:\"\n            echo \"  -a              Update HDFS contents. This switch should only be specified for ONE node in a cluster patch.\"\n            echo \"  -u HDFS_USER    Specifies the user name with superuser privileges on HDFS. Applicable only if the -a switch is specified.\"\n            echo \"  -p DIRECTORY_PREFIX \"\n            echo \"                  Specifies a prefix that is specific to the Hadoop distro & version to search for files to patch.\"\n            echo \"  -P HDFS_DIRECTORY_PREFIX \"\n            echo \"                  Specifies a prefix that is specific to the Hadoop distro & version to search on HDFS for files to patch.\"\n            echo \"  -R ROLLBACK_VERSION \"\n            echo \"                  Rollback installation. Restores previously backed up versions of hadoop-azure jar file. Rollback for HDFS \"\n            echo \"                  should follow same model as deployment. Specify the backup version for the rollback. Ex: Specify 2020-06-07-10-10-10 \"\n            echo \"                  for the backup file named hadoop-azure.*.jar.original_2020-06-07-10-10-10\"\n            exit 1\n            ;;\n    esac\ndone\n\n\n[[ \"${DIR_PREFIX}\" != */ ]] && DIR_PREFIX=\"${DIR_PREFIX}/\"\n[[ \"${HDFS_DIR_PREFIX}\" != */ ]] && HDFS_DIR_PREFIX=\"${HDFS_DIR_PREFIX}/\"\n\n\n# Confirm rollback\nif [ $ROLLBACK -gt 0 ]; then\n    \n    echo \"find $DIR_PREFIX -name $MATCHED_JAR_FILE_NAME*.jar$BACKUP_SUFFIX -a ! -name *datalake* | wc -l\"\n    JARCOUNT=$(find $DIR_PREFIX -name $MATCHED_JAR_FILE_NAME*.jar$BACKUP_SUFFIX -a ! -name *datalake* | wc -l)\n    echo \"jar files found with rollback version: $JARCOUNT\"\n\n    echo \"find $DIR_PREFIX -name *.tar.gz${BACKUP_SUFFIX} -a ! -name *datalake* | wc -l\"\n    GZCOUNT=$(find $DIR_PREFIX -name ${GZ}${BACKUP_SUFFIX} -a ! -name *datalake* | wc -l)\n    echo \"Zip files found with rollback version: $GZCOUNT\"\n\n    TOT=$(($JARCOUNT+$GZCOUNT))\n    echo \"Number of files found for rollback : $TOT\"\n    if [[ ${TOT} -eq 0 ]]; then\n        echo \"Exiting. Backup version for rollback specified is not found.\"\n        exit 4\n    fi\n\n    echo \"***************** NOTICE ****************************\"\n    echo \"This script will rollback previously applied changes.\"\n    echo \"Multiple patches and rollbacks are NOT idempotent. Rolling back after applying multiple patches \"\n    echo \"may result in an unusable system.\"\n    echo \"Only rollback if you are confident there is only one saved original version (*.jar.original).\"\n    read -r -p \"Are you sure you want to proceed with this operation? [y/N] \" response\n    if [ \"${response,,}\" != \"y\" ]; then\n\n        exit 4\n    fi\n    JAR_FIND_SUFFIX=\"*\"\nfi\n\n\nRELEASE_INFO=$(curl \"${GITHUB_API_ROOT_URI}/releases/tags/${TARGET_RELEASE}\")\nJAR_ASSET=$(echo $RELEASE_INFO | jq -r '.assets[] | select(.content_type == \"application/java-archive\" or .content_type == \"application/octet-stream\") | .')\nif [[ -z \"$JAR_ASSET\" ]]; then\n\n    echo \"Unable to get information for .jar file associated with $TARGET_RELEASE release.\"\n    exit 4\nfi\nPATCHED_JAR_FILE_NAME=$(basename $(echo $JAR_ASSET | jq -r '.name') .jar)\nREMOTE_PATCH_PATH=$(echo $JAR_ASSET | jq -r '.browser_download_url')\nLOCAL_PATCH_PATH=\"/tmp/$PATCHED_JAR_FILE_NAME.new\"\n\nif [ $ROLLBACK -eq 0 ]; then\n\n    if [ -e $LOCAL_PATCH_PATH ]; then \n\n        rm $LOCAL_PATCH_PATH; \n        checkstatus \"rm $LOCAL_PATCH_PATH;\"\n    fi\n    echo \"\"\n    echo \"Downloading $REMOTE_PATCH_PATH to $LOCAL_PATCH_PATH\"\n    wget $REMOTE_PATCH_PATH -O $LOCAL_PATCH_PATH\n    if [ $? -ne 0 ]; then\n\n        echo \"ERROR: failed to download $REMOTE_PATCH_PATH to $LOCAL_PATCH_PATH\"\n        exit 3\n    fi\nfi\n\n\necho \"\"\necho \"Locating all JAR files in $DIR_PREFIX*.tar.gz\"\nGZs=$(find \"$DIR_PREFIX\" -name \"*.tar.gz\" -print0 | xargs -0 zgrep \"$MATCHED_JAR_FILE_NAME\" | tr \":\" \"\\n\" | grep .tar.gz)\nfor GZ in $GZs\ndo\n\n    echo $GZ\n    if [ $ROLLBACK -eq 0 ]; then\n\n        if [[ ! -e \"${GZ}${BACKUP_SUFFIX}\" ]]; then\n\n            cp \"$GZ\" \"${GZ}${BACKUP_SUFFIX}\"\n            checkstatus \"cp $GZ ${GZ}${BACKUP_SUFFIX}\"\n        fi\n\n        ARCHIVE_DIR=\"${GZ}.dir\"\n        if [[ -d $ARCHIVE_DIR ]]; then\n\n            rm -rf \"$ARCHIVE_DIR\"\n            checkstatus \"rm -rf \"$ARCHIVE_DIR\"\"\n        fi\n        mkdir \"$ARCHIVE_DIR\"\n        checkstatus \"mkdir $ARCHIVE_DIR\"\n        echo \"    tar -C \"$ARCHIVE_DIR\" -zxf $GZ\"\n        tar -C \"$ARCHIVE_DIR\" -zxf \"$GZ\"\n        checkstatus \"tar -C $ARCHIVE_DIR -zxf $GZ\"\n    else\n\n        # Rollback changes\n        if [[ -e \"${GZ}${BACKUP_SUFFIX}\" ]]; then\n\n            echo \"    cp ${GZ}${BACKUP_SUFFIX} $GZ\"\n            cp \"${GZ}${BACKUP_SUFFIX}\" \"$GZ\" \n            checkstatus \"cp ${GZ}${BACKUP_SUFFIX} $GZ\"\n            rm \"${GZ}${BACKUP_SUFFIX}\"\n            checkstatus \"rm ${GZ}${BACKUP_SUFFIX}\"\n        fi\n    fi\ndone\n\n\necho \"\"\necho \"Updating all JAR files with the same name in $DIR_PREFIX$MATCHED_JAR_FILE_NAME*.jar$JAR_FIND_SUFFIX\"\nfor DST in $(find \"$DIR_PREFIX\" -name \"$MATCHED_JAR_FILE_NAME*.jar$JAR_FIND_SUFFIX\" -a ! -name \"*datalake*\")\ndo\n    echo $DST\n    if [ $ROLLBACK -eq 0 ]; then\n\n        # Backup original file (jar or symlink) if not already backed up\n        if [[ ! -e \"${DST}${BACKUP_SUFFIX}\" ]]; then\n\n            cp -P \"$DST\" \"${DST}${BACKUP_SUFFIX}\"\n            checkstatus \"cp $DST ${DST}${BACKUP_SUFFIX}\"\n        fi\n\n        # Different handling for symlink or real file\n        if [[ ! -h \"$DST\" ]]; then\n\n            # Replace with patched JAR\n            rm -f \"$DST\"\n            checkstatus \"rm -f $DST\"\n            DST=\"$(dirname \"$DST\")/$PATCHED_JAR_FILE_NAME.jar\"\n            echo \"    cp $LOCAL_PATCH_PATH $DST\"\n            cp \"$LOCAL_PATCH_PATH\" \"$DST\"\n            checkstatus \"cp $LOCAL_PATCH_PATH $DST\"\n        else\n\n            # For symlink, assume the target will be replaced with the correctly named file. Just update the link.\n            NEW_TARGET=\"$(dirname $(readlink \"$DST\"))/$PATCHED_JAR_FILE_NAME.jar\"\n            ln -sfn \"$NEW_TARGET\" \"$DST\"\n            checkstatus \"ln -sfn NEW_TARGET DST\"\n        fi\n        \n    else\n\n        # Rollback changes - need to handle 2 cases; hadoop-azure*.jar.original -> hadoop-azure*.jar & hadoop-azure*.jar -> rm\n        DST_FILENAME=$(basename \"$DST\")\n        DST_EXTENSION=.${DST_FILENAME##*.}\n        if [[ \"$DST_EXTENSION\" == \"$BACKUP_SUFFIX\" ]]; then\n\n            # hadoop-azure*.jar.original -> hadoop-azure*.jar\n            DST_ORIG=$(dirname \"$DST\")/$(basename \"$DST\" $BACKUP_SUFFIX)\n            echo \"    cp ${DST} $DST_ORIG\"\n            cp -P \"${DST}\" \"$DST_ORIG\"\n            checkstatus \"cp ${DST} $DST_ORIG\"\n            rm \"${DST}\"\n            checkstatus \"rm ${DST}\"\n\n        elif [[ \"$DST_EXTENSION\" == \"$JAR_EXTENSION\" ]]; then\n\n            # hadoop-azure*.jar -> rm\n            echo \"    rm $DST\"\n            rm \"$DST\"\n            checkstatus \"rm $DST\"\n        fi\n    fi\ndone\n\n\n# HDFS update\nif [ $APPLY_HDFS_PATCH -gt 0 ]; then\n\n    echo \"\"\n    echo \"Updating all JAR files on HDFS matching; $HDFS_DIR_PREFIX$MATCHED_JAR_FILE_NAME*.jar$JAR_FIND_SUFFIX\"\n    for HDST in $(sudo -u $HDFS_USER hadoop fs -find \"$HDFS_DIR_PREFIX\" -name \"$MATCHED_JAR_FILE_NAME*.jar$JAR_FIND_SUFFIX\" | grep -v \"datalake\")\n    do\n\n        if [ $ROLLBACK -eq 0 ]; then\n\n            sudo -u $HDFS_USER hadoop fs -test -e \"${HDST}${BACKUP_SUFFIX}\"\n            if [ $? -ne 0 ]; then\n\n                sudo -u $HDFS_USER hadoop fs -cp \"$HDST\" \"${HDST}${BACKUP_SUFFIX}\"\n                checkstatus \"hadoop fs -cp $HDST ${HDST}${BACKUP_SUFFIX})\"\n            fi\n\n            sudo -u $HDFS_USER hadoop fs -rm $HDST\n            checkstatus \"hadoop fs -rm $HDST)\"\n            HDST=\"$(dirname \"$HDST\")/$PATCHED_JAR_FILE_NAME.jar\"\n            echo \"    hadoop fs -put -f $LOCAL_PATCH_PATH $HDST\"\n            sudo -u $HDFS_USER hadoop fs -put -f \"$LOCAL_PATCH_PATH\" \"$HDST\"\n            checkstatus \"hadoop fs -put -f $LOCAL_PATCH_PATH $HDST\"\n        else\n\n            # Rollback changes - need to handle 2 cases; hadoop-azure*.jar.original -> hadoop-azure*.jar & hadoop-azure*.jar -> rm\n            HDST_FILENAME=$(basename \"$HDST\")\n            HDST_EXTENSION=.${HDST_FILENAME##*.}\n            if [[ \"$HDST_EXTENSION\" == \"$BACKUP_SUFFIX\" ]]; then\n\n                # hadoop-azure*.jar.original -> hadoop-azure*.jar\n                HDST_ORIG=$(dirname \"$HDST\")/$(basename \"$HDST\" $BACKUP_SUFFIX)\n                echo \"    hadoop fs -cp $HDST $HDST_ORIG\"\n                sudo -u $HDFS_USER hadoop fs -cp \"$HDST\" \"$HDST_ORIG\" \n                checkstatus \"hadoop fs -cp $HDST $HDST_ORIG\"\n                sudo -u $HDFS_USER hadoop fs -rm \"$HDST\"\n                checkstatus \"hadoop fs -rm $HDST\"\n\n            elif [[ \"$HDST_EXTENSION\" == \"$JAR_EXTENSION\" ]]; then\n\n                # hadoop-azure*.jar -> rm\n                echo \"    hadoop fs -rm $HDST\"\n                sudo -u $HDFS_USER hadoop fs -rm \"$HDST\"\n                checkstatus \"hadoop fs -rm $HDST\"\n            fi\n        fi\n    done\nfi\n\n\nif [ $ROLLBACK -eq 0 ]; then\n\n    echo \"\"\n    echo \"Updating all .tar.gz\"\n    for GZ in $GZs\n    do\n\n        echo \"    tar -czf $GZ -C ${GZ}.dir\"\n        tar -czf \"$GZ\" -C \"${GZ}.dir\" .\n        checkstatus \"    tar -czf $GZ -C ${GZ}.dir\"\n        rm -rf \"${GZ}.dir\"\n        checkstatus \"rm -rf ${GZ}.dir\"\n    done\nfi\n\n\nif [ $APPLY_HDFS_PATCH -gt 0 ]; then\n\n    echo \"\"\n    echo \"Updating all .tar.gz files on HDFS matching $HDFS_DIR_PREFIX*.tar.gz\"\n    # Get list of *.tar.gz files from HDFS & filter for those containing our patch jar in 2 steps, so that we can correctly preserve the user context\n    HGZ_FILES_ALL=$(sudo -u $HDFS_USER hadoop fs -find \"$HDFS_DIR_PREFIX\" -name \"*.tar.gz\")\n    for HGZ in $(for f in $HGZ_FILES_ALL; do sudo -u $HDFS_USER hadoop fs -cat $f | tar -tzv | grep \"$MATCHED_JAR_FILE_NAME\" && echo $f; done | grep \".tar.gz\")\n    do\n\n        echo \"$HGZ\"\n        if [ $ROLLBACK -eq 0 ]; then\n\n            # Create backup\n            sudo -u $HDFS_USER hadoop fs -test -e \"${HGZ}${BACKUP_SUFFIX}\"\n            if [ $? -ne 0 ]; then\n\n                sudo -u $HDFS_USER hadoop fs -cp \"$HGZ\" \"${HGZ}${BACKUP_SUFFIX}\"\n                checkstatus \"hadoop fs -cp $HGZ ${HGZ}${BACKUP_SUFFIX}\"\n            fi\n\n            # Get the archive, update it with the new jar, repackage the archive & copy it to HDFS\n            ARCHIVE_NAME=$(basename $HGZ)\n            ARCHIVE_DIR=/tmp/${ARCHIVE_NAME}.dir\n            LOCAL_TAR_FILE=/tmp/$ARCHIVE_NAME\n\n            if [[ -e $LOCAL_TAR_FILE ]]; then\n\n                rm -f $LOCAL_TAR_FILE;\n                checkstatus \"rm -f $LOCAL_TAR_FILE;\"\n            fi\n            sudo -u $HDFS_USER hadoop fs -copyToLocal \"$HGZ\" \"$LOCAL_TAR_FILE\"\n            checkstatus \"sudo -u $HDFS_USER hadoop fs -copyToLocal $HGZ $LOCAL_TAR_FILE\"\n\n            if [[ -d $ARCHIVE_DIR ]]; then\n\n                rm -rf $ARCHIVE_DIR\n                checkstatus \"rm -rf $ARCHIVE_DIR\"\n            fi\n            mkdir $ARCHIVE_DIR\n            checkstatus \"mkdir $ARCHIVE_DIR\"\n            tar -xzf $LOCAL_TAR_FILE -C $ARCHIVE_DIR\n            checkstatus \"tar -xzf $LOCAL_TAR_FILE -C $ARCHIVE_DIR\"\n\n            for DST in $(find $ARCHIVE_DIR -name \"$MATCHED_JAR_FILE_NAME*.jar\" -a ! -name \"*datalake*\")\n            do\n\n                # Backup original JAR if not already backed up\n                if [[ ! -e \"${DST}${BACKUP_SUFFIX}\" ]]; then\n\n                    cp \"$DST\" \"${DST}${BACKUP_SUFFIX}\"\n                    checkstatus \"cp $DST ${DST}${BACKUP_SUFFIX}\"\n                fi\n                rm -f \"$DST\"\n                checkstatus \"rm -f $DST\"\n                cp \"$LOCAL_PATCH_PATH\" \"$(dirname \"$DST\")/$PATCHED_JAR_FILE_NAME.jar\"\n                checkstatus \"cp $LOCAL_PATCH_PATH $(dirname $DST)/$PATCHED_JAR_FILE_NAME.jar\"\n            done\n\n            cd $ARCHIVE_DIR\n            checkstatus \"cd $ARCHIVE_DIR\"\n            tar -zcf $LOCAL_TAR_FILE *\n            checkstatus \"tar -zcf $LOCAL_TAR_FILE *\"\n            cd ..\n            checkstatus \"cd ..\"\n\n            echo \"    hadoop fs -copyFromLocal -p -f $LOCAL_TAR_FILE $HGZ\"\n            sudo -u $HDFS_USER hadoop fs -copyFromLocal -p -f \"$LOCAL_TAR_FILE\" \"$HGZ\"\n            checkstatus \"sudo -u $HDFS_USER hadoop fs -copyFromLocal -p -f $LOCAL_TAR_FILE $HGZ\"\n            rm -rf $ARCHIVE_DIR\n            checkstatus \"rm -rf $ARCHIVE_DIR\"\n            rm -f $LOCAL_TAR_FILE\n            checkstatus \"rm -f $LOCAL_TAR_FILE\"\n        else\n\n            # Rollback changes\n            sudo -u $HDFS_USER hadoop fs -test -e \"${HGZ}${BACKUP_SUFFIX}\"\n            checkstatus \"sudo -u $HDFS_USER hadoop fs -test -e ${HGZ}${BACKUP_SUFFIX}\"\n            if [ $? -eq 0 ]; then\n\n                echo \"    hadoop fs -cp ${HGZ}${BACKUP_SUFFIX} ${HGZ}\"\n                sudo -u $HDFS_USER hadoop fs -cp \"${HGZ}${BACKUP_SUFFIX}\" \"$HGZ\" \n                checkstatus \"sudo -u $HDFS_USER hadoop fs -cp ${HGZ}${BACKUP_SUFFIX} $HGZ\"\n                sudo -u $HDFS_USER hadoop fs -rm \"${HGZ}${BACKUP_SUFFIX}\"\n                checkstatus \"sudo -u $HDFS_USER hadoop fs -rm ${HGZ}${BACKUP_SUFFIX}\"\n            fi\n        fi\n    done\nfi\necho \"Finished\"", "num_lines": 405}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n### #################################################################\n### This script is used to bootstrap the environment for the workshop\n### #################################################################\n\n\necho \"### Removes all the generated files from the project\"\nrm -rf pom.xml \\\n  quarkus-app \\\n  micronaut-app\n\necho \"### Creates a Parent POM\"\necho -e \"<?xml version=\\\"1.0\\\"?>\n<project xsi:schemaLocation=\\\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\\\"\n         xmlns=\\\"http://maven.apache.org/POM/4.0.0\\\"\n         xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>io.containerapps.javaruntime.workshop</groupId>\n  <artifactId>parent</artifactId>\n  <version>1.0.0-SNAPSHOT</version>\n  <packaging>pom</packaging>\n  <name>Azure Container Apps and Java Runtimes Workshop</name>\n  \n  <modules>\n    <module>micronaut-app</module>\n    <module>springboot-app</module>\n  </modules>\n\n</project>\n\" >> pom.xml\n\n\necho \"### Bootstraps the Micronaut App\"\ncurl --location --request GET 'https://launch.micronaut.io/create/default/io.containerapps.javaruntime.workshop.micronaut.micronaut-app?lang=JAVA&build=MAVEN&test=JUNIT&javaVersion=JDK_17&features=data-jpa&features=postgres&features=testcontainers&features=micronaut-test-rest-assured' --output micronaut-app.zip && unzip -o micronaut-app.zip && rm micronaut-app.zip\n\necho \"### Bootstraps the Quarkus App\"\nmvn io.quarkus:quarkus-maven-plugin:3.0.0.CR1:create \\\n    -DplatformVersion=3.0.0.CR1 \\\n    -DprojectGroupId=io.containerapps.javaruntime.workshop \\\n    -DprojectArtifactId=quarkus-app \\\n    -DprojectName=\"Azure Container Apps and Java Runtimes Workshop :: Quarkus\" \\\n    -DjavaVersion=17 \\\n    -DclassName=\"io.containerapps.javaruntime.workshop.quarkus.QuarkusResource\" \\\n    -Dpath=\"/quarkus\" \\\n    -Dextensions=\"resteasy, resteasy-jsonb, hibernate-orm-panache, jdbc-postgresql\"\n\necho \"### Bootstraps the Spring Boot App\"\ncurl https://start.spring.io/starter.tgz  -d bootVersion=3.0.5 -d javaVersion=17 -d dependencies=web,data-jpa,postgresql,testcontainers -d type=maven-project -d packageName=io.containerapps.javaruntime.workshop.springboot -d artifactId=springboot-app -d version=1.0.0-SNAPSHOT -d baseDir=springboot-app -d name=springboot -d groupId=io.containerapps.javaruntime.workshop -d description=Azure%20Container%20Apps%20and%20Java%20Runtimes%20Workshop%20%3A%3A%20Spring%20Boot | tar -xzvf -\n\necho \"### Running all the Tests\"\nmvn test\n\n\necho \"### Adding .editorconfig file\"\necho -e \"# EditorConfig helps developers define and maintain consistent\n# coding styles between different editors and IDEs\n# editorconfig.org\n\nroot = true\n\n[*]\n\n# We recommend you to keep these unchanged\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n\n# Change these settings to your own preference\nindent_style = space\nindent_size = 4\n\n[*.{ts, tsx, js, jsx, json, css, scss, yml}]\nindent_size = 2\n\n[*.md]\ntrim_trailing_whitespace = false\nmax_line_length = 1024\n\" >> quarkus-app/.editorconfig\n\ncp quarkus-app/.editorconfig micronaut-app/.editorconfig\ncp quarkus-app/.editorconfig springboot-app/.editorconfig\n", "num_lines": 84}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: ./create-github-template.sh\n# Creates a temporary folder in ~/temp/template with all the needed files to create a new project template.\n##############################################################################\n\nTEMPLATE_HOME=~/temp/template\nmkdir -p $TEMPLATE_HOME\n\ncp -r ../ $TEMPLATE_HOME\n\nrm -rf $TEMPLATE_HOME/.idea\nrm -rf $TEMPLATE_HOME/.vscode\nrm -rf $TEMPLATE_HOME/docs\nrm -rf $TEMPLATE_HOME/scripts/infra/azure.*\nrm -rf $TEMPLATE_HOME/scripts/infra/deploy.sh\nrm -rf $TEMPLATE_HOME/scripts/infra/scale.sh\nrm -rf $TEMPLATE_HOME/scripts/infra/README.md\nrm -rf $TEMPLATE_HOME/scripts/create-github-template.sh\nrm -rf $TEMPLATE_HOME/bootstrap.sh\nrm -rf $TEMPLATE_HOME/CODE_OF_CONDUCT.md\nrm -rf $TEMPLATE_HOME/LICENSE\nrm -rf $TEMPLATE_HOME/SECURITY.md\nrm -rf $TEMPLATE_HOME/SUPPORT.md\n\n### Removing the Workflow files\nrm -rf $TEMPLATE_HOME/.github/workflows/*\ntouch $TEMPLATE_HOME/.github/workflows/.gitkeep\n\n### Removing the Micronaut files\nrm -rf $TEMPLATE_HOME/micronaut-app/target\nrm -rf $TEMPLATE_HOME/micronaut-app/src/main/java/io/containerapps/javaruntime/workshop/micronaut/Micronaut*\nrm -rf $TEMPLATE_HOME/micronaut-app/src/main/java/io/containerapps/javaruntime/workshop/micronaut/Statistics*\ntouch $TEMPLATE_HOME/micronaut-app/src/main/java/io/containerapps/javaruntime/workshop/micronaut/.gitkeep\nrm -rf $TEMPLATE_HOME/micronaut-app/src/main/resources/application.yml\ntouch $TEMPLATE_HOME/micronaut-app/src/main/resources/application.yml\nrm -rf $TEMPLATE_HOME/micronaut-app/src/test/java/io/containerapps/javaruntime/workshop/micronaut/Micronaut*\ntouch $TEMPLATE_HOME/micronaut-app/src/test/java/io/containerapps/javaruntime/workshop/micronaut/.gitkeep\n\n### Removing the Quarkus files\nrm -rf $TEMPLATE_HOME/quarkus-app/target\nrm -rf $TEMPLATE_HOME/quarkus-app/*.sql\nrm -rf $TEMPLATE_HOME/quarkus-app/src/main/java/io/containerapps/javaruntime/workshop/quarkus/Quarkus*\nrm -rf $TEMPLATE_HOME/quarkus-app/src/main/java/io/containerapps/javaruntime/workshop/quarkus/Statistics*\ntouch $TEMPLATE_HOME/quarkus-app/src/main/java/io/containerapps/javaruntime/workshop/quarkus/.gitkeep\nrm -rf $TEMPLATE_HOME/quarkus-app/src/main/resources/application.properties\ntouch $TEMPLATE_HOME/quarkus-app/src/main/resources/application.properties\nrm -rf $TEMPLATE_HOME/quarkus-app/src/test/java/io/containerapps/javaruntime/workshop/quarkus/Quarkus*\ntouch $TEMPLATE_HOME/quarkus-app/src/test/java/io/containerapps/javaruntime/workshop/quarkus/.gitkeep\n\n### Removing the Spring Boot files\nrm -rf $TEMPLATE_HOME/springboot-app/target\nrm -rf $TEMPLATE_HOME/springboot-app/src/main/java/io/containerapps/javaruntime/workshop/springboot/Springboot*\nrm -rf $TEMPLATE_HOME/springboot-app/src/main/java/io/containerapps/javaruntime/workshop/springboot/Statistics*\ntouch $TEMPLATE_HOME/springboot-app/src/main/java/io/containerapps/javaruntime/workshop/springboot/.gitkeep\nrm -rf $TEMPLATE_HOME/springboot-app/src/main/resources/application.properties\ntouch $TEMPLATE_HOME/springboot-app/src/main/resources/application.properties\nrm -rf $TEMPLATE_HOME/springboot-app/src/test/java/io/containerapps/javaruntime/workshop/springboot/Springboot*\ntouch $TEMPLATE_HOME/springboot-app/src/test/java/io/containerapps/javaruntime/workshop/springboot/.gitkeep\n\n\necho -e \"package io.containerapps.javaruntime.workshop.springboot;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringbootApplication {\n\n\tpublic static void main(String[] args) {\n\t\tSpringApplication.run(SpringbootApplication.class, args);\n\t}\n\n}\n\" >> $TEMPLATE_HOME/springboot-app/src/main/java/io/containerapps/javaruntime/workshop/springboot/SpringbootApplication.java\n\n### Creating a new pom.xml without docs\nrm $TEMPLATE_HOME/pom.xml\n\necho -e \"<?xml version=\\\"1.0\\\"?>\n<project xsi:schemaLocation=\\\"http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd\\\" xmlns=\\\"http://maven.apache.org/POM/4.0.0\\\"\n    xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\">\n  <modelVersion>4.0.0</modelVersion>\n  <groupId>io.containerapps.javaruntime.workshop</groupId>\n  <artifactId>parent</artifactId>\n  <version>1.0.0-SNAPSHOT</version>\n  <packaging>pom</packaging>\n  <name>Azure Container Apps and Java Runtimes Workshop</name>\n  <modules>\n    <module>micronaut-app</module>\n    <module>springboot-app</module>\n    <module>quarkus-app</module>\n  </modules>\n</project>\n\" >> $TEMPLATE_HOME/pom.xml\n\n### Removing the .git folder\nrm -rf $TEMPLATE_HOME/.git\n", "num_lines": 99}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: ./azure.sh login|setup|cleanup\n# Setup or cleanup the Azure infrastructure for this project.\n##############################################################################\n# Dependencies: Azure CLI, GitHub CLI, jq\n##############################################################################\n\nset -e\npushd $(dirname ${BASH_SOURCE[0]})\n\nproject_name=\"java-runtimes\"\nenvironment=\"prod\"\nlocation=\"eastus\"\nresource_group_name=rg-${project_name}\n\nshowUsage() {\n  script_name=\"$(basename \"$0\")\"\n  echo \"Usage: ./$script_name setup|cleanup|env\"\n  echo \"Setup or cleanup the Azure infrastructure for this project.\"\n  echo\n  echo \"Commands:\"\n  echo \"  login    Log in to Azure and GitHub\"\n  echo \"  setup    Create Azure infrastructure and setup repo\"\n  echo \"  cleanup  Clean up Azure infrastructure and repo secrets\"\n  echo \"  env      Export environment variables\"\n  echo\n  echo \"Options:\"\n  echo \"  -s        Skip repository setup\"\n  echo \n}\n\nsetupRepo() {\n  echo \"Retrieving Azure subscription...\"\n  echo \"Creating Azure service principal...\"\n\n  # tag::adocCreatePrincipal[]\n  SUBSCRIPTION_ID=$(\n    az account show \\\n      --query id \\\n      --output tsv \\\n      --only-show-errors\n  )\n\n  AZURE_CREDENTIALS=$(\n    MSYS_NO_PATHCONV=1 az ad sp create-for-rbac \\\n      --name=\"sp-${PROJECT}-${UNIQUE_IDENTIFIER}\" \\\n      --role=\"Contributor\" \\\n      --scopes=\"/subscriptions/$SUBSCRIPTION_ID\" \\\n      --sdk-auth \\\n      --only-show-errors\n  )\n\n  echo $AZURE_CREDENTIALS\n  # end::adocCreatePrincipal[]\n\n  REGISTRY_USERNAME=$(\n    az acr credential show \\\n      --resource-group \"$RESOURCE_GROUP\" \\\n      --name \"$REGISTRY\" \\\n      --query \"username\" \\\n      --output tsv\n    )\n\n  REGISTRY_PASSWORD=$(\n    az acr credential show \\\n      --resource-group \"$RESOURCE_GROUP\" \\\n      --name \"$REGISTRY\" \\\n      --query \"passwords[0].value\" \\\n      --output tsv\n  )\n\n  echo \"Retrieving GitHub repository URL...\"\n  remote_repo=$(git config --get remote.origin.url)\n  echo \"Setting up GitHub repository secrets...\"\n  gh secret set AZURE_CREDENTIALS -b\"$AZURE_CREDENTIALS\" -R $remote_repo\n  gh secret set REGISTRY_USERNAME -b\"$REGISTRY_USERNAME\" -R $remote_repo\n  gh secret set REGISTRY_PASSWORD -b\"$REGISTRY_PASSWORD\" -R $remote_repo\n}\n\ncleanupRepo() {\n  echo \"Retrieving GitHub repository URL...\"\n  remote_repo=$(git config --get remote.origin.url)\n  # TODO: delete az sp\n  gh secret delete AZURE_CREDENTIALS -R $remote_repo\n  gh secret delete REGISTRY_USERNAME -R $remote_repo\n  gh secret delete REGISTRY_PASSWORD -R $remote_repo\n  echo \"Cleanup complete.\"\n}\n\ncreateInfrastructure() {\n  echo \"Preparing environment '${environment}' of project '${project_name}'...\"\n\n# tag::adocSetupAzCli[]\n  az config set extension.use_dynamic_install=yes_without_prompt\n  az provider register --namespace Microsoft.App\n  az provider register --namespace Microsoft.OperationalInsights\n  az provider register --namespace Microsoft.Insights\n# end::adocSetupAzCli[]\n\n# tag::adocEnvironmentVariables[]\n  PROJECT=\"java-runtimes\"\n  RESOURCE_GROUP=\"rg-$PROJECT\"\n  LOCATION=\"westeurope\"\n  TAG=\"$PROJECT\"\n\n  LOG_ANALYTICS_WORKSPACE=\"log-$PROJECT\"\n  CONTAINERAPPS_ENVIRONMENT=\"cae-$PROJECT\"\n\n  # If you're using a a dev container, you should manually set this to\n  # a unique value (like your name) to avoid conflicts with other users.\n  UNIQUE_IDENTIFIER=${GITHUB_USER:-$(whoami)}\n  REGISTRY=\"crjavaruntimes${UNIQUE_IDENTIFIER}\"\n  IMAGES_TAG=\"1.0\"\n\n  POSTGRES_DB_ADMIN=\"javaruntimesadmin\"\n  POSTGRES_DB_PWD=\"java-runtimes-p#ssw0rd-12046\"\n  POSTGRES_DB_VERSION=\"14\"\n  POSTGRES_SKU=\"Standard_B1ms\"\n  POSTGRES_TIER=\"Burstable\"\n  POSTGRES_DB=\"psql-stats-$UNIQUE_IDENTIFIER\"\n  POSTGRES_DB_SCHEMA=\"stats\"\n  POSTGRES_DB_CONNECT_STRING=\"jdbc:postgresql://${POSTGRES_DB}.postgres.database.azure.com:5432/${POSTGRES_DB_SCHEMA}?ssl=true&sslmode=require\"\n\n  QUARKUS_APP=\"quarkus-app\"\n  MICRONAUT_APP=\"micronaut-app\"\n  SPRING_APP=\"springboot-app\"\n# end::adocEnvironmentVariables[]\n\n# tag::adocResourceGroup[]\n  az group create \\\n    --name \"$RESOURCE_GROUP\" \\\n    --location \"$LOCATION\" \\\n    --tags system=\"$TAG\"\n# end::adocResourceGroup[]\n\n  echo \"Resource group '$RESOURCE_GROUP' ready.\"\n\n# tag::adocLogAnalytics[]\n  az monitor log-analytics workspace create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --location \"$LOCATION\" \\\n    --tags system=\"$TAG\" \\\n    --workspace-name \"$LOG_ANALYTICS_WORKSPACE\"\n# end::adocLogAnalytics[]\n\n# tag::adocLogAnalyticsSecrets[]\n  LOG_ANALYTICS_WORKSPACE_CLIENT_ID=$(\n    az monitor log-analytics workspace show \\\n      --resource-group \"$RESOURCE_GROUP\" \\\n      --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n      --query customerId  \\\n      --output tsv | tr -d '[:space:]'\n  )\n  echo \"LOG_ANALYTICS_WORKSPACE_CLIENT_ID=$LOG_ANALYTICS_WORKSPACE_CLIENT_ID\"\n\n  LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET=$(\n    az monitor log-analytics workspace get-shared-keys \\\n      --resource-group \"$RESOURCE_GROUP\" \\\n      --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n      --query primarySharedKey \\\n      --output tsv | tr -d '[:space:]'\n  )\n  echo \"LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET=$LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET\"\n# end::adocLogAnalyticsSecrets[]\n\n# tag::adocRegistry[]\n  az acr create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --location \"$LOCATION\" \\\n    --tags system=\"$TAG\" \\\n    --name \"$REGISTRY\" \\\n    --workspace \"$LOG_ANALYTICS_WORKSPACE\" \\\n    --sku Standard \\\n    --admin-enabled true\n# end::adocRegistry[]\n\n# tag::adocRegistryUpdate[]\n  az acr update \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --name \"$REGISTRY\" \\\n    --anonymous-pull-enabled true\n# end::adocRegistryUpdate[]\n\n# tag::adocRegistryShow[]\n  REGISTRY_URL=$(\n    az acr show \\\n      --resource-group \"$RESOURCE_GROUP\" \\\n      --name \"$REGISTRY\" \\\n      --query \"loginServer\" \\\n      --output tsv\n  )\n\n  echo \"REGISTRY_URL=$REGISTRY_URL\"\n# end::adocRegistryShow[]\n\n# tag::adocACAEnv[]\naz containerapp env create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --location \"$LOCATION\" \\\n    --tags system=\"$TAG\" \\\n    --name \"$CONTAINERAPPS_ENVIRONMENT\" \\\n    --logs-workspace-id \"$LOG_ANALYTICS_WORKSPACE_CLIENT_ID\" \\\n    --logs-workspace-key \"$LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET\"\n# end::adocACAEnv[]\n\n# tag::adocACACreate[]\n  az containerapp create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --tags system=\"$TAG\" application=\"$QUARKUS_APP\" \\\n    --image \"mcr.microsoft.com/azuredocs/containerapps-helloworld:latest\" \\\n    --name \"$QUARKUS_APP\" \\\n    --environment \"$CONTAINERAPPS_ENVIRONMENT\" \\\n    --ingress external \\\n    --target-port 80 \\\n    --min-replicas 0 \\\n    --env-vars QUARKUS_HIBERNATE_ORM_DATABASE_GENERATION=validate \\\n               QUARKUS_HIBERNATE_ORM_SQL_LOAD_SCRIPT=no-file \\\n               QUARKUS_DATASOURCE_USERNAME=\"$POSTGRES_DB_ADMIN\" \\\n               QUARKUS_DATASOURCE_PASSWORD=\"$POSTGRES_DB_PWD\" \\\n               QUARKUS_DATASOURCE_JDBC_URL=\"$POSTGRES_DB_CONNECT_STRING\"\n\n  az containerapp create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --tags system=\"$TAG\" application=\"$MICRONAUT_APP\" \\\n    --image \"mcr.microsoft.com/azuredocs/containerapps-helloworld:latest\" \\\n    --name \"$MICRONAUT_APP\" \\\n    --environment \"$CONTAINERAPPS_ENVIRONMENT\" \\\n    --ingress external \\\n    --target-port 80 \\\n    --min-replicas 0 \\\n    --env-vars DATASOURCES_DEFAULT_USERNAME=\"$POSTGRES_DB_ADMIN\" \\\n               DATASOURCES_DEFAULT_PASSWORD=\"$POSTGRES_DB_PWD\" \\\n               DATASOURCES_DEFAULT_URL=\"$POSTGRES_DB_CONNECT_STRING\"\n\n  az containerapp create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --tags system=\"$TAG\" application=\"$SPRING_APP\" \\\n    --image \"mcr.microsoft.com/azuredocs/containerapps-helloworld:latest\" \\\n    --name \"$SPRING_APP\" \\\n    --environment \"$CONTAINERAPPS_ENVIRONMENT\" \\\n    --ingress external \\\n    --target-port 80 \\\n    --min-replicas 0 \\\n    --env-vars SPRING_DATASOURCE_USERNAME=\"$POSTGRES_DB_ADMIN\" \\\n               SPRING_DATASOURCE_PASSWORD=\"$POSTGRES_DB_PWD\" \\\n               SPRING_DATASOURCE_URL=\"$POSTGRES_DB_CONNECT_STRING\"\n\n# end::adocACACreate[]\n\n# tag::adocPostgresCreate[]\n  az postgres flexible-server create \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --location \"$LOCATION\" \\\n    --tags system=\"$TAG\" \\\n    --name \"$POSTGRES_DB\" \\\n    --database-name \"$POSTGRES_DB_SCHEMA\" \\\n    --admin-user \"$POSTGRES_DB_ADMIN\" \\\n    --admin-password \"$POSTGRES_DB_PWD\" \\\n    --public all \\\n    --tier \"$POSTGRES_TIER\" \\\n    --sku-name \"$POSTGRES_SKU\" \\\n    --storage-size 256 \\\n    --version \"$POSTGRES_DB_VERSION\"\n# end::adocPostgresCreate[]\n\n  # In case Julien deletes the database again :-)\n  # az postgres flexible-server db create \\\n  #     --resource-group \"$RESOURCE_GROUP\" \\\n  #     --server-name \"$POSTGRES_DB\" \\\n  #     --database-name \"$POSTGRES_DB_SCHEMA\"\n\n  pushd ../..\n# tag::adocPostgresTable[]\n  az postgres flexible-server execute \\\n    --name \"$POSTGRES_DB\" \\\n    --admin-user \"$POSTGRES_DB_ADMIN\" \\\n    --admin-password \"$POSTGRES_DB_PWD\" \\\n    --database-name \"$POSTGRES_DB_SCHEMA\" \\\n    --file-path \"infrastructure/db-init/initialize-databases.sql\"\n# end::adocPostgresTable[]\n  popd\n\n# tag::adocPostgresSelect[]\n  az postgres flexible-server execute \\\n    --name \"$POSTGRES_DB\" \\\n    --admin-user \"$POSTGRES_DB_ADMIN\" \\\n    --admin-password \"$POSTGRES_DB_PWD\" \\\n    --database-name \"$POSTGRES_DB_SCHEMA\" \\\n    --querytext \"select * from Statistics_Quarkus\"\n# end::adocPostgresSelect[]\n\n# tag::adocPostgresConnectionString[]\n  POSTGRES_CONNECTION_STRING=$(\n    az postgres flexible-server show-connection-string \\\n      --server-name \"$POSTGRES_DB\" \\\n      --admin-user \"$POSTGRES_DB_ADMIN\" \\\n      --admin-password \"$POSTGRES_DB_PWD\" \\\n      --database-name \"$POSTGRES_DB_SCHEMA\" \\\n      --query \"connectionStrings.jdbc\" \\\n      --output tsv\n  )\n\n  echo \"POSTGRES_CONNECTION_STRING=$POSTGRES_CONNECTION_STRING\"\n# end::adocPostgresConnectionString[]\n\n  echo \"Environment '${environment}' of project '${project_name}' ready.\"\n}\n\ndeleteInfrastructure() {\n  echo \"Deleting environment '${environment}' of project '${project_name}'...\"\n  az group delete --yes --name \"${RESOURCE_GROUP}\"\n  echo \"Environment '${environment}' of project '${project_name}' deleted.\"\n}\n\nargs=()\nskip_repo_setup=false\n\nwhile [ $# -gt 0 ]; do\n  case $1 in\n    -s)\n      echo \"Skipping repository setup/cleanup...\"\n      skip_repo_setup=true\n      shift\n      ;;\n    --help)\n      showUsage\n      exit 0\n      ;;\n    -*|--*)\n      showUsage\n      echo \"Unknown option $1\"\n      exit 1\n      ;;\n    *)\n      # save positional arg\n      args+=(\"$1\")\n      shift\n      ;;\n  esac\ndone\n\n# restore positional args\nset -- \"${args[@]}\"\n\ncommand=${1}\n\nif ! command -v az &> /dev/null; then\n  echo \"Azure CLI not found.\"\n  echo \"See https://aka.ms/tools/azure-cli for installation instructions.\"\n  exit 1\nfi\n\nif ! command -v gh &> /dev/null; then\n  echo \"GitHub CLI not found.\"\n  echo \"See https://cli.github.com for installation instructions.\"\n  exit 1\nfi\n\nif [ \"$command\" = \"login\" ]; then\n  echo \"Logging in to Azure...\"\n  az login\n  echo \"Logging in to GitHub...\"\n  gh auth login\n  echo \"Login successful.\"\nelif [ \"$command\" = \"setup\" ]; then\n  createInfrastructure\n  if [ \"$skip_repo_setup\" = false ]; then\n    setupRepo\n  fi\nelif [ \"$command\" = \"cleanup\" ]; then\n  deleteInfrastructure\n  if [ \"$skip_repo_setup\" = false ]; then\n    cleanupRepo\n  fi\nelse\n  showUsage\n  echo \"Error, unknown command '${command}'\"\n  exit 1\nfi\n\nset +e\npopd\n", "num_lines": 384}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: ./deploy.sh\n# Build & deploy apps manually (for testing)\n# Make sure you have the correct environment variables set. For that, first run: source ./azure.sh env\n##############################################################################\n# Dependencies: Azure CLI, jq\n##############################################################################\n\nset -e\ncd $(dirname ${BASH_SOURCE[0]})\ncd ../..\n\necho \"Retrieving credentials...\"\n\n# tag::adocRegistryCredentials[]\nREGISTRY_USERNAME=$(\n  az acr credential show \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --name \"$REGISTRY\" \\\n    --query \"username\" \\\n    --output tsv\n)\necho \"REGISTRY_USERNAME=$REGISTRY_USERNAME\"\n\nREGISTRY_PASSWORD=$(\n  az acr credential show \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --name \"$REGISTRY\" \\\n    --query \"passwords[0].value\" \\\n    --output tsv\n)\necho \"REGISTRY_PASSWORD=$REGISTRY_PASSWORD\"\n# end::adocRegistryCredentials[]\n\necho \"Logging in to Docker registry...\"\necho $REGISTRY_PASSWORD | docker login --username $REGISTRY_USERNAME --password-stdin $REGISTRY_URL\n\necho \"Enabling ingress for each container app...\"\n\n# tag::adocIngressUpdate[]\naz containerapp ingress enable \\\n  --name \"$QUARKUS_APP\" \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --target-port 8701 \\\n  --type external\n\naz containerapp ingress enable \\\n  --name \"$MICRONAUT_APP\" \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --target-port 8702 \\\n  --type external\n\naz containerapp ingress enable \\\n  --name \"$SPRING_APP\" \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --target-port 8703 \\\n  --type external\n# end::adocIngressUpdate[]\n\necho \"Building and deploying Quarkus app...\"\npushd quarkus-app\n\n./mvnw package\n\ndocker build -f src/main/docker/Dockerfile.jvm -t \"$REGISTRY_URL/$PROJECT/$QUARKUS_APP:latest\" .\n\necho \"Pushing the Quarkus app...\"\n\ndocker push \"$REGISTRY_URL/$PROJECT/$QUARKUS_APP:latest\"\n              \necho \"Updating the Quarkus container app...\"\n\naz containerapp update \\\n  --name \"$QUARKUS_APP\" \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --image \"${REGISTRY_URL}/${PROJECT}/${QUARKUS_APP}:latest\" \\\n  --query \"properties.configuration.ingress.fqdn\" \\\n  --output tsv\n\npopd\n\necho \"Retrieving the public URLs...\"\n\n# tag::adocIngressHosts[]\nQUARKUS_HOST=$(\n  az containerapp show \\\n    --name \"$QUARKUS_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n)\necho \"QUARKUS_HOST=$QUARKUS_HOST\"\n\nMICRONAUT_HOST=$(\n  az containerapp show \\\n    --name \"$MICRONAUT_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n)\necho \"MICRONAUT_HOST=$MICRONAUT_HOST\"\n\nSPRING_HOST=$(\n  az containerapp show \\\n    --name \"$SPRING_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n)\necho \"SPRING_HOST=$SPRING_HOST\"\n# end::adocIngressHosts[]\n\necho \"Done.\"\n", "num_lines": 115}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: source env.sh\n# Set all environment variables needed for the project.\n##############################################################################\n# Dependencies: Azure CLI\n##############################################################################\n\necho \"Exporting environment variables...\" \n\nexport PROJECT=\"java-runtimes\"\nexport RESOURCE_GROUP=\"rg-$PROJECT\"\nexport LOCATION=\"eastus\"\nexport TAG=\"$PROJECT\"\n\nexport LOG_ANALYTICS_WORKSPACE=\"log-$PROJECT\"\nexport CONTAINERAPPS_ENVIRONMENT=\"cae-$PROJECT\"\n\nexport UNIQUE_IDENTIFIER=${UNIQUE_IDENTIFIER:-${GITHUB_USER:-$(whoami)}}\n\necho \"Using unique identifier is: $UNIQUE_IDENTIFIER\"\necho \"You can override it by setting it manually before running this script:\"\necho \"export UNIQUE_IDENTIFIER=<your-unique-identifier>\"\n\nexport REGISTRY=\"crjavaruntimes${UNIQUE_IDENTIFIER}\"\nexport IMAGES_TAG=\"1.0\"\n\nexport POSTGRES_DB_ADMIN=\"javaruntimesadmin\"\nexport POSTGRES_DB_PWD=\"java-runtimes-p#ssw0rd-12046\"\nexport POSTGRES_DB_VERSION=\"14\"\nexport POSTGRES_SKU=\"Standard_B1ms\"\nexport POSTGRES_TIER=\"Burstable\"\nexport POSTGRES_DB=\"psql-stats-$UNIQUE_IDENTIFIER\"\nexport POSTGRES_DB_SCHEMA=\"stats\"\nexport POSTGRES_DB_CONNECT_STRING=\"jdbc:postgresql://${POSTGRES_DB}.postgres.database.azure.com:5432/${POSTGRES_DB_SCHEMA}?ssl=true&sslmode=require\"\n\nexport QUARKUS_APP=\"quarkus-app\"\nexport MICRONAUT_APP=\"micronaut-app\"\nexport SPRING_APP=\"springboot-app\"\n\nexport LOG_ANALYTICS_WORKSPACE_CLIENT_ID=$(az monitor log-analytics workspace show  \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n  --query customerId  \\\n  --output tsv \\\n  2>/dev/null | tr -d '[:space:]' \\\n)\n\nexport LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET=$(az monitor log-analytics workspace get-shared-keys \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n  --query primarySharedKey \\\n  --output tsv \\\n  2>/dev/null | tr -d '[:space:]' \\\n)\n\nexport REGISTRY_URL=$(az acr show \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --name \"$REGISTRY\" \\\n  --query \"loginServer\" \\\n  --output tsv \\\n  2>/dev/null \\\n)\n\nexport QUARKUS_HOST=$(\n  az containerapp show \\\n    --name \"$QUARKUS_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\nexport MICRONAUT_HOST=$(\n  az containerapp show \\\n    --name \"$MICRONAUT_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\nexport SPRING_HOST=$(\n  az containerapp show \\\n    --name \"$SPRING_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\necho \"Exported environment variables for project '${PROJECT}'.\"\n", "num_lines": 93}
{"repo_name": "aca-java-runtimes-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: ./scaling.sh\n# Switch auto scaling modes\n# Make sure you have the correct environment variables set.\n# For that, first run: source ./azure.sh env\n##############################################################################\n# Dependencies: Azure CLI\n##############################################################################\n\nset -e\ncd $(dirname ${BASH_SOURCE[0]})\ncd ../..\n\ncommand=${1}\n\nshowUsage() {\n  script_name=\"$(basename \"$0\")\"\n  echo \"Usage: ./$script_name setup|restore|ping\"\n  echo \"Setup auto-scaling mode for apps.\"\n  echo\n  echo \"Commands:\"\n  echo \"  setup    Setup auto-scaling as in the docs\"\n  echo \"  restore  Restore default auto-scaling\"\n  echo \"  ping     Send a curl to the 3 apps\"\n  echo \n}\n\nif [ -z \"$command\" ]; then\n  showUsage\n  exit 1\nfi\n\nif [ \"$command\" == \"setup\" ]; then\n\n  echo \"Setting up auto-scaling...\"\n\n# tag::adocAutoScalingCpu[]\n  az containerapp update \\\n    --name \"$QUARKUS_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --scale-rule-name \"cpu-scaling\" \\\n    --scale-rule-type \"cpu\" \\\n    --scale-rule-metadata type=Utilization value=10 \\\n    --min-replicas 1 \\\n    --max-replicas 10\n# end::adocAutoScalingCpu[]\n\n# tag::adocAutoScalingMemory[]\n  az containerapp update \\\n    --name \"$MICRONAUT_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --scale-rule-name \"memory-scaling\" \\\n    --scale-rule-type \"memory\" \\\n    --scale-rule-metadata type=Utilization value=15 \\\n    --min-replicas 1 \\\n    --max-replicas 10\n# end::adocAutoScalingMemory[]\n\n  echo \"Done.\"\n\nelif [ \"$command\" == \"restore\" ]; then\n\n  echo \"Restoring default auto-scaling...\"\n  \n  az containerapp update \\\n    --name \"$QUARKUS_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --scale-rule-name \"http-scaling\" \\\n    --scale-rule-metadata concurrentRequests=10 \\\n    --min-replicas 0 \\\n    --max-replicas 10\n\n  az containerapp update \\\n    --name \"$MICRONAUT_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --scale-rule-name \"http-scaling\" \\\n    --scale-rule-metadata concurrentRequests=10 \\\n    --min-replicas 0 \\\n    --max-replicas 10\n\n  az containerapp update \\\n    --name \"$SPRING_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --scale-rule-name \"http-scaling\" \\\n    --scale-rule-metadata concurrentRequests=10 \\\n    --min-replicas 0 \\\n    --max-replicas 10\n\n  echo \"Done.\"\n\nelif [ \"$command\" == \"ping\" ]; then\n\n  echo \"Pinging apps...\"\n# tag::adocPingApps[]  \n  curl https://${QUARKUS_HOST}/quarkus\n  echo \n  curl https://${MICRONAUT_HOST}/micronaut\n  echo \n  curl https://${SPRING_HOST}/springboot\n  echo \n# end::adocPingApps[]\n\nelse\n  showUsage\n  exit\nfi\n", "num_lines": 108}
{"repo_name": "aca-java-runtimes-workshop-template", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n##############################################################################\n# Usage: source env.sh\n# Set all environment variables needed for the project.\n##############################################################################\n# Dependencies: Azure CLI\n##############################################################################\n\necho \"Exporting environment variables...\" \n\nexport PROJECT=\"java-runtimes\"\nexport RESOURCE_GROUP=\"rg-$PROJECT\"\nexport LOCATION=\"eastus\"\nexport TAG=\"$PROJECT\"\n\nexport LOG_ANALYTICS_WORKSPACE=\"log-$PROJECT\"\nexport CONTAINERAPPS_ENVIRONMENT=\"cae-$PROJECT\"\n\nexport UNIQUE_IDENTIFIER=${UNIQUE_IDENTIFIER:-${GITHUB_USER:-$(whoami)}}\n\necho \"Using unique identifier is: $UNIQUE_IDENTIFIER\"\necho \"You can override it by setting it manually before running this script:\"\necho \"export UNIQUE_IDENTIFIER=<your-unique-identifier>\"\n\nexport REGISTRY=\"crjavaruntimes${UNIQUE_IDENTIFIER}\"\nexport IMAGES_TAG=\"1.0\"\n\nexport POSTGRES_DB_ADMIN=\"javaruntimesadmin\"\nexport POSTGRES_DB_PWD=\"java-runtimes-p#ssw0rd-12046\"\nexport POSTGRES_DB_VERSION=\"14\"\nexport POSTGRES_SKU=\"Standard_B1ms\"\nexport POSTGRES_TIER=\"Burstable\"\nexport POSTGRES_DB=\"psql-stats-$UNIQUE_IDENTIFIER\"\nexport POSTGRES_DB_SCHEMA=\"stats\"\nexport POSTGRES_DB_CONNECT_STRING=\"jdbc:postgresql://${POSTGRES_DB}.postgres.database.azure.com:5432/${POSTGRES_DB_SCHEMA}?ssl=true&sslmode=require\"\n\nexport QUARKUS_APP=\"quarkus-app\"\nexport MICRONAUT_APP=\"micronaut-app\"\nexport SPRING_APP=\"springboot-app\"\n\nexport LOG_ANALYTICS_WORKSPACE_CLIENT_ID=$(az monitor log-analytics workspace show  \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n  --query customerId  \\\n  --output tsv \\\n  2>/dev/null | tr -d '[:space:]' \\\n)\n\nexport LOG_ANALYTICS_WORKSPACE_CLIENT_SECRET=$(az monitor log-analytics workspace get-shared-keys \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --workspace-name \"$LOG_ANALYTICS_WORKSPACE\" \\\n  --query primarySharedKey \\\n  --output tsv \\\n  2>/dev/null | tr -d '[:space:]' \\\n)\n\nexport REGISTRY_URL=$(az acr show \\\n  --resource-group \"$RESOURCE_GROUP\" \\\n  --name \"$REGISTRY\" \\\n  --query \"loginServer\" \\\n  --output tsv \\\n  2>/dev/null \\\n)\n\nexport QUARKUS_HOST=$(\n  az containerapp show \\\n    --name \"$QUARKUS_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\nexport MICRONAUT_HOST=$(\n  az containerapp show \\\n    --name \"$MICRONAUT_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\nexport SPRING_HOST=$(\n  az containerapp show \\\n    --name \"$SPRING_APP\" \\\n    --resource-group \"$RESOURCE_GROUP\" \\\n    --query \"properties.configuration.ingress.fqdn\" \\\n    --output tsv \\\n    2>/dev/null \\\n)\n\necho \"Exported environment variables for project '${PROJECT}'.\"\n", "num_lines": 93}
{"repo_name": "aca-landing-zone-accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script Definition\nlogpath=/var/log/deploymentscriptlog\n\n# Upgrading Linux Distribution\necho \"#############################\" >> $logpath\necho \"Upgrading Linux Distribution\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update >> $logpath\nsudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n# Install Azure CLI\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Install Docker\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n\n# install Terraform CLI\n# https://learn.hashicorp.com/tutorials/terraform/install-cli\necho \"#############################\" >> $logpath\necho \"Installing Terraform\" >> $logpath\necho \"#############################\" >> $logpath\n\nwget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg\necho \"deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main\" | sudo tee /etc/apt/sources.list.d/hashicorp.list\nsudo apt update && sudo apt install terraform\n\nterraform version", "num_lines": 39}
{"repo_name": "aca-landing-zone-accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##########################################################\n# Example of script to setup the jumpbox, build the images\n# and push them to the container registry\n##########################################################\n\nsudo apt-get update\nsudo apt-get upgrade\n\n# Install Microsoft OpenJDK 17\nubuntu_release=`lsb_release -rs`\nwget https://packages.microsoft.com/config/ubuntu/${ubuntu_release}/packages-microsoft-prod.deb -O packages-microsoft-prod.deb\nsudo dpkg -i packages-microsoft-prod.deb\nrm packages-microsoft-prod.deb\nsudo apt-get install apt-transport-https\nsudo apt-get update\nsudo apt-get install msopenjdk-17 -y\n\n# Install Maven\nwget https://dlcdn.apache.org/maven/maven-3/3.9.1/binaries/apache-maven-3.9.1-bin.tar.gz -P /tmp\nsudo tar xf /tmp/apache-maven-*.tar.gz -C /opt\nsudo ln -s /opt/apache-maven-3.9.1 /opt/maven -s\n\necho \"export JAVA_HOME=/usr/lib/jvm/msopenjdk-17-amd64\" >> ~/.bashrc\necho \"export M2_HOME=/opt/maven\" >> ~/.bashrc\necho \"export MAVEN_HOME=/opt/maven\" >> ~/.bashrc\necho \"export PATH=${M2_HOME}/bin:${PATH}\" >> ~/.bashrc\nexit\n\nsource ~/.bashrc\n\n# Install Docker\nsudo apt-get remove docker docker-engine docker.io containerd runc\nsudo apt-get update\nsudo apt-get install     ca-certificates     curl     gnupg     lsb-release -y\nsudo mkdir -p /etc/apt/keyrings\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg\necho   \"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \\\n  $(lsb_release -cs) stable\" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null\nsudo apt-get update\nsudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin -y\n# TODO check this. Needed to run docker without sudo and to access the docker.sock\nsudo chmod 666 /home/azureuser/.docker/config.json\nsudo chmod 666 /var/run/docker.sock\n\n# Install AZ CLI\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Clone the repository and build it\ncd ~\ngit clone https://github.com/Azure/java-aks-aca-dapr-workshop.git\ncd ~/java-aks-aca-dapr-workshop\ngit checkout feature/e2e-flow\nmvn clean package\n\n# Setup container registry\nVEHICLE_REGISTRATION_SERVICE=\"vehicle-registration-service\"\nFINE_COLLECTION_SERVICE=\"fine-collection-service\"\nTRAFFIC_CONTROL_SERVICE=\"traffic-control-service\"\n# TODO get the registry name and get the auto login\nAZURE_CONTAINER_REGISTRY=\"<ADD_CONTAINER REGISTRY_NAME>\"\nAZURE_CONTAINER_REGISTRY_URL=\"<ADD_CONTAINER REGISTRY_NAME>.azurecr.io\"\nIMAGE_TAG=\"1.0\"\n\n# Login to Azure and AZ ACR\naz login\nsudo az acr login -n $AZURE_CONTAINER_REGISTRY\n\n# Build Vehicle Registration Service Image\ncd VehicleRegistrationService\nmvn spring-boot:build-image -Dspring-boot.build-image.imageName=$AZURE_CONTAINER_REGISTRY_URL/$VEHICLE_REGISTRATION_SERVICE:$IMAGE_TAG\nsudo docker push $AZURE_CONTAINER_REGISTRY_URL/$VEHICLE_REGISTRATION_SERVICE:$IMAGE_TAG\n\n# Build Fine Collection Service Image\ncd ../FineCollectionService\nmvn spring-boot:build-image -Dspring-boot.build-image.imageName=$AZURE_CONTAINER_REGISTRY_URL/$FINE_COLLECTION_SERVICE:$IMAGE_TAG\nsudo docker push $AZURE_CONTAINER_REGISTRY_URL/$FINE_COLLECTION_SERVICE:$IMAGE_TAG\n\n# Build Traffic Control Service Image\ncd ../TrafficControlService\nmvn spring-boot:build-image -Dspring-boot.build-image.imageName=$AZURE_CONTAINER_REGISTRY_URL/$TRAFFIC_CONTROL_SERVICE:$IMAGE_TAG\nsudo docker push $AZURE_CONTAINER_REGISTRY_URL/$TRAFFIC_CONTROL_SERVICE:$IMAGE_TAG\n\n# Build Simulation Image\ncd ../Simulation\nmvn spring-boot:build-image -Dspring-boot.build-image.imageName=$AZURE_CONTAINER_REGISTRY_URL/simulation:$IMAGE_TAG\nsudo docker push $AZURE_CONTAINER_REGISTRY_URL/simulation:$IMAGE_TAG\n", "num_lines": 89}
{"repo_name": "aca-landing-zone-accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script Definition\nlogpath=/var/log/deploymentscriptlog\n\n# Upgrading Linux Distribution\necho \"#############################\" >> $logpath\necho \"Upgrading Linux Distribution\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update >> $logpath\nsudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n# Install Azure CLI\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Install Docker\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n\n# install Terraform CLI\n# https://learn.hashicorp.com/tutorials/terraform/install-cli\necho \"#############################\" >> $logpath\necho \"Installing Terraform\" >> $logpath\necho \"#############################\" >> $logpath\n\nwget -O- https://apt.releases.hashicorp.com/gpg | sudo gpg --dearmor -o /usr/share/keyrings/hashicorp-archive-keyring.gpg\necho \"deb [signed-by=/usr/share/keyrings/hashicorp-archive-keyring.gpg] https://apt.releases.hashicorp.com $(lsb_release -cs) main\" | sudo tee /etc/apt/sources.list.d/hashicorp.list\nsudo apt update && sudo apt install terraform\n\nterraform version", "num_lines": 39}
{"repo_name": "Accord-NET", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\n# Compares software version numbers\n# 10 means EQUAL\n# 11 means GREATER THAN\n# 9 means LESS THAN\ncheck_version() {\n\ttest -z \"$1\" && return 1\n\tlocal ver1=$1\n\twhile test `echo $ver1 | egrep -c [^0123456789.]` -gt 0 ; do\n\t\tchar=`echo $ver1 | sed 's/.*\\([^0123456789.]\\).*/\\1/'`\n\t\tchar_dec=`echo -n \"$char\" | od -b | head -1 | awk {'print $2'}`\n\t\tver1=`echo $ver1 | sed \"s/$char/.$char_dec/g\"`\n\tdone\t\n\ttest -z \"$2\" && return 1\n\tlocal ver2=$2\n\twhile test `echo $ver2 | egrep -c [^0123456789.]` -gt 0 ; do\n\t\tchar=`echo $ver2 | sed 's/.*\\([^0123456789.]\\).*/\\1/'`\n\t\tchar_dec=`echo -n \"$char\" | od -b | head -1 | awk {'print $2'}`\n\t\tver2=`echo $ver2 | sed \"s/$char/.$char_dec/g\"`\n\tdone\t\n\n\tver1=`echo $ver1 | sed 's/\\.\\./.0/g'`\n\tver2=`echo $ver2 | sed 's/\\.\\./.0/g'`\n\n\tdo_version_check \"$ver1\" \"$ver2\"\n}\n\ndo_version_check() {\n\t\n\ttest \"$1\" -eq \"$2\" && return 10\n\n\tver1front=`echo $1 | cut -d \".\" -f -1`\n\tver1back=`echo $1 | cut -d \".\" -f 2-`\n\tver2front=`echo $2 | cut -d \".\" -f -1`\n\tver2back=`echo $2 | cut -d \".\" -f 2-`\n\n\tif test \"$ver1front\" != \"$1\"  || test \"$ver2front\" != \"$2\" ; then\n\t\ttest \"$ver1front\" -gt \"$ver2front\" && return 11\n\t\ttest \"$ver1front\" -lt \"$ver2front\" && return 9\n\n\t\ttest \"$ver1front\" -eq \"$1\" || test -z \"$ver1back\" && ver1back=0\n\t\ttest \"$ver2front\" -eq \"$2\" || test -z \"$ver2back\" && ver2back=0\n\t\tdo_version_check \"$ver1back\" \"$ver2back\"\n\t\treturn $?\n\telse\n\t\ttest \"$1\" -gt \"$2\" && return 11 || return 9\n\tfi\n}\n\nPROJECT=Accord.NET\nFILE=\nCONFIGURE=configure.ac\n\n: ${AUTOCONF=autoconf}\n: ${AUTOHEADER=autoheader}\n: ${AUTOMAKE=automake}\n: ${ACLOCAL=aclocal}\n: ${MONO=mono}\n: ${XBUILD=xbuild}\n\nDIE=0\n\n($AUTOCONF --version) < /dev/null > /dev/null 2>&1 || {\n        echo\n        echo \"You must have autoconf installed to compile $PROJECT.\"\n        echo \"Download the appropriate package for your distribution,\"\n        echo \"or get the source tarball at ftp://ftp.gnu.org/pub/gnu/\"\n\t\techo \n\t\techo \"On apt-get systems, you might want to run 'sudo apt-get install autoconf'\"\n        DIE=1\n}\n\n($AUTOMAKE --version) < /dev/null > /dev/null 2>&1 || {\n        echo\n        echo \"You must have automake installed to compile $PROJECT.\"\n        echo \"Get ftp://sourceware.cygnus.com/pub/automake/automake-1.4.tar.gz\"\n        echo \"(or a newer version if it is available)\"\n\t\techo\n\t\techo \"On apt-get systems, you might want to run 'sudo apt-get install automake'\"\n        DIE=1\n}\n\n($MONO --version) < /dev/null > /dev/null 2>&1 || {\n        echo\n        echo \"You must have mono runtime installed to compile $PROJECT.\"\n\t\techo\n\t\techo \"On apt-get systems, you might want to run 'sudo apt-get install mono-complete'\"\n        DIE=1\n}\n\n($XBUILD /version) < /dev/null > /dev/null 2>&1 || {\n        echo\n        echo \"You must have mono-xbuild installed to compile $PROJECT.\"\n\t\techo\n\t\techo \"On apt-get systems, you might want to run 'sudo apt-get install mono-xbuild'\"\n        DIE=1\n}\n\nif test \"$DIE\" -eq 1; then\n        exit 1\nfi\n\nunset GREP_OPTIONS\n\nxbuild_version=`xbuild /version | grep '^XBuild' | egrep -o '([0-9]+\\.?){2,}'`\ncheck_version \"$xbuild_version\" \"2.4\" 2> /dev/null\nif test $? -eq 9; then\n\techo\n\techo \"A newer version of XBuild is required to build $PROJECT ( >= 2.4 )\"\n\texit 1\nfi\n\nmono_version=`xbuild /version | grep '^Mono' | egrep -o '([0-9]+\\.?){2,}'`\ncheck_version \"$xbuild_version\" \"2.4\" 2> /dev/null\nif test $? -eq 9; then\n\techo\n\techo \"A newer version of Mono is required to run $PROJECT ( >= 2.4 )\"\n\texit 1\nfi\n\n\n#Check directoy \nsrcdir=`dirname $0`\ntest -z \"$srcdir\" && srcdir=.\n\nORIGDIR=`pwd`\ncd $srcdir\nTEST_TYPE=-f\naclocalinclude=\"-I . $ACLOCAL_FLAGS\"\n\n                                                                     \ntest $TEST_TYPE $FILE || {\n        echo \"You must run this script in the top-level $PROJECT directory\"\n        exit 1\n}\n\nif test -z \"$*\"; then\n        echo \"I am going to run ./configure with no arguments - if you wish \"\n        echo \"to pass any to it, please specify them on the $0 command line.\"\nfi\n\necho \"Running $ACLOCAL $aclocalinclude ...\"\n$ACLOCAL $aclocalinclude\n\necho \"Running $AUTOMAKE --gnu $am_opt ...\"\n$AUTOMAKE --add-missing --gnu $am_opt\n\necho \"Running $AUTOCONF ...\"\n$AUTOCONF\n\necho Running $srcdir/configure $conf_flags \"$@\" ...\n$srcdir/configure $conf_flags \"$@\"", "num_lines": 153}
{"repo_name": "ACE_Azure_ML", "repo_creator": "Azure", "programming_language": "Shell", "code": "# You can use this script to export a folder (containing notebooks, or\n# folders of notebooks) from ADB as a DBC archive, so you can then\n# unzip the archive and add the individual notebooks to version\n# control.  Adding the notebooks individually enables text-based\n# version control, which makes it easier to see the actual changes to\n# notebooks.\n\nUSERNAME=wopauli@microsoft.com\n\nREGION=westus\n\nFILE=token.txt\n\nif [ -f $FILE ]; then\n    echo \"Token file $FILE exists.\"\n    token=$(cat $FILE)\nelse\n    echo \"Token file $FILE does not exist.\"\n    exit 1\nfi\n\n\necho \"Using access token: $token\"\n\n# curl -n -o notebooks.dbc https://${REGION}.azuredatabricks.net/api/2.0/workspace/export\\?path=/Users/$USERNAME/notebooks\\&direct_download=true\\&format=DBC -H \"Authorization: Bearer ${token}\"\n\n# Here are some further instructions\n\n# To extract the content of the archive, simply use unzip:\n# > unzip notebooks.dbc\n\n# To create a dbc archive of folders, just create a zip file without compressing python notebooks (-n option)\n# > zip -r -n python notebooks.dbc notebooks\n\n# To import this new archive into databricks, use curl again\n# >\n#curl -n -F path=/Users/${USERNAME}/notebooks -F format=DBC -F content=@notebooks.dbc https://${REGION}.azuredatabricks.net/api/2.0/workspace/import  -H \"Authorization: Bearer ${token}\"\n", "num_lines": 38}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n\n# abort on errors\nset -e\n\nnpm install -g vuepress\n# build\nnpm run docs:build\n\n# navigate into the build output directory\ncd ./gh-pages\n\n# if you are deploying to a custom domain\n# echo 'www.example.com' > CNAME\n\ngit init && \\\ngit config --global user.email @users.noreply.github.com && \\\ngit config --global user.name \"Git Hub Deploy Action\" && \\\ngit add . \ngit commit -m 'deploy'\n\ngit push -f git@github.com:${GH_REPOSITORY}.git master:gh-pages\n\n", "num_lines": 24}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nCERT_FINGERPRINT=$1\nexport BACKEND_HOST=$2\nexport FRONTEND_HOST=$3\nCA_CERT_URL=$4\n\nSOURCE_ROOT=\"https://raw.githubusercontent.com/Azure/acr/main\"\n\ncurl \"$SOURCE_ROOT/docs/custom-domain/deprecated/docker-vm-deploy/setup-certs.sh\" -o  setup-certs.sh\nchmod +x ./setup-certs.sh\n. ./setup-certs.sh $CERT_FINGERPRINT $CA_CERT_URL\n\nexport CONTAINER_CERT_LOCATION=\"/etc/nginx/ssl/cert.crt\"\nexport CONTAINER_PRV_LOCATION=\"/etc/nginx/ssl/private.key\"\n\ncurl \"$SOURCE_ROOT/docs/custom-domain/deprecated/docker-vm-deploy/docker-compose.yml.template\" -o  docker-compose.yml.template\nsudo -E envsubst '$CERT_LOCATION$PRV_LOCATION$CONTAINER_CERT_LOCATION$CONTAINER_PRV_LOCATION' < docker-compose.yml.template > docker-compose.yml\n\nexport CERT_LOCATION=$CONTAINER_CERT_LOCATION\nexport PRV_LOCATION=$CONTAINER_PRV_LOCATION\n\ncurl \"$SOURCE_ROOT/docs/custom-domain/deprecated/docker-vm-deploy/nginx.conf.template\" -o  nginx.conf.template\nsudo -E envsubst '$FRONTEND_HOST$BACKEND_HOST$CERT_LOCATION$PRV_LOCATION' < nginx.conf.template > nginx.conf\n\n## Docker installation extension installs docker in the background\n## So we cannot make assumption about its completion time\nuntil docker-compose up\ndo\n    sleep 10\ndone\n", "num_lines": 33}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCERT_FINGERPRINT=$1\nCA_CERT_URL=$2\n\nCERT_FINGERPRINT=`echo $CERT_FINGERPRINT | tr [a-z] [A-Z]`\n\nif [ ! -z \"$CA_CERT_URL\" ]; then\n\n    curl $CA_CERT_URL -o ca_cert.crt\n\n    set +e\n    certDetails=`openssl x509 -in ca_cert.crt -text -noout`\n    set -e\n\n    # if it is not PEM, it must be DER\n    if [ -z \"$certDetails\" ]; then\n        openssl x509 -in ca_cert.crt -inform der -outform pem -out ca_cert_pem.crt\n    else\n        mv ca_cert.crt ca_cert_pem.crt\n    fi\n\n    sudo cat \"/var/lib/waagent/$CERT_FINGERPRINT.crt\" ca_cert_pem.crt > cert.crt\n    export CERT_LOCATION=`pwd`/cert.crt\n\nelse\n    export CERT_LOCATION=/var/lib/waagent/${CERT_FINGERPRINT}.crt\nfi\n\nexport PRV_LOCATION=/var/lib/waagent/${CERT_FINGERPRINT}.prv\n", "num_lines": 31}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#usage: check-expansion.sh acr-name repo tag\n#usage: eg: check-expansion.sh demo42 /demo42/hello-world 2.1\n#usage: eg: check-expansion.sh demo42 /demo42/hello-world 2.1 --debug\n# Assumes ACR_USER and ACR_PWD are set to valid ACRPULL role\n# Retrieve the ACR_PWD with the following command, if the Admin account is enabled\n# ACR_PWD=\"$(az acr credential show -n demo42t --query passwords[0].value -o tsv)\"\n# NOTE: Repo scoped tokens will be coming online in November\nACR_NAME=$1\nACR_REPO=$2\nACR_TAG=$3\nDEBUG=$4\n\n# Troubleshooting \nif [[ $DEBUG = '--debug' ]]; then\n    echo \"Parameter Validation:\"\n    echo \"  ACR_USER: ${ACR_USER}\"\n    echo \"  ACR_PWD : ${ACR_PWD}\"\n    echo \"  ACR_NAME: ${ACR_NAME}\"\n    echo \"  ACR_REPO: ${ACR_REPO}\"\n    echo \"  ACR_TAG : ${ACR_TAG}\"\nfi\n\necho \"Getting Access Token\"\n\nACR_ACCESS_TOKEN=$(curl -s -u ${ACR_USER}:${ACR_PWD} \"https://${ACR_NAME}.azurecr.io/oauth2/token?service=${ACR_NAME}.azurecr.io&scope=repository:${ACR_REPO}:pull\" | sed -e 's/[{}]/''/g' | awk -v RS=',\"' -F: '/access_token/ {print $2}' | sed 's/^.//;s/.$//')\n\nif [[ $ACR_ACCESS_TOKEN == '' ]]; then\n    echo \"Could not get access token, make sure credentials are accurate and have pull access\"\n    exit 1\nfi\n\nif [[ $DEBUG == '--debug' ]]; then\n    echo \"  ACR_ACCESS_TOKEN: ${ACR_ACCESS_TOKEN}\"\nfi\n\necho \"Finding Digest for $ACR_REPO:$ACR_TAG https://$ACR_NAME.azurecr.io/v2/$ACR_REPO/manifests/$ACR_TAG\"\n\nACR_DIGEST=$(curl -s -L -I \\\n  -H \"Accept: application/vnd.docker.distribution.manifest.v2+json\" \\\n  -H \"Authorization: Bearer ${ACR_ACCESS_TOKEN}\" \\\n  https://$ACR_NAME.azurecr.io/v2/$ACR_REPO/manifests/$ACR_TAG | grep ^Docker-Content-Digest | awk '{print $2}' | head -c 71)\n\nif [[ $DEBUG == '--debug' ]]; then\n    echo \"  ACR_DIGEST: ${ACR_DIGEST}\"\nfi\n\nif [[ $ACR_DIGEST == '' ]]; then\n    echo \"Could not return the image digest. Confirm the identity has access to the repo, and the image exists.\"\n    exit 1\nfi\n\necho \"Checking https://$ACR_NAME.azurecr.io/mount/v1/$ACR_REPO/_manifests/$ACR_DIGEST\"\nwhile true\ndo\n    STATUS=$(curl -s -o /dev/null -w \"%{http_code}\" \\\n    -H \"Authorization: Bearer ${ACR_ACCESS_TOKEN}\" \\\n    \"https://$ACR_NAME.azurecr.io/mount/v1/$ACR_REPO/_manifests/$ACR_DIGEST\")\n\n    echo \"Status: ${STATUS}\"\n    if [ $STATUS -eq 200 ]; then\n        echo \"Teleport: layers ready\"\n        break\n    elif [ $STATUS -eq 409 ]; then\n        echo \"Teleport: expanding layers\"\n    elif  [ $STATUS -eq 404 ]; then\n        echo \"Teleport: ${ACR_NAME}-${ACR_REPO}:${ACR_TAG} not enabled\"\n        break\n    else\n        echo \"Unknown status $STATUS\"\n    fi\n    sleep 2\ndone\n", "num_lines": 74}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#usage: edit-teleport-attribute.sh acr-name repo enable\n#usage: eg: edit-teleport-attribute.sh demo42 /demo42/hello-world 2.1 disable\n#usage: eg: edit-teleport-attribute.sh demo42 /demo42/hello-world 2.1 enable --debug\n# Assumes ACR_USER and ACR_PWD are set to valid ACRPULL role\n# Retrieve the ACR_PWD with the following command, if the Admin account is enabled\n# ACR_PWD=\"$(az acr credential show -n demo42t --query passwords[0].value -o tsv)\"\n# NOTE: Repo scoped tokens will be coming online in November\nACR_NAME=$1\nACR_REPO=$2\nSTATE=$3\nDEBUG=$4\n\n# Troubleshooting \nif [[ $DEBUG = '--debug' ]]; then\n    echo \"Parameter Validation:\"\n    echo \"  ACR_USER: ${ACR_USER}\"\n    echo \"  ACR_PWD : ${ACR_PWD}\"\n    echo \"  ACR_NAME: ${ACR_NAME}\"\n    echo \"  ACR_REPO: ${ACR_REPO}\"\nfi\n\necho \"Getting Access Token\"\n\nACR_ACCESS_TOKEN=$(curl -s -u ${ACR_USER}:${ACR_PWD} \"https://${ACR_NAME}.azurecr.io/oauth2/token?service=${ACR_NAME}.azurecr.io&scope=repository:${ACR_REPO}:pull,push\" | sed -e 's/[{}]/''/g' | awk -v RS=',\"' -F: '/access_token/ {print $2}' | sed 's/^.//;s/.$//')\n\nif [[ $ACR_ACCESS_TOKEN == '' ]]; then\n    echo \"Could not get access token, make sure credentials are accurate and have pull access\"\n    exit 1\nfi\n\nif [[ $DEBUG == '--debug' ]]; then\n    echo \"  ACR_ACCESS_TOKEN: ${ACR_ACCESS_TOKEN}\"\nfi\n\nSET_STATE=\"\"\n\nif [[ $STATE == 'enable' ]]; then\n   SET_STATE=\"{\\\"teleportEnabled\\\": true }\"\nfi\n\nif [[ $STATE == 'disable' ]]; then\n    SET_STATE=\"{\\\"teleportEnabled\\\": false }\"\nfi\n\nif [[ $DEBUG == '--debug' ]]; then\n    echo \"  SET_STATE: ${SET_STATE}\"\nfi\n\necho \"Sendng Patch Request for $ACR_REPO\"\n\nRESULT=$(curl -s -S \\\n  -H \"Content-Type: application/json\" \\\n  -H \"Authorization: Bearer ${ACR_ACCESS_TOKEN}\" \\\n  --request PATCH \\\n  --data \"${SET_STATE}\" \\\n  https://$ACR_NAME.azurecr.io/acr/v1/$ACR_REPO)\n\necho \"  RESULT: ${RESULT}\"\n\n\n", "num_lines": 62}
{"repo_name": "acr", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Prerequisites:\n# azure cli (logged in)\n# jq \n# usage: find-teleport-enabled-repositories.sh acr-name\n\nACR_NAME=$1\n\nenabled_repos=()\n\nIFS=$'\\n' # Each iteration of the for loop should read until we find an end-of-line\nfor row in $(az acr repository list --name ${ACR_NAME} |  jq '.[]' | jq @sh)\ndo\n    # Run the row through the shell interpreter to remove enclosing double-quotes\n    stripped=$(echo $row | xargs echo)\n    stripped=$(echo $stripped | xargs echo)  \n    \n    is_teleport_enabled=$(az acr repository show --name \"${ACR_NAME}\" --repository \"${stripped}\"  --query \"changeableAttributes.teleportEnabled\")\n\n    if [[ \"$is_teleport_enabled\" = 'true' ]]; then\n        echo \"$stripped -> Enabled\"\n        enabled_repos+=(\"$stripped\")\n    else \n        echo \"$stripped -> Disabled\"\n    fi\n\ndone\n\nunset IFS\n\necho \"\"\necho \"Summary:\"\necho \"Enabled Repositories:\"\necho \"\"\n\nfor value in \"${enabled_repos[@]}\"\ndo\n     echo $value\ndone", "num_lines": 39}
{"repo_name": "acr-build", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nINPUT_DOCKERFILE=${INPUT_DOCKERFILE:-Dockerfile}\nINPUT_TAG=${INPUT_TAG:-${GITHUB_SHA::8}}\nINPUT_BRANCH=${INPUT_BRANCH:-master}\nIMAGE_PART=\"\"\nif [ -n \"$INPUT_BUILD_ARGS\" ]; then\n        BUILD_ARGS=`echo -n ${INPUT_BUILD_ARGS:-''} |jq -j '.[] | keys[] as $k | values[] as $v |  \"--build-arg \\($k)=\\\"\\($v)\\\" \"'`\nfi\n\nif [ \"$INPUT_IMAGE\" != \"\" ]; then\n        IMAGE_PART=\"/${INPUT_IMAGE}\"\nfi\n\nif [ -n \"$INPUT_GIT_ACCESS_TOKEN\" ]; then\n        GIT_ACCESS_TOKEN_FLAG=\"${INPUT_GIT_ACCESS_TOKEN}@\"\nfi\n\necho \"Building Docker image ${INPUT_REPOSITORY}${IMAGE_PART}:${INPUT_TAG} from ${GITHUB_REPOSITORY} on ${INPUT_BRANCH} and using context ${INPUT_FOLDER} ; and pushing it to ${INPUT_REGISTRY} Azure Container Registry\"\n\necho \"Logging into azure..\"\naz login --service-principal -u ${INPUT_SERVICE_PRINCIPAL} -p ${INPUT_SERVICE_PRINCIPAL_PASSWORD} --tenant ${INPUT_TENANT}\n\necho \"Sending build job to ACR..\"\naz acr build -r ${INPUT_REGISTRY} ${BUILD_ARGS} -f ${INPUT_DOCKERFILE} -t ${INPUT_REPOSITORY}${IMAGE_PART}:${INPUT_TAG} https://${GIT_ACCESS_TOKEN_FLAG}github.com/${GITHUB_REPOSITORY}.git#${INPUT_BRANCH}:${INPUT_FOLDER}\n", "num_lines": 27}
{"repo_name": "acr-builder", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\ncd s2/cmd/_s2sx/ || exit 1\ngo generate .\n", "num_lines": 5}
{"repo_name": "acr-builder", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "acr-builder", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "acr-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "acr-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nbuildImageName=\"acr-cred-helper-build-img\"\nbuildContainerName=\"acr-cred-helper-build\"\n\nif [[ \"$(docker images -q ${buildImageName} 2> /dev/null)\" == \"\" ]]; then\n    docker rmi -f ${buildImageName}\nfi\n\nset -e\n./build/build-clean.sh bin artifacts\n\ndocker build -t ${buildImageName} .\ndocker run --name ${buildContainerName} ${buildImageName}\ndocker cp ${buildContainerName}:/build-root/artifacts artifacts\n\ndocker rm ${buildContainerName}\ndocker rmi ${buildImageName}\n", "num_lines": 18}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nbindir=$1\nartifactsdir=$2\n\nrm -rf $bindir\nrm -rf $artifactsdir\n", "num_lines": 8}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nbindir=$1\n\nif [[ -z \"${bindir}\" ]]; then\n    bindir=\"$PWD/bin\"\nfi\n\nsourcedir=\"./src/config-edit\"\nif [[ ! -d \"$sourcedir\" ]]; then\n    echo \"Please run the script from project root...\"\n\texit -1\nfi\n\nexport CGO_ENABLED=0\nexport GOARCH=amd64\nexport GOPATH=$PWD\necho \"Go path = $GOPATH\"\nfor go_os in \"linux\" \"windows\" \"darwin\"\ndo\n    if [[ \"$go_os\" == \"windows\" ]]; then\n        exe_extension=\".exe\"\n    else\n        exe_extension=\"\"\n    fi\n    outputFile=\"${bindir}/${go_os}/${GOARCH}/config-edit${exe_extension}\"\n    echo \"Building ${outputFile}...\"\n    export GOOS=$go_os\n    go build -o $outputFile $sourcedir\n    buildExitCode=$?\n\n    if [[ $buildExitCode == 0 ]]; then\n        echo \"Built ${outputFile} successfully\"\n    else\n        exit $buildExitCode\n    fi\ndone\n", "num_lines": 38}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nbindir=$1\n\nif [[ -z \"${bindir}\" ]]; then\n    bindir=\"$PWD/bin\"\nfi\n\nsourcedir=\"./src/docker-credential-acr\"\nif [[ ! -d \"$sourcedir\" ]]; then\n    echo \"Please run the script from project root...\"\n\texit -1\nfi\n\nif [[ ! -z \"${2}\" ]]; then\n\tbuildtags=\"--tags '${2}'\"\nfi\n\nif [[ ! -z \"${3}\" ]]; then\n    outputSuffix=\"-${3}\"\nfi\n\nexport BUILDVERSION=acr-docker-credential-helper`date -u +.%Y%m%d.%H%M%S`\nexport CGO_ENABLED=0\nexport GOARCH=amd64\nexport GOPATH=$PWD\nfor go_os in \"linux\" \"windows\" \"darwin\"\ndo\n    export GOOS=$go_os\n    if [[ \"$GOOS\" == \"windows\" ]]; then\n        exe_extension=\".exe\"\n    else\n        exe_extension=\"\"\n    fi\n    outputFile=\"${bindir}/${GOOS}/${GOARCH}/docker-credential-acr-${GOOS}${outputSuffix}${exe_extension}\"\n    echo \"Building ${outputFile} ${buildtags}...\"\n    go build -ldflags \"-X main.userAgentVersion=$GOOS-$GOARCH-$BUILDVERSION\" -o $outputFile ${buildtags} $sourcedir\n    buildExitCode=$?\n\n    if [[ $buildExitCode == 0 ]]; then\n        echo \"Built ${outputFile} successfully\"\n    else\n        exit $buildExitCode\n    fi\ndone\n", "num_lines": 46}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nbinroot=$1\nartifactsdir=$2\n\nif [[ -z \"${TRAVIS_TAG}\" ]]; then\n    echo \"TRAVIS_TAG is missing... Release should be skipped...\"\n    TRAVIS_TAG=\"notags\"\nfi\n\nif [[ ! -d $binroot ]]; then\n    echo \"Please run the script from project root...\"\n\texit -1\nfi\n\nif [[ ! -d $artifactsdir ]]; then\n    mkdir $artifactsdir\nfi\n\nfor osname in $(ls $binroot) ; do\n    for arch in $(ls \"$binroot/$osname\") ; do\n        bindir=\"$binroot/$osname/$arch\"\n        if [[ -d $bindir ]]; then\n            echo \"Packaging for ${osname}-${arch}\"\n            pkgName=\"docker-credential-acr-${osname}-${arch}\"\n            pushd $bindir\n            if [[ \"$osname\" == \"windows\" ]]; then\n                pkgFile=\"${pkgName}.zip\"\n                zip ${pkgFile} *\n            else\n                pkgFile=\"${pkgName}.tar.gz\"\n                tar czf ${pkgFile} *\n            fi\n            popd\n            mv ${bindir}/$pkgFile ${artifactsdir}\n            echo \"Packaged in ${pkgFile}\"\n        fi\n    done\ndone\n", "num_lines": 40}
{"repo_name": "acr-docker-credential-helper", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nbaseurl=\"https://aadacr.blob.core.windows.net/acr-docker-credential-helper\"\nos=`uname | tr '[:upper:]' '[:lower:]'`\n\nif [[ \"$os\" != \"linux\" && \"$os\" != \"darwin\" ]]; then\n    echo \"Operation System $os is not supported currently.\"\n    exit -1\nfi\n\narchstr=`uname -m`\ncase \"$archstr\" in\n    x86) arch=\"x86\" ;;\n    i?86) arch=\"x86\" ;;\n    amd64) arch=\"amd64\" ;;\n    x86_64) arch=\"amd64\" ;;\n    *)\n        echo \"Unknown arch $archstr.\"\n        exit -1\nesac\n\nif [[ \"$arch\" -ne \"amd64\" ]]; then\n    echo \"Arch $arch is currently not supported.\"\n    exit -1\nfi\n\nwhile getopts \":b:s:\" opt; do\n    case $opt in\n        b) baseurl=\"$OPTARG\"\n        ;;\n        s) skipCleanup=\"true\"\n        ;;\n        \\?) echo \"Invalid option -$OPTARG\" >&2\n        ;;\n    esac\ndone\n\nif [[ $HOME == \"/root\" ]]; then\n   echo \"WARNING: Home directory is /root and not pointing to a specific user. This script might not give you the result you want.\"\n   echo \"You should run \\\"sudo -i \\${installscript}\\\" instead.\"\n   read -p \"Exit? (Y/n)\" yn\n   case $yn in\n     [Yy]*) exit 1 ;;\n     *) echo \"Continuing...\";;\n   esac\nfi\n\ntempdir=\"deleteme\"\narchiveFile=\"docker-credential-acr-${os}-${arch}.tar.gz\"\nrm -f ${archiveFile}\nrm -rf ${tempdir}\n\ncurl -o ${archiveFile} ${baseurl}/${archiveFile}\nmkdir ${tempdir}\ntar -xf ${archiveFile} -C ${tempdir}\n\ndefaultInstallLocation=\"/usr/local/bin\"\n## This is an attempt to check whether we are running the script interactively\n## It can't detect when user pipes the script into bash, in that case default would still be used\ncase $- in\n*i*)\n    echo \"Non-interactive shell detected. ACR Credentials Helper will be installed in default location: ${defaultInstallLocation}\"\n;;\n*)\n    echo \"Please enter desired install location or press enter to install in ${defaultInstallLocation}. Note that you will need to add the install location to PATH.\"\n    read installLocation\nesac\n\n## If user choose to install into default location, we will elevate the permission while copying the file\nif [[ -z \"${installLocation}\" ]]; then\n    installLocation=$defaultInstallLocation\n    echo \"Installing in default location ${installLocation}...\"\n    if [[ $EUID -ne 0 ]]; then\n        sudoCmd=`which sudo`\n        if [[ -z \"$sudoCmd\" ]]; then\n            echo \"Unable to elevate permissions.\"\n            exit 1\n        fi\n        sudoOption=\"$sudoCmd \"\n    fi\nelse\n    if [[ ! -d \"${installLocation}\" ]]; then\n        mkdir -p ${installLocation}\n    fi\nfi\n\n${sudoOption}cp ${tempdir}/docker-credential-acr-${os} ${installLocation}\n${sudoOption}chmod +x ${installLocation}/docker-credential-acr-${os}\n\nconfigdir=\"$HOME/.docker\"\nconfigFile=\"${configdir}/config.json\"\nscriptRunner=`ls -ld $HOME | awk '{print $3}'`\n\nif [[ ! -d \"${configdir}\" ]]; then\n    mkdir ${configdir}\nfi\n\nif [[ ! -f \"${configFile}\" ]]; then\n    dummyConfigCreated=\"true\"\n    echo \"{\\\"auths\\\":{}}\" >> ${configFile}\nfi\n\n./${tempdir}/config-edit --helper acr-${os} --config-file ${configFile} --force\n\nif [[ ! -z \"${dummyConfigCreated}\" ]]; then\n    rm -f \"${configFile}.bak\"\nfi\n\nif [[ -z \"$skipCleanup\" ]]; then\n    rm -f ${archiveFile}\n    rm -rf ${tempdir}\nfi\n", "num_lines": 114}
{"repo_name": "acr-task-commands", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -Eeuo pipefail\n\n# first arg is `-f` or `--some-option`\n# or there are no args\nif [ \"$#\" -eq 0 ] || [ \"${1#-}\" != \"$1\" ]; then\n\t# docker run bash -c 'echo hi'\n\texec bash \"$@\"\nfi\n\nexec \"$@\"", "num_lines": 11}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker build -t biglittlechallenge/trials-base-arm -f Dockerfile-trials-base-arm .\n\ndocker build -t biglittlechallenge/trials-engine-arm -f Dockerfile-trials-engine-arm .\n\ndocker build -t biglittlechallenge/trials-engine-dashboard-arm -f Dockerfile-trials-engine-dashboard-arm .\n\ndocker build -t biglittlechallenge/trials-ai-arm -f Dockerfile-trials-ai-arm .\n \n", "num_lines": 9}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker build -t biglittlechallenge/trials-base -f Dockerfile-trials-base .\n\ndocker build -t biglittlechallenge/trials-engine -f Dockerfile-trials-engine .\n\ndocker build -t biglittlechallenge/trials-engine-dashboard -f Dockerfile-trials-engine-dashboard .\n\ndocker build -t biglittlechallenge/trials-ai -f Dockerfile-trials-ai .\n", "num_lines": 8}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker push biglittlechallenge/trials-base\n\ndocker push biglittlechallenge/trials-engine\n\ndocker push biglittlechallenge/trials-engine-dashboard\n\ndocker push biglittlechallenge/trials-ai\n", "num_lines": 8}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Creates a swarm \n\nMASTER_IP=192.168.42.1\n\necho \"Tear down old Swarm (if it exists)\"\nsshpass -p 'raspberry' ssh pi@piswarm-agent1.local docker swarm leave\nsshpass -p 'raspberry' ssh pi@piswarm-agent2.local docker swarm leave\nsshpass -p 'raspberry' ssh pi@piswarm-agent3.local docker swarm leave\ndocker swarm leave --force\n\necho\necho \"Configure Leader\"\ndocker swarm init --advertise-addr $MASTER_IP\nJOIN_TOKEN=$(docker swarm join-token worker -q)\n\necho\necho \"Configure Agent 1\"\nsshpass -p 'raspberry' ssh pi@piswarm-agent1.local docker swarm join --token $JOIN_TOKEN $MASTER_IP:2377\n\necho\necho \"Configure Agent 2\"\nsshpass -p 'raspberry' ssh pi@piswarm-agent2.local docker swarm join --token $JOIN_TOKEN $MASTER_IP:2377\n\necho\necho \"Configure Agent 3\"\nsshpass -p 'raspberry' ssh pi@piswarm-agent3.local docker swarm join --token $JOIN_TOKEN $MASTER_IP:2377\n\necho\necho \"Status of Swarm Nodes\"\ndocker node ls\n", "num_lines": 31}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker push biglittlechallenge/trials-base-arm\n\ndocker push biglittlechallenge/trials-engine-arm\n\ndocker push biglittlechallenge/trials-engine-dashboard-arm\n\ndocker push biglittlechallenge/trials-ai-arm\n", "num_lines": 8}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo Creating Network\ndocker network create --driver overlay trials\nsleep 5\n\necho\necho Creating engine service\ndocker service create --replicas=1 --hostname=engine --network=trials --publish 8080:8080 --name engine --env MIN_NUMBER_OF_PLAYERS=5 biglittlechallenge/trials-engine-arm\nsleep 5 # ensure that DNS updates have completed before we start other services\n\necho\necho Creating engine-dashboard\ndocker service create --replicas=1 --network=trials --publish 8181:80 --name engine-dashboard biglittlechallenge/trials-engine-dashboard-arm\n\necho\necho Creating aiplayer service\ndocker service create --name aiplayer --replicas=2 --network=trials --publish 8888 biglittlechallenge/trials-ai-arm\n\necho\ndocker service ls\n\necho \"use 'docker service scale aiplayer=5' to add more players\"\n", "num_lines": 22}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker service rm engine\n\ndocker service rm engine-dashboard\n\ndocker service rm aiplayer\n\ndocker network rm trials\n\n", "num_lines": 9}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker service update biglittlechallenge/trials-engine-arm\n\ndocker service update biglittlechallenge/trials-engine-dashboard-arm\n\ndocker service update create --name aiplayer --replicas=2 --network=trials --publish 8888 biglittlechallenge/trials-ai-arm\n\nwatch docker service ls\n", "num_lines": 8}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script builds a standalone SimDem container with one of the\n# demo's installed.\n#\n# Usage:\n#\n# build_container NAME [SCRIPTS_DIR] [FLAVOR] \n#\n# NAME is the Name of the container to be created.\n#\n# SCRIPTS_DIR defines the scripts directory to be copied into the\n# container. \n#\n# FLAVOR, if present, tells the script which container to build. Takes\n# the value `novnc` or `cli`. If missing both flavors will be built\n\nif [ -z \"$1\" ]; then\n    # FIXME: create a usage description\n    echo \"You must provide a name for the image as the first parameter\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]; then\n    # FIXME: create a usage description\n    echo \"You must provide the name of a directory that contains the scripts to include in the container\"\n    exit 1\nfi\n\nREPOSITORY=rgardler\nNAME_PREFIX=${1}\nSCRIPTS_DIR=${2}\nFLAVOR=${3:}\n\nbuild_container() {\n    IMAGE_NAME=${NAME_PREFIX}_$1\n    docker build -t $IMAGE_NAME --build-arg SCRIPTS_DIR=$2 -f Dockerfile_$1 .\n    \n    if [ $? -eq 0 ]; then\n\techo \"Built $IMAGE_NAME containing scripts in $2\"\n    else\n\techo \"Failed to build $IMAGE_NAME containing scripts in $2\"\n\treturn 0\n    fi\n}\n\nif [[ $FLAVOR == \"novnc\" ]]; then\n    echo \"FIXME: novnc does not work yet (fails authentication)\"\n    build_container novnc $SCRIPTS_DIR\nelif [[ $FLAVOR == \"cli\" ]]; then\n    build_container cli $SCRIPTS_DIR\nelse\n    build_container cli $SCRIPTS_DIR\n    if [ $? eq 1 ]; then\n\texit 1\n    fi\n    build_container novnc $SCRIPTS_DIR\nfi\n\nexit $?\n", "num_lines": 61}
{"repo_name": "acs-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Runs either a command line or headless VNC Docker container with\n# Simdem installed.\n#\n# The container will be called `acs_demo_FLAVOR`\n#\n# Usage: run.sh [FLAVOR] [SCRIPT_DIR] [MODE]\n#\n# FLAVOR is an optional parameter to define which container to run,\n# either the `novnc` or the `cli` versions. If not specified the\n# `novnc` version is used\n#\n# SCRIPT_DIR is an optional parameter to define a directory containing\n# SimDem scripts that will be mounted into the final container. Default\n# value is `./demo_scripts`.\n#\n# MODE is an optional parameter that is only used by the CLI\n# container, the novnc container will ignore it. MODE defines the mode\n# of execution. It can take the values 'tutorial' (default, run with\n# full instructional text), 'demo' (run with no instructional text and\n# simulate typed commnds', 'test' (run in auto mode and test results\n# against expected results)\n#\n# Connect with a browser at http://YOUR_DOCKER_HOST:8080/?password=vncpassword\n#\n# Based on https://github.com/ConSol/docker-headless-vnc-container\n\n\n# Configuration options:\n# You can configure the following variables to change behaviour of\n# the container.\n#\n# VNC config\n# ==========\nVNC_COL_DEPTH='24'\nVNC_RESOLUTION='1024x768'\nVNC_PW='vncpassword'\n\nVERSION=0.8.1-dev # The version of SimDem we have tested against.\nFLAVOR=${1:-novnc}\nSCRIPTS_DIR=${2:-`pwd`/demo_scripts}\nMODE=${3:-tutorial}\nREPOSITORY=rgardler\nCONTAINER_NAME=simdem_$FLAVOR\nSCRIPTS_VOLUME=${CONTAINER_NAME}_scripts\nAZURE_VOLUME=azure_data\nSSH_VOLUME=ssh_data\n\nif [[ $FLAVOR == \"novnc\" ]]; then\n    HOME=\"/headless\"\nelse\n    HOME=\"/home/simdem\"\nfi\n\necho Runing $REPOSITORY/$CONTAINER_NAME:$VERSION\n\necho Stopping and removing pre-existing containers\ndocker stop $CONTAINER_NAME\ndocker rm $CONTAINER_NAME\ndocker stop $SCRIPTS_VOLUME\ndocker rm $SCRIPTS_VOLUME\n\necho Creating scripts data container named $SCRIPTS_VOLUME containing the scripts in $SCRIPTS_DIR\ndocker create -v $HOME/demo_scripts --name $SCRIPTS_VOLUME ubuntu /bin/true\ndocker cp $SCRIPTS_DIR/. $SCRIPTS_VOLUME:$HOME/demo_scripts/\n\necho starting the $CONTAINER_NAME container in mode $MODE\n\nif [[ $MODE == \"tutorial\" ]]; then\n    COMMAND=\"run\"\nelif [[ $MODE == \"demo\" ]]; then\n    COMMAND=\"run --style simulate\"\nelif [[ $MODE == \"test\" ]]; then\n    COMMAND=\"test\"\nfi\n\nif [[ $FLAVOR == \"novnc\" ]]; then\n   docker run -d -p 5901:5901 -p 8080:6901 --name $CONTAINER_NAME \\\n       --volume $AZURE_VOLUME:$HOME/.azure \\\n       --volume $SSH_VOLUME:$HOME/.ssh \\\n       --volumes-from $SCRIPTS_VOLUME \\\n       -e VNC_COL_DEPTH=$VNC_COL_DEPTH \\\n       -e VNC_RESOLUTION=$VNC_RESOLUTION \\\n       -e VNC_PW=$VNC_PW \\\n       $REPOSITORY/$CONTAINER_NAME:$VERSION\nelse\n    docker run -it \\\n       --volume $AZURE_VOLUME:$HOME/.azure \\\n       --volume $SSH_VOLUME:$HOME/.ssh \\\n       --volumes-from $SCRIPTS_VOLUME \\\n       --name $CONTAINER_NAME \\\n       $REPOSITORY/$CONTAINER_NAME:$VERSION \\\n       $COMMAND\nfi\n", "num_lines": 96}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# some tests set NEW_AGENT_NODE_COUNT in .env files\nENV_FILE=\"${CLUSTER_DEFINITION}.env\"\nif [ -e \"${ENV_FILE}\" ]; then\n  source \"${ENV_FILE}\"\nfi\n\n[[ ! -z \"${NEW_AGENT_NODE_COUNT:-}\" ]] || (echo \"Must specify NEW_AGENT_NODE_COUNT\" && exit 1)\n\nOUTPUT=\"_output/${INSTANCE_NAME}\"\n\n# allow nodes to run for a while before scaling\nsleep 180\n\n./bin/acs-engine scale \\\n  --subscription-id ${SUBSCRIPTION_ID} \\\n  --deployment-dir ${OUTPUT} \\\n  --location ${LOCATION} \\\n  --resource-group ${RESOURCE_GROUP} \\\n  --master-FQDN \"${INSTANCE_NAME}.${LOCATION}.cloudapp.azure.com\" \\\n  --node-pool \"agentpool1\" \\\n  --new-node-count ${NEW_AGENT_NODE_COUNT} \\\n  --auth-method client_secret \\\n  --client-id ${SERVICE_PRINCIPAL_CLIENT_ID} \\\n  --client-secret ${SERVICE_PRINCIPAL_CLIENT_SECRET}\n", "num_lines": 29}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# some tests set EXPECTED_ORCHESTRATOR_VERSION in .env files\nENV_FILE=\"${CLUSTER_DEFINITION}.env\"\nif [ -e \"${ENV_FILE}\" ]; then\n  source \"${ENV_FILE}\"\nfi\n\n[[ ! -z \"${EXPECTED_ORCHESTRATOR_VERSION:-}\" ]] || (echo \"Must specify EXPECTED_ORCHESTRATOR_VERSION\" && exit 1)\n\nOUTPUT=\"_output/${INSTANCE_NAME}\"\n\n./bin/acs-engine upgrade \\\n  --subscription-id ${SUBSCRIPTION_ID} \\\n  --deployment-dir ${OUTPUT} \\\n  --location ${LOCATION} \\\n  --resource-group ${RESOURCE_GROUP} \\\n  --upgrade-version ${EXPECTED_ORCHESTRATOR_VERSION} \\\n  --auth-method client_secret \\\n  --client-id ${SERVICE_PRINCIPAL_CLIENT_ID} \\\n  --client-secret ${SERVICE_PRINCIPAL_CLIENT_SECRET}\n", "num_lines": 24}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\naz network vnet create -g ${RESOURCE_GROUP} -n DualCustomVNET --address-prefixes 10.100.0.0/24 10.200.0.0/24 --subnet-name DualMasterSubnet --subnet-prefix 10.100.0.0/24\naz network vnet subnet create --name DualAgentSubnet --address-prefix 10.200.0.0/24 -g ${RESOURCE_GROUP} --vnet-name DualCustomVNET\n\ntempfile=\"$(mktemp)\"\ntrap \"rm -rf \\\"${tempfile}\\\"\" EXIT\n\njq \".properties.masterProfile.vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/DualCustomVNET/subnets/DualMasterSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n\nindx=0\nfor poolname in `jq -r '.properties.agentPoolProfiles[].name' \"${CLUSTER_DEFINITION}\"`; do\n  jq \".properties.agentPoolProfiles[$indx].vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/DualCustomVNET/subnets/DualAgentSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n  indx=$((indx+1))\ndone\n", "num_lines": 16}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\naz network vnet create -g ${RESOURCE_GROUP} -n KubernetesCustomVNET --address-prefixes 10.239.0.0/16 --subnet-name KubernetesSubnet --subnet-prefix 10.239.0.0/16\n\ntempfile=\"$(mktemp)\"\ntrap \"rm -rf \\\"${tempfile}\\\"\" EXIT\n\njq \".properties.masterProfile.vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/KubernetesCustomVNET/subnets/KubernetesSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n\nindx=0\nfor poolname in `jq -r '.properties.agentPoolProfiles[].name' \"${CLUSTER_DEFINITION}\"`; do\n  jq \".properties.agentPoolProfiles[$indx].vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/KubernetesCustomVNET/subnets/KubernetesSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n  indx=$((indx+1))\ndone\n", "num_lines": 15}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nrt=$(az network route-table list -g ${RESOURCE_GROUP} | jq -r '.[].id')\n\naz network vnet subnet update -n KubernetesSubnet -g ${RESOURCE_GROUP} --vnet-name KubernetesCustomVNET --route-table $rt\n", "num_lines": 6}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\naz network vnet create -g ${RESOURCE_GROUP} -n KubernetesCustomVNET --address-prefixes 10.239.0.0/16 10.244.0.0/16 --subnet-name KubernetesSubnet --subnet-prefix 10.239.0.0/16\n\ntempfile=\"$(mktemp)\"\ntrap \"rm -rf \\\"${tempfile}\\\"\" EXIT\n\njq \".properties.masterProfile.vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/KubernetesCustomVNET/subnets/KubernetesSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n\nindx=0\nfor poolname in `jq -r '.properties.agentPoolProfiles[].name' \"${CLUSTER_DEFINITION}\"`; do\n  jq \".properties.agentPoolProfiles[$indx].vnetSubnetId = \\\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/KubernetesCustomVNET/subnets/KubernetesSubnet\\\"\" ${CLUSTER_DEFINITION} > $tempfile && mv $tempfile ${CLUSTER_DEFINITION}\n  indx=$((indx+1))\ndone\n", "num_lines": 15}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Add support for registering host on dns server. Must allow non-secure updates\n\nset -e\n\nDOMAINNAME=$1\n\necho $(date) \" - Starting Script\"\n\ncat > /etc/network/if-up.d/register-dns <<EOFDHCP\n#!/bin/sh\n\n# only execute on the primary nic\nif [ \"\\${IFACE}\" = \"eth0\" ]\nthen\n    ip=\\$(ip address show eth0 | awk '/inet / {print \\$2}' | cut -d/ -f1)\n    host=\\$(hostname -s)\n    nsupdatecmds=/var/tmp/nsupdatecmds\n    echo \"update delete \\${host}.${DOMAINNAME} a\" > \\$nsupdatecmds\n    echo \"update add \\${host}.${DOMAINNAME} 3600 a \\${ip}\" >> \\$nsupdatecmds\n    echo \"send\" >> \\$nsupdatecmds\n\n    nsupdate \\$nsupdatecmds\nfi\nEOFDHCP\n\nchmod 755 /etc/network/if-up.d/register-dns\n\nif ! grep -Fq \"${DOMAINNAME}\" /etc/dhcp/dhclient.conf\nthen\n    echo $(date) \" - Adding domain to dhclient.conf\"\n\n    echo \"supersede domain-name \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\n    echo \"prepend domain-search \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\nfi\n\n# service networking restart\necho $(date) \" - Restarting network\"\nsudo ifdown eth0 && sudo ifup eth0", "num_lines": 39}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script file to run hello-world in bash\n\n#!/bin/bash\necho \"hello\"", "num_lines": 4}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script file to run hello-world in dcos\n\n#!/bin/bash\n\nset -e\n\necho $(date) \" - Starting Script\"\n\n# Deploy container\necho $(date) \" - Deploying hello-world\"\n\ncurl -X post http://localhost:8080/v2/apps -d \"{ \\\"id\\\": \\\"hello-marathon\\\", \\\"cmd\\\": \\\"while [ true ] ; do echo 'Hello World' ; sleep 5 ; done\\\", \\\"cpus\\\": 0.1, \\\"mem\\\": 10.0, \\\"instances\\\": 1 }\" -H \"Content-type:application/json\"\n\necho $(date) \" - view applications in marathon UI to validate\"\necho $(date) \" - Script complete\"\n\n", "num_lines": 17}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script file to install the docker hello-world container\n\n#!/bin/bash\n\nset -e\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        /usr/local/bin/kubectl cluster-info\n        if [ \"$?\" = \"0\" ]\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        /usr/bin/docker ps | grep apiserver\n        if [ \"$?\" = \"0\" ]\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\n# Deploy container\necho $(date) \" - Deploying hello-world container\"\n\nkubectl run hello-world --quiet --image=busybox --restart=OnFailure -- echo \"Hello Kubernetes!\"\n\necho $(date) \" - run kubectl get pods --show-all to list the pods\"\necho $(date) \" - run kubectl logs (passing the pod name gathered from kubectl get pods)\"\necho $(date) \" - Script complete\"\n", "num_lines": 46}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n[ \"$DEBUG\" == 'true' ] && set -x\n\nparameters=$(echo $1 | base64 -d -)\n\nlog() {\n  echo \"`date +'[%Y-%m-%d %H:%M:%S:%N %Z]'` $1\"\n}\n\nget_param() {\n  local param=$1\n  echo $(echo \"$parameters\" | jq \".$param\" -r)\n}\n\ninstall_script_dependencies() {\n  log ''\n  log 'Installing script dependencies'\n  log ''\n\n  # Install jq to obtain the input parameters\n  log 'Installing jq'\n  log ''\n  sudo apt-get -y install jq\n  log ''\n\n  log 'done'\n  log ''\n}\n\ncleanup_script_dependencies() {\n  log ''\n  log 'Removing script dependencies'\n  log ''\n\n  log 'Removing jq'\n  log ''\n  sudo apt-get -y remove jq\n  log ''\n\n  log 'done'\n  log ''\n}\n\ncreate_secret_yaml() {\n  log ''\n  log 'Creating oms-agentsecret.yaml file'\n  log ''\n\n  local wsid=$(get_param 'WSID')\n  local key=$(get_param 'KEY')\n\n  cat > ./oms-agentsecret.yaml <<EOFSECRET\napiVersion: v1\nkind: Secret\nmetadata:\n  name: omsagent-secret\ntype: Opaque\ndata:\n  wsid: `echo $wsid | base64 -w0`\n  key: `echo $key | base64 -w0` \nEOFSECRET\n\n  log 'done'\n  log ''\n}\n\ncreate_daemonset_yaml() {\n  log ''\n  log 'Creating oms-daemonset.yaml file'\n  log ''\n\n  cat > oms-daemonset.yaml <<EOFDAEMONSET\napiVersion: extensions/v1beta1\nkind: DaemonSet\nmetadata:\n name: omsagent\nspec:\n template:\n  metadata:\n   labels:\n    app: omsagent\n    agentVersion: 1.3.4-127\n    dockerProviderVersion: 10.0.0-22\n  spec:\n   containers:\n     - name: omsagent \n       image: \"microsoft/oms\"\n       imagePullPolicy: Always\n       env:\n        - name: WSID\n          valueFrom:\n            secretKeyRef:\n              name: omsagent-secret\n              key: wsid\n        - name: KEY\n          valueFrom:\n            secretKeyRef:\n              name: omsagent-secret\n              key: key\n       securityContext:\n         privileged: true\n       ports:\n       - containerPort: 25225\n         protocol: TCP \n       - containerPort: 25224\n         protocol: UDP\n       volumeMounts:\n        - mountPath: /var/run/docker.sock\n          name: docker-sock\n        - mountPath: /var/opt/microsoft/omsagent/state/containerhostname\n          name: container-hostname\n        - mountPath: /var/log \n          name: host-log\n   volumes:\n    - name: docker-sock \n      hostPath:\n       path: /var/run/docker.sock\n    - name: container-hostname\n      hostPath:\n       path: /etc/hostname\n    - name: host-log\n      hostPath:\n       path: /var/log \nEOFDAEMONSET\n\n  log 'done'\n  log ''\n}\n\ndeploy_yaml() {\n  log ''\n  log 'Deploying yaml files'\n  log ''\n\n  log 'Deploying oms agent secret - oms-agentsecret.yaml'\n  kubectl create -f 'oms-agentsecret.yaml'\n\n  log 'Deploying oms agent daemonset - oms-daemonset.yaml' \n  kubectl create -f 'oms-daemonset.yaml'\n\n  log 'done'\n  log ''\n}\n\n\nlog  \" Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        /usr/local/bin/kubectl cluster-info\n        if [ \"$?\" = \"0\" ]\n        then\n            log \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        /usr/bin/docker ps | grep apiserver\n        if [ \"$?\" = \"0\" ]\n        then\n            log \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    log \"kubernetes did not start\"\n    exit 1\nfi\n\nlog ''\nlog 'ACS-Engine - installing Microsoft OMS Agent (k8s)'\nlog '--------------------------------------------------'\n\ninstall_script_dependencies\ncreate_secret_yaml\ncreate_daemonset_yaml\ndeploy_yaml\ncleanup_script_dependencies\n\nlog ''\nlog 'done'\nlog ''\n", "num_lines": 190}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Setting kubeconfig\"\nexport KUBECONFIG=/var/lib/kubelet/kubeconfig\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        /usr/local/bin/kubectl cluster-info\n        if [ \"$?\" = \"0\" ]\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        /usr/bin/docker ps | grep apiserver\n        if [ \"$?\" = \"0\" ]\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\nmaster_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=master --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_master_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning master nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_MASTER=$(master_nodes)\n\n        if [[ -n $FIRST_K8S_MASTER ]]; then\n            echo $(date) \" - kubectl is returning master nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return master nodes in the alotted time\"\n    return 1\n}\n\nagent_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_agent_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning agent nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_AGENT=$(agent_nodes)\n\n        if [[ -n $FIRST_K8S_AGENT ]]; then\n            echo $(date) \" - kubectl is returning agent nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return agent nodes in the alotted time\"\n    return 1\n}\n\nshould_this_node_run_extension() {\n    FIRST_K8S_MASTER=$(master_nodes)\n    if [[ $FIRST_K8S_MASTER = $(hostname) ]]; then\n        echo $(date) \" - Local node $(hostname) is found to be the first master node $FIRST_K8S_MASTER\"\n        return\n    else\n        FIRST_K8S_AGENT=$(agent_nodes)\n        if [[ $FIRST_K8S_AGENT = $(hostname) ]]; then\n            echo $(date) \" - Local node $(hostname) is found to be the first agent node $FIRST_K8S_AGENT\"\n            return\n        else\n            echo $(date) \" - Local node $(hostname) is not the first master node $FIRST_K8S_MASTER or the first agent node $FIRST_K8S_AGENT\"\n            return 1\n        fi\n    fi\n}\n\nstorageclass_param() {\n\tkubectl get no -l kubernetes.io/role=agent -l storageprofile=managed --no-headers -o jsonpath=\"{.items[0].metadata.name}\" > /dev/null 2> /dev/null\n\tif [[ $? -eq 0 ]]; then\n\t\techo '--set server.persistentVolume.storageClass=managed-standard'\n\tfi\n}\n\nwait_for_tiller() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is Helm running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        helm version > /dev/null 2> /dev/null\n\n        if [[ $? -eq 0 ]]; then\n            echo $(date) \" - Helm is running\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - Helm failed to start in the alotted time\"\n    return 1\n}\n\ninstall_helm() {\n    echo $(date) \" - Downloading helm\"\n    curl https://storage.googleapis.com/kubernetes-helm/helm-v2.6.2-linux-amd64.tar.gz > helm-v2.6.2-linux-amd64.tar.gz\n    tar -zxvf helm-v2.6.2-linux-amd64.tar.gz\n    mv linux-amd64/helm /usr/local/bin/helm\n    echo $(date) \" - Downloading prometheus values\"\n\n    curl \"$1\" > prometheus_values.yaml\n\n    sleep 10\n\n    echo $(date) \" - helm version\"\n    helm version\n    helm init\n\n    echo $(date) \" - helm installed\"\n}\n\ndaemonset_api() {\n    SERVER_VERSION_REGEX=\"Server Version: v([0-9]+)\\.([0-9]+)\\.([0-9]+)$\"\n    K8S_SERVER_VERSION=$(kubectl version --short | grep Server)\n    K8S_SERVER_VERSION_MAJOR=$(echo \"$K8S_SERVER_VERSION\" | sed -r \"s/$SERVER_VERSION_REGEX/\\1/g\")\n    K8S_SERVER_VERSION_MINOR=$(sed -r \"s/$SERVER_VERSION_REGEX/\\2/g\" \"$K8S_SERVER_VERSION\")\n\n    if [[ $K8S_SERVER_VERSION_MAJOR -gt 1 ]]; then\n        echo \"apps/v1\"\n    elif [[ $K8S_SERVER_VERSION_MAJOR -eq 1 ]]; then\n        if [[ $K8S_SERVER_VERSION_MINOR -gt 8 ]]; then\n            echo \"apps/v1\"\n        else\n            echo \"apps/v1beta2\"\n        fi\n    fi\n}\n\ninstall_cadvisor() {\n    echo \"$(date) - Installing cAdvisor\"\n    local NAMESPACE=\"$1\"\n    echo \"$(date) - Using namespace $NAMESPACE\"\n    local CADVISOR_DS_CONFIG_URL=\"$2\"\n    echo \"$(date) - Using cAdvisor config at $CADVISOR_DS_CONFIG_URL\"\n\n    curl -o cadvisor_ds.yml \"$CADVISOR_DS_CONFIG_URL\"\n    DAEMONSET_API=$(daemonset_api)\n    echo \"$(date) - Using DaemonSet api group $DAEMONSET_API\"\n    sed -i 's|DAEMONSET_API|'\"$DAEMONSET_API\"'|g' cadvisor_ds.yml\n    kubectl apply -f ./cadvisor_ds.yml\n}\n\nupdate_helm() {\n    echo $(date) \" - Updating Helm repositories\"\n    helm repo update\n}\n\ninstall_prometheus() {\n    PROM_RELEASE_NAME=monitoring\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Prometheus Helm chart\"\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        helm install -f prometheus_values.yaml \\\n            --name $PROM_RELEASE_NAME \\\n            --version 5.1.3 \\\n            --namespace $NAMESPACE stable/prometheus $(storageclass_param)\n\n        if [[ $? -eq 0 ]]; then\n            echo $(date) \" - Helm install successfully completed\"\n            break\n        else\n            echo $(date) \" - Helm install returned a non-zero exit code. Retrying.\"\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    PROM_POD_PREFIX=\"$PROM_RELEASE_NAME-prometheus-server\"\n    DESIRED_POD_STATE=Running\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the prometheus server pod ($PROM_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $PROM_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE\n\n        if [[ $? -eq 0 ]]; then\n            echo $(date) \" - $PROM_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\ninstall_grafana() {\n    GF_RELEASE_NAME=dashboard\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Grafana Helm chart\"\n    helm install \\\n        --name $GF_RELEASE_NAME \\\n        --version 0.8.5 \\\n        --namespace $NAMESPACE stable/grafana $(storageclass_param)\n\n    GF_POD_PREFIX=\"$GF_RELEASE_NAME-grafana\"\n    DESIRED_POD_STATE=Running\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the grafana pod ($GF_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $GF_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE\n\n        if [[ $? -eq 0 ]]; then\n            echo $(date) \" - $GF_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\nensure_k8s_namespace_exists() {\n    NAMESPACE_TO_EXIST=\"$1\"\n\n    kubectl get ns $NAMESPACE_TO_EXIST > /dev/null 2> /dev/null\n    if [[ $? -ne 0 ]]; then\n        echo $(date) \" - Creating namespace $NAMESPACE_TO_EXIST\"\n        kubectl create ns $NAMESPACE_TO_EXIST\n    else\n        echo $(date) \" - Namespace $NAMESPACE_TO_EXIST already exists\"\n    fi\n}\n\nNAMESPACE=default\nRAW_PROMETHEUS_CHART_VALS=\"https://raw.githubusercontent.com/Azure/acs-engine/master/extensions/prometheus-grafana-k8s/v1/prometheus_values.yaml\"\nCADVISOR_CONFIG_URL=\"https://raw.githubusercontent.com/Azure/acs-engine/master/extensions/prometheus-grafana-k8s/v1/cadvisor_daemonset.yml\"\n\n# retrieve and parse extension parameters\nif [[ -n \"$1\" ]]; then\n    IFS=';' read -ra INPUT <<< \"$1\"\n    if [[ -n \"${INPUT[0]}\" ]]; then\n        NAMESPACE=\"${INPUT[0]}\"\n        echo \"$(date) - Custom namespace specified: $NAMESPACE\"\n    fi\n    if [[ -n \"${INPUT[1]}\" ]]; then\n        RAW_PROMETHEUS_CHART_VALS=\"${INPUT[1]}\"\n        echo \"$(date) - Custom prometheus chart values url specified: $RAW_PROMETHEUS_CHART_VALS\"\n    fi\n    if [[ -n \"${INPUT[2]}\" ]]; then\n        CADVISOR_CONFIG_URL=\"${INPUT[2]}\"\n        echo \"$(date) - Custom cAdvisor config url specified: $CADVISOR_CONFIG_URL\"\n    fi\nfi\n\n# this extension should only run on a single node\n# the logic to decide whether or not this current node\n# should run the extension is to alphabetically determine\n# if this local machine is the first in the list of master nodes\n# if it is, then run the extension. if not, exit\nwait_for_master_nodes\nif [[ $? -ne 0 ]]; then\n    echo $(date) \" - Error while waiting for kubectl to output master nodes. Exiting\"\n    exit 1\nfi\n\nwait_for_agent_nodes\nif [[ $? -ne 0 ]]; then\n    echo $(date) \" - Error while waiting for kubectl to output agent nodes. Exiting\"\n    exit 1\nfi\n\necho \"$(date) - Dumping out sorted agent nodes\"\nkubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort\n\nshould_this_node_run_extension\nif [[ $? -ne 0 ]]; then\n    echo $(date) \" - Not the first master node or the first agent node, no longer continuing extension. Exiting\"\n    exit 1\nfi\n\nensure_k8s_namespace_exists $NAMESPACE\n\nK8S_SECRET_NAME=dashboard-grafana\nDS_TYPE=prometheus\nDS_NAME=prometheus1\n\nPROM_URL=http://monitoring-prometheus-server\n\n# When RBAC is enabled, need to grant permission to tiller\nkubectl create clusterrolebinding tiller-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default\n\ninstall_helm \"$RAW_PROMETHEUS_CHART_VALS\"\nwait_for_tiller\nif [[ $? -ne 0 ]]; then\n    echo $(date) \" - Tiller did not respond in a timely manner. Exiting\"\n    exit 1\nfi\nupdate_helm\ninstall_cadvisor $NAMESPACE $CADVISOR_CONFIG_URL\ninstall_prometheus $NAMESPACE\ninstall_grafana $NAMESPACE\n\nsleep 5\n\necho $(date) \" - Creating the Prometheus datasource in Grafana\"\nGF_USER_NAME=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-user}\" | base64 --decode)\necho $GF_USER_NAME\nGF_PASSWORD=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-password}\" | base64 --decode)\necho $GF_PASSWORD\nGF_URL=$(kubectl get svc -n $NAMESPACE -l \"app=dashboard-grafana,component=grafana\" -o jsonpath=\"{.items[0].spec.clusterIP}\")\necho $GF_URL\n\necho retrieving current data sources...\nCURRENT_DS_LIST=$(curl -s --user \"$GF_USER_NAME:$GF_PASSWORD\" \"$GF_URL/api/datasources\")\necho $CURRENT_DS_LIST | grep -q \"\\\"name\\\":\\\"$DS_NAME\\\"\"\nif [[ $? -eq 0 ]]; then\n    echo data source $DS_NAME already exists\n    echo $CURRENT_DS_LIST | python -m json.tool\n    exit 0\nfi\n\necho data source $DS_NAME does not exist, creating...\nDS_RAW=$(cat << EOF\n{\n    \"name\": \"$DS_NAME\",\n    \"type\": \"$DS_TYPE\",\n    \"url\": \"$PROM_URL\",\n    \"access\": \"proxy\"\n}\nEOF\n)\n\n\n\nATTEMPTS=90\nSLEEP_TIME=10\n\nITERATION=0\nwhile [[ $ITERATION -lt $ATTEMPTS ]]; do\n    echo $(date) \" - Is the grafana api running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n    response=$(curl \\\n        -X POST \\\n        --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n        -H \"Content-Type: application/json\" \\\n        -d \"$DS_RAW\" \\\n        \"$GF_URL/api/datasources\")\n\n    if [[ $response == *\"Datasource added\"* ]]; then\n        echo $(date) \" - Data source added successfully\"\n        break\n    fi\n\n    ITERATION=$(( $ITERATION + 1 ))\n    sleep $SLEEP_TIME\ndone\n\necho $(date) \" - Creating the Kubernetes dashboard in Grafana\"\n\ncat << EOF > sanitize_dashboard.py\n#!/usr/bin/python3\n\nimport fileinput\nimport json\n\ndashboard = json.loads(''.join(fileinput.input()))\ndashboard.pop('__inputs')\ndashboard.pop('__requires')\nprint(json.dumps(dashboard).replace('\\${DS_PROMETHEUS}', 'prometheus1'))\n\nEOF\n\nchmod u+x sanitize_dashboard.py\n\nDB_RAW=$(cat << EOF\n{\n    \"dashboard\": $(curl -sL \"https://grafana.com/api/dashboards/3119/revisions/2/download\" | ./sanitize_dashboard.py),\n    \"overwrite\": false\n}\nEOF\n)\n\ncurl \\\n    -X POST \\\n    --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n    -H \"Content-Type: application/json\" \\\n    -d \"$DB_RAW\" \\\n    \"$GF_URL/api/dashboards/db\"\n\necho $(date) \" - Script complete\"\n", "num_lines": 446}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "# baseUrl=\"http://localhost:8080/marathon\" # handy for local testing with SSH\nbaseUrl=\"http://marathon.mesos:8080\" \n\n# definitions for elasticsearch and vamp applications (from http://vamp.io/documentation/installation/v0.9.3/dcos/)\nelasticsearch='{\"id\":\"elasticsearch\",\"instances\":1,\"cpus\":0.2,\"mem\":1024,\"container\":{\"docker\":{\"image\":\"magneticio/elastic:2.2\",\"network\":\"HOST\",\"forcePullImage\":true}},\"healthChecks\":[{\"protocol\":\"TCP\",\"gracePeriodSeconds\":30,\"intervalSeconds\":10,\"timeoutSeconds\":5,\"port\":9200,\"maxConsecutiveFailures\":0}]}'\nvamp='{\"id\":\"vamp/vamp\",\"instances\":1,\"cpus\":0.5,\"mem\":1024,\"container\":{\"type\":\"DOCKER\",\"docker\":{\"image\":\"magneticio/vamp:0.9.4-dcos\",\"network\":\"BRIDGE\",\"portMappings\":[{\"containerPort\":8080,\"hostPort\":0,\"name\":\"vip0\",\"labels\":{\"VIP_0\":\"10.20.0.100:8080\"}}],\"forcePullImage\":true}},\"labels\":{\"DCOS_SERVICE_NAME\":\"vamp\",\"DCOS_SERVICE_SCHEME\":\"http\",\"DCOS_SERVICE_PORT_INDEX\":\"0\"},\"env\":{\"VAMP_WAIT_FOR\":\"http://elasticsearch.marathon.mesos:9200/.kibana\",\"VAMP_WORKFLOW_DRIVER_VAMP_URL\":\"http://10.20.0.100:8080\",\"VAMP_ELASTICSEARCH_URL\":\"http://elasticsearch.marathon.mesos:9200\"},\"healthChecks\":[{\"protocol\":\"TCP\",\"gracePeriodSeconds\":30,\"intervalSeconds\":10,\"timeoutSeconds\":5,\"portIndex\":0,\"maxConsecutiveFailures\":0}]}'\n   \n\nfunction wait_for_running_app(){\n    ## args\n    ## $1 - app name\n    appname=$1\n\n    ## wait for deployment\n    waitCount=0\n    appRunning=0\n    while [ $waitCount -lt 12 ]\n    do\n        echo \"Testing for $appname running...\"\n        appResponse=$(curl \"$baseUrl/v2/apps/$appname\" 2>/dev/null) # url for $appname app\n        if [[ $appResponse =~ \\\"state\\\":\\\"TASK_RUNNING\\\" ]]; then # test for TASK_RUNNING\n            echo \"$appname running!\"\n            appRunning=1\n            return 0\n        fi\n        \n        sleep 10s\n        waitCount=$[$waitCount+1]\n    done\n    return 1\n}\n\n## Start elasticsearch deployment\necho \"Starting elasticsearch deployment\"\ncurl -X POST \"$baseUrl/v2/apps\" -H 'Content-Type: application/json' -d $elasticsearch\necho \"\"\n\nwait_for_running_app \"elasticsearch\"\nelasticRunning=$?\n\nif [[ $elasticRunning -ne 0 ]]; then\n    echo \"elasticsearch not running - quitting\"\n    exit 100\nfi\n\n## Start vamp deployment\necho \"Starting vamp deployment\"\ncurl -X POST \"$baseUrl/v2/apps\" -H 'Content-Type: application/json' -d $vamp\necho \"\"\n\nwait_for_running_app \"vamp/vamp\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/vamp not running - quitting\"\n    exit 100\nfi\n\nwait_for_running_app \"vamp/vamp-gateway-agent\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/vamp-gateway-agent not running - quitting\"\n    exit 100\nfi\n\nwait_for_running_app \"vamp/workflow-health\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/workflow-health not running - quitting\"\n    exit 100\nfi\n\nwait_for_running_app \"vamp/workflow-kibana\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/workflow-kibana not running - quitting\"\n    exit 100\nfi\n\nwait_for_running_app \"vamp/workflow-metrics\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/workflow-metrics not running - quitting\"\n    exit 100\nfi\n\nwait_for_running_app \"vamp/workflow-vga\"\nrunning=$?\nif [[ $running -ne 0 ]]; then\n    echo \"vamp/workflow-vga not running - quitting\"\n    exit 100\nfi\n", "num_lines": 92}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n## Cleanup packer SSH key and machine ID generated for this boot\nrm -f /root/.ssh/authorized_keys\nrm -f /home/packer/.ssh/authorized_keys\nrm -f /etc/machine-id\ntouch /etc/machine-id", "num_lines": 7}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nCDIR=$(dirname \"${BASH_SOURCE}\")\n\nSETTINGS_JSON=\"${SETTINGS_JSON:-./packer/settings.json}\"\nSP_JSON=\"${SP_JSON:-./packer/sp.json}\"\nSUBSCRIPTION_ID=\"${SUBSCRIPTION_ID:-`az account show -o json --query=\"id\" | tr -d '\"'`}\"\nSTORAGE_ACCOUNT_NAME=\"aksimages$(date +%s)\"\n\necho \"Subscription ID: ${SUBSCRIPTION_ID}\"\necho \"Service Principal Path: ${SP_JSON}\"\n\nif [ -a \"${SP_JSON}\" ]; then\n\techo \"Existing credentials file found.\"\n\texit 0\nelif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"Service principal not found! Generating one @ ${SP_JSON}\"\n\taz ad sp create-for-rbac -n aks-images-packer$(date +%s) -o json > ${SP_JSON}\n\tCLIENT_ID=`cat ${SP_JSON} | jq -r .appId`\n\tCLIENT_SECRET=`cat ${SP_JSON} | jq -r .password`\n\tTENANT_ID=`cat ${SP_JSON} | jq -r .tenant`\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n\techo \"creating new storage account ${STORAGE_ACCOUNT_NAME}\"\n\taz storage account create -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME --sku \"Standard_RAGRS\"\n\techo \"creating new container system\"\n\tkey=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME | jq -r '.[0].value')\n\taz storage container create --name system --public-access container --account-key=$key --account-name=$STORAGE_ACCOUNT_NAME\nelse\n\techo \"storage account ${STORAGE_ACCOUNT_NAME} already exists.\"\nfi\n\nif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"CLIENT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${CLIENT_SECRET}\" ]; then\n\techo \"CLIENT_SECRET was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${TENANT_ID}\" ]; then\n\techo \"TENANT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\necho \"storage name: ${STORAGE_ACCOUNT_NAME}\"\n\ncat <<EOF > packer/settings.json\n{\n  \"subscription_id\":  \"${SUBSCRIPTION_ID}\",\n  \"client_id\": \"${CLIENT_ID}\",\n  \"client_secret\": \"${CLIENT_SECRET}\",\n  \"tenant_id\":      \"${TENANT_ID}\",\n  \"resource_group_name\": \"${AZURE_RESOURCE_GROUP_NAME}\",\n  \"location\": \"${AZURE_LOCATION}\",\n  \"storage_account_name\": \"${STORAGE_ACCOUNT_NAME}\",\n  \"vm_size\": \"${AZURE_VM_SIZE}\"\n}\nEOF\n\ncat packer/settings.json\n", "num_lines": 66}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_source.sh\n\necho \"Starting build on \" `date` > /var/log/azure/golden-image-install.complete\necho \"Using kernel:\" >> /var/log/azure/golden-image-install.complete\ncat /proc/version | tee -a /var/log/azure/golden-image-install.complete\n\nETCD_VERSION=\"3.2.24\"\nETCD_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/github-coreos\"\ninstallEtcd\n\ninstallDeps\n\nif [[ ${FEATURE_FLAGS} == *\"docker-engine\"* ]]; then\n    DOCKER_ENGINE_REPO=\"https://apt.dockerproject.org/repo\"\n    installDockerEngine\n    installGPUDrivers\nelse\n    installMoby\nfi\n\ninstallClearContainersRuntime\n\nVNET_CNI_VERSIONS=\"1.0.10 1.0.11 1.0.12 1.0.13 1.0.14\"\nCNI_PLUGIN_VERSIONS=\"0.7.1\"\n\nfor VNET_CNI_VERSION in $VNET_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/cni/azure-vnet-cni-linux-amd64-v${VNET_CNI_VERSION}.tgz\"\n    downloadAzureCNI\ndone\n\nfor CNI_PLUGIN_VERSION in $CNI_PLUGIN_VERSIONS; do\n    CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/cni/cni-plugins-amd64-v${CNI_PLUGIN_VERSION}.tgz\"\n    downloadCNI\ndone\n\nCONTAINERD_DOWNLOAD_URL_BASE=\"https://storage.googleapis.com/cri-containerd-release/\"\ninstallContainerd\n\ninstallImg\n\nDASHBOARD_VERSIONS=\"1.10.0 1.6.3\"\nfor DASHBOARD_VERSION in ${DASHBOARD_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/kubernetes-dashboard-amd64:v${DASHBOARD_VERSION}\"\ndone\n\nEXECHEALTHZ_VERSIONS=\"1.2\"\nfor EXECHEALTHZ_VERSION in ${EXECHEALTHZ_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/exechealthz-amd64:${EXECHEALTHZ_VERSION}\"\ndone\n\nADDON_RESIZER_VERSIONS=\"1.8.1 1.7\"\nfor ADDON_RESIZER_VERSION in ${ADDON_RESIZER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/addon-resizer:${ADDON_RESIZER_VERSION}\"\ndone\n\nHEAPSTER_VERSIONS=\"1.5.3 1.5.1 1.3.0\"\nfor HEAPSTER_VERSION in ${HEAPSTER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/heapster-amd64:v${HEAPSTER_VERSION}\"\ndone\n\nMETRICS_SERVER_VERSIONS=\"0.2.1\"\nfor METRICS_SERVER_VERSION in ${METRICS_SERVER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/metrics-server-amd64:v${METRICS_SERVER_VERSION}\"\ndone\n\nKUBE_DNS_VERSIONS=\"1.14.13 1.14.5\"\nfor KUBE_DNS_VERSION in ${KUBE_DNS_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/k8s-dns-kube-dns-amd64:${KUBE_DNS_VERSION}\"\ndone\n\nKUBE_ADDON_MANAGER_VERSIONS=\"8.8 8.7 8.6\"\nfor KUBE_ADDON_MANAGER_VERSION in ${KUBE_ADDON_MANAGER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/kube-addon-manager-amd64:v${KUBE_ADDON_MANAGER_VERSION}\"\ndone\n\nKUBE_DNS_MASQ_VERSIONS=\"1.14.10 1.14.8 1.14.5\"\nfor KUBE_DNS_MASQ_VERSION in ${KUBE_DNS_MASQ_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/k8s-dns-dnsmasq-nanny-amd64:${KUBE_DNS_MASQ_VERSION}\"\ndone\n\nPAUSE_VERSIONS=\"3.1\"\nfor PAUSE_VERSION in ${PAUSE_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/pause-amd64:${PAUSE_VERSION}\"\ndone\n\nTILLER_VERSIONS=\"2.8.1\"\nfor TILLER_VERSION in ${TILLER_VERSIONS}; do\n    pullContainerImage \"docker\" \"gcr.io/kubernetes-helm/tiller:v${TILLER_VERSION}\"\ndone\n\nCLUSTER_AUTOSCALER_VERSIONS=\"1.3.4 1.3.3 1.2.2 1.1.2\"\nfor CLUSTER_AUTOSCALER_VERSION in ${CLUSTER_AUTOSCALER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/cluster-autoscaler:v${CLUSTER_AUTOSCALER_VERSION}\"\ndone\n\nK8S_DNS_SIDECAR_VERSIONS=\"1.14.10 1.14.8 1.14.7\"\nfor K8S_DNS_SIDECAR_VERSION in ${K8S_DNS_SIDECAR_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/k8s-dns-sidecar-amd64:${K8S_DNS_SIDECAR_VERSION}\"\ndone\n\nCORE_DNS_VERSIONS=\"1.2.2\"\nfor CORE_DNS_VERSION in ${CORE_DNS_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/coredns:${CORE_DNS_VERSION}\"\ndone\n\nRESCHEDULER_VERSIONS=\"0.4.0 0.3.1\"\nfor RESCHEDULER_VERSION in ${RESCHEDULER_VERSIONS}; do\n    pullContainerImage \"docker\" \"k8s.gcr.io/rescheduler:v${RESCHEDULER_VERSION}\"\ndone\n\nVIRTUAL_KUBELET_VERSIONS=\"latest\"\nfor VIRTUAL_KUBELET_VERSION in ${VIRTUAL_KUBELET_VERSIONS}; do\n    pullContainerImage \"docker\" \"microsoft/virtual-kubelet:${VIRTUAL_KUBELET_VERSION}\"\ndone\n\nAZURE_CNI_NETWORKMONITOR_VERSIONS=\"0.0.4\"\nfor AZURE_CNI_NETWORKMONITOR_VERSION in ${AZURE_CNI_NETWORKMONITOR_VERSIONS}; do\n    pullContainerImage \"docker\" \"containernetworking/networkmonitor:v${AZURE_CNI_NETWORKMONITOR_VERSION}\"\ndone\n\nNVIDIA_DEVICE_PLUGIN_VERSIONS=\"1.11 1.10\"\nfor NVIDIA_DEVICE_PLUGIN_VERSION in ${NVIDIA_DEVICE_PLUGIN_VERSIONS}; do\n    pullContainerImage \"docker\" \"nvidia/k8s-device-plugin:${NVIDIA_DEVICE_PLUGIN_VERSION}\"\ndone\n\nTUNNELFRONT_VERSIONS=\"v1.9.2-v4.0.4\"\nfor TUNNELFRONT_VERSION in ${TUNNELFRONT_VERSIONS}; do\n    pullContainerImage \"docker\" \"docker.io/deis/hcp-tunnel-front:${TUNNELFRONT_VERSION}\"\ndone\n\nKUBE_SVC_REDIRECT_VERSIONS=\"1.0.2\"\nfor KUBE_SVC_REDIRECT_VERSION in ${KUBE_SVC_REDIRECT_VERSIONS}; do\n    pullContainerImage \"docker\" \"docker.io/deis/kube-svc-redirect:v${KUBE_SVC_REDIRECT_VERSION}\"\ndone\n\nKV_FLEXVOLUME_VERSIONS=\"0.0.5\"\nfor KV_FLEXVOLUME_VERSION in ${KV_FLEXVOLUME_VERSIONS}; do\n    pullContainerImage \"docker\" \"mcr.microsoft.com/k8s/flexvolume/keyvault-flexvolume:v${KV_FLEXVOLUME_VERSION}\"\ndone\n\nIP_MASQ_AGENT_VERSIONS=\"2.0.0\"\nfor IP_MASQ_AGENT_VERSION in ${IP_MASQ_AGENT_VERSIONS}; do\n    pullContainerImage \"docker\" \"gcr.io/google-containers/ip-masq-agent-amd64:v${IP_MASQ_AGENT_VERSION}\"\ndone\n\nNGINX_VERSIONS=\"1.13.12-alpine\"\nfor NGINX_VERSION in ${NGINX_VERSIONS}; do\n    pullContainerImage \"docker\" \"nginx:${NGINX_VERSION}\"\ndone\n\npullContainerImage \"docker\" \"busybox\"\n\n# TODO: fetch supported k8s versions from an acs-engine command instead of hardcoding them here\nK8S_VERSIONS=\"1.7.15 1.7.16 1.8.14 1.8.15 1.9.10 1.9.11 1.10.8 1.10.9 1.11.4 1.11.5 1.12.1 1.12.2\"\n\nfor KUBERNETES_VERSION in ${K8S_VERSIONS}; do\n    HYPERKUBE_URL=\"k8s.gcr.io/hyperkube-amd64:v${KUBERNETES_VERSION}\"\n    extractHyperkube \"docker\"\n    pullContainerImage \"docker\" \"k8s.gcr.io/cloud-controller-manager-amd64:v${KUBERNETES_VERSION}\"\ndone\n\ndf -h\n\necho \"Install completed successfully on \" `date` >> /var/log/azure/golden-image-install.complete\necho \"VSTS Build NUMBER: ${BUILD_NUMBER}\" >> /var/log/azure/golden-image-install.complete\necho \"VSTS Build ID: ${BUILD_ID}\" >> /var/log/azure/golden-image-install.complete\necho \"Commit: ${COMMIT}\" >> /var/log/azure/golden-image-install.complete\necho \"Feature flags: ${FEATURE_FLAGS}\" >> /var/log/azure/golden-image-install.complete\n", "num_lines": 172}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMESOSDIR=/var/lib/mesos/dl\nmkdir $MESOSDIR\n\n# load the env vars\n. /etc/mesosphere/setup-flags/dcos-deploy-environment\n\n# default dc/os component download address (Azure CDN)\nDOCKER_ENGINE_DOWNLOAD_URL=https://mesosphere.blob.core.windows.net/dcos-deps/docker-engine_1.13.1-0-ubuntu-xenial_amd64.deb\nLIBIPSET_DOWNLOAD_URL=https://az837203.vo.msecnd.net/dcos-deps/libipset3_6.29-1_amd64.deb\nIPSET_DOWNLOAD_URL=https://az837203.vo.msecnd.net/dcos-deps/ipset_6.29-1_amd64.deb\nUNZIP_DOWNLOAD_URL=https://az837203.vo.msecnd.net/dcos-deps/unzip_6.0-20ubuntu1_amd64.deb\nLIBLTDL_DOWNLOAD_URL=https://az837203.vo.msecnd.net/dcos-deps/libltdl7_2.4.6-0.1_amd64.deb\n\ncase $DCOS_ENVIRONMENT in\n    # because of Chinese GreatWall Firewall, the default packages on Azure CDN is blocked. So the following Chinese local mirror url should be used instead.\n    AzureChinaCloud)\n        DOCKER_ENGINE_DOWNLOAD_URL=http://acsengine.blob.core.chinacloudapi.cn/dcos/docker-engine_1.11.2-0~xenial_amd64.deb\n        LIBIPSET_DOWNLOAD_URL=http://acsengine.blob.core.chinacloudapi.cn/dcos/libipset3_6.29-1_amd64.deb\n        IPSET_DOWNLOAD_URL=http://acsengine.blob.core.chinacloudapi.cn/dcos/ipset_6.29-1_amd64.deb\n        UNZIP_DOWNLOAD_URL=http://acsengine.blob.core.chinacloudapi.cn/dcos/unzip_6.0-20ubuntu1_amd64.deb\n        LIBLTDL_DOWNLOAD_URL=http://acsengine.blob.core.chinacloudapi.cn/dcos/libltdl7_2.4.6-0.1_amd64.deb\n    ;;\nesac\n\ncurl -fLsSv --retry 20 -Y 100000 -y 60 -o $MESOSDIR/d.deb $DOCKER_ENGINE_DOWNLOAD_URL &\ncurl -fLsSv --retry 20 -Y 100000 -y 60 -o $MESOSDIR/1.deb $LIBIPSET_DOWNLOAD_URL &\ncurl -fLsSv --retry 20 -Y 100000 -y 60 -o $MESOSDIR/2.deb $IPSET_DOWNLOAD_URL &\ncurl -fLsSv --retry 20 -Y 100000 -y 60 -o $MESOSDIR/3.deb $UNZIP_DOWNLOAD_URL &\ncurl -fLsSv --retry 20 -Y 100000 -y 60 -o $MESOSDIR/4.deb $LIBLTDL_DOWNLOAD_URL &\nwait\n\nfor i in {1..300}; do\n    dpkg -i $MESOSDIR/{1,2,3,4}.deb\n    if [ \"$?\" = \"0\" ]\n    then\n        echo \"succeeded\"\n        break\n    fi\n    sleep 1\ndone\n\nROLESFILECONTENTS\n\n# add Azure update domain and fault domain attributes\nud=$( curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/platformUpdateDomain?api-version=2017-04-02&format=text\" )\nfd=$( curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/platformFaultDomain?api-version=2017-04-02&format=text\" )\necho \";azure.faultdomain:$fd;azure.updatedomain:$ud\" >> /var/lib/dcos/mesos-slave-common", "num_lines": 49}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "function retry_download() {\n  retries=$1; wait_sleep=$2; timeout=$3; url=$4; path=$5 checksum=$6\n  for i in $(seq 1 $retries); do\n    rm -f $path\n    timeout $timeout curl -fsSL $url -o $path\n    if [ $? -ne 0 ]; then\n      echo \"retry_download[$i] Error: Failed to execute curl -fsSL $url -o $path\"\n      sleep $wait_sleep\n      continue\n    fi\n    if [ ! -z \"${checksum:-}\" ]; then\n      actual=$(sha1sum -b $path | cut -f 1 -d \" \")\n      if [ $? -ne 0 ]; then\n        echo \"retry_download[$i] Error: Failed to execute sha1sum -b $path (per $url)\"\n        sleep $wait_sleep\n        continue\n      fi\n      if [ \"$checksum\" != \"$actual\" ]; then\n        echo \"retry_download[$i] Error: sha1sum mismatch for $url\"\n        sleep $wait_sleep\n        continue\n      fi\n    fi\n    return 0\n  done\n  return 1\n}\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@}\n        [ $? -eq 0 ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"Error: Failed to execute \\\"$@\\\" after $i attempts\"\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction retry_get_install_deb() {\n  retries=$1; wait_sleep=$2; timeout=$3; url=$4; checksum=$5\n  deb=$(mktemp)\n  trap \"rm -f $deb\" RETURN\n  retry_download $retries $wait_sleep $timeout $url $deb $checksum\n  if [ $? -ne 0 ]; then\n    echo \"Error: Failed to download $url\"\n    return 1\n  fi\n  retrycmd_if_failure $retries $wait_sleep $timeout dpkg -i $deb\n  if [ $? -ne 0 ]; then\n    echo \"Error: Failed to install $url\"\n    return 1\n  fi\n}\n", "num_lines": 59}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource /opt/azure/containers/provision_source.sh\nsource /opt/azure/dcos/environment\n\n# default dc/os component download address (Azure CDN)\npackages=(\n  https://dcos-mirror.azureedge.net/pkg/libltdl7_2.4.6-0.1_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/docker-ce_17.09.0~ce-0~ubuntu_amd64.deb\n)\n\n# sha1sum checksums for @packages\nsha1sums=(\n  9a0f9f2769d3dc834737aa7df50aaaea369af98d\n  94f6e89be6d45d9988269a237eb27c7d6a844d7f\n)\n\ncase $DCOS_ENVIRONMENT in\n  # because of Chinese GreatWall Firewall, the default packages on Azure CDN is blocked. So the following Chinese local mirror url should be used instead.\n  AzureChinaCloud)\n    packages=(\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/libltdl7_2.4.6-0.1_amd64.deb\n      http://mirror.kaiyuanshe.cn/docker-ce/linux/ubuntu/dists/xenial/pool/stable/amd64/docker-ce_17.09.0~ce-0~ubuntu_amd64.deb\n    )\n    ;;\nesac\n\nlen=$((${#packages[@]}-1))\nfor i in $(seq 0 $len); do\n  retry_get_install_deb 10 10 120 ${packages[$i]} ${sha1sums[$i]}\n    if [ $? -ne 0  ]; then\n    exit 1\n  fi\ndone\n", "num_lines": 35}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource /opt/azure/containers/provision_source.sh\nsource /opt/azure/dcos/environment\n\nTMPDIR=\"/tmp/dcos\"\nmkdir -p $TMPDIR\n\n# default dc/os component download address (Azure CDN)\npackages=(\n  https://dcos-mirror.azureedge.net/pkg/libipset3_6.29-1_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/ipset_6.29-1_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/unzip_6.0-20ubuntu1_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/libltdl7_2.4.6-0.1_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/docker-ce_17.09.0~ce-0~ubuntu_amd64.deb\n  https://dcos-mirror.azureedge.net/pkg/selinux-utils_2.4-3build2_amd64.deb\n)\n\n# sha1sum checksums for @packages\nsha1sums=(\n  f88d09688291917c8bb65682fea9f5d571ec8d6a\n  807dc11f5bfa39bb4b0dc9024fc51bb309905a21\n  57ae2bb6ded1fdf91b6d518294134df1ff13fcca\n  9a0f9f2769d3dc834737aa7df50aaaea369af98d\n  94f6e89be6d45d9988269a237eb27c7d6a844d7f\n  77bdb5847060845c0a158f567b1ddd7fa34b7236\n)\n\ncase $DCOS_ENVIRONMENT in\n  # because of Chinese GreatWall Firewall, the default packages on Azure CDN is blocked. So the following Chinese local mirror url should be used instead.\n  AzureChinaCloud)\n    packages=(\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/libipset3_6.29-1_amd64.deb\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/ipset_6.29-1_amd64.deb\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/unzip_6.0-20ubuntu1_amd64.deb\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/libltdl7_2.4.6-0.1_amd64.deb\n      http://mirror.kaiyuanshe.cn/docker-ce/linux/ubuntu/dists/xenial/pool/stable/amd64/docker-ce_17.09.0~ce-0~ubuntu_amd64.deb\n      http://acsengine.blob.core.chinacloudapi.cn/dcos/selinux-utils_2.4-3build2_amd64.deb\n    )\n  ;;\nesac\n\nlen=$((${#packages[@]}-1))\nfor i in $(seq 0 $len); do\n  retry_get_install_deb 10 10 120 ${packages[$i]} ${sha1sums[$i]}\n    if [ $? -ne 0  ]; then\n    exit 1\n  fi\ndone\n\nretrycmd_if_failure 10 10 120 curl -fsSL -o $TMPDIR/dcos_install.sh http://BOOTSTRAP_IP:8086/dcos_install.sh\nif [ $? -ne 0  ]; then\n  exit 1\nfi\n", "num_lines": 55}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script originated at https://github.com/kubernetes/kubernetes/blob/master/cluster/gce/gci/health-monitor.sh\n# and has been modified for acs-engine.\n\nset -o nounset\nset -o pipefail\n\ncontainer_runtime_monitoring() {\n  local -r max_attempts=5\n  local attempt=1\n  local -r crictl=\"${KUBE_HOME}/bin/crictl\"\n  local -r container_runtime_name=\"${CONTAINER_RUNTIME_NAME:-docker}\"\n  local healthcheck_command=\"docker ps\"\n  if [[ \"${CONTAINER_RUNTIME:-docker}\" != \"docker\" ]]; then\n    healthcheck_command=\"${crictl} pods\"\n  fi\n  \n  until timeout 60 ${healthcheck_command} > /dev/null; do\n    if (( attempt == max_attempts )); then\n      echo \"Max attempt ${max_attempts} reached! Proceeding to monitor container runtime healthiness.\"\n      break\n    fi\n    echo \"$attempt initial attempt \\\"${healthcheck_command}\\\"! Trying again in $attempt seconds...\"\n    sleep \"$(( 2 ** attempt++ ))\"\n  done\n  while true; do\n    if ! timeout 60 ${healthcheck_command} > /dev/null; then\n      echo \"Container runtime ${container_runtime_name} failed!\"\n      if [[ \"$container_runtime_name\" == \"docker\" ]]; then\n          pkill -SIGUSR1 dockerd\n      fi\n      systemctl kill --kill-who=main \"${container_runtime_name}\"\n      sleep 120\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\nkubelet_monitoring() {\n  echo \"Wait for 2 minutes for kubelet to be functional\"\n  sleep 120\n  local -r max_seconds=10\n  local output=\"\"\n  while [ 1 ]; do\n    if ! output=$(curl -m \"${max_seconds}\" -f -s -S http://127.0.0.1:10255/healthz 2>&1); then\n      echo $output\n      echo \"Kubelet is unhealthy!\"\n      systemctl kill kubelet\n      sleep 60\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\nif [[ \"$#\" -ne 1 ]]; then\n  echo \"Usage: health-monitor.sh <container-runtime/kubelet>\"\n  exit 1\nfi\n\nKUBE_HOME=\"/usr/local/bin\"\nKUBE_ENV=\"/etc/default/kube-env\"\nif [[  -e \"${KUBE_ENV}\" ]]; then\n  source \"${KUBE_ENV}\"\nfi\n\nSLEEP_SECONDS=10\ncomponent=$1\necho \"Start kubernetes health monitoring for ${component}\"\n\nif [[ \"${component}\" == \"container-runtime\" ]]; then\n  container_runtime_monitoring\nelif [[ \"${component}\" == \"kubelet\" ]]; then\n  kubelet_monitoring\nelse\n  echo \"Health monitoring for component \"${component}\" is not supported!\"\nfi\n", "num_lines": 80}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\nPRIVATE_IP=$(hostname -I | cut -d' ' -f1)\nETCD_PEER_URL=\"https://${PRIVATE_IP}:2380\"\nETCD_CLIENT_URL=\"https://${PRIVATE_IP}:2379\"\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    retrycmd_if_failure 120 5 25 systemctl enable $1\n    if [ $? -ne 0 ]; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nconfigureEtcd() {\n    useradd -U \"etcd\"\n    usermod -p \"$(head -c 32 /dev/urandom | base64)\" \"etcd\"\n    passwd -u \"etcd\"\n    id \"etcd\"\n\n    APISERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/apiserver.key\"\n    touch \"${APISERVER_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${APISERVER_PRIVATE_KEY_PATH}\"\n    chown root:root \"${APISERVER_PRIVATE_KEY_PATH}\"\n\n    CA_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/ca.key\"\n    touch \"${CA_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${CA_PRIVATE_KEY_PATH}\"\n    chown root:root \"${CA_PRIVATE_KEY_PATH}\"\n\n    ETCD_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/etcdserver.key\"\n    touch \"${ETCD_SERVER_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${ETCD_SERVER_PRIVATE_KEY_PATH}\"\n    chown etcd:etcd \"${ETCD_SERVER_PRIVATE_KEY_PATH}\"\n\n    ETCD_CLIENT_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/etcdclient.key\"\n    touch \"${ETCD_CLIENT_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${ETCD_CLIENT_PRIVATE_KEY_PATH}\"\n    chown root:root \"${ETCD_CLIENT_PRIVATE_KEY_PATH}\"\n\n    ETCD_PEER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.key\"\n    touch \"${ETCD_PEER_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${ETCD_PEER_PRIVATE_KEY_PATH}\"\n    chown etcd:etcd \"${ETCD_PEER_PRIVATE_KEY_PATH}\"\n\n    ETCD_SERVER_CERTIFICATE_PATH=\"/etc/kubernetes/certs/etcdserver.crt\"\n    touch \"${ETCD_SERVER_CERTIFICATE_PATH}\"\n    chmod 0644 \"${ETCD_SERVER_CERTIFICATE_PATH}\"\n    chown root:root \"${ETCD_SERVER_CERTIFICATE_PATH}\"\n\n    ETCD_CLIENT_CERTIFICATE_PATH=\"/etc/kubernetes/certs/etcdclient.crt\"\n    touch \"${ETCD_CLIENT_CERTIFICATE_PATH}\"\n    chmod 0644 \"${ETCD_CLIENT_CERTIFICATE_PATH}\"\n    chown root:root \"${ETCD_CLIENT_CERTIFICATE_PATH}\"\n\n    ETCD_PEER_CERTIFICATE_PATH=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.crt\"\n    touch \"${ETCD_PEER_CERTIFICATE_PATH}\"\n    chmod 0644 \"${ETCD_PEER_CERTIFICATE_PATH}\"\n    chown root:root \"${ETCD_PEER_CERTIFICATE_PATH}\"\n\n    set +x\n    echo \"${APISERVER_PRIVATE_KEY}\" | base64 --decode > \"${APISERVER_PRIVATE_KEY_PATH}\"\n    echo \"${CA_PRIVATE_KEY}\" | base64 --decode > \"${CA_PRIVATE_KEY_PATH}\"\n    echo \"${ETCD_SERVER_PRIVATE_KEY}\" | base64 --decode > \"${ETCD_SERVER_PRIVATE_KEY_PATH}\"\n    echo \"${ETCD_CLIENT_PRIVATE_KEY}\" | base64 --decode > \"${ETCD_CLIENT_PRIVATE_KEY_PATH}\"\n    echo \"${ETCD_PEER_KEY}\" | base64 --decode > \"${ETCD_PEER_PRIVATE_KEY_PATH}\"\n    echo \"${ETCD_SERVER_CERTIFICATE}\" | base64 --decode > \"${ETCD_SERVER_CERTIFICATE_PATH}\"\n    echo \"${ETCD_CLIENT_CERTIFICATE}\" | base64 --decode > \"${ETCD_CLIENT_CERTIFICATE_PATH}\"\n    echo \"${ETCD_PEER_CERT}\" | base64 --decode > \"${ETCD_PEER_CERTIFICATE_PATH}\"\n    set -x\n\n    ETCD_SETUP_FILE=/opt/azure/containers/setup-etcd.sh\n    wait_for_file 1200 1 $ETCD_SETUP_FILE || exit $ERR_ETCD_CONFIG_FAIL\n    $ETCD_SETUP_FILE > /opt/azure/containers/setup-etcd.log 2>&1\n    RET=$?\n    if [ $RET -ne 0 ]; then\n        exit $RET\n    fi\n\n    MOUNT_ETCD_FILE=/opt/azure/containers/mountetcd.sh\n    wait_for_file 1200 1 $MOUNT_ETCD_FILE || exit $ERR_ETCD_CONFIG_FAIL\n    $MOUNT_ETCD_FILE || exit $ERR_ETCD_VOL_MOUNT_FAIL\n    systemctlEnableAndStart etcd || exit $ERR_ETCD_START_TIMEOUT\n    for i in $(seq 1 600); do\n        MEMBER=\"$(sudo etcdctl member list | grep -E ${NODE_NAME} | cut -d':' -f 1)\"\n        if [ \"$MEMBER\" != \"\" ]; then\n            break\n        else\n            sleep 1\n        fi\n    done\n    retrycmd_if_failure 120 5 25 sudo etcdctl member update $MEMBER ${ETCD_PEER_URL} || exit $ERR_ETCD_CONFIG_FAIL\n}\n\nensureRPC() {\n    systemctlEnableAndStart rpcbind || exit $ERR_SYSTEMCTL_START_FAIL\n    systemctlEnableAndStart rpc-statd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nrunAptDaily() {\n    wait_for_apt_locks\n    /usr/lib/apt/apt.systemd.daily\n}\n\ngenerateAggregatedAPICerts() {\n    AGGREGATED_API_CERTS_SETUP_FILE=/etc/kubernetes/generate-proxy-certs.sh\n    wait_for_file 1200 1 $AGGREGATED_API_CERTS_SETUP_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    $AGGREGATED_API_CERTS_SETUP_FILE\n}\n\nconfigureK8s() {\n    KUBELET_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/client.key\"\n    touch \"${KUBELET_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${KUBELET_PRIVATE_KEY_PATH}\"\n    chown root:root \"${KUBELET_PRIVATE_KEY_PATH}\"\n\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    set +x\n    echo \"${KUBELET_PRIVATE_KEY}\" | base64 --decode > \"${KUBELET_PRIVATE_KEY_PATH}\"\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping for special characters \" and \\\n    SERVICE_PRINCIPAL_CLIENT_SECRET=$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | sed \"s|\\\\\\\\|\\\\\\\\\\\\\\|g\")\n    SERVICE_PRINCIPAL_CLIENT_SECRET=$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | sed 's|\"|\\\\\"|g')\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\":\"${TARGET_ENVIRONMENT}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRatelimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ ! -z \"${MASTER_NODE}\" ]]; then\n        if [[ \"${ENABLE_AGGREGATED_APIS}\" = True ]]; then\n            generateAggregatedAPICerts\n        fi\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        if [[ \"${NETWORK_POLICY}\" != \"calico\" ]]; then\n            mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n            chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\nsetKubeletOpts () {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    wait_for_file 1200 1 $KUBELET_DEFAULT_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    sed -i \"s#^KUBELET_OPTS=.*#KUBELET_OPTS=${1}#\" $KUBELET_DEFAULT_FILE\n}\n\nensureCCProxy() {\n    cat $CC_SERVICE_IN_TMP | sed 's#@libexecdir@#/usr/libexec#' > /etc/systemd/system/cc-proxy.service\n    cat $CC_SOCKET_IN_TMP sed 's#@localstatedir@#/var#' > /etc/systemd/system/cc-proxy.socket\n\techo \"Enabling and starting Clear Containers proxy service...\"\n\tsystemctlEnableAndStart cc-proxy || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nsetupContainerd() {\n    echo \"Configuring cri-containerd...\"\n    mkdir -p \"/etc/containerd\"\n    CRI_CONTAINERD_CONFIG=\"/etc/containerd/config.toml\"\n    echo \"subreaper = false\" > \"$CRI_CONTAINERD_CONFIG\"\n    echo \"oom_score = 0\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"[plugins.cri]\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"sandbox_image = \\\"$POD_INFRA_CONTAINER_SPEC\\\"\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"[plugins.cri.containerd.untrusted_workload_runtime]\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"runtime_type = 'io.containerd.runtime.v1.linux'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    if [[ \"$CONTAINER_RUNTIME\" == \"clear-containers\" ]]; then\n        echo \"runtime_engine = '/usr/bin/cc-runtime'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    elif [[ \"$CONTAINER_RUNTIME\" == \"kata-containers\" ]]; then\n        echo \"runtime_engine = '/usr/bin/kata-runtime'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    else\n        echo \"runtime_engine = '/usr/local/sbin/runc'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    fi\n    echo \"[plugins.cri.containerd.default_runtime]\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"runtime_type = 'io.containerd.runtime.v1.linux'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    echo \"runtime_engine = '/usr/local/sbin/runc'\" >> \"$CRI_CONTAINERD_CONFIG\"\n    setKubeletOpts \" --container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock\"\n}\n\nensureContainerd() {\n    if [[ \"$CONTAINER_RUNTIME\" == \"clear-containers\" ]] || [[ \"$CONTAINER_RUNTIME\" == \"kata-containers\" ]] || [[ \"$CONTAINER_RUNTIME\" == \"containerd\" ]]; then\n        setupContainerd\n        echo \"Enabling and starting cri-containerd service...\"\n        systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n    fi\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    wait_for_file 1200 1 $DOCKER_SERVICE_EXEC_START_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    echo \"ExecStartPost=/sbin/iptables -P FORWARD ACCEPT\" >> $DOCKER_SERVICE_EXEC_START_FILE\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    wait_for_file 1200 1 $DOCKER_MOUNT_FLAGS_SYSTEMD_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    wait_for_file 1200 1 $DOCKER_JSON_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    systemctlEnableAndStart docker\n    # Delay start of docker-monitor for 30 mins after booting\n    DOCKER_MONITOR_SYSTEMD_TIMER_FILE=/etc/systemd/system/docker-monitor.timer\n    wait_for_file 1200 1 $DOCKER_MONITOR_SYSTEMD_TIMER_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    DOCKER_MONITOR_SYSTEMD_FILE=/etc/systemd/system/docker-monitor.service\n    wait_for_file 1200 1 $DOCKER_MONITOR_SYSTEMD_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    systemctlEnableAndStart docker-monitor.timer || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureKMS() {\n    systemctlEnableAndStart kms || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    wait_for_file 1200 1 $KUBELET_DEFAULT_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n    wait_for_file 1200 1 $KUBECONFIG_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    wait_for_file 1200 1 $KUBELET_RUNTIME_CONFIG_SCRIPT_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n    # Delay start of kubelet-monitor for 30 mins after booting\n    #KUBELET_MONITOR_SYSTEMD_TIMER_FILE=/etc/systemd/system/kubelet-monitor.timer\n    #wait_for_file 1200 1 $KUBELET_MONITOR_SYSTEMD_TIMER_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    #KUBELET_MONITOR_SYSTEMD_FILE=/etc/systemd/system/kubelet-monitor.service\n    #wait_for_file 1200 1 $KUBELET_MONITOR_SYSTEMD_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    #systemctlEnableAndStart kubelet-monitor.timer || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureJournal(){\n    echo \"Storage=persistent\" >> /etc/systemd/journald.conf\n    echo \"SystemMaxUse=1G\" >> /etc/systemd/journald.conf\n    echo \"RuntimeMaxUse=1G\" >> /etc/systemd/journald.conf\n    echo \"ForwardToSyslog=no\" >> /etc/systemd/journald.conf\n    systemctlEnableAndStart systemd-journald || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensurePodSecurityPolicy() {\n    POD_SECURITY_POLICY_FILE=\"/etc/kubernetes/manifests/pod-security-policy.yaml\"\n    if [ -f $POD_SECURITY_POLICY_FILE ]; then\n        $KUBECTL create -f $POD_SECURITY_POLICY_FILE\n    fi\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    wait_for_file 3600 1 $KUBECTL || exit $ERR_FILE_WATCH_TIMEOUT\n    # workaround for 1.12 bug https://github.com/Azure/acs-engine/issues/3681\n    if [[ \"${KUBERNETES_VERSION}\" = 1.12.* ]]; then\n        ensureKubelet\n        retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || ensureKubelet && retrycmd_if_failure 900 1 20 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n    fi\n}\n\nensureEtcd() {\n    retrycmd_if_failure 120 5 25 curl --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/etcdclient.crt --key /etc/kubernetes/certs/etcdclient.key ${ETCD_CLIENT_URL}/v2/machines || exit $ERR_ETCD_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    wait_for_file 1200 1 $CLUSTER_AUTOSCALER_ADDON_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    if [[ \"${USE_MANAGED_IDENTITY_EXTENSION}\" == true ]]; then\n        CLUSTER_AUTOSCALER_MSI_VOLUME_MOUNT=\"- mountPath: /var/lib/waagent/\\n\\          name: waagent\\n\\          readOnly: true\"\n        CLUSTER_AUTOSCALER_MSI_VOLUME=\"- hostPath:\\n\\          path: /var/lib/waagent/\\n\\        name: waagent\"\n        CLUSTER_AUTOSCALER_MSI_HOST_NETWORK=\"hostNetwork: true\"\n\n        sed -i \"s|<volMounts>|${CLUSTER_AUTOSCALER_MSI_VOLUME_MOUNT}|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n        sed -i \"s|<vols>|${CLUSTER_AUTOSCALER_MSI_VOLUME}|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n        sed -i \"s|<hostNet>|$(echo \"${CLUSTER_AUTOSCALER_MSI_HOST_NETWORK}\")|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    elif [[ \"${USE_MANAGED_IDENTITY_EXTENSION}\" == false ]]; then\n        sed -i \"s|<volMounts>|\"\"|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n        sed -i \"s|<vols>|\"\"|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n        sed -i \"s|<hostNet>|\"\"|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    fi\n\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<vmType>|$(echo $VM_TYPE | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<vmssName>|$(echo $PRIMARY_SCALE_SET)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"$(echo $SERVICE_PRINCIPAL_CLIENT_ID)\\\", \\\"clientSecret\\\": \\\"$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET)\\\", \\\"tenantId\\\": \\\"$(echo $TENANT_ID)\\\", \\\"subscriptionId\\\": \\\"$(echo $SUBSCRIPTION_ID)\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    wait_for_file 1200 1 $ACI_CONNECTOR_ADDON_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$(echo $RESOURCE_GROUP)|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$(echo $ACI_CONNECTOR_CERT)|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$(echo $ACI_CONNECTOR_KEY)|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAddons() {\n    if [[ \"${CLUSTER_AUTOSCALER_ADDON}\" = True ]]; then\n        configClusterAutoscalerAddon\n    fi\n\n    if [[ \"${ACI_CONNECTOR_ADDON}\" = True ]]; then\n        configACIConnectorAddon\n    fi\n}\n\nconfigGPUDrivers() {\n    retrycmd_if_failure 30 1 120 sh $GPU_DEST/nvidia-drivers-$GPU_DV --silent --accept-license --no-drm --dkms --utility-prefix=\"${GPU_DEST}\" --opengl-prefix=\"${GPU_DEST}\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    echo \"${GPU_DEST}/lib64\" > /etc/ld.so.conf.d/nvidia.conf\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    umount -l /usr/lib/x86_64-linux-gnu\n    retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 $GPU_DEST/bin/nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n}\n\nensureGPUDrivers() {\n    configGPUDrivers\n    systemctlEnableAndStart nvidia-modprobe || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 30 1 120 systemctl restart kubelet || exit $ERR_GPU_DRIVERS_START_FAIL\n}\n", "num_lines": 417}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nset -x\necho `date`,`hostname`, startcustomscript>>/opt/m\n\nscript_lib=/opt/azure/containers/provision_source.sh\nfor i in $(seq 1 3600); do\n    if [ -f $script_lib ]; then\n        break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsource $script_lib\n\ninstall_script=/opt/azure/containers/provision_installs.sh\nwait_for_file 3600 1 $install_script || exit $ERR_FILE_WATCH_TIMEOUT\nsource $install_script\n\nconfig_script=/opt/azure/containers/provision_configs.sh\nwait_for_file 3600 1 $config_script || exit $ERR_FILE_WATCH_TIMEOUT\nsource $config_script\n\nCUSTOM_SEARCH_DOMAIN_SCRIPT=/opt/azure/containers/setup-custom-search-domains.sh\n\nset +x\nETCD_PEER_CERT=$(echo ${ETCD_PEER_CERTIFICATES} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((${NODE_INDEX}+1)))\nETCD_PEER_KEY=$(echo ${ETCD_PEER_PRIVATE_KEYS} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((${NODE_INDEX}+1)))\nset -x\n\nif [[ $OS == $COREOS_OS_NAME ]]; then\n    echo \"Changing default kubectl bin location\"\n    KUBECTL=/opt/kubectl\nfi\n\nif [ -f /var/run/reboot-required ]; then\n    REBOOTREQUIRED=true\nelse\n    REBOOTREQUIRED=false\nfi\n\nif [ -f /var/log/azure/golden-image-install.complete ]; then\n    echo \"detected golden image pre-install\"\n    FULL_INSTALL_REQUIRED=false\n    rm -rf /home/packer\n    cleanUpContainerImages\nelse\n    FULL_INSTALL_REQUIRED=true\nfi\n\nholdWALinuxAgent() {\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure 120 5 25 apt-mark hold walinuxagent || exit $ERR_HOLD_WALINUXAGENT\n        wait_for_apt_locks\n    fi\n}\n\nif [[ ! -z \"${MASTER_NODE}\" ]]; then\n    installEtcd\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    holdWALinuxAgent\n    installDeps\nelse \n    echo \"Golden image; skipping dependencies installation\"\nfi\n\ninstallContainerRuntime\ninstallNetworkPlugin\ninstallContainerd\nif [[ \"${GPU_NODE}\" = true ]]; then\n    if $FULL_INSTALL_REQUIRED; then\n        installGPUDrivers\n    fi\n    ensureGPUDrivers\nfi\ninstallKubeletAndKubectl\nensureRPC\ncreateKubeManifestDir\n\nif [[ ! -z \"${MASTER_NODE}\" ]]; then\n    configureEtcd\nelse\n    removeEtcd\nfi\n\nif [ -f $CUSTOM_SEARCH_DOMAIN_SCRIPT ]; then\n    $CUSTOM_SEARCH_DOMAIN_SCRIPT > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\nif [[ \"$CONTAINER_RUNTIME\" == \"docker\" ]]; then\n    ensureDocker\nelif [[ \"$CONTAINER_RUNTIME\" == \"clear-containers\" ]]; then\n\tif grep -q vmx /proc/cpuinfo; then\n        ensureCCProxy\n\tfi\nelif [[ \"$CONTAINER_RUNTIME\" == \"kata-containers\" ]]; then\n    if grep -q vmx /proc/cpuinfo; then\n        installKataContainersRuntime\n    fi\nfi\n\nconfigureK8s\nconfigureCNI\n\nif [[ ! -z \"${MASTER_NODE}\" ]]; then\n    configAddons\nfi\n\nensureContainerd\n\nif [[ ! -z \"${MASTER_NODE}\" && \"${KMS_PROVIDER_VAULT_NAME}\" != \"\" ]]; then\n    ensureKMS\nfi\n\nensureKubelet\nensureJournal\n\nif [[ ! -z \"${MASTER_NODE}\" ]]; then\n    writeKubeConfig\n    ensureEtcd\n    ensureK8sControlPlane\n    ensurePodSecurityPolicy\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635\n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n\n        wait_for_apt_locks\n        retrycmd_if_failure 120 5 25 apt-mark unhold walinuxagent || exit $ERR_RELEASE_HOLD_WALINUXAGENT\n        wait_for_apt_locks\n    fi\nfi\n\necho \"Custom script finished successfully\"\n\necho `date`,`hostname`, endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\nps auxfww > /opt/azure/provision-ps.log &\n\nif $REBOOTREQUIRED; then\n  echo 'reboot required, rebooting node in 1 minute'\n  /bin/bash -c \"shutdown -r 1 &\"\nelse\n  runAptDaily &\nfi", "num_lines": 154}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\n\nremoveEtcd() {\n    rm -rf /usr/bin/etcd &\n}\n\ninstallEtcd() {\n    CURRENT_VERSION=$(etcd --version | grep \"etcd Version\" | cut -d \":\" -f 2 | tr -d '[:space:]')\n    if [[ \"$CURRENT_VERSION\" == \"${ETCD_VERSION}\" ]]; then\n        echo \"etcd version ${ETCD_VERSION} is already installed, skipping download\"\n    else\n        retrycmd_get_tarball 360 10 /tmp/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz ${ETCD_DOWNLOAD_URL}/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz || exit $ERR_ETCD_DOWNLOAD_TIMEOUT\n        removeEtcd\n        tar -xzvf /tmp/etcd-v${ETCD_VERSION}-linux-amd64.tar.gz -C /usr/bin/ --strip-components=1 || exit $ERR_ETCD_DOWNLOAD_TIMEOUT\n    fi\n}\n\ninstallDeps() {\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    apt_get_install 30 1 600 apt-transport-https blobfuse ca-certificates ceph-common cgroup-lite cifs-utils conntrack ebtables ethtool fuse git glusterfs-client init-system-helpers iproute2 ipset iptables jq mount nfs-common pigz socat util-linux xz-utils zip || exit $ERR_APT_INSTALL_TIMEOUT\n}\n\ninstallGPUDrivers() {\n    rmmod nouveau\n    echo blacklist nouveau >> /etc/modprobe.d/blacklist.conf\n    retrycmd_if_failure_no_stats 120 5 25 update-initramfs -u || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    mkdir -p $GPU_DEST\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/gpgkey > /tmp/aptnvidia.gpg || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-key add /tmp/aptnvidia.gpg || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu16.04/amd64/nvidia-docker.list > /tmp/nvidia-docker.list || exit  $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure_no_stats 120 5 25 cat /tmp/nvidia-docker.list > /etc/apt/sources.list.d/nvidia-docker.list\n    apt_get_update\n    retrycmd_if_failure 30 5 3600 apt-get install -y linux-headers-$(uname -r) gcc make dkms || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    retrycmd_if_failure 30 5 3600 apt-get -o Dpkg::Options::=\"--force-confold\" install -y nvidia-docker2=${NVIDIA_DOCKER_VERSION}+docker${DOCKER_VERSION} nvidia-container-runtime=${NVIDIA_CONTAINER_RUNTIME_VERSION}+docker${DOCKER_VERSION} || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    retrycmd_if_failure 30 5 60 curl -fLS https://us.download.nvidia.com/tesla/$GPU_DV/NVIDIA-Linux-x86_64-${GPU_DV}.run -o ${GPU_DEST}/nvidia-drivers-${GPU_DV} || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    mkdir -p $GPU_DEST/lib64 $GPU_DEST/overlay-workdir\n    retrycmd_if_failure 120 5 25 mount -t overlay -o lowerdir=/usr/lib/x86_64-linux-gnu,upperdir=${GPU_DEST}/lib64,workdir=${GPU_DEST}/overlay-workdir none /usr/lib/x86_64-linux-gnu || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n}\n\ninstallContainerRuntime() {\n    if [[ \"$CONTAINER_RUNTIME\" == \"docker\" ]]; then\n        if [[ \"$DOCKER_ENGINE_REPO\" != \"\" ]]; then\n            installDockerEngine\n        else\n            installMoby\n        fi\n    elif [[ \"$CONTAINER_RUNTIME\" == \"clear-containers\" ]]; then\n\t    # Ensure we can nest virtualization\n        if grep -q vmx /proc/cpuinfo; then\n            installClearContainersRuntime\n        fi\n    fi\n}\n\ninstallMoby() {\n    dockerd --version\n    if [ $? -eq 0 ]; then\n        echo \"dockerd is already installed, skipping download\"\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n        retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n        apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n        apt_get_install 20 30 120 moby-engine moby-cli || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\ninstallDockerEngine() {\n    DOCKER_ENGINE_VERSION=\"1.13.*\"\n    dockerd --version\n    if [ $? -eq 0 ]; then\n        echo \"dockerd is already installed, skipping download\"\n    else\n        retrycmd_if_failure_no_stats 20 1 5 curl -fsSL https://aptdocker.azureedge.net/gpg > /tmp/aptdocker.gpg || exit $ERR_DOCKER_KEY_DOWNLOAD_TIMEOUT\n        retrycmd_if_failure 10 5 10 apt-key add /tmp/aptdocker.gpg || exit $ERR_DOCKER_APT_KEY_TIMEOUT\n        echo \"deb ${DOCKER_ENGINE_REPO} ubuntu-xenial main\" | sudo tee /etc/apt/sources.list.d/docker.list\n        printf \"Package: docker-engine\\nPin: version ${DOCKER_ENGINE_VERSION}\\nPin-Priority: 550\\n\" > /etc/apt/preferences.d/docker.pref\n        apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n        apt_get_install 20 30 120 docker-engine || exit $ERR_DOCKER_INSTALL_TIMEOUT\n    fi\n}\n\ninstallKataContainersRuntime() {\n    # TODO incorporate this into packer CI so that it is pre-baked into the VHD image\n    echo \"Adding Kata Containers repository key...\"\n    KATA_RELEASE_KEY_TMP=/tmp/kata-containers-release.key\n    KATA_URL=http://download.opensuse.org/repositories/home:/katacontainers:/release/xUbuntu_16.04/Release.key\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL $KATA_URL > $KATA_RELEASE_KEY_TMP || exit $ERR_KATA_KEY_DOWNLOAD_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure 30 5 30 apt-key add $KATA_RELEASE_KEY_TMP || exit $ERR_KATA_APT_KEY_TIMEOUT\n    echo \"Adding Kata Containers repository...\"\n    echo 'deb http://download.opensuse.org/repositories/home:/katacontainers:/release/xUbuntu_16.04/ /' > /etc/apt/sources.list.d/kata-containers.list\n    echo \"Installing Kata Containers runtime...\"\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    apt_get_install 120 5 25 kata-runtime || exit $ERR_KATA_INSTALL_TIMEOUT\n}\n\ninstallClearContainersRuntime() {\n    cc-runtime --version\n    if [ $? -eq 0 ]; then\n        echo \"cc-runtime is already installed, skipping download\"\n    else\n        echo \"Adding Clear Containers repository key...\"\n        CC_RELEASE_KEY_TMP=/tmp/clear-containers-release.key\n        CC_URL=https://download.opensuse.org/repositories/home:clearcontainers:clear-containers-3/xUbuntu_16.04/Release.key\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL $CC_URL > $CC_RELEASE_KEY_TMP || exit $ERR_APT_INSTALL_TIMEOUT\n        wait_for_apt_locks\n        retrycmd_if_failure 120 5 25 apt-key add $CC_RELEASE_KEY_TMP || exit $ERR_APT_INSTALL_TIMEOUT\n        echo \"Adding Clear Containers repository...\"\n        echo 'deb http://download.opensuse.org/repositories/home:/clearcontainers:/clear-containers-3/xUbuntu_16.04/ /' > /etc/apt/sources.list.d/cc-runtime.list\n        echo \"Installing Clear Containers runtime...\"\n        apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n        apt_get_install 120 5 25 cc-runtime\n        local repo_uri=\"https://raw.githubusercontent.com/clearcontainers/proxy/3.0.23\"\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL \"${repo_uri}/cc-proxy.service.in\" > $CC_SERVICE_IN_TMP\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL \"${repo_uri}/cc-proxy.socket.in\" > $CC_SOCKET_IN_TMP\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=$(echo ${CNI_PLUGINS_URL} | cut -d \"/\" -f 5)\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=$(echo ${VNET_CNI_PLUGINS_URL} | cut -d \"/\" -f 5)\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=$(echo ${CNI_PLUGINS_URL} | cut -d \"/\" -f 5)\n    if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n        downloadCNI\n    fi\n    mkdir -p $CNI_BIN_DIR\n    tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=$(echo ${VNET_CNI_PLUGINS_URL} | cut -d \"/\" -f 5)\n    if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n        downloadAzureCNI\n    fi\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n    mkdir -p $CNI_BIN_DIR\n    tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n}\n\ninstallContainerd() {\n    containerd --version\n    if [ $? -eq 0 ]; then\n        echo \"containerd is already installed, skipping download\"\n    else\n        CRI_CONTAINERD_VERSION=\"1.1.0\"\n        CONTAINERD_DOWNLOAD_URL=\"${CONTAINERD_DOWNLOAD_URL_BASE}cri-containerd-${CRI_CONTAINERD_VERSION}.linux-amd64.tar.gz\"\n        CONTAINERD_TGZ_TMP=/tmp/containerd.tar.gz\n        retrycmd_get_tarball 120 5 \"$CONTAINERD_TGZ_TMP\" \"$CONTAINERD_DOWNLOAD_URL\" || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n        tar -xzf \"$CONTAINERD_TGZ_TMP\" -C /\n        rm -f \"$CONTAINERD_TGZ_TMP\"\n        sed -i '/\\[Service\\]/a ExecStartPost=\\/sbin\\/iptables -P FORWARD ACCEPT' /etc/systemd/system/containerd.service\n        echo \"Successfully installed cri-containerd...\"\n    fi\n}\n\ninstallImg() {\n    img_filepath=/usr/local/bin/img\n    retrycmd_get_executable 120 5 $img_filepath \"https://acs-mirror.azureedge.net/img/img-linux-amd64-v0.4.6\" ls || exit $ERR_IMG_DOWNLOAD_TIMEOUT\n}\n\nextractHyperkube() {\n    CLI_TOOL=$1\n    path=\"/home/hyperkube-downloads/${KUBERNETES_VERSION}\"\n    mkdir -p \"$path\"\n    pullContainerImage $CLI_TOOL ${HYPERKUBE_URL}\n    if [[ \"$CLI_TOOL\" == \"docker\" ]]; then\n        docker run --rm -v $path:$path ${HYPERKUBE_URL} /bin/bash -c \"cp /hyperkube $path\"\n    else\n        img unpack -o \"$path\" ${HYPERKUBE_URL}\n    fi\n\n    if [[ $OS == $COREOS_OS_NAME ]]; then\n        cp \"$path/hyperkube\" \"/opt/kubelet\"\n        mv \"$path/hyperkube\" \"/opt/kubectl\"\n        chmod a+x /opt/kubelet /opt/kubectl\n    else\n        cp \"$path/hyperkube\" \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\"\n        mv \"$path/hyperkube\" \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\"\n    fi\n}\n\ninstallKubeletAndKubectl() {\n    if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n        if [[ \"$CONTAINER_RUNTIME\" == \"docker\" ]]; then\n            extractHyperkube \"docker\"\n        else\n            installImg\n            extractHyperkube \"img\"\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    DOCKER_IMAGE_URL=$2\n    retrycmd_if_failure 60 1 1200 $CLI_TOOL pull $DOCKER_IMAGE_URL || exit $ERR_CONTAINER_IMG_PULL_TIMEOUT\n}\n\ncleanUpContainerImages() {\n    # TODO remove all unused container images at runtime\n    docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep -v ${KUBERNETES_VERSION} | grep 'hyperkube') &\n    docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep -v ${KUBERNETES_VERSION} | grep 'cloud-controller-manager') &\n    if [ \"$IS_HOSTED_MASTER\" = \"false\" ]; then\n        echo \"Cleaning up AKS container images, not an AKS cluster\"\n        docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep 'hcp-tunnel-front') &\n        docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep 'kube-svc-redirect') &\n        docker rmi $(docker images --format '{{.Repository}}:{{.Tag}}' | grep 'nginx') &\n    fi\n}", "num_lines": 249}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsource /opt/azure/containers/provision_source.sh\n\nPROXY_CA_KEY=\"${PROXY_CA_KEY:=/tmp/proxy-client-ca.key}\"\nPROXY_CRT=\"${PROXY_CRT:=/tmp/proxy-client-ca.crt}\"\nPROXY_CLIENT_KEY=\"${PROXY_CLIENT_KEY:=/tmp/proxy-client.key}\"\nPROXY_CLIENT_CSR=\"${PROXY_CLIENT_CSR:=/tmp/proxy-client.csr}\"\nPROXY_CLIENT_CRT=\"${PROXY_CLIENT_CRT:=/tmp/proxy-client.crt}\"\nETCD_REQUESTHEADER_CLIENT_CA=\"${ETCD_REQUESTHEADER_CLIENT_CA:=/proxycerts/requestheader-client-ca-file}\"\nETCD_PROXY_CERT=\"${ETCD_PROXY_CERT:=/proxycerts/proxy-client-cert-file}\"\nETCD_PROXY_KEY=\"${ETCD_PROXY_KEY:=/proxycerts/proxy-client-key-file}\"\nK8S_PROXY_CA_CRT_FILEPATH=\"${K8S_PROXY_CA_CRT_FILEPATH:=/etc/kubernetes/certs/proxy-ca.crt}\"\nK8S_PROXY_KEY_FILEPATH=\"${K8S_PROXY_KEY_FILEPATH:=/etc/kubernetes/certs/proxy.key}\"\nK8S_PROXY_CRT_FILEPATH=\"${K8S_PROXY_CRT_FILEPATH:=/etc/kubernetes/certs/proxy.crt}\"\n\nexport ETCDCTL_ENDPOINTS=\"${ETCDCTL_ENDPOINTS:=https://127.0.0.1:2379}\"\nexport ETCDCTL_CA_FILE=\"${ETCDCTL_CA_FILE:=/etc/kubernetes/certs/ca.crt}\"\nexport ETCDCTL_KEY_FILE=\"${ETCDCTL_KEY_FILE:=/etc/kubernetes/certs/etcdclient.key}\"\nexport ETCDCTL_CERT_FILE=\"${ETCDCTL_CERT_FILE:=/etc/kubernetes/certs/etcdclient.crt}\"\nexport RANDFILE=$(mktemp)\n\n# generate root CA\nopenssl genrsa -out $PROXY_CA_KEY 2048\nopenssl req -new -x509 -days 1826 -key $PROXY_CA_KEY -out $PROXY_CRT -subj '/CN=proxyClientCA'\n# generate new cert\nopenssl genrsa -out $PROXY_CLIENT_KEY 2048\nopenssl req -new -key $PROXY_CLIENT_KEY -out $PROXY_CLIENT_CSR -subj '/CN=aggregator/O=system:masters'\nopenssl x509 -req -days 730 -in $PROXY_CLIENT_CSR -CA $PROXY_CRT -CAkey $PROXY_CA_KEY -set_serial 02 -out $PROXY_CLIENT_CRT\n\nwrite_certs_to_disk() {\n    etcdctl get $ETCD_REQUESTHEADER_CLIENT_CA > $K8S_PROXY_CA_CRT_FILEPATH\n    etcdctl get $ETCD_PROXY_KEY > $K8S_PROXY_KEY_FILEPATH\n    etcdctl get $ETCD_PROXY_CERT > $K8S_PROXY_CRT_FILEPATH\n    # Remove whitespace padding at beginning of 1st line\n    sed -i '1s/\\s//' $K8S_PROXY_CA_CRT_FILEPATH $K8S_PROXY_CRT_FILEPATH $K8S_PROXY_KEY_FILEPATH\n    chmod 600 $K8S_PROXY_KEY_FILEPATH\n}\n\nwrite_certs_to_disk_with_retry() {\n    for i in 1 2 3 4 5 6 7 8 9 10 11 12; do\n        write_certs_to_disk\n        [ $? -eq 0  ] && break || sleep 5\n    done\n}\n\n# block until all etcd is ready\nretrycmd_if_failure 100 5 10 etcdctl cluster-health\n# Make etcd keys, adding a leading whitespace because etcd won't accept a val that begins with a '-' (hyphen)!\n# etcdctl will output the data it's given, stdout is redirected to dev null to avoid capturing sensitive data in logs\nif etcdctl mk $ETCD_REQUESTHEADER_CLIENT_CA \" $(cat ${PROXY_CRT})\" > /dev/null 2>&1; then\n    etcdctl mk $ETCD_PROXY_KEY \" $(cat ${PROXY_CLIENT_KEY})\" > /dev/null 2>&1\n    etcdctl mk $ETCD_PROXY_CERT \" $(cat ${PROXY_CLIENT_CRT})\" > /dev/null 2>&1\n    sleep 5\n    write_certs_to_disk_with_retry\n# If the etcdtl mk command failed, that means the key already exists\nelse\n    sleep 5\n    write_certs_to_disk_with_retry\nfi\n", "num_lines": 61}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#ERR_SYSTEMCTL_ENABLE_FAIL=3 # Service could not be enabled by systemctl -- DEPRECATED\nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_ETCD_DATA_DIR_NOT_FOUND=10 # Etcd data dir not found\nERR_ETCD_RUNNING_TIMEOUT=11 # Timeout waiting for etcd to be accessible\nERR_ETCD_DOWNLOAD_TIMEOUT=12 # Timeout waiting for etcd to download\nERR_ETCD_VOL_MOUNT_FAIL=13 # Unable to mount etcd disk volume\nERR_ETCD_START_TIMEOUT=14 # Unable to start etcd runtime\nERR_ETCD_CONFIG_FAIL=15 # Unable to configure etcd cluster\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker download(s)\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes download(s)\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_CONTAINER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a container image\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI download(s)\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n#ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 # Failed to add repo pkg file -- DEPRECATED\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd download(s)\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this (!) script on the vm\n\nOS=$(cat /etc/*-release | grep ^ID= | tr -d 'ID=\"' | awk '{print toupper($0)}')\nUBUNTU_OS_NAME=\"UBUNTU\"\nRHEL_OS_NAME=\"RHEL\"\nCOREOS_OS_NAME=\"COREOS\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\nGPU_DV=396.26\nGPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.0.3\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=2.0.0\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSL $url -o $tarball\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_executable() {\n    retries=$1; wait_sleep=$2; filepath=$3; url=$4; validation_args=$5\n    echo \"${retries} retries\"\n    for i in $(seq 1 $retries); do\n        $filepath $validation_args\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            timeout 30 curl -fsSL $url -o $filepath\n            chmod +x $filepath\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    for i in $(seq 1 $retries); do\n        if [ -f $filepath ]; then\n            break\n        fi\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        dpkg --configure -a\n        apt-get -f -y install\n        apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        dpkg --configure -a\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}", "num_lines": 180}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Mounting is done here instead of etcd because of bug https://bugs.launchpad.net/cloud-init/+bug/1692093\n# Once the bug is fixed, replace the below with the cloud init changes replaced in https://github.com/Azure/acs-engine/pull/661.\nset -x\nDISK=/dev/sdc\nPARTITION=${DISK}1\nMOUNTPOINT=/var/lib/etcddisk\nudevadm settle\nmkdir -p $MOUNTPOINT\nmount | grep $MOUNTPOINT\nif [ $? -eq 0 ]\nthen\n    echo \"disk is already mounted\"\n    exit 0\nfi\ngrep \"/dev/sdc1\" /etc/fstab\nif [ $? -ne 0 ]\nthen\n    echo \"$PARTITION       $MOUNTPOINT       auto    defaults,nofail       0       2\" >> /etc/fstab\nfi\nls $PARTITION\nif [ $? -ne 0 ]\nthen\n    /sbin/sgdisk --new 1 $DISK\n    /sbin/mkfs.ext4 $PARTITION -L etcd_disk -F -E lazy_itable_init=1,lazy_journal_init=1\nfi\nmount $MOUNTPOINT\n/bin/chown -R etcd:etcd /var/lib/etcddisk", "num_lines": 28}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource /opt/azure/containers/provision_source.sh\n\nsudo echo \"  dns-search <searchDomainName>\" >> /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 restart networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"<searchDomainRealmPassword>\" | realm join -U <searchDomainRealmUser>@`echo \"<searchDomainName>\" | tr /a-z/ /A-Z/` `echo \"<searchDomainName>\" | tr /a-z/ /A-Z/`", "num_lines": 10}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: /etc/dnsmasq.d/origin-upstream-dns.conf is currently hardcoded; it\n# probably shouldn't be\n\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n\tSERVICE_TYPE=atomic-openshift\nelse\n\tSERVICE_TYPE=origin\nfi\nVERSION=\"$(rpm -q $SERVICE_TYPE --queryformat %{VERSION})\"\n\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n\tANSIBLE_DEPLOY_TYPE=\"openshift-enterprise\"\n\tIMAGE_TYPE=ose\n\tIMAGE_PREFIX=\"registry.access.redhat.com/openshift3\"\n\tANSIBLE_CONTAINER_VERSION=\"v${VERSION}\"\n\tPROMETHEUS_EXPORTER_VERSION=\"v${VERSION}\"\n\tCOCKPIT_PREFIX=\"${IMAGE_PREFIX}\"\n\tCOCKPIT_BASENAME=\"registry-console\"\n\tCOCKPIT_VERSION=\"v${VERSION}\"\nelse\n\tANSIBLE_DEPLOY_TYPE=\"origin\"\n\tIMAGE_TYPE=\"${SERVICE_TYPE}\"\n\tIMAGE_PREFIX=\"openshift\"\n\t# FIXME: These versions are set to deal with differences in how Origin and OCP\n\t#        components are versioned\n\tANSIBLE_CONTAINER_VERSION=\"v${VERSION%.*}\"\n\tCOCKPIT_PREFIX=\"cockpit\"\n\tCOCKPIT_BASENAME=\"kubernetes\"\n\tCOCKPIT_VERSION=\"latest\"\nfi\n\necho \"BOOTSTRAP_CONFIG_NAME=node-config-master\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n\nfor dst in tcp,2379 tcp,2380 tcp,8443 tcp,8444 tcp,8053 udp,8053 tcp,9090; do\n\tproto=${dst%%,*}\n\tport=${dst##*,}\n\tiptables -A OS_FIREWALL_ALLOW -p $proto -m state --state NEW -m $proto --dport $port -j ACCEPT\ndone\n\niptables-save >/etc/sysconfig/iptables\n\nsed -i -e \"s#--master=.*#--master=https://$(hostname --fqdn):8443#\" /etc/sysconfig/${SERVICE_TYPE}-master-api\nsed -i -e \"s#--loglevel=2#--loglevel=4#\" /etc/sysconfig/${SERVICE_TYPE}-master-api\nsed -i -e \"s#--loglevel=2#--loglevel=4#\" /etc/sysconfig/${SERVICE_TYPE}-master-controllers\n\nrm -rf /etc/etcd/* /etc/origin/master/* /etc/origin/node/*\n\nMASTER_OREG_URL=\"$IMAGE_PREFIX/$IMAGE_TYPE-\\${component}:\\${version}\"\nif [[ -f /etc/origin/oreg_url ]]; then\n\tMASTER_OREG_URL=$(cat /etc/origin/oreg_url)\nfi\n\noc adm create-bootstrap-policy-file --filename=/etc/origin/master/policy.json\n\n( cd / && base64 -d <<< {{ .ConfigBundle | shellQuote }} | tar -xz)\n\ncp /etc/origin/node/ca.crt /etc/pki/ca-trust/source/anchors/openshift-ca.crt\nupdate-ca-trust\n\n# FIXME: It is horrible that we're installing az.  Try to avoid adding\n# additional functionality in this script that requires it.  One route to remove\n# this code is to bake this script into the base image, then pass in parameters\n# such as the registry storage account name and key direct from ARM.\nrpm -i https://packages.microsoft.com/yumrepos/azure-cli/azure-cli-2.0.31-1.el7.x86_64.rpm\n\nset +x\n. <(sed -e 's/: */=/' /etc/azure/azure.conf)\naz login --service-principal -u \"$aadClientId\" -p \"$aadClientSecret\" --tenant \"$aadTenantId\" &>/dev/null\nREGISTRY_STORAGE_AZURE_ACCOUNTNAME=$(az storage account list -g \"$resourceGroup\" --query \"[?ends_with(name, 'registry')].name\" -o tsv)\nREGISTRY_STORAGE_AZURE_ACCOUNTKEY=$(az storage account keys list -g \"$resourceGroup\" -n \"$REGISTRY_STORAGE_AZURE_ACCOUNTNAME\" --query \"[?keyName == 'key1'].value\" -o tsv)\naz logout\nset -x\n\n###\n# retrieve the public ip via dns for the router public ip and sub it in for the routingConfig.subdomain\n###\nrouterLBHost={{ .RouterLBHostname | shellQuote }}\nrouterLBIP=$(dig +short $routerLBHost)\n\n# NOTE: The version of openshift-ansible for origin defaults the ansible var\n#       openshift_prometheus_node_exporter_image_version correctly as needed by\n#       origin, but for OCP it does not.\n#\n#       This is fixed in openshift/openshift-ansible@c27a0f4, which is in\n#       openshift-ansible >= 3.9.15, so once we're shipping OCP >= v3.9.15 we\n#       can remove this and the definition of the cooresonding variable in the\n#       ansible inventory file.\nif [[ \"${ANSIBLE_DEPLOY_TYPE}\" == \"origin\" ]]; then\n    sed -i \"/PROMETHEUS_EXPORTER_VERSION/d\" /tmp/ansible/azure-local-master-inventory.yml\nelse\n    sed -i \"s|PROMETHEUS_EXPORTER_VERSION|${PROMETHEUS_EXPORTER_VERSION}|g;\" /tmp/ansible/azure-local-master-inventory.yml\nfi\n\nfor i in /etc/origin/master/master-config.yaml /tmp/bootstrapconfigs/* /tmp/ansible/azure-local-master-inventory.yml; do\n    sed -i \"s/TEMPROUTERIP/${routerLBIP}/; s|IMAGE_PREFIX|$IMAGE_PREFIX|g; s|ANSIBLE_DEPLOY_TYPE|$ANSIBLE_DEPLOY_TYPE|g\" $i\n    sed -i \"s|REGISTRY_STORAGE_AZURE_ACCOUNTNAME|${REGISTRY_STORAGE_AZURE_ACCOUNTNAME}|g; s|REGISTRY_STORAGE_AZURE_ACCOUNTKEY|${REGISTRY_STORAGE_AZURE_ACCOUNTKEY}|g\" $i\n    sed -i \"s|COCKPIT_VERSION|${COCKPIT_VERSION}|g; s|COCKPIT_BASENAME|${COCKPIT_BASENAME}|g; s|COCKPIT_PREFIX|${COCKPIT_PREFIX}|g;\" $i\n    sed -i \"s|VERSION|${VERSION}|g; s|SHORT_VER|${VERSION%.*}|g; s|SERVICE_TYPE|${SERVICE_TYPE}|g; s|IMAGE_TYPE|${IMAGE_TYPE}|g\" $i\n    sed -i \"s|HOSTNAME|${HOSTNAME}|g;\" $i\n    sed -i \"s|MASTER_OREG_URL|${MASTER_OREG_URL}|g\" $i\ndone\n\n# note: ${SERVICE_TYPE}-node crash loops until master is up\nfor unit in etcd.service ${SERVICE_TYPE}-master-api.service ${SERVICE_TYPE}-master-controllers.service; do\n\tsystemctl enable $unit\n\tsystemctl start $unit\ndone\n\nmkdir -p /root/.kube\ncp /etc/origin/master/admin.kubeconfig /root/.kube/config\n\nexport KUBECONFIG=/etc/origin/master/admin.kubeconfig\n\nwhile ! curl -o /dev/null -m 2 -kfs https://localhost:8443/healthz; do\n\tsleep 1\ndone\n\nwhile ! oc get svc kubernetes &>/dev/null; do\n\tsleep 1\ndone\n\noc create -f - <<'EOF'\nkind: StorageClass\napiVersion: storage.k8s.io/v1beta1\nmetadata:\n  name: azure\n  annotations:\n    storageclass.kubernetes.io/is-default-class: \"true\"\nprovisioner: kubernetes.io/azure-disk\nparameters:\n  skuName: Premium_LRS\n  location: {{ .Location | quote }}\n  kind: managed\nEOF\n\noc create configmap node-config-master --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/master-config.yaml\noc create configmap node-config-compute --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/compute-config.yaml\noc create configmap node-config-infra --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/infra-config.yaml\n\n# must start ${SERVICE_TYPE}-node after master is fully up and running\n# otherwise the implicit dns change may cause master startup to fail\nsystemctl enable ${SERVICE_TYPE}-node.service\nsystemctl start ${SERVICE_TYPE}-node.service &\n\nchmod +x /tmp/ansible/ansible.sh\n\ndocker run \\\n\t--rm \\\n\t-u \"$(id -u)\" \\\n\t-v /etc/origin:/etc/origin:z \\\n\t-v /tmp/ansible:/opt/app-root/src:z \\\n\t-v /root/.kube:/opt/app-root/src/.kube:z \\\n\t-w /opt/app-root/src \\\n\t-e IMAGE_BASE=\"${IMAGE_PREFIX}/${IMAGE_TYPE}\" \\\n\t-e VERSION=\"$VERSION\" \\\n\t-e HOSTNAME=\"$(hostname)\" \\\n\t--network=\"host\" \\\n\t\"${IMAGE_PREFIX}/${IMAGE_TYPE}-ansible:${ANSIBLE_CONTAINER_VERSION}\" \\\n\t/opt/app-root/src/ansible.sh\n", "num_lines": 162}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: /etc/dnsmasq.d/origin-upstream-dns.conf is currently hardcoded; it\n# probably shouldn't be\nSERVICE_TYPE=origin\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n    SERVICE_TYPE=atomic-openshift\nfi\n\n{{if eq .Role \"infra\"}}\necho \"BOOTSTRAP_CONFIG_NAME=node-config-infra\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n{{else}}\necho \"BOOTSTRAP_CONFIG_NAME=node-config-compute\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n{{end}}\n\nsed -i -e \"s#--loglevel=2#--loglevel=4#\" /etc/sysconfig/${SERVICE_TYPE}-node\n\nrm -rf /etc/etcd/* /etc/origin/master/* /etc/origin/node/*\n\n( cd / && base64 -d <<< {{ .ConfigBundle | shellQuote }} | tar -xz)\n\ncp /etc/origin/node/ca.crt /etc/pki/ca-trust/source/anchors/openshift-ca.crt\nupdate-ca-trust\n\n# note: ${SERVICE_TYPE}-node crash loops until master is up\nsystemctl enable ${SERVICE_TYPE}-node.service\nsystemctl start ${SERVICE_TYPE}-node.service &\n\nwhile [[ $(KUBECONFIG=/etc/origin/node/node.kubeconfig oc get node $(hostname) -o template \\\n    --template '{{`{{range .status.conditions}}{{if eq .type \"Ready\"}}{{.status}}{{end}}{{end}}`}}') != True ]]; do\n    sleep 1\ndone\n", "num_lines": 33}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: /etc/dnsmasq.d/origin-upstream-dns.conf is currently hardcoded; it\n# probably shouldn't be\n\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n\tSERVICE_TYPE=atomic-openshift\nelse\n\tSERVICE_TYPE=origin\nfi\nVERSION=\"$(rpm -q $SERVICE_TYPE --queryformat %{VERSION})\"\nIP_ADDRESS=\"{{ .MasterIP }}\"\n\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n\tANSIBLE_DEPLOY_TYPE=\"openshift-enterprise\"\n\tIMAGE_TYPE=ose\n\tIMAGE_PREFIX=\"registry.access.redhat.com/openshift3\"\n\tANSIBLE_CONTAINER_VERSION=\"v${VERSION}\"\n\tPROMETHEUS_EXPORTER_VERSION=\"v${VERSION}\"\n\tCOCKPIT_PREFIX=\"${IMAGE_PREFIX}\"\n\tCOCKPIT_BASENAME=\"registry-console\"\n\tCOCKPIT_VERSION=\"v${VERSION}\"\nelse\n\tANSIBLE_DEPLOY_TYPE=\"origin\"\n\tIMAGE_TYPE=\"${SERVICE_TYPE}\"\n\tIMAGE_PREFIX=\"openshift\"\n\t# FIXME: These versions are set to deal with differences in how Origin and OCP\n\t#        components are versioned\n\tANSIBLE_CONTAINER_VERSION=\"v${VERSION%.*}\"\n\tCOCKPIT_PREFIX=\"cockpit\"\n\tCOCKPIT_BASENAME=\"kubernetes\"\n\tCOCKPIT_VERSION=\"latest\"\nfi\n\nif grep -q ^ResourceDisk.Filesystem=xfs /etc/waagent.conf; then\n\t# Bad image: docker and waagent are racing.  Try to fix up.  Leave this code\n\t# until the bad images have gone away.\n\tset +e\n\n\t# stop docker if it hasn't failed already\n\tsystemctl stop docker.service\n\n\t# wait until waagent has run mkfs and mounted /var/lib/docker\n\twhile ! mountpoint -q /var/lib/docker; do\n\t\tsleep 1\n\tdone\n\n\t# now roll us back. /var/lib/docker/* may be mounted if docker lost the\n\t# race.\n\tumount /var/lib/docker\n\tumount /var/lib/docker/*\n\n\t# disable waagent from racing again if we reboot.\n\tsed -i -e '/^ResourceDisk.Format=/ s/=.*/=n/' /etc/waagent.conf\n\tset -e\nfi\n\nsystemctl stop docker.service\n# Also a bad image: the umount should also go away.\numount /var/lib/docker || true\nmkfs.xfs -f /dev/sdb1\necho '/dev/sdb1  /var/lib/docker  xfs  grpquota  0 0' >>/etc/fstab\nmount /var/lib/docker\nrestorecon -R /var/lib/docker\nsystemctl start docker.service\n\necho \"BOOTSTRAP_CONFIG_NAME=node-config-master\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n\nfor dst in tcp,2379 tcp,2380 tcp,8443 tcp,8444 tcp,8053 udp,8053 tcp,9090; do\n\tproto=${dst%%,*}\n\tport=${dst##*,}\n\tiptables -A OS_FIREWALL_ALLOW -p $proto -m state --state NEW -m $proto --dport $port -j ACCEPT\ndone\n\niptables-save >/etc/sysconfig/iptables\n\nrm -rf /etc/etcd/* /etc/origin/master/*\n\nmkdir -p /etc/origin/master\n\noc adm create-bootstrap-policy-file --filename=/etc/origin/master/policy.json\n\n( cd / && base64 -d <<< {{ .ConfigBundle | shellQuote }} | tar -xz)\n\ncp /etc/origin/node/ca.crt /etc/pki/ca-trust/source/anchors/openshift-ca.crt\nupdate-ca-trust\n\n# FIXME: It is horrible that we're installing az.  Try to avoid adding\n# additional functionality in this script that requires it.  One route to remove\n# this code is to bake this script into the base image, then pass in parameters\n# such as the registry storage account name and key direct from ARM.\nrpm -i https://packages.microsoft.com/yumrepos/azure-cli/azure-cli-2.0.31-1.el7.x86_64.rpm\n\nset +x\n. <(sed -e 's/: */=/' /etc/origin/cloudprovider/azure.conf)\naz login --service-principal -u \"$aadClientId\" -p \"$aadClientSecret\" --tenant \"$aadTenantId\" &>/dev/null\nREGISTRY_STORAGE_AZURE_ACCOUNTNAME=$(az storage account list -g \"$resourceGroup\" --query \"[?ends_with(name, 'registry')].name\" -o tsv)\nREGISTRY_STORAGE_AZURE_ACCOUNTKEY=$(az storage account keys list -g \"$resourceGroup\" -n \"$REGISTRY_STORAGE_AZURE_ACCOUNTNAME\" --query \"[?keyName == 'key1'].value\" -o tsv)\naz logout\nset -x\n\n###\n# retrieve the public ip via dns for the router public ip and sub it in for the routingConfig.subdomain\n###\nrouterLBHost={{ .RouterLBHostname | shellQuote }}\nrouterLBIP=$(dig +short $routerLBHost)\n\n# NOTE: The version of openshift-ansible for origin defaults the ansible var\n#       openshift_prometheus_node_exporter_image_version correctly as needed by\n#       origin, but for OCP it does not.\n#\n#       This is fixed in openshift/openshift-ansible@c27a0f4, which is in\n#       openshift-ansible >= 3.9.15, so once we're shipping OCP >= v3.9.15 we\n#       can remove this and the definition of the cooresonding variable in the\n#       ansible inventory file.\nif [[ \"${ANSIBLE_DEPLOY_TYPE}\" == \"origin\" ]]; then\n    sed -i \"/PROMETHEUS_EXPORTER_VERSION/d\" /tmp/ansible/azure-local-master-inventory.yml\nelse\n    sed -i \"s|PROMETHEUS_EXPORTER_VERSION|${PROMETHEUS_EXPORTER_VERSION}|g;\" /tmp/ansible/azure-local-master-inventory.yml\nfi\n\nMASTER_OREG_URL=\"$IMAGE_PREFIX/$IMAGE_TYPE-\\${component}:\\${version}\"\nif [[ -f /etc/origin/oreg_url ]]; then\n\tMASTER_OREG_URL=$(cat /etc/origin/oreg_url)\nfi\n\nfor i in /etc/origin/master/master-config.yaml /tmp/bootstrapconfigs/* /tmp/ansible/azure-local-master-inventory.yml; do\n    sed -i \"s/TEMPROUTERIP/${routerLBIP}/; s|IMAGE_PREFIX|$IMAGE_PREFIX|g; s|ANSIBLE_DEPLOY_TYPE|$ANSIBLE_DEPLOY_TYPE|g\" $i\n    sed -i \"s|REGISTRY_STORAGE_AZURE_ACCOUNTNAME|${REGISTRY_STORAGE_AZURE_ACCOUNTNAME}|g; s|REGISTRY_STORAGE_AZURE_ACCOUNTKEY|${REGISTRY_STORAGE_AZURE_ACCOUNTKEY}|g\" $i\n    sed -i \"s|COCKPIT_VERSION|${COCKPIT_VERSION}|g; s|COCKPIT_BASENAME|${COCKPIT_BASENAME}|g; s|COCKPIT_PREFIX|${COCKPIT_PREFIX}|g;\" $i\n    sed -i \"s|VERSION|${VERSION}|g; s|SHORT_VER|${VERSION%.*}|g; s|SERVICE_TYPE|${SERVICE_TYPE}|g; s|IMAGE_TYPE|${IMAGE_TYPE}|g\" $i\n    sed -i \"s|HOSTNAME|${HOSTNAME}|g;\" $i\n    sed -i \"s|MASTER_OREG_URL|${MASTER_OREG_URL}|g\" $i\ndone\n\nmkdir -p /root/.kube\n\nfor loc in /root/.kube/config /etc/origin/node/bootstrap.kubeconfig /etc/origin/node/node.kubeconfig; do\n  cp /etc/origin/master/admin.kubeconfig \"$loc\"\ndone\n\n\n# Patch the etcd_ip address placed inside of the static pod definition from the node install\nsed -i \"s/ETCD_IP_REPLACE/${IP_ADDRESS}/g\" /etc/origin/node/disabled/etcd.yaml\n\nexport KUBECONFIG=/etc/origin/master/admin.kubeconfig\n\n# Move each static pod into place so the kubelet will run it.\n# Pods: [apiserver, controller, etcd]\noc set env --local -f /etc/origin/node/disabled/apiserver.yaml DEBUG_LOGLEVEL=4 -o yaml --dry-run > /etc/origin/node/pods/apiserver.yaml\noc set env --local -f /etc/origin/node/disabled/controller.yaml DEBUG_LOGLEVEL=4 -o yaml --dry-run > /etc/origin/node/pods/controller.yaml\nmv /etc/origin/node/disabled/etcd.yaml /etc/origin/node/pods/etcd.yaml\nrm -rf /etc/origin/node/disabled\n\nsystemctl start ${SERVICE_TYPE}-node\n\nwhile ! curl -o /dev/null -m 2 -kfs https://localhost:8443/healthz; do\n\tsleep 1\ndone\n\nwhile ! oc get svc kubernetes &>/dev/null; do\n\tsleep 1\ndone\n\noc create -f - <<'EOF'\nkind: StorageClass\napiVersion: storage.k8s.io/v1beta1\nmetadata:\n  name: azure\n  annotations:\n    storageclass.kubernetes.io/is-default-class: \"true\"\nprovisioner: kubernetes.io/azure-disk\nparameters:\n  skuName: Premium_LRS\n  location: {{ .Location | quote }}\n  kind: managed\nEOF\n\noc create configmap node-config-master --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/master-config.yaml\noc create configmap node-config-compute --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/compute-config.yaml\noc create configmap node-config-infra --namespace openshift-node --from-file=node-config.yaml=/tmp/bootstrapconfigs/infra-config.yaml\n\nchmod +x /tmp/ansible/ansible.sh\n\ndocker run \\\n\t--rm \\\n\t-u \"$(id -u)\" \\\n\t-v /etc/origin:/etc/origin:z \\\n\t-v /tmp/ansible:/opt/app-root/src:z \\\n\t-v /root/.kube:/opt/app-root/src/.kube:z \\\n\t-w /opt/app-root/src \\\n\t-e IMAGE_BASE=\"${IMAGE_PREFIX}/${IMAGE_TYPE}\" \\\n\t-e VERSION=\"$VERSION\" \\\n\t-e HOSTNAME=\"$(hostname)\" \\\n\t--network=\"host\" \\\n\t\"${IMAGE_PREFIX}/${IMAGE_TYPE}-ansible:${ANSIBLE_CONTAINER_VERSION}\" \\\n\t/opt/app-root/src/ansible.sh\n", "num_lines": 198}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: /etc/dnsmasq.d/origin-upstream-dns.conf is currently hardcoded; it\n# probably shouldn't be\nSERVICE_TYPE=origin\nif [ -f \"/etc/sysconfig/atomic-openshift-node\" ]; then\n    SERVICE_TYPE=atomic-openshift\nfi\n\nif grep -q ^ResourceDisk.Filesystem=xfs /etc/waagent.conf; then\n\t# Bad image: docker and waagent are racing.  Try to fix up.  Leave this code\n\t# until the bad images have gone away.\n\tset +e\n\n\t# stop docker if it hasn't failed already\n\tsystemctl stop docker.service\n\n\t# wait until waagent has run mkfs and mounted /var/lib/docker\n\twhile ! mountpoint -q /var/lib/docker; do\n\t\tsleep 1\n\tdone\n\n\t# now roll us back. /var/lib/docker/* may be mounted if docker lost the\n\t# race.\n\tumount /var/lib/docker\n\tumount /var/lib/docker/*\n\n\t# disable waagent from racing again if we reboot.\n\tsed -i -e '/^ResourceDisk.Format=/ s/=.*/=n/' /etc/waagent.conf\n\tset -e\nfi\n\nsystemctl stop docker.service\n# Also a bad image: the umount should also go away.\numount /var/lib/docker || true\nmkfs.xfs -f /dev/sdb1\necho '/dev/sdb1  /var/lib/docker  xfs  grpquota  0 0' >>/etc/fstab\nmount /var/lib/docker\nrestorecon -R /var/lib/docker\nsystemctl start docker.service\n\n{{if eq .Role \"infra\"}}\necho \"BOOTSTRAP_CONFIG_NAME=node-config-infra\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n{{else}}\necho \"BOOTSTRAP_CONFIG_NAME=node-config-compute\" >>/etc/sysconfig/${SERVICE_TYPE}-node\n{{end}}\n\nsed -i -e \"s#DEBUG_LOGLEVEL=2#DEBUG_LOGLEVEL=4#\" /etc/sysconfig/${SERVICE_TYPE}-node\n\nrm -rf /etc/etcd/* /etc/origin/master/*\n\n( cd / && base64 -d <<< {{ .ConfigBundle | shellQuote }} | tar -xz)\n\ncp /etc/origin/node/ca.crt /etc/pki/ca-trust/source/anchors/openshift-ca.crt\nupdate-ca-trust\n\n# note: ${SERVICE_TYPE}-node crash loops until master is up\nsystemctl enable ${SERVICE_TYPE}-node.service\nsystemctl start ${SERVICE_TYPE}-node.service &\n\nwhile [[ $(KUBECONFIG=/etc/origin/node/node.kubeconfig oc get node $(hostname) -o template \\\n    --template '{{`{{range .status.conditions}}{{if eq .type \"Ready\"}}{{.status}}{{end}}{{end}}`}}') != True ]]; do\n    sleep 1\ndone\n", "num_lines": 65}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\necho \"starting swarm cluster configuration\"\ndate\nps ax\n\n#############\n# Parameters\n#############\n\nSWARM_VERSION=${1}\nDOCKER_COMPOSE_VERSION=${2}\nMASTERCOUNT=${3}\nMASTERPREFIX=${4}\nMASTERFIRSTADDR=${5}\nAZUREUSER=${6}\nPOSTINSTALLSCRIPTURI=${7}\nBASESUBNET=${8}\nDOCKERENGINEDOWNLOADREPO=${9}\nDOCKERCOMPOSEDOWNLOADURL=${10}\nDOCKER_CE_VERSION=17.03.*\nVMNAME=`hostname`\nVMNUMBER=`echo $VMNAME | sed 's/.*[^0-9]\\([0-9]\\+\\)*$/\\1/'`\nVMPREFIX=`echo $VMNAME | sed 's/\\(.*[^0-9]\\)*[0-9]\\+$/\\1/'`\n\necho \"Master Count: $MASTERCOUNT\"\necho \"Master Prefix: $MASTERPREFIX\"\necho \"Master First Addr: $MASTERFIRSTADDR\"\necho \"vmname: $VMNAME\"\necho \"VMNUMBER: $VMNUMBER, VMPREFIX: $VMPREFIX\"\necho \"BASESUBNET: $BASESUBNET\"\necho \"AZUREUSER: $AZUREUSER\"\n\n###################\n# Common Functions\n###################\n\nensureAzureNetwork()\n{\n  # ensure the network works\n  networkHealthy=1\n  for i in {1..12}; do\n    wget -O/dev/null http://bing.com\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 10\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, aborting install\"\n    ifconfig\n    ip a\n    exit 1\n  fi\n  # ensure the host ip can resolve\n  networkHealthy=1\n  for i in {1..120}; do\n    hostname -i\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 1\n  done\n  # attempt to fix hostname, in case dns is not resolving Azure IPs (but can resolve public ips)\n  if [ $networkHealthy -ne 0 ]\n  then\n    HOSTNAME=`hostname`\n    HOSTADDR=`ip address show dev eth0 | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*'`\n    echo $HOSTADDR $HOSTNAME >> /etc/hosts\n    hostname -i\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy by updating /etc/hosts\"\n    fi\n  fi\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, cannot resolve ip address, aborting install\"\n    ifconfig\n    ip a\n    exit 2\n  fi\n}\nensureAzureNetwork\nHOSTADDR=`hostname -i`\n\n# apply all Canonical security updates during provisioning\n/usr/lib/apt/apt.systemd.daily\n\nismaster ()\n{\n  if [ \"$MASTERPREFIX\" == \"$VMPREFIX\" ]\n  then\n    return 0\n  else\n    return 1\n  fi\n}\nif ismaster ; then\n  echo \"this node is a master\"\nfi\n\nisagent()\n{\n  if ismaster ; then\n    return 1\n  else\n    return 0\n  fi\n}\nif isagent ; then\n  echo \"this node is an agent\"\nfi\n\nconsulstr()\n{\n  consulargs=\"\"\n  for i in `seq 0 $((MASTERCOUNT-1))` ;\n  do\n    MASTEROCTET=`expr $MASTERFIRSTADDR + $i`\n    IPADDR=\"${BASESUBNET}${MASTEROCTET}\"\n\n    if [ \"$VMNUMBER\" -eq \"0\" ]\n    then\n      consulargs=\"${consulargs}-bootstrap-expect $MASTERCOUNT \"\n    fi\n    if [ \"$VMNUMBER\" -eq \"$i\" ]\n    then\n      consulargs=\"${consulargs}-advertise $IPADDR \"\n    else\n      consulargs=\"${consulargs}-retry-join $IPADDR \"\n    fi\n  done\n  echo $consulargs\n}\n\nconsulargs=$(consulstr)\nMASTER0IPADDR=\"${BASESUBNET}${MASTERFIRSTADDR}\"\n\n######################\n# resolve self in DNS\n######################\n\necho \"$HOSTADDR $VMNAME\" | sudo tee -a /etc/hosts\n\n################\n# Install Docker\n################\n\necho \"Installing and configuring docker\"\n\n# simple general command retry function\nretrycmd_if_failure() { for i in 1 2 3 4 5; do $@; [ $? -eq 0  ] && break || sleep 5; done ; }\n\ninstallDocker()\n{\n  for i in {1..10}; do\n    apt-get install -y apt-transport-https ca-certificates curl software-properties-common\n    curl --max-time 60 -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - \n    add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\n    apt-get update\n    apt-get install -y docker-ce=${DOCKER_CE_VERSION}\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      echo \"Docker installed successfully\"\n      break\n    fi\n    sleep 10\n  done\n}\ntime installDocker\nsudo usermod -aG docker $AZUREUSER\nif isagent ; then\n  # Start Docker and listen on :2375 (no auth, but in vnet)\n  echo 'DOCKER_OPTS=\"-H unix:///var/run/docker.sock -H 0.0.0.0:2375 --cluster-store=consul://'$MASTER0IPADDR:8500 --cluster-advertise=$HOSTADDR:2375'\"' | sudo tee -a /etc/default/docker\nfi\n\necho \"Installing docker compose\"\ninstallDockerCompose()\n{\n  for i in {1..10}; do\n    wget --tries 4 --retry-connrefused --waitretry=15 -qO- $DOCKERCOMPOSEDOWNLOADURL/$DOCKER_COMPOSE_VERSION/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      echo \"docker-compose installed successfully\"\n      break\n    fi\n    sleep 10\n  done\n}\ntime installDockerCompose\nchmod +x /usr/local/bin/docker-compose\n\nsudo service docker restart\n\nensureDocker()\n{\n  # ensure that docker is healthy\n  dockerHealthy=1\n  for i in {1..3}; do\n    sudo docker info\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      dockerHealthy=0\n      echo \"Docker is healthy\"\n      sudo docker ps -a\n      break\n    fi\n    sleep 10\n  done\n  if [ $dockerHealthy -ne 0 ]\n  then\n    echo \"Docker is not healthy\"\n  fi\n}\nensureDocker\n\n##############################################\n# configure init rules restart all processes\n##############################################\n\nif ismaster ; then\n  mkdir -p /data/consul\n  echo \"consul:\n  image: \\\"progrium/consul\\\"\n  command: -server -node $VMNAME $consulargs\n  ports:\n    - \\\"8500:8500\\\"\n    - \\\"8300:8300\\\"\n    - \\\"8301:8301\\\"\n    - \\\"8301:8301/udp\\\"\n    - \\\"8302:8302\\\"\n    - \\\"8302:8302/udp\\\"\n    - \\\"8400:8400\\\"\n  volumes:\n    - \\\"/data/consul:/data\\\"\n  restart: \\\"always\\\"\nswarm:\n  image: \\\"$SWARM_VERSION\\\"\n  command: manage --replication --advertise $HOSTADDR:2375 --discovery-opt kv.path=docker/nodes consul://$MASTER0IPADDR:8500\n  ports:\n    - \\\"2375:2375\\\"\n  links:\n    - \\\"consul\\\"\n  volumes:\n    - \\\"/etc/docker:/etc/docker\\\"\n  restart: \\\"always\\\"\n\" > /opt/azure/containers/docker-compose.yml\n\n  pushd /opt/azure/containers/\n  docker-compose up -d\n  popd\n  echo \"completed starting docker swarm on the master\"\nfi\n\nif ismaster ; then\n  echo \"Having ssh listen to port 2222 as well as 22\"\n  sudo sed  -i \"s/^Port 22$/Port 22\\nPort 2222/1\" /etc/ssh/sshd_config\nfi\n\nif [ $POSTINSTALLSCRIPTURI != \"disabled\" ]\nthen\n  echo \"downloading, and kicking off post install script\"\n  /bin/bash -c \"wget --tries 20 --retry-connrefused --waitretry=15 -qO- $POSTINSTALLSCRIPTURI | nohup /bin/bash >> /var/log/azure/cluster-bootstrap-postinstall.log 2>&1 &\"\nfi\n\necho \"processes at end of script\"\nps ax\ndate\necho \"completed Swarm cluster configuration\"\n\necho \"restart system to install any remaining software\"\nif isagent ; then\n  shutdown -r now\nelse\n  # wait 1 minute to restart master\n  /bin/bash -c \"shutdown -r 1 &\"\nfi\n", "num_lines": 295}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n###########################################################\n# Configure Swarm Mode One Box\n#\n# This installs the following components\n# - Docker\n# - Docker Compose\n# - Swarm Mode masters\n# - Swarm Mode agents\n###########################################################\n\nset -x\n\necho \"starting Swarm Mode cluster configuration\"\ndate\nps ax\n\n#############\n# Parameters\n#############\n\nDOCKER_CE_VERSION=${1}\nDOCKER_COMPOSE_VERSION=${2}\nMASTERCOUNT=${3}\nMASTERPREFIX=${4}\nMASTERFIRSTADDR=${5}\nAZUREUSER=${6}\nPOSTINSTALLSCRIPTURI=${7}\nBASESUBNET=${8}\nDOCKERENGINEDOWNLOADREPO=${9}\nDOCKERCOMPOSEDOWNLOADURL=${10}\nVMNAME=`hostname`\nVMNUMBER=`echo $VMNAME | sed 's/.*[^0-9]\\([0-9]\\+\\)*$/\\1/'`\nVMPREFIX=`echo $VMNAME | sed 's/\\(.*[^0-9]\\)*[0-9]\\+$/\\1/'`\nOS=\"$(. /etc/os-release; echo $ID)\"\n\necho \"Master Count: $MASTERCOUNT\"\necho \"Master Prefix: $MASTERPREFIX\"\necho \"Master First Addr: $MASTERFIRSTADDR\"\necho \"vmname: $VMNAME\"\necho \"VMNUMBER: $VMNUMBER, VMPREFIX: $VMPREFIX\"\necho \"BASESUBNET: $BASESUBNET\"\necho \"AZUREUSER: $AZUREUSER\"\necho \"OS ID: $OS\"\n\n###################\n# Common Functions\n###################\n\nisUbuntu()\n{\n  if [ \"$OS\" == \"ubuntu\" ]\n  then\n    return 0\n  else\n    return 1\n  fi\n}\n\nisRHEL()\n{\n  if [ \"$OS\" == \"rhel\" ]\n  then\n    return 0\n  else\n    return 1\n  fi\n}\n\nensureAzureNetwork()\n{\n  # ensure the network works\n  networkHealthy=1\n  for i in {1..12}; do\n    wget -O/dev/null http://bing.com\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 10\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, aborting install\"\n    ifconfig\n    ip a\n    exit 1\n  fi\n  # ensure the host ip can resolve\n  networkHealthy=1\n  for i in {1..120}; do\n    hostname -i\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 1\n  done\n  # attempt to fix hostname, in case dns is not resolving Azure IPs (but can resolve public ips)\n  if [ $networkHealthy -ne 0 ]\n  then\n    HOSTNAME=`hostname`\n    HOSTADDR=`ip address show dev eth0 | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*'`\n    echo $HOSTADDR $HOSTNAME >> /etc/hosts\n    hostname -i\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy by updating /etc/hosts\"\n    fi\n  fi\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, cannot resolve ip address, aborting install\"\n    ifconfig\n    ip a\n    exit 2\n  fi\n}\nensureAzureNetwork\nHOSTADDR=`hostname -i`\n\n# apply all Canonical security updates during provisioning\n/usr/lib/apt/apt.systemd.daily\n\nismaster ()\n{\n  if [ \"$MASTERPREFIX\" == \"$VMPREFIX\" ]\n  then\n    return 0\n  else\n    return 1\n  fi\n}\nif ismaster ; then\n  echo \"this node is a master\"\nfi\n\nisagent()\n{\n  if ismaster ; then\n    return 1\n  else\n    return 0\n  fi\n}\nif isagent ; then\n  echo \"this node is an agent\"\nfi\n\nMASTER0IPADDR=\"${BASESUBNET}${MASTERFIRSTADDR}\"\n\n######################\n# resolve self in DNS\n######################\n\nif [ -z \"$(grep \"$HOSTADDR $VMNAME\" /etc/hosts)\" ]; then\n    echo \"$HOSTADDR $VMNAME\" | sudo tee -a /etc/hosts\nfi\n\n################\n# Install Docker\n################\n\necho \"Installing and configuring Docker\"\n\ninstallDockerUbuntu()\n{\n  for i in {1..10}; do\n    apt-get install -y apt-transport-https ca-certificates curl software-properties-common\n    curl --max-time 60 -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - \n    add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\n    apt-get update\n    apt-get install -y docker-ce=${DOCKER_CE_VERSION}\n    if [ $? -eq 0 ]\n    then\n      systemctl restart docker\n      # hostname has been found continue\n      echo \"Docker installed successfully\"\n      break\n    fi\n    sleep 10\n  done\n}\n\ninstallDockerRHEL()\n{\n  for i in {1..10}; do\n    yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo\n    yum makecache fast\n    yum -y install docker-ce\n    if [ $? -eq 0 ]\n    then\n      systemctl enable docker\n      systemctl start docker\n      echo \"Docker installed successfully\"\n      break\n    fi\n    sleep 10\n  done\n}\n\ninstallDocker()\n{\n  if isUbuntu ; then\n    installDockerUbuntu\n  elif isRHEL ; then\n    installDockerRHEL\n  else\n    echo \"OS not supported, aborting install\"\n    exit 5\n  fi\n}\n\ntime installDocker\n\nsudo usermod -aG docker $AZUREUSER\n\necho \"Updating Docker daemon options\"\n\nupdateDockerDaemonOptions()\n{\n    sudo mkdir -p /etc/systemd/system/docker.service.d\n    # Start Docker and listen on :2375 (no auth, but in vnet) and\n    # also have it bind to the unix socket at /var/run/docker.sock\n    sudo bash -c 'echo \"[Service]\n    ExecStart=\n    ExecStart=/usr/bin/dockerd -H tcp://0.0.0.0:2375 -H unix:///var/run/docker.sock\n  \" > /etc/systemd/system/docker.service.d/override.conf'\n}\ntime updateDockerDaemonOptions\n\necho \"Installing Docker Compose\"\ninstallDockerCompose()\n{\n  # sudo -i\n\n  for i in {1..10}; do\n    wget --tries 4 --retry-connrefused --waitretry=15 -qO- $DOCKERCOMPOSEDOWNLOADURL/$DOCKER_COMPOSE_VERSION/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      echo \"docker-compose installed successfully\"\n      break\n    fi\n    sleep 10\n  done\n}\ntime installDockerCompose\nchmod +x /usr/local/bin/docker-compose\n\nif ismaster && isRHEL ; then\n  echo \"Opening Docker ports\"\n  firewall-cmd --add-port=2375/tcp --permanent\n  firewall-cmd --add-port=2377/tcp --permanent\n  firewall-cmd --reload\nfi\n\necho \"Restarting Docker\"\nsudo systemctl daemon-reload\nsudo service docker restart\n\nensureDocker()\n{\n  # ensure that docker is healthy\n  dockerHealthy=1\n  for i in {1..3}; do\n    sudo docker info\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      dockerHealthy=0\n      echo \"Docker is healthy\"\n      sudo docker ps -a\n      break\n    fi\n    sleep 10\n  done\n  if [ $dockerHealthy -ne 0 ]\n  then\n    echo \"Docker is not healthy\"\n  fi\n}\nensureDocker\n\n##############################################\n# configure init rules restart all processes\n##############################################\n\nif ismaster ; then\n    if [ \"$HOSTADDR\" = \"$MASTER0IPADDR\" ]; then\n          echo \"Creating a new Swarm on first master\"\n          docker swarm init --advertise-addr $(hostname -i):2377 --listen-addr $(hostname -i):2377\n    else\n        echo \"Secondary master attempting to join an existing Swarm\"\n        swarmmodetoken=\"\"\n        swarmmodetokenAcquired=1\n        for i in {1..120}; do\n            swarmmodetoken=$(docker -H $MASTER0IPADDR:2375 swarm join-token -q manager)\n            if [ $? -eq 0 ]; then\n                swarmmodetokenAcquired=0\n                break\n            fi\n            sleep 5\n        done\n        if [ $swarmmodetokenAcquired -ne 0 ]\n        then\n            echo \"Secondary master couldn't connect to Swarm, aborting install\"\n            exit 3\n        fi\n        docker swarm join --token $swarmmodetoken $MASTER0IPADDR:2377\n    fi\nfi\n\nif ismaster ; then\n  echo \"Having ssh listen to port 2222 as well as 22\"\n  sudo sed  -i \"s/^Port 22$/Port 22\\nPort 2222/1\" /etc/ssh/sshd_config\nfi\n\nif ismaster ; then\n  echo \"Setting availability of master node: '$VMNAME' to pause\"\n  docker node update --availability pause $VMNAME\nfi\n\nif isagent ; then\n    echo \"Agent attempting to join an existing Swarm\"\n    swarmmodetoken=\"\"\n    swarmmodetokenAcquired=1\n    for i in {1..120}; do\n        swarmmodetoken=$(docker -H $MASTER0IPADDR:2375 swarm join-token -q worker)\n        if [ $? -eq 0 ]; then\n            swarmmodetokenAcquired=0\n            break\n        fi\n        sleep 5\n    done\n    if [ $swarmmodetokenAcquired -ne 0 ]\n    then\n        echo \"Agent couldn't join Swarm, aborting install\"\n        exit 4\n    fi\n    docker swarm join --token $swarmmodetoken $MASTER0IPADDR:2377\nfi\n\nif [ $POSTINSTALLSCRIPTURI != \"disabled\" ]\nthen\n  echo \"downloading, and kicking off post install script\"\n  /bin/bash -c \"wget --tries 20 --retry-connrefused --waitretry=15 -qO- $POSTINSTALLSCRIPTURI | nohup /bin/bash >> /var/log/azure/cluster-bootstrap-postinstall.log 2>&1 &\"\nfi\n\n# mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635\necho 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\nsed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n\necho \"processes at end of script\"\nps ax\ndate\necho \"completed Swarm Mode cluster configuration\"\n\necho \"restart system to install any remaining software\"\nif isagent ; then\n  shutdown -r now\nelse\n  # wait 1 minute to restart master\n  /bin/bash -c \"shutdown -r 1 &\"\nfi\n", "num_lines": 375}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nfor f in $(find . -name \"*.err\"); do\n        len=${#f}\n\tmv ${f} ${f::len-4};\ndone\n", "num_lines": 7}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: do this, and more (registry console, asb), the proper way\n\n# we get \"dial tcp: lookup foo.eastus.cloudapp.azure.com on 10.0.0.11:53: read\n# udp 172.17.0.2:56662->10.0.0.11:53: read: no route to host errors\" at\n# start-up: wait until these subside.\nwhile ! oc version &>/dev/null; do\n  sleep 1\ndone\n\nfor project in default openshift-infra; do\n  oc patch project $project -p '{\"metadata\":{\"annotations\":{\"openshift.io/node-selector\": \"\"}}}'\ndone\n\n# FIXME - This should be handled by the openshift-ansible playbooks to ensure\n#         a directory it needs to write to exists before attempting to write\n#         to it\nmkdir -p /etc/origin/master/named_certificates\n\n# Deploy all infra components reusing relevant parts from openshift-ansible\nANSIBLE_ROLES_PATH=/usr/share/ansible/openshift-ansible/roles/ \\\n  ansible-playbook\\\n  -M /usr/share/ansible/openshift-ansible/roles/lib_utils/library \\\n  -c local azure-ocp-deploy.yml \\\n  -i azure-local-master-inventory.yml\n\n# TODO: possibly wait here for convergence?\n", "num_lines": 29}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# TODO: do this, and more (registry console, asb), the proper way\n\n# we get \"dial tcp: lookup foo.eastus.cloudapp.azure.com on 10.0.0.11:53: read\n# udp 172.17.0.2:56662->10.0.0.11:53: read: no route to host errors\" at\n# start-up: wait until these subside.\nwhile ! oc version &>/dev/null; do\n  sleep 1\ndone\n\nfor project in default openshift-infra; do\n  oc patch project $project -p '{\"metadata\":{\"annotations\":{\"openshift.io/node-selector\": \"\"}}}'\ndone\n\n# FIXME - This should be handled by the openshift-ansible playbooks to ensure\n#         a directory it needs to write to exists before attempting to write\n#         to it\nmkdir -p /etc/origin/master/named_certificates\n\n# Deploy all infra components reusing relevant parts from openshift-ansible\nANSIBLE_ROLES_PATH=/usr/share/ansible/openshift-ansible/roles/ \\\n  ansible-playbook\\\n  -M /usr/share/ansible/openshift-ansible/roles/lib_utils/library \\\n  -c local azure-ocp-deploy.yml \\\n  -i azure-local-master-inventory.yml\n\n# TODO: possibly wait here for convergence?\n", "num_lines": 29}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ -z \"$CLIENT_ID\" ]; then\n    echo \"must provide a CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$CLIENT_SECRET\" ]; then\n    echo \"must provide a CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID env var\"\n    exit 1;\nfi\n\naz login --service-principal \\\n\t\t--username \"${CLIENT_ID}\" \\\n\t\t--password \"${CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null\n\n# set to the sub id we want to cleanup\naz account set -s $SUBSCRIPTION_ID\n\npython pkg/helpers/Get-AzureConstants.py\ngit status | grep pkg/helpers/azureconst.go\nexit_code=$?\nif [ $exit_code -gt \"0\" ]; then\n  echo \"No modifications found! Exiting 0\"\n  exit 0\nelse\n  echo \"File was modified! Exiting 1\"\n  exit 1\nfi\n", "num_lines": 40}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eo pipefail\n\nfetch_k8s() {\n\tgit clone https://github.com/Azure/kubernetes ${GOPATH}/src/k8s.io/kubernetes || true\n\tcd $KUBEPATH\n\tgit remote add upstream https://github.com/kubernetes/kubernetes || true\n\tgit fetch upstream\n}\n\nset_git_config() {\n\tgit config user.name \"ACS CI\"\n\tgit config user.email \"containers@microsoft.com\"\n}\n\ncreate_version_branch() {\n\tgit checkout -b ${ACS_BRANCH_NAME} ${KUBERNETES_TAG_BRANCH} || true\n}\n\nversion_lt() {\n        [ \"$1\" != $(printf \"$1\\n$2\" | sort -V | head -n 2 | tail -n 1) ]\n}\n\nversion_ge() {\n        [ \"$1\" == $(printf \"$1\\n$2\" | sort -V | head -n 2 | tail -n 1) ]\n}\n\nk8s_16_cherry_pick() {\n\t# 232fa6e5bc (HEAD -> release-1.6, origin/release-1.6) Fix the delay caused by network setup in POD Infra container\n\t# 02b1c2b9e2 Use dns policy to determine setting DNS servers on the correct NIC in Windows container\n\t# 4c2a2d79aa Fix getting host DNS for Windows node when dnsPolicy is Default\n\t# caa314ccdc Update docker version parsing to allow nonsemantic versions as they have changed how they do their versions\n\t# f18be40948 Fix the issue in unqualified name where DNS client such as ping or iwr validate name in response and original question. Switch to use miekg's DNS library\n\t# c862b583c9 Remove DNS server from NAT network adapter inside container\n\t# f6c27f9375 Merged libCNI-on-Windows changes from CNI release 0.5.0, PRs 359 and 361\n\t# 4f196c6cac Fix the issue that ping uses the incorrect NIC to resolve name sometimes\n\t# 2c9fd27449 Workaround for Outbound Internet traffic in Azure Kubernetes\n\t# 5fa0725025 Use adapter vEthernet (HNSTransparent) on Windows host network to find node IP\n\n\tgit cherry-pick 5fa0725025^..232fa6e5bc\n}\n\nk8s_17_cherry_pick() {\n\tif version_ge \"${version}\" \"1.7.10\"; then\n\t\techo \"version 1.7.10 and after...\"\n\t\t# In 1.7.10, the following commit is not needed and has conflict with 137f4cb16e\n\t\t# due to the out-of-order back porting into Azure 1.7. So removing it.\n\t\t# cee32e92f7 fix#50150: azure disk mount failure on coreos\n\t\tgit revert --no-edit cee32e92f7 || true\n\n\t\tif version_ge \"${version}\" \"1.7.12\"; then\n\t\t\techo \"version 1.7.12 and after...\"\n\t\t\t# In 1.7.12, the following commits are cherry-picked in upstream and has conflict\n\t\t\t# with 137f4cb16e. So removing them.\n\t\t\tgit revert --no-edit 593653c384 || true #only for linux\n\t\t\tgit revert --no-edit 7305738dd1 || true #add tests only\n\t\t\tgit revert --no-edit e01bafcf80 || true #only for linux\n\t\t\tgit revert --no-edit afd79db7a6 || true #only for linux\n\t\t\tgit revert --no-edit 3a4abca2f7 || true #covered by commit 3aa179744f\n\t\t\tgit revert --no-edit 6a2e2f47d3 || true #covered by commit 3aa179744f\n\n\t\t\tif version_ge \"${version}\" \"1.7.13\"; then\n\t\t\t\techo \"version 1.7.13 and after...\"\n\t\t\t\t# In 1.7.13, the following commit is cherry-picked in upstream and has conflict\n\t\t\t\t# with 137f4cb16e. So removing it.\n\t\t\t\tgit revert --no-edit 3aa179744f || true #only for linux\n\n\t\t\t\tif version_ge \"${version}\" \"1.7.14\"; then\n\t\t\t\t\techo \"version 1.7.14 and after...\"\n\t\t\t\t\tif version_ge \"${version}\" \"1.7.15\"; then\n\t\t\t\t\t\techo \"version 1.7.15 and after...\"\n\t\t\t\t\t\tif version_ge \"${version}\" \"1.7.16\"; then\n\t\t\t\t\t\t\techo \"version 1.7.16 and after...\"\n\t\t\t\t\t\t\t# From 1.7.16, 3e530479ed conflict with reverting 975d0a4bb9. We use 5f9113ce9b in Azure repo instead of 3e530479ed\n\t\t\t\t\t\t\tgit revert --no-edit 3e530479ed || true\n\t\t\t\t\t\t\t# From 1.7.16, 76017a002b conflict with reverting 975d0a4bb9. We use 3d97a43e41 in Azure repo instead of 76017a002b\n\t\t\t\t\t\t\tgit revert --no-edit 76017a002b || true\n\t\t\t\t\t\tfi\n\n\t\t\t\t\t\t# From 1.7.15, 0d5df36f05 conflict with reverting 975d0a4bb9. We use 631e363b9d in Azure repo instead of 0d5df36f05\n\t\t\t\t\t\tgit revert --no-edit 0d5df36f05 || true\n\t\t\t\t\t\t# From 1.7.15, 4d50500614 conflict with reverting 51584188ee. It is server side code so jsut revert it.\n\t\t\t\t\t\tgit revert --no-edit 4d50500614 || true\n\t\t\t\t\tfi\n\t\t\t\t\t# From 1.7.14, 975d0a4bb9 conflict with 137f4cb16e. We use a36d59ddda in Azure repo instead of 975d0a4bb9\n\t\t\t\t\tgit revert --no-edit 975d0a4bb9 || true\n\t\t\t\t\t# From 1.7.14, 51584188ee and 3a0db21dcb conflict with af3a93b07e. We use f5c45d3def in Azure repo instead of them\n\t\t\t\t\tgit revert --no-edit 51584188ee || true\n\t\t\t\t\tgit revert --no-edit 3a0db21dcb || true\n\t\t\t\t\t# From 1.7.14, 273411cc90 conflict with e9591ef03e. We use d18812a049 in Azure repo instead of 273411cc90\n\t\t\t\t\tgit revert --no-edit 273411cc90 || true\n\t\t\t\t\t# From 1.7.14, a97f60fbf3 conflict with a36d59ddda. We use 69c56c6037 in Azure repo instead of a97f60fbf3\n\t\t\t\t\tgit revert --no-edit a97f60fbf3 || true\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\tfi\n\n\t# 32ceaa7918 fix #60625: add remount logic for azure file plugin on Windows\n\t# ...\n\t# b8fe713754 Use adapter vEthernet (HNSTransparent) on Windows host network to find node IP\n\t# From 1.7.13, acbdec96da is not needed since 060111c603 supercedes it\n\tgit cherry-pick --allow-empty --keep-redundant-commits b8fe713754^..e912889a7f\n\tif version_lt \"${version}\" \"1.7.13\"; then\n\t\techo \"before version 1.7.13...\"\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits acbdec96da\n\tfi\n\tgit cherry-pick --allow-empty --keep-redundant-commits 76d7c23f62^..32ceaa7918\n\n\tif version_ge \"${version}\" \"1.7.14\"; then\n\t\techo \"version 1.7.14 and after...\"\n\t\t# From 1.7.14, 975d0a4bb9 conflict with 137f4cb16e. We use a36d59ddda in Azure repo instead of 975d0a4bb9\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits a36d59ddda\n\t\t# From 1.7.14, 51584188ee and 3a0db21dcb conflict with af3a93b07e. We use f5c45d3def in Azure repo instead of them\n\t\tgit cherry-pick -X theirs --allow-empty --keep-redundant-commits f5c45d3def # git complains about a conflict and just take theirs\n\t\t# From 1.7.14, 273411cc90 conflict with e9591ef03e. We use d18812a049 in Azure repo instead of 273411cc90\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits d18812a049\n\t\t# From 1.7.14, a97f60fbf3 conflict with a36d59ddda. We use 69c56c6037 in Azure repo instead of a97f60fbf3\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits 69c56c6037\n\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits 3e930be6bc\n\n\t\tif version_ge \"${version}\" \"1.7.15\"; then\n\t\t\techo \"version 1.7.15 and after...\"\n\t\t\t# From 1.7.15, 0d5df36f05 conflict with reverting 975d0a4bb9. We use 631e363b9d in Azure repo instead of 0d5df36f05\n\t\t\tgit cherry-pick --allow-empty --keep-redundant-commits 631e363b9d\n\n\t\t\tif version_ge \"${version}\" \"1.7.16\"; then\n\t\t\t\techo \"version 1.7.16 and after...\"\n\t\t\t\t# From 1.7.16, 76017a002b conflict with reverting 975d0a4bb9. We use 3d97a43e41 in Azure repo instead of 76017a002b\n\t\t\t\tgit cherry-pick --allow-empty --keep-redundant-commits 3d97a43e41\n\t\t\t\t# From 1.7.16, 3e530479ed conflict with reverting 975d0a4bb9. We use 5f9113ce9b in Azure repo instead of 3e530479ed\n\t\t\t\tgit cherry-pick --allow-empty --keep-redundant-commits 5f9113ce9b\n\t\t\tfi\n\t\tfi\n\tfi\n}\n\nk8s_18_cherry_pick() {\n\t# 4fd355d04a fix #60625: add remount logic for azure file plugin on Windows\n\t# ...\n\t# 4647f2f616 merge #52401: add windows implementation of GetMountRefs\n\n\t# d75ef50170 merge#54334: fix azure disk mount failure on coreos and some other distros\n\n\t# Only cherry pick before 1.8.6 due to merge conflict with 1.8.6 and up: b8594873f4 merge #50673: azure disk fix of SovereignCloud support\n\n\t# cb29df51c0 Fixing 'targetport' to service 'port' mapping\n\t# ...\n\t# b42981f90b merge#53629: fix azure file mount limit issue on windows due to using drive letter\n\n\t# We have to skip 8b3345114e due to merge conflict with 1.8.4 and up, 4647f2f616 has the change.\n\n\t# 8d477271f7 update bazel\n\t# ...\n\t# 69644018c8 Use adapter vEthernet (HNSTransparent) on Windows host network to find node IP\n\n\tif version_ge \"${version}\" \"1.8.9\"; then\n\t\techo \"version 1.8.9 and after...\"\n\t\tif version_ge \"${version}\" \"1.8.10\"; then\n\t\t\techo \"version 1.8.10 and after...\"\n\t\t\tif version_ge \"${version}\" \"1.8.11\"; then\n\t\t\t\techo \"version 1.8.11 and after...\"\n\t\t\t\t# From 1.8.11, 6487f82b13 conflict with 86107edff5. We use 8e081d5da9 in Azure repo instead of 6487f82b13\n\t\t\t\tgit revert --no-edit 6487f82b13 || true\n\t\t\t\t# From 1.8.11, 2704ef877b conflict with reverting a418057ddd. We skip it since it is test file\n\t\t\t\tgit revert --no-edit 2704ef877b || true\n\t\t\t\t# From 1.8.11, dc21ebe936 conflict with reverting 63b4f60e43. We use 18589971f7 in Azure repo instead of dc21ebe936\n\t\t\t\tgit revert --no-edit dc21ebe936 || true\n\t\t\t\t# From 1.8.11, a418057ddd conflict with reverting 63b4f60e43. We use 57038dce90 in Azure repo instead of a418057ddd\n\t\t\t\tgit revert --no-edit a418057ddd || true\n\t\t\t\t# From 1.8.11, beaca32611 conflict with reverting 63b4f60e43. We use e6d8af84df in Azure repo instead of beaca32611\n\t\t\t\tgit revert --no-edit beaca32611 || true\n\t\t\tfi\n\t\t\t# From 1.8.10, 5936faed37 conflict with reverting 63b4f60e43. We use 1f26b7a083 in Azure repo instead of 5936faed37\n\t\t\tgit revert --no-edit 5936faed37 || true\n\t\tfi\n\t\t# From 1.8.9, 63b4f60e43 conflict with b42981f90b. We use 6a8305e419 in Azure repo instead of 63b4f60e43\n\t\tgit revert --no-edit 63b4f60e43 || true\n\t\t# From 1.8.9, 40d5e0a34f conflict with 6a8305e419. We use b90d61a48c in Azure repo instead of 40d5e0a34f\n\t\tgit revert --no-edit 40d5e0a34f || true\n\tfi\n\n\tgit cherry-pick --allow-empty --keep-redundant-commits 69644018c8^..8d477271f7\n\tgit cherry-pick --allow-empty --keep-redundant-commits b42981f90b^..cb29df51c0\n\tif version_lt \"${version}\" \"1.8.6\"; then\n\t\techo \"before version 1.8.6...\"\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits b8594873f4\n\tfi\n\tgit cherry-pick --allow-empty --keep-redundant-commits d75ef50170\n\tgit cherry-pick --allow-empty --keep-redundant-commits 4647f2f616^..4fd355d04a\n\n\tif version_ge \"${version}\" \"1.8.9\"; then\n\t\techo \"version 1.8.9 and after...\"\n\t\t# From 1.8.9, 63b4f60e43 conflict with b42981f90b. We use 6a8305e419 in Azure repo instead of 63b4f60e43\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits 6a8305e419\n\t\t# From 1.8.9, 40d5e0a34f conflict with 6a8305e419. We use b90d61a48c in Azure repo instead of 40d5e0a34f\n\t\tgit cherry-pick --allow-empty --keep-redundant-commits b90d61a48c\n\t\tif version_ge \"${version}\" \"1.8.10\"; then\n\t\t\techo \"version 1.8.10 and after...\"\n\t\t\t# From 1.8.10, 5936faed37 conflict with reverting 63b4f60e43. We use 1f26b7a083 in Azure repo instead of 5936faed37\n\t\t\tgit cherry-pick --allow-empty --keep-redundant-commits 1f26b7a083\n\t\t\tif version_ge \"${version}\" \"1.8.11\"; then\n\t\t\t\techo \"version 1.8.11 and after...\"\n\t\t\t\t# From 1.8.11, 6487f82b13 conflict with 86107edff5. We use 8e081d5da9 in Azure repo instead of 6487f82b13\n\t\t\t\t# From 1.8.11, dc21ebe936 conflict with reverting 63b4f60e43. We use 18589971f7 in Azure repo instead of dc21ebe936\n\t\t\t\t# From 1.8.11, a418057ddd conflict with reverting 63b4f60e43. We use 57038dce90 in Azure repo instead of a418057ddd\n\t\t\t\t# From 1.8.11, beaca32611 conflict with reverting 63b4f60e43. We use e6d8af84df in Azure repo instead of beaca32611\n\t\t\t\tgit cherry-pick --allow-empty --keep-redundant-commits 8e081d5da9^..18589971f7\n\t\t\tfi\n\t\tfi\n\tfi\n}\n\napply_acs_cherry_picks() {\n\tif [ \"${KUBERNETES_RELEASE}\" == \"1.6\" ]; then\n\t\tk8s_16_cherry_pick\n\telif [ \"${KUBERNETES_RELEASE}\" == \"1.7\" ]; then\n\t\tk8s_17_cherry_pick\n\telif [ \"${KUBERNETES_RELEASE}\" == \"1.8\" ]; then\n\t\tk8s_18_cherry_pick\n\telif version_ge \"${KUBERNETES_RELEASE}\" \"1.9\"; then\n\t\techo \"No need to cherry-pick for version greater than or equal to 1.9!\"\n\telse\n\t\techo \"Unable to apply cherry picks for ${KUBERNETES_RELEASE}.\"\n\t\texit 1\n\tfi\n}\n\ncreate_dist_dir() {\n\tmkdir -p ${DIST_DIR}\n}\n\nbuild_kubelet() {\n\techo \"building kubelet.exe...\"\n\t$KUBEPATH/build/run.sh make WHAT=cmd/kubelet KUBE_BUILD_PLATFORMS=windows/amd64\n\tcp ${GOPATH}/src/k8s.io/kubernetes/_output/dockerized/bin/windows/amd64/kubelet.exe ${DIST_DIR}\n}\n\nbuild_kubeproxy() {\n\techo \"building kube-proxy.exe...\"\n\t$KUBEPATH/build/run.sh make WHAT=cmd/kube-proxy KUBE_BUILD_PLATFORMS=windows/amd64\n\tcp ${GOPATH}/src/k8s.io/kubernetes/_output/dockerized/bin/windows/amd64/kube-proxy.exe ${DIST_DIR}\n}\n\nbuild_kubectl() {\n\techo \"building kubectl.exe...\"\n    $KUBEPATH/build/run.sh make WHAT=cmd/kubectl KUBE_BUILD_PLATFORMS=windows/amd64\n    cp ${GOPATH}/src/k8s.io/kubernetes/_output/dockerized/bin/windows/amd64/kubectl.exe ${DIST_DIR}\n}\n\ndownload_kubectl() {\n\tkubectl=\"https://storage.googleapis.com/kubernetes-release/release/v${version}/bin/windows/amd64/kubectl.exe\"\n\techo \"dowloading ${kubectl} ...\"\n\tcurl -L ${kubectl} -o ${DIST_DIR}/kubectl.exe\n\tchmod 775 ${DIST_DIR}/kubectl.exe\n}\n\nget_kube_binaries() {\n\tif version_lt \"${KUBERNETES_RELEASE}\" \"1.9\"; then\n\t\techo \"building kubelet/kubeproxy from azure repo...\"\n\t\tfetch_k8s\n\t\tset_git_config\n\t\tcreate_version_branch\n\t\tapply_acs_cherry_picks\n\n\t\t# Due to what appears to be a bug in the Kubernetes Windows build system, one\n\t\t# has to first build a linux binary to generate _output/bin/deepcopy-gen.\n\t\t# Building to Windows w/o doing this will generate an empty deepcopy-gen.\n\t\tbuild/run.sh make WHAT=cmd/kubelet KUBE_BUILD_PLATFORMS=linux/amd64\n\n\t\tbuild_kubelet\n\t\tbuild_kubeproxy\n\n\t\techo \"downloading kubectl...\"\n\t\tdownload_kubectl\n\telse\n\t\techo \"downloading kubelet/kubeproxy/kubectl from upstream...\"\n\t\tWIN_TAR=kubernetes-node-windows-amd64.tar.gz\n\t\tSUB_DIR=kubernetes/node/bin\n\t\tcurl -L https://storage.googleapis.com/kubernetes-release/release/v${version}/${WIN_TAR} -o ${TOP_DIR}/${WIN_TAR}\n\t\ttar -xzvf ${TOP_DIR}/${WIN_TAR} -C ${TOP_DIR}\n\t\tcp ${TOP_DIR}/${SUB_DIR}/kubelet.exe ${DIST_DIR}\n\t\tcp ${TOP_DIR}/${SUB_DIR}/kube-proxy.exe ${DIST_DIR}\n\t\tcp ${TOP_DIR}/${SUB_DIR}/kubectl.exe ${DIST_DIR}\n\t\tchmod 775 ${DIST_DIR}/kubectl.exe\n\tfi\n}\n\nbuild_kube_binaries_for_upstream_e2e() {\n\t\t$KUBEPATH/build/run.sh make WHAT=cmd/kubelet KUBE_BUILD_PLATFORMS=linux/amd64\n\n\t\tbuild_kubelet\n\t\tbuild_kubeproxy\n\t\tbuild_kubectl\n}\n\ndownload_nssm() {\n\tNSSM_VERSION=2.24\n\tNSSM_URL=https://nssm.cc/release/nssm-${NSSM_VERSION}.zip\n\techo \"downloading nssm ...\"\n\tcurl ${NSSM_URL} -o /tmp/nssm-${NSSM_VERSION}.zip\n\tunzip -q -d /tmp /tmp/nssm-${NSSM_VERSION}.zip\n\tcp /tmp/nssm-${NSSM_VERSION}/win64/nssm.exe ${DIST_DIR}\n\tchmod 775 ${DIST_DIR}/nssm.exe\n\trm -rf /tmp/nssm-${NSSM_VERSION}*\n}\n\ndownload_wincni() {\n\tmkdir -p ${DIST_DIR}/cni/config\n\tWINSDN_URL=https://github.com/Microsoft/SDN/raw/master/Kubernetes/windows/\n\tWINCNI_EXE=cni/wincni.exe\n\tHNS_PSM1=hns.psm1\n\tcurl -L ${WINSDN_URL}${WINCNI_EXE} -o ${DIST_DIR}/${WINCNI_EXE}\n\tcurl -L ${WINSDN_URL}${HNS_PSM1} -o ${DIST_DIR}/${HNS_PSM1}\n}\n\ncopy_dockerfile() {\n  cp ${ACS_ENGINE_HOME}/windows/Dockerfile ${DIST_DIR}\n}\n\ncreate_zip() {\n\tZIP_NAME=\"${k8s_e2e_upstream_version:-\"v${ACS_VERSION}int.zip\"}\"\n\tcd ${DIST_DIR}/..\n\tzip -r ../${ZIP_NAME} k/*\n\tcd -\n}\n\nupload_zip_to_blob_storage() {\n\taz storage blob upload -f ${TOP_DIR}/../v${ACS_VERSION}int.zip -c ${AZURE_STORAGE_CONTAINER_NAME} -n v${ACS_VERSION}int.zip\n}\n\npush_acs_branch() {\n\tif version_lt \"${KUBERNETES_RELEASE}\" \"1.9\"; then\n\t\techo \"push to azure repo...\"\n\t\tcd ${GOPATH}/src/k8s.io/kubernetes\n\t\tgit push origin ${ACS_BRANCH_NAME}\n\telse\n\t\techo \"no need to push to azure repo\"\n\tfi\n}\n\ncleanup_output() {\n\trm ${TOP_DIR}/../v${ACS_VERSION}int.zip\n\trm -r ${TOP_DIR}\n}\n\n\nACS_ENGINE_HOME=${GOPATH}/src/github.com/Azure/acs-engine\n\nusage() {\n\techo \"$0 [-v version] [-p acs_patch_version]\"\n\techo \" -v <version>: version\"\n\techo \" -p <patched version>: acs_patch_version\"\n\techo \" -u <version build for kubernetes upstream e2e tests>: k8s_e2e_upstream_version\"\n\techo \" -z <zip path>: zip_path\"\n}\n\nwhile getopts \":v:p:u:z:\" opt; do\n  case ${opt} in\n    v)\n      version=${OPTARG}\n      ;;\n    p)\n      acs_patch_version=${OPTARG}\n      ;;\n\tu)\n\t  k8s_e2e_upstream_version=${OPTARG}\n\t  ;;\n\tz)\n\t  zip_path=${OPTARG}\n\t  ;;  \n    *)\n\t\t\tusage\n\t\t\texit\n      ;;\n  esac\ndone\n\nKUBEPATH=${GOPATH}/src/k8s.io/kubernetes\n\nif [ -z \"${k8s_e2e_upstream_version}\" ]; then\n\n\tif [ -z \"${version}\" ] || [ -z \"${acs_patch_version}\" ]; then\n\t\tusage\n\t\t\texit 1\n\tfi\n\n\tif [ -z \"${AZURE_STORAGE_CONNECTION_STRING}\" ] || [ -z \"${AZURE_STORAGE_CONTAINER_NAME}\" ]; then\n\t\techo '$AZURE_STORAGE_CONNECTION_STRING and $AZURE_STORAGE_CONTAINER_NAME need to be set for upload to Azure Blob Storage.'\n\t\t\texit 1\n\tfi\n\n\tKUBERNETES_RELEASE=$(echo $version | cut -d'.' -f1,2)\n\tKUBERNETES_TAG_BRANCH=v${version}\n\tACS_VERSION=${version}-${acs_patch_version}\n\tACS_BRANCH_NAME=acs-v${ACS_VERSION}\n\tTOP_DIR=${ACS_ENGINE_HOME}/_dist/k8s-windows-v${ACS_VERSION}\n\tDIST_DIR=${TOP_DIR}/k\n\n\tcreate_dist_dir\n\tget_kube_binaries\n\tdownload_nssm\n\tdownload_wincni\n\tcopy_dockerfile\n\tcreate_zip\n\tupload_zip_to_blob_storage\n\tpush_acs_branch\n\tcleanup_output\n\nelse\n\tDIST_DIR=${zip_path}/k\n\tcreate_dist_dir\n\tbuild_kube_binaries_for_upstream_e2e\n\tdownload_nssm\n\tdownload_wincni\n\tcreate_zip\nfi\t\n\n", "num_lines": 420}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# DON'T RUN. This script requires PythonLocalizerTool which is not published yet.\n# TODO: make PythonLocalizerTool public\nset -eo pipefail\n\nlangdirs=loc/*\n\nconvert_lcl_to_po() {\n  for dir in $langdirs\n  do\n    loc_lang=`basename \"$dir\"`\n    translation_lang=`echo $loc_lang | tr - _`\n    publish/PythonLocalizerTool lcltopo $dir translations/$translation_lang/LC_MESSAGES/ translations/en_US/LC_MESSAGES/en-US/metadata acsengine \"\"\n    msgfmt -c -v -o translations/$translation_lang/LC_MESSAGES/acsengine.mo translations/$translation_lang/LC_MESSAGES/acsengine.po\n  done\n}\n\nconvert_po_to_lcg() {\n  publish/PythonLocalizerTool potolcg translations/en_US/LC_MESSAGES acsengine\n}\n\ncase \"${1-}\" in\n  --potolcg)\n    echo \"converting po to lcg...\"\n    convert_po_to_lcg\n    ;;\n  --lcltopo)\n    echo \"converting lcl to po...\"\n    convert_lcl_to_po\n    ;;\n  *)\n    echo $\"Usage: $0 {--potolcg|--lcltopo}\"\n    exit 1\nesac\n", "num_lines": 36}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\nfor i in $(find .. -type f -iname '*.go' ! -path '../vendor/*') # do not run on the vendor dir\ndo\n  if ! grep -q Copyright \"$i\"\n  then\n    cat copyright.txt \"$i\" > \"$i\".new && mv \"$i\".new \"$i\"\n  fi\ndone\n", "num_lines": 12}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\ncovermode=${COVERMODE:-atomic}\ncoverdir=$(mktemp -d /tmp/coverage.XXXXXXXXXX)\nprofile=\"${coverdir}/cover.out\"\n\nhash goveralls 2>/dev/null || go get github.com/mattn/goveralls\nhash godir 2>/dev/null || go get github.com/Masterminds/godir\n\ngenerate_cover_data() {\n  for d in $(godir) ; do\n    (\n      local output=\"${coverdir}/${d//\\//-}.cover\"\n      go test -coverprofile=\"${output}\" -covermode=\"$covermode\" \"$d\"\n    )\n  done\n\n  echo \"mode: $covermode\" >\"$profile\"\n  grep -h -v \"^mode:\" \"$coverdir\"/*.cover >>\"$profile\"\n}\n\npush_to_coveralls() {\n  goveralls -coverprofile=\"${profile}\" -repotoken $COVERALLS_TOKEN\n}\n\ngenerate_cover_data\ngo tool cover -func \"${profile}\"\n\ncase \"${1-}\" in\n  --html)\n    go tool cover -html \"${profile}\"\n    ;;\n  --coveralls)\n\t\tif [ -z $COVERALLS_TOKEN ]; then\n\t\t\techo '$COVERALLS_TOKEN not set. Skipping pushing coverage report to coveralls.io'\n\t\t\texit\n\t\tfi\n    push_to_coveralls\n    ;;\nesac\n\n", "num_lines": 58}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eu -o pipefail\nset -x\n\ndocker build --pull -t acs-engine .\n\ndocker run -it \\\n\t--privileged \\\n\t--security-opt seccomp:unconfined \\\n\t-v /var/run/docker.sock:/var/run/docker.sock \\\n\t-v `pwd`:/gopath/src/github.com/Azure/acs-engine \\\n\t-v ~/.azure:/root/.azure \\\n\t-w /gopath/src/github.com/Azure/acs-engine \\\n\t\tacs-engine /bin/bash\n\nchown -R \"$(logname):$(id -gn $(logname))\" . ~/.azure\n", "num_lines": 18}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eo pipefail\n\ncovermode=${COVERMODE:-atomic}\ncoverdir=$(mktemp -d /tmp/coverage.XXXXXXXXXX)\nprofile=\"${coverdir}/cover.out\"\ncoveragetxt=\"coverage.txt\"\n\nhash goveralls 2>/dev/null || go get github.com/mattn/goveralls\nhash godir 2>/dev/null || go get github.com/Masterminds/godir\n\ngenerate_cover_data() {\n  ginkgo -skipPackage test/e2e/dcos,test/e2e/kubernetes,test/e2e/openshift -failFast -cover -r .\n  echo \"\" > ${coveragetxt}\n  find . -type f -name \"*.coverprofile\" | while read -r file;  do cat $file >> ${coveragetxt} && mv $file ${coverdir}; done\n  echo \"mode: $covermode\" >\"$profile\"\n  grep -h -v \"^mode:\" \"$coverdir\"/*.coverprofile >>\"$profile\"\n}\n\npush_to_coveralls() {\n  goveralls -coverprofile=\"${profile}\" -service=circle-ci -repotoken $COVERALLS_REPO_TOKEN || echo \"push to coveralls failed\"\n}\n\npush_to_codecov() {\n  bash <(curl -s https://codecov.io/bash) || echo \"push to codecov failed\"\n}\n\ngenerate_cover_data\ngo tool cover -func \"${profile}\"\n\ncase \"${1-}\" in\n  --html)\n    go tool cover -html \"${profile}\"\n    ;;\n  --coveralls)\n\t\tif [ -z $COVERALLS_REPO_TOKEN ]; then\n\t\t\techo '$COVERALLS_REPO_TOKEN not set. Skipping pushing coverage report to coveralls.io'\n\t\t\texit\n\t\tfi\n    push_to_coveralls\n    ;;\n  --codecov)\n    push_to_codecov\n    ;;\nesac\n", "num_lines": 61}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nscripts/update-translation.sh -l en_US -p\n\nmv acsengine.po translations/en_US/LC_MESSAGES/acsengine.po\nrm acsengine.pot", "num_lines": 6}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nGO_SOURCE=\"pkg/acsengine/*.go pkg/acsengine/transform/*.go pkg/api/*.go pkg/operations/*.go pkg/operations/kubernetesupgrade/*.go\"\nLANGUAGE=\"en_US\"\nDOMAIN=\"acsengine\"\ngenerate_po=\"false\"\ngenerate_mo=\"false\"\n\nwhile getopts \"hl:pm\" opt; do\n  case $opt in\n    h)\n      echo \"$0 [-l language] [-p] [-m]\"\n      echo \" -l <language>: Language to translate\"\n      echo \" -p extract strings and generate PO file\"\n      echo \" -m generate MO file\"\n      exit 0\n      ;;\n    l)\n      LANGUAGE=\"${OPTARG}\"\n      ;;\n    p)\n      generate_po=\"true\"\n      ;;\n    m)\n      generate_mo=\"true\"\n      ;;\n    \\?)\n      echo \"$0 [-l language] [-p] [-m]\"\n      exit 1\n      ;;\n  esac\ndone\n\nif ! which go-xgettext > /dev/null; then\n  echo 'Can not find go-xgettext, install with:'\n  echo 'go get github.com/JiangtianLi/gettext/go-xgettext'\n  exit 1\nfi\n\nif ! which msginit > /dev/null; then\n  echo 'Can not find msginit, install with:'\n  echo 'apt-get install gettext'\n  exit 1\nfi\n\nif [[ \"${generate_po}\" == \"true\" ]]; then\n  echo \"Extract strings and generate PO files...\"\n  go-xgettext -o ${DOMAIN}.pot --keyword=Translator.Errorf --keyword-plural=Translator.NErrorf --msgid-bugs-address=\"\" --sort-output ${GO_SOURCE}\n  msginit -l ${LANGUAGE} -o ${DOMAIN}.po -i ${DOMAIN}.pot\nfi\n\nif [[ \"${generate_mo}\" == \"true\" ]]; then\n  echo \"Generate MO file...\"\n  if [ ! -f ${DOMAIN}.po ]; then\n    echo \"${DOMAIN}.po not found!\"\n\texit 1\n  fi\n  msgfmt -c -v -o ${DOMAIN}.mo ${DOMAIN}.po\nfi\n", "num_lines": 60}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\necho \"==> Checking copyright headers <==\"\n\nfiles=$(find . -type f -iname '*.go' ! -path './vendor/*')\nlicRes=$(for file in $files; do\n           awk 'NR<=3' \"$file\" | grep -Eq \"(Copyright|generated|GENERATED)\" || echo \"$file\";\n         done)\n\nif [ -n \"$licRes\" ]; then\n        echo \"Copyright header check failed:\";\n        echo \"${licRes}\";\n        exit 1;\nfi\n", "num_lines": 17}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexit_code=0\n\necho \"==> Running dep check <==\"\n\ndep check || exit_code=1\n\nif [ $exit_code -ne 0 ]; then\n  echo \"The dependency state is out of sync. Please run dep ensure.\"\nelse\n  echo \"dep check passed.\"\nfi\n\nexit $exit_code", "num_lines": 15}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -euo pipefail\n\nexit_code=0\n\nif ! hash gometalinter 2>/dev/null ; then\n  go get -u github.com/alecthomas/gometalinter\n  gometalinter --install\nfi\n\necho\necho \"==> Running static validations <==\"\n# Run linters that should return errors\ngometalinter \\\n  --disable-all \\\n  --enable deadcode \\\n  --enable gofmt \\\n  --enable goimports \\\n  --enable gosimple \\\n  --enable ineffassign \\\n  --enable misspell \\\n  --enable unused \\\n  --enable vet \\\n  --tests \\\n  --vendor \\\n  --deadline 120s \\\n  --skip test/i18n \\\n  --skip pkg/test \\\n  --exclude pkg/i18n/i18n.go \\\n  --exclude pkg/i18n/translations.go \\\n  --exclude pkg/acsengine/templates.go \\\n  --exclude pkg/openshift/certgen/release39/templates/bindata.go \\\n  --exclude pkg/openshift/certgen/unstable/templates/bindata.go \\\n  ./... || exit_code=1\n\necho\necho \"==> Running linters <==\"\n# Run linters that should return warnings\ngometalinter \\\n  --disable-all \\\n  --enable golint \\\n  --vendor \\\n  --skip proto \\\n  --skip pkg/test \\\n  --deadline 60s \\\n  --exclude pkg/i18n/translations.go \\\n  --exclude pkg/acsengine/templates.go \\\n  --exclude pkg/openshift/certgen/release39/templates/bindata.go \\\n  --exclude pkg/openshift/certgen/unstable/templates/bindata.go \\\n  ./... || exit_code=1\n\nexit $exit_code\n", "num_lines": 67}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\nROOT=\"${DIR}/..\"\n\n# see: https://github.com/stedolan/jq/issues/105 & https://github.com/stedolan/jq/wiki/FAQ#general-questions\nfunction jqi() { filename=\"${1}\"; jqexpr=\"${2}\"; jq \"${jqexpr}\" \"${filename}\" > \"${filename}.tmp\" && mv \"${filename}.tmp\" \"${filename}\"; }\n\nfunction generate_template() {\n\t# Check pre-requisites\n\t[[ ! -z \"${INSTANCE_NAME:-}\" ]] || (echo \"Must specify INSTANCE_NAME\" && exit -1)\n\t[[ ! -z \"${CLUSTER_DEFINITION:-}\" ]] || (echo \"Must specify CLUSTER_DEFINITION\" && exit -1)\n\t[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_ID:-}\" ]] || [[ ! -z \"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID:-}\" ]] || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_ID\" && exit -1)\n\t[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_SECRET:-}\" ]] || [[ ! -z \"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET:-}\" ]] || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_SECRET\" && exit -1)\n\t[[ ! -z \"${OUTPUT:-}\" ]] || (echo \"Must specify OUTPUT\" && exit -1)\n\n\t# Set output directory\n\tmkdir -p \"${OUTPUT}\"\n\n\t# Prep SSH Key\n\tssh-keygen -b 2048 -t rsa -f \"${OUTPUT}/id_rsa\" -q -N \"\"\n\tssh-keygen -y -f \"${OUTPUT}/id_rsa\" > \"${OUTPUT}/id_rsa.pub\"\n\texport SSH_KEY_DATA=\"$(cat \"${OUTPUT}/id_rsa.pub\")\"\n\n\t# Allow different credentials for cluster vs the deployment\n\texport CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID=\"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID:-${SERVICE_PRINCIPAL_CLIENT_ID}}\"\n\texport CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET=\"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET:-${SERVICE_PRINCIPAL_CLIENT_SECRET}}\"\n\n\t# Form the final cluster_definition file\n\texport FINAL_CLUSTER_DEFINITION=\"${OUTPUT}/clusterdefinition.json\"\n\tcp \"${CLUSTER_DEFINITION}\" \"${FINAL_CLUSTER_DEFINITION}\"\n\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.masterProfile.dnsPrefix = \\\"${INSTANCE_NAME}\\\"\"\n\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.agentPoolProfiles |= map(if .name==\\\"agentpublic\\\" then .dnsPrefix = \\\"${INSTANCE_NAME}0\\\" else . end)\"\n\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.linuxProfile.ssh.publicKeys[0].keyData = \\\"${SSH_KEY_DATA}\\\"\"\n\n\tk8sServicePrincipal=$(jq 'getpath([\"properties\",\"servicePrincipalProfile\"])' ${FINAL_CLUSTER_DEFINITION})\n\tif [[ \"${k8sServicePrincipal}\" != \"null\" ]]; then\n\t\tapiVersion=$(get_api_version)\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.servicePrincipalProfile.clientId = \\\"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID}\\\"\"\n\t\tif [[ ${CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET} =~ /subscription.* ]]; then\n\t\t\tvaultID=$(echo $CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET | awk -F\"/secrets/\" '{print $1}')\n\t\t\tsecretName=$(echo $CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET | awk -F\"/secrets/\" '{print $2}')\n\t\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.servicePrincipalProfile.keyvaultSecretRef.vaultID = \\\"${vaultID}\\\"\"\n\t\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.servicePrincipalProfile.keyvaultSecretRef.secretName  = \\\"${secretName}\\\"\"\n\t\telse\n\t\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.servicePrincipalProfile.secret = \\\"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET}\\\"\"\n\t\tfi\n\tfi\n\n\tsecrets=$(jq 'getpath([\"properties\",\"linuxProfile\",\"secrets\"])' ${FINAL_CLUSTER_DEFINITION})\n\tif [[ \"${secrets}\" != \"null\" ]]; then\n\t\t[[ ! -z \"${CERT_KEYVAULT_ID:-}\" ]] || (echo \"Must specify CERT_KEYVAULT_ID\" && exit -1)\n\t\t[[ ! -z \"${CERT_SECRET_URL:-}\" ]] || (echo \"Must specify CERT_SECRET_URL\" && exit -1)\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.linuxProfile.secrets[0].sourceVault.id = \\\"${CERT_KEYVAULT_ID}\\\"\"\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.linuxProfile.secrets[0].vaultCertificates[0].certificateUrl = \\\"${CERT_SECRET_URL}\\\"\"\n\tfi\n\tsecrets=$(jq 'getpath([\"properties\",\"windowsProfile\",\"secrets\"])' ${FINAL_CLUSTER_DEFINITION})\n\tif [[ \"${secrets}\" != \"null\" ]]; then\n\t\t[[ ! -z \"${CERT_KEYVAULT_ID:-}\" ]] || (echo \"Must specify CERT_KEYVAULT_ID\" && exit -1)\n\t\t[[ ! -z \"${CERT_SECRET_URL:-}\" ]] || (echo \"Must specify CERT_SECRET_URL\" && exit -1)\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.windowsProfile.secrets[0].sourceVault.id = \\\"${CERT_KEYVAULT_ID}\\\"\"\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.windowsProfile.secrets[0].vaultCertificates[0].certificateUrl = \\\"${CERT_SECRET_URL}\\\"\"\n\t\tjqi \"${FINAL_CLUSTER_DEFINITION}\" \".properties.windowsProfile.secrets[0].vaultCertificates[0].certificateStore = \\\"My\\\"\"\n\tfi\n\t# Generate template\n\t\"${DIR}/../bin/acs-engine\" generate --output-directory \"${OUTPUT}\" \"${FINAL_CLUSTER_DEFINITION}\" --debug\n\n\t# Fill in custom hyperkube spec, if it was set\n\tif [[ ! -z \"${CUSTOM_HYPERKUBE_SPEC:-}\" ]]; then\n\t\t# TODO: plumb hyperkube into the apimodel\n\t\tjqi \"${OUTPUT}/azuredeploy.parameters.json\" \".parameters.kubernetesHyperkubeSpec.value = \\\"${CUSTOM_HYPERKUBE_SPEC}\\\"\"\n\tfi\n}\n\nfunction set_azure_account() {\n\t# Check pre-requisites\n\t[[ ! -z \"${SUBSCRIPTION_ID:-}\" ]] || (echo \"Must specify SUBSCRIPTION_ID\" && exit -1)\n\t[[ ! -z \"${TENANT_ID:-}\" ]] || (echo \"Must specify TENANT_ID\" && exit -1)\n\t[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_ID:-}\" ]] || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_ID\" && exit -1)\n\t[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_SECRET:-}\" ]] || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_SECRET\" && exit -1)\n\twhich kubectl || (echo \"kubectl must be on PATH\" && exit -1)\n\twhich az || (echo \"az must be on PATH\" && exit -1)\n\n\t# Login to Azure-Cli\n\taz login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null\n\n\taz account set --subscription \"${SUBSCRIPTION_ID}\"\n}\n\nfunction create_resource_group() {\n\t[[ ! -z \"${LOCATION:-}\" ]] || (echo \"Must specify LOCATION\" && exit -1)\n\t[[ ! -z \"${RESOURCE_GROUP:-}\" ]] || (echo \"Must specify RESOURCE_GROUP\" && exit -1)\n\n\t# Create resource group if doesn't exist\n\taz group show --name=\"${RESOURCE_GROUP}\" || [ $? -eq 3  ] && echo \"will create resource group ${RESOURCE_GROUP}\" || exit -1\n\taz group create --name=\"${RESOURCE_GROUP}\" --location=\"${LOCATION}\" --tags \"type=${RESOURCE_GROUP_TAG_TYPE:-}\" \"now=$(date +%s)\" \"job=${JOB_BASE_NAME:-}\" \"buildno=${BUILD_NUM:-}\"\n\t\tsleep 3 # TODO: investigate why this is needed (eventual consistency in ARM)\n}\n\nfunction deploy_template() {\n\t# Check pre-requisites\n\t[[ ! -z \"${DEPLOYMENT_NAME:-}\" ]] || (echo \"Must specify DEPLOYMENT_NAME\" && exit -1)\n\t[[ ! -z \"${LOCATION:-}\" ]] || (echo \"Must specify LOCATION\" && exit -1)\n\t[[ ! -z \"${RESOURCE_GROUP:-}\" ]] || (echo \"Must specify RESOURCE_GROUP\" && exit -1)\n\t[[ ! -z \"${OUTPUT:-}\" ]] || (echo \"Must specify OUTPUT\" && exit -1)\n\n\twhich kubectl || (echo \"kubectl must be on PATH\" && exit -1)\n\twhich az || (echo \"az must be on PATH\" && exit -1)\n\n\tcreate_resource_group\n\n\t# Deploy the template\n\taz group deployment create \\\n\t\t--name \"${DEPLOYMENT_NAME}\" \\\n\t\t--resource-group \"${RESOURCE_GROUP}\" \\\n\t\t--template-file \"${OUTPUT}/azuredeploy.json\" \\\n\t\t--parameters \"@${OUTPUT}/azuredeploy.parameters.json\"\n}\n\nfunction scale_agent_pool() {\n\t# Check pre-requisites\n\t[[ ! -z \"${AGENT_POOL_SIZE:-}\" ]] || (echo \"Must specify AGENT_POOL_SIZE\" && exit -1)\n\t[[ ! -z \"${DEPLOYMENT_NAME:-}\" ]] || (echo \"Must specify DEPLOYMENT_NAME\" && exit -1)\n\t[[ ! -z \"${LOCATION:-}\" ]] || (echo \"Must specify LOCATION\" && exit -1)\n\t[[ ! -z \"${RESOURCE_GROUP:-}\" ]] || (echo \"Must specify RESOURCE_GROUP\" && exit -1)\n\t[[ ! -z \"${OUTPUT:-}\" ]] || (echo \"Must specify OUTPUT\" && exit -1)\n\n\twhich az || (echo \"az must be on PATH\" && exit -1)\n\n\tAPIMODEL=\"${OUTPUT}/apimodel.json\"\n\tDEPLOYMENT_PARAMS=\"${OUTPUT}/azuredeploy.parameters.json\"\n\n\tfor poolname in `jq '.properties.agentPoolProfiles[].name' \"${APIMODEL}\" | tr -d '\\\"'`; do\n\t  offset=$(jq \"getpath([\\\"parameters\\\", \\\"${poolname}Count\\\", \\\"value\\\"])\" ${DEPLOYMENT_PARAMS})\n\t  echo \"$poolname : offset=$offset count=$AGENT_POOL_SIZE\"\n\t  jqi \"${DEPLOYMENT_PARAMS}\" \".${poolname}Count.value = $AGENT_POOL_SIZE\"\n\t  jqi \"${DEPLOYMENT_PARAMS}\" \".${poolname}Offset.value = $offset\"\n\tdone\n\n\taz group deployment create \\\n\t\t--name \"${DEPLOYMENT_NAME}\" \\\n\t\t--resource-group \"${RESOURCE_GROUP}\" \\\n\t\t--template-file \"${OUTPUT}/azuredeploy.json\" \\\n\t\t--parameters \"@${OUTPUT}/azuredeploy.parameters.json\"\n}\n\nfunction get_node_count() {\n\t[[ ! -z \"${CLUSTER_DEFINITION:-}\" ]] || (echo \"Must specify CLUSTER_DEFINITION\" && exit -1)\n\n\tcount=$(jq '.properties.masterProfile.count' ${CLUSTER_DEFINITION})\n\tlinux_agents=0\n\twindows_agents=0\n\n\tnodes=$(jq -r '.properties.agentPoolProfiles[].count' ${CLUSTER_DEFINITION})\n\tosTypes=$(jq -r '.properties.agentPoolProfiles[].osType' ${CLUSTER_DEFINITION})\n\n\tnArr=( $nodes )\n\toArr=( $osTypes )\n\tindx=0\n\tfor n in \"${nArr[@]}\"; do\n\t\tcount=$((count+n))\n\t\tif [ \"${oArr[$indx]}\" = \"Windows\" ]; then\n\t\t\twindows_agents=$((windows_agents+n))\n\t\telse\n\t\t\tlinux_agents=$((linux_agents+n))\n\t\tfi\n\t\tindx=$((indx+1))\n\tdone\n\techo \"${count}:${linux_agents}:${windows_agents}\"\n}\n\nfunction get_orchestrator_type() {\n\t[[ ! -z \"${CLUSTER_DEFINITION:-}\" ]] || (echo \"Must specify CLUSTER_DEFINITION\" && exit -1)\n\n\torchestratorType=$(jq -r 'getpath([\"properties\",\"orchestratorProfile\",\"orchestratorType\"])' ${CLUSTER_DEFINITION} | tr '[:upper:]' '[:lower:]')\n\n\techo $orchestratorType\n}\n\nfunction get_orchestrator_version() {\n\t[[ ! -z \"${CLUSTER_DEFINITION:-}\" ]] || (echo \"Must specify CLUSTER_DEFINITION\" && exit -1)\n\n\torchestratorVersion=$(jq -r 'getpath([\"properties\",\"orchestratorProfile\",\"orchestratorVersion\"])' ${CLUSTER_DEFINITION})\n\tif [[ \"$orchestratorVersion\" == \"null\" ]]; then\n\t\torchestratorVersion=\"\"\n\tfi\n\n\techo $orchestratorVersion\n}\n\nfunction get_api_version() {\n\t[[ ! -z \"${CLUSTER_DEFINITION:-}\" ]] || (echo \"Must specify CLUSTER_DEFINITION\" && exit -1)\n\n\tapiVersion=$(jq -r 'getpath([\"apiVersion\"])' ${CLUSTER_DEFINITION})\n\tif [[ \"$apiVersion\" == \"null\" ]]; then\n\t\tapiVersion=\"\"\n\tfi\n\n\techo $apiVersion\n}\n\nfunction cleanup() {\n\tif [[ \"${CLEANUP:-}\" == \"y\" ]]; then\n\t\taz group delete --no-wait --name=\"${RESOURCE_GROUP}\" --yes || true\n\tfi\n}\n", "num_lines": 219}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n\n###############################################################################\n\nset -e\nset -u\nset -o pipefail\n\nROOT=\"${DIR}/..\"\n\n# Usage:\n#\n# Manual user usage (Specific name):\n#   export INSTANCE_NAME=official-jenkins-infra\n#   ./scripts/deploy.sh ./examples/kubernetes.json\n#\n# Manual user usage (Lots of rapid fire):\n# In this mode, the user can repeat the same deploy\n# command blindly and get new clusters each time.\n#   unset INSTANCE_NAME\n#   vim ./test/user.env (add your stuff)\n#   ./scripts/deploy.sh ./examples.kubernetes.json\n#   sleep 1\n#   ./scripts/deploy.sh ./examples.kubernetes.json\n#\n# Prow:\n#   export PULL_NUMBER=...\n#   export VALIDATE=<script path>\n#   export CLUSTER_DEFIITION=examples/kubernetes.json\n#   ./scripts/deploy.sh\n\n# Load any user set environment\nif [[ -f \"${ROOT}/test/user.env\" ]]; then\n\tsource \"${ROOT}/test/user.env\"\nfi\n\n\n# Ensure Cluster Definition\nif [[ -z \"${CLUSTER_DEFINITION:-}\" ]]; then\n\tif [[ -z \"${1:-}\" ]]; then echo \"You must specify a parameterized apimodel.json clusterdefinition\"; exit -1; fi\n\tCLUSTER_DEFINITION=\"${1}\"\nfi\n\n# Set Instance Name for PR or random run\nif [[ ! -z \"${PULL_NUMBER:-}\" ]]; then\n\texport INSTANCE_NAME=\"${JOB_NAME}-${PULL_NUMBER}-$(printf \"%x\" $(date '+%s'))\"\n\t# if we're running a pull request, assume we want to cleanup unless the user specified otherwise\n\tif [[ -z \"${CLEANUP:-}\" ]]; then\n\t\texport CLEANUP=\"y\"\n\tfi\nelse\n\texport INSTANCE_NAME_DEFAULT=\"${INSTANCE_NAME_PREFIX}-$(printf \"%x\" $(date '+%s'))\"\n\texport INSTANCE_NAME=\"${INSTANCE_NAME:-${INSTANCE_NAME_DEFAULT}}\"\nfi\n\n# Let the example json.env file set any env vars it may need ahead of time\n# (For example, the `managed-identity/kubernetes.json.env` sets env vars for a\n# custom MSI-compatible build of Kubernetes, as well as the SP cred values.)\nENV_FILE=\"${CLUSTER_DEFINITION}.env\"\nif [ -e \"${ENV_FILE}\" ]; then\n  source \"${ENV_FILE}\"\nfi\n\n\n# Set extra parameters\nexport OUTPUT=\"${ROOT}/_output/${INSTANCE_NAME}\"\nexport RESOURCE_GROUP=\"${INSTANCE_NAME}\"\nexport DEPLOYMENT_NAME=\"${INSTANCE_NAME}\"\n\nsource \"${ROOT}/test/common.sh\"\n\n# Set custom dir so we don't clobber global 'az' config\nexport AZURE_CONFIG_DIR=\"$(mktemp -d)\"\ntrap 'rm -rf ${AZURE_CONFIG_DIR}' EXIT\n\nmake -C \"${ROOT}\" ci\ngenerate_template\nset_azure_account\ntrap cleanup EXIT\ndeploy_template\n\nif [[ -z \"${VALIDATE:-}\" ]]; then\n\texit 0\nfi\n\nexport SSH_KEY=\"${OUTPUT}/id_rsa\"\nexport KUBECONFIG=\"${OUTPUT}/kubeconfig/kubeconfig.${LOCATION}.json\"\n\n\"${ROOT}/${VALIDATE}\"\n\necho \"post-test...\"\n", "num_lines": 100}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n\n###############################################################################\n\nset -e\nset -o pipefail\n\nROOT=\"${DIR}/..\"\n\n# Check pre-requisites\n[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_ID:-}\" ]]             || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_ID\" && exit -1)\n[[ ! -z \"${SERVICE_PRINCIPAL_CLIENT_SECRET:-}\" ]]         || (echo \"Must specify SERVICE_PRINCIPAL_CLIENT_SECRET\" && exit -1)\n[[ ! -z \"${TENANT_ID:-}\" ]]                               || (echo \"Must specify TENANT_ID\" && exit -1)\n[[ ! -z \"${SUBSCRIPTION_ID:-}\" ]]                         || (echo \"Must specify SUBSCRIPTION_ID\" && exit -1)\n[[ ! -z \"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID:-}\" ]]     || (echo \"Must specify CLUSTER_SERVICE_PRINCIPAL_CLIENT_ID\" && exit -1)\n[[ ! -z \"${CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET:-}\" ]] || (echo \"Must specify CLUSTER_SERVICE_PRINCIPAL_CLIENT_SECRET\" && exit -1)\n[[ ! -z \"${STAGE_TIMEOUT_MIN:-}\" ]]                       || (echo \"Must specify STAGE_TIMEOUT_MIN\" && exit -1)\n[[ ! -z \"${TEST_CONFIG:-}\" ]]                             || (echo \"Must specify TEST_CONFIG\" && exit -1)\n\nmake bootstrap build\n\n${ROOT}/test/acs-engine-test/acs-engine-test -c ${TEST_CONFIG} -d ${ROOT} -e ${LOGERROR_CONFIG:-${ROOT}/test/acs-engine-test/acs-engine-errors.json} -j ${SA_NAME} -k ${SA_KEY}\n", "num_lines": 31}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n\n###############################################################################\n\nset -e\nset -u\nset -o pipefail\n\nROOT=\"${DIR}/..\"\n\nsource \"${ROOT}/test/common.sh\"\n\ncase $1 in\n\nset_azure_account)\n  set_azure_account\n;;\n\ncreate_resource_group)\n  create_resource_group\n;;\n\npredeploy)\n  ACSE_PREDEPLOY=${ACSE_PREDEPLOY:-}\n  if [ ! -z \"${ACSE_PREDEPLOY}\" ] && [ -x \"${ACSE_PREDEPLOY}\" ]; then\n      \"${ACSE_PREDEPLOY}\"\n  fi\n;;\n\npostdeploy)\n  ACSE_POSTDEPLOY=${ACSE_POSTDEPLOY:-}\n  if [ ! -z \"${ACSE_POSTDEPLOY}\" ] && [ -x \"${ACSE_POSTDEPLOY}\" ]; then\n      \"${ACSE_POSTDEPLOY}\"\n  fi\n;;\n\ngenerate_template)\n  export OUTPUT=\"${ROOT}/_output/${INSTANCE_NAME}\"\n  generate_template\n;;\n\ndeploy_template)\n  export OUTPUT=\"${ROOT}/_output/${INSTANCE_NAME}\"\n  deploy_template\n;;\n\nget_node_count)\n  export OUTPUT=\"${ROOT}/_output/${INSTANCE_NAME}\"\n  get_node_count\n;;\n\nget_orchestrator_type)\n  get_orchestrator_type\n;;\n\nget_orchestrator_release)\n  get_orchestrator_release\n;;\n\nvalidate)\n  export OUTPUT=\"${ROOT}/_output/${INSTANCE_NAME}\"\n  export SSH_KEY=\"${OUTPUT}/id_rsa\"\n  if [ ${ORCHESTRATOR} = \"kubernetes\" ]; then\n    export KUBECONFIG=\"${OUTPUT}/kubeconfig/kubeconfig.${LOCATION}.json\"\n  fi\n  \"${ROOT}/test/cluster-tests/${ORCHESTRATOR}/test.sh\"\n;;\n\ncleanup)\n  export CLEANUP=\"${CLEANUP:-y}\"\n  cleanup\n;;\nesac\n", "num_lines": 82}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\nset -eu -o pipefail\nset -x\n\ngit init .\ngit clean -dfx\ngit reset --hard\ngit config --local user.name 'ACS Bot'\ngit config --local user.email 'acs-bot@microsoft.com'\ngit fetch --tags https://github.com/${REPO_OWNER}/${REPO_NAME} master +refs/pull/${PULL_NUMBER}/head:refs/pr/${PULL_NUMBER}\ngit checkout -B test \"${PULL_BASE_SHA}\"\ngit merge --no-ff -m \"Merge +refs/pull/${PULL_NUMBER}/head:refs/pr/${PULL_NUMBER}\" \"${PULL_PULL_SHA}\"\n\necho \"----------------------------------------------------------\"\nenv\necho \"----------------------------------------------------------\"\n", "num_lines": 28}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "\nfunction log {\n  local message=\"$1\"\n  local caller=\"$(caller 0)\"\n  now=$(date +\"%D %T %Z\")\n\n  if [[ ! -z \"${LOGFILE:-}\" ]]; then\n    echo \"[${now}] [${caller}] ${message}\" | tee -a ${LOGFILE}\n  else\n    echo \"[${now}] [${caller}] ${message}\"\n  fi\n}\n", "num_lines": 13}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\n# do not use 'set -e'\n# -o pipefail\nset -x\n\nsource \"$DIR/../utils.sh\"\n\nENV_FILE=\"${CLUSTER_DEFINITION}.env\"\nif [ -e \"${ENV_FILE}\" ]; then\n  source \"${ENV_FILE}\"\nfi\n\nMARATHON_JSON=\"${MARATHON_JSON:-marathon.json}\"\n\nremote_exec=\"ssh -i \"${SSH_KEY}\" -o ConnectTimeout=30 -o StrictHostKeyChecking=no azureuser@${INSTANCE_NAME}.${LOCATION}.cloudapp.azure.com -p2200\"\nagentFQDN=\"${INSTANCE_NAME}0.${LOCATION}.cloudapp.azure.com\"\nremote_cp=\"scp -i \"${SSH_KEY}\" -P 2200 -o StrictHostKeyChecking=no\"\n\nfunction teardown {\n  ${remote_exec} ./dcos marathon app remove /web\n}\n\n###### Check node count\nfunction check_node_count() {\n  log \"Checking node count\"\n  count=20\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    node_count=$(${remote_exec} curl -s http://localhost:1050/system/health/v1/nodes | jq '.nodes | length')\n    [ $? -eq 0 ] && [ ! -z \"$node_count\" ] && [ $node_count -eq ${EXPECTED_NODE_COUNT} ] && log \"Successfully got $EXPECTED_NODE_COUNT nodes\" && break\n    sleep 30; count=$((count-1))\n  done\n  if (( $node_count != ${EXPECTED_NODE_COUNT} )); then\n    log \"gave up waiting for DCOS nodes: $node_count available, ${EXPECTED_NODE_COUNT} expected\"\n    exit 1\n  fi\n}\n\ncheck_node_count\n\nlog \"Downloading dcos\"\n${remote_exec} curl -O https://dcos-mirror.azureedge.net/binaries/cli/linux/x86-64/dcos-1.10/dcos\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to download dcos\"; exit 1; fi\nlog \"Setting dcos permissions\"\n${remote_exec} chmod a+x ./dcos\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to chmod dcos\"; exit 1; fi\nlog \"Configuring dcos\"\n${remote_exec} ./dcos cluster setup http://localhost:80\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to configure dcos\"; exit 1; fi\n\nlog \"Copying marathon.json\"\n\n${remote_cp} \"${DIR}/${MARATHON_JSON}\" azureuser@${INSTANCE_NAME}.${LOCATION}.cloudapp.azure.com:marathon.json\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to copy marathon.json\"; exit 1; fi\n\n# feed agentFQDN to marathon.json\nlog \"Configuring marathon.json\"\n${remote_exec} sed -i \"s/{agentFQDN}/${agentFQDN}/g\" marathon.json\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to configure marathon.json\"; exit 1; fi\n\n\nlog \"Adding marathon app\"\ncount=20\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  ${remote_exec} ./dcos marathon app list | grep /web\n  retval=$?\n  if [[ $retval -eq 0 ]]; then log \"Marathon App successfully installed\" && break; fi\n  ${remote_exec} ./dcos marathon app add marathon.json\n  retval=$?\n  if [[ \"$retval\" == \"0\" ]]; then break; fi\n  sleep 15; count=$((count-1))\ndone\nif [[ $retval -ne 0 ]]; then log \"gave up waiting for marathon to be added\"; exit 1; fi\n\n# only need to teardown if app added successfully\ntrap teardown EXIT\n\nlog \"Validating marathon app\"\ncount=0\nwhile [[ ${count} -lt 25 ]]; do\n  count=$((count+1))\n  log \"  ... cycle $count\"\n  running=$(${remote_exec} ./dcos marathon app show /web | jq .tasksRunning)\n  if [[ \"${running}\" == \"3\" ]]; then\n    log \"Found 3 running tasks\"\n    break\n  fi\n  sleep ${count}\ndone\n\nif [[ \"${running}\" != \"3\" ]]; then\n  log \"marathon validation failed\"\n  ${remote_exec} ./dcos marathon app show /web\n  ${remote_exec} ./dcos marathon app list\n  exit 1\nfi\n\n# install marathon-lb\n${remote_exec} ./dcos package install marathon-lb --yes\nif [[ \"$?\" != \"0\" ]]; then log \"Failed to install marathon-lb\"; exit 1; fi\n\n# curl simpleweb through external haproxy\nlog \"Checking Service\"\ncount=20\nwhile true; do\n  log \"  ... counting down $count\"\n  rc=$(curl -sI --max-time 60 \"http://${agentFQDN}\" | head -n1 | cut -d$' ' -f2)\n  [[ \"$rc\" -eq \"200\" ]] && log \"Successfully hitting simpleweb through external haproxy http://${agentFQDN}\" && break\n  if [[ \"${count}\" -le 1 ]]; then\n    log \"failed to get expected response from nginx through the loadbalancer: Error $rc\"\n    exit 1\n  fi\n  sleep 15; count=$((count-1))\ndone\n", "num_lines": 127}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "function test_linux_deployment() {\n  ###### Testing an nginx deployment\n  log \"Testing deployments\"\n  kubectl create namespace ${namespace}\n\n  NGINX=\"docker.io/library/nginx:latest\"\n  IMAGE=\"${NGINX}\" # default to the library image unless we're in TEST_ACR mode\n  if [[ \"${TEST_ACR}\" == \"y\" ]]; then\n    # force it to pull from ACR\n    IMAGE=\"${ACR_REGISTRY}/test/nginx:latest\"\n    # wait for acr\n    wait\n    # TODO: how to do this without polluting user home dir?\n    docker login --username=\"${SERVICE_PRINCIPAL_CLIENT_ID}\" --password=\"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \"${ACR_REGISTRY}\"\n    docker pull \"${NGINX}\"\n    docker tag \"${NGINX}\" \"${IMAGE}\"\n    docker push \"${IMAGE}\"\n  fi\n\n  kubectl run --image=\"${IMAGE}\" nginx --namespace=${namespace} --overrides='{ \"apiVersion\": \"extensions/v1beta1\", \"spec\":{\"template\":{\"spec\": {\"nodeSelector\":{\"beta.kubernetes.io/os\":\"linux\"}}}}}'\n  count=12\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    running=$(kubectl get pods --namespace=${namespace} | grep nginx | grep Running | wc | awk '{print $1}')\n    if (( ${running} == 1 )); then break; fi\n      sleep 5; count=$((count-1))\n  done\n  if (( ${running} != 1 )); then\n    log \"K8S-Linux: gave up waiting for deployment\"\n    kubectl get all --namespace=${namespace}\n    exit 1\n  fi\n\n  kubectl expose deployments/nginx --type=LoadBalancer --namespace=${namespace} --port=80\n\n  log \"Checking Service External IP\"\n  count=60\n  external_ip=\"\"\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    external_ip=$(kubectl get svc --namespace ${namespace} nginx --template=\"{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}\" || echo \"\")\n    [[ ! -z \"${external_ip}\" ]] && break\n    sleep 10; count=$((count-1))\n  done\n  if [[ -z \"${external_ip}\" ]]; then\n    log \"K8S-Linux: gave up waiting for loadbalancer to get an ingress ip\"\n    exit 1\n  fi\n\n  log \"Checking Service\"\n  count=5\n  success=\"n\"\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    ret=$(curl -f --max-time 60 \"http://${external_ip}\" | grep 'Welcome to nginx!' || echo \"curl_error\")\n    if [[ $ret =~ .*'Welcome to nginx!'.* ]]; then\n      success=\"y\"\n      break\n    fi\n    sleep 5; count=$((count-1))\n  done\n  if [[ \"${success}\" != \"y\" ]]; then\n    log \"K8S-Linux: failed to get expected response from nginx through the loadbalancer\"\n    exit 1\n  fi\n}\n\nfunction test_windows_deployment() {\n  ###### Testing a simpleweb windows deployment\n  log \"Testing Windows deployments\"\n\n  log \"Creating simpleweb service\"\n  kubectl apply -f \"$DIR/simpleweb-windows.yaml\"\n  count=90\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    running=$(kubectl get pods --namespace=default | grep win-webserver | grep Running | wc | awk '{print $1}')\n    if (( ${running} == 1 )); then break; fi\n    sleep 10; count=$((count-1))\n  done\n  if (( ${running} != 1 )); then\n    log \"K8S-Windows: gave up waiting for deployment\"\n    kubectl get all --namespace=default\n    exit 1\n  fi\n\n  log \"Checking Service External IP\"\n  count=60\n  external_ip=\"\"\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    external_ip=$(kubectl get svc --namespace default win-webserver --template=\"{{range .status.loadBalancer.ingress}}{{.ip}}{{end}}\" || echo \"\")\n    [[ ! -z \"${external_ip}\" ]] && break\n    sleep 10; count=$((count-1))\n  done\n  if [[ -z \"${external_ip}\" ]]; then\n    log \"K8S-Windows: gave up waiting for loadbalancer to get an ingress ip\"\n    exit 1\n  fi\n\n  log \"Checking Service\"\n  count=5\n  success=\"n\"\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    ret=$(curl -f --max-time 60 \"http://${external_ip}\" | grep 'Windows Container Web Server' || echo \"curl_error\")\n    if [[ $ret =~ .*'Windows Container Web Server'.* ]]; then\n      success=\"y\"\n      break\n    fi\n    sleep 10; count=$((count-1))\n  done\n  if [[ \"${success}\" != \"y\" ]]; then\n    log \"K8S-Windows: failed to get expected response from simpleweb through the loadbalancer\"\n    exit 1\n  fi\n\n  log \"Checking outbound connection\"\n  count=10\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    winpodname=$(kubectl get pods --namespace=default | grep win-webserver | awk '{print $1}')\n    [[ ! -z \"${winpodname}\" ]] && break\n    sleep 10; count=$((count-1))\n  done\n  if [[ -z \"${winpodname}\" ]]; then\n    log \"K8S-Windows: failed to get expected pod name for simpleweb\"\n    exit 1\n  fi\n\n  log \"query DNS\"\n  count=0 # disabled while outbound connection bug is present\n  success=\"y\" # disabled while outbound connection bug is present\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    query=$(kubectl exec $winpodname -- powershell nslookup www.bing.com)\n    if [[ $(echo ${query} | grep \"DNS request timed out\" | wc -l) == 0 ]] && [[ $(echo ${query} | grep \"UnKnown\" | wc -l) == 0 ]]; then\n      success=\"y\"\n      break\n    fi\n    sleep 10; count=$((count-1))\n  done\n\n  # temporarily disable breaking on errors to allow the retry\n  set +e\n  log \"curl external website\"\n  count=0 # disabled while outbound connection bug is present\n  success=\"y\" # disabled while outbound connection bug is present\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    # curl without getting status first and see the response. getting status sometimes has the problem to hang\n    # and it doesn't repro when running kubectl from the node\n    kubectl exec $winpodname -- powershell iwr -UseBasicParsing -TimeoutSec 60 www.bing.com\n    statuscode=$(kubectl exec $winpodname -- powershell iwr -UseBasicParsing -TimeoutSec 60 www.bing.com | grep StatusCode)\n    if [[ ${statuscode} != \"\" ]] && [[ $(echo ${statuscode} | grep 200 | awk '{print $3}' | tr -d '\\r') -eq \"200\" ]]; then\n      log \"got 200 status code\"\n      log \"${statuscode}\"\n      success=\"y\"\n      break\n    fi\n    log \"curl failed, retrying...\"\n    ipconfig=$(kubectl exec $winpodname -- powershell ipconfig /all)\n    log \"$ipconfig\"\n    # TODO: reduce sleep time when outbound connection delay is fixed\n    sleep 100; count=$((count-1))\n  done\n  set -e\n  if [[ \"${success}\" != \"y\" ]]; then\n    nslookup=$(kubectl exec $winpodname -- powershell nslookup www.bing.com)\n    log \"$nslookup\"\n    log \"getting the last 50 events to check timeout failure\"\n    hdr=$(kubectl get events | head -n 1)\n    log \"$hdr\"\n    evt=$(kubectl get events | tail -n 50)\n    log \"$evt\"\n    log \"K8S-Windows: failed to get outbound internet connection inside simpleweb container\"\n    exit 1\n  else\n    log \"outbound connection succeeded!\"\n  fi\n}\n", "num_lines": 182}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\n# exit on errors\nset -e\n# exit on unbound variables\nset -u\n# verbose logging\nset -x\n\nsource \"$DIR/../utils.sh\"\nsource \"$DIR/k8s-utils.sh\"\n\nENV_FILE=\"${CLUSTER_DEFINITION}.env\"\nif [ -e \"${ENV_FILE}\" ]; then\n  source \"${ENV_FILE}\"\nfi\n\nEXPECTED_NODE_COUNT=\"${EXPECTED_NODE_COUNT:-4}\"\nEXPECTED_LINUX_AGENTS=\"${EXPECTED_LINUX_AGENTS:-3}\"\nEXPECTED_WINDOWS_AGENTS=\"${EXPECTED_WINDOWS_AGENTS:-0}\"\nEXPECTED_DNS=\"${EXPECTED_DNS:-2}\"\nEXPECTED_DASHBOARD=\"${EXPECTED_DASHBOARD:-1}\"\nEXPECTED_RESCHEDULER=\"${EXPECTED_RESCHEDULER:-0}\"\nEXPECTED_ORCHESTRATOR_VERSION=\"${EXPECTED_ORCHESTRATOR_VERSION:-}\"\n\nKUBE_PROXY_COUNT=$((EXPECTED_NODE_COUNT-$EXPECTED_WINDOWS_AGENTS))\n\n# set TEST_ACR to \"y\" for ACR testing\nTEST_ACR=\"${TEST_ACR:-n}\"\n\nnamespace=\"namespace-${RANDOM}\"\nlog \"Running test in namespace: ${namespace}\"\ntrap teardown EXIT\n\nfunction teardown {\n  kubectl get all --all-namespaces || echo \"teardown error\"\n  kubectl get nodes || echo \"teardown error\"\n  kubectl get namespaces || echo \"teardown error\"\n  kubectl delete namespaces ${namespace} || echo \"teardown error\"\n}\n\n# TODO: cleanup the loops more\n# TODO: the wc|awk business can just be kubectl with an output format and wc -l\n\n###### Deploy ACR\nif [[ \"${TEST_ACR}\" == \"y\" ]]; then\n\tACR_NAME=\"${INSTANCE_NAME//[-._]/}1\"\n\tACR_REGISTRY=\"${ACR_NAME}-microsoft.azurecr.io\" # fix this for non-ms tenant users\n\tif ! az acr show --resource-group \"${RESOURCE_GROUP}\" --name \"${ACR_NAME}\" ; then\n\t\taz acr create --location \"${LOCATION}\" --resource-group \"${RESOURCE_GROUP}\" --name \"${ACR_NAME}\" &\n\tfi\nfi\n\n###### Check node count\nfunction check_node_count() {\n  log \"Checking node count\"\n  count=120\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    node_count=$(kubectl get nodes --no-headers | grep -v NotReady | grep Ready | wc | awk '{print $1}')\n    if (( ${node_count} == ${EXPECTED_NODE_COUNT} )); then break; fi\n    sleep 5; count=$((count-1))\n  done\n  if (( $node_count != ${EXPECTED_NODE_COUNT} )); then\n    log \"K8S: gave up waiting for apiserver / node counts\"; exit 1\n  fi\n}\n\ncheck_node_count\n\n###### Validate Kubernetes version\nkubernetes_version=$(kubectl version --short)\nDASHBOARD_PORT=80\nif [[ ${kubernetes_version} == *\"Server Version: v1.9.\"* ]]; then\n  DASHBOARD_PORT=443\nfi\nlog \"Setting dashboard port to ${DASHBOARD_PORT}\"\n\nlog \"Checking Kubernetes version. Expected: ${EXPECTED_ORCHESTRATOR_VERSION}\"\nif [ ! -z \"${EXPECTED_ORCHESTRATOR_VERSION}\" ]; then\n  if [[ ${kubernetes_version} != *\"Server Version: v${EXPECTED_ORCHESTRATOR_VERSION}\"* ]]; then\n    log \"K8S: unexpected kubernetes version:\\n${kubernetes_version}\"; exit 1\n  fi\nfi\n\n###### Wait for no more container creating\nlog \"Checking containers being created\"\ncount=60\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  creating_count=$(kubectl get nodes --no-headers | grep 'CreatingContainer' | wc | awk '{print $1}')\n  if (( ${creating_count} == 0 )); then break; fi\n  sleep 5; count=$((count-1))\ndone\nif (( ${creating_count} != 0 )); then\n  log \"K8S: gave up waiting for containers\"; exit 1\nfi\n\n###### Check existence and status of essential pods\n\n# we test other essential pods (kube-dns, kube-proxy) separately\npods=\"heapster kube-addon-manager kube-apiserver kube-controller-manager kube-scheduler tiller\"\nif (( ${EXPECTED_RESCHEDULER} != 0 )); then\n    pods=\"$pods rescheduler\"\nfi\nlog \"Checking $pods\"\n\ncount=60\nwhile (( $count > 0 )); do\n  for pod in $pods; do\n    running=$(kubectl get pods --all-namespaces | grep $pod | grep Running | wc -l)\n    if (( $running > 0 )); then\n      log \"... $pod is Running\"\n      pods=$(echo $pods | sed -e \"s/ *$pod */ /\")\n    fi\n  done\n  if [ -z \"$(echo $pods | tr -d '[:space:]')\" ]; then\n    break\n  fi\n  sleep 5; count=$((count-1))\ndone\n\nif [ ! -z \"$(echo $pods | tr -d '[:space:]')\" ]; then\n  log \"K8S: gave up waiting for running pods [$pods]\"; exit 1\nfi\n\n###### Check for Kube-DNS\nlog \"Checking Kube-DNS\"\ncount=60\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  running=$(kubectl get pods --namespace=kube-system | grep kube-dns | grep Running | wc | awk '{print $1}')\n  if (( ${running} == ${EXPECTED_DNS} )); then break; fi\n  sleep 5; count=$((count-1))\ndone\nif (( ${running} != ${EXPECTED_DNS} )); then\n  log \"K8S: gave up waiting for kube-dns\"; exit 1\nfi\n\n###### Check for Kube-Dashboard\nif (( ${EXPECTED_DASHBOARD} != 0 )); then\n  log \"Checking Kube-Dashboard\"\n  count=60\n  while (( $count > 0 )); do\n    log \"  ... counting down $count\"\n    running=$(kubectl get pods --namespace=kube-system | grep kubernetes-dashboard | grep Running | wc | awk '{print $1}')\n    if (( ${running} == ${EXPECTED_DASHBOARD} )); then break; fi\n    sleep 5; count=$((count-1))\n  done\n  if (( ${running} != ${EXPECTED_DASHBOARD} )); then\n    log \"K8S: gave up waiting for kubernetes-dashboard\"; exit 1\n  fi\nelse\n  log \"Expecting no dashboard\"\nfi\n\n###### Check for Kube-Proxys\nlog \"Checking Kube-Proxys\"\ncount=60\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  running=$(kubectl get pods --namespace=kube-system | grep kube-proxy | grep Running | wc | awk '{print $1}')\n  if (( ${running} == ${KUBE_PROXY_COUNT} )); then break; fi\n  sleep 5; count=$((count-1))\ndone\nif (( ${running} != ${KUBE_PROXY_COUNT} )); then\n  log \"K8S: gave up waiting for kube-proxy\"; exit 1\nfi\n\nif ! [ $EXPECTED_WINDOWS_AGENTS -gt 0 ] ; then\n  if (( ${EXPECTED_DASHBOARD} != 0 )); then\n    # get master public hostname\n    master=$(kubectl config view | grep server | cut -f 3- -d \"/\" | tr -d \" \")\n    # get dashboard port\n    port=$(kubectl get svc --namespace=kube-system | grep dashboard | awk '{print $4}' | sed -n 's/^'${DASHBOARD_PORT}':\\(.*\\)\\/TCP$/\\1/p')\n    # get internal IPs of the nodes\n    ips=$(kubectl get nodes --all-namespaces -o yaml | grep -B 1 InternalIP | grep address | awk '{print $3}')\n\n    for ip in $ips; do\n      log \"Probing IP address ${ip}\"\n      count=60\n      success=\"n\"\n      while (( $count > 0 )); do\n        log \"  ... counting down $count\"\n        ret=$(ssh -i \"${OUTPUT}/id_rsa\" -o ConnectTimeout=30 -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null \"azureuser@${master}\" \"curl --max-time 60 http://${ip}:${port}\" || echo \"curl_error\")\n        if [[ ! $ret =~ .*curl_error.* ]]; then\n          success=\"y\"\n          break\n        fi\n        if (( $count < 2 )); then\n            log $ret\n        fi\n        sleep 5; count=$((count-1))\n      done\n      if [[ \"${success}\" == \"n\" ]]; then\n        log \"K8S: gave up verifying proxy\"; exit 1\n      fi\n    done\n  fi\nfi\n\nif [ $EXPECTED_LINUX_AGENTS -gt 0 ] ; then\n  test_linux_deployment\nfi\n\nif [ $EXPECTED_WINDOWS_AGENTS -gt 0 ] ; then\n  test_windows_deployment\nfi\n\ncheck_node_count\n", "num_lines": 221}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\n# do not use 'set -e'\nset -x\nset -u\n\nsource \"$DIR/../utils.sh\"\n\nSSH=\"ssh -i ${SSH_KEY} -o ConnectTimeout=30 -o StrictHostKeyChecking=no -p2200 azureuser@${INSTANCE_NAME}.${LOCATION}.cloudapp.azure.com\"\n\ndeploy=\"docker -H :2375 run -d -p 80:80 yeasy/simple-web\"\nwait_duration=10\ntotal_loops=30\nwhile true; do\n  # || true is used to suppress the failure like \"Error response from daemon: No elected primary cluster manager\"\n  # it should be gone after a few retries\n  containerId=\"$($SSH $deploy 2>/dev/null )\" || true\n  [[ ! -z $containerId ]] && [[ \"$(echo $containerId | grep '[0-9a-z]\\{64\\}')\" ]] && log \"container deployed! containerId is $containerId\" && break\n  log \"Validation: Expected to get containerId. $(($total_loops*$wait_duration)) seconds remain\"\n  sleep $wait_duration\n  total_loops=$((total_loops-1))\n  if [ $total_loops -eq 0 ]; then\n      log \"Swarm validation failed: timeout\"; exit 1;\n  fi\ndone\n\nresult=$($SSH curl localhost:2375/containers/json | jq \"[.[].Id==\\\"$containerId\\\"] | any\")\n\nif [ \"$result\" != \"true\" ]; then\n  log \"Swarm validation failed: container not found\"; exit 1;\nfi\n\nlog \"Swarm validation completed\"\n", "num_lines": 44}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n####################################################\n\n# do not use 'set -e'\nset -x\nset -u\n\n\nsource \"$DIR/../utils.sh\"\n\nssh_args=\"-i ${SSH_KEY} -o ConnectTimeout=30 -o StrictHostKeyChecking=no -p2200 azureuser@${INSTANCE_NAME}.${LOCATION}.cloudapp.azure.com\"\n\nfunction teardown {\n  ssh ${ssh_args} docker service rm nginx\n  sleep 10\n  ssh ${ssh_args} docker network rm network\n}\n\ntrap teardown EXIT\n\nlog \"Starting swarmmode deployment validation in ${LOCATION}\"\nsleep 30\nlog \"Creating network\"\nwait=10\ncount=12\nargs=\"${ssh_args} docker network create --driver overlay --subnet 10.0.9.0/24 --opt encrypted network\"\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  timeout -k 60s -s KILL 60s ssh $args\n  retval=$?\n  if [[ \"$retval\" == \"0\" ]]; then break; fi\n  sleep $wait\n  count=$((count-1))\ndone\nif [[ \"$retval\" != \"0\" ]]; then\n  log \"DockerCE: gave up waiting for network to be created\"\n  exit 1\nfi\n\nlog \"Creating service\"\nwait=5\ncount=12\nargs=\"${ssh_args} docker service create --replicas 3 --name nginx --network network --publish 80:80 nginx\"\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  ssh $args\n  retval=$?\n  if [[ \"$retval\" == \"0\" ]]; then break; fi\n  sleep $wait\n  count=$((count-1))\ndone\nif [[ \"$retval\" != \"0\" ]]; then\n  log \"DockerCE: gave up waiting for service to be created\"\n  exit 1\nfi\n\nsleep 10\nlog \"Testing service\"\nwait=5\ncount=12\nwhile (( $count > 0 )); do\n  log \"  ... counting down $count\"\n  curl --fail \"http://${INSTANCE_NAME}0.${LOCATION}.cloudapp.azure.com:80/\"\n  retval=$?\n  if [[ \"$retval\" == \"0\" ]]; then break; fi\n  sleep $wait\n  count=$((count-1))\ndone\nif [[ \"$retval\" != \"0\" ]]; then\n  log \"DockerCE: gave up waiting for service to be externally reachable\"\n  exit 1\nfi\n", "num_lines": 82}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_ID\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID_TO_CLEANUP\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID_TO_CLEANUP env var\"\n    exit 1;\nfi\n\nif [ -z \"$EXPIRATION_IN_HOURS\" ]; then\n    EXPIRATION_IN_HOURS=2\nfi\n\naz login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null\n\n# set to the sub id we want to cleanup\naz account set -s $SUBSCRIPTION_ID_TO_CLEANUP\n\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n# find resource groups created before our deadline\necho \"Looking for resource groups created over ${EXPIRATION_IN_HOURS} hours ago...\"\nfor resourceGroup in `az group list | jq --arg dl $deadline '.[] | select(.name | contains(\"acse-test\") | not) | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"`; do\n    for deployment in `az group deployment list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || \"\"`; do\n        echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n        az group deployment delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\ndone", "num_lines": 51}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource \"${HOME}/test/common.sh\"\n\nfunction shunittest_deploy_template {\n  set -eux -o pipefail\n\n  export OUTPUT=\"${HOME}/_output/${INSTANCE_NAME}\"\n\n  deploy_template\n}\n", "num_lines": 12}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource \"${HOME}/test/common.sh\"\n\nfunction shunittest_generate_template {\n  set -eux -o pipefail\n\n  export OUTPUT=\"${HOME}/_output/${INSTANCE_NAME}\"\n\n  generate_template\n}\n", "num_lines": 12}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource \"${HOME}/test/common.sh\"\n\nfunction shunittest_scale_agent_pool {\n  set -eux -o pipefail\n\n  export OUTPUT=\"${HOME}/_output/${INSTANCE_NAME}\"\n\n  scale_agent_pool\n}\n", "num_lines": 12}
{"repo_name": "acs-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction shunittest_validate_deployment {\n  set -eux -o pipefail\n\n  export OUTPUT=\"${HOME}/_output/${INSTANCE_NAME}\"\n  export SSH_KEY=\"${OUTPUT}/id_rsa\"\n  if [[ \"${ORCHESTRATOR}\" == \"kubernetes\" ]]; then\n    export KUBECONFIG=\"${OUTPUT}/kubeconfig/kubeconfig.${LOCATION}.json\"\n    nodes=$(${HOME}/test/step.sh get_node_count)\n    IFS=':' read -a narr <<< \"${nodes}\"\n    export EXPECTED_NODE_COUNT=${narr[0]}\n    export EXPECTED_LINUX_AGENTS=${narr[1]}\n    export EXPECTED_WINDOWS_AGENTS=${narr[1]}\n    export EXPECTED_ORCHESTRATOR_VERSION=$(${HOME}/test/step.sh get_orchestrator_release)\n  fi\n\n  script=\"${HOME}/test/cluster-tests/${ORCHESTRATOR}/test.sh\"\n\n  if [ -x \"${script}\" ]; then\n    \"${script}\"\n  else\n    echo \"${script}: not an executable or no such file\"\n    exit 1\n  fi\n}\n", "num_lines": 27}
{"repo_name": "ACSS-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# <copyright file=\"DownloadDeployerVMPackages.sh\" company=\"Microsoft Corporation\">\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# </copyright>\n\n#!/bin/bash\n\n#Exit when any command fails\nset -e\n\n#download packages locally\n\nworkloadWorkdir=DeployerVMPackages\n\nif [[ ! -d \"$workloadWorkdir\" ]]; then\n        mkdir $workloadWorkdir\nfi\n\nif [[ ! -d \"$workloadWorkdir/packages\" ]]; then\n        mkdir $workloadWorkdir/packages\nfi\n\n#download python3-pip\ncd $workloadWorkdir/packages\n\nif [[ ! -f \"pip-21.3.1.tar.gz\" ]]; then\n        wget -nv -q https://files.pythonhosted.org/packages/da/f6/c83229dcc3635cdeb51874184241a9508ada15d8baa337a41093fab58011/pip-21.3.1.tar.gz\n        tar -xvf pip-21.3.1.tar.gz\nfi\n\ncd pip-21.3.1/\n\n#Check if pip3 is already installed\nif [[ -z $(which pip3) ]]; then\n        #Install pip\n        echo \"Installing pip3.\"\n        sudo python3 setup.py install\nfi\n\ncd ../../..\n#download wheel\npip3 download -d $workloadWorkdir/packages wheel==0.37.1\n\n#download netaddr\npip3 download -d $workloadWorkdir/packages netaddr==0.8.0\n\n#download jq 1.6\nif [[ ! -d \"$workloadWorkdir/jq_pkg\" ]]; then\n        mkdir $workloadWorkdir/jq_pkg\nfi\n\ncd $workloadWorkdir/jq_pkg\nwget -O jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64\nchmod +x jq\n\ncd -\n#download ansible\nif [[ ! -d \"$workloadWorkdir/ansible_pkg\" ]]; then\n        mkdir $workloadWorkdir/ansible_pkg\nfi\npip3 download -d $workloadWorkdir/ansible_pkg \"ansible==2.9.27\"\n\n#download azure cli libraries\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg\nfi\n\ncd $workloadWorkdir/azure_cli_pkg\nwget -nv -q https://raw.githubusercontent.com/Azure/azure-cli/azure-cli-2.30.0/src/azure-cli/requirements.py3.Linux.txt\n\ncd -\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg/azure_cli_requirements\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\nfi\n\npip3 download -r $workloadWorkdir/azure_cli_pkg/requirements.py3.Linux.txt -d $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\n\n#Check if zip is already installed\nif [[ -z $(which zip) ]]; then\n        echo \"Installing zip package.\"\n        #Install zip\n        sudo apt-get --assume-yes install zip\nfi\n\nzip -r $workloadWorkdir.zip $workloadWorkdir\n\n#Check if user have an existing storage account\necho \"Do you have an existing storage account?\"\necho -n \"y/n: \"\nread -r userInput\n\nif [[ ${userInput^^} == \"Y\" ]]; then\n        #sapbits_location_base_path  \n        echo \"Enter the SAP storage account base path(sapbits-location-base-path) url copied from storage container properties. This is the storage container where SAP installation bits and deployer vm packages are stored/will be stored.\"\n        read -r sapbits_location_base_path\n\n        #check if customer entered an empty string\n        while [ -z $sapbits_location_base_path ]\n        do    \n            echo \"Empty sapbits-location-base-path given, please re-enter the SAP storage account base path(sapbits-location-base-path) url else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r sapbits_location_base_path\n\n            if [[ ${sapbits_location_base_path^^} == \"EXIT\" ]]; then\n                    exit 1\n            fi\n        done\n        IFS='//'\n        read -ra arr <<< $sapbits_location_base_path \n        container=${arr[3]} \n\n        IFS='.'\n        read -ra arr <<< ${arr[2]}\n        storageAccountName=${arr[0]} \n\n        #Fetch container name\n        IFS='\"'\n        read -ra arr <<< $container\n        containerName=${arr[0]}\nelse\n        #Storage account name\n        echo \"Enter the new storage account name you want to create.\"\n        read -r storageAccountName\n        while [ -z $storageAccountName ]\n        do    \n            echo \"Empty storage account name given, please re-enter the storage account name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r storageAccountName\n\n            if [[ ${storageAccountName^^} == \"EXIT\" ]]; then\n                    exit 2\n            fi\n        done  \n\n        #Check subscription\n        subscription=$(az account show --query name)\n        echo \"Current subscription is $subscription, do you want to change the subscription? This is the subscription where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the new subscription name or id. (Use az account list to get a list of subscriptions for the logged in account).\"\n                read -r subscription\n                az account set --subscription \"$subscription\"\n        fi\n\n        echo \"Do you want to use an existing resource group? This is the resource group where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the resource group name.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 3\n                    fi\n                done\n        else\n                echo \"Enter the new resource group name to create a new resource group.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 4\n                    fi\n                done\n\n                echo \"Enter the location where you want to create resource group.\"\n                read -r resourceGroupLocation\n                while [ -z $resourceGroupLocation ]\n                do    \n                    echo \"Empty resource group locaion given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupLocation\n\n                    if [[ ${resourceGroupLocation^^} == \"EXIT\" ]]; then\n                            exit 5\n                    fi\n                done\n                az group create --location $resourceGroupLocation --name $resourceGroupName\n        fi\n\n        echo \"Creating storage account $storageAccountName in resource group $resourceGroupName and subscription $subscription\"\n        az storage account create --name $storageAccountName --resource-group $resourceGroupName\n\n        #Container name\n        echo \"Enter the new container name you want to create.\"\n        read -r containerName\n        while [ -z $containerName ]\n        do    \n            echo \"Empty container name given, please re-enter the container name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r containerName\n\n            if [[ ${containerName^^} == \"EXIT\" ]]; then\n                    exit 6\n            fi\n        done\n        \n        echo \"Create container $containerName in storage account $storageAccountName\"\n        az storage container create --name $containerName --account-name $storageAccountName\nfi\n\n#sapbits-access-key\necho \"Enter the sapbits-access-key copied from storage account 'Access keys'.\"   \nread -r sapbits_access_key\n\n#Repeat while loop until customer enters a non empty sapbits-access-key\nwhile [ -z $sapbits_access_key ]\ndo\n    read -r sapbits_access_key\n    echo \"No sapbits-access-key detected, please re-enter the sapbits-access-key else press 'Ctrl+C' or type 'exit' to end the process.\"\n\n    if [[ ${sapbits_access_key^^} == \"EXIT\" ]]; then\n            exit 7\n    fi\ndone\n    \necho \"Storage account name where deployer vm packages are stored/will be stored: $storageAccountName.\"\necho \"Container name where deployer vm packages are stored/will be stored: $containerName/deployervmpackages.\"\n\nisBlobExists=$(az storage blob exists --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --query exists)\n\nif [[ $isBlobExists == \"false\" ]]; then\n        #upload to storage account\n        az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\nelse\n        echo \"Existing blob $workloadWorkdir.zip found in storage account, do you want to update the blob?\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                #delete existing blob\n                az storage blob delete --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip\n                az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\n        fi\nfi\n\n", "num_lines": 241}
{"repo_name": "ACSS-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# <copyright file=\"DownloadDeployerVMPackages.sh\" company=\"Microsoft Corporation\">\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# </copyright>\n\n#!/bin/bash\n\n#Exit when any command fails\nset -e\n\n#download packages locally\n\nworkloadWorkdir=DeployerVMPackages\n\nif [[ ! -d \"$workloadWorkdir\" ]]; then\n        mkdir $workloadWorkdir\nfi\n\nif [[ ! -d \"$workloadWorkdir/packages\" ]]; then\n        mkdir $workloadWorkdir/packages\nfi\n\n#download python3-pip\ncd $workloadWorkdir/packages\n\nif [[ ! -f \"pip-21.3.1.tar.gz\" ]]; then\n        wget -nv -q https://files.pythonhosted.org/packages/da/f6/c83229dcc3635cdeb51874184241a9508ada15d8baa337a41093fab58011/pip-21.3.1.tar.gz\n        tar -xvf pip-21.3.1.tar.gz\nfi\n\ncd pip-21.3.1/\n\n#Check if pip3 is already installed\nif [[ -z $(which pip3) ]]; then\n        #Install pip\n        echo \"Installing pip3.\"\n        sudo python3 setup.py install\nfi\n\ncd ../../..\n#download wheel\npip3 download -d $workloadWorkdir/packages wheel==0.37.1\n\n\n#download jq 1.6\nif [[ ! -d \"$workloadWorkdir/jq_pkg\" ]]; then\n        mkdir $workloadWorkdir/jq_pkg\nfi\n\ncd $workloadWorkdir/jq_pkg\nwget -O jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64\nchmod +x jq\n\ncd -\n#download ansible\nif [[ ! -d \"$workloadWorkdir/ansible_pkg\" ]]; then\n        mkdir $workloadWorkdir/ansible_pkg\nfi\npip3 download -d $workloadWorkdir/ansible_pkg \"ansible==2.9.27\"\n\n#download azure cli libraries\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg\nfi\n\ncd $workloadWorkdir/azure_cli_pkg\nwget -nv -q https://raw.githubusercontent.com/Azure/azure-cli/azure-cli-2.30.0/src/azure-cli/requirements.py3.Linux.txt\n\ncd -\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg/azure_cli_requirements\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\nfi\n\npip3 download -r $workloadWorkdir/azure_cli_pkg/requirements.py3.Linux.txt -d $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\n\n#Check if zip is already installed\nif [[ -z $(which zip) ]]; then\n        echo \"Installing zip package.\"\n        #Install zip\n        sudo apt-get --assume-yes install zip\nfi\n\nzip -r $workloadWorkdir.zip $workloadWorkdir\n\n#Check if user have an existing storage account\necho \"Do you have an existing storage account?\"\necho -n \"y/n: \"\nread -r userInput\n\nif [[ ${userInput^^} == \"Y\" ]]; then\n        #sapbits_location_base_path  \n        echo \"Enter the SAP storage account base path(sapbits-location-base-path) url copied from storage container properties. This is the storage container where SAP installation bits and deployer vm packages are stored/will be stored.\"\n        read -r sapbits_location_base_path\n\n        #check if customer entered an empty string\n        while [ -z $sapbits_location_base_path ]\n        do    \n            echo \"Empty sapbits-location-base-path given, please re-enter the SAP storage account base path(sapbits-location-base-path) url else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r sapbits_location_base_path\n\n            if [[ ${sapbits_location_base_path^^} == \"EXIT\" ]]; then\n                    exit 1\n            fi\n        done\n        IFS='//'\n        read -ra arr <<< $sapbits_location_base_path \n        container=${arr[3]} \n\n        IFS='.'\n        read -ra arr <<< ${arr[2]}\n        storageAccountName=${arr[0]} \n\n        #Fetch container name\n        IFS='\"'\n        read -ra arr <<< $container\n        containerName=${arr[0]}\nelse\n        #Storage account name\n        echo \"Enter the new storage account name you want to create.\"\n        read -r storageAccountName\n        while [ -z $storageAccountName ]\n        do    \n            echo \"Empty storage account name given, please re-enter the storage account name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r storageAccountName\n\n            if [[ ${storageAccountName^^} == \"EXIT\" ]]; then\n                    exit 2\n            fi\n        done  \n\n        #Check subscription\n        subscription=$(az account show --query name)\n        echo \"Current subscription is $subscription, do you want to change the subscription? This is the subscription where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the new subscription name or id. (Use az account list to get a list of subscriptions for the logged in account).\"\n                read -r subscription\n                az account set --subscription \"$subscription\"\n        fi\n\n        echo \"Do you want to use an existing resource group? This is the resource group where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the resource group name.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 3\n                    fi\n                done\n        else\n                echo \"Enter the new resource group name to create a new resource group.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 4\n                    fi\n                done\n\n                echo \"Enter the location where you want to create resource group.\"\n                read -r resourceGroupLocation\n                while [ -z $resourceGroupLocation ]\n                do    \n                    echo \"Empty resource group locaion given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupLocation\n\n                    if [[ ${resourceGroupLocation^^} == \"EXIT\" ]]; then\n                            exit 5\n                    fi\n                done\n                az group create --location $resourceGroupLocation --name $resourceGroupName\n        fi\n\n        echo \"Creating storage account $storageAccountName in resource group $resourceGroupName and subscription $subscription\"\n        az storage account create --name $storageAccountName --resource-group $resourceGroupName\n\n        #Container name\n        echo \"Enter the new container name you want to create.\"\n        read -r containerName\n        while [ -z $containerName ]\n        do    \n            echo \"Empty container name given, please re-enter the container name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r containerName\n\n            if [[ ${containerName^^} == \"EXIT\" ]]; then\n                    exit 6\n            fi\n        done\n        \n        echo \"Create container $containerName in storage account $storageAccountName\"\n        az storage container create --name $containerName --account-name $storageAccountName\nfi\n\n#sapbits-access-key\necho \"Enter the sapbits-access-key copied from storage account 'Access keys'.\"   \nread -r sapbits_access_key\n\n#Repeat while loop until customer enters a non empty sapbits-access-key\nwhile [ -z $sapbits_access_key ]\ndo\n    read -r sapbits_access_key\n    echo \"No sapbits-access-key detected, please re-enter the sapbits-access-key else press 'Ctrl+C' or type 'exit' to end the process.\"\n\n    if [[ ${sapbits_access_key^^} == \"EXIT\" ]]; then\n            exit 7\n    fi\ndone\n    \necho \"Storage account name where deployer vm packages are stored/will be stored: $storageAccountName.\"\necho \"Container name where deployer vm packages are stored/will be stored: $containerName/deployervmpackages.\"\n\nisBlobExists=$(az storage blob exists --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --query exists)\n\nif [[ $isBlobExists == \"false\" ]]; then\n        #upload to storage account\n        az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\nelse\n        echo \"Existing blob $workloadWorkdir.zip found in storage account, do you want to update the blob?\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                #delete existing blob\n                az storage blob delete --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip\n                az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\n        fi\nfi\n\n", "num_lines": 239}
{"repo_name": "active-learning-workshop", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Add RServer libraries to the R session config, but only after all libs are installed\n# sudo echo \"r-libs-user=/data/mlserver/9.2.1/libraries/RServer\" >>/etc/rstudio/rsession.conf\n\n# Enable the RStudio Server service\nsudo systemctl enable rstudio-server\n\n# Start the RStudio Server service\nsudo systemctl start rstudio-server\n\nsudo mkdir /data/active-learning-data\n\n# take ownership of /data/active-learning-data\nsudo chown -R remoteuser:remoteuser /data/active-learning-data\n\n# create conda environment\ncd text_featurization/lm_finetune\n/anaconda/bin/conda env create -f conda.yml\nsource /anaconda/bin/activate py35\npip install ipykernel\nsudo /anaconda/envs/embeddings/bin/python -m ipykernel install --name embeddings --display-name \"embeddings\"\n", "num_lines": 21}
{"repo_name": "adx-automation-client", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z $TRAVIS_TAG ]; then\n    echo \"Skip publishing since it is not a build triggered by a tag.\" >&2\n    exit 0\nfi\n\ncd dist\nwheel_file=`ls adx_automation_cli-*-py3-none-any.whl`\n\nversion=${wheel_file/adx_automation_cli-/}\nversion=${version/-py3-none-any.whl/}\necho $version\n\naz storage blob upload -c client -f $wheel_file -n archive/$wheel_file --validate-content --no-progress\naz storage blob url -c client -n archive/$wheel_file -otsv | tee ./blob_path\naz storage blob upload -c client -f ./blob_path -n latest --validate-content --no-progress\n", "num_lines": 18}
{"repo_name": "ADXIoTAnalytics", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Helper Functions\nfunction banner() {\n    clear\n    echo '           _______   __           _   ______   ________            '\n    echo '     /\\   |  __ \\ \\ / /          | | |  _   | |__   ___|           '\n    echo '    /  \\  | |  | \\ V /   ______  | | | |  | |    |  |              '\n    echo \"   / /\\ \\ | |  | |> <   |______| | | | |  | |    |  |              \"\n    echo '  / ____ \\| |__| / . \\           | | | |__| |    |  |              '\n    echo ' /_/    \\_\\_____/_/_\\_\\          |_| |_____ |    |_ |              '\n    echo '        |__   __| | |                   | |                        '\n    echo '           | | ___| | ___ _ __ ___   ___| |_ _ __ _   _            '\n    echo \"           | |/ _ \\ |/ _ \\ '_ \\` _ \\ / _ \\ __| '__| | | |          \"\n    echo '           | |  __/ |  __/ | | | | |  __/ |_| |  | |_| |           '\n    echo '           |_|\\___|_|\\___|_| |_| |_|\\___|\\__|_|   \\__, |           '\n    echo '                                                   __/ |           '\n    echo '                                                  |___/            '\n}\n\nfunction spinner() {\n    local info=\"$1\"\n    local pid=$!\n    local delay=0.75\n    local spinstr='|/-\\'\n    while kill -0 $pid 2> /dev/null; do\n        local temp=${spinstr#?}\n        printf \" [%c]  $info\" \"$spinstr\"\n        local spinstr=$temp${spinstr%\"$temp\"}\n        sleep $delay\n        echo -ne \"\\033[0K\\r\"\n    done\n}\n\nfunction deletePreLine() {\n    echo -ne '\\033[1A'\n    echo -ne \"\\r\\033[0K\"\n}\n\n# Service Specific Functions\nfunction add_required_extensions() {\n    az extension add --name azure-iot --only-show-errors --output none; \\\n    az extension update --name azure-iot --only-show-errors --output none; \\\n    az extension add --name kusto --only-show-errors --output none; \\\n    az extension update --name kusto --only-show-errors --output none\n}\n\nfunction create_resource_group() {\n    az group create --name $rgName --location \"East US\" --only-show-errors --output none\n}\n\nfunction deploy_azure_services() {\n    az deployment group create -n $deploymentName -g $rgName \\\n        --template-file main.bicep \\\n        --parameters deploymentSuffix=$randomNum principalId=$principalId @iotanalytics.parameters.json \\\n        --only-show-errors --output none\n}\n\nfunction get_deployment_output() {\n    dtName=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.digitalTwinName.value --output tsv)\n    dtHostName=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.digitalTwinHostName.value --output tsv)\n    saName=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.saName.value --output tsv)\n    saKey=$(az storage account keys list --account-name $saName --query [0].value -o tsv)\n    saId=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.saId.value --output tsv)\n    adxName=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.adxName.value --output tsv)\n    adxResoureId=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.adxClusterId.value --output tsv)\n    location=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.location.value --output tsv)\n    eventHubNSId=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.eventhubClusterId.value --output tsv)\n    eventHubResourceId=\"$eventHubNSId/eventhubs/iotdata\"\n    eventHubHistoricId=\"$eventHubNSId/eventhubs/historicdata\"\n    iotCentralName=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.iotCentralName.value --output tsv)\n    iotCentralAppID=$(az iot central app show -n $iotCentralName -g $rgName --query  applicationId --output tsv)\n    numDevices=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.deviceNumber.value --output tsv)\n    eventHubConnectionString=$(az deployment group show -n $deploymentName -g $rgName --query properties.outputs.eventHubConnectionString.value --output tsv)\n}\n\nfunction configure_ADX_cluster() {\n    sed -i \"s/<dtURI>/$dtHostName/g\" config/configDB.kql ;\\\n    #sed -i \"s/<saname>/$saName/g\" config/configDB.kql ;\\\n    #sed -i \"s/<sakey>/$saKey/g\" config/configDB.kql ;\\\n    az storage blob upload -f config/configDB.kql -c adxscript -n configDB.kql \\\n        --account-key $saKey --account-name $saName --only-show-errors --output none  ;\\\n    blobURI=\"https://$saName.blob.core.windows.net/adxscript/configDB.kql\"  ;\\\n    blobSAS=$(az storage blob generate-sas --account-name $saName --container-name adxscript \\\n        --name configDB.kql --permissions acdrw --expiry $tomorrow --account-key $saKey --output tsv)  ;\\\n    az kusto script create --cluster-name $adxName --database-name IoTAnalytics  \\\n        --force-update-tag \"config1\" --script-url $blobURI --script-url-sas-token $blobSAS \\\n        --resource-group $rgName --name 'configDB' --only-show-errors --output none  ;\\\n    az kusto data-connection event-hub create --cluster-name $adxName --name \"IoTAnalytics\" \\\n        --database-name \"IoTAnalytics\" --location $location --consumer-group '$Default' \\\n        --event-hub-resource-id $eventHubResourceId --managed-identity-resource-id $adxResoureId \\\n        --data-format 'JSON' --table-name 'StageIoTRawData' --mapping-rule-name 'StageIoTRawData_mapping' \\\n        --compression 'None' --resource-group $rgName --only-show-errors --output none\n\n    az kusto data-connection event-grid create --cluster-name $adxName -g $rgName --database-name \"IoTAnalytics\" \\\n        --table-name \"Thermostats\" --name \"HistoricalLoad\" --ignore-first-record true --data-format csv  \\\n        --mapping-rule-name \"Thermostats_mapping\" --storage-account-resource-id $saId \\\n        --consumer-group '$Default' --event-hub-resource-id $eventHubHistoricId\n    az storage blob upload -f config/Thermostat_January2022.csv -c adxscript -n Thermostat_January2022.csv \\\n        --account-key $saKey --account-name $saName --only-show-errors --output none  ;\\\n}\n\nfunction create_digital_twin_models() {\n    az dt model create -n $dtName --from-directory ./dtconfig  --only-show-errors --output none ; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Office;1\" --twin-id Dallas --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Office;1\" --twin-id Seattle --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Office;1\" --twin-id Atlanta --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL1 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL2 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL3 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL4 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL5 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id DAL6 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA1 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA2 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA3 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA4 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA5 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id SEA6 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL1 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL2 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL3 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL4 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL5 --only-show-errors --output none; \\\n    az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Floor;1\" --twin-id ATL6 --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F1'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL1' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F2'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL2' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F3'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL3' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F4'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL4' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F5'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL5' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'DAL_F6'  \\\n        --relationship 'officecontainsfloors' --source 'Dallas' --target 'DAL6' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F1'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA1' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F2'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA2' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F3'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA3' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F4'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA4' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F5'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA5' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'SEA_F6'  \\\n        --relationship 'officecontainsfloors' --source 'Seattle' --target 'SEA6' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F1'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL1' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F2'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL2' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F3'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL3' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F4'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL4' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F5'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL5' \\\n        --only-show-errors --output none; \\\n    az dt twin relationship create -n $dtName --relationship-id 'ATL_F6'  \\\n        --relationship 'officecontainsfloors' --source 'Atlanta' --target 'ATL6' \\\n        --only-show-errors --output none; \\\n}\n\nfunction deploy_thermostat_devices() {\n    for (( c=1; c<=$numDevices; c++ ))\n    do\n        deviceId=$(cat /proc/sys/kernel/random/uuid)\n        az iot central device create --device-id $deviceId --app-id $iotCentralAppID \\\n            --template dtmi:m43gbjjsrr5:fp1yz0dm0qs --simulated --only-show-errors --output none\n\n        floornum=$(expr $c % 18)\n        \n        floor=${floors[$floornum]}\n            \n        az dt twin create -n $dtName --dtmi \"dtmi:StageIoTRawData:Thermostat;1\" --twin-id $deviceId \\\n            --only-show-errors --output none ;\\\n        az dt twin relationship create -n $dtName --relationship-id \"contains${deviceId}\" \\\n            --relationship 'floorcontainsdevices' --source $floor --target $deviceId --only-show-errors --output none\n    done\n}\n\nfunction configure_IoT_Central_output() {\n    az iot central export destination create --app-id $iotCentralAppID --dest-id 'eventHubExport' \\\n        --type eventhubs@v1 --name 'eventHubExport' \\\n        --authorization '{\"type\": \"connectionString\", \"connectionString\": \"'$eventHubConnectionString'\" }' \\\n        --only-show-errors --output none  ; \\\n    az iot central export create --app-id $iotCentralAppID --export-id 'iotEventHubExport' \\\n        --display-name 'iotEventHubExport' --source 'telemetry' --destinations '[{\"id\": \"eventHubExport\"}]' \\\n        --only-show-errors --output none\n}\n\n# Define required variables\nrandomNum=$RANDOM\ncurrentDate=$(date)\ntomorrow=$(date +\"%Y-%m-%dT00:00:00Z\" -d \"$currentDate +1 days\")\ndeploymentName=ADXIoTAnalyticsDeployment$randomNum\nrgName=ADXIoTAnalytics$randomNum\nprincipalId=$(az ad signed-in-user show --query id -o tsv)\n\n# Setup array to utilize when assiging devices to departments and patients\nfloors=('DAL1' 'DAL2' 'DAL3' 'DAL4' 'DAL5' 'DAL6' 'SEA1' 'SEA2' 'SEA3' 'SEA4' 'SEA5' 'SEA6' 'ATL1' 'ATL2' 'ATL3' 'ATL4' 'ATL5' 'ATL6')\n\nbanner # Show Welcome banner\n\necho '1. Starting solution deployment'\nadd_required_extensions & # Install/Update required eztensions\nspinner \"Installing IoT Extensions\"\ncreate_resource_group & # Create parent resurce group\nspinner \"Creating Resource Group\"\ndeploy_azure_services & # Create all additional services using main Bicep template\nspinner \"Deploying Azure Services\"\n\necho \"2. Starting configuration for deployment $deploymentName\"\nget_deployment_output  # Get Deployment output values\n\n# Start Configuration\nconfigure_ADX_cluster & # Configure ADX cluster\nspinner \"Configuring ADX Cluster\"\n# Get/Refresh IoT Central Token \naz account get-access-token --resource https://apps.azureiotcentral.com --only-show-errors --output none\ncreate_digital_twin_models & # Create all the models from folder in git repo\nspinner \"Creating model for Azure Digital Twins $dtName\"\n\n# Complete configuration\necho \"Creating $numDevices Smart Knee Brace devices on IoT Central: $iotCentralName ($iotCentralAppID) and Digital Twins: $dtName\"\ndeploy_thermostat_devices # Deploy Thermostat simulated devices\nconfigure_IoT_Central_output & # On IoT Central, create an Event Hub export and destination with json payload\nspinner \" Creating IoT Central App export and destination on IoT Central: $iotCentralName ($iotCentralAppID)\"\n\necho \"3. Configuration completed\"\n", "num_lines": 249}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euxo pipefail\n\n: \"${SUBSCRIPTION_ID:=8ecadfc9-d1a3-4ea4-b844-0d9f87e4d7c8}\" #Azure Container Service - Test Subscription\n: \"${RESOURCE_GROUP_NAME:=agentbaker-e2e-tests}\"\n: \"${LOCATION:=eastus}\"\n: \"${CLUSTER_NAME:=agentbaker-e2e-test-cluster}\"\n: \"${AZURE_TENANT_ID:=72f988bf-86f1-41af-91ab-2d7cd011db47}\"\n: \"${TIMEOUT:=30m}\"\n\nexport SUBSCRIPTION_ID\nexport RESOURCE_GROUP_NAME\nexport LOCATION\nexport CLUSTER_NAME\nexport AZURE_TENANT_ID\n\ngo version\ngo test -timeout $TIMEOUT -v -run Test_All ./", "num_lines": 19}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euox pipefail\n\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSL $url -o $tarball\n            sleep $wait_sleep\n        fi\n    done\n}\n\nsudo swapoff -a\nsudo ctr version\nsudo systemctl status containerd\n\nsed '$ d' parts/linux/cloud-init/artifacts/manifest.json > temporary_manifest.json\nKUBE_BINARY_VERSIONS=\"$(jq -r .kubernetes.versions[] temporary_manifest.json)\"\nfor KUBE_BINARY_VERSION in $KUBE_BINARY_VERSIONS; do\n    K8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\n    KUBE_BINARY_URL=\"https://acs-mirror.azureedge.net/kubernetes/v${KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-amd64.tar.gz\"\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit 120\n    tar --transform=\"s|.*|&-${KUBE_BINARY_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n    export KUBE_BINARY_VERSION\n    pushd e2e || exit 1\n    go run -ldflags=\"-X main.KUBE_BINARY_VERSION=${KUBE_BINARY_VERSION}\" kubelet/main.go\n    cat kubelet/${KUBE_BINARY_VERSION}-flags.json\n    popd || exit 1\ndone\nrm -f temporary_manifest.json", "num_lines": 39}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euxo pipefail\n\nsource e2e-helper.sh\n\nlog \"Starting to create windows nodepool\"\n\nRESOURCE_GROUP_NAME=\"$RESOURCE_GROUP_NAME-$WINDOWS_E2E_IMAGE-$K8S_VERSION\"\n\nout=$(az aks nodepool list --cluster-name $CLUSTER_NAME -g $RESOURCE_GROUP_NAME | jq '.[].name')\n\nif [[ \"$out\" != *\"winnp\"* ]]; then\n    log \"Creating windows nodepool\"\n    retval=0\n    az aks nodepool add --resource-group $RESOURCE_GROUP_NAME --cluster-name $CLUSTER_NAME --name \"winnp\" --os-type Windows --os-sku $WINDOWS_E2E_OSSKU --node-vm-size $WINDOWS_E2E_VMSIZE --node-count 1 || retval=$?\n    if [ \"$retval\" -ne 0 ]; then\n        log \"Other pipeline may be creating the same nodepool, waiting for ready\"\n    else\n        log \"Created windows nodepool\"\n    fi\nelse\n    log \"Already create windows nodepool\"\nfi\n\nprovisioning_state=$(az aks nodepool show --cluster-name $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -n \"winnp\" -ojson | jq '.provisioningState' | tr -d \"\\\"\")\nif [ \"$provisioning_state\" == \"Creating\" ]; then\n    log \"Other pipeline may be creating the same nodepool, waiting for ready\"\n    az aks nodepool wait --nodepool-name \"winnp\" --cluster-name $CLUSTER_NAME --resource-group $RESOURCE_GROUP_NAME --created --interval 60 --timeout 1800\nfi\n\nprovisioning_state=$(az aks nodepool show --cluster-name $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -n \"winnp\" -ojson | jq '.provisioningState' | tr -d \"\\\"\")\nif [ \"$provisioning_state\" == \"Succeeded\" ]; then\n    log \"Windows nodepool is in succeed state\"\nelse\n    err \"Windows nodepool is not in succeeded state. Current state is $provisioning_state.\"\n    exit 1\nfi\n", "num_lines": 39}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nlog() {\n    printf \"\\\\033[1;33m%s\\\\033[0m\\\\n\" \"$*\"\n}\n\nok() {\n    printf \"\\\\033[1;32m%s\\\\033[0m\\\\n\" \"$*\"\n}\n\nerr() {\n    printf \"\\\\033[1;31m%s\\\\033[0m\\\\n\" \"$*\"\n}\n\nexec_on_host() {\n    kubectl exec $(kubectl get pod -l app=debug -o jsonpath=\"{.items[0].metadata.name}\") -- bash -c \"nsenter -t 1 -m bash -c \\\"$1\\\"\" > $2\n}\n\nbackfill_clean_storage_container() {\n    set +x\n    # Get supported kubernetes versions\n    versions=$(az aks get-versions --location $LOCATION --query \"orchestrators[].orchestratorVersion\" -o tsv)\n    k8s_versions=${versions//./}\n\n    # Get container names e.g. akswinstore2022-1256 (for this $container_version would be \"1256\")\n    container_names=$(az storage container list --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --query \"[?starts_with(name, 'akswinstore')].name\" -o tsv)\n    # Check if the container version is still supported and delete the container if not\n    for container_name in $container_names; do\n        container_version=$(echo $container_name | cut -d '-' -f 2- | awk '{print tolower($0)}')\n        echo \"container version is $container_version\"\n        if [[ $k8s_versions == *\"$container_version\"* ]]; then\n            echo \"The version $container_version is available in the $LOCATION region.\"\n        else\n            echo \"The version $container_version is not available in the $LOCATION region.\"\n            echo \"Deleting the container.\"\n            az storage container delete --name $container_name --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY\n            echo \"Deletion completed.\"\n        fi\n    done\n\n    set -x\n}\n\ncreate_storage_container() {\n    set +x\n\n    # check if the storage container exists and create one if not\n    exists=$(az storage container exists --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --name $WINDOWS_E2E_STORAGE_CONTAINER)\n    if [[ $exists == *false* ]]; then\n        az storage container create -n $WINDOWS_E2E_STORAGE_CONTAINER --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY\n        echo \"Created storage container $WINDOWS_E2E_STORAGE_CONTAINER in $STORAGE_ACCOUNT_NAME\"\n    else\n        # check if the storage container is empty and delete the blobs within one by one if not\n        blob_list=$(az storage blob list --account-name $STORAGE_ACCOUNT_NAME --container-name $WINDOWS_E2E_STORAGE_CONTAINER --account-key $MAPPED_ACCOUNT_KEY -o json | jq -r '.[] | .name')\n        if [[ -n $blob_list ]]; then\n            for blob in $blob_list; do\n                az storage blob delete --account-name $STORAGE_ACCOUNT_NAME --container-name $WINDOWS_E2E_STORAGE_CONTAINER --account-key $MAPPED_ACCOUNT_KEY --name $blob\n                echo \"Deleted blob $blob from storage container $WINDOWS_E2E_STORAGE_CONTAINER in the storage account $STORAGE_ACCOUNT_NAME\"\n            done\n        fi\n    fi\n    set -x\n}\n\nupload_linux_file_to_storage_account() {\n    local retval=0\n    MC_RESOURCE_GROUP_NAME=\"MC_${RESOURCE_GROUP_NAME}_${CLUSTER_NAME}_$LOCATION\"\n    MC_VMSS_NAME=$(az vmss list -g $MC_RESOURCE_GROUP_NAME --query \"[?contains(name, 'nodepool')]\" -ojson | jq -r '.[0].name')\n    VMSS_INSTANCE_ID=\"$(az vmss list-instances --name $MC_VMSS_NAME -g $MC_RESOURCE_GROUP_NAME | jq -r '.[0].instanceId')\"\n\n    set +x\n    expiryTime=$(date --date=\"2 day\" +%Y-%m-%d)\n    token=$(az storage container generate-sas --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --permissions 'w' --expiry $expiryTime --name $WINDOWS_E2E_STORAGE_CONTAINER)\n    linuxFileURL=\"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${WINDOWS_E2E_STORAGE_CONTAINER}/${MC_VMSS_NAME}-linux-file.zip?${token}\"\n\n    az vmss run-command invoke --command-id RunShellScript \\\n        --resource-group $MC_RESOURCE_GROUP_NAME \\\n        --name $MC_VMSS_NAME \\\n        --instance-id $VMSS_INSTANCE_ID \\\n        --scripts \"cat /etc/kubernetes/azure.json > /home/fields.json; cat /etc/kubernetes/certs/apiserver.crt | base64 -w 0 > /home/apiserver.crt; cat /etc/kubernetes/certs/ca.crt | base64 -w 0 > /home/ca.crt; cat /etc/kubernetes/certs/client.key | base64 -w 0 > /home/client.key; cat /var/lib/kubelet/bootstrap-kubeconfig > /home/bootstrap-kubeconfig; cd /home; zip file.zip fields.json apiserver.crt ca.crt client.key bootstrap-kubeconfig; wget https://aka.ms/downloadazcopy-v10-linux; tar -xvf downloadazcopy-v10-linux; cd ./azcopy_*; ./azcopy copy /home/file.zip $linuxFileURL\" || retval=$?\n    \n    set -x\n    if [ \"$retval\" -eq 0 ]; then\n        log \"Upload linux file successfully\"\n    else\n        err \"Failed to upload linux file. Error code is $retval.\"\n    fi\n}\n\ndownload_linux_file_from_storage_account() {\n    wget https://aka.ms/downloadazcopy-v10-linux\n    tar -xvf downloadazcopy-v10-linux\n\n    expiryTime=$(date --date=\"2 day\" +%Y-%m-%d)\n\n    set +x\n\n    token=$(az storage container generate-sas --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --permissions 'rl' --expiry $expiryTime --name $WINDOWS_E2E_STORAGE_CONTAINER)\n    tokenWithoutQuote=${token//\\\"}\n    linuxFileURL=\"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${WINDOWS_E2E_STORAGE_CONTAINER}/${MC_VMSS_NAME}-linux-file.zip?${tokenWithoutQuote}\"\n\n    array=(azcopy_*)\n    noExistStr=\"File count: 0\"\n    local fileExist=\"false\"\n    for i in $(seq 1 20); do\n        listResult=$(${array[0]}/azcopy list $linuxFileURL --running-tally)\n        if [[ \"$listResult\" == *\"$noExistStr\"* ]]; then\n            log \"Linux file has not been uploaded, waiting...\"\n            sleep 10\n            continue\n        fi\n        fileExist=\"true\"\n        break;\n    done\n    set -x\n\n    if [ \"$fileExist\" == \"false\" ]; then\n        err \"File does not exist in storage account.\"\n        exit 1\n    fi\n\n    set +x\n    ${array[0]}/azcopy copy $linuxFileURL file.zip\n    set -x\n\n    unzip file.zip\n}\n\naddJsonToFile() {\n    k=$1; v=$2\n    jq -r --arg key $k --arg value $v '. + { ($key) : $value}' < fields.json > dummy.json && mv dummy.json fields.json\n}\n\ngetAgentPoolProfileValues() {\n    declare -a properties=(\"mode\" \"name\" \"nodeImageVersion\")\n\n    for property in \"${properties[@]}\"; do\n        value=$(jq -r .agentPoolProfiles[].${property} < cluster_info.json)\n        addJsonToFile $property $value\n    done\n}\n\ngetFQDN() {\n    fqdn=$(jq -r '.fqdn' < cluster_info.json)\n    addJsonToFile \"fqdn\" $fqdn\n}\n\ngetMSIResourceID() {\n    msiResourceID=$(jq -r '.identityProfile.kubeletidentity.resourceId' < cluster_info.json)\n    addJsonToFile \"msiResourceID\" $msiResourceID\n}\n\ngetTenantID() {\n    tenantID=$(jq -r '.identity.tenantId' < cluster_info.json)\n    addJsonToFile \"tenantID\" $tenantID\n}\n\ncleanupOutdatedFiles() {\n    # delete blobs created 1 day ago\n    EXPIRATION_IN_HOURS=24\n    (( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n    (( deadline=$(date +%s)-${expirationInSecs%.*} ))\n    dateOfdeadline=$(date -d @${deadline} +\"%Y-%m-%dT%H:%M:%S+00:00\")\n\n    # two containers need to be cleaned up now\n    CONTAINER_LIST=(\"cselogs\" \"csepackages\")\n\n    for CONTAINER_NAME in \"${CONTAINER_LIST[@]}\"\n    do \n        result=$(az storage blob list -c $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY -o json \\\n        | jq -r --arg time \"$dateOfdeadline\" '.[] | select(.properties.creationTime < $time)' \\\n        | jq -r '.name')\n\n        for item in $result\n        do\n            az storage blob delete -c $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY -n $item\n            echo \"Deleted $item in $CONTAINER_NAME\"\n        done\n    done\n}", "num_lines": 180}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euxo pipefail\n\nsource e2e-helper.sh\n\nchoose() {\n    echo ${1:RANDOM%${#1}:1} $RANDOM;\n}\n\ncollect-logs() {\n    local retval\n    retval=0\n    mkdir -p $SCENARIO_NAME-logs\n    VMSS_INSTANCE_ID=\"$(az vmss list-instances --name $DEPLOYMENT_VMSS_NAME -g $MC_RESOURCE_GROUP_NAME | jq -r '.[0].instanceId')\"\n    set +x\n    expiryTime=$(date --date=\"2 day\" +%Y-%m-%d)\n    token=$(az storage container generate-sas --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --permissions 'rwld' --expiry $expiryTime --name $STORAGE_LOG_CONTAINER --https-only)\n    # Use .ps1 file to run scripts since single quotes of parameters for --scripts would fail in check-shell\n    az vmss run-command invoke --command-id RunPowerShellScript \\\n        --resource-group $MC_RESOURCE_GROUP_NAME \\\n        --name $DEPLOYMENT_VMSS_NAME \\\n        --instance-id $VMSS_INSTANCE_ID \\\n        --scripts @upload-cse-logs.ps1 \\\n        --parameters arg1=$STORAGE_ACCOUNT_NAME arg2=$STORAGE_LOG_CONTAINER arg3=$DEPLOYMENT_VMSS_NAME arg4=$token || retval=$?\n    if [ \"$retval\" -ne 0 ]; then\n        err \"Failed in uploading cse logs. Error code is $retval.\"\n    fi\n\n    tokenWithoutQuote=${token//\\\"}\n    # use array to pass shellcheck\n    array=(azcopy_*)\n    ${array[0]}/azcopy copy \"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_LOG_CONTAINER}/${DEPLOYMENT_VMSS_NAME}-cse.log?${tokenWithoutQuote}\" $SCENARIO_NAME-logs/$WINDOWS_E2E_IMAGE-CustomDataSetupScript.log || retval=$?\n    if [ \"$retval\" -ne 0 ]; then\n        err \"Failed in downloading cse logs. Error code is $retval.\"\n    else\n        log \"Collect cse logs done\"\n        ${array[0]}/azcopy rm \"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_LOG_CONTAINER}/${DEPLOYMENT_VMSS_NAME}-cse.log?${tokenWithoutQuote}\" || retval=$?\n        if [ \"$retval\" -ne 0 ]; then\n            err \"Failed in deleting cse logs in remote storage. Error code is $retval.\"\n        fi\n    fi\n    set -x\n}\n\nRESOURCE_GROUP_NAME=\"$RESOURCE_GROUP_NAME-$WINDOWS_E2E_IMAGE-$K8S_VERSION\"\n\nDEPLOYMENT_VMSS_NAME=\"$(mktemp -u winXXXXX | tr '[:upper:]' '[:lower:]')\"\nexport DEPLOYMENT_VMSS_NAME\n\n# download azcopy\nwget https://aka.ms/downloadazcopy-v10-linux\ntar -xvf downloadazcopy-v10-linux\n\n# zip and upload cse package\ntimeStamp=$(date +%s)\ncd ../staging/cse/windows\nzip -r ../../../$WINDOWS_E2E_IMAGE/$WINDOWS_E2E_IMAGE-aks-windows-cse-scripts.zip ./* -x ./*.tests.ps1 -x \"*azurecnifunc.tests.suites*\" -x README -x provisioningscripts/*.md -x debug/update-scripts.ps1\nlog \"Zip cse packages done\"\n\nset +x\nexpiryTime=$(date --date=\"2 day\" +%Y-%m-%d)\ntoken=$(az storage container generate-sas --account-name $STORAGE_ACCOUNT_NAME --account-key $MAPPED_ACCOUNT_KEY --permissions 'rwld' --expiry $expiryTime --name $STORAGE_PACKAGE_CONTAINER)\ntokenWithoutQuote=${token//\\\"}\n\ncsePackageURL=\"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_PACKAGE_CONTAINER}/${timeStamp}-${DEPLOYMENT_VMSS_NAME}-aks-windows-cse-scripts.zip?${tokenWithoutQuote}\"\nexport csePackageURL\n\ncd ../../../$WINDOWS_E2E_IMAGE\n\narray=(azcopy_*)\nnoExistStr=\"File count: 0\"\nlistResult=$(${array[0]}/azcopy list $csePackageURL --running-tally)\n\nfor i in $(seq 1 10); do\n    if [[ \"$listResult\" != *\"$noExistStr\"* ]]; then\n        log \"Cse package with the same exists, retry $i to use new name...\"\n        timeStamp=$(date +%s)\n        csePackageURL=\"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_PACKAGE_CONTAINER}/${timeStamp}-${DEPLOYMENT_VMSS_NAME}-aks-windows-cse-scripts.zip?${tokenWithoutQuote}\"\n        listResult=$(${array[0]}/azcopy list $csePackageURL --running-tally)\n        continue\n    fi\n    ${array[0]}/azcopy copy $WINDOWS_E2E_IMAGE-aks-windows-cse-scripts.zip $csePackageURL\n    break;\ndone\n\nset -x\n\nlistResult=$(${array[0]}/azcopy list $csePackageURL --running-tally)\nif [[ \"$listResult\" == *\"$noExistStr\"* ]]; then\n    err \"Failed to upload cse package\"\n    exit 1\nfi\n\nlog \"Upload cse packages done\"\n\nlog \"Scenario is $SCENARIO_NAME\"\nlog \"Windows package version is $WINDOWS_PACKAGE_VERSION\"\n\n# Generate vmss cse deployment config for windows nodepool testing\nexport orchestratorVersion=$WINDOWS_PACKAGE_VERSION\nenvsubst < scenarios/$SCENARIO_NAME/property-$SCENARIO_NAME-template.json > scenarios/$SCENARIO_NAME/$WINDOWS_E2E_IMAGE-property-$SCENARIO_NAME.json\n\nset +x\nWINDOWS_PASSWORD=$({\n    choose '0123456789'\n    choose 'abcdefghijklmnopqrstuvwxyz'\n    choose 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n    choose '#@'\n    for i in $(seq 1 16)\n    do\n        choose '#@0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'\n    done\n} | sort -R | awk '{printf \"%s\", $1}')\nset -x\necho $WINDOWS_PASSWORD\n\nMC_RESOURCE_GROUP_NAME=\"MC_${RESOURCE_GROUP_NAME}_${CLUSTER_NAME}_eastus\"\n\nKUBECONFIG=$(pwd)/kubeconfig\nexport KUBECONFIG\n\nclientCertificate=$(grep \"client-certificate-data\" $KUBECONFIG | awk '{print $2}')\n\ntee $SCENARIO_NAME-vmss.json > /dev/null <<EOF\n{\n    \"group\": \"${MC_RESOURCE_GROUP_NAME}\",\n    \"vmss\": \"${DEPLOYMENT_VMSS_NAME}\"\n}\nEOF\n\n# Removed the \"network-plugin\" tag o.w. kubelet error for 1.24.0+ contains \"failed to parse kubelet flag: unknown flag: --network-plugin\"\n# \"network-plugin\" works for 1.23.15 and below (you won't see this parsing error in kubelet.err.log)\njq --arg clientCrt \"$clientCertificate\" --arg vmssName $DEPLOYMENT_VMSS_NAME 'del(.KubeletConfig.\"--pod-manifest-path\") | del(.KubeletConfig.\"--pod-max-pids\") | del(.KubeletConfig.\"--protect-kernel-defaults\") | del(.KubeletConfig.\"--tls-cert-file\") | del(.KubeletConfig.\"--tls-private-key-file\") | del(.KubeletConfig.\"--network-plugin\") | .ContainerService.properties.certificateProfile += {\"clientCertificate\": $clientCrt} | .PrimaryScaleSetName=$vmssName' nodebootstrapping_config.json > $WINDOWS_E2E_IMAGE-nodebootstrapping_config_for_windows.json\njq -s '.[0] * .[1]' $WINDOWS_E2E_IMAGE-nodebootstrapping_config_for_windows.json scenarios/$SCENARIO_NAME/$WINDOWS_E2E_IMAGE-property-$SCENARIO_NAME.json > scenarios/$SCENARIO_NAME/$WINDOWS_E2E_IMAGE-nbc-$SCENARIO_NAME.json\n\ngo test -tags bash_e2e -run TestE2EWindows\n\nMC_WIN_VMSS_NAME=$(az vmss list -g $MC_RESOURCE_GROUP_NAME --query \"[?contains(name, 'winnp')]\" -ojson | jq -r '.[0].name')\nVMSS_RESOURCE_Id=$(az resource show --resource-group $MC_RESOURCE_GROUP_NAME --name $MC_WIN_VMSS_NAME --resource-type Microsoft.Compute/virtualMachineScaleSets --query id --output tsv)\n\naz group export --resource-group $MC_RESOURCE_GROUP_NAME --resource-ids $VMSS_RESOURCE_Id --include-parameter-default-value > test.json\n# TODO: use prod image\n# IMAGE_REFERENCE=$(jq -c '.resources[0].properties.virtualMachineProfile.storageProfile.imageReference.id' test.json)\nIMAGE_REFERENCE=\"[concat(parameters('galleries_AKSWindows_externalid'), '/images/windows-e2e-test-$WINDOWS_E2E_IMAGE/versions/2023.02.07')]\"\nIMAGE_EXTERNALID=\"/subscriptions/$IMAGE_SUBSCRIPTION_ID/resourceGroups/akswinvhdbuilderrg/providers/Microsoft.Compute/galleries/AKSWindows\"\nWINDOWS_VNET=$(jq -c '.parameters | with_entries( select(.key|contains(\"vnet\")))' test.json)\nWINDOWS_LOADBALANCER=$(jq -c '.parameters | with_entries( select(.key|contains(\"loadBalancers\")))' test.json)\nWINDOWS_IDENTITY=$(jq -c '.resources[0] | with_entries( select(.key|contains(\"identity\")))' test.json)\nWINDOWS_SKU=$(jq -c '.resources[0] | with_entries( select(.key|contains(\"sku\")))' test.json)\nWINDOWS_OSDISK=$(jq -c '.resources[0].properties.virtualMachineProfile.storageProfile | with_entries( select(.key|contains(\"osDisk\")))' test.json)\nNETWORK_PROPERTIES=$(jq -c '.resources[0].properties.virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0] | with_entries( select(.key|contains(\"properties\")))' test.json)\nCUSTOM_DATA=$(cat scenarios/$SCENARIO_NAME/$WINDOWS_E2E_IMAGE-$SCENARIO_NAME-cloud-init.txt)\nCSE_CMD=$(cat scenarios/$SCENARIO_NAME/$WINDOWS_E2E_IMAGE-$SCENARIO_NAME-cseCmd)\n\njq --argjson JsonForVnet \"$WINDOWS_VNET\" \\\n    --argjson JsonForLB \"$WINDOWS_LOADBALANCER\" \\\n    --argjson JsonForIdentity \"$WINDOWS_IDENTITY\" \\\n    --argjson JsonForSKU \"$WINDOWS_SKU\" \\\n    --argjson JsonForNetwork \"$NETWORK_PROPERTIES\" \\\n    --argjson JsonForOSDisk \"$WINDOWS_OSDISK\" \\\n    --arg ValueForImageExternalID \"$IMAGE_EXTERNALID\" \\\n    --arg ValueForImageReference \"$IMAGE_REFERENCE\" \\\n    --arg ValueForAdminPassword \"$WINDOWS_PASSWORD\" \\\n    --arg ValueForCustomData \"$CUSTOM_DATA\" \\\n    --arg ValueForCSECmd \"$CSE_CMD\" \\\n    --arg ValueForVMSS \"$DEPLOYMENT_VMSS_NAME\" \\\n    '.parameters += $JsonForVnet | .parameters += $JsonForLB | .parameters.galleries_AKSWindows_externalid.defaultValue=$ValueForImageExternalID | .resources[0] += $JsonForIdentity | .resources[0] += $JsonForSKU | .resources[0].properties.virtualMachineProfile.storageProfile+=$JsonForOSDisk | .resources[0].properties.virtualMachineProfile.networkProfile.networkInterfaceConfigurations[0] += $JsonForNetwork | .resources[0].properties.virtualMachineProfile.storageProfile.imageReference.id=$ValueForImageReference | .resources[0].properties.virtualMachineProfile.osProfile.adminPassword=$ValueForAdminPassword | .resources[0].properties.virtualMachineProfile.osProfile.customData=$ValueForCustomData | .resources[0].properties.virtualMachineProfile.extensionProfile.extensions[0].properties.settings.commandToExecute=$ValueForCSECmd | .parameters.virtualMachineScaleSets_akswin30_name.defaultValue=$ValueForVMSS' \\\n    windows_vmss_template.json > $DEPLOYMENT_VMSS_NAME-deployment.json\n\nretval=0\nset +e\naz deployment group create --resource-group $MC_RESOURCE_GROUP_NAME \\\n         --template-file $DEPLOYMENT_VMSS_NAME-deployment.json || retval=$?\nset -e\nlog \"Deployment of windows vmss succeeded.\"\n\nif [ \"$retval\" -ne 0 ]; then\n    err \"Failed to deploy windows vmss. Error code is $retval.\"\n    exit 1\nfi\n\n# delete cse package in storage account\n${array[0]}/azcopy rm $csePackageURL || retval=$?\n\nif [ \"$retval\" -ne 0 ]; then\n    err \"Failed to delete cse package in storage account. Error code is $retval.\"\nelse\n    log \"Delete cse package in storage account done\"\nfi\n\nlog \"Collect cse log\"\ncollect-logs \n\ncat $SCENARIO_NAME-vmss.json\n\nVMSS_INSTANCE_NAME=$(az vmss list-instances \\\n                    -n ${DEPLOYMENT_VMSS_NAME} \\\n                    -g $MC_RESOURCE_GROUP_NAME \\\n                    -ojson | \\\n                    jq -r '.[].osProfile.computerName')\nexport VMSS_INSTANCE_NAME\n\n# Sleep to let the automatic upgrade of the VM finish\nwaitForNodeStartTime=$(date +%s)\nfor i in $(seq 1 10); do\n    set +e\n    kubectl get nodes | grep $VMSS_INSTANCE_NAME\n    retval=$?\n    # pipefail interferes with conditional.\n    # shellcheck disable=SC2143\n    if [ -z \"$(kubectl get nodes | grep $VMSS_INSTANCE_NAME | grep -v \"NotReady\")\" ]; then\n        log \"Retrying attempt $i\"\n        sleep 10\n        continue\n    fi\n    break;\ndone\nwaitForNodeEndTime=$(date +%s)\nlog \"Waited $((waitForNodeEndTime-waitForNodeStartTime)) seconds for node to join\"\n\nFAILED=0\n# Check if the node joined the cluster\nif [ \"$retval\" -eq 0 ]; then\n    ok \"Test succeeded, node joined the cluster\"\n    kubectl get nodes -o wide | grep $VMSS_INSTANCE_NAME\nelse\n    err \"Node did not join cluster\"\n    FAILED=1\nfi\n\n# Run a windows servercore pod on the node to check if pod runs\nPOD_NAME=$(mktemp -u podName-XXXXXXX | tr '[:upper:]' '[:lower:]')\nexport POD_NAME\nif [[ \"$WINDOWS_E2E_IMAGE\" == *\"2019\"* ]]; then\n    WINDOWS_POD_IMAGE=\"2019\"\nelse\n    WINDOWS_POD_IMAGE=\"2022\"\nfi\nexport WINDOWS_POD_IMAGE\nenvsubst < pod-windows-template.yaml > pod-windows.yaml\n\nkubectl apply -f pod-windows.yaml\n\n# Sleep to let Pod Status=Running\nwaitForPodStartTime=$(date +%s)\nfor i in $(seq 1 20); do\n    set +e\n    kubectl get pods -o wide | grep $POD_NAME\n    kubectl get pods -o wide | grep $POD_NAME | grep 'Running'\n    retval=$?\n    set -e\n    if [ \"$retval\" -ne 0 ]; then\n        log \"Retrying attempt $i\"\n        sleep 15\n        continue\n    fi\n    break;\ndone\nwaitForPodEndTime=$(date +%s)\nlog \"Waited $((waitForPodEndTime-waitForPodStartTime)) seconds for pod to come up\"\n\nif [ \"$retval\" -eq 0 ]; then\n    ok \"Pod ran successfully\"\nelse\n    err \"Pod pending/not running. Error code is $retval.\"\n    kubectl get pods -o wide | grep $POD_NAME\n    kubectl describe pod $POD_NAME\n    exit 1\nfi\n\nif [ \"$FAILED\" -ne 0  ] || [ \"$retval\" -ne 0 ]; then\n    log \"Reserve vmss and node for failed pipeline\"\nelse\n    waitForDeleteStartTime=$(date +%s)\n\n    # Only delete node and vmss since we reuse the resource group and cluster now\n    kubectl delete node $VMSS_INSTANCE_NAME\n    az vmss delete -g $(jq -r .group $SCENARIO_NAME-vmss.json) -n $(jq -r .vmss $SCENARIO_NAME-vmss.json)\n\n    waitForDeleteEndTime=$(date +%s)\n    log \"Waited $((waitForDeleteEndTime-waitForDeleteStartTime)) seconds to delete VMSS and node\"   \nfi", "num_lines": 283}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euxo pipefail\n\nsource e2e-helper.sh\n\nlog \"Starting e2e tests\"\n\n# Create a resource group for the cluster\nlog \"Creating resource group\"\nRESOURCE_GROUP_NAME=\"$RESOURCE_GROUP_NAME-$WINDOWS_E2E_IMAGE-$K8S_VERSION\"\n\nrgStartTime=$(date +%s)\naz group create -l $LOCATION -n $RESOURCE_GROUP_NAME --subscription $SUBSCRIPTION_ID -ojson\nrgEndTime=$(date +%s)\nlog \"Created resource group in $((rgEndTime-rgStartTime)) seconds\"\n\n# Check if there exists a cluster in the RG. If yes, check if the MC_RG associated with it still exists.\n# MC_RG gets deleted due to ACS-Test Garbage Collection but the cluster hangs around\nout=$(az aks list -g $RESOURCE_GROUP_NAME -ojson | jq '.[].name')\ncreate_cluster=\"false\"\nif [ -n \"$out\" ]; then\n    provisioning_state=$(az aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson | jq '.provisioningState' | tr -d \"\\\"\")\n    MC_RG_NAME=\"MC_${RESOURCE_GROUP_NAME}_${CLUSTER_NAME}_$LOCATION\"\n    exists=$(az group exists -n $MC_RG_NAME)\n    if [ \"$exists\" == \"false\" ] || [ \"$provisioning_state\" == \"Failed\" ] || [ \"$provisioning_state\" == \"Canceled\" ]; then\n        # The cluster is in a broken state\n        log \"Cluster $CLUSTER_NAME is in an unusable state, deleting...\"\n        clusterDeleteStartTime=$(date +%s)\n        az aks delete -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME --yes\n        clusterDeleteEndTime=$(date +%s)\n        log \"Deleted cluster $CLUSTER_NAME in $((clusterDeleteEndTime-clusterDeleteStartTime)) seconds\"\n        create_cluster=\"true\"\n    elif [ \"$provisioning_state\" == \"Creating\" ]; then\n        # Other pipeline is creating this cluster\n        log \"Cluster $CLUSTER_NAME is being created, waiting for ready\"\n        az aks wait --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP_NAME --created --interval 60 --timeout 1800\n        provisioning_state=$(az aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson | jq '.provisioningState' | tr -d \"\\\"\")\n        if [ \"$provisioning_state\" == \"Succeeded\" ]; then\n            log \"Cluster created by other pipeline successfully\"\n        else\n            err \"Other pipeline failed to create the cluster. Current state of cluster is $provisioning_state.\"\n            exit 1\n        fi\n    elif [ \"$provisioning_state\" == \"Updating\" ]; then\n        # Other pipeline is updating this cluster\n        log \"Cluster $CLUSTER_NAME is being updated, waiting for ready\"\n        az aks wait --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP_NAME --updated --interval 60 --timeout 1800\n        provisioning_state=$(az aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson | jq '.provisioningState' | tr -d \"\\\"\")\n        if [ \"$provisioning_state\" == \"Succeeded\" ]; then\n            log \"Cluster updated by other pipeline successfully\"\n        else\n            err \"Other pipeline failed to update the cluster. Current state of cluster is $provisioning_state.\"\n            exit 1\n        fi\n    elif [ \"$provisioning_state\" == \"Deleting\" ]; then\n        log \"Cluster $CLUSTER_NAME is being deleted, waiting for ready\"\n        az aks wait --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP_NAME --deleted --interval 60 --timeout 1800\n        retval=0\n        az aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson || retval=$?\n        if [ \"$retval\" -ne 0  ]; then\n            log \"Cluster deleted successfully\"\n            create_cluster=\"true\"\n        else\n            err \"Failed to delete the cluster.\"\n            exit 1\n        fi\n    fi\nelse\n    create_cluster=\"true\"\nfi\n\n# Create the AKS cluster and get the kubeconfig\nif [ \"$create_cluster\" == \"true\" ]; then\n    log \"Creating cluster $CLUSTER_NAME\"\n    clusterCreateStartTime=$(date +%s)\n    retval=0\n    \n    az aks create -g $RESOURCE_GROUP_NAME -n $CLUSTER_NAME --node-count 1 --generate-ssh-keys --network-plugin azure -ojson || retval=$?\n\n    if [ \"$retval\" -ne 0  ]; then\n        log \"Other pipelines may be creating cluster $CLUSTER_NAME, waiting for ready\"\n        create_cluster=\"false\"\n        az aks wait --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP_NAME --created --interval 60 --timeout 1800\n    fi\n    provisioning_state=$(az aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson | jq '.provisioningState' | tr -d \"\\\"\")\n    if [ \"$provisioning_state\" == \"Succeeded\" ]; then\n        log \"Created cluster successfully\"\n    else\n        err \"Failed to create cluster. Current state is $provisioning_state.\"\n        exit 1\n    fi\n    clusterCreateEndTime=$(date +%s)\n    log \"Created cluster $CLUSTER_NAME in $((clusterCreateEndTime-clusterCreateStartTime)) seconds\"\nfi\n\naz aks get-credentials -g $RESOURCE_GROUP_NAME -n $CLUSTER_NAME --file kubeconfig --overwrite-existing\nKUBECONFIG=$(pwd)/kubeconfig\nexport KUBECONFIG\n\n# Store the contents of az aks show to a file to reduce API call overhead\naz aks show -n $CLUSTER_NAME -g $RESOURCE_GROUP_NAME -ojson > cluster_info.json\n\nMC_RESOURCE_GROUP_NAME=\"MC_${RESOURCE_GROUP_NAME}_${CLUSTER_NAME}_eastus\"\naz vmss list -g $MC_RESOURCE_GROUP_NAME --query \"[?contains(name, 'nodepool')]\" -otable\nMC_VMSS_NAME=$(az vmss list -g $MC_RESOURCE_GROUP_NAME --query \"[?contains(name, 'nodepool')]\" -ojson | jq -r '.[0].name')\nCLUSTER_ID=$(echo $MC_VMSS_NAME | cut -d '-' -f3)\n\nbackfill_clean_storage_container\nif [ \"$create_cluster\" == \"true\" ]; then\n    create_storage_container\n    upload_linux_file_to_storage_account\n    if [ \"$WINDOWS_E2E_IMAGE\" == \"2019-containerd\" ]; then\n        cleanupOutdatedFiles\n    fi\nfi\ndownload_linux_file_from_storage_account\nlog \"Download of linux file from storage account completed\"\n\nset +x\naddJsonToFile \"apiserverCrt\" \"$(cat apiserver.crt)\"\naddJsonToFile \"caCrt\" \"$(cat ca.crt)\"\naddJsonToFile \"clientKey\" \"$(cat client.key)\"\nif [ -f \"bootstrap-kubeconfig\" ] && [ -n \"$(cat bootstrap-kubeconfig)\" ]; then\n    tlsToken=\"$(grep \"token\" < bootstrap-kubeconfig | cut -f2 -d \":\" | tr -d '\"')\"\n    addJsonToFile \"tlsbootstraptoken\" \"$tlsToken\"\nfi\nset -x\n\n# # Add other relevant information needed by AgentBaker for bootstrapping later\ngetAgentPoolProfileValues\ngetFQDN\ngetMSIResourceID\n\naddJsonToFile \"mcRGName\" $MC_RESOURCE_GROUP_NAME\naddJsonToFile \"clusterID\" $CLUSTER_ID\naddJsonToFile \"subID\" $SUBSCRIPTION_ID\n\nset +x\n# shellcheck disable=SC2091\n$(jq -r 'keys[] as $k | \"export \\($k)=\\(.[$k])\"' fields.json)\nenvsubst < percluster_template.json > percluster_config.json\njq -s '.[0] * .[1]' nodebootstrapping_template.json percluster_config.json > nodebootstrapping_config.json\nlog \"Node bootstrapping config generated\"\n", "num_lines": 145}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# This script was originally generated by logrotate automatically and placed in /etc/cron.daily/logrotate\n# This will be saved on the target VM within /usr/local/bin/logrotate.sh and invoked by logrotate.service\n\n# Clean non existent log file entries from status file\ncd /var/lib/logrotate\ntest -e status || touch status\nhead -1 status > status.clean\nsed 's/\"//g' status | while read logfile date\ndo\n    [ -e \"$logfile\" ] && echo \"\\\"$logfile\\\" $date\"\ndone >> status.clean\nmv status.clean status\n\ntest -x /usr/sbin/logrotate || exit 0\n/usr/sbin/logrotate --verbose /etc/logrotate.conf", "num_lines": 16}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o nounset\nset -o pipefail\n\n[ ! -f \"/var/run/mdsd-ci/update.status\" ] && exit 0\nstatus=$(cat /var/run/mdsd-ci/update.status)\n\nif [[ \"$status\" == \"add\" ]]; then\n        echo \"Status changed to $status.\"\n        [ -f \"/var/run/mdsd-ci/70-rsyslog-forward-mdsd-ci.conf\" ] && cp /var/run/mdsd-ci/70-rsyslog-forward-mdsd-ci.conf /etc/rsyslog.d\nelif [[ \"$status\" == \"remove\" ]]; then\n        echo \"Status changed to $status.\"\n        [ -f \"/etc/rsyslog.d/70-rsyslog-forward-mdsd-ci.conf\" ] && rm /etc/rsyslog.d/70-rsyslog-forward-mdsd-ci.conf\nelse\n        echo \"Unexpected status change to $status. Exiting\"\n        exit 1\nfi\n\necho \"Restarting rsyslog\"\nsystemctl restart rsyslog\n\nexit 0\n", "num_lines": 24}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This gets us the error codes we use and the os and such.\nsource /home/packer/provision_source.sh\n\nassignRootPW() {\n    if grep '^root:[!*]:' /etc/shadow; then\n        VERSION=$(grep DISTRIB_RELEASE /etc/*-release | cut -f 2 -d \"=\")\n        SALT=$(openssl rand -base64 5)\n        SECRET=$(openssl rand -base64 37)\n        CMD=\"import crypt, getpass, pwd; print(crypt.crypt('$SECRET', '\\$6\\$$SALT\\$'))\"\n        if [[ \"${VERSION}\" == \"22.04\" ]]; then\n            HASH=$(python3 -c \"$CMD\")\n        else\n            HASH=$(python -c \"$CMD\")\n        fi\n\n        echo 'root:'$HASH | /usr/sbin/chpasswd -e || exit $ERR_CIS_ASSIGN_ROOT_PW\n    fi\n}\n\nassignFilePermissions() {\n    FILES=\"\n    auth.log\n    alternatives.log\n    cloud-init.log\n    cloud-init-output.log\n    daemon.log\n    dpkg.log\n    kern.log\n    lastlog\n    waagent.log\n    syslog\n    unattended-upgrades/unattended-upgrades.log\n    unattended-upgrades/unattended-upgrades-dpkg.log\n    azure-vnet-ipam.log\n    azure-vnet-telemetry.log\n    azure-cnimonitor.log\n    azure-vnet.log\n    kv-driver.log\n    blobfuse-driver.log\n    blobfuse-flexvol-installer.log\n    landscape/sysinfo.log\n    \"\n    for FILE in ${FILES}; do\n        FILEPATH=\"/var/log/${FILE}\"\n        DIR=$(dirname \"${FILEPATH}\")\n        mkdir -p ${DIR} || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n        touch ${FILEPATH} || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n        chmod 640 ${FILEPATH} || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    done\n    find /var/log -type f -perm '/o+r' -exec chmod 'g-wx,o-rwx' {} \\;\n    chmod 600 /etc/passwd- || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    chmod 600 /etc/shadow- || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    chmod 600 /etc/group- || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n\n    if [[ -f /etc/default/grub ]]; then\n        chmod 644 /etc/default/grub || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    fi\n\n    if [[ -f /etc/crontab ]]; then\n        chmod 0600 /etc/crontab || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    fi\n    for filepath in /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly /etc/cron.d; do\n        if [[ -e $filepath ]]; then\n            chmod 0600 $filepath || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n        fi\n    done\n\n    # Docs: https://www.man7.org/linux/man-pages/man1/crontab.1.html\n    # If cron.allow exists, then cron.deny is ignored. To minimize who can use cron, we\n    # always want cron.allow and will default it to empty if it doesn't exist.\n    # We also need to set appropriate permissions on it.\n    # Since it will be ignored anyway, we delete cron.deny.\n    touch /etc/cron.allow || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    chmod 640 /etc/cron.allow || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n    rm -rf /etc/cron.deny || exit $ERR_CIS_ASSIGN_FILE_PERMISSION\n}\n\n# Helper function to replace or append settings to a setting file.\n# This abstracts the general logic of:\n#   1. Search for the setting (via a pattern passed in).\n#   2. If it's there, replace it with desired setting line; otherwise append it to the end of the file.\n#   3. Validate that there is now exactly one instance of the setting, and that it is the one we want.\nreplaceOrAppendSetting() {\n    local SEARCH_PATTERN=$1\n    local SETTING_LINE=$2\n    local FILE=$3\n\n    # Search and replace/append.\n    if grep -E \"$SEARCH_PATTERN\" \"$FILE\" >/dev/null; then\n        sed -E -i \"s|${SEARCH_PATTERN}|${SETTING_LINE}|g\" \"$FILE\" || exit $ERR_CIS_APPLY_PASSWORD_CONFIG\n    else\n        echo -e \"\\n${SETTING_LINE}\" >>\"$FILE\"\n    fi\n\n    # After replacement/append, there should be exactly one line that sets the setting,\n    # and it must have the value we want.\n    # If not, then there's something wrong with this script.\n    if [[ $(grep -E \"$SEARCH_PATTERN\" \"$FILE\") != \"$SETTING_LINE\" ]]; then\n        echo \"replacement was wrong\"\n        exit $ERR_CIS_APPLY_PASSWORD_CONFIG\n    fi\n}\n\n# Creates the search pattern and setting lines for login.defs settings, and calls through\n# to do the replacement. Note that this uses extended regular expressions, so both\n# grep and sed need to be called as such.\n#\n# The search pattern is:\n#   '^#{0,1} {0,1}' -- Line starts with 0 or 1 '#' followed by 0 or 1 space\n#   '${1}\\s+'       -- Then the setting name followed by one or more whitespace characters\n#   '[0-9]+$'       -- Then one more more number, which is the setting value, which is the end of the line.\n#\n# This is based on a combination of the syntax for the file and real examples we've found.\nreplaceOrAppendLoginDefs() {\n    replaceOrAppendSetting \"^#{0,1} {0,1}${1}\\s+[0-9]+$\" \"${1} ${2}\" /etc/login.defs\n}\n\n# Creates the search pattern and setting lines for useradd default settings, and calls through\n# to do the replacement. Note that this uses extended regular expressions, so both\n# grep and sed need to be called as such.\n#\n# The search pattern is:\n#   '^#{0,1} {0,1}' -- Line starts with 0 or 1 '#' followed by 0 or 1 space\n#   '${1}='         -- Then the setting name followed by '='\n#   '.*$'           -- Then 0 or nore of any character which is the end of the line.\n#                      Note that this allows for a setting value to be there or not.\n#\n# This is based on a combination of the syntax for the file and real examples we've found.\nreplaceOrAppendUserAdd() {\n    replaceOrAppendSetting \"^#{0,1} {0,1}${1}=.*$\" \"${1}=${2}\" /etc/default/useradd\n}\n\nsetPWExpiration() {\n    replaceOrAppendLoginDefs PASS_MAX_DAYS 90\n    replaceOrAppendLoginDefs PASS_MIN_DAYS 7\n    replaceOrAppendUserAdd INACTIVE 30\n}\n\n# Creates the search pattern and setting lines for the core dump settings, and calls through\n# to do the replacement. Note that this uses extended regular expressions, so both\n# grep and sed need to be called as such.\n#\n# The search pattern is:\n#  '^#{0,1} {0,1}' -- Line starts with 0 or 1 '#' followed by 0 or 1 space\n#  '${1}='         -- Then the setting name followed by '='\n#  '.*$'           -- Then 0 or nore of any character which is the end of the line.\n#\n# This is based on a combination of the syntax for the file (https://www.man7.org/linux/man-pages/man5/coredump.conf.5.html)\n# and real examples we've found.\nreplaceOrAppendCoreDump() {\n    replaceOrAppendSetting \"^#{0,1} {0,1}${1}=.*$\" \"${1}=${2}\" /etc/systemd/coredump.conf\n}\n\nconfigureCoreDump() {\n    replaceOrAppendCoreDump Storage none\n    replaceOrAppendCoreDump ProcessSizeMax 0\n}\n\nfixDefaultUmaskForAccountCreation() {\n    replaceOrAppendLoginDefs UMASK 027\n}\n\nfunction maskNfsServer() {\n    # If nfs-server.service exists, we need to mask it per CIS requirement.\n    # Note that on ubuntu systems, it isn't installed but on mariner we need it\n    # due to a dependency, but disable it by default.\n    if systemctl list-unit-files nfs-server.service >/dev/null; then\n        systemctl --now mask nfs-server || $ERR_SYSTEMCTL_MASK_FAIL\n    fi\n}\n\nfunction addFailLockDir() {\n    # Mariner V2 uses pamd faillocking, which requires a directory to store the faillock files.\n    # Default is /var/run/faillock, but that's a tmpfs, so we need to use /var/log/faillock instead.\n    # But we need to leave settings alone for other skus.\n    if [[ \"${OS}\" == \"${MARINER_OS_NAME}\" && \"${OS_VERSION}\" == \"2.0\" ]]; then\n        # Replace or append the dir setting in /etc/security/faillock.conf\n        # Docs: https://www.man7.org/linux/man-pages/man5/faillock.conf.5.html\n        #\n        # Search pattern is:\n        # '^#{0,1} {0,1}' -- Line starts with 0 or 1 '#' followed by 0 or 1 space\n        # 'dir\\s+'        -- Then the setting name followed by one or more whitespace characters\n        # '.*$'           -- Then 0 or nore of any character which is the end of the line.\n        #\n        # This is based on a combination of the syntax for the file and real examples we've found.\n        local fail_lock_dir=\"/var/log/faillock\"\n        mkdir -p ${fail_lock_dir}\n        replaceOrAppendSetting \"^#{0,1} {0,1}dir\\s+.*$\" \"dir = ${fail_lock_dir}\" /etc/security/faillock.conf\n    fi\n}\n\napplyCIS() {\n    setPWExpiration\n    assignRootPW\n    assignFilePermissions\n    configureCoreDump\n    fixDefaultUmaskForAccountCreation\n    maskNfsServer\n    addFailLockDir\n}\n\napplyCIS\n\n#EOF\n", "num_lines": 206}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "PROVISION_OUTPUT=\"/var/log/azure/cluster-provision-cse-output.log\";\necho $(date),$(hostname) > ${PROVISION_OUTPUT};\n{{if ShouldEnableCustomData}}\ncloud-init status --wait > /dev/null 2>&1;\n[ $? -ne 0 ] && echo 'cloud-init failed' >> ${PROVISION_OUTPUT} && exit 1;\necho \"cloud-init succeeded\" >> ${PROVISION_OUTPUT};\n{{end}}\n{{if IsAKSCustomCloud}}\nREPO_DEPOT_ENDPOINT=\"{{AKSCustomCloudRepoDepotEndpoint}}\"\n{{GetInitAKSCustomCloudFilepath}} >> /var/log/azure/cluster-provision.log 2>&1;\n{{end}}\nADMINUSER={{GetParameter \"linuxAdminUsername\"}}\nMOBY_VERSION={{GetParameter \"mobyVersion\"}}\nTENANT_ID={{GetVariable \"tenantID\"}}\nKUBERNETES_VERSION={{GetParameter \"kubernetesVersion\"}}\nHYPERKUBE_URL={{GetParameter \"kubernetesHyperkubeSpec\"}}\nKUBE_BINARY_URL={{GetParameter \"kubeBinaryURL\"}}\nCUSTOM_KUBE_BINARY_URL={{GetParameter \"customKubeBinaryURL\"}}\nKUBEPROXY_URL={{GetParameter \"kubeProxySpec\"}}\nAPISERVER_PUBLIC_KEY={{GetParameter \"apiServerCertificate\"}}\nSUBSCRIPTION_ID={{GetVariable \"subscriptionId\"}}\nRESOURCE_GROUP={{GetVariable \"resourceGroup\"}}\nLOCATION={{GetVariable \"location\"}}\nVM_TYPE={{GetVariable \"vmType\"}}\nSUBNET={{GetVariable \"subnetName\"}}\nNETWORK_SECURITY_GROUP={{GetVariable \"nsgName\"}}\nVIRTUAL_NETWORK={{GetVariable \"virtualNetworkName\"}}\nVIRTUAL_NETWORK_RESOURCE_GROUP={{GetVariable \"virtualNetworkResourceGroupName\"}}\nROUTE_TABLE={{GetVariable \"routeTableName\"}}\nPRIMARY_AVAILABILITY_SET={{GetVariable \"primaryAvailabilitySetName\"}}\nPRIMARY_SCALE_SET={{GetVariable \"primaryScaleSetName\"}}\nSERVICE_PRINCIPAL_CLIENT_ID={{GetParameter \"servicePrincipalClientId\"}}\nNETWORK_PLUGIN={{GetParameter \"networkPlugin\"}}\nNETWORK_POLICY={{GetParameter \"networkPolicy\"}}\nVNET_CNI_PLUGINS_URL={{GetParameter \"vnetCniLinuxPluginsURL\"}}\nCNI_PLUGINS_URL={{GetParameter \"cniPluginsURL\"}}\nCLOUDPROVIDER_BACKOFF={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoff\"}}\nCLOUDPROVIDER_BACKOFF_MODE={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoffMode\"}}\nCLOUDPROVIDER_BACKOFF_RETRIES={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoffRetries\"}}\nCLOUDPROVIDER_BACKOFF_EXPONENT={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoffExponent\"}}\nCLOUDPROVIDER_BACKOFF_DURATION={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoffDuration\"}}\nCLOUDPROVIDER_BACKOFF_JITTER={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderBackoffJitter\"}}\nCLOUDPROVIDER_RATELIMIT={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderRateLimit\"}}\nCLOUDPROVIDER_RATELIMIT_QPS={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderRateLimitQPS\"}}\nCLOUDPROVIDER_RATELIMIT_QPS_WRITE={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderRateLimitQPSWrite\"}}\nCLOUDPROVIDER_RATELIMIT_BUCKET={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderRateLimitBucket\"}}\nCLOUDPROVIDER_RATELIMIT_BUCKET_WRITE={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderRateLimitBucketWrite\"}}\nLOAD_BALANCER_DISABLE_OUTBOUND_SNAT={{GetParameterProperty \"cloudproviderConfig\" \"cloudProviderDisableOutboundSNAT\"}}\nUSE_MANAGED_IDENTITY_EXTENSION={{GetVariable \"useManagedIdentityExtension\"}}\nUSE_INSTANCE_METADATA={{GetVariable \"useInstanceMetadata\"}}\nLOAD_BALANCER_SKU={{GetVariable \"loadBalancerSku\"}}\nEXCLUDE_MASTER_FROM_STANDARD_LB={{GetVariable \"excludeMasterFromStandardLB\"}}\nMAXIMUM_LOADBALANCER_RULE_COUNT={{GetVariable \"maximumLoadBalancerRuleCount\"}}\nCONTAINER_RUNTIME={{GetParameter \"containerRuntime\"}}\nCLI_TOOL={{GetParameter \"cliTool\"}}\nCONTAINERD_DOWNLOAD_URL_BASE={{GetParameter \"containerdDownloadURLBase\"}}\nNETWORK_MODE={{GetParameter \"networkMode\"}}\nKUBE_BINARY_URL={{GetParameter \"kubeBinaryURL\"}}\nUSER_ASSIGNED_IDENTITY_ID={{GetVariable \"userAssignedIdentityID\"}}\nAPI_SERVER_NAME={{GetKubernetesEndpoint}}\nIS_VHD={{GetVariable \"isVHD\"}}\nGPU_NODE={{GetVariable \"gpuNode\"}}\nSGX_NODE={{GetVariable \"sgxNode\"}}\nMIG_NODE={{GetVariable \"migNode\"}}\nCONFIG_GPU_DRIVER_IF_NEEDED={{GetVariable \"configGPUDriverIfNeeded\"}}\nENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED={{GetVariable \"enableGPUDevicePluginIfNeeded\"}}\nTELEPORTD_PLUGIN_DOWNLOAD_URL={{GetParameter \"teleportdPluginURL\"}}\nCONTAINERD_VERSION={{GetParameter \"containerdVersion\"}}\nCONTAINERD_PACKAGE_URL={{GetParameter \"containerdPackageURL\"}}\nRUNC_VERSION={{GetParameter \"runcVersion\"}}\nRUNC_PACKAGE_URL={{GetParameter \"runcPackageURL\"}}\nENABLE_HOSTS_CONFIG_AGENT=\"{{EnableHostsConfigAgent}}\"\nDISABLE_SSH=\"{{ShouldDisableSSH}}\"\nNEEDS_CONTAINERD=\"{{NeedsContainerd}}\"\nTELEPORT_ENABLED=\"{{TeleportEnabled}}\"\nSHOULD_CONFIGURE_HTTP_PROXY=\"{{ShouldConfigureHTTPProxy}}\"\nSHOULD_CONFIGURE_HTTP_PROXY_CA=\"{{ShouldConfigureHTTPProxyCA}}\"\nHTTP_PROXY_TRUSTED_CA=\"{{GetHTTPProxyCA}}\"\nSHOULD_CONFIGURE_CUSTOM_CA_TRUST=\"{{ShouldConfigureCustomCATrust}}\"\nCUSTOM_CA_TRUST_COUNT=\"{{len GetCustomCATrustConfigCerts}}\"\n{{range $i, $cert := GetCustomCATrustConfigCerts}}\nCUSTOM_CA_CERT_{{$i}}=\"{{$cert}}\"\n{{end}}\nIS_KRUSTLET=\"{{IsKrustlet}}\"\nGPU_NEEDS_FABRIC_MANAGER=\"{{GPUNeedsFabricManager}}\"\nNEEDS_DOCKER_LOGIN=\"{{and IsDockerContainerRuntime HasPrivateAzureRegistryServer}}\"\nIPV6_DUAL_STACK_ENABLED=\"{{IsIPv6DualStackFeatureEnabled}}\"\nOUTBOUND_COMMAND=\"{{GetOutboundCommand}}\"\nENABLE_UNATTENDED_UPGRADES=\"{{EnableUnattendedUpgrade}}\"\nENSURE_NO_DUPE_PROMISCUOUS_BRIDGE=\"{{ and NeedsContainerd IsKubenet (not HasCalicoNetworkPolicy) }}\"\nSHOULD_CONFIG_SWAP_FILE=\"{{ShouldConfigSwapFile}}\"\nSHOULD_CONFIG_TRANSPARENT_HUGE_PAGE=\"{{ShouldConfigTransparentHugePage}}\"\nSHOULD_CONFIG_CONTAINERD_ULIMITS=\"{{ShouldConfigContainerdUlimits}}\"\nCONTAINERD_ULIMITS=\"{{GetContainerdUlimitString}}\"\n{{/* both CLOUD and ENVIRONMENT have special values when IsAKSCustomCloud == true */}}\n{{/* CLOUD uses AzureStackCloud and seems to be used by kubelet, k8s cloud provider */}}\n{{/* target environment seems to go to ARM SDK config */}}\n{{/* not sure why separate/inconsistent? */}}\n{{/* see GetCustomEnvironmentJSON for more weirdness. */}}\nTARGET_CLOUD=\"{{- if IsAKSCustomCloud -}} AzureStackCloud {{- else -}} {{GetTargetEnvironment}} {{- end -}}\"\nTARGET_ENVIRONMENT=\"{{GetTargetEnvironment}}\"\nCUSTOM_ENV_JSON=\"{{GetBase64EncodedEnvironmentJSON}}\"\nIS_CUSTOM_CLOUD=\"{{IsAKSCustomCloud}}\"\nCSE_HELPERS_FILEPATH=\"{{GetCSEHelpersScriptFilepath}}\"\nCSE_DISTRO_HELPERS_FILEPATH=\"{{GetCSEHelpersScriptDistroFilepath}}\"\nCSE_INSTALL_FILEPATH=\"{{GetCSEInstallScriptFilepath}}\"\nCSE_DISTRO_INSTALL_FILEPATH=\"{{GetCSEInstallScriptDistroFilepath}}\"\nCSE_CONFIG_FILEPATH=\"{{GetCSEConfigScriptFilepath}}\"\nAZURE_PRIVATE_REGISTRY_SERVER=\"{{GetPrivateAzureRegistryServer}}\"\nHAS_CUSTOM_SEARCH_DOMAIN=\"{{HasCustomSearchDomain}}\"\nCUSTOM_SEARCH_DOMAIN_FILEPATH=\"{{GetCustomSearchDomainsCSEScriptFilepath}}\"\nHTTP_PROXY_URLS=\"{{GetHTTPProxy}}\"\nHTTPS_PROXY_URLS=\"{{GetHTTPSProxy}}\"\nNO_PROXY_URLS=\"{{GetNoProxy}}\"\nPROXY_VARS=\"{{GetProxyVariables}}\"\nCLIENT_TLS_BOOTSTRAPPING_ENABLED=\"{{IsKubeletClientTLSBootstrappingEnabled}}\"\nDHCPV6_SERVICE_FILEPATH=\"{{GetDHCPv6ServiceCSEScriptFilepath}}\"\nDHCPV6_CONFIG_FILEPATH=\"{{GetDHCPv6ConfigCSEScriptFilepath}}\"\nTHP_ENABLED=\"{{GetTransparentHugePageEnabled}}\"\nTHP_DEFRAG=\"{{GetTransparentHugePageDefrag}}\"\nSERVICE_PRINCIPAL_FILE_CONTENT=\"{{GetServicePrincipalSecret}}\"\nKUBELET_CLIENT_CONTENT=\"{{GetKubeletClientKey}}\"\nKUBELET_CLIENT_CERT_CONTENT=\"{{GetKubeletClientCert}}\"\nKUBELET_CONFIG_FILE_ENABLED=\"{{IsKubeletConfigFileEnabled}}\"\nKUBELET_CONFIG_FILE_CONTENT=\"{{GetKubeletConfigFileContentBase64}}\"\nSWAP_FILE_SIZE_MB=\"{{GetSwapFileSizeMB}}\"\nGPU_DRIVER_VERSION=\"{{GPUDriverVersion}}\"\nGPU_INSTANCE_PROFILE=\"{{GetGPUInstanceProfile}}\"\nCUSTOM_SEARCH_DOMAIN_NAME=\"{{GetSearchDomainName}}\"\nCUSTOM_SEARCH_REALM_USER=\"{{GetSearchDomainRealmUser}}\"\nCUSTOM_SEARCH_REALM_PASSWORD=\"{{GetSearchDomainRealmPassword}}\"\nMESSAGE_OF_THE_DAY=\"{{GetMessageOfTheDay}}\"\nHAS_KUBELET_DISK_TYPE=\"{{HasKubeletDiskType}}\"\nNEEDS_CGROUPV2=\"{{Is2204VHD}}\"\nTLS_BOOTSTRAP_TOKEN=\"{{GetTLSBootstrapTokenForKubeConfig}}\"\nKUBELET_FLAGS=\"{{GetKubeletConfigKeyVals}}\"\nNETWORK_POLICY=\"{{GetParameter \"networkPolicy\"}}\"\n{{- if not (IsKubernetesVersionGe \"1.17.0\")}}\nKUBELET_IMAGE=\"{{GetHyperkubeImageReference}}\"\n{{end}}\n{{if IsKubernetesVersionGe \"1.16.0\"}}\nKUBELET_NODE_LABELS=\"{{GetAgentKubernetesLabels . }}\"\n{{else}}\nKUBELET_NODE_LABELS=\"{{GetAgentKubernetesLabelsDeprecated . }}\"\n{{end}}\nAZURE_ENVIRONMENT_FILEPATH=\"{{- if IsAKSCustomCloud}}/etc/kubernetes/{{GetTargetEnvironment}}.json{{end}}\"\nKUBE_CA_CRT=\"{{GetParameter \"caCertificate\"}}\"\nKUBENET_TEMPLATE=\"{{GetKubenetTemplate}}\"\nCONTAINERD_CONFIG_CONTENT=\"{{GetContainerdConfigContent}}\"\nCONTAINERD_CONFIG_NO_GPU_CONTENT=\"{{GetContainerdConfigNoGPUContent}}\"\nIS_KATA=\"{{IsKata}}\"\nSYSCTL_CONTENT=\"{{GetSysctlContent}}\"\n/usr/bin/nohup /bin/bash -c \"/bin/bash /opt/azure/containers/provision_start.sh\"", "num_lines": 153}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script originated at https://github.com/kubernetes/kubernetes/blob/master/cluster/gce/gci/health-monitor.sh\n# and has been modified for aks-engine.\n\nset -o nounset\nset -o pipefail\n\ncontainer_runtime_monitoring() {\n  local -r max_attempts=5\n  local attempt=1\n  local -r container_runtime_name=$1\n\n  if [[ ${container_runtime_name} == \"containerd\" ]]; then\n    local healthcheck_command=\"ctr --namespace k8s.io container list\"\n  else \n    local healthcheck_command=\"docker ps\"\n  fi\n\n  until timeout 60 ${healthcheck_command} > /dev/null; do\n    if (( attempt == max_attempts )); then\n      echo \"Max attempt ${max_attempts} reached! Proceeding to monitor container runtime healthiness.\"\n      break\n    fi\n    echo \"$attempt initial attempt \\\"${healthcheck_command}\\\"! Trying again in $attempt seconds...\"\n    sleep \"$(( 2 ** attempt++ ))\"\n  done\n  while true; do\n    if ! timeout 60 ${healthcheck_command} > /dev/null; then\n      echo \"Container runtime ${container_runtime_name} failed!\"\n      if [[ \"$container_runtime_name\" == \"containerd\" ]]; then\n        pkill -SIGUSR1 containerd\n      else \n        pkill -SIGUSR1 dockerd\n      fi\n      systemctl kill --kill-who=main \"${container_runtime_name}\"\n      sleep 120\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\nkubelet_monitoring() {\n  echo \"Wait for 2 minutes for kubelet to be functional\"\n  sleep 120\n  local -r max_seconds=10\n  local output=\"\"\n  while true; do\n    if ! output=$(curl -m \"${max_seconds}\" -f -s -S http://127.0.0.1:10255/healthz 2>&1); then\n      echo $output\n      echo \"Kubelet is unhealthy!\"\n      systemctl kill kubelet\n      sleep 60\n    else\n      sleep \"${SLEEP_SECONDS}\"\n    fi\n  done\n}\n\nif [[ \"$#\" -lt 1 ]]; then\n  echo \"Usage: health-monitor.sh <container-runtime/kubelet>\"\n  exit 1\nfi\n\ncomponent=$1\nif [[ \"${component}\" == \"container-runtime\" ]]; then\n  if [[ -z $2 ]]; then\n    echo \"Usage: health-monitor.sh container-runtime <docker/containerd>\"\n    exit 1\n  fi\n  container_runtime=$2\nfi\n\nKUBE_HOME=\"/usr/local/bin\"\nKUBE_ENV=\"/etc/default/kube-env\"\nif [[  -e \"${KUBE_ENV}\" ]]; then\n  source \"${KUBE_ENV}\"\nfi\n\nSLEEP_SECONDS=10\n\necho \"Start kubernetes health monitoring for ${component}\"\n\nif [[ \"${component}\" == \"container-runtime\" ]]; then\n  container_runtime_monitoring ${container_runtime}\nelif [[ \"${component}\" == \"kubelet\" ]]; then\n  kubelet_monitoring\nelse\n  echo \"Health monitoring for component ${component} is not supported!\"\nfi\n", "num_lines": 92}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nmkdir -p /root/AzureCACertificates\n# http://168.63.129.16 is a constant for the host's wireserver endpoint\ncerts=$(curl \"http://168.63.129.16/machine?comp=acmspackage&type=cacertificates&ext=json\")\nIFS_backup=$IFS\nIFS=$'\\r\\n'\ncertNames=($(echo $certs | grep -oP '(?<=Name\\\": \\\")[^\\\"]*'))\ncertBodies=($(echo $certs | grep -oP '(?<=CertBody\\\": \\\")[^\\\"]*'))\nfor i in ${!certBodies[@]}; do\n    echo ${certBodies[$i]}  | sed 's/\\\\r\\\\n/\\n/g' | sed 's/\\\\//g' > \"/root/AzureCACertificates/$(echo ${certNames[$i]} | sed 's/.cer/.crt/g')\"\ndone\nIFS=$IFS_backup\n\ncp /root/AzureCACertificates/*.crt /etc/pki/ca-trust/source/anchors/\n/usr/bin/update-ca-trust\n\ncloud-init status --wait\n\n# TODO - Set the repoDepotEndpoint in a .repo file if package update becomes necessary\n\n# Set the chrony config to use the PHC /dev/ptp0 clock\ncat > /etc/chrony.conf <<EOF\n# This directive specify the location of the file containing ID/key pairs for\n# NTP authentication.\nkeyfile /etc/chrony.keys\n\n# This directive specify the file into which chronyd will store the rate\n# information.\ndriftfile /var/lib/chrony/drift\n\n# Uncomment the following line to turn logging on.\n#log tracking measurements statistics\n\n# Log files location.\nlogdir /var/log/chrony\n\n# Stop bad estimates upsetting machine clock.\nmaxupdateskew 100.0\n\n# This directive enables kernel synchronisation (every 11 minutes) of the\n# real-time clock. Note that it can\u00e2\u20ac\u2122t be used along with the 'rtcfile' directive.\nrtcsync\n\n# Settings come from: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync\nrefclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\nmakestep 1.0 -1\nEOF\n\nsystemctl restart chronyd\n\n#EOF", "num_lines": 51}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nmkdir -p /root/AzureCACertificates\n# http://168.63.129.16 is a constant for the host's wireserver endpoint\ncerts=$(curl \"http://168.63.129.16/machine?comp=acmspackage&type=cacertificates&ext=json\")\nIFS_backup=$IFS\nIFS=$'\\r\\n'\ncertNames=($(echo $certs | grep -oP '(?<=Name\\\": \\\")[^\\\"]*'))\ncertBodies=($(echo $certs | grep -oP '(?<=CertBody\\\": \\\")[^\\\"]*'))\nfor i in ${!certBodies[@]}; do\n    echo ${certBodies[$i]}  | sed 's/\\\\r\\\\n/\\n/g' | sed 's/\\\\//g' > \"/root/AzureCACertificates/$(echo ${certNames[$i]} | sed 's/.cer/.crt/g')\"\ndone\nIFS=$IFS_backup\n\ncp /root/AzureCACertificates/*.crt /usr/local/share/ca-certificates/\n/usr/sbin/update-ca-certificates\n\n# This copies the updated bundle to the location used by OpenSSL which is commonly used\ncp /etc/ssl/certs/ca-certificates.crt /usr/lib/ssl/cert.pem\n\n# This section creates a cron job to poll for refreshed CA certs daily\n# It can be removed if not needed or desired\naction=${1:-init}\nif [ $action == \"ca-refresh\" ]\nthen\n    exit\nfi\n\n(crontab -l ; echo \"0 19 * * * $0 ca-refresh\") | crontab -\n\ncloud-init status --wait\nrepoDepotEndpoint=\"${REPO_DEPOT_ENDPOINT}\"\nsudo sed -i \"s,http://.[^ ]*,$repoDepotEndpoint,g\" /etc/apt/sources.list\n\n# Disable systemd-timesyncd and install chrony and uses local time source\nsystemctl stop systemd-timesyncd\nsystemctl disable systemd-timesyncd\n\napt-get update\napt-get install chrony -y\ncat > /etc/chrony/chrony.conf <<EOF\n# Welcome to the chrony configuration file. See chrony.conf(5) for more\n# information about usuable directives.\n\n# This will use (up to):\n# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled\n# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well\n# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)\n# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only\n# sources will be used.\n# At the same time it retains some protection against one of the entries being\n# down (compare to just using one of the lines). See (LP: #1754358) for the\n# discussion.\n#\n# About using servers from the NTP Pool Project in general see (LP: #104525).\n# Approved by Ubuntu Technical Board on 2011-02-08.\n# See http://www.pool.ntp.org/join.html for more information.\n#pool ntp.ubuntu.com        iburst maxsources 4\n#pool 0.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 1.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 2.ubuntu.pool.ntp.org iburst maxsources 2\n\n# This directive specify the location of the file containing ID/key pairs for\n# NTP authentication.\nkeyfile /etc/chrony/chrony.keys\n\n# This directive specify the file into which chronyd will store the rate\n# information.\ndriftfile /var/lib/chrony/chrony.drift\n\n# Uncomment the following line to turn logging on.\n#log tracking measurements statistics\n\n# Log files location.\nlogdir /var/log/chrony\n\n# Stop bad estimates upsetting machine clock.\nmaxupdateskew 100.0\n\n# This directive enables kernel synchronisation (every 11 minutes) of the\n# real-time clock. Note that it can\u00e2\u20ac\u2122t be used along with the 'rtcfile' directive.\nrtcsync\n\n# Settings come from: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync\nrefclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\nmakestep 1.0 -1\nEOF\n\nsystemctl restart chrony\n\n#EOF", "num_lines": 90}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nset -uo pipefail\nset -x\nset -e\n\nNFTABLES_RULESET_FILE=/etc/systemd/system/ipv6_nftables\n\n# query IMDS to check if node has IPv6\n# example interface\n# [\n#   {\n#     \"ipv4\": {\n#       \"ipAddress\": [\n#         {\n#           \"privateIpAddress\": \"10.224.0.4\",\n#           \"publicIpAddress\": \"\"\n#         }\n#       ],\n#       \"subnet\": [\n#         {\n#           \"address\": \"10.224.0.0\",\n#           \"prefix\": \"16\"\n#         }\n#       ]\n#     },\n#     \"ipv6\": {\n#       \"ipAddress\": [\n#         {\n#           \"privateIpAddress\": \"fd85:534e:4cd6:ab02::5\"\n#         }\n#       ]\n#     },\n#     \"macAddress\": \"000D3A98DA20\"\n#   }\n# ]\n\n# check the number of IPv6 addresses this instance has from IMDS\nIPV6_ADDR_COUNT=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/network/interface?api-version=2021-02-01\" | \\\n    jq '[.[].ipv6.ipAddress[] | select(.privateIpAddress != \"\")] | length')\n\nif [[ $IPV6_ADDR_COUNT -eq 0 ]];\nthen\n    echo \"instance is not configured with IPv6, skipping nftables rules\"\nelse\n    echo \"writing nftables from $NFTABLES_RULESET_FILE\"\n    nft -f $NFTABLES_RULESET_FILE\nfi\n", "num_lines": 49}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# 5.4.4 Ensure default user umask is 027 or more restrictive\numask 027\n", "num_lines": 5}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nSRC=/var/log/containers\nDST=/var/log/azure/aks/pods\n\n# Bring in OS-related bash vars\nsource /etc/os-release\n\n# Install inotify-tools if they're missing from the image\nif [[ ${ID} == \"mariner\" ]]; then\n  command -v inotifywait >/dev/null 2>&1 || dnf install -y inotify-tools\nelse \n  command -v inotifywait >/dev/null 2>&1 || apt-get -o DPkg::Lock::Timeout=300 -y install inotify-tools\nfi\n\n# Set globbing options so that compgen grabs only the logs we want\nshopt -s extglob\nshopt -s nullglob\n\n# Wait for /var/log/containers to exist\nif [ ! -d $SRC ]; then\n  echo -n \"Waiting for $SRC to exist...\"\n  while [ ! -d $SRC ]; do\n    sleep 15\n    echo -n \".\"\n  done\n  echo \"done.\"\nfi\n\n# Make the destination directory if not already present\nmkdir -p $DST\n\n# Start a background process to clean up logs from deleted pods that\n# haven't been modified in 2 hours. This allows us to retain pod\n# logs after a restart.\nwhile true; do\n  find /var/log/azure/aks/pods -type f -links 1 -mmin +120 -delete\n  sleep 3600\ndone &\n\n# Manually sync all matching logs once\nfor CONTAINER_LOG_FILE in $(compgen -G \"$SRC/*_kube-system_*.log\"); do\n   echo \"Linking $CONTAINER_LOG_FILE\"\n   /bin/ln -Lf $CONTAINER_LOG_FILE $DST/\ndone\necho \"Starting inotifywait...\"\n\n# Monitor for changes\ninotifywait -q -m -r -e delete,create $SRC | while read DIRECTORY EVENT FILE; do\n    case $FILE in\n        *_kube-system_*.log)\n            case $EVENT in\n                CREATE*)\n                    echo \"Linking $FILE\"\n                    /bin/ln -Lf \"$DIRECTORY/$FILE\" \"$DST/$FILE\"\n                    ;;\n            esac;;\n    esac\ndone\n", "num_lines": 60}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -uo pipefail\n\ncertSource=/opt/certs\ncertDestination=\"${1:-/usr/local/share/ca-certificates/certs}\"\nupdateCmd=\"${2:-update-ca-certificates -f}\"\ndestPrefix=\"aks-custom-\"\n\n[ ! -d \"$certDestination\" ] && mkdir \"$certDestination\"\nfor file in \"$certSource\"/*; do\n  [ -f \"$file\" ] || continue\n  cp -a -- \"$file\" \"$certDestination/$destPrefix${file##*/}\"\ndone\n\nif [[ -z $(ls -A \"$certSource\") ]]; then\n  echo \"Source dir \"$certSource\" was empty, attempting to remove cert files\"\n  ls \"$certDestination\" | grep -E '^'$destPrefix'[0-9]{14}' | while read -r line; do\n    echo \"removing \"$line\" in \"$certDestination\"\"\n    rm $certDestination/\"$line\"\n  done\nelse\n  echo \"found cert files in \"$certSource\"\"\n  certsToCopy=(${certSource}/*)\n  currIterationCertFile=${certsToCopy[0]##*/}\n  currIterationTag=${currIterationCertFile:0:14}\n  for file in \"$certDestination/$destPrefix\"*.crt; do\n     currFile=${file##*/}\n     if [[ \"${currFile:${#destPrefix}:14}\" != \"${currIterationTag}\" && -f \"${file}\" ]]; then\n          echo \"removing \"$file\" in \"$certDestination\"\"\n          rm \"${file}\"\n     fi\n  done\nfi\n\n$updateCmd", "num_lines": 35}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "# !/bin/bash\n\nif [[ $# -ne 1 ]]; then\n    echo \"Usage: $0 <test-case-data-folder>\"\n    exit 1;\nfi\n\nrm $1/line*.sh\nfile=\"./$1/CustomData\"\n#echo \"Processing $file\"\nlineNumber=`grep \"content: \\!\\!binary\"  -n $file | cut -d':' -f1`\nfor i in $lineNumber; do\nc=$((i+1));\n#echo \"Working on line $c\";\nz=`sed -n ${c}p $file`\n\necho $z | base64 --decode | gunzip > $1/line${c}.sh\ndone", "num_lines": 18}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\n/bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(head -c 3000 \"/var/log/azure/cluster-provision-cse-output.log\")\nKUBELET_START_TIME=$(echo \"$OUTPUT\" | cut -d ',' -f -1 | head -1)\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\necho $JSON_STRING\nexit $EXIT_CODE", "num_lines": 24}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s /opt/azure/containers/provision_source.sh ]; then\n        grep -Fq '#HELPERSEOF' /opt/azure/containers/provision_source.sh && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" /opt/azure/containers/provision_source.sh\nsource /opt/azure/containers/provision_source.sh\n\nwait_for_file 3600 1 /opt/azure/containers/provision_source_distro.sh || exit $ERR_FILE_WATCH_TIMEOUT\nsource /opt/azure/containers/provision_source_distro.sh\n\nwait_for_file 3600 1 /opt/azure/containers/provision_installs.sh || exit $ERR_FILE_WATCH_TIMEOUT\nsource /opt/azure/containers/provision_installs.sh\n\nwait_for_file 3600 1 /opt/azure/containers/provision_installs_distro.sh || exit $ERR_FILE_WATCH_TIMEOUT\nsource /opt/azure/containers/provision_installs_distro.sh\n\nwait_for_file 3600 1 /opt/azure/containers/provision_configs.sh || exit $ERR_FILE_WATCH_TIMEOUT\nsource /opt/azure/containers/provision_configs.sh\n\nif [[ \"${GPU_NODE}\" != \"true\" ]]; then\n    cleanUpGPUDrivers\nfi\n\ndisable1804SystemdResolved\n\nif [ -f /var/run/reboot-required ]; then\n    REBOOTREQUIRED=true\nelse\n    REBOOTREQUIRED=false\nfi\n\nconfigureAdminUser\n# If crictl gets installed then use it as the cri cli instead of ctr\n# crictl is not a critical component so continue with boostrapping if the install fails\n# CLI_TOOL is by default set to \"ctr\"\ninstallCrictl && CLI_TOOL=\"crictl\"\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\ninstallContainerRuntime\n\ninstallKubeletKubectlAndKubeProxy\n\nensureRPC\n\ncreateKubeManifestDir\n\nconfigureK8s\n\n\nensureContainerd \n\nensureMonitorService\n\nensureSysctl\nensureJournal\nensureKubelet\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\nrm -f /etc/apt/apt.conf.d/99periodic\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n    apt_get_purge 20 30 120 apache2-utils &\nfi\n\nVALIDATION_ERR=0\nAPI_SERVER_DNS_RETRIES=100\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n  API_SERVER_DNS_RETRIES=200\nfi\nRES=$(retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 10 nslookup ${API_SERVER_NAME})\nSTS=$?\nif [[ $STS != 0 ]]; then\n    time nslookup ${API_SERVER_NAME}\n    if [[ $RES == *\"168.63.129.16\"*  ]]; then\n        VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n    else\n        VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n    fi\nelse\n    API_SERVER_CONN_RETRIES=50\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n        API_SERVER_CONN_RETRIES=100\n    fi\n    retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443 || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\n# If it is a MIG Node, enable mig-partition systemd service to create MIG instances\nif [[ \"${MIG_NODE}\" == \"true\" ]]; then\n    REBOOTREQUIRED=true\n    ensureMigPartition\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        /usr/lib/apt/apt.systemd.daily &\n        aptmarkWALinuxAgent unhold &\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\nps auxfww > /opt/azure/provision-ps.log &\n\nexit $VALIDATION_ERR\n\n#EOF\n", "num_lines": 161}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nKRUSTLET_VERSION=\"v1.0.0-alpha.1\"\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    \n        installStandaloneContainerd ${CONTAINERD_VERSION}\n    \n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadKrustlet() {\n    local krustlet_url=\"https://acs-mirror.azureedge.net/krustlet/${KRUSTLET_VERSION}/linux/amd64/krustlet-wasi\"\n    local krustlet_filepath=\"/usr/local/bin/krustlet-wasi\"\n    if [[ -f \"$krustlet_filepath\" ]]; then\n        installed_version=\"$(\"$krustlet_filepath\" --version | cut -d' ' -f2)\"\n        if [[ \"${KRUSTLET_VERSION}\" == \"$installed_version\" ]]; then\n            echo \"desired krustlet version exists on disk, skipping download.\"\n            return\n        fi\n        rm -rf \"$krustlet_filepath\"\n    fi\n    retrycmd_if_failure 30 5 60 curl -fSL -o \"$krustlet_filepath\" \"$krustlet_url\" || exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT\n    chmod 755 \"$krustlet_filepath\"\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://github.com/kubernetes-sigs/cri-tools/releases/download/v${CRICTL_VERSION}/crictl-v${CRICTL_VERSION}-linux-amd64.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    local CRICTL_VERSION=${KUBERNETES_VERSION%.*}.0\n    if [[ ${currentVersion} =~ ${CRICTL_VERSION} ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${CRICTL_VERSION}\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-amd64.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n    rm -rf ${CRICTL_DOWNLOAD_DIR}\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n        downloadCNI\n    fi\n    mkdir -p $CNI_BIN_DIR\n    tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n        downloadAzureCNI\n    fi\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n    mkdir -p $CNI_BIN_DIR\n    tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\nextractHyperkube() {\n    CLI_TOOL=$1\n    path=\"/home/hyperkube-downloads/${KUBERNETES_VERSION}\"\n    pullContainerImage $CLI_TOOL ${HYPERKUBE_URL}\n    mkdir -p \"$path\"\n    if [[ \"$CLI_TOOL\" == \"ctr\" ]]; then\n        if ctr --namespace k8s.io run --rm --mount type=bind,src=$path,dst=$path,options=bind:rw ${HYPERKUBE_URL} extractTask /bin/bash -c \"cp /usr/local/bin/{kubelet,kubectl} $path\"; then\n            mv \"$path/kubelet\" \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\"\n            mv \"$path/kubectl\" \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\"\n        else\n            ctr --namespace k8s.io run --rm --mount type=bind,src=$path,dst=$path,options=bind:rw ${HYPERKUBE_URL} extractTask /bin/bash -c \"cp /hyperkube $path\"\n        fi\n\n    else\n        if docker run --rm --entrypoint \"\" -v $path:$path ${HYPERKUBE_URL} /bin/bash -c \"cp /usr/local/bin/{kubelet,kubectl} $path\"; then\n            mv \"$path/kubelet\" \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\"\n            mv \"$path/kubectl\" \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\"\n        else\n            docker run --rm -v $path:$path ${HYPERKUBE_URL} /bin/bash -c \"cp /hyperkube $path\"\n        fi\n    fi\n\n    cp \"$path/hyperkube\" \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\"\n    mv \"$path/hyperkube\" \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n    if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n        #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n        if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n            extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n        else\n            if [[ \"$CONTAINER_RUNTIME\" == \"containerd\" ]]; then\n                extractHyperkube \"ctr\"\n            else\n                extractHyperkube \"docker\"\n            fi\n        fi\n    fi\n\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n\n    if [ -n \"${KUBEPROXY_URL}\" ]; then\n        #kubeproxy is a system addon that is dictated by control plane so it shouldn't block node provisioning\n        pullContainerImage ${CLI_TOOL} ${KUBEPROXY_URL} &\n    fi\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL || ( echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT )\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL || ( echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT )\n    else\n        retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL || ( echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT )\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image rm $CONTAINER_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl rmi $CONTAINER_IMAGE_URL\n    else\n        docker image rm $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        \n        if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n            images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        else\n            images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        \n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                \n                removeContainerImage ${CLI_TOOL} ${image}\n                \n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpHyperkubeImages() {\n    echo $(date),$(hostname), cleanUpHyperkubeImages\n    cleanUpImages \"hyperkube\"\n    echo $(date),$(hostname), endCleanUpHyperkubeImages\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanUpContainerImages() {\n    # run cleanUpHyperkubeImages and cleanUpKubeProxyImages concurrently\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpHyperkubeImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpHyperkubeImages &\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat << EOF >> ${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 282}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 60 apt-get purge -y moby-engine moby-cli\n}\n\nremoveContainerd() {\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 60 apt-get purge -y moby-containerd\n}\n\ninstallDeps() {\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    apt_get_dist_upgrade || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for apt_package in apache2-utils apt-transport-https blobfuse=1.3.7 ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool fuse git glusterfs-client htop iftop init-system-helpers iotop iproute2 ipset iptables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils zip; do\n      if ! apt_get_install 30 1 600 $apt_package; then\n        journalctl --no-pager -u $apt_package\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\ninstallGPUDrivers() {\n    mkdir -p $GPU_DEST/tmp\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/gpgkey > $GPU_DEST/tmp/aptnvidia.gpg || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-key add $GPU_DEST/tmp/aptnvidia.gpg || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu${UBUNTU_RELEASE}/nvidia-docker.list > $GPU_DEST/tmp/nvidia-docker.list || exit  $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    wait_for_apt_locks\n    retrycmd_if_failure_no_stats 120 5 25 cat $GPU_DEST/tmp/nvidia-docker.list > /etc/apt/sources.list.d/nvidia-docker.list || exit  $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    apt_get_update\n    retrycmd_if_failure 30 5 3600 apt-get install -y linux-headers-$(uname -r) gcc make dkms || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    retrycmd_if_failure 30 5 60 curl -fLS https://us.download.nvidia.com/tesla/$GPU_DV/NVIDIA-Linux-x86_64-${GPU_DV}.run -o ${GPU_DEST}/nvidia-drivers-${GPU_DV} || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    tmpDir=$GPU_DEST/tmp\n    if ! (\n      set -e -o pipefail\n      cd \"${tmpDir}\"\n      retrycmd_if_failure 30 5 3600 apt-get download nvidia-docker2=\"${NVIDIA_DOCKER_VERSION}\" || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    ); then\n      exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\ninstallSGXDrivers() {\n    echo \"Installing SGX driver\"\n    local VERSION\n    VERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    case $VERSION in\n    \"18.04\")\n        SGX_DRIVER_URL=\"https://download.01.org/intel-sgx/dcap-1.2/linux/dcap_installers/ubuntuServer18.04/sgx_linux_x64_driver_1.12_c110012.bin\"\n        ;;\n    \"16.04\")\n        SGX_DRIVER_URL=\"https://download.01.org/intel-sgx/dcap-1.2/linux/dcap_installers/ubuntuServer16.04/sgx_linux_x64_driver_1.12_c110012.bin\"\n        ;;\n    \"*\")\n        echo \"Version $VERSION is not supported\"\n        exit 1\n        ;;\n    esac\n\n    local PACKAGES=\"make gcc dkms\"\n    wait_for_apt_locks\n    retrycmd_if_failure 30 5 3600 apt-get -y install $PACKAGES  || exit $ERR_SGX_DRIVERS_INSTALL_TIMEOUT\n\n    local SGX_DRIVER\n    SGX_DRIVER=$(basename $SGX_DRIVER_URL)\n    local OE_DIR=/opt/azure/containers/oe\n    mkdir -p ${OE_DIR}\n\n    retrycmd_if_failure 120 5 25 curl -fsSL ${SGX_DRIVER_URL} -o ${OE_DIR}/${SGX_DRIVER} || exit $ERR_SGX_DRIVERS_INSTALL_TIMEOUT\n    chmod a+x ${OE_DIR}/${SGX_DRIVER}\n    ${OE_DIR}/${SGX_DRIVER} || exit $ERR_SGX_DRIVERS_START_FAIL\n}\n\nupdateAptWithMicrosoftPkg() {\n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.4.8\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}\"\n    fi\n\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeMoby\n        removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        if [ -f $VHD_LOGS_FILEPATH ]; then\n            CONTAINERD_DEB_TMP=\"moby-containerd_${CONTAINERD_VERSION/-/\\~}+azure-1_amd64.deb\"\n            CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n            if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n                installDebPackageFromFile ${CONTAINERD_DEB_FILE} || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n                return 0\n            fi\n        fi\n        updateAptWithMicrosoftPkg\n        apt_get_install 20 30 120 moby-containerd=${CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    fi\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n}\n\ndownloadContainerd() {\n    CONTAINERD_VERSION=$1\n    # currently upstream maintains the package on a storage endpoint rather than an actual apt repo\n    CONTAINERD_DOWNLOAD_URL=\"https://mobyartifacts.azureedge.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/bionic/linux_amd64/moby-containerd_${CONTAINERD_VERSION/-/\\~}+azure-1_amd64.deb\"\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n}\n\nensureRunc() {\n    TARGET_VERSION=$1\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.0.0-rc95\"\n    fi\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    if [ \"${CURRENT_VERSION}\" == \"${TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${TARGET_VERSION} is already installed. skipping installRunc.\"\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_${TARGET_VERSION/-/\\~}+azure-*_amd64.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION/-/\\~}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST\n    rm -f /etc/apt/sources.list.d/nvidia-docker.list\n}\n\n#EOF\n", "num_lines": 181}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nensureRPC() {\n    systemctlEnableAndStart rpcbind || exit $ERR_SYSTEMCTL_START_FAIL\n    systemctlEnableAndStart rpc-statd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    KUBELET_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/client.key\"\n    touch \"${KUBELET_PRIVATE_KEY_PATH}\"\n    chmod 0600 \"${KUBELET_PRIVATE_KEY_PATH}\"\n    chown root:root \"${KUBELET_PRIVATE_KEY_PATH}\"\n\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    set +x\n    echo \"${KUBELET_PRIVATE_KEY}\" | base64 --decode > \"${KUBELET_PRIVATE_KEY_PATH}\"\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    \n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"AzurePublicCloud\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n}\n\nconfigureCNI() {\n    \n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisable1804SystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    echo \"Disable1804SystemdResolved is false. Skipping.\"\n}\nensureContainerd() {\n  wait_for_file 1200 1 /etc/systemd/system/containerd.service.d/exec_start.conf || exit $ERR_FILE_WATCH_TIMEOUT\n  wait_for_file 1200 1 /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  wait_for_file 1200 1 /etc/sysctl.d/11-containerd.conf || exit $ERR_FILE_WATCH_TIMEOUT\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\nensureMonitorService() {\n    \n    CONTAINERD_MONITOR_SYSTEMD_TIMER_FILE=/etc/systemd/system/containerd-monitor.timer\n    wait_for_file 1200 1 $CONTAINERD_MONITOR_SYSTEMD_TIMER_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    CONTAINERD_MONITOR_SYSTEMD_FILE=/etc/systemd/system/containerd-monitor.service\n    wait_for_file 1200 1 $CONTAINERD_MONITOR_SYSTEMD_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    systemctlEnableAndStart containerd-monitor.timer || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\n\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    wait_for_file 1200 1 $KUBELET_DEFAULT_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n    wait_for_file 1200 1 $KUBECONFIG_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    wait_for_file 1200 1 $KUBELET_RUNTIME_CONFIG_SCRIPT_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n    \n    \n}\n\nensureMigPartition(){\n    systemctlEnableAndStart mig-partition || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    wait_for_file 1200 1 $SYSCTL_CONFIG_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureJournal() {\n    {\n        echo \"Storage=persistent\"\n        echo \"SystemMaxUse=1G\"\n        echo \"RuntimeMaxUse=1G\"\n        echo \"ForwardToSyslog=yes\"\n    } >> /etc/systemd/journald.conf\n    systemctlEnableAndStart systemd-journald || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    wait_for_file 1200 1 $CLUSTER_AUTOSCALER_ADDON_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    wait_for_file 1200 1 $ACI_CONNECTOR_ADDON_FILE || exit $ERR_FILE_WATCH_TIMEOUT\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\n\n#EOF\n", "num_lines": 248}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\n\n[Service]\nRestart=always\nEnvironmentFile=/etc/default/kubelet\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 30}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nERR_SYSTEMCTL_START_FAIL=4 \nERR_CLOUD_INIT_TIMEOUT=5 \nERR_FILE_WATCH_TIMEOUT=6 \nERR_HOLD_WALINUXAGENT=7 \nERR_RELEASE_HOLD_WALINUXAGENT=8 \nERR_APT_INSTALL_TIMEOUT=9 \nERR_DOCKER_INSTALL_TIMEOUT=20 \nERR_DOCKER_DOWNLOAD_TIMEOUT=21 \nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 \nERR_DOCKER_APT_KEY_TIMEOUT=23 \nERR_DOCKER_START_FAIL=24 \nERR_MOBY_APT_LIST_TIMEOUT=25 \nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 \nERR_MOBY_INSTALL_TIMEOUT=27 \nERR_CONTAINERD_INSTALL_TIMEOUT=28 \nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 \nERR_RUNC_INSTALL_TIMEOUT=29 \nERR_K8S_RUNNING_TIMEOUT=30 \nERR_K8S_DOWNLOAD_TIMEOUT=31 \nERR_KUBECTL_NOT_FOUND=32 \nERR_IMG_DOWNLOAD_TIMEOUT=33 \nERR_KUBELET_START_FAIL=34 \nERR_DOCKER_IMG_PULL_TIMEOUT=35 \nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 \nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 \nERR_CNI_DOWNLOAD_TIMEOUT=41 \nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 \nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 \n\nERR_SYSTEMD_INSTALL_FAIL=48 \nERR_MODPROBE_FAIL=49 \nERR_OUTBOUND_CONN_FAIL=50 \nERR_K8S_API_SERVER_CONN_FAIL=51 \nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 \nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 \nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 \nERR_KATA_APT_KEY_TIMEOUT=61 \nERR_KATA_INSTALL_TIMEOUT=62 \nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 \nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 \nERR_GPU_DRIVERS_START_FAIL=84 \nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 \nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 \nERR_GPU_INFO_ROM_CORRUPTED=87 \nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 \nERR_SGX_DRIVERS_START_FAIL=91 \nERR_APT_DAILY_TIMEOUT=98 \nERR_APT_UPDATE_TIMEOUT=99 \nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 \nERR_APT_DIST_UPGRADE_TIMEOUT=101 \nERR_APT_PURGE_FAIL=102 \nERR_SYSCTL_RELOAD=103 \nERR_CIS_ASSIGN_ROOT_PW=111 \nERR_CIS_ASSIGN_FILE_PERMISSION=112 \nERR_PACKER_COPY_FILE=113 \nERR_CIS_APPLY_PASSWORD_CONFIG=115 \nERR_SYSTEMD_DOCKER_STOP_FAIL=116 \nERR_CRICTL_DOWNLOAD_TIMEOUT=117 \nERR_CRICTL_OPERATION_ERROR=118 \nERR_CTR_OPERATION_ERROR=119 \n\nERR_VHD_FILE_NOT_FOUND=124 \nERR_VHD_BUILD_ERROR=125 \n\n\nERR_AZURE_STACK_GET_ARM_TOKEN=120 \nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 \nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 \n\nERR_SWAP_CREAT_FAIL=130 \nERR_SWAP_CREAT_INSUFFICIENT_DISK_SPACE=131 \n\nERR_TELEPORTD_DOWNLOAD_ERR=150 \nERR_TELEPORTD_INSTALL_ERR=151 \n\nERR_HTTP_PROXY_CA_CONVERT=160 \nERR_HTTP_PROXY_CA_UPDATE=161 \n\nERR_DISBALE_IPTABLES=170 \n\nERR_MIG_PARTITION_FAILURE=180 \nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 \n\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\nexport GPU_DV=470.57.02\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=3.6.0-1\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSL $url -o $tarball\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSL $url -o $filepath\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\n#HELPERSEOF\n", "num_lines": 257}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Service]\nEnvironment=KUBELET_CONTAINERD_FLAGS=\"--container-runtime=remote --runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock\"\n", "num_lines": 3}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nmkdir -p /root/AzureCACertificates\n# http://168.63.129.16 is a constant for the host's wireserver endpoint\ncerts=$(curl \"http://168.63.129.16/machine?comp=acmspackage&type=cacertificates&ext=json\")\nIFS_backup=$IFS\nIFS=$'\\r\\n'\ncertNames=($(echo $certs | grep -oP '(?<=Name\\\": \\\")[^\\\"]*'))\ncertBodies=($(echo $certs | grep -oP '(?<=CertBody\\\": \\\")[^\\\"]*'))\nfor i in ${!certBodies[@]}; do\n    echo ${certBodies[$i]}  | sed 's/\\\\r\\\\n/\\n/g' | sed 's/\\\\//g' > \"/root/AzureCACertificates/$(echo ${certNames[$i]} | sed 's/.cer/.crt/g')\"\ndone\nIFS=$IFS_backup\n\ncp /root/AzureCACertificates/*.crt /usr/local/share/ca-certificates/\n/usr/sbin/update-ca-certificates\n\n# This copies the updated bundle to the location used by OpenSSL which is commonly used\ncp /etc/ssl/certs/ca-certificates.crt /usr/lib/ssl/cert.pem\n\n# This section creates a cron job to poll for refreshed CA certs daily\n# It can be removed if not needed or desired\naction=${1:-init}\nif [ $action == \"ca-refresh\" ]\nthen\n    exit\nfi\n\n(crontab -l ; echo \"0 19 * * * $0 ca-refresh\") | crontab -\n\ncloud-init status --wait\nrepoDepotEndpoint=\"${REPO_DEPOT_ENDPOINT}\"\nsudo sed -i \"s,http://.[^ ]*,$repoDepotEndpoint,g\" /etc/apt/sources.list\n\n# Disable systemd-timesyncd and install chrony and uses local time source\nsystemctl stop systemd-timesyncd\nsystemctl disable systemd-timesyncd\n\napt-get update\napt-get install chrony -y\ncat > /etc/chrony/chrony.conf <<EOF\n# Welcome to the chrony configuration file. See chrony.conf(5) for more\n# information about usuable directives.\n\n# This will use (up to):\n# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled\n# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well\n# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)\n# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only\n# sources will be used.\n# At the same time it retains some protection against one of the entries being\n# down (compare to just using one of the lines). See (LP: #1754358) for the\n# discussion.\n#\n# About using servers from the NTP Pool Project in general see (LP: #104525).\n# Approved by Ubuntu Technical Board on 2011-02-08.\n# See http://www.pool.ntp.org/join.html for more information.\n#pool ntp.ubuntu.com        iburst maxsources 4\n#pool 0.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 1.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 2.ubuntu.pool.ntp.org iburst maxsources 2\n\n# This directive specify the location of the file containing ID/key pairs for\n# NTP authentication.\nkeyfile /etc/chrony/chrony.keys\n\n# This directive specify the file into which chronyd will store the rate\n# information.\ndriftfile /var/lib/chrony/chrony.drift\n\n# Uncomment the following line to turn logging on.\n#log tracking measurements statistics\n\n# Log files location.\nlogdir /var/log/chrony\n\n# Stop bad estimates upsetting machine clock.\nmaxupdateskew 100.0\n\n# This directive enables kernel synchronisation (every 11 minutes) of the\n# real-time clock. Note that it can\u00e2\u20ac\u2122t be used along with the 'rtcfile' directive.\nrtcsync\n\n# Settings come from: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync\nrefclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\nmakestep 1.0 -1\nEOF\n\nsystemctl restart chrony\n\n#EOF", "num_lines": 90}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Mariner\"\n\ndnfversionlockWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\naptmarkWALinuxAgent() {\n    echo \"No aptmark equivalent for DNF by default. If this is necessary add support for dnf versionlock plugin\"\n}\n\ndnf_makecache() {\n    retries=10\n    dnf_makecache_output=/tmp/dnf-makecache.out\n    for i in $(seq 1 $retries); do\n        ! (dnf makecache -y 2>&1 | tee $dnf_makecache_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $dnf_makecache_output && break || \\\n        cat $dnf_makecache_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed dnf makecache -y $i times\n}\ndnf_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf install -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            dnf_makecache\n        fi\n    done\n    echo Executed dnf install -y \\\"$@\\\" $i times;\n}\ndnf_remove() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        dnf remove -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed dnf remove  -y \\\"$@\\\" $i times;\n}\ndnf_update() {\n  retries=10\n  dnf_update_output=/tmp/dnf-update.out\n  for i in $(seq 1 $retries); do\n    ! (dnf update --exclude mshv-linuxloader --exclude kernel-mshv -y --refresh 2>&1 | tee $dnf_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $dnf_update_output && break || \\\n    cat $dnf_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed dnf update -y --refresh $i times\n}\n#EOF\n", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Mariner\"\n\nremoveContainerd() {\n    retrycmd_if_failure 10 5 60 dnf remove -y moby-containerd\n}\n\ninstallDeps() {\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n    for dnf_package in blobfuse ca-certificates check-restart cifs-utils cloud-init-azure-kvp conntrack-tools cracklib dnf-automatic ebtables ethtool fuse git inotify-tools iotop iproute ipset iptables jq kernel-devel logrotate lsof nmap-ncat nfs-utils pam pigz psmisc rsyslog socat sysstat traceroute util-linux xz zip; do\n      if ! dnf_install 30 1 600 $dnf_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n\n    # install additional apparmor deps for 2.0;\n    if [[ $OS_VERSION == \"2.0\" ]]; then\n      for dnf_package in apparmor-parser libapparmor blobfuse2 nftables; do\n        if ! dnf_install 30 1 600 $dnf_package; then\n          exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n      done\n    fi\n}\n\ndownloadGPUDrivers() {\n    # Mariner CUDA rpm name comes in the following format:\n    #\n    # cuda-%{nvidia gpu driver version}_%{kernel source version}.%{kernel release version}.{mariner rpm postfix}\n    #\n    # Before installing cuda, check the active kernel version (uname -r) and use that to determine which cuda to install\n    KERNEL_VERSION=$(uname -r | sed 's/-/./g')\n    CUDA_VERSION=\"*_${KERNEL_VERSION}*\"\n\n    if ! dnf_install 30 1 600 cuda-${CUDA_VERSION}; then\n      exit $ERR_APT_INSTALL_TIMEOUT\n    fi\n}\n\ninstallNvidiaContainerRuntime() {\n    MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION=\"3.11.0\"\n    MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION=\"1.11.0\"\n    \n    for nvidia_package in nvidia-container-runtime-${MARINER_NVIDIA_CONTAINER_RUNTIME_VERSION} nvidia-container-toolkit-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} nvidia-container-toolkit-base-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container-tools-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION} libnvidia-container1-${MARINER_NVIDIA_CONTAINER_TOOLKIT_VERSION}; do\n      if ! dnf_install 30 1 600 $nvidia_package; then\n        exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n    done\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    CONTAINERD_VERSION=$1\n    #overwrite the passed containerd_version since mariner uses only 1 version now which is different than ubuntu's\n    CONTAINERD_VERSION=\"1.3.4\"\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    # v1.4.1 is our lowest supported version of containerd\n    \n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${CONTAINERD_VERSION}; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        removeContainerd\n        # TODO: tie runc to r92 once that's possible on Mariner's pkg repo and if we're still using v1.linux shim\n        if ! dnf_install 30 1 600 moby-containerd; then\n          exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n    fi\n\n    # Workaround to restore the CSE configuration after containerd has been installed from the package server.\n    if [[ -f /etc/containerd/config.toml.rpmsave ]]; then\n        mv /etc/containerd/config.toml.rpmsave /etc/containerd/config.toml\n    fi\n\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\ndownloadContainerdFromVersion() {\n    echo \"downloadContainerdFromVersion not implemented for mariner\"\n}\n\ndownloadContainerdFromURL() {\n    echo \"downloadContainerdFromURL not implemented for mariner\"\n}\n\n#EOF\n", "num_lines": 93}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Kubelet\nConditionPathExists=/usr/local/bin/kubelet\nWants=network-online.target containerd.service\nAfter=network-online.target containerd.service\n\n[Service]\nRestart=always\nRestartSec=2\nEnvironmentFile=/etc/default/kubelet\n# Graceful termination (SIGTERM)\nSuccessExitStatus=143\nExecStartPre=/bin/bash /opt/azure/containers/kubelet.sh\nExecStartPre=/bin/mkdir -p /var/lib/kubelet\nExecStartPre=/bin/mkdir -p /var/lib/cni\nExecStartPre=/bin/bash -c \"if [ $(mount | grep \\\"/var/lib/kubelet\\\" | wc -l) -le 0 ] ; then /bin/mount --bind /var/lib/kubelet /var/lib/kubelet ; fi\"\nExecStartPre=/bin/mount --make-shared /var/lib/kubelet\n\nExecStartPre=-/sbin/ebtables -t nat --list\nExecStartPre=-/sbin/iptables -t nat --numeric --list\n\nExecStart=/usr/local/bin/kubelet \\\n        --enable-server \\\n        --node-labels=\"${KUBELET_NODE_LABELS}\" \\\n        --v=2 \\\n        --volume-plugin-dir=/etc/kubernetes/volumeplugins \\\n        $KUBELET_TLS_BOOTSTRAP_FLAGS \\\n        $KUBELET_CONFIG_FILE_FLAGS \\\n        $KUBELET_CONTAINERD_FLAGS \\\n        $KUBELET_CONTAINER_RUNTIME_FLAG \\\n        $KUBELET_CGROUP_FLAGS \\\n        $KUBELET_FLAGS\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Apply MIG configuration on Nvidia A100 GPU\n\n[Service]\nRestart=on-failure\nExecStartPre=/usr/bin/nvidia-smi -mig 1\nExecStart=/bin/bash /opt/azure/containers/mig-partition.sh ${GPU_INSTANCE_PROFILE}\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 11}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#NOTE: Currently, Nvidia library mig-parted (https://github.com/NVIDIA/mig-parted) cannot work properly because of the outdated GPU driver version\n#TODO: Use mig-parted library to do the partition after the above issue is fixed \nMIG_PROFILE=${1}\ncase ${MIG_PROFILE} in \n    \"MIG1g\")\n        nvidia-smi mig -cgi 19,19,19,19,19,19,19\n        ;;\n    \"MIG2g\")\n        nvidia-smi mig -cgi 14,14,14\n        ;;\n    \"MIG3g\")\n        nvidia-smi mig -cgi 9,9\n        ;;\n    \"MIG4g\")\n        nvidia-smi mig -cgi 5\n        ;;\n    \"MIG7g\")\n        nvidia-smi mig -cgi 0\n        ;;  \n    *)\n        echo \"not a valid GPU instance profile\"\n        exit 1\n        ;;\nesac\nnvidia-smi mig -cci", "num_lines": 27}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o nounset\nset -o pipefail\nset -x\n\n# Bind mount kubelet to ephemeral storage on startup, as necessary.\n#\n# This fixes an issue with kubelet's ability to detect allocatable\n# capacity for Node ephemeral-storage. On Azure, ephemeral-storage\n# should correspond to the temp disk if a VM has one. This script makes\n# that true by bind mounting the temp disk to /var/lib/kubelet, so\n# kubelet thinks it's located on the temp disk (/dev/sdb). This results\n# in correct calculation of ephemeral-storage capacity.\n\n# if aks ever supports alternatives besides temp disk\n# this mount point will need to be updated\nMOUNT_POINT=\"/mnt/aks\"\n\nKUBELET_MOUNT_POINT=\"${MOUNT_POINT}/kubelet\"\nKUBELET_DIR=\"/var/lib/kubelet\"\n\nmkdir -p \"${MOUNT_POINT}\"\n\n# only move the kubelet directory to alternate location on first boot.\nSENTINEL_FILE=\"/opt/azure/containers/bind-sentinel\"\nif [ ! -e \"$SENTINEL_FILE\" ]; then\n    mv \"$KUBELET_DIR\" \"$MOUNT_POINT\"\n    touch \"$SENTINEL_FILE\"\nfi\n\n# on every boot, bind mount the kubelet directory back to the expected\n# location before kubelet itself may start.\nmkdir -p \"${KUBELET_DIR}\"\nmount --bind \"${KUBELET_MOUNT_POINT}\" \"${KUBELET_DIR}\" \nchmod a+w \"${KUBELET_DIR}\"", "num_lines": 36}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Bind mount kubelet data\n[Service]\nRestart=on-failure\nRemainAfterExit=yes\nExecStart=/bin/bash /opt/azure/containers/bind-mount.sh\n\n[Install]\nWantedBy=multi-user.target\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=enabledhcpv6\nAfter=network-online.target\n\n[Service]\nType=oneshot\nExecStart=/opt/azure/containers/enable-dhcpv6.sh\n\n[Install]\nWantedBy=multi-user.target\n#EOF\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION << EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n    grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >> \"${2}\"\n}\n\necho \"Configuring dhcpv6 ...\"\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n    add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n    sudo ifdown eth0 && sudo ifup eth0\n\necho \"Configuration complete\"\n#EOF\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_helpers_distro.sh for Ubuntu\"\n\n\naptmarkWALinuxAgent() {\n    echo $(date),$(hostname), startAptmarkWALinuxAgent \"$1\"\n    wait_for_apt_locks\n    retrycmd_if_failure 120 5 25 apt-mark $1 walinuxagent || \\\n    if [[ \"$1\" == \"hold\" ]]; then\n        exit $ERR_HOLD_WALINUXAGENT\n    elif [[ \"$1\" == \"unhold\" ]]; then\n        exit $ERR_RELEASE_HOLD_WALINUXAGENT\n    fi\n    echo $(date),$(hostname), endAptmarkWALinuxAgent \"$1\"\n}\n\nwait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\napt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get -f -y install\n        ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n        cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 5\n        fi\n    done\n    echo Executed apt-get update $i times\n    wait_for_apt_locks\n}\napt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_purge() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        timeout $timeout apt-get purge -o Dpkg::Options::=\"--force-confold\" -y ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed apt-get purge -y \\\"$@\\\" $i times;\n    wait_for_apt_locks\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get -o Dpkg::Options::=\"--force-confnew\" dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n  wait_for_apt_locks\n}\ninstallDebPackageFromFile() {\n    DEB_FILE=$1\n    wait_for_apt_locks\n    retrycmd_if_failure 10 5 600 apt-get -y -f install ${DEB_FILE} --allow-downgrades\n    if [[ $? -ne 0 ]]; then\n        return 1\n    fi\n}\n#EOF\n", "num_lines": 105}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Add dedup ebtable rules for kubenet bridge in promiscuous mode\nAfter=containerd.service\nAfter=kubelet.service\n[Service]\nRestart=on-failure\nRestartSec=2\nExecStart=/bin/bash /opt/azure/containers/ensure-no-dup.sh\n#EOF\n", "num_lines": 10}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# remove this if we are no longer using promiscuous bridge mode for containerd\n# background: we get duplicated packets from pod to serviceIP if both are on the same node (one from the cbr0 bridge and one from the pod ip itself via kernel due to promiscuous mode being on)\n# we should filter out the one from pod ip\n# this is exactly what kubelet does for dockershim+kubenet\n# https://github.com/kubernetes/kubernetes/pull/28717\n\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nif [[ $? -eq 0 ]]; then\n    echo \"AKS-DEDUP-PROMISC rule already set\"\n    exit 0\nfi\nif [[ ! -f /etc/cni/net.d/10-containerd-net.conflist ]]; then\n    echo \"cni config not up yet...exiting early\"\n    exit 1\nfi\n\nbridgeName=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .bridge\")\npromiscMode=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .promiscMode\")\nif [[ \"${promiscMode}\" != \"true\" ]]; then\n    echo \"bridge ${bridgeName} not in promiscuous mode...exiting early\"\n    exit 0\nfi\n\nif [[ ! -f /sys/class/net/${bridgeName}/address ]]; then\n    echo \"bridge ${bridgeName} not up yet...exiting early\"\n    exit 1\nfi\n\n\nbridgeIP=$(ip addr show ${bridgeName} | grep -Eo \"inet ([0-9]*\\.){3}[0-9]*\" | grep -Eo \"([0-9]*\\.){3}[0-9]*\")\nif [[ -z \"${bridgeIP}\" ]]; then\n    echo \"bridge ${bridgeName} does not have an ipv4 address...exiting early\"\n    exit 1\nfi\n\npodSubnetAddr=$(cat /etc/cni/net.d/10-containerd-net.conflist  | jq -r \".plugins[] | select(.type == \\\"bridge\\\") | .ipam.subnet\")\nif [[ -z \"${podSubnetAddr}\" ]]; then\n    echo \"could not determine this node's pod ipam subnet range from 10-containerd-net.conflist...exiting early\"\n    exit 1\nfi\n\nbridgeMAC=$(cat /sys/class/net/${bridgeName}/address)\n\necho \"adding AKS-DEDUP-PROMISC ebtable chain\"\nebtables -t filter -N AKS-DEDUP-PROMISC # add new AKS-DEDUP-PROMISC chain\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${bridgeIP} -j ACCEPT\nebtables -t filter -A AKS-DEDUP-PROMISC -p IPv4 -s ${bridgeMAC} -o veth+ --ip-src ${podSubnetAddr} -j DROP\nebtables -t filter -A OUTPUT -j AKS-DEDUP-PROMISC # add new rule to OUTPUT chain jump to AKS-DEDUP-PROMISC\n\necho \"outputting newly added AKS-DEDUP-PROMISC rules:\"\nebtables -t filter -L OUTPUT 2>/dev/null\nebtables -t filter -L AKS-DEDUP-PROMISC 2>/dev/null\nexit 0\n#EOF", "num_lines": 56}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "CSE_STARTTIME=$(date)\nCSE_STARTTIME_FORMATTED=$(date +\"%F %T.%3N\")\ntimeout -k5s 15m /bin/bash /opt/azure/containers/provision.sh >> /var/log/azure/cluster-provision.log 2>&1\nEXIT_CODE=$?\nsystemctl --no-pager -l status kubelet >> /var/log/azure/cluster-provision-cse-output.log 2>&1\nOUTPUT=$(tail -c 3000 \"/var/log/azure/cluster-provision.log\")\nKERNEL_STARTTIME=$(systemctl show -p KernelTimestamp | sed -e  \"s/KernelTimestamp=//g\" || true)\nKERNEL_STARTTIME_FORMATTED=$(date -d \"${KERNEL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITLOCAL_STARTTIME=$(systemctl show cloud-init-local -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITLOCAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITLOCAL_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINIT_STARTTIME=$(systemctl show cloud-init -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINIT_STARTTIME_FORMATTED=$(date -d \"${CLOUDINIT_STARTTIME}\" +\"%F %T.%3N\" )\nCLOUDINITFINAL_STARTTIME=$(systemctl show cloud-final -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nCLOUDINITFINAL_STARTTIME_FORMATTED=$(date -d \"${CLOUDINITFINAL_STARTTIME}\" +\"%F %T.%3N\" )\nNETWORKD_STARTTIME=$(systemctl show systemd-networkd -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nNETWORKD_STARTTIME_FORMATTED=$(date -d \"${NETWORKD_STARTTIME}\" +\"%F %T.%3N\" )\nGUEST_AGENT_STARTTIME=$(systemctl show walinuxagent.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nGUEST_AGENT_STARTTIME_FORMATTED=$(date -d \"${GUEST_AGENT_STARTTIME}\" +\"%F %T.%3N\" )\nKUBELET_START_TIME=$(systemctl show kubelet.service -p ExecMainStartTimestamp | sed -e \"s/ExecMainStartTimestamp=//g\" || true)\nKUBELET_START_TIME_FORMATTED=$(date -d \"${KUBELET_START_TIME}\" +\"%F %T.%3N\" )\nKUBELET_READY_TIME_FORMATTED=\"$(date -d \"$(journalctl -u kubelet | grep NodeReady | cut -d' ' -f1-3)\" +\"%F %T.%3N\")\"\nSYSTEMD_SUMMARY=$(systemd-analyze || true)\nCSE_ENDTIME_FORMATTED=$(date +\"%F %T.%3N\")\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nEVENTS_FILE_NAME=$(date +%s%3N)\nEXECUTION_DURATION=$(echo $(($(date +%s) - $(date -d \"$CSE_STARTTIME\" +%s))))\n\nJSON_STRING=$( jq -n \\\n                  --arg ec \"$EXIT_CODE\" \\\n                  --arg op \"$OUTPUT\" \\\n                  --arg er \"\" \\\n                  --arg ed \"$EXECUTION_DURATION\" \\\n                  --arg ks \"$KERNEL_STARTTIME\" \\\n                  --arg cinitl \"$CLOUDINITLOCAL_STARTTIME\" \\\n                  --arg cinit \"$CLOUDINIT_STARTTIME\" \\\n                  --arg cf \"$CLOUDINITFINAL_STARTTIME\" \\\n                  --arg ns \"$NETWORKD_STARTTIME\" \\\n                  --arg cse \"$CSE_STARTTIME\" \\\n                  --arg ga \"$GUEST_AGENT_STARTTIME\" \\\n                  --arg ss \"$SYSTEMD_SUMMARY\" \\\n                  --arg kubelet \"$KUBELET_START_TIME\" \\\n                  '{ExitCode: $ec, Output: $op, Error: $er, ExecDuration: $ed, KernelStartTime: $ks, CloudInitLocalStartTime: $cinitl, CloudInitStartTime: $cinit, CloudFinalStartTime: $cf, NetworkdStartTime: $ns, CSEStartTime: $cse, GuestAgentStartTime: $ga, SystemdSummary: $ss, BootDatapoints: { KernelStartTime: $ks, CSEStartTime: $cse, GuestAgentStartTime: $ga, KubeletStartTime: $kubelet }}' )\nmkdir -p /var/log/azure/aks\necho $JSON_STRING | tee /var/log/azure/aks/provision.json\n\n# messsage_string is here because GA only accepts strings in Message.\nmessage_string=$( jq -n \\\n--arg EXECUTION_DURATION                  \"${EXECUTION_DURATION}\" \\\n--arg EXIT_CODE                           \"${EXIT_CODE}\" \\\n--arg KERNEL_STARTTIME_FORMATTED          \"${KERNEL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITLOCAL_STARTTIME_FORMATTED  \"${CLOUDINITLOCAL_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINIT_STARTTIME_FORMATTED       \"${CLOUDINIT_STARTTIME_FORMATTED}\" \\\n--arg CLOUDINITFINAL_STARTTIME_FORMATTED  \"${CLOUDINITFINAL_STARTTIME_FORMATTED}\" \\\n--arg NETWORKD_STARTTIME_FORMATTED        \"${NETWORKD_STARTTIME_FORMATTED}\" \\\n--arg GUEST_AGENT_STARTTIME_FORMATTED     \"${GUEST_AGENT_STARTTIME_FORMATTED}\" \\\n--arg KUBELET_START_TIME_FORMATTED        \"${KUBELET_START_TIME_FORMATTED}\" \\\n--arg KUBELET_READY_TIME_FORMATTED       \"${KUBELET_READY_TIME_FORMATTED}\" \\\n'{ExitCode: $EXIT_CODE, E2E: $EXECUTION_DURATION, KernelStartTime: $KERNEL_STARTTIME_FORMATTED, CloudInitLocalStartTime: $CLOUDINITLOCAL_STARTTIME_FORMATTED, CloudInitStartTime: $CLOUDINIT_STARTTIME_FORMATTED, CloudFinalStartTime: $CLOUDINITFINAL_STARTTIME_FORMATTED, NetworkdStartTime: $NETWORKD_STARTTIME_FORMATTED, GuestAgentStartTime: $GUEST_AGENT_STARTTIME_FORMATTED, KubeletStartTime: $KUBELET_START_TIME_FORMATTED, KubeletReadyTime: $KUBELET_READY_TIME_FORMATTED } | tostring'\n)\n# this clean up brings me no joy, but removing extra \"\\\" and then removing quotes at the end of the string\n# allows parsing to happening without additional manipulation\nmessage_string=$(echo $message_string | sed 's/\\\\//g' | sed 's/^.\\(.*\\).$/\\1/')\n\n# arg names are defined by GA and all these are required to be correctly read by GA\n# EventPid, EventTid are required to be int. No use case for them at this point.\nEVENT_JSON=$( jq -n \\\n    --arg Timestamp     \"${CSE_STARTTIME_FORMATTED}\" \\\n    --arg OperationId   \"${CSE_ENDTIME_FORMATTED}\" \\\n    --arg Version       \"1.23\" \\\n    --arg TaskName      \"AKS.CSE.cse_start\" \\\n    --arg EventLevel    \"${eventlevel}\" \\\n    --arg Message       \"${message_string}\" \\\n    --arg EventPid      \"0\" \\\n    --arg EventTid      \"0\" \\\n    '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n)\necho ${EVENT_JSON} > ${EVENTS_LOGGING_DIR}${EVENTS_FILE_NAME}.json\n\n# force a log upload to the host after the provisioning script finishes\n# if we failed, wait for the upload to complete so that we don't remove\n# the VM before it finishes. if we succeeded, upload in the background\n# so that the provisioning script returns success more quickly\nupload_logs() {\n    # find the most recent version of WALinuxAgent and use it to collect logs per\n    # https://supportability.visualstudio.com/AzureIaaSVM/_wiki/wikis/AzureIaaSVM/495009/Log-Collection_AGEX?anchor=manually-collect-logs\n    PYTHONPATH=$(find /var/lib/waagent -name WALinuxAgent\\*.egg | sort -rV | head -n1)\n    python3 $PYTHONPATH -collect-logs -full >/dev/null 2>&1\n    python3 /opt/azure/containers/provision_send_logs.py >/dev/null 2>&1\n}\nif [ $EXIT_CODE -ne 0 ]; then\n    upload_logs\nelse\n    upload_logs &\nfi\n\nexit $EXIT_CODE", "num_lines": 96}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\n\necho \"  dns-search ${CUSTOM_SEARCH_DOMAIN_NAME}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd_if_failure 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"${CUSTOM_SEARCH_REALM_PASSWORD}\" | realm join -U ${CUSTOM_SEARCH_REALM_USER}@$(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/) $(echo \"${CUSTOM_SEARCH_DOMAIN_NAME}\" | tr /a-z/ /A-Z/)\n", "num_lines": 12}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Timeout waiting for a file\nERR_FILE_WATCH_TIMEOUT=6 \nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n      echo \"Already ran to success exiting...\"\n      exit 0\nfi\n\naptmarkWALinuxAgent hold &\n\n# Setup logs for upload to host\nLOG_DIR=/var/log/azure/aks\nmkdir -p ${LOG_DIR}\nln -s /var/log/azure/cluster-provision.log \\\n      /var/log/azure/cluster-provision-cse-output.log \\\n      /opt/azure/*.json \\\n      /opt/azure/cloud-init-files.paved \\\n      /opt/azure/vhd-install.complete \\\n      ${LOG_DIR}/\n\n# Redact the necessary secrets from cloud-config.txt so we don't expose any sensitive information\n# when cloud-config.txt gets included within log bundles\npython3 /opt/azure/containers/provision_redact_cloud_config.py \\\n    --cloud-config-path /var/lib/cloud/instance/cloud-config.txt \\\n    --output-path ${LOG_DIR}/cloud-config.txt\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    sudo apt-get -y autoremove chrony\n    echo $?\n    sudo systemctl restart systemd-timesyncd\nfi\n\necho $(date),$(hostname), startcustomscript>>/opt/m\n\nfor i in $(seq 1 3600); do\n    if [ -s \"${CSE_HELPERS_FILEPATH}\" ]; then\n        grep -Fq '#HELPERSEOF' \"${CSE_HELPERS_FILEPATH}\" && break\n    fi\n    if [ $i -eq 3600 ]; then\n        exit $ERR_FILE_WATCH_TIMEOUT\n    else\n        sleep 1\n    fi\ndone\nsed -i \"/#HELPERSEOF/d\" \"${CSE_HELPERS_FILEPATH}\"\nsource \"${CSE_HELPERS_FILEPATH}\"\n\nsource \"${CSE_DISTRO_HELPERS_FILEPATH}\"\nsource \"${CSE_INSTALL_FILEPATH}\"\nsource \"${CSE_DISTRO_INSTALL_FILEPATH}\"\nsource \"${CSE_CONFIG_FILEPATH}\"\n\nif [[ \"${DISABLE_SSH}\" == \"true\" ]]; then\n    disableSSH || exit $ERR_DISABLE_SSH\nfi\n\nif [[ \"${SHOULD_CONFIGURE_HTTP_PROXY}\" == \"true\" ]]; then\n    if [[ \"${SHOULD_CONFIGURE_HTTP_PROXY_CA}\" == \"true\" ]]; then\n        configureHTTPProxyCA || exit $ERR_UPDATE_CA_CERTS\n    fi\n    configureEtcEnvironment\nfi\n\n\nif [[ \"${SHOULD_CONFIGURE_CUSTOM_CA_TRUST}\" == \"true\" ]]; then\n    configureCustomCaCertificate || $ERR_UPDATE_CA_CERTS\nfi\n\nif [[ -n \"${OUTBOUND_COMMAND}\" ]]; then\n    if [[ -n \"${PROXY_VARS}\" ]]; then\n        eval $PROXY_VARS\n    fi\n    retrycmd_if_failure 50 1 5 $OUTBOUND_COMMAND >> /var/log/azure/cluster-provision-cse-output.log 2>&1 || exit $ERR_OUTBOUND_CONN_FAIL;\nfi\n\n# Bring in OS-related vars\nsource /etc/os-release\n\n# Mandb is not currently available on MarinerV1\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Removing man-db auto-update flag file...\"\n    logs_to_events \"AKS.CSE.removeManDbAutoUpdateFlagFile\" removeManDbAutoUpdateFlagFile\nfi\n\nexport -f should_skip_nvidia_drivers\nskip_nvidia_driver_install=$(retrycmd_if_failure_no_stats 10 1 10 bash -cx should_skip_nvidia_drivers)\nret=$?\nif [[ \"$ret\" != \"0\" ]]; then\n    echo \"Failed to determine if nvidia driver install should be skipped\"\n    exit $ERR_NVIDIA_DRIVER_INSTALL\nfi\n\nif [[ \"${GPU_NODE}\" != \"true\" ]] || [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.cleanUpGPUDrivers\" cleanUpGPUDrivers\nfi\n\nlogs_to_events \"AKS.CSE.disableSystemdResolved\" disableSystemdResolved\n\nlogs_to_events \"AKS.CSE.configureAdminUser\" configureAdminUser\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected golden image pre-install\"\n    logs_to_events \"AKS.CSE.cleanUpContainerImages\" cleanUpContainerImages\n    FULL_INSTALL_REQUIRED=false\nelse\n    if [[ \"${IS_VHD}\" = true ]]; then\n        echo \"Using VHD distro but file $VHD_LOGS_FILEPATH not found\"\n        exit $ERR_VHD_FILE_NOT_FOUND\n    fi\n    FULL_INSTALL_REQUIRED=true\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n    logs_to_events \"AKS.CSE.installDeps\" installDeps\nelse\n    echo \"Golden image; skipping dependencies installation\"\nfi\n\nlogs_to_events \"AKS.CSE.installContainerRuntime\" installContainerRuntime\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] && [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then \n    logs_to_events \"AKS.CSE.installTeleportdPlugin\" installTeleportdPlugin\nfi\n\nsetupCNIDirs\n\nlogs_to_events \"AKS.CSE.installNetworkPlugin\" installNetworkPlugin\n\nif [ \"${IS_KRUSTLET}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.downloadKrustlet\" downloadContainerdWasmShims\nfi\n\n# By default, never reboot new nodes.\nREBOOTREQUIRED=false\n\necho $(date),$(hostname), \"Start configuring GPU drivers\"\nif [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" != \"true\" ]]; then\n    logs_to_events \"AKS.CSE.ensureGPUDrivers\" ensureGPUDrivers\n    if [[ \"${ENABLE_GPU_DEVICE_PLUGIN_IF_NEEDED}\" = true ]]; then\n        if [[ \"${MIG_NODE}\" == \"true\" ]] && [[ -f \"/etc/systemd/system/nvidia-device-plugin.service\" ]]; then\n            mkdir -p \"/etc/systemd/system/nvidia-device-plugin.service.d\"\n            tee \"/etc/systemd/system/nvidia-device-plugin.service.d/10-mig_strategy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"MIG_STRATEGY=--mig-strategy single\"\nExecStart=\nExecStart=/usr/local/nvidia/bin/nvidia-device-plugin $MIG_STRATEGY    \nEOF\n        fi\n        logs_to_events \"AKS.CSE.start.nvidia-device-plugin\" \"systemctlEnableAndStart nvidia-device-plugin\" || exit $ERR_GPU_DEVICE_PLUGIN_START_FAIL\n    else\n        logs_to_events \"AKS.CSE.stop.nvidia-device-plugin\" \"systemctlDisableAndStop nvidia-device-plugin\"\n    fi\n\n    if [[ \"${GPU_NEEDS_FABRIC_MANAGER}\" == \"true\" ]]; then\n        # fabric manager trains nvlink connections between multi instance gpus.\n        # it appears this is only necessary for systems with *multiple cards*.\n        # i.e., an A100 can be partitioned a maximum of 7 ways.\n        # An NC24ads_A100_v4 has one A100.\n        # An ND96asr_v4 has eight A100, for a maximum of 56 partitions.\n        # ND96 seems to require fabric manager *even when not using mig partitions*\n        # while it fails to install on NC24.\n        logs_to_events \"AKS.CSE.nvidia-fabricmanager\" \"systemctlEnableAndStart nvidia-fabricmanager\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n\n    # This will only be true for multi-instance capable VM sizes\n    # for which the user has specified a partitioning profile.\n    # it is valid to use mig-capable gpus without a partitioning profile.\n    if [[ \"${MIG_NODE}\" == \"true\" ]]; then\n        # A100 GPU has a bit in the physical card (infoROM) to enable mig mode.\n        # Changing this bit in either direction requires a VM reboot on Azure (hypervisor/plaform stuff).\n        # Commands such as `nvidia-smi --gpu-reset` may succeed,\n        # while commands such as `nvidia-smi -q` will show mismatched current/pending mig mode.\n        # this will not be required per nvidia for next gen H100.\n        REBOOTREQUIRED=true\n        \n        # this service applies the partitioning scheme with nvidia-smi.\n        # we should consider moving to mig-parted which is simpler/newer.\n        # we couldn't because of old drivers but that has long been fixed.\n        logs_to_events \"AKS.CSE.ensureMigPartition\" ensureMigPartition\n    fi\nfi\n\necho $(date),$(hostname), \"End configuring GPU drivers\"\n\nif [ \"${NEEDS_DOCKER_LOGIN}\" == \"true\" ]; then\n    set +x\n    docker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET \"${AZURE_PRIVATE_REGISTRY_SERVER}\"\n    set -x\nfi\n\nlogs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy\" installKubeletKubectlAndKubeProxy\n\ncreateKubeManifestDir\n\nif [ \"${HAS_CUSTOM_SEARCH_DOMAIN}\" == \"true\" ]; then\n    \"${CUSTOM_SEARCH_DOMAIN_FILEPATH}\" > /opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit $ERR_CUSTOM_SEARCH_DOMAINS_FAIL\nfi\n\n\n# for drop ins, so they don't all have to check/create the dir\nmkdir -p \"/etc/systemd/system/kubelet.service.d\"\n\nlogs_to_events \"AKS.CSE.configureK8s\" configureK8s\n\nlogs_to_events \"AKS.CSE.configureCNI\" configureCNI\n\n# configure and enable dhcpv6 for dual stack feature\nif [ \"${IPV6_DUAL_STACK_ENABLED}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureDHCPv6\" ensureDHCPv6\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # containerd should not be configured until cni has been configured first\n    logs_to_events \"AKS.CSE.ensureContainerd\" ensureContainerd \nelse\n    logs_to_events \"AKS.CSE.ensureDocker\" ensureDocker\nfi\n\nif [[ \"${MESSAGE_OF_THE_DAY}\" != \"\" ]]; then\n    echo \"${MESSAGE_OF_THE_DAY}\" | base64 -d > /etc/motd\nfi\n\n# must run before kubelet starts to avoid race in container status using wrong image\n# https://github.com/kubernetes/kubernetes/issues/51017\n# can remove when fixed\nif [[ \"${TARGET_CLOUD}\" == \"AzureChinaCloud\" ]]; then\n    retagMCRImagesForChina\nfi\n\nif [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" == \"true\" ]]; then\n    logs_to_events \"AKS.CSE.configPrivateClusterHosts\" configPrivateClusterHosts\nfi\n\nif [ \"${SHOULD_CONFIG_TRANSPARENT_HUGE_PAGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureTransparentHugePage\" configureTransparentHugePage\nfi\n\nif [ \"${SHOULD_CONFIG_SWAP_FILE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.configureSwapFile\" configureSwapFile\nfi\n\nif [ \"${NEEDS_CGROUPV2}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-cgroupv2.conf\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CGROUP_FLAGS=--cgroup-driver=systemd\"\nEOF\nfi\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n    # gross, but the backticks make it very hard to do in Go\n    # TODO: move entirely into vhd.\n    # alternatively, can we verify this is safe with docker?\n    # or just do it even if not because docker is out of support?\n    mkdir -p /etc/containerd\n    echo \"${KUBENET_TEMPLATE}\" | base64 -d > /etc/containerd/kubenet_template.conf\n\n    # In k8s 1.27, the flag --container-runtime was removed.\n    # We now have 2 drop-in's, one with the still valid flags that will be applied to all k8s versions,\n    # the flags are --runtime-request-timeout, --container-runtime-endpoint, --runtime-cgroups\n    # For k8s >= 1.27, the flag --container-runtime will not be passed.\n    tee \"/etc/systemd/system/kubelet.service.d/10-containerd-base-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINERD_FLAGS=--runtime-request-timeout=15m --container-runtime-endpoint=unix:///run/containerd/containerd.sock --runtime-cgroups=/system.slice/containerd.service\"\nEOF\n    \n    # if k8s version < 1.27.0, add the drop in for --container-runtime flag\n    if ! semverCompare ${KUBERNETES_VERSION:-\"0.0.0\"} \"1.27.0\"; then\n        tee \"/etc/systemd/system/kubelet.service.d/10-container-runtime-flag.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironment=\"KUBELET_CONTAINER_RUNTIME_FLAG=--container-runtime=remote\"\nEOF\n    fi\nfi\n\nif [ \"${HAS_KUBELET_DISK_TYPE}\" == \"true\" ]; then\n    tee \"/etc/systemd/system/kubelet.service.d/10-bindmount.conf\" > /dev/null <<EOF\n[Unit]\nRequires=bind-mount.service\nAfter=bind-mount.service\nEOF\nfi\n\nlogs_to_events \"AKS.CSE.ensureSysctl\" ensureSysctl\n\nif [ \"${NEEDS_CONTAINERD}\" == \"true\" ] &&  [ \"${SHOULD_CONFIG_CONTAINERD_ULIMITS}\" == \"true\" ]; then\n  logs_to_events \"AKS.CSE.setContainerdUlimits\" configureContainerdUlimits\nfi\n\nlogs_to_events \"AKS.CSE.ensureKubelet\" ensureKubelet\nif [ \"${ENSURE_NO_DUPE_PROMISCUOUS_BRIDGE}\" == \"true\" ]; then\n    logs_to_events \"AKS.CSE.ensureNoDupOnPromiscuBridge\" ensureNoDupOnPromiscuBridge\nfi\n\nif $FULL_INSTALL_REQUIRED; then\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 \n        echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\n        sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n    fi\nfi\n\nVALIDATION_ERR=0\n\n# Edge case scenarios:\n# high retry times to wait for new API server DNS record to replicate (e.g. stop and start cluster)\n# high timeout to address high latency for private dns server to forward request to Azure DNS\n# dns check will be done only if we use FQDN for API_SERVER_NAME\nAPI_SERVER_CONN_RETRIES=50\nif [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n    API_SERVER_CONN_RETRIES=100\nfi\nif ! [[ ${API_SERVER_NAME} =~ ^[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+$ ]]; then\n    API_SERVER_DNS_RETRIES=100\n    if [[ $API_SERVER_NAME == *.privatelink.* ]]; then\n       API_SERVER_DNS_RETRIES=200\n    fi\n    if [[ \"${ENABLE_HOSTS_CONFIG_AGENT}\" != \"true\" ]]; then\n        RES=$(logs_to_events \"AKS.CSE.apiserverNslookup\" \"retrycmd_if_failure ${API_SERVER_DNS_RETRIES} 1 20 nslookup -timeout=5 -retry=0 ${API_SERVER_NAME}\")\n        STS=$?\n    else\n        STS=0\n    fi\n    if [[ $STS != 0 ]]; then\n        time nslookup ${API_SERVER_NAME}\n        if [[ $RES == *\"168.63.129.16\"*  ]]; then\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL\n        else\n            VALIDATION_ERR=$ERR_K8S_API_SERVER_DNS_LOOKUP_FAIL\n        fi\n    else\n        logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\n    fi\nelse\n    logs_to_events \"AKS.CSE.apiserverNC\" \"retrycmd_if_failure ${API_SERVER_CONN_RETRIES} 1 10 nc -vz ${API_SERVER_NAME} 443\" || time nc -vz ${API_SERVER_NAME} 443 || VALIDATION_ERR=$ERR_K8S_API_SERVER_CONN_FAIL\nfi\n\nif [[ ${ID} != \"mariner\" ]]; then\n    echo \"Recreating man-db auto-update flag file and kicking off man-db update process at $(date)\"\n    createManDbAutoUpdateFlagFile\n    /usr/bin/mandb && echo \"man-db finished updates at $(date)\" &\nfi\n\nif $REBOOTREQUIRED; then\n    echo 'reboot required, rebooting node in 1 minute'\n    /bin/bash -c \"shutdown -r 1 &\"\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        aptmarkWALinuxAgent unhold &\n    fi\nelse\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        # logs_to_events should not be run on & commands\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            UU_CONFIG_DIR=\"/etc/apt/apt.conf.d/99periodic\"\n            mkdir -p \"$(dirname \"${UU_CONFIG_DIR}\")\"\n            touch \"${UU_CONFIG_DIR}\"\n            chmod 0644 \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Update-Package-Lists \"1\";' >> \"${UU_CONFIG_DIR}\"\n            echo 'APT::Periodic::Unattended-Upgrade \"1\";' >> \"${UU_CONFIG_DIR}\"\n            systemctl unmask apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.service apt-daily-upgrade.service\n            systemctl enable apt-daily.timer apt-daily-upgrade.timer\n            systemctl restart --no-block apt-daily.timer apt-daily-upgrade.timer            \n            # this is the DOWNLOAD service\n            # meaning we are wasting IO without even triggering an upgrade \n            # -________________-\n            systemctl restart --no-block apt-daily.service\n            \n        fi\n        aptmarkWALinuxAgent unhold &\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        if [ \"${ENABLE_UNATTENDED_UPGRADES}\" == \"true\" ]; then\n            if [ \"${IS_KATA}\" == \"true\" ]; then\n                # Currently kata packages must be updated as a unit (including the kernel which requires a reboot). This can\n                # only be done reliably via image updates as of now so never enable automatic updates.\n                echo 'EnableUnattendedUpgrade is not supported by kata images, will not be enabled'\n            else\n                # By default the dnf-automatic is service is notify only in Mariner.\n                # Enable the automatic install timer and the check-restart timer.\n                # Stop the notify only dnf timer since we've enabled the auto install one.\n                # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n                systemctl disable dnf-automatic-notifyonly.timer\n                systemctl stop dnf-automatic-notifyonly.timer\n                # At 6:00:00 UTC (1 hour random fuzz) download and install package updates.\n                systemctl unmask dnf-automatic-install.service || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctl unmask dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                systemctlEnableAndStart dnf-automatic-install.timer || exit $ERR_SYSTEMCTL_START_FAIL\n                # The check-restart service which will inform kured of required restarts should already be running\n            fi\n        fi\n    fi\nfi\n\necho \"Custom script finished. API server connection check code:\" $VALIDATION_ERR\necho $(date),$(hostname), endcustomscript>>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\n\nexit $VALIDATION_ERR\n\n\n#EOF\n", "num_lines": 404}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCC_SERVICE_IN_TMP=/opt/azure/containers/cc-proxy.service.in\nCC_SOCKET_IN_TMP=/opt/azure/containers/cc-proxy.socket.in\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCRICTL_DOWNLOAD_DIR=\"/opt/crictl/downloads\"\nCRICTL_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nRUNC_DOWNLOADS_DIR=\"/opt/runc/downloads\"\nK8S_DOWNLOADS_DIR=\"/opt/kubernetes/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nTELEPORTD_PLUGIN_DOWNLOAD_DIR=\"/opt/teleportd/downloads\"\nTELEPORTD_PLUGIN_BIN_DIR=\"/usr/local/bin\"\nCONTAINERD_WASM_VERSIONS=\"v0.3.0 v0.5.1\"\nMANIFEST_FILEPATH=\"/opt/azure/manifest.json\"\nMAN_DB_AUTO_UPDATE_FLAG_FILEPATH=\"/var/lib/man-db/auto-update\"\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nremoveManDbAutoUpdateFlagFile() {\n    rm -f $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncreateManDbAutoUpdateFlagFile() {\n    touch $MAN_DB_AUTO_UPDATE_FLAG_FILEPATH\n}\n\ncleanupContainerdDlFiles() {\n    rm -rf $CONTAINERD_DOWNLOADS_DIR\n}\n\ninstallContainerRuntime() {\n    if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n        echo \"in installContainerRuntime - KUBERNETES_VERSION = ${KUBERNETES_VERSION}\"\n        local containerd_version\n        if [ -f \"$MANIFEST_FILEPATH\" ]; then\n            containerd_version=\"$(jq -r .containerd.edge \"$MANIFEST_FILEPATH\")\"\n        else\n            echo \"WARNING: containerd version not found in manifest, defaulting to hardcoded.\"\n        fi\n\n        containerd_patch_version=\"$(echo \"$containerd_version\" | cut -d- -f1)\"\n        containerd_revision=\"$(echo \"$containerd_version\" | cut -d- -f2)\"\n        if [ -z \"$containerd_patch_version\" ] || [ \"$containerd_patch_version\" == \"null\" ] || [ \"$containerd_revision\" == \"null\" ]; then\n            echo \"invalid container version: $containerd_version\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n\n        logs_to_events \"AKS.CSE.installContainerRuntime.installStandaloneContainerd\" \"installStandaloneContainerd ${containerd_patch_version} ${containerd_revision}\"\n        echo \"in installContainerRuntime - CONTAINERD_VERION = ${containerd_patch_version}\"\n    else\n        installMoby\n    fi\n}\n\ninstallNetworkPlugin() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        installAzureCNI\n    fi\n    installCNI\n    rm -rf $CNI_DOWNLOADS_DIR &\n}\n\ndownloadCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadContainerdWasmShims() {\n    for shim_version in $CONTAINERD_WASM_VERSIONS; do\n        binary_version=\"$(echo \"${shim_version}\" | tr . -)\"\n        local containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/amd64\"\n        local containerd_wasm_filepath=\"/usr/local/bin\"\n        if [[ $(isARM64) == 1 ]]; then\n            containerd_wasm_url=\"https://acs-mirror.azureedge.net/containerd-wasm-shims/${shim_version}/linux/arm64\"\n        fi\n\n        if [ ! -f \"$containerd_wasm_filepath/containerd-shim-spin-${shim_version}\" ] || [ ! -f \"$containerd_wasm_filepath/containerd-shim-slight-${shim_version}\" ]; then\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-spin-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            retrycmd_if_failure 30 5 60 curl -fSLv -o \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\" \"$containerd_wasm_url/containerd-shim-slight-v1\" 2>&1 | tee $CURL_OUTPUT >/dev/null | grep -E \"^(curl:.*)|([eE]rr.*)$\" && (cat $CURL_OUTPUT && exit $ERR_KRUSTLET_DOWNLOAD_TIMEOUT)\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-spin-${binary_version}-v1\"\n            chmod 755 \"$containerd_wasm_filepath/containerd-shim-slight-${binary_version}-v1\"\n        fi\n    done\n}\n\ndownloadAzureCNI() {\n    mkdir -p $CNI_DOWNLOADS_DIR\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit $ERR_CNI_DOWNLOAD_TIMEOUT\n}\n\ndownloadCrictl() {\n    CRICTL_VERSION=$1\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    mkdir -p $CRICTL_DOWNLOAD_DIR\n    CRICTL_DOWNLOAD_URL=\"https://acs-mirror.azureedge.net/cri-tools/v${CRICTL_VERSION}/binaries/crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n    CRICTL_TGZ_TEMP=${CRICTL_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 10 5 60 \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ${CRICTL_DOWNLOAD_URL}\n}\n\ninstallCrictl() {\n    CPU_ARCH=$(getCPUArch) #amd64 or arm64\n    currentVersion=$(crictl --version 2>/dev/null | sed 's/crictl version //g')\n    if [[ \"${currentVersion}\" != \"\" ]]; then\n        echo \"version ${currentVersion} of crictl already installed. skipping installCrictl of target version ${KUBERNETES_VERSION%.*}.0\"\n    else\n        # this is only called during cse. VHDs should have crictl binaries pre-cached so no need to download.\n        # if the vhd does not have crictl pre-baked, return early\n        CRICTL_TGZ_TEMP=\"crictl-v${CRICTL_VERSION}-linux-${CPU_ARCH}.tar.gz\"\n        if [[ ! -f \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" ]]; then\n            rm -rf ${CRICTL_DOWNLOAD_DIR}\n            echo \"pre-cached crictl not found: skipping installCrictl\"\n            return 1\n        fi\n        echo \"Unpacking crictl into ${CRICTL_BIN_DIR}\"\n        tar zxvf \"$CRICTL_DOWNLOAD_DIR/${CRICTL_TGZ_TEMP}\" -C ${CRICTL_BIN_DIR}\n        chown root:root $CRICTL_BIN_DIR/crictl\n        chmod 755 $CRICTL_BIN_DIR/crictl\n    fi\n}\n\ndownloadTeleportdPlugin() {\n    DOWNLOAD_URL=$1\n    TELEPORTD_VERSION=$2\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    if [[ -z ${DOWNLOAD_URL} ]]; then\n        echo \"download url parameter for downloadTeleportdPlugin was not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    if [[ -z ${TELEPORTD_VERSION} ]]; then\n        echo \"teleportd version not given\"\n        exit $ERR_TELEPORTD_DOWNLOAD_ERR\n    fi\n    mkdir -p $TELEPORTD_PLUGIN_DOWNLOAD_DIR\n    retrycmd_curl_file 10 5 60 \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${DOWNLOAD_URL}/v${TELEPORTD_VERSION}/teleportd\" || exit ${ERR_TELEPORTD_DOWNLOAD_ERR}\n}\n\ninstallTeleportdPlugin() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no arm64 teleport binaries according to owner\n        return\n    fi\n\n    CURRENT_VERSION=$(teleportd --version 2>/dev/null | sed 's/teleportd version v//g')\n    local TARGET_VERSION=\"0.8.0\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${TARGET_VERSION}; then\n        echo \"currently installed teleportd version ${CURRENT_VERSION} is greater than (or equal to) target base version ${TARGET_VERSION}. skipping installTeleportdPlugin.\"\n    else\n        downloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} ${TARGET_VERSION}\n        mv \"${TELEPORTD_PLUGIN_DOWNLOAD_DIR}/teleportd-v${TELEPORTD_VERSION}\" \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n        chmod 755 \"${TELEPORTD_PLUGIN_BIN_DIR}/teleportd\" || exit ${ERR_TELEPORTD_INSTALL_ERR}\n    fi\n    rm -rf ${TELEPORTD_PLUGIN_DOWNLOAD_DIR}\n}\n\nsetupCNIDirs() {\n    mkdir -p $CNI_BIN_DIR\n    chown -R root:root $CNI_BIN_DIR\n    chmod -R 755 $CNI_BIN_DIR\n\n    mkdir -p $CNI_CONFIG_DIR\n    chown -R root:root $CNI_CONFIG_DIR\n    chmod 755 $CNI_CONFIG_DIR\n}\n\ninstallCNI() {\n    CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}    # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar cni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\ninstallAzureCNI() {\n    CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/} # Use bash builtin ## to remove all chars (\"*\") up to the final \"/\"\n    CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}         # Use bash builtin % to remove the .tgz to look for a folder rather than tgz\n\n    # We want to use the untar azurecni reference first. And if that doesn't exist on the vhd does the tgz?\n    # And if tgz is already on the vhd then just untar into CNI_BIN_DIR\n    # Latest VHD should have the untar, older should have the tgz. And who knows will have neither.\n    if [[ -d \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" ]]; then\n        mv ${CNI_DOWNLOADS_DIR}/${CNI_DIR_TMP}/* $CNI_BIN_DIR\n    else\n        if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n            downloadAzureCNI\n        fi\n\n        tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n    fi\n\n    chown -R root:root $CNI_BIN_DIR\n}\n\nextractKubeBinaries() {\n    K8S_VERSION=$1\n    KUBE_BINARY_URL=$2\n\n    mkdir -p ${K8S_DOWNLOADS_DIR}\n    K8S_TGZ_TMP=${KUBE_BINARY_URL##*/}\n    retrycmd_get_tarball 120 5 \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" ${KUBE_BINARY_URL} || exit $ERR_K8S_DOWNLOAD_TIMEOUT\n    tar --transform=\"s|.*|&-${K8S_VERSION}|\" --show-transformed-names -xzvf \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\" \\\n        --strip-components=3 -C /usr/local/bin kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n    rm -f \"$K8S_DOWNLOADS_DIR/${K8S_TGZ_TMP}\"\n}\n\ninstallKubeletKubectlAndKubeProxy() {\n\n    CUSTOM_KUBE_BINARY_DOWNLOAD_URL=\"${CUSTOM_KUBE_BINARY_URL:=}\"\n    if [[ ! -z ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL} ]]; then\n        # remove the kubelet binaries to make sure the only binary left is from the CUSTOM_KUBE_BINARY_DOWNLOAD_URL\n        rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-*\n\n        # NOTE(mainred): we expect kubelet binary to be under `kubernetes/node/bin`. This suits the current setting of\n        # kube binaries used by AKS and Kubernetes upstream.\n        # TODO(mainred): let's see if necessary to auto-detect the path of kubelet\n        logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${CUSTOM_KUBE_BINARY_DOWNLOAD_URL}\n\n    else\n        if [[ ! -f \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" ]]; then\n            #TODO: remove the condition check on KUBE_BINARY_URL once RP change is released\n            if (($(echo ${KUBERNETES_VERSION} | cut -d\".\" -f2) >= 17)) && [ -n \"${KUBE_BINARY_URL}\" ]; then\n                logs_to_events \"AKS.CSE.installKubeletKubectlAndKubeProxy.extractKubeBinaries\" extractKubeBinaries ${KUBERNETES_VERSION} ${KUBE_BINARY_URL}\n            fi\n        fi\n    fi\n    mv \"/usr/local/bin/kubelet-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubelet\"\n    mv \"/usr/local/bin/kubectl-${KUBERNETES_VERSION}\" \"/usr/local/bin/kubectl\"\n\n    chmod a+x /usr/local/bin/kubelet /usr/local/bin/kubectl\n    rm -rf /usr/local/bin/kubelet-* /usr/local/bin/kubectl-* /home/hyperkube-downloads &\n}\n\npullContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    echo \"pulling the image ${CONTAINER_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullctr.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 ctr --namespace k8s.io image pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via ctr\" && exit $ERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT)\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        logs_to_events \"AKS.CSE.imagepullcrictl.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 crictl pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via crictl\" && exit $ERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT)\n    else\n        logs_to_events \"AKS.CSE.imagepull.${CONTAINER_IMAGE_URL}\" \"retrycmd_if_failure 60 1 1200 docker pull $CONTAINER_IMAGE_URL\" || (echo \"timed out pulling image ${CONTAINER_IMAGE_URL} via docker\" && exit $ERR_DOCKER_IMG_PULL_TIMEOUT)\n    fi\n}\n\nretagContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    RETAG_IMAGE_URL=$3\n    echo \"retaging from ${CONTAINER_IMAGE_URL} to ${RETAG_IMAGE_URL} using ${CLI_TOOL}\"\n    if [[ ${CLI_TOOL} == \"ctr\" ]]; then\n        ctr --namespace k8s.io image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    elif [[ ${CLI_TOOL} == \"crictl\" ]]; then\n        crictl image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    else\n        docker image tag $CONTAINER_IMAGE_URL $RETAG_IMAGE_URL\n    fi\n}\n\nretagMCRImagesForChina() {\n    # retag all the mcr for mooncake\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        # shellcheck disable=SC2016\n        allMCRImages=($(ctr --namespace k8s.io images list | grep '^mcr.microsoft.com/' | awk '{print $1}'))\n    else\n        # shellcheck disable=SC2016\n        allMCRImages=($(docker images | grep '^mcr.microsoft.com/' | awk '{str = sprintf(\"%s:%s\", $1, $2)} {print str}'))\n    fi\n    if [[ \"${allMCRImages}\" == \"\" ]]; then\n        echo \"failed to find mcr images for retag\"\n        return\n    fi\n    for mcrImage in ${allMCRImages[@]+\"${allMCRImages[@]}\"}; do\n        # in mooncake, the mcr endpoint is: mcr.azk8s.cn\n        # shellcheck disable=SC2001\n        retagMCRImage=$(echo ${mcrImage} | sed -e 's/^mcr.microsoft.com/mcr.azk8s.cn/g')\n        # can't use CLI_TOOL because crictl doesn't support retagging.\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            retagContainerImage \"ctr\" ${mcrImage} ${retagMCRImage}\n        else\n            retagContainerImage \"docker\" ${mcrImage} ${retagMCRImage}\n        fi\n    done\n}\n\nremoveContainerImage() {\n    CLI_TOOL=$1\n    CONTAINER_IMAGE_URL=$2\n    if [[ \"${CLI_TOOL}\" == \"docker\" ]]; then\n        docker image rm $CONTAINER_IMAGE_URL\n    else\n        # crictl should always be present\n        crictl rmi $CONTAINER_IMAGE_URL\n    fi\n}\n\ncleanUpImages() {\n    local targetImage=$1\n    export targetImage\n    function cleanupImagesRun() {\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}.[0-9]+$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep ${targetImage} | tr ' ' '\\n')\n        fi\n        local exit_code=$?\n        if [[ $exit_code != 0 ]]; then\n            exit $exit_code\n        elif [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    removeContainerImage ${CLI_TOOL} ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    }\n    export -f cleanupImagesRun\n    retrycmd_if_failure 10 5 120 bash -c cleanupImagesRun\n}\n\ncleanUpKubeProxyImages() {\n    echo $(date),$(hostname), startCleanUpKubeProxyImages\n    cleanUpImages \"kube-proxy\"\n    echo $(date),$(hostname), endCleanUpKubeProxyImages\n}\n\ncleanupRetaggedImages() {\n    if [[ \"${TARGET_CLOUD}\" != \"AzureChinaCloud\" ]]; then\n        if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n            if [[ \"${CLI_TOOL}\" == \"crictl\" ]]; then\n                images_to_delete=$(crictl images | awk '{print $1\":\"$2}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            else\n                images_to_delete=$(ctr --namespace k8s.io images list | awk '{print $1}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n            fi\n        else\n            images_to_delete=$(docker images --format '{{.Repository}}:{{.Tag}}' | grep '^mcr.azk8s.cn/' | tr ' ' '\\n')\n        fi\n        if [[ \"${images_to_delete}\" != \"\" ]]; then\n            echo \"${images_to_delete}\" | while read image; do\n                if [ \"${NEEDS_CONTAINERD}\" == \"true\" ]; then\n                    # always use ctr, even if crictl is installed.\n                    # crictl will remove *ALL* references to a given imageID (SHA), which removes too much.\n                    removeContainerImage \"ctr\" ${image}\n                else\n                    removeContainerImage \"docker\" ${image}\n                fi\n            done\n        fi\n    else\n        echo \"skipping container cleanup for AzureChinaCloud\"\n    fi\n}\n\ncleanUpContainerImages() {\n    export KUBERNETES_VERSION\n    export CLI_TOOL\n    export -f retrycmd_if_failure\n    export -f removeContainerImage\n    export -f cleanUpImages\n    export -f cleanUpKubeProxyImages\n    bash -c cleanUpKubeProxyImages &\n}\n\ncleanUpContainerd() {\n    rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n\noverrideNetworkConfig() {\n    CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n    touch ${CONFIG_FILEPATH}\n    cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 403}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "import yaml\nimport argparse\n\n# String value used to replace secret data\nREDACTED = 'REDACTED'\n\n# Redact functions\ndef redact_bootstrap_kubeconfig_tls_token(bootstrap_kubeconfig_write_file):\n    content_yaml = yaml.safe_load(bootstrap_kubeconfig_write_file['content'])\n    content_yaml['users'][0]['user']['token'] = REDACTED\n    bootstrap_kubeconfig_write_file['content'] = yaml.dump(content_yaml)\n\n\ndef redact_service_principal_secret(sp_secret_write_file):\n    sp_secret_write_file['content'] = REDACTED\n\n\n# Maps write_file's path to the corresponding function used to redact it within cloud-config.txt\n# This script will always redact these write_files if they exist within the specified cloud-config.txt\nPATH_TO_REDACT_FUNC = {\n    '/var/lib/kubelet/bootstrap-kubeconfig': redact_bootstrap_kubeconfig_tls_token,\n    '/etc/kubernetes/sp.txt': redact_service_principal_secret\n}\n\n\ndef redact_cloud_config(cloud_config_path, output_path):\n    target_paths = set(PATH_TO_REDACT_FUNC.keys())\n\n    with open(cloud_config_path, 'r') as f:\n        cloud_config_data = f.read()\n    cloud_config = yaml.safe_load(cloud_config_data)\n\n    for write_file in cloud_config['write_files']:\n        if write_file['path'] in target_paths:\n            target_path = write_file['path']\n            target_paths.remove(target_path)\n\n            print('Redacting secrets from write_file: ' + target_path)\n            PATH_TO_REDACT_FUNC[target_path](write_file)\n\n        if len(target_paths) == 0:\n            break\n\n\n    print('Dumping redacted cloud-config to: ' + output_path)\n    with open(output_path, 'w+') as output_file:\n        output_file.write(yaml.dump(cloud_config))\n\n\nif __name__ == '__main__':\n    parser = argparse.ArgumentParser(\n        description='Command line utility used to redact secrets from write_file definitions for ' +\n            str([\", \".join(PATH_TO_REDACT_FUNC)]) + ' within a specified cloud-config.txt. \\\n            These secrets must be redacted before cloud-config.txt can be collected for logging.')\n    parser.add_argument(\n        \"--cloud-config-path\",\n        required=True,\n        type=str,\n        help='Path to cloud-config.txt to redact')\n    parser.add_argument(\n        \"--output-path\",\n        required=True,\n        type=str,\n        help='Path to the newly generated cloud-config.txt with redacted secrets')\n\n    args = parser.parse_args()\n    redact_cloud_config(args.cloud_config_path, args.output_path)", "num_lines": 67}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env python3\n\nimport urllib3\nimport uuid\nimport xml.etree.ElementTree as ET\n\nhttp = urllib3.PoolManager()\n\n# Get the container_id and deployment_id from the Goal State\ngoal_state_xml = http.request(\n        'GET',\n        'http://168.63.129.16/machine/?comp=goalstate',\n        headers={\n            'x-ms-version': '2012-11-30'\n        }\n    )\ngoal_state = ET.fromstring(goal_state_xml.data.decode('utf-8'))\ncontainer_id = goal_state.findall('./Container/ContainerId')[0].text\nrole_config_name = goal_state.findall('./Container/RoleInstanceList/RoleInstance/Configuration/ConfigName')[0].text\ndeployment_id = role_config_name.split('.')[0]\n\n# Upload the logs\nwith open('/var/lib/waagent/logcollector/logs.zip', 'rb') as logs:\n    logs_data = logs.read()\n    upload_logs = http.request(\n        'PUT',\n        'http://168.63.129.16:32526/vmAgentLog',\n        headers={\n            'x-ms-version': '2015-09-01',\n            'x-ms-client-correlationid': str(uuid.uuid4()),\n            'x-ms-client-name': 'AKSCSEPlugin',\n            'x-ms-client-version': '0.1.0',\n            'x-ms-containerid': container_id,\n            'x-ms-vmagentlog-deploymentid': deployment_id,\n        },\n        body=logs_data,\n    )\n\nif upload_logs.status == 200:\n    print(\"Successfully uploaded logs\")\n    exit(0)\nelse:\n    print('Failed to upload logs')\n    print(f'Response status: {upload_logs.status}')\n    print(f'Response body:\\n{upload_logs.data.decode(\"utf-8\")}')\n    exit(1)\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing cse_install_distro.sh for Ubuntu\"\n\nremoveMoby() {\n    apt_get_purge 10 5 300 moby-engine moby-cli\n}\n\nremoveContainerd() {\n    apt_get_purge 10 5 300 moby-containerd\n}\n\ninstallDeps() {\n    if [[ $(isARM64) == 1 ]]; then\n        wait_for_apt_locks\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl -fsSL https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb > /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT\n    fi\n    retrycmd_if_failure 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit $ERR_MS_PROD_DEB_PKG_ADD_FAIL\n\n    aptmarkWALinuxAgent hold\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n\n    pkg_list=(apt-transport-https ca-certificates ceph-common cgroup-lite cifs-utils conntrack cracklib-runtime ebtables ethtool git glusterfs-client htop iftop init-system-helpers inotify-tools iotop iproute2 ipset iptables nftables jq libpam-pwquality libpwquality-tools mount nfs-common pigz socat sysfsutils sysstat traceroute util-linux xz-utils netcat dnsutils zip rng-tools kmod gcc make dkms initramfs-tools linux-headers-$(uname -r))\n\n    local OSVERSION\n    OSVERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    BLOBFUSE_VERSION=\"1.4.5\"\n    BLOBFUSE2_VERSION=\"2.0.3\"\n\n    if [ \"${OSVERSION}\" == \"16.04\" ]; then\n        BLOBFUSE_VERSION=\"1.3.7\"\n    fi\n\n    if [[ $(isARM64) != 1 ]]; then\n        # blobfuse is not present in ARM64\n        # blobfuse2 is installed for all ubuntu versions, it is included in pkg_list\n        # for 22.04, fuse3 is installed. for all others, fuse is installed\n        # for 16.04, installed blobfuse1.3.7, for all others except 22.04, installed blobfuse1.4.5\n        pkg_list+=(blobfuse2=${BLOBFUSE2_VERSION})\n        if [[ \"${OSVERSION}\" == \"22.04\" ]]; then\n            pkg_list+=(fuse3)\n        else\n            pkg_list+=(blobfuse=${BLOBFUSE_VERSION} fuse)\n        fi\n    fi\n\n    for apt_package in ${pkg_list[*]}; do\n        if ! apt_get_install 30 1 600 $apt_package; then\n            journalctl --no-pager -u $apt_package\n            exit $ERR_APT_INSTALL_TIMEOUT\n        fi\n    done\n}\n\nupdateAptWithMicrosoftPkg() {\n    if [[ $(isARM64) == 1 ]]; then\n        if [ \"${UBUNTU_RELEASE}\" == \"22.04\" ]; then\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        else\n            retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/multiarch/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n        fi\n    else\n        retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/config/ubuntu/${UBUNTU_RELEASE}/prod.list > /tmp/microsoft-prod.list || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    fi\n\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit $ERR_MOBY_APT_LIST_TIMEOUT\n    if [[ ${UBUNTU_RELEASE} == \"18.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/18.04/multiarch/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    elif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then {\n        echo \"deb [arch=amd64,arm64,armhf] https://packages.microsoft.com/ubuntu/${UBUNTU_RELEASE}/prod testing main\" > /etc/apt/sources.list.d/microsoft-prod-testing.list\n    }\n    fi\n    \n    retrycmd_if_failure_no_stats 120 5 25 curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /tmp/microsoft.gpg || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    retrycmd_if_failure 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit $ERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}\n\ncleanUpGPUDrivers() {\n    rm -Rf $GPU_DEST /opt/gpu\n}\n\n# CSE+VHD can dictate the containerd version, users don't care as long as it works\ninstallStandaloneContainerd() {\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    UBUNTU_CODENAME=$(lsb_release -c -s)\n    CONTAINERD_VERSION=$1    \n    # we always default to the .1 patch versons\n    CONTAINERD_PATCH_VERSION=\"${2:-1}\"\n\n    # runc needs to be installed first or else existing vhd version causes conflict with containerd.\n    logs_to_events \"AKS.CSE.installContainerRuntime.ensureRunc\" \"ensureRunc ${RUNC_VERSION:-\"\"}\" # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n\n    # azure-built runtimes have a \"+azure\" suffix in their version strings (i.e 1.4.1+azure). remove that here.\n    CURRENT_VERSION=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||' | cut -d \"+\" -f 1)\n    CURRENT_COMMIT=$(containerd -version | cut -d \" \" -f 4)\n    # v1.4.1 is our lowest supported version of containerd\n\n    if [ -z \"$CURRENT_VERSION\" ]; then\n        CURRENT_VERSION=\"0.0.0\"\n    fi\n\n    # the user-defined package URL is always picked first, and the other options won't be tried when this one fails\n    CONTAINERD_PACKAGE_URL=\"${CONTAINERD_PACKAGE_URL:=}\"\n    if [[ ! -z ${CONTAINERD_PACKAGE_URL} ]]; then\n        echo \"Installing containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromURL\" downloadContainerdFromURL ${CONTAINERD_PACKAGE_URL}\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        echo \"Succeeded to install containerd from user input: ${CONTAINERD_PACKAGE_URL}\"\n        return 0\n    fi\n\n    #if there is no containerd_version input from RP, use hardcoded version\n    if [[ -z ${CONTAINERD_VERSION} ]]; then\n        CONTAINERD_VERSION=\"1.7.1\"\n        CONTAINERD_PATCH_VERSION=\"1\"\n        echo \"Containerd Version not specified, using default version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    else\n        echo \"Using specified Containerd Version: ${CONTAINERD_VERSION}-${CONTAINERD_PATCH_VERSION}\"\n    fi\n\n    CURRENT_MAJOR_MINOR=\"$(echo $CURRENT_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    DESIRED_MAJOR_MINOR=\"$(echo $CONTAINERD_VERSION | tr '.' '\\n' | head -n 2 | paste -sd.)\"\n    semverCompare \"$CURRENT_VERSION\" \"$CONTAINERD_VERSION\"\n    HAS_GREATER_VERSION=\"$?\"\n\n    if [[ \"$HAS_GREATER_VERSION\" == \"0\" ]] && [[ \"$CURRENT_MAJOR_MINOR\" == \"$DESIRED_MAJOR_MINOR\" ]]; then\n        echo \"currently installed containerd version ${CURRENT_VERSION} matches major.minor with higher patch ${CONTAINERD_VERSION}. skipping installStandaloneContainerd.\"\n    else\n        echo \"installing containerd version ${CONTAINERD_VERSION}\"\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeMoby\" removeMoby\n        logs_to_events \"AKS.CSE.installContainerRuntime.removeContainerd\" removeContainerd\n        # if containerd version has been overriden then there should exist a local .deb file for it on aks VHDs (best-effort)\n        # if no files found then try fetching from packages.microsoft repo\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -f \"${CONTAINERD_DEB_FILE}\" ]]; then\n            logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n            return 0\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.downloadContainerdFromVersion\" \"downloadContainerdFromVersion ${CONTAINERD_VERSION} ${CONTAINERD_PATCH_VERSION}\"\n        CONTAINERD_DEB_FILE=\"$(ls ${CONTAINERD_DOWNLOADS_DIR}/moby-containerd_${CONTAINERD_VERSION}*)\"\n        if [[ -z \"${CONTAINERD_DEB_FILE}\" ]]; then\n            echo \"Failed to locate cached containerd deb\"\n            exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        fi\n        logs_to_events \"AKS.CSE.installContainerRuntime.installDebPackageFromFile\" \"installDebPackageFromFile ${CONTAINERD_DEB_FILE}\" || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n        return 0\n    fi\n}\n\ndownloadContainerdFromVersion() {\n    CONTAINERD_VERSION=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    # Adding updateAptWithMicrosoftPkg since AB e2e uses an older image version with uncached containerd 1.6 so it needs to download from testing repo.\n    # And RP no image pull e2e has apt update restrictions that prevent calls to packages.microsoft.com in CSE\n    # This won't be called for new VHDs as they have containerd 1.6 cached\n    updateAptWithMicrosoftPkg \n    apt_get_download 20 30 moby-containerd=${CONTAINERD_VERSION}* || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n    cp -al ${APT_CACHE_DIR}moby-containerd_${CONTAINERD_VERSION}* $CONTAINERD_DOWNLOADS_DIR/ || exit $ERR_CONTAINERD_INSTALL_TIMEOUT\n}\n\ndownloadContainerdFromURL() {\n    CONTAINERD_DOWNLOAD_URL=$1\n    mkdir -p $CONTAINERD_DOWNLOADS_DIR\n    CONTAINERD_DEB_TMP=${CONTAINERD_DOWNLOAD_URL##*/}\n    retrycmd_curl_file 120 5 60 \"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\" ${CONTAINERD_DOWNLOAD_URL} || exit $ERR_CONTAINERD_DOWNLOAD_TIMEOUT\n    CONTAINERD_DEB_FILE=\"$CONTAINERD_DOWNLOADS_DIR/${CONTAINERD_DEB_TMP}\"\n}\n\ninstallMoby() {\n    ensureRunc ${RUNC_VERSION:-\"\"} # RUNC_VERSION is an optional override supplied via NodeBootstrappingConfig api\n    CURRENT_VERSION=$(dockerd --version | grep \"Docker version\" | cut -d \",\" -f 1 | cut -d \" \" -f 3 | cut -d \"+\" -f 1)\n    local MOBY_VERSION=\"19.03.14\"\n    local MOBY_CONTAINERD_VERSION=\"1.4.13\"\n    if semverCompare ${CURRENT_VERSION:-\"0.0.0\"} ${MOBY_VERSION}; then\n        echo \"currently installed moby-docker version ${CURRENT_VERSION} is greater than (or equal to) target base version ${MOBY_VERSION}. skipping installMoby.\"\n    else\n        removeMoby\n        updateAptWithMicrosoftPkg\n        MOBY_CLI=${MOBY_VERSION}\n        if [[ \"${MOBY_CLI}\" == \"3.0.4\" ]]; then\n            MOBY_CLI=\"3.0.3\"\n        fi\n        apt_get_install 20 30 120 moby-engine=${MOBY_VERSION}* moby-cli=${MOBY_CLI}* moby-containerd=${MOBY_CONTAINERD_VERSION}* --allow-downgrades || exit $ERR_MOBY_INSTALL_TIMEOUT\n    fi\n}\n\nensureRunc() {\n    RUNC_PACKAGE_URL=\"${RUNC_PACKAGE_URL:=}\"\n    # the user-defined runc package URL is always picked first, and the other options won't be tried when this one fails\n    if [[ ! -z ${RUNC_PACKAGE_URL} ]]; then\n        echo \"Installing runc from user input: ${RUNC_PACKAGE_URL}\"\n        mkdir -p $RUNC_DOWNLOADS_DIR\n        RUNC_DEB_TMP=${RUNC_PACKAGE_URL##*/}\n        RUNC_DEB_FILE=\"$RUNC_DOWNLOADS_DIR/${RUNC_DEB_TMP}\"\n        retrycmd_curl_file 120 5 60 ${RUNC_DEB_FILE} ${RUNC_PACKAGE_URL} || exit $ERR_RUNC_DOWNLOAD_TIMEOUT\n        # we'll use a user-defined containerd package to install containerd even though it's the same version as\n        # the one already installed on the node considering the source is built by the user for hotfix or test\n        installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n        echo \"Succeeded to install runc from user input: ${RUNC_PACKAGE_URL}\"\n        return 0\n    fi\n\n    TARGET_VERSION=${1:-\"\"}\n    if [[ -z ${TARGET_VERSION} ]]; then\n        TARGET_VERSION=\"1.1.7+azure-ubuntu${UBUNTU_RELEASE}\"\n    fi\n\n    if [[ $(isARM64) == 1 ]]; then\n        if [[ ${TARGET_VERSION} == \"1.0.0-rc92\" || ${TARGET_VERSION} == \"1.0.0-rc95\" ]]; then\n            # only moby-runc-1.0.3+azure-1 exists in ARM64 ubuntu repo now, no 1.0.0-rc92 or 1.0.0-rc95\n            return\n        fi\n    fi\n\n    CPU_ARCH=$(getCPUArch)  #amd64 or arm64\n    CURRENT_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\n    CLEANED_TARGET_VERSION=${TARGET_VERSION%+*} # removes the +azure-ubuntu18.04u1 (or similar) suffix\n\n    if [ \"${CURRENT_VERSION}\" == \"${CLEANED_TARGET_VERSION}\" ]; then\n        echo \"target moby-runc version ${CLEANED_TARGET_VERSION} is already installed. skipping installRunc.\"\n        return\n    fi\n    # if on a vhd-built image, first check if we've cached the deb file\n    if [ -f $VHD_LOGS_FILEPATH ]; then\n        RUNC_DEB_PATTERN=\"moby-runc_*.deb\"\n        RUNC_DEB_FILE=$(find ${RUNC_DOWNLOADS_DIR} -type f -iname \"${RUNC_DEB_PATTERN}\" | sort -V | tail -n1)\n        if [[ -f \"${RUNC_DEB_FILE}\" ]]; then\n            installDebPackageFromFile ${RUNC_DEB_FILE} || exit $ERR_RUNC_INSTALL_TIMEOUT\n            return 0\n        fi\n    fi\n    apt_get_install 20 30 120 moby-runc=${TARGET_VERSION}* --allow-downgrades || exit $ERR_RUNC_INSTALL_TIMEOUT\n}\n\n#EOF\n", "num_lines": 244}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\n\nconfigureAdminUser(){\n    chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n    chage -l \"${ADMINUSER}\"\n}\n\nconfigPrivateClusterHosts() {\n    mkdir -p /etc/systemd/system/reconcile-private-hosts.service.d/\n    touch /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf\n    tee /etc/systemd/system/reconcile-private-hosts.service.d/10-fqdn.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBE_API_SERVER_NAME=${API_SERVER_NAME}\"\nEOF\n  systemctlEnableAndStart reconcile-private-hosts || exit $ERR_SYSTEMCTL_START_FAIL\n}\nconfigureTransparentHugePage() {\n    ETC_SYSFS_CONF=\"/etc/sysfs.conf\"\n    if [[ \"${THP_ENABLED}\" != \"\" ]]; then\n        echo \"${THP_ENABLED}\" > /sys/kernel/mm/transparent_hugepage/enabled\n        echo \"kernel/mm/transparent_hugepage/enabled=${THP_ENABLED}\" >> ${ETC_SYSFS_CONF}\n    fi\n    if [[ \"${THP_DEFRAG}\" != \"\" ]]; then\n        echo \"${THP_DEFRAG}\" > /sys/kernel/mm/transparent_hugepage/defrag\n        echo \"kernel/mm/transparent_hugepage/defrag=${THP_DEFRAG}\" >> ${ETC_SYSFS_CONF}\n    fi\n}\n\nconfigureSwapFile() {\n    # https://learn.microsoft.com/en-us/troubleshoot/azure/virtual-machines/troubleshoot-device-names-problems#identify-disk-luns\n    swap_size_kb=$(expr ${SWAP_FILE_SIZE_MB} \\* 1000)\n    swap_location=\"\"\n    \n    # Attempt to use the resource disk\n    if [[ -L /dev/disk/azure/resource-part1 ]]; then\n        resource_disk_path=$(findmnt -nr -o target -S $(readlink -f /dev/disk/azure/resource-part1))\n        disk_free_kb=$(df ${resource_disk_path} | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use resource disk for swap file\"\n            swap_location=${resource_disk_path}/swapfile\n        else\n            echo \"Insufficient disk space on resource disk to create swap file: request ${swap_size_kb} free ${disk_free_kb}, attempting to fall back to OS disk...\"\n        fi\n    fi\n\n    # If we couldn't use the resource disk, attempt to use the OS disk\n    if [[ -z \"${swap_location}\" ]]; then\n        # Directly check size on the root directory since we can't rely on 'root-part1' always being the correct label\n        os_device=$(readlink -f /dev/disk/azure/root)\n        disk_free_kb=$(df -P / | sed 1d | awk '{print $4}')\n        if [[ ${disk_free_kb} -gt ${swap_size_kb} ]]; then\n            echo \"Will use OS disk for swap file\"\n            swap_location=/swapfile\n        else\n            echo \"Insufficient disk space on OS device ${os_device} to create swap file: request ${swap_size_kb} free ${disk_free_kb}\"\n            exit $ERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE\n        fi\n    fi\n\n    echo \"Swap file will be saved to: ${swap_location}\"\n    retrycmd_if_failure 24 5 25 fallocate -l ${swap_size_kb}K ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    chmod 600 ${swap_location}\n    retrycmd_if_failure 24 5 25 mkswap ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    retrycmd_if_failure 24 5 25 swapon --show | grep ${swap_location} || exit $ERR_SWAP_CREATE_FAIL\n    echo \"${swap_location} none swap sw 0 0\" >> /etc/fstab\n}\n\nconfigureEtcEnvironment() {\n    mkdir -p /etc/systemd/system.conf.d/\n    touch /etc/systemd/system.conf.d/proxy.conf\n    chmod 0644 /etc/systemd/system.conf.d/proxy.conf\n\n    mkdir -p  /etc/apt/apt.conf.d\n    chmod 0644 /etc/apt/apt.conf.d/95proxy\n    touch /etc/apt/apt.conf.d/95proxy\n\n    # TODO(ace): this pains me but quick and dirty refactor\n    echo \"[Manager]\" >> /etc/systemd/system.conf.d/proxy.conf\n    if [ \"${HTTP_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTP_PROXY=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"http_proxy=${HTTP_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::http::proxy \\\"${HTTP_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTP_PROXY=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"http_proxy=${HTTP_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${HTTPS_PROXY_URLS}\" != \"\" ]; then\n        echo \"HTTPS_PROXY=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"https_proxy=${HTTPS_PROXY_URLS}\" >> /etc/environment\n        echo \"Acquire::https::proxy \\\"${HTTPS_PROXY_URLS}\\\";\" >> /etc/apt/apt.conf.d/95proxy\n        echo \"DefaultEnvironment=\\\"HTTPS_PROXY=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"https_proxy=${HTTPS_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n    if [ \"${NO_PROXY_URLS}\" != \"\" ]; then\n        echo \"NO_PROXY=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"no_proxy=${NO_PROXY_URLS}\" >> /etc/environment\n        echo \"DefaultEnvironment=\\\"NO_PROXY=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n        echo \"DefaultEnvironment=\\\"no_proxy=${NO_PROXY_URLS}\\\"\" >> /etc/systemd/system.conf.d/proxy.conf\n    fi\n\n    # for kubelet to pick up the proxy\n    mkdir -p \"/etc/systemd/system/kubelet.service.d\"\n    tee \"/etc/systemd/system/kubelet.service.d/10-httpproxy.conf\" > /dev/null <<'EOF'\n[Service]\nEnvironmentFile=/etc/environment\nEOF\n}\n\nconfigureHTTPProxyCA() {\n    if [[ $OS == $MARINER_OS_NAME ]]; then\n        cert_dest=\"/usr/share/pki/ca-trust-source/anchors\"\n        update_cmd=\"update-ca-trust\"\n    else\n        cert_dest=\"/usr/local/share/ca-certificates\"\n        update_cmd=\"update-ca-certificates\"\n    fi\n    echo \"${HTTP_PROXY_TRUSTED_CA}\" | base64 -d > \"${cert_dest}/proxyCA.crt\" || exit $ERR_UPDATE_CA_CERTS\n    $update_cmd || exit $ERR_UPDATE_CA_CERTS\n}\n\nconfigureCustomCaCertificate() {\n    mkdir -p /opt/certs\n    for i in $(seq 0 $((${CUSTOM_CA_TRUST_COUNT} - 1))); do\n        # directly referring to the variable as \"${CUSTOM_CA_CERT_${i}}\"\n        # causes bad substitution errors in bash\n        # dynamically declare and use `!` to add a layer of indirection\n        declare varname=CUSTOM_CA_CERT_${i} \n        echo \"${!varname}\" | base64 -d > /opt/certs/00000000000000cert${i}.crt\n    done\n    # This will block until the service is considered active.\n    # Update_certs.service is a oneshot type of unit that\n    # is considered active when the ExecStart= command terminates with a zero status code.\n    systemctl restart update_certs.service || exit $ERR_UPDATE_CA_CERTS\n    # after new certs are added to trust store, containerd will not pick them up properly before restart.\n    # aim here is to have this working straight away for a freshly provisioned node\n    # so we force a restart after the certs are updated\n    # custom CA daemonset copies certs passed by the user to the node, what then triggers update_certs.path unit\n    # path unit then triggers the script that copies over cert files to correct location on the node and updates the trust store\n    # as a part of this flow we could restart containerd everytime a new cert is added to the trust store using custom CA\n    systemctl restart containerd\n}\n\nconfigureContainerdUlimits() {\n  CONTAINERD_ULIMIT_DROP_IN_FILE_PATH=\"/etc/systemd/system/containerd.service.d/set_ulimits.conf\"\n  touch \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  chmod 0600 \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\"\n  tee \"${CONTAINERD_ULIMIT_DROP_IN_FILE_PATH}\" > /dev/null <<EOF\n$(echo \"$CONTAINERD_ULIMITS\" | tr ' ' '\\n')\nEOF\n\n  systemctl daemon-reload\n  systemctl restart containerd\n}\n\n\nconfigureKubeletServerCert() {\n    KUBELET_SERVER_PRIVATE_KEY_PATH=\"/etc/kubernetes/certs/kubeletserver.key\"\n    KUBELET_SERVER_CERT_PATH=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n    openssl genrsa -out $KUBELET_SERVER_PRIVATE_KEY_PATH 2048\n    openssl req -new -x509 -days 7300 -key $KUBELET_SERVER_PRIVATE_KEY_PATH -out $KUBELET_SERVER_CERT_PATH -subj \"/CN=${NODE_NAME}\" -addext \"subjectAltName=DNS:${NODE_NAME}\"\n}\n\nconfigureK8s() {\n    APISERVER_PUBLIC_KEY_PATH=\"/etc/kubernetes/certs/apiserver.crt\"\n    touch \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chmod 0644 \"${APISERVER_PUBLIC_KEY_PATH}\"\n    chown root:root \"${APISERVER_PUBLIC_KEY_PATH}\"\n\n    AZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\n    touch \"${AZURE_JSON_PATH}\"\n    chmod 0600 \"${AZURE_JSON_PATH}\"\n    chown root:root \"${AZURE_JSON_PATH}\"\n\n    mkdir -p \"/etc/kubernetes/certs\"\n    if [ -n \"${KUBELET_CLIENT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.key\n    fi\n    if [ -n \"${KUBELET_CLIENT_CERT_CONTENT}\" ]; then\n        echo \"${KUBELET_CLIENT_CERT_CONTENT}\" | base64 -d > /etc/kubernetes/certs/client.crt\n    fi\n    if [ -n \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" ]; then\n        echo \"${SERVICE_PRINCIPAL_FILE_CONTENT}\" | base64 -d > /etc/kubernetes/sp.txt\n    fi\n\n    set +x\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode > \"${APISERVER_PUBLIC_KEY_PATH}\"\n    # Perform the required JSON escaping\n    SP_FILE=\"/etc/kubernetes/sp.txt\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=\"$(cat \"$SP_FILE\")\"\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n    SERVICE_PRINCIPAL_CLIENT_SECRET=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n    rm \"$SP_FILE\" # unneeded after reading from disk.\n    cat << EOF > \"${AZURE_JSON_PATH}\"\n{\n    \"cloud\": \"${TARGET_CLOUD}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRateLimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRateLimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRateLimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOF\n    set -x\n    if [[ \"${CLOUDPROVIDER_BACKOFF_MODE}\" = \"v2\" ]]; then\n        sed -i \"/cloudProviderBackoffExponent/d\" /etc/kubernetes/azure.json\n        sed -i \"/cloudProviderBackoffJitter/d\" /etc/kubernetes/azure.json\n    fi\n\n    configureKubeletServerCert\n    if [ \"${IS_CUSTOM_CLOUD}\" == \"true\" ]; then\n        set +x\n        AKS_CUSTOM_CLOUD_JSON_PATH=\"/etc/kubernetes/${TARGET_ENVIRONMENT}.json\"\n        touch \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chmod 0600 \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        chown root:root \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n\n        echo \"${CUSTOM_ENV_JSON}\" | base64 -d > \"${AKS_CUSTOM_CLOUD_JSON_PATH}\"\n        set -x\n    fi\n\n    if [ \"${KUBELET_CONFIG_FILE_ENABLED}\" == \"true\" ]; then\n        set +x\n        KUBELET_CONFIG_JSON_PATH=\"/etc/default/kubeletconfig.json\"\n        touch \"${KUBELET_CONFIG_JSON_PATH}\"\n        chmod 0600 \"${KUBELET_CONFIG_JSON_PATH}\"\n        chown root:root \"${KUBELET_CONFIG_JSON_PATH}\"\n        echo \"${KUBELET_CONFIG_FILE_CONTENT}\" | base64 -d > \"${KUBELET_CONFIG_JSON_PATH}\"\n        set -x\n        KUBELET_CONFIG_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-componentconfig.conf\"\n        touch \"${KUBELET_CONFIG_DROP_IN}\"\n        chmod 0600 \"${KUBELET_CONFIG_DROP_IN}\"\n        tee \"${KUBELET_CONFIG_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_CONFIG_FILE_FLAGS=--config /etc/default/kubeletconfig.json\"\nEOF\n    fi\n}\n\nconfigureCNI() {\n    # needed for the iptables rules to work on bridges\n    retrycmd_if_failure 120 5 25 modprobe br_netfilter || exit $ERR_MODPROBE_FAIL\n    echo -n \"br_netfilter\" > /etc/modules-load.d/br_netfilter.conf\n    configureCNIIPTables\n}\n\nconfigureCNIIPTables() {\n    if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n        mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n        chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n        if [[ \"${NETWORK_POLICY}\" == \"calico\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        elif [[ \"${NETWORK_POLICY}\" == \"\" || \"${NETWORK_POLICY}\" == \"none\" ]] && [[ \"${NETWORK_MODE}\" == \"transparent\" ]]; then\n          sed -i 's#\"mode\":\"bridge\"#\"mode\":\"transparent\"#g' $CNI_CONFIG_DIR/10-azure.conflist\n        fi\n        /sbin/ebtables -t nat --list\n    fi\n}\n\ndisableSystemdResolved() {\n    ls -ltr /etc/resolv.conf\n    cat /etc/resolv.conf\n    UBUNTU_RELEASE=$(lsb_release -r -s)\n    if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n        echo \"Ingorings systemd-resolved query service but using its resolv.conf file\"\n        echo \"This is the simplest approach to workaround resolved issues without completely uninstall it\"\n        [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n        ls -ltr /etc/resolv.conf\n        cat /etc/resolv.conf\n    fi\n}\n\nensureContainerd() {\n  if [ \"${TELEPORT_ENABLED}\" == \"true\" ]; then\n    ensureTeleportd\n  fi\n  mkdir -p \"/etc/systemd/system/containerd.service.d\" \n  tee \"/etc/systemd/system/containerd.service.d/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\n  mkdir -p /etc/containerd\n  if [[ \"${GPU_NODE}\" = true ]] && [[ \"${skip_nvidia_driver_install}\" == \"true\" ]]; then\n    echo \"Generating non-GPU containerd config for GPU node due to VM tags\"\n    echo \"${CONTAINERD_CONFIG_NO_GPU_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  else\n    echo \"Generating containerd config...\"\n    echo \"${CONTAINERD_CONFIG_CONTENT}\" | base64 -d > /etc/containerd/config.toml || exit $ERR_FILE_WATCH_TIMEOUT\n  fi\n\n  tee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n  retrycmd_if_failure 120 5 25 sysctl --system || exit $ERR_SYSCTL_RELOAD\n  systemctl is-active --quiet docker && (systemctl_disable 20 30 120 docker || exit $ERR_SYSTEMD_DOCKER_STOP_FAIL)\n  systemctlEnableAndStart containerd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureNoDupOnPromiscuBridge() {\n    systemctlEnableAndStart ensure-no-dup || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureTeleportd() {\n    systemctlEnableAndStart teleportd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\nensureDocker() {\n    DOCKER_SERVICE_EXEC_START_FILE=/etc/systemd/system/docker.service.d/exec_start.conf\n    usermod -aG docker ${ADMINUSER}\n    DOCKER_MOUNT_FLAGS_SYSTEMD_FILE=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n    DOCKER_JSON_FILE=/etc/docker/daemon.json\n    for i in $(seq 1 1200); do\n        if [ -s $DOCKER_JSON_FILE ]; then\n            jq '.' < $DOCKER_JSON_FILE && break\n        fi\n        if [ $i -eq 1200 ]; then\n            exit $ERR_FILE_WATCH_TIMEOUT\n        else\n            sleep 1\n        fi\n    done\n    systemctl is-active --quiet containerd && (systemctl_disable 20 30 120 containerd || exit $ERR_SYSTEMD_CONTAINERD_STOP_FAIL)\n    systemctlEnableAndStart docker || exit $ERR_DOCKER_START_FAIL\n\n}\n\nensureDHCPv6() {\n    systemctlEnableAndStart dhcpv6 || exit $ERR_SYSTEMCTL_START_FAIL\n    retrycmd_if_failure 120 5 25 modprobe ip6_tables || exit $ERR_MODPROBE_FAIL\n}\n\nensureKubelet() {\n    KUBELET_DEFAULT_FILE=/etc/default/kubelet\n    mkdir -p /etc/default\n    echo \"KUBELET_FLAGS=${KUBELET_FLAGS}\" > \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_REGISTER_SCHEDULABLE=true\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"NETWORK_POLICY=${NETWORK_POLICY}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_IMAGE=${KUBELET_IMAGE}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    echo \"KUBELET_NODE_LABELS=${KUBELET_NODE_LABELS}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    if [ -n \"${AZURE_ENVIRONMENT_FILEPATH}\" ]; then\n        echo \"AZURE_ENVIRONMENT_FILEPATH=${AZURE_ENVIRONMENT_FILEPATH}\" >> \"${KUBELET_DEFAULT_FILE}\"\n    fi\n    \n    KUBE_CA_FILE=\"/etc/kubernetes/certs/ca.crt\"\n    mkdir -p \"$(dirname \"${KUBE_CA_FILE}\")\"\n    echo \"${KUBE_CA_CRT}\" | base64 -d > \"${KUBE_CA_FILE}\"\n    chmod 0600 \"${KUBE_CA_FILE}\"\n    \n    if [ \"${CLIENT_TLS_BOOTSTRAPPING_ENABLED}\" == \"true\" ]; then\n        KUBELET_TLS_DROP_IN=\"/etc/systemd/system/kubelet.service.d/10-tlsbootstrap.conf\"\n        mkdir -p \"$(dirname \"${KUBELET_TLS_DROP_IN}\")\"\n        touch \"${KUBELET_TLS_DROP_IN}\"\n        chmod 0600 \"${KUBELET_TLS_DROP_IN}\"\n        tee \"${KUBELET_TLS_DROP_IN}\" > /dev/null <<EOF\n[Service]\nEnvironment=\"KUBELET_TLS_BOOTSTRAP_FLAGS=--kubeconfig /var/lib/kubelet/kubeconfig --bootstrap-kubeconfig /var/lib/kubelet/bootstrap-kubeconfig\"\nEOF\n        BOOTSTRAP_KUBECONFIG_FILE=/var/lib/kubelet/bootstrap-kubeconfig\n        mkdir -p \"$(dirname \"${BOOTSTRAP_KUBECONFIG_FILE}\")\"\n        touch \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        chmod 0644 \"${BOOTSTRAP_KUBECONFIG_FILE}\"\n        tee \"${BOOTSTRAP_KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: kubelet-bootstrap\n  user:\n    token: \"${TLS_BOOTSTRAP_TOKEN}\"\ncontexts:\n- context:\n    cluster: localcluster\n    user: kubelet-bootstrap\n  name: bootstrap-context\ncurrent-context: bootstrap-context\nEOF\n    else\n        KUBECONFIG_FILE=/var/lib/kubelet/kubeconfig\n        mkdir -p \"$(dirname \"${KUBECONFIG_FILE}\")\"\n        touch \"${KUBECONFIG_FILE}\"\n        chmod 0644 \"${KUBECONFIG_FILE}\"\n        tee \"${KUBECONFIG_FILE}\" > /dev/null <<EOF\napiVersion: v1\nkind: Config\nclusters:\n- name: localcluster\n  cluster:\n    certificate-authority: /etc/kubernetes/certs/ca.crt\n    server: https://${API_SERVER_NAME}:443\nusers:\n- name: client\n  user:\n    client-certificate: /etc/kubernetes/certs/client.crt\n    client-key: /etc/kubernetes/certs/client.key\ncontexts:\n- context:\n    cluster: localcluster\n    user: client\n  name: localclustercontext\ncurrent-context: localclustercontext\nEOF\n    fi\n    KUBELET_RUNTIME_CONFIG_SCRIPT_FILE=/opt/azure/containers/kubelet.sh\n    tee \"${KUBELET_RUNTIME_CONFIG_SCRIPT_FILE}\" > /dev/null <<EOF\n#!/bin/bash\n# Disallow container from reaching out to the special IP address 168.63.129.16\n# for TCP protocol (which http uses)\n#\n# 168.63.129.16 contains protected settings that have priviledged info.\n#\n# The host can still reach 168.63.129.16 because it goes through the OUTPUT chain, not FORWARD.\n#\n# Note: we should not block all traffic to 168.63.129.16. For example UDP traffic is still needed\n# for DNS.\niptables -I FORWARD -d 168.63.129.16 -p tcp --dport 80 -j DROP\nEOF\n    systemctlEnableAndStart kubelet || exit $ERR_KUBELET_START_FAIL\n}\n\nensureMigPartition(){\n    mkdir -p /etc/systemd/system/mig-partition.service.d/\n    touch /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf\n    tee /etc/systemd/system/mig-partition.service.d/10-mig-profile.conf > /dev/null <<EOF\n[Service]\nEnvironment=\"GPU_INSTANCE_PROFILE=${GPU_INSTANCE_PROFILE}\"\nEOF\n    # this is expected to fail and work only on next reboot\n    # it MAY succeed, only due to unreliability of systemd\n    # service type=Simple, which does not exit non-zero\n    # on failure if ExecStart failed to invoke.\n    systemctlEnableAndStart mig-partition\n}\n\nensureSysctl() {\n    SYSCTL_CONFIG_FILE=/etc/sysctl.d/999-sysctl-aks.conf\n    mkdir -p \"$(dirname \"${SYSCTL_CONFIG_FILE}\")\"\n    touch \"${SYSCTL_CONFIG_FILE}\"\n    chmod 0644 \"${SYSCTL_CONFIG_FILE}\"\n    echo \"${SYSCTL_CONTENT}\" | base64 -d > \"${SYSCTL_CONFIG_FILE}\"\n    retrycmd_if_failure 24 5 25 sysctl --system\n}\n\nensureK8sControlPlane() {\n    if $REBOOTREQUIRED || [ \"$NO_OUTBOUND\" = \"true\" ]; then\n        return\n    fi\n    retrycmd_if_failure 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit $ERR_K8S_RUNNING_TIMEOUT\n}\n\ncreateKubeManifestDir() {\n    KUBEMANIFESTDIR=/etc/kubernetes/manifests\n    mkdir -p $KUBEMANIFESTDIR\n}\n\nwriteKubeConfig() {\n    KUBECONFIGDIR=/home/$ADMINUSER/.kube\n    KUBECONFIGFILE=$KUBECONFIGDIR/config\n    mkdir -p $KUBECONFIGDIR\n    touch $KUBECONFIGFILE\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGDIR\n    chown $ADMINUSER:$ADMINUSER $KUBECONFIGFILE\n    chmod 700 $KUBECONFIGDIR\n    chmod 600 $KUBECONFIGFILE\n    set +x\n    echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $KUBECONFIG_SERVER\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" > $KUBECONFIGFILE\n    set -x\n}\n\nconfigClusterAutoscalerAddon() {\n    CLUSTER_AUTOSCALER_ADDON_FILE=/etc/kubernetes/addons/cluster-autoscaler-deployment.yaml\n    sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n    sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $CLUSTER_AUTOSCALER_ADDON_FILE\n}\n\nconfigACIConnectorAddon() {\n    ACI_CONNECTOR_CREDENTIALS=$(printf \"{\\\"clientId\\\": \\\"%s\\\", \\\"clientSecret\\\": \\\"%s\\\", \\\"tenantId\\\": \\\"%s\\\", \\\"subscriptionId\\\": \\\"%s\\\", \\\"activeDirectoryEndpointUrl\\\": \\\"https://login.microsoftonline.com\\\",\\\"resourceManagerEndpointUrl\\\": \\\"https://management.azure.com/\\\", \\\"activeDirectoryGraphResourceId\\\": \\\"https://graph.windows.net/\\\", \\\"sqlManagementEndpointUrl\\\": \\\"https://management.core.windows.net:8443/\\\", \\\"galleryEndpointUrl\\\": \\\"https://gallery.azure.com/\\\", \\\"managementEndpointUrl\\\": \\\"https://management.core.windows.net/\\\"}\" \"$SERVICE_PRINCIPAL_CLIENT_ID\" \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" \"$TENANT_ID\" \"$SUBSCRIPTION_ID\" | base64 -w 0)\n\n    openssl req -newkey rsa:4096 -new -nodes -x509 -days 3650 -keyout /etc/kubernetes/certs/aci-connector-key.pem -out /etc/kubernetes/certs/aci-connector-cert.pem -subj \"/C=US/ST=CA/L=virtualkubelet/O=virtualkubelet/OU=virtualkubelet/CN=virtualkubelet\"\n    ACI_CONNECTOR_KEY=$(base64 /etc/kubernetes/certs/aci-connector-key.pem -w0)\n    ACI_CONNECTOR_CERT=$(base64 /etc/kubernetes/certs/aci-connector-cert.pem -w0)\n\n    ACI_CONNECTOR_ADDON_FILE=/etc/kubernetes/addons/aci-connector-deployment.yaml\n    sed -i \"s|<creds>|$ACI_CONNECTOR_CREDENTIALS|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<rgName>|$RESOURCE_GROUP|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<cert>|$ACI_CONNECTOR_CERT|g\" $ACI_CONNECTOR_ADDON_FILE\n    sed -i \"s|<key>|$ACI_CONNECTOR_KEY|g\" $ACI_CONNECTOR_ADDON_FILE\n}\n\nconfigAzurePolicyAddon() {\n    AZURE_POLICY_ADDON_FILE=/etc/kubernetes/addons/azure-policy-deployment.yaml\n    sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AZURE_POLICY_ADDON_FILE\n}\n\nconfigGPUDrivers() {\n    # install gpu driver\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        mkdir -p /opt/{actions,gpu}\n        if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n            ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n            retrycmd_if_failure 5 10 600 bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\"\n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            ctr images rm --sync $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        else\n            bash -c \"$DOCKER_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG install\" \n            ret=$?\n            if [[ \"$ret\" != \"0\" ]]; then\n                echo \"Failed to install GPU driver, exiting...\"\n                exit $ERR_GPU_DRIVERS_START_FAIL\n            fi\n            docker rmi $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n        fi\n    elif [[ $OS == $MARINER_OS_NAME ]]; then\n        downloadGPUDrivers\n        installNvidiaContainerRuntime\n    else \n        echo \"os $OS not supported at this time. skipping configGPUDrivers\"\n        exit 1\n    fi\n\n    # validate on host, already done inside container.\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        retrycmd_if_failure 120 5 25 nvidia-modprobe -u -c0 || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n    retrycmd_if_failure 120 5 300 nvidia-smi || exit $ERR_GPU_DRIVERS_START_FAIL\n    retrycmd_if_failure 120 5 25 ldconfig || exit $ERR_GPU_DRIVERS_START_FAIL\n    \n    # reload containerd/dockerd\n    if [[ \"${CONTAINER_RUNTIME}\" == \"containerd\" ]]; then\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP containerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    else\n        retrycmd_if_failure 120 5 25 pkill -SIGHUP dockerd || exit $ERR_GPU_DRIVERS_INSTALL_TIMEOUT\n    fi\n}\n\nvalidateGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    retrycmd_if_failure 24 5 25 nvidia-modprobe -u -c0 && echo \"gpu driver loaded\" || configGPUDrivers || exit $ERR_GPU_DRIVERS_START_FAIL\n    which nvidia-smi\n    if [[ $? == 0 ]]; then\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 nvidia-smi)\n    else\n        SMI_RESULT=$(retrycmd_if_failure 24 5 300 $GPU_DEST/bin/nvidia-smi)\n    fi\n    SMI_STATUS=$?\n    if [[ $SMI_STATUS != 0 ]]; then\n        if [[ $SMI_RESULT == *\"infoROM is corrupted\"* ]]; then\n            exit $ERR_GPU_INFO_ROM_CORRUPTED\n        else\n            exit $ERR_GPU_DRIVERS_START_FAIL\n        fi\n    else\n        echo \"gpu driver working fine\"\n    fi\n}\n\nensureGPUDrivers() {\n    if [[ $(isARM64) == 1 ]]; then\n        # no GPU on ARM64\n        return\n    fi\n\n    if [[ \"${CONFIG_GPU_DRIVER_IF_NEEDED}\" = true ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.configGPUDrivers\" configGPUDrivers\n    else\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.validateGPUDrivers\" validateGPUDrivers\n    fi\n    if [[ $OS == $UBUNTU_OS_NAME ]]; then\n        logs_to_events \"AKS.CSE.ensureGPUDrivers.nvidia-modprobe\" \"systemctlEnableAndStart nvidia-modprobe\" || exit $ERR_GPU_DRIVERS_START_FAIL\n    fi\n}\n\ndisableSSH() {\n    systemctlDisableAndStop ssh || exit $ERR_DISABLE_SSH\n}\n\n#EOF\n", "num_lines": 648}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "{\n    \"containerd\": {\n        \"fileName\": \"moby-containerd_${CONTAINERD_VERSION}+azure-${CONTAINERD_PATCH_VERSION}.deb\",\n        \"downloadLocation\": \"/opt/containerd/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-containerd/${CONTAINERD_VERSION}+azure/${UBUNTU_CODENAME}/linux_${CPU_ARCH}/moby-containerd_${CONTAINERD_VERSION}+azure-ubuntu${UBUNTU_RELEASE}u${CONTAINERD_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"edge\": \"1.7.1-1\"\n    },\n    \"runc\": {\n        \"fileName\": \"moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"downloadLocation\": \"/opt/runc/downloads\",\n        \"downloadURL\": \"https://moby.blob.core.windows.net/moby/moby-runc/${RUNC_VERSION}+azure/bionic/linux_${CPU_ARCH}/moby-runc_${RUNC_VERSION}+azure-ubuntu${RUNC_PATCH_VERSION}_${CPU_ARCH}.deb\",\n        \"versions\": [],\n        \"installed\": {\n            \"default\": \"1.1.7\"\n        }\n    },\n    \"nvidia-container-runtime\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"nvidia-drivers\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    },\n    \"kubernetes\": {\n        \"fileName\": \"kubernetes-node-linux-arch.tar.gz\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\",\n        \"versions\": [\n            \"1.24.9-hotfix.20230612\",\n            \"1.24.10-hotfix.20230612\",\n            \"1.25.5-hotfix.20230612\",\n            \"1.25.6-hotfix.20230612\",\n            \"1.26.0-hotfix.20230612\",\n            \"1.26.3-hotfix.20230612\",\n            \"1.27.1-hotfix.20230612\"\n        ]\n    },\n    \"_template\": {\n        \"fileName\": \"\",\n        \"downloadLocation\": \"\",\n        \"downloadURL\": \"\",\n        \"versions\": []\n    }\n}\n#EOF\n", "num_lines": 52}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "", "num_lines": 1}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# ERR_SYSTEMCTL_ENABLE_FAIL=3 Service could not be enabled by systemctl -- DEPRECATED \nERR_SYSTEMCTL_START_FAIL=4 # Service could not be started or enabled by systemctl\nERR_CLOUD_INIT_TIMEOUT=5 # Timeout waiting for cloud-init runcmd to complete\nERR_FILE_WATCH_TIMEOUT=6 # Timeout waiting for a file\nERR_HOLD_WALINUXAGENT=7 # Unable to place walinuxagent apt package on hold during install\nERR_RELEASE_HOLD_WALINUXAGENT=8 # Unable to release hold on walinuxagent apt package after install\nERR_APT_INSTALL_TIMEOUT=9 # Timeout installing required apt packages\nERR_DOCKER_INSTALL_TIMEOUT=20 # Timeout waiting for docker install\nERR_DOCKER_DOWNLOAD_TIMEOUT=21 # Timout waiting for docker downloads\nERR_DOCKER_KEY_DOWNLOAD_TIMEOUT=22 # Timeout waiting to download docker repo key\nERR_DOCKER_APT_KEY_TIMEOUT=23 # Timeout waiting for docker apt-key\nERR_DOCKER_START_FAIL=24 # Docker could not be started by systemctl\nERR_MOBY_APT_LIST_TIMEOUT=25 # Timeout waiting for moby apt sources\nERR_MS_GPG_KEY_DOWNLOAD_TIMEOUT=26 # Timeout waiting for MS GPG key download\nERR_MOBY_INSTALL_TIMEOUT=27 # Timeout waiting for moby-docker install\nERR_CONTAINERD_INSTALL_TIMEOUT=28 # Timeout waiting for moby-containerd install\nERR_RUNC_INSTALL_TIMEOUT=29 # Timeout waiting for moby-runc install\nERR_K8S_RUNNING_TIMEOUT=30 # Timeout waiting for k8s cluster to be healthy\nERR_K8S_DOWNLOAD_TIMEOUT=31 # Timeout waiting for Kubernetes downloads\nERR_KUBECTL_NOT_FOUND=32 # kubectl client binary not found on local disk\nERR_IMG_DOWNLOAD_TIMEOUT=33 # Timeout waiting for img download\nERR_KUBELET_START_FAIL=34 # kubelet could not be started by systemctl\nERR_DOCKER_IMG_PULL_TIMEOUT=35 # Timeout trying to pull a Docker image\nERR_CONTAINERD_CTR_IMG_PULL_TIMEOUT=36 # Timeout trying to pull a containerd image via cli tool ctr\nERR_CONTAINERD_CRICTL_IMG_PULL_TIMEOUT=37 # Timeout trying to pull a containerd image via cli tool crictl\nERR_CONTAINERD_INSTALL_FILE_NOT_FOUND=38 # Unable to locate containerd debian pkg file\nERR_CNI_DOWNLOAD_TIMEOUT=41 # Timeout waiting for CNI downloads\nERR_MS_PROD_DEB_DOWNLOAD_TIMEOUT=42 # Timeout waiting for https://packages.microsoft.com/config/ubuntu/16.04/packages-microsoft-prod.deb\nERR_MS_PROD_DEB_PKG_ADD_FAIL=43 # Failed to add repo pkg file\n# ERR_FLEXVOLUME_DOWNLOAD_TIMEOUT=44 Failed to add repo pkg file -- DEPRECATED\nERR_SYSTEMD_INSTALL_FAIL=48 # Unable to install required systemd version\nERR_MODPROBE_FAIL=49 # Unable to load a kernel module using modprobe\nERR_OUTBOUND_CONN_FAIL=50 # Unable to establish outbound connection\nERR_K8S_API_SERVER_CONN_FAIL=51 # Unable to establish connection to k8s api serve\nERR_K8S_API_SERVER_DNS_LOOKUP_FAIL=52 # Unable to resolve k8s api server name\nERR_K8S_API_SERVER_AZURE_DNS_LOOKUP_FAIL=53 # Unable to resolve k8s api server name due to Azure DNS issue\nERR_KATA_KEY_DOWNLOAD_TIMEOUT=60 # Timeout waiting to download kata repo key\nERR_KATA_APT_KEY_TIMEOUT=61 # Timeout waiting for kata apt-key\nERR_KATA_INSTALL_TIMEOUT=62 # Timeout waiting for kata install\nERR_VHD_FILE_NOT_FOUND=65 # VHD log file not found on VM built from VHD distro (previously classified as exit code 124)\nERR_CONTAINERD_DOWNLOAD_TIMEOUT=70 # Timeout waiting for containerd downloads\nERR_RUNC_DOWNLOAD_TIMEOUT=71 # Timeout waiting for runc downloads\nERR_CUSTOM_SEARCH_DOMAINS_FAIL=80 # Unable to configure custom search domains\nERR_GPU_DOWNLOAD_TIMEOUT=83 # Timeout waiting for GPU driver download\nERR_GPU_DRIVERS_START_FAIL=84 # nvidia-modprobe could not be started by systemctl\nERR_GPU_DRIVERS_INSTALL_TIMEOUT=85 # Timeout waiting for GPU drivers install\nERR_GPU_DEVICE_PLUGIN_START_FAIL=86 # nvidia device plugin could not be started by systemctl\nERR_GPU_INFO_ROM_CORRUPTED=87 # info ROM corrupted error when executing nvidia-smi\nERR_SGX_DRIVERS_INSTALL_TIMEOUT=90 # Timeout waiting for SGX prereqs to download\nERR_SGX_DRIVERS_START_FAIL=91 # Failed to execute SGX driver binary\nERR_APT_DAILY_TIMEOUT=98 # Timeout waiting for apt daily updates\nERR_APT_UPDATE_TIMEOUT=99 # Timeout waiting for apt-get update to complete\nERR_CSE_PROVISION_SCRIPT_NOT_READY_TIMEOUT=100 # Timeout waiting for cloud-init to place this script on the vm\nERR_APT_DIST_UPGRADE_TIMEOUT=101 # Timeout waiting for apt-get dist-upgrade to complete\nERR_APT_PURGE_FAIL=102 # Error purging distro packages\nERR_SYSCTL_RELOAD=103 # Error reloading sysctl config\nERR_CIS_ASSIGN_ROOT_PW=111 # Error assigning root password in CIS enforcement\nERR_CIS_ASSIGN_FILE_PERMISSION=112 # Error assigning permission to a file in CIS enforcement\nERR_PACKER_COPY_FILE=113 # Error writing a file to disk during VHD CI\nERR_CIS_APPLY_PASSWORD_CONFIG=115 # Error applying CIS-recommended passwd configuration\nERR_SYSTEMD_DOCKER_STOP_FAIL=116 # Error stopping dockerd\nERR_CRICTL_DOWNLOAD_TIMEOUT=117 # Timeout waiting for crictl downloads\nERR_CRICTL_OPERATION_ERROR=118 # Error executing a crictl operation\nERR_CTR_OPERATION_ERROR=119 # Error executing a ctr containerd cli operation\n\n# Azure Stack specific errors\nERR_AZURE_STACK_GET_ARM_TOKEN=120 # Error generating a token to use with Azure Resource Manager\nERR_AZURE_STACK_GET_NETWORK_CONFIGURATION=121 # Error fetching the network configuration for the node\nERR_AZURE_STACK_GET_SUBNET_PREFIX=122 # Error fetching the subnet address prefix for a subnet ID\n\n# Error code 124 is returned when a `timeout` command times out, and --preserve-status is not specified: https://man7.org/linux/man-pages/man1/timeout.1.html\nERR_VHD_BUILD_ERROR=125 # Reserved for VHD CI exit conditions\n\nERR_SWAP_CREATE_FAIL=130 # Error allocating swap file\nERR_SWAP_CREATE_INSUFFICIENT_DISK_SPACE=131 # Error insufficient disk space for swap file creation\n\nERR_TELEPORTD_DOWNLOAD_ERR=150 # Error downloading teleportd binary\nERR_TELEPORTD_INSTALL_ERR=151 # Error installing teleportd binary\n\nERR_HTTP_PROXY_CA_CONVERT=160 # Error converting http proxy ca cert from pem to crt format\nERR_UPDATE_CA_CERTS=161 # Error updating ca certs to include user-provided certificates\n\nERR_DISBALE_IPTABLES=170 # Error disabling iptables service\n\nERR_KRUSTLET_DOWNLOAD_TIMEOUT=171 # Timeout waiting for krustlet downloads\nERR_DISABLE_SSH=172 # Error disabling ssh service\n\nERR_VHD_REBOOT_REQUIRED=200 # Reserved for VHD reboot required exit condition\nERR_NO_PACKAGES_FOUND=201 # Reserved for no security packages found exit condition\n\nERR_SYSTEMCTL_MASK_FAIL=2 # Service could not be masked by systemctl\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nKUBECTL=/usr/local/bin/kubectl\nDOCKER=/usr/bin/docker\n# this will be empty during VHD build\n# but vhd build runs with `set -o nounset`\n# so needs a default value\n# prefer empty string to avoid potential \"it works but did something weird\" scenarios\nexport GPU_DV=\"${GPU_DRIVER_VERSION:=}\"\nexport GPU_DEST=/usr/local/nvidia\nNVIDIA_DOCKER_VERSION=2.8.0-1\nDOCKER_VERSION=1.13.1-1\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.6.0\"\nexport NVIDIA_DRIVER_IMAGE_SHA=\"sha-e8873b\"\nexport NVIDIA_DRIVER_IMAGE_TAG=\"${GPU_DV}-${NVIDIA_DRIVER_IMAGE_SHA}\"\nexport NVIDIA_DRIVER_IMAGE=\"mcr.microsoft.com/aks/aks-gpu\"\nexport CTR_GPU_INSTALL_CMD=\"ctr run --privileged --rm --net-host --with-ns pid:/proc/1/ns/pid --mount type=bind,src=/opt/gpu,dst=/mnt/gpu,options=rbind --mount type=bind,src=/opt/actions,dst=/mnt/actions,options=rbind\"\nexport DOCKER_GPU_INSTALL_CMD=\"docker run --privileged --net=host --pid=host -v /opt/gpu:/mnt/gpu -v /opt/actions:/mnt/actions --rm\"\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\nEVENTS_LOGGING_DIR=/var/log/azure/Microsoft.Azure.Extensions.CustomScript/events/\nCURL_OUTPUT=/tmp/curl_verbose.out\n\nretrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout \"${@}\" && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\nretrycmd_if_failure_no_stats() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@} && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_get_tarball() {\n    tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n    echo \"${tar_retries} retries\"\n    for i in $(seq 1 $tar_retries); do\n        tar -tzf $tarball && break || \\\n        if [ $i -eq $tar_retries ]; then\n            return 1\n        else\n            timeout 60 curl -fsSLv $url -o $tarball 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nretrycmd_curl_file() {\n    curl_retries=$1; wait_sleep=$2; timeout=$3; filepath=$4; url=$5\n    echo \"${curl_retries} retries\"\n    for i in $(seq 1 $curl_retries); do\n        [[ -f $filepath ]] && break\n        if [ $i -eq $curl_retries ]; then\n            return 1\n        else\n            timeout $timeout curl -fsSLv $url -o $filepath 2>&1 | tee $CURL_OUTPUT >/dev/null\n            if [[ $? != 0 ]]; then\n                cat $CURL_OUTPUT\n            fi\n            sleep $wait_sleep\n        fi\n    done\n}\nwait_for_file() {\n    retries=$1; wait_sleep=$2; filepath=$3\n    paved=/opt/azure/cloud-init-files.paved\n    grep -Fq \"${filepath}\" $paved && return 0\n    for i in $(seq 1 $retries); do\n        grep -Fq '#EOF' $filepath && break\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    sed -i \"/#EOF/d\" $filepath\n    echo $filepath >> $paved\n}\nsystemctl_restart() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl restart $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_stop() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl stop $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsystemctl_disable() {\n    retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n    for i in $(seq 1 $retries); do\n        timeout $timeout systemctl daemon-reload\n        timeout $timeout systemctl disable $svcname && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nsysctl_reload() {\n    retries=$1; wait_sleep=$2; timeout=$3\n    for i in $(seq 1 $retries); do\n        timeout $timeout sysctl --system && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n\nsystemctlEnableAndStart() {\n    systemctl_restart 100 5 30 $1\n    RESTART_STATUS=$?\n    systemctl status $1 --no-pager -l > /var/log/azure/$1-status.log\n    if [ $RESTART_STATUS -ne 0 ]; then\n        echo \"$1 could not be started\"\n        return 1\n    fi\n    if ! retrycmd_if_failure 120 5 25 systemctl enable $1; then\n        echo \"$1 could not be enabled by systemctl\"\n        return 1\n    fi\n}\n\nsystemctlDisableAndStop() {\n    if systemctl list-units --full --all | grep -q \"$1.service\"; then\n        systemctl_stop 20 5 25 $1 || echo \"$1 could not be stopped\"\n        systemctl_disable 20 5 25 $1 || echo \"$1 could not be disabled\"\n    fi\n}\n\n# return true if a >= b \nsemverCompare() {\n    VERSION_A=$(echo $1 | cut -d \"+\" -f 1)\n    VERSION_B=$(echo $2 | cut -d \"+\" -f 1)\n    [[ \"${VERSION_A}\" == \"${VERSION_B}\" ]] && return 0\n    sorted=$(echo ${VERSION_A} ${VERSION_B} | tr ' ' '\\n' | sort -V )\n    highestVersion=$(IFS= echo \"${sorted}\" | cut -d$'\\n' -f2)\n    [[ \"${VERSION_A}\" == ${highestVersion} ]] && return 0\n    return 1\n}\ndownloadDebPkgToFile() {\n    PKG_NAME=$1\n    PKG_VERSION=$2\n    PKG_DIRECTORY=$3\n    mkdir -p $PKG_DIRECTORY\n    # shellcheck disable=SC2164\n    pushd ${PKG_DIRECTORY}\n    retrycmd_if_failure 10 5 600 apt-get download ${PKG_NAME}=${PKG_VERSION}*\n    # shellcheck disable=SC2164\n    popd\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    dpkg --configure -a --force-confdef\n    wait_for_apt_locks\n    apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ngetCPUArch() {\n    arch=$(uname -m)\n    if [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n        echo \"arm64\"\n    else\n        echo \"amd64\"\n    fi\n}\nisARM64() {\n    if [[ $(getCPUArch) == \"arm64\" ]]; then\n        echo 1\n    else\n        echo 0\n    fi\n}\n\nlogs_to_events() {\n    # local vars here allow for nested function tracking\n    # installContainerRuntime for example\n    local task=$1; shift\n    local eventsFileName=$(date +%s%3N)\n\n    local startTime=$(date +\"%F %T.%3N\")\n    ${@}\n    ret=$?\n    local endTime=$(date +\"%F %T.%3N\")\n\n    # arg names are defined by GA and all these are required to be correctly read by GA\n    # EventPid, EventTid are required to be int. No use case for them at this point.\n    json_string=$( jq -n \\\n        --arg Timestamp   \"${startTime}\" \\\n        --arg OperationId \"${endTime}\" \\\n        --arg Version     \"1.23\" \\\n        --arg TaskName    \"${task}\" \\\n        --arg EventLevel  \"Informational\" \\\n        --arg Message     \"Completed: ${@}\" \\\n        --arg EventPid    \"0\" \\\n        --arg EventTid    \"0\" \\\n        '{Timestamp: $Timestamp, OperationId: $OperationId, Version: $Version, TaskName: $TaskName, EventLevel: $EventLevel, Message: $Message, EventPid: $EventPid, EventTid: $EventTid}'\n    )\n    echo ${json_string} > ${EVENTS_LOGGING_DIR}${eventsFileName}.json\n\n    # this allows an error from the command at ${@} to be returned and correct code assigned in cse_main\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n}\n\nshould_skip_nvidia_drivers() {\n    set -x\n    body=$(curl -fsSL -H \"Metadata: true\" --noproxy \"*\" \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\")\n    ret=$?\n    if [ \"$ret\" != \"0\" ]; then\n      return $ret\n    fi\n    should_skip=$(echo \"$body\" | jq -e '.compute.tagsList | map(select(.name | test(\"SkipGpuDriverInstall\"; \"i\")))[0].value // \"false\" | test(\"true\"; \"i\")')\n    echo \"$should_skip\" # true or false\n}\n#HELPERSEOF\n", "num_lines": 355}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o pipefail\n\nget-apiserver-ip-from-tags() {\n  tags=$(curl -sSL -H \"Metadata: true\" \"http://169.254.169.254/metadata/instance/compute/tags?api-version=2019-03-11&format=text\")\n  if [ \"$?\" == \"0\" ]; then\n    IFS=\";\" read -ra tagList <<< \"$tags\"\n    for i in \"${tagList[@]}\"; do\n      tagKey=$(cut -d\":\" -f1 <<<$i)\n      tagValue=$(cut -d\":\" -f2 <<<$i)\n      if echo $tagKey | grep -iq \"^aksAPIServerIPAddress$\"; then\n        echo -n \"$tagValue\"\n        return\n      fi\n    done\n  fi\n  echo -n \"\"\n}\n\nSLEEP_SECONDS=15\nclusterFQDN=\"${KUBE_API_SERVER_NAME}\"\nif [[ $clusterFQDN != *.privatelink.* ]]; then\n  echo \"skip reconcile hosts for $clusterFQDN since it's not AKS private cluster\"\n  exit 0\nfi\necho \"clusterFQDN: $clusterFQDN\"\n\nwhile true; do\n  clusterIP=$(get-apiserver-ip-from-tags)\n  if [ -z $clusterIP ]; then\n    sleep \"${SLEEP_SECONDS}\"\n    continue\n  fi\n  if grep -q \"$clusterIP $clusterFQDN\" /etc/hosts; then\n    echo -n \"\"\n  else\n    sudo sed -i \"/$clusterFQDN/d\" /etc/hosts\n    echo \"$clusterIP $clusterFQDN\" | sudo tee -a /etc/hosts > /dev/null\n    echo \"Updated $clusterFQDN to $clusterIP\"\n  fi\n  sleep \"${SLEEP_SECONDS}\"\ndone\n\n#EOF\n", "num_lines": 47}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "[Unit]\nDescription=Reconcile /etc/hosts file for private cluster\n[Service]\nType=simple\nRestart=on-failure\nExecStart=/bin/bash /opt/azure/containers/reconcilePrivateHosts.sh\n[Install]\nWantedBy=multi-user.target", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\nEXPIRATION_IN_HOURS=168\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n\nif [[ \"${MODE}\" != \"windowsVhdMode\" ]]; then\n  exit 0\nfi\n\nif [[ \"${BACKFILL_RESOURCE_DELETION}\" == \"False\" ]]; then\n  exit 0\nfi\n\n# attempt to clean up Windows managed images and SIG image versions created over a week ago in SIG_GALLERY_NAME (cannot be the production gallery)\n# this can be used in PR check-in pipelines together with a set SIG_GALLERY_NAME from which we'd like to free up resources\nif [[ -n \"${AZURE_RESOURCE_GROUP_NAME}\" && \"${SIG_GALLERY_NAME}\" != \"AKSWindows\" ]]; then\n  echo \"Looking for Windows managed images in ${AZURE_RESOURCE_GROUP_NAME} created over ${EXPIRATION_IN_HOURS} hours ago...\"\n\n  managed_image_ids=\"\"\n  sig_version_ids=\"\"\n\n  # delete outdated Windows managed images and associated SIG versions (.tags.os must be \"Windows\")\n  images=$(az image list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline -r '.[] | select(.tags.os == \"Windows\") | select(.tags.now < $dl).name')\n  for image in $images; do\n    managed_image_ids+=\" /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/images/${image}\"\n    sig_version_ids+=\" /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/galleries/${SIG_GALLERY_NAME}/images/${image%-*}/versions/${image#*-}\"\n    echo \"Will delete Windows managed image ${image} and associated SIG version from resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n  done\n\n  if [[ -n \"${managed_image_ids}\" ]]; then\n    echo \"Attempting to delete $(echo ${managed_image_ids} | wc -w) Windows managed images...\"\n    az resource delete --ids ${managed_image_ids} > /dev/null || echo \"Windows managed image deletion was not successful, continuing...\"\n  else\n    echo \"Did not find any Windows managed images eligible for deletion\"\n  fi\n\n  if [[ -n \"${sig_version_ids}\" ]]; then\n    echo \"Attempting to delete $(echo ${sig_version_ids} | wc -w) Windows SIG image versions associated with old managed images...\"\n    az resource delete --ids ${sig_version_ids} > /dev/null || echo \"Windows SIG image version deletion was not successful, continuing...\"\n  else\n    echo \"Did not find any SIG versions associated with old Windows managed images eligible for deletion\"\n  fi\nfi\n\n# attempt to clean up Windows SIG image versions in all galleries except \"AKSWindows\" created over a week ago\nif [[ -n \"${AZURE_RESOURCE_GROUP_NAME}\" ]]; then\n  gallery_list=$(az sig list -g ${AZURE_RESOURCE_GROUP_NAME} | jq -r '.[] | select(.name != \"AKSWindows\") | .name')\n  for gallery in $gallery_list; do\n    if [[ \"${gallery}\" =~ WS2019Gallery* ]]; then\n      create_date=${gallery:13:6}\n    elif [[ \"${gallery}\" =~ WS2019_containerdGallery* ]]; then\n      create_date=${gallery:24:6}\n    elif [[ \"${gallery}\" =~ WS2022_containerdGallery* ]]; then\n      create_date=${gallery:24:6}\n    elif [[ \"${gallery}\" =~ WS2022_containerd_gen2Gallery* ]]; then\n      create_date=${gallery:29:6}\n    else\n      continue\n    fi\n\n    due_date=$(date +%y%m%d -d \"7 days ago\")\n    echo \"create_date is ${create_date}\"\n    echo \"due_date is ${due_date}\"\n    # clean the entire SIG resources if it's one week ago\n    if [[ $create_date < $due_date ]]; then\n      echo \"Finding sig image definitions from gallery ${gallery}\"\n      image_defs=$(az sig image-definition list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${gallery} | jq -r '.[] | select(.osType == \"Windows\").name')\n      for image_definition in $image_defs; do\n          echo \"Finding sig image versions associated with ${image_definition} in gallery ${gallery}\"\n          image_versions=$(az sig image-version list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${gallery} -i ${image_definition} | jq -r '.[].name')\n          for image_version in $image_versions; do\n              echo \"Deleting sig image-version ${image_version} ${image_definition} from gallery ${gallery} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n              az sig image-version delete -e $image_version -i ${image_definition} -r ${gallery} -g ${AZURE_RESOURCE_GROUP_NAME}\n          done\n          image_versions=$(az sig image-version list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${gallery} -i ${image_definition} | jq -r '.[].name')\n          echo \"image versions are $image_versions\"\n          if [[ -z \"${image_versions}\" ]]; then\n            echo \"Deleting sig image-definition ${image_definition} from gallery ${gallery} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n            az sig image-definition delete --gallery-image-definition ${image_definition} -r ${gallery} -g ${AZURE_RESOURCE_GROUP_NAME}\n          fi\n      done\n      image_defs=$(az sig image-definition list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${gallery} | jq -r '.[] | select(.osType == \"Windows\").name')\n\n      if [[ -n $image_defs ]]; then\n        echo $image_defs\n      fi\n      \n      echo \"Deleting gallery ${gallery}\"\n      az sig delete --gallery-name ${gallery} --resource-group ${AZURE_RESOURCE_GROUP_NAME}\n    fi\n  done\nfi\n\n# clean up storage account created over a week ago\nif [[ -n \"${AZURE_RESOURCE_GROUP_NAME}\" ]]; then\n  echo \"Looking for storage accounts in ${AZURE_RESOURCE_GROUP_NAME} created over ${EXPIRATION_IN_HOURS} hours ago...\"\n  echo \"That is, those created before $(date -d@$deadline) As shown below\"\n  az storage account list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline -r '.[] | select(.tags.now < $dl).name'\n  for storage_account in $(az storage account list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline -r '.[] | select(.tags.now < $dl).name'); do\n      if [[ $storage_account = aksimages* ]]; then\n          echo \"Will delete storage account ${storage_account}# from resource group ${AZURE_RESOURCE_GROUP_NAME}...\"\n          az storage account delete --name ${storage_account} -g ${AZURE_RESOURCE_GROUP_NAME} --yes  || echo \"unable to delete storage account ${storage_account}, will continue...\"\n          echo \"Deletion completed\"\n      fi\n  done\nfi\n\n# clean up old packer and vnet resource groups created over a week ago that didn't get cleaned in the building vhd step in case the pipeline fails\nif [[ -n \"${AZURE_RESOURCE_GROUP_NAME}\" ]]; then\n  pkr_groups=$(az group list | jq --arg dl $deadline -r '.[] | select(.name | test(\"pkr-Resource-Group*\")) | select(.tags.now < $dl).name')\n  for pkr_group in $pkr_groups; do\n      echo \"Deleting packer resource group $pkr_group\"\n      az group delete --name ${pkr_group} --yes \n      echo \"Deleted packer resource group $pkr_group\"\n  done\nfi\n", "num_lines": 120}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n# Cleanup packer SSH key and machine ID generated for this boot\nrm -f /root/.ssh/authorized_keys\nrm -f /home/packer/.ssh/authorized_keys\nrm -f /var/log/cloud-init.log /var/log/cloud-init-output.log \nrm -f /etc/machine-id\ntouch /etc/machine-id\nchmod 644 /etc/machine-id", "num_lines": 9}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\nEXPIRATION_IN_HOURS=168\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n\nif [[ -z \"$SIG_GALLERY_NAME\" ]]; then\n  SIG_GALLERY_NAME=\"PackerSigGalleryEastUS\"\nfi\n\nif [[ -n \"$PKR_RG_NAME\" ]]; then\n  #clean up the packer generated resource group\n  id=$(az group show --name ${PKR_RG_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    echo \"Deleting packer resource group ${PKR_RG_NAME}\"\n    az group delete --name ${PKR_RG_NAME} --yes\n  fi\nfi\n\n#clean up managed image\nif [[ -n \"$AZURE_RESOURCE_GROUP_NAME\" && -n \"$IMAGE_NAME\" ]]; then\n  if [[ \"$MODE\" != \"default\" ]]; then\n    id=$(az image show -n ${IMAGE_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n    if [ -n \"$id\" ]; then\n      echo \"deleting managed image ${IMAGE_NAME} under resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n      az image delete -n ${IMAGE_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n    fi\n  fi\nfi\n\n#cleanup imported sig image version\nif [[ -n \"${IMPORTED_IMAGE_NAME}\" ]]; then\n  id=$(az sig image-version show -e 1.0.0 -i ${IMPORTED_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    echo \"Deleting sig image-version 1.0.0 ${IMPORTED_IMAGE_NAME} from gallery ${SIG_GALLERY_NAME} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n    az sig image-version delete -e 1.0.0 -i ${IMPORTED_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n  fi\nfi\n\n#cleanup imported sig image definition\nif [[ -n \"${IMPORTED_IMAGE_NAME}\" ]]; then\n  id=$(az sig image-definition show --gallery-image-definition ${IMPORTED_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    echo \"Deleting sig image-definition ${IMPORTED_IMAGE_NAME} from gallery ${SIG_GALLERY_NAME} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n    az sig image-definition delete --gallery-image-definition ${IMPORTED_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n  fi\nfi\n\n#cleanup imported image\nif [[ -n \"${IMPORTED_IMAGE_NAME}\" ]]; then\n  id=$(az image show -n ${IMPORTED_IMAGE_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    echo \"Deleting managed image ${IMPORTED_IMAGE_NAME} from rg ${AZURE_RESOURCE_GROUP_NAME}\"\n    az image delete -n ${IMPORTED_IMAGE_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n  fi\nfi\n\n#cleanup built sig image if the generated sig is for production only, but not for test purpose.\n#If SIG_FOR_PRODUCTION is set to true, the sig has been converted to VHD before this step.\n#And since we only need to upload the converted VHD to the classic storage account, there's no need to keep the built sig.\nif [[ \"${MODE}\" == \"windowsVhdMode\" && \"$SIG_FOR_PRODUCTION\" == \"True\" ]]; then\n  if [[ -n \"${SIG_IMAGE_NAME}\" ]]; then\n    # Delete sig image version first\n    echo \"SIG_IMAGE_NAME is ${SIG_IMAGE_NAME}, deleting sig image version first\"\n    versions=$(az sig image-version list -i ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq -r '.[].name')\n    for version in $versions; do\n        az sig image-version show -e $version -i ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id\n        echo \"Deleting sig image-version ${version} ${SIG_IMAGE_NAME} from gallery ${SIG_GALLERY_NAME} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n        az sig image-version delete -e $version -i ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n        #double confirm\n        id=$(az sig image-version show -e $version -i ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n        if [ -n \"$id\" ]; then\n            echo \"Deleting sig image-version $version failed\"\n        else \n            echo \"Deletion of sig image-version $version completed\"\n        fi\n    done\n\n    # Delete sig image finally\n    echo \"SIG_IMAGE_NAME is ${SIG_IMAGE_NAME}, deleting sig image definition next\"\n    id=$(az sig image-definition show --gallery-image-definition ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n    if [ -n \"$id\" ]; then\n      echo \"Deleting sig image-definition ${SIG_IMAGE_NAME} from gallery ${SIG_GALLERY_NAME} rg ${AZURE_RESOURCE_GROUP_NAME}\"\n      az sig image-definition delete --gallery-image-definition ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n      #double confirm\n      id=$(az sig image-definition show --gallery-image-definition ${SIG_IMAGE_NAME} -r ${SIG_GALLERY_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n      if [ -n \"$id\" ]; then\n          echo \"Deleting sig image-definition ${SIG_IMAGE_NAME} failed\"\n      else \n          echo \"Deletion of sig image-definition ${SIG_IMAGE_NAME} completed\"\n      fi\n    fi\n\n    # Delete sig image gallery\n    echo \"SIG_GALLERY_NAME is ${SIG_GALLERY_NAME}, deleting sig gallery since sig is no longer needed\"\n    az sig delete --gallery-name ${SIG_GALLERY_NAME} --resource-group ${AZURE_RESOURCE_GROUP_NAME}\n  fi\nfi\n\n#clean up arm64 OS disk snapshot\nif [[ \"${MODE}\" == \"linuxVhdMode\" ]] && [[ ${ARCHITECTURE,,} == \"arm64\" ]] && [ -n \"${ARM64_OS_DISK_SNAPSHOT_NAME}\" ]; then\n  id=$(az snapshot show -n ${ARM64_OS_DISK_SNAPSHOT_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    az snapshot delete -n ${ARM64_OS_DISK_SNAPSHOT_NAME} -g ${AZURE_RESOURCE_GROUP_NAME}\n  fi\nfi\n\n#clean up the temporary storage account\nif [[ -n \"${SA_NAME}\" ]]; then\n  id=$(az storage account show -n ${SA_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} | jq .id)\n  if [ -n \"$id\" ]; then\n    az storage account delete -n ${SA_NAME} -g ${AZURE_RESOURCE_GROUP_NAME} --yes\n  fi\nfi\n\n#delete the SIG version that was created during a dry-run of linuxVhdMode\nif [[ \"${MODE}\" == \"linuxVhdMode\" && \"${DRY_RUN,,}\" == \"true\" ]]; then\n  echo \"running dry-run in mode ${MODE}, attempting to delete output SIG version: ${AZURE_RESOURCE_GROUP_NAME}/${SIG_GALLERY_NAME}/${SIG_IMAGE_NAME}/${CAPTURED_SIG_VERSION}\"\n  id=$(az sig image-definition show -g ${AZURE_RESOURCE_GROUP_NAME} -r ${SIG_GALLERY_NAME} -i ${SIG_IMAGE_NAME} | jq '.id')\n  if [ -n \"$id\" ]; then\n    az sig image-version delete -g ${AZURE_RESOURCE_GROUP_NAME} -r ${SIG_GALLERY_NAME} -i ${SIG_IMAGE_NAME} -e ${CAPTURED_SIG_VERSION}\n  else\n    echo \"specified image-definition ${AZURE_RESOURCE_GROUP_NAME}/${SIG_GALLERY_NAME}/${SIG_IMAGE_NAME} does not exist, will not delete SIG image version\"\n  fi\nfi\n\n# attempt to clean up managed images and associated SIG versions created over a week ago\nif [[ \"${MODE}\" == \"linuxVhdMode\" && -n \"${AZURE_RESOURCE_GROUP_NAME}\" && \"${DRY_RUN,,}\" == \"false\" ]]; then\n  set +x # to avoid blowing up logs\n  echo \"Looking for managed images in ${AZURE_RESOURCE_GROUP_NAME} created over ${EXPIRATION_IN_HOURS} hours ago...\"\n\n  managed_image_ids=\"\"\n  sig_version_ids=\"\"\n  # we limit deletions to 25 managed images to make sure the build doesn't take too long and can finish successfully\n  for image in $(az image list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline '.[] | select(.name | test(\"Ubuntu*|CBLMariner*|V1*|V2*|1804*|2004*|2204*\")) | select(.tags.now < $dl).name' | head -n 25 | tr -d '\\\"' || \"\"); do\n    managed_image_ids=\"${managed_image_ids} /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/images/${image}\"\n    sig_version_ids=\"${sig_version_ids} /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/galleries/${SIG_GALLERY_NAME}/images/${image%-*}/versions/${image#*-}\"\n    echo \"Will delete managed image ${image} and associated SIG version from resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n  done\n\n  if [[ -n \"${managed_image_ids}\" ]]; then\n    echo \"Attempting to delete $(echo ${managed_image_ids} | wc -w) managed images...\"\n    az resource delete --ids ${managed_image_ids} > /dev/null || echo \"managed image deletion was not successful, continuing...\"\n  else\n    echo \"Did not find any managed images eligible for deletion\"\n  fi\n\n  if [[ -n \"${sig_version_ids}\" ]]; then\n    echo \"Attempting to delete $(echo ${sig_version_ids} | wc -w) SIG image versions associated with old managed images...\"\n    az resource delete --ids ${sig_version_ids} > /dev/null || echo \"SIG image version deletion was not successful, continuing...\"\n  else\n    echo \"Did not find any SIG versions associated with old managed images eligible for deletion\"\n  fi\n\n  old_sig_version_ids=\"\"\n  # we limit deletion to 15 SIG image versions per image definition\n  for image_definition in $(az sig image-definition list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${SIG_GALLERY_NAME} | jq '.[] | select(.name | test(\"Ubuntu*|CBLMariner*|V1*|V2*|1804*|2004*|2204*\")).name' | tr -d '\\\"' || \"\"); do\n    for image_version in $(az sig image-version list -g ${AZURE_RESOURCE_GROUP_NAME} -r ${SIG_GALLERY_NAME} -i ${image_definition} | jq --arg dl $deadline '.[] | select(.tags.now < $dl).name' | head -n 15 | tr -d '\\\"' || \"\"); do\n      old_sig_version_ids=\"${old_sig_version_ids} /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/galleries/${SIG_GALLERY_NAME}/images/${image_definition}/versions/${image_version}\"\n    done\n  done\n\n  if [[ -n \"${old_sig_version_ids}\" ]]; then\n    echo \"Attempting to delete $(echo ${old_sig_version_ids} | wc -w) SIG image versions older than ${EXPIRATION_IN_HOURS} hours...\"\n    az resource delete --ids ${old_sig_version_ids} > /dev/null || echo \"SIG image version deletion was not successful, continuing...\"\n  else\n    echo \"Did not find any old SIG versions eligible for deletion\"\n  fi\n  \n  set -x\nfi\n\n# clean up storage accounts created over a week ago\nif [[ -n \"${AZURE_RESOURCE_GROUP_NAME}\" && \"${DRY_RUN}\" == \"False\" ]]; then\n  echo \"Looking for storage accounts in ${AZURE_RESOURCE_GROUP_NAME} created over ${EXPIRATION_IN_HOURS} hours ago...\"\n  echo \"That is, those created before $(date -d@$deadline) As shown below\"\n  az storage account list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline '.[] | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"\n  for storage_account in $(az storage account list -g ${AZURE_RESOURCE_GROUP_NAME} | jq --arg dl $deadline '.[] | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"); do\n      if [[ $storage_account = aksimages* ]]; then\n          echo \"Will delete storage account ${storage_account}# from resource group ${AZURE_RESOURCE_GROUP_NAME}...\"\n          az storage account delete --name ${storage_account} -g ${AZURE_RESOURCE_GROUP_NAME} --yes  || echo \"unable to delete storage account ${storage_account}, will continue...\"\n          echo \"Deletion completed\"\n      fi\n  done\nfi", "num_lines": 187}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"SUBSCRIPTION_ID\"\n    \"AZURE_RESOURCE_GROUP_NAME\"\n    \"AZURE_LOCATION\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nARM64_OS_DISK_SNAPSHOT_NAME=\"$(grep \"arm64_os_disk_snapshot_name\" ./vhdbuilder/packer/settings.json | awk -F':' '{print $2}' | awk -F'\"' '{print $2}')\"\nCAPTURED_SIG_VERSION=\"$(grep \"captured_sig_version\" ./vhdbuilder/packer/settings.json | awk -F':' '{print $2}' | awk -F'\"' '{print $2}')\"\nSIG_IMAGE_NAME=\"$(grep \"sig_image_name\" ./vhdbuilder/packer/settings.json | awk -F':' '{print $2}' | awk -F'\"' '{print $2}')\" && \\\necho \"ManagedImageSharedImageGalleryId: /subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/galleries/PackerSigGalleryEastUS/images/${SIG_IMAGE_NAME}/versions/${CAPTURED_SIG_VERSION}\"\n\ntime_now=$(echo ${CAPTURED_SIG_VERSION} | cut -d '.' -f2)\ndisk_snapshot_id=\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${AZURE_RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/snapshots/${ARM64_OS_DISK_SNAPSHOT_NAME}\"\naz snapshot update --resource-group ${AZURE_RESOURCE_GROUP_NAME} -n ${ARM64_OS_DISK_SNAPSHOT_NAME} --architecture Arm64\naz sig image-version create --location $AZURE_LOCATION --resource-group ${AZURE_RESOURCE_GROUP_NAME} --gallery-name PackerSigGalleryEastUS \\\n     --gallery-image-definition ${SIG_IMAGE_NAME} --gallery-image-version ${CAPTURED_SIG_VERSION} \\\n     --os-snapshot ${disk_snapshot_id} --tags now=${time_now}\n", "num_lines": 28}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"SUBSCRIPTION_ID\"\n    \"RESOURCE_GROUP_NAME\"\n    \"CAPTURED_SIG_VERSION\"\n    \"LOCATION\"\n    \"OS_TYPE\"\n    \"SIG_IMAGE_NAME\"\n)\n\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\n# Default to this hard-coded value for Linux does not pass this environment variable into here\nif [[ -z \"$SIG_GALLERY_NAME\" ]]; then\n  SIG_GALLERY_NAME=\"PackerSigGalleryEastUS\"\nfi\n\necho \"SIG_IMAGE_VERSION before checking and assigning is $SIG_IMAGE_VERSION\"\n# Windows Gen 2: use the passed environment variable $SIG_IMAGE_VERSION\n# Linux Gen 2: assign $CAPTURED_SIG_VERSION to $SIG_IMAGE_VERSION\nif [[ -z \"$SIG_IMAGE_VERSION\" ]]; then\n  SIG_IMAGE_VERSION=${CAPTURED_SIG_VERSION}\nfi\n\n# Use $SIG_IMAGE_VERSION for the sig resource, and $CAPTURED_SIG_VERSION (a random number) for the disk resource\nsig_resource_id=\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/galleries/${SIG_GALLERY_NAME}/images/${SIG_IMAGE_NAME}/versions/${SIG_IMAGE_VERSION}\"\ndisk_resource_id=\"/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/${RESOURCE_GROUP_NAME}/providers/Microsoft.Compute/disks/${CAPTURED_SIG_VERSION}\"\n\necho \"Converting $sig_resource_id to $disk_resource_id\"\nif [[ ${OS_TYPE} == \"Linux\" && ${ENABLE_TRUSTED_LAUNCH} == \"True\" ]]; then\n  az resource create --id $disk_resource_id  --is-full-object --location $LOCATION --properties \"{\\\"location\\\": \\\"$LOCATION\\\", \\\n    \\\"properties\\\": { \\\n      \\\"osType\\\": \\\"$OS_TYPE\\\", \\\n      \\\"securityProfile\\\": { \\\n        \\\"securityType\\\": \\\"TrustedLaunch\\\" \\\n      }, \\\n      \\\"creationData\\\": { \\\n        \\\"createOption\\\": \\\"FromImage\\\", \\\n        \\\"galleryImageReference\\\": { \\\n          \\\"id\\\": \\\"${sig_resource_id}\\\" \\\n        } \\\n      } \\\n    } \\\n  }\"\nelse\n  az resource create --id $disk_resource_id  --is-full-object --location $LOCATION --properties \"{\\\"location\\\": \\\"$LOCATION\\\", \\\n    \\\"properties\\\": { \\\n      \\\"osType\\\": \\\"$OS_TYPE\\\", \\\n      \\\"creationData\\\": { \\\n        \\\"createOption\\\": \\\"FromImage\\\", \\\n        \\\"galleryImageReference\\\": { \\\n          \\\"id\\\": \\\"${sig_resource_id}\\\" \\\n        } \\\n      } \\\n    } \\\n  }\"\nfi\necho \"Converted $sig_resource_id to $disk_resource_id\"\n\n# shellcheck disable=SC2102\nsas=$(az disk grant-access --ids $disk_resource_id --duration-in-seconds 3600 --query [accessSas] -o tsv)\n\necho \"Uploading $disk_resource_id to ${CLASSIC_BLOB}/${CAPTURED_SIG_VERSION}.vhd\"\n\nazcopy-preview copy \"${sas}\" \"${CLASSIC_BLOB}/${CAPTURED_SIG_VERSION}.vhd${CLASSIC_SAS_TOKEN}\" --recursive=true\n\necho \"Uploaded $disk_resource_id to ${CLASSIC_BLOB}/${CAPTURED_SIG_VERSION}.vhd\"\n\naz disk revoke-access --ids $disk_resource_id \n\naz resource delete --ids $disk_resource_id\n\necho \"Deleted $disk_resource_id\"", "num_lines": 81}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"CLASSIC_SA_CONNECTION_STRING\"\n    \"STORAGE_ACCT_BLOB_URL\"\n    \"VHD_NAME\"\n    \"OS_NAME\"\n    \"OFFER_NAME\"\n    \"SKU_NAME\"\n    \"HYPERV_GENERATION\"\n    \"IMAGE_VERSION\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        if [ \"$v\" == \"IMAGE_VERSION\" ]; then\n           IMAGE_VERSION=$(date +%Y%m.%d.0)\n           echo \"$v was not set, set it to ${!v}\"\n        else\n            echo \"$v was not set!\"\n            exit 1\n        fi\n    fi\ndone\n\n# SIG image definition for AMD64/ARM64 has subtle difference, otherwise a SIG version cannot be used to create VM/VMSS of corresponding sku.\n# 'az sig image-definition create' will have a new property (--architecture Arm64|x64) for this soon. We need this in the publishing-info\n# in order that the VHD publish EV2 pipeline can create image-definition with right architecture.\nif [[ ${ARCHITECTURE,,} == \"arm64\" ]]; then\n    IMAGE_ARCH=\"Arm64\"\nelse\n    IMAGE_ARCH=\"x64\"\nfi\n\necho \"generating traditional SAS token with CLASSIC_SA_CONNECTION_STRING...\"\nstart_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"-1 day\")\nexpiry_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"+1 year\")\nif [[ \"${OS_NAME,,}\" != \"windows\" ]]; then\n    [ -z \"${OUTPUT_STORAGE_CONTAINER_NAME}\" ] && echo \"OUTPUT_STORAGE_CONTAINER_NAME should be set...\" && exit 1\n    echo \"storage container name: ${OUTPUT_STORAGE_CONTAINER_NAME}\"\n    # max of 7 day expiration time when using user delegation SAS\n    sas_token=$(az storage container generate-sas --name ${OUTPUT_STORAGE_CONTAINER_NAME} --permissions lr --connection-string ${CLASSIC_SA_CONNECTION_STRING} --start ${start_date} --expiry ${expiry_date} | tr -d '\"')\nelse\n    # we still need to use the original connection string when not using a system-assigned identity on 1ES pools\n    sas_token=$(az storage container generate-sas --name vhds --permissions lr --connection-string ${CLASSIC_SA_CONNECTION_STRING} --start ${start_date} --expiry ${expiry_date} | tr -d '\"')\nfi\n\nif [ \"$sas_token\" == \"\" ]; then\n    echo \"sas_token is empty\"\n    exit 1\nfi\nvhd_url=\"${STORAGE_ACCT_BLOB_URL}/${VHD_NAME}?$sas_token\"\n\necho \"Testing whether the generated sas token works\"\nvhd_size=$(curl -sI $vhd_url | grep -i Content-Length | awk '{print $2}')\nif [ \"$vhd_size\" == \"\" ]; then\n    echo \"The genrated sas token does not work\"\n    exit 1\nfi\necho \"The generated sas token works\"\n\n# Do not log sas token\necho \"COPY ME ---> ${STORAGE_ACCT_BLOB_URL}/${VHD_NAME}?***\"\n\n# Note: The offer_name is the value from OS_SKU (eg. Ubuntu)\ncat <<EOF > vhd-publishing-info.json\n{\n    \"vhd_url\" : \"$vhd_url\",\n    \"os_name\" : \"$OS_NAME\",\n    \"sku_name\" : \"$SKU_NAME\",\n    \"offer_name\" : \"$OFFER_NAME\",\n    \"hyperv_generation\": \"${HYPERV_GENERATION}\",\n    \"image_architecture\": \"${IMAGE_ARCH}\",\n    \"image_version\": \"${IMAGE_VERSION}\"\n}\nEOF\n\n# Do not log sas token\nsed 's/?.*\\\",/?***\\\",/g' < vhd-publishing-info.json\n", "num_lines": 81}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\nset -x\nCDIR=$(dirname \"${BASH_SOURCE}\")\n\nSETTINGS_JSON=\"${SETTINGS_JSON:-./packer/settings.json}\"\nSP_JSON=\"${SP_JSON:-./packer/sp.json}\"\nSUBSCRIPTION_ID=\"${SUBSCRIPTION_ID:-$(az account show -o json --query=\"id\" | tr -d '\"')}\"\nCREATE_TIME=\"$(date +%s)\"\nSTORAGE_ACCOUNT_NAME=\"aksimages${CREATE_TIME}$RANDOM\"\n\n# We use the provided SIG_IMAGE_VERSION if it's instantiated and we're running linuxVhdMode, otherwise we randomly generate one\nif [[ \"${MODE}\" == \"linuxVhdMode\" ]] && [[ -n \"${SIG_IMAGE_VERSION}\" ]]; then\n\tCAPTURED_SIG_VERSION=${SIG_IMAGE_VERSION}\nelse\n\tCAPTURED_SIG_VERSION=\"1.${CREATE_TIME}.$RANDOM\"\nfi\n\nif [ -z \"${POOL_NAME}\" ]; then\n\techo \"POOL_NAME is not set, can't compute vnet_rg_name for packer templates\"\n\texit 1\nfi\n\nvnet_rg_name=\"\"\nif [[ \"${POOL_NAME}\" == *nodesigprod* ]]; then\n\tvnet_rg_name=\"nodesigprod-agent-pool\"\nelse\n\tvnet_rg_name=\"nodesigtest-agent-pool\"\nfi\n\necho \"vnet_rg_name set to: ${vnet_rg_name}\"\n\necho \"CAPTURED_SIG_VERSION set to: ${CAPTURED_SIG_VERSION}\"\n\necho \"Subscription ID: ${SUBSCRIPTION_ID}\"\necho \"Service Principal Path: ${SP_JSON}\"\n\nif [ -a \"${SP_JSON}\" ]; then\n\techo \"Existing credentials file found.\"\n\texit 0\nelif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"Service principal not found! Generating one @ ${SP_JSON}\"\n\taz ad sp create-for-rbac -n aks-images-packer${CREATE_TIME} -o json > ${SP_JSON}\n\tCLIENT_ID=$(jq -r .appId ${SP_JSON})\n\tCLIENT_SECRET=$(jq -r .password ${SP_JSON})\n\tTENANT_ID=$(jq -r .tenant ${SP_JSON})\nfi\n\nrg_id=$(az group show --name $AZURE_RESOURCE_GROUP_NAME) || rg_id=\"\"\nif [ -z \"$rg_id\" ]; then\n\techo \"Creating resource group $AZURE_RESOURCE_GROUP_NAME, location ${AZURE_LOCATION}\"\n\taz group create --name $AZURE_RESOURCE_GROUP_NAME --location ${AZURE_LOCATION}\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n\techo \"creating new storage account ${STORAGE_ACCOUNT_NAME}\"\n\taz storage account create -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME --sku \"Standard_RAGRS\" --tags \"now=${CREATE_TIME}\" --location ${AZURE_LOCATION}\n\techo \"creating new container system\"\n\tkey=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME | jq -r '.[0].value')\n\taz storage container create --name system --account-key=$key --account-name=$STORAGE_ACCOUNT_NAME\nelse\n\techo \"storage account ${STORAGE_ACCOUNT_NAME} already exists.\"\nfi\n\nif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"CLIENT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${CLIENT_SECRET}\" ]; then\n\techo \"CLIENT_SECRET was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${TENANT_ID}\" ]; then\n\techo \"TENANT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\necho \"storage name: ${STORAGE_ACCOUNT_NAME}\"\n\n# If SIG_GALLERY_NAME/SIG_IMAGE_NAME hasnt been provided in linuxVhdMode, use defaults\nif [[ \"${MODE}\" == \"linuxVhdMode\" ]]; then\n\t# Ensure the SIG name\n\tif [[ -z \"${SIG_GALLERY_NAME}\" ]]; then\n\t\tSIG_GALLERY_NAME=\"PackerSigGalleryEastUS\"\n\t\techo \"No input for SIG_GALLERY_NAME was provided, using auto-generated value: ${SIG_GALLERY_NAME}\"\n\telse\n\t\techo \"Using provided SIG_GALLERY_NAME: ${SIG_GALLERY_NAME}\"\n\tfi\n\t\n\t# Ensure the image-definition name\n\tif [[ -z \"${SIG_IMAGE_NAME}\" ]]; then\n\t\tSIG_IMAGE_NAME=${OS_VERSION//./}\n\t\tif [[ \"${OS_SKU}\" == \"Ubuntu\" && \"${IMG_SKU}\" == \"20_04-lts-cvm\" ]]; then\n\t\t\tSIG_IMAGE_NAME=${SIG_IMAGE_NAME}CVM\n\t\tfi\n\n\t\tif [[ \"${IMG_SKU}\" == *\"minimal\"* ]]; then\n\t\t\tSIG_IMAGE_NAME=${SIG_IMAGE_NAME}Minimal\n\t\tfi\n\t\t\n\t\tif [[ \"${OS_SKU}\" == \"CBLMariner\" ]]; then\n\t\t\tSIG_IMAGE_NAME=CBLMariner${SIG_IMAGE_NAME}\n\t\tfi\n\n\t\tif [[ \"${ENABLE_TRUSTED_LAUNCH}\" == \"True\" ]]; then\n\t\t\tSIG_IMAGE_NAME=${SIG_IMAGE_NAME}TL\n\t\tfi\n\n\t\tif [[ \"${HYPERV_GENERATION,,}\" == \"v2\" && (\"${OS_SKU}\" == \"CBLMariner\" || \"${OS_SKU}\" == \"Ubuntu\") ]]; then\n\t\t\tSIG_IMAGE_NAME=${SIG_IMAGE_NAME}Gen2\n\t\tfi\n\t\techo \"No input for SIG_IMAGE_NAME was provided, using auto-generated value: ${SIG_IMAGE_NAME}\"\n\telse\n\t\techo \"Using provided SIG_IMAGE_NAME: ${SIG_IMAGE_NAME}\"\n\tfi\nfi\n\nif [[ ${ARCHITECTURE,,} == \"arm64\" ]]; then\n  ARM64_OS_DISK_SNAPSHOT_NAME=\"arm64_osdisk_snapshot_${CREATE_TIME}_$RANDOM\"\n  SIG_IMAGE_NAME=${SIG_IMAGE_NAME//./}Arm64\n  # Only az published after April 06 2022 supports --architecture for command 'az sig image-definition create...'\n  azversion=$(az version | jq '.\"azure-cli\"' | tr -d '\"')\n  if [[ \"${azversion}\" < \"2.35.0\" ]]; then\n    az upgrade -y\n    az login --service-principal -u ${CLIENT_ID} -p ${CLIENT_SECRET} --tenant ${TENANT_ID}\n    az account set -s ${SUBSCRIPTION_ID}\n  fi\nfi\n\necho \"Using finalized SIG_IMAGE_NAME: ${SIG_IMAGE_NAME}, SIG_GALLERY_NAME: ${SIG_GALLERY_NAME}\"\n\n# If we're building a Linux VHD or we're building a windows VHD in windowsVhdMode, ensure SIG resources\nif [[ \"$MODE\" == \"linuxVhdMode\" || \"$MODE\" == \"windowsVhdMode\" ]]; then\n\techo \"SIG existence checking for $MODE\"\n\tid=$(az sig show --resource-group ${AZURE_RESOURCE_GROUP_NAME} --gallery-name ${SIG_GALLERY_NAME}) || id=\"\"\n\tif [ -z \"$id\" ]; then\n\t\techo \"Creating gallery ${SIG_GALLERY_NAME} in the resource group ${AZURE_RESOURCE_GROUP_NAME} location ${AZURE_LOCATION}\"\n\t\taz sig create --resource-group ${AZURE_RESOURCE_GROUP_NAME} --gallery-name ${SIG_GALLERY_NAME} --location ${AZURE_LOCATION}\n\telse\n\t\techo \"Gallery ${SIG_GALLERY_NAME} exists in the resource group ${AZURE_RESOURCE_GROUP_NAME} location ${AZURE_LOCATION}\"\n\tfi\n\n\tid=$(az sig image-definition show \\\n\t\t--resource-group ${AZURE_RESOURCE_GROUP_NAME} \\\n\t\t--gallery-name ${SIG_GALLERY_NAME} \\\n\t\t--gallery-image-definition ${SIG_IMAGE_NAME}) || id=\"\"\n\tif [ -z \"$id\" ]; then\n\t\techo \"Creating image definition ${SIG_IMAGE_NAME} in gallery ${SIG_GALLERY_NAME} resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n\t\tTARGET_COMMAND_STRING=\"\"\n\t\tif [[ ${ARCHITECTURE,,} == \"arm64\" ]]; then\n\t\t\tTARGET_COMMAND_STRING+=\"--architecture Arm64\"\n\t\telif [[ ${IMG_SKU} == \"20_04-lts-cvm\" ]]; then\n\t\t\tTARGET_COMMAND_STRING+=\"--features SecurityType=ConfidentialVMSupported\"\n\t\telif [[ ${ENABLE_TRUSTED_LAUNCH} == \"True\" ]]; then\n\t\t\tTARGET_COMMAND_STRING+=\"--features SecurityType=TrustedLaunch\"\n\t\tfi\n\n\t\taz sig image-definition create \\\n\t\t\t--resource-group ${AZURE_RESOURCE_GROUP_NAME} \\\n\t\t\t--gallery-name ${SIG_GALLERY_NAME} \\\n\t\t\t--gallery-image-definition ${SIG_IMAGE_NAME} \\\n\t\t\t--publisher microsoft-aks \\\n\t\t\t--offer ${SIG_GALLERY_NAME} \\\n\t\t\t--sku ${SIG_IMAGE_NAME} \\\n\t\t\t--os-type ${OS_TYPE} \\\n\t\t\t--hyper-v-generation ${HYPERV_GENERATION} \\\n\t\t\t--location ${AZURE_LOCATION} \\\n\t\t\t${TARGET_COMMAND_STRING}\n\telse\n\t\techo \"Image definition ${SIG_IMAGE_NAME} existing in gallery ${SIG_GALLERY_NAME} resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n\tfi\nelse\n\techo \"Skipping SIG check for $MODE, os-type: ${OS_TYPE}\"\nfi\n\n# considerations to also add the windows support here instead of an extra script to initialize windows variables:\n# 1. we can demonstrate the whole user defined parameters all at once\n# 2. help us keep in mind that changes of these variables will influence both windows and linux VHD building\n\n# windows image sku and windows image version are recorded in code instead of pipeline variables\n# because a pr gives a better chance to take a review of the version changes.\nWINDOWS_IMAGE_PUBLISHER=\"MicrosoftWindowsServer\"\nWINDOWS_IMAGE_OFFER=\"WindowsServer\"\nWINDOWS_IMAGE_SKU=\"\"\nWINDOWS_IMAGE_VERSION=\"\"\nWINDOWS_IMAGE_URL=\"\"\nwindows_servercore_image_url=\"\"\nwindows_nanoserver_image_url=\"\"\n# shellcheck disable=SC2236\nif [ \"$OS_TYPE\" == \"Windows\" ]; then\n\timported_windows_image_name=\"\"\n\tsource $CDIR/windows-image.env\n\n\techo \"Set the base image sku and version from windows-image.env\"\n\tcase \"${WINDOWS_SKU}\" in\n\t\"2019\")\n\t\tWINDOWS_IMAGE_SKU=$WINDOWS_2019_BASE_IMAGE_SKU\n\t\tWINDOWS_IMAGE_VERSION=$WINDOWS_2019_BASE_IMAGE_VERSION\n\t\timported_windows_image_name=\"windows-2019-imported-${CREATE_TIME}-${RANDOM}\"\n\n\t\techo \"Set OS disk size\"\n\t\tif [ -n \"${WINDOWS_2019_OS_DISK_SIZE_GB}\" ]; then\n\t\t\techo \"Setting os_disk_size_gb to the value in windows-image.env for 2019 Docker: ${WINDOWS_2019_OS_DISK_SIZE_GB}\"\n\t\t\tos_disk_size_gb=${WINDOWS_2019_OS_DISK_SIZE_GB}\n\t\tfi\n\t\t;;\n\t\"2019-containerd\")\n\t\tWINDOWS_IMAGE_SKU=$WINDOWS_2019_BASE_IMAGE_SKU\n\t\tWINDOWS_IMAGE_VERSION=$WINDOWS_2019_BASE_IMAGE_VERSION\n\t\timported_windows_image_name=\"windows-2019-containerd-imported-${CREATE_TIME}-${RANDOM}\"\n\n\t\techo \"Set OS disk size\"\n\t\tif [ -n \"${WINDOWS_2019_CONTAINERD_OS_DISK_SIZE_GB}\" ]; then\n\t\t\techo \"Setting os_disk_size_gb to the value in windows-image.env for 2019 Containerd: ${WINDOWS_2019_CONTAINERD_OS_DISK_SIZE_GB}\"\n\t\t\tos_disk_size_gb=${WINDOWS_2019_CONTAINERD_OS_DISK_SIZE_GB}\n\t\tfi\n\t\t;;\n\t\"2022-containerd\" | \"2022-containerd-gen2\")\n\t\tWINDOWS_IMAGE_SKU=$WINDOWS_2022_BASE_IMAGE_SKU\n\t\tWINDOWS_IMAGE_VERSION=$WINDOWS_2022_BASE_IMAGE_VERSION\n\t\timported_windows_image_name=\"windows-2022-containerd-imported-${CREATE_TIME}-${RANDOM}\"\n\n\t\techo \"Set OS disk size\"\n\t\tif [ -n \"${WINDOWS_2022_CONTAINERD_OS_DISK_SIZE_GB}\" ]; then\n\t\t\techo \"Setting os_disk_size_gb to the value in windows-image.env for 2022 Containerd: ${WINDOWS_2022_CONTAINERD_OS_DISK_SIZE_GB}\"\n\t\t\tos_disk_size_gb=${WINDOWS_2022_CONTAINERD_OS_DISK_SIZE_GB}\n\t\tfi\n\t\t# Default: read from the official MCR image\n\t\tif [[ $HYPERV_GENERATION == \"V2\" ]]; then\n\t\t\tWINDOWS_IMAGE_SKU=$WINDOWS_2022_GEN2_BASE_IMAGE_SKU\n\t\t\tWINDOWS_IMAGE_VERSION=$WINDOWS_2022_GEN2_BASE_IMAGE_VERSION\n\t\tfi\n\t\t;;\n\t*)\n\t\techo \"unsupported windows sku: ${WINDOWS_SKU}\"\n\t\texit 1\n\t\t;;\n\tesac\n\n\t# Create the sig image from the official images defined in windows-image.env by default\n\twindows_sigmode_source_subscription_id=\"\"\n\twindows_sigmode_source_resource_group_name=\"\"\n\twindows_sigmode_source_gallery_name=\"\"\n\twindows_sigmode_source_image_name=\"\"\n\twindows_sigmode_source_image_version=\"\"\n\n\t# default: build VHD images from a marketplace base image\n\tIMPORTED_IMAGE_NAME=$imported_windows_image_name\n\tIMPORTED_IMAGE_URL=\"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/system/$IMPORTED_IMAGE_NAME.vhd\"\n\n\t# build from a pre-supplied VHD blob a.k.a. external raw VHD\n\tif [ -n \"${WINDOWS_BASE_IMAGE_URL}\" ]; then\n\t\techo \"WINDOWS_BASE_IMAGE_URL is set in pipeline variables\"\n\n\t\tWINDOWS_IMAGE_URL=${IMPORTED_IMAGE_URL}\n\n\t\techo \"Generating sas token to copy Windows base image\"\n\t\texpiry_date=$(date -u -d \"20 minutes\" '+%Y-%m-%dT%H:%MZ')\n\t\techo \"Copy Windows base image to ${WINDOWS_IMAGE_URL}\"\n\t\tset +x\n\t\tsas_token=$(az storage account generate-sas --account-name ${STORAGE_ACCOUNT_NAME} --permissions cw --account-key \"$key\" --resource-types o --services b --expiry ${expiry_date} | tr -d '\"')\n\t\tazcopy-preview copy \"${WINDOWS_BASE_IMAGE_URL}\" \"${WINDOWS_IMAGE_URL}?${sas_token}\"\n\t\tset -x\n\t\t# https://www.packer.io/plugins/builders/azure/arm#image_url\n\t\t# WINDOWS_IMAGE_URL to a custom VHD to use for your base image. If this value is set, image_publisher, image_offer, image_sku, or image_version should not be set.\n\t\tWINDOWS_IMAGE_PUBLISHER=\"\"\n\t\tWINDOWS_IMAGE_OFFER=\"\"\n\t\tWINDOWS_IMAGE_SKU=\"\"\n\t\tWINDOWS_IMAGE_VERSION=\"\"\n\n\t\t# Need to use a sig image to create the build VM\n\t\t# create a new managed image $IMPORTED_IMAGE_NAME from os disk source $IMPORTED_IMAGE_URL\n\t\techo \"Creating new image for imported vhd ${IMPORTED_IMAGE_URL}\"\n\t\taz image create \\\n\t\t\t--resource-group $AZURE_RESOURCE_GROUP_NAME \\\n\t\t\t--name $IMPORTED_IMAGE_NAME \\\n\t\t\t--source ${IMPORTED_IMAGE_URL} \\\n\t\t\t--location $AZURE_LOCATION \\\n\t\t\t--hyper-v-generation $HYPERV_GENERATION \\\n\t\t\t--os-type ${OS_TYPE}\n\n\t\t# create a gallery image definition $IMPORTED_IMAGE_NAME\t\n\t\techo \"Creating new image-definition for imported image ${IMPORTED_IMAGE_NAME}\"\n\t\t# Need to specifiy hyper-v-generation to support Gen 2\n\t\taz sig image-definition create \\\n\t\t\t--resource-group $AZURE_RESOURCE_GROUP_NAME \\\n\t\t\t--gallery-name $SIG_GALLERY_NAME \\\n\t\t\t--gallery-image-definition $IMPORTED_IMAGE_NAME \\\n\t\t\t--location $AZURE_LOCATION \\\n\t\t\t--hyper-v-generation $HYPERV_GENERATION \\\n\t\t\t--os-type ${OS_TYPE} \\\n\t\t\t--publisher microsoft-aks \\\n\t\t\t--sku ${WINDOWS_SKU} \\\n\t\t\t--offer $IMPORTED_IMAGE_NAME \\\n\t\t\t--os-state generalized \\\n\t\t\t--description \"Imported image for AKS Packer build\"\n\t\t\t\n\t\t# create a image version defaulting to 1.0.0 for $IMPORTED_IMAGE_NAME\n\t\techo \"Creating new image-version for imported image ${IMPORTED_IMAGE_NAME}\"\n\t\taz sig image-version create \\\n\t\t\t--location $AZURE_LOCATION \\\n\t\t\t--resource-group $AZURE_RESOURCE_GROUP_NAME \\\n\t\t\t--gallery-name $SIG_GALLERY_NAME \\\n\t\t\t--gallery-image-definition $IMPORTED_IMAGE_NAME \\\n\t\t\t--gallery-image-version 1.0.0 \\\n\t\t\t--managed-image $IMPORTED_IMAGE_NAME\n\n\t\t# Use imported sig image to create the build VM\n\t\tWINDOWS_IMAGE_URL=\"\"\n\t\twindows_sigmode_source_subscription_id=$SUBSCRIPTION_ID\n\t\twindows_sigmode_source_resource_group_name=$AZURE_RESOURCE_GROUP_NAME\n\t\twindows_sigmode_source_gallery_name=$SIG_GALLERY_NAME\n\t\twindows_sigmode_source_image_name=$IMPORTED_IMAGE_NAME\n\t\twindows_sigmode_source_image_version=\"1.0.0\"\n\tfi\n\n\t# Set nanoserver image url if the pipeline variable is set\n\tif [ -n \"${WINDOWS_NANO_IMAGE_URL}\" ]; then\n\t\techo \"WINDOWS_NANO_IMAGE_URL is set in pipeline variables\"\n\t\twindows_nanoserver_image_url=\"${WINDOWS_NANO_IMAGE_URL}\"\n\tfi\n\n\t# Set servercore image url if the pipeline variable is set\n\tif [ -n \"${WINDOWS_CORE_IMAGE_URL}\" ]; then\n\t\techo \"WINDOWS_CORE_IMAGE_URL is set in pipeline variables\"\n\t\twindows_servercore_image_url=\"${WINDOWS_CORE_IMAGE_URL}\"\n\tfi\nfi\n\ncat <<EOF > vhdbuilder/packer/settings.json\n{\n  \"subscription_id\":  \"${SUBSCRIPTION_ID}\",\n  \"client_id\": \"${CLIENT_ID}\",\n  \"client_secret\": \"${CLIENT_SECRET}\",\n  \"tenant_id\":      \"${TENANT_ID}\",\n  \"resource_group_name\": \"${AZURE_RESOURCE_GROUP_NAME}\",\n  \"location\": \"${AZURE_LOCATION}\",\n  \"storage_account_name\": \"${STORAGE_ACCOUNT_NAME}\",\n  \"vm_size\": \"${AZURE_VM_SIZE}\",\n  \"create_time\": \"${CREATE_TIME}\",\n  \"windows_image_publisher\": \"${WINDOWS_IMAGE_PUBLISHER}\",\n  \"windows_image_offer\": \"${WINDOWS_IMAGE_OFFER}\",\n  \"windows_image_sku\": \"${WINDOWS_IMAGE_SKU}\",\n  \"windows_image_version\": \"${WINDOWS_IMAGE_VERSION}\",\n  \"windows_image_url\": \"${WINDOWS_IMAGE_URL}\",\n  \"imported_image_name\": \"${IMPORTED_IMAGE_NAME}\",\n  \"sig_image_name\":  \"${SIG_IMAGE_NAME}\",\n  \"sig_gallery_name\": \"${SIG_GALLERY_NAME}\",\n  \"arm64_os_disk_snapshot_name\": \"${ARM64_OS_DISK_SNAPSHOT_NAME}\",\n  \"captured_sig_version\": \"${CAPTURED_SIG_VERSION}\",\n  \"os_disk_size_gb\": \"${os_disk_size_gb}\",\n  \"nano_image_url\": \"${windows_nanoserver_image_url}\",\n  \"core_image_url\": \"${windows_servercore_image_url}\",\n  \"windows_sigmode_source_subscription_id\": \"${windows_sigmode_source_subscription_id}\",\n  \"windows_sigmode_source_resource_group_name\": \"${windows_sigmode_source_resource_group_name}\",\n  \"windows_sigmode_source_gallery_name\": \"${windows_sigmode_source_gallery_name}\",\n  \"windows_sigmode_source_image_name\": \"${windows_sigmode_source_image_name}\",\n  \"windows_sigmode_source_image_version\": \"${windows_sigmode_source_image_version}\",\n  \"vnet_name\": \"nodesig-pool-vnet\",\n  \"subnet_name\": \"packer\",\n  \"vnet_resource_group_name\": \"${vnet_rg_name}\"\n}\nEOF\n\ncat vhdbuilder/packer/settings.json", "num_lines": 367}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nUBUNTU_OS_NAME=\"UBUNTU\"\nMARINER_OS_NAME=\"MARINER\"\nTHIS_DIR=\"$(cd \"$(dirname ${BASH_SOURCE[0]})\" && pwd)\"\n\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_installs_distro.sh\nsource /home/packer/provision_source.sh\nsource /home/packer/provision_source_distro.sh\nsource /home/packer/tool_installs.sh\nsource /home/packer/tool_installs_distro.sh\n\nCPU_ARCH=$(getCPUArch)  #amd64 or arm64\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nCOMPONENTS_FILEPATH=/opt/azure/components.json\n\necho \"\"\necho \"Components downloaded in this VHD build (some of the below components might get deleted during cluster provisioning if they are not needed):\" >> ${VHD_LOGS_FILEPATH}\n\n# fix grub issue with cvm by reinstalling before other deps\n# other VHDs use grub-pc, not grub-efi\nif [[ \"${UBUNTU_RELEASE}\" == \"20.04\" ]] && [[ \"$IMG_SKU\" == \"20_04-lts-cvm\" ]]; then\n  apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT \n  wait_for_apt_locks\n  apt_get_install 30 1 600 grub-efi || exit 1\nfi\n\nif [[ \"$OS\" == \"$UBUNTU_OS_NAME\" ]]; then\n  # disable and mask all UU timers/services\n  # save some background io/latency\n  systemctl mask apt-daily.service apt-daily-upgrade.service || exit 1\n  systemctl disable apt-daily.service apt-daily-upgrade.service || exit 1\n  systemctl disable apt-daily.timer apt-daily-upgrade.timer || exit 1\n\n  tee /etc/apt/apt.conf.d/99periodic > /dev/null <<EOF || exit 1\nAPT::Periodic::Update-Package-Lists \"0\";\nAPT::Periodic::Download-Upgradeable-Packages \"0\";\nAPT::Periodic::AutocleanInterval \"0\";\nAPT::Periodic::Unattended-Upgrade \"0\";\nEOF\nfi\n\n# If the IMG_SKU does not contain \"minimal\", installDeps normally\nif [[ \"$IMG_SKU\" != *\"minimal\"* ]]; then\n  installDeps\nelse\n  # The following packages are required for an Ubuntu Minimal Image to build and successfully run CSE\n  # jq - for manipulation JSON data\n  # iptables - required to run containerd\n  # netcat - network comms with API server\n  # dnsutils - contains nslookup, to query API server DNS\n  required_pkg_list=(jq iptables netcat dnsutils)\n  for apt_package in ${required_pkg_list[*]}; do\n      if ! apt_get_install 30 1 600 $apt_package; then\n          journalctl --no-pager -u $apt_package\n          exit $ERR_APT_INSTALL_TIMEOUT\n      fi\n  done\nfi\n\ntee -a /etc/systemd/journald.conf > /dev/null <<'EOF'\nStorage=persistent\nSystemMaxUse=1G\nRuntimeMaxUse=1G\nForwardToSyslog=yes\nEOF\n\nif [[ ${CONTAINER_RUNTIME:-\"\"} != \"containerd\" ]]; then\n  echo \"Unsupported container runtime. Only containerd is supported for new VHD builds.\"\n  exit 1\nfi\n\nif [[ $(isARM64) == 1 ]]; then\n  if [[ ${ENABLE_FIPS,,} == \"true\" ]]; then\n    echo \"No FIPS support on arm64, exiting...\"\n    exit 1\n  fi\n  if [[ ${HYPERV_GENERATION,,} == \"v1\" ]]; then\n    echo \"No arm64 support on V1 VM, exiting...\"\n    exit 1\n  fi\n\n  if [[ ${CONTAINER_RUNTIME,,} == \"docker\" ]]; then\n    echo \"No dockerd is allowed on arm64 vhd, exiting...\"\n    exit 1\n  fi\nfi\n\nif [[ \"${UBUNTU_RELEASE}\" == \"18.04\" || \"${UBUNTU_RELEASE}\" == \"20.04\" || \"${UBUNTU_RELEASE}\" == \"22.04\" ]]; then\n  overrideNetworkConfig || exit 1\n  disableNtpAndTimesyncdInstallChrony || exit 1\nfi\n\nCONTAINERD_SERVICE_DIR=\"/etc/systemd/system/containerd.service.d\"\nmkdir -p \"${CONTAINERD_SERVICE_DIR}\"\ntee \"${CONTAINERD_SERVICE_DIR}/exec_start.conf\" > /dev/null <<EOF\n[Service]\nExecStartPost=/sbin/iptables -P FORWARD ACCEPT\nEOF\n\ntee \"/etc/sysctl.d/99-force-bridge-forward.conf\" > /dev/null <<EOF \nnet.ipv4.ip_forward = 1\nnet.ipv4.conf.all.forwarding = 1\nnet.ipv6.conf.all.forwarding = 1\nnet.bridge.bridge-nf-call-iptables = 1\nEOF\n\nif [[ $OS == $MARINER_OS_NAME ]]; then\n    disableSystemdResolvedCache\n    disableSystemdIptables || exit 1\n    setMarinerNetworkdConfig\n    fixCBLMarinerPermissions\n    addMarinerNvidiaRepo\n    overrideNetworkConfig || exit 1\n    if grep -q \"kata\" <<< \"$FEATURE_FLAGS\"; then\n      enableMarinerKata\n    fi\n    disableTimesyncd\n    disableDNFAutomatic\n    enableCheckRestart\n    activateNfConntrack\nfi\n\ndownloadContainerdWasmShims\necho \"  - containerd-wasm-shims ${CONTAINERD_WASM_VERSIONS}\" >> ${VHD_LOGS_FILEPATH}\n\necho \"VHD will be built with containerd as the container runtime\"\nupdateAptWithMicrosoftPkg\ncontainerd_manifest=\"$(jq .containerd manifest.json)\" || exit $?\ninstalled_version=\"$(echo ${containerd_manifest} | jq -r '.edge')\"\ncontainerd_version=\"$(echo \"$installed_version\" | cut -d- -f1)\"\ncontainerd_patch_version=\"$(echo \"$installed_version\" | cut -d- -f2)\"\ninstallStandaloneContainerd ${containerd_version} ${containerd_patch_version}\necho \"  - [installed] containerd v${containerd_version}-${containerd_patch_version}\" >> ${VHD_LOGS_FILEPATH}\n\nDOWNLOAD_FILES=$(jq \".DownloadFiles\" $COMPONENTS_FILEPATH | jq .[] --monochrome-output --compact-output)\nfor componentToDownload in ${DOWNLOAD_FILES[*]}; do\n  fileName=$(echo \"${componentToDownload}\" | jq .fileName -r)\n  if [ $fileName == \"crictl-v*-linux-amd64.tar.gz\" ]; then\n    CRICTL_VERSIONS_STR=$(echo \"${componentToDownload}\" | jq .versions -r)\n    CRICTL_VERSIONS=\"\"\n    if [[ ${CRICTL_VERSIONS_STR} != null ]]; then\n      CRICTL_VERSIONS=$(echo \"${CRICTL_VERSIONS_STR}\" | jq -r \".[]\")\n      CRICTL_VERSIONS=$(echo -e \"$CRICTL_VERSIONS\" | tail -n 2 | head -n 1 | tr -d ' ')\n    fi\n    break\n  fi\ndone\necho $CRICTL_VERSIONS\n\nfor CRICTL_VERSION in ${CRICTL_VERSIONS}; do\n  downloadCrictl ${CRICTL_VERSION}\n  echo \"  - crictl version ${CRICTL_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKUBERNETES_VERSION=$CRICTL_VERSIONS installCrictl || exit $ERR_CRICTL_DOWNLOAD_TIMEOUT\n\n# k8s will use images in the k8s.io namespaces - create it\nctr namespace create k8s.io\ncliTool=\"ctr\"\n\n# also pre-download Teleportd plugin for containerd\ndownloadTeleportdPlugin ${TELEPORTD_PLUGIN_DOWNLOAD_URL} \"0.8.0\"\n\nINSTALLED_RUNC_VERSION=$(runc --version | head -n1 | sed 's/runc version //')\necho \"  - runc version ${INSTALLED_RUNC_VERSION}\" >> ${VHD_LOGS_FILEPATH}\n\nif [[ $OS == $UBUNTU_OS_NAME && $(isARM64) != 1 ]]; then  # no ARM64 SKU with GPU now\n  gpu_action=\"copy\"\n  export NVIDIA_DRIVER_IMAGE_TAG=\"cuda-525.85.12-${NVIDIA_DRIVER_IMAGE_SHA}\"\n\n  mkdir -p /opt/{actions,gpu}\n  ctr image pull $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG\n  if grep -q \"fullgpu\" <<< \"$FEATURE_FLAGS\"; then\n    bash -c \"$CTR_GPU_INSTALL_CMD $NVIDIA_DRIVER_IMAGE:$NVIDIA_DRIVER_IMAGE_TAG gpuinstall /entrypoint.sh install\" \n    ret=$?\n    if [[ \"$ret\" != \"0\" ]]; then\n      echo \"Failed to install GPU driver, exiting...\"\n      exit $ret\n    fi\n  fi    \nfi\n\nsystemctlEnableAndStart containerd-monitor.timer || exit $ERR_SYSTEMCTL_START_FAIL\n\nls -ltr /opt/gpu/* >> ${VHD_LOGS_FILEPATH}\n\ninstallBpftrace\necho \"  - $(bpftrace --version)\" >> ${VHD_LOGS_FILEPATH}\n\ncat << EOF >> ${VHD_LOGS_FILEPATH}\n  - nvidia-driver=${NVIDIA_DRIVER_IMAGE_TAG}\nEOF\n\ninstallBcc\ncat << EOF >> ${VHD_LOGS_FILEPATH}\n  - bcc-tools\n  - libbcc-examples\nEOF\n\necho \"${CONTAINER_RUNTIME} images pre-pulled:\" >> ${VHD_LOGS_FILEPATH}\n\nstring_replace() {\n  echo ${1//\\*/$2}\n}\n\nContainerImages=$(jq \".ContainerImages\" $COMPONENTS_FILEPATH | jq .[] --monochrome-output --compact-output)\nfor imageToBePulled in ${ContainerImages[*]}; do\n  downloadURL=$(echo \"${imageToBePulled}\" | jq .downloadURL -r)\n  amd64OnlyVersionsStr=$(echo \"${imageToBePulled}\" | jq .amd64OnlyVersions -r)\n  multiArchVersionsStr=$(echo \"${imageToBePulled}\" | jq .multiArchVersions -r)\n\n  amd64OnlyVersions=\"\"\n  if [[ ${amd64OnlyVersionsStr} != null ]]; then\n    amd64OnlyVersions=$(echo \"${amd64OnlyVersionsStr}\" | jq -r \".[]\")\n  fi\n  multiArchVersions=\"\"\n  if [[ ${multiArchVersionsStr} != null ]]; then\n    multiArchVersions=$(echo \"${multiArchVersionsStr}\" | jq -r \".[]\")\n  fi\n\n  if [[ $(isARM64) == 1 ]]; then\n    versions=\"${multiArchVersions}\"\n  else\n    versions=\"${amd64OnlyVersions} ${multiArchVersions}\"\n  fi\n\n  for version in ${versions}; do\n    CONTAINER_IMAGE=$(string_replace $downloadURL $version)\n    pullContainerImage ${cliTool} ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n  done\ndone\n\nwatcher=$(jq '.ContainerImages[] | select(.downloadURL | contains(\"aks-node-ca-watcher\"))' $COMPONENTS_FILEPATH)\nwatcherBaseImg=$(echo $watcher | jq -r .downloadURL)\nwatcherVersion=$(echo $watcher | jq -r .multiArchVersions[0])\nwatcherFullImg=${watcherBaseImg//\\*/$watcherVersion}\n\n# this image will never get pulled, the tag must be the same across different SHAs.\n# it will only ever be upgraded via node image changes.\n# we do this because the image is used to bootstrap custom CA trust when MCR egress\n# may be intercepted by an untrusted TLS MITM firewall.\nwatcherStaticImg=${watcherBaseImg//\\*/static}\n\n# can't use cliTool because crictl doesn't support retagging.\nretagContainerImage \"ctr\" ${watcherFullImg} ${watcherStaticImg}\n\n# doing this at vhd allows CSE to be faster with just mv\nunpackAzureCNI() {\n  local URL=$1\n  CNI_TGZ_TMP=${URL##*/}\n  CNI_DIR_TMP=${CNI_TGZ_TMP%.tgz}\n  mkdir \"$CNI_DOWNLOADS_DIR/${CNI_DIR_TMP}\" \n  tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_DOWNLOADS_DIR/$CNI_DIR_TMP\n  rm -rf ${CNI_DOWNLOADS_DIR:?}/${CNI_TGZ_TMP}\n  echo \"  - Ran tar -xzf on the CNI downloaded then rm -rf to clean up\"\n}\n\n#must be both amd64/arm64 images\nVNET_CNI_VERSIONS=\"\n1.5.5\n1.4.43\n\"\n\n\nfor VNET_CNI_VERSION in $VNET_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/azure-cni/v${VNET_CNI_VERSION}/binaries/azure-vnet-cni-linux-${CPU_ARCH}-v${VNET_CNI_VERSION}.tgz\"\n    downloadAzureCNI\n    unpackAzureCNI $VNET_CNI_PLUGINS_URL\n    echo \"  - Azure CNI version ${VNET_CNI_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\n#UNITE swift and overlay versions?\n#Please add new version (>=1.4.13) in this section in order that it can be pulled by both AMD64/ARM64 vhd\nSWIFT_CNI_VERSIONS=\"\n1.5.5\n1.4.43\n\"\n\nfor SWIFT_CNI_VERSION in $SWIFT_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/azure-cni/v${SWIFT_CNI_VERSION}/binaries/azure-vnet-cni-swift-linux-${CPU_ARCH}-v${SWIFT_CNI_VERSION}.tgz\"\n    downloadAzureCNI\n    unpackAzureCNI $VNET_CNI_PLUGINS_URL\n    echo \"  - Azure Swift CNI version ${SWIFT_CNI_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nOVERLAY_CNI_VERSIONS=\"\n1.5.5\n1.4.43\n\"\n\nfor OVERLAY_CNI_VERSION in $OVERLAY_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/azure-cni/v${OVERLAY_CNI_VERSION}/binaries/azure-vnet-cni-overlay-linux-${CPU_ARCH}-v${OVERLAY_CNI_VERSION}.tgz\"\n    downloadAzureCNI\n    unpackAzureCNI $VNET_CNI_PLUGINS_URL\n    echo \"  - Azure Overlay CNI version ${OVERLAY_CNI_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\n\n# After v0.7.6, URI was changed to renamed to https://acs-mirror.azureedge.net/cni-plugins/v*/binaries/cni-plugins-linux-arm64-v*.tgz\nMULTI_ARCH_CNI_PLUGIN_VERSIONS=\"\n1.1.1\n\"\nCNI_PLUGIN_VERSIONS=\"${MULTI_ARCH_CNI_PLUGIN_VERSIONS}\"\n\nfor CNI_PLUGIN_VERSION in $CNI_PLUGIN_VERSIONS; do\n    CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/cni-plugins/v${CNI_PLUGIN_VERSION}/binaries/cni-plugins-linux-${CPU_ARCH}-v${CNI_PLUGIN_VERSION}.tgz\"\n    downloadCNI\n    unpackAzureCNI $CNI_PLUGINS_URL\n    echo \"  - CNI plugin version ${CNI_PLUGIN_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\n# IPv6 nftables rules are only available on Ubuntu or Mariner v2\nif [[ $OS == $UBUNTU_OS_NAME || ( $OS == $MARINER_OS_NAME && $OS_VERSION == \"2.0\" ) ]]; then\n  systemctlEnableAndStart ipv6_nftables || exit 1\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME && $(isARM64) != 1 ]]; then  # no ARM64 SKU with GPU now\nNVIDIA_DEVICE_PLUGIN_VERSIONS=\"\nv0.13.0.7\n\"\nfor NVIDIA_DEVICE_PLUGIN_VERSION in ${NVIDIA_DEVICE_PLUGIN_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/nvidia/k8s-device-plugin:${NVIDIA_DEVICE_PLUGIN_VERSION}\"\n    pullContainerImage ${cliTool} ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\n# GPU device plugin\nif grep -q \"fullgpu\" <<< \"$FEATURE_FLAGS\" && grep -q \"gpudaemon\" <<< \"$FEATURE_FLAGS\"; then\n  kubeletDevicePluginPath=\"/var/lib/kubelet/device-plugins\"\n  mkdir -p $kubeletDevicePluginPath\n  echo \"  - $kubeletDevicePluginPath\" >> ${VHD_LOGS_FILEPATH}\n\n  DEST=\"/usr/local/nvidia/bin\"\n  mkdir -p $DEST\n  ctr --namespace k8s.io run --rm --mount type=bind,src=${DEST},dst=${DEST},options=bind:rw --cwd ${DEST} \"mcr.microsoft.com/oss/nvidia/k8s-device-plugin:v0.13.0.7\" plugingextract /bin/sh -c \"cp /usr/bin/nvidia-device-plugin $DEST\" || exit 1\n  chmod a+x $DEST/nvidia-device-plugin\n  echo \"  - extracted nvidia-device-plugin...\" >> ${VHD_LOGS_FILEPATH}\n  ls -ltr $DEST >> ${VHD_LOGS_FILEPATH}\n\n  systemctlEnableAndStart nvidia-device-plugin || exit 1\nfi\nfi\n\n# this is used by kube-proxy and need to cover previously supported version for VMAS scale up scenario\n# So keeping as many versions as we can - those unsupported version can be removed when we don't have enough space\n# NOTE that we keep multiple files per k8s patch version as kubeproxy version is decided by CCP.\n\n# kube-proxy regular versions >=v1.17.0  hotfixes versions >= 20211009 are 'multi-arch'. All versions in kube-proxy-images.json are 'multi-arch' version now.\n\nKUBE_PROXY_IMAGE_VERSIONS=$(jq -r '.containerdKubeProxyImages.ContainerImages[0].multiArchVersions[]' <\"$THIS_DIR/kube-proxy-images.json\")\n\nfor KUBE_PROXY_IMAGE_VERSION in ${KUBE_PROXY_IMAGE_VERSIONS}; do\n  # use kube-proxy as well\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/kube-proxy:v${KUBE_PROXY_IMAGE_VERSION}\"\n  pullContainerImage ${cliTool} ${CONTAINER_IMAGE}\n  ctr --namespace k8s.io run --rm ${CONTAINER_IMAGE} checkTask /bin/sh -c \"iptables --version\" | grep -v nf_tables && echo \"kube-proxy contains no nf_tables\"\n  \n  # shellcheck disable=SC2181\n  echo \"  - ${CONTAINER_IMAGE}\" >>${VHD_LOGS_FILEPATH}\ndone\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  # remove snapd, which is not used by container stack\n  apt_get_purge 20 30 120 snapd || exit 1\n  apt_get_purge 20 30 120 apache2-utils || exit 1\n\n  apt-get -y autoclean || exit 1\n  apt-get -y autoremove --purge || exit 1\n  apt-get -y clean || exit 1\n  # update message-of-the-day to start after multi-user.target\n  # multi-user.target usually start at the end of the boot sequence\n  sed -i 's/After=network-online.target/After=multi-user.target/g' /lib/systemd/system/motd-news.service\nfi\n\n# kubelet and kubectl\n# need to cover previously supported version for VMAS scale up scenario\n# So keeping as many versions as we can - those unsupported version can be removed when we don't have enough space\n# NOTE that we only keep the latest one per k8s patch version as kubelet/kubectl is decided by VHD version\n# Please do not use the .1 suffix, because that's only for the base image patches\n# regular version >= v1.17.0 or hotfixes >= 20211009 has arm64 binaries. \nKUBE_BINARY_VERSIONS=\"$(jq -r .kubernetes.versions[] manifest.json)\"\n\nfor PATCHED_KUBE_BINARY_VERSION in ${KUBE_BINARY_VERSIONS}; do\n  KUBERNETES_VERSION=$(echo ${PATCHED_KUBE_BINARY_VERSION} | cut -d\"_\" -f1 | cut -d\"-\" -f1 | cut -d\".\" -f1,2,3)\n  extractKubeBinaries $KUBERNETES_VERSION \"https://acs-mirror.azureedge.net/kubernetes/v${PATCHED_KUBE_BINARY_VERSION}/binaries/kubernetes-node-linux-${CPU_ARCH}.tar.gz\"\ndone\n\necho \"install-dependencies step completed successfully\"\n", "num_lines": 393}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n\nTEMP_IMAGE_BOM_PATH=/opt/azure/containers/temp-image-bom.json\nIMAGE_BOM_PATH=/opt/azure/containers/image-bom.json\n\nSKU_NAME=\"${SKU_NAME:=}\"\nIMAGE_VERSION=\"${IMAGE_VERSION:-$(date +%Y%m.%d.0)}\"\nCONTAINER_RUNTIME=\"${CONTAINER_RUNTIME:-containerd}\"\n\nif [[ -z \"${SKU_NAME}\" ]]; then\n    echo \"SKU_NAME must be set when generating image list\"\n    exit 1\nfi\n\nfunction generate_image_bom_for_containerd() {\n    IFS_backup=$IFS; IFS=$'\\n'\n    ctr_list=$(ctr -n k8s.io image list | sed 1d | awk '{print $1, $3}')\n    digests=$(echo \"$ctr_list\" | awk '{print $2}' | xargs -n1 | sort -u)\n\n    for digest in $digests; do\n        digest_entries=$(echo \"$ctr_list\" | grep -e \"$digest\")\n        tags=$(echo \"$digest_entries\" | awk '{print $1}' | grep -v \"sha256\")\n        id=$(echo \"$digest_entries\" | awk '{print $1}' | grep -e \"sha256\")\n\n        jq --arg tags \"$tags\" --arg digest \"$digest\" --arg id \"$id\" -n '{id:$id, repoTags:$tags | split(\"\\n\"), repoDigests:[$digest]}' >> $TEMP_IMAGE_BOM_PATH\n    done\n\n    IFS=$IFS_backup\n    bom=$(jq --slurpfile images $TEMP_IMAGE_BOM_PATH -n '$images | group_by(.id) | map({id:.[0].id, repoTags:[.[].repoTags] | add | unique, repoDigests:[.[].repoDigests] | add | unique})')\n    jq --argjson bom \"$bom\" --arg version \"$IMAGE_VERSION\" --arg sku \"$SKU_NAME\" -n '{sku:$sku, imageVersion:$version, imageBom:$bom}' > $IMAGE_BOM_PATH\n    rm -f $TEMP_IMAGE_BOM_PATH\n}\n\nfunction generate_image_bom_for_docker() {\n    docker inspect $(docker images -aq) -f '{\"id\":\"{{.ID}}\",\"repoTags\":{{json .RepoTags}},\"repoDigests\":{{json .RepoDigests}}}' | jq --slurp . | jq  'map({id:.id, repoTags:.repoTags, repoDigests:.repoDigests | map(split(\"@\")[1])})' > $IMAGE_BOM_PATH\n}\n\necho \"Generating image-bom with IMAGE_VERSION=${IMAGE_VERSION}\"\n\nif [[ ${CONTAINER_RUNTIME} == \"containerd\" ]]; then\n    generate_image_bom_for_containerd\nelif [[ ${CONTAINER_RUNTIME} == \"docker\" ]]; then\n    generate_image_bom_for_docker\nelse\n    echo \"Unknown container runtime: ${CONTAINER_RUNTIME}\"\n    exit 1\nfi\n\nchmod a+r $IMAGE_BOM_PATH\n", "num_lines": 51}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncopyPackerFiles() {\n  SYSCTL_CONFIG_SRC=/home/packer/sysctl-d-60-CIS.conf\n  SYSCTL_CONFIG_DEST=/etc/sysctl.d/60-CIS.conf\n  RSYSLOG_CONFIG_SRC=/home/packer/rsyslog-d-60-CIS.conf\n  RSYSLOG_CONFIG_DEST=/etc/rsyslog.d/60-CIS.conf\n  ETC_ISSUE_CONFIG_SRC=/home/packer/etc-issue\n  ETC_ISSUE_CONFIG_DEST=/etc/issue\n  ETC_ISSUE_NET_CONFIG_SRC=/home/packer/etc-issue.net\n  ETC_ISSUE_NET_CONFIG_DEST=/etc/issue.net\n  SSHD_CONFIG_SRC=/home/packer/sshd_config\n  SSHD_CONFIG_DEST=/etc/ssh/sshd_config\n  MODPROBE_CIS_SRC=/home/packer/modprobe-CIS.conf\n  MODPROBE_CIS_DEST=/etc/modprobe.d/CIS.conf\n  PWQUALITY_CONF_SRC=/home/packer/pwquality-CIS.conf\n  PWQUALITY_CONF_DEST=/etc/security/pwquality.conf\n  PAM_D_COMMON_AUTH_SRC=/home/packer/pam-d-common-auth\n  PAM_D_COMMON_AUTH_DEST=/etc/pam.d/common-auth\n  PAM_D_COMMON_PASSWORD_SRC=/home/packer/pam-d-common-password\n  PAM_D_COMMON_PASSWORD_DEST=/etc/pam.d/common-password\n  PAM_D_SYSTEM_AUTH_SRC=/home/packer/pam-d-system-auth\n  PAM_D_SYSTEM_AUTH_DEST=/etc/pam.d/system-auth\n  PAM_D_SYSTEM_PASSWORD_SRC=/home/packer/pam-d-system-password\n  PAM_D_SYSTEM_PASSWORD_DEST=/etc/pam.d/system-password\n  PAM_D_SU_SRC=/home/packer/pam-d-su\n  PAM_D_SU_DEST=/etc/pam.d/su\n  PROFILE_D_CIS_SH_SRC=/home/packer/profile-d-cis.sh\n  PROFILE_D_CIS_SH_DEST=/etc/profile.d/CIS.sh\n  CIS_SRC=/home/packer/cis.sh\n  CIS_DEST=/opt/azure/containers/provision_cis.sh\n  APT_PREFERENCES_SRC=/home/packer/apt-preferences\n  APT_PREFERENCES_DEST=/etc/apt/preferences\n  KMS_SERVICE_SRC=/home/packer/kms.service\n  KMS_SERVICE_DEST=/etc/systemd/system/kms.service\n  HEALTH_MONITOR_SRC=/home/packer/health-monitor.sh\n  HEALTH_MONITOR_DEST=/usr/local/bin/health-monitor.sh\n  MIG_PARTITION_SRC=/home/packer/mig-partition.sh\n  MIG_PARTITION_DEST=/opt/azure/containers/mig-partition.sh\n  DOCKER_MONITOR_SERVICE_SRC=/home/packer/docker-monitor.service\n  DOCKER_MONITOR_SERVICE_DEST=/etc/systemd/system/docker-monitor.service\n  DOCKER_MONITOR_TIMER_SRC=/home/packer/docker-monitor.timer\n  DOCKER_MONITOR_TIMER_DEST=/etc/systemd/system/docker-monitor.timer\n  CONTAINERD_EXEC_START_SRC=/home/packer/containerd_exec_start.conf\n  CONTAINERD_EXEC_START_DEST=/etc/systemd/system/containerd.service.d/exec_start.conf\n  CONTAINERD_MONITOR_SERVICE_SRC=/home/packer/containerd-monitor.service\n  CONTAINERD_MONITOR_SERVICE_DEST=/etc/systemd/system/containerd-monitor.service\n  CONTAINERD_MONITOR_TIMER_SRC=/home/packer/containerd-monitor.timer\n  CONTAINERD_MONITOR_TIMER_DEST=/etc/systemd/system/containerd-monitor.timer\n  CONTAINERD_SERVICE_SRC=/home/packer/containerd.service\n  CONTAINERD_SERVICE_DEST=/etc/systemd/system/containerd.service\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC=/home/packer/docker_clear_mount_propagation_flags.conf\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n  IPV6_NFTABLES_RULES_SRC=/home/packer/ipv6_nftables\n  IPV6_NFTABLES_RULES_DEST=/etc/systemd/system/ipv6_nftables\n  IPV6_NFTABLES_SCRIPT_SRC=/home/packer/ipv6_nftables.sh\n  IPV6_NFTABLES_SCRIPT_DEST=/opt/scripts/ipv6_nftables.sh\n  IPV6_NFTABLES_SERVICE_SRC=/home/packer/ipv6_nftables.service\n  IPV6_NFTABLES_SERVICE_DEST=/etc/systemd/system/ipv6_nftables.service\n  NVIDIA_MODPROBE_SERVICE_SRC=/home/packer/nvidia-modprobe.service\n  NVIDIA_MODPROBE_SERVICE_DEST=/etc/systemd/system/nvidia-modprobe.service\n  NVIDIA_DOCKER_DAEMON_SRC=/home/packer/nvidia-docker-daemon.json\n  NVIDIA_DOCKER_DAEMON_DEST=/etc/systemd/system/nvidia-docker-daemon.json\n  NVIDIA_DEVICE_PLUGIN_SERVICE_SRC=/home/packer/nvidia-device-plugin.service\n  NVIDIA_DEVICE_PLUGIN_SERVICE_DEST=/etc/systemd/system/nvidia-device-plugin.service\n  DISK_QUEUE_SERVICE_SRC=/home/packer/disk_queue.service\n  DISK_QUEUE_SERVICE_DEST=/etc/systemd/system/disk_queue.service\n  UPDATE_CERTS_SERVICE_SRC=/home/packer/update_certs.service\n  UPDATE_CERTS_SERVICE_DEST=/etc/systemd/system/update_certs.service\n  UPDATE_CERTS_PATH_SRC=/home/packer/update_certs.path\n  UPDATE_CERTS_PATH_DEST=/etc/systemd/system/update_certs.path\n  UPDATE_CERTS_SCRIPT_SRC=/home/packer/update_certs.sh\n  UPDATE_CERTS_SCRIPT_DEST=/opt/scripts/update_certs.sh\n  CI_SYSLOG_WATCHER_PATH_SRC=/home/packer/ci-syslog-watcher.path\n  CI_SYSLOG_WATCHER_PATH_DEST=/etc/systemd/system/ci-syslog-watcher.path\n  CI_SYSLOG_WATCHER_SERVICE_SRC=/home/packer/ci-syslog-watcher.service\n  CI_SYSLOG_WATCHER_SERVICE_DEST=/etc/systemd/system/ci-syslog-watcher.service\n  CI_SYSLOG_WATCHER_SCRIPT_SRC=/home/packer/ci-syslog-watcher.sh\n  CI_SYSLOG_WATCHER_SCRIPT_DEST=/usr/local/bin/ci-syslog-watcher.sh\n  AKS_LOGROTATE_SCRIPT_SRC=/home/packer/logrotate.sh\n  AKS_LOGROTATE_SCRIPT_DEST=/usr/local/bin/logrotate.sh\n  AKS_LOGROTATE_SERVICE_SRC=/home/packer/logrotate.service\n  AKS_LOGROTATE_SERVICE_DEST=/etc/systemd/system/logrotate.service\n  AKS_LOGROTATE_TIMER_SRC=/home/packer/logrotate.timer\n  AKS_LOGROTATE_TIMER_DEST=/etc/systemd/system/logrotate.timer\n  AKS_LOGROTATE_TIMER_DROPIN_SRC=/home/packer/override.conf\n  AKS_LOGROTATE_TIMER_DROPIN_DEST=/etc/systemd/system/logrotate.timer.d/override.conf\n  AKS_LOGROTATE_CONF_SRC=/home/packer/rsyslog\n  AKS_LOGROTATE_CONF_DEST=/etc/logrotate.d/rsyslog\n  BLOCK_WIRESERVER_SRC=/home/packer/block_wireserver.sh\n  BLOCK_WIRESERVER_DEST=/opt/azure/containers/kubelet.sh\n  RECONCILE_PRIVATE_HOSTS_SRC=/home/packer/reconcile-private-hosts.sh\n  RECONCILE_PRIVATE_HOSTS_DEST=/opt/azure/containers/reconcilePrivateHosts.sh\n  KUBELET_SERVICE_SRC=/home/packer/kubelet.service\n  KUBELET_SERVICE_DEST=/etc/systemd/system/kubelet.service\n  VHD_CLEANUP_SCRIPT_SRC=/home/packer/cleanup-vhd.sh\n  VHD_CLEANUP_SCRIPT_DEST=/opt/azure/containers/cleanup-vhd.sh\n\n  CSE_REDACT_SRC=/home/packer/cse_redact_cloud_config.py\n  CSE_REDACT_DEST=/opt/azure/containers/provision_redact_cloud_config.py\n  cpAndMode $CSE_REDACT_SRC $CSE_REDACT_DEST 0744\n\n  CSE_SEND_SRC=/home/packer/cse_send_logs.py\n  CSE_SEND_DEST=/opt/azure/containers/provision_send_logs.py\n  cpAndMode $CSE_SEND_SRC $CSE_SEND_DEST 0744\n\n  INIT_CUSTOM_CLOUD_SRC=/home/packer/init-aks-custom-cloud.sh\n  INIT_CUSTOM_CLOUD_DEST=/opt/azure/containers/init-aks-custom-cloud.sh\n  cpAndMode $INIT_CUSTOM_CLOUD_SRC $INIT_CUSTOM_CLOUD_DEST 0744\n\n  PVT_HOST_SVC_SRC=/home/packer/reconcile-private-hosts.service\n  PVT_HOST_SVC_DEST=/etc/systemd/system/reconcile-private-hosts.service\n  cpAndMode $CSE_REDACT_SRC $CSE_REDACT_DEST 600\n\n  MIG_PART_SRC=/home/packer/mig-partition.service\n  MIG_PART_DEST=/etc/systemd/system/mig-partition.service\n  cpAndMode $MIG_PART_SRC $MIG_PART_DEST 600\n\n  MNT_SH_SRC=/home/packer/bind-mount.sh\n  MNT_SH_DEST=/opt/azure/containers/bind-mount.sh\n  cpAndMode $MNT_SH_SRC $MNT_SH_DEST 0544\n\n  MNT_SVC_SRC=/home/packer/bind-mount.service\n  MNT_SVC_DEST=/etc/systemd/system/bind-mount.service\n  cpAndMode $MNT_SVC_SRC $MNT_SVC_DEST 600\n\n  DHCP6_SH_SRC=/home/packer/enable-dhcpv6.sh\n  DHCP6_SH_DEST=/opt/azure/containers/enable-dhcpv6.sh\n  cpAndMode $DHCP6_SH_SRC $DHCP6_SH_DEST 0544\n\n  DHCP6_SVC_SRC=/home/packer/dhcpv6.service\n  DHCP6_SVC_DEST=/etc/systemd/system/dhcpv6.service\n  cpAndMode $DHCP6_SVC_SRC $DHCP6_SVC_DEST 600\n\n  SYNC_LOGS_SH_SRC=/home/packer/sync-container-logs.sh\n  SYNC_LOGS_SH_DEST=/opt/azure/containers/sync-container-logs.sh\n  cpAndMode $SYNC_LOGS_SH_SRC $SYNC_LOGS_SH_DEST 0544\n\n  SYNC_LOGS_SVC_SRC=/home/packer/sync-container-logs.service\n  SYNC_LOGS_SVC_DEST=/etc/systemd/system/sync-container-logs.service\n  cpAndMode $SYNC_LOGS_SVC_SRC $SYNC_LOGS_SVC_DEST 600\n\n  CRICTL_SRC=/home/packer/crictl.yaml\n  CRICTL_DEST=/etc/crictl.yaml\n  cpAndMode $CRICTL_SRC $CRICTL_DEST 0644\n\n  NO_DUP_SH_SRC=/home/packer/ensure-no-dup.sh\n  NO_DUP_SH_DEST=/opt/azure/containers/ensure-no-dup.sh\n  cpAndMode $NO_DUP_SH_SRC $NO_DUP_SH_DEST 0755\n\n  NO_DUP_SVC_SRC=/home/packer/ensure-no-dup.service\n  NO_DUP_SVC_DEST=/etc/systemd/system/ensure-no-dup.service\n  cpAndMode $NO_DUP_SVC_SRC $NO_DUP_SVC_DEST 600\n\n  TELED_SRC=/home/packer/teleportd.service\n  TELED_DEST=/etc/systemd/system/teleportd.service\n  cpAndMode $TELED_SRC $TELED_DEST 600\n\n  SETUP_SEARCH_SRC=/home/packer/setup-custom-search-domains.sh\n  SETUP_SEARCH_DEST=/opt/azure/containers/setup-custom-search-domains.sh\n  cpAndMode $SETUP_SEARCH_SRC $SETUP_SEARCH_DEST 0744\n\n  CSE_MAIN_SRC=/home/packer/provision.sh\n  CSE_MAIN_DEST=/opt/azure/containers/provision.sh\n  cpAndMode $CSE_MAIN_SRC $CSE_MAIN_DEST 0744\n\n  CSE_START_SRC=/home/packer/provision_start.sh\n  CSE_START_DEST=/opt/azure/containers/provision_start.sh\n  cpAndMode $CSE_START_SRC $CSE_START_DEST 0744\n\n  CSE_CONFIG_SRC=/home/packer/provision_configs.sh\n  CSE_CONFIG_DEST=/opt/azure/containers/provision_configs.sh\n  cpAndMode $CSE_CONFIG_SRC $CSE_CONFIG_DEST 0744\n\n  CSE_INSTALL_SRC=/home/packer/provision_installs.sh\n  CSE_INSTALL_DEST=/opt/azure/containers/provision_installs.sh\n  cpAndMode $CSE_INSTALL_SRC $CSE_INSTALL_DEST 0744\n\n  CSE_INSTALL_DISTRO_SRC=/home/packer/provision_installs_distro.sh\n  CSE_INSTALL_DISTRO_DEST=/opt/azure/containers/provision_installs_distro.sh\n  cpAndMode $CSE_INSTALL_DISTRO_SRC $CSE_INSTALL_DISTRO_DEST 0744\n\n  CSE_HELPERS_SRC=/home/packer/provision_source.sh\n  CSE_HELPERS_DEST=/opt/azure/containers/provision_source.sh\n  cpAndMode $CSE_HELPERS_SRC $CSE_HELPERS_DEST 0744\n\n  CSE_HELPERS_DISTRO_SRC=/home/packer/provision_source_distro.sh\n  CSE_HELPERS_DISTRO_DEST=/opt/azure/containers/provision_source_distro.sh\n  cpAndMode $CSE_HELPERS_DISTRO_SRC $CSE_HELPERS_DISTRO_DEST 0744\n\n  NOTICE_SRC=/home/packer/NOTICE.txt\n  NOTICE_DEST=/NOTICE.txt\n\n  if [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    SSHD_CONFIG_SRC=/home/packer/sshd_config_1604\n  elif [[ ${UBUNTU_RELEASE} == \"18.04\" && ${ENABLE_FIPS,,} == \"true\" ]]; then\n    SSHD_CONFIG_SRC=/home/packer/sshd_config_1804_fips\n  fi\n\n  cpAndMode $AKS_LOGROTATE_CONF_SRC $AKS_LOGROTATE_CONF_DEST 644\n  # If a logrotation timer does not exist on the base image\n  if [ ! -f /etc/systemd/system/logrotate.timer ] && [ ! -f /usr/lib/systemd/system/logrotate.timer ]; then\n    cpAndMode $AKS_LOGROTATE_SCRIPT_SRC $AKS_LOGROTATE_SCRIPT_DEST 544\n    cpAndMode $AKS_LOGROTATE_SERVICE_SRC $AKS_LOGROTATE_SERVICE_DEST 644\n    cpAndMode $AKS_LOGROTATE_TIMER_SRC $AKS_LOGROTATE_TIMER_DEST 644\n  else\n    cpAndMode $AKS_LOGROTATE_TIMER_DROPIN_SRC $AKS_LOGROTATE_TIMER_DROPIN_DEST 644\n  fi\n\n  if [[ ${UBUNTU_RELEASE} == \"22.04\" ]]; then\n    PAM_D_COMMON_AUTH_SRC=/home/packer/pam-d-common-auth-2204\n  fi\n\n  cpAndMode $KUBELET_SERVICE_SRC $KUBELET_SERVICE_DEST 600\n  cpAndMode $BLOCK_WIRESERVER_SRC $BLOCK_WIRESERVER_DEST 755\n  cpAndMode $RECONCILE_PRIVATE_HOSTS_SRC $RECONCILE_PRIVATE_HOSTS_DEST 744\n  cpAndMode $SYSCTL_CONFIG_SRC $SYSCTL_CONFIG_DEST 644\n  cpAndMode $RSYSLOG_CONFIG_SRC $RSYSLOG_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_CONFIG_SRC $ETC_ISSUE_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_NET_CONFIG_SRC $ETC_ISSUE_NET_CONFIG_DEST 644\n  cpAndMode $SSHD_CONFIG_SRC $SSHD_CONFIG_DEST 600\n  cpAndMode $MODPROBE_CIS_SRC $MODPROBE_CIS_DEST 644\n  cpAndMode $PWQUALITY_CONF_SRC $PWQUALITY_CONF_DEST 600\n  cpAndMode $PAM_D_SU_SRC $PAM_D_SU_DEST 644\n  cpAndMode $PROFILE_D_CIS_SH_SRC $PROFILE_D_CIS_SH_DEST 755\n  cpAndMode $CIS_SRC $CIS_DEST 744\n  cpAndMode $APT_PREFERENCES_SRC $APT_PREFERENCES_DEST 644\n  cpAndMode $KMS_SERVICE_SRC $KMS_SERVICE_DEST 644\n  cpAndMode $HEALTH_MONITOR_SRC $HEALTH_MONITOR_DEST 544\n  cpAndMode $MIG_PARTITION_SRC $MIG_PARTITION_DEST 544\n  cpAndMode $CONTAINERD_EXEC_START_SRC $CONTAINERD_EXEC_START_DEST 644\n  cpAndMode $CONTAINERD_MONITOR_SERVICE_SRC $CONTAINERD_MONITOR_SERVICE_DEST 644\n  cpAndMode $CONTAINERD_MONITOR_TIMER_SRC $CONTAINERD_MONITOR_TIMER_DEST 644\n  cpAndMode $DISK_QUEUE_SERVICE_SRC $DISK_QUEUE_SERVICE_DEST 644\n  cpAndMode $UPDATE_CERTS_SERVICE_SRC $UPDATE_CERTS_SERVICE_DEST 644\n  cpAndMode $UPDATE_CERTS_PATH_SRC $UPDATE_CERTS_PATH_DEST 644\n  cpAndMode $UPDATE_CERTS_SCRIPT_SRC $UPDATE_CERTS_SCRIPT_DEST 755\n  cpAndMode $IPV6_NFTABLES_RULES_SRC $IPV6_NFTABLES_RULES_DEST 644\n  cpAndMode $IPV6_NFTABLES_SCRIPT_SRC $IPV6_NFTABLES_SCRIPT_DEST 755\n  cpAndMode $IPV6_NFTABLES_SERVICE_SRC $IPV6_NFTABLES_SERVICE_DEST 644\n  cpAndMode $CI_SYSLOG_WATCHER_PATH_SRC $CI_SYSLOG_WATCHER_PATH_DEST 644\n  cpAndMode $CI_SYSLOG_WATCHER_SERVICE_SRC $CI_SYSLOG_WATCHER_SERVICE_DEST 644\n  cpAndMode $CI_SYSLOG_WATCHER_SCRIPT_SRC $CI_SYSLOG_WATCHER_SCRIPT_DEST 755\n\n  if [[ $OS != $MARINER_OS_NAME ]]; then\n    cpAndMode $DOCKER_MONITOR_SERVICE_SRC $DOCKER_MONITOR_SERVICE_DEST 644\n    cpAndMode $DOCKER_MONITOR_TIMER_SRC $DOCKER_MONITOR_TIMER_DEST 644\n    cpAndMode $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST 644\n    cpAndMode $NVIDIA_MODPROBE_SERVICE_SRC $NVIDIA_MODPROBE_SERVICE_DEST 644\n    cpAndMode $PAM_D_COMMON_AUTH_SRC $PAM_D_COMMON_AUTH_DEST 644\n    cpAndMode $PAM_D_COMMON_PASSWORD_SRC $PAM_D_COMMON_PASSWORD_DEST 644\n  fi\n  if [[ $OS == $MARINER_OS_NAME ]]; then\n    cpAndMode $CONTAINERD_SERVICE_SRC $CONTAINERD_SERVICE_DEST 644\n\n    # MarinerV2 uses system-auth and system-password instead of common-auth and common-password.\n    if [[ ${OS_VERSION} == \"2.0\" ]]; then\n      cpAndMode $PAM_D_SYSTEM_AUTH_SRC $PAM_D_SYSTEM_AUTH_DEST 644\n      cpAndMode $PAM_D_SYSTEM_PASSWORD_SRC $PAM_D_SYSTEM_PASSWORD_DEST 644\n    else\n      cpAndMode $PAM_D_COMMON_AUTH_SRC $PAM_D_COMMON_AUTH_DEST 644\n      cpAndMode $PAM_D_COMMON_PASSWORD_SRC $PAM_D_COMMON_PASSWORD_DEST 644\n    fi\n  fi\n\n  if grep -q \"fullgpu\" <<<\"$FEATURE_FLAGS\"; then\n    cpAndMode $NVIDIA_DOCKER_DAEMON_SRC $NVIDIA_DOCKER_DAEMON_DEST 644\n    if grep -q \"gpudaemon\" <<<\"$FEATURE_FLAGS\"; then\n      cpAndMode $NVIDIA_DEVICE_PLUGIN_SERVICE_SRC $NVIDIA_DEVICE_PLUGIN_SERVICE_DEST 644\n    fi\n  fi\n\n  cpAndMode $NOTICE_SRC $NOTICE_DEST 444\n\n  # Always copy the VHD cleanup script responsible for prepping the instance for first boot\n  # to disk so we can run it again if needed in subsequent builds/releases (prefetch during SIG release)\n  cpAndMode $VHD_CLEANUP_SCRIPT_SRC $VHD_CLEANUP_SCRIPT_DEST 644\n}\n\ncpAndMode() {\n  src=$1\n  dest=$2\n  mode=$3\n  DIR=$(dirname \"$dest\") && mkdir -p ${DIR} && cp $src $dest && chmod $mode $dest || exit $ERR_PACKER_COPY_FILE\n}\n", "num_lines": 286}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\n\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_installs_distro.sh\nsource /home/packer/provision_source.sh\nsource /home/packer/provision_source_distro.sh\nsource /home/packer/tool_installs.sh\nsource /home/packer/tool_installs_distro.sh\n\nCPU_ARCH=$(getCPUArch)  #amd64 or arm64\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\n\n# Hardcode the desired size of the OS disk so we don't accidently rely on extra disk space\nMAX_BLOCK_COUNT=30298176 # 30 GB\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  # shellcheck disable=SC2021\n  current_kernel=\"$(uname -r | cut -d- -f-2)\"\n  if [[ \"${ENABLE_FIPS,,}\" == \"true\" ]]; then\n    dpkg --get-selections | grep -e \"linux-\\(headers\\|modules\\|image\\)\" | grep -v \"$current_kernel\" | grep -v \"fips\" | tr -s '[[:space:]]' | tr '\\t' ' ' | cut -d' ' -f1 | xargs -I{} apt-get --purge remove -yq {}\n  else\n    dpkg --get-selections | grep -e \"linux-\\(headers\\|modules\\|image\\)\" | grep -v \"linux-\\(headers\\|modules\\|image\\)-azure\" | grep -v \"$current_kernel\" | tr -s '[[:space:]]' | tr '\\t' ' ' | cut -d' ' -f1 | xargs -I{} apt-get --purge remove -yq {}\n  fi\n\n  # remove apport\n  retrycmd_if_failure 10 2 60 apt-get purge --auto-remove apport open-vm-tools -y || exit 1\n\n  # strip old kernels/packages\n  retrycmd_if_failure 10 2 60 apt-get -y autoclean || exit 1\n  retrycmd_if_failure 10 2 60 apt-get -y autoremove --purge || exit 1\n  retrycmd_if_failure 10 2 60 apt-get -y clean || exit 1\nfi\n\n# shellcheck disable=SC2129\necho \"kubelet/kubectl downloaded:\" >> ${VHD_LOGS_FILEPATH}\nls -ltr /usr/local/bin/* >> ${VHD_LOGS_FILEPATH}\n\n# shellcheck disable=SC2010\nls -ltr /dev/* | grep sgx >>  ${VHD_LOGS_FILEPATH} \n\necho -e \"=== Installed Packages Begin\\n$(listInstalledPackages)\\n=== Installed Packages End\" >> ${VHD_LOGS_FILEPATH}\n\necho \"Disk usage:\" >> ${VHD_LOGS_FILEPATH}\ndf -h >> ${VHD_LOGS_FILEPATH}\n\n# check the size of the OS disk after installing all dependencies: warn at 75% space taken, error at 99% space taken\nos_device=$(readlink -f /dev/disk/azure/root)\nused_blocks=$(df -P / | sed 1d | awk '{print $3}')\nusage=$(awk -v used=${used_blocks} -v capacity=${MAX_BLOCK_COUNT} 'BEGIN{print (used/capacity) * 100}')\nusage=${usage%.*}\n[ ${usage} -ge 99 ] && echo \"ERROR: root partition on OS device (${os_device}) already passed 99% of the 30GB cap!\" && exit 1\n[ ${usage} -ge 75 ] && echo \"WARNING: root partition on OS device (${os_device}) already passed 75% of the 30GB cap!\"\n\necho \"Using kernel:\" >> ${VHD_LOGS_FILEPATH}\ntee -a ${VHD_LOGS_FILEPATH} < /proc/version\n{\n  echo \"Install completed successfully on \" $(date)\n  echo \"VSTS Build NUMBER: ${BUILD_NUMBER}\"\n  echo \"VSTS Build ID: ${BUILD_ID}\"\n  echo \"Commit: ${COMMIT}\"\n  echo \"Ubuntu version: ${UBUNTU_RELEASE}\"\n  echo \"Hyperv generation: ${HYPERV_GENERATION}\"\n  echo \"Feature flags: ${FEATURE_FLAGS}\"\n  echo \"Container runtime: ${CONTAINER_RUNTIME}\"\n  echo \"FIPS enabled: ${ENABLE_FIPS}\"\n} >> ${VHD_LOGS_FILEPATH}\n\necho -e \"=== os-release Begin\" >> ${VHD_LOGS_FILEPATH}\ncat /etc/os-release >> ${VHD_LOGS_FILEPATH}\necho -e \"=== os-release End\" >> ${VHD_LOGS_FILEPATH}\n\nif [[ $(isARM64) != 1 ]]; then\n  # no asc-baseline-1.1.0-268.arm64.deb\n  installAscBaseline\nfi\n\nif [[ ${UBUNTU_RELEASE} == \"18.04\" || ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"22.04\" ]]; then\n  if [[ ${ENABLE_FIPS,,} == \"true\" || ${CPU_ARCH} == \"arm64\" ]]; then\n    relinkResolvConf\n  fi\nfi\n\necho \"post-install-dependencies step completed successfully\"", "num_lines": 85}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(coreos)|ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nOS_VERSION=$(sort -r /etc/*-release | gawk 'match($0, /^(VERSION_ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }' | tr -d '\"')\nTHIS_DIR=\"$(cd \"$(dirname ${BASH_SOURCE[0]})\" && pwd)\"\n\n#the following sed removes all comments of the format {{/* */}}\nsed -i 's/{{\\/\\*[^*]*\\*\\/}}//g' /home/packer/provision_source.sh\nsed -i 's/{{\\/\\*[^*]*\\*\\/}}//g' /home/packer/tool_installs_distro.sh\n\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_installs_distro.sh\nsource /home/packer/provision_source.sh\nsource /home/packer/provision_source_distro.sh\nsource /home/packer/tool_installs.sh\nsource /home/packer/tool_installs_distro.sh\nsource /home/packer/packer_source.sh\n\nCPU_ARCH=$(getCPUArch)  #amd64 or arm64\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nCOMPONENTS_FILEPATH=/opt/azure/components.json\nMANIFEST_FILEPATH=/opt/azure/manifest.json\nKUBE_PROXY_IMAGES_FILEPATH=/opt/azure/kube-proxy-images.json\n#this is used by post build test to check whether the compoenents do indeed exist\ncat components.json > ${COMPONENTS_FILEPATH}\ncat manifest.json > ${MANIFEST_FILEPATH}\ncat ${THIS_DIR}/kube-proxy-images.json > ${KUBE_PROXY_IMAGES_FILEPATH}\necho \"Starting build on \" $(date) > ${VHD_LOGS_FILEPATH}\n\nif [[ $OS == $MARINER_OS_NAME ]]; then\n  chmod 755 /opt\n  chmod 755 /opt/azure\n  chmod 644 ${VHD_LOGS_FILEPATH}\nfi\n\ncopyPackerFiles\nsystemctlEnableAndStart disk_queue || exit 1\n\nmkdir /opt/certs\nchmod 1666 /opt/certs\nsystemctlEnableAndStart update_certs.path || exit 1\n\nsystemctlEnableAndStart ci-syslog-watcher.path || exit 1\nsystemctlEnableAndStart ci-syslog-watcher.service || exit 1\n\n# enable the modified logrotate service and remove the auto-generated default logrotate cron job if present\nsystemctlEnableAndStart logrotate.timer || exit 1\nrm -f /etc/cron.daily/logrotate\n\nsystemctlEnableAndStart sync-container-logs.service || exit 1\n\n# First handle Mariner + FIPS\nif [[ ${OS} == ${MARINER_OS_NAME} ]]; then\n  dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n  dnf_update || exit $ERR_APT_DIST_UPGRADE_TIMEOUT\n  if [[ \"${ENABLE_FIPS,,}\" == \"true\" ]]; then\n    # This is FIPS install for Mariner and has nothing to do with Ubuntu Advantage\n    echo \"Install FIPS for Mariner SKU\"\n    installFIPS\n  fi\nelse\n  # Handle FIPS and ESM for Ubuntu\n  if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" ]] || [[ \"${ENABLE_FIPS,,}\" == \"true\" ]]; then\n    autoAttachUA\n  fi\n\n  # Run apt get update to refresh repo list\n  # Run apt dist get upgrade to install packages/kernels\n\n  # CVM breaks on kernel image updates due to nullboot package post-install.\n  # it relies on boot measurements from real tpm hardware.\n  # building on a real CVM would solve this, but packer doesn't support it.\n  # we could make upstream changes but that takes time, and we are broken now.\n  # so we just hold the kernel image packages for now on CVM.\n  # this still allows us base image and package updates on a weekly cadence.\n  if [[ \"$IMG_SKU\" != \"20_04-lts-cvm\" ]]; then\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    apt_get_dist_upgrade || exit $ERR_APT_DIST_UPGRADE_TIMEOUT    \n  fi\n\n  if [[ \"${ENABLE_FIPS,,}\" == \"true\" ]]; then\n    # This is FIPS Install for Ubuntu, it purges non FIPS Kernel and attaches UA FIPS Updates\n    echo \"Install FIPS for Ubuntu SKU\"\n    installFIPS\n  fi\n\n  # Final step, if 1804 or FIPS, log ua status, detach UA and clean up\n  if [[ \"${UBUNTU_RELEASE}\" == \"18.04\" ]] || [[ \"${ENABLE_FIPS,,}\" == \"true\" ]]; then\n    # 'ua status' for logging\n    ua status\n    detachAndCleanUpUA\n  fi\nfi\n\necho \"pre-install-dependencies step finished successfully\"", "num_lines": 94}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n\nTRIVY_REPORT_JSON_PATH=/opt/azure/containers/trivy-report.json\nTRIVY_REPORT_TABLE_PATH=/opt/azure/containers/trivy-images-table.txt\nTRIVY_VERSION=\"0.40.0\"\nTRIVY_ARCH=\"\"\n\narch=\"$(uname -m)\"\nif [ \"${arch,,}\" == \"arm64\" ] || [ \"${arch,,}\" == \"aarch64\" ]; then\n    TRIVY_ARCH=\"Linux-ARM64\"\nelif [ \"${arch,,}\" == \"x86_64\" ]; then\n    TRIVY_ARCH=\"Linux-64bit\"\nelse\n    echo \"invalid architecture ${arch,,}\"\n    exit 1\nfi\n\nmkdir -p \"$(dirname \"${TRIVY_REPORT_JSON_PATH}\")\"\nmkdir -p \"$(dirname \"${TRIVY_REPORT_TABLE_PATH}\")\"\n\nwget \"https://github.com/aquasecurity/trivy/releases/download/v${TRIVY_VERSION}/trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz\"\ntar -xvzf \"trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz\"\nrm \"trivy_${TRIVY_VERSION}_${TRIVY_ARCH}.tar.gz\"\nchmod a+x trivy \n\n./trivy --scanners vuln rootfs -f json --skip-dirs /var/lib/containerd --ignore-unfixed --severity HIGH,CRITICAL -o \"${TRIVY_REPORT_JSON_PATH}\" /\n\nIMAGE_LIST=$(ctr -n k8s.io image list -q | grep -v sha256)\n\necho \"This contains the list of images with high and critical level CVEs (if present), that are present in the node. \nNote: images without CVEs are also listed\" >> \"${TRIVY_REPORT_TABLE_PATH}\"\n\nfor image in $IMAGE_LIST; do\n    ./trivy --scanners vuln image --ignore-unfixed --severity HIGH,CRITICAL -f table $image >> ${TRIVY_REPORT_TABLE_PATH} || true\ndone\n\nrm ./trivy \n\nchmod a+r \"${TRIVY_REPORT_JSON_PATH}\"\nchmod a+r \"${TRIVY_REPORT_TABLE_PATH}\"\n", "num_lines": 42}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nCOMPONENTS_FILEPATH=/opt/azure/components.json\nKUBE_PROXY_IMAGES_FILEPATH=/opt/azure/kube-proxy-images.json\nMANIFEST_FILEPATH=/opt/azure/manifest.json\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\n\nTHIS_DIR=\"$(cd \"$(dirname ${BASH_SOURCE[0]})\" && pwd)\"\nCONTAINER_RUNTIME=\"$1\"\nOS_VERSION=\"$2\"\nENABLE_FIPS=\"$3\"\nOS_SKU=\"$4\"\nGIT_BRANCH=\"$5\"\n\nerr() {\n  echo \"$1:Error: $2\" >>/dev/stderr\n}\n\n# Clone the repo and checkout the branch provided.\n# Simply clone with just the branch doesn't work for pull requests, but this technique works\n# with everything we've tested so far.\n#\n# Strategy is to clone the repo, fetch the remote branch by ref into a local branch, and then checkout the local branch.\n# The remote branch will be something like 'refs/heads/branch/name' or 'refs/pull/number/head'. Using the same name\n# for the local branch has weird semantics, so we replace '/' with '-' for the local branch name.\nLOCAL_GIT_BRANCH=${GIT_BRANCH//\\//-}\necho \"Cloning AgentBaker repo and checking out remote branch '${GIT_BRANCH}' into local branch '${LOCAL_GIT_BRANCH}'\"\nCOMMAND=\"git clone --quiet https://github.com/Azure/AgentBaker.git\"\nif ! ${COMMAND}; then\n  err 'git-clone' \"Failed to clone AgentBaker repo\"\n  err 'git-clone' \"Used command '${COMMAND}'\"\n  exit 1\nfi\nif ! pushd ./AgentBaker; then\n  err 'git-clone' \"Failed to pushd into AgentBaker repo -- this is weird given that clone succeeded\"\n  err 'git-clone' \"Current directory is '$(pwd)'\"\n  err 'git-clone' \"Contents of current directory: $(ls -al)\"\n  exit 1\nfi\nCOMMAND=\"git fetch --quiet origin ${GIT_BRANCH}:${LOCAL_GIT_BRANCH}\"\nif ! ${COMMAND}; then\n  err 'git-clone' \"Failed to fetch remote branch '${GIT_BRANCH}' into local branch '${LOCAL_GIT_BRANCH}'\"\n  err 'git-clone' \"Used command '${COMMAND}'\"\n  exit 1\nfi\nCOMMAND=\"git checkout --quiet ${LOCAL_GIT_BRANCH}\"\nif ! ${COMMAND}; then\n  err 'git-clone' \"Failed to checkout local branch '${LOCAL_GIT_BRANCH}'\"\n  err 'git-clone' \"Used command '${COMMAND}'\"\n  exit 1\nfi\nif ! popd; then\n  err 'git-clone' \"Failed to popd out of AgentBaker repo -- this seems impossible\"\n  err 'git-clone' \"Current directory is $(pwd)\"\n  err 'git-clone' \"pushd stack is $(dirs -p)\"\n  exit 1\nfi\n\nsource ./AgentBaker/parts/linux/cloud-init/artifacts/ubuntu/cse_install_ubuntu.sh 2>/dev/null\nsource ./AgentBaker/parts/linux/cloud-init/artifacts/cse_helpers.sh 2>/dev/null\n\ntestFilesDownloaded() {\n  test=\"testFilesDownloaded\"\n  containerRuntime=$1\n  if [[ $(isARM64) == 1 ]]; then\n    return\n  fi\n  echo \"$test:Start\"\n  filesToDownload=$(jq .DownloadFiles[] --monochrome-output --compact-output <$COMPONENTS_FILEPATH)\n\n  for fileToDownload in ${filesToDownload[*]}; do\n    fileName=$(echo \"${fileToDownload}\" | jq .fileName -r)\n    downloadLocation=$(echo \"${fileToDownload}\" | jq .downloadLocation -r)\n    versions=$(echo \"${fileToDownload}\" | jq .versions -r | jq -r \".[]\")\n    download_URL=$(echo \"${fileToDownload}\" | jq .downloadURL -r)\n    targetContainerRuntime=$(echo \"${fileToDownload}\" | jq .targetContainerRuntime -r)\n    if [ \"${targetContainerRuntime}\" != \"null\" ] && [ \"${containerRuntime}\" != \"${targetContainerRuntime}\" ]; then\n      echo \"$test: skipping ${fileName} verification as VHD container runtime is ${containerRuntime}, not ${targetContainerRuntime}\"\n      continue\n    fi\n    if [ ! -d $downloadLocation ]; then\n      err $test \"Directory ${downloadLocation} does not exist\"\n      continue\n    fi\n\n    for version in ${versions}; do\n      file_Name=$(string_replace $fileName $version)\n      dest=\"$downloadLocation/${file_Name}\"\n      downloadURL=$(string_replace $download_URL $version)/$file_Name\n      if [ ! -s $dest ]; then\n        err $test \"File ${dest} does not exist\"\n        continue\n      fi\n      # no wc -c on a dir. This is for downloads we've un tar'd and deleted from the vhd\n      if [ ! -d $dest ]; then\n        # -L since some urls are redirects (i.e github)\n        fileSizeInRepo=$(curl -sLI $downloadURL | grep -i Content-Length | tail -n1 | awk '{print $2}' | tr -d '\\r')\n        fileSizeDownloaded=$(wc -c $dest | awk '{print $1}' | tr -d '\\r')\n        if [[ \"$fileSizeInRepo\" != \"$fileSizeDownloaded\" ]]; then\n          err $test \"File size of ${dest} from ${downloadURL} is invalid. Expected file size: ${fileSizeInRepo} - downlaoded file size: ${fileSizeDownloaded}\"\n          continue\n        fi\n        # Validate whether package exists in Azure China cloud\n        if [[ $downloadURL == https://acs-mirror.azureedge.net/* ]]; then\n          mcURL=\"${downloadURL/https:\\/\\/acs-mirror.azureedge.net/https:\\/\\/kubernetesartifacts.blob.core.chinacloudapi.cn}\"\n          echo \"Validating: $mcURL\"\n          isExist=$(curl -sLI $mcURL | grep -i \"404 The specified blob does not exist.\" | awk '{print $2}')\n          if [[ \"$isExist\" == \"404\" ]]; then\n            err \"$mcURL is invalid\"\n            continue\n          fi\n\n          fileSizeInMC=$(curl -sLI $mcURL | grep -i Content-Length | tail -n1 | awk '{print $2}' | tr -d '\\r')\n          if [[ \"$fileSizeInMC\" != \"$fileSizeDownloaded\" ]]; then\n            err \"$mcURL is valid but the file size is different. Expected file size: ${fileSizeDownloaded} - downlaoded file size: ${fileSizeInMC}\"\n            continue\n          fi\n        fi\n      fi\n    done\n\n    echo \"---\"\n  done\n  echo \"$test:Finish\"\n}\n\ntestImagesPulled() {\n  test=\"testImagesPulled\"\n  echo \"$test:Start\"\n  containerRuntime=$1\n  if [ $containerRuntime == 'containerd' ]; then\n    pulledImages=$(ctr -n k8s.io image ls)\n  elif [ $containerRuntime == 'docker' ]; then\n    pulledImages=$(docker images --format \"{{.Repository}}:{{.Tag}}\")\n  else\n    err $test \"unsupported container runtime $containerRuntime\"\n    return\n  fi\n\n  imagesToBePulled=$(echo $2 | jq .ContainerImages[] --monochrome-output --compact-output)\n\n  for imageToBePulled in ${imagesToBePulled[*]}; do\n    downloadURL=$(echo \"${imageToBePulled}\" | jq .downloadURL -r)\n    amd64OnlyVersionsStr=$(echo \"${imageToBePulled}\" | jq .amd64OnlyVersions -r)\n    multiArchVersionsStr=$(echo \"${imageToBePulled}\" | jq .multiArchVersions -r)\n\n    amd64OnlyVersions=\"\"\n    if [[ ${amd64OnlyVersionsStr} != null ]]; then\n      amd64OnlyVersions=$(echo \"${amd64OnlyVersionsStr}\" | jq -r \".[]\")\n    fi\n    multiArchVersions=\"\"\n    if [[ ${multiArchVersionsStr} != null ]]; then\n      multiArchVersions=$(echo \"${multiArchVersionsStr}\" | jq -r \".[]\")\n    fi\n    if [[ $(isARM64) == 1 ]]; then\n      versions=\"${multiArchVersions}\"\n    else\n      versions=\"${amd64OnlyVersions} ${multiArchVersions}\"\n    fi\n    for version in ${versions}; do\n      download_URL=$(string_replace $downloadURL $version)\n\n      if [[ $pulledImages =~ $downloadURL ]]; then\n        echo \"Image ${download_URL} pulled\"\n      else\n        err $test \"Image ${download_URL} has NOT been pulled\"\n      fi\n    done\n\n    echo \"---\"\n  done\n  echo \"$test:Finish\"\n}\n\n# check all the mcr images retagged for mooncake\ntestImagesRetagged() {\n  containerRuntime=$1\n  if [ $containerRuntime == 'containerd' ]; then\n    # shellcheck disable=SC2207\n    pulledImages=($(ctr -n k8s.io image ls))\n  elif [ $containerRuntime == 'docker' ]; then\n    # shellcheck disable=SC2207\n    pulledImages=($(docker images --format \"{{.Repository}}:{{.Tag}}\"))\n  else\n    err $test \"unsupported container runtime $containerRuntime\"\n    return\n  fi\n  mcrImagesNumber=0\n  mooncakeMcrImagesNumber=0\n  for pulledImage in ${pulledImages[@]}; do\n    if [[ $pulledImage == \"mcr.microsoft.com\"* ]]; then\n      mcrImagesNumber=$((${mcrImagesNumber} + 1))\n    fi\n    if [[ $pulledImage == \"mcr.azk8s.cn\"* ]]; then\n      mooncakeMcrImagesNumber=$((${mooncakeMcrImagesNumber} + 1))\n    fi\n  done\n  if [[ \"${mcrImagesNumber}\" != \"${mooncakeMcrImagesNumber}\" ]]; then\n    echo \"the number of the mcr images & mooncake mcr images are not the same.\"\n    echo \"all the images are:\"\n    echo \"${pulledImages[@]}\"\n    exit 1\n  fi\n}\n\ntestAuditDNotPresent() {\n  test=\"testAuditDNotPresent\"\n  echo \"$test:Start\"\n  status=$(systemctl show -p SubState --value auditd.service)\n  if [ $status == 'dead' ]; then\n    echo \"AuditD is not present, as expected\"\n  else\n    err $test \"AuditD is active with status ${status}\"\n  fi\n  echo \"$test:Finish\"\n}\n\ntestChrony() {\n  os_sku=$1\n  test=\"testChrony\"\n  echo \"$test:Start\"\n\n  # ---- Test Setup ----\n  # Test ntp is not active\n  status=$(systemctl show -p SubState --value ntp)\n  if [ $status == 'dead' ]; then\n    echo $test \"ntp is removed, as expected\"\n  else\n    err $test \"ntp is active with status ${status}\"\n  fi\n  #test chrony is running\n  #if mariner check chronyd, else check chrony\n  os_chrony=\"chrony\"\n  if [[ \"$os_sku\" == \"CBLMariner\" ]]; then\n    os_chrony=\"chronyd\"\n  fi\n  status=$(systemctl show -p SubState --value $os_chrony)\n  if [ $status == 'running' ]; then\n    echo $test \"$os_chrony is running, as expected\"\n  else\n    err $test \"$os_chrony is not running with status ${status}\"\n  fi\n\n  #test if chrony corrects time\n  if [ $os_sku == 'CBLMariner' ]; then\n    echo $test \"exiting without checking chrony time correction\"\n    echo $test \"reenable after Mariner updates the chrony config in base image\"\n    echo \"$test:Finish\"\n    return\n  fi\n  initialDate=$(date +%s)\n  date --set \"27 Feb 2021\"\n  for i in $(seq 1 10); do\n    newDate=$(date +%s)\n    if (($newDate > $initialDate)); then\n      echo \"$os_chrony readjusted the system time correctly\"\n      break\n    fi\n    sleep 10\n    echo \"${i}: retrying: check if chrony modified the time\"\n  done\n  if (($i == 10)); then\n    err $test \"$os_chrony failed to readjust the system time\"\n  fi\n  echo \"$test:Finish\"\n}\n\ntestFips() {\n  test=\"testFips\"\n  echo \"$test:Start\"\n  os_version=$1\n  enable_fips=$2\n\n  if [[ (${os_version} == \"18.04\" || ${os_version} == \"20.04\" || ${os_version} == \"V2\") && ${enable_fips,,} == \"true\" ]]; then\n    kernel=$(uname -r)\n    if [[ -f /proc/sys/crypto/fips_enabled ]]; then\n      fips_enabled=$(cat /proc/sys/crypto/fips_enabled)\n      if [[ \"${fips_enabled}\" == \"1\" ]]; then\n        echo \"FIPS is enabled.\"\n      else\n        err $test \"content of /proc/sys/crypto/fips_enabled is not 1.\"\n      fi\n    else\n      err $test \"FIPS is not enabled.\"\n    fi\n\n    if [[ ${os_version} == \"18.04\" || ${os_version} == \"20.04\" ]]; then\n      if [[ -f /usr/src/linux-headers-${kernel}/Makefile ]]; then\n        echo \"fips header files exist.\"\n      else\n        err $test \"fips header files don't exist.\"\n      fi\n    fi\n  fi\n\n  echo \"$test:Finish\"\n}\n\ntestKubeBinariesPresent() {\n  test=\"testKubeBinaries\"\n  echo \"$test:Start\"\n  containerRuntime=$1\n  binaryDir=/usr/local/bin\n  k8sVersions=\"$(jq -r .kubernetes.versions[] </opt/azure/manifest.json)\"\n  for patchedK8sVersion in ${k8sVersions}; do\n    # Only need to store k8s components >= 1.19 for containerd VHDs\n    if (($(echo ${patchedK8sVersion} | cut -d\".\" -f2) < 19)) && [[ ${containerRuntime} == \"containerd\" ]]; then\n      continue\n    fi\n    # strip the last .1 as that is for base image patch for hyperkube\n    if grep -iq hotfix <<<${patchedK8sVersion}; then\n      # shellcheck disable=SC2006\n      patchedK8sVersion=$(echo ${patchedK8sVersion} | cut -d\".\" -f1,2,3,4)\n    else\n      patchedK8sVersion=$(echo ${patchedK8sVersion} | cut -d\".\" -f1,2,3)\n    fi\n    k8sVersion=$(echo ${patchedK8sVersion} | cut -d\"_\" -f1 | cut -d\"-\" -f1 | cut -d\".\" -f1,2,3)\n    kubeletDownloadLocation=\"$binaryDir/kubelet-$k8sVersion\"\n    kubectlDownloadLocation=\"$binaryDir/kubectl-$k8sVersion\"\n    kubeletInstallLocation=\"/usr/local/bin/kubelet\"\n    kubectlInstallLocation=\"/usr/local/bin/kubectl\"\n    #Test whether the binaries have been extracted\n    if [ ! -s $kubeletDownloadLocation ]; then\n      err $test \"Binary ${kubeletDownloadLocation} does not exist\"\n    fi\n    if [ ! -s $kubectlDownloadLocation ]; then\n      err $test \"Binary ${kubectlDownloadLocation} does not exist\"\n    fi\n    #Test whether the installed binary version is indeed correct\n    mv $kubeletDownloadLocation $kubeletInstallLocation\n    mv $kubectlDownloadLocation $kubectlInstallLocation\n    chmod a+x $kubeletInstallLocation $kubectlInstallLocation\n    echo \"kubectl version\"\n    kubectlLongVersion=$(kubectl version 2>/dev/null)\n    if [[ ! $kubectlLongVersion =~ $k8sVersion ]]; then\n      err $test \"The kubectl version is not correct: expected kubectl version $k8sVersion existing: $kubectlLongVersion\"\n    fi\n    echo \"kubelet version\"\n    kubeletLongVersion=$(kubelet --version 2>/dev/null)\n    if [[ ! $kubeletLongVersion =~ $k8sVersion ]]; then\n      err $test \"The kubelet version is not correct: expected kubelet version $k8sVersion existing: $kubeletLongVersion\"\n    fi\n  done\n  echo \"$test:Finish\"\n}\n\ntestKubeProxyImagesPulled() {\n  test=\"testKubeProxyImagesPulled\"\n  echo \"$test:Start\"\n  containerRuntime=$1\n  containerdKubeProxyImages=$(jq .containerdKubeProxyImages <${KUBE_PROXY_IMAGES_FILEPATH})\n\n  if [ $containerRuntime == 'containerd' ]; then\n    testImagesPulled containerd \"$containerdKubeProxyImages\"\n  else\n    err $test \"unsupported container runtime $containerRuntime\"\n    return\n  fi\n  echo \"$test:Finish\"\n}\n\n# nc and nslookup is used in CSE to check connectivity\ntestCriticalTools() {\n  test=\"testCriticalTools\"\n  echo \"$test:Start\"\n  if ! nc -h 2>/dev/null; then\n    err $test \"nc is not installed\"\n  else\n    echo $test \"nc is installed\"\n  fi\n\n  if ! nslookup -version 2>/dev/null; then\n    err $test \"nslookup is not installed\"\n  else\n    echo $test \"nslookup is installed\"\n  fi\n\n  echo \"$test:Finish\"\n}\n\ntestCustomCAScriptExecutable() {\n  test=\"testCustomCAScriptExecutable\"\n  permissions=$(stat -c \"%a\" /opt/scripts/update_certs.sh)\n  if [ \"$permissions\" != \"755\" ]; then\n    err $test \"/opt/scripts/update_certs.sh has incorrect permissions\"\n  fi\n  echo \"$test:Finish\"\n}\n\ntestCustomCATimerNotStarted() {\n  isUnitThere=$(systemctl list-units --type=timer | grep update_certs.timer)\n  if [[ -n \"$isUnitThere\" ]]; then\n    err $test \"Custom CA timer was loaded, but shouldn't be\"\n  fi\n  echo \"$test:Finish\"\n}\n\ntestVHDBuildLogsExist() {\n  test=\"testVHDBuildLogsExist\"\n  if [ -f $VHD_LOGS_FILEPATH ]; then\n    echo \"detected vhd logs file\"\n  else\n    err $test \"File $VHD_LOGS_FILEPATH not found\"\n    exit $ERR_VHD_FILE_NOT_FOUND\n  fi\n  echo \"$test:Finish\"\n}\n\n# Ensures that /etc/login.defs is valid. This is a best-effort test, as we aren't going to\n# re-implement everything that uses this file.\ntestLoginDefs() {\n  test=\"testLoginDefs\"\n  local settings_file=/etc/login.defs\n  echo \"$test:Start\"\n\n  # Existence and format check. Based on https://man7.org/linux/man-pages/man5/login.defs.5.html,\n  # we expect the file to have lines that are either a comment or \"NAME VALUE\" pairs. Arbitrary whitespace\n  # is allowed before NAME and between NAME and VALUE. NAME seems tobe upper-case and '_'.\n  # all-caps and include letters and '_'. Values can be anything, so we make sure they're printable.\n  testSettingFileFormat $test $settings_file '^[[:space:]]*(#|$)' '^[[:space:]]*[A-Z_]+[[:space:]]+[^[:cntrl:]]+$'\n\n  # Look for the settings we specifically set in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh\n  # and ensure they're set to the values we expect.\n  echo \"$test: Checking specific settings in $settings_file\"\n  testSetting $test $settings_file PASS_MAX_DAYS '^[[:space:]]*PASS_MAX_DAYS[[:space:]]' ' ' 90\n  testSetting $test $settings_file PASS_MIN_DAYS '^[[:space:]]*PASS_MIN_DAYS[[:space:]]+' ' ' 7\n  testSetting $test $settings_file UMASK '^[[:space:]]*UMASK[[:space:]]+' ' ' 027\n\n  echo \"$test:Finish\"\n}\n\n# Ensures that /etc/default/useradd is valid. This is a best-effort test, as we aren't going to\n# re-implement everything that uses this file.\ntestUserAdd() {\n  test=\"testUserAdd\"\n  local settings_file=/etc/default/useradd\n  echo \"$test:Start\"\n\n  # Existence and format check. The man page https://www.man7.org/linux/man-pages/man8/useradd.8.html\n  # doesn't really state the format of the file, but experimentation and examples show that each\n  # line must be a comment or 'NAME=VALUE', where values can be empty or strings, and strings\n  # is pretty loose (any printable character).\n  testSettingFileFormat $test $settings_file '^[[:space:]]*(#|$)' '^[A-Z_]+=[^[:cntrl:]]*$'\n\n  # Look for the settings we specifically set in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh\n  # and ensure they're set to the values we expect.\n  echo \"$test: Checking specific settings in $settings_file\"\n  testSetting $test $settings_file INACTIVE '^INACTIVE=' '=' 30\n\n  # Double-check that the setting we set is actually used by useradd.\n  # Disable shellcheck warning about using '$?' in an if statement because we don't want\n  # the return value anyway and the ways it suggests reorganizing the if statement\n  # actually confuse it even more.\n  echo \"$test: Checking that INACTIVE is used by useradd\"\n  useradd -D | grep -E -v \"^INACTIVE=30$\" >/dev/null\n  # shellcheck disable=SC2181\n  if [ $? -ne 0 ]; then\n    err $test \"useradd is not using INACTIVE=30 from $settings_file\"\n  fi\n  echo \"$test: useradd is using INACTIVE=30 from $settings_file\"\n\n  echo \"$test:Finish\"\n}\n\ntestNetworkSettings() {\n  local test=\"testNetworkSettings\"\n  local settings_file=/etc/sysctl.d/60-CIS.conf\n  echo \"$test:Start\"\n\n  # Existence and format check. Based on the man page https://www.man7.org/linux/man-pages/man5/sysctl.conf.5.html\n  # we expect the file to have lines that are either a comment or \"NAME = VALUE\" pairs. Arbitrary whitespace\n  # is allowed before NAME and between NAME and VALUE. It can also just be \"NAME\" (no '='). Name seems to be\n  # lower-case and include letters and '_' and '.'. Value can be anything, so we make sure they're printable.\n  # If a line starts with '-', it has special meaning so we need to allow that too.\n  testSettingFileFormat $test $settings_file '^[[:space:]]*(#|;|$)' '^-{0,1}[[:space:]]*[a-z\\.0-9_\\*]+[[:space:]]*$' '^-{0,1}[[:space:]]*[a-z\\.0-9_\\*]+[[:space:]]*=[[:space:]]*[^[:cntrl:]]*$'\n\n  echo \"$test:End\"\n}\n\n# Tests that the modes on the cron-related files and directories in /etc are set correctly, per the\n# function assignFilePermissions in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh.\ntestCronPermissions() {\n  local test=\"testCronPermissions\"\n  echo \"$test:Start\"\n\n  declare -A required_pathss=(\n    ['/etc/cron.allow']=640\n    ['/etc/cron.hourly']=600\n    ['/etc/cron.daily']=600\n    ['/etc/cron.weekly']=600\n    ['/etc/cron.monthly']=600\n    ['/etc/cron.d']=600\n  )\n\n  declare -A optional_paths=(\n    ['/etc/crontab']=600\n  )\n\n  declare -a disallowed_paths=(\n    '/etc/cron.deny'\n  )\n\n  echo \"$test: Checking required paths\"\n  for path in \"${!required_path[@]}\"; do\n    checkPathPermissions $test $path ${required_paths[$path]} 1\n  done\n\n  echo \"$test: Checking optional paths\"\n  for path in \"${!optional_paths[@]}\"; do\n    checkPathPermissions $test $path ${optional_paths[$path]} 0\n  done\n\n  echo \"$test: Checking disallowed paths\"\n  for path in \"${disallowed_paths[@]}\"; do\n    checkPathDoesNotExist $test $path\n  done\n\n  echo \"$test:Finish\"\n}\n\n# Tests that /etc/systemd/coredump.conf is set correctly, per the function\n# configureCoreDump in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh.\ntestCoreDumpSettings() {\n  local test=\"testCoreDumpSettings\"\n  local settings_file=/etc/systemd/coredump.conf\n  echo \"$test:Start\"\n\n  # Existence and format check. The man page https://www.man7.org/linux/man-pages/man5/coredump.conf.5.html\n  # doesn't really state the format of the file, but show that each line must be one o:\n  #   A comment starting with '#'.\n  #   A section heading -- this file is only supposed to have '[Coredump]'\n  #   Settings, which take the form 'NAME=VALUE', where values can be empty or strings, and strings\n  #   is pretty loose (more or less any printable character).\n  testSettingFileFormat $test $settings_file '^(#|$)' '^\\[Coredump\\]$' '^[A-Za-z_]+=[^[:cntrl:]]*$'\n\n  # Look for the settings we specifically set in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh\n  # and ensure they're set to the values we expect.\n  echo \"$test: Checking specific settings in $settings_file\"\n  testSetting $test $settings_file 'Storage' '^Storage=' '=' 'none'\n  testSetting $test $settings_file 'ProcessSizeMax' '^ProcessSizeMax=' '=' '0'\n\n  echo \"$test:Finish\"\n}\n\n# Tests that the nfs-server systemd service is masked, per the function\n# configuremaskNfsServerNfsServer in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh.\ntestNfsServerService() {\n  local test=\"testNfsServerService\"\n  local service_name=\"nfs-server.service\"\n  echo \"$test:Start\"\n\n  # is-enabled returns 'masked' if the service is masked and an empty\n  # string if the service is not installed. Either is fine.\n  echo \"$test: Checking that $service_name is masked\"\n  local is_enabled=\n  is_enabled=$(systemctl is-enabled $service_name 2>/dev/null)\n  if [[ \"${is_enabled}\" == \"masked\" ]]; then\n    echo \"$test: $service_name is correctly masked\"\n  elif [[ \"${is_enabled}\" == \"\" ]]; then\n    echo \"$test: $service_name is not installed, which is fine\"\n  else\n    err $test \"$service_name is not masked\"\n  fi\n\n  echo \"$test:Finish\"\n}\n\n# Tests that the pam.d settings are set correctly, per the function\n# addFailLockDir in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh.\ntestPamDSettings() {\n  local os_sku=\"${1}\"\n  local os_version=\"${2}\"\n  local test=\"testPamDSettings\"\n  local settings_file=/etc/security/faillock.conf\n  echo \"$test:Start\"\n\n  # We only want to run this test on Mariner 2.0\n  # So if it's anything else, report that we're skipping the test and bail.\n  if [[ \"${os_sku}\" != \"CBLMariner\" || \"${os_version}\" != \"2.0\" ]]; then\n    echo \"$test: Skipping test on ${os_sku} ${os_version}\"\n  else\n\n    # Existence and format check. The man page https://www.man7.org/linux/man-pages/man5/faillock.conf.5.html\n    # describes the following format for each line:\n    #   Comments start with '#'.\n    #   Blank lines are ignored.\n    #   Lines are of in two forms:\n    #       'setting = value', where settings are lower-case and include '_'\n    #       'setting'\n    #   Whitespace at beginning and end of line, along with around the '=' is ignored.\n    testSettingFileFormat $test $settings_file '^(#|$)' '^[[:space:]]*$' '^[[:space:]]*[a-z_][[:space:]]*' '^[[:space:]]*[a-z_]+[[:space::]]*=[^[:cntrl:]]*$'\n\n    # Look for the setting we specifically set in <repo-root>/parts/linux/cloud-init/artifacts/cis.sh\n    # and ensure it's set to the values we expect.\n    echo \"$test: Checking specific settings in $settings_file\"\n    testSetting $test $settings_file 'dir' '^[[:space:]]*dir[[:space:]]*=' '=' '/var/log/faillock'\n  fi\n\n  echo \"$test:Finish\"\n}\n\n# Checks a single file or directory's permissions.\n# Parameters:\n#  test: The name of the test.\n#  path: The path to check.\n#  expected_perms: The expected permissions.\n#  required: If 1, the path must exist. If 0, the path is optional.\nfunction checkPathPermissions() {\n  local test=\"$1\"\n  local path=\"$2\"\n  local expected_perms=\"$3\"\n  local required=\"$4\"\n\n  echo \"$test: Checking permissions for '$path'\"\n  if [ ! -e \"$path\" ]; then\n    if [ \"$required\" -eq 1 ]; then\n      err $test \"Required path '$path' does not exist\"\n    else\n      echo \"$test: Optional path '$path' does not exist\"\n    fi\n  else\n    local actual_perms=\n    actual_perms=$(stat -c %a $path)\n    if [ \"$actual_perms\" != \"$expected_perms\" ]; then\n      err $test \"Path '$path' has permissions $actual_perms; expected $expected_perms\"\n    else\n      echo \"$test: $path has correct permissions $actual_perms\"\n    fi\n  fi\n}\n\n# Checks that a single file or directory does not exist.\n# Parameters:\n#  test: The name of the test.\n#  path: The path to check.\nfunction checkPathDoesNotExist() {\n  local test=\"$1\"\n  local path=\"$2\"\n\n  echo \"$test: Checking that '$path' does not exist\"\n  if [ -e \"$path\" ]; then\n    err $test \"Path '$path' exists\"\n  else\n    echo \"$test: $path correctly does not exist\"\n  fi\n}\n\n# Tests a setting file's format. This is a simple, line-by line check.\n# Parameters:\n#  test: The name of the test.\n#  settings_file: The path to the settings file.\n#  Remaining parameters are regexes used for validation.\n#\n#  The file will be tested for existence, then each line of the file is expected\n#  to match at least one of the regexes.\n#\n#  Any lines that match none of the regexes are printed to stderr.\n#  Returns 0 if all lines are valid, 1 otherwise.\ntestSettingFileFormat() {\n  local test=\"$1\"\n  local settings_file=\"$2\"\n  shift 2\n\n  # If the file doesn't exist, everything is broken.\n  echo \"$test: Checking existence of $settings_file\"\n  if [ ! -f $settings_file ]; then\n    err $test \"File $settings_file not found\"\n    return 1\n  fi\n  echo \"$test: $settings_file exists\"\n\n  # Loop through each line in the file.\n  # For each line, each regex is checked. If none match, the line is invalid.\n  echo \"$test: Checking format of $settings_file\"\n  local line_num=1\n  local line\n  local regex\n  local valid=0\n  local any_invalid=0\n  while read -r line; do\n    line_num=$((line_num + 1))\n    for regex in \"$@\"; do\n      if [[ \"$line\" =~ $regex ]]; then\n        valid=1\n        break\n      fi\n    done\n\n    if [ $valid -eq 0 ]; then\n      any_invalid=1\n      err $test \"Invalid line $line_num in $settings_file: '$line'\"\n    fi\n\n    valid=0\n  done <$settings_file\n\n  if [ $any_invalid -eq 0 ]; then\n    echo \"$test: $settings_file is valid\"\n  fi\n\n  return $any_invalid\n}\n\n# Tests an individual setting in a settings file, ensuring it's set with the correct value.\n# Note: This assumes the file format is generally correct (see function testSettingFileFormat).\n# Parameters:\n#  test: The name of the test.\n#  settings_file: The path to the settings file.\n#  setting_name: The name of the setting to check.\n#  setting_line_regex: A regex that matches the line that contains the setting. This should be\n#                      setting-specific -- if you want to check setting 'FOO', this should look\n#                      specifically for 'FOO' in the line.\n#  setting_value_awk_separator: The separator to use when parsing the setting value from the line.\n#                               This is used in an awk command, so it should be a single character.\n#  expected_value: The expected value of the setting.\ntestSetting() {\n  local test=\"$1\"\n  local settings_file=\"$2\"\n  local setting_name=\"$3\"\n  local setting_line_regex=\"$4\"\n  local setting_value_awk_separator=\"$5\"\n  local expected_value=\"$6\"\n\n  echo \"$test: Checking setting '$setting_name' has value '$expected_value' in $settings_file\"\n  # Get the lines that match the setting name. Note that this will come with the line number.\n  local value_lines=\n  value_lines=$(grep -E -n \"${setting_line_regex}\" \"${settings_file}\")\n\n  # If the setting isn't present, that's an error.\n  if [ -z \"$value_lines\" ]; then\n    err $test \"Setting '$setting_name' not found in $settings_file\"\n    return 1\n  fi\n\n  # If the setting is present more than once, that's an error.\n  if [ $(echo \"$value_lines\" | wc -l) -gt 1 ]; then\n    err $test \"Setting '$setting_name' found more than once in $settings_file. See below for lines.\"\n    echo \"$value_lines\" >>/dev/stderr\n    return 1\n  fi\n\n  # Get the value of the setting and test it. To do this we must strip out the line number. We also\n  # trim leading and trailing whitespace around the value with xargs.\n  local value=\n  value=$(echo \"$value_lines\" | sed -E 's/^([0-9]+:)//' | awk -F \"$setting_value_awk_separator\" '{print $2}' | xargs)\n  if [ \"$value\" != \"$expected_value\" ]; then\n    err $test \"Setting '$setting_name' has value '$value' in $settings_file, expected '$expected_value'\"\n    return 1\n  fi\n\n  echo \"$test: Setting '$setting_name' has value correct value '$expected_value' in $settings_file\"\n  return 0\n}\n\nstring_replace() {\n  echo ${1//\\*/$2}\n}\n\n# As we call these tests, we need to bear in mind how the test results are processed by the\n# the caller in run-tests.sh. That code uses az vm run-command invoke to run this script\n# on a VM. It then looks at stderr to see if any errors were reported. Notably it doesn't\n# look the exit code of this script -- in fact, it can't due to a limitation in the\n# run-command invoke command. So we need to be careful to report errors to stderr\n#\n# We should also avoid early exit from the test run -- like if a command fails with\n# an exit rather than a return -- because that prevents other tests from running.\ntestVHDBuildLogsExist\ntestCriticalTools\ntestFilesDownloaded $CONTAINER_RUNTIME\ntestImagesPulled $CONTAINER_RUNTIME \"$(cat $COMPONENTS_FILEPATH)\"\ntestChrony $OS_SKU\ntestAuditDNotPresent\ntestFips $OS_VERSION $ENABLE_FIPS\ntestKubeBinariesPresent $CONTAINER_RUNTIME\ntestKubeProxyImagesPulled $CONTAINER_RUNTIME\n# Commenting out testImagesRetagged because at present it fails, but writes errors to stdout\n# which means the test failures haven't been caught. It also calles exit 1 on a failure,\n# which means the rest of the tests aren't being run.\n# See https://msazure.visualstudio.com/CloudNativeCompute/_backlogs/backlog/Node%20Lifecycle/Features/?workitem=24246232\n# testImagesRetagged $CONTAINER_RUNTIME\ntestCustomCAScriptExecutable\ntestCustomCATimerNotStarted\ntestLoginDefs\ntestUserAdd\ntestNetworkSettings\ntestCronPermissions\ntestCoreDumpSettings\ntestNfsServerService\ntestPamDSettings $OS_SKU $OS_VERSION\n", "num_lines": 789}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\ncomponents=$(jq .ContainerImages[] --monochrome-output --compact-output < vhdbuilder/packer/components.json)\nfor component in ${components[*]}; do\n\tdownloadURL=$(echo ${component} | jq .downloadURL)\n\tdownloadURL=$(echo ${downloadURL//\\*/} | jq 'sub(\".com/\" ; \".com/v2/\") | sub(\":\" ; \"/tags/list\")' -r)\n\tamd64OnlyVersionsStr=$(echo \"${component}\" | jq .amd64OnlyVersions -r)\n\tmultiArchVersionsStr=$(echo \"${component}\" | jq .multiArchVersions -r)\n\tamd64OnlyVersions=\"\"\n\tif [[ ${amd64OnlyVersionsStr} != null ]]; then\n\t\tamd64OnlyVersions=$(echo \"${amd64OnlyVersionsStr}\" | jq -r \".[]\")\n\tfi\n\tmultiArchVersions=\"\"\n\tif [[ ${multiArchVersionsStr} != null ]]; then\n\t\tmultiArchVersions=$(echo \"${multiArchVersionsStr}\" | jq -r \".[]\")\n\tfi\n\tarch=$(uname -m)\n\tif [[ ${arch,,} == \"aarch64\" || ${arch,,} == \"arm64\"  ]]; then\n\t\tversionsToBeDownloaded=\"${multiArchVersions}\"\n\telse\n\t\tversionsToBeDownloaded=\"${amd64OnlyVersions} ${multiArchVersions}\"\n\tfi\n\n\tvalidVersions=$(curl -sL https://$downloadURL | jq .tags[])\n\t\n\tfor versionToBeDownloaded in ${versionsToBeDownloaded[*]}; do\n\t\t[[ ${validVersions[*]}  =~  ${versionToBeDownloaded} ]] || (echo \"${versionToBeDownloaded} does not exist in ${downloadURL}\" && exit 1)\n\tdone\ndone\n", "num_lines": 31}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eux\nLINUX_SCRIPT_PATH=\"linux-vhd-content-test.sh\"\nWIN_CONFIGURATION_SCRIPT_PATH=\"generate-windows-vhd-configuration.ps1\"\nWIN_SCRIPT_PATH=\"windows-vhd-content-test.ps1\"\nTEST_RESOURCE_PREFIX=\"vhd-test\"\nTEST_VM_ADMIN_USERNAME=\"azureuser\"\n\nset +x\nTEST_VM_ADMIN_PASSWORD=\"TestVM@$(date +%s)\"\nset -x\n\nif [ \"$OS_TYPE\" == \"Linux\" ]; then\n  if [ \"$IMG_SKU\" == \"20_04-lts-cvm\" ] || [ \"$OS_VERSION\" == \"V1\" ] && [ \"$OS_SKU\" == \"CBLMariner\" ]; then\n    echo \"Skipping tests for CVM 20.04 and Mariner 1.0\"\n    exit 0\n  fi\nfi\n\nRESOURCE_GROUP_NAME=\"$TEST_RESOURCE_PREFIX-$(date +%s)-$RANDOM\"\naz group create --name $RESOURCE_GROUP_NAME --location ${AZURE_LOCATION} --tags 'source=AgentBaker'\n\n# defer function to cleanup resource group when VHD debug is not enabled\nfunction cleanup() {\n  if [[ \"$VHD_DEBUG\" == \"True\" ]]; then\n    echo \"VHD debug mode is enabled, please manually delete test vm resource group $RESOURCE_GROUP_NAME after debugging\"\n  else\n    echo \"Deleting resource group ${RESOURCE_GROUP_NAME}\"\n    az group delete --name $RESOURCE_GROUP_NAME --yes --no-wait\n  fi\n}\ntrap cleanup EXIT\n\nDISK_NAME=\"${TEST_RESOURCE_PREFIX}-disk\"\nVM_NAME=\"${TEST_RESOURCE_PREFIX}-vm\"\n\nif [ \"$MODE\" == \"default\" ]; then\n  az disk create --resource-group $RESOURCE_GROUP_NAME \\\n    --name $DISK_NAME \\\n    --source \"${OS_DISK_URI}\" \\\n    --query id\n  az vm create --name $VM_NAME \\\n    --resource-group $RESOURCE_GROUP_NAME \\\n    --attach-os-disk $DISK_NAME \\\n    --os-type $OS_TYPE \\\n    --public-ip-address \"\"\nelse \n  if [ \"$MODE\" == \"sigMode\" ]; then\n    id=$(az sig show --resource-group ${AZURE_RESOURCE_GROUP_NAME} --gallery-name ${SIG_GALLERY_NAME}) || id=\"\"\n    if [ -z \"$id\" ]; then\n      echo \"Shared Image gallery ${SIG_GALLERY_NAME} does not exist in the resource group ${AZURE_RESOURCE_GROUP_NAME} location ${AZURE_LOCATION}\"\n      exit 1\n    fi\n\n    id=$(az sig image-definition show \\\n      --resource-group ${AZURE_RESOURCE_GROUP_NAME} \\\n      --gallery-name ${SIG_GALLERY_NAME} \\\n      --gallery-image-definition ${SIG_IMAGE_NAME}) || id=\"\"\n    if [ -z \"$id\" ]; then\n      echo \"Image definition ${SIG_IMAGE_NAME} does not exist in gallery ${SIG_GALLERY_NAME} resource group ${AZURE_RESOURCE_GROUP_NAME}\"\n      exit 1\n    fi\n  fi\n\n  if [ -z \"${MANAGED_SIG_ID}\" ]; then\n    echo \"Managed Sig Id from packer-output is empty, unable to proceed...\"\n    exit 1\n  else\n    echo \"Managed Sig Id from packer-output is ${MANAGED_SIG_ID}\"\n    IMG_DEF=${MANAGED_SIG_ID}\n  fi\n\n  # In SIG mode, Windows VM requires admin-username and admin-password to be set,\n  # otherwise 'root' is used by default but not allowed by the Windows Image. See the error image below:\n  # ERROR: This user name 'root' meets the general requirements, but is specifically disallowed for this image. Please try a different value.\n  TARGET_COMMAND_STRING=\"\"\n  if [[ \"${ARCHITECTURE,,}\" == \"arm64\" ]]; then\n    TARGET_COMMAND_STRING+=\"--size Standard_D2pds_v5\"\n  elif [[ \"${FEATURE_FLAGS,,}\" == \"kata\" ]]; then\n    TARGET_COMMAND_STRING=\"--size Standard_D4ds_v5\"\n  fi\n\n  if [[ \"${OS_TYPE}\" == \"Linux\" && \"${ENABLE_TRUSTED_LAUNCH}\" == \"True\" ]]; then\n    if [[ -n \"$TARGET_COMMAND_STRING\" ]]; then\n      # To take care of Mariner Kata TL images\n      TARGET_COMMAND_STRING+=\" \"\n    fi\n    TARGET_COMMAND_STRING+=\"--security-type TrustedLaunch --enable-secure-boot true --enable-vtpm true\"\n  fi\n\n  az vm create \\\n      --resource-group $RESOURCE_GROUP_NAME \\\n      --name $VM_NAME \\\n      --image $IMG_DEF \\\n      --admin-username $TEST_VM_ADMIN_USERNAME \\\n      --admin-password $TEST_VM_ADMIN_PASSWORD \\\n      --public-ip-address \"\" \\\n      ${TARGET_COMMAND_STRING}\n      \n  echo \"VHD test VM username: $TEST_VM_ADMIN_USERNAME, password: $TEST_VM_ADMIN_PASSWORD\"\nfi\n\ntime az vm wait -g $RESOURCE_GROUP_NAME -n $VM_NAME --created\n\nFULL_PATH=$(realpath $0)\nCDIR=$(dirname $FULL_PATH)\n\nif [ \"$OS_TYPE\" == \"Linux\" ]; then\n  if [[ -z \"${ENABLE_FIPS// }\" ]]; then\n    ENABLE_FIPS=\"false\"\n  fi\n\n  SCRIPT_PATH=\"$CDIR/$LINUX_SCRIPT_PATH\"\n  for i in $(seq 1 3); do\n    ret=$(az vm run-command invoke --command-id RunShellScript \\\n      --name $VM_NAME \\\n      --resource-group $RESOURCE_GROUP_NAME \\\n      --scripts @$SCRIPT_PATH \\\n      --parameters ${CONTAINER_RUNTIME} ${OS_VERSION} ${ENABLE_FIPS} ${OS_SKU} ${GIT_BRANCH}) && break\n    echo \"${i}: retrying az vm run-command\"\n  done\n  # The error message for a Linux VM run-command is as follows:\n  #  \"value\": [\n  #    {\n  #      \"code\": \"ProvisioningState/succeeded\",\n  #      \"displayStatus\": \"Provisioning succeeded\",\n  #      \"level\": \"Info\",\n  #      \"message\": \"Enable succeeded: \\n[stdout]\\n\\n[stderr]\\ntestImagesPulled:Error: Image mcr.microsoft.com/azure-policy/policy-kubernetes-addon-prod:prod_20201015.1 has NOT been pulled\n  # \\n\",\n  #      \"time\": null\n  #    }\n  #  ]\n  #  We have extract the message field from the json, and get the errors outputted to stderr + remove \\n\n  errMsg=$(echo -e $(echo $ret | jq \".value[] | .message\" | grep -oP '(?<=stderr]).*(?=\\\\n\")'))\n  echo $errMsg\n  if [[ $errMsg != '' ]]; then\n    exit 1\n  fi\nelse\n  SCRIPT_PATH=\"$CDIR/../$WIN_CONFIGURATION_SCRIPT_PATH\"\n  echo \"Run $SCRIPT_PATH\"\n  az vm run-command invoke --command-id RunPowerShellScript \\\n    --name $VM_NAME \\\n    --resource-group $RESOURCE_GROUP_NAME \\\n    --scripts @$SCRIPT_PATH \\\n    --output json\n\n  SCRIPT_PATH=\"$CDIR/$WIN_SCRIPT_PATH\"\n  echo \"Run $SCRIPT_PATH\"\n  ret=$(az vm run-command invoke --command-id RunPowerShellScript \\\n    --name $VM_NAME \\\n    --resource-group $RESOURCE_GROUP_NAME \\\n    --scripts @$SCRIPT_PATH \\\n    --output json \\\n    --parameters \"containerRuntime=${CONTAINER_RUNTIME}\" \"windowsSKU=${WINDOWS_SKU}\")\n  # An example of failed run-command output:\n  # {\n  #   \"value\": [\n  #     {\n  #       \"code\": \"ComponentStatus/StdOut/succeeded\",\n  #       \"displayStatus\": \"Provisioning succeeded\",\n  #       \"level\": \"Info\",\n  #       \"message\": \"c:\\akse-cache\\containerd\\containerd-0.0.87-public.zip is cached as expected\n  # c:\\akse-cache\\win-vnet-cni\\azure-vnet-cni-singletenancy-windows-amd64-v1.1.2.zip is cached as expected\n  # ... ...\n  # \"\n  #       \"time\": null\n  #     },\n  #     {\n  #       \"code\": \"ComponentStatus/StdErr/succeeded\",\n  #       \"displayStatus\": \"Provisioning succeeded\",\n  #       \"level\": \"Info\",\n  #       \"message\": \"Test-FilesToCacheOnVHD : File c:\\akse-cache\\win-k8s\\v1.15.10-azs-1int.zip does not exist\n  # At C:\\Packages\\Plugins\\Microsoft.CPlat.Core.RunCommandWindows\\1.1.5\\Downloads\\script0.ps1:146 char:1\n  # + Test-FilesToCacheOnVHD\n  # + ~~~~~~~~~~~~~~~~~~~~~~\n  #     + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException\n  #     + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-FilesToCacheOnVHD\n  #  \",\n  #       \"time\": null\n  #     }\n  #   ]\n  # }\n  # we have to use `-E` to disable interpretation of backslash escape sequences, for jq cannot process string\n  # with a range of control characters not escaped as shown in the error below:\n  #   Invalid string: control characters from U+0000 through U+001F must be escaped\n  errMsg=$(echo -E $ret | jq '.value[]  | select(.code == \"ComponentStatus/StdErr/succeeded\") | .message')\n  # a successful errMsg should be '\"\"' after parsed by `jq`\n  if [[ $errMsg != \\\"\\\" ]]; then\n    exit 1\n  fi\nfi\n\necho \"Tests Run Successfully\"", "num_lines": 194}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n[[ -z \"${MANAGED_IMAGE_NAME}\" ]] && echo \"MANAGED_IMAGE_NAME is not set\" && exit 1\n[[ -z \"${MANAGED_IMAGE_RG_NAME}\" ]] && echo \"MANAGED_IMAGE_RG_NAME is not set\" && exit 1\n\necho \"Deleting managed image ${MANAGED_IMAGE_NAME}, from resource group ${MANAGED_IMAGE_RG_NAME}\"\naz image delete \\\n   --resource-group ${MANAGED_IMAGE_RG_NAME} \\\n   --name ${MANAGED_IMAGE_NAME}", "num_lines": 8}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Create the necessary infrastructure if it doesn't exist, so that we can publish the SIG image version\n[[ -z \"${CLIENT_ID}\" ]] && echo \"CLIENT_ID is not set\" && exit 1\n[[ -z \"${CLIENT_SECRET}\" ]] && echo \"CLIENT_SECRET is not set\" && exit 1\n[[ -z \"${TENANT_ID}\" ]] && echo \"TENANT_ID is not set\" && exit 1\n[[ -z \"${SUBSCRIPTION_ID}\" ]] && echo \"SUBSCRIPTION_ID is not set\" && exit 1\n[[ -z \"${REGION}\" ]] && echo \"REGION is not set\" && exit 1\n\n[[ -z \"${RG_NAME}\" ]] && echo \"RG_NAME is not set\" && exit 1\n[[ -z \"${OS_NAME}\" ]] && echo \"OS_NAME is not set\" && exit 1\n[[ -z \"${GALLERY_NAME}\" ]] && echo \"GALLERY_NAME is not set\" && exit 1\n[[ -z \"${IMAGEDEFINITION_NAME}\" ]] && echo \"IMAGEDEFINITION_NAME is not set\" && exit 1\n[[ -z \"${HYPERV_GENERATION}\" ]] && echo \"HYPERV_GENERATION is not set\" && exit 1\n\necho \"az login --service-principal -u ${CLIENT_ID} -p *** --tenant ${TENANT_ID}\"\naz login --service-principal -u ${CLIENT_ID} -p ${CLIENT_SECRET} --tenant ${TENANT_ID}\n\necho \"az account set --subscription ${SUBSCRIPTION_ID}\"\naz account set --subscription ${SUBSCRIPTION_ID}\n\n echo \"Check if Resource Group exists, if not create it\"\n id=$(az group show --name ${RG_NAME})\n if [ -z \"$id\" ] ; then\n   echo \"Creating resource group ${RG_NAME} in ${REGION} region\"\n   az group create --name ${RG_NAME} --location ${REGION}\n fi\n\n echo \"Check if Shared Image Gallery exists, if not create it\"\n id=$(az sig show --resource-group ${RG_NAME} --gallery-name ${GALLERY_NAME})\n if [ -z \"$id\" ]; then\n   echo \"Creating Shared Image Gallery ${GALLERY_NAME} in the resource group ${RG_NAME}\"\n   az sig create --resource-group ${RG_NAME} --gallery-name ${GALLERY_NAME} --location ${REGION}\n fi\n\n echo \"Check if SIG imagedefnition exists, if not create it\"\n id=$(az sig image-definition show \\\n   --resource-group ${RG_NAME} \\\n   --gallery-name ${GALLERY_NAME} \\\n   --gallery-image-definition ${IMAGEDEFINITION_NAME})\n if [ -z \"$id\" ]; then\n   echo \"Creating image definition ${IMAGEDEFINITION_NAME} generation ${HYPERV_GENERATION} in Shared Image Gallery ${GALLERY_NAME} inside the resource group ${RG_NAME}\"\n   az sig image-definition create \\\n     --resource-group ${RG_NAME} \\\n     --gallery-name ${GALLERY_NAME} \\\n     --gallery-image-definition ${IMAGEDEFINITION_NAME} \\\n     --publisher microsoft-aks \\\n     --offer ${GALLERY_NAME} \\\n     --sku ${IMAGEDEFINITION_NAME} \\\n     --os-type ${OS_NAME} \\\n     --location ${REGION} \\\n     --hyper-v-generation ${HYPERV_GENERATION}\n fi\n\necho \"##vso[task.setvariable variable=RG_NAME;]$RG_NAME\"\necho \"##vso[task.setvariable variable=GALLERY_NAME;]$GALLERY_NAME\"\necho \"##vso[task.setvariable variable=IMAGEDEFINITION_NAME;]$IMAGEDEFINITION_NAME\"\n\necho \"##vso[task.setvariable variable=OS_NAME;]$OS_NAME\"\n", "num_lines": 60}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Create managed Image from VHD sas url and then publish the managed image into the already created shared image gallery\n\n[[ -z \"${REGION}\" ]] && echo \"REGION is not set\" && exit 1\n[[ -z \"${RG_NAME}\" ]] && echo \"RG_NAME is not set\" && exit 1\n[[ -z \"${GALLERY_NAME}\" ]] && echo \"GALLERY_NAME is not set\" && exit 1\n[[ -z \"${IMAGEDEFINITION_NAME}\" ]] && echo \"IMAGEDEFINITION_NAME is not set\" && exit 1\n[[ -z \"${IMAGE_VERSION}\" ]] && echo \"IMAGE_VERSION is not set\" && exit 1\n#TARGET_REGIONS must be set in the following format region=replicacount \"westus2=1 eastus=4 uksouth=3\"\n[[ -z \"${TARGET_CREATE_REGIONS}\" ]] && echo \"TARGET_CREATE_REGIONS is not set\" && exit 1\n[[ -z \"${MANAGED_IMAGE_RG_NAME}\" ]] && echo \"MANAGED_IMAGE_RG_NAME is not set\" && exit 1\n[[ -z \"${VHD_SOURCE}\" ]] && echo \"VHD_SOURCE is not set\" && exit 1\n[[ -z \"${OS_NAME}\" ]] && echo \"OS_NAME is not set\" && exit 1\n[[ -z \"${HYPERV_GENERATION}\" ]] && echo \"HYPERV_GENERATION is not set\" && exit 1\n\nMANAGED_IMAGE_NAME=\"MI_${REGION}_${GALLERY_NAME}_${IMAGEDEFINITION_NAME}_${IMAGE_VERSION}\"\n\n# TODO(qinhao): change image version pattern of Windows to ${WINDOWS_VERSION}.$(date +\"%y%m%d\"), e.g. 17763.1457.200909,\n# in which, WINDOWS_VERSION can be obtained from vhd-publishing-info.json in VHD building artifacts\n\necho \"Creating managed image ${MANAGED_IMAGE_NAME} from VHD, inside resource group ${MANAGED_IMAGE_RG_NAME}\"\ncreate_managed_image_command=\"az image create --resource-group ${MANAGED_IMAGE_RG_NAME} --name ${MANAGED_IMAGE_NAME} --os-type ${OS_NAME} --hyper-v-generation ${HYPERV_GENERATION} --source ${VHD_SOURCE}\"\neval $create_managed_image_command\n\necho \"Get managed image URI for the managed image ${MANAGED_IMAGE_NAME}\"\nsleep 1m\nMANAGED_IMAGE_URI=$(az image show --resource-group ${MANAGED_IMAGE_RG_NAME} --name ${MANAGED_IMAGE_NAME} -o json | jq -r \".id\")\n\necho \"publishing managed image to /resourcegroup/${RG_NAME}/galleries/${GALLERY_NAME}/images/${IMAGEDEFINITION_NAME}/versions/${IMAGE_VERSION} with 5 replcia count in ${TARGET_CREATE_REGIONS}\"\n \n az sig image-version create \\\n   --resource-group ${RG_NAME} \\\n   --gallery-name ${GALLERY_NAME} \\\n   --gallery-image-definition ${IMAGEDEFINITION_NAME} \\\n   --gallery-image-version ${IMAGE_VERSION} \\\n   --managed-image \"${MANAGED_IMAGE_URI}\" \\\n   --target-regions ${TARGET_CREATE_REGIONS} \\\n   --storage-account-type Premium_LRS \\\n   --replica-count 5\n\n\necho \"##vso[task.setvariable variable=MANAGED_IMAGE_NAME;]$MANAGED_IMAGE_NAME\"", "num_lines": 43}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Create managed Image from VHD sas url and then publish the managed image into the already created shared image gallery\n\n[[ -z \"${RG_NAME}\" ]] && echo \"RG_NAME is not set\" && exit 1\n[[ -z \"${GALLERY_NAME}\" ]] && echo \"GALLERY_NAME is not set\" && exit 1\n[[ -z \"${IMAGEDEFINITION_NAME}\" ]] && echo \"IMAGEDEFINITION_NAME is not set\" && exit 1\n[[ -z \"${IMAGE_VERSION}\" ]] && echo \"IMAGE_VERSION is not set\" && exit 1\n#TARGET_REGIONS must be set in the following format region=replicacount \"westus2=1 eastus=4 uksouth=3\"\n[[ -z \"${TARGET_REGIONS}\" ]] && echo \"TARGET_REGIONS is not set\" && exit 1\n\necho \"scaling the image version /resourcegroup/${RG_NAME}/galleries/${GALLERY_NAME}/images/${IMAGEDEFINITION_NAME}/versions/${IMAGE_VERSION} as follows ${TARGET_REGIONS}\"\n\n az sig image-version update \\\n   --resource-group ${RG_NAME} \\\n   --gallery-name ${GALLERY_NAME} \\\n   --gallery-image-definition ${IMAGEDEFINITION_NAME} \\\n   --gallery-image-version ${IMAGE_VERSION} \\\n   --target-regions ${TARGET_REGIONS} \\\n", "num_lines": 20}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -xeu\n\nrequired_env_vars=(\n    \"SKU_PREFIX\"\n    \"SKU_TEMPLATE_FILE\"\n    \"AZURE_TENANT_ID\"\n    \"AZURE_CLIENT_ID\"\n    \"AZURE_CLIENT_SECRET\"\n    \"PUBLISHER\"\n    \"OFFER\"\n    \"CONTAINER_RUNTIME\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nif [ ! -f \"$SKU_TEMPLATE_FILE\" ]; then\n    echo \"Could not find sku template file: ${SKU_TEMPLATE_FILE}!\"\n    exit 1\nfi\n\n# we use token as a workaround even after a successful login as a result of pub tool Authorization failure.\n# allow-no-subscriptions is safe because we have no sub-level operations\necho \"Get cloudpartner access token\"\naz login --service-principal -u $AZURE_CLIENT_ID -p $AZURE_CLIENT_SECRET --tenant $AZURE_TENANT_ID --allow-no-subscriptions\ntoken=$(az account get-access-token --resource https://cloudpartner.azure.com --query \"accessToken\" -o tsv)\nexport AZURE_TOKEN=$token\n\nls -lhR artifacts\nvhd_artifacts_path=\"publishing-info-2019\"\nif [[ ${CONTAINER_RUNTIME} = \"containerd\" ]]; then\n    vhd_artifacts_path=\"publishing-info-2019-containerd\"\nfi\nVHD_INFO=\"artifacts/vhd/${vhd_artifacts_path}/vhd-publishing-info.json\"\nif [ ! -f \"$VHD_INFO\" ]; then\n    echo \"Could not find VHD info file: ${VHD_INFO}!\"\n    exit 1\nfi\n\nshort_date=$(date +\"%y%m\")\npretty_date=$(date +\"%b %Y\")\nsku_id=\"${SKU_PREFIX}-${short_date}\"\necho \"Checking if offer contains SKU: $sku_id\"\n# Check if SKU already exists in offer\n(set -x; hack/tools/bin/pub skus list -p $PUBLISHER -o $OFFER | jq \".[] | .planId\" | tr -d '\"' | tee skus.txt)\necho \"\"\nif grep -q $sku_id skus.txt; then\n    echo \"Offer already has SKU\"\nelse\n    echo \"Creating new SKU\"\n    < $SKU_TEMPLATE_FILE sed s/{{ID}}/\"$sku_id\"/ | sed s/{{MONTH-YEAR}}/\"$pretty_date/\" | sed s/{{CONTAINER_RUNTIME}}/\"$CONTAINER_RUNTIME/\" > sku.json\n    echo \"\" ; cat sku.json ; echo \"\"\n    hack/tools/bin/pub skus put -p $PUBLISHER -o $OFFER -f sku.json ; echo \"\"\nfi\n\necho \"Vhd publishing info:\"\ncat $VHD_INFO\necho\n\n# Get VHD version info for vhd-publishing-info.json produced by previous pipeline stage\nvhd_url=$(< $VHD_INFO jq -r \".vhd_url\")\nredact_vhd_url=${vhd_url/\\?*/?***}\nimage_version=$(< $VHD_INFO jq -r \".image_version\")\n\n# generate media name\n# Media name must be under 63 characters\nmedia_name=\"${SKU_PREFIX}-${image_version}\"\nif [ \"${#media_name}\" -ge 63 ]; then\n\techo \"$media_name should be undr 63 characters\"\n\texit 1\nfi\n\npublished_date=$(date +\"%m/%d/%Y\")\npublished_image_label=\"AKS Base Image for Windows\"\npublished_image_description=\"AKS Base Image for Windows\"\necho \"publish image version to Marketplace\"\necho \"pubilsher: $PUBLISHER\"\necho \"offer: $OFFER\"\necho \"sku id: $sku_id\"\necho \"image version: $image_version\"\necho \"vhd url: $redact_vhd_url\"\necho \"media name: $media_name\"\necho \"published date: $published_date\"\necho \"image label: $published_image_label\"\necho \"image description: $published_image_description\"\necho \"\"\nset -x ; hack/tools/bin/pub versions put corevm -p $PUBLISHER -o $OFFER -s $sku_id --version $image_version --vhd-uri $vhd_url --media-name $media_name --label \"AKS Base Image for Windows\" --desc \"AKS Base Image for Windows\" --published-date \"$published_date\"", "num_lines": 92}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\n\nsource vhdbuilder/scripts/automate_helpers.sh\n\necho \"Triggering ev2 artifact pipeline with Build ID $1\"\n\nbuild_ids=$1\n\ntrigger_pipeline() {\n    pipeline_id=\"319030\"   # 317897 is the pipeline ID for ev2 artifacts pipeline\n    for build_id in $build_ids; do\n        echo \"Build ID for the release is $build_id\"\n        az pipelines variable update --name VHD_PIPELINE_RUN_ID --pipeline-id $pipeline_id --value $build_id  # Update the VHD_PIPELINE_RUN_ID with the build ID\n        # In case auth fails/other issue, we do not want the pipeline to run if the build ID was not correctly updated\n        if [[ $build_id != $(az pipelines variable list --pipeline-id $pipeline_id | jq -r '.VHD_PIPELINE_RUN_ID.value') ]]; then\n            echo \"Build ID failed to update, cancel operation\"\n            exit 1\n        else\n            echo \"Build ID successfully updated\"\n        fi\n\n        # Run the pipeline and fetch the run ID to poll for success later\n        run_id=$(az pipelines run --id $pipeline_id | jq -r '.id')\n        while ! az pipelines runs show --id $run_id | grep -q '\"result\": \"succeeded\"'; do\n            echo \"ev2 artifacts still running for build $build_id\"\n            sleep 100\n        done\n        echo \"ev2 artifacts successfully built for build $build_id\"\n    done\n}\n\ntrigger_pipeline", "num_lines": 33}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\n\nbuild_ids=$1\nglobal_image_version=\"${IMAGE_VERSION:=}\"\nfor build_id in $build_ids; do\n    for artifact in $(az pipelines runs artifact list --run-id $build_id | jq -r '.[].name'); do    # Retrieve what artifacts were published\n        # This loop is because of how the Image Version is set for builds. \n        # It uses the UTC time of when the build for a particular SKU ends. \n        # So in the past, it has happened that you trigger a build at say 3/4pm PST, \n        # some SKUs will have todays date some will have tomorrows based on when they are triggered because of UTC conversion\n        # TODO(amaheshwari): Change VHD script to use a common var for image version that is plumbed down to all SKUs\n        if [[ $artifact == *\"publishing-info\"* ]]; then\n            az pipelines runs artifact download --artifact-name $artifact --path $(pwd) --run-id $build_id\n            current_image_version=$(jq -r .image_version < vhd-publishing-info.json)\n            if [[ $global_image_version != $current_image_version ]]; then\n                if [[ -z $global_image_version ]]; then\n                    global_image_version=$current_image_version\n                else \n                    echo \"mismatched image, exiting\"\n                    exit 1\n                fi\n            fi\n        fi\n    done\ndone\n\necho $global_image_version\nrm -rf vhd-publishing-info.json", "num_lines": 29}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\nset_git_config() {\n    # git config needs to be set in the agent\n    git config --global user.email \"amaheshwari@microsoft.com\"\n    git config --global user.name \"anujmaheshwari1\"\n    git config --list\n}\n\nconfigure_az_devops() {\n    # Login to azure devops using PAT/System Access Token for artifacts and triggering ev2 builds\n    # TODO(amaheshwari): Use only PAT for both artifacts and builds\n    az extension add -n azure-devops\n\n    set +x\n    echo $1 | az devops login --organization=https://dev.azure.com/msazure\n    set -x\n    \n    az devops configure --defaults organization=https://dev.azure.com/msazure project=CloudNativeCompute\n}\n\ncreate_branch() {\n    # Create PR branch\n    echo \"Create branch named $1\"\n    git checkout master\n    git pull\n    git checkout -b $1\n}\n\ncreate_pull_request() {\n    # Commit current changes and create PR using curl\n    echo \"Image Version is $1\"\n    echo \"Branch Name is $3\"\n    echo \"PR is for $4\"\n\n    git remote set-url origin https://anujmaheshwari1:$2@github.com/Azure/AgentBaker.git  # Set remote URL with PAT\n    git add .\n    \n    if [[ $4 == \"ReleaseNotes\" ]]; then\n        git commit -m \"chore: release notes for release $1\"\n    else\n        git commit -m \"chore: bumping image version to $1\"\n    fi\n\n    git push -u origin $3 -f\n\n    set +x  # To avoid logging PAT during curl\n    curl \\\n        -X POST \\\n        https://api.github.com/repos/Azure/AgentBaker/pulls \\\n        -d '{\n            \"head\" : \"'$3'\", \n            \"base\" : \"master\", \n            \"title\" : \"chore: automated PR to update '$4' for '$1' VHD\", \n            \"body\" : \"This is an automated PR to bump '$4' for the VHD release with image version '$1'\"\n        }' \\\n        -u \"anujmaheshwari1:$2\"\n    set -x\n    \n    git checkout master # Checkout to master for subsequent stages of the pipeline\n}", "num_lines": 62}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\n\nsource vhdbuilder/scripts/automate_helpers.sh\n\necho \"Image version for release notes is $1\"\n\nimage_version=$1\nbuild_ids=$2\n\nset +x\ngithub_access_token=$3\nset -x\n\nbranch_name=releaseNotes/$1\npr_title=\"ReleaseNotes\"\n\ngenerate_release_notes() {\n    for build_id in $build_ids; do\n        echo $build_id\n        included_skus=\"\"\n        for artifact in $(az pipelines runs artifact list --run-id $build_id | jq -r '.[].name'); do    # Retrieve what artifacts were published\n            if [[ $artifact == *\"vhd-release-notes\"* ]]; then\n                sku=$(echo $artifact | cut -d \"-\" -f4-) # Format of artifact is vhd-release-notes-<name of sku>\n                included_skus+=\"$sku,\"\n            fi\n        done\n        echo \"SKUs for release notes are $included_skus\"\n        go run vhdbuilder/release-notes/autonotes/main.go --build $build_id --date $image_version --include ${included_skus%?}\n    done\n}\n\nset_git_config\nif [ `git branch --list $branch_name` ]; then\n    git checkout $branch_name\n    git pull origin\n    git checkout master -- .\nelse\n    create_branch $branch_name\nfi\n\ngenerate_release_notes\ngit status\nset +x\ncreate_pull_request $image_version $github_access_token $branch_name $pr_title", "num_lines": 45}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euxo pipefail\n\nsource vhdbuilder/scripts/automate_helpers.sh\n\necho \"New image version: $1\"\n\ncurrent_image_version=\"\"\nnew_image_version=$1\n\nset +x\ngithub_access_token=$2\nset -x\n\nbuild_ids=$3\n\nbranch_name=imageBump/$new_image_version\npr_title=\"VHDVersion\"\n\n# This function finds the current SIG Image version from the input JSON file\nfind_current_image_version() {\n    filepath=$1\n    current_image_version=$(jq -r .version $filepath)\n    echo \"Current image version is: ${current_image_version}\"\n}\n\n# This function replaces the old image version with the new input image version for all relevant files\nupdate_image_version() {\n    sed -i \"s/${current_image_version}/${new_image_version}/g\" pkg/agent/datamodel/linux_sig_version.json\n}\n\ncreate_image_bump_pr() {\n    create_branch $branch_name\n    update_image_version\n\n    set +x\n    create_pull_request $new_image_version $github_access_token $branch_name $pr_title\n    set -x\n}\n\n# This function cuts the official branch based off the commit ID that the builds were triggered from and tags it\ncut_official_branch() {\n    # Image version format: YYYYMM.DD.revision\n    # Official branch format: official/vYYYYMMDD\n    # Official tag format: v0.YYYYMMDD.revision\n    parsed_image_version=\"$(echo -n \"${new_image_version}\" | head -c-1 | tr -d .)\"\n    official_branch_name=\"official/v${parsed_image_version}\"\n    official_tag=\"v0.${parsed_image_version}.0\"\n    final_commit_hash=\"\"\n    for build_id in $build_ids; do\n        current_build_commit_hash=$(az pipelines runs show --id $build_id | jq -r '.sourceVersion')\n        if [[ -z \"$final_commit_hash\" ]]; then\n            final_commit_hash=$current_build_commit_hash\n        else\n            if [[ $final_commit_hash != $current_build_commit_hash ]]; then\n                echo \"Builds are not triggered off the same commit, exit\"\n                exit 1\n            fi\n        fi\n    done\n    echo \"All builds are based off the same commit\"\n\n    # Checkout branch and commit the image bump file diff to official branch too\n    if [ `git branch -r | grep $official_branch_name` ]; then\n        git checkout $official_branch_name\n        git pull origin\n    else\n        git checkout -b $official_branch_name $final_commit_hash\n    fi\n    update_image_version\n    git add .\n    git commit -m\"chore: update image version in official branch\"\n    git push -u origin $official_branch_name\n\n    git tag $official_tag\n    git push origin tag $official_tag -f\n    git checkout master\n}\n\nset_git_config\nfind_current_image_version \"pkg/agent/datamodel/linux_sig_version.json\"\ncreate_image_bump_pr\ncut_official_branch\n", "num_lines": 84}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n{{/* BCC/BPF-related error codes */}} \nERR_IOVISOR_KEY_DOWNLOAD_TIMEOUT=168 {{/* Timeout waiting to download IOVisor repo key */}}\nERR_IOVISOR_APT_KEY_TIMEOUT=169 {{/* Timeout waiting for IOVisor apt-key */}}\nERR_BCC_INSTALL_TIMEOUT=170 {{/* Timeout waiting for bcc install */}}\nERR_BPFTRACE_BIN_DOWNLOAD_FAIL=171 {{/* Failed to download bpftrace binary */}}\nERR_BPFTRACE_TOOLS_DOWNLOAD_FAIL=172 {{/* Failed to download bpftrace default programs */}}\n\nBPFTRACE_DOWNLOADS_DIR=\"/opt/bpftrace/downloads\"\nUBUNTU_CODENAME=$(lsb_release -c -s)\n\ninstallBpftrace() {\n    local version=\"v0.9.4\"\n    local bpftrace_bin=\"bpftrace\"\n    local bpftrace_tools=\"bpftrace-tools.tar\"\n    local bpftrace_url=\"https://upstreamartifacts.azureedge.net/$bpftrace_bin/$version\"\n    local bpftrace_filepath=\"/usr/local/bin/$bpftrace_bin\"\n    local tools_filepath=\"/usr/local/share/$bpftrace_bin\"\n    if [[ -f \"$bpftrace_filepath\" ]]; then\n        installed_version=\"$($bpftrace_bin -V | cut -d' ' -f2)\"\n        if [[ \"$version\" == \"$installed_version\" ]]; then\n            return\n        fi\n        rm \"$bpftrace_filepath\"\n        if [[ -d \"$tools_filepath\" ]]; then\n            rm -r  \"$tools_filepath\"\n        fi\n    fi\n    mkdir -p \"$tools_filepath\"\n    install_dir=\"$BPFTRACE_DOWNLOADS_DIR/$version\"\n    mkdir -p \"$install_dir\"\n    download_path=\"$install_dir/$bpftrace_tools\"\n    retrycmd_if_failure 30 5 60 curl -fSL -o \"$bpftrace_filepath\" \"$bpftrace_url/$bpftrace_bin\" || exit $ERR_BPFTRACE_BIN_DOWNLOAD_FAIL\n    retrycmd_if_failure 30 5 60 curl -fSL -o \"$download_path\" \"$bpftrace_url/$bpftrace_tools\" || exit $ERR_BPFTRACE_TOOLS_DOWNLOAD_FAIL\n    tar -xvf \"$download_path\" -C \"$tools_filepath\"\n    chmod +x \"$bpftrace_filepath\"\n    chmod -R +x \"$tools_filepath/tools\"\n}\n\nensureGPUDrivers() {\n    configGPUDrivers\n    systemctlEnableAndStart nvidia-modprobe || exit $ERR_GPU_DRIVERS_START_FAIL\n}\n\ndisableSystemdResolvedCache() {\n    SERVICE_FILEPATH=\"/etc/systemd/system/resolv-uplink-override.service\"\n    touch ${SERVICE_FILEPATH}\n    cat << EOF >> ${SERVICE_FILEPATH}\n[Unit]\nDescription=Symlink /etc/resolv.conf to /run/systemd/resolve/resolv.conf\nAfter=systemd-networkd.service\n\n[Service]\nType=oneshot\nExecStart=/usr/bin/ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\nRemainAfterExit=no\n\n[Install]\nRequiredBy=network-online.target kubelet.service\nEOF\n\n    systemctlEnableAndStart resolv-uplink-override || exit $ERR_SYSTEMCTL_START_FAIL\n\n}\n\ndisableSystemdIptables() {\n    systemctlDisableAndStop iptables || exit $ERR_DISBALE_IPTABLES\n\n    # Mask the iptables service to prevent it from ever re-enabling and breaking pod networking.\n    systemctl mask iptables || exit $ERR_DISBALE_IPTABLES\n}\n", "num_lines": 72}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Sourcing tool_installs_mariner.sh\"\n\ninstallAscBaseline() {\n   echo \"Mariner TODO: installAscBaseline\"\n}\n\ninstallBcc() {\n    echo \"Installing BCC tools...\"\n    dnf_makecache || exit $ERR_APT_UPDATE_TIMEOUT\n    dnf_install 120 5 25 bcc-tools || exit $ERR_BCC_INSTALL_TIMEOUT\n    echo \"Installing BCC examples...\"\n    dnf_install 120 5 25 bcc-examples || exit $ERR_BCC_INSTALL_TIMEOUT\n}\n\naddMarinerNvidiaRepo() {\n    if [[ $OS_VERSION == \"2.0\" ]]; then \n        MARINER_NVIDIA_REPO_FILEPATH=\"/etc/yum.repos.d/mariner-nvidia.repo\"\n        touch \"${MARINER_NVIDIA_REPO_FILEPATH}\"\n        cat << EOF > \"${MARINER_NVIDIA_REPO_FILEPATH}\"\n[mariner-official-nvidia]\nname=CBL-Mariner Official Nvidia 2.0 x86_64\nbaseurl=https://packages.microsoft.com/cbl-mariner/2.0/prod/nvidia/x86_64\ngpgkey=file:///etc/pki/rpm-gpg/MICROSOFT-RPM-GPG-KEY file:///etc/pki/rpm-gpg/MICROSOFT-METADATA-GPG-KEY\ngpgcheck=1\nrepo_gpgcheck=1\nenabled=1\nskip_if_unavailable=True\nsslverify=1\nEOF\n    fi\n}\n\nforceEnableIpForward() {\n    CONFIG_FILEPATH=\"/etc/sysctl.d/99-force-bridge-forward.conf\"\n    touch ${CONFIG_FILEPATH}\n    cat << EOF >> ${CONFIG_FILEPATH}\n    net.ipv4.ip_forward = 1\n    net.ipv4.conf.all.forwarding = 1\n    net.ipv6.conf.all.forwarding = 1\n    net.bridge.bridge-nf-call-iptables = 1\nEOF\n}\n\n# The default 99-dhcp-en config on Mariner attempts to assign an IP address\n# to the eth1 virtual function device, which delays cluster setup by 2 minutes.\n# This workaround makes it so that dhcp is only enabled on eth0.\nsetMarinerNetworkdConfig() {\n    CONFIG_FILEPATH=\"/etc/systemd/network/99-dhcp-en.network\"\n    touch ${CONFIG_FILEPATH}\n    cat << EOF > ${CONFIG_FILEPATH} \n    [Match]\n    Name=eth0\n\n    [Network]\n    DHCP=yes\n    IPv6AcceptRA=no\nEOF\n# On Mariner 2.0 Marketplace images, the default systemd network config\n# has an additional change that prevents Mariner from changing IP addresses\n# every reboot\nif [[ $OS_VERSION == \"2.0\" ]]; then \n    cat << EOF >> ${CONFIG_FILEPATH}\n\n    [DHCPv4]\n    SendRelease=false\nEOF\nfi\n}\n\n\nlistInstalledPackages() {\n    rpm -qa\n}\n\n# disable and mask all UU timers/services\ndisableDNFAutomatic() {\n    # Make sure dnf-automatic is running with the notify timer rather than the auto install timer\n    systemctlEnableAndStart dnf-automatic-notifyonly.timer || exit $ERR_SYSTEMCTL_START_FAIL\n\n    # Ensure the automatic install timer is disabled. \n    # systemctlDisableAndStop adds .service to the end which doesn't work on timers.\n    systemctl disable dnf-automatic-install.service || exit 1\n    systemctl mask dnf-automatic-install.service || exit 1\n\n    systemctl stop dnf-automatic-install.timer || exit 1\n    systemctl disable dnf-automatic-install.timer || exit 1\n    systemctl mask dnf-automatic-install.timer || exit 1\n}\n\ndisableTimesyncd() {\n    # Disable and Mask timesyncd to prevent it from interfering with chronyd's work\n    systemctl stop systemd-timesyncd || exit 1\n    systemctl disable systemd-timesyncd || exit 1\n    systemctl mask systemd-timesyncd || exit 1\n    \n    # Before we return, make sure that chronyd is running\n    systemctlEnableAndStart chronyd || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\n# Regardless of UU mode, ensure check-restart is running\nenableCheckRestart() {\n  # Even if UU is disabled, we should still run check-restart so that kured\n  # will work as expected if it is installed.\n  # At 8:000:00 UTC check if a reboot-required package was installed\n  # Touch /var/run/reboot-required if a reboot required package was installed.\n  # This helps avoid a Mariner specific reboot check command in kured.\n  systemctlEnableAndStart check-restart.timer || exit $ERR_SYSTEMCTL_START_FAIL\n}\n\n# There are several issues in default file permissions when trying to run AMA and ASA extensions.\n# These will be resolved in an upcoming base image. Work around them here for now.\nfixCBLMarinerPermissions() {\n# Set the dmi/id/product_uuid permissions to 444 so that mdsd can read the VM unique ID\n# https://github.com/Azure/WALinuxAgent/blob/develop/config/99-azure-product-uuid.rules\n# Future base images will include this config in the WALinuxAgent package.\n    CONFIG_FILEPATH=\"/etc/udev/rules.d/99-azure-product-uuid.rules\"\n    touch ${CONFIG_FILEPATH}\n    cat << EOF > ${CONFIG_FILEPATH}\nSUBSYSTEM!=\"dmi\", GOTO=\"product_uuid-exit\"\nATTR{sys_vendor}!=\"Microsoft Corporation\", GOTO=\"product_uuid-exit\"\nATTR{product_name}!=\"Virtual Machine\", GOTO=\"product_uuid-exit\"\nTEST!=\"/sys/devices/virtual/dmi/id/product_uuid\", GOTO=\"product_uuid-exit\"\n\nRUN+=\"/bin/chmod 0444 /sys/devices/virtual/dmi/id/product_uuid\"\n\nLABEL=\"product_uuid-exit\"\n\nEOF\n\n# /etc/rsyslog.d is 750 but should be 755 so non root users can read the configs\n# This occurs because the umask in Mariner is 0027 and packer_source.sh created the folder\n# Future base images will already have rsyslog installed with 755 /etc/rsyslog.d\n    chmod 755 /etc/rsyslog.d\n}\n\nenableMarinerKata() {\n    # Enable the mshv boot path\n    sudo sed -i -e 's@menuentry \"CBL-Mariner\"@menuentry \"Dom0\" {\\n    search --no-floppy --set=root --file /EFI/Microsoft/Boot/bootmgfw.efi\\n        chainloader /EFI/Microsoft/Boot/bootmgfw.efi\\n}\\n\\nmenuentry \"CBL-Mariner\"@'  /boot/grub2/grub.cfg\n\n    # kata-osbuilder-generate is responsible for triggering the kata-osbuilder.sh script, which uses\n    # dracut to generate an initrd for the nested VM using binaries from the Mariner host OS.\n    systemctlEnableAndStart kata-osbuilder-generate\n}\n\nactivateNfConntrack() {\n    # explicitly activate nf_conntrack module so associated sysctls can be properly set \n    echo nf_conntrack >> /etc/modules-load.d/contrack.conf\n}\n\ninstallFIPS() {\n\n    echo \"Installing FIPS...\"\n\n    # Install necessary rpm pacakages\n    dnf_install 120 5 25 grubby || exit $ERR_APT_INSTALL_TIMEOUT\n    dnf_install 120 5 25 dracut-fips || exit $ERR_APT_INSTALL_TIMEOUT\n\n    # Add the boot= cmd line parameter if the boot dir is not the same as the root dir\n    boot_dev=\"$(df /boot/ | tail -1 | cut -d' ' -f1)\"\n    root_dev=\"$(df / | tail -1 | cut -d' ' -f1)\"\n    if [ ! \"$root_dev\" == \"$boot_dev\" ]; then\n        boot_uuid=\"UUID=$(blkid $boot_dev -s UUID -o value)\"\n\n        # Enable FIPS mode and modify boot directory\n        if grub2-editenv - list | grep -q kernelopts;then\n                grub2-editenv - set \"$(grub2-editenv - list | grep kernelopts) fips=1 boot=$boot_uuid\"\n        else\n                grubby --update-kernel=ALL --args=\"fips=1 boot=$boot_uuid\"\n        fi\n    fi\n    \n}\n", "num_lines": 175}
{"repo_name": "AgentBaker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n{{/* FIPS-related error codes */}}\nERR_UA_TOOLS_INSTALL_TIMEOUT=180 {{/* Timeout waiting for ubuntu-advantage-tools install */}}\nERR_ADD_UA_APT_REPO=181 {{/* Error to add UA apt repository */}}\nERR_AUTO_UA_ATTACH=182 {{/* Error to auto UA attach */}}\nERR_UA_DISABLE_LIVEPATCH=183 {{/* Error to disable UA livepatch */}}\nERR_UA_ENABLE_FIPS=184 {{/* Error to enable UA FIPS */}}\nERR_UA_DETACH=185 {{/* Error to detach UA */}}\nERR_LINUX_HEADER_INSTALL_TIMEOUT=186 {{/* Timeout to install linux header */}}\nERR_STRONGSWAN_INSTALL_TIMEOUT=187 {{/* Timeout to install strongswan */}}\n\nERR_NTP_INSTALL_TIMEOUT=10 {{/*Unable to install NTP */}}\nERR_NTP_START_TIMEOUT=11 {{/* Unable to start NTP */}}\nERR_STOP_OR_DISABLE_SYSTEMD_TIMESYNCD_TIMEOUT=12 {{/* Timeout waiting for systemd-timesyncd stop */}}\nERR_STOP_OR_DISABLE_NTP_TIMEOUT=13 {{/* Timeout waiting for ntp stop */}}\nERR_CHRONY_INSTALL_TIMEOUT=14 {{/*Unable to install CHRONY */}}\nERR_CHRONY_START_TIMEOUT=15 {{/* Unable to start CHRONY */}}\n\necho \"Sourcing tool_installs_ubuntu.sh\"\n\ninstallAscBaseline() {\n   echo \"Installing ASC Baseline tools...\"\n   ASC_BASELINE_TMP=/home/packer/asc-baseline.deb\n   retrycmd_if_failure_no_stats 120 5 25 dpkg -i $ASC_BASELINE_TMP || exit $ERR_APT_INSTALL_TIMEOUT\n   sudo cp /opt/microsoft/asc-baseline/baselines/*.xml /opt/microsoft/asc-baseline/\n   cd /opt/microsoft/asc-baseline\n   sudo ./ascbaseline -d .\n   sudo ./ascremediate -d . -m all\n   sudo ./ascbaseline -d . | grep -B2 -A6 \"FAIL\"\n   cd -\n   echo \"Check UDF\"\n   cat /etc/modprobe.d/*.conf | grep udf\n   echo \"Finished Setting up ASC Baseline\"\n}\n\ninstallBcc() {\n    echo \"Installing BCC tools...\"\n    wait_for_apt_locks\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    VERSION=$(grep DISTRIB_RELEASE /etc/*-release| cut -f 2 -d \"=\")\n    if [[ \"${VERSION}\" == \"22.04\" ]]; then\n        apt_get_install 120 5 300 build-essential git bison cmake flex libedit-dev libllvm14 llvm-14-dev libclang-14-dev python3 zlib1g-dev libelf-dev python3-distutils libfl-dev || exit $ERR_BCC_INSTALL_TIMEOUT\n    else\n        apt_get_install 120 5 300 build-essential git bison cmake flex libedit-dev libllvm6.0 llvm-6.0-dev libclang-6.0-dev python zlib1g-dev libelf-dev python3-distutils libfl-dev || exit $ERR_BCC_INSTALL_TIMEOUT\n    fi\n\n    mkdir -p /tmp/bcc\n    pushd /tmp/bcc\n    git clone https://github.com/iovisor/bcc.git\n    mkdir bcc/build; cd bcc/build\n    git checkout v0.24.0\n    cmake .. || exit 1\n    make\n    sudo make install || exit 1\n    cmake -DPYTHON_CMD=python3 .. || exit 1 # build python3 binding \n    pushd src/python/\n    make\n    sudo make install || exit 1\n    popd\n    popd\n    # we explicitly do not remove build-essential or git\n    # these are standard packages we want to keep, they should usually be in the final build anyway.\n    # only ensuring they are installed above.\n    if [[ \"${VERSION}\" == \"22.04\" ]]; then\n        apt_get_purge 120 5 300 bison cmake flex libedit-dev libllvm14 llvm-14-dev libclang-14-dev zlib1g-dev libelf-dev libfl-dev || exit $ERR_BCC_INSTALL_TIMEOUT\n    else\n        apt_get_purge 120 5 300 bison cmake flex libedit-dev libllvm6.0 llvm-6.0-dev libclang-6.0-dev zlib1g-dev libelf-dev libfl-dev || exit $ERR_BCC_INSTALL_TIMEOUT\n    fi\n}\n\ndisableNtpAndTimesyncdInstallChrony() {\n    # Disable systemd-timesyncd\n    systemctl_stop 20 30 120 systemd-timesyncd || exit $ERR_STOP_OR_DISABLE_SYSTEMD_TIMESYNCD_TIMEOUT\n    systemctl disable systemd-timesyncd || exit $ERR_STOP_OR_DISABLE_SYSTEMD_TIMESYNCD_TIMEOUT\n\n    # Disable ntp if present\n    status=$(systemctl show -p SubState --value ntp)\n    if [ $status == 'dead' ]; then\n        echo \"ntp is removed, no need to disable\"\n    else\n        systemctl_stop 20 30 120 ntp || exit $ERR_STOP_OR_DISABLE_NTP_TIMEOUT\n        systemctl disable ntp || exit $ERR_STOP_OR_DISABLE_NTP_TIMEOUT\n    fi\n\n    # Install chrony\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n    apt_get_install 20 30 120 chrony || exit $ERR_CHRONY_INSTALL_TIMEOUT\n    cat > /etc/chrony/chrony.conf <<EOF\n# Welcome to the chrony configuration file. See chrony.conf(5) for more\n# information about usuable directives.\n\n# This will use (up to):\n# - 4 sources from ntp.ubuntu.com which some are ipv6 enabled\n# - 2 sources from 2.ubuntu.pool.ntp.org which is ipv6 enabled as well\n# - 1 source from [01].ubuntu.pool.ntp.org each (ipv4 only atm)\n# This means by default, up to 6 dual-stack and up to 2 additional IPv4-only\n# sources will be used.\n# At the same time it retains some protection against one of the entries being\n# down (compare to just using one of the lines). See (LP: #1754358) for the\n# discussion.\n#\n# About using servers from the NTP Pool Project in general see (LP: #104525).\n# Approved by Ubuntu Technical Board on 2011-02-08.\n# See http://www.pool.ntp.org/join.html for more information.\n#pool ntp.ubuntu.com        iburst maxsources 4\n#pool 0.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 1.ubuntu.pool.ntp.org iburst maxsources 1\n#pool 2.ubuntu.pool.ntp.org iburst maxsources 2\n\n# This directive specify the location of the file containing ID/key pairs for\n# NTP authentication.\nkeyfile /etc/chrony/chrony.keys\n\n# This directive specify the file into which chronyd will store the rate\n# information.\ndriftfile /var/lib/chrony/chrony.drift\n\n# Uncomment the following line to turn logging on.\n#log tracking measurements statistics\n\n# Log files location.\nlogdir /var/log/chrony\n\n# Stop bad estimates upsetting machine clock.\nmaxupdateskew 100.0\n\n# This directive enables kernel synchronisation (every 11 minutes) of the\n# real-time clock. Note that it can\u00e2\u20ac\u2122t be used along with the 'rtcfile' directive.\nrtcsync\n\n# Settings come from: https://docs.microsoft.com/en-us/azure/virtual-machines/linux/time-sync\nrefclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\nmakestep 1.0 -1\nEOF\n\n    systemctlEnableAndStart chrony || exit $ERR_CHRONY_START_TIMEOUT\n}\n\ninstallFIPS() {\n    echo \"Installing FIPS...\"\n    wait_for_apt_locks\n\n    # installing fips kernel doesn't remove non-fips kernel now, purge current linux-image-azure\n    echo \"purging linux-image-azure...\"\n    linuxImages=$(apt list --installed | grep linux-image- | grep azure | cut -d '/' -f 1)\n    for image in $linuxImages; do\n        echo \"Removing non-fips kernel ${image}...\"\n        if [[ ${image} != \"linux-image-$(uname -r)\" ]]; then\n            apt_get_purge 5 10 120 ${image} || exit 1\n        fi\n    done\n\n    echo \"enabling ua fips-updates...\"\n    retrycmd_if_failure 5 10 1200 echo y | ua enable fips-updates || exit $ERR_UA_ENABLE_FIPS\n}\n\nrelinkResolvConf() {\n    # /run/systemd/resolve/stub-resolv.conf contains local nameserver 127.0.0.53\n    # remove this block after toggle disable-1804-systemd-resolved is enabled prod wide\n    resolvconf=$(readlink -f /etc/resolv.conf)\n    if [[ \"${resolvconf}\" == */run/systemd/resolve/stub-resolv.conf ]]; then\n        unlink /etc/resolv.conf\n        ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n    fi\n}\n\nlistInstalledPackages() {\n    apt list --installed\n}\n\nautoAttachUA() {\n    echo \"auto attaching ua...\"\n    retrycmd_if_failure 5 10 120 ua auto-attach || exit $ERR_AUTO_UA_ATTACH\n\n    echo \"disabling ua livepatch...\"\n    retrycmd_if_failure 5 10 300 echo y | ua disable livepatch\n}\n\ndetachAndCleanUpUA() {\n    echo \"detaching ua...\"\n    retrycmd_if_failure 5 10 120 printf \"y\\nN\" | ua detach || $ERR_UA_DETACH\n\n    # now that the ESM/FIPS packages are installed, clean up apt settings in the vhd,\n    # the VMs created on customers' subscriptions don't have access to UA repo\n    rm -f /etc/apt/trusted.gpg.d/ubuntu-advantage-esm-apps.gpg\n    rm -f /etc/apt/trusted.gpg.d/ubuntu-advantage-esm-infra-trusty.gpg\n    rm -f /etc/apt/trusted.gpg.d/ubuntu-advantage-fips.gpg\n    rm -f /etc/apt/sources.list.d/ubuntu-esm-apps.list\n    rm -f /etc/apt/sources.list.d/ubuntu-esm-infra.list\n    rm -f /etc/apt/sources.list.d/ubuntu-fips-updates.list\n    rm -f /etc/apt/auth.conf.d/*ubuntu-advantage\n    apt_get_update || exit $ERR_APT_UPDATE_TIMEOUT\n}", "num_lines": 193}
{"repo_name": "ahds-reference-architecture", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd Scenarios/Baseline/bicep\n\n# Registering Resource Providers\naz provider register --namespace Microsoft.Network\naz provider register --namespace Microsoft.Compute\naz provider register --namespace Microsoft.ContainerInstance\naz provider register --namespace Microsoft.KeyVault\naz provider register --namespace Microsoft.ManagedIdentity\naz provider register --namespace Microsoft.Storage\naz provider register --namespace Microsoft.HealthcareApis\naz provider register --namespace Microsoft.Diagnostics\naz provider register --namespace Microsoft.ContainerRegistry\naz provider register --namespace Microsoft.Web\n\n# Checking registration status\naz provider show --namespace Microsoft.Network\naz provider show --namespace Microsoft.Compute\naz provider show --namespace Microsoft.ContainerInstance\naz provider show --namespace Microsoft.KeyVault\naz provider show --namespace Microsoft.ManagedIdentity\naz provider show --namespace Microsoft.Storage\naz provider show --namespace Microsoft.HealthcareApis\naz provider show --namespace Microsoft.Diagnostics\naz provider show --namespace Microsoft.ContainerRegistry\naz provider show --namespace Microsoft.Web\n\n# To see the resource types for a resource provider\naz provider show --namespace Microsoft.Network --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.Compute --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.ContainerInstance --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.KeyVault --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.ManagedIdentity --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.Storage --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.HealthcareApis --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.Diagnostics --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.ContainerRegistry --query \"resourceTypes[*].resourceType\" --out table\naz provider show --namespace Microsoft.Web --query \"resourceTypes[*].resourceType\" --out table\n\n\n# AZ CLI\n# 01-Network-Hub\n# *** The JumpBox VM User Name and Password will be auto generated and will be saved at the Key Vault under HUB Resource Group\n# You have to give yourself access in order to read the both Secrets with username and password\naz deployment sub create -n \"ESLZ-HUB-AHDS\" -l \"EastUS\" -f 01-Network-Hub/main.bicep -p 01-Network-Hub/parameters-main.json\naz deployment sub create -n \"ESLZ-AHDS-HUB-UDR\" -l \"EastUS\" -f 01-Network-Hub/updateUDR.bicep -p 01-Network-Hub/parameters-updateUDR.json\naz deployment sub create -n \"ESLZ-HUB-VM\" -l \"EastUS\" -f 01-Network-Hub/deploy-vm.bicep -p 01-Network-Hub/parameters-deploy-vm.json\n\n# 02-Network-LZ\n# Bash\nrgSpoke=ESLZ-AHDS-SPOKE\n# Powershell\n$rgSpoke=\"ESLZ-AHDS-SPOKE\"\naz deployment sub create -n \"ESLZ-Spoke-AHDS\" -l \"EastUS\" -f 02-Network-LZ/main.bicep -p 02-Network-LZ/parameters-main.json -p rgName=$rgSpoke\n\n# 03-AHDS\n# ** Important Note ** Review (or Update) 03-AHDS/parameters-main.json file to make sure APIMName on line 36 is globally unique and not used by any one else\n# ** and that APIM name should match Application Gateway backend pool value (primaryBackendEndFQDN) on line 81.\naz deployment sub create -n \"ESLZ-AHDS\" -l \"EastUS\" -f 03-AHDS/main.bicep -p 03-AHDS/parameters-main.json -p rgName=$rgSpoke -p appGatewayFQDN=\"api.example.com\"\n\n# Victor ToDo: Prompt for Region and Application Gateway FQDN\n# Victor ToDo: Print the Public IP of the Application Gateway and add a statement saying they must create a DNS record for this IP\n\n\n# Full Cleanup\n# Delete Resource Groups\n# az group delete -n ESLZ-AHDS-HUB -y --no-wait\n# az group delete -n ESLZ-AHDS-SPOKE -y --no-wait\n# az apim deletedservice purge --service-name APIM-AHDS --location EastUS\n# # Delete Deployments\n# az deployment sub delete -n ESLZ-HUB-AHDS -y --no-wait\n# az deployment sub delete -n ESLZ-AHDS-HUB-UDR --no-wait\n# az deployment sub delete -n ESLZ-HUB-VM --no-wait\n# az deployment sub delete -n ESLZ-Spoke-AHDS --no-wait\n# az deployment sub delete -n ESLZ-AHDS-Supporting --no-wait", "num_lines": 76}
{"repo_name": "ahds-reference-architecture", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n###################\n# Prompt and Validating Azure Region\n###################\nread -p \"Inform Azure Region to be deployed? \" answerAzRegion\nazRegions=$(az account list-locations --query '[].name' -o tsv)\nif [[ $azRegions == *$answerAzRegion* ]]; then\n  echo \"Azure Region found: $answerAzRegion\"\nelse\n  echo \"Region $answerAzRegion Not found\"\n  echo \"\"\n  echo \"Use one of the available Azure Regions:\"\n  echo $azRegions\n  exit;\nfi\n\n###################\n# Prompt Azure Aplication Gateway FQDN\n###################\nread -p \"Inform Azure Application Gateway FQDN? \" answerAppGWFQDN\necho \"Azure Aplication Gateway FQDN: $answerAppGWFQDN\"\n\n###################\n# List of required azure providers\n###################\nazProviders=(\"Microsoft.Network\" \"Microsoft.Compute\" \"Microsoft.ContainerInstance\" \"Microsoft.KeyVault\" \"Microsoft.ManagedIdentity\" \"Microsoft.Storage\" \"Microsoft.HealthcareApis\" \"Microsoft.Diagnostics\" \"Microsoft.ContainerRegistry\" \"Microsoft.Web\")\n\n###################\n# Checking if a required provider is not registered and save in array azProvidersNotRegistered\n###################\nazProvidersNotRegistered=()\nfor provider in \"${azProviders[@]}\"\ndo\n  registrationState=$(az provider show --namespace $provider --query \"[registrationState]\" --output tsv)\n  if [ \"$registrationState\" != \"Registered\" ]; then\n    #echo \"Found an Azure Resource Provider not registred: $provider\"\n    azProvidersNotRegistered+=($provider)\n    #echo \"${azProvidersNotRegistered[@]}\"\n  fi\ndone\n\n###################\n# Registering all missing required Azure providers\n###################\nif (( ${#azProvidersNotRegistered[@]} > 0 )); then\n  echo \"Registering required Azure Providers\"\n  echo \"\"\n  for provider in \"${azProvidersNotRegistered[@]}\"\n  do\n    echo \"Registering Azure Provider: $provider\"\n    az provider register --namespace $provider\n  done\nfi\necho \"\"\n\n###################\n# Function to remove an element of an array\n###################\nremove_array_element_byname(){\n    index=0\n    name=$1[@]\n    param2=$2\n    fun_arr=(\"${!name}\")\n\n    for element in \"${fun_arr[@]}\"\n    do\n      if [[ $element == $param2 ]]; then\n        foundindex=$index\n      fi\n      index=$(($index + 1))\n    done\n    unset fun_arr[$foundindex]\n    ret_val=(\"${fun_arr[@]}\")\n}\n\n###################\n# Checking the status of missing Azure Providers\n###################\nif (( ${#azProvidersNotRegistered[@]} > 0 )); then\n  copy_azProvidersNotRegistered=(\"${azProvidersNotRegistered[@]}\")\n  while (( ${#copy_azProvidersNotRegistered[@]} > 0 ))\n  do\n    elementcount=0\n    for provider in \"${azProvidersNotRegistered[@]}\"\n    do\n      registrationState=$(az provider show --namespace $provider --query \"[registrationState]\" --output tsv)\n      if [ \"$registrationState\" != \"Registered\" ]; then\n        echo \"Waiting for Azure provider $provider ...\"\n      else\n        echo \"Azure provider $provider registered!\"\n        remove_array_element_byname copy_azProvidersNotRegistered $provider\n        ret_remove_array_element_byname=(\"${ret_val[@]}\")\n        copy_azProvidersNotRegistered=(\"${ret_remove_array_element_byname[@]}\")\n      fi\n    done\n    azProvidersNotRegistered=(\"${copy_azProvidersNotRegistered[@]}\")\n    echo \"\"\n\n    echo \"Amount of providers waiting to be registered: ${#azProvidersNotRegistered[@]}\"\n    echo \"Waiting 10 seconds to check the missing providers again\"\n    echo \"############################################################\"\n    sleep 10\n    clear\n  done\n  echo \"Done registering required Azure Providers\"\nfi\n\n# End of working part\n#=======================================================================\n\n######################################################\n######################################################\n######################################################\n#### From this part bellow is working in progress ####\n######################################################\n######################################################\n######################################################\n\n# AZ CLI\n# 01-Network-Hub\n# *** The JumpBox VM User Name and Password will be auto generated and will be saved at the Key Vault under HUB Resource Group\n# You have to give yourself access in order to read the both Secrets with username and password\naz deployment sub create -n \"ESLZ-HUB-AHDS\" -l $answerAzRegion -f 01-Network-Hub/main.bicep -p 01-Network-Hub/parameters-main.json\naz deployment sub create -n \"ESLZ-AHDS-HUB-UDR\" -l $answerAzRegion -f 01-Network-Hub/updateUDR.bicep -p 01-Network-Hub/parameters-updateUDR.json\naz deployment sub create -n \"ESLZ-HUB-VM\" -l $answerAzRegion -f 01-Network-Hub/deploy-vm.bicep -p 01-Network-Hub/parameters-deploy-vm.json\n\n# 02-Network-LZ\nrgSpoke=ESLZ-AHDS-SPOKE\naz deployment sub create -n \"ESLZ-Spoke-AHDS\" -l $answerAzRegion -f 02-Network-LZ/main.bicep -p 02-Network-LZ/parameters-main.json -p rgName=$rgSpoke\n\n# 03-AHDS\n# ** Important Note ** Review (or Update) 03-AHDS/parameters-main.json file to make sure APIMName on line 36 is globally unique and not used by any one else\n# ** and that APIM name should match Application Gateway backend pool value (primaryBackendEndFQDN) on line 81.\n# az deployment group create -g \"ESLZ-HUB\" -n \"test-public-ip\" -f test.bicep --query \"properties.outputs.publicipappgw.value\" -o tsv\npublicipappgw=$(az deployment sub create -n \"ESLZ-AHDS\" -l $answerAzRegion -f 03-AHDS/main.bicep -p 03-AHDS/parameters-main.json -p rgName=$rgSpoke -p appGatewayFQDN=$answerAppGWFQDN --query \"properties.outputs.publicipappgw.value\" -o tsv)\necho \"Please create a DNS record for the Application Gateway Public IP: $publicipappgw with the FQDN: $answerAppGWFQDN\"\n\n# Victor ToDo: Prompt for Region and Application Gateway FQDN - Done\n# Victor ToDo: Print the Public IP of the Application Gateway and add a statement saying they must create a DNS record for this IP\n\necho Done", "num_lines": 142}
{"repo_name": "AI-PredictiveMaintenance", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# View extension logs by running\n# sudo cat /var/log/azure/Microsoft.OSTCExtensions.CustomScriptForLinux/1.5.2.2/extension.log\n# (the version may be different)\n\nuser=`awk -F: '$3 >= 1000 {print $1, $6}' /etc/passwd | tail -n 1`\necho $user\nusername=${user% *}\nhomedir=${user#* }\n\nbasedir=$PWD\n\npushd $homedir/notebooks\nrm -rf *\nunzip $basedir/Notebooks.zip\nchown $username:$username *\npopd\n\ntouch $homedir/NotebookEnvironmentVariablesConfig.json\ncat << EOF > $homedir/NotebookEnvironmentVariablesConfig.json\n{\n\t\"DataIngestion\" : {\n\t\t\"STORAGE_ACCOUNT_NAME\" : \"$3\",\n\t\t\"STORAGE_ACCOUNT_KEY\" : \"$4\",\n\t\t\"TELEMETRY_CONTAINER_NAME\" : \"telemetry\",\n\t\t\"LOG_TABLE_NAME\" : \"Logs\",\n\t\t\"DATA_ROOT_FOLDER\" : \"$homedir\"\n\t}\n}\nEOF\n\nmv $basedir/spark-avro_2.11-4.0.0.jar /dsvm/tools/spark/current/jars/\n\nsource /anaconda/bin/activate py35\n\npip install --upgrade pip\n\n#to install ggplot in DSVM uncomment the following\n#conda remove -n py35 -y pandas\n#conda install -n py35 -y pandas==0.20.3\n#conda install -n py35 -y -c conda-forge ggplot\n\nconda install -n py35 -y python-snappy\npip install imblearn\npip install --upgrade --extra-index-url https://azuremlsdktestpypi.azureedge.net/sdk-release/Preview/E7501C02541B433786111FE8E140CAA1 azureml-sdk\npip install --upgrade databricks-cli\n\ntouch $homedir/.databrickscfg\ncat << EOF > $homedir/.databrickscfg\n[DEFAULT]\nhost = $1\ntoken = $2\nEOF", "num_lines": 54}
{"repo_name": "AI-PredictiveMaintenance", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nconvert -density 150 -background white -alpha remove data_flow.pdf -quality 90 data_flow.png\nconvert -density 90 -background white -alpha remove data_collection.pdf -quality 90 data_collection.png\nconvert -density 150 -background white -alpha remove modeling.pdf -quality 90 modeling.png\nconvert -density 90 -background white -alpha remove productionalization_feature_engineering.pdf -quality 90 productionalization_feature_engineering.png\nconvert -density 90 -background white -alpha remove productionalization_scoring.pdf -quality 90 productionalization_scoring.png\n\n\ncp data_collection.png modeling.png productionalization_feature_engineering.png productionalization_scoring.png data_flow.png ../../docs/img/", "num_lines": 10}
{"repo_name": "AI-PredictiveMaintenance", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwget -O spark-logo.png https://spark.apache.org/images/spark-logo-trademark.png\nwget -O kafka-logo.png https://svn.apache.org/repos/asf/kafka/site/logos/kafka-logo-no-text.png\nwget -O event-hub.svg https://worldvectorlogo.com/download/azure-event-hub.svg\nwget -O iot-hub.svg \"https://azure.microsoft.com/svghandler/iot-hub/?width=600&amp;height=600\"\nwget -O databricks.svg \"https://azure.microsoft.com/svghandler/databricks?width=600&height=600\"\nwget -O table-storage.svg \"https://docs.microsoft.com/en-us/azure/media/index/storage.svg\"\nwget -O stream-analytics.svg \"https://azure.microsoft.com/svghandler/stream-analytics?width=600&height=600\"\nwget -O sql-database.svg \"https://azure.microsoft.com/svghandler/sql-database?width=600&height=600\"\nwget -O cosmos-db.svg \"https://azure.microsoft.com/svghandler/cosmos-db?width=600&height=600\"\nwget -O webjob.png https://developersde.blob.core.windows.net/usercontent/2018/4/15734_webjobs.png\nwget -O aks.png https://stephanefrechette.com/wp-content/uploads/2018/04/Azure-Container-Service_COLOR-300x300.png\nwget -O dashboard.png https://www.freeiconspng.com/uploads/dashboard-icon-3.png\nwget -O blob-storage.png https://azureautomation950740325.files.wordpress.com/2018/02/azure-storage-blob.png\nwget -O python-logo.png https://upload.wikimedia.org/wikipedia/commons/thumb/c/c3/Python-logo-notext.svg/2000px-Python-logo-notext.svg.png\nwget -O dsvm.svg \"https://azure.microsoft.com/svghandler/virtual-machines-data-science-virtual-machines/?width=600&height=600\"\nwget -O databricks.png \"https://databricks.com/wp-content/themes/databricks/assets/images/header_logo.png\"\nwget -O file-storage.png \"https://ievgensaxblog.files.wordpress.com/2017/07/azure-storage-files.png\"\nwget -O aml-workbench.svg \"http://azureml.azureedge.net/content/apphome/media/AML-Logo.svg\"\nwget -O model.png \"https://vc4prod.blob.core.windows.net/catalog/Recommendations/Machine-Learning.png\"\nwget -O jupyter.png \"http://jupyter.org/assets/try/jupyter.png\"\n\nconvert -density 300 event-hub.svg event-hub.png\nconvert -density 300 iot-hub.svg iot-hub.png\nconvert -density 300 databricks.svg databricks.png\nconvert -density 300 table-storage.svg table-storage.png\nconvert -density 300 stream-analytics.svg stream-analytics.png\nconvert -density 300 sql-database.svg sql-database.png\nconvert -density 300 cosmos-db.svg cosmos-db.png\nconvert -density 300 dsvm.svg dsvm.png\nconvert -density 300 aml-workbench.svg aml-workbench.png\n", "num_lines": 32}
{"repo_name": "ai-toolkit-iot-edge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Install IOT Edge Runtime and register the edge device\n\n# HOME is not set when the extension runs, so set it now\nexport HOME=$2\n\nusermod -aG docker $2\n\nsource /anaconda/bin/activate root\npip install -U azure-iot-edge-runtime-ctl\niotedgectl setup --connection-string $1 --auto-cert-gen-force-no-passwords\niotedgectl start\n\nchmod 644 /etc/azure-iot-edge/config.json", "num_lines": 14}
{"repo_name": "AKS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# Please Add\n# Your AKS Cluster Subscription:\nsub=\"<YOUR-SUBSCRIPTION-ID>\"\n# Your AKS Cluster Resource Group:\nrg=\"<YOUR-RESOURCE-GROUP-NAME>\"\n# Your AKS Cluster Name:\ncn=\"<YOUR-AKS-CLUSTER-NAME>\"\n\n# Set AKS kubectl creds\naz account set --subscription $sub\naz aks get-credentials --resource-group $rg --name $cn\n\nmcrg=$(az aks show --name $cn --resource-group $rg --query \"nodeResourceGroup\" -o tsv)\necho \"MC RG $mcrg\"\n\n# Check each nodepool individually\nfor np in $(az aks nodepool list --cluster-name $cn --resource-group $rg --query \"[].name\" -o tsv)\ndo\n    echo \"Going to cleanup for node pool $np\"\n    # find total nodes\n    totalNodes=$(kubectl get nodes -l kubernetes.azure.com/agentpool=$np -o wide | grep $np | wc -l)\n    echo \"Total nodes of node pool $np is $totalNodes\"\n    nodeList=$(kubectl get nodes -l kubernetes.azure.com/agentpool=$np -o wide | grep \"5.4.0-1095-azure\" | awk '{print $1}')\n    echo \"node list: $nodeList\"\n\n    autoScalerEnabled=$(az aks nodepool show --cluster-name $cn --resource-group $rg --name $np --query \"enableAutoScaling\" -o tsv)\n    echo \"auto-scaler enabled: $autoScalerEnabled\"\n\n    if [ \"$autoScalerEnabled\" != \"true\" ]; then\n        echo \"Scale cluster by 1 node for removal of bad node\"\n        az aks scale --resource-group $rg --name $cn --node-count $((totalNodes+1)) --nodepool-name $np\n    fi\n\n    # Clean up each node with bad kernel\n    for ns in $nodeList\n    do\n        echo \"Going to cleanup for node $ns\"\n    \n        echo \"Cordoning $ns\"\n        kubectl cordon $ns\n    \n        echo \"Draining $ns\"\n        kubectl drain $ns --ignore-daemonsets --delete-emptydir-data\n    \n        vmssName=$(kubectl get node $ns -o yaml | grep \"providerID\" | awk -F '/' '{print $(NF-2)}')\n        instanceId=$(kubectl get node $ns -o yaml | grep \"providerID\" | awk -F '/' '{print $NF}')\n        echo \"Re-image $vmssName/$instanceId\"\n        az vmss reimage --instance-id $instanceId --name $vmssName --resource-group $mcrg\n    \n        echo \"Uncordoning $ns\"\n        kubectl uncordon $ns\n    \n        echo \"Cleanup for $ns ($vmssName/$instanceId) done\"\n    done\n\n    if [ \"$autoScalerEnabled\" != \"true\" ]; then\n        echo \"Scale cluster to $totalNodes nodes\"\n        az aks scale --resource-group $rg --name $cn --node-count $totalNodes --nodepool-name $np\n    fi\ndone\n", "num_lines": 65}
{"repo_name": "aks-advanced-autoscaling", "repo_creator": "Azure", "programming_language": "Shell", "code": "#### First, set the values of the variables (SETTING ALL VARIABLES section)\n#### Then run the rest of the script (SCRIPT EXECUTION section)  \n\n## Note: if your value set contains spaces please enclose the value in double quotes.\n## Also, please make sure to run the following commands from same command directory \n## as the location of LvLUpAutoscalingLoadTest.jmx in order to let the \"-F file=\" parameter \n## load the jmx content correctly (use cd to set your command directory) </br>\n\n### *** BEGIN - SETTING ALL VARIABLES\ndirectory_of_LvLUpAutoscalingLoadTestjmx=\"[cd path of LvLUpAutoscalingLoadTest.jmx]\"\nsubscription=[your subscription id used in Module 1]\nrg_name=[name of resource group created in Module 1]\nservicebus_namespace=[name of your azure service bus namespace]  \nazure_key_vault=[your azure key vault name created in Module 1]\nalt=[your azure load testing instance name created in Module 1]\n## set the value of the azure service bus endpoint uri to test - e.g.: \"asbnamespace.servicebus.windows.net\" - no http(s) prefix\nasb_endpoint_uri=[your asb uri]\n\n### *** END - SETTING ALL VARIABLES\n\n### BEGIN - SCRIPT EXECUTION - copy, paste, run\n\n# Unless you are already logged in, 'az login'  will open a browser window to let you authenticate. Once authenticated, the script will continue running \ncd \"$directory_of_LvLUpAutoscalingLoadTestjmx\"\naz login\naz account set -s $subscription \nasb_queue=orders \nasb_queue_key_name=alt-send\n\nasb_uri=\"https://\"$servicebus_namespace\".servicebus.windows.net/\"$asb_queue\"/messages\"\nasb_queue_primary_key=$(az servicebus queue authorization-rule keys list -g $rg_name --namespace-name $servicebus_namespace --queue-name $asb_queue --name $asb_queue_key_name --query primaryKey -o tsv)\necho $asb_queue_primary_key\n\nget_sas_token() {\n    local ASB_URI=$1\n    local SHARED_ACCESS_KEY_NAME=$2\n    local SHARED_ACCESS_KEY=$3\n    local EXPIRY=${EXPIRY:=$((60 * 60 * 8))} # Setting default token expiration at 8 hours\n\n    local ENCODED_URI=$(echo -n $ASB_URI | jq -s -R -r @uri)\n    local TTL=$(($(date +%s) + $EXPIRY))\n    local UTF8_SIGNATURE=$(printf \"%s\\n%s\" $ENCODED_URI $TTL | iconv -t UTF-8)\n\n    local HASH=$(echo -n \"$UTF8_SIGNATURE\" | openssl sha256 -hmac $SHARED_ACCESS_KEY -binary | base64)\n    local ENCODED_HASH=$(echo -n $HASH | jq -s -R -r @uri)\n\n    echo -n \"SharedAccessSignature sr=$ENCODED_URI&sig=$ENCODED_HASH&se=$TTL&skn=$SHARED_ACCESS_KEY_NAME\"\n}\n\nsastoken=$(get_sas_token $asb_uri $asb_queue_key_name $asb_queue_primary_key)\nsecretvalue=$sastoken\nsecret_name=\"sastoken\"\n\n## get current user upn\nupn=$(az ad signed-in-user show --query userPrincipalName -o tsv)\n## add access policy for current user to azure key vault\naz keyvault set-policy -g $rg_name -n $azure_key_vault --secret-permissions all --upn $upn\n\n# this will set the secret expiration in 8 hours from current date/time\nexpiredate=$(date +%Y-%m-%d'T'%H:%M:%S'Z' -d \"$(date) + 8 hours\")\n\naz keyvault secret set --name $secret_name --vault-name $azure_key_vault --value \"$secretvalue\" --subscription $subscription --expires \"$expiredate\"\n\nsecret_uri=$(az keyvault secret show --name $secret_name --vault-name $azure_key_vault --query id -o tsv)\n$secret_uri\n\n## Default value already set for the load test instance that we are going to create. Feel free to keep it as-is or modify\ntestname=\"LvlUpNewTest\"\n\n## Values are already set. No need to change. Modify only if you would like to use different ones. \ntestdate=$(date)\ntestdescription=\"Level Up Azure Load Testing Instance - Created on: $testdate\"\n\n## constant values - do not change unless instructed by trainer\narm_apiversion=\"api-version=2021-12-01-preview\"\nalt_apiversion=\"api-version=2021-07-01-preview\"\n\n## formatting resourceId string based on submitted variables \nresourceId=\"/subscriptions/\"$subscription\"/resourcegroups/\"$rg_name\"/providers/microsoft.loadtestservice/loadtests/\"$alt\n\n## formatting management endpoint url based on submitted variables \narmEndpoint=\"https://management.azure.com\"$resourceId\"?$arm_apiversion\"\n\naccessToken=$(az account get-access-token --resource \"https://management.core.windows.net\" --query accessToken -o tsv) \n\nhdr_authorization=\"Authorization: Bearer $accessToken\"\nhdr_content_type=\"Content-Type: application/json\"\n\ndataPlaneURI=$(curl -G -H \"$hdr_authorization\" -H \"$hdr_content_type\" $armEndpoint | jq -r .properties.dataPlaneURI) \n\n# utility function to create random guid\nuuid()\n{\n    local N B C='89ab'\n\n    for (( N=0; N < 16; ++N ))\n    do\n        B=$(( $RANDOM%256 ))\n\n        case $N in\n            6)\n                printf '4%x' $(( B%16 ))\n                ;;\n            8)\n                printf '%c%x' ${C:$RANDOM%${#C}:1} $(( B%16 ))\n                ;;\n            3 | 5 | 7 | 9)\n                printf '%02x-' $B\n                ;;\n            *)\n                printf '%02x' $B\n                ;;\n        esac\n    done\n\n    echo\n}\n\ntestId=$(uuid) # do not change\n\n# get access token for Azure Load Testing API endpoint\naccessToken=$(az account get-access-token --resource \"https://loadtest.azure-dev.com\" --query accessToken -o tsv) \n\n## Number of Instances to run the test\nEngineInstancesCount=1\n\n## random id for the metrics - no need to change \npassFailMetrics1Guid=$(uuid) \npassFailMetrics2Guid=$(uuid) \n\n#\ntestJson=$(cat <<EOF\n{\n    \"resourceId\": \"$resourceId\",\n    \"testId\": \"$testId\",\n    \"description\": \"$testdescription\",\n    \"displayName\": \"$testname\",\n    \"loadTestConfig\": {\n        \"engineSize\": \"m\",\n        \"engineInstances\": $EngineInstancesCount\n    },\n    \"secrets\": {\n        \"sastoken\": {\n        \"value\": \"$secret_uri\",\n        \"type\": \"AKV_SECRET_URI\"\n        }\n    },\n    \"environmentVariables\": {\n        \"endpoint_uri\": \"$asb_endpoint_uri\"\n    },\n    \"passFailCriteria\": {\n        \"passFailMetrics\": {\n            \"$passFailMetrics1Guid\": {\n                \"clientmetric\": \"response_time_ms\",\n                \"aggregate\": \"avg\",\n                \"condition\": \">\",\n                \"value\": 500,\n                \"action\": \"continue\",\n                \"result\": null,\n                \"actualValue\": 0\n            },\n            \"$passFailMetrics2Guid\": {\n                \"clientmetric\": \"error\",\n                \"aggregate\": \"percentage\",\n                \"condition\": \">\",\n                \"value\": 30,\n                \"action\": \"continue\",\n                \"result\": null,\n                \"actualValue\": 0\n            }\n        }\n    }\n}\nEOF\n)\n\nhdr_authorization=\"Authorization: Bearer $accessToken\"\nhdr_content_type=\"Content-Type: application/merge-patch+json\"\n\n## set the Create Load Test API Endpoint URI \nloadCreateTestURI=\"https://\"$dataPlaneURI\"/loadtests/\"$testId\"?$alt_apiversion\"\nloadCreateTestResponse=$(curl $loadCreateTestURI -X PATCH -H \"$hdr_authorization\" -H \"$hdr_content_type\" -d \"$testJson\")\n\necho \"****** Begin - Create Test API Response\"\necho $loadCreateTestResponse\necho \"****** End - Create Test API Response\"\n\n### The previous command should result in a json output with the properties of the Test instance just created.\n### If you see a json output and no error (or null) value - process is working fine\n\n## Let's wait for the creation of the Test to be completed\nsleep 5\n\nfileid=$(uuid)\nhdr_authorization=\"Authorization: Bearer $accessToken\"\nvalidateUploadFileTestURI=\"https://$dataPlaneURI/file/$fileid:validate?\"$alt_apiversion\nvalidateUploadFileTestResponse=$(curl $validateUploadFileTestURI -w \"%{http_code}\" -H \"$hdr_authorization\" -F \"file=@LvLUpAutoscalingLoadTest.jmx\")\n\n## Now we will upload the jmx to the test with the next sequence of commands\nuploadFileTestURI=\"https://$dataPlaneURI/loadtests/$testId/files/$fileid?\"$alt_apiversion\n\n## Please make sure to run the following from same command directory as the location of LvLUpAutoscalingLoadTest.jmx \n## in order to let the -F file= parameter load the jmx content correctly\n\nuploadFileTestURIResponse=$(curl $uploadFileTestURI -X PUT -w \"%{http_code}\" -H \"$hdr_authorization\" -F \"file=@LvLUpAutoscalingLoadTest.jmx\")\n\n### END - SCRIPT EXECUTION\n\n\n### BEGIN - SOME FINAL CHECKS\n\n## Let's verify that we got a http code 200 = OK for the Test File upload validation\nRESPONSE_200_OK=\"200\"\nif [[ \"$validateUploadFileTestResponse\" == *\"$RESPONSE_200_OK\"* ]]\nthen \n    echo -e \"\\n\\n*** STATUS OK *** :-) --> File ID is available  OK to continue\"\nelse\n    echo -e \"\\n\\n*** IMPORTANT *** :'-( ***: File ID validation failed - Stop Executing any further and verify the error\"\n    echo -e \"Status: \"$validateUploadFileTestResponse\nfi\n\n## Let's verify that we got a http code 201 = OK for the Test creation\nRESPONSE_201_OK=\"201\"\nif [[ \"$uploadFileTestURIResponse\" == *\"$RESPONSE_201_OK\"* ]]\nthen \n    echo -e \"\\n\\n*** STATUS OK *** :-) --> Jmx File Uploaded - OK to continue\"\nelse\n    echo -e \"\\n\\n*** IMPORTANT *** :'-( ***: Jmx File Not Uploaded - Stop Executing any further and verify the error\"\n    echo -e \"Status: \"$uploadFileTestURIResponse\nfi\n### END - SOME FINAL CHECKS\n\n### You can also check in the Azure portal that the Test is present and configured correctly (refer to README)\n", "num_lines": 234}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nrun_invoke () {\n  CLUSTER_NAME=$1\n  CLUSTER_RESOURCE_GROUP=$2\n  KUBECTL_CMD=$3\n  FILEPATH=$4\n\n  KUBECTL_CMD_RESULT=\"\"\n  if [ -z $FILEPATH  ]; then\n    KUBECTL_CMD_RESULT=$(az aks command invoke -o json --resource-group $CLUSTER_RESOURCE_GROUP --name $CLUSTER_NAME --command \"$KUBECTL_CMD\")\n  else\n    KUBECTL_CMD_RESULT=$(az aks command invoke -o json --resource-group $CLUSTER_RESOURCE_GROUP --name $CLUSTER_NAME --command \"$KUBECTL_CMD\" --file $FILEPATH)\n  fi\n\n  FORMATTED_RESULT=$(echo $KUBECTL_CMD_RESULT | tr -d '\\n\\r')\n  KUBECTL_EXIT_CODE=$(echo $FORMATTED_RESULT | jq '.exitCode')\n\n  if [ $KUBECTL_EXIT_CODE != \"0\" ]\n  then\n    echo \"Failed to run kubectl command $KUBECTL_CMD\"\n    echo $KUBECTL_CMD_RESULT\n    exit $KUBECTL_EXIT_CODE\n  fi\n\n  echo $KUBECTL_CMD_RESULT\n\n}", "num_lines": 27}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nsource ./devenv/scripts/command_invoke_with_output.sh\n\nCLUSTER_RESOURCE_GROUP=$(cat devenv/state/cluster-info.json | jq '.ClusterResourceGroup' | tr -d '\"')\nCLUSTER_NAME=$(cat devenv/state/cluster-info.json | jq '.ClusterName' | tr -d '\"')\n\necho \"adding image tags to kustomize and generating configmaps...\"\ncp devenv/kustomize/e2e/* devenv/state/kustomize/e2e\ncp devenv/state/e2e-prom-client.txt devenv/state/kustomize/e2e\n\ncd devenv/state/kustomize/e2e # change workingdir to kustomize/e2e\nkustomize edit set image placeholderfortesterimage=`cat ../../e2e-image-tag.txt`\n\necho \"deleting any existing e2e job...\"\nDELETE_APPLY_RESULT=$(run_invoke $CLUSTER_NAME $CLUSTER_RESOURCE_GROUP \"kubectl delete jobs app-routing-operator-e2e -n kube-system --ignore-not-found && kubectl apply -k .\" \".\")\n\ncd ../.. # go back to root as working dir\n\n# wait until cluster has reached terminated status, keep checking until terminated result is not null\nNUM_ACTIVE=\"1\"\nwhile [ \"$NUM_ACTIVE\" = \"1\" ]\ndo\n  # use az cli to get status from pod JSON\n  STATUS=$(run_invoke $CLUSTER_NAME $CLUSTER_RESOURCE_GROUP 'kubectl get jobs --selector=app=app-routing-operator-e2e --output=\"jsonpath={.items[0].status}\" -n kube-system' | jq \".logs\" | tr -d '\\\\' )\n\n  # remove quotes at prefix and suffix from output to be able to use jquery\n  STATUSNOQUOTES=${STATUS#\"\\\"\"}\n  STATUSNOQUOTES=${STATUSNOQUOTES%\"\\\"\"}\n\n  NUM_ACTIVE=$(echo $STATUSNOQUOTES | jq '.active')\n  echo \"test status is currently $STATUSNOQUOTES\"\n\n  sleep 5\n\ndone\n\necho \"exited loop with status $STATUSNOQUOTES\"\n\nSUCCEEDED=$(echo $STATUSNOQUOTES | jq \".succeeded\")\n\necho \"Test finished, echoing test pod logs...\"\nPOD_LOGS_RESULT=$(run_invoke $CLUSTER_NAME $CLUSTER_RESOURCE_GROUP 'kubectl logs jobs/app-routing-operator-e2e -n kube-system' | tr -d '\\n\\r' | jq \".logs\")\necho $POD_LOGS_RESULT\n\n\nif [[ $SUCCEEDED == \"1\" ]]\nthen\n  echo \"TEST PASSED\"\n  exit 0\nfi\n\necho \"TEST FAILED WITH STATUS $STATUSNOQUOTES\"\nexit 1\n", "num_lines": 55}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\n\nsource ./devenv/scripts/command_invoke_with_output.sh\n\n# Load variables generated by tf\nexport CLUSTER_CLIENT_ID=$(cat devenv/state/deployment-auth-info.json | jq '.ClusterClientId' | tr -d '\"')\nexport ARM_CLIENT_TENANT_ID=$(cat devenv/state/deployment-auth-info.json | jq '.ArmTenantId' | tr -d '\"')\nexport RG_LOCATION=$(cat devenv/state/deployment-auth-info.json | jq '.ResourceGroupLocation' | tr -d '\"')\nexport DNS_ZONE_IDS=$(cat devenv/state/deployment-auth-info.json | jq '.DnsZones' | tr -d '\"')\nexport CLUSTER_UID=$(cat devenv/state/deployment-auth-info.json | jq '.ClusterUid' | tr -d '\"')\n\n# move into state before envsubst\nmkdir -p devenv/state/kustomize/operator-deployment\ncp devenv/kustomize/operator-deployment/* devenv/state/kustomize/operator-deployment\n\n# Write env to kustomize patch\nenvsubst < devenv/kustomize/operator-deployment/kustomization.yaml > devenv/state/kustomize/operator-deployment/kustomization.yaml\n\n# Get cluster information for az aks command invoke\nCLUSTER_RESOURCE_GROUP=$(cat devenv/state/cluster-info.json | jq '.ClusterResourceGroup' | tr -d '\"')\nCLUSTER_NAME=$(cat devenv/state/cluster-info.json | jq '.ClusterName' | tr -d '\"')\n\necho \"deploying to ${CLUSTER_NAME} in resource group ${CLUSTER_RESOURCE_GROUP}\"\ncd devenv/state/kustomize/operator-deployment\n\nAPPLY_RESULT=$(run_invoke $CLUSTER_NAME $CLUSTER_RESOURCE_GROUP \"kubectl apply -k .\" \".\")\n", "num_lines": 28}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nsource ./devenv/scripts/command_invoke_with_output.sh\n\n# Get cluster information for az aks command invoke\nCLUSTER_RESOURCE_GROUP=$(cat devenv/state/cluster-info.json | jq '.ClusterResourceGroup' | tr -d '\"')\nCLUSTER_NAME=$(cat devenv/state/cluster-info.json | jq '.ClusterName' | tr -d '\"')\n\nif [ -z $CLUSTER_RESOURCE_GROUP  ]; then\n  echo \"CLUSTER_RESOURCE_GROUP is empty\"\n  exit 1\nfi\n\nif [ -z $CLUSTER_NAME  ]; then\n  echo \"CLUSTER_NAME is empty\"\n  exit 1\nfi\n\nTAG=$(cat devenv/state/operator-image-tag.txt)\n\nif [ -z $TAG  ]; then\n  echo \"TAG is empty\"\n  exit 1\nfi\n\n# Push image\nCMD=\"kubectl set image -n kube-system deployments/app-routing-operator operator=$TAG\"\n\nrun_invoke $CLUSTER_NAME $CLUSTER_RESOURCE_GROUP \"$CMD\"\n", "num_lines": 30}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\necho \"beginning private cluster tests...\"\nmake dev CLUSTER_TYPE=private\nmake push\nmake e2e\n\n", "num_lines": 7}
{"repo_name": "aks-app-routing-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\necho \"beginning public cluster tests...\"\nmake clean\nmake dev CLUSTER_TYPE=public\nmake push\nmake e2e", "num_lines": 6}
{"repo_name": "aks-auditd", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n/app/setup.sh\nexec /app/monitor.sh", "num_lines": 4}
{"repo_name": "aks-auditd", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile :\ndo\n    if [ ! -z \"$(ls /audit-rules)\" ]; then\n        cp /audit-rules/* /node/etc/audit/rules.d/\n    fi\n    \n    if [ ! -z \"$(ls /audisp-plugins)\" ]; then\n        cp /audisp-plugins/* /node/etc/audisp/plugins.d/\n    fi\n\n    if [ ! -z \"$(ls /oms-config)\" ]; then\n        cp /oms-config/* /node/etc/opt/microsoft/omsagent/${LOG_ANALYTICS_WORKSPACE_ID}/conf/omsagent.d/\n    fi\n\n    chroot /node systemctl reload auditd\n    sleep 30\ndone\n\n", "num_lines": 21}
{"repo_name": "aks-auditd", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Install auditd on VMSS worker node\necho \"Installing auditd\"\nchroot /node apt-get update\nchroot /node apt-get install auditd -y\n\n# Make sure that auditd is running\nchroot /node systemctl start auditd\n\n", "num_lines": 11}
{"repo_name": "aks-baseline-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"getting akv secretid for $CERTNAME\";\nversionedSecretId=$(az keyvault certificate show -n $CERTNAME --vault-name $KVNAME --query \"sid\" -o tsv);\nunversionedSecretId=$(echo $versionedSecretId | cut -d'/' -f-5) # remove the version from the url;\necho $unversionedSecretId;\n\necho \"creating root certificate reference in application gateway\";\nrootcertcmd=\"az network application-gateway root-cert create --gateway-name $AGNAME  -g $RG -n $CERTNAME --keyvault-secret $unversionedSecretId\";\n$rootcertcmd", "num_lines": 11}
{"repo_name": "aks-baseline-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"getting id for ${CERTNAME}-fe\";\nversionedSecretId=$(az keyvault certificate show -n ${CERTNAME}-fe --vault-name $AKVNAME --query \"sid\" -o tsv);\nunversionedSecretId=$(echo $versionedSecretId | cut -d'/' -f-5) # remove the version from the url;\necho $unversionedSecretId;\n\necho \"Creating SSL Cert ${CERTNAME}-fe in application gateway\"\nfecertcmd=\"az network application-gateway ssl-cert create -n ${CERTNAME}-fe --gateway-name $AGNAME -g $RG --key-vault-secret-id $unversionedSecretId\";\n$fecertcmd", "num_lines": 11}
{"repo_name": "aks-baseline-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ncertnamebackend=$APPNAME\ncertnamefrontend=\"$APPNAME-fe\"\n\necho \"creating akv cert $certnamebackend\";\naz keyvault certificate create --vault-name $AKVNAME -n $certnamebackend -p \"$(az keyvault certificate get-default-policy | sed -e s/CN=CLIGetDefaultPolicy/CN=${certnamebackend}/g )\";\n\necho \"creating akv cert $certnamefrontend\";\naz keyvault certificate create --vault-name $AKVNAME -n $certnamefrontend -p \"$(az keyvault certificate get-default-policy | sed -e s/CN=CLIGetDefaultPolicy/CN=${certnamefrontend}/g )\";\n\nsleep 2m", "num_lines": 13}
{"repo_name": "aks-canipull", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\necho \"docker login to ${MCR_REGISTRY}\"\ndocker login ${MCR_REGISTRY} -u ${MCR_USERNAME} -p ${MCR_PASSWORD}\n\nTAG=${TAG:-$BUILD_NUMBER}\necho \"image tag will be ${TAG}\"\n\nexport IMG=\"${MCR_REGISTRY}/public/aks/${APP}:${TAG}\"\nmake docker-build\nmake docker-push\n\n# push to latest tag as well\nexport IMG=\"${MCR_REGISTRY}/public/aks/${APP}:latest\"\ndocker tag \"${MCR_REGISTRY}/public/aks/${APP}:${TAG}\" \"${IMG}\"\nmake docker-push\n", "num_lines": 21}
{"repo_name": "AKS-Construction", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Installing Cert Manager from $CERTMANAGERURI\"\nkubectl apply -f $CERTMANAGERURI\nsleep 1m\n\necho \"Installing Cert Manager ClusterIssuer\"\necho \"Email Address for Lets Encrypt: $EMAILAD\"\nhelm upgrade --install smokecertissuer $CERTMANAGERISSUERURI --set email=$EMAILAD\nsleep 1m", "num_lines": 11}
{"repo_name": "AKS-Construction", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Retrieving KubeletId for $AKSNAME in $RG\"\nKubeletId=$(az aks show -n $AKSNAME -g $RG --query \"identityProfile.kubeletidentity.clientId\" -o tsv)\nTenantId=$(az account show --query tenantId -o tsv)\nSubscriptionId=$(az account show --query id -o tsv)\n\nJSONSECRETPATH=\"azure.json\"\ncat<<EOF>$JSONSECRETPATH\n{\n\"userAssignedIdentityID\": \"$KubeletId\",\n\"tenantId\": \"$TenantId\",\n\"useManagedIdentityExtension\": true,\n\"subscriptionId\": \"$SubscriptionId\",\n\"resourceGroup\": \"$DNSRG\"\n}\nEOF\n\ncat azure.json\n\nkubectl create secret generic azure-config-file --dry-run=client -o yaml --from-file=azure.json | kubectl apply -f -\n\necho \"Installing ExternalDns for $DNSDOMAIN\"\nhelm upgrade --install externaldns $EXTERNALDNSURI --set externaldns.domainfilter=\"$DNSDOMAIN\"\n", "num_lines": 26}
{"repo_name": "AKS-Construction", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nbegin=$(date +\"%s\")\necho \"Creating Sku list...\"\n\n#Parameters\nlocationsInputFile=\"../../helper/src/locations.json\"\nskuFamiliesInputFile=\"../../helper/src/skuFamilies.json\"\nskuOutputFile=\"../../helper/src/vmSKUs.json\"\ntempFile=\"tempSkus.json\"\nephMinCacheSizeGB=137\nminCPUs=2\nmaxCPUs=8\n\n#Variables\nSubscriptionId=$(az account show --query id -o tsv)\n\n#if subscription id is null\nif [ -z \"$SubscriptionId\" ]; then exit 1; fi\n\necho \"Using SubscriptionId $SubscriptionId\"\n\n#Load Files\nlocations=$(cat $locationsInputFile | jq) ##Get Locations\nskuFamilies=$(cat $skuFamiliesInputFile | jq) #Get Virtual Machine SKU Families\n\n#Loop through sku families\nfor loc in $(echo \"${locations}\" | jq -r '.[] | @base64'); do\n    _jqloc() {\n    echo ${loc} | base64 --decode | jq -r ${1}\n    }\n    location=$(_jqloc '.key') #location\n    locationFilter=\"location%20eq%20'$location'\"\n    #Only call API for locations and not groups of locations\n    if [ $(_jqloc 'has(\"itemType\")') = false ]\n    then\n        reqUrl=\"https://management.azure.com/subscriptions/$SubscriptionId/providers/Microsoft.Compute/skus?api-version=2021-07-01&\\$filter=$locationFilter\"\n        skus=$(az rest --method GET --uri $reqUrl)\n\n        #Looking to reduce the json object size for performance\n        skus=$(echo \"${skus}\" | jq -r --argjson family \"$skuFamilies\"  '.value[] | select(.resourceType == \"virtualMachines\") | select(.family|  IN($family[].key) )')\n\n        for fam in $(echo \"${skuFamilies}\" | jq -r '.[] | @base64'); do\n            _jqfam() {\n            echo ${fam} | base64 --decode | jq -r ${1}\n            }\n            family=$(_jqfam '.key')\n            computeType=$(_jqfam '.computeType')\n\n            jq -n \\\n            --arg key \"$family\" \\\n            --arg text \"$(_jqfam '.text')\" \\\n            --arg itemType 2 \\\n            --arg location \"$location\" \\\n            --arg computeType \"$computeType\" \\\n            --arg eph false \\\n            '{key: $key, text: $text, itemType: $itemType | tonumber, eph: $eph | test(\"true\"), location: $location, computeType: $computeType}'\n\n            for row in $(echo \"${skus}\" | jq -r --arg family \"$family\" 'select(.family == $family) |  @base64'); do\n                _jq() {\n                echo ${row} | base64 --decode | jq -r ${1}\n                }\n                cpu=$(echo $(_jq) | jq -r        '.capabilities | .[] | select(.name==\"vCPUs\") | .value')\n                if [ $cpu -ge $minCPUs ] && [ $cpu -le $maxCPUs ];\n                then\n                    name=$(_jq '.name')\n                    osSize=$(echo $(_jq) | jq -r     '.capabilities | .[] | select(.name==\"OSVhdSizeMB\") | .value')\n                    ram=$(echo $(_jq) | jq -r        '.capabilities | .[] | select(.name==\"MemoryGB\") | .value')\n                    cachedSize=$(echo $(_jq) | jq -r '.capabilities | .[] | select(.name==\"CachedDiskBytes\") | .value')\n\n                    #Convert to GB\n                    osSizeGB=$(( osSize/1024 ))\n                    cacheGB=$(( cachedSize/1073741824 ))\n\n                    #Build text property\n                    cacheGB=$((cacheGB + 0))\n                    if [ $cacheGB -eq 0  ];\n                    then\n                        cache=\"\"\n                        eph=false\n                    else\n                        iops=$(echo $(_jq) | jq -r       '.capabilities | .[] | select(.name==\"CombinedTempDiskAndCachedIOPS\") | .value')\n                        cache=\", $cacheGB cache ($iops IOPS)\"\n                        if [ $cacheGB -ge $ephMinCacheSizeGB ];\n                        then\n                            eph=true\n                        else\n                            eph=false\n                        fi\n                    fi\n                    text=\"[$name]: $cpu vCPU, $ram RAM, $osSizeGB SSD $cache\"\n\n                    #Create JSON\n                    jq -n \\\n                    --arg key \"$name\" \\\n                    --arg text \"$text\" \\\n                    --arg eph $eph \\\n                    --arg location \"$location\" \\\n                    --arg computeType \"$computeType\" \\\n                    '{key: $key, text: $text, eph: $eph | test(\"true\"), location: $location, computeType: $computeType}'\n                fi\n            done\n        done\n    fi\ndone | jq -n '[inputs]'  > $tempFile\nmv $tempFile $skuOutputFile\n\n#Write out durable of script execution\ntermin=$(date +\"%s\")\ndifftimelps=$(($termin-$begin))\necho \"$(($difftimelps / 60)) minutes and $(($difftimelps % 60)) seconds elapsed for Script Execution.\"\n", "num_lines": 112}
{"repo_name": "AKS-Construction", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ---------------------------------------------------------------------------\n# NOTE: This needs to be kept in sync with the postdeploy.ps1 (PowerShell) script\n# ---------------------------------------------------------------------------\n\n# Fail if any command fails\nset -e\n\ningress=\"\"\nmonitor=\"\"\nenableMonitorIngress=\"false\"\ngrafanaHostname=\"grafana\"\ningressEveryNode=\"\"\ndnsZoneId=\"\"\ndenydefaultNetworkPolicy=\"\"\ncertEmail=\"\"\ncertClusterIssuer=\"letsencrypt-prod\"\ncontainerLogsV2=\"\"\n\nacrName=\"\"\nKubeletId=\"\"\nTenantId=\"\"\n\nrelease_version=\"\"\n\nwhile getopts \"p:g:n:r:\" opt; do\n  case ${opt} in\n    p )\n        IFS=',' read -ra params <<< \"$OPTARG\"\n        for i in \"${params[@]}\"; do\n            if [[ $i =~ (ingress|monitor|enableMonitorIngress|grafanaHostname|ingressEveryNode|dnsZoneId|denydefaultNetworkPolicy|certEmail|certClusterIssuer|acrName|KubeletId|TenantId|containerLogsV2)=([^ ]*) ]]; then\n                echo \"set ${BASH_REMATCH[1]}=${BASH_REMATCH[2]}\"\n                declare ${BASH_REMATCH[1]}=${BASH_REMATCH[2]}\n            else\n                echo \"Unknown parameter $i\"\n                show_usage=true\n                break\n            fi\n        done\n      ;;\n    r )\n     release_version=$OPTARG\n     ;;\n    \\? )\n      echo \"Unknown arg\"\n      show_usage=true\n\n      ;;\n  esac\ndone\n\ndnsZoneId_domain=\"\"\nif [ \"$dnsZoneId\" ]; then\n    if [[ $dnsZoneId =~ ^/subscriptions/([^/ ]+)/resourceGroups/([^/ ]+)/providers/Microsoft.Network/(dnszones|privateDnsZones)/([^/ ]+)$ ]]; then\n        dnsZoneId_sub=${BASH_REMATCH[1]}\n        dnsZoneId_rg=${BASH_REMATCH[2]}\n        dnsZoneId_type=${BASH_REMATCH[3]}\n        dnsZoneId_domain=${BASH_REMATCH[4]}\n    else\n        echo \"dnsZoneId parameter needs to be a resourceId format for Azure DNS Zone\"\n        show_usage=true\n    fi\n\n    if [ -z \"$KubeletId\" ] || [ -z \"$TenantId\" ]; then\n        echo \"If supplying dnsZoneId for extneral-dns, need to also provide 'KubeletId' && 'TenantId'\"\n        show_usage=true\n    fi\n\nfi\n\nif [ \"$ingressEveryNode\" ] && [[ ! $ingressEveryNode = \"true\" ]]; then\n echo \"supported ingressEveryNode parameter values (true)\"\n show_usage=true\nfi\n\nif [ \"$denydefaultNetworkPolicy\" ] && [[ ! $denydefaultNetworkPolicy = \"true\" ]]; then\n echo \"supported denydefaultNetworkPolicy parameter values (true)\"\n show_usage=true\nfi\n\nif [ \"$ingress\" ] && [[ ! $ingress =~ (appgw|contour|nginx|traefik) ]]; then\n echo \"supported ingress parameter values (appgw|contour|nginx|traefik)\"\n show_usage=true\nfi\n\nif [ \"$ingressEveryNode\" ] && [[ $ingress = \"appgw\" ]]; then\n echo \"ingressEveryNode only supported if ingress parameter is (nginx|contour|traefik)\"\n show_usage=true\nfi\n\nif [  \"$monitor\" ] && [[ ! \"$monitor\" = \"oss\" ]]; then\n echo \"supported monitor parameter values are (oss)\"\n show_usage=true\nfi\n\nif [  \"$certClusterIssuer\" ] && [[ ! $certClusterIssuer =~ (letsencrypt-staging|letsencrypt-prod) ]]; then\n echo \"supported cluster issuer parameter values are (letsencrypt-staging|letsencrypt-prod)\"\n show_usage=true\nfi\n\nif [ \"$show_usage\" ]; then\n    echo \"Usage: $0\"\n    echo \"args:\"\n    echo \" < -r release download url>  the github release download url where the dependent files will be referenced\"\n    echo \" [ -p: parameters] : Can provide one or multiple features:\"\n    echo \"     ingress=<appgw|contour|nginx> - Enable cluster AutoScaler with max nodes\"\n    echo \"     monitor=<oss> - Enable cluster AutoScaler with max nodes\"\n    echo \"     enableMonitorIngress=<true> - Enable Ingress for prometheus\"\n    echo \"     grafanaHostname=<true> - Specify a hostname for the grafana dashboard\"\n    echo \"     ingressEveryNode=<true> - Enable cluster AutoScaler with max nodes\"\n    echo \"     denydefaultNetworkPolicy=<true> - Deploy deny all network police\"\n    echo \"     dnsZoneId=<Azure DNS Zone resourceId> - Enable cluster AutoScaler with max nodes\"\n    echo \"     certEmail=<email for certman certificates> - Enables cert-manager\"\n    echo \"     certClusterIssuer=<letsencrypt-staging|letsencrypt-prod> - Specifies cert-manager cluster issuer used by grafana\"\n    echo \"     KubeletId=<managed identity of Kubelet> *Require for cert-manager\"\n    echo \"     TenantId=<AzureAD TenentId> *Require for cert-manager\"\n    echo \"     acrName=<name of ACR> * If provided, used imported images for 3rd party charts\"\n    echo \"     containerLogsV2=<true> - Enables ContainerLogsV2\"\n    exit 1\nfi\n\n#  Uses dependencies.json as a config file to retrieve Helm Chart version details\nget_image_property () {\n\n    fileloc=${release_version:-./helper/src}/dependencies.json\n\n    if [ \"$release_version\" ] && [[ $release_version == http* ]]; then\n      dependenciesJson=$(curl -sL $fileloc)\n    else\n      dependenciesJson=$(cat $fileloc)\n    fi\n\n    arrKey=(${1//./ })\n    nk=false\n    n=-1\n    l=()\n    while IFS=\"[: ,]+\" read -ra tokens; do\n        for i in \"${tokens[@]}\"; do\n            if [ \"$i\" = \"{\" ]; then\n            ((n+=1))\n            nk=true\n            elif  [ \"$i\" = \"}\" ]; then\n            ((n-=1))\n            else\n            if $nk; then\n                #echo \"testing: new key $n - $i\"\n                l[$n]=$(echo $i | tr -d '\"')\n                nk=false\n            else\n                print=true\n                #echo \"testing:  n=$n\"\n                for o in $(seq 0 $n); do\n                    #echo \"testing:  ${l[$o]} = ${arrKey[$o]}\"\n                    if [[ ! ${l[$o]} = ${arrKey[$o]} ]]; then\n                    print=false\n                    break\n                    fi\n                done\n                if $print; then\n                echo -n $i | tr -d '\"'\n                fi\n                nk=true\n            fi\n            fi\n        done\n    done <<<$dependenciesJson\n\n}\n\n#  AWK Not on Invote Command. Use the dependencies file to get the helmchart image details\nget_image_property_awk () {\n\n    fileloc=${release_version:-./helper/src}/dependencies.json\n\n    if [ \"$release_version\" ] && [[ $release_version == http* ]]; then\n      dependenciesJson=$(curl -sL $fileloc)\n    else\n      dependenciesJson=$(cat $fileloc)\n    fi\n\n    echo $dependenciesJson | awk -v key=$1 'BEGIN { FS=\"[: \\t\\n,]+\";  RS=\"[ \\t\\n]+:[ \\t\\n]+\"; nk=0; n=0; split(key,ka,\".\")} {\n        for(i=1;i<=NF;i++) {\n            if ($i ~ /[{\\[]/ ) {\n                n++; if ($1 == \"{\") nk=1; else nk=0\n            } else if ($i ~ /[}\\]]/) { n-- } else {\n                gsub(/\"/, \"\", $i)\n                if (nk) { l[n] = $i; nk=0\n                } else {\n                    p=1; for (o=0;o<=n;o++) if (l[o]!=ka[o]) p=0\n                    if (p) printf(\"%s\", $i)\n                    nk=1\n                }\n            }\n        }\n    }' -\n}\n\n\n## KH - Check this workaround is still needed with the latest AGIC - MAYBE NOT!\n\n#if [ \"$vnet_opt\" = \"byo\" ] && [ \"$ingress\" = \"appgw\" ]; then\n#    echo \"# ------------------------------------------------\"\n#    echo \"#          Workaround to enable AGIC with BYO VNET\"\n#    APPGW_RG_ID=\"$(az group show -n ${rg} --query id -o tsv)\"\n#    APPGW_ID=\"$(az network application-gateway show -g ${rg} -n ${agw} --query id -o tsv)\"\n#    az aks enable-addons -n ${aks} -g ${rg} -a ingress-appgw --appgw-id $APPGW_ID\n\n#    AKS_AGIC_IDENTITY_ID=\"$(az aks show -g ${rg} -n ${aks} --query addonProfiles.ingressApplicationGateway.identity.objectId -o tsv)\"\n#    az role assignment create --role \"Contributor\" --assignee-principal-type ServicePrincipal --assignee-object-id $AKS_AGIC_IDENTITY_ID --scope $APPGW_ID\n#    az role assignment create --role \"Reader\" --assignee-principal-type ServicePrincipal --assignee-object-id $AKS_AGIC_IDENTITY_ID --scope $APPGW_RG_ID\n\n    #  additionally required if appgwKVIntegration (app gateway has assigned identity)\n#    if true; then\n\n#        APPGW_IDENTITY=\"$(az network application-gateway show -g ${rg} -n ${agw} --query 'keys(identity.userAssignedIdentities)[0]' -o tsv)\"\n#        az role assignment create --role \"Managed Identity Operator\" --assignee-principal-type ServicePrincipal --assignee-object-id $AKS_AGIC_IDENTITY_ID --scope $APPGW_IDENTITY\n#    fi\n#fi\n\n## KH - Moved to Bicep!! YAY\n#\n#if [ \"$dnsZoneId\"  ] && [ \"$ingress\" ]; then\n\n#    KubeletId=$(az aks show -g ${rg} -n ${aks} --query identityProfile.kubeletidentity.clientId -o tsv)\n#    TenantId=$(az account show --query tenantId -o tsv)\n\n#        if [ \"$apisecurity\" = \"private\" ]; then\n#            # Import external-dns Image to ACR\n#            export acrName=$(az acr list -g ${rg} --query [0].name -o tsv)\n#            az acr import -n $acrName --source ${EXTERNAL_DNS_REGISTRY}/${EXTERNAL_DNS_REPO}:${EXTERNAL_DNS_TAG} --image ${EXTERNAL_DNS_REPO}:${EXTERNAL_DNS_TAG}\n#        fi\n#fi\n\n# ingress_controller_kind=\"Deployment\"\n# ingress_externalTrafficPolicy=\"Cluster\"\n# if [ \"$ingressEveryNode\" ]; then\n#     ingress_controller_kind=\"DaemonSet\"\n#     ingress_externalTrafficPolicy=\"Local\"\n# fi\ningress_metrics_enabled=false\nif [ \"$monitor\" = \"oss\" ]; then\n    ingress_metrics_enabled=true\nfi\n\ningressClass=$ingress\nlegacyIngressClass=$ingress\n# https://azure.github.io/application-gateway-kubernetes-ingress/ingress-v1/\nif [ \"$ingress\" = \"appgw\" ]; then\n    ingressClass=\"azure-application-gateway\"\n    legacyIngressClass=\"azure/application-gateway\"\nfi\n\nprometheus_namespace=\"monitoring\"\nprometheus_helm_release_name=\"monitoring\"\n\nif [ \"$monitor\" = \"oss\" ]; then\n    echo \"# ------------------------------------------------\"\n    echo \"#              Install kube-prometheus-stack chart\"\n    helm repo add prometheus-community https://prometheus-community.github.io/helm-charts\n    helm repo update\n    kubectl create namespace ${prometheus_namespace} --dry-run=client -o yaml | kubectl apply -f -\n    helm upgrade --install ${prometheus_helm_release_name} prometheus-community/kube-prometheus-stack --namespace ${prometheus_namespace} \\\n        --set grafana.ingress.enabled=${enableMonitorIngress} \\\n        --set grafana.ingress.annotations.\"cert-manager\\.io/cluster-issuer\"=$certClusterIssuer \\\n        --set grafana.ingress.annotations.\"ingress\\.kubernetes\\.io/force-ssl-redirect\"=\\\"true\\\" \\\n        --set grafana.ingress.ingressClassName=${ingressClass} \\\n        --set grafana.ingress.hosts[0]=${grafanaHostname}.${dnsZoneId_domain} \\\n        --set grafana.ingress.tls[0].hosts[0]=${grafanaHostname}.${dnsZoneId_domain},grafana.ingress.tls[0].secretName=aks-grafana\nfi\n\n\nif [ \"$ingress\" = \"nginx\" ]; then\n\n    ingress_controller_kind=\"Deployment\"\n    ingress_externalTrafficPolicy=\"Cluster\"\n    if [ \"$ingressEveryNode\" ]; then\n    ingress_controller_kind=\"DaemonSet\"\n    ingress_externalTrafficPolicy=\"Local\"\n    fi\n    nginx_namespace=\"ingress-basic\"\n    nginx_helm_release_name=\"nginx-ingress\"\n\n    echo \"# ------------------------------------------------\"\n    echo \"#                 Install Nginx Ingress Controller\"\n    kubectl create namespace ${nginx_namespace} --dry-run=client -o yaml | kubectl apply -f -\n    helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx\n    helm upgrade --install ${nginx_helm_release_name} ingress-nginx/ingress-nginx \\\n        --set controller.publishService.enabled=true \\\n        --set controller.kind=${ingress_controller_kind} \\\n        --set controller.service.externalTrafficPolicy=${ingress_externalTrafficPolicy} \\\n        --set controller.metrics.enabled=${ingress_metrics_enabled} \\\n        --set controller.metrics.serviceMonitor.enabled=${ingress_metrics_enabled} \\\n        --set controller.metrics.serviceMonitor.namespace=${prometheus_namespace} \\\n        --set controller.metrics.serviceMonitor.additionalLabels.release=${prometheus_helm_release_name} \\\n        --namespace ${nginx_namespace}\nfi\n\nif [ \"$ingress\" = \"traefik\" ]; then\n\n    ingress_controller_kind=\"Deployment\"\n    ingress_externalTrafficPolicy=\"Cluster\"\n    if [ \"$ingressEveryNode\" ]; then\n    ingress_controller_kind=\"DaemonSet\"\n    ingress_externalTrafficPolicy=\"Local\"\n    fi\n\n    traefik_namespace=\"ingress-basic\"\n    traefik_helm_release_name=\"traefik\"\n\n    echo \"# ------------------------------------------------\"\n    echo \"#                 Install Traefik Ingress Controller\"\n    kubectl create namespace ${traefik_namespace} --dry-run=client -o yaml | kubectl apply -f -\n    helm repo add traefik https://helm.traefik.io/traefik\n    helm upgrade --install ${traefik_helm_release_name} traefik/traefik \\\n        --set deployment.kind=\"${ingress_controller_kind}\" \\\n        --set service.spec.externalTrafficPolicy=${ingress_externalTrafficPolicy} \\\n        --set providers.kubernetesIngress.publishedService.enabled=true \\\n        --set metrics.prometheus.enabled=true \\\n        --namespace ${traefik_namespace}\nfi\n\n\nif [ \"$ingress\" = \"contour\" ]; then\n\n    ingress_controller_kind=\"deployment\"\n    ingress_externalTrafficPolicy=\"Cluster\"\n    if [ \"$ingressEveryNode\" ]; then\n    ingress_controller_kind=\"daemonset\"\n    ingress_externalTrafficPolicy=\"Local\"\n    fi\n\n    contour_namespace=\"ingress-basic\"\n    contour_helm_release_name=\"contour-ingress\"\n    # https://artifacthub.io/packages/helm/bitnami/contour\n    echo \"# ------------------------------------------------\"\n    echo \"#               Install Contour Ingress Controller\"\n    helm repo add bitnami https://charts.bitnami.com/bitnami\n    helm upgrade --install ${contour_helm_release_name} bitnami/contour --namespace ${contour_namespace} --create-namespace \\\n        --set envoy.kind=${ingress_controller_kind} \\\n        --set contour.service.externalTrafficPolicy=${ingress_externalTrafficPolicy} \\\n        --set metrics.serviceMonitor.enabled=${ingress_metrics_enabled} \\\n        --set commonLabels.\"release\"=${prometheus_helm_release_name} \\\n        --set metrics.serviceMonitor.namespace=${prometheus_namespace}\nfi\n\n\n# External DNS\n# external-dns needs permissions to make changes in the Azure DNS server.\n# https://github.com/kubernetes-sigs/external-dns/blob/master/docs/tutorials/azure.md#azure-managed-service-identity-msi\nif [ \"$dnsZoneId\" ]; then\n\n    echo \"# ------------------------------------------------\"\n    echo \"#                             Install external-dns\"\n    kubectl create secret generic aks-kube-msi --from-literal=azure.json=\"{\n        userAssignedIdentityID: $KubeletId,\n        tenantId: $TenantId,\n        useManagedIdentityExtension: true,\n        subscriptionId: ${dnsZoneId_sub},\n        resourceGroup: ${dnsZoneId_rg}\n    }\" --dry-run=client -o yaml | kubectl apply -f -\n\n    provider=\"azure\"\n    if [ \"$dnsZoneId_type\" = \"privateDnsZones\" ]; then\n        provider=\"azure-private-dns\"\n    fi\n\n    EXTERNAL_DNS_REPO=$(get_image_property \"externaldns.1_9_0.images.image.repository\")\n    dnsImageRepo=\"$(get_image_property \"externaldns.1_9_0.images.image.registry\")/${EXTERNAL_DNS_REPO}\"\n    if [ \"$acrName\" ]; then\n        dnsImageRepo=\"${acrName}.azurecr.io/${EXTERNAL_DNS_REPO}\"\n    fi\n\n    helm upgrade --install externaldns \"https://$(get_image_property \"externaldns.1_9_0.github_https_url\")\" \\\n    --set domainFilters={\"${dnsZoneId_domain}\"} \\\n    --set provider=\"${provider}\" \\\n    --set extraVolumeMounts[0].name=aks-kube-msi,extraVolumeMounts[0].mountPath=/etc/kubernetes,extraVolumeMounts[0].readOnly=true \\\n    --set extraVolumes[0].name=aks-kube-msi,extraVolumes[0].secret.secretName=aks-kube-msi \\\n    --set image.repository=${dnsImageRepo} \\\n    --set image.tag=$(get_image_property \"externaldns.1_9_0.images.image.tag\")\nfi\n\n\nif [ \"$certEmail\" ]; then\n\n    echo \"# ------------------------------------------------\"\n    echo \"#                             Install cert-manager\"\n\n    #certMan_Version=\"v1.8.2\"\n    # NOT Needed anymore!\n    #if [ \"$ingress\" = \"appgw\" ]; then\n    #    echo \"Downgrading cert-manager for AppGateway IC\"\n    #    certMan_Version=\"v1.5.3\"\n    #fi\n\n\n    kubectl apply -f \"https://$(get_image_property \"cert_manager.1_8_2.github_https_url\")\"\n    sleep 30s # wait for cert-manager webhook to install\n\n    helm upgrade --install letsencrypt-issuer ${release_version:-./postdeploy/helm}/Az-CertManagerIssuer-0.3.0.tgz \\\n        --set email=${certEmail}  \\\n        --set ingressClass=${legacyIngressClass}\nfi\n\n\nif [ \"$denydefaultNetworkPolicy\" ]; then\n    echo \"# ----------- Default Deny All Network Policy, east-west traffic in cluster\"\n    kubectl apply -f ${release_version:-./postdeploy/k8smanifests}/networkpolicy-deny-all.yml\nfi\n\nif [ \"$containerLogsV2\" ]; then\n    echo \"Downloading default ConfigMap\"\n    configMapYamlFile=\"$(curl -s https://raw.githubusercontent.com/microsoft/Docker-Provider/ci_prod/kubernetes/container-azm-ms-agentconfig.yaml)\"\n    echo \"Setting containerlog_schema_version to v2\"\n    configMapYamlFile=$(sed 's/#\\[log_collection_settings.schema\\]/[log_collection_settings.schema]/'<<<$configMapYamlFile)\n    configMapYamlFile=$(sed 's/# containerlog_schema_version = \\\"v2\\\"/containerlog_schema_version = \"v2\"/'<<<$configMapYamlFile)\n    echo \"$configMapYamlFile\" > container-azm-ms-agentconfig.yaml\n    echo \"Applying ConfigMap using kubectl apply\"\n    kubectl apply -f container-azm-ms-agentconfig.yaml\nfi", "num_lines": 420}
{"repo_name": "AKS-Construction", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n\nget_image_property () {\n\n    dependenciesJson=$(cat $1)\n    arrKey=(${2//./ })\n    nk=false\n    n=-1\n    l=()\n    while IFS=\"[: ,]+\" read -ra tokens; do\n        for i in \"${tokens[@]}\"; do\n            if [ \"$i\" = \"{\" ]; then\n            ((n+=1))\n            nk=true\n            elif  [ \"$i\" = \"}\" ]; then\n            ((n-=1))\n            else\n            if $nk; then\n                #echo \"new key $n - $i\"\n                l[$n]=$(echo $i | tr -d '\"')\n                nk=false\n            else\n                print=true\n                #echo \"testing:  n=$n\"\n                for o in $(seq 0 $n); do\n\n                    #echo \"testing:  ${l[$o]} = ${arrKey[$o]}\"\n                    if [[ ! ${l[$o]} = ${arrKey[$o]} ]]; then\n                    print=false\n                    break\n                    fi\n                done\n                if $print; then\n                echo -n $i | tr -d '\"'\n                fi\n                nk=true\n            fi\n            fi\n        done\n    done <<<$dependenciesJson\n}\n\nTEST=$(get_image_property $1 \"externaldns.1_9_0.images.image.repository\")\necho $TEST", "num_lines": 45}
{"repo_name": "aks-create-action", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -l\n\n. /root/.bashrc\n\nexport ARM_CLIENT_ID=$INPUT_ARM_CLIENT_ID\nexport ARM_CLIENT_SECRET=$INPUT_ARM_CLIENT_SECRET\nexport ARM_SUBSCRIPTION_ID=$INPUT_ARM_SUBSCRIPTION_ID\nexport ARM_TENANT_ID=$INPUT_ARM_TENANT_ID\nexport STORAGE_ACCOUNT_NAME=$INPUT_STORAGE_ACCOUNT_NAME\nexport STORAGE_CONTAINER_NAME=$INPUT_STORAGE_CONTAINER_NAME\nexport STORAGE_ACCESS_KEY=$INPUT_STORAGE_ACCESS_KEY\nexport IAC_TYPE=$INPUT_IAC_TYPE\n\nexport TF_VAR_resource_group_name=$INPUT_RESOURCE_GROUP_NAME\nexport TF_VAR_cluster_name=$INPUT_CLUSTER_NAME\nexport TF_VAR_create_acr=$INPUT_CREATE_ACR\nexport TF_IN_AUTOMATION=true\n\n\necho \"*******************\"\necho \"Running init\"\necho \"*******************\"\n\ncd /action/$INPUT_CLUSTER_SIZE\n\n# Using Pulumi\nif [ $INPUT_IAC_TYPE = \"pulumi\" ]; then\n echo \"Using Pulumi\"\n\n /pulumi/bin/pulumi stack select dev --create\n /pulumi/bin/pulumi config set azure:clientId ${ARM_CLIENT_ID}\n /pulumi/bin/pulumi config set azure:clientSecret ${ARM_CLIENT_SECRET} --secret\n /pulumi/bin/pulumi config set azure:tenantId ${ARM_TENANT_ID}\n /pulumi/bin/pulumi config set azure:subscriptionId ${ARM_SUBSCRIPTION_ID}\n\n  if [ $INPUT_ACTION_TYPE = \"destroy\" ]; then\n      echo \"*******************\"\n      echo \"Running destroy\"\n      echo \"*******************\"\n      /pulumi/bin/pulumi destroy -force\n  else\n      echo \"*******************\"\n      echo \"Running apply\"\n      echo \"*******************\"\n      /pulumi/bin/pulumi up --yes\n  fi\n\n  exit 1\nfi\n\n# Using Terraform -  Default\necho \"Using Terraform\"\nterraform init -backend-config=\"resource_group_name=${TF_VAR_resource_group_name}\" \\\n-backend-config=\"storage_account_name=${STORAGE_ACCOUNT_NAME}\" \\\n-backend-config=\"container_name=${STORAGE_CONTAINER_NAME}\" \\\n-backend-config=\"key=${TF_VAR_cluster_name}.tfstate\" \\\n-backend-config=\"access_key=${STORAGE_ACCESS_KEY}\"\n\nif [ $INPUT_ACTION_TYPE = \"destroy\" ]; then\n    echo \"*******************\"\n    echo \"Running destroy\"\n    echo \"*******************\"\n    terraform destroy -force\nelse\n    echo \"*******************\"\n    echo \"Running plan\"\n    echo \"*******************\"\n\n    terraform plan -no-color -out=tfplan -input=false\n\n    echo \"*******************\"\n    echo \"Running apply\"\n    echo \"*******************\"\n\n    terraform apply tfplan\nfi\n\n\n\n", "num_lines": 80}
{"repo_name": "aks-create-action", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nusage=\"$(basename \"$0\") [-h] [-c CLUSTER_NAME] [-g RESOURCE_GROUP_NAME] [-s SUBSCRIPTION_ID] [-r REGION]\nCreates a service principal and storage account for using terraform on Azure\nwhere:\n    -h  show this help text\n    -c  desired cluster name\n    -g  desired resource group name\n    -s  subscription id for cluster\n    -r  region for cluster\"\n\nwhile getopts h:c:g:s:r: flag\ndo\n    case \"${flag}\" in\n        h) echo \"$usage\"; exit;;\n        c) cluster_name=${OPTARG};;\n        g) resource_group_name=${OPTARG};;\n        s) subscription=${OPTARG};;\n        r) region=${OPTARG};;\n        :) printf \"missing argument for -%s\\n\" \"$OPTARG\" >&2; echo \"$usage\" >&2; exit 1;;\n        \\?) printf \"illegal option: -%s\\n\" \"$OPTARG\" >&2; echo \"$usage\" >&2; exit 1;;\n    esac\ndone\n\n# mandatory arguments\nif [ ! \"$cluster_name\" ] || [ ! \"$resource_group_name\" ] || [ ! \"$subscription\" ] || [ ! \"$region\" ]; then\n  echo \"all arguments must be provided\"\n  echo \"$usage\" >&2; exit 1\nfi\n\necho \"Arguments provided:\"\necho \"Cluster Name: $cluster_name\";\necho \"Resource Group Name: $resource_group_name\";\necho \"Subscription: $subscription\";\necho \"Region: $region\";\n\nSTORAGE_ACCOUNT_NAME=$(echo \"${resource_group_name}\" | tr '[:upper:]' '[:lower:]')$RANDOM\nCONTAINER_NAME=$(echo \"${cluster_name}\" | tr '[:upper:]' '[:lower:]')tstate\n\naz account set --subscription $subscription &> /dev/null\n# Create resource group\naz group create --location $region --resource-group $resource_group_name &> /dev/null\n\n#Create service principal and give it access to group\nSP_OUTPUT=$(az ad sp create-for-rbac --name $resource_group_name --role contributor --scopes /subscriptions/$subscription/resourceGroups/$resource_group_name --sdk-auth)\necho $SP_OUTPUT\nARM_CLIENT_ID=$(echo $SP_OUTPUT | jq -r .clientId)\nARM_CLIENT_SECRET=$(echo $SP_OUTPUT | jq -r .clientSecret)\nARM_TENANT_ID=$(echo $SP_OUTPUT | jq -r .tenantId)\n\n\n# Create storage account\naz storage account create --resource-group $resource_group_name --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob\n\n# Get storage account key\nACCOUNT_KEY=$(az storage account keys list --resource-group $resource_group_name --account-name $STORAGE_ACCOUNT_NAME --query '[0].value' -o tsv)\n\n# Create blob container\naz storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key $ACCOUNT_KEY\n\necho \"____________________________________________________________\"\necho \"____________________________________________________________\"\necho \"the following should be passed to the action\"\necho \"CLUSTER_NAME: $cluster_name\";\necho \"RESOURCE_GROUP_NAME: $resource_group_name\";\necho \"STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME\"\necho \"STORAGE_CONTAINER_NAME: $CONTAINER_NAME\"\necho \"STORAGE_ACCESS_KEY: $ACCOUNT_KEY\"\necho \"ARM_CLIENT_ID: $ARM_CLIENT_ID\"\necho \"ARM_CLIENT_SECRET: $ARM_CLIENT_SECRET\"\necho \"ARM_SUBSCRIPTION_ID: $subscription\"\necho \"ARM_TENANT_ID: $ARM_TENANT_ID\"", "num_lines": 72}
{"repo_name": "AKS-Edge-Labs", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (C) 2021 scalers.ai\n\nWELD_POROSITY_MODEL=/models/weld_porosity/FP32/weld-porosity-detection-0001.xml\n\nrunPipeline() {\ngst-launch-1.0 \\\n    rtspsrc location=$INPUT ! decodebin  ! videoconvert ! video/x-raw,format=BGRx ! \\\n    gvapython module=weld_porosity.py class=InferenceTime ! \\\n    gvainference model=${WELD_POROSITY_MODEL} inference-interval=1  device=$DEVICE ! \\\n    gvapython  module=weld_porosity.py class=WeldPorosity ! \\\n    gvametaconvert format=json add-tensor-data=true ! \\\n    gvametapublish method=mqtt address=$MQTT_IP:1883 topic=weld\n\nreturn \n}\n\nuntil runPipeline;\ndo\n    echo 'Restarting pipeline'\n    sleep 1\ndone", "num_lines": 21}
{"repo_name": "AKS-Edge-Labs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#sh\n# Copyright (C) 2021 scalers.ai\n\n./rtsp-simple-server & \\\npython3 streamer.py", "num_lines": 5}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -x\n\ngroup=$1\nsubscription=$2\nlocation=$3\n\naz group create --name $group --location $3 --subscription $2\n\n# Create role\naz ad sp create-for-rbac --role=\"Contributor\" --scopes=\"/subscriptions/$subscription/resourceGroups/$group\" >~/.kube/$group-sp.json\n# shellcheck disable=SC2002,SC2155\nexport appId=$(cat ~/.kube/$group-sp.json | jq -r .appId)\n# shellcheck disable=SC2002,SC2155\nexport password=$(cat ~/.kube/$group-sp.json | jq -r .password)\n\n# give the sp time to propagate\nsleep 180\n\n# Deploy Cluster\naks-engine deploy --subscription-id $subscription --resource-group $group --location $location us --api-model apimodel.json --dns-prefix $group\n\ncp $(pwd)/_output/$group/kubeconfig/kubeconfig.eastus.json ~/.kube/$group.json\n\nsleep 180\n\naks-engine addpool --subscription-id $subscription --resource-group $group --location $location us --api-model _output/$group/apimodel.json --agent-pool agentpool.json\n\naz vmss list -g $group --subscription $subscription -o table\n\nKUBECONFIG=~/.kube/$group.json kubectl get nodes\n\n#cleanup\n#az vmss delete -n $(az vmss list -g $group --subscription $subscription -o json | jq .[1].name) -g $group --subscription $subscription --no-wait\n\n#az group delete -g $group --subscription $subscription --no-wait\n", "num_lines": 37}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nKIND= # allowed values \"deployment\" or \"statefulset\"\nNS= # namespace name of the deployment/statefulset, ex: \"default\"\nNAME= # resource name of the deployment/statefulset\nPVC_LIST= # PVCs to migrate, ex: \"pvc1-name pvc2-name\"\nTMP=$(mktemp -d)\n\nmkdir -p ${TMP}/${KIND} ${TMP}/pvc ${TMP}/pv\n\n# Back kind/name, remove ID\nID_PROPS=\".metadata.annotations, .metadata.creationTimestamp, .metadata.generation, .metadata.resourceVersion, .metadata.uid, .metadata.managedFields, .status, .spec.template.metadata.creationTimestamp\"\nif [[ \"${KIND,,}\" == \"statefulset\" ]]; then \n    ID_PROPS=\"${ID_PROPS}, .spec.volumeClaimTemplates[].metadata.creationTimestamp, .spec.volumeClaimTemplates[].status\"\nfi\n\nkubectl get ${KIND}/${NAME} -n ${NS} -o json | \\\n    jq \"del(${ID_PROPS})\" \\\n    > ${TMP}/${KIND}/${NS}-${NAME}.json\n\n# Delete kind/name\nkubectl delete -n ${NS} ${KIND}/${NAME}\n\nfor pvc in ${PVC_LIST}\ndo\n    # Get PV data from PVC\n    PV_NAME=$(kubectl get pvc ${pvc} -o jsonpath='{.spec.volumeName}')\n    PV_DISK_URI=$(kubectl get pv ${PV_NAME} -o jsonpath='{.spec.azureDisk.diskURI}')\n    PV_FS_TYPE=$(kubectl get pv ${PV_NAME} -o jsonpath='{.spec.azureDisk.fSType}')\n\n    # Back PVC, remove ID\n    kubectl get pvc ${pvc} -n ${NS} -o json | \\\n        jq 'del(.metadata.annotations, .metadata.creationTimestamp, .metadata.resourceVersion, .metadata.uid, .status)' \\\n        > ${TMP}/pvc/${NS}-${pvc}.json\n\n    # Back PV, remove ID, remove spec.azureDisk, add spec.csi\n    cat << EOF > ${TMP}/csi-pv.spec\n{\n    \"csi\": {\n        \"driver\": \"disk.csi.azure.com\",\n        \"volumeHandle\": \"${PV_DISK_URI}\",\n        \"fsType\": \"${PV_FS_TYPE}\"\n    }\n}\nEOF\n\n    kubectl get pv ${PV_NAME} -n ${NS} -o json | \\\n        jq 'del(.metadata.annotations, .metadata.creationTimestamp, .metadata.managedFields, .metadata.resourceVersion, .metadata.uid, .status, .spec.claimRef.resourceVersion, .spec.claimRef.uid, .spec.azureDisk)' | \\\n        jq \".spec += $(cat ${TMP}/csi-pv.spec)\" \\\n        > ${TMP}/pv/${NS}-${PV_NAME}.json\n\n    # Retain Azure disk on PV deletion\n    kubectl patch pv ${PV_NAME} -p '{\"spec\":{\"persistentVolumeReclaimPolicy\":\"Retain\"}}'\n\n    # Delete PVC+PV pair\n    kubectl delete -n ${NS} pvc/${pvc}\n    kubectl delete pv/${PV_NAME}\ndone\n\n# Recreate resources\nkubectl apply -f ${TMP}/pv\nif [[ \"${KIND,,}\" == \"deployment\" ]]; then \n    kubectl apply -f ${TMP}/pvc; \nfi\nkubectl apply -f ${TMP}/${KIND}", "num_lines": 65}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Add support for registering host on dns server. Must allow non-secure updates\n\nset -e\n\nDOMAINNAME=$1\n\necho $(date) \" - Starting Script\"\n\ncat > /etc/network/if-up.d/register-dns <<EOFDHCP\n#!/bin/sh\n\n# only execute on the primary nic\nif [ \"\\${IFACE}\" = \"eth0\" ]\nthen\n    ip=\\$(ip address show eth0 | awk '/inet / {print \\$2}' | cut -d/ -f1)\n    host=\\$(hostname -s)\n    nsupdatecmds=/var/tmp/nsupdatecmds\n    echo \"update delete \\${host}.${DOMAINNAME} a\" > \\$nsupdatecmds\n    echo \"update add \\${host}.${DOMAINNAME} 3600 a \\${ip}\" >> \\$nsupdatecmds\n    echo \"send\" >> \\$nsupdatecmds\n\n    nsupdate \\$nsupdatecmds\nfi\nEOFDHCP\n\nchmod 755 /etc/network/if-up.d/register-dns\n\nif ! grep -Fq \"${DOMAINNAME}\" /etc/dhcp/dhclient.conf\nthen\n    echo $(date) \" - Adding domain to dhclient.conf\"\n\n    echo \"supersede domain-name \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\n    echo \"prepend domain-search \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\nfi\n\n# service networking restart\necho $(date) \" - Restarting network\"\nsudo ifdown eth0 && sudo ifup eth0", "num_lines": 39}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script file to run hello-world in bash\n\necho \"hello\"\n", "num_lines": 6}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script file to install the docker hello-world container\n\nset -e\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        if /usr/local/bin/kubectl cluster-info\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        if /usr/bin/docker ps | grep apiserver\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\n# Deploy container\necho $(date) \" - Deploying hello-world container\"\n\nkubectl run hello-world --quiet --image=busybox --restart=OnFailure -- echo \"Hello Kubernetes!\"\n\necho $(date) \" - run kubectl get pods --show-all to list the pods\"\necho $(date) \" - run kubectl logs (passing the pod name gathered from kubectl get pods)\"\necho $(date) \" - Script complete\"\n", "num_lines": 44}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Setting kubeconfig\"\nexport KUBECONFIG=/var/lib/kubelet/kubeconfig\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        if /usr/local/bin/kubectl cluster-info\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        if /usr/bin/docker ps | grep apiserver\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\nmaster_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=master --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_master_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning master nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_MASTER=$(master_nodes)\n\n        if [[ -n $FIRST_K8S_MASTER ]]; then\n            echo $(date) \" - kubectl is returning master nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return master nodes in the alotted time\"\n    return 1\n}\n\nagent_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_agent_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning agent nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_AGENT=$(agent_nodes)\n\n        if [[ -n $FIRST_K8S_AGENT ]]; then\n            echo $(date) \" - kubectl is returning agent nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return agent nodes in the alotted time\"\n    return 1\n}\n\nshould_this_node_run_extension() {\n    FIRST_K8S_MASTER=$(master_nodes)\n    if [[ $FIRST_K8S_MASTER = $(hostname) ]]; then\n        echo $(date) \" - Local node $(hostname) is found to be the first master node $FIRST_K8S_MASTER\"\n        return\n    else\n        FIRST_K8S_AGENT=$(agent_nodes)\n        if [[ $FIRST_K8S_AGENT = $(hostname) ]]; then\n            echo $(date) \" - Local node $(hostname) is found to be the first agent node $FIRST_K8S_AGENT\"\n            return\n        else\n            echo $(date) \" - Local node $(hostname) is not the first master node $FIRST_K8S_MASTER or the first agent node $FIRST_K8S_AGENT\"\n            return 1\n        fi\n    fi\n}\n\nstorageclass_param() {\n\tif kubectl get no -l kubernetes.io/role=agent -l storageprofile=managed --no-headers -o jsonpath=\"{.items[0].metadata.name}\" >/dev/null 2>&1; then\n\t\techo '--set server.persistentVolume.storageClass=managed-standard'\n\tfi\n}\n\nwait_for_tiller() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is Helm running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if helm version >/dev/null 2>&1; then\n            echo $(date) \" - Helm is running\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - Helm failed to start in the alotted time\"\n    return 1\n}\n\ninstall_helm() {\n    echo $(date) \" - Downloading helm\"\n    curl https://storage.googleapis.com/kubernetes-helm/helm-v2.6.2-linux-amd64.tar.gz > helm-v2.6.2-linux-amd64.tar.gz\n    tar -zxvf helm-v2.6.2-linux-amd64.tar.gz\n    mv linux-amd64/helm /usr/local/bin/helm\n    echo $(date) \" - Downloading prometheus values\"\n\n    curl \"$1\" > prometheus_values.yaml\n\n    sleep 10\n\n    echo $(date) \" - helm version\"\n    helm version\n    helm init\n\n    echo $(date) \" - helm installed\"\n}\n\ndaemonset_api() {\n    SERVER_VERSION_REGEX=\"Server Version: v([0-9]+)\\.([0-9]+)\\.([0-9]+)$\"\n    K8S_SERVER_VERSION=$(kubectl version --short | grep Server)\n    K8S_SERVER_VERSION_MAJOR=$(echo \"$K8S_SERVER_VERSION\" | sed -r \"s/$SERVER_VERSION_REGEX/\\1/g\")\n    K8S_SERVER_VERSION_MINOR=$(sed -r \"s/$SERVER_VERSION_REGEX/\\2/g\" \"$K8S_SERVER_VERSION\")\n\n    if [[ $K8S_SERVER_VERSION_MAJOR -gt 1 ]]; then\n        echo \"apps/v1\"\n    elif [[ $K8S_SERVER_VERSION_MAJOR -eq 1 ]]; then\n        if [[ $K8S_SERVER_VERSION_MINOR -gt 8 ]]; then\n            echo \"apps/v1\"\n        else\n            echo \"apps/v1beta2\"\n        fi\n    fi\n}\n\ninstall_cadvisor() {\n    echo \"$(date) - Installing cAdvisor\"\n    local NAMESPACE=\"$1\"\n    echo \"$(date) - Using namespace $NAMESPACE\"\n    local CADVISOR_DS_CONFIG_URL=\"$2\"\n    echo \"$(date) - Using cAdvisor config at $CADVISOR_DS_CONFIG_URL\"\n\n    curl -o cadvisor_ds.yml \"$CADVISOR_DS_CONFIG_URL\"\n    DAEMONSET_API=$(daemonset_api)\n    echo \"$(date) - Using DaemonSet api group $DAEMONSET_API\"\n    sed -i 's|DAEMONSET_API|'\"$DAEMONSET_API\"'|g' cadvisor_ds.yml\n    kubectl apply -f ./cadvisor_ds.yml --namespace=$NAMESPACE\n}\n\nupdate_helm() {\n    echo $(date) \" - Updating Helm repositories\"\n    helm repo update\n}\n\ninstall_prometheus() {\n    PROM_RELEASE_NAME=monitoring\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Prometheus Helm chart\"\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        if helm install -f prometheus_values.yaml \\\n            --name $PROM_RELEASE_NAME \\\n            --version 5.1.3 \\\n            --namespace $NAMESPACE stable/prometheus $(storageclass_param); then\n            echo $(date) \" - Helm install successfully completed\"\n            break\n        else\n            echo $(date) \" - Helm install returned a non-zero exit code. Retrying.\"\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    PROM_POD_PREFIX=\"$PROM_RELEASE_NAME-prometheus-server\"\n    DESIRED_POD_STATE=Running\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the prometheus server pod ($PROM_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $PROM_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE; then\n            echo $(date) \" - $PROM_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\ninstall_grafana() {\n    GF_RELEASE_NAME=dashboard\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Grafana Helm chart\"\n    helm install \\\n        --name $GF_RELEASE_NAME \\\n        --version 0.8.5 \\\n        --namespace $NAMESPACE stable/grafana $(storageclass_param)\n\n    GF_POD_PREFIX=\"$GF_RELEASE_NAME-grafana\"\n    DESIRED_POD_STATE=Running\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the grafana pod ($GF_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $GF_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE; then\n            echo $(date) \" - $GF_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\nensure_k8s_namespace_exists() {\n    NAMESPACE_TO_EXIST=\"$1\"\n\n    if ! kubectl get ns $NAMESPACE_TO_EXIST >/dev/null 2>&1; then\n        echo $(date) \" - Creating namespace $NAMESPACE_TO_EXIST\"\n        kubectl create ns $NAMESPACE_TO_EXIST\n    else\n        echo $(date) \" - Namespace $NAMESPACE_TO_EXIST already exists\"\n    fi\n}\n\nNAMESPACE=default\nRAW_PROMETHEUS_CHART_VALS=\"https://raw.githubusercontent.com/Azure/aks-engine/master/extensions/prometheus-grafana-k8s/v1/prometheus_values.yaml\"\nCADVISOR_CONFIG_URL=\"https://raw.githubusercontent.com/Azure/aks-engine/master/extensions/prometheus-grafana-k8s/v1/cadvisor_daemonset.yml\"\n\n# retrieve and parse extension parameters\nif [[ -n \"$1\" ]]; then\n    IFS=';' read -ra INPUT <<< \"$1\"\n    if [[ -n \"${INPUT[0]}\" ]]; then\n        NAMESPACE=\"${INPUT[0]}\"\n        echo \"$(date) - Custom namespace specified: $NAMESPACE\"\n    fi\n    if [[ -n \"${INPUT[1]}\" ]]; then\n        RAW_PROMETHEUS_CHART_VALS=\"${INPUT[1]}\"\n        echo \"$(date) - Custom prometheus chart values url specified: $RAW_PROMETHEUS_CHART_VALS\"\n    fi\n    if [[ -n \"${INPUT[2]}\" ]]; then\n        CADVISOR_CONFIG_URL=\"${INPUT[2]}\"\n        echo \"$(date) - Custom cAdvisor config url specified: $CADVISOR_CONFIG_URL\"\n    fi\nfi\n\n# this extension should only run on a single node\n# the logic to decide whether or not this current node\n# should run the extension is to alphabetically determine\n# if this local machine is the first in the list of master nodes\n# if it is, then run the extension. if not, exit\nif ! wait_for_master_nodes; then\n    echo $(date) \" - Error while waiting for kubectl to output master nodes. Exiting\"\n    exit 1\nfi\n\nif ! wait_for_agent_nodes; then\n    echo $(date) \" - Error while waiting for kubectl to output agent nodes. Exiting\"\n    exit 1\nfi\n\necho \"$(date) - Dumping out sorted agent nodes\"\nkubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort\n\nif ! should_this_node_run_extension; then\n    echo $(date) \" - Not the first master node or the first agent node, no longer continuing extension. Exiting\"\n    exit 1\nfi\n\nensure_k8s_namespace_exists $NAMESPACE\n\nK8S_SECRET_NAME=dashboard-grafana\nDS_TYPE=prometheus\nDS_NAME=prometheus1\n\nPROM_URL=http://monitoring-prometheus-server\n\n# When RBAC is enabled, need to grant permission to tiller\nkubectl create clusterrolebinding tiller-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default\n\ninstall_helm \"$RAW_PROMETHEUS_CHART_VALS\"\nif ! wait_for_tiller; then\n    echo $(date) \" - Tiller did not respond in a timely manner. Exiting\"\n    exit 1\nfi\nupdate_helm\ninstall_cadvisor $NAMESPACE $CADVISOR_CONFIG_URL\ninstall_prometheus $NAMESPACE\ninstall_grafana $NAMESPACE\n\nsleep 5\n\necho $(date) \" - Creating the Prometheus datasource in Grafana\"\nGF_USER_NAME=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-user}\" | base64 --decode)\necho $GF_USER_NAME\nGF_PASSWORD=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-password}\" | base64 --decode)\necho $GF_PASSWORD\nGF_URL=$(kubectl get svc -n $NAMESPACE -l \"app=dashboard-grafana,component=grafana\" -o jsonpath=\"{.items[0].spec.clusterIP}\")\necho $GF_URL\n\necho retrieving current data sources...\nCURRENT_DS_LIST=$(curl -s --user \"$GF_USER_NAME:$GF_PASSWORD\" \"$GF_URL/api/datasources\")\nif echo $CURRENT_DS_LIST | grep -q \"\\\"name\\\":\\\"$DS_NAME\\\"\"; then\n    echo data source $DS_NAME already exists\n    echo $CURRENT_DS_LIST | python -m json.tool\n    exit 0\nfi\n\necho data source $DS_NAME does not exist, creating...\nDS_RAW=$(cat << EOF\n{\n    \"name\": \"$DS_NAME\",\n    \"type\": \"$DS_TYPE\",\n    \"url\": \"$PROM_URL\",\n    \"access\": \"proxy\"\n}\nEOF\n)\n\n\n\nATTEMPTS=90\nSLEEP_TIME=10\n\nITERATION=0\nwhile [[ $ITERATION -lt $ATTEMPTS ]]; do\n    echo $(date) \" - Is the grafana api running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n    response=$(curl \\\n        -X POST \\\n        --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n        -H \"Content-Type: application/json\" \\\n        -d \"$DS_RAW\" \\\n        \"$GF_URL/api/datasources\")\n\n    if [[ $response == *\"Datasource added\"* ]]; then\n        echo $(date) \" - Data source added successfully\"\n        break\n    fi\n\n    ITERATION=$(( $ITERATION + 1 ))\n    sleep $SLEEP_TIME\ndone\n\necho $(date) \" - Creating the Kubernetes dashboard in Grafana\"\n\ncat << EOF > sanitize_dashboard.py\n#!/usr/bin/python3\n\nimport fileinput\nimport json\n\ndashboard = json.loads(''.join(fileinput.input()))\ndashboard.pop('__inputs')\ndashboard.pop('__requires')\nprint(json.dumps(dashboard).replace('\\${DS_PROMETHEUS}', 'prometheus1'))\n\nEOF\n\nchmod u+x sanitize_dashboard.py\n\nDB_RAW=$(cat << EOF\n{\n    \"dashboard\": $(curl -sL \"https://grafana.com/api/dashboards/3119/revisions/2/download\" | ./sanitize_dashboard.py),\n    \"overwrite\": false\n}\nEOF\n)\n\ncurl \\\n    -X POST \\\n    --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n    -H \"Content-Type: application/json\" \\\n    -d \"$DB_RAW\" \\\n    \"$GF_URL/api/dashboards/db\"\n\necho $(date) \" - Script complete\"\n", "num_lines": 429}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nexport WD=/etc/kubernetes/rotate-certs\nexport NEW_CERTS_DIR=${WD}/certs\n\n# copied from cse_helpers.sh, sourcing that file not always works\nsystemctl_restart() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl restart $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\n\nbackup() {\n  if [ ! -d /etc/kubernetes/certs.bak ]; then\n    cp -rp /etc/kubernetes/certs/ /etc/kubernetes/certs.bak\n  fi\n}\n\ncp_certs() {\n  cp -p ${NEW_CERTS_DIR}/etcdpeer* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/etcdclient* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/etcdserver* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/ca.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/client.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/apiserver.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/kubeconfig /home/$(logname)/.kube/config\n\n  rm -f /var/lib/kubelet/pki/kubelet-client-current.pem\n}\n\ncp_proxy() {\n  source /etc/environment\n  local NODE_INDEX\n  NODE_INDEX=$(hostname | tail -c 2)\n  if [[ $NODE_INDEX == 0 ]]; then\n    export OVERRIDE_PROXY_CERTS=\"true\"\n  fi\n  /etc/kubernetes/generate-proxy-certs.sh\n}\n\nagent_certs() {\n  cp -p ${NEW_CERTS_DIR}/ca.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/client.* /etc/kubernetes/certs/\n\n  rm -f /var/lib/kubelet/pki/kubelet-client-current.pem\n  sync\n  sleep 5\n  systemctl_restart 10 5 10 kubelet\n}\n\ncleanup() {\n  rm -rf ${WD}\n  rm -rf /etc/kubernetes/certs.bak\n}\n\n\"$@\"\n", "num_lines": 64}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nassignRootPW() {\n  if grep '^root:[!*]:' /etc/shadow; then\n    SALT=$(openssl rand -base64 5)\n    SECRET=$(openssl rand -base64 37)\n    if command -v python; then\n      CMD=\"import crypt, getpass, pwd; print crypt.crypt('$SECRET', '\\$6\\$$SALT\\$')\"\n      HASH=$(python -c \"$CMD\")\n    elif command -v python3; then\n      CMD=\"import crypt, getpass, pwd; print(crypt.crypt('$SECRET', '\\$6\\$$SALT\\$'))\"\n      HASH=$(python3 -c \"$CMD\")\n    else\n      exit 112\n    fi\n\n    echo 'root:'$HASH | /usr/sbin/chpasswd -e || exit 112\n  fi\n}\n\nassignFilePermissions() {\n  FILES=\"\n    auth.log\n    alternatives.log\n    cloud-init.log\n    cloud-init-output.log\n    daemon.log\n    dpkg.log\n    kern.log\n    lastlog\n    waagent.log\n    syslog\n    unattended-upgrades/unattended-upgrades.log\n    unattended-upgrades/unattended-upgrades-dpkg.log\n    azure-vnet-ipam.log\n    azure-vnet-telemetry.log\n    azure-cnimonitor.log\n    azure-vnet.log\n    kv-driver.log\n    blobfuse-driver.log\n    blobfuse-flexvol-installer.log\n    landscape/sysinfo.log\n    \"\n  for FILE in ${FILES}; do\n    FILEPATH=\"/var/log/${FILE}\"\n    DIR=$(dirname \"${FILEPATH}\")\n    mkdir -p ${DIR} || exit 112\n    touch ${FILEPATH} || exit 112\n    chmod 640 ${FILEPATH} || exit 112\n  done\n  find /var/log -type f -perm '/o+r' -exec chmod 'g-wx,o-rwx' {} \\;\n  chmod 600 /etc/passwd- || exit 112\n  chmod 600 /etc/shadow- || exit 112\n  chmod 600 /etc/group- || exit 112\n  chmod 644 /etc/default/grub || exit 112\n  for filepath in /etc/crontab /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly /etc/cron.d; do\n    chmod 0600 $filepath || exit 112\n  done\n}\n\nsetPWExpiration() {\n  sed -i \"s|PASS_MAX_DAYS||g\" /etc/login.defs || exit 115\n  grep 'PASS_MAX_DAYS' /etc/login.defs && exit 115\n  sed -i \"s|PASS_MIN_DAYS||g\" /etc/login.defs || exit 115\n  grep 'PASS_MIN_DAYS' /etc/login.defs && exit 115\n  sed -i \"s|INACTIVE=||g\" /etc/default/useradd || exit 115\n  grep 'INACTIVE=' /etc/default/useradd && exit 115\n  echo 'PASS_MAX_DAYS 90' >>/etc/login.defs || exit 115\n  grep 'PASS_MAX_DAYS 90' /etc/login.defs || exit 115\n  echo 'PASS_MIN_DAYS 7' >>/etc/login.defs || exit 115\n  grep 'PASS_MIN_DAYS 7' /etc/login.defs || exit 115\n  echo 'INACTIVE=30' >>/etc/default/useradd || exit 115\n  grep 'INACTIVE=30' /etc/default/useradd || exit 115\n}\n\napplyCIS() {\n  setPWExpiration\n  assignRootPW\n  assignFilePermissions\n}\n\napplyCIS\n\n#EOF\n", "num_lines": 85}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\nKUBECTL=\"/usr/local/bin/kubectl --kubeconfig=/home/$ADMINUSER/.kube/config\"\nADDONS_DIR=/etc/kubernetes/addons\nPOD_SECURITY_POLICY_SPEC=$ADDONS_DIR/pod-security-policy.yaml\nADDON_MANAGER_SPEC=/etc/kubernetes/manifests/kube-addon-manager.yaml\nGET_KUBELET_LOGS=\"journalctl -u kubelet --no-pager\"\n\nsystemctlEnableAndStart() {\n  local ret\n  systemctl_restart 100 5 30 $1\n  ret=$?\n  systemctl status $1 --no-pager -l >/var/log/azure/$1-status.log\n  if [ $ret -ne 0 ]; then\n    return 1\n  fi\n  if ! retrycmd 120 5 25 systemctl enable $1; then\n    return 1\n  fi\n}\nsystemctlEtcd() {\n  for i in $(seq 1 60); do\n    timeout 30 systemctl daemon-reload\n    timeout 30 systemctl restart etcd && break ||\n      if [ $i -eq 60 ]; then\n        return 1\n      else\n        sleep 5\n      fi\n  done\n  if ! retrycmd 120 5 25 systemctl enable etcd; then\n    return 1\n  fi\n}\nconfigureAdminUser(){\n  chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n  chage -l \"${ADMINUSER}\"\n}\nconfigureEtcdUser(){\n  useradd -U etcd\n  chage -E -1 -I -1 -m 0 -M 99999 etcd\n  chage -l etcd\n  id etcd\n}\nconfigureSecrets(){\n  local apiserver_key=\"/etc/kubernetes/certs/apiserver.key\" ca_key=\"/etc/kubernetes/certs/ca.key\" etcdserver_key=\"/etc/kubernetes/certs/etcdserver.key\"\n  touch \"${apiserver_key}\"\n  touch \"${ca_key}\"\n  touch \"${etcdserver_key}\"\n  if [[ -z ${COSMOS_URI} ]]; then\n    chown etcd:etcd \"${etcdserver_key}\"\n  fi\n  local etcdclient_key=\"/etc/kubernetes/certs/etcdclient.key\" etcdpeer_key=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.key\"\n  touch \"${etcdclient_key}\"\n  touch \"${etcdpeer_key}\"\n  if [[ -z ${COSMOS_URI} ]]; then\n    chown etcd:etcd \"${etcdpeer_key}\"\n  fi\n  chmod 0600 \"${apiserver_key}\" \"${ca_key}\" \"${etcdserver_key}\" \"${etcdclient_key}\" \"${etcdpeer_key}\"\n  chown root:root \"${apiserver_key}\" \"${ca_key}\" \"${etcdclient_key}\"\n  local etcdserver_crt=\"/etc/kubernetes/certs/etcdserver.crt\" etcdclient_crt=\"/etc/kubernetes/certs/etcdclient.crt\" etcdpeer_crt=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.crt\"\n  touch \"${etcdserver_crt}\"\n  touch \"${etcdclient_crt}\"\n  touch \"${etcdpeer_crt}\"\n  chmod 0644 \"${etcdserver_crt}\" \"${etcdclient_crt}\" \"${etcdpeer_crt}\"\n  chown root:root \"${etcdserver_crt}\" \"${etcdclient_crt}\" \"${etcdpeer_crt}\"\n\n  set +x\n  echo \"${APISERVER_PRIVATE_KEY}\" | base64 --decode >\"${apiserver_key}\"\n  echo \"${CA_PRIVATE_KEY}\" | base64 --decode >\"${ca_key}\"\n  echo \"${ETCD_SERVER_PRIVATE_KEY}\" | base64 --decode >\"${etcdserver_key}\"\n  echo \"${ETCD_CLIENT_PRIVATE_KEY}\" | base64 --decode >\"${etcdclient_key}\"\n  echo \"${ETCD_PEER_KEY}\" | base64 --decode >\"${etcdpeer_key}\"\n  echo \"${ETCD_SERVER_CERTIFICATE}\" | base64 --decode >\"${etcdserver_crt}\"\n  echo \"${ETCD_CLIENT_CERTIFICATE}\" | base64 --decode >\"${etcdclient_crt}\"\n  echo \"${ETCD_PEER_CERT}\" | base64 --decode >\"${etcdpeer_crt}\"\n}\nconfigureEtcd() {\n  set -x\n\n  local ret f=/opt/azure/containers/setup-etcd.sh etcd_peer_url=\"https://${PRIVATE_IP}:2380\"\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_ETCD_CONFIG_FAIL\"}}\n  $f >/opt/azure/containers/setup-etcd.log 2>&1\n  ret=$?\n  if [ $ret -ne 0 ]; then\n    exit $ret\n  fi\n\n  if [[ -z ${ETCDCTL_ENDPOINTS} ]]; then\n    {{/* Variables necessary for etcdctl are not present */}}\n    {{/* Must pull them from /etc/environment */}}\n    for entry in $(cat /etc/environment); do\n      export ${entry}\n    done\n  fi\n\n  chown -R etcd:etcd /var/lib/etcddisk\n  systemctlEtcd || exit {{GetCSEErrorCode \"ERR_ETCD_START_TIMEOUT\"}}\n  for i in $(seq 1 600); do\n    MEMBER=\"$(sudo -E etcdctl member list | grep -E ${NODE_NAME} | cut -d':' -f 1)\"\n    if [ \"$MEMBER\" != \"\" ]; then\n      break\n    else\n      sleep 1\n    fi\n  done\n  retrycmd 120 5 25 sudo -E etcdctl member update $MEMBER ${etcd_peer_url} || exit {{GetCSEErrorCode \"ERR_ETCD_CONFIG_FAIL\"}}\n}\nconfigureChrony() {\n  sed -i \"s/makestep.*/makestep 1.0 -1/g\" /etc/chrony/chrony.conf\n  echo \"refclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\" >> /etc/chrony/chrony.conf\n}\nensureChrony() {\n  systemctlEnableAndStart chrony || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ndisable1804SystemdResolved() {\n  {{/* Ignoring systemd-resolved query service but using its resolv.conf file */}}\n  {{/* This is the simplest approach to workaround resolved issues without completely uninstall it */}}\n  [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n}\nensureRPC() {\n  systemctlEnableAndStart rpcbind || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  systemctlEnableAndStart rpc-statd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\nensureAuditD() {\n  if [[ ${AUDITD_ENABLED} == true ]]; then\n    systemctlEnableAndStart auditd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  else\n    apt_get_purge auditd mlocate &\n  fi\n}\nensureCron() {\n  local s=/lib/systemd/system/cron.service\n  if [[ -f ${s} ]]; then\n    if ! grep -q 'Restart=' ${s}; then\n      sed -i 's/\\[Service\\]/[Service]\\nRestart=always/' ${s}\n      systemctlEnableAndStart cron\n    fi\n  fi\n}\ngenerateAggregatedAPICerts() {\n  local f=/etc/kubernetes/generate-proxy-certs.sh\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  $f\n}\nconfigureKubeletServerCert() {\n  local kubeletserver_key=\"/etc/kubernetes/certs/kubeletserver.key\" kubeletserver_crt=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n  openssl genrsa -out $kubeletserver_key 2048\n  openssl req -new -x509 -days 7300 -key $kubeletserver_key -out $kubeletserver_crt -subj \"/CN=${NODE_NAME}\"\n}\nconfigureK8s() {\n  local client_key=\"/etc/kubernetes/certs/client.key\" apiserver_crt=\"/etc/kubernetes/certs/apiserver.crt\" azure_json=\"/etc/kubernetes/azure.json\"\n  touch \"${client_key}\"\n  chmod 0600 \"${client_key}\"\n  chown root:root \"${client_key}\"\n  if [[ -n ${MASTER_NODE} ]]; then\n    touch \"${apiserver_crt}\"\n    chmod 0644 \"${apiserver_crt}\"\n    chown root:root \"${apiserver_crt}\"\n  fi\n  set +x\n  echo \"${KUBELET_PRIVATE_KEY}\" | base64 --decode >\"${client_key}\"\n  configureKubeletServerCert\n  if [[ -n ${MASTER_NODE} ]]; then\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode >\"${apiserver_crt}\"\n    if [[ ${ENABLE_AGGREGATED_APIS} == True ]]; then\n      generateAggregatedAPICerts\n    fi\n  else\n    {{- /* If we are a node that does not need azure.json (cloud-init tells us), then return immediately */}}\n    wait_for_file 1 1 /opt/azure/needs_azure.json || return\n  fi\n\n  touch $azure_json\n  chmod 0600 $azure_json\n  chown root:root $azure_json\n  {{/* Perform the required JSON escaping */}}\n  local sp_secret=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n  sp_secret=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n  cat <<EOF >\"${azure_json}\"\n{\n    \"cloud\":\"{{GetTargetEnvironment}}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${sp_secret}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRatelimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRatelimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRatelimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\",\n    \"enableMultipleStandardLoadBalancers\": ${ENABLE_MULTIPLE_STANDARD_LOAD_BALANCERS},\n    \"tags\": \"${TAGS}\"\n}\nEOF\n  set -x\n  if [[ ${CLOUDPROVIDER_BACKOFF_MODE} == \"v2\" ]]; then\n    sed -i \"/cloudProviderBackoffExponent/d\" $azure_json\n    sed -i \"/cloudProviderBackoffJitter/d\" $azure_json\n  fi\n}\n\ninstallNetworkPlugin() {\n{{- if IsAzureCNI}}\n  installAzureCNI\n{{end}}\n  installCNI\n  rm -rf $CNI_DOWNLOADS_DIR &\n}\ninstallCNI() {\n  CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/}\n  if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n    downloadCNI\n  fi\n  mkdir -p $CNI_BIN_DIR\n  tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n  chown -R root:root $CNI_BIN_DIR\n  chmod -R 755 $CNI_BIN_DIR\n}\n{{- if IsAzureCNI}}\ninstallAzureCNI() {\n  CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/}\n  if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n    downloadAzureCNI\n  fi\n  mkdir -p $CNI_CONFIG_DIR\n  chown -R root:root $CNI_CONFIG_DIR\n  chmod 755 $CNI_CONFIG_DIR\n  mkdir -p $CNI_BIN_DIR\n  tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n}\n{{end}}\nconfigureCNI() {\n  {{/* needed for the iptables rules to work on bridges */}}\n  retrycmd 120 5 25 modprobe br_netfilter || exit {{GetCSEErrorCode \"ERR_MODPROBE_FAIL\"}}\n  echo -n \"br_netfilter\" >/etc/modules-load.d/br_netfilter.conf\n  configureAzureCNI\n  {{if HasCiliumNetworkPlugin}}\n  systemctl enable sys-fs-bpf.mount\n  systemctl restart sys-fs-bpf.mount\n  touch /var/run/reboot-required\n  {{end}}\n{{- if IsAzureStackCloud}}\n  if [[ ${NETWORK_PLUGIN} == \"azure\" ]]; then\n    {{/* set environment to mas when using Azure CNI on Azure Stack */}}\n    {{/* shellcheck disable=SC2002,SC2005 */}}\n    echo $(cat \"$CNI_CONFIG_DIR/10-azure.conflist\" | jq '.plugins[0].ipam.environment = \"mas\"') >\"$CNI_CONFIG_DIR/10-azure.conflist\"\n  fi\n{{end}}\n}\nconfigureAzureCNI() {\n  local tmpDir=$(mktemp -d \"$(pwd)/XXX\")\n  if [[ \"${NETWORK_PLUGIN}\" == \"azure\" ]]; then\n    mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n    chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n{{- if IsIPv6DualStackFeatureEnabled}}\n    jq '.plugins[0].ipv6Mode=\"ipv6nat\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n    mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n{{- end}}\n    if [[ {{GetKubeProxyMode}} == \"ipvs\" ]]; then\n      serviceCidrs={{GetServiceCidr}}\n      jq --arg serviceCidrs $serviceCidrs '.plugins[0]+={serviceCidrs: $serviceCidrs}' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n    fi\n    if [[ \"${NETWORK_MODE}\" == \"bridge\" ]]; then\n      jq '.plugins[0].mode=\"bridge\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      jq '.plugins[0].bridge=\"azure0\"' \"$tmpDir/tmp\" > $tmpDir/tmp2\n      mv $tmpDir/tmp2 $CNI_CONFIG_DIR/10-azure.conflist\n    else\n      jq '.plugins[0].mode=\"transparent\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n    fi\n    /sbin/ebtables -t nat --list\n  fi\n  rm -Rf $tmpDir\n}\nenableCRISystemdMonitor() {\n  wait_for_file 1200 1 /etc/systemd/system/docker-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart docker-monitor || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{- if NeedsContainerd}}\ninstallContainerd() {\n  removeMoby\n  local v\n  v=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||')\n  if [[ $v != \"${CONTAINERD_VERSION}\"* ]]; then\n    os_lower=$(echo ${OS} | tr '[:upper:]' '[:lower:]')\n    if [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n      url_path=\"${os_lower}/${UBUNTU_RELEASE}\"\n      [[ ${UBUNTU_RELEASE} == \"20.04\" ]] || url_path+=\"/multiarch\"\n      url_path+=\"/prod\"\n    elif [[ ${OS} == \"${DEBIAN_OS_NAME}\" ]]; then\n      url_path=\"${os_lower}/${UBUNTU_RELEASE}/prod\"\n    else\n      exit 25\n    fi\n    removeContainerd\n    apt_get_update || exit 99\n    apt_get_install 20 30 120 moby-runc moby-containerd=${CONTAINERD_VERSION}* --allow-downgrades || exit 27\n  fi\n}\nensureContainerd() {\n  wait_for_file 1200 1 /etc/systemd/system/containerd.service.d/exec_start.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/containerd/config.toml || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/containerd.service.d/kubereserved-slice.conf|| exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- end}}\n  systemctlEnableAndStart containerd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  enableCRISystemdMonitor\n}\n{{end}}\n{{- if IsDockerContainerRuntime}}\nensureDocker() {\n  wait_for_file 1200 1 /etc/systemd/system/docker.service.d/exec_start.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  usermod -aG docker ${ADMINUSER}\n  if [[ $OS != $FLATCAR_OS_NAME ]]; then\n    wait_for_file 1200 1 /etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  fi\n  {{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/docker.service.d/kubereserved-slice.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- end}}\n  local daemon_json=/etc/docker/daemon.json\n  for i in $(seq 1 1200); do\n    if [ -s $daemon_json ]; then\n      jq '.' <$daemon_json && break\n    fi\n    if [ $i -eq 1200 ]; then\n      exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    else\n      sleep 1\n    fi\n  done\n  systemctlEnableAndStart docker || exit {{GetCSEErrorCode \"ERR_DOCKER_START_FAIL\"}}\n  enableCRISystemdMonitor\n}\n{{end}}\n{{- if IsIPv6Enabled}}\nensureDHCPv6() {\n  if [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    wait_for_file 3600 1 {{GetDHCPv6ServiceCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    wait_for_file 3600 1 {{GetDHCPv6ConfigCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    systemctlEnableAndStart dhcpv6 || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n    retrycmd 120 5 25 modprobe ip6_tables || exit {{GetCSEErrorCode \"ERR_MODPROBE_FAIL\"}}\n  fi\n}\n{{end}}\n{{- if EnableEncryptionWithExternalKms}}\nensureKMSKeyvaultKey() {\n    wait_for_file 3600 1 {{GetKMSKeyvaultKeyServiceCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    wait_for_file 3600 1 {{GetKMSKeyvaultKeyCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    systemctlEnableAndStart kms-keyvault-key || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{end}}\nensureKubelet() {\n  wait_for_file 1200 1 /etc/sysctl.d/11-aks-engine.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  sysctl_reload 10 5 120 || exit {{GetCSEErrorCode \"ERR_SYSCTL_RELOAD\"}}\n  wait_for_file 1200 1 /etc/default/kubelet || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /var/lib/kubelet/kubeconfig || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  if [[ -n ${MASTER_NODE} ]]; then\n{{- if IsMasterVirtualMachineScaleSets}}\n    sed -i \"s|<SERVERIP>|https://$PRIVATE_IP:443|g\" \"/var/lib/kubelet/kubeconfig\" || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{- end}}\n    local f=/etc/kubernetes/manifests/kube-apiserver.yaml\n    wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    sed -i \"s|<advertiseAddr>|$PRIVATE_IP|g\" $f\n  fi\n  wait_for_file 1200 1 /opt/azure/containers/kubelet.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n{{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/{{- GetKubeReservedCgroup -}}.slice || exit {{GetCSEErrorCode \"ERR_KUBERESERVED_SLICE_SETUP_FAIL\"}}\n  wait_for_file 1200 1 /etc/systemd/system/kubelet.service.d/kubereserved-slice.conf || exit {{GetCSEErrorCode \"ERR_KUBELET_SLICE_SETUP_FAIL\"}}\n{{- end}}\n  if [[ -n ${MASTER_NODE} ]]; then\n    systemctlEnableAndStart kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  else\n{{- if not RunUnattendedUpgradesOnBootstrap}}\n    systemctlEnableAndStart kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{else}}\n    systemctl_enable 100 5 30 kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{- end}}\n  fi\n{{- if HasKubeletHealthZPort}}\n  wait_for_file 1200 1 /etc/systemd/system/kubelet-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  if [[ -n ${MASTER_NODE} ]]; then\n    systemctlEnableAndStart kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  else\n  {{- if not RunUnattendedUpgradesOnBootstrap}}\n    systemctlEnableAndStart kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  {{else}}\n    systemctl_enable 100 5 30 kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  {{- end}}\n  fi\n{{- end}}\nif [[ -n ${MASTER_NODE} ]]; then\n  wait_for_file 1200 1 /etc/systemd/system/apiserver-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart apiserver-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\nfi\n}\n\nensureKubeAddonManager() {\n  {{/* Wait 5 mins for kube-addon-manager to become Ready */}}\n  if ! retrycmd 60 5 30 ${KUBECTL} wait --for=condition=Ready --timeout=5s -l app=kube-addon-manager po -n kube-system; then\n    {{/* Restart kubelet if kube-addon-manager is not Ready after 5 mins */}}\n    systemctl_restart 3 5 30 kubelet\n    {{/* Wait 5 more mins for kube-addon-manager to become Ready, and then return failure if not */}}\n    retrycmd 60 5 30 ${KUBECTL} wait --for=condition=Ready --timeout=5s -l app=kube-addon-manager po -n kube-system || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $GET_KUBELET_LOGS\n  fi\n}\n\nensureAddons() {\n{{- if IsDashboardAddonEnabled}} {{/* Note: dashboard addon is deprecated */}}\n  retrycmd 120 5 30 $KUBECTL get namespace kubernetes-dashboard || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $GET_KUBELET_LOGS\n{{- end}}\n{{- if IsAzurePolicyAddonEnabled}}\n  retrycmd 120 5 30 $KUBECTL get namespace gatekeeper-system || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $GET_KUBELET_LOGS\n{{- end}}\n{{- if not HasCustomPodSecurityPolicy}}\n  retrycmd 120 5 30 $KUBECTL get podsecuritypolicy privileged restricted || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $GET_KUBELET_LOGS\n{{- end}}\n  replaceAddonsInit\n  rm -Rf ${ADDONS_DIR}/init\n  ensureKubeAddonManager\n  {{/* Manually delete any kube-addon-manager pods that point to the init directory */}}\n  for initPod in $(${KUBECTL} get pod -l app=kube-addon-manager -n kube-system -o json | jq -r '.items[] | select(.spec.containers[0].env[] | select(.value==\"/etc/kubernetes/addons/init\")) | select(.status.phase==\"Running\") .metadata.name'); do\n    retrycmd 120 5 30 ${KUBECTL} delete pod $initPod -n kube-system --force --grace-period 0 || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $GET_KUBELET_LOGS\n  done\n  {{if HasCiliumNetworkPolicy}}\n  while [ ! -f /etc/cni/net.d/05-cilium.conf ]; do\n    sleep 3\n  done\n  {{end}}\n  {{if HasAntreaNetworkPolicy}}\n  if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n    while ! $(grep -sq \"antrea\" $CNI_CONFIG_DIR/10-azure.conflist); do\n      sleep 3\n    done\n  else\n    while [ ! -f $CNI_CONFIG_DIR/10-antrea.conflist ]; do\n      sleep 3\n    done\n  fi\n  {{end}}\n  {{if HasFlannelNetworkPlugin}}\n  while [ ! -f /etc/cni/net.d/10-flannel.conf ]; do\n    sleep 3\n  done\n  {{end}}\n}\nreplaceAddonsInit() {\n  wait_for_file 1200 1 $ADDON_MANAGER_SPEC || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  cp $ADDON_MANAGER_SPEC /tmp/kube-addon-manager.yaml || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  sed -i \"s|${ADDONS_DIR}/init|${ADDONS_DIR}|g\" /tmp/kube-addon-manager.yaml || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  mv /tmp/kube-addon-manager.yaml $ADDON_MANAGER_SPEC || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n}\nensureLabelNodes() {\n  wait_for_file 1200 1 /opt/azure/containers/label-nodes.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/label-nodes.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart label-nodes || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{- if IsAADPodIdentityAddonEnabled}}\nensureTaints() {\n  wait_for_file 1200 1 /opt/azure/containers/untaint-nodes.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/untaint-nodes.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart untaint-nodes || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{end}}\nensureJournal() {\n  {\n    echo \"Storage=persistent\"\n    echo \"SystemMaxUse=1G\"\n    echo \"RuntimeMaxUse=1G\"\n    echo \"ForwardToSyslog=yes\"\n  } >>/etc/systemd/journald.conf\n  systemctlEnableAndStart systemd-journald || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ninstallKubeletAndKubectl() {\n  local binPath=/usr/local/bin\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    binPath=/opt/bin\n  fi\n  if [[ ! -f \"${binPath}/kubectl-${KUBERNETES_VERSION}\" ]] || [[ -n \"${CUSTOM_HYPERKUBE_IMAGE}\" ]] || [[ -n \"${KUBE_BINARY_URL}\" ]]; then\n    if version_gte ${KUBERNETES_VERSION} 1.17; then\n      extractKubeBinaries\n    else\n      if [[ $CONTAINER_RUNTIME == \"docker\" ]]; then\n        extractHyperkube \"docker\"\n      else\n        extractHyperkube \"img\"\n      fi\n    fi\n  fi\n  mv \"${binPath}/kubelet-${KUBERNETES_VERSION}\" \"${binPath}/kubelet\"\n  mv \"${binPath}/kubectl-${KUBERNETES_VERSION}\" \"${binPath}/kubectl\"\n  chmod a+x ${binPath}/kubelet ${binPath}/kubectl\n  rm -rf ${binPath}/kubelet-* ${binPath}/kubectl-* /home/hyperkube-downloads &\n}\nensureK8sControlPlane() {\n  if [ \"$NO_OUTBOUND\" = \"true\" ]; then\n    return\n  fi\n  retrycmd 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit_cse {{GetCSEErrorCode \"ERR_K8S_RUNNING_TIMEOUT\"}} $GET_KUBELET_LOGS\n}\n{{- if IsAzurePolicyAddonEnabled}}\nensureLabelExclusionForAzurePolicyAddon() {\n  retrycmd 120 5 25 $KUBECTL label ns kube-system control-plane=controller-manager --overwrite 2>/dev/null || exit_cse {{GetCSEErrorCode \"ERR_K8S_RUNNING_TIMEOUT\"}} $GET_KUBELET_LOGS\n}\n{{end}}\nensureEtcd() {\n  local etcd_client_url=\"https://${PRIVATE_IP}:2379\"\n  retrycmd 120 5 25 curl --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/etcdclient.crt --key /etc/kubernetes/certs/etcdclient.key ${etcd_client_url}/v2/machines || exit {{GetCSEErrorCode \"ERR_ETCD_RUNNING_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/etcd-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart etcd-monitor || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ncreateKubeManifestDir() {\n  mkdir -p /etc/kubernetes/manifests\n}\nwriteKubeConfig() {\n  local d=/home/$ADMINUSER/.kube\n  local f=$d/config\n{{- if HasBlockOutboundInternet}}\n  local server=https://localhost\n{{else}}\n  local server=$KUBECONFIG_SERVER\n{{- end}}\n  mkdir -p $d\n  touch $f\n  chown $ADMINUSER:$ADMINUSER $d $f\n  chmod 700 $d\n  chmod 600 $f\n  set +x\n  echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $server\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" >$f\n  set -x\n}\n{{- if IsClusterAutoscalerAddonEnabled}}\nconfigClusterAutoscalerAddon() {\n  local f=$ADDONS_DIR/cluster-autoscaler.yaml\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $f\n  sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $f\n  sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $f\n  sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $f\n  sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $f\n}\n{{end}}\n{{- if IsAzurePolicyAddonEnabled}}\nconfigAzurePolicyAddon() {\n  sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $ADDONS_DIR/azure-policy-deployment.yaml\n}\n{{end}}\n\nconfigAddons() {\n  {{if IsClusterAutoscalerAddonEnabled}}\n  if [[ ${CLUSTER_AUTOSCALER_ADDON} == true ]]; then\n    configClusterAutoscalerAddon\n  fi\n  {{end}}\n  {{if IsAzurePolicyAddonEnabled}}\n  configAzurePolicyAddon\n  {{end}}\n  {{- if and (not HasCustomPodSecurityPolicy) IsPodSecurityPolicyAddonEnabled}}\n  wait_for_file 1200 1 $POD_SECURITY_POLICY_SPEC || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  mkdir -p $ADDONS_DIR/init && cp $POD_SECURITY_POLICY_SPEC $ADDONS_DIR/init/ || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  {{- end}}\n}\n{{- if and HasNSeriesSKU IsNvidiaDevicePluginAddonEnabled}}\n{{- /* installNvidiaDrivers is idempotent, it will uninstall itself if it is already installed, and then install anew */}}\ninstallNvidiaDrivers() {\n  local d=\"/var/lib/dkms/nvidia/${GPU_DV}\" k log_file=\"/var/log/nvidia-installer-$(date +%s).log\"\n  k=$(uname -r)\n  if [ -d $d ]; then\n    dkms remove -m nvidia -v $GPU_DV -k $k\n  fi\n  sh $GPU_DEST/nvidia-drivers-$GPU_DV -s -k=$k --log-file-name=$log_file -a --no-drm --dkms --utility-prefix=\"${GPU_DEST}\" --opengl-prefix=\"${GPU_DEST}\"\n}\nconfigGPUDrivers() {\n  rmmod nouveau\n  echo blacklist nouveau >>/etc/modprobe.d/blacklist.conf\n  retrycmd_no_stats 120 5 25 update-initramfs -u || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  wait_for_apt_locks\n  for apt_package in $NVIDIA_PACKAGES; do\n    dpkg -i ${PERMANENT_CACHE_DIR}${apt_package}* || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  done\n  dpkg -i ${PERMANENT_CACHE_DIR}nvidia-container-runtime* || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  mkdir -p $GPU_DEST/lib64 $GPU_DEST/overlay-workdir\n  retrycmd 120 5 25 mount -t overlay -o lowerdir=/usr/lib/x86_64-linux-gnu,upperdir=${GPU_DEST}/lib64,workdir=${GPU_DEST}/overlay-workdir none /usr/lib/x86_64-linux-gnu || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  export -f installNvidiaDrivers\n  retrycmd 3 1 600 bash -c installNvidiaDrivers || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  mv ${GPU_DEST}/bin/* /usr/bin\n  echo \"${GPU_DEST}/lib64\" >/etc/ld.so.conf.d/nvidia.conf\n  retrycmd 120 5 25 ldconfig || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  umount -l /usr/lib/x86_64-linux-gnu\n  retrycmd 120 5 25 nvidia-modprobe -u -c0 || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  retrycmd 120 5 25 nvidia-smi || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  retrycmd 120 5 25 ldconfig || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  rm -Rf ${PERMANENT_CACHE_DIR}\n}\nensureGPUDrivers() {\n  configGPUDrivers\n  systemctlEnableAndStart nvidia-modprobe || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n}\n{{end}}\n{{- if HasDCSeriesSKU}}\ninstallSGXDrivers() {\n  [[ $UBUNTU_RELEASE == \"20.04\" || $UBUNTU_RELEASE == \"18.04\" || $UBUNTU_RELEASE == \"16.04\" ]] || exit 92\n\n  local packages=\"make gcc dkms\" oe_dir=\"/opt/azure/containers/oe\"\n  wait_for_apt_locks\n  retrycmd 30 5 3600 apt-get -y install \"$packages\" || exit 90\n  rm -rf ${oe_dir}\n  mkdir -p ${oe_dir}\n  pushd ${oe_dir} || exit\n  retrycmd 10 10 120 curl -fsSL -O \"https://download.01.org/intel-sgx/latest/version.xml\" || exit 90\n  dcap_version=\"$(grep dcap version.xml | grep -o -E \"[.0-9]+\")\"\n  sgx_driver_folder_url=\"https://download.01.org/intel-sgx/sgx-dcap/$dcap_version/linux\"\n  retrycmd 10 10 120 curl -fsSL -O \"$sgx_driver_folder_url/SHA256SUM_dcap_$dcap_version.cfg\" || exit 90\n  matched_line=\"$(grep \"distro/ubuntuServer$UBUNTU_RELEASE/sgx_linux_x64_driver_.*bin\" SHA256SUM_dcap_$dcap_version.cfg)\"\n  read -ra tmp_array <<<\"$matched_line\"\n  sgx_driver_sha256sum_expected=\"${tmp_array[0]}\"\n  sgx_driver_remote_path=\"${tmp_array[1]}\"\n  sgx_driver_url=\"${sgx_driver_folder_url}/${sgx_driver_remote_path}\"\n  sgx_driver=$(basename \"$sgx_driver_url\")\n\n  retrycmd 10 10 120 curl -fsSL -O \"${sgx_driver_url}\" || exit 90\n  read -ra tmp_array <<<\"$(sha256sum ./\"$sgx_driver\")\"\n  sgx_driver_sha256sum_real=\"${tmp_array[0]}\"\n  [[ $sgx_driver_sha256sum_real == \"$sgx_driver_sha256sum_expected\" ]] || exit 93\n\n  chmod a+x ./\"${sgx_driver}\"\n  if ! ./\"${sgx_driver}\"; then\n    popd || exit\n    exit 91\n  fi\n  popd || exit\n  rm -rf ${oe_dir}\n}\n{{end}}\n{{- if HasVHDDistroNodes}}\ncleanUpContainerImages() {\n  {{- if NeedsContainerd}}\n  docker rmi -f $(docker images -a -q) &\n  {{else}}\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${ETCD_VERSION}$|${ETCD_VERSION}-|${ETCD_VERSION}_\" | grep 'etcd') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-proxy') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-controller-manager') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-apiserver') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-scheduler') &\n  docker rmi registry:2.7.1 &\n  ctr -n=k8s.io image rm $(ctr -n=k8s.io images ls -q) &\n  {{- end}}\n}\ncleanUpGPUDrivers() {\n  rm -Rf $GPU_DEST\n  rm -f /etc/apt/sources.list.d/nvidia-docker.list\n  apt-key del $(apt-key list | grep NVIDIA -B 1 | head -n 1 | cut -d \"/\" -f 2 | cut -d \" \" -f 1)\n}\ncleanUpContainerd() {\n  rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n{{end}}\nremoveEtcd() {\n  rm -rf /usr/bin/etcd\n}\nexit_cse() {\n  local exit_code=$1\n  shift\n  $@ >> {{GetLinuxCSELogPath}} &\n  exit $exit_code\n}\n#EOF\n", "num_lines": 717}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n{{- if IsCustomCloudProfile}}\n  {{- if not IsAzureStackCloud}}\nensureCustomCloudRootCertificates() {\n    CUSTOM_CLOUD_ROOT_CERTIFICATES=\"{{GetCustomCloudRootCertificates}}\"\n    KUBE_CONTROLLER_MANAGER_FILE=/etc/kubernetes/manifests/kube-controller-manager.yaml\n\n    if [ ! -z $CUSTOM_CLOUD_ROOT_CERTIFICATES ]; then\n        # Replace placeholder for ssl binding\n        if [ -f $KUBE_CONTROLLER_MANAGER_FILE ]; then\n            sed -i \"s|<volumessl>|- name: ssl\\n      hostPath:\\n        path: \\\\/etc\\\\/ssl\\\\/certs|g\" $KUBE_CONTROLLER_MANAGER_FILE\n            sed -i \"s|<volumeMountssl>|- name: ssl\\n          mountPath: \\\\/etc\\\\/ssl\\\\/certs\\n          readOnly: true|g\" $KUBE_CONTROLLER_MANAGER_FILE\n        fi\n\n        local i=1\n        for cert in $(echo $CUSTOM_CLOUD_ROOT_CERTIFICATES | tr ',' '\\n')\n        do\n            echo $cert | base64 -d > \"/usr/local/share/ca-certificates/customCloudRootCertificate$i.crt\"\n            ((i++))\n        done\n\n        update-ca-certificates\n    else\n        if [ -f $KUBE_CONTROLLER_MANAGER_FILE ]; then\n            # remove the placeholder for ssl binding\n            sed -i \"/<volumessl>/d\" $KUBE_CONTROLLER_MANAGER_FILE\n            sed -i \"/<volumeMountssl>/d\" $KUBE_CONTROLLER_MANAGER_FILE\n        fi\n    fi\n}\n\nensureCustomCloudSourcesList() {\n    CUSTOM_CLOUD_SOURCES_LIST=\"{{GetCustomCloudSourcesList}}\"\n\n    if [ ! -z $CUSTOM_CLOUD_SOURCES_LIST ]; then\n        # Just in case, let's take a back up before we overwrite\n        cp /etc/apt/sources.list /etc/apt/sources.list.backup\n        echo $CUSTOM_CLOUD_SOURCES_LIST | base64 -d > /etc/apt/sources.list\n    fi\n}\n  {{end}}\n\nconfigureK8sCustomCloud() {\n  {{- if IsAzureStackCloud}}\n  local azure_json_path=\"/etc/kubernetes/azure.json\"\n  export -f ensureAzureStackCertificates\n  retrycmd 60 10 30 bash -c ensureAzureStackCertificates\n  set +x\n  # When AUTHENTICATION_METHOD is client_certificate, the certificate is stored into key valut,\n  # And SERVICE_PRINCIPAL_CLIENT_SECRET will be the following json payload with based64 encode\n  #{\n  #    \"data\": \"$pfxAsBase64EncodedString\",\n  #    \"dataType\" :\"pfx\",\n  #    \"password\": \"$password\"\n  #}\n  if [[ ${AUTHENTICATION_METHOD,,} == \"client_certificate\" ]]; then\n    SERVICE_PRINCIPAL_CLIENT_SECRET_DECODED=$(echo ${SERVICE_PRINCIPAL_CLIENT_SECRET} | base64 --decode)\n    SERVICE_PRINCIPAL_CLIENT_SECRET_CERT=$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET_DECODED | jq .data)\n    SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD=$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET_DECODED | jq .password)\n\n    # trim the starting and ending \"\n    SERVICE_PRINCIPAL_CLIENT_SECRET_CERT=${SERVICE_PRINCIPAL_CLIENT_SECRET_CERT#'\"'}\n    SERVICE_PRINCIPAL_CLIENT_SECRET_CERT=${SERVICE_PRINCIPAL_CLIENT_SECRET_CERT%'\"'}\n\n    SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD=${SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD#'\"'}\n    SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD=${SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD%'\"'}\n\n    KUBERNETES_FILE_DIR=$(dirname \"${azure_json_path}\")\n    K8S_CLIENT_CERT_PATH=\"${KUBERNETES_FILE_DIR}/k8s_auth_certificate.pfx\"\n    echo $SERVICE_PRINCIPAL_CLIENT_SECRET_CERT | base64 --decode >$K8S_CLIENT_CERT_PATH\n    # shellcheck disable=SC2002,SC2005\n    echo $(cat \"${azure_json_path}\" |\n      jq --arg K8S_CLIENT_CERT_PATH ${K8S_CLIENT_CERT_PATH} '. + {aadClientCertPath:($K8S_CLIENT_CERT_PATH)}' |\n      jq --arg SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD ${SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD} '. + {aadClientCertPassword:($SERVICE_PRINCIPAL_CLIENT_SECRET_PASSWORD)}' |\n      jq 'del(.aadClientSecret)') >${azure_json_path}\n  fi\n\n  if [[ ${IDENTITY_SYSTEM,,} == \"adfs\" ]]; then\n    # update the tenent id for ADFS environment.\n    # shellcheck disable=SC2002,SC2005\n    echo $(cat \"${azure_json_path}\" | jq '.tenantId = \"adfs\"') >${azure_json_path}\n  fi\n  set -x\n\n  {{/* Log whether the custom login endpoint is reachable to simplify troubleshooting. */}}\n  {{/* CSE will finish successfully but kubelet will error out if not reachable. */}}\n  LOGIN_ENDPOINT=$(jq -r .activeDirectoryEndpoint /etc/kubernetes/azurestackcloud.json)\n  LOGIN_ENDPOINT=${LOGIN_ENDPOINT#'https://'}\n  LOGIN_ENDPOINT=${LOGIN_ENDPOINT%'/'}\n  timeout 10 nc -vz ${LOGIN_ENDPOINT} 443 \\\n  && echo \"login endpoint reachable: ${LOGIN_ENDPOINT}\" \\\n  || echo \"error: login endpoint not reachable: ${LOGIN_ENDPOINT}\"\n\n  {{- if not IsAzureCNI}}\n  # Decrease eth0 MTU to mitigate Azure Stack's NRP issue\n  echo \"iface eth0 inet dhcp\" | sudo tee -a /etc/network/interfaces\n  echo \"    post-up /sbin/ifconfig eth0 mtu 1350\" | sudo tee -a /etc/network/interfaces\n  ifconfig eth0 mtu 1350\n  {{end}}\n\n  {{else}}\n  ensureCustomCloudRootCertificates\n  ensureCustomCloudSourcesList\n  {{end}}\n}\n{{end}}\n\n{{- if IsAzureStackCloud}}\nensureAzureStackCertificates() {\n  AZURESTACK_ENVIRONMENT_JSON_PATH=\"/etc/kubernetes/azurestackcloud.json\"\n  AZURESTACK_RESOURCE_MANAGER_ENDPOINT=$(jq .resourceManagerEndpoint $AZURESTACK_ENVIRONMENT_JSON_PATH | tr -d '\"')\n  AZURESTACK_RESOURCE_METADATA_ENDPOINT=\"$AZURESTACK_RESOURCE_MANAGER_ENDPOINT/metadata/endpoints?api-version=2015-01-01\"\n  curl $AZURESTACK_RESOURCE_METADATA_ENDPOINT\n  CURL_RETURNCODE=$?\n  KUBE_CONTROLLER_MANAGER_FILE=/etc/kubernetes/manifests/kube-controller-manager.yaml\n  if [ $CURL_RETURNCODE != 0 ]; then\n    # Replace placeholder for ssl binding\n    if [ -f $KUBE_CONTROLLER_MANAGER_FILE ]; then\n      sed -i \"s|<volumessl>|- name: ssl\\n      hostPath:\\n        path: \\\\/etc\\\\/ssl\\\\/certs|g\" $KUBE_CONTROLLER_MANAGER_FILE\n      sed -i \"s|<volumeMountssl>|- name: ssl\\n          mountPath: \\\\/etc\\\\/ssl\\\\/certs\\n          readOnly: true|g\" $KUBE_CONTROLLER_MANAGER_FILE\n    fi\n\n    # Copying the AzureStack root certificate to the appropriate store to be updated.\n    AZURESTACK_ROOT_CERTIFICATE_SOURCE_PATH=\"/var/lib/waagent/Certificates.pem\"\n    AZURESTACK_ROOT_CERTIFICATE__DEST_PATH=\"/usr/local/share/ca-certificates/azsCertificate.crt\"\n    cp $AZURESTACK_ROOT_CERTIFICATE_SOURCE_PATH $AZURESTACK_ROOT_CERTIFICATE__DEST_PATH\n    update-ca-certificates\n  else\n    if [ -f $KUBE_CONTROLLER_MANAGER_FILE ]; then\n      # the ARM resource manager endpoint binding certificate is trusted, remove the placeholder for ssl binding\n      sed -i \"/<volumessl>/d\" $KUBE_CONTROLLER_MANAGER_FILE\n      sed -i \"/<volumeMountssl>/d\" $KUBE_CONTROLLER_MANAGER_FILE\n    fi\n  fi\n\n  # ensureAzureStackCertificates will be retried if the exit code is not 0\n  curl $AZURESTACK_RESOURCE_METADATA_ENDPOINT\n  exit $?\n}\n\nconfigureAzureStackInterfaces() {\n  NETWORK_INTERFACES_FILE=\"/etc/kubernetes/network_interfaces.json\"\n  AZURE_CNI_CONFIG_FILE=\"/etc/kubernetes/interfaces.json\"\n  AZURESTACK_ENVIRONMENT_JSON_PATH=\"/etc/kubernetes/azurestackcloud.json\"\n  SERVICE_MANAGEMENT_ENDPOINT=$(jq -r '.serviceManagementEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  ACTIVE_DIRECTORY_ENDPOINT=$(jq -r '.activeDirectoryEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  RESOURCE_MANAGER_ENDPOINT=$(jq -r '.resourceManagerEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  TOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}${TENANT_ID}/oauth2/token\"\n\n  if [[ ${IDENTITY_SYSTEM,,} == \"adfs\" ]]; then\n    TOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}adfs/oauth2/token\"\n  fi\n\n  set +x\n\n  TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X POST \\\n    -H \"Content-Type: application/x-www-form-urlencoded\" \\\n    -d \"grant_type=client_credentials\" \\\n    -d \"client_id=$SERVICE_PRINCIPAL_CLIENT_ID\" \\\n    --data-urlencode \"client_secret=$SERVICE_PRINCIPAL_CLIENT_SECRET\" \\\n    --data-urlencode \"resource=$SERVICE_MANAGEMENT_ENDPOINT\" \\\n    ${TOKEN_URL} | jq '.access_token' | xargs)\n\n  if [[ -z $TOKEN ]]; then\n    echo \"Error generating token for Azure Resource Manager\"\n    exit 120\n  fi\n\n  curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X GET \\\n    -H \"Authorization: Bearer $TOKEN\" \\\n    -H \"Content-Type: application/json\" \\\n    \"${RESOURCE_MANAGER_ENDPOINT}subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/networkInterfaces?api-version=$NETWORK_API_VERSION\" >${NETWORK_INTERFACES_FILE}\n\n  if [[ ! -s ${NETWORK_INTERFACES_FILE} ]]; then\n    echo \"Error fetching network interface configuration for node\"\n    exit 121\n  fi\n\n  echo \"Generating Azure CNI interface file\"\n\n  mapfile -t local_interfaces < <(cat /sys/class/net/*/address | tr -d : | sed 's/.*/\\U&/g')\n\n  SDN_INTERFACES=$(jq \".value | map(select(.properties != null) | select(.properties.macAddress != null) | select(.properties.macAddress | inside(\\\"${local_interfaces[*]}\\\"))) | map(select((.properties.ipConfigurations | length) > 0))\" ${NETWORK_INTERFACES_FILE})\n\n  if [[ -z $SDN_INTERFACES ]]; then\n      echo \"Error extracting the SDN interfaces from the network interfaces file\"\n      exit 123\n  fi\n\n  AZURE_CNI_CONFIG=$(echo ${SDN_INTERFACES} | jq \"{Interfaces: [.[] | {MacAddress: .properties.macAddress, IsPrimary: .properties.primary, IPSubnets: [{Prefix: .properties.ipConfigurations[0].properties.subnet.id, IPAddresses: .properties.ipConfigurations | [.[] | {Address: .properties.privateIPAddress, IsPrimary: .properties.primary}]}]}]}\")\n\n  mapfile -t SUBNET_IDS < <(echo ${SDN_INTERFACES} | jq '[.[].properties.ipConfigurations[0].properties.subnet.id] | unique | .[]' -r)\n\n  for SUBNET_ID in \"${SUBNET_IDS[@]}\"; do\n    SUBNET_PREFIX=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X GET \\\n      -H \"Authorization: Bearer $TOKEN\" \\\n      -H \"Content-Type: application/json\" \\\n      \"${RESOURCE_MANAGER_ENDPOINT}${SUBNET_ID:1}?api-version=$NETWORK_API_VERSION\" |\n      jq '.properties.addressPrefix' -r)\n\n    if [[ -z $SUBNET_PREFIX ]]; then\n      echo \"Error fetching the subnet address prefix for a subnet ID\"\n      exit 122\n    fi\n\n    # shellcheck disable=SC2001\n    AZURE_CNI_CONFIG=$(echo ${AZURE_CNI_CONFIG} | sed \"s|$SUBNET_ID|$SUBNET_PREFIX|g\")\n  done\n\n  echo ${AZURE_CNI_CONFIG} >${AZURE_CNI_CONFIG_FILE}\n\n  chmod 0444 ${AZURE_CNI_CONFIG_FILE}\n\n  set -x\n}\n{{end}}\n#EOF\n", "num_lines": 219}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n  OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\nif [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n  UBUNTU_RELEASE=$(lsb_release -r -s)\nfi\nDOCKER=/usr/bin/docker\nif [[ $UBUNTU_RELEASE == \"20.04\" || $UBUNTU_RELEASE == \"18.04\" ]]; then\n  export GPU_DV=515.65.01\nelse\n  export GPU_DV=418.40.04\nfi\nexport GPU_DEST=/usr/local/nvidia\nPRIVATE_IP=$( (ip -br -4 addr show eth0 || ip -br -4 addr show azure0) | grep -Po '\\d+\\.\\d+\\.\\d+\\.\\d+')\nif ! [[ $(echo -n \"$PRIVATE_IP\" | grep -c '^') == 1 ]]; then\n  PRIVATE_IP=$(hostname -i)\nfi\nexport PRIVATE_IP\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\n\nconfigure_prerequisites() {\n  ip_forward_path=/proc/sys/net/ipv4/ip_forward\n  ip_forward_setting=\"net.ipv4.ip_forward=0\"\n  sysctl_conf=/etc/sysctl.conf\n  if ! grep -qE \"^1$\" ${ip_forward_path}; then\n    echo 1 >${ip_forward_path}\n  fi\n  if grep -qE \"${ip_forward_setting}\" ${sysctl_conf}; then\n    sed -i '/^net.ipv4.ip_forward=0$/d' ${sysctl_conf}\n  fi\n}\n\naptmarkWALinuxAgent() {\n  wait_for_apt_locks\n  retrycmd 120 5 25 apt-mark $1 walinuxagent ||\n    if [[ $1 == \"hold\" ]]; then\n      exit 7\n    elif [[ $1 == \"unhold\" ]]; then\n      exit 8\n    fi\n}\n\nretrycmd() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    timeout $timeout ${@} && break ||\n      if [ $i -eq $retries ]; then\n        echo Executed \\\"$@\\\" $i times\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n  echo Executed \\\"$@\\\" $i times\n}\nretrycmd_no_stats() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    timeout $timeout ${@} && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nretrycmd_get_tarball() {\n  tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n  echo \"${tar_retries} retries\"\n  for i in $(seq 1 $tar_retries); do\n    tar -tzf $tarball && break ||\n      if [ $i -eq $tar_retries ]; then\n        return 1\n      else\n        timeout 60 curl -fsSL $url -o $tarball\n        sleep $wait_sleep\n      fi\n  done\n}\nretrycmd_get_executable() {\n  retries=$1; wait_sleep=$2; filepath=$3; url=$4; validation_args=$5\n  echo \"${retries} retries\"\n  for i in $(seq 1 $retries); do\n    $filepath $validation_args && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        timeout 30 curl -fsSL $url -o $filepath\n        chmod +x $filepath\n        sleep $wait_sleep\n      fi\n  done\n}\nwait_for_file() {\n  retries=$1; wait_sleep=$2; filepath=$3\n  paved=/opt/azure/cloud-init-files.paved\n  grep -Fq \"${filepath}\" $paved && return 0\n  for i in $(seq 1 $retries); do\n    grep -Fq '#EOF' $filepath && break\n    if [ $i -eq $retries ]; then\n      return 1\n    else\n      sleep $wait_sleep\n    fi\n  done\n  sed -i \"/#EOF/d\" $filepath\n  echo $filepath >>$paved\n}\nwait_for_apt_locks() {\n  while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n    echo 'Waiting for release of apt locks'\n    sleep 3\n  done\n}\napt_get_update() {\n  retries=10\n  apt_update_output=/tmp/apt-get-update.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") &&\n      cat $apt_update_output && break ||\n      cat $apt_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get update $i times\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks; apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ndpkg_install() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks; dpkg -i \"${1}\" && break; apt-get update --fix-missing; do_apt_get_install -f && break\n    if [ $i -eq $retries ]; then return 1; fi; sleep $wait_sleep\n  done\n}\ndo_apt_get_install() {\n  dpkg --configure -a --force-confdef; DEBIAN_FRONTEND=noninteractive apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@}\n}\napt_get_install() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    do_apt_get_install ${@} && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n        apt_get_update\n      fi\n  done\n  echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times\n}\napt_get_purge() {\n  retries=20; wait_sleep=30; timeout=120\n  for package in $@; do\n    if apt list --installed | grep $package; then\n      for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get purge -o Dpkg::Options::=\"--force-confold\" -y $package && break ||\n          if [ $i -eq $retries ]; then\n            return 1\n          else\n            sleep $wait_sleep\n          fi\n      done\n    fi\n  done\n  echo Executed apt-get purge -y \\\"$package\\\" $i times\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n}\nunattended_upgrade() {\n  retries=10\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    /usr/bin/unattended-upgrade && break ||\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed unattended-upgrade $i times\n}\nsystemctl_restart() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl restart $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsystemctl_enable() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl enable $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsystemctl_stop() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl stop $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsysctl_reload() {\n  retries=$1; wait_sleep=$2; timeout=$3\n  for i in $(seq 1 $retries); do\n    timeout $timeout sysctl --system && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n#HELPERSEOF\n", "num_lines": 276}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nAPMZ_DOWNLOADS_DIR=\"/opt/apmz/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nUBUNTU_CODENAME=$(lsb_release -c -s)\nNVIDIA_PACKAGES=\"libnvidia-container1 libnvidia-container-tools nvidia-container-toolkit\"\nNVIDIA_CONTAINER_TOOLKIT_VER=1.6.0\nNVIDIA_RUNTIME_VER=3.6.0\n\ndisableTimeSyncd() {\n  systemctl_stop 20 5 10 systemd-timesyncd || exit 3\n  retrycmd 120 5 25 systemctl disable systemd-timesyncd || exit 3\n}\ninstallEtcd() {\n  local  v\n  v=$(etcd --version | grep \"etcd Version\" | cut -d \":\" -f 2 | tr -d '[:space:]')\n  if [[ $v != \"${ETCD_VERSION}\" ]]; then\n    local cli_tool=$1 path=\"/usr/bin\" image=${ETCD_DOWNLOAD_URL}etcd:v${ETCD_VERSION}\n    pullContainerImage $cli_tool ${image}\n    removeEtcd\n    if [[ $cli_tool == \"docker\" ]]; then\n      mkdir -p \"$path\"\n      docker run --rm --entrypoint cat ${image} /usr/local/bin/etcd >\"$path/etcd\"\n      docker run --rm --entrypoint cat ${image} /usr/local/bin/etcdctl >\"$path/etcdctl\"\n    else\n      tmpdir=/root/etcd${RANDOM}\n      img unpack -o ${tmpdir} ${image}\n      mv ${tmpdir}/usr/local/bin/etcd ${tmpdir}/usr/local/bin/etcdctl ${path}\n      rm -rf ${tmpdir}\n    fi\n    chmod a+x \"$path/etcd\" \"$path/etcdctl\"\n  fi\n}\ninstallDeps() {\n  {{/* We used to pin to 1.1.1 of blobfuse - does not exist in 20.04 and it is questionable */}}\n  packages=\"apache2-utils apt-transport-https blobfuse ca-certificates cifs-utils conntrack cracklib-runtime dbus dkms ebtables ethtool fuse gcc git htop iftop init-system-helpers iotop iproute2 ipset iptables jq libpam-pwquality libpwquality-tools linux-headers-$(uname -r) make mount net-tools nfs-common pigz socat sysstat traceroute util-linux xz-utils zip\"\n  {{/* ... but if we need to in 18.04, this will pin it - we likely should not */}}\n  [[ $UBUNTU_RELEASE == \"18.04\" ]] && packages=${packages/ blobfuse / blobfuse=1.1.1 }\n  if [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n    retrycmd_no_stats 120 5 25 curl -fsSL ${MS_APT_REPO}/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb >/tmp/packages-microsoft-prod.deb || exit 42\n    retrycmd 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit 43\n    retrycmd_no_stats 120 5 25 curl ${MS_APT_REPO}/config/ubuntu/${UBUNTU_RELEASE}/prod.list >/tmp/microsoft-prod.list || exit 25\n    retrycmd 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit 25\n    retrycmd_no_stats 120 5 25 curl ${MS_APT_REPO}/keys/microsoft.asc | gpg --dearmor >/tmp/microsoft.gpg || exit 26\n    retrycmd 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit 26\n    aptmarkWALinuxAgent hold\n    packages+=\" cgroup-lite ceph-common glusterfs-client\"\n    if [[ $UBUNTU_RELEASE == \"20.04\" || $UBUNTU_RELEASE == \"18.04\" ]]; then\n      disableTimeSyncd\n      packages+=\" ntp ntpstat chrony net-tools\"\n    fi\n  elif [[ $OS == $DEBIAN_OS_NAME ]]; then\n    packages+=\" gpg cgroup-bin\"\n  fi\n\n  apt_get_update || exit 99\n  apt_get_dist_upgrade || exit 101\n\n  for apt_package in ${packages}; do\n    if ! apt_get_install 30 1 600 $apt_package; then\n      journalctl --no-pager -u $apt_package\n      exit 9\n    fi\n  done\n  if [[ ${AUDITD_ENABLED} == true ]]; then\n    if ! apt_get_install 30 1 600 auditd; then\n      journalctl --no-pager -u auditd\n      exit 9\n    fi\n  fi\n}\ngpuDriversDownloaded() {\n  for apt_package in $NVIDIA_PACKAGES; do\n    ls ${PERMANENT_CACHE_DIR}${apt_package}* || return 1\n  done\n  ls ${PERMANENT_CACHE_DIR}nvidia-container-runtime* || return 1\n}\ndownloadGPUDrivers() {\n  mkdir -p $GPU_DEST/tmp\n  retrycmd_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/gpgkey >$GPU_DEST/tmp/aptnvidia.gpg || exit 85\n  wait_for_apt_locks\n  retrycmd 120 5 25 apt-key add $GPU_DEST/tmp/aptnvidia.gpg || exit 85\n  wait_for_apt_locks\n  retrycmd_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu${UBUNTU_RELEASE}/nvidia-docker.list >$GPU_DEST/tmp/nvidia-docker.list || exit 85\n  wait_for_apt_locks\n  retrycmd_no_stats 120 5 25 cat $GPU_DEST/tmp/nvidia-docker.list >/etc/apt/sources.list.d/nvidia-docker.list || exit 85\n  apt_get_update\n  retrycmd 30 5 60 curl -fLS https://us.download.nvidia.com/tesla/$GPU_DV/NVIDIA-Linux-x86_64-${GPU_DV}.run -o ${GPU_DEST}/nvidia-drivers-${GPU_DV} || exit 85\n  mkdir -p $PERMANENT_CACHE_DIR\n  for apt_package in $NVIDIA_PACKAGES; do\n    apt_get_download 20 30 \"${apt_package}=${NVIDIA_CONTAINER_TOOLKIT_VER}*\" || exit 85\n    cp -al ${APT_CACHE_DIR}${apt_package}_${NVIDIA_CONTAINER_TOOLKIT_VER}* $PERMANENT_CACHE_DIR || exit 85\n  done\n  apt_get_download 20 30 nvidia-container-runtime=${NVIDIA_RUNTIME_VER}* || exit 85\n  cp -al ${APT_CACHE_DIR}nvidia-container-runtime_${NVIDIA_RUNTIME_VER}* $PERMANENT_CACHE_DIR || exit 85\n}\nremoveMoby() {\n  apt_get_purge moby-engine moby-cli || exit 27\n}\nremoveContainerd() {\n  apt_get_purge moby-containerd || exit 27\n}\nmobyPkgVersion() {\n  dpkg -s \"${1}\" | grep \"Version:\" | awk '{ print $2 }' | cut -d '+' -f 1\n}\ninstallRunc() {\n  local v\n  local url\n  v=$(runc --version | head -n 1 | cut -d\" \" -f3)\n  if [[ $v != \"1.1.2\" ]]; then\n    url=${MS_APT_REPO}/ubuntu/${UBUNTU_RELEASE}\n    [[ ${UBUNTU_RELEASE} == \"20.04\" ]] || url=${url}/multiarch\n    url=${url}/prod/pool/main/m/moby-runc/moby-runc_1.1.2%2Bazure-ubuntu${UBUNTU_RELEASE}u1_amd64.deb\n    if [[ -n \"${url:-}\" ]]; then\n      DEB=\"${url##*/}\"\n      retrycmd_no_stats 120 5 25 curl -fsSL ${url} >/tmp/${DEB} || exit 184\n      dpkg_install 20 30 /tmp/${DEB} || exit 184\n    fi\n  fi\n}\ninstallMoby() {\n  local install_pkgs=\"\" v cli_ver=\"${MOBY_VERSION}\"\n  v=\"$(mobyPkgVersion moby-containerd)\"\n  if [ -n \"${CONTAINERD_VERSION}\" ] && [ ! \"${v}\" = \"${CONTAINERD_VERSION}\" ]; then\n    install_pkgs+=\" moby-containerd=${CONTAINERD_VERSION}*\"\n    removeMoby\n    removeContainerd\n  fi\n  v=\"$(mobyPkgVersion moby-engine)\"\n  if [ ! \"${v}\" = \"${MOBY_VERSION}\" ]; then\n    install_pkgs+=\" moby-engine=${MOBY_VERSION}*\"\n    if [ \"${cli_ver}\" = \"3.0.4\" ]; then\n      cli_ver=\"3.0.3\"\n    fi\n    install_pkgs+=\" moby-cli=${cli_ver}*\"\n    removeMoby\n  fi\n  if [ -n \"${install_pkgs}\" ]; then\n    apt_get_install 20 30 120 ${install_pkgs} --allow-downgrades || exit 27\n  fi\n}\ndownloadCNI() {\n  mkdir -p $CNI_DOWNLOADS_DIR\n  CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/}\n  retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit 41\n}\ndownloadAzureCNI() {\n  mkdir -p $CNI_DOWNLOADS_DIR\n  CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/}\n  retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit 41\n}\nensureAPMZ() {\n  local ver=$1 v\n  local d=\"$APMZ_DOWNLOADS_DIR/$ver\"\n  local url=\"https://upstreamartifacts.azureedge.net/apmz/$ver/binaries/apmz_linux_amd64.tar.gz\" fp=\"/usr/local/bin/apmz\" dest=\"$d/apmz.gz\" bin_fp=\"$d/apmz_linux_amd64\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    fp=\"/opt/bin/apmz\"\n    export PATH=\"${PATH}:/opt/bin\"\n  fi\n  if [[ -f $fp ]]; then\n    v=$($fp version)\n    if [[ $ver == \"$v\" ]]; then\n      return\n    fi\n  fi\n  mkdir -p \"$d\"\n  retrycmd_get_tarball 120 5 \"$dest\" \"${url}\"\n  tar -xvf \"$dest\" -C \"$d\"\n  chmod +x \"$bin_fp\"\n  ln -Ffs \"$bin_fp\" \"$fp\"\n}\ninstallBpftrace() {\n  local ver=\"v0.9.4\" v bin=\"bpftrace\" tools=\"bpftrace-tools.tar\"\n  local url=\"https://upstreamartifacts.azureedge.net/$bin/$ver\"\n  local bpftrace_fp=\"/usr/local/bin/$bin\"\n  local tools_fp=\"/usr/local/share/$bin\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    bpftrace_fp=\"/opt/bin/$bin\"\n    tools_fp=\"/opt/share/$bin\"\n    export PATH=\"${PATH}:/opt/bin\"\n  fi\n  if [[ -f $bpftrace_fp ]]; then\n    v=\"$($bin -V | cut -d' ' -f2)\"\n    if [[ $ver == \"$v\" ]]; then\n      return\n    fi\n    rm \"$bpftrace_fp\"\n    if [[ -d $tools_fp ]]; then\n      rm -r \"$tools_fp\"\n    fi\n  fi\n  mkdir -p \"$tools_fp\"\n  install_dir=\"/opt/bpftrace/downloads/$ver\"\n  mkdir -p \"$install_dir\"\n  download_path=\"$install_dir/$tools\"\n  retrycmd 30 5 60 curl -fSL -o \"$bpftrace_fp\" \"$url/$bin\" || exit 169\n  retrycmd 30 5 60 curl -fSL -o \"$download_path\" \"$url/$tools\" || exit 170\n  tar -xvf \"$download_path\" -C \"$tools_fp\"\n  chmod +x \"$bpftrace_fp\"\n  chmod -R +x \"$tools_fp/tools\"\n}\ninstallImg() {\n  img_filepath=/usr/local/bin/img\n  retrycmd_get_executable 120 5 $img_filepath \"https://upstreamartifacts.azureedge.net/img/img-linux-amd64-v0.5.6\" ls || exit 33\n}\nextractHyperkube() {\n  local cli_tool=$1 fp=\"/home/hyperkube-downloads/${KUBERNETES_VERSION}\" dest=\"/usr/local/bin\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    dest=\"/opt/bin\"\n  fi\n  pullContainerImage $cli_tool ${HYPERKUBE_URL}\n  if [[ $cli_tool == \"docker\" ]]; then\n    mkdir -p \"$fp\"\n    if docker run --rm --entrypoint \"\" -v $path:$path ${HYPERKUBE_URL} /bin/bash -c \"cp $dest/{kubelet,kubectl} $fp\"; then\n      mv \"${fp}/kubelet\" \"${dest}/kubelet-${KUBERNETES_VERSION}\"\n      mv \"${fp}/kubectl\" \"${dest}/kubectl-${KUBERNETES_VERSION}\"\n      return\n    else\n      docker run --rm -v $fp:$fp ${HYPERKUBE_URL} /bin/bash -c \"cp /hyperkube $fp\"\n    fi\n  else\n    img unpack -o \"$fp\" ${HYPERKUBE_URL}\n  fi\n\n  cp \"${fp}/hyperkube\" \"${dest}/kubelet-${KUBERNETES_VERSION}\"\n  mv \"${fp}/hyperkube\" \"${dest}/kubectl-${KUBERNETES_VERSION}\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    chmod a+x ${dest}/kubelet-${KUBERNETES_VERSION} ${dest}/kubectl-${KUBERNETES_VERSION}\n  fi\n}\nextractKubeBinaries() {\n  KUBE_BINARY_URL=${KUBE_BINARY_URL:-\"https://kubernetesartifacts.azureedge.net/kubernetes/v${KUBERNETES_VERSION}/binaries/kubernetes-node-linux-amd64.tar.gz\"}\n  local dest=\"/opt/kubernetes/downloads\" tmpDir=${KUBE_BINARY_URL##*/}\n  mkdir -p \"${dest}\"\n  retrycmd_get_tarball 120 5 \"$dest/${tmpDir}\" ${KUBE_BINARY_URL} || exit 31\n  path=/usr/local/bin\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    path=/opt/bin\n  fi\n  tar --transform=\"s|.*|&-${KUBERNETES_VERSION}|\" --show-transformed-names -xzvf \"$dest/${tmpDir}\" \\\n    --strip-components=3 -C ${path} kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n  rm -f \"$dest/${tmpDir}\"\n}\npullContainerImage() {\n  local cli_tool=$1 url=$2\n  retrycmd 60 1 1200 $cli_tool pull $url || exit 35\n}\nloadContainerImage() {\n  docker pull $1 || exit 35\n  docker save $1 | ctr -n=k8s.io images import - || exit 35\n\n}\noverrideNetworkConfig() {\n  CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n  touch ${CONFIG_FILEPATH}\n  cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 267}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nERR_FILE_WATCH_TIMEOUT=6 {{/* Timeout waiting for a file */}}\n\n{{/* delete non-working iovisor definition to ensure apt operations work */}}\nrm -Rf /etc/apt/sources.list.d/iovisor.list\n\nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n  exit 0\nfi\n\necho $(date),$(hostname), startcustomscript >>/opt/m\n\nfor i in $(seq 1 3600); do\n  if [ -s {{GetCSEHelpersScriptFilepath}} ]; then\n    grep -Fq '#HELPERSEOF' {{GetCSEHelpersScriptFilepath}} && break\n  fi\n  if [ $i -eq 3600 ]; then\n    exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  else\n    sleep 1\n  fi\ndone\nsed -i \"/#HELPERSEOF/d\" {{GetCSEHelpersScriptFilepath}}\nsource {{GetCSEHelpersScriptFilepath}}\nconfigure_prerequisites\n\nwait_for_file 3600 1 {{GetCSEInstallScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCSEInstallScriptFilepath}}\n\nensureAPMZ \"v0.5.1\"\n{{- if HasTelemetryEnabled }}\neval \"$(apmz bash -n \"cse\" -t \"{{GetLinuxDefaultTelemetryTags}}\" --api-keys \"{{GetApplicationInsightsTelemetryKeys}}\")\"\n{{else}}\neval \"$(apmz bash -d)\"\n{{end}}\n\nwait_for_file 3600 1 {{GetCSEConfigScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCSEConfigScriptFilepath}}\n\n{{- if IsCustomCloudProfile}}\nwait_for_file 3600 1 {{GetCustomCloudConfigCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCustomCloudConfigCSEScriptFilepath }}\n{{end}}\n\nif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"18.04\" ]]; then\n  disable1804SystemdResolved\nfi\n\nset +x\nETCD_PEER_CERT=$(echo ${ETCD_PEER_CERTIFICATES} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((NODE_INDEX + 1)))\nETCD_PEER_KEY=$(echo ${ETCD_PEER_PRIVATE_KEYS} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((NODE_INDEX + 1)))\nset -x\n\ntime_metric \"ConfigureAdminUser\" configureAdminUser\n\n{{- if HasVHDDistroNodes}}\n  {{- if not NeedsContainerd}}\ntime_metric \"CleanupContainerd\" cleanUpContainerd\n  {{end}}\n  {{- if HasNSeriesSKU}}\nif [[ ${GPU_NODE} != \"true\" ]]; then\n  time_metric \"CleanupGPUDrivers\" cleanUpGPUDrivers\nfi\n  {{else}}\ntime_metric \"CleanupGPUDrivers\" cleanUpGPUDrivers\n  {{end}}\n{{end}}\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n  time_metric \"CleanUpContainerImages\" cleanUpContainerImages\n  FULL_INSTALL_REQUIRED=false\nelse\n  if [[ ${IS_VHD} == true ]]; then\n    exit {{GetCSEErrorCode \"ERR_VHD_FILE_NOT_FOUND\"}}\n  fi\n  FULL_INSTALL_REQUIRED=true\nfi\n\n{{- if not IsVHDDistroForAllNodes}}\nif [[ $OS == $UBUNTU_OS_NAME || $OS == $DEBIAN_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n  time_metric \"InstallDeps\" installDeps\n  if [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"18.04\" ]]; then\n    overrideNetworkConfig\n  fi\n  {{- if not IsDockerContainerRuntime}}\n  time_metric \"InstallImg\" installImg\n  {{end}}\nfi\n{{end}}\n\nif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"18.04\" ]]; then\n  if apt list --installed | grep 'chrony'; then\n    time_metric \"ConfigureChrony\" configureChrony\n    time_metric \"EnsureChrony\" ensureChrony\n  fi\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  time_metric \"EnsureAuditD\" ensureAuditD\nfi\n\n{{- if not IsVHDDistroForAllNodes}}\nif [[ $FULL_INSTALL_REQUIRED == \"true\" ]]; then\n  time_metric \"InstallBpftrace\" installBpftrace\nfi\n{{end}}\n\nif [[ $OS != $FLATCAR_OS_NAME ]]; then\n{{- if NeedsContainerd}}\ntime_metric \"InstallContainerd\" installContainerd\n{{else}}\ntime_metric \"installMoby\" installMoby\n{{end}}\ntime_metric \"installRunc\" installRunc\n{{- if HasLinuxMobyURL}}\n  LINUX_MOBY_URL={{GetLinuxMobyURL}}\n  if [[ -n \"${LINUX_MOBY_URL:-}\" ]]; then\n    DEB=\"${LINUX_MOBY_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_MOBY_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\n{{- if HasLinuxContainerdURL}}\n  LINUX_CONTAINERD_URL={{GetLinuxContainerdURL}}\n  if [[ -n \"${LINUX_CONTAINERD_URL:-}\" ]]; then\n    DEB=\"${LINUX_CONTAINERD_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_CONTAINERD_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\n{{- if HasLinuxRuncURL}}\n  LINUX_RUNC_URL={{GetLinuxRuncURL}}\n  if [[ -n \"${LINUX_RUNC_URL:-}\" ]]; then\n    DEB=\"${LINUX_RUNC_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_RUNC_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\nfi\n\nif [[ -n ${MASTER_NODE} ]] && [[ -z ${COSMOS_URI} ]]; then\n  {{- if IsDockerContainerRuntime}}\n  cli_tool=\"docker\"\n  {{else}}\n  cli_tool=\"img\"\n  {{end}}\n  time_metric \"InstallEtcd\" installEtcd $cli_tool\nfi\n\n{{/* this will capture the amount of time to install of the network plugin during cse */}}\ntime_metric \"InstallNetworkPlugin\" installNetworkPlugin\n\n{{- if and HasNSeriesSKU IsNvidiaDevicePluginAddonEnabled}}\nif [[ ${GPU_NODE} == true ]]; then\n  gpuDriversDownloaded || time_metric \"DownloadGPUDrivers\" downloadGPUDrivers\n  time_metric \"EnsureGPUDrivers\" ensureGPUDrivers\nfi\n{{end}}\n\n{{- if and IsDockerContainerRuntime HasPrivateAzureRegistryServer}}\ndocker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET {{GetPrivateAzureRegistryServer}}\n{{end}}\n\ntime_metric \"InstallKubeletAndKubectl\" installKubeletAndKubectl\n\nif [[ $OS != $FLATCAR_OS_NAME ]]; then\n    time_metric \"EnsureRPC\" ensureRPC\n    time_metric \"EnsureCron\" ensureCron\nfi\n\ntime_metric \"CreateKubeManifestDir\" createKubeManifestDir\n\n{{- if HasDCSeriesSKU}}\nif [[ ${SGX_NODE} == true && ! -e \"/dev/sgx\" ]]; then\n  time_metric \"InstallSGXDrivers\" installSGXDrivers\nfi\n{{end}}\n\nif [[ -n ${MASTER_NODE} ]]; then\n  {{/* create etcd user if we are configured for etcd */}}\n  if [[ -z ${COSMOS_URI} ]]; then\n    time_metric \"ConfigureEtcdUser\" configureEtcdUser\n  fi\n\n  {{/* this step configures all certs */}}\n  {{/* both configs etcd/cosmos */}}\n  time_metric \"ConfigureSecrets\" configureSecrets\n\n  {{/* HACK:  in case a master starts with incorrectly defeind cloud-init IPs */}}\n  if grep -q -E '^ +addresses:|^ +- ' /etc/netplan/50-cloud-init.yaml; then\n    x=$(grep -v -E '^ +addresses:|^ +- ' /etc/netplan/50-cloud-init.yaml)\n    echo \"$x\" >/etc/netplan/50-cloud-init.yaml\n    netplan apply\n  fi\nfi\n\n{{/* configure etcd if we are configured for etcd */}}\nif [[ -n ${MASTER_NODE} ]] && [[ -z ${COSMOS_URI} ]]; then\n  time_metric \"ConfigureEtcd\" configureEtcd\nelse\n  time_metric \"RemoveEtcd\" removeEtcd\nfi\n\n{{- if HasCustomSearchDomain}}\nwait_for_file 3600 1 {{GetCustomSearchDomainsCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n{{GetCustomSearchDomainsCSEScriptFilepath}} >/opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit {{GetCSEErrorCode \"ERR_CUSTOM_SEARCH_DOMAINS_FAIL\"}}\n{{end}}\n\n{{- if IsDockerContainerRuntime}}\ntime_metric \"EnsureDocker\" ensureDocker\n{{end}}\n\ntime_metric \"ConfigureK8s\" configureK8s\n\n{{- if IsCustomCloudProfile}}\ntime_metric \"ConfigureK8sCustomCloud\" configureK8sCustomCloud\n{{- if and IsAzureStackCloud IsAzureCNI}}\ntime_metric \"ConfigureAzureStackInterfaces\" configureAzureStackInterfaces\n{{end}}\n{{end}}\n\ntime_metric \"ConfigureCNI\" configureCNI\n\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"ConfigAddons\" configAddons\n  time_metric \"WriteKubeConfig\" writeKubeConfig\nfi\n\n{{- if NeedsContainerd}}\ntime_metric \"EnsureContainerd\" ensureContainerd\n{{end}}\n\n{{/* configure and enable dhcpv6 for ipv6 features */}}\n{{- if IsIPv6Enabled}}\ntime_metric \"EnsureDHCPv6\" ensureDHCPv6\n{{end}}\n\n{{/* configure and enable kms plugin */}}\n{{- if EnableEncryptionWithExternalKms}}\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"EnsureKMSKeyvaultKey\" ensureKMSKeyvaultKey\nfi\n{{end}}\n\ntime_metric \"EnsureKubelet\" ensureKubelet\n{{if IsAzurePolicyAddonEnabled}}\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"EnsureLabelExclusionForAzurePolicyAddon\" ensureLabelExclusionForAzurePolicyAddon\nfi\n{{end}}\ntime_metric \"EnsureJournal\" ensureJournal\n\nif [[ -n ${MASTER_NODE} ]]; then\n  if version_gte ${KUBERNETES_VERSION} 1.16; then\n    time_metric \"EnsureLabelNodes\" ensureLabelNodes\n  fi\n{{- if IsAADPodIdentityAddonEnabled}}\n  time_metric \"EnsureTaints\" ensureTaints\n{{end}}\n  if [[ -z ${COSMOS_URI} ]]; then\n    time_metric \"EnsureEtcd\" ensureEtcd\n  fi\n  time_metric \"EnsureK8sControlPlane\" ensureK8sControlPlane\n  time_metric \"EnsureAddons\" ensureAddons\n  {{- if HasClusterInitComponent}}\n  if [[ $NODE_INDEX == 0 ]]; then\n    retrycmd 120 5 30 $KUBECTL apply -f /opt/azure/containers/cluster-init.yaml || exit {{GetCSEErrorCode \"ERR_CLUSTER_INIT_FAIL\"}}\n  fi\n  {{end}}\nfi\n\n{{- if not IsVHDDistroForAllNodes}}\nif $FULL_INSTALL_REQUIRED; then\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    {{/* mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 */}}\n    echo 2dd1ce17-079e-403c-b352-a1921ee207ee >/sys/bus/vmbus/drivers/hv_util/unbind\n    sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n  fi\nfi\n{{end}}\n\n{{- /* re-enable unattended upgrades */}}\n{{- if EnableUnattendedUpgrades}}\nrm -f /etc/apt/apt.conf.d/99periodic\n{{- end}}\n\n{{- if not IsAzureStackCloud}}\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  time_metric \"PurgeApt\" apt_get_purge apache2-utils &\nfi\n{{end}}\n\n{{- if not HasBlockOutboundInternet}}\n    {{- if RunUnattendedUpgradesOnBootstrap}}\napt_get_update && unattended_upgrade\n    {{- end}}\n{{- end}}\n\nif [ -f /var/run/reboot-required ]; then\n  trace_info \"RebootRequired\" \"reboot=true\"\n  /bin/bash -c \"shutdown -r 1 &\"\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    aptmarkWALinuxAgent unhold &\n  fi\nelse\n{{- if RunUnattendedUpgradesOnBootstrap}}\n  if [[ -z ${MASTER_NODE} ]]; then\n    systemctl_restart 100 5 30 kubelet\n    systemctl_restart 100 5 30 kubelet-monitor\n  fi\n{{- end}}\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    /usr/lib/apt/apt.systemd.daily &\n    aptmarkWALinuxAgent unhold &\n  fi\nfi\n\necho \"CSE finished successfully\"\necho $(date),$(hostname), endcustomscript >>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\nps auxfww >/opt/azure/provision-ps.log &\n\nexit 0\n\n#EOF\n", "num_lines": 328}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION <<EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n  grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >>\"${2}\"\n}\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n  add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n  sudo ifdown eth0 && sudo ifup eth0\n#EOF\n", "num_lines": 24}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROXY_CA_KEY=\"${PROXY_CA_KEY:=/tmp/proxy-client-ca.key}\"\nPROXY_CRT=\"${PROXY_CRT:=/tmp/proxy-client-ca.crt}\"\nPROXY_CLIENT_KEY=\"${PROXY_CLIENT_KEY:=/tmp/proxy-client.key}\"\nPROXY_CLIENT_CSR=\"${PROXY_CLIENT_CSR:=/tmp/proxy-client.csr}\"\nPROXY_CLIENT_CRT=\"${PROXY_CLIENT_CRT:=/tmp/proxy-client.crt}\"\nETCD_REQUESTHEADER_CLIENT_CA=\"${ETCD_REQUESTHEADER_CLIENT_CA:=/proxycerts/requestheader-client-ca-file}\"\nETCD_PROXY_CERT=\"${ETCD_PROXY_CERT:=/proxycerts/proxy-client-cert-file}\"\nETCD_PROXY_KEY=\"${ETCD_PROXY_KEY:=/proxycerts/proxy-client-key-file}\"\nK8S_PROXY_CA_CRT_FILEPATH=\"${K8S_PROXY_CA_CRT_FILEPATH:=/etc/kubernetes/certs/proxy-ca.crt}\"\nK8S_PROXY_KEY_FILEPATH=\"${K8S_PROXY_KEY_FILEPATH:=/etc/kubernetes/certs/proxy.key}\"\nK8S_PROXY_CRT_FILEPATH=\"${K8S_PROXY_CRT_FILEPATH:=/etc/kubernetes/certs/proxy.crt}\"\n\nPROXY_CERTS_LOCK_NAME=\"master_proxy_cert_lock\"\nPROXY_CERT_LOCK_FILE=\"/tmp/create_cert.fifl\"\n\nif [[ -z ${COSMOS_URI} ]]; then\n  ETCDCTL_ENDPOINTS=\"${ETCDCTL_ENDPOINTS:=https://127.0.0.1:2379}\"\n  ETCDCTL_CA_FILE=\"${ETCDCTL_CA_FILE:=/etc/kubernetes/certs/ca.crt}\"\n  ETCD_CA_PARAM=\"--cacert=${ETCDCTL_CA_FILE}\"\nelse\n  ETCDCTL_ENDPOINTS=\"${ETCDCTL_ENDPOINTS:=https://${COSMOS_URI}:2379}\"\n  ETCD_CA_PARAM=\"\"\nfi\nETCDCTL_KEY_FILE=\"${ETCDCTL_KEY_FILE:=/etc/kubernetes/certs/etcdclient.key}\"\nETCDCTL_CERT_FILE=\"${ETCDCTL_CERT_FILE:=/etc/kubernetes/certs/etcdclient.crt}\"\n\nETCDCTL_PARAMS=\"--command-timeout=30s --cert=${ETCDCTL_CERT_FILE} --key=${ETCDCTL_KEY_FILE} ${ETCD_CA_PARAM} --endpoints=${ETCDCTL_ENDPOINTS}\"\nRANDFILE=$(mktemp)\nexport RANDFILE\n\nopenssl genrsa -out $PROXY_CA_KEY 2048\nopenssl req -new -x509 -days 262824 -key $PROXY_CA_KEY -out $PROXY_CRT -subj '/CN=proxyClientCA'\nopenssl genrsa -out $PROXY_CLIENT_KEY 2048\nopenssl req -new -key $PROXY_CLIENT_KEY -out $PROXY_CLIENT_CSR -subj '/CN=aggregator/O=system:masters'\nopenssl x509 -req -days 262824 -in $PROXY_CLIENT_CSR -CA $PROXY_CRT -CAkey $PROXY_CA_KEY -set_serial 02 -out $PROXY_CLIENT_CRT\n\nwrite_certs_to_disk() {\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_REQUESTHEADER_CLIENT_CA --print-value-only >$K8S_PROXY_CA_CRT_FILEPATH\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_KEY --print-value-only >$K8S_PROXY_KEY_FILEPATH\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_CERT --print-value-only >$K8S_PROXY_CRT_FILEPATH\n  sed -i '1s/\\s//' $K8S_PROXY_CA_CRT_FILEPATH $K8S_PROXY_CRT_FILEPATH $K8S_PROXY_KEY_FILEPATH\n  chmod 600 $K8S_PROXY_KEY_FILEPATH\n}\n\nwrite_certs_to_disk_with_retry() {\n  for i in $(seq 1 12); do\n    write_certs_to_disk && break || sleep 5\n  done\n}\nis_etcd_healthy() {\n  for i in $(seq 1 100); do\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} endpoint health && break || sleep 5\n  done\n}\nis_etcd_healthy\nrm -f \"${PROXY_CERT_LOCK_FILE}\"\nmkfifo \"${PROXY_CERT_LOCK_FILE}\"\n\nETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} lock ${PROXY_CERTS_LOCK_NAME} >\"${PROXY_CERT_LOCK_FILE}\" &\n\npid=$!\nif read -r lockthis <\"${PROXY_CERT_LOCK_FILE}\"; then\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_REQUESTHEADER_CLIENT_CA --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_REQUESTHEADER_CLIENT_CA \" $(cat ${PROXY_CRT})\" >/dev/null 2>&1\n  fi\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_KEY --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_PROXY_KEY \" $(cat ${PROXY_CLIENT_KEY})\" >/dev/null 2>&1\n  fi\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_CERT --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_PROXY_CERT \" $(cat ${PROXY_CLIENT_CRT})\" >/dev/null 2>&1\n  fi\nfi\nkill $pid\nwait $pid\nrm -f \"${PROXY_CERT_LOCK_FILE}\"\n\nwrite_certs_to_disk_with_retry\n#EOF\n", "num_lines": 81}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nsource {{GetCSEHelpersScriptFilepath}}\n\n{{- /* This script originated at https://github.com/kubernetes/kubernetes/blob/master/cluster/gce/gci/health-monitor.sh */}}\n{{- /* and has been modified for aks-engine. */}}\n\nset -o nounset\nset -o pipefail\n\ncontainer_runtime_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for CRI to be functional/stable */}}\n  local cri_name=\"${CONTAINER_RUNTIME:-docker}\" cmd=\"docker ps\"\n  if [[ ${CONTAINER_RUNTIME} == \"containerd\" ]]; then\n    cmd=\"ctr -n k8s.io containers ls\"\n  fi\n\n  while true; do\n    if ! timeout 60 ${cmd} >/dev/null; then\n      echo \"Container runtime ${cri_name} failed!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! timeout 60 ${cmd} >/dev/null; then\n        if [[ $cri_name == \"docker\" ]]; then\n          pkill -SIGUSR1 dockerd\n        fi\n        if [[ $cri_name == \"containerd\" ]]; then\n          pkill -SIGUSR1 containerd\n        fi\n        systemctl kill --kill-who=main \"${cri_name}\"\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active ${cri_name}; then\n          systemctl start ${cri_name}\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\nkubelet_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for kubelet to be functional/stable */}}\n  local max_seconds=10 output=\"\"\n  local monitor_cmd=\"curl -m ${max_seconds} -f -s -S http://127.0.0.1:${HEALTHZPORT}/healthz\"\n  while true; do\n    if ! output=$(${monitor_cmd} 2>&1); then\n      echo $output\n      echo \"Kubelet is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd} 2>&1); then\n        systemctl kill kubelet\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active kubelet; then\n          systemctl start kubelet\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\napiserver_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for apiserver to be functional/stable */}}\n  local private_ip=$( (ip -br -4 addr show eth0 || ip -br -4 addr show azure0) | grep -Po '\\d+\\.\\d+\\.\\d+\\.\\d+')\n  local max_seconds=10 output=\"\"\n  local monitor_cmd=\"curl -m ${max_seconds} --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/client.crt --key /etc/kubernetes/certs/client.key https://${private_ip}:443/readyz?verbose\"\n  while true; do\n    if ! output=$(${monitor_cmd} 2>&1); then\n      echo $output\n      echo \"apiserver is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd} 2>&1); then\n        systemctl kill kubelet\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active kubelet; then\n          systemctl start kubelet\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\netcd_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for etcd to be functional/stable */}}\n  local max_seconds=10 output=\"\"\n  local endpoint=\"https://${PRIVATE_IP}:2379\"\n  local monitor_cmd=\"curl -s -S -m ${max_seconds} --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/etcdclient.crt --key /etc/kubernetes/certs/etcdclient.key ${endpoint}/v2/machines\"\n  while true; do\n    if ! output=$(${monitor_cmd}); then\n      echo $output\n      echo \"etcd is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd}); then\n        systemctl kill etcd\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active etcd; then\n          systemctl start etcd\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\nif [[ $# -ne 1 ]]; then\n  echo \"Usage: health-monitor.sh <container-runtime|kubelet|etcd>\"\n  exit 1\nfi\n\nSLEEP_TIME=10\ncomponent=$1\necho \"Start kubernetes health monitoring for ${component}\"\n\nif [[ ${component} == \"container-runtime\" ]]; then\n  container_runtime_monitoring\nelif [[ ${component} == \"kubelet\" ]]; then\n  kubelet_monitoring\nelif [[ ${component} == \"apiserver\" ]]; then\n  apiserver_monitoring\nelif [[ ${component} == \"etcd\" ]]; then\n  etcd_monitoring\nelse\n  echo \"Health monitoring for component ${component} is not supported!\"\nfi\n", "num_lines": 128}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset +x\nset -euo pipefail\n\nAZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\nSERVICE_PRINCIPAL_CLIENT_ID=$(jq -r '.aadClientId' ${AZURE_JSON_PATH})\nSERVICE_PRINCIPAL_CLIENT_SECRET=$(jq -r '.aadClientSecret' ${AZURE_JSON_PATH})\nTENANT_ID=$(jq -r '.tenantId' ${AZURE_JSON_PATH})\nKMS_KEYVAULT_NAME=$(jq -r '.providerVaultName' ${AZURE_JSON_PATH})\nKMS_KEY_NAME=$(jq -r '.providerKeyName' ${AZURE_JSON_PATH})\nUSER_ASSIGNED_IDENTITY_ID=$(jq -r '.userAssignedIdentityID' ${AZURE_JSON_PATH})\nPROVIDER_KEY_VERSION=$(jq -r '.providerKeyVersion' ${AZURE_JSON_PATH})\nAZURE_CLOUD=$(jq -r '.cloud' ${AZURE_JSON_PATH})\n\n# get the required parameters specific for cloud\nif [[ $AZURE_CLOUD == \"AzurePublicCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.com/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.azure.net\"\nelif [[ $AZURE_CLOUD == \"AzureChinaCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.chinacloudapi.cn/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.azure.cn\"\nelif [[ $AZURE_CLOUD == \"AzureGermanCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.de/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.microsoftazure.de\"\nelif [[ $AZURE_CLOUD == \"AzureUSGovernmentCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.us/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.usgovcloudapi.net\"\nelif [[ $AZURE_CLOUD == \"AzureStackCloud\" ]]; then\n    AZURESTACK_ENVIRONMENT_JSON_PATH=\"/etc/kubernetes/azurestackcloud.json\"\n    ACTIVE_DIRECTORY_ENDPOINT=$(jq -r '.activeDirectoryEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n    KEYVAULT_DNS_SUFFIX=$(jq -r '.keyVaultDNSSuffix' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\nelse\n    echo \"Invalid cloud name\"\n    exit 120\nfi\n\nTOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}${TENANT_ID}/oauth2/token\"\nKEYVAULT_URL=\"https://${KMS_KEYVAULT_NAME}.${KEYVAULT_DNS_SUFFIX}/keys/${KMS_KEY_NAME}/versions?maxresults=1&api-version=7.1\"\nKEYVAULT_ENDPOINT=\"https://${KEYVAULT_DNS_SUFFIX}\"\nKMS_KUBERNETES_FILE=/etc/kubernetes/manifests/kube-azure-kms.yaml\n\n# provider key version already exists\n# this will be the case for BYOK\nif [[ -n $PROVIDER_KEY_VERSION ]]; then\n    echo \"KMS provider key version already exists\"\n    exit 0\nfi\n\necho \"Generating token for Azure Key Vault\"\necho \"------------------------------------------------------------------------\"\necho \"Parameters\"\necho \"------------------------------------------------------------------------\"\necho \"SERVICE_PRINCIPAL_CLIENT_ID:     ...\"\necho \"SERVICE_PRINCIPAL_CLIENT_SECRET: ...\"\necho \"ACTIVE_DIRECTORY_ENDPOINT:       $ACTIVE_DIRECTORY_ENDPOINT\"\necho \"TENANT_ID:                       $TENANT_ID\"\necho \"TOKEN_URL:                       $TOKEN_URL\"\necho \"SCOPE:                           $KEYVAULT_ENDPOINT\"\necho \"------------------------------------------------------------------------\"\n\nif [[ $SERVICE_PRINCIPAL_CLIENT_ID == \"msi\" ]] && [[ $SERVICE_PRINCIPAL_CLIENT_SECRET == \"msi\" ]]; then\n    if [[ -z $USER_ASSIGNED_IDENTITY_ID ]]; then\n        # using system-assigned identity to access keyvault\n        TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 \\\n            -H Metadata:true \\\n            \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=$KEYVAULT_ENDPOINT\" | jq '.access_token' | xargs)\n    else\n        # using user-assigned managed identity to access keyvault\n        TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 \\\n            -H Metadata:true \\\n            \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&client_id=$USER_ASSIGNED_IDENTITY_ID&resource=$KEYVAULT_ENDPOINT\" | jq '.access_token' | xargs)\n    fi\nelse\n    # use service principal token to access keyvault\n    TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X POST \\\n        -H \"Content-Type: application/x-www-form-urlencoded\" \\\n        -d \"grant_type=client_credentials\" \\\n        -d \"client_id=$SERVICE_PRINCIPAL_CLIENT_ID\" \\\n        --data-urlencode \"client_secret=$SERVICE_PRINCIPAL_CLIENT_SECRET\" \\\n        --data-urlencode \"resource=$KEYVAULT_ENDPOINT\" \\\n        ${TOKEN_URL} | jq '.access_token' | xargs)\nfi\n\n\nif [[ -z $TOKEN ]]; then\n    echo \"Error generating token for Azure Keyvault\"\n    exit 120\nfi\n\n# Get the keyID for the kms key created as part of cluster bootstrap\nKEY_ID=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f \\\n    ${KEYVAULT_URL} -H \"Authorization: Bearer ${TOKEN}\" | jq '.value[0].kid' | xargs)\n\nif [[ -z \"$KEY_ID\" || \"$KEY_ID\" == \"null\" ]]; then\n    echo \"Error getting the kms key version\"\n    exit 120\nfi\n\n# KID format: https://<keyvault name>.vault.azure.net/keys/<key name>/<key version>\n# Example KID: \"https://akv0112master.vault.azure.net/keys/k8s/128a3d9956bc44feb6a0e2c2f35b732c\"\nKEY_VERSION=${KEY_ID##*/}\n\n# Set the version in azure.json\nif [ -f $AZURE_JSON_PATH ]; then\n    # once the version is set in azure.json, kms plugin will just default to using the key\n    # this will be changed in upcoming kms release to set the version as container args\n    tmpDir=$(mktemp -d \"$(pwd)/XXX\")\n    jq --arg KEY_VERSION ${KEY_VERSION} '.providerKeyVersion=($KEY_VERSION)' \"$AZURE_JSON_PATH\" > $tmpDir/tmp\n    mv $tmpDir/tmp \"$AZURE_JSON_PATH\"\n    # set the permissions for azure json\n    chmod 0600 \"$AZURE_JSON_PATH\"\n    chown root:root \"$AZURE_JSON_PATH\"\n    rm -Rf $tmpDir\nfi\n\nset -x\n#EOF\n", "num_lines": 119}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script looks for nodes that don't have the required kubernetes.io/role label,\n# and then labels them appropriately\n#\n# Because nodes can't self-label their role in this way,\n# we need control plane nodes to do this continually\n# to ensure that new nodes get the role labels quickly\n\nset -euo pipefail\n\nKUBECONFIG=\"$(find /home/*/.kube/config)\"\nKUBECTL=\"kubectl --kubeconfig=${KUBECONFIG}\"\n\nMASTER_SELECTOR=\"kubernetes.azure.com/role=master,kubernetes.io/role!=master,node-role.kubernetes.io/master!=\"\nMASTER_LABELS=\"kubernetes.io/role=master node-role.kubernetes.io/master=\"\nAGENT_SELECTOR=\"kubernetes.azure.com/role=agent,kubernetes.io/role!=agent,node-role.kubernetes.io/agent!=\"\nAGENT_LABELS=\"kubernetes.io/role=agent node-role.kubernetes.io/agent=\"\n\n${KUBECTL} label nodes --overwrite -l $MASTER_SELECTOR $MASTER_LABELS\n${KUBECTL} label nodes --overwrite -l $AGENT_SELECTOR $AGENT_LABELS\n#EOF\n", "num_lines": 23}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# 5.4.4 Ensure default user umask is 027 or more restrictive\numask 027\n", "num_lines": 5}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource {{GetCSEHelpersScriptFilepath}}\n\necho \"  dns-search {{GetSearchDomainName}}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"{{GetSearchDomainRealmPassword}}\" | realm join -U {{GetSearchDomainRealmUser}}@$(echo \"{{GetSearchDomainName}}\" | tr /a-z/ /A-Z/) $(echo \"{{GetSearchDomainName}}\" | tr /a-z/ /A-Z/)\n#EOF\n", "num_lines": 12}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nKUBECONFIG=\"$(find /home/*/.kube/config)\"\nKUBECTL=\"kubectl --kubeconfig=${KUBECONFIG}\"\nAAD_POD_ID_TAINT_KEY={{GetAADPodIdentityTaintKey}}\n\nif ! ${KUBECTL} get daemonsets -n kube-system -o json | jq -e -r '.items[] | select(.metadata.name == \"nmi\")' > /dev/null; then\n  for node in $(${KUBECTL} get nodes -o json | jq -e -r '.items[] | .metadata.name'); do\n    ${KUBECTL} taint nodes $node $AAD_POD_ID_TAINT_KEY:NoSchedule- 2>&1 | grep -v 'not found';\n  done\n  exit 0\nfi\nfor pod in $(${KUBECTL} get pods -n kube-system -o json | jq -r '.items[] | select(.status.phase == \"Running\") | .metadata.name'); do\n  if [[ \"$pod\" =~ ^nmi ]]; then\n    ${KUBECTL} taint nodes $(${KUBECTL} get pod ${pod} -n kube-system -o json | jq -r '.spec.nodeName') $AAD_POD_ID_TAINT_KEY:NoSchedule- 2>&1 | grep -v 'not found';\n  fi;\ndone\nexit 0\n#EOF\n", "num_lines": 20}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwhile IFS= read -r -d '' f; do\n  len=${#f}\n  mv ${f} ${f::len-4}\ndone < <(find . -name \"*.err\" -print0)\n", "num_lines": 7}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e -x -o pipefail\n\nGOTAG=\"1.13.7\"\nDOCKERARGS=\"--network=host\"\n\nOUTDIR=\"$(pwd)/_output\"\nif [ ! -d $OUTDIR ]; then\n    mkdir $OUTDIR\nfi\n\ncat <<EOF > $OUTDIR/buildcri.sh\nset -e -x -o pipefail\nexport GOOS=windows\nexport GOARCH=amd64\ngo get github.com/Microsoft/hcsshim\ncd src/github.com/Microsoft/hcsshim\ngit rev-parse HEAD > /output/hcsshim-revision.txt\ncd \\$GOPATH\ngo build -o /output/containerd-shim-runhcs-v1.exe github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1\nmkdir -p src/github.com/containerd\ncd src/github.com/containerd\npwd\ngit clone https://github.com/containerd/containerd.git\ncd containerd\ngit rev-parse HEAD > /output/containerd-revision.txt\nmake\n# make cri-release # should work, but doesn't\ncp bin/ctr.exe /output\n#cp bin/containerd.exe /output # missing CRI plugin, so build from containerd/cri\ncd \\$GOPATH\ncd src/github.com/containerd\ngit clone https://github.com/jterry75/cri.git\ncd cri\ngit checkout windows_port\ngit rev-parse HEAD > /output/cri-revision.txt\nmake containerd\ncp _output/containerd.exe /output\napt update\napt install -y zip\ncd /output\nzip windows-cri-containerd.zip *.exe *.txt *.toml\nrm -f /output/*.exe\nrm -f /output/*.txt\nEOF\nchmod +x $OUTDIR/buildcri.sh\n\ndocker run $DOCKERARGS -v $OUTDIR:/output golang:$GOTAG /bin/bash -c /output/buildcri.sh\n", "num_lines": 50}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrequired_env_vars=(\n    \"CLIENT_ID\"\n    \"CLIENT_SECRET\"\n    \"LOCATION\"\n    \"RESOURCE_GROUP_NAME\"\n    \"STORAGE_ACCOUNT_NAME\"\n    \"STORAGE_CONTAINER_NAME\"\n    \"SUBSCRIPTION_ID\"\n    \"TENANT_ID\"\n)\n\nunset_vars=()\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        unset_vars+=(${v})\n    fi\ndone\n\nif (( ${#unset_vars[@]} )); then\n    echo \"Required environment variables: ${required_env_vars[@]}\"\n    echo \"Unset environment variables: ${unset_vars[@]}\"\n    exit 1\nfi\n\nCREATE_TIME=\"$(date +%s)\"\naz login --service-principal -u $CLIENT_ID -p $CLIENT_SECRET --tenant $TENANT_ID\n\nrg_exists=$(az group exists -g $RESOURCE_GROUP_NAME --subscription $SUBSCRIPTION_ID -o json)\nif $rg_exists ; then\n    echo \"resource group '${RESOURCE_GROUP_NAME}' exists\"\nelse\n    echo \"creating new resource group: ${RESOURCE_GROUP_NAME}\"\n    az group create -l $LOCATION -g $RESOURCE_GROUP_NAME --subscription $SUBSCRIPTION_ID\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n    echo \"creating new storage account: ${STORAGE_ACCOUNT_NAME}...\"\n    az storage account create -n $STORAGE_ACCOUNT_NAME -g $RESOURCE_GROUP_NAME --sku \"Standard_RAGRS\" --tags \"now=${CREATE_TIME}\"\nelse\n    echo \"storage account '${STORAGE_ACCOUNT_NAME}' already exists.\"\nfi\n\nexists=$(az storage container exists -n ${STORAGE_CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT_NAME} -o json | jq -r .exists)\nif ! $exists ; then\n    echo \"creating new storage container: ${STORAGE_CONTAINER_NAME}...\"\n    key=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $RESOURCE_GROUP_NAME -o json | jq -r '.[0].value')\n    az storage container create --name $STORAGE_CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key=$key --public-access=blob\nelse\n    echo \"storage container '${STORAGE_CONTAINER_NAME}' already exists.\"\nfi\n\ntemp_dir=$(mktemp -d -t aks-engine-XXXXXXXX)\nzip_name=windows-provisioning-scripts-${CREATE_TIME}.zip\nzip_path=\"${temp_dir}/$zip_name\"\necho \"creating provisioning ${zip_path}...\"\nzip -j $zip_path ./staging/provisioning/windows/*\n\necho \"uploading zip to storage account...\"\naz storage copy --source-local-path $zip_path --destination-account-name $STORAGE_ACCOUNT_NAME --destination-container $STORAGE_CONTAINER_NAME\n\nrm -r -f $temp_dir\necho \"\"\necho \"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_CONTAINER_NAME}/${zip_name}\"", "num_lines": 73}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o pipefail\nsource /opt/azure/containers/provision_source.sh\n\nclusterInfo() {\n    if [ -f .kube/config ]; then\n        FIRST_MASTER_READY=$(retrycmd_no_stats 3 3 10 kubectl get nodes -l node-role.kubernetes.io/master | grep Ready | sort | head -n 1 | cut -d ' ' -f 1)\n        if [[ \"${FIRST_MASTER_READY}\" == \"${HOSTNAME}\" ]]; then\n            retrycmd_no_stats 3 5 300 kubectl cluster-info dump --namespace=kube-system --output-directory=${OUTDIR}/cluster-info\n        fi\n    fi\n}\n\ncollectCloudProviderJson() {\n    local DIR=${OUTDIR}/etc/kubernetes\n    mkdir -p ${DIR}\n    if [ -f /etc/kubernetes/azure.json ]; then\n        jq . /etc/kubernetes/azure.json | grep -v aadClient > ${DIR}/azure.json\n    fi\n    if [ -f /etc/kubernetes/azurestackcloud.json ]; then\n        jq . /etc/kubernetes/azurestackcloud.json > ${DIR}/azurestackcloud.json\n    fi\n    if [ -f /etc/kubernetes/network_interfaces.json ]; then\n        cp /etc/kubernetes/network_interfaces.json ${DIR}\n    fi\n    if [ -f /etc/kubernetes/interfaces.json ]; then\n        cp /etc/kubernetes/interfaces.json ${DIR}\n    fi\n    if [ -f /opt/azure/vhd-install.complete ]; then\n        mkdir -p ${OUTDIR}/opt/azure\n        cp /opt/azure/vhd-install.complete ${OUTDIR}/opt/azure\n    fi\n}\n\ncollectDirLogs() {\n    local DIR=${OUTDIR}${1}\n    if [ -d ${1} ]; then\n        mkdir -p ${DIR}\n        cp ${1}/*.log ${DIR}\n    fi\n}\n\ncollectDir() {\n    local DIR=${OUTDIR}${1}\n    if [ -d ${1} ]; then\n        mkdir -p ${DIR}\n        cp ${1}/* ${DIR}\n    fi\n}\n\ncollectDaemonLogs() {\n    local DIR=${OUTDIR}/daemons\n    mkdir -p ${DIR}\n    if systemctl list-units --no-pager | grep -q ${1}; then\n        timeout 15 systemctl status ${1} &> ${DIR}/${1}.status\n        timeout 15 journalctl --utc -o short-iso --no-pager -r -u ${1} &> /tmp/${1}.log\n        tac /tmp/${1}.log > ${DIR}/${1}.log\n    fi\n}\n\ncollectContainerLogs() {\n    local DIR=${OUTDIR}/containers\n    mkdir -p ${DIR}\n    find /var/log/containers -name \"${1}*\" -exec cp {} ${DIR} \\;\n}\n\ncompressLogsDirectory() {\n    sync\n    ZIP=\"/tmp/logs.zip\"\n    rm -f ${ZIP}\n    (cd ${OUTDIR}/.. && zip -q -r ${ZIP} ${HOSTNAME})\n}\n\n# AzS headers\nstackfy() {\n    # Azure Stack can store/ingest these files in a Edge Kusto DB.\n    # Data team asked for metadata to simplify queries. It is added as a header to each file.\n    RESOURCE_GROUP=$(sudo jq -r '.resourceGroup' /etc/kubernetes/azure.json)\n    SUB_ID=$(sudo jq -r '.subscriptionId' /etc/kubernetes/azure.json)\n    TENANT_ID=$(sudo jq -r '.tenantId' /etc/kubernetes/azure.json)\n    if [ \"${TENANT_ID}\" == \"adfs\" ]; then\n        TENANT_ID=$(sudo jq -r '.serviceManagementEndpoint' /etc/kubernetes/azurestackcloud.json | cut -d / -f4)\n    fi\n\n    stackfyKubeletLog\n    stackfyMobyLog\n    stackfyEtcdLog\n    stackfyFileNames /var/log\n    stackfyFileNames /var/log/azure\n    stackfyClusterInfo\n    stackfyNetwork\n}\n\nstackfyKubeletLog() {\n    KUBELET_VERSION=$(kubelet --version | grep -oh -E 'v.*$')\n    KUBELET_VERBOSITY=$(grep -e '--v=[0-9]' -oh /etc/systemd/system/kubelet.service | grep -e '[0-9]' -oh /etc/systemd/system/kubelet.service | head -n 1)\n    KUBELET_LOG_FILE=${OUTDIR}/daemons/k8s-kubelet.log\n    \n    {\n        echo \"== BEGIN HEADER ==\";\n        echo \"Type: Daemon\";\n        echo \"TenantId: ${TENANT_ID}\";\n        echo \"Name: kubelet\";\n        echo \"Version: ${KUBELET_VERSION}\";\n        echo \"Verbosity: ${KUBELET_VERBOSITY}\";\n        echo \"Image: \";\n        echo \"Hostname: ${HOSTNAME}\";\n        echo \"SubscriptionID: ${SUB_ID}\";\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\";\n        echo \"== END HEADER ==\"\n    } >> ${KUBELET_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/kubelet.service.log >> ${KUBELET_LOG_FILE}\n    rm ${OUTDIR}/daemons/kubelet.service.log\n}\n\nstackfyMobyLog() {\n    DOCKER_VERSION=$(docker version | grep -A 20 \"Server:\" | grep \"Version:\" | head -n 1 | cut -d \":\" -f 2 | xargs)\n    DOCKER_LOG_FILE=${OUTDIR}/daemons/k8s-docker.log\n    \n    {\n        echo \"== BEGIN HEADER ==\"\n        echo \"Type: Daemon\"\n        echo \"TenantId: ${TENANT_ID}\"\n        echo \"Name: docker\"\n        echo \"Version: ${DOCKER_VERSION}\"\n        echo \"Hostname: ${HOSTNAME}\"\n        echo \"SubscriptionID: ${SUB_ID}\"\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n        echo \"== END HEADER ==\"\n    } >> ${DOCKER_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/docker.service.log >> ${DOCKER_LOG_FILE}\n    rm ${OUTDIR}/daemons/docker.service.log\n}\n\nstackfyEtcdLog() {\n    if [ ! -f /usr/bin/etcd ]; then\n        return\n    fi\n\n    ETCD_VERSION=$(/usr/bin/etcd --version | grep \"etcd Version:\" | cut -d \":\" -f 2 | xargs)\n    ETCD_LOG_FILE=${OUTDIR}/daemons/k8s-etcd.log\n    \n    {\n        echo \"== BEGIN HEADER ==\"\n        echo \"Type: Daemon\"\n        echo \"TenantId: ${TENANT_ID}\"\n        echo \"Name: etcd\"\n        echo \"Version: ${ETCD_VERSION}\"\n        echo \"Hostname: ${HOSTNAME}\"\n        echo \"SubscriptionID: ${SUB_ID}\"\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n        echo \"== END HEADER ==\"\n    } >> ${ETCD_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/etcd.service.log >> ${ETCD_LOG_FILE}\n    rm ${OUTDIR}/daemons/etcd.service.log\n}\n\nstackfyClusterInfo() {\n    if [ ! -f ${OUTDIR}/cluster-info/nodes.json ]; then\n        return\n    fi\n    mkdir -p ${OUTDIR}/containers\n    for SRC in \"${OUTDIR}\"/cluster-info/kube-system/kube-controller-manager-*/logs.txt; do\n        KCM_VERBOSITY=$(grep -e \"--v=[0-9]\" -oh /etc/kubernetes/manifests/kube-controller-manager.yaml | grep -e \"[0-9]\" -oh | head -n 1)\n        KCM_IMAGE=$(grep image: /etc/kubernetes/manifests/kube-controller-manager.yaml | xargs | cut -f 2 -d \" \")\n        KCM_DIR=$(dirname ${SRC})\n        KCM_NAME=$(basename ${KCM_DIR})\n        KCM_LOG_FILE=${OUTDIR}/containers/k8s-${KCM_NAME}.log\n        \n        {\n            echo \"== BEGIN HEADER ==\"\n            echo \"Type: Container\"\n            echo \"TenantId: ${TENANT_ID}\"\n            echo \"Name: ${KCM_NAME}\"\n            echo \"Hostname: ${HOSTNAME}\"\n            echo \"ContainerID: \"\n            echo \"Image: ${KCM_IMAGE}\"\n            echo \"Verbosity: ${KCM_VERBOSITY}\"\n            echo \"SubscriptionID: ${SUB_ID}\"\n            echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n            echo \"== END HEADER ==\"\n        } >> ${KCM_LOG_FILE}\n        \n        cat ${SRC} >> ${KCM_LOG_FILE}\n    done\n}\n\nstackfyNetwork() {\n    local DIR=${OUTDIR}/network\n    mkdir -p ${DIR}\n    # basic name resolution test\n    ping ${HOSTNAME} -c 3 &> ${DIR}/k8s-ping.txt\n\n    if [ -f /etc/kubernetes/azurestackcloud.json ]; then\n        LOGIN_ENDPOINT=$(jq -r .activeDirectoryEndpoint /etc/kubernetes/azurestackcloud.json)\n        LOGIN_ENDPOINT=${LOGIN_ENDPOINT#'https://'}\n        LOGIN_ENDPOINT=${LOGIN_ENDPOINT%'/'}\n        LOGIN_ENDPOINT_LOG=${DIR}/k8s-loginEndpoint.txt\n        timeout 10 nc -vz ${LOGIN_ENDPOINT} 443 \\\n        && echo \"login endpoint reachable: ${LOGIN_ENDPOINT}\" &> ${LOGIN_ENDPOINT_LOG} \\\n        || echo \"error: login endpoint not reachable: ${LOGIN_ENDPOINT}\" &> ${LOGIN_ENDPOINT_LOG}\n    fi\n}\n\nstackfyFileNames() {\n    local DIR=${OUTDIR}/${1}\n    for SRC in \"${DIR}\"/*.log; do\n        NAME=$(basename ${SRC})\n        mv ${SRC} ${DIR}/k8s-${NAME}\n    done\n}\n\nOUTDIR=\"$(mktemp -d)/${HOSTNAME}\"\n\ncollectCloudProviderJson\ncollectDirLogs /var/log\ncollectDirLogs /var/log/azure\ncollectDirLogs /var/log/kubeaudit\ncollectDir /etc/kubernetes/manifests\ncollectDir /etc/kubernetes/addons\ncollectContainerLogs cloud-controller-manager\ncollectContainerLogs kube-addon-manager\ncollectContainerLogs kube-apiserver\ncollectContainerLogs kube-controller-manager\ncollectContainerLogs kube-scheduler\ncollectDaemonLogs kubelet.service\ncollectDaemonLogs etcd.service\ncollectDaemonLogs docker.service\nclusterInfo\n\nif [ \"${AZURE_ENV}\" = \"AzureStackCloud\" ]; then\n    stackfy\nfi\n\ncompressLogsDirectory\n", "num_lines": 240}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\nfiles=$(find .. -type f -iname '*.go' ! -path '../vendor/*')  # do not run on the vendor dir\n\nfor i in $files\ndo\n  if ! grep -q Copyright \"$i\"\n  then\n    cat copyright.txt \"$i\" > \"$i\".new && mv \"$i\".new \"$i\"\n  fi\ndone\n", "num_lines": 17}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\nROOT=\"${DIR}/..\"\n####################################################\n\nset -x\n\nGENERATED_FILES=(\n\t\"pkg/i18n/translations_generated.go\"\n\t\"pkg/engine/templates_generated.go\"\n)\n\nT=\"$(mktemp -d)\"\ntrap 'rm -rf \"${T}\"' EXIT\n\nfor file in ${GENERATED_FILES[*]}; do\n\tcp -a \"${file}\" \"${T}/\"\ndone\n\nmake generate\n\nfor file in ${GENERATED_FILES[*]}; do\n\tbasefile=$(basename \"${file}\")\n\tif ! diff -r \"${T}/${basefile}\" \"${ROOT}/${file}\" 2>&1 ; then\n\t\techo \"go generate produced changes that were not already present.\"\n\t\techo \"Make sure you include generated assets in your commit.\"\n\t\texit 1\n\tfi\ndone\n\necho \"Generated assets have no material difference than what is committed.\"\n", "num_lines": 43}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -eo pipefail\n\nPROJECT_NAME=\"aks-engine\"\n\nif [ -n \"$ACC_CLOUD\" ]; then\n  # Cloud Shell doesn't have sudo and prefers a different directory.\n  : \"${USE_SUDO:=\"false\"}\"\n  : \"${AKSE_INSTALL_DIR:=\"/usr/local/bundle/bin\"}\"\n  mkdir -p $AKSE_INSTALL_DIR\nelse\n  : \"${USE_SUDO:=\"true\"}\"\n  : \"${AKSE_INSTALL_DIR:=\"/usr/local/bin\"}\"\nfi\n\n# initArch discovers the architecture for this system.\ninitArch() {\n  ARCH=$(uname -m)\n  case $ARCH in\n    armv5*) ARCH=\"armv5\";;\n    armv6*) ARCH=\"armv6\";;\n    armv7*) ARCH=\"arm\";;\n    aarch64) ARCH=\"arm64\";;\n    x86) ARCH=\"386\";;\n    x86_64) ARCH=\"amd64\";;\n    i686) ARCH=\"386\";;\n    i386) ARCH=\"386\";;\n  esac\n}\n\n# initOS discovers the operating system for this system.\ninitOS() {\n  OS=$(uname | tr '[:upper:]' '[:lower:]')\n\n  case \"$OS\" in\n    # Minimalist GNU for Windows\n    mingw*) OS='windows';;\n  esac\n}\n\n# runs the given command as root (detects if we are root already)\nrunAsRoot() {\n  local CMD=\"$*\"\n\n  if [ $EUID -ne 0 ] && [ \"$USE_SUDO\" = \"true\" ]; then\n    CMD=\"sudo $CMD\"\n  fi\n\n  $CMD\n}\n\n# verifySupported checks that the os/arch combination is supported for\n# binary builds.\nverifySupported() {\n  local supported=\"darwin-386\\ndarwin-amd64\\nlinux-386\\nlinux-amd64\\nlinux-arm\\nlinux-arm64\\nlinux-ppc64le\\nwindows-386\\nwindows-amd64\"\n  if ! echo \"${supported}\" | grep -q \"${OS}-${ARCH}\"; then\n    echo \"No prebuilt binary for ${OS}-${ARCH}.\"\n    echo \"To build from source, go to https://github.com/Azure/aks-engine\"\n    exit 1\n  fi\n\n  if ! type \"curl\" > /dev/null && ! type \"wget\" > /dev/null; then\n    echo \"Either curl or wget is required\"\n    exit 1\n  fi\n\n  if ! type \"jq\" > /dev/null; then\n    echo \"jq is required\"\n    exit 1\n  fi\n}\n\n# checkDesiredVersion checks if the desired version is available.\ncheckDesiredVersion() {\n  # Use the GitHub releases API for the project to find the desired version for this project.\n  local release_url\n  if [[ -z \"${DESIRED_VERSION}\" ]]; then\n    release_url=\"https://api.github.com/repos/Azure/aks-engine/releases/latest\"\n  else\n    release_url=\"https://api.github.com/repos/Azure/aks-engine/releases/tags/${DESIRED_VERSION}\"\n  fi\n\n  # shellcheck disable=SC2086\n  local requestCmd\n  if type \"curl\" > /dev/null; then\n    requestCmd=\"curl -Ssl \"\n    if [[ -n \"${GITHUB_TOKEN}\" ]]; then\n      requestCmd+=\"-H 'Authorization: token ${GITHUB_TOKEN}'\"\n    fi\n    requestCmd+=\" --fail ${release_url}\"\n  elif type \"wget\" > /dev/null; then\n    requestCmd=\"wget -nv \"\n    if [[ -n \"${GITHUB_TOKEN}\" ]]; then\n      requestCmd+=\"--header='Authorization: token ${GITHUB_TOKEN}'\"\n    fi\n    requestCmd+=\" -O - ${release_url}\"\n  fi\n\n  local response\n  if ! response=$(eval \"${requestCmd}\") ; then\n    echo \"Failed requesting release for ${DESIRED_VERSION} tag from GitHub API.\"\n    exit 1\n  fi\n\n  TAG=$(jq -r '.name | values' <<< \"${response}\")\n  if [[ -z \"${TAG}\" ]]; then\n    echo \"Cannot determine ${DESIRED_VERSION} tag.\"\n    exit 1\n  fi\n}\n\n# checkAKSEInstalledVersion checks which version of AKSE is installed and\n# if it needs to be changed.\ncheckAKSEInstalledVersion() {\n  if [[ -f \"${AKSE_INSTALL_DIR}/${PROJECT_NAME}\" ]]; then\n    local version\n    version=$(aks-engine version | grep 'Version' | cut -d' ' -f2)\n    if [[ \"$version\" == \"$TAG\" ]]; then\n      echo \"AKS-Engine ${version} is already ${DESIRED_VERSION:-latest}\"\n      return 0\n    else\n      echo \"AKS-Engine ${TAG} is available. Changing from version ${version}.\"\n      return 1\n    fi\n  else\n    return 1\n  fi\n}\n\n# downloadFile downloads the latest binary package and also the checksum\n# for that binary.\ndownloadFile() {\n  AKSE_DIST=\"aks-engine-$TAG-$OS-$ARCH.tar.gz\"\n  DOWNLOAD_URL=\"https://github.com/Azure/aks-engine/releases/download/$TAG/$AKSE_DIST\"\n  AKSE_TMP_ROOT=\"$(mktemp -dt akse-installer-XXXXXX)\"\n  AKSE_TMP_FILE=\"$AKSE_TMP_ROOT/$AKSE_DIST\"\n  echo \"Downloading $DOWNLOAD_URL\"\n  if type \"curl\" > /dev/null; then\n    curl -SsL \"$DOWNLOAD_URL\" -o \"$AKSE_TMP_FILE\"\n  elif type \"wget\" > /dev/null; then\n    wget -q -O \"$AKSE_TMP_FILE\" \"$DOWNLOAD_URL\"\n  fi\n}\n\n# installFile vunpacks and installs it.\ninstallFile() {\n  AKSE_TMP=\"$AKSE_TMP_ROOT/$PROJECT_NAME\"\n\n  mkdir -p \"$AKSE_TMP\"\n  tar xf \"$AKSE_TMP_FILE\" -C \"$AKSE_TMP\"\n  AKSE_TMP_BIN=\"$AKSE_TMP/$PROJECT_NAME-$TAG-$OS-$ARCH\"\n  echo \"Preparing to install $PROJECT_NAME into ${AKSE_INSTALL_DIR}\"\n  runAsRoot cp \"$AKSE_TMP_BIN/$PROJECT_NAME\" \"$AKSE_INSTALL_DIR\"\n  echo \"$PROJECT_NAME installed into $AKSE_INSTALL_DIR/$PROJECT_NAME\"\n}\n\n# fail_trap is executed if an error occurs.\nfail_trap() {\n  result=$?\n  if [ \"$result\" != \"0\" ]; then\n    if [[ -n \"$INPUT_ARGUMENTS\" ]]; then\n      echo \"Failed to install $PROJECT_NAME with the arguments provided: $INPUT_ARGUMENTS\"\n      help\n    else\n      echo \"Failed to install $PROJECT_NAME\"\n    fi\n    echo -e \"\\tFor support, go to https://github.com/Azure/aks-engine.\"\n  fi\n  cleanup\n  exit $result\n}\n\n# testVersion tests the installed client to make sure it is working.\ntestVersion() {\n  set +e\n  if [ \"$?\" = \"1\" ]; then\n    # shellcheck disable=SC2016\n    echo \"$PROJECT_NAME not found. Is $AKSE_INSTALL_DIR on your \"'$PATH?'\n    exit 1\n  fi\n  set -e\n  echo \"Run '$PROJECT_NAME version' to test.\"\n}\n\n# help provides possible cli installation arguments\nhelp () {\n  echo \"Accepted cli arguments are:\"\n  echo -e \"\\t[--help|-h ] ->> prints this help\"\n  echo -e \"\\t[--version|-v <desired_version>] . When not defined it defaults to latest\"\n  echo -e \"\\te.g. --version v0.32.3  or -v latest\"\n  echo -e \"\\t[--no-sudo]  ->> install without sudo\\n\"\n  echo -e \"\\tIf GITHUB_TOKEN env var is set, it will be used to fetch releases via the GitHub API.\\n\"\n}\n\n# cleanup temporary files\ncleanup() {\n  if [[ -d \"${AKSE_TMP_ROOT:-}\" ]]; then\n    rm -rf \"$AKSE_TMP_ROOT\"\n  fi\n}\n\n# Execution\n\n#Stop execution on any error\ntrap \"fail_trap\" EXIT\nset -e\n\n# Parsing input arguments (if any)\nexport INPUT_ARGUMENTS=( \"${@}\" )\nset -u\nwhile [[ $# -gt 0 ]]; do\n  case $1 in\n    '--version'|-v)\n       shift\n       if [[ $# -ne 0 ]]; then\n           export DESIRED_VERSION=\"${1}\"\n       else\n           echo -e \"Please provide the desired version. e.g. --version v0.32.3 or -v latest\"\n           exit 0\n       fi\n       ;;\n    '--no-sudo')\n       USE_SUDO=\"false\"\n       ;;\n    '--help'|-h)\n       help\n       exit 0\n       ;;\n    *) exit 1\n       ;;\n  esac\n  shift\ndone\nset +u\n\ninitArch\ninitOS\nverifySupported\ncheckDesiredVersion\nif ! checkAKSEInstalledVersion; then\n  downloadFile\n  installFile\nfi\ntestVersion\ncleanup\n", "num_lines": 250}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n# IMPORTANT: This script is meant for use only within CI environments as it assumes the linux amd64 architecture.\n\necho \"==> Downloading kubectl version ${KUBECTL_VERSION} <==\"\n\ncurl -L https://storage.googleapis.com/kubernetes-release/release/v\"${KUBECTL_VERSION}\"/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl\nchmod +x /usr/local/bin/kubectl\n", "num_lines": 12}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ncovermode=${COVERMODE:-atomic}\ncoverdir=$(mktemp -d /tmp/coverage.XXXXXXXXXX)\nprofile=\"${coverdir}/cover.out\"\ncoveragetxt=\"coverage.txt\"\n\ngenerate_cover_data() {\n  ginkgo version\n  ginkgo -mod=vendor -skipPackage test/e2e -failFast -cover -r -v -tags=fast -ldflags \"${LDFLAGS}\" .\n  echo \"\" > ${coveragetxt}\n  find . -type f -name \"*.coverprofile\" | while read -r file;  do cat \"$file\" >> ${coveragetxt} && mv \"$file\" \"${coverdir}\"; done\n  echo \"mode: $covermode\" >\"$profile\"\n  grep -h -v \"^mode:\" \"$coverdir\"/*.coverprofile >>\"$profile\"\n}\n\npush_to_codecov() {\n  bash <(curl -s https://codecov.io/bash) || echo \"push to codecov failed\"\n}\n\ngenerate_cover_data\ngo tool cover -func \"${profile}\"\n\ncase \"${1-}\" in\n  --html)\n    go tool cover -html \"${profile}\"\n    ;;\n  --codecov)\n    push_to_codecov\n    ;;\nesac\n", "num_lines": 48}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nscripts/update-translation.sh -l en_US -p\n\nmv acsengine.po translations/en_US/LC_MESSAGES/acsengine.po\nrm acsengine.pot\n", "num_lines": 10}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nGO_SOURCE=\"pkg/engine/*.go pkg/engine/transform/*.go pkg/api/*.go pkg/operations/*.go pkg/operations/kubernetesupgrade/*.go\"\nLANGUAGE=\"en_US\"\nDOMAIN=\"acsengine\"\ngenerate_po=\"false\"\ngenerate_mo=\"false\"\n\nwhile getopts \"hl:pm\" opt; do\n  case $opt in\n    h)\n      echo \"$0 [-l language] [-p] [-m]\"\n      echo \" -l <language>: Language to translate\"\n      echo \" -p extract strings and generate PO file\"\n      echo \" -m generate MO file\"\n      exit 0\n      ;;\n    l)\n      LANGUAGE=\"${OPTARG}\"\n      ;;\n    p)\n      generate_po=\"true\"\n      ;;\n    m)\n      generate_mo=\"true\"\n      ;;\n    \\?)\n      echo \"$0 [-l language] [-p] [-m]\"\n      exit 1\n      ;;\n  esac\ndone\n\nif ! command -v go-xgettext > /dev/null; then\n  echo 'Can not find go-xgettext, install with:'\n  echo 'go get github.com/JiangtianLi/gettext/go-xgettext'\n  exit 1\nfi\n\nif ! command -v msginit > /dev/null; then\n  echo 'Can not find msginit, install with:'\n  echo 'apt-get install gettext'\n  exit 1\nfi\n\nif [[ \"${generate_po}\" == \"true\" ]]; then\n  echo \"Extract strings and generate PO files...\"\n  go-xgettext -o ${DOMAIN}.pot --keyword=Translator.Errorf --keyword-plural=Translator.NErrorf --msgid-bugs-address=\"\" --sort-output \"${GO_SOURCE}\"\n  msginit -l \"${LANGUAGE}\" -o ${DOMAIN}.po -i ${DOMAIN}.pot\nfi\n\nif [[ \"${generate_mo}\" == \"true\" ]]; then\n  echo \"Generate MO file...\"\n  if [ ! -f ${DOMAIN}.po ]; then\n    echo \"${DOMAIN}.po not found!\"\n\texit 1\n  fi\n  msgfmt -c -v -o ${DOMAIN}.mo ${DOMAIN}.po\nfi\n", "num_lines": 63}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\necho \"==> Checking copyright headers <==\"\n\nfiles=$(find . -type f -iname '*.go' ! -path './vendor/*' ! -path './hack/tools/*' ! -path './test/e2e/vendor/*')\nlicRes=$(for file in $files; do\n           awk 'NR<=4' \"$file\" | grep -Eq \"(Copyright|generated|GENERATED)\" || echo \"$file\";\n         done)\n\nif [ -n \"$licRes\" ]; then\n        echo \"Copyright header check failed:\";\n        echo \"${licRes}\";\n        exit 1;\nfi\n", "num_lines": 20}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nexit_code=0\n\necho \"==> Running go mod check <==\"\n\ngit diff --exit-code --quiet go.mod go.sum vendor/modules.txt\nerror_code=$?\n\nif [ $error_code -ne 0 ]; then\n  git --no-pager diff go.mod go.sum vendor/modules.txt\n  echo \"The dependency state is out of sync. Please commit changes to go.mod, go.sum.\"\nelse\n  echo \"go mod ok.\"\nfi\n\nexit $error_code\n", "num_lines": 21}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -euo pipefail\n\necho\necho \"==> Running Go linter <==\"\ngo version\ngolangci-lint --version\nif [ -f /.dockerenv ]; then\n    echo \"Running inside container\";\nfi\n\ngolangci-lint run --modules-download-mode=vendor\n", "num_lines": 27}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\necho \"==> Running shell linter <==\"\nshellcheck --version\nif [ -f /.dockerenv ]; then\n    echo \"Running inside container\";\nfi\n\n# All shell scripts, except those that support deprecated orchestrators or are in vendored code.\nfiles=$(find . -type f -name \"*.sh\" -not -path './vendor/*' -not -path './hack/tools/*' -not -path './test/e2e/vendor/*')\n\nIGNORED=\"\nSC1127\nSC1009\nSC1054\nSC1056\nSC1072\nSC1073\nSC1083\nSC1090\nSC1091\nSC2004\nSC2015\nSC2034\nSC2046\nSC2053\nSC2068\nSC2086\nSC2128\nSC2145\nSC2154\nSC2206\n\"\n\nshellcheck $(printf -- \"-e %s \" $IGNORED) $files\n", "num_lines": 41}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\nset -euo pipefail\n\nfunction validate_package() {\n    local package_url=$1\n\n    temp_dir=$(mktemp -d -t aks-engine-XXXXXXXX)\n    echo \"Downloading $package_version to $temp_dir/scripts.zip\"\n    curl -L \"$package_url\" -o \"$temp_dir/scripts.zip\"\n\n    echo \"Extracting files to $temp_dir/scripts\"\n    unzip \"$temp_dir/scripts.zip\" -d \"$temp_dir/scripts\"\n\n    # Perform a recursive diff of the two directories but ignore comments since checked in powershell files\n    # will not container signature blocks at the end of the files.\n    diff -bBr --ignore-matching-lines='^#' \"$temp_dir/scripts\" \"./staging/provisioning/windows/\"\n\n    echo \"Files match\"\n}\n\necho \"Validating content of Windows provisioning scripts...\"\npackage_version=$(grep  \"DefaultWindowsProvisioningScriptsPackageVersion\" ./pkg/api/const.go  | cut -d ' ' -f 3 | cut -d '\"' -f2)\n\necho \"Package version: $package_version\"\nif [ -z \"$package_version\" ]; then\n    echo \"Could not find value for 'DefaultWindowsProvisioningScriptsPackageVersion' in /pkg/api/const.go\"\n    exit 1\nfi\n\n# urls from pkg/api/azenvtypes.go\nvalidate_package \"https://kubernetesartifacts.azureedge.net/aks-engine/windows/provisioning/signedscripts-${package_version}.zip\"\nvalidate_package \"https://mirror.azk8s.cn/aks-engine/windows/provisioning/signedscripts-${package_version}.zip\"\n\n", "num_lines": 37}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\n\nGOPATH=\"/go\"\nWORK_DIR=\"/aks-engine\"\n\n# Assumes we're running from the git root of aks-engine\ndocker run --rm \\\n-v $(pwd):${WORK_DIR} \\\n-w ${WORK_DIR} \\\n\"${DEV_IMAGE}\" make build-binary || exit 1\n", "num_lines": 13}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_ID\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID_TO_CLEANUP\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID_TO_CLEANUP env var\"\n    exit 1;\nfi\n\nif [ -z \"$EXPIRATION_IN_HOURS\" ]; then\n    EXPIRATION_IN_HOURS=2\nfi\n\nif az login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null; then\n    echo \"Successfully logged in using service principal\"\nelse\n    exit 1\nfi\n\n# set to the sub id we want to cleanup\nif az account set -s $SUBSCRIPTION_ID_TO_CLEANUP; then\n    echo \"Successfully set subscription\"\nelse\n    exit 1\nfi\n\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n# find resource groups created before our deadline\necho \"Looking for resource groups created over ${EXPIRATION_IN_HOURS} hours ago...\"\nif [ -z \"$RESOURCE_GROUP_SUBSTRING\" ]; then\n  for resourceGroup in $(az group list | jq --arg dl $deadline '.[] | select(.name | contains(\"acse-test\") or contains(\"aksimages\") or contains(\"NetworkWatcherRG\") | not) | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || \"\"); do\n      echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n      az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n  done\nelse\n  for resourceGroup in $(az group list | jq --arg dl $deadline --arg rg $RESOURCE_GROUP_SUBSTRING '.[] | select(.name | contains(\"acse-test\") or contains(\"aksimages\") or contains (\"NetworkWatcherRG\") | not) | select(.name | contains($rg)) | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || \"\"); do\n      echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n      az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n  done\nfi\n", "num_lines": 72}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nTMP_DIR=$(mktemp -d \"$(pwd)/XXXXXXXXXXXX\")\nTMP_BASENAME=$(basename ${TMP_DIR})\nGOPATH=\"/go\"\nWORK_DIR=\"/aks-engine\"\nMASTER_VM_UPGRADE_SKU=\"${MASTER_VM_UPGRADE_SKU:-Standard_D4_v3}\"\nNODE_VM_UPGRADE_SKU=\"${NODE_VM_UPGRADE_SKU:-Standard_D4_v3}\"\nAZURE_ENV=\"${AZURE_ENV:-AzurePublicCloud}\"\nIDENTITY_SYSTEM=\"${IDENTITY_SYSTEM:-azure_ad}\"\nARC_LOCATION=\"eastus\"\nGINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST:-false}\"\nTEST_PVC=\"${TEST_PVC:-false}\"\nROTATE_CERTS=\"${ROTATE_CERTS:-false}\"\nVALIDATE_CPU_LOAD=\"${VALIDATE_CPU_LOAD:-false}\"\nmkdir -p _output || exit 1\n\n# Assumes we're running from the git root of aks-engine\nif [ \"${BUILD_AKS_ENGINE}\" = \"true\" ]; then\n  docker run --rm \\\n  -v $(pwd):${WORK_DIR} \\\n  -w ${WORK_DIR} \\\n  \"${DEV_IMAGE}\" make build-binary || exit 1\nfi\n\ncat > ${TMP_DIR}/apimodel-input.json <<END\n${API_MODEL_INPUT}\nEND\n\n# Jenkinsfile will yield a null $ADD_NODE_POOL_INPUT if not set in the test job config\nif [ \"$ADD_NODE_POOL_INPUT\" == \"null\" ]; then\n  ADD_NODE_POOL_INPUT=\"\"\nfi\nif [ \"$LB_TEST_TIMEOUT\" == \"\" ]; then\n  LB_TEST_TIMEOUT=\"${E2E_TEST_TIMEOUT}\"\nfi\nif [ \"$STABILITY_ITERATIONS\" == \"\" ]; then\n  STABILITY_ITERATIONS=3\nfi\nif [ \"$STABILITY_ITERATIONS_SUCCESS_RATE\" == \"\" ]; then\n  STABILITY_ITERATIONS_SUCCESS_RATE=1.0\nfi\nif [ \"$SINGLE_COMMAND_TIMEOUT_MINUTES\" == \"\" ]; then\n  SINGLE_COMMAND_TIMEOUT_MINUTES=1\nfi\nif [ \"$STABILITY_TIMEOUT_SECONDS\" == \"\" ]; then\n  STABILITY_TIMEOUT_SECONDS=5\nfi\nif [ \"$RUN_VMSS_NODE_PROTOTYPE\" == \"\" ]; then\n  RUN_VMSS_NODE_PROTOTYPE=\"false\"\nfi\n\nif [ -n \"$PRIVATE_SSH_KEY_FILE\" ]; then\n  PRIVATE_SSH_KEY_FILE=$(realpath --relative-to=$(pwd) ${PRIVATE_SSH_KEY_FILE})\nfi\n\nfunction tryExit {\n  if [ \"${AZURE_ENV}\" != \"AzureStackCloud\" ]; then\n    exit 1\n  fi\n}\n\nfunction renameResultsFile {\n  JUNIT_PATH=$(pwd)/test/e2e/kubernetes/junit.xml\n  if [ \"${AZURE_ENV}\" == \"AzureStackCloud\" ] && [ -f ${JUNIT_PATH} ]; then\n    mv ${JUNIT_PATH} $(pwd)/test/e2e/kubernetes/${1}-junit.xml\n  fi\n}\n\nfunction rotateCertificates {\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e REGION=${REGION} \\\n    -e RESOURCE_GROUP=${RESOURCE_GROUP} \\\n    ${DEV_IMAGE} \\\n    ./bin/aks-engine rotate-certs \\\n    --api-model _output/${RESOURCE_GROUP}/apimodel.json \\\n    --ssh-host ${API_SERVER} \\\n    --location ${REGION} \\\n    --linux-ssh-private-key _output/${RESOURCE_GROUP}-ssh \\\n    --resource-group ${RESOURCE_GROUP} \\\n    --client-id ${AZURE_CLIENT_ID} \\\n    --client-secret ${AZURE_CLIENT_SECRET} \\\n    --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n    --azure-env ${AZURE_ENV} \\\n    --identity-system ${IDENTITY_SYSTEM} \\\n    --debug\n\n  # Retry if it fails the first time (validate --certificate-profile instead of regenerating a new set of certs)\n  exit_code=$?\n  if [ $exit_code -ne 0 ]; then\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"jq '.properties.certificateProfile' _output/${RESOURCE_GROUP}/_rotate_certs_output/apimodel.json > _output/${RESOURCE_GROUP}/certificateProfile.json\" || exit 1\n\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e REGION=${REGION} \\\n      -e RESOURCE_GROUP=${RESOURCE_GROUP} \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine rotate-certs \\\n      --api-model _output/${RESOURCE_GROUP}/apimodel.json \\\n      --ssh-host ${API_SERVER} \\\n      --location ${REGION} \\\n      --linux-ssh-private-key _output/${RESOURCE_GROUP}-ssh \\\n      --resource-group ${RESOURCE_GROUP} \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --certificate-profile _output/${RESOURCE_GROUP}/certificateProfile.json --force \\\n      --azure-env ${AZURE_ENV} \\\n      --identity-system ${IDENTITY_SYSTEM} \\\n      --debug\n\n    exit $?\n  fi\n}\n\necho \"Running E2E tests against a cluster built with the following API model:\"\ncat ${TMP_DIR}/apimodel-input.json\n\nCLEANUP_AFTER_DEPLOYMENT=${CLEANUP_ON_EXIT}\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ] || [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  CLEANUP_AFTER_DEPLOYMENT=\"false\"\nfi\n\nif [ -n \"${GINKGO_SKIP}\" ]; then\n  if [ -n \"${GINKGO_SKIP_AFTER_SCALE_DOWN}\" ]; then\n    SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_SCALE_DOWN}\"\n  else\n    SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP}\"\n  fi\n  if [ -n \"${GINKGO_SKIP_AFTER_SCALE_UP}\" ]; then\n    SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_SCALE_UP}\"\n  else\n    SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP}\"\n  fi\n  if [ -n \"${GINKGO_SKIP_AFTER_UPGRADE}\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}\"\n  fi\n  if [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${SKIP_AFTER_SCALE_DOWN}|${SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${SKIP_AFTER_UPGRADE}\"\n  fi\nelse\n  SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP_AFTER_SCALE_DOWN}\"\n  SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP_AFTER_SCALE_UP}\"\n  if [ -n \"${GINKGO_SKIP_AFTER_UPGRADE}\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"\"\n  fi\n  if [ \"${SCALE_CLUSTER}\" = \"true\" ] && [ \"${SKIP_AFTER_UPGRADE}\" != \"\" ]; then\n    SKIP_AFTER_UPGRADE=\"${SKIP_AFTER_SCALE_DOWN}|${SKIP_AFTER_UPGRADE}\"\n  elif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    SKIP_AFTER_UPGRADE=\"${SKIP_AFTER_SCALE_DOWN}\"\n  fi\nfi\n\ndocker run --rm \\\n-v $(pwd):${WORK_DIR} \\\n-v /etc/ssl/certs:/etc/ssl/certs \\\n-w ${WORK_DIR} \\\n-e CLUSTER_DEFINITION=${TMP_BASENAME}/apimodel-input.json \\\n-e CLIENT_ID=\"${AZURE_CLIENT_ID}\" \\\n-e CLIENT_SECRET=\"${AZURE_CLIENT_SECRET}\" \\\n-e CLIENT_OBJECTID=\"${CLIENT_OBJECTID}\" \\\n-e TENANT_ID=\"${AZURE_TENANT_ID}\" \\\n-e SUBSCRIPTION_ID=\"${AZURE_SUBSCRIPTION_ID}\" \\\n-e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n-e ORCHESTRATOR=kubernetes \\\n-e ORCHESTRATOR_RELEASE=\"${ORCHESTRATOR_RELEASE}\" \\\n-e CREATE_VNET=\"${CREATE_VNET}\" \\\n-e PRIVATE_SSH_KEY_FILE=\"${PRIVATE_SSH_KEY_FILE}\" \\\n-e TIMEOUT=\"${E2E_TEST_TIMEOUT}\" \\\n-e LB_TIMEOUT=\"${LB_TEST_TIMEOUT}\" \\\n-e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n-e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n-e CLEANUP_ON_EXIT=${CLEANUP_AFTER_DEPLOYMENT} \\\n-e SKIP_LOGS_COLLECTION=\"${SKIP_LOGS_COLLECTION}\" \\\n-e REGIONS=\"${REGION_OPTIONS}\" \\\n-e WINDOWS_NODE_IMAGE_GALLERY=\"${WINDOWS_NODE_IMAGE_GALLERY}\" \\\n-e WINDOWS_NODE_IMAGE_NAME=\"${WINDOWS_NODE_IMAGE_NAME}\" \\\n-e WINDOWS_NODE_IMAGE_RESOURCE_GROUP=\"${WINDOWS_NODE_IMAGE_RESOURCE_GROUP}\" \\\n-e WINDOWS_NODE_IMAGE_SUBSCRIPTION_ID=\"${WINDOWS_NODE_IMAGE_SUBSCRIPTION_ID}\" \\\n-e WINDOWS_NODE_IMAGE_VERSION=\"${WINDOWS_NODE_IMAGE_VERSION}\" \\\n-e WINDOWS_NODE_VHD_URL=\"${WINDOWS_NODE_VHD_URL}\" \\\n-e LINUX_NODE_IMAGE_GALLERY=$LINUX_NODE_IMAGE_GALLERY \\\n-e LINUX_NODE_IMAGE_NAME=$LINUX_NODE_IMAGE_NAME \\\n-e LINUX_NODE_IMAGE_RESOURCE_GROUP=$LINUX_NODE_IMAGE_RESOURCE_GROUP \\\n-e LINUX_NODE_IMAGE_SUBSCRIPTION_ID=$LINUX_NODE_IMAGE_SUBSCRIPTION_ID \\\n-e LINUX_NODE_IMAGE_VERSION=$LINUX_NODE_IMAGE_VERSION \\\n-e OS_DISK_SIZE_GB=$OS_DISK_SIZE_GB \\\n-e DISTRO=$DISTRO \\\n-e CONTAINER_RUNTIME=$CONTAINER_RUNTIME \\\n-e LOG_ANALYTICS_WORKSPACE_KEY=\"${LOG_ANALYTICS_WORKSPACE_KEY}\" \\\n-e CUSTOM_HYPERKUBE_IMAGE=\"${CUSTOM_HYPERKUBE_IMAGE}\" \\\n-e CUSTOM_KUBE_PROXY_IMAGE=\"${CUSTOM_KUBE_PROXY_IMAGE}\" \\\n-e IS_JENKINS=\"${IS_JENKINS}\" \\\n-e TEST_PVC=\"${TEST_PVC}\" \\\n-e SKIP_TEST=\"${SKIP_TESTS}\" \\\n-e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n-e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n-e GINKGO_SKIP=\"${GINKGO_SKIP}\" \\\n-e API_PROFILE=\"${API_PROFILE}\" \\\n-e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n-e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n-e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n-e LOCATION=\"${LOCATION}\" \\\n-e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n-e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n-e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n-e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n-e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n-e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n-e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n-e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n-e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n-e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n-e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n-e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n-e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n-e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n-e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n-e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n-e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n-e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n-e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n-e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n-e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n-e LINUX_CONTAINERD_URL=${LINUX_CONTAINERD_URL} \\\n-e WINDOWS_CONTAINERD_URL=${WINDOWS_CONTAINERD_URL} \\\n-e LINUX_MOBY_URL=${LINUX_MOBY_URL} \\\n-e LINUX_RUNC_URL=${LINUX_RUNC_URL} \\\n-e VALIDATE_CPU_LOAD=${VALIDATE_CPU_LOAD} \\\n-e RUN_VMSS_NODE_PROTOTYPE=${RUN_VMSS_NODE_PROTOTYPE} \\\n-e KAMINO_VMSS_PROTOTYPE_LOCAL_CHART_PATH=${KAMINO_VMSS_PROTOTYPE_LOCAL_CHART_PATH} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_REGISTRY=${KAMINO_VMSS_PROTOTYPE_IMAGE_REGISTRY} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_REPOSITORY=${KAMINO_VMSS_PROTOTYPE_IMAGE_REPOSITORY} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_TAG=${KAMINO_VMSS_PROTOTYPE_IMAGE_TAG} \\\n-e CUSTOM_KUBE_PROXY_IMAGE=${CUSTOM_KUBE_PROXY_IMAGE} \\\n-e CUSTOM_KUBE_APISERVER_IMAGE=${CUSTOM_KUBE_APISERVER_IMAGE} \\\n-e CUSTOM_KUBE_SCHEDULER_IMAGE=${CUSTOM_KUBE_SCHEDULER_IMAGE} \\\n-e CUSTOM_KUBE_CONTROLLER_MANAGER_IMAGE=${CUSTOM_KUBE_CONTROLLER_MANAGER_IMAGE} \\\n-e CUSTOM_KUBE_BINARY_URL=${CUSTOM_KUBE_BINARY_URL} \\\n-e CUSTOM_WINDOWS_PACKAGE_URL=${CUSTOM_WINDOWS_PACKAGE_URL} \\\n-e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n\"${DEV_IMAGE}\" make test-kubernetes || tryExit && renameResultsFile \"deploy\"\n\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ] || [ \"${GET_CLUSTER_LOGS}\" = \"true\" ] || [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  # shellcheck disable=SC2012\n  RESOURCE_GROUP=$(ls -dt1 _output/* | head -n 1 | cut -d/ -f2)\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -w ${WORK_DIR} \\\n    -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n    ${DEV_IMAGE} \\\n    /bin/bash -c \"chmod -R 777 _output/$RESOURCE_GROUP _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n  # shellcheck disable=SC2012\n  REGION=$(ls -dt1 _output/* | head -n 1 | cut -d/ -f2 | cut -d- -f2)\n  API_SERVER=${RESOURCE_GROUP}.${REGION}.${RESOURCE_MANAGER_VM_DNS_SUFFIX:-cloudapp.azure.com}\n\n  if [ \"${GET_CLUSTER_LOGS}\" = \"true\" ]; then\n      docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine get-logs \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --ssh-host $API_SERVER \\\n      --linux-ssh-private-key _output/$RESOURCE_GROUP-ssh \\\n      --linux-script ./scripts/collect-logs.sh \\\n      --windows-script ./scripts/collect-windows-logs.ps1\n  fi\n\n  if [ $(( RANDOM % 4 )) -eq 3 ]; then\n    echo Removing bookkeeping tags from VMs in resource group $RESOURCE_GROUP ...\n    az login --username ${AZURE_CLIENT_ID} --password ${AZURE_CLIENT_SECRET} --tenant ${AZURE_TENANT_ID} --service-principal > /dev/null\n    for vm_type in vm vmss; do\n      for vm in $(az $vm_type list -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --query '[].name' -o table | tail -n +3); do\n        az $vm_type update -n $vm -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --set tags={} > /dev/null\n      done\n    done\n  fi\n\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ]; then\n    git reset --hard\n    git remote rm $UPGRADE_FORK\n    git remote add $UPGRADE_FORK https://github.com/$UPGRADE_FORK/aks-engine.git\n    git fetch --prune $UPGRADE_FORK\n    git branch -D $UPGRADE_FORK/$UPGRADE_BRANCH\n    git checkout -b $UPGRADE_FORK/$UPGRADE_BRANCH --track $UPGRADE_FORK/$UPGRADE_BRANCH\n    git pull\n    git log -1\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      \"${DEV_IMAGE}\" make build-binary > /dev/null 2>&1 || exit 1\n  fi\nelse\n  exit 0\nfi\n\nif [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  rotateCertificates\n\n  SKIP_AFTER_ROTATE_CERTS=\"${GINKGO_SKIP}|should be able to autoscale\"\n  SKIP_AFTER_SCALE_DOWN=\"${SKIP_AFTER_SCALE_DOWN}|should be able to autoscale\"\n  SKIP_AFTER_SCALE_UP=\"${SKIP_AFTER_SCALE_DOWN}|should be able to autoscale\"\n  CLEANUP_AFTER_ROTATE_CERTS=${CLEANUP_ON_EXIT}\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ]; then\n    CLEANUP_AFTER_ROTATE_CERTS=\"false\"\n  fi\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_AFTER_ROTATE_CERTS} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_ROTATE_CERTS}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e SKIP_TEST=false \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"rotate-certs\"\nfi\n\nif [ -n \"$ADD_NODE_POOL_INPUT\" ]; then\n  for pool in $(echo ${ADD_NODE_POOL_INPUT} | jq -c '.[]'); do\n    echo $pool > ${TMP_DIR}/addpool-input.json\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine addpool \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --node-pool ${TMP_BASENAME}/addpool-input.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --auth-method client_secret \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  CLEANUP_AFTER_ADD_NODE_POOL=${CLEANUP_ON_EXIT}\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    CLEANUP_AFTER_ADD_NODE_POOL=\"false\"\n  fi\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_AFTER_ADD_NODE_POOL} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_DOWN}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_ADD_POOL} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"add-node-pool\"\nfi\n\nif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n  nodepoolcount=$(jq '.properties.agentPoolProfiles| length' < _output/$RESOURCE_GROUP/apimodel.json)\n  for ((i = 0; i < $nodepoolcount; ++i)); do\n    nodepool=$(jq -r --arg i $i '. | .properties.agentPoolProfiles[$i | tonumber].name' < _output/$RESOURCE_GROUP/apimodel.json)\n    if [ \"${UPDATE_NODE_POOLS}\" = \"true\" ]; then\n      # modify the master VM SKU to simulate vertical vm scaling via upgrade\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        -e NODE_VM_UPGRADE_SKU=$NODE_VM_UPGRADE_SKU \\\n        ${DEV_IMAGE} \\\n        /bin/bash -c \"jq --arg sku \\\"$NODE_VM_UPGRADE_SKU\\\" --arg i $i '. | .properties.agentPoolProfiles[$i | tonumber].vmSize = \\$sku' < _output/$RESOURCE_GROUP/apimodel.json > _output/$RESOURCE_GROUP/apimodel-update.json\" || exit 1\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        ${DEV_IMAGE} \\\n        /bin/bash -c \"mv _output/$RESOURCE_GROUP/apimodel-update.json _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -v /etc/ssl/certs:/etc/ssl/certs \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        -e REGION=$REGION \\\n        -e UPDATE_POOL_NAME=$UPDATE_POOL_NAME \\\n        ${DEV_IMAGE} \\\n        ./bin/aks-engine update \\\n        --azure-env ${AZURE_ENV} \\\n        --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n        --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n        --node-pool $nodepool \\\n        --location $REGION \\\n        --resource-group $RESOURCE_GROUP \\\n        --auth-method client_secret \\\n        --client-id ${AZURE_CLIENT_ID} \\\n        --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n      az vmss list -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --query '[].sku' | grep $NODE_VM_UPGRADE_SKU || exit 1\n    fi\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine scale \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --apiserver $API_SERVER \\\n      --node-pool $nodepool \\\n      --new-node-count 1 \\\n      --auth-method client_secret \\\n      --identity-system ${IDENTITY_SYSTEM} \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=false \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_DOWN}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_SCALE_DOWN} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"scale-down\"\nfi\n\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ]; then\n  # modify the master VM SKU to simulate vertical vm scaling via upgrade\n  docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e MASTER_VM_UPGRADE_SKU=$MASTER_VM_UPGRADE_SKU \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"jq --arg sku \\\"$MASTER_VM_UPGRADE_SKU\\\" '. | .properties.masterProfile.vmSize = \\$sku' < _output/$RESOURCE_GROUP/apimodel.json > _output/$RESOURCE_GROUP/apimodel-upgrade.json\" || exit 1\n  docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"mv _output/$RESOURCE_GROUP/apimodel-upgrade.json _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n  for ver_target in $UPGRADE_VERSIONS; do\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine upgrade --force \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --upgrade-version $ver_target \\\n      --vm-timeout 20 \\\n      --auth-method client_secret \\\n      --identity-system ${IDENTITY_SYSTEM}\\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n      -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n      -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n      -e TENANT_ID=${AZURE_TENANT_ID} \\\n      -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n      -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n      -e ORCHESTRATOR=kubernetes \\\n      -e NAME=$RESOURCE_GROUP \\\n      -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n      -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n      -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n      -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n      -e CLEANUP_ON_EXIT=false \\\n      -e REGIONS=$REGION \\\n      -e IS_JENKINS=${IS_JENKINS} \\\n      -e SKIP_LOGS_COLLECTION=${SKIP_LOGS_COLLECTION} \\\n      -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n      -e GINKGO_SKIP=\"${SKIP_AFTER_UPGRADE}\" \\\n      -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n      -e TEST_PVC=\"${TEST_PVC}\" \\\n      -e SKIP_TEST=${SKIP_TESTS_AFTER_UPGRADE} \\\n      -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n      -e API_PROFILE=\"${API_PROFILE}\" \\\n      -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n      -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n      -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n      -e LOCATION=\"${LOCATION}\" \\\n      -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n      -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n      -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n      -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n      -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n      -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n      -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n      -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n      -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n      -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n      -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n      -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n      -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n      -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n      -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n      -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n      -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n      -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n      -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n      -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n      -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n      -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n      ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"upgrade\"\n  done\nfi\n\nif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n  for nodepool in $(jq -r '.properties.agentPoolProfiles[].name' < _output/$RESOURCE_GROUP/apimodel.json); do\n    docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n    -e REGION=$REGION \\\n    ${DEV_IMAGE} \\\n    ./bin/aks-engine scale \\\n    --azure-env ${AZURE_ENV} \\\n    --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n    --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n    --location $REGION \\\n    --resource-group $RESOURCE_GROUP \\\n    --apiserver $API_SERVER \\\n    --node-pool $nodepool \\\n    --new-node-count $NODE_COUNT \\\n    --auth-method client_secret \\\n    --identity-system ${IDENTITY_SYSTEM}\\\n    --client-id ${AZURE_CLIENT_ID} \\\n    --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_ON_EXIT} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=${SKIP_LOGS_COLLECTION} \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_UP}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_SCALE_UP} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"scale-up\"\nfi\n", "num_lines": 758}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsudo chown -R jenkins:jenkins .\n", "num_lines": 4}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nsystemctl status auditd\nRET=$?\nif $ENABLED; then\n  if [ $RET -eq 0 ]; then\n    exit 0\n  else\n    exit 1\n  fi\nelse\n  if [ $RET -ne 0 ]; then\n    exit 0\n  else\n    exit 1\n  fi\nfi\n", "num_lines": 19}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsource /etc/profile.d/CIS.sh\n\nCIS_FILES=\"\n/etc/issue\n/etc/issue.net\n/etc/sysctl.d/60-CIS.conf\n/etc/rsyslog.d/60-CIS.conf\n/etc/security/pwquality.conf\n/etc/pam.d/su\n\"\nfor CIS_FILE in ${CIS_FILES}; do\n    ls -la $CIS_FILE || exit 2\n    [ -s $CIS_FILE ] || exit 1\ndone\n\n# specific file mode validations\nfor filepath in /etc/crontab /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly /etc/cron.d; do\n  stat $filepath | grep 'Access: (0600' || exit 1\ndone\n# validate su configuration\nsudo grep \"auth required pam_wheel.so use_uid\" /etc/pam.d/su\n# validate password lockout config\nsudo grep \"auth required pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900\" /etc/pam.d/common-auth\n# validate password change uniqueness config\nsudo grep \"pam_unix.so obscure use_authtok try_first_pass sha512 remember=5\" /etc/pam.d/common-password\n# validate umask configuration\ntouch test-umask\nstat test-umask | grep 'Access: (0640' || exit 1\nrm -f test-umask\n", "num_lines": 31}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ $(sudo cat /etc/kubernetes/azure.json | jq --arg mode $BACKOFF_MODE '.cloudProviderBackoffMode|contains($mode)') != 'true' ]; then\n    exit 1\nfi\n", "num_lines": 6}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nkubelet_version=$(docker run ${CUSTOM_HYPERKUBE_IMAGE} kubelet --version)\n[[ $(kubelet --version) == \"${kubelet_version}\" ]] || exit 1\n\nkubectl_version=$(docker run ${CUSTOM_HYPERKUBE_IMAGE} kubectl version --client)\n[[ $(kubectl version --client) == \"${kubectl_version}\" ]] || exit 1\n", "num_lines": 10}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nsudo ifconfig -a -v || exit 1\ncat /etc/resolv.conf || exit 1\nset +x\n# validate that all node vms can resolve DNS to all other node vms, including themselves\n# also validate external DNS lookups\n# configurable retries\nsuccess=\"no\"\nretries=${LOOKUP_RETRIES}\nHOSTS=\"${NODE_HOSTNAMES} www.bing.com google.com\"\nfor i in $(seq 1 $retries); do\n  for host in $HOSTS; do\n    set -x\n    addrs=$(dig +short +search +answer ${host})\n    if [ -z \"$addrs\" ]; then\n      success=\"no\"\n      break\n    fi\n    set +x\n    success=\"yes\"\n  done\n  if [[ \"${success}\" == \"yes\" ]]; then\n    break\n  fi\n  if [ $i -eq $retries ]; then\n    exit 1\n  else\n    sleep 10\n  fi\ndone\n\nsuccess=\"no\"\nHOSTS=\"www.bing.com google.com\"\nfor i in $(seq 1 $retries); do\n  for host in $HOSTS; do\n    set -x\n    addrs=$(dig +short +search +answer ${host} @8.8.8.8)\n    if [ -z \"$addrs\" ]; then\n      success=\"no\"\n      break\n    fi\n    set +x\n    success=\"yes\"\n  done\n  if [[ \"${success}\" == \"yes\" ]]; then\n    break\n  fi\n  if [ $i -eq $retries ]; then\n    exit 1\n  else\n    sleep 10\n  fi\ndone\n", "num_lines": 56}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n[ $(findmnt /mnt -no FSTYPE) == \"ext4\" ] || exit 1\nif [[ $MASTER_NODE == \"true\" ]]; then\n  [ $(findmnt /var/lib/etcddisk -no FSTYPE) == \"ext4\" ] || exit 1\nfi\n", "num_lines": 8}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nmodprobe -n -v tipc | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep tipc) ] || exit 1\nmodprobe -n -v dccp | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep dccp) ] || exit 1\nmodprobe -n -v sctp | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep sctp) ] || exit 1\nmodprobe -n -v rds | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep rds) ] || exit 1\nmodprobe -n -v cramfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep cramfs) ] || exit 1\nmodprobe -n -v freevxfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep freevxfs) ] || exit 1\nmodprobe -n -v jffs2 | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep jffs2) ] || exit 1\nmodprobe -n -v hfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep hfs) ] || exit 1\nmodprobe -n -v hfsplus | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep hfsplus) ] || exit 1\n[ -s $(lsmod | grep squashfs) ] || exit 1\n[ -s $(lsmod | grep vfat) ] || exit 1\n", "num_lines": 24}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nIPV4_SEND_REDIRECTS_VALUE=0\nIPV4_ACCEPT_SOURCE_ROUTE_VALUE=0\nIPV4_ACCEPT_REDIRECTS_VALUE=0\nIPV4_SECURE_REDIRECTS_VALUE=0\nIPV4_LOG_MARTIANS_VALUE=1\nIPV4_TCP_RETRIES2_VALUE=8\nIPV6_ACCEPT_RA_VALUE=0\nIPV6_ACCEPT_REDIRECTS_VALUE=0\nKERNEL_PANIC_VALUE=10\nKERNEL_PANIC_ON_OOPS_VALUE=1\nVM_OVERCOMMIT_MEMORY_VALUE=1\nINOTIFY_MAX_USER_WATCHES=1048576\nSOMAXCONN=16384\nTCP_MAX_SYN_BACKLOG=16384\nMESSAGE_COST=40\nMESSAGE_BURST=80\nIPV4_NEIGH_GC_THRESH1=4096\nIPV4_NEIGH_GC_THRESH2=8192\nIPV4_NEIGH_GC_THRESH3=16384\n\nset -x\ngrep $IPV4_SEND_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/send_redirects || exit 1\ngrep $IPV4_SEND_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/send_redirects || exit 1\ngrep $IPV4_ACCEPT_SOURCE_ROUTE_VALUE /proc/sys/net/ipv4/conf/all/accept_source_route || exit 1\ngrep $IPV4_ACCEPT_SOURCE_ROUTE_VALUE /proc/sys/net/ipv4/conf/default/accept_source_route || exit 1\ngrep $IPV4_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/accept_redirects || exit 1\ngrep $IPV4_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/accept_redirects || exit 1\ngrep $IPV4_SECURE_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/secure_redirects || exit 1\ngrep $IPV4_SECURE_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/secure_redirects || exit 1\ngrep $IPV4_LOG_MARTIANS_VALUE /proc/sys/net/ipv4/conf/all/log_martians || exit 1\ngrep $IPV4_LOG_MARTIANS_VALUE /proc/sys/net/ipv4/conf/default/log_martians || exit 1\ngrep $IPV6_ACCEPT_RA_VALUE /proc/sys/net/ipv6/conf/all/accept_ra || exit 1\ngrep $IPV6_ACCEPT_RA_VALUE /proc/sys/net/ipv6/conf/default/accept_ra || exit 1\ngrep $IPV6_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv6/conf/all/accept_redirects || exit 1\ngrep $IPV6_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv6/conf/default/accept_redirects || exit 1\n\n# validate kubelet.service configs\ngrep $IPV4_TCP_RETRIES2_VALUE /proc/sys/net/ipv4/tcp_retries2 || exit 1\ngrep $KERNEL_PANIC_VALUE /proc/sys/kernel/panic || exit 1\ngrep $KERNEL_PANIC_ON_OOPS_VALUE /proc/sys/kernel/panic_on_oops || exit 1\ngrep $VM_OVERCOMMIT_MEMORY_VALUE /proc/sys/vm/overcommit_memory || exit 1\ngrep $INOTIFY_MAX_USER_WATCHES /proc/sys/fs/inotify/max_user_watches || exit 1\ngrep $SOMAXCONN /proc/sys/net/core/somaxconn || exit 1\ngrep $TCP_MAX_SYN_BACKLOG /proc/sys/net/ipv4/tcp_max_syn_backlog || exit 1\ngrep $MESSAGE_COST /proc/sys/net/core/message_cost || exit 1\ngrep $MESSAGE_BURST /proc/sys/net/core/message_burst || exit 1\n\ngrep $IPV4_NEIGH_GC_THRESH1 /proc/sys/net/ipv4/neigh/default/gc_thresh1 || exit 1\ngrep $IPV4_NEIGH_GC_THRESH2 /proc/sys/net/ipv4/neigh/default/gc_thresh2 || exit 1\ngrep $IPV4_NEIGH_GC_THRESH3 /proc/sys/net/ipv4/neigh/default/gc_thresh3 || exit 1\n\n# validate eth0 MTU\nif [ \"$ETH0_MTU\" != \"\" ]; then\n  grep $ETH0_MTU /sys/class/net/eth0/mtu || exit 1\nfi\n", "num_lines": 57}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\n# an invalid password should fail\necho \"tooshort1@\" | sudo pwscore && exit 1\necho \"password123456@J\" | sudo pwscore && exit 1\necho \"passSDWword@@@@J\" | sudo pwscore && exit 1\necho \"passSDWword1111J\" | sudo pwscore && exit 1\necho \"lowerrrr12case@\" | sudo pwscore && exit 1\necho \"UPPERRR12CASE@\" | sudo pwscore && exit 1\n\n# a valid password should succeed\necho \"passSDWword1232rdw#@\" | sudo pwscore || exit 1\n\n# validate password age settings\ngrep 'PASS_MAX_DAYS 90' /etc/login.defs || exit 1\ngrep 'PASS_MIN_DAYS 7' /etc/login.defs || exit 1\ngrep 'INACTIVE=30' /etc/default/useradd || exit 1\n", "num_lines": 20}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nCONFIGS=(\"ClientAliveInterval 120\"\n\"ClientAliveCountMax 3\"\n\"MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com\"\n\"KexAlgorithms curve25519-sha256@libssh.org\"\n\"Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr\"\n\"HostKey /etc/ssh/ssh_host_rsa_key\"\n\"HostKey /etc/ssh/ssh_host_dsa_key\"\n\"HostKey /etc/ssh/ssh_host_ecdsa_key\"\n\"HostKey /etc/ssh/ssh_host_ed25519_key\"\n\"SyslogFacility AUTH\"\n\"LogLevel INFO\"\n\"LoginGraceTime 60\"\n\"PermitRootLogin no\"\n\"PermitUserEnvironment no\"\n\"StrictModes yes\"\n\"PubkeyAuthentication yes\"\n\"IgnoreRhosts yes\"\n\"HostbasedAuthentication no\"\n\"X11Forwarding no\"\n\"MaxAuthTries 4\"\n\"Banner /etc/issue.net\"\n\"AcceptEnv LANG LC_*\"\n\"Subsystem sftp /usr/lib/openssh/sftp-server\"\n\"UsePAM yes\"\n\"UseDNS no\"\n\"GSSAPIAuthentication no\")\n\nfor ((i = 0; i < ${#CONFIGS[@]}; i++))\ndo\n    grep -i \"${CONFIGS[$i]}\" /etc/ssh/sshd_config || exit 1\ndone\n\nCONFIGS=(\"RSAAuthentication yes\"\n\"UsePrivilegeSeparation yes\"\n\"KeyRegenerationInterval 3600\"\n\"ServerKeyBits 1024\"\n\"RhostsRSAAuthentication no\")\n    \nif [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    for ((i = 0; i < ${#CONFIGS[@]}; i++))\n    do\n        sshd -T | grep -i \"${CONFIGS[$i]}\" || exit 1\n    done\nfi", "num_lines": 49}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nMAX_ATTEMPTS=10\nSLEEP_BETWEEN_PHASES=10\n\nwait_systemd() {\n  local attempt=1\n  until sudo systemctl is-active $1; do\n  if ((attempt == MAX_ATTEMPTS)); then\n    exit 1\n  fi\n  sleep \"$((2 ** ATTEMPT++))\"\ndone\n}\n\nservice_started_only_once() {\n  if ! [[ $(sudo journalctl -b -u ${1} | grep -c \": Started \") == 1 ]]; then\n    exit 1\n  fi\n}\n\n# Validate that the monitor services themselves are stable\nservice_started_only_once \"kubelet-monitor\"\nif sudo kill $(pgrep etcd); then\n  service_started_only_once \"etcd-monitor\"\nfi\nservice_started_only_once \"docker-monitor\"\n\n# manually kill kubelet\nsudo kill $(pgrep kubelet)\nsleep $SLEEP_BETWEEN_PHASES\nwait_systemd \"kubelet\" # validate that systemd brought the kubelet service back online\n\nif apt list --installed | grep moby-engine; then\n  CONTAINER_RUNTIME=docker\nelse\n  CONTAINER_RUNTIME=containerd\nfi\nwait_systemd $CONTAINER_RUNTIME\n\n# manually kill the cri\nif [ $CONTAINER_RUNTIME == \"docker\" ]; then\n  sudo kill -9 $(pgrep docker)\nelse\n  sudo kill -9 $(pgrep containerd)\nfi\nsleep $SLEEP_BETWEEN_PHASES\nwait_systemd $CONTAINER_RUNTIME # validate that systemd brought the cri service back online\n\n# if I have an etcd binary that means I'm running etcd (control plane VM)\nif sudo kill $(pgrep etcd); then\n  sleep $SLEEP_BETWEEN_PHASES\n  wait_systemd \"etcd\" # validate that systemd brought the etcd service back online\nfi\nsleep $SLEEP_BETWEEN_PHASES\n\nwait_systemd \"kubelet\" # after all this nonsense let's verify that the kubelet systemd service is online\n", "num_lines": 59}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n    OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  RELEASE=$(grep -oP 'DISTRIB_RELEASE=\\K(\\S+)' /etc/lsb-release)\n  # verify that timesyncd configuration is healthy\n  if [[ $RELEASE == \"16.04\" ]]; then\n    sudo timedatectl status | grep 'Network time on: yes' || exit 1\n    sudo timedatectl status | grep 'NTP synchronized: yes' || exit 1\n  elif [[ $RELEASE == \"20.04\" || $RELEASE == \"18.04\" ]]; then\n    if apt list --installed | grep 'chrony'; then\n      sudo chronyc sources | grep '#* PHC' || exit 1 # Make sure chrony is running and synced with host-based PTP source clock ('#' means local clock and '*' means synced)\n    else\n      sudo ntpstat | grep 'synchronised to NTP server' || exit 1\n    fi\n    sudo timedatectl status | grep 'System clock synchronized: yes' || exit 1\n  fi\nfi\nif [[ $OS == $DEBIAN_OS_NAME ]]; then\n  sudo timedatectl status | grep 'NTP service: active' || exit 1\n  sudo timedatectl status | grep 'System clock synchronized: yes' || exit 1\nfi\n\nsudo timedatectl status | grep 'RTC in local TZ: no' || exit 1\nif ! { [ $OS = $UBUNTU_OS_NAME ]; }; then\n  sudo systemctl status systemd-timesyncd | grep 'Active: active' || exit 1\n  sudo systemctl status systemd-timesyncd | grep 'Status: \"Synchronized to time server' || exit 1\nfi\n", "num_lines": 36}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n    OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\n\nENSURE_NOT_INSTALLED=\"\npostfix\n\"\nfor PACKAGE in ${ENSURE_NOT_INSTALLED}; do\n    apt list --installed | grep -E \"^${PACKAGE}\" && exit 1\ndone\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n    ENSURE_INSTALLED_UBUNTU=\"\nceph-common\ncgroup-lite\nglusterfs-client\n\"\n    for PACKAGE in ${ENSURE_INSTALLED_UBUNTU}; do\n        apt list --installed | grep -E \"^${PACKAGE}\" || exit 1\n    done\nfi\n\nENSURE_INSTALLED=\"\napt-transport-https\nblobfuse\nca-certificates\ncifs-utils\nconntrack\ndbus\nebtables\nethtool\nfuse\ngit\ninit-system-helpers\niproute2\nipset\niptables\njq\nmount\nnfs-common\npigz\nsocat\nutil-linux\nxz-utils\nzip\nhtop\niotop\niftop\nsysstat\n\"\nfor PACKAGE in ${ENSURE_INSTALLED}; do\n    apt list --installed | grep -E \"^${PACKAGE}\" || exit 1\ndone\n", "num_lines": 60}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z \"$RESOURCE_GROUP\" ]; then\n    echo \"must provide a RESOURCE_GROUP env var\"\n    exit 1;\nfi\n\n# TODO: track VMSS in a \"Creating\" state, enforce TTL, if \"Creating TTL\" expires:\n#  1. Check if the \"Creating\" VMSS instance correlates with a running Kubernetes node in the cluster\n#     If so, (1) cordon/drain the node\n#  2. Delete the instance in a stuck \"Creating\" state\n#  3. Wait for the VMSS to achive a \"Succeeded\" ProvisioningState\n#  4. Scale out the VMSS by 1\n\n# Continually look for non-Succeeded VMSS instances\nwhile true; do\n  NUM_VMSS=0\n  NUM_TERMINAL_VMSS=0\n  echo \"$(date)    Starting VMSS Health Remediation loop\"\n  for VMSS in $(az vmss list -g $RESOURCE_GROUP | jq -r '.[] | .name'); do\n    ((NUM_VMSS++))\n    NUM_DELETED_INSTANCES=0\n    VMSS_PROVISIONING_STATE=$(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '.provisioningState')\n    echo $(date)    VMSS $VMSS has a ProvisioningState of $VMSS_PROVISIONING_STATE\n    VMSS_CAPACITY=$(az vmss list -g $RESOURCE_GROUP | jq -r --arg VMSS \"$VMSS\" '.[] | select(.name == $VMSS) | .sku.capacity')\n    echo $(date)    VMSS $VMSS has a current capacity of $VMSS_CAPACITY\n    if [ \"$VMSS_PROVISIONING_STATE\" == \"Succeeded\" ] || [ \"$VMSS_PROVISIONING_STATE\" == \"Failed\" ]; then\n      ((NUM_TERMINAL_VMSS++))\n      HAS_FAILED_STATE_INSTANCE=\"false\"\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[] | select(.provisioningState == \"Failed\") | .name'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo $(date)    Deleting VMSS $VMSS instance $TARGET_VMSS_INSTANCE\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_} --no-wait; then\n          sleep 30\n        else\n          sleep 1\n          ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.name == \"vmssCSE\" and .provisioningState == \"Failed\") | .id' | awk -F'/' '{print $9}'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo $(date)    Deleting VMSS $VMSS instance $TARGET_VMSS_INSTANCE\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then\n           sleep 30\n        else\n           sleep 1\n           ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.publisher == \"Microsoft.AKS\" and .provisioningState != \"Succeeded\" and .provisioningState != \"Creating\" and .provisioningState != \"Deleting\") | .id' | awk -F'/' '{print $9}'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo $(date)    Deleting VMSS $VMSS instance $TARGET_VMSS_INSTANCE\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then\n          sleep 30\n        else\n          sleep 1\n          ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      if [ \"$HAS_FAILED_STATE_INSTANCE\" == \"true\" ]; then\n        echo $(date)    Waiting for $VMSS to reach a terminal ProvisioningState after failed instances were deleted...\n        sleep 30\n        until [[ $(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '. | select(.provisioningState == \"Succeeded\" or .provisioningState == \"Failed\") | .name') ]]; do\n          echo $(date)    Waiting for $VMSS to reach a terminal ProvisioningState after failed instances were deleted...\n          sleep 30\n        done\n        echo $(date)    VMSS $VMSS is in a terminal state after failed instances were deleted!\n      fi\n    fi\n    if [ \"$NUM_DELETED_INSTANCES\" -gt \"0\" ]; then\n      echo $(date)    Instances were deleted from VMSS $VMSS, ensuring that capacity is set to $VMSS_CAPACITY\n      az vmss scale --new-capacity $VMSS_CAPACITY -n $VMSS -g $RESOURCE_GROUP --no-wait;\n    fi\n  done\n  if [ \"$LOOP_FOREVER\" == \"true\" ]; then\n    sleep 150\n  else\n    if [[ \"${NUM_VMSS}\" == \"${NUM_TERMINAL_VMSS}\" ]]; then\n      exit 0\n    fi\n  fi\ndone\n", "num_lines": 83}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -euo pipefail\n\ncd \"$(git rev-parse --show-toplevel)\"\n\nSTD_PATH=src/crypto/ed25519/internal/edwards25519/field\nLOCAL_PATH=curve25519/internal/field\nLAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint)\n\ngit fetch https://go.googlesource.com/go master\n\nif git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then\n    echo \"No changes.\"\nelse\n    NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint)\n    echo \"Applying changes from $LAST_SYNC_REF to $NEW_REF...\"\n    git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \\\n        git apply -3 --directory=$LOCAL_PATH\nfi\n", "num_lines": 20}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 779}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n# Cleanup packer SSH key and machine ID generated for this boot\nrm -f /root/.ssh/authorized_keys\nrm -f /home/packer/.ssh/authorized_keys\nrm -f /etc/machine-id\ntouch /etc/machine-id", "num_lines": 7}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"CLASSIC_SA_CONNECTION_STRING\"\n    \"STORAGE_ACCT_BLOB_URL\"\n    \"VHD_NAME\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nstart_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"-1 day\")\nexpiry_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"+1 year\")\nsas_token=$(az storage container generate-sas --name vhds --permissions lr --connection-string ${CLASSIC_SA_CONNECTION_STRING} --start ${start_date} --expiry ${expiry_date} | tr -d '\"')\nvhd_url=\"${STORAGE_ACCT_BLOB_URL}/${VHD_NAME}?$sas_token\"\n\n# Get verion info from release notes\nRELEASE_NOTES_FILE=release-notes.txt\n\nif [ ! -f \"$RELEASE_NOTES_FILE\" ]; then\n    echo \"Could not fine release notes file!\"\n    exit 1\nfi\n\nwindows_version=$(grep \"OS Version\" < release-notes.txt | cut -d \":\" -f 2 | tr -d \"[:space:]\")\n\ncat <<EOF > windows-vhd-publishing-info.json\n{\n    \"vhd_url\" : \"$vhd_url\",\n    \"windows_version\" : \"$windows_version\"\n}\nEOF\n\ncat windows-vhd-publishing-info.json\n", "num_lines": 40}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nCDIR=$(dirname \"${BASH_SOURCE}\")\n\nSETTINGS_JSON=\"${SETTINGS_JSON:-./settings.json}\"\nSP_JSON=\"${SP_JSON:-./sp.json}\"\nSUBSCRIPTION_ID=\"${SUBSCRIPTION_ID:-$(az account show -o json --query=\"id\" | tr -d '\"')}\"\nCREATE_TIME=\"$(date +%s)\"\nSTORAGE_ACCOUNT_NAME=\"aksimages${CREATE_TIME}${RANDOM}\"\n\n\necho \"Subscription ID: ${SUBSCRIPTION_ID}\"\necho \"Service Principal Path: ${SP_JSON}\"\n\nif [ -a \"${SP_JSON}\" ]; then\n\techo \"Existing credentials file found.\"\n\texit 0\nelif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"Service principal not found! Generating one @ ${SP_JSON}\"\n\taz ad sp create-for-rbac -n aks-images-packer${CREATE_TIME} -o json > ${SP_JSON}\n\tCLIENT_ID=$(jq -r .appId ${SP_JSON})\n\tCLIENT_SECRET=$(jq -r .password ${SP_JSON})\n\tTENANT_ID=$(jq -r .tenant ${SP_JSON})\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n\techo \"creating new storage account ${STORAGE_ACCOUNT_NAME}\"\n\taz storage account create -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME --sku \"Standard_RAGRS\" --tags \"now=${CREATE_TIME}\" --allow-blob-public-access false\n\techo \"creating new container system\"\n\tkey=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $AZURE_RESOURCE_GROUP_NAME | jq -r '.[0].value')\n\taz storage container create --name system --account-key=$key --account-name=$STORAGE_ACCOUNT_NAME\nelse\n\techo \"storage account ${STORAGE_ACCOUNT_NAME} already exists.\"\nfi\n\nif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"CLIENT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${CLIENT_SECRET}\" ]; then\n\techo \"CLIENT_SECRET was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${TENANT_ID}\" ]; then\n\techo \"TENANT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\necho \"storage name: ${STORAGE_ACCOUNT_NAME}\"\n\ncat <<EOF > vhd/packer/settings.json\n{\n  \"subscription_id\":  \"${SUBSCRIPTION_ID}\",\n  \"client_id\": \"${CLIENT_ID}\",\n  \"client_secret\": \"${CLIENT_SECRET}\",\n  \"tenant_id\":      \"${TENANT_ID}\",\n  \"resource_group_name\": \"${AZURE_RESOURCE_GROUP_NAME}\",\n  \"location\": \"${AZURE_LOCATION}\",\n  \"storage_account_name\": \"${STORAGE_ACCOUNT_NAME}\",\n  \"vm_size\": \"${AZURE_VM_SIZE}\",\n  \"create_time\": \"${CREATE_TIME}\"\n}\nEOF\n\ncat vhd/packer/settings.json\n", "num_lines": 69}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_source.sh\nsource /home/packer/packer_source.sh\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\n\necho \"Starting build on \" $(date) > ${VHD_LOGS_FILEPATH}\n\ncopyPackerFiles\n\necho \"\"\necho \"Components downloaded in this VHD build (some of the below components might get deleted during cluster provisioning if they are not needed):\" >> ${VHD_LOGS_FILEPATH}\n\nAUDITD_ENABLED=true\nMS_APT_REPO=packages.microsoft.com\ninstallDeps\ncat << EOF >> ${VHD_LOGS_FILEPATH}\napt packages:\n  - apache2-utils\n  - apt-transport-https\n  - auditd\n  - blobfuse\n  - ca-certificates\n  - ceph-common\n  - cgroup-lite\n  - cifs-utils\n  - conntrack\n  - cracklib-runtime\n  - dkms\n  - dbus\n  - ebtables\n  - ethtool\n  - fuse\n  - gcc\n  - git\n  - glusterfs-client\n  - htop\n  - iftop\n  - init-system-helpers\n  - iotop\n  - iproute2\n  - ipset\n  - iptables\n  - jq\n  - libpam-pwquality\n  - libpwquality-tools\n  - make\n  - mount\n  - nfs-common\n  - pigz\n  - socat\n  - sysstat\n  - traceroute\n  - util-linux\n  - xz-utils\n  - zip\nEOF\nif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"18.04\" ]]; then\n{\n  echo \"  - ntp\"\n  echo \"  - ntpstat\"\n  echo \"  - chrony\"\n} >> ${VHD_LOGS_FILEPATH}\nfi\n\nchmod a-x /etc/update-motd.d/??-{motd-news,release-upgrade}\n\nif [[ ${UBUNTU_RELEASE} == \"20.04\" || ${UBUNTU_RELEASE} == \"18.04\" ]]; then\n  overrideNetworkConfig\nfi\n\ncat << EOF >> ${VHD_LOGS_FILEPATH}\nBinaries:\nEOF\n\napmz_version=\"v0.5.1\"\nensureAPMZ \"${apmz_version}\"\necho \"  - apmz $apmz_version\" >> ${VHD_LOGS_FILEPATH}\n\ninstallBpftrace\necho \"  - bpftrace\" >> ${VHD_LOGS_FILEPATH}\n\nMOBY_VERSION=\"20.10.14\"\nCONTAINERD_VERSION=\"1.5.13\"\ninstallMoby\ninstallRunc\nsystemctl_restart 100 5 30 docker || exit 1\necho \"  - moby v${MOBY_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndownloadGPUDrivers\necho \"  - nvidia-container-runtime\" >> ${VHD_LOGS_FILEPATH}\n\nETCD_VERSION=\"3.3.25\"\nETCD_DOWNLOAD_URL=\"mcr.microsoft.com/oss/etcd-io/\"\ninstallEtcd \"docker\"\necho \"  - etcd v${ETCD_VERSION}\" >> ${VHD_LOGS_FILEPATH}\n\nVNET_CNI_VERSIONS=\"\n1.4.16\n1.4.14\n1.4.13\n\"\nfor VNET_CNI_VERSION in $VNET_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://kubernetesartifacts.azureedge.net/azure-cni/v${VNET_CNI_VERSION}/binaries/azure-vnet-cni-linux-amd64-v${VNET_CNI_VERSION}.tgz\"\n    downloadAzureCNI\n    echo \"  - Azure CNI version ${VNET_CNI_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCNI_PLUGIN_VERSIONS=\"\n0.9.1\n\"\nfor CNI_PLUGIN_VERSION in $CNI_PLUGIN_VERSIONS; do\n    CNI_PLUGINS_URL=\"https://kubernetesartifacts.azureedge.net/cni-plugins/v${CNI_PLUGIN_VERSION}/binaries/cni-plugins-linux-amd64-v${CNI_PLUGIN_VERSION}.tgz\"\n    downloadCNI\n    echo \"  - CNI plugin version ${CNI_PLUGIN_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\ninstallImg\necho \"  - img\" >> ${VHD_LOGS_FILEPATH}\n\nsystemctl status docker --no-pager || exit 1\necho \"Docker images pre-pulled:\" >> ${VHD_LOGS_FILEPATH}\n\nMETRICS_SERVER_VERSIONS=\"\n0.5.2\n\"\nfor METRICS_SERVER_VERSION in ${METRICS_SERVER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/metrics-server:v${METRICS_SERVER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKUBE_ADDON_MANAGER_VERSIONS=\"\n9.1.3\n9.1.5\n\"\nfor KUBE_ADDON_MANAGER_VERSION in ${KUBE_ADDON_MANAGER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/kube-addon-manager:v${KUBE_ADDON_MANAGER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nMCR_PAUSE_VERSIONS=\"3.4.1\"\nfor PAUSE_VERSION in ${MCR_PAUSE_VERSIONS}; do\n    # Pull the arch independent MCR pause image which is built for Linux and Windows\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/pause:${PAUSE_VERSION}\"\n    loadContainerImage \"${CONTAINER_IMAGE}\"\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCLUSTER_AUTOSCALER_VERSIONS=\"\n1.22.1\n\"\nfor CLUSTER_AUTOSCALER_VERSION in ${CLUSTER_AUTOSCALER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/autoscaler/cluster-autoscaler:v${CLUSTER_AUTOSCALER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCORE_DNS_VERSIONS=\"\n1.8.6\n\"\nfor CORE_DNS_VERSION in ${CORE_DNS_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/coredns:${CORE_DNS_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAZURE_CNIIMAGEBASE=\"mcr.microsoft.com/containernetworking\"\nAZURE_NPM_VERSIONS=\"\n1.2.2_hotfix\n\"\nfor AZURE_NPM_VERSION in ${AZURE_NPM_VERSIONS}; do\n    CONTAINER_IMAGE=\"${AZURE_CNIIMAGEBASE}/azure-npm:v${AZURE_NPM_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nNVIDIA_DEVICE_PLUGIN_VERSIONS=\"\n1.0.0-beta6\n\"\nfor NVIDIA_DEVICE_PLUGIN_VERSION in ${NVIDIA_DEVICE_PLUGIN_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/nvidia/k8s-device-plugin:${NVIDIA_DEVICE_PLUGIN_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKV_FLEXVOLUME_VERSIONS=\"0.0.16\"\nfor KV_FLEXVOLUME_VERSION in ${KV_FLEXVOLUME_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/flexvolume/keyvault-flexvolume:v${KV_FLEXVOLUME_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nBLOBFUSE_FLEXVOLUME_VERSIONS=\"1.0.8\"\nfor BLOBFUSE_FLEXVOLUME_VERSION in ${BLOBFUSE_FLEXVOLUME_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/flexvolume/blobfuse-flexvolume:${BLOBFUSE_FLEXVOLUME_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nIP_MASQ_AGENT_VERSIONS=\"\n2.8.0\n\"\nfor IP_MASQ_AGENT_VERSION in ${IP_MASQ_AGENT_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/ip-masq-agent:v${IP_MASQ_AGENT_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKMS_PLUGIN_VERSIONS=\"0.0.10\"\nfor KMS_PLUGIN_VERSION in ${KMS_PLUGIN_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/kms/keyvault:v${KMS_PLUGIN_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nloadContainerImage \"mcr.microsoft.com/oss/busybox/busybox:1.33.1\"\necho \"  - busybox\" >> ${VHD_LOGS_FILEPATH}\n\nK8S_VERSIONS=\"\n1.24.13\n1.23.17\n1.22.17\n1.21.14\n\"\nfor KUBERNETES_VERSION in ${K8S_VERSIONS}; do\n  for component in kube-apiserver kube-controller-manager kube-proxy kube-scheduler; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/${component}:v${KUBERNETES_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n  done\n  KUBE_BINARY_URL=\"https://kubernetesartifacts.azureedge.net/kubernetes/v${KUBERNETES_VERSION}/binaries/kubernetes-node-linux-amd64.tar.gz\"\n  extractKubeBinaries\ndone\n\n# Starting with 1.16 we pull cloud-controller-manager and cloud-node-manager\nCLOUD_MANAGER_VERSIONS=\"\n1.24.0\n1.23.11\n1.1.14\n1.0.18\n\"\nfor CLOUD_MANAGER_VERSION in ${CLOUD_MANAGER_VERSIONS}; do\n  for COMPONENT in azure-cloud-controller-manager azure-cloud-node-manager; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/${COMPONENT}:v${CLOUD_MANAGER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n  done\ndone\n\nAZUREDISK_CSI_VERSIONS=\"\n1.10.0\n\"\nfor AZUREDISK_CSI_VERSION in ${AZUREDISK_CSI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/azuredisk-csi:v${AZUREDISK_CSI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAZUREFILE_CSI_VERSIONS=\"\n1.9.0\n\"\nfor AZUREFILE_CSI_VERSION in ${AZUREFILE_CSI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/azurefile-csi:v${AZUREFILE_CSI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_ATTACHER_VERSIONS=\"\n3.3.0\n\"\nfor CSI_ATTACHER_VERSION in ${CSI_ATTACHER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-attacher:v${CSI_ATTACHER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_NODE_DRIVER_REGISTRAR_VERSIONS=\"\n2.4.0\n\"\nfor CSI_NODE_DRIVER_REGISTRAR_VERSION in ${CSI_NODE_DRIVER_REGISTRAR_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-node-driver-registrar:v${CSI_NODE_DRIVER_REGISTRAR_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_PROVISIONER_VERSIONS=\"\n3.0.0\n\"\nfor CSI_PROVISIONER_VERSION in ${CSI_PROVISIONER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-provisioner:v${CSI_PROVISIONER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nLIVENESSPROBE_VERSIONS=\"\n2.5.0\n\"\nfor LIVENESSPROBE_VERSION in ${LIVENESSPROBE_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/livenessprobe:v${LIVENESSPROBE_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_RESIZER_VERSIONS=\"\n1.3.0\n\"\nfor CSI_RESIZER_VERSION in ${CSI_RESIZER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-resizer:v${CSI_RESIZER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SNAPSHOTTER_VERSIONS=\"\n4.2.1\n\"\nfor CSI_SNAPSHOTTER_VERSION in ${CSI_SNAPSHOTTER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-snapshotter:v${CSI_SNAPSHOTTER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nSNAPSHOT_CONTROLLER_VERSIONS=\"\n4.2.1\n\"\nfor SNAPSHOT_CONTROLLER_VERSION in ${SNAPSHOT_CONTROLLER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/snapshot-controller:v${SNAPSHOT_CONTROLLER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SECRETS_STORE_PROVIDER_AZURE_VERSIONS=\"\n0.0.12\n\"\nfor CSI_SECRETS_STORE_PROVIDER_AZURE_VERSION in ${CSI_SECRETS_STORE_PROVIDER_AZURE_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/azure/secrets-store/provider-azure:${CSI_SECRETS_STORE_PROVIDER_AZURE_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SECRETS_STORE_DRIVER_VERSIONS=\"\n0.0.19\n\"\nfor CSI_SECRETS_STORE_DRIVER_VERSION in ${CSI_SECRETS_STORE_DRIVER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/secrets-store/driver:v${CSI_SECRETS_STORE_DRIVER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAAD_POD_IDENTITY_MIC_VERSIONS=\"\n1.6.1\n\"\nfor AAD_POD_IDENTITY_MIC_VERSION in ${AAD_POD_IDENTITY_MIC_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/aad-pod-identity/mic:${AAD_POD_IDENTITY_MIC_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAAD_POD_IDENTITY_NMI_VERSIONS=\"\n1.6.1\n\"\nfor AAD_POD_IDENTITY_NMI_VERSION in ${AAD_POD_IDENTITY_NMI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/aad-pod-identity/nmi:${AAD_POD_IDENTITY_NMI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCLUSTER_PROPORTIONAL_AUTOSCALER_VERSIONS=\"\n1.8.5\n\"\nfor CLUSTER_PROPORTIONAL_AUTOSCALER_VERSION in ${CLUSTER_PROPORTIONAL_AUTOSCALER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/autoscaler/cluster-proportional-autoscaler:${CLUSTER_PROPORTIONAL_AUTOSCALER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\n# This is to accommodate air-gapped environments, e.g., Azure Stack\nCONTAINER_IMAGE=\"registry:2.7.1\"\nloadContainerImage ${CONTAINER_IMAGE}\necho \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n\ndf -h\n\n# warn at 75% space taken\n[ -s $(df -P | grep '/dev/sda1' | awk '0+$5 >= 75 {print}') ] || echo \"WARNING: 75% of /dev/sda1 is used\" >> ${VHD_LOGS_FILEPATH}\n# error at 95% space taken\n[ -s $(df -P | grep '/dev/sda1' | awk '0+$5 >= 95 {print}') ] || exit 1\n\necho \"Using kernel:\" >> ${VHD_LOGS_FILEPATH}\ntee -a ${VHD_LOGS_FILEPATH} < /proc/version\n{ printf \"Installed apt packages:\\n\"; apt list --installed | grep -v 'Listing...'; } >> ${VHD_LOGS_FILEPATH}\n{\n  echo \"Install completed successfully on \" $(date)\n  echo \"VSTS Build NUMBER: ${BUILD_NUMBER}\"\n  echo \"VSTS Build ID: ${BUILD_ID}\"\n  echo \"Commit: ${COMMIT}\"\n  echo \"Feature flags: ${FEATURE_FLAGS}\"\n} >> ${VHD_LOGS_FILEPATH}\n", "num_lines": 400}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncopyPackerFiles() {\n  SYSCTL_CONFIG_SRC=/home/packer/sysctl-d-60-CIS.conf\n  SYSCTL_CONFIG_DEST=/etc/sysctl.d/60-CIS.conf\n  RSYSLOG_CONFIG_SRC=/home/packer/rsyslog-d-60-CIS.conf\n  RSYSLOG_CONFIG_DEST=/etc/rsyslog.d/60-CIS.conf\n  ETC_ISSUE_CONFIG_SRC=/home/packer/etc-issue\n  ETC_ISSUE_CONFIG_DEST=/etc/issue\n  ETC_ISSUE_NET_CONFIG_SRC=/home/packer/etc-issue.net\n  ETC_ISSUE_NET_CONFIG_DEST=/etc/issue.net\n  SSHD_CONFIG_SRC=/home/packer/sshd_config\n  SSHD_CONFIG_DEST=/etc/ssh/sshd_config\n  MODPROBE_CIS_SRC=/home/packer/modprobe-CIS.conf\n  MODPROBE_CIS_DEST=/etc/modprobe.d/CIS.conf\n  PWQUALITY_CONF_SRC=/home/packer/pwquality-CIS.conf\n  PWQUALITY_CONF_DEST=/etc/security/pwquality.conf\n  PAM_D_SU_SRC=/home/packer/pam-d-su\n  PAM_D_SU_DEST=/etc/pam.d/su\n  PROFILE_D_CIS_SH_SRC=/home/packer/profile-d-cis.sh\n  PROFILE_D_CIS_SH_DEST=/etc/profile.d/CIS.sh\n  LABEL_NODES_SRC=/home/packer/label-nodes.sh\n  LABEL_NODES_DEST=/opt/azure/containers/label-nodes.sh\n  LABEL_NODES_SERVICE_SRC=/home/packer/label-nodes.service\n  LABEL_NODES_SERVICE_DEST=/etc/systemd/system/label-nodes.service\n  CIS_SRC=/home/packer/cis.sh\n  CIS_DEST=/opt/azure/containers/provision_cis.sh\n  APT_PREFERENCES_SRC=/home/packer/apt-preferences\n  APT_PREFERENCES_DEST=/etc/apt/preferences\n  HEALTH_MONITOR_SRC=/home/packer/health-monitor.sh\n  HEALTH_MONITOR_DEST=/usr/local/bin/health-monitor.sh\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC=/home/packer/docker_clear_mount_propagation_flags.conf\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n  GENERATE_PROXY_CERTS_SRC=/home/packer/generateproxycerts.sh\n  GENERATE_PROXY_CERTS_DEST=/etc/kubernetes/generate-proxy-certs.sh\n  COLLECT_LOGS_SRC=/home/packer/collect-logs.sh\n  COLLECT_LOGS_DEST=/opt/azure/containers/collect-logs.sh\n  NOTICE_SRC=/home/packer/NOTICE.txt\n  NOTICE_DEST=/NOTICE.txt\n  if [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    SSHD_CONFIG_SRC=/home/packer/sshd_config_1604\n  fi\n  cpAndMode $SYSCTL_CONFIG_SRC $SYSCTL_CONFIG_DEST 644\n  cpAndMode $RSYSLOG_CONFIG_SRC $RSYSLOG_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_CONFIG_SRC $ETC_ISSUE_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_NET_CONFIG_SRC $ETC_ISSUE_NET_CONFIG_DEST 644\n  cpAndMode $SSHD_CONFIG_SRC $SSHD_CONFIG_DEST 644\n  cpAndMode $MODPROBE_CIS_SRC $MODPROBE_CIS_DEST 644\n  cpAndMode $PWQUALITY_CONF_SRC $PWQUALITY_CONF_DEST 600\n  cpAndMode $PAM_D_SU_SRC $PAM_D_SU_DEST 644\n  cpAndMode $PROFILE_D_CIS_SH_SRC $PROFILE_D_CIS_SH_DEST 755\n  cpAndMode $LABEL_NODES_SRC $LABEL_NODES_DEST 744\n  cpAndMode $LABEL_NODES_SERVICE_SRC $LABEL_NODES_SERVICE_DEST 644\n  cpAndMode $CIS_SRC $CIS_DEST 744\n  cpAndMode $APT_PREFERENCES_SRC $APT_PREFERENCES_DEST 644\n  cpAndMode $HEALTH_MONITOR_SRC $HEALTH_MONITOR_DEST 544\n  cpAndMode $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST 644\n  cpAndMode $GENERATE_PROXY_CERTS_SRC $GENERATE_PROXY_CERTS_DEST 744\n  cpAndMode $COLLECT_LOGS_SRC $COLLECT_LOGS_DEST 744\n  cpAndMode $NOTICE_SRC $NOTICE_DEST 444\n}\n\ncpAndMode() {\n  src=$1; dest=$2; mode=$3\n  DIR=$(dirname \"$dest\") && mkdir -p ${DIR} && cp $src $dest && chmod $mode $dest || exit 113\n}\n", "num_lines": 67}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_ID\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID_TO_CLEANUP\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID_TO_CLEANUP env var\"\n    exit 1;\nfi\n\nif [ -z \"$EXPIRATION_IN_HOURS\" ]; then\n    EXPIRATION_IN_HOURS=2\nfi\n\nif [ -z \"$DRY_RUN\" ]; then\n    echo \"no DRY_RUN env var provided, will default to true\"\n    DRY_RUN=true\nfi\n\nif az login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null; then\n    echo \"Successfully logged in using service principal\"\nelse\n    exit 1\nfi\n\n# set to the sub id we want to cleanup\nif az account set -s $SUBSCRIPTION_ID_TO_CLEANUP; then\n    echo \"Successfully set subscription\"\nelse\n    exit 1\nfi\n\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n\n# clean up Packer resource groups\n\n# find packer resource groups created before our deadline\necho \"Looking for resource groups created over ${EXPIRATION_IN_HOURS} hours ago...\"\nfor resourceGroup in $( az group list | jq --arg dl $deadline '.[] | select(.name | contains(\"packer-Resource-Group\") or contains(\"pkr-Resource-Group\")) | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || \"\"); do\n        echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n        if [[ \"${DRY_RUN}\" = false ]]; then\n            az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n        else\n            echo \"skipping because DRY_RUN is set to true\"\n        fi\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    if [[ \"${DRY_RUN}\" = false ]]; then\n        az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n    else\n            echo \"skipping because DRY_RUN is set to true\"\n    fi\ndone\n\n# cleanup storage accounts. We only want to delete storage accounts created by Packer, NOT the classic storage account that is used by the Marketplace to publish the VHDs as images.\nif [ -z \"$STORAGE_RG\" ]; then\n    echo \"must provide a STORAGE_RG env var\"\n    exit 1;\nfi\n\necho \"Looking for storage accounts in ${STORAGE_RG} created over ${EXPIRATION_IN_HOURS} hours ago...\"\nfor storage_account in $(az storage account list -g $STORAGE_RG | jq --arg dl $deadline '.[] | select(.tags.now < $dl).name' | tr -d '\\\"' || \"\"); do\n    echo \"Will delete storage account ${storage_account} from resource group ${STORAGE_RG}...\"\n    if [[ \"${DRY_RUN}\" = false ]]; then\n        az storage account delete -y -n $storage_account -g $STORAGE_RG || echo \"unable to delete storage account ${storage_account}, will continue...\"\n    else\n            echo \"skipping because DRY_RUN is set to true\"\n    fi\ndone\n", "num_lines": 92}
{"repo_name": "aks-engine", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"SKU_PREFIX\"\n    \"SKU_TEMPLATE_FILE\"\n    \"AZURE_TENANT_ID\"\n    \"AZURE_CLIENT_ID\"\n    \"AZURE_CLIENT_SECRET\"\n    \"PUBLISHER\"\n    \"OFFER\"\n    \"CONTAINER_RUNTIME\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nif [ ! -f \"$SKU_TEMPLATE_FILE\" ]; then\n    echo \"Could not find sku template file: ${SKU_TEMPLATE_FILE}!\"\n    exit 1\nfi\n\n(set -x; ls -lhR artifacts )\n\nVHD_INFO=\"artifacts/vhd/windows-vhd-publishing-info.json\"\n\nif [ ! -f \"$VHD_INFO\" ]; then\n    echo \"Could not find VHD info file: ${VHD_INFO}!\"\n    exit 1\nfi\n\nshort_date=$(date +\"%y%m\")\npretty_date=$(date +\"%b %Y\")\n\nsku_id=\"${SKU_PREFIX}-${short_date}\"\n\necho \"Get access token for use with pub\"\naz login --service-principal -u ${AZURE_CLIENT_ID} -p ${AZURE_CLIENT_SECRET} --tenant ${AZURE_TENANT_ID} --allow-no-subscriptions\ntoken=$(az account get-access-token --resource https://cloudpartner.azure.com --query \"accessToken\" -o tsv)\nexport AZURE_TOKEN=$token\n\necho \"Checking if offer contains SKU: $sku_id\"\n# Check if SKU already exists in offer\nset -x \nhack/tools/bin/pub skus list -p $PUBLISHER -o $OFFER | jq \".[] | .planId\" | tr -d '\"' | tee skus.txt\nset +x\necho \"\"\n\nif grep -q \"^$sku_id$\" skus.txt; then\n    echo \"Offer already has SKU\"\nelse\n    echo \"Creating new SKU\"\n\n    < $SKU_TEMPLATE_FILE sed s/{{ID}}/\"$sku_id\"/ | sed s/{{MONTH-YEAR}}/\"$pretty_date/\" | sed s/{{CONTAINER_RUNTIME}}/\"$CONTAINER_RUNTIME/\" > sku.json\n\n    echo \"\" ; cat sku.json ; echo \"\"\n\n    (set -x ; hack/tools/bin/pub skus put -p $PUBLISHER -o \"$OFFER\" -f sku.json ; echo \"\")\nfi\n\n# Get VHD version info for windows-vhd-publishing-info.json produced by previous pipeline stage\nvhd_url=$(< $VHD_INFO jq -r \".vhd_url\")\nvhd_version=$(< $VHD_INFO jq -r \".windows_version\")\nversion_date=$(date +\"%y%m%d\")\nimage_version=\"${vhd_version}.${version_date}\"\n\n# media name must be under 63 characters\nmedia_name=\"aks-windows-${SKU_PREFIX}-${image_version}\"\nif [ \"${#media_name}\" -ge 63 ]; then\n\techo \"$media_name should be under 63 characters\"\n\texit 1\nfi\n\npublished_date=$(date +\"%m/%d/%Y\")\n\nset -x\nhack/tools/bin/pub versions put corevm -p $PUBLISHER -o $OFFER -s $sku_id --version $image_version --vhd-uri $vhd_url --media-name $media_name --label \"AKS Base Image for Windows\" --desc \"AKS Base Image for Windows\" --published-date \"$published_date\"\nset +x\n", "num_lines": 83}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -x\n\ngroup=$1\nsubscription=$2\nlocation=$3\n\naz group create --name $group --location $3 --subscription $2\n\n# Create role\naz ad sp create-for-rbac --role=\"Contributor\" --scopes=\"/subscriptions/$subscription/resourceGroups/$group\" >~/.kube/$group-sp.json\n# shellcheck disable=SC2002,SC2155\nexport appId=$(cat ~/.kube/$group-sp.json | jq -r .appId)\n# shellcheck disable=SC2002,SC2155\nexport password=$(cat ~/.kube/$group-sp.json | jq -r .password)\n\n# give the sp time to propagate\nsleep 180\n\n# Deploy Cluster\naks-engine-azurestack deploy --subscription-id $subscription --resource-group $group --location $location us --api-model apimodel.json --dns-prefix $group\n\ncp $(pwd)/_output/$group/kubeconfig/kubeconfig.eastus.json ~/.kube/$group.json\n\nsleep 180\n\naks-engine-azurestack addpool --subscription-id $subscription --resource-group $group --location $location us --api-model _output/$group/apimodel.json --agent-pool agentpool.json\n\naz vmss list -g $group --subscription $subscription -o table\n\nKUBECONFIG=~/.kube/$group.json kubectl get nodes\n\n#cleanup\n#az vmss delete -n $(az vmss list -g $group --subscription $subscription -o json | jq .[1].name) -g $group --subscription $subscription --no-wait\n\n#az group delete -g $group --subscription $subscription --no-wait\n", "num_lines": 37}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nKIND= # allowed values \"deployment\" or \"statefulset\"\nNS= # namespace name of the deployment/statefulset, ex: \"default\"\nNAME= # resource name of the deployment/statefulset\nPVC_LIST= # PVCs to migrate, ex: \"pvc1-name pvc2-name\"\nTMP=$(mktemp -d)\n\nmkdir -p ${TMP}/${KIND} ${TMP}/pvc ${TMP}/pv\n\n# Back kind/name, remove ID\nID_PROPS=\".metadata.annotations, .metadata.creationTimestamp, .metadata.generation, .metadata.resourceVersion, .metadata.uid, .metadata.managedFields, .status, .spec.template.metadata.creationTimestamp\"\nif [[ \"${KIND,,}\" == \"statefulset\" ]]; then \n    ID_PROPS=\"${ID_PROPS}, .spec.volumeClaimTemplates[].metadata.creationTimestamp, .spec.volumeClaimTemplates[].status\"\nfi\n\nkubectl get ${KIND}/${NAME} -n ${NS} -o json | \\\n    jq \"del(${ID_PROPS})\" \\\n    > ${TMP}/${KIND}/${NS}-${NAME}.json\n\n# Delete kind/name\nkubectl delete -n ${NS} ${KIND}/${NAME}\n\nfor pvc in ${PVC_LIST}\ndo\n    # Get PV data from PVC\n    PV_NAME=$(kubectl get pvc ${pvc} -o jsonpath='{.spec.volumeName}')\n    PV_DISK_URI=$(kubectl get pv ${PV_NAME} -o jsonpath='{.spec.azureDisk.diskURI}')\n    PV_FS_TYPE=$(kubectl get pv ${PV_NAME} -o jsonpath='{.spec.azureDisk.fSType}')\n\n    # Back PVC, remove ID\n    kubectl get pvc ${pvc} -n ${NS} -o json | \\\n        jq 'del(.metadata.annotations, .metadata.creationTimestamp, .metadata.resourceVersion, .metadata.uid, .status)' \\\n        > ${TMP}/pvc/${NS}-${pvc}.json\n\n    # Back PV, remove ID, remove spec.azureDisk, add spec.csi\n    cat << EOF > ${TMP}/csi-pv.spec\n{\n    \"csi\": {\n        \"driver\": \"disk.csi.azure.com\",\n        \"volumeHandle\": \"${PV_DISK_URI}\",\n        \"fsType\": \"${PV_FS_TYPE}\"\n    }\n}\nEOF\n\n    kubectl get pv ${PV_NAME} -n ${NS} -o json | \\\n        jq 'del(.metadata.annotations, .metadata.creationTimestamp, .metadata.managedFields, .metadata.resourceVersion, .metadata.uid, .status, .spec.claimRef.resourceVersion, .spec.claimRef.uid, .spec.azureDisk)' | \\\n        jq \".spec += $(cat ${TMP}/csi-pv.spec)\" \\\n        > ${TMP}/pv/${NS}-${PV_NAME}.json\n\n    # Retain Azure disk on PV deletion\n    kubectl patch pv ${PV_NAME} -p '{\"spec\":{\"persistentVolumeReclaimPolicy\":\"Retain\"}}'\n\n    # Delete PVC+PV pair\n    kubectl delete -n ${NS} pvc/${pvc}\n    kubectl delete pv/${PV_NAME}\ndone\n\n# Recreate resources\nkubectl apply -f ${TMP}/pv\nif [[ \"${KIND,,}\" == \"deployment\" ]]; then \n    kubectl apply -f ${TMP}/pvc; \nfi\nkubectl apply -f ${TMP}/${KIND}", "num_lines": 65}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Add support for registering host on dns server. Must allow non-secure updates\n\nset -e\n\nDOMAINNAME=$1\n\necho $(date) \" - Starting Script\"\n\ncat > /etc/network/if-up.d/register-dns <<EOFDHCP\n#!/bin/sh\n\n# only execute on the primary nic\nif [ \"\\${IFACE}\" = \"eth0\" ]\nthen\n    ip=\\$(ip address show eth0 | awk '/inet / {print \\$2}' | cut -d/ -f1)\n    host=\\$(hostname -s)\n    nsupdatecmds=/var/tmp/nsupdatecmds\n    echo \"update delete \\${host}.${DOMAINNAME} a\" > \\$nsupdatecmds\n    echo \"update add \\${host}.${DOMAINNAME} 3600 a \\${ip}\" >> \\$nsupdatecmds\n    echo \"send\" >> \\$nsupdatecmds\n\n    nsupdate \\$nsupdatecmds\nfi\nEOFDHCP\n\nchmod 755 /etc/network/if-up.d/register-dns\n\nif ! grep -Fq \"${DOMAINNAME}\" /etc/dhcp/dhclient.conf\nthen\n    echo $(date) \" - Adding domain to dhclient.conf\"\n\n    echo \"supersede domain-name \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\n    echo \"prepend domain-search \\\"${DOMAINNAME}\\\";\" >> /etc/dhcp/dhclient.conf\nfi\n\n# service networking restart\necho $(date) \" - Restarting network\"\nsudo ifdown eth0 && sudo ifup eth0", "num_lines": 39}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script file to run hello-world in bash\n\necho \"hello\"\n", "num_lines": 6}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script file to install the docker hello-world container\n\nset -e\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        if /usr/local/bin/kubectl cluster-info\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        if /usr/bin/docker ps | grep apiserver\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\n# Deploy container\necho $(date) \" - Deploying hello-world container\"\n\nkubectl run hello-world --quiet --image=busybox --restart=OnFailure -- echo \"Hello Kubernetes!\"\n\necho $(date) \" - run kubectl get pods --show-all to list the pods\"\necho $(date) \" - run kubectl logs (passing the pod name gathered from kubectl get pods)\"\necho $(date) \" - Script complete\"\n", "num_lines": 44}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\necho $(date) \" - Starting Script\"\n\necho $(date) \" - Setting kubeconfig\"\nexport KUBECONFIG=/var/lib/kubelet/kubeconfig\n\necho $(date) \" - Waiting for API Server to start\"\nkubernetesStarted=1\nfor i in {1..600}; do\n    if [ -e /usr/local/bin/kubectl ]\n    then\n        if /usr/local/bin/kubectl cluster-info\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    else\n        if /usr/bin/docker ps | grep apiserver\n        then\n            echo \"kubernetes started\"\n            kubernetesStarted=0\n            break\n        fi\n    fi\n    sleep 1\ndone\nif [ $kubernetesStarted -ne 0 ]\nthen\n    echo \"kubernetes did not start\"\n    exit 1\nfi\n\nmaster_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=master --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_master_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning master nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_MASTER=$(master_nodes)\n\n        if [[ -n $FIRST_K8S_MASTER ]]; then\n            echo $(date) \" - kubectl is returning master nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return master nodes in the alotted time\"\n    return 1\n}\n\nagent_nodes() {\n    kubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort | head -n 1\n}\n\nwait_for_agent_nodes() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is kubectl returning agent nodes? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        FIRST_K8S_AGENT=$(agent_nodes)\n\n        if [[ -n $FIRST_K8S_AGENT ]]; then\n            echo $(date) \" - kubectl is returning agent nodes\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - kubectl failed to return agent nodes in the alotted time\"\n    return 1\n}\n\nshould_this_node_run_extension() {\n    FIRST_K8S_MASTER=$(master_nodes)\n    if [[ $FIRST_K8S_MASTER = $(hostname) ]]; then\n        echo $(date) \" - Local node $(hostname) is found to be the first master node $FIRST_K8S_MASTER\"\n        return\n    else\n        FIRST_K8S_AGENT=$(agent_nodes)\n        if [[ $FIRST_K8S_AGENT = $(hostname) ]]; then\n            echo $(date) \" - Local node $(hostname) is found to be the first agent node $FIRST_K8S_AGENT\"\n            return\n        else\n            echo $(date) \" - Local node $(hostname) is not the first master node $FIRST_K8S_MASTER or the first agent node $FIRST_K8S_AGENT\"\n            return 1\n        fi\n    fi\n}\n\nstorageclass_param() {\n\tif kubectl get no -l kubernetes.io/role=agent -l storageprofile=managed --no-headers -o jsonpath=\"{.items[0].metadata.name}\" >/dev/null 2>&1; then\n\t\techo '--set server.persistentVolume.storageClass=managed-standard'\n\tfi\n}\n\nwait_for_tiller() {\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is Helm running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if helm version >/dev/null 2>&1; then\n            echo $(date) \" - Helm is running\"\n            return\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    echo $(date) \" - Helm failed to start in the alotted time\"\n    return 1\n}\n\ninstall_helm() {\n    echo $(date) \" - Downloading helm\"\n    curl https://storage.googleapis.com/kubernetes-helm/helm-v2.6.2-linux-amd64.tar.gz > helm-v2.6.2-linux-amd64.tar.gz\n    tar -zxvf helm-v2.6.2-linux-amd64.tar.gz\n    mv linux-amd64/helm /usr/local/bin/helm\n    echo $(date) \" - Downloading prometheus values\"\n\n    curl \"$1\" > prometheus_values.yaml\n\n    sleep 10\n\n    echo $(date) \" - helm version\"\n    helm version\n    helm init\n\n    echo $(date) \" - helm installed\"\n}\n\ndaemonset_api() {\n    SERVER_VERSION_REGEX=\"Server Version: v([0-9]+)\\.([0-9]+)\\.([0-9]+)$\"\n    K8S_SERVER_VERSION=$(kubectl version --short | grep Server)\n    K8S_SERVER_VERSION_MAJOR=$(echo \"$K8S_SERVER_VERSION\" | sed -r \"s/$SERVER_VERSION_REGEX/\\1/g\")\n    K8S_SERVER_VERSION_MINOR=$(sed -r \"s/$SERVER_VERSION_REGEX/\\2/g\" \"$K8S_SERVER_VERSION\")\n\n    if [[ $K8S_SERVER_VERSION_MAJOR -gt 1 ]]; then\n        echo \"apps/v1\"\n    elif [[ $K8S_SERVER_VERSION_MAJOR -eq 1 ]]; then\n        if [[ $K8S_SERVER_VERSION_MINOR -gt 8 ]]; then\n            echo \"apps/v1\"\n        else\n            echo \"apps/v1beta2\"\n        fi\n    fi\n}\n\ninstall_cadvisor() {\n    echo \"$(date) - Installing cAdvisor\"\n    local NAMESPACE=\"$1\"\n    echo \"$(date) - Using namespace $NAMESPACE\"\n    local CADVISOR_DS_CONFIG_URL=\"$2\"\n    echo \"$(date) - Using cAdvisor config at $CADVISOR_DS_CONFIG_URL\"\n\n    curl -o cadvisor_ds.yml \"$CADVISOR_DS_CONFIG_URL\"\n    DAEMONSET_API=$(daemonset_api)\n    echo \"$(date) - Using DaemonSet api group $DAEMONSET_API\"\n    sed -i 's|DAEMONSET_API|'\"$DAEMONSET_API\"'|g' cadvisor_ds.yml\n    kubectl apply -f ./cadvisor_ds.yml --namespace=$NAMESPACE\n}\n\nupdate_helm() {\n    echo $(date) \" - Updating Helm repositories\"\n    helm repo update\n}\n\ninstall_prometheus() {\n    PROM_RELEASE_NAME=monitoring\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Prometheus Helm chart\"\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        if helm install -f prometheus_values.yaml \\\n            --name $PROM_RELEASE_NAME \\\n            --version 5.1.3 \\\n            --namespace $NAMESPACE stable/prometheus $(storageclass_param); then\n            echo $(date) \" - Helm install successfully completed\"\n            break\n        else\n            echo $(date) \" - Helm install returned a non-zero exit code. Retrying.\"\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n\n    PROM_POD_PREFIX=\"$PROM_RELEASE_NAME-prometheus-server\"\n    DESIRED_POD_STATE=Running\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the prometheus server pod ($PROM_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $PROM_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE; then\n            echo $(date) \" - $PROM_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\ninstall_grafana() {\n    GF_RELEASE_NAME=dashboard\n    NAMESPACE=$1\n\n    echo $(date) \" - Installing the Grafana Helm chart\"\n    helm install \\\n        --name $GF_RELEASE_NAME \\\n        --version 0.8.5 \\\n        --namespace $NAMESPACE stable/grafana $(storageclass_param)\n\n    GF_POD_PREFIX=\"$GF_RELEASE_NAME-grafana\"\n    DESIRED_POD_STATE=Running\n\n    ATTEMPTS=90\n    SLEEP_TIME=10\n\n    ITERATION=0\n    while [[ $ITERATION -lt $ATTEMPTS ]]; do\n        echo $(date) \" - Is the grafana pod ($GF_POD_PREFIX-*) running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n        if kubectl get po -n $NAMESPACE --no-headers |\n            awk '{print $1 \" \" $3}' |\n            grep $GF_POD_PREFIX |\n            grep -q $DESIRED_POD_STATE; then\n            echo $(date) \" - $GF_POD_PREFIX-* is $DESIRED_POD_STATE\"\n            break\n        fi\n\n        ITERATION=$(( $ITERATION + 1 ))\n        sleep $SLEEP_TIME\n    done\n}\n\nensure_k8s_namespace_exists() {\n    NAMESPACE_TO_EXIST=\"$1\"\n\n    if ! kubectl get ns $NAMESPACE_TO_EXIST >/dev/null 2>&1; then\n        echo $(date) \" - Creating namespace $NAMESPACE_TO_EXIST\"\n        kubectl create ns $NAMESPACE_TO_EXIST\n    else\n        echo $(date) \" - Namespace $NAMESPACE_TO_EXIST already exists\"\n    fi\n}\n\nNAMESPACE=default\nRAW_PROMETHEUS_CHART_VALS=\"https://raw.githubusercontent.com/Azure/aks-engine/master/extensions/prometheus-grafana-k8s/v1/prometheus_values.yaml\"\nCADVISOR_CONFIG_URL=\"https://raw.githubusercontent.com/Azure/aks-engine/master/extensions/prometheus-grafana-k8s/v1/cadvisor_daemonset.yml\"\n\n# retrieve and parse extension parameters\nif [[ -n \"$1\" ]]; then\n    IFS=';' read -ra INPUT <<< \"$1\"\n    if [[ -n \"${INPUT[0]}\" ]]; then\n        NAMESPACE=\"${INPUT[0]}\"\n        echo \"$(date) - Custom namespace specified: $NAMESPACE\"\n    fi\n    if [[ -n \"${INPUT[1]}\" ]]; then\n        RAW_PROMETHEUS_CHART_VALS=\"${INPUT[1]}\"\n        echo \"$(date) - Custom prometheus chart values url specified: $RAW_PROMETHEUS_CHART_VALS\"\n    fi\n    if [[ -n \"${INPUT[2]}\" ]]; then\n        CADVISOR_CONFIG_URL=\"${INPUT[2]}\"\n        echo \"$(date) - Custom cAdvisor config url specified: $CADVISOR_CONFIG_URL\"\n    fi\nfi\n\n# this extension should only run on a single node\n# the logic to decide whether or not this current node\n# should run the extension is to alphabetically determine\n# if this local machine is the first in the list of master nodes\n# if it is, then run the extension. if not, exit\nif ! wait_for_master_nodes; then\n    echo $(date) \" - Error while waiting for kubectl to output master nodes. Exiting\"\n    exit 1\nfi\n\nif ! wait_for_agent_nodes; then\n    echo $(date) \" - Error while waiting for kubectl to output agent nodes. Exiting\"\n    exit 1\nfi\n\necho \"$(date) - Dumping out sorted agent nodes\"\nkubectl get no -L kubernetes.io/role -l kubernetes.io/role=agent --no-headers -o jsonpath=\"{.items[*].metadata.name}\" | tr \" \" \"\\n\" | sort\n\nif ! should_this_node_run_extension; then\n    echo $(date) \" - Not the first master node or the first agent node, no longer continuing extension. Exiting\"\n    exit 1\nfi\n\nensure_k8s_namespace_exists $NAMESPACE\n\nK8S_SECRET_NAME=dashboard-grafana\nDS_TYPE=prometheus\nDS_NAME=prometheus1\n\nPROM_URL=http://monitoring-prometheus-server\n\n# When RBAC is enabled, need to grant permission to tiller\nkubectl create clusterrolebinding tiller-cluster-admin --clusterrole=cluster-admin --serviceaccount=kube-system:default\n\ninstall_helm \"$RAW_PROMETHEUS_CHART_VALS\"\nif ! wait_for_tiller; then\n    echo $(date) \" - Tiller did not respond in a timely manner. Exiting\"\n    exit 1\nfi\nupdate_helm\ninstall_cadvisor $NAMESPACE $CADVISOR_CONFIG_URL\ninstall_prometheus $NAMESPACE\ninstall_grafana $NAMESPACE\n\nsleep 5\n\necho $(date) \" - Creating the Prometheus datasource in Grafana\"\nGF_USER_NAME=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-user}\" | base64 --decode)\necho $GF_USER_NAME\nGF_PASSWORD=$(kubectl get secret -n $NAMESPACE $K8S_SECRET_NAME -o jsonpath=\"{.data.grafana-admin-password}\" | base64 --decode)\necho $GF_PASSWORD\nGF_URL=$(kubectl get svc -n $NAMESPACE -l \"app=dashboard-grafana,component=grafana\" -o jsonpath=\"{.items[0].spec.clusterIP}\")\necho $GF_URL\n\necho retrieving current data sources...\nCURRENT_DS_LIST=$(curl -s --user \"$GF_USER_NAME:$GF_PASSWORD\" \"$GF_URL/api/datasources\")\nif echo $CURRENT_DS_LIST | grep -q \"\\\"name\\\":\\\"$DS_NAME\\\"\"; then\n    echo data source $DS_NAME already exists\n    echo $CURRENT_DS_LIST | python -m json.tool\n    exit 0\nfi\n\necho data source $DS_NAME does not exist, creating...\nDS_RAW=$(cat << EOF\n{\n    \"name\": \"$DS_NAME\",\n    \"type\": \"$DS_TYPE\",\n    \"url\": \"$PROM_URL\",\n    \"access\": \"proxy\"\n}\nEOF\n)\n\n\n\nATTEMPTS=90\nSLEEP_TIME=10\n\nITERATION=0\nwhile [[ $ITERATION -lt $ATTEMPTS ]]; do\n    echo $(date) \" - Is the grafana api running? (attempt $(( $ITERATION + 1 )) of $ATTEMPTS)\"\n\n    response=$(curl \\\n        -X POST \\\n        --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n        -H \"Content-Type: application/json\" \\\n        -d \"$DS_RAW\" \\\n        \"$GF_URL/api/datasources\")\n\n    if [[ $response == *\"Datasource added\"* ]]; then\n        echo $(date) \" - Data source added successfully\"\n        break\n    fi\n\n    ITERATION=$(( $ITERATION + 1 ))\n    sleep $SLEEP_TIME\ndone\n\necho $(date) \" - Creating the Kubernetes dashboard in Grafana\"\n\ncat << EOF > sanitize_dashboard.py\n#!/usr/bin/python3\n\nimport fileinput\nimport json\n\ndashboard = json.loads(''.join(fileinput.input()))\ndashboard.pop('__inputs')\ndashboard.pop('__requires')\nprint(json.dumps(dashboard).replace('\\${DS_PROMETHEUS}', 'prometheus1'))\n\nEOF\n\nchmod u+x sanitize_dashboard.py\n\nDB_RAW=$(cat << EOF\n{\n    \"dashboard\": $(curl -sL \"https://grafana.com/api/dashboards/3119/revisions/2/download\" | ./sanitize_dashboard.py),\n    \"overwrite\": false\n}\nEOF\n)\n\ncurl \\\n    -X POST \\\n    --user \"$GF_USER_NAME:$GF_PASSWORD\" \\\n    -H \"Content-Type: application/json\" \\\n    -d \"$DB_RAW\" \\\n    \"$GF_URL/api/dashboards/db\"\n\necho $(date) \" - Script complete\"\n", "num_lines": 429}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nexport WD=/etc/kubernetes/rotate-certs\nexport NEW_CERTS_DIR=${WD}/certs\n\n# copied from cse_helpers.sh, sourcing that file not always works\nsystemctl_restart() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl restart $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\n\nbackup() {\n  if [ ! -d /etc/kubernetes/certs.bak ]; then\n    cp -rp /etc/kubernetes/certs/ /etc/kubernetes/certs.bak\n  fi\n}\n\ncp_certs() {\n  cp -p ${NEW_CERTS_DIR}/etcdpeer* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/etcdclient* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/etcdserver* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/ca.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/client.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/apiserver.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/kubeconfig /home/$(logname)/.kube/config\n\n  rm -f /var/lib/kubelet/pki/kubelet-client-current.pem\n}\n\ncp_proxy() {\n  source /etc/environment\n  local NODE_INDEX\n  NODE_INDEX=$(hostname | tail -c 2)\n  if [[ $NODE_INDEX == 0 ]]; then\n    export OVERRIDE_PROXY_CERTS=\"true\"\n  fi\n  /etc/kubernetes/generate-proxy-certs.sh\n}\n\nagent_certs() {\n  cp -p ${NEW_CERTS_DIR}/ca.* /etc/kubernetes/certs/\n  cp -p ${NEW_CERTS_DIR}/client.* /etc/kubernetes/certs/\n\n  rm -f /var/lib/kubelet/pki/kubelet-client-current.pem\n  sync\n  sleep 5\n  systemctl_restart 10 5 10 kubelet\n}\n\ncleanup() {\n  rm -rf ${WD}\n  rm -rf /etc/kubernetes/certs.bak\n}\n\n\"$@\"\n", "num_lines": 64}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nassignRootPW() {\n  if grep '^root:[!*]:' /etc/shadow; then\n    SECRET=$(openssl rand -base64 37)\n    CMD=\"import crypt; print (crypt.crypt('$SECRET', crypt.mksalt()))\"\n    HASH=$(python3 -c \"$CMD\")\n\n    echo 'root:'$HASH | /usr/sbin/chpasswd -e || exit 112\n  fi\n}\n\nassignFilePermissions() {\n  FILES=\"\n    auth.log\n    alternatives.log\n    cloud-init.log\n    cloud-init-output.log\n    daemon.log\n    dpkg.log\n    kern.log\n    lastlog\n    waagent.log\n    syslog\n    unattended-upgrades/unattended-upgrades.log\n    unattended-upgrades/unattended-upgrades-dpkg.log\n    azure-vnet-ipam.log\n    azure-vnet-telemetry.log\n    azure-cnimonitor.log\n    azure-vnet.log\n    kv-driver.log\n    blobfuse-driver.log\n    blobfuse-flexvol-installer.log\n    landscape/sysinfo.log\n    \"\n  for FILE in ${FILES}; do\n    FILEPATH=\"/var/log/${FILE}\"\n    DIR=$(dirname \"${FILEPATH}\")\n    mkdir -p ${DIR} || exit 112\n    touch ${FILEPATH} || exit 112\n    chmod 640 ${FILEPATH} || exit 112\n  done\n  find /var/log -type f -perm '/o+r' -exec chmod 'g-wx,o-rwx' {} \\;\n  chmod 600 /etc/passwd- || exit 112\n  chmod 600 /etc/shadow- || exit 112\n  chmod 600 /etc/group- || exit 112\n  chmod 644 /etc/default/grub || exit 112\n  for filepath in /etc/crontab /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly /etc/cron.d; do\n    chmod 0600 $filepath || exit 112\n  done\n}\n\nsetPWExpiration() {\n  sed -i \"s|PASS_MAX_DAYS||g\" /etc/login.defs || exit 115\n  grep 'PASS_MAX_DAYS' /etc/login.defs && exit 115\n  sed -i \"s|PASS_MIN_DAYS||g\" /etc/login.defs || exit 115\n  grep 'PASS_MIN_DAYS' /etc/login.defs && exit 115\n  sed -i \"s|INACTIVE=||g\" /etc/default/useradd || exit 115\n  grep 'INACTIVE=' /etc/default/useradd && exit 115\n  echo 'PASS_MAX_DAYS 90' >>/etc/login.defs || exit 115\n  grep 'PASS_MAX_DAYS 90' /etc/login.defs || exit 115\n  echo 'PASS_MIN_DAYS 7' >>/etc/login.defs || exit 115\n  grep 'PASS_MIN_DAYS 7' /etc/login.defs || exit 115\n  echo 'INACTIVE=30' >>/etc/default/useradd || exit 115\n  grep 'INACTIVE=30' /etc/default/useradd || exit 115\n}\n\napplyCIS() {\n  setPWExpiration\n  assignRootPW\n  assignFilePermissions\n}\n\napplyCIS\n\n#EOF\n", "num_lines": 77}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nNODE_INDEX=$(hostname | tail -c 2)\nNODE_NAME=$(hostname)\nKUBECTL=\"/usr/local/bin/kubectl --kubeconfig=/home/$ADMINUSER/.kube/config\"\nAO_DIR=/etc/kubernetes/addons\nPSP_SPEC=$AO_DIR/pod-security-policy.yaml\nAOM_SPEC=/etc/kubernetes/manifests/kube-addon-manager.yaml\nK_LOG=\"journalctl -u kubelet --no-pager\"\n\nsystemctlEnableAndStart() {\n  local ret\n  systemctl_restart 100 5 30 $1\n  ret=$?\n  systemctl status $1 --no-pager -l >/var/log/azure/$1-status.log\n  if [ $ret -ne 0 ]; then\n    return 1\n  fi\n  if ! retrycmd 120 5 25 systemctl enable $1; then\n    return 1\n  fi\n}\nsystemctlEtcd() {\n  for i in $(seq 1 60); do\n    timeout 30 systemctl daemon-reload\n    timeout 30 systemctl restart etcd && break ||\n      if [ $i -eq 60 ]; then\n        return 1\n      else\n        sleep 5\n      fi\n  done\n  if ! retrycmd 120 5 25 systemctl enable etcd; then\n    return 1\n  fi\n}\nconfigureAdminUser(){\n  chage -E -1 -I -1 -m 0 -M 99999 \"${ADMINUSER}\"\n  chage -l \"${ADMINUSER}\"\n}\nconfigureEtcdUser(){\n  useradd -U etcd\n  chage -E -1 -I -1 -m 0 -M 99999 etcd\n  chage -l etcd\n  id etcd\n}\nconfigureSecrets(){\n  local apiserver_key=\"/etc/kubernetes/certs/apiserver.key\" ca_key=\"/etc/kubernetes/certs/ca.key\" etcdserver_key=\"/etc/kubernetes/certs/etcdserver.key\"\n  touch \"${apiserver_key}\"\n  touch \"${ca_key}\"\n  touch \"${etcdserver_key}\"\n  if [[ -z ${COSMOS_URI} ]]; then\n    chown etcd:etcd \"${etcdserver_key}\"\n  fi\n  local etcdclient_key=\"/etc/kubernetes/certs/etcdclient.key\" etcdpeer_key=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.key\"\n  touch \"${etcdclient_key}\"\n  touch \"${etcdpeer_key}\"\n  if [[ -z ${COSMOS_URI} ]]; then\n    chown etcd:etcd \"${etcdpeer_key}\"\n  fi\n  chmod 0600 \"${apiserver_key}\" \"${ca_key}\" \"${etcdserver_key}\" \"${etcdclient_key}\" \"${etcdpeer_key}\"\n  chown root:root \"${apiserver_key}\" \"${ca_key}\" \"${etcdclient_key}\"\n  local etcdserver_crt=\"/etc/kubernetes/certs/etcdserver.crt\" etcdclient_crt=\"/etc/kubernetes/certs/etcdclient.crt\" etcdpeer_crt=\"/etc/kubernetes/certs/etcdpeer${NODE_INDEX}.crt\"\n  touch \"${etcdserver_crt}\"\n  touch \"${etcdclient_crt}\"\n  touch \"${etcdpeer_crt}\"\n  chmod 0644 \"${etcdserver_crt}\" \"${etcdclient_crt}\" \"${etcdpeer_crt}\"\n  chown root:root \"${etcdserver_crt}\" \"${etcdclient_crt}\" \"${etcdpeer_crt}\"\n\n  set +x\n  echo \"${APISERVER_PRIVATE_KEY}\" | base64 --decode >\"${apiserver_key}\"\n  echo \"${CA_PRIVATE_KEY}\" | base64 --decode >\"${ca_key}\"\n  echo \"${ETCD_SERVER_PRIVATE_KEY}\" | base64 --decode >\"${etcdserver_key}\"\n  echo \"${ETCD_CLIENT_PRIVATE_KEY}\" | base64 --decode >\"${etcdclient_key}\"\n  echo \"${ETCD_PEER_KEY}\" | base64 --decode >\"${etcdpeer_key}\"\n  echo \"${ETCD_SERVER_CERTIFICATE}\" | base64 --decode >\"${etcdserver_crt}\"\n  echo \"${ETCD_CLIENT_CERTIFICATE}\" | base64 --decode >\"${etcdclient_crt}\"\n  echo \"${ETCD_PEER_CERT}\" | base64 --decode >\"${etcdpeer_crt}\"\n}\nconfigureEtcd() {\n  set -x\n\n  local ret f=/opt/azure/containers/setup-etcd.sh etcd_peer_url=\"https://${PRIVATE_IP}:2380\"\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_ETCD_CONFIG_FAIL\"}}\n  $f >/opt/azure/containers/setup-etcd.log 2>&1\n  ret=$?\n  if [ $ret -ne 0 ]; then\n    exit $ret\n  fi\n\n  if [[ -z ${ETCDCTL_ENDPOINTS} ]]; then\n    {{/* Variables necessary for etcdctl are not present */}}\n    {{/* Must pull them from /etc/environment */}}\n    for entry in $(cat /etc/environment); do\n      export ${entry}\n    done\n  fi\n\n  chown -R etcd:etcd /var/lib/etcddisk\n  systemctlEtcd || exit {{GetCSEErrorCode \"ERR_ETCD_START_TIMEOUT\"}}\n  for i in $(seq 1 600); do\n    MEMBER=\"$(sudo -E etcdctl member list | grep -E ${NODE_NAME} | cut -d':' -f 1)\"\n    if [ \"$MEMBER\" != \"\" ]; then\n      break\n    else\n      sleep 1\n    fi\n  done\n  retrycmd 120 5 25 sudo -E etcdctl member update $MEMBER ${etcd_peer_url} || exit {{GetCSEErrorCode \"ERR_ETCD_CONFIG_FAIL\"}}\n}\nconfigureChrony() {\n  sed -i \"s/makestep.*/makestep 1.0 -1/g\" /etc/chrony/chrony.conf\n  echo \"refclock PHC /dev/ptp0 poll 3 dpoll -2 offset 0\" >> /etc/chrony/chrony.conf\n}\nensureChrony() {\n  systemctlEnableAndStart chrony || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ndisableSystemdResolved() {\n  {{/* Ignoring systemd-resolved query service but using its resolv.conf file */}}\n  {{/* This is the simplest approach to workaround resolved issues without completely uninstall it */}}\n  [ -f /run/systemd/resolve/resolv.conf ] && sudo ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n}\nensureRPC() {\n  systemctlEnableAndStart rpcbind || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  systemctlEnableAndStart rpc-statd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\nensureAuditD() {\n  if [[ ${AUDITD_ENABLED} == true ]]; then\n    systemctlEnableAndStart auditd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  else\n    apt_get_purge auditd mlocate &\n  fi\n}\nensureCron() {\n  local s=/lib/systemd/system/cron.service\n  if [[ -f ${s} ]]; then\n    if ! grep -q 'Restart=' ${s}; then\n      sed -i 's/\\[Service\\]/[Service]\\nRestart=always/' ${s}\n      systemctlEnableAndStart cron\n    fi\n  fi\n}\ngenerateAggregatedAPICerts() {\n  local f=/etc/kubernetes/generate-proxy-certs.sh\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  $f\n}\nconfigureKubeletServerCert() {\n  local kubeletserver_key=\"/etc/kubernetes/certs/kubeletserver.key\" kubeletserver_crt=\"/etc/kubernetes/certs/kubeletserver.crt\"\n\n  openssl genrsa -out $kubeletserver_key 2048\n  openssl req -new -x509 -days 7300 -key $kubeletserver_key -out $kubeletserver_crt -subj \"/CN=${NODE_NAME}\"\n}\nconfigureK8s() {\n  local client_key=\"/etc/kubernetes/certs/client.key\" apiserver_crt=\"/etc/kubernetes/certs/apiserver.crt\" azure_json=\"/etc/kubernetes/azure.json\"\n  touch \"${client_key}\"\n  chmod 0600 \"${client_key}\"\n  chown root:root \"${client_key}\"\n  if [[ -n ${MASTER_NODE} ]]; then\n    touch \"${apiserver_crt}\"\n    chmod 0644 \"${apiserver_crt}\"\n    chown root:root \"${apiserver_crt}\"\n  fi\n  set +x\n  echo \"${KUBELET_PRIVATE_KEY}\" | base64 --decode >\"${client_key}\"\n  configureKubeletServerCert\n  if [[ -n ${MASTER_NODE} ]]; then\n    echo \"${APISERVER_PUBLIC_KEY}\" | base64 --decode >\"${apiserver_crt}\"\n    if [[ ${ENABLE_AGGREGATED_APIS} == True ]]; then\n      generateAggregatedAPICerts\n    fi\n  else\n    {{- /* If we are a node that does not need azure.json (cloud-init tells us), then return immediately */}}\n    wait_for_file 1 1 /opt/azure/needs_azure.json || return\n  fi\n\n  touch $azure_json\n  chmod 0600 $azure_json\n  chown root:root $azure_json\n  {{/* Perform the required JSON escaping */}}\n  local sp_secret=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\\/\\\\\\\\}\n  sp_secret=${SERVICE_PRINCIPAL_CLIENT_SECRET//\\\"/\\\\\\\"}\n  cat <<EOF >\"${azure_json}\"\n{\n    \"cloud\":\"{{GetTargetEnvironment}}\",\n    \"tenantId\": \"${TENANT_ID}\",\n    \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n    \"aadClientId\": \"${SERVICE_PRINCIPAL_CLIENT_ID}\",\n    \"aadClientSecret\": \"${sp_secret}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${LOCATION}\",\n    \"vmType\": \"${VM_TYPE}\",\n    \"subnetName\": \"${SUBNET}\",\n    \"securityGroupName\": \"${NETWORK_SECURITY_GROUP}\",\n    \"vnetName\": \"${VIRTUAL_NETWORK}\",\n    \"vnetResourceGroup\": \"${VIRTUAL_NETWORK_RESOURCE_GROUP}\",\n    \"routeTableName\": \"${ROUTE_TABLE}\",\n    \"primaryAvailabilitySetName\": \"${PRIMARY_AVAILABILITY_SET}\",\n    \"primaryScaleSetName\": \"${PRIMARY_SCALE_SET}\",\n    \"cloudProviderBackoffMode\": \"${CLOUDPROVIDER_BACKOFF_MODE}\",\n    \"cloudProviderBackoff\": ${CLOUDPROVIDER_BACKOFF},\n    \"cloudProviderBackoffRetries\": ${CLOUDPROVIDER_BACKOFF_RETRIES},\n    \"cloudProviderBackoffExponent\": ${CLOUDPROVIDER_BACKOFF_EXPONENT},\n    \"cloudProviderBackoffDuration\": ${CLOUDPROVIDER_BACKOFF_DURATION},\n    \"cloudProviderBackoffJitter\": ${CLOUDPROVIDER_BACKOFF_JITTER},\n    \"cloudProviderRatelimit\": ${CLOUDPROVIDER_RATELIMIT},\n    \"cloudProviderRateLimitQPS\": ${CLOUDPROVIDER_RATELIMIT_QPS},\n    \"cloudProviderRateLimitBucket\": ${CLOUDPROVIDER_RATELIMIT_BUCKET},\n    \"cloudProviderRatelimitQPSWrite\": ${CLOUDPROVIDER_RATELIMIT_QPS_WRITE},\n    \"cloudProviderRatelimitBucketWrite\": ${CLOUDPROVIDER_RATELIMIT_BUCKET_WRITE},\n    \"useManagedIdentityExtension\": ${USE_MANAGED_IDENTITY_EXTENSION},\n    \"userAssignedIdentityID\": \"${USER_ASSIGNED_IDENTITY_ID}\",\n    \"useInstanceMetadata\": ${USE_INSTANCE_METADATA},\n    \"loadBalancerSku\": \"${LOAD_BALANCER_SKU}\",\n    \"disableOutboundSNAT\": ${LOAD_BALANCER_DISABLE_OUTBOUND_SNAT},\n    \"excludeMasterFromStandardLB\": ${EXCLUDE_MASTER_FROM_STANDARD_LB},\n    \"providerVaultName\": \"${KMS_PROVIDER_VAULT_NAME}\",\n    \"maximumLoadBalancerRuleCount\": ${MAXIMUM_LOADBALANCER_RULE_COUNT},\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\",\n    \"enableMultipleStandardLoadBalancers\": ${ENABLE_MULTIPLE_STANDARD_LOAD_BALANCERS},\n    \"tags\": \"${TAGS}\"\n}\nEOF\n  set -x\n  if [[ ${CLOUDPROVIDER_BACKOFF_MODE} == \"v2\" ]]; then\n    sed -i \"/cloudProviderBackoffExponent/d\" $azure_json\n    sed -i \"/cloudProviderBackoffJitter/d\" $azure_json\n  fi\n}\n\ninstallNetworkPlugin() {\n{{- if IsAzureCNI}}\n  installAzureCNI\n{{end}}\n  installCNI\n  rm -rf $CNI_DOWNLOADS_DIR &\n}\ninstallCNI() {\n  CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/}\n  if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n    downloadCNI\n  fi\n  mkdir -p $CNI_BIN_DIR\n  tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n  chown -R root:root $CNI_BIN_DIR\n  chmod -R 755 $CNI_BIN_DIR\n}\n{{- if IsAzureCNI}}\ninstallAzureCNI() {\n  CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/}\n  if [[ ! -f \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ]]; then\n    downloadAzureCNI\n  fi\n  mkdir -p $CNI_CONFIG_DIR\n  chown -R root:root $CNI_CONFIG_DIR\n  chmod 755 $CNI_CONFIG_DIR\n  mkdir -p $CNI_BIN_DIR\n  tar -xzf \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" -C $CNI_BIN_DIR\n}\n{{end}}\nconfigureCNI() {\n  {{/* needed for the iptables rules to work on bridges */}}\n  retrycmd 120 5 25 modprobe br_netfilter || exit {{GetCSEErrorCode \"ERR_MODPROBE_FAIL\"}}\n  echo -n \"br_netfilter\" >/etc/modules-load.d/br_netfilter.conf\n  configureAzureCNI\n  {{if HasCiliumNetworkPlugin}}\n  systemctl enable sys-fs-bpf.mount\n  systemctl restart sys-fs-bpf.mount\n  touch /var/run/reboot-required\n  {{end}}\n{{- if IsAzureStackCloud}}\n  if [[ ${NETWORK_PLUGIN} == \"azure\" ]]; then\n    {{/* set environment to mas when using Azure CNI on Azure Stack */}}\n    {{/* shellcheck disable=SC2002,SC2005 */}}\n    echo $(cat \"$CNI_CONFIG_DIR/10-azure.conflist\" | jq '.plugins[0].ipam.environment = \"mas\"') >\"$CNI_CONFIG_DIR/10-azure.conflist\"\n  fi\n{{end}}\n}\nconfigureAzureCNI() {\n  local tmpDir=$(mktemp -d \"$(pwd)/XXX\")\n  if [[ \"${NETWORK_PLUGIN}\" == \"azure\" ]]; then\n    mv $CNI_BIN_DIR/10-azure.conflist $CNI_CONFIG_DIR/\n    chmod 600 $CNI_CONFIG_DIR/10-azure.conflist\n{{- if IsIPv6DualStackFeatureEnabled}}\n    jq '.plugins[0].ipv6Mode=\"ipv6nat\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n    mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n{{- end}}\n    if [[ {{GetKubeProxyMode}} == \"ipvs\" ]]; then\n      serviceCidrs={{GetServiceCidr}}\n      jq --arg serviceCidrs $serviceCidrs '.plugins[0]+={serviceCidrs: $serviceCidrs}' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n    fi\n    if [[ \"${NETWORK_MODE}\" == \"bridge\" ]]; then\n      jq '.plugins[0].mode=\"bridge\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      jq '.plugins[0].bridge=\"azure0\"' \"$tmpDir/tmp\" > $tmpDir/tmp2\n      mv $tmpDir/tmp2 $CNI_CONFIG_DIR/10-azure.conflist\n    else\n      jq '.plugins[0].mode=\"transparent\"' \"$CNI_CONFIG_DIR/10-azure.conflist\" > $tmpDir/tmp\n      mv $tmpDir/tmp $CNI_CONFIG_DIR/10-azure.conflist\n    fi\n    /sbin/ebtables -t nat --list\n  fi\n  rm -Rf $tmpDir\n}\nenableCRISystemdMonitor() {\n  wait_for_file 1200 1 /etc/systemd/system/docker-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart docker-monitor || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{- if NeedsContainerd}}\ninstallContainerd() {\n  removeMoby\n  local v\n  v=$(containerd -version | cut -d \" \" -f 3 | sed 's|v||')\n  if [[ $v != \"${CONTAINERD_VERSION}\"* ]]; then\n    os_lower=$(echo ${OS} | tr '[:upper:]' '[:lower:]')\n    if [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n      url_path=\"${os_lower}/${UBUNTU_RELEASE}/multiarch/prod\"\n    elif [[ ${OS} == \"${DEBIAN_OS_NAME}\" ]]; then\n      url_path=\"${os_lower}/${UBUNTU_RELEASE}/prod\"\n    else\n      exit 25\n    fi\n    removeContainerd\n    apt_get_update || exit 99\n    apt_get_install 20 30 120 moby-runc moby-containerd=${CONTAINERD_VERSION}* --allow-downgrades || exit 27\n  fi\n}\nensureContainerd() {\n  wait_for_file 1200 1 /etc/systemd/system/containerd.service.d/exec_start.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/containerd/config.toml || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/containerd.service.d/kubereserved-slice.conf|| exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- end}}\n  systemctlEnableAndStart containerd || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n  enableCRISystemdMonitor\n}\n{{end}}\n{{- if IsDockerContainerRuntime}}\nensureDocker() {\n  wait_for_file 1200 1 /etc/systemd/system/docker.service.d/exec_start.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  usermod -aG docker ${ADMINUSER}\n  if [[ $OS != $FLATCAR_OS_NAME ]]; then\n    wait_for_file 1200 1 /etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  fi\n  {{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/docker.service.d/kubereserved-slice.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  {{- end}}\n  local daemon_json=/etc/docker/daemon.json\n  for i in $(seq 1 1200); do\n    if [ -s $daemon_json ]; then\n      jq '.' <$daemon_json && break\n    fi\n    if [ $i -eq 1200 ]; then\n      exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    else\n      sleep 1\n    fi\n  done\n  systemctlEnableAndStart docker || exit {{GetCSEErrorCode \"ERR_DOCKER_START_FAIL\"}}\n  enableCRISystemdMonitor\n}\n{{end}}\n{{- if IsIPv6Enabled}}\nensureDHCPv6() {\n  if [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    wait_for_file 3600 1 {{GetDHCPv6ServiceCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    wait_for_file 3600 1 {{GetDHCPv6ConfigCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    systemctlEnableAndStart dhcpv6 || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n    retrycmd 120 5 25 modprobe ip6_tables || exit {{GetCSEErrorCode \"ERR_MODPROBE_FAIL\"}}\n  fi\n}\n{{end}}\n{{- if EnableEncryptionWithExternalKms}}\nensureKMSKeyvaultKey() {\n    wait_for_file 3600 1 {{GetKMSKeyvaultKeyServiceCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    wait_for_file 3600 1 {{GetKMSKeyvaultKeyCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    systemctlEnableAndStart kms-keyvault-key || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{end}}\nensureKubelet() {\n  wait_for_file 1200 1 /etc/sysctl.d/11-aks-engine.conf || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  sysctl_reload 10 5 120 || exit {{GetCSEErrorCode \"ERR_SYSCTL_RELOAD\"}}\n  wait_for_file 1200 1 /etc/default/kubelet || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /var/lib/kubelet/kubeconfig || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  if [[ -n ${MASTER_NODE} ]]; then\n{{- if IsMasterVirtualMachineScaleSets}}\n    sed -i \"s|<SERVERIP>|https://$PRIVATE_IP:443|g\" \"/var/lib/kubelet/kubeconfig\" || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{- end}}\n    local f=/etc/kubernetes/manifests/kube-apiserver.yaml\n    wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n    sed -i \"s|<advertiseAddr>|$PRIVATE_IP|g\" $f\n  fi\n  wait_for_file 1200 1 /opt/azure/containers/kubelet.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n{{- if HasKubeReservedCgroup}}\n  wait_for_file 1200 1 /etc/systemd/system/{{- GetKubeReservedCgroup -}}.slice || exit {{GetCSEErrorCode \"ERR_KUBERESERVED_SLICE_SETUP_FAIL\"}}\n  wait_for_file 1200 1 /etc/systemd/system/kubelet.service.d/kubereserved-slice.conf || exit {{GetCSEErrorCode \"ERR_KUBELET_SLICE_SETUP_FAIL\"}}\n{{- end}}\n  if [[ -n ${MASTER_NODE} ]]; then\n    systemctlEnableAndStart kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  else\n{{- if not RunUnattendedUpgradesOnBootstrap}}\n    systemctlEnableAndStart kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{else}}\n    systemctl_enable 100 5 30 kubelet || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n{{- end}}\n  fi\n{{- if HasKubeletHealthZPort}}\n  wait_for_file 1200 1 /etc/systemd/system/kubelet-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  if [[ -n ${MASTER_NODE} ]]; then\n    systemctlEnableAndStart kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  else\n  {{- if not RunUnattendedUpgradesOnBootstrap}}\n    systemctlEnableAndStart kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  {{else}}\n    systemctl_enable 100 5 30 kubelet-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\n  {{- end}}\n  fi\n{{- end}}\nif [[ -n ${MASTER_NODE} ]]; then\n  wait_for_file 1200 1 /etc/systemd/system/apiserver-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart apiserver-monitor || exit {{GetCSEErrorCode \"ERR_KUBELET_START_FAIL\"}}\nfi\n}\n\nensureKubeAddonManager() {\n  local kam_pod=kube-addon-manager-${HOSTNAME}\n  {{/* This empty directory clears an addon-manager warning  */}}\n  mkdir -p /etc/kubernetes/admission-controls\n  {{/* Wait 30 sec for kube-addon-manager to become Ready */}}\n  if ! retrycmd 6 5 30 ${KUBECTL} wait --for=condition=Ready --timeout=5s po ${kam_pod} -n kube-system; then\n    {{/* Restart kubelet if kube-addon-manager is not Ready after timeout */}}\n    systemctl_restart 3 5 30 kubelet\n  fi\n  {{/* Wait 5 mins for kube-addon-manager to become Ready */}}\n  if ! retrycmd 60 5 30 ${KUBECTL} wait --for=condition=Ready --timeout=5s po ${kam_pod} -n kube-system; then\n    {{/* Restart kubelet if kube-addon-manager is not Ready after 5 mins */}}\n    systemctl_restart 3 5 30 kubelet\n    {{/* Wait 5 more mins for kube-addon-manager to become Ready, and then return failure if not */}}\n    retrycmd 60 5 30 ${KUBECTL} wait --for=condition=Ready --timeout=5s po ${kam_pod} -n kube-system || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $K_LOG\n  fi\n}\n\nensureAddons() {\n  local kam_pod=kube-addon-manager-${HOSTNAME}\n{{- if IsDashboardAddonEnabled}} {{/* Note: dashboard addon is deprecated */}}\n  retrycmd 120 5 30 $KUBECTL get namespace kubernetes-dashboard || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $K_LOG\n{{- end}}\n{{- if IsAzurePolicyAddonEnabled}}\n  retrycmd 120 5 30 $KUBECTL get namespace gatekeeper-system || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $K_LOG\n{{- end}}\n{{- if and (not HasCustomPodSecurityPolicy) IsPodSecurityPolicyAddonEnabled}}\n  retrycmd 120 5 30 $KUBECTL get podsecuritypolicy privileged restricted || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $K_LOG\n{{- end}}\n  replaceAddonsInit\n  rm -Rf ${AO_DIR}/init\n  ensureKubeAddonManager\n  {{/* Manually delete any kube-addon-manager pods that point to the init directory */}}\n  for initPod in $(${KUBECTL} get pod ${kam_pod} -n kube-system -o json | jq -r '.items[] | select(.spec.containers[0].env[] | select(.value==\"/etc/kubernetes/addons/init\")) | select(.status.phase==\"Running\") .metadata.name'); do\n    retrycmd 120 5 30 ${KUBECTL} delete pod ${kam_pod} -n kube-system --force --grace-period 0 || exit_cse {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}} $K_LOG\n  done\n  {{if HasCiliumNetworkPolicy}}\n  while [ ! -f /etc/cni/net.d/05-cilium.conf ]; do\n    sleep 3\n  done\n  {{end}}\n  {{if HasAntreaNetworkPolicy}}\n  if [[ \"${NETWORK_PLUGIN}\" = \"azure\" ]]; then\n    while ! $(grep -sq \"antrea\" $CNI_CONFIG_DIR/10-azure.conflist); do\n      sleep 3\n    done\n  else\n    while [ ! -f $CNI_CONFIG_DIR/10-antrea.conflist ]; do\n      sleep 3\n    done\n  fi\n  {{end}}\n  {{if HasFlannelNetworkPlugin}}\n  while [ ! -f /etc/cni/net.d/10-flannel.conf ]; do\n    sleep 3\n  done\n  {{end}}\n}\nreplaceAddonsInit() {\n  wait_for_file 1200 1 $AOM_SPEC || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  cp $AOM_SPEC /tmp/kube-addon-manager.yaml || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  sed -i \"s|${AO_DIR}/init|${AO_DIR}|g\" /tmp/kube-addon-manager.yaml || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  mv /tmp/kube-addon-manager.yaml $AOM_SPEC || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n}\nensureLabelNodes() {\n  wait_for_file 1200 1 /opt/azure/containers/label-nodes.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/label-nodes.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart label-nodes || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{- if IsAADPodIdentityAddonEnabled}}\nensureTaints() {\n  wait_for_file 1200 1 /opt/azure/containers/untaint-nodes.sh || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/untaint-nodes.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart untaint-nodes || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\n{{end}}\nensureJournal() {\n  {\n    echo \"Storage=persistent\"\n    echo \"SystemMaxUse=1G\"\n    echo \"RuntimeMaxUse=1G\"\n    echo \"ForwardToSyslog=yes\"\n  } >>/etc/systemd/journald.conf\n  systemctlEnableAndStart systemd-journald || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ninstallKubeletAndKubectl() {\n  local binPath=/usr/local/bin\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    binPath=/opt/bin\n  fi\n  if [[ ! -f \"${binPath}/kubectl-${KUBERNETES_VERSION}\" ]] || [[ -n \"${CUSTOM_HYPERKUBE_IMAGE}\" ]] || [[ -n \"${KUBE_BINARY_URL}\" ]]; then\n    if version_gte ${KUBERNETES_VERSION} 1.17; then\n      extractKubeBinaries\n    else\n      if [[ $CONTAINER_RUNTIME == \"docker\" ]]; then\n        extractHyperkube \"docker\"\n      else\n        extractHyperkube \"img\"\n      fi\n    fi\n  fi\n  mv \"${binPath}/kubelet-${KUBERNETES_VERSION}\" \"${binPath}/kubelet\"\n  mv \"${binPath}/kubectl-${KUBERNETES_VERSION}\" \"${binPath}/kubectl\"\n  chmod a+x ${binPath}/kubelet ${binPath}/kubectl\n  rm -rf ${binPath}/kubelet-* ${binPath}/kubectl-* /home/hyperkube-downloads &\n}\nensureK8sControlPlane() {\n  if [ \"$NO_OUTBOUND\" = \"true\" ]; then\n    return\n  fi\n  retrycmd 120 5 25 $KUBECTL 2>/dev/null cluster-info || exit_cse {{GetCSEErrorCode \"ERR_K8S_RUNNING_TIMEOUT\"}} $K_LOG\n}\n{{- if IsAzurePolicyAddonEnabled}}\nensureLabelExclusionForAzurePolicyAddon() {\n  retrycmd 120 5 25 $KUBECTL label ns kube-system control-plane=controller-manager --overwrite 2>/dev/null || exit_cse {{GetCSEErrorCode \"ERR_K8S_RUNNING_TIMEOUT\"}} $K_LOG\n}\n{{end}}\nensureEtcd() {\n  local etcd_client_url=\"https://${PRIVATE_IP}:2379\"\n  retrycmd 120 5 25 curl --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/etcdclient.crt --key /etc/kubernetes/certs/etcdclient.key ${etcd_client_url}/v2/machines || exit {{GetCSEErrorCode \"ERR_ETCD_RUNNING_TIMEOUT\"}}\n  wait_for_file 1200 1 /etc/systemd/system/etcd-monitor.service || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  systemctlEnableAndStart etcd-monitor || exit {{GetCSEErrorCode \"ERR_SYSTEMCTL_START_FAIL\"}}\n}\ncreateKubeManifestDir() {\n  mkdir -p /etc/kubernetes/manifests\n}\nwriteKubeConfig() {\n  local d=/home/$ADMINUSER/.kube\n  local f=$d/config\n{{- if HasBlockOutboundInternet}}\n  local server=https://localhost\n{{else}}\n  local server=$KUBECONFIG_SERVER\n{{- end}}\n  mkdir -p $d\n  touch $f\n  chown $ADMINUSER:$ADMINUSER $d $f\n  chmod 700 $d\n  chmod 600 $f\n  set +x\n  echo \"\n---\napiVersion: v1\nclusters:\n- cluster:\n    certificate-authority-data: \\\"$CA_CERTIFICATE\\\"\n    server: $server\n  name: \\\"$MASTER_FQDN\\\"\ncontexts:\n- context:\n    cluster: \\\"$MASTER_FQDN\\\"\n    user: \\\"$MASTER_FQDN-admin\\\"\n  name: \\\"$MASTER_FQDN\\\"\ncurrent-context: \\\"$MASTER_FQDN\\\"\nkind: Config\nusers:\n- name: \\\"$MASTER_FQDN-admin\\\"\n  user:\n    client-certificate-data: \\\"$KUBECONFIG_CERTIFICATE\\\"\n    client-key-data: \\\"$KUBECONFIG_KEY\\\"\n\" >$f\n  set -x\n}\n{{- if IsClusterAutoscalerAddonEnabled}}\nconfigClusterAutoscalerAddon() {\n  local f=$AO_DIR/cluster-autoscaler.yaml\n  wait_for_file 1200 1 $f || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  sed -i \"s|<clientID>|$(echo $SERVICE_PRINCIPAL_CLIENT_ID | base64)|g\" $f\n  sed -i \"s|<clientSec>|$(echo $SERVICE_PRINCIPAL_CLIENT_SECRET | base64)|g\" $f\n  sed -i \"s|<subID>|$(echo $SUBSCRIPTION_ID | base64)|g\" $f\n  sed -i \"s|<tenantID>|$(echo $TENANT_ID | base64)|g\" $f\n  sed -i \"s|<rg>|$(echo $RESOURCE_GROUP | base64)|g\" $f\n}\n{{end}}\n{{- if IsAzurePolicyAddonEnabled}}\nconfigAzurePolicyAddon() {\n  sed -i \"s|<resourceId>|/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP|g\" $AO_DIR/azure-policy-deployment.yaml\n}\n{{end}}\n\nconfigAddons() {\n  echo \"configAddons placeholder, keep\"\n  {{if IsClusterAutoscalerAddonEnabled}}\n  if [[ ${CLUSTER_AUTOSCALER_ADDON} == true ]]; then\n    configClusterAutoscalerAddon\n  fi\n  {{end}}\n  {{if IsAzurePolicyAddonEnabled}}\n  configAzurePolicyAddon\n  {{end}}\n  {{- if and (not HasCustomPodSecurityPolicy) IsPodSecurityPolicyAddonEnabled}}\n  wait_for_file 1200 1 $PSP_SPEC || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  mkdir -p $AO_DIR/init && cp $PSP_SPEC $AO_DIR/init/ || exit {{GetCSEErrorCode \"ERR_ADDONS_START_FAIL\"}}\n  {{- end}}\n}\n{{- if and HasNSeriesSKU IsNvidiaDevicePluginAddonEnabled}}\n{{- /* installNvidiaDrivers is idempotent, it will uninstall itself if it is already installed, and then install anew */}}\ninstallNvidiaDrivers() {\n  local d=\"/var/lib/dkms/nvidia/${GPU_DV}\" k log_file=\"/var/log/nvidia-installer-$(date +%s).log\"\n  k=$(uname -r)\n  if [ -d $d ]; then\n    dkms remove -m nvidia -v $GPU_DV -k $k\n  fi\n  sh $GPU_DEST/nvidia-drivers-$GPU_DV -s -k=$k --log-file-name=$log_file -a --no-drm --dkms --utility-prefix=\"${GPU_DEST}\" --opengl-prefix=\"${GPU_DEST}\"\n}\nconfigGPUDrivers() {\n  rmmod nouveau\n  echo blacklist nouveau >>/etc/modprobe.d/blacklist.conf\n  retrycmd_no_stats 120 5 25 update-initramfs -u || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  wait_for_apt_locks\n  for apt_package in $NVIDIA_PACKAGES; do\n    dpkg -i ${PERMANENT_CACHE_DIR}${apt_package}* || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  done\n  dpkg -i ${PERMANENT_CACHE_DIR}nvidia-container-runtime* || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  mkdir -p $GPU_DEST/lib64 $GPU_DEST/overlay-workdir\n  retrycmd 120 5 25 mount -t overlay -o lowerdir=/usr/lib/x86_64-linux-gnu,upperdir=${GPU_DEST}/lib64,workdir=${GPU_DEST}/overlay-workdir none /usr/lib/x86_64-linux-gnu || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_CONFIG\"}}\n  export -f installNvidiaDrivers\n  retrycmd 3 1 600 bash -c installNvidiaDrivers || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  mv ${GPU_DEST}/bin/* /usr/bin\n  echo \"${GPU_DEST}/lib64\" >/etc/ld.so.conf.d/nvidia.conf\n  retrycmd 120 5 25 ldconfig || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  umount -l /usr/lib/x86_64-linux-gnu\n  retrycmd 120 5 25 nvidia-modprobe -u -c0 || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  retrycmd 120 5 25 nvidia-smi || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  retrycmd 120 5 25 ldconfig || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n  rm -Rf ${PERMANENT_CACHE_DIR}\n}\nensureGPUDrivers() {\n  configGPUDrivers\n  systemctlEnableAndStart nvidia-modprobe || exit {{GetCSEErrorCode \"ERR_GPU_DRIVERS_START_FAIL\"}}\n}\n{{end}}\n{{- if HasDCSeriesSKU}}\ninstallSGXDrivers() {\n  [[ $UBUNTU_RELEASE == \"18.04\" || $UBUNTU_RELEASE == \"20.04\" ]] || exit 92\n\n  local packages=\"make gcc dkms\" oe_dir=\"/opt/azure/containers/oe\"\n  wait_for_apt_locks\n  retrycmd 30 5 3600 apt-get -y install \"$packages\" || exit 90\n  rm -rf ${oe_dir}\n  mkdir -p ${oe_dir}\n  pushd ${oe_dir} || exit\n  retrycmd 10 10 120 curl -fsSL -O \"https://download.01.org/intel-sgx/latest/version.xml\" || exit 90\n  dcap_version=\"$(grep dcap version.xml | grep -o -E \"[.0-9]+\")\"\n  sgx_driver_folder_url=\"https://download.01.org/intel-sgx/sgx-dcap/$dcap_version/linux\"\n  retrycmd 10 10 120 curl -fsSL -O \"$sgx_driver_folder_url/SHA256SUM_dcap_$dcap_version.cfg\" || exit 90\n  matched_line=\"$(grep \"distro/ubuntuServer$UBUNTU_RELEASE/sgx_linux_x64_driver_.*bin\" SHA256SUM_dcap_$dcap_version.cfg)\"\n  read -ra tmp_array <<<\"$matched_line\"\n  sgx_driver_sha256sum_expected=\"${tmp_array[0]}\"\n  sgx_driver_remote_path=\"${tmp_array[1]}\"\n  sgx_driver_url=\"${sgx_driver_folder_url}/${sgx_driver_remote_path}\"\n  sgx_driver=$(basename \"$sgx_driver_url\")\n\n  retrycmd 10 10 120 curl -fsSL -O \"${sgx_driver_url}\" || exit 90\n  read -ra tmp_array <<<\"$(sha256sum ./\"$sgx_driver\")\"\n  sgx_driver_sha256sum_real=\"${tmp_array[0]}\"\n  [[ $sgx_driver_sha256sum_real == \"$sgx_driver_sha256sum_expected\" ]] || exit 93\n\n  chmod a+x ./\"${sgx_driver}\"\n  if ! ./\"${sgx_driver}\"; then\n    popd || exit\n    exit 91\n  fi\n  popd || exit\n  rm -rf ${oe_dir}\n}\n{{end}}\n{{- if HasVHDDistroNodes}}\ncleanUpContainerImages() {\n  {{- if NeedsContainerd}}\n  docker rmi -f $(docker images -a -q) &\n  {{else}}\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${ETCD_VERSION}$|${ETCD_VERSION}-|${ETCD_VERSION}_\" | grep 'etcd') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-proxy') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-controller-manager') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-apiserver') &\n  docker rmi $(docker images --format '{{OpenBraces}}.Repository{{CloseBraces}}:{{OpenBraces}}.Tag{{CloseBraces}}' | grep -vE \"${KUBERNETES_VERSION}$|${KUBERNETES_VERSION}-|${KUBERNETES_VERSION}_\" | grep 'kube-scheduler') &\n  ctr -n=k8s.io image rm $(ctr -n=k8s.io images ls -q) &\n  {{- end}}\n}\ncleanUpGPUDrivers() {\n  rm -Rf $GPU_DEST\n  rm -f /etc/apt/sources.list.d/nvidia-docker.list\n  apt-key del $(apt-key list | grep NVIDIA -B 1 | head -n 1 | cut -d \"/\" -f 2 | cut -d \" \" -f 1)\n}\ncleanUpContainerd() {\n  rm -Rf $CONTAINERD_DOWNLOADS_DIR\n}\n{{end}}\nremoveEtcd() {\n  rm -rf /usr/bin/etcd\n}\nexit_cse() {\n  local exit_code=$1\n  shift\n  $@ >> {{GetLinuxCSELogPath}} &\n  exit $exit_code\n}\n#EOF\n", "num_lines": 724}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n{{- if IsCustomCloudProfile}}\n  {{- if not IsAzureStackCloud}}\nensureCustomCloudRootCertificates() {\n    CUSTOM_CLOUD_CERTS=\"{{GetCustomCloudRootCertificates}}\"\n    KCM_FILE=/etc/kubernetes/manifests/kube-controller-manager.yaml\n\n    if [ ! -z $CUSTOM_CLOUD_CERTS ]; then\n        # Replace placeholder for ssl binding\n        if [ -f $KCM_FILE ]; then\n            sed -i \"s|<volumessl>|- name: ssl\\n      hostPath:\\n        path: \\\\/etc\\\\/ssl\\\\/certs|g\" $KCM_FILE\n            sed -i \"s|<volumeMountssl>|- name: ssl\\n          mountPath: \\\\/etc\\\\/ssl\\\\/certs\\n          readOnly: true|g\" $KCM_FILE\n        fi\n\n        local i=1\n        for cert in $(echo $CUSTOM_CLOUD_CERTS | tr ',' '\\n')\n        do\n            echo $cert | base64 -d > \"/usr/local/share/ca-certificates/customCloudRootCertificate$i.crt\"\n            ((i++))\n        done\n\n        update-ca-certificates\n    else\n        if [ -f $KCM_FILE ]; then\n            # remove the placeholder for ssl binding\n            sed -i \"/<volumessl>/d\" $KCM_FILE\n            sed -i \"/<volumeMountssl>/d\" $KCM_FILE\n        fi\n    fi\n}\n\nensureCustomCloudSourcesList() {\n    CUSTOM_CLOUD_LIST=\"{{GetCustomCloudSourcesList}}\"\n\n    if [ ! -z $CUSTOM_CLOUD_LIST ]; then\n        # Just in case, let's take a back up before we overwrite\n        cp /etc/apt/sources.list /etc/apt/sources.list.backup\n        echo $CUSTOM_CLOUD_LIST | base64 -d > /etc/apt/sources.list\n    fi\n}\n  {{end}}\n\nconfigureK8sCustomCloud() {\n  {{- if IsAzureStackCloud}}\n  local azure_json_path=\"/etc/kubernetes/azure.json\"\n  export -f ensureAzureStackCertificates\n  retrycmd 60 10 30 bash -c ensureAzureStackCertificates\n  set +x\n  # When AUTHENTICATION_METHOD is client_certificate, the certificate is stored into key valut,\n  # And SERVICE_PRINCIPAL_CLIENT_SECRET will be the following json payload with based64 encode\n  #{\n  #    \"data\": \"$pfxAsBase64EncodedString\",\n  #    \"dataType\" :\"pfx\",\n  #    \"password\": \"$password\"\n  #}\n  if [[ ${AUTHENTICATION_METHOD,,} == \"client_certificate\" ]]; then\n    SPN_DECODED=$(echo ${SERVICE_PRINCIPAL_CLIENT_SECRET} | base64 --decode)\n    SPN_CERT=$(echo $SPN_DECODED | jq .data)\n    SPN_PWD=$(echo $SPN_DECODED | jq .password)\n\n    # trim the starting and ending \"\n    SPN_CERT=${SPN_CERT#'\"'}\n    SPN_CERT=${SPN_CERT%'\"'}\n\n    SPN_PWD=${SPN_PWD#'\"'}\n    SPN_PWD=${SPN_PWD%'\"'}\n\n    K8S_CLIENT_CERT=\"$(dirname ${azure_json_path})/k8s_auth_certificate.pfx\"\n    echo $SPN_CERT | base64 --decode >$K8S_CLIENT_CERT\n    # shellcheck disable=SC2002,SC2005\n    echo $(cat \"${azure_json_path}\" |\n      jq --arg K8S_CLIENT_CERT ${K8S_CLIENT_CERT} '. + {aadClientCertPath:($K8S_CLIENT_CERT)}' |\n      jq --arg SPN_PWD ${SPN_PWD} '. + {aadClientCertPassword:($SPN_PWD)}' |\n      jq 'del(.aadClientSecret)') >${azure_json_path}\n  fi\n\n  if [[ ${IDENTITY_SYSTEM,,} == \"adfs\" ]]; then\n    # update the tenent id for ADFS environment.\n    # shellcheck disable=SC2002,SC2005\n    echo $(cat \"${azure_json_path}\" | jq '.tenantId = \"adfs\"') >${azure_json_path}\n  fi\n  set -x\n\n  {{/* Log whether the custom login endpoint is reachable to simplify troubleshooting. */}}\n  {{/* CSE will finish successfully but kubelet will error out if not reachable. */}}\n  LOGIN_ENDPOINT=$(jq -r .activeDirectoryEndpoint /etc/kubernetes/azurestackcloud.json)\n  LOGIN_ENDPOINT=${LOGIN_ENDPOINT#'https://'}\n  LOGIN_ENDPOINT=${LOGIN_ENDPOINT%'/'}\n  timeout 10 nc -vz ${LOGIN_ENDPOINT} 443 \\\n  && echo \"login endpoint reachable: ${LOGIN_ENDPOINT}\" \\\n  || echo \"error: login endpoint not reachable: ${LOGIN_ENDPOINT}\"\n\n  {{- if not IsAzureCNI}}\n  # Decrease eth0 MTU to mitigate Azure Stack's NRP issue\n  echo \"iface eth0 inet dhcp\" | sudo tee -a /etc/network/interfaces\n  echo \"    post-up /sbin/ifconfig eth0 mtu 1350\" | sudo tee -a /etc/network/interfaces\n  ifconfig eth0 mtu 1350\n  {{end}}\n\n  {{else}}\n  ensureCustomCloudRootCertificates\n  ensureCustomCloudSourcesList\n  {{end}}\n}\n{{end}}\n\n{{- if IsAzureStackCloud}}\nensureAzureStackCertificates() {\n  ENV_JSON=\"/etc/kubernetes/azurestackcloud.json\"\n  ARM_EP=$(jq .resourceManagerEndpoint $ENV_JSON | tr -d '\"')\n  META_EP=\"$ARM_EP/metadata/endpoints?api-version=2015-01-01\"\n  curl $META_EP\n  RET=$?\n  KCM_FILE=/etc/kubernetes/manifests/kube-controller-manager.yaml\n  if [ $RET != 0 ]; then\n    if [ -f $KCM_FILE ]; then\n      sed -i \"s|<volumessl>|- name: ssl\\n      hostPath:\\n        path: \\\\/etc\\\\/ssl\\\\/certs|g\" $KCM_FILE\n      sed -i \"s|<volumeMountssl>|- name: ssl\\n          mountPath: \\\\/etc\\\\/ssl\\\\/certs\\n          readOnly: true|g\" $KCM_FILE\n    fi\n    cp /var/lib/waagent/Certificates.pem /usr/local/share/ca-certificates/azsCertificate.crt\n    update-ca-certificates\n  else\n    if [ -f $KCM_FILE ]; then\n      sed -i \"/<volumessl>/d\" $KCM_FILE\n      sed -i \"/<volumeMountssl>/d\" $KCM_FILE\n    fi\n  fi\n  curl $META_EP\n  exit $?\n}\n{{end}}\n#EOF\n", "num_lines": 134}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nconfigureAzureStackInterfaces() {\n  NETWORK_INTERFACES_FILE=\"/etc/kubernetes/network_interfaces.json\"\n  AZURE_CNI_CONFIG_FILE=\"/etc/kubernetes/interfaces.json\"\n  AZURESTACK_ENVIRONMENT_JSON_PATH=\"/etc/kubernetes/azurestackcloud.json\"\n  SERVICE_MANAGEMENT_ENDPOINT=$(jq -r '.serviceManagementEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  ACTIVE_DIRECTORY_ENDPOINT=$(jq -r '.activeDirectoryEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  RESOURCE_MANAGER_ENDPOINT=$(jq -r '.resourceManagerEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n  TOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}${TENANT_ID}/oauth2/token\"\n\n  if [[ ${IDENTITY_SYSTEM,,} == \"adfs\" ]]; then\n    TOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}adfs/oauth2/token\"\n  fi\n\n  set +x\n\n  TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X POST \\\n    -H \"Content-Type: application/x-www-form-urlencoded\" \\\n    -d \"grant_type=client_credentials\" \\\n    -d \"client_id=$SERVICE_PRINCIPAL_CLIENT_ID\" \\\n    --data-urlencode \"client_secret=$SERVICE_PRINCIPAL_CLIENT_SECRET\" \\\n    --data-urlencode \"resource=$SERVICE_MANAGEMENT_ENDPOINT\" \\\n    ${TOKEN_URL} | jq '.access_token' | xargs)\n\n  if [[ -z $TOKEN ]]; then\n    echo \"Error generating token for Azure Resource Manager\"\n    exit 120\n  fi\n\n  curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X GET \\\n    -H \"Authorization: Bearer $TOKEN\" \\\n    -H \"Content-Type: application/json\" \\\n    \"${RESOURCE_MANAGER_ENDPOINT}subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.Network/networkInterfaces?api-version=$NETWORK_API_VERSION\" >${NETWORK_INTERFACES_FILE}\n\n  if [[ ! -s ${NETWORK_INTERFACES_FILE} ]]; then\n    echo \"Error fetching network interface configuration for node\"\n    exit 121\n  fi\n\n  echo \"Generating Azure CNI interface file\"\n\n  mapfile -t local_interfaces < <(cat /sys/class/net/*/address | tr -d : | sed 's/.*/\\U&/g')\n\n  SDN_INTERFACES=$(jq \".value | map(select(.properties != null) | select(.properties.macAddress != null) | select(.properties.macAddress | inside(\\\"${local_interfaces[*]}\\\"))) | map(select((.properties.ipConfigurations | length) > 0))\" ${NETWORK_INTERFACES_FILE})\n\n  if [[ -z $SDN_INTERFACES ]]; then\n      echo \"Error extracting the SDN interfaces from the network interfaces file\"\n      exit 123\n  fi\n\n  AZURE_CNI_CONFIG=$(echo ${SDN_INTERFACES} | jq \"{Interfaces: [.[] | {MacAddress: .properties.macAddress, IsPrimary: .properties.primary, IPSubnets: [{Prefix: .properties.ipConfigurations[0].properties.subnet.id, IPAddresses: .properties.ipConfigurations | [.[] | {Address: .properties.privateIPAddress, IsPrimary: .properties.primary}]}]}]}\")\n\n  mapfile -t SUBNET_IDS < <(echo ${SDN_INTERFACES} | jq '[.[].properties.ipConfigurations[0].properties.subnet.id] | unique | .[]' -r)\n\n  for SUBNET_ID in \"${SUBNET_IDS[@]}\"; do\n    SUBNET_PREFIX=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X GET \\\n      -H \"Authorization: Bearer $TOKEN\" \\\n      -H \"Content-Type: application/json\" \\\n      \"${RESOURCE_MANAGER_ENDPOINT}${SUBNET_ID:1}?api-version=$NETWORK_API_VERSION\" |\n      jq '.properties.addressPrefix' -r)\n\n    if [[ -z $SUBNET_PREFIX ]]; then\n      echo \"Error fetching the subnet address prefix for a subnet ID\"\n      exit 122\n    fi\n\n    # shellcheck disable=SC2001\n    AZURE_CNI_CONFIG=$(echo ${AZURE_CNI_CONFIG} | sed \"s|$SUBNET_ID|$SUBNET_PREFIX|g\")\n  done\n\n  echo ${AZURE_CNI_CONFIG} >${AZURE_CNI_CONFIG_FILE}\n\n  chmod 0444 ${AZURE_CNI_CONFIG_FILE}\n\n  set -x\n}\n#EOF\n", "num_lines": 79}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n  OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\nif [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n  UBUNTU_RELEASE=$(lsb_release -r -s)\nfi\nDOCKER=/usr/bin/docker\nif [[ $UBUNTU_RELEASE == \"18.04\" ]]; then\n  export GPU_DV=470.103.01\nelif [[ $UBUNTU_RELEASE == \"20.04\" ]]; then\n  export GPU_DV=470.103.01\nelse\n  export GPU_DV=418.40.04\nfi\nexport GPU_DEST=/usr/local/nvidia\nPRIVATE_IP=$( (ip -br -4 addr show eth0 || ip -br -4 addr show azure0) | grep -Po '\\d+\\.\\d+\\.\\d+\\.\\d+')\nif ! [[ $(echo -n \"$PRIVATE_IP\" | grep -c '^') == 1 ]]; then\n  PRIVATE_IP=$(hostname -i)\nfi\nexport PRIVATE_IP\nAPT_CACHE_DIR=/var/cache/apt/archives/\nPERMANENT_CACHE_DIR=/root/aptcache/\n\nconfigure_prerequisites() {\n  ip_forward_path=/proc/sys/net/ipv4/ip_forward\n  ip_forward_setting=\"net.ipv4.ip_forward=0\"\n  sysctl_conf=/etc/sysctl.conf\n  if ! grep -qE \"^1$\" ${ip_forward_path}; then\n    echo 1 >${ip_forward_path}\n  fi\n  if grep -qE \"${ip_forward_setting}\" ${sysctl_conf}; then\n    sed -i '/^net.ipv4.ip_forward=0$/d' ${sysctl_conf}\n  fi\n}\n\naptmarkWALinuxAgent() {\n  wait_for_apt_locks\n  retrycmd 120 5 25 apt-mark $1 walinuxagent ||\n    if [[ $1 == \"hold\" ]]; then\n      exit 7\n    elif [[ $1 == \"unhold\" ]]; then\n      exit 8\n    fi\n}\n\nretrycmd() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    timeout $timeout ${@} && break ||\n      if [ $i -eq $retries ]; then\n        echo Executed \\\"$@\\\" $i times\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n  echo Executed \\\"$@\\\" $i times\n}\nretrycmd_no_stats() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    timeout $timeout ${@} && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nretrycmd_get_tarball() {\n  tar_retries=$1; wait_sleep=$2; tarball=$3; url=$4\n  echo \"${tar_retries} retries\"\n  for i in $(seq 1 $tar_retries); do\n    tar -tzf $tarball && break ||\n      if [ $i -eq $tar_retries ]; then\n        return 1\n      else\n        timeout 60 curl -fsSL $url -o $tarball\n        sleep $wait_sleep\n      fi\n  done\n}\nretrycmd_get_executable() {\n  retries=$1; wait_sleep=$2; filepath=$3; url=$4; validation_args=$5\n  echo \"${retries} retries\"\n  for i in $(seq 1 $retries); do\n    $filepath $validation_args && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        timeout 30 curl -fsSL $url -o $filepath\n        chmod +x $filepath\n        sleep $wait_sleep\n      fi\n  done\n}\nwait_for_file() {\n  retries=$1; wait_sleep=$2; filepath=$3\n  paved=/opt/azure/cloud-init-files.paved\n  grep -Fq \"${filepath}\" $paved && return 0\n  for i in $(seq 1 $retries); do\n    grep -Fq '#EOF' $filepath && break\n    if [ $i -eq $retries ]; then\n      return 1\n    else\n      sleep $wait_sleep\n    fi\n  done\n  sed -i \"/#EOF/d\" $filepath\n  echo $filepath >>$paved\n}\nwait_for_apt_locks() {\n  while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n    echo 'Waiting for release of apt locks'\n    sleep 3\n  done\n}\napt_get_update() {\n  retries=10\n  apt_update_output=/tmp/apt-get-update.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    ! (apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") &&\n      cat $apt_update_output && break ||\n      cat $apt_update_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get update $i times\n}\napt_get_download() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  local ret=0\n  pushd $APT_CACHE_DIR || return 1\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks; apt-get -o Dpkg::Options::=--force-confold download -y \"${@}\" && break\n    if [ $i -eq $retries ]; then ret=1; else sleep $wait_sleep; fi\n  done\n  popd || return 1\n  return $ret\n}\ndpkg_install() {\n  retries=$1; wait_sleep=$2; shift && shift;\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks; dpkg -i \"${1}\" && break; apt-get update --fix-missing; do_apt_get_install -f && break\n    if [ $i -eq $retries ]; then return 1; fi; sleep $wait_sleep\n  done\n}\ndo_apt_get_install() {\n  dpkg --configure -a --force-confdef; DEBIAN_FRONTEND=noninteractive apt-get install -o Dpkg::Options::=\"--force-confold\" --no-install-recommends -y ${@}\n}\napt_get_install() {\n  retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    do_apt_get_install ${@} && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n        apt_get_update\n      fi\n  done\n  echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times\n}\napt_get_purge() {\n  retries=20; wait_sleep=30; timeout=120\n  for package in $@; do\n    if apt list --installed | grep $package; then\n      for i in $(seq 1 $retries); do\n        wait_for_apt_locks\n        export DEBIAN_FRONTEND=noninteractive\n        dpkg --configure -a --force-confdef\n        apt-get purge -o Dpkg::Options::=\"--force-confold\" -y $package && break ||\n          if [ $i -eq $retries ]; then\n            return 1\n          else\n            sleep $wait_sleep\n          fi\n      done\n    fi\n  done\n  echo Executed apt-get purge -y \\\"$package\\\" $i times\n}\napt_get_dist_upgrade() {\n  retries=10\n  apt_dist_upgrade_output=/tmp/apt-get-dist-upgrade.out\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    export DEBIAN_FRONTEND=noninteractive\n    dpkg --configure -a --force-confdef\n    apt-get -f -y install\n    apt-mark showhold\n    ! (apt-get dist-upgrade -y 2>&1 | tee $apt_dist_upgrade_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\") && \\\n    cat $apt_dist_upgrade_output && break || \\\n    cat $apt_dist_upgrade_output\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed apt-get dist-upgrade $i times\n}\nunattended_upgrade() {\n  retries=10\n  for i in $(seq 1 $retries); do\n    wait_for_apt_locks\n    /usr/bin/unattended-upgrade && break ||\n    if [ $i -eq $retries ]; then\n      return 1\n    else sleep 5\n    fi\n  done\n  echo Executed unattended-upgrade $i times\n}\nsystemctl_restart() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl restart $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsystemctl_enable() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl enable $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsystemctl_stop() {\n  retries=$1; wait_sleep=$2; timeout=$3 svcname=$4\n  for i in $(seq 1 $retries); do\n    timeout $timeout systemctl daemon-reload\n    timeout $timeout systemctl stop $svcname && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nsysctl_reload() {\n  retries=$1; wait_sleep=$2; timeout=$3\n  for i in $(seq 1 $retries); do\n    timeout $timeout sysctl --system && break ||\n      if [ $i -eq $retries ]; then\n        return 1\n      else\n        sleep $wait_sleep\n      fi\n  done\n}\nversion_gte() {\n  test \"$(printf '%s\\n' \"$@\" | sort -rV | head -n 1)\" == \"$1\"\n}\n#HELPERSEOF\n", "num_lines": 278}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCNI_CONFIG_DIR=\"/etc/cni/net.d\"\nCNI_BIN_DIR=\"/opt/cni/bin\"\nCNI_DOWNLOADS_DIR=\"/opt/cni/downloads\"\nCONTAINERD_DOWNLOADS_DIR=\"/opt/containerd/downloads\"\nAPMZ_DOWNLOADS_DIR=\"/opt/apmz/downloads\"\nUBUNTU_RELEASE=$(lsb_release -r -s)\nUBUNTU_CODENAME=$(lsb_release -c -s)\nNVIDIA_PACKAGES=\"libnvidia-container1 libnvidia-container-tools nvidia-container-toolkit\"\nNVIDIA_CONTAINER_TOOLKIT_VER=1.6.0\nNVIDIA_RUNTIME_VER=3.6.0\n\ndisableSshd() {\n  systemctl_stop 20 5 10 sshd || exit 3\n  retrycmd 120 5 25 systemctl disable sshd || exit 3\n}\ndisableTimeSyncd() {\n  systemctl_stop 20 5 10 systemd-timesyncd || exit 3\n  retrycmd 120 5 25 systemctl disable systemd-timesyncd || exit 3\n}\ninstallEtcd() {\n  local  v\n  v=$(etcd --version | grep \"etcd Version\" | cut -d \":\" -f 2 | tr -d '[:space:]')\n  if [[ $v != \"${ETCD_VERSION}\" ]]; then\n    local cli_tool=$1 path=\"/usr/bin\" image=${ETCD_DOWNLOAD_URL}etcd:v${ETCD_VERSION}\n    pullContainerImage $cli_tool ${image}\n    removeEtcd\n    if [[ $cli_tool == \"docker\" ]]; then\n      mkdir -p \"$path\"\n      docker run --rm --entrypoint cat ${image} /usr/local/bin/etcd >\"$path/etcd\"\n      docker run --rm --entrypoint cat ${image} /usr/local/bin/etcdctl >\"$path/etcdctl\"\n    else\n      tmpdir=/root/etcd${RANDOM}\n      img unpack -o ${tmpdir} ${image}\n      mv ${tmpdir}/usr/local/bin/etcd ${tmpdir}/usr/local/bin/etcdctl ${path}\n      rm -rf ${tmpdir}\n    fi\n    chmod a+x \"$path/etcd\" \"$path/etcdctl\"\n  fi\n}\ninstallDeps() {\n  packages=\"apt-transport-https blobfuse=1.4.5 ca-certificates cifs-utils conntrack cracklib-runtime dbus dkms ebtables ethtool fuse gcc git htop iftop init-system-helpers iotop iproute2 ipset iptables jq libpam-pwquality libpwquality-tools linux-headers-$(uname -r) make mount net-tools nfs-common pigz socat sysstat traceroute util-linux xz-utils zip\"\n  if [[ ${OS} == \"${UBUNTU_OS_NAME}\" ]]; then\n    retrycmd_no_stats 120 5 25 curl -fsSL ${MS_APT_REPO}/config/ubuntu/${UBUNTU_RELEASE}/packages-microsoft-prod.deb >/tmp/packages-microsoft-prod.deb || exit 42\n    retrycmd 60 5 10 dpkg -i /tmp/packages-microsoft-prod.deb || exit 43\n    retrycmd_no_stats 120 5 25 curl ${MS_APT_REPO}/config/ubuntu/${UBUNTU_RELEASE}/prod.list >/tmp/microsoft-prod.list || exit 25\n    retrycmd 10 5 10 cp /tmp/microsoft-prod.list /etc/apt/sources.list.d/ || exit 25\n    retrycmd_no_stats 120 5 25 curl ${MS_APT_REPO}/keys/microsoft.asc | gpg --dearmor >/tmp/microsoft.gpg || exit 26\n    retrycmd 10 5 10 cp /tmp/microsoft.gpg /etc/apt/trusted.gpg.d/ || exit 26\n    aptmarkWALinuxAgent hold\n    packages+=\" cgroup-lite ceph-common glusterfs-client\"\n    disableTimeSyncd\n    packages+=\" ntp ntpstat chrony\"\n    {{/* STIG SV-238200r653775_rule, SV-238231r653868_rule, SV-238230r653865_rule */}}\n    packages+=\" vlock opensc-pkcs11 libpam-pkcs11\"\n  elif [[ $OS == $DEBIAN_OS_NAME ]]; then\n    packages+=\" gpg cgroup-bin\"\n  fi\n\n  apt_get_update || exit 99\n  apt_get_dist_upgrade || exit 101\n\n  for apt_package in ${packages}; do\n    if ! apt_get_install 30 1 600 $apt_package; then\n      journalctl --no-pager -u $apt_package\n      exit 9\n    fi\n  done\n  if [[ ${AUDITD_ENABLED} == true ]]; then\n    if ! apt_get_install 30 1 600 auditd; then\n      journalctl --no-pager -u auditd\n      exit 9\n    fi\n  fi\n}\ngpuDriversDownloaded() {\n  for apt_package in $NVIDIA_PACKAGES; do\n    ls ${PERMANENT_CACHE_DIR}${apt_package}* || return 1\n  done\n  ls ${PERMANENT_CACHE_DIR}nvidia-container-runtime* || return 1\n}\ndownloadGPUDrivers() {\n  mkdir -p $GPU_DEST/tmp\n  retrycmd_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/gpgkey >$GPU_DEST/tmp/aptnvidia.gpg || exit 85\n  wait_for_apt_locks\n  retrycmd 120 5 25 apt-key add $GPU_DEST/tmp/aptnvidia.gpg || exit 85\n  wait_for_apt_locks\n  retrycmd_no_stats 120 5 25 curl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu${UBUNTU_RELEASE}/nvidia-docker.list >$GPU_DEST/tmp/nvidia-docker.list || exit 85\n  wait_for_apt_locks\n  retrycmd_no_stats 120 5 25 cat $GPU_DEST/tmp/nvidia-docker.list >/etc/apt/sources.list.d/nvidia-docker.list || exit 85\n  apt_get_update\n  retrycmd 30 5 60 curl -fLS https://us.download.nvidia.com/tesla/$GPU_DV/NVIDIA-Linux-x86_64-${GPU_DV}.run -o ${GPU_DEST}/nvidia-drivers-${GPU_DV} || exit 85\n  mkdir -p $PERMANENT_CACHE_DIR\n  for apt_package in $NVIDIA_PACKAGES; do\n    apt_get_download 20 30 \"${apt_package}=${NVIDIA_CONTAINER_TOOLKIT_VER}*\" || exit 85\n    cp -al ${APT_CACHE_DIR}${apt_package}_${NVIDIA_CONTAINER_TOOLKIT_VER}* $PERMANENT_CACHE_DIR || exit 85\n  done\n  apt_get_download 20 30 nvidia-container-runtime=${NVIDIA_RUNTIME_VER}* || exit 85\n  cp -al ${APT_CACHE_DIR}nvidia-container-runtime_${NVIDIA_RUNTIME_VER}* $PERMANENT_CACHE_DIR || exit 85\n}\nremoveMoby() {\n  apt_get_purge moby-engine moby-cli || exit 27\n}\nremoveContainerd() {\n  apt_get_purge moby-containerd || exit 27\n}\nmobyPkgVersion() {\n  dpkg -s \"${1}\" | grep \"Version:\" | awk '{ print $2 }' | cut -d '+' -f 1\n}\ninstallRunc() {\n  local v\n  local url\n  v=$(runc --version | head -n 1 | cut -d\" \" -f3)\n  if [[ $v != \"1.1.4\" ]]; then\n    apt_get_install 20 30 120 moby-runc=1.1.4* --allow-downgrades || exit 27\n  fi\n}\ninstallMoby() {\n  local install_pkgs=\"\" v cli_ver=\"${MOBY_VERSION}\"\n  v=\"$(mobyPkgVersion moby-containerd)\"\n  if [ -n \"${CONTAINERD_VERSION}\" ] && [ ! \"${v}\" = \"${CONTAINERD_VERSION}\" ]; then\n    install_pkgs+=\" moby-containerd=${CONTAINERD_VERSION}*\"\n    removeMoby\n    removeContainerd\n  fi\n  v=\"$(mobyPkgVersion moby-engine)\"\n  if [ ! \"${v}\" = \"${MOBY_VERSION}\" ]; then\n    install_pkgs+=\" moby-engine=${MOBY_VERSION}*\"\n    if [ \"${cli_ver}\" = \"3.0.4\" ]; then\n      cli_ver=\"3.0.3\"\n    fi\n    install_pkgs+=\" moby-cli=${cli_ver}*\"\n    removeMoby\n  fi\n  if [ -n \"${install_pkgs}\" ]; then\n    apt_get_install 20 30 120 ${install_pkgs} --allow-downgrades || exit 27\n  fi\n}\ndownloadCNI() {\n  mkdir -p $CNI_DOWNLOADS_DIR\n  CNI_TGZ_TMP=${CNI_PLUGINS_URL##*/}\n  retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${CNI_PLUGINS_URL} || exit 41\n}\ndownloadAzureCNI() {\n  mkdir -p $CNI_DOWNLOADS_DIR\n  CNI_TGZ_TMP=${VNET_CNI_PLUGINS_URL##*/}\n  retrycmd_get_tarball 120 5 \"$CNI_DOWNLOADS_DIR/${CNI_TGZ_TMP}\" ${VNET_CNI_PLUGINS_URL} || exit 41\n}\nensureAPMZ() {\n  local ver=$1 v\n  local d=\"$APMZ_DOWNLOADS_DIR/$ver\"\n  local url=\"https://upstreamartifacts.azureedge.net/apmz/$ver/binaries/apmz_linux_amd64.tar.gz\" fp=\"/usr/local/bin/apmz\" dest=\"$d/apmz.gz\" bin_fp=\"$d/apmz_linux_amd64\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    fp=\"/opt/bin/apmz\"\n    export PATH=\"${PATH}:/opt/bin\"\n  fi\n  if [[ -f $fp ]]; then\n    v=$($fp version)\n    if [[ $ver == \"$v\" ]]; then\n      return\n    fi\n  fi\n  mkdir -p \"$d\"\n  retrycmd_get_tarball 120 5 \"$dest\" \"${url}\"\n  tar -xvf \"$dest\" -C \"$d\"\n  chmod +x \"$bin_fp\"\n  ln -Ffs \"$bin_fp\" \"$fp\"\n}\ninstallBpftrace() {\n  local ver=\"v0.9.4\" v bin=\"bpftrace\" tools=\"bpftrace-tools.tar\"\n  local url=\"https://upstreamartifacts.azureedge.net/$bin/$ver\"\n  local bpftrace_fp=\"/usr/local/bin/$bin\"\n  local tools_fp=\"/usr/local/share/$bin\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    bpftrace_fp=\"/opt/bin/$bin\"\n    tools_fp=\"/opt/share/$bin\"\n    export PATH=\"${PATH}:/opt/bin\"\n  fi\n  if [[ -f $bpftrace_fp ]]; then\n    v=\"$($bin -V | cut -d' ' -f2)\"\n    if [[ $ver == \"$v\" ]]; then\n      return\n    fi\n    rm \"$bpftrace_fp\"\n    if [[ -d $tools_fp ]]; then\n      rm -r \"$tools_fp\"\n    fi\n  fi\n  mkdir -p \"$tools_fp\"\n  install_dir=\"/opt/bpftrace/downloads/$ver\"\n  mkdir -p \"$install_dir\"\n  download_path=\"$install_dir/$tools\"\n  retrycmd 30 5 60 curl -fSL -o \"$bpftrace_fp\" \"$url/$bin\" || exit 169\n  retrycmd 30 5 60 curl -fSL -o \"$download_path\" \"$url/$tools\" || exit 170\n  tar -xvf \"$download_path\" -C \"$tools_fp\"\n  chmod +x \"$bpftrace_fp\"\n  chmod -R +x \"$tools_fp/tools\"\n}\ninstallImg() {\n  img_filepath=/usr/local/bin/img\n  retrycmd_get_executable 120 5 $img_filepath \"https://upstreamartifacts.azureedge.net/img/img-linux-amd64-v0.5.6\" ls || exit 33\n}\nextractHyperkube() {\n  local cli_tool=$1 fp=\"/home/hyperkube-downloads/${KUBERNETES_VERSION}\" dest=\"/usr/local/bin\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    dest=\"/opt/bin\"\n  fi\n  pullContainerImage $cli_tool ${HYPERKUBE_URL}\n  if [[ $cli_tool == \"docker\" ]]; then\n    mkdir -p \"$fp\"\n    if docker run --rm --entrypoint \"\" -v $path:$path ${HYPERKUBE_URL} /bin/bash -c \"cp $dest/{kubelet,kubectl} $fp\"; then\n      mv \"${fp}/kubelet\" \"${dest}/kubelet-${KUBERNETES_VERSION}\"\n      mv \"${fp}/kubectl\" \"${dest}/kubectl-${KUBERNETES_VERSION}\"\n      return\n    else\n      docker run --rm -v $fp:$fp ${HYPERKUBE_URL} /bin/bash -c \"cp /hyperkube $fp\"\n    fi\n  else\n    img unpack -o \"$fp\" ${HYPERKUBE_URL}\n  fi\n\n  cp \"${fp}/hyperkube\" \"${dest}/kubelet-${KUBERNETES_VERSION}\"\n  mv \"${fp}/hyperkube\" \"${dest}/kubectl-${KUBERNETES_VERSION}\"\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    chmod a+x ${dest}/kubelet-${KUBERNETES_VERSION} ${dest}/kubectl-${KUBERNETES_VERSION}\n  fi\n}\nextractKubeBinaries() {\n  KUBE_BINARY_URL=${KUBE_BINARY_URL:-\"https://kubernetesartifacts.azureedge.net/kubernetes/v${KUBERNETES_VERSION}/binaries/kubernetes-node-linux-amd64.tar.gz\"}\n  local dest=\"/opt/kubernetes/downloads\" tmpDir=${KUBE_BINARY_URL##*/}\n  mkdir -p \"${dest}\"\n  retrycmd_get_tarball 120 5 \"$dest/${tmpDir}\" ${KUBE_BINARY_URL} || exit 31\n  path=/usr/local/bin\n  if [[ $OS == $FLATCAR_OS_NAME ]]; then\n    path=/opt/bin\n  fi\n  tar --transform=\"s|.*|&-${KUBERNETES_VERSION}|\" --show-transformed-names -xzvf \"$dest/${tmpDir}\" \\\n    --strip-components=3 -C ${path} kubernetes/node/bin/kubelet kubernetes/node/bin/kubectl\n  rm -f \"$dest/${tmpDir}\"\n}\npullContainerImage() {\n  local cli_tool=$1 url=$2\n  retrycmd 60 1 1200 $cli_tool pull $url || exit 35\n}\nloadContainerImage() {\n  docker pull $1 || exit 35\n  docker save $1 | ctr -n=k8s.io images import - || exit 35\n\n}\noverrideNetworkConfig() {\n  CONFIG_FILEPATH=\"/etc/cloud/cloud.cfg.d/80_azure_net_config.cfg\"\n  touch ${CONFIG_FILEPATH}\n  cat <<EOF >>${CONFIG_FILEPATH}\ndatasource:\n    Azure:\n        apply_network_config: false\nEOF\n}\n#EOF\n", "num_lines": 261}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nERR_FILE_WATCH_TIMEOUT=6 {{/* Timeout waiting for a file */}}\n\n{{/* delete non-working iovisor definition to ensure apt operations work */}}\nrm -Rf /etc/apt/sources.list.d/iovisor.list\n\nset -x\nif [ -f /opt/azure/containers/provision.complete ]; then\n  exit 0\nfi\n\necho $(date),$(hostname), startcustomscript >>/opt/m\n\nfor i in $(seq 1 3600); do\n  if [ -s {{GetCSEHelpersScriptFilepath}} ]; then\n    grep -Fq '#HELPERSEOF' {{GetCSEHelpersScriptFilepath}} && break\n  fi\n  if [ $i -eq 3600 ]; then\n    exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n  else\n    sleep 1\n  fi\ndone\nsed -i \"/#HELPERSEOF/d\" {{GetCSEHelpersScriptFilepath}}\nsource {{GetCSEHelpersScriptFilepath}}\nconfigure_prerequisites\n\nwait_for_file 3600 1 {{GetCSEInstallScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCSEInstallScriptFilepath}}\n\nensureAPMZ \"v0.5.1\"\n{{- if HasTelemetryEnabled }}\neval \"$(apmz bash -n \"cse\" -t \"{{GetLinuxDefaultTelemetryTags}}\" --api-keys \"{{GetApplicationInsightsTelemetryKeys}}\")\"\n{{else}}\neval \"$(apmz bash -d)\"\n{{end}}\n\nwait_for_file 3600 1 {{GetCSEConfigScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCSEConfigScriptFilepath}}\n\n{{- if IsCustomCloudProfile}}\nwait_for_file 3600 1 {{GetCustomCloudConfigCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\nsource {{GetCustomCloudConfigCSEScriptFilepath }}\n{{end}}\n\ndisableSystemdResolved\n\nset +x\nETCD_PEER_CERT=$(echo ${ETCD_PEER_CERTIFICATES} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((NODE_INDEX + 1)))\nETCD_PEER_KEY=$(echo ${ETCD_PEER_PRIVATE_KEYS} | cut -d'[' -f 2 | cut -d']' -f 1 | cut -d',' -f $((NODE_INDEX + 1)))\nset -x\n\ntime_metric \"ConfigureAdminUser\" configureAdminUser\n\n{{- if HasVHDDistroNodes}}\n  {{- if not NeedsContainerd}}\ntime_metric \"CleanupContainerd\" cleanUpContainerd\n  {{end}}\n  {{- if HasNSeriesSKU}}\nif [[ ${GPU_NODE} != \"true\" ]]; then\n  time_metric \"CleanupGPUDrivers\" cleanUpGPUDrivers\nfi\n  {{else}}\ntime_metric \"CleanupGPUDrivers\" cleanUpGPUDrivers\n  {{end}}\n{{end}}\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\nif [ -f $VHD_LOGS_FILEPATH ]; then\n  time_metric \"CleanUpContainerImages\" cleanUpContainerImages\n  FULL_INSTALL_REQUIRED=false\nelse\n  if [[ ${IS_VHD} == true ]]; then\n    exit {{GetCSEErrorCode \"ERR_VHD_FILE_NOT_FOUND\"}}\n  fi\n  FULL_INSTALL_REQUIRED=true\nfi\n\n{{- if ShouldEnforceKubernetesDisaStig}}\ndisableSshd\n{{- end}}\n\n{{- if not IsVHDDistroForAllNodes}}\nif [[ $OS == $UBUNTU_OS_NAME || $OS == $DEBIAN_OS_NAME ]] && [ \"$FULL_INSTALL_REQUIRED\" = \"true\" ]; then\n  time_metric \"InstallDeps\" installDeps\n  overrideNetworkConfig\n  {{- if not IsDockerContainerRuntime}}\n  time_metric \"InstallImg\" installImg\n  {{end}}\nfi\n{{end}}\n\nif apt list --installed | grep 'chrony'; then\n  time_metric \"ConfigureChrony\" configureChrony\n  time_metric \"EnsureChrony\" ensureChrony\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  time_metric \"EnsureAuditD\" ensureAuditD\nfi\n\n{{- if not IsVHDDistroForAllNodes}}\nif [[ $FULL_INSTALL_REQUIRED == \"true\" ]]; then\n  time_metric \"InstallBpftrace\" installBpftrace\nfi\n{{end}}\n\nif [[ $OS != $FLATCAR_OS_NAME ]]; then\n{{- if NeedsContainerd}}\ntime_metric \"InstallContainerd\" installContainerd\n{{else}}\ntime_metric \"installMoby\" installMoby\n{{end}}\ntime_metric \"installRunc\" installRunc\n{{- if HasLinuxMobyURL}}\n  LINUX_MOBY_URL={{GetLinuxMobyURL}}\n  if [[ -n \"${LINUX_MOBY_URL:-}\" ]]; then\n    DEB=\"${LINUX_MOBY_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_MOBY_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\n{{- if HasLinuxContainerdURL}}\n  LINUX_CONTAINERD_URL={{GetLinuxContainerdURL}}\n  if [[ -n \"${LINUX_CONTAINERD_URL:-}\" ]]; then\n    DEB=\"${LINUX_CONTAINERD_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_CONTAINERD_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\n{{- if HasLinuxRuncURL}}\n  LINUX_RUNC_URL={{GetLinuxRuncURL}}\n  if [[ -n \"${LINUX_RUNC_URL:-}\" ]]; then\n    DEB=\"${LINUX_RUNC_URL##*/}\"\n    retrycmd_no_stats 120 5 25 curl -fsSL ${LINUX_RUNC_URL} >/tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_DOWNLOAD_TIMEOUT\"}}\n    dpkg_install 20 30 /tmp/${DEB} || exit {{GetCSEErrorCode \"ERR_DEB_PKG_ADD_FAIL\"}}\n  fi\n{{end}}\nfi\n\nif [[ -n ${MASTER_NODE} ]] && [[ -z ${COSMOS_URI} ]]; then\n  {{- if IsDockerContainerRuntime}}\n  cli_tool=\"docker\"\n  {{else}}\n  cli_tool=\"img\"\n  {{end}}\n  time_metric \"InstallEtcd\" installEtcd $cli_tool\nfi\n\n{{/* this will capture the amount of time to install of the network plugin during cse */}}\ntime_metric \"InstallNetworkPlugin\" installNetworkPlugin\n\n{{- if and HasNSeriesSKU IsNvidiaDevicePluginAddonEnabled}}\nif [[ ${GPU_NODE} == true ]]; then\n  gpuDriversDownloaded || time_metric \"DownloadGPUDrivers\" downloadGPUDrivers\n  time_metric \"EnsureGPUDrivers\" ensureGPUDrivers\nfi\n{{end}}\n\n{{- if and IsDockerContainerRuntime HasPrivateAzureRegistryServer}}\ndocker login -u $SERVICE_PRINCIPAL_CLIENT_ID -p $SERVICE_PRINCIPAL_CLIENT_SECRET {{GetPrivateAzureRegistryServer}}\n{{end}}\n\ntime_metric \"InstallKubeletAndKubectl\" installKubeletAndKubectl\n\nif [[ $OS != $FLATCAR_OS_NAME ]]; then\n    time_metric \"EnsureRPC\" ensureRPC\n    time_metric \"EnsureCron\" ensureCron\nfi\n\ntime_metric \"CreateKubeManifestDir\" createKubeManifestDir\n\n{{- if HasDCSeriesSKU}}\nif [[ ${SGX_NODE} == true && ! -e \"/dev/sgx\" ]]; then\n  time_metric \"InstallSGXDrivers\" installSGXDrivers\nfi\n{{end}}\n\n{{/* create etcd user if we are configured for etcd */}}\nif [[ -n ${MASTER_NODE} ]] && [[ -z ${COSMOS_URI} ]]; then\n  time_metric \"ConfigureEtcdUser\" configureEtcdUser\nfi\n\nif [[ -n ${MASTER_NODE} ]]; then\n  {{/* this step configures all certs */}}\n  {{/* both configs etcd/cosmos */}}\n  time_metric \"ConfigureSecrets\" configureSecrets\n\n  {{/* HACK: in case a control plane node starts with incorrectly defined cloud-init IPs */}}\n  if grep -q -E '^ +addresses:|^ +- ' /etc/netplan/50-cloud-init.yaml; then\n    x=$(grep -v -E '^ +addresses:|^ +- ' /etc/netplan/50-cloud-init.yaml)\n    echo \"$x\" >/etc/netplan/50-cloud-init.yaml\n    netplan apply\n  fi\nfi\n\n{{/* configure etcd if we are configured for etcd */}}\nif [[ -n ${MASTER_NODE} ]] && [[ -z ${COSMOS_URI} ]]; then\n  time_metric \"ConfigureEtcd\" configureEtcd\nelse\n  time_metric \"RemoveEtcd\" removeEtcd\nfi\n\n{{- if HasCustomSearchDomain}}\nwait_for_file 3600 1 {{GetCustomSearchDomainsCSEScriptFilepath}} || exit {{GetCSEErrorCode \"ERR_FILE_WATCH_TIMEOUT\"}}\n{{GetCustomSearchDomainsCSEScriptFilepath}} >/opt/azure/containers/setup-custom-search-domain.log 2>&1 || exit {{GetCSEErrorCode \"ERR_CUSTOM_SEARCH_DOMAINS_FAIL\"}}\n{{end}}\n\n{{- if IsDockerContainerRuntime}}\ntime_metric \"EnsureDocker\" ensureDocker\n{{end}}\n\ntime_metric \"ConfigureK8s\" configureK8s\n\n{{- if IsCustomCloudProfile}}\ntime_metric \"ConfigureK8sCustomCloud\" configureK8sCustomCloud\n{{- if and IsAzureStackCloud IsAzureCNI}}\nsource {{GetCustomCloudAzureCNIConfigCSEScriptFilepath}}\ntime_metric \"ConfigureAzureStackInterfaces\" configureAzureStackInterfaces\n{{end}}\n{{end}}\n\ntime_metric \"ConfigureCNI\" configureCNI\n\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"ConfigAddons\" configAddons\n  time_metric \"WriteKubeConfig\" writeKubeConfig\nfi\n\n{{- if NeedsContainerd}}\ntime_metric \"EnsureContainerd\" ensureContainerd\n{{end}}\n\n{{/* configure and enable dhcpv6 for ipv6 features */}}\n{{- if IsIPv6Enabled}}\ntime_metric \"EnsureDHCPv6\" ensureDHCPv6\n{{end}}\n\n{{/* configure and enable kms plugin */}}\n{{- if EnableEncryptionWithExternalKms}}\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"EnsureKMSKeyvaultKey\" ensureKMSKeyvaultKey\nfi\n{{end}}\n\ntime_metric \"EnsureKubelet\" ensureKubelet\n{{if IsAzurePolicyAddonEnabled}}\nif [[ -n ${MASTER_NODE} ]]; then\n  time_metric \"EnsureLabelExclusionForAzurePolicyAddon\" ensureLabelExclusionForAzurePolicyAddon\nfi\n{{end}}\ntime_metric \"EnsureJournal\" ensureJournal\n\nif [[ -n ${MASTER_NODE} ]]; then\n  if version_gte ${KUBERNETES_VERSION} 1.16; then\n    time_metric \"EnsureLabelNodes\" ensureLabelNodes\n  fi\n{{- if IsAADPodIdentityAddonEnabled}}\n  time_metric \"EnsureTaints\" ensureTaints\n{{end}}\n  if [[ -z ${COSMOS_URI} ]]; then\n    time_metric \"EnsureEtcd\" ensureEtcd\n  fi\n  time_metric \"EnsureK8sControlPlane\" ensureK8sControlPlane\n  time_metric \"EnsureAddons\" ensureAddons\n  {{- if HasClusterInitComponent}}\n  if [[ $NODE_INDEX == 0 ]]; then\n    retrycmd 120 5 30 $KUBECTL apply -f /opt/azure/containers/cluster-init.yaml || exit {{GetCSEErrorCode \"ERR_CLUSTER_INIT_FAIL\"}}\n  fi\n  {{end}}\nfi\n\n{{- if not IsVHDDistroForAllNodes}}\nif $FULL_INSTALL_REQUIRED; then\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    {{/* mitigation for bug https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1676635 */}}\n    echo 2dd1ce17-079e-403c-b352-a1921ee207ee >/sys/bus/vmbus/drivers/hv_util/unbind\n    sed -i \"13i\\echo 2dd1ce17-079e-403c-b352-a1921ee207ee > /sys/bus/vmbus/drivers/hv_util/unbind\\n\" /etc/rc.local\n  fi\nfi\n{{end}}\n\n{{- /* re-enable unattended upgrades */}}\n{{- if EnableUnattendedUpgrades}}\nrm -f /etc/apt/apt.conf.d/99periodic\n{{- end}}\n\n{{- if not HasBlockOutboundInternet}}\n    {{- if RunUnattendedUpgradesOnBootstrap}}\napt_get_update && unattended_upgrade\n    {{- end}}\n{{- end}}\n\n{{- if ShouldEnforceUbuntu2004DisaStig}}\n{{GetUbuntu2004DisaStigScriptFilepath}}\n{{- end}}\n\nif [ -f /var/run/reboot-required ]; then\n  trace_info \"RebootRequired\" \"reboot=true\"\n  /bin/bash -c \"shutdown -r 1 &\"\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    aptmarkWALinuxAgent unhold &\n  fi\nelse\n{{- if RunUnattendedUpgradesOnBootstrap}}\n  if [[ -z ${MASTER_NODE} ]]; then\n    systemctl_restart 100 5 30 kubelet\n    systemctl_restart 100 5 30 kubelet-monitor\n  fi\n{{- end}}\n  if [[ $OS == $UBUNTU_OS_NAME ]]; then\n    /usr/lib/apt/apt.systemd.daily &\n    aptmarkWALinuxAgent unhold &\n  fi\nfi\n\necho \"CSE finished successfully\"\necho $(date),$(hostname), endcustomscript >>/opt/m\nmkdir -p /opt/azure/containers && touch /opt/azure/containers/provision.complete\nps auxfww >/opt/azure/provision-ps.log &\n\nexit 0\n\n#EOF\n", "num_lines": 325}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsetLoginDefs() {\n  local f=/etc/login.defs\n  sed -i '/^PASS_MAX_DAYS/d' ${f} || exit 115\n  sed -i '$aPASS_MAX_DAYS 60' ${f} || exit 115\n  sed -i '/^PASS_MIN_DAYS/d' ${f} || exit 115\n  sed -i '$aPASS_MIN_DAYS 1' ${f} || exit 115\n  sed -i '/^UMASK/d' ${f} || exit 115\n  sed -i '$aUMASK 077' ${f} || exit 115\n}\nsetPwqualityConf() {\n  local f=/etc/security/pwquality.conf\n  sed -i '/^difok/d' ${f} || exit 115\n  sed -i '$adifok=8' ${f} || exit 115\n  sed -i '/^dictcheck/d' ${f} || exit 115\n  sed -i '$adictcheck=1' ${f} || exit 115\n  sed -i '/^minlen/d' ${f} || exit 115\n  sed -i '$aminlen=15' ${f} || exit 115\n  sed -i '/^lcredit/d' ${f} || exit 115\n  sed -i '$alcredit=-1' ${f} || exit 115\n}\nsetTerminalTimeout() {\n  local f=/etc/profile.d/99-terminal_tmout.sh\n  {{/* STIG SV-238207r653796_rule */}}\n  if [[ -f ${f} ]]; then\n    sed -i '/^TMOUT/d' ${f} || exit 115\n    sed -i '$aTMOUT=600' ${f} || exit 115\n  else\n    echo \"TMOUT=600\" > ${f}\n    truncate -s -1 ${f}\n  fi\n}\nsetSSHDConfig() {\n  local f=/etc/ssh/sshd_config\n  {{/* STIG SV-238212r653811_rule */}}\n  sed -i '/^ClientAliveCountMax/d' ${f} || exit 115\n  sed -i '$aClientAliveCountMax 1' ${f} || exit 115\n  {{/* STIG SV-238216r654316_rule */}}\n  sed -i '/^MACs/d' ${f} || exit 115\n  sed -i '$aMACs hmac-sha2-512,hmac-sha2-256' ${f} || exit 115\n  {{/* STIG SV-238217r653826_rule */}}\n  sed -i '/^Ciphers/d' ${f} || exit 115\n  sed -i '$aCiphers aes256-ctr,aes192-ctr,aes128-ctr' ${f} || exit 115\n  {{/* STIG SV-238220r653835_rule */}}\n  sed -i '/^X11UseLocalhost/d' ${f} || exit 115\n  sed -i '$aX11UseLocalhost yes' ${f} || exit 115\n  {{/* STIG SV-238214r653817_rule */}}\n  if [[ -f /etc/issue-stig.net ]]; then\n    sed -i '/^Banner/d' ${f} || exit 115\n    sed -i '$aBanner /etc/issue-stig.net' ${f} || exit 115\n  fi\n}\nsetAuditd() {\n  local f=/etc/audit/auditd.conf\n  {{/* STIG SV-238244r653907_rule */}}\n  sed -i '/^disk_full_action/d' ${f} || exit 115\n  sed -i '$adisk_full_action = HALT' ${f} || exit 115\n}\nsetLimitsConf() {\n  local f=/etc/security/limits.conf\n  {{/* STIG SV-238323r654144_rule */}}\n  sed -i '1s|^|* hard maxlogins 10\\n|' ${f}\n}\nsetAPTConfig() {\n  local f=/etc/apt/apt.conf.d/01-vendor-ubuntu\n  {{/* STIG SV-219155r610963_rule */}}\n  sed -i '/^APT::Get::AllowUnauthenticated/d' ${f} || exit 115\n  sed -i '$aAPT::Get::AllowUnauthenticated \"false\";' ${f} || exit 115\n  local g=/etc/apt/apt.conf.d/50unattended-upgrades\n  {{/* STIG SV-219156r610963_rule */}}\n  sed -i '/^Unattended-Upgrade::Remove-Unused-Dependencies/d' ${g} || exit 115\n  sed -i '$aUnattended-Upgrade::Remove-Unused-Dependencies \"true\";' ${g} || exit 115\n  {{/* STIG SV-219156r610963_rule */}}\n  sed -i '/^Unattended-Upgrade::Remove-Unused-Kernel-Packages/d' ${g} || exit 115\n  sed -i '$aUnattended-Upgrade::Remove-Unused-Kernel-Packages \"true\";' ${g} || exit 115\n}\nsetLoginDefs\nsetPwqualityConf\nsetTerminalTimeout\nsetSSHDConfig\nsetAuditd\nsetLimitsConf\nsetAPTConfig\n#EOF\n", "num_lines": 86}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nset -o pipefail\nset -u\n\nDHCLIENT6_CONF_FILE=/etc/dhcp/dhclient6.conf\nCLOUD_INIT_CFG=/etc/network/interfaces.d/50-cloud-init.cfg\n\nread -r -d '' NETWORK_CONFIGURATION <<EOC || true\niface eth0 inet6 auto\n    up sleep 5\n    up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true\nEOC\n\nadd_if_not_exists() {\n  grep -qxF \"${1}\" \"${2}\" || echo \"${1}\" >>\"${2}\"\n}\n\ntouch /etc/dhcp/dhclient6.conf && add_if_not_exists \"timeout 10;\" ${DHCLIENT6_CONF_FILE} && \\\n  add_if_not_exists \"${NETWORK_CONFIGURATION}\" ${CLOUD_INIT_CFG} && \\\n  sudo ifdown eth0 && sudo ifup eth0\n#EOF\n", "num_lines": 24}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nPROXY_CA_KEY=\"${PROXY_CA_KEY:=/tmp/proxy-client-ca.key}\"\nPROXY_CRT=\"${PROXY_CRT:=/tmp/proxy-client-ca.crt}\"\nPROXY_CLIENT_KEY=\"${PROXY_CLIENT_KEY:=/tmp/proxy-client.key}\"\nPROXY_CLIENT_CSR=\"${PROXY_CLIENT_CSR:=/tmp/proxy-client.csr}\"\nPROXY_CLIENT_CRT=\"${PROXY_CLIENT_CRT:=/tmp/proxy-client.crt}\"\nETCD_REQUESTHEADER_CLIENT_CA=\"${ETCD_REQUESTHEADER_CLIENT_CA:=/proxycerts/requestheader-client-ca-file}\"\nETCD_PROXY_CERT=\"${ETCD_PROXY_CERT:=/proxycerts/proxy-client-cert-file}\"\nETCD_PROXY_KEY=\"${ETCD_PROXY_KEY:=/proxycerts/proxy-client-key-file}\"\nK8S_PROXY_CA_CRT_FILEPATH=\"${K8S_PROXY_CA_CRT_FILEPATH:=/etc/kubernetes/certs/proxy-ca.crt}\"\nK8S_PROXY_KEY_FILEPATH=\"${K8S_PROXY_KEY_FILEPATH:=/etc/kubernetes/certs/proxy.key}\"\nK8S_PROXY_CRT_FILEPATH=\"${K8S_PROXY_CRT_FILEPATH:=/etc/kubernetes/certs/proxy.crt}\"\n\nPROXY_CERTS_LOCK_NAME=\"master_proxy_cert_lock\"\nPROXY_CERT_LOCK_FILE=\"/tmp/create_cert.fifl\"\n\nif [[ -z ${COSMOS_URI} ]]; then\n  ETCDCTL_ENDPOINTS=\"${ETCDCTL_ENDPOINTS:=https://127.0.0.1:2379}\"\n  ETCDCTL_CA_FILE=\"${ETCDCTL_CA_FILE:=/etc/kubernetes/certs/ca.crt}\"\n  ETCD_CA_PARAM=\"--cacert=${ETCDCTL_CA_FILE}\"\nelse\n  ETCDCTL_ENDPOINTS=\"${ETCDCTL_ENDPOINTS:=https://${COSMOS_URI}:2379}\"\n  ETCD_CA_PARAM=\"\"\nfi\nETCDCTL_KEY_FILE=\"${ETCDCTL_KEY_FILE:=/etc/kubernetes/certs/etcdclient.key}\"\nETCDCTL_CERT_FILE=\"${ETCDCTL_CERT_FILE:=/etc/kubernetes/certs/etcdclient.crt}\"\n\nETCDCTL_PARAMS=\"--command-timeout=30s --cert=${ETCDCTL_CERT_FILE} --key=${ETCDCTL_KEY_FILE} ${ETCD_CA_PARAM} --endpoints=${ETCDCTL_ENDPOINTS}\"\nRANDFILE=$(mktemp)\nexport RANDFILE\n\nopenssl genrsa -out $PROXY_CA_KEY 2048\nopenssl req -new -x509 -days 262824 -key $PROXY_CA_KEY -out $PROXY_CRT -subj '/CN=proxyClientCA'\nopenssl genrsa -out $PROXY_CLIENT_KEY 2048\nopenssl req -new -key $PROXY_CLIENT_KEY -out $PROXY_CLIENT_CSR -subj '/CN=aggregator/O=system:masters'\nopenssl x509 -req -days 262824 -in $PROXY_CLIENT_CSR -CA $PROXY_CRT -CAkey $PROXY_CA_KEY -set_serial 02 -out $PROXY_CLIENT_CRT\n\nwrite_certs_to_disk() {\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_REQUESTHEADER_CLIENT_CA --print-value-only >$K8S_PROXY_CA_CRT_FILEPATH\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_KEY --print-value-only >$K8S_PROXY_KEY_FILEPATH\n  ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_CERT --print-value-only >$K8S_PROXY_CRT_FILEPATH\n  sed -i '1s/\\s//' $K8S_PROXY_CA_CRT_FILEPATH $K8S_PROXY_CRT_FILEPATH $K8S_PROXY_KEY_FILEPATH\n  chmod 600 $K8S_PROXY_KEY_FILEPATH\n}\n\nwrite_certs_to_disk_with_retry() {\n  for i in $(seq 1 12); do\n    write_certs_to_disk && break || sleep 5\n  done\n}\nis_etcd_healthy() {\n  for i in $(seq 1 100); do\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} endpoint health && break || sleep 5\n  done\n}\nis_etcd_healthy\nrm -f \"${PROXY_CERT_LOCK_FILE}\"\nmkfifo \"${PROXY_CERT_LOCK_FILE}\"\n\nETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} lock ${PROXY_CERTS_LOCK_NAME} >\"${PROXY_CERT_LOCK_FILE}\" &\n\npid=$!\nif read -r lockthis <\"${PROXY_CERT_LOCK_FILE}\"; then\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_REQUESTHEADER_CLIENT_CA --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_REQUESTHEADER_CLIENT_CA \" $(cat ${PROXY_CRT})\" >/dev/null 2>&1\n  fi\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_KEY --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_PROXY_KEY \" $(cat ${PROXY_CLIENT_KEY})\" >/dev/null 2>&1\n  fi\n  if [[ \"${OVERRIDE_PROXY_CERTS}\" == \"true\" ]] || [[ \"\" == \"$(ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} get $ETCD_PROXY_CERT --print-value-only)\" ]]; then\n    ETCDCTL_API=3 etcdctl ${ETCDCTL_PARAMS} put $ETCD_PROXY_CERT \" $(cat ${PROXY_CLIENT_CRT})\" >/dev/null 2>&1\n  fi\nfi\nkill $pid\nwait $pid\nrm -f \"${PROXY_CERT_LOCK_FILE}\"\n\nwrite_certs_to_disk_with_retry\n#EOF\n", "num_lines": 81}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nsource {{GetCSEHelpersScriptFilepath}}\n\n{{- /* This script originated at https://github.com/kubernetes/kubernetes/blob/master/cluster/gce/gci/health-monitor.sh */}}\n{{- /* and has been modified for aks-engine. */}}\n\nset -o nounset\nset -o pipefail\n\ncontainer_runtime_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for CRI to be functional/stable */}}\n  local cri_name=\"${CONTAINER_RUNTIME:-docker}\" cmd=\"docker ps\"\n  if [[ ${CONTAINER_RUNTIME} == \"containerd\" ]]; then\n    cmd=\"ctr -n k8s.io containers ls\"\n  fi\n\n  while true; do\n    if ! timeout 60 ${cmd} >/dev/null; then\n      echo \"Container runtime ${cri_name} failed!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! timeout 60 ${cmd} >/dev/null; then\n        if [[ $cri_name == \"docker\" ]]; then\n          pkill -SIGUSR1 dockerd\n        fi\n        if [[ $cri_name == \"containerd\" ]]; then\n          pkill -SIGUSR1 containerd\n        fi\n        systemctl kill --kill-who=main \"${cri_name}\"\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active ${cri_name}; then\n          systemctl start ${cri_name}\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\nkubelet_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for kubelet to be functional/stable */}}\n  local max_seconds=10 output=\"\"\n  local monitor_cmd=\"curl -m ${max_seconds} -f -s -S http://127.0.0.1:${HEALTHZPORT}/healthz\"\n  while true; do\n    if ! output=$(${monitor_cmd} 2>&1); then\n      echo $output\n      echo \"Kubelet is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd} 2>&1); then\n        systemctl kill kubelet\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active kubelet; then\n          systemctl start kubelet\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\napiserver_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for apiserver to be functional/stable */}}\n  local private_ip=$( (ip -br -4 addr show eth0 || ip -br -4 addr show azure0) | grep -Po '\\d+\\.\\d+\\.\\d+\\.\\d+')\n  local max_seconds=10 output=\"\"\n  local monitor_cmd=\"curl -m ${max_seconds} --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/client.crt --key /etc/kubernetes/certs/client.key https://${private_ip}:443/readyz?verbose\"\n  while true; do\n    if ! output=$(${monitor_cmd} 2>&1); then\n      echo $output\n      echo \"apiserver is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd} 2>&1); then\n        systemctl kill kubelet\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active kubelet; then\n          systemctl start kubelet\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\netcd_monitoring() {\n  sleep 300 {{/* Wait for 5 minutes for etcd to be functional/stable */}}\n  local max_seconds=10 output=\"\"\n  local endpoint=\"https://${PRIVATE_IP}:2379\"\n  local monitor_cmd=\"curl -s -S -m ${max_seconds} --cacert /etc/kubernetes/certs/ca.crt --cert /etc/kubernetes/certs/etcdclient.crt --key /etc/kubernetes/certs/etcdclient.key ${endpoint}/v2/machines\"\n  while true; do\n    if ! output=$(${monitor_cmd}); then\n      echo $output\n      echo \"etcd is unhealthy!\"\n      sleep 10 {{/* Wait 10 more seconds, check again, because the systemd job itself may have already restarted things */}}\n      if ! output=$(${monitor_cmd}); then\n        systemctl kill etcd\n        sleep 60 {{/* Wait a minute to validate that the systemd job restarted itself after we manually killed the process */}}\n        if ! systemctl is-active etcd; then\n          systemctl start etcd\n        fi\n      fi\n    else\n      sleep \"${SLEEP_TIME}\"\n    fi\n  done\n}\n\nif [[ $# -ne 1 ]]; then\n  echo \"Usage: health-monitor.sh <container-runtime|kubelet|etcd>\"\n  exit 1\nfi\n\nSLEEP_TIME=10\ncomponent=$1\necho \"Start kubernetes health monitoring for ${component}\"\n\nif [[ ${component} == \"container-runtime\" ]]; then\n  container_runtime_monitoring\nelif [[ ${component} == \"kubelet\" ]]; then\n  kubelet_monitoring\nelif [[ ${component} == \"apiserver\" ]]; then\n  apiserver_monitoring\nelif [[ ${component} == \"etcd\" ]]; then\n  etcd_monitoring\nelse\n  echo \"Health monitoring for component ${component} is not supported!\"\nfi\n", "num_lines": 128}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset +x\nset -euo pipefail\n\nAZURE_JSON_PATH=\"/etc/kubernetes/azure.json\"\nSERVICE_PRINCIPAL_CLIENT_ID=$(jq -r '.aadClientId' ${AZURE_JSON_PATH})\nSERVICE_PRINCIPAL_CLIENT_SECRET=$(jq -r '.aadClientSecret' ${AZURE_JSON_PATH})\nTENANT_ID=$(jq -r '.tenantId' ${AZURE_JSON_PATH})\nKMS_KEYVAULT_NAME=$(jq -r '.providerVaultName' ${AZURE_JSON_PATH})\nKMS_KEY_NAME=$(jq -r '.providerKeyName' ${AZURE_JSON_PATH})\nUSER_ASSIGNED_IDENTITY_ID=$(jq -r '.userAssignedIdentityID' ${AZURE_JSON_PATH})\nPROVIDER_KEY_VERSION=$(jq -r '.providerKeyVersion' ${AZURE_JSON_PATH})\nAZURE_CLOUD=$(jq -r '.cloud' ${AZURE_JSON_PATH})\n\n# get the required parameters specific for cloud\nif [[ $AZURE_CLOUD == \"AzurePublicCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.com/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.azure.net\"\nelif [[ $AZURE_CLOUD == \"AzureChinaCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.chinacloudapi.cn/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.azure.cn\"\nelif [[ $AZURE_CLOUD == \"AzureGermanCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.de/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.microsoftazure.de\"\nelif [[ $AZURE_CLOUD == \"AzureUSGovernmentCloud\" ]]; then\n    ACTIVE_DIRECTORY_ENDPOINT=\"https://login.microsoftonline.us/\"\n    KEYVAULT_DNS_SUFFIX=\"vault.usgovcloudapi.net\"\nelif [[ $AZURE_CLOUD == \"AzureStackCloud\" ]]; then\n    AZURESTACK_ENVIRONMENT_JSON_PATH=\"/etc/kubernetes/azurestackcloud.json\"\n    ACTIVE_DIRECTORY_ENDPOINT=$(jq -r '.activeDirectoryEndpoint' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\n    KEYVAULT_DNS_SUFFIX=$(jq -r '.keyVaultDNSSuffix' ${AZURESTACK_ENVIRONMENT_JSON_PATH})\nelse\n    echo \"Invalid cloud name\"\n    exit 120\nfi\n\nTOKEN_URL=\"${ACTIVE_DIRECTORY_ENDPOINT}${TENANT_ID}/oauth2/token\"\nKEYVAULT_URL=\"https://${KMS_KEYVAULT_NAME}.${KEYVAULT_DNS_SUFFIX}/keys/${KMS_KEY_NAME}/versions?maxresults=1&api-version=7.1\"\nKEYVAULT_ENDPOINT=\"https://${KEYVAULT_DNS_SUFFIX}\"\nKMS_KUBERNETES_FILE=/etc/kubernetes/manifests/kube-azure-kms.yaml\n\n# provider key version already exists\n# this will be the case for BYOK\nif [[ -n $PROVIDER_KEY_VERSION ]]; then\n    echo \"KMS provider key version already exists\"\n    exit 0\nfi\n\necho \"Generating token for Azure Key Vault\"\necho \"------------------------------------------------------------------------\"\necho \"Parameters\"\necho \"------------------------------------------------------------------------\"\necho \"SERVICE_PRINCIPAL_CLIENT_ID:     ...\"\necho \"SERVICE_PRINCIPAL_CLIENT_SECRET: ...\"\necho \"ACTIVE_DIRECTORY_ENDPOINT:       $ACTIVE_DIRECTORY_ENDPOINT\"\necho \"TENANT_ID:                       $TENANT_ID\"\necho \"TOKEN_URL:                       $TOKEN_URL\"\necho \"SCOPE:                           $KEYVAULT_ENDPOINT\"\necho \"------------------------------------------------------------------------\"\n\nif [[ $SERVICE_PRINCIPAL_CLIENT_ID == \"msi\" ]] && [[ $SERVICE_PRINCIPAL_CLIENT_SECRET == \"msi\" ]]; then\n    if [[ -z $USER_ASSIGNED_IDENTITY_ID ]]; then\n        # using system-assigned identity to access keyvault\n        TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 \\\n            -H Metadata:true \\\n            \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=$KEYVAULT_ENDPOINT\" | jq '.access_token' | xargs)\n    else\n        # using user-assigned managed identity to access keyvault\n        TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 \\\n            -H Metadata:true \\\n            \"http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&client_id=$USER_ASSIGNED_IDENTITY_ID&resource=$KEYVAULT_ENDPOINT\" | jq '.access_token' | xargs)\n    fi\nelse\n    # use service principal token to access keyvault\n    TOKEN=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f -X POST \\\n        -H \"Content-Type: application/x-www-form-urlencoded\" \\\n        -d \"grant_type=client_credentials\" \\\n        -d \"client_id=$SERVICE_PRINCIPAL_CLIENT_ID\" \\\n        --data-urlencode \"client_secret=$SERVICE_PRINCIPAL_CLIENT_SECRET\" \\\n        --data-urlencode \"resource=$KEYVAULT_ENDPOINT\" \\\n        ${TOKEN_URL} | jq '.access_token' | xargs)\nfi\n\n\nif [[ -z $TOKEN ]]; then\n    echo \"Error generating token for Azure Keyvault\"\n    exit 120\nfi\n\n# Get the keyID for the kms key created as part of cluster bootstrap\nKEY_ID=$(curl -s --retry 5 --retry-delay 10 --max-time 60 -f \\\n    ${KEYVAULT_URL} -H \"Authorization: Bearer ${TOKEN}\" | jq '.value[0].kid' | xargs)\n\nif [[ -z \"$KEY_ID\" || \"$KEY_ID\" == \"null\" ]]; then\n    echo \"Error getting the kms key version\"\n    exit 120\nfi\n\n# KID format: https://<keyvault name>.vault.azure.net/keys/<key name>/<key version>\n# Example KID: \"https://akv0112master.vault.azure.net/keys/k8s/128a3d9956bc44feb6a0e2c2f35b732c\"\nKEY_VERSION=${KEY_ID##*/}\n\n# Set the version in azure.json\nif [ -f $AZURE_JSON_PATH ]; then\n    # once the version is set in azure.json, kms plugin will just default to using the key\n    # this will be changed in upcoming kms release to set the version as container args\n    tmpDir=$(mktemp -d \"$(pwd)/XXX\")\n    jq --arg KEY_VERSION ${KEY_VERSION} '.providerKeyVersion=($KEY_VERSION)' \"$AZURE_JSON_PATH\" > $tmpDir/tmp\n    mv $tmpDir/tmp \"$AZURE_JSON_PATH\"\n    # set the permissions for azure json\n    chmod 0600 \"$AZURE_JSON_PATH\"\n    chown root:root \"$AZURE_JSON_PATH\"\n    rm -Rf $tmpDir\nfi\n\nset -x\n#EOF\n", "num_lines": 119}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script looks for nodes that don't have the required kubernetes.io/role label,\n# and then labels them appropriately\n#\n# Because nodes can't self-label their role in this way,\n# we need control plane nodes to do this continually\n# to ensure that new nodes get the role labels quickly\n\nset -euo pipefail\n\nKUBECONFIG=\"$(find /home/*/.kube/config)\"\nKUBECTL=\"kubectl --kubeconfig=${KUBECONFIG}\"\n\nMASTER_SELECTOR=\"kubernetes.azure.com/role=master,kubernetes.io/role!=master,node-role.kubernetes.io/master!=\"\nMASTER_LABELS=\"kubernetes.io/role=master node-role.kubernetes.io/master=\"\nAGENT_SELECTOR=\"kubernetes.azure.com/role=agent,kubernetes.io/role!=agent,node-role.kubernetes.io/agent!=\"\nAGENT_LABELS=\"kubernetes.io/role=agent node-role.kubernetes.io/agent=\"\n\n${KUBECTL} label nodes --overwrite -l $MASTER_SELECTOR $MASTER_LABELS\n${KUBECTL} label nodes --overwrite -l $AGENT_SELECTOR $AGENT_LABELS\n#EOF\n", "num_lines": 23}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# 5.4.4 Ensure default user umask is 027 or more restrictive\numask 027\n", "num_lines": 5}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nsource {{GetCSEHelpersScriptFilepath}}\n\necho \"  dns-search {{GetSearchDomainName}}\" | tee -a /etc/network/interfaces.d/50-cloud-init.cfg\nsystemctl_restart 20 5 10 networking\nwait_for_apt_locks\nretrycmd 10 5 120 apt-get -y install realmd sssd sssd-tools samba-common samba samba-common python2.7 samba-libs packagekit\nwait_for_apt_locks\necho \"{{GetSearchDomainRealmPassword}}\" | realm join -U {{GetSearchDomainRealmUser}}@$(echo \"{{GetSearchDomainName}}\" | tr /a-z/ /A-Z/) $(echo \"{{GetSearchDomainName}}\" | tr /a-z/ /A-Z/)\n#EOF\n", "num_lines": 12}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nKUBECONFIG=\"$(find /home/*/.kube/config)\"\nKUBECTL=\"kubectl --kubeconfig=${KUBECONFIG}\"\nAAD_POD_ID_TAINT_KEY={{GetAADPodIdentityTaintKey}}\n\nif ! ${KUBECTL} get daemonsets -n kube-system -o json | jq -e -r '.items[] | select(.metadata.name == \"nmi\")' > /dev/null; then\n  for node in $(${KUBECTL} get nodes -o json | jq -e -r '.items[] | .metadata.name'); do\n    ${KUBECTL} taint nodes $node $AAD_POD_ID_TAINT_KEY:NoSchedule- 2>&1 | grep -v 'not found';\n  done\n  exit 0\nfi\nfor pod in $(${KUBECTL} get pods -n kube-system -o json | jq -r '.items[] | select(.status.phase == \"Running\") | .metadata.name'); do\n  if [[ \"$pod\" =~ ^nmi ]]; then\n    ${KUBECTL} taint nodes $(${KUBECTL} get pod ${pod} -n kube-system -o json | jq -r '.spec.nodeName') $AAD_POD_ID_TAINT_KEY:NoSchedule- 2>&1 | grep -v 'not found';\n  fi;\ndone\nexit 0\n#EOF\n", "num_lines": 20}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwhile IFS= read -r -d '' f; do\n  len=${#f}\n  mv ${f} ${f::len-4}\ndone < <(find . -name \"*.err\" -print0)\n", "num_lines": 7}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e -x -o pipefail\n\nGOTAG=\"1.13.7\"\nDOCKERARGS=\"--network=host\"\n\nOUTDIR=\"$(pwd)/_output\"\nif [ ! -d $OUTDIR ]; then\n    mkdir $OUTDIR\nfi\n\ncat <<EOF > $OUTDIR/buildcri.sh\nset -e -x -o pipefail\nexport GOOS=windows\nexport GOARCH=amd64\ngo get github.com/Microsoft/hcsshim\ncd src/github.com/Microsoft/hcsshim\ngit rev-parse HEAD > /output/hcsshim-revision.txt\ncd \\$GOPATH\ngo build -o /output/containerd-shim-runhcs-v1.exe github.com/Microsoft/hcsshim/cmd/containerd-shim-runhcs-v1\nmkdir -p src/github.com/containerd\ncd src/github.com/containerd\npwd\ngit clone https://github.com/containerd/containerd.git\ncd containerd\ngit rev-parse HEAD > /output/containerd-revision.txt\nmake\n# make cri-release # should work, but doesn't\ncp bin/ctr.exe /output\n#cp bin/containerd.exe /output # missing CRI plugin, so build from containerd/cri\ncd \\$GOPATH\ncd src/github.com/containerd\ngit clone https://github.com/jterry75/cri.git\ncd cri\ngit checkout windows_port\ngit rev-parse HEAD > /output/cri-revision.txt\nmake containerd\ncp _output/containerd.exe /output\napt update\napt install -y zip\ncd /output\nzip windows-cri-containerd.zip *.exe *.txt *.toml\nrm -f /output/*.exe\nrm -f /output/*.txt\nEOF\nchmod +x $OUTDIR/buildcri.sh\n\ndocker run $DOCKERARGS -v $OUTDIR:/output golang:$GOTAG /bin/bash -c /output/buildcri.sh\n", "num_lines": 50}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\nset -o errexit\nset -o nounset\nset -o pipefail\n\nrequired_env_vars=(\n    \"CLIENT_ID\"\n    \"CLIENT_SECRET\"\n    \"LOCATION\"\n    \"RESOURCE_GROUP_NAME\"\n    \"STORAGE_ACCOUNT_NAME\"\n    \"STORAGE_CONTAINER_NAME\"\n    \"SUBSCRIPTION_ID\"\n    \"TENANT_ID\"\n)\n\nunset_vars=()\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        unset_vars+=(${v})\n    fi\ndone\n\nif (( ${#unset_vars[@]} )); then\n    echo \"Required environment variables: ${required_env_vars[@]}\"\n    echo \"Unset environment variables: ${unset_vars[@]}\"\n    exit 1\nfi\n\nCREATE_TIME=\"$(date +%s)\"\naz login --service-principal -u $CLIENT_ID -p $CLIENT_SECRET --tenant $TENANT_ID\n\nrg_exists=$(az group exists -g $RESOURCE_GROUP_NAME --subscription $SUBSCRIPTION_ID -o json)\nif $rg_exists ; then\n    echo \"resource group '${RESOURCE_GROUP_NAME}' exists\"\nelse\n    echo \"creating new resource group: ${RESOURCE_GROUP_NAME}\"\n    az group create -l $LOCATION -g $RESOURCE_GROUP_NAME --subscription $SUBSCRIPTION_ID\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n    echo \"creating new storage account: ${STORAGE_ACCOUNT_NAME}...\"\n    az storage account create -n $STORAGE_ACCOUNT_NAME -g $RESOURCE_GROUP_NAME --sku \"Standard_RAGRS\" --tags \"now=${CREATE_TIME}\"\nelse\n    echo \"storage account '${STORAGE_ACCOUNT_NAME}' already exists.\"\nfi\n\nexists=$(az storage container exists -n ${STORAGE_CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT_NAME} -o json | jq -r .exists)\nif ! $exists ; then\n    echo \"creating new storage container: ${STORAGE_CONTAINER_NAME}...\"\n    key=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $RESOURCE_GROUP_NAME -o json | jq -r '.[0].value')\n    az storage container create --name $STORAGE_CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key=$key --public-access=blob\nelse\n    echo \"storage container '${STORAGE_CONTAINER_NAME}' already exists.\"\nfi\n\ntemp_dir=$(mktemp -d -t aks-engine-XXXXXXXX)\nzip_name=windows-provisioning-scripts-${CREATE_TIME}.zip\nzip_path=\"${temp_dir}/$zip_name\"\necho \"creating provisioning ${zip_path}...\"\nzip -j $zip_path ./staging/provisioning/windows/*\n\necho \"uploading zip to storage account...\"\naz storage copy --source-local-path $zip_path --destination-account-name $STORAGE_ACCOUNT_NAME --destination-container $STORAGE_CONTAINER_NAME\n\nrm -r -f $temp_dir\necho \"\"\necho \"https://${STORAGE_ACCOUNT_NAME}.blob.core.windows.net/${STORAGE_CONTAINER_NAME}/${zip_name}\"", "num_lines": 73}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o pipefail\nsource /opt/azure/containers/provision_source.sh\n\nclusterInfo() {\n    if [ -f .kube/config ]; then\n        FIRST_MASTER_READY=$(retrycmd_no_stats 3 3 10 kubectl get nodes -l node-role.kubernetes.io/master | grep Ready | sort | head -n 1 | cut -d ' ' -f 1)\n        if [[ \"${FIRST_MASTER_READY}\" == \"${HOSTNAME}\" ]]; then\n            retrycmd_no_stats 3 5 300 kubectl cluster-info dump --namespace=kube-system --output-directory=${OUTDIR}/cluster-info\n        fi\n    fi\n}\n\ncollectCloudProviderJson() {\n    local DIR=${OUTDIR}/etc/kubernetes\n    mkdir -p ${DIR}\n    if [ -f /etc/kubernetes/azure.json ]; then\n        jq . /etc/kubernetes/azure.json | grep -v aadClient > ${DIR}/azure.json\n    fi\n    if [ -f /etc/kubernetes/azurestackcloud.json ]; then\n        jq . /etc/kubernetes/azurestackcloud.json > ${DIR}/azurestackcloud.json\n    fi\n    if [ -f /etc/kubernetes/network_interfaces.json ]; then\n        cp /etc/kubernetes/network_interfaces.json ${DIR}\n    fi\n    if [ -f /etc/kubernetes/interfaces.json ]; then\n        cp /etc/kubernetes/interfaces.json ${DIR}\n    fi\n    if [ -f /opt/azure/vhd-install.complete ]; then\n        mkdir -p ${OUTDIR}/opt/azure\n        cp /opt/azure/vhd-install.complete ${OUTDIR}/opt/azure\n    fi\n}\n\ncollectDirLogs() {\n    local DIR=${OUTDIR}${1}\n    if [ -d ${1} ]; then\n        mkdir -p ${DIR}\n        cp ${1}/*.log ${DIR}\n    fi\n}\n\ncollectDir() {\n    local DIR=${OUTDIR}${1}\n    if [ -d ${1} ]; then\n        mkdir -p ${DIR}\n        cp ${1}/* ${DIR}\n    fi\n}\n\ncollectDaemonLogs() {\n    local DIR=${OUTDIR}/daemons\n    mkdir -p ${DIR}\n    if systemctl list-units --no-pager | grep -q ${1}; then\n        timeout 15 systemctl status ${1} &> ${DIR}/${1}.status\n        timeout 15 journalctl --utc -o short-iso --no-pager -r -u ${1} &> /tmp/${1}.log\n        tac /tmp/${1}.log > ${DIR}/${1}.log\n    fi\n}\n\ncollectEtcdMetrics() {\n    local DIR=${OUTDIR}/daemons\n    mkdir -p ${DIR}\n    if [ -f .kube/config ]; then\n        curl -L http://$(hostname -i):2480/metrics | grep -v debugging > ${DIR}/etcd.metrics\n    fi\n}\n\ncollectContainerLogs() {\n    local DIR=${OUTDIR}/containers\n    mkdir -p ${DIR}\n    find /var/log/containers -name \"${1}*\" -exec cp {} ${DIR} \\;\n}\n\ncompressLogsDirectory() {\n    sync\n    ZIP=\"/tmp/logs.zip\"\n    rm -f ${ZIP}\n    (cd ${OUTDIR}/.. && zip -q -r ${ZIP} ${HOSTNAME})\n}\n\n# AzS headers\nstackfy() {\n    # Azure Stack can store/ingest these files in a Edge Kusto DB.\n    # Data team asked for metadata to simplify queries. It is added as a header to each file.\n    RESOURCE_GROUP=$(sudo jq -r '.resourceGroup' /etc/kubernetes/azure.json)\n    SUB_ID=$(sudo jq -r '.subscriptionId' /etc/kubernetes/azure.json)\n    TENANT_ID=$(sudo jq -r '.tenantId' /etc/kubernetes/azure.json)\n    if [ \"${TENANT_ID}\" == \"adfs\" ]; then\n        TENANT_ID=$(sudo jq -r '.serviceManagementEndpoint' /etc/kubernetes/azurestackcloud.json | cut -d / -f4)\n    fi\n\n    stackfyKubeletLog\n    stackfyMobyLog\n    stackfyEtcdLog\n    stackfyFileNames /var/log\n    stackfyFileNames /var/log/azure\n    stackfyClusterInfo\n    stackfyNetwork\n}\n\nstackfyKubeletLog() {\n    KUBELET_VERSION=$(kubelet --version | grep -oh -E 'v.*$')\n    KUBELET_VERBOSITY=$(grep -e '--v=[0-9]' -oh /etc/systemd/system/kubelet.service | grep -e '[0-9]' -oh /etc/systemd/system/kubelet.service | head -n 1)\n    KUBELET_LOG_FILE=${OUTDIR}/daemons/k8s-kubelet.log\n    \n    {\n        echo \"== BEGIN HEADER ==\";\n        echo \"Type: Daemon\";\n        echo \"TenantId: ${TENANT_ID}\";\n        echo \"Name: kubelet\";\n        echo \"Version: ${KUBELET_VERSION}\";\n        echo \"Verbosity: ${KUBELET_VERBOSITY}\";\n        echo \"Image: \";\n        echo \"Hostname: ${HOSTNAME}\";\n        echo \"SubscriptionID: ${SUB_ID}\";\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\";\n        echo \"== END HEADER ==\"\n    } >> ${KUBELET_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/kubelet.service.log >> ${KUBELET_LOG_FILE}\n    rm ${OUTDIR}/daemons/kubelet.service.log\n}\n\nstackfyMobyLog() {\n    DOCKER_VERSION=$(docker version | grep -A 20 \"Server:\" | grep \"Version:\" | head -n 1 | cut -d \":\" -f 2 | xargs)\n    DOCKER_LOG_FILE=${OUTDIR}/daemons/k8s-docker.log\n    \n    {\n        echo \"== BEGIN HEADER ==\"\n        echo \"Type: Daemon\"\n        echo \"TenantId: ${TENANT_ID}\"\n        echo \"Name: docker\"\n        echo \"Version: ${DOCKER_VERSION}\"\n        echo \"Hostname: ${HOSTNAME}\"\n        echo \"SubscriptionID: ${SUB_ID}\"\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n        echo \"== END HEADER ==\"\n    } >> ${DOCKER_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/docker.service.log >> ${DOCKER_LOG_FILE}\n    rm ${OUTDIR}/daemons/docker.service.log\n}\n\nstackfyEtcdLog() {\n    if [ ! -f /usr/bin/etcd ]; then\n        return\n    fi\n\n    ETCD_VERSION=$(/usr/bin/etcd --version | grep \"etcd Version:\" | cut -d \":\" -f 2 | xargs)\n    ETCD_LOG_FILE=${OUTDIR}/daemons/k8s-etcd.log\n    \n    {\n        echo \"== BEGIN HEADER ==\"\n        echo \"Type: Daemon\"\n        echo \"TenantId: ${TENANT_ID}\"\n        echo \"Name: etcd\"\n        echo \"Version: ${ETCD_VERSION}\"\n        echo \"Hostname: ${HOSTNAME}\"\n        echo \"SubscriptionID: ${SUB_ID}\"\n        echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n        echo \"== END HEADER ==\"\n    } >> ${ETCD_LOG_FILE}\n\n    cat ${OUTDIR}/daemons/etcd.service.log >> ${ETCD_LOG_FILE}\n    rm ${OUTDIR}/daemons/etcd.service.log\n}\n\nstackfyClusterInfo() {\n    if [ ! -f ${OUTDIR}/cluster-info/nodes.json ]; then\n        return\n    fi\n    mkdir -p ${OUTDIR}/containers\n    for SRC in \"${OUTDIR}\"/cluster-info/kube-system/kube-controller-manager-*/logs.txt; do\n        KCM_VERBOSITY=$(grep -e \"--v=[0-9]\" -oh /etc/kubernetes/manifests/kube-controller-manager.yaml | grep -e \"[0-9]\" -oh | head -n 1)\n        KCM_IMAGE=$(grep image: /etc/kubernetes/manifests/kube-controller-manager.yaml | xargs | cut -f 2 -d \" \")\n        KCM_DIR=$(dirname ${SRC})\n        KCM_NAME=$(basename ${KCM_DIR})\n        KCM_LOG_FILE=${OUTDIR}/containers/k8s-${KCM_NAME}.log\n        \n        {\n            echo \"== BEGIN HEADER ==\"\n            echo \"Type: Container\"\n            echo \"TenantId: ${TENANT_ID}\"\n            echo \"Name: ${KCM_NAME}\"\n            echo \"Hostname: ${HOSTNAME}\"\n            echo \"ContainerID: \"\n            echo \"Image: ${KCM_IMAGE}\"\n            echo \"Verbosity: ${KCM_VERBOSITY}\"\n            echo \"SubscriptionID: ${SUB_ID}\"\n            echo \"ResourceGroup: ${RESOURCE_GROUP}\"\n            echo \"== END HEADER ==\"\n        } >> ${KCM_LOG_FILE}\n        \n        cat ${SRC} >> ${KCM_LOG_FILE}\n    done\n}\n\nstackfyNetwork() {\n    local DIR=${OUTDIR}/network\n    mkdir -p ${DIR}\n    # basic name resolution test\n    ping ${HOSTNAME} -c 3 &> ${DIR}/k8s-ping.txt\n\n    if [ -f /etc/kubernetes/azurestackcloud.json ]; then\n        LOGIN_ENDPOINT=$(jq -r .activeDirectoryEndpoint /etc/kubernetes/azurestackcloud.json)\n        LOGIN_ENDPOINT=${LOGIN_ENDPOINT#'https://'}\n        LOGIN_ENDPOINT=${LOGIN_ENDPOINT%'/'}\n        LOGIN_ENDPOINT_LOG=${DIR}/k8s-loginEndpoint.txt\n        timeout 10 nc -vz ${LOGIN_ENDPOINT} 443 \\\n        && echo \"login endpoint reachable: ${LOGIN_ENDPOINT}\" &> ${LOGIN_ENDPOINT_LOG} \\\n        || echo \"error: login endpoint not reachable: ${LOGIN_ENDPOINT}\" &> ${LOGIN_ENDPOINT_LOG}\n    fi\n}\n\nstackfyFileNames() {\n    local DIR=${OUTDIR}/${1}\n    for SRC in \"${DIR}\"/*.log; do\n        NAME=$(basename ${SRC})\n        mv ${SRC} ${DIR}/k8s-${NAME}\n    done\n}\n\nOUTDIR=\"$(mktemp -d)/${HOSTNAME}\"\n\ncollectCloudProviderJson\ncollectDirLogs /var/log\ncollectDirLogs /var/log/azure\ncollectDirLogs /var/log/kubeaudit\ncollectDir /etc/kubernetes/manifests\ncollectDir /etc/kubernetes/addons\ncollectContainerLogs cloud-controller-manager\ncollectContainerLogs kube-addon-manager\ncollectContainerLogs kube-apiserver\ncollectContainerLogs kube-controller-manager\ncollectContainerLogs kube-scheduler\ncollectDaemonLogs kubelet.service\ncollectDaemonLogs etcd.service\ncollectDaemonLogs docker.service\ncollectEtcdMetrics\nclusterInfo\n\nif [ \"${AZURE_ENV}\" = \"AzureStackCloud\" ]; then\n    stackfy\nfi\n\ncompressLogsDirectory\n", "num_lines": 249}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\nfiles=$(find .. -type f -iname '*.go' ! -path '../vendor/*')  # do not run on the vendor dir\n\nfor i in $files\ndo\n  if ! grep -q Copyright \"$i\"\n  then\n    cat copyright.txt \"$i\" > \"$i\".new && mv \"$i\".new \"$i\"\n  fi\ndone\n", "num_lines": 17}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n####################################################\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nDIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" && pwd )\"\nROOT=\"${DIR}/..\"\n####################################################\n\nset -x\n\nGENERATED_FILES=(\n\t\"pkg/i18n/translations_generated.go\"\n\t\"pkg/engine/templates_generated.go\"\n)\n\nT=\"$(mktemp -d)\"\ntrap 'rm -rf \"${T}\"' EXIT\n\nfor file in \"${GENERATED_FILES[@]}\"; do\n\tcp -a \"${file}\" \"${T}/\"\ndone\n\nmake generate\n\nfor file in \"${GENERATED_FILES[@]}\"; do\n\tbasefile=$(basename \"${file}\")\n\tif ! diff -r \"${T}/${basefile}\" \"${ROOT}/${file}\" 2>&1 ; then\n\t\techo \"go generate produced changes that were not already present.\"\n\t\techo \"Make sure you include generated assets in your commit.\"\n\t\texit 1\n\tfi\ndone\n\necho \"Generated assets have no material difference than what is committed.\"\n", "num_lines": 43}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -eo pipefail\n\nPROJECT_NAME=\"aks-engine-azurestack\"\n\nif [ -n \"$ACC_CLOUD\" ]; then\n  # Cloud Shell doesn't have sudo and prefers a different directory.\n  : \"${USE_SUDO:=\"false\"}\"\n  : \"${AKSE_INSTALL_DIR:=\"/usr/local/bundle/bin\"}\"\n  mkdir -p $AKSE_INSTALL_DIR\nelse\n  : \"${USE_SUDO:=\"true\"}\"\n  : \"${AKSE_INSTALL_DIR:=\"/usr/local/bin\"}\"\nfi\n\n# initArch discovers the architecture for this system.\ninitArch() {\n  ARCH=$(uname -m)\n  case $ARCH in\n    armv5*) ARCH=\"armv5\";;\n    armv6*) ARCH=\"armv6\";;\n    armv7*) ARCH=\"arm\";;\n    aarch64) ARCH=\"arm64\";;\n    x86) ARCH=\"386\";;\n    x86_64) ARCH=\"amd64\";;\n    i686) ARCH=\"386\";;\n    i386) ARCH=\"386\";;\n  esac\n}\n\n# initOS discovers the operating system for this system.\ninitOS() {\n  OS=$(uname | tr '[:upper:]' '[:lower:]')\n\n  case \"$OS\" in\n    # Minimalist GNU for Windows\n    mingw*) OS='windows';;\n  esac\n}\n\n# runs the given command as root (detects if we are root already)\nrunAsRoot() {\n  local CMD=\"$*\"\n\n  if [ $EUID -ne 0 ] && [ \"$USE_SUDO\" = \"true\" ]; then\n    CMD=\"sudo $CMD\"\n  fi\n\n  $CMD\n}\n\n# verifySupported checks that the os/arch combination is supported for\n# binary builds.\nverifySupported() {\n  local supported=\"darwin-386\\ndarwin-amd64\\nlinux-386\\nlinux-amd64\\nlinux-arm\\nlinux-arm64\\nlinux-ppc64le\\nwindows-386\\nwindows-amd64\"\n  if ! echo \"${supported}\" | grep -q \"${OS}-${ARCH}\"; then\n    echo \"No prebuilt binary for ${OS}-${ARCH}.\"\n    echo \"To build from source, go to https://github.com/Azure/aks-engine-azurestack\"\n    exit 1\n  fi\n\n  if ! type \"curl\" > /dev/null && ! type \"wget\" > /dev/null; then\n    echo \"Either curl or wget is required\"\n    exit 1\n  fi\n\n  if ! type \"jq\" > /dev/null; then\n    echo \"jq is required\"\n    exit 1\n  fi\n}\n\n# checkDesiredVersion checks if the desired version is available.\ncheckDesiredVersion() {\n  # Use the GitHub releases API for the project to find the desired version for this project.\n  local release_url\n  if [[ -z \"${DESIRED_VERSION}\" ]]; then\n    release_url=\"https://api.github.com/repos/Azure/aks-engine-azurestack/releases/latest\"\n  else\n    release_url=\"https://api.github.com/repos/Azure/aks-engine-azurestack/releases/tags/${DESIRED_VERSION}\"\n  fi\n\n  # shellcheck disable=SC2086\n  local requestCmd\n  if type \"curl\" > /dev/null; then\n    requestCmd=\"curl -Ssl \"\n    if [[ -n \"${GITHUB_TOKEN}\" ]]; then\n      requestCmd+=\"-H 'Authorization: token ${GITHUB_TOKEN}'\"\n    fi\n    requestCmd+=\" --fail ${release_url}\"\n  elif type \"wget\" > /dev/null; then\n    requestCmd=\"wget -nv \"\n    if [[ -n \"${GITHUB_TOKEN}\" ]]; then\n      requestCmd+=\"--header='Authorization: token ${GITHUB_TOKEN}'\"\n    fi\n    requestCmd+=\" -O - ${release_url}\"\n  fi\n\n  local response\n  if ! response=$(eval \"${requestCmd}\") ; then\n    echo \"Failed requesting release for ${DESIRED_VERSION} tag from GitHub API.\"\n    exit 1\n  fi\n\n  TAG=$(jq -r '.name | values' <<< \"${response}\")\n  if [[ -z \"${TAG}\" ]]; then\n    echo \"Cannot determine ${DESIRED_VERSION} tag.\"\n    exit 1\n  fi\n}\n\n# checkAKSEInstalledVersion checks which version of AKSE is installed and\n# if it needs to be changed.\ncheckAKSEInstalledVersion() {\n  if [[ -f \"${AKSE_INSTALL_DIR}/${PROJECT_NAME}\" ]]; then\n    local version\n    version=$(aks-engine version | grep 'Version' | cut -d' ' -f2)\n    if [[ \"$version\" == \"$TAG\" ]]; then\n      echo \"AKS-Engine ${version} is already ${DESIRED_VERSION:-latest}\"\n      return 0\n    else\n      echo \"AKS-Engine ${TAG} is available. Changing from version ${version}.\"\n      return 1\n    fi\n  else\n    return 1\n  fi\n}\n\n# downloadFile downloads the latest binary package and also the checksum\n# for that binary.\ndownloadFile() {\n  AKSE_DIST=\"aks-engine-azurestack-$TAG-$OS-$ARCH.tar.gz\"\n  DOWNLOAD_URL=\"https://github.com/Azure/aks-engine-azurestack/releases/download/$TAG/$AKSE_DIST\"\n  AKSE_TMP_ROOT=\"$(mktemp -dt akse-installer-XXXXXX)\"\n  AKSE_TMP_FILE=\"$AKSE_TMP_ROOT/$AKSE_DIST\"\n  echo \"Downloading $DOWNLOAD_URL\"\n  if type \"curl\" > /dev/null; then\n    curl -SsL \"$DOWNLOAD_URL\" -o \"$AKSE_TMP_FILE\"\n  elif type \"wget\" > /dev/null; then\n    wget -q -O \"$AKSE_TMP_FILE\" \"$DOWNLOAD_URL\"\n  fi\n}\n\n# installFile vunpacks and installs it.\ninstallFile() {\n  AKSE_TMP=\"$AKSE_TMP_ROOT/$PROJECT_NAME\"\n\n  mkdir -p \"$AKSE_TMP\"\n  tar xf \"$AKSE_TMP_FILE\" -C \"$AKSE_TMP\"\n  AKSE_TMP_BIN=\"$AKSE_TMP/$PROJECT_NAME-$TAG-$OS-$ARCH\"\n  echo \"Preparing to install $PROJECT_NAME into ${AKSE_INSTALL_DIR}\"\n  runAsRoot cp \"$AKSE_TMP_BIN/$PROJECT_NAME\" \"$AKSE_INSTALL_DIR\"\n  echo \"$PROJECT_NAME installed into $AKSE_INSTALL_DIR/$PROJECT_NAME\"\n}\n\n# fail_trap is executed if an error occurs.\nfail_trap() {\n  result=$?\n  if [ \"$result\" != \"0\" ]; then\n    if [[ -n \"$INPUT_ARGUMENTS\" ]]; then\n      echo \"Failed to install $PROJECT_NAME with the arguments provided: $INPUT_ARGUMENTS\"\n      help\n    else\n      echo \"Failed to install $PROJECT_NAME\"\n    fi\n    echo -e \"\\tFor support, go to https://github.com/Azure/aks-engine-azurestack.\"\n  fi\n  cleanup\n  exit $result\n}\n\n# testVersion tests the installed client to make sure it is working.\ntestVersion() {\n  set +e\n  if [ \"$?\" = \"1\" ]; then\n    # shellcheck disable=SC2016\n    echo \"$PROJECT_NAME not found. Is $AKSE_INSTALL_DIR on your \"'$PATH?'\n    exit 1\n  fi\n  set -e\n  echo \"Run '$PROJECT_NAME version' to test.\"\n}\n\n# help provides possible cli installation arguments\nhelp () {\n  echo \"Accepted cli arguments are:\"\n  echo -e \"\\t[--help|-h ] ->> prints this help\"\n  echo -e \"\\t[--version|-v <desired_version>] . When not defined it defaults to latest\"\n  echo -e \"\\te.g. --version v0.32.3  or -v latest\"\n  echo -e \"\\t[--no-sudo]  ->> install without sudo\\n\"\n  echo -e \"\\tIf GITHUB_TOKEN env var is set, it will be used to fetch releases via the GitHub API.\\n\"\n}\n\n# cleanup temporary files\ncleanup() {\n  if [[ -d \"${AKSE_TMP_ROOT:-}\" ]]; then\n    rm -rf \"$AKSE_TMP_ROOT\"\n  fi\n}\n\n# Execution\n\n#Stop execution on any error\ntrap \"fail_trap\" EXIT\nset -e\n\n# Parsing input arguments (if any)\nexport INPUT_ARGUMENTS=( \"${@}\" )\nset -u\nwhile [[ $# -gt 0 ]]; do\n  case $1 in\n    '--version'|-v)\n       shift\n       if [[ $# -ne 0 ]]; then\n           export DESIRED_VERSION=\"${1}\"\n       else\n           echo -e \"Please provide the desired version. e.g. --version v0.32.3 or -v latest\"\n           exit 0\n       fi\n       ;;\n    '--no-sudo')\n       USE_SUDO=\"false\"\n       ;;\n    '--help'|-h)\n       help\n       exit 0\n       ;;\n    *) exit 1\n       ;;\n  esac\n  shift\ndone\nset +u\n\ninitArch\ninitOS\nverifySupported\ncheckDesiredVersion\nif ! checkAKSEInstalledVersion; then\n  downloadFile\n  installFile\nfi\ntestVersion\ncleanup\n", "num_lines": 250}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n# IMPORTANT: This script is meant for use only within CI environments as it assumes the linux amd64 architecture.\n\necho \"==> Downloading kubectl version ${KUBECTL_VERSION} <==\"\n\ncurl -L https://storage.googleapis.com/kubernetes-release/release/v\"${KUBECTL_VERSION}\"/bin/linux/amd64/kubectl -o /usr/local/bin/kubectl\nchmod +x /usr/local/bin/kubectl\n", "num_lines": 12}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nWORKFLOW_FROM_BRANCH=${WORKFLOW_FROM_BRANCH:-master}\necho WORKFLOW_FROM_BRANCH=${WORKFLOW_FROM_BRANCH}\n\nRELEASE_REPOSITORY=${RELEASE_REPOSITORY:-Azure/aks-engine-azurestack}\necho RELEASE_REPOSITORY=${RELEASE_REPOSITORY}\n\nif [[ -z ${RELEASE_VERSION} ]]; then\n  echo \"RELEASE_VERSION is not set (e.x.: v0.76.0, v0.76.1)\"\n  exit 1\nfi\necho RELEASE_VERSION=${RELEASE_VERSION}\n\nif [[ -z ${RELEASE_FROM_BRANCH} ]]; then\n  echo \"RELEASE_FROM_BRANCH is not set (e.x: master, patch-release-v0.76.1)\"\n  exit 1\nfi\necho RELEASE_FROM_BRANCH=${RELEASE_FROM_BRANCH}\n\ngh workflow run create-release-branch.yaml \\\n  --ref ${WORKFLOW_FROM_BRANCH} \\\n  -R ${RELEASE_REPOSITORY} \\\n  -f release_version=${RELEASE_VERSION} \\\n  -f from_branch=${RELEASE_FROM_BRANCH}\n", "num_lines": 29}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ncovermode=${COVERMODE:-atomic}\ncoverdir=$(mktemp -d /tmp/coverage.XXXXXXXXXX)\nprofile=\"${coverdir}/cover.out\"\ncoveragetxt=\"coverage.txt\"\n\ngenerate_cover_data() {\n  ginkgo version\n  ginkgo -mod=vendor -skipPackage test/e2e -failFast -cover -r -v -tags=fast -ldflags \"${LDFLAGS}\" .\n  echo \"\" > ${coveragetxt}\n  find . -type f -name \"*.coverprofile\" | while read -r file;  do cat \"$file\" >> ${coveragetxt} && mv \"$file\" \"${coverdir}\"; done\n  echo \"mode: $covermode\" >\"$profile\"\n  grep -h -v \"^mode:\" \"$coverdir\"/*.coverprofile >>\"$profile\"\n}\n\npush_to_codecov() {\n  bash <(curl -s https://codecov.io/bash) || echo \"push to codecov failed\"\n}\n\ngenerate_cover_data\ngo tool cover -func \"${profile}\"\n\ncase \"${1-}\" in\n  --html)\n    go tool cover -html \"${profile}\"\n    ;;\n  --codecov)\n    push_to_codecov\n    ;;\nesac\n", "num_lines": 48}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nscripts/update-translation.sh -l en_US -p\n\nmv acsengine.po translations/en_US/LC_MESSAGES/acsengine.po\nrm acsengine.pot\n", "num_lines": 10}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nGO_SOURCE=\"pkg/engine/*.go pkg/engine/transform/*.go pkg/api/*.go pkg/operations/*.go pkg/operations/kubernetesupgrade/*.go\"\nLANGUAGE=\"en_US\"\nDOMAIN=\"acsengine\"\ngenerate_po=\"false\"\ngenerate_mo=\"false\"\n\nwhile getopts \"hl:pm\" opt; do\n  case $opt in\n    h)\n      echo \"$0 [-l language] [-p] [-m]\"\n      echo \" -l <language>: Language to translate\"\n      echo \" -p extract strings and generate PO file\"\n      echo \" -m generate MO file\"\n      exit 0\n      ;;\n    l)\n      LANGUAGE=\"${OPTARG}\"\n      ;;\n    p)\n      generate_po=\"true\"\n      ;;\n    m)\n      generate_mo=\"true\"\n      ;;\n    \\?)\n      echo \"$0 [-l language] [-p] [-m]\"\n      exit 1\n      ;;\n  esac\ndone\n\nif ! command -v go-xgettext > /dev/null; then\n  echo 'Can not find go-xgettext, install with:'\n  echo 'go get github.com/JiangtianLi/gettext/go-xgettext'\n  exit 1\nfi\n\nif ! command -v msginit > /dev/null; then\n  echo 'Can not find msginit, install with:'\n  echo 'apt-get install gettext'\n  exit 1\nfi\n\nif [[ \"${generate_po}\" == \"true\" ]]; then\n  echo \"Extract strings and generate PO files...\"\n  go-xgettext -o ${DOMAIN}.pot --keyword=Translator.Errorf --keyword-plural=Translator.NErrorf --msgid-bugs-address=\"\" --sort-output \"${GO_SOURCE}\"\n  msginit -l \"${LANGUAGE}\" -o ${DOMAIN}.po -i ${DOMAIN}.pot\nfi\n\nif [[ \"${generate_mo}\" == \"true\" ]]; then\n  echo \"Generate MO file...\"\n  if [ ! -f ${DOMAIN}.po ]; then\n    echo \"${DOMAIN}.po not found!\"\n\texit 1\n  fi\n  msgfmt -c -v -o ${DOMAIN}.mo ${DOMAIN}.po\nfi\n", "num_lines": 63}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\necho \"==> Checking copyright headers <==\"\n\nfiles=$(find . -type f -iname '*.go' ! -path './vendor/*' ! -path './hack/tools/*' ! -path './test/e2e/vendor/*')\nlicRes=$(for file in $files; do\n           awk 'NR<=4' \"$file\" | grep -Eq \"(Copyright|generated|GENERATED)\" || echo \"$file\";\n         done)\n\nif [ -n \"$licRes\" ]; then\n        echo \"Copyright header check failed:\";\n        echo \"${licRes}\";\n        exit 1;\nfi\n", "num_lines": 20}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nexit_code=0\n\necho \"==> Running go mod check <==\"\n\ngit diff --exit-code --quiet go.mod go.sum vendor/modules.txt\nerror_code=$?\n\nif [ $error_code -ne 0 ]; then\n  git --no-pager diff go.mod go.sum vendor/modules.txt\n  echo \"The dependency state is out of sync. Please commit changes to go.mod, go.sum.\"\nelse\n  echo \"go mod ok.\"\nfi\n\nexit $error_code\n", "num_lines": 21}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors All rights reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nset -euo pipefail\n\necho\necho \"==> Running Go linter <==\"\ngolangci-lint --version\nif [ -f /.dockerenv ]; then\n    echo \"Running inside container\";\nfi\n\ngolangci-lint run --modules-download-mode=vendor\n", "num_lines": 26}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\nset -euo pipefail\n\necho \"==> Running shell linter <==\"\nshellcheck --version\nif [ -f /.dockerenv ]; then\n    echo \"Running inside container\";\nfi\n\n# All shell scripts, except those that support deprecated orchestrators or are in vendored code.\nfiles=$(find . -type f -name \"*.sh\" -not -path './vendor/*' -not -path './hack/tools/*' -not -path './test/e2e/vendor/*')\n\nIGNORED=\"\nSC1127\nSC1009\nSC1054\nSC1056\nSC1072\nSC1073\nSC1083\nSC1090\nSC1091\nSC2004\nSC2015\nSC2034\nSC2046\nSC2053\nSC2068\nSC2086\nSC2128\nSC2145\nSC2154\nSC2206\n\"\n\nshellcheck $(printf -- \"-e %s \" $IGNORED) $files\n", "num_lines": 41}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\nset -euo pipefail\n\nfunction validate_package() {\n    local package_url=$1\n\n    temp_dir=$(mktemp -d -t aks-engine-XXXXXXXX)\n    echo \"Downloading $package_version to $temp_dir/scripts.zip\"\n    curl -L \"$package_url\" -o \"$temp_dir/scripts.zip\"\n\n    echo \"Extracting files to $temp_dir/scripts\"\n    unzip \"$temp_dir/scripts.zip\" -d \"$temp_dir/scripts\"\n\n    # Perform a recursive diff of the two directories but ignore comments since checked in powershell files\n    # will not container signature blocks at the end of the files.\n    diff -bBr --ignore-matching-lines='^#' \"$temp_dir/scripts\" \"./staging/provisioning/windows/\"\n\n    echo \"Files match\"\n}\n\necho \"Validating content of Windows provisioning scripts...\"\npackage_version=$(grep  \"DefaultWindowsProvisioningScriptsPackageVersion\" ./pkg/api/const.go  | cut -d ' ' -f 3 | cut -d '\"' -f2)\n\necho \"Package version: $package_version\"\nif [ -z \"$package_version\" ]; then\n    echo \"Could not find value for 'DefaultWindowsProvisioningScriptsPackageVersion' in /pkg/api/const.go\"\n    exit 1\nfi\n\n# urls from pkg/api/azenvtypes.go\nvalidate_package \"https://kubernetesartifacts.azureedge.net/aks-engine/windows/provisioning/signedscripts-${package_version}.zip\"\nvalidate_package \"https://mirror.azk8s.cn/aks-engine/windows/provisioning/signedscripts-${package_version}.zip\"\n\n", "num_lines": 37}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\n\nGOPATH=\"/go\"\nWORK_DIR=\"/aks-engine\"\n\n# Assumes we're running from the git root of aks-engine\ndocker run --rm \\\n-v $(pwd):${WORK_DIR} \\\n-w ${WORK_DIR} \\\n\"${DEV_IMAGE}\" make build-binary || exit 1\n", "num_lines": 13}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_ID\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID_TO_CLEANUP\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID_TO_CLEANUP env var\"\n    exit 1;\nfi\n\nif [ -z \"$EXPIRATION_IN_HOURS\" ]; then\n    EXPIRATION_IN_HOURS=2\nfi\n\nif az login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null; then\n    echo \"Successfully logged in using service principal\"\nelse\n    exit 1\nfi\n\n# set to the sub id we want to cleanup\nif az account set -s $SUBSCRIPTION_ID_TO_CLEANUP; then\n    echo \"Successfully set subscription\"\nelse\n    exit 1\nfi\n\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n# find resource groups created before our deadline\necho \"Looking for resource groups created over ${EXPIRATION_IN_HOURS} hours ago...\"\nif [ -z \"$RESOURCE_GROUP_SUBSTRING\" ]; then\n  for resourceGroup in $(az group list | jq --arg dl $deadline '.[] | select(.name | contains(\"acse-test\") or contains(\"aksimages\") or contains(\"NetworkWatcherRG\") | not) | select(.tags.now < $dl).name' | tr -d '\\\"' || true); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || true); do\n      echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n      az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n  done\nelse\n  for resourceGroup in $(az group list | jq --arg dl $deadline --arg rg $RESOURCE_GROUP_SUBSTRING '.[] | select(.name | contains(\"acse-test\") or contains(\"aksimages\") or contains (\"NetworkWatcherRG\") | not) | select(.name | contains($rg)) | select(.tags.now < $dl).name' | tr -d '\\\"' || true); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || true); do\n      echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n      az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n  done\nfi\n", "num_lines": 72}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nTMP_DIR=$(mktemp -d \"$(pwd)/XXXXXXXXXXXX\")\nTMP_BASENAME=$(basename ${TMP_DIR})\nGOPATH=\"/go\"\nWORK_DIR=\"/aks-engine-azurestack\"\nMASTER_VM_UPGRADE_SKU=\"${MASTER_VM_UPGRADE_SKU:-Standard_D4_v3}\"\nNODE_VM_UPGRADE_SKU=\"${NODE_VM_UPGRADE_SKU:-Standard_D4_v3}\"\nAZURE_ENV=\"${AZURE_ENV:-AzurePublicCloud}\"\nIDENTITY_SYSTEM=\"${IDENTITY_SYSTEM:-azure_ad}\"\nARC_LOCATION=\"eastus\"\nGINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST:-false}\"\nTEST_PVC=\"${TEST_PVC:-false}\"\nCLEAN_PVC=\"${CLEAN_PVC:-true}\"\nROTATE_CERTS=\"${ROTATE_CERTS:-false}\"\nVALIDATE_CPU_LOAD=\"${VALIDATE_CPU_LOAD:-false}\"\nmkdir -p _output || exit 1\n\n# Assumes we're running from the git root of aks-engine\nif [ \"${BUILD_AKS_ENGINE}\" = \"true\" ]; then\n  docker run --rm \\\n  -v $(pwd):${WORK_DIR} \\\n  -w ${WORK_DIR} \\\n  \"${DEV_IMAGE}\" make build-binary || exit 1\nfi\n\ncat > ${TMP_DIR}/apimodel-input.json <<END\n${API_MODEL_INPUT}\nEND\n\n# Jenkinsfile will yield a null $ADD_NODE_POOL_INPUT if not set in the test job config\nif [ \"$ADD_NODE_POOL_INPUT\" == \"null\" ]; then\n  ADD_NODE_POOL_INPUT=\"\"\nfi\nif [ \"$LB_TEST_TIMEOUT\" == \"\" ]; then\n  LB_TEST_TIMEOUT=\"${E2E_TEST_TIMEOUT}\"\nfi\nif [ \"$STABILITY_ITERATIONS\" == \"\" ]; then\n  STABILITY_ITERATIONS=3\nfi\nif [ \"$STABILITY_ITERATIONS_SUCCESS_RATE\" == \"\" ]; then\n  STABILITY_ITERATIONS_SUCCESS_RATE=1.0\nfi\nif [ \"$SINGLE_COMMAND_TIMEOUT_MINUTES\" == \"\" ]; then\n  SINGLE_COMMAND_TIMEOUT_MINUTES=1\nfi\nif [ \"$STABILITY_TIMEOUT_SECONDS\" == \"\" ]; then\n  STABILITY_TIMEOUT_SECONDS=5\nfi\nif [ \"$RUN_VMSS_NODE_PROTOTYPE\" == \"\" ]; then\n  RUN_VMSS_NODE_PROTOTYPE=\"false\"\nfi\n\nif [ -n \"$PRIVATE_SSH_KEY_FILE\" ]; then\n  PRIVATE_SSH_KEY_FILE=$(realpath --relative-to=$(pwd) ${PRIVATE_SSH_KEY_FILE})\nfi\n\nfunction tryExit {\n  if [ \"${AZURE_ENV}\" != \"AzureStackCloud\" ]; then\n    exit 1\n  fi\n}\n\nfunction renameResultsFile {\n  JUNIT_PATH=$(pwd)/test/e2e/kubernetes/junit.xml\n  if [ \"${AZURE_ENV}\" == \"AzureStackCloud\" ] && [ -f ${JUNIT_PATH} ]; then\n    mv ${JUNIT_PATH} $(pwd)/test/e2e/kubernetes/${1}-junit.xml\n  fi\n}\n\nfunction rotateCertificates {\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e REGION=${REGION} \\\n    -e RESOURCE_GROUP=${RESOURCE_GROUP} \\\n    ${DEV_IMAGE} \\\n    ./bin/aks-engine-azurestack rotate-certs \\\n    --api-model _output/${RESOURCE_GROUP}/apimodel.json \\\n    --ssh-host ${API_SERVER} \\\n    --location ${REGION} \\\n    --linux-ssh-private-key _output/${RESOURCE_GROUP}-ssh \\\n    --resource-group ${RESOURCE_GROUP} \\\n    --client-id ${AZURE_CLIENT_ID} \\\n    --client-secret ${AZURE_CLIENT_SECRET} \\\n    --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n    --azure-env ${AZURE_ENV} \\\n    --identity-system ${IDENTITY_SYSTEM} \\\n    --debug\n\n  # Retry if it fails the first time (validate --certificate-profile instead of regenerating a new set of certs)\n  exit_code=$?\n  if [ $exit_code -ne 0 ]; then\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"jq '.properties.certificateProfile' _output/${RESOURCE_GROUP}/_rotate_certs_output/apimodel.json > _output/${RESOURCE_GROUP}/certificateProfile.json\" || exit 1\n\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e REGION=${REGION} \\\n      -e RESOURCE_GROUP=${RESOURCE_GROUP} \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine-azurestack rotate-certs \\\n      --api-model _output/${RESOURCE_GROUP}/apimodel.json \\\n      --ssh-host ${API_SERVER} \\\n      --location ${REGION} \\\n      --linux-ssh-private-key _output/${RESOURCE_GROUP}-ssh \\\n      --resource-group ${RESOURCE_GROUP} \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --certificate-profile _output/${RESOURCE_GROUP}/certificateProfile.json --force \\\n      --azure-env ${AZURE_ENV} \\\n      --identity-system ${IDENTITY_SYSTEM} \\\n      --debug\n\n    exit $?\n  fi\n}\n\necho \"Running E2E tests against a cluster built with the following API model:\"\ncat ${TMP_DIR}/apimodel-input.json\n\nCLEANUP_AFTER_DEPLOYMENT=${CLEANUP_ON_EXIT}\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ] || [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  CLEANUP_AFTER_DEPLOYMENT=\"false\"\nfi\n\nif [ -n \"${GINKGO_SKIP}\" ]; then\n  if [ -n \"${GINKGO_SKIP_AFTER_SCALE_DOWN}\" ]; then\n    SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_SCALE_DOWN}\"\n  else\n    SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP}\"\n  fi\n  if [ -n \"${GINKGO_SKIP_AFTER_SCALE_UP}\" ]; then\n    SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_SCALE_UP}\"\n  else\n    SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP}\"\n  fi\n  if [ -n \"${GINKGO_SKIP_AFTER_UPGRADE}\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${GINKGO_SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}\"\n  fi\n  if [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${SKIP_AFTER_SCALE_DOWN}|${SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP}|${SKIP_AFTER_UPGRADE}\"\n  fi\nelse\n  SKIP_AFTER_SCALE_DOWN=\"${GINKGO_SKIP_AFTER_SCALE_DOWN}\"\n  SKIP_AFTER_SCALE_UP=\"${GINKGO_SKIP_AFTER_SCALE_UP}\"\n  if [ -n \"${GINKGO_SKIP_AFTER_UPGRADE}\" ]; then\n    SKIP_AFTER_UPGRADE=\"${GINKGO_SKIP_AFTER_UPGRADE}\"\n  else\n    SKIP_AFTER_UPGRADE=\"\"\n  fi\n  if [ \"${SCALE_CLUSTER}\" = \"true\" ] && [ \"${SKIP_AFTER_UPGRADE}\" != \"\" ]; then\n    SKIP_AFTER_UPGRADE=\"${SKIP_AFTER_SCALE_DOWN}|${SKIP_AFTER_UPGRADE}\"\n  elif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    SKIP_AFTER_UPGRADE=\"${SKIP_AFTER_SCALE_DOWN}\"\n  fi\nfi\n\ndocker run --rm \\\n-v $(pwd):${WORK_DIR} \\\n-v /etc/ssl/certs:/etc/ssl/certs \\\n-w ${WORK_DIR} \\\n-e CLUSTER_DEFINITION=${TMP_BASENAME}/apimodel-input.json \\\n-e CLIENT_ID=\"${AZURE_CLIENT_ID}\" \\\n-e CLIENT_SECRET=\"${AZURE_CLIENT_SECRET}\" \\\n-e CLIENT_OBJECTID=\"${CLIENT_OBJECTID}\" \\\n-e TENANT_ID=\"${AZURE_TENANT_ID}\" \\\n-e SUBSCRIPTION_ID=\"${AZURE_SUBSCRIPTION_ID}\" \\\n-e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n-e ORCHESTRATOR=kubernetes \\\n-e ORCHESTRATOR_RELEASE=\"${ORCHESTRATOR_RELEASE}\" \\\n-e CREATE_VNET=\"${CREATE_VNET}\" \\\n-e PRIVATE_SSH_KEY_FILE=\"${PRIVATE_SSH_KEY_FILE}\" \\\n-e TIMEOUT=\"${E2E_TEST_TIMEOUT}\" \\\n-e LB_TIMEOUT=\"${LB_TEST_TIMEOUT}\" \\\n-e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n-e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n-e CLEANUP_ON_EXIT=${CLEANUP_AFTER_DEPLOYMENT} \\\n-e SKIP_LOGS_COLLECTION=\"${SKIP_LOGS_COLLECTION}\" \\\n-e REGIONS=\"${REGION_OPTIONS}\" \\\n-e WINDOWS_NODE_IMAGE_GALLERY=\"${WINDOWS_NODE_IMAGE_GALLERY}\" \\\n-e WINDOWS_NODE_IMAGE_NAME=\"${WINDOWS_NODE_IMAGE_NAME}\" \\\n-e WINDOWS_NODE_IMAGE_RESOURCE_GROUP=\"${WINDOWS_NODE_IMAGE_RESOURCE_GROUP}\" \\\n-e WINDOWS_NODE_IMAGE_SUBSCRIPTION_ID=\"${WINDOWS_NODE_IMAGE_SUBSCRIPTION_ID}\" \\\n-e WINDOWS_NODE_IMAGE_VERSION=\"${WINDOWS_NODE_IMAGE_VERSION}\" \\\n-e WINDOWS_NODE_VHD_URL=\"${WINDOWS_NODE_VHD_URL}\" \\\n-e LINUX_NODE_IMAGE_GALLERY=$LINUX_NODE_IMAGE_GALLERY \\\n-e LINUX_NODE_IMAGE_NAME=$LINUX_NODE_IMAGE_NAME \\\n-e LINUX_NODE_IMAGE_RESOURCE_GROUP=$LINUX_NODE_IMAGE_RESOURCE_GROUP \\\n-e LINUX_NODE_IMAGE_SUBSCRIPTION_ID=$LINUX_NODE_IMAGE_SUBSCRIPTION_ID \\\n-e LINUX_NODE_IMAGE_VERSION=$LINUX_NODE_IMAGE_VERSION \\\n-e OS_DISK_SIZE_GB=$OS_DISK_SIZE_GB \\\n-e DISTRO=$DISTRO \\\n-e CONTAINER_RUNTIME=$CONTAINER_RUNTIME \\\n-e LOG_ANALYTICS_WORKSPACE_KEY=\"${LOG_ANALYTICS_WORKSPACE_KEY}\" \\\n-e CUSTOM_HYPERKUBE_IMAGE=\"${CUSTOM_HYPERKUBE_IMAGE}\" \\\n-e CUSTOM_KUBE_PROXY_IMAGE=\"${CUSTOM_KUBE_PROXY_IMAGE}\" \\\n-e IS_JENKINS=\"${IS_JENKINS}\" \\\n-e TEST_PVC=\"${TEST_PVC}\" \\\n-e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n-e SKIP_TEST=\"${SKIP_TESTS}\" \\\n-e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n-e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n-e GINKGO_SKIP=\"${GINKGO_SKIP}\" \\\n-e API_PROFILE=\"${API_PROFILE}\" \\\n-e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n-e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n-e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n-e LOCATION=\"${LOCATION}\" \\\n-e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n-e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n-e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n-e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n-e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n-e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n-e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n-e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n-e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n-e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n-e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n-e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n-e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n-e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n-e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n-e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n-e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n-e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n-e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n-e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n-e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n-e LINUX_CONTAINERD_URL=${LINUX_CONTAINERD_URL} \\\n-e WINDOWS_CONTAINERD_URL=${WINDOWS_CONTAINERD_URL} \\\n-e LINUX_MOBY_URL=${LINUX_MOBY_URL} \\\n-e LINUX_RUNC_URL=${LINUX_RUNC_URL} \\\n-e VALIDATE_CPU_LOAD=${VALIDATE_CPU_LOAD} \\\n-e RUN_VMSS_NODE_PROTOTYPE=${RUN_VMSS_NODE_PROTOTYPE} \\\n-e KAMINO_VMSS_PROTOTYPE_LOCAL_CHART_PATH=${KAMINO_VMSS_PROTOTYPE_LOCAL_CHART_PATH} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_REGISTRY=${KAMINO_VMSS_PROTOTYPE_IMAGE_REGISTRY} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_REPOSITORY=${KAMINO_VMSS_PROTOTYPE_IMAGE_REPOSITORY} \\\n-e KAMINO_VMSS_PROTOTYPE_IMAGE_TAG=${KAMINO_VMSS_PROTOTYPE_IMAGE_TAG} \\\n-e CUSTOM_KUBE_PROXY_IMAGE=${CUSTOM_KUBE_PROXY_IMAGE} \\\n-e CUSTOM_KUBE_APISERVER_IMAGE=${CUSTOM_KUBE_APISERVER_IMAGE} \\\n-e CUSTOM_KUBE_SCHEDULER_IMAGE=${CUSTOM_KUBE_SCHEDULER_IMAGE} \\\n-e CUSTOM_KUBE_CONTROLLER_MANAGER_IMAGE=${CUSTOM_KUBE_CONTROLLER_MANAGER_IMAGE} \\\n-e CUSTOM_KUBE_BINARY_URL=${CUSTOM_KUBE_BINARY_URL} \\\n-e CUSTOM_WINDOWS_PACKAGE_URL=${CUSTOM_WINDOWS_PACKAGE_URL} \\\n-e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n\"${DEV_IMAGE}\" make test-kubernetes || tryExit && renameResultsFile \"deploy\"\n\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ] || [ \"${GET_CLUSTER_LOGS}\" = \"true\" ] || [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  # shellcheck disable=SC2012\n  RESOURCE_GROUP=$(ls -dt1 _output/* | head -n 1 | cut -d/ -f2)\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -w ${WORK_DIR} \\\n    -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n    ${DEV_IMAGE} \\\n    /bin/bash -c \"chmod -R 777 _output/$RESOURCE_GROUP _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n  # shellcheck disable=SC2012\n  REGION=$(ls -dt1 _output/* | head -n 1 | cut -d/ -f2 | cut -d- -f2)\n  API_SERVER=${RESOURCE_GROUP}.${REGION}.${RESOURCE_MANAGER_VM_DNS_SUFFIX:-cloudapp.azure.com}\n\n  if [ \"${GET_CLUSTER_LOGS}\" = \"true\" ]; then\n      docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine-azurestack get-logs \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --ssh-host $API_SERVER \\\n      --linux-ssh-private-key _output/$RESOURCE_GROUP-ssh \\\n      --linux-script ./scripts/collect-logs.sh \\\n      --windows-script ./scripts/collect-windows-logs.ps1\n\n      for logfile in \"_output/${RESOURCE_GROUP}/_logs\"/*.zip; do\n        if [ -z \"$(cat ${logfile})\" ]; then\n          echo \"File ${logfile} is empty\"\n          exit 1\n        fi\n      done\n  fi\n\n  if [ $(( RANDOM % 4 )) -eq 3 ]; then\n    echo Removing bookkeeping tags from VMs in resource group $RESOURCE_GROUP ...\n    az login --username ${AZURE_CLIENT_ID} --password ${AZURE_CLIENT_SECRET} --tenant ${AZURE_TENANT_ID} --service-principal > /dev/null\n    for vm_type in vm vmss; do\n      for vm in $(az $vm_type list -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --query '[].name' -o table | tail -n +3); do\n        az $vm_type update -n $vm -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --set tags={} > /dev/null\n      done\n    done\n  fi\n\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ]; then\n    git reset --hard\n    git remote rm $UPGRADE_FORK\n    git remote add $UPGRADE_FORK https://github.com/$UPGRADE_FORK/aks-engine-azurestack.git\n    git fetch --prune $UPGRADE_FORK\n    git branch -D $UPGRADE_FORK/$UPGRADE_BRANCH\n    git checkout -b $UPGRADE_FORK/$UPGRADE_BRANCH --track $UPGRADE_FORK/$UPGRADE_BRANCH\n    git pull\n    git log -1\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      \"${DEV_IMAGE}\" make build-binary > /dev/null 2>&1 || exit 1\n  fi\nelse\n  exit 0\nfi\n\nif [ \"${ROTATE_CERTS}\" = \"true\" ]; then\n  rotateCertificates\n\n  SKIP_AFTER_ROTATE_CERTS=\"${GINKGO_SKIP}|should be able to autoscale\"\n  SKIP_AFTER_SCALE_DOWN=\"${SKIP_AFTER_SCALE_DOWN}|should be able to autoscale\"\n  SKIP_AFTER_SCALE_UP=\"${SKIP_AFTER_SCALE_DOWN}|should be able to autoscale\"\n  CLEANUP_AFTER_ROTATE_CERTS=${CLEANUP_ON_EXIT}\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ] || [ -n \"$ADD_NODE_POOL_INPUT\" ]; then\n    CLEANUP_AFTER_ROTATE_CERTS=\"false\"\n  fi\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_AFTER_ROTATE_CERTS} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_ROTATE_CERTS}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n    -e SKIP_TEST=false \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"rotate-certs\"\nfi\n\nif [ -n \"$ADD_NODE_POOL_INPUT\" ]; then\n  for pool in $(echo ${ADD_NODE_POOL_INPUT} | jq -c '.[]'); do\n    echo $pool > ${TMP_DIR}/addpool-input.json\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine-azurestack addpool \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --node-pool ${TMP_BASENAME}/addpool-input.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --auth-method client_secret \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  CLEANUP_AFTER_ADD_NODE_POOL=${CLEANUP_ON_EXIT}\n  if [ \"${UPGRADE_CLUSTER}\" = \"true\" ] || [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n    CLEANUP_AFTER_ADD_NODE_POOL=\"false\"\n  fi\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_AFTER_ADD_NODE_POOL} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_DOWN}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_ADD_POOL} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"add-node-pool\"\nfi\n\nif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n  nodepoolcount=$(jq '.properties.agentPoolProfiles| length' < _output/$RESOURCE_GROUP/apimodel.json)\n  for ((i = 0; i < $nodepoolcount; ++i)); do\n    nodepool=$(jq -r --arg i $i '. | .properties.agentPoolProfiles[$i | tonumber].name' < _output/$RESOURCE_GROUP/apimodel.json)\n    if [ \"${UPDATE_NODE_POOLS}\" = \"true\" ]; then\n      # modify the master VM SKU to simulate vertical vm scaling via upgrade\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        -e NODE_VM_UPGRADE_SKU=$NODE_VM_UPGRADE_SKU \\\n        ${DEV_IMAGE} \\\n        /bin/bash -c \"jq --arg sku \\\"$NODE_VM_UPGRADE_SKU\\\" --arg i $i '. | .properties.agentPoolProfiles[$i | tonumber].vmSize = \\$sku' < _output/$RESOURCE_GROUP/apimodel.json > _output/$RESOURCE_GROUP/apimodel-update.json\" || exit 1\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        ${DEV_IMAGE} \\\n        /bin/bash -c \"mv _output/$RESOURCE_GROUP/apimodel-update.json _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n      docker run --rm \\\n        -v $(pwd):${WORK_DIR} \\\n        -v /etc/ssl/certs:/etc/ssl/certs \\\n        -w ${WORK_DIR} \\\n        -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n        -e REGION=$REGION \\\n        -e UPDATE_POOL_NAME=$UPDATE_POOL_NAME \\\n        ${DEV_IMAGE} \\\n        ./bin/aks-engine-azurestack update \\\n        --azure-env ${AZURE_ENV} \\\n        --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n        --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n        --node-pool $nodepool \\\n        --location $REGION \\\n        --resource-group $RESOURCE_GROUP \\\n        --auth-method client_secret \\\n        --client-id ${AZURE_CLIENT_ID} \\\n        --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n      az vmss list -g $RESOURCE_GROUP --subscription ${AZURE_SUBSCRIPTION_ID} --query '[].sku' | grep $NODE_VM_UPGRADE_SKU || exit 1\n    fi\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine-azurestack scale \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --apiserver $API_SERVER \\\n      --node-pool $nodepool \\\n      --new-node-count 1 \\\n      --auth-method client_secret \\\n      --identity-system ${IDENTITY_SYSTEM} \\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=false \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=true \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_DOWN}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_SCALE_DOWN} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"scale-down\"\nfi\n\nif [ \"${UPGRADE_CLUSTER}\" = \"true\" ]; then\n  # modify the master VM SKU to simulate vertical vm scaling via upgrade\n  docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e MASTER_VM_UPGRADE_SKU=$MASTER_VM_UPGRADE_SKU \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"jq --arg sku \\\"$MASTER_VM_UPGRADE_SKU\\\" '. | .properties.masterProfile.vmSize = \\$sku' < _output/$RESOURCE_GROUP/apimodel.json > _output/$RESOURCE_GROUP/apimodel-upgrade.json\" || exit 1\n  docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      ${DEV_IMAGE} \\\n      /bin/bash -c \"mv _output/$RESOURCE_GROUP/apimodel-upgrade.json _output/$RESOURCE_GROUP/apimodel.json\" || exit 1\n  for ver_target in $UPGRADE_VERSIONS; do\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n      -e REGION=$REGION \\\n      ${DEV_IMAGE} \\\n      ./bin/aks-engine-azurestack upgrade --force \\\n      --azure-env ${AZURE_ENV} \\\n      --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n      --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n      --location $REGION \\\n      --resource-group $RESOURCE_GROUP \\\n      --upgrade-version $ver_target \\\n      --vm-timeout 20 \\\n      --auth-method client_secret \\\n      --identity-system ${IDENTITY_SYSTEM}\\\n      --client-id ${AZURE_CLIENT_ID} \\\n      --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n\n    docker run --rm \\\n      -v $(pwd):${WORK_DIR} \\\n      -v /etc/ssl/certs:/etc/ssl/certs \\\n      -w ${WORK_DIR} \\\n      -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n      -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n      -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n      -e TENANT_ID=${AZURE_TENANT_ID} \\\n      -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n      -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n      -e ORCHESTRATOR=kubernetes \\\n      -e NAME=$RESOURCE_GROUP \\\n      -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n      -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n      -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n      -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n      -e CLEANUP_ON_EXIT=false \\\n      -e REGIONS=$REGION \\\n      -e IS_JENKINS=${IS_JENKINS} \\\n      -e SKIP_LOGS_COLLECTION=${SKIP_LOGS_COLLECTION} \\\n      -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n      -e GINKGO_SKIP=\"${SKIP_AFTER_UPGRADE}\" \\\n      -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n      -e TEST_PVC=\"${TEST_PVC}\" \\\n      -e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n      -e SKIP_TEST=${SKIP_TESTS_AFTER_UPGRADE} \\\n      -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n      -e API_PROFILE=\"${API_PROFILE}\" \\\n      -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n      -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n      -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n      -e LOCATION=\"${LOCATION}\" \\\n      -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n      -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n      -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n      -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n      -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n      -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n      -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n      -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n      -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n      -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n      -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n      -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n      -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n      -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n      -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n      -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n      -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n      -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n      -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n      -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n      -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n      -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n      ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"upgrade\"\n  done\nfi\n\nif [ \"${SCALE_CLUSTER}\" = \"true\" ]; then\n  for nodepool in $(jq -r '.properties.agentPoolProfiles[].name' < _output/$RESOURCE_GROUP/apimodel.json); do\n    docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e RESOURCE_GROUP=$RESOURCE_GROUP \\\n    -e REGION=$REGION \\\n    ${DEV_IMAGE} \\\n    ./bin/aks-engine-azurestack scale \\\n    --azure-env ${AZURE_ENV} \\\n    --subscription-id ${AZURE_SUBSCRIPTION_ID} \\\n    --api-model _output/$RESOURCE_GROUP/apimodel.json \\\n    --location $REGION \\\n    --resource-group $RESOURCE_GROUP \\\n    --apiserver $API_SERVER \\\n    --node-pool $nodepool \\\n    --new-node-count $NODE_COUNT \\\n    --auth-method client_secret \\\n    --identity-system ${IDENTITY_SYSTEM}\\\n    --client-id ${AZURE_CLIENT_ID} \\\n    --client-secret ${AZURE_CLIENT_SECRET} || exit 1\n  done\n\n  docker run --rm \\\n    -v $(pwd):${WORK_DIR} \\\n    -v /etc/ssl/certs:/etc/ssl/certs \\\n    -w ${WORK_DIR} \\\n    -e CLIENT_ID=${AZURE_CLIENT_ID} \\\n    -e CLIENT_SECRET=${AZURE_CLIENT_SECRET} \\\n    -e CLIENT_OBJECTID=${CLIENT_OBJECTID} \\\n    -e TENANT_ID=${AZURE_TENANT_ID} \\\n    -e SUBSCRIPTION_ID=${AZURE_SUBSCRIPTION_ID} \\\n    -e INFRA_RESOURCE_GROUP=\"${INFRA_RESOURCE_GROUP}\" \\\n    -e ORCHESTRATOR=kubernetes \\\n    -e NAME=$RESOURCE_GROUP \\\n    -e TIMEOUT=${E2E_TEST_TIMEOUT} \\\n    -e LB_TIMEOUT=${LB_TEST_TIMEOUT} \\\n    -e KUBERNETES_IMAGE_BASE=$KUBERNETES_IMAGE_BASE \\\n    -e KUBERNETES_IMAGE_BASE_TYPE=$KUBERNETES_IMAGE_BASE_TYPE \\\n    -e CLEANUP_ON_EXIT=${CLEANUP_ON_EXIT} \\\n    -e REGIONS=$REGION \\\n    -e IS_JENKINS=${IS_JENKINS} \\\n    -e SKIP_LOGS_COLLECTION=${SKIP_LOGS_COLLECTION} \\\n    -e GINKGO_FAIL_FAST=\"${GINKGO_FAIL_FAST}\" \\\n    -e GINKGO_SKIP=\"${SKIP_AFTER_SCALE_UP}\" \\\n    -e GINKGO_FOCUS=\"${GINKGO_FOCUS}\" \\\n    -e TEST_PVC=\"${TEST_PVC}\" \\\n    -e CLEAN_PVC=\"${CLEAN_PVC}\" \\\n    -e SKIP_TEST=${SKIP_TESTS_AFTER_SCALE_UP} \\\n    -e ADD_NODE_POOL_INPUT=${ADD_NODE_POOL_INPUT} \\\n    -e API_PROFILE=\"${API_PROFILE}\" \\\n    -e CUSTOM_CLOUD_NAME=\"${ENVIRONMENT_NAME}\" \\\n    -e IDENTITY_SYSTEM=\"${IDENTITY_SYSTEM}\" \\\n    -e AUTHENTICATION_METHOD=\"${AUTHENTICATION_METHOD}\" \\\n    -e LOCATION=\"${LOCATION}\" \\\n    -e CUSTOM_CLOUD_CLIENT_ID=\"${CUSTOM_CLOUD_CLIENT_ID}\" \\\n    -e CUSTOM_CLOUD_SECRET=\"${CUSTOM_CLOUD_SECRET}\" \\\n    -e PORTAL_ENDPOINT=\"${PORTAL_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_ENDPOINT=\"${SERVICE_MANAGEMENT_ENDPOINT}\" \\\n    -e RESOURCE_MANAGER_ENDPOINT=\"${RESOURCE_MANAGER_ENDPOINT}\" \\\n    -e STORAGE_ENDPOINT_SUFFIX=\"${STORAGE_ENDPOINT_SUFFIX}\" \\\n    -e KEY_VAULT_DNS_SUFFIX=\"${KEY_VAULT_DNS_SUFFIX}\" \\\n    -e ACTIVE_DIRECTORY_ENDPOINT=\"${ACTIVE_DIRECTORY_ENDPOINT}\" \\\n    -e GALLERY_ENDPOINT=\"${GALLERY_ENDPOINT}\" \\\n    -e GRAPH_ENDPOINT=\"${GRAPH_ENDPOINT}\" \\\n    -e SERVICE_MANAGEMENT_VM_DNS_SUFFIX=\"${SERVICE_MANAGEMENT_VM_DNS_SUFFIX}\" \\\n    -e RESOURCE_MANAGER_VM_DNS_SUFFIX=\"${RESOURCE_MANAGER_VM_DNS_SUFFIX}\" \\\n    -e STABILITY_ITERATIONS=${STABILITY_ITERATIONS} \\\n    -e STABILITY_ITERATIONS_SUCCESS_RATE=${STABILITY_ITERATIONS_SUCCESS_RATE} \\\n    -e SINGLE_COMMAND_TIMEOUT_MINUTES=${SINGLE_COMMAND_TIMEOUT_MINUTES} \\\n    -e STABILITY_TIMEOUT_SECONDS=${STABILITY_TIMEOUT_SECONDS} \\\n    -e ARC_CLIENT_ID=${ARC_CLIENT_ID:-$AZURE_CLIENT_ID} \\\n    -e ARC_CLIENT_SECRET=${ARC_CLIENT_SECRET:-$AZURE_CLIENT_SECRET} \\\n    -e ARC_SUBSCRIPTION_ID=${ARC_SUBSCRIPTION_ID:-$AZURE_SUBSCRIPTION_ID} \\\n    -e ARC_LOCATION=${ARC_LOCATION:-$LOCATION} \\\n    -e ARC_TENANT_ID=${ARC_TENANT_ID:-$AZURE_TENANT_ID} \\\n    -e AZURE_CORE_ONLY_SHOW_ERRORS=\"True\" \\\n    ${DEV_IMAGE} make test-kubernetes || tryExit && renameResultsFile \"scale-up\"\nfi\n", "num_lines": 772}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsudo chown -R jenkins:jenkins .\n", "num_lines": 4}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nsystemctl status auditd\nRET=$?\nif $ENABLED; then\n  if [ $RET -eq 0 ]; then\n    exit 0\n  else\n    exit 1\n  fi\nelse\n  if [ $RET -ne 0 ]; then\n    exit 0\n  else\n    exit 1\n  fi\nfi\n", "num_lines": 19}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsource /etc/profile.d/CIS.sh\n\nCIS_FILES=\"\n/etc/issue\n/etc/issue.net\n/etc/sysctl.d/60-CIS.conf\n/etc/rsyslog.d/60-CIS.conf\n/etc/security/pwquality.conf\n/etc/pam.d/su\n\"\nfor CIS_FILE in ${CIS_FILES}; do\n    ls -la $CIS_FILE || exit 2\n    [ -s $CIS_FILE ] || exit 1\ndone\n\n# specific file mode validations\nfor filepath in /etc/crontab /etc/cron.hourly /etc/cron.daily /etc/cron.weekly /etc/cron.monthly /etc/cron.d; do\n  stat $filepath | grep 'Access: (0600' || exit 1\ndone\n# validate su configuration\nsudo grep \"auth required pam_wheel.so use_uid\" /etc/pam.d/su\n# validate password lockout config\nsudo grep \"auth required pam_tally2.so onerr=fail audit silent deny=5 unlock_time=900\" /etc/pam.d/common-auth\n# validate password change uniqueness config\nsudo grep \"pam_unix.so obscure use_authtok try_first_pass sha512 remember=5\" /etc/pam.d/common-password\n# validate umask configuration\ntouch test-umask\nstat test-umask | grep 'Access: (0640' || exit 1\nrm -f test-umask\n", "num_lines": 31}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ $(sudo cat /etc/kubernetes/azure.json | jq --arg mode $BACKOFF_MODE '.cloudProviderBackoffMode|contains($mode)') != 'true' ]; then\n    exit 1\nfi\n", "num_lines": 6}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nkubelet_version=$(docker run ${CUSTOM_HYPERKUBE_IMAGE} kubelet --version)\n[[ $(kubelet --version) == \"${kubelet_version}\" ]] || exit 1\n\nkubectl_version=$(docker run ${CUSTOM_HYPERKUBE_IMAGE} kubectl version --client)\n[[ $(kubectl version --client) == \"${kubectl_version}\" ]] || exit 1\n", "num_lines": 10}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nsudo ifconfig -a -v || exit 1\ncat /etc/resolv.conf || exit 1\nset +x\n# validate that all node vms can resolve DNS to all other node vms, including themselves\n# also validate external DNS lookups\n# configurable retries\nsuccess=\"no\"\nretries=${LOOKUP_RETRIES}\nHOSTS=\"${NODE_HOSTNAMES} www.bing.com google.com\"\nfor i in $(seq 1 $retries); do\n  for host in $HOSTS; do\n    set -x\n    addrs=$(dig +short +search +answer ${host})\n    if [ -z \"$addrs\" ]; then\n      success=\"no\"\n      break\n    fi\n    set +x\n    success=\"yes\"\n  done\n  if [[ \"${success}\" == \"yes\" ]]; then\n    break\n  fi\n  if [ $i -eq $retries ]; then\n    exit 1\n  else\n    sleep 10\n  fi\ndone\n\nsuccess=\"no\"\nHOSTS=\"www.bing.com google.com\"\nfor i in $(seq 1 $retries); do\n  for host in $HOSTS; do\n    set -x\n    addrs=$(dig +short +search +answer ${host} @8.8.8.8)\n    if [ -z \"$addrs\" ]; then\n      success=\"no\"\n      break\n    fi\n    set +x\n    success=\"yes\"\n  done\n  if [[ \"${success}\" == \"yes\" ]]; then\n    break\n  fi\n  if [ $i -eq $retries ]; then\n    exit 1\n  else\n    sleep 10\n  fi\ndone\n", "num_lines": 56}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n[ $(findmnt /mnt -no FSTYPE) == \"ext4\" ] || exit 1\nif [[ $MASTER_NODE == \"true\" ]]; then\n  [ $(findmnt /var/lib/etcddisk -no FSTYPE) == \"ext4\" ] || exit 1\nfi\n", "num_lines": 8}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nmodprobe -n -v tipc | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep tipc) ] || exit 1\nmodprobe -n -v dccp | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep dccp) ] || exit 1\nmodprobe -n -v sctp | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep sctp) ] || exit 1\nmodprobe -n -v rds | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep rds) ] || exit 1\nmodprobe -n -v cramfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep cramfs) ] || exit 1\nmodprobe -n -v freevxfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep freevxfs) ] || exit 1\nmodprobe -n -v jffs2 | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep jffs2) ] || exit 1\nmodprobe -n -v hfs | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep hfs) ] || exit 1\nmodprobe -n -v hfsplus | grep -E 'install /bin/true' || exit 1\n[ -s $(lsmod | grep hfsplus) ] || exit 1\n[ -s $(lsmod | grep squashfs) ] || exit 1\n[ -s $(lsmod | grep vfat) ] || exit 1\n", "num_lines": 24}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nIPV4_SEND_REDIRECTS_VALUE=0\nIPV4_ACCEPT_SOURCE_ROUTE_VALUE=0\nIPV4_ACCEPT_REDIRECTS_VALUE=0\nIPV4_SECURE_REDIRECTS_VALUE=0\nIPV4_LOG_MARTIANS_VALUE=1\nIPV4_TCP_RETRIES2_VALUE=8\nIPV6_ACCEPT_RA_VALUE=0\nIPV6_ACCEPT_REDIRECTS_VALUE=0\nKERNEL_PANIC_VALUE=10\nKERNEL_PANIC_ON_OOPS_VALUE=1\nVM_OVERCOMMIT_MEMORY_VALUE=1\nINOTIFY_MAX_USER_WATCHES=1048576\nSOMAXCONN=16384\nTCP_MAX_SYN_BACKLOG=16384\nMESSAGE_COST=40\nMESSAGE_BURST=80\nIPV4_NEIGH_GC_THRESH1=4096\nIPV4_NEIGH_GC_THRESH2=8192\nIPV4_NEIGH_GC_THRESH3=16384\n\nset -x\ngrep $IPV4_SEND_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/send_redirects || exit 1\ngrep $IPV4_SEND_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/send_redirects || exit 1\ngrep $IPV4_ACCEPT_SOURCE_ROUTE_VALUE /proc/sys/net/ipv4/conf/all/accept_source_route || exit 1\ngrep $IPV4_ACCEPT_SOURCE_ROUTE_VALUE /proc/sys/net/ipv4/conf/default/accept_source_route || exit 1\ngrep $IPV4_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/accept_redirects || exit 1\ngrep $IPV4_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/accept_redirects || exit 1\ngrep $IPV4_SECURE_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/all/secure_redirects || exit 1\ngrep $IPV4_SECURE_REDIRECTS_VALUE /proc/sys/net/ipv4/conf/default/secure_redirects || exit 1\ngrep $IPV4_LOG_MARTIANS_VALUE /proc/sys/net/ipv4/conf/all/log_martians || exit 1\ngrep $IPV4_LOG_MARTIANS_VALUE /proc/sys/net/ipv4/conf/default/log_martians || exit 1\ngrep $IPV6_ACCEPT_RA_VALUE /proc/sys/net/ipv6/conf/all/accept_ra || exit 1\ngrep $IPV6_ACCEPT_RA_VALUE /proc/sys/net/ipv6/conf/default/accept_ra || exit 1\ngrep $IPV6_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv6/conf/all/accept_redirects || exit 1\ngrep $IPV6_ACCEPT_REDIRECTS_VALUE /proc/sys/net/ipv6/conf/default/accept_redirects || exit 1\n\n# validate kubelet.service configs\ngrep $IPV4_TCP_RETRIES2_VALUE /proc/sys/net/ipv4/tcp_retries2 || exit 1\ngrep $KERNEL_PANIC_VALUE /proc/sys/kernel/panic || exit 1\ngrep $KERNEL_PANIC_ON_OOPS_VALUE /proc/sys/kernel/panic_on_oops || exit 1\ngrep $VM_OVERCOMMIT_MEMORY_VALUE /proc/sys/vm/overcommit_memory || exit 1\ngrep $INOTIFY_MAX_USER_WATCHES /proc/sys/fs/inotify/max_user_watches || exit 1\ngrep $SOMAXCONN /proc/sys/net/core/somaxconn || exit 1\ngrep $TCP_MAX_SYN_BACKLOG /proc/sys/net/ipv4/tcp_max_syn_backlog || exit 1\ngrep $MESSAGE_COST /proc/sys/net/core/message_cost || exit 1\ngrep $MESSAGE_BURST /proc/sys/net/core/message_burst || exit 1\n\ngrep $IPV4_NEIGH_GC_THRESH1 /proc/sys/net/ipv4/neigh/default/gc_thresh1 || exit 1\ngrep $IPV4_NEIGH_GC_THRESH2 /proc/sys/net/ipv4/neigh/default/gc_thresh2 || exit 1\ngrep $IPV4_NEIGH_GC_THRESH3 /proc/sys/net/ipv4/neigh/default/gc_thresh3 || exit 1\n\n# validate eth0 MTU\nif [ \"$ETH0_MTU\" != \"\" ]; then\n  grep $ETH0_MTU /sys/class/net/eth0/mtu || exit 1\nfi\n", "num_lines": 57}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\n# an invalid password should fail\nif [[ ${STIG} == true ]]; then\n    echo \"tooshort12@\" | sudo pwscore && exit 1\nelse\n    echo \"tooshort1@\" | sudo pwscore && exit 1\nfi\necho \"password123456@J\" | sudo pwscore && exit 1\necho \"passSDWword@@@@J\" | sudo pwscore && exit 1\necho \"passSDWword1111J\" | sudo pwscore && exit 1\necho \"lowerrrr12case@\" | sudo pwscore && exit 1\necho \"UPPERRR12CASE@\" | sudo pwscore && exit 1\n\n# a valid password should succeed\necho \"passSDWword1232rdw#@\" | sudo pwscore || exit 1\n\n# validate password age settings\nif [[ ${STIG} == true ]]; then\n    grep -E '^PASS_MAX_DAYS 60$' /etc/login.defs || exit 1\n    grep -E '^PASS_MIN_DAYS 1$' /etc/login.defs || exit 1\n    grep -E '^UMASK 077$' /etc/login.defs || exit 1\nelse\n    grep 'PASS_MAX_DAYS 90' /etc/login.defs || exit 1\n    grep 'PASS_MIN_DAYS 7' /etc/login.defs || exit 1\nfi\ngrep 'INACTIVE=30' /etc/default/useradd || exit 1\n", "num_lines": 30}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nUBUNTU_RELEASE=$(lsb_release -r -s)\nCONFIGS=(\"ClientAliveInterval 120\"\n\"ClientAliveCountMax 3\"\n\"MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,umac-128-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,umac-128@openssh.com\"\n\"KexAlgorithms curve25519-sha256@libssh.org\"\n\"Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr\"\n\"HostKey /etc/ssh/ssh_host_rsa_key\"\n\"HostKey /etc/ssh/ssh_host_dsa_key\"\n\"HostKey /etc/ssh/ssh_host_ecdsa_key\"\n\"HostKey /etc/ssh/ssh_host_ed25519_key\"\n\"SyslogFacility AUTH\"\n\"LogLevel INFO\"\n\"LoginGraceTime 60\"\n\"PermitRootLogin no\"\n\"PermitUserEnvironment no\"\n\"StrictModes yes\"\n\"PubkeyAuthentication yes\"\n\"IgnoreRhosts yes\"\n\"HostbasedAuthentication no\"\n\"X11Forwarding no\"\n\"MaxAuthTries 4\"\n\"Banner /etc/issue.net\"\n\"AcceptEnv LANG LC_*\"\n\"Subsystem sftp /usr/lib/openssh/sftp-server\"\n\"UsePAM yes\"\n\"UseDNS no\"\n\"GSSAPIAuthentication no\")\n\nfor ((i = 0; i < ${#CONFIGS[@]}; i++))\ndo\n    grep -i \"${CONFIGS[$i]}\" /etc/ssh/sshd_config || exit 1\ndone\n", "num_lines": 37}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo grep \"* hard maxlogins 10\" /etc/security/limits.conf || exit 1\n\nsudo grep \"disk_full_action = HALT\" /etc/audit/auditd.conf || exit 1\n\nsudo grep \"TMOUT=600\" /etc/profile.d/99-terminal_tmout.sh || exit 1\n\nsudo grep \"difok=8\" /etc/security/pwquality.conf || exit 1\nsudo grep \"dictcheck=1\" /etc/security/pwquality.conf || exit 1\nsudo grep \"minlen=15\" /etc/security/pwquality.conf || exit 1\nsudo grep \"lcredit=-1\" /etc/security/pwquality.conf || exit 1\n\nsudo grep 'APT::Get::AllowUnauthenticated \"false\"' /etc/apt/apt.conf.d/01-vendor-ubuntu || exit 1\nsudo grep 'Unattended-Upgrade::Remove-Unused-Dependencies \"true\"' /etc/apt/apt.conf.d/50unattended-upgrades || exit 1\nsudo grep 'Unattended-Upgrade::Remove-Unused-Kernel-Packages \"true\"' /etc/apt/apt.conf.d/50unattended-upgrades || exit 1\n\nset -x\n\nCONFIGS=(\"ClientAliveInterval 120\"\n\"ClientAliveCountMax 1\"\n\"MACs hmac-sha2-512,hmac-sha2-256\"\n\"KexAlgorithms curve25519-sha256@libssh.org\"\n\"Ciphers aes256-ctr,aes192-ctr,aes128-ctr\"\n\"HostKey /etc/ssh/ssh_host_rsa_key\"\n\"HostKey /etc/ssh/ssh_host_dsa_key\"\n\"HostKey /etc/ssh/ssh_host_ecdsa_key\"\n\"HostKey /etc/ssh/ssh_host_ed25519_key\"\n\"SyslogFacility AUTH\"\n\"LogLevel INFO\"\n\"LoginGraceTime 60\"\n\"PermitRootLogin no\"\n\"PermitUserEnvironment no\"\n\"StrictModes yes\"\n\"PubkeyAuthentication yes\"\n\"IgnoreRhosts yes\"\n\"HostbasedAuthentication no\"\n\"X11Forwarding no\"\n\"X11UseLocalhost yes\"\n\"MaxAuthTries 4\"\n\"AcceptEnv LANG LC_*\"\n\"Subsystem sftp /usr/lib/openssh/sftp-server\"\n\"UsePAM yes\"\n\"UseDNS no\"\n\"Banner /etc/issue-stig.net\"\n\"GSSAPIAuthentication no\")\n\nfor ((i = 0; i < ${#CONFIGS[@]}; i++))\ndo\n    grep -i \"${CONFIGS[$i]}\" /etc/ssh/sshd_config || exit 1\ndone\n\nENSURE_INSTALLED=\"\nauditd\n\"\n\nfor PACKAGE in ${ENSURE_INSTALLED}; do\n    apt list --installed | grep -E \"^${PACKAGE}\" || exit 1\ndone", "num_lines": 59}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nMAX_ATTEMPTS=10\nSLEEP_BETWEEN_PHASES=10\n\nwait_systemd() {\n  local attempt=1\n  until sudo systemctl is-active $1; do\n  if ((attempt == MAX_ATTEMPTS)); then\n    exit 1\n  fi\n  sleep \"$((2 ** ATTEMPT++))\"\ndone\n}\n\nservice_started_only_once() {\n  if ! [[ $(sudo journalctl -b -u ${1} | grep -c \": Started \") == 1 ]]; then\n    exit 1\n  fi\n}\n\n# Validate that the monitor services themselves are stable\nservice_started_only_once \"kubelet-monitor\"\nif sudo kill $(pgrep etcd); then\n  service_started_only_once \"etcd-monitor\"\nfi\nservice_started_only_once \"docker-monitor\"\n\n# manually kill kubelet\nsudo kill $(pgrep kubelet)\nsleep $SLEEP_BETWEEN_PHASES\nwait_systemd \"kubelet\" # validate that systemd brought the kubelet service back online\n\nif apt list --installed | grep moby-engine; then\n  CONTAINER_RUNTIME=docker\nelse\n  CONTAINER_RUNTIME=containerd\nfi\nwait_systemd $CONTAINER_RUNTIME\n\n# manually kill the cri\nif [ $CONTAINER_RUNTIME == \"docker\" ]; then\n  sudo kill -9 $(pgrep docker)\nelse\n  sudo kill -9 $(pgrep containerd)\nfi\nsleep $SLEEP_BETWEEN_PHASES\nwait_systemd $CONTAINER_RUNTIME # validate that systemd brought the cri service back online\n\n# if I have an etcd binary that means I'm running etcd (control plane VM)\nif sudo kill $(pgrep etcd); then\n  sleep $SLEEP_BETWEEN_PHASES\n  wait_systemd \"etcd\" # validate that systemd brought the etcd service back online\nfi\nsleep $SLEEP_BETWEEN_PHASES\n\nwait_systemd \"kubelet\" # after all this nonsense let's verify that the kubelet systemd service is online\n", "num_lines": 59}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n    OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n  RELEASE=$(grep -oP 'DISTRIB_RELEASE=\\K(\\S+)' /etc/lsb-release)\n  # verify that timesyncd configuration is healthy\n  if [[ $RELEASE == \"16.04\" ]]; then\n    sudo timedatectl status | grep 'Network time on: yes' || exit 1\n    sudo timedatectl status | grep 'NTP synchronized: yes' || exit 1\n  else\n    if apt list --installed | grep 'chrony'; then\n      sudo chronyc sources | grep '#* PHC' || exit 1 # Make sure chrony is running and synced with host-based PTP source clock ('#' means local clock and '*' means synced)\n    else\n      sudo ntpstat | grep 'synchronised to NTP server' || exit 1\n    fi\n    sudo timedatectl status | grep 'System clock synchronized: yes' || exit 1\n  fi\nfi\nif [[ $OS == $DEBIAN_OS_NAME ]]; then\n  sudo timedatectl status | grep 'NTP service: active' || exit 1\n  sudo timedatectl status | grep 'System clock synchronized: yes' || exit 1\nfi\n\nsudo timedatectl status | grep 'RTC in local TZ: no' || exit 1\n", "num_lines": 32}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\nOS=$(sort -r /etc/*-release | gawk 'match($0, /^ID=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nUBUNTU_OS_NAME=\"UBUNTU\"\nFLATCAR_OS_NAME=\"FLATCAR\"\nDEBIAN_OS_NAME=\"DEBIAN\"\nif ! echo \"${UBUNTU_OS_NAME} ${FLATCAR_OS_NAME} ${DEBIAN_OS_NAME}\" | grep -q \"${OS}\"; then\n    OS=$(sort -r /etc/*-release | gawk 'match($0, /^(ID_LIKE=(.*))$/, a) { print toupper(a[2] a[3]); exit }')\nfi\n\nENSURE_NOT_INSTALLED=\"\npostfix\n\"\nfor PACKAGE in ${ENSURE_NOT_INSTALLED}; do\n    apt list --installed | grep -E \"^${PACKAGE}\" && exit 1\ndone\n\nif [[ $OS == $UBUNTU_OS_NAME ]]; then\n    ENSURE_INSTALLED_UBUNTU=\"\nceph-common\ncgroup-lite\nglusterfs-client\n\"\n    for PACKAGE in ${ENSURE_INSTALLED_UBUNTU}; do\n        apt list --installed | grep -E \"^${PACKAGE}\" || exit 1\n    done\nfi\n\nENSURE_INSTALLED=\"\napt-transport-https\nblobfuse\nca-certificates\nchrony\ncifs-utils\nconntrack\ncracklib-runtime\ndkms\ndbus\nebtables\nethtool\nfuse\ngcc\ngit\nhtop\niftop\ninit-system-helpers\niotop\niproute2\nipset\niptables\njq\nlibpam-pkcs11\nlibpam-pwquality\nlibpwquality-tools\nmake\nmount\nnet-tools\nnfs-common\nntp\nntpstat\nopensc-pkcs11\npigz\nsocat\nsysstat\ntraceroute\nutil-linux\nvlock\nxz-utils\nzip\n\"\nfor PACKAGE in ${ENSURE_INSTALLED}; do\n    apt list --installed | grep -E \"^${PACKAGE}\" || exit 1\ndone\n", "num_lines": 74}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z \"$RESOURCE_GROUP\" ]; then\n    echo \"must provide a RESOURCE_GROUP env var\"\n    exit 1;\nfi\n\n# TODO: track VMSS in a \"Creating\" state, enforce TTL, if \"Creating TTL\" expires:\n#  1. Check if the \"Creating\" VMSS instance correlates with a running Kubernetes node in the cluster\n#     If so, (1) cordon/drain the node\n#  2. Delete the instance in a stuck \"Creating\" state\n#  3. Wait for the VMSS to achive a \"Succeeded\" ProvisioningState\n#  4. Scale out the VMSS by 1\n\n# Continually look for non-Succeeded VMSS instances\nwhile true; do\n  NUM_VMSS=0\n  NUM_TERMINAL_VMSS=0\n  echo \"$(date)    Starting VMSS Health Remediation loop\"\n  for VMSS in $(az vmss list -g $RESOURCE_GROUP | jq -r '.[] | .name'); do\n    ((NUM_VMSS++))\n    NUM_DELETED_INSTANCES=0\n    VMSS_PROVISIONING_STATE=$(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '.provisioningState')\n    echo \"$(date)    VMSS ${VMSS} has a ProvisioningState of ${VMSS_PROVISIONING_STATE}\"\n    VMSS_CAPACITY=$(az vmss list -g $RESOURCE_GROUP | jq -r --arg VMSS \"$VMSS\" '.[] | select(.name == $VMSS) | .sku.capacity')\n    echo \"$(date)    VMSS ${VMSS} has a current capacity of ${VMSS_CAPACITY}\"\n    if [ \"$VMSS_PROVISIONING_STATE\" == \"Succeeded\" ] || [ \"$VMSS_PROVISIONING_STATE\" == \"Failed\" ]; then\n      ((NUM_TERMINAL_VMSS++))\n      HAS_FAILED_STATE_INSTANCE=\"false\"\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[] | select(.provisioningState == \"Failed\") | .name'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo \"$(date)    Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}\"\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_} --no-wait; then\n          sleep 30\n        else\n          sleep 1\n          ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.name == \"vmssCSE\" and .provisioningState == \"Failed\") | .id' | awk -F'/' '{print $9}'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo \"$(date)    Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}\"\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then\n           sleep 30\n        else\n           sleep 1\n           ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      for TARGET_VMSS_INSTANCE in $(az vmss list-instances -g $RESOURCE_GROUP -n $VMSS | jq -r '.[].resources[] | select(.publisher == \"Microsoft.AKS\" and .provisioningState != \"Succeeded\" and .provisioningState != \"Creating\" and .provisioningState != \"Deleting\") | .id' | awk -F'/' '{print $9}'); do\n        HAS_FAILED_STATE_INSTANCE=\"true\"\n        echo \"$(date)    Deleting VMSS ${VMSS} instance ${TARGET_VMSS_INSTANCE}\"\n        if ! az vmss delete-instances -n $VMSS -g $RESOURCE_GROUP --instance-id ${TARGET_VMSS_INSTANCE##*_}; then\n          sleep 30\n        else\n          sleep 1\n          ((NUM_DELETED_INSTANCES++))\n        fi\n      done\n      if [ \"$HAS_FAILED_STATE_INSTANCE\" == \"true\" ]; then\n        echo \"$(date)    Waiting for ${VMSS} to reach a terminal ProvisioningState after failed instances were deleted...\"\n        sleep 30\n        until [[ $(az vmss show -g $RESOURCE_GROUP -n $VMSS | jq -r '. | select(.provisioningState == \"Succeeded\" or .provisioningState == \"Failed\") | .name') ]]; do\n          echo \"$(date)    Waiting for ${VMSS} to reach a terminal ProvisioningState after failed instances were deleted...\"\n          sleep 30\n        done\n        echo \"$(date)    VMSS ${VMSS} is in a terminal state after failed instances were deleted!\"\n      fi\n    fi\n    if [ \"$NUM_DELETED_INSTANCES\" -gt \"0\" ]; then\n      echo \"$(date)    Instances were deleted from VMSS ${VMSS}, ensuring that capacity is set to ${VMSS_CAPACITY}\"\n      az vmss scale --new-capacity $VMSS_CAPACITY -n $VMSS -g $RESOURCE_GROUP --no-wait;\n    fi\n  done\n  if [ \"$LOOP_FOREVER\" == \"true\" ]; then\n    sleep 150\n  else\n    if [[ \"${NUM_VMSS}\" == \"${NUM_TERMINAL_VMSS}\" ]]; then\n      exit 0\n    fi\n  fi\ndone\n", "num_lines": 83}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -euo pipefail\n\ncd \"$(git rev-parse --show-toplevel)\"\n\nSTD_PATH=src/crypto/ed25519/internal/edwards25519/field\nLOCAL_PATH=curve25519/internal/field\nLAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint)\n\ngit fetch https://go.googlesource.com/go master\n\nif git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then\n    echo \"No changes.\"\nelse\n    NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint)\n    echo \"Applying changes from $LAST_SYNC_REF to $NEW_REF...\"\n    git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \\\n        git apply -3 --directory=$LOCAL_PATH\nfi\n", "num_lines": 20}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <netinet/udp.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrncpy(buf, strerror(e), sizeof(buf) - 1);\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrncpy(buf, strsignal(e), sizeof(buf) - 1);\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 784}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n# Cleanup packer SSH key and machine ID generated for this boot\nrm -f /root/.ssh/authorized_keys\nrm -f /home/packer/.ssh/authorized_keys\nrm -f /etc/machine-id\ntouch /etc/machine-id", "num_lines": 7}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"CLASSIC_SA_CONNECTION_STRING\"\n    \"STORAGE_ACCT_BLOB_URL\"\n    \"VHD_NAME\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nstart_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"-1 day\")\nexpiry_date=$(date +\"%Y-%m-%dT00:00Z\" -d \"+1 year\")\nsas_token=$(az storage container generate-sas --name windows --permissions lr --connection-string ${CLASSIC_SA_CONNECTION_STRING} --start ${start_date} --expiry ${expiry_date} | tr -d '\"')\nvhd_url=\"${STORAGE_ACCT_BLOB_URL}/${VHD_NAME}?$sas_token\"\n\n# Get verion info from release notes\nRELEASE_NOTES_FILE=release-notes.txt\n\nif [ ! -f \"$RELEASE_NOTES_FILE\" ]; then\n    echo \"Could not fine release notes file!\"\n    exit 1\nfi\n\nwindows_version=$(grep \"OS Version\" < release-notes.txt | cut -d \":\" -f 2 | tr -d \"[:space:]\")\n\ncat <<EOF > windows-vhd-publishing-info.json\n{\n    \"vhd_url\" : \"$vhd_url\",\n    \"windows_version\" : \"$windows_version\"\n}\nEOF\n\ncat windows-vhd-publishing-info.json\n", "num_lines": 40}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nCDIR=$(dirname \"${BASH_SOURCE}\")\n\nSETTINGS_JSON=\"${SETTINGS_JSON:-./settings.json}\"\nSP_JSON=\"${SP_JSON:-./sp.json}\"\nSUBSCRIPTION_ID=\"${SUBSCRIPTION_ID:-$(az account show -o json --query=\"id\" | tr -d '\"')}\"\nCREATE_TIME=\"$(date +%s)\"\nSTORAGE_ACCOUNT_NAME=\"aksimages${CREATE_TIME}${RANDOM}\"\n\n\necho \"Subscription ID: ${SUBSCRIPTION_ID}\"\necho \"Service Principal Path: ${SP_JSON}\"\n\nif [ -a \"${SP_JSON}\" ]; then\n\techo \"Existing credentials file found.\"\n\texit 0\nelif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"Service principal not found! Generating one @ ${SP_JSON}\"\n\taz ad sp create-for-rbac -n aks-images-packer${CREATE_TIME} -o json > ${SP_JSON}\n\tCLIENT_ID=$(jq -r .appId ${SP_JSON})\n\tCLIENT_SECRET=$(jq -r .password ${SP_JSON})\n\tTENANT_ID=$(jq -r .tenant ${SP_JSON})\nfi\n\navail=$(az storage account check-name -n ${STORAGE_ACCOUNT_NAME} -o json | jq -r .nameAvailable)\nif $avail ; then\n\techo \"creating new storage account ${STORAGE_ACCOUNT_NAME}\"\n\taz storage account create -n $STORAGE_ACCOUNT_NAME -g $PACKER_TEMP_GROUP --sku \"Standard_RAGRS\" --tags \"now=${CREATE_TIME}\"\n\techo \"creating new container system\"\n\tkey=$(az storage account keys list -n $STORAGE_ACCOUNT_NAME -g $PACKER_TEMP_GROUP | jq -r '.[0].value')\n\taz storage container create --name system --account-key=$key --account-name=$STORAGE_ACCOUNT_NAME\nelse\n\techo \"storage account ${STORAGE_ACCOUNT_NAME} already exists.\"\nfi\n\nif [ -z \"${CLIENT_ID}\" ]; then\n\techo \"CLIENT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${CLIENT_SECRET}\" ]; then\n\techo \"CLIENT_SECRET was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\nif [ -z \"${TENANT_ID}\" ]; then\n\techo \"TENANT_ID was not set! Something happened when generating the service principal or when trying to read the sp file!\"\n\texit 1\nfi\n\necho \"storage name: ${STORAGE_ACCOUNT_NAME}\"\n\necho \"UBUNTU_SKU set to ${UBUNTU_SKU}\"\nUBUNTU_OFFER=\"UbuntuServer\"\nUBUNTU_VER=\"18.04\"\nif [[ \"${UBUNTU_SKU}\" == \"20.04\" ]]; then\n\tUBUNTU_OFFER=\"0001-com-ubuntu-server-focal\"\n\tUBUNTU_VER=\"20_04\"\nfi\n\ncat <<EOF > vhd/packer/settings.json\n{\n  \"subscription_id\": \"${SUBSCRIPTION_ID}\",\n  \"client_id\": \"${CLIENT_ID}\",\n  \"client_secret\": \"${CLIENT_SECRET}\",\n  \"tenant_id\": \"${TENANT_ID}\",\n  \"resource_group_name\": \"${PACKER_TEMP_GROUP}\",\n  \"location\": \"${AZURE_LOCATION}\",\n  \"storage_account_name\": \"${STORAGE_ACCOUNT_NAME}\",\n  \"vm_size\": \"${AZURE_VM_SIZE}\",\n  \"ubuntu_offer\": \"${UBUNTU_OFFER}\",\n  \"ubuntu_sku\": \"${UBUNTU_VER}\",\n  \"create_time\": \"${CREATE_TIME}\"\n}\nEOF\n\ncat vhd/packer/settings.json\n", "num_lines": 79}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsource /home/packer/provision_installs.sh\nsource /home/packer/provision_source.sh\nsource /home/packer/packer_source.sh\n\nVHD_LOGS_FILEPATH=/opt/azure/vhd-install.complete\n\necho \"Starting build on \" $(date) > ${VHD_LOGS_FILEPATH}\n\ncopyPackerFiles\n\necho \"\"\necho \"Components downloaded in this VHD build (some of the below components might get deleted during cluster provisioning if they are not needed):\" >> ${VHD_LOGS_FILEPATH}\n\nAUDITD_ENABLED=true\nMS_APT_REPO=packages.microsoft.com\ninstallDeps\ncat << EOF >> ${VHD_LOGS_FILEPATH}\napt packages:\n  - apt-transport-https\n  - auditd\n  - blobfuse\n  - ca-certificates\n  - ceph-common\n  - cgroup-lite\n  - chrony\n  - cifs-utils\n  - conntrack\n  - cracklib-runtime\n  - dkms\n  - dbus\n  - ebtables\n  - ethtool\n  - fuse\n  - gcc\n  - git\n  - glusterfs-client\n  - htop\n  - iftop\n  - init-system-helpers\n  - iotop\n  - iproute2\n  - ipset\n  - iptables\n  - jq\n  - libpam-pkcs11\n  - libpam-pwquality\n  - libpwquality-tools\n  - make\n  - mount\n  - net-tools\n  - nfs-common\n  - ntp\n  - ntpstat\n  - opensc-pkcs11\n  - pigz\n  - socat\n  - sysstat\n  - traceroute\n  - util-linux\n  - vlock\n  - xz-utils\n  - zip\nEOF\n\nchmod a-x /etc/update-motd.d/??-{motd-news,release-upgrade}\n\noverrideNetworkConfig\n\ncat << EOF >> ${VHD_LOGS_FILEPATH}\nBinaries:\nEOF\n\napmz_version=\"v0.5.1\"\nensureAPMZ \"${apmz_version}\"\necho \"  - apmz $apmz_version\" >> ${VHD_LOGS_FILEPATH}\n\ninstallBpftrace\necho \"  - bpftrace\" >> ${VHD_LOGS_FILEPATH}\n\nMOBY_VERSION=\"20.10.14\"\nCONTAINERD_VERSION=\"1.5.16\"\ninstallMoby\ninstallRunc\nsystemctl_restart 100 5 30 docker || exit 1\necho \"  - moby v${MOBY_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndownloadGPUDrivers\necho \"  - nvidia-container-runtime\" >> ${VHD_LOGS_FILEPATH}\n\nETCD_VERSION=\"3.3.25\"\nETCD_DOWNLOAD_URL=\"mcr.microsoft.com/oss/etcd-io/\"\ninstallEtcd \"docker\"\necho \"  - etcd v${ETCD_VERSION}\" >> ${VHD_LOGS_FILEPATH}\n\nVNET_CNI_VERSIONS=\"\n1.4.32\n\"\nfor VNET_CNI_VERSION in $VNET_CNI_VERSIONS; do\n    VNET_CNI_PLUGINS_URL=\"https://acs-mirror.azureedge.net/azure-cni/v${VNET_CNI_VERSION}/binaries/azure-vnet-cni-linux-amd64-v${VNET_CNI_VERSION}.tgz\"\n    downloadAzureCNI\n    echo \"  - Azure CNI version ${VNET_CNI_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCNI_PLUGIN_VERSIONS=\"\n0.9.1\n\"\nfor CNI_PLUGIN_VERSION in $CNI_PLUGIN_VERSIONS; do\n    CNI_PLUGINS_URL=\"https://kubernetesartifacts.azureedge.net/cni-plugins/v${CNI_PLUGIN_VERSION}/binaries/cni-plugins-linux-amd64-v${CNI_PLUGIN_VERSION}.tgz\"\n    downloadCNI\n    echo \"  - CNI plugin version ${CNI_PLUGIN_VERSION}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\ninstallImg\necho \"  - img\" >> ${VHD_LOGS_FILEPATH}\n\nsystemctl status docker --no-pager || exit 1\necho \"Docker images pre-pulled:\" >> ${VHD_LOGS_FILEPATH}\n\nMETRICS_SERVER_VERSIONS=\"\n0.5.2\n\"\nfor METRICS_SERVER_VERSION in ${METRICS_SERVER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/metrics-server:v${METRICS_SERVER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKUBE_ADDON_MANAGER_VERSIONS=\"\n9.1.5\n9.1.6\n\"\nfor KUBE_ADDON_MANAGER_VERSION in ${KUBE_ADDON_MANAGER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/kube-addon-manager:v${KUBE_ADDON_MANAGER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nMCR_PAUSE_VERSIONS=\"\n3.8\n\"\nfor PAUSE_VERSION in ${MCR_PAUSE_VERSIONS}; do\n    # Pull the arch independent MCR pause image which is built for Linux and Windows\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/pause:${PAUSE_VERSION}\"\n    loadContainerImage \"${CONTAINER_IMAGE}\"\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCLUSTER_AUTOSCALER_VERSIONS=\"\n1.22.1\n\"\nfor CLUSTER_AUTOSCALER_VERSION in ${CLUSTER_AUTOSCALER_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/autoscaler/cluster-autoscaler:v${CLUSTER_AUTOSCALER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCORE_DNS_VERSIONS=\"\n1.9.4\n\"\nfor CORE_DNS_VERSION in ${CORE_DNS_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/coredns:v${CORE_DNS_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAZURE_CNIIMAGEBASE=\"mcr.microsoft.com/containernetworking\"\nAZURE_NPM_VERSIONS=\"\n1.4.32\n\"\nfor AZURE_NPM_VERSION in ${AZURE_NPM_VERSIONS}; do\n    CONTAINER_IMAGE=\"${AZURE_CNIIMAGEBASE}/azure-npm:v${AZURE_NPM_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nNVIDIA_DEVICE_PLUGIN_VERSIONS=\"\n1.0.0-beta6\n\"\nfor NVIDIA_DEVICE_PLUGIN_VERSION in ${NVIDIA_DEVICE_PLUGIN_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/nvidia/k8s-device-plugin:${NVIDIA_DEVICE_PLUGIN_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nBLOBFUSE_FLEXVOLUME_VERSIONS=\"1.0.8\"\nfor BLOBFUSE_FLEXVOLUME_VERSION in ${BLOBFUSE_FLEXVOLUME_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/flexvolume/blobfuse-flexvolume:${BLOBFUSE_FLEXVOLUME_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nIP_MASQ_AGENT_VERSIONS=\"\n2.8.0\n\"\nfor IP_MASQ_AGENT_VERSION in ${IP_MASQ_AGENT_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/ip-masq-agent:v${IP_MASQ_AGENT_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nKMS_PLUGIN_VERSIONS=\"0.0.10\"\nfor KMS_PLUGIN_VERSION in ${KMS_PLUGIN_VERSIONS}; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/kms/keyvault:v${KMS_PLUGIN_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nBUSYBOX_IMAGE=\"mcr.microsoft.com/oss/busybox/busybox:1.33.1\"\nloadContainerImage ${BUSYBOX_IMAGE}\necho \"  - ${BUSYBOX_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n\nK8S_VERSIONS=\"\n1.25.7\n1.24.11\n\"\nfor KUBERNETES_VERSION in ${K8S_VERSIONS}; do\n  for component in kube-apiserver kube-controller-manager kube-proxy kube-scheduler; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/${component}:v${KUBERNETES_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n  done\n  KUBE_BINARY_URL=\"https://kubernetesartifacts.azureedge.net/kubernetes/v${KUBERNETES_VERSION}/binaries/kubernetes-node-linux-amd64.tar.gz\"\n  extractKubeBinaries\ndone\n\n# Starting with 1.16 we pull cloud-controller-manager and cloud-node-manager\nCLOUD_MANAGER_VERSIONS=\"\n1.25.9\n1.24.0\n\"\nfor CLOUD_MANAGER_VERSION in ${CLOUD_MANAGER_VERSIONS}; do\n  for COMPONENT in azure-cloud-controller-manager azure-cloud-node-manager; do\n    CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/${COMPONENT}:v${CLOUD_MANAGER_VERSION}\"\n    loadContainerImage ${CONTAINER_IMAGE}\n    echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\n  done\ndone\n\nAZUREDISK_CSI_VERSIONS=\"\n1.10.0\n\"\nfor AZUREDISK_CSI_VERSION in ${AZUREDISK_CSI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/azuredisk-csi:v${AZUREDISK_CSI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAZUREFILE_CSI_VERSIONS=\"\n1.9.0\n\"\nfor AZUREFILE_CSI_VERSION in ${AZUREFILE_CSI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/azurefile-csi:v${AZUREFILE_CSI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_ATTACHER_VERSIONS=\"\n3.3.0\n\"\nfor CSI_ATTACHER_VERSION in ${CSI_ATTACHER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-attacher:v${CSI_ATTACHER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_NODE_DRIVER_REGISTRAR_VERSIONS=\"\n2.4.0\n\"\nfor CSI_NODE_DRIVER_REGISTRAR_VERSION in ${CSI_NODE_DRIVER_REGISTRAR_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-node-driver-registrar:v${CSI_NODE_DRIVER_REGISTRAR_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_PROVISIONER_VERSIONS=\"\n3.0.0\n\"\nfor CSI_PROVISIONER_VERSION in ${CSI_PROVISIONER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-provisioner:v${CSI_PROVISIONER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nLIVENESSPROBE_VERSIONS=\"\n2.5.0\n\"\nfor LIVENESSPROBE_VERSION in ${LIVENESSPROBE_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/livenessprobe:v${LIVENESSPROBE_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_RESIZER_VERSIONS=\"\n1.3.0\n\"\nfor CSI_RESIZER_VERSION in ${CSI_RESIZER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-resizer:v${CSI_RESIZER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SNAPSHOTTER_VERSIONS=\"\n4.2.1\n\"\nfor CSI_SNAPSHOTTER_VERSION in ${CSI_SNAPSHOTTER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/csi-snapshotter:v${CSI_SNAPSHOTTER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nSNAPSHOT_CONTROLLER_VERSIONS=\"\n4.2.1\n\"\nfor SNAPSHOT_CONTROLLER_VERSION in ${SNAPSHOT_CONTROLLER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/snapshot-controller:v${SNAPSHOT_CONTROLLER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SECRETS_STORE_PROVIDER_AZURE_VERSIONS=\"\n0.0.12\n\"\nfor CSI_SECRETS_STORE_PROVIDER_AZURE_VERSION in ${CSI_SECRETS_STORE_PROVIDER_AZURE_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/azure/secrets-store/provider-azure:${CSI_SECRETS_STORE_PROVIDER_AZURE_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCSI_SECRETS_STORE_DRIVER_VERSIONS=\"\n0.0.19\n\"\nfor CSI_SECRETS_STORE_DRIVER_VERSION in ${CSI_SECRETS_STORE_DRIVER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes-csi/secrets-store/driver:v${CSI_SECRETS_STORE_DRIVER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAAD_POD_IDENTITY_MIC_VERSIONS=\"\n1.6.1\n\"\nfor AAD_POD_IDENTITY_MIC_VERSION in ${AAD_POD_IDENTITY_MIC_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/aad-pod-identity/mic:${AAD_POD_IDENTITY_MIC_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nAAD_POD_IDENTITY_NMI_VERSIONS=\"\n1.6.1\n\"\nfor AAD_POD_IDENTITY_NMI_VERSION in ${AAD_POD_IDENTITY_NMI_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/k8s/aad-pod-identity/nmi:${AAD_POD_IDENTITY_NMI_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\nCLUSTER_PROPORTIONAL_AUTOSCALER_VERSIONS=\"\n1.8.5\n\"\nfor CLUSTER_PROPORTIONAL_AUTOSCALER_VERSION in ${CLUSTER_PROPORTIONAL_AUTOSCALER_VERSIONS}; do\n  CONTAINER_IMAGE=\"mcr.microsoft.com/oss/kubernetes/autoscaler/cluster-proportional-autoscaler:${CLUSTER_PROPORTIONAL_AUTOSCALER_VERSION}\"\n  loadContainerImage ${CONTAINER_IMAGE}\n  echo \"  - ${CONTAINER_IMAGE}\" >> ${VHD_LOGS_FILEPATH}\ndone\n\ndf -h\n\n# warn at 75% space taken\n[ -s $(df -P | grep '/dev/sda1' | awk '0+$5 >= 75 {print}') ] || echo \"WARNING: 75% of /dev/sda1 is used\" >> ${VHD_LOGS_FILEPATH}\n# error at 95% space taken\n[ -s $(df -P | grep '/dev/sda1' | awk '0+$5 >= 95 {print}') ] || exit 1\n\necho \"Using kernel:\" >> ${VHD_LOGS_FILEPATH}\ntee -a ${VHD_LOGS_FILEPATH} < /proc/version\n{ printf \"Installed apt packages:\\n\"; apt list --installed | grep -v 'Listing...'; } >> ${VHD_LOGS_FILEPATH}\n{\n  echo \"Install completed successfully on \" $(date)\n  echo \"VSTS Build NUMBER: ${BUILD_NUMBER}\"\n  echo \"VSTS Build ID: ${BUILD_ID}\"\n  echo \"Commit: ${COMMIT}\"\n  echo \"Feature flags: ${FEATURE_FLAGS}\"\n} >> ${VHD_LOGS_FILEPATH}\n", "num_lines": 382}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncopyPackerFiles() {\n  SYSCTL_CONFIG_SRC=/home/packer/sysctl-d-60-CIS.conf\n  SYSCTL_CONFIG_DEST=/etc/sysctl.d/60-CIS.conf\n  RSYSLOG_CONFIG_SRC=/home/packer/rsyslog-d-60-CIS.conf\n  RSYSLOG_CONFIG_DEST=/etc/rsyslog.d/60-CIS.conf\n  ETC_ISSUE_CONFIG_SRC=/home/packer/etc-issue\n  ETC_ISSUE_CONFIG_DEST=/etc/issue\n  ETC_ISSUE_NET_CONFIG_SRC=/home/packer/etc-issue.net\n  ETC_ISSUE_NET_CONFIG_DEST=/etc/issue.net\n  ETC_ISSUE_STIG_NET_CONFIG_SRC=/home/packer/etc-issue-stig.net\n  ETC_ISSUE_STIG_NET_CONFIG_DEST=/etc/issue-stig.net\n  SSHD_CONFIG_SRC=/home/packer/sshd_config\n  SSHD_CONFIG_DEST=/etc/ssh/sshd_config\n  MODPROBE_CIS_SRC=/home/packer/modprobe-CIS.conf\n  MODPROBE_CIS_DEST=/etc/modprobe.d/CIS.conf\n  PWQUALITY_CONF_SRC=/home/packer/pwquality-CIS.conf\n  PWQUALITY_CONF_DEST=/etc/security/pwquality.conf\n  PAM_D_SU_SRC=/home/packer/pam-d-su\n  PAM_D_SU_DEST=/etc/pam.d/su\n  PROFILE_D_CIS_SH_SRC=/home/packer/profile-d-cis.sh\n  PROFILE_D_CIS_SH_DEST=/etc/profile.d/CIS.sh\n  LABEL_NODES_SRC=/home/packer/label-nodes.sh\n  LABEL_NODES_DEST=/opt/azure/containers/label-nodes.sh\n  LABEL_NODES_SERVICE_SRC=/home/packer/label-nodes.service\n  LABEL_NODES_SERVICE_DEST=/etc/systemd/system/label-nodes.service\n  CIS_SRC=/home/packer/cis.sh\n  CIS_DEST=/opt/azure/containers/provision_cis.sh\n  APT_PREFERENCES_SRC=/home/packer/apt-preferences\n  APT_PREFERENCES_DEST=/etc/apt/preferences\n  HEALTH_MONITOR_SRC=/home/packer/health-monitor.sh\n  HEALTH_MONITOR_DEST=/usr/local/bin/health-monitor.sh\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC=/home/packer/docker_clear_mount_propagation_flags.conf\n  DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST=/etc/systemd/system/docker.service.d/clear_mount_propagation_flags.conf\n  GENERATE_PROXY_CERTS_SRC=/home/packer/generateproxycerts.sh\n  GENERATE_PROXY_CERTS_DEST=/etc/kubernetes/generate-proxy-certs.sh\n  COLLECT_LOGS_SRC=/home/packer/collect-logs.sh\n  COLLECT_LOGS_DEST=/opt/azure/containers/collect-logs.sh\n  NOTICE_SRC=/home/packer/NOTICE.txt\n  NOTICE_DEST=/NOTICE.txt\n  PROVISION_AZURESTACK_CNI_SRC=/home/packer/provision_azurestack_cni.sh\n  PROVISION_AZURESTACK_CNI_DEST=/opt/azure/containers/provision_azurestack_cni.sh\n  UBUNTU_STIG_SRC=/home/packer/provision_stig_ubuntu2004.sh\n  UBUNTU_STIG_DEST=/opt/azure/containers/provision_stig_ubuntu2004.sh\n  AUDITD_RULES_SRC=/home/packer/auditd-rules\n  AUDITD_RULES_DEST=/etc/audit/rules.d/aks-engine.rules\n  if [[ ${UBUNTU_RELEASE} == \"16.04\" ]]; then\n    SSHD_CONFIG_SRC=/home/packer/sshd_config_1604\n  fi\n  cpAndMode $SYSCTL_CONFIG_SRC $SYSCTL_CONFIG_DEST 644\n  cpAndMode $RSYSLOG_CONFIG_SRC $RSYSLOG_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_CONFIG_SRC $ETC_ISSUE_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_NET_CONFIG_SRC $ETC_ISSUE_NET_CONFIG_DEST 644\n  cpAndMode $ETC_ISSUE_STIG_NET_CONFIG_SRC $ETC_ISSUE_STIG_NET_CONFIG_DEST 644\n  cpAndMode $SSHD_CONFIG_SRC $SSHD_CONFIG_DEST 644\n  cpAndMode $MODPROBE_CIS_SRC $MODPROBE_CIS_DEST 644\n  cpAndMode $PWQUALITY_CONF_SRC $PWQUALITY_CONF_DEST 600\n  cpAndMode $PAM_D_SU_SRC $PAM_D_SU_DEST 644\n  cpAndMode $PROFILE_D_CIS_SH_SRC $PROFILE_D_CIS_SH_DEST 755\n  cpAndMode $LABEL_NODES_SRC $LABEL_NODES_DEST 744\n  cpAndMode $LABEL_NODES_SERVICE_SRC $LABEL_NODES_SERVICE_DEST 644\n  cpAndMode $CIS_SRC $CIS_DEST 744\n  cpAndMode $APT_PREFERENCES_SRC $APT_PREFERENCES_DEST 644\n  cpAndMode $HEALTH_MONITOR_SRC $HEALTH_MONITOR_DEST 544\n  cpAndMode $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_SRC $DOCKER_CLEAR_MOUNT_PROPAGATION_FLAGS_DEST 644\n  cpAndMode $GENERATE_PROXY_CERTS_SRC $GENERATE_PROXY_CERTS_DEST 744\n  cpAndMode $COLLECT_LOGS_SRC $COLLECT_LOGS_DEST 744\n  cpAndMode $NOTICE_SRC $NOTICE_DEST 444\n  cpAndMode $PROVISION_AZURESTACK_CNI_SRC $PROVISION_AZURESTACK_CNI_DEST 744\n  cpAndMode $UBUNTU_STIG_SRC $UBUNTU_STIG_DEST 744\n  cpAndMode $AUDITD_RULES_SRC $AUDITD_RULES_DEST 744\n}\n\ncpAndMode() {\n  src=$1; dest=$2; mode=$3\n  DIR=$(dirname \"$dest\") && mkdir -p ${DIR} && cp $src $dest && chmod $mode $dest || exit 113\n}\n", "num_lines": 79}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n####################################################\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_ID\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SERVICE_PRINCIPAL_CLIENT_SECRET\" ]; then\n    echo \"must provide a SERVICE_PRINCIPAL_CLIENT_SECRET env var\"\n    exit 1;\nfi\n\nif [ -z \"$TENANT_ID\" ]; then\n    echo \"must provide a TENANT_ID env var\"\n    exit 1;\nfi\n\nif [ -z \"$SUBSCRIPTION_ID_TO_CLEANUP\" ]; then\n    echo \"must provide a SUBSCRIPTION_ID_TO_CLEANUP env var\"\n    exit 1;\nfi\n\nif [ -z \"$EXPIRATION_IN_HOURS\" ]; then\n    EXPIRATION_IN_HOURS=2\nfi\n\nif [ -z \"$DRY_RUN\" ]; then\n    echo \"no DRY_RUN env var provided, will default to true\"\n    DRY_RUN=true\nfi\n\nif az login --service-principal \\\n\t\t--username \"${SERVICE_PRINCIPAL_CLIENT_ID}\" \\\n\t\t--password \"${SERVICE_PRINCIPAL_CLIENT_SECRET}\" \\\n\t\t--tenant \"${TENANT_ID}\" &>/dev/null; then\n    echo \"Successfully logged in using service principal\"\nelse\n    exit 1\nfi\n\n# set to the sub id we want to cleanup\nif az account set -s $SUBSCRIPTION_ID_TO_CLEANUP; then\n    echo \"Successfully set subscription\"\nelse\n    exit 1\nfi\n\n# convert to seconds so we can compare it against the \"tags.now\" property in the resource group metadata\n(( expirationInSecs = ${EXPIRATION_IN_HOURS} * 60 * 60 ))\n# deadline = the \"date +%s\" representation of the oldest age we're willing to keep\n(( deadline=$(date +%s)-${expirationInSecs%.*} ))\n\n# clean up Packer resource groups\n\n# find packer resource groups created before our deadline\necho \"Looking for resource groups created over ${EXPIRATION_IN_HOURS} hours ago...\"\nfor resourceGroup in $( az group list | jq --arg dl $deadline '.[] | select(.name | contains(\"packer-Resource-Group\") or contains(\"pkr-Resource-Group\")) | select(.tags.now < $dl).name' | tr -d '\\\"' || true); do\n    for deployment in $(az deployment group list -g $resourceGroup | jq '.[] | .name' | tr -d '\\\"' || true); do\n        echo \"Will delete deployment ${deployment} from resource group ${resourceGroup}...\"\n        if [[ \"${DRY_RUN}\" = false ]]; then\n            az deployment group delete -n $deployment -g $resourceGroup || echo \"unable to delete deployment ${deployment}, will continue...\"\n        else\n            echo \"skipping because DRY_RUN is set to true\"\n        fi\n    done\n    echo \"Will delete resource group ${resourceGroup}...\"\n    # delete old resource groups\n    if [[ \"${DRY_RUN}\" = false ]]; then\n        az group delete -y -n $resourceGroup --no-wait >> delete.log || echo \"unable to delete resource group ${resourceGroup}, will continue...\"\n    else\n            echo \"skipping because DRY_RUN is set to true\"\n    fi\ndone\n\n# cleanup storage accounts. We only want to delete storage accounts created by Packer, NOT the classic storage account that is used by the Marketplace to publish the VHDs as images.\nif [ -z \"$STORAGE_RG\" ]; then\n    echo \"must provide a STORAGE_RG env var\"\n    exit 1;\nfi\n\necho \"Looking for storage accounts in ${STORAGE_RG} created over ${EXPIRATION_IN_HOURS} hours ago...\"\nfor storage_account in $(az storage account list -g $STORAGE_RG | jq --arg dl $deadline '.[] | select(.tags.now < $dl).name' | tr -d '\\\"' || true); do\n    echo \"Will delete storage account ${storage_account} from resource group ${STORAGE_RG}...\"\n    if [[ \"${DRY_RUN}\" = false ]]; then\n        az storage account delete -y -n $storage_account -g $STORAGE_RG || echo \"unable to delete storage account ${storage_account}, will continue...\"\n    else\n            echo \"skipping because DRY_RUN is set to true\"\n    fi\ndone\n", "num_lines": 92}
{"repo_name": "aks-engine-azurestack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nrequired_env_vars=(\n    \"SKU_PREFIX\"\n    \"SKU_TEMPLATE_FILE\"\n    \"AZURE_TENANT_ID\"\n    \"AZURE_CLIENT_ID\"\n    \"AZURE_CLIENT_SECRET\"\n    \"PUBLISHER\"\n    \"OFFER\"\n    \"CONTAINER_RUNTIME\"\n)\n\nfor v in \"${required_env_vars[@]}\"\ndo\n    if [ -z \"${!v}\" ]; then\n        echo \"$v was not set!\"\n        exit 1\n    fi\ndone\n\nif [ ! -f \"$SKU_TEMPLATE_FILE\" ]; then\n    echo \"Could not find sku template file: ${SKU_TEMPLATE_FILE}!\"\n    exit 1\nfi\n\n(set -x; ls -lhR artifacts )\n\nVHD_INFO=\"artifacts/vhd/windows-vhd-publishing-info.json\"\n\nif [ ! -f \"$VHD_INFO\" ]; then\n    echo \"Could not find VHD info file: ${VHD_INFO}!\"\n    exit 1\nfi\n\nshort_date=$(date +\"%y%m\")\npretty_date=$(date +\"%b %Y\")\n\nsku_id=\"${SKU_PREFIX}-${short_date}\"\n\necho \"Get access token for use with pub\"\naz login --service-principal -u ${AZURE_CLIENT_ID} -p ${AZURE_CLIENT_SECRET} --tenant ${AZURE_TENANT_ID} --allow-no-subscriptions\ntoken=$(az account get-access-token --resource https://cloudpartner.azure.com --query \"accessToken\" -o tsv)\nexport AZURE_TOKEN=$token\n\necho \"Checking if offer contains SKU: $sku_id\"\n# Check if SKU already exists in offer\nset -x \nhack/tools/bin/pub skus list -p $PUBLISHER -o $OFFER | jq \".[] | .planId\" | tr -d '\"' | tee skus.txt\nset +x\necho \"\"\n\nif grep -q \"^$sku_id$\" skus.txt; then\n    echo \"Offer already has SKU\"\nelse\n    echo \"Creating new SKU\"\n\n    < $SKU_TEMPLATE_FILE sed s/{{ID}}/\"$sku_id\"/ | sed s/{{MONTH-YEAR}}/\"$pretty_date/\" | sed s/{{CONTAINER_RUNTIME}}/\"$CONTAINER_RUNTIME/\" > sku.json\n\n    echo \"\" ; cat sku.json ; echo \"\"\n\n    (set -x ; hack/tools/bin/pub skus put -p $PUBLISHER -o \"$OFFER\" -f sku.json ; echo \"\")\nfi\n\n# Get VHD version info for windows-vhd-publishing-info.json produced by previous pipeline stage\nvhd_url=$(< $VHD_INFO jq -r \".vhd_url\")\nvhd_version=$(< $VHD_INFO jq -r \".windows_version\")\nversion_date=$(date +\"%y%m%d\")\nimage_version=\"${vhd_version}.${version_date}\"\n\n# media name must be under 63 characters\nmedia_name=\"aks-windows-${SKU_PREFIX}-${image_version}\"\nif [ \"${#media_name}\" -ge 63 ]; then\n\techo \"$media_name should be under 63 characters\"\n\texit 1\nfi\n\npublished_date=$(date +\"%m/%d/%Y\")\n\nset -x\nhack/tools/bin/pub versions put corevm -p $PUBLISHER -o $OFFER -s $sku_id --version $image_version --vhd-uri $vhd_url --media-name $media_name --label \"AKS Base Image for Windows\" --desc \"AKS Base Image for Windows\" --published-date \"$published_date\"\nset +x\n", "num_lines": 83}
{"repo_name": "aks-github-runner", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nusage=\"$(basename \"$0\") [-h] [-c CLUSTER_NAME] [-g RESOURCE_GROUP_NAME] [-s SUBSCRIPTION_ID] [-r REGION]\nCreates a service principal and storage account for using terraform on Azure\nwhere:\n    -h  show this help text\n    -c  desired cluster name\n    -g  desired resource group name\n    -s  subscription id for cluster\n    -r  region for cluster\"\n\nwhile getopts h:c:g:s:r: flag\ndo\n    case \"${flag}\" in\n        h) echo \"$usage\"; exit;;\n        c) cluster_name=${OPTARG};;\n        g) resource_group_name=${OPTARG};;\n        s) subscription=${OPTARG};;\n        r) region=${OPTARG};;\n        :) printf \"missing argument for -%s\\n\" \"$OPTARG\" >&2; echo \"$usage\" >&2; exit 1;;\n        \\?) printf \"illegal option: -%s\\n\" \"$OPTARG\" >&2; echo \"$usage\" >&2; exit 1;;\n    esac\ndone\n\n# mandatory arguments\nif [ ! \"$cluster_name\" ] || [ ! \"$resource_group_name\" ] || [ ! \"$subscription\" ] || [ ! \"$region\" ]; then\n  echo \"all arguments must be provided\"\n  echo \"$usage\" >&2; exit 1\nfi\n\nif ! command -v jq &> /dev/null\nthen\n    echo \"jq could not be found, please make sure jq is installed and in your path \"\n    exit\nfi\n\nif ! command -v az &> /dev/null\nthen\n    echo \"az could not be found, please make sure azure-cli is installed and in your path\"\n    exit\nfi\n\nif ! command -v gh &> /dev/null\nthen\n    echo \"gh could not be found, please make sure github cli is installed and in your path\"\n    exit\nfi\n\n\necho \"Arguments provided:\"\necho \"Cluster Name: $cluster_name\";\necho \"Resource Group Name: $resource_group_name\";\necho \"Subscription: $subscription\";\necho \"Region: $region\";\n\nSTORAGE_ACCOUNT_NAME=$(echo \"${resource_group_name}\" | tr '[:upper:]' '[:lower:]')$RANDOM\nCONTAINER_NAME=$(echo \"${cluster_name}\" | tr '[:upper:]' '[:lower:]')tfstate\n\naz account set --subscription $subscription &> /dev/null\n# Create resource group\naz group create --location $region --resource-group $resource_group_name &> /dev/null\n\n#Create service principal and give it access to group\nSP_OUTPUT=$(az ad sp create-for-rbac --name $resource_group_name --role contributor --scopes /subscriptions/$subscription)\n# echo $SP_OUTPUT\nARM_CLIENT_ID=$(echo $SP_OUTPUT | jq -r .appId)\nARM_CLIENT_SECRET=$(echo $SP_OUTPUT | jq -r .password)\nARM_TENANT_ID=$(echo $SP_OUTPUT | jq -r .tenant)\n\n# Create storage account\naz storage account create --resource-group $resource_group_name --name $STORAGE_ACCOUNT_NAME --sku Standard_LRS --encryption-services blob &> /dev/null\n\n# Get storage account key\nACCOUNT_KEY=$(az storage account keys list --resource-group $resource_group_name --account-name $STORAGE_ACCOUNT_NAME --query '[0].value' -o tsv) \n\n# Create blob container\naz storage container create --name $CONTAINER_NAME --account-name $STORAGE_ACCOUNT_NAME --account-key $ACCOUNT_KEY &> /dev/null\n\n# gh secret set\necho \"Saving secrets to github\"\ngh secret set \"CLUSTER_NAME\" -b $cluster_name\ngh secret set \"RESOURCE_GROUP_NAME\" -b $resource_group_name\ngh secret set \"STORAGE_ACCOUNT_NAME\" -b $STORAGE_ACCOUNT_NAME\ngh secret set \"STORAGE_CONTAINER_NAME\" -b $CONTAINER_NAME\ngh secret set \"STORAGE_ACCESS_KEY\" -b $ACCOUNT_KEY\ngh secret set \"ARM_CLIENT_ID\" -b $ARM_CLIENT_ID\ngh secret set \"ARM_CLIENT_SECRET\" -b $ARM_CLIENT_SECRET\ngh secret set \"ARM_SUBSCRIPTION_ID\" -b $subscription\ngh secret set \"ARM_TENANT_ID\" -b $ARM_TENANT_ID\n\n# echo \"____________________________________________________________\"\n# echo \"____________________________________________________________\"\n# echo \"CLUSTER_NAME: $cluster_name\";\n# echo \"RESOURCE_GROUP_NAME: $resource_group_name\";\n# echo \"STORAGE_ACCOUNT_NAME: $STORAGE_ACCOUNT_NAME\"\n# echo \"STORAGE_CONTAINER_NAME: $CONTAINER_NAME\"\n# echo \"STORAGE_ACCESS_KEY: $ACCOUNT_KEY\"\n# echo \"ARM_CLIENT_ID: $ARM_CLIENT_ID\"\n# echo \"ARM_CLIENT_SECRET: $ARM_CLIENT_SECRET\"\n# echo \"ARM_SUBSCRIPTION_ID: $subscription\"\n# echo \"ARM_TENANT_ID: $ARM_TENANT_ID\"\n\n# below is only needed if running locally, and not as part of a workflow\nexport RESOURCE_GROUP_NAME=$resource_group_name\nexport ARM_CLIENT_ID=$ARM_CLIENT_ID\nexport ARM_CLIENT_SECRET=$ARM_CLIENT_SECRET\nexport STORAGE_ACCOUNT_NAME=$STORAGE_ACCOUNT_NAME\nexport STORAGE_CONTAINER_NAME=$CONTAINER_NAME\nexport ARM_ACCESS_KEY=$ACCOUNT_KEY\nexport ARM_SUBSCRIPTION_ID=$subscription\nexport ARM_TENANT_ID=$ARM_TENANT_ID\nexport CLUSTER_NAME=$cluster_name", "num_lines": 112}
{"repo_name": "aks-github-runner", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -eEuo pipefail\n\nACTIONS_RUNNER_INPUT_NAME=$HOSTNAME\nexport RUNNER_ALLOW_RUNASROOT=1\n\nTOKEN=\"$(curl -sS --request POST --url \"https://api.github.com/repos/${REPO_OWNER}/${REPO_NAME}/actions/runners/registration-token\" --header \"authorization: Bearer ${GH_TOKEN}\"  --header 'content-type: application/json' | jq -r .token)\"\n\n/actions-runner/config.sh --unattended --replace --work \"/tmp\" --url \"$ACTIONS_RUNNER_INPUT_URL\" --token \"$TOKEN\" --labels aks-runner\n/actions-runner/bin/runsvc.sh", "num_lines": 10}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "DRIVER_VERSION=\"${DRIVER_VERSION}\"\nDRIVER_KIND=\"${DRIVER_KIND}\"\nNVIDIA_DOCKER_VERSION=\"2.8.0-1\"\nNVIDIA_CONTAINER_RUNTIME_VERSION=\"3.13.0\"\nNVIDIA_CONTAINER_TOOLKIT_VER=\"1.13.1\"\nNVIDIA_PACKAGES=\"libnvidia-container1 libnvidia-container-tools nvidia-container-toolkit-base nvidia-container-toolkit\"\nGPU_DEST=\"/usr/local/nvidia\"\n", "num_lines": 8}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\nsource /etc/os-release\nsource /opt/gpu/config.sh\n\nworkdir=\"$(mktemp -d)\"\npushd \"$workdir\" || exit\n\nif [[ \"${DRIVER_KIND}\" == \"cuda\" ]]; then\n    RUNFILE=\"NVIDIA-Linux-x86_64-${DRIVER_VERSION}\"\n    curl -fsSLO https://us.download.nvidia.com/tesla/${DRIVER_VERSION}/${RUNFILE}.run \nelif [[ \"${DRIVER_KIND}\" == \"grid\" ]]; then\n    RUNFILE=\"NVIDIA-Linux-x86_64-${DRIVER_VERSION}-grid-azure\"\n    curl -fsSLO \"${DRIVER_URL}\"\nelse\n    echo \"Invalid driver kind: ${DRIVER_KIND}\"\n    exit 1\nfi\n\n# download nvidia drivers, move to permanent cache\nmv ${RUNFILE}.run /opt/gpu/${RUNFILE}.run\npushd /opt/gpu\n# extract runfile, takes some time, so do ahead of time\nsh /opt/gpu/${RUNFILE}.run -x\nrm /opt/gpu/${RUNFILE}.run\npopd\n\n\nif [[ \"${DRIVER_KIND}\" == \"cuda\" ]]; then\n    # download fabricmanager for nvlink based systems, e.g. multi instance gpu vms.\n    curl -fsSLO https://developer.download.nvidia.com/compute/cuda/redist/fabricmanager/linux-x86_64/fabricmanager-linux-x86_64-${DRIVER_VERSION}-archive.tar.xz\n    tar -xvf fabricmanager-linux-x86_64-${DRIVER_VERSION}-archive.tar.xz\n    mv fabricmanager-linux-x86_64-${DRIVER_VERSION}-archive /opt/gpu/fabricmanager-linux-x86_64-${DRIVER_VERSION}\n    mv /opt/gpu/fm_run_package_installer.sh /opt/gpu/fabricmanager-linux-x86_64-${DRIVER_VERSION}/sbin/fm_run_package_installer.sh\nfi\n\n# configure nvidia apt repo to cache packages\ncurl -fsSLO https://nvidia.github.io/nvidia-docker/gpgkey\ngpg --dearmor -o aptnvidia.gpg gpgkey\nmv aptnvidia.gpg /etc/apt/trusted.gpg.d/aptnvidia.gpg\ncurl -fsSL https://nvidia.github.io/nvidia-docker/ubuntu${VERSION_ID}/nvidia-docker.list -o /etc/apt/sources.list.d/nvidia-docker.list\n\napt update\n\n# download nvidia debian packages for nvidia-container-runtime compat\nfor apt_package in $NVIDIA_PACKAGES; do\n    apt-get download ${apt_package}=${NVIDIA_CONTAINER_TOOLKIT_VER}*\n    mv ${apt_package}_${NVIDIA_CONTAINER_TOOLKIT_VER}* /opt/gpu\ndone\napt-get download nvidia-container-runtime=${NVIDIA_CONTAINER_RUNTIME_VERSION}*\n\n# move debs to permanent cache\nmv nvidia-container-runtime_${NVIDIA_CONTAINER_RUNTIME_VERSION}* /opt/gpu\n\n# nvidia-docker2 for docker runtime\napt-get download nvidia-docker2=${NVIDIA_DOCKER_VERSION}\nmkdir -p /tmp/nvidia-docker2\ndpkg-deb -R ./nvidia-docker2_${NVIDIA_DOCKER_VERSION}_all.deb /tmp/nvidia-docker2\nmkdir -p /opt/gpu/nvidia-docker2_${NVIDIA_DOCKER_VERSION}\ncp -r /tmp/nvidia-docker2/usr/* /opt/gpu/nvidia-docker2_${NVIDIA_DOCKER_VERSION}/\n\npopd || exit\nrm -r \"$workdir\"\n", "num_lines": 65}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o pipefail\nset -o nounset\n\nset -x\n\nsleep=\"${2:-}\"\n\n# clean up any existing gpu files\n# can happen if using a different version than cached\nrm -r /mnt/gpu/* || true\n\nset -o errexit\nif [[ -z \"${1}\" ]]; then\n    echo \"Must provide a non-empty action as first argument\"\n    exit 1\nfi\n\nif [[ \"${1}\" == \"copy\" ]]; then\n    echo \"copying gpu cache files and exiting\"\n    cp -a /opt/gpu/. /mnt/gpu/\n    echo \"Completed successfully!\"\n    exit 0\nfi\n\nif [[ \"${1}\" == \"install\" ]]; then\n    echo \"copying gpu cache files\"\n    cp -a /opt/gpu/. /mnt/gpu/\n    echo \"copied successfully!\"\nfi\n\nACTION_FILE=\"/opt/actions/install.sh\"\n\nif [[ ! -f \"$ACTION_FILE\" ]]; then\n    echo \"Expected to find action file '$ACTION_FILE', but did not exist\"\n    exit 1\nfi\n\necho \"Cleaning up stale actions\"\n\nrm -rf /mnt/actions/*\n\necho \"Copying fresh actions\"\n\ncp -R /opt/actions/. /mnt/actions\n\necho \"Executing nsenter\"\n\nnsenter -t 1 -m bash \"${ACTION_FILE}\"\nRESULT=\"${PIPESTATUS[0]}\"\n\nif [ $RESULT -eq 0 ]; then\n    # Success.\n    rm -rf /mnt/actions/*\n    echo \"Completed successfully!\"\nelse\n    echo \"Failed during nsenter command execution\"\n    exit 1\nfi\n\nif [[ -z \"${sleep}\" ]]; then\n  exit 0\nfi\n\necho \"Sleeping forever\"\n\nsleep infinity\n", "num_lines": 68}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nset -uxo pipefail\n\necho \"Staring NVIDIA Fabric Manager installation\"\n\nROOTDIR=\"$(dirname $(realpath \"${BASH_SOURCE[0]}\"))/..\"\n\n# currently support only Ubuntu and Debian\nlinuxdistro=`grep -w ID /etc/*-release | awk -F '=' '{print $2}'`\nif [ \"$linuxdistro\" != \"ubuntu\" ] && [ \"$linuxdistro\" != \"debian\" ]; then\n  echo \"Error: .RUN based installation is supported only for Ubuntu and Debian distributions\"\n  #exit\nfi\n\necho \"Checking for running Fabric Manager service\"\n\nSTATUS=`systemctl is-active nvidia-fabricmanager`\n  if [ \"${STATUS}\" == 'active' ]; then\n    echo \"Fabric Manager service is running, stopping the same.....\"\n    systemctl stop nvidia-fabricmanager\n  else\n    echo \"Fabric Manager service is not running.....\"\n  fi\n\n# copy all the files\necho \"Copying files to desired location\"\ncp ${ROOTDIR}/lib/libnvfm.so.1 /usr/lib/x86_64-linux-gnu\ncp -P ${ROOTDIR}/lib/libnvfm.so   /usr/lib/x86_64-linux-gnu\n\ncp ${ROOTDIR}/bin/nv-fabricmanager  /usr/bin\ncp ${ROOTDIR}/bin/nvswitch-audit  /usr/bin\ncp ${ROOTDIR}/systemd/nvidia-fabricmanager.service  /lib/systemd/system\n\nmkdir /usr/share/nvidia  > /dev/null 2>&1\nmkdir /usr/share/nvidia/nvswitch/  > /dev/null 2>&1\ncp ${ROOTDIR}/share/nvidia/nvswitch/dgx2_hgx2_topology    /usr/share/nvidia/nvswitch/\ncp ${ROOTDIR}/share/nvidia/nvswitch/dgxa100_hgxa100_topology    /usr/share/nvidia/nvswitch/\ncp ${ROOTDIR}/etc/fabricmanager.cfg  /usr/share/nvidia/nvswitch/\n\ncp ${ROOTDIR}/include/nv_fm_agent.h     /usr/include\ncp ${ROOTDIR}/include/nv_fm_types.h     /usr/include\n\nmkdir /usr/share/doc/nvidia-fabricmanager > /dev/null 2>&1\ncp ${ROOTDIR}/LICENSE  /usr/share/doc/nvidia-fabricmanager\ncp ${ROOTDIR}/third-party-notices.txt  /usr/share/doc/nvidia-fabricmanager\n\n# enable Fabric Manager service\nsystemctl enable nvidia-fabricmanager\n\n# let the user start FM service manually.\necho \"Fabric Manager installation completed.\"\necho \"Note: Fabric Manager service is not started. Start it using systemctl commands (like systemctl start nvidia-fabricmanager)\"\n", "num_lines": 53}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n\nsource /opt/gpu/config.sh\nsource /opt/gpu/package_manager_helpers.sh\n\ntrap 'PS4=\"+ \"' exit\nPS4='+ $(date -u -I\"seconds\" | cut -c1-19) '\n\nKERNEL_NAME=$(uname -r)\nLOG_FILE_NAME=\"/var/log/nvidia-installer-$(date +%s).log\"\n\nset +euo pipefail\nopen_devices=\"$(lsof /dev/nvidia* 2>/dev/null)\"\necho \"Open devices: $open_devices\"\n\nopen_gridd=\"$(lsof /usr/bin/nvidia-gridd 2>/dev/null)\"\necho \"Open gridd: $open_gridd\"\n\nset -euo pipefail\n\ninstall_linux_headers() {\n  apt install -y linux-headers-$(uname -r) --no-install-recommends\n}\n\nuse_package_manager_with_retries wait_for_apt_locks install_linux_headers 10 3\n\n# install cached nvidia debian packages for container runtime compatibility\ninstall_cached_nvidia_packages() {\nfor apt_package in $NVIDIA_PACKAGES; do\n    dpkg -i --force-overwrite /opt/gpu/${apt_package}_${NVIDIA_CONTAINER_TOOLKIT_VER}*\ndone\ndpkg -i --force-overwrite /opt/gpu/nvidia-container-runtime_${NVIDIA_CONTAINER_RUNTIME_VERSION}*\n}\n\nuse_package_manager_with_retries wait_for_dpkg_lock install_cached_nvidia_packages 10 3\n\n# blacklist nouveau driver, nvidia driver dependency\ncp /opt/gpu/blacklist-nouveau.conf /etc/modprobe.d/blacklist-nouveau.conf\nupdate-initramfs -u\n\n# clean up lingering files from previous install\nset +e\numount -l /usr/lib/x86_64-linux-gnu || true\numount -l /tmp/overlay || true\nrm -r /tmp/overlay || true\nset -e\n\n# set up overlayfs to change install location of nvidia libs from /usr/lib/x86_64-linux-gnu to /usr/local/nvidia\n# add an extra layer of indirection via tmpfs because it's not possible to have an overlayfs on an overlayfs (i.e., inside a container)\nmkdir /tmp/overlay\nmount -t tmpfs tmpfs /tmp/overlay\nmkdir /tmp/overlay/{workdir,lib64}\nmkdir -p ${GPU_DEST}/lib64\nmount -t overlay overlay -o lowerdir=/usr/lib/x86_64-linux-gnu,upperdir=/tmp/overlay/lib64,workdir=/tmp/overlay/workdir /usr/lib/x86_64-linux-gnu\n\nif [[ \"${DRIVER_KIND}\" == \"cuda\" ]]; then\n    RUNFILE=\"NVIDIA-Linux-x86_64-${DRIVER_VERSION}\"\nelif [[ \"${DRIVER_KIND}\" == \"grid\" ]]; then\n    RUNFILE=\"NVIDIA-Linux-x86_64-${DRIVER_VERSION}-grid-azure\"\nelse\n    echo \"Invalid driver kind: ${DRIVER_KIND}\"\n    exit 1\nfi\n\n# install nvidia drivers\npushd /opt/gpu\n/opt/gpu/${RUNFILE}/nvidia-installer -s -k=$KERNEL_NAME --log-file-name=${LOG_FILE_NAME} -a --no-drm --dkms --utility-prefix=\"${GPU_DEST}\" --opengl-prefix=\"${GPU_DEST}\"\npopd\n\n# move nvidia libs to correct location from temporary overlayfs\ncp -a /tmp/overlay/lib64 ${GPU_DEST}/lib64\n\n# grid starts a daemon that prevents copying binaries\nif [ \"${DRIVER_KIND}\" == \"grid\" ]; then\n    systemctl stop nvidia-gridd || true\nfi\n\n# move nvidia binaries to /usr/bin...because we like that?\ncp -rvT ${GPU_DEST}/bin /usr/bin || true\n\n# restart that daemon, lol\nif [ \"${DRIVER_KIND}\" == \"grid\" ]; then\n    systemctl restart nvidia-gridd || true\nfi\n\n# configure system to know about nvidia lib paths\necho \"${GPU_DEST}/lib64\" > /etc/ld.so.conf.d/nvidia.conf\nldconfig \n\n# unmount, cleanup\nset +e\numount -l /usr/lib/x86_64-linux-gnu\numount /tmp/overlay\nrm -r /tmp/overlay\nset -e\n\n# validate that nvidia driver is working\ndkms status\nnvidia-modprobe -u -c0\n\n# configure persistence daemon\n# decreases latency for later driver loads\n# reduces nvidia-smi invocation time 10x from 30 to 2 sec \n# notable on large VM sizes with multiple GPUs\n# especially when nvidia-smi process is in CPU cgroup\ncp /opt/gpu/nvidia-persistenced.service /etc/systemd/system/nvidia-persistenced.service\nsystemctl enable nvidia-persistenced.service\nsystemctl restart nvidia-persistenced.service\nnvidia-smi\n\ncp -r  /opt/gpu/nvidia-docker2_${NVIDIA_DOCKER_VERSION}/* /usr/\n\n# install fabricmanager for nvlink based systems\nif [[ \"${DRIVER_KIND}\" == \"cuda\" ]]; then\n    bash /opt/gpu/fabricmanager-linux-x86_64-${DRIVER_VERSION}/sbin/fm_run_package_installer.sh\nfi\n\nmkdir -p /etc/containerd/config.d\ncp /opt/gpu/10-nvidia-runtime.toml /etc/containerd/config.d/10-nvidia-runtime.toml\n\nmkdir -p \"$(dirname /lib/udev/rules.d/71-nvidia-dev-char.rules)\"\ncp /opt/gpu/71-nvidia-char-dev.rules /lib/udev/rules.d/71-nvidia-dev-char.rules\n/usr/bin/nvidia-ctk system create-dev-char-symlinks --create-all\n\nrm -r /opt/gpu\n", "num_lines": 127}
{"repo_name": "aks-gpu", "repo_creator": "Azure", "programming_language": "Shell", "code": "wait_for_apt_locks() {\n    while fuser /var/lib/dpkg/lock /var/lib/apt/lists/lock /var/cache/apt/archives/lock >/dev/null 2>&1; do\n        echo 'Waiting for release of apt locks'\n        sleep 3\n    done\n}\n\nwait_for_dpkg_lock() {\n   while fuser /var/lib/dpkg/lock >/dev/null 2>&1; do\n     echo 'Waiting for release of dpkg locks'\n     sleep 3\n   done\n}\n\nuse_package_manager_with_retries() {\n  local wait_for_locks=$1\n  local install_dependencies=$2\n  local retries=$3\n  local sleep_duration=$4\n\n  export DEBIAN_FRONTEND=noninteractive\n  for i in $(seq 1 \"$3\"); do\n    $wait_for_locks\n    dpkg --configure -a --force-confdef\n    ($install_dependencies) && break\n    if [ \"$i\" -eq \"$retries\" ]; then\n      return 1\n    else sleep \"$sleep_duration\"\n    fi\n  done\n}", "num_lines": 31}
{"repo_name": "AKS-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#############################\n# Script Definition\n#############################\nlogpath=/var/log/deploymentscriptlog\n\n#############################\n# Upgrading Linux Distribution\n#############################\necho \"#############################\" >> $logpath\necho \"Upgrading Linux Distribution\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update >> $logpath\nsudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n#############################\n#Install Azure CLI\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n#############################\n#Install Docker\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n#############################\n#Install Kubectl\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Kubectl\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates curl\nsudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg\necho \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list\nsudo apt-get update\nsudo apt-get install -y kubectl\n\n\n#############################\n#Install Helm\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Helm\" >> $logpath\necho \"#############################\" >> $logpath\ncurl https://baltocdn.com/helm/signing.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https --yes\necho \"deb https://baltocdn.com/helm/stable/debian/ all main\" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list\nsudo apt-get update\nsudo apt-get install helm", "num_lines": 59}
{"repo_name": "AKS-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#############################\n# Script Definition\n#############################\nlogpath=/var/log/deploymentscriptlog\n\n#############################\n# Upgrading Linux Distribution\n#############################\necho \"#############################\" >> $logpath\necho \"Upgrading Linux Distribution\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update >> $logpath\nsudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n#############################\n#Install Azure CLI\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n#############################\n#Install Docker\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n#############################\n#Install Kubectl\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Kubectl\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates curl\nsudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg\necho \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list\nsudo apt-get update\nsudo apt-get install -y kubectl\n\n\n#############################\n#Install Helm\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Helm\" >> $logpath\necho \"#############################\" >> $logpath\ncurl https://baltocdn.com/helm/signing.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https --yes\necho \"deb https://baltocdn.com/helm/stable/debian/ all main\" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list\nsudo apt-get update\nsudo apt-get install helm", "num_lines": 59}
{"repo_name": "aks-node-ca-watcher", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\nset -x\n\nclean_up() {\n  kind delete cluster\n}\n\ntrap clean_up EXIT ERR\n\npoll_container() {\n  n=0; until ((n >= $2)); do $1 && break; n=$((n + 1)); sleep 5; done; ((n < $2))\n}\n\ncheck_if_first_cert_appeared_at_source() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [ -z \\$(ls -A \"$certSource\") ]; then\n     echo \"Cert files from secret didn't appear in /opt/certs\" >&2\n     exit 1\n  fi\nEOF\n}\n\ncheck_if_first_cert_copied_to_dest() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ ! -f \"\"$certDestination\"/\"$firstCertName\"\" ]]; then\n     echo \"expected \"$firstCertName\" in \"$certDestination\" but not found\" >&2\n     exit 1\n  fi\nEOF\n}\n\ncheck_if_first_cert_added_to_trusted_ca() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ ! -f \"/etc/ssl/certs/\"$firstCertNameNoExt\".pem\" ]]; then\n     echo \"expected \"$firstCertNameNoExt\" in /etc/ssl/certs but not found\" >&2\n     exit 1\n  fi\nEOF\n}\n\ncheck_if_first_cert_removed_from_dest() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ -f \"\"$certDestination\"/\"$firstCertName\"\" ]]; then\n       echo \"old file ($firstCertName) not removed from $certDestination\" >&2\n       exit 1\n  fi\nEOF\n}\n\ncheck_if_first_cert_removed_from_source() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ -f \"\"$certSource\"/\"$firstCertName\"\" ]]; then\n      echo \"old file ($firstCertName) not removed from $certSource\" >&2\n      exit 1\n  fi\nEOF\n}\n\ncheck_if_first_cert_removed_from_trusted_ca() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  for file in \"/etc/ssl/certs\"/*; do\n    name=\\${file##*/}\n     if [[ \\$name == \"$firstCertName\" ]]; then\n         echo \"old file (\"$firstCertName\") not removed from /etc/ssl/certs\" >&2\n         exit 1\n     fi\n  done\nEOF\n}\n\ncheck_if_new_certs_appeared_at_source () {\n  docker exec -i \"${containerName}\" bash <<EOF\n  srcFileCount=\\$(find $certSource -type f -name \"*.crt\" | wc -l)\n  if [[ \\$srcFileCount -ne 2 ]]; then\n    echo \"Incorrect amount of certs found in $certSource, expected 2, found \\$srcFileCount\" >&2\n    exit 1\n  fi\nEOF\n}\n\ncheck_if_new_certs_appeared_at_dest () {\n  docker exec -i \"${containerName}\" bash <<EOF\n  destFileCount=\\$(find $certDestination -type f -name \"*.crt\" | wc -l)\n  if [[ \\$destFileCount -ne 2 ]]; then\n    echo \"Incorrect amount of certs found in $certDestination, expected 2, found \\$destFileCount\" >&2\n    exit 1\n  fi\nEOF\n}\n\ncheck_if_new_certs_added_to_trusted_ca() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  for file in \"$certDestination\"/*; do\n    name=\\${file##*/}\n    nameWithoutExt=\\${name%.*}\n     if [[ ! -f \"/etc/ssl/certs/\\$nameWithoutExt.pem\" ]]; then\n         echo \"\\$nameWithoutExt expected in /etc/ssl/certs but not found\" >&2\n         exit 1\n     fi\n  done\nEOF\n}\n\ncheck_if_source_dir_empty() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ ! -z \\$(ls -A \"$certSource\") ]]; then\n     echo \"Cert files not removed from $certSource after secret was removed\" >&2\n     exit 1\n  fi\nEOF\n}\n\ncheck_if_dest_dir_empty() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ ! -z \\$(ls -A \"$certDestination\") ]]; then\n     echo \"Cert files not removed from $certDestination after secret was removed\" >&2\n     exit 1\n  fi\nEOF\n}\n\ncheck_if_no_tagged_files_in_trusted_ca() {\n  docker exec -i \"${containerName}\" bash <<EOF\n  if [[ $(ls /etc/ssl/certs | grep -cE '^[0-9]{14}') != 0 ]]; then\n     echo \"Cert files not removed from /etc/ssl/certs (Trusted CA) after secret was removed\" >&2\n     exit 1\n  fi\nEOF\n}\n\n# 1. Create kind cluster\nkind create cluster\nkubectl cluster-info --context kind-kind\npoll_container \"kubectl -n default get serviceaccount default -o name\" 60\ncontainerName=$(docker ps -q | head -n 1)\n\n# 2. Build docker image\ndocker build .. -t aks-node-ca-watcher:latest\n\n# 3. Load image to kind cluster\nkind load docker-image aks-node-ca-watcher\n\n# 4. Setup systemd unit and timer\ndocker cp . \"${containerName}\":/opt/scripts/\n\n# 5. Run daemonset with aks-node-ca-watcher and run services\nkubectl apply -f ../manifests/trustedCADS.yaml\n\n# 6. Start systemd timer/service\ndocker exec \"${containerName}\" chmod -R +x /opt/scripts\n\ndocker exec \"${containerName}\" /opt/scripts/setup_service.sh\ncertSource=/opt/certs\ncertDestination=/usr/local/share/ca-certificates/certs\n\n# 7. Check that first cert file appeared in /opt/cert on node\npoll_container check_if_first_cert_appeared_at_source 60\n\n# Get name of the first cert\nfirstCertPath=$(docker exec -i \"${containerName}\" bash <<EOF\nif [ -z \\$(ls -A \"$certSource\") ]; then\n   echo \"Cert files from secret didn't appear in /opt/certs\" >&2\n   exit 1\nelse\n  currentCerts=(\"$certSource\"/*)\n  echo \\${currentCerts[0]}\nfi\nEOF\n)\nfirstCertName=${firstCertPath##*/}\nfirstCertNameNoExt=${firstCertName%.*}\n\n#check if first cert is copied to /usr/local/share/ca-certificates/certs on node\npoll_container check_if_first_cert_copied_to_dest 60\n\n# check if first cert file is present at /etc/ssl/certs\npoll_container check_if_first_cert_added_to_trusted_ca 60\n\n# 8. Change secret with certs - remove old one, add two new ones\nkubectl apply -f ../manifests/updatedCerts.yaml\n\n# 9. Assert that old file is removed and new ones are added correctly\n# check if new file appeared in /opt/certs\npoll_container check_if_new_certs_appeared_at_source 30\n\n# check if old file is removed from /opt/certs after new ones arrive\npoll_container check_if_first_cert_removed_from_source 30\n\n# check if new files are in /usr/local/share/ca-certificates/certs\npoll_container check_if_new_certs_appeared_at_dest 30\n\n#check if first cert is removed from /usr/local/share/ca-certificates/certs after new ones arrive\ncheck_if_first_cert_removed_from_dest\n\n# check if new file is visible in /etc/ssl/certs and old file is no longer there\npoll_container check_if_new_certs_added_to_trusted_ca 60\n\ncheck_if_first_cert_removed_from_trusted_ca\n\n# 10. Remove secret and check if all files are removed from node\nkubectl apply -f ../manifests/emptySecret.yaml\n\npoll_container check_if_source_dir_empty 30\n\npoll_container check_if_dest_dir_empty 30\n\npoll_container check_if_no_tagged_files_in_trusted_ca 30\n\nexit 0", "num_lines": 210}
{"repo_name": "aks-node-ca-watcher", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\nset -x\n\ncp /opt/scripts/update-certs.timer /etc/systemd/system/update-certs.timer\ncp /opt/scripts/update-certs.service /etc/systemd/system/update-certs.service\ncp /opt/scripts/update-certs.path /etc/systemd/system/update-certs.path\n\nsystemctl enable --now update-certs.path\nsystemctl start update-certs.path\nsystemctl enable --now update-certs.timer\n\ntimerStatus=$(systemctl is-enabled update-certs.timer)\npathStatus=$(systemctl is-enabled update-certs.path)\n\nif [[ $timerStatus == \"enabled\" && $pathStatus == \"enabled\" ]]; then\n        exit 0\nelse\n        echo \"Failed to enable timer or path, cleaning up\" >&2\n        rm /etc/systemd/system/update-certs.service /etc/systemd/system/update-certs.timer /etc/systemd/system/update-certs.path\n        exit 1\nfi\n", "num_lines": 23}
{"repo_name": "aks-node-ca-watcher", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\nset -x\n\ncertSource=/opt/certs\ncertDestination=/usr/local/share/ca-certificates/certs\n\ncp -a \"$certSource\"/. \"$certDestination\"\n\nif [[ -z $(ls -A \"$certSource\") ]]; then\n  ls \"$certDestination\" | grep -E '^[0-9]{14}' | while read -r line; do\n    rm $certDestination/\"$line\"\n  done\nelse\n  certsToCopy=(${certSource}/*)\n  currIterationCertFile=${certsToCopy[0]##*/}\n  currTag=${currIterationCertFile:0:14}\n  for file in \"$certDestination\"/*.crt; do\n      currFile=${file##*/}\n     if [[ ${currFile:0:14} < ${currTag} ]]; then\n          rm \"${file}\"\n     fi\n  done\nfi\n\nupdate-ca-certificates -f", "num_lines": 26}
{"repo_name": "aks-periscope", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho\necho 1. Network Setup\nfor NODEAPD in $(kubectl -n aks-periscope get apd -o name)\ndo\n    kubectl -n aks-periscope get $NODEAPD -o jsonpath=\"{.spec.networkconfig}\" | jq .\ndone\n\necho\necho 2. Network Outbound Check\nfor NODEAPD in $(kubectl -n aks-periscope get apd -o name)\ndo\n    kubectl -n aks-periscope get $NODEAPD -o jsonpath=\"{.spec.networkoutbound}\" | jq .\n    echo\ndone", "num_lines": 16}
{"repo_name": "aks-production-patterns", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n", "num_lines": 2}
{"repo_name": "aks-production-patterns", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n", "num_lines": 2}
{"repo_name": "aks-rdma-infiniband", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\napt update && apt install -y curl\ncurl -L https://content.mellanox.com/ofed/MLNX_OFED-5.6-2.0.9.0/MLNX_OFED_LINUX-5.6-2.0.9.0-ubuntu18.04-x86_64.iso -o MLNX_OFED_LINUX-5.6-2.0.9.0-ubuntu18.04-x86_64.iso", "num_lines": 4}
{"repo_name": "aks-rdma-infiniband", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -o errexit\nset -o pipefail\nset -o nounset\n\nset -x\n\nif [[ -z \"${1}\" ]]; then\n    echo \"Must provide a non-empty action as first argument\"\n    exit 1\nfi\n\nACTION_FILE=\"/opt/actions/${1}\"\n\nif [[ ! -f \"$ACTION_FILE\" ]]; then\n    echo \"Expected to find action file '$ACTION_FILE', but did not exist\"\n    exit 1\nfi\n\necho \"Cleaning up stale actions\"\n\nrm -rf /mnt/actions/*\n\necho \"Copying fresh actions\"\n\ncp -R /opt/actions/. /mnt/actions\n\necho \"Executing nsenter\"\n\ncp -a /opt/debs/. /mnt/debs/\nnsenter -t 1 -m bash \"${ACTION_FILE}\"\nRESULT=\"${PIPESTATUS[0]}\"\n\nif [ $RESULT -eq 0 ]; then\n    # Success.\n    rm -rf /mnt/actions/*\n    echo \"Completed successfully!\"\n    sleep infinity\nelse\n    echo \"Failed during nsenter command execution\"\n    exit 1\nfi", "num_lines": 42}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /tmp\n# Get version of ALAR and fetch it\nVERSION=$(curl -s -L https://raw.githubusercontent.com/Azure/ALAR/main/Cargo.toml | grep  -i VERSION | cut -f3 -d' ' | cut -c2-6)\ncurl -s -o alar2 -L https://github.com/Azure/ALAR/releases/download/v$VERSION/alar2\nchmod 700 alar2\n\n# Start the recovery \n./alar2 $1\nexit $?", "num_lines": 11}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/bash\n# Load helper library\nIMPL_DIR=`dirname $0`\n. $IMPL_DIR/helpers.sh\n\nfunction check_space_for_mount() {\n  # Since we must be prepared to work in a rescue environment, we cannot assume the disk is mounted.\n  # Pull the log location from the auditd config\n\n  # parse the fstab file to locate where this directory is rooted\n  #DIRTEST=$LOGDIR\n  DIRTEST=$1\n  DIRTESTIN=$DIRTEST\n  echo \"Testing $DIRTEST\"\n\n  until ( grep -q -w $DIRTEST /etc/fstab ); do\n    echo \"$DIRTEST not in fstab\"\n    # since we are iterating, strip the deepest subdirectory and store it back to the test variable\n    DIRTEST=`dirname $DIRTEST`\n    # Set these vars any time we check them, so that we know we don't ever have to look again\n    if [ $DIRTEST == \"/\" ]; then NEEDROOT=0; fi\n    if [ $DIRTEST == \"/var\" ]; then NEEDVAR=0; fi\n    if [ $DIRTEST == \"/var/log\" ]; then NEEDVARLOG=0; fi\n  done\n  echo \"found mounted directory for $DIRTESTIN is $DIRTEST\"\n\n  FSTABLINE=`grep -w $DIRTEST /etc/fstab`\n\n  LOGDEV=`echo $FSTABLINE | cut -d' ' -f 1`\n  # Sanity check - most that use LVM do not do UUIDs, so that should be a good indication, but derive\n  #  the underlying volume anyway\n  if ( echo $LOGDEV | grep -q -w \"UUID\" ); then\n    echo \"UUID Present\"\n    # UUID in fstab, we need to derive the volume\n    LOGDEV=`blkid | grep $LOGDEV | cut -d: -f 1`\n    echo found $LOGDEV behind UUID\n  fi\n\n  # Verify what type of device the logfile is sitting on and act appropriately\n  DEVTYPE=`lsblk -n -o TYPE $LOGDEV`\n  if [ $DEVTYPE == \"lvm\" ]; then\n    echo \"mountpoint device confirmed as LVM\"; \n    # check if the log filesystem is mounted, so we can check for free space\n    if ! ( grep -q -w $LOGDEV /proc/mounts ); then\n      echo \"device not mounted for $DIRTEST, will mount for testing\"\n      mkdir $AUDITTEMP\n      mount $LOGDEV $AUDITTEMP\n      # change our target dir to match the new temp mount\n      LOGDIR=$AUDITTEMP\n    fi\n    \n    LOGLVUSEDPCENT=`df $DIRTEST --output=pcent | tail -n 1 | tr -d [:space:] | tr -d '%'`\n    # We are setting the threshold at 95%, since auditd should ideally take 100% util to \n    #  shut the system down.\n    if [ $LOGLVUSEDPCENT -gt 95 ]; then\n      # find VG for LV\n      LOGLV=`lvs $LOGDEV --no-headings --o lv_name | tr -d [:space:]`\n      LOGVG=`lvs $LOGDEV --no-headings --o vg_name | tr -d [:space:]`\n\n      echo \"$LOGLV is nearly full:$LOGLVUSEDPCENT%  Will try to add 10% if available in the VG\"\n      # Try to expand by a bit\n      \n      LOGLVSIZEKB=`lvs -v $LOGDEV --units k --o lv_size --no-headings | tr -d [:space:] | cut -d. -f 1`\n      LOGLVADDKB=$(($LOGLVSIZEKB/10))\n      LOGVGFREEKB=`vgs -v $LOGVG -o vg_free --no-headings --units k | tr -d [:space:] | cut -d. -f 1`\n      if [ $LOGVGFREEKB -gt $LOGLVADDKB ]; then\n        echo \"$LOGVG has more than enough space left ( $LOGVGFREEKB > $LOGLVADDKB ).  Will attempt to grow $LOGLV\"\n        lvextend /dev/$LOGVG/$LOGLV -L +$(($LOGLVADDKB))k --resizefs\n        # need to check if --resizefs actually worked\n      else\n        echo \"Not enough free space to grow $LOGLV, wanted $LOGLVADDKB, $LOGVGFREEKB available\"\n      fi\n\n    else\n      echo \"Used space in $DIRTEST under 95% - $LOGLVUSEDPCENT% utilized\"\n    fi\n\n    # Clean up the temporary test mount, if we used it\n    if findmnt $AUDITTEMP; then \n      echo \"Unmounting temporary mount on $AUDITTEMP\"\n      umount $AUDITTEMP\n    fi\n  else \n    echo \"audit log volume is not LVM, will not attempt to alter size\"; \n  fi\n}\n\n# This script will attempt two fixes to non-booting systems who are suspected to be \n#  out of space and shutting down due to auditd rules\n# 1. Disable any rules in the auditd config which shut down the system on failure to log\n# 2. Should the logical volume (LV) holding the configured log location be over 95%, try\n#    to expand it, but will attempt to grow the LV should there be room in the containing \n#    volume group.  Will not touch a RAW partition\n\nAUDACT=\"HALT\"\n# TEST condition\n# AUDACT=\"SUSPEND\"\nNEWAUDACT=\"SYSLOG\"\n\nCONFIGFILE=\"/etc/audit/auditd.conf\"\nAUDITTEMP=\"/tmp/auditlog\"\n\n\n# start editing auditd.conf file\nif ( grep -i $AUDACT -q  $CONFIGFILE ); then\n  echo \"$AUDACT directives found in $CONFIGFILE\"\n  echo \"Creating backup of $CONFIGFILE before altering\"\n  backup $CONFIGFILE\n  echo \"Changing $AUDACT in $CONFIGFILE to $NEWAUDACT\"\n  sed -i s/$AUDACT/$NEWAUDACT/ig $CONFIGFILE\nelse\n  echo \"No $AUDACT directives found in config files\"\nfi\n\n# end auditd.conf\n\n# start file system space checks\n# IF any mountpoint is full-ish AND (is LVM && free extents in the VG), we will try to expand \n#  the LV 5% of its current size from the VG's free extents.\n# -- will not attempt to work on RAW partitions\necho \"Checking for full filesystems\"\n# vars to check / and /var also, because we should process those as well as audit log location\nNEEDROOT=1\nNEEDVAR=1\nNEEDVARLOG=1\n# audit log location first\nLOGFILEPATH=`egrep '^log_file' $CONFIGFILE | tr -d '[:space:]' | cut -d '=' -f 2`\nLOGDIR=`dirname $LOGFILEPATH`\necho \"- Checking the log location from $CONFIGFILE\"\ncheck_space_for_mount $LOGDIR\n\necho \"- Checking important locations\"\nif [ $NEEDROOT -eq 1 ] ; then\n  echo \"-- Checking /\"\n  check_space_for_mount \"/\"\nelse\n  echo \"-- Already processed /\"\nfi\nif [ $NEEDVAR -eq 1 ] ; then\n  echo \"-- Checking /var\"\n  check_space_for_mount \"/var\"\nelse\n  echo \"-- Already processed /var\"\nfi\nif [ $NEEDVARLOG -eq 1 ] ; then\n  echo \"-- Checking /var/log\"\n  check_space_for_mount \"/var/log\"\nelse\n  echo \"-- Already processed /var/log\"\nfi\n# end filesystem modification\n", "num_lines": 152}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# In case the resolv.conf isn't set correct use the default resolver\nresolv-pre() {\n    mv /etc/resolv.conf /etc/resolv.conf.org\n    echo \"nameserver 168.63.129.16\" >/etc/resolv.conf\n}\n\n# restore the originail resolv.conf\nresolv-after() {\n    mv /etc/resolv.conf.org /etc/resolve.conf\n}\n\nrecover_redhat() {\n    resolv-pre\n    device=$(cut -c -$((${#boot_part_path} - 1)) <<<$boot_part_path)\n    umount $efi_part_path\n    mkfs.vfat -F16 $efi_part_path\n    mount $efi_part_path /boot/efi\n    yum reinstall -y grub2-efi shim\n    grub2-mkconfig -o /boot/efi/EFI/$(ls /boot/efi/EFI | grep -i -E \"centos|redhat\")/grub.cfg\n    uuid_to_be_replaced=$(awk '/efi/ {print($1)}' /etc/fstab)\n    read -ra EFI_DISK <<<$(blkid $efi_part_path)\n    new_uuid=$(for i in \"${EFI_DISK[@]}\"; do grep ^UUID= <<<$i; done)\n    sed -i \"s/$uuid_to_be_replaced/$new_uuid/\" /etc/fstab\n    \n    resolv-after\n}\n\nrecover_suse() {\n    resolv-pre\n    device=$(cut -c -$((${#boot_part_path} - 1)) <<<$boot_part_path)\n    umount $efi_part_path\n    mkfs.vfat -F16 $efi_part_path\n    mount $efi_part_path /boot/efi\n    zypper remove -y grub2\n    zypper install -y grub2\n    zypper install -y shim\n    cp /etc/default/grub.rpmsave /etc/default/grub\n    shim-install\n    grub2-mkconfig -o /boot/efi/EFI/$(ls /boot/efi/EFI | grep -i -E \"sles\")/grub.cfg\n    uuid_to_be_replaced=$(awk '/efi/ {print($1)}' /etc/fstab)\n    read -ra EFI_DISK <<<$(blkid $efi_part_path)\n    new_uuid=$(for i in \"${EFI_DISK[@]}\"; do grep ^UUID= <<<$i; done)\n    sed -i \"s/$uuid_to_be_replaced/$new_uuid/\" /etc/fstab\n\n    resolv-after\n}\n\nrecover_ubuntu() {\n    resolve-pre\n\n    umount $efi_part_path\n    mkfs.vfat -F16 $efi_part_path\n    mount $efi_part_path /boot/efi\n    apt-get install -y --reinstall grub-efi\n    grub-install --efi-directory=/boot/efi --target=x86_64-efi $device\n    update-grub\n    uuid_to_be_replaced=$(awk '/efi/ {print($1)}' /etc/fstab)\n    read -ra EFI_DISK <<<$(blkid $efi_part_path)\n    new_uuid=$(for i in \"${EFI_DISK[@]}\"; do grep ^UUID= <<<$i; done)\n    sed -i \"s/$uuid_to_be_replaced/$new_uuid/\" /etc/fstab\n\n    resolv-after\n}\n\nif [[ \"$isRedHat\" == \"true\" ]]; then\n    recover_redhat\nfi\n\nif [[ \"$isSuse\" == \"true\" ]]; then\n    recover_suse\nfi\n\nif [[ \"$isUbuntu\" == \"true\" ]]; then\n    recover_ubuntu\nfi\n\nexit 0\n", "num_lines": 79}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmv -f /etc/fstab{,.copy}\n\n# For Debian we need to instal gawk first. It comes only with mawk\nif [[ -f /usr/bin/apt ]]; then\n    apt-get install -qq -y gawk\nfi\n\nawk '/[[:space:]]+\\/[[:space:]]+/ {print}' /etc/fstab.copy >>/etc/fstab\nawk '/[[:space:]]+\\/boot[[:space:]]+/ {print}' /etc/fstab.copy >>/etc/fstab\n# For Suse\nawk '/[[:space:]]+\\/boot\\/efi[[:space:]]+/ {print}' /etc/fstab.copy >>/etc/fstab\n# In case we have a LVM system\nawk '/rootvg-homelv/ {print}' /etc/fstab.copy >>/etc/fstab\nawk '/rootvg-optlv/ {print}' /etc/fstab.copy >>/etc/fstab\nawk '/rootvg-tmplv/ {print}' /etc/fstab.copy >>/etc/fstab\nawk '/rootvg-usrlv/ {print}' /etc/fstab.copy >>/etc/fstab\nawk '/rootvg-varlv/ {print}' /etc/fstab.copy >>/etc/fstab\n\necho \"Content of fstab after running the script -->\"\ncat /etc/fstab\n\nexit 0", "num_lines": 24}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# In case the resolv.conf isn't set correct use the default resolver\nresolv-pre() {\n    mv /etc/resolv.conf /etc/resolv.conf.org\n    echo \"nameserver 168.63.129.16\" >/etc/resolv.conf\n}\n\n# restore the originail resolv.conf\nresolv-after() {\n    mv /etc/resolv.conf.org /etc/resolve.conf\n}\n\nrecover_redhat() {\n    resolv-pre\n    yum install gdisk -y\n    device=$(cut -c -$((${#boot_part_path} - 1)) <<<$boot_part_path)\n    if [[ \"$isRedHat6\" == \"true\" ]]; then\n        grub-install $device\n        # update-grub is not available on version 6.x so the functionality is limitted\n    else\n        sgdisk -e $device\n        grub2-install --target i386-pc $device\n        # Generate both config files.\n        grub2-mkconfig -o /boot/efi/EFI/$(ls /boot/efi/EFI | grep -i -E \"centos|redhat\")/grub.cfg\n        grub2-mkconfig -o /boot/grub2/grub.cfg\n\n   fi\n    resolv-after\n}\n\nrecover_suse() {\n    resolv-pre\n    zypper install -y gptfdisk\n    device=$(cut -c -$((${#boot_part_path} - 1)) <<<$boot_part_path)\n    sgdisk -e $device\n    grub2-install $device\n    grub2-mkconfig -o /boot/grub2/grub.cfg\n\n    resolv-after\n}\n\nrecover_ubuntu() {\n    resolve-pre\n\n    apt install gdisk -y\n    apt-get install -y --reinstall grub2-common grub-pc\n    device=$(cut -c -$((${#boot_part_path} - 1)) <<<$boot_part_path)\n    sgdisk -e $device\n    grub-install $device\n    update-grub\n\n    resolv-after\n}\n\nif [[ \"$isRedHat\" == \"true\" ]]; then\n    recover_redhat\nfi\n\nif [[ \"$isSuse\" == \"true\" ]]; then\n    recover_suse\nfi\n\nif [[ \"$isUbuntu\" == \"true\" ]]; then\n    recover_ubuntu\nfi\n\nexit 0\n", "num_lines": 68}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/bash\nTIMESTAMP=`date +%Y%m%dT%H%M%S`\n\nfunction backup() {\n  ORIGFILE=$1\n  BACKUP=$1.alar.$TIMESTAMP\n  cp -v -p $ORIGFILE $BACKUP\n}\n", "num_lines": 9}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# recover logic for handling and initrd or kernel problem\n#\n\nrecover_suse() {\n    kernel_version=$(sed -e \"s/kernel-azure-//\" <<< $(rpm -q kernel-azure --last  | head -n 1 | cut -f1 -d'|' | cut -f 1-4 -d '.'))-azure\n    # Get sure that all required modles are loaded\n    echo 'add_drivers+=\" hv_vmbus\u00e2\u20ac\u00afhv_netvsc\u00e2\u20ac\u00afhv_storvsc\"' >> /etc/dracut.conf\n    mkinitrd /boot/initrd-\"${kernel_version}\" \"$kernel_version\"\n    grub2-mkconfig -o /boot/grub2/grub.cfg\n}\n\nrecover_ubuntu() {\n    if [[ ! -e /var/log/dpkg.log ]]; then\n    # if this file is empty we have to assume that we have a vanilla system. Only one kernel available\n        kernel_version=$(ls /boot/vmlinuz-*)\n        kernel_version=${kernel_version#/boot/vmlinuz-}\n    else\n        kernel_version=$( zgrep linux-image /var/log/dpkg.log* | grep installed  | cut -d' ' -f5 | cut -d':' -f1 | sed -e 's/linux-image-//' | grep ^[1-9] | sort -V | tail -n 1)\n    fi\n    # This is needed on Debian only\n    if [[ -e /boot/initrd.img-${kernel_version} ]]; then\n            rm /boot/initrd.img-${kernel_version}\n    fi\n    # Get sure that all required modles are loaded\n        echo \"hv_vmbus\" >> /etc/initramfs-tools/modules\n        echo \"hv_storvsc\" >> /etc/initramfs-tools/modules\n        echo \"hv_netvsc\" >> /etc/initramfs-tools/modules\n\n    update-initramfs -k \"$kernel_version\" -c\n    update-grub\n\n}\n\n#\n# Should handle all redhat based distros\n#\nrecover_redhat() {\n    kernel_version=$(sed -e \"s/kernel-//\" <<< $(rpm -q kernel --last  | head -n 1 | cut -f1 -d' '))\n    # Get sure that all required modles are loaded\n    echo 'add_drivers+=\" hv_vmbus\u00e2\u20ac\u00afhv_netvsc\u00e2\u20ac\u00afhv_storvsc\"' >> /etc/dracut.conf\n    if [[ \"$isRedHat6\" == \"true\" ]]; then\n        # verify the grub.conf and correct it if needed\n        cd \"$tmp_dir\"\n        awk -f alar-fki/grub.awk /boot/grub/grub.conf\n        # rebuild the initrd\n        dracut -f /boot/initramfs-\"${kernel_version}\".img \"$kernel_version\"\n    else\n        if [[ $(grep -qe 'VERSION_ID=\\\"8.\\?[0-2]\\?\\\"' /etc/os-release) -eq 0 ]]; then\n            for installed_kernel in $(rpm -qa kernel); do\n                     kernel-install add $(sed 's/kernel-//' <<< $installed_kernel) /boot/vmlinuz-$(sed 's/kernel-//' <<< $installed_kernel)\n            done\n        else\n            depmod ${kernel_version}\n            mkinitrd --force /boot/initramfs-\"${kernel_version}\".img \"$kernel_version\"\n            grub2-mkconfig -o /boot/grub2/grub.cfg\n        fi\n    fi\n\n}\n\nif [[ \"$isRedHat\" == \"true\" ]]; then\n    recover_redhat\nfi\n\nif [[ \"$isSuse\" == \"true\" ]]; then\n    recover_suse\nfi\n\nif [[ \"$isUbuntu\" == \"true\" ]]; then\n    recover_ubuntu\nfi\n\nexit 0\n", "num_lines": 75}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# The main intention is to roll back to the previous working kernel\n# We do this by altering the grub configuration\n\n# From the man page\n# Set the default boot menu entry for GRUB.  This requires setting GRUB_DEFAULT=saved in /etc/default/grub\nset_grub_default() {\n        # verify whether GRUB_DEFAULT is available\n        grep -q 'GRUB_DEFAULT=.*' /etc/default/grub || echo 'GRUB_DEFAULT=saved' >>/etc/default/grub\n        # The next line could be garded and/or improved with the help of an if for instance\n        # though I keep it simple\n        sed -i \"s/GRUB_DEFAULT=[[:digit:]]/GRUB_DEFAULT=saved/\" /etc/default/grub\n}\n\n# set the default kernel accordingly\n# This is different for RedHat and Ubuntu/SUSE distros\n# Ubuntu and SLES use sub-menues\n# Variables are set by action.rs\n\nif [[ $isRedHat == \"true\" ]]; then\n        if [[ $isRedHat6 == \"true\" ]]; then\n                grubby --set-default=1 # This is the previous kernel\n                ldconfig\n        else\n                set_grub_default\n                # set to previous kernel\n                sed -i -e 's/GRUB_DEFAULT=.*/GRUB_DEFAULT=1/' /etc/default/grub\n\n                # Generate both config files. \n                grub2-mkconfig -o /boot/efi/EFI/$(ls /boot/efi/EFI | grep -i -E \"centos|redhat\")/grub.cfg\n                grub2-mkconfig -o /boot/grub2/grub.cfg\n\n                # enable sysreq\n                echo \"kernel.sysrq = 1\" >>/etc/sysctl.conf\n        fi\nfi\n\nif [[ $isUbuntu == \"true\" ]]; then\n        set_grub_default\n        sed -i -e 's/GRUB_DEFAULT=.*/GRUB_DEFAULT=\"1>2\"/' /etc/default/grub\n        update-grub\nfi\n\nif [[ $isSuse == \"true\" ]]; then\n        set_grub_default\n        sed -i -e 's/GRUB_DEFAULT=.*/GRUB_DEFAULT=\"1>2\"/' /etc/default/grub\n        grub2-mkconfig -o /boot/grub2/grub.cfg\nfi\n\n# For reference --> https://www.linuxsecrets.com/2815-grub2-submenu-change-boot-order\n\nexit 0\n", "num_lines": 53}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# A helper functions to prevent an accidently exit of the chroot environment\n# This script is used in together with the chroot-cli action\nfunction exit-chroot() {\n    unset exit\n    exit\n}\nexport -f exit-chroot\n\nfunction exit() {\n    echo \"If you want to exit please use 'exit-chroot' instead\"\n}\nexport -f exit\n", "num_lines": 14}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# serialconsole-impl is responsible to set the configuration for the serialconsole\n# correct in case this is missing in a VM image.\n# It also enables sysreq to allow a reboot from the Portal\n#\n\nenable_sysreq() {\n    if [[ $isRedHat == \"true\"  ]]; then\n        echo \"kernel.sysrq = 1\" >> /etc/sysctl.d/90-alar2.conf\n    else\n        echo \"kernel.sysrq = 1\" >> /etc/sysctl.conf\n    fi\n}\n\nalter_serial_properties() {\n    # The aim of this funtion is to provide access to the grub_serial console\n    # as well allow the OS to communicate with the serialconsole\n    # Just simple append operations are used in this case. Which is enough to gt access to a system\n    # if further adjusting is required the administrator needs to perform these steps later on after he/she got access to the system\n    \n    echo \"# Inserted by Azure Linux Autorecovery Tool\" >> $grub_file\n    echo \"# -----------------------------------------\" >> $grub_file\n    echo \"GRUB_TIMEOUT=10\" >> $grub_file\n    echo 'GRUB_CMDLINE_LINUX=\"USE_BY_UUID_DEVICE_NAMES=1 rootdelay=300 multipath=off net.ifnames=0 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 console=tty1 earlyprintk=ttyS1\"' >> $grub_file\n    echo 'GRUB_SERIAL_COMMAND=\"serial --speed=9600 --unit=0 --word=8 --parity=no --stop=1\"' >> $grub_file\n    echo 'GRUB_TIMEOUT_STYLE=\"\"' >> $grub_file\n}\n\nserial_fix_suse_redhat () {\n    if [[ \"$isRedHat6\" == \"true\" ]]; then\n        echo \"Configuring the serialconsole for RedHat 6.x is not implemented\"\n        exit 1\n    fi\n    \n    grub_file=\"/etc/default/grub\"\n    enable_sysreq\n    \n    if [[ -f $grub_file ]]; then\n        alter_serial_properties\n    else\n        # file does not exist\n        touch $grub_file\n    cat << EOF > $grub_file\nGRUB_TIMEOUT=30\nGRUB_DISTRIBUTOR=\"$(sed 's, release .*$,,g' /etc/system-release)\"\nGRUB_DEFAULT=saved\nGRUB_DISABLE_SUBMENU=true\nGRUB_TERMINAL=\"serial\"\nGRUB_CMDLINE_LINUX=\"USE_BY_UUID_DEVICE_NAMES=1 rootdelay=300 multipath=off net.ifnames=0 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 console=tty1 earlyprintk=ttyS1\"\nGRUB_DISABLE_RECOVERY=\"true\"\nGRUB_SERIAL_COMMAND=\"serial --speed=9600 --unit=0 --word=8 --parity=no --stop=1\"\nEOF\n    fi\n    \n    # update grub\n    if [[ $isRedHat == \"true\" ]]; then\n        distro=$(grep '^ID=' /etc/os-release | cut -d '\"' -f2)\n        if [[ ${distro} == \"rhel\" ]]; then\n            distro=\"redhat\" ;\n        fi\n        grub2-mkconfig -o /boot/efi/EFI/${distro}/grub.cfg\n    fi\n    \n    grub2-mkconfig -o /boot/grub2/grub.cfg\n}\n\n# REDHAT/CENTOS PART\nif [[ \"$isRedHat\" == \"true\" ]]; then\n    serial_fix_suse_redhat\nfi\n\n# SUSE PART\nif [[ \"$isSuse\" == \"true\" ]]; then\n    serial_fix_suse_redhat\n    \nfi\n\n# UBUNTU PART\nif [[ \"$isUbuntu\" == \"true\" ]]; then\n    grub_file=\"/etc/default/grub.d/50-cloudimg-settings.cfg\"\n    enable_sysreq\n    \n    if [[ -f $grub_file ]]; then\n        alter_serial_properties\n        update-grub\n    else\n        # file does not exist\n        touch $grub_file\n    cat << EOF > $grub_file\n# Set the default commandline\nGRUB_CMDLINE_LINUX=\"USE_BY_UUID_DEVICE_NAMES=1 rootdelay=300 multipath=off net.ifnames=0 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 console=tty1 earlyprintk=ttyS1\"\nGRUB_CMDLINE_LINUX_DEFAULT=\"\"\n\n# Set the grub console type\nGRUB_TERMINAL=serial\n\n# Set the serial command\nGRUB_SERIAL_COMMAND=\"serial --speed=9600 --unit=0 --word=8 --parity=no --stop=1\"\n\n# Set the recordfail timeout\nGRUB_RECORDFAIL_TIMEOUT=30\n\n# Wait briefly on grub prompt\nGRUB_TIMEOUT=10\nEOF\n        # update grub\n        update-grub\n    fi\nfi", "num_lines": 111}
{"repo_name": "ALAR", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This is just a simple demo in order to print out the environment seen by the script\n# The calling process is preparing the environment accordingly\nprintenv\npwd", "num_lines": 6}
{"repo_name": "ALZ-Bicep", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nazureResourceGroup='rsg-private-bicep-registry'\nazureLocation='eastus'\n\n#Create resource group\naz group create --name $azureResourceGroup --location $azureLocation\n\n#Deploy Container Registry into Resource Group\naz deployment group create --template-file infra-as-code/bicep/CRML/containerRegistry/containerRegistry.bicep  --resource-group $azureResourceGroup --name deployACR\n\n#Query the Deployment to get the login server to pass.\n#https://docs.microsoft.com/en-us/cli/azure/query-azure-cli#get-a-single-value\nazureContainerRegistryName=$(az deployment group show -n deployACR -g $azureResourceGroup --query properties.outputs.outLoginServer.value -o tsv)\n\n#Leverage Bash utilities too loop through all bicep modules within the repository\n#convert the filename to lower case as Azure Container Registry doesnt support Camelcase\n#Leverage az bicep to publish module to Azure Container Registry created above\nfor file in $(find ./infra-as-code/bicep/modules -type f -name \"*.bicep\" ! -path \"./infra-as-code/bicep/modules/unstable*\")\ndo\n  f=$(echo \"${file##*/}\");\n  filename=$(echo $f| cut  -d'.' -f 1| tr '[:upper:]' '[:lower:]')\n  echo \"Publishing $filename.bicep to ACR: $azureContainerRegistryName\"\n  az bicep publish --file $file --target \"br:$azureContainerRegistryName/bicep/modules/$filename:V1\"\ndone       \n", "num_lines": 26}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "ADR=${1:-127.0.0.1:9090/score}\nAUTH=${2:+\"Authorization: Bearer $2\"}\nIN_FILE=${3:-../SampleImages/dog.jpg}\n\n( set -x; curl $ADR -H \"$AUTH\" --data-binary @$IN_FILE )\necho \"\"\necho \"\"\n\n( set -x; curl $ADR?count=1 -H \"$AUTH\" --data-binary @$IN_FILE )\necho \"\"", "num_lines": 10}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\n./download_model.sh\n\necho ''\necho \"Creating Azure ML service (it takes a while)\"\necho ''\nset -x\naz ml service create realtime --model-file model -f score.py -d app.py -d ui.html -n inceptionv3 -r python -p requirements.txt\n", "num_lines": 10}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ ! -f model/classify_image_graph_def.pb ]; then\n    echo \"\"\n    echo Downloading Model\n    echo \"\"\n\n    wget -nc -P model/ http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz\n    tar xvzf model/inception-2015-12-05.tgz -C model/\n    rm model/cropped_panda.jpg\n    rm model/inception-2015-12-05.tgz\n    \n    echo \"\"\n    cat legal.notice\n    echo \"\"\n    read -n1 -s -r -p \"Press any key to continue . . .\"\n    echo \"\"\nfi\n", "num_lines": 17}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "gunicorn3 -c gunicorn_conf.py \"wsgi:app\" | jq -R -r '. as $line | try (fromjson | .message, .exc_info) catch $line'\n", "num_lines": 2}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "SOURCE=${1:-../../local_debugging/*}\n\ncp -n -r $SOURCE ./\n\nsudo apt-get install python3.6 python3-pip gunicorn3 jq\n\npip3 install json-logging-py flask applicationinsights azure-ml-api-sdk tensorflow\n\n./download_model.sh\n\n", "num_lines": 11}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ ! -f model/libdarknet.so ]; then\n    echo ''\n    echo Building Model\n    echo ''\n\n    sed -i '/^OPENMP=0$/c OPENMP=1' ./darknet/Makefile\n    pushd ./darknet ; make ; popd\n\n    # Copy model related files over to the model directory\n    mkdir -p data/labels\n    cp -a ./darknet/data/labels/. ./data/labels/\n    cp ./darknet/data/coco.names ./data/\n    cp ./darknet/data/coco9k.map ./data/\n    cp ./darknet/libdarknet.so ./model/\n    cp ./darknet/cfg/coco.data ./model/\n    cp ./darknet/cfg/yolov3.cfg ./model/\n    cp ./darknet/LICENSE* ./model/\nfi\n", "num_lines": 19}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "URL=${1:-127.0.0.1:9090/score}\nAUTH=${2:+\"Authorization: Bearer $2\"}\nIN_FILE=${3:-../SampleImages/dog.jpg}\nOUT_FILE=${4:-out.jpg}\n\n( set -x; curl $URL -H \"$AUTH\" --data-binary @$IN_FILE )\necho \"\"\necho \"\"\n\nrm -f $OUT_FILE\n\n(\n  set -x\n  curl $URL?output=image -s -H \"$AUTH\" --data-binary @$IN_FILE --output $OUT_FILE\n  xdg-open $OUT_FILE\n)\n", "num_lines": 17}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\n./download_model.sh\n./build_model.sh\n\necho ''\necho \"Creating Azure ML service (it takes a while)\"\necho ''\nset -x\naz ml service create realtime --model-file model --model-file data -f score.py -d app.py -d ui.html -n yolov3 -r python\n", "num_lines": 11}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ ! -f model/yolov3.weights ]; then\n    echo ''\n    echo Downloading Yolov3\n    echo ''\n\n    # Clone Darknet repo\n    git clone https://github.com/pjreddie/darknet\n    \n    # Download model weights\n    wget -nc -P model/ https://pjreddie.com/media/files/yolov3.weights\n    \n    echo \"\"\n    cat legal.notice\n    echo \"\"\n    read -n1 -s -r -p \"Press any key to continue . . .\"\n    echo \"\"\nfi\n", "num_lines": 18}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "gunicorn3 -c gunicorn_conf.py \"wsgi:app\" | jq -R -r '. as $line | try (fromjson | .message, .exc_info) catch $line'\n", "num_lines": 2}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "SOURCE=${1:-../../local_debugging/*}\n\ncp -n -r $SOURCE ./\n\nsudo apt-get install python3.6 python3-pip gunicorn3 jq\n\npip3 install json-logging-py flask applicationinsights azure-ml-api-sdk\n\n./download_model.sh\n./build_model.sh\n\n", "num_lines": 12}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nif [ ! -f model/mleap-airbnb-assembly-0.0.1.jar ]; then\n    echo ''\n    echo Building Model\n    echo ''\n\n    pushd ./scoringmodel\n    sbt clean\n    sbt assembly\n    popd\n\n    mkdir -p model\n    cp ./scoringmodel/mleap-airbnb-assembly-0.0.1.jar ./model/\nfi\n", "num_lines": 16}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "ADR=${1:-127.0.0.1:9090/score}\nAUTH=${2:+\"Authorization: Bearer $2\"}\nIN_FILE=${3:-./sample_input.json}\n\n( set -x; curl $ADR -H \"$AUTH\" -H \"Content-Type: application/json\" -d @$IN_FILE )\necho \"\"", "num_lines": 6}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\n./download_model.sh\n./build_scoring_model.sh\n\necho ''\necho \"Creating Azure ML service (it takes a while)\"\necho ''\nset -x\naz ml service create realtime --model-file model -f score.py -d app.py -d ui.html -n mleapairbnb -r spark-py\n", "num_lines": 11}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nif [ ! -f model/airbnb.model.lr.zip ] || [ ! -f model/airbnb.model.rf.zip ]; then\n    echo \"\"\n    echo Downloading Model\n    echo \"\"\n\n    wget -nc -P model/ https://github.com/combust/mleap/raw/master/LICENSE\n    wget -nc -P model/ https://github.com/combust/mleap/raw/master/mleap-benchmark/src/main/resources/models/airbnb.model.lr.zip\n    wget -nc -P model/ https://github.com/combust/mleap/raw/master/mleap-benchmark/src/main/resources/models/airbnb.model.rf.zip\n\n    echo \"\"\n    cat legal.notice\n    echo \"\"\n    read -n1 -s -r -p \"Press any key to continue . . .\"\n    echo \"\"\nfi\n", "num_lines": 18}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "gunicorn3 -c gunicorn_conf.py \"wsgi:app\" | jq -R -r '. as $line | try (fromjson | .message, .exc_info) catch $line'\n", "num_lines": 2}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nSOURCE=${1:-../../local_debugging/*}\n\ncp -n -r $SOURCE ./\n\nsudo apt-get install python3.6 python3-pip gunicorn3 jq\n\npip3 install json-logging-py flask applicationinsights azure-ml-api-sdk pyspark\n\nif ! grep -q \"mleap-airbnb-assembly-0.0.1.jar\" \"./main.py\"; then\n    echo \"$(cat append_to_main.txt main.py)\" > main.py\nfi\n\n./download_model.sh\n./build_scoring_model.sh\n\n\n\n", "num_lines": 20}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "ADR=${1:-127.0.0.1:9090/score}\nAUTH=${2:+\"Authorization: Bearer $2\"}\nIN_FILE=${3:-./sample_input.txt}\n\n( set -x; curl $ADR -H \"$AUTH\" --data @$IN_FILE )\necho \"\"", "num_lines": 6}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\n./download_model.sh\n\necho ''\necho \"Creating Azure ML service (it takes a while)\"\necho ''\nset -x\naz ml service create realtime --model-file model --model-file torchmoji --model-file data -f score.py -d app.py -d ui.html -c conda_dependencies.yml -n deepmoji -r python\n", "num_lines": 10}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nif [ ! -d ./torchmoji ]; then\n    echo \"\"\n    echo Downloading Model\n    echo \"\"\n\n    # Clone torchMoji repo\n    git clone https://github.com/huggingface/torchMoji.git ./torchmoji_repo\n\n    # Copy model related files over to the model directory\n    mkdir -p torchmoji\n    cp ./torchmoji_repo/torchmoji/attlayer.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/create_vocab.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/filter_utils.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/global_variables.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/lstm.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/model_def.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/sentence_tokenizer.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/tokenizer.py ./torchmoji/\n    cp ./torchmoji_repo/torchmoji/word_generator.py ./torchmoji/\n    cp ./torchmoji_repo/LICENSE ./torchmoji/\n\n    mkdir -p data\n    cp ./torchmoji_repo/data/emoji_codes.json ./data/\n    cp ./torchmoji_repo/data/filtering/wanted_emojis.csv ./data/\n\n    mkdir -p model\n    cp ./torchmoji_repo/model/vocabulary.json ./model/\n\n    echo \"\"\n    cat legal.notice\n    echo \"\"\n    read -n1 -s -r -p \"Press any key to continue . . .\"\n    echo \"\"\nfi\n\nif [ ! -f model/pytorch_model.bin ]; then\n    # Download model weights\n    wget -nc https://www.dropbox.com/s/q8lax9ary32c7t9/pytorch_model.bin?dl=0# -O model/pytorch_model.bin\nfi\n", "num_lines": 42}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nsource activate deepmojienv\n\ngunicorn -c gunicorn_conf.py \"wsgi:app\" | jq -R -r '. as $line | try (fromjson | .message, .exc_info) catch $line'\n", "num_lines": 6}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nSOURCE=${1:-../../local_debugging/*}\n\ncp -n -r $SOURCE ./\n\nsudo apt-get install jq\n./download_model.sh\n\n# Setup Conda enviornment\nif ! conda env list | grep -q deepmojienv; then\n    conda env create -f conda_dependencies.yml\nfi\n\n# Activate Conda enviornment\nsource activate deepmojienv\npip install -I gunicorn json-logging-py flask applicationinsights azure-ml-api-sdk\nsource deactivate\n", "num_lines": 19}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "ADR=${1:-127.0.0.1:9090/score}\nAUTH=${2:+\"Authorization: Bearer $2\"}\nIN_FILE=${3:-./sample_input.csv}\n\n( set -x; curl $ADR -H \"$AUTH\" --data-binary @$IN_FILE )\necho \"\"", "num_lines": 6}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nif [ ! -f legal.notice.shown  ]; then\n    echo \"\"\n    cat legal.notice\n    echo \"\"\n    read -n1 -s -r -p \"Press any key to continue . . .\"\n    echo \"\"\n    touch legal.notice.shown\nfi\n\necho ''\necho \"Creating Azure ML service (it takes a while)\"\necho ''\nset -x\naz ml service create realtime --model-file model -f score.py -d app.py -d ui.html -n solar -r python -p requirements.txt\n", "num_lines": 17}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "gunicorn3 -c gunicorn_conf.py \"wsgi:app\" | jq -R -r '. as $line | try (fromjson | .message, .exc_info) catch $line'\n", "num_lines": 2}
{"repo_name": "AML-AirField", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nSOURCE=${1:-../../local_debugging/*}\n\ncp -n -r $SOURCE ./\n\nsudo apt-get install python3.6 python3-pip gunicorn3 jq\n\npip3 install json-logging-py flask applicationinsights azure-ml-api-sdk cntk\n", "num_lines": 10}
{"repo_name": "aml-compute", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\npython /code/main.py\n", "num_lines": 6}
{"repo_name": "aml-deploy", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\npython /code/main.py\n", "num_lines": 6}
{"repo_name": "AML-Kubernetes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script should be executed on Linux Ubuntu Virtual Machine\n\nDATA_DIRECTORY=${1:-/data}\nAKS_SUBNET=${2:-*}\n\nEXPORT_DIRECTORY=\"/export/$(basename \"$DATA_DIRECTORY\")\"\n\necho \"Updating packages\"\napt-get -y update\n\necho \"Installing NFS kernel server\"\n\napt-get -y install nfs-kernel-server\n\necho \"Making data directory ${DATA_DIRECTORY}\"\nmkdir -p ${DATA_DIRECTORY}\n\necho \"Making new directory to be exported and linked to data directory: ${EXPORT_DIRECTORY}\"\nmkdir -p ${EXPORT_DIRECTORY}\n\necho \"Mount binding ${DATA_DIRECTORY} to ${EXPORT_DIRECTORY}\"\nmount --bind ${DATA_DIRECTORY} ${EXPORT_DIRECTORY}\n\necho \"Giving 777 permissions to ${EXPORT_DIRECTORY} directory\"\nchmod 777 ${EXPORT_DIRECTORY}\n\nparentdir=\"$(dirname \"$EXPORT_DIRECTORY\")\"\necho \"Giving 777 permissions to parent: ${parentdir} directory\"\nchmod 777 $parentdir\n\necho \"Appending bound directories into fstab\"\necho \"${DATA_DIRECTORY}    ${EXPORT_DIRECTORY}   none    bind  0  0\" >> /etc/fstab\n\necho \"Appending localhost and Kubernetes subnet address ${AKS_SUBNET} to exports configuration file\"\necho \"/export        ${AKS_SUBNET}(rw,async,insecure,fsid=0,crossmnt,no_subtree_check)\" >> /etc/exports\necho \"/export        localhost(rw,async,insecure,fsid=0,crossmnt,no_subtree_check)\" >> /etc/exports\n\nnohup service nfs-kernel-server restart", "num_lines": 40}
{"repo_name": "AML-Kubernetes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsubscription_id=\"<YOUR_SUBSCRIPTION_ID>\"\nresource_group=\"<YOUR_RESOURCE_GROUP>\"\ncluster_name=\"<YOUR_AKS_CLUSTER_NAME>\"\n\narcml_extension_name=\"arcml-extension\"\n\nssl_cname=\"<YOUR_SSL_CNAME>\"\nssl_cert_pem_file=\"<YOUR_CERT_PEM_FILE>\"\nssl_key_pem_file=\"<YOUR_KEY_PEM_FILE>\"\n\n# STEP1 Register feature providers\necho 'Register features...'\naz feature register --namespace Microsoft.ContainerService -n AKS-ExtensionManager --subscription \"$subscription_id\"\necho 'Waiting for feature register...'\nwhile [ \"$(az feature list --query \"[?contains(name, 'Microsoft.ContainerService/AKS-ExtensionManager')].[properties.state]\" -o json |jq '.[0][0]')\" == 'Registered' ]\ndo\n  sleep 5\ndone\naz provider register -n Microsoft.ContainerService 1\n\n\n# STEP2 Deploy AmlArc extension\n# OPTION A) AKS service has public https endpoint\naz k8s-extension create --cluster-name $cluster_name --cluster-type managedClusters -n $arcml_extension_name \\\n--extension-type Microsoft.AzureML.Kubernetes --scope cluster --configuration-settings enableInference=True \\\nsslCname=$ssl_cname --config-protected sslCertPemFile=$ssl_cert_pem_file sslKeyPemFile=$ssl_key_pem_file \\\n--subscription $subscription_id -g $resource_group --auto-upgrade-minor-version False\n\n# OPTION B) AKS service has public http endpoint\n#az k8s-extension create --cluster-name $cluster_name --cluster-type managedClusters -n $arcml_extension_name \\\n#--extension-type Microsoft.AzureML.Kubernetes --scope cluster --configuration-settings enableInference=True allowInsecureConnections=true \\\n#--subscription $subscription_id -g $resource_group --auto-upgrade-minor-version False\n\n# OPTION C) AKS service has private http endpoint\n#az k8s-extension create --cluster-name $cluster_name --cluster-type managedClusters -n $arcml_extension_name \\\n#--extension-type Microsoft.AzureML.Kubernetes --scope cluster --configuration-settings enableInference=True allowInsecureConnections=true \\\n#privateEndpointILB=True --subscription $subscription_id -g $resource_group --auto-upgrade-minor-version False\n\n\nextension_install_state=$(az k8s-extension show --name $arcml_extension_name  --cluster-type managedClusters --cluster-name \"$cluster_name\"   --resource-group \"$resource_group\" --subscription \"$subscription_id\" | jq -r '.provisioningState')\necho \"$extension_install_state\"\nif [[ $extension_install_state == \"Succeeded\" ]]\nthen\n  echo \"AzureML extention created successfully\"\nelse\n  echo \"AzureML extention creation failed\"\n  exit 1\nfi\n", "num_lines": 53}
{"repo_name": "AML-Kubernetes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nAZ_K8S_EXTENSION_VERSION='1.2.2'\nAZ_CONNECTED_K8S_VERSION='1.2.8'\n\naz extension add --name connectedk8s --version $AZ_CONNECTED_K8S_VERSION\naz extension add --name k8s-extension --version $AZ_K8S_EXTENSION_VERSION\n\npython deploy.py", "num_lines": 9}
{"repo_name": "aml-real-time-ai", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nconda env create -f environment.yml\nsource /etc/conda/bin/activate amlrealtimeai\nconda install -y pytest\nexport TEST_SERVICE_PRINCIPAL_KEY=$1\npytest pythonlib/tests/integration_tests\nERR=$?\nsource /etc/conda/bin/activate base\nconda env remove -y -n amlrealtimeai\nexit $ERR\n", "num_lines": 12}
{"repo_name": "aml-real-time-ai", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndotnet test sample-clients/csharp/client.tests\nERR=$?\nif [ $ERR -ne 0 ]\nthen\n    exit $ERR\nfi\nsource /usr/share/miniconda/etc/profile.d/conda.sh\n\nconda env create -f environment.yml\nconda activate amlrealtimeai\nconda install -y pytest pytest-cov\npython -m pytest --cov=pythonlib/amlrealtimeai pythonlib/tests/unit_tests\nERR=$?\nconda activate base\nconda env remove -y -n amlrealtimeai\nif [ $ERR -ne 0 ]\nthen\n    exit $ERR\nfi\n", "num_lines": 22}
{"repo_name": "aml-registermodel", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\npython /code/main.py\n", "num_lines": 6}
{"repo_name": "aml-run", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\npython /code/main.py\n", "num_lines": 6}
{"repo_name": "aml-workspace", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\npython /code/main.py\n", "num_lines": 6}
{"repo_name": "Ansible", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho $@\nfunction print_usage() {\n  cat <<EOF\nInstalls Ansible with specific version\nCommand\n  $0\nArguments\n  --version|-v                        : Ansible version\n  --service_principal_type|-sp        : The type of service principal: MSI or manual.\n  --service_principal_id|-sid         : The service principal ID.\n  --service_principal_secret|-ss      : The service principal secret.\n  --subscription_id|-subid            : The subscription ID of the SP.\n  --tenant_id|-tid                    : The tenant id of the SP.\n  --help|-h                           : Help of the script.\nEOF\n}\n\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --version|-v)\n      ansible_version=\"$1\"\n      shift\n      ;;\n    --service_principal_type|-sp)\n      service_principal_type=\"$1\"\n      shift\n      ;;\n    --service_principal_id|-spid)\n      service_principal_id=\"$1\"\n      shift\n      ;;\n    --service_principal_secret|-ss)\n      service_principal_secret=\"$1\"\n      shift\n      ;;\n    --subscription_id|-subid)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-tid)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nfunction run_command {\n    \"${@}\"\n\n    if [ $? -ne 0 ]; then\n        echo Failed to run \"${@}\"\n        exit 1\n\n    fi\n}\n\nfunction get_ansible_install_option {\n    if [ \"${ansible_version}\" == \"latest\" ]; then\n      version_option=\"\"\n    else\n      version_option=\"==${ansible_version}\"\n    fi\n}\n\nsp_cred=$(cat <<EOF\n[default]\nsubscription_id=${subscription_id}\nclient_id=${service_principal_id}\nsecret=${service_principal_secret}\ntenant=${tenant_id}\nEOF\n)\n\nfunction set_azure_credentials {\n    # write Azure credentials file\n    if [ \"${service_principal_type}\" == \"manual\" ]; then\n        echo export AZURE_SUBSCRIPTION_ID=${subscription_id} >> /etc/profile\n        echo export AZURE_CLIENT_ID=${service_principal_id} >> /etc/profile\n        echo export AZURE_SECRET=${service_principal_secret} >> /etc/profile\n        echo export AZURE_TENANT=${tenant_id} >> /etc/profile\n\n        echo export AZURE_SUBSCRIPTION_ID=${subscription_id} >> /etc/bashrc\n        echo export AZURE_CLIENT_ID=${service_principal_id} >> /etc/bashrc\n        echo export AZURE_SECRET=${service_principal_secret} >> /etc/bashrc\n        echo export AZURE_TENANT=${tenant_id} >> /etc/bashrc\n\n    elif [ \"${service_principal_type}\" == \"msi\" ]; then\n        echo export ANSIBLE_AZURE_AUTH_SOURCE=msi >> /etc/profile\n        echo export ANSIBLE_AZURE_AUTH_SOURCE=msi >> /etc/bashrc\n    fi\n}\n\n# install pip\nsudo yum install -y epel-release\nsudo yum install -y python-pip python\n\n# install Ansible with specific version\nversion_option=\"==${ansible_version}\"\nget_ansible_install_option\nrun_command sudo pip install ansible[azure]${version_option}\nansible-galaxy collection install azure.azcollection\n\n# set azure credentials\nset_azure_credentials\n\n# install common tools\nsudo rpm --import https://packages.microsoft.com/keys/microsoft.asc\nsudo sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\nsudo yum install -y azure-cli", "num_lines": 121}
{"repo_name": "Ansible", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho $@\nfunction print_usage() {\n  cat <<EOF\nInstalls Ansible with specific version\nCommand\n  $0\nArguments\n  --version|-v                        : Ansible version\n  --service_principal_type|-sp        : The type of service principal: MSI or manual.\n  --service_principal_id|-sid         : The service principal ID.\n  --service_principal_secret|-ss      : The service principal secret.\n  --subscription_id|-subid            : The subscription ID of the SP.\n  --tenant_id|-tid                    : The tenant id of the SP.\n  --help|-h                           : Help of the script.\nEOF\n}\n\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --version|-v)\n      ansible_version=\"$1\"\n      shift\n      ;;\n    --service_principal_type|-sp)\n      service_principal_type=\"$1\"\n      shift\n      ;;\n    --service_principal_id|-spid)\n      service_principal_id=\"$1\"\n      shift\n      ;;\n    --service_principal_secret|-ss)\n      service_principal_secret=\"$1\"\n      shift\n      ;;\n    --subscription_id|-subid)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-tid)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nfunction run_command {\n    \"${@}\"\n\n    if [ $? -ne 0 ]; then\n        echo Failed to run \"${@}\"\n        exit 1\n\n    fi\n}\n\nfunction get_ansible_install_option {\n    if [ \"${ansible_version}\" == \"latest\" ]; then\n      version_option=\"\"\n    else\n      version_option=\"==${ansible_version}\"\n    fi\n}\n\nsp_cred=$(cat <<EOF\n[default]\nsubscription_id=${subscription_id}\nclient_id=${service_principal_id}\nsecret=${service_principal_secret}\ntenant=${tenant_id}\nEOF\n)\n\nfunction set_azure_credentials {\n    # write Azure credentials file\n    if [ \"${service_principal_type}\" == \"manual\" ]; then\n        echo export AZURE_SUBSCRIPTION_ID=${subscription_id} >> /etc/profile\n        echo export AZURE_CLIENT_ID=${service_principal_id} >> /etc/profile\n        echo export AZURE_SECRET=${service_principal_secret} >> /etc/profile\n        echo export AZURE_TENANT=${tenant_id} >> /etc/profile\n\n        echo export AZURE_SUBSCRIPTION_ID=${subscription_id} >> /etc/bash.bashrc\n        echo export AZURE_CLIENT_ID=${service_principal_id} >> /etc/bash.bashrc\n        echo export AZURE_SECRET=${service_principal_secret} >> /etc/bash.bashrc\n        echo export AZURE_TENANT=${tenant_id} >> /etc/bash.bashrc\n\n    elif [ \"${service_principal_type}\" == \"msi\" ]; then\n        echo export ANSIBLE_AZURE_AUTH_SOURCE=msi >> /etc/profile\n        echo export ANSIBLE_AZURE_AUTH_SOURCE=msi >> /etc/bash.bashrc\n    fi\n}\n\n# install pip\nsudo apt-get install -y python-pip\n\n# install Ansible with specific version\nversion_option=\"==${ansible_version}\"\nget_ansible_install_option\nrun_command sudo pip install ansible[azure]${version_option}\nansible-galaxy collection install azure.azcollection\n\n# set azure credentials\nset_azure_credentials\n\n# install common tools\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $(lsb_release -cs) main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\nwget -q -O - https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https\nsudo apt-get update --yes\nsudo apt-get install -y azure-cli\n", "num_lines": 123}
{"repo_name": "api-management-developer-portal", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Generate and provision default content of an API Management portal - incl. pages, layouts, configuration, media files, etc.\n\nexport management_endpoint=\"< service name >.management.azure-api.net\"\nexport access_token=\"SharedAccessSignature ...\"\nexport source_folder=\"../dist/snapshot\"\n\n# make sure to double quote the $access_token variable so it handles the space correctly\nnode ./generate $management_endpoint \"$access_token\" $data_file", "num_lines": 8}
{"repo_name": "api-management-developer-portal", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Generate and provision default content of an API Management portal - incl. pages, layouts, configuration, media files, etc.\n# Make sure you're logged-in with `az login` command before running the script.\n\nnode ./generate \\\n--subscriptionId \"< your subscription ID >\" \\\n--resourceGroupName \"< your resource group name >\" \\\n--serviceName \"< your service name >\"\n", "num_lines": 8}
{"repo_name": "app-configuration-import-action", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nname=\"$1\"\nfilePath=\"$2\"\nprefix=\"$3\"\nlabel=\"$4\"\n\nreadonly fileExtensions=\"json properties yaml\"\nreadonly fileExtension=\"${filePath##*.}\"\n\n# Create a label parameter if label value is not empty\nlabelParam=\nif [ ! -z \"$label\" ]; then\n  labelParam=\"--label $label\"\nfi\n\n# Create a prefix parameter if prefix value is not empty\nprefixParam=\nif [ ! -z \"$prefix\" ]; then\n  prefixParam=\"--prefix $prefix\"\nfi\n\nfileFormat=\nif [[ \"$fileExtension\" == \"yml\" ]]; then\n  fileFormat=\"yaml\"\nelse\n  if [[ \"$fileExtensions\" == *\"$fileExtension\"* ]]; then\n    fileFormat=$fileExtension\n  fi\nfi\n\n# Return error if file extension is not supported\n[ -z \"$fileFormat\" ] && echo \"Invalid '$fileFormat' file format. Supported values are: json, properties and yaml.\" && exit 1\n\naz appconfig kv import \\\n  --name \"$name\" \\\n  --source file \\\n  --path \"$filePath\" \\\n  --format $fileFormat \\\n  $labelParam $prefixParam --yes\n", "num_lines": 41}
{"repo_name": "app-configuration-import-action", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\npath=\"$1\"\nsourceName=\"$2\"\nappServiceAccountName=\"$3\"\n\n# Ensure only one of the input parameters are specified\nSIMULATE_XOR=\"${path:+VALID}${sourceName:+VALID}${appServiceAccountName:+VALID}\"\nif [[ \"${SIMULATE_XOR}\" != \"VALID\" ]]; then \n  echo \"Only one of the 'path', 'sourceName' and 'appServiceAccountName' input values is accepted.\"\n  exit 1\nfi\n", "num_lines": 13}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x -e\n\nbuildnumber=${4-$(date -u +\"%y%m%d%H%M\")}\n\ndocker build -t \"$1\"/node:4.4.7_\"$buildnumber\" 4.4.7\ndocker build -t \"$1\"/node:4.5.0_\"$buildnumber\" 4.5.0\ndocker build -t \"$1\"/node:4.8.3_\"$buildnumber\" 4.8.3\ndocker build -t \"$1\"/node:4.8.4_\"$buildnumber\" 4.8.4\ndocker build -t \"$1\"/node:6.2.2_\"$buildnumber\" 6.2.2\ndocker build -t \"$1\"/node:6.6.0_\"$buildnumber\" 6.6.0\ndocker build -t \"$1\"/node:6.9.3_\"$buildnumber\" 6.9.3\ndocker build -t \"$1\"/node:6.10.3_\"$buildnumber\" 6.10.3\ndocker build -t \"$1\"/node:6.11.0_\"$buildnumber\" 6.11.0\ndocker build -t \"$1\"/node:6.11.1_\"$buildnumber\" 6.11.1\ndocker build -t \"$1\"/node:6.11.5_\"$buildnumber\" 6.11.5\ndocker build -t \"$1\"/node:8.0.0_\"$buildnumber\" 8.0.0\ndocker build -t \"$1\"/node:8.1.2_\"$buildnumber\" 8.1.2\ndocker build -t \"$1\"/node:8.1.3_\"$buildnumber\" 8.1.3\ndocker build -t \"$1\"/node:8.1.4_\"$buildnumber\" 8.1.4\ndocker build -t \"$1\"/node:8.2.1_\"$buildnumber\" 8.2.1\ndocker build -t \"$1\"/node:8.8.0_\"$buildnumber\" 8.8.0\ndocker build -t \"$1\"/node:8.8.1_\"$buildnumber\" 8.8.1\ndocker build -t \"$1\"/node:8.9.4_\"$buildnumber\" -t \"$1\"/node:lts_\"$buildnumber\" 8.9.4\ndocker build -t \"$1\"/node:9.4.0_\"$buildnumber\" -t \"$1\"/node:latest_\"$buildnumber\" 9.4.0\n\ndocker login -u \"$2\" -p \"$3\"\n\ndocker push \"$1\"/node:4.4.7_\"$buildnumber\"\ndocker push \"$1\"/node:4.5.0_\"$buildnumber\"\ndocker push \"$1\"/node:4.8.3_\"$buildnumber\"\ndocker push \"$1\"/node:4.8.4_\"$buildnumber\"\ndocker push \"$1\"/node:6.2.2_\"$buildnumber\"\ndocker push \"$1\"/node:6.6.0_\"$buildnumber\"\ndocker push \"$1\"/node:6.9.3_\"$buildnumber\"\ndocker push \"$1\"/node:6.10.3_\"$buildnumber\"\ndocker push \"$1\"/node:6.11.0_\"$buildnumber\"\ndocker push \"$1\"/node:6.11.1_\"$buildnumber\"\ndocker push \"$1\"/node:6.11.5_\"$buildnumber\"\ndocker push \"$1\"/node:8.0.0_\"$buildnumber\"\ndocker push \"$1\"/node:8.1.2_\"$buildnumber\"\ndocker push \"$1\"/node:8.1.3_\"$buildnumber\"\ndocker push \"$1\"/node:8.1.4_\"$buildnumber\"\ndocker push \"$1\"/node:8.2.1_\"$buildnumber\"\ndocker push \"$1\"/node:8.8.0_\"$buildnumber\"\ndocker push \"$1\"/node:8.8.1_\"$buildnumber\"\ndocker push \"$1\"/node:8.9.4_\"$buildnumber\"\ndocker push \"$1\"/node:lts_\"$buildnumber\"\ndocker push \"$1\"/node:9.4.0_\"$buildnumber\"\ndocker push \"$1\"/node:latest_\"$buildnumber\"\n\ndocker logout\n", "num_lines": 53}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 28}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"", "num_lines": 31}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nNodeJS quickstart: https://aka.ms/node-qs\n\nEOL\ncat /etc/motd\n\nrc-update add sshd\n/etc/init.d/sshd start\n\nmkdir \"$PM2HOME\"\nchmod 777 \"$PM2HOME\"\nln -s /home/LogFiles \"$PM2HOME\"/logs\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\necho \"$@\" > /opt/startup/startupCommand\nnode /opt/startup/generateStartupCommand.js\n\nSTARTUPCOMMAND=$(cat /opt/startup/startupCommand)\necho \"Running $STARTUPCOMMAND\"\neval \"exec $STARTUPCOMMAND\"\n", "num_lines": 33}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x -e\n\nbuildnumber=${4-$(date -u +\"%y%m%d%H%M\")}\n\n# docker build -t \"$1\"/php:5.6.21-apache_\"$buildnumber\" 5.6.21-apache\n# docker build -t \"$1\"/php:5.6.21-apache-xdebug_\"$buildnumber\" 5.6.21-apache-xdebug\n# docker build -t \"$1\"/php:7.0.6-apache_\"$buildnumber\" 7.0.6-apache\n# docker build -t \"$1\"/php:7.0.6-apache-xdebug_\"$buildnumber\" 7.0.6-apache-xdebug\n# docker build -t \"$1\"/php:7.2.1-apache_\"$buildnumber\" -t \"$1\"/php:latest_\"$buildnumber\" 7.2.1-apache\ndocker build -t \"$1\"/php:7.2.1-apache-xdebug_\"$buildnumber\" -t \"$1\"/php:latest-xdebug_\"$buildnumber\" 7.2.1-apache-xdebug\n\ndocker login -u \"$2\" -p \"$3\"\n\n# docker push \"$1\"/php:5.6.21-apache_\"$buildnumber\"\n# docker push \"$1\"/php:5.6.21-apache-xdebug_\"$buildnumber\"\n# docker push \"$1\"/php:7.0.6-apache_\"$buildnumber\"\n# docker push \"$1\"/php:7.0.6-apache-xdebug_\"$buildnumber\"\ndocker push \"$1\"/php:latest_\"$buildnumber\"\ndocker push \"$1\"/php:7.2.1-apache_\"$buildnumber\"\ndocker push \"$1\"/php:latest-xdebug_\"$buildnumber\"\ndocker push \"$1\"/php:7.2.1-apache-xdebug_\"$buildnumber\"\n\ndocker logout\n", "num_lines": 25}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nPHP quickstart: https://aka.ms/php-qs\n\nEOL\ncat /etc/motd\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\nservice ssh start\nsed -i \"s/{PORT}/$PORT/g\" /etc/apache2/apache2.conf\nmkdir /var/lock/apache2\nmkdir /var/run/apache2\n/usr/sbin/apache2ctl -D FOREGROUND\n", "num_lines": 25}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nPHP quickstart: https://aka.ms/php-qs\n\nEOL\ncat /etc/motd\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\nservice ssh start\nsed -i \"s/{PORT}/$PORT/g\" /etc/apache2/apache2.conf\nmkdir /var/lock/apache2\nmkdir /var/run/apache2\n/usr/sbin/apache2ctl -D FOREGROUND\n", "num_lines": 25}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nPHP quickstart: https://aka.ms/php-qs\n\nEOL\ncat /etc/motd\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\nservice ssh start\nsed -i \"s/{PORT}/$PORT/g\" /etc/apache2/apache2.conf\nmkdir /var/lock/apache2\nmkdir /var/run/apache2\n/usr/sbin/apache2ctl -D FOREGROUND\n", "num_lines": 25}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x -e\n\nbuildnumber=${4-$(date -u +\"%y%m%d%H%M\")}\n\n#docker build -t \"$1\"/rubybase:2.3.3_\"$buildnumber\" base_images/2.3.3\ndocker build -t \"$1\"/ruby:2.3.3_\"$buildnumber\" -t \"$1\"/ruby:latest_\"$buildnumber\" 2.3.3\n\ndocker login -u \"$2\" -p \"$3\"\n\ndocker push \"$1\"/ruby:latest_\"$buildnumber\"\ndocker push \"$1\"/ruby:2.3.3_\"$buildnumber\"\n\ndocker logout\n", "num_lines": 15}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncat >/etc/motd <<EOL \n  _____                               \n  /  _  \\ __________ _________   ____  \n /  /_\\  \\\\___   /  |  \\_  __ \\_/ __ \\ \n/    |    \\/    /|  |  /|  | \\/\\  ___/ \n\\____|__  /_____ \\____/ |__|    \\___  >\n        \\/      \\/                  \\/ \nA P P   S E R V I C E   O N   L I N U X\n\nDocumentation: http://aka.ms/webapp-linux\nRuby quickstart: https://aka.ms/ruby-qs\n\nEOL\ncat /etc/motd\n\nservice ssh start\n\n# Get environment variables to show up in SSH session\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\neval \"$(rbenv init -)\"\nrbenv global 2.3.3\n/opt/startup.sh \"$@\"\n\n", "num_lines": 26}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif ! [ -e /home/site/wwwroot/Gemfile ] && [ -z \"$RAILS_IGNORE_SPLASH\" ]\n  then\n   echo 'No Gemfile found and RAILS_IGNORE_SPLASH not set, running default static site'\n   exec ruby /opt/staticsite.rb\nfi\n\nif [ -z \"$BUNDLE_WITHOUT\" ]; then \n  echo \"Bundle install with no 'without' options\"; \n  RUBY_OPTIONS=\"\";\nelse \n  RUBY_OPTIONS=\"--without $BUNDLE_WITHOUT\";\n  echo \"Bundle install with options $RUBY_OPTIONS\";\nfi\n\nif [ -z \"$BUNDLE_INSTALL_LOCATION\" ]; then \n  echo \"Defaulting gem installation directory to /tmp/bundle\"; \n  BUNDLE_INSTALL_LOCATION=\"/tmp/bundle\";\nelse \n  echo \"Gem installation directory is $BUNDLE_INSTALL_LOCATION\";\nfi\n\nif [ -z \"$RUBY_SITE_CONFIG_DIR\" ]; then \n  echo \"Defaulting site config directory to /home/site/config\"; \n  RUBY_SITE_CONFIG_DIR=\"/home/site/config\"\nelse \n  echo \"site config directory is $RUBY_SITE_CONFIG_DIR\";\nfi\n\nif [ -n \"$SECRET_KEY_BASE\" ]\n  then\n    echo 'Secret key base present'\n  else\n    echo 'Generating a secret key base'\n    export SECRET_KEY_BASE=$(ruby -rsecurerandom -e 'puts SecureRandom.hex(64)')\nfi\n\nif [ -n \"$RAILS_ENV\" ]\n  then\n    echo \"RAILS_ENV set to $RAILS_ENV\"\n  else\n    echo 'RAILS_ENV not set, default to production'\n    export RAILS_ENV='production'\nfi\n\necho 'Removing any leftover pids if present'\nrm -f tmp/pids/* ;\n\n# Support zipped gems \n\nif [ -f  \"${RUBY_SITE_CONFIG_DIR}/gems.tgz\" ]\n  then\n    echo \"gems.tgz detected, beginning unzipping process\"\n    echo \"unzipping...\"\n    mkdir -p $BUNDLE_INSTALL_LOCATION\n    cp  ${RUBY_SITE_CONFIG_DIR}/gems.tgz /tmp\n    tar -C $BUNDLE_INSTALL_LOCATION -xf /tmp/gems.tgz\n    \n    echo 'Removing bundler config'\n    rm -f ${BUNDLE_INSTALL_LOCATION}/config\n    \n    export ZIPPED_GEMS=1\nfi\n\necho 'Running bundle check'\nif [ \"$ZIPPED_GEMS\" -eq 1 ]\n  then\n    bundle config --global path $BUNDLE_INSTALL_LOCATION\n    if bundle check | grep satisfied\n    then\n      echo 'dependency check passed'\n    else\n      echo 'missing dependencies, try redeploying'\n      exit -1\n    fi\n  else\n    bundle config --local path \"vendor/bundle\"\n    if bundle check --path \"vendor/bundle\" | grep satisfied\n      then\n        echo 'dependency check passed'\n      else\n        echo 'missing dependencies, try redeploying'\n        exit -1\n    fi\nfi\n\nif [ \"$ZIPPED_GEMS\" -eq 1 ]\n  then\n    echo \"running bundle install $RUBY_OPTIONS --no-deployment\"\n    bundle install --no-deployment $RUBY_OPTIONS\n  else\n    echo \"running bundle install $RUBY_OPTIONS --local --path vendor/bundle\"\n    bundle install  $RUBY_OPTIONS --local --path vendor/bundle\nfi\n\nif [ -n \"$GEM_PRISTINE\" ]\n  then\n    echo 'running \"gem pristine --all\"'\n    bundle exec gem pristine --all\nfi\n\nif [ $# -ne 0 ]\n  then\n    echo \"Executing $@\"\n    exec \"$@\"\n  else\n    echo \"defaulting to command: \\\"bundle exec rails server -e $RAILS_ENV -p $PORT\\\"\"\n    exec bundle exec rails server -b 0.0.0.0 -e \"$RAILS_ENV\" -p \"$PORT\"\nfi", "num_lines": 110}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\nbuild_image(){  \n    _do cd ${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION}\n    _do docker build -t \"${DOCKER_IMAGE_NAME}\" .\n    _do cd $TRAVIS_BUILD_DIR    \n    testBuildImage=$(docker images | grep \"${DOCKER_IMAGE_NAME}\")\n    if [ -z \"${testBuildImage}\" ]; then \n        echo \"FAILED - Build fail!!!\"\n        exit 1\n    else\n        echo \"${testBuildImage}\"\n        echo \"${testBuildImage}\" >> result.log        \n        echo \"PASSED - Build Successfully!!!.\"\n        echo \"PASSED - Build Successfully!!!.\" >> result.log\n    fi\n    _do cd ..\n    _do cd ..\n}\n\nbuild_image\n", "num_lines": 29}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\ntest_Dockerfile(){\n    _do docker inspect ${DOCKER_IMAGE_NAME} > inspect.json\n    echo \"INFORMATION: Details of \"${DOCKER_IMAGE_NAME}\":\"\n    cat inspect.json\n\n    # Check SSH Ports\n    # Only 2 ports allowed where one is always 2222\n    testPORTS=$(jq .[].Config.ExposedPorts inspect.json | grep -o \":\" | wc -w)\n    if [ ${testPORTS} -gt 2 ]; then\n        echo \"${testPORTS}\" \n        echo \"FAILED - Too many ports are exposed!!!\"\n        exit 1\n    fi\n\n    testSSH=$(jq .[].Config.ExposedPorts inspect.json | grep 2222)\n    if [ -z \"${testSSH}\" ]; then \n        echo \"FAILED - PORT 2222 isn't opened, SSH isn't working!!!\"\n        exit 1\n    else\n        echo \"${testSSH}\"\n        echo \"PASSED - PROT 2222 is opened.\"\n    fi\n\n    # Check SSH is opened\n    entryPointFile=$(jq .[].Config.Entrypoint inspect.json)\n    entryPointFile=$(echo $entryPointFile | sed 's/\\[ \\\"//g')\n    entryPointFile=$(echo $entryPointFile | sed 's/\\\" ]//g')\n    entryPointFile=${entryPointFile##/*/}\n    _do cd ${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION}\n    entryPointFile=$(find . -name $entryPointFile)\n    testSSHEnable=$(cat $entryPointFile | grep \"service ssh start\")\n    if [ -z \"${testSSHEnable}\" ]; then \n        testSSHEnable=$(cat $entryPointFile | grep \"rc-service sshd start\")\n    fi\n    if [ -z \"${testSSHEnable}\" ]; then \n        testSSHEnable=$(cat $entryPointFile | grep \"/etc/init.d/sshd start\")\n    fi\n    \n    _do cd $TRAVIS_BUILD_DIR    \n    if [ -z \"${testSSHEnable}\" ]; then \n        echo \"FAILER - entrypoint is:\"$entryPointFile\n        echo \"FAILED - Doesn't found cmd about enable SSH in entrypoint file!!!\"\n        exit 1\n    else\n        echo \"${testSSHEnable}\"\n        echo \"PASSED - Cmd about enable SSH is found in entrypoint file.\"\n    fi\n\n    # Check Volume\n    testVOLUME=$(jq .[].Config.Volumes inspect.json | grep null)\n    if [ -z \"${testVOLUME}\" ]; then \n        testVOLUME=$(jq .[].Config.Volumes inspect.json)\n        echo \"${testVOLUME}\"\n        echo \"FAILED - These VOLUME lines should not be existed!!!\"\n        exit 1\n    else\n        echo \"PASSED - Great, there is no VOLUME lines.\"            \n    fi\n\n    # Check User\n    testUSER=$(jq .[].Config.User inspect.json)\n    if test \"${testUSER}\" != '\"\"' ; then        \n        echo \"${testUSER}\"\n        echo \"FAILED - These USER lines should not be existed!!!\"\n        exit 1\n    else\n        echo \"PASSED - Great, there is no USER lines.\"            \n    fi\n}\n\necho \"Docker: \"${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION}\necho \"Docker: \"${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION} >> result.log\ntest_Dockerfile\necho \"PASSED - Passed this stage.\" >> result.log\n\n\n\n\n", "num_lines": 88}
{"repo_name": "app-service-builtin-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\nsetTag_push_rm(){\n    echo \"TAG: ${TAG}\"\n    _do docker tag \"${DOCKER_IMAGE_NAME}\" \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    testBuildImage=$(docker images | grep \"$TAG\")\n    if [ -z \"${testBuildImage}\" ]; then \n        echo \"FAILED - Set TAG Failed!!!\"\n        exit 1\n    else\n        echo \"${testBuildImage}\"\n        echo \"${testBuildImage}\" >> result.log\n        echo \"PASSED - Set TAG Successfully!.\"\n        echo \"PASSED - Set TAG Successfully!.\" >> result.log\n    fi\n    _do docker push \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    echo \"PASSED - Pushed  ${DOCKER_ACCOUNT}/${DOCKER_IMAGE_NAME}:${TAG} Successfully!.\"\n    echo \"PASSED - Pushed  ${DOCKER_ACCOUNT}/${DOCKER_IMAGE_NAME}:${TAG} Successfully!.\" >> result.log\n    echo \"INFORMATION: Before rmi - docker images\"\n    _do docker images\n    echo \"INFORMATION - RM \"\"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    _do docker rmi \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    echo \"INFORMATION - After rmi - docker images\"\n    _do docker images\n}\n\necho \"Stage1 - Set Tag and Push\"\necho \"Stage1 - Set Tag and Push\" >> result.log\necho \"Build Number: ${TRAVIS_BUILD_NUMBER}\"\necho \"TRAVIS_EVENT_TYPE: ${TRAVIS_EVENT_TYPE}\"\necho \"TRAVIS_COMMIT_MESSAGE: ${TRAVIS_COMMIT_MESSAGE}\"\n\nisSignOff=\"false\"\nSignOff=\"#sign-off\"        \nsignOff=$(echo \"${TRAVIS_COMMIT_MESSAGE}\" | grep \"${SignOff}\")\nif [ -n \"${signOff}\" ]; then #contains \"#Sign-off\"\n    isSignOff=\"true\"\nfi\nif [ $DOCKER_ACCOUNT == $PROD_DOCKER_ACCOUNT ]; then #It's master branch\n    echo \"INFORMATION - This time, push to PROD docker hub.....\"\n    isSignOff=\"true\"    \nelse\n    echo \"INFORMATION - This time push to TEST docker hub......\"    \nfi\n\n_do echo \"${DOCKER_PASSWORD}\" | _do docker login \"${DOCKER_ACCOUNT}\" -u=\"${DOCKER_USERNAME}\" --password-stdin\n\nif [ $isSignOff == \"true\" ]; then\n    echo \"INFORMATION - This time, set tag as \"${DOCKER_IMAGE_VERSION}\" and push.....\"    \n    TAG=${DOCKER_IMAGE_VERSION}       \nelse\n    echo \"INFORMATION - This time, set tag as \"${DOCKER_IMAGE_VERSION}\"-\"${TRAVIS_BUILD_NUMBER}\" and push.....\"    \n    TAG=${DOCKER_IMAGE_VERSION}\"-\"${TRAVIS_BUILD_NUMBER}        \nfi\necho \"INFORMATION - Set TAG as \"\"${TAG}\"\" and push......\" \nsetTag_push_rm\n\necho \"========================================\"\necho \"Stage2 - PULL and Verify\"\necho \"INFORMATION - Start to Pull \"\"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\necho \"INFORMATION - Before Pull - docker images\"\n_do docker images\n_do docker run -d -p 80:80 --name testdocker $DOCKER_ACCOUNT/${DOCKER_IMAGE_NAME}:\"$TAG\"\necho \"INFORMATION: After Pull - docker images\"\n_do docker images\ntestBuildImage=$(docker images | grep \"${TAG}\")\n    if [ -z \"$testBuildImage\" ]; then \n        echo \"FAILED - Docker pull and run Failed!!!\"\n        docker images\n        exit 1\n    else\n        echo \"$testBuildImage\"\n        echo \"$testBuildImage\" >> result.log\n        echo \"PASSED - Docker image pull and run Successfully!. You can manually verify it!\"\n        echo \"PASSED - Docker image pull and run Successfully!. You can manually verify it!\" >> result.log\n    fi\n_do docker stop testdocker\n_do docker rm testdocker\n_do docker rmi ${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\n\n# Deal With latest version\nif [ $isSignOff == \"true\" ]; then #Is it \"#sign-off\" or \"master_brnach\"?\n    _do cd ${DOCKER_IMAGE_NAME}\n    if test -e latest.txt; then\n        LATEST_VERSION=$(cat latest.txt)\n        _do cd ..\n        echo \"LATEST_VERSION:\"$LATEST_VERSION\n        if [ $DOCKER_IMAGE_VERSION == $LATEST_VERSION ]; then             \n            echo \"INFORMATION - This time, also need to push as latest version......\"\n            echo \"INFORMATION - This time, also need to push as latest version......\" >> result.log    \n            TAG=\"latest\"\n            echo \"INFORMATION - Set TAG as \"\"${TAG}\"\" and push......\" \n            setTag_push_rm        \n        fi\n    else\n        _do cd ..\n    fi    \nfi\n", "num_lines": 106}
{"repo_name": "App-Service-Migration-Assistant", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script contains sample commands for creating resources for an Azure App Service web site using Azure CLI - it is meant to be used as an example of az commands\n# Prior to running this script you should install Azure CLI, login to Azure, and select the subscription you want to use\n# Installing Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-apt?view=azure-cli-latest):\n#     curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n# Logging in: \n#     az login\n# Selecting a subscription (https://docs.microsoft.com/en-us/cli/azure/manage-azure-subscriptions-azure-cli?view=azure-cli-latest):\n#     az account set --subscription \"<SUBSCRIPTION NAME>\"\n\nmyResourceGroupName=\"MyNewRG\"\n# myAzureRegion value options can be found using: https://docs.microsoft.com/en-us/cli/azure/appservice?view=azure-cli-latest#az-appservice-list-locations) \nmyAzureRegion=\"Central US\"\nmyASPName=\"MyNewASP\"\nmySiteName=\"MyNewUniqueSiteName\"\nmyACRName=\"MyNewUniqueACRName\"\nimageAndTag=\"imagename:latest\"\nmyLocalContainerId=\"96302002acff\"\n\necho \"Creating resource group $myResourceGroupName\"\naz group create --name $myResourceGroupName --location \"$myAzureRegion\"\n\necho ''\necho \"Creating an Azure Container Registry ($myACRName) and saving the registry password for later step\"\naz acr create --name $myACRName --resource-group $myResourceGroupName --sku Basic --admin-enabled true -l \"$myAzureRegion\"\nacrpwd=$(az acr credential show --name $myACRName | grep  '\"value\"' -m 1 | cut -d '\"' -f 4)\n\necho ''\necho \"Creating a single web worker App Service Plan\"\naz appservice plan create -n $myASPName -g $myResourceGroupName --is-linux -l \"$myAzureRegion\" --sku P1v2 --number-of-workers 1\n\necho \"Create image from specified container, login to ACR, and push image to the new Azure Container Registry\"\nsudo docker commit $myLocalContainerId ${myACRName}.azurecr.io/$imageAndTag\nsudo docker login ${myACRName}.azurecr.io --username $myACRName -p $acrpwd\nsudo docker push ${myACRName}.azurecr.io/$imageAndTag\n\necho \"Creating site using image in Azure Container Registry\"\naz webapp create --resource-group $myResourceGroupName --plan $myASPName --name $mySiteName --deployment-container-image-name ${myACRName}.azurecr.io/$imageAndTag --docker-registry-server-user $myACRName --docker-registry-server-password $acrpwd\n\necho ''\necho \"Created site ${mySiteName}.azurewebsites.net\"", "num_lines": 40}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    chown -R www-data:www-data $PHPMYADMIN_HOME\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nchown -R www-data:www-data $APP_HOME\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nchown -R www-data:www-data $HTTPD_LOG_DIR\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting Apache httpd -D FOREGROUND ...\"\napachectl start -D FOREGROUND\n", "num_lines": 89}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi    \n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \ntest ! -e \"$APP_HOME/index.php\" && echo \"INFO: index.php not found. createing\" && echo \"<?php phpinfo();?>\" > \"$APP_HOME/index.php\"\n\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR  \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi \n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n#rc-service sshd start\n#apachectl start -D FOREGROUND\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n\n\n", "num_lines": 108}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi    \n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \ntest ! -e \"$APP_HOME/index.php\" && echo \"INFO: index.php not found. createing\" && echo \"<?php phpinfo();?>\" > \"$APP_HOME/index.php\"\n\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR  \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi \n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n#rc-service sshd start\n#apachectl start -D FOREGROUND\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n\n\n", "num_lines": 109}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi    \n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \ntest ! -e \"$APP_HOME/index.php\" && echo \"INFO: index.php not found. createing\" && echo \"<?php phpinfo();?>\" > \"$APP_HOME/index.php\"\n\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR  \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi \n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n#rc-service sshd start\n#apachectl start -D FOREGROUND\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n\n\n", "num_lines": 109}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi    \n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \ntest ! -e \"$APP_HOME/index.php\" && echo \"INFO: index.php not found. createing\" && echo \"<?php phpinfo();?>\" > \"$APP_HOME/index.php\"\n\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR  \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi \n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n#rc-service sshd start\n#apachectl start -D FOREGROUND\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n\n\n", "num_lines": 109}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n    \n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi    \n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \ntest ! -e \"$APP_HOME/index.php\" && echo \"INFO: index.php not found. createing\" && echo \"<?php phpinfo();?>\" > \"$APP_HOME/index.php\"\n\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR  \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi \n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username:\"\n    echo \"$DATABASE_USERNAME\"\n    echo \"phpmyadmin password:\"\n    echo \"$DATABASE_PASSWORD\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n\n\n", "num_lines": 102}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Starting SSH ...\"\nservice ssh start\n\npython /code/app.py", "num_lines": 7}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Starting SSH ...\"\nservice ssh start\n\ncd / && django-admin startproject djangoapp\necho \"ALLOWED_HOSTS=['*']\" >> /djangoapp/djangoapp/settings.py\npython /djangoapp/manage.py runserver 0.0.0.0:8000\n", "num_lines": 10}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nphp -v\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\nsed -i \"s|error_log /var/log/nginx/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\nrm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\n\n# setup server root\nmkdir -p \"$DRUPAL_HOME\"\nchown -R www-data:www-data \"$DRUPAL_HOME/\"\n\n# create index.html\ntest -d \"${DRUPAL_HOME}/index.html\" && rm ${DRUPAL_HOME}/index.html \necho '<html><head><meta http-equiv=\"refresh\" content=\"30\" /><meta http-equiv=\"pragma\" content=\"no-cache\" /><meta http-equiv=\"cache-control\" content=\"no-cache\" /><title>Installing Drupal</title></head><body>Installing Drupal ... This could be done in minutes. <p>Please refresh your browser and go to  http://[website]/index.php later.</p></body></html>' > ${DRUPAL_HOME}/index.html \n\ncd $DRUPAL_SOURCE \ntar -xf drupal.tar.gz -C $DRUPAL_HOME/ --strip-components=1 \nchmod a+w \"$DRUPAL_HOME/sites/default\" \nmkdir -p \"$DRUPAL_HOME/sites/default/files\"\nchmod a+w \"$DRUPAL_HOME/sites/default/files\"\ncp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\nchmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\ncd $DRUPAL_HOME\nrm -rf $DRUPAL_SOURCE\n\necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\n/usr/sbin/nginx\n\n\n", "num_lines": 46}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n#unzip drupal\nsetup_drupal(){\n    # tar drupal\n    cd $DRUPAL_SOURCE \n    tar -xf drupal.tar.gz -C $DRUPAL_HOME/ --strip-components=1 \n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n    cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n}\n\n# setup server root\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n    chown -R www-data:www-data $DRUPAL_HOME \nfi \n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then\n    echo \"Installing Drupal ...\"\n    setup_drupal\nfi\ncd $DRUPAL_HOME\nrm -rf $DRUPAL_SOURCE\n       \necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx\n\n\n", "num_lines": 126}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi\n}\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi \n    setup_drupal\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx\n\n\n", "num_lines": 147}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi\n}\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi \n    setup_drupal\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx\n\n\n", "num_lines": 147}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi   \n}\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi \n    setup_drupal\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 158}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi   \n}\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi \n    setup_drupal\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 158}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi   \n}\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi \n    setup_drupal\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 158}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\ninstall_drush(){\n    composer global require consolidation/cgr \n\tcomposer_home=$(find / -name .composer)\n    ln -s $composer_home/vendor/bin/cgr /usr/local/bin/cgr\n\tcgr drush/drush \n    ln -s $composer_home/vendor/bin/drush /usr/local/bin/drush\n}\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi   \n}\n\ninstall_drush\n\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n    \n    setup_drupal\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi\n    chown -R www-data:www-data /var/www/html\nfi\ncd $DRUPAL_HOME\n\necho \"Starting Redis ...\"\nredis-server &\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 169}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\ninstall_drush(){\n    composer self-update\n    composer global require consolidation/cgr \n\tcomposer_home=$(find / -name .composer)\n    ln -s $composer_home/vendor/bin/cgr /usr/local/bin/cgr\n\tcgr drush/drush \n    ln -s $composer_home/vendor/bin/drush /usr/local/bin/drush\n}\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# Generate drupal by composer\nsetup_drupal(){\t\n\tmkdir -p \"$DRUPAL_HOME/config/sync\"\n    chmod a+w \"$DRUPAL_HOME/config/sync\"\n    chmod a+w \"$DRUPAL_HOME/web/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/web/sites/default/files\"\n    # still like to chown in Azure.\n    chown -R www-data:www-data $DRUPAL_HOME     \t\n}\n\ninstall_drush\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/web/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    if test -e \"$DRUPAL_HOME/composer.json\"; then \n        cd $DRUPAL_HOME && composer install\n    else\n        while test -d \"$DRUPAL_HOME\"  \n        do\n            echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n            mv $DRUPAL_HOME /home/site/bak$(date +%s)\n        done\n        composer create-project drupal-composer/drupal-project:8.x-dev  $DRUPAL_HOME --stability dev --no-interaction\n    fi\n    setup_drupal    \nfi\ncd $DRUPAL_HOME\n\necho \"Starting Redis ...\"\nredis-server &\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 143}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf   \n    cd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){    \n    cd $DRUPAL_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linuxappservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t\n    chmod a+w \"$DRUPAL_HOME/sites/default\" \n    mkdir -p \"$DRUPAL_HOME/sites/default/files\"\n    chmod a+w \"$DRUPAL_HOME/sites/default/files\"\n\tif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n        #Test this time, after git pull, myabe drupal has already installed in repo.\n        cp \"$DRUPAL_HOME/sites/default/default.settings.php\" \"$DRUPAL_HOME/sites/default/settings.php\"\n        chmod a+w \"$DRUPAL_HOME/sites/default/settings.php\"\n\tfi   \n}\n\ntest ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif test ! -e \"$DRUPAL_HOME/sites/default/settings.php\"; then \n#Test this time, if WEBSITES_ENABLE_APP_SERVICE_STORAGE = true and drupal has already installed.\n    echo \"Installing Drupal ...\"    \n    # If home folder is exist, clean it, ready to git pull\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it to ready for git...\"\n        rm -rf $DRUPAL_HOME\n    done \n    test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\n    \n    setup_drupal\n\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME  \n        chown -R www-data:www-data $DRUPAL_HOME \n    fi\n    chown -R www-data:www-data /var/www/html\nfi\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n\n", "num_lines": 157}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb restart\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/nginx.conf\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    cp -R default.phpmyadmin.vcl /etc/varnish/default.vcl\n    cd /\n    rm -Rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    # test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\t# cd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\n# test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\n\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R www-data:www-data $DRUPAL_PRJ \nfi\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\n\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    chmod 777 /run/php/php7.0-fpm.sock\nfi\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n", "num_lines": 217}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb restart\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/nginx.conf\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    cp -R default.phpmyadmin.vcl /etc/varnish/default.vcl\n    cd /\n    rm -Rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\n# test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-localhost}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\n\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R www-data:www-data $DRUPAL_PRJ \nfi\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\n\ncd $DRUPAL_HOME\n       \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    chmod 777 /run/php/php7.0-fpm.sock\nfi\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n", "num_lines": 233}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    rc-service mariadb restart\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1 \n    cp -R phpmyadmin-default.conf /etc/nginx/nginx.conf\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    cp -R default.phpmyadmin.vcl /etc/varnish/default.vcl\n    cd /\n    rm -Rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\n# test ! -d \"$DRUPAL_HOME\" && echo \"INFO: $DRUPAL_HOME not found. creating...\" && mkdir -p \"$DRUPAL_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-localhost}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\n\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R www-data:www-data $DRUPAL_PRJ \nfi\n\ncd $DRUPAL_HOME\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config       \necho \"Starting SSH ...\"\nrc-service sshd start\n\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\nif [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n    touch $NGINX_LOG_DIR/php-error.log;    \nfi\nchmod 666 $NGINX_LOG_DIR/php-error.log;\ntest ! -d \"/usr/local/php/tmp\" && echo \"INFO: Session folder for php not found. creating...\" && mkdir -p \"/usr/local/php/tmp\"\nchmod 777 /usr/local/php/tmp\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php7.0-fpm.sock && chown www-data:www-data /run/php/php7.0-fpm.sock && chmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting php-fpm ...\"\nphp-fpm -D && chmod 777 /run/php/php7.0-fpm.sock\n\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"Starting Nginx ...\"\nif test ! -e $NGINX_LOG_DIR/error.log; then \n    touch $NGINX_LOG_DIR/error.log\nfi\nchmod 666 $NGINX_LOG_DIR/error.log;\n/usr/sbin/nginx -g \"daemon off;\"\n", "num_lines": 221}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1\n    cp -R phpmyadmin-default.conf /etc/nginx/nginx.conf    \n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    cp -R default.phpmyadmin.vcl /etc/varnish/default.vcl    \n\tcd /\n    rm -Rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -Rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R www-data:www-data $DRUPAL_PRJ \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi   \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# Backup default nginx setting, use customer's nginx setting\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php7.0-fpm.sock && chown www-data:www-data /run/php/php7.0-fpm.sock && chmod 777 /run/php/php7.0-fpm.sock\n\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config  \n\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 237}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nAZURE_DETECTED=$WEBSITES_ENABLE_APP_SERVICE_STORAGE # if defined, assume the container is running on Azure\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1\n    cp -R phpmyadmin-default.conf /etc/nginx/nginx.conf    \n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    cp -R default.phpmyadmin.vcl /etc/varnish/default.vcl    \n\tcd /\n    rm -Rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -Rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R www-data:www-data $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $AZURE_DETECTED ]; then\n    echo \"INFO: NOT in Azure, chown for $DRUPAL_PRJ\"\n    chown -R www-data:www-data $DRUPAL_PRJ \n    echo \"INFO: NOT in Azure, skipping fluentd setup...\"\nelse\n    if [ ! $APPSETTING_OMSWORKSPACE_ID ]; then\n        echo 'INFO: Environment variable APPSETTING_OMSWORKSPACE_ID not found. Skipping fluentd setup...'\n    else\n        echo 'INFO: Azure detected. Adding fluentd to /etc/supervisord.conf...'\n        echo_default_fluentd_config() {\n            echo '[program:fluentd]'\n            echo 'command=fluentd -c /etc/fluent.conf -o /var/log/fluentd.log --log-rotate-age=3 --log-rotate-size 10240000' \n        }\n        echo_default_fluentd_config >> /etc/supervisord.conf\n    fi\nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi   \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# Backup default nginx setting, use customer's nginx setting\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php7.0-fpm.sock && chown www-data:www-data /run/php/php7.0-fpm.sock && chmod 777 /run/php/php7.0-fpm.sock\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config  \n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 249}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/nginx.conf    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-vcl.txt\" /etc/varnish/default.vcl    \n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n\tcd /\n    rm -Rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R nginx:nginx $PHPMYADMIN_HOME\n    fi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -Rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R nginx:nginx $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R nginx:nginx $DRUPAL_PRJ \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi   \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# Backup default nginx setting, use customer's nginx setting\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"/home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n# Backup default varnish setting, use customer's nginx setting\ntest -d \"/home/etc/varnish\" && mv /etc/varnish /etc/varnish-bak && ln -s /home/etc/varnish /etc/varnish\ntest ! -d \"/home/etc/varnish\" && mkdir -p /home/etc && mv /etc/varnish /home/etc/varnish && ln -s /home/etc/varnish /etc/varnish\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php7.0-fpm.sock && chown nginx:nginx /run/php/php7.0-fpm.sock && chmod 777 /run/php/php7.0-fpm.sock\n\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config  \n\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 240}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/nginx.conf    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-vcl.txt\" /etc/varnish/default.vcl    \n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n\tcd /\n    rm -Rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R nginx:nginx $PHPMYADMIN_HOME\n    fi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -Rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R nginx:nginx $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R nginx:nginx $DRUPAL_PRJ \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi   \n\n# Persist drupal/sites, modules, themes\ntest -d \"/home/sites\" && mv $DRUPAL_PRJ/web/sites $DRUPAL_PRJ/web/sites-bak  \ntest ! -d \"/home/sites\" && mv $DRUPAL_PRJ/web/sites /home/sites \nln -s /home/sites $DRUPAL_PRJ/web/sites\ntest -d \"/home/modules\" && mv $DRUPAL_PRJ/web/modules $DRUPAL_PRJ/web/modules-bak  \ntest ! -d \"/home/modules\" && mv $DRUPAL_PRJ/web/modules /home/modules \nln -s /home/modules $DRUPAL_PRJ/web/modules\ntest -d \"/home/themes\" && mv $DRUPAL_PRJ/web/themes $DRUPAL_PRJ/web/themes-bak  \ntest ! -d \"/home/themes\" && mv $DRUPAL_PRJ/web/themes /home/themes \nln -s /home/themes $DRUPAL_PRJ/web/themes\n\n# Create Log folders\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# Backup default nginx setting, use customer's nginx setting\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n# Backup default varnish setting, use customer's nginx setting\ntest -d \"/home/etc/varnish\" && mv /etc/varnish /etc/varnish-bak && ln -s /home/etc/varnish /etc/varnish\ntest ! -d \"home/etc/varnish\" && mkdir -p /home/etc && mv /etc/varnish /home/etc/varnish && ln -s /home/etc/varnish /etc/varnish\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php-fpm.sock && chown nginx:nginx /run/php/php-fpm.sock && chmod 777 /run/php/php-fpm.sock\n\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config  \n\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 252}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -Rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld    \n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME/ --strip-components=1    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/nginx.conf    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-vcl.txt\" /etc/varnish/default.vcl    \n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n\tcd /\n    rm -Rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R nginx:nginx $PHPMYADMIN_HOME\n    fi\n}\n\n#Get drupal from Git\nsetup_drupal(){\n    while test -d \"$DRUPAL_PRJ\"  \n    do\n        echo \"INFO: $DRUPAL_PRJ is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $DRUPAL_PRJ /home/bak/drupal_prj_bak$(date +%s)\n    done\n    test ! -d \"$DRUPAL_PRJ\" && echo \"INFO: $DRUPAL_PRJ not found. creating...\" && mkdir -p \"$DRUPAL_PRJ\"\t\n\tcd $DRUPAL_PRJ\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/drupalcms-composer-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $DRUPAL_PRJ\t&& cd $DRUPAL_PRJ\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n\n    if [ $DATABASE_USERNAME ]; then\n        #cd $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Installing\n        echo \"INFO: Setting of DATABASE ...\"\n        mkdir -p /home/bak\n        mv $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php /home/bak/Tasks$(date +%s).php        \n        cp $DRUPAL_SOURCE/drupal-database-install-tasks.php $DRUPAL_PRJ/web/core/lib/Drupal/Core/Database/Install/Tasks.php \n        # cd $DRUPAL_PRJ/\n    fi\n\n    # restore old site to drupal project\n    if [ -d /home/bak/drupal_site ]; then \n        echo \"INFO: Restore old version site ...\"\n        while test -d \"$DRUPAL_PRJ/web\"  \n        do\n            # mv is faster than rm.\n            mv $DRUPAL_PRJ/web /home/bak/drupal_prj_web_bak$(date +%s)            \n        done\n        mv /home/bak/drupal_site $DRUPAL_PRJ/web/\n    fi\n        \n    chmod a+w \"$DRUPAL_PRJ/web/sites/default\" \n    if [ -e \"$DRUPAL_PRJ/web/sites/default/settings.php\" ]; then \n        #Test this time, if application settings are set to a personal git, myabe drupal has already installed in repo.\n        echo \"INFO: Settings.php is exist...\"    \n    else\n        echo \"INFO: Settings.php isn't exist...\"    \n        mkdir -p \"$DRUPAL_PRJ/web/sites/default/files\"\n        cp \"$DRUPAL_PRJ/web/sites/default/default.settings.php\" \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    fi\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/files\"\n    chmod a+w \"$DRUPAL_PRJ/web/sites/default/settings.php\"\n    while test -d \"$DRUPAL_HOME\"  \n    do\n        echo \"INFO: $DRUPAL_HOME is exist, clean it ...\"        \n        chmod 777 -R $DRUPAL_HOME \n        rm -Rf $DRUPAL_HOME\n    done\n    ln -s $DRUPAL_PRJ/web  $DRUPAL_HOME           \t\n}\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_HOME \n    chown -R nginx:nginx $DRUPAL_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    DATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n    DATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD \n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD   \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n     \n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\n# setup Drupal\nif [ -e \"$DRUPAL_HOME/sites/default/settings.php\" ]; then\n# Site is exist.\n    if [ -d \"$DRUPAL_PRJ\" ]; then\n    # site is exist and is built by composer build, no need to git pull again.\n        echo \"INFO: $DRUPAL_PRJ is exist...\"        \n        echo \"INFO: Site is Ready...\"\n    else\n    # site is exist and it's not built by composer build, backup it at first.\n        echo \"INFO: Old Version Site is exist, Backup Site...\"        \n        if [ -d /home/bak/drupal_site ]; then\n            mv /home/bak/drupal_site /home/bak/drupal_site$(date +%s)\n        else            \n            mkdir -p /home/bak\n        fi\n        mv $DRUPAL_HOME /home/bak/drupal_site\n        echo \"Installing Drupal ...\"    \n        setup_drupal  \n    fi    \nelse\n# drupal isn't installed, fresh start\n    echo \"Installing Drupal ...\"    \n    setup_drupal   \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$DRUPAL_PRJ  \n    chown -R nginx:nginx $DRUPAL_PRJ \nfi\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi   \n\ntest ! -d /home/apache-solr && mkdir /home/apache-solr && tar -xf /usr/src/apache-solr.tgz -C /home/apache-solr/ --strip-components=1 \ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$VARNISH_LOG_DIR\" && echo \"INFO: Log folder for varnish found. creating...\" && mkdir -p \"$VARNISH_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# Backup default nginx setting, use customer's nginx setting\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"/home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n# Backup default varnish setting, use customer's nginx setting\ntest -d \"/home/etc/varnish\" && mv /etc/varnish /etc/varnish-bak && ln -s /home/etc/varnish /etc/varnish\ntest ! -d \"/home/etc/varnish\" && mkdir -p /home/etc && mv /etc/varnish /home/etc/varnish && ln -s /home/etc/varnish /etc/varnish\n\necho \"Starting Varnishd ...\"\n/usr/sbin/varnishd -a :80 -f /etc/varnish/default.vcl\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php && touch /run/php/php7.0-fpm.sock && chown nginx:nginx /run/php/php7.0-fpm.sock && chmod 777 /run/php/php7.0-fpm.sock\n\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config  \n\necho \"Starting Apache Solr Server ...\"\ncd /home/apache-solr/solr/example && java -jar start.jar &\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 243}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\necho \"Starting SSH ...\"\nservice ssh start\n\npython /code/runserver.py", "num_lines": 7}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_moodle(){\n\ttest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating ...\" && mkdir -p \"$MOODLE_HOME\"\n\tcd $MOODLE_HOME\n    GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/moodle-linuxappservice-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $MOODLE_HOME/moodle\t&& cd $MOODLE_HOME/moodle\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n    cp -rf $MOODLE_SOURCE/installlib.php $MOODLE_HOME/moodle/lib/installlib.php    \n    mkdir -p $MOODLE_HOME/moodledata    \n    chmod -R 777 $MOODLE_HOME\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$MOODLE_HOME  \n        chown -R www-data:www-data $MOODLE_HOME\n    fi \n}\n\nupdate_db_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD\t \n}\n\n# setup server root\ntest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating...\" && mkdir -p \"$MOODLE_HOME\"\n# if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n#     echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n#     chown -R www-data:www-data $WORDPRESS_HOME\n# fi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    update_db_config\n    # DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    # DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin    \nfi\n\n# That config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$MOODLE_HOME/moodle/config.php\" ]; then\n\techo \"INFO: $MOODLE_HOME/moodle/config.php not found.\"\n\techo \"Installing Moodle for the first time ...\" \n\tsetup_moodle\t\n\n\tif [ ${DATABASE_HOST} ]; then\n        echo \"INFO: Update config.php...\"\n        \n        cd $MOODLE_HOME/moodle\n\t\tcp $MOODLE_SOURCE/config.php .\n        chmod 777 config.php\n\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data config.php\n        fi\n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n            #$CFG->dbtype    = 'mariadb';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mariadb'/g\" config.php\n        else\n            sed -i \"s/getenv('DATABASE_TYPE')/'mysqli'/g\" config.php\n        fi\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" config.php\n    else \n        echo \"INFO: DATABASE_HOST: ${DATABASE_HOST}\"\t\t\t        \n\tfi\nelse\n\techo \"INFO: $MOODLE_HOME/moodle/config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\nif [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n    touch $NGINX_LOG_DIR/php-error.log;    \nfi\nchmod 777 $NGINX_LOG_DIR/php-error.log;\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    chmod 777 /run/php/php7.0-fpm.sock\nfi\n\necho \"Starting Nginx ...\"\nif test ! -e $NGINX_LOG_DIR/error.log; then \n    touch $NGINX_LOG_DIR/nginx/error.log\nfi\nchmod 777 $NGINX_LOG_DIR/nginx/error.log\n/usr/sbin/nginx -g \"daemon off;\"\n\n", "num_lines": 214}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_moodle(){\n\ttest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating ...\" && mkdir -p \"$MOODLE_HOME\"\n\tcd $MOODLE_HOME\n    GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/moodle-linuxappservice-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $MOODLE_HOME/moodle\t&& cd $MOODLE_HOME/moodle\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n    cp -rf $MOODLE_SOURCE/installlib.php $MOODLE_HOME/moodle/lib/installlib.php    \n    mkdir -p $MOODLE_HOME/moodledata    \n    chmod -R 777 $MOODLE_HOME\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$MOODLE_HOME  \n        chown -R www-data:www-data $MOODLE_HOME\n    fi \n}\n\nupdate_db_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD\t \n}\n\n# setup server root\ntest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating...\" && mkdir -p \"$MOODLE_HOME\"\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"    \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    update_db_config\n    # DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    # DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin    \nfi\n\n# That config.php doesn't exist means moodle is not installed/configured yet.\nif [ ! -e \"$MOODLE_HOME/moodle/config.php\" ]; then\n\techo \"INFO: $MOODLE_HOME/moodle/config.php not found.\"\n\techo \"Installing Moodle for the first time ...\" \n\tsetup_moodle\t\n\n\tif [ ${DATABASE_HOST} ]; then\n        echo \"INFO: Update config.php...\"\n        \n        cd $MOODLE_HOME/moodle\n\t\tcp $MOODLE_SOURCE/config.php .\n        chmod 777 config.php\n\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data config.php\n        fi\n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n            #$CFG->dbtype    = 'mariadb';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mariadb'/g\" config.php\n        else\n            sed -i \"s/getenv('DATABASE_TYPE')/'mysqli'/g\" config.php\n        fi\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" config.php\n    else \n        echo \"INFO: DATABASE_HOST: ${DATABASE_HOST}\"\t\t\t        \n\tfi\nelse\n\techo \"INFO: $MOODLE_HOME/moodle/config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting Memcached ...\"\n/usr/bin/memcached -u memcached -v -m 128 -p 11211 -c 1024 -I 4M &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 231}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_moodle(){\n\ttest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating ...\" && mkdir -p \"$MOODLE_HOME\"\n\tcd $MOODLE_HOME\n    GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/moodle-linuxappservice-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $MOODLE_HOME/moodle\t&& cd $MOODLE_HOME/moodle\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n    cp -rf $MOODLE_SOURCE/installlib.php $MOODLE_HOME/moodle/lib/installlib.php    \n    mkdir -p $MOODLE_HOME/moodledata    \n    chmod -R 777 $MOODLE_HOME\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$MOODLE_HOME  \n        chown -R www-data:www-data $MOODLE_HOME\n    fi \n}\n\nupdate_db_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST\n    export DATABASE_NAME\n    export DATABASE_USERNAME\n    export DATABASE_PASSWORD\t \n}\n\n# setup server root\ntest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating...\" && mkdir -p \"$MOODLE_HOME\"\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"    \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    update_db_config\n    # DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    # DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin    \nfi\n\n# That config.php doesn't exist means moodle is not installed/configured yet.\nif [ ! -e \"$MOODLE_HOME/moodle/config.php\" ]; then\n\techo \"INFO: $MOODLE_HOME/moodle/config.php not found.\"\n\techo \"Installing Moodle for the first time ...\" \n\tsetup_moodle\t\n\n\tif [ ${DATABASE_HOST} ]; then\n        echo \"INFO: Update config.php...\"\n        \n        cd $MOODLE_HOME/moodle\n\t\tcp $MOODLE_SOURCE/config.php .\n        chmod 777 config.php\n\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data config.php\n        fi\n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n            #$CFG->dbtype    = 'mariadb';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mariadb'/g\" config.php\n        else\n            sed -i \"s/getenv('DATABASE_TYPE')/'mysqli'/g\" config.php\n        fi\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" config.php\n    else \n        echo \"INFO: DATABASE_HOST: ${DATABASE_HOST}\"\t\t\t        \n\tfi\nelse\n\techo \"INFO: $MOODLE_HOME/moodle/config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting Memcached ...\"\nmemcached -u memcache &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 231}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_moodle(){\n    while test -d \"$MOODLE_HOME/moodle\"\n    do\n        echo \"INFO: $MOODLE_HOME/moodle is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $MOODLE_HOME/moodle /home/bak/moodle$(date +%s)\n    done\n\ttest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating ...\" && mkdir -p \"$MOODLE_HOME\"\n\tcd $MOODLE_HOME\n    GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/moodle-linuxappservice-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $MOODLE_HOME/moodle\t&& cd $MOODLE_HOME/moodle\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n    cp -rf $MOODLE_SOURCE/installlib.php $MOODLE_HOME/moodle/lib/installlib.php    \n    chmod -R 777 $MOODLE_HOME\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$MOODLE_HOME  \n        chown -R www-data:www-data $MOODLE_HOME\n    fi    \n}\n\nupdate_db_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD    \n}\n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"    \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    update_db_config\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin    \nfi\n\n# setup Moodle\n# That config.php doesn't exist means moodle is not installed/configured yet.\nif [ ! -e \"$MOODLE_HOME/moodle/config.php\" ]; then    \n\techo \"INFO: $MOODLE_HOME/moodle/config.php not found.\"\n\techo \"Installing Moodle for the first time ...\" \n\tsetup_moodle\t\n\n\tif [ ${DATABASE_HOST} ]; then\n        echo \"INFO: DB Parameters are setted, Update config.php...\"\n        \n        cd $MOODLE_HOME/moodle && cp $MOODLE_SOURCE/config.php . \n        chmod 777 config.php\n\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data config.php\n        fi\n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n            #$CFG->dbtype    = 'mariadb';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mariadb'/g\" config.php\n        else\n            #$CFG->dbtype    = 'mysqli';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mysqli'/g\" config.php\n        fi        \n    else \n        echo \"INFO: DATABASE_HOST isn't exist, please fill parameters during installation!\"\t\t\t        \n\tfi\nelse\n\techo \"INFO: $MOODLE_HOME/moodle/config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"    \nfi\t\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\n# Set Cache path of moodle\nmkdir -p $MOODLE_HOME/moodledata/filedir && mkdir -p /var/moodledata \nln -s $MOODLE_HOME/moodledata/filedir /var/moodledata/filedir \nchmod -R 777 /var/moodledata && chmod -R 777 $MOODLE_HOME/moodledata/filedir\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting Memcached ...\"\nmemcached -u memcache &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -e \"$SUPERVISOR_LOG_DIR/supervisord.log\" && echo \"INFO: $SUPERVISOR_LOG_DIR/supervisord.log not found. creating ...\" && touch $SUPERVISOR_LOG_DIR/supervisord.log\nchmod 777 $SUPERVISOR_LOG_DIR/supervisord.log\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 207}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /    \n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_moodle(){\n    while test -d \"$MOODLE_HOME/moodle\"\n    do\n        echo \"INFO: $MOODLE_HOME/moodle is exist, clean it ...\"\n        # mv is faster than rm.    \n        mv $MOODLE_HOME/moodle /home/bak/moodle$(date +%s)\n    done\n\ttest ! -d \"$MOODLE_HOME\" && echo \"INFO: $MOODLE_HOME not found. creating ...\" && mkdir -p \"$MOODLE_HOME\"\n\tcd $MOODLE_HOME\n    GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/moodle-linuxappservice-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-master}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\n    git clone $GIT_REPO $MOODLE_HOME/moodle\t&& cd $MOODLE_HOME/moodle\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\n    cp -rf $MOODLE_SOURCE/installlib.php $MOODLE_HOME/moodle/lib/installlib.php    \n    chmod -R 777 $MOODLE_HOME\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$MOODLE_HOME  \n        chown -R www-data:www-data $MOODLE_HOME\n    fi    \n}\n\nupdate_db_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD    \n}\n\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"    \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    update_db_config\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin    \nfi\n\n# setup Moodle\n# That config.php doesn't exist means moodle is not installed/configured yet.\nif [ ! -e \"$MOODLE_HOME/moodle/config.php\" ]; then    \n\techo \"INFO: $MOODLE_HOME/moodle/config.php not found.\"\n\techo \"Installing Moodle for the first time ...\" \n\tsetup_moodle\t\n\n\tif [ ${DATABASE_HOST} ]; then\n        echo \"INFO: DB Parameters are setted, Update config.php...\"\n        \n        cd $MOODLE_HOME/moodle && cp $MOODLE_SOURCE/config.php . \n        chmod 777 config.php\n\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data config.php\n        fi\n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n            #$CFG->dbtype    = 'mariadb';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mariadb'/g\" config.php\n        else\n            #$CFG->dbtype    = 'mysqli';\n            sed -i \"s/getenv('DATABASE_TYPE')/'mysqli'/g\" config.php\n        fi        \n    else \n        echo \"INFO: DATABASE_HOST isn't exist, please fill parameters during installation!\"\t\t\t        \n\tfi\nelse\n\techo \"INFO: $MOODLE_HOME/moodle/config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"    \nfi\t\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nchown www-data:www-data /run/php/php-fpm.sock\nchmod 777 /run/php/php-fpm.sock\n\n# Set Cache path of moodle\nmkdir -p $MOODLE_HOME/moodledata/filedir && mkdir -p /var/moodledata \nln -s $MOODLE_HOME/moodledata/filedir /var/moodledata/filedir \nchmod -R 777 /var/moodledata && chmod -R 777 $MOODLE_HOME/moodledata/filedir\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting Memcached ...\"\nmemcached -u memcache &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -e \"$SUPERVISOR_LOG_DIR/supervisord.log\" && echo \"INFO: $SUPERVISOR_LOG_DIR/supervisord.log not found. creating ...\" && touch $SUPERVISOR_LOG_DIR/supervisord.log\nchmod 777 $SUPERVISOR_LOG_DIR/supervisord.log\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 207}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nphp -v\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\nsed -i \"s|error_log /var/log/nginx/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\n# setup server root\nmkdir -p \"$HOME_SITE\"\nchown -R www-data:www-data \"$HOME_SITE/\"\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\nrm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\n\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\n/usr/sbin/nginx\n\n\n", "num_lines": 34}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpMyAdmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p \"$HOME_SITE\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi        \necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx\n\n\n", "num_lines": 107}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R --no-clobber /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p \"$HOME_SITE\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi        \necho \"Starting SSH ...\"\nservice ssh start\n\necho \"Starting php-fpm ...\"\nservice php7.0-fpm start\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx\n\n\n", "num_lines": 110}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p \"$HOME_SITE\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\n#service php7.0-fpm start\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n#/usr/sbin/nginx\n\n\n", "num_lines": 117}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-default.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p \"$HOME_SITE\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi        \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n", "num_lines": 111}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\nfi        \n\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\nif [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n    touch $NGINX_LOG_DIR/php-error.log;    \nfi\nchmod 666 $NGINX_LOG_DIR/php-error.log;\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Start crond\"\ncrond\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\n\necho \"Starting SSH ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 137}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test ! -e $NGINX_LOG_DIR/error.log; then \n    touch $NGINX_LOG_DIR/error.log\nfi\nchmod 666 $NGINX_LOG_DIR/error.log\n/usr/sbin/nginx -g \"daemon off;\"", "num_lines": 5}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\nfi        \n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 134}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo \n    if [ -e /run/php/php7.0-fpm.sock ]; then\n        echo \"exist...chmod... \"\n        chmod 777 /run/php/php7.0-fpm.sock                      \n    else            \n        echo \"INFO: It's not ready...\"                        \n    fi\n    if test ! -e $NGINX_LOG_DIR/access.log; then \n        touch $NGINX_LOG_DIR/access.log\n    fi\n    if test ! -e $NGINX_LOG_DIR/error.log; then \n        touch $NGINX_LOG_DIR/error.log\n    fi\n    if [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n        touch $NGINX_LOG_DIR/php-error.log;    \n    fi    \n    chmod 666 $NGINX_LOG_DIR/access.log\n    chmod 666 $NGINX_LOG_DIR/error.log\n    chmod 666 $NGINX_LOG_DIR/php-error.log;\n    test ! -d \"/home/LogFiles/olddir\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"/home/LogFiles/olddir\"\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for $NGINX_LOG_DIR\"  \n        chown -R nginx:nginx $NGINX_LOG_DIR\n        chown -R nginx:nginx /home/LogFiles/olddir \n    fi\n    sleep 3s\ndone \n", "num_lines": 31}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nps -ef | grep logrotate | grep -v grep\nprocess=`ps -ef | grep logrotate | grep -v grep | wc -l`\necho $process\nif [ $process -eq 0 ]; then \n    logrotate /etc/logrotate.conf\nfi\n", "num_lines": 8}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n\tcp -R phpmyadmin-nginx.conf /etc/nginx/nginx.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p \"$HOME_SITE\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\nfi        \necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\n#service php7.0-fpm start\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n#/usr/sbin/nginx\n\n\n", "num_lines": 115}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php-fpm.sock \nfi \nchmod 777 /run/php/php-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\nfi        \n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 134}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo \n    if [ -e /run/php/php-fpm.sock ]; then\n        echo \"exist...chmod... \"\n        chmod 777 /run/php/php-fpm.sock                      \n    else            \n        echo \"INFO: It's not ready...\"                        \n    fi\n    if test ! -e $NGINX_LOG_DIR/access.log; then \n        touch $NGINX_LOG_DIR/access.log\n    fi\n    if test ! -e $NGINX_LOG_DIR/error.log; then \n        touch $NGINX_LOG_DIR/error.log\n    fi\n    if [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n        touch $NGINX_LOG_DIR/php-error.log;    \n    fi\n    if [ ! -e \"$SUPERVISOR_LOG_DIR/supervisord.log\" ]; then    \n        touch $SUPERVISOR_LOG_DIR/supervisord.log;    \n    fi\n    chmod 666 $NGINX_LOG_DIR/access.log\n    chmod 666 $NGINX_LOG_DIR/error.log\n    chmod 666 $NGINX_LOG_DIR/php-error.log\n    chmod 666 $SUPERVISOR_LOG_DIR/supervisord.log\n    test ! -d \"/home/LogFiles/olddir\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"/home/LogFiles/olddir\"\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for $NGINX_LOG_DIR\"  \n        chown -R nginx:nginx $NGINX_LOG_DIR\n        chown -R nginx:nginx /home/LogFiles/olddir \n    fi\n    sleep 3s\ndone \n", "num_lines": 35}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nps -ef | grep logrotate | grep -v grep\nprocess=`ps -ef | grep logrotate | grep -v grep | wc -l`\necho $process\nif [ $process -eq 0 ]; then \n    logrotate /etc/logrotate.conf\nfi\n", "num_lines": 8}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # if test ! -e /run/mysqld/mysqld.sock; then \n    #     touch /run/mysqld/mysqld.sock\n    # fi\n    # chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n    }\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php-fpm.sock \nfi \nchmod 777 /run/php/php-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\nfi        \n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 134}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo \n    if [ -e /run/php/php-fpm.sock ]; then\n        echo \"exist...chmod... \"\n        chmod 777 /run/php/php-fpm.sock                      \n    else            \n        echo \"INFO: It's not ready...\"                        \n    fi\n    if test ! -e $NGINX_LOG_DIR/access.log; then \n        touch $NGINX_LOG_DIR/access.log\n    fi\n    if test ! -e $NGINX_LOG_DIR/error.log; then \n        touch $NGINX_LOG_DIR/error.log\n    fi\n    if [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n        touch $NGINX_LOG_DIR/php-error.log;    \n    fi\n    if [ ! -e \"$SUPERVISOR_LOG_DIR/supervisord.log\" ]; then    \n        touch $SUPERVISOR_LOG_DIR/supervisord.log;    \n    fi\n    chmod 666 $NGINX_LOG_DIR/access.log\n    chmod 666 $NGINX_LOG_DIR/error.log\n    chmod 666 $NGINX_LOG_DIR/php-error.log\n    chmod 666 $SUPERVISOR_LOG_DIR/supervisord.log\n    test ! -d \"/home/LogFiles/olddir\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"/home/LogFiles/olddir\"\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for $NGINX_LOG_DIR\"  \n        chown -R nginx:nginx $NGINX_LOG_DIR\n        chown -R nginx:nginx /home/LogFiles/olddir \n    fi\n    sleep 3s\ndone \n", "num_lines": 35}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nps -ef | grep logrotate | grep -v grep\nprocess=`ps -ef | grep logrotate | grep -v grep | wc -l`\necho $process\nif [ $process -eq 0 ]; then \n    logrotate /etc/logrotate.conf\nfi\n", "num_lines": 8}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php-fpm.sock \nfi \nchmod 777 /run/php/php-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\n\necho \"Starting Redis ...\"\nredis-server &\n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# take customer's nginx config files\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 136}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # if test ! -e /run/mysqld/mysqld.sock; then \n    #     touch /run/mysqld/mysqld.sock\n    # fi\n    # chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n    }\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n\tfi\n}\n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi \n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\n# setup nginx log dir\n# http://nginx.org/en/docs/ngx_core_module.html#error_log\n# sed -i \"s|error_log /var/log/error.log;|error_log stderr;|g\" /etc/nginx/nginx.conf\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php-fpm.sock \nfi \nchmod 777 /run/php/php-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo \"Starting MariaDB and PHPMYADMIN...\"\n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    echo \"phpmyadmin username: \"$DATABASE_USERNAME    \n    echo \"phpmyadmin password: \"$DATABASE_PASSWORD    \n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\nfi        \n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 134}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo \n    if [ -e /run/php/php-fpm.sock ]; then\n        #echo \"exist...chmod... \"\n        chmod 777 /run/php/php-fpm.sock                      \n    else            \n        echo \"INFO: It's not ready...\"                        \n    fi\n    if test ! -e $NGINX_LOG_DIR/access.log; then \n        touch $NGINX_LOG_DIR/access.log\n    fi\n    if test ! -e $NGINX_LOG_DIR/error.log; then \n        touch $NGINX_LOG_DIR/error.log\n    fi\n    if [ ! -e \"$NGINX_LOG_DIR/php-error.log\" ]; then    \n        touch $NGINX_LOG_DIR/php-error.log;    \n    fi\n    if [ ! -e \"$SUPERVISOR_LOG_DIR/supervisord.log\" ]; then    \n        touch $SUPERVISOR_LOG_DIR/supervisord.log;    \n    fi\n    chmod 666 $NGINX_LOG_DIR/access.log\n    chmod 666 $NGINX_LOG_DIR/error.log\n    chmod 666 $NGINX_LOG_DIR/php-error.log\n    chmod 666 $SUPERVISOR_LOG_DIR/supervisord.log\n    test ! -d \"/home/LogFiles/olddir\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"/home/LogFiles/olddir\"\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for $NGINX_LOG_DIR\"  \n        chown -R nginx:nginx $NGINX_LOG_DIR\n        chown -R nginx:nginx /home/LogFiles/olddir \n    fi\n    sleep 3s\ndone \n", "num_lines": 35}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nps -ef | grep logrotate | grep -v grep\nprocess=`ps -ef | grep logrotate | grep -v grep | wc -l`\necho $process\nif [ $process -eq 0 ]; then \n    logrotate /etc/logrotate.conf\nfi\n", "num_lines": 8}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\n# setup server root\ntest ! -d \"$HOME_SITE\" && echo \"INFO: $HOME_SITE not found. creating...\" && mkdir -p $HOME_SITE\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for \"$HOME_SITE  \n    chown -R www-data:www-data $HOME_SITE \nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php-fpm.sock \nfi \nchmod 777 /run/php/php-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\n\necho \"Starting Redis ...\"\nredis-server &\n\n# log rotate will hung with web app, only start it with other environments.\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# take customer's nginx config files\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 136}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /var/www/html\ntry_count=1\n\nwhile [ $try_count -le 20  ]\ndo \n    if [ -e index.php -a -e wp-includes/version.php  ]; then \n        echo \"INFORMATION - Wordpress is ready ...\"              \n        break\n    else\n        sleep 10s\n        let try_count+=1        \n    fi\ndone\n\necho \"Starting nginx ...\"\nexec \"$@\"\n\n", "num_lines": 20}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\necho \"========================================\" |  tee -a result.log\necho \"INFORMATION - AquaSec Scanner-cli......\" | tee -a result.log\n\nif [ $DOCKER_ACCOUNT == $PROD_DOCKER_ACCOUNT ]; then #It's master branch\n    echo \"This is Master Branch, SKIP this process......\" | tee -a result.log\n    echo \"========================================\" | tee -a result.log\n    exit 0\nfi\n\necho \"DOCKER_IMAGE_NAME: ${DOCKER_IMAGE_NAME}\"\n\nAQUASEC_CONTAINRE=\"${DOCKER_ACCOUNT}\"/scanner-cli:3.0\n\ndocker run -v /var/run/docker.sock:/var/run/docker.sock ${AQUASEC_CONTAINRE} scan \\\n    -H ${AQUASEC_SITE} -U ${AQUASEC_USER} -P ${AQUASEC_PASSWORD} \\\n    --local ${DOCKER_IMAGE_NAME} \\\n    --register --registry local_scanner \\\n    > scan_log.json\necho \"========================================\"\n#cat scan_log.json\n\ntestResult=$(jq '.image_assurance_results | .disallowed' scan_log.json)\n#echo \"testResult? \"${testResult}\nif [ ! -z \"$testResult\" ]; then    \n    echo \"FAILED - High vulnerablilites are found!!!\" | tee -a result.log\n    echo $(jq '.image_assurance_results' scan_log.json) | tee -a result.log\nelse\n    echo \"PASSED - No high vulnerability is found !\" | tee -a result.log\nfi\n\necho \"INFO - Get scan result......\"\ncurl -u ${AQUASEC_USER}:${AQUASEC_PASSWORD}  \\\n       ${AQUASEC_SITE}/api/v1/scanner/registry/local_scanner/image/${DOCKER_IMAGE_NAME}:latest/scan_result > scan_result.json\njq . scan_result.json | tee -a result.log\necho \"\"\n\nexit 0\n\n\n", "num_lines": 48}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\nbuild_image(){  \n    _do cd ${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION}\n    _do docker build -t \"${DOCKER_IMAGE_NAME}\" .\n    _do cd $TRAVIS_BUILD_DIR    \n    testBuildImage=$(docker images | grep \"${DOCKER_IMAGE_NAME}\")\n    if [ -z \"${testBuildImage}\" ]; then \n        echo \"FAILED - Build fail!!!\"\n        exit 1\n    else\n        echo \"${testBuildImage}\" | tee -a result.log\n        echo \"PASSED - Build Successfully!!!.\" | tee -a result.log\n    fi\n    _do cd ..\n    _do cd ..\n}\n\nbuild_image\n", "num_lines": 27}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\ntest_Dockerfile(){\n    _do docker inspect ${DOCKER_IMAGE_NAME} > inspect.json\n    echo \"INFORMATION: Details of \"${DOCKER_IMAGE_NAME}\":\"\n    cat inspect.json\n\n    # Check SSH Ports\n    # Only 2 ports allowed where one is always 2222\n    testPORTS=$(jq .[].Config.ExposedPorts inspect.json | grep -o \":\" | wc -w)\n    if [ ${testPORTS} -gt 2 ]; then\n        echo \"${testPORTS}\" \n        echo \"WARNING - Too many ports are exposed!!!\"\n        echo \"WARNING - Too many ports are exposed!!!\" | tee -a result.log\n        #exit 1\n    fi\n\n    testSSH=$(jq .[].Config.ExposedPorts inspect.json | grep 2222)\n    if [ -z \"${testSSH}\" ]; then \n        echo \"FAILED - PORT 2222 isn't opened, SSH isn't working!!!\"\n        exit 1\n    else\n        echo \"${testSSH}\"\n        echo \"PASSED - PROT 2222 is opened.\"\n    fi \n\n    # Check Volume\n    testVOLUME=$(jq .[].Config.Volumes inspect.json | grep null)\n    if [ -z \"${testVOLUME}\" ]; then \n        testVOLUME=$(jq .[].Config.Volumes inspect.json)\n        echo \"${testVOLUME}\"\n        echo \"FAILED - These VOLUME lines should not be existed!!!\"\n        exit 1\n    else\n        echo \"PASSED - Great, there is no VOLUME lines.\"            \n    fi\n\n    # Check User\n    testUSER=$(jq .[].Config.User inspect.json)\n    if test \"${testUSER}\" != '\"\"' ; then        \n        echo \"${testUSER}\"\n        echo \"FAILED - These USER lines should not be existed!!!\"\n        exit 1\n    else\n        echo \"PASSED - Great, there is no USER lines.\"            \n    fi\n}\n\necho \"Docker: \"${DOCKER_IMAGE_NAME}\"/\"${DOCKER_IMAGE_VERSION} | tee -a result.log\ntest_Dockerfile\necho \"PASSED - Passed this stage.\" | tee -a result.log\n\n\n\n\n", "num_lines": 63}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "DOCKER_IMAGE_NAME=$1\nDOCKER_IMAGE_VERSION=$2\n\n# If script run to error, exist -1;\nfunction _do() \n{\n        \"$@\" || { echo \"exec failed: \"\"$@\"; exit -1; }\n}\n\nsetTag_push_rm(){\n    echo \"TAG: ${TAG}\"\n    _do docker tag \"${DOCKER_IMAGE_NAME}\" \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    testBuildImage=$(docker images | grep \"$TAG\")\n    if [ -z \"${testBuildImage}\" ]; then \n        echo \"FAILED - Set TAG Failed!!!\"\n        exit 1\n    else\n        echo \"${testBuildImage}\" | tee -a result.log\n        echo \"PASSED - Set TAG Successfully!.\" | tee -a result.log\n    fi\n    _do docker push \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    echo \"PASSED - Pushed  ${DOCKER_ACCOUNT}/${DOCKER_IMAGE_NAME}:${TAG} Successfully!.\" | tee -a result.log\n    echo \"INFORMATION: Before rmi - docker images\"\n    _do docker images\n    echo \"INFORMATION - RM \"\"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    _do docker rmi \"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\n    echo \"INFORMATION - After rmi - docker images\"\n    _do docker images\n}\n\necho \"Stage1 - Set Tag and Push\" | tee -a result.log\necho \"Build Number: ${TRAVIS_BUILD_NUMBER}\"\necho \"TRAVIS_EVENT_TYPE: ${TRAVIS_EVENT_TYPE}\"\necho \"TRAVIS_COMMIT_MESSAGE: ${TRAVIS_COMMIT_MESSAGE}\"\n\nisSignOff=\"false\"\nSignOff=\"#sign-off\"        \nsignOff=$(echo \"${TRAVIS_COMMIT_MESSAGE}\" | grep \"${SignOff}\")\nif [ -n \"${signOff}\" ]; then #contains \"#Sign-off\"\n    isSignOff=\"true\"\nfi\nif [ $DOCKER_ACCOUNT == $PROD_DOCKER_ACCOUNT ]; then #It's master branch\n    echo \"INFORMATION - This time, push to PROD docker hub.....\"\n    isSignOff=\"true\"\n    _do echo \"${DOCKER_PASSWORD}\" | _do docker login -u=\"${DOCKER_USERNAME}\" --password-stdin\nelse\n    echo \"INFORMATION - This time push to TEST docker hub......\"\n    _do echo \"${DOCKER_PASSWORD}\" | _do docker login \"${DOCKER_ACCOUNT}\" -u=\"${DOCKER_USERNAME}\" --password-stdin\nfi\n\nif [ $isSignOff == \"true\" ]; then\n    echo \"INFORMATION - This time, set tag as \"${DOCKER_IMAGE_VERSION}\" and push.....\"    \n    TAG=${DOCKER_IMAGE_VERSION}       \nelse\n    echo \"INFORMATION - This time, set tag as \"${DOCKER_IMAGE_VERSION}\"-\"${TRAVIS_BUILD_NUMBER}\" and push.....\"    \n    TAG=${DOCKER_IMAGE_VERSION}\"-\"${TRAVIS_BUILD_NUMBER}        \nfi\necho \"INFORMATION - Set TAG as \"\"${TAG}\"\" and push......\" \nsetTag_push_rm\n\necho \"========================================\"\necho \"Stage2 - PULL and Verify\"\necho \"INFORMATION - Start to Pull \"\"${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\"\necho \"INFORMATION - Before Pull - docker images\"\n_do docker images\n_do docker run -d -p 80:80 --name testdocker $DOCKER_ACCOUNT/${DOCKER_IMAGE_NAME}:\"$TAG\"\necho \"INFORMATION: After Pull - docker images\"\n_do docker images\ntestBuildImage=$(docker images | grep \"${TAG}\")\n    if [ -z \"$testBuildImage\" ]; then \n        echo \"FAILED - Docker pull and run Failed!!!\"\n        docker images\n        exit 1\n    else\n        echo \"$testBuildImage\"\n        echo \"$testBuildImage\" >> result.log\n        echo \"PASSED - Docker image pull and run Successfully!. You can manually verify it!\" | tee -a result.log\n    fi\n_do docker stop testdocker\n_do docker rm testdocker\n_do docker rmi ${DOCKER_ACCOUNT}\"/\"${DOCKER_IMAGE_NAME}\":\"${TAG}\n\n# Deal With latest version\nif [ $isSignOff == \"true\" ]; then #Is it \"#sign-off\" or \"master_brnach\"?\n    _do cd ${DOCKER_IMAGE_NAME}\n    if test -e latest.txt; then\n        LATEST_VERSION=$(cat latest.txt)\n        _do cd ..\n        echo \"LATEST_VERSION:\"$LATEST_VERSION\n        if [ $DOCKER_IMAGE_VERSION == $LATEST_VERSION ]; then             \n            echo \"INFORMATION - This time, also need to push as latest version......\" | tee -a result.log    \n            TAG=\"latest\"\n            echo \"INFORMATION - Set TAG as \"\"${TAG}\"\" and push......\" \n            setTag_push_rm        \n        fi\n    else\n        _do cd ..\n    fi    \nfi\n", "num_lines": 100}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Check SSH is opened\n\necho \"INFORMATION - Blow service are running...\"\ndocker top testdocker\ntestSSHEnable=$(docker top testdocker | grep sshd)\ntry_ssh_count=1\n\nwhile [ $try_ssh_count -le 10 ]\ndo \n    if [ -z \"${testSSHEnable}\" ]; then \n        echo \"INFORMATION - Haven't found SSH Service this time, Wait 10s, try again...\"\n        sleep 10s\n        let try_ssh_count+=1\n        echo \"INFORMATION - Blow service are running...\"\n        docker top testdocker\n        testSSHEnable=$(docker top testdocker | grep sshd)        \n    else\n        echo \"${testSSHEnable}\"\n        echo \"PASSED - SSH Service is running...\" | tee -a result.log\n        break\n    fi\ndone\n\nif [ -z \"${testSSHEnable}\" ]; then\n    echo \"FAILED - Tried 10 times, still hasn't found SSH service!!!\"\n    exit -1\nfi\n\n\n", "num_lines": 30}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    chown -R www-data:www-data $PHPMYADMIN_HOME\n}\n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\n\tcd $WORDPRESS_SOURCE\n\ttar -xf wp.tar.gz -C $WORDPRESS_HOME/ --strip-components=1\n\t\n\tchown -R www-data:www-data $WORDPRESS_HOME\n    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nchown -R www-data:www-data $APP_HOME\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nchown -R www-data:www-data $HTTPD_LOG_DIR\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\n\t\n        cd $WORDPRESS_HOME \n\t\tcp $WORDPRESS_SOURCE/wp-config.php . && chmod 777 wp-config.php && chown -R www-data:www-data wp-config.php\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\ncd $WORDPRESS_HOME \nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting Apache httpd -D FOREGROUND ...\"\napachectl start -D FOREGROUND\n", "num_lines": 164}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    chown -R www-data:www-data $PHPMYADMIN_HOME\n}\n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\n\tcd $WORDPRESS_SOURCE\n\ttar -xf wp.tar.gz -C $WORDPRESS_HOME/ --strip-components=1\n\t\n\tchown -R www-data:www-data $WORDPRESS_HOME\n    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\n\t\n        cd $WORDPRESS_HOME \n\t\tcp $WORDPRESS_SOURCE/wp-config.php . && chmod 777 wp-config.php && chown -R www-data:www-data wp-config.php\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\ncd $WORDPRESS_HOME \nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting Apache httpd -D FOREGROUND ...\"\napachectl start -D FOREGROUND\n", "num_lines": 170}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}\n    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $WORDPRESS_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 190}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}\n    \nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $WORDPRESS_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Creating Varnish folders ...\"\nmkdir -p /var/lib/varnish/localhost && chown nobody /var/lib/varnish/localhost\nmkdir -p /var/lib/varnish/$(hostname) && chown nobody /var/lib/varnish/$(hostname)\n\necho \"Getting Host IP for Varnish ...\"\nexport HOST_IP=$(hostname -i)\n\n# start-varnish.sh\n# Varnish and Apache both listen to port 80. Apache listens to 127.0.0.1:80 and Varnish to HOST_IP:80 in order to not be in conflict.\n# The startup script curls 127.0.0.1:80 each second until Apache is up and running and is able to respond to HTTP requests.\n# This step is necessary in order for an App Service to not swap containers before Apache is actually ready.\n# Starting Varnish too early would cause that.\n\necho \"Running start-varnish.sh async and waiting for apache to be ready before starting Apache...\"\nstart-varnish.sh &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 198}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "RESPONSE_CODE=\"\"\nprintf 'Waiting for Apache\\n'\nwhile [ -z \"$RESPONSE_CODE\" ]\ndo\n    RESPONSE_CODE=$(curl -s -I http://127.0.0.1 | grep HTTP | awk {'print $2'})\n    sleep 2\ndone\nprintf 'Apache ready. Starting Varnish\\n'\n/usr/sbin/varnishd -s malloc,${VARNISH_CACHE_SIZE} -a ${HOST_IP}:${VARNISH_PORT} -b ${VARNISH_BACKEND_ADDRESS}:${VARNISH_BACKEND_PORT}\n", "num_lines": 10}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}\n    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $WORDPRESS_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 191}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t\n        # The wp-config.php is designed for default GIT/BRANCH, remove it if need.\n        if [ \"${DATABASE_TYPE}\" != \"local\" -a \"${GIT_REPO}\" == \"https://github.com/azureappserviceoss/wordpress-azure\" -a \"${GIT_BRANCH}\" == \"linux-appservice\" ];then\n           rm wp-config.php\n        fi\n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 197}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 193}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\n# setup server root\ntest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating...\" && mkdir -p \"$WORDPRESS_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R www-data:www-data $WORDPRESS_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n", "num_lines": 192}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\n# setup server root\ntest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating...\" && mkdir -p \"$WORDPRESS_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R www-data:www-data $WORDPRESS_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\n\necho \"Starting Redis ...\"\nredis-server &\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting php-fpm ...\"\nphp-fpm -D\nchmod 777 /run/php/php7.0-fpm.sock\n\necho \"Starting Nginx ...\"\nmkdir -p /home/LogFiles/nginx\nif test ! -e /home/LogFiles/nginx/error.log; then \n    touch /home/LogFiles/nginx/error.log\nfi\n/usr/sbin/nginx -g \"daemon off;\"\n\n", "num_lines": 192}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_localdb_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD   \n}\n\nshow_wordpress_db_config(){\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"INFO: WORDPRESS_ENVS:\"\n    echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n    echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n    echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n    echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n}\n\n# setup server root\ntest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating...\" && mkdir -p \"$WORDPRESS_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R www-data:www-data $WORDPRESS_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"INFO: NOT in Azure, chown for /run/php/php7.0-fpm.sock\"  \n    chown -R www-data:www-data /run/php/php7.0-fpm.sock \nfi \nchmod 777 /run/php/php7.0-fpm.sock\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"    \n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\n    chmod 777 $WORDPRESS_SOURCE/wp-config.php\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n       echo \"INFO: NOT in Azure, chown for wp-config.php\"\n       chown -R www-data:www-data $WORDPRESS_SOURCE/wp-config.php\n    fi\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_localdb_config\n        show_wordpress_db_config\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\n        cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/\n\telse\n        if [ $DATABASE_HOST ]; then\n            echo \"INFO: External Mysql is used.\"                \n            show_wordpress_db_config\n      \t    cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/\n        fi\n\tfi   \nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 215}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then \n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    cp -R phpmyadmin-default.conf /etc/nginx/conf.d/default.conf\n\tcd /\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_localdb_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD   \n}\n\nshow_wordpress_db_config(){\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"INFO: WORDPRESS_ENVS:\"\n    echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n    echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n    echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n    echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n}\n\n# setup server root\ntest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating...\" && mkdir -p \"$WORDPRESS_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R www-data:www-data $WORDPRESS_HOME\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n    echo \"INFO: local MariaDB is used.\"\n    update_localdb_config\n    show_wordpress_db_config\n    echo \"Creating database for WordPress if not exists ...\"\n\tmysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\techo \"Granting user for WordPress ...\"\n\tmysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"        \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"    \n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\n    chmod 777 $WORDPRESS_SOURCE/wp-config.php\n\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n       echo \"INFO: NOT in Azure, chown for wp-config.php\"\n       chown -R www-data:www-data $WORDPRESS_SOURCE/wp-config.php\n    fi    \n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then        \n        cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/\n\telse\n        if [ $DATABASE_HOST ]; then\n            echo \"INFO: External Mysql is used.\"                \n            show_wordpress_db_config\n            cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/\n        fi        \n\tfi   \nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n    echo \"NOT in AZURE, Start crond, log rotate...\"\n    crond\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\n# Set php-fpm listen type\n# By default, It's socket.\n# LISTEN_TYPE==port, It's port.\nLISTEN_TYPE=${LISTEN_TYPE:-socket}\nLISTEN_TYPE=$(echo ${LISTEN_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${LISTEN_TYPE}\" == \"socket\" ]; then  \n    echo \"INFO: creating /run/php/php7.0-fpm.sock ...\"\n    test -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\n    mkdir -p /run/php\n    touch /run/php/php7.0-fpm.sock\n    chown www-data:www-data /run/php/php7.0-fpm.sock\n    chmod 777 /run/php/php7.0-fpm.sock\nelse\n    echo \"INFO: PHP-FPM listener is 127.0.0.1:9000 ...\"    \n    #/etc/nginx/conf.d/default.conf\n    sed -i \"s/unix:\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /etc/nginx/conf.d/default.conf\n    #/usr/local/etc/php/conf.d/www.conf\n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/127.0.0.1:9000/g\" /usr/local/etc/php/conf.d/www.conf\n    #/usr/local/etc/php-fpm.d/zz-docker.conf \n    sed -i \"s/\\/var\\/run\\/php\\/php7.0-fpm.sock/9000/g\" /usr/local/etc/php-fpm.d/zz-docker.conf \nfi\n\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 227}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nAZURE_DETECTED=$WEBSITES_ENABLE_APP_SERVICE_STORAGE # if defined, assume the container is running on Azure\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then\n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    # rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $AZURE_DETECTED ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\tif ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        while [ -d $WORDPRESS_HOME ]\n        do\n            mkdir -p /home/bak\n            mv $WORDPRESS_HOME /home/bak/wordpress_bak$(date +%s)            \n        done\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t&& cd $WORDPRESS_HOME\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\n\n        chmod 777 $WORDPRESS_SOURCE/wp-config.php\n        if [ ! $AZURE_DETECTED ]; then \n            echo \"INFO: NOT in Azure, chown for wp-config.php\"\n            chown -R www-data:www-data $WORDPRESS_SOURCE/wp-config.php\n        fi\n\n        #IF App settings of DB are exist, Use Special wp-config file.    \n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then        \n            cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php       \n        else\n            if [ $DATABASE_HOST ]; then\n                echo \"INFO: External Mysql is used.\"                \n                # show_wordpress_db_config\n                cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php            \n            fi        \n        fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME\n}\n\nupdate_localdb_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}    \n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD   \n}\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n    echo \"INFO: local MariaDB is used.\"\n    update_localdb_config\n    # show_wordpress_db_config\n    echo \"Creating database for WordPress if not exists ...\"\n\tmysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\techo \"Granting user for WordPress ...\"\n\tmysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"        \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"    \n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\nfi\n\nif [  -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n    echo \"INFO: Check SSL Setting...\"    \n    SSL_DETECTED=$(grep \"\\$_SERVER\\['HTTPS'\\] = 'on';\" $WORDPRESS_HOME/wp-config.php)\n    if [ ! SSL_DETECTED ];then\n        echo \"INFO: Add SSL Setting...\"\n        sed -i \"/stop editing!/r $WORDPRESS_SOURCE/ssl-settings.txt\" $WORDPRESS_HOME/wp-config.php        \n    else        \n        echo \"INFO: SSL Setting is exist!\"\n    fi\nfi\n\n# set permalink as 'Day and Name' and default, it has best performance with nginx re_write config.\n# PERMALINK_DETECTED=$(grep \"\\$wp_rewrite->set_permalink_structure\" $WORDPRESS_HOME/wp-settings.php)\n# if [ ! $PERMALINK_DETECTED ];then\n#     echo \"INFO: Set Permalink...\"\n#     init_string=\"do_action( 'init' );\"\n#     sed -i \"/$init_string/r $WORDPRESS_SOURCE/permalink-settings.txt\" $WORDPRESS_HOME/wp-settings.php\n#     init_row=$(grep \"$init_string\" -n $WORDPRESS_HOME/wp-settings.php | head -n 1 | cut -d \":\" -f1)\n#     sed -i \"${init_row}d\" $WORDPRESS_HOME/wp-settings.php\n# else\n#     echo \"INFO: Permalink setting is exist!\"\n# fi\n\n# setup server root\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R www-data:www-data $WORDPRESS_HOME\nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\nif [ ! $AZURE_DETECTED ]; then\t\n    echo \"NOT in AZURE, Start crond, log rotate...\"\t\n    crond\t\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\ntest -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\ntest ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\n#Just In Case, use external DB before, change to Local DB this time.\nif [ \"$DATABASE_TYPE\" == \"local\" ]; then\n    PHPMYADMIN_SETTINGS_DETECTED=$(grep 'location /phpmyadmin' /etc/nginx/conf.d/default.conf )    \n    if [ ! \"$PHPMYADMIN_SETTINGS_DETECTED\" ]; then\n        sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n    fi\nfi\n\necho \"INFO: creating /run/php/php7.0-fpm.sock ...\"\ntest -e /run/php/php7.0-fpm.sock && rm -f /run/php/php7.0-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php7.0-fpm.sock\nchown www-data:www-data /run/php/php7.0-fpm.sock\nchmod 777 /run/php/php7.0-fpm.sock\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 233}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nAZURE_DETECTED=$WEBSITES_ENABLE_APP_SERVICE_STORAGE # if defined, assume the container is running on Azure\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then\n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    # rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $AZURE_DETECTED ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R nginx:nginx $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\tif ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        while [ -d $WORDPRESS_HOME ]\n        do\n            mkdir -p /home/bak\n            mv $WORDPRESS_HOME /home/bak/wordpress_bak$(date +%s)            \n        done\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t&& cd $WORDPRESS_HOME\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi       \n        #IF App settings of DB are exist, Use Special wp-config file.    \n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then        \n            cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php        \n        else\n            if [ $DATABASE_HOST ]; then\n                echo \"INFO: External Mysql is used.\"                \n                # show_wordpress_db_config\n                cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php            \n            fi        \n        fi        \t\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R nginx:nginx $WORDPRESS_HOME    \n}\n\nupdate_localdb_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}    \n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD    \n}\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"INFO: local MariaDB is used.\"\n    update_localdb_config\n    # show_wordpress_db_config\n    echo \"Creating database for WordPress if not exists ...\"\n    chown -R mysql:mysql $MARIADB_DATA_DIR && mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\techo \"Granting user for WordPress ...\"\n\tmysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"        \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"    \n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\nfi\n\nchmod 777 $WORDPRESS_SOURCE/wp-config.php\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for wp-config.php\"\n    chown -R nginx:nginx $WORDPRESS_SOURCE/wp-config.php\nfi\n\nif [  -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n    echo \"INFO: Check SSL Setting...\"    \n    SSL_DETECTED=$(grep \"\\$_SERVER\\['HTTPS'\\] = 'on';\" $WORDPRESS_HOME/wp-config.php)\n    if [ ! SSL_DETECTED ];then\n        echo \"INFO: Add SSL Setting...\"\n        sed -i \"/stop editing!/r $WORDPRESS_SOURCE/ssl-settings.txt\" $WORDPRESS_HOME/wp-config.php        \n    else        \n        echo \"INFO: SSL Setting is exist!\"\n    fi\nfi\n\n# setup server root\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R nginx:nginx $WORDPRESS_HOME\nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\nif [ ! $AZURE_DETECTED ]; then\t\n    echo \"NOT in AZURE, Start crond, log rotate...\"\t\n    crond\t\nfi \n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for nginx/php not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# test -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\n# test ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\nif [ ! -d \"/home/etc/nginx\" ]; then\n    mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx\nelse\n    mv /etc/nginx /etc/nginx-bak\n    # Is it upgrade from 0.72? \n    sed -i \"s/php7.0-fpm.sock/php-fpm.sock/g\" /home/etc/nginx/conf.d/default.conf\nfi\nln -s /home/etc/nginx /etc/nginx\n\n#Just In Case, use external DB before, change to Local DB this time.\nif [ \"$DATABASE_TYPE\" == \"local\" ]; then\n    PHPMYADMIN_SETTINGS_DETECTED=$(grep 'location /phpmyadmin' /etc/nginx/conf.d/default.conf )    \n    if [ ! \"$PHPMYADMIN_SETTINGS_DETECTED\" ]; then\n        sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n    fi\nfi\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nchown nginx:nginx /run/php/php-fpm.sock\nchmod 777 /run/php/php-fpm.sock\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 226}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo\n    mkdir -p /var/log/php_fpm\n    try_count=1\n    d_php_fpm=`top -b -n 1 | grep php-fpm | grep D | wc -l`\n    if [ $d_php_fpm -ne 0 ]; then\n        # STAT D php_fpm exist.\n        # echo \"========================================\"\n        # date >> /var/log/php_fpm/watch.log\n        # top -b -n 1 | grep php_fpm >> /var/log/php_fpm/watch.log\n        while [ $try_count -le 5 ]\n        do\n            sleep 3s\n            let try_count+=1\n            d_php_fpm=`top -b -n 1 | grep php-fpm | grep D | wc -l`\n            # echo \"========================================\"\n            # date >> /var/log/php_fpm/watch.log\n            # top -b -n 1 | grep php_fpm >> /var/log/php_fpm/watch.log\n            if [ $d_php_fpm -eq 0 ]; then\n                break\n            fi\n        done\n        if [ $try_count -ge 5 ]; then\n            # echo \"========================================\"\n            # date >> /var/log/php_fpm/watch.log\n            # echo \"Start to KILL!\"\n            # # STAT D has keep for 15 secs.\n            killall -9 php-fpm\n            killall -9 nginx  \n        fi    \n    fi\n    sleep 3s\ndone", "num_lines": 35}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsleep 5\n", "num_lines": 3}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set -e\n\nphp -v\n\nAZURE_DETECTED=$WEBSITES_ENABLE_APP_SERVICE_STORAGE # if defined, assume the container is running on Azure\n\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\t    echo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\t    echo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\t    cp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\t    echo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    if test ! -e /run/mysqld/mysqld.sock; then\n        touch /run/mysqld/mysqld.sock\n    fi\n    chmod 777 /run/mysqld/mysqld.sock\n    mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql\n    /usr/bin/mysqld --user=mysql &\n    # make sure mysql service is started...\n    port=`netstat -nlt|grep 3306|wc -l`\n    process=`ps -ef |grep mysql|grep -v grep |wc -l`\n    try_count=1\n\n    while [ $try_count -le 10 ]\n    do \n        if [ $port -eq 1 ] && [ $process -eq 1 ]; then \n            echo \"INFO: MariaDB is running... \"            \n            break\n        else            \n            echo \"INFO: Haven't found MariaDB Service this time, Wait 10s, try again...\"\n            sleep 10s\n            let try_count+=1\n            port=`netstat -nlt|grep 3306|wc -l`\n            process=`ps -ef |grep mysql|grep -v grep |wc -l`    \n        fi\n    done    \n}\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpMyAdmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php    \n    sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n\tcd /\n    # rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $AZURE_DETECTED ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R nginx:nginx $PHPMYADMIN_HOME\n    fi \n}    \n\nsetup_wordpress(){\n\tif ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        while [ -d $WORDPRESS_HOME ]\n        do\n            mkdir -p /home/bak\n            mv $WORDPRESS_HOME /home/bak/wordpress_bak$(date +%s)            \n        done\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t&& cd $WORDPRESS_HOME\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi       \n        #IF App settings of DB are exist, Use Special wp-config file.    \n        if [ \"${DATABASE_TYPE}\" == \"local\" ]; then        \n            cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php        \n        else\n            if [ $DATABASE_HOST ]; then\n                echo \"INFO: External Mysql is used.\"                \n                # show_wordpress_db_config\n                cp $WORDPRESS_SOURCE/wp-config.php $WORDPRESS_HOME/ && chmod 777 $WORDPRESS_HOME/wp-config.php            \n            fi        \n        fi        \t\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R nginx:nginx $WORDPRESS_HOME    \n}\n\nupdate_localdb_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-127.0.0.1}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}    \n    export DATABASE_HOST DATABASE_NAME DATABASE_USERNAME DATABASE_PASSWORD    \n}\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    echo \"Starting MariaDB and PHPMYADMIN...\"  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"INFO: local MariaDB is used.\"\n    update_localdb_config\n    # show_wordpress_db_config\n    echo \"Creating database for WordPress if not exists ...\"\n    chown -R mysql:mysql $MARIADB_DATA_DIR && mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\techo \"Granting user for WordPress ...\"\n\tmysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"        \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"    \n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\nfi\n\nchmod 777 $WORDPRESS_SOURCE/wp-config.php\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for wp-config.php\"\n    chown -R nginx:nginx $WORDPRESS_SOURCE/wp-config.php\nfi\n\nif [  -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n    echo \"INFO: Check SSL Setting...\"    \n    SSL_DETECTED=$(grep \"\\$_SERVER\\['HTTPS'\\] = 'on';\" $WORDPRESS_HOME/wp-config.php)\n    if [ ! SSL_DETECTED ];then\n        echo \"INFO: Add SSL Setting...\"\n        sed -i \"/stop editing!/r $WORDPRESS_SOURCE/ssl-settings.txt\" $WORDPRESS_HOME/wp-config.php        \n    else        \n        echo \"INFO: SSL Setting is exist!\"\n    fi\nfi\n\n# setup server root\nif [ ! $AZURE_DETECTED ]; then \n    echo \"INFO: NOT in Azure, chown for \"$WORDPRESS_HOME \n    chown -R nginx:nginx $WORDPRESS_HOME\nfi\n\necho \"Starting Redis ...\"\nredis-server &\n\nif [ ! $AZURE_DETECTED ]; then\t\n    echo \"NOT in AZURE, Start crond, log rotate...\"\t\n    crond\t\nfi \n\n#\n# Remove symlinks to /home/LogFiles\n#\necho \"Removing symlinks to /home/LogFiles\"\nunlink /var/log/nginx\nunlink /var/log/mysql\nunlink /var/log/supervisor\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$NGINX_LOG_DIR\" && echo \"INFO: Log folder for $NGINX_LOG_DIR not found. creating...\" && mkdir -p \"$NGINX_LOG_DIR\"\ntest ! -e /home/50x.html && echo \"INFO: 50x file not found. createing...\" && cp /usr/share/nginx/html/50x.html /home/50x.html\n# test -d \"/home/etc/nginx\" && mv /etc/nginx /etc/nginx-bak && ln -s /home/etc/nginx /etc/nginx\n# test ! -d \"home/etc/nginx\" && mkdir -p /home/etc && mv /etc/nginx /home/etc/nginx && ln -s /home/etc/nginx /etc/nginx\n\n#Just In Case, use external DB before, change to Local DB this time.\nif [ \"$DATABASE_TYPE\" == \"local\" ]; then\n    PHPMYADMIN_SETTINGS_DETECTED=$(grep 'location /phpmyadmin' /etc/nginx/conf.d/default.conf )    \n    if [ ! \"$PHPMYADMIN_SETTINGS_DETECTED\" ]; then\n        sed -i \"/# Add locations of phpmyadmin here./r $PHPMYADMIN_SOURCE/phpmyadmin-locations.txt\" /etc/nginx/conf.d/default.conf\n    fi\nfi\n\necho \"INFO: creating /run/php/php-fpm.sock ...\"\ntest -e /run/php/php-fpm.sock && rm -f /run/php/php-fpm.sock\nmkdir -p /run/php\ntouch /run/php/php-fpm.sock\nchown nginx:nginx /run/php/php-fpm.sock\nchmod 777 /run/php/php-fpm.sock\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\necho \"Starting SSH ...\"\necho \"Starting php-fpm ...\"\necho \"Starting Nginx ...\"\n\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n\n", "num_lines": 226}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhile [ 1 ]\ndo\n    mkdir -p /var/log/php_fpm\n    try_count=1\n    d_php_fpm=`top -b -n 1 | grep php-fpm | grep D | wc -l`\n    if [ $d_php_fpm -ne 0 ]; then\n        # STAT D php_fpm exist.\n        # echo \"========================================\"\n        # date >> /var/log/php_fpm/watch.log\n        # top -b -n 1 | grep php_fpm >> /var/log/php_fpm/watch.log\n        while [ $try_count -le 5 ]\n        do\n            sleep 3s\n            let try_count+=1\n            d_php_fpm=`top -b -n 1 | grep php-fpm | grep D | wc -l`\n            # echo \"========================================\"\n            # date >> /var/log/php_fpm/watch.log\n            # top -b -n 1 | grep php_fpm >> /var/log/php_fpm/watch.log\n            if [ $d_php_fpm -eq 0 ]; then\n                break\n            fi\n        done\n        if [ $try_count -ge 5 ]; then\n            # echo \"========================================\"\n            # date >> /var/log/php_fpm/watch.log\n            # echo \"Start to KILL!\"\n            # # STAT D has keep for 15 secs.\n            killall -9 php-fpm\n            killall -9 nginx  \n        fi    \n    fi\n    sleep 3s\ndone", "num_lines": 35}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    #rc-service mariadb start \n    service mysql start\n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t\n        # The wp-config.php is designed for default GIT/BRANCH, remove it if need.\n        if [ \"${DATABASE_TYPE}\" != \"local\" -a \"${GIT_REPO}\" == \"https://github.com/azureappserviceoss/wordpress-azure\" -a \"${GIT_BRANCH}\" == \"linux-appservice\" ];then\n           rm wp-config.php\n        fi\n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\n#test ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 196}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    chown -R www-data:www-data $PHPMYADMIN_HOME\n}\n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\n\tcd $WORDPRESS_SOURCE\n\ttar -xf wp.tar.gz -C $WORDPRESS_HOME/ --strip-components=1\n\t\n\tchown -R www-data:www-data $WORDPRESS_HOME\n    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\n\t\n        cd $WORDPRESS_HOME \n\t\tcp $WORDPRESS_SOURCE/wp-config.php . && chmod 777 wp-config.php && chown -R www-data:www-data wp-config.php\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\ncd $WORDPRESS_HOME \nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting SSH ...\"\nrc-service sshd start\n\necho \"Starting Apache httpd -D FOREGROUND ...\"\napachectl start -D FOREGROUND\n", "num_lines": 170}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}\n    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $WORDPRESS_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n    if ! grep -q \"^Include conf/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n        echo 'Include conf/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n    fi\nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 190}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}\n    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n\tGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\tGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\techo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $WORDPRESS_HOME\t\n\tif [ \"$GIT_BTANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){\t\n    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n        if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\n        echo \"Starting local Redis ...\"\n        redis-server --daemonize yes\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 191}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t\n        # The wp-config.php is designed for default GIT/BRANCH, remove it if need.\n        if [ \"${DATABASE_TYPE}\" != \"local\" -a \"${GIT_REPO}\" == \"https://github.com/azureappserviceoss/wordpress-azure\" -a \"${GIT_BRANCH}\" == \"linux-appservice\" ];then\n           rm wp-config.php\n        fi\n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/${DATABASE_NAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/${DATABASE_USERNAME}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/${DATABASE_PASSWORD}/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/${DATABASE_HOST}/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 197}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    # /etc/init.d/mariadb setup\n    /usr/bin/mysql_install_db --user=mysql --datadir=${MARIADB_DATA_DIR}\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 193}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 192}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#set -e\nsetup_mariadb_data_dir(){\n    test ! -d \"$MARIADB_DATA_DIR\" && echo \"INFO: $MARIADB_DATA_DIR not found. creating ...\" && mkdir -p \"$MARIADB_DATA_DIR\"\n\n    # check if 'mysql' database exists\n    if [ ! -d \"$MARIADB_DATA_DIR/mysql\" ]; then\n\techo \"INFO: 'mysql' database doesn't exist under $MARIADB_DATA_DIR. So we think $MARIADB_DATA_DIR is empty.\"\n\techo \"Copying all data files from the original folder /var/lib/mysql to $MARIADB_DATA_DIR ...\"\n\tcp -R /var/lib/mysql/. $MARIADB_DATA_DIR\n    else\n\techo \"INFO: 'mysql' database already exists under $MARIADB_DATA_DIR.\"\n    fi\n\n    rm -rf /var/lib/mysql\n    ln -s $MARIADB_DATA_DIR /var/lib/mysql\n    chown -R mysql:mysql $MARIADB_DATA_DIR\n    test ! -d /run/mysqld && echo \"INFO: /run/mysqld not found. creating ...\" && mkdir -p /run/mysqld\n    chown -R mysql:mysql /run/mysqld\n}\n\nstart_mariadb(){\n    /etc/init.d/mariadb setup\n    rc-service mariadb start \n\n    rm -f /tmp/mysql.sock\n    ln -s /var/run/mysqld/mysqld.sock /tmp/mysql.sock\n\n    # create default database 'azurelocaldb'\n    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS azurelocaldb; FLUSH PRIVILEGES;\"\n}\n\n#unzip phpmyadmin\nsetup_phpmyadmin(){\n    test ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi \n}    \n\nload_phpmyadmin(){\n        if ! grep -q \"^Include conf.d/httpd-phpmyadmin.conf\" $HTTPD_CONF_FILE; then\n                echo 'Include conf.d/httpd-phpmyadmin.conf' >> $HTTPD_CONF_FILE\n        fi\n}\n\nsetup_wordpress(){\n\ttest ! -d \"$WORDPRESS_HOME\" && echo \"INFO: $WORDPRESS_HOME not found. creating ...\" && mkdir -p \"$WORDPRESS_HOME\"\n\tcd $WORDPRESS_HOME\n    if ! [ -e wp-includes/version.php ]; then\n        echo \"INFO: There in no wordpress, going to GIT pull...:\"\n        rm -rf * .*\n        GIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\n\t    GIT_BRANCH=${GIT_BRANCH:-linux-appservice}\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\t    echo \"REPO: \"$GIT_REPO\n\t    echo \"BRANCH: \"$GIT_BRANCH\n\t    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    \n\t    echo \"INFO: Clone from \"$GIT_REPO\t\t\n        git clone $GIT_REPO $WORDPRESS_HOME\t\n\t    if [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\t    echo \"INFO: Checkout to \"$GIT_BRANCH\n\t\t    git fetch origin\n\t        git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\t    fi\t        \n    else\n        echo \"INFO: There is one wordpress exist, no need to GIT pull again.\"\n    fi\n\t\n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $WORDPRESS_HOME    \n}\n\nupdate_wordpress_config(){    \n\tDATABASE_HOST=${DATABASE_HOST:-localhost}\n\tDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\n\tDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n}\n\nload_wordpress(){\n    if ! grep -q \"^Include conf.d/httpd-wordpress.conf\" $HTTPD_CONF_FILE; then\n            echo 'Include conf.d/httpd-wordpress.conf' >> $HTTPD_CONF_FILE\n    fi\n}\n\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$APP_HOME \n    chown -R www-data:www-data $APP_HOME\nfi\n\ntest ! -d \"$HTTPD_LOG_DIR\" && echo \"INFO: $HTTPD_LOG_DIR not found. creating...\" && mkdir -p \"$HTTPD_LOG_DIR\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n    echo \"INFO: NOT in Azure, chown for \"$HTTPD_LOG_DIR \n    chown -R www-data:www-data $HTTPD_LOG_DIR\nfi\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\n\nDATABASE_TYPE=$(echo ${DATABASE_TYPE}|tr '[A-Z]' '[a-z]')\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> $PHP_CONF_FILE     \n    #setup MariaDB\n    echo \"INFO: loading local MariaDB and phpMyAdmin ...\"\n    echo \"Setting up MariaDB data dir ...\"\n    setup_mariadb_data_dir\n    echo \"Setting up MariaDB log dir ...\"\n    test ! -d \"$MARIADB_LOG_DIR\" && echo \"INFO: $MARIADB_LOG_DIR not found. creating ...\" && mkdir -p \"$MARIADB_LOG_DIR\"\n    chown -R mysql:mysql $MARIADB_LOG_DIR\n    echo \"Starting local MariaDB ...\"\n    start_mariadb\n\n    echo \"Granting user for phpMyAdmin ...\"\n    # Set default value of username/password if they are't exist/null.\n    DATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n    DATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"phpmyadmin username:\" $DATABASE_USERNAME\n    echo \"phpmyadmin password:\" $DATABASE_PASSWORD\n    echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    mysql -u root -e \"GRANT ALL ON *.* TO \\`$DATABASE_USERNAME\\`@'localhost' IDENTIFIED BY '$DATABASE_PASSWORD' WITH GRANT OPTION; FLUSH PRIVILEGES;\"\n    echo \"Installing phpMyAdmin ...\"\n    setup_phpmyadmin\n    echo \"Loading phpMyAdmin conf ...\"\n\tload_phpmyadmin    \nfi\n\n# That wp-config.php doesn't exist means WordPress is not installed/configured yet.\nif [ ! -e \"$WORDPRESS_HOME/wp-config.php\" ]; then\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php not found.\"\n\techo \"Installing WordPress for the first time ...\" \n\tsetup_wordpress\t\n\n\tif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"Creating database for WordPress if not exists ...\"\n\t    mysql -u root -e \"CREATE DATABASE IF NOT EXISTS \\`$DATABASE_NAME\\` CHARACTER SET utf8 COLLATE utf8_general_ci;\"\n\t    echo \"Granting user for WordPress ...\"\n\t    mysql -u root -e \"GRANT ALL ON \\`$DATABASE_NAME\\`.* TO \\`$DATABASE_USERNAME\\`@\\`$DATABASE_HOST\\` IDENTIFIED BY '$DATABASE_PASSWORD'; FLUSH PRIVILEGES;\"\t\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php\n\t\tcd $WORDPRESS_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n\tfi\nelse\n\techo \"INFO: $WORDPRESS_HOME/wp-config.php already exists.\"\n\techo \"INFO: You can modify it manually as need.\"\nfi\t\n\necho \"Loading WordPress conf ...\"\nload_wordpress\nrm -rf $WORDPRESS_SOURCE\n\necho \"Starting Redis ...\"\nredis-server &\necho \"Starting SSH ...\"\necho \"Starting Apache httpd -D FOREGROUND ...\"\n\ntest ! -d \"$HTTPD_PID_DIR\" && echo \"INFO: $HTTPD_PID_DIR not found. creating ...\" && mkdir -p \"$HTTPD_PID_DIR\"\ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ncd /usr/bin/\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 192}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# set -euo pipefail\n\nGIT_REPO=${GIT_REPO:-https://github.com/azureappserviceoss/wordpress-azure}\nGIT_BRANCH=${GIT_BRANCH:-linux-appservice}\nDATABASE_TYPE=${DATABASE_TYPE:-\"\"}\nWEBSITES_ENABLE_APP_SERVICE_STORAGE=${WEBSITES_ENABLE_APP_SERVICE_STORAGE:-true}\nDATABASE_HOST=${DATABASE_HOST:-db}\nDATABASE_NAME=${DATABASE_NAME:-azurelocaldb}\nDATABASE_USERNAME=${DATABASE_USERNAME:-phpmyadmin}\n\t# if DATABASE_USERNAME equal phpmyadmin, it means it's nothing at beginning.\n\tif [ \"${DATABASE_USERNAME}\" == \"phpmyadmin\" ]; then\n\t    DATABASE_USERNAME='wordpress'\n\tfi\t\nDATABASE_PASSWORD=${DATABASE_PASSWORD:-MS173m_QN}   \n\nsetup_wordpress(){    \n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n\techo \"REPO: \"$GIT_REPO\n\techo \"BRANCH: \"$GIT_BRANCH\n\techo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n    echo \"INFO: Clone from \"$GIT_REPO\t\t\n    git clone $GIT_REPO $APP_HOME\t\n\tif [ \"$GIT_BRANCH\" != \"master\" ];then\n\t\techo \"INFO: Checkout to \"$GIT_BRANCH\n\t\tgit fetch origin\n\t    git branch --track $GIT_BRANCH origin/$GIT_BRANCH && git checkout $GIT_BRANCH\n\tfi    \t\n    \n\t# Although in AZURE, we still need below chown cmd.\n    chown -R www-data:www-data $APP_HOME\t\n}\n\nsetup_phpmyadmin(){\n\ttest ! -d \"$PHPMYADMIN_HOME\" && echo \"INFO: $PHPMYADMIN_HOME not found. creating...\" && mkdir -p \"$PHPMYADMIN_HOME\"\n    cd /usr/src && ls -al\n    cd $PHPMYADMIN_SOURCE\n    tar -xf phpmyadmin.tar.gz -C $PHPMYADMIN_HOME --strip-components=1\n    cp -R phpmyadmin-config.inc.php $PHPMYADMIN_HOME/config.inc.php\n    mkdir $PHPMYADMIN_HOME/tmp && chmod 777 $PHPMYADMIN_HOME/tmp\n    rm -rf $PHPMYADMIN_SOURCE\n    if [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n        echo \"INFO: NOT in Azure, chown for \"$PHPMYADMIN_HOME  \n        chown -R www-data:www-data $PHPMYADMIN_HOME\n    fi\n}\n\ntest ! -d \"$LOG_DIR\" && echo \"INFO: $LOG_DIR not found. creating...\" && mkdir -p \"$LOG_DIR\" \ntest ! -d \"$SUPERVISOR_LOG_DIR\" && echo \"INFO: $SUPERVISOR_LOG_DIR not found. creating ...\" && mkdir -p \"$SUPERVISOR_LOG_DIR\"\ntest ! -d \"$APP_HOME\" && echo \"INFO: $APP_HOME not found. creating...\" && mkdir -p \"$APP_HOME\"\nif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then\n#    echo \"INFO: NOT in Azure, chown for \"$APP_HOME  \n    chown -R www-data:www-data $APP_HOME\nfi \n\ncd $APP_HOME\nif ! [ -e index.php -a -e wp-includes/version.php ]; then\n    echo \"WordPress not found in $APP_HOME...\"\t\n    echo \"Start to clean $APP_HOME...\" && cd /home/site && rm -rf $APP_HOME && mkdir -p $APP_HOME && cd $APP_HOME\n    echo \"Copying now...\" && cd $APP_HOME && ls -al    \n\tsetup_wordpress\n    cp $WORDPRESS_SOURCE/wp-config-sample.php .\n\n    if [ \"$DATABASE_TYPE\" == \"local\" ]; then\n        echo \"INFO: local MariaDB is used.\"\n        #update_wordpress_config\n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n        echo \"INFO: WORDPRESS_ENVS:\"\n        echo \"INFO: DATABASE_HOST:\" $DATABASE_HOST\n        echo \"INFO: WORDPRESS_DATABASE_NAME:\" $DATABASE_NAME\n        echo \"INFO: WORDPRESS_DATABASE_USERNAME:\" $DATABASE_USERNAME\n        echo \"INFO: WORDPRESS_DATABASE_PASSWORD:\" $DATABASE_PASSWORD\t        \n        echo \"INFO: ++++++++++++++++++++++++++++++++++++++++++++++++++:\"\n         \n\t\tcd $WORDPRESS_SOURCE && chmod 777 wp-config.php\n\t\tif [ ! $WEBSITES_ENABLE_APP_SERVICE_STORAGE ]; then \n           echo \"INFO: NOT in Azure, chown for wp-config.php\"\n           chown -R www-data:www-data wp-config.php\n        fi\t\t\t\t\n        sed -i \"s/getenv('DATABASE_NAME')/'${DATABASE_NAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_USERNAME')/'${DATABASE_USERNAME}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_PASSWORD')/'${DATABASE_PASSWORD}'/g\" wp-config.php\n        sed -i \"s/getenv('DATABASE_HOST')/'${DATABASE_HOST}'/g\" wp-config.php        \n\t\tcd $APP_HOME\n\t\tcp $WORDPRESS_SOURCE/wp-config.php .\n    else \n        # The wp-config.php in default GIT/BRANCH is designed fo local DB, remove it if need.\n        if [ \"${GIT_REPO}\" == \"https://github.com/azureappserviceoss/wordpress-azure\" -a \"${GIT_BRANCH}\" == \"linux-appservice\" ]; then\n           echo \"The wp-config.php in default GIT/BRANCH is designed fo local DB, remove it if need...\"\n           rm wp-config.php\n        fi        \n    fi\nfi\n\ncd $APP_HOME\n# Install Redis Cache WordPress Plugin\nif [ ! -e wp-content/plugins/redis-cache ]; then\n\t# Update package repos\n\tapt-get update\n\t# Install unzip\n\tapt-get install unzip\n\techo \"Downloading https://downloads.wordpress.org/plugin/redis-cache.1.3.8.zip\"\n\tcurl -o redis-cache.1.3.8.zip -fsL \"https://downloads.wordpress.org/plugin/redis-cache.1.3.8.zip\"\n\techo \"Unzipping redis-cache.1.3.8.zip to /var/www/html/wp-content/plugins/\"\n\tunzip -q redis-cache.1.3.8.zip -d /var/www/html/wp-content/plugins/\n\techo \"Removing redis-cache.1.3.8.zip\"\n\trm redis-cache.1.3.8.zip\nfi\n\nif [ \"${DATABASE_TYPE}\" == \"local\" ]; then\n    setup_phpmyadmin  \n    echo 'mysql.default_socket = /run/mysqld/mysqld.sock' >> /usr/local/etc/php/php.ini\n    echo 'mysqli.default_socket = /run/mysqld/mysqld.sock' >> /usr/local/etc/php/php.ini    \nfi\n\necho \"Starting SSH ...\"\n#service ssh start\necho \"Starting Apache...\"\n#apache2-foreground\ncd /usr/bin\nsupervisord -c /etc/supervisord.conf\n", "num_lines": 122}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n# usage: file_env VAR [DEFAULT]\n#    ie: file_env 'XYZ_DB_PASSWORD' 'example'\n# (will allow for \"$XYZ_DB_PASSWORD_FILE\" to fill in the value of\n#  \"$XYZ_DB_PASSWORD\" from a file, especially for Docker's secrets feature)\nfile_env() {\n\tlocal var=\"$1\"\n\tlocal fileVar=\"${var}_FILE\"\n\tlocal def=\"${2:-}\"\n\tif [ \"${!var:-}\" ] && [ \"${!fileVar:-}\" ]; then\n\t\techo >&2 \"error: both $var and $fileVar are set (but are exclusive)\"\n\t\texit 1\n\tfi\n\tlocal val=\"$def\"\n\tif [ \"${!var:-}\" ]; then\n\t\tval=\"${!var}\"\n\telif [ \"${!fileVar:-}\" ]; then\n\t\tval=\"$(< \"${!fileVar}\")\"\n\tfi\n\texport \"$var\"=\"$val\"\n\tunset \"$fileVar\"\n}\n\nif [[ \"$1\" == apache2* ]] || [ \"$1\" == php-fpm ]; then\n\tif [ \"$(id -u)\" = '0' ]; then\n\t\tcase \"$1\" in\n\t\t\tapache2*)\n\t\t\t\tuser=\"${APACHE_RUN_USER:-www-data}\"\n\t\t\t\tgroup=\"${APACHE_RUN_GROUP:-www-data}\"\n\t\t\t\t;;\n\t\t\t*) # php-fpm\n\t\t\t\tuser='www-data'\n\t\t\t\tgroup='www-data'\n\t\t\t\t;;\n\t\tesac\n\telse\n\t\tuser=\"$(id -u)\"\n\t\tgroup=\"$(id -g)\"\n\tfi\n\n\tif ! [ -e index.php -a -e wp-includes/version.php ]; then\n\t\techo >&2 \"WordPress not found in $PWD - copying now...\"\n\t\tif [ \"$(ls -A)\" ]; then\n\t\t\techo >&2 \"WARNING: $PWD is not empty - press Ctrl+C now if this is an error!\"\n\t\t\t( set -x; ls -A; sleep 10 )\n\t\tfi\n\t\ttar --create \\\n\t\t\t--file - \\\n\t\t\t--one-file-system \\\n\t\t\t--directory /usr/src/wordpress \\\n\t\t\t--owner \"$user\" --group \"$group\" \\\n\t\t\t. | tar --extract --file -\n\t\techo >&2 \"Complete! WordPress has been successfully copied to $PWD\"\n\t\tif [ ! -e .htaccess ]; then\n\t\t\t# NOTE: The \"Indexes\" option is disabled in the php:apache base image\n\t\t\tcat > .htaccess <<-'EOF'\n\t\t\t\t# BEGIN WordPress\n\t\t\t\t<IfModule mod_rewrite.c>\n\t\t\t\tRewriteEngine On\n\t\t\t\tRewriteBase /\n\t\t\t\tRewriteRule ^index\\.php$ - [L]\n\t\t\t\tRewriteCond %{REQUEST_FILENAME} !-f\n\t\t\t\tRewriteCond %{REQUEST_FILENAME} !-d\n\t\t\t\tRewriteRule . /index.php [L]\n\t\t\t\t</IfModule>\n\t\t\t\t# END WordPress\n\t\t\tEOF\n\t\t\tchown \"$user:$group\" .htaccess\n\t\tfi\n\tfi\n\n\t# TODO handle WordPress upgrades magically in the same way, but only if wp-includes/version.php's $wp_version is less than /usr/src/wordpress/wp-includes/version.php's $wp_version\n\n\t# allow any of these \"Authentication Unique Keys and Salts.\" to be specified via\n\t# environment variables with a \"WORDPRESS_\" prefix (ie, \"WORDPRESS_AUTH_KEY\")\n\tuniqueEnvs=(\n\t\tAUTH_KEY\n\t\tSECURE_AUTH_KEY\n\t\tLOGGED_IN_KEY\n\t\tNONCE_KEY\n\t\tAUTH_SALT\n\t\tSECURE_AUTH_SALT\n\t\tLOGGED_IN_SALT\n\t\tNONCE_SALT\n\t)\n\tenvs=(\n\t\tWORDPRESS_DB_HOST\n\t\tWORDPRESS_DB_USER\n\t\tWORDPRESS_DB_PASSWORD\n\t\tWORDPRESS_DB_NAME\n\t\t\"${uniqueEnvs[@]/#/WORDPRESS_}\"\n\t\tWORDPRESS_TABLE_PREFIX\n\t\tWORDPRESS_DEBUG\n\t)\n\thaveConfig=\n\tfor e in \"${envs[@]}\"; do\n\t\tfile_env \"$e\"\n\t\tif [ -z \"$haveConfig\" ] && [ -n \"${!e}\" ]; then\n\t\t\thaveConfig=1\n\t\tfi\n\tdone\n\n\t# linking backwards-compatibility\n\tif [ -n \"${!MYSQL_ENV_MYSQL_*}\" ]; then\n\t\thaveConfig=1\n\t\t# host defaults to \"mysql\" below if unspecified\n\t\t: \"${WORDPRESS_DB_USER:=${MYSQL_ENV_MYSQL_USER:-root}}\"\n\t\tif [ \"$WORDPRESS_DB_USER\" = 'root' ]; then\n\t\t\t: \"${WORDPRESS_DB_PASSWORD:=${MYSQL_ENV_MYSQL_ROOT_PASSWORD:-}}\"\n\t\telse\n\t\t\t: \"${WORDPRESS_DB_PASSWORD:=${MYSQL_ENV_MYSQL_PASSWORD:-}}\"\n\t\tfi\n\t\t: \"${WORDPRESS_DB_NAME:=${MYSQL_ENV_MYSQL_DATABASE:-}}\"\n\tfi\n\n\t# only touch \"wp-config.php\" if we have environment-supplied configuration values\n\tif [ \"$haveConfig\" ]; then\n\t\t: \"${WORDPRESS_DB_HOST:=mysql}\"\n\t\t: \"${WORDPRESS_DB_USER:=root}\"\n\t\t: \"${WORDPRESS_DB_PASSWORD:=}\"\n\t\t: \"${WORDPRESS_DB_NAME:=wordpress}\"\n\n\t\t# version 4.4.1 decided to switch to windows line endings, that breaks our seds and awks\n\t\t# https://github.com/docker-library/wordpress/issues/116\n\t\t# https://github.com/WordPress/WordPress/commit/1acedc542fba2482bab88ec70d4bea4b997a92e4\n\t\tsed -ri -e 's/\\r$//' wp-config*\n\n\t\tif [ ! -e wp-config.php ]; then\n\t\t\tawk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' wp-config-sample.php > wp-config.php <<'EOPHP'\n// If we're behind a proxy server and using HTTPS, we need to alert Wordpress of that fact\n// see also http://codex.wordpress.org/Administration_Over_SSL#Using_a_Reverse_Proxy\nif (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {\n\t$_SERVER['HTTPS'] = 'on';\n}\n\nEOPHP\n\t\t\tchown \"$user:$group\" wp-config.php\n\t\tfi\n\n\t\t# see http://stackoverflow.com/a/2705678/433558\n\t\tsed_escape_lhs() {\n\t\t\techo \"$@\" | sed -e 's/[]\\/$*.^|[]/\\\\&/g'\n\t\t}\n\t\tsed_escape_rhs() {\n\t\t\techo \"$@\" | sed -e 's/[\\/&]/\\\\&/g'\n\t\t}\n\t\tphp_escape() {\n\t\t\tlocal escaped=\"$(php -r 'var_export(('\"$2\"') $argv[1]);' -- \"$1\")\"\n\t\t\tif [ \"$2\" = 'string' ] && [ \"${escaped:0:1}\" = \"'\" ]; then\n\t\t\t\tescaped=\"${escaped//$'\\n'/\"' + \\\"\\\\n\\\" + '\"}\"\n\t\t\tfi\n\t\t\techo \"$escaped\"\n\t\t}\n\t\tset_config() {\n\t\t\tkey=\"$1\"\n\t\t\tvalue=\"$2\"\n\t\t\tvar_type=\"${3:-string}\"\n\t\t\tstart=\"(['\\\"])$(sed_escape_lhs \"$key\")\\2\\s*,\"\n\t\t\tend=\"\\);\"\n\t\t\tif [ \"${key:0:1}\" = '$' ]; then\n\t\t\t\tstart=\"^(\\s*)$(sed_escape_lhs \"$key\")\\s*=\"\n\t\t\t\tend=\";\"\n\t\t\tfi\n\t\t\tsed -ri -e \"s/($start\\s*).*($end)$/\\1$(sed_escape_rhs \"$(php_escape \"$value\" \"$var_type\")\")\\3/\" wp-config.php\n\t\t}\n\n\t\tset_config 'DB_HOST' \"$WORDPRESS_DB_HOST\"\n\t\tset_config 'DB_USER' \"$WORDPRESS_DB_USER\"\n\t\tset_config 'DB_PASSWORD' \"$WORDPRESS_DB_PASSWORD\"\n\t\tset_config 'DB_NAME' \"$WORDPRESS_DB_NAME\"\n\n\t\tfor unique in \"${uniqueEnvs[@]}\"; do\n\t\t\tuniqVar=\"WORDPRESS_$unique\"\n\t\t\tif [ -n \"${!uniqVar}\" ]; then\n\t\t\t\tset_config \"$unique\" \"${!uniqVar}\"\n\t\t\telse\n\t\t\t\t# if not specified, let's generate a random value\n\t\t\t\tcurrentVal=\"$(sed -rn -e \"s/define\\((([\\'\\\"])$unique\\2\\s*,\\s*)(['\\\"])(.*)\\3\\);/\\4/p\" wp-config.php)\"\n\t\t\t\tif [ \"$currentVal\" = 'put your unique phrase here' ]; then\n\t\t\t\t\tset_config \"$unique\" \"$(head -c1m /dev/urandom | sha1sum | cut -d' ' -f1)\"\n\t\t\t\tfi\n\t\t\tfi\n\t\tdone\n\n\t\tif [ \"$WORDPRESS_TABLE_PREFIX\" ]; then\n\t\t\tset_config '$table_prefix' \"$WORDPRESS_TABLE_PREFIX\"\n\t\tfi\n\n\t\tif [ \"$WORDPRESS_DEBUG\" ]; then\n\t\t\tset_config 'WP_DEBUG' 1 boolean\n\t\tfi\n\n\t\tTERM=dumb php -- <<'EOPHP'\n<?php\n// database might not exist, so let's try creating it (just to be safe)\n\n$stderr = fopen('php://stderr', 'w');\n\n// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Alternate_Port\n//   \"hostname:port\"\n// https://codex.wordpress.org/Editing_wp-config.php#MySQL_Sockets_or_Pipes\n//   \"hostname:unix-socket-path\"\nlist($host, $socket) = explode(':', getenv('WORDPRESS_DB_HOST'), 2);\n$port = 0;\nif (is_numeric($socket)) {\n\t$port = (int) $socket;\n\t$socket = null;\n}\n$user = getenv('WORDPRESS_DB_USER');\n$pass = getenv('WORDPRESS_DB_PASSWORD');\n$dbName = getenv('WORDPRESS_DB_NAME');\n\n$maxTries = 10;\ndo {\n\t$mysql = new mysqli($host, $user, $pass, '', $port, $socket);\n\tif ($mysql->connect_error) {\n\t\t$mysql = mysqli_init();\n\t\tmysqli_ssl_set($mysql, NULL, NULL, ABSPATH . 'BaltimoreCyberTrustRoot.crt.pem', NULL, NULL); \n\t\tmysqli_real_connect($mysql, $host, $user, $pass, '', $port, MYSQLI_CLIENT_SSL, MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);\n\t\tif ($mysql->connect_error) {\n\t\t  fwrite($stderr, \"\\n\" . 'MySQL Connection Error: (' . $mysql->connect_errno . ') ' . $mysql->connect_error . \"\\n\");\n\t\t  --$maxTries;\n\t\t  if ($maxTries <= 0) {\n\t\t\t  exit(1);\n\t\t  }\n\t\t  sleep(3);\n\t\t}\n\t}\n} while ($mysql->connect_error);\n\nif (!$mysql->query('CREATE DATABASE IF NOT EXISTS `' . $mysql->real_escape_string($dbName) . '`')) {\n\tfwrite($stderr, \"\\n\" . 'MySQL \"CREATE DATABASE\" Error: ' . $mysql->error . \"\\n\");\n\t$mysql->close();\n\texit(1);\n}\n\n$mysql->close();\nEOPHP\n\tfi\n\n\t# now that we're definitely done writing configuration, let's clear out the relevant envrionment variables (so that stray \"phpinfo()\" calls don't leak secrets from our code)\n\tfor e in \"${envs[@]}\"; do\n\t\tunset \"$e\"\n\tdone\nfi\n\nexec \"$@\"\n", "num_lines": 250}
{"repo_name": "app-service-quickstart-docker-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# start SSH service\n#/etc/init.d/sshd restart\n\n# Get environment variables to show up in SSH session\n\nsetup_wp_config(){\n  # Generate vars for wp-config.php injection\n  echo \"Generating PHP Defines from ENV...\"\n  DEFINES=$(awk -v pat=\"$WPFPM_FLAG\" 'END {\n    print \"// Generated by docker-entrypoint2.sh:\";\n\n    for (name in ENVIRON) {\n      if ( name ~ pat ) {\n        print \"define(\\\"\" substr(name, length(pat)+1) \"\\\", \\\"\" ENVIRON[name] \"\\\");\"\n      }\n  }\n\n    print \" \"\n  }' < /dev/null)\n  echo $DEFINES\n\n  echo \"Adding Defines to wp-config.php...\"\n\n  # Remove previously-injected vars\n  sed '/\\/\\/ENTRYPOINT_START/,/\\/\\/ENTRYPOINT_END/d' wp-config.php > wp-config.tmp\n\n  # Add current vars\n  awk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' wp-config.tmp > wp-config.php <<EOF\n  //ENTRYPOINT_START\n\n  $DEFINES\n\n  if (isset(\\$_SERVER['HTTP_X_FORWARDED_PROTO']) && \\$_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https') {\n    \\$_SERVER['HTTPS'] = 'on';\n  }\n\n  //ENTRYPOINT_END\n\nEOF\n\n  rm wp-config.tmp\n\n}\n\nadd_wp_configs(){\n  mv $CON_FILE.php $CON_FILE.tmp \n  awk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' $CON_FILE.tmp > $CON_FILE.php <<EOPHP\n  $DEFINE_CODE    \nEOPHP\n  rm $CON_FILE.tmp\n}\n\nadd_redis_host(){\n  mv $CON_FILE.php $CON_FILE.tmp \n  awk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' $CON_FILE.tmp > $CON_FILE.php <<'EOPHP'\n    define('WP_REDIS_HOST', getenv('WP_REDIS_HOST'));    \nEOPHP\n  rm $CON_FILE.tmp\n}\n\nadd_mysql_ssl_ca(){\n  mv $CON_FILE.php $CON_FILE.tmp \n  awk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' $CON_FILE.tmp > $CON_FILE.php <<'EOPHP'\n    define('MYSQL_SSL_CA', getenv('MYSQL_SSL_CA'));    \nEOPHP\n  rm $CON_FILE.tmp\n}\n\nadd_mysql_client_flag(){\n  mv $CON_FILE.php $CON_FILE.tmp \n  awk '/^\\/\\*.*stop editing.*\\*\\/$/ && c == 0 { c = 1; system(\"cat\") } { print }' $CON_FILE.tmp > $CON_FILE.php <<'EOPHP'\n    define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);\nEOPHP\n  rm $CON_FILE.tmp\n}\n\nadd_redis_ssl_client_flag(){  \n  grep -q \"define('WP_REDIS_HOST', getenv('WP_REDIS_HOST'));\" $CON_FILE.php\n  if [ \"$?\" -eq '0' ]; then\n    echo \"Redis Host is exist in \"$CON_FILE\".php ...\"\n  else\n    echo \"ADD Redis host into \"$CON_FILE\".php ...\"\n    #add_redis_host\n    DEFINE_CODE=\"define('WP_REDIS_HOST', getenv('WP_REDIS_HOST'));\"\n    add_wp_configs \n  fi\n  sed -i \"s/#define('MYSQL_SSL_CA'/define('MYSQL_SSL_CA'/g\" $CON_FILE.php\n  grep -q \"define('MYSQL_SSL_CA', getenv('MYSQL_SSL_CA'));\" $CON_FILE.php\n  if [ \"$?\" -eq '0' ]; then\n    echo \"MYSQL_SSL_CA is exist in \"$CON_FILE\".php ...\"\n  else\n    echo \"ADD MYSQL_SSL_CA into \"$CON_FILE\".php ...\"\n    #add_mysql_ssl_ca\n    DEFINE_CODE=\"define('MYSQL_SSL_CA', getenv('MYSQL_SSL_CA'));\"\n    add_wp_configs\n  fi\n  sed -i \"s/#define('MYSQL_CLIENT_FLAGS'/define('MYSQL_CLIENT_FLAGS'/g\" $CON_FILE.php\n  grep -q \"define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);\" $CON_FILE.php\n  if [ \"$?\" -eq '0' ]; then\n    echo \"MYSQL_CLIENT_FLAGS is exist in \"$CON_FILE\".php ...\"\n  else\n    echo \"ADD MYSQL_CLIENT_FLAGS into \"$CON_FILE\".php ...\"\n    #add_mysql_client_flag\n    DEFINE_CODE=\"define('MYSQL_CLIENT_FLAGS', MYSQLI_CLIENT_SSL | MYSQLI_CLIENT_SSL_DONT_VERIFY_SERVER_CERT);\"\n    add_wp_configs\n  fi  \n}\n\neval $(printenv | awk -F= '{print \"export \" $1\"=\"$2 }' >> /etc/profile)\n\n#set -euo pipefail\n\necho \"Setup openrc ...\" && openrc && touch /run/openrc/softlevel\necho \"Starting SSH ...\"\nrc-service sshd start\n\n# Remove exec from original entrypoint so we can continue here\nsed -i -e 's/exec/\\# exec/g' /usr/local/bin/docker-entrypoint.sh\n\n# Normal setup\ncd /var/www/html\n/bin/bash /usr/local/bin/docker-entrypoint.sh $1\n\ncd /var/www/html\ncp /usr/src/BaltimoreCyberTrustRoot.crt.pem .\nCON_FILE=wp-config-sample\nif [ -e $CON_FILE.php ]; then \n  add_redis_ssl_client_flag\nfi\n\n# The wp-config.php is created as soon as there are some application settings exist.\nif [ -e wp-config.php ]; then  \n  setup_wp_config\n  CON_FILE=wp-config\n  add_redis_ssl_client_flag  \nfi\n\n\n# Install Nginx Helper plugin\nif [ ! -e wp-content/plugins/nginx-helper ]; then\n  if ( wget https://downloads.wordpress.org/plugin/nginx-helper.1.9.10.zip ); then\n    unzip nginx-helper.1.9.10.zip -q -d /var/www/html/wp-content/plugins/\n    rm nginx-helper.1.9.10.zip\n  else\n    echo \"## WARN: wget failed for https://downloads.wordpress.org/plugin/nginx-helper.1.9.10.zip\"\n  fi\nfi\n\n# Install Redis Cache plugin\nif [ ! -e wp-content/plugins/redis-cache ]; then\n  if ( wget https://downloads.wordpress.org/plugin/redis-cache.1.3.8.zip ); then\n    unzip redis-cache.1.3.8.zip -q -d /var/www/html/wp-content/plugins/\n    rm redis-cache.1.3.8.zip\n  else\n    echo \"## WARN: wget failed for https://downloads.wordpress.org/plugin/redis-cache.1.3.8.zip\"\n  fi\nfi\n\n# Set up Nginx Helper log directory\nmkdir -p wp-content/uploads/nginx-helper\n\n# Set usergroup for all modified files\nchown -R www-data:www-data /var/www/html/\n\necho \"Starting php-fpm ...\"\nexec \"$@\"\n\n", "num_lines": 169}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -auexo pipefail\n\ngo test -v -tags unittest $(go list ./... | grep 'application-gateway'); echo $?\n", "num_lines": 6}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eauo pipefail\n\nTAG=${1:-$(git describe --abbrev=0 --tags)}\n\nOFFICIAL_REGISTRY=\"mcr.microsoft.com/azure-application-gateway/kubernetes-ingress\"\nSTAGING_REGISTRY=\"mcr.microsoft.com/azure-application-gateway/kubernetes-ingress-staging\"\nHELM_GIT_REPO_URL=\"https://azure.github.io/application-gateway-kubernetes-ingress/helm\"\nHELM_REPO_URL=${2:-$HELM_GIT_REPO_URL}\n\necho \" - tagging with [$TAG]\"\nTGZ_FILE=(ingress-azure-$TAG.tgz)\n\nif [ -f $TGZ_FILE ]; then\n  echo \"File $TGZ_FILE already exists!\"\n  exit 0\nfi\n\nENV=${3:-\"\"}\nREGISTRY=\"\"\nif [ \"$ENV\" = \"prod\" ]; then\n  REGISTRY=$OFFICIAL_REGISTRY  \nelif [ \"$ENV\" = \"staging\" ]; then\n  REGISTRY=$STAGING_REGISTRY\nelse\n  echo \" - exiting bad/unknown environment provided: \" $ENV\n  exit 1\nfi\n\necho \" - deployment will use registry: \" $REGISTRY\n\necho \" - update helm templates\"\ncat ingress-azure/Chart-template.yaml | sed \"s/XXVERSIONXX/$TAG/g\" > ingress-azure/Chart.yaml\ncat ingress-azure/values-template.yaml | sed \"s/XXVERSIONXX/$TAG/g\" | sed \"s#XXREGISTRYXX#$REGISTRY#g\" > ingress-azure/values.yaml\n\necho \" - running helm package\"\nhelm package ingress-azure --version \"$TAG\"\n\nINDEX_FILE_URL=\"$HELM_REPO_URL/index.yaml\"\necho \" - check if helm index [$INDEX_FILE_URL] exists in helm repo [$HELM_REPO_URL]\"\nstatus_code=$(curl -s --head $INDEX_FILE_URL | head -n 1 | awk '{print $2}')\n\nif [ $status_code -eq \"200\" ]; then\n  echo \" - get current helm index from helm repo [$HELM_REPO_URL]\"\n  curl -s -S $INDEX_FILE_URL -o previous_index.yaml > /dev/null\n\n  echo \" - merging with existing helm repo index\"\n  helm repo index . --url $HELM_REPO_URL --merge previous_index.yaml\nelse\n  echo \" - creating a new helm repo index\"\n  helm repo index . --url $HELM_REPO_URL\nfi\n\n\necho \" - done!\"\n", "num_lines": 57}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# colors\nCOLOR_RESET='\\e[0m'\nCOLOR_BLUE='\\e[44;97m'\nCOLOR_RED='\\e[101;97m'\nCOLOR_GREEN='\\e[42;97m'\n\n\nexport GOOS=linux\nexport GOBIN=`pwd`/bin\n\nGO_PROJ=\"github.com/Azure/application-gateway-kubernetes-ingress\"\nGO_PKGS=`go list ./... | grep -v vendor/`\nGO_FILES=`find . -type f -name '*.go' -not -path \"./vendor/*\"`\n\nORG_PATH=\"github.com/Azure\"\nPROJECT_NAME=\"application-gateway-kubernetes-ingress\"\nREPO_PATH=\"${ORG_PATH}/${PROJECT_NAME}\"\n\nVERSION_VAR=\"${REPO_PATH}/pkg/version.Version\"\nVERSION=$(git describe --abbrev=0 --tags)\n\nDATE_VAR=\"${REPO_PATH}/pkg/version.BuildDate\"\nBUILD_DATE=$(date +%Y-%m-%d-%H:%MT%z)\n\nCOMMIT_VAR=\"${REPO_PATH}/pkg/version.GitCommit\"\nGIT_HASH=$(git rev-parse --short HEAD)\n\n\necho -e \"$COLOR_BLUE Running go lint.. $COLOR_RESET\"\ngolint $GO_PKGS > /tmp/lint.out\ncat /tmp/lint.out\nif [ -s /tmp/lint.out ]; then\n    echo -e \"$COLOR_RED golint FAILED $COLOR_RESET\"\n    exit 1\nelse\n    echo -e \"$COLOR_GREEN golint SUCCEEDED $COLOR_RESET\"\nfi\n\necho -e \"$COLOR_BLUE Running govet ... $COLOR_RESET\"\nif go vet -v $GO_PKGS; then\n    echo -e \"$COLOR_GREEN govet SUCCEEDED $COLOR_RESET\"\nelse\n    echo -e \"$COLOR_RED govet FAILED $COLOR_RESET\"\n    exit 1\nfi\n\necho -e \"$COLOR_BLUE Running goimports ... $COLOR_RESET\"\ngoimports -local $GO_PROJ -w $GO_FILES > /tmp/goimports.out\ncat /tmp/goimports.out\nif [ -s /tmp/goimports.out ]; then\n    echo -e \"$COLOR_RED goimports FAILED $COLOR_RESET\"\n    exit 1\nelse\n    echo -e \"$COLOR_GREEN goimports SUCCEEDED $COLOR_RESET\"\nfi\n\necho -e \"$COLOR_BLUE Compiling ... $COLOR_RESET\"\nif  go install -ldflags \"-s -X ${VERSION_VAR}=${VERSION} -X ${DATE_VAR}=${BUILD_DATE} -X ${COMMIT_VAR}=${GIT_HASH}\" -v ./cmd/appgw-ingress; then\n    chmod -R 777 bin\n    echo -e \"$COLOR_GREEN Build SUCCEEDED $COLOR_RESET\"\nelse\n    echo -e \"$COLOR_RED Build FAILED $COLOR_RESET\"\n    exit 1\nfi\n", "num_lines": 67}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#This script uses AKS Periscope to collect the AGIC logs. See https://github.com/Azure/aks-periscope for more details\n\nif ! [ \"which az\" ]; then\n  echo \"Cannot find Azure CLI. Please see to install if : https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest\"\n  exit 1\nfi\n\nif ! [ \"which kubectl\" ]; then\n  echo \"Cannot find kubectl. Please install it\"\n  exit 1\nfi\n\nread -p 'Please confirm azure-cli is updated to latest version (y/N):' cliVersionConfirmation\nif [ $cliVersionConfirmation != \"y\" ]\nthen\n  exit 1\nfi\n\naz extension add --name aks-preview\naz extension update --name aks-preview\n\nclusterName=$(kubectl config current-context)\n\nread -p 'ResourceGroup for '$clusterName' cluster: ' resourceGroupName\nread -p 'StorageAccountName: ' storageAccountName\nread -p 'StorageAccountSAS: ' sasKey\n\nfile=\"/tmp/agict0923\"\ndeclare -a logContainer\nkubectl get pods -l \"app=ingress-azure\" --template '{{range .items}}{{.spec.nodeName}}{{\"/\"}}{{.metadata.namespace}}{{\"/\"}}{{.metadata.name}}{{\"\\n\"}}{{end}}' > $file\n\n## Construct the pods to get the logs from\nwhile IFS= read -r line\ndo\n  #echo \"$line\"\n  IFS='/' read -ra pod_info <<< \"$line\"\n  podName=\"${pod_info[1]}/${pod_info[2]}\"\n  logLocation=\"${pod_info[0]}/collector/containerlogs/${pod_info[1]}_${pod_info[2]}\"\n  logContainer+=($logLocation)\n  containers=\"$containers $podName\"\ndone < \"$file\"\n\nif [ -z \"$containers\" ]\nthen\n  echo \"No AGIC deployments found\"\n  exit 1\nfi\n\necho \"Collect Logs for following AGIC containers: $containers\"\naz aks kollect -n $clusterName -g $resourceGroupName --storage-account \"$storageAccountName\" --sas-token \"$sasKey\" --container-logs \"$containers\"\n\nprintf '\\n\\n %s\\n\\n' \"------- Please collect logs at following paths under the latest timestamped container named '$clusterName' in storage '$storageAccountName' ---\"\nprintf '%s\\n' \"${logContainer[@]}\"\n\nrm -rf $file\n", "num_lines": 57}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Logging into docker....\"\necho \"$DOCKER_PASSWORD\" | docker login $ACR_REGISTRY -u \"$DOCKER_USERNAME\" --password-stdin\necho \"Login successful. Getting ready to deploy.\"\n\nset -x\npushd $TRAVIS_BUILD_DIR/build\ncmake --build . --target dockerpush\npopd\nset +x", "num_lines": 10}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngrep 'errors.New' $(find . -name '*.go' -not -path './git/*' -not -path './vendor/*' | grep -v '_test.go' | grep -v 'crd_client') | grep -oE '\\([A-Z]{4}[0-9]{3}\\)' | sort | uniq -c |  awk '{if ($1 > 1) print $0}'\n", "num_lines": 4}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\n# This script requres a checkout of https://github.com/kubernetes/code-generator release-1.21 in ../\n# For more information read https://blog.openshift.com/kubernetes-deep-dive-code-generation-customresources/\n# To generate CRDs, run this in the base directory of AGIC repo. Generated files will be in ~/go/src/ dir. Copy them over to ./pkg folder.\n\n# Commands to copy:\n# cp ~/go/src/github.com/Azure/application-gateway-kubernetes-ingress/pkg/apis           ./pkg -r\n# cp ~/go/src/github.com/Azure/application-gateway-kubernetes-ingress/pkg/crd_client     ./pkg -r\n\n# echo -e \"Cleanup previously generated code...\"\n# rm -rf pkg/client $(find ./pkg -name 'zz_*.go')\n\necho -e \"Generate Application Gateway CRDs...\"\n../code-generator/generate-groups.sh \\\n    all \\\n    github.com/Azure/application-gateway-kubernetes-ingress/pkg/crd_client/agic_crd_client \\\n    github.com/Azure/application-gateway-kubernetes-ingress/pkg/apis \\\n    \"azureapplicationgatewayinstanceupdatestatus:v1beta1 azureapplicationgatewaybackendpool:v1beta1 azureingressprohibitedtarget:v1 loaddistributionpolicy:v1beta1 azureapplicationgatewayrewrite:v1beta1\" \\\n    --go-header-file ../code-generator/hack/boilerplate.go.txt\n\necho -e \"Generate Azure Multi-Cluster CRDs...\"\n../code-generator/generate-groups.sh \\\n    all \\\n    github.com/Azure/application-gateway-kubernetes-ingress/pkg/crd_client/azure_multicluster_crd_client \\\n    github.com/Azure/application-gateway-kubernetes-ingress/pkg/apis \"multiclusterservice:v1alpha1 multiclusteringress:v1alpha1\" \\\n    --go-header-file ../code-generator/hack/boilerplate.go.txt \\\n    -v 10\n\n# go get github.com/knative/pkg/apis/istio/v1alpha3\n\n# go mod vendor\n\necho -e \"Generate Istio CRDs...\"\n../code-generator/generate-groups.sh \\\n    all \\\n    github.com/Azure/application-gateway-kubernetes-ingress/pkg/crd_client/istio_crd_client \\\n    github.com/knative/pkg/apis \"istio:v1alpha3\" \\\n    --go-header-file ../code-generator/hack/boilerplate.go.txt", "num_lines": 41}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nAGIC_NAME=\"ingress-azure\"\nAGIC_NAMESPACE=\"default\"\nHELM_CONFIG=\"./helm-config.yaml\"\n\n[[ -f $HELM_CONFIG ]] || { echo \"File $HELM_CONFIG does not exist!\"; exit 1; }\n\n\nhelm template \"${AGIC_NAME}\" ./helm/ingress-azure \\\n     --namespace \"${AGIC_NAMESPACE=}\" \\\n     --values \"${HELM_CONFIG}\" \\\n    | tee /dev/tty | kubectl apply -f -\n\n\n", "num_lines": 16}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -aueo pipefail\n\nsource .env\n\nGOBIN=$(pwd)/bin\n\necho -e \"Cleanup: delete $GOBIN\"\nrm -rf \"$GOBIN\"\n\nORG_PATH=\"github.com/Azure\"\nPROJECT_NAME=\"application-gateway-kubernetes-ingress\"\nREPO_PATH=\"${ORG_PATH}/${PROJECT_NAME}\"\nVERSION_VAR=\"${REPO_PATH}/pkg/version.Version\"\nDATE_VAR=\"${REPO_PATH}/pkg/version.BuildDate\"\nCOMMIT_VAR=\"${REPO_PATH}/pkg/version.GitCommit\"\nVERSION=$(git describe --abbrev=0 --tags)\nBUILD_DATE=$(date +%Y-%m-%d-%H:%MT%z)\nGIT_HASH=$(git rev-parse --short HEAD)\n\necho -e \"Compiling...\"\ngo build -ldflags \"-s -X ${VERSION_VAR}=${VERSION} -X ${DATE_VAR}=${BUILD_DATE} -X ${COMMIT_VAR}=${GIT_HASH}\" -o ./bin/appgw-ingress -v ./cmd/appgw-ingress\nRESULT=$?\nif [ \"$RESULT\" -eq \"0\" ]; then\n    chmod -R 777 bin\n    echo -e \"Build SUCCEEDED\"\nelse\n    echo -e \"Build FAILED\"\n    exit 1\nfi\n\n# Print Version\n./bin/appgw-ingress --version || true\n\n# Feature Flags\nexport APPGW_ENABLE_SAVE_CONFIG_TO_FILE=\"true\"\n\n# Run\n./bin/appgw-ingress \\\n    --in-cluster=false \\\n    --kubeconfig=\"$KUBE_CONFIG_FILE\" \\\n    --verbosity=9\n", "num_lines": 44}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nrm -rf vendor\ngo mod vendor\nchmod -R 777 vendor\n", "num_lines": 5}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "export subResourceNamePrefix=\"fake-prod-\"\n\nfunction DeleteOtherAGICVersions() {\n    [[ -z \"${version}\" ]] && (\n        echo \"version is not set\"\n        exit 1\n    )\n\n    list=$(helm ls --all --short -n agic | grep -v agic-${version})\n    if [[ $list != \"\" ]]; then\n        helm delete $list -n agic\n    fi\n}\n\nfunction InstallAGIC() {\n    [[ -z \"${version}\" ]] && (\n        echo \"version is not set\"\n        exit 1\n    )\n    # Using 'applicationGatewayName' without providing 'subscription' and 'resource group' will make AGIC use values from azure.json\n    [[ -z \"${applicationGatewayName}\" ]] && (\n        echo \"applicationGatewayName is not set\"\n        exit 1\n    )\n    [[ -z \"${applicationGatewaySubnetPrefix}\" ]] && (\n        echo \"applicationGatewaySubnetPrefix is not set\"\n        exit 1\n    )\n    [[ -z \"${identityResourceId}\" ]] && (\n        echo \"identityResourceId is not set\"\n        exit 1\n    )\n    [[ -z \"${identityClientId}\" ]] && (\n        echo \"identityClientId is not set\"\n        exit 1\n    )\n\n    DeleteOtherAGICVersions || true\n\n    kubectl create namespace agic || true\n\n    # clean up brownfield namespace if exist\n    kubectl delete ns test-brownfield-ns || true\n\n    echo \"Installing BuildId ${version}\"\n\n    helm repo add staging https://appgwingress.blob.core.windows.net/ingress-azure-helm-package-staging/\n    helm repo update\n\n    # AAD pod identity is taking time to assign identity. Timeout is set to 120 sec\n    helm upgrade --install agic-${version} staging/ingress-azure \\\n        --set appgw.name=${applicationGatewayName} \\\n        --set appgw.subnetPrefix=${applicationGatewaySubnetPrefix} \\\n        --set appgw.subResourceNamePrefix=${subResourceNamePrefix} \\\n        --set armAuth.type=workloadIdentity \\\n        --set armAuth.identityClientID=${identityClientId} \\\n        --set rbac.enabled=true \\\n        --set appgw.shared=false \\\n        --set kubernetes.ingressClass=\"$1\" \\\n        --timeout 120s \\\n        --wait \\\n        -n agic \\\n        --version ${version}\n\n    # apply backends to test prohibited target, wait for 90s to apply appgw config\n    kubectl apply -f cmd/runner/testdata/extensions-v1beta1/prohibited-target/test-prohibit-backend.yaml || true\n    kubectl apply -f cmd/runner/testdata/networking-v1/prohibited-target/test-prohibit-backend.yaml || true\n    sleep 30\n}\n\nfunction SetupSharedBackend() {\n    [[ -z \"${version}\" ]] && (\n        echo \"version is not set\"\n        exit 1\n    )\n    [[ -z \"${applicationGatewayId}\" ]] && (\n        echo \"applicationGatewayId is not set\"\n        exit 1\n    )\n    [[ -z \"${identityResourceId}\" ]] && (\n        echo \"identityResourceId is not set\"\n        exit 1\n    )\n    [[ -z \"${identityClientId}\" ]] && (\n        echo \"identityClientId is not set\"\n        exit 1\n    )\n\n    # install agic with shared enabled\n    helm upgrade --install agic-${version} staging/ingress-azure \\\n        -f ./helm-config-with-prohibited-rules.yaml \\\n        --set appgw.applicationGatewayID=${applicationGatewayId} \\\n        --set appgw.subResourceNamePrefix=${subResourceNamePrefix} \\\n        --set armAuth.type=workloadIdentity \\\n        --set armAuth.identityClientID=${identityClientId} \\\n        --set kubernetes.ingressClass=\"$1\" \\\n        --timeout 120s \\\n        --wait \\\n        -n agic \\\n        --version ${version}\n\n    # get all the prohibited target config\n    kubectl get AzureIngressProhibitedTargets -n agic -o yaml\n}\n\nfunction EvaluateTestStatus() {\n    failedCount=$(grep \"type=\\\"Failure\\\"\" report.*.xml | wc -l | cut -d' ' -f8)\n    if [[ failedCount -ne 0 ]]; then\n        exit 1\n    fi\n\n    exit 0\n}\n", "num_lines": 114}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n. helper.sh\n\n# install\nInstallAGIC\n\n# set up shared backend\nSetupSharedBackend\n\n# run test\ngo mod init || true\ngo mod tidy\ngo test -v -timeout 240m -tags e2e ./... >testoutput.txt || true\nmv ./cmd/runner/report.xml report.e2e.xml\n\n# install with custom tag\nInstallAGIC \"custom-ingress-class\"\n\ngo test -v -timeout 240m -tags e2eingressclass ./... || true\nmv ./cmd/runner/report.xml report.e2eingressclass.xml\n\n# print test logs\ncat testoutput.txt\n\nEvaluateTestStatus\n", "num_lines": 28}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\nhelm template ./app/ > generated.yaml ", "num_lines": 4}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\nkubectl create namespace e2e-three-ings || true\n\nkubectl apply -f app.yaml", "num_lines": 7}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\necho -e \"The goal of this is to ensure health probe is generated from container readiness probe and backend should be removed when the probe is unhealthy\"\n\nfor ns in e2e-probe1 e2e-probe2; do\n    kubectl create namespace \"${ns}\" || true\n\nkubectl apply -f app.yaml", "num_lines": 10}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\necho -e \"The goal of this is to ensure that containers with the same probel and same labels in 3 different namespaces have unique and working health probes\"\n\nfor ns in e2e-ns-x e2e-ns-y e2e-ns-z; do\n    kubectl create namespace \"${ns}\" || true\n\nkubectl apply -f app.yaml", "num_lines": 10}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\nhelm template ./app/ > generated.yaml ", "num_lines": 4}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\nkubectl create namespace e2e-three-ings || true\n\nkubectl apply -f app.yaml", "num_lines": 7}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\necho -e \"The goal of this is to ensure health probe is generated from container readiness probe and backend should be removed when the probe is unhealthy\"\n\nfor ns in e2e-probe1 e2e-probe2; do\n    kubectl create namespace \"${ns}\" || true\n\nkubectl apply -f app.yaml", "num_lines": 10}
{"repo_name": "application-gateway-kubernetes-ingress", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -auexo pipefail\n\necho -e \"The goal of this is to ensure that containers with the same probel and same labels in 3 different namespaces have unique and working health probes\"\n\nfor ns in e2e-ns-x e2e-ns-y e2e-ns-z; do\n    kubectl create namespace \"${ns}\" || true\n\nkubectl apply -f app.yaml", "num_lines": 10}
{"repo_name": "applicationhealth-extension-linux", "repo_creator": "Azure", "programming_language": "Shell", "code": "openssl genrsa -out testbin/webserverkey.pem 2048\nopenssl req -new -x509 -sha256 -key testbin/webserverkey.pem -out testbin/webservercert.pem -days 3650 -subj '/CN=www.contoso.com/O=Contoso LTD./C=US'\nsudo bats integration-test/test/", "num_lines": 3}
{"repo_name": "appservice-build", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ncheckArg() {\n    # Check if the input has content and is not just whitepsace or is empty\n    case $1 in\n        (*[![:blank:]]*) echo \"$1\";;\n        (*) echo \"\"\n    esac\n}\n\ngetAbsolutePath(){\n    local path=\"$1\"\n\n    if [ -z \"$path\" ]; then\n        echo \"$PWD\"\n    fi\n\n    # Check if the path is relative or absolute.\n    # If relative path is given, create an absolute path\n    case $path in\n        /*) echo $path ;;\n        *) echo \"$PWD/$path\" ;;\n    esac\n}\n\nsourceDirectory=$(checkArg \"$1\")\nplatform=$(checkArg \"$2\")\nplatformVersion=$(checkArg \"$3\")\noutputDirectory=$(checkArg \"$4\")\n\necho\nif [ -z \"$sourceDirectory\" ]\nthen\n    sourceDirectory=\"$PWD\"\n    echo \"No source directory was provided -- the root of the repository ('GITHUB_WORKSPACE' environment variable) will be built: '$sourceDirectory'\"\nelse\n    sourceDirectory=$(getAbsolutePath \"$sourceDirectory\")\n    echo \"Source directory was provided. Following directory will be built: '$sourceDirectory'\"\nfi\n\noryxCommand=\"oryx build $sourceDirectory\"\n\nif [ -z \"$outputDirectory\" ]\nthen\n    echo \"No output directory was provided\"\nelse\n    outputDirectory=$(getAbsolutePath \"$outputDirectory\")\n    oryxCommand=\"$oryxCommand -o $outputDirectory\"\n    echo \"Output directory was provided: '$outputDirectory'\"\nfi\n\nif [ -z \"$platform\" ]\nthen\n    echo \"No platform provided -- Oryx will enumerate the source directory to determine the platform.\"\nelse\n    echo \"Platform provided: '$platform'\"\n    oryxCommand=\"$oryxCommand --platform $platform\"\nfi\n\nif [ -z \"$platformVersion\" ]\nthen\n    echo \"No platform version provided -- Oryx will determine the version.\"\nelse\n    echo \"Platform version provided: '$platformVersion'\"\n    oryxCommand=\"$oryxCommand --platform-version $platformVersion\"\nfi\n\nif [ -z \"$ORYX_DISABLE_TELEMETRY\" ] || [ \"$ORYX_DISABLE_TELEMETRY\" == \"false\" ]; then\n    url=\"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs\"\n    jobs=$(curl -X GET \"${url}\")\n    appserviceBuildJob=${jobs#*Build*/appservice-build@*,}\n    startedAtTime=$(echo \"${appserviceBuildJob}\" | sed 's/,/\\n/g' | grep \"started_at\" | awk '{print $2}' | sed -n '1p' | tr -d '\"')\n    completedAtTime=$(echo \"${appserviceBuildJob}\" | sed 's/,/\\n/g' | grep \"completed_at\" | awk '{print $2}' | sed -n '1p' | tr -d '\"')\n    export GITHUB_ACTIONS_BUILD_IMAGE_PULL_START_TIME=\"$startedAtTime\"\n    export GITHUB_ACTIONS_BUILD_IMAGE_PULL_END_TIME=\"$completedAtTime\"\n    export CALLER_ID=\"appservice-build-github-action-v3\"\nfi\n\necho\necho \"Running command '$oryxCommand'\"\neval $oryxCommand\n", "num_lines": 83}
{"repo_name": "appservice-build-test1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -l\n\nsourceDirectory=$1\nplatform=$2\nplatformVersion=$3\n\necho\n\nif [ -n \"${sourceDirectory}\" ]\nthen\n    sourceDirectory=\"$PWD/$sourceDirectory\"\n    echo \"Relative path to source directory provided -- the following directory will be built: '${sourceDirectory}'\"\nelse\n    sourceDirectory=$PWD\n    echo \"No source directory provided -- the root of the repository ('GITHUB_WORKSPACE' environment variable) will be built: '${sourceDirectory}'\"\nfi\n\necho\noryxCommand=\"oryx build ${sourceDirectory}\"\n\necho\n\nif [ -n \"${platform}\" ]\nthen\n    echo \"Platform provided: '${platform}'\"\n    oryxCommand=\"${oryxCommand} --platform ${platform}\"\nelse\n    echo \"No platform provided -- Oryx will enumerate the source directory to determine the platform.\"\nfi\n\necho\n\nif [ -n \"${platformVersion}\" ]\nthen\n    echo \"Platform version provided: '${platformVersion}'\"\n    oryxCommand=\"${oryxCommand} --platform-version ${platformVersion}\"\nelse\n    echo \"No platform version provided -- Oryx will determine the version.\"\nfi\n\necho\necho \"Running command '${oryxCommand}'\"\n\nif [ -z \"$ORYX_DISABLE_TELEMETRY\" ] || [ \"$ORYX_DISABLE_TELEMETRY\" == \"false\" ]; then\n    url=\"https://api.github.com/repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/jobs\"\n    json=$(curl -X GET \"${url}\")\n    startTime=${json#*Build*/appservice-build@*,}\n    startTime=$(echo \"${startTime}\"| sed 's/,/\\n/g' | grep \"started_at\" | awk '{print $2}' | sed -n '1p')\n    endTime=${json#*Build*/appservice-build@*,}\n    endTime=$(echo \"${endTime}\" | sed 's/,/\\n/g' | grep \"completed_at\" | awk '{print $2}' | sed -n '1p')\n    export GITHUB_ACTIONS_BUILD_IMAGE_PULL_START_TIME=$startTime\n    export GITHUB_ACTIONS_BUILD_IMAGE_PULL_END_TIME=$endTime\nfi\n\nexport ORYX_SDK_STORAGE_BASE_URL=\"https://oryxsdksdev.blob.core.windows.net\"\neval $oryxCommand", "num_lines": 56}
{"repo_name": "appservice-landing-zone-accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "# /bin/bash\n\ncommandToExecute='powershell.exe -ExecutionPolicy Unrestricted -File post-deployment.ps1 -az_cli_commands \"az version\" -install_ssms'\nfileUris=\"'https://raw.githubusercontent.com/Azure/appservice-landing-zone-accelerator/main/scenarios/shared/scripts/win-devops-vm-extensions/post-deployment.ps1'\"\nprotectedSettings='{\"fileUris\": \"['$fileUris']\", \"commandToExecute\": \"'$commandToExecute'\" }'\necho $protectedSettings\n\naz vm extension set -n CustomScriptExtension \\\n    --publisher Microsoft.Compute --version 1.10 \\\n    --vm-name vm-devops-1201 --resource-group rg-secure-appsvc-prod \\\n    --protected-settings $protectedSettings \\\n    --verbose\n\naz vm extension set -n CustomScriptExtension \\ \n    --publisher Microsoft.Compute --version 1.10 \\    \n    --vm-name vm-devops-1201 --resource-group rg-secure-appsvc-prod \\\n    --protected-settings '{\"fileUris\": \"['https://raw.githubusercontent.com/Azure/appservice-landing-zone-accelerator/main/scenarios/shared/scripts/win-devops-vm-extensions/post-deployment.ps1']\", \"commandToExecute\": \"powershell.exe -ExecutionPolicy Unrestricted -File post-deployment.ps1 -az_cli_commands \\\"az version\\\" -install_ssms\" }' \\\n    --verbose", "num_lines": 18}
{"repo_name": "appservice-landing-zone-accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "# /bin/bash\n\ncommandToExecute='powershell.exe -ExecutionPolicy Unrestricted -File post-deployment.ps1 -az_cli_commands \"az version\" -install_ssms'\nfileUris=\"'https://raw.githubusercontent.com/Azure/appservice-landing-zone-accelerator/main/scenarios/shared/scripts/win-devops-vm-extensions/post-deployment.ps1'\"\nprotectedSettings='{\"fileUris\": \"['$fileUris']\", \"commandToExecute\": \"'$commandToExecute'\" }'\necho $protectedSettings\n\naz vm extension set -n CustomScriptExtension \\\n    --publisher Microsoft.Compute --version 1.10 \\\n    --vm-name vm-devops-1201 --resource-group rg-secure-appsvc-prod \\\n    --protected-settings $protectedSettings \\\n    --verbose\n\naz vm extension set -n CustomScriptExtension \\ \n    --publisher Microsoft.Compute --version 1.10 \\    \n    --vm-name vm-devops-1201 --resource-group rg-secure-appsvc-prod \\\n    --protected-settings '{\"fileUris\": \"['https://raw.githubusercontent.com/Azure/appservice-landing-zone-accelerator/main/scenarios/shared/scripts/win-devops-vm-extensions/post-deployment.ps1']\", \"commandToExecute\": \"powershell.exe -ExecutionPolicy Unrestricted -File post-deployment.ps1 -az_cli_commands \\\"az version\\\" -install_ssms\" }' \\\n    --verbose", "num_lines": 18}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nenv_name=$1\ntenant_name=$2\nrelease_number=$3\nmanifests_repo=$4\nmanifests_branch=$5\n\npr_user_name=\"Git Ops\"\npr_user_email=\"agent@gitops.com\"\n\ngit config --global user.email $pr_user_email\ngit config --global user.name $pr_user_name\n\ngit checkout $env_name\n./utils/add-release-env.sh $tenant_name $release_number $manifests_repo $manifests_branch\n\ngit add *\nif [[ `git status --porcelain | head -1` ]]; then\n  git commit -m 'add release to fleet'\nfi\n", "num_lines": 22}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"f:g:s:u:r:t:d:\" option;\n    do\n    case \"$option\" in\n        f ) SRC_FOLDER=${OPTARG};;\n        g ) GITHUB_WORKSPACE=${OPTARG};;\n        s ) SOURCE_LOCATION=${OPTARG};;\n        u ) AZ_ACR_NAME=${OPTARG};;\n        r ) REPOSITORY=${OPTARG};;\n        t ) TASKNAME=${OPTARG};;\n        d ) DOCKER_FILE=${OPTARG};;\n    esac\ndone\necho $SRC_FOLDER\necho $GITHUB_WORKSPACE\necho $SOURCE_LOCATION\necho $AZ_ACR_NAME\necho $REPOSITORY\necho $TASKNAME\necho $DOCKER_FILE\n\nset -euxo pipefail  # fail on error\n  \n# Generate an tag with a reproducible checksum of all files in . by doing a checksum of all files\n# in alphabetical order, then another checksum of their names and checksums.\n# Running this command on windows-based infrastructure may return a different result due to CRLF\npushd $GITHUB_WORKSPACE/$SRC_FOLDER/$SOURCE_LOCATION\nimageTag=$(git log -n 1 --format=\"%H\" -- \".\")\npopd\n  \n# If the image with the generated tag doesn't already exist, build it.\nif ! az acr repository show -n $AZ_ACR_NAME --image \"$REPOSITORY:$imageTag\" -o table; then\n    echo No match found. Container will be built.\n    echo Tag for new container: $imageTag\n    az acr build \\\n        -r $AZ_ACR_NAME \\\n        -t \"$REPOSITORY:$imageTag\" \\\n        -t \"$REPOSITORY:latest\" \\\n        -f \"$GITHUB_WORKSPACE/$SRC_FOLDER/$SOURCE_LOCATION/$DOCKER_FILE\" \\\n        $GITHUB_WORKSPACE/$SRC_FOLDER/$SOURCE_LOCATION\nelse\n    echo \"The existing image with tag \"$imageTag\" is found.\"\nfi\nset +x\necho \"setting IMAGE_TAG output for task $TASKNAME\"\necho \"##vso[task.setvariable variable=IMAGE_TAG;isOutput=true]$imageTag\"\n\n# write a file containing the image tag\nmkdir -p $GITHUB_WORKSPACE/image_tags      \necho \"$imageTag\" > $GITHUB_WORKSPACE/image_tags/$TASKNAME\n", "num_lines": 51}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nwhile getopts \"s:d:r:b:i:t:e:p:\" option;\n    do\n    case \"$option\" in\n        s ) SOURCE_FOLDER=${OPTARG};;\n        d ) DEST_FOLDER=${OPTARG};;\n        r ) DEST_REPO=${OPTARG};;\n        b ) DEST_BRANCH=${OPTARG};;\n        i ) DEPLOY_ID=${OPTARG};;\n        t ) TOKEN=${OPTARG};;\n        e ) ENV_NAME=${OPTARG};;\n    esac\ndone\necho \"List input params\"\necho $SOURCE_FOLDER\necho $DEST_FOLDER\necho $DEST_REPO\necho $DEST_BRANCH\necho $DEPLOY_ID\necho $ENV_NAME\necho \"end of list\"\n\nset -euo pipefail  # fail on error\n\npr_user_name=\"Git Ops\"\npr_user_email=\"agent@gitops.com\"\n\ngit config --global user.email $pr_user_email\ngit config --global user.name $pr_user_name\n\n# Clone manifests repo\necho \"Clone manifests repo\"\nrepo_url=\"${DEST_REPO#http://}\"\nrepo_url=\"${DEST_REPO#https://}\"\nrepo_url=\"https://automated:$TOKEN@$repo_url\"\n\necho \"git clone $repo_url -b $DEST_BRANCH --depth 1 --single-branch\"\ngit clone $repo_url -b $DEST_BRANCH --depth 1 --single-branch\nrepo=${DEST_REPO##*/}\nrepo_name=${repo%.*}\ncd \"$repo_name\"\necho \"git status\"\ngit status\n\n# Create a new branch \ndeploy_branch_name=deploy/$DEPLOY_ID/$BACKEND_IMAGE/$DEST_BRANCH\n\necho \"Create a new branch $deploy_branch_name\"\ngit checkout -b $deploy_branch_name\n\n# Add generated manifests to the new deploy branch\nmkdir -p $DEST_FOLDER\ncp -r $SOURCE_FOLDER/* $DEST_FOLDER/\ngit add -A\ngit status\nif [[ `git status --porcelain | head -1` ]]; then\n    git commit -m \"deployment $DEPLOY_ID\"\n\n    # Push to the deploy branch \n    echo \"Push to the deploy branch $deploy_branch_name\"\n    echo \"git push --set-upstream $repo_url $deploy_branch_name\"\n    git push --set-upstream $repo_url $deploy_branch_name\n\n    # Create a PR \n    echo \"Create a PR to $DEST_BRANCH\"\n    \n    owner_repo=\"${DEST_REPO#https://github.com/}\"\n    echo $owner_repo\n    GITHUB_TOKEN=$TOKEN\n    echo $GITHUB_TOKEN | gh auth login --with-token\n    gh pr create --base $DEST_BRANCH --head $deploy_branch_name --title \"deployment '$DEPLOY_ID'\" --body \"Deploy to '$ENV_NAME'\"\nfi ", "num_lines": 73}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Generates K8s manifests from Helm + Kustomize templates\n# Uses env variables to substitute values \n# Requires to be installed:  \n#   - helm \n#   - kubectl\n#   - envsubst (https://command-not-found.com/envsubst)\n# \n\n# Usage:\n# generate-manifests.sh FOLDER_WITH_MANIFESTS GENERATED_MANIFESTS_FOLDER\n# e.g.:\n# generate-manifests-dev.sh cloud-native-ops/azure-vote/manifests\n\n\n# Substitute env variables in all yaml files in the manifest folder\nfor file in `find $1 -name '*.yaml'`; do envsubst <\"$file\" > \"$file\"1 && mv \"$file\"1 \"$file\"; done\n\n\n# Generate manifests\nfor app in `find $1 -maxdepth 1 -mindepth 1 -type d `; do \\\n    helm template \"$app\"/helm > \"$app\"/kustomize/base/manifests.yaml\ndone\npwd\n\n", "num_lines": 26}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Generates K8s manifests from Helm + Kustomize templates\n# Uses env variables to substitute values \n# Requires to be installed:  \n#   - helm \n#   - kubectl\n#   - envsubst (https://command-not-found.com/envsubst)\n# \n\n# For the Azure-Vote sample the following env varuables are supposed to be initialized: \n# export VOTE_APP_TITLE='Awesome Voting App'\n# export AZURE_VOTE_IMAGE_REPO=gitopsflowacr.azurecr.io/azvote\n# export FRONTEND_IMAGE=v3\n# export BACKEND_IMAGE=6.0.8\n# export TARGET_NAMESPACE=dev\nexport gen_manifests_file_name='gen_manifests.yaml'\n\n# Usage:\n# generate-manifests.sh FOLDER_WITH_MANIFESTS GENERATED_MANIFESTS_FOLDER\n# e.g.:\n# generate-manifests.sh cloud-native-ops/azure-vote/manifests gen_manifests\n# \n# the script will put Helm + Kustomize manifests with substituted variable values\n# to gen_manifests/hld folder and plain yaml manifests to gen_manifests/gen_manifests.yaml file\n\n# demo-cluster/manifests/dev/azure-vote-app.yml\nmkdir -p $2/$TARGET_CLUSTER/manifests/$TARGET_NAMESPACE\n# demo-cluster/templates/dev/azure-vote-app/helm\nmkdir -p $2/$TARGET_CLUSTER/templates/$TARGET_NAMESPACE\n\n# Substitute env variables in all yaml files in the manifest folder\nfor file in `find $1 -name '*.yaml'`; do envsubst <\"$file\" > \"$file\"1 && mv \"$file\"1 \"$file\"; done\n\n# Generate manifests\nfor app in `find $1 -type d -maxdepth 1 -mindepth 1 -printf \"%f\\n\"`; do \\\n  mkdir -p $2/$TARGET_CLUSTER/templates/$TARGET_NAMESPACE/$app/\n  cp -r $1/\"$app\"/helm $2/$TARGET_CLUSTER/templates/$TARGET_NAMESPACE/$app/\n  cp -r $1/\"$app\"/kustomize $2/$TARGET_CLUSTER/templates/$TARGET_NAMESPACE/$app/\n  \n  helm template $1/\"$app\"/helm > $1/\"$app\"/kustomize/base/manifests.yaml\n  kubectl kustomize $1/\"$app\"/kustomize/base >> $2/$TARGET_CLUSTER/manifests/$TARGET_NAMESPACE/$app.yaml \n  cat $2/$TARGET_CLUSTER/manifests/$TARGET_NAMESPACE/$app.yaml\ndone\npwd", "num_lines": 43}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\n#!/usr/bin/env bash\n\n# Usage:\n# publish_helm_chart.sh FOLDER_WITH_CHART CHART_REPO_NAME CHART_REPO_URL\n\nset -euo pipefail  # fail on error\n\nFOLDER_WITH_CHART=$1\nCHART_REPO_NAME=$2\nCHART_REPO_URL=$3\n\n\n\nDEST_BRANCH=\"gh-pages\"\n\npr_user_name=\"Git Ops\"\npr_user_email=\"agent@gitops.com\"\n\ngit config --global user.email $pr_user_email\ngit config --global user.name $pr_user_name\n\n# Clone chart repo\necho \"Clone chart repo\"\nrepo_url=\"${CHART_REPO_NAME#http://}\"\nrepo_url=\"${CHART_REPO_NAME#https://}\"\nrepo_url=\"https://automated:$TOKEN@$repo_url\"\n\necho \"git clone $repo_url -b $DEST_BRANCH --depth 1 --single-branch\"\n\ngit clone $repo_url -b $DEST_BRANCH --depth 1 --single-branch\n\necho \"git clone\"\n\nrepo=${CHART_REPO_NAME##*/}\nrepo_name=${repo%.*}\n\nfor app in `find $FOLDER_WITH_CHART -type d -maxdepth 1 -mindepth 1`; \ndo \n  echo $app\n  ls -ltr $app\n  helm package $app/helm\n  cp *.tgz $repo_name/\ndone\n\ncd $repo_name\nhelm repo index . --url $CHART_REPO_URL\n\ngit add -A\necho \"git status\"\ngit status\n\ngit commit -m \"add a new chart\"\ngit push origin", "num_lines": 56}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nwhile getopts \"r:b:p:\" option;\n    do\n    case \"$option\" in      \n        r ) REPO=${OPTARG};;\n        b ) TARGET_BRANCH=${OPTARG};;        \n        p ) PR_ID=${OPTARG};;\n    esac\ndone\necho \"List input params\"\necho $REPO\necho $TARGET_BRANCH\necho $PR_ID\necho \"end of list\"\n\nset -euo pipefail  # fail on error\n\nexport REVERT_BRANCH='refs/heads/revert-'$PR_ID\n\n# https://docs.microsoft.com/en-us/rest/api/azure/devops/git/repositories/get%20repository?view=azure-devops-rest-6.0\ngit_repo=$(curl -v -H \"Authorization: Bearer $SYSTEM_ACCESSTOKEN\" -H \"Content-Type: application/json\" --fail \\\n           \"$SYSTEM_COLLECTIONURI$SYSTEM_TEAMPROJECT/_apis/git/repositories/$REPO?api-version=6.0\")           \n\n\n# https://docs.microsoft.com/en-us/rest/api/azure/devops/git/reverts/create?view=azure-devops-rest-6.0\nrevert_response=$(curl -v -X POST -H \"Authorization: Bearer $SYSTEM_ACCESSTOKEN\" -H \"Content-Type: application/json\" --fail -d '{\"repository\":'$git_repo',\"source\":{\"pullRequestId\":\"'$PR_ID'\"},\"ontoRefName\":\"'$TARGET_BRANCH'\",\"generatedRefName\":\"'$REVERT_BRANCH'\"}' \"$SYSTEM_COLLECTIONURI$SYSTEM_TEAMPROJECT/_apis/git/repositories/$REPO/reverts?api-version=6.0-preview.1\")\nexport REVERT_ID=$(echo $revert_response | jq '.revertId')\n\necho $SYSTEM_ACCESSTOKEN | az devops login\naz devops configure --defaults organization=$SYSTEM_COLLECTIONURI project=$SYSTEM_TEAMPROJECT --use-git-aliases true\n\npr_response=$(az repos pr create --project $SYSTEM_TEAMPROJECT --repository $REPO --target-branch $TARGET_BRANCH --source-branch $REVERT_BRANCH --title Rollback --squash -o json)\nexport pr_num=$(echo $pr_response | jq '.pullRequestId')\n\n\necho \"===================================== OUTPUT =====================================\"\necho 'Revert ID = '$REVERT_ID\necho 'Rollback Pull Request ID = '$pr_num\necho 'Rollback Pull Request URL = '$SYSTEM_COLLECTIONURI''$SYSTEM_TEAMPROJECT'/_git/'$REPO'/pullrequest/'$pr_num\n   \n\n", "num_lines": 43}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Simple smoke test requesting demo app url and failing in case of error response\n\nset -x\n\naz aks get-credentials --resource-group $AKS_RESOURCE_GROUP --name $AKS_NAME\n\nkubectl port-forward svc/azure-vote-front 5678:80 --namespace=$TARGET_NAMESPACE&\nportForwardPid=$!\n\n\nsleep 3s\n\ncurl -v --fail http://127.0.0.1:5678\n\nkill $portForwardPid", "num_lines": 17}
{"repo_name": "arc-cicd-demo-src", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\norig_branch_name=$1\nbranch_name=$2\n\ngit ls-remote --exit-code --heads origin $branch_name 2> /dev/null\n\nif [ $? -eq 2 ]\nthen\n    echo \"Branch $branch_name doesn't exist\"\n    git checkout origin/$orig_branch_name\n    git checkout -b $branch_name\n    git push --set-upstream origin $branch_name\n    exit 0\nfi\n", "num_lines": 17}
{"repo_name": "ArcOnAVS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Use empty string for the version to fetch latest CLI version\ndeclare -A AzExtensions=(\n    [\"arcappliance\"]=\"\"\n    [\"connectedvmware\"]=\"\"\n    [\"k8s-extension\"]=\"\"\n    [\"customlocation\"]=\"\")\n\nfail () {\n   echo 'Execution failed.'\n   exit 1\n}\n\nactivate_python_venv() {\n  echo \"Activating python venv...\"\n  source .temp/.env/bin/activate\n}\n\ndeactivate_python_venv() {\n  echo \"Deactivating python venv...\"\n  deactivate\n}\n\ncheck_if_extension_is_installed() {\n  name=\"$1\"\n  version=\"$2\"\n  extensionVersion=$(az version --query \"extensions.\\\"$name\\\"\" -o tsv)\n  # extension is not isntalled\n  if [ \"$extendedVersion\" == \"\" ]\n  then\n    return 0\n  fi\n  # Extension is installed and extension version is equal to required version\n  if [ \"$extensionVersion\" == \"$version\" ]\n  then\n    return 1\n  fi\n  return 0\n}\n\ninstall_extensions_if_not_already_installed() {\n  name=\"$1\"\n  version=\"$2\"\n  if [ \"$version\" == \"\" ]\n    then\n      az extension add --name \"$name\" --upgrade\n  else\n    check_if_extension_is_installed $name $version\n      if [ $? == 0 ]\n        then\n          echo \"Installing Az extension $name of version $version...\"\n          az extension add --name \"$name\" --version \"$version\" --upgrade\n      else\n        echo \"Extension $name of version $version is already present\"\n      fi\n  fi\n}\n\nprint_operation_status_message() {\n  operation_name=\"$1\"\n  operation_exit_code=\"$2\"\n\n  RED=\"\\e[0;91m\"\n  GREEN=\"\\e[0;92m\"\n  RESET=\"\\e[0m\"\n\n  if [ $operation_exit_code -eq 0 ]\n  then\n    echo -e \"${GREEN}$operation_name operation was successfull.${RESET}\"\n  else\n    echo -e \"${RED}$operation_name operation failed! Please check stderr or equivalent for more details.${RESET}\"\n  fi\n}\n\nmkdir .temp\nif [ ! -z \"$2\" ] && [ -f \"$2\" ]\nthen\n  http_p=$(grep -Po '(?<=\"http\": \")[^\"]*' \"$2\")\n  https_p=$(grep -Po '(?<=\"https\": \")[^\"]*' \"$2\")\n  export http_proxy=$http_p\n  export HTTP_PROXY=$http_p\n  export https_proxy=$https_p\n  export HTTPS_PROXY=$https_p\nfi\n\nsudo -E apt-get -y update || fail\nsudo -E apt-get -y install jq || fail\n\nif [ ! -z $https_p ]\nthen\n  noproxy=$(cat \"$2\" | jq -r '.proxyDetails.noProxy')\n  export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt\nfi\n\nif [ ! -z $noproxy ] && [ ! $noproxy == 'null' ]\nthen\n  export no_proxy=$noproxy\n  export NO_PROXY=$noproxy\nfi\n\nif [ ! -f \".temp/govc\" ]\nthen\n  echo \"Downloading govc...\"\n  sudo -E apt-get -y install curl || fail\n  sudo -E apt-get -y install gzip || fail\n  URL_TO_BINARY=\"https://github.com/vmware/govmomi/releases/download/v0.24.0/govc_linux_amd64.gz\"\n  curl -L $URL_TO_BINARY | gunzip > ./.temp/govc\n  sudo -E chmod +x ./.temp/govc\nfi\n\n( ( az version || (curl -sL https://aka.ms/InstallAzureCLIDeb | sudo -E bash) ) && ( az account get-access-token || az login --use-device-code ) ) || { echo 'az installation or login failed' ; fail; }\n\nfor key in \"${!AzExtensions[@]}\"\ndo\n  name=\"$key\"\n  version=\"${AzExtensions[$key]}\"\n  install_extensions_if_not_already_installed $name $version\ndone\n\necho \"Installing python3.8...\"\nsudo -E apt-get -y install python3.8 || fail\nsudo -E apt-get -y install python3.8-venv python3-venv|| fail\n\necho \"Creating python venv...\"\npython3.8 -m venv .temp/.env || fail\n\n\nactivate_python_venv\npython -m pip install --upgrade pip || fail\npython -m pip install -r ./appliance_setup/dependencies || fail\n# TODO: Add support for automation testing in Linux Scripts.\npython ./appliance_setup/run.py \"$1\" \"$2\" \"${3:-INFO}\" \"${4:-false}\"\noperation_exit_code=$?\nprint_operation_status_message $1 $operation_exit_code\ndeactivate_python_venv\n\nexit $operation_exit_code", "num_lines": 138}
{"repo_name": "ArcOnAVSInternal", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Use empty string for the version to fetch latest CLI version\ndeclare -A AzExtensions=(\n    [\"arcappliance\"]=\"\"\n    [\"connectedvmware\"]=\"\"\n    [\"k8s-extension\"]=\"\"\n    [\"customlocation\"]=\"\")\n\nfail () {\n   echo 'Execution failed.'\n   exit 1\n}\n\nactivate_python_venv() {\n  echo \"Activating python venv...\"\n  source .temp/.env/bin/activate\n}\n\ndeactivate_python_venv() {\n  echo \"Deactivating python venv...\"\n  deactivate\n}\n\ncheck_if_extension_is_installed() {\n  name=\"$1\"\n  version=\"$2\"\n  extensionVersion=$(az version --query \"extensions.\\\"$name\\\"\" -o tsv)\n  # extension is not isntalled\n  if [ \"$extendedVersion\" == \"\" ]\n  then\n    return 0\n  fi\n  # Extension is installed and extension version is equal to required version\n  if [ \"$extensionVersion\" == \"$version\" ]\n  then\n    return 1\n  fi\n  return 0\n}\n\ninstall_extensions_if_not_already_installed() {\n  name=\"$1\"\n  version=\"$2\"\n  if [ \"$version\" == \"\" ]\n    then\n      az extension add --name \"$name\" --upgrade\n  else\n    check_if_extension_is_installed $name $version\n      if [ $? == 0 ]\n        then\n          echo \"Installing Az extension $name of version $version...\"\n          az extension add --name \"$name\" --version \"$version\" --upgrade\n      else\n        echo \"Extension $name of version $version is already present\"\n      fi\n  fi\n}\n\nprint_operation_status_message() {\n  operation_name=\"$1\"\n  operation_exit_code=\"$2\"\n\n  RED=\"\\e[0;91m\"\n  GREEN=\"\\e[0;92m\"\n  RESET=\"\\e[0m\"\n\n  if [ $operation_exit_code -eq 0 ]\n  then\n    echo -e \"${GREEN}$operation_name operation was successfull.${RESET}\"\n  else\n    echo -e \"${RED}$operation_name operation failed! Please check stderr or equivalent for more details.${RESET}\"\n  fi\n}\n\nmkdir .temp\nif [ ! -z \"$2\" ] && [ -f \"$2\" ]\nthen\n  http_p=$(grep -Po '(?<=\"http\": \")[^\"]*' \"$2\")\n  https_p=$(grep -Po '(?<=\"https\": \")[^\"]*' \"$2\")\n  export http_proxy=$http_p\n  export HTTP_PROXY=$http_p\n  export https_proxy=$https_p\n  export HTTPS_PROXY=$https_p\nfi\n\nsudo -E apt-get -y update || fail\nsudo -E apt-get -y install jq || fail\n\nif [ ! -z $https_p ]\nthen\n  noproxy=$(cat \"$2\" | jq -r '.proxyDetails.noProxy')\n  export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt\nfi\n\nif [ ! -z $noproxy ] && [ ! $noproxy == 'null' ]\nthen\n  export no_proxy=$noproxy\n  export NO_PROXY=$noproxy\nfi\n\nif [ ! -f \".temp/govc\" ]\nthen\n  echo \"Downloading govc...\"\n  sudo -E apt-get -y install curl || fail\n  sudo -E apt-get -y install gzip || fail\n  URL_TO_BINARY=\"https://github.com/vmware/govmomi/releases/download/v0.24.0/govc_linux_amd64.gz\"\n  curl -L $URL_TO_BINARY | gunzip > ./.temp/govc\n  sudo -E chmod +x ./.temp/govc\nfi\n\n( ( az version || (curl -sL https://aka.ms/InstallAzureCLIDeb | sudo -E bash) ) && ( az account get-access-token || az login --use-device-code ) ) || { echo 'az installation or login failed' ; fail; }\n\nfor key in \"${!AzExtensions[@]}\"\ndo\n  name=\"$key\"\n  version=\"${AzExtensions[$key]}\"\n  install_extensions_if_not_already_installed $name $version\ndone\n\necho \"Installing python3.8...\"\nsudo -E apt-get -y install python3.8 || fail\nsudo -E apt-get -y install python3.8-venv python3-venv|| fail\n\necho \"Creating python venv...\"\npython3.8 -m venv .temp/.env || fail\n\n\nactivate_python_venv\npython -m pip install --upgrade pip || fail\npython -m pip install -r ./appliance_setup/dependencies || fail\n# TODO: Add support for automation testing in Linux Scripts.\npython ./appliance_setup/run.py \"$1\" \"$2\" \"${3:-INFO}\" \"${4:-false}\"\noperation_exit_code=$?\nprint_operation_status_message $1 $operation_exit_code\ndeactivate_python_venv\n\nexit $operation_exit_code", "num_lines": 138}
{"repo_name": "arcvmware-util", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ -z \"$SQUID_AUTH_CREDS\" ]; then\n  cat <<EOF\nSQUID_AUTH_CREDS environment variable is required.\nIt is required for health check.\nIt should be in the following format: \"username:password\".\nIf the proxy is not protected by authentication, you can set it to \"none\".\nEOF\n  exit 1\nfi\n\nif [ \"$SQUID_AUTH_CREDS\" == \"none\" ]; then\n  SQUID_AUTH_CREDS=\"\"\nfi\n\nSQUID_IMG=\"${SQUID_IMG:-\"nascarsayan/squid-proxy:latest\"}\"\nSQUID_CONFIG=\"$(base64 -w 0 \"files/squid.conf\")\"\n\nfiles=$(ls files)\nFILES=\"\"\nfor file in $files\ndo\n  if [ ! \"$file\" == \"squid.conf\" ]; then\n    content=$(base64 -w 0 \"files/$file\")\n    FILES=\"$FILES;$file:$content\"\n  fi\ndone\nFILES=\"${FILES:1}\"\n\ndocker run -d \\\n  --env SQUID_CONFIG=\"$SQUID_CONFIG\" \\\n  --env FILES=\"$FILES\" \\\n  --env SQUID_AUTH_CREDS=\"$SQUID_AUTH_CREDS\" \\\n  --name squid-proxy \\\n  --restart on-failure:3 \\\n  --net host \\\n  \"$SQUID_IMG\"\n", "num_lines": 39}
{"repo_name": "arcvmware-util", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ndocker stop squid-proxy\ndocker rm squid-proxy\n", "num_lines": 4}
{"repo_name": "arcvmware-util", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ndocker logs squid-proxy -f -n 50\n", "num_lines": 3}
{"repo_name": "arcvmware-util", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ntrue\n", "num_lines": 3}
{"repo_name": "ARM-private-deployment", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexit_with_error() {\n  echo \"Usage: $0 -r {RESOURCE_GROUP} -l {LOCATION}\" 1>&2\n  exit 1\n}\n\nwhile getopts r:l: option\ndo\n  case \"${option}\"\n    in\n      r) rg=${OPTARG};;\n      l) location=${OPTARG};;\n      *) exit_with_error;;\n  esac\ndone\n\nif [ $(az group exists --name $rg -o tsv) = false ]; then\n  az group create \\\n    --name \"$rg\" \\\n    --location \"$location\"\nfi", "num_lines": 22}
{"repo_name": "ARM-private-deployment", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexit_with_error() {\n  echo \"Usage: $0 -r {RESOURCE_GROUP} -l {LOCATION} -v {VERSION} -t {PATH_TO_TEMPLATE_FILE} -n {TEMPLATE_NAME}\" 1>&2\n  exit 1\n}\n\nwhile getopts r:l:v:t:n: option\ndo\n  case \"${option}\"\n    in\n      r) rg=${OPTARG};;\n      l) location=${OPTARG};;\n      v) version=${OPTARG};;\n      t) template_path=${OPTARG};;\n      n) template_name=${OPTARG};;\n      *) exit_with_error;;\n  esac\ndone\n\naz ts create \\\n  --name \"$template_name\" \\\n  --version \"$version\" \\\n  --resource-group \"$rg\" \\\n  --location \"$location\" \\\n  --template-file \"$template_path\" \\\n  --yes", "num_lines": 27}
{"repo_name": "ARM-private-deployment", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexit_with_error() {\n  echo -e \"Usage: $0\\n\" \\\n    \"flag value                                    description\\n\" \\\n    \"-r   {RESOURCE_GROUP}                         Name of the resource group for the deployment.\\n\" \\\n    \"-l   {LOCATION}                               Location for the deployment.\\n\" \\\n    \"-t   {TEMPLATE_SPEC_RESOURCE_GROUP}           Name of the resource group containing the Template Spec.\\n\" \\\n    \"-n   {TEMPLATE_SPEC_NAME}                     Name of the Template Spec to deploy\\n\" \\\n    \"-v   {VERSION}                                Version number to use for template specs i.e. 1.0.\\n\" 1>&2\n  exit 1\n}\n\nwhile getopts :r:v:n:h:t:l: option\ndo\n  case \"${option}\"\n    in\n      r) rg=${OPTARG};;\n      v) version=${OPTARG};;\n      n) template_spec=${OPTARG};;\n      t) template_spec_rg=${OPTARG};;\n      l) location=${OPTARG};;\n      h) exit_with_error;;\n      :) exit_with_error;;\n      *) exit_with_error;;\n  esac\ndone\n\nif [ $(az group exists --name $rg -o tsv) = false ]; then\n  az group create \\\n    --name \"$rg\" \\\n    --location \"$location\"\nfi\n\nid=$(az ts show --name \"$template_spec\" --resource-group \"$template_spec_rg\" --version \"$version\" --query \"id\" -o tsv)\n\naz deployment group create \\\n  --resource-group \"$rg\" \\\n  --name \"arm-private-deployment\" \\\n  --template-spec \"$id\" \\\n  --output json\n", "num_lines": 42}
{"repo_name": "arm-ttk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nLOCAL_READLINK=readlink\n\n# https://stackoverflow.com/questions/3466166/how-to-check-if-running-in-cygwin-mac-or-linux\nunameOut=\"$(uname -s)\"\ncase \"${unameOut}\" in\n    Darwin*)    LOCAL_READLINK=greadlink;;\nesac\n\npwsh -noprofile -nologo -command \"Import-Module '$(dirname $(${LOCAL_READLINK} -f $0))/arm-ttk.psd1'; Test-AzTemplate $@ ; if (\\$Error.Count) { exit 1}\"\n", "num_lines": 12}
{"repo_name": "arm-ttk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash -e\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToInstall=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation/$pathToFile/$fileToInstall$token\"\nstagingDir=\"/staging\"\n\nmkdir -v \"$stagingDir\"\n\necho \"....................\"\necho \"path: $stagingDir/$fileToInstall\"\necho \"....................\"\necho \"uri: $fileUrl\"\necho \"....................\"\n\ncurl -v -o \"$stagingDir/$fileToInstall\" $fileUrl\n", "num_lines": 31}
{"repo_name": "ARO-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#############################\n# Script Definition\n#############################\nlogpath=/var/log/deploymentscriptlog\n\n#############################\n# Upgrading Linux Distribution\n#############################\n#echo \"#############################\" >> $logpath\n#echo \"Upgrading Linux Distribution\" >> $logpath\n#echo \"#############################\" >> $logpath\n#sudo apt-get update >> $logpath\n#sudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n#############################\n#Install Misc Tools\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Misc Tools\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates curl vim git\n\n#############################\n#Install Azure CLI\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n#############################\n#Install Docker\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n#############################\n#Install Kubectl\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Kubectl\" >> $logpath\necho \"#############################\" >> $logpath\nsudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg\necho \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list\nsudo apt-get update\nsudo apt-get install -y kubectl\n\n\n#############################\n#Install Helm\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Helm\" >> $logpath\necho \"#############################\" >> $logpath\ncurl https://baltocdn.com/helm/signing.asc | sudo apt-key add -\necho \"deb https://baltocdn.com/helm/stable/debian/ all main\" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list\nsudo apt-get update\nsudo apt-get install helm\n\n#############################\n#Install OC CLI\n#############################\necho \"#############################\" >> $logpath\necho \"Installing OC\" >> $logpath\necho \"#############################\" >> $logpath\nwget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/latest/openshift-client-linux.tar.gz\ntar -zxvf openshift-client-linux.tar.gz\nsudo mv oc /usr/local/bin\nrm README.md\nrm kubectl\nrm openshift-client-linux.tar.gz\n\n#############################\n#Upgrade packages\n#############################\necho \"#############################\" >> $logpath\necho \"Upgrading Packages\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt upgrade -y\n\n", "num_lines": 88}
{"repo_name": "ARO-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e -x\n\nsudo dnf install -y wget curl python36 python36-devel net-tools gcc libffi-devel openssl-devel jq\n\nsudo rpm --import https://packages.microsoft.com/keys/microsoft.asc\n\necho -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" | sudo tee /etc/yum.repos.d/azure-cli.repo\n\nsudo yum install -y azure-cli\nwget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/latest/openshift-client-linux.tar.gz\nmkdir openshift\ntar -zxvf openshift-client-linux.tar.gz -C openshift\nsudo install openshift/oc /usr/local/bin/oc\nsudo install openshift/kubectl /usr/local/bin/kubectl\n", "num_lines": 21}
{"repo_name": "ARO-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Set Vars for env check\nRHO_PROVIDER=$(az provider show --namespace Microsoft.RedHatOpenShift --query \"[registrationState]\" --output tsv)\nCOMP_PROVIDER=$(az provider show --namespace Microsoft.Compute --query \"[registrationState]\" --output tsv)\nSTOR_PROVIDER=$(az provider show --namespace Microsoft.Storage --query \"[registrationState]\" --output tsv)\nAUTH_PROVIDER=$(az provider show --namespace Microsoft.Authorization --query \"[registrationState]\" --output tsv)\n\n#Check if the resource Providers are Installed\nif [ \"$RHO_PROVIDER\" != \"Registered\" ]; then\n    echo \"RedHat OpenShift Provider Is Not Installed\"\n    az provider register --namespace Microsoft.RedHatOpenShift --wait\n    echo \"RedHat OpenShift Provider has been Installed\"\n    else\n    echo \"RedHat Openshift Provider was already installed\"\nfi\nif [ \"$COMP_PROVIDER\" != \"Registered\" ]; then\n    echo \"Microsoft Compute Provider Is Not Installed\"\n    az provider register --namespace Microsoft.Compute --wait\n    echo \"Microsoft Compute Provider has been Installed\"\n    else\n    echo \"Microsoft Compute Provider was already installed\"\nfi\nif [ \"$STOR_PROVIDER\" != \"Registered\" ]; then\n    echo \"Microsoft Storage Provider Is Not Installed\"\n    az provider register --namespace Microsoft.Storage --wait\n    echo \"Microsoft Storage Provider has been Installed\"\n    else\n    echo \"Microsoft Storage Provider was already installed\"\nfi\nif [ \"$AUTH_PROVIDER\" != \"Registered\" ]; then\n    echo \"Microsoft Authentication Provider Is Not Installed\"\n    az provider register --namespace Microsoft.Authorization --wait\n    echo \"Microsoft Authorization Provider has been Installed\"\n    else\n    echo \"Microsoft Authorization Provider was already installed\"\nfi\n\n# Prompt user for an Service Principal Name and Subscription ID\necho \"Enter the Name of the Service Principal for ARO to use:\"\nread -r SPNNAME\n#echo \"Enter the Subscription ID where you want ARO deployed:\"\n#read -r SUBSCRIPTIONID\nSUB_ID=$(az account show | jq -r \".id\")\n\n# Create the Service Principal\n# TODO: Add check to see if the SPN already exists\naz ad sp create-for-rbac --name $SPNNAME --scopes /subscriptions/$SUB_ID --role Contributor --output json > /tmp/sp.json\n\n# Set variables from the Service Principal\nSP_CLIENT_ID=$(jq -r '.appId' /tmp/sp.json)\nSP_CLIENT_SECRET=$(jq -r '.password' /tmp/sp.json)\nSP_OBJECT_ID=$(az ad sp show --id $SP_CLIENT_ID | jq -r '.id')\n\n# Set variable for ARO Provider SP Object ID\nARO_SP_OBJECT_ID=$(az ad sp list --display-name \"Azure Red Hat OpenShift RP\" --query \"[0].id\" -o tsv)\n\n#get the value for the pull secret\nRHPS=$(cat pullsecret.txt)\n\necho \"The ARO RP SP Object ID is:\" $ARO_SP_OBJECT_ID\necho \"The APPSP client ID is:\" $SP_CLIENT_ID\necho \"The APPSP object ID is:\" $SP_OBJECT_ID\necho \"The APPSP password is:\" $SP_CLIENT_SECRET\necho \"The redhat pull secret is:\" $RHPS\necho \"  \"\necho \"MAKE SURE TO NOTE THESE NOW AS THE APPSP PASSWORD CAN NEVER BE RETRIEVED AGAIN!!!!\"\necho \"Now would be a good time to check / update your paramaters files with these\"\necho \" values before continuing this deployment.\"\necho \"  \"\necho \"press return if ready to proceed.... press CTRL-C to cancel....\"\nread -r ready\n\n#Deploy the hub Vnet/routes/etc\naz deployment sub create -n \"LZ-HUB-ARO\" -l \"eastus\" \\\n-f 01-Network-Hub/main.bicep \\\n-p 01-Network-Hub/parameters-main.json\n\n#deploy the bastion VM\naz deployment sub create -n \"LZ-HUB-ARO-VM\" -l \"eastus\" \\\n-f 01-Network-Hub/deploy-vm.bicep \\\n-p 01-Network-Hub/parameters-deploy-vm.json\n\n#Update the HUB UDR\naz deployment sub create -n \"LZ-HUB-ARO-UDR\" -l \"eastus\" \\\n-f 01-Network-Hub/updateUDR.bicep \\\n-p 01-Network-Hub/parameters-updateUDR.json\n\n#Deploy the Spoke Vnet/routes/etc\naz deployment sub create -n \"LZ-SPOKE-ARO\" -l \"eastus\" \\\n-f 02-Network-Spoke/main.bicep \\\n-p 02-Network-Spoke/parameters-main.json\n\n#sleep and wait for completion, else route update below will fail\nsleep 300\n\n#Update the Spoke Route Table\n\naz deployment sub create -n \"LZ-SPOKE-ARO-updateUDR\" -l \"eastus\" \\\n-f 02-Network-Spoke/updateUDR.bicep \\\n-p 02-Network-Spoke/parameters-updateUDR.json\n\n#Deploy the supporting services\naz deployment sub create -n \"LZ-SUPPORTING-ARO\" -l \"eastus\" \\\n-f 03-Supporting/main.bicep \\\n-p 03-Supporting/parameters-main.json\n\n#Deploy the ARO cluster\naz deployment group create -n \"LZ-ARO\" -g \"spoke-aro\" \\\n-f 04-ARO/arocluster.bicep \\\n-p aadClientId=${SP_CLIENT_ID} \\\n-p rpObjectId=${ARO_SP_OBJECT_ID} \\\n-p aadObjectId=${SP_OBJECT_ID} \\\n-p aadClientSecret=${SP_CLIENT_SECRET} \\\n-p rhps=${RHPS} \\\n-p 04-ARO/params.json\n\n\n", "num_lines": 117}
{"repo_name": "ARO-Landing-Zone-Accelerator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#############################\n# Script Definition\n#############################\nlogpath=/var/log/deploymentscriptlog\n\n#TODO: update this script for RHEL usage\n\n#############################\n# Upgrading Linux Distribution\n#############################\necho \"#############################\" >> $logpath\necho \"Upgrading Linux Distribution\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update >> $logpath\nsudo apt-get -y upgrade >> $logpath\necho \" \" >> $logpath\n\n#############################\n#Install Azure CLI\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Azure CLI\" >> $logpath\necho \"#############################\" >> $logpath\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n#############################\n#Install Docker\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Docker\" >> $logpath\necho \"#############################\" >> $logpath\nwget -qO- https://get.docker.com/ | sh >> $logpath\nsudo usermod -aG docker $1\necho \" \" >> $logpath\n\n#############################\n#Install Kubectl\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Kubectl\" >> $logpath\necho \"#############################\" >> $logpath\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates curl\nsudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg https://packages.cloud.google.com/apt/doc/apt-key.gpg\necho \"deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee /etc/apt/sources.list.d/kubernetes.list\nsudo apt-get update\nsudo apt-get install -y kubectl\n\n\n#############################\n#Install Helm\n#############################\necho \"#############################\" >> $logpath\necho \"Installing Helm\" >> $logpath\necho \"#############################\" >> $logpath\ncurl https://baltocdn.com/helm/signing.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https --yes\necho \"deb https://baltocdn.com/helm/stable/debian/ all main\" | sudo tee /etc/apt/sources.list.d/helm-stable-debian.list\nsudo apt-get update\nsudo apt-get install helm", "num_lines": 61}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nfunction clean() {\n  local API_VERSION=$1\n  local FOLDER=$2\n\n  rm -rf pkg/client/services/redhatopenshift/mgmt/\"$API_VERSION\"\n  mkdir pkg/client/services/redhatopenshift/mgmt/\"$API_VERSION\"\n\n  rm -rf python/client/azure/mgmt/redhatopenshift/v\"${API_VERSION//-/_}\"\n  mkdir -p python/client/azure/mgmt/redhatopenshift/v\"${API_VERSION//-/_}\"\n}\n\nfunction checksum() {\n  local API_VERSION=$1\n  local FOLDER=$2\n\n  sha256sum swagger/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/\"$FOLDER\"/\"$API_VERSION\"/redhatopenshift.json >> .sha256sum\n}\n\nfunction generate_golang() {\n  local AUTOREST_IMAGE=$1\n  local API_VERSION=$2\n  local FOLDER=$3\n\n  # Generating Track 1 Golang SDK\n  # Needs work to migrate to Track 2\n  docker run \\\n    --platform=linux/amd64 \\\n    --rm \\\n    -v $PWD/pkg/client:/github.com/Azure/ARO-RP/pkg/client:z \\\n    -v $PWD/swagger:/swagger:z \\\n    \"${AUTOREST_IMAGE}\" \\\n    --go \\\n    --use=@microsoft.azure/autorest.go@~2.1.187 \\\n    --use=@microsoft.azure/autorest.modeler@~2.3.38 \\\n    --version=~2.0.4421 \\\n    --license-header=MICROSOFT_APACHE_NO_VERSION \\\n    --namespace=redhatopenshift \\\n    --input-file=/swagger/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/\"$FOLDER\"/\"$API_VERSION\"/redhatopenshift.json \\\n    --output-folder=/github.com/Azure/ARO-RP/pkg/client/services/redhatopenshift/mgmt/\"$API_VERSION\"/redhatopenshift\n\n  docker run \\\n    --platform=linux/amd64 \\\n    --rm \\\n    -v $PWD/pkg/client:/github.com/Azure/ARO-RP/pkg/client:z \\\n    --entrypoint sed \\\n    \"${AUTOREST_IMAGE}\" \\\n    --in-place \\\n    --expression='s|azure/aro-rp|Azure/ARO-RP|g' \\\n    \"/github.com/Azure/ARO-RP/pkg/client/services/redhatopenshift/mgmt/${API_VERSION}/redhatopenshift/models.go\" \\\n    \"/github.com/Azure/ARO-RP/pkg/client/services/redhatopenshift/mgmt/${API_VERSION}/redhatopenshift/redhatopenshiftapi/interfaces.go\"\n\n  go run ./vendor/golang.org/x/tools/cmd/goimports -w -local=github.com/Azure/ARO-RP pkg/client\n}\n\nfunction generate_python() {\n  local AUTOREST_IMAGE=$1\n  local API_VERSION=$2\n  local FOLDER=$3\n\n  # Generating Track 2 Python SDK\n  docker run \\\n    --platform=linux/amd64 \\\n    --rm \\\n    -v $PWD/python/client:/python/client:z \\\n    -v $PWD/swagger:/swagger:z \\\n    \"${AUTOREST_IMAGE}\" \\\n    --use=@autorest/python@~5.12.0 \\\n    --use=@autorest/modelerfour@~4.20.0 \\\n    --version=~3.6.2 \\\n    --python \\\n    --azure-arm \\\n    --license-header=MICROSOFT_APACHE_NO_VERSION \\\n    --namespace=azure.mgmt.redhatopenshift.v\"${API_VERSION//-/_}\" \\\n    --input-file=/swagger/redhatopenshift/resource-manager/Microsoft.RedHatOpenShift/\"$FOLDER\"/\"$API_VERSION\"/redhatopenshift.json \\\n    --output-folder=/python/client\n\n  rm -rf python/client/azure/mgmt/redhatopenshift/v\"${API_VERSION//-/_}\"/aio\n  >python/client/__init__.py\n}\n\nif [ -f .sha256sum ]; then\n  rm .sha256sum\nfi\n\nAUTOREST_IMAGE=$1\n\nfor API_VERSION in \"${@: 2}\"\ndo\n  FOLDER=stable\n  if [[ \"$API_VERSION\" =~ .*preview ]]; then\n    FOLDER=preview\n  fi\n\n  printf \"\\nGENERATING API v$API_VERSION\\n\"\n  printf \"%*s\\n\" \"${COLUMNS:-$(tput cols)}\" \"\" | tr \" \" -\n\n  printf \"CLEANING OLD API GENERATED FILES...\\n\"\n  clean \"$API_VERSION\" \"$FOLDER\"\n  printf \"[\\u2714] SUCCESS\\n\\n\"\n\n  printf \"GENERATING CHECKSUM...\\n\"\n  checksum \"$API_VERSION\" \"$FOLDER\"\n  printf \"[\\u2714] SUCCESS\\n\\n\"\n\n  printf \"GENERATING GOLANG SDK...\\n\"\n  generate_golang \"$AUTOREST_IMAGE\" \"$API_VERSION\" \"$FOLDER\"\n  printf \"[\\u2714] SUCCESS\\n\\n\"\n\n  printf \"GENERATING PYTHON SDK...\\n\"\n  generate_python \"$AUTOREST_IMAGE\" \"$API_VERSION\" \"$FOLDER\"\n  printf \"[\\u2714] SUCCESS\\n\\n\"\n  printf \"%*s\\n\" \"${COLUMNS:-$(tput cols)}\" \"\" | tr \" \" -\n  printf \"\\n\"\ndone\n\nprintf \"[\\u2714] CLIENT GENERATION COMPLETED SUCCESSFULLY\\n\"\n", "num_lines": 119}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z \"$RESOURCEGROUP\" ]; then\n    echo \"the environment variable RESOURCEGROUP is required\" >&2\n    exit 1\nfi\n\n[ -f aks.kubeconfig ] && rm -f aks.kubeconfig\n\nif az aks get-credentials --admin -g \"$RESOURCEGROUP\" -n aro-aks-cluster-001 --public-fqdn -f aks.kubeconfig 2>/dev/null; then\n    chmod 600 aks.kubeconfig\nelse\n    echo \"Error generating AKS kubeconfig\"\n    exit 1\nfi\n", "num_lines": 16}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ \"$#\" -ne 1 ]]; then\n    echo \"usage: $0 resourceid\" >&2\n    exit 1\nfi\n\nif [[ $CI ]]; then\n    ./db \"$1\" | jq -r .openShiftCluster.properties.adminKubeconfig | base64 -d | sed -e 's|https://api-int\\.|https://api\\.|'\nelse\n    go run ./hack/db \"$1\" | jq -r .openShiftCluster.properties.adminKubeconfig | base64 -d | sed -e 's|https://api-int\\.|https://api\\.|'\nfi\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nHIVE_OPERATOR_NS=\"hive\"\nKUBECTL=$( which kubectl 2> /dev/null || which oc 2> /dev/null)\n\nfunction cleanup {\n\t[ -f \"$(pwd)/kubectl\" ] && rm -f \"$(pwd)/kubectl\"\n}\n\nfunction download_tmp_kubectl {\n\tcurl -sLO \"https://dl.k8s.io/release/$(curl -L -s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl\"\n\tif [ $? -ne 0 ]; then\n\t\techo \": error downloading kubectl\"\n\t\texit 1\n\tfi\n\tchmod 755 kubectl\n\tKUBECTL=\"$(pwd)/kubectl\"\n}\n\nfunction verify_tools {\n\tif [ ! -z \"$KUBECTL\" ]; then\n\t\treturn\n\tfi\n\techo -n \"kubectl or oc not detected, downloading\"\n\tdownload_tmp_kubectl\n\techo \", done.\"\n\n\tif [ $( $KUBECTL get nodes 2>/dev/null | wc -l ) -eq 0 ]; then\n\t\techo \"unable to connect to the cluster\"\n\t\texit 1\n\tfi\n}\n\nset -e\ntrap cleanup EXIT\n\nif [ ! -f go.mod ] || [ ! -d \".git\" ]; then\n\techo \"this script must by run from the repo's root directory\"\n\texit 1\nfi\n\nif [ ! -f \"./hack/hive-config/hive-deployment.yaml\" ] || [ ! -d \"./hack/hive-config/crds\" ] ; then\n\techo \"hive config is missing, generating config, please rerun this script afterwards\"\n\t./hack/hive-generate-config.sh\n\tif [ $? -ne 0 ]; then\n\t\techo \"error generating the hive configs\"\n\t\texit 1\n\tfi\nfi\n\nif [ -z \"$PULL_SECRET\" ]; then\n\techo \"global pull secret variable required, please source ./env\"\n\texit\nfi\n\nverify_tools\n\nif [ $( $KUBECTL get namespace $HIVE_OPERATOR_NS -o yaml 2>/dev/null | wc -l ) -ne 0 ]; then\n\techo \"hive is already installed in the namespace\"\n\techo -n \"would you like to reapply the configs? (y/N): \"\n\tread answer\n\tif [[ \"$answer\" != \"y\" ]]; then\n\t\texit\n\tfi\nelse\n\t$KUBECTL create namespace $HIVE_OPERATOR_NS\nfi\n\n$KUBECTL apply -f ./hack/hive-config/crds\n$KUBECTL apply -f ./hack/hive-config/hive-deployment.yaml\n\necho \"$PULL_SECRET\" > /tmp/.tmp-secret\n# Using dry-run allows updates to work seamlessly\n$KUBECTL create secret generic hive-global-pull-secret --from-file=.dockerconfigjson=/tmp/.tmp-secret --type=kubernetes.io/dockerconfigjson --namespace $HIVE_OPERATOR_NS -o yaml --dry-run=client | $KUBECTL apply -f - 2>/dev/null\nrm -f /tmp/.tmp-secret\n\nsed \"s/HIVE_OPERATOR_NS/$HIVE_OPERATOR_NS/g\" hack/hive-config/hive-config.yaml | $KUBECTL apply -f -\n\necho -e \"\\nHive is installed.\"\n", "num_lines": 80}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This is the commit sha that the image was built from and ensures we use the correct configs for the release\nHIVE_IMAGE_COMMIT_HASH=\"fec14dc\"\n\n# For now we'll use the quay hive image, but this will change to an ACR once the quay.io -> ACR mirroring is setup\n# Note: semi-scientific way to get the latest image: `podman search --list-tags --limit 10000 quay.io/app-sre/hive | tail -n1`\nHIVE_IMAGE=\"quay.io/app-sre/hive:${HIVE_IMAGE_COMMIT_HASH}\"\n\nHIVE_OPERATOR_NS=\"hive\"\n\n# This version is specified in the hive repo and is the only hard dependency for this script\n# https://github.com/openshift/hive/blob/master/vendor/github.com/openshift/build-machinery-go/make/targets/openshift/kustomize.mk#L7\nKUSTOMIZE_VERSION=4.1.3\nKUSTOMIZE=$( which kustomize 2>/dev/null )\nTMPDIR=$( mktemp -d )\n\nfunction cleanup {\n\tpopd >& /dev/null\n\t[ -d \"$TMPDIR\" ] && rm -fr \"$TMPDIR\"\n}\n\nfunction verify_kustomize {\n\tif [ ! -z \"$KUSTOMIZE\" ]; then\n\t\treturn\n\tfi\n\techo -n \"kustomize not detected, downloading \"\n\tcurl -s \"https://raw.githubusercontent.com/kubernetes-sigs/kustomize/kustomize/v${KUSTOMIZE_VERSION}/hack/install_kustomize.sh\" | bash -s \"$KUSTOMIZE_VERSION\" \"$TMPDIR\"\n\tif [ $? -ne 0 ]; then\n\t\techo \"error downloading kustomize\"\n\t\texit 1\n\tfi\n\tKUSTOMIZE=\"${TMPDIR}/kustomize\"\n}\n\nfunction hive_repo_clone {\n\techo -n \"Cloning hive repo into tmp for config generation\"\n\tCLONE_ERROR=$(git clone https://github.com/openshift/hive.git \"$TMPDIR\" 2>/dev/null )\n\tif [ $? -ne 0 ]; then\n\t\techo \": error cloning the hive repo: ${CLONE_ERROR}\"\n\t\texit 1\n\tfi\n\techo \", done.\"\n}\n\nfunction hive_repo_hash_checkout {\n\t# go into $TMPDIR and checkout the commit the image was built with\n\tpushd $TMPDIR >& /dev/null\n\tgit reset --hard $HIVE_IMAGE_COMMIT_HASH\n\tif [ $? -ne 0 ] || [[ $( git rev-parse --short=${#HIVE_IMAGE_COMMIT_HASH} HEAD ) != ${HIVE_IMAGE_COMMIT_HASH} ]]; then\n\t\techo \"error resetting the hive repo to the correct git hash '${HIVE_IMAGE_COMMIT_HASH}'\"\n\t\texit 1\n\tfi\n}\n\nfunction generate_hive_config {\n\t# Create the hive operator install config using kustomize\n\tmkdir -p overlays/deploy\n\tcp overlays/template/kustomization.yaml overlays/deploy\n\tpushd overlays/deploy >& /dev/null\n\t$KUSTOMIZE edit set image registry.ci.openshift.org/openshift/hive-v4.0:hive=$HIVE_IMAGE\n\t$KUSTOMIZE edit set namespace $HIVE_OPERATOR_NS\n\tpopd >& /dev/null\n\n\t$KUSTOMIZE build overlays/deploy > hive-deployment.yaml\n\n\t# return to the repo directory to copy the generated config from $TMPDIR\n\tpopd >& /dev/null\n\tmv \"$TMPDIR/hive-deployment.yaml\" ./hack/hive-config/\n\n\tif [ -d ./hack/hive-config/crds ]; then\n\t\trm -fr ./hack/hive-config/crds\n\tfi\n\tcp -R \"$TMPDIR/config/crds\" ./hack/hive-config/\n}\n\nset -e\ntrap cleanup EXIT\n\nif [ ! -f go.mod ] || [ ! -d \".git\" ]; then\n\techo \"this script must by run from the repo's root directory\"\n\texit 1\nfi\nif [[ ! \"$TMPDIR\" || ! -d \"$TMPDIR\" ]]; then\n\techo \"could not create temp working dir\"\n\texit 1\nfi\n\nhive_repo_clone\nhive_repo_hash_checkout\nverify_kustomize\ngenerate_hive_config\n\necho -e \"\\nHive config generated.\"\n", "num_lines": 95}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# lint-go.sh is used to run Go linting. This shell script is invoked by the Makefile.\n# It is not used in our pipelines as we have a github action that does the Go linting, so this script\n# is intended to be used locally when developing.\n\n# What does this script?\n# It will try to execute the golangci-lint binary to check if there are any linter errors.\n# In case the binary that is trying to execute does not exist,\n# the script will print a message with instructions to download the binary and will exit with a non-zero exit code.\n\nif ! command -v golangci-lint &> /dev/null\nthen\n    echo \"ERROR: golangci-lint could not be found, Go linting aborted. To install it visit https://golangci-lint.run/usage/install/#local-installation\"\n    exit 1\nelse\n    golangci-lint run\nfi\n", "num_lines": 19}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# shared-cluster.sh is used to provide a repeatable production cluster create script\n\nLOCATION=\"westcentralus\"\nCLUSTER=\"shared-cluster\"\nRESOURCEGROUP=\"shared-cluster\"\nCLUSTERRESOURCEGROUP=\"aro-shared-cluster\"\n\nusage() {\n\techo -e \"usage: ${0} <create|delete>\"\n\texit 1\n}\n\nif [ \"$#\" -ne 1 ]; then\n\tusage\n\nelif [[ $1 == create ]]; then\n    echo \"creating resource group and network\"\n    az group create --name $RESOURCEGROUP --location $LOCATION\n\n    az network vnet create \\\n      --resource-group $RESOURCEGROUP \\\n      --name aro-vnet \\\n      --address-prefixes 10.0.0.0/22\n\n    az network vnet subnet create \\\n      --resource-group $RESOURCEGROUP \\\n      --vnet-name aro-vnet \\\n      --name master-subnet \\\n      --address-prefixes 10.0.0.0/23 \\\n      --service-endpoints Microsoft.ContainerRegistry\n\n    az network vnet subnet create \\\n      --resource-group $RESOURCEGROUP \\\n      --vnet-name aro-vnet \\\n      --name worker-subnet \\\n      --address-prefixes 10.0.2.0/23 \\\n      --service-endpoints Microsoft.ContainerRegistry\n\n    az network vnet subnet update \\\n      --name master-subnet \\\n      --resource-group $RESOURCEGROUP \\\n      --vnet-name aro-vnet \\\n      --disable-private-link-service-network-policies true\n    echo \"resource group and vnet/subnets created...\"\n    \n    echo \"creating cluster...\"\n    az aro create \\\n      --resource-group $RESOURCEGROUP \\\n      --cluster-resource-group $CLUSTERRESOURCEGROUP \\\n      --name $CLUSTER \\\n      --vnet aro-vnet \\\n      --master-subnet master-subnet \\\n      --worker-subnet worker-subnet\n\nelif [[ $1 == \"delete\" ]]; then\n  az aro delete --name $CLUSTER -g $RESOURCEGROUP --yes\n  az network vnet delete --name aro-vnet -g $RESOURCEGROUP\n  az group delete --resource-group $RESOURCEGROUP --yes\n\nelse\n  usage\nfi\n", "num_lines": 65}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# ssh-agent.sh is intended to behave very similarly to ssh: specify the master or\n# worker hostname that you want to connect to, along with any other ssh options\n# you want to pass in\n\nusage() {\n    echo \"usage: CLUSTER=cluster $0 hostname_pattern\" >&2\n    echo \"       Examples: CLUSTER=cluster $0 master1\" >&2\n    echo \"                 CLUSTER=cluster $0 eastus1 # worker node 1\" >&2\n    echo \"                 CLUSTER=cluster $0 bootstrap\" >&2\n    exit 1\n}\n\nif [[ \"$#\" -ne 1 ]]; then\n   usage\nfi\n\ncleanup() {\n    rm -rf id_rsa\n}\n\ntrap cleanup EXIT\n\neval \"$(ssh-agent | grep -v '^echo ')\"\n\nif [[ -z \"$RESOURCEID\" ]]; then\n    if [[ -z \"$CLUSTER\" ]]; then\n        echo \"CLUSTER must be specified\"\n        usage\n    fi\n    \n    RESOURCEID=\"/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourceGroups/${RESOURCEGROUP}/providers/Microsoft.RedHatOpenShift/openShiftClusters/${CLUSTER}\"\nfi\n\nCLUSTER_RESOURCEGROUP=$(go run ./hack/db \"$RESOURCEID\" | jq -r .openShiftCluster.properties.clusterProfile.resourceGroupId | cut -d/ -f5)\n\ngo run ./hack/db \"$RESOURCEID\" | jq -r .openShiftCluster.properties.sshKey | base64 -d | openssl rsa -inform der -outform pem >id_rsa 2>/dev/null\nchmod 0600 id_rsa\n\n# seeing ARM cache issues with -g $CLUSTER_RESOURCEGROUP, so using --query\nIP=$(az network nic list --query \"[?resourceGroup == '$CLUSTER_RESOURCEGROUP' && contains(name, '$1')].ipConfigurations[0].privateIPAddress\" -o tsv)\n\nif [[ $(grep -c . <<<\"$IP\") -ne 1 ]]; then\n     echo -e \"VM with pattern $1 not found in resourceGroup $CLUSTER_RESOURCEGROUP\\n\"\n     usage\nfi\n\nssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i id_rsa -l core \"$IP\"\n", "num_lines": 50}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\n# ssh-aks.sh allows you to ssh into the specifed AKS clusters worker nodes\n\nusage() {\n\techo -e \"usage: ${0} <cluster-name> <worker-node-index>\\n\" >&2\n\techo \"       Examples: ${0} aks-test 0        # the first VM node in 'aks-test'\" >&2\n\techo \"                 ${0} aro-aks-cluster 1 # The second VM node in 'aro-aks-cluster'\" >&2\n\texit 1\n}\n\nif [ \"$#\" -ne 2 ]; then\n\tusage\nfi\n\nif [ -z \"$RESOURCEGROUP\" ]; then\n\techo \"RESOURCEGROUP env variable must be set\"\n\texit 1\nfi\n\nNODE_RESOURCEGROUP=$( az aks list -g \"$RESOURCEGROUP\" --query \"[?contains(name, '$1')].nodeResourceGroup\" -o tsv )\nif [[ $(grep -c . <<<\"$NODE_RESOURCEGROUP\") -ne 1 ]]; then\n\techo \"Cluster with pattern \"${1}\" not found in resource group ${RESOURCEGROUP}\"\n\techo \"The following AKS clusters are available:\"\n\taz aks list -g $RESOURCEGROUP -otable\n\texit 1\nfi\n\necho \"Node RG:   ${NODE_RESOURCEGROUP}\"\n\nNODE_VMSS=$( az vmss list -g \"$NODE_RESOURCEGROUP\" --query \"[?contains(name, 'system')].name\" -otsv )\nif [[ $(grep -c . <<<\"$NODE_VMSS\") -ne 1 ]]; then\n\techo \"VMSS not found in the node resource group ${NODE_RESOURCEGROUP}\"\n\tusage\nfi\n\necho \"Node VMSS: ${NODE_VMSS}\"\n\nIPs=$( az vmss nic list -g \"$NODE_RESOURCEGROUP\" --vmss-name \"$NODE_VMSS\" --query '[?items[].ipConfigurations[].primary == true].ipConfigurations[0].privateIpAddress' )\nif [ -z \"$IPs\" ]; then\n\techo \"Primary IPs not found for VMs in ${NODE_VMSS}\"\n\tusage\nfi\n\nIP_COUNT=$( echo ${IPs} | jq -r \". | length\" )\necho \"Found ${IP_COUNT} worker node IPs\"\n\nIP=$( echo \"$IPs\" | jq -r \".[${2}]\" )\nif [ -z \"$IP\" ]; then\n\techo \"IP not found for worker index ${2}\"\n\tusage\nfi\n\nssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -i secrets/proxy_id_rsa -l cloud-user \"$IP\"\n", "num_lines": 55}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -o pipefail\n\nwhile [[ $1 == -* ]]; do\n  if [[ $1 == -- ]]; then\n    shift\n    break\n  fi\n  shift\ndone\n\nif [[ \"$#\" -gt 0 ]]; then\n  NODENAME=$1\n  shift\nfi\n\nCOMMAND='bash --login'\nTTY=true\nTTYOPT=-t\nif [[ \"$#\" -gt 0 ]]; then\n  COMMAND=\"bash -c $(printf ' %q' \"$@\" | sed -e \"s/'/''/g\")\"\n  TTY=false\n  TTYOPT=\nfi\n\ncleanup() {\n    [[ -n \"$POD\" ]] && oc delete pod -n default \"$POD\" >/dev/null\n}\n\ntrap cleanup EXIT\n\nPOD=$(oc create -o json -f - <<EOF | jq -r .metadata.name\nkind: Pod\napiVersion: v1\nmetadata:\n  generateName: debug\n  labels:\n    openshift.io/run-level: \"0\"\n  namespace: default\nspec:\n  containers:\n  - command:\n    - /sbin/chroot\n    - /host\n    - /bin/bash\n    - -c\n    - 'cd && exec $COMMAND'\n    image: ubi8/ubi-minimal\n    name: debug\n    securityContext:\n      capabilities:\n        add:\n        - CHOWN\n        - DAC_OVERRIDE\n        - DAC_READ_SEARCH\n        - FOWNER\n        - FSETID\n        - KILL\n        - SETGID\n        - SETUID\n        - SETPCAP\n        - LINUX_IMMUTABLE\n        - NET_BIND_SERVICE\n        - NET_BROADCAST\n        - NET_ADMIN\n        - NET_RAW\n        - IPC_LOCK\n        - IPC_OWNER\n        - SYS_MODULE\n        - SYS_RAWIO\n        - SYS_CHROOT\n        - SYS_PTRACE\n        - SYS_PACCT\n        - SYS_ADMIN\n        - SYS_BOOT\n        - SYS_NICE\n        - SYS_RESOURCE\n        - SYS_TIME\n        - SYS_TTY_CONFIG\n        - MKNOD\n        - LEASE\n        - AUDIT_WRITE\n        - AUDIT_CONTROL\n        - SETFCAP\n        - MAC_OVERRIDE\n        - MAC_ADMIN\n        - SYSLOG\n        - WAKE_ALARM\n        - BLOCK_SUSPEND\n        - AUDIT_READ\n    stdin: true\n    tty: $TTY\n    volumeMounts:\n    - mountPath: /host\n      name: host\n  hostIPC: true\n  hostNetwork: true\n  hostPID: true\n  nodeName: \"$NODENAME\"\n  restartPolicy: Never\n  terminationGracePeriodSeconds: 0\n  volumes:\n  - hostPath:\n      path: /\n    name: host\nEOF\n)\n\noc wait --timeout=300s --for=condition=Ready -n default \"pod/$POD\" >/dev/null\noc attach -i $TTYOPT -n default -c debug \"pod/$POD\"\n", "num_lines": 112}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script executes Python unit tests. It first tries to activate the virtual environment, \n# but if it does not exist it will be created and then activated.\n# When executing \"pytest\" command, it ignores integration test folder as \n# this script is intended to just execute unit tests. \n\n. pyenv/bin/activate || python3 -m venv pyenv && . pyenv/bin/activate\npip install pytest\ncd python\npytest --ignore=az/aro/azext_aro/tests/latest/integration\n", "num_lines": 12}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# Background: https://groups.google.com/forum/#!topic/golang-nuts/51-D_YFC78k\n#\n# TLDR: OCP consists of many repos where for each release a new release branch gets created (release-X.Y).\n# When we update vendors we want to get latest changes from the release branch for all of the dependencies.\n# With Go modules we can't easily do it, but there is a workaround which consists of multiple steps:\n# \t1. Get the latest commit from the branch using `go list -mod=mod -m MODULE@release-x.y`.\n# \t2. Using `sed`, transform output of the above command into format accepted by `go mod edit -replace`.\n#\t3. Modify `go.mod` by calling `go mod edit -replace`.\n#\n# This needs to happen for each module that uses this branching strategy: all these repos\n# live under github.com/openshift organisation.\n#\n# There are however, some exceptions:\n# \t* Some repos under github.com/openshift do not use this strategy.\n#     We should skip them in this script and manage directly with `go mod`.\n# \t* Some dependencies pin their own dependencies to older commits.\n#     For example, dependency Foo from release-4.7 branch requires\n#\t  dependency Bar at older commit which is\n#     not compatible with Bar@release-4.7.\n#\n# Note that github.com/openshift org also contains forks of K8s upstream repos and we\n# use these forks (indirectly in most cases). This means that\n# we also must take care of replacing modules such as sigs.k8s.io/cluster-api-provider-azure\n# with github.com/openshift/cluster-api-provider-azure (just an example, there are more).\n\nfor x in vendor/github.com/openshift/*; do\n\tcase $x in\n\t\t# Review the list of special cases on each release.\n\n\t\t# Do not update Hive: it is not part of OCP\n\t\tvendor/github.com/openshift/hive)\n\t\t\t;;\n\n\t\t# Replace the installer with our own fork below in this script.\n\t\tvendor/github.com/openshift/installer)\n\t\t\t;;\n\n\t\t# Inconsistent imports: some of our dependencies import it as github.com/metal3-io/cluster-api-provider-baremetal\n\t\t# but in some places directly from the openshift fork.\n\t\t# Replace github.com/metal3-io/cluster-api-provider-baremetal with an openshift fork in go.mod\n\t\tvendor/github.com/openshift/cluster-api-provider-baremetal)\n\t\t\t;;\n\n\t\t# It is only used indirectly and intermediate dependencies pin to different incompatible commits.\n\t\t# We force a specific commit here to make all dependencies happy.\n\t\tvendor/github.com/openshift/cloud-credential-operator)\n\t\t\tgo mod edit -replace github.com/openshift/cloud-credential-operator=github.com/openshift/cloud-credential-operator@v0.0.0-20200316201045-d10080b52c9e\n\t\t\t;;\n\n\t\t# This repo doesn't follow release-x.y branching strategy\n\t\t# We skip it and let go mod resolve it\n\t\tvendor/github.com/openshift/custom-resource-status)\n\t\t\t;;\n\n\t\t*)\n\t\t\tgo mod edit -replace ${x##vendor/}=$(go list -mod=mod -m ${x##vendor/}@release-4.10 | sed -e 's/ /@/')\n\t\t\t;;\n\tesac\ndone\n\nfor x in aws azure openstack; do\n\tgo mod edit -replace sigs.k8s.io/cluster-api-provider-$x=$(go list -mod=mod -m github.com/openshift/cluster-api-provider-$x@release-4.10 | sed -e 's/ /@/')\ndone\n\ngo mod edit -replace github.com/openshift/installer=$(go list -mod=mod -m github.com/jewzaam/installer-aro@release-4.10-azure | sed -e 's/ /@/')\n\ngo get -u ./...\n\ngo mod tidy -compat=1.18\ngo mod vendor\n", "num_lines": 73}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -xe \n\ngo run hack/ci-utils/differenceChecker/main.go make generate\nmake build-all\nmake unit-test-go\n", "num_lines": 8}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -xe\n\nDOCKERID=$(docker create $1)\ndocker export $DOCKERID > aro.tar\ntar -xvf aro.tar --strip-components=3 usr/local/bin/\ndocker rm $DOCKERID\n", "num_lines": 9}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -xe\nif [[ ! -z \"$(git status -s)\" ]]\nthen\n    echo \"there are some modified files\"\n    git status\n    exit 1 \nfi\n\n\n", "num_lines": 12}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n######## Helper file to run E2e either locally or using Azure DevOps Pipelines ########\n\ncreate_infra_rg() {\n    echo \"########## Creating RG $RESOURCEGROUP in $LOCATION ##########\"\n    az group create -g \"$RESOURCEGROUP\" -l \"$LOCATION\" --tags persist=true >/dev/null\n}\n\ndeploy_rp_dev_predeploy() {\n    echo \"########## Deploying rp-development-predeploy in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n rp-development-predeploy \\\n        --template-file pkg/deploy/assets/rp-development-predeploy.json \\\n        --parameters \\\n            \"adminObjectId=$ADMIN_OBJECT_ID\" \\\n            \"fpServicePrincipalId=$(az ad sp list --filter \"appId eq '$AZURE_FP_CLIENT_ID'\" --query '[].id' -o tsv)\" \\\n            \"keyvaultPrefix=$KEYVAULT_PREFIX\" \\\n            \"rpServicePrincipalId=$(az ad sp list --filter \"appId eq '$AZURE_RP_CLIENT_ID'\" --query '[].id' -o tsv)\" >/dev/null\n}\n\ndeploy_rp_dev() {\n    echo \"########## Deploying rp-development in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n rp-development \\\n        --template-file pkg/deploy/assets/rp-development.json \\\n        --parameters \\\n            \"clusterParentDomainName=$PARENT_DOMAIN_NAME\" \\\n            \"databaseAccountName=$DATABASE_ACCOUNT_NAME\" \\\n            \"fpServicePrincipalId=$(az ad sp list --filter \"appId eq '$AZURE_FP_CLIENT_ID'\" --query '[].id' -o tsv)\" \\\n            \"rpServicePrincipalId=$(az ad sp list --filter \"appId eq '$AZURE_RP_CLIENT_ID'\" --query '[].id' -o tsv)\" >/dev/null\n}\n\ndeploy_env_dev() {\n    echo \"########## Deploying env-development in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n env-development \\\n        --template-file pkg/deploy/assets/env-development.json \\\n        --parameters \\\n            \"proxyCert=$(base64 -w0 <secrets/proxy.crt)\" \\\n            \"proxyClientCert=$(base64 -w0 <secrets/proxy-client.crt)\" \\\n            \"proxyDomainNameLabel=$(cut -d. -f2 <<<$PROXY_HOSTNAME)\" \\\n            \"proxyImage=arointsvc.azurecr.io/proxy:latest\" \\\n            \"proxyImageAuth=$(jq -r '.auths[\"arointsvc.azurecr.io\"].auth' <<<$PULL_SECRET)\" \\\n            \"proxyKey=$(base64 -w0 <secrets/proxy.key)\" \\\n            \"sshPublicKey=$(<secrets/proxy_id_rsa.pub)\" \\\n            \"vpnCACertificate=$(base64 -w0 <secrets/vpn-ca.crt)\" >/dev/null\n}\n\ndeploy_aks_dev() {\n    echo \"########## Deploying aks-development in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n aks-development \\\n        --template-file pkg/deploy/assets/aks-development.json \\\n        --parameters \\\n            \"dnsZone=$DOMAIN_NAME\" \\\n            \"keyvaultPrefix=$KEYVAULT_PREFIX\" \\\n            \"sshRSAPublicKey=$(<secrets/proxy_id_rsa.pub)\" >/dev/null\n}\n\ndeploy_vpn_for_dedicated_rp() {\n    echo \"########## Deploying Dev VPN in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n dev-vpn \\\n        --template-file pkg/deploy/assets/vpn-development.json \\\n        --parameters \\\n             \"vpnCACertificate=$(base64 -w0 <secrets/vpn-ca.crt)\" >/dev/null\n}\n\ndeploy_env_dev_override() {\n    echo \"########## Deploying env-development in RG $RESOURCEGROUP ##########\"\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n env-development \\\n        --template-file pkg/deploy/assets/env-development.json \\\n        --parameters \\\n            \"proxyCert=$(base64 -w0 <secrets/proxy.crt)\" \\\n            \"proxyClientCert=$(base64 -w0 <secrets/proxy-client.crt)\" \\\n            \"proxyDomainNameLabel=$(cut -d. -f2 <<<$PROXY_HOSTNAME)\" \\\n            \"proxyImage=arointsvc.azurecr.io/proxy:latest\" \\\n            \"proxyImageAuth=$(jq -r '.auths[\"arointsvc.azurecr.io\"].auth' <<<$PULL_SECRET)\" \\\n            \"proxyKey=$(base64 -w0 <secrets/proxy.key)\" \\\n            \"sshPublicKey=$(<secrets/proxy_id_rsa.pub)\" \\\n            \"vpnCACertificate=$(base64 -w0 <secrets/vpn-ca.crt)\" \\\n            \"publicIPAddressSkuName=Basic\" \\\n            \"publicIPAddressAllocationMethod=Dynamic\" >/dev/null\n}\n\nimport_certs_secrets() {\n    echo \"########## Import certificates to $KEYVAULT_PREFIX-svc KV ##########\"\n    az keyvault certificate import \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name rp-server \\\n        --file secrets/localhost.pem >/dev/null\n    az keyvault certificate import \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name dev-arm \\\n        --file secrets/arm.pem >/dev/null\n    az keyvault certificate import \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --name portal-server \\\n        --file secrets/localhost.pem >/dev/null\n    az keyvault certificate import \\\n        --vault-name \"$KEYVAULT_PREFIX-dbt\" \\\n        --name dbtoken-server \\\n        --file secrets/localhost.pem >/dev/null\n    az keyvault certificate import \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --name portal-client \\\n        --file secrets/portal-client.pem >/dev/null\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^encryption-key$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name encryption-key \\\n        --value \"$(openssl rand -base64 32)\" >/dev/null\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^encryption-key-v2$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name encryption-key-v2 \\\n        --value \"$(openssl rand -base64 64)\"\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^fe-encryption-key$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name fe-encryption-key \\\n        --value \"$(openssl rand -base64 32)\" >/dev/null\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^fe-encryption-key-v2$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-svc\" \\\n        --name fe-encryption-key-v2 \\\n        --value \"$(openssl rand -base64 64)\"\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^portal-session-key$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --name portal-session-key \\\n        --value \"$(openssl rand -base64 32)\" >/dev/null\n    az keyvault secret list \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --query '[].name' \\\n        -o tsv | grep -q ^portal-sshkey$ || \\\n    az keyvault secret set \\\n        --vault-name \"$KEYVAULT_PREFIX-por\" \\\n        --name portal-sshkey \\\n        --value \"$(openssl genpkey -algorithm rsa -pkeyopt rsa_keygen_bits:2048 -outform der | base64 -w0)\" >/dev/null\n}\n\nupdate_parent_domain_dns_zone() {\n    CHILD_DOMAIN_PREFIX=\"$(cut -d. -f1 <<<$DOMAIN_NAME)\"\n    echo \"########## Creating NS record to DNS Zone $CHILD_DOMAIN_PREFIX ##########\"\n    az network dns record-set ns create \\\n        --resource-group \"$PARENT_DOMAIN_RESOURCEGROUP\" \\\n        --zone \"$PARENT_DOMAIN_NAME\" \\\n        --name \"$CHILD_DOMAIN_PREFIX\" >/dev/null\n    for ns in $(az network dns zone show \\\n        --resource-group \"$RESOURCEGROUP\" \\\n        --name \"$DOMAIN_NAME\" \\\n        --query nameServers -o tsv); do\n        az network dns record-set ns add-record \\\n          --resource-group \"$PARENT_DOMAIN_RESOURCEGROUP\" \\\n          --zone \"$PARENT_DOMAIN_NAME\" \\\n          --record-set-name \"$CHILD_DOMAIN_PREFIX\" \\\n          --nsdname \"$ns\" >/dev/null\n      done\n}\n\nvpn_configuration() {\n    echo \"########## VPN Configuration ##########\"\n    curl -so vpnclientconfiguration.zip \"$(az network vnet-gateway vpn-client generate \\\n        -g \"$RESOURCEGROUP\" \\\n        -n dev-vpn \\\n        -o tsv)\"\n    export CLIENTCERTIFICATE=\"$(openssl x509 -inform der -in secrets/vpn-client.crt)\"\n    export PRIVATEKEY=\"$(openssl rsa -inform der -in secrets/vpn-client.key)\"\n    unzip -qc vpnclientconfiguration.zip 'OpenVPN\\\\vpnconfig.ovpn' \\\n        | envsubst \\\n        | grep -v '^log ' >\"secrets/vpn-$LOCATION.ovpn\"\n    rm vpnclientconfiguration.zip\n}\n\nvalidate_arm_template_state() {\n    ARM_TEMPLATE_STATE=$(az deployment group show -n $1 -g $RESOURCEGROUP --query properties.provisioningState -o tsv)\n    if [[ $ARM_TEMPLATE_STATE == \"Failed\" ]]; then\n        echo \"##[error] Error deploying $1 $(az deployment group show -n $1 -g $RESOURCEGROUP --query properties.error.details -o tsv)\"\n        exit 1\n    fi\n}\n\nclean_env() {\n    echo \"########## Deleting RG $RESOURCEGROUP in $LOCATION ##########\"\n    az group delete -g \"$RESOURCEGROUP\" -y\n    az network dns record-set ns delete \\\n        --resource-group \"$PARENT_DOMAIN_RESOURCEGROUP\" \\\n        --zone \"$PARENT_DOMAIN_NAME\" \\\n        --name \"$RESOURCEGROUP\"\n    for ns in $(az network dns zone show \\\n        --resource-group \"$RESOURCEGROUP\" \\\n        --name \"$DOMAIN_NAME\" \\\n        --query nameServers -o tsv); do\n        az network dns record-set ns remove-record \\\n          --resource-group \"$PARENT_DOMAIN_RESOURCEGROUP\" \\\n          --zone \"$PARENT_DOMAIN_NAME\" \\\n          --record-set-name \"$RESOURCEGROUP\" \\\n          --nsdname \"$ns\"\n      done\n}\n\necho \"##########################################\"\necho \"##### ARO V4 Dev Env helper sourced ######\"\necho \"##########################################\"\necho \"########## Current settings : ############\"\necho \"RESOURCEGROUP=$RESOURCEGROUP\"\necho \"AZURE_SUBSCRIPTION_ID=$AZURE_SUBSCRIPTION_ID\"\necho\necho \"LOCATION=$LOCATION\"\necho\necho \"DATABASE_ACCOUNT_NAME=$DATABASE_ACCOUNT_NAME\"\necho\necho \"ADMIN_OBJECT_ID=$ADMIN_OBJECT_ID\"\necho \"AZURE_RP_CLIENT_ID=$AZURE_RP_CLIENT_ID\"\necho \"AZURE_FP_CLIENT_ID=$AZURE_FP_CLIENT_ID\"\necho\necho \"PARENT_DOMAIN_NAME=$PARENT_DOMAIN_NAME\"\necho \"PARENT_DOMAIN_RESOURCEGROUP=$PARENT_DOMAIN_RESOURCEGROUP\"\necho\necho \"KEYVAULT_PREFIX=$KEYVAULT_PREFIX\"\necho\necho \"PROXY_HOSTNAME=$PROXY_HOSTNAME\"\necho \"######################################\"\n\n[ \"$LOCATION\" ] || ( echo \">> LOCATION is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$RESOURCEGROUP\" ] || ( echo \">> RESOURCEGROUP is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$PROXY_HOSTNAME\" ] || ( echo \">> PROXY_HOSTNAME is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$DATABASE_ACCOUNT_NAME\" ] || ( echo \">> DATABASE_ACCOUNT_NAME is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$ADMIN_OBJECT_ID\" ] || ( echo \">> ADMIN_OBJECT_ID is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$PARENT_DOMAIN_NAME\" ] || ( echo \">> PARENT_DOMAIN_NAME is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$AZURE_FP_CLIENT_ID\" ] || ( echo \">> AZURE_FP_CLIENT_ID is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$KEYVAULT_PREFIX\" ] || ( echo \">> KEYVAULT_PREFIX is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$AZURE_RP_CLIENT_ID\" ] || ( echo \">> AZURE_RP_CLIENT_ID is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$PULL_SECRET\" ] || ( echo \">> PULL_SECRET is not set please validate your ./secrets/env\"; exit 128 )\n[ \"$PARENT_DOMAIN_RESOURCEGROUP\" ] || ( echo \">> PARENT_DOMAIN_RESOURCEGROUP is not set please validate your ./secrets/env\"; exit 128 )\n", "num_lines": 259}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Local development environment script.\n# Execute this script from the root folder of the repo (ARO-RP).\n# This script is aimed to provide an automatic and easy way to prepare \n# the environment and execute the ARO RP locally.\n# The steps here are the ones defined in docs/deploy-development-rp.md\n# We recommend to use this script after you understand the steps of the process, not before.\n\n\nbuild_development_az_aro_extension() {\n    echo \"INFO: Building development az aro extension...\"\n    make az\n}\n\nverify_aro_extension() {\n    echo \"INFO: Verifying aro extension...\"\n    grep -q 'dev_sources' ~/.azure/config || cat >>~/.azure/config <<EOF\n[extension]\ndev_sources = $PWD/python\nEOF\n}\n\nset_storage_account() {\n    echo \"INFO: Setting storage account...\"\n    export SECRET_SA_ACCOUNT_NAME=rharosecretsdev make secrets\n}\n\nask_to_create_default_env_config() {\n    local answer\n    read -p \"Do you want to create a default env file? (existing one will be overwritten, if any) (y / n) \" answer\n\n    if [[ \"$answer\" == \"y\" || \"$answer\" == \"Y\" ]]; then\n        create_env_file\n    elif [[ \"$answer\" == \"n\" || \"$answer\" == \"N\" ]]; then\n        echo \"INFO: Skipping creation of default env file...\"\n    else\n        echo \"INFO: Unknown option, skipping step...\"\n    fi\n}\n\ncreate_env_file() {\n    echo \"INFO: Creating default env config file...\"\n\n    cat >env <<EOF\nexport LOCATION=eastus\nexport ARO_IMAGE=arointsvc.azurecr.io/aro:latest\nexport RP_MODE=development # to use a development RP running at https://localhost:8443/\n\nsource secrets/env\nEOF\n}\n\nask_to_create_Azure_deployment() {\n    local answer\n    read -p \"Create Azure deployment in the current subscription ($AZURE_SUBSCRIPTION_ID)? (y / n / l (list existing deployments)) \" answer\n\n    if [[ \"$answer\" == \"y\" || \"$answer\" == \"Y\" ]]; then\n        create_Azure_deployment\n    elif [[ \"$answer\" == \"n\" || \"$answer\" == \"N\" ]]; then\n        echo \"INFO: Skipping creation of Azure deployment...\"\n    elif [[ \"$answer\" == \"l\" ]]; then\n        list_Azure_deployment_names\n        ask_to_create_Azure_deployment\n    else\n        echo \"INFO: Unknown option, skipping step...\"\n    fi\n}\n\nlist_Azure_deployment_names() {\n    echo \"INFO: Existing deployment names in the current subscription ($AZURE_SUBSCRIPTION_ID):\"\n    az deployment group list --resource-group $RESOURCEGROUP | jq '[ .[] | {deployment_name: ( .id ) | split(\"/deployments/\")[1] } | .deployment_name ]'\n}\n\ncreate_Azure_deployment() {\n    echo \"INFO: Creating Azure deployment...\"\n\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n \"databases-development-$USER\" \\\n        --template-file pkg/deploy/assets/databases-development.json \\\n        --parameters \\\n        \"databaseAccountName=$DATABASE_ACCOUNT_NAME\" \\\n        \"databaseName=$DATABASE_NAME\" \\\n        >/dev/null\n    \n    echo \"INFO: Azure deployment created.\"\n}\n\nsource_env() {\n    echo \"INFO: Sourcing env file...\"\n    source ./env\n}\n\nrun_the_RP() {\n    echo \"INFO: Running the ARO RP locally...\"\n    make runlocal-rp\n}\n\nmain() {\n    build_development_az_aro_extension\n    verify_aro_extension\n    set_storage_account\n    ask_to_create_default_env_config\n    source_env\n    ask_to_create_Azure_deployment\n    run_the_RP\n}\n\nmain\n", "num_lines": 111}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n######## Helper file to run E2e either locally or using Azure DevOps Pipelines ########\n\nif [[ $CI ]]; then\n    set -o pipefail\n\n    . secrets/env\n    echo \"##vso[task.setvariable variable=RP_MODE]$RP_MODE\"\n\n    set -a\n    HIVEKUBECONFIGPATH=\"secrets/e2e-aks-kubeconfig\"\n    HIVE_KUBE_CONFIG_PATH_1=\"secrets/aks.kubeconfig\"\n    CLUSTER=\"v4-e2e-V$BUILD_BUILDID-$LOCATION\"\n    DATABASE_NAME=\"v4-e2e-V$BUILD_BUILDID-$LOCATION\"\n    PRIVATE_CLUSTER=true\n    E2E_DELETE_CLUSTER=false\n    set +a\nfi\n\nvalidate_rp_running() {\n    echo \"########## \u00ef\u00bc\u0178Checking ARO RP Status ##########\"\n    ELAPSED=0\n    while true; do\n        sleep 5\n        http_code=$(curl -k -s -o /dev/null -w '%{http_code}' https://localhost:8443/healthz/ready || true)\n        case $http_code in\n        \"200\")\n            echo \"########## \u00e2\u0153\u2026 ARO RP Running ##########\"\n            break\n            ;;\n        *)\n            echo \"Attempt $ELAPSED - local RP is NOT up. Code : $http_code, waiting\"\n            sleep 2\n            # after 40 secs return exit 1 to not block ci\n            ELAPSED=$((ELAPSED + 1))\n            if [ $ELAPSED -eq 20 ]; then\n                exit 1\n            fi\n            ;;\n        esac\n    done\n}\n\nrun_rp() {\n    echo \"########## \u00f0\u0178\u0161\u20ac Run ARO RP in background ##########\"\n    ./aro rp &\n}\n\nkill_rp() {\n    echo \"########## Kill the RP running in background ##########\"\n    rppid=$(lsof -t -i :8443)\n    kill $rppid\n    wait $rppid\n}\n\nvalidate_portal_running() {\n    echo \"########## \u00ef\u00bc\u0178Checking Admin Portal Status ##########\"\n    ELAPSED=0\n    while true; do\n        sleep 5\n        http_code=$(curl -k -s -o /dev/null -w '%{http_code}' https://localhost:8444/healthz/ready)\n        case $http_code in\n        \"200\")\n            echo \"########## \u00e2\u0153\u2026 ARO Admin Portal Running ##########\"\n            break\n            ;;\n        *)\n            echo \"Attempt $ELAPSED - local Admin Portal is NOT up. Code : $http_code, waiting\"\n            sleep 2\n            # after 40 secs return exit 1 to not block ci\n            ELAPSED=$((ELAPSED + 1))\n            if [ $ELAPSED -eq 20 ]; then\n                exit 1\n            fi\n            ;;\n        esac\n    done\n}\n\nrun_portal() {\n    echo \"########## \u00f0\u0178\u0161\u20ac Run Admin Portal in background ##########\"\n    export AZURE_ENVIRONMENT=AzurePublicCloud\n    ./aro portal &\n}\n\nkill_portal() {\n    echo \"########## Kill the Admin Portal running in background ##########\"\n    rppid=$(lsof -t -i :8444)\n    kill $rppid\n    wait $rppid\n}\n\nrun_vpn() {\n    echo \"########## \u00f0\u0178\u0161\u20ac Run OpenVPN in background ##########\"\n    echo \"Using Secret secrets/$VPN\"\n    sudo openvpn --config secrets/$VPN --daemon --writepid vpnpid\n    sleep 10\n}\n\nkill_vpn() {\n    echo \"########## Kill the OpenVPN running in background ##########\"\n    while read pid; do sudo kill $pid; done <vpnpid\n}\n\nrun_podman() {\n    echo \"########## \u00f0\u0178\u0161\u20ac Run Podman in background ##########\"\n    podman --log-level=debug system service --time=0 tcp://127.0.0.1:8888 >podmanlog &\n}\n\nkill_podman() {\n    echo \"podman logs:\"\n    cat podmanlog\n    echo \"########## Kill the podman running in background ##########\"\n    rppid=$(lsof -t -i :8888)\n    kill $rppid\n    wait $rppid\n}\n\nvalidate_podman_running() {\n    echo \"########## \u00ef\u00bc\u0178Checking podman Status ##########\"\n    ELAPSED=0\n    while true; do\n        sleep 5\n        http_code=$(curl -k -s -o /dev/null -w '%{http_code}' http://localhost:8888/v1.30/_ping || true)\n        case $http_code in\n        \"200\")\n            echo \"########## \u00e2\u0153\u2026 Podman Running ##########\"\n            break\n            ;;\n        *)\n            echo \"Attempt $ELAPSED - podman is NOT up. Code : $http_code, waiting\"\n            sleep 2\n            # after 40 secs return exit 1 to not block ci\n            ELAPSED=$((ELAPSED + 1))\n            if [ $ELAPSED -eq 20 ]; then\n                exit 1\n            fi\n            ;;\n        esac\n    done\n}\n\nrun_selenium() {\n    echo \"########## \u00f0\u0178\u0161\u20ac Run Selenium in background ##########\"\n    podman -r --url tcp://localhost:8888 pull docker.io/selenium/standalone-edge:latest\n    podman -r --url tcp://localhost:8888 run -d --name selenium-edge-standalone --network=host --shm-size=2g docker.io/selenium/standalone-edge:latest\n\n}\n\nkill_selenium() {\n    podman stop -i selenium-edge-standalone\n}\n\nvalidate_selenium_running() {\n    echo \"########## \u00ef\u00bc\u0178Checking selenium Status ##########\"\n    ELAPSED=0\n    while true; do\n        sleep 5\n        http_code=$(curl -k -s -o /dev/null -w '%{http_code}' http://localhost:4444/status || true)\n        case $http_code in\n        \"200\")\n            echo \"########## \u00e2\u0153\u2026 Podman Running ##########\"\n            break\n            ;;\n        *)\n            echo \"Attempt $ELAPSED - selenium is NOT up. Code : $http_code, waiting\"\n            sleep 2\n            # after 40 secs return exit 1 to not block ci\n            ELAPSED=$((ELAPSED + 1))\n            if [ $ELAPSED -eq 20 ]; then\n                exit 1\n            fi\n            ;;\n        esac\n    done\n}\n\ndeploy_e2e_db() {\n    echo \"########## \u00f0\u0178\u201c\u00a6 Creating new DB $DATABASE_NAME in $DATABASE_ACCOUNT_NAME ##########\"\n\n    az deployment group create \\\n        -g \"$RESOURCEGROUP\" \\\n        -n \"databases-development-$DATABASE_NAME\" \\\n        --template-file pkg/deploy/assets/databases-development.json \\\n        --parameters \\\n        \"databaseAccountName=$DATABASE_ACCOUNT_NAME\" \\\n        \"databaseName=$DATABASE_NAME\" \\\n        >/dev/null\n\n}\n\nregister_sub() {\n    echo \"########## \u00f0\u0178\u201d\u2018 Registering subscription ##########\"\n    curl -sko /dev/null -X PUT \\\n        -H 'Content-Type: application/json' \\\n        -d '{\"state\": \"Registered\", \"properties\": {\"tenantId\": \"'\"$AZURE_TENANT_ID\"'\"}}' \\\n        \"https://localhost:8443/subscriptions/$AZURE_SUBSCRIPTION_ID?api-version=2.0\"\n}\n\nclean_e2e_db() {\n    echo \"########## \u00f0\u0178\u00a7\u00b9 Deleting DB $DATABASE_NAME ##########\"\n    az cosmosdb sql database delete --name $DATABASE_NAME \\\n        --yes \\\n        --account-name $DATABASE_ACCOUNT_NAME \\\n        --resource-group $RESOURCEGROUP >/dev/null\n}\n\ndelete_e2e_cluster() {\n    echo \"########## \u00f0\u0178\u00a7\u00b9 Deleting Cluster $CLUSTER ##########\"\n    if [[ $CI ]]; then\n        ./cluster delete\n    else\n        go run ./hack/cluster delete\n    fi\n}\n\n# TODO: CLUSTER and is also recalculated in multiple places\n# in the billing pipelines :-(\n\nif [[ -z $CLUSTER ]]; then\n    echo \"CLUSTER is not set, aborting\"\n    return 1\nfi\n\nif [[ -z $DATABASE_NAME ]]; then\n    echo \"DATABASE_NAME is not set, aborting\"\n    return 1\nfi\n\necho \"######################################\"\necho \"##### ARO V4 E2e helper sourced ######\"\necho \"######################################\"\necho \"######## Current settings : ##########\"\necho\necho \"LOCATION=$LOCATION\"\necho \"AZURE_SUBSCRIPTION_ID=$AZURE_SUBSCRIPTION_ID\"\necho\necho \"RP_MODE=$RP_MODE\"\necho\necho \"DATABASE_ACCOUNT_NAME=$DATABASE_ACCOUNT_NAME\"\necho \"DATABASE_NAME=$DATABASE_NAME\"\necho \"RESOURCEGROUP=$RESOURCEGROUP\"\necho\necho \"CLUSTER=$CLUSTER\"\necho\necho \"PROXY_HOSTNAME=$PROXY_HOSTNAME\"\necho \"######################################\"\n\n[[ $LOCATION ]] || (\n    echo \">> LOCATION is not set please validate your ./secrets/env\"\n    return 128\n)\n[[ $RESOURCEGROUP ]] || (\n    echo \">> RESOURCEGROUP is not set; please validate your ./secrets/env\"\n    return 128\n)\n[[ $PROXY_HOSTNAME ]] || (\n    echo \">> PROXY_HOSTNAME is not set; please validate your ./secrets/env\"\n    return 128\n)\n[[ $DATABASE_ACCOUNT_NAME ]] || (\n    echo \">> DATABASE_ACCOUNT_NAME is not set; please validate your ./secrets/env\"\n    return 128\n)\n[[ $DATABASE_NAME ]] || (\n    echo \">> DATABASE_NAME is not set; please validate your ./secrets/env\"\n    return 128\n)\n[[ $AZURE_SUBSCRIPTION_ID ]] || (\n    echo \">> AZURE_SUBSCRIPTION_ID is not set; please validate your ./secrets/env\"\n    return 128\n)\n", "num_lines": 273}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The small go program below will validate that a \n# FIPS validated crypto lib\ncat > ./hack/fips/main.go << 'EOF'\npackage main\n\n// Copyright (c) Microsoft Corporation.\n// Licensed under the Apache License 2.0.\n\nimport (\n\t_ \"crypto/tls/fipsonly\"\n\n\tutillog \"github.com/Azure/ARO-RP/pkg/util/log\"\n)\n\nfunc main() {\n\tlog := utillog.GetLogger()\n\tlog.Println(\"FIPS mode enabled\")\n}\nEOF\ntrap \"rm ./hack/fips/main.go\" EXIT\necho \"Attempting to run program that requires FIPS crypto\"\ngo run ./hack/fips/main.go\n", "num_lines": 25}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd ./portal/v2\n\nif npm audit --omit=dev | grep -q 'found 0 vulnerabilities'; then\n  echo \"No vulnerabilities found.\"\n  exit 0\nelse\n  echo \"Vulnerabilities found, please run `npm audit --omit=dev` locally and fix or record issues and create an ADO card.\"\n  exit 1\nfi\n", "num_lines": 12}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Setup the VM\nrpm --import https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-7\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\nyum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n\ncat >/etc/yum.repos.d/azure.repo <<'EOF'\n[azure-cli]\nname=azure-cli\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=yes\ngpgcheck=yes\nEOF\n\nyum --enablerepo=rhui-rhel-7-server-rhui-optional-rpms -y install \\\n   azure-cli \\\n   docker \\\n   jq \\\n   gcc \\\n   rh-git29 \\\n   rh-python36 \\\n   tmpwatch \\\n   lttng-usr \\\n   gpgme-devel \\\n   libassuan-devel \\\n   socat\n\n\nsed -i -e 's/^OPTIONS='\\''/OPTIONS='\\''-G cloud-user /' /etc/sysconfig/docker\n\nsystemctl enable docker\nsystemctl restart docker\n\n\n\n\n", "num_lines": 37}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\nset +x\n\nBASE=$( git rev-parse --show-toplevel)\n\nHOSTNAME=$( hostname )\nNAME=\"mdm\"\nMDMIMAGE=linuxgeneva-microsoft.azurecr.io/genevamdm:master_20211120.1\nMDMFRONTENDURL=https://global.ppe.microsoftmetrics.com/\nMDMSOURCEENVIRONMENT=$LOCATION\nMDMSOURCEROLE=rp\nMDMSOURCEROLEINSTANCE=$HOSTNAME\n\necho \"Using:\"\n\necho \"Resourcegroup = $RESOURCEGROUP\"\necho \"User          = $USER\"\necho \"HOSTNAME      = $HOSTNAME\"\necho \"Containername = $NAME\"\necho \"Location      = $LOCATION\"\necho \"MDM image     = $MDMIMAGE\"\necho \"  (version hardcoded. Check against pkg/util/version/const.go if things don't work)\"\necho \"Geneva API URL= $MDMFRONTENDURL\"\necho \"MDMSOURCEENV  = $MDMSOURCEENVIRONMENT\"\necho \"MDMSOURCEROLE  = $MDMSOURCEROLE\"\necho \"MDMSOURCEROLEINSTANCE  = $MDMSOURCEROLEINSTANCE\"\n\nVMName=\"$USER-mdm-link\"\n\nCLOUDUSER=\"cloud-user\"\n\n\n\nif [ \"$(az vm show -g $RESOURCEGROUP --name $VMName)\" = \"\" ];\nthen\n  echo \"Creating VM $VMName in RG $RESOURCEGROUP\"   \n  az vm create -g $RESOURCEGROUP -n $VMName --image RedHat:RHEL:7-LVM:latest --ssh-key-values @~/.ssh/id_rsa.pub --admin-username $CLOUDUSER\nelse\n  echo \"VM already exists, skipping...\"\nfi\n\n\nPUBLICIP=$( az vm list-ip-addresses --name $VMName -g $RESOURCEGROUP | jq -r '.[0].virtualMachine.network.publicIpAddresses[0].ipAddress' )\n\necho \"Found IP $PUBLICIP\"\n\nscp $BASE/secrets/rp-metrics-int.pem $CLOUDUSER@$PUBLICIP:mdm.pem\nscp $BASE/hack/local-monitor-testing/configureRemote.sh $CLOUDUSER@$PUBLICIP:\n\nssh $CLOUDUSER@$PUBLICIP \"sudo cp mdm.pem /etc/mdm.pem\"\nssh $CLOUDUSER@$PUBLICIP \"sudo ./configureRemote.sh\"\n\n\nssh $CLOUDUSER@$PUBLICIP \"sudo docker pull $MDMIMAGE\"\n\ncat <<EOF > $BASE/dockerStartCommand.sh\ndocker run \\\n  --entrypoint /usr/sbin/MetricsExtension \\\n  --hostname $HOSTNAME \\\n  --name $NAME \\\n  -d \\\n  --restart=always \\\n  -m 2g \\\n  -v /etc/mdm.pem:/etc/mdm.pem \\\n  -v /var/etw:/var/etw:z \\\n  $MDMIMAGE \\\n  -CertFile /etc/mdm.pem \\\n  -FrontEndUrl $MDMFRONTENDURL \\\n  -Logger Console \\\n  -LogLevel Debug \\\n  -PrivateKeyFile /etc/mdm.pem \\\n  -SourceEnvironment $MDMSOURCEENVIRONMENT \\\n  -SourceRole $MDMSOURCEROLE \\\n  -SourceRoleInstance $MDMSOURCEROLEINSTANCE\nEOF\n\n\n#disable SELINUX (don't shoot me)\nssh $CLOUDUSER@$PUBLICIP \"sudo setenforce 0\"\nssh $CLOUDUSER@$PUBLICIP \"sudo getenforce\"\n\n#make it permanent\nssh $CLOUDUSER@$PUBLICIP \"sudo sed -i 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config\"\n\n\nssh $CLOUDUSER@$PUBLICIP \"sudo firewall-cmd --zone=public --add-port=12345/tcp --permanent\"\nssh $CLOUDUSER@$PUBLICIP \"sudo firewall-cmd --reload\"\n\nscp $BASE/dockerStartCommand.sh $CLOUDUSER@$PUBLICIP:\nssh $CLOUDUSER@$PUBLICIP \"chmod +x dockerStartCommand.sh\"\nssh $CLOUDUSER@$PUBLICIP \"sudo ./dockerStartCommand.sh &\"\n", "num_lines": 92}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash \nset +x\ntrap ctrl_c INT\n\nfunction ctrl_c() {    \n    echo \"** Trapped CTRL-C. Stopping  processes...\"\n    killProcesses\n}\n\nfunction killProcesses() {\n    for pid in ${pids[*]}; do\n        echo -n \"Stopping local PID: $pid\"\n        kill $pid\n        echo \" stopped.\"\n    done\n\n    for pid in ${rempids[*]}; do\n        echo -n \"Stopping remote PID: $pid\"\n        ssh $CLOUDUSER@$PUBLICIP sudo kill $pid\n        echo \" stopped.\"\n    done\n    \n    echo \"All Stopped.\"\n    exit 1\n}\n\n\nBASE=$( git rev-parse --show-toplevel)\nSOCKETFILE=\"$BASE/cmd/aro/mdm_statsd.socket\"\n\necho \"Using:\"\n\necho \"Resourcegroup = $RESOURCEGROUP\"\necho \"User          = $USER\"\n\nVMName=\"$USER-mdm-link\"\nCLOUDUSER=\"cloud-user\"\n\necho \"Looking for a VM called $VMName and its public IP\"\nPUBLICIP=$( az vm list-ip-addresses --name $VMName -g $RESOURCEGROUP | jq -r '.[0].virtualMachine.network.publicIpAddresses[0].ipAddress' )\n\nif [ \"$PUBLICIP\" == \"\" ] || [ \"$PUBLICIP\" == \"null\" ]; then\n    echo \"ERR: no PUBLICIP IP address found for $VMName. Giving up.\"\n    \n    exit 2\nfi\n\necho -n \"Found IP $PUBLICIP, starting socat on the mdm-link vm\"\nssh $CLOUDUSER@$PUBLICIP 'sudo socat -v TCP-LISTEN:12345,fork UNIX-CONNECT:/var/etw/mdm_statsd.socket'  &\nsleep 2\nREMPS=$( ssh $CLOUDUSER@$PUBLICIP 'ps aux | grep \"socat -v TCP-LISTEN:12345,fork UNIX-CONNECT:/var/etw/mdm_statsd.socket\" | grep -v sudo | grep -v grep' )\nREMPID=$( echo $REMPS |  awk '{print $2}' )\nif [ \"$REMPID\" == \"\" ]; then\n    echo \"\"\n    echo \"ERR: FAILED TO START REMOTE SOCAT..\"\n    killProcesses\n    exit 1\nfi\n\n\nrempids[0]=$REMPID\necho \"...remote socat started.\"\necho -n \"Starting SSH Tunnel...\" \nssh $CLOUDUSER@$PUBLICIP -N -L 12345:127.0.0.1:12345 -o ConnectTimeout=4 &\npids[0]=$!\nsleep 5\nkill -0 ${pids[0]}\nif [ $? -eq 0 ]; then\n    echo \"...SSH Tunnel started. PID: ${pids[0]}.\"\nelse\n    echo \"\"\n    echo \"ERR: FAILED TO START TUNNEL..\"\n    killProcesses\n    exit 1\nfi\n\nif [ -e \"$SOCKETFILE\" ] ; then\n    echo \"Cleaning up old socket file.\"\n    rm \"$SOCKETFILE\"\nfi\necho -n \"Starting local socat link to the tunnel...\"\nsocat -v UNIX-LISTEN:$SOCKETFILE,fork TCP-CONNECT:127.0.0.1:12345 &\npids[1]=$!\nsleep 2\n\nkill -0 ${pids[1]}\nif [ $? -eq 0 ]; then\n    echo \"...local socat started.PID: ${pids[1]}.\"\nelse\n    echo \"ERR: FAILED TO START SOCAT. Cleaning up:\"    \n    echo \"Killing SSH tunnel\"\n    killProcesses\n    echo \"Killed.\"\n    exit 1\nfi\n\n\necho \"\"\necho \"**********************************************************************\"\necho \"*  Remote socat: Started. SSH Tunnel: Started. Local socat: Started. *\"\necho \"*                                                                    *\"\necho \"*      Hit CTRL-C to stop                                            *\"\necho \"*                                                                    *\"\necho \"**********************************************************************\"\necho \"\"\necho \"\"\nwhile true\ndo\n    sleep 100\ndone\n", "num_lines": 111}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#/bin/bash\n\nfailedChecks=0\nwhile read var; do\n  [ -z \"${!var}\" ] && { echo \"required $var is empty or not set.\"; let failedChecks=failedChecks+1; }\ndone << EOF\nLOCATION\nRESOURCEGROUP\nUSER\nEOF\n\nif [ $failedChecks -gt 0 ]; then\n  exit 1\nfi\n\n#ARO-RP repo root folder\nBASE=$( git rev-parse --show-toplevel)\n\nSOCKETPATH=\"/var/home/core\"\n\nHOSTNAME=$( hostname )\nNAME=\"mdm2\"\nMDMIMAGE=linuxgeneva-microsoft.azurecr.io/genevamdm:master_20211120.1\nMDMFRONTENDURL=https://global.ppe.microsoftmetrics.com/\nMDMSOURCEENVIRONMENT=$LOCATION\nMDMSOURCEROLE=rp\nMDMSOURCEROLEINSTANCE=$HOSTNAME\n\n\necho \"Using:\"\n\necho \"Resourcegroup = $RESOURCEGROUP\"\necho \"User          = $USER\"\necho \"HOSTNAME      = $HOSTNAME\"\necho \"Containername = $NAME\"\necho \"Location      = $LOCATION\"\necho \"MDM image     = $MDMIMAGE\"\necho \"  (version hardcoded. Check against pkg/util/version/const.go if things don't work)\"\necho \"Geneva API URL= $MDMFRONTENDURL\"\necho \"MDMSOURCEENV  = $MDMSOURCEENVIRONMENT\"\necho \"MDMSOURCEROLE  = $MDMSOURCEROLE\"\necho \"MDMSOURCEROLEINSTANCE  = $MDMSOURCEROLEINSTANCE\" \n\npodman run \\\n  --entrypoint /usr/sbin/MetricsExtension \\\n  --hostname $HOSTNAME \\\n  --name $NAME \\\n  -p 8125:8125/udp \\\n  -d \\\n  -m 2g \\\n  -v $BASE/secrets/rp-metrics-int.pem:/etc/mdm.pem \\\n  $MDMIMAGE \\\n  -CertFile /etc/mdm.pem \\\n  -FrontEndUrl $MDMFRONTENDURL \\\n  -Logger Console \\\n  -LogLevel Debug \\\n  -PrivateKeyFile /etc/mdm.pem \\\n  -SourceEnvironment $MDMSOURCEENVIRONMENT \\\n  -SourceRole $MDMSOURCEROLE \\\n  -SourceRoleInstance $MDMSOURCEROLEINSTANCE \\\n  -Input statsd_udp", "num_lines": 62}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n\n\n#/bin/bash\n\nfailedChecks=0\nwhile read var; do\n  [ -z \"${!var}\" ] && { echo \"required $var is empty or not set.\"; let failedChecks=failedChecks+1; }\ndone << EOF\nLOCATION\nRESOURCEGROUP\nUSER\nEOF\n\nif [ $failedChecks -gt 0 ]; then\n  exit 1\nfi\n\nBASE=$( git rev-parse --show-toplevel)\n\nSOCKETPATH=\"$BASE/cmd/aro\"\n\nHOSTNAME=$( hostname )\nNAME=\"mdm\"\nMDMIMAGE=linuxgeneva-microsoft.azurecr.io/genevamdm:master_20211120.1\nMDMFRONTENDURL=https://global.ppe.microsoftmetrics.com/\nMDMSOURCEENVIRONMENT=$LOCATION\nMDMSOURCEROLE=rp\nMDMSOURCEROLEINSTANCE=$HOSTNAME\n\n\necho \"Using:\"\n\necho \"Resourcegroup = $RESOURCEGROUP\"\necho \"User          = $USER\"\necho \"HOSTNAME      = $HOSTNAME\"\necho \"Containername = $NAME\"\necho \"Location      = $LOCATION\"\necho \"MDM image     = $MDMIMAGE\"\necho \"  (version hardcoded. Check against pkg/util/version/const.go if things don't work)\"\necho \"Geneva API URL= $MDMFRONTENDURL\"\necho \"MDMSOURCEENV  = $MDMSOURCEENVIRONMENT\"\necho \"MDMSOURCEROLE  = $MDMSOURCEROLE\"\necho \"MDMSOURCEROLEINSTANCE  = $MDMSOURCEROLEINSTANCE\"\n\n\npodman run \\\n  --entrypoint /usr/sbin/MetricsExtension \\\n  --hostname $HOSTNAME \\\n  --name $NAME \\\n  -d \\\n  --restart=always \\\n  -m 2g \\\n  -v $BASE/secrets/rp-metrics-int.pem:/etc/mdm.pem \\\n  -v $SOCKETPATH:/var/etw:z \\\n  $MDMIMAGE \\\n  -CertFile /etc/mdm.pem \\\n  -FrontEndUrl $MDMFRONTENDURL \\\n  -Logger Console \\\n  -LogLevel Debug \\\n  -PrivateKeyFile /etc/mdm.pem \\\n  -SourceEnvironment $MDMSOURCEENVIRONMENT \\\n  -SourceRole $MDMSOURCEROLE \\\n  -SourceRoleInstance $MDMSOURCEROLEINSTANCE\n", "num_lines": 65}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo \"running RHUI fix\"\nyum update -y --disablerepo='*' --enablerepo='rhui-microsoft-azure*'\n\nyum -y -x WALinuxAgent -x WALinuxAgent-udev update\nyum -y install podman-docker\n\nfirewall-cmd --add-port=443/tcp --permanent\n\nmkdir /root/.docker\ncat >/root/.docker/config.json <<EOF\n{\n\t\"auths\": {\n\t\t\"${PROXYIMAGE%%/*}\": {\n\t\t\t\"auth\": \"$PROXYIMAGEAUTH\"\n\t\t}\n\t}\n}\nEOF\n\nmkdir -p /etc/containers/\ntouch /etc/containers/nodocker\n\ndocker pull \"$PROXYIMAGE\"\n\nmkdir /etc/proxy\nbase64 -d <<<\"$PROXYCERT\" >/etc/proxy/proxy.crt\nbase64 -d <<<\"$PROXYKEY\" >/etc/proxy/proxy.key\nbase64 -d <<<\"$PROXYCLIENTCERT\" >/etc/proxy/proxy-client.crt\nchown -R 1000:1000 /etc/proxy\nchmod 0600 /etc/proxy/proxy.key\n\ncat >/etc/sysconfig/proxy <<EOF\nPROXY_IMAGE='$PROXYIMAGE'\nEOF\n\ncat >/etc/systemd/system/proxy.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/proxy\nExecStartPre=-/usr/bin/docker rm -f %n\nExecStart=/usr/bin/docker run --rm --name %n -p 443:8443 -v /etc/proxy:/secrets $PROXY_IMAGE\nExecStop=/usr/bin/docker stop %n\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable proxy.service\n\ncat >/etc/cron.weekly/pull-image <<'EOF'\n#!/bin/bash\n\ndocker pull $PROXYIMAGE\nsystemctl restart proxy.service\nEOF\nchmod +x /etc/cron.weekly/pull-image\n\ncat >/etc/cron.weekly/yumupdate <<'EOF'\n#!/bin/bash\n\nyum update -y\nEOF\nchmod +x /etc/cron.weekly/yumupdate\n\ncat >/etc/cron.daily/restart-proxy <<'EOF'\n#!/bin/bash\n\nsystemctl restart proxy.service\nEOF\nchmod +x /etc/cron.daily/restart-proxy\n\n(\n\tsleep 30\n\treboot\n) &\n", "num_lines": 82}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"setting ssh password authentication\"\n# We need to manually set PasswordAuthentication to true in order for the VMSS Access JIT to work\nsed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config\nsystemctl reload sshd.service\n\necho \"running RHUI fix\"\nyum update -y --disablerepo='*' --enablerepo='rhui-microsoft-azure*'\n\necho \"running yum update\"\nyum -y -x WALinuxAgent -x WALinuxAgent-udev update --allowerasing\n\necho \"extending partition table\"\n# Linux block devices are inconsistently named\n# it's difficult to tie the lvm pv to the physical disk using /dev/disk files, which is why lvs is used here\nphysicalDisk=\"$(lvs -o devices -a | head -n2 | tail -n1 | cut -d ' ' -f 3 | cut -d \\( -f 1 | tr -d '[:digit:]')\"\ngrowpart \"$physicalDisk\" 2\n\necho \"extending filesystems\"\nlvextend -l +20%FREE /dev/rootvg/rootlv\nxfs_growfs /\n\nlvextend -l +100%FREE /dev/rootvg/varlv\nxfs_growfs /var\n\nrpm --import https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-8\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\nfor attempt in {1..5}; do\n  yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm && break\n  if [[ ${attempt} -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\necho \"configuring logrotate\"\ncat >/etc/logrotate.conf <<'EOF'\n# see \"man logrotate\" for details\n# rotate log files weekly\nweekly\n\n# keep 2 weeks worth of backlogs\nrotate 2\n\n# create new (empty) log files after rotating old ones\ncreate\n\n# use date as a suffix of the rotated file\ndateext\n\n# uncomment this if you want your log files compressed\ncompress\n\n# RPM packages drop log rotation information into this directory\ninclude /etc/logrotate.d\n\n# no packages own wtmp and btmp -- we'll rotate them here\n/var/log/wtmp {\n    monthly\n    create 0664 root utmp\n        minsize 1M\n    rotate 1\n}\n\n/var/log/btmp {\n    missingok\n    monthly\n    create 0600 root utmp\n    rotate 1\n}\nEOF\n\necho \"configuring yum repository and running yum update\"\ncat >/etc/yum.repos.d/azure.repo <<'EOF'\n[azure-cli]\nname=azure-cli\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=yes\ngpgcheck=yes\n\n[azurecore]\nname=azurecore\nbaseurl=https://packages.microsoft.com/yumrepos/azurecore\nenabled=yes\ngpgcheck=no\nEOF\n\nsemanage fcontext -a -t var_log_t \"/var/log/journal(/.*)?\"\nmkdir -p /var/log/journal\n\nfor attempt in {1..5}; do\n  yum -y install clamav azsec-clamav azsec-monitor azure-cli azure-mdsd azure-security podman-docker openssl-perl python3 && break\n  # hack - we are installing python3 on hosts due to an issue with Azure Linux Extensions https://github.com/Azure/azure-linux-extensions/pull/1505\n  if [[ ${attempt} -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\necho \"applying firewall rules\"\n# https://access.redhat.com/security/cve/cve-2020-13401\ncat >/etc/sysctl.d/02-disable-accept-ra.conf <<'EOF'\nnet.ipv6.conf.all.accept_ra=0\nEOF\n\ncat >/etc/sysctl.d/01-disable-core.conf <<'EOF'\nkernel.core_pattern = |/bin/true\nEOF\nsysctl --system\n\nfirewall-cmd --add-port=80/tcp --permanent\nfirewall-cmd --add-port=8081/tcp --permanent\nfirewall-cmd --add-port=443/tcp --permanent\n\necho \"logging into prod acr\"\nexport AZURE_CLOUD_NAME=$AZURECLOUDNAME\naz login -i --allow-no-subscriptions\n\n# The managed identity that the VM runs as only has a single roleassignment.\n# This role assignment is ACRPull which is not necessarily present in the\n# subscription we're deploying into.  If the identity does not have any\n# role assignments scoped on the subscription we're deploying into, it will\n# not show on az login -i, which is why the below line is commented.\n# az account set -s \"$SUBSCRIPTIONID\"\n\n# Suppress emulation output for podman instead of docker for az acr compatability\nmkdir -p /etc/containers/\ntouch /etc/containers/nodocker\n\nmkdir -p /root/.docker\nREGISTRY_AUTH_FILE=/root/.docker/config.json az acr login --name \"$(sed -e 's|.*/||' <<<\"$ACRRESOURCEID\")\"\n\nMDMIMAGE=\"${RPIMAGE%%/*}/${MDMIMAGE##*/}\"\ndocker pull \"$MDMIMAGE\"\ndocker pull \"$RPIMAGE\"\ndocker pull \"$FLUENTBITIMAGE\"\n\naz logout\n\necho \"configuring fluentbit service\"\nmkdir -p /etc/fluentbit/\nmkdir -p /var/lib/fluent\n\ncat >/etc/fluentbit/fluentbit.conf <<'EOF'\n[INPUT]\n\tName systemd\n\tTag journald\n\tSystemd_Filter _COMM=aro\n\n[FILTER]\n\tName modify\n\tMatch journald\n\tRemove_wildcard _\n\tRemove TIMESTAMP\n\n[OUTPUT]\n\tName forward\n\tMatch *\n\tPort 29230\nEOF\n\necho \"FLUENTBITIMAGE=$FLUENTBITIMAGE\" >/etc/sysconfig/fluentbit\n\ncat >/etc/systemd/system/fluentbit.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\nStartLimitIntervalSec=0\n\n[Service]\nRestartSec=1s\nEnvironmentFile=/etc/sysconfig/fluentbit\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --security-opt label=disable \\\n  --entrypoint /opt/td-agent-bit/bin/td-agent-bit \\\n  --net=host \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -v /etc/fluentbit/fluentbit.conf:/etc/fluentbit/fluentbit.conf \\\n  -v /var/lib/fluent:/var/lib/fluent:z \\\n  -v /var/log/journal:/var/log/journal:ro \\\n  -v /etc/machine-id:/etc/machine-id:ro \\\n  $FLUENTBITIMAGE \\\n  -c /etc/fluentbit/fluentbit.conf\n\nExecStop=/usr/bin/docker stop %N\nRestart=always\nRestartSec=5\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring mdm service\"\ncat >/etc/sysconfig/mdm <<EOF\nMDMFRONTENDURL='$MDMFRONTENDURL'\nMDMIMAGE='$MDMIMAGE'\nMDMSOURCEENVIRONMENT='$LOCATION'\nMDMSOURCEROLE=gateway\nMDMSOURCEROLEINSTANCE='$(hostname)'\nEOF\n\nmkdir /var/etw\ncat >/etc/systemd/system/mdm.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/mdm\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --entrypoint /usr/sbin/MetricsExtension \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -m 2g \\\n  -v /etc/mdm.pem:/etc/mdm.pem \\\n  -v /var/etw:/var/etw:z \\\n  $MDMIMAGE \\\n  -CertFile /etc/mdm.pem \\\n  -FrontEndUrl $MDMFRONTENDURL \\\n  -Logger Console \\\n  -LogLevel Warning \\\n  -PrivateKeyFile /etc/mdm.pem \\\n  -SourceEnvironment $MDMSOURCEENVIRONMENT \\\n  -SourceRole $MDMSOURCEROLE \\\n  -SourceRoleInstance $MDMSOURCEROLEINSTANCE\nExecStop=/usr/bin/docker stop %N\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring aro-gateway service\"\ncat >/etc/sysconfig/aro-gateway <<EOF\nACR_RESOURCE_ID='$ACRRESOURCEID'\nDATABASE_ACCOUNT_NAME='$DATABASEACCOUNTNAME'\nAZURE_DBTOKEN_CLIENT_ID='$DBTOKENCLIENTID'\nDBTOKEN_URL='$DBTOKENURL'\nMDM_ACCOUNT=\"$RPMDMACCOUNT\"\nMDM_NAMESPACE=Gateway\nGATEWAY_DOMAINS='$GATEWAYDOMAINS'\nGATEWAY_FEATURES='$GATEWAYFEATURES'\nRPIMAGE='$RPIMAGE'\nEOF\n\ncat >/etc/systemd/system/aro-gateway.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/aro-gateway\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -e ACR_RESOURCE_ID \\\n  -e DATABASE_ACCOUNT_NAME \\\n  -e AZURE_DBTOKEN_CLIENT_ID \\\n  -e DBTOKEN_URL \\\n  -e GATEWAY_DOMAINS \\\n  -e GATEWAY_FEATURES \\\n  -e MDM_ACCOUNT \\\n  -e MDM_NAMESPACE \\\n  -m 2g \\\n  -p 80:8080 \\\n  -p 8081:8081 \\\n  -p 443:8443 \\\n  -v /run/systemd/journal:/run/systemd/journal \\\n  -v /var/etw:/var/etw:z \\\n  $RPIMAGE \\\n  gateway\nExecStop=/usr/bin/docker stop -t 3600 %N\nTimeoutStopSec=3600\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nchcon -R system_u:object_r:var_log_t:s0 /var/opt/microsoft/linuxmonagent\n\nmkdir -p /var/lib/waagent/Microsoft.Azure.KeyVault.Store\n\necho \"configuring mdsd and mdm services\"\nfor var in \"mdsd\" \"mdm\"; do\ncat >/etc/systemd/system/download-$var-credentials.service <<EOF\n[Unit]\nDescription=Periodic $var credentials refresh\n\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/download-credentials.sh $var\nEOF\n\ncat >/etc/systemd/system/download-$var-credentials.timer <<EOF\n[Unit]\nDescription=Periodic $var credentials refresh\nAfter=network-online.target\nWants=network-online.target\n\n[Timer]\nOnBootSec=0min\nOnCalendar=0/12:00:00\nAccuracySec=5s\n\n[Install]\nWantedBy=timers.target\nEOF\ndone\n\ncat >/usr/local/bin/download-credentials.sh <<EOF\n#!/bin/bash\nset -eu\n\nCOMPONENT=\"\\$1\"\necho \"Download \\$COMPONENT credentials\"\n\nTEMP_DIR=\\$(mktemp -d)\nexport AZURE_CONFIG_DIR=\\$(mktemp -d)\n\necho \"Logging into Azure...\"\nRETRIES=3\nwhile [ \"\\$RETRIES\" -gt 0 ]; do\n    if az login -i --allow-no-subscriptions\n    then\n        echo \"az login successful\"\n        break\n    else\n        echo \"az login failed. Retrying...\"\n        let RETRIES-=1\n        sleep 5\n    fi\ndone\n\ntrap \"cleanup\" EXIT\n\ncleanup() {\n  az logout\n  [[ \"\\$TEMP_DIR\" =~ /tmp/.+ ]] && rm -rf \\$TEMP_DIR\n  [[ \"\\$AZURE_CONFIG_DIR\" =~ /tmp/.+ ]] && rm -rf \\$AZURE_CONFIG_DIR\n}\n\nif [ \"\\$COMPONENT\" = \"mdm\" ]; then\n  CURRENT_CERT_FILE=\"/etc/mdm.pem\"\nelif [ \"\\$COMPONENT\" = \"mdsd\" ]; then\n  CURRENT_CERT_FILE=\"/var/lib/waagent/Microsoft.Azure.KeyVault.Store/mdsd.pem\"\nelse\n  echo Invalid usage && exit 1\nfi\n\nSECRET_NAME=\"gwy-\\${COMPONENT}\"\nNEW_CERT_FILE=\"\\$TEMP_DIR/\\$COMPONENT.pem\"\nfor attempt in {1..5}; do\n  az keyvault secret download --file \\$NEW_CERT_FILE --id \"https://$KEYVAULTPREFIX-gwy.$KEYVAULTDNSSUFFIX/secrets/\\$SECRET_NAME\" && break\n  if [[ \\$attempt -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\nif [ -f \\$NEW_CERT_FILE ]; then\n  if [ \"\\$COMPONENT\" = \"mdsd\" ]; then\n    chown syslog:syslog \\$NEW_CERT_FILE\n  else\n    sed -i -ne '1,/END CERTIFICATE/ p' \\$NEW_CERT_FILE\n  fi\n  if ! diff $NEW_CERT_FILE $CURRENT_CERT_FILE >/dev/null 2>&1; then\n    chmod 0600 \\$NEW_CERT_FILE\n    mv \\$NEW_CERT_FILE \\$CURRENT_CERT_FILE\n  fi\nelse\n  echo Failed to refresh certificate for \\$COMPONENT && exit 1\nfi\nEOF\n\nchmod u+x /usr/local/bin/download-credentials.sh\n\nsystemctl enable download-mdsd-credentials.timer\nsystemctl enable download-mdm-credentials.timer\n\n/usr/local/bin/download-credentials.sh mdsd\n/usr/local/bin/download-credentials.sh mdm\nMDSDCERTIFICATESAN=$(openssl x509 -in /var/lib/waagent/Microsoft.Azure.KeyVault.Store/mdsd.pem -noout -subject | sed -e 's/.*CN = //')\n\ncat >/etc/systemd/system/watch-mdm-credentials.service <<EOF\n[Unit]\nDescription=Watch for changes in mdm.pem and restarts the mdm service\n\n[Service]\nType=oneshot\nExecStart=/usr/bin/systemctl restart mdm.service\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\ncat >/etc/systemd/system/watch-mdm-credentials.path <<EOF\n[Path]\nPathModified=/etc/mdm.pem\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable watch-mdm-credentials.path\nsystemctl start watch-mdm-credentials.path\n\nmkdir /etc/systemd/system/mdsd.service.d\ncat >/etc/systemd/system/mdsd.service.d/override.conf <<'EOF'\n[Unit]\nAfter=network-online.target\nEOF\n\ncat >/etc/default/mdsd <<EOF\nMDSD_ROLE_PREFIX=/var/run/mdsd/default\nMDSD_OPTIONS=\"-A -d -r \\$MDSD_ROLE_PREFIX\"\n\nexport MONITORING_GCS_ENVIRONMENT='$MDSDENVIRONMENT'\nexport MONITORING_GCS_ACCOUNT='$RPMDSDACCOUNT'\nexport MONITORING_GCS_REGION='$LOCATION'\nexport MONITORING_GCS_AUTH_ID_TYPE=AuthKeyVault\nexport MONITORING_GCS_AUTH_ID='$MDSDCERTIFICATESAN'\nexport MONITORING_GCS_NAMESPACE='$RPMDSDNAMESPACE'\nexport MONITORING_CONFIG_VERSION='$GATEWAYMDSDCONFIGVERSION'\nexport MONITORING_USE_GENEVA_CONFIG_SERVICE=true\n\nexport MONITORING_TENANT='$LOCATION'\nexport MONITORING_ROLE=gateway\nexport MONITORING_ROLE_INSTANCE='$(hostname)'\n\nexport MDSD_MSGPACK_SORT_COLUMNS=1\nEOF\n\n# setting MONITORING_GCS_AUTH_ID_TYPE=AuthKeyVault seems to have caused mdsd not\n# to honour SSL_CERT_FILE any more, heaven only knows why.\nmkdir -p /usr/lib/ssl/certs\ncsplit -f /usr/lib/ssl/certs/cert- -b %03d.pem /etc/pki/tls/certs/ca-bundle.crt /^$/1 {*} >/dev/null\nc_rehash /usr/lib/ssl/certs\n\n# we leave clientId blank as long as only 1 managed identity assigned to vmss\n# if we have more than 1, we will need to populate with clientId used for off-node scanning\ncat >/etc/default/vsa-nodescan-agent.config <<EOF\n{\n    \"Nice\": 19,\n    \"Timeout\": 10800,\n    \"ClientId\": \"\",\n    \"TenantId\": \"$AZURESECPACKVSATENANTID\",\n    \"QualysStoreBaseUrl\": \"$AZURESECPACKQUALYSURL\",\n    \"ProcessTimeout\": 300,\n    \"CommandDelay\": 0\n  }\nEOF\n\n# we start a cron job to run every hour to ensure the said directory is accessible\n# by the correct user as it gets created by root and may cause a race condition\n# where root owns the dir instead of syslog\n# TODO: https://msazure.visualstudio.com/AzureRedHatOpenShift/_workitems/edit/12591207\ncat >/etc/cron.d/mdsd-chown-workaround <<EOF\nSHELL=/bin/bash\nPATH=/bin\n0 * * * * root chown syslog:syslog /var/opt/microsoft/linuxmonagent/eh/EventNotice/arorplogs*\nEOF\n\necho \"enabling aro services\"\nfor service in aro-gateway auoms azsecd azsecmond mdsd mdm chronyd fluentbit; do\n  systemctl enable $service.service\ndone\n\nfor scan in baseline clamav software; do\n  /usr/local/bin/azsecd config -s $scan -d P1D\ndone\n\necho \"rebooting\"\nrestorecon -RF /var/log/*\n(sleep 30; reboot) &\n", "num_lines": 484}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"setting ssh password authentication\"\n# We need to manually set PasswordAuthentication to true in order for the VMSS Access JIT to work\nsed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config\nsystemctl reload sshd.service\n\necho \"running RHUI fix\"\nyum update -y --disablerepo='*' --enablerepo='rhui-microsoft-azure*'\n\necho \"running yum update\"\nyum -y -x WALinuxAgent -x WALinuxAgent-udev update --allowerasing\n\necho \"extending partition table\"\n# Linux block devices are inconsistently named\n# it's difficult to tie the lvm pv to the physical disk using /dev/disk files, which is why lvs is used here\nphysicalDisk=\"$(lvs -o devices -a | head -n2 | tail -n1 | cut -d ' ' -f 3 | cut -d \\( -f 1 | tr -d '[:digit:]')\"\ngrowpart \"$physicalDisk\" 2\n\necho \"extending filesystems\"\nlvextend -l +20%FREE /dev/rootvg/rootlv\nxfs_growfs /\n\nlvextend -l +100%FREE /dev/rootvg/varlv\nxfs_growfs /var\n\necho \"importing rpm repositories\"\nrpm --import https://dl.fedoraproject.org/pub/epel/RPM-GPG-KEY-EPEL-8\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\nfor attempt in {1..5}; do\n  yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm && break\n  if [[ ${attempt} -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\necho \"configuring logrotate\"\ncat >/etc/logrotate.conf <<'EOF'\n# see \"man logrotate\" for details\n# rotate log files weekly\nweekly\n\n# keep 2 weeks worth of backlogs\nrotate 2\n\n# create new (empty) log files after rotating old ones\ncreate\n\n# use date as a suffix of the rotated file\ndateext\n\n# uncomment this if you want your log files compressed\ncompress\n\n# RPM packages drop log rotation information into this directory\ninclude /etc/logrotate.d\n\n# no packages own wtmp and btmp -- we'll rotate them here\n/var/log/wtmp {\n    monthly\n    create 0664 root utmp\n        minsize 1M\n    rotate 1\n}\n\n/var/log/btmp {\n    missingok\n    monthly\n    create 0600 root utmp\n    rotate 1\n}\nEOF\n\necho \"configuring yum repository and running yum update\"\ncat >/etc/yum.repos.d/azure.repo <<'EOF'\n[azure-cli]\nname=azure-cli\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=yes\ngpgcheck=yes\n\n[azurecore]\nname=azurecore\nbaseurl=https://packages.microsoft.com/yumrepos/azurecore\nenabled=yes\ngpgcheck=no\nEOF\n\nsemanage fcontext -a -t var_log_t \"/var/log/journal(/.*)?\"\nmkdir -p /var/log/journal\n\nfor attempt in {1..5}; do\nyum -y install clamav azsec-clamav azsec-monitor azure-cli azure-mdsd azure-security podman podman-docker openssl-perl python3 && break\n  # hack - we are installing python3 on hosts due to an issue with Azure Linux Extensions https://github.com/Azure/azure-linux-extensions/pull/1505\n  if [[ ${attempt} -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\n# https://access.redhat.com/security/cve/cve-2020-13401\necho \"applying firewall rules\"\ncat >/etc/sysctl.d/02-disable-accept-ra.conf <<'EOF'\nnet.ipv6.conf.all.accept_ra=0\nEOF\n\ncat >/etc/sysctl.d/01-disable-core.conf <<'EOF'\nkernel.core_pattern = |/bin/true\nEOF\nsysctl --system\n\nfirewall-cmd --add-port=443/tcp --permanent\nfirewall-cmd --add-port=444/tcp --permanent\nfirewall-cmd --add-port=445/tcp --permanent\nfirewall-cmd --add-port=2222/tcp --permanent\n\nexport AZURE_CLOUD_NAME=$AZURECLOUDNAME\n\necho \"logging into prod acr\"\naz login -i --allow-no-subscriptions\n\n# Suppress emulation output for podman instead of docker for az acr compatability\nmkdir -p /etc/containers/\ntouch /etc/containers/nodocker\n\nmkdir -p /root/.docker\nREGISTRY_AUTH_FILE=/root/.docker/config.json az acr login --name \"$(sed -e 's|.*/||' <<<\"$ACRRESOURCEID\")\"\n\nMDMIMAGE=\"${RPIMAGE%%/*}/${MDMIMAGE##*/}\"\ndocker pull \"$MDMIMAGE\"\ndocker pull \"$RPIMAGE\"\ndocker pull \"$FLUENTBITIMAGE\"\n\naz logout\n\necho \"configuring fluentbit service\"\nmkdir -p /etc/fluentbit/\nmkdir -p /var/lib/fluent\n\ncat >/etc/fluentbit/fluentbit.conf <<'EOF'\n[INPUT]\n\tName systemd\n\tTag journald\n\tSystemd_Filter _COMM=aro\n\n[FILTER]\n\tName modify\n\tMatch journald\n\tRemove_wildcard _\n\tRemove TIMESTAMP\n\n[FILTER]\n\tName rewrite_tag\n\tMatch journald\n\tRule $LOGKIND asyncqos asyncqos true\n\n[FILTER]\n\tName modify\n\tMatch asyncqos\n\tRemove CLIENT_PRINCIPAL_NAME\n\tRemove FILE\n\tRemove COMPONENT\n\n[FILTER]\n\tName rewrite_tag\n\tMatch journald\n\tRule $LOGKIND ifxaudit ifxaudit false\n\n[OUTPUT]\n\tName forward\n\tMatch *\n\tPort 29230\nEOF\n\necho \"FLUENTBITIMAGE=$FLUENTBITIMAGE\" >/etc/sysconfig/fluentbit\n\ncat >/etc/systemd/system/fluentbit.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\nStartLimitIntervalSec=0\n\n[Service]\nRestartSec=1s\nEnvironmentFile=/etc/sysconfig/fluentbit\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --security-opt label=disable \\\n  --entrypoint /opt/td-agent-bit/bin/td-agent-bit \\\n  --net=host \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -v /etc/fluentbit/fluentbit.conf:/etc/fluentbit/fluentbit.conf \\\n  -v /var/lib/fluent:/var/lib/fluent:z \\\n  -v /var/log/journal:/var/log/journal:ro \\\n  -v /etc/machine-id:/etc/machine-id:ro \\\n  $FLUENTBITIMAGE \\\n  -c /etc/fluentbit/fluentbit.conf\n\nExecStop=/usr/bin/docker stop %N\nRestart=always\nRestartSec=5\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nmkdir /etc/aro-rp\nbase64 -d <<<\"$ADMINAPICABUNDLE\" >/etc/aro-rp/admin-ca-bundle.pem\nif [[ -n \"$ARMAPICABUNDLE\" ]]; then\n  base64 -d <<<\"$ARMAPICABUNDLE\" >/etc/aro-rp/arm-ca-bundle.pem\nfi\nchown -R 1000:1000 /etc/aro-rp\n\necho \"configuring mdm service\"\ncat >/etc/sysconfig/mdm <<EOF\nMDMFRONTENDURL='$MDMFRONTENDURL'\nMDMIMAGE='$MDMIMAGE'\nMDMSOURCEENVIRONMENT='$LOCATION'\nMDMSOURCEROLE=rp\nMDMSOURCEROLEINSTANCE='$(hostname)'\nEOF\n\nmkdir /var/etw\ncat >/etc/systemd/system/mdm.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/mdm\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --entrypoint /usr/sbin/MetricsExtension \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -m 2g \\\n  -v /etc/mdm.pem:/etc/mdm.pem \\\n  -v /var/etw:/var/etw:z \\\n  $MDMIMAGE \\\n  -CertFile /etc/mdm.pem \\\n  -FrontEndUrl $MDMFRONTENDURL \\\n  -Logger Console \\\n  -LogLevel Warning \\\n  -PrivateKeyFile /etc/mdm.pem \\\n  -SourceEnvironment $MDMSOURCEENVIRONMENT \\\n  -SourceRole $MDMSOURCEROLE \\\n  -SourceRoleInstance $MDMSOURCEROLEINSTANCE\nExecStop=/usr/bin/docker stop %N\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring aro-rp service\"\ncat >/etc/sysconfig/aro-rp <<EOF\nACR_RESOURCE_ID='$ACRRESOURCEID'\nADMIN_API_CLIENT_CERT_COMMON_NAME='$ADMINAPICLIENTCERTCOMMONNAME'\nARM_API_CLIENT_CERT_COMMON_NAME='$ARMAPICLIENTCERTCOMMONNAME'\nAZURE_ARM_CLIENT_ID='$ARMCLIENTID'\nAZURE_FP_CLIENT_ID='$FPCLIENTID'\nAZURE_FP_SERVICE_PRINCIPAL_ID='$FPSERVICEPRINCIPALID'\nBILLING_E2E_STORAGE_ACCOUNT_ID='$BILLINGE2ESTORAGEACCOUNTID'\nCLUSTER_MDSD_ACCOUNT='$CLUSTERMDSDACCOUNT'\nCLUSTER_MDSD_CONFIG_VERSION='$CLUSTERMDSDCONFIGVERSION'\nCLUSTER_MDSD_NAMESPACE='$CLUSTERMDSDNAMESPACE'\nDATABASE_ACCOUNT_NAME='$DATABASEACCOUNTNAME'\nDOMAIN_NAME='$LOCATION.$CLUSTERPARENTDOMAINNAME'\nGATEWAY_DOMAINS='$GATEWAYDOMAINS'\nGATEWAY_RESOURCEGROUP='$GATEWAYRESOURCEGROUPNAME'\nKEYVAULT_PREFIX='$KEYVAULTPREFIX'\nMDM_ACCOUNT='$RPMDMACCOUNT'\nMDM_NAMESPACE=RP\nMDSD_ENVIRONMENT='$MDSDENVIRONMENT'\nRP_FEATURES='$RPFEATURES'\nRPIMAGE='$RPIMAGE'\nARO_INSTALL_VIA_HIVE='$CLUSTERSINSTALLVIAHIVE'\nARO_HIVE_DEFAULT_INSTALLER_PULLSPEC='$CLUSTERDEFAULTINSTALLERPULLSPEC'\nARO_ADOPT_BY_HIVE='$CLUSTERSADOPTBYHIVE'\nUSE_CHECKACCESS='$USECHECKACCESS'\nEOF\n\ncat >/etc/systemd/system/aro-rp.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/aro-rp\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -e ACR_RESOURCE_ID \\\n  -e ADMIN_API_CLIENT_CERT_COMMON_NAME \\\n  -e ARM_API_CLIENT_CERT_COMMON_NAME \\\n  -e AZURE_ARM_CLIENT_ID \\\n  -e AZURE_FP_CLIENT_ID \\\n  -e BILLING_E2E_STORAGE_ACCOUNT_ID \\\n  -e CLUSTER_MDSD_ACCOUNT \\\n  -e CLUSTER_MDSD_CONFIG_VERSION \\\n  -e CLUSTER_MDSD_NAMESPACE \\\n  -e DATABASE_ACCOUNT_NAME \\\n  -e DOMAIN_NAME \\\n  -e GATEWAY_DOMAINS \\\n  -e GATEWAY_RESOURCEGROUP \\\n  -e KEYVAULT_PREFIX \\\n  -e MDM_ACCOUNT \\\n  -e MDM_NAMESPACE \\\n  -e MDSD_ENVIRONMENT \\\n  -e RP_FEATURES \\\n  -e ARO_INSTALL_VIA_HIVE \\\n  -e ARO_HIVE_DEFAULT_INSTALLER_PULLSPEC \\\n  -e ARO_ADOPT_BY_HIVE \\\n  -e USE_CHECKACCESS \\\n  -m 2g \\\n  -p 443:8443 \\\n  -v /etc/aro-rp:/etc/aro-rp \\\n  -v /run/systemd/journal:/run/systemd/journal \\\n  -v /var/etw:/var/etw:z \\\n  $RPIMAGE \\\n  rp\nExecStop=/usr/bin/docker stop -t 3600 %N\nTimeoutStopSec=3600\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring aro-dbtoken service\"\ncat >/etc/sysconfig/aro-dbtoken <<EOF\nDATABASE_ACCOUNT_NAME='$DATABASEACCOUNTNAME'\nAZURE_DBTOKEN_CLIENT_ID='$DBTOKENCLIENTID'\nAZURE_GATEWAY_SERVICE_PRINCIPAL_ID='$GATEWAYSERVICEPRINCIPALID'\nKEYVAULT_PREFIX='$KEYVAULTPREFIX'\nMDM_ACCOUNT='$RPMDMACCOUNT'\nMDM_NAMESPACE=DBToken\nRPIMAGE='$RPIMAGE'\nEOF\n\ncat >/etc/systemd/system/aro-dbtoken.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/aro-dbtoken\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -e AZURE_GATEWAY_SERVICE_PRINCIPAL_ID \\\n  -e DATABASE_ACCOUNT_NAME \\\n  -e AZURE_DBTOKEN_CLIENT_ID \\\n  -e KEYVAULT_PREFIX \\\n  -e MDM_ACCOUNT \\\n  -e MDM_NAMESPACE \\\n  -m 2g \\\n  -p 445:8445 \\\n  -v /run/systemd/journal:/run/systemd/journal \\\n  -v /var/etw:/var/etw:z \\\n  $RPIMAGE \\\n  dbtoken\nExecStop=/usr/bin/docker stop -t 3600 %N\nTimeoutStopSec=3600\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring aro-monitor service\"\ncat >/etc/sysconfig/aro-monitor <<EOF\nCLUSTER_MDM_ACCOUNT='$CLUSTERMDMACCOUNT'\nCLUSTER_MDM_NAMESPACE=BBM\nDATABASE_ACCOUNT_NAME='$DATABASEACCOUNTNAME'\nKEYVAULT_PREFIX='$KEYVAULTPREFIX'\nMDM_ACCOUNT='$RPMDMACCOUNT'\nMDM_NAMESPACE=BBM\nRPIMAGE='$RPIMAGE'\nEOF\n\ncat >/etc/systemd/system/aro-monitor.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nEnvironmentFile=/etc/sysconfig/aro-monitor\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -e CLUSTER_MDM_ACCOUNT \\\n  -e CLUSTER_MDM_NAMESPACE \\\n  -e DATABASE_ACCOUNT_NAME \\\n  -e KEYVAULT_PREFIX \\\n  -e MDM_ACCOUNT \\\n  -e MDM_NAMESPACE \\\n  -m 2.5g \\\n  -v /run/systemd/journal:/run/systemd/journal \\\n  -v /var/etw:/var/etw:z \\\n  $RPIMAGE \\\n  monitor\nRestart=always\nRestartSec=1\nStartLimitInterval=0\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring aro-portal service\"\ncat >/etc/sysconfig/aro-portal <<EOF\nAZURE_PORTAL_ACCESS_GROUP_IDS='$PORTALACCESSGROUPIDS'\nAZURE_PORTAL_CLIENT_ID='$PORTALCLIENTID'\nAZURE_PORTAL_ELEVATED_GROUP_IDS='$PORTALELEVATEDGROUPIDS'\nDATABASE_ACCOUNT_NAME='$DATABASEACCOUNTNAME'\nKEYVAULT_PREFIX='$KEYVAULTPREFIX'\nMDM_ACCOUNT='$RPMDMACCOUNT'\nMDM_NAMESPACE=Portal\nPORTAL_HOSTNAME='$LOCATION.admin.$RPPARENTDOMAINNAME'\nRPIMAGE='$RPIMAGE'\nEOF\n\ncat >/etc/systemd/system/aro-portal.service <<'EOF'\n[Unit]\nAfter=network-online.target\nWants=network-online.target\nStartLimitInterval=0\n\n[Service]\nEnvironmentFile=/etc/sysconfig/aro-portal\nExecStartPre=-/usr/bin/docker rm -f %N\nExecStart=/usr/bin/docker run \\\n  --hostname %H \\\n  --name %N \\\n  --rm \\\n  --cap-drop net_raw \\\n  -e AZURE_PORTAL_ACCESS_GROUP_IDS \\\n  -e AZURE_PORTAL_CLIENT_ID \\\n  -e AZURE_PORTAL_ELEVATED_GROUP_IDS \\\n  -e DATABASE_ACCOUNT_NAME \\\n  -e KEYVAULT_PREFIX \\\n  -e MDM_ACCOUNT \\\n  -e MDM_NAMESPACE \\\n  -e PORTAL_HOSTNAME \\\n  -m 2g \\\n  -p 444:8444 \\\n  -p 2222:2222 \\\n  -v /run/systemd/journal:/run/systemd/journal \\\n  -v /var/etw:/var/etw:z \\\n  $RPIMAGE \\\n  portal\nRestart=always\nRestartSec=1\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\necho \"configuring mdsd and mdm services\"\nchcon -R system_u:object_r:var_log_t:s0 /var/opt/microsoft/linuxmonagent\n\nmkdir -p /var/lib/waagent/Microsoft.Azure.KeyVault.Store\n\nfor var in \"mdsd\" \"mdm\"; do\ncat >/etc/systemd/system/download-$var-credentials.service <<EOF\n[Unit]\nDescription=Periodic $var credentials refresh\n\n[Service]\nType=oneshot\nExecStart=/usr/local/bin/download-credentials.sh $var\nEOF\n\ncat >/etc/systemd/system/download-$var-credentials.timer <<EOF\n[Unit]\nDescription=Periodic $var credentials refresh\nAfter=network-online.target\nWants=network-online.target\n\n[Timer]\nOnBootSec=0min\nOnCalendar=0/12:00:00\nAccuracySec=5s\n\n[Install]\nWantedBy=timers.target\nEOF\ndone\n\ncat >/usr/local/bin/download-credentials.sh <<EOF\n#!/bin/bash\nset -eu\n\nCOMPONENT=\"\\$1\"\necho \"Download \\$COMPONENT credentials\"\n\nTEMP_DIR=\\$(mktemp -d)\nexport AZURE_CONFIG_DIR=\\$(mktemp -d)\n\necho \"Logging into Azure...\"\nRETRIES=3\nwhile [ \"\\$RETRIES\" -gt 0 ]; do\n    if az login -i --allow-no-subscriptions\n    then\n        echo \"az login successful\"\n        break\n    else\n        echo \"az login failed. Retrying...\"\n        let RETRIES-=1\n        sleep 5\n    fi\ndone\n\ntrap \"cleanup\" EXIT\n\ncleanup() {\n  az logout\n  [[ \"\\$TEMP_DIR\" =~ /tmp/.+ ]] && rm -rf \\$TEMP_DIR\n  [[ \"\\$AZURE_CONFIG_DIR\" =~ /tmp/.+ ]] && rm -rf \\$AZURE_CONFIG_DIR\n}\n\nif [ \"\\$COMPONENT\" = \"mdm\" ]; then\n  CURRENT_CERT_FILE=\"/etc/mdm.pem\"\nelif [ \"\\$COMPONENT\" = \"mdsd\" ]; then\n  CURRENT_CERT_FILE=\"/var/lib/waagent/Microsoft.Azure.KeyVault.Store/mdsd.pem\"\nelse\n  echo Invalid usage && exit 1\nfi\n\nSECRET_NAME=\"rp-\\${COMPONENT}\"\nNEW_CERT_FILE=\"\\$TEMP_DIR/\\$COMPONENT.pem\"\nfor attempt in {1..5}; do\n  az keyvault secret download --file \\$NEW_CERT_FILE --id \"https://$KEYVAULTPREFIX-svc.$KEYVAULTDNSSUFFIX/secrets/\\$SECRET_NAME\" && break\n  if [[ \\$attempt -lt 5 ]]; then sleep 10; else exit 1; fi\ndone\n\nif [ -f \\$NEW_CERT_FILE ]; then\n  if [ \"\\$COMPONENT\" = \"mdsd\" ]; then\n    chown syslog:syslog \\$NEW_CERT_FILE\n  else\n    sed -i -ne '1,/END CERTIFICATE/ p' \\$NEW_CERT_FILE\n  fi\n  if ! diff $NEW_CERT_FILE $CURRENT_CERT_FILE >/dev/null 2>&1; then\n    chmod 0600 \\$NEW_CERT_FILE\n    mv \\$NEW_CERT_FILE \\$CURRENT_CERT_FILE\n  fi\nelse\n  echo Failed to refresh certificate for \\$COMPONENT && exit 1\nfi\nEOF\n\nchmod u+x /usr/local/bin/download-credentials.sh\n\nsystemctl enable download-mdsd-credentials.timer\nsystemctl enable download-mdm-credentials.timer\n\n/usr/local/bin/download-credentials.sh mdsd\n/usr/local/bin/download-credentials.sh mdm\nMDSDCERTIFICATESAN=$(openssl x509 -in /var/lib/waagent/Microsoft.Azure.KeyVault.Store/mdsd.pem -noout -subject | sed -e 's/.*CN = //')\n\ncat >/etc/systemd/system/watch-mdm-credentials.service <<EOF\n[Unit]\nDescription=Watch for changes in mdm.pem and restarts the mdm service\n\n[Service]\nType=oneshot\nExecStart=/usr/bin/systemctl restart mdm.service\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\ncat >/etc/systemd/system/watch-mdm-credentials.path <<EOF\n[Path]\nPathModified=/etc/mdm.pem\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable watch-mdm-credentials.path\nsystemctl start watch-mdm-credentials.path\n\nmkdir /etc/systemd/system/mdsd.service.d\ncat >/etc/systemd/system/mdsd.service.d/override.conf <<'EOF'\n[Unit]\nAfter=network-online.target\nEOF\n\ncat >/etc/default/mdsd <<EOF\nMDSD_ROLE_PREFIX=/var/run/mdsd/default\nMDSD_OPTIONS=\"-A -d -r \\$MDSD_ROLE_PREFIX\"\n\nexport MONITORING_GCS_ENVIRONMENT='$MDSDENVIRONMENT'\nexport MONITORING_GCS_ACCOUNT='$RPMDSDACCOUNT'\nexport MONITORING_GCS_REGION='$LOCATION'\nexport MONITORING_GCS_AUTH_ID_TYPE=AuthKeyVault\nexport MONITORING_GCS_AUTH_ID='$MDSDCERTIFICATESAN'\nexport MONITORING_GCS_NAMESPACE='$RPMDSDNAMESPACE'\nexport MONITORING_CONFIG_VERSION='$RPMDSDCONFIGVERSION'\nexport MONITORING_USE_GENEVA_CONFIG_SERVICE=true\n\nexport MONITORING_TENANT='$LOCATION'\nexport MONITORING_ROLE=rp\nexport MONITORING_ROLE_INSTANCE='$(hostname)'\n\nexport MDSD_MSGPACK_SORT_COLUMNS=1\nEOF\n\n# setting MONITORING_GCS_AUTH_ID_TYPE=AuthKeyVault seems to have caused mdsd not\n# to honour SSL_CERT_FILE any more, heaven only knows why.\nmkdir -p /usr/lib/ssl/certs\ncsplit -f /usr/lib/ssl/certs/cert- -b %03d.pem /etc/pki/tls/certs/ca-bundle.crt /^$/1 {*} >/dev/null\nc_rehash /usr/lib/ssl/certs\n\n# we leave clientId blank as long as only 1 managed identity assigned to vmss\n# if we have more than 1, we will need to populate with clientId used for off-node scanning\ncat >/etc/default/vsa-nodescan-agent.config <<EOF\n{\n    \"Nice\": 19,\n    \"Timeout\": 10800,\n    \"ClientId\": \"\",\n    \"TenantId\": \"$AZURESECPACKVSATENANTID\",\n    \"QualysStoreBaseUrl\": \"$AZURESECPACKQUALYSURL\",\n    \"ProcessTimeout\": 300,\n    \"CommandDelay\": 0\n  }\nEOF\n\n# we start a cron job to run every hour to ensure the said directory is accessible\n# by the correct user as it gets created by root and may cause a race condition\n# where root owns the dir instead of syslog\n# TODO: https://msazure.visualstudio.com/AzureRedHatOpenShift/_workitems/edit/12591207\ncat >/etc/cron.d/mdsd-chown-workaround <<EOF\nSHELL=/bin/bash\nPATH=/bin\n0 * * * * root chown syslog:syslog /var/opt/microsoft/linuxmonagent/eh/EventNotice/arorplogs*\nEOF\n\necho \"enabling aro services\"\nfor service in aro-dbtoken aro-monitor aro-portal aro-rp auoms azsecd azsecmond mdsd mdm chronyd fluentbit; do\n  systemctl enable $service.service\ndone\n\nfor scan in baseline clamav software; do\n  /usr/local/bin/azsecd config -s $scan -d P1D\ndone\n\necho \"rebooting\"\nrestorecon -RF /var/log/*\n(sleep 30; reboot) &\n", "num_lines": 670}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eu\n\ntemplate_src_path=\"gktemplates-src\"\ntemplate_path=\"gktemplates\"\n\nmain() {\n\n  if [[ ! -d ${template_path} ]]; then\n    mkdir -p \"${template_path}\"\n  fi\n\n  for tmpl in $(find ${template_src_path} -name '*.tmpl'); do\n    filename=\"$(basename -- ${tmpl} .tmpl).yaml\"\n    echo \"Generating ${template_path}/${filename} from ${tmpl}\"\n    gomplate -f \"${tmpl}\" > \"${template_path}/${filename}\"\n\n    src_dir=\"$(dirname \"${tmpl}\")\"\n    for req in src.rego src_test.rego; do\n      if [[ ! -f \"${src_dir}/${req}\" ]]; then\n        echo \"${src_dir}/${req} is missing\"\n        exit 1\n      fi\n    done\n  done\n}\n\nmain\n", "num_lines": 30}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -eu\n\ntemplate_src_path=\"gktemplates-src\"\nconstraint_path=\"gkconstraints\"\nconstraint_test_path=\"gkconstraints-test\"\n\necho \"opa test:\"\nfor folder in ${template_src_path}/*\ndo\n  echo \"opa test ${folder}/*.rego\"\n  opa test ${folder}/*.rego\ndone\n\necho \"gator test:\"\nif [[ ! -d ${constraint_test_path} ]]; then\n  mkdir -p \"${constraint_test_path}\"\nfi\nfor file in ${constraint_path}/*\ndo\n  echo \"expand constraints $file\"\n  filename=\"$(basename -- ${file})\"\n  sed 's/{{.Enforcement}}/deny/g' $file > $constraint_test_path/$filename\ndone\n\n\nfor folder in ${template_src_path}/*\ndo\n  echo \"gator verify ${folder}\"\n  gator verify ${folder}\ndone\n", "num_lines": 33}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\ncd s2/cmd/_s2sx/ || exit 1\ngo generate .\n", "num_lines": 5}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -race -coverprofile=profile.out -covermode=atomic \"$d\"\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -race -coverprofile=profile.out -covermode=atomic \"$d\"\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -race -coverprofile=profile.out -covermode=atomic \"$d\"\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Run all the different permutations of all the tests and other things\n# This helps ensure that nothing gets broken.\n\n_tests() {\n    local vet=\"\" # TODO: make it off\n    local gover=$( ${gocmd} version | cut -f 3 -d ' ' )\n    [[ $( ${gocmd} version ) == *\"gccgo\"* ]] && zcover=0\n    [[ $( ${gocmd} version ) == *\"gollvm\"* ]] && zcover=0\n    case $gover in\n        go1.[7-9]*|go1.1[0-9]*|go2.*|devel*) true ;;\n        *) return 1\n    esac\n    # note that codecgen requires fastpath, so you cannot do \"codecgen codec.notfastpath\"\n    # we test the following permutations wnich all execute different code paths as below.\n    echo \"TestCodecSuite: (fastpath/unsafe), (!fastpath/unsafe), (fastpath/!unsafe), (!fastpath/!unsafe), (codecgen/unsafe)\"\n    local echo=1\n    local nc=2 # count\n    local cpus=\"1,$(nproc)\"\n    # if using the race detector, then set nc to\n    if [[ \" ${zargs[@]} \" =~ \"-race\" ]]; then\n        cpus=\"$(nproc)\"\n    fi\n    local a=( \"\" \"codec.notfastpath\" \"codec.safe\" \"codec.notfastpath codec.safe\"  \"codecgen\" )\n    local b=()\n    local c=()\n    for i in \"${a[@]}\"\n    do\n        local i2=${i:-default}\n        [[ \"$zwait\" == \"1\" ]] && echo \">>>> TAGS: 'alltests $i'; RUN: 'TestCodecSuite'\"\n        [[ \"$zcover\" == \"1\" ]] && c=( -coverprofile \"${i2// /-}.cov.out\" )\n        true &&\n            ${gocmd} vet -printfuncs \"errorf\" \"$@\" &&\n            if [[ \"$echo\" == 1 ]]; then set -o xtrace; fi &&\n            ${gocmd} test ${zargs[*]} ${ztestargs[*]} -vet \"$vet\" -tags \"alltests $i\" -count $nc -cpu $cpus -run \"TestCodecSuite\" \"${c[@]}\" \"$@\" &\n        if [[ \"$echo\" == 1 ]]; then set +o xtrace; fi\n        b+=(\"${i2// /-}.cov.out\")\n        [[ \"$zwait\" == \"1\" ]] && wait\n            \n        # if [[ \"$?\" != 0 ]]; then return 1; fi\n    done\n    if [[ \"$zextra\" == \"1\" ]]; then\n        [[ \"$zwait\" == \"1\" ]] && echo \">>>> TAGS: 'codec.notfastpath x'; RUN: 'Test.*X$'\"\n        [[ \"$zcover\" == \"1\" ]] && c=( -coverprofile \"x.cov.out\" )\n        ${gocmd} test ${zargs[*]} ${ztestargs[*]} -vet \"$vet\" -tags \"codec.notfastpath x\" -count $nc -run 'Test.*X$' \"${c[@]}\" &\n        b+=(\"x.cov.out\")\n        [[ \"$zwait\" == \"1\" ]] && wait\n    fi\n    wait\n    # go tool cover is not supported for gccgo, gollvm, other non-standard go compilers\n    [[ \"$zcover\" == \"1\" ]] &&\n        command -v gocovmerge &&\n        gocovmerge \"${b[@]}\" > __merge.cov.out &&\n        ${gocmd} tool cover -html=__merge.cov.out\n}\n\n# is a generation needed?\n_ng() {\n    local a=\"$1\"\n    if [[ ! -e \"$a\" ]]; then echo 1; return; fi \n    for i in `ls -1 *.go.tmpl gen.go values_test.go`\n    do\n        if [[ \"$a\" -ot \"$i\" ]]; then echo 1; return; fi \n    done\n}\n\n_prependbt() {\n    cat > ${2} <<EOF\n// +build generated\n\nEOF\n    cat ${1} >> ${2}\n    rm -f ${1}\n}\n\n# _build generates fast-path.go and gen-helper.go.\n_build() {\n    if ! [[ \"${zforce}\" || $(_ng \"fast-path.generated.go\") || $(_ng \"gen-helper.generated.go\") || $(_ng \"gen.generated.go\") ]]; then return 0; fi \n    \n    if [ \"${zbak}\" ]; then\n        _zts=`date '+%m%d%Y_%H%M%S'`\n        _gg=\".generated.go\"\n        [ -e \"gen-helper${_gg}\" ] && mv gen-helper${_gg} gen-helper${_gg}__${_zts}.bak\n        [ -e \"fast-path${_gg}\" ] && mv fast-path${_gg} fast-path${_gg}__${_zts}.bak\n        [ -e \"gen${_gg}\" ] && mv gen${_gg} gen${_gg}__${_zts}.bak\n    fi \n    rm -f gen-helper.generated.go fast-path.generated.go gen.generated.go \\\n       *safe.generated.go *_generated_test.go *.generated_ffjson_expose.go \n\n    cat > gen.generated.go <<EOF\n// +build codecgen.exec\n\n// Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.\n// Use of this source code is governed by a MIT license found in the LICENSE file.\n\npackage codec\n\n// DO NOT EDIT. THIS FILE IS AUTO-GENERATED FROM gen-dec-(map|array).go.tmpl\n\nconst genDecMapTmpl = \\`\nEOF\n    cat >> gen.generated.go < gen-dec-map.go.tmpl\n    cat >> gen.generated.go <<EOF\n\\`\n\nconst genDecListTmpl = \\`\nEOF\n    cat >> gen.generated.go < gen-dec-array.go.tmpl\n    cat >> gen.generated.go <<EOF\n\\`\n\nconst genEncChanTmpl = \\`\nEOF\n    cat >> gen.generated.go < gen-enc-chan.go.tmpl\n    cat >> gen.generated.go <<EOF\n\\`\nEOF\n    cat > gen-from-tmpl.codec.generated.go <<EOF\npackage codec \nfunc GenRunTmpl2Go(in, out string) { genRunTmpl2Go(in, out) }\nfunc GenRunSortTmpl2Go(in, out string) { genRunSortTmpl2Go(in, out) }\nEOF\n\n    # stub xxxRv and xxxRvSlice creation, before you create it\n    cat > gen-from-tmpl.sort-slice-stubs.generated.go <<EOF\n// +build codecgen.sort_slice\n\npackage codec\n\nimport \"reflect\"\nimport \"time\"\n\nEOF\n\n    for i in string bool uint64 int64 float64 bytes time; do\n        local i2=$i\n        case $i in\n            'time' ) i2=\"time.Time\";;\n            'bytes' ) i2=\"[]byte\";;\n        esac\n\n        cat >> gen-from-tmpl.sort-slice-stubs.generated.go <<EOF\ntype ${i}Rv struct { v ${i2}; r reflect.Value }\n\ntype ${i}RvSlice []${i}Rv\n\nfunc (${i}RvSlice) Len() int { return 0 }\nfunc (${i}RvSlice) Less(i, j int) bool { return false }\nfunc (${i}RvSlice) Swap(i, j int) {}\n\ntype ${i}Intf struct { v ${i2}; i interface{} }\n\ntype ${i}IntfSlice []${i}Intf\n\nfunc (${i}IntfSlice) Len() int { return 0 }\nfunc (${i}IntfSlice) Less(i, j int) bool { return false }\nfunc (${i}IntfSlice) Swap(i, j int) {}\n\nEOF\n    done\n\n    sed -e 's+// __DO_NOT_REMOVE__NEEDED_FOR_REPLACING__IMPORT_PATH__FOR_CODEC_BENCH__+import . \"github.com/ugorji/go/codec\"+' \\\n        shared_test.go > bench/shared_test.go\n\n    # explicitly return 0 if this passes, else return 1\n    local btags=\"codec.notfastpath codec.safe codecgen.exec\"\n    rm -f sort-slice.generated.go fast-path.generated.go gen-helper.generated.go mammoth_generated_test.go mammoth2_generated_test.go\n    \n    cat > gen-from-tmpl.sort-slice.generated.go <<EOF\n// +build ignore\n\npackage main\n\nimport \"${zpkg}\"\n\nfunc main() {\ncodec.GenRunSortTmpl2Go(\"sort-slice.go.tmpl\", \"sort-slice.generated.go\")\n}\nEOF\n\n    ${gocmd} run -tags \"$btags codecgen.sort_slice\" gen-from-tmpl.sort-slice.generated.go || return 1\n    rm -f gen-from-tmpl.sort-slice.generated.go\n    \n    cat > gen-from-tmpl.generated.go <<EOF\n// +build ignore\n\npackage main\n\nimport \"${zpkg}\"\n\nfunc main() {\ncodec.GenRunTmpl2Go(\"fast-path.go.tmpl\", \"fast-path.generated.go\")\ncodec.GenRunTmpl2Go(\"gen-helper.go.tmpl\", \"gen-helper.generated.go\")\ncodec.GenRunTmpl2Go(\"mammoth-test.go.tmpl\", \"mammoth_generated_test.go\")\ncodec.GenRunTmpl2Go(\"mammoth2-test.go.tmpl\", \"mammoth2_generated_test.go\")\n}\nEOF\n\n    ${gocmd} run -tags \"$btags\" gen-from-tmpl.generated.go || return 1\n    rm -f gen-from-tmpl.generated.go\n    \n    rm -f gen-from-tmpl.*generated.go\n    return 0\n}\n\n_codegenerators() {\n    local c5=\"_generated_test.go\"\n    local c7=\"$PWD/codecgen\"\n    local c8=\"$c7/__codecgen\"\n    local c9=\"codecgen-scratch.go\"\n\n    if ! [[ $zforce || $(_ng \"values_codecgen${c5}\") ]]; then return 0; fi\n    \n    # Note: ensure you run the codecgen for this codebase/directory i.e. ./codecgen/codecgen\n    true &&\n        echo \"codecgen ... \" &&\n        if [[ $zforce || ! -f \"$c8\" || \"$c7/gen.go\" -nt \"$c8\" ]]; then\n            echo \"rebuilding codecgen ... \" && ( cd codecgen && ${gocmd} build -o $c8 ${zargs[*]} . )\n        fi &&\n        $c8 -rt 'codecgen' -t 'codecgen generated' -o \"values_codecgen${c5}\" -d 19780 \"$zfin\" \"$zfin2\" &&\n        cp mammoth2_generated_test.go $c9 &&\n        $c8 -t 'codecgen,!codec.notfastpath,!codec.notmammoth generated,!codec.notfastpath,!codec.notmammoth' -o \"mammoth2_codecgen${c5}\" -d 19781 \"mammoth2_generated_test.go\" &&\n        rm -f $c9 &&\n        echo \"generators done!\" \n}\n\n_prebuild() {\n    echo \"prebuild: zforce: $zforce\"\n    local d=\"$PWD\"\n    local zfin=\"test_values.generated.go\"\n    local zfin2=\"test_values_flex.generated.go\"\n    local zpkg=\"github.com/ugorji/go/codec\"\n    local returncode=1\n\n    # zpkg=${d##*/src/}\n    # zgobase=${d%%/src/*}\n    # rm -f *_generated_test.go \n    rm -f codecgen-*.go &&\n        _build &&\n        cp $d/values_test.go $d/$zfin &&\n        cp $d/values_flex_test.go $d/$zfin2 &&\n        _codegenerators &&\n        if [[ \"$(type -t _codegenerators_external )\" = \"function\" ]]; then _codegenerators_external ; fi &&\n        if [[ $zforce ]]; then ${gocmd} install ${zargs[*]} .; fi &&\n        returncode=0 &&\n        echo \"prebuild done successfully\"\n    rm -f $d/$zfin $d/$zfin2\n    return $returncode\n    # unset zfin zfin2 zpkg\n}\n\n_make() {\n    local makeforce=${zforce}\n    zforce=1\n    (cd codecgen && ${gocmd} install ${zargs[*]} .) && _prebuild && ${gocmd} install ${zargs[*]} .\n    zforce=${makeforce}\n}\n\n_clean() {\n    rm -f \\\n       gen-from-tmpl.*generated.go \\\n       codecgen-*.go \\\n       test_values.generated.go test_values_flex.generated.go\n}\n\n_release() {\n    local reply\n    read -p \"Pre-release validation takes a few minutes and MUST be run from within GOPATH/src. Confirm y/n? \" -n 1 -r reply\n    echo\n    if [[ ! $reply =~ ^[Yy]$ ]]; then return 1; fi\n\n    # expects GOROOT, GOROOT_BOOTSTRAP to have been set.\n    if [[ -z \"${GOROOT// }\" || -z \"${GOROOT_BOOTSTRAP// }\" ]]; then return 1; fi\n    # (cd $GOROOT && git checkout -f master && git pull && git reset --hard)\n    (cd $GOROOT && git pull)\n    local f=`pwd`/make.release.out\n    cat > $f <<EOF\n========== `date` ===========\nEOF\n    # # go 1.6 and below kept giving memory errors on Mac OS X during SDK build or go run execution,\n    # # that is fine, as we only explicitly test the last 3 releases and tip (2 years).\n    local makeforce=${zforce}\n    zforce=1\n    for i in 1.10 1.11 1.12 master\n    do\n        echo \"*********** $i ***********\" >>$f\n        if [[ \"$i\" != \"master\" ]]; then i=\"release-branch.go$i\"; fi\n        (false ||\n             (echo \"===== BUILDING GO SDK for branch: $i ... =====\" &&\n                  cd $GOROOT &&\n                  git checkout -f $i && git reset --hard && git clean -f . &&\n                  cd src && ./make.bash >>$f 2>&1 && sleep 1 ) ) &&\n            echo \"===== GO SDK BUILD DONE =====\" &&\n            _prebuild &&\n            echo \"===== PREBUILD DONE with exit: $? =====\" &&\n            _tests \"$@\"\n        if [[ \"$?\" != 0 ]]; then return 1; fi\n    done\n    zforce=${makeforce}\n    echo \"++++++++ RELEASE TEST SUITES ALL PASSED ++++++++\"\n}\n\n_usage() {\n    # hidden args:\n    # -pf [p=prebuild (f=force)]\n    \n    cat <<EOF\nprimary usage: $0 \n    -[tesow m n l d]   -> [t=tests (e=extra, s=short, o=cover, w=wait), m=make, n=inlining diagnostics, l=mid-stack inlining, d=race detector]\n    -v                   -> v=verbose\nEOF\n    if [[ \"$(type -t _usage_run)\" = \"function\" ]]; then _usage_run ; fi\n}\n\n_main() {\n    if [[ -z \"$1\" ]]; then _usage; return 1; fi\n    local x # determines the main action to run in this build\n    local zforce # force\n    local zcover # generate cover profile and show in browser when done\n    local zwait # run tests in sequence, not parallel ie wait for one to finish before starting another\n    local zextra # means run extra (python based tests, etc) during testing\n    \n    local ztestargs=()\n    local zargs=()\n    local zverbose=()\n    local zbenchflags=\"\"\n\n    local gocmd=${MYGOCMD:-go}\n    \n    OPTIND=1\n    while getopts \":cetmnrgpfvldsowkxyzb:\" flag\n    do\n        case \"x$flag\" in\n            'xo') zcover=1 ;;\n            'xe') zextra=1 ;;\n            'xw') zwait=1 ;;\n            'xf') zforce=1 ;;\n            'xs') ztestargs+=(\"-short\") ;;\n            'xv') zverbose+=(1) ;;\n            'xl') zargs+=(\"-gcflags\"); zargs+=(\"-l=4\") ;;\n            'xn') zargs+=(\"-gcflags\"); zargs+=(\"-m=2\") ;;\n            'xd') zargs+=(\"-race\") ;;\n            'xb') x='b'; zbenchflags=${OPTARG} ;;\n            x\\?) _usage; return 1 ;;\n            *) x=$flag ;;\n        esac\n    done\n    shift $((OPTIND-1))\n    # echo \">>>> _main: extra args: $@\"\n    case \"x$x\" in\n        'xt') _tests \"$@\" ;;\n        'xm') _make \"$@\" ;;\n        'xr') _release \"$@\" ;;\n        'xg') _go ;;\n        'xp') _prebuild \"$@\" ;;\n        'xc') _clean \"$@\" ;;\n        'xx') _analyze_checks \"$@\" ;;\n        'xy') _analyze_debug_types \"$@\" ;;\n        'xz') _analyze_do_inlining_and_more \"$@\" ;;\n        'xk') _go_compiler_validation_suite ;;\n        'xb') _bench \"$@\" ;;\n    esac\n    # unset zforce zargs zbenchflags\n}\n\n[ \".\" = `dirname $0` ] && _main \"$@\"\n\n", "num_lines": 369}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ntop_dir='.'\nif [[ $# -gt 0 ]]; then\n    top_dir=\"${1}\"\nfi\n\np=$(pwd)\nmod_dirs=()\n\n# Note `mapfile` does not exist in older bash versions:\n# https://stackoverflow.com/questions/41475261/need-alternative-to-readarray-mapfile-for-script-on-older-version-of-bash\n\nwhile IFS= read -r line; do\n    mod_dirs+=(\"$line\")\ndone < <(find \"${top_dir}\" -type f -name 'go.mod' -exec dirname {} \\; | sort)\n\nfor mod_dir in \"${mod_dirs[@]}\"; do\n    cd \"${mod_dir}\"\n\n    while IFS= read -r line; do\n        echo \".${line#${p}}\"\n    done < <(go list --find -f '{{.Name}}|{{.Dir}}' ./... | grep '^main|' | cut -f 2- -d '|')\n    cd \"${p}\"\ndone\n", "num_lines": 42}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright The OpenTelemetry Authors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -euo pipefail\n\ncd $(dirname $0)\nTOOLS_DIR=$(pwd)/.tools\n\nif [ -z \"${GOPATH}\" ] ; then\n\tprintf \"GOPATH is not defined.\\n\"\n\texit -1\nfi\n\nif [ ! -d \"${GOPATH}\" ] ; then\n\tprintf \"GOPATH ${GOPATH} is invalid \\n\"\n\texit -1\nfi\n\n# Pre-requisites\nif ! git diff --quiet; then \\\n\tgit status\n\tprintf \"\\n\\nError: working tree is not clean\\n\"\n\texit -1\nfi\n\nif [ \"$(git tag --contains $(git log -1 --pretty=format:\"%H\"))\" = \"\" ] ; then\n\tprintf \"$(git log -1)\"\n\tprintf \"\\n\\nError: HEAD is not pointing to a tagged version\"\nfi\n\nmake ${TOOLS_DIR}/gojq\n\nDIR_TMP=\"${GOPATH}/src/oteltmp/\"\nrm -rf $DIR_TMP\nmkdir -p $DIR_TMP\n\nprintf \"Copy examples to ${DIR_TMP}\\n\"\ncp -a ./example ${DIR_TMP}\n\n# Update go.mod files\nprintf \"Update go.mod: rename module and remove replace\\n\"\n\nPACKAGE_DIRS=$(find . -mindepth 2 -type f -name 'go.mod' -exec dirname {} \\; | egrep 'example' | sed 's/^\\.\\///' | sort)\n\nfor dir in $PACKAGE_DIRS; do\n\tprintf \"  Update go.mod for $dir\\n\"\n\t(cd \"${DIR_TMP}/${dir}\" && \\\n\t # replaces is (\"mod1\" \"mod2\" \u00e2\u20ac\u00a6)\n\t replaces=($(go mod edit -json | ${TOOLS_DIR}/gojq '.Replace[].Old.Path')) && \\\n\t # strip double quotes\n\t replaces=(\"${replaces[@]%\\\"}\") && \\\n\t replaces=(\"${replaces[@]#\\\"}\") && \\\n\t # make an array (-dropreplace=mod1 -dropreplace=mod2 \u00e2\u20ac\u00a6)\n\t dropreplaces=(\"${replaces[@]/#/-dropreplace=}\") && \\\n\t go mod edit -module \"oteltmp/${dir}\" \"${dropreplaces[@]}\" && \\\n\t go mod tidy)\ndone\nprintf \"Update done:\\n\\n\"\n\n# Build directories that contain main package. These directories are different than\n# directories that contain go.mod files.\nprintf \"Build examples:\\n\"\nEXAMPLES=$(./get_main_pkgs.sh ./example)\nfor ex in $EXAMPLES; do\n\tprintf \"  Build $ex in ${DIR_TMP}/${ex}\\n\"\n\t(cd \"${DIR_TMP}/${ex}\" && \\\n\t go build .)\ndone\n\n# Cleanup\nprintf \"Remove copied files.\\n\"\nrm -rf $DIR_TMP\n", "num_lines": 86}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -euo pipefail\n\ncd \"$(git rev-parse --show-toplevel)\"\n\nSTD_PATH=src/crypto/ed25519/internal/edwards25519/field\nLOCAL_PATH=curve25519/internal/field\nLAST_SYNC_REF=$(cat $LOCAL_PATH/sync.checkpoint)\n\ngit fetch https://go.googlesource.com/go master\n\nif git diff --quiet $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH; then\n    echo \"No changes.\"\nelse\n    NEW_REF=$(git rev-parse FETCH_HEAD | tee $LOCAL_PATH/sync.checkpoint)\n    echo \"Applying changes from $LAST_SYNC_REF to $NEW_REF...\"\n    git diff $LAST_SYNC_REF:$STD_PATH FETCH_HEAD:$STD_PATH | \\\n        git apply -3 --directory=$LOCAL_PATH\nfi\n", "num_lines": 20}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,386\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_amd64)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,amd64\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\nplan9_arm)\n\tmkerrors=\n\tmksyscall=\"go run mksyscall.go -l32 -plan9 -tags plan9,arm\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 151}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; DO NOT EDIT.'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <netinet/udp.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 782}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=$(mktemp -d /tmp/sdk.XXX) \\\n&& curl -o $TMP.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\" \\\n&& unzip -q $TMP.zip -d $TMP \\\n&& export PATH=\"$PATH:$TMP/go_appengine\"", "num_lines": 6}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu -o pipefail\n\nWORKDIR=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$WORKDIR\"\n}\ntrap finish EXIT\n\nexport GOBIN=${WORKDIR}/bin\nexport PATH=${GOBIN}:${PATH}\nmkdir -p ${GOBIN}\n\necho \"remove existing generated files\"\n# grpc_testingv3/testv3.pb.go is not re-generated because it was\n# intentionally generated by an older version of protoc-gen-go.\nrm -f $(find . -name '*.pb.go' | grep -v 'grpc_testingv3/testv3.pb.go')\n\necho \"go install google.golang.org/protobuf/cmd/protoc-gen-go\"\n(cd test/tools && go install google.golang.org/protobuf/cmd/protoc-gen-go)\n\necho \"go install cmd/protoc-gen-go-grpc\"\n(cd cmd/protoc-gen-go-grpc && go install .)\n\necho \"git clone https://github.com/grpc/grpc-proto\"\ngit clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto\n\necho \"git clone https://github.com/protocolbuffers/protobuf\"\ngit clone --quiet https://github.com/protocolbuffers/protobuf ${WORKDIR}/protobuf\n\n# Pull in code.proto as a proto dependency\nmkdir -p ${WORKDIR}/googleapis/google/rpc\necho \"curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto\"\ncurl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto\n\nmkdir -p ${WORKDIR}/out\n\n# Generates sources without the embed requirement\nLEGACY_SOURCES=(\n  ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto\n  ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto\n  ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto\n  ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto\n  profiling/proto/service.proto\n  reflection/grpc_reflection_v1alpha/reflection.proto\n)\n\n# Generates only the new gRPC Service symbols\nSOURCES=(\n  $(git ls-files --exclude-standard --cached --others \"*.proto\" | grep -v '^\\(profiling/proto/service.proto\\|reflection/grpc_reflection_v1alpha/reflection.proto\\)$')\n  ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto\n  ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto\n  ${WORKDIR}/grpc-proto/grpc/testing/*.proto\n  ${WORKDIR}/grpc-proto/grpc/core/*.proto\n)\n\n# These options of the form 'Mfoo.proto=bar' instruct the codegen to use an\n# import path of 'bar' in the generated code when 'foo.proto' is imported in\n# one of the sources.\nOPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config,Mgrpc/core/stats.proto=google.golang.org/grpc/interop/grpc_testing/core\n\nfor src in ${SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    -I${WORKDIR}/istio \\\n    ${src}\ndone\n\nfor src in ${LEGACY_SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS},require_unimplemented_servers=false:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/protobuf/src \\\n    -I${WORKDIR}/istio \\\n    ${src}\ndone\n\n# The go_package option in grpc/lookup/v1/rls.proto doesn't match the\n# current location. Move it into the right place.\nmkdir -p ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\nmv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\n\n# grpc_testingv3/testv3.pb.go is not re-generated because it was\n# intentionally generated by an older version of protoc-gen-go.\nrm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testingv3/*.pb.go\n\n# grpc/service_config/service_config.proto does not have a go_package option.\nmv ${WORKDIR}/out/grpc/service_config/service_config.pb.go internal/proto/grpc_service_config\n\n# grpc/testing does not have a go_package option.\nmv ${WORKDIR}/out/grpc/testing/*.pb.go interop/grpc_testing/\nmv ${WORKDIR}/out/grpc/core/*.pb.go interop/grpc_testing/core/\n\ncp -R ${WORKDIR}/out/google.golang.org/grpc/* .\n", "num_lines": 120}
{"repo_name": "ARO-RP", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\n# not makes sure the command passed to it does not exit with a return code of 0.\nnot() {\n  # This is required instead of the earlier (! $COMMAND) because subshells and\n  # pipefail don't work the same on Darwin as in Linux.\n  ! \"$@\"\n}\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | not read\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${HOME}/go/bin:${GOROOT}/bin:${PATH}\"\ngo version\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Install the pinned versions as defined in module tools.\n  pushd ./test/tools\n  go install \\\n    golang.org/x/lint/golint \\\n    golang.org/x/tools/cmd/goimports \\\n    honnef.co/go/tools/cmd/staticcheck \\\n    github.com/client9/misspell/cmd/misspell\n  popd\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif [[ \"${GITHUB_ACTIONS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.14.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/runner/go\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif not which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\nnot git grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" -- '*.go'\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\nnot grep 'func Test[^(]' *_test.go\nnot grep 'func Test[^(]' test/*.go\n\n# - Do not import x/net/context.\nnot git grep -l 'x/net/context' -- \"*.go\"\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit grep -l '\"math/rand\"' -- \"*.go\" 2>&1 | not grep -v '^examples\\|^stress\\|grpcrand\\|^benchmark\\|wrr_test'\n\n# - Do not call grpclog directly. Use grpclog.Component instead.\ngit grep -l 'grpclog.I\\|grpclog.W\\|grpclog.E\\|grpclog.F\\|grpclog.V' -- \"*.go\" | not grep -v '^grpclog/component.go\\|^internal/grpctest/tlogger_test.go'\n\n# - Ensure all ptypes proto packages are renamed when importing.\nnot git grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\" -- \"*.go\"\n\n# - Ensure all xds proto imports are renamed to *pb or *grpc.\ngit grep '\"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*.pb.go' | not grep -v 'pb \"\\|grpc \"'\n\n# - Check imports that are illegal in appengine (until Go 1.11).\n# TODO: Remove when we drop Go 1.10 support\ngo list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go\n\nmisspell -error .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet,\n# go mod tidy.\n# Perform these checks on each module inside gRPC.\nfor MOD_FILE in $(find . -name 'go.mod'); do\n  MOD_DIR=$(dirname ${MOD_FILE})\n  pushd ${MOD_DIR}\n  go vet -all ./... | fail_on_output\n  gofmt -s -d -l . 2>&1 | fail_on_output\n  goimports -l . 2>&1 | not grep -vE \"\\.pb\\.go\"\n  golint ./... 2>&1 | not grep -vE \"/testv3\\.pb\\.go:\"\n\n  go mod tidy\n  git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\n  popd\ndone\n\n# - Collection of static analysis checks\n#\n# TODO(dfawley): don't use deprecated functions in examples or first-party\n# plugins.\nSC_OUT=\"$(mktemp)\"\nstaticcheck -go 1.9 -checks 'inherit,-ST1015' ./... > \"${SC_OUT}\" || true\n# Error if anything other than deprecation warnings are printed.\nnot grep -v \"is deprecated:.*SA1019\" \"${SC_OUT}\"\n# Only ignore the following deprecated types/fields/functions.\nnot grep -Fv '.CredsBundle\n.HeaderMap\n.Metadata is deprecated: use Attributes\n.NewAddress\n.NewServiceConfig\n.Type is deprecated: use Attributes\nBuildVersion is deprecated\nbalancer.ErrTransientFailure\nbalancer.Picker\nextDesc.Filename is deprecated\ngithub.com/golang/protobuf/jsonpb is deprecated\ngrpc.CallCustomCodec\ngrpc.Code\ngrpc.Compressor\ngrpc.CustomCodec\ngrpc.Decompressor\ngrpc.MaxMsgSize\ngrpc.MethodConfig\ngrpc.NewGZIPCompressor\ngrpc.NewGZIPDecompressor\ngrpc.RPCCompressor\ngrpc.RPCDecompressor\ngrpc.ServiceConfig\ngrpc.WithBalancerName\ngrpc.WithCompressor\ngrpc.WithDecompressor\ngrpc.WithDialer\ngrpc.WithMaxMsgSize\ngrpc.WithServiceConfig\ngrpc.WithTimeout\nhttp.CloseNotifier\ninfo.SecurityVersion\nproto is deprecated\nproto.InternalMessageInfo is deprecated\nproto.EnumName is deprecated\nproto.ErrInternalBadWireType is deprecated\nproto.FileDescriptor is deprecated\nproto.Marshaler is deprecated\nproto.MessageType is deprecated\nproto.RegisterEnum is deprecated\nproto.RegisterFile is deprecated\nproto.RegisterType is deprecated\nproto.RegisterExtension is deprecated\nproto.RegisteredExtension is deprecated\nproto.RegisteredExtensions is deprecated\nproto.RegisterMapType is deprecated\nproto.Unmarshaler is deprecated\nresolver.Backend\nresolver.GRPCLB\nTarget is deprecated: Use the Target field in the BuildOptions instead.\nxxx_messageInfo_\n' \"${SC_OUT}\"\n\n# - special golint on package comments.\nlint_package_comment_per_package() {\n  # Number of files in this go package.\n  fileCount=$(go list -f '{{len .GoFiles}}' $1)\n  if [ ${fileCount} -eq 0 ]; then\n    return 0\n  fi\n  # Number of package errors generated by golint.\n  lintPackageCommentErrorsCount=$(golint --min_confidence 0 $1 | grep -c \"should have a package comment\")\n  # golint complains about every file that's missing the package comment. If the\n  # number of files for this package is greater than the number of errors, there's\n  # at least one file with package comment, good. Otherwise, fail.\n  if [ ${fileCount} -le ${lintPackageCommentErrorsCount} ]; then\n    echo \"Package $1 (with ${fileCount} files) is missing package comment\"\n    return 1\n  fi\n}\nlint_package_comment() {\n  set +ex\n\n  count=0\n  for i in $(go list ./...); do\n    lint_package_comment_per_package \"$i\"\n    ((count += $?))\n  done\n\n  set -ex\n  return $count\n}\nlint_package_comment\n\necho SUCCESS\n", "num_lines": 216}
{"repo_name": "asa-in-spark", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ \"$1\" == \"debug\" ]; then\n  echo \"[INFO] Not generating ASA-x.x.x.jar as debug mode is enabled and user wants to troubleshoot the build process\"\n  exit 0\nfi\n\necho \"Cleaning existing build files...\"\nrm -rf cpp/build dotnet/bin dotnet/obj java/target || true\necho \"Older build deleted\"\n\necho \"Downloading maven dependencies...\"\ncd java \nmvn compile \ncd ..\n\necho \"Creating cpp build...\"\nmkdir -p cpp/build\ncd cpp/build\ncmake ..\ncmake --build .\ncd ../..\necho \"cpp build created successfully\"\n\n\necho \"\"\"\n====================================================================================================================================\nMake sure azure credentials were provided successfully while building the docker image. \nIf not then stop this build.sh script and run\n$ cd dotnet && dotnet restore --interactive\nOpen the URL on a browser and enter the code when prompted to authenticate\n\nAfter the authentication, rerun the build.sh\n\nFor more information: \nAzure Credential provider was installed while building the docker image to interactively acquire credentials for Azure Artifacts\nhttps://github.com/microsoft/artifacts-credprovider\n====================================================================================================================================\n\"\"\"\n\necho \"Creating dotnet build ...\"\n# This is where it hits case sensitive dir name errors. Wierd, but it works if triggerred second time\ncd dotnet && (dotnet build || dotnet build) && cd ..\n\necho \"Creating ASA-x.x.x.jar ...\"\ncd java \nmvn package\n# At this point jar should be created\nls -lh target/*.jar\necho \"Jar created successfully\"\ncd ..\n\necho \"Running sbt test...\"\n# Run test\ncd scala && sbt test \n", "num_lines": 55}
{"repo_name": "asa-in-spark", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# DESCRIPTION: A simple shell script designed to fetch the latest version\n# of the artifacts credential provider plugin for dotnet and\n# install it into $HOME/.nuget/plugins.\n# SEE: https://github.com/Microsoft/artifacts-credprovider/blob/master/README.md\n\nREPO=\"Microsoft/artifacts-credprovider\"\nFILE=\"Microsoft.NuGet.CredentialProvider.tar.gz\"\nVERSION=\"latest\"\n# URL pattern documented at https://help.github.com/en/articles/linking-to-releases as of 2019-03-29\nURI=\"https://github.com/$REPO/releases/$VERSION/download/$FILE\"\nNUGET_PLUGIN_DIR=\"$HOME/.nuget/plugins\"\n\n# Ensure plugin directory exists\nif [ ! -d \"${NUGET_PLUGIN_DIR}\" ]; then\n  echo \"INFO: Creating the nuget plugin directory (i.e. ${NUGET_PLUGIN_DIR}). \"\n  if ! mkdir -p \"${NUGET_PLUGIN_DIR}\"; then\n    echo \"ERROR: Unable to create nuget plugins directory (i.e. ${NUGET_PLUGIN_DIR}).\"\n    exit 1\n  fi\nfi\n\necho \"Downloading from $URI\"\n# Extract netcore from the .tar.gz into the plugin directory\n\n#Fetch the file\ncurl -H \"Accept: application/octet-stream\" \\\n     -s \\\n     -S \\\n     -L \\\n     \"$URI\" | tar xz -C \"$HOME/.nuget/\" \"plugins/netcore\"\n\necho \"INFO: credential provider netcore plugin extracted to $HOME/.nuget/\"\n", "num_lines": 34}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n# This script creates / updates repos. The $_repos param should be *all* repos needed in the system, not just new ones needs.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_subscription_id=\"$4\"\n_prefix=\"$5\"\n_applications=\"$6\"\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform destroy \\\n    -auto-approve \\\n    -var \"subscription_id=$_subscription_id\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nrm -rf .terraform\npopd || exit 2", "num_lines": 26}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n# This script creates / updates repos. The $_repos param should be *all* repos needed in the system, not just new ones needs.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_subscription_id=\"$4\"\n_prefix=\"$5\"\n_applications=\"$6\"\n_ini_file=${7:-}\n_timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform plan \\\n    -lock=true \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"subscription_id=$_subscription_id\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nterraform apply \"${_timestamp}.tfplan\"\n\nif [ -n \"${_ini_file:-}\" ];\nthen\n    _break_glass=\"$(terraform output break_glass_id)\"\n    _read_only=\"$(terraform output read_only_id)\"\n    _sre=\"$(terraform output sre_id)\"\n\n    ini_val \"$_ini_file\" c12:generated.break-glass_group_id \"$_break_glass\"\n    ini_val \"$_ini_file\" c12:generated.read-only_group_id \"$_read_only\"\n    ini_val \"$_ini_file\" c12:generated.sre_group_id \"$_sre\"\nfi\n\nrm \"${_timestamp}.tfplan\"\npopd || exit 2", "num_lines": 42}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n\n  function post_grant_request () {\n    _resource_id=$(az ad sp show --id \"$1\" --query \"objectId\" -o json | jq \".\" -r)\n    echo  \"{\\\"principalId\\\": \\\"$3\\\", \\\"resourceId\\\": \\\"$_resource_id\\\", \\\"appRoleId\\\": \\'$2\\\"}\"\n    az rest --method POST --uri https://graph.microsoft.com/beta/servicePrincipals/\"$3\"/appRoleAssignedTo \\\n            --header Content-Type=application/json \\\n            --body \"{\\\"principalId\\\": \\\"$3\\\", \\\"resourceId\\\": \\\"$_resource_id\\\", \\\"appRoleId\\\": \\\"$2\\\"}\"\n  }\n\nsleep 30\nif [ -n \"${GITHUB_ACTIONS+set}\" ]; then\n  # When on CI Pipeline Logged in Service Principal is currently unable to exec `az ad app permission admin-consent`\n  # This calls the the Azure REST API and grants the listed Roles.\n  echo \"[INFO] sleep 30secs... \"\n  sleep 30 \n  _principal_id=${SP_ID}\n  echo \"[INFO] grant AAD roles\"\n  post_grant_request \"00000002-0000-0000-c000-000000000000\" \"78c8a3c8-a07e-4b9e-af1b-b5ccab50a175\" \"$_principal_id\"\n  post_grant_request \"00000002-0000-0000-c000-000000000000\" \"1cda74f2-2616-4834-b122-5cb1b07f8a59\" \"$_principal_id\"\n  echo \"[INFO] grant Microsoft Graph roles\"\n  post_grant_request \"00000003-0000-0000-c000-000000000000\" \"06b708a9-e830-4db3-a914-8e69da51d44f\" \"$_principal_id\"\n  post_grant_request \"00000003-0000-0000-c000-000000000000\" \"19dbc75e-c2e2-444c-a770-ec69d8559fc7\" \"$_principal_id\"\nelse\n  # When on Bootstrap (User account) use simpler Grant permission admin-consent\n  az ad app permission admin-consent --id \"${SP_APP_ID}\"\nfi\n\n\n\n", "num_lines": 32}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n# This script creates / updates repos. The $_repos param should be *all* repos needed in the system, not just new ones needs.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_access_token=\"$4\"\n_org=\"$5\"\n_prefix=\"$6\"\n_applications=\"$7\"\n_timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform plan \\\n    -lock=true \\\n    -destroy \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"org=$_org\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nterraform apply \"${_timestamp}.tfplan\"\nrm \"${_timestamp}.tfplan\"\nrm -rf .terraform\npopd || exit 2\n\n", "num_lines": 37}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n# This script creates / updates repos. The $_repos param should be *all* repos needed in the system, not just new ones needs.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_access_token=\"$4\"\n_org=\"$5\"\n_prefix=\"$6\"\n_applications=\"$7\"\n_timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform plan \\\n    -lock=true \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"org=$_org\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nterraform apply \"${_timestamp}.tfplan\"\nrm \"${_timestamp}.tfplan\"\npopd || exit 2\n\n", "num_lines": 35}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n# This script creates / updates teams in github. The $_teams param should be *all* teams needed in the system, not just new ones needed.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_access_token=\"$4\"\n_subscription_id=\"$5\"\n_org=\"$6\"\n_prefix=\"$7\"\n_applications=\"$8\"\n_timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform plan \\\n    -destroy \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"org=$_org\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"subscription_id=$_subscription_id\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nterraform apply \"${_timestamp}.tfplan\"\nrm \"${_timestamp}.tfplan\"\nrm -rf .terraform\npopd || exit 2", "num_lines": 36}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euxo pipefail\n# This script creates / updates teams in github. The $_teams param should be *all* teams needed in the system, not just new ones needed.\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../../../runtime/bootstrap/lib/tools.sh\"\n\n_storage_account_name=\"$1\"\n_container_name=\"$2\"\n_container_rg=\"$3\"\n_access_token=\"$4\"\n_subscription_id=\"$5\"\n_org=\"$6\"\n_prefix=\"$7\"\n_applications=\"$8\"\n_timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n\n\npushd \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\" || exit 2\n\nterraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\nterraform plan \\\n    -lock=true \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"org=$_org\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"subscription_id=$_subscription_id\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\nterraform apply \"${_timestamp}.tfplan\"\nrm \"${_timestamp}.tfplan\"\npopd || exit 2", "num_lines": 35}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# shellcheck disable=SC2034\nread -r -d '' __usage <<-'EOF' || true # exits non-zero when EOF encountered\n  -f --file [arg]  Config Filename to use. Default=\"./c12.ini\"\n  -v               Enable verbose mode, print script as it is executed\n  -g --generate-config-example Generate a config file example\n  -d --debug       Enables debug mode\n  -h --help        This page\n  -n --no-color    Disable color output\n  -D --delete      Delete C12\nEOF\n\n# shellcheck disable=SC2034\nread -r -d '' __helptext <<-'EOF' || true # exits non-zero when EOF encountered\n This script bootstraps a C12 environment for evaluation and testing.\n Examine the README.md file to see the resources it creates.\n\n To get started run './bootstrap --generate-config-example' and update the values\n in c12.ini\nEOF\n## Boilerplate files\n# shellcheck source=src/runtime/bootstrap/lib/main.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/lib/main.sh\"\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/lib/ini_val.sh\"\n\n## Component Files\n# These contain the bash scripts to run the create / delete / update for each\n# bootstrap step\n# shellcheck source=src/runtime/bootstrap/steps/terraform_storage_account.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/terraform_storage_account.sh\"\n\n# shellcheck source=src/runtime/bootstrap/steps/terraform_network.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/terraform_network.sh\"\n\n# shellcheck source=src/runtime/bootstrap/steps/terraform_aks.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/terraform_aks.sh\"\n\n# shellcheck source=src/runtime/bootstrap/steps/terraform_aad_credentials_pipeline.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/terraform_aad_credentials_pipeline.sh\"\n\n# shellcheck source=src/runtime/bootstrap/steps/provision_ci_docker_images.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/provision_ci_docker_images.sh\"\n\n# shellcheck source=src/runtime/bootstrap/steps/populate-repos.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/steps/populate-repos.sh\"\n\n### Validation. Error out if the things required for your script are not present\n##############################################################################\n\n[[ \"${arg_f:-}\" ]]     || help      \"Setting a filename with -f or --file is required\"\n[[ \"${LOG_LEVEL:-}\" ]] || emergency \"Cannot continue without LOG_LEVEL. \"\n\nconfig_file=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/$arg_f\"\ndebug \"expanding config file to $config_file\"\n\n# debug mode\nif [[ \"${arg_d:?}\" = \"1\" ]]; then\n  set -o xtrace\n  PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'\n  LOG_LEVEL=\"7\"\n  # Enable error backtracing\n  trap '__b3bp_err_report \"${FUNCNAME:-.}\" ${LINENO}' ERR\nfi\n\n# verbose mode\nif [[ \"${arg_v:?}\" = \"1\" ]]; then\n  set -o verbose\nfi\n\n# no color mode\nif [[ \"${arg_n:?}\" = \"1\" ]]; then\n  NO_COLOR=\"true\"\nfi\n\n# help mode\nif [[ \"${arg_h:?}\" = \"1\" ]]; then\n  # Help exists with code 1\n  help \"Help using ${0}\"\nfi\n\n### Runtime\n##############################################################################\n\n\nset -e\n\n\nfunction destroy() {\n    aad_credentials_for_pipelines_destroy\n    destroy_aks\n    destroy_network\n    github_teams_delete\n    aad_groups_delete\n    github_repos_delete\n    destroy_storage_account\n    rm -rf ../cluster-on-boarding/terraform/.terraform\n}\n\n\nfunction generate_config() {\n  # Azure info\n  ini_val \"$config_file\" azure.subscription \"<subscription id>\" \"ID of the subscription used for the C12 components\"\n  ini_val \"$config_file\" azure.location \"<location id>\" \"ID of the location used for the C12 components\"\n  ini_val \"$config_file\" azure.arc-support \"false\" \"[PREVIEW] See README for more info.\"\n  # C12 info\n  ini_val \"$config_file\" c12.prefix \"<prefix>\" \"Prefix to use for names within the C12 deployments\"\n  ini_val \"$config_file\" c12:bootstrap.phase \"bootstrap-config-generated\" \"Phase of C12 bootstrap - do not manually edit\"\n\n  # Github info\n  ini_val \"$config_file\" github.org \"<github org>\" \"GitHub org to use for C12 repos and co-ordination\"\n  ini_val \"$config_file\" github.access-token \"<access token>\" \"GitHub Personal Access Token Used to manage the GitHub Organisation \"\n  ini_val \"$config_file\" github.access-token-username \"<github username>\" \"GitHub username that was used to generate the access-token\"\n}\n\n\nfunction aad_groups_create(){\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    # shellcheck disable=SC2154\n    \"$__dir\"/../../components/identity-providers/aad/upsert-groups.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_subscription_id\" \\\n        \"$_prefix\" \\\n        null \\\n        \"$config_file\"\n}\n\nfunction aad_groups_delete(){\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    \"$__dir\"/../../components/identity-providers/aad/delete-groups.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_subscription_id\" \\\n        \"$_prefix\" \\\n        \"[\\\"sample-app-nodejs\\\"]\"\n}\n\n# shellcheck disable=SC2086\nfunction github_repos_create() {\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _org=$(ini_val \"$config_file\" github.org)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    \"$__dir\"/../../components/infrastructure/repos/github-enterprise-cloud/upsert-repos.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_access_token\" \\\n        \"$_org\" \\\n        \"$_prefix\" \\\n        null\n}\n\n# shellcheck disable=SC2086\nfunction github_repos_delete() {\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _org=$(ini_val \"$config_file\" github.org)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    \"$__dir\"/../../components/infrastructure/repos/github-enterprise-cloud/delete-repos.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_access_token\" \\\n        \"$_org\" \\\n        \"$_prefix\" \\\n        \"[\\\"sample-app-nodejs\\\"]\"\n}\n# shellcheck disable=SC2086\nfunction github_teams_create() {\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _org=$(ini_val \"$config_file\" github.org)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    \"$__dir\"/../../components/infrastructure/teams/github-enterprise-cloud/upsert-teams.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_access_token\" \\\n        \"$_subscription_id\" \\\n        \"$_org\" \\\n        \"$_prefix\" \\\n        null\n}\n\nfunction github_teams_delete() {\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _org=$(ini_val \"$config_file\" github.org)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    \"$__dir\"/../../components/infrastructure/teams/github-enterprise-cloud/delete-teams.sh \\\n        \"$_storage_account_name\" \\\n        \"$_container_name\" \\\n        \"$_container_rg\" \\\n        \"$_access_token\" \\\n        \"$_subscription_id\" \\\n        \"$_org\" \\\n        \"$_prefix\" \\\n        \"[\\\"sample-app-nodejs\\\"]\"\n}\n\nfunction hydrate_repos() {\n     populate-repos \"$config_file\"\n}\n\nfunction adopt_cluster() {\n    \"$__dir\"/../cluster-on-boarding/scripts/on_board_cluster.sh -f \"$config_file\"\n}\n\nfunction test_config() {\n    warning \"test_config not implemented yet. Only turning Github org string to lowercase if needed for now.\"\n    info \"./validate-config.sh\"\n\n    current_org=$(ini_val \"$config_file\" github.org)\n    # shellcheck disable=SC2020\n    lowercase_org=\"$(echo \"$current_org\" | tr '[:upper:]' '[:lower:]')\"\n\n    if [[ $current_org != \"$lowercase_org\" ]]; then\n        # Turning Github org string to lowercase and writing it back to .ini file to avoid error creating repos\n        ini_val \"$config_file\" github.org \"$lowercase_org\"\n        warning \"Github org value in .ini file was turned to lowercase (to create valid repo names).\"\n\n    fi\n}\n\nif [[ \"${arg_g:?}\" = \"1\" ]]; then\n  # Help exists with code 1\n  info \"Generating sample config file in $config_file\"\n  generate_config\n  exit 0\nfi\n\nif [[ \"${arg_D:?}\" = \"1\" ]]; then\n  # Help exists with code 1\n  warning \"Destroying C12 infrastructure\"\n  destroy\n  exit 0\nfi\n\n# shellcheck disable=SC2086\nif [[ \"$(ini_val $config_file azure.arc-support)\" == \"true\" ]]; then\n  # Check if location is support for Azure Arc\n  _location=$(ini_val \"$config_file\" azure.location)\n  _supported_locations=\"eastus westeurope\"\n  _supported=\"false\"\n  for supported in $_supported_locations\n  do\n    if [ \"$_location\" == \"$supported\" ]; then\n      info \"Azure location ${_location} is supported for Azure Arc\"\n      _supported=\"true\"\n      break   # break the for looop\n    fi\n  done\n  if [ \"$_supported\" == \"false\" ]; then\n    warning \"Azure location ${_location} currently not supported for Azure Arc\"\n    exit 0\n  fi\nfi\n\n# shellcheck disable=SC2086\nwhile [ \"$(ini_val $config_file c12:bootstrap.phase)\" != \"done\" ]\ndo\n    # shellcheck disable=SC2086\n    case \"$(ini_val $config_file c12:bootstrap.phase)\" in\n        \"bootstrap-config-generated\")\n            test_config\n            ini_val \"$config_file\" c12:bootstrap.phase \"bootstrap-config-tested\"\n            ;;\n        \"bootstrap-config-tested\")\n            terraform_storage_account\n            ini_val \"$config_file\" c12:bootstrap.phase \"storage-account-created\"\n            ;;\n        \"storage-account-created\")\n            aad_groups_create\n            ini_val \"$config_file\" c12:bootstrap.phase \"aad-groups-created\"\n            ;;\n        \"aad-groups-created\")\n            terraform_network\n            ini_val \"$config_file\" c12:bootstrap.phase \"network-created\"\n            ;;\n        \"network-created\")\n            terraform_aks\n            ini_val \"$config_file\" c12:bootstrap.phase \"aks-created\"\n            ;;\n        \"aks-created\")\n            github_repos_create\n            ini_val \"$config_file\" c12:bootstrap.phase \"github-created\"\n            ;;\n        \"github-created\")\n            provision_ci_docker_image\n            ini_val \"$config_file\" c12:bootstrap.phase \"ci-images-provisioned\"\n            ;;\n        \"ci-images-provisioned\")\n            github_teams_create\n            ini_val \"$config_file\" c12:bootstrap.phase \"github-teams-created\"\n            ;;\n        \"github-teams-created\")\n            aad_credentials_for_pipelines_create\n            ini_val \"$config_file\" c12:bootstrap.phase \"aad-credentials-for-pipelines-created\"\n            ;;\n        \"aad-credentials-for-pipelines-created\")\n            adopt_cluster\n            ini_val \"$config_file\" c12:bootstrap.phase \"cluster-adopted\"\n            ;;\n        \"cluster-adopted\")\n            hydrate_repos\n            ini_val \"$config_file\" c12:bootstrap.phase \"github-repos-hydrated\"\n            ;;\n        \"github-repos-hydrated\")\n            ini_val \"$config_file\" c12:bootstrap.phase \"done\"\n            ;;\n        *)\n            error \"Unknown C12 state - exiting - have you ran './bootstrap.sh --generate-config-example'?\"\n            exit 3\n    esac\ndone\n", "num_lines": 341}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# BASH3 Boilerplate: ini_val\n#\n# This file:\n#\n#  - Can read and write .ini files using pure bash\n#\n# Limitations:\n#\n#  - All keys inside a section of the .ini file must be unique\n#  - Optional comment parameter for the creation of new entries\n#\n# Usage as a function:\n#\n#  source ini_val.sh\n#  ini_val data.ini connection.host 127.0.0.1 \"Host name or IP address\"\n#\n# Usage as a command:\n#\n#  ini_val.sh data.ini connection.host 127.0.0.1 \"Host name or IP address\"\n#\n# Based on a template by BASH3 Boilerplate v2.4.1\n# http://bash3boilerplate.sh/#authors\n#\n# The MIT License (MIT)\n# Copyright (c) 2013 Kevin van Zonneveld and contributors\n# You are not obligated to bundle the LICENSE file with your b3bp projects as long\n# as you leave these references intact in the header comments of your source files.\n\nfunction ini_val() {\n  local file=\"${1:-}\"\n  local sectionkey=\"${2:-}\"\n  local val=\"${3:-}\"\n  local comment=\"${4:-}\"\n  local delim=\"=\"\n  local comment_delim=\";\"\n  local section=\"\"\n  local key=\"\"\n  local current=\"\"\n  # add default section\n  local section_default=\"default\"\n\n  if [[ ! -f \"${file}\" ]]; then\n    # touch file if not exists\n    touch \"${file}\"\n  fi\n\n  # Split on . for section. However, section is optional\n  IFS='.' read -r section key <<< \"${sectionkey}\"\n  if [[ ! \"${key}\" ]]; then\n    key=\"${section}\"\n    # default section if not given\n    section=\"${section_default}\"\n  fi\n\n  current=$(sed -En \"/^\\[/{h;d;};G;s/^${key}([[:blank:]]*)${delim}(.*)\\n\\[${section}\\]$/\\2/p\" \"${file}\"|awk '{$1=$1};1')\n\n  if ! grep -q \"\\[${section}\\]\" \"${file}\"; then\n    # create section if not exists (empty line to seperate new section)\n    echo  >> \"${file}\"\n    echo \"[${section}]\" >> \"${file}\"\n  fi\n\n  if [[ ! \"${val}\" ]]; then\n    # get a value\n    echo \"${current}\"\n  else\n    # set a value\n    if [[ ! \"${current}\" ]]; then\n      # doesn't exist yet, add\n      if [[ ! \"${section}\" ]]; then\n        # if no section is given, propagate the default section\n        section=${section_default}\n      fi\n      # add to section\n      if [[ ! \"${comment}\" ]]; then\n        # add new key/value without comment\n        RET=\"/\\\\[${section}\\\\]/a\\\\\n${key}${delim}${val}\"\n      else\n        # add new key/value with preceeding comment\n        RET=\"/\\\\[${section}\\\\]/a\\\\\n${comment_delim}[${key}] ${comment}\\\\\n${key}${delim}${val}\"\n      fi\n      sed -i.bak -e \"${RET}\" \"${file}\"\n      # this .bak dance is done for BSD/GNU portability: http://stackoverflow.com/a/22084103/151666\n      rm -f \"${file}.bak\"\n    else\n      # replace existing (modified to replace only keys in given section)\n      sed -i.bak -e \"/^\\[${section}\\]/,/^\\[.*\\]/ s|^\\(${key}[ \\t]*${delim}[ \\t]*\\).*$|\\1${val}|\" \"${file}\"\n      # this .bak dance is done for BSD/GNU portability: http://stackoverflow.com/a/22084103/151666\n      rm -f \"${file}.bak\"\n    fi\n  fi\n}\n\nif [[ \"${BASH_SOURCE[0]}\" != \"${0}\" ]]; then\n  export -f ini_val\nelse\n  ini_val \"${@}\"\n  exit ${?}\nfi", "num_lines": 103}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n\nfunction __b3bp_log () {\n  local log_level=\"${1}\"\n  shift\n\n  # shellcheck disable=SC2034\n  local color_debug=\"\\\\x1b[35m\"\n  # shellcheck disable=SC2034\n  local color_info=\"\\\\x1b[32m\"\n  # shellcheck disable=SC2034\n  local color_notice=\"\\\\x1b[34m\"\n  # shellcheck disable=SC2034\n  local color_warning=\"\\\\x1b[33m\"\n  # shellcheck disable=SC2034\n  local color_error=\"\\\\x1b[31m\"\n  # shellcheck disable=SC2034\n  local color_critical=\"\\\\x1b[1;31m\"\n  # shellcheck disable=SC2034\n  local color_alert=\"\\\\x1b[1;37;41m\"\n  # shellcheck disable=SC2034\n  local color_emergency=\"\\\\x1b[1;4;5;37;41m\"\n\n  local colorvar=\"color_${log_level}\"\n\n  local color=\"${!colorvar:-${color_error}}\"\n  local color_reset=\"\\\\x1b[0m\"\n\n  if [[ \"${NO_COLOR:-}\" = \"true\" ]] || { [[ \"${TERM:-}\" != \"xterm\"* ]] && [[ \"${TERM:-}\" != \"screen\"* ]]; } || [[ ! -t 2 ]]; then\n    if [[ \"${NO_COLOR:-}\" != \"false\" ]]; then\n      # Don't use colors on pipes or non-recognized terminals\n      color=\"\"; color_reset=\"\"\n    fi\n  fi\n\n  # all remaining arguments are to be printed\n  local log_line=\"\"\n\n  while IFS=$'\\n' read -r log_line; do\n    echo -e \"$(date -u +\"%Y-%m-%d %H:%M:%S UTC\") ${color}$(printf \"[%9s]\" \"${log_level}\")${color_reset} ${log_line}\" 1>&2\n  done <<< \"${@:-}\"\n}\n\nfunction emergency () {                                __b3bp_log emergency \"${@}\"; exit 1; }\nfunction alert ()     { [[ \"${LOG_LEVEL:-0}\" -ge 1 ]] && __b3bp_log alert \"${@}\"; true; }\nfunction critical ()  { [[ \"${LOG_LEVEL:-0}\" -ge 2 ]] && __b3bp_log critical \"${@}\"; true; }\nfunction error ()     { [[ \"${LOG_LEVEL:-0}\" -ge 3 ]] && __b3bp_log error \"${@}\"; true; }\nfunction warning ()   { [[ \"${LOG_LEVEL:-0}\" -ge 4 ]] && __b3bp_log warning \"${@}\"; true; }\nfunction notice ()    { [[ \"${LOG_LEVEL:-0}\" -ge 5 ]] && __b3bp_log notice \"${@}\"; true; }\nfunction info ()      { [[ \"${LOG_LEVEL:-0}\" -ge 6 ]] && __b3bp_log info \"${@}\"; true; }\nfunction debug ()     { [[ \"${LOG_LEVEL:-0}\" -ge 7 ]] && __b3bp_log debug \"${@}\"; true; }", "num_lines": 53}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# This file:\n#\n#  - Demos BASH3 Boilerplate (change this for your script)\n#\n# Usage:\n#\n#  LOG_LEVEL=7 ./main.sh -f /tmp/x -d (change this for your script)\n#\n# Based on a template by BASH3 Boilerplate v2.4.1\n# http://bash3boilerplate.sh/#authors\n#\n# The MIT License (MIT)\n# Copyright (c) 2013 Kevin van Zonneveld and contributors\n# You are not obligated to bundle the LICENSE file with your b3bp projects as long\n# as you leave these references intact in the header comments of your source files.\n\n# Exit on error. Append \"|| true\" if you expect an error.\nset -o errexit\n# Exit on error inside any functions or subshells.\nset -o errtrace\n# Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR\nset -o nounset\n# Catch the error in case mysqldump fails (but gzip succeeds) in `mysqldump |gzip`\nset -o pipefail\n# Turn on traces, useful while debugging but commented out by default\n# set -o xtrace\n\n# shellcheck source=src/runtime/bootstrap/lib/main.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/logging.sh\"\n\n\nif [[ \"${BASH_SOURCE[0]}\" != \"${0}\" ]]; then\n  __i_am_main_script=\"0\" # false\n\n  if [[ \"${__usage+x}\" ]]; then\n    if [[ \"${BASH_SOURCE[1]}\" = \"${0}\" ]]; then\n      __i_am_main_script=\"1\" # true\n    fi\n\n    __b3bp_external_usage=\"true\"\n    __b3bp_tmp_source_idx=1\n  fi\nelse\n  __i_am_main_script=\"1\" # true\n  [[ \"${__usage+x}\" ]] && unset -v __usage\n  [[ \"${__helptext+x}\" ]] && unset -v __helptext\nfi\n\n# Set magic variables for current file, directory, os, etc.\n__dir=\"$(cd \"$(dirname \"${BASH_SOURCE[${__b3bp_tmp_source_idx:-0}]}\")\" && pwd)\"\n__file=\"${__dir}/$(basename \"${BASH_SOURCE[${__b3bp_tmp_source_idx:-0}]}\")\"\n__base=\"$(basename \"${__file}\" .sh)\"\n# shellcheck disable=SC2034,SC2015\n__invocation=\"$(printf %q \"${__file}\")$( (($#)) && printf ' %q' \"$@\" || true)\"\n\n# Define the environment variables (and their defaults) that this script depends on\nLOG_LEVEL=\"${LOG_LEVEL:-6}\" # 7 = debug -> 0 = emergency\nNO_COLOR=\"${NO_COLOR:-}\"    # true = disable color. otherwise autodetected\n\n\n### Functions\n##############################################################################\n\n\nfunction help () {\n  echo \"\" 1>&2\n  echo \" ${*}\" 1>&2\n  echo \"\" 1>&2\n  echo \"  ${__usage:-No usage available}\" 1>&2\n  echo \"\" 1>&2\n\n  if [[ \"${__helptext:-}\" ]]; then\n    echo \" ${__helptext}\" 1>&2\n    echo \"\" 1>&2\n  fi\n\n  exit 1\n}\n\n\n### Parse commandline options\n##############################################################################\n\n\n# Translate usage string -> getopts arguments, and set $arg_<flag> defaults\nwhile read -r __b3bp_tmp_line; do\n  if [[ \"${__b3bp_tmp_line}\" =~ ^- ]]; then\n    # fetch single character version of option string\n    __b3bp_tmp_opt=\"${__b3bp_tmp_line%% *}\"\n\n    __b3bp_tmp_opt=\"${__b3bp_tmp_opt:1}\"\n\n    # fetch long version if present\n    __b3bp_tmp_long_opt=\"\"\n\n    if [[ \"${__b3bp_tmp_line}\" = *\"--\"* ]]; then\n      __b3bp_tmp_long_opt=\"${__b3bp_tmp_line#*--}\"\n      __b3bp_tmp_long_opt=\"${__b3bp_tmp_long_opt%% *}\"\n    fi\n\n    # map opt long name to+from opt short name\n    printf -v \"__b3bp_tmp_opt_long2short_${__b3bp_tmp_long_opt//-/_}\" '%s' \"${__b3bp_tmp_opt}\"\n    printf -v \"__b3bp_tmp_opt_short2long_${__b3bp_tmp_opt}\" '%s' \"${__b3bp_tmp_long_opt//-/_}\"\n\n    # check if option takes an argument\n    if [[ \"${__b3bp_tmp_line}\" =~ \\[.*\\] ]]; then\n      __b3bp_tmp_opt=\"${__b3bp_tmp_opt}:\" # add : if opt has arg\n      __b3bp_tmp_init=\"\"  # it has an arg. init with \"\"\n      printf -v \"__b3bp_tmp_has_arg_${__b3bp_tmp_opt:0:1}\" '%s' \"1\"\n    elif [[ \"${__b3bp_tmp_line}\" =~ \\{.*\\} ]]; then\n      __b3bp_tmp_opt=\"${__b3bp_tmp_opt}:\" # add : if opt has arg\n      __b3bp_tmp_init=\"\"  # it has an arg. init with \"\"\n      # remember that this option requires an argument\n      printf -v \"__b3bp_tmp_has_arg_${__b3bp_tmp_opt:0:1}\" '%s' \"2\"\n    else\n      __b3bp_tmp_init=\"0\" # it's a flag. init with 0\n      printf -v \"__b3bp_tmp_has_arg_${__b3bp_tmp_opt:0:1}\" '%s' \"0\"\n    fi\n    __b3bp_tmp_opts=\"${__b3bp_tmp_opts:-}${__b3bp_tmp_opt}\"\n\n    if [[ \"${__b3bp_tmp_line}\" =~ ^Can\\ be\\ repeated\\. ]] || [[ \"${__b3bp_tmp_line}\" =~ \\.\\ *Can\\ be\\ repeated\\. ]]; then\n      # remember that this option can be repeated\n      printf -v \"__b3bp_tmp_is_array_${__b3bp_tmp_opt:0:1}\" '%s' \"1\"\n    else\n      printf -v \"__b3bp_tmp_is_array_${__b3bp_tmp_opt:0:1}\" '%s' \"0\"\n    fi\n  fi\n\n  [[ \"${__b3bp_tmp_opt:-}\" ]] || continue\n\n  if [[ \"${__b3bp_tmp_line}\" =~ ^Default= ]] || [[ \"${__b3bp_tmp_line}\" =~ \\.\\ *Default= ]]; then\n    # ignore default value if option does not have an argument\n    __b3bp_tmp_varname=\"__b3bp_tmp_has_arg_${__b3bp_tmp_opt:0:1}\"\n    if [[ \"${!__b3bp_tmp_varname}\" != \"0\" ]]; then\n      # take default\n      __b3bp_tmp_init=\"${__b3bp_tmp_line##*Default=}\"\n      # strip double quotes from default argument\n      __b3bp_tmp_re='^\"(.*)\"$'\n      if [[ \"${__b3bp_tmp_init}\" =~ ${__b3bp_tmp_re} ]]; then\n        __b3bp_tmp_init=\"${BASH_REMATCH[1]}\"\n      else\n        # strip single quotes from default argument\n        __b3bp_tmp_re=\"^'(.*)'$\"\n        if [[ \"${__b3bp_tmp_init}\" =~ ${__b3bp_tmp_re} ]]; then\n          __b3bp_tmp_init=\"${BASH_REMATCH[1]}\"\n        fi\n      fi\n    fi\n  fi\n\n  if [[ \"${__b3bp_tmp_line}\" =~ ^Required\\. ]] || [[ \"${__b3bp_tmp_line}\" =~ \\.\\ *Required\\. ]]; then\n    # remember that this option requires an argument\n    printf -v \"__b3bp_tmp_has_arg_${__b3bp_tmp_opt:0:1}\" '%s' \"2\"\n  fi\n\n  # Init var with value unless it is an array / a repeatable\n  __b3bp_tmp_varname=\"__b3bp_tmp_is_array_${__b3bp_tmp_opt:0:1}\"\n  [[ \"${!__b3bp_tmp_varname}\" = \"0\" ]] && printf -v \"arg_${__b3bp_tmp_opt:0:1}\" '%s' \"${__b3bp_tmp_init}\"\ndone <<< \"${__usage:-}\"\n\n# run getopts only if options were specified in __usage\nif [[ \"${__b3bp_tmp_opts:-}\" ]]; then\n  # Allow long options like --this\n  __b3bp_tmp_opts=\"${__b3bp_tmp_opts}-:\"\n\n  # Reset in case getopts has been used previously in the shell.\n  OPTIND=1\n\n  # start parsing command line\n  set +o nounset # unexpected arguments will cause unbound variables\n                 # to be dereferenced\n  # Overwrite $arg_<flag> defaults with the actual CLI options\n  while getopts \"${__b3bp_tmp_opts}\" __b3bp_tmp_opt; do\n    [[ \"${__b3bp_tmp_opt}\" = \"?\" ]] && help \"Invalid use of script: ${*} \"\n\n    if [[ \"${__b3bp_tmp_opt}\" = \"-\" ]]; then\n      # OPTARG is long-option-name or long-option=value\n      if [[ \"${OPTARG}\" =~ .*=.* ]]; then\n        # --key=value format\n        __b3bp_tmp_long_opt=${OPTARG/=*/}\n        # Set opt to the short option corresponding to the long option\n        __b3bp_tmp_varname=\"__b3bp_tmp_opt_long2short_${__b3bp_tmp_long_opt//-/_}\"\n        printf -v \"__b3bp_tmp_opt\" '%s' \"${!__b3bp_tmp_varname}\"\n        OPTARG=${OPTARG#*=}\n      else\n        # --key value format\n        # Map long name to short version of option\n        __b3bp_tmp_varname=\"__b3bp_tmp_opt_long2short_${OPTARG//-/_}\"\n        printf -v \"__b3bp_tmp_opt\" '%s' \"${!__b3bp_tmp_varname}\"\n        # Only assign OPTARG if option takes an argument\n        __b3bp_tmp_varname=\"__b3bp_tmp_has_arg_${__b3bp_tmp_opt}\"\n        __b3bp_tmp_varvalue=\"${!__b3bp_tmp_varname}\"\n        [[ \"${__b3bp_tmp_varvalue}\" != \"0\" ]] && __b3bp_tmp_varvalue=\"1\"\n        printf -v \"OPTARG\" '%s' \"${@:OPTIND:${__b3bp_tmp_varvalue}}\"\n        # shift over the argument if argument is expected\n        ((OPTIND+=__b3bp_tmp_varvalue))\n      fi\n      # we have set opt/OPTARG to the short value and the argument as OPTARG if it exists\n    fi\n\n    __b3bp_tmp_value=\"${OPTARG}\"\n\n    __b3bp_tmp_varname=\"__b3bp_tmp_is_array_${__b3bp_tmp_opt:0:1}\"\n    if [[ \"${!__b3bp_tmp_varname}\" != \"0\" ]]; then\n      # repeatables\n      # shellcheck disable=SC2016\n      if [[ -z \"${OPTARG}\" ]]; then\n        # repeatable flags, they increcemnt\n        __b3bp_tmp_varname=\"arg_${__b3bp_tmp_opt:0:1}\"\n        debug \"cli arg ${__b3bp_tmp_varname} = (${__b3bp_tmp_default}) -> ${!__b3bp_tmp_varname}\"\n        # shellcheck disable=SC2004\n        __b3bp_tmp_value=$((${!__b3bp_tmp_varname} + 1))\n        printf -v \"${__b3bp_tmp_varname}\" '%s' \"${__b3bp_tmp_value}\"\n      else\n        # repeatable args, they get appended to an array\n        __b3bp_tmp_varname=\"arg_${__b3bp_tmp_opt:0:1}[@]\"\n        debug \"cli arg ${__b3bp_tmp_varname} append ${__b3bp_tmp_value}\"\n        declare -a \"${__b3bp_tmp_varname}\"='(\"${!__b3bp_tmp_varname}\" \"${__b3bp_tmp_value}\")'\n      fi\n    else\n      # non-repeatables\n      __b3bp_tmp_varname=\"arg_${__b3bp_tmp_opt:0:1}\"\n      __b3bp_tmp_default=\"${!__b3bp_tmp_varname}\"\n\n      if [[ -z \"${OPTARG}\" ]]; then\n        __b3bp_tmp_value=$((__b3bp_tmp_default + 1))\n      fi\n\n      printf -v \"${__b3bp_tmp_varname}\" '%s' \"${__b3bp_tmp_value}\"\n\n      debug \"cli arg ${__b3bp_tmp_varname} = (${__b3bp_tmp_default}) -> ${!__b3bp_tmp_varname}\"\n    fi\n  done\n  set -o nounset # no more unbound variable references expected\n\n  shift $((OPTIND-1))\n\n  if [[ \"${1:-}\" = \"--\" ]] ; then\n    shift\n  fi\nfi\n\n\n### Automatic validation of required option arguments\n##############################################################################\n\nfor __b3bp_tmp_varname in ${!__b3bp_tmp_has_arg_*}; do\n  # validate only options which required an argument\n  [[ \"${!__b3bp_tmp_varname}\" = \"2\" ]] || continue\n\n  __b3bp_tmp_opt_short=\"${__b3bp_tmp_varname##*_}\"\n  __b3bp_tmp_varname=\"arg_${__b3bp_tmp_opt_short}\"\n  [[ \"${!__b3bp_tmp_varname}\" ]] && continue\n\n  __b3bp_tmp_varname=\"__b3bp_tmp_opt_short2long_${__b3bp_tmp_opt_short}\"\n  printf -v \"__b3bp_tmp_opt_long\" '%s' \"${!__b3bp_tmp_varname}\"\n  [[ \"${__b3bp_tmp_opt_long:-}\" ]] && __b3bp_tmp_opt_long=\" (--${__b3bp_tmp_opt_long//_/-})\"\n\n  help \"Option -${__b3bp_tmp_opt_short}${__b3bp_tmp_opt_long:-} requires an argument\"\ndone\n\n\n### Cleanup Environment variables\n##############################################################################\n\nfor __tmp_varname in ${!__b3bp_tmp_*}; do\n  unset -v \"${__tmp_varname}\"\ndone\n\nunset -v __tmp_varname\n\n\n### Externally supplied __usage. Nothing else to do here\n##############################################################################\n\nif [[ \"${__b3bp_external_usage:-}\" = \"true\" ]]; then\n  unset -v __b3bp_external_usage\n  return\nfi\n\n\n### Signal trapping and backtracing\n##############################################################################\n\nfunction __b3bp_cleanup_before_exit () {\n  info \"Cleaning up. Done\"\n}\ntrap __b3bp_cleanup_before_exit EXIT\n\n# requires `set -o errtrace`\n__b3bp_err_report() {\n    local error_code=${?}\n    error \"Error in ${__file} in function ${1} on line ${2}\"\n    exit ${error_code}\n}\n# Uncomment the following line for always providing an error backtrace\ntrap '__b3bperr_report \"${FUNCNAME:-.}\" ${LINENO}' ERR\n\n\n### Command-line argument switches (like -d for debugmode, -h for showing helppage)\n##############################################################################\n\n# debug mode\nif [[ \"${arg_d:?}\" = \"1\" ]]; then\n  set -o xtrace\n  PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'\n  LOG_LEVEL=\"7\"\n  # Enable error backtracing\n  trap '__b3bp_err_report \"${FUNCNAME:-.}\" ${LINENO}' ERR\nfi\n\n# verbose mode\nif [[ \"${arg_v:?}\" = \"1\" ]]; then\n  set -o verbose\nfi\n\n# no color mode\nif [[ \"${arg_n:?}\" = \"1\" ]]; then\n  NO_COLOR=\"true\"\nfi\n\n# help mode\nif [[ \"${arg_h:?}\" = \"1\" ]]; then\n  # Help exists with code 1\n  help \"Help using ${0}\"\nfi\n\n\n### Validation. Error out if the things required for your script are not present\n##############################################################################\n\n[[ \"${arg_f:-}\" ]]     || help      \"Setting a filename with -f or --file is required\"\n[[ \"${LOG_LEVEL:-}\" ]] || emergency \"Cannot continue without LOG_LEVEL. \"\n\n\n### Runtime\n##############################################################################\n\ninfo \"__i_am_main_script: ${__i_am_main_script}\"\ninfo \"__file: ${__file}\"\ninfo \"__dir: ${__dir}\"\ninfo \"__base: ${__base}\"\ninfo \"OSTYPE: ${OSTYPE}\"\n\ninfo \"arg_f: ${arg_f}\"\ninfo \"arg_d: ${arg_d}\"\ninfo \"arg_v: ${arg_v}\"\ninfo \"arg_h: ${arg_h}\"\n\n# shellcheck disable=SC2015\nif [[ -n \"${arg_i:-}\" ]] && declare -p arg_i 2> /dev/null | grep -q '^declare \\-a'; then\n  info \"arg_i:\"\n  for input_file in \"${arg_i[@]}\"; do\n    info \" - ${input_file}\"\n  done\nelif [[ -n \"${arg_i:-}\" ]]; then\n  info \"arg_i: ${arg_i}\"\nelse\n  info \"arg_i: 0\"\nfi\n\n# shellcheck disable=SC2015\nif [[ -n \"${arg_x:-}\" ]] && declare -p arg_x 2> /dev/null | grep -q '^declare \\-a'; then\n  info \"arg_x: ${#arg_x[@]}\"\nelif [[ -n \"${arg_x:-}\" ]]; then\n  info \"arg_x: ${arg_x}\"\nelse\n  info \"arg_x: 0\"\nfi\n\ninfo \"$(echo -e \"multiple lines example - line #1\\\\nmultiple lines example - line #2\\\\nimagine logging the output of 'ls -al /path/'\")\"\n\n# All of these go to STDERR, so you can use STDOUT for piping machine readable information to other software\ndebug \"Info useful to developers for debugging the application, not useful during operations.\"\ninfo \"Normal operational messages - may be harvested for reporting, measuring throughput, etc. - no action required.\"\nnotice \"Events that are unusual but not error conditions - might be summarized in an email to developers or admins to spot potential problems - no immediate action required.\"\nwarning \"Warning messages, not an error, but indication that an error will occur if action is not taken, e.g. file system 85% full - each item must be resolved within a given time. This is a debug message\"\nerror \"Non-urgent failures, these should be relayed to developers or admins; each item must be resolved within a given time.\"\ncritical \"Should be corrected immediately, but indicates failure in a primary system, an example is a loss of a backup ISP connection.\"\nalert \"Should be corrected immediately, therefore notify staff who can fix the problem. An example would be the loss of a primary ISP connection.\"\nemergency \"A \\\"panic\\\" condition usually affecting multiple apps/servers/sites. At this level it would usually notify all tech staff on call.\"\n\n### Signal trapping and backtracing\n##############################################################################\n\nfunction __b3bp_cleanup_before_exit () {\n  info \"Cleaning up. Done\"\n}\ntrap __b3bp_cleanup_before_exit EXIT\n\n# requires `set -o errtrace`\n__b3bp_err_report() {\n    local error_code=${?}\n    # shellcheck disable=SC2154\n    error \"Error in ${__file} in function ${1} on line ${2}\"\n    exit ${error_code}\n}\n# Uncomment the following line for always providing an error backtrace\ntrap '__b3bp_err_report \"${FUNCNAME:-.}\" ${LINENO}' ERR\n\n\n### Command-line argument switches (like -d for debugmode, -h for showing helppage)\n##############################################################################\n\n# debug mode\nif [[ \"${arg_d:?}\" = \"1\" ]]; then\n  set -o xtrace\n  PS4='+(${BASH_SOURCE}:${LINENO}): ${FUNCNAME[0]:+${FUNCNAME[0]}(): }'\n  LOG_LEVEL=\"7\"\n  # Enable error backtracing\n  trap '__b3bp_err_report \"${FUNCNAME:-.}\" ${LINENO}' ERR\nfi\n\n# verbose mode\nif [[ \"${arg_v:?}\" = \"1\" ]]; then\n  set -o verbose\nfi\n\n# no color mode\nif [[ \"${arg_n:?}\" = \"1\" ]]; then\n  NO_COLOR=\"true\"\nfi\n\n# help mode\nif [[ \"${arg_h:?}\" = \"1\" ]]; then\n  # Help exists with code 1\n  help \"Help using ${0}\"\nfi", "num_lines": 429}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n## Tools / Functions that are used in multiple different scripts.\n\n# Terraform Init - intialise a tf template + Azure Blob storage\n# call with\nfunction terraform_init() {\n\n    if [[ $# -ne 3 ]];\n    then\n        error \"terraform_init expects 3 arguments $# received\"\n        return 1\n    fi\n\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n\n    _storage_account_name=\"$1\"\n    _container_name=\"$2\"\n    _container_rg=\"$3\"\n\n    terraform init \\\n        -backend-config \"storage_account_name=$_storage_account_name\" \\\n        -backend-config \"container_name=$_container_name\" \\\n        -backend-config \"resource_group_name=$_container_rg\"\n}\n\n# Polls for the latest run of a workflow and waits until it\n# Arg1 github username\n# Arg2 github personal access toem\n# Arg3 github organization\n# Arg4 github repository name\nfunction wait_for_gitgub_workflow() {\n\n    if [[ $# -ne 4 ]];\n    then\n        error \"wait_for_gitgub_workflow expects 4 arguments $# received\"\n        return 1\n    fi\n\n    local _pat_username=\"$1\"\n    local _pat_password=\"$2\"\n    local _org=\"$3\"\n    local _repo=\"$4\"\n\n    # First get the what is the workflow id.\n    # This works only with one workflow\n    local workflow_count=0\n    local workkflow_list_response=\"\"\n\n    while [ $workflow_count -le 0 ]\n    do\n        workkflow_list_response=$(curl -s -u \"$_pat_username\":\"$_pat_password\" https://api.github.com/repos/\"$_org\"/\"$_repo\"/actions/workflows)\n        error_message=$(echo \"$workkflow_list_response\" | jq -r '.message' | tr -d \"\\n\")\n        \n        if [[ \"$error_message\" == \"null\" ]]\n        then\n             workflow_count=$(echo \"$workkflow_list_response\" | jq -r '.total_count' | tr -d \"\\n\")\n             debug \"Workflows in repo: $workflow_count\"\n             if [ \"$workflow_count\" -gt \"1\" ]\n             then\n                error \"This script only supports repositories with one workflow file, please PR to improve\"\n                exit 44\n             fi\n             if [ \"$workflow_count\" -lt \"1\" ]\n             then\n                error \"The repository $_org/$_repo does not have any workflow\"\n                exit 44\n             fi\n\n\n        elif [[ \"$error_message\" == \"Not Found\" ]]\n        then\n             error \"Repository $_org/$_repo not found\"             \n             exit 33\n        else\n             error \"Unknown error received from GH $error_message\"\n             debug \"$workkflow_list_response\"\n             exit 32\n        fi\n    done\n\n    workflow_id=$(echo \"$workkflow_list_response\" | jq -r '.workflows[].id' | tr -d \"\\n\")\n    workflow_name=$(echo \"$workkflow_list_response\" | jq -r '.workflows[].name' | tr -d \"\\n\")\n    info \"Polling for the status of $workflow_name\"\n    conclusion=\"temp\"\n    while [[ \"$conclusion\" = \"temp\" ]]\n    do\n        result=$(curl -s -u \"$_pat_username\":\"$_pat_password\" https://api.github.com/repos/\"$_org\"/\"$_repo\"/actions/workflows/\"$workflow_id\"/runs | jq '.workflow_runs | sort_by(.created_at) | reverse | .[0] | { status: .status, conclusion: .conclusion }')        \n        status=$(echo \"$result\" | jq -r '.status' | tr -d \"\\n\")\n        info \"Workflow $workflow_name for repo $_repo is $status\"\n        if [[ \"$status\" == \"completed\" ]]\n        then\n            conclusion=$(echo \"$result\" | jq -r '.conclusion' | tr -d \"\\n\")\n        else\n            sleep 10\n        fi\n    done\n    info \"Workflow $workflow_name for repo $_repo is $status with conclusion $conclusion\" \n    echo \"$conclusion\"\n}", "num_lines": 102}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/tools.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/logging.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/ini_val.sh\"\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/clone-repos.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../../pipelines/application-management/scripts/clone-repos.sh\"\n\nfunction populate-repos() {\n\n    info \"Populating repositories\"    \n    _config_file=\"$1\"\n    \n    _file_root=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\n    _builtin=(\"archetype-management\" \"cluster-management\" \"application-management\" \"cluster-state\")\n    _applications=(\"sample-app-nodejs\")\n    \n    _org=$(ini_val \"$_config_file\" github.org)\n    _prefix=$(ini_val \"$_config_file\" c12.prefix)\n    _pat_username=$(ini_val \"$_config_file\" github.access-token-username)\n    _pat_password=$(ini_val \"$_config_file\" github.access-token)\n    \n    aks_name=$(ini_val \"$_config_file\" c12:generated.aks_name)\n    ci_acr_name=$(ini_val \"$_config_file\" c12:generated.ci_acr_name)\n    \n    _tempfile=$(mktemp -d)\n    \n    pushd \"$_tempfile\" || exit 2\n    \n    info \"Cloning management repositories\"\n    for repo in \"${_builtin[@]}\"; do\n        git clone \"https://${_pat_username}:${_pat_password}@github.com/$_org/$_prefix-$repo.git\"\n    done    \n\n    info \"Seeding management repositories with workflows and dependencies\"\n    for managment_repo in \"${_builtin[@]}\"; do\n        info \"Feeding static data of from $managment_repo to $_prefix-$managment_repo\"\n        pushd \"$_prefix-$managment_repo\" || exit 2\n        cp -R \"$_file_root/../../pipelines/$managment_repo/.\" .\n        if [ -d \"./scripts\" ]; then\n            # add scripts to .c12 dir\n            mkdir -p \".c12/scripts/\"\n            rsync -qa --progress --remove-source-files \"scripts/.\" \".c12/scripts/\"\n            echo \".c12/*   @$_org/$_prefix-$managment_repo-owner\" > ./CODEOWNERS        \n        fi\n        #Add prefex to codeowners file in Management repo.\n        echo \".github/*   @$_org/$_prefix-$managment_repo-owner\" > ./CODEOWNERS        \n        popd || exit 2\n    done    \n\n    #Temporary workaround until we see how much templating is actually required.\n    docker_registry_url=$(az acr show -n \"${ci_acr_name}\" -o json | jq -r '.loginServer' | tr -d '\\n')\n        \n    pushd \"$_prefix-application-management/.github/actions\" || exit 2\n    # this warning is about filenames with spaces or globbing issues, which in this case is impossible as we\n    # are looking for an exact filename match that does not have any globbing issues or spaces,\n    # shellcheck disable=SC2044\n    for file in $(find ./ -name \"action.yaml.tmpl\")\n    do\n        docker_login_server=\"$docker_registry_url\" envsubst < \"$file\" > \"${file%.*}\"\n        rm \"$file\"\n    done\n    popd  || exit 2\n        \n    #Copy Terraform Components to Application Management repo.\n    info \"Adding terraform to application-management repository\"\n    mkdir -p \"$_prefix-application-management/.c12/components\"\n    rsync -avr --exclude='**/.terraform/' --exclude='*.tfplan' \"$_file_root/../../../components/.\" \"$_prefix-application-management/.c12/components\"\n\n    # Copy Application Source pipline and Plus Repo contence to `application-management/components/c--solutions`\n    mkdir -p \"$_prefix-application-management/.c12/components/ci-solutions\"\n    rsync -avr --exclude='README.md' \"$_file_root/../../pipelines/application-src/.\" \"$_prefix-application-management/.c12/components/ci-solutions\"\n    mkdir -p \"$_prefix-application-management/.c12/components/ci-solutions/.c12/scripts\"\n    rsync -qa --progress --remove-source-files \"$_prefix-application-management/.c12/components/ci-solutions/scripts/.\" \"$_prefix-application-management/.c12/components/ci-solutions/.c12/scripts/\"\n\n    info \"Commiting management repositories\"\n    for managment_repo in \"${_builtin[@]}\"; \n    do\n        pushd \"$_prefix-$managment_repo\" || exit 2\n        git add -A\n        git diff-index --quiet HEAD || git commit -a -m \"C12 Bootstrap - Creation of workflows and actions\"\n        git push\n        popd || exit 2\n    done\n\n    #Push sample archetype\n    info \"Feeding sample archetype\"\n    pushd \"$_prefix-archetype-management\" || exit 2\n    cp -R \"$_file_root/../../manifests/archetype-management/.\" .\n    git add -A\n    git diff-index --quiet HEAD || git commit -a -m \"C12 Bootstrap - Add demo Archetype\"\n    git push\n    popd || exit\n\n\n    info \"Onboarding sample apps\"\n    for app_repo in \"${_applications[@]}\"; do\n        info \"Creating demo app $app_repo definition, no versions\"\n        #Generate the app.yaml for this app, this will trigger the pipeline and the creation of all infrastructure required,\n        app_version=\"null\" \\\n        aks_name=$aks_name \\\n        envsubst < \"$_file_root/../../manifests/application-management/$app_repo.yaml\" > \"$_prefix-application-management/$app_repo.yaml\"\n    done\n\n\n    pushd \"$_prefix-application-management\" || exit 2\n    git add -A\n    git commit -m \"C12 Bootstrap - On board demo appplications\"\n    git push \n    popd || exit    \n\n    info \"Waiting for management pipelines to run\"\n    \n    arch_completion=$(wait_for_gitgub_workflow \"${_pat_username}\" \"${_pat_password}\" \"${_org}\" \"$_prefix-archetype-management\")\n    app_completion=$(wait_for_gitgub_workflow \"${_pat_username}\" \"${_pat_password}\" \"${_org}\" \"$_prefix-application-management\")\n    \n    if [[ \"$arch_completion\" != \"success\" ]] || [[ \"$app_completion\" != \"success\" ]] \n    then\n        error \"Pipelines did not run successfully: archetype-management:$arch_completion application-management:$app_completion\"\n        exit 55\n    fi\n    \n    info \"Pipelines completed successfully, adding demo sources to the repositories\"    \n\n    for app_repo in \"${_applications[@]}\"; do\n        info \"Seeding  demo content for $app_repo\"\n        \n        #Seed the contents for the -src repository with the source code to be compiled and deployed.        \n        git clone \"https://${_pat_username}:${_pat_password}@github.com/$_org/$_prefix-$app_repo-src.git\"\n        cd \"$_prefix-$app_repo-src\"        \n        \n        rsync -avr --exclude='.github/.' --exclude='.github/.' \"$_file_root/../../manifests/sample-app-nodejs-src/.\" \".\"\n        \n        git add -A\n        git diff-index --quiet HEAD || git commit -a -m \"Initial code import\"        \n        git rev-parse v0.0.0 || git tag -a v0.0.0 -m \"Initial commit\"\n        git push -u origin master --follow-tags --force\n        \n        app_version=$(git describe --long --tags)\n\n        ini_val \"$_config_file\" c12:generated.app_version \"$app_version\"\n        cd ..\n        sleep 1\n        #Wait until the app-src has completed, so the images are available.\n        app_src_completion=$(wait_for_gitgub_workflow \"${_pat_username}\" \"${_pat_password}\" \"${_org}\" \"$_prefix-$app_repo-src\")\n\n        if [[ \"$app_src_completion\" != \"success\" ]]\n        then\n            error \"Pipelines did not run successfully: app-src:$app_src_completion\"\n            exit 55\n        fi\n        \n        #Generate the app.yaml for this app with the version we just added\n        app_version=$app_version \\\n        aks_name=$aks_name \\\n        envsubst < \"$_file_root/../../manifests/application-management/$app_repo.yaml\" > \"$_prefix-application-management/$app_repo.yaml\"\n        \n        # commit managment repo to trigger Pipeling and creat app repos\n        cd \"$_prefix-application-management/\"\n        git add -A\n        git diff-index --quiet HEAD || git commit -a -m \"C12 Bootstrap -- Update $app_repo, version $app_version\"\n        git push\n        sleep 1\n        cd ..\n        \n        # Pushing sample Source code to the newly created (from the Application Managment Pipeline) scr repo\n        # Polls for the latest run of a workflow and waits until it\n        app_completion=$(wait_for_gitgub_workflow \"${_pat_username}\" \"${_pat_password}\" \"${_org}\" \"$_prefix-application-management\")\n    \n        if [[ \"$app_completion\" != \"success\" ]] \n        then\n            error \"Pipelines did not run successfully: application-management:$app_completion\"\n            exit 55\n        fi\n    done\n    \n    popd || exit 2\n    \n}", "num_lines": 186}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/tools.sh\"\n\nrelative_ci_docker_image=\"../ci-tooling\"\ndocker_ci_image_name=\"c12/ci-tooling\"\ndocker_ci_image_tag=\"latest\"\n\nfunction push_docker_image() {\n\n    acr_name=\"$1\"\n    docker_image_repository=\"$2\"\n\n    #echo -n \"$docker_image_repository_passwd\" | docker login \"$docker_image_repository\" --username \"$docker_image_repository_username\" --password-stdin\n    az acr login -n \"$acr_name\"\n\n    docker push \"$docker_image_repository\"/\"$docker_ci_image_name\":\"$docker_ci_image_tag\"\n}\n\nfunction build_docker_image() {\n\n    image_full_name=\"$1\"\n\n    pushd \"$relative_ci_docker_image\"  || exit 2\n    docker build -t \"$image_full_name\" .\n    popd  || exit 2\n}\n\nfunction provision_ci_docker_image() {\n    # shellcheck disable=SC2154\n    ci_acr_name=$(ini_val \"$config_file\" c12:generated.ci_acr_name)\n    docker_image_repository=\"$(az acr show --n \"$ci_acr_name\" -o json | jq -r '.loginServer' | tr -d '\\n')\"\n    image_full_name=\"$docker_image_repository\"/\"$docker_ci_image_name\":\"$docker_ci_image_tag\"\n\n    build_docker_image \"$image_full_name\"\n    push_docker_image \"$ci_acr_name\" \"$docker_image_repository\"\n}", "num_lines": 39}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/tools.sh\"\n\nrelative_terraform_path=\"../../components/infrastructure/azure/aad_credentials_actions/\"\n_required_repos=\"archetype-management application-management\"\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction aad_credentials_for_pipelines_create(){\n\n    local _timestamp\n    local _subscription_id\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n    local _access_token_username\n    local _access_token\n    local _org\n    local _ci_acr_name\n\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Creating SP and provision in GH as secret\"\n\n    pushd \"$relative_terraform_path\" || exit 2\n\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token_username=$(ini_val \"$config_file\" github.access-token-username)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _org=$(ini_val \"$config_file\" github.org)\n    _ci_acr_name=$(ini_val \"$config_file\" c12:generated.ci_acr_name)\n\n    _repositories=\"[\"\n    for repo in $_required_repos\n    do\n         _repositories=$_repositories\"\\\"\"\"$_prefix\"-\"$repo\"\"\\\", \"\n    done\n    # Trim the last two charcaters\n    _repositories=\"${_repositories%??}\"\"]\"\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"subscription_id=$_subscription_id\" \\\n        -var \"prefix=$_prefix\"\\\n        -var \"org=$_org\" \\\n        -var \"access_token=$_access_token\" \\\n        -var \"access_token_username=$_access_token_username\" \\\n        -var \"repositories=$_repositories\"\\\n        -var \"ci_acr_name=$_ci_acr_name\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    rm \"$_timestamp.tfplan\"\n\n    popd || exit 2\n\n    info \"Service principal created and provisioned in github\"\n}\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction aad_credentials_for_pipelines_destroy(){\n\n    local _timestamp\n    local _subscription_id\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n    local _access_token_username\n    local _access_token\n    local _org\n    local _ci_acr_name\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Destroying SP and GH secrets\"\n\n    pushd \"$relative_terraform_path\" || exit 2\n\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _access_token_username=$(ini_val \"$config_file\" github.access-token-username)\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _org=$(ini_val \"$config_file\" github.org)\n    _ci_acr_name=$(ini_val \"$config_file\" c12:generated.ci_acr_name)\n\n\n    _repositories=\"[\"\n    for repo in $_required_repos\n    do\n         _repositories=$_repositories\"\\\"\"\"$_prefix\"-\"$repo\"\"\\\", \"\n    done\n    # Trim the last two charcaters\n    _repositories=\"${_repositories%??}\"\"]\"\n\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan \\\n        -lock=true \\\n        -destroy \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"subscription_id=$_subscription_id\" \\\n        -var \"prefix=$_prefix\"\\\n        -var \"org=$_org\" \\\n        -var \"access_token=$_access_token\" \\\n        -var \"access_token_username=$_access_token_username\" \\\n        -var \"repositories=$_repositories\"\\\n        -var \"ci_acr_name=$_ci_acr_name\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    rm \"$_timestamp.tfplan\"\n    rm -rf .terraform\n\n    popd || exit 2\n\n    info \"Destroyed Service principal and GH secrets\"\n}\n", "num_lines": 132}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/tools.sh\"\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction terraform_aks(){\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n    local _service_principal_id\n    local _service_principal_application_id\n    local _service_principal_password\n    local _regional_acr_name\n    local _ci_acr_name\n    local _aks_name\n    local _ssh_key_location\n\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Creating AKS Cluster\"\n\n    pushd ../../components/infrastructure/azure/aks/ || exit 2\n\n    pwd\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"location=$_location\" \\\n        -var \"subscription_id=$_subscription\" \\\n        -var \"prefix=$_prefix\"\\\n        -var \"storage_account_name=$_storage_account_name\"\\\n        -var \"container_name=$_container_name\"\\\n        -var \"resource_group_name=$_container_rg\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    _service_principal_id=$(terraform output service_principal_id)\n    _service_principal_application_id=$(terraform output service_principal_application_id)\n    _service_principal_password=$(terraform output service_principal_password)\n    _regional_acr_name=$(terraform output regional_acr_name)\n    _ci_acr_name=$(terraform output ci_acr_name)\n    _ssh_key_location=\"$(pwd)/$(terraform output ssh_key_location)\"\n    _aks_name=\"$(terraform output aks_name)\"\n    _disk_encryption_set_id=\"$(terraform output disk_encryption_set_id)\"\n\n\n    ini_val \"$config_file\" c12:generated.service_principal_id \"$_service_principal_id\"\n    ini_val \"$config_file\" c12:generated.service_principal_application_id \"$_service_principal_application_id\"\n    ini_val \"$config_file\" c12:generated.service_principal_password \"$_service_principal_password\"\n    ini_val \"$config_file\" c12:generated.regional_acr_name \"$_regional_acr_name\"\n    ini_val \"$config_file\" c12:generated.ci_acr_name \"$_ci_acr_name\"\n    ini_val \"$config_file\" c12:generated.aks_name \"$_aks_name\"\n    ini_val \"$config_file\" c12:generated.aks_ssh_key_location \"$_ssh_key_location\"\n    ini_val \"$config_file\" c12:generated.disk_encryption_set_id \"$_disk_encryption_set_id\"\n\n\n    rm \"$_timestamp.tfplan\"\n\n    popd || exit 2\n\n    info \"Created AKS Cluster\"\n\n}\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction destroy_aks(){\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Destroying AKS Cluster\"\n\n    pushd ../../components/infrastructure/azure/aks/ || exit 2\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan \\\n        -lock=true \\\n        -destroy \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"location=$_location\" \\\n        -var \"subscription_id=$_subscription\" \\\n        -var \"prefix=$_prefix\"\\\n        -var \"storage_account_name=$_storage_account_name\"\\\n        -var \"container_name=$_container_name\"\\\n        -var \"resource_group_name=$_container_rg\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    rm \"$_timestamp.tfplan\"\n    rm -rf .terraform\n\n    popd || exit 2\n\n    info \"Destroyed AKS Cluster\"\n\n}", "num_lines": 128}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../lib/tools.sh\"\n\n\n# Installs all the required software on jumphost\nfunction install_dependencies() {\n\n\tcurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\t# required az cli extentions for Azure Arc\n\taz extension add --name connectedk8s\n\taz extension add --name k8sconfiguration\n\n\t# latest Kubernetes\n\tsudo apt-get update && sudo apt-get install -y apt-transport-https gnupg2\n\tcurl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | sudo apt-key add -\n\techo \"deb https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list\n\tsudo apt-get update\n\tsudo apt-get install -y kubectl\n\n\t# instal latest Helm 3\n\tcurl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash\n\n}\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction terraform_network(){\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n    local _vnet_id\n    local _ssh_key_location\n    local _jumphost_user\n    local _jumphost_ip\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Creating Networks\"\n\n    pushd ../../components/infrastructure/azure/network/ || exit 2\n\n    pwd\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"location=$_location\" \\\n        -var \"subscription_id=$_subscription\" \\\n        -var \"prefix=$_prefix\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    _vnet_id=$(terraform output vnet_id)\n    _ssh_key_location=\"$(pwd)/$(terraform output ssh_key_location)\"\n    _jumphost_user=$(terraform output jumphost_user)\n    _jumphost_ip=$(terraform output jumphost_ip)\n\n\n    ini_val \"$config_file\" c12:generated.vnet-id \"$_vnet_id\"\n    ini_val \"$config_file\" c12:generated.jumphost_ssh_key_location \"$_ssh_key_location\"\n    ini_val \"$config_file\" c12:generated.jumphost_user \"$_jumphost_user\"\n    ini_val \"$config_file\" c12:generated.jumphost_ip \"$_jumphost_ip\"\n\n\n    ssh -oStrictHostKeyChecking=no \"$_jumphost_user\"@\"$_jumphost_ip\" -i \"$_ssh_key_location\" \"cat /etc/hostname && ifconfig\"\n    ssh -oStrictHostKeyChecking=no \"$_jumphost_user\"@\"$_jumphost_ip\" -i \"$_ssh_key_location\" \"sudo apt-get -y update && sudo apt-get install -y tinyproxy\"\n\t# shellcheck disable=SC2154\n\tssh -oStrictHostKeyChecking=no \"$_jumphost_user\"@\"$_jumphost_ip\" -i \"$_ssh_key_location\" \"$(typeset -f); install_dependencies\"\n\n    rm \"$_timestamp.tfplan\"\n\n    popd || exit 2\n\n    info \"Created Networks\"\n\n}\n\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction destroy_network(){\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n\n     _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n    info \"Destroying Networks\"\n\n    pushd ../../components/infrastructure/azure/network/ || exit 2\n\n    pwd\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n\n    terraform_init \"$_storage_account_name\" \"$_container_name\" \"$_container_rg\"\n\n    terraform plan -destroy \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"location=$_location\" \\\n        -var \"subscription_id=$_subscription\"  \\\n        -var \"prefix=$_prefix\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    rm \"$_timestamp.tfplan\"\n    rm -rf .terraform\n\n    popd || exit 2\n\n    info \"Destroyed Networks\"\n\n}", "num_lines": 137}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction terraform_storage_account() {\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n\n    info \"Creating Storage Account for Terraform State\"\n\n    pushd ../../components/infrastructure/azure/state-store/ || exit 2\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    terraform init\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"location=$_location\" \\\n        -var \"subscription_id=$_subscription\" \\\n        -var \"prefix=$_prefix\"\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    _access_key=$(terraform output access_key)\n    _storage_account_name=$(terraform output storage_account_name)\n    _container_name=$(terraform output container_name)\n    _container_rg=$(terraform output arm_rg_name)\n\n    ini_val \"$config_file\" terraform:generated.arm-access-key \"$_access_key\"\n    ini_val \"$config_file\" terraform:generated.storage-account-name \"$_storage_account_name\"\n    ini_val \"$config_file\" terraform:generated.container-name \"$_container_name\"\n    ini_val \"$config_file\" terraform:generated.container-rg \"$_container_rg\"\n\n    rm \"$_timestamp.tfplan\"\n\n    popd || exit 2\n\n    info \"Created Storage Account $_storage_account_name for Terraform State\"\n}\n# we know the config_file var is set from script that is sourcing this one\n# shellcheck disable=SC2154\nfunction destroy_storage_account() {\n\n    local _timestamp\n    local _location\n    local _subscription\n    local _prefix\n    local _storage_account_name\n    local _container_name\n    local _container_rg\n\n    _timestamp=$(date \"+%Y:%m:%d-%H:%M\")\n\n\n    info \"Deleting Storage Account for Terraform State\"\n\n    pushd ../../components/infrastructure/azure/state-store/ || exit 2\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n\n    terraform plan -destroy -out \"${_timestamp}.tfplan\" -var \"location=$_location\" -var \"subscription_id=$_subscription\" -var \"prefix=$_prefix\"\n    terraform apply \"${_timestamp}.tfplan\"\n\n    rm \"$_timestamp.tfplan\"\n    rm -rf .terraform\n\n    popd || exit 2\n\n    info \"Deleted Storage Account $_storage_account_name for Terraform State\"\n}\n", "num_lines": 86}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# This functions iterates over the rbac folder, and for each file found\n# It gets from the .ini file the ${prefix}_group_id.  ${prefix} being the file name in rbac\n# then renders the file and copies it to the cluster folder, defined by Arg1\n# then it commits git and pushes the changes.\n# Arg1 the cluster-state folder where the rbac files render will be added.\nfunction configure_gatekeeper() {\n\n    if [[ $# -ne 1 ]];\n    then\n        error \"Expecting 1 arguments for this function\"\n        return 1\n    fi\n\n    cluster_folder=\"$1\"\n    info \"Adding Gatekeeper configuration to  files to $cluster_folder\"\n    \n    rbac_folder=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/manifests/gatekeeper/*\"\n    for f in $rbac_folder\n    do\n        info \"Adding $f \"\n        local_file_name=\"$(basename -- \"${f}\")\"       \n        cp \"$f\" \"$cluster_folder\"/\"$local_file_name\"\n    done\n\n    pushd \"$cluster_folder\" >/dev/null || return 1    \n  \n    cd ..\n    info \"Commiting Gatekeeper config\"\n    git add .\n    git commit -m \"Onboarding: Gatekeeper config\" || true\n    git push \n    popd >/dev/null || return 1\n}", "num_lines": 42}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\nfunction get_all_k8s_objects_by_kind() {\n    \n    if [[ $# -ne 1 ]];\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    local _kind\n    _kind=\"$1\"\n    kubectl get \"$_kind\" -o json  | jq -r '.items[]'\n}\n\nfunction configure_storage_classes() {\n\n    if [[ $# -ne 1 ]];\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    local _disk_encryption_set_id\n    _disk_encryption_set_id=\"$1\"\n    \n    all_storage_classes=$(get_all_k8s_objects_by_kind \"storageclasses.storage.k8s.io\")\n\n    #Iterate it over the non encrypted storage classes so we create a duplicated version with encryption\n    for storageclass in $(echo \"$all_storage_classes\" | jq -r '. | select(.provisioner == \"kubernetes.io/azure-disk\") | select(.parameters.diskEncryptionSetID == null)  | .metadata.name')\n    do\n        echo \"Creating encrypted storage class based on $storageclass\"\n        echo \"$all_storage_classes\" | jq --arg name \"$storageclass\" --arg disk_encryption_set_id \"$_disk_encryption_set_id\" '. | select(.metadata.name == $name) | . * {\"parameters\" : {\"diskEncryptionSetID\": $disk_encryption_set_id}}  | . *{\"metadata\": {\"name\": ( $name + \"-encrypted\") }}' | kubectl apply -f -\n    done\n\n    #Delete all storage classes that are not encryptable \n    #Currently this is impossible in AKS since they get recreated automatically\n    #delete happens, but it gets re-applyed by the add-on manager anytime.\n    #for storageclass in $(echo \"$all_storage_classes\" | jq -r 'select(.parameters.diskEncryptionSetID == null) | .metadata.name')\n    #do\n    #     kubectl delete storageclasses.storage.k8s.io \"$storageclass\"\n    #done\n}", "num_lines": 47}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# Checks out the repository url received in Arg1 and creates a folder with the name of the cluster (Arg2)\n# Arg1 the url of the git repository\n# Arg2 the name of the clusteer\nfunction create_folder_for_state_repo() {\n    set -euo pipefail\n    \n    info \"Creating folder in cluster-state repository for cluster\"\n    if [[ $# -ne 2 ]];\n    then\n        error \"Expecting 2 arguments for this function\"\n        return 1\n    fi\n\n    git_url=\"$1\"\n    cluster_name=\"$2\"\n\n    tmp_dir=\"$(mktemp -d)\"\n\n    cluster_folder=\"$tmp_dir/$cluster_name\"\n\n\n    info \"Clonning cluster state repo ($git_url) into $tmp_dir\"\n    git clone \"$git_url\" \"$tmp_dir\"\n\n\n    # If the destination folder already contains the cluster folder\n    # It most likely mean that the script failed before, but the folder was already commited\n    if [[ -d \"$cluster_folder\" ]]; then\n        warning \"Folder in the cluster-state repository already exists, ovewriting contents\"\n        echo \"$cluster_folder\"\n        return 0\n    fi\n\n    pushd \"$tmp_dir\" >/dev/null || return 2\n    mkdir \"$cluster_name\"\n\n    touch \"$cluster_name\"/.gitignore\n    git add \"$cluster_name\"\n    git commit -m \"Onboarding: Add $cluster_name folder\" >/dev/null\n\n    info \"Commiting folder to git\"\n    git push\n    popd >/dev/null || return 2\n    echo \"$cluster_folder\"\n    return 0\n}", "num_lines": 52}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n\nfunction generate_cluster_management_file() {\n\n    info \"Creating cluster management file\"\n\n    # Gather the login URL for ACR\n    cluster_name=$(get_from_ini_or_error \"$config_file\" c12:generated.aks_name)\n    acr_name=$(get_from_ini_or_error \"$config_file\" c12:generated.regional_acr_name)\n    prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n    \n    docker_registry_url=$(az acr show -n \"${acr_name}\" -o json | jq -r '.loginServer' | tr -d '\\n')\n    kubernetes_api_url=$(az aks get-credentials  -n \"$cluster_name\" -g \"$prefix\"-c12-rg -f - | grep 'server:' | cut -d' ' -f 6 | tr -d '\\n')\n    helm_registry_url=\"https://${docker_registry_url}/helm/v1/repo\"\n    \n    cluster_file_contents=$(render_cluster_management_temaplate \"$cluster_name\" \"$docker_registry_url\" \"$helm_registry_url\" \"$kubernetes_api_url\") \n    cluster_file_path=/tmp/\"$cluster_name\".yaml\n    \n    echo \"$cluster_file_contents\" > \"$cluster_file_path\"  \n    echo \"$cluster_file_path\"\n}\n\n# render_cluster_management_temaplate renders the cluster.yaml into the stdin\n# Arg1 the name of the cluster\n# Arg2 the docker registry\n# Arg3 the helm chart registry URL\n# Arg4 the URL of kubernetes API\nfunction render_cluster_management_temaplate() {\n \n    if [[ $# -ne 4 ]]\n    then\n        error \"render_cluster_management_temaplete 4 arguments for this function\"\n        return 1\n    fi\n\n    cluster_name=\"$1\" \n    docker_registry_url=\"$2\"\n    helm_registry_url=\"$3\"\n    kubernetes_api_url=\"$4\"\n\n    cluster_file_template=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../manifests/cluster-management-template.yaml\"\n\n    # the file contains the token to be replaced by the values.\n    cluster_name=$cluster_name docker_registry_url=$docker_registry_url \\\n    helm_registry_url=$helm_registry_url  kubernetes_api_url=$kubernetes_api_url \\\n    envsubst < \"$cluster_file_template\"\n}\n", "num_lines": 56}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n\nflux_access_retries=10\nflux_sleep_interval=10\n\n\nfunction get_flux_ssh_keys() {\n\n    if [[ $# -ne 2 ]]\n    then\n        error \"Expecting 2 arguments for this function\"\n        return 1\n    fi\n\n    namespace=\"$1\"\n    releasename=\"$2\"\n    servicename=\"$releasename\"\n\n    # ensure the release is deployed before trying to get the services.\n    counter=1\n    status='unknown'\n    while [ $counter -le $flux_access_retries ] && [[ ! \"$status\" == 'deployed' ]]\n    do\n        [ $counter -ge 2 ] && sleep $flux_sleep_interval\n        info \"Getting the status of the flux release $releasename\"\n        status=$(kubectl get -n \"$namespace\" helmreleases.helm.fluxcd.io \"$releasename\" -o jsonpath='{.status.releaseStatus}')\n        counter=$(( counter + 1 ))\n    done\n\n    if  [[ ! $status == 'deployed' ]]; then\n        error \"Flux release failed, status $status\"\n        return 1\n    fi\n\n    # port-forward flux service to access the API that will give us the key\n    info \"Accessing flux api to retrieve ssh keys\"\n    kubectl -n \"$namespace\" --pod-running-timeout=2m0s port-forward service/\"$servicename\" 3030 &>/dev/null &\n\n    # get the ssh key generated by flux by invoking the unprotected API, a POST to that url would force the regeneration of the key\n    ssh_key_path=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/flux_id_rsa.pub\"\n\n    sleep 3\n    curl -sS  http://localhost:3030/api/flux/v6/identity.pub | jq -r '.key' | tr -d '\\n' > \"$ssh_key_path\"\n\n\n    ini_val \"$config_file\" c12:generated.flux_ssh_key \"$ssh_key_path\"\n\n    #kill the kubectl port-forward\n    for job in $(jobs -l \"%kubectl\"  | cut -d' ' -f 2)\n    do\n        kill \"$job\"\n    done\n}\n", "num_lines": 62}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/ini_val.sh\"\n\n\nfunction get_from_ini_or_error() {\n    \n    if [[ $# -ne 2 ]];\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n    \n    ini_file=\"$1\"\n    key=\"$2\"\n\n    if [ ! -f \"$ini_file\" ]; then\n        error \"Ini file with path $ini_file  not found\"\n        return 1\n    fi\n\n   \n    val=$(ini_val \"$ini_file\" \"$key\")\n\n    if [ -z \"$val\" ]; then\n        error \"$key not found in $ini_file, parameter not defined or missing value\"\n        return 1;\n    fi\n\n    echo \"$val\"\n    return 0\n}\n\nfunction get_cluster_state_repo() {\n\n   # shellcheck disable=SC2154\n   org=$(get_from_ini_or_error \"$config_file\" github.org)\n   prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n   echo \"git@github.com:$org/$prefix-cluster-state.git\"\n   return 0\n}\n\nfunction  get_cluster_management_repo() {\n\n   # shellcheck disable=SC2154\n   org=$(get_from_ini_or_error \"$config_file\" github.org)\n   prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n   echo \"git@github.com:$org/$prefix-cluster-management.git\"\n   return 0\n}\n\n\n\n", "num_lines": 59}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# Imports a chart into ACR, overriding it if it already exists.\n# Param 1 the URL of the source repository ie: https://charts.gitlab.io/\n# Param 2 the name of the helm chart  ie: gitlab\n# Param 3 the version of the helm chart: ie: gitlab 3.1.1\n# Param 4 the name of the ACR wher the helm chart will be pushed\nfunction import_chart_acr() {\n\n    if [[ $# -ne 4 ]];\n    then\n\t\terror \"Missing input parameters\"\n        return 1\n    fi\n\n    tmp_dir=\"$(mktemp -d)\"\n    helm_source_repo=\"$1\"\n    helm_chart=\"$2\"\n    helm_chart_version=\"$3\"\n    acr_name=\"$4\"\n\n    info \"Importing into ACR $acr_name chart $helm_chart with version $helm_chart_version from ${helm_source_repo} \"\n\n    #ACR requires that the chart is uploaded in .tgz so we have to pull it first.\n    helm repo add temp \"$helm_source_repo\" 1>/dev/null\n    tmp_helm_tar=\"${tmp_dir}\"/\"$helm_chart\"-\"$helm_chart_version\".tgz\n    helm pull temp/\"$helm_chart\" --version \"$helm_chart_version\" -d \"$tmp_dir\"\n\n    az acr helm push --force -n \"${acr_name}\" \"$tmp_helm_tar\"\n    helm repo remove temp 1>/dev/null\n    rm \"$tmp_helm_tar\"\n}\n", "num_lines": 37}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n\n# import_image uploads an image to ACR without pulling and pulling. ACR pulls the image directly\n# Arg 1 the name of the ACR where the image will be pulled.\n# Arg 2 the image name with tag version included, ie: memcached:1.3.45\n# returns the imported image full qualified/expanded name in the imported repository\nfunction import_image() {\n    if [[ $# -ne 2 ]];\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    acr_name=$1\n    image=$(strip_tag \"$2\")\n    tag=$(get_image_tag \"$2\")\n    image_fq_name=$(to_full_qualified_image_name \"$image\")\n   \n    info \"Importing into ACR ${acr_name} image ${image_fq_name}:${tag}\"\n    az acr import --force -n \"${acr_name}\" --source \"${image_fq_name}\":\"${tag}\"\n    login_server=$(az acr show -n \"$acr_name\" --query 'loginServer' -o tsv |  tr -d \"\\n\")\n    rewrite_full_qualified_image_name \"$image_fq_name\" \"$login_server\"\n}\n\n# Strips the tag number from an image\n# Arg1 the image with tag included\nfunction strip_tag() {\n   if [ -z \"$1\" ]\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n   echo \"$1\" | cut -d: -f1\n   return 0\n}\n\n# Gets the tag from an image if the image does not contain a tag, returns latest\n# Arg1 the image name\nfunction get_image_tag() {\n    if [ -z \"$1\" ]\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    tag=$(echo \"$1\" | cut -d: -f2)\n    #does the image miss the tag\n    if [ \"$1\" == \"$tag\" ]\n    then\n        tag=\"latest\"\n    fi\n\n    echo \"$tag\"\n    return 0\n}\n\n# Applies the same logic as docker pull to get the full image names. IE: memcached is translated to\n# docker.io/library/memcached. See unit tests for more examples. \n# Arg1 the image name. \nfunction to_full_qualified_image_name() {\n\n    if [ -z \"$1\" ]\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n    image=$1 \n    domain=$(echo \"$image\" | cut -d/ -f1)\n    domain_has_dots=$(echo \"$domain\" | cut -d. -f1)\n\n    #does the image contain an slash? \n    if [ \"$domain\" == \"$image\" ]\n    then\n        echo \"docker.io/library/$1\"\n        return 0\n    #does the first part of the image name, has a dot? \n    elif [ \"$domain\" == \"$domain_has_dots\" ]\n    then\n        echo \"docker.io/$1\"     \n        return 0\n    fi\n    echo \"$image\"\n    return 0\n}\n\n# Rewrites an image into a new repo\n# Arg1 the full image name without tags ie: docker.io/library/memcached\n# Arg2 the domain of the new repository\nfunction rewrite_full_qualified_image_name() {\n\n    if [ -z \"$1\" ] || [ -z \"$2\" ]\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    image=\"$1\"\n    new_repo=\"$2\"\n    echo \"$new_repo/${image#*/}\"\n    return 0\n}\n", "num_lines": 108}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# Exit on error. Append \"|| true\" if you expect an error.\nset -o errexit\n# Exit on error inside any functions or subshells.\nset -o errtrace\n# Catch the error in case any step of a pipe chain fails.\nset -o pipefail\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/import_helm_chart_to_acr.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/import_helm_chart_to_acr.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/import_images.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/import_images.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/ini_val.sh\"\n\nDEF_HELM_OPERATOR_CHART_REPOSITORY=\"https://charts.fluxcd.io\"\nDEF_FLUX_IMAGE=\"fluxcd/flux\"\nDEF_FLUX_IMAGE_TAG=\"1.19.0\"\nDEF_FLUX_HELM_CHART=\"flux\"\nDEF_FLUX_HELM_CHART_VERSION=\"1.3.0\"\n\nfunction install_flux() {\n\n    # shellcheck disable=SC2154\n    if [ -z \"$config_file\" ]\n    then\n        error \"Configuration file argument not defined\"\n        return 1\n    fi\n\n    flux_chart_repository=\"$DEF_HELM_OPERATOR_CHART_REPOSITORY\"\n    flux_image=\"$DEF_FLUX_IMAGE\"\n    flux_image_tag=\"$DEF_FLUX_IMAGE_TAG\"\n\n    flux_helm_chart=\"$DEF_FLUX_HELM_CHART\"\n    flux_helm_chart_version=\"$DEF_FLUX_HELM_CHART_VERSION\"\n\n    acr_name=$(get_from_ini_or_error \"$config_file\" c12:generated.regional_acr_name)\n    naming_prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n    admin_namespace=\"$naming_prefix-c12-system\"\n    cluster_state_repo=\"$(get_cluster_state_repo)\"\n    cluster_name=\"$(get_from_ini_or_error \"$config_file\" c12:generated.aks_name)\"\n\n     # Gather the login URL for ACR\n    login_server=$(az acr show -n \"${acr_name}\" -o json | jq -r '.loginServer' | tr -d '\\n')\n\n    helm_repo_url=\"https://${login_server}/helm/v1/repo\"\n\n    flux_imported_image_name=$(import_image \"${acr_name}\" \"${flux_image}\":\"${flux_image_tag}\")\n    import_chart_acr \"${flux_chart_repository}\" \"${flux_helm_chart}\" \"${flux_helm_chart_version}\" \"${acr_name}\"\n\n    # Render the secrets file needed by helm operator\n    render_flux_helm_release \"$admin_namespace\" \\\n        \"$helm_repo_url\" \\\n        \"$flux_helm_chart\" \\\n        \"$flux_helm_chart_version\" \\\n        \"$cluster_state_repo\" \\\n        \"$cluster_name\" \\\n        \"$flux_imported_image_name\" \\\n        | kubectl apply -f -\n}\n\n\n# This function renders the HelmRelease cdr with the release for flux.\n# Arg1 namespace where the helm release will be created and also the target namespace for the release\n# Arg2 repo_url the url of the repo where the chart should be pulled from\n# Arg3 chart_name the name of the chart to be installed\n# Arg4 chart_version version of the flux chart to install\n# Arg5 the url of the git repository to sync flux\n# Arg6 the folder in the git repository for the cluster being synced\nfunction render_flux_helm_release() {\n    namespace=${1:?Required paramater not supplied}\n    repo_url=${2:?Required paramater not supplied}\n    chart_name=${3:?Required paramater not supplied}\n    chart_version=${4:?Required paramater not supplied}\n    git_repo_url=${5:?Required paramater not supplied}\n    git_repo_folder=${6:?Required paramater not supplied}\n    flux_image=${7:?Required paramater not supplied}\n\n    release_file_template=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../manifests/flux-helm-release.yaml\"\n\n    # the file contains the token to be replaced by the values.\n    namespace=${namespace} repo_url=${repo_url} chart_name=${chart_name} \\\n        chart_version=${chart_version} git_repo_url=${git_repo_url} git_repo_folder=${git_repo_folder} \\\n        flux_image=${flux_image} envsubst < \"$release_file_template\"\n\n    return 0\n }\n", "num_lines": 99}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# Exit on error. Append \"|| true\" if you expect an error.\nset -o errexit\n# Exit on error inside any functions or subshells.\nset -o errtrace\n# Catch the error in case any step of a pipe chain fails.\nset -o pipefail\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/import_helm_chart_to_acr.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/import_helm_chart_to_acr.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/import_images.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/import_images.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n\nDEF_HELM_OPERATOR_CHART_REPOSITORY=\"https://charts.fluxcd.io\"\nDEF_HELM_OPERATOR_CHART_CHART=\"helm-operator\"\nDEF_HELM_OPERATOR_CHART_VERSION=\"0.7.0\"\nDEF_HELM_OPERATOR_IMAGE_NAME=\"fluxcd/helm-operator\"\nDEF_HELM_OPERATOR_IMAGE_TAG=\"1.0.0-rc9\"\n\n\n# Imports a chart into ACR, overriding it if it already exists.\nfunction install_helm_operator {\n\n    # shellcheck disable=SC2154\n    if [ -z \"$config_file\" ]\n    then\n        error \"Configuration file argument not defined\"\n        exit 1\n    fi\n\n    flux_chart_repository=\"$DEF_HELM_OPERATOR_CHART_REPOSITORY\"\n    helm_operator_chart=\"$DEF_HELM_OPERATOR_CHART_CHART\"\n    helm_operator_chart_version=\"$DEF_HELM_OPERATOR_CHART_VERSION\"\n    helm_operator_image=\"$DEF_HELM_OPERATOR_IMAGE_NAME\"\n    helm_operator_image_version=\"$DEF_HELM_OPERATOR_IMAGE_TAG\"\n\n    naming_prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n    acr_name=$(get_from_ini_or_error \"$config_file\" c12:generated.regional_acr_name)\n    admin_namespace=\"$naming_prefix-c12-system\"\n    service_principal_application_id=$(get_from_ini_or_error \"$config_file\" c12:generated.service_principal_application_id)\n    service_principal_password=$(get_from_ini_or_error \"$config_file\" c12:generated.service_principal_password)\n\n    helm_operator_helm_release_manifest_url=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../manifests/flux-helm-release-crd.yaml\"\n\n    info \"Creating helmrelease CRD\"\n    # Install the CRD for helmrelease (handled by helm operator)\n    kubectl apply -f \"${helm_operator_helm_release_manifest_url}\"\n\n    info \"Importing helm operator \"\n    # Import the helm operator chart and required images into ACR\n    import_image \"${acr_name}\" \"${helm_operator_image}\":\"${helm_operator_image_version}\"\n    import_chart_acr \"${flux_chart_repository}\" \"${helm_operator_chart}\" \"${helm_operator_chart_version}\" \"${acr_name}\"\n\n    # Gather the login URL for ACR\n    login_server=$(az acr show -n \"${acr_name}\" -o json | jq -r '.loginServer' | tr -d '\\n')\n\n    helm_repos_yaml=\"$(mktemp)\"\n\n    # Render the secrets file needed by helm operator\n    render_helm_repositories_template \"$acr_name\" \"https://${login_server}/helm/v1/repo\" \"$service_principal_application_id\" \"$service_principal_password\" > \"$helm_repos_yaml\"\n\n    info \"Creating credentials for HelmOperator in kubernetes\"\n    kubectl create secret generic flux-helm-repositories --namespace \"${admin_namespace}\" --from-file=repositories.yaml=\"$helm_repos_yaml\" --dry-run -o yaml | kubectl apply  -f -\n    rm -rf \"$helm_repos_yaml\"\n\n    #install the helm operator through helm\n    helm repo add tmprepo https://charts.fluxcd.io\n\n    helm_operator_values_file=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\"  && pwd)/../manifests/helm-operator-install-values.yaml\"\n    helm_operator_release_name=\"$naming_prefix-c12-system-helm-operator\"\n    helm_operator_image_in_acr=\"tmprepo/$helm_operator_chart\"\n\n    info \"Installing HelmOperator release:$helm_operator_release_name in namespace:$admin_namespace\"\n    #install the the helm operator\n    helm upgrade -i \\\n    --set helm.versions=v3 \\\n    --set image.repository=\"$login_server/$helm_operator_image\" \\\n    --set image.tag=\"$helm_operator_image_version\" \\\n    --namespace \"$admin_namespace\" \\\n    -f \"$helm_operator_values_file\" \\\n    --wait \\\n    \"$helm_operator_release_name\" \\\n    \"$helm_operator_image_in_acr\"\n}\n\n# this function renders the template file that contains the list of repositories that helm operator will have acess to.\nfunction render_helm_repositories_template() {\n\n    if [ -z \"$1\" ] || [ -z \"$2\" ] || [ -z \"$4\" ] || [ -z \"$4\" ]\n    then\n        error \"input parameter not received\"\n        return 1\n    fi\n\n    name=\"$1\"\n    repo_url=\"$2\"\n    username=\"$3\"\n    password=\"$4\"\n\n    repositories_file_template=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/../manifests/helm-repositories.yaml\"\n\n    #create the repositories.yaml that helm-operator requires\n    name=${name} repo_url=${repo_url} username=${username} password=${password} \\\n    envsubst < \"$repositories_file_template\"\n\n    return 0\n }", "num_lines": 117}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\nset -euo pipefail\n\n# shellcheck disable=SC2034\nread -r -d '' __usage <<-'EOF' || true # exits non-zero when EOF encountered\n  -f --file [arg]  Config Filename to use.\n  -v               Enable verbose mode, print script as it is executed\n  -d --debug       Enables debug mode\n  -h --help        This page\n  -n --no-color    Disable color output\nEOF\n\n## Boilerplate files\n# shellcheck source=src/runtime/bootstrap/lib/main.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/main.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/ini_val.sh\"\n\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/install_flux.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/install_flux.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/install_helm_operator.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/install_helm_operator.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/render_azure_service_operator.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/render_azure_service_operator.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/create_cluster_folder_git.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/create_cluster_folder_git.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/render_and_copy_rbac.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/render_and_copy_rbac.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/render_and_copy_cert_manager.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/render_and_copy_cert_manager.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/upsert_namespace.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/upsert_namespace.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/get_flux_ssh_keys.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/get_flux_ssh_keys.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/upload_ssh_keys.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/upload_ssh_keys.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/upload_cluster_management_file.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/upload_cluster_management_file.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/create_cluster_management_file.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/create_cluster_management_file.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/upsert_arc.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/upsert_arc.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/configure_storage_classes.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/configure_storage_classes.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/configure_gatekeeper.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/configure_gatekeeper.sh\"\n\n\n\n### Validation. Error out if the things required for your script are not present\n##############################################################################\n\n[[ \"${arg_f:-}\" ]]     || help      \"Setting a filename with -f or --file is required\"\n[[ \"${LOG_LEVEL:-}\" ]] || emergency \"Cannot continue without LOG_LEVEL. \"\n\nconfig_file=\"$arg_f\"\ninfo \"Reading $config_file for configuration\"\n\njumphost_user=$(get_from_ini_or_error \"$config_file\" c12:generated.jumphost_user)\njumphost_ip=$(get_from_ini_or_error \"$config_file\" c12:generated.jumphost_ip)\njumphost_ssh_key_location=$(get_from_ini_or_error \"$config_file\" c12:generated.jumphost_ssh_key_location)\ninfo \"Creating SSH Tunnel\"\nssh -oStrictHostKeyChecking=no \"$jumphost_user\"@\"$jumphost_ip\" -i \"$jumphost_ssh_key_location\" -L 1234:127.0.0.1:8888 -C -N &\n\n# These env vars are used by helm / kubectl to talk to the K8S API server via the jumphost\n# shellcheck disable=SC2034\nexport HTTPS_PROXY=http://127.0.0.1:1234\n# shellcheck disable=SC2034\nexport https_proxy=http://127.0.0.1:1234\n\nprefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\nnamespace=\"$prefix-c12-system\"\nflux_release_name=\"$namespace-flux\"\ngit_cluster_state=$(get_cluster_state_repo)\ncluster_name=$(get_from_ini_or_error \"$config_file\" c12:generated.aks_name)\nrg=$(get_from_ini_or_error \"$config_file\" terraform:generated.container-rg)\ndisk_encryption_set_id=$(ini_val \"$config_file\" c12:generated.disk_encryption_set_id)\n\naz aks get-credentials --resource-group \"$rg\" --name \"$cluster_name\" --admin --overwrite-existing\n\ndebug \"namespace:$namespace flux_release_name:$flux_release_name git_cluster_state:$git_cluster_state\"\n\n\n# First step is create the folder in the cluster-state and add all the required manifests\n# We keep the local folder of the cluster for installing rbac later.\ncluster_state_folder=$(create_folder_for_state_repo \"$git_cluster_state\" \"$cluster_name\") \nrender_and_copy_rbac \"$cluster_state_folder\"\n\n#Create the storage classes with encrypted disk sets and delete any other\nconfigure_storage_classes \"$disk_encryption_set_id\"\n\nconfigure_gatekeeper \"$cluster_state_folder\"\n\n# Install the cert-manager components and CRDs\nacr_name=$(get_from_ini_or_error \"$config_file\" c12:generated.regional_acr_name)\nrender_and_copy_cert_manager \"$cluster_state_folder\"\nimport_image \"$acr_name\" \"quay.io/jetstack/cert-manager-cainjector:v0.14.3\"\nimport_image \"$acr_name\" \"quay.io/jetstack/cert-manager-controller:v0.14.3\"\nimport_image \"$acr_name\" \"quay.io/jetstack/cert-manager-webhook:v0.14.3\"\n\n\n#  Renders the azure-service-operator's HelmRelease\n#  Generates sufficient Service Principal for ASO\n#  Transfers required Images to Cluster ACR\nrender_azure_service_operator \"$cluster_state_folder\"\n\n\n# if the feature flag for Azure Arc is `true` will on board with ARC Config Agent.\n# shellcheck disable=SC2086\nif [[ \"$(ini_val $config_file azure.arc-support)\" == \"true\" ]]; then\n  # Install Azure Arc and connect to ARC Config Agent and obtain Flux SSH key\n  info \"Connect cluster to Azure ARC Config Agent\"\n  upsert_arc\n  info \"Cluster Successfully Connect Azure ARC Config Agent\"\n  # Install helm operator and flux\n  info \"Installing HelmOperator in the cluster\"\n  install_helm_operator\n  # Upload the SSH keys generated by flux using terraform into the state repository so the cluster\n  info \"Granting permissions to flux in cluster-state repository\"\n  upload_ssh_keys\nelse\n  # Install helm operator and flux\n  info \"Installing HelmOperator and Flux in the cluster\"\n  upsert_namespace \"$namespace\"\n  install_helm_operator\n  install_flux\n\n  # Upload the SSH keys generated by flux using terraform into the state repository so the cluster\n  # can perform the pull\n  info \"Granting permissions to flux in cluster-state repository\"\n  get_flux_ssh_keys \"$namespace\" \"$flux_release_name\"\n  upload_ssh_keys\nfi\n\ncluster_file_path=$(generate_cluster_management_file)\ncluster_namagement_git=$(get_cluster_management_repo)\nupload_cluster_management_file \"$cluster_namagement_git\" \"$cluster_file_path\" \"$cluster_name\"\n\n\n\ninfo \"Cluster successfully onboarded\"\n\nfor job in $(jobs -l \"%ssh\"  | cut -d' ' -f 2)\ndo\n    kill \"$job\"\ndone\nunset HTTPS_PROXY\nunset https_proxy\n", "num_lines": 169}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# This functions iterates over the rbac folder, and for each file found\n# It gets from the .ini file the ${prefix}_group_id.  ${prefix} being the file name in rbac\n# then renders the file and copies it to the cluster folder, defined by Arg1\n# then it commits git and pushes the changes.\n# Arg1 the cluster-state folder where the rbac files render will be added.\nfunction render_and_copy_cert_manager {\n\n    if [[ $# -ne 1 ]];\n    then\n        error \"Expecting 1 arguments for this function\"\n        return 1\n    fi\n\n    cluster_folder=\"$1\"\n    info \"Adding cert-manager files to $cluster_folder\"\n\n    info \"Processing rendering cert-manager-template.yaml \"\n    acr=$(ini_val \"$config_file\" c12:generated.regional_acr_name )\n    acr=$acr envsubst < \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/manifests/cert-manager-template.yaml\" > \"$cluster_folder/cert-manager.yaml\"\n\n\n    pushd \"$cluster_folder\" >/dev/null || return 1\n    cd ..\n\n    info \"Commiting settings for cert-manager\"\n    git add .\n    git commit -m \"Onboarding: Add cert-manager\" || true\n    git push\n    popd >/dev/null || return 1\n}", "num_lines": 39}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# This functions iterates over the rbac folder, and for each file found\n# It gets from the .ini file the ${prefix}_group_id.  ${prefix} being the file name in rbac\n# then renders the file and copies it to the cluster folder, defined by Arg1\n# then it commits git and pushes the changes.\n# Arg1 the cluster-state folder where the rbac files render will be added.\nfunction render_and_copy_rbac {\n\n    if [[ $# -ne 1 ]];\n    then\n        error \"Expecting 1 arguments for this function\"\n        return 1\n    fi\n\n    cluster_folder=\"$1\"\n    info \"Adding RBAC files to $cluster_folder\"\n    \n    rbac_folder=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/manifests/rbac/*\"\n    for f in $rbac_folder\n    do\n        info \"Processing $f \"\n        local_file_name=\"$(basename -- \"${f}\")\"\n        role_name=${local_file_name%.*}\n        groupid=$(ini_val \"$config_file\" c12:generated.\"${role_name}\"_group_id )\n        groupObjectId=$groupid envsubst < \"$f\" > \"$cluster_folder\"/\"$local_file_name\"\n    done\n\n    pushd \"$cluster_folder\" >/dev/null || return 1    \n  \n    cd ..\n    info \"Commiting rbac settings for rbac\"\n    git add .\n    git commit -m \"Onboarding: Add rbac files\" || true\n    git push \n    popd >/dev/null || return 1\n}", "num_lines": 44}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n\n# New azure service principal required with \"Contributor\" roles\n# for the Azure Service Operator to have sufficient right to create Azure Resources\nfunction generate_aso_service_principal {\n\n    _timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n    _subscription_id=$(ini_val \"$config_file\" azure.subscription)\n    _cluster_name=$(get_from_ini_or_error \"$config_file\" \"c12:generated.aks_name\")\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n    _key=\"azure/${_cluster_name}_aks_azure_service_operator_service_principal.tfstate\"\n\n    pushd  \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/terraform/azure_service_operator_service_principal\" || return 1    \n\n    terraform init \\\n       -backend-config \"storage_account_name=$_storage_account_name\" \\\n       -backend-config \"container_name=$_container_name\" \\\n       -backend-config \"resource_group_name=$_container_rg\" \\\n       -backend-config \"key=$_key\" \\\n       -backend-config \"subscription_id=$_subscription_id\" \\\n       -reconfigure\n\n    terraform workspace select default\n\n    terraform plan \\\n         -lock=true \\\n         -out \"${_timestamp}.tfplan\" \\\n         -var \"prefix=$_prefix\" \\\n         -var \"cluster_name=$_cluster_name\" \\\n         -var \"subscription_id=$_subscription_id\"\n\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    _azure_service_operator_service_principal_id=$(terraform output id)\n    _azure_service_operator_service_principal_application_id=$(terraform output application_id)\n    _azure_service_operator_service_principal_password=$(terraform output password)\n\n    ini_val \"$config_file\" c12:generated.azure_service_operator_service_principal_id \"$_azure_service_operator_service_principal_id\"\n    ini_val \"$config_file\" c12:generated.azure_service_operator_service_principal_application_id \"$_azure_service_operator_service_principal_application_id\"\n    ini_val \"$config_file\" c12:generated.azure_service_operator_service_principal_password \"$_azure_service_operator_service_principal_password\"\n\n    popd || return 1\n}\n\n# Renders HelmRelease config for  azure-service-operator\nfunction render_and_copy_azure_service_operator {\n\n    # Set the cloud environment, possible values include: AzurePublicCloud, AzureUSGovernmentCloud, AzureChinaCloud, AzureGermanCloud\n    AZURE_CLOUD_ENV=\"AzurePublicCloud\"\n\n    info \"Adding azure-service-operator files to $cluster_folder\"\n\n    info \"Processing rendering azure-service-operator-values.yaml\"\n    subscription=$(ini_val \"$config_file\" azure.subscription)\n    tenantId=$(az account list -o json | jq -r --arg SUB_ID \"${subscription}\" '.[] | select( .id == $SUB_ID ) | .tenantId')\n    service_principal_application_id=$(ini_val \"$config_file\" c12:generated.azure_service_operator_service_principal_application_id )\n    service_principal_password=$(ini_val \"$config_file\" c12:generated.azure_service_operator_service_principal_password )\n    acr=$(ini_val \"$config_file\" c12:generated.regional_acr_name )\n    \n    # Base64 encoding required varables.\n    acr=$acr \\\n    azurePublicCloud=\"$(echo -ne \"${AZURE_CLOUD_ENV}\" | base64)\" \\\n    subscription=\"$(echo -ne \"${subscription}\" | base64)\" \\\n    service_principal_application_id=\"$(echo -ne \"${service_principal_application_id}\" | base64)\" \\\n    service_principal_password=\"$(echo -ne \"${service_principal_password}\"  | base64)\" \\\n    tenantId=\"$(echo -ne \"${tenantId}\" | base64)\" \\\n    envsubst < \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/manifests/azure-service-operator-template.yaml\" > \"$cluster_folder/azure-service-operator.yaml\"\n\n    pushd \"$cluster_folder\" >/dev/null || return 1\n    cd ..\n\n    info \"Commiting settings for azure-service-operator-values\"\n    git add .\n    git commit -m \"Onboarding: Add azure-service-operator-values\" || true\n    git push\n    popd >/dev/null || return 1\n}\n\n\nfunction render_azure_service_operator {\n\n    if [[ $# -ne 1 ]];\n    then\n        error \"Expecting 1 arguments for this function\"\n        return 1\n    fi\n    cluster_folder=\"$1\"\n\n    info \"Generate Service Principal for azure-service-operator\"\n    generate_aso_service_principal\n    info \"Service Principal Generated\"\n\n\n    render_and_copy_azure_service_operator\n\n\n    DEF_ASO_CHART_REPOSITORY=\"https://raw.githubusercontent.com/Azure/azure-service-operator/master/charts\"\n    DEF_ASO_HELM_CHART=\"azure-service-operator\"\n    DEF_ASO_HELM_CHART_VERSION=\"0.1.0\"\n    acr_name=$(ini_val \"$config_file\" c12:generated.regional_acr_name )\n\n    import_chart_acr \"${DEF_ASO_CHART_REPOSITORY}\" \"${DEF_ASO_HELM_CHART}\" \"${DEF_ASO_HELM_CHART_VERSION}\" \"${acr_name}\"\n    \n    info \"Importing azure-service-operator image into cluster ACR\"\n    import_image \"$acr_name\" \"mcr.microsoft.com/k8s/azure-service-operator:latest\"\n    info \"Importing azure-service-operator image into cluster ACR\"\n\n}\n\n", "num_lines": 122}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n\n# This function checkouts the repository and adds the cluster folder to the root of the repository\n# Arg1 the url of the cluster mangement state repository\n# Arg2 the path of the cluster file to be uploaded to the repository\n# Arg3 the cluster name, for commit message purposes\nfunction upload_cluster_management_file() {\n\n\n    if [[ $# -ne 3 ]];\n    then\n        error \"upload_cluster_management_file 2 arguments for this function\"\n        return 1\n    fi\n\n    info \"Creating folder in cluster-state repository for cluster\"\n\n    git_url=\"$1\"\n    cluster_file_path=\"$2\"\n    cluster_name=\"$3\"\n    tmp_dir=\"$(mktemp -d)\"\n\n    info \"Clonning cluster state repo ($git_url) into $tmp_dir\"\n    git clone \"$git_url\" \"$tmp_dir\"\n\n    pushd \"$tmp_dir\" >/dev/null || return 2\n\n    cp \"$cluster_file_path\" \"$tmp_dir\"\n\n    git add \".\"\n    git diff-index --quiet HEAD || git commit -m \"Onboarding: Add $cluster_name\" >/dev/null\n\n    info \"Commiting folder to git\"\n    git push\n    popd >/dev/null || return 2\n    rm -rf \"$tmp_dir\"\n    return 0\n}", "num_lines": 46}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/tools.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/tools.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\nfunction upload_ssh_keys() {\n\n    _timestamp=\"$(date \"+%Y:%m:%d-%H:%M\")\"\n    _cluster_name=$(get_from_ini_or_error \"$config_file\" \"c12:generated.aks_name\")\n    _storage_account_name=$(ini_val \"$config_file\" terraform:generated.storage-account-name)\n    _container_name=$(ini_val \"$config_file\" terraform:generated.container-name)\n    _container_rg=$(ini_val \"$config_file\" terraform:generated.container-rg)\n    _key=\"azure/aks.fluxadmin${_cluster_name}\"\n    _access_token=$(ini_val \"$config_file\" github.access-token)\n    _org=$(ini_val \"$config_file\" github.org)\n    _ssh_key_file_path=$(ini_val \"$config_file\" c12:generated.flux_ssh_key)\n    _prefix=$(ini_val \"$config_file\" c12.prefix)\n\n    pushd  \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd .. && pwd)/terraform/deploy_flux_key_github\" || return 1    \n    terraform init \\\n       -backend-config \"storage_account_name=$_storage_account_name\" \\\n       -backend-config \"container_name=$_container_name\" \\\n       -backend-config \"resource_group_name=$_container_rg\" \\\n       -backend-config \"key=$_key\" \\\n       -reconfigure\n\n    terraform workspace select default\n\n    terraform plan \\\n         -lock=true \\\n         -out \"${_timestamp}.tfplan\" \\\n         -var \"prefix=$_prefix\"\\\n         -var \"access_token=$_access_token\" \\\n         -var \"org=$_org\" \\\n         -var \"ssh_pub_key=$_ssh_key_file_path\" \\\n         -var \"cluster_name=$_cluster_name\"\n\n\n    terraform apply \"${_timestamp}.tfplan\"\n\n    popd || return 1\n}", "num_lines": 49}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\nARC_CLUSTER_CONFIG_NAME=\"cluster-config\"\nARC_CLUSTER_TYPE=\"managedclusters\"\n\nDEF_HELM_OPERATOR_CHART_REPOSITORY=\"https://charts.fluxcd.io\"\nDEF_FLUX_HELM_CHART=\"flux\"\nDEF_FLUX_HELM_CHART_VERSION=\"1.3.0\"\nDEF_FLUX_IMAGE=\"fluxcd/flux\"\nDEF_FLUX_IMAGE_TAG=\"1.19.0\"\n\n\n# Allows time for  Arc Config Agent to fully initialize and generate flux ssh key\nfunction monitor_arc_setup() {\n\n    info \"Polling for the status of of Azure Arc Config Agent to fully initialize\"\n    conclusion=\"temp\"\n    while [[ \"$conclusion\" = \"temp\" ]]\n    do\n\t    # shellcheck disable=SC2154\n        result=$(az k8sconfiguration show --resource-group \"$rg\" \\\n\t\t\t\t\t--cluster-name \"$cluster_name\" \\\n\t\t\t\t\t--name \"$ARC_CLUSTER_CONFIG_NAME\" \\\n\t\t\t\t\t--cluster-type \"$ARC_CLUSTER_TYPE\" \\\n\t\t\t\t\t-o json | jq -r '.complianceStatus.complianceState' | tail -1)        \n        info \"Arc Config Agent initialization is $result\"\n        if [[ \"$result\" == \"Installed\" ]]\n        then\n            conclusion=$result\n        else\n            sleep 10\n        fi\n    done\n    info \"Arc Config Agent initialization is now $conclusion\" \n\taz k8sconfiguration show --resource-group \"$rg\" \\\n\t\t\t--cluster-name \"$cluster_name\" \\\n\t\t\t--name \"$ARC_CLUSTER_CONFIG_NAME\" \\\n\t\t\t--cluster-type \"$ARC_CLUSTER_TYPE\" \\\n\t\t\t-o json \n}\n\n\nfunction install_arc_config_agent() {\n\n    _location=$(ini_val \"$config_file\" azure.location)\n    _subscription=$(ini_val \"$config_file\" azure.subscription)\n    _tenantId=$(az account list -o json | jq -r --arg SUB_ID \"${_subscription}\" '.[] | select( .id == $SUB_ID ) | .tenantId')\n\t_prefix=$(get_from_ini_or_error \"$config_file\" c12.prefix)\n\tcluster_state_repo=\"$(get_cluster_state_repo)\"\n\t\n\t# Installing the Azure ARC Kubernetes configuration agent\n\thelm repo add azurearcfork8s https://azurearcfork8s.azurecr.io/helm/v1/repo\n\n\thelm upgrade azure-k8s-config azurearcfork8s/azure-k8s-config --install \\\n\t--set global.subscriptionId=\"$_subscription\",global.resourceGroupName=\"$rg\" \\\n\t--set global.resourceName=\"$cluster_name\",global.location=\"$_location\" \\\n\t--set global.tenantId=\"$_tenantId\"\n\n\n\taz k8sconfiguration create --resource-group \"$rg\" \\\n\t\t\t--cluster-name \"$cluster_name\" \\\n\t\t\t--cluster-type managedclusters \\\n\t\t\t--name cluster-config \\\n\t\t\t--operator-instance-name \"${_prefix}-c12-system\" \\\n\t\t\t--operator-namespace \"${_prefix}-c12-system\" \\\n\t\t\t--enable-helm-operator false \\\n    \t\t--repository-url \"${cluster_state_repo}\" \\\n\t\t\t--operator-params \"--git-readonly --git-path ${cluster_name} --git-poll-interval=30s --registry-disable-scanning\" \\\n\t\t\t--scope cluster\n\n}\n\n\n# Optains Flux SSH key from k8sconfiguration expose command and saves in temp file and c12.ini for later uses.\nfunction get_flux_key_from_arc() {\n\t\n\tssh_key=$(az k8sconfiguration show --resource-group \"$rg\" \\\n\t\t\t--cluster-name \"$cluster_name\" \\\n\t\t\t--name \"$ARC_CLUSTER_CONFIG_NAME\" \\\n\t\t\t--cluster-type \"$ARC_CLUSTER_TYPE\" \\\n\t\t\t--query 'repositoryPublicKey' -o json | jq -r '.')\n \n    ssh_key_path=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/flux_id_rsa.pub\"\n\n    echo \"$ssh_key\" > \"$ssh_key_path\"\n\n    ini_val \"$config_file\" c12:generated.flux_ssh_key \"$ssh_key_path\"\n}\n\nfunction import_app_flux_to_cluster_acr() {\n\n    acr_name=$(get_from_ini_or_error \"$config_file\" c12:generated.regional_acr_name)\n\t\n    import_image \"${acr_name}\" \"${DEF_FLUX_IMAGE}\":\"${DEF_FLUX_IMAGE_TAG}\"\n\timport_chart_acr \"${DEF_HELM_OPERATOR_CHART_REPOSITORY}\" \"${DEF_FLUX_HELM_CHART}\" \"${DEF_FLUX_HELM_CHART_VERSION}\" \"${acr_name}\"\n}\n\n# Creates Arc nessary Dependencies in cluster and connects cluster to Azure\nfunction upsert_arc() {\n\t# import flux image into cluster ACR, nessary for Application flux instances \n\timport_app_flux_to_cluster_acr\n\n\t# install ARC Agent helm chart and provision.\n\tinstall_arc_config_agent\n\n\t# Wait for ARC Agent to fully initialize before requesting Flux SSH key.\n\tmonitor_arc_setup\n\tget_flux_key_from_arc\n}", "num_lines": 116}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# shellcheck source=src/runtime/bootstrap/lib/logging.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../.. && pwd)/bootstrap/lib/logging.sh\"\n\n# shellcheck source=src/runtime/cluster-on-boarding/scripts/helpers.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/helpers.sh\"\n\n# Creates or updates a kubernetes namespace\nfunction upsert_namespace() {\n\n\tif [ -z \"$1\" ] \n\tthen\n\t\terror \"Missing input parameters\"\n\t\texit 1\n\tfi\n\t\n\tinfo \"creating namespace $1\"\n\tkubectl create namespace \"$1\" --dry-run=client -o yaml  | kubectl apply -f -\n}", "num_lines": 21}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\nTOOLS_PATH=\"/app\"\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/git-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/git-utils.sh\"\n\nfunction clone-all-repos-actions() {\n\n    set -euo pipefail\n\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local _org=\"$GITHUB_REPOSITORY_OWNER\"\n    local _prefix=\"$PREFIX\"\n    local _pat_username=\"$PAT_USERNAME\"\n    local _pat_password=\"$PAT_TOKEN\"\n    local _checkout_path=\"$GITHUB_WORKSPACE/cloned_repos\"\n\n    APP_LIST_JSON=$(\"${TOOLS_PATH}\"/appsourceextractor -a \"${GITHUB_WORKSPACE}\")\n    APP_LIST=$(echo \"$APP_LIST_JSON\" | tail -1 | jq -r '.[]')\n    echo \"Apps found: $APP_LIST\"\n\n    mkdir -p \"$_checkout_path\"\n    pushd \"$_checkout_path\" || exit 3\n    \n    for app in $APP_LIST\n    do\n        clone-state-only-repo \"$_org\" \"$_prefix\" \"$_pat_username\" \"$_pat_password\" \"$app\"     \n    done\n    \n\n    management_repos=\"archetype-management cluster-state cluster-management\"\n    # Iterate the string variable using for loop\n    for repo in $management_repos; do\n        repo_full_name=\"${PREFIX}-${repo}\"\n        clone-repo  \"$repo_full_name\" \"$_pat_username\" \"$_pat_password\" \"$_org\"\n    done\n    popd || exit 3\n\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    clone-all-repos-actions\nfi", "num_lines": 48}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\nfunction commit-all-repos() {\n    \n   # This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local _checkout_path=\"$GITHUB_WORKSPACE/cloned_repos\"\n    local _git_email=\"$GIT_EMAIL\"\n    local _git_name=\"$GIT_NAME\"\n\n    git config --global user.email \"$_git_email\"\n    git config --global user.name \"$_git_name\"\n\n    temp_dir=$(mktemp -d)\n\n    mv \"$_checkout_path\" \"$temp_dir\"\n\n    pushd \"$temp_dir/cloned_repos\" || exit 2\n    while IFS= read -r d; do \n        commit-repo \"$d\"\n    done < <(find -- * -maxdepth 0 -type d)\n    popd || exit 2\n\n    mv \"$temp_dir/cloned_repos\" \"$GITHUB_WORKSPACE\"\n\n}\n\nfunction commit-repo() {\n    local _repo=\"$1\"\n\n    echo \"Commiting $_repo\"\n    pushd \"$_repo\" || exit 2\n    if [ -z \"$(git status --porcelain)\" ]; then \n        # Working directory clean\n        echo \"No changes in $_repo\"\n    else \n        # Uncommitted changes\n        git add -A;\n        git commit -m \"application-management ci\"\n        git push    \n    fi\n    popd || exit 2\n\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    commit-all-repos\nfi", "num_lines": 54}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -euo pipefail\n# This script creates / updates repos. The $_repos param should be *all* repos needed in the system, not just new ones needs.\n\n_prefix=\"$1\"\n_application=\"$2\"\n\nfor suffix in \"state\" \"src\"; do\n    cd \"$_prefix-$_application-$suffix\"\n    git add -A\n    git diff-index --quiet HEAD || git commit -a -m \"C12 CI Update\"\n    git push\n    cd ..\ndone\n", "num_lines": 15}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/terraform-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/terraform-utils.sh\"\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\n\nfunction create-aad-groups-actions() {\n    set -euo pipefail\n    pushd .c12/components/identity-providers/aad\n\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local ORG=\"$GITHUB_REPOSITORY_OWNER\"\n    _application_names=$(get-application-list-json)\n\n\n    _subscription_id=\"$ARM_SUBSCRIPTION_ID\"\n    _prefix=\"$PREFIX\" \n    _applications=\"$_application_names\"\n    _timestamp=\"$(date \"+%Y-%m-%d_%H-%M\")\"\n\n    terraform_init_gh\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"subscription_id=$_subscription_id\" \\\n        -var \"prefix=$_prefix\" \\\n        -var \"applications=$_applications\"\n\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        terraform apply \"${_timestamp}.tfplan\"\n    fi\n    popd\n}\nfunction create-github-teams-actions() {\n    set -euo pipefail\n    pushd .c12/components/infrastructure/teams/github-enterprise-cloud\n\n    # avoid getting (local-exec): /bin/sh: : Permission denied on agent\n    chmod 777 ./delete-teams.sh\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local ORG=\"$GITHUB_REPOSITORY_OWNER\"\n    _application_names=$(get-application-list-json)\n\n    _subscription_id=\"$ARM_SUBSCRIPTION_ID\"\n    _prefix=\"$PREFIX\" \n    _applications=\"$_application_names\"\n    _timestamp=\"$(date \"+%Y-%m-%d_%H-%M\")\"\n    _access_token=\"$PAT_TOKEN\"\n    _org=\"$ORG\"\n\n    terraform_init_gh\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"access_token=$_access_token\" \\\n        -var \"org=$_org\" \\\n        -var \"access_token=$_access_token\" \\\n        -var \"subscription_id=$_subscription_id\" \\\n        -var \"prefix=$_prefix\" \\\n        -var \"applications=$_applications\"\n\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        terraform apply \"${_timestamp}.tfplan\"\n    fi\n\n    popd\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    create-aad-groups-actions\n\n    # running into a fauilure in e2e where planing will fail as AAD Groups not created yet\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        create-github-teams-actions\n    fi\nfi", "num_lines": 88}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n\n# This function will copy a container from a source ACR to a destination ACR\nfunction copy_container_acr () {\n\n    # Test if exactly four arguments are passed into the function\n    if [[ $# -ne 4 ]];\n    then\n        echo \"Error: Expecting 4 arguments for this function\"\n        exit 1\n    fi\n\n    # Validate existence of environment variables\n\tif [ -z \"$SP_APP_ID\" ] \n\tthen\n\t\techo \"Error: SP_APP_ID is not set\"\n\t\texit 1\n\tfi\n\n    \tif [ -z \"$SP_APP_PASSWORD\" ] \n\tthen\n\t\techo \"Error: SP_APP_PASSWORD is not set\"\n\t\texit 1\n\tfi\n\n    # Create variables for arguments\n    ACR_SRC=\"$1\"\n    ACR_DEST=\"$2\"\n    ACR_IMAGE_NAME=\"$3\"\n    ACR_IMAGE_DIGEST=\"$4\"\n\n    # Log in to source ACR with service principal credentials\n    echo -n \"$SP_PASSWORD\" | sudo docker login \"$ACR_SRC\" --username \"$SP_APP_ID\" --password-stdin\n\n    # Pull the container from the source ACR referencing the image digest\n    sudo docker pull \"$ACR_SRC\"/\"$ACR_IMAGE_NAME\"@\"$ACR_IMAGE_DIGEST\"\n\n    sudo docker logout \"$ACR_SRC\"\n\n    # Get the local image ID using the digest\n    IMAGE_ID=$(sudo docker images --format \"{{.ID}}\" --filter=reference=\"$ACR_SRC\"/\"$ACR_IMAGE_NAME\"@\"$ACR_IMAGE_DIGEST\")\n\n    # Tag the pulled image with the destination registry\n    sudo docker tag \"$IMAGE_ID\" \"$ACR_DEST\"/\"$ACR_IMAGE_NAME\"\n\n    # Log in to the destination ACR with service principal credentials\n    echo -n \"$SP_PASSWORD\" | sudo docker login \"$ACR_DEST\" --username \"$SP_APP_ID\" --password-stdin\n\n    # Push the newly tagged image to the destination registry\n    sudo docker push \"$ACR_DEST\"/\"$ACR_IMAGE_NAME\"\n\n    sudo docker logout \"$ACR_DEST\"\n\n    # Remove the local image (needs a force since there are two)\n    sudo docker image rm \"$IMAGE_ID\" -f\n\n}\n", "num_lines": 60}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\nfunction generate-app-helm-releases() {\n\n    # This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local _prefix=\"$PREFIX\"\n    local _app_definitions_path=\"$GITHUB_WORKSPACE\"\n    local _checkout_path=\"$GITHUB_WORKSPACE/cloned_repos\"\n    local _cluster_definitions_path=\"$_checkout_path/$_prefix-cluster-management\"\n    local _org=\"$GITHUB_REPOSITORY_OWNER\"\n\n    _application_names=$(get-application-list)\n    echo \"Applications found '$_application_names'\"\n\n    if [[ \"$_application_names\" == \"\" ]] \n    then\n        echo \"No applications found, nothing done\"\n        return 0\n    fi\n   \n    for app in \"${_application_names[@]}\"; do\n        _app_state_repo_path=\"$_checkout_path/$_prefix-$app-state\"\n        echo \"Generating Helm Release, Namespace for $app, using path: $_app_state_repo_path\"\n        \"$TOOLS_PATH\"/apprendering -a \"$_app_definitions_path\"/\"$app\".yaml -c \"$_cluster_definitions_path\" -p \"$_prefix\" -d \"$_app_state_repo_path\" -o \"$_org\"\n    done\n\n    tree \"$_checkout_path\"\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    generate-app-helm-releases\nfi", "num_lines": 39}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\n\nfunction generate-application-admin-manifests() {\n\n    # This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local _prefix=\"$PREFIX\"\n    local _app_definitions_path=\"$GITHUB_WORKSPACE\"\n    local _checkout_path=\"$GITHUB_WORKSPACE/cloned_repos\"\n    local _cluster_definitions_path=\"$_checkout_path/$_prefix-cluster-management\"\n    local _org=\"$GITHUB_REPOSITORY_OWNER\"\n    local _cluster_state_folder=\"$_checkout_path/$_prefix-cluster-state\"\n    # shellcheck disable=SC2154\n    _application_names=\"$application_secret_mappings\"\n\n    for app_key in $(echo \"${_application_names}\" | jq -r '.[] | @base64'); do\n        app=$( echo \"${app_key}\" | base64 --decode |  jq -r '.name')\n        ssh_key=$( echo \"${app_key}\" | base64 --decode |  jq -r '.ssh_key')\n\n        _app_state_repo_path=\"$_checkout_path/$_prefix-$app-state\"\n        echo \"Generating Helm Release, Namespace for $app, using path: $_app_state_repo_path\"\n        \"$TOOLS_PATH\"/adminc12render -a \"$_app_definitions_path\"/\"$app\".yaml -c \"$_cluster_definitions_path\" -o \"$_org\" -p \"$_prefix\" -d \"$_cluster_state_folder\" -s \"$ssh_key\"\n    done\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    generate-application-admin-manifests\nfi\n", "num_lines": 36}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/terraform-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/terraform-utils.sh\"\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\n\nfunction generate-clone-repos-actions() {\n\n    pushd .c12/components/infrastructure/repos/github-enterprise-cloud\n\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local ORG=\"$GITHUB_REPOSITORY_OWNER\"\n\n    _application_names=$(get-application-list-json)\n    _access_token=\"$PAT_TOKEN\"\n    _org=\"$ORG\"\n    _prefix=\"$PREFIX\" \n    _applications=\"$_application_names\"\n    _timestamp=\"$(date \"+%Y-%m-%d_%H-%M\")\"\n\n    terraform_init_gh\n\n    terraform plan \\\n    -lock=true \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"org=$_org\" \\\n    -var \"prefix=$_prefix\" \\\n    -var \"applications=$_applications\"\n\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        terraform apply \"${_timestamp}.tfplan\"\n    fi\n    popd\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    generate-clone-repos-actions\nfi", "num_lines": 47}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/terraform-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/terraform-utils.sh\"\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\nfunction generate-deploy-keys-actions() {\n    pushd .c12/components/infrastructure/repos/deploy-keys\n\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local ORG=\"$GITHUB_REPOSITORY_OWNER\"\n    _application_names=$(get-application-list-json)\n\n    echo \"Applications found: $_application_names\"\n\n    _subscription_id=\"$ARM_SUBSCRIPTION_ID\"\n    _prefix=\"$PREFIX\" \n    _applications=\"$_application_names\"\n    _access_token=\"$PAT_TOKEN\"\n    _org=\"$ORG\"\n\n    _timestamp=\"$(date \"+%Y-%m-%d_%H-%M\")\"\n\n    terraform_init_gh\n\n    terraform plan \\\n        -lock=true \\\n        -out \"${_timestamp}.tfplan\" \\\n        -var \"subscription_id=$_subscription_id\" \\\n        -var \"org=$_org\" \\\n        -var \"access_token=$_access_token\" \\\n        -var \"prefix=$_prefix\" \\\n        -var \"applications=$_applications\"\n\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        terraform apply \"${_timestamp}.tfplan\"\n\n        # get generated keys from Terraform to deploy to app-states.\n        _app_keys=$( terraform output -json | jq -c '.\"application-secret-mappings\".value' )\n        echo \"_app_keys: $_app_keys\" \n        # sets as ENV var for next task in pipeline\n        echo \"::set-env name=application_secret_mappings::$_app_keys\"\n    fi\n    popd\n\n}\n\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    generate-deploy-keys-actions\nfi", "num_lines": 58}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nTOOLS_PATH=\"/app\"\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/terraform-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/terraform-utils.sh\"\n\n\nfunction generate-pipeline-secrets-actions() {\n\n    set -euo pipefail\n    pushd .c12/components/infrastructure/azure/aad_credentials_actions/\n    chmod 777 ./post_grant_request.sh\n\n    az login --service-principal -u \"$ARM_CLIENT_ID\" -p \"$ARM_CLIENT_SECRET\" -t \"$ARM_TENANT_ID\"\n\n    #This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local ORG=\"$GITHUB_REPOSITORY_OWNER\"\n\n    APP_LIST_JSON=$(\"${TOOLS_PATH}\"/appsourceextractor -a \"${GITHUB_WORKSPACE}\")\n    APP_LIST=$(echo \"$APP_LIST_JSON\" | tail -1 | jq -r '.[]')\n    echo \"Apps found: $APP_LIST\"\n\n\n    _access_token=\"$PAT_TOKEN\"\n    _access_token_username=\"$PAT_USERNAME\"\n    _org=\"$ORG\"\n    _prefix=\"$PREFIX\" \n    _subscription_id=\"$ARM_SUBSCRIPTION_ID\"\n    _ci_acr_name=\"$CI_ACR_NAME\"\n    _timestamp=\"$(date \"+%Y-%m-%d_%H-%M\")\"\n\n    _required_repos=\"archetype-management application-management\"\n\n\n    _repositories=\"[\"\n    for repo in $_required_repos\n    do\n         _repositories=$_repositories\"\\\"\"\"$_prefix\"-\"$repo\"\"\\\", \"\n    done\n    for repo in $APP_LIST\n    do\n         _repositories=$_repositories\"\\\"\"\"$_prefix\"-\"$repo\"'-src'\"\\\", \"\n    done\n    # Trim the last two charcaters\n    _repositories=\"${_repositories%??}\"\"]\"\n    echo \"Repositories: ${_repositories}\"\n    \n    terraform_init_gh\n\n\n    terraform plan \\\n    -lock=true \\\n    -out \"${_timestamp}.tfplan\" \\\n    -var \"subscription_id=$_subscription_id\" \\\n    -var \"prefix=$_prefix\"\\\n    -var \"org=$_org\" \\\n    -var \"access_token=$_access_token\" \\\n    -var \"access_token_username=$_access_token_username\" \\\n    -var \"repositories=$_repositories\"\\\n    -var \"ci_acr_name=$_ci_acr_name\"\n\n\n    if [ -z \"${TF_DRY_RUN+set}\" ];\n    then\n        terraform apply \"${_timestamp}.tfplan\"\n    fi\n    popd\n}\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    generate-pipeline-secrets-actions\nfi", "num_lines": 75}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\nfunction clone-repo() {\n    \n    local _repo_name    \n    local _pat_username\n\n    _repo_name=\"$1\"\n    _pat_username=\"$2\"\n    _pat_password=\"$3\"\n    _github_repository_owner=\"$4\"\n\n\n    git_url=\"https://${_pat_username}:${_pat_password}@github.com/$_github_repository_owner/$_repo_name.git\"\n\n    echo \"Cloning: $_repo_name\"    \n\n    git clone \"$git_url\"\n    pushd \"$_repo_name\" || exit 2\n    git config --local gc.auto 0\n    popd || exit 2\n}\n\nfunction clone-state-only-repo() {\n    set -euo pipefail\n    \n    local _org=\"$1\"\n    local _pat_username=\"$3\"\n    local _pat_password=\"$4\"\n    local _app_name=\"$5\"\n\n    # clone clone application state/source repos\n    echo \"Clonning state app with name: '$_app_name'\"\n    repo_name=\"${PREFIX}-${_app_name}-state\"\n    clone-repo  \"$repo_name\" \"$_pat_username\" \"$_pat_password\" \"$_org\"    \n}\n\nfunction clone-src-only-repo() {\n    set -euo pipefail\n    \n    local _org=\"$1\"\n    local _pat_username=\"$3\"\n    local _pat_password=\"$4\"\n    local _app_name=\"$5\"\n\n    # clone clone application state/source repos\n    echo \"Clonning src app with name: '$_app_name'\"\n    repo_name=\"${PREFIX}-${_app_name}-src\"\n    clone-repo  \"$repo_name\" \"$_pat_username\" \"$_pat_password\" \"$_org\"    \n}\n", "num_lines": 52}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/git-utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/git-utils.sh\"\n\nfunction push-content-to-application-src-repo() {\n\n    cp -R \"$_ci_solutions/.\" .        \n    sed \"s/%ORG%/$_org/; s/%REPO%/$app/; s/%PREFIX%/$_prefix/\" < \"$_ci_solutions/.github/CODEOWNERS\" > CODEOWNERS\n\n    git add -A\n    git diff-index --quiet HEAD || git commit -a -m \"Initial C12 Build Pipeline Import\"        \n    git push -u origin master\n    echo \"$_app_src_repo_path - CI Scripts Pushed Successfully\"\n}\n\nfunction hydrate-application-src-repos-actions() {\n\n    # This variables gets injected automatically by github actions docker type, declaring locals just for clarity of the code.\n    local _prefix=\"$PREFIX\"\n    local _org=\"$GITHUB_REPOSITORY_OWNER\"\n    local _checkout_path=\"$GITHUB_WORKSPACE/cloned_repos\"\n    local _ci_solutions=\"$GITHUB_WORKSPACE/.c12/components/ci-solutions\"\n    local _pat_username=\"$PAT_USERNAME\"\n    local _pat_password=\"$PAT_TOKEN\"\n    _application_names=$(get-application-list)\n    local _git_email=\"$GIT_EMAIL\"\n    local _git_name=\"$GIT_NAME\"\n\n   \n\n    if [[ \"$_application_names\" == \"\" ]] \n    then\n        echo \"No applications found, nothing done\"\n        return 0\n    fi\n\n    git config --global user.email \"$_git_email\"\n    git config --global user.name \"$_git_name\"\n\n    for app in \"${_application_names[@]}\"; do\n        cd \"$_checkout_path\"\n        clone-src-only-repo \"$_org\" \"$_prefix\" \"$_pat_username\" \"$_pat_password\" \"$app\"     \n        _app_src_repo_path=\"$_checkout_path/$_prefix-$app-src\"\n        if [ ! -f \"$_app_src_repo_path/.github/workflows/application-src-pipeline.yml\" ] || [ ! -f \"$_app_src_repo_path/CODEOWNERS\" ] || [ ! -d \"$_app_src_repo_path/.c12\" ]; then\n            echo \"$_app_src_repo_path - CI Scripts Missing\"\n            cd \"$_app_src_repo_path\"\n            push-content-to-application-src-repo\n            cd ..\n        fi\n    done\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    hydrate-application-src-repos-actions\nfi\n", "num_lines": 65}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\nfunction lint() {\n    echo \"lint app.yaml files\"\n  if [ \"$1\" ] && [ \"$2\" ]\n  then\n    docker run --mount src=\"$(pwd)\",target=/mount-dir,type=bind stelligent/config-lint \"$1\" \"$2\"\n    return 0\n  else\n    echo \"No args..\"\n    echo \"The program can also read files from a separate YAML file, and can scan these types of files:\"\n    return 1\n  fi\n}\n", "num_lines": 16}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\nfunction push-docker-images() {\n\n    # This variables are assigned by the workflow when running as an action, specified here as locals for clarity.\n    local _org=\"$GITHUB_REPOSITORY_OWNER\"\n    local _prefix=\"$PREFIX\"\n    local _appplication_definitions_path=\"$GITHUB_WORKSPACE\"\n    local _cluster_definitions_path=\"$GITHUB_WORKSPACE/cloned_repos/$_prefix-cluster-management\"\n    local _application_names\n    local _ci_acr_name=\"$CI_ACR_NAME\"\n    \n    _application_names=$(get-application-list)\n\n    _all_acr=$(az acr list -o json)\n    _ci_acr_login_url=$(az acr list | jq -r ' .[] | select(.name == \"'\"$_ci_acr_name\"'\") | .loginServer' | tr -d \"\\n\" )\n\n    for _app_name in $_application_names\n    do\n        echo \"Provisioning images for $_app_name\"\n        _app_definition_path=\"$_appplication_definitions_path\"/\"$_app_name\".yaml\n        for _deployment_group in $(yq -r '.spec.\"deployment-groups\"[].name' \"$_app_definition_path\")\n        do\n            echo \"Pushing images of $_deployment_group\"\n            _app_version=$(yq -r '.spec.\"deployment-groups\"[]  | select(.name==\"'\"$_deployment_group\"'\") | .application.version ' \"$_app_definition_path\")\n            if [[ \"$_app_version\" == \"null\" ]]\n            then\n                echo \"Skipping image push of app $_app_name for deployment group $_deployment_group application version is null\"\n            else\n                echo \"Version for deployment group is $_app_version\"\n                source_image=\"$_ci_acr_login_url\"/\"$_org\"/\"$_prefix\"-\"$_app_name\"-src:\"$_app_version\"\n                \n                for cluster in $(yq -r '.spec.\"deployment-groups\"[]  | select(.name==\"'\"$_deployment_group\"'\") | .clusters[].name ' \"$_app_definition_path\")\n                do\n                    echo \"Pushing $_app_name version: $_app_version to cluster: $cluster\"\n                    cluster_acr_registry_url=$(yq -r ' . | select(.metadata.name==\"'\"$cluster\"'\") | .spec.registry.docker.url' \"$_cluster_definitions_path\"/*.yaml | tr -d \"\\n\")\n                    cluster_acr_azure_name=$(echo \"$_all_acr\" | jq -r ' .[] | select( .loginServer == \"'\"$cluster_acr_registry_url\"'\") | .name' | tr -d \"\\n\" )\n                    echo \"destination: ${cluster_acr_azure_name} source image: ${source_image}\"\n                    az acr import --force -n \"${cluster_acr_azure_name}\" --source \"$source_image\"\n                done\n            fi            \n        done        \n    done\n}\n\nset -euo pipefail\n\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    az_cli_sp_login\n    push-docker-images\nfi", "num_lines": 56}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# shellcheck source=src/runtime/pipelines/application-management/scripts/utils.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)/utils.sh\"\n\n\n\n# Reads all app.yaml and all the clusters.yaml and pushes the helm charts used by apps\n# in the appropiate clusters, this version still does not support archetypes versions\nfunction push_helm_chart_to_clusters() {\n\n    # This variables are set by the github workflow when running the docker actions.\n    local _prefix=\"$PREFIX\"\n    local _helm_username=\"$IMAGE_REPOSITORY_USERNAME\"\n    local _helm_password=\"$IMAGE_REPOSITORY_PASSWORD\"\n    local _ci_acr_name=\"$CI_ACR_NAME\"\n\n    repos_root=\"$GITHUB_WORKSPACE\"\n    cluster_definitions_path=\"$repos_root/cloned_repos/$_prefix-cluster-management\"\n    appplication_definitions_path=\"$repos_root\"\n\n    APP_LIST_JSON=$(\"$TOOLS_PATH\"/chartextractor -a \"$appplication_definitions_path\" -c \"$cluster_definitions_path\")\n\n    #Login in the source repository\n    echo \"Adding ci helm repository to local helm\"\n    helm repo add ci_acr https://\"$_ci_acr_name\".azurecr.io/helm/v1/repo --username \"$_helm_username\" --password \"$_helm_password\"\n\n    # #Login in all required clusters helm registries, this is v2 OCI mode, hemloperator does not support it yet.\n    # export HELM_EXPERIMENTAL_OCI=1\n    # for clust in $(echo $JSON | jq -r 'flatten | unique | .[]')\n    # do\n    #     cluster_helm_repo_name=\"cluster_$clust\"\n    #     cluster_helm_repo=$(echo \"$clusters_json\" | jq -r ' . | select(.metadata.name==\"'\"$clust\"'\") | .spec.registry.helm.url' | tr -d \"\\n\")\n    #     echo \"Login in $cluster_helm_repo\"\n    #     helm repo add \"$cluster_helm_repo_name\"  \"$cluster_helm_repo\" --username \"$_helm_username\" --password \"$_helm_password\"\n    # done   \n    \n    #Create a temp repository for all the charts\n    local _temp_folder\n    _temp_folder=$(mktemp -d)\n\n    #Loop over all the different achetypes used by the clusters\n    for arch in $(echo \"$APP_LIST_JSON\" | jq -r \"keys | .[]\"); \n    do \n        echo \"Pulling chart $arch from ci helm repository\"\n        helm pull ci_acr/\"$arch\" --destination \"$_temp_folder\"\n        helm_chart_filename=$(find \"$_temp_folder\" -name \"$arch*.tgz\" | tr -d \"\\n\")\n\n        echo \"Looking for all clusters where $arch is required ($helm_chart_filename)\"\n\n        #Go to each cluster where the archetype is required.\n        for cluster in $(echo \"$APP_LIST_JSON\" | jq -r \".[\\\"$arch\\\"]? | .[]\"); \n        do\n            cluster_helm_repo=$(yq -r ' . | select(.metadata.name==\"'\"$cluster\"'\") | .spec.registry.helm.url' \"$cluster_definitions_path\"/*.yaml | tr -d \"\\n\")\n            echo \"Cluster helm repository url: $cluster_helm_repo\"\n            acr_name=$(echo \"$cluster_helm_repo\" | grep --color=never -o -P '(?<=https://).*(?=\\.azurecr\\.io/helm/v1/repo)' | tr -d \"\\n\")\n           \n            echo \"pushing $arch to $cluster (using az cli to acr:$acr_name)\"\n            az acr helm push -n \"$acr_name\" \"$helm_chart_filename\" --force\n        done\n    done\n}\n\nset -euo pipefail\n\nif [ -n \"${GITHUB_ACTIONS+set}\" ];\nthen\n    az_cli_sp_login\n    push_helm_chart_to_clusters\nfi", "num_lines": 71}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\n# fixes prefexes like E2E-AAD-Test -> e2eaadtestterraformstate which is needed to az storage names\n# and trims to the max 24 chars limit ie MOREthank24CharPrexfi -> morethank24charprexfiter\nfunction az_storage_normalize() {                                                                                                   \n    echo \"$1\" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._]//g' | sed 's/$/terraformstate&/' | cut -c -24\n}\n\n# Terraform Init - intialise a tf template + Azure Blob storage on Github action agent\nfunction terraform_init_gh() {\n\n    # shellcheck disable=SC2155\n    local _storage_account_name=\"$(az_storage_normalize \"$PREFIX\")\"\n    local _container_name=\"${PREFIX}-terraform-state-sac\"\n    local _container_rg=\"${PREFIX}-c12-rg\"\n    local _subscription_id=\"$ARM_SUBSCRIPTION_ID\"\n    \n    terraform init \\\n        -backend-config \"storage_account_name=$_storage_account_name\" \\\n        -backend-config \"container_name=$_container_name\" \\\n        -backend-config \"resource_group_name=$_container_rg\" \\\n        -backend-config \"subscription_id=$_subscription_id\"\n}\n", "num_lines": 25}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nTOOLS_PATH=\"/app\"\n\nfunction az_cli_sp_login(){\n    echo \"Login to azure with az cli\"\n    az login --service-principal --tenant \"$ARM_TENANT_ID\" --username \"$ARM_CLIENT_ID\" --password \"$ARM_CLIENT_SECRET\"\n}\n\nfunction get-application-list() {\n\n    APP_LIST_JSON=$(\"${TOOLS_PATH}\"/appsourceextractor -a \"${GITHUB_WORKSPACE}\")\n    APP_LIST=$(echo \"$APP_LIST_JSON\" | tail -1 | jq -r '.[]')\n    echo \"$APP_LIST\"\n}\n\nfunction get-application-list-json() {\n\n    APP_LIST_JSON=$(\"${TOOLS_PATH}\"/appsourceextractor -a \"${GITHUB_WORKSPACE}\")\n    APP_LIST=$(echo \"$APP_LIST_JSON\" | tail -1 | jq -r '.')\n    echo \"$APP_LIST\"\n}\n", "num_lines": 23}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n# Builds images for each Dockerfile found recursively in the given directory.\n# Resolves image dependencies for images in the same organization.\n# Tags images based on the directory structure and git branch names.\n#\n# source ./image_build.sh\n# Usage:image_build [Dockerfile|directory] [...]\n\n# Normalizes according to docker hub organization/image naming conventions:\nnormalize() {\n  echo \"$1\" | tr '[:upper:]' '[:lower:]' | sed 's/[^a-z0-9._-]//g'\n}\n\nlowerize() {\n  echo \"$1\" | tr '[:upper:]' '[:lower:]'\n}\n\n# Builds an image for each git branch of the given Dockerfile directory:\nbuild_versions() {\n  image=\"$1\"\n  # unset image var\n  shift 1\n  git_tag=\"$(git log -1 --format=%H)\"\n  docker build -t \"$image:$git_tag\" \"$@\" .\n}\n\n\n# Builds an image for each git branch of the given Dockerfile directory:\nbuild() {\n  cwd=\"$PWD\"\n  file=\"$(basename \"$1\")\"\n  dir=\"$(dirname \"$1\")\"\n  cd \"$dir\" || return 1\n  organization=\"$ACR_IMAGE_URL\"\n  if [ -z \"$organization\" ]; then\n    # Use the parent folder for the organization/user name:\n    organization=\"$(cd ../.. && normalize \"$(basename \"$PWD\")\")\"\n  fi\n  # Use the REPO_GITHUB env for the image name:\n  image=\"$organization/$(lowerize \"$REPO_GITHUB\")\"\n  # Check if the image depends on another image of the same organization:\n  echo -n \"$IMAGE_REPOSITORY_PASSWORD\" | docker login \"$ACR_IMAGE_URL\" --username \"$IMAGE_REPOSITORY_USERNAME\" --password-stdin\n  # docker pull \"$image\"\n  build_versions \"$image\" -f \"$file\"\n  status=$?\n  cd \"$cwd\" || return 1\n  return $status\n}\n\n# Builds and tags images for each Dockerfile in the arguments list:\nbuild_images() {\n  for file; do\n    # Shift the arguments list to remove the current Dockerfile:\n    shift\n    # Basic check if the file is a valid Dockerfile:\n    if ! grep '^FROM ' \"$file\"; then\n      echo \"Invalid Dockerfile: $file\" >&2\n      continue\n    else \n      build \"$file\"\n    fi\n  done\n}\n\nNEWLINE='\n'\n# finds Dockerfiles and starts the builds:\nfind_dockerfiles() {\n  dockerfiles_list=\n  for arg; do\n    if [ -d \"$arg\" ]; then\n      # Search for Dockerfiles and add them to the list:\n      dockerfiles_list=\"$dockerfiles_list$NEWLINE$(find \"$arg\" -name Dockerfile)\"\n    else\n      dockerfiles_list=\"$dockerfiles_list$NEWLINE$arg\"\n    fi\n  done\n  # Set the list as arguments, splitting only at newlines:\n  IFS=\"$NEWLINE\";\n  # shellcheck disable=SC2086\n  set -- $dockerfiles_list;\n  unset IFS\n  build_images \"$@\"\n}\n\nfunction image_build () {\n# Test if exactly 4 arguments are passed into the function\nif [ -z \"$ACR_IMAGE_URL\" ] \nthen\n  echo \"Error: ACR_IMAGE_URL is not set\"\n  exit 1\nfi\nif [ -z \"$IMAGE_REPOSITORY_USERNAME\" ] \nthen\n  echo \"Error: IMAGE_REPOSITORY_USERNAME is not set\"\n  exit 1\nfi\n  \n  if [ -z \"$IMAGE_REPOSITORY_PASSWORD\" ] \nthen\n  echo \"Error: IMAGE_REPOSITORY_PASSWORD is not set\"\n  exit 1\nfi\n  # finds Dockerfiles and starts the builds:\n  find_dockerfiles \"${@:-.}\"\n}\n\n# Usage:image_build [Dockerfile|directory] [...]\n", "num_lines": 111}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\nlowerize() {\n    echo \"$1\" | tr '[:upper:]' '[:lower:]'\n}\n\nfunction image_publishing () {\n    # Test if exactly four arguments are passed into the function\n    if [[ $# -ne 2 ]];\n    then\n        echo \"Error: Expecting 2 arguments for this function\"\n        exit 1\n    fi\n    # Validate existence of environment variables\n    if [ -z \"$IMAGE_REPOSITORY_USERNAME\" ] \n    then\n    echo \"Error: IMAGE_REPOSITORY_USERNAME is not set\"\n    exit 1\n    fi\n    \n    if [ -z \"$IMAGE_REPOSITORY_PASSWORD\" ] \n    then\n    echo \"Error: IMAGE_REPOSITORY_PASSWORD is not set\"\n    exit 1\n    fi\n    # Create variables for arguments\n    ACR_IMAGE_URL=\"$1\"\n    APP_IMAGE_NAME=\"$2\"\n    # Log in to DEV ACR with service principal credentials\n    echo -n \"$IMAGE_REPOSITORY_PASSWORD\" | docker login \"$ACR_IMAGE_URL\" --username \"$IMAGE_REPOSITORY_USERNAME\" --password-stdin\n    docker push \"$ACR_IMAGE_URL\"/\"$APP_IMAGE_NAME\"\n    docker logout \"$ACR_IMAGE_URL\"\n}\n", "num_lines": 35}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\nfunction image_scanning () {\n    echo \"Docker Image scanning\" \n    echo \"$1\" \n    echo \"$2\" \n    echo \"$3\" \n    \n}\n\nfunction functional_test () {\n    echo \"functional_tests\" \n    echo \"$1\" \n    echo \"$2\" \n    echo \"$3\" \n    \n}\n\nfunction integration_test () {\n    echo \"image integration tests\" \n    echo \"$1\" \n    echo \"$2\" \n    echo \"$3\" \n    \n}\n\nfunction image_signing () {\n    echo \"image_signing\" \n    echo \"$1\" \n    echo \"$2\" \n    echo \"$3\" \n}\n\n", "num_lines": 35}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -*- coding: utf-8 -*-\n\n\nfunction lint() {\n    echo \"lint app.yaml files\"\n  if [ \"$1\" ] && [ \"$2\" ]\n  then\n    docker run --mount src=\"$(pwd)\",target=/mount-dir,type=bind stelligent/config-lint \"$1\" \"$2\"\n    return 0\n  else\n    echo \"No args..\"\n    echo \"The program can also read files from a separate YAML file, and can scan these types of files:\"\n    return 1\n  fi\n}\n\nfunction compile () {\n  echo \"compile Example\" \n  case \"$1\" in\n  \"mvn\")\n      info \"mvn clean install\"\n      exit 0\n      ;;\n  \"go\" | \"gobuild\")\n      info \"go build\"\n      exit 0\n      ;;\n  *)\n      echo \"Unknown Compile step \\'$1\\'\"\n      exit 1\n      ;;\n  esac\n}\n\nfunction unit_test () {\n  echo \"Unit Test Example\" \n  case \"$1\" in\n  \"mvn\")\n      info \"mvn test-DskipITs=true\"\n      exit 0\n      ;;\n  \"go\" | \"gotest\")\n      info \"go test\"\n      exit 0\n      ;;\n  *)\n      echo \"Unknown test step \\'$1\\'\"\n      exit 1\n      ;;\n  esac\n}\n\nfunction integration_test () {\n  echo \"Integration Test Example\" \n  case \"$1\" in\n  \"mvn\")\n      info \"mvn test -DskipITs=false\"\n      exit 0\n      ;;\n  \"go\" | \"gotest\")\n      info \"go test -run 'Integration'\"\n      exit 0\n      ;;\n  *)\n      echo \"Unknown integration test step \\'$1\\'\"\n      exit 1\n      ;;\n  esac\n}\n\nfunction code_scanning () {\n  echo \"code_scanning\" \n\n  if [ -z \"$SONAR_HOST_URL\" ] \n\tthen\n\t  echo \"SONAR_HOST_URL is not set\"\n\t  exit 1\n\tfi\n\n  if [ -z \"$SONAR_TOKEN\" ] \n\tthen\n\t\techo \"SONAR_TOKEN is not set\"\n\t\texit 1\n\tfi\n\n  if [ -z \"$IMAGE_SONAR_SCANNER\" ] \n\tthen\n\t\techo \"IMAGE_SONAR_SCANNER is not set\"\n\t\texit 1\n\tfi\n\n  if [ \"$1\" ]\n  then\n    docker run -e SONAR_HOST_URL=\"$SONAR_HOST_URL\" -e SONAR_TOKEN=\"$SONAR_TOKEN\" -e SONAR_PROJECT_BASE_DIR=\"$1\" --user=\"$(id -u):$(id -g)\" -it -v \"$(PWD):/src\" \"$IMAGE_SONAR_SCANNER\"\n    return 0\n  else\n    echo \"No args..\"\n    echo \"The program can scan code with sonar-scanner-cli to a sonarqube instance specified, required Argument scanning dir path.\"\n    return 1\n  fi    \n}\n\nfunction dependency_checks () {\n  echo \"dependency_checks\"\n\n  if [ -z \"$IMAGE_DEPENDENCY_CHECK\" ] \n\t  then\n\t\t  echo \"IMAGE_DEPENDENCY_CHECK is not set\"\n\t\t  exit 1\n\tfi\n\n  if [ \"$1\" ]\n  then\n    docker run --rm --volume \"$(pwd)\":/src \"$IMAGE_DEPENDENCY_CHECK\" --scan \"$1\" --format \"ALL\" --out \"$(pwd)/reports/dependency_checks/\"\n    echo \"Reports Location: '$(pwd)'/reports/dependency_checks/\"\n    return 0\n  else\n    echo \"No args..\"\n    echo \"The program can scan code and dependency for OSWAP known vulnerabilities, required Arugment scanning dir path.\"\n    return 1\n  fi\n}\n", "num_lines": 124}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# shellcheck disable=SC2034\nread -r -d '' __usage <<-'EOF' || true # exits non-zero when EOF encountered\n  -f --file [arg]  Config Filename to use\nEOF\n\n# shellcheck source=src/runtime/bootstrap/lib/main.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../ && pwd)/runtime/bootstrap/lib/main.sh\"\n\n# shellcheck source=src/runtime/bootstrap/lib/ini_val.sh\nsource \"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && cd ../ && pwd)/runtime/bootstrap/lib/ini_val.sh\"\n\n\n\nfunction ssh_tunnel() {\n\n    config_file=\"$1\"\n\n    local_tunnel_port=\"1234\"\n\n    ssh_key_path=$(ini_val \"$config_file\" c12:generated.jumphost_ssh_key_location)\n    ssh_host=$(ini_val \"$config_file\" c12:generated.jumphost_ip)\n    ssh_username=$(ini_val \"$config_file\" c12:generated.jumphost_user)    \n    \n    ssh -oStrictHostKeyChecking=no -l \"$ssh_username\" -i \"$ssh_key_path\" -L \"$local_tunnel_port\":127.0.0.1:8888 -C -N \"$ssh_host\" &\n\n    echo \"export HTTPS_PROXY=http://127.0.0.1:$local_tunnel_port && export https_proxy=http://127.0.0.1:$local_tunnel_port\"\n}\n\nconfig_file=\"$arg_f\"\nssh_tunnel \"$config_file\"", "num_lines": 32}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n\nexport NO_COLOR=\"true\"\nexport LOG_LEVEL=7", "num_lines": 5}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nBASE_PATH=./ironbank\nBASE_IMAGE_ARCHIVE=$BASE_PATH/nodejs-12.16.tar\nBASE_REPO_SERVER=ocpacr.azurecr.us\nBASE_REPO_SERVER_USERNAME=[YOUR USERNAME]\nBASE_REPO_SERVER_PASSWORD=[YOUR PASSWORD]\nBASE_REPO=$BASE_REPO_SERVER/ironbank/opensource/nodejs/nodejs\nBASE_TAG=12.16-development\nAPPLICATION_IMAGE=$BASE_REPO_SERVER/demo/hello-azure-gov:dev\nAPPLICATION_K8S_NAMESPACE=azure-gov-demo\n\nRED='\\033[0;31m'\nGREEN='\\033[0;32m'\nBLUE='\\033[0;34m'\nHEADER=''\nNC='\\033[0m' # No Color\n\necho -e \"\\n\\n${HEADER}Importing Iron Bank public key${NC}\"\necho -e \"----------------------------------------------------\\n\"\ngpg --import $BASE_PATH/ironbank.asc\n\n\necho -e \"\\n\\n${HEADER}Checking manifest using Iron Bank signature${NC}\"\necho -e \"----------------------------------------------------\"\n\ngpg --verify $BASE_PATH/signature.sig $BASE_PATH/manifest.json\n\necho -e  \"\\n\\n${HEADER}Getting image checksum${NC}\"\necho -e  \"----------------------------------------------------\"\nEXPECTED_IMAGE_256_CHECKSUM=$(jq -r '.critical.image[\"image-tar-sha256-checksum\"]' $BASE_PATH/manifest.json)\necho -e \"Expected checksum is: \" ${BLUE}${EXPECTED_IMAGE_256_CHECKSUM}${NC}\necho -e \"Comparing against .tar file...\"\nACTUAL_IMAGE_256_CHECKSUM=$(sha256sum $BASE_PATH/nodejs-12.16.tar)\necho -e \"Actual checksum is:   \" ${BLUE}${ACTUAL_IMAGE_256_CHECKSUM}${NC}\ndocker run -ti --rm mpepping/ponysay --colour \"1;35\" --pony spike checksums match!!\nread\n\necho -e  \"\\n\\n${HEADER}Loading, tagging, and pushing image${NC}\"\necho -e  \"----------------------------------------------------\"\nLOADED_IMAGE=\"$(docker load -i $BASE_IMAGE_ARCHIVE | awk '{print $3}')\"\necho -e \"Loaded image:\" $LOADED_IMAGE\nTARGET_IMAGE=\"${LOADED_IMAGE/localhost/$BASE_REPO_SERVER}\"\necho -e \"Target image:\" ${GREEN} $TARGET_IMAGE ${NC}\necho -e \"${BLUE}Retagging...${NC}\"\ndocker tag $LOADED_IMAGE $TARGET_IMAGE\necho -e \"${BLUE}Pushing \" $TARGET_IMAGE ${NC}\ndocker push $TARGET_IMAGE\necho -e \"${GREEN}Completed base image push!${NC}\"\n\n\necho -e  \"\\n\\n${HEADER}Build and push application image${NC}\"\necho -e  \"----------------------------------------------------\"\necho -e \"${BLUE}Building image...${NC}\"\ndocker build -t $APPLICATION_IMAGE . >> /dev/null\necho -e \"\"\necho -e \"${BLUE}Pushing image...${NC}\"\ndocker push $APPLICATION_IMAGE\necho -e \"${GREEN}Completed application image push!${NC}\"\n\necho -e  \"\\n\\n${HEADER}Deploy application image${NC}\"\necho -e  \"----------------------------------------------------\"\nkubectl create namespace $APPLICATION_K8S_NAMESPACE\nkubectl create secret docker-registry ocpacr --docker-server=$BASE_REPO_SERVER --docker-username=$BASE_REPO_SERVER_USERNAME --docker-password=$BASE_REPO_SERVER_PASSWORD -n $APPLICATION_K8S_NAMESPACE\n\nAPPLICATION_IMAGE_HASH=$(docker inspect ${APPLICATION_IMAGE} | jq -r '.[0].RepoDigests[0]')\necho -e \"${BLUE}Using Helm to deploy image with digest hash: ${APPLICATION_IMAGE_HASH##*@}${NC}\"\nhelm install -n ${APPLICATION_K8S_NAMESPACE} hello-azure-gov ./charts/helloAzureGov --set image.sha=${APPLICATION_IMAGE_HASH##*@} --wait\n\nsleep 5\n\necho -e  \"\\n\\nPods${NC}\"\necho -e  \"----------------------------------------------------\"\nkubectl get pods -n $APPLICATION_K8S_NAMESPACE\n\necho -e  \"\"\ndocker run -ti --rm mpepping/ponysay --colour \"0;32\" --pony gummy Application ready: https://website.$APPLICATION_K8S_NAMESPACE.cloudfitdsop.com/\n", "num_lines": 77}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Bastion Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=\"${PASSWORD_ACT_KEY}\"\nexport POOL_ID=${POOL_ID}\nexport SUDOUSER=${SUDOUSER}\nexport CUSTOMROUTINGCERTTYPE=${CUSTOMROUTINGCERTTYPE}\nexport CUSTOMMASTERCERTTYPE=${CUSTOMMASTERCERTTYPE}\nexport CUSTOMROUTINGCAFILE=\"${CUSTOMROUTINGCAFILE}\"\nexport CUSTOMROUTINGCERTFILE=\"${CUSTOMROUTINGCERTFILE}\"\nexport CUSTOMROUTINGKEYFILE=\"${CUSTOMROUTINGKEYFILE}\"\nexport CUSTOMMASTERCAFILE=\"${CUSTOMMASTERCAFILE}\"\nexport CUSTOMMASTERCERTFILE=\"${CUSTOMMASTERCERTFILE}\"\nexport CUSTOMMASTERKEYFILE=\"${CUSTOMMASTERKEYFILE}\"\nexport CUSTOMDOMAIN=\"${CUSTOMDOMAIN}\"\nexport MINORVERSION=${MINORVERSION}\nexport CUSTOMMASTERTYPE=${CUSTOMMASTERTYPE}\nexport CUSTOMROUTINGTYPE=${CUSTOMROUTINGTYPE}\nexport REPOSERVER=${REPOSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\nexport REGISTRYSERVER=${REGISTRYSERVER}\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        echo \"Incorrect Username / Password or Organization ID / Activation Key specified\"\n        exit 3\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n        fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Update system to latest packages\necho $(date) \" - Update system to latest packages\"\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - System update complete\"\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages\"\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible\nyum -y update glusterfs-fuse\necho $(date) \" - Base package installation complete\"\n\n# Install OpenShift utilities\necho $(date) \" - Installing OpenShift utilities\"\nyum -y install openshift-ansible-3.11.${MINORVERSION}\necho $(date) \" - OpenShift utilities installation complete\"\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Installing Azure CLI\n# From https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-yum\necho $(date) \" - Installing Azure CLI\"\n# sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc\n# sudo sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\nsudo yum install -y azure-cli\necho $(date) \" - Azure CLI installation complete\"\n\n# Install ImageMagick to resize image for Custom Header\nsudo yum install -y ImageMagick\n\n# Configure DNS so it always has the domain name\necho $(date) \" - Adding DOMAIN to search for resolv.conf\"\nif [[ \"${CUSTOMDOMAIN}\" == \"none\" ]]\nthen\n\tDOMAINNAME=`domainname -d`\nelse\n\tDOMAINNAME=${CUSTOMDOMAIN}\nfi\n\necho \"DOMAIN=${DOMAINNAME}\" >> /etc/sysconfig/network-scripts/ifcfg-eth0\n\necho $(date) \" - Restarting NetworkManager\"\nrunuser -l ${SUDOUSER} -c \"ansible localhost -o -b -m service -a \\\"name=NetworkManager state=restarted\\\"\"\necho $(date) \" - NetworkManager configuration complete\"\n\n# Run Ansible Playbook to update ansible.cfg file\necho $(date) \" - Updating ansible.cfg file\"\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 -t 5 https://raw.githubusercontent.com/microsoft/openshift-container-platform-playbooks/master/updateansiblecfg.yaml\n    ansible-playbook -f 10 ./updateansiblecfg.yaml\nelse\n    wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 -t 5 http://${SCRIPTSLOCATION}/ocpp/updateansiblecfg.yaml\n    ansible-playbook -f 10 ./ocpp/updateansiblecfg.yaml\nfi\n\n# Create certificate files \n\nif [[ \"${CUSTOMMASTERCERTTYPE}\" == \"custom\" ]]\nthen\n    echo $(date) \" - Creating custom master certificate files\"\n    runuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERCAFILE}\\\" > /tmp/masterca.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERCERTFILE}\\\" > /tmp/mastercert.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERKEYFILE}\\\" > /tmp/masterkey.pem\"\n\techo $(date) \" - Custom master certificate files masterca.pem, mastercert.pem, masterkey.pem created in /tmp\"\nfi\n\nif [ \"${CUSTOMROUTINGCERTTYPE}\" == \"custom\" ]\nthen\n    echo $(date) \" - Creating custom routing certificate files\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGCAFILE}\\\" > /tmp/routingca.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGCERTFILE}\\\" > /tmp/routingcert.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGKEYFILE}\\\" > /tmp/routingkey.pem\"\n\techo $(date) \" - Custom routing certificate files routingca.pem, routingcert.pem, routingkey.pem created in /tmp\"\nfi\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n", "num_lines": 182}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Script\"\n\nset -e\n\nexport SUDOUSER=${SUDOUSER}\nexport PASSWORD=${PASSWORD}\nexport MASTER=${MASTER}\nexport MASTERPUBLICIPHOSTNAME=${MASTERPUBLICIPHOSTNAME}\nexport MASTERPUBLICIPADDRESS=${MASTERPUBLICIPADDRESS}\nexport INFRA=${INFRA}\nexport NODE=${NODE}\nexport NODECOUNT=${NODECOUNT}\nexport INFRACOUNT=${INFRACOUNT}\nexport MASTERCOUNT=${MASTERCOUNT}\nexport ROUTING=${ROUTING}\nexport REGISTRYSA=${REGISTRYSA}\nexport ACCOUNTKEY=${ACCOUNTKEY}\nexport METRICS=${METRICS}\nexport LOGGING=${LOGGING}\nexport TENANTID=${TENANTID}\nexport SUBSCRIPTIONID=${SUBSCRIPTIONID}\nexport AADCLIENTID=${AADCLIENTID}\nexport AADCLIENTSECRET=${AADCLIENTSECRET}\nexport RESOURCEGROUP=${RESOURCEGROUP}\nexport LOCATION=${LOCATION}\nexport AZURE=${AZURE}\nexport STORAGEKIND=${STORAGEKIND}\nexport ENABLECNS=${ENABLECNS}\nexport CNS=${CNS}\nexport CNSCOUNT=${CNSCOUNT}\nexport VNETNAME=${VNETNAME}\nexport NODENSG=${NODENSG}\nexport NODEAVAILIBILITYSET=${NODEAVAILIBILITYSET}\nexport MASTERCLUSTERTYPE=${MASTERCLUSTERTYPE}\nexport PRIVATEIP=${PRIVATEIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRAPIPNAME=${INFRAPIPNAME}\nexport CUSTOMROUTINGCERTTYPE=${CUSTOMROUTINGCERTTYPE}\nexport CUSTOMMASTERCERTTYPE=${CUSTOMMASTERCERTTYPE}\nexport MINORVERSION=${MINORVERSION}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\nexport DOCKERREGISTRYREALM=${DOCKERREGISTRYREALM} \nexport BASTION=$(hostname)\n\n# Set CNS to default storage type.  Will be overridden later if Azure is true\nexport CNS_DEFAULT_STORAGE=true\n\n# Setting DOMAIN variable\nexport DOMAIN=`domainname -d`\n\n# Determine if Commercial Azure or Azure Government\n# CLOUD=$( curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/location?api-version=2017-04-02&format=text\" | cut -c 1-2 )\nexport CLOUD=${CLOUD^^}\n# export CLOUDNAME=\"AzureUSGovernmentCloud\"\n# export CLOUDNAME=\"AzurePublicCloud\"\n\nexport MASTERLOOP=$((MASTERCOUNT - 1))\nexport INFRALOOP=$((INFRACOUNT - 1))\nexport NODELOOP=$((NODECOUNT - 1))\n\necho $(date) \" - Configuring SSH ControlPath to use shorter path name\"\n\nsed -i -e \"s/^# control_path = %(directory)s\\/%%h-%%r/control_path = %(directory)s\\/%%h-%%r/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#host_key_checking = False/host_key_checking = False/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#pty=False/pty=False/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#stdout_callback = skippy/stdout_callback = skippy/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#pipelining = False/pipelining = True/\" /etc/ansible/ansible.cfg\n\n# echo $(date) \" - Modifying sudoers\"\nsed -i -e \"s/Defaults    requiretty/# Defaults    requiretty/\" /etc/sudoers\nsed -i -e '/Defaults    env_keep += \"LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY\"/aDefaults    env_keep += \"PATH\"' /etc/sudoers\n\n# Setting the default openshift_cloudprovider_kind if Azure enabled\nif [[ ${AZURE} == \"true\" ]]\nthen\n    CLOUDKIND=\"openshift_cloudprovider_kind=azure\nopenshift_cloudprovider_azure_client_id=${AADCLIENTID}\nopenshift_cloudprovider_azure_client_secret=${AADCLIENTSECRET}\nopenshift_cloudprovider_azure_tenant_id=${TENANTID}\nopenshift_cloudprovider_azure_subscription_id=${SUBSCRIPTIONID}\nopenshift_cloudprovider_azure_cloud=${CLOUDNAME}\nopenshift_cloudprovider_azure_vnet_name=${VNETNAME}\nopenshift_cloudprovider_azure_security_group_name=${NODENSG}\nopenshift_cloudprovider_azure_availability_set_name=${NODEAVAILIBILITYSET}\nopenshift_cloudprovider_azure_resource_group=${RESOURCEGROUP}\nopenshift_cloudprovider_azure_location=${LOCATION}\"\n\tCNS_DEFAULT_STORAGE=false\n\tif [[ ${STORAGEKIND} == \"managed\" ]]\n\tthen\n\t\tSCKIND=\"openshift_storageclass_parameters={'kind': 'managed', 'storageaccounttype': 'Premium_LRS'}\"\n\telse\n\t\tSCKIND=\"openshift_storageclass_parameters={'kind': 'shared', 'storageaccounttype': 'Premium_LRS'}\"\n\tfi\nfi\n\n# Cloning Ansible playbook repository\n\necho $(date) \" - Cloning Ansible playbook repository\"\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    #Connected use this:\n    ((cd /home/${SUDOUSER} && git clone https://github.com/Microsoft/openshift-container-platform-playbooks.git) || (cd /home/${SUDOUSER}/openshift-container-platform-playbooks && git pull))\nelse\n    #Disconnected use this:\n    cd /home/${SUDOUSER} && wget -r -np ${REPOSERVER}/ocpp/\n    [ -d /home/${SUDOUSER}/openshift-container-platform-playbooks ] && rm -rf /home/${SUDOUSER}/openshift-container-platform-playbooks\n    mv /home/${SUDOUSER}/${REPOSERVER}/ocpp /home/${SUDOUSER}/openshift-container-platform-playbooks\n    [ -d /home/${SUDOUSER}/${REPOSERVER} ] && rm -rf /home/${SUDOUSER}/${REPOSERVER}\n    cd /home/${SUDOUSER}/openshift-container-platform-playbooks\nfi\n\nif [ -d /home/${SUDOUSER}/openshift-container-platform-playbooks ]\nthen\n    echo \" - Retrieved playbooks successfully\"\nelse\n    echo \" - Retrieval of playbooks failed\"\n    exit 7\nfi\n\n# Configure custom routing certificate\necho $(date) \" - Create variable for routing certificate based on certificate type\"\nif [[ ${CUSTOMROUTINGCERTTYPE} == \"custom\" ]]\nthen\n\tROUTINGCERTIFICATE=\"openshift_hosted_router_certificate={\\\"cafile\\\": \\\"/tmp/routingca.pem\\\", \\\"certfile\\\": \\\"/tmp/routingcert.pem\\\", \\\"keyfile\\\": \\\"/tmp/routingkey.pem\\\"}\"\nelse\n\tROUTINGCERTIFICATE=\"\"\nfi\n\n\n# Configure master cluster address information based on Cluster type (private or public)\necho $(date) \" - Create variable for master cluster address based on cluster type\"\nif [[ ${MASTERCLUSTERTYPE} == \"private\" ]]\nthen\n    MASTERCLUSTERHOSTNAME=${PRIVATEDNS}\n\tMASTERCLUSTERADDRESS=\"openshift_master_cluster_hostname=${MASTER}-001v\nopenshift_master_cluster_public_hostname=${PRIVATEDNS}\nopenshift_master_cluster_public_vip=${PRIVATEIP}\"\nelse\n    MASTERCLUSTERHOSTNAME=${MASTERPUBLICIPHOSTNAME}\n\tMASTERCLUSTERADDRESS=\"openshift_master_cluster_hostname=${MASTERPUBLICIPHOSTNAME}\nopenshift_master_cluster_public_hostname=${MASTERPUBLICIPHOSTNAME}\nopenshift_master_cluster_public_vip=${MASTERPUBLICIPADDRESS}\"\nfi\n\n# Configure custom master API certificate\necho $(date) \" - Create variable for master api certificate based on certificate type\"\nif [[ ${CUSTOMMASTERCERTTYPE} == \"custom\" ]]\nthen\n\tMASTERCERTIFICATE=\"openshift_master_overwrite_named_certificates=true\nopenshift_master_named_certificates=[{\\\"names\\\": [\\\"${MASTERCLUSTERHOSTNAME}\\\"], \\\"cafile\\\": \\\"/tmp/masterca.pem\\\", \\\"certfile\\\": \\\"/tmp/mastercert.pem\\\", \\\"keyfile\\\": \\\"/tmp/masterkey.pem\\\"}]\"\nelse\n\tMASTERCERTIFICATE=\"\"\nfi\n\n# Create Master nodes grouping\necho $(date) \" - Creating Master nodes grouping\"\nMASTERLIST=\"00${MASTERCOUNT}\"\nfor c in $(seq -f \"%03g\" 1 ${MASTERCOUNT})\ndo\n    mastergroup=\"$mastergroup\n${MASTER}-${c}v openshift_node_group_name='node-config-master'\"\ndone\n\n# Create Infra nodes grouping \necho $(date) \" - Creating Infra nodes grouping\"\nfor c in $(seq -f \"%03g\" 1 ${INFRACOUNT})\ndo\n    infragroup=\"$infragroup\n${INFRA}-${c}v openshift_node_group_name='node-config-infra'\"\ndone\n\n# Create Nodes grouping\necho $(date) \" - Creating Nodes grouping\"\nfor c in $(seq -f \"%03g\" 1 ${NODECOUNT})\ndo\n    nodegroup=\"$nodegroup\n${NODE}-${c}v openshift_node_group_name='node-config-compute'\"\ndone\n\n# Create CNS nodes grouping if CNS is enabled\nif [[ ${ENABLECNS} == \"true\" ]]\nthen\n    echo $(date) \" - Creating CNS nodes grouping\"\n\n    for c in $(seq -f \"%03g\" 1 ${CNSCOUNT})\n    do\n        cnsgroup=\"$cnsgroup\n${CNS}-${c}v openshift_node_group_name='node-config-compute'\"\n    done\nfi\n\n# Setting the HA Mode if more than one master\nif [ ${MASTERCOUNT} != 1 ]\nthen\n\techo $(date) \" - Enabling HA mode for masters\"\n    export HAMODE=\"openshift_master_cluster_method=native\"\nfi\n\n# Create Temp Ansible Hosts File\necho $(date) \" - Create Ansible Hosts file\"\n\ncat > /etc/ansible/hosts <<EOF\n[tempnodes]\n$mastergroup\n$infragroup\n$nodegroup\n$cnsgroup\nEOF\n\n# Run a loop playbook to ensure DNS Hostname resolution is working prior to continuing with script\necho $(date) \" - Running DNS Hostname resolution check\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook ~/openshift-container-platform-playbooks/check-dns-host-name-resolution.yaml\"\n\n# Create glusterfs configuration if CNS is enabled\nif [[ ${ENABLECNS} == \"true\" ]]\nthen\n    echo $(date) \" - Creating glusterfs configuration\"\n\n\t# Ensuring selinux is configured properly\n    echo $(date) \" - Setting selinux to allow gluster-fuse access\"\n    runuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -a 'sudo setsebool -P virt_sandbox_use_fusefs on'\" || true\n\trunuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -a 'sudo setsebool -P virt_use_fusefs on'\" || true\n\n    for c in $(seq -f \"%03g\" 1 ${CNSCOUNT})\n    do\n        runuser ${SUDOUSER} -c \"ssh-keyscan -H ${CNS}-${c}v >> ~/.ssh/known_hosts\"\n        drive=$(runuser ${SUDOUSER} -c \"ssh ${CNS}-${c}v 'sudo /usr/sbin/fdisk -l'\" | awk '$1 == \"Disk\" && $2 ~ /^\\// && ! /mapper/ {if (drive) print drive; drive = $2; sub(\":\", \"\", drive);} drive && /^\\// {drive = \"\"} END {if (drive) print drive;}')\n        drive1=$(echo $drive | cut -d ' ' -f 1)\n        drive2=$(echo $drive | cut -d ' ' -f 2)\n        drive3=$(echo $drive | cut -d ' ' -f 3)\n        cnsglusterinfo=\"$cnsglusterinfo\n${CNS}-${c}v glusterfs_devices='[ \\\"${drive1}\\\", \\\"${drive2}\\\", \\\"${drive3}\\\" ]'\"\n    done\n\n    HOSTEDREGISTRYVALS=\"openshift_hosted_registry_storage_kind=glusterfs\nopenshift_hosted_registry_storage_volume_size=20Gi\nopenshift_hosted_registry_selector='node-role.kubernetes.io/infra=true'\"\n\nelse\n\n    HOSTEDREGISTRYVALS=\"openshift_hosted_registry_storage_kind=object\nopenshift_hosted_registry_storage_provider=azure_blob\nopenshift_hosted_registry_storage_azure_blob_accountname=${REGISTRYSA}\nopenshift_hosted_registry_storage_azure_blob_accountkey=${ACCOUNTKEY}\nopenshift_hosted_registry_storage_azure_blob_container=registry\nopenshift_hosted_registry_storage_azure_blob_realm=$DOCKERREGISTRYREALM\"\n\nfi\n\n# Create Ansible Hosts File\necho $(date) \" - Create Ansible Hosts file\"\n\ncat > /etc/ansible/hosts <<EOF\n# Create an OSEv3 group that contains the masters and nodes groups\n[OSEv3:children]\nmasters\nnodes\netcd\nmaster0\nglusterfs\nglusterfs_registry\nnew_nodes\n\n# Set variables common for all OSEv3 hosts\n[OSEv3:vars]\nansible_ssh_user=${SUDOUSER}\nansible_become=yes\nopenshift_install_examples=true\ndeployment_type=openshift-enterprise\nopenshift_release=v3.11\nopenshift_image_tag=v3.11.${MINORVERSION}\nopenshift_pkg_version=-3.11.${MINORVERSION}\ndocker_udev_workaround=True\nopenshift_use_dnsmasq=true\nopenshift_master_default_subdomain=${ROUTING}\nopenshift_override_hostname_check=true\nosm_use_cockpit=true\nos_sdn_network_plugin_name='redhat/openshift-ovs-multitenant'\nopenshift_master_api_port=443\nopenshift_master_console_port=443\nosm_default_node_selector='node-role.kubernetes.io/compute=true'\nopenshift_disable_check=memory_availability,docker_image_availability\n$CLOUDKIND\n$SCKIND\n$CUSTOMCSS\n$ROUTINGCERTIFICATE\n$MASTERCERTIFICATE\n$PROXY\n\n# Workaround for docker image failure\n# https://access.redhat.com/solutions/3480921\noreg_url=${REGISTRYSERVER}/openshift3/ose-\\${component}:\\${version}\nopenshift_examples_modify_imagestreams=true\n\n# default selectors for router and registry services\nopenshift_router_selector='node-role.kubernetes.io/infra=true'\nopenshift_registry_selector='node-role.kubernetes.io/infra=true'\n\n# Configure registry not to use Azure blob storage\nopenshift_hosted_registry_replicas=1\n$HOSTEDREGISTRYVALS\n\n# Deploy Service Catalog\nopenshift_enable_service_catalog=false\n\n# Type of clustering being used by OCP\n$HAMODE\n\n# Addresses for connecting to the OpenShift master nodes\n$MASTERCLUSTERADDRESS\n\n# Enable HTPasswdPasswordIdentityProvider\nopenshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider'}]\n\n# Specify CNS images\nopenshift_storage_glusterfs_image=${REGISTRYSERVER}/rhgs3/rhgs-server-rhel7:v3.11\nopenshift_storage_glusterfs_block_image=${REGISTRYSERVER}/rhgs3/rhgs-gluster-block-prov-rhel7:v3.11\nopenshift_storage_glusterfs_s3_image=${REGISTRYSERVER}/rhgs3/rhgs-s3-server-rhel7:v3.11\nopenshift_storage_glusterfs_heketi_image=${REGISTRYSERVER}/rhgs3/rhgs-volmanager-rhel7:v3.11\n\n# Setup metrics\nopenshift_metrics_install_metrics=$METRICS\nopenshift_metrics_start_cluster=$METRICS\nopenshift_metrics_hawkular_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_metrics_cassandra_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_metrics_heapster_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\n\n# Setup logging\nopenshift_logging_install_logging=$LOGGING\nopenshift_logging_fluentd_nodeselector={\"logging\":\"true\"}\nopenshift_logging_es_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_kibana_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_curator_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_master_public_url=https://${MASTERCLUSTERHOSTNAME}\n\n# host group for masters\n[masters]\n${MASTER}-[001:${MASTERLIST}]v\n\n# host group for etcd\n[etcd]\n${MASTER}-[001:${MASTERLIST}]v\n\n[master0]\n${MASTER}-001v\n\n# Only populated when CNS is enabled\n[glusterfs]\n$cnsglusterinfo\n\n[glusterfs_registry]\n$cnsglusterinfo\n\n# host group for nodes\n[nodes]\n$mastergroup\n$infragroup\n$nodegroup\n$cnsgroup\n\n# host group for adding new nodes\n[new_nodes]\nEOF\n\n# Update WALinuxAgent\necho $(date) \" - Updating WALinuxAgent on all cluster nodes\"\nrunuser ${SUDOUSER} -c \"ansible all -f 30 -b -m yum -a 'name=WALinuxAgent state=latest'\"\n\n# Setup NetworkManager to manage eth0\necho $(date) \" - Running NetworkManager playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-node/network_manager.yml\"\n\n# Configure DNS so it always has the domain name\necho $(date) \" - Adding $DOMAIN to search for resolv.conf\"\nrunuser ${SUDOUSER} -c \"ansible all -o -f 30 -b -m lineinfile -a 'dest=/etc/sysconfig/network-scripts/ifcfg-eth0 line=\\\"DOMAIN=$DOMAIN\\\"'\"\n\n# Configure resolv.conf on all hosts through NetworkManager\necho $(date) \" - Restarting NetworkManager\"\nrunuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -m service -a \\\"name=NetworkManager state=restarted\\\"\"\necho $(date) \" - NetworkManager configuration complete\"\n\n# Restarting things so everything is clean before continuing with installation\necho $(date) \" - Rebooting cluster to complete installation\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/reboot-master.yaml\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/reboot-nodes.yaml\"\nsleep 20\n\n# Run OpenShift Container Platform prerequisites playbook\necho $(date) \" - Running Prerequisites via Ansible Playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/prerequisites.yml\"\necho $(date) \" - Prerequisites check complete\"\n\n# Initiating installation of OpenShift Container Platform using Ansible Playbook\necho $(date) \" - Installing OpenShift Container Platform via Ansible Playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/deploy_cluster.yml\"\nif [ $? -eq 0 ]\nthen\n    echo $(date) \" - OpenShift Cluster installed successfully\"\nelse\n    echo $(date) \" - OpenShift Cluster failed to install\"\n    exit 6\nfi\n\n# Install OpenShift Atomic Client\ncd /root\nmkdir .kube\nrunuser ${SUDOUSER} -c \"scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${SUDOUSER}@${MASTER}-001v:~/.kube/config /tmp/kube-config\"\ncp /tmp/kube-config /root/.kube/config\nmkdir /home/${SUDOUSER}/.kube\ncp /tmp/kube-config /home/${SUDOUSER}/.kube/config\nchown --recursive ${SUDOUSER} /home/${SUDOUSER}/.kube\nrm -f /tmp/kube-config\nyum -y install atomic-openshift-clients\n\n# Adding user to OpenShift authentication file\necho $(date) \" - Adding OpenShift user\"\nrunuser ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/addocpuser.yaml\"\n\n# Assigning cluster admin rights to OpenShift user\necho $(date) \" - Assigning cluster admin rights to user\"\nrunuser ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/assignclusteradminrights.yaml\"\n\n# Installing Service Catalog, Ansible Service Broker and Template Service Broker\nif [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\nthen\n    runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_enable_service_catalog=true -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-service-catalog/config.yml\"\nfi\n\n# Adding Open Sevice Broker for Azaure (requires service catalog)\n# Disabling deployment of OSBA\nif [[ ${AZURE} == \"true\" ]]\nthen\n    oc new-project osba\n    oc process -f https://raw.githubusercontent.com/Azure/open-service-broker-azure/master/contrib/openshift/osba-os-template.yaml  \\\n        -p ENVIRONMENT=AzurePublicCloud \\\n        -p AZURE_SUBSCRIPTION_ID=${SUBSCRIPTIONID} \\\n        -p AZURE_TENANT_ID=${TENANTID} \\\n        -p AZURE_CLIENT_ID=${AADCLIENTID} \\\n        -p AZURE_CLIENT_SECRET=${AADCLIENTSECRET} \\\n        | oc create -f -\nfi\n\n# Configure Metrics\nif [[ ${METRICS} == \"true\" ]]\nthen\n    sleep 30\n    echo $(date) \"- Deploying Metrics\"\n    if [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\n    then\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_metrics_install_metrics=True -e openshift_metrics_cassandra_storage_type=dynamic -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-metrics/config.yml\"\n    else\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_metrics_install_metrics=True /usr/share/ansible/openshift-ansible/playbooks/openshift-metrics/config.yml\"\n    fi\n    if [ $? -eq 0 ]\n    then\n        echo $(date) \" - Metrics configuration completed successfully\"\n    else\n        echo $(date) \" - Metrics configuration failed\"\n        exit 11\n    fi\nfi\n\n# Configure Logging\n\nif [[ ${LOGGING} == \"true\" ]]\nthen\n    sleep 60\n    echo $(date) \"- Deploying Logging\"\n    if [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\n    then\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_logging_install_logging=True -e openshift_logging_es_pvc_dynamic=true -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-logging/config.yml\"\n    else\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_logging_install_logging=True -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-logging/config.yml\"\n    fi\n    if [ $? -eq 0 ]\n    then\n        echo $(date) \" - Logging configuration completed successfully\"\n    else\n        echo $(date) \" - Logging configuration failed\"\n        exit 12\n    fi\nfi\n\nif [[ ${AZURE} == \"true\" ]]\nthen\n    # Creating variables file for private master and Azure AD configuration playbook\n    echo $(date) \" - Creating variables file for future playbooks\"\ncat > /home/${SUDOUSER}/openshift-container-platform-playbooks/vars.yaml <<EOF\nadmin_user: $SUDOUSER\nmaster_lb_private_dns: $PRIVATEDNS\ndomain: $DOMAIN\nEOF\n\n    # Configure cluster for private masters\n    if [[ ${MASTERCLUSTERTYPE} == \"private\" ]]\n    then\n        echo $(date) \" - Configure cluster for private masters\"\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/activate-private-lb-fqdn.31x.yaml\"\n    fi\nfi\n\n# Delete yaml files\necho $(date) \" - Deleting unecessary files\"\nrm -rf /home/${SUDOUSER}/openshift-container-platform-playbooks\n\n# Delete pem files\necho $(date) \" - Delete pem files\"\nrm -rf /tmp/*.pem\n\necho $(date) \" - Sleep for 15 seconds\"\nsleep 15\n\necho $(date) \" - Script complete\"\n\n# *.apps.beta-openshift.com == 10.3.101.200\n# *.console.beta-openshift.com == 10.3.101.100\n\n\n# address=/console.dev-openshift.com/10.3.104.100\n# address=/apps.dev-openshift.com/10.3.104.200\n", "num_lines": 524}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Node Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n    sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n    echo \"Pool attached successfully\"\n    else\n    grep attached attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n    else\n        echo \"Incorrect Pool ID or no entitlements available\"\n        exit 4\n    fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct\nyum -y install cloud-utils-growpart.noarch\nyum -y install ansible\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and starting service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n    echo \"Docker thin pool logical volume created successfully\"\nelse\n    echo \"Error creating logical volume for Docker\"\n    exit 5\nfi\n\n# Enable and start Docker services\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n\n", "num_lines": 159}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Master Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n    fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible\n\nyum -y install cloud-utils-growpart.noarch\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo \"Root partition expanded\"\nelse\n    echo \"Root partition failed to expand\"\n    exit 6\nfi\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker \n\n# Update docker config for insecure registry\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and staring service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n   echo \"Docker thin pool logical volume created successfully\"\nelse\n   echo \"Error creating logical volume for Docker\"\n   exit 5\nfi\n\n# Enable and start Docker services\nsysctl -w vm.max_map_count=262144\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n", "num_lines": 167}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Infra / Node Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n        fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct ansible\nyum -y install cloud-utils-growpart.noarch\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo \"Root partition expanded\"\nelse\n    echo \"Root partition failed to expand\"\n    exit 6\nfi\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and staring service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n    echo \"Docker thin pool logical volume created successfully\"\nelse\n    echo \"Error creating logical volume for Docker\"\n    exit 5\nfi\n\n# Enable and start Docker services\nsysctl -w vm.max_map_count=262144\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n\n", "num_lines": 167}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Bastion Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=\"${PASSWORD_ACT_KEY}\"\nexport POOL_ID=${POOL_ID}\n# export PRIVATEKEY=$4\nexport SUDOUSER=${SUDOUSER}\nexport CUSTOMROUTINGCERTTYPE=${CUSTOMROUTINGCERTTYPE}\nexport CUSTOMMASTERCERTTYPE=${CUSTOMMASTERCERTTYPE}\nexport CUSTOMROUTINGCAFILE=\"${CUSTOMROUTINGCAFILE}\"\nexport CUSTOMROUTINGCERTFILE=\"${CUSTOMROUTINGCERTFILE}\"\nexport CUSTOMROUTINGKEYFILE=\"${CUSTOMROUTINGKEYFILE}\"\nexport CUSTOMMASTERCAFILE=\"${CUSTOMMASTERCAFILE}\"\nexport CUSTOMMASTERCERTFILE=\"${CUSTOMMASTERCERTFILE}\"\nexport CUSTOMMASTERKEYFILE=\"${CUSTOMMASTERKEYFILE}\"\nexport CUSTOMDOMAIN=\"${CUSTOMDOMAIN}\"\nexport MINORVERSION=${MINORVERSION}\nexport CUSTOMMASTERTYPE=${CUSTOMMASTERTYPE}\nexport CUSTOMROUTINGTYPE=${CUSTOMROUTINGTYPE}\nexport REPOSERVER=${REPOSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\n# export SCRIPTSLOCATION=${23}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\nexport REGISTRYSERVER=${REGISTRYSERVER}\n\n# # Generate private keys for use by Ansible\n# **********Moved to deployment scripts\n# echo $(date) \" - Generating Private keys for use by Ansible for OpenShift Installation\"\n\n# runuser -l $SUDOUSER -c \"echo \\\"$PRIVATEKEY\\\" > ~/.ssh/id_rsa\"\n# runuser -l $SUDOUSER -c \"chmod 600 ~/.ssh/id_rsa*\"\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        echo \"Incorrect Username / Password or Organization ID / Activation Key specified\"\n        exit 3\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n        fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo\n    # mv -f ose.repo /etc/yum.repos.d/ose.repo\n\n    # disconnected\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Update system to latest packages\necho $(date) \" - Update system to latest packages\"\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - System update complete\"\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages\"\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible\nyum -y update glusterfs-fuse\necho $(date) \" - Base package installation complete\"\n\n# Install OpenShift utilities\necho $(date) \" - Installing OpenShift utilities\"\nyum -y install openshift-ansible-3.11.${MINORVERSION}\necho $(date) \" - OpenShift utilities installation complete\"\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\nsystemctl enable docker\nsystemctl start docker\n\n# Installing Azure CLI\n# From https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-yum\necho $(date) \" - Installing Azure CLI\"\n# sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc\n# sudo sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\nsudo yum install -y azure-cli\necho $(date) \" - Azure CLI installation complete\"\n\n# Install ImageMagick to resize image for Custom Header\nsudo yum install -y ImageMagick\n\n# Configure DNS so it always has the domain name\necho $(date) \" - Adding DOMAIN to search for resolv.conf\"\nif [[ \"${CUSTOMDOMAIN}\" == \"none\" ]]\nthen\n\tDOMAINNAME=`domainname -d`\nelse\n\tDOMAINNAME=${CUSTOMDOMAIN}\nfi\n\necho \"DOMAIN=${DOMAINNAME}\" >> /etc/sysconfig/network-scripts/ifcfg-eth0\n\necho $(date) \" - Restarting NetworkManager\"\nrunuser -l ${SUDOUSER} -c \"ansible localhost -o -b -m service -a \\\"name=NetworkManager state=restarted\\\"\"\necho $(date) \" - NetworkManager configuration complete\"\n\n# Run Ansible Playbook to update ansible.cfg file\necho $(date) \" - Updating ansible.cfg file\"\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 -t 5 https://raw.githubusercontent.com/microsoft/openshift-container-platform-playbooks/master/updateansiblecfg.yaml\n    ansible-playbook -f 10 ./updateansiblecfg.yaml\nelse\n    wget --retry-connrefused --waitretry=1 --read-timeout=20 --timeout=15 -t 5 http://${SCRIPTSLOCATION}/ocpp/updateansiblecfg.yaml\n    ansible-playbook -f 10 ./ocpp/updateansiblecfg.yaml\nfi\n\n# Create certificate files \n\nif [[ \"${CUSTOMMASTERCERTTYPE}\" == \"custom\" ]]\nthen\n    echo $(date) \" - Creating custom master certificate files\"\n    runuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERCAFILE}\\\" > /tmp/masterca.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERCERTFILE}\\\" > /tmp/mastercert.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMMASTERKEYFILE}\\\" > /tmp/masterkey.pem\"\n\techo $(date) \" - Custom master certificate files masterca.pem, mastercert.pem, masterkey.pem created in /tmp\"\nfi\n\nif [ \"${CUSTOMROUTINGCERTTYPE}\" == \"custom\" ]\nthen\n    echo $(date) \" - Creating custom routing certificate files\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGCAFILE}\\\" > /tmp/routingca.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGCERTFILE}\\\" > /tmp/routingcert.pem\"\n\trunuser -l ${SUDOUSER} -c \"echo \\\"${CUSTOMROUTINGKEYFILE}\\\" > /tmp/routingkey.pem\"\n\techo $(date) \" - Custom routing certificate files routingca.pem, routingcert.pem, routingkey.pem created in /tmp\"\nfi\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n", "num_lines": 199}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Script\"\n\nset -e\n\nexport SUDOUSER=${SUDOUSER}\nexport PASSWORD=${PASSWORD}\nexport MASTER=${MASTER}\nexport MASTERPUBLICIPHOSTNAME=${MASTERPUBLICIPHOSTNAME}\nexport MASTERPUBLICIPADDRESS=${MASTERPUBLICIPADDRESS}\nexport INFRA=${INFRA}\nexport NODE=${NODE}\nexport NODECOUNT=${NODECOUNT}\nexport INFRACOUNT=${INFRACOUNT}\nexport MASTERCOUNT=${MASTERCOUNT}\nexport ROUTING=${ROUTING}\nexport REGISTRYSA=${REGISTRYSA}\nexport ACCOUNTKEY=${ACCOUNTKEY}\nexport METRICS=${METRICS}\nexport LOGGING=${LOGGING}\nexport TENANTID=${TENANTID}\nexport SUBSCRIPTIONID=${SUBSCRIPTIONID}\nexport AADCLIENTID=${AADCLIENTID}\nexport AADCLIENTSECRET=${AADCLIENTSECRET}\nexport RESOURCEGROUP=${RESOURCEGROUP}\nexport LOCATION=${LOCATION}\nexport AZURE=${AZURE}\nexport STORAGEKIND=${STORAGEKIND}\nexport ENABLECNS=${ENABLECNS}\nexport CNS=${CNS}\nexport CNSCOUNT=${CNSCOUNT}\nexport VNETNAME=${VNETNAME}\nexport NODENSG=${NODENSG}\nexport NODEAVAILIBILITYSET=${NODEAVAILIBILITYSET}\nexport MASTERCLUSTERTYPE=${MASTERCLUSTERTYPE}\nexport PRIVATEIP=${PRIVATEIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRAPIPNAME=${INFRAPIPNAME}\nexport CUSTOMROUTINGCERTTYPE=${CUSTOMROUTINGCERTTYPE}\nexport CUSTOMMASTERCERTTYPE=${CUSTOMMASTERCERTTYPE}\nexport MINORVERSION=${MINORVERSION}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\nexport DOCKERREGISTRYREALM=${DOCKERREGISTRYREALM} #\n# export CLOUDNAME=${CLOUDNAME} # for AAD\nexport BASTION=$(hostname)\n\n# Set CNS to default storage type.  Will be overridden later if Azure is true\nexport CNS_DEFAULT_STORAGE=true\n\n# Setting DOMAIN variable\nexport DOMAIN=`domainname -d`\n\n# Determine if Commercial Azure or Azure Government\n# CLOUD=$( curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/location?api-version=2017-04-02&format=text\" | cut -c 1-2 )\nexport CLOUD=${CLOUD^^}\n# export CLOUDNAME=\"AzureUSGovernmentCloud\"\n# export CLOUDNAME=\"AzurePublicCloud\"\n\nexport MASTERLOOP=$((MASTERCOUNT - 1))\nexport INFRALOOP=$((INFRACOUNT - 1))\nexport NODELOOP=$((NODECOUNT - 1))\n\necho $(date) \" - Configuring SSH ControlPath to use shorter path name\"\n\nsed -i -e \"s/^# control_path = %(directory)s\\/%%h-%%r/control_path = %(directory)s\\/%%h-%%r/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#host_key_checking = False/host_key_checking = False/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#pty=False/pty=False/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#stdout_callback = skippy/stdout_callback = skippy/\" /etc/ansible/ansible.cfg\nsed -i -e \"s/^#pipelining = False/pipelining = True/\" /etc/ansible/ansible.cfg\n\n# echo $(date) \" - Modifying sudoers\"\nsed -i -e \"s/Defaults    requiretty/# Defaults    requiretty/\" /etc/sudoers\nsed -i -e '/Defaults    env_keep += \"LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY\"/aDefaults    env_keep += \"PATH\"' /etc/sudoers\n\n# Setting the default openshift_cloudprovider_kind if Azure enabled\nif [[ ${AZURE} == \"true\" ]]\nthen\n    CLOUDKIND=\"openshift_cloudprovider_kind=azure\nopenshift_cloudprovider_azure_client_id=${AADCLIENTID}\nopenshift_cloudprovider_azure_client_secret=${AADCLIENTSECRET}\nopenshift_cloudprovider_azure_tenant_id=${TENANTID}\nopenshift_cloudprovider_azure_subscription_id=${SUBSCRIPTIONID}\nopenshift_cloudprovider_azure_cloud=${CLOUDNAME}\nopenshift_cloudprovider_azure_vnet_name=${VNETNAME}\nopenshift_cloudprovider_azure_security_group_name=${NODENSG}\nopenshift_cloudprovider_azure_availability_set_name=${NODEAVAILIBILITYSET}\nopenshift_cloudprovider_azure_resource_group=${RESOURCEGROUP}\nopenshift_cloudprovider_azure_location=${LOCATION}\"\n\tCNS_DEFAULT_STORAGE=false\n\tif [[ ${STORAGEKIND} == \"managed\" ]]\n\tthen\n\t\tSCKIND=\"openshift_storageclass_parameters={'kind': 'managed', 'storageaccounttype': 'Premium_LRS'}\"\n\telse\n\t\tSCKIND=\"openshift_storageclass_parameters={'kind': 'shared', 'storageaccounttype': 'Premium_LRS'}\"\n\tfi\nfi\n\n# Cloning Ansible playbook repository\n\necho $(date) \" - Cloning Ansible playbook repository\"\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    #Connected use this:\n    ((cd /home/${SUDOUSER} && git clone https://github.com/Microsoft/openshift-container-platform-playbooks.git) || (cd /home/${SUDOUSER}/openshift-container-platform-playbooks && git pull))\nelse\n    #Disconnected use this:\n    cd /home/${SUDOUSER} && wget -r -np ${REPOSERVER}/ocpp/\n    [ -d /home/${SUDOUSER}/openshift-container-platform-playbooks ] && rm -rf /home/${SUDOUSER}/openshift-container-platform-playbooks\n    mv /home/${SUDOUSER}/${REPOSERVER}/ocpp /home/${SUDOUSER}/openshift-container-platform-playbooks\n    [ -d /home/${SUDOUSER}/${REPOSERVER} ] && rm -rf /home/${SUDOUSER}/${REPOSERVER}\n    cd /home/${SUDOUSER}/openshift-container-platform-playbooks\nfi\n\nif [ -d /home/${SUDOUSER}/openshift-container-platform-playbooks ]\nthen\n    echo \" - Retrieved playbooks successfully\"\nelse\n    echo \" - Retrieval of playbooks failed\"\n    exit 7\nfi\n\n# Configure custom routing certificate\necho $(date) \" - Create variable for routing certificate based on certificate type\"\nif [[ ${CUSTOMROUTINGCERTTYPE} == \"custom\" ]]\nthen\n\tROUTINGCERTIFICATE=\"openshift_hosted_router_certificate={\\\"cafile\\\": \\\"/tmp/routingca.pem\\\", \\\"certfile\\\": \\\"/tmp/routingcert.pem\\\", \\\"keyfile\\\": \\\"/tmp/routingkey.pem\\\"}\"\nelse\n\tROUTINGCERTIFICATE=\"\"\nfi\n\n\n# Configure master cluster address information based on Cluster type (private or public)\necho $(date) \" - Create variable for master cluster address based on cluster type\"\nif [[ ${MASTERCLUSTERTYPE} == \"private\" ]]\nthen\n    MASTERCLUSTERHOSTNAME=${PRIVATEDNS}\n\tMASTERCLUSTERADDRESS=\"openshift_master_cluster_hostname=${MASTER}-001v\nopenshift_master_cluster_public_hostname=${PRIVATEDNS}\nopenshift_master_cluster_public_vip=${PRIVATEIP}\"\nelse\n    MASTERCLUSTERHOSTNAME=${MASTERPUBLICIPHOSTNAME}\n\tMASTERCLUSTERADDRESS=\"openshift_master_cluster_hostname=${MASTERPUBLICIPHOSTNAME}\nopenshift_master_cluster_public_hostname=${MASTERPUBLICIPHOSTNAME}\nopenshift_master_cluster_public_vip=${MASTERPUBLICIPADDRESS}\"\nfi\n\n# Configure custom master API certificate\necho $(date) \" - Create variable for master api certificate based on certificate type\"\nif [[ ${CUSTOMMASTERCERTTYPE} == \"custom\" ]]\nthen\n\tMASTERCERTIFICATE=\"openshift_master_overwrite_named_certificates=true\nopenshift_master_named_certificates=[{\\\"names\\\": [\\\"${MASTERCLUSTERHOSTNAME}\\\"], \\\"cafile\\\": \\\"/tmp/masterca.pem\\\", \\\"certfile\\\": \\\"/tmp/mastercert.pem\\\", \\\"keyfile\\\": \\\"/tmp/masterkey.pem\\\"}]\"\nelse\n\tMASTERCERTIFICATE=\"\"\nfi\n\n# Create Master nodes grouping\necho $(date) \" - Creating Master nodes grouping\"\nMASTERLIST=\"00${MASTERCOUNT}\"\nfor c in $(seq -f \"%03g\" 1 ${MASTERCOUNT})\ndo\n    mastergroup=\"$mastergroup\n${MASTER}-${c}v openshift_node_group_name='node-config-master'\"\ndone\n\n# Create Infra nodes grouping \necho $(date) \" - Creating Infra nodes grouping\"\nfor c in $(seq -f \"%03g\" 1 ${INFRACOUNT})\ndo\n    infragroup=\"$infragroup\n${INFRA}-${c}v openshift_node_group_name='node-config-infra'\"\ndone\n\n# Create Nodes grouping\necho $(date) \" - Creating Nodes grouping\"\nfor c in $(seq -f \"%03g\" 1 ${NODECOUNT})\ndo\n    nodegroup=\"$nodegroup\n${NODE}-${c}v openshift_node_group_name='node-config-compute'\"\ndone\n\n# Create CNS nodes grouping if CNS is enabled\nif [[ ${ENABLECNS} == \"true\" ]]\nthen\n    echo $(date) \" - Creating CNS nodes grouping\"\n\n    for c in $(seq -f \"%03g\" 1 ${CNSCOUNT})\n    do\n        cnsgroup=\"$cnsgroup\n${CNS}-${c}v openshift_node_group_name='node-config-compute'\"\n    done\nfi\n\n# Setting the HA Mode if more than one master\nif [ ${MASTERCOUNT} != 1 ]\nthen\n\techo $(date) \" - Enabling HA mode for masters\"\n    export HAMODE=\"openshift_master_cluster_method=native\"\nfi\n\n# Create Temp Ansible Hosts File\necho $(date) \" - Create Ansible Hosts file\"\n\ncat > /etc/ansible/hosts <<EOF\n[tempnodes]\n$mastergroup\n$infragroup\n$nodegroup\n$cnsgroup\nEOF\n\n# Run a loop playbook to ensure DNS Hostname resolution is working prior to continuing with script\necho $(date) \" - Running DNS Hostname resolution check\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook ~/openshift-container-platform-playbooks/check-dns-host-name-resolution.yaml\"\n\n# Create glusterfs configuration if CNS is enabled\nif [[ ${ENABLECNS} == \"true\" ]]\nthen\n    echo $(date) \" - Creating glusterfs configuration\"\n\n\t# Ensuring selinux is configured properly\n    echo $(date) \" - Setting selinux to allow gluster-fuse access\"\n    runuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -a 'sudo setsebool -P virt_sandbox_use_fusefs on'\" || true\n\trunuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -a 'sudo setsebool -P virt_use_fusefs on'\" || true\n\n    for c in $(seq -f \"%03g\" 1 ${CNSCOUNT})\n    do\n        runuser ${SUDOUSER} -c \"ssh-keyscan -H ${CNS}-${c}v >> ~/.ssh/known_hosts\"\n        drive=$(runuser ${SUDOUSER} -c \"ssh ${CNS}-${c}v 'sudo /usr/sbin/fdisk -l'\" | awk '$1 == \"Disk\" && $2 ~ /^\\// && ! /mapper/ {if (drive) print drive; drive = $2; sub(\":\", \"\", drive);} drive && /^\\// {drive = \"\"} END {if (drive) print drive;}')\n        drive1=$(echo $drive | cut -d ' ' -f 1)\n        drive2=$(echo $drive | cut -d ' ' -f 2)\n        drive3=$(echo $drive | cut -d ' ' -f 3)\n        cnsglusterinfo=\"$cnsglusterinfo\n${CNS}-${c}v glusterfs_devices='[ \\\"${drive1}\\\", \\\"${drive2}\\\", \\\"${drive3}\\\" ]'\"\n    done\n\n    HOSTEDREGISTRYVALS=\"openshift_hosted_registry_storage_kind=glusterfs\nopenshift_hosted_registry_storage_volume_size=20Gi\nopenshift_hosted_registry_selector='node-role.kubernetes.io/infra=true'\"\n\nelse\n\n    HOSTEDREGISTRYVALS=\"openshift_hosted_registry_storage_kind=object\nopenshift_hosted_registry_storage_provider=azure_blob\nopenshift_hosted_registry_storage_azure_blob_accountname=${REGISTRYSA}\nopenshift_hosted_registry_storage_azure_blob_accountkey=${ACCOUNTKEY}\nopenshift_hosted_registry_storage_azure_blob_container=registry\nopenshift_hosted_registry_storage_azure_blob_realm=$DOCKERREGISTRYREALM\"\n\nfi\n\n# Create Ansible Hosts File\necho $(date) \" - Create Ansible Hosts file\"\n\ncat > /etc/ansible/hosts <<EOF\n# Create an OSEv3 group that contains the masters and nodes groups\n[OSEv3:children]\nmasters\nnodes\netcd\nmaster0\nglusterfs\nglusterfs_registry\nnew_nodes\n\n# Set variables common for all OSEv3 hosts\n[OSEv3:vars]\nansible_ssh_user=${SUDOUSER}\nansible_become=yes\nopenshift_install_examples=true\ndeployment_type=openshift-enterprise\nopenshift_release=v3.11\nopenshift_image_tag=v3.11.${MINORVERSION}\nopenshift_pkg_version=-3.11.${MINORVERSION}\ndocker_udev_workaround=True\nopenshift_use_dnsmasq=true\nopenshift_master_default_subdomain=${ROUTING}\nopenshift_override_hostname_check=true\nosm_use_cockpit=true\nos_sdn_network_plugin_name='redhat/openshift-ovs-multitenant'\nopenshift_master_api_port=443\nopenshift_master_console_port=443\nosm_default_node_selector='node-role.kubernetes.io/compute=true'\nopenshift_disable_check=memory_availability,docker_image_availability\n$CLOUDKIND\n$SCKIND\n$CUSTOMCSS\n$ROUTINGCERTIFICATE\n$MASTERCERTIFICATE\n$PROXY\n\n# Workaround for docker image failure\n# https://access.redhat.com/solutions/3480921\noreg_url=${REGISTRYSERVER}/openshift3/ose-\\${component}:\\${version}\nopenshift_examples_modify_imagestreams=true\n\n# default selectors for router and registry services\nopenshift_router_selector='node-role.kubernetes.io/infra=true'\nopenshift_registry_selector='node-role.kubernetes.io/infra=true'\n\n# Configure registry not to use Azure blob storage\nopenshift_hosted_registry_replicas=1\n$HOSTEDREGISTRYVALS\n\n# Deploy Service Catalog\nopenshift_enable_service_catalog=false\n\n# Type of clustering being used by OCP\n$HAMODE\n\n# Addresses for connecting to the OpenShift master nodes\n$MASTERCLUSTERADDRESS\n\n# Enable HTPasswdPasswordIdentityProvider\nopenshift_master_identity_providers=[{'name': 'htpasswd_auth', 'login': 'true', 'challenge': 'true', 'kind': 'HTPasswdPasswordIdentityProvider'}]\n\n# Specify CNS images\nopenshift_storage_glusterfs_image=${REGISTRYSERVER}/rhgs3/rhgs-server-rhel7:v3.11\nopenshift_storage_glusterfs_block_image=${REGISTRYSERVER}/rhgs3/rhgs-gluster-block-prov-rhel7:v3.11\nopenshift_storage_glusterfs_s3_image=${REGISTRYSERVER}/rhgs3/rhgs-s3-server-rhel7:v3.11\nopenshift_storage_glusterfs_heketi_image=${REGISTRYSERVER}/rhgs3/rhgs-volmanager-rhel7:v3.11\n\n# Setup metrics\nopenshift_metrics_install_metrics=$METRICS\nopenshift_metrics_start_cluster=$METRICS\nopenshift_metrics_hawkular_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_metrics_cassandra_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_metrics_heapster_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\n\n# Setup logging\nopenshift_logging_install_logging=$LOGGING\nopenshift_logging_fluentd_nodeselector={\"logging\":\"true\"}\nopenshift_logging_es_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_kibana_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_curator_nodeselector={\"node-role.kubernetes.io/infra\":\"true\"}\nopenshift_logging_master_public_url=https://${MASTERCLUSTERHOSTNAME}\n\n# host group for masters\n[masters]\n${MASTER}-[001:${MASTERLIST}]v\n\n# host group for etcd\n[etcd]\n${MASTER}-[001:${MASTERLIST}]v\n\n[master0]\n${MASTER}-001v\n\n# Only populated when CNS is enabled\n[glusterfs]\n$cnsglusterinfo\n\n[glusterfs_registry]\n$cnsglusterinfo\n\n# host group for nodes\n[nodes]\n$mastergroup\n$infragroup\n$nodegroup\n$cnsgroup\n\n# host group for adding new nodes\n[new_nodes]\nEOF\n\n# Update WALinuxAgent\necho $(date) \" - Updating WALinuxAgent on all cluster nodes\"\nrunuser ${SUDOUSER} -c \"ansible all -f 30 -b -m yum -a 'name=WALinuxAgent state=latest'\"\n\n# Setup NetworkManager to manage eth0\necho $(date) \" - Running NetworkManager playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-node/network_manager.yml\"\n\n# Configure DNS so it always has the domain name\necho $(date) \" - Adding $DOMAIN to search for resolv.conf\"\nrunuser ${SUDOUSER} -c \"ansible all -o -f 30 -b -m lineinfile -a 'dest=/etc/sysconfig/network-scripts/ifcfg-eth0 line=\\\"DOMAIN=$DOMAIN\\\"'\"\n\n# Configure resolv.conf on all hosts through NetworkManager\necho $(date) \" - Restarting NetworkManager\"\nrunuser -l ${SUDOUSER} -c \"ansible all -o -f 30 -b -m service -a \\\"name=NetworkManager state=restarted\\\"\"\necho $(date) \" - NetworkManager configuration complete\"\n\n# Restarting things so everything is clean before continuing with installation\necho $(date) \" - Rebooting cluster to complete installation\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/reboot-master.yaml\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/reboot-nodes.yaml\"\nsleep 20\n\n# Run OpenShift Container Platform prerequisites playbook\necho $(date) \" - Running Prerequisites via Ansible Playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/prerequisites.yml\"\necho $(date) \" - Prerequisites check complete\"\n\n# Initiating installation of OpenShift Container Platform using Ansible Playbook\necho $(date) \" - Installing OpenShift Container Platform via Ansible Playbook\"\nrunuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 /usr/share/ansible/openshift-ansible/playbooks/deploy_cluster.yml\"\nif [ $? -eq 0 ]\nthen\n    echo $(date) \" - OpenShift Cluster installed successfully\"\nelse\n    echo $(date) \" - OpenShift Cluster failed to install\"\n    exit 6\nfi\n\n# Install OpenShift Atomic Client\ncd /root\nmkdir .kube\nrunuser ${SUDOUSER} -c \"scp -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null ${SUDOUSER}@${MASTER}-001v:~/.kube/config /tmp/kube-config\"\ncp /tmp/kube-config /root/.kube/config\nmkdir /home/${SUDOUSER}/.kube\ncp /tmp/kube-config /home/${SUDOUSER}/.kube/config\nchown --recursive ${SUDOUSER} /home/${SUDOUSER}/.kube\nrm -f /tmp/kube-config\nyum -y install atomic-openshift-clients\n\n# Adding user to OpenShift authentication file\necho $(date) \" - Adding OpenShift user\"\nrunuser ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/addocpuser.yaml\"\n\n# Assigning cluster admin rights to OpenShift user\necho $(date) \" - Assigning cluster admin rights to user\"\nrunuser ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/assignclusteradminrights.yaml\"\n\n# Installing Service Catalog, Ansible Service Broker and Template Service Broker\nif [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\nthen\n    runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_enable_service_catalog=true -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-service-catalog/config.yml\"\nfi\n\n# Adding Open Sevice Broker for Azaure (requires service catalog)\n# Disabling deployment of OSBA\nif [[ ${AZURE} == \"true\" ]]\nthen\n    oc new-project osba\n    oc process -f https://raw.githubusercontent.com/Azure/open-service-broker-azure/master/contrib/openshift/osba-os-template.yaml  \\\n        -p ENVIRONMENT=AzurePublicCloud \\\n        -p AZURE_SUBSCRIPTION_ID=${SUBSCRIPTIONID} \\\n        -p AZURE_TENANT_ID=${TENANTID} \\\n        -p AZURE_CLIENT_ID=${AADCLIENTID} \\\n        -p AZURE_CLIENT_SECRET=${AADCLIENTSECRET} \\\n        | oc create -f -\nfi\n\n# Configure Metrics\nif [[ ${METRICS} == \"true\" ]]\nthen\n    sleep 30\n    echo $(date) \"- Deploying Metrics\"\n    if [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\n    then\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_metrics_install_metrics=True -e openshift_metrics_cassandra_storage_type=dynamic -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-metrics/config.yml\"\n    else\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_metrics_install_metrics=True /usr/share/ansible/openshift-ansible/playbooks/openshift-metrics/config.yml\"\n    fi\n    if [ $? -eq 0 ]\n    then\n        echo $(date) \" - Metrics configuration completed successfully\"\n    else\n        echo $(date) \" - Metrics configuration failed\"\n        exit 11\n    fi\nfi\n\n# Configure Logging\n\nif [[ ${LOGGING} == \"true\" ]]\nthen\n    sleep 60\n    echo $(date) \"- Deploying Logging\"\n    if [[ ${AZURE} == \"true\" || ${ENABLECNS} == \"true\" ]]\n    then\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_logging_install_logging=True -e openshift_logging_es_pvc_dynamic=true -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-logging/config.yml\"\n    else\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -e openshift_logging_install_logging=True -f 30 /usr/share/ansible/openshift-ansible/playbooks/openshift-logging/config.yml\"\n    fi\n    if [ $? -eq 0 ]\n    then\n        echo $(date) \" - Logging configuration completed successfully\"\n    else\n        echo $(date) \" - Logging configuration failed\"\n        exit 12\n    fi\nfi\n\nif [[ ${AZURE} == \"true\" ]]\nthen\n    # Creating variables file for private master and Azure AD configuration playbook\n    echo $(date) \" - Creating variables file for future playbooks\"\ncat > /home/${SUDOUSER}/openshift-container-platform-playbooks/vars.yaml <<EOF\nadmin_user: $SUDOUSER\nmaster_lb_private_dns: $PRIVATEDNS\ndomain: $DOMAIN\nEOF\n\n    # Configure cluster for private masters\n    if [[ ${MASTERCLUSTERTYPE} == \"private\" ]]\n    then\n        echo $(date) \" - Configure cluster for private masters\"\n        runuser -l ${SUDOUSER} -c \"ansible-playbook -f 30 ~/openshift-container-platform-playbooks/activate-private-lb-fqdn.31x.yaml\"\n    fi\nfi\n\n# Delete yaml files\necho $(date) \" - Deleting unecessary files\"\nrm -rf /home/${SUDOUSER}/openshift-container-platform-playbooks\n\n# Delete pem files\necho $(date) \" - Delete pem files\"\nrm -rf /tmp/*.pem\n\necho $(date) \" - Sleep for 15 seconds\"\nsleep 15\n\necho $(date) \" - Script complete\"\n\n# *.apps.beta-openshift.com == 10.3.101.200\n# *.console.beta-openshift.com == 10.3.101.100\n\n\n# address=/console.dev-openshift.com/10.3.104.100\n# address=/apps.dev-openshift.com/10.3.104.200\n", "num_lines": 525}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Node Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n    sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n    echo \"Pool attached successfully\"\n    else\n    grep attached attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n    else\n        echo \"Incorrect Pool ID or no entitlements available\"\n        exit 4\n    fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\n    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo\n    # mv -f ose.repo /etc/yum.repos.d/ose.repo\n\n    # disconnected\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct\nyum -y install cloud-utils-growpart.noarch\nyum -y install ansible\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\n# echo \"\n# # Adding insecure-registry option required by OpenShift\n# OPTIONS=\\\"\\$OPTIONS --insecure-registry 10.3.103.5:5000\\\"\n# \" >> /etc/sysconfig/docker\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and starting service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n    echo \"Docker thin pool logical volume created successfully\"\nelse\n    echo \"Error creating logical volume for Docker\"\n    exit 5\nfi\n\n# Enable and start Docker services\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n\n", "num_lines": 167}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Master Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n    fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\n    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo\n    # mv -f ose.repo /etc/yum.repos.d/ose.repo\n\n    # disconnected\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible\n\n#um -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion httpd-tools kexec-tools sos psacct ansible\n\nyum -y install cloud-utils-growpart.noarch\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo \"Root partition expanded\"\nelse\n    echo \"Root partition failed to expand\"\n    exit 6\nfi\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker \n\n# Update docker config for insecure registry\n# echo \"\n# # Adding insecure-registry option required by OpenShift\n# OPTIONS=\\\"\\$OPTIONS --insecure-registry 10.3.103.5:5000\\\"\n# \" >> /etc/sysconfig/docker\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and staring service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n   echo \"Docker thin pool logical volume created successfully\"\nelse\n   echo \"Error creating logical volume for Docker\"\n   exit 5\nfi\n\n# Enable and start Docker services\nsysctl -w vm.max_map_count=262144\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n", "num_lines": 177}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $(date) \" - Starting Infra / Node Prep Script\"\n\nexport USERNAME_ORG=${USERNAME_ORG}\nexport PASSWORD_ACT_KEY=${PASSWORD_ACT_KEY}\nexport POOL_ID=${POOL_ID}\nexport REPOSERVER=${REPOSERVER}\nexport REGISTRYSERVER=${REGISTRYSERVER}\nexport PRIVATEIP=${PRIVATEIP}\nexport ROUTERIP=${ROUTERIP}\nexport PRIVATEDNS=${PRIVATEDNS}\nexport INFRADNS=${INFRADNS}\nexport DEPLOYMENTTYPE=${DEPLOYMENTTYPE}\n\n# Remove RHUI\n\nrm -f /etc/yum.repos.d/*.repo\nsleep 10\n\nif [[ ${DEPLOYMENTTYPE} == 3 ]]\nthen\n    # connected\n    # Register Host with Cloud Access Subscription\n    echo $(date) \" - Register host with Cloud Access Subscription\"\n\n    subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n    RETCODE=$?\n\n    if [ $RETCODE -eq 0 ]\n    then\n        echo \"Subscribed successfully\"\n    elif [ $RETCODE -eq 64 ]\n    then\n        echo \"This system is already registered.\"\n    else\n        sleep 5\n        subscription-manager register --force --username=\"${USERNAME_ORG}\" --password=\"${PASSWORD_ACT_KEY}\" || subscription-manager register --force --activationkey=\"${PASSWORD_ACT_KEY}\" --org=\"${USERNAME_ORG}\"\n        RETCODE2=$?\n        if [ $RETCODE2 -eq 0 ]\n        then\n            echo \"Subscribed successfully\"\n        elif [ $RETCODE2 -eq 64 ]\n        then\n            echo \"This system is already registered.\"\n        else\n            echo \"Incorrect Username / Password or Organization ID / Activation Key specified. Unregistering system from RHSM\"\n            subscription-manager unregister\n            exit 3\n        fi\n    fi\n\n    subscription-manager attach --pool=${POOL_ID} > attach.log\n    if [ $? -eq 0 ]\n    then\n        echo \"Pool attached successfully\"\n    else\n        grep attached attach.log\n        if [ $? -eq 0 ]\n        then\n            echo \"Pool ${POOL_ID} was already attached and was not attached again.\"\n        else\n            echo \"Incorrect Pool ID or no entitlements available\"\n            exit 4\n        fi\n    fi\n\n    # Disable all repositories and enable only the required ones\n    echo $(date) \" - Disabling all repositories and enabling only the required repos\"\n\n    subscription-manager repos --disable=\"*\"\n\n    subscription-manager repos \\\n        --enable=\"rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-extras-rpms\" \\\n        --enable=\"rhel-7-server-ose-3.11-rpms\" \\\n        --enable=\"rhel-7-server-ansible-2.6-rpms\" \\\n        --enable=\"rhel-7-fast-datapath-rpms\" \\\n        --enable=\"rh-gluster-3-client-for-rhel-7-server-rpms\" \\\n        --enable=\"rhel-7-server-optional-rpms\"\nelse\n\n    # wget http://10.3.101.17/ocp-3-11-single-subnet/scripts/ose.repo\n    # mv -f ose.repo /etc/yum.repos.d/ose.repo\n\n    # disconnected\ncat > /etc/yum.repos.d/ose.repo <<EOF\n[rhel-7-repo]\nname=rhel-7-repo\nbaseurl=http://${REPOSERVER}/repos\nenabled=1\ngpgcheck=0\nEOF\n\nfi\n\n# Install base packages and update system to latest packages\necho $(date) \" - Install base packages and update system to latest packages\"\n\nyum -y install wget git net-tools bind-utils iptables-services bridge-utils bash-completion kexec-tools sos psacct ansible\nyum -y install cloud-utils-growpart.noarch\nyum -y update glusterfs-fuse\nyum -y update --exclude=WALinuxAgent\necho $(date) \" - Base package insallation and updates complete\"\n\n# Grow Root File System\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo \"Root partition expanded\"\nelse\n    echo \"Root partition failed to expand\"\n    exit 6\nfi\n\n# Install Docker\necho $(date) \" - Installing Docker\"\nyum -y install docker\n\n# Update docker config for insecure registry\n# echo \"\n# # Adding insecure-registry option required by OpenShift\n# OPTIONS=\\\"\\${OPTIONS} --insecure-registry 10.3.103.5:5000\\\"\n# \" >> /etc/sysconfig/docker\nrm -f /etc/docker/daemon.json\ncat > /etc/docker/daemon.json <<EOF \n{\n  \"insecure-registries\" : [\"${REGISTRYSERVER}\",\"docker-registry-default.${INFRADNS}\"]\n}\nEOF\n\n# Create thin pool logical volume for Docker\necho $(date) \" - Creating thin pool logical volume for Docker and staring service\"\n\nDOCKERVG=$( parted -m /dev/sda print all 2>/dev/null | grep unknown | grep /dev/sd | cut -d':' -f1 | head -n1 )\n\necho \"\n# Adding OpenShift data disk for docker\nDEVS=${DOCKERVG}\nVG=docker-vg\n\" >> /etc/sysconfig/docker-storage-setup\n\n# Running setup for docker storage\ndocker-storage-setup\nif [ $? -eq 0 ]\nthen\n    echo \"Docker thin pool logical volume created successfully\"\nelse\n    echo \"Error creating logical volume for Docker\"\n    exit 5\nfi\n\n# Enable and start Docker services\nsysctl -w vm.max_map_count=262144\n\nsystemctl enable docker\nsystemctl start docker\n\n# Add DNS host entries for cluster naming\ncat >> /etc/hosts <<EOF\n${PRIVATEIP} ${PRIVATEDNS}\n${ROUTERIP} ${INFRADNS}\nEOF\n\necho $(date) \" - Script Complete\"\n\n", "num_lines": 175}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\n# only run once during deployment\nif [ -f ./azAutomationComplete ]; then\n    echo \"STIG Automation completed, exiting...\"\n    exit 0\nfi\n\n# https://docs.microsoft.com/en-us/azure/virtual-machines/workloads/redhat/redhat-rhui\nid=$(. /etc/os-release && echo $ID)\nif [ ${id} == 'rhel' ]; then\n    echo \"Executing yum update to disable all repos and enable all microsoft repos...\"\n    yum update -y --disablerepo='*' --enablerepo='*microsoft*' > ./yumupdateresults.log\nfi\n\n# dsc deployment automation\necho \"Move (OS Specific) .mof to configuration store as Pending.mof...\"\nmv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof\necho \"Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly...\"\n/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log\necho \"Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration...\"\n/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log\nif grep -q \"MI_RESULT_FAILED\" ./dscresults.log; then\n    echo \"Failed to apply Desired State Configuration successfully, check dscresults.log for more details...\"\n    exit 1\nelse\n    echo \"Applied Desired State Configuration successfully...\"\nfi\n\n# authentication/password/session automation\necho \"Backing up password-auth, postlogin and system-auth files...\"\ncp --force /etc/pam.d/system-auth /etc/pam.d/backup.system-auth\ncp --force /etc/pam.d/password-auth /etc/pam.d/backup.password-auth\ncp --force /etc/pam.d/postlogin /etc/pam.d/backup.postlogin\necho \"Removing 'nullok' from password-auth and system-auth files...\"\nsed -i 's/nullok //g' /etc/pam.d/system-auth /etc/pam.d/password-auth\necho \"Updating auth pam_faillock.so module in password-auth and system-auth files...\"\nauthRequiredFailDelay='auth        required      pam_faildelay.so delay=2000000'\nauthRequiredFaillock='auth        required      pam_faillock.so preauth silent audit deny=3 even_deny_root fail_interval=900 unlock_time=900'\nauthDefaultFaillock='auth        [default=die] pam_faillock.so authfail audit deny=3 even_deny_root fail_interval=900 unlock_time=900'\nsed -i \"s/\\(auth.*sufficient.*pam_fprintd.so\\)/${authRequiredFailDelay}/g\" /etc/pam.d/system-auth\nsed -i \"s/\\(auth.*delay.*2000000\\)/\\1\\n${authRequiredFaillock}/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\nsed -i \"s/\\(auth.*pam_unix.so.*\\)/\\1\\n${authDefaultFaillock}/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\necho \"Updating account pam_faillock.so module in password-auth and system-auth files...\"\nacctReqPamFaillock='account     required      pam_faillock.so'\nsed -i \"s/\\(account.*pam_unix\\.so\\)/${acctReqPamFaillock}\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\necho \"Updating password pam_pwhistory.so module in password-auth and system-auth files...\"\npassReqPamPwHistory='password    requisite     pam_pwhistory.so use_authtok remember=5 retry=3'\nsed -i \"s/\\(password.*requisite.*pam_pwquality\\.so.*\\)/\\1\\n${passReqPamPwHistory}/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\necho \"Updating session pam_lastlog.so module in /etc/pam.d/postlogin\"\nsessReqPamLastlog='session     required      pam_lastlog.so showfailed'\nsed -i \"s/\\(session.*quiet\\)/${sessReqPamLastlog}\\n\\1/g\" /etc/pam.d/postlogin\necho \"Removing 'NOPASSWD' tag from all files in /etc/sudoers.d/* /etc/sudoers\"\ngrep -r -l -i nopasswd /etc/sudoers.d/* /etc/sudoers | xargs sed -i 's/\\s*NOPASSWD://g'\necho \"Setting minimum number of days before password change for user specified admin account to 1\"\nchage -m 1 $1\necho \"Setting maximum number of days before password change for user specified admin account to 60\"\nchage -M 60 $1\n\n# file system automation\necho \"Setting /home mount to use nosuid in /etc/fstab...\"\nsed -i \"s/\\(.*\\/home.*defaults\\)/\\1,nosuid/g\" /etc/fstab\necho \"Setting tmpfs /dev/shm to mount using nodev, nosuid and noexec in /etc/fstab\"\necho 'tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0' >> /etc/fstab\n\n# fips automation\nif rpm -q --quiet \"dracut-fips\"; then\n    echo \"Recreating initramfs with dracut to support FIPS...\"\n    dracut --force --verbose 2> ./fipsresults.log\n    echo \"Modifying grub to support FIPS...\"\n    BOOT_UUID=$(findmnt --noheadings --output uuid --target /boot)\n    sed -i \"s/\\(GRUB_CMDLINE_LINUX=\\\".*[^\\\"]\\+\\)/\\1 fips=1 boot=UUID=${BOOT_UUID}/g\" /etc/default/grub\n    if [ -f /boot/grub2/grub.cfg ]; then\n        echo \"Regenerating /boot/grub2/grub.cfg (BIOS)...\"\n        grub2-mkconfig -o /boot/grub2/grub.cfg 2>> ./fipsresults.log\n    fi\n    if [ -f /boot/efi/EFI/centos/grub.cfg ]; then\n        echo \"Regenerating /boot/efi/EFI/centos/grub.cfg (UEFI)...\"\n        grub2-mkconfig -o /boot/efi/EFI/centos/grub.cfg 2>> ./fipsresults.log\n    elif [ -f /boot/efi/EFI/redhat/grub.cfg ]; then\n        echo \"Regenerating /boot/efi/EFI/redhat/grub.cfg (UEFI)...\"\n        grub2-mkconfig -o /boot/efi/EFI/redhat/grub.cfg 2>> ./fipsresults.log\n    else\n        echo \"Skipping grub2-mkconfig for UEFI, no EFI grub.cfg file found...\"\n    fi\nelse\n    echo \"Skipping fips automation due to dracut-fips package installation absence...\"\nfi\n\n# aide configuration automation\nif rpm -q --quiet \"aide\"; then\n    echo \"Modifying /etc/aide.conf to use sha512...\"\n    sed -i 's/CONTENT_EX = sha256/CONTENT_EX = sha512/g' /etc/aide.conf\n    echo \"Executing /usr/sbin/aide --init...\"\n    /usr/sbin/aide --init > aideresults.log\n    echo \"Moving /var/lib/aide/aide.db.new.gz to /var/lib/aide/aide.db.gz...\"\n    mv --verbose --force /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz\n    echo \"Adding aide daily check cron job...\"\n    echo '0 5 * * * root /usr/sbin/aide --check | /bin/mail -s \"$(hostname) - AIDE Integrity Check\" root@localhost' > /etc/cron.daily/aide\nelse\n    echo \"Skipping aide automation due to aide package installation absence...\"\nfi\n\n# system reboot\necho \"Rebooting to apply STIG settings...\"\ntouch ./azAutomationComplete\nshutdown -r +1 2>&1\n", "num_lines": 108}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "# only run once during deployment\nif [ -f ./azAutomationComplete ]; then\n    echo \"STIG Automation completed, exiting...\"\n    exit 0\nfi\n\n###############################################################################\necho \"Setting script variables\"\n###############################################################################\nversion=$(. /etc/os-release && echo $VERSION_ID)\n\n###############################################################################\necho \"Enabling Microsoft Repos\"\n###############################################################################\nyum update -y --disablerepo='*' --enablerepo='*microsoft*'\n\n###############################################################################\necho \"Automating Rule Id V-230233\"\n###############################################################################\nsed -i \"s/\\(password\\s*sufficient.*\\)/\\1 rounds=5000/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n# END V-230233\n\n###############################################################################\necho \"Automating Rule Id V-230234\"\n# SCAP fails if /boot/efi/EFI/redhat/grub.cfg exists on Gen 1 Azure VM\n###############################################################################\nfirmwarecheck=$([ -d /sys/firmware/efi ] && echo UEFI || echo BIOS)\nif [ $firmwarecheck = 'BIOS' ]; then\n    mv /boot/efi/EFI/redhat/grub.cfg /boot/efi/EFI/redhat/grub.bak\nfi\n# END V-230234\n\n###############################################################################\necho \"Automating Rule Id V-230253\"\n###############################################################################\nsed -i \"s/^SSH_USE_STRONG_RNG=.*/SSH_USE_STRONG_RNG=32/g\" /etc/sysconfig/sshd\n# END V-230253\n\n###############################################################################\necho \"Automating Rule Id V-230257\"\n###############################################################################\nfind -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin -perm /0022 -type f -exec chmod 0755 {} \\;\n# END V-230257\n\n###############################################################################\necho \"Automating Rule Id V-230271\"\n###############################################################################\ngrep -r -l -i nopasswd /etc/sudoers.d/* /etc/sudoers | xargs sed -i 's/\\s*NOPASSWD://g' 2>&1\n# END V-230271\n\n###############################################################################\necho \"Automating Rule Id V-230287\"\n###############################################################################\nchmod 0600 /etc/ssh/ssh_host*key\n# END V-230287\n\n###############################################################################\necho \"Automating Rule Id V-230301\"\n###############################################################################\nsed -i \"s/\\(.*[[:space:]]\\/[[:alpha:]].*defaults\\)/\\1,nodev/g\" /etc/fstab\n# END V-230301\n\n###############################################################################\necho \"Automating Rule Id V-230311\"\n###############################################################################\nrm -f /usr/lib/sysctl.d/50-coredump.conf\necho \"kernel.core_pattern = |/bin/false\" > /etc/sysctl.d/90-azurestig-v230311.conf\n# END V-230311\n\n###############################################################################\necho \"Automating Rule Ids V-230332, V-230334, V-230336, V-230338, V-230340, V-230342, V-230344\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    authRequired='auth        required'\n    acctRequired='account     required'\n    spacing='                                     '\n    authFaillockPreAuth='pam_faillock.so preauth dir=\\/var\\/log\\/faillock silent audit deny=3 even_deny_root fail_interval=900 unlock_time=0'\n    authFaillockAuthFail='pam_faillock.so authfail dir=\\/var\\/log\\/faillock unlock_time=0'\n    sed -i \"s/\\(auth.*pam_unix.so.*\\)/${authRequired}${spacing}${authFaillockPreAuth}\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n    sed -i \"s/\\(auth.*pam_unix.so.*\\)/\\1\\n${authRequired}${spacing}${authFaillockAuthFail}/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n    sed -i \"s/\\(account.*pam_unix.so\\)/${acctRequired}${spacing}pam_faillock.so\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\nelse\n    echo \"  Automation intended for 8.0 and 8.1; '$version' detected, skipping...\"\nfi\n# END V-230332, V-230334, V-230336, V-230338, V-230340, V-230342, V-230344\n\n###############################################################################\necho \"Automating Rule Id V-230333\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    authRequiredFaillock='auth        required      pam_faillock.so'\n    acctRequiredFaillock='account     required      pam_faillock.so'\n    sed -i \"s/\\(auth.*required.*pam_env.so\\)/\\1\\n${authRequiredFaillock} preauth/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n    sed -i \"s/\\(auth.*required.*pam_deny.so\\)/${authRequiredFaillock} authfail\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n    sed -i \"s/\\(account.*required.*pam_unix.so\\)/${acctRequiredFaillock}\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n    sed -i \"s/.*deny\\s*=.*/deny = 3/g\" /etc/security/faillock.conf\nfi\n# END V-230333\n\n###############################################################################\necho \"Automating Rule Id V-230335\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    sed -i \"s/.*fail_interval\\s*=.*/fail_interval = 900/g\" /etc/security/faillock.conf\nfi\n# END V-230335\n\n###############################################################################\necho \"Automating Rule Id V-230337\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    sed -i \"s/^\\(#\\|\\)[[:space:]]*unlock_time\\s*=.*/unlock_time = 0/g\" /etc/security/faillock.conf\nfi\n# END V-230337\n\n###############################################################################\necho \"Automating Rule Id V-230341\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    if grep -q -i silent /etc/security/faillock.conf; then\n        sed -i \"s/.*silent.*/silent/g\" /etc/security/faillock.conf\n    else\n        echo \"silent\" >> /etc/security/faillock.conf\n    fi\nfi\n# END V-230341\n\n###############################################################################\necho \"Automating Rule Id V-230343\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    if grep -q -i audit /etc/security/faillock.conf; then\n        sed -i \"s/.*audit.*/audit/g\" /etc/security/faillock.conf\n    else\n        echo \"audit\" >> /etc/security/faillock.conf\n    fi\nfi\n# END V-230343\n\n###############################################################################\necho \"Automating Rule Id V-230345\"\n###############################################################################\nif [ ${version} == '8.0' ] || [ ${version} == '8.1' ]; then\n    echo \"  Automation intended for 8.2 and newer, '$version' detected, skipping...\"\nelse\n    sed -i \"s/^\\(#\\|\\)[[:space:]]*even_deny_root.*/even_deny_root/g\" /etc/security/faillock.conf\nfi\n# END V-230345\n\n###############################################################################\necho \"Automating Rule Id V-230349\"\n###############################################################################\necho 'if [ \"$PS1\" ]; then' >> /etc/profile.d/230348-customshell.sh\necho 'parent=$(ps -o ppid= -p $$)' >> /etc/profile.d/230348-customshell.sh\necho 'name=$(ps -o comm= -p $parent)' >> /etc/profile.d/230348-customshell.sh\necho 'case \"$name\" in (sshd|login) exec tmux ;; esac' >> /etc/profile.d/230348-customshell.sh\necho 'fi' >> /etc/profile.d/230348-customshell.sh\n# END V-230349\n\n###############################################################################\necho \"Automating Rule Id V-230367\"\n###############################################################################\nchage -M 60 $1\nchage -M 60 root\n# END V-230367\n\n###############################################################################\necho \"Automating Rule Id V-230368\"\n###############################################################################\npasswordRequired='password    required'\nspacing='      '\npasswordReqPwHist='pam_pwhistory.so use_authtok remember=5 retry=3'\nsed -i \"s/\\(password.*pam_unix.so.*\\)/${passwordRequired}${spacing}${passwordReqPwHist}\\n\\1/g\" /etc/pam.d/password-auth /etc/pam.d/system-auth\n# END V-230368\n\n###############################################################################\necho \"Automating Rule Id V-230373\"\n###############################################################################\nuseradd -D -f 35\n# END V-230373\n\n###############################################################################\necho \"Automating Rule Id V-230380\"\n###############################################################################\nsed -i 's/\\s*nullok\\s*/ /g' /etc/pam.d/system-auth /etc/pam.d/password-auth\nsed -i \"s/.*PermitEmptyPasswords.*/PermitEmptyPasswords no/g\" /etc/ssh/sshd_config\n# END V-230380\n\n###############################################################################\necho \"Automating Rule Id V-230439\"\n###############################################################################\necho '-a always,exit -F arch=b32 -S rename,unlink,rmdir,renameat,unlinkat -F auid>=1000 -F auid!=unset -k delete' >> /etc/audit/rules.d/audit.rules\necho '-a always,exit -F arch=b64 -S rename,unlink,rmdir,renameat,unlinkat -F auid>=1000 -F auid!=unset -k delete' >> /etc/audit/rules.d/audit.rules\n# END V-230439\n\n###############################################################################\necho \"Automating Rule Id V-230485\"\n###############################################################################\nif ! grep -q -w 'port' /etc/chrony.conf; then\n    echo 'port 0' >> /etc/chrony.conf\nelse\n    sed -i 's/\\(^port\\|^#port\\).*/port 0/g' /etc/chrony.conf\nfi\n# END V-230485\n\n###############################################################################\necho \"Automating Rule Id V-230486\"\n###############################################################################\nif ! grep -q -w 'cmdport' /etc/chrony.conf; then\n    echo 'cmdport 0' >> /etc/chrony.conf\nelse\n    sed -i 's/\\(^cmdport\\|^#cmdport\\).*/cmdport 0/g' /etc/chrony.conf\nfi\n# END V-230486\n\n###############################################################################\necho \"Automating Rule Id V-230494\"\n###############################################################################\necho 'install atm /bin/true' > /etc/modprobe.d/atm.conf\necho 'blacklist atm' >> /etc/modprobe.d/blacklist.conf\n# END V-230494\n\n###############################################################################\necho \"Automating Rule Id V-230495\"\n###############################################################################\necho 'install can /bin/true' > /etc/modprobe.d/can.conf\necho 'blacklist can' >> /etc/modprobe.d/blacklist.conf\n# END V-230495\n\n###############################################################################\necho \"Automating Rule Id V-230496\"\n###############################################################################\necho 'install sctp /bin/true' > /etc/modprobe.d/sctp.conf\necho 'blacklist sctp' >> /etc/modprobe.d/blacklist.conf\n# END V-230496\n\n###############################################################################\necho \"Automating Rule Id V-230497\"\n###############################################################################\necho 'install tipc /bin/true' > /etc/modprobe.d/tipc.conf\necho 'blacklist tipc' >> /etc/modprobe.d/blacklist.conf\n# END V-230497\n\n###############################################################################\necho \"Automating Rule Id V-230498\"\n###############################################################################\necho 'install cramfs /bin/true' > /etc/modprobe.d/cramfs.conf\necho 'blacklist cramfs' >> /etc/modprobe.d/blacklist.conf\n# END V-230498\n\n###############################################################################\necho \"Automating Rule Id V-230499\"\n###############################################################################\necho 'install firewire-core /bin/true' > /etc/modprobe.d/firewire-core.conf\necho 'blacklist firewire-core' >> /etc/modprobe.d/blacklist.conf\n# END V-230499\n\n###############################################################################\necho \"Automating Rule Id V-230503\"\n###############################################################################\necho 'install usb-storage /bin/true' > /etc/modprobe.d/usb-storage.conf\necho 'blacklist usb-storage' >> /etc/modprobe.d/blacklist.conf\n# END V-230503\n\n###############################################################################\necho \"Automating Rule Id V-230507\"\n###############################################################################\necho 'install bluetooth /bin/true' > /etc/modprobe.d/bluetooth.conf\n# END V-230507\n\n###############################################################################\necho \"Automating Rule Ids V-230508, V-230509, V-230510\"\n###############################################################################\necho 'tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 0 0' >> /etc/fstab\n# END V-230508, V-230509, V-230510\n\n###############################################################################\necho \"Automating Rule Id V-230511, V-230512, V-230513\"\n###############################################################################\nsed -i 's/\\(\\/tmp.*\\)defaults.*/\\1defaults,nodev,nosuid,noexec 0 0/g' /etc/fstab\n# END V-230511, V-230512, V-230513\n\n###############################################################################\necho \"Automating Rule Id V-230546\"\n###############################################################################\nrm -f /usr/lib/sysctl.d/10-default-yama-scope.conf\nsysctl -w kernel.yama.ptrace_scope=1\necho \"kernel.yama.ptrace_scope = 1\" > /etc/sysctl.d/90-azurestig-v230546.conf\n# END V-230546\n\n###############################################################################\necho \"Automating Rule Id V-237642\"\n###############################################################################\necho 'Defaults !targetpw' >> /etc/sudoers.d/237642\necho 'Defaults !rootpw' >> /etc/sudoers.d/237642\necho 'Defaults !runaspw' >> /etc/sudoers.d/237642\n# END V-237642\n\n###############################################################################\necho \"Installing Ansible for STIG automation (pip3 install)...\"\n###############################################################################\npip3 install ansible --user\n\n###############################################################################\necho \"Unzipping rhel8STIG-ansible.zip to ./rhel8STIG\"\n###############################################################################\nunzip rhel8STIG-ansible.zip -d ./rhel8STIG\n\n###############################################################################\necho \"Invoking ansible-playbook to automate STIG rules\"\n###############################################################################\n/root/.local/bin/ansible-playbook -v -b -i /dev/null ./rhel8STIG/site.yml\n\n\n###############################################################################\n# \"Automating Rule Id V-230483\" 8.0 auditd.conf does not recogn. percent sign\n###############################################################################\nif [ ${version} == '8.0' ]; then\n    echo \"Automating Rule Id V-230483\"\n    sed -i 's/25%/2048/g' /etc/audit/auditd.conf\nfi\n# END V-230483\n\n###############################################################################\necho \"Automating Rule Id V-230350\"\n###############################################################################\nsed -i 's/.*tmux.*//g' /etc/shells\necho '---------- /etc/shells content begin ----------'\ncat /etc/shells\necho '---------- /etc/shells content end ----------'\n# END V-230350\n\n###############################################################################\necho \"Automating Rule Id V-230223\"\n###############################################################################\nfips-mode-setup --enable\n# END V-230223\n\n###############################################################################\necho \"Restarting system to apply STIG settings...\"\n###############################################################################\ntouch ./azAutomationComplete\nshutdown -r +1 2>&1\n", "num_lines": 354}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "# only run once during deployment\nif [ -f ./azAutomationComplete ]; then\n    echo \"STIG Automation completion detected, exiting...\"\n    exit 0\nfi\n\n# apt-get update to assist nxPackage dsc automation\necho \"Executing apt-get update...\"\napt-get update -q > ./aptgetupdateresults.log\n\nset -e\n\n# dsc deployment automation\necho \"Move (OS Specific) .mof to configuration store as Pending.mof...\"\nmv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof\necho \"Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly...\"\n/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log\necho \"Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration...\"\n/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log\nif grep -q \"MI_RESULT_FAILED\" ./dscresults.log; then\n    echo \"Failed to apply Desired State Configuration successfully, check dscresults.log for more details...\"\n    exit 1\nelse\n    echo \"Applied Desired State Configuration successfully...\"\nfi\n\n# authentication/password/session automation\necho \"Creating /etc/pam.d/common-password to meet STIG requirements...\"\nmv --force /etc/pam.d/common-password /etc/pam.d/backup.common-password\necho \"# Generated by Microsoft.Azure.Extensions/CustomScript\" > /etc/pam.d/common-password\necho \"# Original common-password was moved to /etc/pam.d/backup.common-password\" >> /etc/pam.d/common-password\necho \"password\\trequisite\\t\\t\\tpam_pwquality.so retry=3 enforce_for_root\" >> /etc/pam.d/common-password\necho \"password\\t[success=1 default=ignore]\\tpam_unix.so obscure sha512 shadow remember=5 rounds=5000\" >> /etc/pam.d/common-password\necho \"password\\trequired\\t\\t\\tpam_permit.so\" >> /etc/pam.d/common-password\necho \"Creating /etc/pam.d/common-auth to meet STIG requirements...\"\nmv --force /etc/pam.d/common-auth /etc/pam.d/backup.common-auth\necho \"# Generated by Microsoft.Azure.Extensions/CustomScript\" > /etc/pam.d/common-auth\necho \"# Original common-auth was moved to /etc/pam.d/backup.common-auth\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_tally2.so onerr=fail deny=3\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_faildelay.so delay=4000000\" >> /etc/pam.d/common-auth\necho \"auth\\t[success=1 default=ignore]\\tpam_unix.so nullok_secure\" >> /etc/pam.d/common-auth\necho \"auth\\trequisite\\t\\t\\tpam_deny.so\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_permit.so\" >> /etc/pam.d/common-auth\necho \"auth\\toptional\\t\\t\\tpam_cap.so\" >> /etc/pam.d/common-auth\necho \"# auth\\t[success=2 default=ignore]\\tpam_pkcs11.so\" >> /etc/pam.d/common-auth\necho \"Adding 'session required pam_lastlog.so showfailed' after session pam_selinux.so module in /etc/pam.d/login...\"\nsed -i 's/\\(session.*pam_selinux\\.so close\\)/\\1\\nsession required pam_lastlog.so showfailed/g' /etc/pam.d/login\necho \"Removing 'NOPASSWD' tag from all files in /etc/sudors.d/\"\ngrep -r -l -i nopasswd /etc/sudoers.d/* | xargs sed -i 's/\\s*NOPASSWD://g'\necho \"Executing useradd -D -f 35...\"\nuseradd -D -f 35\n\n# file system permissions automation\necho \"Setting permissions to all log files under /far/log to 640...\"\nfind /var/log -perm /137 -type f -exec chmod -c 640 '{}' \\;\necho \"Setting mode to 0750 for /var/log...\"\nchmod -c 0750 /var/log\necho \"Setting group ownership to root for /lib, /usr/lib and /lib64...\"\nfind /lib /usr/lib /lib64 ! -group root -type f -exec chgrp -c root '{}' \\;\necho \"Setting ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin...\"\nset +e\nfind -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -user root -type f -exec chown -c root '{}' \\;\necho \"Setting group ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin...\"\nfind -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -group root -type f -exec chgrp -c root '{}' \\;\nset -e\necho \"Setting mode to 0600 for /var/log/audit/*...\"\nchmod -c 0600 /var/log/audit/*\n\n# chmod persistent cloud-init per-boot script\nif [ ! -f /var/lib/cloud/scripts/per-boot/per-boot.sh ]; then\n    echo \"Writing /var/lib/cloud/scripts/per-boot/per-boot.sh to address chmod persistence post reboot...\"\n    echo '#!/bin/bash' > /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'echo $(date) > /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \\; >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'chmod -c 0750 /var/log >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'chmod -c 0600 /var/log/audit/* >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    chmod +x /var/lib/cloud/scripts/per-boot/per-boot.sh\nfi\n\n# boot / audit automation\necho \"Adding 'audit=1' to /etc/default/grub to enable auditing at system startup...\"\ncp --force /etc/default/grub /etc/default/backup.grub\nsed -i 's/\\(GRUB_CMDLINE_LINUX=\"\\)/\\1audit=1/g' /etc/default/grub\nupdate-grub 2> ./updategrubresults.log\n\n# system reboot\necho \"Rebooting to apply STIG settings...\"\ntouch ./azAutomationComplete\nshutdown -r +1 2>&1\n", "num_lines": 90}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "# only run once during deployment\nif [ -f ./azAutomationComplete ]; then\n    echo \"STIG Automation completion detected, exiting...\"\n    exit 0\nfi\n\n# apt-get update to assist nxPackage dsc automation\necho \"Executing apt-get update...\"\napt-get update -q > ./aptgetupdateresults.log\n\nset -e\n\n# dsc deployment automation\necho \"Move (OS Specific) .mof to configuration store as Pending.mof...\"\nmv ./*.mof /etc/opt/omi/conf/dsc/configuration/Pending.mof\necho \"Execute Register.py --RefreshMode Push --ConfigurationMode ApplyOnly...\"\n/opt/microsoft/dsc/Scripts/Register.py --RefreshMode Push --ConfigurationMode ApplyOnly > ./dscresults.log\necho \"Execute PerformRequiredConfigurationChecks.py to apply the Pending.mof configuration...\"\n/opt/microsoft/dsc/Scripts/PerformRequiredConfigurationChecks.py >> ./dscresults.log\nif grep -q \"MI_RESULT_FAILED\" ./dscresults.log; then\n    echo \"Failed to apply Desired State Configuration successfully, check dscresults.log for more details...\"\n    exit 1\nelse\n    echo \"Applied Desired State Configuration successfully...\"\nfi\n\n# authentication/password/session automation\necho \"Creating /etc/pam.d/common-password to meet STIG requirements...\"\nmv --force /etc/pam.d/common-password /etc/pam.d/backup.common-password\necho \"# Generated by Microsoft.Azure.Extensions/CustomScript\" > /etc/pam.d/common-password\necho \"# Original common-password was moved to /etc/pam.d/backup.common-password\" >> /etc/pam.d/common-password\necho \"password\\trequisite\\t\\t\\tpam_pwquality.so retry=3 enforce_for_root\" >> /etc/pam.d/common-password\necho \"password\\t[success=1 default=ignore]\\tpam_unix.so obscure sha512 shadow remember=5 rounds=5000\" >> /etc/pam.d/common-password\necho \"password\\trequired\\t\\t\\tpam_permit.so\" >> /etc/pam.d/common-password\necho \"Creating /etc/pam.d/common-auth to meet STIG requirements...\"\nmv --force /etc/pam.d/common-auth /etc/pam.d/backup.common-auth\necho \"# Generated by Microsoft.Azure.Extensions/CustomScript\" > /etc/pam.d/common-auth\necho \"# Original common-auth was moved to /etc/pam.d/backup.common-auth\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_tally2.so onerr=fail deny=3\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_faildelay.so delay=4000000\" >> /etc/pam.d/common-auth\necho \"auth\\t[success=1 default=ignore]\\tpam_unix.so nullok_secure\" >> /etc/pam.d/common-auth\necho \"auth\\trequisite\\t\\t\\tpam_deny.so\" >> /etc/pam.d/common-auth\necho \"auth\\trequired\\t\\t\\tpam_permit.so\" >> /etc/pam.d/common-auth\necho \"auth\\toptional\\t\\t\\tpam_cap.so\" >> /etc/pam.d/common-auth\necho \"# auth\\t[success=2 default=ignore]\\tpam_pkcs11.so\" >> /etc/pam.d/common-auth\necho \"Adding 'session required pam_lastlog.so showfailed' after session pam_selinux.so module in /etc/pam.d/login...\"\nsed -i 's/\\(session.*pam_selinux\\.so close\\)/\\1\\nsession required pam_lastlog.so showfailed/g' /etc/pam.d/login\necho \"Removing 'NOPASSWD' tag from all files in /etc/sudors.d/\"\ngrep -r -l -i nopasswd /etc/sudoers.d/* | xargs sed -i 's/\\s*NOPASSWD://g'\necho \"Executing useradd -D -f 35...\"\nuseradd -D -f 35\n\n# file system permissions automation\necho \"Setting permissions to all log files under /far/log to 640...\"\nfind /var/log -perm /137 -type f -exec chmod -c 640 '{}' \\;\necho \"Setting mode to 0750 for /var/log...\"\nchmod -c 0750 /var/log\necho \"Setting group ownership to root for /lib, /usr/lib and /lib64...\"\nfind /lib /usr/lib /lib64 ! -group root -type f -exec chgrp -c root '{}' \\;\necho \"Setting ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin...\"\nfind -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -user root -type f -exec chown -c root '{}' \\;\necho \"Setting group ownership to root for /bin, /sbin, /usr/bin, /usr/sbin, /usr/local/bin and /usr/local/sbin...\"\nfind -L /bin /sbin /usr/bin /usr/sbin /usr/local/bin /usr/local/sbin ! -group root -type f -exec chgrp -c root '{}' \\;\necho \"Setting mode to 0600 for /var/log/audit/*...\"\nchmod -c 0600 /var/log/audit/*\n\n# chmod persistent cloud-init per-boot script\nif [ ! -f /var/lib/cloud/scripts/per-boot/per-boot.sh ]; then\n    echo \"Writing /var/lib/cloud/scripts/per-boot/per-boot.sh to address chmod persistence post reboot...\"\n    echo '#!/bin/bash' > /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'echo $(date) > /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'find /var/log -perm /137 -type f -exec chmod -c 640 '{}' \\; >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'chmod -c 0750 /var/log >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    echo 'chmod -c 0600 /var/log/audit/* >> /var/log/cloud-init-per-boot.log' >> /var/lib/cloud/scripts/per-boot/per-boot.sh\n    chmod +x /var/lib/cloud/scripts/per-boot/per-boot.sh\nfi\n\n# boot / audit automation\necho \"Adding 'audit=1' to /etc/default/grub to enable auditing at system startup...\"\ncp --force /etc/default/grub /etc/default/backup.grub\nsed -i 's/\\(GRUB_CMDLINE_LINUX=\"\\)/\\1audit=1/g' /etc/default/grub\nupdate-grub 2> ./updategrubresults.log\n\n# system reboot\necho \"Rebooting to apply STIG settings...\"\ntouch ./azAutomationComplete\nshutdown -r +1 2>&1\n", "num_lines": 88}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "# set up variables needed\nworkingFolder=\"/var/tmp/zta-files\"\narchive=\"offline-zta.tar.gz\"\nofflineRepoName=\"offline-zta-repo\"\nstigFile=\"rhel7.sh\"\n\n# create the working folder\necho \"..creating the working folder: $workingFolder\"\nmkdir $workingFolder\n\n# uncompress the archive\necho \"..uncompressing archive to: $workingFolder\"\ntar -xzvf \"$archive\" -C \"$workingFolder\"\n\n# create an entry for the repo\necho \"..creating repo file: /etc/yum.repos.d/$offlineRepoName.repo\"\ncat > /etc/yum.repos.d/$offlineRepoName.repo<< EOF\n[offline-zta-repo]\nname=$offlineRepoName\nbaseurl=file:///$workingFolder/$offlineRepoName\nenabled=0\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7\nEOF\n\n# run the stig script\necho \"..executing stig script: $stigFile\"\nbash \"$stigFile\"\n\n# remove the repo file and working folder\necho \"..stig script done. Time for cleanup\"\necho \"..removing repo file: /etc/yum.repos.d/$offlineRepoName.repo\"\nrm -f /etc/yum.repos.d/$offlineRepoName.repo\necho \"..removing working folder: $workingFolder\"\nrm -r $workingFolder\n\n", "num_lines": 37}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "stigFile=\"rhel7.sh\"\n\n# run the stig script\necho \"..executing stig script: $stigFile\"\nbash \"$stigFile\"\n", "num_lines": 6}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "# set up variables needed\nworkingFolder=\"/var/tmp/zta-files\"\narchive=\"offline-zta.tar.gz\"\nofflineRepoName=\"offline-zta-repo\"\nstigFile=\"rhel7.sh\"\n\n# create the working folder\necho \"..creating the working folder: $workingFolder\"\nmkdir $workingFolder\n\n# uncompress the archive\necho \"..uncompressing archive to: $workingFolder\"\ntar -xzvf \"$archive\" -C \"$workingFolder\"\n\n# create an entry for the repo\necho \"..creating repo file: /etc/yum.repos.d/$offlineRepoName.repo\"\ncat > /etc/yum.repos.d/$offlineRepoName.repo<< EOF\n[offline-zta-repo]\nname=$offlineRepoName\nbaseurl=file:///$workingFolder/$offlineRepoName\nenabled=0\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7\nEOF\n\n# run the stig script\necho \"..executing stig script: $stigFile\"\nbash \"$stigFile\"\n\n# remove the repo file and working folder\necho \"..stig script done. Time for cleanup\"\necho \"..removing repo file: /etc/yum.repos.d/$offlineRepoName.repo\"\nrm -f /etc/yum.repos.d/$offlineRepoName.repo\necho \"..removing working folder: $workingFolder\"\nrm -r $workingFolder\n\n", "num_lines": 37}
{"repo_name": "ato-toolkit", "repo_creator": "Azure", "programming_language": "Shell", "code": "stigFile=\"rhel7.sh\"\n\n# run the stig script\necho \"..executing stig script: $stigFile\"\nbash \"$stigFile\"\n", "num_lines": 6}
{"repo_name": "AtUniverse", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script to deploy the app\n# This file is needed only when you want to deploy the app to a Linux VM\n\n# install node\npushd .\ncd ~\ncurl -sL https://deb.nodesource.com/setup_6.x -o nodesource_setup.sh\nsudo bash nodesource_setup.sh\nsudo apt-get install nodejs -y\nsudo apt-get install build-essential -y\n\n# install express\nsudo npm install express -y -g\npopd\n\n# configure nginx\nsudo rm -f /etc/nginx/sites-enabled/default\nsudo cp -f ./nginx-config /etc/nginx/sites-available/example\nsudo ln -fs /etc/nginx/sites-available/example /etc/nginx/sites-enabled\nsudo service nginx reload\n\n# install pm2 and start the node server as a daemon\ncd ..\nsudo npm install pm2 -g -y\npm2 delete example -s\npm2 start server.js -n example\n", "num_lines": 27}
{"repo_name": "AtUniverse", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Test driver script to be used in a container\n# See http://docs.microsoft.com/azure/devops/pipelines/languages/docker for more information\nsleep 5\nif curl web | grep -q 'Hello world'; then\n  echo \"Tests passed!\"\n  exit 0\nelse\n  echo \"Tests failed!\"\n  exit 1\nfi\n\n", "num_lines": 12}
{"repo_name": "autorest", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x;\n\ndocker build -t azsdkengsys.azurecr.io/azuresdk/autorest --build-arg REGISTRY=\"mcr.microsoft.com/mirror/docker/library/\" ./base/ubuntu\ndocker build -t azsdkengsys.azurecr.io/azuresdk/autorest-dotnet ./dotnet/ubuntu\ndocker build -t azsdkengsys.azurecr.io/azuresdk/autorest-python ./python/ubuntu\ndocker build -t azsdkengsys.azurecr.io/azuresdk/autorest-java ./java/ubuntu\ndocker build -t azsdkengsys.azurecr.io/azuresdk/autorest-all ./all/ubuntu\n", "num_lines": 9}
{"repo_name": "autorest.java", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nexport SPEC_REPO=https://github.com/Azure/azure-rest-api-specs.git\nexport TSP_PATH=specification/eventgrid/Azure.Messaging.EventGrid\nexport REPO_BRANCH=feature/eventgrid/typespec\n\nmkdir tsp-repo\ncd tsp-repo\ngit init\ngit config core.sparseCheckout true\ngit remote add -f origin $SPEC_REPO\necho $TSP_PATH > .git/info/sparse-checkout\ngit checkout $REPO_BRANCH\ncd ..\n\ncp -rf tsp-repo/$TSP_PATH tsp-src\nrm -rf tsp-repo\n", "num_lines": 19}
{"repo_name": "autorest.swift", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd ./.build/checkouts/SwiftLint/Source/swiftlint\nswift build\n\ncd ../../../../..", "num_lines": 6}
{"repo_name": "autorest.swift", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# git_sync.sh\n\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nREPO_ROOT=\"$( cd -P \"$( dirname \"$SOURCE\" )\"/.. >/dev/null 2>&1 && pwd )\"\n\n# TODO: make this not hard coded\nSDK_REPO_ROOT=\"/Users/travisprescott/repos/azure-sdk-for-ios/\"\nSDK_PACKAGE_ROOT=\"/Users/travisprescott/repos/azure-sdk-for-ios/sdk/communication/\"\nSDK_SRC=\"/Users/travisprescott/Documents/generated/sdk\"\n\n# FIXME: The build step fails when run with makefile.\n#echo\n#echo \"AutoRest.Swift root: $REPO_ROOT\"\n#echo\n#echo \"==~ Building AutoRest.Swift ~==\"\n#echo\n#make build -C $REPO_ROOT\n#echo\n#echo \"==~ Generating SDK ~==\"\n#echo\n#swift run --package-path $REPO_ROOT\n\necho\necho \"==~ Copying generated code to azure-sdk-for-ios ~==\"\nPACKAGE_NAME=$(ls  -1 -t $SDK_SRC | head -1)\n\n# copy the jazzy files from the generated package into the SDK root\ncp -r $SDK_SRC/$PACKAGE_NAME/.jazzy/ $SDK_REPO_ROOT/.jazzy\n\n# copy the generated code into the SDK repo\ncp -rf $SDK_SRC/. $SDK_PACKAGE_ROOT\n\necho\necho \"Switching to: \" $SDK_REPO_ROOT\ncd $SDK_REPO_ROOT\n\necho\necho \"Checking out feature/communication branch\"\ngit reset\ngit checkout feature/communication\n\ncd $REPO_ROOT\n\necho \"==~ Ready to Commit Changes in SourceTree! ~==\"\n", "num_lines": 52}
{"repo_name": "autorest.swift", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#  swiftlint.sh\nSOURCE=\"${BASH_SOURCE[0]}\"\nwhile [ -h \"$SOURCE\" ]; do # resolve $SOURCE until the file is no longer a symlink\n  DIR=\"$( cd -P \"$( dirname \"$SOURCE\" )\" >/dev/null 2>&1 && pwd )\"\n  SOURCE=\"$(readlink \"$SOURCE\")\"\n  [[ $SOURCE != /* ]] && SOURCE=\"$DIR/$SOURCE\" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located\ndone\nREPO_ROOT=\"$( cd -P \"$( dirname \"$SOURCE\" )\"/.. >/dev/null 2>&1 && pwd )\"\n\necho\necho \"Repo root: $REPO_ROOT\"\necho\n\nif which swiftformat >/dev/null; then\n    echo \"Formatting Swift files at: $REPO_ROOT/src\"\n    swiftformat --quiet --config \"$REPO_ROOT/.swiftformat\" \"$REPO_ROOT/src\" &> /dev/null\n    echo \"Formatting Swift files at: $REPO_ROOT/AutorestSwiftTest\"\n    swiftformat --quiet --config \"$REPO_ROOT/.swiftformat\" \"$REPO_ROOT/AutorestSwiftTest\" &> /dev/null\nelse\n    echo \"warning: SwiftFormat not installed. Download from https://github.com/nicklockwood/SwiftFormat\"\nfi\n\nif which swiftlint >/dev/null; then\n    echo \"Correcting Swift files at: $REPO_ROOT/src\"\n    swiftlint autocorrect --quiet --config \"$REPO_ROOT/.swiftlint.yml\" \"$REPO_ROOT/src\" &> /dev/null\n    echo \"Linting Swift files at: $REPO_ROOT/src\"\n    swiftlint lint --quiet --config \"$REPO_ROOT/.swiftlint.yml\" \"$REPO_ROOT/src\"\n    echo \"Correcting Swift files at: $REPO_ROOT/AutorestSwiftTest\"\n    swiftlint autocorrect --quiet --config \"$REPO_ROOT/.swiftlint.yml\" \"$REPO_ROOT/AutorestSwiftTest\" &> /dev/null\n    echo \"Linting Swift files at: $REPO_ROOT/AutorestSwiftTest\"\n    swiftlint lint --quiet --config \"$REPO_ROOT/.swiftlint.yml\" \"$REPO_ROOT/AutorestSwiftTest\"\nelse\n    echo \"warning: SwiftLint not installed. Download from https://github.com/realm/SwiftLint\"\nfi\n", "num_lines": 37}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "go get github.com/golang/protobuf/protoc-gen-go\n\nprotoc \\\n--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto \n\n", "num_lines": 6}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\t# Use then new build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd -arm\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd -arm\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 195}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\tif [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\t\techo 1>&2 \"In the new build system, mkerrors should not be called directly.\"\n\t\techo 1>&2 \"See README.md\"\n\t\texit 1\n\tfi\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capability.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/keyctl.h>\n#include <linux/netlink.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/watchdog.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE)/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 570}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\necho \"Updating ${GOPATH}\"\n\nto_fix=$(ls \"${GOPATH}/src/k8s.io/kubernetes/staging/src/k8s.io\")\nfor item in $to_fix; do\n   echo \"Updating staging dep ${item}\"\n   rm -rf \"${GOPATH}/src/k8s.io/${item}\"\n   mkdir \"${GOPATH}/src/k8s.io/${item}\"\n   cd \"${GOPATH}/src/k8s.io/${item}\"\n   git init\n   # shellcheck disable=SC2086\n   cp -R ${GOPATH}/src/k8s.io/kubernetes/staging/src/k8s.io/${item}/* ./\n   git add .\n   git commit -a -m from_staging\ndone\n\nwith_vendor=$(find \"${GOPATH}/src/\" -type d | grep vendor | grep -v 'vendor/')\nfor item in $with_vendor; do\n    echo \"Removing vendor from ${item}\"\n    (cd \"$item\")\n    rm -rf \"$item\"\n    git commit -a -m no_vendor\ndone\n\necho Overriding AKS API\nmkdir -p \"${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice\"\n# shellcheck disable=SC2086\ncp ${GOPATH}/src/k8s.io/autoscaler/cluster-autoscaler/_override/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice/* \"${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice/\"\ncd \"${GOPATH}/src/github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice\"\ngit add .\ngit commit -a -m \"Api override for AKS\"\n\necho Overriding Azure autorest\n# shellcheck disable=SC2086\ncp -r ${GOPATH}/src/k8s.io/autoscaler/cluster-autoscaler/_override/github.com/Azure/go-autorest/* \"${GOPATH}/src/github.com/Azure/go-autorest/\"\ncd \"${GOPATH}/src/github.com/Azure/go-autorest/\"\ngit add .\ngit commit -a -m \"Api override for autorest\"\n", "num_lines": 42}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nIMAGE_TO_PUSH=$1\nif [ -z $IMAGE_TO_PUSH ]; then\n  echo No image passed\n  exit 1\nfi\n\ndocker_push_cmd=(\"docker\")\nif [[ \"${IMAGE_TO_PUSH}\" == \"gcr.io/\"* ]] || [[ \"${IMAGE_TO_PUSH}\" == \"staging-k8s.gcr.io/\"* ]] ; then\n    docker_push_cmd=(\"gcloud\" \"docker\" \"--\")\nfi\n\necho \"About to push image $IMAGE_TO_PUSH\"\nread -r -p \"Are you sure? [y/N] \" response\nif [[ \"$response\" =~ ^([yY])+$ ]]; then\n  \"${docker_push_cmd[@]}\" pull $IMAGE_TO_PUSH\n  if [ $? -eq 0 ]; then\n    echo $IMAGE_TO_PUSH already exists\n    exit 1\n  fi\n  \"${docker_push_cmd[@]}\" push $IMAGE_TO_PUSH\nelse\n  echo Aborted\n  exit 1\nfi\n", "num_lines": 41}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#env /usr/bin/bash\n\nset -o errexit\nset -o pipefail\nset -o nounset\nshopt -s lastpipe\n\nif [[ $(basename $(pwd)) != \"cluster-autoscaler\" ]];then\n  echo \"The script must be run in cluster-autoscaler directory\"\n  exit 1\nfi\n\nif ! which jq > /dev/null; then\n  echo \"This script requires jq command to be available\"\n  exit 1\nfi\n\nSCRIPT_NAME=$(basename \"$0\")\nK8S_FORK=\"git@github.com:kubernetes/kubernetes.git\"\nK8S_REV=\"master\"\nBATCH_MODE=\"false\"\nTARGET_MODULE=${TARGET_MODULE:-k8s.io/autoscaler/cluster-autoscaler}\n\nARGS=\"$@\"\nOPTS=`getopt -o f::r::d::v::b:: --long k8sfork::,k8srev::,workdir::,batch:: -n $SCRIPT_NAME -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\neval set -- \"$OPTS\"\nwhile true; do\n  case \"$1\" in\n    -f | --k8sfork ) K8S_FORK=\"$2\"; shift; shift ;;\n    -r | --k8srev ) K8S_REV=\"$2\"; shift; shift ;;\n    -d | --workdir ) WORK_DIR=\"$2\"; shift; shift ;;\n    -b | --batch ) BATCH_MODE=\"true\"; shift; shift ;;\n    -v ) VERBOSE=1; shift; if [[ \"$1\" == \"v\" ]]; then VERBOSE=2; shift; fi; ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\nexport GO111MODULE=on\n\nset -o errexit\nWORK_DIR=\"${WORK_DIR:-$(mktemp -d /tmp/ca-update-vendor.XXXX)}\"\necho \"Operating in ${WORK_DIR}\"\n\nif [ ! -d $WORK_DIR ]; then\n  echo \"Work dir ${WORK_DIR} does not exist\"\n  exit 1\nfi\n\nLOG_FILE=\"${LOG_FILE:-${WORK_DIR}/ca-update-vendor.log}\"\necho \"Sending logs to: ${LOG_FILE}\"\nif [ -z \"${BASH_XTRACEFD:-}\" ]; then\n  exec 19> \"${LOG_FILE}\"\n  export BASH_XTRACEFD=\"19\"\nfi\nset -x\n\nEXPECTED_ERROR_MARKER=\"${WORK_DIR}/expected_error\"\n\n# Try\nset +o errexit\n(\n  set -o errexit\n  rm -f $EXPECTED_ERROR_MARKER\n  K8S_REPO=\"${WORK_DIR}/kubernetes\"\n  if [ -d ${K8S_REPO} ]; then\n    pushd ${K8S_REPO} >/dev/null\n    if [[ \"$(git remote get-url origin)\" != \"${K8S_FORK}\" ]]; then\n      echo \"Mismated checked out k8s repo; deleting\"\n      rm -rf \"${K8S_REPO}\"\n    fi\n    popd >/dev/null\n  fi\n\n  echo \"Updating vendor against ${K8S_FORK}:${K8S_REV}\"\n\n  if [ ! -d ${K8S_REPO} ]; then\n    echo \"Cloning ${K8S_FORK} into ${K8S_REPO}\"\n    git clone ${K8S_FORK} ${K8S_REPO} >&${BASH_XTRACEFD} 2>&1\n  fi\n\n  pushd ${K8S_REPO} >/dev/null\n  git checkout ${K8S_REV} >&${BASH_XTRACEFD} 2>&1\n  K8S_REV_PARSED=$(git rev-parse ${K8S_REV})\n  popd >/dev/null\n\n\n  function err_rerun() {\n    touch ${EXPECTED_ERROR_MARKER}\n    echo \"$*\"\n    if [[ \"${BATCH_MODE}\" == \"false\" ]]; then\n      echo \"Fix errors and rerun script:\"\n      echo \" $0 -d${WORK_DIR} -f${K8S_FORK} -r${K8S_REV}\"\n    fi\n    exit 1\n  }\n\n  # Deleting old stuff\n  rm -rf vendor\n  rm -f go.mod\n  rm -f go.sum\n\n  # Base CA go.mod on one from k8s.io/kuberntes\n  cp $K8S_REPO/go.mod .\n\n  # Check go version\n  REQUIRED_GO_VERSION=$(cat go.mod  |grep '^go ' |tr -s ' ' |cut -d ' '  -f 2)\n  USED_GO_VERSION=$(go version |sed 's/.*go\\([0-9]\\+\\.[0-9]\\+\\).*/\\1/')\n\n  if [[ \"${REQUIRED_GO_VERSION}\" != \"${USED_GO_VERSION}\" ]];then\n    err_rerun \"Invalid go version ${USED_GO_VERSION}; required go version is ${REQUIRED_GO_VERSION}.\"\n  fi\n\n  # Fix module name and staging modules links\n  sed -i \"s#module k8s.io/kubernetes#module ${TARGET_MODULE}#\" go.mod\n  sed -i \"s#\\\\./staging#${K8S_REPO}/staging#\" go.mod\n\n  function list_dependencies() {\n    local_tmp_dir=$(mktemp -d \"${WORK_DIR}/list_dependencies.XXXX\")\n    local go_dep_file=\"$1\"\n    local tmp_file=\"${local_tmp_dir}/list_dependencies.tmp\"\n    rm -f ${tmp_file}\n    go mod edit -json ${go_dep_file} |jq -r '.Replace[]? | select(.New.Version != null)| \"\\(.Old.Path) \\(.New.Version)\"' >> ${tmp_file}\n    go mod edit -json ${go_dep_file} |jq -r '.Require[]? | \"\\(.Path) \\(.Version)\"' >> ${tmp_file}\n    cat ${tmp_file} |sort |uniq\n  }\n\n  function version_gt() {\n    test \"$(printf '%s\\n' \"$@\" | sort -V | head -n 1)\" != \"$1\";\n  }\n\n  OLD_EXTRA_FOUND=\"false\"\n  for go_mod_extra in go.mod-extra*; do\n    list_dependencies ${go_mod_extra} | while read extra_path extra_version; do\n      list_dependencies go.mod | while read source_path source_version; do\n        if [[ \"${source_path}\" == \"${extra_path}\" ]]; then\n          if ! version_gt $extra_version $source_version; then\n            echo \"Extra dependency ${source_path} already used by k8s in >= version ${source_version}\"\n            OLD_EXTRA_FOUND=\"true\"\n          fi\n        fi\n      done\n    done\n  done\n  if [[ \"${OLD_EXTRA_FOUND}\" == \"true\" ]]; then\n    err_rerun \"Extra dependencies found in one of go.mod-extra files\"\n  fi\n\n  # Add dependencies from go.mod-extra to go.mod\n  # Propagate require entries to both require and replace\n  for go_mod_extra in go.mod-extra*; do\n    go mod edit -json ${go_mod_extra} | jq -r '.Require[]? | \"-require \\(.Path)@\\(.Version)\"' | xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1\n    go mod edit -json ${go_mod_extra} | jq -r '.Require[]? | \"-replace \\(.Path)=\\(.Path)@\\(.Version)\"' | xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1\n    # And add explicit replace entries\n    go mod edit -json ${go_mod_extra} | jq -r '.Replace[]? | \"-replace \\(.Old.Path)=\\(.New.Path)@\\(.New.Version)\"' | sed \"s/@null//g\" |xargs -t -r go mod edit >&${BASH_XTRACEFD} 2>&1\n  done\n  # Add k8s.io/kubernetes dependency\n  go mod edit -require k8s.io/kubernetes@v0.0.0\n  go mod edit -replace k8s.io/kubernetes=${K8S_REPO}\n\n  # Fail if there are implicit dependencies\n  list_dependencies go.mod > ${WORK_DIR}/packages-before-tidy\n  go mod tidy -v >&${BASH_XTRACEFD} 2>&1\n  list_dependencies go.mod > ${WORK_DIR}/packages-after-tidy\n\n  IMPLICIT_FOUND=\"false\"\n  set +o pipefail\n  diff -u ${WORK_DIR}/packages-before-tidy ${WORK_DIR}/packages-after-tidy | grep -v '\\+\\+\\+ ' | grep '^\\+' | cut -b 2- |while read line; do\n    IMPLICIT_FOUND=\"true\"\n    echo \"Implicit dependency found: ${line}\"\n  done\n  set -o pipefail\n\n  if [[ \"${IMPLICIT_FOUND}\" == \"true\" ]]; then\n    err_rerun \"Implicit dependencies missing from go.mod-extra\"\n  fi\n\n  echo \"Running go mod vendor\"\n  go mod vendor\n\n  echo \"Running go test -mod=vendor ./...\"\n  if ! go test -mod=vendor ./... >&${BASH_XTRACEFD} 2>&1; then\n    err_rerun \"Test run failed\"\n  fi\n\n  # Commit go.mod* and vendor\n  git restore --staged . >&${BASH_XTRACEFD} 2>&1\n  git add vendor go.mod go.sum >&${BASH_XTRACEFD} 2>&1\n  if ! git diff --quiet --cached; then\n    echo \"Commiting vendor, go.mod and go.sum\"\n    git ci -m \"Updating vendor against ${K8S_FORK}:${K8S_REV} (${K8S_REV_PARSED})\" >&${BASH_XTRACEFD} 2>&1\n  else\n    echo \"No changes after vendor update; skipping commit\"\n  fi\n\n\n  if ! git diff --quiet; then\n    echo \"Uncommited changes (manual fixes?) still present in repository - please commit those\"\n  fi\n\n  echo \"Operation finished successfully\"\n  if [[ \"$(basename \"${WORK_DIR}\" | cut -d '.' -f 1)\" == \"ca-update-vendor\" ]];then\n    echo \"Deleting working directory ${WORK_DIR}\"\n    rm -rf ${WORK_DIR}\n  else\n    echo \"Preserving working directory ${WORK_DIR}\"\n  fi\n)\n\n# Catch\nerr=$?\nif [[ $err -ne 0 ]]; then\n  if [ ! -f \"${EXPECTED_ERROR_MARKER}\" ]; then\n    echo\n    echo \"Unexpected error occured; check $LOG_FILE\"\n  fi\nfi\nexit $err\n", "num_lines": 220}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "go get github.com/golang/protobuf/protoc-gen-go\n\nprotoc \\\n--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto \n\n", "num_lines": 6}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    echo -e \"TESTS FOR: for \\033[0;35m${d}\\033[0m\"\n    go test -race -v -coverprofile=profile.coverage.out -covermode=atomic $d\n    if [ -f profile.coverage.out ]; then\n        cat profile.coverage.out >> coverage.txt\n        rm profile.coverage.out\n    fi\n    echo \"\"\ndone\n", "num_lines": 15}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"darwin\" ]; then\n\t\t\t        # pre-1.12, direct syscalls\n\t\t\t        echo \"$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go\";\n\t\t\t        # 1.12 and later, syscalls via libSystem\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOARCH\"; fi\n\tfi\n) | $run\n", "num_lines": 215}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/errqueue.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/watchdog.h>\n#include <linux/hdreg.h>\n#include <linux/rtc.h>\n#include <linux/if_xdp.h>\n#include <mtd/ubi-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 658}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ `uname -a` = *\"Darwin\"* ]]; then\n  echo \"It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047\"\n  exit 1\nfi\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nPATH=\"$GOPATH/bin:$GOROOT/bin:$PATH\"\n\n# Check proto in manual runs or cron runs.\nif [[ \"$TRAVIS\" != \"true\" || \"$TRAVIS_EVENT_TYPE\" = \"cron\" ]]; then\n  check_proto=\"true\"\nfi\n\nif [ \"$1\" = \"-install\" ]; then\n  go get -d \\\n    google.golang.org/grpc/...\n  go get -u \\\n    github.com/golang/lint/golint \\\n    golang.org/x/tools/cmd/goimports \\\n    honnef.co/go/tools/cmd/staticcheck \\\n    github.com/client9/misspell/cmd/misspell \\\n    github.com/golang/protobuf/protoc-gen-go\n  if [[ \"$check_proto\" = \"true\" ]]; then\n    if [[ \"$TRAVIS\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.3.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif ! which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# TODO: Remove this check and the mangling below once \"context\" is imported\n# directly.\nif git status --porcelain | read; then\n  die \"Uncommitted or untracked files found; commit changes first\"\nfi\n\ngit ls-files \"*.go\" | xargs grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" 2>&1 | tee /dev/stderr | (! read)\ngit ls-files \"*.go\" | xargs grep -l '\"unsafe\"' 2>&1 | (! grep -v '_test.go') | tee /dev/stderr | (! read)\ngit ls-files \"*.go\" | xargs grep -l '\"math/rand\"' 2>&1 | (! grep -v '^examples\\|^stress\\|grpcrand') | tee /dev/stderr | (! read)\ngofmt -s -d -l . 2>&1 | tee /dev/stderr | (! read)\ngoimports -l . 2>&1 | tee /dev/stderr | (! read)\ngolint ./... 2>&1 | (grep -vE \"(_mock|\\.pb)\\.go:\" || true) | tee /dev/stderr | (! read)\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\n# Rewrite golang.org/x/net/context -> context imports (see grpc/grpc-go#1484).\n# TODO: Remove this mangling once \"context\" is imported directly (grpc/grpc-go#711).\ngit ls-files \"*.go\" | xargs sed -i 's:\"golang.org/x/net/context\":\"context\":'\nset +o pipefail\n# TODO: Stop filtering pb.go files once golang/protobuf#214 is fixed.\ngo tool vet -all . 2>&1 | grep -vE '(clientconn|transport\\/transport_test).go:.*cancel (function|var)' | grep -vF '.pb.go:' | tee /dev/stderr | (! read)\nset -o pipefail\ngit reset --hard HEAD\n\nif [[ \"$check_proto\" = \"true\" ]]; then\n  PATH=\"/home/travis/bin:$PATH\" make proto && \\\n    git status --porcelain 2>&1 | (! read) || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# TODO(menghanl): fix errors in transport_test.\nstaticcheck -ignore '\ngoogle.golang.org/grpc/transport/transport_test.go:SA2002\ngoogle.golang.org/grpc/benchmark/benchmain/main.go:SA1019\ngoogle.golang.org/grpc/stats/stats_test.go:SA1019\ngoogle.golang.org/grpc/test/end2end_test.go:SA1019\ngoogle.golang.org/grpc/balancer_test.go:SA1019\ngoogle.golang.org/grpc/balancer.go:SA1019\ngoogle.golang.org/grpc/clientconn_test.go:SA1019\n' ./...\nmisspell -error .\n", "num_lines": 95}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\nCN_BASE=\"webhook_tests\"\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=${CN_BASE}_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=${CN_BASE}_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 108}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook authz plugin tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=webhook_authz_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=webhook_authz_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 103}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o pipefail\nset -o nounset\n\nCONTRIB_ROOT=\"$(dirname ${BASH_SOURCE})/..\"\nPROJECT_NAMES=(addon-resizer cluster-autoscaler vertical-pod-autoscaler)\n\nif [[ $# -ne 1 ]]; then\n  echo \"missing subcommand: [build|install|test]\"\n  exit 1\nfi\n\nCMD=\"${1}\"\n\ncase \"${CMD}\" in\n  \"build\")\n    ;;\n  \"install\")\n    ;;\n  \"test\")\n    ;;\n  *)\n    echo \"invalid subcommand: ${CMD}\"\n    exit 1\n    ;;\nesac\n\nfor project_name in ${PROJECT_NAMES[*]}; do\n  (\n    project=${CONTRIB_ROOT}/${project_name}\n    echo \"${CMD}ing ${project}\"\n    cd \"${project}\"\n    case \"${CMD}\" in\n      \"test\")\n        if [[ -n $(find . -name \"Godeps.json\") ]]; then\n          godep go test -race $(go list ./... | grep -v /vendor/ | grep -v vertical-pod-autoscaler/e2e)\n        else\n          go test -race $(go list ./... | grep -v /vendor/ | grep -v vertical-pod-autoscaler/e2e)\n        fi\n        ;;\n      *)\n        godep go \"${CMD}\" ./...\n        ;;\n    esac\n  )\ndone;\n", "num_lines": 63}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/..\n\ngo get -u golang.org/x/lint/golint\n\ngo get -u github.com/tools/godep\n\ngo get -u github.com/client9/misspell/cmd/misspell\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 30}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Some useful colors.\nif [[ -z \"${color_start-}\" ]]; then\n  declare -r color_start=\"\\033[\"\n  declare -r color_red=\"${color_start}0;31m\"\n  declare -r color_yellow=\"${color_start}0;33m\"\n  declare -r color_green=\"${color_start}0;32m\"\n  declare -r color_norm=\"${color_start}0m\"\nfi\n\n# Returns the server version as MMmmpp, with MM as the major\n# component, mm the minor component, and pp as the patch\n# revision. e.g. 0.7.1 is echoed as 701, and 1.0.11 would be\n# 10011. (This makes for easy integer comparison in bash.)\nfunction kube_server_version() {\n  local server_version\n  local major\n  local minor\n  local patch\n\n  # This sed expression is the POSIX BRE to match strings like:\n  # Server Version: &version.Info{Major:\"0\", Minor:\"7+\", GitVersion:\"v0.7.0-dirty\", GitCommit:\"ad44234f7152e9c66bc2853575445c7071335e57\", GitTreeState:\"dirty\"}\n  # and capture the GitVersion portion (which has the patch level)\n  server_version=$(${KUBECTL} --match-server-version=false version | grep \"Server Version:\")\n  read major minor patch < <(\n    echo ${server_version} | \\\n      sed \"s/.*GitVersion:\\\"v\\([0-9]\\{1,\\}\\)\\.\\([0-9]\\{1,\\}\\)\\.\\([0-9]\\{1,\\}\\).*/\\1 \\2 \\3/\")\n  printf \"%02d%02d%02d\" ${major} ${minor} ${patch} | sed 's/^0*//'\n}\n", "num_lines": 45}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nfind . -name \"*.go\" | grep -v \"\\/vendor\\/\" | xargs gofmt -s -w\n", "num_lines": 22}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/..\nsource \"${KUBE_ROOT}/hack/kube-env.sh\"\n\nSILENT=true\nEXCLUDE=${EXCLUDE:-} # nothing excluded by default\n\nfunction is-excluded {\n  if [[ $1 -ef ${BASH_SOURCE} ]]; then\n    return\n  fi\n  for e in $EXCLUDE; do\n    if [[ $1 -ef \"$KUBE_ROOT/hack/$e\" ]]; then\n      return\n    fi\n  done\n  return 1\n}\n\nwhile getopts \":v\" opt; do\n  case $opt in\n    v)\n      SILENT=false\n      ;;\n    \\?)\n      echo \"Invalid flag: -$OPTARG\" >&2\n      exit 1\n      ;;\n  esac\ndone\n\nif $SILENT ; then\n  echo \"Running in the silent mode, run with -v if you want to see script logs.\"\nfi\n\nret=0\nfor t in `ls $KUBE_ROOT/hack/verify-*.sh`\ndo\n  if is-excluded $t ; then\n    echo \"Skipping $t\"\n    continue\n  fi\n  if ! $SILENT ; then\n    echo -e \"Verifying $t\"\n    if bash \"$t\"; then\n      echo -e \"${color_green}SUCCESS${color_norm}\"\n    else\n      echo -e \"${color_red}FAILED${color_norm}\"\n      ret=1\n    fi\n  else\n    bash \"$t\" &> /dev/null || ret=1\n  fi\ndone\n\nexit $ret\n", "num_lines": 76}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/..\n\nboilerDir=\"${KUBE_ROOT}/hack/boilerplate\"\nboiler=\"${boilerDir}/boilerplate.py\"\n\nfiles_need_boilerplate=($(${boiler} \"$@\"))\n\n# Run boilerplate check\nif [[ ${#files_need_boilerplate[@]} -gt 0 ]]; then\n  for file in \"${files_need_boilerplate[@]}\"; do\n    echo \"Boilerplate header is wrong for: ${file}\"\n  done\n\n  exit 1\nfi\n", "num_lines": 36}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# GoFmt apparently is changing @ head...\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/..\ncd \"${KUBE_ROOT}\"\n\nfind_files() {\n  find . -not \\( \\\n      \\( \\\n        -wholename './output' \\\n        -o -wholename './_output' \\\n        -o -wholename './release' \\\n        -o -wholename './target' \\\n        -o -wholename './.git' \\\n        -o -wholename '*/third_party/*' \\\n        -o -wholename '*/Godeps/*' \\\n        -o -wholename '*/vendor/*' \\\n        -o -wholename './cluster-autoscaler/cloudprovider/magnum/gophercloud/*' \\\n        -o -wholename './cluster-autoscaler/cloudprovider/digitalocean/godo/*' \\\n      \\) -prune \\\n    \\) -name '*.go'\n}\n\nDOCKER_IMAGE=`grep 'FROM golang' builder/Dockerfile | sed 's/FROM //'`\nGOFMT=\"docker run -v $(pwd):/code -w /code $DOCKER_IMAGE gofmt -s\"\n\nbad_files=$(find_files | xargs $GOFMT -l)\nif [[ -n \"${bad_files}\" ]]; then\n  echo \"Please run hack/update-gofmt.sh to fix the following files:\"\n  echo \"${bad_files}\"\n  exit 1\nfi\n", "num_lines": 52}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2014 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nKUBE_ROOT=$(dirname \"${BASH_SOURCE}\")/..\ncd \"${KUBE_ROOT}\"\n\nGOLINT=${GOLINT:-\"golint\"}\nexcluded_packages=(\n  '/vendor/'\n  'vertical-pod-autoscaler/pkg/client'\n  'cluster-autoscaler/cloudprovider/magnum/gophercloud'\n  'cluster-autoscaler/cloudprovider/digitalocean/godo'\n)\n\nFIND_PACKAGES='go list ./... '\nfor package in \"${excluded_packages[@]}\"; do\n     FIND_PACKAGES+=\"| grep -v ${package} \"\ndone\n\nPACKAGES=()\nmapfile -t PACKAGES < <(eval ${FIND_PACKAGES})\nbad_files=()\nfor package in \"${PACKAGES[@]}\"; do\n  out=$(\"${GOLINT}\" -min_confidence=0.9 \"${package}\")\n  if [[ -n \"${out}\" ]]; then\n    bad_files+=(\"${out}\")\n  fi\ndone\nif [[ \"${#bad_files[@]}\" -ne 0 ]]; then\n  echo \"!!! '$GOLINT' problems: \"\n  echo \"${bad_files[@]}\"\n  exit 1\nfi\n\n# ex: ts=2 sw=2 et filetype=sh\n", "num_lines": 53}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash \n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nDIR=$(dirname $0) \n\n# Install tools we need\ngo install ${DIR}/../../../github.com/client9/misspell/cmd/misspell\n\n# Spell checking\ngit ls-files --full-name | grep -v -e vendor | grep -v cluster-autoscaler/cloudprovider/magnum/gophercloud|  grep -v cluster-autoscaler/cloudprovider/digitalocean/godo | xargs misspell -error -o stderr\n", "num_lines": 27}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\noutdir=`mktemp -d --tmpdir vpa-alpha-XXXXXXXXX`\n\nkubectl get verticalpodautoscalers.poc.autoscaling.k8s.io --all-namespaces --no-headers -o=custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name >${outdir}/list\nif [[ -z `cat ${outdir}/list` ]]\nthen\n  echo \"No alpha VPA objects to store\"\n  exit 0\nfi\n\necho \"Fetching alpha VPA objects into ${outdir}.\"\nwhile read ns name\ndo\n  outfile=`mktemp --tmpdir=${outdir} vpa-XXXXXXXXX.yaml`\n  echo \"Storing converted ${ns}:${name} into ${outfile}.\"\n  kubectl get verticalpodautoscalers.poc.autoscaling.k8s.io -n ${ns} ${name} -o yaml >${outfile}\n  sed -i -e 's|poc.autoscaling.k8s.io/v1alpha1|autoscaling.k8s.io/v1beta1|' ${outfile}\ndone <${outdir}/list\nrm ${outdir}/list\n\necho\necho \"Please have a look at converted VPA objects in ${outdir}.\"\necho \"If everything looks OK you can migrate to beta VPA by:\"\necho \"1. disabling alpha VPA via vpa-down.sh script,\"\necho \"2. enabling beta VPA via vpa-up.sh script,\"\necho \"3. re-creating VPA objects by executing:\"\necho \"   kubectl create -f ${outdir}\"\necho\necho \"NOTE: The recommendations will NOT be kept between versions.\"\necho \"There will be a disruption period until beta VPA computes new recommendations.\"\necho\n\n", "num_lines": 48}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\nfunction print_help {\n  echo \"ERROR! Usage: deploy-for-e2e.sh [suite]*\"\n  echo \"<suite> should be one of:\"\n  echo \" - recommender\"\n  echo \" - updater\"\n  echo \" - admission-controller\"\n  echo \" - actuation\"\n  echo \" - full-vpa\"\n  echo \"If component is not specified all above will be started.\"\n}\n\nif [ $# -eq 0 ]; then\n  print_help\n  exit 1\nfi\n\nif [ $# -gt 1 ]; then\n  print_help\n  exit 1\nfi\n\nSUITE=$1\n\ncase ${SUITE} in\n  recommender|updater|admission-controller)\n    COMPONENTS=\"${SUITE}\"\n    ;;\n  full-vpa)\n    COMPONENTS=\"recommender updater admission-controller\"\n    ;;\n  actuation)\n    COMPONENTS=\"updater admission-controller\"\n    ;;\n  *)\n    print_help\n    exit 1\n    ;;\nesac\n\nexport REGISTRY=gcr.io/`gcloud config get-value core/project`\nexport TAG=latest\n\necho \"Configuring registry authentication\"\nmkdir -p \"${HOME}/.docker\"\ngcloud auth configure-docker -q\n\nfor i in ${COMPONENTS}; do\n  if [ $i == admission-controller ] ; then\n    (cd ${SCRIPT_ROOT}/pkg/${i} && bash ./gencerts.sh || true)\n  fi\n  make --directory ${SCRIPT_ROOT}/pkg/${i} release\ndone\n\nkubectl create -f ${SCRIPT_ROOT}/deploy/vpa-v1-crd.yaml\nkubectl create -f ${SCRIPT_ROOT}/deploy/vpa-rbac.yaml\n\nfor i in ${COMPONENTS}; do\n  ${SCRIPT_ROOT}/hack/vpa-process-yaml.sh  ${SCRIPT_ROOT}/deploy/${i}-deployment.yaml | kubectl create -f -\ndone\n\n", "num_lines": 83}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\nfunction print_help {\n  echo \"ERROR! Usage: run-e2e-tests.sh <suite>\"\n  echo \"<suite> should be one of:\"\n  echo \" - recommender\"\n  echo \" - updater\"\n  echo \" - admission-controller\"\n  echo \" - actuation\"\n  echo \" - full-vpa\"\n}\n\n\nif [ $# -eq 0 ]; then\n  print_help\n  exit 1\nfi\n\nif [ $# -gt 1 ]; then\n  print_help\n  exit 1\nfi\n\nSUITE=$1\n\ncase ${SUITE} in\n  recommender|updater|admission-controller|actuation|full-vpa)\n    export KUBECONFIG=$HOME/.kube/config\n    go test ${SCRIPT_ROOT}/e2e/v1beta2/*go -v -test.timeout=60m  --args --ginkgo.v=true --ginkgo.focus=\"\\[VPA\\] \\[${SUITE}\\]\" --report-dir=/workspace/_artifacts --disable-log-dump\n    FIRST_RESULT=$?\n    go test ${SCRIPT_ROOT}/e2e/v1/*go -v -test.timeout=60m  --args --ginkgo.v=true --ginkgo.focus=\"\\[VPA\\] \\[${SUITE}\\]\" --report-dir=/workspace/_artifacts --disable-log-dump\n    echo First test result: ${FIRST_RESULT}\n    if [ $FIRST_RESULT -gt 0 ]; then\n      echo \"Please check first \\\"go test\\\" logs!\"\n    fi\n    ;;\n  *)\n    print_help\n    exit 1\n    ;;\nesac\n", "num_lines": 61}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\nfunction print_help {\n  echo \"ERROR! Usage: run-e2e.sh <suite>\"\n  echo \"<suite> should be one of:\"\n  echo \" - recommender\"\n  echo \" - updater\"\n  echo \" - admission-controller\"\n  echo \" - actuation\"\n  echo \" - full-vpa\"\n}\n\nif [ $# -eq 0 ]; then\n  print_help\n  exit 1\nfi\n\nif [ $# -gt 1 ]; then\n  print_help\n  exit 1\nfi\n\nSUITE=$1\n\ncase ${SUITE} in\n  recommender|updater|admission-controller|actuation|full-vpa)\n    ${SCRIPT_ROOT}/hack/vpa-down.sh\n    ${SCRIPT_ROOT}/hack/deploy-for-e2e.sh ${SUITE}\n    ${SCRIPT_ROOT}/hack/run-e2e-tests.sh ${SUITE}\n    ;;\n  *)\n    print_help\n    exit 1\n    ;;\nesac\n\n", "num_lines": 56}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd ${SCRIPT_ROOT}; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../../code-generator)}\n\n# generate the code with:\n# --output-base    because this script should also be able to run inside the vendor dir of\n#                  k8s.io/kubernetes. The output-base is needed for the generators to output into the vendor dir\n#                  instead of the $GOPATH directly. For normal projects this can be dropped.\n${CODEGEN_PKG}/generate-groups.sh all \\\n  k8s.io/autoscaler/vertical-pod-autoscaler/pkg/client k8s.io/autoscaler/vertical-pod-autoscaler/pkg/apis \\\n  \"autoscaling.k8s.io:v1 autoscaling.k8s.io:v1beta2 autoscaling.k8s.io:v1beta1 poc.autoscaling.k8s.io:v1alpha1\" \\\n  --output-base \"$(dirname ${BASH_SOURCE})/../../../..\"\n\n# To use your own boilerplate text append:\n#   --go-header-file ${SCRIPT_ROOT}/hack/custom-boilerplate.go.txt\n", "num_lines": 35}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/pkg\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/pkg\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 49}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\n$SCRIPT_ROOT/hack/vpa-process-yamls.sh apply $*\n", "num_lines": 24}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\n$SCRIPT_ROOT/hack/vpa-process-yamls.sh delete $*\n", "num_lines": 24}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\nfunction print_help {\n  echo \"ERROR! Usage: vpa-process-yaml.sh <YAML files>+\"\n  echo \"Script will output content of YAML files separated with YAML document\"\n  echo \"separator and substituting REGISTRY and TAG for pod images\"\n}\n\nif [ $# -eq 0 ]; then\n  print_help\n  exit 1\nfi\n\nDEFAULT_REGISTRY=\"k8s.gcr.io\"\nDEFAULT_TAG=\"0.5.0\"\n\nREGISTRY_TO_APPLY=${REGISTRY-$DEFAULT_REGISTRY}\nTAG_TO_APPLY=${TAG-$DEFAULT_TAG}\n\nif [ \"${REGISTRY_TO_APPLY}\" != \"${DEFAULT_REGISTRY}\" ]; then\n  (>&2 echo \"WARNING! Using image repository from REGISTRY env variable (${REGISTRY_TO_APPLY}) instead of ${DEFAULT_REGISTRY}.\")\nfi\n\nif [ \"${TAG_TO_APPLY}\" != \"${DEFAULT_TAG}\" ]; then\n  (>&2 echo \"WARNING! Using tag from TAG env variable (${TAG_TO_APPLY}) instead of the default (${DEFAULT_TAG}).\")\nfi\n\nfor i in $*; do\n  sed -e \"s,${DEFAULT_REGISTRY}/\\([a-z-]*\\):.*,${REGISTRY_TO_APPLY}/\\1:${TAG_TO_APPLY},\" $i\n  echo \"\"\n  echo \"---\"\ndone\n", "num_lines": 53}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\nfunction print_help {\n  echo \"ERROR! Usage: vpa-process-yamls.sh <action> [<component>]\"\n  echo \"<action> should be either 'create' or 'delete'.\"\n  echo \"<component> might be one of 'admission-controller', 'updater', 'recommender'.\"\n  echo \"If <component> is set, only the deployment of that component will be processed,\"\n  echo \"otherwise all components and configs will be processed.\"\n}\n\nif [ $# -eq 0 ]; then\n  print_help\n  exit 1\nfi\n\nif [ $# -gt 2 ]; then\n  print_help\n  exit 1\nfi\n\nACTION=$1\nCOMPONENTS=\"vpa-beta2-crd vpa-rbac updater-deployment recommender-deployment admission-controller-deployment\"\nif [ ${ACTION} == delete ]; then\n  COMPONENTS+=\" vpa-beta2-crd\"\nfi\n\nif [ $# -gt 1 ]; then\n  COMPONENTS=\"$2-deployment\"\nfi\n\nfor i in $COMPONENTS; do\n  if [ $i == admission-controller-deployment ] ; then\n    if [ ${ACTION} == create ] ; then\n      (bash ${SCRIPT_ROOT}/pkg/admission-controller/gencerts.sh || true)\n    elif [ ${ACTION} == delete ] ; then\n      (bash ${SCRIPT_ROOT}/pkg/admission-controller/rmcerts.sh || true)\n      (bash ${SCRIPT_ROOT}/pkg/admission-controller/delete-webhook.sh || true)\n    fi\n  fi\n  ${SCRIPT_ROOT}/hack/vpa-process-yaml.sh ${SCRIPT_ROOT}/deploy/$i.yaml | kubectl ${ACTION} -f - || true\ndone\n\n", "num_lines": 63}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname ${BASH_SOURCE})/..\n\n$SCRIPT_ROOT/hack/vpa-process-yamls.sh create $*\n", "num_lines": 24}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Unregisters the admission controller webhook.\nset -e\n\necho \"Unregistering VPA admission controller webhook\"\n\nkubectl delete -n kube-system mutatingwebhookconfiguration.v1beta1.admissionregistration.k8s.io vpa-webhook-config\n\n", "num_lines": 24}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Generates the a CA cert, a server key, and a server cert signed by the CA.\n# reference:\n# https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/webhook/gencerts.sh\nset -e\n\nCN_BASE=\"vpa_webhook\"\nTMP_DIR=\"/tmp/vpa-certs\"\n\necho \"Generating certs for the VPA Admission Controller in ${TMP_DIR}.\"\nmkdir -p ${TMP_DIR}\ncat > ${TMP_DIR}/server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out ${TMP_DIR}/caKey.pem 2048\nopenssl req -x509 -new -nodes -key ${TMP_DIR}/caKey.pem -days 100000 -out ${TMP_DIR}/caCert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out ${TMP_DIR}/serverKey.pem 2048\n# Note the CN is the DNS name of the service of the webhook.\nopenssl req -new -key ${TMP_DIR}/serverKey.pem -out ${TMP_DIR}/server.csr -subj \"/CN=vpa-webhook.kube-system.svc\" -config ${TMP_DIR}/server.conf\nopenssl x509 -req -in ${TMP_DIR}/server.csr -CA ${TMP_DIR}/caCert.pem -CAkey ${TMP_DIR}/caKey.pem -CAcreateserial -out ${TMP_DIR}/serverCert.pem -days 100000 -extensions v3_req -extfile ${TMP_DIR}/server.conf\n\necho \"Uploading certs to the cluster.\"\nkubectl create secret --namespace=kube-system generic vpa-tls-certs --from-file=${TMP_DIR}/caKey.pem --from-file=${TMP_DIR}/caCert.pem --from-file=${TMP_DIR}/serverKey.pem --from-file=${TMP_DIR}/serverCert.pem\n\n# Clean up after we're done.\necho \"Deleting ${TMP_DIR}.\"\nrm -rf ${TMP_DIR}\n", "num_lines": 54}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2018 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# Generates the a CA cert, a server key, and a server cert signed by the CA.\n# reference:\n# https://github.com/kubernetes/kubernetes/blob/master/plugin/pkg/admission/webhook/gencerts.sh\nset -e\n\necho \"Deleting VPA Admission Controller certs.\"\nkubectl delete secret --namespace=kube-system vpa-tls-certs\n", "num_lines": 24}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "go get github.com/golang/protobuf/protoc-gen-go\n\nprotoc \\\n--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto \n\n", "num_lines": 6}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nreference_ref=${1:-master}\nreference_git=${2:-.}\n\nif ! `hash benchstat 2>/dev/null`; then\n    echo \"Installing benchstat\"\n    go get golang.org/x/perf/cmd/benchstat\n    go install golang.org/x/perf/cmd/benchstat\nfi\n\ntempdir=`mktemp -d /tmp/go-toml-benchmark-XXXXXX`\nref_tempdir=\"${tempdir}/ref\"\nref_benchmark=\"${ref_tempdir}/benchmark-`echo -n ${reference_ref}|tr -s '/' '-'`.txt\"\nlocal_benchmark=\"`pwd`/benchmark-local.txt\"\n\necho \"=== ${reference_ref} (${ref_tempdir})\"\ngit clone ${reference_git} ${ref_tempdir} >/dev/null 2>/dev/null\npushd ${ref_tempdir} >/dev/null\ngit checkout ${reference_ref} >/dev/null 2>/dev/null\ngo test -bench=. -benchmem | tee ${ref_benchmark}\npopd >/dev/null\n\necho \"\"\necho \"=== local\"\ngo test -bench=. -benchmem  | tee ${local_benchmark}\n\necho \"\"\necho \"=== diff\"\nbenchstat -delta-test=none ${ref_benchmark} ${local_benchmark}", "num_lines": 32}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\nset -eu\n\ngo get github.com/dvyukov/go-fuzz/go-fuzz\ngo get github.com/dvyukov/go-fuzz/go-fuzz-build\n\nif [ ! -e toml-fuzz.zip ]; then\n    go-fuzz-build github.com/pelletier/go-toml\nfi\n\nrm -fr fuzz\nmkdir -p fuzz/corpus\ncp *.toml fuzz/corpus\n\ngo-fuzz -bin=toml-fuzz.zip -workdir=fuzz\n", "num_lines": 16}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# fail out of the script if anything here fails\nset -e\nset -o pipefail\n\n# set the path to the present working directory\nexport GOPATH=`pwd`\n\nfunction git_clone() {\n  path=$1\n  branch=$2\n  version=$3\n  if [ ! -d \"src/$path\" ]; then\n    mkdir -p src/$path\n    git clone https://$path.git src/$path\n  fi\n  pushd src/$path\n  git checkout \"$branch\"\n  git reset --hard \"$version\"\n  popd\n}\n\n# Remove potential previous runs\nrm -rf src test_program_bin toml-test\n\ngo get github.com/pelletier/go-buffruneio\ngo get github.com/davecgh/go-spew/spew\ngo get gopkg.in/yaml.v2\ngo get github.com/BurntSushi/toml\n\n# get code for BurntSushi TOML validation\n# pinning all to 'HEAD' for version 0.3.x work (TODO: pin to commit hash when tests stabilize)\ngit_clone github.com/BurntSushi/toml master HEAD\ngit_clone github.com/BurntSushi/toml-test master HEAD #was: 0.2.0 HEAD\n\n# build the BurntSushi test application\ngo build -o toml-test github.com/BurntSushi/toml-test\n\n# vendorize the current lib for testing\n# NOTE: this basically mocks an install without having to go back out to github for code\nmkdir -p src/github.com/pelletier/go-toml/cmd\nmkdir -p src/github.com/pelletier/go-toml/query\ncp *.go *.toml src/github.com/pelletier/go-toml\ncp -R cmd/* src/github.com/pelletier/go-toml/cmd\ncp -R query/* src/github.com/pelletier/go-toml/query\ngo build -o test_program_bin src/github.com/pelletier/go-toml/cmd/test_program.go\n\n# Run basic unit tests\ngo test github.com/pelletier/go-toml -covermode=count -coverprofile=coverage.out\ngo test github.com/pelletier/go-toml/cmd/tomljson\ngo test github.com/pelletier/go-toml/query\n\n# run the entire BurntSushi test suite\nif [[ $# -eq 0 ]] ; then\n  echo \"Running all BurntSushi tests\"\n  ./toml-test ./test_program_bin | tee test_out\nelse\n  # run a specific test\n  test=$1\n  test_path='src/github.com/BurntSushi/toml-test/tests'\n  valid_test=\"$test_path/valid/$test\"\n  invalid_test=\"$test_path/invalid/$test\"\n\n  if [ -e \"$valid_test.toml\" ]; then\n    echo \"Valid Test TOML for $test:\"\n    echo \"====\"\n    cat \"$valid_test.toml\"\n\n    echo \"Valid Test JSON for $test:\"\n    echo \"====\"\n    cat \"$valid_test.json\"\n\n    echo \"Go-TOML Output for $test:\"\n    echo \"====\"\n    cat \"$valid_test.toml\" | ./test_program_bin\n  fi\n\n  if [ -e \"$invalid_test.toml\" ]; then\n    echo \"Invalid Test TOML for $test:\"\n    echo \"====\"\n    cat \"$invalid_test.toml\"\n\n    echo \"Go-TOML Output for $test:\"\n    echo \"====\"\n    echo \"go-toml Output:\"\n    cat \"$invalid_test.toml\" | ./test_program_bin\n  fi\nfi\n", "num_lines": 89}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\t# Use then new build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_sparc64)\n\tGOOSARCH_in=syscall_linux_sparc64.go\n\tunistd_h=/usr/include/sparc64-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd -arm\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd -arm\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 195}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOARCH\" != \"sparc64\" ]]; then\n\tif [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\t\techo 1>&2 \"In the new build system, mkerrors should not be called directly.\"\n\t\techo 1>&2 \"See README.md\"\n\t\texit 1\n\tfi\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capability.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/keyctl.h>\n#include <linux/netlink.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/watchdog.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|E?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE)/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 570}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "autoscaler", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ `uname -a` = *\"Darwin\"* ]]; then\n  echo \"It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047\"\n  exit 1\nfi\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nPATH=\"$GOPATH/bin:$GOROOT/bin:$PATH\"\n\n# Check proto in manual runs or cron runs.\nif [[ \"$TRAVIS\" != \"true\" || \"$TRAVIS_EVENT_TYPE\" = \"cron\" ]]; then\n  check_proto=\"true\"\nfi\n\nif [ \"$1\" = \"-install\" ]; then\n  go get -d \\\n    google.golang.org/grpc/...\n  go get -u \\\n    github.com/golang/lint/golint \\\n    golang.org/x/tools/cmd/goimports \\\n    honnef.co/go/tools/cmd/staticcheck \\\n    github.com/client9/misspell/cmd/misspell \\\n    github.com/golang/protobuf/protoc-gen-go\n  if [[ \"$check_proto\" = \"true\" ]]; then\n    if [[ \"$TRAVIS\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.3.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif ! which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# TODO: Remove this check and the mangling below once \"context\" is imported\n# directly.\nif git status --porcelain | read; then\n  die \"Uncommitted or untracked files found; commit changes first\"\nfi\n\ngit ls-files \"*.go\" | xargs grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" 2>&1 | tee /dev/stderr | (! read)\ngit ls-files \"*.go\" | xargs grep -l '\"unsafe\"' 2>&1 | (! grep -v '_test.go') | tee /dev/stderr | (! read)\ngit ls-files \"*.go\" | xargs grep -l '\"math/rand\"' 2>&1 | (! grep -v '^examples\\|^stress\\|grpcrand') | tee /dev/stderr | (! read)\ngofmt -s -d -l . 2>&1 | tee /dev/stderr | (! read)\ngoimports -l . 2>&1 | tee /dev/stderr | (! read)\ngolint ./... 2>&1 | (grep -vE \"(_mock|\\.pb)\\.go:\" || true) | tee /dev/stderr | (! read)\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\n# Rewrite golang.org/x/net/context -> context imports (see grpc/grpc-go#1484).\n# TODO: Remove this mangling once \"context\" is imported directly (grpc/grpc-go#711).\ngit ls-files \"*.go\" | xargs sed -i 's:\"golang.org/x/net/context\":\"context\":'\nset +o pipefail\n# TODO: Stop filtering pb.go files once golang/protobuf#214 is fixed.\ngo tool vet -all . 2>&1 | grep -vE '(clientconn|transport\\/transport_test).go:.*cancel (function|var)' | grep -vF '.pb.go:' | tee /dev/stderr | (! read)\nset -o pipefail\ngit reset --hard HEAD\n\nif [[ \"$check_proto\" = \"true\" ]]; then\n  PATH=\"/home/travis/bin:$PATH\" make proto && \\\n    git status --porcelain 2>&1 | (! read) || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# TODO(menghanl): fix errors in transport_test.\nstaticcheck -ignore '\ngoogle.golang.org/grpc/transport/transport_test.go:SA2002\ngoogle.golang.org/grpc/benchmark/benchmain/main.go:SA1019\ngoogle.golang.org/grpc/stats/stats_test.go:SA1019\ngoogle.golang.org/grpc/test/end2end_test.go:SA1019\ngoogle.golang.org/grpc/balancer_test.go:SA1019\ngoogle.golang.org/grpc/balancer.go:SA1019\ngoogle.golang.org/grpc/clientconn_test.go:SA1019\n' ./...\nmisspell -error .\n", "num_lines": 95}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n#\n# The following script mounts a default folder round robined across\n# the vFXT ip addresses.\n#\n# Save this script to any Avere vFXT volume, for example:\n#     /bootstrap/bootstrap.sh\n#\n# The following environment variables must be set:\n#     NFS_IP_CSV=\"10.0.0.22,10.0.0.23,10.0.0.24\"\n#     NFS_PATH=/msazure\n#     BASE_DIR=/nfs\n#\nset -x\nNODE_MOUNT_PREFIX=\"/node\"\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction mount_round_robin() {\n    # to ensure the nodes are spread out somewhat evenly the default\n    # mount point is based on this node's IP octet4 % vFXT node count.\n    declare -a AVEREVFXT_NODES=\"($(echo ${NFS_IP_CSV} | sed \"s/,/ /g\"))\"\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n    DEFAULT_MOUNT_INDEX=$((${OCTET4} % ${#AVEREVFXT_NODES[@]}))\n    ROUND_ROBIN_IP=${AVEREVFXT_NODES[${DEFAULT_MOUNT_INDEX}]}\n\n    DEFAULT_MOUNT_POINT=\"${BASE_DIR}/default\"\n\n    # no need to write again if it is already there\n    if ! grep --quiet \"${DEFAULT_MOUNT_POINT}\" /etc/fstab; then\n        echo \"${ROUND_ROBIN_IP}:${NFS_PATH}    ${DEFAULT_MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n        mkdir -p \"${DEFAULT_MOUNT_POINT}\"\n        chown nobody:nogroup \"${DEFAULT_MOUNT_POINT}\"\n    fi\n    if ! grep -qs \"${DEFAULT_MOUNT_POINT} \" /proc/mounts; then\n        retrycmd_if_failure 12 20 mount \"${DEFAULT_MOUNT_POINT}\" || exit 1\n    fi\n}\n\nfunction mount_all() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            retrycmd_if_failure 60 5 mount ${MOUNT_POINT}\n            chmod 777 ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction main() {\n    echo \"mount round robin default path\"\n    if [ -z $MOUNT_ALL ]; then\n        mount_round_robin\n    else\n        mount_all\n    fi\n\n    # add extra bootstrap and installation code here\n    # this could be:\n    #  - installation bash scripts\n    #  - chef and puppet scripts\n    #  - ansible scripts\n    # when pulling content from the NFS server, ensure to use the round robin path, listed\n    # under the default path, something similar to DEFAULT_MOUNT_POINT=\"${BASE_DIR}/default\"\n}\n\nmain", "num_lines": 91}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n# Save this script to any Avere vFXT volume, for example:\n#     /bootstrap/bootstrap.sh\n#\n# The following environment variables must be set:\n#  BASE_DIR=/nfs\n#  BOOTSTRAP_NFS_IP=10.0.0.22\n#  BOOTSTRAP_SCRIPT_PATH=/bootstrap/bootstrap.sh\n#  NFS_IP_CSV=\"10.0.0.22,10.0.0.23,10.0.0.24\"\n#  NFS_PATH=/msazure\n#\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction install_nfs() {\n    apt-get update && apt-get install -y nfs-common\n}\n\nfunction mount_bootstrap_and_install() {\n    echo \"mount bootstrap, and run bootstrap script\"\n    OPT_DIR=/opt\n    RUN_SCRIPT=$OPT_DIR/bootstrap.sh\n    BOOTSTRAP_BASE_DIR=$BASE_DIR/b\n    mkdir -p $BOOTSTRAP_BASE_DIR\n    retrycmd_if_failure 60 5 mount -o \"hard,nointr,proto=tcp,mountproto=tcp,retry=30\" ${BOOTSTRAP_NFS_IP}:${NFS_PATH} ${BOOTSTRAP_BASE_DIR}\n    mkdir -p $OPT_DIR\n    retrycmd_if_failure 60 5 cp ${BOOTSTRAP_BASE_DIR}${BOOTSTRAP_SCRIPT_PATH} ${RUN_SCRIPT}\n    /bin/bash ${RUN_SCRIPT} 2>&1 | tee -a /var/log/bootstrap.log\n    umount $BOOTSTRAP_BASE_DIR\n    rmdir $BOOTSTRAP_BASE_DIR\n}\n\nfunction debug_dump_env_vars() {\n    echo \"start env dump\"\n    echo $(pwd)\n    echo \"export BASE_DIR=$BASE_DIR\"\n    echo \"export BOOTSTRAP_NFS_IP=$BOOTSTRAP_NFS_IP\"\n    echo \"export BOOTSTRAP_SCRIPT_PATH=$BOOTSTRAP_SCRIPT_PATH\"\n    echo \"export NFS_IP_CSV=$NFS_IP_CSV\"\n    echo \"export NFS_PATH=$NFS_PATH\"\n    echo \"finish env dump\"\n}\n\nfunction main() {\n    echo \"install NFS\"\n    retrycmd_if_failure 60 5 install_nfs\n\n    echo \"dump env vars\"\n    debug_dump_env_vars\n\n    echo \"mount bootstrap and install\"\n    mount_bootstrap_and_install\n}\n\nmain", "num_lines": 70}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# This script configures the VMSS Host, and does the following:\n#   1. sets the hostname to HOST_NAME_PREFIX + suffix of last two\n#      octets of ip address\n#   2. installs NFS and mounts the nas filer\n# \n# Requires the following environment variables to be set:\n#   HOST_NAME_PREFIX - is the prefix for the \n#   NFS_HOST - this is the hostname or ip address of the NFS filer\n#   NFS_EXPORT - this is the path exported \n#   LOCAL_MOUNTPOINT - this is the local mount point\n\nset -x # Display executed commands\n\nfunction GetHostAddress() {\n       for i in {1..120}; do\n              hostname --all-ip-addresses > /dev/null\n              if [ $? -eq 0 ]\n              then\n                     break\n              fi\n              sleep 1\n       done\n       echo $(hostname --all-ip-addresses | cut -d' ' -f1)\n}\n\nfunction GetHostName() {\n       hostAddress=\"$(GetHostAddress)\"\n       hostAddressOctet3=\"$(cut --delimiter '.' --fields 3 <<< $hostAddress)\"\n       hostAddressOctet4=\"$(cut --delimiter '.' --fields 4 <<< $hostAddress)\"\n       echo \"$HOST_NAME_PREFIX-$hostAddressOctet3-$hostAddressOctet4\"\n}\n\nfunction SetHostName() {\n       hostname $(GetHostName)\n       /etc/init.d/network restart\n}\n\nfunction InstallNFS() {\n    yum -y install nfs-utils\n}\n\nfunction MountNFS() {\n    mkdir -p $LOCAL_MOUNTPOINT\n    r=5\n    for i in $(seq 1 $r); do\n        mount -o 'hard,nointr,proto=tcp,mountproto=tcp,retry=30' ${NFS_HOST}:${NFS_EXPORT} $LOCAL_MOUNTPOINT && break\n        [ $i == $r ] && break 0\n        sleep 5\n    done\n}\n\nfunction main() {\n    SetHostName\n\n    #InstallNFS\n\n    #MountNFS\n}\n\nmain\n", "num_lines": 64}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        timeout $timeout ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        # timeout occasionally freezes\n        #echo \"timeout $timeout apt-get install --no-install-recommends -y ${@}\"\n        #timeout $timeout apt-get install --no-install-recommends -y ${@}\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n\texport DEBIAN_FRONTEND=noninteractive\n\tapt_get_update\n\tapt_get_install 20 10 180 nfs-common parallel\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"$VFXT\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction write_parallelcp() {\n    FILENAME=/usr/bin/parallelcp\n    sudo touch $FILENAME\n    sudo chmod 755 $FILENAME\n    sudo /bin/cat <<EOM >$FILENAME\n#!/bin/bash\n\ndisplay_usage() {\n    echo -e \"\\nUsage: \\$0 SOURCE_DIR DEST_DIR\\n\"\n}\n\nif [  \\$# -le 1 ] ; then\n    display_usage\n    exit 1\nfi\n\nif [[ ( \\$# == \"--help\") ||  \\$# == \"-h\" ]] ; then\n    display_usage\n    exit 0\nfi\n\nSOURCE_DIR=\"\\$1\"\nDEST_DIR=\"\\$2\"\n\nif [ ! -d \"\\$SOURCE_DIR\" ] ; then\n    echo \"Source directory \\$SOURCE_DIR does not exist, or is not a directory\"\n    display_usage\n    exit 2\nfi\n\nif [ ! -d \"\\$DEST_DIR\" ] && ! mkdir -p \\$DEST_DIR ; then\n    echo \"Destination directory \\$DEST_DIR does not exist, or is not a directory\"\n    display_usage\n    exit 2\nfi\n\nif [ ! -w \"\\$DEST_DIR\" ] ; then\n    echo \"Destination directory \\$DEST_DIR is not writeable, or is not a directory\"\n    display_usage\n    exit 3\nfi\n\nif ! which parallel > /dev/null ; then\n    sudo apt-get update && sudo apt install -y parallel\nfi\n\nDIRJOBS=225\nJOBS=225\nfind \\$SOURCE_DIR -mindepth 1 -type d -print0 | sed -z \"s:\\$SOURCE_DIR\\/::\" | parallel --will-cite -j\\$DIRJOBS -0 \"mkdir -p \\$DEST_DIR/{}\"\nfind \\$SOURCE_DIR -mindepth 1 ! -type d -print0 | sed -z \"s:\\$SOURCE_DIR\\/::\" | parallel --will-cite -j\\$JOBS -0 \"cp -P \\$SOURCE_DIR/{} \\$DEST_DIR/{}\"\nEOM\n}\n\nfunction write_msrsync() {\n    # install this from https://github.com/jbd/msrsync\n    FILENAME=/usr/bin/msrsync\n    sudo touch $FILENAME\n    sudo chmod 755 $FILENAME\n    sudo curl --retry 5 --retry-delay 5 -o $FILENAME https://raw.githubusercontent.com/jbd/msrsync/master/msrsync\n    sudo chmod +x $FILENAME\n\n    PRIMEFILE=/usr/bin/prime.py\n    sudo curl --retry 5 --retry-delay 5 -o $PRIMEFILE https://raw.githubusercontent.com/Azure/Avere/main/src/clientapps/dataingestor/prime.py\n    sudo chmod +x $PRIMEFILE\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n    echo \"mount avere\"\n    mount_avere\n    echo \"write parallelcp\"\n    write_parallelcp\n    echo \"install msrsync\"\n    write_msrsync\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 157}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nTARGETDIR=/nfs/node0/bootstrap\nDATAINGESTORINSTALL=$TARGETDIR/bootstrap.dataingestor.sh\n\nif [ ! -d \"$TARGETDIR\" ]; then\n    echo \"ERROR: directory $TARGETDIR does not exist\"\n    exit 1\nelse\n    echo \"SUCCESS: $TARGETDIR found\"\nfi\n\nif ! ls $DATAINGESTORINSTALL > /dev/null 2>&1; then\n    echo \"MISSING: $DATAINGESTORINSTALL.  Please download the install script per instructions.\"\nelse\n    echo \"SUCCESS: $DATAINGESTORINSTALL found\"\nfi", "num_lines": 18}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n#\n# The following script mounts a default folder round robined across\n# the vFXT ip addresses.\n#\n# Save this script to any Avere vFXT volume, for example:\n#     /bootstrap/bootstrap.sh\n#\n# The following environment variables must be set, example values below that may not match your environment:\n#     NFS_IP_CSV=\"10.0.0.22,10.0.0.23,10.0.0.24\" # the ip addresses for your NFS (vFXT, ot HPC Cache) servers in CSV format\n#     NFS_PATH=/msazure # the path on the NFS server that you want to mount\n#     BASE_DIR=/nfs # base directory where your NFS server will be mounted\n#     CUEBOT_HOSTNAME=\"10.0.0.30\" # Cuebot IP address (or hostname)\n#     CUEBOT_FS_ROOT=$BASE_DIR/opencue-demo # Cuebot filesystem root, used to store Cuebot logs\n#\nset -x\nNODE_MOUNT_PREFIX=\"/node\"\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction mount_round_robin() {\n    # to ensure the nodes are spread out somewhat evenly the default\n    # mount point is based on this node's IP octet4 % vFXT node count.\n    declare -a AVEREVFXT_NODES=\"($(echo ${NFS_IP_CSV} | sed \"s/,/ /g\"))\"\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n    DEFAULT_MOUNT_INDEX=$((${OCTET4} % ${#AVEREVFXT_NODES[@]}))\n    ROUND_ROBIN_IP=${AVEREVFXT_NODES[${DEFAULT_MOUNT_INDEX}]}\n\n    DEFAULT_MOUNT_POINT=\"${BASE_DIR}/opencue-demo\"\n\n    # no need to write again if it is already there\n    if ! grep --quiet \"${DEFAULT_MOUNT_POINT}\" /etc/fstab; then\n        echo \"${ROUND_ROBIN_IP}:${NFS_PATH}    ${DEFAULT_MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n        mkdir -p \"${DEFAULT_MOUNT_POINT}\"\n        chown nobody:nogroup \"${DEFAULT_MOUNT_POINT}\"\n    fi\n    if ! grep -qs \"${DEFAULT_MOUNT_POINT} \" /proc/mounts; then\n        retrycmd_if_failure 12 20 mount \"${DEFAULT_MOUNT_POINT}\" || exit 1\n    fi\n}\n\nfunction mount_all() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            retrycmd_if_failure 60 5 mount ${MOUNT_POINT}\n            chmod 777 ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction main() {\n    echo \"mount round robin default path\"\n    if [ -z $MOUNT_ALL ]; then\n        mount_round_robin\n    else\n        mount_all\n    fi\n\n    # Build and install PBRT on render nodes\n    # Reference: https://github.com/mmp/pbrt-v3/\n    cd /\n    apt install -yq cmake build-essential gcc-4.8 g++-4.8 make bison flex libpthread-stubs0-dev\n    update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-4.8 40 --slave /usr/bin/g++ g++ /usr/bin/g++-4.8\n    git clone --recursive https://github.com/mmp/pbrt-v3/\n    mkdir pbrt\n    cd pbrt\n    cmake -DCMAKE_BUILD_TYPE=Release ../pbrt-v3/\n    make\n\n    # Use pre-built pbrt tools\n    # If you have pre-built PBRT (or another render engine and it is stored on your NFS server) you can copy it to your render nodes for use\n    # echo \"copy PBRT from cache to /opencue-tools/tools/pbrt-release/pbrt\"\n    # mkdir /opencue-tools\n    # cp -r \"${BASE_DIR}/opencue-demo/tools\" /opencue-tools\n\n\n    # Set up the RQD environment on each node\n    # Based on https://www.opencue.io/docs/getting-started/deploying-rqd/\n    echo \"set up RQD server and connect to CueBot server\"\n\n    # yum based install\n    # yum -y install gcc\n    # yum -y install python3-devel\n    # yum -y install redhat-rpm-config\n    # cd /usr/local/bin\n    # pip3 install -r opencue-requirements.txt\n    # tar -xzf opencue-rqd.tar.gz\n    # find . -type f -name '*.pyc' -delete\n    # cd rqd-*\n    # python3 setup.py install\n    \n    # apt based install\n    apt install -yq python3 python3-dev python3-pip gcc\n    cd ~\n    echo \"CUEBOT_HOSTNAME=$CUEBOT_HOSTNAME\"\n    echo \"CUE_FS_ROOT=$CUE_FS_ROOT\"\n    wget \"https://github.com/AcademySoftwareFoundation/OpenCue/releases/download/0.4.14/rqd-0.4.14-all.tar.gz\"\n    export RQD_TARBALL=\"rqd-0.4.14-all.tar.gz\"\n    export RQD_DIR=$(basename \"${RQD_TARBALL}\" .tar.gz)\n    tar zxvf \"$RQD_TARBALL\"\n    cd \"$RQD_DIR\"\n    pip3 install -r requirements.txt\n    python3 setup.py install\n    cd ..\n    rm -rf \"$RQD_DIR\"\n    /usr/bin/nohup /bin/bash -c \"rqd\" > /dev/null 2>&1 &\n\n    # add extra bootstrap and installation code here\n    # this could be:\n    #  - installation bash scripts\n    #  - chef and puppet scripts\n    #  - ansible scripts\n    # when pulling content from the NFS server, ensure to use the round robin path, listed\n    # under the default path, something similar to DEFAULT_MOUNT_POINT=\"${BASE_DIR}/default\"\n}\n\nmain", "num_lines": 142}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# /datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island.png island.pbrt\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/islandX.png islandX.pbrt > islandX.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_beachCam.png island_beachCam.pbrt > island_beachCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_dunesACam.png island_dunesACam.pbrt > island_dunesACam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_frame90.png island_frame90.pbrt > island_frame90.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_grassCam.png island_grassCam.pbrt > island_grassCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_hibiscusCam.png island_hibiscusCam.pbrt > island_hibiscusCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_palmsCam.png island_palmsCam.pbrt > island_palmsCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_rootsCam.png island_rootsCam.pbrt > island_rootsCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_shotCam.png island_shotCam.pbrt > island_shotCam.log\n/datadrive/pbrt/release/pbrt -outfile /home/AzureUser/island_4096.png island_4096.pbrt > island_4096.log", "num_lines": 13}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\nset -x\n\nNODE_MOUNT_PREFIX=\"/node\"\nHOST_DNS_SERVER=\"168.63.129.16\"\n\n#######################################\n# wait for network to become ready\n#######################################\nensureAzureNetwork()\n{\n  # ensure the hostname -i works\n  networkHealthy=1\n  for i in {1..120}; do\n    hostname -i\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 1\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, cannot resolve ip address, aborting install\"\n    ifconfig\n    ip a\n    exit 2\n  fi\n  # ensure all names are resolvable\n  networkHealthy=1\n  for i in {1..240}; do\n    COUNTER=0\n    if hostname -s | grep -E \"000[0-9A-Fa-f]{3}$\" > /dev/null ; then\n        # these are VMSS nodes, count the VMSS nodes\n        LOCAL_IP=$(host vmss000000${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep vmss000000 | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n\tIFS=\".\" read -a IP_ARRAY <<< $LOCAL_IP\n        FAILURE_COUNTER=0\n        FAILURE_MAX=255\n        while (( (COUNTER-FAILURE_COUNTER) < NODE_COUNT && FAILURE_COUNTER < $FAILURE_MAX )); do\n            VMSS_INDEX=$COUNTER\n            FOURTH_OCT=$((${IP_ARRAY[3]}+$COUNTER))\n            # VMSS_INDEX_HEX=$( printf '%06x' $VMSS_INDEX )\n            # NODE_NAME=\"${NODE_PREFIX}${VMSS_INDEX_HEX}\"\n            # IP=$( host ${NODE_NAME}${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep ${NODE_NAME} | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n            NODE_NAME=$(nslookup -a ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT | awk '{print $4}' | cut -d. -f1 | grep vmss)\n\n            if [ $? -ne 0 ] ; then\n                FAILURE_COUNTER=$[$FAILURE_COUNTER+1]\n            fi\n            COUNTER=$[$COUNTER+1]\n        done\n        COUNTER=$[$COUNTER-$FAILURE_COUNTER]\n    else    \n        # these are VM nodes, count the VMs\n        while [ $COUNTER -lt $NODE_COUNT ]; do\n            HOST_NUMBER=$(($COUNTER + 1))\n            HOST_NUMBER_HEX=$( printf '%02x' $HOST_NUMBER )\n            NODE_NAME=\"${NODE_PREFIX}-${COUNTER}\"\n            host ${NODE_NAME}${DNS_SUFFIX} ${HOST_DNS_SERVER}\n            if [ $? -ne 0 ]\n            then\n                echo \"command 'host ${NODE_NAME}${DNS_SUFFIX} ${HOST_DNS_SERVER}' failed\"\n                break\n            fi\n            COUNTER=$[$COUNTER+1]\n        done\n    fi\n    if [ $COUNTER -eq $NODE_COUNT ]\n    then\n        # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 1\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"not all vdbench host names resolve, is DNS blocked?, aborting install\"\n    exit 1\n  fi\n  # ensure hostname -f works\n  networkHealthy=1\n  for i in {1..120}; do\n    hostname -f\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 1\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, cannot resolve hostname, aborting install\"\n    ifconfig\n    ip a\n    exit 2\n  fi\n  VMNAME=`hostname`\n}\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n    export DEBIAN_FRONTEND=noninteractive\n    apt_get_update\n    apt_get_install 20 10 180 default-jre zip csh unzip tmux\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            retrycmd_if_failure 60 5 mount ${MOUNT_POINT}\n            chmod 777 ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction install_vdbench() {\n    DIRECTORY=/home/$LINUX_USER/vdbench\n    if [ -d \"$DIRECTORY\" ]; then\n      # already installed\n      return 0\n    fi\n    mkdir -p $DIRECTORY\n    pushd $DIRECTORY\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n    VDBENCHSRC=\"$BOOTSTRAP_PATH/vdbench*.zip\"\n\n    if ! ls $VDBENCHSRC > /dev/null 2>&1; then\n        echo \"MISSING: $VDBENCHSRC, please ensure the vdbench zip is downloaded to the bootstrap directory and reinstall.\"\n        exit 1\n    fi\n\n    cp $VDBENCHSRC .\n    unzip vdbench*.zip\n    rm vdbench*.zip\n    popd\n    echo \"chown -R $LINUX_USER:$LINUX_USER $DIRECTORY\"\n    chown -R $LINUX_USER:$LINUX_USER $DIRECTORY\n}\n\nfunction write_run_vdbench() {\n    FILENAME=/home/$LINUX_USER/run_vdbench.sh\n    /bin/cat <<EOM >$FILENAME\n#!/usr/bin/env bash\nCONF=\\$1\nUNIQ=\\$2\nJUNC=vdbench\n/home/$LINUX_USER/vdbench/vdbench -f /home/$LINUX_USER/\\${CONF} -o /home/$LINUX_USER/vdbench/output/\\`date +%F\\`_\\${CONF}_\\${UNIQ}\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n    chmod +x $FILENAME\n}\n\nfunction write_copy_idrsa() {\n    FILENAME=/home/$LINUX_USER/copy_idrsa.sh\n    echo \"#!/usr/bin/env bash\" > \"copy_idrsa.sh\"\n    COUNTER=0\n    while [ $COUNTER -lt $NODE_COUNT ]; do\n        LOCAL_IP=$(host vmss000000${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep vmss000000 | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n\tIFS=\".\" read -a IP_ARRAY <<< $LOCAL_IP\n\tFOURTH_OCT=$((${IP_ARRAY[3]}+$COUNTER))\n        NODE_NAME=$(nslookup -a ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT | awk '{print $4}' | cut -d. -f1 | grep vmss)\n        echo \"scp -o \\\"StrictHostKeyChecking no\\\" /home/$LINUX_USER/.ssh/id_rsa ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT:.ssh/id_rsa\" >> $FILENAME\n        COUNTER=$[$COUNTER+1]\n    done\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n    chmod +x $FILENAME\n}\n\nfunction write_azure_clients() {\n    FILENAME=/home/$LINUX_USER/azure-clients.conf\n/bin/cat <<EOM >$FILENAME\nhd=default,user=${LINUX_USER},shell=ssh\nEOM\n    # add each of the clients\n    COUNTER=0\n    while [ $COUNTER -lt $NODE_COUNT ]; do\n        HOST_NUMBER=$(($COUNTER + 1))\n\tLOCAL_IP=$(host vmss000000${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep vmss000000 | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n        IFS=\".\" read -a IP_ARRAY <<< $LOCAL_IP\n\tFOURTH_OCT=$((${IP_ARRAY[3]}+$COUNTER))\n        NODE_NAME=$(nslookup -a ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT | awk '{print $4}' | cut -d. -f1 | grep vmss)\n        echo \"NODE NAME ${NODE_NAME}, ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT\"\n        echo \"hd=host${HOST_NUMBER},system=${IP}\">>$FILENAME\n        COUNTER=$[$COUNTER+1]\n    done\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_vmss_copy_idrsa() {\n    FILENAME=/home/$LINUX_USER/copy_idrsa.sh\n    echo \"#!/usr/bin/env bash\" > \"copy_idrsa.sh\"\n    COUNTER=0\n    FAILURE_COUNTER=0\n    FAILURE_MAX=255\n    while (( (COUNTER-FAILURE_COUNTER) < NODE_COUNT && FAILURE_COUNTER < $FAILURE_MAX )); do\n        VMSS_INDEX=$COUNTER\n\tLOCAL_IP=$(host vmss000000${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep vmss000000 | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n        IFS=\".\" read -a IP_ARRAY <<< $LOCAL_IP\n\tFOURTH_OCT=$((${IP_ARRAY[3]}+$COUNTER))\n        NODE_NAME=$(nslookup -a ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT | awk '{print $4}' | cut -d. -f1 | grep vmss)\n        IP=${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"${FOURTH_OCT}\n        if [ $? -ne 0 ] ; then\n                FAILURE_COUNTER=$[$FAILURE_COUNTER+1]\n        else\n                echo \"scp -o \\\"StrictHostKeyChecking no\\\" /home/$LINUX_USER/.ssh/id_rsa ${IP}:.ssh/id_rsa\" >> $FILENAME\n        fi\n        COUNTER=$[$COUNTER+1]\n    done\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n    chmod +x $FILENAME\n}\n\nfunction write_vmss_azure_clients() {\n    FILENAME=/home/$LINUX_USER/azure-clients.conf\n/bin/cat <<EOM >$FILENAME\nhd=default,user=${LINUX_USER},shell=ssh\nEOM\n    # add each of the clients\n    COUNTER=0\n    FAILURE_COUNTER=0\n    FAILURE_MAX=255\n    while (( (COUNTER-FAILURE_COUNTER) < NODE_COUNT && FAILURE_COUNTER < $FAILURE_MAX )); do\n        HOST_NUMBER=$[1+($COUNTER-$FAILURE_COUNTER)]\n\tLOCAL_IP=$(host vmss000000${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep vmss000000 | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n        IFS=\".\" read -a IP_ARRAY <<< $LOCAL_IP\n\tFOURTH_OCT=$((${IP_ARRAY[3]}+$COUNTER))\n\tNODE_NAME=$(nslookup -a  ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT | awk '{print $4}' | cut -d. -f1 | grep vmss)\n        # HOST_NUMBER_HEX=$( printf '%02x' $HOST_NUMBER )\n        VMSS_INDEX=$COUNTER\n        # VMSS_INDEX_HEX=$( printf '%06x' $VMSS_INDEX )\n        # NODE_NAME=\"${NODE_PREFIX}${VMSS_INDEX}\"\n        # IP=$( host ${NODE_NAME}${DNS_SUFFIX} ${HOST_DNS_SERVER} | grep ${NODE_NAME} | grep -oE '((1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])\\.){3}(1?[0-9][0-9]?|2[0-4][0-9]|25[0-5])' )\n\n        if [ $? -ne 0 ] ; then\n                FAILURE_COUNTER=$[$FAILURE_COUNTER+1]\n        else\n                echo \"NODE NAME ${NODE_NAME}, ${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT\"\n                echo \"hd=host$(seq -f \"%03g\" ${HOST_NUMBER} ${HOST_NUMBER}),system=${IP_ARRAY[0]}\".\"${IP_ARRAY[1]}\".\"${IP_ARRAY[2]}\".\"$FOURTH_OCT\">>$FILENAME\n        fi\n        COUNTER=$[$COUNTER+1]\n    done\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_inmem() {\n    FILENAME=/home/$LINUX_USER/inmem.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=28,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=24\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=600,fwdrate=max,interval=1,maxdata=126g,rd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\nrd=readall1,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\nrd=readall2,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nrd=readall3,fwd=(fwdRhost*),format=no,maxdata=432g\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_inmem_32() {\n    FILENAME=/home/$LINUX_USER/inmem32.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=64,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=24\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=1080,fwdrate=max,interval=1,maxdata=72g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\nrd=readall1,fwd=(fwdRhost*)\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\nrd=readall2,fwd=(fwdRhost*),format=no\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nrd=readall3,fwd=(fwdRhost*)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_perf.conf() {\n    FILENAME=/home/$LINUX_USER/max_perf.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=64,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd_thrp!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!${FSD_HOST},depth=1,files=3,sizes=1g,width=1\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd_iops!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!${FSD_HOST},depth=1,files=32,sizes=256m,width=1\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\nfwd=format,threads=18,xfersize=512k,openflags=fsync\nfwd=fwd_thrp!host,fsd=(fsd_thrp!host*),host=!host,fileio=sequential,operation=write,openflags=directio,threads=6,xfersize=32m\nfwd=fwd_iops!host,fsd=(fsd_iops!host*),host=!host,fileio=sequential,operation=write,openflags=directio,threads=6,xfersize=32m\nfwd=fwd_rd_thrp!host,fsd=(fsd_thrp!host*),host=!host,fileio=sequential,fileselect=sequential,operation=read,openflags=o_direct,threads=9,xfersize=32m\nfwd=fwd_rd_iops!host,fsd=(fsd_iops!host*),host=!host,fileio=random,fileselect=random,operation=read,openflags=o_direct,threads=96,xfersize=4k\nfwd=fwd_wr_thrp!host,fsd=(fsd_thrp!host*),host=!host,fileio=sequential,fileselect=sequential,operation=write,openflags=o_direct,threads=6,xfersize=32m\nfwd=fwd_wr_iops!host,fsd=(fsd_iops!host*),host=!host,fileio=random,fileselect=random,operation=write,openflags=o_direct,threads=64,xfersize=4k\n\nrd=format_thrp_files,fwd=fwd_thrp*,fwdrate=max,format=yes,elapsed=2,interval=1\nrd=format_iops_files,fwd=fwd_iops*,fwdrate=max,format=yes,elapsed=2,interval=1\nrd=filesys_maxRDthrp,fwd=fwd_rd_thrp*,fwdrate=max,format=no,elapsed=120,interval=1\nrd=filesys_maxRDiops,fwd=fwd_rd_iops*,fwdrate=max,format=no,elapsed=120,interval=1\nrd=filesys_maxWRthrp,fwd=fwd_wr_thrp*,fwdrate=max,format=no,elapsed=120,interval=1\nrd=filesys_maxWRiops,fwd=fwd_wr_iops*,fwdrate=max,format=no,elapsed=120,interval=1\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_3node_inmem32() {\n    FILENAME=/home/$LINUX_USER/inmem32node3.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=64,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=24\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=1080,fwdrate=max,interval=1,maxdata=144g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\nrd=readall1,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\nrd=readall2,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nrd=readall3,fwd=(fwdRhost*),format=no,maxdata=432g\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_6node_inmem32() {\n    FILENAME=/home/$LINUX_USER/inmem32node6.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=96,size=16m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=24\nfwd=format,xfersize=512k,threads=24\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=300,fwdrate=max,interval=1,maxdata=216g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*),format=restart,maxdata=1m\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall1,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles2,fwd=(fwdWhost*),format=no\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall2,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall3,fwd=(fwdRhost*),format=no,maxdata=432g\n\nrd=deleteall1=fwd(fwdRhost*),format=no,operations=(delete),maxdata=1m\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_3node_32client_inmem() {\n    FILENAME=/home/$LINUX_USER/3node_32client_inmem.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=38,size=21m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/vdbench/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=18\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync,threads=12\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct,threads=30\n\nrd=default,elapsed=600,fwdrate=max,interval=1,maxdata=126g,rd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=readall1,fwd=(fwdRhost*),format=no,maxdata=432g\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=readall2,fwd=(fwdRhost*),format=no,maxdata=432g\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=readall3,fwd=(fwdRhost*),format=no,maxdata=432g\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_ondisk() {\n    FILENAME=/home/$LINUX_USER/ondisk.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=180,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/!junction/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=format,threads=18,xfersize=512k,openflags=fsync\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=18\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=10800,fwdrate=max,interval=1,maxdata=202.5g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\nrd=readall1,fwd=(fwdRhost*)\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\nrd=readall2,fwd=(fwdRhost*)\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nrd=readall3,fwd=(fwdRhost*)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_3node_32_ondisk() {\n    FILENAME=/home/$LINUX_USER/ondisk32_3node.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=768,size=64m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/!junction/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=format,threads=18,xfersize=512k,openflags=fsync\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=18\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=2400,fwdrate=max,interval=1,maxdata=1728g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\nrd=readall1,fwd=(fwdRhost*)\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\nrd=readall2,fwd=(fwdRhost*)\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nrd=readall3,fwd=(fwdRhost*)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_6node_32_ondisk() {\n    FILENAME=/home/$LINUX_USER/ondisk32_6node.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=1024,size=24m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/!junction/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential,threads=24\nfwd=format,xfersize=512k,threads=24\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=2000,fwdrate=max,interval=1,maxdata=3.375t\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*),format=restart,maxdata=1m\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall1,fwd=(fwdRhost*),format=no\n\nrd=writefiles2,fwd=(fwdWhost*),format=no\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall2,fwd=(fwdRhost*),format=no\n\n# only do this cycle twice, since it takes an hour each lap around the track\n\nrd=deleteall1=fwd(fwdRhost*),format=no,operations=(delete),maxdata=1m\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_3node_32client_ondisk() {\n    FILENAME=/home/$LINUX_USER/3node_32client_ondisk.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=1,files=180,size=32m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/!junction/!sizedir/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=format,threads=18,xfersize=512k,openflags=fsync\nfwd=default,xfersize=512k,fileio=sequential,fileselect=sequential\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync,threads=18\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct,threads=30\n\nrd=default,elapsed=10800,fwdrate=max,interval=1,maxdata=202.5g\nrd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\nrd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*)\nrd=readall1,fwd=(fwdRhost*)\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*)\n\nrd=writefiles2,fwd=(fwdWhost*)\nrd=readall2,fwd=(fwdRhost*)\nrd=writeread2,fwd=(fwdRhost*,fwdWhost*)\n\nrd=writefiles3,fwd=(fwdWhost*)\nrd=readall3,fwd=(fwdRhost*)\nrd=writeread3,fwd=(fwdRhost*,fwdWhost*)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_throughput() {\n    FILENAME=/home/$LINUX_USER/throughput.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\n#N vFXT nodes ${NFS_IP_CSV}, 12 clients, 36 FSDs, 1TiB workingset\nfsd=default,depth=1,width=1,files=180,size=160m\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/sequential/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=format,threads=36,xfersize=512k,openflags=fsync\nfwd=default,threads=36,xfersize=512k,fileio=sequential,fileselect=sequential\nfwd=fwdW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync\nfwd=fwdR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\n\nrd=default,elapsed=10800,fwdrate=max,interval=1,maxdata=1012.5g\n#rd=makedirs1,fwd=(fwdWhost*),operations=(mkdir),maxdata=1m\n#rd=makefiles1,fwd=(fwdWhost*),operations=(create),maxdata=1m\n\nrd=writefiles1,fwd=(fwdWhost*),format=restart\nrd=writeread1,fwd=(fwdRhost*,fwdWhost*),format=no\nrd=readall1,fwd=(fwdRhost*),format=no\nrd=delall1,fwd=(fwdRhost*),operations=(delete),maxdata=1m\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_smallfileIO() {\n    FILENAME=/home/$LINUX_USER/smallfileIO.conf\n    /bin/cat <<EOM >$FILENAME\ncreate_anchors=yes\ninclude=azure-clients.conf\n\nfsd=default,depth=1,width=10,files=1500,size=384k\nEOM\n\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        FSD_HOST=\"host-${COUNTER}\"\n        echo \"fsd=fsd!${FSD_HOST},anchor=${MOUNT_POINT}/sequential/!${FSD_HOST}\" >> $FILENAME\n        COUNTER=$(($COUNTER + 1))\n    done\n\n    /bin/cat <<EOM >>$FILENAME\n\nfwd=format,threads=48,xfersize=512k,openflags=fsync\nfwd=default,xfersize=16k,fileio=random,fileselect=(sequential),threads=24\nfwd=fwdrandW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=o_direct,threads=48\nfwd=fwdseqW!host,host=!host,fsd=(fsd!host*),operation=write,openflags=fsync,fileio=sequential,xfersize=512k\nfwd=fwdrandR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct\nfwd=fwdseqR!host,host=!host,fsd=(fsd!host*),operation=read,openflags=o_direct,fileio=sequential,xfersize=512k\n\nrd=default,elapsed=1800,fwdrate=max,interval=1,maxdata=202500m\nrd=seqwritefsync1,fwd=(fwdseqWhost*),format=restart\nrd=seqwritedirect1,fwd=(fwdseqWhost*),format=no\nrd=randwrite2,fwd=(fwdrandWhost*),format=no,elapsed=900\nrd=writeread1,fwd=(fwdrandRhost*,fwdrandWhost*),format=no\nrd=randread1,fwd=(fwdrandRhost*),format=no\nrd=seqreadcc1,fwd=(fwdseqRhost*),format=no\nrd=seqreaddirect1,fwd=(fwdseqRhost*),format=no,openflags=o_direct\nrd=deleteall1,fwd=(fwdRhost*),operations=(delete)\nEOM\n    chown $LINUX_USER:$LINUX_USER $FILENAME\n}\n\nfunction write_vdbench_files() {\n    write_run_vdbench\n    write_inmem\n    write_3node_inmem32\n    write_6node_inmem32\n    write_3node_32client_inmem\n    write_ondisk\n    write_3node_32_ondisk\n    write_6node_32_ondisk\n    write_3node_32client_ondisk\n    write_throughput\n    write_smallfileIO\n    write_perf.conf\n    # choose how to write the files based on node type\n    if hostname -s | grep -E \"000[0-9A-Fa-f]{3}$\" > /dev/null ; then\n        write_vmss_copy_idrsa\n        write_vmss_azure_clients\n    else\n        write_copy_idrsa\n        write_azure_clients\n    fi\n}\n\nfunction main() {\n    echo \"ensure Azure network\"\n    ensureAzureNetwork\n\n    echo \"config Linux\"\n    config_linux\n\n    echo \"mount avere\"\n    mount_avere\n\n    echo \"install vdbench\"\n    install_vdbench\n\n    echo \"write vdbench files\"\n    write_vdbench_files\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 869}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\nset -e\n\nTARGETDIR=/nfs/node0/bootstrap\nVDBENCHINSTALL=$TARGETDIR/bootstrap.vdbench.sh\nVDBENCHSRC=\"$TARGETDIR/vdbench*.zip\"\n\nif [ ! -d \"$TARGETDIR\" ]; then\n    echo \"ERROR: directory $TARGETDIR does not exist\"\n    exit 1\nelse\n    echo \"SUCCESS: $TARGETDIR found\"\nfi\n\nif ! ls $VDBENCHINSTALL > /dev/null 2>&1; then\n    echo \"MISSING: $VDBENCHINSTALL.  Please download the install script per instructions.\"\n    exit 2\nelse\n    echo \"SUCCESS: $VDBENCHINSTALL found\"\nfi\n\nif ! ls $VDBENCHSRC > /dev/null 2>&1; then\n    echo \"MISSING: $VDBENCHSRC.  Please download the vdbench zip file from Oracle.\"\n    exit 3\nelse\n    echo \"SUCCESS: $VDBENCHSRC found\"\nfi\n\necho success!\nexit 0", "num_lines": 33}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n# NEED following ENV VARS\n# BOOTSTRAP_PATH - the mount path for bootstrap\n#\n# STORAGE_ACCOUNT_RESOURCE_GROUP - the resource group of the storage account\n# STORAGE_ACCOUNT - the storage account hosting the job queue\n\n# QUEUE_PREFIX - the queue prefix\n# BOOTSTRAP_EXPORT_PATH\n# BOOTSTRAP_MOUNT_ADDRESS\n# BOOTSTRAP_SCRIPT\n# VMSS_USERNAME\n# (OPT)VMSS_SUBNET\n# (OPT)VMSS_SSHPUBLICKEY\n# (OPT)VMSS_PASSWORD\n# (OPT)VMSS_WORKER_COUNT\n\nSERVICE_USER=root\nRSYSLOG_FILE=\"35-cachewarmer-manager.conf\"\nCACHEWARMER_MANAGER_SERVICE=cachewarmer-manager\nCACHEWARMER_MANAGER_SERVICE_FILE=\"${CACHEWARMER_MANAGER_SERVICE}.service\"\n\nfunction copy_binaries() {\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n    CACHEWARMER_BIN=$BOOTSTRAP_BASE_PATH/cachewarmerbin\n    cp $CACHEWARMER_BIN/* /usr/local/bin/.\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_BASE_PATH/systemd/${CACHEWARMER_MANAGER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${CACHEWARMER_MANAGER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n    sed -i \"s/USERREPLACE/$SERVICE_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$SERVICE_USER/g\" $DST_FILE\n    sed -i \"s:STORAGE_RG_REPLACE:$STORAGE_ACCOUNT_RESOURCE_GROUP:g\" $DST_FILE\n    sed -i \"s:STORAGE_ACCOUNT_REPLACE:$STORAGE_ACCOUNT:g\" $DST_FILE\n    sed -i \"s/QUEUE_PREFIX_REPLACE/$QUEUE_PREFIX/g\" $DST_FILE\n    sed -i \"s:BOOTSTRAP_EXPORT_PATH_REPLACE:$BOOTSTRAP_EXPORT_PATH:g\" $DST_FILE\n    sed -i \"s:BOOTSTRAP_MOUNT_ADDRESS_REPLACE:$BOOTSTRAP_MOUNT_ADDRESS:g\" $DST_FILE\n    sed -i \"s:BOOTSTRAP_SCRIPT_PATH_REPLACE:$BOOTSTRAP_SCRIPT:g\" $DST_FILE\n    sed -i \"s:VMSS_USERNAME_REPLACE:$VMSS_USERNAME:g\" $DST_FILE\n    \n    if [[ -z \"${VMSS_SSHPUBLICKEY}\" ]]; then\n        sed -i \"s:VMSS_SSH_PUBLIC_KEY_REPLACE::g\" $DST_FILE\n    else\n        sed -i \"s:VMSS_SSH_PUBLIC_KEY_REPLACE:-vmssSshPublicKey '$VMSS_SSHPUBLICKEY':g\" $DST_FILE\n    fi\n    # disable output so secrets are not printed\n    set +x\n    if [[ -z \"${VMSS_PASSWORD}\" ]]; then\n        sed -i \"s:VMSS_PASSWORD_REPLACE::g\" $DST_FILE\n    else\n        sed -i \"s:VMSS_PASSWORD_REPLACE:-vmssPassword '$VMSS_PASSWORD':g\" $DST_FILE\n    fi\n    set -x\n    if [[ -z \"${VMSS_SUBNET}\" ]]; then\n        sed -i \"s/VMSS_SUBNET_NAME_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s/VMSS_SUBNET_NAME_REPLACE/-vmssSubnetName $VMSS_SUBNET/g\" $DST_FILE\n    fi\n    \n    if [[ -z \"${VMSS_WORKER_COUNT}\" ]]; then\n        sed -i \"s/VMSS_WORKER_COUNT_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s/VMSS_WORKER_COUNT_REPLACE/-workerCount $VMSS_WORKER_COUNT/g\" $DST_FILE\n    fi\n\n    # set the proxy information\n    if [[ -z \"${http_proxy}\" ]]; then\n        sed -i \"s/HTTP_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s#HTTP_PROXY_REPLACE#Environment=\\\"http_proxy=$http_proxy\\\"#g\" $DST_FILE\n    fi\n\n    if [[ -z \"${https_proxy}\" ]]; then\n        sed -i \"s/HTTPS_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s#HTTPS_PROXY_REPLACE#Environment=\\\"https_proxy=$https_proxy\\\"#g\" $DST_FILE\n    fi\n\n    if [[ -z \"${no_proxy}\" ]]; then\n        sed -i \"s/NO_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s/NO_PROXY_REPLACE/Environment=\\\"no_proxy=$no_proxy\\\"/g\" $DST_FILE\n    fi\n\n    if [ -f '/etc/centos-release' ]; then \n        sed -i \"s/chown syslog:adm/chown root:root/g\" $DST_FILE\n    fi\n    \n    # copy the rsyslog file\n    cp $BOOTSTRAP_BASE_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    \n    # ensure the logs are rotating\n    if grep -F --quiet \"/var/log/cachewarmer-manager.log\" /etc/logrotate.d/rsyslog; then\n        echo \"not updating /etc/logrotate.d/rsyslog, already there\"\n    else\n        /bin/cat <<EOM >>/etc/logrotate.d/rsyslog\n/var/log/cachewarmer-manager.log\n{\n        rotate 2\n        daily\n        missingok\n        notifempty\n        compress\n        postrotate\n                /usr/lib/rsyslog/rsyslog-rotate\n        endscript\n}\nEOM\n    fi\n    \n    # restart syslog\n    systemctl restart rsyslog\n}\n\nfunction stop_service() {\n    systemctl stop ${CACHEWARMER_MANAGER_SERVICE}\n    systemctl disable ${CACHEWARMER_MANAGER_SERVICE_FILE}\n}\n\nfunction configure_service() {\n    systemctl daemon-reload\n    systemctl enable ${CACHEWARMER_MANAGER_SERVICE_FILE}\n    systemctl start ${CACHEWARMER_MANAGER_SERVICE}\n}\n\nfunction main() {\n    echo \"stop service if exists\"\n    stop_service\n\n    echo \"copy binaries\"\n    copy_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 162}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n# NEED following ENV VARS\n# BOOTSTRAP_PATH\n# BOOTSTRAP_SCRIPT\n# STORAGE_ACCOUNT - the storage account hosting the job queue\n# STORAGE_KEY - the key to the storage account\n# QUEUE_PREFIX - the queue prefix\n\nSERVICE_USER=root\nRSYSLOG_FILE=\"36-cachewarmer-worker.conf\"\nCACHEWARMER_WORKER_SERVICE=cachewarmer-worker\nCACHEWARMER_WORKER_SERVICE_FILE=\"${CACHEWARMER_WORKER_SERVICE}.service\"\n\nfunction copy_binaries() {\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n    CACHEWARMER_BIN=$BOOTSTRAP_BASE_PATH/cachewarmerbin\n    cp $CACHEWARMER_BIN/* /usr/local/bin/.\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_BASE_PATH/systemd/${CACHEWARMER_WORKER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${CACHEWARMER_WORKER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n    sed -i \"s/USERREPLACE/$SERVICE_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$SERVICE_USER/g\" $DST_FILE\n    sed -i \"s:STORAGE_RG_REPLACE:$STORAGE_ACCOUNT_RESOURCE_GROUP:g\" $DST_FILE\n    sed -i \"s/STORAGEACCOUNTREPLACE/$STORAGE_ACCOUNT/g\" $DST_FILE\n    sed -i \"s:STORAGEKEYREPLACE:$STORAGE_KEY:g\" $DST_FILE\n    sed -i \"s:QUEUEPREFIXREPLACE:$QUEUE_PREFIX:g\" $DST_FILE\n\n    if [ -f '/etc/centos-release' ]; then \n        sed -i \"s/chown syslog:adm/chown root:root/g\" $DST_FILE\n    fi\n\n    # set the proxy information\n    if [[ -z \"${http_proxy}\" ]]; then\n        sed -i \"s/HTTP_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s#HTTP_PROXY_REPLACE#Environment=\\\"http_proxy=$http_proxy\\\"#g\" $DST_FILE\n    fi\n\n    if [[ -z \"${https_proxy}\" ]]; then\n        sed -i \"s/HTTPS_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s#HTTPS_PROXY_REPLACE#Environment=\\\"https_proxy=$https_proxy\\\"#g\" $DST_FILE\n    fi\n\n    if [[ -z \"${no_proxy}\" ]]; then\n        sed -i \"s/NO_PROXY_REPLACE//g\" $DST_FILE\n    else\n        sed -i \"s/NO_PROXY_REPLACE/Environment=\\\"no_proxy=$no_proxy\\\"/g\" $DST_FILE\n    fi\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_BASE_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n\n    # ensure the logs are rotating\n    if grep -F --quiet \"/var/log/cachewarmer-worker.log\" /etc/logrotate.d/rsyslog; then\n        echo \"not updating /etc/logrotate.d/rsyslog, already there\"\n    else\n        /bin/cat <<EOM >>/etc/logrotate.d/rsyslog\n/var/log/cachewarmer-worker.log\n{\n        rotate 2\n        daily\n        missingok\n        notifempty\n        compress\n        postrotate\n                /usr/lib/rsyslog/rsyslog-rotate\n        endscript\n}\nEOM\n    fi\n\n    systemctl restart rsyslog\n}\n\nfunction stop_service() {\n    systemctl stop ${CACHEWARMER_WORKER_SERVICE_FILE}\n    systemctl disable ${CACHEWARMER_WORKER_SERVICE_FILE}\n}\n\nfunction configure_service() {\n    systemctl daemon-reload\n    systemctl enable ${CACHEWARMER_WORKER_SERVICE_FILE}\n    systemctl start ${CACHEWARMER_WORKER_SERVICE}\n}\n\nfunction main() {\n    echo \"stop service if exists\"\n    stop_service\n\n    echo \"copy binaries\"\n    copy_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 124}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\npushd jobsubmitter\ngo build\npopd\n\npushd onpremjobuploader\ngo build\npopd\n\npushd orchestrator\ngo build\npopd\n\npushd statscollector\ngo build\npopd\n\n\npushd worker\ngo build\npopd\n", "num_lines": 24}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n###########################################################\n# on rare occasions the extension beats the user setup,\n# wait until complete\n###########################################################\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$LINUX_USER\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\necho \"wait azure home dir\"\nwait_azure_home_dir\n###########################################################\n\nNODE_MOUNT_PREFIX=\"/node\"\nJOB_DIR=\"/job\"\nWORK_DIR=\"/work\"\nSTATS_DIR=\"/stats\"\nRSYSLOG_FILE=\"33-jobsubmitter.conf\"\nJOBSUBMITTER_SERVICE=jobsubmitter\nJOBSUBMITTER_SERVICE_FILE=\"${JOBSUBMITTER_SERVICE}.service\"\n\nif [ -z \"$JOBSUBMITTER_THREAD_COUNT\" ] ; then\n    export JOBSUBMITTER_THREAD_COUNT=4\nfi\necho $JOBSUBMITTER_THREAD_COUNT\n\nfunction remove_quotes() {\n        QUOTED_STR=$1; shift\n        QUOTED_STR=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$QUOTED_STR\")\n        QUOTED_STR=$(sed -e \"s/^'//\" -e \"s/'\\$//\" <<<\"$QUOTED_STR\")\n        echo $QUOTED_STR\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction copy_edasim_binaries() {\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n    EDASIM_BIN=$BOOTSTRAP_PATH/edasim\n    cp $EDASIM_BIN/* /usr/local/bin/.\n}\n\nfunction get_node_csv_string() {\n    WORKING_DIR=$1; shift\n    COUNTER=0\n    RETURN_STR=\"\"\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        if [ \"$COUNTER\" -ne \"0\" ]; then\n            RETURN_STR=\"${RETURN_STR},\"\n        fi\n\t# get the mount point and record it\n        MOUNT_POINT=${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\n        RETURN_STR=\"${RETURN_STR}${MOUNT_POINT}\"\n\n        # ensure the working directory exists\n        TARGET_DIR=${MOUNT_POINT}${WORKING_DIR}\n        mkdir -p ${TARGET_DIR}\n        chown $LINUX_USER:$LINUX_USER ${TARGET_DIR}\n\n        COUNTER=$(($COUNTER + 1))\n    done\n    echo $RETURN_STR\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n\n    # disable output so secrets are not printed\n    set +x\n    # write env file\n    ENVFILE=/etc/default/edasim\n    /bin/cat <<EOM >$ENVFILE\nAZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\nAZURE_STORAGE_ACCOUNT_KEY=\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\"\nAZURE_EVENTHUB_SENDERKEYNAME=$AZURE_EVENTHUB_SENDERKEYNAME\nAZURE_EVENTHUB_SENDERKEY=\"$(remove_quotes $AZURE_EVENTHUB_SENDERKEY)\"\nAZURE_EVENTHUB_NAMESPACENAME=$AZURE_EVENTHUB_NAMESPACENAME\nEOM\n    chmod 600 $ENVFILE\n    set -x\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_PATH/systemd/${JOBSUBMITTER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${JOBSUBMITTER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n\n    WORKDIRCSV=$(get_node_csv_string $WORK_DIR)\n    sed -i \"s/USERREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/UNIQUENAMEREPLACE/$UNIQUE_NAME/g\" $DST_FILE\n    sed -i \"s/THREADCOUNTREPLACE/$JOBSUBMITTER_THREAD_COUNT/g\" $DST_FILE\n    sed -i \"s:WORKDIRSCSVREPLACE:$WORKDIRCSV:g\" $DST_FILE\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    systemctl restart rsyslog\n}\n\nfunction configure_service() {\n    systemctl enable ${JOBSUBMITTER_SERVICE_FILE}\n    sudo systemctl start ${JOBSUBMITTER_SERVICE}\n}\n\nfunction configure_user() {\n    # disable output so secrets are not printed\n    set +x\n    USER_PROFILE_FILE=\"${AZURE_HOME_DIR}/.profile\"\n    echo \"export AZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\" >> $USER_PROFILE_FILE\n    echo \"export AZURE_STORAGE_ACCOUNT_KEY=\\\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\\\"\" >> $USER_PROFILE_FILE\n    echo \"export AZURE_EVENTHUB_SENDERKEYNAME=$AZURE_EVENTHUB_SENDERKEYNAME\" >> $USER_PROFILE_FILE\n    echo \"export AZURE_EVENTHUB_SENDERKEY=\\\"$(remove_quotes $AZURE_EVENTHUB_SENDERKEY)\\\"\" >> $USER_PROFILE_FILE\n    echo \"export AZURE_EVENTHUB_NAMESPACENAME=$AZURE_EVENTHUB_NAMESPACENAME\" >> $USER_PROFILE_FILE\n    echo \"export UNIQUE_NAME=$UNIQUE_NAME\" >> $USER_PROFILE_FILE\n    set -x\n\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n\n    # write the jobrun script file\n    JOBRUN_SCRIPT=\"${AZURE_HOME_DIR}/jobrun.sh\"\n    /bin/cat <<EOM >$JOBRUN_SCRIPT\n#!/bin/bash\nif [ \"\\$#\" -ne 1 ]; then\n    echo \"ERROR missing a job run name, use a different job run for each run\"\n    echo \"\"\n    echo \"usage: \\$0 JOB_RUN_NAME\"\n    exit 1\nfi\njobrun -uniqueName=\\$UNIQUE_NAME \\\\\n    -jobRunName=\\$1 \\\\\n    -batchCount=4 \\\\\n    -deleteFiles=true \\\\\n    -jobCount=500 \\\\\n    -mountParity=true \\\\\n    -jobFileConfigSizeKB=384 \\\\\n    -workStartFileConfigSizeKB=384 \\\\\n    -workStartFileCount=3 \\\\\n    -workCompleteFileSizeKB=384 \\\\\n    -workCompleteFailedFileSizeKB=1024 \\\\\n    -workFailedProbability=0.01 \\\\\n    -workCompleteFileCount=12\nEOM\n    chown $LINUX_USER:$LINUX_USER $JOBRUN_SCRIPT\n    chmod 755 $JOBRUN_SCRIPT\n\n    # write the stats_collector script file\n    STATS_COLLECTOR_SCRIPT=\"${AZURE_HOME_DIR}/stats_collector.sh\"\n    TARGET_DIR=${BASE_DIR}${NODE_MOUNT_PREFIX}0${STATS_DIR}\n    mkdir -p ${TARGET_DIR}\n    chown $LINUX_USER:$LINUX_USER ${TARGET_DIR}\n    /bin/cat <<EOM >$STATS_COLLECTOR_SCRIPT\nstatscollector -uniqueName=\\$UNIQUE_NAME -statsFilePath=${TARGET_DIR}\nEOM\n    chown $LINUX_USER:$LINUX_USER $STATS_COLLECTOR_SCRIPT\n    chmod 755 $STATS_COLLECTOR_SCRIPT\n}\n\nfunction main() {\n    echo \"mount avere\"\n    mount_avere\n\n    echo \"copy edasim binaries\"\n    copy_edasim_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"configure user to run the stats collector\"\n    configure_user\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 216}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n###########################################################\n# on rare occasions the extension beats the user setup,\n# wait until complete\n###########################################################\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$LINUX_USER\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\necho \"wait azure home dir\"\nwait_azure_home_dir\n###########################################################\n\nNODE_MOUNT_PREFIX=\"/node\"\nJOB_DIR=\"/job\"\nWORK_DIR=\"/work\"\nRSYSLOG_FILE=\"32-onpremjobuploader.conf\"\nONPREMJOBUPLOADER_SERVICE=onpremjobuploader\nONPREMJOBUPLOADER_SERVICE_FILE=\"${ONPREMJOBUPLOADER_SERVICE}.service\"\n\nfunction remove_quotes() {\n        QUOTED_STR=$1; shift\n        QUOTED_STR=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$QUOTED_STR\")\n        QUOTED_STR=$(sed -e \"s/^'//\" -e \"s/'\\$//\" <<<\"$QUOTED_STR\")\n        echo $QUOTED_STR\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction copy_edasim_binaries() {\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n    EDASIM_BIN=$BOOTSTRAP_PATH/edasim\n    cp $EDASIM_BIN/* /usr/local/bin/.\n}\n\nfunction get_mount_csv_string() {\n    WORKING_DIR=$1; shift\n    COUNTER=0\n    RETURN_STR=\"\"\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        if [ \"$COUNTER\" -ne \"0\" ]; then\n            RETURN_STR=\"${RETURN_STR},\"\n        fi\n        # get the mount point and record it\n        MOUNT_POINT=${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\n        RETURN_STR=\"${RETURN_STR}${MOUNT_POINT}\"\n\n        COUNTER=$(($COUNTER + 1))\n    done\n    echo $RETURN_STR\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n\n    # write env file\n    ENVFILE=/etc/default/edasim\n    /bin/cat <<EOM >$ENVFILE\nAZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\nAZURE_STORAGE_ACCOUNT_KEY=\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\"\nAZURE_EVENTHUB_SENDERKEYNAME=$AZURE_EVENTHUB_SENDERKEYNAME\nAZURE_EVENTHUB_SENDERKEY=\"$(remove_quotes $AZURE_EVENTHUB_SENDERKEY)\"\nAZURE_EVENTHUB_NAMESPACENAME=$AZURE_EVENTHUB_NAMESPACENAME\nEOM\n    chmod 600 $ENVFILE\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_PATH/systemd/${ONPREMJOBUPLOADER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${ONPREMJOBUPLOADER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n\n    sed -i \"s/USERREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/UNIQUENAMEREPLACE/$UNIQUE_NAME/g\" $DST_FILE\n    WORKDIRCSV=$(get_mount_csv_string)\n    sed -i \"s:WORKDIRSCSVREPLACE:$WORKDIRCSV:g\" $DST_FILE\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    systemctl restart rsyslog\n}\n\nfunction configure_service() {\n    systemctl enable ${ONPREMJOBUPLOADER_SERVICE_FILE}\n    sudo systemctl start ${ONPREMJOBUPLOADER_SERVICE}\n}\n\nfunction main() {\n    echo \"mount avere\"\n    mount_avere\n\n    echo \"copy edasim binaries\"\n    copy_edasim_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 145}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n###########################################################\n# on rare occasions the extension beats the user setup,\n# wait until complete\n###########################################################\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$LINUX_USER\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\necho \"wait azure home dir\"\nwait_azure_home_dir\n###########################################################\n\nNODE_MOUNT_PREFIX=\"/node\"\nJOB_DIR=\"/job\"\nWORK_DIR=\"/work\"\nRSYSLOG_FILE=\"30-orchestrator.conf\"\nORCHESTRATOR_SERVICE=orchestrator\nORCHESTRATOR_SERVICE_FILE=\"${ORCHESTRATOR_SERVICE}.service\"\n\nif [ -z \"$ORCHESTRATOR_THREAD_COUNT\" ] ; then\n    export ORCHESTRATOR_THREAD_COUNT=4\nfi\necho $ORCHESTRATOR_THREAD_COUNT\n\nfunction remove_quotes() {\n        QUOTED_STR=$1; shift\n        QUOTED_STR=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$QUOTED_STR\")\n        QUOTED_STR=$(sed -e \"s/^'//\" -e \"s/'\\$//\" <<<\"$QUOTED_STR\")\n        echo $QUOTED_STR\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction copy_edasim_binaries() {\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n    EDASIM_BIN=$BOOTSTRAP_PATH/edasim\n    cp $EDASIM_BIN/* /usr/local/bin/.\n}\n\nfunction get_node_csv_string() {\n    WORKING_DIR=$1; shift\n    COUNTER=0\n    RETURN_STR=\"\"\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        if [ \"$COUNTER\" -ne \"0\" ]; then\n            RETURN_STR=\"${RETURN_STR},\"\n        fi\n        # get the mount point and record it\n        MOUNT_POINT=${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\n        RETURN_STR=\"${RETURN_STR}${MOUNT_POINT}\"\n\n        # ensure the working directory exists\n        TARGET_DIR=${MOUNT_POINT}${WORKING_DIR}\n        mkdir -p ${TARGET_DIR}\n        chown $LINUX_USER:$LINUX_USER ${TARGET_DIR}\n\n        COUNTER=$(($COUNTER + 1))\n    done\n    echo $RETURN_STR\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n\n    # disable output so secrets are not printed\n    set +x\n    # write env file\n    ENVFILE=/etc/default/edasim\n    /bin/cat <<EOM >$ENVFILE\nAZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\nAZURE_STORAGE_ACCOUNT_KEY=\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\"\nAZURE_EVENTHUB_SENDERKEYNAME=$AZURE_EVENTHUB_SENDERKEYNAME\nAZURE_EVENTHUB_SENDERKEY=\"$(remove_quotes $AZURE_EVENTHUB_SENDERKEY)\"\nAZURE_EVENTHUB_NAMESPACENAME=$AZURE_EVENTHUB_NAMESPACENAME\nEOM\n    chmod 600 $ENVFILE\n    set -x\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_PATH/systemd/${ORCHESTRATOR_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${ORCHESTRATOR_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n\n    WORKDIRCSV=$(get_node_csv_string $WORK_DIR)\n    sed -i \"s/USERREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/UNIQUENAMEREPLACE/$UNIQUE_NAME/g\" $DST_FILE\n    sed -i \"s/THREADCOUNTREPLACE/$ORCHESTRATOR_THREAD_COUNT/g\" $DST_FILE\n    sed -i \"s:WORKDIRSCSVREPLACE:$WORKDIRCSV:g\" $DST_FILE\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    systemctl restart rsyslog\n}\n\nfunction configure_service() {\n    systemctl enable ${ORCHESTRATOR_SERVICE_FILE}\n    sudo systemctl start ${ORCHESTRATOR_SERVICE}\n}\n\nfunction main() {\n    echo \"mount avere\"\n    mount_avere\n\n    echo \"copy edasim binaries\"\n    copy_edasim_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 159}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n###########################################################\n# on rare occasions the extension beats the user setup,\n# wait until complete\n###########################################################\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$LINUX_USER\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\necho \"wait azure home dir\"\nwait_azure_home_dir\n###########################################################\n\nNODE_MOUNT_PREFIX=\"/node\"\nJOB_DIR=\"/job\"\nWORK_DIR=\"/work\"\nRSYSLOG_FILE=\"31-worker.conf\"\nWORKER_SERVICE=worker\nWORKER_SERVICE_FILE=\"${WORKER_SERVICE}.service\"\n\nfunction remove_quotes() {\n        QUOTED_STR=$1; shift\n        QUOTED_STR=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$QUOTED_STR\")\n        QUOTED_STR=$(sed -e \"s/^'//\" -e \"s/'\\$//\" <<<\"$QUOTED_STR\")\n        echo $QUOTED_STR\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction copy_edasim_binaries() {\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n    EDASIM_BIN=$BOOTSTRAP_PATH/edasim\n    cp $EDASIM_BIN/* /usr/local/bin/.\n}\n\nfunction get_mount_csv_string() {\n    WORKING_DIR=$1; shift\n    COUNTER=0\n    RETURN_STR=\"\"\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        if [ \"$COUNTER\" -ne \"0\" ]; then\n            RETURN_STR=\"${RETURN_STR},\"\n        fi\n        # get the mount point and record it\n        MOUNT_POINT=${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\n        RETURN_STR=\"${RETURN_STR}${MOUNT_POINT}\"\n\n        COUNTER=$(($COUNTER + 1))\n    done\n    echo $RETURN_STR\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_PATH=\"$(dirname ${BASE_DIR}${NODE_MOUNT_PREFIX}0${BOOTSTRAP_SCRIPT_PATH})\"\n\n    # write env file\n    ENVFILE=/etc/default/edasim\n    /bin/cat <<EOM >$ENVFILE\nAZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\nAZURE_STORAGE_ACCOUNT_KEY=\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\"\nAZURE_EVENTHUB_SENDERKEYNAME=$AZURE_EVENTHUB_SENDERKEYNAME\nAZURE_EVENTHUB_SENDERKEY=\"$(remove_quotes $AZURE_EVENTHUB_SENDERKEY)\"\nAZURE_EVENTHUB_NAMESPACENAME=$AZURE_EVENTHUB_NAMESPACENAME\nEOM\n    chmod 600 $ENVFILE\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_PATH/systemd/${WORKER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${WORKER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n\n    sed -i \"s/USERREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/UNIQUENAMEREPLACE/$UNIQUE_NAME/g\" $DST_FILE\n    WORKDIRCSV=$(get_mount_csv_string)\n    sed -i \"s:WORKDIRSCSVREPLACE:$WORKDIRCSV:g\" $DST_FILE\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    systemctl restart rsyslog\n}\n\nfunction configure_service() {\n    systemctl enable ${WORKER_SERVICE_FILE}\n    sudo systemctl start ${WORKER_SERVICE}\n}\n\nfunction main() {\n    echo \"mount avere\"\n    mount_avere\n\n    echo \"copy edasim binaries\"\n    copy_edasim_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 145}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\nset -x\n\n###########################################################\n# on rare occasions the extension beats the user setup,\n# wait until complete\n###########################################################\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$LINUX_USER\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\necho \"wait azure home dir\"\nwait_azure_home_dir\n###########################################################\n\nNODE_MOUNT_PREFIX=\"/node\"\nJOB_DIR=\"/job\"\nWORK_DIR=\"/work\"\nRSYSLOG_FILE=\"34-vmscaler.conf\"\nVMSCALER_SERVICE=vmscaler\nVMSCALER_SERVICE_FILE=\"${VMSCALER_SERVICE}.service\"\n\nfunction remove_quotes() {\n        QUOTED_STR=$1; shift\n        QUOTED_STR=$(sed -e 's/^\"//' -e 's/\"$//' <<<\"$QUOTED_STR\")\n        QUOTED_STR=$(sed -e \"s/^'//\" -e \"s/'\\$//\" <<<\"$QUOTED_STR\")\n        echo $QUOTED_STR\n}\n\nfunction copy_binaries() {\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n    VMSCALER_BIN=$BOOTSTRAP_BASE_PATH/vmscalerbin\n    cp $VMSCALER_BIN/* /usr/local/bin/.\n}\n\nfunction write_system_files() {\n    # configuration inspired by https://fabianlee.org/2017/05/21/golang-running-a-go-binary-as-a-systemd-service-on-ubuntu-16-04/\n    BOOTSTRAP_BASE_PATH=\"$(dirname ${BOOTSTRAP_PATH}${BOOTSTRAP_SCRIPT})\"\n\n    # write env file\n    ENVFILE=/etc/default/vmscaler\n    /bin/cat <<EOM >$ENVFILE\nAZURE_STORAGE_ACCOUNT=$AZURE_STORAGE_ACCOUNT\nAZURE_STORAGE_ACCOUNT_KEY=\"$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY)\"\nAZURE_SUBSCRIPTION_ID=$AZURE_SUBSCRIPTION_ID\nEOM\n    chmod 600 $ENVFILE\n\n    # copy the systemd file and search replace users/groups/workdircsv\n    SRC_FILE=$BOOTSTRAP_BASE_PATH/systemd/${VMSCALER_SERVICE_FILE}\n    DST_FILE=/lib/systemd/system/${VMSCALER_SERVICE_FILE}\n\n    cp $SRC_FILE $DST_FILE\n\n    sed -i \"s:IMAGEIDREPLACE:$IMAGE_ID:g\" $DST_FILE\n    sed -i \"s/LOCATIONREPLACE/$LOCATION/g\" $DST_FILE\n    sed -i \"s/VMSECRETREPLACE/$VM_PASSWORD/g\" $DST_FILE\n    sed -i \"s/RESOURCEGROUPREPLACE/$RESOURCE_GROUP/g\" $DST_FILE\n    sed -i \"s/VNETRGREPLACE/$VNET_RG/g\" $DST_FILE\n    sed -i \"s/VNETNAMEREPLACE/$VNET_NAME/g\" $DST_FILE\n    sed -i \"s/SUBNETREPLACE/$SUBNET_NAME/g\" $DST_FILE\n    sed -i \"s/SKUREPLACE/$SKU/g\" $DST_FILE\n    sed -i \"s/VMSPERVMSSREPLACE/$VMS_PER_VMSS/g\" $DST_FILE\n    sed -i \"s/PRIORITYREPLACE/$PRIORITY/g\" $DST_FILE\n    sed -i \"s/USERREPLACE/$LINUX_USER/g\" $DST_FILE\n    sed -i \"s/GROUPREPLACE/$LINUX_USER/g\" $DST_FILE\n\n    # copy the rsyslog file\n    cp $BOOTSTRAP_BASE_PATH/rsyslog/$RSYSLOG_FILE /etc/rsyslog.d/.\n\n    # copy the delete vmss instance file\n    SRC_FILE=$BOOTSTRAP_BASE_PATH/delete_vmss_instance.sh\n    DST_FILE=/home/$LINUX_USER/delete_vmss_instance.sh\n    cp  $SRC_FILE $DST_FILE\n    sed -i \"s/STORAGEACCOUNTREPLACE/$AZURE_STORAGE_ACCOUNT/g\" $DST_FILE\n    sed -i \"s:STORAGEKEYREPLACE:$(remove_quotes $AZURE_STORAGE_ACCOUNT_KEY):g\" $DST_FILE\n    chmod +x $DST_FILE\n\n    # copy the set capacity files\n    SRC_FILE=$BOOTSTRAP_BASE_PATH/set_capacity.imds.sh\n    DST_FILE=/home/$LINUX_USER/set_capacity.imds.sh\n    cp  $SRC_FILE $DST_FILE\n    chmod +x $DST_FILE\n    \n    SRC_FILE=$BOOTSTRAP_BASE_PATH/set_capacity.service_principal.sh\n    DST_FILE=/home/$LINUX_USER/set_capacity.service_principal.sh\n    cp  $SRC_FILE $DST_FILE\n    chmod +x $DST_FILE\n}\n\nfunction configure_rsyslog() {\n    # enable listen on port 514/TCP\n    sed -i 's/^#module(load=\"imtcp\")/module(load=\"imtcp\")/g' /etc/rsyslog.conf\n    sed -i 's/^#input(type=\"imtcp\" port=\"514\")/input(type=\"imtcp\" port=\"514\")/g' /etc/rsyslog.conf\n    systemctl restart rsyslog\n}\n\nfunction configure_service() {\n    systemctl enable ${VMSCALER_SERVICE_FILE}\n    sudo systemctl start ${VMSCALER_SERVICE}\n}\n\nfunction main() {\n    echo \"copy binaries\"\n    copy_binaries\n\n    echo \"write system files\"\n    write_system_files\n\n    echo \"configure rsyslog\"\n    configure_rsyslog\n\n    echo \"start the service\"\n    configure_service\n\n    echo \"installation complete\"\n}\n\nmain", "num_lines": 130}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# uses the IMDS to get the VMSS name and ID to post a message queue\n#\n# the curl technique guidance from:\n#   https://social.msdn.microsoft.com/Forums/lync/en-US/8ea29f47-6256-4873-8370-9fe92089a349/how-to-access-rest-azure-blob-using-curl?forum=windowsazuredata\n#   https://gist.github.com/rtyler/30e51dc72bed23718388c43f9c11da76\n#   https://stackoverflow.com/questions/42361336/how-to-make-a-rest-call-to-an-azure-queue\n#   https://docs.microsoft.com/en-us/rest/api/storageservices/put-message\n\nset -x\n\n# provided by system\nSTORAGE_ACCOUNT=\"STORAGEACCOUNTREPLACE\"\nAZURE_STORAGE_ACCOUNT_KEY=\"STORAGEKEYREPLACE\"\n\n# provided by IMDS\nAZURE_SUBSCRIPTION_ID=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/subscriptionId?api-version=2018-10-01&format=text\")\nRESOURCE_GROUP=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/resourceGroupName?api-version=2018-10-01&format=text\")\nCONTAINER_NAME=\"vmscaler-${AZURE_SUBSCRIPTION_ID}-${RESOURCE_GROUP}\"\nVMSS_NAME=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/vmScaleSetName?api-version=2018-10-01&format=text\")\nVMSS_INSTANCE_ID=$(curl -s -H Metadata:true -s \"http://169.254.169.254/metadata/instance/compute/name?api-version=2018-10-01&format=text\" | awk -F'_' '{print $2}')\n\nif [ \"${#VMSS_NAME}\" -eq 0 ];\nthen\n    echo \"ERROR: this is not a VMSS Instance\"\n    exit 1\nfi\n\n# storage variables\nQUEUE_STORE_URL=\"queue.core.windows.net\"\nAUTHORIZATION=\"SharedKey\"\n\nREQUEST_METHOD=\"POST\"\nREQUEST_DATE=$(TZ=GMT LC_ALL=en_US.utf8 date \"+%a, %d %h %Y %H:%M:%S %Z\")\nSTORAGE_SERVICE_VERSION=\"2018-03-28\"\n\n# HTTP Request headers\nX_MS_DATE_H=\"x-ms-date:$REQUEST_DATE\"\nX_MS_VERSION_H=\"x-ms-version:$STORAGE_SERVICE_VERSION\"\n\n# Build the SIGNATURE string\nCANONICALIZED_HEADERS=\"${X_MS_DATE_H}\\n${X_MS_VERSION_H}\"\nRESOURCE_ID=\"/${CONTAINER_NAME}/messages\"\nCANONICALIZED_RESOURCE=\"/${STORAGE_ACCOUNT}${RESOURCE_ID}\"\n\nQUEUE_MESSAGE=\"<QueueMessage><MessageText>${VMSS_NAME},${VMSS_INSTANCE_ID}</MessageText></QueueMessage>\"\nMESSAGE_LENGTH=$(echo -n \"${QUEUE_MESSAGE}\" | wc --bytes)\nCONTENT_TYPE=\"application/x-www-form-urlencoded\"\n\nSTRING_TO_SIGN=\"${REQUEST_METHOD}\\n\\n\\n${MESSAGE_LENGTH}\\n\\n${CONTENT_TYPE}\\n\\n\\n\\n\\n\\n\\n${CANONICALIZED_HEADERS}\\n${CANONICALIZED_RESOURCE}\"\n\n# Decode the Base64 encoded access key, convert to Hex.\nDECODED_HEX_KEY=\"$(echo -n $AZURE_STORAGE_ACCOUNT_KEY | base64 -d -w0 | xxd -p -c256)\"\n\n# Create the HMAC SIGNATURE for the Authorization header\nSIGNATURE=$(printf \"$STRING_TO_SIGN\" | openssl dgst -sha256 -mac HMAC -macopt \"hexkey:$DECODED_HEX_KEY\" -binary |  base64 -w0)\nAUTHORIZATION_HEADER=\"Authorization: $AUTHORIZATION $STORAGE_ACCOUNT:$SIGNATURE\"\n\ncurl --verbose --retry 18 --retry-delay 10 \\\n    -X $REQUEST_METHOD \\\n    -H \"$X_MS_DATE_H\" \\\n    -H \"$X_MS_VERSION_H\" \\\n    -H \"$AUTHORIZATION_HEADER\" \\\n    -d $QUEUE_MESSAGE \\\n    https://${STORAGE_ACCOUNT}.${QUEUE_STORE_URL}${RESOURCE_ID}\n\necho \"curl result: $?\"", "num_lines": 68}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndisplay_usage() {\n    echo -e \"\\nUsage: $0 NEW_NODE_COUNT\\n\"\n    echo -e \"sets capacity using values from IMDS.  Access to management.azure.com must exist and IMDS must have write access to the resource group.\"\n}\n\nif [ $# -lt 1 ] ; then\n    display_usage\n    exit 1\nfi\n\nNEW_NODE_COUNT=$1\n\nif [ \"$NEW_NODE_COUNT\" -eq \"$NEW_NODE_COUNT\" ] ;\nthen\n   echo \"$NEW_NODE_COUNT is a valid integer\"\nelse\n   echo \"ERROR: NEW_NODE_COUNT must be a valid integer.\"\n   exit 1\nfi\n\nset -x\nset -e\n\n# https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http\n\n# get the bearer token\nBEARER_TOKEN=$(curl -s -H \"Metadata: true\" 'http://169.254.169.254/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/' | grep -Po 'access_token\":\"\\K[^\"]*')\n\n# get sub id and resource groups\nAZURE_SUBSCRIPTION_ID=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/subscriptionId?api-version=2018-10-01&format=text\")\nRESOURCE_GROUP=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/resourceGroupName?api-version=2018-10-01&format=text\")\n\n# get the existing resource group metadata\nRESOURCE_GROUP_PAYLOAD=$(curl -s -H \"Authorization: Bearer ${BEARER_TOKEN}\" -H \"Content-Type: application/json\" \"https://management.azure.com/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourcegroups/${RESOURCE_GROUP}?api-version=2018-05-01\")\n\nNEW_PAYLOAD=$(echo $RESOURCE_GROUP_PAYLOAD | sed -r \"s/\\\"TOTAL_NODES\\\":\\\"[0-9]*\\\"/\\\"TOTAL_NODES\\\":\\\"${NEW_NODE_COUNT}\\\"/g\" | sed -r \"s/\\\"properties\\\":\\{[^\\}]*\\}/\\\"properties\\\":\\{\\}/g\")\n\ncurl --verbose --retry 18 --retry-delay 10 \\\n    -X PATCH \\\n    -H \"Authorization: Bearer ${BEARER_TOKEN}\" \\\n    -H \"Content-Type: application/json\" \\\n    -d $NEW_PAYLOAD \\\n    \"https://management.azure.com/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourcegroups/${RESOURCE_GROUP}?api-version=2018-05-01\"\n    \nset -x", "num_lines": 47}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndisplay_usage() {\n    echo -e \"\\nUsage: $0 NEW_NODE_COUNT\\n\"\n    echo -e \"sets capacity on the resource group using environment variables.\"\n    echo -e \"Access to management.azure.com and login.microsoftonline.com must\"\n    echo -e \"exist, and the following environment variables must be set:\\n\"\n    echo -e \"AZURE_SUBSCRIPTION_ID - the customer subscription id\"\n    echo -e \"AZURE_TENANT_ID - the tenant ID associated with the subscription\"\n    echo -e \"AZURE_CLIENT_ID - the service principal client id\"\n    echo -e \"AZURE_CLIENT_SECRET - the service principal secret\"\n    echo -e \"RESOURCE_GROUP - the resource group that needs the node count tag updated\\n\"\n}\n\n\n\nif [ $# -lt 1 ] ; then\n    display_usage\n    exit 1\nfi\n\nif [ ! \"$AZURE_SUBSCRIPTION_ID\" ] ; then\n    echo \"ERROR: missing env var AZURE_SUBSCRIPTION_ID\"\n    display_usage\n    exit 1\nfi\n\nif [ -z \"$AZURE_TENANT_ID\" ] ; then\n    echo \"ERROR: missing env var AZURE_TENANT_ID\"\n    display_usage\n    exit 1\nfi\n\nif [ -z \"$AZURE_CLIENT_ID\" ] ; then\n    echo \"ERROR: missing env var AZURE_CLIENT_ID\"\n    display_usage\n    exit 1\nfi\n\nif [ -z \"$AZURE_CLIENT_SECRET\" ] ; then\n    echo \"ERROR: missing env var AZURE_CLIENT_SECRET\"\n    display_usage\n    exit 1\nfi\n\nif [ -z \"$RESOURCE_GROUP\" ] ; then\n    echo \"ERROR: missing env var RESOURCE_GROUP\"\n    display_usage\n    exit 1\nfi\n\nNEW_NODE_COUNT=$1\n\nif [ \"$NEW_NODE_COUNT\" -eq \"$NEW_NODE_COUNT\" ] ;\nthen\n   echo \"$NEW_NODE_COUNT is a valid integer\"\nelse\n   echo \"ERROR: NEW_NODE_COUNT must be a valid integer.\"\n   exit 1\nfi\n\nset -x\nset -e\n\n# https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http\n\n# get the bearer token\nBEARER_TOKEN=$(curl --verbose -X POST -d \"grant_type=client_credentials&client_id=${AZURE_CLIENT_ID}&client_secret=${AZURE_CLIENT_SECRET}&resource=https%3A%2F%2Fmanagement.azure.com%2F\" https://login.microsoftonline.com/${AZURE_TENANT_ID}/oauth2/token | grep -Po 'access_token\":\"\\K[^\"]*')\n\n# get the existing resource group metadata\nRESOURCE_GROUP_PAYLOAD=$(curl -s -H \"Authorization: Bearer ${BEARER_TOKEN}\" -H \"Content-Type: application/json\" \"https://management.azure.com/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourcegroups/${RESOURCE_GROUP}?api-version=2018-05-01\")\n\nNEW_PAYLOAD=$(echo $RESOURCE_GROUP_PAYLOAD | sed -r \"s/\\\"TOTAL_NODES\\\":\\\"[0-9]*\\\"/\\\"TOTAL_NODES\\\":\\\"${NEW_NODE_COUNT}\\\"/g\" | sed -r \"s/\\\"properties\\\":\\{[^\\}]*\\}/\\\"properties\\\":\\{\\}/g\")\n\ncurl --verbose --retry 18 --retry-delay 10 \\\n    -X PATCH \\\n    -H \"Authorization: Bearer ${BEARER_TOKEN}\" \\\n    -H \"Content-Type: application/json\" \\\n    -d $NEW_PAYLOAD \\\n    \"https://management.azure.com/subscriptions/${AZURE_SUBSCRIPTION_ID}/resourcegroups/${RESOURCE_GROUP}?api-version=2018-05-01\"\n    \nset -x", "num_lines": 82}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Cluster Clone Script\n# ------- ----- ------\n# This script is designed to duplicate the existing configuration of a cluster. It is ideal for \"cloning\" a cluster. If you need to\n# setup another cluster SIMILAR to the original cluster, you will need to pay special attention to numerous variables \n# such as cluster/client/vserver/management/IPMI IPs and cluster name etc\n\n# Changelog - 03/16 - changed cloud bucket variable.  It was \"grep bucket\" and is now \"grep \"\\<bucket\\>\"\" - Thanks KOber\n# Changelog - 03/22 - added the command to upload the latest cluster_rebuild directory once this script finishes\n# Changelog - 04/04 - when adding a junction with 'inheritPolicy' set to 'no', a policy needs provided - Thanks KOber\n# Changelog - 05/07 - added Initial cluster object information\n# Changelog - 05/24 - added Share ACL/ACE\n# Changelog - 05/25 - Export rules with a \"network\" scope was not working\n# Changelog - 07/03 - Removed licensing since the cluster ID changes. \n# Changelog - 07/03 - Configured Atmos core filer creation so $SERVERNAME =  $NETWORK (prior to this $BUCKET.$NETWORK was not correct)\n# Changelog - 07/03 - Changed Cloud snapshots so that it only queries cloud core filers which were configured for snapshots, not all cloud core filers. \n# Changelog - 07/25 - Changed the cache policy search to explicitly exclude \"Full Caching\" so that cache policies named like \"Full Caching with 1m WB\" would not be excluded\n# Changelog - 07/26 - Removed the commas for the corefiler.create section\n# Changelog - 10/10 - use dbutil for any custom settings with note of \"not in cluster\" to keep things from being confusing\n# Changelog - 10/31 - add simple vserver creation\n# Changelog - 11/02 - added the ability to change a core filer's network. Thanks Bogacki\n# to do - export rules for netgroups. This does not work due to an averecmd issue.  Engineering ticket 24116 was created to address this.  The script will output the netgroup rule\n# Changelog - 04/25 - added functionality for AvereOS 4.6, 4.7 and 4.8\n# Changelog - 05/02 - improved performance for getting CIFS shares\n# Changelog - 05/14 - added the \"createSubdir\" setting when creating junctions\n# Changelog - 05/30 - enabled mapping old vserver internal name to new vserver internal name (similar to mass custom settings). Thanks Griffith\n# Changelog - 05/30 - modified commands to query syslog servers for code earlier than 4.7. Thanks Griffith\n# Changelog - 06/07 - discovered custom settings for vserver and cpolicyActive/cpolicyAdmin would not be mapped properly on the new cluster. Fixed\n# Changelog - 06/27 - added CIFS \"Server Signing\"\n# Changelog - 08/10 - added 'force':'$FORCE' for NFS core filer creation\n# Changelog - 08/17 - fixed a bug with cifs.addShare \n# Changelog - 11/12 - changed \"echo \"# \"`echo $CLUSTER|grep name|grep -v clusterIPs` >> $OUTPUT\" to \"echo \"# \"`echo $CLUSTER|grep name|grep -v clusterIP` >> $OUTPUT\"\n# Changelog - 11/12 - changed \"echo \"# \"`echo $CLUSTER|grep clusterIPs` >> $OUTPUT \" to \"echo \"# \"`echo $CLUSTER|grep clusterIP0` >> $OUTPUT\"\n# Changelog - 11/13 - changed \"if [ $S3TYPE = \"ECS\" ] || [ $S3TYPE = \"ATMOS\" ]; then\" to \"if [[ $S3TYPE = \"ECS\" ]] || [[ $S3TYPE = \"ATMOS\" ]]; then\"\n# Changelog - 11/13 - cleaned up old comments\n# Changelog - 11/13 - added the ability to add a network that is not the cluster network\n# Changelog - 11/13 - ignored the vserverX.smbacldMassids custom settings since they are added automatically\n# Changelog - 11/19 - added a 3 second pause after each core filer creation\n# Changelog - 11/19 - fixed the cluster.addNetworkAddressRange to eliminate the last '}' typo\n# Changelog - 12/13 - Changed the way we poll the directory services for 'default' and 'login'\n# Changelog - 12/14 - excluded nodeMgmtIP when trying to collect the name of the cluster with cluster.get\n# Changelog - 05/02 - added the trailing '}' for cluster.addClusterIPs\n# Changelog - 2019/08/15 - Modified the vserver add to support vlans.  Also moved the section AFTER the core filer creation because a simple vserver can not be created without an existing core filer.  \n#                          Added a section to indicate what version of config_restore is being executed\n#                          Moved the custom setting section to be after the core filer creation to allow more time for the core filers to be added\n#                          Removed some old comments\n# Changelog - 2019/09/03 - To ignoreWarnings if a core filer already exists, the 'true' option was changed to 'True'\n#                          When an Azure core filer is added, the Network name should match the Server Name (similar to ECS and ATMOS).  Added this conditional\n# Changelog - 2019/09/26 - added corefiler.modify [corefiler_name] {'clientSuspend':'no'} after all core filers get created\n# Changelog - 2020/03/19 - had to modify addJunction function because 'language' was an added option in newer code 6515549\n#                          found a bug with generating the cache policy. it has been corrected\n# Changelog - 2020/05/12 - when doing a cluster.get and DNSdomain is empty, it will return 'undefined'.  if doing a restore with this setting, it may cause\n#                          problems with the DNS settings.  So the logic was added to convert 'undefined' to an empty set for cluster.modify\n#                          Users other than 'admin' will have their passwords set to null. Meaning they do not have a password to log in. This should be\n#                          set by the admin once the cluster is running\n\nclear\nTIMESTAMP=`date +%Y-%m-%d_%T`\nOUTPUT_DIR=\"/support/Backups/cluster_rebuild_$TIMESTAMP\"\nmkdir -p $OUTPUT_DIR\nexport OUTPUT=\"$OUTPUT_DIR/1-config_restore.sh\"\nRELEASE=`averecmd cluster.get|grep activeImage|cut -c 51,53`\n\ntouch $OUTPUT_DIR/1-config_restore.sh\nchmod 700 $OUTPUT_DIR/1-config_restore.sh\n\necho \"#Initial cluster object information\" >> $OUTPUT\nIFS=$' ';CLUSTER=`averecmd --pretty cluster.get`\necho \"# \"`echo $CLUSTER|grep activeImage` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep name|egrep -v 'clusterIP|nodeMgmtIP'` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep mgmtIP` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep default_router` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep clusterIP0` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep DNSserver` >> $OUTPUT \necho \"#  \"`echo $CLUSTER|grep DNSdomain|cut -d { -f 2-` >> $OUTPUT \necho \"# \"`echo $CLUSTER|grep NTPservers` >> $OUTPUT \necho \"#  \"`grep \"Changelog - \" /support/Backups/config_restore.sh|tail -2|head -1|cut -d '-' -f 1,2` >> $OUTPUT\necho \"\" >> $OUTPUT\n \necho \"#VLAN\" |tee -a $OUTPUT\nIFS=$'\\n';for i in `lsu cluster.vlans|grep -v _|cut -d ':' -f 1`;do \\\n  if [ $i ]; then\n    NAME=`lsu $i|grep \"\\<name\\>\"|cut -d ' ' -f 2`\n    ROLES=`lsu $i|grep roles|cut -d ' ' -f 2`\n    MTU=`lsu $i|grep mtu|cut -d ' ' -f 2`\n    ROUTER=`averecmd --pretty cluster.getVLAN $NAME|grep router|cut -d \"'\" -f 4`\n    TAG=`averecmd --pretty cluster.getVLAN $NAME|grep tag|cut -d \"'\" -f 4`\n    echo \"averecmd cluster.addVLAN $NAME $TAG $ROUTER $ROLES $MTU\" >> $OUTPUT\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#Cluster Networks - Address ranges\" |tee -a $OUTPUT\necho |tee -a $OUTPUT\necho \"#Cluster Networks - Non-cluster IP ranges, VLANS\" |tee -a $OUTPUT\nIFS=$'\\n';for i in `averecmd cluster.listNetworks|awk '{print $1}'`; do \\\n  ADDRESSESPERNODE=`averecmd cluster.getNetwork $i|grep addressesPerNode|cut -d \"'\" -f 2`\n  echo \"averecmd cluster.addNetwork $i \\\"{'addressesPerNode':'$ADDRESSESPERNODE'}\\\"\" >> $OUTPUT\n  if [ $i = \"cluster\" ]; then \\\n    for j in `averecmd cluster.getNetwork $i|grep addressRange|grep -v addressRange0`; do \\\n      NETWORK_NAME=`echo $i`\n      RANGE=`echo $j|cut -d \",\" -f 2-|rev|cut -c 3-|rev`\n      echo \"averecmd cluster.addClusterIPs \\\"{$RANGE}\\\"\" >> $OUTPUT\n      echo \"averecmd cluster.addNetworkAddressRange $NETWORK_NAME \\\"{$RANGE}\\\"\" >> $OUTPUT\n    done\n  else\n    for j in `averecmd cluster.getNetwork $i|grep addressRange`; do \\\n      NETWORK_NAME=`echo $i`\n      RANGE=`echo $j|cut -d \",\" -f 2-|rev|cut -c 3-|rev`\n#      echo \"averecmd cluster.addClusterIPs \\\"{$RANGE\\\"\" >> $OUTPUT\n      echo \"averecmd cluster.addNetworkAddressRange $NETWORK_NAME \\\"{$RANGE}\\\"\" >> $OUTPUT\n    done\n  fi\ndone\n\n# Moving the VServer section after the core filer add section.  This is because simple vservers require a core filer name and a simple vserver can't be created without an exisiting core filer\n#echo |tee -a $OUTPUT\n#echo \"#Manage VServers\" |tee -a $OUTPUT\n#IFS=$'\\n';for i in `averecmd vserver.list`; do \\\n#  for j in `averecmd vserver.get $i`;do \\\n#    FIRST_IP=`echo $j |awk -F\":\" '{print $12}'|cut -d \"'\" -f 2`\n#    LAST_IP=`echo $j|awk -F\":\" '{print $15}'|cut -d \"'\" -f 2`\n#    NETMASK=`echo $j|awk -F\":\" '{print $13}'|cut -d \"'\" -f 2`\n#    MASS=`echo $j|cut -d \"'\" -f 29`\n#    TYPE=`echo $j|cut -d \"'\" -f 59`\n#    if [ $TYPE == \"simple\" ]; then \\\n#      echo \"averecmd vserver.create $i \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','lastIP':'$LAST_IP'}\\\" $MASS\" >> $OUTPUT\n#    else\n#      echo \"averecmd vserver.create $i \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','lastIP':'$LAST_IP'}\\\"\" >> $OUTPUT\n#    fi\n#  done\n#done\n\necho |tee -a $OUTPUT\necho \"#Manage Caching Policies\" |tee -a $OUTPUT\n#IFS=$'\\n';for i in `averecmd --pretty cachePolicy.list|egrep -v \"'Clients Bypassing the Cluster'|'Read Caching'|'Read and Write Caching'|'Full Caching'|'Transitioning Clients Before or After a Migration'\"|grep name|awk -F\"'\" '{print $4}'`;do \\\n\nIFS=$'\\n';for i in `averecmd cachePolicy.list|egrep -v \"'Clients Bypassing the Cluster'|'Read Caching'|'Read and Write Caching'|'Full Caching'|'Transitioning Clients Before or After a Migration'\"|grep name|awk -F \"name\" '{print $2}'|cut -d \"'\" -f 3`; do \\\n  WRITEBACKDELAY=`averecmd cachePolicy.get $i|grep writebackDelay|awk -F\"'\" '{print $2}'`\n  NAME=`averecmd cachePolicy.get $i|grep name|awk -F\"'\" '{print $2}'`\n  LOCALDIRECTORIES=`averecmd cachePolicy.get $i|grep localDirectories|awk -F\"'\" '{print $2}'`\n  CACHEMODE=`averecmd cachePolicy.get $i|grep cacheMode|awk -F\"'\" '{print $2}'`\n  CHECKATTRIBUTES=`averecmd cachePolicy.get $i|grep checkAttributes|cut -d '{' -f 2|cut -d '}' -f 1`\n  DESCRIPTION=`averecmd cachePolicy.get $i|grep description|awk -F\"'\" '{print $2}'`\n  echo \"averecmd cachePolicy.create \\\"$NAME\\\" $CACHEMODE $WRITEBACKDELAY \\\"{$CHECKATTRIBUTES}\\\" $LOCALDIRECTORIES {} \\\"\\\" \\\"$DESCRIPTION\\\"\" >> $OUTPUT\ndone\n\necho |tee -a $OUTPUT\necho \"#Manage Core Filers and Core Filer Details\" |tee -a $OUTPUT\n\nIFS=$'\\n';for i in `averecmd corefiler.list`;do \\\n  TYPE=`averecmd --pretty corefiler.get $i|grep type|cut -d \"'\" -f 4`\n  if [ $TYPE == \"NFS\" ]; then\n    CORE_FILER=`averecmd --pretty corefiler.get $i|egrep \"filerClass|\\<name\\>|\\<network\\>|\\<networkName\\>|policyName\"`\n    FILERCLASS=`echo $CORE_FILER|tr ',' '\\n'|grep filerClass|cut -d \"'\" -f 4`\n    NAME=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<name\\>'|cut -d \"'\" -f 4`\n    NETWORK=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<network\\>'|cut -d \"'\" -f 4`\n    NETWORKNAME=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<networkName\\>'|cut -d \"'\" -f 4`\n    POLICYNAME=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<policyName\\>'|cut -d \"'\" -f 4`\n    FORCE=True\n    echo \"averecmd corefiler.create \\\"$NAME\\\" \\\"$NETWORKNAME\\\" True \\\"{'filerClass':'$FILERCLASS', 'force':'$FORCE', 'cachePolicy':'$POLICYNAME'}\\\";sleep 3\" >> $OUTPUT\n\techo \"averecmd corefiler.modify \\\"$NAME\\\" \\\"{'clientSuspend':'no'}\\\"\">> $OUTPUT\n  fi\n  if [ \"$NETWORK\" != \"cluster\" ]; then \n    echo \"averecmd corefiler.modifyNetwork \\\"$NAME\\\" \\\"$NETWORK\\\"\" >> $OUTPUT\n  fi\n\n  if  [ $TYPE == \"cloud\" ]; then\n    CORE_FILER=`averecmd --pretty corefiler.get $i`\n    NAME=`echo $i`\n    NETWORKNAME=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<networkName\\>'|cut -d \"'\" -f 4`\n    CLOUDTYPE=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<cloudType\\>'|cut -d \"'\" -f 4`\n    FORCE=True\n    BUCKET=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<bucket\\>'|cut -d \"'\" -f 4`\n    CLOUDCREDENTIAL=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<cloudCredential\\>'|cut -d \"'\" -f 4`\n    CRYPTOMODE=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<cryptoMode\\>'|cut -d \"'\" -f 4`\n    COMPRESSMODE=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<compressMode\\>'|cut -d \"'\" -f 4`\n    CACHEPOLICYNAME=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<policyName\\>'|cut -d \"'\" -f 4`\n    SSLVERIFY=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<sslVerifyMode\\>'|cut -d \"'\" -f 4`\n    PORT=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<port\\>'|cut -d \"'\" -f 4`\n    HTTPS=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<https\\>'|cut -d \"'\" -f 4`\n    NETWORK=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<network\\>'|cut -d \"'\" -f 4`\n    REGION=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<region\\>'|cut -d \"'\" -f 4`\n    S3TYPE=`echo $CORE_FILER|tr ',' '\\n'|grep '\\<s3Type\\>'|cut -d \"'\" -f 4`\n    if [[ $S3TYPE = \"ECS\" ]] || [[ $S3TYPE = \"ATMOS\" ]] || [[ $CLOUDTYPE = \"azure\" ]]; then\n      SERVERNAME=$NETWORKNAME\n    else\n      SERVERNAME=$BUCKET.$NETWORKNAME\n    fi\n    echo \"averecmd corefiler.createCloudFiler \\\"$NAME\\\" \\\"{'cloudType':'$CLOUDTYPE', 'force':'$FORCE', 'bucket':'$BUCKET', 'cloudCredential':'$CLOUDCREDENTIAL', 'cryptoMode':'$CRYPTOMODE','compressMode':'$COMPRESSMODE', 'cachePolicyName':'$CACHEPOLICYNAME', 'sslVerifyMode':'$SSLVERIFY', 'port':'$PORT', 'https':'$HTTPS', 'networkName':'$NETWORKNAME', 'bucketContents':'used', 'region':'$REGION', 's3Type':'$S3TYPE', 'serverName':'$SERVERNAME'}\\\";sleep 3\" >> $OUTPUT\n    echo \"averecmd corefiler.modify \\\"$NAME\\\" \\\"{'clientSuspend':'no'}\\\"\">> $OUTPUT\n\n    if [ $NETWORK != \"cluster\" ]; then \n      echo \"averecmd corefiler.modifyNetwork \\\"$NAME\\\" \\\"$NETWORK\\\"\" >> $OUTPUT\n    fi\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#Manage VServers\" |tee -a $OUTPUT\nfor VSERVER in `lsu vservers|grep -v _|cut -d ':' -f 1`; do \\\n  for j in `lsu $VSERVER|grep dataIP|cut -d ' ' -f 2`; do \\\n    FIRST_IP=`echo $j|cut -d ',' -f 1`\n    LAST_IP=`echo $j|cut -d ',' -f 2|cut -d ';' -f 1`\n    NETMASK=`echo $j|cut -d ',' -f 2|cut -d ':' -f 2`\n    FIB=`echo $j|cut -d ' ' -f2|cut -d ',' -f 3|cut -d ':' -f 2`\n    NAME=`lsu $VSERVER name|cut -d ' ' -f 2`\n    VLAN=`averecmd --pretty vserver.get $NAME|grep vlan|cut -d \"'\" -f 4`\n    TYPE=`averecmd --pretty vserver.get $NAME|grep type|cut -d \"'\" -f 4`\n    MASS=`averecmd --pretty vserver.get $NAME|grep mass|cut -d \"'\" -f 4`\n#    echo $j\n#    echo \"Name:     \" $NAME\n#    echo \"First IP: \" $FIRST_IP\n#    echo \"Last IP:  \" $LAST_IP\n#    echo \"Netmask:  \" $NETMASK\n#    echo \"FIB:      \" $FIB\n#    echo \"VLAN:     \" $VLAN\n#    echo \"Type:     \" $TYPE\n#    echo \"Mass:     \" $MASS\n    if [[ $TYPE == \"simple\" ]]; then \\\n\t  if  [[ $VLAN ]]; then \\\n        echo \"averecmd vserver.create $NAME \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','vlan':'$VLAN','lastIP':'$LAST_IP'}\\\" $MASS\" >> $OUTPUT\n\t  else\n\t    echo \"averecmd vserver.create $NAME \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','lastIP':'$LAST_IP'}\\\" $MASS\" >> $OUTPUT\n\t  fi\n    elif [[ $TYPE != \"simple\" ]]; then \\\n      if [[ $VLAN ]]; then \\\n        echo \"averecmd vserver.create $NAME \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','vlan':'$VLAN','lastIP':'$LAST_IP'}\\\"\" >> $OUTPUT\n      else\n        echo \"averecmd vserver.create $NAME \\\"{'firstIP':'$FIRST_IP','netmask':'$NETMASK','lastIP':'$LAST_IP'}\\\"\" >> $OUTPUT\n\t  fi\n    fi\n#  echo\n  done\ndone\n\necho |tee -a $OUTPUT\necho \"#Custom settings are addressed with \\\"2-run_on_new_cluster_mass_mappings.sh\\\", \\\"3-run_on_new_cluster_new_custom_settings.sh\\\", \\\"4-run_on_new_cluster_new_custom_settings.sh\\\"\" |tee -a $OUTPUT\n\n#IFS=$'\\n';for i in `name_mapping.py --custom|egrep -v 'Custom Settings:|----------------'`;do \\\nIFS=$'\\n';for i in `name_mapping.py --custom|egrep -v 'Custom Settings:|----------------|smbacldMassids'`;do \\\n  NAME=`echo $i|cut -d ':' -f 1|awk '{print $1}'`\n  CHECKCODE=`averecmd support.checkCode $NAME|grep check|cut -d \"'\" -f 2`\n  VALUE=`echo $i|awk '{print $2}'`\n  NOTE=`echo $i|cut -d '(' -f 2`;\n  if [[ $NOTE = *\"NOT in cluster.settings\"* ]]; then \\\n    NAME2=`echo $NAME|tr . ' '`\n    echo \"dbutil.py set $NAME2 $VALUE -x\" >> $OUTPUT_DIR/original_custom_settings.txt\n  else\n    echo \"averecmd support.setCustomSetting $NAME $CHECKCODE $VALUE \\\"($NOTE\\\"\" >> $OUTPUT_DIR/original_custom_settings.txt\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#Cloud Snapshot Policies\" |tee -a $OUTPUT\n# New in 4.7\nfor i in `averecmd --pretty snapshot.listPolicies|grep corefilers|cut -d \"'\" -f 4`; do \\\n  if [ `averecmd --pretty corefiler.get $i|grep type|cut -d \"'\" -f 4` = \"cloud\" ]; then\n    DEFAULTWEEKDAY=`averecmd snapshot.getFilerPolicy $i|grep defaultWeekDay|cut -d \"'\" -f 2`\n    NAME=`averecmd snapshot.getFilerPolicy $i|grep name|cut -d \"'\" -f 2`\n    DEFAULTMONTHDAY=`averecmd snapshot.getFilerPolicy $i|grep defaultMonthDay|cut -d \"'\" -f 2`\n    DEFAULTTIME=`averecmd snapshot.getFilerPolicy $i|grep defaultTime|cut -d \"'\" -f 2`\n    NOTE=`averecmd snapshot.getFilerPolicy $i|grep note|cut -d \"'\" -f 2`\n    POLICY=`averecmd snapshot.getFilerPolicy $i|grep policy|cut -d \"'\" -f 2-|rev|cut -d \"'\" -f 2-|rev`\n    if [ ! `averecmd snapshot.getFilerPolicy $i|grep snapType|cut -d \"'\" -f 2` ]; then\n      SNAPTYPE=strict\n    else \n      SNAPTYPE=`averecmd snapshot.getFilerPolicy $i|grep snapType|cut -d \"'\" -f 2`\n    fi\n    if [ \"$POLICY\" ]; then\n      if [ \"$RELEASE\" -ge \"48\" ]; then\n        echo \"averecmd snapshot.createPolicy \\\"$NAME\\\" \\\"$POLICY\\\" \\\"{'note':'$NOTE','defaultTime':'$DEFAULTTIME', 'snapType':'$SNAPTYPE'}\\\"\" >> $OUTPUT\n      else\n        echo \"averecmd snapshot.createPolicy \\\"$NAME\\\" \\\"$POLICY\\\" \\\"{'note':'$NOTE','defaultTime':'$DEFAULTTIME'}\\\"\" >> $OUTPUT\n      fi\n      echo \"sleep 5\" >> $OUTPUT\n      echo \"averecmd snapshot.modifyFilerPolicy $i \\\"$NAME\\\"\" >> $OUTPUT\n    fi\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#NFS\" |tee -a $OUTPUT\nN=0;IFS=$'\\n';for i in `averecmd vserver.list`;do \\\n  for j in `averecmd nfs.get $i`; do \\\n    A_NFS[$N]=`echo $j|cut -d \"'\" -f 2`\n    let \"N=$N+1\"\n  done\n  RWSIZE=`echo ${A_NFS[0]}`\n  KERBEROS=`echo ${A_NFS[1]}`\n  EXTENDEDGROUPS=`echo ${A_NFS[2]}`\n  echo \"averecmd nfs.modify $i \\\"{'kerberos':'$KERBEROS','extendedGroups':'$EXTENDEDGROUPS'}\\\"\" >> $OUTPUT\ndone\n\necho |tee -a $OUTPUT\necho \"#Namespace\" |tee -a $OUTPUT\necho \"sleep 5\" >> $OUTPUT\n#IFS=$'\\n';for i in `averecmd vserver.list`;do \\\n#  for j in `averecmd vserver.listJunctions $i`;do \\\n#    SHARESUBDIR=`echo $j|cut -d \"'\" -f 4`\n#    INHERITPOLICY=`echo $j|cut -d \"'\" -f 8`\n#    SHARENAME=`echo $j|cut -d \"'\" -f 16`\n#    ACCESS=`echo $j|cut -d \"'\" -f 24`\n#    EXPORT=`echo $j|cut -d \"'\" -f 28`\n#    SUBDIR=`echo $j|cut -d \"'\" -f 32`\n#    if [ $SUBDIR ]; then\n#      CREATESUBDIRS=yes\n#    else\n#      CREATESUBDIRS=no\n#    fi\n#    JUNCTION_PATH=`echo $j|cut -d \"'\" -f 40`\n#    COREFILER=`echo $j|cut -d \"'\" -f 44`\n#    if [ $INHERITPOLICY == \"no\" ]; then\n#      POLICY=`echo $j|cut -d \"'\" -f 36`\n#      echo \"averecmd vserver.addJunction $i $JUNCTION_PATH $COREFILER $EXPORT \\\"{'sharesubdir': '$SHARESUBDIR', 'inheritPolicy': '$INHERITPOLICY', 'sharename': '$SHARENAME', 'access': '$ACCESS', 'subdir': '$SUBDIR', 'createSubdirs':'$CREATESUBDIRS', 'policy':'$POLICY'}\\\"\" >> $OUTPUT\n#    else\n#      echo \"averecmd vserver.addJunction $i $JUNCTION_PATH $COREFILER $EXPORT \\\"{'sharesubdir': '$SHARESUBDIR', 'inheritPolicy': '$INHERITPOLICY', 'sharename': '$SHARENAME', 'access': '$ACCESS', 'subdir': '$SUBDIR', 'createSubdirs':'$CREATESUBDIRS'}\\\"\" >> $OUTPUT\n#    fi\n#  done\n#done\n\nIFS=$'\\n';for i in `averecmd vserver.list`;do \\\n  for j in `averecmd vserver.listJunctions $i`;do \\\n    SHARESUBDIR=`echo $j|tr ',' '\\n'|egrep \"\\<sharesubdir\\>\"|awk -F\"'\" '{print $4}'`\n    INHERITPOLICY=`echo $j|tr ',' '\\n'|egrep \"\\<inheritPolicy\\>\"|awk -F\"'\" '{print $4}'`\n    SHARENAME=`echo $j|tr ',' '\\n'|egrep \"\\<sharename\\>\"|awk -F\"'\" '{print $4}'`\n    ACCESS=`echo $j|tr ',' '\\n'|egrep \"\\<access\\>\"|awk -F\"'\" '{print $4}'`\n    EXPORT=`echo $j|tr ',' '\\n'|egrep \"\\<export\\>\"|awk -F\"'\" '{print $4}'`\n    SUBDIR=`echo $j|tr ',' '\\n'|egrep \"\\<subdir\\>\"|awk -F\"'\" '{print $4}'`\n    if [ $SUBDIR ]; then\n      CREATESUBDIRS=yes\n    else\n      CREATESUBDIRS=no\n    fi\n    JUNCTION_PATH=`echo $j|tr ',' '\\n'|egrep \"\\<path\\>\"|awk -F\"'\" '{print $4}'`\n    COREFILER=`echo $j|tr ',' '\\n'|egrep \"\\<corefiler\\>\"|awk -F\"'\" '{print $4}'`\n    if [ $INHERITPOLICY == \"no\" ]; then\n      POLICY=`echo $j|tr ',' '\\n'|egrep \"\\<policy\\>\"|awk -F\"'\" '{print $4}'`\n      echo \"averecmd vserver.addJunction $i $JUNCTION_PATH $COREFILER $EXPORT \\\"{'sharesubdir': '$SHARESUBDIR', 'inheritPolicy': '$INHERITPOLICY', 'sharename': '$SHARENAME', 'access': '$ACCESS', 'subdir': '$SUBDIR', 'createSubdirs':'$CREATESUBDIRS', 'policy':'$POLICY'}\\\"\" >> $OUTPUT\n    else\n      echo \"averecmd vserver.addJunction $i $JUNCTION_PATH $COREFILER $EXPORT \\\"{'sharesubdir': '$SHARESUBDIR', 'inheritPolicy': '$INHERITPOLICY', 'sharename': '$SHARENAME', 'access': '$ACCESS', 'subdir': '$SUBDIR', 'createSubdirs':'$CREATESUBDIRS'}\\\"\" >> $OUTPUT\n    fi\n  done\ndone\n\n\necho |tee -a $OUTPUT\necho \"#Directory Services and Kerberos\" |tee -a $OUTPUT\nA_DIRSERVICES=()\nN=0;IFS=$'\\n';for i in `averecmd dirServices.get default`;do \\\n  A_DIRSERVICES[$N]=`echo $i\\|`\n  let \"N = $N + 1\"\ndone\n\nM=0;\nMAX=`expr ${#A_DIRSERVICES[@]} - 1`\nfor i in ${A_DIRSERVICES[@]}; do \\\nif [[ $i != \"rev\"* ]] && [[ $i != \"id\"* ]]; then \\\n  SETTING=`echo $i|awk '{print $1}'`; \n  VALUE=`echo $i|cut -d \"'\" -f 2`; \n  if [ $M = \"0\" ]; then \\\n    echo \"averecmd dirServices.modify 'default' \\\"{'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  elif [ $VALUE ]; then \\\n    echo \"'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  fi\nfi\nlet \"M=$M+1\"\ndone\necho \"}\\\"\" >> $OUTPUT\n\n\nA_DIRSERVICES=()\nN=0;IFS=$'\\n';for i in `averecmd dirServices.get login`;do \\\n  A_DIRSERVICES[$N]=`echo $i\\|`\n  let \"N = $N + 1\"\ndone\n\nM=0;\nMAX=`expr ${#A_DIRSERVICES[@]} - 1`\nfor i in ${A_DIRSERVICES[@]}; do \\\nif [[ $i != \"rev\"* ]] && [[ $i != \"id\"* ]]; then \\\n  SETTING=`echo $i|awk '{print $1}'`; \n  VALUE=`echo $i|cut -d \"'\" -f 2`; \n  if [ $M = \"0\" ]; then \\\n    echo \"averecmd dirServices.modify 'login' \\\"{'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  elif [ $VALUE ]; then \\\n    echo \"'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  fi\nfi\nlet \"M=$M+1\"\ndone\necho \"}\\\"\" >> $OUTPUT\n\necho |tee -a $OUTPUT\nfor i in `averecmd vserver.list`; do \\\n  if [[ `averecmd cifs.getConfig $i|grep enabled|cut -d \"'\" -f 2` = \"True\" ]]; then \\\n    ENABLE_CIFS=True\n    CIFSSERVERNAME=`averecmd cifs.getConfig $i|grep CIFSServerName|cut -d \"'\" -f 2`;\n    echo \"#CIFS for vServer \\\"$i\\\"\" |tee -a $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n    chmod 700 $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n    CLIENT_NTLMSSP_DISABLE=`averecmd cifs.getOptions $i|grep client_ntlmssp_disable|cut -d \"'\" -f 2`;\n    GUEST_ACCOUNT=`averecmd cifs.getOptions $i|grep guest_account|cut -d \"'\" -f 2`;\n    SMB2=`averecmd cifs.getOptions $i|grep smb2|cut -d \"'\" -f 2`;\n    SMB1=`averecmd cifs.getOptions $i|grep smb1|cut -d \"'\" -f 2`;\n    NATIVE_IDENTITY=`averecmd cifs.getOptions $i|grep native_identity|cut -d \"'\" -f 2`;\n    READ_ONLY_OPTIMIZED=`averecmd cifs.getOptions $i|grep read_only_optimized|cut -d \"'\" -f 2`;\n    SERVER_SIGNING=`averecmd cifs.getOptions $i|grep server_signing|cut -d \"'\" -f 2`;\n    echo \"echo \"\"\" >> $OUTPUT\n    echo \"echo \"We have identified vserver \\\\\\\"$i\\\\\\\" has CIFS enabled however the Avere does not retain passwords so we are unable to automatically enable CIFS.\"\" >> $OUTPUT\n    echo \"echo \"You will need to join the vserver \\\\\\\"$i\\\\\\\" to the domain with the following information and then run the \\\\\\\"1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\\\\\\\" script.\"\" >> $OUTPUT\n    echo \"echo \"\"\" >> $OUTPUT\n    echo \"echo \"vserver is: \"$i\" >> $OUTPUT\n    echo \"echo \"Enable CIFS: \"$ENABLE_CIFS\" >> $OUTPUT\n    if [ $SMB1 ]; then \\\n      echo \"echo \"Enable SMB1: \"$SMB1\" >> $OUTPUT\n    fi\n    echo \"echo \"Enable SMB2: \"$SMB2\" >> $OUTPUT\n    echo \"echo \"CIFS Server Name: \"$CIFSSERVERNAME\" >> $OUTPUT\n    echo \"echo \"Enable Native Identity: \"$NATIVE_IDENTITY\" >> $OUTPUT\n    echo \"echo \"Enable Read-only Optimized: \"$READ_ONLY_OPTIMIZED\" >> $OUTPUT\n    echo \"echo \"Client NTLMSSP Disable: \"$CLIENT_NTLMSSP_DISABLE\" >> $OUTPUT\n    if [ $SERVER_SIGNING ]; then \\\n      echo \"echo \"Server Signing \"$SERVER_SIGNING\" >> $OUTPUT\n    fi\n    echo \"echo \"Guest Account: \"$GUEST_ACCOUNT\" >> $OUTPUT\n    echo \"echo \"\"\" >> $OUTPUT\n    echo \"read -p \\\"Press enter AFTER \\\\\\\"$i\\\\\\\" has joined the domain\\\"\" >> $OUTPUT\n  else\n    echo \"echo \"\"\" >> $OUTPUT\n    echo \"#CIFS is not enabled for vServer \\\"$i\\\"\" |tee -a $OUTPUT\n  fi\ndone\n\necho |tee -a $OUTPUT\n\n# This method of getting CIFS shares cut time down\nIFS=$'\\n';for i in `averecmd vserver.list`; do \\\n  for SHARENAME in `averecmd --pretty cifs.listShares $i|grep shareName|cut -d \"'\" -f 4`; do \\\n    IFS=$' '\n    CIFS_SHARE=`averecmd cifs.getShare $i $SHARENAME`\n    ACCESSCONTROL=`echo $CIFS_SHARE|grep accessControl|cut -d \"'\" -f 2`\n    HOMEDIR=`echo $CIFS_SHARE|grep homeDir|cut -d \"'\" -f 2`\n    EXPORT=`echo $CIFS_SHARE|grep export|cut -d \"'\" -f 2`\n    SUFFIX=`echo $CIFS_SHARE|grep suffix|cut -d \"'\" -f 2`\n    NAMESPACE=`averecmd --pretty vserver.get $i|grep type|cut -d \"'\" -f 4`\n    if [ $HOMEDIR == \"yes\" ]; then \\\n      HOMEDIR=True\n    fi\n    if [ $NAMESPACE == \"gns\" ]; then \\\n      ACCESSCONTROL=\"''\"\n    fi\n    if [ -z \"$SUFFIX\" ]; then \\\n      SUFFIX=\"''\"\n    fi\n    FORCE_USER=`echo $CIFS_SHARE|grep \"force user\"|cut -d \"'\" -f 2`\n    LEVEL2_OPLOCKS=`echo $CIFS_SHARE|grep \"level2 oplocks\"|cut -d \"'\" -f 2`\n    STRICT_LOCKING=`echo $CIFS_SHARE|grep \"strict locking\"|cut -d \"'\" -f 2`\n    READ_ONLY_OPTIMIZED=`echo $CIFS_SHARE|grep \"read only optimized\"|cut -d \"'\" -f 2`\n    INHERIT_PERMISSIONS=`echo $CIFS_SHARE|grep \"inherit permissions\"|cut -d \"'\" -f 2`\n    CREATE_MASK=`echo $CIFS_SHARE|grep \"create mask\"|cut -d \"'\" -f 2`\n    BROWSEABLE=`echo $CIFS_SHARE|grep \"browseable\"|cut -d \"'\" -f 2`\n    SECURITY_MASK=`echo $CIFS_SHARE|grep \"security mask\"|grep -v directory|cut -d \"'\" -f 2`\n    DIRECTORY_MASK=`echo $CIFS_SHARE|grep \"directory mask\"|cut -d \"'\" -f 2`\n    GUEST_OK=`echo $CIFS_SHARE|grep \"guest ok\"|cut -d \"'\" -f 2`\n    FORCE_CREATE_MODE=`echo $CIFS_SHARE|grep \"force create mode\"|cut -d \"'\" -f 2`\n    HIDE_UNREADABLE=`echo $CIFS_SHARE|grep \"hide unreadable\"|cut -d \"'\" -f 2`\n    FORCE_DIRECTORY_MODE=`echo $CIFS_SHARE|grep \"force directory mode\"|cut -d \"'\" -f 2`\n    READ_ONLY=`echo $CIFS_SHARE|grep \"read only\"|grep -v optimized|cut -d \"'\" -f 2`\n    DIRECTORY_SECURITY_MASK=`echo $CIFS_SHARE|grep \"\\<directory security mask\\>\"|cut -d \"'\" -f 2`\n    FORCE_DIRECTORY_SECURITY_MODE=`echo $CIFS_SHARE|grep \"force directory security mode\"|cut -d \"'\" -f 2`\n    OPLOCKS=`echo $CIFS_SHARE|grep oplocks|grep -v level2|cut -d \"'\" -f 2`\n    FORCE_GROUP=`echo $CIFS_SHARE|grep \"force group\"|cut -d \"'\" -f 2`\n    FORCE_SECURITY_MODE=`echo $CIFS_SHARE|grep \"force security mode\"|cut -d \"'\" -f 2`\n    echo \"averecmd cifs.addShare $i $SHARENAME $EXPORT $SUFFIX $ACCESSCONTROL $HOMEDIR \\\"{'browseable':'$BROWSEABLE', 'inherit permissions':'$INHERIT_PERMISSIONS', 'read only':'$READ_ONLY', 'hide unreadable':'$HIDE_UNREADABLE', 'strict locking':'$STRICT_LOCKING', 'oplocks':'$OPLOCKS', 'level2 oplocks':'$LEVEL2_OPLOCKS', 'read only optimized':'$READ_ONLY_OPTIMIZED', 'guest ok':'$GUEST_OK', 'create mask':'$CREATE_MASK', 'security mask':'$SECURITY_MASK', 'directory mask':'$DIRECTORY_MASK', 'directory security mask':'$DIRECTORY_SECURITY_MASK', 'force create mode':'$FORCE_CREATE_MODE', 'force security mode':'$FORCE_SECURITY_MODE', 'force directory mode':'$FORCE_DIRECTORY_MODE', 'force directory security mode':'$FORCE_DIRECTORY_SECURITY_MODE', 'force user':'$FORCE_USER', 'force group':'$FORCE_GROUP'}\\\"\" >> $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n  done\ndone\necho \"sleep 5\" >> $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n\nif [ $ENABLE_CIFS == \"True\" ]; then\n  echo \"#CIFS shares\" |tee -a $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n  IFS=$'\\n';for i in `averecmd vserver.list`; do \\\n    for j in `averecmd --pretty cifs.listShares $i|grep shareName|cut -d \"'\" -f 4`; do \\\n      HOMEDIR=`averecmd --pretty cifs.getShare $i $j|grep homeDir|cut -d \"'\" -f 4`\n      if [ $HOMEDIR == \"no\" ]; then\n        echo \"averecmd cifs.removeShareAce $i $j \\\"{'id':'Everyone', 'type':'ALLOW', 'perm':'FULL'}\\\"\" >> $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n        for SHARE in `averecmd cifs.getShareAcl $i $j`; do \\\n          TYPE=`echo $SHARE|cut -d \"'\" -f 4`\n          ID=`echo $SHARE|cut -d \"'\" -f 8`\n          PERM=`echo $SHARE|cut -d \"'\" -f 12`\n          echo \"averecmd cifs.addShareAce $i $j \\\"{'id':'$ID', 'type':'$TYPE', 'perm':'$PERM'}\\\"\" >> $OUTPUT_DIR/1.5-run_on_new_cluster_before_custom_settings_restore_cifs.sh\n        done\n      fi\n    done\n  done\nfi\n\necho |tee -a $OUTPUT\necho \"#Vserver Details\" |tee -a $OUTPUT\nfor i in `averecmd vserver.list`; do \\\n  HOTCLIENTENABLED=`averecmd --pretty vserver.get $i|grep hotClientEnabled|cut -d \"'\" -f 4`\n  HOTCLIENTPERIOD=`averecmd --pretty vserver.get $i|grep hotClientPeriod|cut -d \"'\" -f 4`\n  HOTCLIENTLIMIT=`averecmd --pretty vserver.get $i|grep hotClientLimit|cut -d \"'\" -f 4`\n  CLIENTSUSPENDSTATUS=`averecmd --pretty vserver.get $i|grep clientSuspendStatus|cut -d \"'\" -f 4`\n  if [ $HOTCLIENTENABLED == yes ]; then \\\n    echo \"averecmd stats.enableHotCollection $i $HOTCLIENTLIMIT $HOTCLIENTPERIOD\" >> $OUTPUT\n  else\n    echo \"#Nothing to do for $i\" >> $OUTPUT\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#Export Policies\" |tee -a $OUTPUT\nfor i in `averecmd vserver.list`; do \\\n  for j in `averecmd nfs.listPolicies $i`; do \\\n    if [ $j != \"default\" ]; then \\\n      echo \"averecmd nfs.addPolicy $i $j\" >> $OUTPUT\n    fi\n  done\ndone\n\n\necho |tee -a $OUTPUT\necho \"#Export Rules\" |tee -a $OUTPUT\nIFS=$'\\n';for VSERVER in `averecmd vserver.list`; do \\\n  for POLICY in `averecmd nfs.listPolicies $VSERVER`; do \\\n    for RULE in `averecmd nfs.listRules $VSERVER $POLICY`; do \\\n      if [ `echo $RULE|grep netgroup` ]; then\n        echo \"\" >> $OUTPUT\n        echo \"#We can't restore netgroup policies at this time so please note the following...\" >> $OUTPUT\n        echo \"#  \"`echo $RULE|grep netgroup` >> $OUTPUT\n        echo \"\" >> $OUTPUT\n      else\n        if [ `echo $RULE |grep -v netgroup|grep '*'` ]; then \\\n          FILTER=0.0.0.0\n        else \n          FILTER=`echo $RULE|tr ',' '\\n'|grep filter|cut -d \"'\" -f 4`\n        fi\n        if [[ $FILTER = *\"/\"* ]]; then \\\n          NETMASK=/`echo $FILTER|cut -d '/' -f 2`\n          FILTER=`echo $FILTER|cut -d '/' -f 1`\n        fi\n        ACCESS=`echo $RULE|tr ',' '\\n'|grep access|cut -d \"'\" -f 4`\n        ANONUID=`echo $RULE|tr ',' '\\n'|grep anonuid|cut -d \"'\" -f 4`\n        if [ -z $ANONUID ]; then \\\n          ANONUID=0;\n        fi\n        PERMISSION=`echo $RULE|tr ',' '\\n'|grep access|cut -d \"'\" -f 4`\n        AUTHKRB=`echo $RULE|tr ',' '\\n'|grep authKrb|cut -d \"'\" -f 4`\n        AUTHSYS=`echo $RULE|tr ',' '\\n'|grep authSys|cut -d \"'\" -f 4`\n        SCOPE=`echo $RULE|tr ',' '\\n'|grep scope|cut -d \"'\" -f 4`\n        SQUASH=`echo $RULE|tr ',' '\\n'|grep squash|cut -d \"'\" -f 4`\n        SUBDIR=`echo $RULE|tr ',' '\\n'|grep subdir|cut -d \"'\" -f 4`\n        SUID=`echo $RULE|tr ',' '\\n'|grep suid|cut -d \"'\" -f 4`\n        if [[ $FILTER == \"0.0.0.0\" ]]; then \\\n          FILTER=\"*\"\n        fi\n        if [[ $POLICY == \"default\" && $SCOPE == \"default\" && $FILTER == \"*\" ]]; then \\\n          echo \"NEW_ID=\\`averecmd --pretty nfs.listRules $VSERVER default 0.0.0.0 |grep \\\"\\\\<id\\\\>\\\"|cut -d \\\"'\\\" -f 4\\`\" >> $OUTPUT\n          echo \"averecmd nfs.modifyRule \\$NEW_ID \\\"{'scope':'$SCOPE' , 'access':'$PERMISSION' , 'anonuid':'$ANONUID'}\\\"\" >> $OUTPUT\n        elif [ $SCOPE = \"network\" ]; then \\\n          echo \"averecmd nfs.addRule '$VSERVER' '$POLICY' '$SCOPE' '$FILTER$NETMASK' '$PERMISSION' '$SQUASH' '$ANONUID' '$SUID' '$SUBDIR' \\\"{'authKrb':'$AUTHKRB', 'authSys':'$AUTHSYS'}\\\"\" >> $OUTPUT\n        else\n          echo \"averecmd nfs.addRule '$VSERVER' '$POLICY' '$SCOPE' '$FILTER' '$PERMISSION' '$SQUASH' '$ANONUID' '$SUID' '$SUBDIR' \\\"{'authKrb':'$AUTHKRB', 'authSys':'$AUTHSYS'}\\\"\" >> $OUTPUT\n        fi\n      fi\n    done\n  done\ndone\n\necho |tee -a $OUTPUT\necho \"#Cloud Encryption Settings\" |tee -a $OUTPUT\necho \"#Nothing to do here since we already added the encryption type when creating the core filer\" |tee -a $OUTPUT\n\necho |tee -a $OUTPUT\necho \"#General Setup, Administrative Network, Proxy Configuration, FXT Nodes\" |tee -a $OUTPUT\n\n#Unable to set the following options: advancedNetworking, MTU, ha, default router, dirmgrDistributionState, clusterIPNumPerNode, proxyuser, proxyurl\n#Also excluding \"mgmtIP\" and \"ClusterIPs\" because those values are part of the initial setup process\n\n# This will empty the array\nA_CLUSTER=();\n# This will fill up the array with values\n#N=0;IFS=$'\\n';for i in `averecmd cluster.get|egrep -v 'alternateImage|activeImage|dirmgrDistributionState|avereDataParameters|clusterIPs|mgmtIP'`;do   A_CLUSTER[$N]=`echo $i`;   let \"N = $N + 1\"; done\nN=0;IFS=$'\\n';for i in `averecmd cluster.get|egrep -v 'alternateImage|activeImage|dirmgrDistributionState|avereDataParameters|clusterIPs|mgmtIP|advancedNetworking|default_mtu|proxyurl|default_router|proxyuser|netmask|\\<ha\\>|clusterIPNumPerNode'`;do   A_CLUSTER[$N]=`echo $i`;   let \"N = $N + 1\"; done\nN=0; MAX=`expr ${#A_CLUSTER[@]} - 1`; \nfor i in ${A_CLUSTER[@]}; do \\\nif [[ $i != \"rev\"* ]] && [[ $i != \"id\"* ]]; then \\\n  SETTING=`echo $i|awk '{print $1}'`; \n  VALUE=`echo $i|awk -F \\= '{print $2}'`; \n\n  if [[ $SETTING = \"DNSdomain\" ]] && [[ $VALUE = *\"undefined\"* ]]; then \\\n    VALUE=\"''\"\n  fi\n\n  if [ $N = \"0\" ]; then \\\n    echo \"averecmd cluster.modify \\\"{'$SETTING'\":\"$VALUE\",\"\"  >> $OUTPUT;\n  elif [ $N = \"$MAX\" ]; then \\\n    echo \"'$SETTING'\":\"$VALUE}\\\"\"  >> $OUTPUT;\n  else\n    echo \"'$SETTING'\":\"$VALUE\",\"\" >> $OUTPUT;\n  fi\nfi\nlet \"N=$N+1\"\ndone\n\necho  |tee -a $OUTPUT\necho \"#Cluster networks are addressed in the cluster section\" |tee -a $OUTPUT\n\necho |tee -a $OUTPUT\necho \"#Proxy configuration is addressed in the cluster section\" |tee -a $OUTPUT\n\necho |tee -a $OUTPUT\necho \"#High Availability\" |tee -a $OUTPUT\necho \"#We are always enabling cluster HA because we don't support non-HA clusters\"\nN=0;IFS=$'\\n';for i in `averecmd cluster.getHADataParameters`; do \\\n  A_HADATA[$N]=`echo $i|cut -d \"'\" -f 2`\n  let \"N=$N+1\"\ndone\nDATAEXPORT=`echo ${A_HADATA[0]}`\nCOREFILER=`echo ${A_HADATA[1]}`\nMASS=`echo ${A_HADATA[2]}`\nDATADIR=`echo ${A_HADATA[3]}`\necho \"averecmd cluster.enableHA\" >> $OUTPUT\nif [ $MASS ]; then\n  echo \"averecmd cluster.setHADataParameters $COREFILER $DATAEXPORT $DATADIR\" >> $OUTPUT\nfi\n\necho |tee -a $OUTPUT\necho \"#Monitoring\" |tee -a $OUTPUT\nN=0;IFS=$'\\n';for i in `averecmd monitoring.emailSettings`; do \\\n  A_EMAILMONITORING[$N]=`echo $i|cut -d \"'\" -f 2-|rev|cut -d \"'\" -f 2-|rev`\n  let \"N=$N+1\"\ndone\nRECIPIENTS=`echo ${A_EMAILMONITORING[0]}`\nENABLED=`echo ${A_EMAILMONITORING[1]}`\nREV=`echo ${A_EMAILMONITORING[2]}`\nMORECONTEXT=`echo ${A_EMAILMONITORING[3]}`\nMAILFROMADDRESS=`echo ${A_EMAILMONITORING[4]}`\nID=`echo ${A_EMAILMONITORING[5]}`\nMAILSERVER=`echo ${A_EMAILMONITORING[6]}`\nif [ -z $MAILSERVER ]; then \\\n  echo \"#Monitoring is not configured\" >> $OUTPUT\nelse\n  echo \"averecmd monitoring.modifyEmailSettings \\\"{'mailFromAddress':'$MAILFROMADDRESS', 'mailServer':'$MAILSERVER', 'recipients':'$RECIPIENTS'}\\\"\" >> $OUTPUT\nfi\n\necho |tee -a $OUTPUT\necho \"#Client Facing Network\" |tee -a $OUTPUT\nIFS=$'\\n';for i in `averecmd vserver.list`;do \\\n  for j in `averecmd vserver.listClientIPHomes $i`; do \\\n    NODE=`echo $j|awk -F\"'\" '{print $4}'`\n    IP=`echo $j|awk -F\"'\" '{print $8}'`\n    HOME=`echo $j|awk -F\"'\" '{print $12}'`\n    if [ $HOME != None ]; then \\\n      echo \"averecmd vserver.modifyClientIPHomes $i \\\"{'$IP':'$HOME'}\\\"\" >> $OUTPUT\n    fi\n  done\ndone\n\necho |tee -a $OUTPUT\necho \"#Monitoring - Logs\" |tee -a $OUTPUT\n\nif [ $RELEASE -lt \"47\" ]; then \\\n#  PRE47\n  SYSLOGSERVER=`averecmd monitoring.syslogServer`\n  if [ $SYSLOGSERVER ]; then \\\n    echo \"averecmd monitoring.setSyslogServer $SYSLOGSERVER\" >> $OUTPUT\n  else\n    echo \"#A syslog server has not been set\" >> $OUTPUT\n  fi\nelse\n#  POST47\n  if [ `averecmd monitoring.getSyslogServer` ]; then \\\n    REMOVESYSLOGSERVER=`averecmd monitoring.getSyslogSettings|grep remoteSyslogServer|cut -d \"'\" -f 2`\n    FORWARDING_OPTIONS=`averecmd monitoring.getSyslogSettings|grep forwarding_options|cut -d \"'\" -f 2-8`\n    echo \"averecmd monitoring.setSyslogServer $REMOVESYSLOGSERVER \\\"$FORWARDING_OPTIONS\\\"\" >> $OUTPUT\n  else \n    FORWARDING_OPTIONS=`averecmd monitoring.getSyslogSettings|grep forwarding_options|cut -d \"'\" -f 2-8`\n    echo \"averecmd monitoring.setSyslogServer '' \\\"$FORWARDING_OPTIONS\\\"\" >> $OUTPUT\n  fi\nfi\n\necho |tee -a $OUTPUT\necho \"#Monitoring - SNMP monitoring\" |tee -a $OUTPUT\nN=0;IFS=$'\\n';for i in `averecmd monitoring.snmpSettings|awk '{print $3}'`;do \\\n  A_SNMP[$N]=`echo $i`\n  let \"N=$N+1\"\ndone\nif [[ ${A_SNMP[0]} == *\"yes\"* ]]; then \\\n  ENABLE=`echo ${A_SNMP[0]}`\n  READCOMMUNITYSTRING=`echo ${A_SNMP[1]}`\n  TRAPHOST=`echo ${A_SNMP[2]}`\n  REV=`echo ${A_SNMP[3]}`\n  CONTACT=`echo ${A_SNMP[4]}`\n  LOCATION=`echo ${A_SNMP[5]}`\n  TRAPPORT=`echo ${A_SNMP[6]}`\n  ID=`echo ${A_SNMP[7]}`\n  echo \"averecmd monitoring.modifySnmpSettings \\\"{'enable':$ENABLE, 'contact':$CONTACT, 'location':$LOCATION, 'trapHost':$TRAPHOST, 'trapPort':$TRAPPORT, 'readCommunityString':$READCOMMUNITYSTRING}\\\"\" >> $OUTPUT\nelse\n  echo \"#SNMP monitoring has not been set\" >> $OUTPUT\nfi\n\necho |tee -a $OUTPUT\necho \"#Schedules\" |tee -a $OUTPUT\nIFS=$'\\n';for i in `averecmd cluster.listSchedules`; do \\\n  NAME=`echo $i|cut -d \"'\" -f 18`\n  MINUTES=`echo $i|cut -d \"'\" -f 10`\n  HOURS=`echo $i|cut -d \"'\" -f 6`\n  DAYS=`echo $i|cut -d \"'\" -f 14`\n  echo \"averecmd cluster.addSchedule $NAME \\\"[{'hours':'$HOURS', 'minutes':'$MINUTES', 'days':'$DAYS'}]\\\"\" >> $OUTPUT\ndone\n\necho |tee -a $OUTPUT\necho \"#IPMI\" |tee -a $OUTPUT\necho \"#Note: If you see something like \\\"Caught Exception: Couldn't fetch attribute\\\" that means IPMI is not configured\"\nIFS=$'\\n';for i in `lsu nodes|grep -v _|cut -d ':' -f 1`; do \\\n  for j in `lsu $i ipmi`;do \\\n    if [[ $j != *\"Couldn't fetch attribute\"* ]]; then \\\n      MODE=`echo $j|awk '{print $3}'|cut -d '=' -f 2`\n      ADDRESS=`echo $j|awk '{print $4}'|cut -d '=' -f 2`\n      NETMASK=`echo $j|awk '{print $5}'|cut -d '=' -f 2`\n      ROUTER=`echo $j|awk '{print $6}'|cut -d '=' -f 2`\n      NAME=`lsu $i name`\n      echo \"averecmd node.modifyIPMI $NAME $MODE \\\"{'address':'$ADDRESS', 'netmask':'$NETMASK', 'router':'$ROUTER'}\\\"\" >> $OUTPUT\n    else \n      echo \"IPMI is not configured for node \"`lsu $i name` >> $OUTPUT\n    fi\n  done\ndone\n\necho |tee -a $OUTPUT\necho \"#Support - Customer Info and Secure Proactive Support (SPS)\" |tee -a $OUTPUT\n# This will empty the array\nA_SUPPORT=();\n# This will fill up the array with values\nN=0;IFS=$'\\n';for i in `averecmd support.get|egrep -v 'remoteCommandEnabledTime|tested|priorRemoteCommandLevel'`;do   A_SUPPORT[$N]=`echo $i`;   let \"N = $N + 1\"; done\n\nN=0; MAX=`expr ${#A_SUPPORT[@]} - 1`; \nfor i in ${A_SUPPORT[@]}; do \\\nif [[ $i != \"rev\"* ]] && [[ $i != \"id\"* ]]; then \\\n  SETTING=`echo $i|awk '{print $1}'`; \n  VALUE=`echo $i|awk -F \\' '{print $2}'`; \n  if [ $N = \"0\" ]; then \\\n    echo \"averecmd support.modify \\\"{'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  elif [ $N = \"$MAX\" ]; then \\\n    echo \"'$SETTING'\":\"'$VALUE'}\\\"\" >> $OUTPUT;\n  else\n    echo \"'$SETTING'\":\"'$VALUE'\",\"\" >> $OUTPUT;\n  fi\nfi\nlet \"N=$N+1\"\ndone\n\n# Moving cusom settings section after core filer add to give the core filers more time to be created\n#echo |tee -a $OUTPUT\n#echo \"#Custom settings are addressed with \\\"2-run_on_new_cluster_mass_mappings.sh\\\", \\\"3-run_on_new_cluster_new_custom_settings.sh\\\", \\\"4-run_on_new_cluster_new_custom_settings.sh\\\"\" |tee -a $OUTPUT\n#\n##IFS=$'\\n';for i in `name_mapping.py --custom|egrep -v 'Custom Settings:|----------------'`;do \\\n#IFS=$'\\n';for i in `name_mapping.py --custom|egrep -v 'Custom Settings:|----------------|smbacldMassids'`;do \\\n#  NAME=`echo $i|cut -d ':' -f 1|awk '{print $1}'`\n#  CHECKCODE=`averecmd support.checkCode $NAME|grep check|cut -d \"'\" -f 2`\n#  VALUE=`echo $i|awk '{print $2}'`\n#  NOTE=`echo $i|cut -d '(' -f 2`;\n#  if [[ $NOTE = *\"NOT in cluster.settings\"* ]]; then \\\n#    NAME2=`echo $NAME|tr . ' '`\n#    echo \"dbutil.py set $NAME2 $VALUE -x\" >> $OUTPUT_DIR/original_custom_settings.txt\n#  else\n#    echo \"averecmd support.setCustomSetting $NAME $CHECKCODE $VALUE \\\"($NOTE\\\"\" >> $OUTPUT_DIR/original_custom_settings.txt\n#  fi\n#done\n\n#vserver mapping\n# Convert current mass to new mass\nfor i in `lsu masses|grep -v _|cut -d ':' -f 1`; do \\\n  NAME=`lsu $i name|cut -d ' ' -f 2` \n  if [[ $NAME != \"127.0.0\"* ]]; then \\\n    echo \"********$i:$NAME\" >> $OUTPUT_DIR/masses.txt\n  fi\ndone  \n\nfor VSERVER in `lsu vservers|grep -v _|cut -d ':' -f 1`; do \\\n  VSERVER_NAME=`lsu $VSERVER name|cut -d ' ' -f 2`\n  echo \"********$VSERVER:$VSERVER_NAME\" >> $OUTPUT_DIR/masses.txt\ndone\n\n# Read core filer name and the new mass number....THESE STEP NEEDS TO BE PERFORMED ON THE NEW CLUSTER AND RUN FROM THE SAME DIR WHERE masses.txt EXISTS.\necho \"N=0;while read -r line; do \\\\\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"ARRAY[\\$N]=\\`echo \\$line|cut -c 9-\\`\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"INTERNAL_NAME=\\`echo \\${ARRAY[\\$N]}|cut -d ':' -f 1\\`\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"ADMINISTRATIVE_NAME=\\`echo \\${ARRAY[\\$N]}|cut -d ':' -f 2\\`\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"if [[ \\$INTERNAL_NAME = \\\"mass\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"NEW_VALUE=\\`averecmd --pretty corefiler.get \\$ADMINISTRATIVE_NAME|grep internalName|cut -d \\\"'\\\" -f 4\\`\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"elif [[ \\$INTERNAL_NAME = \\\"vserver\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"for i in \\`lsu vservers|grep -v _|cut -d ':' -f 1\\`; do \\\\\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"if [[ \\`lsu \\$i|grep \\$ADMINISTRATIVE_NAME\\` ]]; then \\\\\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"NEW_VALUE=\\`lsu \\$i __name|cut -d ' ' -f 2\\`\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"fi\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"done\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"fi\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"let \\\"N=\\$N+1\\\"\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"echo \\$INTERNAL_NAME:\\$ADMINISTRATIVE_NAME:\\$NEW_VALUE >> mass_mapping.txt\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\necho \"done < masses.txt\" >> $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\nchmod 700 $OUTPUT_DIR/2-run_on_new_cluster_mass_mappings.sh\n\necho \"while read line; do \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  NAME=\\`echo \\$line|cut -d ' ' -f 3|cut -d '.' -f 1\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  if [[ \\$NAME != *\\\"mass\\\"* ]] && [[ \\$NAME != \\\"vserver\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    line2=\\`echo \\$line\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  fi\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  if [[ \\$NAME = \\\"cloudmass\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NAME=\\`echo \\$NAME| cut -c 6-\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  fi\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  if [ \\\"\\$line\\\" != \\\"\\$line2\\\" ]; then \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NEW=\\`grep \\\"\\$NAME:\\\" mass_mapping.txt |cut -d ':' -f 3\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    line2=\\`echo \\$line|sed \\\"s/\\$NAME/\\$NEW/\\\"\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  fi\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  if [[ \\$NAME = \\\"cpolicyAdmin\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    tmp=\\`echo \\$NAME|cut -c 13-\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NEW=\\`grep \\\"mass\\$tmp:\\\" mass_mapping.txt |cut -d ':' -f 3\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NEW_ADMIN=cpolicyAdmin\\`echo \\$NEW|cut -c 5-\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    line2=\\`echo \\$line|sed \\\"s/\\$NAME/\\$NEW_ADMIN/\\\"\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  fi\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  if [[ \\$NAME = \\\"cpolicyActive\\\"* ]]; then \\\\\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    tmp=\\`echo \\$NAME|cut -c 14-\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NEW=\\`grep \\\"mass\\$tmp:\\\" mass_mapping.txt |cut -d ':' -f 3\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    NEW_ACTIVE=cpolicyActive\\`echo \\$NEW|cut -c 5-\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"    line2=\\`echo \\$line|sed \\\"s/\\$NAME/\\$NEW_ACTIVE/\\\"\\`\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  fi\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  echo \\$line2 >> 4-run_on_new_cluster_new_custom_settings.sh\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"  line2=''\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"done < original_custom_settings.txt\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\necho \"chmod 700 4-run_on_new_cluster_new_custom_settings.sh\" >> $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\nchmod 700 $OUTPUT_DIR/3-run_on_new_cluster_new_custom_settings.sh\n\necho |tee -a $OUTPUT\necho \"#Certificates\" |tee -a $OUTPUT\necho \"#Nothing to do here since we don't store the certificates\" |tee -a $OUTPUT\n\necho |tee -a $OUTPUT\necho \"#KMIP Servers\" |tee -a $OUTPUT\necho \"#Nothing to do here due to password requirments\" |tee -a $OUTPUT\n\necho |tee -a $OUTPUT\necho \"#Users\" |tee -a $OUTPUT\necho \"#Note: recreated users will all have the their password set to null so please log into the GUI and set them appropriately\" |tee -a $OUTPUT\nN=0;IFS=$'\\n';for i in `averecmd admin.listUsers`; do \\\n  NAME=`echo $i|cut -d \"'\" -f 4`\n  PERMISSION=`echo $i|cut -d \"'\" -f 8`\n  if [ $NAME != \"admin\" ]; then\n#    echo \"averecmd admin.addUser $NAME $PERMISSION tiered2010\" >> $OUTPUT\n    echo \"averecmd admin.addUser $NAME $PERMISSION ''\" >> $OUTPUT\n  fi\ndone\n\necho |tee -a $OUTPUT\necho \"#Login Services\" |tee -a $OUTPUT\necho \"#Nothing to do here since it was addressed when completing the \\\"Directory Services\\\" section\" |tee -a $OUTPUT\necho |tee -a $OUTPUT\n\necho \"#Hidden Alerts\" |tee -a $OUTPUT\necho \"#Nothing to do here since there are no xmlrpc commands to find this\" |tee -a $OUTPUT\necho |tee -a $OUTPUT\n\necho \"####Administration section...DONE####\" |tee -a $OUTPUT\n/support/lib/python/support/data_upload.py -C $OUTPUT_DIR\n", "num_lines": 867}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\nset -x\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n\n    yum install -y nfs-utils\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils\n}\n\nfunction update_hostname() {\n    OCTET3=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)\\.[0-9]*/\\1/'  | sed 's/[^0-9]*//g'`))\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n\n    hostnamectl set-hostname \"vm${OCTET3}_${OCTET4}\"\n}\n\nfunction update_search_domain() {\n    if [[ ! -z \"$SEARCH_DOMAIN\" ]]; then\n        NETWORK_FILE=/etc/sysconfig/network-scripts/ifcfg-eth0\n        if grep --quiet \"DOMAIN=\" $NETWORK_FILE; then\n            sed -i 's/^#\\s*DOMAIN=/DOMAIN=/g' $NETWORK_FILE\n            sed -i \"s/^DOMAIN=.*$/DOMAIN=\\\"${SEARCH_DOMAIN}\\\"/g\"  $NETWORK_FILE\n        else\n            echo \"DOMAIN=\\\"${SEARCH_DOMAIN}\\\"\" >> $NETWORK_FILE\n        fi\n        # restart network to take effect\n        systemctl restart network\n    fi\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n\n    echo \"update hostname\"\n    update_hostname\n\n    echo \"update search domain\"\n    update_search_domain\n\n    echo \"installation complete\"\n\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 65}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\nset -x\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n\n    yum install -y nfs-utils\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils\n}\n\nfunction update_hostname() {\n    OCTET3=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)\\.[0-9]*/\\1/'  | sed 's/[^0-9]*//g'`))\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n\n    hostnamectl set-hostname \"vm${OCTET3}_${OCTET4}\"\n}\n\nfunction update_search_domain() {\n    if [[ ! -z \"$SEARCH_DOMAIN\" ]]; then\n        NETWORK_FILE=/etc/sysconfig/network-scripts/ifcfg-eth0\n        if grep --quiet \"DOMAIN=\" $NETWORK_FILE; then\n            sed -i 's/^#\\s*DOMAIN=/DOMAIN=/g' $NETWORK_FILE\n            sed -i \"s/^DOMAIN=.*$/DOMAIN=\\\"${SEARCH_DOMAIN}\\\"/g\"  $NETWORK_FILE\n        else\n            echo \"DOMAIN=\\\"${SEARCH_DOMAIN}\\\"\" >> $NETWORK_FILE\n        fi\n        # restart network to take effect\n        systemctl restart network\n    fi\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n\n    echo \"update hostname\"\n    update_hostname\n\n    echo \"update search domain\"\n    update_search_domain\n\n    echo \"installation complete\"\n\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 65}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\nset -x\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n\n    yum install -y nfs-utils\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils\n}\n\nfunction update_hostname() {\n    OCTET3=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)\\.[0-9]*/\\1/'  | sed 's/[^0-9]*//g'`))\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n\n    hostnamectl set-hostname \"vm${OCTET3}_${OCTET4}\"\n}\n\nfunction update_search_domain() {\n    if [[ ! -z \"$SEARCH_DOMAIN\" ]]; then\n        NETWORK_FILE=/etc/sysconfig/network-scripts/ifcfg-eth0\n        if grep --quiet \"DOMAIN=\" $NETWORK_FILE; then\n            sed -i 's/^#\\s*DOMAIN=/DOMAIN=/g' $NETWORK_FILE\n            sed -i \"s/^DOMAIN=.*$/DOMAIN=\\\"${SEARCH_DOMAIN}\\\"/g\"  $NETWORK_FILE\n        else\n            echo \"DOMAIN=\\\"${SEARCH_DOMAIN}\\\"\" >> $NETWORK_FILE\n        fi\n        # restart network to take effect\n        systemctl restart network\n    fi\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n\n    echo \"update hostname\"\n    update_hostname\n\n    echo \"update search domain\"\n    update_search_domain\n\n    echo \"installation complete\"\n\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 65}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "function SetServiceAccount {\n  accountName=$1\n  accountPassword=$2\n  if ! id -u $accountName &> /dev/null; then\n    useradd --system --password $accountPassword $accountName\n  fi\n}\n\nfunction GetEncodedValue {\n  echo $1 | base64 -d | jq -r $2\n}\n\nfunction SetFileSystemMount {\n  fileSystemMount=\"$1\"\n  mountDirectory=$(cut -d \" \" -f 2 <<< \"$fileSystemMount\")\n  if [ $(grep -c $mountDirectory /etc/fstab) ]; then\n    mkdir -p $mountDirectory\n    echo \"$fileSystemMount\" >> /etc/fstab\n  fi\n}\n\nfunction EnableClientApp {\n  renderManager=\"$1\"\n  serviceAccountName=$2\n  serviceAccountPassword=$3\n  curl http://data.artist.studio:14000/dist/v1/install | sh\n  if [[ $renderManager == *RoyalRender* ]]; then\n    installType=\"royal-render-client\"\n    rrWorkstation_installer -plugins -service -rrUser $serviceAccountName -rrUserPW $serviceAccountPassword -fwOut 2>&1 | tee $installType-service.log\n    sed -i \"s|BLENDER_PATH|local/blender|\" /RoyalRender/render_apps/_install_paths/Blender.cfg\n  fi\n}\n", "num_lines": 33}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nbinPaths=\"\"\nbinDirectory=\"/usr/local/bin\"\ncd $binDirectory\n\naaaProfile=\"/etc/profile.d/aaa.sh\"\ntouch $aaaProfile\n\necho \"Customize (Start): Image Build Parameters\"\ndnf -y install jq\nbuildConfig=$(echo $buildConfigEncoded | base64 -d)\nmachineType=$(echo $buildConfig | jq -r .machineType)\ngpuProvider=$(echo $buildConfig | jq -r .gpuProvider)\nrenderManager=$(echo $buildConfig | jq -r .renderManager)\nrenderEngines=$(echo $buildConfig | jq -c .renderEngines)\nbinStorageHost=$(echo $buildConfig | jq -r .binStorageHost)\nbinStorageAuth=$(echo $buildConfig | jq -r .binStorageAuth)\nservicePassword=$(echo $buildConfig | jq -r .servicePassword)\necho \"Machine Type: $machineType\"\necho \"GPU Provider: $gpuProvider\"\necho \"Render Manager: $renderManager\"\necho \"Render Engines: $renderEngines\"\necho \"Customize (End): Image Build Parameters\"\n\necho \"Customize (Start): Image Build Platform\"\nsed -i \"s/SELINUX=enforcing/SELINUX=disabled/\" /etc/selinux/config\ndnf -y install gcc gcc-c++ perl elfutils-libelf-devel # openssl-devel bison flex\ninstallFile=\"kernel-devel-4.18.0-372.16.1.el8_6.0.1.x86_64.rpm\"\ndownloadUrl=\"$binStorageHost/Linux/Rocky/$installFile$binStorageAuth\"\ncurl -o $installFile -L $downloadUrl\nrpm -i $installFile\ndnf -y install python3-devel bc git lsof unzip\nif [ $machineType == Workstation ]; then\n  dnf -y group install Workstation\n  dnf -y module install nodejs:18\nfi\n\nversionInfo=\"3.26.4\"\ninstallType=\"cmake\"\ninstallFile=\"cmake-$versionInfo-linux-x86_64.sh\"\ndownloadUrl=\"https://github.com/Kitware/CMake/releases/download/v$versionInfo/cmake-$versionInfo-linux-x86_64.sh\"\ncurl -o $installFile -L $downloadUrl\nchmod +x $installFile\nmkdir -p $installType\n./$installFile --skip-license --prefix=$installType 2>&1 | tee $installType.log\nbinPathCMake=\"$binDirectory/$installType/bin\"\nbinPaths=\"$binPaths:$binPathCMake\"\necho \"Customize (End): Image Build Platform\"\n\nif [ \"$gpuProvider\" == NVIDIA ]; then\n  dnf -y install epel-release\n  dnf -y install dkms\n\n  echo \"Customize (Start): NVIDIA GPU (GRID)\"\n  installType=\"nvidia-gpu-grid\"\n  installFile=\"$installType.run\"\n  downloadUrl=\"https://go.microsoft.com/fwlink/?linkid=874272\"\n  curl -o $installFile -L $downloadUrl\n  chmod +x $installFile\n  ./$installFile --silent --dkms 2>&1 | tee $installType.log\n  echo \"Customize (End): NVIDIA GPU (GRID)\"\n\n  echo \"Customize (Start): NVIDIA GPU (CUDA)\"\n  installType=\"nvidia-cuda\"\n  dnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/cuda-rhel8.repo\n  dnf -y module install nvidia-driver:latest-dkms 2>&1 | tee $installType-dkms.log\n  dnf -y install cuda 2>&1 | tee $installType.log\n  echo \"Customize (End): NVIDIA GPU (CUDA)\"\n\n  echo \"Customize (Start): NVIDIA OptiX\"\n  dnf -y install mesa-libGL\n  dnf -y install mesa-libGL-devel\n  dnf -y install libXrandr-devel\n  dnf -y install libXinerama-devel\n  dnf -y install libXcursor-devel\n  versionInfo=\"7.7.0\"\n  installType=\"nvidia-optix\"\n  installFile=\"NVIDIA-OptiX-SDK-$versionInfo-linux64-x86_64.sh\"\n  downloadUrl=\"$binStorageHost/NVIDIA/OptiX/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  chmod +x $installFile\n  mkdir -p $installType\n  ./$installFile --skip-license --prefix=$installType 2>&1 | tee $installType.log\n  buildDirectory=\"$binDirectory/$installType/build\"\n  mkdir -p $buildDirectory\n  $binPathCMake/cmake -B $buildDirectory -S $binDirectory/$installType/SDK 2>&1 | tee $installType-cmake.log\n  make -C $buildDirectory 2>&1 | tee $installType-make.log\n  binPaths=\"$binPaths:$buildDirectory/bin\"\n  echo \"Customize (End): NVIDIA OptiX\"\nfi\n\nif [[ $renderEngines == *Maya* ]]; then\n  echo \"Customize (Start): Maya\"\n  dnf -y install mesa-libGL\n  dnf -y install mesa-libGLU\n  dnf -y install alsa-lib\n  dnf -y install libXxf86vm\n  dnf -y install libXmu\n  dnf -y install libXpm\n  dnf -y install libnsl\n  dnf -y install gtk3\n  versionInfo=\"2024_0_1\"\n  installType=\"autodesk-maya\"\n  installFile=\"Autodesk_Maya_${versionInfo}_Update_Linux_64bit.tgz\"\n  downloadUrl=\"$binStorageHost/Maya/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  mkdir -p $installType\n  tar -xzf $installFile -C $installType\n  ./$installType/Setup --silent 2>&1 | tee $installType.log\n  binPaths=\"$binPaths:/usr/autodesk/maya/bin\"\n  echo \"Customize (End): Maya\"\nfi\n\nif [[ $renderEngines == *PBRT* ]]; then\n  echo \"Customize (Start): PBRT v3\"\n  versionInfo=\"v3\"\n  installType=\"pbrt-$versionInfo\"\n  installPath=\"/usr/local/pbrt\"\n  installPathV3=\"$installPath/$versionInfo\"\n  git clone --recursive https://github.com/mmp/$installType.git 2>&1 | tee $installType-git.log\n  mkdir -p $installPathV3\n  $binPathCMake/cmake -B $installPathV3 -S $binDirectory/$installType 2>&1 | tee $installType-cmake.log\n  make -C $installPathV3 2>&1 | tee $installType-make.log\n  ln -s $installPathV3/pbrt $installPath/pbrt3\n  echo \"Customize (End): PBRT v3\"\n\n  echo \"Customize (Start): PBRT v4\"\n  dnf -y install mesa-libGL-devel\n  dnf -y install libXrandr-devel\n  dnf -y install libXinerama-devel\n  dnf -y install libXcursor-devel\n  dnf -y install libXi-devel\n  versionInfo=\"v4\"\n  installType=\"pbrt-$versionInfo\"\n  installPathV4=\"$installPath/$versionInfo\"\n  git clone --recursive https://github.com/mmp/$installType.git 2>&1 | tee $installType-git.log\n  mkdir -p $installPathV4\n  $binPathCMake/cmake -B $installPathV4 -S $binDirectory/$installType 2>&1 | tee $installType-cmake.log\n  make -C $installPathV4 2>&1 | tee $installType-make.log\n  ln -s $installPathV4/pbrt $installPath/pbrt4\n  echo \"Customize (End): PBRT v4\"\n\n  binPaths=\"$binPaths:$installPath\"\nfi\n\nif [[ $renderEngines == *Houdini* ]]; then\n  echo \"Customize (Start): Houdini\"\n  dnf -y install mesa-libGL\n  dnf -y install libXcomposite\n  dnf -y install libXdamage\n  dnf -y install libXrandr\n  dnf -y install libXcursor\n  dnf -y install libXi\n  dnf -y install libXtst\n  dnf -y install libXScrnSaver\n  dnf -y install alsa-lib\n  dnf -y install libnsl\n  dnf -y install avahi\n  versionInfo=\"19.5.569\"\n  versionEULA=\"2021-10-13\"\n  installType=\"houdini\"\n  installFile=\"$installType-$versionInfo-linux_x86_64_gcc9.3.tar.gz\"\n  downloadUrl=\"$binStorageHost/Houdini/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  tar -xzf $installFile\n  [[ $machineType == Workstation ]] && desktopMenus=--install-menus || desktopMenus=--no-install-menus\n  [[ $renderEngines == *Maya* ]] && mayaPlugIn=--install-engine-maya || mayaPlugIn=--no-install-engine-maya\n  [[ $renderEngines == *Unreal* ]] && unrealPlugIn=--install-engine-unreal || unrealPlugIn=--no-install-engine-unreal\n  ./houdini*/houdini.install --auto-install --make-dir --no-install-license --accept-EULA $versionEULA $desktopMenus $mayaPlugIn $unrealPlugIn 2>&1 | tee $installType.log\n  binPaths=\"$binPaths:/opt/hfs$versionInfo/bin\"\n  echo \"Customize (End): Houdini\"\nfi\n\nif [[ $renderEngines == *Blender* ]]; then\n  echo \"Customize (Start): Blender\"\n  dnf -y install mesa-libGL\n  dnf -y install libXxf86vm\n  dnf -y install libXfixes\n  dnf -y install libXi\n  dnf -y install libSM\n  versionInfo=\"3.6.0\"\n  versionType=\"linux-x64\"\n  installType=\"blender\"\n  installPath=\"/usr/local/$installType\"\n  installFile=\"$installType-$versionInfo-$versionType.tar.xz\"\n  downloadUrl=\"$binStorageHost/Blender/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  tar -xJf $installFile\n  mkdir -p $installPath\n  mv $installType-$versionInfo-$versionType/* $installPath\n  binPaths=\"$binPaths:$installPath\"\n  echo \"Customize (End): Blender\"\nfi\n\nif [[ $renderEngines == *Unreal* ]] || [[ $renderEngines == *Unreal+PixelStream* ]]; then\n  echo \"Customize (Start): Unreal Engine Setup\"\n  dnf -y install libicu\n  versionInfo=\"5.2.0\"\n  installType=\"unreal-engine\"\n  installPath=\"/usr/local/unreal\"\n  installFile=\"UnrealEngine-$versionInfo-release.tar.gz\"\n  downloadUrl=\"$binStorageHost/Unreal/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  tar -xzf $installFile\n  mkdir -p $installPath\n  mv UnrealEngine-$versionInfo-release/* $installPath\n  $installPath/Setup.sh 2>&1 | tee $installType-setup.log\n  echo \"Customize (End): Unreal Engine Setup\"\n\n  echo \"Customize (Start): Unreal Project Files Generate\"\n  $installPath/GenerateProjectFiles.sh 2>&1 | tee unreal-project-files-generate.log\n  echo \"Customize (End): Unreal Project Files Generate\"\n\n  echo \"Customize (Start): Unreal Engine Build\"\n  make -C $installPath 2>&1 | tee $installType-make.log\n  echo \"Customize (End): Unreal Engine Build\"\n\n  if [[ $renderEngines == *Unreal+PixelStream* ]]; then\n    echo \"Customize (Start): Unreal Pixel Streaming\"\n    dnf -y install coturn\n    unrealVersion=$versionInfo\n    versionInfo=\"UE5.2-0.6.2\"\n    installType=\"unreal-stream\"\n    installFile=\"PixelStreamingInfrastructure-$versionInfo.tar.gz\"\n    downloadUrl=\"$binStorageHost/Unreal/$unrealVersion/$installFile$binStorageAuth\"\n    curl -o $installFile -L $downloadUrl\n    tar -xzf $installFile\n    installFile=\"PixelStreamingInfrastructure-$versionInfo/SignallingWebServer/platform_scripts/bash/setup.sh\"\n    chmod +x $installFile\n    ./$installFile 2>&1 | tee $installType-signalling.log\n    installFile=\"PixelStreamingInfrastructure-$versionInfo/Matchmaker/platform_scripts/bash/setup.sh\"\n    chmod +x $installFile\n    ./$installFile 2>&1 | tee $installType-matchmaker.log\n    installFile=\"PixelStreamingInfrastructure-$versionInfo/SFU/platform_scripts/bash/setup.sh\"\n    chmod +x $installFile\n    ./$installFile 2>&1 | tee $installType-sfu.log\n    echo \"Customize (End): Unreal Pixel Streaming\"\n  fi\n\n  binPaths=\"$binPaths:$installPath/Engine/Binaries/Linux\"\nfi\n\nif [[ $renderEngines == *MoonRay* ]]; then\n  echo \"Customize (Start): MoonRay\"\n  dnf -y install mesa-libGL\n  dnf -y install mesa-libGL-devel\n  dnf -y --enablerepo=devel install libcgroup-devel\n  dnf -y --enablerepo=devel install giflib-devel\n  dnf -y install libtiff-devel\n  dnf -y install libjpeg-devel\n  dnf -y install libuuid-devel\n  dnf -y install libcurl-devel\n  dnf -y install openssl-devel\n  dnf -y install libmng-devel\n  dnf -y install libatomic\n  dnf -y install patch\n  dnf -y install bison\n  dnf -y install flex\n  if [ $machineType == Workstation ]; then\n    dnf -y install qt5-qtbase-devel\n    dnf -y install qt5-qtscript-devel\n  fi\n\n  git clone --recurse-submodules https://github.com/dreamworksanimation/openmoonray.git /openmoonray\n\n  mkdir -p /installs/bin\n  mkdir -p /installs/lib\n  mkdir -p /installs/include\n  mkdir -p /installs/openmoonray\n\n  dnf -y install gcc-toolset-9 python2\n  source /opt/rh/gcc-toolset-9/enable\n  ln -s /bin/python2 /bin/python\n\n  mkdir -p /openmoonray/build\n  cd /openmoonray/build\n  ln -s /openmoonray/building /building\n  installType=\"openmoonray-prereq\"\n  $binPathCMake/cmake ../building 2>&1 | tee $installType.log\n  $binPathCMake/cmake --build . -- -j 64 2>&1 | tee $installType-build.log\n\n  cd /openmoonray\n  installType=\"openmoonray\"\n  [[ \"$gpuProvider\" == NVIDIA ]] && useCUDA=YES || useCUDA=NO\n  [[ $machineType == Workstation ]] && uiApps=YES || uiApps=NO\n  $binPathCMake/cmake --preset container-release -D MOONRAY_USE_CUDA=$useCUDA -D BUILD_QT_APPS=$uiApps 2>&1 | tee $installType-preset.log\n  $binPathCMake/cmake --build --preset container-release -- -j 64 2>&1 | tee $installType-preset-build.log\n  $binPathCMake/cmake --install /build --prefix /installs/openmoonray 2>&1 | tee $installType-install.log\n  echo \"source /installs/openmoonray/scripts/setup.sh\" >> $aaaProfile\n  cd $binDirectory\n  echo \"Customize (End): MoonRay\"\nfi\n\nif [ $machineType == Scheduler ]; then\n  echo \"Customize (Start): Azure CLI\"\n  installType=\"azure-cli\"\n  rpm --import https://packages.microsoft.com/keys/microsoft.asc\n  dnf -y install https://packages.microsoft.com/config/rhel/8/packages-microsoft-prod.rpm\n  dnf -y install $installType 2>&1 | tee $installType.log\n  echo \"Customize (End): Azure CLI\"\n\n  if [[ $renderManager == *Deadline* || $renderManager == *RoyalRender* ]]; then\n    echo \"Customize (Start): NFS Server\"\n    systemctl --now enable nfs-server\n    echo \"Customize (End): NFS Server\"\n  fi\nfi\n\nif [[ $renderManager == *Deadline* ]]; then\n  versionInfo=\"10.2.1.0\"\n  installRoot=\"/Deadline\"\n  serverMount=\"/DeadlineServer\"\n  databaseHost=$(hostname)\n  databasePort=27017\n  databaseUser=\"dbService\"\n  databaseName=\"deadline10db\"\n  binPathScheduler=\"$installRoot/bin\"\n\n  echo \"Customize (Start): Deadline Download\"\n  installFile=\"Deadline-$versionInfo-linux-installers.tar\"\n  installPath=$(echo ${installFile%.tar})\n  downloadUrl=\"$binStorageHost/Deadline/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  mkdir -p $installPath\n  tar -xzf $installFile -C $installPath\n  echo \"Customize (End): Deadline Download\"\n\n  if [ $machineType == Scheduler ]; then\n    echo \"Customize (Start): Mongo DB Service\"\n    repoPath=\"/etc/yum.repos.d/mongodb.repo\"\n    echo \"[mongodb-org-4.4]\" > $repoPath\n    echo \"name=MongoDB 4.4\" >> $repoPath\n    echo \"baseurl=https://repo.mongodb.org/yum/redhat/8/mongodb-org/4.4/x86_64/\" >> $repoPath\n    echo \"gpgcheck=1\" >> $repoPath\n    echo \"enabled=1\" >> $repoPath\n    echo \"gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc\" >> $repoPath\n    dnf -y install mongodb-org\n    configFile=\"/etc/mongod.conf\"\n    sed -i \"s/bindIp: 127.0.0.1/bindIp: 0.0.0.0/\" $configFile\n    sed -i \"/bindIp: 0.0.0.0/a\\  tls:\" $configFile\n    sed -i \"/tls:/a\\    mode: disabled\" $configFile\n    systemctl --now enable mongod\n    sleep 10s\n    echo \"Customize (End): Mongo DB Service\"\n\n    echo \"Customize (Start): Mongo DB User\"\n    installType=\"mongo-create-user\"\n    createUserScript=\"$installType.js\"\n    echo \"db = db.getSiblingDB(\\\"$databaseName\\\");\" > $createUserScript\n    echo \"db.createUser({\" >> $createUserScript\n    echo \"user: \\\"$databaseUser\\\",\" >> $createUserScript\n    echo \"pwd: \\\"$servicePassword\\\",\" >> $createUserScript\n    echo \"roles: [\" >> $createUserScript\n    echo \"{ role: \\\"dbOwner\\\", db: \\\"$databaseName\\\" }\" >> $createUserScript\n    echo \"]})\" >> $createUserScript\n    mongo $createUserScript 2>&1 | tee $installType.log\n    if grep --silent --ignore-case exception $installType.log; then\n      exit 1\n    fi\n    echo \"Customize (End): Mongo DB User\"\n\n    echo \"Customize (Start): Deadline Server\"\n    export DB_PASSWORD=$servicePassword\n    installFile=\"DeadlineRepository-$versionInfo-linux-x64-installer.run\"\n    $installPath/$installFile --mode unattended --dbLicenseAcceptance accept --prefix $installRoot --dbhost $databaseHost --dbport $databasePort --dbname $databaseName --installmongodb false --dbauth true --dbuser $databaseUser --dbpassword env:DB_PASSWORD\n    mv /tmp/installbuilder_installer.log $binDirectory/deadline-repository.log\n    echo \"$installRoot *(rw,sync,no_subtree_check,no_root_squash)\" >> /etc/exports\n    exportfs -r\n    echo \"Customize (End): Deadline Server\"\n  fi\n\n  echo \"Customize (Start): Deadline Client\"\n  installFile=\"DeadlineClient-$versionInfo-linux-x64-installer.run\"\n  installArgs=\"--mode unattended --prefix $installRoot --repositorydir $serverMount\"\n  if [ $machineType == Scheduler ]; then\n    installArgs=\"$installArgs --slavestartup false --launcherdaemon false\"\n  else\n    [ $machineType == Farm ] && workerStartup=true || workerStartup=false\n    installArgs=\"$installArgs --slavestartup $workerStartup --launcherdaemon true\"\n  fi\n  $installPath/$installFile $installArgs\n  cp /tmp/installbuilder_installer.log $binDirectory/deadline-client.log\n  echo \"$binPathScheduler/deadlinecommand -StoreDatabaseCredentials $databaseUser $servicePassword\" >> $aaaProfile\n  echo \"Customize (End): Deadline Client\"\n\n  binPaths=\"$binPaths:$binPathScheduler\"\nfi\n\nif [[ $renderManager == *RoyalRender* ]]; then\n  versionInfo=\"9.0.06\"\n  installRoot=\"/RoyalRender\"\n  binPathScheduler=\"$installRoot/bin/lx64\"\n\n  echo \"Customize (Start): Royal Render Download\"\n  installFile=\"RoyalRender__${versionInfo}__installer.zip\"\n  downloadUrl=\"$binStorageHost/RoyalRender/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  unzip -q $installFile\n  echo \"Customize (End): Royal Render Download\"\n\n  dnf -y install xcb-util-wm\n  dnf -y install xcb-util-image\n  dnf -y install xcb-util-keysyms\n  dnf -y install xcb-util-renderutil\n  dnf -y install libxkbcommon-x11\n  dnf -y install qt5-qtbase\n  if [ $machineType == Scheduler ]; then\n    echo \"Customize (Start): Royal Render Server\"\n    installPath=\"RoyalRender*\"\n    installFile=\"rrSetup_linux\"\n    chmod +x ./$installPath/$installFile\n    mkdir -p $installRoot\n    ./$installPath/$installFile -console -rrRoot $installRoot 2>&1 | tee royal-render.log\n    echo \"$installRoot *(rw,sync,no_subtree_check,no_root_squash)\" >> /etc/exports\n    exportfs -r\n    echo \"Customize (End): Royal Render Server\"\n  fi\n\n  binPaths=\"$binPaths:$binPathScheduler\"\nfi\n\nif [[ $renderManager == *Qube* ]]; then\n  versionInfo=\"8.0-0\"\n  installRoot=\"/usr/local/pfx/qube\"\n  binPathScheduler=\"$installRoot/bin\"\n\n  echo \"Customize (Start): Qube Core\"\n  dnf -y install perl\n  dnf -y install xinetd\n  installType=\"qube-core\"\n  installFile=\"$installType-$versionInfo.CENTOS_8.2.x86_64.rpm\"\n  downloadUrl=\"$binStorageHost/Qube/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  rpm -i $installType-*.rpm 2>&1 | tee $installType.log\n  echo \"Customize (End): Qube Core\"\n\n  if [ $machineType == Scheduler ]; then\n    echo \"Customize (Start): Qube Supervisor\"\n    installType=\"qube-supervisor\"\n    installFile=\"$installType-${versionInfo}.CENTOS_8.2.x86_64.rpm\"\n    downloadUrl=\"$binStorageHost/Qube/$versionInfo/$installFile$binStorageAuth\"\n    curl -o $installFile -L $downloadUrl\n    rpm -i $installType-*.rpm 2>&1 | tee $installType.log\n    echo \"Customize (End): Qube Supervisor\"\n\n    echo \"Customize (Start): Qube Data Relay Agent (DRA)\"\n    installType=\"qube-dra\"\n    installFile=\"$installType-$versionInfo.CENTOS_8.2.x86_64.rpm\"\n    downloadUrl=\"$binStorageHost/Qube/$versionInfo/$installFile$binStorageAuth\"\n    curl -o $installFile -L $downloadUrl\n    rpm -i $installType-*.rpm 2>&1 | tee $installType.log\n    echo \"Customize (End): Qube Data Relay Agent (DRA)\"\n  else\n    echo \"Customize (Start): Qube Worker\"\n    installType=\"qube-worker\"\n    installFile=\"$installType-$versionInfo.CENTOS_8.2.x86_64.rpm\"\n    downloadUrl=\"$binStorageHost/Qube/$versionInfo/$installFile$binStorageAuth\"\n    curl -o $installFile -L $downloadUrl\n    rpm -i $installType-*.rpm 2>&1 | tee $installType.log\n    echo \"Customize (End): Qube Worker\"\n\n    echo \"Customize (Start): Qube Client\"\n    installType=\"qube-client\"\n    installFile=\"$installType-$versionInfo.CENTOS_8.2.x86_64.rpm\"\n    downloadUrl=\"$binStorageHost/Qube/$versionInfo/$installFile$binStorageAuth\"\n    curl -o $installFile -L $downloadUrl\n    rpm -i $installType-*.rpm 2>&1 | tee $installType.log\n    echo \"Customize (End): Qube Client\"\n\n    configFile=\"/etc/qb.conf\"\n    sed -i \"s/#qb_supervisor =/qb_supervisor = scheduler.artist.studio/\" $configFile\n    sed -i \"s/#worker_cpus = 0/worker_cpus = 1/\" $configFile\n  fi\n\n  binPaths=\"$binPaths:$binPathScheduler:$installRoot/sbin\"\nfi\n\nif [ $machineType == Workstation ]; then\n  echo \"Customize (Start): Teradici PCoIP\"\n  versionInfo=\"23.04.1\"\n  [ \"$gpuProvider\" == \"\" ] && installType=pcoip-agent-standard || installType=pcoip-agent-graphics\n  installFile=\"pcoip-agent-offline-rocky8.6_$versionInfo-1.el8.x86_64.tar.gz\"\n  downloadUrl=\"$binStorageHost/Teradici/$versionInfo/$installFile$binStorageAuth\"\n  curl -o $installFile -L $downloadUrl\n  mkdir -p $installType\n  tar -xzf $installFile -C $installType\n  cd $installType\n  ./install-pcoip-agent.sh $installType usb-vhci 2>&1 | tee ../$installType.log\n  cd $binDirectory\n  echo \"Customize (End): Teradici PCoIP\"\nfi\n\necho \"PATH=$PATH$binPaths\" >> $aaaProfile\n", "num_lines": 495}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nscheduledEvents=$(curl -H Metadata:true \"http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01\" | jq -c .Events)\nfor scheduledEvent in $(echo $scheduledEvents | jq -r '.[] | @base64'); do\n  _jq() {\n    echo $scheduledEvent | base64 -d | jq -r $1\n  }\n  eventType=$(_jq .EventType)\n\n  if [[ $eventType == Preempt || $eventType == Terminate ]]; then\n    eventScope=$(_jq .Resources[0])\n    instanceName=$(curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/name?api-version=2021-05-01&format=text\")\n\n    if [ $eventScope == $instanceName ]; then\n      if [[ $renderManager == *Deadline* ]]; then\n        deadlineworker -shutdown\n        deadlinecommand -DeleteSlave $(hostname)\n      fi\n      if [[ $renderManager == *RoyalRender* ]]; then\n        :\n      fi\n      if [[ $renderManager == *Qube* ]]; then\n        qbadmin worker --remove $(hostname)\n      fi\n    fi\n  fi\ndone\n", "num_lines": 28}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\ncd ${binDirectory}\n\nif [ \"${wekaClusterName}\" != \"\" ]; then\n  volumeLabel=\"weka-iosw\"\n  installDisk=\"/dev/$(lsblk | grep ${wekaDataDiskSize}G | awk '{print $1}')\"\n  mkfs.ext4 -L $volumeLabel $installDisk 2>&1 | tee weka-mkfs.log\n  installPath=\"/opt/weka\"\n  mkdir -p $installPath\n  echo \"LABEL=$volumeLabel $installPath ext4 defaults 0 2\" >> /etc/fstab\n  mount -a\n\n  curl https://${wekaApiToken}@get.weka.io/dist/v1/install/${wekaVersion}/${wekaVersion} | sh\n\n  coreIdsScript=${wekaCoreIdsScript}\n  echo 'coreCountDrives=$(echo $machineSpec | jq -r .coreDrives)' > $coreIdsScript\n  echo 'coreCountCompute=$(echo $machineSpec | jq -r .coreCompute)' >> $coreIdsScript\n  echo 'coreCountFrontend=$(echo $machineSpec | jq -r .coreFrontend)' >> $coreIdsScript\n  echo 'computeMemory=$(echo $machineSpec | jq -r .computeMemory)' >> $coreIdsScript\n  echo '' >> $coreIdsScript\n  echo 'coreIds=\"$(cat /sys/devices/system/cpu/cpu*/topology/thread_siblings_list | cut --delimiter - --fields 1 | sort --unique | tr \\\\n -)\"' >> $coreIdsScript\n  echo 'coreIds=\"$${coreIds:2}\"' >> $coreIdsScript\n  echo 'IFS=\"-\" read -a coreIds <<< \"$coreIds\"' >> $coreIdsScript\n  echo '' >> $coreIdsScript\n  echo 'function GetCoreIds {' >> $coreIdsScript\n  echo '  coreCount=$1' >> $coreIdsScript\n  echo '  coreIdStart=$2' >> $coreIdsScript\n  echo '  coreIdEnd=$(($coreIdStart + $coreCount))' >> $coreIdsScript\n  echo '  containerCoreIds=\"\"' >> $coreIdsScript\n  echo '  for (( i=$coreIdStart; i<$coreIdEnd; i++ )); do' >> $coreIdsScript\n  echo '    if [ \"$containerCoreIds\" != \"\" ]; then' >> $coreIdsScript\n  echo '      containerCoreIds=\"$containerCoreIds,\"' >> $coreIdsScript\n  echo '    fi' >> $coreIdsScript\n  echo '    containerCoreIds=\"$containerCoreIds$${coreIds[i]}\"' >> $coreIdsScript\n  echo '  done' >> $coreIdsScript\n  echo '  echo $containerCoreIds' >> $coreIdsScript\n  echo '}' >> $coreIdsScript\n  echo '' >> $coreIdsScript\n  echo 'coreIdsDrives=$(GetCoreIds $coreCountDrives 0)' >> $coreIdsScript\n  echo 'coreIdsCompute=$(GetCoreIds $coreCountCompute $coreCountDrives)' >> $coreIdsScript\n  echo 'coreIdsFrontend=$(GetCoreIds $coreCountFrontend $(($coreCountDrives + $coreCountCompute)))' >> $coreIdsScript\n\n  machineSpec='${wekaMachineSpec}'\n  source $coreIdsScript\n\n  driveDisksScript=${wekaDriveDisksScript}\n  echo 'nvmeDisks=/dev/nvme0n1' > $driveDisksScript\n  echo 'for (( d=1; d<$(echo $machineSpec | jq -r .nvmeDisks); d++ )); do' >> $driveDisksScript\n  echo '  nvmeDisks=\"$nvmeDisks /dev/nvme$(echo $d)n1\"' >> $driveDisksScript\n  echo 'done' >> $driveDisksScript\n\n  fileSystemScript=${wekaFileSystemScript}\n  echo \"fileSystemName=${wekaFileSystemName}\" > $fileSystemScript\n  echo 'fileSystemDriveBytes=$(weka status --json | jq -r .capacity.total_bytes)' >> $fileSystemScript\n  echo 'fileSystemTotalBytes=$(echo \"$fileSystemDriveBytes * 100 / (100 - ${wekaObjectTierPercent})\" | bc)' >> $fileSystemScript\n\n  containerName=\"default\"\n  weka local stop --force $containerName\n  weka local rm --force $containerName\n\n  az login --identity\n  failureDomain=$(hostname)\n  drivesContainerName=drives0\n  vmScaleSetState=$(az vmss show --resource-group ${wekaResourceGroupName} --name ${wekaClusterName} --query provisioningState --output tsv)\n  if [ \"$vmScaleSetState\" == Updating ]; then\n    joinIps=$(az vmss nic list --resource-group ${wekaResourceGroupName} --vmss-name ${wekaClusterName} --query [].ipConfigurations[0].privateIPAddress --output tsv | tr \\\\n ',')\n    weka local setup container --name $drivesContainerName --base-port 14000 --failure-domain $failureDomain --join-ips $${joinIps::-1} --cores $coreCountDrives --drives-dedicated-cores $coreCountDrives --core-ids $coreIdsDrives --dedicate --no-frontends &> weka-container-setup-$drivesContainerName.log\n    weka local setup container --name compute0 --base-port 15000 --failure-domain $failureDomain --join-ips $${joinIps::-1} --cores $coreCountCompute --compute-dedicated-cores $coreCountCompute --core-ids $coreIdsCompute --dedicate --memory $computeMemory --no-frontends &> weka-container-setup-compute0.log\n    weka local setup container --name frontend0 --base-port 16000 --failure-domain $failureDomain --join-ips $${joinIps::-1} --cores $coreCountFrontend --frontend-dedicated-cores $coreCountFrontend --core-ids $coreIdsFrontend --dedicate &> weka-container-setup-frontend0.log\n    weka user login admin ${wekaAdminPassword}\n    source $driveDisksScript\n    containerId=$(weka cluster container --filter container=$drivesContainerName,ips=$(hostname -i) --output id --no-header)\n    weka cluster drive add $containerId $nvmeDisks &> weka-cluster-drive-add.log\n    if [ ${wekaFileSystemAutoScale} == true ]; then\n      source $fileSystemScript\n      weka fs update $fileSystemName --ssd-capacity \"$fileSystemDriveBytes\"B --total-capacity \"$fileSystemTotalBytes\"B &> weka-fs-update.log\n    fi\n    dnsRecordQuery=\"aRecords[?ipv4Address=='$(hostname -i)']\"\n    while [ -z \"$dnsRecordAddress\" ]; do\n      az network private-dns record-set a add-record --resource-group ${dnsResourceGroupName} --zone-name ${dnsZoneName} --record-set-name ${dnsRecordSetName} --ipv4-address $(hostname -i)\n      sleep 5s\n      dnsRecordAddress=$(az network private-dns record-set a show --resource-group ${dnsResourceGroupName} --zone-name ${dnsZoneName} --name ${dnsRecordSetName} --query $dnsRecordQuery --output tsv)\n    done\n  else\n    weka local setup container --name $drivesContainerName --base-port 14000 --failure-domain $failureDomain --cores $coreCountDrives --drives-dedicated-cores $coreCountDrives --core-ids $coreIdsDrives --dedicate --no-frontends &> weka-container-setup-$drivesContainerName.log\n  fi\n\n  if [ $(hostname) == ${wekaClusterName}000000 ]; then\n    systemctl --now enable nfs-server\n    mkdir -p ${binDirectory}/log\n    echo \"${binDirectory}/log *(rw,sync,no_subtree_check,no_root_squash)\" >> /etc/exports\n    exportfs -r\n  fi\n\n  dataFilePath=\"/var/lib/waagent/ovf-env.xml\"\n  dataFileText=$(xmllint --xpath \"//*[local-name()='Environment']/*[local-name()='ProvisioningSection']/*[local-name()='LinuxProvisioningConfigurationSet']/*[local-name()='CustomData']/text()\" $dataFilePath)\n  codeFilePath=\"${binDirectory}/terminate.sh\"\n  echo $dataFileText | base64 -d > $codeFilePath\n  chmod +x $codeFilePath\n\n  if [ ${wekaTerminateNotification.enable} == true ]; then\n    cronFilePath=\"/tmp/crontab\"\n    echo \"* * * * * $codeFilePath\" > $cronFilePath\n    crontab $cronFilePath\n  fi\nfi\n", "num_lines": 108}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nrootHost=${wekaClusterName}000000\n\nlogDirectory=/mnt/log\nif ! mountpoint -q $logDirectory; then\n  mkdir -p $logDirectory\n  mount $rootHost:${binDirectory}/log $logDirectory\nfi\n\nmetadataUrl=\"http://169.254.169.254/metadata\"\neventsUrl=\"$metadataUrl/scheduledevents?api-version=2020-07-01\"\nvmNameUrl=\"$metadataUrl/instance/compute/name?api-version=2021-12-13&format=text\"\n\ninstanceName=$(curl --silent --header Metadata:true $vmNameUrl)\nscheduledEvents=$(curl --silent --header Metadata:true $eventsUrl | jq -c .Events)\n\nfunction GetEncodedValue {\n  echo $scheduledEvent | base64 -d | jq -r $1\n}\n\nfor scheduledEvent in $(echo $scheduledEvents | jq -r '.[] | @base64'); do\n  eventType=$(GetEncodedValue .EventType)\n  eventScope=$(GetEncodedValue .Resources[0])\n\n  if [[ $eventType == Terminate && $eventScope == $instanceName ]]; then\n    az login --identity\n    dnsRecordQuery=\"aRecords[?ipv4Address=='$(hostname -i)']\"\n    dnsRecordAddress=$(az network private-dns record-set a show --resource-group ${dnsResourceGroupName} --zone-name ${dnsZoneName} --name ${dnsRecordSetName} --query $dnsRecordQuery --output tsv)\n    if [ -n \"$dnsRecordAddress\" ]; then\n      az network private-dns record-set a remove-record --resource-group ${dnsResourceGroupName} --zone-name ${dnsZoneName} --record-set-name ${dnsRecordSetName} --ipv4-address $dnsRecordAddress --keep-empty-record-set\n    fi\n\n    weka user login admin ${wekaAdminPassword}\n    instanceName=\"$instanceName-$(date +%T)\"\n\n    drivesRemoved=false\n    driveIds=$(weka cluster drive --filter hostname=$(hostname),status=ACTIVE --output uuid --no-header | tr \\\\n ' ')\n    driveIds=$${driveIds::-1}\n    if [ \"$driveIds\" != \"\" ]; then\n      weka cluster drive deactivate --force $driveIds &> $logDirectory/$instanceName-weka-cluster-drive-deactivate.log\n\n      read -a driveIds <<< \"$driveIds\"\n      for (( i=0; i<$${#driveIds[@]}; i++ )); do\n        driveId=$${driveIds[i]}\n        while\n          driveStatus=$(weka cluster drive --filter uuid=$driveId --output status --no-header)\n          [ $driveStatus != INACTIVE ]\n        do\n          sleep 3\n        done\n        weka cluster drive remove --force $driveId &> $logDirectory/$instanceName-weka-cluster-drive-remove-$driveId.log\n      done\n      drivesRemoved=true\n    fi\n\n    containersRemoved=false\n    containerIds=$(weka cluster container --filter ips=$(hostname -i),status=UP --output id --no-header | tr \\\\n ' ')\n    containerIds=$${containerIds::-1}\n    if [ \"$containerIds\" != \"\" ]; then\n      weka cluster container deactivate $containerIds &> $logDirectory/$instanceName-weka-cluster-container-deactivate.log\n\n      read -a containerIds <<< \"$containerIds\"\n      for (( i=0; i<$${#containerIds[@]}; i++ )); do\n        containerId=$${containerIds[i]}\n        while\n          containerStatus=$(weka cluster container --HOST $rootHost --filter id=$containerId --output status --no-header)\n          [ $containerStatus != INACTIVE ]\n        do\n          sleep 3\n        done\n        weka cluster container remove $containerId --HOST $rootHost &> $logDirectory/$instanceName-weka-cluster-container-remove-$containerId.log\n      done\n      containersRemoved=true\n    fi\n\n    if [[ $drivesRemoved == true && $containersRemoved == true ]]; then\n      eventId=$(GetEncodedValue .EventId)\n      eventData=\"{\\\"StartRequests\\\":[{\\\"EventId\\\":\\\"$eventId\\\"}]}\"\n      curl --silent --request POST --header Metadata:true --header Content-Type:application/json --data $eventData $eventsUrl &> $logDirectory/$instanceName-event-$eventId.log\n    fi\n  fi\ndone\n", "num_lines": 84}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nsource /etc/profile.d/aaa.sh\n\nbinDirectory=\"/usr/local/bin\"\ncd $binDirectory\n\nuseradd --system --password ${serviceAccountPassword} ${serviceAccountName}\n\nif [[ ${renderManager} == *RoyalRender* ]]; then\n  installType=\"royal-render-server\"\n  rrServerconsole -initAndClose 2>&1 | tee $installType-init.log\n  rrWorkstation_installer -serviceServer -rrUser ${serviceAccountName} -rrUserPW ${serviceAccountPassword} 2>&1 | tee $installType-service.log\nfi\n\nif [ \"${qubeLicense.userName}\" != \"\" ]; then\n  configFilePath=\"/etc/qube/dra.conf\"\n  sed -i \"s/# mls_user =/mls_user = ${qubeLicense.userName}/\" $configFilePath\n  sed -i \"s/# mls_password =/mls_password = ${qubeLicense.userPassword}/\" $configFilePath\n  systemctl restart dra.service\nfi\n\nserviceFile=\"aaaAutoScaler\"\ndataFilePath=\"/var/lib/waagent/ovf-env.xml\"\ndataFileText=$(xmllint --xpath \"//*[local-name()='Environment']/*[local-name()='ProvisioningSection']/*[local-name()='LinuxProvisioningConfigurationSet']/*[local-name()='CustomData']/text()\" $dataFilePath)\ncodeFilePath=\"$binDirectory/$serviceFile.sh\"\necho $dataFileText | base64 -d > $codeFilePath\nchmod +x $codeFilePath\n\nserviceName=\"AAA Auto Scaler\"\nservicePath=\"/etc/systemd/system/$serviceFile.service\"\necho \"[Unit]\" > $servicePath\necho \"Description=$serviceName Service\" >> $servicePath\necho \"After=network-online.target\" >> $servicePath\necho \"\" >> $servicePath\necho \"[Service]\" >> $servicePath\necho \"Environment=renderManager=${renderManager}\" >> $servicePath\necho \"Environment=resourceGroupName=${autoScale.resourceGroupName}\" >> $servicePath\necho \"Environment=scaleSetName=${autoScale.scaleSetName}\" >> $servicePath\necho \"Environment=scaleSetMachineCountMax=${autoScale.scaleSetMachineCountMax}\" >> $servicePath\necho \"Environment=jobWaitThresholdSeconds=${autoScale.jobWaitThresholdSeconds}\" >> $servicePath\necho \"Environment=workerIdleDeleteSeconds=${autoScale.workerIdleDeleteSeconds}\" >> $servicePath\necho \"ExecStart=/bin/bash $codeFilePath\" >> $servicePath\necho \"\" >> $servicePath\n\ntimerPath=\"/etc/systemd/system/$serviceFile.timer\"\necho \"[Unit]\" > $timerPath\necho \"Description=$serviceName Timer\" >> $timerPath\necho \"\" >> $timerPath\necho \"[Timer]\" >> $timerPath\necho \"OnUnitActiveSec=${autoScale.detectionIntervalSeconds}\" >> $timerPath\necho \"AccuracySec=1us\" >> $timerPath\necho \"\" >> $timerPath\necho \"[Install]\" >> $timerPath\necho \"WantedBy=timers.target\" >> $timerPath\n\nif [ ${autoScale.enable} == true ]; then\n  systemctl --now enable $serviceFile\nfi\n", "num_lines": 60}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\naz login --identity\n\nqueuedTasks=0\nif [[ $renderManager == *Deadline* ]]; then\n  activeJobIds=$(deadlinecommand -GetJobIdsFilter Status=Active)\n  for jobId in $(echo $activeJobIds); do\n    jobDetails=$(deadlinecommand -GetJobDetails $jobId)\n    jobProperty=\"SubmitDate=\"\n    jobSubmitDate=$(echo \"$jobDetails\" | grep $jobProperty)\n    jobSubmitDate=$(echo $${jobSubmitDate#$jobProperty})\n    jobWaitSecondsStart=$(date -u +%s --date=\"$jobSubmitDate\")\n    jobWaitSecondsEnd=$(date -u +%s)\n    jobWaitSeconds=$(($jobWaitSecondsEnd - $jobWaitSecondsStart))\n    if [ $jobWaitSeconds -gt $jobWaitThresholdSeconds ]; then\n      taskIds=$(deadlinecommand -GetJobTaskIds $jobId)\n      for taskId in $(echo $taskIds); do\n        task=$(deadlinecommand -GetJobTask $jobId $taskId)\n        taskStatus=$(echo \"$task\" | grep \"TaskStatus=\")\n        taskStatus=$(echo $${taskStatus#*=})\n        if [ $taskStatus == Queued ]; then\n          ((queuedTasks++))\n        fi\n      done\n    fi\n  done\nfi\n\nif [ $queuedTasks -gt 0 ]; then # Scale Up\n  scaleSetNodeCount=$(az vmss show --resource-group $resourceGroupName --name $scaleSetName --query \"sku.capacity\")\n  if [[ $scaleSetMachineCountMax > 0 && $(($scaleSetNodeCount + $queuedTasks)) > $scaleSetMachineCountMax ]]; then\n    scaleSetNodeCount=$scaleSetMachineCountMax\n  else\n    scaleSetNodeCount=$(($farmNodeCount + $queuedTasks))\n  fi\n  az vmss scale --resource-group $resourceGroupName --name $scaleSetName --new-capacity $scaleSetNodeCount\nelse # Scale Down\n  if [[ $renderManager == *Deadline* ]]; then\n    workerNames=$(deadlinecommand -GetSlaveNames)\n    for workerName in $(echo $workerNames); do\n      workerState=$(deadlinecommand -GetSlaveInfo $workerName SlaveState)\n      if [ $workerState == Idle ]; then\n        worker=$(deadlinecommand -GetSlave $workerName)\n        workerProperty=\"WorkerLastRenderFinishedTime=\"\n        workerIdleStartTime=$(echo \"$worker\" | grep $workerProperty)\n        workerIdleStartTime=$(echo $${workerIdleStartTime#$workerProperty})\n        if [ \"$workerIdleStartTime\" != \"\" ]; then\n          workerIdleSecondsStart=$(date -u +%s --date=\"$workerIdleStartTime\")\n          workerIdleSecondsEnd=$(date -u +%s)\n          workerIdleSeconds=$(($workerIdleSecondsEnd - $workerIdleSecondsStart))\n        else\n          workerIdleSeconds=$(deadlinecommand -GetSlaveInfo $workerName UpTimeSeconds)\n        fi\n        if [ $workerIdleSeconds -gt $workerIdleDeleteSeconds ]; then\n          instanceId=$(az vmss list-instances --resource-group $resourceGroupName --name $scaleSetName --query \"[?osProfile.computerName=='$workerName'].instanceId\" --output tsv)\n          az vmss delete-instances --resource-group $resourceGroupName --name $scaleSetName --instance-ids $instanceId\n        fi\n      fi\n    done\n  fi\nfi\n", "num_lines": 63}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nsource /etc/profile.d/aaa.sh\n\nbinDirectory=\"/usr/local/bin\"\ncd $binDirectory\n\nfunctionsCode=\"functions.sh\"\nfunctionsData=\"${filebase64(\"../0.Global.Foundation/functions.sh\")}\"\necho $functionsData | base64 --decode > $functionsCode\nsource $functionsCode\n\nSetServiceAccount ${serviceAccountName} ${serviceAccountPassword}\n\nfileSystemMounts='${jsonencode(fileSystemMounts)}'\nfor fileSystemMount in $(echo $fileSystemMounts | jq -r '.[] | @base64'); do\n  if [ $(GetEncodedValue $fileSystemMount .enable) == true ]; then\n    SetFileSystemMount \"$(GetEncodedValue $fileSystemMount .mount)\"\n  fi\ndone\nmount -a\n\nEnableClientApp \"${renderManager}\" ${serviceAccountName} ${serviceAccountPassword}\n\nif [ ${terminateNotification.enable} == true ]; then\n  cronFilePath=\"/tmp/crontab\"\n  echo \"* * * * * /tmp/terminate.sh\" > $cronFilePath\n  crontab $cronFilePath\nfi\n", "num_lines": 30}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nsource /etc/profile.d/aaa.sh\n\nbinDirectory=\"/usr/local/bin\"\ncd $binDirectory\n\nfunctionsCode=\"functions.sh\"\nfunctionsData=\"${filebase64(\"../0.Global.Foundation/functions.sh\")}\"\necho $functionsData | base64 --decode > $functionsCode\nsource $functionsCode\n\nSetServiceAccount ${serviceAccountName} ${serviceAccountPassword}\n\nfileSystemMounts='${jsonencode(fileSystemMounts)}'\nfor fileSystemMount in $(echo $fileSystemMounts | jq -r '.[] | @base64'); do\n  if [ $(GetEncodedValue $fileSystemMount .enable) == true ]; then\n    SetFileSystemMount \"$(GetEncodedValue $fileSystemMount .mount)\"\n  fi\ndone\nmount -a\n\nEnableClientApp \"${renderManager}\" ${serviceAccountName} ${serviceAccountPassword}\n\nif [ \"${teradiciLicenseKey}\" != \"\" ]; then\n  /sbin/pcoip-register-host --registration-code=${teradiciLicenseKey} 2>&1 | tee pcoip-agent-license.log\nfi\n", "num_lines": 28}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\nset -x\n\nfunction fix_mod_probe() {\n    FILENAME=/etc/modprobe.d/blacklist-nouveau.conf\n    /bin/cat <<EOM >$FILENAME\n# CLOUD_IMG: This file was created/modified by the Cloud Image build process\n# Eliminate conflicts with nVIDIA drivers for GPU instances using stock kernels\nblacklist nouveau\noptions nouveau modeset=0\nEOM\n}\n\nfunction fix_cloud_config() {\n    rm -f /etc/cloud/ds-identify.cfg\n    rm -f /etc/cloud/cloud.cfg.d/50-curtin-networking.cfg\n    rm -f /etc/cloud/cloud.cfg.d/curtin-preserve-sources.cfg\n\n    FILENAME=/etc/cloud/cloud.cfg.d/10-azure-kvp.cfg\n    /bin/cat <<EOM >$FILENAME\n# CLOUD_IMG: This file was created/modified by the Cloud Image build process\nreporting:\n  logging:\n    type: log\n  telemetry:\n    type: hyperv\nEOM\n    \n    FILENAME=/etc/cloud/cloud.cfg.d/90_dpkg.cfg\n    /bin/cat <<EOM >$FILENAME\n# to update this file, run dpkg-reconfigure cloud-init\ndatasource_list: [ Azure ]\nEOM\n    FILENAME=/etc/cloud/cloud.cfg.d/90-azure.cfg\n    /bin/cat <<EOM >$FILENAME\n# CLOUD_IMG: This file was created/modified by the Cloud Image build process\nsystem_info:\n   package_mirrors:\n     - arches: [i386, amd64]\n       failsafe:\n         primary: http://archive.ubuntu.com/ubuntu\n         security: http://security.ubuntu.com/ubuntu\n       search:\n         primary:\n           - http://azure.archive.ubuntu.com/ubuntu/\n         security: []\n     - arches: [armhf, armel, default]\n       failsafe:\n         primary: http://ports.ubuntu.com/ubuntu-ports\n         security: http://ports.ubuntu.com/ubuntu-ports\nEOM\n    # after systemd changes\n}\n\nfunction fix_cloud_init() {\n    mkdir -p /lib/systemd/system/cloud-init-local.service.d\n    FILENAME=/lib/systemd/system/cloud-init-local.service.d/50-azure-clear-persistent-obj-pkl.conf\n    /bin/cat <<EOM >$FILENAME\n[Service]\nExecStartPre=-/bin/sh -xc 'if [ -e /var/lib/cloud/instance/obj.pkl ]; then echo \"cleaning persistent cloud-init object\"; rm /var/lib/cloud/instance/obj.pkl; fi; exit 0'\nEOM\n    systemctl daemon-reload\n}\n\nfunction fix_grub() {\n    FILENAME=/etc/default/grub.d/50-cloudimg-settings.cfg\n    /bin/cat <<EOM >$FILENAME\n# Windows Azure specific grub settings\n# CLOUD_IMG: This file was created/modified by the Cloud Image build process\n\n# Set the default commandline\nGRUB_CMDLINE_LINUX_DEFAULT=\"console=tty1 console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n\n# Set the grub console type\nGRUB_TERMINAL=serial\n\n# Set the serial command\nGRUB_SERIAL_COMMAND=\"serial --speed=9600 --unit=0 --word=8 --parity=no --stop=1\"\n\n# Set the recordfail timeout\nGRUB_RECORDFAIL_TIMEOUT=0\n\n# Do not wait on grub prompt\nGRUB_TIMEOUT=0\nEOM\n\n    FILENAME=/etc/default/grub\n    /bin/cat <<EOM >$FILENAME\n# If you change this file, run 'update-grub' afterwards to update\n# /boot/grub/grub.cfg.\n# For full documentation of the options in this file, see:\n#   info -f grub -n 'Simple configuration'\n\n# Set the default commandline\nGRUB_CMDLINE_LINUX_DEFAULT=\"console=tty1 console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n\n# Set the grub console type\nGRUB_TERMINAL=serial\n\n# Set the serial command\nGRUB_SERIAL_COMMAND=\"serial --speed=9600 --unit=0 --word=8 --parity=no --stop=1\"\n\n# Set the recordfail timeout\nGRUB_RECORDFAIL_TIMEOUT=0\n\n# Do not wait on grub prompt\nGRUB_TIMEOUT=0\n\nGRUB_DEFAULT=0\nGRUB_TIMEOUT_STYLE=hidden\nGRUB_DISTRIBUTOR=\\`lsb_release -i -s 2> /dev/null || echo Debian\\`\n\n# Uncomment to enable BadRAM filtering, modify to suit your needs\n# This works with Linux (no patch required) and with any kernel that obtains\n# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)\n#GRUB_BADRAM=\"0x01234567,0xfefefefe,0x89abcdef,0xefefefef\"\n\n# Uncomment to disable graphical terminal (grub-pc only)\n#GRUB_TERMINAL=console\n\n# The resolution used on graphical terminal\n# note that you can use only modes which your graphic card supports via VBE\n# you can see them in real GRUB with the command \\`vbeinfo\\`\n#GRUB_GFXMODE=640x480\n\n# Uncomment if you don't want GRUB to pass \"root=UUID=xxx\" parameter to Linux\n#GRUB_DISABLE_LINUX_UUID=true\n\n# Uncomment to disable generation of recovery mode menu entries\n#GRUB_DISABLE_RECOVERY=\"true\"\n\n# Uncomment to get a beep at grub start\n#GRUB_INIT_TUNE=\"480 440 1\"\nEOM\n    update-grub\n}\n\nfunction fix_initramfs() {\n    FILENAME=/etc/initramfs-tools/modules\n    /bin/cat <<EOM >$FILENAME\n# List of modules that you want to include in your initramfs.\n# They will be loaded at boot time in the order below.\n#\n# Syntax:  module_name [args ...]\n#\n# You must run update-initramfs(8) to effect this change.\n#\n# Examples:\n#\n# raid1\n# sd_mod\n\n# CLOUD_IMG: This file was created/modified by the Cloud Image build process\n# This fix is important on virtual machines, because when hyperv_fb.ko is\n# missing, the \"setfont\" stage for the console (part of the boot process)\n# will add 2-4 minutes to initialization on Ubuntu. Apparently this operation\n# does a lot of work with the emulated device and its generic VGA driver.\nhyperv_fb\nEOM\n}\n\nfunction main() {\n    fix_mod_probe\n    fix_cloud_config\n    fix_initramfs\n    fix_grub\n    fix_cloud_init\n}\n\nmain", "num_lines": 173}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            retrycmd_if_failure 12 5 apt-get update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt-get update\n    apt_get_install 12 5 nfs-kernel-server iotop iperf3 bwm-ng\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 52}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            retrycmd_if_failure 12 5 apt-get update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt-get update\n    apt_get_install 12 5 nfs-kernel-server iotop iperf3 bwm-ng\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 52}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\n# always source to get go in the path\n. $HOME/.profile\n\n# install golang\nif ! command -v go &> /dev/null ; then\n    GO_DL_FILE=go1.16.6.linux-amd64.tar.gz\n    wget --tries=12 --wait=5 https://dl.google.com/go/$GO_DL_FILE\n    sudo -E tar -C /usr/local -xzf $GO_DL_FILE\n    rm -f $GO_DL_FILE\n    echo \"export PATH=$PATH:/usr/local/go/bin\" >> $HOME/.profile\n    . $HOME/.profile\nfi\n\n# checkout and build CacheWarmer\ncd\nRELEASE_DIR=$HOME/release\nmkdir -p $RELEASE_DIR\ngit clone https://github.com/Azure/Avere.git\n# build the cache warmer\ncd $HOME/Avere/src/go/cmd/cachewarmer/cachewarmer-jobsubmitter\ngo build\nmv cachewarmer-jobsubmitter $RELEASE_DIR/.\ncd $HOME/Avere/src/go/cmd/cachewarmer/cachewarmer-manager\ngo build\nmv cachewarmer-manager $RELEASE_DIR/.\ncd $HOME/Avere/src/go/cmd/cachewarmer/cachewarmer-worker\ngo build\nmv cachewarmer-worker $RELEASE_DIR/.\ncd\n\n# set the path\nexport CACHEWARMER_MANAGER_PATH=$RELEASE_DIR/cachewarmer-manager\nexport CACHEWARMER_WORKER_PATH=$RELEASE_DIR/cachewarmer-worker\nexport CACHEWARMER_JOBSUBMITTER_PATH=$RELEASE_DIR/cachewarmer-jobsubmitter\n\nset +x", "num_lines": 39}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# before running this script define the following env vars\n# LOCAL_MOUNT_DIR=/b\n# BOOTSTRAP_MOUNT_ADDRESS=FILE_ADDRESS\n# BOOTSTRAP_MOUNT_EXPORT=/data\n# BOOTSTRAP_SUBDIR=/bootstrap\n#\n# # leave CACHEWARMER_MANAGER_PATH empty if you did not build your own cachewarmer binaries\n# CACHEWARMER_MANAGER_PATH=\"\"\n# CACHEWARMER_WORKER_PATH=\"\"\n# CACHEWARMER_JOBSUBMITTER_PATH=\"\"\n\nif [ -z $LOCAL_MOUNT_DIR ]; then\n    echo \"LOCAL_MOUNT_DIR is not set\"\n    return\nfi\nif [ -z $BOOTSTRAP_MOUNT_ADDRESS ]; then\n    echo \"BOOTSTRAP_MOUNT_ADDRESS is not set\"\n    return\nfi\nif [ -z $BOOTSTRAP_MOUNT_EXPORT ]; then\n    echo \"BOOTSTRAP_MOUNT_EXPORT is not set\"\n    return\nfi\nif [ -z $BOOTSTRAP_SUBDIR ]; then\n    echo \"BOOTSTRAP_SUBDIR is not set\"\n    return\nfi\n\nset -x\n\n# go home\ncd\n\n# \"sudo -E\" required to pass environment variables including proxy settings\n\n# remove a previous install if one exists\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/bootstrap.cachewarmer-manager.sh\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/bootstrap.cachewarmer-worker.sh\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/rsyslog/35-cachewarmer-manager.conf\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/rsyslog/36-cachewarmer-worker.conf\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/systemd/cachewarmer-manager.service\nsudo -E rm -f $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/systemd/cachewarmer-worker.service\n\n# create the bootstrap directory\nsudo -E mkdir -p $LOCAL_MOUNT_DIR\nsudo -E mount -o 'hard,nointr,proto=tcp,mountproto=tcp,retry=30' $BOOTSTRAP_MOUNT_ADDRESS:$BOOTSTRAP_MOUNT_EXPORT $LOCAL_MOUNT_DIR\nsudo -E mkdir -p $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/cachewarmerbin\nsudo -E mkdir -p $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/rsyslog\nsudo -E mkdir -p $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/systemd\n\n# download the content\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/bootstrap.cachewarmer-manager.sh https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/bootstrap.cachewarmer-manager.sh\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/bootstrap.cachewarmer-worker.sh https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/bootstrap.cachewarmer-worker.sh\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/rsyslog/35-cachewarmer-manager.conf https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/rsyslog/35-cachewarmer-manager.conf\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/rsyslog/36-cachewarmer-worker.conf https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/rsyslog/36-cachewarmer-worker.conf\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/systemd/cachewarmer-manager.service https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/systemd/cachewarmer-manager.service\nsudo -E curl --retry 5 --retry-delay 5 -L -o $LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/systemd/cachewarmer-worker.service https://raw.githubusercontent.com/Azure/Avere/main/src/go/cmd/cachewarmer/deploymentartifacts/bootstrap/systemd/cachewarmer-worker.service\n\nTARGET_PATH=$LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/cachewarmerbin/cachewarmer-manager\nif [ -z \"$CACHEWARMER_MANAGER_PATH\" ]; then\n    browser_download_url=$(curl -s https://api.github.com/repos/Azure/Avere/releases/latest | jq -r .assets[].browser_download_url | grep -e \"cachewarmer-manager$\")\n    sudo -E curl --retry 5 --retry-delay 5 -L -o $TARGET_PATH $browser_download_url\n    sudo -E chmod +x $TARGET_PATH\nelse\n    sudo -E cp $CACHEWARMER_MANAGER_PATH $TARGET_PATH\nfi\nTARGET_PATH=$LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/cachewarmerbin/cachewarmer-worker\nif [ -z \"$CACHEWARMER_WORKER_PATH\" ]; then\n    browser_download_url=$(curl -s https://api.github.com/repos/Azure/Avere/releases/latest | jq -r .assets[].browser_download_url | grep -e \"cachewarmer-worker$\")\n    sudo -E curl --retry 5 --retry-delay 5 -L -o $TARGET_PATH $browser_download_url\n    sudo -E chmod +x $TARGET_PATH\nelse\n    sudo -E cp $CACHEWARMER_WORKER_PATH $TARGET_PATH\nfi\nTARGET_PATH=$LOCAL_MOUNT_DIR/$BOOTSTRAP_SUBDIR/cachewarmerbin/cachewarmer-jobsubmitter\nif [ -z \"$CACHEWARMER_JOBSUBMITTER_PATH\" ]; then\n    browser_download_url=$(curl -s https://api.github.com/repos/Azure/Avere/releases/latest | jq -r .assets[].browser_download_url | grep -e \"cachewarmer-jobsubmitter$\")\n    sudo -E curl --retry 5 --retry-delay 5 -L -o $TARGET_PATH $browser_download_url\n    sudo -E chmod +x $TARGET_PATH\nelse\n    sudo -E cp $CACHEWARMER_JOBSUBMITTER_PATH $TARGET_PATH\nfi\n\n# umount and remove the local mount directory\nsudo -E umount $LOCAL_MOUNT_DIR\nsudo -E rmdir $LOCAL_MOUNT_DIR\n\nset +x", "num_lines": 90}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\nAZURE_HOME_DIR=/home/$ADMIN_USER_NAME\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 yum -y install wget unzip git nfs-utils tmux unbound\n}\n\nfunction configure_grid() {\n    # instructions from https://docs.microsoft.com/en-us/azure/virtual-machines/linux/n-series-driver-setup#install-grid-drivers-on-nv-or-nvv3-series-vms\n    NVIDIA_RUN_FILE=/opt/nvidia.run\n    # get pre-reqs\n    retrycmd_if_failure 12 5 yum -y install gcc\n    # unable to do a retry because of the quotes\n    yum -y install \"kernel-devel-uname-r == $(uname -r)\"\n    retrycmd_if_failure 12 5 rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n    retrycmd_if_failure 12 5 yum -y install dkms\n    retrycmd_if_failure 12 5 yum -y install hyperv-daemons\n     \n    # download\n    mkdir -p /opt && curl -L --retry 5 --retry-delay 5 -o $NVIDIA_RUN_FILE  https://go.microsoft.com/fwlink/?linkid=874272\n\n    chmod +x $NVIDIA_RUN_FILE\n    $NVIDIA_RUN_FILE -s\n}\n\nfunction configure_gnome() {\n    retrycmd_if_failure 12 5 yum -y groups install 'GNOME Desktop'\n}\n\nfunction configure_teradici() {\n    # downloads.terradici.com will eventually be deprecated\n    retrycmd_if_failure 12 5 yum -y install https://downloads.teradici.com/rhel/teradici-repo-latest.noarch.rpm\n\n    retrycmd_if_failure 12 5 yum -y install epel-release\n\n    retrycmd_if_failure 12 5 yum -y install usb-vhci\n\n    retrycmd_if_failure 12 5 yum -y install pcoip-agent-graphics\n}\n\nfunction configure_teradici_license() {\n    # run the following on the machine after the install\n    if [[ ! -z \"$TERADICI_KEY\" ]]; then\n        REGISTER_PATH=$(which pcoip-register-host 2> /dev/null)\n        if [[ -x \"$REGISTER_PATH\" ]] ; then\n            pcoip-register-host --registration-code=$TERADICI_KEY\n        fi\n    fi\n}\n\nfunction update_search_domain() {\n    if [[ ! -z \"$SEARCH_DOMAIN\" ]]; then\n        NETWORK_FILE=/etc/sysconfig/network-scripts/ifcfg-eth0\n        if grep --quiet \"DOMAIN=\" $NETWORK_FILE; then\n            sed -i 's/^#\\s*DOMAIN=/DOMAIN=/g' $NETWORK_FILE\n            sed -i \"s/^DOMAIN=.*$/DOMAIN=\\\"${SEARCH_DOMAIN}\\\"/g\"  $NETWORK_FILE\n        else\n            echo \"DOMAIN=\\\"${SEARCH_DOMAIN}\\\"\" >> $NETWORK_FILE\n        fi\n        # restart network to take effect\n        systemctl restart network\n    fi\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"configure GNOME Desktop\"\n    configure_gnome\n\n    if [[ \"true\" == \"$INSTALL_PCOIP\" ]]; then\n        echo \"configure grid\"\n        configure_grid\n\n        echo \"configure Teradici\"\n        configure_teradici\n    else\n        echo \"not installing pcoip\"\n    fi\n\n    echo \"configure Teradici License\"\n    configure_teradici_license\n\n    echo \"update search domain\"\n    update_search_domain\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 113}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installcycle.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils wget unzip git tmux\n}\n\n# export the ephemeral disk as specified by $EXPORT_PATH\nfunction configure_cyclecloud() {\n    echo \"configure_cyclecloud\"\n    cat > /etc/yum.repos.d/cyclecloud.repo <<EOF\n[cyclecloud]\nname=cyclecloud\nbaseurl=https://packages.microsoft.com/yumrepos/cyclecloud\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\nEOF\n\n    yum_install 12 10 180 cyclecloud8\n}\n\nfunction install_az_cli() {\n    retrycmd_if_failure 12 5 rpm --import https://packages.microsoft.com/keys/microsoft.asc\n    sh -c 'echo -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n    retrycmd_if_failure 12 5 yum -y install azure-cli\n}\n\nfunction wait_az_login() {\n    # wait for RBAC assignments to be applied\n    # unfortunately, the RBAC assignments take undetermined time past their associated resource completions to be assigned.\n    if ! retrycmd_if_failure 120 5 az login --identity ; then\n        echo \"MANAGED IDENTITY FAILURE: failed to login after waiting 10 minutes, this is managed identity bug\"\n        exit 1\n    fi\n    if ! retrycmd_if_failure 12 5 az account set --subscription $SUBSCRIPTION_ID ; then\n        echo \"MANAGED IDENTITY FAILURE: failed to set subscription\"\n        exit 1\n    fi\n}\n\nfunction main() {\n    mkdir -p /opt\n    \n    if [ \"${USE_MARKETPLACE}\" = \"false\" ]; then\n\n        echo \"config Linux\"\n        config_linux\n\n        echo \"setup CycleCloud\"\n        configure_cyclecloud\n    fi\n\n    echo \"install az cli\"\n    install_az_cli\n\n    echo \"wait az login\"\n    wait_az_login\n    \n    echo \"installation complete\"\n\n    touch /opt/installcycle.complete\n}\n\nmain\n", "num_lines": 104}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines, and exit on error\nset -x\nset -e\n\nAZURE_HOME_DIR=/home/$ADMIN_USER_NAME\n\nfunction retrycmd_if_failure() {\n    set +e\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    set -e\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 yum -y install wget unzip git nfs-utils tmux unbound\n}\n\nfunction configure_unbound() {\n    UNBOUND_CONF_FILE=/etc/unbound/unbound.conf\n    cp $UNBOUND_CONF_FILE $UNBOUND_CONF_FILE.bak\n    cp /opt/unbound.conf $UNBOUND_CONF_FILE\n\n    systemctl start unbound\n    systemctl enable unbound\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"configure unbound\"\n    configure_unbound\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 53}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines, and exit on error\nset -x\nset -e\n\nAZURE_HOME_DIR=/home/$ADMIN_USER_NAME\n\nfunction retrycmd_if_failure() {\n    set +e\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    set -e\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt update -y\n    retrycmd_if_failure 12 5 apt install -y unbound\n}\n\nfunction configure_unbound() {\n    # first disable systemd-resolved\n    systemctl stop systemd-resolved\n    systemctl disable systemd-resolved\n    ln -sf /run/systemd/resolve/resolv.conf /etc/resolv.conf\n\n    UNBOUND_CONF_FILE=/etc/unbound/unbound.conf\n    cp $UNBOUND_CONF_FILE $UNBOUND_CONF_FILE.bak\n    cp /opt/unbound.conf $UNBOUND_CONF_FILE\n\n    systemctl restart unbound\n    systemctl enable unbound\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"configure unbound\"\n    configure_unbound\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 59}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines, and exit on error\nset -x\nset -e\n\nAZURE_HOME_DIR=/home/$ADMIN_USER_NAME\n\nfunction retrycmd_if_failure() {\n    set +e\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    set -e\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 yum -y install wget unzip git nfs-utils tmux nc jq\n    retrycmd_if_failure 12 5 yum -y install epel-release\n    retrycmd_if_failure 12 5 yum -y install python-pip\n    #retrycmd_if_failure 3 5 pip install hstk\n}\n\nfunction install_golang() {\n    cd $AZURE_HOME_DIR\n    GO_DL_FILE=go1.16.6.linux-amd64.tar.gz\n    wget --tries=12 --wait=5 https://dl.google.com/go/$GO_DL_FILE\n    sudo tar -C /usr/local -xzf $GO_DL_FILE\n    rm -f $GO_DL_FILE\n    #echo \"export GOPATH=$AZURE_HOME_DIR/gopath\" >> $AZURE_HOME_DIR/.profile\n    echo \"export PATH=$PATH:/usr/local/go/bin\" >> $AZURE_HOME_DIR/.profile\n}\n\nfunction pull_avere_github() {\n    # use workaround set home for go to work, bug here: https://github.com/golang/go/issues/43938\n    OLD_HOME=$HOME\n    export HOME=$AZURE_HOME_DIR\n\n    # best effort to build the github content\n    set +e\n    RELEASE_DIR=$AZURE_HOME_DIR/releases\n    mkdir -p $RELEASE_DIR\n    source $AZURE_HOME_DIR/.profile\n    cd $AZURE_HOME_DIR\n    git clone https://github.com/Azure/Avere.git\n    \n    # build the provider\n    cd $AZURE_HOME_DIR/Avere/src/terraform/providers/terraform-provider-avere\n    go build\n    GOOS=windows GOARCH=amd64 go build\n    mv terraform-provider-avere* $RELEASE_DIR/.\n    \n    # build the cachewarmer\n    cd $AZURE_HOME_DIR/Avere/src/go/cmd/cachewarmer/cachewarmer-jobsubmitter\n    go build\n    mv cachewarmer-jobsubmitter $RELEASE_DIR/.\n    cd $AZURE_HOME_DIR/Avere/src/go/cmd/cachewarmer/cachewarmer-manager\n    go build\n    mv cachewarmer-manager $RELEASE_DIR/.\n    cd $AZURE_HOME_DIR/Avere/src/go/cmd/cachewarmer/cachewarmer-worker\n    go build\n    mv cachewarmer-worker $RELEASE_DIR/.\n    \n    cd $RELEASE_DIR/.\n    ls -lh\n\n    # install provider\n    version=$(curl -s https://api.github.com/repos/Azure/Avere/releases/latest | jq -r .tag_name | sed -e 's/[^0-9]*\\([0-9].*\\)$/\\1/')\n    echo $version\n    mkdir -p $AZURE_HOME_DIR/.terraform.d/plugins/registry.terraform.io/hashicorp/avere/$version/linux_amd64\n    cp $RELEASE_DIR/terraform-provider-avere $AZURE_HOME_DIR/.terraform.d/plugins/registry.terraform.io/hashicorp/avere/$version/linux_amd64\n\n    # restore HOME\n    export HOME=$OLD_HOME\n\n    # re-enable exit on error\n    set -e\n}\n\nfunction install_az_cli() {\n    retrycmd_if_failure 12 5 rpm --import https://packages.microsoft.com/keys/microsoft.asc\n    sh -c 'echo -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n    retrycmd_if_failure 12 5 yum -y install azure-cli\n}\n\nfunction install_terraform() {\n    cd $AZURE_HOME_DIR/.\n    wget --tries=12 --wait=5 https://releases.hashicorp.com/terraform/1.0.2/terraform_1.0.2_linux_amd64.zip\n    unzip terraform_1.0.2_linux_amd64.zip -d /usr/local/bin\n    rm terraform_1.0.2_linux_amd64.zip\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    if [ \"${BUILD_VFXT_PROVIDER}\" = \"true\" ]; then\n        echo \"install golang\"\n        install_golang\n\n        echo \"pull and build the Avere github project\"\n        pull_avere_github\n    fi\n\n    echo \"install az cli\"\n    install_az_cli\n\n    echo \"install terraform\"\n    install_terraform\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain\n", "num_lines": 133}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt update\n    retrycmd_if_failure 12 5 apt install -y unzip nfs-kernel-server iotop iperf3 bwm-ng\n    retrycmd_if_failure 12 5 apt install -y unison\n}\n\nfunction configure_sync() {\n    # installing per https://docs.microsoft.com/en-us/azure/avere-vfxt/avere-vfxt-data-ingest#use-the-msrsync-utility\n    curl --retry 5 --retry-delay 5 -o /usr/bin/prime.py https://raw.githubusercontent.com/Azure/Avere/main/src/clientapps/dataingestor/prime.py\n    sed -i 's:^#!/usr/bin/env python$:#!/usr/bin/env python2:' /usr/bin/prime.py\n    chmod +x /usr/bin/prime.py\n\n    curl --retry 5 --retry-delay 5 -o /usr/bin/msrsync https://raw.githubusercontent.com/jbd/msrsync/master/msrsync\n    chmod +x /usr/bin/msrsync   \n\n    # unison - popular two-way synchronization - https://github.com/bcpierce00/unison\n    #retrycmd_if_failure 12 5 yum -y install epel-release\n    #retrycmd_if_failure 12 5 yum -y install unison\n\n    # here are some other choices that have not been installed\n    #  syncthing - modern, actively developed, open, 2-way synchronization tool, syncthing does not preserve uid/gid\n    #  https://dirsyncpro.org/index.html - for syncing two directories\n\n    # download syncthing: https://computingforgeeks.com/install-and-configure-syncthing-on-centos-linux/\n    # syncthing does not preserve uid/gid\n    #mkdir -p /opt\n    #cd /opt\n    #curl -s https://api.github.com/repos/syncthing/syncthing/releases/latest | grep browser_download_url | grep linux-amd64 | cut -d '\"' -f 4 | wget -qi -\n    #tar xvf syncthing-linux-amd64*.tar.gz\n    #cp syncthing-linux-amd64-*/syncthing  /bin/.\n    #chmod +x /bin/syncthing\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"configure sync\"\n    configure_sync\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 67}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# EXPORT_PATH=/data\n# EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\"\n#\n# called like this:\n#  sudo EXPORT_PATH=/data EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\" ./installnfs.sh\n#\n\n# terraform variables: tf_env_variables\n\nset -x\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n\n    yum install -y nfs-utils\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils\n}\n\nfunction config_ephemeral_nvme {\n    RAIDDISK=/dev/md0\n    DISKS=($(ls /dev/nvme*n*))\n    DISKCOUNT=${#DISKS[@]}\n    if [ \"$DISKCOUNT\" -eq \"1\" ] ; then\n        DISK_DEVICE=${DISKS[0]}\n    else\n        udevadm control --stop-exec-queue\n        echo \"yes\" | mdadm --create $RAIDDISK --level=0 --raid-devices=$DISKCOUNT ${DISKS[@]}\n        udevadm control --start-exec-queue\n        mkdir -p /etc/mdadm\n        mdadm --detail --verbose --scan > /etc/mdadm/mdadm.conf\n        # log the details of the mount to STDOUT\n        mdadm --detail --verbose --scan\n        cat /proc/mdstat\n        DISK_DEVICE=$RAIDDISK\n    fi\n\n    # add the ext4 filesystem\n    mkfs.ext4 -F $DISK_DEVICE\n\n    read UUID FS_TYPE < <(blkid -u filesystem $DISK_DEVICE|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    echo -e \"UUID=\\\"${UUID}\\\"\\t$EXPORT_PATH\\t$FS_TYPE\\tnoatime,nodiratime,nodev,noexec,nosuid,nofail\\t1 2\" >> /etc/fstab\n    mount $EXPORT_PATH\n}\n\nfunction config_ephemeral_ssd {\n    grep -e \"/mnt\\s\" /etc/fstab > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        # this is managed by the new cloud init\n\n        # export the ephemeral disk\n        EPHEMERAL_DISK_PATH=\"/mnt\"\n        umount $EPHEMERAL_DISK_PATH\n        sed -i \"s:${EPHEMERAL_DISK_PATH}:${EXPORT_PATH}:g\" /etc/fstab\n        mount ${EXPORT_PATH}\n    else \n        grep -e \"cloud-init.service\" /etc/fstab > /dev/null 2>&1\n        if [ $? = \"0\" ]; then\n            # export the ephemeral disk\n            EPHEMERAL_DISK_PATH=\"/mnt/resource\"\n            umount $EPHEMERAL_DISK_PATH\n            sed -i \"s:${EPHEMERAL_DISK_PATH}:${EXPORT_PATH}:g\" /etc/fstab\n            mount ${EXPORT_PATH}\n        else\n            # this is managed by older waagent\n\n            # export the ephemeral disk\n            EPHEMERAL_DISK_PATH=\"/mnt/resource\"\n            # move the ephemeral mount to the mount chosen by the customer\n            # we cannot do the symbolic link because it is not supported by nfsv4\n            umount $EPHEMERAL_DISK_PATH\n            sed -i \"s:${EPHEMERAL_DISK_PATH}:${EXPORT_PATH}:g\" /etc/waagent.conf\n            # restart waagent to mount the new share\n            systemctl restart waagent\n        fi\n    fi\n}\n\nfunction config_ephemeral_disk {\n    mkdir -p $EXPORT_PATH\n    grep nfsnobody /etc/passwd > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        chown nfsnobody:nfsnobody $EXPORT_PATH\n    else\n        chown nobody:nogroup $EXPORT_PATH\n    fi\n    \n    ls -1 /dev/nvme*\n    if [ $? = \"0\" ]; then\n        config_ephemeral_nvme\n    else\n        config_ephemeral_ssd\n    fi\n    chmod 777 $EXPORT_PATH\n}\n\n# export the ephemeral disk as specified by $EXPORT_PATH\nfunction configure_nfs() {\n    # enable the nfs service\n    systemctl enable nfs-server rpcbind\n\n    # stop the nfs service\n    systemctl stop nfs-server rpcbind\n\n    # configure NFS export for the export path\n    grep \"^${EXPORT_PATH}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${EXPORT_PATH} is already exported. Returning...\"\n    else\n        echo -e \"\\n${EXPORT_PATH}   ${EXPORT_OPTIONS}\" >> /etc/exports\n    fi\n\n    # update to use 64 threads to get most performance\n    sed -i 's/^.*RPCNFSDCOUNT=.*$/RPCNFSDCOUNT=64/g' /etc/sysconfig/nfs\n    \n    # start the nfs service\n    systemctl start nfs-server rpcbind\n}\n\nfunction main() {\n    mkdir -p /opt\n    \n    if [ -z \"$EXPORT_PATH\" ]; then\n        echo \"env var EXPORT_PATH is not defined, please define\"\n        touch /opt/installnfs.failed\n        exit 1\n    fi\n\n    if [ -z \"$EXPORT_OPTIONS\" ]; then\n        echo \"env var EXPORT_OPTIONS is not defined, please define\"\n        touch /opt/installnfs.failed\n        exit 1\n    fi\n\n    echo \"config Linux\"\n    config_linux\n\n    echo \"config Ephemeral Disk\"\n    config_ephemeral_disk\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 169}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# EXPORT_PATH=/data\n#\n# called like this:\n#  sudo EXPORT_PATH=/data ./installnfs.sh\n#\n\nset -x\n\nMOUNT_OPTIONS=\"noatime,nodiratime,nodev,noexec,nosuid,nofail\"\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        # timeout occasionally freezes\n        #echo \"timeout $timeout apt-get install --no-install-recommends -y ${@}\"\n        #timeout $timeout apt-get install --no-install-recommends -y ${@}\n        apt-get install --no-install-recommends -y ${@}\n        echo \"completed\"\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n\texport DEBIAN_FRONTEND=noninteractive  \n    add-apt-repository universe\n\tapt_get_update\n\tapt_get_install 20 10 180 nfs-ganesha nfs-ganesha-vfs\n    # perf diagnostic tools\n    if [ ! -z \"$PERF_DIAG_TOOLS\" ]; then\n        apt_get_install 20 10 180 iotop iperf3 bwm-ng\n    fi\n    # enable root login, sometimes useful for rsync\n    if [ ! -z \"$ALLOW_ROOT_LOGIN\" ]; then\n        sed -i 's/.* ssh-rsa/ssh-rsa/' /root/.ssh/authorized_keys\n        sed -i 's/^#PermitRootLogin.*$/PermitRootLogin yes/' /etc/ssh/sshd_config\n        systemctl restart sshd\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction is_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction has_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction add_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\t${MOUNT_OPTIONS}\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction do_partition() {\n    # This function creates one (1) primary partition on the\n    # disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=8300\n    fi\n    echo \"n\n1\n\n\n${_type}\nw\ny\"| gdisk \"${_disk}\"\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from gdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${_disk}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_partition_format()\n{\n    echo \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n    if [ \"${#DISKS[@]}\" -eq 0 ];\n    then\n        echo \"No unpartitioned disks without filesystems detected\"\n        return\n    fi\n    if [ \"${#DISKS[@]}\" -gt 1 ];\n    then\n        echo \"WARNING: there are ${#DISKS[@]} unformatted disks, only the first disk will be mounted\"\n    fi\n    echo \"Disks are ${DISKS[@]}\"\n    DISK=${DISKS[0]}\n    \n    echo \"Working on ${DISK}\"\n    is_partitioned ${DISK}\n    if [ ${?} -ne 0 ];\n    then\n        echo \"${DISK} is not partitioned, partitioning\"\n        do_partition ${DISK}\n    fi\n    PARTITION_NUM=$(gdisk -l ${DISK}|grep -A 1 Number|tail -n 1|awk '{print $1}')\n    PARTITION=${DISK}${PARTITION_NUM}\n    has_filesystem ${PARTITION}\n    if [ ${?} -ne 0 ];\n    then\n        echo \"Creating filesystem on ${PARTITION}.\"\n        mkfs -j -t ext4 ${PARTITION}\n    fi\n}\n\nfunction get_unmounted_disk()\n{\n    DEVS=($(ls -1 /dev/sd*|egrep \"[a-z][0-9]$\"))\n    TARGET_PARTITION=\"\"\n    for DEV in \"${DEVS[@]}\";\n    do\n        if ! mount | grep -F --quiet \"$DEV\"; then\n            TARGET_PARTITION=$DEV\n            break\n        fi\n    done\n    echo \"$TARGET_PARTITION\"\n}\n\nfunction mount_disk() {\n    PARTITION=$1; shift\n\n    MOUNTPOINT=$EXPORT_PATH\n    echo \"mount point is ${MOUNTPOINT}\"\n    if [ ! -d \"${MOUNTPOINT}\" ];\n    then\n        mkdir -p \"${MOUNTPOINT}\"\n        chown nobody:nogroup \"${MOUNTPOINT}\"\n        chmod 777 \"${MOUNTPOINT}\"\n        ls -l \"${MOUNTPOINT}\"\n    fi \n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nfunction wait_for_disk_attach() {\n    retries=$1; wait_sleep=$2; shift && shift\n\n    for i in $(seq 1 $retries); do\n        DISKS=($(scan_for_new_disks))\n        if [ \"${#DISKS[@]}\" -gt 0 ]; then\n            echo \"new disk found!\"\n            return\n        fi\n        \n        PARTITION=$(get_unmounted_disk)\n\n        if [ ${#PARTITION} -gt 0 ]; then\n            echo \"unattached disk found!\"\n            return \n        fi\n\n        echo \"no disks found, sleeping for $wait_sleep seconds\"\n        sleep $wait_sleep\n    done\n}\n\n# export the ephemeral disk as specified by $EXPORT_PATH\nfunction configure_nfs() {\n    # enable the nfs service\n    systemctl enable nfs-ganesha\n\n    # stop the nfs service\n    systemctl stop nfs-ganesha\n\n    cp /etc/ganesha/ganesha.conf /etc/ganesha/ganesha.conf.bak\n    \n    echo \"EXPORT\n{\n        # Export Id (mandatory, each EXPORT must have a unique Export_Id)\n        Export_Id = 87;\n\n        # Exported path (mandatory)\n        Path = ${EXPORT_PATH};\n\n        # Pseudo Path (required for NFS v4)\n        Pseudo = ${EXPORT_PATH};\n\n        # Required for access (default is None)\n        # Could use CLIENT blocks instead\n        Access_Type = RW;\n\n        # Exporting FSAL\n        FSAL {\n                Name = VFS;\n        }\n        CLIENT {\n                Access_Type=RW;\n                Anonymous_gid=4294967294;\n                Anonymous_uid=4294967294;\n                Clients=*;\n                Delegations=none;\n                Manage_Gids=FALSE;\n                NFS_Commit=FALSE;\n                PrivilegedPort=FALSE;\n                Protocols= 3,4;\n                SecType=NONE,SYS;\n                Squash=NO_ROOT_SQUASH;\n                Transports=UDP,TCP;\n        }\n}\" > /etc/ganesha/ganesha.conf\n    \n    # start the nfs service\n    systemctl start nfs-ganesha\n}\n\nfunction main() {\n    mkdir -p /opt\n    \n    if [ -z \"$EXPORT_PATH\" ]; then\n        echo \"env var EXPORT_PATH is not defined, please define\"\n        touch /opt/installnfs.failed\n        touch /opt/installnfs.complete\n        exit 1\n    fi\n\n    echo \"config Linux\"\n    config_linux\n\n    # wait 10 minutes for a disk to show up\n    wait_for_disk_attach 60 10\n    \n    echo \"scan_partition_format\"\n    scan_partition_format\n\n    echo \"mount_unmounted_disk\"\n    PARTITION=$(get_unmounted_disk)\n\n    if [ ${#PARTITION} -eq 0 ]; then\n        echo \"no unmounted file system exists\"\n        touch /opt/installnfs.failed\n        touch /opt/installnfs.complete\n        return 1\n    fi\n\n    mount_disk $PARTITION\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 330}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# EXPORT_PATH=/data\n# EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\"\n#\n# called like this:\n#  sudo EXPORT_PATH=/data EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\" ./installnfs.sh\n#\n\nset -x\n\nMOUNT_OPTIONS=\"noatime,nodiratime,nodev,noexec,nosuid,nofail\"\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n    # try for 20 minutes\n    yum_install 120 10 180 nfs-utils\n    # perf diagnostic tools\n    if [ ! -z \"$PERF_DIAG_TOOLS\" ]; then\n        yum_install 120 10 180 iotop iperf3\n        yum_install 120 10 180 epel-release\n        yum_install 120 10 180 bwm-ng\n    fi\n    # enable root login, sometimes useful for rsync\n    if [ ! -z \"$ALLOW_ROOT_LOGIN\" ]; then\n        sed -i 's/.* ssh-rsa/ssh-rsa/' /root/.ssh/authorized_keys\n        sed -i 's/^#PermitRootLogin.*$/PermitRootLogin yes/' /etc/ssh/sshd_config\n        systemctl restart sshd\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction is_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction has_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction add_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\t${MOUNT_OPTIONS}\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction do_partition() {\n    # This function creates one (1) primary partition on the\n    # disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=8300\n    fi\n    echo \"n\n1\n\n\n${_type}\nw\ny\"| gdisk \"${_disk}\"\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from gdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${_disk}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_partition_format()\n{\n    echo \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n    if [ \"${#DISKS[@]}\" -eq 0 ];\n    then\n        echo \"No unpartitioned disks without filesystems detected\"\n        return\n    fi\n    if [ \"${#DISKS[@]}\" -gt 1 ];\n    then\n        echo \"WARNING: there are ${#DISKS[@]} unformatted disks, only the first disk will be mounted\"\n    fi\n    echo \"Disks are ${DISKS[@]}\"\n    DISK=${DISKS[0]}\n    \n    echo \"Working on ${DISK}\"\n    is_partitioned ${DISK}\n    if [ ${?} -ne 0 ];\n    then\n        echo \"${DISK} is not partitioned, partitioning\"\n        do_partition ${DISK}\n    fi\n    PARTITION_NUM=$(gdisk -l ${DISK}|grep -A 1 Number|tail -n 1|awk '{print $1}')\n    PARTITION=${DISK}${PARTITION_NUM}\n    has_filesystem ${PARTITION}\n    if [ ${?} -ne 0 ];\n    then\n        echo \"Creating filesystem on ${PARTITION}.\"\n        mkfs -j -t ext4 ${PARTITION}\n    fi\n}\n\nfunction get_unmounted_disk()\n{\n    DEVS=($(ls -1 /dev/sd*|egrep \"[0-9]$\"))\n    TARGET_PARTITION=\"\"\n    for DEV in \"${DEVS[@]}\";\n    do\n        if ! mount | grep -F --quiet \"$DEV\"; then\n            TARGET_PARTITION=$DEV\n            break\n        fi\n    done\n    echo \"$TARGET_PARTITION\"\n}\n\nfunction mount_disk() {\n    PARTITION=$1; shift\n\n    MOUNTPOINT=$EXPORT_PATH\n    echo \"mount point is ${MOUNTPOINT}\"\n    if [ ! -d \"${MOUNTPOINT}\" ];\n    then\n        mkdir -p \"${MOUNTPOINT}\"\n        chown nfsnobody:nfsnobody \"${MOUNTPOINT}\"\n        chmod 777 \"${MOUNTPOINT}\"\n        ls -l \"${MOUNTPOINT}\"\n    fi \n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nfunction wait_for_disk_attach() {\n    retries=$1; wait_sleep=$2; shift && shift\n\n    for i in $(seq 1 $retries); do\n        DISKS=($(scan_for_new_disks))\n        if [ \"${#DISKS[@]}\" -gt 0 ]; then\n            echo \"new disk found!\"\n            return\n        fi\n        \n        PARTITION=$(get_unmounted_disk)\n\n        if [ ${#PARTITION} -gt 0 ]; then\n            echo \"unattached disk found!\"\n            return \n        fi\n\n        echo \"no disks found, sleeping for $wait_sleep seconds\"\n        sleep $wait_sleep\n    done\n}\n\n# export the ephemeral disk as specified by $EXPORT_PATH\nfunction configure_nfs() {\n    # enable the nfs service\n    systemctl enable nfs-server rpcbind\n\n    # stop the nfs service\n    systemctl stop nfs-server rpcbind\n\n    # configure NFS export for the export path\n    grep \"^${EXPORT_PATH}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${EXPORT_PATH} is already exported. Returning...\"\n    else\n        echo -e \"\\n${EXPORT_PATH}   ${EXPORT_OPTIONS}\" >> /etc/exports\n    fi\n\n    # update to use 64 threads to get most performance\n    sed -i 's/^.*RPCNFSDCOUNT=.*$/RPCNFSDCOUNT=64/g' /etc/sysconfig/nfs\n    \n    # start the nfs service\n    systemctl start nfs-server rpcbind\n}\n\nfunction main() {\n    mkdir -p /opt\n    \n    if [ -z \"$EXPORT_PATH\" ]; then\n        echo \"env var EXPORT_PATH is not defined, please define\"\n        touch /opt/installnfs.failed\n        touch /opt/installnfs.complete\n        exit 1\n    fi\n\n    if [ -z \"$EXPORT_OPTIONS\" ]; then\n        echo \"env var EXPORT_OPTIONS is not defined, please define\"\n        touch /opt/installnfs.failed\n        touch /opt/installnfs.complete\n        exit 1\n    fi\n\n    echo \"config Linux\"\n    config_linux\n\n    # wait 10 minutes for a disk to show up\n    wait_for_disk_attach 60 10\n    \n    echo \"scan_partition_format\"\n    scan_partition_format\n\n    echo \"mount_unmounted_disk\"\n    PARTITION=$(get_unmounted_disk)\n\n    if [ ${#PARTITION} -eq 0 ]; then\n        echo \"no unmounted file system exists\"\n        touch /opt/installnfs.failed\n        touch /opt/installnfs.complete\n        return 1\n    fi\n\n    mount_disk $PARTITION\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 295}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines, and exit on error\nset -x\nset -e\n\nAZURE_HOME_DIR=/home/$ADMIN_USER_NAME\n\nfunction retrycmd_if_failure() {\n    set +e\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    set -e\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 yum -y install wget unzip git nfs-utils tmux squid\n}\n\nfunction start_squid() {\n    systemctl start squid\n    systemctl enable squid\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"start squid\"\n    start_squid\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 49}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            retrycmd_if_failure 12 5 apt-get update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt-get update\n    apt_get_install 180 10 nfs-common\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 52}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/vbash\n\n# use /bin/vbash as stated in the vyos documentation\n\n# report all lines\nset -x\n\n# required to get all the VyOS alias definitions\nsource /opt/vyatta/etc/functions/script-template\n\n# variables passed in\n# ONPREM_VTI_DUMMY_ADDRESS\n# VYOS_ADDRESS\n# VYOS_BGP_ADDRESS\n# CLOUD_ADDRESS\n# CLOUD_BGP_ADDRESS\n# PRE_SHARED_KEY\n# VYOS_ASN\n# CLOUD_ASN\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction configure_vyos() {\n    # The below configuration was based on the following VyOS documentation\n    # 1. https://docs.vyos.io/en/equuleus/automation/command-scripting.html\n    # 2. https://docs.vyos.io/en/equuleus/configexamples/azure-vpn-bgp.html\n    echo \"enter configure\"\n    configure\n    echo \"inside configure\"\n    set vpn ipsec esp-group AZURE compression 'disable'\n    set vpn ipsec esp-group AZURE lifetime '3600'\n    set vpn ipsec esp-group AZURE mode 'tunnel'\n    set vpn ipsec esp-group AZURE pfs 'dh-group2'\n    set vpn ipsec esp-group AZURE proposal 1 encryption 'aes256'\n    set vpn ipsec esp-group AZURE proposal 1 hash 'sha1'\n    set vpn ipsec ike-group AZURE dead-peer-detection action 'restart'\n    set vpn ipsec ike-group AZURE dead-peer-detection interval '15'\n    set vpn ipsec ike-group AZURE dead-peer-detection timeout '30'\n    set vpn ipsec ike-group AZURE ikev2-reauth 'yes'\n    set vpn ipsec ike-group AZURE key-exchange 'ikev2'\n    set vpn ipsec ike-group AZURE lifetime '28800'\n    set vpn ipsec ike-group AZURE proposal 1 dh-group '2'\n    set vpn ipsec ike-group AZURE proposal 1 encryption 'aes256'\n    set vpn ipsec ike-group AZURE proposal 1 hash 'sha1'\n    set vpn ipsec ipsec-interfaces interface 'eth0'\n    set interfaces vti vti1 address $ONPREM_VTI_DUMMY_ADDRESS/32\n    set interfaces vti vti1 description 'Azure Tunnel'\n    set firewall options interface vti1 adjust-mss 1350\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS authentication id $VYOS_ADDRESS\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS authentication mode 'pre-shared-secret'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS authentication pre-shared-secret $PRE_SHARED_KEY\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS authentication remote-id $CLOUD_ADDRESS\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS connection-type 'respond'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS description 'AZURE PRIMARY TUNNEL'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS ike-group 'AZURE'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS ikev2-reauth 'inherit'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS local-address $VYOS_BGP_ADDRESS\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS vti bind 'vti1'\n    set vpn ipsec site-to-site peer $CLOUD_ADDRESS vti esp-group 'AZURE'\n    set protocols static interface-route $CLOUD_BGP_ADDRESS/32 next-hop-interface vti1\n    set protocols bgp $VYOS_ASN neighbor $CLOUD_BGP_ADDRESS remote-as $CLOUD_ASN\n    set protocols bgp $VYOS_ASN neighbor $CLOUD_BGP_ADDRESS address-family ipv4-unicast soft-reconfiguration 'inbound'\n    set protocols bgp $VYOS_ASN neighbor $CLOUD_BGP_ADDRESS timers holdtime '30'\n    set protocols bgp $VYOS_ASN neighbor $CLOUD_BGP_ADDRESS timers keepalive '10'\n    set protocols bgp $VYOS_ASN neighbor $CLOUD_BGP_ADDRESS disable-connected-check\n    echo \"start commit\"\n    # add some retries for commit as there can be temporary locks on config\n    commit || (sleep 10 && commit) || (sleep 10 && commit) || (sleep 10 && commit) || (sleep 10 && commit)\n    echo \"start save\"\n    save\n    echo \"finish save\"\n    exit\n    echo \"successful exit\"\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"configure VyOS VPN Connection\"\n    configure_vyos\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 99}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines\nset -x\n\n# the following variables are set and used in this script\n#    PRIVATE_KEY\n#    PEER_PUBLIC_KEY\n#    PEER_PUBLIC_ADDRESS\n#    PEER_ADDRESS_SPACE_CSV\n#    TUNNEL_SIDE\n#    DUMMY_IP_PREFIX\n#    TUNNEL_COUNT\n#    BASE_UDP_PORT\n\nfunction retrycmd_if_failure() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            retrycmd_if_failure 12 5 apt-get update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction update_linux() {\n    retrycmd_if_failure 12 5 apt-get update\n    apt_get_install 12 5 nfs-kernel-server iotop iperf3 bwm-ng wireguard\n}\n\nfunction configure_wireguard() {\n    # add ECMP script for the wireguard interfaces\n    /bin/cat <<EOM >/usr/bin/wg-ecmp\n#!/bin/bash\nset -x\n\nPEER_ADDRESS_SPACE_CSV=\"$PEER_ADDRESS_SPACE_CSV\"\nWG_INTERFACES=\\$(wg | grep interface | awk '{ print \\$2 }')\nWGARR=(\\$WG_INTERFACES)\nWGCOUNT=\\${#WGARR[@]}\n\nif [ \\$WGCOUNT -gt 0 ] ; then\n    for AddressSpace in \\$(echo \\$PEER_ADDRESS_SPACE_CSV | sed \"s/,/ /g\"); do\n        ecmpCmd=\"ip route change \\$AddressSpace\"\n        for wg in \\$WG_INTERFACES; do\n            ecmpCmd=\"\\$ecmpCmd nexthop dev \\$wg weight 1\"\n        done\n        \\$(\\$ecmpCmd)\n    done\nfi\nEOM\n    chmod +x /usr/bin/wg-ecmp\n\n    PRIMARY=\"primary\"\n    SECONDARY=\"secondary\"\n    START_OCTET4=0\n    if [ \"$TUNNEL_SIDE\" == \"$SECONDARY\" ]; then\n        START_OCTET4=1\n    fi\n    \n    for i in $(seq 0 $(expr ${TUNNEL_COUNT} - 1)); do\n        WGIFACE=\"wg$i\"\n        PORT=$(expr ${BASE_UDP_PORT} + $i)\n        BASE_OCTET4=$(expr $i \\* 2)\n        OCTET4=$(expr ${START_OCTET4} + $i \\* 2)\n        # avoid printing secrets\n        set +x\n        /bin/cat <<EOM >/etc/wireguard/${WGIFACE}.conf\n[Interface]\nPrivateKey = ${PRIVATE_KEY}\nListenPort = ${PORT}\nAddress = ${DUMMY_IP_PREFIX}.${OCTET4}/31\nEOM\n        set -x\n\n        # add Table = off, to avoid adding routes on all but first tunnel, per guidance https://blog.muthuraj.in/2020/06/high-throughput-site-to-site-vpn-using.html?m=1\n        if [ $i -eq 0 ]; then\n            /bin/cat <<EOM >>/etc/wireguard/${WGIFACE}.conf\nPostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE\nPostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE           \nEOM\n        else\n            /bin/cat <<EOM >>/etc/wireguard/${WGIFACE}.conf\nTable = off\nPostUp = /usr/bin/wg-ecmp\nPostDown = /usr/bin/wg-ecmp\nEOM\n        fi\n\n/bin/cat <<EOM >>/etc/wireguard/${WGIFACE}.conf\n\n[Peer]\nPublicKey = ${PEER_PUBLIC_KEY}\nAllowedIPs = ${DUMMY_IP_PREFIX}.${BASE_OCTET4}/31,${PEER_ADDRESS_SPACE_CSV}\nEndpoint= ${PEER_PUBLIC_ADDRESS}:${PORT}\nPersistentKeepalive = 10\nEOM\n        sudo systemctl enable wg-quick@${WGIFACE}.service\n        sudo systemctl daemon-reload\n        sudo systemctl start wg-quick@${WGIFACE}\n    done\n\n    # enable IP forwarding, and make persistent after boot\n    sed -i 's/^#\\s*net.ipv4.ip_forward\\s*=.*/net.ipv4.ip_forward=1/' /etc/sysctl.conf\n    sysctl --system\n}\n\nfunction main() {\n    touch /opt/install.started\n\n    echo \"update linux\"\n    update_linux\n\n    echo \"install wireguard\"\n    configure_wireguard\n\n    echo \"installation complete\"\n    touch /opt/install.completed\n}\n\nmain", "num_lines": 142}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\n#\n# The following script mounts a default round robin's across the\n# vFXT ip addresses.\n#\n# Save this script to any Avere vFXT volume, for example:\n#     /bootstrap/centosbootstrap.sh\n#\n# The following environment variables must be set:\n#     NFS_IP_CSV=\"172.16.0.22,172.16.0.23,172.16.0.24\"\n#     NFS_PATH=/msazure\n#     BASE_DIR=/avere\n#     BOOTSTRAP_PATH=/b\n#     BOOTSTRAP_SCRIPT=/b/bootstrap/centosbootstrap.sh\n#     BOOTSTRAP_NFS_IP=172.16.0.22\n#     BOOTSTRAP_NFS_PATH=msazure\n#\n# This is executed as a startup task from batch, using the\n# following command line:\n#\n#     bash -c 'sudo yum -y install nfs-utils && sudo mkdir -p $BOOTSTRAP_PATH && sudo mount ${BOOTSTRAP_NFS_IP}:/${BOOTSTRAP_NFS_PATH} $BOOTSTRAP_PATH && sudo -E /bin/bash $BOOTSTRAP_SCRIPT 2>&1 | sudo tee -a /var/log/bootstrap.log && sudo umount $BOOTSTRAP_PATH && sudo rmdir $BOOTSTRAP_PATH'\n#\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction mount_round_robin() {\n    # to ensure the nodes are spread out somewhat evenly the default\n    # mount point is based on this node's IP octet4 % vFXT node count.\n    declare -a AVEREVFXT_NODES=\"($(echo ${NFS_IP_CSV} | sed \"s/,/ /g\"))\"\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n    DEFAULT_MOUNT_INDEX=$((${OCTET4} % ${#AVEREVFXT_NODES[@]}))\n    ROUND_ROBIN_IP=${AVEREVFXT_NODES[${DEFAULT_MOUNT_INDEX}]}\n\n    DEFAULT_MOUNT_POINT=\"${BASE_DIR}/default\"\n\n    # no need to write again if it is already there\n    if ! grep --quiet \"${DEFAULT_MOUNT_POINT}\" /etc/fstab; then\n        echo \"${ROUND_ROBIN_IP}:${NFS_PATH}    ${DEFAULT_MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n        mkdir -p \"${DEFAULT_MOUNT_POINT}\"\n        chown nfsnobody:nfsnobody \"${DEFAULT_MOUNT_POINT}\"\n    fi\n    if ! grep -qs \"${DEFAULT_MOUNT_POINT} \" /proc/mounts; then\n        retrycmd_if_failure 12 20 mount \"${DEFAULT_MOUNT_POINT}\" || exit 1\n    fi\n}\n\nfunction main() {\n    echo \"mount round robin default path\"\n    mount_round_robin\n\n    # add extra bootstrap code here\n}\n\nmain", "num_lines": 70}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\n#\n# The following script render a generic maya scene.\n#\n# Save this script to any Avere vFXT volume, for example:\n#     /src/render.sh\n#\n# The following environment variables must be set:\n#     FRAME_START=1\n#     FRAME_END=1\n#     MAYA_PROJECT_PATH=/nfs/default/demoscene\n#     SCENE_FILE=/nfs/default/demoscene/kongSkeleton_walk.ma\n#     IMAGES_OUTPUT_BASE_PATH=/nfs/default/images\n#     ADDITIONAL_FLAGS=\" -of png \"\n#\n# This is executed as the render job from batch, using the\n# following command line:\n#\n#     /bin/bash -c '/bin/bash [parameters('renderScriptPath')] ; err=$? ; exit $err'\n#\n\n# if doing real work, remove or set to false\nIS_DEMO=true\n\nfunction render_scene() {\n    if [ \"${IS_DEMO}\" = true ] ; then\n        # clear client caches - good for demo, but not good for real job\n        echo     3 | sudo tee /proc/sys/vm/drop_caches > /dev/null\n    fi\n\n    # render the scene\n    echo \"running command: /bin/maya2018.sh -r sw ${ADDITIONAL_FLAGS} -proj ${MAYA_PROJECT_PATH} -rd ${IMAGES_OUTPUT_BASE_PATH}/${AZ_BATCH_JOB_ID} -s ${FRAME_START} -e ${FRAME_END} ${SCENE_FILE}\"\n    /bin/maya2018.sh -r sw ${ADDITIONAL_FLAGS} -proj ${MAYA_PROJECT_PATH} -rd ${IMAGES_OUTPUT_BASE_PATH}/${AZ_BATCH_JOB_ID} -s ${FRAME_START} -e ${FRAME_END} ${SCENE_FILE}\n}\n\nfunction main() {\n    render_scene\n\n    # add extra render code here\n}\n\nmain", "num_lines": 45}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n#\n# Save this script to any Avere vFXT volume, for example:\n#     /src/render8gb.sh\n#\n# The following environment variables must be set:\n#     FRAME_START=1\n#     FRAME_END=1\n#     MAYA_PROJECT_PATH=/nfs/default/scenes/8gbscene\n#     SCENE_FILE=/nfs/default/scenes/8gbscene/scenes/SEQ001/SHOT001/anim/versions/SEQ001_SHOT001_anim_v010_Imported.ma\n#     IMAGES_OUTPUT_BASE_PATH=/nfs/default/images\n#     DEBUG_PATH=/nfs/default/debug\n#     ADDITIONAL_FLAGS=\" -of png \"\n#\n# This is executed as the render job from batch, using the\n# following command line:\n#\n#     /bin/bash -c '/bin/bash [parameters('renderScriptPath')] ; err=$? ; exit $err'\n#\n\n# if doing real work, remove or set to false\nIS_DEMO=true\n\nfunction log_debug_info() {\n    set\n    mount\n    whoami\n\n    # add empty file named after this machine's ip to the mount folder for the job\n    MOUNT_POINT=`mount | grep default | sed -e 's/^\\([^:]*\\):.*/\\1/'`\n    THIS_HOST=`hostname -i`\n    DEBUG_TARGET_DIR=${DEBUG_PATH}/${AZ_BATCH_JOB_ID}/${MOUNT_POINT}\n    mkdir -p ${DEBUG_TARGET_DIR}\n    touch ${DEBUG_TARGET_DIR}/${THIS_HOST}\n}\n\nfunction stagger_on_first_task_round_algorithm1() {\n    # stagger the first round of jobs over 6 minutes, but only for the first set of tasks\n    TASK_COUNT_FOR_NODE=`find ${AZ_BATCH_NODE_ROOT_DIR}/workitems/${AZ_BATCH_JOB_ID}/. -maxdepth 3 -type d | grep wd | wc -l`\n    if [ \"${TASK_COUNT_FOR_NODE}\" -le \"${MAX_TASKS_PER_NODE}\" ] ; then\n        SLEEP_TIME=$(($RANDOM % 360))\n        echo \"staggering by sleeping for ${SLEEP_TIME} seconds (${TASK_COUNT_FOR_NODE} < ${MAX_TASKS_PER_NODE})\"\n        sleep ${SLEEP_TIME}\n    else\n        echo \"no stagger because ${TASK_COUNT_FOR_NODE} >= ${MAX_TASKS_PER_NODE}\"\n    fi\n}\n\nfunction stagger_on_first_task_round_algorithm2() {\n    # stagger the first round of jobs over 6 minutes, but only for the first set of tasks\n    TASK_COUNT_FOR_NODE=`find ${AZ_BATCH_NODE_ROOT_DIR}/workitems/${AZ_BATCH_JOB_ID}/. -maxdepth 3 -type d | grep wd | wc -l`\n    if [ \"${TASK_COUNT_FOR_NODE}\" -le \"${MAX_TASKS_PER_NODE}\" ] ; then\n        NODE_ID=`echo $AZ_BATCH_NODE_ID | sed -e 's/^.*_\\([0-9]*\\)-.*/\\1/'`\n        SLEEP_TIME=$((($NODE_ID/5)*7))\n        echo \"staggering by sleeping for ${SLEEP_TIME} seconds (${TASK_COUNT_FOR_NODE} < ${MAX_TASKS_PER_NODE})\"\n        sleep ${SLEEP_TIME}\n    else\n        echo \"no stagger because ${TASK_COUNT_FOR_NODE} >= ${MAX_TASKS_PER_NODE}\"\n    fi\n}\n\nfunction run_demo_code() {\n    # clear client caches - good for demo, but not good for real job\n    echo \"clearing client cache by running '3 | sudo tee /proc/sys/vm/drop_caches > /dev/null'\"\n    echo     3 | sudo tee /proc/sys/vm/drop_caches > /dev/null\n}\n\nfunction render_scene() {\n    # render the scene\n    echo \"running command: /bin/maya2018.sh -r sw ${ADDITIONAL_FLAGS} -proj ${MAYA_PROJECT_PATH} -rd ${IMAGES_OUTPUT_BASE_PATH}/${AZ_BATCH_JOB_ID} -s ${FRAME_START} -e ${FRAME_END} ${SCENE_FILE}\"\n    /bin/maya2018.sh -r sw ${ADDITIONAL_FLAGS} -proj ${MAYA_PROJECT_PATH} -rd ${IMAGES_OUTPUT_BASE_PATH}/${AZ_BATCH_JOB_ID} -s ${FRAME_START} -e ${FRAME_END} ${SCENE_FILE}\n}\n\nfunction main() {\n\n    log_debug_info\n\n    #stagger_on_first_task_round_algorithm1\n    stagger_on_first_task_round_algorithm2\n\n    if [ \"${IS_DEMO}\" = true ] ; then\n        run_demo_code\n    fi\n\n    render_scene\n\n    # add extra render code here\n}\n\nmain", "num_lines": 92}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# EXPORT_PATH=/data\n# EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\"\n#\n# called like this:\n#  sudo EXPORT_PATH=/data EXPORT_OPTIONS=\"*(rw,sync,no_root_squash)\" ./installnfs.sh\n#\n\n# terraform variables: tf_env_variables\n\nset -x\n\nfunction yum_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        yum install -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            touch /opt/installnfs.failed\n            exit 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    echo \"completed\"\n    echo Executed yum install -y \\\"$@\\\" $i times;\n\n    yum install -y nfs-utils\n}\n\nfunction config_linux() {\n\tyum_install 20 10 180 nfs-utils\n}\n\n# export the ephemeral disk as specified by $EXPORT_PATH\nfunction configure_nfs() {\n    # enable the nfs service\n    systemctl enable nfs-server rpcbind\n\n    # stop the nfs service\n    systemctl stop nfs-server rpcbind\n\n    mkdir -p $EXPORT_PATH\n\n    grep -e \"/mnt\\s\" /etc/fstab > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        # this is managed by the new cloud init\n\n        # export the ephemeral disk\n        EPHEMERAL_DISK_PATH=\"/mnt\"\n        umount $EPHEMERAL_DISK_PATH\n        sed -i \"s:${EPHEMERAL_DISK_PATH}:${EXPORT_PATH}:g\" /etc/fstab\n        mount ${EXPORT_PATH}\n    else \n        # this is managed by older waagent\n\n        # export the ephemeral disk\n        EPHEMERAL_DISK_PATH=\"/mnt/resource\"\n        # move the ephemeral mount to the mount chosen by the customer\n        # we cannot do the symbolic link because it is not supported by nfsv4\n        umount $EPHEMERAL_DISK_PATH\n        sed -i \"s:${EPHEMERAL_DISK_PATH}:${EXPORT_PATH}:g\" /etc/waagent.conf\n        # restart waagent to mount the new share\n        systemctl restart waagent\n    fi\n    \n    # configure NFS export for the export path\n    grep \"^${EXPORT_PATH}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${EXPORT_PATH} is already exported. Returning...\"\n    else\n        echo -e \"\\n${EXPORT_PATH}   ${EXPORT_OPTIONS}\" >> /etc/exports\n    fi\n\n    # update to use 64 threads to get most performance\n    sed -i 's/^.*RPCNFSDCOUNT=.*$/RPCNFSDCOUNT=64/g' /etc/sysconfig/nfs\n    \n    # start the nfs service\n    systemctl start nfs-server rpcbind\n}\n\nfunction main() {\n    mkdir -p /opt\n    \n    if [ -z \"$EXPORT_PATH\" ]; then\n        echo \"env var EXPORT_PATH is not defined, please define\"\n        touch /opt/installnfs.failed\n        exit 1\n    fi\n\n    if [ -z \"$EXPORT_OPTIONS\" ]; then\n        echo \"env var EXPORT_OPTIONS is not defined, please define\"\n        touch /opt/installnfs.failed\n        exit 1\n    fi\n\n    echo \"config Linux\"\n    config_linux\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n\n    touch /opt/installnfs.complete\n}\n\nmain\n", "num_lines": 112}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# DATA_BASE=/datadisks\n#\n# called like this:\n#  sudo DATA_BASE=/datadisks ./installnfs.sh\n#\n\nMOUNT_OPTIONS=\"noatime,nodiratime,nodev,noexec,nosuid,nofail\"\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        # timeout occasionally freezes\n        #echo \"timeout $timeout apt-get install --no-install-recommends -y ${@}\"\n        #timeout $timeout apt-get install --no-install-recommends -y ${@}\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n\t#hostname=`hostname -s`\n\t#sudo sed -ie \"s/127.0.0.1 localhost/127.0.0.1 localhost ${hostname}/\" /etc/hosts\n\texport DEBIAN_FRONTEND=noninteractive  \n\tapt_get_update\n\tapt_get_install 20 10 180 nfs-kernel-server nfs-common\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction is_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction has_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\t${MOUNT_OPTIONS}\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction do_partition() {\n    # This function creates one (1) primary partition on the\n    # disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=83\n    fi\n    echo \"n\np\n1\n\n\nt\n${_type}\nw\"| fdisk \"${_disk}\"\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from fdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${_disk}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nget_next_mountpoint() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    MAX=$(echo \"${DIRS}\"|tail -n 1 | tr -d \"[a-zA-Z/]\")\n    if [ -z \"${MAX}\" ];\n    then\n        echo \"${DATA_BASE}/disk1\"\n        return\n    fi\n    IDX=1\n    while [ \"${IDX}\" -lt \"${MAX}\" ];\n    do\n        NEXT_DIR=\"${DATA_BASE}/disk${IDX}\"\n        if [ ! -d \"${NEXT_DIR}\" ];\n        then\n            echo \"${NEXT_DIR}\"\n            return\n        fi\n        IDX=$(( ${IDX} + 1 ))\n    done\n    IDX=$(( ${MAX} + 1))\n    echo \"${DATA_BASE}/disk${IDX}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_partition_format()\n{\n    echo \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n\tif [ \"${#DISKS}\" -eq 0 ];\n\tthen\n\t    echo \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\techo \"Disks are ${DISKS[@]}\"\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK}\n\t    fi\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n\t    has_filesystem ${PARTITION}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"Creating filesystem on ${PARTITION}.\"\n\t        mkfs -j -t ext4 ${PARTITION}\n\t    fi\n\t    MOUNTPOINT=$(get_next_mountpoint)\n\t    echo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t    if [ ! -d \"${MOUNTPOINT}\" ];\n        then\n            mkdir -p \"${MOUNTPOINT}\"\n            chown nobody:nogroup \"${MOUNTPOINT}\"\n            chmod 777 \"${MOUNTPOINT}\"\n            ls -l \"${MOUNTPOINT}\"\n        fi \n\t    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\t    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\t    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n\t    mount \"${MOUNTPOINT}\"\n\tdone\n}\n\n# export all the disks under ${DATA_BASE} for NFS\nfunction configure_nfs() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    for MOUNTPOINT in \"${DIRS[@]}\";\n\tdo\n        # configure NFS export for the disk\n        grep \"^${MOUNTPOINT}\" /etc/exports > /dev/null 2>&1\n        if [ $? = \"0\" ]; then\n            echo \"${MOUNTPOINT} is already exported. Returning...\"\n        else\n            echo -e \"\\n${MOUNTPOINT}   *(rw,sync,no_root_squash)\" >> /etc/exports\n        fi\n    done\n    \n    systemctl enable nfs-kernel-server.service\n    systemctl restart nfs-kernel-server.service\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n\n    echo \"scan_partition_format\"\n    scan_partition_format\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n}\n\nmain\n", "num_lines": 243}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n#\n# The following script mounts a default round robin's across the\n# vFXT ip addresses.\n#\n\n# the comma separated Avere vFXT vServer IP addresses\nexport NFS_IP_CSV=\"10.0.0.22,10.0.0.23,10.0.0.24\"\nexport TARGET_IP_EASTUS=192.168.255.4\nexport TARGET_IP_WESTUS=192.168.255.20\nexport TARGET_IP_WESTINDIA=192.168.255.52\nexport TARGET_IP_SOUTHEASTASIA=192.168.255.36\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction mount_target() {\n    NFS_PATH=$1\n    TARGET_MOUNT_POINT=$2\n    TARGET_IP=$3\n    if ! grep --quiet \"${TARGET_IP}:${NFS_PATH}\" /etc/fstab; then\n        echo \"${TARGET_IP}:${NFS_PATH}    ${TARGET_MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n        mkdir -p \"${TARGET_MOUNT_POINT}\"\n        chown nfsnobody:nfsnobody \"${TARGET_MOUNT_POINT}\"\n    fi\n    if ! grep -qs \"${TARGET_MOUNT_POINT} \" /proc/mounts; then\n        retrycmd_if_failure 12 20 mount \"${TARGET_MOUNT_POINT}\" || exit 1\n    fi\n}\n\nfunction mount_round_robin_e32() {\n    # to ensure the nodes are spread out somewhat evenly the default\n    # mount point is based on this node's IP octet4 % vFXT node count.\n    declare -a AVEREVFXT_NODES=\"($(echo ${NFS_IP_CSV} | sed \"s/,/ /g\"))\"\n    OCTET4=$((`hostname -i | sed -e 's/^.*\\.\\([0-9]*\\)/\\1/'  | sed 's/[^0-9]*//g'`))\n    DEFAULT_MOUNT_INDEX=$((${OCTET4} % ${#AVEREVFXT_NODES[@]}))\n    ROUND_ROBIN_IP=${AVEREVFXT_NODES[${DEFAULT_MOUNT_INDEX}]}\n\n    NFS_PATH=\"/eastus\"\n    TARGET_MOUNT_POINT=\"/nfs/${NFS_PATH}vfxt\"\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $ROUND_ROBIN_IP\n\n    NFS_PATH=\"/westus\"\n    TARGET_MOUNT_POINT=\"/nfs/${NFS_PATH}vfxt\"\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $ROUND_ROBIN_IP\n\n    NFS_PATH=\"/westindia\"\n    TARGET_MOUNT_POINT=\"/nfs/${NFS_PATH}vfxt\"\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $ROUND_ROBIN_IP\n\n    NFS_PATH=\"/southeastasia\"\n    TARGET_MOUNT_POINT=\"/nfs/${NFS_PATH}vfxt\"\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $ROUND_ROBIN_IP\n}\n\nfunction mount_regional_cluster() {\n    # no need to write again if it is already there\n    NFS_PATH=/datadisks/disk1\n\n    TARGET_MOUNT_POINT=/nfs/eastus\n    TARGET_IP=$TARGET_IP_EASTUS\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $TARGET_IP\n\n    TARGET_MOUNT_POINT=/nfs/westus\n    TARGET_IP=$TARGET_IP_WESTUS\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $TARGET_IP\n\n    TARGET_MOUNT_POINT=/nfs/westindia\n    TARGET_IP=$TARGET_IP_WESTINDIA\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $TARGET_IP\n\n    TARGET_MOUNT_POINT=/nfs/southeastasia\n    TARGET_IP=$TARGET_IP_SOUTHEASTASIA\n    mount_target $NFS_PATH $TARGET_MOUNT_POINT $TARGET_IP\n}\n\nfunction main() {\n    echo \"mount the regional cluster\"\n    mount_regional_cluster\n\n    echo \"mount round robin the e32 vfxt default path\"\n    mount_round_robin_e32\n\n    # add extra bootstrap code here\n}\n\nmain\n", "num_lines": 102}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n\n#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\nset -x\n\nfunction wait_vfxt_log() {\n    mountpoint=$1\n    while :\n    do\n\n        if timeout 5 ls $mountpoint; then\n            echo \"mount is live\"\n            break\n        fi\n        echo \"$(date) mount is frozen\"\n    done\n}\n\nexport DstSub=\"b52fce95-de5f-4b37-afca-db203a5d0b6a\"\nexport DstResourceGroupName=\"avereeastusbatch\"\nexport DstLocation=\"eastus\"\nexport BatchAccountName=\"avereeastusbatch\"\naz account set --subscription $DstSub\naz batch account login --resource-group $DstResourceGroupName --name $BatchAccountName\nwait_vfxt_log \"/nfs/node0\"", "num_lines": 28}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# variables that must be set beforehand\n# DATA_BASE=/datadisks\n#\n# called like this:\n#  sudo DATA_BASE=/datadisks ./installnfs.sh\n#\n\nMOUNT_OPTIONS=\"noatime,nodiratime,nodev,noexec,nosuid,nofail\"\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        # timeout occasionally freezes\n        #echo \"timeout $timeout apt-get install --no-install-recommends -y ${@}\"\n        #timeout $timeout apt-get install --no-install-recommends -y ${@}\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo \"failed\"\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n\t#hostname=`hostname -s`\n\t#sudo sed -ie \"s/127.0.0.1 localhost/127.0.0.1 localhost ${hostname}/\" /etc/hosts\n\texport DEBIAN_FRONTEND=noninteractive  \n\tapt_get_update\n\tapt_get_install 20 10 180 nfs-kernel-server nfs-common\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction is_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction has_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\t${MOUNT_OPTIONS}\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction do_partition() {\n    # This function creates one (1) primary partition on the\n    # disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=83\n    fi\n    echo \"n\np\n1\n\n\nt\n${_type}\nw\"| fdisk \"${_disk}\"\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from fdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${_disk}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nget_next_mountpoint() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    MAX=$(echo \"${DIRS}\"|tail -n 1 | tr -d \"[a-zA-Z/]\")\n    if [ -z \"${MAX}\" ];\n    then\n        echo \"${DATA_BASE}/disk1\"\n        return\n    fi\n    IDX=1\n    while [ \"${IDX}\" -lt \"${MAX}\" ];\n    do\n        NEXT_DIR=\"${DATA_BASE}/disk${IDX}\"\n        if [ ! -d \"${NEXT_DIR}\" ];\n        then\n            echo \"${NEXT_DIR}\"\n            return\n        fi\n        IDX=$(( ${IDX} + 1 ))\n    done\n    IDX=$(( ${MAX} + 1))\n    echo \"${DATA_BASE}/disk${IDX}\"\n}\n\n# source from https://github.com/Azure/azure-quickstart-templates/blob/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\nfunction scan_partition_format()\n{\n    echo \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n\tif [ \"${#DISKS}\" -eq 0 ];\n\tthen\n\t    echo \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\techo \"Disks are ${DISKS[@]}\"\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK}\n\t    fi\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n\t    has_filesystem ${PARTITION}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"Creating filesystem on ${PARTITION}.\"\n\t        mkfs -j -t ext4 ${PARTITION}\n\t    fi\n\t    MOUNTPOINT=$(get_next_mountpoint)\n\t    echo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t    if [ ! -d \"${MOUNTPOINT}\" ];\n        then\n            mkdir -p \"${MOUNTPOINT}\"\n            chown nobody:nogroup \"${MOUNTPOINT}\"\n            chmod 777 \"${MOUNTPOINT}\"\n            ls -l \"${MOUNTPOINT}\"\n        fi \n\t    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\t    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\t    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n\t    mount \"${MOUNTPOINT}\"\n\tdone\n}\n\n# export all the disks under ${DATA_BASE} for NFS\nfunction configure_nfs() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    for MOUNTPOINT in \"${DIRS[@]}\";\n\tdo\n        # configure NFS export for the disk\n        grep \"^${MOUNTPOINT}\" /etc/exports > /dev/null 2>&1\n        if [ $? = \"0\" ]; then\n            echo \"${MOUNTPOINT} is already exported. Returning...\"\n        else\n            echo -e \"\\n${MOUNTPOINT}   *(rw,sync,no_root_squash)\" >> /etc/exports\n        fi\n    done\n    \n    systemctl enable nfs-kernel-server.service\n    systemctl restart nfs-kernel-server.service\n}\n\nfunction main() {\n    echo \"config Linux\"\n    config_linux\n\n    echo \"scan_partition_format\"\n    scan_partition_format\n\n    echo \"setup NFS Server\"\n    configure_nfs\n    \n    echo \"installation complete\"\n}\n\nmain\n", "num_lines": 244}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n###########################################################\n#\n# Watch vfxt.log and enable cloud trace after the\n# management IP is received, and disable cloud trace after\n# the script has finished.  The purpose of cloud trace is\n# for additional debugging information during installation.\n#\n# Ensure completion by stopping if the vfxt.log file does\n# not show up or if the installation script stops, and\n# vfxt.log stops being updated.\n#\n###########################################################\n\n# report all lines, and exit on error\nset -x\n\n# this script will handle all its errors, so don't set -e\n# set -e\n\nAZURE_HOME_DIR=/home/$CONTROLLER_ADMIN_USER_NAME\nVFXT_LOG_FILE=$AZURE_HOME_DIR/vfxt.log\nWAIT_SECONDS=300\nRPC_ENABLE=\"enable\"\nRPC_DISABLE=\"disable\"\n\nfunction sendRPC() {\n    set +x\n    ipaddress=$1; action=$2\n\n    AVERECMD=\"averecmd --raw --no-check-certificate --user admin --password $ADMIN_PASSWORD --server $ipaddress\"\n    if [ \"$action\" == \"$RPC_ENABLE\" ] ; then\n        echo \"send 'support.acceptTerms yes' to ${ipaddress}\"\n        $AVERECMD support.acceptTerms yes\n        result=$?\n\n        echo \"send ${action} to ${ipaddress}\"\n        $AVERECMD support.modify \"{'traceLevel': '0xE00000000100', 'rollingTrace': 'yes', 'statsMonitor': 'yes', 'memoryDebugging': 'yes'}\"\n        result=$((result+$?))\n    elif [ \"$action\" == \"$RPC_DISABLE\" ] ; then\n        echo \"send ${action} to ${ipaddress}\"\n        $AVERECMD support.modify \"{'traceLevel': '0x1', 'rollingTrace': 'no', 'statsMonitor': 'no', 'memoryDebugging': 'no'}\"\n        result=$?\n    else\n        echo \"ERROR: bad action\"\n        result=1\n    fi\n\n    set -x\n    return $result\n}\n\nfunction check_halted_vfxt() {\n    now=$(date +%s)\n    filemtime=$(stat -c %Y $VFXT_LOG_FILE)\n    difference=$(($now-$filemtime))\n    if [ \"$difference\" -gt \"$WAIT_SECONDS\" ] ; then\n        echo \"FATAL: the log file ${VFXT_LOG_FILE} has halted\"\n        exit 1\n    fi\n}\n\nfunction wait_vfxt_log() {\n    counter=0\n    while [ ! -f $VFXT_LOG_FILE ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"file '${VFXT_LOG_FILE}' did not appear after ${WAIT_SECONDS} seconds\"\n            exit 1\n        fi\n    done\n}\n\nfunction wait_management_ip() {\n    while :\n    do\n        ipaddress=$(egrep \"^address=([0-9]{1,3}\\.){3}[0-9]{1,3}\" ${VFXT_LOG_FILE} | awk '{match($0,/[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+/); ip = substr($0,RSTART,RLENGTH); print ip}')\n        if [ \"${#ipaddress}\" -gt \"0\" ]\n        then\n            echo \"${ipaddress}\"\n            break\n        fi\n        check_halted_vfxt\n        sleep 1\n    done\n}\n\nfunction wait_complete_message() {\n    while :\n    do\n        if grep --quiet \"vfxt:INFO - Complete\" ${VFXT_LOG_FILE}; then\n            echo \"vfxt has completed installation\"\n            break\n        elif grep --quiet \"vfxt:ERROR - Failed to create cluster\" ${VFXT_LOG_FILE}; then\n            echo \"vfxt installation failed\"\n            break\n        fi\n        check_halted_vfxt\n        sleep 1\n    done\n}\n\nfunction enable_cloud_trace() {\n    ipaddress=$1\n    echo \"trying to enable cloud trace \"\n\n    while :\n    do\n        # retry forever until we reach the mgmt ip or the vfxt.log stops\n        if sendRPC $ipaddress $RPC_ENABLE ; then\n            echo \"sendRPC success\"\n            break\n        fi\n\n        check_halted_vfxt\n        sleep 5\n    done\n\n    echo \"cloud trace enabled\"\n}\n\nfunction disable_cloud_trace() {\n    ipaddress=$1\n    echo \"trying to disable cloud trace \"\n\n    while :\n    do\n        # retry forever until we reach the mgmt ip or the vfxt.log stops\n        if sendRPC $ipaddress $RPC_DISABLE ; then\n            echo \"sendRPC success\"\n            break\n        fi\n\n        check_halted_vfxt\n        sleep 5\n    done\n\n    echo \"cloud trace disabled\"\n}\n\nfunction main() {\n    echo \"wait for vfxt log file to appear\"\n    wait_vfxt_log\n\n    MGMT_IP=$(wait_management_ip)\n\n    enable_cloud_trace $MGMT_IP\n\n    wait_complete_message\n\n    disable_cloud_trace $MGMT_IP\n}\n\nmain", "num_lines": 156}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# report all lines, and exit on error\nset -x\nset -e\n\nARM_TRUE=\"True\"\nWAIT_SECONDS=600\nAZURE_HOME_DIR=/home/$CONTROLLER_ADMIN_USER_NAME\nVFXT_INSTALL_TEMPLATE=$AZURE_HOME_DIR/vfxtinstall\nCLOUD_BACKED_TEMPLATE=/create-cloudbacked-cluster\nMINIMAL_TEMPLATE=/create-minimal-cluster\nVFXT_LOG_FILE=$AZURE_HOME_DIR/vfxt.log\nARM_ENDPOINT=https://management.azure.com/metadata/endpoints?api-version=2017-12-01\n\nfunction retrycmd_if_failure() {\n    set +e\n    retries=$1; wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n        fi\n    done\n    set -e\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction wait_azure_home_dir() {\n    counter=0\n    while [ ! -d $AZURE_HOME_DIR ]; do\n        sleep 1\n        counter=$((counter + 1))\n        if [ $counter -ge $WAIT_SECONDS ]; then\n            echo \"directory $AZURE_HOME_DIR not available after waiting $WAIT_SECONDS seconds\"\n            exit 1\n        fi\n    done\n}\n\nfunction wait_arm_endpoint() {\n    # ensure the arm endpoint is reachable\n    # https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service#getting-azure-environment-where-the-vm-is-running\n    if ! retrycmd_if_failure 24 5 curl -m 5 -o /dev/null $ARM_ENDPOINT ; then\n        echo \"no internet! arm endpoint $ARM_ENDPOINT not reachable.  Please see https://github.com/Azure/Avere/tree/main/src/vfxt#internet-access on how to configure firewall, dns, or proxy.\"\n        exit 1\n    fi\n}\n\nfunction wait_az_login_and_vnet() {\n    # wait for RBAC assignments to be applied\n    # unfortunately, the RBAC assignments take undetermined time past their associated resource completions to be assigned.\n    if ! retrycmd_if_failure 120 5 az login --identity ; then\n        echo \"MANAGED IDENTITY FAILURE: failed to login after waiting 10 minutes, this is managed identity bug\"\n        exit 1\n    fi\n    if ! retrycmd_if_failure 12 5 az account set --subscription $SUBSCRIPTION_ID ; then\n        echo \"MANAGED IDENTITY FAILURE: failed to set subscription\"\n        exit 1\n    fi\n    if ! retrycmd_if_failure 120 5 az network vnet subnet list -g $NETWORK_RESOURCE_GROUP --vnet-name $NETWORK ; then\n        echo \"RBAC ASSIGNMENT FAILURE: failed to list vnet after waiting 10 minutes, this is rbac assignment bug\"\n        exit 1\n    fi\n}\n\nfunction configure_vfxt_template() {\n    if [ \"$CREATE_CLOUD_BACKED_CLUSTER\" == \"$ARM_TRUE\" ]; then\n        cp $CLOUD_BACKED_TEMPLATE $VFXT_INSTALL_TEMPLATE\n    else\n        cp $MINIMAL_TEMPLATE $VFXT_INSTALL_TEMPLATE\n    fi\n\n    # update the internal variables\n    sed -i 's/^RESOURCE_GROUP/#RESOURCE_GROUP/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^LOCATION/#LOCATION/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^NETWORK/#NETWORK/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^SUBNET/#SUBNET/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^AVERE_CLUSTER_ROLE/#AVERE_CLUSTER_ROLE/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^STORAGE_ACCOUNT/#STORAGE_ACCOUNT/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^CACHE_SIZE/#CACHE_SIZE/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^CLUSTER_NAME/#CLUSTER_NAME/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^ADMIN_PASSWORD/#ADMIN_PASSWORD/g' $VFXT_INSTALL_TEMPLATE\n    sed -i 's/^INSTANCE_TYPE/#INSTANCE_TYPE/g' $VFXT_INSTALL_TEMPLATE\n    # replace \"--from-environment\" with \"--on-instance\" since we are using\n    sed -i 's/ --from-environment / --on-instance /g' $VFXT_INSTALL_TEMPLATE\n    sed -i \"s:~/vfxt.log:$VFXT_LOG_FILE:g\"  $VFXT_INSTALL_TEMPLATE\n    # do not trace password in log, instead the command is captured in file ~/create_cluster_command.log, with password correctly redacted\n    sed -i \"s/^set -exu/set -eu/g\"  $VFXT_INSTALL_TEMPLATE\n}\n\nfunction create_vfxt() {\n    #######################################################\n    # do not trace passwords\n    #######################################################\n    set -x\n    #######################################################\n\n    cd $AZURE_HOME_DIR\n    # enable cloud trace during installation\n    if [ \"${ENABLE_CLOUD_TRACE_DEBUG}\" == \"${ARM_TRUE}\" ] ; then\n        nohup /bin/bash /opt/avere/enablecloudtrace.sh > $AZURE_HOME_DIR/enablecloudtrace.log 2>&1 &\n    fi\n    # ensure the create cluster command is recorded for the future\n    sleep 2 && ps -a -x -o cmd | egrep '[v]fxt.py' |  sed 's/--admin-password [^ ]*/--admin-password ***/' > create_cluster_command.log &\n    $VFXT_INSTALL_TEMPLATE\n\n    #######################################################\n    # re-enable tracing\n    #######################################################\n    set +x\n    #######################################################\n}\n\nfunction print_vfxt_vars() {\n    echo \"VSERVER_IPS=$(sed -n \"s/^.*Creating vserver vserver (\\(.*\\)\\/255.255.255.255).*$/\\1/p\" $VFXT_LOG_FILE)\"\n    echo \"MGMT_IP=$(sed -n \"s/^.*management address: \\(.*\\)/\\1/p\" $VFXT_LOG_FILE)\"\n}\n\nfunction dump_env_vars() {\n    echo \"start env dump\"\n    echo $(pwd)\n    echo \"export RESOURCE_GROUP=$RESOURCE_GROUP\"\n    echo \"export LOCATION=$LOCATION\"\n    echo \"export NETWORK_RESOURCE_GROUP=$NETWORK_RESOURCE_GROUP\"\n    echo \"export NETWORK=$NETWORK\"\n    echo \"export SUBNET=$SUBNET\"\n    echo \"export AVERE_CLUSTER_ROLE=$AVERE_CLUSTER_ROLE\"\n    echo \"export CREATE_CLOUD_BACKED_CLUSTER=$CREATE_CLOUD_BACKED_CLUSTER\"\n    echo \"export STORAGE_ACCOUNT=$STORAGE_ACCOUNT\"\n    echo \"export CACHE_SIZE=$CACHE_SIZE\"\n    echo \"export CLUSTER_NAME=$CLUSTER_NAME\"\n    echo \"export INSTANCE_TYPE=$INSTANCE_TYPE\"\n    echo \"export ADMIN_PASSWORD=$ADMIN_PASSWORD\"\n    echo \"finish env dump\"\n}\n\nfunction apt_get_update() {\n    set +e\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 300 apt-get update 2>&1\n        [ $? -eq 0  ] && break\n        if [ $i -eq $retries ]; then\n            set -e\n            return 1\n        else sleep 30\n        fi\n    done\n    set +e\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    set +e\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        # timeout occasionally freezes\n        #echo \"timeout $timeout apt-get install --no-install-recommends -y ${@}\"\n        #timeout $timeout apt-get install --no-install-recommends -y ${@}\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            set -e\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    set -e\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction main() {\n    # ensure waagent upgrade does not interrupt this CSE\n    retrycmd_if_failure 240 5 apt-mark hold walinuxagent\n\n    echo \"wait arm endpoint\"\n    wait_arm_endpoint\n\n    echo \"wait azure home dir\"\n    wait_azure_home_dir\n\n    echo \"wait az login\"\n    wait_az_login_and_vnet\n\n    #echo \"dump env vars for debugging\"\n    #dump_env_vars\n\n    echo \"configure vfxt install template\"\n    configure_vfxt_template\n\n    echo \"create_vfxt\"\n    create_vfxt\n\n    echo \"print vfxt vars\"\n    print_vfxt_vars\n\n    # ensure waagent upgrade can proceed\n    retrycmd_if_failure 300 15 apt-mark unhold walinuxagent\n\n    echo \"installation complete\"\n}\n\nmain\n", "num_lines": 213}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nNODE_MOUNT_PREFIX=\"/node\"\n\nfunction retrycmd_if_failure() {\n    retries=$1; max_wait_sleep=$2; shift && shift\n    for i in $(seq 1 $retries); do\n        ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            echo Executed \\\"$@\\\" $i times;\n            return 1\n        else\n            sleep $(($RANDOM % $max_wait_sleep))\n        fi\n    done\n    echo Executed \\\"$@\\\" $i times;\n}\n\nfunction apt_get_update() {\n    retries=10\n    apt_update_output=/tmp/apt-get-update.out\n    for i in $(seq 1 $retries); do\n        timeout 120 apt-get update 2>&1 | tee $apt_update_output | grep -E \"^([WE]:.*)|([eE]rr.*)$\"\n        [ $? -ne 0  ] && cat $apt_update_output && break || \\\n        cat $apt_update_output\n        if [ $i -eq $retries ]; then\n            return 1\n        else sleep 30\n        fi\n    done\n    echo Executed apt-get update $i times\n}\n\nfunction apt_get_install() {\n    retries=$1; wait_sleep=$2; timeout=$3; shift && shift && shift\n    for i in $(seq 1 $retries); do\n        apt-get install --no-install-recommends -y ${@}\n        [ $? -eq 0  ] && break || \\\n        if [ $i -eq $retries ]; then\n            return 1\n        else\n            sleep $wait_sleep\n            apt_get_update\n        fi\n    done\n    echo \"completed\"\n    echo Executed apt-get install --no-install-recommends -y \\\"$@\\\" $i times;\n}\n\nfunction config_linux() {\n    export DEBIAN_FRONTEND=noninteractive\n    apt_get_update\n    apt_get_install 20 10 180 default-jre zip csh unzip\n}\n\nfunction mount_avere() {\n    COUNTER=0\n    for VFXT in $(echo $NFS_IP_CSV | sed \"s/,/ /g\")\n    do\n        MOUNT_POINT=\"${BASE_DIR}${NODE_MOUNT_PREFIX}${COUNTER}\"\n        echo \"Mounting to ${VFXT}:${NFS_PATH} to ${MOUNT_POINT}\"\n        mkdir -p $MOUNT_POINT\n        # no need to write again if it is already there\n        if grep -F --quiet \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}\" /etc/fstab; then\n            echo \"not updating file, already there\"\n        else\n            echo \"${VFXT}:${NFS_PATH}    ${MOUNT_POINT}    nfs hard,nointr,proto=tcp,mountproto=tcp,retry=30 0 0\" >> /etc/fstab\n            mount ${MOUNT_POINT}\n        fi\n        COUNTER=$(($COUNTER + 1))\n    done\n}\n\nfunction setup_staf_server() {\n    # Install Docker and Blobfuse.\n    wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb\n    sudo dpkg -i packages-microsoft-prod.deb\n    sudo apt update\n    sudo apt install docker.io blobfuse -y\n\n    # Configure blobfuse.\n    sudo mkdir /mnt/resource/blobfusetmp -p\n    sudo chown $LINUX_USER /mnt/resource/blobfusetmp\n    mkdir -p blobmnt\n    echo \"accountName <pipelines_sa>\"         >  fuse_connection.cfg\n    echo \"accountKey <pipelines_sa_key>\"      >> fuse_connection.cfg\n    echo \"containerName vfxt-pipelines-blob\"  >> fuse_connection.cfg\n    chmod 600 fuse_connection.cfg\n\n    # Mount the Azure blob to blobmnt.\n    blobfuse blobmnt \\\n        --tmp-path=/mnt/resource/blobfusetmp \\\n        --config-file=fuse_connection.cfg \\\n        --file-cache-timeout-in-seconds=0 \\\n        -o attr_timeout=240 \\\n        -o entry_timeout=240 \\\n        -o negative_timeout=120\n\n    # Copy Azure blob contents.\n    cp -r blobmnt/docker-staf .\n\n    # Unmount the Azure blob and clean up.\n    sudo umount blobmnt\n    sudo rm -r blobmnt /mnt/resource/blobfusetmp\n\n    # Build Docker STAF image.\n    sudo docker build -t azpipelines/staf docker-staf/.\n\n    # Run Docker STAF image.\n    sudo docker run -d -p 6500:6500 -p 6550:6550 -t azpipelines/staf\n}\n\nfunction setup_sv_virtualenv() {\n    # Install Ansible.\n    sudo apt install ansible -y\n\n    # Clone Avre-ansible and Avere-sv repos.\n    GIT_USERNAME=\"<git_username>\"\n    GIT_PASSWORD=\"<git_password>\"\n    git clone https://${GIT_USERNAME}:${GIT_PASSWORD}@msazure.visualstudio.com/DefaultCollection/One/_git/Avere-ansible\n    git clone https://${GIT_USERNAME}:${GIT_PASSWORD}@msazure.visualstudio.com/DefaultCollection/One/_git/Avere-sv\n\n    # Copy requirements.txt (needed for Ansible playbooks).\n    cp Avere-sv/requirements.txt /tmp/requirements.sv\n    cp Avere-sv/requirements.txt /tmp/requirements.ats\n\n    # Copy pip.conf to a few places.\n    PIP_CONF_FILE=$(find /nfs -name pip.conf -print -quit)\n    sudo cp -v $PIP_CONF_FILE /etc/.\n    sudo cp -v $PIP_CONF_FILE /etc/default/.\n\n    # Run Ansible playbooks.\n    ansible-playbook Avere-ansible/ansible/ats_venv/ats_venv.yml\n    ansible-playbook Avere-ansible/ansible/sv_venv/sv_venv.yml\n\n    # Set ownership of $LINUX_USER's homedir and make Python dir writeable.\n    chown -R $LINUX_USER /home/$LINUX_USER\n    chmod -R 777 /usr/sv/env/lib/python2.7\n\n    # Virtual env setup.\n    cd Avere-sv\n    source /usr/sv/env/bin/activate\n    export PYTHONPATH=~/Avere-sv:~/Avere-sv/averesv:$PYTHONPATH:$PATH\n    python setup.py develop\n    cd ..\n}\n\nfunction setup_staf_client() {\n    # Install Blobfuse.\n    wget https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb\n    sudo dpkg -i packages-microsoft-prod.deb\n    sudo apt update\n    sudo apt install blobfuse -y\n\n    # Configure blobfuse.\n    sudo mkdir /mnt/resource/blobfusetmp -p\n    sudo chown $LINUX_USER /mnt/resource/blobfusetmp\n    mkdir -p blobmnt\n    echo \"accountName <pipelines_sa>\"         >  fuse_connection.cfg\n    echo \"accountKey <pipelines_sa_key>\"      >> fuse_connection.cfg\n    echo \"containerName vfxt-pipelines-blob\"  >> fuse_connection.cfg\n    chmod 600 fuse_connection.cfg\n\n    # Mount the Azure blob to blobmnt.\n    blobfuse blobmnt \\\n        --tmp-path=/mnt/resource/blobfusetmp \\\n        --config-file=fuse_connection.cfg \\\n        --file-cache-timeout-in-seconds=0 \\\n        -o attr_timeout=240 \\\n        -o entry_timeout=240 \\\n        -o negative_timeout=120\n\n    # Copy Azure blob contents (STAF tarball).\n    cp blobmnt/STAF*.tar.gz /tmp\n\n    # Unmount the Azure blob and clean up.\n    sudo umount blobmnt\n    sudo rm -r blobmnt /mnt/resource/blobfusetmp\n\n    # Run Ansible playbook.\n    ansible-playbook Avere-ansible/ansible/staf/staf.yml\n\n    # Set STAF envars to load on login.\n    sudo sed -i '1isource /usr/local/staf/STAFEnv.sh' ~/.bashrc\n}\n\nfunction main() {\n    echo \"STEP: config_linux\"\n    config_linux\n\n    echo \"STEP: mount_avere\"\n    mount_avere\n\n    # $HOME isn't set at this point in the VM's lifecycle. Set it and go there.\n    ORIG_DIR=$(pwd)\n    export HOME=/home/$LINUX_USER\n    cd $HOME\n\n    set -e\n    if [ \"$REG_CLIENT_TYPE\" == \"SERVER\" ]; then\n        echo \"STEP: setup_staf_server\"\n        setup_staf_server\n    fi\n\n    echo \"STEP: setup_sv_virtualenv\"\n    setup_sv_virtualenv\n\n    if [ \"$REG_CLIENT_TYPE\" == \"CLIENT\" ]; then\n        echo \"STEP: setup_staf_client\"\n        setup_staf_client\n    fi\n\n    # Set ownership of $LINUX_USER's homedir and make Python dir writeable.\n    chown -R $LINUX_USER /home/$LINUX_USER\n\n    set +e\n\n    cd $ORIG_DIR\n\n    echo \"DONE: installation complete\"\n}\n\nmain\n", "num_lines": 225}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See LICENSE-CODE in the project root for license information.\n\n# Simple file operations check for a vFXT controller that has mounted three\n# vFXT nodes. These checks do operations such as writing a file in one mount,\n# then checking to see if a different mount sees the file, etc.\n\nset -e\nset -x\n\nTOP_DIR_PFX=\"/nfs/node\"\n\nDIR0=${TOP_DIR_PFX}0\nDIR1=${TOP_DIR_PFX}1\nDIR2=${TOP_DIR_PFX}2\n\nSUBDIRS='lvl_1/lvl.2/lvl-3'\nFILE1='file01.txt'\nFILE2='file02.md'\n\n# Operations on node0's mount.\ncd $DIR0\nrm -rf $SUBDIRS || true\nmkdir -p $SUBDIRS\ncd $SUBDIRS\npwd\ndd if=/dev/urandom of=$FILE1 bs=1024 count=512\nls -l $FILE1\n\n# Operations on node1's mount.\nmv $FILE1 $DIR1/$SUBDIRS/..\ncd $DIR1/$SUBDIRS/..\npwd\nls -l $FILE1\nmv $FILE1 $FILE2\nls -l $FILE2\ndd if=/dev/urandom of=$FILE2 bs=1024 count=1024\nls -l $FILE2\ncp $FILE2 $DIR2/$SUBDIRS\ndiff $FILE2 $DIR2/$SUBDIRS\n\n# Operations on node2's mount.\ncd $DIR2/$SUBDIRS/..\npwd\nls\nls -l $FILE2\ncp $FILE2 $FILE1\nls -l $FILE1\nchmod -r $FILE2\n[[ ! -r $FILE2 ]]\nrm $FILE2\n[[ ! -e $FILE2 ]]\n\n# Cleanup.\ncd $DIR0\nrm -rf $SUBDIRS\n[[ ! -e $SUBDIRS ]]\n", "num_lines": 59}
{"repo_name": "Avere", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (C) Microsoft Corporation. All rights reserved.\n#\n# Evaluate if a given exit code indicates success (0) or failure.\n#\n# If failure, output an error message in Azure DevOps Pipelines format.\n# Additionally, output the \"current task failed\" Pipelines string.\n#\n# PARAMETERS:\n#   This script takes two positional parameters:\n#     $1: exit code to evaluate (usually called as $?)\n#     $2: a string describing the activity whose exit code is being checked\n#\n# SAMPLE USAGE:\n#   * Check the previous command.\n#     check_rc.sh $? \"resource group creation\"\n#   * Check the previous command and exit if failed.\n#     check_rc.sh $? \"resource group creation\" || exit 1\n#   * Check the previous command. If failed, tag the build and exit.\n#     check_rc.sh $? \"resource group creation\" || (echo \"##vso[build.addbuildtag]FAIL RG_create\" && exit 1)\n\nif [ \"$#\" -lt 2 ]; then\n    >&2 echo \"ERROR: At least two positional parameters are required.\"\n    cat <<EOI\n    USAGE: $0 <rc> <activity_msg>\n        <rc>: The return (exit) code being checked.\n        <activity_msg>: The activity being tested (e.g., \"resource group creation\")\nEOI\n    exit 1\nfi\n\nrc=$1\nshift\nactivity=$*\n\nnowstr=\"[$(date -u '+%F %T %Z')]\"\nif [ \"${rc}\" -ne 0 ]; then\n    >&2 echo \"${nowstr}: ERROR: FAILED: ${activity}.\"\n    echo \"##vso[task.logissue type=error;]FAILED: ${activity}. See log for details.\"\n    echo \"##vso[task.complete result=Failed;]\"\n    exit ${rc}\nelse\n    echo \"${nowstr}: INFO: SUCCESS: ${activity}.\"\nfi\n", "num_lines": 45}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nANSIBLE_VERSION_UBUNTU=5.8.0\nANSIBLE_VERSION_CENTOS=4.10.0\n\nos_release=$(cat /etc/os-release | grep \"^ID\\=\" | cut -d'=' -f 2 | xargs)\nos_release=${os_release^^}\n\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nif [[ `pip3 list pypsrp` == *\"pypsrp\"* ]]; then \n  echo pypsrp is already installed \nelse\n  pip3 install pypsrp\nfi\nif [[ `pip3 list PySocks` == *\"PySocks\"* ]]; then \n  echo PySocks is already installed \nelse\n  pip3 install PySocks\nfi\nif [[ `pip3 list netaddr` == *\"netaddr\"* ]]; then \n  echo netaddr is already installed \nelse\n  pip3 install netaddr\nfi\n\nansible-galaxy collection install ansible.windows\nansible-galaxy collection install community.windows\nansible-galaxy collection install ansible.posix\nansible-galaxy collection install community.general\n\n# This is to fix an issue when using delegate_to\nif [ -f /usr/bin/python3 ] && [ ! -f /usr/bin/python ]; then \n  sudo ln --symbolic /usr/bin/python3 /usr/bin/python; \nfi\n\n# Test if the ood-ansible repo has been pulled\nOOD_ANSIBLE=$THIS_DIR/playbooks/roles/ood-ansible\nif [ \"$(ls -A $OOD_ANSIBLE)\" ]; then\n     echo \"OOD Ansible playbook has been pulled\"\nelse\n    echo \"$OOD_ANSIBLE is empty. Please git clone this repo using the --recursive option or run 'git submodule init && git submodule update'\"\n    exit 1\nfi\n\nansible --version\npip3 list | grep ansible\nversion=$(pip3 list | grep ansible | sort | head -n 1 | xargs | cut -d' ' -f 2)\nANSIBLE_VERSION=\"ANSIBLE_VERSION_$os_release\"\nif [ \"$version\" != ${!ANSIBLE_VERSION} ]; then\n  echo \"Ansible version is ${!ANSIBLE_VERSION}. Please run ./toolset/scripts/install.sh to install the correct version of Ansible\"\n  exit 1\nfi\n", "num_lines": 54}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Download / Upload state files from blobs\n# Skip any existing newer local ones\nCOMMAND=${1,,}\nSA_ACCOUNT=$2\nSA_CONTAINER=$3\nRESOURCE_GROUP=$4\n\nSTATE_DIR=.state\n\nfunction usage()\n{\n  echo \"azhop_state command account container resource_group\"\n  echo \"    command        = download, upload, delete\"\n  echo \"    account        = azure storage account to read/write state\"\n  echo \"    container      = container to use\"\n  echo \"    resource group = resource group to use (only for download)\"\n  exit 1\n}\n\nfunction get_resource_group()\n{\n    # If resource group is empty, read it from the configuration file\n    if [ -z $RESOURCE_GROUP ]; then\n        if [ ! -e $AZHOP_CONFIG ]; then\n          echo \"$AZHOP_CONFIG doesn't exist, exiting\"\n          exit 1\n        fi\n\n        RESOURCE_GROUP=$(yq eval '.resource_group' $AZHOP_CONFIG)\n        if [ -z $RESOURCE_GROUP ]; then\n          echo \"Resource group is empty, exiting\"\n          exit 1\n        fi\n    fi\n}\n\nif [ \"$COMMAND\" != \"upload\" ] && [ \"$COMMAND\" != \"download\" ] && [ \"$COMMAND\" != \"delete\" ]; then\n  usage\nfi\n\nAZHOP_CONFIG=config.yml\n\nstart=$(date -u -d \"-10 minutes\" '+%Y-%m-%dT%H:%MZ')\nexpiry=$(date -u -d \"60 minutes\" '+%Y-%m-%dT%H:%MZ')\n\ncase $COMMAND in \n  download)\n\n    get_resource_group\n    echo \"Download state for $RESOURCE_GROUP\"\n    sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rl --start $start --expiry $expiry --output tsv)\n    azcopy copy \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$RESOURCE_GROUP/*?$sas\" \"$STATE_DIR\" --recursive \n\n    if [ -d $STATE_DIR ]; then\n      # Use a local state directory as azcopy swallow the prefix file name if this one is the same that the directory name !!! \n      # This will also help uploading the whole directory content as well\n      cp -r -u $STATE_DIR/* .\n      # Fix SSH Keys permission as they are not preserved\n      ADMIN_USER=$(yq eval '.admin_user' $AZHOP_CONFIG)\n      chmod 600 ${ADMIN_USER}_id_rsa\n      chmod 644 ${ADMIN_USER}_id_rsa.pub\n      # Add chmod+x on scripts\n      if [ -d ./bin ]; then\n        chmod +x ./bin/*\n      fi\n    fi\n  ;;\n\n  upload)\n    if [ ! -e $AZHOP_CONFIG ]; then\n      echo \"$AZHOP_CONFIG doesn't exist, exiting\"\n      exit\n    fi\n\n    RESOURCE_GROUP=$(yq eval '.resource_group' $AZHOP_CONFIG)\n    echo \"Upload state for $RESOURCE_GROUP\"\n    if [ -z $RESOURCE_GROUP ]; then\n      echo \"Resource group is empty, exiting\"\n      exit 1\n    fi\n    # Copy state files into the state directory\n    mkdir -p $STATE_DIR\n    cp $AZHOP_CONFIG $STATE_DIR\n    ADMIN_USER=$(yq eval '.admin_user' $AZHOP_CONFIG)\n    cp ${ADMIN_USER}_id_rsa $STATE_DIR\n    cp ${ADMIN_USER}_id_rsa.pub $STATE_DIR\n    mkdir -p $STATE_DIR/packer\n    cp packer/options.json $STATE_DIR/packer/options.json\n    mkdir -p $STATE_DIR/playbooks/group_vars\n    cp playbooks/group_vars/all.yml $STATE_DIR/playbooks/group_vars\n    cp playbooks/inventory $STATE_DIR/playbooks\n    cp playbooks/inventory.cis.yml $STATE_DIR/playbooks\n    mkdir -p $STATE_DIR/tf\n    cp tf/terraform.tfstate $STATE_DIR/tf\n    mkdir -p $STATE_DIR/bin\n    cp bin/* $STATE_DIR/bin\n    mkdir -p $STATE_DIR/tf/cloud-init\n    cp tf/cloud-init/*.yml $STATE_DIR/tf/cloud-init\n\n    sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rwdl --start $start --expiry $expiry --output tsv)\n    azcopy copy \"$STATE_DIR/*\" \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$RESOURCE_GROUP?$sas\"  --recursive\n  ;;\n\n  delete)\n    get_resource_group\n    echo \"Delete state for $RESOURCE_GROUP\"\n    sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rwdl --start $start --expiry $expiry --output tsv)\n    azcopy remove \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$RESOURCE_GROUP?$sas\" --recursive=true\n  ;;\nesac\n\n", "num_lines": 113}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\n# Build the HPC infrastructure with Terraform.\n# build.sh -a [plan, apply, destroy] -v <vars file> -f <folder>\n#\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nAZHOP_CONFIG=config.yml\nBICEP_ROOT=$THIS_DIR/bicep\nARM_ROOT=$THIS_DIR/marketplace/solution\nAZCLI_VERSION_MAJOR=2\nAZCLI_VERSION_MINOR=37\nAZCLI_VERSION_PATCH=0\nAZCLI_VERSION=\"$AZCLI_VERSION_MAJOR.$AZCLI_VERSION_MINOR.$AZCLI_VERSION_PATCH\"\n\nAZHOP_ROOT=$THIS_DIR\nAZHOP_FROM=local\n#TFVARS_FILE=\"\"\nTF_FOLDER=$THIS_DIR/tf\nTF_TARGET=\nVALIDATE_CONFIG=true\nVERBOSE=0\n\nfunction usage()\n{\n  echo \"Usage build.sh \"\n  echo \"  Required arguments:\"\n  echo \"    -a|--action [plan, apply, destroy] - Destroy will not applied with Bicep\"\n  echo \"   \"\n  echo \"  Optional arguments:\"\n  echo \"    -f|--folder <relative path>      - relative folder name containing the terraform files, default is ./tf\"\n  echo \"    -l|--language <tf, bicep, arm>   - deployment language to use, default is tf. arm template will be generated from bicep\"\n  echo \"    --no-validate                    - skip validation of config.yml\"\n}\n\n#######################################################################################################################\n#\n#                       Terraform Helpers\n#\n#######################################################################################################################\nfunction terraform_init()\n{\n  export TF_CLI_ARGS_apply=\"-auto-approve\"\n  #export TF_LOG=INFO\n  #export TF_LOG_PATH=.terraform/terraform.log\n\n  # As we don't managed TF state in blob don't call this\n  #get_arm_access_key\n\n  # If an existing terraform state exists for a different resource group, then delete it.\n  if [ -e $THIS_DIR/tf/terraform.tfstate ]; then\n    rg_in_state=$(jq -r '.resources[] | select(.type==\"azurerm_resource_group\") | .instances[] | .attributes.name' $THIS_DIR/tf/terraform.tfstate)\n    rg_in_config=$(yq eval '.resource_group' $AZHOP_CONFIG)\n    set +e\n    echo $rg_in_state | grep -w -q $rg_in_config\n    if [ $? -eq 1 ]; then\n      echo \"Deleting existing terraform state for resource group $rg_in_state\"\n      rm -rf $THIS_DIR/tf/terraform.tfstate\n    else\n      echo \"Keep existing terraform state for resource group $rg_in_state\"\n    fi\n    set -e\n  fi\n\n  terraform -chdir=$TF_FOLDER init -upgrade\n\n  if [ -e $THIS_DIR/tf/terraform.tfstate ] && [ $TF_FOLDER != $THIS_DIR/tf ]; then\n    cp -u -f $THIS_DIR/tf/terraform.tfstate $TF_FOLDER\n  fi\n\n}\n\nfunction terraform_run()\n{\n  # -parallelism=30\n  set +e\n  export TF_LOG=\"INFO\"\n  export TF_LOG_PATH=\"$THIS_DIR/tf/terraform.log\"\n  rm -f $TF_LOG_PATH\n\n  echo \"terraform -chdir=$TF_FOLDER $TF_COMMAND $PARAMS\"\n  terraform -chdir=$TF_FOLDER $TF_COMMAND $PARAMS\n  export EXIT_CODE=$?\n\n  if [ -e $TF_FOLDER/terraform.tfstate ] && [ $TF_FOLDER != $THIS_DIR/tf ]; then\n    cp -u -f $TF_FOLDER/terraform.tfstate $THIS_DIR/tf/terraform.tfstate\n  fi\n}\n\n# Set the ARM_ACCESS_KEY env variable to be used by TF to manage states in azure blobs backend\n# The ./tf/backend.tf file contains the values of the storage ressource group, account and container to be used\nfunction get_arm_access_key {\n  TF_BACKEND_FILE=$TF_FOLDER/backend.tf\n\n  if [ ! -e $TF_BACKEND_FILE ]; then\n    echo \"No backend specified, using local state\"\n  else\n    RESOURCE_GROUP_NAME=$(grep \"resource_group_name\" $TF_BACKEND_FILE | cut -d'=' -f 2 | xargs)\n    STORAGE_ACCOUNT_NAME=$(grep \"storage_account_name\" $TF_BACKEND_FILE | cut -d'=' -f 2 | xargs)\n    ACCOUNT_KEY=$(az storage account keys list --resource-group $RESOURCE_GROUP_NAME --account-name $STORAGE_ACCOUNT_NAME --query '[0].value' -o tsv)\n\n    if [ \"$ACCOUNT_KEY\" == \"\" ]; then\n      echo \"unable to retrieve the account key for accessing terraform blob backend\"\n      exit 1\n    fi\n\n    echo \"Using backend stored in $RESOURCE_GROUP_NAME/$STORAGE_ACCOUNT_NAME\"\n    export ARM_ACCESS_KEY=$ACCOUNT_KEY\n  fi\n}\n\n#######################################################################################################################\n#\n#                       Azure Functions\n#\n#######################################################################################################################\nfunction get_azure_context()\n{\n  # Inspired from https://github.com/aztfmod/rover/blob/4098ce32e46f854445ac85839125f21410b439fc/scripts/functions.sh#L807\n  # Retrieve under which identity we run\n  user_type=$(az account show --query user.type -o tsv)\n  export TF_VAR_tenant_id=$(az account show -o json | jq -r .tenantId)\n  subscription_id=$(az account show --query id -o tsv)\n  if [ ${user_type} == \"user\" ]; then\n    unset ARM_TENANT_ID\n    unset ARM_SUBSCRIPTION_ID\n    unset ARM_CLIENT_ID\n    unset ARM_CLIENT_SECRET\n    unset ARM_USE_MSI\n    export TF_VAR_logged_user_objectId=$(az ad signed-in-user show --query id -o tsv)\n    logged_user_upn=$(az ad signed-in-user show --query userPrincipalName -o tsv)\n    echo \" - logged in Azure with User ${logged_user_upn}\"\n  else\n    unset TF_VAR_logged_user_objectId\n    export clientId=$(az account show --query user.name -o tsv)\n    case \"${clientId}\" in\n        \"systemAssignedIdentity\")\n            mds=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2019-08-15\")\n            vmname=$(echo $mds | jq -r '.compute.name')\n            rgname=$(echo $mds | jq -r '.compute.resourceGroupName')\n            echo \" - logged in Azure with System Assigned Identity from ${vmname}/${rgname}\"\n            export TF_VAR_logged_user_objectId=$(az resource list -n $vmname -g $rgname --query [*].identity.principalId --out tsv)\n            if [ \"$TF_VAR_logged_user_objectId\" == \"\" ]; then\n              export TF_VAR_logged_user_objectId=$(az resource list -n $vmname -g $rgname --query [*].identity.userAssignedIdentities.*.principalId --out tsv)\n            fi\n            export ARM_TENANT_ID=${TF_VAR_tenant_id}\n            export ARM_SUBSCRIPTION_ID=${subscription_id}\n            export ARM_USE_MSI=true\n            logged_user_upn=\"${TF_VAR_logged_user_objectId} from ${vmname}\"\n            ;;\n        \"userAssignedIdentity\")\n            mds=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2019-08-15\")\n            vmname=$(echo $mds | jq -r '.compute.name')\n            rgname=$(echo $mds | jq -r '.compute.resourceGroupName')\n            echo \" - logged in Azure with User Assigned Identity from ${vmname}/${rgname}\"\n            export TF_VAR_logged_user_objectId=$(az resource list -n $vmname -g $rgname --query [*].identity.userAssignedIdentities.*.principalId --out tsv)\n            client_id=$(az vm identity show -g $rgname --n $vmname --query userAssignedIdentities.*.clientId -o tsv)\n            export ARM_TENANT_ID=${TF_VAR_tenant_id}\n            export ARM_CLIENT_ID=${client_id}\n            export ARM_SUBSCRIPTION_ID=${subscription_id}\n            export ARM_USE_MSI=true\n            logged_user_upn=\"${TF_VAR_logged_user_objectId} from ${vmname}\"\n            ;;\n        *)\n            export TF_VAR_logged_user_objectId=$(az ad sp show --id ${clientId} --query id -o tsv)\n            logged_user_upn=$(az ad sp show --id ${clientId} --query displayName -o tsv)\n            echo \" - logged in Azure with Service Principal Name ${logged_user_upn}\"\n            export ARM_TENANT_ID=${TF_VAR_tenant_id}\n            export ARM_SUBSCRIPTION_ID=${subscription_id}\n            ;;\n    esac\n  fi\n  export TF_VAR_CreatedBy=${logged_user_upn}\n}\n\nfunction get_storage_id {\n  # get the storage account ID to use\n  id=$(az storage account list -g $RESOURCE_GROUP --query \"[?contains(@.name, 'storage')==\\`true\\`].id\" | jq -r '.[0]')\n  if [ ${id} == null ]; then\n    echo \"no storage account found to store the TF state\"\n    exit 1\n  fi\n}\n\nfunction check_azcli_version {\n  version=$(az --version | grep azure-cli | xargs | cut -d' ' -f 2)\n  major=$(echo $version | cut -d'.' -f 1)\n  minor=$(echo $version | cut -d'.' -f 2)\n  patch=$(echo $version | cut -d'.' -f 3)\n\n  if [ $major -lt $AZCLI_VERSION_MAJOR ]; then\n    echo \"azure-cli version $AZCLI_VERSION or higher is required\"\n    exit 1\n  else\n    if [ $minor -lt $AZCLI_VERSION_MINOR ]; then\n      echo \"azure-cli version $AZCLI_VERSION or higher is required\"\n      exit 1\n    else\n      if [ $patch -lt $AZCLI_VERSION_PATCH ]; then\n        echo \"azure-cli version $AZCLI_VERSION or higher is required\"\n        exit 1\n      fi\n    fi\n  fi\n}\n\nfunction accept_terms()\n{\n  # Accept Lustre marketplace image terms\n  accepted=$(az vm image terms show --offer azurehpc-lustre --publisher azhpc --plan azurehpc-lustre-2_12 --query 'accepted' -o tsv)\n  if [ \"$accepted\" != \"true\" ]; then\n    echo \"Azure Lustre marketplace image terms are not accepted, accepting them now\"\n    az vm image terms accept --offer azurehpc-lustre --publisher azhpc --plan azurehpc-lustre-2_12 -o tsv\n  else\n    echo \"Azure Lustre marketplace image terms already accepted\"\n  fi\n\n  # Accept AlmaLinux marketplace image terms\n  # accepted=$(az vm image terms show --offer almalinux-hpc --publisher almalinux --plan 8_5-hpc-gen2 --query 'accepted' -o tsv)\n  # if [ \"$accepted\" != \"true\" ]; then\n  #   echo \"Azure AlmaLinux marketplace image terms are not accepted, accepting them now\"\n  #   az vm image terms accept --offer almalinux-hpc --publisher almalinux --plan 8_5-hpc-gen2 -o tsv\n  # else\n  #   echo \"Azure AlmaLinux marketplace image terms already accepted\"\n  # fi\n\n}\n\nfunction get_azure_cloud_env()\n{\n  # Retrieve on which cloud environment we run on\n  # env details from here: https://github.com/hashicorp/terraform-provider-azurerm/blob/main/vendor/github.com/Azure/go-autorest/autorest/azure/environments.go\n  # TODO: check az environmentName for AzureChina and AzureGerman\n  cloud_env=\"Public\"\n  account_env=$(az account show --output json| jq '.environmentName' -r)\n  case \"$account_env\" in\n    # AzureChinaCloud)\n    #   export TF_VAR_AzureEnvironment=AZURECHINACLOUD\n    #   export TF_VAR_KeyVaultSuffix=vault.azure.cn\n    #   export TF_VAR_BlobStorageSuffix=blob.core.chinacloudapi.cn\n    #   ;;\n    # AzureGermanCloud)\n    #   export TF_VAR_AzureEnvironment=AZUREGERMANCLOUD\n    #   export TF_VAR_KeyVaultSuffix=vault.microsoftazure.de\n    #   export TF_VAR_BlobStorageSuffix=blob.core.cloudapi.de\n    #   ;;\n    AzureCloud)\n      export TF_VAR_AzureEnvironment=AZUREPUBLICCLOUD\n      # export TF_VAR_KeyVaultSuffix=vault.azure.net\n      # export TF_VAR_BlobStorageSuffix=blob.core.windows.net\n      ;;\n    AzureUSGovernment)\n      export TF_VAR_AzureEnvironment=AZUREUSGOVERNMENTCLOUD\n      # export TF_VAR_KeyVaultSuffix=vault.usgovcloudapi.net\n      # export TF_VAR_BlobStorageSuffix=blob.core.usgovcloudapi.net\n      ;;\n    *)\n      echo \"ERROR: Unknown Azure environment ${account_env}\"\n      exit 1\n      ;;\n  esac\n}\n\n#######################################################################################################################\n#\n#                       BICEP Helpers\n#\n#######################################################################################################################\nfunction set_bicep_param_value()\n{\n  local Param=$1\n  local Value=$2\n\n  case $Value in\n    \"true\"|\"True\")\n      eval_str=\". | $Param=true\"\n    ;;\n    \"false\"|\"False\")\n      eval_str=\". | $Param=false\"\n    ;;\n    *)\n      eval_str=\". | $Param=\\$param\"\n    ;;\n\n  esac\n\n  jq \"$eval_str\" --arg param \"$Value\" $BICEP_PARAMS > $TMP_PARAMS\n  cp $TMP_PARAMS $BICEP_PARAMS\n\n}\n\nfunction set_bicep_azhopconfig()\n{\n  jq '. | .parameters.azhopConfig.value=$json' --argjson json \"$(yq $AZHOP_CONFIG -o json | jq '.' -c)\" $BICEP_PARAMS > $TMP_PARAMS\n  cp $TMP_PARAMS $BICEP_PARAMS\n}\n\nfunction arm_init()\n{\n  pushd $ARM_ROOT\n  ./build.sh\n  popd\n}\n\n\nfunction bicep_init()\n{\n  # Build the parameters.json file based on the config file content\n  location=$(yq '.location' $AZHOP_CONFIG)\n  resource_group=$(yq '.resource_group' $AZHOP_CONFIG)\n  adminuser=$(yq '.admin_user' $AZHOP_CONFIG)\n  BICEP_PARAMS=$resource_group.parameters.json\n  TMP_PARAMS=tmp.parameters.json\n  AZHOP_DEPLOYMENT_OUTPUT=$resource_group.outputs.json\n\n  # Set default param template file if it doesn't exists for the resource group\n  if [ ! -e $BICEP_PARAMS ]; then \n    cp $BICEP_ROOT/param.json $BICEP_PARAMS\n  fi\n\n  if [ \"$AZHOP_FROM\" == \"local\" ]; then\n    set_bicep_param_value \".parameters.loggedUserObjectId.value\" \"$TF_VAR_logged_user_objectId\"\n  fi\n\n  set_bicep_param_value \".parameters.autogenerateSecrets.value\" \"false\"\n  set_bicep_param_value \".parameters.branchName.value\" \"$(git branch | grep \"*\" | cut -d' ' -f 2)\"\n\n  set_bicep_azhopconfig\n\n  if [ \"$AZHOP_FROM\" == \"deployer\" ]; then\n    # Change the jumpbox name to deployer if present\n    sed -i 's/jumpbox/deployer/g' $BICEP_PARAMS\n\n    # Add the logged user as a reader of the keyvault\n    set_bicep_param_value \".parameters.azhopConfig.value.key_vault_readers\" \"$TF_VAR_logged_user_objectId\"\n  fi\n\n  # Read secrets from the parameter file as we don't know the keyvault name until a proper deployment has been successful\n  adminPassword=$(jq -r '.parameters.adminPassword.value' $BICEP_PARAMS)\n  if [ \"$adminPassword\" == \"null\" ]; then\n    set_bicep_param_value \".parameters.adminPassword.value\" \"$(openssl rand -base64 24)\"\n  fi\n  databaseAdminPassword=$(jq -r '.parameters.databaseAdminPassword.value' $BICEP_PARAMS)\n  if [ \"$adminPassword\" == \"null\" ]; then\n    set_bicep_param_value \".parameters.databaseAdminPassword.value\" \"$(openssl rand -base64 24)\"\n  fi\n  adminSshPublicKey=$(jq -r '.parameters.adminSshPublicKey.value' $BICEP_PARAMS)\n  if [ \"$adminSshPublicKey\" == \"null\" ]; then\n    # generate a new key if it doesn't exists\n    if [ ! -e $AZHOP_ROOT/${adminuser}_id_rsa ]; then\n      ssh-keygen -f $AZHOP_ROOT/${adminuser}_id_rsa  -N \"\"\n    fi\n    set_bicep_param_value \".parameters.adminSshPublicKey.value\" \"$(cat $AZHOP_ROOT/${adminuser}_id_rsa.pub)\"\n    set_bicep_param_value \".parameters.adminSshPrivateKey.value\" \"$(cat $AZHOP_ROOT/${adminuser}_id_rsa)\"\n  fi\n\n}\n\nfunction bicep_run()\n{\n  timestamp=$(date -u +\"%Y.%m%d.%H%M%S\")\n  deployment_name=azhop_${timestamp}\n  deployment_op=\"create\"\n  if [ \"$TF_COMMAND\" == \"plan\" ]; then\n    deployment_op=\"what-if\"\n  fi\n\n  if [ \"$VERBOSE\" == \"1\" ]; then\n    az bicep build --file $BICEP_ROOT/mainTemplate.bicep --outfile mainTemplate.json\n    cat mainTemplate.json\n    az deployment sub validate --template-file $BICEP_ROOT/mainTemplate.bicep --location $location --parameters @$BICEP_PARAMS\n  fi\n\n  case $DEPLOY_LANGUAGE in\n    \"bicep\")\n      echo \"* Deploying using Bicep\"\n      TEMPLATE_FILE=$BICEP_ROOT/mainTemplate.bicep\n      ;;\n    \"arm\")\n      TEMPLATE_FILE=$ARM_ROOT/build/mainTemplate.json\n      echo \"* Deploying using ARM\"\n      ;;\n  esac\n\n  az deployment sub $deployment_op --template-file $TEMPLATE_FILE --location $location -n $deployment_name --parameters @$BICEP_PARAMS\n\n  if [ \"$TF_COMMAND\" == \"plan\" ]; then\n    exit\n  fi\n\n  echo \"* Getting deployment output\"\n  az deployment group show \\\n      -g $resource_group \\\n      -n azhop \\\n      --query properties.outputs \\\n      > $AZHOP_DEPLOYMENT_OUTPUT\n\n#  if [ \"$AZHOP_FROM\" == \"local\" ]; then\n\n    # Update config path \n    jq '. | .azhopGlobalConfig.value.global_config_file=$param' --arg param $AZHOP_ROOT/config.yml $AZHOP_DEPLOYMENT_OUTPUT > $TMP_PARAMS\n    cp $TMP_PARAMS $AZHOP_DEPLOYMENT_OUTPUT\n\n    kv=$(jq -r .keyvaultName.value $AZHOP_DEPLOYMENT_OUTPUT)\n\n    echo \"* Getting keys from keyvault\"\n    az keyvault secret show --vault-name $kv -n ${adminuser}-pubkey --query \"value\" -o tsv > $AZHOP_ROOT/${adminuser}_id_rsa.pub\n    az keyvault secret show --vault-name $kv -n ${adminuser}-privkey --query \"value\" -o tsv > $AZHOP_ROOT/${adminuser}_id_rsa\n    chmod 600 $AZHOP_ROOT/${adminuser}_id_rsa*\n\n    mkdir -p $AZHOP_ROOT/bin\n    jq -r .azhopGetSecretScript.value $AZHOP_DEPLOYMENT_OUTPUT > $AZHOP_ROOT/bin/get_secret\n    chmod +x $AZHOP_ROOT/bin/get_secret\n    jq -r .azhopConnectScript.value $AZHOP_DEPLOYMENT_OUTPUT > $AZHOP_ROOT/bin/connect\n    chmod +x $AZHOP_ROOT/bin/connect\n\n    mkdir -p $AZHOP_ROOT/playbooks/group_vars\n    jq .azhopGlobalConfig.value $AZHOP_DEPLOYMENT_OUTPUT | yq -P > $AZHOP_ROOT/playbooks/group_vars/all.yml\n\n    jq '.azhopInventory.value.all.hosts *= (.lustre_oss_private_ips.value | to_entries | map({(\"lustre-oss-\" + (.key | tostring)): {\"ansible_host\": .value}}) | add // {}) | .azhopInventory.value' $AZHOP_DEPLOYMENT_OUTPUT | yq -P > $AZHOP_ROOT/playbooks/inventory\n\n    # substitute passwords into the file\n    #  - __ADMIN_PASSWORD__\n    admin_pass=\"$(az keyvault secret show --vault-name $kv -n ${adminuser}-password --query \"value\" -o tsv)\"\n    sed -i \"s/__ADMIN_PASSWORD__/$(sed 's/[&/\\]/\\\\&/g' <<< $admin_pass)/g\" $AZHOP_ROOT/playbooks/inventory\n    jq .azhopPackerOptions.value $AZHOP_DEPLOYMENT_OUTPUT > $AZHOP_ROOT/packer/options.json\n#  fi\n}\n\n\nif [ $# -eq 0 ]; then\n  usage\n  exit 1\nfi\n\nunset PARAMS\nDEPLOY_LANGUAGE=tf\n\nwhile (( \"$#\" )); do\n  case \"${1}\" in\n    -a|--action)\n      TF_COMMAND=${2}\n      # verify that the action is either plan, apply or destroy\n      if [ \"$TF_COMMAND\" != \"plan\" ] && [ \"$TF_COMMAND\" != \"apply\" ] && [ \"$TF_COMMAND\" != \"destroy\" ]; then\n        echo \"Invalid action $TF_COMMAND. Valid values are plan, apply or destroy\"\n        exit 1\n      fi\n      shift 2\n    ;;\n    -l|--language)\n      DEPLOY_LANGUAGE=${2}\n      # verify that the language is either tf or bicep\n      if [ \"$DEPLOY_LANGUAGE\" != \"tf\" ] && [ \"$DEPLOY_LANGUAGE\" != \"bicep\" ] && [ \"$DEPLOY_LANGUAGE\" != \"arm\" ]; then\n        echo \"Invalid language $DEPLOY_LANGUAGE. Valid values are tf, bicep or arm\"\n        exit 1\n      fi\n      shift 2\n    ;;\n    -f|--folder)\n      TF_FOLDER=${THIS_DIR}/${2}\n      shift 2\n    ;;\n    --no-validate)\n      VALIDATE_CONFIG=false\n      shift 1\n    ;;\n    *)\n      PARAMS+=\"${1} \"\n      shift\n      ;;\n  esac\ndone\n\n# Check that action is set\nif [ -z \"$TF_COMMAND\" ]; then\n  echo \"Action is required\"\n  usage\n  exit 1\nfi\n\nif [ -d ${THIS_DIR}/miniconda ]; then\n  echo \"Activating conda environment\"\n  source ${THIS_DIR}/miniconda/bin/activate\nfi\n\n# Validate config against schema\nif [ \"$VALIDATE_CONFIG\" = true ]; then\n  $THIS_DIR/validate_config.sh $AZHOP_CONFIG\nfi\n\ncheck_azcli_version\ncase $DEPLOY_LANGUAGE in\n  tf)\n    terraform_init\n    get_azure_context\n    get_azure_cloud_env\n    terraform_run\n    ;;\n  bicep)\n    # If a Jumpbox VM is defined in the config file then assume it's a local deployment, otherwise it's done from the deployer VM\n    jumpbox=$(yq '.jumpbox' $AZHOP_CONFIG)\n    if [ \"$jumpbox\" == \"null\" ]; then\n      AZHOP_FROM=\"deployer\"\n    else\n      AZHOP_FROM=\"local\"\n    fi\n    get_azure_context\n    bicep_init\n    bicep_run\n    ;;\n  arm)\n    # ARM deployment is always using a deplpyed VM\n    AZHOP_FROM=\"deployer\"\n    arm_init\n    get_azure_context\n    bicep_init\n    bicep_run\n    ;;\nesac\n\n\nexit $EXIT_CODE\n", "num_lines": 523}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This script will register an AAD application used for OIDC and authentication. \n# The application secret is stored in the keyvault under a secret named azhop-oidc-password\nset -e\nAZHOP_CONFIG=config.yml\nANSIBLE_VARIABLES=playbooks/group_vars/all.yml\n\nif [ ! -e $AZHOP_CONFIG ]; then\n  echo \"$AZHOP_CONFIG doesn't exist, exiting\"\n  exit 1\nfi\n\nkey_vault=$(yq eval '.key_vault' $ANSIBLE_VARIABLES)\nif [ \"$key_vault\" == \"\" ]; then\n  echo \"Keyvault retrieved from $ANSIBLE_VARIABLES is empty\"\n  exit 1\nfi\n\naadName=$(yq eval '.resource_group' config.yml)\nif [ \"$aadName\" == \"\" ]; then\n  echo \"Resource group retrieved from $ANSIBLE_VARIABLES is empty\"\n  exit 1\nfi\n\nazhop_uri=$(yq eval '.ondemand_fqdn' $ANSIBLE_VARIABLES)\nif [ \"$azhop_uri\" == \"\" ]; then\n  echo \"ondemand_fqdn retrieved from $ANSIBLE_VARIABLES is empty\"\n  exit 1\nfi\n\n# Create the AAD application, generate a client secret, and register it with the AAD tenant\n# Store the secret under <appId>-password in the keyvault\nappId=$(az ad app list --display-name $aadName --query [].appId -o tsv)\nif [ \"$appId\" == \"\" ]; then\n  az ad app create --display-name $aadName \\\n          --web-redirect-uris \"https://$azhop_uri/oidc\" \\\n          --public-client-redirect-uris \"https://$azhop_uri/oidc\" \\\n          --required-resource-accesses @aad_manifest.json \\\n          --optional-claims @aad_claims.json \\\n          --key-type password \n\n  appId=$(az ad app list --display-name $aadName --query [].appId -o tsv)\n  current_password=$(az ad app credential reset --id $appId | jq -r '.password')\n  SECRET_NAME=\"$appId-password\"\n  echo \"Generating a password for $aadName and storing it as secret $SECRET_NAME in keyvault $key_vault\"\n  az keyvault secret set --value \"$current_password\" --name $SECRET_NAME --vault-name $key_vault -o table > /dev/null\nelse\n  SECRET_NAME=\"$appId-password\"\n  echo \"AAD application $aadName already exists\"\n  current_password=$(az keyvault secret list --vault-name $key_vault --query \"[?name=='$SECRET_NAME'].name\" -o tsv)\n  if [ \"$current_password\" == \"\" ] ; then\n    appId=$(az ad app list --display-name $aadName --query [].appId -o tsv)\n    echo \"Generating a password for $aadName and storing it as secret $SECRET_NAME in keyvault $key_vault\"\n    current_password=$(az ad app credential reset --id $appId | jq -r '.password')\n    az keyvault secret set --value \"$current_password\" --name $SECRET_NAME --vault-name $key_vault -o table > /dev/null\n  else\n    echo \"$SECRET_NAME has already a secret stored in keyvault $key_vault\"\n  fi\nfi\n\necho \"AAD appId: $appId\"\n", "num_lines": 62}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This script will create a random password per user and store it in the keyvault under a secret named <user>-password\n\nAZHOP_CONFIG=config.yml\nANSIBLE_VARIABLES=playbooks/group_vars/all.yml\n\nif [ ! -e $AZHOP_CONFIG ]; then\n  echo \"$AZHOP_CONFIG doesn't exist, exiting\"\n  exit 1\nfi\n\nkey_vault=$(yq eval '.key_vault' $ANSIBLE_VARIABLES)\nif [ \"$key_vault\" == \"\" ]; then\n  echo \"Keyvault retrieved from $ANSIBLE_VARIABLES is empty\"\n  exit 1\nfi\n\nusers=$(yq eval '.users[].name' $AZHOP_CONFIG)\nfor user in $users; do\n  # Because secret names are restricted to '^[0-9a-zA-Z-]+$' we need to remove all other characters\n  secret_name=$(echo $user-password | tr -dc 'a-zA-Z0-9-')\n  current_password=$(az keyvault secret list --vault-name $key_vault --query \"[?name=='$secret_name'].name\" -o tsv)\n  if [ \"$current_password\" == \"\" ]; then\n    password=$(openssl rand -base64 20)\n    az keyvault secret set --value $password --name $secret_name --vault-name $key_vault -o table > /dev/null\n    echo \"Generating a password for $user and storing it as secret $secret_name in keyvault $key_vault\"\n  else\n    echo \"User $user has already a password stored in keyvault $key_vault\"\n  fi\ndone\n", "num_lines": 31}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nTARGET=${1:-all}\nshift\nANSIBLE_TAGS=$@\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nPLAYBOOKS_DIR=$THIS_DIR/playbooks\nINVENTORY=$PLAYBOOKS_DIR/inventory\nOOD_AUTH=\"basic\"\n\nload_miniconda() {\n  # Note: packaging this inside a function to avoid forwarding arguments to conda\n  if [ -d ${THIS_DIR}/miniconda ]; then\n    echo \"Activating conda environment\"\n    source ${THIS_DIR}/miniconda/bin/activate\n  fi\n}\nload_miniconda\n\nfunction run_playbook ()\n{\n  local playbook=$1\n  shift\n  local extra_vars_file=$@\n\n  # If running all playbooks and playbook marker doesn't exists, run the playbook\n  # If user requested specific playbook ignore marker file and force run\n  if [ ! -e $PLAYBOOKS_DIR/$playbook.ok ] || [ \"$TARGET\" != \"all\" ]; then\n    local options=\"\"\n    if [ \"$extra_vars_file\" != \"\" ]; then\n      # Merge overrides variables in a single file\n      yq eval-all '. as $item ireduce ({}; . *+ $item)' $extra_vars_file > $PLAYBOOKS_DIR/extra_vars.yml\n      options+=\" --extra-vars=@$PLAYBOOKS_DIR/extra_vars.yml\"\n    fi\n    echo \"Running playbook $PLAYBOOKS_DIR/$playbook.yml ...\"\n    ansible-playbook -i $INVENTORY $PLAYBOOKS_DIR/$playbook.yml $options $ANSIBLE_TAGS || exit 1\n    if [ -e $PLAYBOOKS_DIR/extra_vars.yml ]; then\n      rm $PLAYBOOKS_DIR/extra_vars.yml\n    fi\n    touch $PLAYBOOKS_DIR/$playbook.ok\n  else\n    echo \"Skipping playbook $PLAYBOOKS_DIR/$playbook.yml as it has been successfully run \"\n  fi\n}\n\nfunction get_scheduler ()\n{\n  local scheduler\n  scheduler=$(yq eval '.queue_manager' config.yml)\n  if [ \"$scheduler\" == \"null\" ]; then\n    scheduler=\"openpbs\"\n  fi\n\n  SCHEDULER=$scheduler\n  echo \"Running on $SCHEDULER\"\n}\n\nfunction get_ood_auth ()\n{\n  local ood_auth\n  ood_auth=$(yq eval '.authentication.httpd_auth' config.yml)\n  if [ \"$ood_auth\" == \"null\" ]; then\n    ood_auth=\"basic\"\n  fi\n\n  OOD_AUTH=$ood_auth\n  echo \"Authentication is $OOD_AUTH\"\n}\n\nfunction enable_winviz ()\n{\n  local enable_winviz\n  enable_winviz=$(yq eval '.enable_remote_winviz' config.yml)\n  if [ \"$enable_winviz\" == \"null\" ]; then\n    enable_winviz=false\n  fi\n\n  echo \"Enable WinViz is $enable_winviz\"\n  if [ \"$enable_winviz\" == \"true\" ]; then\n    ENABLE_WINVIZ_PLAYBOOK=$PLAYBOOKS_DIR/ood-overrides-guacamole.yml\n  else\n    touch $PLAYBOOKS_DIR/guacamole.ok\n    touch $PLAYBOOKS_DIR/guac_spooler.ok\n    ENABLE_WINVIZ_PLAYBOOK=\n  fi\n}\n\nfunction enable_lustre ()\n{\n  FEATURE_LUSTRE_IN_CONFIG=$(yq eval '.lustre.create' config.yml)\n  if [ \"$FEATURE_LUSTRE_IN_CONFIG\" != \"null\" ]; then\n    ENABLE_LUSTRE=$(yq '.lustre.create' ./config.yml | tr '[:upper:]' '[:lower:]')\n  else\n    LUSTRE_VM_IN_CONFIG=$(yq eval '.lustre.oss_count' config.yml)\n    if [ \"$LUSTRE_VM_IN_CONFIG\" == \"null\" ]; then\n      ENABLE_LUSTRE=false\n    else\n      ENABLE_LUSTRE=true\n    fi\n  fi\n  \n  if [ \"$ENABLE_LUSTRE\" == \"false\" ]; then\n    touch $PLAYBOOKS_DIR/lustre.ok\n    touch $PLAYBOOKS_DIR/lustre-sas.ok\n  fi\n}\n\nfunction use_existing_ad()\n{\n  local use_existing_ad\n  use_existing_ad=$(yq eval '.domain.use_existing_dc' config.yml)\n  if [ \"$use_existing_ad\" == \"null\" ]; then\n    use_existing_ad=false\n  fi\n\n  if [ \"$use_existing_ad\" == \"true\" ]; then\n    touch $PLAYBOOKS_DIR/ad.ok\n    touch $PLAYBOOKS_DIR/add_users.ok\n  fi\n\n}\n\nfunction use_local_users()\n{\n  local use_local_users\n  use_local_users=$(yq eval '.authentication.user_auth' config.yml)\n  if [ \"$use_local_users\" == \"local\" ]; then\n    use_local_users=true\n  fi\n\n  if [ \"$use_local_users\" == \"true\" ]; then\n    touch $PLAYBOOKS_DIR/ad.ok\n    touch $PLAYBOOKS_DIR/add_users.ok\n  else\n    touch $PLAYBOOKS_DIR/add_local_users.ok\n  fi\n}\n\nfunction use_grafana_telegraf()\n{\n  local use_grafana\n  local use_telegraf\n  use_grafana=$(yq eval '.monitoring.grafana' config.yml)\n  use_telegraf=$(yq eval '.monitoring.telegraf' config.yml)\n  \n  if [ \"$use_grafana\" == \"false\" ]; then\n    echo Skipping Grafana install\n    touch $PLAYBOOKS_DIR/grafana.ok\n  fi\n  if [ \"$use_telegraf\" == \"false\" ]; then\n    echo Skipping Telegraf install\n    touch $PLAYBOOKS_DIR/telegraf.ok\n  fi\n}\n\n\n# Ensure submodule exists\nif [ ! -d \"${PLAYBOOKS_DIR}/roles/ood-ansible/.github\" ]; then\n    printf \"Installing OOD Ansible submodule\\n\"\n    git submodule init\n    git submodule update\nfi\n\n# Validate config against schema\n$THIS_DIR/validate_config.sh config.yml\n\nget_scheduler\nget_ood_auth\nenable_winviz\nenable_lustre\nuse_existing_ad\nuse_local_users\nuse_grafana_telegraf\n\ncase $TARGET in\n  all)\n    run_playbook ad\n    run_playbook dns\n    run_playbook linux\n    run_playbook grafana\n    run_playbook lustre-sas\n    run_playbook lustre\n    run_playbook ccportal\n    run_playbook add_users\n    run_playbook add_local_users\n    run_playbook cccluster\n    run_playbook scheduler\n    run_playbook ood $PLAYBOOKS_DIR/ood-overrides-common.yml $PLAYBOOKS_DIR/ood-overrides-$SCHEDULER.yml $PLAYBOOKS_DIR/ood-overrides-auth-$OOD_AUTH.yml $ENABLE_WINVIZ_PLAYBOOK\n    run_playbook ood-custom\n    run_playbook guacamole\n    run_playbook guac_spooler\n    run_playbook telegraf\n    run_playbook chrony\n  ;;\n  lustre)\n    run_playbook lustre-sas\n    run_playbook lustre\n  ;;\n  ad | ad2 | linux | add_users | add_local_users | ccportal | chrony | cccluster | scheduler | grafana | telegraf | ood-custom | remove_users | tests | guacamole | guac_spooler | dns)\n    run_playbook $TARGET\n  ;;\n  ood)\n    run_playbook ood $PLAYBOOKS_DIR/ood-overrides-common.yml $PLAYBOOKS_DIR/ood-overrides-$SCHEDULER.yml $PLAYBOOKS_DIR/ood-overrides-auth-$OOD_AUTH.yml $ENABLE_WINVIZ_PLAYBOOK\n    run_playbook ood-custom\n  ;;\n  *)\n    echo \"unknown target\"\n    exit 1\n  ;;\nesac\n\n", "num_lines": 212}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Usage:\n# run_ui_tests user <test_name> <playright_options>\n#   test_name: any .ts file located in ./tests\n#   playright_options: --debug\nset -e\nUSER_NAME=$1\nAZHOP_CONFIG=config.yml\nANSIBLE_VARIABLES=playbooks/group_vars/all.yml\n\necho \"Retrieve Username, password and FQDN\"\nkey_vault=$(yq eval '.key_vault' $ANSIBLE_VARIABLES)\nif [ -z \"$USER_NAME\" ]; then\n    USER_NAME=$(yq eval '.users[0].name' $AZHOP_CONFIG)\nelse\n    shift\nfi\n\npassword=$(./bin/get_secret $USER_NAME)\nexport AZHOP_USER=$USER_NAME\nexport AZHOP_PASSWORD=$password\n\nfqdn=$(yq eval '.ondemand_fqdn' $ANSIBLE_VARIABLES)\nexport AZHOP_FQDN=\"https://$fqdn\"\n\necho \"FQDN is $AZHOP_FQDN\"\necho \"User is $AZHOP_USER\"\nnpx playwright test --config=tests/playwright.config.ts $@\n", "num_lines": 29}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nCONFIG=${1:-${THIS_DIR}/config.yml}\nSCHEMA=${THIS_DIR}/config.schema.json\n\n# validate that check-jsonschema is installed\nif ! command -v check-jsonschema &> /dev/null\nthen\n    echo \"check-jsonschema could not be found\"\n    echo \"Please update the toolchain by running: ./toolset/scripts/install.sh\"\n    exit 1\nfi\n\nfunction validate_config_yml {\n    local config=$1\n    # validate file against schema\n    tmp_json=${config}.json\n    yq $config -o json > $tmp_json\n    set +e\n    check-jsonschema --schemafile $SCHEMA $tmp_json\n    retcode=$?\n    set -e\n    rm $tmp_json\n\n    if [[ $retcode -ne 0 ]]; then \n        echo \"$config fails validation\"\n        exit 1\n    fi\n    echo \"$config passes validation\"\n}\n\nyamllint $CONFIG\nvalidate_config_yml $CONFIG\n", "num_lines": 35}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset +e\nAZHOP_CONFIG=config.yml\nANSIBLE_VARIABLES=playbooks/group_vars/all.yml\n\nif [ ! -e $AZHOP_CONFIG ]; then\n  echo \"$AZHOP_CONFIG doesn't exist, exiting\"\n  exit 1\nfi\n\nrg=$(yq '.resource_group' $AZHOP_CONFIG)\n\n# Delete and Purge keyvault\nkey_vault=$(yq eval '.key_vault' $ANSIBLE_VARIABLES)\nif [ \"$key_vault\" != \"\" ]; then\n    echo \"Delete keyvault $key_vault\"\n    az keyvault delete --name $key_vault\n    echo \"Purging keyvault $key_vault\"\n    az keyvault purge --name $key_vault\nfi\n\n# Remove role assignments for ccportal at the subscription level\nccportal_id=$(az vm show -n ccportal -g $rg --query 'identity.principalId' -o tsv)\nif [ \"$ccportal_id\" != \"\" ]; then\n  echo \"Removing role assignments for ccportal\"\n  az role assignment delete --assignee $ccportal_id\nfi\n\n# Remove Role assignments for ccportal at the resource group level\naz role assignment list --assignee $ccportal_id -g $rg --query \"[].{name:roleDefinitionName, scope:scope}\" -o tsv | while read name scope; do\n  echo \"Removing role assignment $name for ccportal\"\n  az role assignment delete --assignee $ccportal_id --role $name --scope $scope\ndone\n\n# removing first peer => need to work to do all !!!!\npeered_vnet=$(yq \".network.peering[0].vnet_name\" $AZHOP_CONFIG)\nif [ \"$peered_vnet\" != \"null\" ]; then\n    peered_vnet_rg=$(yq \".network.peering[0].vnet_resource_group\" $AZHOP_CONFIG)\n    if [ \"$peered_vnet_rg\" != \"null\" ]; then\n      id=$(az network vnet peering list -g $peered_vnet_rg --vnet-name $peered_vnet --query \"[?remoteVirtualNetwork.resourceGroup=='$rg'].id\" -o tsv)\n      if [ \"$id\" != \"\" ]; then\n        echo \"Deleting peering $id\"\n        az network vnet peering delete --ids $id\n      fi\n    fi\nfi", "num_lines": 46}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eo pipefail\n\nretry_command() {\n    local cmd=$1\n    local retries=${2:-5}\n    local delay=${3:-10}\n\n    set +eo pipefail\n\n    for ((i=0; i<retries; i++)); do\n        echo \"Running command: $cmd\"\n        $cmd\n\n        if [ $? -eq 0 ]; then\n            echo \"Command succeeded!\"\n            set -eo pipefail\n            return 0\n        else\n            echo \"Command failed. Retrying in ${delay}s...\"\n            sleep $delay\n        fi\n    done\n\n    echo \"Command failed after $retries retries.\"\n    set -eo pipefail\n    return 1\n}\n\necho \"* apt updating\"\nretry_command \"apt update\"\n\necho \"* Update SSH port\"\nsed -i 's/^#Port 22/Port __SSH_PORT__/' /etc/ssh/sshd_config\nsystemctl restart sshd\n\necho \"* Installing git\"\nretry_command \"apt install -y git\"\n\necho \"* Cloning az-hop repo\"\nif [ -e az-hop ]; then\n    rm -rf az-hop\nfi\ngit clone -b __INSERT_AZHOP_BRANCH__ --recursive https://github.com/Azure/az-hop.git\n\ncd az-hop\nexport azhop_root=$(pwd)\necho \"* Installing azhop toolset dependencies\"\nexport HOME=/root # hack to fix conda install in cloud-init\nretry_command \"./toolset/scripts/install.sh\"\n\nmkdir -p $azhop_root/deploy\ncd $azhop_root/deploy\n\necho \"* Logging in to Azure\"\n# Add retry logic as it could take some delay to apply the Managed Identity\ntimeout 120s bash -c 'until az login -i; do sleep 10; done'\n\ndeployment_name=azhop\nresource_group=$(curl -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2017-08-01\" | jq -r .compute.resourceGroupName)\n\necho \"* Waiting for deployment to complete\"\nwhile deployment_state=$(az deployment group show -g $resource_group -n $deployment_name --query properties.provisioningState -o tsv); [ \"$deployment_state\" != \"Succeeded\" ]; do\n    echo \"Deployment is not yet complete (currently $deployment_state). Waiting...\"\n    sleep 10\ndone\n\necho \"* Getting keys from keyvault\"\naz deployment group show \\\n    -g $resource_group \\\n    -n $deployment_name \\\n    --query properties.outputs \\\n    > azhopOutputs.json\n\nkv=$(jq -r .keyvaultName.value azhopOutputs.json)\nadminuser=$(jq -r .azhopConfig.value.admin_user azhopOutputs.json)\nexport admin_pass=\"$(az keyvault secret show --vault-name $kv -n ${adminuser}-password --query \"value\" -o tsv)\"\n\necho \"* Getting keys from keyvault\"\naz keyvault secret show --vault-name $kv -n ${adminuser}-pubkey --query \"value\" -o tsv > ../${adminuser}_id_rsa.pub\naz keyvault secret show --vault-name $kv -n ${adminuser}-privkey --query \"value\" -o tsv > ../${adminuser}_id_rsa\nchmod 600 ../${adminuser}_id_rsa*\n\necho \"* Generating config files from templates\"\n# config.yml\njq .azhopConfig.value azhopOutputs.json | yq -P  > $azhop_root/config.yml\n\nmkdir -p $azhop_root/bin\njq -r .azhopGetSecretScript.value azhopOutputs.json > $azhop_root/bin/get_secret\nchmod +x $azhop_root/bin/get_secret\njq -r .azhopConnectScript.value azhopOutputs.json > $azhop_root/bin/connect\nchmod +x $azhop_root/bin/connect\n\n# create the group_vars/all.yml\nmkdir -p $azhop_root/playbooks/group_vars\njq '. | .azhopGlobalConfig.value.global_config_file=$param' --arg param $azhop_root/config.yml azhopOutputs.json > tmp.json\ncp tmp.json azhopOutputs.json\njq .azhopGlobalConfig.value azhopOutputs.json | yq -P > $azhop_root/playbooks/group_vars/all.yml\n\njq '.azhopInventory.value.all.hosts *= (.lustre_oss_private_ips.value | to_entries | map({(\"lustre-oss-\" + (.key | tostring)): {\"ansible_host\": .value}}) | add // {}) | .azhopInventory.value' azhopOutputs.json | yq -P > $azhop_root/playbooks/inventory\n# substitute passwords into the file\n#  - __ADMIN_PASSWORD__\nsed -i \"s/__ADMIN_PASSWORD__/$(sed 's/[&/\\]/\\\\&/g' <<< $admin_pass)/g\" $azhop_root/playbooks/inventory\n\njq .azhopPackerOptions.value azhopOutputs.json > $azhop_root/packer/options.json\n\n# We probably don't want to build custom images as part of the cloud-init step\n# if [ \"$(jq -r .azhopConfig.value.features.sig azhopOutputs.json)\" == \"true\" ]; then\n#     echo \"* Building images\"\n#     cd $azhop_root/packer\n#     ./build_image.sh -i azhop-compute-centos-7.9.json\n#     ./build_image.sh -i azhop-desktop-centos-7.9.json\n# fi\n\n \n\necho \"* Generating passwords\"\ncd $azhop_root\n./create_passwords.sh\n\necho \"* Running Ansible\"\n#export ANSIBLE_VERBOSITY=2\nretry_command \"./install.sh\"", "num_lines": 123}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nos=$1\nlot=$2\nazhop_playbooks=$THIS_DIR/../playbooks\n\nfunction usage() {\n    echo \"Usage: $0 <os> <lot>\"\n    echo \"  os: centos7 | centos8\"\n    echo \"  lot: lot1 | lot2 | lot3\"\n    exit 1\n}\n\nif [ -z \"$os\" ]; then\n    usage\nfi\n\nif [ -z \"$lot\" ]; then\n    usage\nfi\n\nvar_name=CIS_PLAYBOOK_DIR_${os}\nif [ -z \"${!var_name}\" ]; then\n  echo \"The $var_name environment variable is not set. Please set (export $var_name=foo) it to the directory where the CIS playbooks for OS $os are stored.\"\n  exit 1\nfi\n\nRULES=$THIS_DIR/$os/rules.yml\necho \"Using CIS playbooks from ${!var_name}\"\n\nfunction appply_rules() {\n    lot=$1\n    echo \"Applying tags for lot $lot\"\n    if [ -z \"$lot\" ]; then\n      echo \"No lot to apply\"\n      return\n    fi\n\n    # Get the rules for the lot\n    if [ \"$lot\" == \"all\" ]; then\n      eval_str=\".rulesets[].rules\"\n    else\n      eval_str=\".rulesets[] | select(.name == \"\\\"$lot\"\\\").rules\"\n    fi\n\n    readarray rules < <(yq eval \"$eval_str\" $RULES)\n    if [ -z \"$rules\" ]; then\n      echo \"No rules found for lot $lot\"\n      exit 1\n    fi\n\n    echo \"Applying rules for lot $lot\"\n    for rule in \"${rules[@]}\"; do\n      tag=$(echo \"$rule\" | cut -d'-' -f 2)\n      tags+=\"$tag,\"\n    done\n    tags+=\" run_audit\"\n\n    echo \"Applying tags: $tags\"\n    ansible-playbook -i $azhop_playbooks/inventory -i $azhop_playbooks/inventory.cis.yml $THIS_DIR/$os/main.yml --tags \"$tags\" -e \"CIS_playbook_dir=${!var_name}\" #--list-tasks\n}\n\nappply_rules $lot\n", "num_lines": 64}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nvault_name=$1\ndebug=1\ncreds=$(az keyvault secret show --query \"value\" --name marketplace-credentials --vault-name $vault_name -o tsv)\n\ntenantId=$(echo $creds | jq -r .tenant)\nappId=$(echo $creds | jq -r .appId)\npassword=$(echo $creds | jq -r .password)\n\nreq=\nres=\n\nprint_last() {\n    #echo \"$req\"\n    echo \"$res\" | jq .\n}\n\n# legacy API\nauthenticate_legacy() {\n    req='curl -s -d \"grant_type=client_credentials&client_id=${appId}&client_secret=${password}&resource=https://cloudpartner.azure.com\" -X POST https://login.microsoftonline.com/$tenantId/oauth2/token'\n    res=$(eval $req)\n    legacy_token=$(echo $res | jq -r .access_token)\n    if [ ! $debug -eq 0 ]; then\n        print_last\n    fi\n}\n\nget_offers() {\n    publisherId=${1:-\"\"}\n    req='curl -s -X GET \"https://cloudpartner.azure.com/api/publishers/${publisherId}/offers?api-version=2017-10-31\" -H \"Authorization: Bearer $legacy_token\" -H \"accept: application/json\"'\n    res=$(eval $req)\n    if [ ! $debug -eq 0 ]; then\n        print_last\n    fi\n}\n\nget_offer_by_id() {\n    publisherId=${1:-\"\"}\n    offerId=${2:-\"\"}\n    req='curl -s -X GET \"https://cloudpartner.azure.com/api/publishers/${publisherId}/offers/${offerId}?api-version=2017-10-31\" -H \"Authorization: Bearer $legacy_token\" -H \"accept: application/json\"'\n    res=$(eval $req)\n    if [ ! $debug -eq 0 ]; then\n        print_last\n    fi\n}\n\n# PUT https://cloudpartner.azure.com/api/publishers/<publisherId>/offers/<offerId>?api-version=2017-10-31\nput_offer() {\n    publisherId=${1:-\"\"}\n    offerId=${2:-\"\"}\n    jsonFile=${3:=\"\"}\n\n    #curl -X PUT -H \"Content-Type: application/json\" -H \"Authorization: Bearer $legacy_token\" -d '{\"key1\":\"value\"}' \"https://cloudpartner.azure.com/api/publishers/${publisherId}/offers/${offerId}?api-version=2017-10-31\"\n    req='curl -s -X PUT -H \"Content-Type: application/json\" -H \"Authorization: Bearer $legacy_token\" -d \"$(<$jsonFile)\" \"https://cloudpartner.azure.com/api/publishers/${publisherId}/offers/${offerId}?api-version=2017-10-31\"'\n\n    res=$(eval $req)\n    if [ ! $debug -eq 0 ]; then\n        print_last\n    fi\n}\n", "num_lines": 61}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -o pipefail\n\noffer=$1\nos=$2\n\nSA_ACCOUNT=azhop\n\nos_disk_id=$(az disk list -g azhop_build_images --query \"[?name=='${offer}-${os}'].id\" -o tsv)\nversion=$(az disk show --id $os_disk_id --query \"tags.Version\" -o tsv)\n\necho \"Check if version exists and if not then add a new one\"\n\nexists=$(jq '.definition.plans[] | select(.planId==$plan) | .\"microsoft-azure-virtualmachines.vmImages\" | has($version)' --arg plan ${os} --arg version ${version} ${offer}-${os}.json)\nif [ \"$exists\" == \"true\" ]; then\n    echo \"Version $version of plan $os already exists, exiting\"\n    exit \nfi\n\nstart=$(date -u -d \"-10 minutes\" '+%Y-%m-%dT%H:%MZ')\nexpiry=$(date -u -d \"+4 years\" '+%Y-%m-%dT%H:%MZ') # 4 years expiration SAS\n\nicon_sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name icons --permissions rl --start $start --expiry $expiry --output tsv)\nimage_sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name images --permissions rl --start $start --expiry $expiry --output tsv)\n\nsasurl=$(echo \"https://$SA_ACCOUNT.blob.core.windows.net/images/${offer}-${os}-v${version}.vhd?${image_sas}\")\n\ncat <<EOF >temp.json\n{\n    \"$version\": {\n    \"osVhdUrl\": \"$sasurl\",\n    \"lunVhdDetails\": []\n    }\n}\nEOF\n\necho \"Adding version $version to ${offer}-${os}\"\ncat temp.json\n\n# For this plan\n# Add the new version to the existing versions\njq '(.definition.plans[] | select(.planId==$plan).\"microsoft-azure-virtualmachines.vmImages\") += $version ' --arg plan ${os} --argjson version \"$(jq '.' temp.json)\" ${offer}-${os}.json > ${offer}-${os}-final.json\n\n#fname=./offers/${offer}-${os}-final.json\n\n#cp ./offers/${offer}-${os}.json $fname\n\n#sed -i 's#INSERT_VHD_URL#'\"$sasurl\"'#g' $fname\n\n# Don't bother with this as it will be done manually in the partner portal\n\n# Add current subscription to the allowed ones\n# tenantId=$(az account show | jq -r '.id')\n# sed -i 's#INSERT_ALLOWED_SUBSCRIPTIONS#'\"$tenantId\"'#g' $fname\n\n# # Add logo URLs\n# for sz in small medium large wide; do\n\n#     # get sas key from log and escape ampsand\n#     sasurl=$(echo \"https://$SA_ACCOUNT.blob.core.windows.net/icons/$offer/azhop-${offer}-${sz}.png?${icon_sas}\" | sed 's/\\&/\\\\\\&/g')\n#     sed -i 's#INSERT_'$(echo $sz | tr [:lower:] [:upper:])'_LOGO_URL#'\"$sasurl\"'#g' $fname\n\n# done\n", "num_lines": 65}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -o pipefail\n\nosdisk_name=$1\nosdisk_resource_group=$2\n\necho \"Retrieving the os_disk_id for disk name $osdisk_name\"\nos_disk_id=$(az disk list -g azhop_build_images --query \"[?name=='$osdisk_name'].id\" -o tsv)\n\necho \"Retrieving the image version for os disk\"\nimage_version=$(az disk show --id $os_disk_id --query \"tags.Version\" -o tsv)\necho \"Image version is $image_version\"\necho \"Create the disk SAS\"\nosdisk_sas=$(az disk grant-access --access-level Read --duration-in-seconds 3600 --name $osdisk_name --resource-group $osdisk_resource_group | jq .accessSas -r)\n\nSA_ACCOUNT=azhop\nSA_CONTAINER=images\n\nimage_name=$osdisk_name-v$image_version.vhd\n\nstart=$(date -u -d \"-10 minutes\" '+%Y-%m-%dT%H:%MZ')\nexpiry=$(date -u -d \"+1 hour\" '+%Y-%m-%dT%H:%MZ')\n\nrw_sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rwdl --start $start --expiry $expiry --output tsv)\n\nazcopy copy \"$osdisk_sas\" \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$image_name?${rw_sas}\"\n", "num_lines": 28}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\n\ntext=$1\ntmpfile=$SCRIPT_DIR/azhop_$text.png\n#tmpfiletext=tmp-azhop-${text}-text.png\n#tmpfile=tmp-azhop-${text}-orig.png\n#convert -background transparent -size 512x512 -stroke white -strokewidth 5 -fill blue -pointsize 156 -font Century-Schoolbook-L-Bold -gravity center label:\"$text\" $tmpfiletext\n#convert -composite -gravity center $SCRIPT_DIR/logo.png $tmpfiletext $tmpfile\n\nconvert $tmpfile -resize 216x216 -gravity center -background transparent -extent 216x216 azhop-${text}-large.png\nconvert $tmpfile -resize 90x90 -gravity center -background transparent -extent 90x90 azhop-${text}-medium.png\nconvert $tmpfile -resize 48x48 -gravity center -background transparent -extent 48x48 azhop-${text}-small.png\nconvert $tmpfile -resize 255x155 -gravity center -background transparent -extent 255x155 azhop-${text}-wide.png\n\n", "num_lines": 17}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ntext=$1\nSA_ACCOUNT=$2\nSA_CONTAINER=$3\n\nstart=$(date -u -d \"-10 minutes\" '+%Y-%m-%dT%H:%MZ')\nexpiry=$(date -u -d \"+1 week\" '+%Y-%m-%dT%H:%MZ')\n\nrw_sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rwdl --start $start --expiry $expiry --output tsv)\nro_sas=$(az storage container generate-sas --account-name $SA_ACCOUNT --name $SA_CONTAINER --permissions rl --start $start --expiry $expiry --output tsv)\n\nfor f in azhop-${text}-*.png; do\n    azcopy copy $f \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$text/?${rw_sas}\"\n    echo \"https://$SA_ACCOUNT.blob.core.windows.net/$SA_CONTAINER/$text/$f?${ro_sas}\"\ndone\n\n\n\n", "num_lines": 20}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nAZHOP_ROOT=${THIS_DIR}/../..\n\n\nif [ -d ${AZHOP_ROOT}/miniconda ]; then\n  echo \"Activating conda environment\"\n  source ${AZHOP_ROOT}/miniconda/bin/activate\nfi\n\nbuild_dir=\"build\"\nrm -rf $build_dir\nmkdir -p $build_dir\necho \"Converting YAML config to JSON\"\nyq -o=json <marketplace_config.yml >$build_dir/config.json\necho \"Embedding config into createUiDefinition.json\"\n# substitutions for the logic in the createUiDefinition\n# * _Xn_ is the nth octet of the baseIpAddress (string)\n# * _Xni_ is the nth octet of the baseIpAddress (int)\njq --argfile azhopConfig $build_dir/config.json '.parameters.outputs.azhopConfig += $azhopConfig' ui_definition.json \\\n    | sed \"s/_X1_/first(split(steps('network').baseIpAddress,'.'))/g\" \\\n    | sed \"s/_X2_/first(skip(split(steps('network').baseIpAddress,'.'),1))/g\" \\\n    | sed \"s/_X3_/first(skip(split(steps('network').baseIpAddress,'.'),2))/g\" \\\n    | sed \"s/_X4_/last(split(steps('network').baseIpAddress,'.'))/g\" \\\n    | sed \"s/_X1i_/int(first(split(steps('network').baseIpAddress,'.')))/g\" \\\n    | sed \"s/_X2i_/int(first(skip(split(steps('network').baseIpAddress,'.'),1)))/g\" \\\n    | sed \"s/_X3i_/int(first(skip(split(steps('network').baseIpAddress,'.'),2)))/g\" \\\n    | sed \"s/_X4i_/int(last(split(steps('network').baseIpAddress,'.')))/g\" \\\n    > $build_dir/createUiDefinition.json\nrm $build_dir/config.json\necho \"Converting Bicep to ARM template\"\naz bicep build --file ../../bicep/mainTemplate.bicep --outdir $build_dir\necho \"Adding tracking resource to ARM template\"\njq --argfile trackingResource tracking_resource.json '.resources += [$trackingResource]' $build_dir/mainTemplate.json > $build_dir/mainTemplateTracking.json\nmv $build_dir/mainTemplateTracking.json $build_dir/mainTemplate.json\necho \"Creating zipfile\"\npushd $build_dir\nzip -r ../$build_dir.zip *\npopd", "num_lines": 40}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Build an image with packer and the provided packer file\n# There are 2 options for providing the SPN used by packer\n#  - With environment variables like in github actions\n#     * ARM_CLIENT_ID, ARM_CLIENT_SECRET and ARM_TENANT_ID\n#  - Thru the spn.json config file\nset -e\nset -o pipefail\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nOPTIONS_FILE=options.json\nFORCE=0\nSPN_FILE=spn.json\nCONFIG_FILE=../config.yml\nANSIBLE_VARIABLES=../playbooks/group_vars/all.yml\n\nif [ $# -lt 2 ]; then\n  echo \"Usage build_image.sh \"\n  echo \"  Required arguments:\"\n  echo \"    -i|--image <image_file.json> | image packer file\"\n  echo \"   \"\n  echo \"  Optional arguments:\"\n  echo \"    -o|--options <options.json>  | file with options for packer generated in the build phase\"\n  echo \"    -f|--force                   | overwrite existing image and always push a new version in the SIG\"\n  echo \"    -k|--keep                    | keep os disk for future reused\"\n  exit 1\nfi\n\nload_miniconda() {\n  # Note: packaging this inside a function to avoid forwarding arguments to conda\n  if [ -d ${THIS_DIR}/../miniconda ]; then\n    echo \"Activating conda environment\"\n    source ${THIS_DIR}/../miniconda/bin/activate\n  fi\n}\n\nload_miniconda\n# Check config syntax\nyamllint $CONFIG_FILE\n\nPACKER_OPTIONS=\"-timestamp-ui\"\nKEEP_OS_DISK=\"false\"\n\nwhile (( \"$#\" )); do\n  case \"${1}\" in\n    -i|--image)\n      PACKER_FILE=${2}\n      shift 2\n    ;;\n    -o|--options)\n      OPTIONS_FILE=${2}\n      shift 2\n    ;;\n    -f|--force)\n      FORCE=1\n      PACKER_OPTIONS+=\" -force\"\n      shift 1\n    ;;\n    -k|--keep)\n      KEEP_OS_DISK=\"true\"\n      shift 1\n    ;;\n    *)\n      shift\n      ;;\n  esac\ndone\n\nif [ ! -f ${PACKER_FILE} ]; then\n  echo \"Packer file ${PACKER_FILE} not found\"\n  exit 1\nfi\n\ntenant_id=$(az account show -o json | jq -r .tenantId)\nuser_type=$(az account show --query user.type -o tsv)\nif [ ${user_type} == \"user\" ]; then\n  use_azure_cli_auth=true\nelse\n  export clientId=$(az account show --query user.name -o tsv)\n  case \"${clientId}\" in\n      \"systemAssignedIdentity\")\n          vmname=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2019-08-15\" | jq -r '.compute.name')\n          echo \" - logged in Azure with System Assigned Identity from ${vmname}\"\n          use_azure_cli_auth=false\n          ;;\n      \"userAssignedIdentity\")\n          echo \"userAssignedIdentity not supported; please use a systemAssignedIdentity or a Service Principal Name instead\"\n          exit 1\n          ;;\n      *)\n          use_azure_cli_auth=true\n          logged_user_upn=$(az ad sp show --id ${clientId} --query displayName -o tsv)\n          echo \" - logged in Azure with Service Principal Name ${logged_user_upn}\"\n          ;;\n  esac\nfi\n\nimage_name=$(basename \"$PACKER_FILE\")\nimage_name=\"${image_name%.*}\"\n\n# Retrieve the Image ID\nresource_group=$(jq -r '.var_resource_group' $OPTIONS_FILE)\nimage_id=$(az image list -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\n\n# Generate install script checksum\nset +e\nfind ./scripts/ -exec md5sum {} \\; > md5sum.txt\nmd5sum $PACKER_FILE >> md5sum.txt\nset -e\npacker_md5=$(md5sum md5sum.txt | cut -d' ' -f 1)\necho \"scripts checksum is $packer_md5\"\n\n# if the image exists compare the build scripts checksum\nif [ \"$image_id\" != \"\" ]; then\n  image_checksum=$(az image show --id $image_id --query \"tags.checksum\" -o tsv)\n  echo \"Image checksum is $image_checksum\"\n  if [ \"$packer_md5\" != \"$image_checksum\" ]; then\n    FORCE=1\n    PACKER_OPTIONS+=\" -force\"\n  fi\nfi\n\n# Build a new image if :\n#   - Image doesn't exists\n#   - Scripts to build the image have changed\n#   - The force option is used\nif [ \"$image_id\" == \"\" ] || [ $FORCE -eq 1 ]; then\n  logfile=\"${PACKER_FILE%.*}.log\"\n\n  # Retrieve on which cloud environment we run on\n  cloud_env=\"Public\"\n  account_env=$(az account show | jq '.environmentName' -r)\n  case \"$account_env\" in\n    AzureUSGovernment)\n      cloud_env=\"USGovernment\"\n      ;;\n    AzureCloud)\n      cloud_env=\"Public\"\n      ;;\n    *)\n      cloud_env=\"Public\"\n      ;;\n  esac\n\n  echo \"Build or Rebuid $image_name in $resource_group (writing log to $logfile)\"\n  key_vault_name=$(yq eval \".key_vault\" $ANSIBLE_VARIABLES)\n\n  echo \"Removing os disk if any\"\n  os_disk_id=$(az disk list -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\n  if [ \"$os_disk_id\" != \"\" ]; then\n    az disk delete --ids $os_disk_id -o tsv -y\n  fi\n\n  packer build $PACKER_OPTIONS -var-file $OPTIONS_FILE \\\n    -var \"var_use_azure_cli_auth=$use_azure_cli_auth\" \\\n    -var \"var_image=$image_name\" \\\n    -var \"var_img_version=$version\" \\\n    -var \"var_cloud_env=$cloud_env\" \\\n    -var \"var_key_vault_name=$key_vault_name\" \\\n    -var \"var_keep_os_disk=$KEEP_OS_DISK\" \\\n    $PACKER_FILE | tee $logfile\n\n  image_id=$(az image list -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\n  # Tag the image with the checksum \n  echo \"Tagging the source image with checksum $packer_md5\"\n  az image update --ids $image_id --tags checksum=$packer_md5 -o tsv\n\nelse\n  echo \"Image $image_name exists, skipping building the image\"\nfi\n\nsig_name=$(jq -r '.var_sig_name' $OPTIONS_FILE)\n\n# Create the image definition if it doesn't exists\nimg_def_id=$(az sig image-definition list -r $sig_name -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\nif [ \"$img_def_id\" == \"\" ]; then\n  echo \"Creating an image definition for $image_name\"\n  # Get the image definition from the config file\n  echo \"Read image definition from $CONFIG_FILE\"\n  eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .offer\"\n  offer=$(yq eval \"$eval_str\" $CONFIG_FILE)\n  eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .publisher\"\n  publisher=$(yq eval \"$eval_str\" $CONFIG_FILE)\n  eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .sku\"\n  sku=$(yq eval \"$eval_str\" $CONFIG_FILE)\n  eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .hyper_v\"\n  hyper_v=$(yq eval \"$eval_str\" $CONFIG_FILE)\n  if [ \"$hyper_v\" == \"\" ]; then \n    hyper_v=\"V1\"\n  fi\n  eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .os_type\"\n  os_type=$(yq eval \"$eval_str\" $CONFIG_FILE)\n\n  az sig image-definition create -r $sig_name -i $image_name -g $resource_group \\\n                -f $offer --os-type $os_type -p $publisher -s $sku --hyper-v-generation $hyper_v \\\n                --query 'id' -o tsv\n  img_def_id=$(az sig image-definition list -r $sig_name -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\nelse\n  echo \"Image definition for $image_name found in gallery $sig_name\"\nfi\n\n# Check if the version of the managed image (retrieved thru the tag) exists in the SIG, if not then push to the SIG\nimage_id=$(az image list -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\nimage_version=$(az image show --id $image_id --query \"tags.Version\" -o tsv)\n\n# Check if the image version exists in the SIG\necho \"Looking for image $image_name version $image_version ...\"\nimg_version_id=$(az sig image-version list  -r $sig_name -i $image_name -g $resource_group --query \"[?name=='$image_version'].id\" -o tsv)\n\nif [ \"$img_version_id\" == \"\" ] || [ $FORCE -eq 1 ]; then\n  # Create an image version Major.Minor.Patch with Patch=YYmmddHHMM\n  #patch=$(date +\"%g%m%d%H%M\" | cut -c 1-9)\n  #eval_str=\".images[] | select(.name == \"\\\"$image_name\"\\\") | .version\"\n  #version=$(yq eval \"$eval_str\" $CONFIG_FILE)\n  #version+=\".$patch\"\n  # Image version is YYY.MMDD.HHMM\n  version=$(date -u +\"%Y.%m%d.%H%M\")\n  echo \"Pushing version $version of $image_name in $sig_name\"\n\n  storage_type=$(az image show --id $image_id --query \"storageProfile.osDisk.storageAccountType\" -o tsv)\n  location=$(jq -r '.var_location' $OPTIONS_FILE)\n\n  az sig image-version create \\\n    --resource-group $resource_group \\\n    --gallery-name $sig_name \\\n    --gallery-image-definition $image_name \\\n    --gallery-image-version $version \\\n    --storage-account-type $storage_type \\\n    --location $location \\\n    --replica-count 1 \\\n    --managed-image $image_id \\\n    -o tsv\n\n  # Tag the image with the version \n  echo \"Tagging the source image with version $version and checksum $packer_md5\"\n  az image update --ids $image_id --tags Version=$version checksum=$packer_md5 -o tsv\n\n  # Tag the os disk with version\n  if [ \"$KEEP_OS_DISK\" == \"true\" ]; then\n    echo \"Tagging the os disk with version $version\"\n    os_disk_id=$(az disk list -g $resource_group --query \"[?name=='$image_name'].id\" -o tsv)\n    az disk update --ids $os_disk_id --set tags.'Version'=$version -o tsv\n  fi\nelse\n  echo \"Image $image_name version $image_version found in galley $sig_name\" \nfi\n", "num_lines": 246}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nyum install -y git\n\ndf -h\n\nmkdir -p /mnt/resource\nchmod 777 /mnt/resource\ncd /mnt/resource\n\ngit clone https://github.com/edwardsp/azhpc-images -b azhop_alma87\n\ncd ./azhpc-images/alma/alma-8.x/alma-8.7-hpc\n\n./install.sh\n\n#cd /mnt/resource/azhpc-images/tests/run-tests.sh --mofed-lts false\n", "num_lines": 18}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n#\n# setup systemd service\n#\n\ncat <<EOF >/usr/sbin/azure_persistent_rdma_naming.sh\n#!/bin/bash\n\nan_index=0\nib_index=0\n\nfor old_device in \\$(ibdev2netdev -v | sort -n | cut -f2 -d' '); do\n\n\tlink_layer=\\$(ibv_devinfo -d \\$old_device | sed -n 's/^[\\ \\t]*link_layer:[\\ \\t]*\\([a-zA-Z]*\\)\\$/\\1/p')\n\t\n\tif [ \"\\$link_layer\" = \"InfiniBand\" ]; then\n\t\t\n\t\trdma dev set \\$old_device name mlx5_ib\\${ib_index}\n\t\tib_index=\\$((\\$ib_index + 1))\n\t\t\n\telif [ \"\\$link_layer\" = \"Ethernet\" ]; then\n\t\n\t\trdma dev set \\$old_device name mlx5_an\\${ib_index}\n\t\tan_index=\\$((\\$an_index + 1))\n\t\t\n\telse\n\t\n\t\techo \"Unknown device type for \\$old_device - \\$device_type.\"\n\t\t\n\tfi\n\t\ndone\nEOF\nchmod 755 /usr/sbin/azure_persistent_rdma_naming.sh\n\ncat <<EOF >/etc/systemd/system/azure_persistent_rdma_naming.service\n[Unit]\nDescription=Azure persistent RDMA naming\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart=/usr/sbin/azure_persistent_rdma_naming.sh\nRemainAfterExit=true\nStandardOutput=journal\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable azure_persistent_rdma_naming.service\nsystemctl start azure_persistent_rdma_naming.service\n", "num_lines": 55}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndnf install -y epel-release\ndnf install -y libglvnd-devel pkgconfig\ndnf install -y dkms\n\ncat <<EOF >/etc/modprobe.d/nouveau.conf\nblacklist nouveau\nblacklist lbm-nouveau\nEOF\n\necho \"################### INSTALL NVIDIA GRID DRIVERS\"\necho \"################### UNLOAD NVIDIA MODULES\"\nsystemctl stop nv_peer_mem.service\nsystemctl stop nvidia-fabricmanager\nsystemctl stop dcgm.service\nsystemctl stop nvidia-dcgm.service\n\nrmmod gdrdrv\nrmmod nvidia_drm\nrmmod drm_kms_helper\nlsof /dev/nvidia0\n# nv_hostengine_pid=$(lsof /dev/nvidia0 | tail -n 1 | cut -d' ' -f2)\n# echo \"Kill process $nv_hostengine_pid\"\n# sudo kill -9 $nv_hostengine_pid\n#lsof /dev/nvidia0\nrmmod nvidia_modeset\nrmmod nvidia_uvm\nrmmod nvidia\nrmmod drm\n\n#init 3\nlsmod\n\n# remove previous kernel modules\nsudo /sbin/dkms status\nsudo /sbin/dkms status | grep nvidia | cut -d',' -f1 | xargs -I{} /sbin/dkms remove {} --all\n#rm -f /lib/modules/$(uname -r)/kernel/drivers/video/*.ko\n\n# Use the direct link which contains the clear version number\n# Check which latest version to use from https://github.com/Azure/azhpc-extensions/blob/master/NvidiaGPU/resources.json\nwget -O /mnt/NVIDIA-Linux-x86_64-grid.run https://download.microsoft.com/download/6/b/d/6bd2850f-5883-4e2a-9a35-edbd3dd6808c/NVIDIA-Linux-x86_64-525.105.17-grid-azure.run\nchmod +x /mnt/NVIDIA-Linux-x86_64-grid.run\nsudo /mnt/NVIDIA-Linux-x86_64-grid.run -s --no-check-for-alternate-installs\ncat /var/log/nvidia-installer.log\nset -e\n/sbin/dkms install --no-depmod -m nvidia -v 525.105.17 -k $(uname -r) --force\n# Answers are: yes, yes, yes\nsudo cp /etc/nvidia/gridd.conf.template /etc/nvidia/gridd.conf\n\ncat <<EOF >>/etc/nvidia/gridd.conf\nIgnoreSP=FALSE\nEnableUI=FALSE \nEOF\nsed -i '/FeatureType=0/d' /etc/nvidia/gridd.conf\n\necho \"Test if nvidia-smi is working\"\nset -e\nnvidia-smi\nset +e\n\necho \"################### INSTALL VirtualGL / VNC\"\ndnf groupinstall -y xfce\ndnf remove -y xfce4-screensaver\ndnf install -y https://kumisystems.dl.sourceforge.net/project/turbovnc/3.0.3/turbovnc-3.0.3.x86_64.rpm\ndnf install -y python3-websockify\n\nwget --no-check-certificate \"https://virtualgl.com/pmwiki/uploads/Downloads/VirtualGL.repo\" -O /etc/yum.repos.d/VirtualGL.repo\n\nyum install -y VirtualGL turbojpeg xorg-x11-apps\nset -e\n/usr/bin/vglserver_config -config +s +f -t\nset +e\nsystemctl disable firstboot-graphical\nsystemctl set-default graphical.target\nsystemctl isolate graphical.target\n\ncat <<EOF >/etc/rc.d/rc3.d/busidupdate.sh\n#!/bin/bash\nnvidia-xconfig --enable-all-gpus --allow-empty-initial-configuration -c /etc/X11/xorg.conf --virtual=1920x1200 -s\n# https://virtualgl.org/Documentation/HeadlessNV\nsed -i '/NVIDIA/a\\    Option         \"HardDPMS\" \"false\"' /etc/X11/xorg.conf\nEOF\nchmod +x /etc/rc.d/rc3.d/busidupdate.sh\n/etc/rc.d/rc3.d/busidupdate.sh\n\n# Create a vglrun alias\ncat <<EOF >/etc/profile.d/vglrun.sh \n#!/bin/bash\n# Set the vglrun alias to pickup a GPU device based on the noVNC port so that each session is landing on a different GPU, modulo the number of GPU devices.\nngpu=\\$(lspci | grep NVIDIA | wc -l)\nalias vglrun='/usr/bin/vglrun -d :0.\\$(( \\${port:-0} % \\${ngpu:-1}))'\nEOF\n\n# browser and codecs\ndnf install -y https://mirrors.rpmfusion.org/free/el/rpmfusion-free-release-8.noarch.rpm\ndnf -y install firefox ffmpeg ffmpeg-devel\n\n# Install archive manager\ndnf install -y file-roller\n#dnf -y install xarchiver\n#rm -f /usr/libexec/thunar-archive-plugin/gnome-file-roller.tap\n#ln -s /usr/libexec/thunar-archive-plugin/xarchiver.tap /usr/libexec/thunar-archive-plugin/gnome-file-roller.tap\n#update-desktop-database /usr/share/applications\n\n# increase buffer size\ncat << EOF >>/etc/sysctl.conf\nnet.core.rmem_max=2097152\nnet.core.wmem_max=2097152\nEOF\n", "num_lines": 111}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndnf install -y dnf-plugins-core\ndnf install -y epel-release\ndnf config-manager --enable epel\ndnf config-manager --enable powertools\n\ndnf install -y sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python-utils\ndnf install -y nfs-utils openssl-devel epel-release ca-certificates nc\ndnf install -y patch gcc gcc-c++ perl-Data-Dumper perl-Thread-Queue Lmod hwloc numactl jq htop python3 libXt\n\n# Disable requiretty to allow run sudo within scripts\nsed -i -e 's/Defaults    requiretty.*/ #Defaults    requiretty/g' /etc/sudoers\n\n# disable selinux\nsetenforce 0\nsed -i 's/SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config\n\ncat << EOF >> /etc/security/limits.d/10-azhop.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Install azcopy\ncd /usr/local/bin\nwget -q https://aka.ms/downloadazcopy-v10-linux -O - | tar zxf - --strip-components 1 --wildcards '*/azcopy'\nchmod 755 /usr/local/bin/azcopy\n", "num_lines": 32}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n   \nDISTRIB_CODENAME=el8\nLUSTRE_VERSION=2.15.1_24_gbaa21ca\nREPO_PATH=/etc/yum.repos.d/amlfs.repo\n   \nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n   \necho -e \"[amlfs]\" > ${REPO_PATH}\necho -e \"name=Azure Lustre Packages\" >> ${REPO_PATH}\necho -e \"baseurl=https://packages.microsoft.com/yumrepos/amlfs-${DISTRIB_CODENAME}\" >> ${REPO_PATH}\necho -e \"enabled=1\" >> ${REPO_PATH}\necho -e \"gpgcheck=1\" >> ${REPO_PATH}\necho -e \"gpgkey=https://packages.microsoft.com/keys/microsoft.asc\" >> ${REPO_PATH}\n\ndnf install -y amlfs-lustre-client-${LUSTRE_VERSION}-$(uname -r | sed -e \"s/\\.$(uname -p)$//\" | sed -re 's/[-_]/\\./g')-1\n", "num_lines": 19}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nBUILD_FROM_SOURCE=yes\n\nif [ \"$BUILD_FROM_SOURCE\" == \"yes\" ] ; then\n    dnf install -y gcc make rpm-build libtool hwloc-devel \\\n        libX11-devel libXt-devel libedit-devel libical-devel \\\n        ncurses-devel perl postgresql-devel postgresql-contrib python2 python2-devel tcl-devel \\\n        tk-devel swig expat-devel openssl-devel libXext libXft \\\n        autoconf automake gcc-c++ git\n\n    cd /mnt\n    git clone https://github.com/open-mpi/hwloc.git -b v1.11\n    cd hwloc\n    ./configure --enable-static --enable-embedded-mode\n    make\n    cd ..\n    \n    wget -q https://github.com/openpbs/openpbs/releases/download/v19.1.1/pbspro-19.1.1.tar.gz -O pbspro-19.1.1.tar.gz\n    tar -xzf pbspro-19.1.1.tar.gz\n    cd pbspro-19.1.1/\n    ./configure --prefix=/opt/pbs PYTHON=/usr/bin/python2.7 CFLAGS=\"-I$PWD/../hwloc/include\" LDFLAGS=\"-L$PWD/../src\"\n    make\n    make install\n\n    /opt/pbs/libexec/pbs_postinstall execution\n    chmod 4755 /opt/pbs/sbin/pbs_iff /opt/pbs/sbin/pbs_rcp\nelse\n    wget https://github.com/openpbs/openpbs/releases/download/v20.0.1/openpbs_20.0.1.centos_8.zip\n    unzip -o pbspro_19.1.1.centos7.zip\n    dnf install epel-release -y\n    dnf install -y openpbs_20.0.1.centos_8/openpbs-execution-20.0.1-0.x86_64.rpm jq\n    rm -rf openpbs_20.0.1.centos_8.zip\n    rm -rf openpbs_20.0.1.centos_8\nfi\n", "num_lines": 36}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Based on: https://github.com/Azure/cyclecloud-slurm/blob/master/specs/default/cluster-init/files/00-build-slurm.sh\nset -e\n\nINSTALL_SLURM=no\n\nSLURM_VERSION=20.11.9\nBUILD_DIR=/mnt/slurm\nmkdir -p $BUILD_DIR\n\n#\n# Build SLURM\n#\n\nSLURM_FOLDER=\"slurm-${SLURM_VERSION}\"\nSLURM_PKG=\"slurm-${SLURM_VERSION}.tar.bz2\"\nDOWNLOAD_URL=\"https://download.schedmd.com/slurm\"\n\ncd $BUILD_DIR\n\ndnf -y install epel-release && dnf -q makecache\n\nif [ \"$SLURM_VERSION\" \\> \"20\" ]; then\n    PYTHON=python3\nelse\n    PYTHON=python2\nfi\n\ndnf install -y dnf-plugins-core\ndnf config-manager --set-enabled powertools\n\nif [ ! -e $BUILD_DIR/bin ]; then\n    mkdir -p $BUILD_DIR/bin\nfi\n\n#\n# Build PMIx\n#\ndnf -y install autoconf flex libevent-devel git\ncd $BUILD_DIR\nmkdir -p /opt/pmix/v3\nmkdir -p pmix\n\ngit clone https://github.com/openpmix/openpmix.git openpmix\ncd openpmix\ngit checkout v3.1\n./autogen.sh\n./configure --prefix=/opt/pmix/v3\nmake -j\nmake install\n\n\nif [ \"$INSTALL_SLURM\" = \"yes\" ]; then\n\n    dnf install -y make $PYTHON which rpm-build readline-devel openssl openssl-devel pam-devel perl-ExtUtils-MakeMaker gcc mysql mysql-devel wget gtk2-devel.x86_64 glib2-devel.x86_64 libtool m4 automake rsync\n    dnf install -y munge munge-devel munge-libs \n\n    #\n    # Build SLURM\n    #\n\n    ln -s `which $PYTHON` $BUILD_DIR/bin/python\n    export PATH=$PATH:$BUILD_DIR/bin\n    wget \"${DOWNLOAD_URL}/${SLURM_PKG}\"\n    rpmbuild --define \"_with_pmix --with-pmix=/opt/pmix/v3\" -ta ${SLURM_PKG}\n\n    #\n    # Install SLURM\n    #\n\n    dnf -y install /root/rpmbuild/RPMS/x86_64/slurm-${SLURM_VERSION}*.rpm /root/rpmbuild/RPMS/x86_64/slurm-slurmd-${SLURM_VERSION}*.rpm\n\n    #\n    # The below is needed to CycleCloud chef recipe\n    #\n    systemctl stop munge\n    userdel munge\n    mkdir -p /etc/slurm\n\nfi\n\n#\n# Install Enroot\n#\n\narch=$(uname -m)\ndnf install -y epel-release\ndnf install -y https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot-3.4.1-1.el8.${arch}.rpm\ndnf install -y https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot+caps-3.4.1-1.el8.${arch}.rpm\n\n# Install NVIDIA container support\n#DIST=$(. /etc/os-release; echo $ID$VERSION_ID)\n#curl -s -L https://nvidia.github.io/libnvidia-container/centos8/libnvidia-container.repo > /etc/yum.repos.d/libnvidia-container.repo\n#\n#dnf -y makecache\n#dnf -y install libnvidia-container-tools\n\n# Add kernel boot parameters\ngrep user.max_user_namespaces /etc/sysctl.conf || echo 'user.max_user_namespaces = 1417997' >> /etc/sysctl.conf\ngrep namespace.unpriv_enable /etc/default/grub || sed -i.bak 's/\\(GRUB_CMDLINE_LINUX.*\\)\"$/\\1 namespace.unpriv_enable=1 user_namespace.enable=1 vsyscall=emulate\"/' /etc/default/grub\n[ -e /boot/grub2/grub.cfg ] && grub2-mkconfig -o /boot/grub2/grub.cfg\n[ -e /boot/efi/EFI/centos/grub.cfg ] && grub2-mkconfig -o /boot/efi/EFI/centos/grub.cfg\n\nenroot version\n", "num_lines": 105}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -e /etc/yum.repos.d/influxdb.repo ]; then\necho \"#### Configuration repo for InfluxDB:\"\ncat <<EOF | tee /etc/yum.repos.d/influxdb.repo\n[influxdb]\nname = InfluxDB Repository - RHEL \\$releasever\nbaseurl = https://repos.influxdata.com/rhel/\\$releasever/\\$basearch/stable\nenabled = 1\ngpgcheck = 1\ngpgkey = https://repos.influxdata.com/influxdata-archive_compat.key\nEOF\nfi\n\necho \"#### Telegraf Installation:\"\ndnf -y install telegraf\n", "num_lines": 17}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for compute nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for desktop nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nyum install -y https://ecsft.cern.ch/dist/cvmfs/cvmfs-release/cvmfs-release-latest.noarch.rpm\nyum install -y cvmfs Lmod hwloc numactl\ncvmfs_config setup\ncurl https://cvmfs.blob.core.windows.net/generic/generic.azure.conf -o /etc/cvmfs/config.d/generic.azure.conf\ncurl https://cvmfs.blob.core.windows.net/generic/generic.azure.pub -o /etc/cvmfs/keys/generic.azure.pub\necho 'export MODULEPATH=$(/usr/share/lmod/lmod/libexec/addto --append MODULEPATH /cvmfs/generic.azure/opt/modules)' > /etc/profile.d/z01_modulepath_cvmfs_generic.azure.sh\n\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Install QT5 runtime\"\nyum install -y qt5-qtbase-gui qt5-qtscript qt5-qtsvg\n\necho \"Add Motif\"\nyum install -y motif motif-devel\n\necho \"Additional packages for Ansys Workbench\"\nyum install -y libXScrnSaver redhat-lsb-core openssl11-libs libpng12 libgfortran5 libcurl-devel json-c-devel", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n# Update packages\nyum update -y --exclude kernel*, kmod*\n\nyum install -y git\n\nchmod 777 /mnt/resource\ncd /mnt/resource\n\ngit clone https://github.com/Azure/azhpc-images -b centos-hpc-20220112\n\n# Fix to allow NVIDIA drivers to be installed\n#yum install -y https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/dkms-3.0.5-1.el7.noarch.rpm\n#sed -i 's/6d88af6382fa3013e158b60128ef1fb117f4a4cc0fb6225155a2f7ff1c4a147f/ade1051a189fe84a326b8021d1446eb03d48e0a998e8cada85081b27a89923f1/g' ./azhpc-images/centos/centos-7.x/common/install_nvidiagpudriver.sh\n#sed -i 's/4bf0cccc4764f59b69e1df3b104ba8ecb77dc4bd98264b89d20aabd290808100/586bf03a7b0c9827c80dc0a82c6e8fe780ff1d76d82b103866906e4cdd191710/g' ./azhpc-images/centos/centos-7.x/common/install_dcgm.sh\n\ncd ./azhpc-images/centos/centos-7.x/centos-7.9-hpc\ncat << EOF >>./install_nogpu.sh\n#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# cleanup downloaded tarballs\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz\nrm -rf -- */\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# Install NCCL\n#./install_nccl.sh\n\n# Install NVIDIA docker container\n#\\$COMMON_DIR/../centos/centos-7.x/common/install_docker.sh\n\n# cleanup downloaded tarballs\nrm -rf *.tar.gz *_offline.sh *.rpm *.run\n\n# Install DCGM\n#./install_dcgm.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# Network Optimization\n#\\$COMMON_DIR/network-tuning.sh\n\n# install persistent rdma naming\n\\$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# add udev rule\n\\$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n\\$COMMON_DIR/../centos/common/network-config.sh\n\n# install diagnostic script\n\\$COMMON_DIR/install_hpcdiag.sh\n\n# copy test file\n\\$COMMON_DIR/copy_test_file.sh\n\n# disable cloud-init\n./disable_cloudinit.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n./clear_history.sh\n\nEOF\n\nchmod +x ./install_nogpu.sh\n./install_nogpu.sh\n\n#./install.sh\n#cd /mnt/resource/azhpc-images/tests/run-tests.sh --mofed-lts false\n", "num_lines": 98}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nyum install -y epel-release\nyum install -y libglvnd-devel pkgconfig\nyum install -y dkms\nyum install -y \"kernel-devel-uname-r == $(uname -r)\"\n\ncat <<EOF >/etc/modprobe.d/nouveau.conf\nblacklist nouveau\nblacklist lbm-nouveau\nEOF\n\necho \"################### INSTALL CUDA\"\nNVIDIA_DRIVER_VERSION=470.82.01\nCUDA_VERSION=11-4\nyum-config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/cuda-rhel7.repo\nyum clean all\nyum -y install nvidia-driver-latest-dkms-$NVIDIA_DRIVER_VERSION \nyum -y install cuda-runtime-$CUDA_VERSION\nyum -y install https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/nvidia-libXNVCtrl-$NVIDIA_DRIVER_VERSION-1.el7.x86_64.rpm\nyum -y install https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/nvidia-libXNVCtrl-devel-$NVIDIA_DRIVER_VERSION-1.el7.x86_64.rpm\nyum -y install https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/nvidia-settings-$NVIDIA_DRIVER_VERSION-1.el7.x86_64.rpm\nyum -y install cuda-drivers-$NVIDIA_DRIVER_VERSION\n\necho \"################### INSTALL NVIDIA GRID DRIVERS\"\necho \"################### UNLOAD NVIDIA MODULES\"\nsystemctl stop nv_peer_mem.service\nsystemctl stop nvidia-fabricmanager\nrmmod gdrdrv\nrmmod drm_kms_helper\nlsof /dev/nvidia0\nnv_hostengine_pid=$(lsof /dev/nvidia0 | tail -n 1 | cut -d' ' -f2)\necho \"Kill process $nv_hostengine_pid\"\nsudo kill -9 $nv_hostengine_pid\nlsof /dev/nvidia0\nrmmod nvidia_drm nvidia_modeset nvidia\n\ninit 3\n# Use the direct link which contains the clear version number\n# Check which latest version to use from https://github.com/Azure/azhpc-extensions/blob/master/NvidiaGPU/resources.json\nwget -O NVIDIA-Linux-x86_64-grid.run https://download.microsoft.com/download/a/3/c/a3c078a0-e182-4b61-ac9b-ac011dc6ccf4/NVIDIA-Linux-x86_64-$NVIDIA_DRIVER_VERSION-grid-azure.run\nchmod +x NVIDIA-Linux-x86_64-grid.run\nsudo ./NVIDIA-Linux-x86_64-grid.run -s || exit 1\n# Answers are: yes, yes, yes\nsudo cp /etc/nvidia/gridd.conf.template /etc/nvidia/gridd.conf\n\ncat <<EOF >>/etc/nvidia/gridd.conf\nIgnoreSP=FALSE\nEnableUI=FALSE \nEOF\nsed -i '/FeatureType=0/d' /etc/nvidia/gridd.conf\n\necho \"Test if nvidia-smi is working\"\nset -e\nnvidia-smi\nset +e\n\necho \"################### INSTALL VirtualGL / VNC\"\nyum groupinstall -y \"X Window system\"\nyum groupinstall -y xfce\nyum install -y https://netix.dl.sourceforge.net/project/turbovnc/2.2.5/turbovnc-2.2.5.x86_64.rpm\nyum install -y https://cbs.centos.org/kojifiles/packages/python-websockify/0.8.0/13.el7/noarch/python2-websockify-0.8.0-13.el7.noarch.rpm\n\nwget --no-check-certificate \"https://virtualgl.com/pmwiki/uploads/Downloads/VirtualGL.repo\" -O /etc/yum.repos.d/VirtualGL.repo\n\nyum install -y VirtualGL turbojpeg xorg-x11-apps\nset -e\n/usr/bin/vglserver_config -config +s +f -t\nset +e\n\nsystemctl disable firstboot-graphical\nsystemctl set-default graphical.target\nsystemctl isolate graphical.target\n\ncat <<EOF >/etc/rc.d/rc3.d/busidupdate.sh\n#!/bin/bash\nnvidia-xconfig --enable-all-gpus --allow-empty-initial-configuration -c /etc/X11/xorg.conf --virtual=1920x1200 -s\n# https://virtualgl.org/Documentation/HeadlessNV\nsed -i '/BusID/a\\    Option         \"HardDPMS\" \"false\"' /etc/X11/xorg.conf\nEOF\nchmod +x /etc/rc.d/rc3.d/busidupdate.sh\n/etc/rc.d/rc3.d/busidupdate.sh\n\n# Create a vglrun alias\ncat <<EOF >/etc/profile.d/vglrun.sh \n#!/bin/bash\n# Set the vglrun alias to pickup a GPU device based on the noVNC port so that each session is landing on a different GPU, modulo the number of GPU devices.\nngpu=\\$(lspci | grep NVIDIA | wc -l)\nalias vglrun='/usr/bin/vglrun -d :0.\\$(( \\${port:-0} % \\${ngpu:-1}))'\nEOF\n\n# browser and codecs\nyum -y localinstall --nogpgcheck https://download1.rpmfusion.org/free/el/rpmfusion-free-release-7.noarch.rpm\nyum -y install firefox ffmpeg ffmpeg-devel\n\n# Install archive manager\nyum -y install xarchiver\nrm -f /usr/libexec/thunar-archive-plugin/gnome-file-roller.tap\nln -s /usr/libexec/thunar-archive-plugin/xarchiver.tap /usr/libexec/thunar-archive-plugin/gnome-file-roller.tap\nupdate-desktop-database /usr/share/applications\n\n# increase buffer size\ncat << EOF >>/etc/sysctl.conf\nnet.core.rmem_max=2097152\nnet.core.wmem_max=2097152\nEOF\n", "num_lines": 107}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Update packages\nyum update -y --exclude kernel*, kmod*\n\nyum install -y sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python\nyum install -y nfs-utils openssl-devel epel-release ca-certificates nc\nyum install -y patch gcc gcc-c++ perl-Data-Dumper perl-Thread-Queue Lmod hwloc numactl jq htop python3 libXt\n\n# Disable requiretty to allow run sudo within scripts\nsed -i -e 's/Defaults    requiretty.*/ #Defaults    requiretty/g' /etc/sudoers\n\n# disable selinux\nsetenforce 0\nsed -i 's/SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config\n\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Install azcopy\ncd /usr/local/bin\nwget -q https://aka.ms/downloadazcopy-v10-linux -O - | tar zxf - --strip-components 1 --wildcards '*/azcopy'\nchmod 755 /usr/local/bin/azcopy\n", "num_lines": 29}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex\n\nDISTRIB_CODENAME=el7\nLUSTRE_VERSION=2.15.1_24_gbaa21ca\nREPO_PATH=/etc/yum.repos.d/amlfs.repo\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\necho -e \"[amlfs]\" > ${REPO_PATH}\necho -e \"name=Azure Lustre Packages\" >> ${REPO_PATH}\necho -e \"baseurl=https://packages.microsoft.com/yumrepos/amlfs-${DISTRIB_CODENAME}\" >> ${REPO_PATH}\necho -e \"enabled=1\" >> ${REPO_PATH}\necho -e \"gpgcheck=1\" >> ${REPO_PATH}\necho -e \"gpgkey=https://packages.microsoft.com/keys/microsoft.asc\" >> ${REPO_PATH}\n\nyum install -y amlfs-lustre-client-${LUSTRE_VERSION}-$(uname -r | sed -e \"s/\\.$(uname -p)$//\" | sed -re 's/[-_]/\\./g')-1\n", "num_lines": 19}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwget https://github.com/PBSPro/pbspro/releases/download/v19.1.1/pbspro_19.1.1.centos7.zip\nunzip -o pbspro_19.1.1.centos7.zip\nyum install epel-release -y\nyum install -y pbspro_19.1.1.centos7/pbspro-execution-19.1.1-0.x86_64.rpm jq\nrm -rf pbspro_19.1.1.centos7.zip\nrm -rf pbspro_19.1.1.centos7\n\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Based on: https://github.com/Azure/cyclecloud-slurm/blob/master/specs/default/cluster-init/files/00-build-slurm.sh\nset -e\n\nINSTALL_SLURM=no\n\nSLURM_VERSION=20.11.9\nBUILD_DIR=/mnt/slurm\nmkdir -p $BUILD_DIR\n\n#\n# Build PMIx\n#\nyum -y install autoconf flex libevent-devel git libxml2\n\ncd $BUILD_DIR\nmkdir -p /opt/pmix/v3\nmkdir -p pmix/build/v3 pmix/install/v3\n\n# Need to update hwloc on Centos7\ncd pmix\nwget https://download.open-mpi.org/release/hwloc/v2.7/hwloc-2.7.1.tar.bz2\ntar xf hwloc-2.7.1.tar.bz2\ncd hwloc-2.7.1\n./configure --prefix=/opt/pmix/v3\nmake -j\nsudo make install\ncd ..\n\ngit clone https://github.com/openpmix/openpmix.git source\ncd source/\ngit branch -a\ngit checkout v3.1\ngit pull\n./autogen.sh\ncd ../build/v3/\n../../source/configure --prefix=/opt/pmix/v3\nmake -j install >/dev/null\ncd ../../install/v3/\n\nif [ \"$INSTALL_SLURM\" = \"yes\" ]; then\n\n    #\n    # Build SLURM\n    #\n\n    SLURM_FOLDER=\"slurm-${SLURM_VERSION}\"\n    SLURM_PKG=\"slurm-${SLURM_VERSION}.tar.bz2\"\n    DOWNLOAD_URL=\"https://download.schedmd.com/slurm\"\n\n    cd $BUILD_DIR\n\n    # munge is in EPEL\n    yum -y install epel-release && yum -q makecache\n\n    if [ \"$SLURM_VERSION\" \\> \"20\" ]; then\n        PYTHON=python3\n    else\n        PYTHON=python2\n    fi\n\n    yum install -y make $PYTHON which rpm-build munge-devel munge-libs readline-devel openssl openssl-devel pam-devel perl-ExtUtils-MakeMaker gcc mysql mysql-devel wget gtk2-devel.x86_64 glib2-devel.x86_64 libtool-2.4.2 m4 automake rsync\n    mkdir -p $BUILD_DIR/bin\n\n    ln -s `which $PYTHON` $BUILD_DIR/bin/python\n    export PATH=$PATH:$BUILD_DIR/bin\n    wget \"${DOWNLOAD_URL}/${SLURM_PKG}\"\n    rpmbuild --define \"_with_pmix --with-pmix=/opt/pmix/v3\" -ta ${SLURM_PKG}\n\n    #\n    # Install SLURM\n    #\n\n    yum -y install /root/rpmbuild/RPMS/x86_64/slurm-${SLURM_VERSION}*.rpm /root/rpmbuild/RPMS/x86_64/slurm-slurmd-${SLURM_VERSION}*.rpm\n\n    #\n    # The below is needed to CycleCloud chef recipe\n    #\n    systemctl stop munge\n    userdel munge\n    mkdir -p /etc/slurm\n\nfi\n\n#\n# Install Enroot\n#\n\narch=$(uname -m)\nyum install -y https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot-3.4.1-1.el8.${arch}.rpm\nyum install -y https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot+caps-3.4.1-1.el8.${arch}.rpm\n\n# # Install NVIDIA container support\n# DIST=$(. /etc/os-release; echo $ID$VERSION_ID)\n# curl -s -L https://nvidia.github.io/libnvidia-container/$DIST/libnvidia-container.repo > /etc/yum.repos.d/libnvidia-container.repo\n\n# yum -y makecache\n# yum -y install libnvidia-container-tools\n\n# Add kernel boot parameters\ngrep user.max_user_namespaces /etc/sysctl.conf || echo 'user.max_user_namespaces = 1417997' >> /etc/sysctl.conf\ngrep namespace.unpriv_enable /etc/default/grub || sed -i.bak 's/\\(GRUB_CMDLINE_LINUX.*\\)\"$/\\1 namespace.unpriv_enable=1 user_namespace.enable=1 vsyscall=emulate\"/' /etc/default/grub\n[ -e /boot/grub2/grub.cfg ] && grub2-mkconfig -o /boot/grub2/grub.cfg\n[ -e /boot/efi/EFI/centos/grub.cfg ] && grub2-mkconfig -o /boot/efi/EFI/centos/grub.cfg\n\nenroot version\n", "num_lines": 107}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -e /etc/yum.repos.d/influxdb.repo ]; then\necho \"#### Configuration repo for InfluxDB:\"\ncat <<EOF | tee /etc/yum.repos.d/influxdb.repo\n[influxdb]\nname = InfluxDB Repository - RHEL \\$releasever\nbaseurl = https://repos.influxdata.com/centos/\\$releasever/\\$basearch/stable\nenabled = 1\ngpgcheck = 1\ngpgkey = https://repos.influxdata.com/influxdata-archive_compat.key\nEOF\nfi\n\necho \"#### Telegraf Installation:\"\nyum -y install telegraf\n", "num_lines": 17}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for base image", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for compute nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for desktop nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \" ********************************************************************************** \"\necho \" *                                                                                * \"\necho \" *     INFINIBAND CONFIGURAION                                                    * \"\necho \" *                                                                                * \"\necho \" ********************************************************************************** \"\nset -ex\n\n# Fix IB module issue\necho \"Configuring openibd...\"\nsed -i 's/FORCE_MODE.*$/FORCE_MODE=yes/' /etc/infiniband/openib.conf\n\n#\n# install rdma_rename with NAME_FIXED option\n# based on: https://github.com/Azure/azhpc-images/blob/master/common/install_azure_persistent_rdma_naming.sh\n#\n\necho \"Installing rdma_rename service...\"\napt-get install -y git cmake gcc ninja-build make libnl-3-dev libnl-3-200\n\npushd /tmp\nrdma_core_branch=stable-v34\ngit clone -b $rdma_core_branch https://github.com/linux-rdma/rdma-core.git\npushd rdma-core\nbash build.sh\ncp build/bin/rdma_rename /usr/sbin/rdma_rename_$rdma_core_branch\npopd\nrm -rf rdma-core\npopd\n\n#\n# setup systemd service\n#\n\ncat <<EOF >/usr/sbin/azure_persistent_rdma_naming.sh\n#!/bin/bash\n\nrdma_rename=/usr/sbin/rdma_rename_${rdma_core_branch}\n\nan_index=0\nib_index=0\n\nfor old_device in \\$(ibdev2netdev -v | sort -n | cut -f2 -d' '); do\n\n\tlink_layer=\\$(ibv_devinfo -d \\$old_device | sed -n 's/^[\\ \\t]*link_layer:[\\ \\t]*\\([a-zA-Z]*\\)\\$/\\1/p')\n\t\n\tif [ \"\\$link_layer\" = \"InfiniBand\" ]; then\n\t\t\n\t\t\\$rdma_rename \\$old_device NAME_FIXED mlx5_ib\\${ib_index}\n\t\tib_index=\\$((\\$ib_index + 1))\n\t\t\n\telif [ \"\\$link_layer\" = \"Ethernet\" ]; then\n\t\n\t\t\\$rdma_rename \\$old_device NAME_FIXED mlx5_an\\${an_index}\n\t\tan_index=\\$((\\$an_index + 1))\n\t\t\n\telse\n\t\n\t\techo \"Unknown device type for \\$old_device - \\$device_type.\"\n\t\t\n\tfi\n\t\ndone\nEOF\nchmod 755 /usr/sbin/azure_persistent_rdma_naming.sh\n\ncat <<EOF >/etc/systemd/system/azure_persistent_rdma_naming.service\n[Unit]\nDescription=Azure persistent RDMA naming\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart=/usr/sbin/azure_persistent_rdma_naming.sh\nRemainAfterExit=true\nStandardOutput=journal\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable azure_persistent_rdma_naming.service\nsystemctl start azure_persistent_rdma_naming.service\n", "num_lines": 84}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \" ********************************************************************************** \"\necho \" *                                                                                * \"\necho \" *     LINUX SETUP                                                                * \"\necho \" *                                                                                * \"\necho \" ********************************************************************************** \"\npackages=\"nfs-common sssd libsss-simpleifp0 sssd-dbus sssd-tools realmd oddjob oddjob-mkhomedir adcli samba-common krb5-user ldap-utils packagekit resolvconf jq chrony netcat\"\n\napt-get clean -y\napt-get autoremove -y\napt -y update\n# this export is needed to stop input for krb5-user\nexport DEBIAN_FRONTEND=noninteractive\napt-get install -y $packages\n\n# Disable requiretty to allow run sudo within scripts\nsed -i -e 's/Defaults    requiretty.*/ #Defaults    requiretty/g' /etc/sudoers\n\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Install azcopy\ncd /usr/local/bin\nwget -q https://aka.ms/downloadazcopy-v10-linux -O - | tar zxf - --strip-components 1 --wildcards '*/azcopy'\nchmod 755 /usr/local/bin/azcopy\n\n# Create a symlink for the Modules to allow compatibility with the HPC CentOS image which have Modules in capital case\nif [ ! -d /usr/share/Modules/modulefiles ]; then\n    ln -s /usr/share/modules /usr/share/Modules\nfi\n\n# Add I_MPI_HYDRA_BOOTSTRAP=ssh in the IMPI module otherwise it will break how PBS launch jobs\nif ! grep I_MPI_HYDRA_BOOTSTRAP /usr/share/modules/modulefiles/mpi/impi-2021 ; then\n    echo \"setenv I_MPI_HYDRA_BOOTSTRAP ssh\" >> /usr/share/modules/modulefiles/mpi/impi-2021\nfi\n", "num_lines": 42}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nLUSTRE_VERSION=2.15.1-24-gbaa21ca\n\nsource /etc/lsb-release\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/amlfs-${DISTRIB_CODENAME}/ ${DISTRIB_CODENAME} main\" | tee /etc/apt/sources.list.d/amlfs.list\ncurl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | tee /etc/apt/trusted.gpg.d/microsoft.gpg\n\napt-get update\napt-get install -y amlfs-lustre-client-${LUSTRE_VERSION}=$(uname -r)\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \" ********************************************************************************** \"\necho \" *                                                                                * \"\necho \" *     PBS PRO                                                                    * \"\necho \" *                                                                                * \"\necho \" ********************************************************************************** \"\n\ncd /mnt\n\napt-get install -y gcc make libtool libhwloc-dev libx11-dev libxt-dev libedit-dev libical-dev ncurses-dev perl postgresql-server-dev-all postgresql-contrib python-dev tcl-dev tk-dev swig libexpat-dev libssl-dev libxext-dev libxft-dev autoconf automake\n\nwget -q https://github.com/openpbs/openpbs/releases/download/v19.1.1/pbspro-19.1.1.tar.gz -O pbspro-19.1.1.tar.gz\ntar -xzf pbspro-19.1.1.tar.gz\n\nif [ \"$(dpkg -s libhwloc-dev| grep Version| sed 's/^[^0-9]*\\([0-9]\\).*$/\\1/')\" != \"1\" ]; then\n    git clone https://github.com/open-mpi/hwloc.git -b v1.11\n    cd hwloc\n    ./autogen.sh\n    ./configure --enable-static --enable-embedded-mode\n    make\n    cd ..\n\n    cd pbspro-19.1.1/\n    ./autogen.sh\n    ./configure --prefix=/opt/pbs PYTHON=/usr/bin/python2.7 CFLAGS=\"-I$PWD/../hwloc/include\" LDFLAGS=\"-L$PWD/../src\"\n    make\n    make install\nelse\n    cd pbspro-19.1.1/\n    ./autogen.sh\n    ./configure --prefix=/opt/pbs PYTHON=/usr/bin/python2.7\n    make\n    make install\nfi\n\n/opt/pbs/libexec/pbs_postinstall execution\nchmod 4755 /opt/pbs/sbin/pbs_iff /opt/pbs/sbin/pbs_rcp\n", "num_lines": 38}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Based on: https://github.com/Azure/cyclecloud-slurm/blob/master/specs/default/cluster-init/files/00-build-slurm.sh\nset -e\n\nINSTALL_SLURM=no\n\nBUILD_DIR=/mnt/slurm\nmkdir -p $BUILD_DIR\n\n#\n# Build PMIx\n#\napt-get update\napt-get install -y git libevent-dev libhwloc-dev autoconf flex make gcc libxml2\n\ncd $BUILD_DIR\nmkdir -p /opt/pmix/v3\nmkdir -p pmix/build/v3\n\ncd pmix\ngit clone https://github.com/openpmix/openpmix.git source\ncd source/\ngit branch -a\ngit checkout v3.1\ngit pull\n./autogen.sh\ncd ../build/v3/\n../../source/configure --prefix=/opt/pmix/v3\nmake -j install\n\nif [ \"$INSTALL_SLURM\" = \"yes\" ]; then\n\n    #\n    # Build SLURM\n    #\n\n    SLURM_VERSION=20.11.9\n    SLURM_FOLDER=\"slurm-${SLURM_VERSION}\"\n    SLURM_PKG=\"slurm-${SLURM_VERSION}.tar.bz2\"\n    DOWNLOAD_URL=\"https://download.schedmd.com/slurm\"\n\n    cd $BUILD_DIR\n\n    apt-get install -y munge libmunge-dev libmysqlclient-dev libpam0g-dev\n    # yum install -y rpm-build munge-devel munge-libs readline-devel openssl openssl-devel pam-devel perl-ExtUtils-MakeMaker gcc mysql mysql-devel wget gtk2-devel.x86_64 glib2-devel.x86_64 libtool-2.4.2 m4 automake rsync\n\n    wget \"${DOWNLOAD_URL}/${SLURM_PKG}\"\n    tar xf ${SLURM_PKG}\n    cd $SLURM_FOLDER\n    # ./configure --prefix=/usr --with-pmix=/opt/pmix/v3 --sysconfdir=/etc/slurm --libdir=/usr/lib64\n    ./configure --program-prefix= --prefix=/usr --exec-prefix=/usr --bindir=/usr/bin --sbindir=/usr/sbin --sysconfdir=/etc/slurm --datadir=/usr/share --includedir=/usr/include --libdir=/usr/lib64 --libexecdir=/usr/libexec --localstatedir=/var --sharedstatedir=/var/lib --mandir=/usr/share/man --infodir=/usr/share/info --with-pmix=/opt/pmix/v3\n    make -j install\n\n    # Create slurmd service\n    cp etc/slurmd.service /usr/lib/systemd/system/\n\n    #\n    # The below is needed to CycleCloud chef recipe to work correctly\n    #\n\n    systemctl stop munge\n    userdel munge\n    rm -f /var/log/munge/munged.log\n    mkdir -p /etc/slurm\n\nfi\n\n#\n# Install Enroot\n#\n\n# Debian-based distributions\narch=$(dpkg --print-architecture)\ncurl -fSsL -O https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot_3.4.1-1_${arch}.deb\ncurl -fSsL -O https://github.com/NVIDIA/enroot/releases/download/v3.4.1/enroot+caps_3.4.1-1_${arch}.deb # optional\napt install -y ./*.deb\n\n# # Install NVIDIA container support\n# distribution=$(. /etc/os-release;echo $ID$VERSION_ID) \\\n#          && curl -fsSL https://nvidia.github.io/libnvidia-container/gpgkey | sudo gpg --dearmor -o /usr/share/keyrings/nvidia-container-toolkit-keyring.gpg \\\n#          && curl -s -L https://nvidia.github.io/libnvidia-container/$distribution/libnvidia-container.list | \\\n#                sed 's#deb https://#deb [signed-by=/usr/share/keyrings/nvidia-container-toolkit-keyring.gpg] https://#g' | \\\n#                sudo tee /etc/apt/sources.list.d/nvidia-container-toolkit.list\n# apt-get update\n# sudo apt install -y curl gawk jq squashfs-tools parallel\n# sudo apt install -y libnvidia-container-tools pigz squashfuse # optional\n\nenroot version\n", "num_lines": 89}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \" ********************************************************************************** \"\necho \" *                                                                                * \"\necho \" *     TELEGRAF                                                                   * \"\necho \" *                                                                                * \"\necho \" ********************************************************************************** \"\n\n# Install Telegraf\nwget -qO- https://repos.influxdata.com/influxdata-archive_compat.key | tee /etc/apt/trusted.gpg.d/influxdb.asc >/dev/null\nsource /etc/os-release\necho \"deb https://repos.influxdata.com/${ID} ${VERSION_CODENAME} stable\" | tee /etc/apt/sources.list.d/influxdb.list\napt-get update\napt-get install -y telegraf\n", "num_lines": 14}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for compute nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This file is a placeholder to add all your customizations for desktop nodes", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nREX=\"([^@]+)%40domain.com\" # To extract user from user%40domain.com\n#REX=\"([^@]+)%40\\w+.com\" # To extract user from any .com domains\n#REX=\"(^\\w+)\" # To extract firstname from firstname.lastname@domain.com\nINPUT_USER=\"$1\"\n\nif [[ $INPUT_USER =~ $REX ]]; then\n  MATCH=\"${BASH_REMATCH[1]}\"\n  echo \"${MATCH:0:20}\" | tr '[:upper:]' '[:lower:]'\nelse\n  # can't write to standard out or error, so let's use syslog\n  logger -t 'ood-mapping' \"cannot map $INPUT_USER\"\n\n  # and exit 1\n  exit 1\nfi\n", "num_lines": 17}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Initialize the user environment the first time it logs in\nwhile (( \"$#\" )); do\n  case \"${1}\" in\n    --user)\n      OOD_USER=${2}\n      shift 2\n  esac\ndone\n\nsu - $OOD_USER\n", "num_lines": 12}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#PBS -N drivaer\n#PBS -l select=2:ncpus=64:mpiprocs=64:slot_type=hb120v3,place=scatter:excl\n#PBS -k oed\n#PBS -j oe\n#PBS -l walltime=300\n\nnp=$(wc -l <$PBS_NODEFILE)\nn=2 # TODO : Get this from PBS\nppn=64 # TODO : Get this from PBS\n\n# setup openfoam environment (from eessi)\nsource /cvmfs/pilot.eessi-hpc.org/versions/2021.12/init/bash\nml OpenFOAM/9-foss-2021a\nsource $FOAM_BASH\n\n# select the tutorial to run (and give any args required for allrun)\ntutorial_path=incompressible/simpleFoam/drivaerFastback\nallrun_args=\"-c $np -m M\"\n\n# the location to run the copy of the tutorial\nlocal_path=$HOME/openfoam_tutorial_runs\nmkdir -p $local_path\n\n# create the case name - add size and date\ncasedir=$local_path/$(basename $tutorial_path)_${n}x${ppn}_$(date +%Y%m%d_%H%M%S)\n\ncp -r $FOAM_TUTORIALS/$tutorial_path $casedir\n\npushd $casedir\n# allow flags to be added to the mpirun command through FOAM_MPIRUN_FLAGS environment variable\nsed -i '/RunFunctions/a source <(declare -f runParallel | sed \"s/mpirun/mpirun \\\\\\$FOAM_MPIRUN_FLAGS/g\")' Allrun\n# change the script to bash (as we are using bash features not necessarily available for just a sh session)\nsed -i 's#/bin/sh#/bin/bash#g' Allrun\n\nranks_per_numa=30\nexport FOAM_MPIRUN_FLAGS=\"-mca pml ucx -hostfile $PBS_NODEFILE $(env |grep 'WM_\\|FOAM_' | cut -d'=' -f1 | sed 's/^/-x /g' | tr '\\n' ' ') -x MPI_BUFFER_SIZE -x UCX_POSIX_USE_PROC_LINK=n -x PATH -x LD_LIBRARY_PATH --map-by ppr:${ranks_per_numa}:numa\"\n\n# Decompress the geometry\ngunzip constant/geometry/*\nmv constant/geometry constant/triSurface\n# Reconstruct the single partition after the solver has run\nsed -i 's/# runApplication reconstructPar/runApplication reconstructPar/g' Allrun\n\n./Allrun $allrun_args\n\n# Create a file to load the model in Paraview\ntouch case.foam\n", "num_lines": 49}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#PBS -N PingPong\n#PBS -l select=2:ncpus=1:mpiprocs=1:slot_type=hb120v3\n#PBS -k oed\n#PBS -j oe\n#PBS -l walltime=300\n\nsource /etc/profile.d/modules.sh\nmodule use /usr/share/Modules/modulefiles\n\nmodule load mpi/impi-2021\n\n#export I_MPI_FABRICS=\"shm:ofi\"\nexport I_MPI_DEBUG=5\n#export FI_PROVIDER=mlx\nexport I_MPI_HYDRA_BOOTSTRAP=ssh\n\nIMB_ROOT=$I_MPI_ROOT/bin\n\nCORES=`cat $PBS_NODEFILE | wc -l`\necho \"Running on $CORES cores\"\nmpirun -hostfile $PBS_NODEFILE -np $CORES -ppn 1 $IMB_ROOT/IMB-MPI1 PingPong", "num_lines": 22}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#PBS -N RingPingPong\n#PBS -l select=4:ncpus=1:mpiprocs=1:slot_type=hb120v3\n#PBS -k oed\n#PBS -j oe\n#PBS -l walltime=300\n\nTYPE=latency\n\nJOBID=$PBS_JOBID\n\nif [ $TYPE == \"latency\" ]; then\n   MSGLOG=\"9:10\"\nelif [ $TYPE == \"bandwidth\" ]; then\n   MSGLOG=\"22:24\"\nelse\n   echo \"Error: Do not recognize MSGLOG option: $MSGLOG\"\n   exit 1\nfi\n\nsource /etc/profile.d/modules.sh\nmodule use /usr/share/Modules/modulefiles\n\nmodule load mpi/impi-2021\n\n#export I_MPI_FABRICS=\"shm:ofi\"\nexport I_MPI_DEBUG=5\n#export FI_PROVIDER=mlx\nexport I_MPI_HYDRA_BOOTSTRAP=ssh\n\nIMB_ROOT=$I_MPI_ROOT/bin\n\nmpi_options=\"-np 2 -ppn 1\"\nhost_option=\"-hosts\"\n\n\n# affinity\nnumactl_options=\" numactl --cpunodebind 0\"\n\nhostlist=$(pwd)/hosts.$JOBID\nsort -u $PBS_NODEFILE > $hostlist\n# remove .internal.cloudapp.net from node names added by PBS in the PBS_NODEFILE\nsed -i 's/.internal.cloudapp.net//g' $hostlist\n\nsrc=$(tail -n 1 $hostlist)\n# -msglog 9:10 is for 512 and 1024 bytes message size only\nfor dst in $(<$hostlist); do\n    mpirun $host_option $src,$dst \\\n        $mpi_options $numactl_options \\\n        $IMB_ROOT/IMB-MPI1 PingPong -msglog $MSGLOG > ${src}_to_${dst}_ringpingpong.$JOBID.log\n    src=$dst\ndone\n\n# clean up\nrm $hostlist\n\nif [ $TYPE == \"latency\" ]; then\necho \"Ring Ping Pong Results (1024 bytes)\"\nprintf \"%-20s %-20s %10s\\n\" \"Source\" \"Destination\" \"Time [usec]\"\ngrep \"^         1024 \" *_ringpingpong.$JOBID.log \\\n    | tr -s ' ' | cut -d ' ' -f 1,4 \\\n    | sed 's/_to_/ /g;s/_ringpingpong[^:]*://g' \\\n    | sort -nk 3 \\\n    | xargs printf \"%-20s %-20s %10s\\n\" | tee output.log\nelse\necho \"Ring Ping Pong Bandwidth Results (16777216 bytes)\"\nprintf \"%-20s %-20s %10s\\n\" \"Source\" \"Destination\" \"Mbytes/sec\"\ngrep \"^ *16777216 \" *_ringpingpong.$JOBID.log \\\n    | tr -s ' ' | cut -d ' ' -f 1,5 \\\n    | sed 's/_to_/ /g;s/_ringpingpong[^:]*://g' \\\n    | sort -nk 3 \\\n    | xargs printf \"%-20s %-20s %10s\\n\" | tee bandwidth_output.log\nfi\n", "num_lines": 74}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH --job-name drivaer\n#SBATCH --partition=hb120v3\n#SBATCH --nodes=2\n#SBATCH --ntasks-per-node=64\n\nnp=$SLURM_NTASKS\nn=$SLURM_NNODES\nppn=$SLURM_CPUS_ON_NODE\n\n# setup openfoam environment (from eessi)\nsource /cvmfs/pilot.eessi-hpc.org/versions/2021.12/init/bash\nml OpenFOAM/9-foss-2021a\nsource $FOAM_BASH\n\n# select the tutorial to run (and give any args required for allrun)\ntutorial_path=incompressible/simpleFoam/drivaerFastback\nallrun_args=\"-c $np -m M\"\n\n# the location to run the copy of the tutorial\nlocal_path=$HOME/openfoam_tutorial_runs\nmkdir -p $local_path\n\n# create the case name - add size and date\ncasedir=$local_path/$(basename $tutorial_path)_${n}x${ppn}_$(date +%Y%m%d_%H%M%S)\n\ncp -r $FOAM_TUTORIALS/$tutorial_path $casedir\n\npushd $casedir\n# allow flags to be added to the mpirun command through FOAM_MPIRUN_FLAGS environment variable\nsed -i '/RunFunctions/a source <(declare -f runParallel | sed \"s/mpirun/SLURM_EXPORT_ENV=ALL mpirun \\\\\\$FOAM_MPIRUN_FLAGS/g\")' Allrun\n# change the script to bash (as we are using bash features not necessarily available for just a sh session)\nsed -i 's#/bin/sh#/bin/bash#g' Allrun\n\nexport FOAM_MPIRUN_FLAGS=\"-mca pml ucx $(env |grep 'WM_\\|FOAM_' | cut -d'=' -f1 | sed 's/^/-x /g' | tr '\\n' ' ') -x MPI_BUFFER_SIZE -x UCX_IB_MLX5_DEVX=n -x UCX_POSIX_USE_PROC_LINK=n -x PATH -x LD_LIBRARY_PATH\"\n\n# Decompress the geometry\ngunzip constant/geometry/*\nmv constant/geometry constant/triSurface\n# Reconstruct the single partition after the solver has run\nsed -i 's/# runApplication reconstructPar/runApplication reconstructPar/g' Allrun\n\n./Allrun $allrun_args\n\n# Create a file to load the model in Paraview\ntouch case.foam\n", "num_lines": 47}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH -J PingPong\n#SBATCH -N 2\n#SBATCH --ntasks-per-node=1\n#SBATCH -p hc44rs\n#SBATCH -t 5\n#SBATCH --export=NONE\n\nsource /etc/profile.d/modules.sh\nmodule use /usr/share/Modules/modulefiles\n\nmodule load mpi/impi-2021\n\necho \"Running on $SLURM_NNODES nodes\"\nmpirun -ppn 1 IMB-MPI1 PingPong\n", "num_lines": 16}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#SBATCH -J RingPingPong\n#SBATCH -N 4\n#SBATCH --ntasks-per-node=1\n#SBATCH -p hc44rs\n#SBATCH -t 5\n#SBATCH --export=NONE\n\nTYPE=latency\n\nJOBID=$SLURM_JOBID\n\nif [ $TYPE == \"latency\" ]; then\n   MSGLOG=\"9:10\"\nelif [ $TYPE == \"bandwidth\" ]; then\n   MSGLOG=\"22:24\"\nelse\n   echo \"Error: Do not recognize MSGLOG option: $MSGLOG\"\n   exit 1\nfi\n\nsource /etc/profile.d/modules.sh\nmodule use /usr/share/Modules/modulefiles\n\nmodule load mpi/impi-2021\n\n#export I_MPI_FABRICS=\"shm:ofi\"\nexport I_MPI_DEBUG=5\n#export FI_PROVIDER=mlx\n\nIMB_ROOT=$I_MPI_ROOT/bin\n\nmpi_options=\"-np 2 -ppn 1\"\nhost_option=\"-hosts\"\n\n\n# affinity\nnumactl_options=\" numactl --cpunodebind 0\"\n\nhostlist=$(pwd)/hosts.$JOBID\nscontrol show hostnames | sort -u > $hostlist\n\nsrc=$(tail -n 1 $hostlist)\n# -msglog 9:10 is for 512 and 1024 bytes message size only\nfor dst in $(<$hostlist); do\n    mpirun $host_option $src,$dst \\\n        $mpi_options $numactl_options \\\n        $IMB_ROOT/IMB-MPI1 PingPong -msglog $MSGLOG > ${src}_to_${dst}_ringpingpong.$JOBID.log\n    src=$dst\ndone\n\n# clean up\nrm $hostlist\n\nif [ $TYPE == \"latency\" ]; then\necho \"Ring Ping Pong Results (1024 bytes)\"\nprintf \"%-20s %-20s %10s\\n\" \"Source\" \"Destination\" \"Time [usec]\"\ngrep \"^         1024 \" *_ringpingpong.$JOBID.log \\\n    | tr -s ' ' | cut -d ' ' -f 1,4 \\\n    | sed 's/_to_/ /g;s/_ringpingpong[^:]*://g' \\\n    | sort -nk 3 \\\n    | xargs printf \"%-20s %-20s %10s\\n\" | tee output.log\nelse\necho \"Ring Ping Pong Bandwidth Results (16777216 bytes)\"\nprintf \"%-20s %-20s %10s\\n\" \"Source\" \"Destination\" \"Mbytes/sec\"\ngrep \"^ *16777216 \" *_ringpingpong.$JOBID.log \\\n    | tr -s ' ' | cut -d ' ' -f 1,5 \\\n    | sed 's/_to_/ /g;s/_ringpingpong[^:]*://g' \\\n    | sort -nk 3 \\\n    | xargs printf \"%-20s %-20s %10s\\n\" | tee bandwidth_output.log\nfi\n", "num_lines": 72}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Library of functions to be used across scripts\nread_os()\n{\n    os_release=$(cat /etc/os-release | grep \"^ID\\=\" | cut -d'=' -f 2 | xargs)\n    os_maj_ver=$(cat /etc/os-release | grep \"^VERSION_ID\\=\" | cut -d'=' -f 2 | xargs)\n    full_version=$(cat /etc/os-release | grep \"^VERSION\\=\" | cut -d'=' -f 2 | xargs)\n}\n\nis_centos()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_centos8()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ] && [ \"$os_maj_ver\" == \"8\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_centos7()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ] && [ \"$os_maj_ver\" == \"7\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_ubuntu()\n{\n    read_os\n    if [ \"$os_release\" == \"ubuntu\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\n", "num_lines": 50}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ndnf install -y https://ecsft.cern.ch/dist/cvmfs/cvmfs-release/cvmfs-release-latest.noarch.rpm\ndnf install -y cvmfs\ndnf install -y https://github.com/EESSI/filesystem-layer/releases/download/latest/cvmfs-config-eessi-latest.noarch.rpm\n\n# configure CernVM-FS (no proxy, 10GB quota for CernVM-FS cache)\nbash -c \"echo 'CVMFS_HTTP_PROXY=DIRECT' > /etc/cvmfs/default.local\"\nbash -c \"echo 'CVMFS_QUOTA_LIMIT=10000' >> /etc/cvmfs/default.local\"\ncvmfs_config setup\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nyum install -y apptainer\n", "num_lines": 4}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Empty on purpose\n", "num_lines": 3}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npackages=\"sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python-utils\"\n\nif ! rpm -q $packages; then\n  echo \"Installing packages $packages\" \n  dnf install -y $packages\n  echo \"Restart dbus systemd-logind\"\n  systemctl restart dbus\n  systemctl restart systemd-logind\nfi\n\necho \"Update nameserver\"\n# https://docs.microsoft.com/en-us/azure/virtual-machines/linux/azure-dns\nif ! grep \"RES_OPTIONS\" /etc/sysconfig/network; then\n  echo \"RES_OPTIONS=\\\"timeout:1 attempts:5\\\"\" >> /etc/sysconfig/network\nfi\n\n# By default, Samba on RHEL 8.3 no longer supports the deprecated RC4 cipher suite \nupdate-crypto-policies --set DEFAULT:AD-SUPPORT\n\n# Stop NetworkManager overwriting /etc/resolv.conf\ncat > /etc/NetworkManager/conf.d/90-dns-none.conf << EOF\n[main]\ndns=none\nEOF\n\n\nfunction enforce_hostname() {\n  local system_hostname=$1\n  local target_hostname=$2\n\n  # ensure the correct hostname (update if necessary)\n  echo \"ensure the correct hostname (update if necessary)\"\n\n  if [ \"$system_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect hostname ($system_hostname), it should be $target_hostname, updating\"\n    hostname $target_hostname\n  fi\n  if grep -i $system_hostname /etc/hosts; then\n    logger -s \"Warning: incorrect hostname ($system_hostname) in /etc/hosts, updating\"\n    sed -i \"s/$system_hostname/$target_hostname/ig\" /etc/hosts\n  fi\n  etc_hostname=$(</etc/hostname)\n  if [ \"$etc_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect /etc/hostname ($etc_hostname), it should be $target_hostname, updating\"\n    echo $target_hostname > /etc/hostname\n  fi\n  eth0_hostname=$(grep DHCP_HOSTNAME /etc/sysconfig/network-scripts/ifcfg-eth0 | cut -d'=' -f2)\n  if [ \"$eth0_hostname\" != \"\" -a \"$eth0_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect DHCP_HOSTNAME in /etc/sysconfig/network-scripts/ifcfg-eth0 ($etc_hostname), it should be $target_hostname, updating\"\n    sed -i \"s/^DHCP_HOSTNAME=.*\\$/DHCP_HOSTNAME=$target_hostname/g\" /etc/sysconfig/network-scripts/ifcfg-eth0\n    systemctl restart NetworkManager\n  fi\n}\n", "num_lines": 55}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npackages=\"nfs-utils\"\n\nif ! rpm -q $packages; then\n  echo \"Installing packages $packages\"\n  dnf install -y $packages\nfi\n\nsetsebool -P use_nfs_home_dirs 1 || true\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nrpm -q lbnl-nhc || dnf install -y \"https://github.com/mej/nhc/releases/download/1.4.3/lbnl-nhc-1.4.3-1.el7.noarch.rpm\"\n", "num_lines": 3}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ ! -e /etc/yum.repos.d/influxdb.repo ]; then\necho \"#### Configuration repo for InfluxDB:\"\ncat <<EOF | tee /etc/yum.repos.d/influxdb.repo\n[influxdb]\nname = InfluxDB Repository - RHEL \\$releasever\nbaseurl = https://repos.influxdata.com/rhel/\\$releasever/\\$basearch/stable\nenabled = 1\ngpgcheck = 1\ngpgkey = https://repos.influxdata.com/influxdata-archive_compat.key\nEOF\nfi\n\nif ! rpm -q telegraf; then\n  echo \"#### Telegraf Installation:\"\n  dnf -y install telegraf jq\nfi\n", "num_lines": 18}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nyum install -y https://ecsft.cern.ch/dist/cvmfs/cvmfs-release/cvmfs-release-latest.noarch.rpm\nyum install -y cvmfs\nyum install -y https://github.com/EESSI/filesystem-layer/releases/download/latest/cvmfs-config-eessi-latest.noarch.rpm\n\n# configure CernVM-FS (no proxy, 10GB quota for CernVM-FS cache)\nbash -c \"echo 'CVMFS_HTTP_PROXY=DIRECT' > /etc/cvmfs/default.local\"\nbash -c \"echo 'CVMFS_QUOTA_LIMIT=10000' >> /etc/cvmfs/default.local\"\ncvmfs_config setup\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nyum install /usr/*bin/fuse2fs -y\nyum install https://github.com/apptainer/apptainer/releases/download/v1.1.6/apptainer-1.1.6-1.x86_64.rpm -y\n", "num_lines": 4}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Empty on purpose\n", "num_lines": 3}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npackages=\"sssd realmd oddjob oddjob-mkhomedir adcli samba-common samba-common-tools krb5-workstation openldap-clients policycoreutils-python\"\n\nif ! rpm -q $packages; then\n  echo \"Installing packages $packages\" \n  yum install -y $packages\n  echo \"Restart dbus systemd-logind\"\n  systemctl restart dbus\n  systemctl restart systemd-logind\nfi\n\necho \"Update nameserver\"\n# https://docs.microsoft.com/en-us/azure/virtual-machines/linux/azure-dns\nif ! grep \"RES_OPTIONS\" /etc/sysconfig/network; then\n  echo \"RES_OPTIONS=\\\"timeout:1 attempts:5\\\"\" >> /etc/sysconfig/network\nfi\n\nfunction enforce_hostname() {\n  local system_hostname=$1\n  local target_hostname=$2\n\n  # ensure the correct hostname (update if necessary)\n  echo \"ensure the correct hostname (update if necessary)\"\n\n  if [ \"$system_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect hostname ($system_hostname), it should be $target_hostname, updating\"\n    hostname $target_hostname\n  fi\n  if grep -i $system_hostname /etc/hosts; then\n    logger -s \"Warning: incorrect hostname ($system_hostname) in /etc/hosts, updating\"\n    sed -i \"s/$system_hostname/$target_hostname/ig\" /etc/hosts\n  fi\n  etc_hostname=$(</etc/hostname)\n  if [ \"$etc_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect /etc/hostname ($etc_hostname), it should be $target_hostname, updating\"\n    echo $target_hostname > /etc/hostname\n  fi\n  eth0_hostname=$(grep DHCP_HOSTNAME /etc/sysconfig/network-scripts/ifcfg-eth0 | cut -d'=' -f2)\n  if [ \"$eth0_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect DHCP_HOSTNAME in /etc/sysconfig/network-scripts/ifcfg-eth0 ($etc_hostname), it should be $target_hostname, updating\"\n    sed -i \"s/^DHCP_HOSTNAME=.*\\$/DHCP_HOSTNAME=$target_hostname/g\" /etc/sysconfig/network-scripts/ifcfg-eth0\n    systemctl restart NetworkManager\n  fi\n}\n", "num_lines": 45}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npackages=\"nfs-utils\"\n\nif ! rpm -q $packages; then\n  echo \"Installing packages $packages\"\n  yum install -y $packages\nfi\n\nsetsebool -P use_nfs_home_dirs 1 || true\n", "num_lines": 10}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nrpm -q lbnl-nhc || yum install -y \"https://github.com/mej/nhc/releases/download/1.4.3/lbnl-nhc-1.4.3-1.el7.noarch.rpm\"\n", "num_lines": 3}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ ! -e /etc/yum.repos.d/influxdb.repo ]; then\necho \"#### Configuration repo for InfluxDB:\"\ncat <<EOF | tee /etc/yum.repos.d/influxdb.repo\n[influxdb]\nname = InfluxDB Repository - RHEL \\$releasever\nbaseurl = https://repos.influxdata.com/centos/\\$releasever/\\$basearch/stable\nenabled = 1\ngpgcheck = 1\ngpgkey = https://repos.influxdata.com/influxdata-archive_compat.key\nEOF\nfi\n\nif ! rpm -q telegraf; then\n  echo \"#### Telegraf Installation:\"\n  yum -y install telegraf jq\nfi\n\n", "num_lines": 19}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This code is executed when NHC detects an error\n# Parameters:\n#    1: SLURM node name\n#    2+: Error message\n# Logs following information in CC log and requests CC to terminate the node:\n#    Hostname\n#    Physical host name\n#    NHC error message\n\necho \"`date '+%Y%m%d %H:%M:%S'` $0 $*\"\n\nHOSTNAME=\"$1\"\nshift\nNOTE=\"$*\"\n\nPHYSICAL_HOST=$(strings /var/lib/hyperv/.kvp_pool_3 | grep -A1 PhysicalHostName | head -n 2 | tail -1)\nJETPACK=/opt/cycle/jetpack/bin/jetpack\n\necho \"$0:  ERROR : Node Health Checks failed on $HOSTNAME - $PHYSICAL_HOST - $NOTE\"\n$JETPACK log \"ERROR : Node Health Checks failed - $(hostname) - $PHYSICAL_HOST - $NOTE\" --level error\n/usr/libexec/nhc/node-mark-offline $HOSTNAME $NOTE\necho \"$JETPACK shutdown --unhealthy\" | at now +2 minutes\n# To keep the VM online for debugging, replace the line above with the following:\n#  $JETPACK keepalive forever\n", "num_lines": 26}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n", "num_lines": 2}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nadd-apt-repository -y ppa:apptainer/ppa\napt install -y apptainer\n", "num_lines": 5}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif ! dpkg -l chrony; then\n  apt-get install -y chrony\nfi\n", "num_lines": 5}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\npackages=\"sssd libsss-simpleifp0 sssd-dbus sssd-tools realmd oddjob oddjob-mkhomedir adcli samba-common krb5-user ldap-utils packagekit resolvconf\"\n\nif [ \"$os_maj_ver\" == \"18.04\" ]; then\n    packages=\"$packages python-sss\"\nfi\n\nif ! dpkg -l $packages ; then\n  apt -y update\n  echo \"Installing packages $packages\" \n  # this export is needed to stop input for krb5-user\n  export DEBIAN_FRONTEND=noninteractive\n  apt-get install -y $packages\n  echo \"Restart dbus\"\n  # Manually restarting dbus is blocked on ubuntu\n  # systemctl restart dbus\n  echo \"Restart systemd-logind\"\n  systemctl restart systemd-logind\nfi\n\n# https://docs.microsoft.com/en-us/azure/virtual-machines/linux/azure-dns\nif grep \"^options \" /etc/resolv.conf; then\n  sed -i 's/^options /options timeout:1 attempts:5 /' /etc/resolv.conf\nelse\n  echo \"options timeout:1 attempts:5\" >> /etc/resolv.conf\nfi\n\n# Disable rdns for libdefaults in /etc/krb5.conf\nif grep \"rdns = false\" /etc/krb5.conf; then\n  echo \"rdns already set to false\"\nelse\n  echo \"set rdns to false for libdefaults\"\n  sed -i '/\\[libdefaults\\]/a\\\\trdns = false' /etc/krb5.conf\nfi\n\n\nfunction enforce_hostname() {\n  local system_hostname=$1\n  local target_hostname=$2\n\n  # ensure the correct hostname (update if necessary)\n  echo \"ensure the correct hostname (update if necessary)\"\n\n  if [ \"$system_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect hostname ($system_hostname), it should be $target_hostname, updating\"\n    hostname $target_hostname\n  fi\n  if grep -i $system_hostname /etc/hosts; then\n    logger -s \"Warning: incorrect hostname ($system_hostname) in /etc/hosts, updating\"\n    sed -i \"s/$system_hostname/$target_hostname/ig\" /etc/hosts\n  fi\n  etc_hostname=$(</etc/hostname)\n  if [ \"$etc_hostname\" != \"$target_hostname\" ]; then\n    logger -s \"Warning: incorrect /etc/hostname ($etc_hostname), it should be $target_hostname, updating\"\n    echo $target_hostname > /etc/hostname\n  fi\n\n  if ! systemctl restart systemd-networkd; then\n    logger -s \"failed to restart systemd-networkd\"\n  fi\n}\n", "num_lines": 63}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npackages=\"nfs-common\"\n\nif ! dpkg -l $packages ; then\n  echo \"Installing packages $packages\"\n  apt-get install -y $packages\nfi\n\n", "num_lines": 9}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /root\nif [ ! -f /usr/sbin/nhc ] || [ ! -d /etc/nhc ] ; then\n    git clone https://github.com/mej/nhc.git -b 1.4.3\n    cd nhc\n    ./autogen.sh\n    ./configure --prefix=/usr --sysconfdir=/etc --libexecdir=/usr/lib\n    #make test\n    make install\nfi", "num_lines": 11}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif ! dpkg -l telegraf; then\n\n  wget -qO- https://repos.influxdata.com/influxdata-archive_compat.key | tee /etc/apt/trusted.gpg.d/influxdb.asc >/dev/null\n  source /etc/os-release\n  echo \"deb https://repos.influxdata.com/${ID} ${VERSION_CODENAME} stable\" | tee /etc/apt/sources.list.d/influxdb.list\n  apt-get update \n  apt-get install -y telegraf jq\n\nfi\n\n", "num_lines": 12}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nNVME_DISKS_NAME=`ls /dev/nvme*n1`\nNVME_DISKS=`ls -latr /dev/nvme*n1 | wc -l`\n\necho \"Number of NVMe Disks: $NVME_DISKS\"\n\nif [ \"$NVME_DISKS\" == \"0\" ]\nthen\n    exit 0\nelse\n    mkdir -p /mnt/nvme\n    # Needed incase something did not unmount as expected. This will delete any data that may be left behind\n    mdadm  --stop /dev/md*\n    mdadm --create /dev/md128 -f --run --level 0 --raid-devices $NVME_DISKS $NVME_DISKS_NAME\n    mkfs.xfs -f /dev/md128\n    mount /dev/md128 /mnt/nvme || exit 1\nfi\n\nchmod 1777 /mnt/nvme\n", "num_lines": 21}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$script_dir/../files/azhop-helpers.sh\" \nread_os\n\n$script_dir/../files/$os_release/init_telegraf.sh\n\necho \"Configuring global tags\"\nAZHPC_VMSIZE=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance/compute?api-version=2019-08-15\" | jq -r '.vmSize' | tr '[:upper:]' '[:lower:]')\nPHYSICAL_HOST=$(strings /var/lib/hyperv/.kvp_pool_3 | grep -A1 PhysicalHostName | head -n 2 | tail -1)\nVMSS=$(curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2018-10-01\" | jq -r '.compute.vmScaleSetName')\n\nsed -i \"s/__SKU__/${AZHPC_VMSIZE}/g\" ../files/telegraf.conf\nsed -i \"s/__PHYS_HOST__/${PHYSICAL_HOST}/g\" ../files/telegraf.conf\nsed -i \"s/__VMSS__/${VMSS}/g\" ../files/telegraf.conf\n\necho \"Copy configuration file to use\"\nTELEGRAF_CONF_DIR=/etc/telegraf\ncp ../files/telegraf.conf $TELEGRAF_CONF_DIR/telegraf.conf\nchown telegraf:root $TELEGRAF_CONF_DIR/telegraf.conf\nchmod 600 $TELEGRAF_CONF_DIR/telegraf.conf\n\necho \"#### Starting Telegraf services:\"\nsystemctl enable telegraf\nsystemctl restart telegraf\n", "num_lines": 26}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$script_dir/../files/azhop-helpers.sh\" \nread_os\n\n$script_dir/../files/$os_release/init_chronyd.sh\n\nif [ -e /dev/ptp_hyperv ]; then\n  PTP=\"ptp_hyperv\"\nelse\n  PTP=\"ptp0\"\nfi\n\ncat <<EOF >/etc/chrony.conf\ndriftfile /var/lib/chrony/drift\nmakestep 1.0 -1\nrtcsync\nlogdir /var/log/chrony\nrefclock PHC /dev/$PTP poll 3 dpoll -2 offset 0 stratum 2\nEOF\n\nchmod 644 /etc/chrony.conf\n\nsystemctl enable chronyd\nsystemctl restart chronyd", "num_lines": 25}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$script_dir/../files/azhop-helpers.sh\" \nread_os\n\n$script_dir/../files/$os_release/cvmfs-eessi.sh\n", "num_lines": 7}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$SCRIPT_DIR/../files/azhop-helpers.sh\" \nread_os\n\n$SCRIPT_DIR/../files/$os_release/init_nhc.sh\n\n# Install custom checks\ncp -v $SCRIPT_DIR/../files/nhc/scripts/* /etc/nhc/scripts/\n\n# Install azhop-node-offline.sh\ncp -v $SCRIPT_DIR/../files/nhc/azhop-node-offline.sh /usr/libexec/nhc/\nchmod 755 /usr/libexec/nhc/azhop-node-offline.sh\n\nNHC_CONFIG_FILE=\"/etc/nhc/nhc.conf\"\nVM_SIZE=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance/compute?api-version=2019-08-15\" | jq -r '.vmSize' | tr '[:upper:]' '[:lower:]' | sed 's/standard_//')\n\nNHC_CONFIG_EXTRA=\"$SCRIPT_DIR/../files/nhc/nhc_${VM_SIZE}.conf\"\n\n# Use common config for all compute nodes\nif [ -e $NHC_CONFIG_FILE ]; then\n    rm -f ${NHC_CONFIG_FILE}.bak\n    mv $NHC_CONFIG_FILE ${NHC_CONFIG_FILE}.bak\nfi\ncp -fv $SCRIPT_DIR/../files/nhc/nhc_common.conf $NHC_CONFIG_FILE\n\n# Append VM size specific config if exists\nif [ -e $NHC_CONFIG_EXTRA  ]; then\n    cat $NHC_CONFIG_EXTRA >> $NHC_CONFIG_FILE\nfi\n\n# Add nvidia-smi health checks for GPU SKUs except NV_v4 as they don't have NVIDIA device\ncase $VM_SIZE in\n    nv*v4)\n    ;;\n    nc*|nv*|nd*)\n        echo \" * || check_nvsmi_healthmon\" >> $NHC_CONFIG_FILE\n    ;;\n    # Check HDR InfiniBand on all HBv2 and HBv3 SKUs\n    hb*v2|hb*v3)\n        echo \" * || check_hw_ib 200 mlx5_ib0:1\" >> $NHC_CONFIG_FILE\n    ;;\n    hc44rs)\n        echo \" * || check_hw_ib 100 mlx5_ib0:1\" >> $NHC_CONFIG_FILE\n    ;;\n\nesac\n", "num_lines": 48}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$script_dir/../files/azhop-helpers.sh\"\nread_os\n\nif [ $os_maj_ver != '18.04' ]; then\n  $script_dir/../files/$os_release/init_apptainer.sh\nelse\n  exit 0\nfi\n", "num_lines": 11}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# written by Jeff Jones. Slight modifications by Matt Chan\n\necho \"Resetting /mnt/resource/tmpscratch and /tmp/scratch\"\nrm -rf /mnt/resource/tmpscratch\nrm -rf /mnt/nvme/tmpscratch\nrm -rf /tmp/scratch\nrm -rf /mnt/scratch\nif [ -d /mnt/nvme ]; then\n    chmod -R 1777 /mnt/nvme\n    mkdir /mnt/nvme/tmpscratch\n    chmod -R 1777 /mnt/nvme/tmpscratch\n#    touch /mnt/nvme/tmpscratch/PUT_YOUR_USER_SCRATCH_FOLDERS_HERE\n    ln -s /mnt/nvme/tmpscratch /tmp/scratch\n    ln -s /mnt/nvme/tmpscratch /mnt/scratch\nelif [ -d /mnt/resource ]; then\n    chmod -R 1777 /mnt/resource\n    mkdir /mnt/resource/tmpscratch\n    chmod -R 1777 /mnt/resource/tmpscratch\n#    touch /mnt/resource/tmpscratch/PUT_YOUR_USER_SCRATCH_FOLDERS_HERE\n    ln -s /mnt/resource/tmpscratch /tmp/scratch\n    ln -s /mnt/resource/tmpscratch /mnt/scratch\nelse\n    echo \"/mnt/resource nor /mnt/nvme does not exist!\"\n    exit 1\nfi\necho \"Cleanup complete.\"\n", "num_lines": 28}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nerrormessage=$( /usr/sbin/nhc 2>&1)\nerror=$?\n\n# In case of health check failure, shutdown the node by calling the script /usr/libexec/nhc/azhop-node-offline.sh\nif [ $error -eq 1 ]; then\n    /usr/libexec/nhc/azhop-node-offline.sh $(hostname) \"$errormessage\"\n    JETPACK=/opt/cycle/jetpack/bin/jetpack\n    $JETPACK shutdown --unhealthy\nfi\n", "num_lines": 12}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Placeholder to add any of your custom scripts here\n\n# If you need to write OS specific scripts then copy them in the ../files/$os_release folder and use the following lines to call it\n#script_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n#source \"$script_dir/../files/azhop-helpers.sh\" \n#read_os\n\n#$script_dir/../files/$os_release/mystuff.sh", "num_lines": 9}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Library of functions to be used across scripts\nread_os()\n{\n    os_release=$(cat /etc/os-release | grep \"^ID\\=\" | cut -d'=' -f 2 | xargs)\n    os_maj_ver=$(cat /etc/os-release | grep \"^VERSION_ID\\=\" | cut -d'=' -f 2 | xargs)\n    full_version=$(cat /etc/os-release | grep \"^VERSION\\=\" | cut -d'=' -f 2 | xargs)\n}\n\nis_centos()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_centos8()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ] && [ \"$os_maj_ver\" == \"8\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_centos7()\n{\n    read_os\n    if [ \"$os_release\" == \"centos\" ] && [ \"$os_maj_ver\" == \"7\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\nis_ubuntu()\n{\n    read_os\n    if [ \"$os_release\" == \"ubuntu\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\n", "num_lines": 50}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nBUILD_FROM_SOURCE=yes\n[ -d /opt/pbs ] && exit 0\n\nif [ \"$BUILD_FROM_SOURCE\" == \"yes\" ] ; then\n    dnf install -y gcc make rpm-build libtool hwloc-devel \\\n        libX11-devel libXt-devel libedit-devel libical-devel \\\n        ncurses-devel perl postgresql-devel postgresql-contrib python2 python2-devel tcl-devel \\\n        tk-devel swig expat-devel openssl-devel libXext libXft \\\n        autoconf automake gcc-c++ git jq\n\n    cd /mnt\n    git clone https://github.com/open-mpi/hwloc.git -b v1.11\n    cd hwloc\n    ./configure --enable-static --enable-embedded-mode\n    make\n    cd ..\n    \n    wget -q https://github.com/openpbs/openpbs/releases/download/v19.1.1/pbspro-19.1.1.tar.gz -O pbspro-19.1.1.tar.gz\n    tar -xzf pbspro-19.1.1.tar.gz\n    cd pbspro-19.1.1/\n    ./configure --prefix=/opt/pbs PYTHON=/usr/bin/python2.7 CFLAGS=\"-I$PWD/../hwloc/include\" LDFLAGS=\"-L$PWD/../src\"\n    make\n    make install\n\n    /opt/pbs/libexec/pbs_postinstall execution\n    chmod 4755 /opt/pbs/sbin/pbs_iff /opt/pbs/sbin/pbs_rcp\nelse\n    wget https://github.com/openpbs/openpbs/releases/download/v20.0.1/openpbs_20.0.1.centos_8.zip\n    unzip -o openpbs_20.0.1.centos_8.zip\n    dnf install epel-release -y\n    dnf install -y openpbs_20.0.1.centos_8/openpbs-execution-20.0.1-0.x86_64.rpm jq\n    rm -rf openpbs_20.0.1.centos_8.zip\n    rm -rf openpbs_20.0.1.centos_8\nfi\n", "num_lines": 37}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Downloading PBS RPMs\"\nwget -q https://github.com/PBSPro/pbspro/releases/download/v19.1.1/pbspro_19.1.1.centos7.zip\nunzip -o pbspro_19.1.1.centos7.zip\necho \"Installing PBS RPMs\"\nyum install -y epel-release\nyum install -y pbspro_19.1.1.centos7/pbspro-execution-19.1.1-0.x86_64.rpm jq\n", "num_lines": 8}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ncd /mnt\nwget -q https://github.com/openpbs/openpbs/releases/download/v19.1.1/pbspro-19.1.1.tar.gz -O pbspro-19.1.1.tar.gz\ntar -xzf pbspro-19.1.1.tar.gz\ncd pbspro-19.1.1/\n\napt-get install -y gcc make libtool libhwloc-dev libx11-dev libxt-dev libedit-dev libical-dev ncurses-dev perl postgresql-server-dev-all postgresql-contrib python-dev tcl-dev tk-dev swig libexpat-dev libssl-dev libxext-dev libxft-dev autoconf automake\n./autogen.sh\n./configure --prefix=/opt/pbs PYTHON=/usr/bin/python2.7\nmake\nmake install\n\n/opt/pbs/libexec/pbs_postinstall execution\nchmod 4755 /opt/pbs/sbin/pbs_iff /opt/pbs/sbin/pbs_rcp\n", "num_lines": 15}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncp ../files/autostop.rb /opt/cycle/jetpack/system/bootstrap/autostop.rb\nchmod 700 /opt/cycle/jetpack/system/bootstrap/autostop.rb\n\n#write out current crontab\ncrontab -l > tempcron\n#echo new cron into cron file\necho \"* * * * * /opt/cycle/jetpack/system/bootstrap/cron_wrapper.sh /opt/cycle/jetpack/system/bootstrap/autostop.rb >> /opt/cycle/jetpack/logs/autostop.out 1>&2\" >> tempcron\n#install new cron file\ncrontab tempcron\n\nrm tempcron\n", "num_lines": 14}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\nsource \"$script_dir/../files/azhop-helpers.sh\" \nread_os\n\nfind $script_dir/../files -name \"*.sh\" -exec chmod +x {} \\;\n\n# If PBS is not installed, then install it\nif [ ! -f \"/etc/pbs.conf\" ]; then\n    $script_dir/../files/$os_release/installpbs.sh\nfi\n\necho \"Configuring PBS\"\n\nsed -i 's/CHANGE_THIS_TO_PBS_PRO_SERVER_HOSTNAME/scheduler/' /etc/pbs.conf\nsed -i 's/CHANGE_THIS_TO_PBS_PRO_SERVER_HOSTNAME/scheduler/' /var/spool/pbs/mom_priv/config\nsed -i \"s/^if /#if /g\" /opt/pbs/lib/init.d/limits.pbs_mom\nsed -i \"s/^fi/#fi /g\" /opt/pbs/lib/init.d/limits.pbs_mom\n\nsystemctl restart pbs || exit 1\necho \"PBS Restarted\"\n", "num_lines": 22}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\necho \"Getting container...\"\necho \"TTT - $(date)\"\ncontainer_image=$1\ncontainer_name=$2\n\necho \"container_image=$container_image\"\necho \"container_name=$container_name\"\n# add the default docker:// if no prefix is provided\nif [ \"$container_image\" != *\"://\"* ]; then\n    container_image=\"docker://$container_image\"\n    echo \"container_image=$container_image\"\nfi\n\necho \"enroot import\"\n# remove any prefix :// and replace chars in (/:) by +\ncontainer_squashfs_path=${container_image#*://}\ncontainer_squashfs_path=${container_squashfs_path//\\//+}\ncontainer_squashfs_path=${container_squashfs_path//:/+}\n\n# get the enroot temp path to store squashfs files\nENROOT_TEMP_PATH=$(grep ENROOT_TEMP_PATH /etc/enroot/enroot.conf | cut -d' ' -f2)\nENROOT_TEMP_PATH=${ENROOT_TEMP_PATH:-/tmp}\necho \"ENROOT_TEMP_PATH=$ENROOT_TEMP_PATH\"\ncontainer_squashfs_path=\"$ENROOT_TEMP_PATH/$container_squashfs_path.sqsh\"\necho \"container_squashfs_path=$container_squashfs_path\"\n\n# import the container and save the sqsh file in the enroot temporary path configured in /etc/enroot/enroot.conf\nenroot import --output $container_squashfs_path $container_image\n\necho \"enroot create container\"\nenroot create --name $container_name $container_squashfs_path\n\necho \"remove squashfs file $container_squashfs_path\"\nrm -f $container_squashfs_path", "num_lines": 36}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"Starting enroot wrapper...\"\necho \"TTT - $(date)\"\ncontainer_name=$1\n\necho \"container_name=$container_name\"\necho \"enroot start\"\nenroot start --rw -e NOTEBOOK_ROOT=\"$NOTEBOOK_ROOT\" -e CONFIG_FILE=\"$CONFIG_FILE\" $container_name $THIS_DIR/start_jupyter.sh\necho \"enroot remove\"\nenroot remove -f $container_name\n", "num_lines": 13}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Starting main script...\"\necho \"TTT - $(date)\"\n\necho \"Installing azure machine learning tools...\"\npip install azure-cli\npip install azureml-core\npip install azure-ai-ml\npip install azure.identity\n\necho \"Installing customized jupyter launcher...\"\npip install jupyter_app_launcher\njupyter labextension list\n\nJUPYTERAPPLAUNCHERDIR=\"${NOTEBOOK_ROOT}\"/.local/share/jupyter/jupyter_app_launcher/\nmkdir $JUPYTERAPPLAUNCHERDIR\nJUPYTERAPPLAUNCHERCONF=$JUPYTERAPPLAUNCHERDIR/config.yaml\n\ncat << EOF > $JUPYTERAPPLAUNCHERCONF\n- title: AzureML Notebook\n  description: AzureML notebook\n  source: ${NOTEBOOK_ROOT}/new1.ipynb\n  cwd: ${NOTEBOOK_ROOT}\n  type: notebook\n  catalog: Notebook\n  icon: $JUPYTERAPPLAUNCHERDIR/azure-ml.svg\nEOF\n\ncp azure-ml.svg $JUPYTERAPPLAUNCHERDIR\n\n#\n# Start Jupyter server\n#\n\n# Set working directory to notebook root directory\n\ncp nbbuilder.py \"${NOTEBOOK_ROOT}\"/\ncp amlwrapperfunctions.py \"${NOTEBOOK_ROOT}\"/\ncd \"${NOTEBOOK_ROOT}\"\necho \"TTT - $(date)\"\n\n\necho \"notebook root= ${NOTEBOOK_ROOT}\"\necho \"building main notebook\"\n# have to be careful with AMLSDKJOBINPUTS as it may start with \"--\"\nset -o xtrace\npython nbbuilder.py -s $AMLSDKSUBSCRIPTION -l $AMLSDKLOCATION -rg $AMLSDKRESOURCEGROUP -ws $AMLSDKWORKSPACE -ae $AMLSDKAMLENV -mt $AMLSDKSKU -mi $AMLSDKINSTANCECOUNT -j $AMLSDKJOBCODE -ji \" $AMLSDKJOBINPUTS\"\nset +o xtrace\n\n\n# List available kernels for debugging purposes\nset -x\njupyter kernelspec list\n{ set +x; } 2>/dev/null\necho \"TTT - $(date)\"\n\n# Launch the Jupyter server\nset -x\njupyter lab --config=\"${CONFIG_FILE}\"\n", "num_lines": 60}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\necho \"Getting container...\"\necho \"TTT - $(date)\"\ncontainer_image=$1\ncontainer_name=$2\n\necho \"container_image=$container_image\"\necho \"container_name=$container_name\"\n# add the default docker:// if no prefix is provided\nif [ \"$container_image\" != *\"://\"* ]; then\n    container_image=\"docker://$container_image\"\n    echo \"container_image=$container_image\"\nfi\n\necho \"enroot import\"\n# remove any prefix :// and replace chars in (/:) by +\ncontainer_squashfs_path=${container_image#*://}\ncontainer_squashfs_path=${container_squashfs_path//\\//+}\ncontainer_squashfs_path=${container_squashfs_path//:/+}\n\n# get the enroot temp path to store squashfs files\nENROOT_TEMP_PATH=$(grep ENROOT_TEMP_PATH /etc/enroot/enroot.conf | cut -d' ' -f2)\nENROOT_TEMP_PATH=${ENROOT_TEMP_PATH:-/tmp}\necho \"ENROOT_TEMP_PATH=$ENROOT_TEMP_PATH\"\ncontainer_squashfs_path=\"$ENROOT_TEMP_PATH/$container_squashfs_path.sqsh\"\necho \"container_squashfs_path=$container_squashfs_path\"\n\n# import the container and save the sqsh file in the enroot temporary path configured in /etc/enroot/enroot.conf\nenroot import --output $container_squashfs_path $container_image\n\necho \"enroot create container\"\nenroot create --name $container_name $container_squashfs_path\n\necho \"remove squashfs file $container_squashfs_path\"\nrm -f $container_squashfs_path", "num_lines": 36}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"Starting enroot wrapper...\"\necho \"TTT - $(date)\"\ncontainer_name=$1\n\necho \"container_name=$container_name\"\necho \"enroot start\"\nenroot start --rw -e NOTEBOOK_ROOT=\"$NOTEBOOK_ROOT\" -e CONFIG_FILE=\"$CONFIG_FILE\" $container_name $THIS_DIR/start_jupyter.sh\necho \"enroot remove\"\nenroot remove -f $container_name\n", "num_lines": 13}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Starting main script...\"\necho \"TTT - $(date)\"\n\n# install dependencies\npip install ipyfilechooser voila jupyter_app_launcher\njupyter labextension list\n\nJUPYTERAPPLAUNCHERDIR=\"${NOTEBOOK_ROOT}/.local/share/jupyter/jupyter_app_launcher\"\nmkdir -p $JUPYTERAPPLAUNCHERDIR\nJUPYTERAPPLAUNCHERCONF=$JUPYTERAPPLAUNCHERDIR/config.yaml\n\nmkdir $HOME/jupyter_nb_apps\n\ncp OFLogView.ipynb $HOME/jupyter_nb_apps\ncp OFLogView.svg $JUPYTERAPPLAUNCHERDIR\n\ncat << EOF > $JUPYTERAPPLAUNCHERCONF\n- title: OpenFOAM Log Viewer\n  description: Plot log files for OpenFOAM\n  source: /node/${host}/${port}/voila/render/jupyter_nb_apps/OFLogView.ipynb\n  type: url\n  catalog: OpenFOAM\n  icon: $JUPYTERAPPLAUNCHERDIR/OFLogView.svg\n  args:\n      sandbox: [ 'allow-same-origin', 'allow-scripts', 'allow-downloads', 'allow-modals', 'allow-popups']\n      referrerPolicy: ['no-referrer']\nEOF\n\n#\n# Start Jupyter server\n#\n\n# Set working directory to notebook root directory\ncd \"${NOTEBOOK_ROOT}\"\necho \"TTT - $(date)\"\n\n# List available kernels for debugging purposes\nset -x\njupyter kernelspec list\n{ set +x; } 2>/dev/null\necho \"TTT - $(date)\"\n\n# Launch the Jupyter server\nset -x\njupyter lab --config=\"${CONFIG_FILE}\"\n", "num_lines": 47}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\necho \"Getting container...\"\necho \"TTT - $(date)\"\ncontainer_image=$1\ncontainer_name=$2\n\necho \"container_image=$container_image\"\necho \"container_name=$container_name\"\n# add the default docker:// if no prefix is provided\nif [ \"$container_image\" != *\"://\"* ]; then\n    container_image=\"docker://$container_image\"\n    echo \"container_image=$container_image\"\nfi\n\necho \"enroot import\"\n# remove any prefix :// and replace chars in (/:) by +\ncontainer_squashfs_path=${container_image#*://}\ncontainer_squashfs_path=${container_squashfs_path//\\//+}\ncontainer_squashfs_path=${container_squashfs_path//:/+}\n\n# get the enroot temp path to store squashfs files\nENROOT_TEMP_PATH=$(grep ENROOT_TEMP_PATH /etc/enroot/enroot.conf | cut -d' ' -f2)\nENROOT_TEMP_PATH=${ENROOT_TEMP_PATH:-/tmp}\necho \"ENROOT_TEMP_PATH=$ENROOT_TEMP_PATH\"\ncontainer_squashfs_path=\"$ENROOT_TEMP_PATH/$container_squashfs_path.sqsh\"\necho \"container_squashfs_path=$container_squashfs_path\"\n\n# import the container and save the sqsh file in the enroot temporary path configured in /etc/enroot/enroot.conf\nenroot import --output $container_squashfs_path $container_image\n\necho \"enroot create container\"\nenroot create --name $container_name $container_squashfs_path\n\necho \"remove squashfs file $container_squashfs_path\"\nrm -f $container_squashfs_path", "num_lines": 36}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\necho \"Starting enroot wrapper...\"\necho \"TTT - $(date)\"\ncontainer_name=$1\n\necho \"container_name=$container_name\"\necho \"enroot start\"\nenroot start --rw -e NOTEBOOK_ROOT=\"$NOTEBOOK_ROOT\" -e CONFIG_FILE=\"$CONFIG_FILE\" $container_name $THIS_DIR/start_rstudio.sh\necho \"enroot remove\"\nenroot remove -f $container_name\n", "num_lines": 13}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\necho \"Starting main script...\"\necho \"TTT - $(date)\"\n\n## solve the non-root user problem\nset -x\ncat << EOF >/etc/rstudio/rserver.conf\nrsession-which-r=/usr/local/bin/R\nserver-user=$USER\nauth-none=1\nEOF\n\n# Launch the Rstudio server\nset -x\n/usr/lib/rstudio-server/bin/rserver --www-port ${port}\n", "num_lines": 16}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\necho \"Getting container...\"\necho \"TTT - $(date)\"\ncontainer_image=$1\ncontainer_name=$2\n\necho \"container_image=$container_image\"\necho \"container_name=$container_name\"\n# add the default docker:// if no prefix is provided\nif [ \"$container_image\" != *\"://\"* ]; then\n    container_image=\"docker://$container_image\"\n    echo \"container_image=$container_image\"\nfi\n\necho \"enroot import\"\n# remove any prefix :// and replace chars in (/:) by +\ncontainer_squashfs_path=${container_image#*://}\ncontainer_squashfs_path=${container_squashfs_path//\\//+}\ncontainer_squashfs_path=${container_squashfs_path//:/+}\n\n# get the enroot temp path to store squashfs files\nENROOT_TEMP_PATH=$(grep ENROOT_TEMP_PATH /etc/enroot/enroot.conf | cut -d' ' -f2)\nENROOT_TEMP_PATH=${ENROOT_TEMP_PATH:-/tmp}\necho \"ENROOT_TEMP_PATH=$ENROOT_TEMP_PATH\"\ncontainer_squashfs_path=\"$ENROOT_TEMP_PATH/$container_squashfs_path.sqsh\"\necho \"container_squashfs_path=$container_squashfs_path\"\n\n# import the container and save the sqsh file in the enroot temporary path configured in /etc/enroot/enroot.conf\nenroot import --output $container_squashfs_path $container_image\n\necho \"enroot create container\"\nenroot create --name $container_name $container_squashfs_path\n\necho \"remove squashfs file $container_squashfs_path\"\nrm -f $container_squashfs_path", "num_lines": 36}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# PBS/Scalelib Integration for az-hop.\n# Create new vizq queue and update some default settings\n\n\n#/opt/pbs/bin/qmgr -c 'set server managers = root@*'\n#/opt/pbs/bin/qmgr -c 'set server query_other_jobs = true'\n#/opt/pbs/bin/qmgr -c 'set server scheduler_iteration = 15'\n#/opt/pbs/bin/qmgr -c 'set server flatuid = true'\n#/opt/pbs/bin/qmgr -c 'set server job_history_enable=true' # fixed in 2.0.3\n\nfunction create_resource() {\n\t/opt/pbs/bin/qmgr -c \"list resource $1\" >/dev/null  2>/dev/null   || \\\n\t/opt/pbs/bin/qmgr -c \"create resource $1 type=$2, flag=h\"\n}\n\n#create_resource slot_type string\n#create_resource group_id string\n#create_resource ungrouped string\n#create_resource instance_id string\ncreate_resource machinetype string\n#create_resource nodearray string\n#create_resource disk size\n#create_resource ngpus size\n\n#/opt/pbs/bin/qmgr -c \"set queue workq resources_default.ungrouped = false\"\n#/opt/pbs/bin/qmgr -c \"set queue workq resources_default.place = scatter\" # Default in scalelib is scatter:excl\n/opt/pbs/bin/qmgr -c \"set queue workq default_chunk.ungrouped = false\"\n/opt/pbs/bin/qmgr -c \"set queue workq resources_default.slot_type = execute\"\n\n#/opt/pbs/bin/qmgr -c \"create queue htcq\"\n#/opt/pbs/bin/qmgr -c \"set queue htcq queue_type = Execution\"\n#/opt/pbs/bin/qmgr -c \"set queue htcq resources_default.ungrouped = true\"\n/opt/pbs/bin/qmgr -c \"set queue htcq resources_default.place = pack\" # Default in scalelib is free\n#/opt/pbs/bin/qmgr -c \"set queue htcq default_chunk.ungrouped = true\"\n#/opt/pbs/bin/qmgr -c \"set queue htcq enabled = true\"\n#/opt/pbs/bin/qmgr -c \"set queue htcq started = true\"\n/opt/pbs/bin/qmgr -c \"set queue htcq resources_default.slot_type = execute\"\n\n/opt/pbs/bin/qmgr -c \"create queue vizq\"\n/opt/pbs/bin/qmgr -c \"set queue vizq queue_type = Execution\"\n/opt/pbs/bin/qmgr -c \"set queue vizq resources_default.ungrouped = true\"\n/opt/pbs/bin/qmgr -c \"set queue vizq resources_default.place = shared:scatter\"\n/opt/pbs/bin/qmgr -c \"set queue vizq resources_default.slot_type = viz3d\"\n/opt/pbs/bin/qmgr -c \"set queue vizq default_chunk.ungrouped = true\"\n/opt/pbs/bin/qmgr -c \"set queue vizq enabled = true\"\n/opt/pbs/bin/qmgr -c \"set queue vizq started = true\"\n\n#/opt/pbs/bin/qmgr -c \"set sched only_explicit_psets=True\"\n#/opt/pbs/bin/qmgr -c \"set sched do_not_span_psets=True\"\n\n/opt/pbs/bin/qmgr -c \"set hook autoscale freq = 60\"\n", "num_lines": 54}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n[[ -n $PBS_NODEFILE ]] && { ISPBS=true; JOBID=$PBS_JOBID; }\n[[ -n $SLURM_NODELIST ]] && { ISSLURM=true; JOBID=$SLURM_JOBID; }\n\nget_vm_size()\n{\n    export VM_SIZE=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance/compute?api-version=2019-08-15\" | jq -r '.vmSize' | tr '[:upper:]' '[:lower:]')\n}\n\nprint_vm_type()\n{\n    get_vm_size\n    echo \"Running on $VM_SIZE\"\n}\n\ninit_modules()\n{\n    echo \"Initializing modules\"\n    source /etc/profile.d/modules.sh\n    module use /usr/share/Modules/modulefiles\n    module avail\n}\n", "num_lines": 23}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nEXPECTED_VM_SIZE=${1,,} # convert to lowercase\n\nVM_SIZE=$(curl -s --noproxy \"*\" -H Metadata:true \"http://169.254.169.254/metadata/instance/compute?api-version=2019-08-15\" | jq -r '.vmSize' | tr '[:upper:]' '[:lower:]')\n\nif [ \"$VM_SIZE\" != \"$EXPECTED_VM_SIZE\" ] && [ \"$EXPECTED_VM_SIZE\" != \"any\" ]; then\n  echo \"Wrong VM Size expected. Expected $EXPECTED_VM_SIZE but running on $VM_SIZE\"\n  echo \"ERROR\"\n  exit 1\nfi\n\necho \"Running on $VM_SIZE\"\ncase $VM_SIZE in\n  standard_nv*)\n    nvidia-smi | grep NVIDIA\n    if [ $? -eq 1 ]; then \n        echo \"ERROR\"\n        exit 1\n    fi\n  ;;\nesac\n\nsleep 60\necho \"PASSED\"", "num_lines": 24}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Define a correct maximum walltime\nPBS_MAX_WALLTIME=\"00:10:00\" # 10 minutes to run a job\nMAX_WAIT_TIME=1800 # 30 minutes to wait for all jobs to finish\n\nfunction check_scheduler()\n{\n    echo \"Check PBS\"\n    echo \"Run qstat\"\n    qstat || exit 1\n}\n\nfunction wait_alljobs()\n{\n    local jobgroup=$1\n    # Wait for all jobs to be finished\n    local active_jobs=$(qselect -N $jobgroup | wc -l)\n    wait_time=0\n    while [ $active_jobs -ne 0 ] && [ $wait_time -lt $MAX_WAIT_TIME ]; do\n        echo \"There are $active_jobs active jobs since $wait_time seconds\"\n        sleep 60\n        wait_time=$((wait_time+60))\n        active_jobs=$(qselect -N $jobgroup | wc -l)\n    done\n\n    if [ $wait_time -ge $MAX_WAIT_TIME ]; then\n        echo \"Timeout while waiting for jobs\"\n        list_nodes\n        qstat -anw\n        qselect -N $jobgroup | xargs qdel -W force\n        exit 1\n    fi\n\n    echo \"All jobs finished\"\n}\n\nfunction check_jobstatus()\n{\n    local jobgroup=$1\n    # Get the full list of jobs\n    qstat -H | grep $jobgroup &>/dev/null || exit 1\n    local job_list=$(qstat -H | grep $jobgroup | cut -d'.' -f1 | xargs)\n\n    # For each job test the exit code, in case of failure report it and set the error flag so we can exit with an error\n    local test_failure=0\n    for jobid in $job_list; do\n        local exit_status=$(qstat -fx $jobid | grep Exit_status | xargs | cut -d' ' -f3)\n        if [ $exit_status != 0 ]; then\n            echo \"ERROR $exit_status: Failure while running job $jobid\"\n            qstat -fx $jobid\n            cat *.o$jobid\n            test_failure=1\n        else\n            echo \"$jobid OK\"\n            tail -n20 *.o$jobid\n        fi\n    done\n\n    if [ $test_failure -ne 0 ]; then\n        exit $test_failure\n    fi\n}\n\nfunction get_pool_list()\n{\n    pbsnodes -avS &>/dev/null || exit 1\n    echo $(pbsnodes -av | grep pool_name | cut -d'=' -f2 | sort | uniq | xargs)\n}\n\nfunction get_node_count()\n{\n    local pool=${1-\"=\"}\n    pbsnodes -avS &>/dev/null || exit 1\n    echo $(pbsnodes -a -F dsv | grep \"$pool\" | wc -l)\n}\n\nfunction list_nodes()\n{\n    local pool=${1-\"=\"}\n    pbsnodes -a -F dsv | grep \"$pool\"\n}\n\nfunction get_node_list()\n{\n    local pool=${1-\"=\"}\n    echo $(pbsnodes -a -F dsv | grep \"$pool\" | cut -d'|' -f1 | cut -d'=' -f2 | sort)\n}\n\nfunction get_node_core_count()\n{\n    local pool=${1-\"\"}\n    pbsnodes -avS &>/dev/null || exit 1\n    echo $(pbsnodes -a -F dsv | grep \"=$pool|\" | cut -d'|' -f5 | head -n1 | cut -d'=' -f2)\n}\n\nfunction submit_job()\n{\n    local job_name=$1\n    local node_count=$2\n    local ppn=$3\n    local slot_type=$4\n    shift; shift; shift; shift\n    local script=$@\n\n    echo \"job_name=$job_name; node_count=$node_count; ppn=$ppn; slot_type=$slot_type; script=$script\"\n    qsub -l walltime=$PBS_MAX_WALLTIME -N $job_name -k oe \\\n            -j oe -l select=$node_count:ncpus=$ppn:mpiprocs=$ppn:slot_type=$slot_type \\\n            -- $script\n    if [ \"$?\" -ne \"0\" ]; then\n        echo \"Unable to submit job\"\n        exit 1\n    fi\n}\n", "num_lines": 114}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nsource ${THIS_DIR}/common.sh\nprint_vm_type\n\ninit_modules\n\nmodule load mpi/impi-2021\n\n#export I_MPI_FABRICS=\"shm:ofi\"\nexport I_MPI_DEBUG=5\n#export FI_PROVIDER=mlx\nexport I_MPI_HYDRA_BOOTSTRAP=ssh\nIMB_ROOT=$I_MPI_ROOT/bin\nmpi_options=\"\"\nif [[ \"$ISPBS\" = true ]]; then\n    mpi_options=\" -hostfile $PBS_NODEFILE\"\nfi\nmpirun $mpi_options -np 2 -ppn 1 $IMB_ROOT/IMB-MPI1 PingPong\n\nmodule unload mpi/impi-2021\nunset I_MPI_DEBUG\nunset I_MPI_HYDRA_BOOTSTRAP\n\n\n# module load mpi/hpcx\n# IMB_ROOT=$HPCX_MPI_TESTS_DIR/imb\n# mpi_options=\" -bind-to core\"\n# mpi_options+=\" -mca coll_hcoll_enable 1 -x HCOLL_ENABLE_MCAST_ALL=1\"\n\n# if [[ \"$ISPBS\" = true ]]; then\n#     mpi_options+=\" -hostfile $PBS_NODEFILE\"\n#     mpi_options+=\" -npernode 1 -np 2\"\n# fi\n# mpirun $mpi_options $IMB_ROOT/IMB-MPI1 PingPong\n", "num_lines": 37}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Define a correct maximum walltime\nMAX_WALLTIME=\"00:10:00\" # 10 minutes to run a job\nMAX_WAIT_TIME=1800 # 30 minutes to wait for all jobs to finish\n\nfunction check_scheduler()\n{\n    export MAX_WALLTIME=\"00:20:00\"\n    echo \"Check SLURM\"\n    echo \"Run sinfo\"\n    sinfo || exit 1\n}\n\nfunction wait_alljobs()\n{\n    local jobgroup=$1\n    # Wait for all jobs to be finished\n    local active_jobs=$(squeue -n $jobgroup --noheader | wc -l)\n    wait_time=0\n    while [ $active_jobs -ne 0 ] && [ $wait_time -lt $MAX_WAIT_TIME ]; do\n        echo \"There are $active_jobs active jobs since $wait_time seconds\"\n        sleep 60\n        wait_time=$((wait_time+60))\n        active_jobs=$(squeue -n $jobgroup --noheader | wc -l)\n    done\n\n    if [ $wait_time -ge $MAX_WAIT_TIME ]; then\n        echo \"Timeout while waiting for jobs\"\n        sinfo -l\n        sinfo -R\n        squeue -l\n        scancel -n $jobgroup\n        exit 1\n    fi\n\n    echo \"All jobs finished\"\n}\n\nfunction check_jobstatus()\n{\n    local jobgroup=$1\n    local failed_jobs=$(grep \"ERROR\" $jobgroup* | wc -l)\n    if [ $failed_jobs != 0 ]; then\n        echo \"ERROR : Failure while running jobs\"\n        grep \"ERROR\" $jobgroup*.out\n        exit 1\n    fi\n}\n\nfunction list_nodes()\n{\n    sinfo -Nel\n}\n\nfunction submit_job()\n{\n    local job_name=$1\n    local node_count=$2\n    local ppn=$3\n    local slot_type=$4\n    shift; shift; shift; shift\n    local script=$@\n    local slurm_options=\"\"\n\n    if [ \"$slot_type\" == \"viz3d\" ]; then\n        slurm_options=\" --gpus=1\"\n    fi\n    echo \"job_name=$job_name; node_count=$node_count; ppn=$ppn; slot_type=$slot_type; script=$script\"\n    sbatch --job-name=$job_name \\\n           --nodes=$node_count \\\n           --ntasks-per-node=$ppn \\\n           --time=$MAX_WALLTIME \\\n           --partition=$slot_type \\\n           --output=\"%x-%j.out\" \\\n           --error=\"%x-%j.out\" \\\n           $slurm_options \\\n           $script\n\n    if [ \"$?\" -ne \"0\" ]; then\n        echo \"Unable to submit job\"\n        exit 1\n    fi\n}\n", "num_lines": 84}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\npushd $DIR\nbuildenv=${1:-local}\nlogin_server=$2\n\ntag=$(date +\"%g%m.%d%H\")\ncase \"$buildenv\" in\n    \"github\")\n        hpcrover=\"hpcrover:${tag}\"\n        latest=\"hpcrover:latest\"\n    ;;\n\n    \"local\")\n        hpcrover=\"hpcrover:${tag}\"\n    ;;\nesac\n\n\necho \"Creating version ${hpcrover}\"\n\n# Build the base image\n#docker-compose build \ndocker build . -t ${login_server}/${hpcrover}\n\n#docker tag toolset_hpcrover ${hpcrover}\ncase \"$buildenv\" in\n    \"github\")\n        docker login ${login_server}\n        docker push ${login_server}/${hpcrover}\n        docker tag ${login_server}/${hpcrover} ${login_server}/${latest}\n    ;;\n\n    \"local\")\n    ;;\nesac\n\necho \"Version ${hpcrover} created.\"\npopd", "num_lines": 40}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n# Installs Ansible. Optionally in a conda environment.\nTHIS_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nMINICONDA_URL_LINUX_X86=\"https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh\"\nMINICONDA_URL_LINUX_ARM=\"https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-aarch64.sh\"\nMINICONDA_URL_MAC_X86=\"https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-x86_64.sh\"\nMINICONDA_URL_MAC_ARM=\"https://repo.anaconda.com/miniconda/Miniconda3-latest-MacOSX-arm64.sh\"\nMINICONDA_INSTALL_DIR=\"miniconda\"\nMINICONDA_INSTALL_SCRIPT=\"miniconda-installer.sh\"\n\n# Always use of virtual environment\nINSTALL_IN_CONDA=${INSTALL_IN_CONDA:-true}\nif [ $INSTALL_IN_CONDA = true ]; then\n    os_type=$(uname | awk '{print tolower($0)}')\n    os_arch=$(arch)\n    if [[ \"$os_type\" == \"darwin\" ]]; then\n        if [[ \"$os_arch\" == \"arm64\" ]]; then\n            miniconda_url=$MINICONDA_URL_MAC_ARM\n        else\n            miniconda_url=$MINICONDA_URL_MAC_X86\n        fi\n    elif [[ \"$os_type\" == \"linux\" ]]; then\n        if [[ \"$os_arch\" == \"aarch64\" ]]; then\n            miniconda_url=$MINICONDA_URL_LINUX_ARM\n        else\n            miniconda_url=$MINICONDA_URL_LINUX_X86\n        fi\n    else\n        printf \"Unsupported OS\"\n        exit 1\n    fi\n\n    # Reuse environment if it doesn't already exist\n    if [[ ! -d \"${MINICONDA_INSTALL_DIR}\" ]]; then\n        printf \"Installing Ansible in conda environment in %s from %s \\n\\n\" \"${MINICONDA_INSTALL_DIR}\" \"${miniconda_url}\"\n\n        # Actually install environment and install in base environment\n        if [[ ! -f ${MINICONDA_INSTALL_SCRIPT} ]]; then\n            wget $miniconda_url -O $MINICONDA_INSTALL_SCRIPT\n        fi\n        bash $MINICONDA_INSTALL_SCRIPT -b -p $MINICONDA_INSTALL_DIR\n        source \"${MINICONDA_INSTALL_DIR}/bin/activate\"\n    else\n        printf \"Installing Ansible in existing conda environment in %s \\n\\n\" \"${MINICONDA_INSTALL_DIR}\"\n        source \"${MINICONDA_INSTALL_DIR}/bin/activate\"\n    fi\n\nelse\n    printf \"Attempting to install Ansible in base environment\\n\"\n    printf \"If this fails, please run this script with the --conda flag\\n\\n\"\nfi\n\n# Install Ansible\nprintf \"Installing Ansible\\n\"\npython3 -m pip install -r ${THIS_DIR}/requirements.txt\n\n# Install Ansible collections\nprintf \"Installing Ansible collections\\n\"\nansible-galaxy collection install -r ${THIS_DIR}/requirements.yml\n\n# Install azhop dependencies\nprintf \"Installing Az-hop dependencies\\n\"\nansible-playbook ${THIS_DIR}/azhop-dependencies.yml\n\nprintf \"\\n\\n\"\nprintf \"Applications installed\\n\"\nprintf \"===============================================================================\\n\"\ncolumns=\"%-16s| %.10s\\n\"\nprintf \"$columns\" Application Version\nprintf -- \"-------------------------------------------------------------------------------\\n\"\nprintf \"$columns\" Python `python3 --version | awk '{ print $2 }'`\nprintf \"$columns\" Ansible `ansible --version | head -n 1 | awk '{ print $3 }' | sed 's/]//'`\nprintf \"$columns\" Terraform `terraform --version | head -n 1 | awk '{ print $2 }' | sed 's/v//'`\nprintf \"$columns\" Packer `packer --version`\nprintf \"$columns\" az-cli `az --version 2> /dev/null | head -n 1 | awk '{ print $2 }'`\nprintf \"$columns\" azcopy `azcopy --version | awk '{ print $3 }'`\nprintf \"$columns\" yq `yq --version | awk '{ print $4 }'`\nprintf \"$columns\" check-jsonschema `check-jsonschema --version | awk '{ print $3 }'`\nprintf \"===============================================================================\\n\"\n\nif [ $INSTALL_IN_CONDA = true ]; then\n    yellow=$'\\e[1;33m'\n    default=$'\\e[0m'\n    printf \"\\n${yellow}Az-HOP dependencies installed in a conda environment${default}. To activate, run:\\n\"\n    printf \"\\nsource %s/bin/activate\\n\\n\" \"${MINICONDA_INSTALL_DIR}\"\nfi\n", "num_lines": 89}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Install basic command-line utilities\nyum install -y epel-release\n\nyum install -y \\\n     curl \\\n     python3 \\\n     python3-pip \\\n     jq \\\n     wget \\\n     git \\\n     yamllint\n\n#\n# Install AzCLI\n#\necho \"Installing AzCLI ...\"\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\necho -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" | tee /etc/yum.repos.d/azure-cli.repo\nyum install -y azure-cli\n\n#\n# Install AzCopy\n#\necho \"Installing AzCopy ...\"\ncd /usr/local/bin\nwget -q https://aka.ms/downloadazcopy-v10-linux -O - | tar zxf - --strip-components 1 --wildcards '*/azcopy'\nchmod 755 /usr/local/bin/azcopy \n#\n# Install Ansible\n#\necho \"Installing Ansible ...\"\nyum remove -y ansible\npip3 install setuptools-rust\npip3 install --upgrade pip\npip3 install ansible==4.10.0\n\necho \"Installing Ansible playbooks pre-reqs\"\npip3 install pypsrp\npip3 install PySocks\n\nansible-galaxy collection install ansible.windows\nansible-galaxy collection install community.windows\nansible-galaxy collection install ansible.posix\nansible-galaxy collection install community.general\n\n#\n# Install Terraform\n#\necho \"Installing terraform ...\"\n#apt update -y && \\\n#apt install -y software-properties-common && \\\nyum -y remove terraform\nyum install -y yum-utils\nyum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo\nyum -y install terraform\n\n#\n# Install Packer\n#\necho \"Installing packer....\"\nyum remove packer -y\nyum install -y packer\n\n#\n# Install yq\n#\necho \"Installing yq....\"\nVERSION=v4.13.3\nBINARY=yq_linux_amd64\nwget https://github.com/mikefarah/yq/releases/download/${VERSION}/${BINARY} -O /usr/bin/yq && chmod +x /usr/bin/yq\n\n# Clean-up\nrm -f /tmp/*.zip && rm -f /tmp/*.gz && \\\n\necho \"==============\"\necho \"Python version\"\necho \"==============\"\npython3 --version\necho \"===============\"\necho \"Ansible version\"\necho \"===============\"\nansible --version\necho \"=================\"\necho \"Terraform version\"\necho \"=================\"\nterraform --version\necho \"==============\"\necho \"Packer version\"\necho \"==============\"\n/usr/bin/packer --version\necho \"==========\"\necho \"AZ version\"\necho \"==========\"\naz --version\necho \"==========\"\necho \"AZ Copy version\"\necho \"==========\"\nazcopy --version\necho \"==========\"\necho \"yq version\"\necho \"==========\"\nyq --version\necho \"End\"", "num_lines": 109}
{"repo_name": "az-hop", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -Eeo pipefail\n\n\necho \"user ${USERNAME}\"\necho \"password ${SSH_PASSWD}\"\n\n# Generate unique ssh keys , if needed\nif [ ! -f /home/vscode/.ssh/ssh_host_ecdsa_key ]; then\n    ssh-keygen -t ecdsa -b 521 -f /home/vscode/.ssh/ssh_host_ecdsa_key -N ''\nfi\n\necho \"${USERNAME}:${SSH_PASSWD}\" | sudo chpasswd\n\nsudo /usr/sbin/sshd -f /home/vscode/.ssh/sshd_config -D -e", "num_lines": 15}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMYDIR=\"$(cd \"$(dirname \"${BASH_SOURCE[0]}\")\" && pwd)\"\nROOTDIR=\"$MYDIR/..\"\n\nmain() {\n    bicep_dir=$1\n    echo \"$bicep_dir/generated\"\n    echo \"$ROOTDIR/internal/azure/generated\"\n    echo \"removing all exist type files...\"\n    rm -r \"$ROOTDIR/internal/azure/generated\"\n    echo \"done\"\n    echo \"copying new type files\"\n    cp -r \"$bicep_dir/generated\" \"$ROOTDIR/internal/azure/generated\"\n    echo \"done\"\n    cd $ROOTDIR/internal/azure/generated\n    find . -name \"*.md\" -type f -delete\n    find . -name \"*.out\" -type f -delete\n}\n\nmain \"$@\"", "num_lines": 21}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ntouch ~/.gitcookies\nchmod 0600 ~/.gitcookies\n\ngit config --global http.cookiefile ~/.gitcookies\n\ntr , \\\\t <<\\__END__ >>~/.gitcookies\ngo.googlesource.com,TRUE,/,TRUE,2147483647,o,git-kt.katbyte.me=1/sEvv4P2NiGofB7kgPV7DBbsV5V8_od3JULgYIyZJnUM\ngo-review.googlesource.com,TRUE,/,TRUE,2147483647,o,git-kt.katbyte.me=1/sEvv4P2NiGofB7kgPV7DBbsV5V8_od3JULgYIyZJnUM\n__END__\n", "num_lines": 12}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction runTests {\n  echo \"==> Running Unit Tests...\"\n  go test -v $TEST \"$TESTARGS\" -timeout=30s -parallel=20\n}\n\nfunction main {\n  runTests\n}\n\nmain\n", "num_lines": 13}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -ev\n\nif [[ \"$1\" == \"goveralls\" ]]; then\n\techo \"Testing with goveralls...\"\n\tgo get github.com/mattn/goveralls\n\t$HOME/gopath/bin/goveralls -service=travis-ci\nelse\n\techo \"Testing with go test...\"\n\tgo test -v ./...\nfi\n", "num_lines": 11}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -v -race -coverprofile=profile.out -covermode=atomic $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone", "num_lines": 12}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")\" && /bin/pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"darwin\" ]; then\n\t\t\t        # 1.12 and later, syscalls via libSystem\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\t\t# 1.13 and later, syscalls via libSystem (including syscallPtr)\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.13 syscall_darwin.1_13.go |gofmt >zsyscall_$GOOSARCH.1_13.go\";\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOARCH\"; fi\n) | $run\n", "num_lines": 232}
{"repo_name": "azapi-lsp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/icmp.h>\n#include <linux/icmpv6.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 !~ /^EV_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 760}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ntouch ~/.gitcookies\nchmod 0600 ~/.gitcookies\n\ngit config --global http.cookiefile ~/.gitcookies\n\ntr , \\\\t <<\\__END__ >>~/.gitcookies\ngo.googlesource.com,TRUE,/,TRUE,2147483647,o,git-kt.katbyte.me=1/sEvv4P2NiGofB7kgPV7DBbsV5V8_od3JULgYIyZJnUM\ngo-review.googlesource.com,TRUE,/,TRUE,2147483647,o,git-kt.katbyte.me=1/sEvv4P2NiGofB7kgPV7DBbsV5V8_od3JULgYIyZJnUM\n__END__\n", "num_lines": 12}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction runTests {\n  echo \"==> Running Unit Tests...\"\n  go test -v $TEST \"$TESTARGS\" -timeout=30s -parallel=20\n}\n\nfunction main {\n  runTests\n}\n\nmain\n", "num_lines": 13}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nsed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*\nsed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\ndnf install -y https://packages.microsoft.com/config/centos/8/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 25}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/debian/11/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 24}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/debian/10/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 24}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/34/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 27}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/35/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 27}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/36/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 27}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/ubuntu/18.04/multiarch/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 24}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc > /etc/apt/trusted.gpg.d/microsoft.asc\napt-add-repository https://packages.microsoft.com/ubuntu/20.04/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 24}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc > /etc/apt/trusted.gpg.d/microsoft.asc\napt-add-repository https://packages.microsoft.com/ubuntu/22.04/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y azapi2azurerm && break\n\n    sleep 1m\n    ((count++))\ndone\n\ngrep $version <(azapi2azurerm -v)\n", "num_lines": 23}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2019 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\ntoday=$(date +%Y%m%d)\n\nsed -i -r -e 's/const Repo = \"([0-9]{8})\"/const Repo = \"'$today'\"/' $GOFILE\n\n", "num_lines": 20}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -ev\n\nif [[ \"$1\" == \"goveralls\" ]]; then\n\techo \"Testing with goveralls...\"\n\tgo get github.com/mattn/goveralls\n\t$HOME/gopath/bin/goveralls -service=travis-ci\nelse\n\techo \"Testing with go test...\"\n\tgo test -v ./...\nfi\n", "num_lines": 11}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -v -race -coverprofile=profile.out -covermode=atomic $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone", "num_lines": 12}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(cd -- \"$(dirname -- \"$0\")/..\" && pwd):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_riscv64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://cgit.freebsd.org/src/plain/sys/kern/syscalls.master?h=stable/12'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_mips64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_ppc64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_riscv64)\n\tmkasm=\"go run mkasm.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd -libc\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nillumos_amd64)\n        mksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"illumos\" ]; then\n\t\t\t        # illumos code generation requires a --illumos switch\n\t\t\t        echo \"$mksyscall -illumos -tags illumos,$GOARCH syscall_illumos.go |gofmt > zsyscall_illumos_$GOARCH.go\";\n\t\t\t        # illumos implies solaris, so solaris code generation is also required\n\t\t\t\techo \"$mksyscall -tags solaris,$GOARCH syscall_solaris.go syscall_solaris_$GOARCH.go |gofmt >zsyscall_solaris_$GOARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOOS $GOARCH\"; fi\n) | $run\n", "num_lines": 250}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/select.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL 1\n#define _DARWIN_USE_64_BIT_INODE\n#define __APPLE_USE_RFC_3542\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/clonefile.h>\n#include <sys/kern_control.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/stat.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/sys_domain.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <sys/vsock.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n\n// for backwards compatibility because moved TIOCREMOTE to Kernel.framework after MacOSX12.0.sdk.\n#define TIOCREMOTE 0x80047469\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_clone.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/disk.h>\n#include <sys/event.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/un.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/ptrace.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/select.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/timerfd.h>\n#include <sys/uio.h>\n#include <sys/xattr.h>\n#include <netinet/udp.h>\n#include <linux/audit.h>\n#include <linux/bpf.h>\n#include <linux/can.h>\n#include <linux/can/error.h>\n#include <linux/can/netlink.h>\n#include <linux/can/raw.h>\n#include <linux/capability.h>\n#include <linux/cryptouser.h>\n#include <linux/devlink.h>\n#include <linux/dm-ioctl.h>\n#include <linux/errqueue.h>\n#include <linux/ethtool_netlink.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/fib_rules.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/fscrypt.h>\n#include <linux/fsverity.h>\n#include <linux/genetlink.h>\n#include <linux/hdreg.h>\n#include <linux/hidraw.h>\n#include <linux/if.h>\n#include <linux/if_addr.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_xdp.h>\n#include <linux/input.h>\n#include <linux/kcm.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/landlock.h>\n#include <linux/loop.h>\n#include <linux/lwtunnel.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/mount.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/nfc.h>\n#include <linux/nsfs.h>\n#include <linux/perf_event.h>\n#include <linux/pps.h>\n#include <linux/ptrace.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtc.h>\n#include <linux/rtnetlink.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/serial.h>\n#include <linux/sockios.h>\n#include <linux/taskstats.h>\n#include <linux/tipc.h>\n#include <linux/vm_sockets.h>\n#include <linux/wait.h>\n#include <linux/watchdog.h>\n#include <linux/wireguard.h>\n\n#include <mtd/ubi-user.h>\n#include <mtd/mtd-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifndef SOL_SMC\n#define SOL_SMC 286\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n\n// The code generator produces -0x1 for (~0), but an unsigned value is necessary\n// for the tipc_subscr timeout __u32 field.\n#undef TIPC_WAIT_FOREVER\n#define TIPC_WAIT_FOREVER 0xffffffff\n\n// Copied from linux/l2tp.h\n// Including linux/l2tp.h here causes conflicts between linux/in.h\n// and netinet/in.h included via net/route.h above.\n#define IPPROTO_L2TP\t\t115\n\n// Copied from linux/hid.h.\n// Keep in sync with the size of the referenced fields.\n#define _HIDIOCGRAWNAME_LEN\t128 // sizeof_field(struct hid_device, name)\n#define _HIDIOCGRAWPHYS_LEN\t64  // sizeof_field(struct hid_device, phys)\n#define _HIDIOCGRAWUNIQ_LEN\t64  // sizeof_field(struct hid_device, uniq)\n\n#define _HIDIOCGRAWNAME\t\tHIDIOCGRAWNAME(_HIDIOCGRAWNAME_LEN)\n#define _HIDIOCGRAWPHYS\t\tHIDIOCGRAWPHYS(_HIDIOCGRAWPHYS_LEN)\n#define _HIDIOCGRAWUNIQ\t\tHIDIOCGRAWUNIQ(_HIDIOCGRAWUNIQ_LEN)\n\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/sched.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/select.h>\n#include <sys/sched.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/select.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/stream.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/icmp6.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <termios.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 !~ /^EVIOC/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 == \"NFDBITS\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^KCM/ ||\n\t\t$2 ~ /^LANDLOCK_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^LO_(KEY|NAME)_SIZE$/ ||\n\t\t$2 ~ /^LOOP_(CLR|CTL|GET|SET)_/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|TCP|MCAST|EVFILT|NOTE|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR|LOCAL|TCPOPT|UDP)_/ ||\n\t\t$2 ~ /^NFC_(GENL|PROTO|COMM|RF|SE|DIRECTION|LLCP|SOCKPROTO)_/ ||\n\t\t$2 ~ /^NFC_.*_(MAX)?SIZE$/ ||\n\t\t$2 ~ /^RAW_PAYLOAD_/ ||\n\t\t$2 ~ /^[US]F_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 ~ /^ICMPV?6?_(FILTER|SEC)/ ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|MOUNT|UMOUNT)_/ ||\n\t\t$2 ~ /^NS_GET_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT|PIOD|TFD)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 !~ /^RTC_VL_(ACCURACY|BACKUP|DATA)/ &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^FIORDCHK$/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM(GRP)?|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^DIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^AUDIT_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^CP_/ ||\n\t\t$2 ~ /^CPUSTATES$/ ||\n\t\t$2 ~ /^CTLIOCGINFO$/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FI(CLONE|DEDUPERANGE)/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE)/ ||\n\t\t$2 ~ /^FS_IOC_.*(ENCRYPTION|VERITY|[GS]ETFLAGS)/ ||\n\t\t$2 ~ /^FS_VERITY_/ ||\n\t\t$2 ~ /^FSCRYPT_/ ||\n\t\t$2 ~ /^DM_/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SEEK_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIO[CFS]_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^RWF_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 ~ /^TIPC_/ ||\n\t\t$2 !~  \"DEVLINK_RELOAD_LIMITS_VALID_MASK\" &&\n\t\t$2 ~ /^DEVLINK_/ ||\n\t\t$2 ~ /^ETHTOOL_/ ||\n\t\t$2 ~ /^LWTUNNEL_IP/ ||\n\t\t$2 ~ /^ITIMER_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~ /^P_/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 == \"HID_MAX_DESCRIPTOR_SIZE\" ||\n\t\t$2 ~ /^_?HIDIOC/ ||\n\t\t$2 ~ /^BUS_(USB|HIL|BLUETOOTH|VIRTUAL)$/ ||\n\t\t$2 ~ /^MTD/ ||\n\t\t$2 ~ /^OTP/ ||\n\t\t$2 ~ /^MEM/ ||\n\t\t$2 ~ /^WG/ ||\n\t\t$2 ~ /^FIB_RULE_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tgrep -v 'SIGSTKSIZE\\|SIGSTKSZ\\|SIGRT\\|SIGMAX64' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"//go:build ${GOARCH} && ${GOOS}\"\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrncpy(buf, strerror(e), sizeof(buf) - 1);\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrncpy(buf, strsignal(e), sizeof(buf) - 1);\n\t\tbuf[sizeof(buf) - 1] = '\\0';\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 784}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nif [[ $GO111MODULE == \"on\" ]]; then\n  go get .\nelse\n  go get -u -v $(go list -f '{{join .Imports \"\\n\"}}{{\"\\n\"}}{{join .TestImports \"\\n\"}}' ./... | sort | uniq | grep -v appengine)\nfi\n\nif [[ $GOAPP == \"true\" ]]; then\n  mkdir /tmp/sdk\n  curl -o /tmp/sdk.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\"\n  unzip -q /tmp/sdk.zip -d /tmp/sdk\n  # NOTE: Set the following env vars in the test script:\n  # export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  # export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\nfi\n\n", "num_lines": 19}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\ngo version\ngo test -v google.golang.org/appengine/...\ngo test -v -race google.golang.org/appengine/...\nif [[ $GOAPP == \"true\" ]]; then\n  export PATH=\"$PATH:/tmp/sdk/go_appengine\"\n  export APPENGINE_DEV_APPSERVER=/tmp/sdk/go_appengine/dev_appserver.py\n  goapp version\n  goapp test -v google.golang.org/appengine/...\nfi\n", "num_lines": 13}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2020 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eu -o pipefail\n\nWORKDIR=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$WORKDIR\"\n}\ntrap finish EXIT\n\nexport GOBIN=${WORKDIR}/bin\nexport PATH=${GOBIN}:${PATH}\nmkdir -p ${GOBIN}\n\necho \"go install github.com/golang/protobuf/protoc-gen-go\"\n(cd test/tools && go install github.com/golang/protobuf/protoc-gen-go)\n\necho \"go install cmd/protoc-gen-go-grpc\"\n(cd cmd/protoc-gen-go-grpc && go install .)\n\necho \"git clone https://github.com/grpc/grpc-proto\"\ngit clone --quiet https://github.com/grpc/grpc-proto ${WORKDIR}/grpc-proto\n\nmkdir -p ${WORKDIR}/googleapis/google/rpc\necho \"curl https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto\"\ncurl --silent https://raw.githubusercontent.com/googleapis/googleapis/master/google/rpc/code.proto > ${WORKDIR}/googleapis/google/rpc/code.proto\n\n# Pull in the following repos to build the MeshCA config proto.\nENVOY_API_REPOS=(\n  \"https://github.com/envoyproxy/data-plane-api\"\n  \"https://github.com/cncf/udpa\"\n  \"https://github.com/envoyproxy/protoc-gen-validate\"\n)\nfor repo in ${ENVOY_API_REPOS[@]}; do\n  dirname=$(basename ${repo})\n  mkdir -p ${WORKDIR}/${dirname}\n  echo \"git clone ${repo}\"\n  git clone --quiet ${repo} ${WORKDIR}/${dirname}\ndone\n\n# Pull in the MeshCA service proto.\nmkdir -p ${WORKDIR}/istio/istio/google/security/meshca/v1\necho \"curl https://raw.githubusercontent.com/istio/istio/master/security/proto/providers/google/meshca.proto\"\ncurl --silent https://raw.githubusercontent.com/istio/istio/master/security/proto/providers/google/meshca.proto > ${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto\n\nmkdir -p ${WORKDIR}/out\n\n# Generates legacy gRPC Server symbols in addition to the newer Service symbols\nLEGACY_SOURCES=(\n  ${WORKDIR}/googleapis/google/rpc/code.proto\n  ${WORKDIR}/grpc-proto/grpc/binlog/v1/binarylog.proto\n  ${WORKDIR}/grpc-proto/grpc/channelz/v1/channelz.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/altscontext.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/handshaker.proto\n  ${WORKDIR}/grpc-proto/grpc/gcp/transport_security_common.proto\n  ${WORKDIR}/grpc-proto/grpc/health/v1/health.proto\n  ${WORKDIR}/grpc-proto/grpc/lb/v1/load_balancer.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls.proto\n  ${WORKDIR}/grpc-proto/grpc/lookup/v1/rls_config.proto\n  ${WORKDIR}/grpc-proto/grpc/service_config/service_config.proto\n  ${WORKDIR}/grpc-proto/grpc/tls/provider/meshca/experimental/config.proto\n  ${WORKDIR}/istio/istio/google/security/meshca/v1/meshca.proto\n  profiling/proto/service.proto\n  reflection/grpc_reflection_v1alpha/reflection.proto\n)\n\n# Generates only the new gRPC Service symbols\nSOURCES=(\n  $(git ls-files --exclude-standard --cached --others \"*.proto\" | grep -v '^\\(profiling/proto/service.proto\\|reflection/grpc_reflection_v1alpha/reflection.proto\\)$')\n)\n\n# These options of the form 'Mfoo.proto=bar' instruct the codegen to use an\n# import path of 'bar' in the generated code when 'foo.proto' is imported in\n# one of the sources.\nOPTS=Mgrpc/service_config/service_config.proto=/internal/proto/grpc_service_config,\\\nMenvoy/config/core/v3/config_source.proto=github.com/envoyproxy/go-control-plane/envoy/config/core/v3\n\nfor src in ${SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS}:${WORKDIR}/out --go-grpc_out=${OPTS}:${WORKDIR}/out ${src}\ndone\n\nfor src in ${LEGACY_SOURCES[@]}; do\n  echo \"protoc ${src}\"\n  protoc --go_out=${OPTS},plugins=grpc:${WORKDIR}/out --go-grpc_out=${OPTS},migration_mode=true:${WORKDIR}/out \\\n    -I\".\" \\\n    -I${WORKDIR}/grpc-proto \\\n    -I${WORKDIR}/googleapis \\\n    -I${WORKDIR}/data-plane-api \\\n    -I${WORKDIR}/udpa \\\n    -I${WORKDIR}/protoc-gen-validate \\\n    -I${WORKDIR}/istio \\\n    ${src}\ndone\n\n# The go_package option in grpc/lookup/v1/rls.proto doesn't match the\n# current location. Move it into the right place.\nmkdir -p ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\nmv ${WORKDIR}/out/google.golang.org/grpc/lookup/grpc_lookup_v1/* ${WORKDIR}/out/google.golang.org/grpc/balancer/rls/internal/proto/grpc_lookup_v1\n\n# grpc_testingv3/testv3.pb.go is not re-generated because it was\n# intentionally generated by an older version of protoc-gen-go.\nrm ${WORKDIR}/out/google.golang.org/grpc/reflection/grpc_testingv3/*.pb.go\n\n# grpc/service_config/service_config.proto does not have a go_package option.\nmv ${WORKDIR}/out/grpc/service_config/service_config.pb.go internal/proto/grpc_service_config\n\n# istio/google/security/meshca/v1/meshca.proto does not have a go_package option.\nmkdir -p ${WORKDIR}/out/google.golang.org/grpc/credentials/tls/certprovider/meshca/internal/v1/\nmv ${WORKDIR}/out/istio/google/security/meshca/v1/* ${WORKDIR}/out/google.golang.org/grpc/credentials/tls/certprovider/meshca/internal/v1/\n\ncp -R ${WORKDIR}/out/google.golang.org/grpc/* .\n", "num_lines": 127}
{"repo_name": "azapi2azurerm", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\n# not makes sure the command passed to it does not exit with a return code of 0.\nnot() {\n  # This is required instead of the earlier (! $COMMAND) because subshells and\n  # pipefail don't work the same on Darwin as in Linux.\n  ! \"$@\"\n}\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | not read\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${GOPATH}/bin:${GOROOT}/bin:${PATH}\"\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Check for module support\n  if go help mod >& /dev/null; then\n    # Install the pinned versions as defined in module tools.\n    pushd ./test/tools\n    go install \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell\n    popd\n  else\n    # Ye olde `go get` incantation.\n    # Note: this gets the latest version of all tools (vs. the pinned versions\n    # with Go modules).\n    go get -u \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell\n  fi\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.3.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif not which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\nnot git grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" -- '*.go'\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\nnot grep 'func Test[^(]' *_test.go\nnot grep 'func Test[^(]' test/*.go\n\n# - Do not import x/net/context.\nnot git grep -l 'x/net/context' -- \"*.go\"\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit grep -l '\"math/rand\"' -- \"*.go\" 2>&1 | not grep -v '^examples\\|^stress\\|grpcrand\\|^benchmark\\|wrr_test'\n\n# - Do not call grpclog directly. Use grpclog.Component instead.\ngit grep -l 'grpclog.I\\|grpclog.W\\|grpclog.E\\|grpclog.F\\|grpclog.V' -- \"*.go\" | not grep -v '^grpclog/component.go\\|^internal/grpctest/tlogger_test.go'\n\n# - Ensure all ptypes proto packages are renamed when importing.\nnot git grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\" -- \"*.go\"\n\n# - Ensure all xds proto imports are renamed to *pb or *grpc.\ngit grep '\"github.com/envoyproxy/go-control-plane/envoy' -- '*.go' ':(exclude)*.pb.go' | not grep -v 'pb \"\\|grpc \"'\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet.\ngofmt -s -d -l . 2>&1 | fail_on_output\ngoimports -l . 2>&1 | not grep -vE \"\\.pb\\.go\"\ngolint ./... 2>&1 | not grep -vE \"\\.pb\\.go:\"\ngo vet -all ./...\n\nmisspell -error .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Check that our modules are tidy.\nif go help mod >& /dev/null; then\n  find . -name 'go.mod' | xargs -IXXX bash -c 'cd $(dirname XXX); go mod tidy'\n  git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Collection of static analysis checks\n#\n# TODO(dfawley): don't use deprecated functions in examples or first-party\n# plugins.\nSC_OUT=\"$(mktemp)\"\nstaticcheck -go 1.9 -checks 'inherit,-ST1015' ./... > \"${SC_OUT}\" || true\n# Error if anything other than deprecation warnings are printed.\nnot grep -v \"is deprecated:.*SA1019\" \"${SC_OUT}\"\n# Only ignore the following deprecated types/fields/functions.\nnot grep -Fv '.CredsBundle\n.HeaderMap\n.Metadata is deprecated: use Attributes\n.NewAddress\n.NewServiceConfig\n.Type is deprecated: use Attributes\nbalancer.ErrTransientFailure\nbalancer.Picker\ngrpc.CallCustomCodec\ngrpc.Code\ngrpc.Compressor\ngrpc.CustomCodec\ngrpc.Decompressor\ngrpc.MaxMsgSize\ngrpc.MethodConfig\ngrpc.NewGZIPCompressor\ngrpc.NewGZIPDecompressor\ngrpc.RPCCompressor\ngrpc.RPCDecompressor\ngrpc.ServiceConfig\ngrpc.WithBalancerName\ngrpc.WithCompressor\ngrpc.WithDecompressor\ngrpc.WithDialer\ngrpc.WithMaxMsgSize\ngrpc.WithServiceConfig\ngrpc.WithTimeout\nhttp.CloseNotifier\ninfo.SecurityVersion\nresolver.Backend\nresolver.GRPCLB' \"${SC_OUT}\"\n\n# - special golint on package comments.\nlint_package_comment_per_package() {\n  # Number of files in this go package.\n  fileCount=$(go list -f '{{len .GoFiles}}' $1)\n  if [ ${fileCount} -eq 0 ]; then\n    return 0\n  fi\n  # Number of package errors generated by golint.\n  lintPackageCommentErrorsCount=$(golint --min_confidence 0 $1 | grep -c \"should have a package comment\")\n  # golint complains about every file that's missing the package comment. If the\n  # number of files for this package is greater than the number of errors, there's\n  # at least one file with package comment, good. Otherwise, fail.\n  if [ ${fileCount} -le ${lintPackageCommentErrorsCount} ]; then\n    echo \"Package $1 (with ${fileCount} files) is missing package comment\"\n    return 1\n  fi\n}\nlint_package_comment() {\n  set +ex\n\n  count=0\n  for i in $(go list ./...); do\n    lint_package_comment_per_package \"$i\"\n    ((count += $?))\n  done\n\n  set -ex\n  return $count\n}\nlint_package_comment\n\necho SUCCESS\n", "num_lines": 190}
{"repo_name": "azch-loadtest", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"***************************************************************************************\"\necho \"*---------------------------------BEGIN LOAD TEST-------------------------------------*\"\necho \"***************************************************************************************\"\n\nif [ -z \"$1\" ]\nthen\n  echo \"No SERVICE_ENDPOINT was passed as a parameter, assuming it is passed as environment variable\"\nelse\n  echo \"SERVICE_ENDPOINT was passed as a parameter\"\n  export SERVICE_ENDPOINT=$1\nfi\n\nexport CONTENT_TYPE=\"Content-Type: application/json\"\nexport PAYLOAD='{\"EmailAddress\": \"email@domain.com\", \"Product\": \"prod-1\", \"Total\": 100}'\nexport ENDPOINT=$SERVICE_ENDPOINT/v1/order\n\necho \"POST $ENDPOINT\"\necho $CONTENT_TYPE\necho $PAYLOAD\n\necho \"Phase 1: Warming up - 30 seconds, 100 users.\"\n./hey -z 30s -c 100 -d \"$PAYLOAD\" -H \"$CONTENT_TYPE\" -m POST \"$ENDPOINT\"\n\necho \"Waiting 15 seconds for the cluster to stabilize\"\nsleep 15\n\necho \"\\nPhase 2: Load test - 30 seconds, 400 users.\"\n./hey -z 30s -c 400 -d \"$PAYLOAD\" -H \"$CONTENT_TYPE\" -m POST \"$ENDPOINT\"\n\necho \"Waiting 15 seconds for the cluster to stabilize\"\nsleep 15\n\necho \"\\nPhase 3: Load test - 30 seconds, 1600 users.\"\n./hey -z 30s -c 1600 -d \"$PAYLOAD\" -H \"$CONTENT_TYPE\" -m POST \"$ENDPOINT\"\n\necho \"Waiting 15 seconds for the cluster to stabilize\"\nsleep 15\n\necho \"\\nPhase 4: Load test - 30 seconds, 3200 users.\"\n./hey -z 30s -c 3200 -d \"$PAYLOAD\" -H \"$CONTENT_TYPE\" -m POST \"$ENDPOINT\"\n\necho \"Waiting 15 seconds for the cluster to stabilize\"\nsleep 15\n\necho \"\\nPhase 5: Load test - 30 seconds, 6400 users.\"\n./hey -z 30s -c 6400 -d \"$PAYLOAD\" -H \"$CONTENT_TYPE\" -m POST \"$ENDPOINT\"\n\necho \"***************************************************************************************\"\necho \"*----------------------------------END LOAD TEST--------------------------------------*\"\necho \"***************************************************************************************\"", "num_lines": 52}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nurl=$1\n\nwget --quiet --output-document=img.jpg $1\nml ocr azcv img.jpg >| img_bb.txt\n\n# Add bounding boxes to the image.\n\ncat img_bb.txt |\n  cut -d',' -f1 |\n  xargs printf '-draw \"polygon %s,%s %s,%s %s,%s %s,%s\" ' |\n  awk '{print \"img.jpg -fill none -stroke red -strokewidth 5 \" $0 \"img_bb.jpg\"}' |\n  xargs convert\n\n# Add the identified text to the image.\n\ncat img_bb.txt |\n  tr ',' ' '| \n  cut -d' ' -f1,2,9- | \n  perl -pe 's|([\\d\\.]+) ([\\d\\.]+) (.+)|-annotate +\\1+\\2 \\\\\"\\3\\\\\"|' | \n  xargs | \n  awk '{print \"img_bb.jpg -stroke white -pointsize 30 \" $0 \" img_bb_text.jpg\"}' | \n  xargs convert\n\n# Create a montage of the original and final image.\n\nmontage -background '#336699' -geometry +4+4 img.jpg img_bb_text.jpg montage.jpg\n\n# Display the image.\n\neog montage.jpg\n\n# Cleanup\n\n# rm img.jpg img_bb.txt img_bb.jpg img_bb_text.jpg\n", "num_lines": 37}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# ml brands azcv gray-shirt-logo.jpg > brands_bb.txt\n\narrow_head=\"l -15,-5  +5,+5  -5,+5  +15,-5 z\"\n\nconvert -size 100x30 xc: -draw 'stroke skyblue fill skyblue rectangle 30,14 70,16' \\\n        -draw \"stroke skyblue fill skyblue path 'M 70,15  $arrow_head' \" \\\n\tarrow_horizontal.png\n\ncat brands_bb.txt |\n  cut -d',' -f1 |\n  xargs printf '-draw \"rectangle %s,%s %s,%s\" ' |\n  awk '{print \"gray-shirt-logo.jpg -fill none -stroke blue -strokewidth 3 \" $0 \"brands_tmp.png\"}' |\n  xargs convert\n\n# Combine\n\nconvert gray-shirt-logo.jpg arrow_horizontal.png brands_tmp.png -gravity Center +append -resize 70% -bordercolor White -border 10x10 brands_bb.png\n\neom brands_bb.png\n", "num_lines": 22}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nimg=$1\ndest=$2\n\naccent=\"#\"$(ml color azcv $1 | cut -d, -f2)\n\nconvert -size 100x30 xc: -draw \"stroke $accent fill $accent rectangle 30,10 90,20\" -gravity North -pointsize 10 -annotate 0 \"$accent\" \\\n\tcolor_accent.png\n\nconvert $1 color_accent.png -gravity Center +append -bordercolor White -border 10x10 $dest\n\neom $dest\n", "num_lines": 14}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# ml faces azcv faces.jpg > faces_bb.txt\n\narrow_head=\"l -15,-5  +5,+5  -5,+5  +15,-5 z\"\n\nconvert -size 100x30 xc: -draw 'stroke skyblue fill skyblue rectangle 30,14 70,16' \\\n        -draw \"stroke skyblue fill skyblue path 'M 70,15  $arrow_head' \" \\\n\tarrow_horizontal.png\n\ncat faces_bb.txt |\n  cut -d, -f1 |\n  xargs printf '-draw \"rectangle %s,%s %s,%s\" ' |\n  awk '{print \"faces.jpg -fill none -stroke blue -strokewidth 3 \" $0 \"faces_tmp.png\"}' |\n  xargs convert\n\n# Combine\n\nconvert faces.jpg arrow_horizontal.png faces_tmp.png -gravity Center +append -resize 30% -bordercolor White -border 10x10 faces_bb.png\n\neom faces_bb.png\n", "num_lines": 22}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# ml objects azcv objects.jpg > objects_bb.txt\n\narrow_head=\"l -15,-5  +5,+5  -5,+5  +15,-5 z\"\n\nconvert -size 100x30 xc: -draw 'stroke skyblue fill skyblue rectangle 30,14 70,16' \\\n        -draw \"stroke skyblue fill skyblue path 'M 70,15  $arrow_head' \" \\\n\tarrow_horizontal.png\n\ncat objects_bb.txt |\n  xargs printf '-draw \"rectangle %s,%s %s,%s\" ' |\n  awk '{print \"objects.jpg -fill none -stroke blue -strokewidth 3 \" $0 \"objects_tmp.png\"}' |\n  xargs convert\n\n# Combine\n\nconvert objects.jpg arrow_horizontal.png objects_tmp.png -gravity Center +append -resize 30% -bordercolor White -border 10x10 objects_bb.png\n\neom objects_bb.png\n", "num_lines": 21}
{"repo_name": "azcv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ \"$#\" -ne 3 ]; then\n  echo \"Three parameters are required: orig.png thumb.png dest.png\"\n  exit\nfi\n\norig=$1\nthumb=$2\ndest=$3\n\narrow_head=\"l -15,-5  +5,+5  -5,+5  +15,-5 z\"\n\nconvert -size 100x30 xc: -draw 'stroke skyblue fill skyblue rectangle 30,14 70,16' \\\n        -draw \"stroke skyblue fill skyblue path 'M 70,15  $arrow_head' \" \\\n\tarrow_horizontal.png\n\n# eom arrow_horizontal.png\n\nconvert ${orig} -resize 400x400 arrow_horizontal.png ${thumb} -gravity Center +append -resize 70% -bordercolor White -border 10x10 ${dest}\n\neom ${dest}\n", "num_lines": 23}
{"repo_name": "azfilebackup", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nrg=test-backup-vm\nvm_name=test-backup\n\naz vm update --resource-group \"${rg}\" --name \"${vm_name}\" --set \\\n    tags.InfrastructureProvider=GMPTIC \\\n    tags.bkp_storage_account=sahec99az1backup0001 \\\n    tags.Name=hec99v106014 \\\n    tags.Serial=AFD83530-840D-11E8-9E6C-FC820C452436 \\\n    tags.bkp_db_schedule=\"mo:111111111111111111111111, tu:111111111111111111111111, we:111111111111111111111111, th:111111111111111111111111, fr:111111111111111111111111, sa:111111111111111111111111, su:111111111111111111111111, min:1d, max:3d\" \\\n    tags.bkp_fs_schedule=\"mo:111111111111111111111111, tu:111111111111111111111111, we:111111111111111111111111, th:111111111111111111111111, fr:111111111111111111111111, sa:111111111111111111111111, su:111111111111111111111111, min:1d, max:3d\" \\\n    tags.bkp_log_schedule=\"mo:111111111111111111111111, tu:111111111111111111111111, we:111111111111111111111111, th:111111111111111111111111, fr:111111111111111111111111, sa:111111111111111111111111, su:111111111111111111111111, min:10m, max:30m\" \\\n    tags.db_backup_interval_max=3d \\\n    tags.db_backup_interval_min=1d \\\n", "num_lines": 16}
{"repo_name": "azhpc-diagnostics", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Azure HPC Diagnostics Tool\n# Gathers Diagnostic info from guest VM\n#\n# tarball directory structure:\n# - VM Information\n#   - dmesg.log\n#   - waagent.log\n#   - lspci.txt\n#   - lsvmbus.log\n#   - ifconfig.txt\n#   - sysctl.txt\n#   - uname.txt\n#   - dmidecode.txt\n#   - journald.log|syslog|messages\n#   - services\n#   - selinux\n#   - hyperv/kvp_pool*.txt\n# - CPU\n#   - lscpu.txt\n# - Memory\n#   - stream.txt\n#   - ulimit\n#   - zone_reclaim_mode\n# - Infiniband\n#   - ib-vmext-status\n#   - ibstat.out\n#   - ibstatus.out\n#   - ibv_devinfo.out\n#   - pkeys\n#   - ethtool.out (ENDURE)\n#   - rate (ENDURE)\n#   - state (ENDURE)\n#   - phys_state (ENDURE)\n# - Nvidia GPU\n#   - nvidia-bug-report.log.gz\n#   - nvidia-installer.log\n#   - nvidia-vmext-status\n#   - nvidia-smi.out\n#   - nvidia-smi-q.out\n#   - nvidia-smi-nvlink.out\n#   - nvidia-debugdump.zip (only Nvidia can read)\n#   - dcgm-diag-2.log\n#   - dcgm-diag-3.log\n#   - nvvs.log\n#   - stats_*.json\n#\n# Outputs:\n# - transcript of run\n# - name of tarball to stdout\n# - tarball of all logs\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n\n\n####################################################################################################\n# Begin Constants\n####################################################################################################\n\nSTREAM_URL='https://azhpcstor.blob.core.windows.net/diagtool-binaries/stream.tgz'\nLSVMBUS_URL='https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/lsvmbus'\nHPC_DIAG_URL='https://raw.githubusercontent.com/Azure/azhpc-diagnostics/main/Linux/src/gather_azhpc_vm_diagnostics.sh'\nSCRIPT_DIR=\"$( cd \"$( dirname \"$0\" )\" >/dev/null 2>&1 && pwd )\"\nSYSFS_PATH=/sys # store as a variable so it is mockable\nETC_PATH=/etc\nPROC_PATH=/proc\nVAR_PATH=/var\n\nNVIDIA_PCI_ID=10de\nGPU_PCI_CLASS_ID=0302\n\n# Mapping for stream benchmark(AMD only)\ndeclare -A CPU_LIST\nCPU_LIST=([\"Standard_HB120rs_v2\"]=\"0 1,5,9,13,17,21,25,29,33,37,41,45,49,53,57,61,65,69,73,77,81,85,89,93,97,101,105,109,113,117\"\n          [\"Standard_HB60rs\"]=\"0 1,5,9,13,17,21,25,29,33,37,41,45,49,53,57\")\nRELEASE_DATE=20220328 # update upon each release\nCOMMIT_HASH=$( \n    (\n        command -v git >/dev/null &&\n        cd \"$SCRIPT_DIR\" &&\n        git config --get remote.origin.url | grep -q 'Azure/azhpc-diagnostics.git$' &&\n        git rev-parse HEAD 2>/dev/null\n    ) || \n    echo 'Unknown')\nVERSION_INFO=\"$RELEASE_DATE-$COMMIT_HASH\"\n\nHELP_MESSAGE=\"\nUsage: $0 [OPTION]\nGather diagnostic info for the current Azure HPC VM.\nHas multiple run levels\nExports data into a tarball in the script directory.\n\nOutput control:\n -d, --dir=DIR         specify custom output location\n\nMiscellaneous:\n -V, --version         display version information and exit\n -h, --help            display this help text and exit\n\nExecution Mode:\n --gpu-level=GPU_LEVEL dcgmi run level (default is 1)\n --mem-level=MEM_LEVEL set to 1 to run stream test (default is 0)\n --no-update           do not prompt for auto-update\n --offline             skips steps that require Internet access\n\nFor more information on this script and the data it gathers, visit its Github:\n\nhttps://github.com/Azure/azhpc-diagnostics\n\"\n\n####################################################################################################\n# End Constants\n####################################################################################################\n\n####################################################################################################\n# Begin Utility Functions\n####################################################################################################\n\n\nprint_log() {\n    echo \"$@\"\n    echo \"$@\" >> \"$DIAG_DIR/transcript.log\"\n}\n\nvalidate_run_level() {\n    # test if arg is integer\n    if ! test \"$1\" -eq \"$1\" 2>/dev/null; then\n        failwith \"Invalid run level: $1. Should be integer.\"\n    fi\n}\n\nvalidate_out_dir() {\n    mkdir -p \"$1\" ||\n    failwith \"Invalid output directory: $1.\" \n}\n\nfailwith() {\n    echo \"$@\" 'Exiting'\n    exit 1\n}\n\nget_python_command() {\n    compgen -c | grep -m 1 '^python[23]$'\n}\n\nprompt() {\n    local message=\"$1\"\n    local response\n    local counter=2\n    while (( counter-- > 0 )); do\n        read -r -p \"$message [y/N]\" response\n        case \"$response\" in\n            [yY][eE][sS]|[yY]) return 0;;\n            [nN][oO]|[nN]) return 1;;\n        esac\n    done\n    return 1\n}\n\nread_binary_record() {\n    od --skip-bytes=\"$1\" --read-bytes=\"$2\" --format=c --width=1 |\n    awk '{\n        if ($2 != \"\\\\0\") {\n            printf(\"%s\",$2)\n        } else {\n            printf(\"\\n\"); exit\n        }\n    }\n    END {\n        printf(\"\\n\")\n        }'\n}\n\nis_infiniband_sku() {\n    echo \"$1\" | cut -d_ -f2 | grep -q r\n}\n\nis_endure_sku() {\n    echo \"$1\" | grep -Eiq '^Standard_(H16m?r|NC24rs?)$'\n}\n\nis_nvidia_sku() {\n    local clean\n    clean=$(echo \"$1\" | sed s/_Promo//g | tr '[:upper:]' '[:lower:]')\n\n    [[ \"$clean\" =~ ^standard_nc(6|12|24r?)$ ]] ||\n    [[ \"$clean\" =~ ^standard_nc(6|12|24r?)s_v2$ ]] ||\n    [[ \"$clean\" =~ ^standard_nc(6|12|24r?)s_v3$ ]] ||\n    \\\n    [[ \"$clean\" =~ ^standard_nc(4|8|16|64)as_t4_v3$ ]] ||\n    \\\n    [[ \"$clean\" =~ ^standard_nd(6|12|24r?)s$ ]] ||\n    [[ \"$clean\" =~ ^standard_nd40r?s_v2$ ]] ||\n    [[ \"$clean\" =~ ^standard_nd96am?sr(_a100)?_v4$ ]] ||\n    \\\n    [[ \"$clean\" =~ ^standard_nv(6|12|24)$ ]] ||\n    [[ \"$clean\" =~ ^standard_nv(6|12|24)s_v2$ ]] ||\n    [[ \"$clean\" =~ ^standard_nv(12|24|48)s_v3$ ]]\n}\n\nis_gpu_compute_sku() {\n    echo \"$1\" | cut -d_ -f1 --complement | grep -Eiq '^N(C|D)'\n}\n\nis_vis_sku() {\n    echo \"$1\" | cut -d_ -f1 --complement | grep -Eiq '^NV'\n}\n\nis_amd_gpu_sku() {\n    local clean\n    clean=$(echo \"$1\" | sed s/_Promo//g | tr '[:upper:]' '[:lower:]')\n    \n    [[ \"$clean\" =~ ^standard_nv(4|8|16|32)as_v4$ ]]\n}\n\nget_cpu_list() {\n    echo \"${CPU_LIST[$1]}\"\n}\n\nif tput cols >/dev/null 2>/dev/null && (( $(tput cols) < 80 )); then\n    COLUMNS=$(tput cols)\nelse\n    COLUMNS=80\nfi\n\nprint_enclosed() {\n    local line\n    while (( \"$#\" )); do\n        line='#'\n        while\n            line=\"$line $1\"\n            shift\n            (( \"$#\" && ${#line} + 1 + ${#1} <  \"$COLUMNS\" - 2 ))\n        do true; done\n        while (( ${#line} < \"$COLUMNS\" - 2 )); do\n            line=\"$line \"\n        done\n        echo \"$line #\"\n    done\n}\n\nprint_divider() {\n    for _ in $(seq \"$COLUMNS\"); do echo -n '#'; done\n    echo ''\n}\n\ncheck_for_updates() {\n    local message=\"You are not running the latest release of this tool. Switch to latest version?\"\n\n    local tmpfile\n    tmpfile=$(mktemp)\n    curl -s \"$HPC_DIAG_URL\" >\"$tmpfile\" || return 1\n    if ! cmp --silent \"$0\" \"$tmpfile\"; then\n        if prompt \"$message\"; then\n            mv \"$tmpfile\" \"$0\"\n            bash \"$0\" \"$RUNTIME_OPTIONS\"\n            exit $?\n        else\n            return 0\n        fi\n    fi\n    rm \"$tmpfile\"\n}\n\nget_metadata() {\n    local path=\"$1\"\n    curl -s -H Metadata:true \"http://169.254.169.254/metadata/instance/$path?api-version=2021-03-01&format=text\"\n}\n\n####################################################################################################\n# End Utility Functions\n####################################################################################################\n\n####################################################################################################\n# Begin Helper Functions\n####################################################################################################\n\nvalidate_options() {\n    if [ \"$OFFLINE\" = true ] && [ \"$MEM_LEVEL\" -gt 0 ]; then\n        echo 'Cannot run stream test in offline mode.'\n        return 1\n    else\n        return 0\n    fi\n}\n\nrun_lsvmbus_resilient() {\n    local LSVMBUS_PATH\n    local PYTHON\n\n    if command -v lsvmbus >/dev/null; then\n        print_log -e \"\\tWriting Hyper-V VMBus device list to {output}/VM/lsvmbus.log\"\n        mkdir -p \"$DIAG_DIR/VM\"\n        lsvmbus -vv >\"$DIAG_DIR/VM/lsvmbus.log\"\n    else\n        if ! PYTHON=\"$(get_python_command)\"; then\n            print_log -e '\\tNeither lsvmbus nor python detected; skipping'\n            return 1\n        elif [ \"$OFFLINE\" = true ]; then\n            print_log -e '\\tlsvmbus not installed and offline mode enabled; skipping'\n            return 1\n        else \n            print_log -e \"\\tNo lsvmbus installed; pulling a copy from Github\"\n            LSVMBUS_PATH=$(mktemp)\n            if curl -s \"$LSVMBUS_URL\" > \"$LSVMBUS_PATH\"; then\n                print_log -e \"\\tWriting Hyper-V VMBus device list to {output}/VM/lsvmbus.log\"\n                mkdir -p \"$DIAG_DIR/VM\"\n                $PYTHON \"$LSVMBUS_PATH\" -vv >\"$DIAG_DIR/VM/lsvmbus.log\"\n                rm -f \"$LSVMBUS_PATH\"\n            else\n                print_log -e '\\tFailed to download lsvmbus; skipping'\n            fi\n        fi\n    fi\n}\n\nfilter_syslog() {\n    # To avoid overcollecting, filter out messages like this\n    # Dec 31 23:59:59 hostname audit: CWD cwd=\"/\"\n    awk '!index($5,\"audit\")'\n}\n\nfetch_syslog() {\n    if systemctl is-active systemd-journald >/dev/null 2>/dev/null && command -v journalctl >/dev/null; then\n        print_log -e \"\\tDumping system logs from journald to {output}/VM/journald.log\"\n        journalctl | filter_syslog > \"$DIAG_DIR/VM/journald.log\"\n    elif [ -f /var/log/syslog ]; then\n        print_log -e \"\\tCopying sytem logs from /var/log/syslog to {output}/VM/syslog\"\n        filter_syslog </var/log/syslog >\"$DIAG_DIR/VM/syslog\"\n    elif [ -f /var/log/messages ]; then\n        print_log -e \"\\tCopying sytem logs from /var/log/messages to {output}/VM/messages\"\n        filter_syslog </var/log/messages >\"$DIAG_DIR/VM/messages\"\n    else\n        print_log -e \"\\tNo system logs found. Checked journald and /var/log/syslog|messages\"\n    fi\n}\n\nread_kvp() {\n    local filename=\"$1\"\n    local KEY_BYTELEN=512\n    local VALUE_BYTELEN=2048\n    local RECORD_BYTELEN=$(( KEY_BYTELEN + VALUE_BYTELEN ))\n    local file_len\n    file_len=$(wc --bytes \"$filename\" | cut -d' ' -f1)\n    local record_count=$(( file_len / RECORD_BYTELEN ))\n    local key value\n    for i in $(seq 0 $(( record_count - 1 ))); do\n        key=$(read_binary_record $(( RECORD_BYTELEN * i )) $KEY_BYTELEN <\"$filename\")\n        value=$(read_binary_record $(( RECORD_BYTELEN * i + KEY_BYTELEN )) $VALUE_BYTELEN <\"$filename\")\n        printf \"Key: %s; Value: %s\\n\" \"$key\" \"$value\"\n    done\n}\n\nrun_vm_diags() {\n    mkdir -p \"$DIAG_DIR/VM\"\n\n    if [ -f /var/log/waagent.log ]; then\n        print_log -e \"\\tCopying Azure VM Agent logs to {output}/VM/waagent.log\"\n        cp /var/log/waagent.log \"$DIAG_DIR/VM/waagent.log\"\n    else\n        print_log -e \"\\tCould not locate Azure VM Agent logs at /var/log/waagent.log\"\n    fi\n\n    print_log -e \"\\tWriting PCI Device List to {output}/VM/lspci.txt\"\n    lspci -vv >\"$DIAG_DIR/VM/lspci.txt\"\n\n    run_lsvmbus_resilient\n\n    print_log -e \"\\tWriting network interface list to {output}/VM/ifconfig.txt\"\n    ip -stats -human-readable address >\"$DIAG_DIR/VM/ifconfig.txt\"\n\n    print_log -e \"\\tWriting kernel parameters to {output}/VM/sysctl.txt\"\n    sysctl --all --ignore 2>/dev/null >\"$DIAG_DIR/VM/sysctl.txt\"\n\n    print_log -e \"\\tWriting system information to {output}/VM/uname.txt\"\n    uname -a >\"$DIAG_DIR/VM/uname.txt\"\n\n    print_log -e \"\\tDumping System Management BIOS table to {output}/VM/dmidecode.txt\"\n    dmidecode >\"$DIAG_DIR/VM/dmidecode.txt\"\n\n    print_log -e \"\\tWriting kernel message buffer to {output}/VM/dmesg.log\"\n    dmesg -T >\"$DIAG_DIR/VM/dmesg.log\"\n\n    print_log -e \"\\tWriting list of active kernel modules to {output}/VM/lsmod.txt\"\n    lsmod >\"$DIAG_DIR/VM/lsmod.txt\"\n\n    fetch_syslog\n\n    mkdir -p \"$DIAG_DIR/VM/hyperv\"\n    for file in \"$VAR_PATH\"/lib/hyperv/.kvp_pool*; do\n        local filename\n        filename=$(basename \"$file\" | sed 's/^\\.//g')\n        print_log -e \"\\tDumping Hyper-V KVP data from $file to {output}/VM/kvp/$filename.txt\"\n        read_kvp \"$file\" >\"$DIAG_DIR/VM/hyperv/$filename.txt\"\n    done\n    \n    local services=(iptables firewalld cpupower waagent walinuxagent)\n    if systemctl >/dev/null; then\n        for service in \"${services[@]}\"; do\n            print_log -e \"\\tWriting status of service $service {output}/VM/services\"\n            echo \"$service $(systemctl is-active \"$service\")\" >> \"$DIAG_DIR/VM/services\"\n        done\n    fi\n\n    if [ -f $ETC_PATH/sysconfig/selinux ]; then\n        print_log -e \"\\tWriting status of selinux {output}/VM/selinux\"\n        grep -V '^[[:space]]#' $ETC_PATH/sysconfig/selinux |\n        grep 'SELINUX=\\(enforcing\\|permissive\\|disabled\\)' $ETC_PATH/sysconfig/selinux |\n        head -1 >\"$DIAG_DIR/VM/selinux\"\n        [ -s \"$DIAG_DIR/VM/selinux\" ] || rm \"$DIAG_DIR/VM/selinux\"\n    fi\n}\n\nrun_cpu_diags() {\n    mkdir -p \"$DIAG_DIR/CPU\"\n\n    print_log -e \"\\tWriting CPU architecture details to {output}/CPU/lscpu.txt\"\n    lscpu >\"$DIAG_DIR/CPU/lscpu.txt\"\n}\n\nrun_stream() {\n    local STREAM_PATH=\"$DIAG_DIR/Memory/stream.tgz\"\n    local cpu_list\n    cpu_list=$(get_cpu_list \"$VM_SIZE\")\n    if [ -z \"$cpu_list\" ]; then\n        print_log -e \"\\tCurrent VM Size is not supported for stream tests. Skipping\"\n        return 1\n    fi\n\n    # Download precompiled stream library\n    print_log -e \"\\tDownloading precompiled Stream binary from Azure HPC Storage\"\n    if curl -s \"$STREAM_URL\" > \"$STREAM_PATH\"; then\n        tar xzf \"$STREAM_PATH\" -C \"$DIAG_DIR/Memory/\"\n\n        # run stream tests\n        local stream_bin=\"$DIAG_DIR/Memory/Stream/stream_zen_double\"\n        if [ -f \"$stream_bin\" ]; then\n            print_log -e \"\\tRunning Stream Benchmark and writing results to {output}/Memory/stream.txt\"\n            \"$stream_bin\" 400000000 \"$cpu_list\" > \"$DIAG_DIR/Memory/stream.txt\"\n        else\n            print_log -e \"\\tFailed to unpack stream binary to $stream_bin; unable to run stream memory tests.\"\n        fi\n\n        # Clean up\n        rm -r \"$DIAG_DIR/Memory/Stream\"\n        rm \"$DIAG_DIR/Memory/._Stream\"\n        rm \"$DIAG_DIR/Memory/stream.tgz\"\n    else\n        print_log -e \"\\tUnable to download stream memory benchmark\"\n    fi\n}\n\nrun_memory_diags() {\n    mkdir -p \"$DIAG_DIR/Memory\"\n    cp $ETC_PATH/security/limits.conf \"$DIAG_DIR/Memory\"\n    cp $PROC_PATH/sys/vm/zone_reclaim_mode \"$DIAG_DIR/Memory\"\n    if [ \"$MEM_LEVEL\" -gt 0 ]; then\n        print_log ''\n        print_log \"Running Memory Performance Test\"\n        run_stream\n    fi \n}\n\nrun_infiniband_diags() {\n    if [ -f /var/log/azure/ib-vmext-status ]; then\n        mkdir -p \"$DIAG_DIR/Infiniband\"\n        print_log -e \"\\tCopying Infiniband Driver Extension logs to {output}/Infiniband/ib-vmext-status\"\n        cp /var/log/azure/ib-vmext-status \"$DIAG_DIR/Infiniband\"\n    fi\n\n    local ib_interfaces\n    if command -v ibstatus >/dev/null; then\n        mkdir -p \"$DIAG_DIR/Infiniband\"\n\n        print_log -e \"\\tQuerying Infiniband device status, writing to {output}/Infiniband/ibstatus.out\"\n        ibstatus > \"$DIAG_DIR/Infiniband/ibstatus.out\"\n\n        ib_interfaces=$(\n            awk '\n            /Infiniband device/ { device_name=$3 }\n            /link_layer:\\s+InfiniBand/ { print device_name }' \"$DIAG_DIR/Infiniband/ibstatus.out\" | tr -d \"'\"\n        )\n        if command -v ibstat >/dev/null; then\n            print_log -e \"\\tWriting ibstat info for device(s) $(echo \"$ib_interfaces\" | xargs) to {output}/Infiniband/ibstat.out\"\n            for ib_interface in $ib_interfaces; do\n                ibstat \"$ib_interface\"\n            done >\"$DIAG_DIR/Infiniband/ibstat.out\"\n        else\n            print_log -e \"\\tibstat not found.\"\n        fi\n\n        print_log -e \"\\tWriting Infiniband device info to {output}/Infiniband/ibv_devinfo.out\"\n        ibv_devinfo -v > \"$DIAG_DIR/Infiniband/ibv_devinfo.out\" 2>&1\n    elif is_endure_sku \"$VM_SIZE\"; then\n        print_log -e \"\\tNon-SR-IOV VM size detected.\"\n        local device_paths=(\"$SYSFS_PATH\"/class/infiniband/*/ports/1)\n        if ip address show eth1 >/dev/null && [ ${#device_paths[@]} -eq 1 ] && [ -d \"${device_paths[0]}\" ]; then\n            local device_path=${device_paths[0]}\n            mkdir -p \"$DIAG_DIR/Infiniband\"\n            print_log -e \"\\tCopying $device_path/state to {output}/Infiniband/state\"\n            cp \"$device_path/state\" \"$DIAG_DIR/Infiniband\"\n            print_log -e \"\\tCopying $device_path/rate to {output}/Infiniband/rate\"\n            cp \"$device_path/rate\" \"$DIAG_DIR/Infiniband\"\n            print_log -e \"\\tCopying $device_path/phys_state to {output}/Infiniband/phys_state\"\n            cp \"$device_path/phys_state\" \"$DIAG_DIR/Infiniband\"\n            ethtool eth1 >\"$DIAG_DIR/Infiniband/ethtool.out\"\n        else\n            print_log \"ENDURE : No IB devices found\"\n        fi\n        ib_interfaces=$(basename \"$SYSFS_PATH\"/class/infiniband/*)\n    else\n        print_log -e \"\\tNo Infiniband Driver Detected\"\n    fi\n\n    print_log -e \"\\tChecking for Infiniband pkeys\"\n    for device in $ib_interfaces; do\n        local dir=\"$SYSFS_PATH/class/infiniband/$device\"\n        if ! [ -d \"$dir\" ]; then\n            print_log \"\\tDevice $device not showing up in $SYSFS_PATH/class/infiniband/\"\n        else\n            print_log -e \"\\tChecking for Infiniband pkeys in $dir\"\n        fi\n        mkdir -p \"$DIAG_DIR/Infiniband/$device/pkeys\"\n\n        local pkey_count\n        local pkey_dir=\"$SYSFS_PATH/class/infiniband/$device/ports/1/pkeys\"\n        pkey_count=$(find \"$pkey_dir/\" -maxdepth 1 -name '[0-9]*' | wc -l)\n        if [ \"$pkey_count\" -gt 0 ]; then\n            mkdir -p \"$(realpath \"$DIAG_DIR\")/Infiniband/$device/pkeys\"\n            print_log -e \"\\tFound $pkey_count pkeys in $pkey_dir; copying them to {output}/Infiniband/$device/pkeys/\"\n            cp \"$SYSFS_PATH/class/infiniband/$device/ports/1/pkeys/\"* \"$(realpath \"$DIAG_DIR\")/Infiniband/$device/pkeys\"\n        else\n            print_log -e \"\\tFound no pkeys in $dir\"\n        fi\n    done\n}\n\nis_dcgm_installed() {\n    command -v nv-hostengine >/dev/null && command -v dcgmi >/dev/null\n}\n\nreset_gpu_state() {\n    for id in $gpus_wout_persistence; do\n        print_log -e \"\\tDisabling Persistence Mode for GPU $id\"\n        nvidia-smi -i \"$id\" -pm 0 >/dev/null\n    done\n    if [ \"$nv_hostengine_already_running\" = false ]; then\n        print_log -e \"\\tTerminating nv-hostengine\"\n        nv-hostengine --term >/dev/null\n    fi\n}\n\nrun_dcgm() {\n    # because dcgmi makes files in working dir\n    pushd \"$DIAG_DIR/Nvidia\" >/dev/null || return 1\n    \n    # start hostengine, remember if it was already running\n    local discovery_output\n    discovery_output=$(dcgmi discovery -l)\n    if [ \"$?\" -eq 255 ] || echo \"$discovery_output\" | grep -iq 'Unable to connect to host engine'; then\n        nv_hostengine_already_running=true\n    else\n        nv_hostengine_already_running=false\n    fi\n\n    if [ \"$nv_hostengine_already_running\" = false ]; then\n        print_log -e \"\\tTemporarily starting nv-hostengine\"\n        nv-hostengine >/dev/null\n    fi\n\n    # enable_persistence_mode for all gpus\n    gpus_wout_persistence=$(dcgmi diag -r 1 | \n        grep -A1 'Persistence Mode.*Fail' | \n        grep -o 'GPU [[:digit:]]\\+' | \n        awk '{print $2}'\n    )\n    for id in $gpus_wout_persistence; do\n        print_log -e \"\\tTemporarily enabling Persistence Mode for GPU $id\"\n        nvidia-smi -i \"$id\" -pm 1 >/dev/null\n    done\n\n    case \"$GPU_LEVEL\" in\n    1)\n        print_log -e \"\\tRunning DCGM diagnostics Level 1 (~ < 1 min)\"\n        timeout 1m dcgmi diag -r 1 >dcgm-diag.log\n        ;;\n    2)\n        print_log -e \"\\tRunning DCGM diagnostics Level 2 (~ 2 min)\"\n        timeout 5m dcgmi diag -r 2 >dcgm-diag.log\n        ;;\n    3)\n        print_log -e \"\\tRunning DCGM diagnostics Level 3 (~ 12 min)\"\n        timeout 20m dcgmi diag -r 3 >dcgm-diag.log\n        ;;\n    *)\n        print_log -e \"\\tInvalid run-level for dcgm: $GPU_LEVEL\"\n        ;;\n    esac\n    if [ $? -eq 124 ]; then\n        print_log -e \"\\tDCGM timed out\"\n    fi\n\n    # reset state to before script ran\n    reset_gpu_state\n\n    popd >/dev/null || failwith \"Failed to popd back to working directory\"\n}\n\nis_nvidia_driver_installed() (\n    lsmod | awk '{print $1}' | grep -Eiq '^nvidia$'\n)\n\ninvestigate_nvidia_driver_installation() (\n    if [ -f /var/log/nvidia-installer.log ]; then\n        mkdir -p \"$DIAG_DIR/Nvidia\"\n        print_log -e \"\\tCopying Nvidia GPU Driver Installer logs to {output}/Nvidia/nvidia-installer.log\"\n        cp /var/log/nvidia-installer.log \"$DIAG_DIR/Nvidia\"\n    else\n        print_log -e \"\\tNo Nvidia GPU Driver Installer logs found.\"\n    fi\n)\n\nrun_nvidia_diags() {\n\n    if [ -f /var/log/azure/nvidia-vmext-status ]; then\n        mkdir -p \"$DIAG_DIR/Nvidia\"\n        print_log -e \"\\tCopying Nvidia GPU Driver Extension logs to {output}/Nvidia/nvidia-vmext-status\"\n        cp /var/log/azure/nvidia-vmext-status \"$DIAG_DIR/Nvidia\"\n    fi\n\n    if ! is_nvidia_driver_installed; then\n        print_log -e \"No NVIDIA driver found. Checking for installation logs\"\n        investigate_nvidia_driver_installation\n    elif ! command -v nvidia-smi >/dev/null; then\n        print_log -e \"NVIDIA driver is installed, but can't find nvidia-smi. Please check that it's on the PATH.\"\n    else\n        mkdir -p \"$DIAG_DIR/Nvidia\"\n        print_log -e \"\\tQuerying Nvidia GPU Info, writing to {output}/Nvidia/nvidia-smi-q.out\"\n        timeout 5m nvidia-smi -q >\"$DIAG_DIR/Nvidia/nvidia-smi-q.out\"\n        if [ $? -eq 124 ]; then\n            print_log -e \"\\tnvidia-smi -q timed out\"\n        else\n            print_log -e \"\\tRunning plain nvidia-smi, writing to {output}/Nvidia/nvidia-smi.out\"\n            timeout 5m nvidia-smi >\"$DIAG_DIR/Nvidia/nvidia-smi.out\"\n        fi\n        print_log -e \"\\tDumping Nvidia GPU internal state to {output}/Nvidia/nvidia-debugdump.zip\"\n        nvidia-debugdump --dumpall --file \"$DIAG_DIR/Nvidia/nvidia-debugdump.zip\"\n        if is_dcgm_installed; then\n            run_dcgm\n        fi\n        print_log -e \"\\tChecking nvlinks\"\n        nvidia-smi nvlink -s >\"$DIAG_DIR/Nvidia/nvlink.out\"\n    fi\n\n    if command -v nvidia-bug-report.sh >/dev/null; then\n        mkdir -p \"$DIAG_DIR/Nvidia\"\n        print_log -e \"\\tRunning nvidia-bug-report.sh and outputting to {output}/Nvidia/nvidia-bug-report.log.gz\"\n        print_log -e \"\\tIn the event of hardware failure, this log may be shared with Nvidia:\"\n        print_log -e \"$(timeout 5m nvidia-bug-report.sh --safe-mode --extra-system-data --output-file \"$DIAG_DIR/Nvidia/nvidia-bug-report.log\" | sed 's/^/\\t/')\"\n    fi\n}\n\nis_extension_running() {\n    sudo ps aux | grep -v grep | grep -m1 'nvidia-vmext.sh enable'\n}\n\nrun_amd_gpu_diags() {\n    print_log -e \"\\tNo AMD GPU diagnostics supported at this time.\"\n}\n\nfunction report_bad_gpu {\n    if ! PARSED_OPTIONS=$(getopt -n \"$0\" -o \"i\" --long \"index:,reason:,pci-domain:\"  -- \"$@\"); then\n        echo \"Illegal arguments\"\n        return 1\n    fi\n    \n    eval set -- \"$PARSED_OPTIONS\"\n    local index reason pci_domain\n    while [ \"$1\" != \"--\" ]; do\n        case \"$1\" in\n            -i|--index) index=$2;;\n            --reason) reason=$2;;\n            --pci-domain) pci_domain=$2;;\n        esac\n        shift 2\n    done\n    shift\n\n    if [ -n \"$index\" ] && [ -n \"$pci_domain\" ]; then\n        if [ \"$pci_domain\" != \"$(nvidia-smi --query-gpu=pci.domain -i \"$index\" --format=csv,noheader)\" ]; then\n            print_log -e \"\\tmismatched gpu index and pci domain passed in\"\n            return 1\n        fi\n    elif [ -n \"$index\" ]; then\n        pci_domain=$(nvidia-smi --query-gpu=pci.domain -i \"$index\" --format=csv,noheader) || {\n            print_log -e \"nvidia-smi failed during bad gpu reporting\"\n            return 1\n        }\n    elif [ -n \"$pci_domain\" ]; then\n        index=$(nvidia-smi --query-gpu=pci.domain,index --format=csv,noheader 2>/dev/null | grep -i \"^0x$pci_domain\" | cut -d' ' -f 2)\n    fi\n\n    local serial\n    [ -n \"$index\" ] &&\n        serial=$(nvidia-smi --query-gpu=serial -i \"$index\" --format=csv,noheader) || \n        serial=UNKNOWN\n\n    local device\n    local DEVICES_PATH=\"$SYSFS_PATH/bus/vmbus/devices\"\n    device=$(find -L \"$DEVICES_PATH\" -maxdepth 2 -mindepth 2 -iname \"*${pci_domain#0x}*\")\n    local bus_id\n    bus_id=$(basename \"$(dirname \"$device\")\")\n    print_log -e \"\\tBAD GPU ($reason) with bus Id $bus_id and serial number $serial\"\n}\n\nfunction check_page_retirement {\n    local remapped_rows sbe_dbe pci_domain\n    remapped_rows=$(nvidia-smi --query-remapped-rows=remapped_rows.failure,gpu_bus_id --format=csv,noheader) || {\n        print_log -e \"\\tcheck_page_retirement called, but nvidia-smi is failing\"\n        return 1\n    }\n    sbe_dbe=$(nvidia-smi --query-gpu=retired_pages.sbe,retired_pages.dbe, --format=csv,noheader) || {\n        print_log -e \"\\tcheck_page_retirement called, but nvidia-smi is failing\"\n        return 1\n    }\n    if echo \"$remapped_rows\" | grep -Eiq '\\[N/A\\]'; then\n        print_log -e \"\\tChecking for GPUs over the page retirement threshold\"\n        local i=0\n        echo \"$sbe_dbe\" | sed 's/, /\\t/g' |\n        while read -r sbe dbe; do \n            local retired_page_count=$(( sbe + dbe ))\n            if (( retired_page_count >= 60 )); then\n                report_bad_gpu --index=\"$i\" --reason=\"DBE($retired_page_count)\"\n            fi\n            ((i++))\n        done\n    else\n        print_log -e \"\\tChecking for GPUs with row remapping failures\"\n        echo \"$remapped_rows\" | sed 's/, /\\t/g' |\n        while read -r row_remap_failure pci_bus_id; do\n            if (( row_remap_failure == 1 )); then\n                pci_domain=$(echo \"$pci_bus_id\" | cut -d: -f1 | sed -E 's/^.{4}//g')\n                report_bad_gpu --pci-domain=\"$pci_domain\" --reason=\"Row Remap Failure\"\n            fi\n        done\n    fi\n}\n\nfunction check_inforom {\n    # e.g. WARNING: infoROM is corrupted at gpu 15B5:00:00.0\n    local keywords='WARNING: infoROM is corrupted at gpu'\n    local nvsmi_domains\n    nvsmi_domains=$(nvidia-smi --query-gpu=pci.domain --format=csv,noheader) || {\n        print_log -e \"\\tcheck_inforom called, but nvidia-smi is failing\"\n        return 1\n    }\n    print_log -e \"\\tChecking for GPUs with corrupted infoROM\"\n\n    grep \"$keywords\" \"$DIAG_DIR/Nvidia/nvidia-smi.out\" | while IFS= read -r warning; do\n        local pci_domain\n        pci_domain=$(echo \"$warning\" | awk '{print $NF}' | awk -F: '{print $1}')\n        local i\n        i=$(echo \"$nvsmi_domains\" | awk \"/$pci_domain/{print FNR}\")\n        ((i--)) # convert to 0-index\n        report_bad_gpu --index=\"$i\" --reason=\"infoROM Corrupted\"\n    done\n}\n\nfunction check_missing_gpus {\n    local pci_domains nvsmi_domains\n    nvsmi_domains=$(mktemp)\n    nvidia-smi --query-gpu=pci.domain --format=csv,noheader >\"$nvsmi_domains\" || {\n        print_log -e \"\\tcheck_missing_gpus called, but nvidia-smi is failing\"\n        return 1\n    }\n    pci_domains=$(lspci -d \"$NVIDIA_PCI_ID:\" -mnD | grep -E \"\\S+\\s\\\"$GPU_PCI_CLASS_ID\\\"\" | cut -d: -f1)\n    print_log -e \"\\tChecking for GPUs that don't appear in nvidia-smi\"\n    for pci_domain in $pci_domains; do\n        if ! grep -iq \"^0x$pci_domain$\" \"$nvsmi_domains\"; then\n            report_bad_gpu --pci-domain=\"$pci_domain\" --reason=\"GPU not coming up in nvidia-smi\"\n        fi\n    done\n    rm \"$nvsmi_domains\"\n}\n\nfunction check_nvlinks {\n    awk '/GPU/{i=$2} /inactive/{print i}' \"$DIAG_DIR/Nvidia/nvidia-smi-nvlink.out\" | tr -d : | uniq |\n    while read -r bad_gpu; do\n        report_bad_gpu --index $bad_gpu --reason \"NVLINK(s) inactive\"\n    done\n}\n\nfunction check_nouveau {\n    if grep -q nouveau \"$DIAG_DIR/VM/lsmod.txt\"; then\n        print_log -e '\\tNouveau driver detected. This driver is unsupported.'\n    fi\n}\n\nfunction check_pci_bandwidth {\n    print_log -e \"\\tChecking PCIe speed training for GPUs\"\n    \n    for pci_id in $(lspci -d \"$NVIDIA_PCI_ID:\" -mnD | awk '$2 == \"\\\"'\"$GPU_PCI_CLASS_ID\"'\\\"\" {print $1}'); do\n        local speed_cap width_cap speed_sta width_sta\n        speed_cap=$(lspci -vv -s \"$pci_id\" | grep 'LnkCap:' | grep -o 'Speed [0-9.]\\+GT/s' | grep -o '[0-9.]\\+')\n        speed_sta=$(lspci -vv -s \"$pci_id\" | grep 'LnkSta:' | grep -o 'Speed [0-9.]\\+GT/s' | grep -o '[0-9.]\\+')\n        width_cap=$(lspci -vv -s \"$pci_id\" | grep 'LnkCap:' | grep -o 'Width x[0-9]\\+' | grep -o '[0-9]\\+')\n        width_sta=$(lspci -vv -s \"$pci_id\" | grep 'LnkSta:' | grep -o 'Width x[0-9]\\+' | grep -o '[0-9]\\+')\n        if [ \"$speed_sta\" -ne \"$speed_cap\" ] || [ \"$width_sta\" -ne \"$width_cap\" ]; then\n            local reason=\"PCIe link not showing expected performance: OBSERVED Speed ${speed_sta}GT/s, Width x${width_sta}; EXPECTED ${speed_cap}GT/s, Width x${width_cap}\"\n            report_bad_gpu --pci-domain=\"$(echo \"$pci_id\" | cut -d: -f1)\" --reason=\"$reason\"\n        fi\n    done\n}\n\nfunction check_pkeys {\n    local device\n    for device_path in \"$DIAG_DIR\"/Infiniband/*; do\n        [ -d \"$device_path\" ] || continue\n        device=$(basename \"$device_path\")\n        for pkeyNum in {0..1}; do\n            if ! [ -s \"$DIAG_DIR/Infiniband/$device/pkeys/$pkeyNum\" ]; then\n                print_log -e \"\\tCould not find pkey $pkeyNum for device $device\"\n            fi\n        done\n    done\n}\n\nfunction check_tuning() {\n    print_log -e \"\\tChecking VM configuration against recommended settings.\"\n    if [ \"$(cat \"$DIAG_DIR/Memory/zone_reclaim_mode\")\" -ne 1 ]; then\n        print_log 'Set zone_reclaim_mode to 1'\n    fi\n\n    awk '/^\\*/{\n        switch ($3) {\n            case \"memlock\":\n                desired=\"unlimited\"\n                break\n            case \"nofile\":\n                desired=65535\n                break\n            case \"stack\":\n                desired=\"unlimited\"\n            default:\n                next\n        }\n        if ($4 != desired) {\n            printf(\"Consider setting ulimit %s to %s\\n\", $3, desired)\n        }\n    }' \"$DIAG_DIR/Memory/limits.conf\" | sort | uniq | while read -r warning; do\n        print_log -e \"\\t$warning\"\n    done\n\n    if [ -s \"$DIAG_DIR/VM/selinux\" ] && [ \"$(cut -d= -f2 \"$DIAG_DIR/VM/selinux\")\" = 'enforcing' ]; then\n        print_log -e \"\\tConsider disabling selinux to avoid interfering with MPI\"\n    fi\n}\n\n####################################################################################################\n# End Helper Functions\n####################################################################################################\n\n####################################################################################################\n# Begin Traps\n####################################################################################################\n\n\nfunction ctrl_c() {\n        echo \"** Aborting Diagnostics\"\n        echo \"** Resetting system state\"\n        reset_gpu_state\n        echo \"** Done!\"\n        \n        exit\n}\ntrap ctrl_c INT\n\n####################################################################################################\n# End Traps\n####################################################################################################\n\nfunction main {\n    print_divider\n    print_enclosed Azure HPC Diagnostics Tool\n    print_divider\n    print_enclosed \"NOTICES:\" \n    print_divider\n    print_enclosed This tool generates and bundles together various logs and diagnostic information. It, however, DOES NOT TRANSMIT any of said data. It is left to the user to choose to transmit this data to Microsoft.\n    print_divider\n    print_enclosed Some of this info, such as IP addresses, may be Personally Identifiable Information. It is up to the user to redact any sensitive info from the output 'if' necessary before sending it to Microsoft.\n    print_divider\n    print_enclosed This tool invokes various 3rd party tools 'if' they are present on the system Please review them and their EULAs at:\n    print_enclosed \"https://github.com/Azure/azhpc-diagnostics\"\n    print_divider\n    print_enclosed WARNING: THINK BEFORE YOU RUN THIS\n    print_divider\n    print_enclosed This tool runs benchmarks against system resource such as Memory and GPU. Expect it to DEGRADE PERFORMANCE 'for' or otherwise INTERFERE WITH any other processes running on this system that use such resources. It is advised that you DO NOT RUN THIS TOOL ALONGSIDE ANY OTHER JOBS on the system.\n    print_divider\n    print_enclosed Interrupt this tool at any 'time' to force it to reset system state and terminate.\n    print_divider\n    if ! prompt \"Please confirm that you understand\"; then\n        echo \"No confirmation received\"\n        echo \"Exiting\"\n        exit\n    fi\n\n    VM_SIZE=$(get_metadata compute/vmSize)\n    VM_ID=$(get_metadata compute/vmId)\n\n    IMAGE_PUBLISHER=$(get_metadata compute/storageProfile/imageReference/publisher)\n    IMAGE_OFFER=$(get_metadata compute/storageProfile/imageReference/offer)\n    IMAGE_SKU=$(get_metadata compute/storageProfile/imageReference/sku)\n    IMAGE_VERSION=$(get_metadata compute/storageProfile/imageReference/version)\n    TIMESTAMP=$(date -u +\"%F.UTC%H.%M.%S\")\n\n    echo ''\n\n    DIAG_DIR=\"$DIAG_DIR_LOC/$VM_ID.$TIMESTAMP\"\n\n    rm -r \"$DIAG_DIR\" 2>/dev/null\n    mkdir -p \"$DIAG_DIR\"\n\n    # keep a trace of this execution\n    exec 2> \"$DIAG_DIR/hpcdiag.err\"\n    set -x\n\n    print_log \"Virtual Machine Details:\"\n    print_log -e \"\\tID: $VM_ID\"\n    print_log -e \"\\tSize: $VM_SIZE\"\n    if [ \"$IMAGE_PUBLISHER\" == 'Not found' ] ||\n        [ \"$IMAGE_OFFER\" == 'Not found' ] ||\n        [ \"$IMAGE_SKU\" == 'Not found' ] ||\n        [ \"$IMAGE_VERSION\" == 'Not found' ]; then\n        print_log -e \"\\tUnrecognized (Likely Custom) OS Image\"\n    else\n        print_log -e \"\\tOS Image: $IMAGE_PUBLISHER:$IMAGE_OFFER:$IMAGE_SKU:$IMAGE_VERSION\"\n    fi\n    print_log ''\n\n    print_log 'Azure HPC Diagnostics Tool Run Details'\n    print_log -e \"\\tTool Version: $VERSION_INFO\"\n    print_log -e \"\\tStart Time: $TIMESTAMP\"\n    print_log -e \"\\tRuntime Options:\"\n    for option in $RUNTIME_OPTIONS; do\n        print_log -e \"\\t\\t$option\"\n    done\n    print_log -e \"\\tSelected Diagnostic Scenarios:\"\n    print_log -e \"\\t- General VM\"\n    print_log -e \"\\t- CPU\"\n\n    if [ \"$MEM_LEVEL\" -gt 0 ]; then\n        print_log -e \"\\t- Stream Memory Benchmark\"\n    fi\n\n    if is_infiniband_sku \"$VM_SIZE\"; then\n        print_log -e \"\\t- Infiniband\"\n    fi\n\n    if is_nvidia_sku \"$VM_SIZE\"; then\n        print_log -e \"\\t- Nvidia GPU\"\n    fi\n\n    if is_amd_gpu_sku \"$VM_SIZE\"; then\n        print_log -e \"\\t- AMD GPU\"\n    fi\n    print_log ''\n\n    print_log \"Collecting Linux VM Diagnostics\"\n    run_vm_diags\n\n    print_log ''\n    print_log \"Collecting CPU Info\"\n    run_cpu_diags\n\n    print_log ''\n    print_log \"Collecting Memory Info\"\n    run_memory_diags\n\n    if is_infiniband_sku \"$VM_SIZE\"; then\n        print_log ''\n        print_log \"Collecting Infiniband Info\"\n        run_infiniband_diags\n    fi\n\n    if is_nvidia_sku \"$VM_SIZE\"; then\n        print_log ''\n        print_log \"Running Nvidia GPU Diagnostics\"\n        run_nvidia_diags\n    fi\n\n    if is_amd_gpu_sku \"$VM_SIZE\"; then\n        print_log ''\n        print_log \"Collecting AMD GPU Info\"\n        run_amd_gpu_diags\n    fi\n\n    print_log ''\n    print_log \"End of Diagnostic Collection\"\n    print_log ''\n    print_log \"Checking for common issues\"\n\n    if is_nvidia_sku \"$VM_SIZE\" && [ -s \"$DIAG_DIR/Nvidia/nvidia-smi.out\" ]; then\n        check_inforom\n        check_page_retirement\n        check_missing_gpus\n        check_pci_bandwidth\n        check_nvlinks\n        if is_gpu_compute_sku \"$VM_SIZE\"; then\n            check_nouveau\n        fi\n    fi\n\n    if is_infiniband_sku \"$VM_SIZE\" && ! is_endure_sku \"$VM_SIZE\"; then\n        check_pkeys\n    fi\n\n    if [ \"$TUNING\" = true ]; then\n        print_log ''\n        print_log 'Checking for opportunities for performance tuning'\n        check_tuning\n    fi\n\n    print_log ''\n\n    set +x\n\n    print_divider\n    print_enclosed 'Placing diagnostic files in the following location:'\n    print_enclosed \"$DIAG_DIR.tar.gz\"\n    print_divider\n    print_enclosed If you have already opened a support request, you can take the tarball and follow this link to upload it:\n    print_enclosed 'https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade/managesupportrequest'\n    print_divider\n    tar czf \"$DIAG_DIR.tar.gz\" -C \"$DIAG_DIR_LOC\" \"$VM_ID.$TIMESTAMP\"  2>/dev/null && rm -r \"$DIAG_DIR\"\n}\n\n####################################################################################################\n# Begin Option Parsing\n####################################################################################################\n\nGPU_LEVEL=1\nMEM_LEVEL=0\nDISPLAY_HELP=false\n# should be /opt/azurehpc/diagnostics\nDIAG_DIR_LOC=\"$SCRIPT_DIR\"\n\n# save options\nRUNTIME_OPTIONS=$*\n\n# Read in options\nOPTIONS_LIST='dir:,help,gpu-level:,mem-level:,no-update,offline,tuning,version'\nif ! PARSED_OPTIONS=$(getopt -n \"$0\"  -o d:hV --long \"$OPTIONS_LIST\"  -- \"$@\"); then\n    echo \"$HELP_MESSAGE\"\n    exit 1\nfi\neval set -- \"$PARSED_OPTIONS\"\n \nwhile [ \"$1\" != \"--\" ]; do\n  case \"$1\" in\n    -d|--dir)\n        shift\n        validate_out_dir \"$1\"\n        DIAG_DIR_LOC=$(realpath \"$1\")\n        ;;\n    --gpu-level) \n        shift\n        validate_run_level \"$1\"\n        GPU_LEVEL=\"$1\"\n        ;;\n    -h|--help) DISPLAY_HELP=true;;\n    --mem-level) \n        shift\n        validate_run_level \"$1\"\n        MEM_LEVEL=\"$1\"\n        ;;\n    --no-update) DISABLE_UPDATE=true;;\n    --offline) OFFLINE=true;;\n    --tuning) TUNING=true;;\n    -V|--version) DISPLAY_VERSION=true;;\n  esac\n  shift\ndone\nshift\n\nif ! validate_options; then\n    echo \"Exiting due to invalid configuration\"\n    exit 1\nfi\n\n####################################################################################################\n# End Option Parsing\n####################################################################################################\n\nif [ \"$OFFLINE\" != true ] && [ \"$DISABLE_UPDATE\" != true ] && ! [[ $- =~ 's' ]]; then\n    check_for_updates\nfi\n\nif [ ! \"${BASH_SOURCE[0]}\" -ef \"$0\" ]; then\n    # This lets us load all functions for unit testing.\n    # We wouldn't want people sourcing this script anyway.\n    echo \"Script is being sourced. Skipping main execution.\"\nelif [ \"$DISPLAY_VERSION\" = true ]; then\n    echo \"$VERSION_INFO\"\nelif [ \"$DISPLAY_HELP\" = true ]; then\n    echo \"$HELP_MESSAGE\"\nelif [ \"$(whoami)\" != 'root' ]; then\n    failwith 'This script requires root privileges to run. Please run again with sudo'\nelif ext_process=$(is_extension_running); then\n    echo 'Detected a VM Extension installation script running in the background'\n    echo 'Please wait for it to finish and retry'\n    echo \"Extension pid: $(echo \"$ext_process\" | awk '{print $2}')\"\n    exit 1\nelse\n    main\nfi\n", "num_lines": 1117}
{"repo_name": "azhpc-diagnostics", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"$0\" )\" >/dev/null 2>&1 && pwd )\"\nPKG_ROOT=\"$(dirname \"$SCRIPT_DIR\")\"\nHPC_DIAG=\"$PKG_ROOT/src/gather_azhpc_vm_diagnostics.sh\"\n\n# BATS tests: this section should eventually absorb all tests\ngit submodule update --init # just in case, ensure BATS installation\n\"$SCRIPT_DIR/bats/bin/bats\" \"$SCRIPT_DIR\" || exit 1\n\n# these make sense as an associative array\n# but hesitant to start using bash4 features\nBASE_FILENAMES=\"\nCPU/\nCPU/lscpu.txt\nVM/\nVM/waagent.log\nVM/dmesg.log\nVM/lspci.txt\nVM/lsvmbus.log\nVM/ifconfig.txt\nVM/sysctl.txt\nVM/uname.txt\nVM/dmidecode.txt\nVM/lsmod.txt\nVM/@(syslog|messages|journald.log)\ntranscript.log\nhpcdiag.err\"\n\nNVIDIA_FILENAMES=\"Nvidia/nvidia-bug-report.log.gz\nNvidia/nvidia-smi-q.out\nNvidia/nvidia-smi.out\nNvidia/nvidia-debugdump.zip\nNvidia/nvlink.out\"\n\nNVIDIA_EXT_FILENAMES=\"Nvidia/nvidia-vmext-status\"\n\nNVIDIA_FOLDER=\"Nvidia/\"\n\nDCGM_FILENAMES=\"Nvidia/dcgm-diag.log\"\n\nMEMORY_FILENAMES=\"Memory/\nMemory/stream.txt\"\n\nINFINIBAND_FILENAMES=\"Infiniband/ibstat.out\nInfiniband/ibstatus.out\nInfiniband/ibv_devinfo.out\"\n\nINFINIBAND_EXT_FILENAMES=\"Infiniband/ib-vmext-status\"\n\nINFINIBAND_FOLDER=\"Infiniband/\"\n\n\n# Test Functions\n\nnosudo_basic_script_test(){\n    local output\n    if ! output=$(bash \"$HPC_DIAG\" --no-update \"$1\" | tee /dev/stderr); then\n        echo 'FAIL 1'\n        overall_retcode=1\n    elif [ \"$1\" = \"-h\" ] || [ \"$1\" = \"--help\" ]; then\n        if [ \"$(echo \"$output\" | wc -l)\" -le 1 ]; then\n            echo 'FAIL HELP'\n            overall_retcode=1\n            return 1\n        else\n            echo 'PASSED'\n            return 0\n        fi\n    elif [ \"$(echo \"$output\" | wc -l)\" -ne 1 ]; then\n        echo 'FAIL 2'\n        overall_retcode=1\n    else\n        echo 'PASSED'\n    fi\n}\n\nsudo_basic_script_test() {\n    local script_args=\"$1\"\n    local additional_expected=\"$2\"\n    local additional_unexpected=\"$3\"\n\n    local retval=0\n\n    local output\n    output=$(yes | sudo bash \"$HPC_DIAG\" --no-update \"$script_args\") || retval=1\n    echo \"$output\" 1>&2\n\n    local tarball\n    tarball=$(echo \"$output\" | grep -o '[^[:space:]]\\+.tar.gz')\n    if [ ! -s \"$tarball\" ]; then\n        return 1\n    fi\n\n    local filenames\n    filenames=$(tar xzvf \"$tarball\" | sed 's|^[^/]*/||g') || return 1\n\n    local expected_patterns\n    expected_patterns=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$additional_expected\") <(echo \"$additional_unexpected\") | sort | uniq -u)\n    \n    \n    pushd \"$(basename \"$tarball\" .tar.gz)\" >/dev/null || return 1\n    shopt -s extglob\n    local expected_filenames\n    for pattern in $expected_patterns; do\n        if [ -e \"$pattern\" ]; then\n            expected_filenames=$(printf '%s\\n%s\\n' \"$expected_filenames\" \"$pattern\")\n        else\n            retval=1\n            echo \"Could not find unique file for pattern $pattern\"\n        fi\n    done\n    shopt -u extglob\n    popd >/dev/null || exit 1\n\n    for filename in $filenames; do\n        if [[ \"$filename\" =~ ^Nvidia/stats_.*$ ]] ||\n           [[ \"$filename\" =~ ^Nvidia/nvvs.log$ ]] ||\n           [[ \"$filename\" =~ ^Nvidia/nvidia-installer.log$ ]] ||\n           [[ \"$filename\" =~ ^Infiniband/.* ]] ||\n           [[ \"$filename\" =~ ^VM.* ]] ||\n           [[ \"$filename\" =~ ^Memory/ ]] ||\n           [[ \"$filename\" =~ ^Memory/zone_reclaim_mode ]] ||\n           [[ \"$filename\" =~ ^Memory/limits.conf ]]; then\n            continue # leave behavior for these undefined\n        fi\n\n        if ! echo \"$expected_filenames\" | grep -q \"^$filename\\$\"; then\n            retval=1\n            echo \"Found extra file: $filename\"\n        fi\n    done\n\n    rm -rf \"$tarball\" \"$(basename \"$tarball\" .tar.gz)\"\n\n    if [ \"$retval\" -eq 0 ]; then\n        echo 'PASSED'\n    else\n        echo 'FAILED'\n    fi\n    return \"$retval\"\n}\n\n\n\n# Read in options\noptions_list='infiniband,ib-ext,nvidia,nvidia-ext,dcgm,stream'\nif ! PARSED_OPTIONS=$(getopt -n \"$0\" -o '' --long \"$options_list\"  -- \"$@\"); then\n        echo \"$HELP_MESSAGE\"\n        exit 1\nfi\neval set -- \"$PARSED_OPTIONS\"\n \nwhile [ \"$1\" != \"--\" ]; do\n  case \"$1\" in\n    --infiniband) INFINIBAND_PRESENT=true;;\n    --ib-ext) INFINIBAND_EXT_PRESENT=true;;\n    --nvidia) NVIDIA_PRESENT=true;;\n    --nvidia-ext) NVIDIA_EXT_PRESENT=true;;\n    --dcgm) DCGM_INSTALLED=true;;\n    --stream) STREAM_ENABLED=true;;\n  esac\n  shift\ndone\nshift\n\nif [ \"$INFINIBAND_PRESENT\" = true ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$INFINIBAND_FILENAMES\"))\nfi\n\nif [ \"$INFINIBAND_EXT_PRESENT\" = true ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$INFINIBAND_EXT_FILENAMES\"))\nfi\n\nif [ \"$INFINIBAND_EXT_PRESENT\" = true ] ||\n    [ \"$INFINIBAND_PRESENT\" = true ] ||\n    [ -n \"$IB_DEVICE_LIST\" ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$INFINIBAND_FOLDER\"))\nfi\n\nif [ \"$NVIDIA_EXT_PRESENT\" = true ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$NVIDIA_EXT_FILENAMES\"))\nfi\n\nif [ \"$NVIDIA_PRESENT\" = true ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$NVIDIA_FILENAMES\"))\n    if [ \"$DCGM_INSTALLED\" = true ];then\n        BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$DCGM_FILENAMES\"))\n    fi\nfi\n\nif [ \"$NVIDIA_EXT_PRESENT\" = true ] || [ \"$NVIDIA_PRESENT\" = true ];then\n    BASE_FILENAMES=$(cat <(echo \"$BASE_FILENAMES\") <(echo \"$NVIDIA_FOLDER\"))\nfi\n\noverall_retcode=0\n\n# zero-output runs\necho 'Testing without sudo'\nif [ \"$(whoami)\" = root ]; then\n    user=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 8)\n    while compgen -u | grep \"$user\"; do\n        user=$(tr -dc A-Za-z0-9 </dev/urandom | head -c 8)\n    done\n    useradd --system --no-create-home \"$user\"\n    tmp=$(mktemp)\n    cp \"$HPC_DIAG\" \"$tmp\"\n    chmod 777 \"$tmp\"\n    output=$(sudo -u \"$user\" bash \"$tmp\" --no-update)\n    retcode=$?\n    rm \"$tmp\"\n    userdel \"$user\"\nelse\n    output=$(bash \"$HPC_DIAG\" --no-update)\n    retcode=$?\nfi\nif [ $retcode -eq 0 ]; then\n    echo 'FAILED'\n    overall_retcode=1\nelse\n    echo 'PASSED'\nfi\n\nHPC_DIAG_URL='https://raw.githubusercontent.com/Azure/azhpc-diagnostics/main/Linux/src/gather_azhpc_vm_diagnostics.sh'\nmain=$(mktemp)\ncurl -s \"$HPC_DIAG_URL\" > \"$main\"\ncorrupted=$(mktemp)\nsed <\"$HPC_DIAG\" '/VERSION_INFO=/c VERSION_INFO=dummy' >\"$corrupted\"\necho 'Testing auto-update'\nif [ \"$(yes | bash \"$corrupted\" --version)\" != \"$(bash \"$main\" --version)\" ]; then\n    echo 'FAILED'\n    overall_retcode=1\nelse\n    echo 'PASSED'\nfi\n\nsed <\"$HPC_DIAG\" '/VERSION_INFO=/c VERSION_INFO=dummy' >\"$tmp\"\necho 'Testing auto-update disablement'\nif [ \"$(yes | bash \"$tmp\" --version --no-update)\" != 'dummy' ]; then\n    echo 'FAILED'\n    overall_retcode=1\nelse\n    echo 'PASSED'\nfi\n\necho 'Testing with -V'\nnosudo_basic_script_test -V\n\necho 'Testing with --version'\nnosudo_basic_script_test --version\n\necho 'Testing with -h'\nnosudo_basic_script_test -h\n\necho 'Testing with --help'\nnosudo_basic_script_test --help\n\nMETADATA_URL='http://169.254.169.254/metadata/instance?api-version=2020-06-01'\nif ! curl -s -H Metadata:true --connect-timeout 1 \"$METADATA_URL\"; then \n    echo \"Couldn't connect to Azure IMDS. Cutting tests short.\"\n    exit 1\nfi\n\n# base version\necho 'Testing with sudo'\necho 'Testing with no options'\nsudo_basic_script_test || overall_retcode=1\n\n# raised mem level\necho 'Testing with --mem-level=1'\nif [ \"$STREAM_ENABLED\" = true ];then\n    sudo_basic_script_test --mem-level=1 \"$MEMORY_FILENAMES\" || overall_retcode=1\nelse\n    sudo_basic_script_test --mem-level=1 || overall_retcode=1\nfi\n\necho 'Testing with invalid arguments'\nif yes | sudo bash \"$HPC_DIAG\" --mem-level=1 --offline 1>&2; then\n    echo 'FAILED'\n    overall_retcode=1\nelse\n    echo 'PASSED'\nfi\n\n# raised gpu-level\necho 'Testing with --gpu-level=3'\nsudo_basic_script_test --gpu-level=3 || overall_retcode=1\n\nexit $overall_retcode", "num_lines": 291}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# Install NCCL\n./install_nccl.sh\n\n# Install NVIDIA docker container\n$COMMON_DIR/../alma/alma-8.x/common/install_docker.sh\n\n# Install DCGM\n./install_dcgm.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# add udev rule\n$COMMON_DIR/../alma/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../alma/common/network-config.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n#install monitoring tools\n$COMMON_DIR/../alma/common/install_monitoring_tools.sh\n\n# install AMD libs\n$COMMON_DIR/../alma/common/install_amd_libs.sh\n\n# install Azure/NHC Health Checks\n$COMMON_DIR/install_health_checks.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# disable cloud-init\n$ALMA_COMMON_DIR/disable_cloudinit.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 73}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../alma/alma-8.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install DCGM\nDCGM_VERSION=2.4.4\nDCGM_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\n$COMMON_DIR/download_and_verify.sh $DCGM_URL \"1d8fbe97797fada8048a7832bfac4bc7d3ad661bb24163d21324965ae7e7817d\"\nrpm -i datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\nsed -i \"$ s/$/ datacenter-gpu-manager/\" /etc/dnf/dnf.conf\nrm -f datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\n$COMMON_DIR/write_component_version.sh \"DCGM\" ${DCGM_VERSION}\n\n# Create service for dcgm to launch on bootup\nbash -c \"cat > /etc/systemd/system/dcgm.service\" <<'EOF'\n[Unit]\nDescription=DCGM service\n\n[Service]\nUser=root\nPrivateTmp=false\nExecStart=/usr/bin/nv-hostengine -n\nRestart=on-abort\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable dcgm\nsystemctl start dcgm\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$ALMA_COMMON_DIR/install_intel_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.8-1.0.1.1\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel8.6-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"f340317047cc815b0f41c3f3c52d2d83ddc7d81b29d9fff91abb859850f77945\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update --distro rhel8.6\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# exclude opensm from updates\nsed -i \"$ s/$/ opensm*/\" /etc/dnf/dnf.conf\n\n# cleanup downloaded files\nrm -rf *.tgz\nrm -rf -- */\n", "num_lines": 29}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.14\nHPCX_VERSION=\"v2.14\"\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc-MLNX_OFED_LINUX-5-redhat8-cuda11-gdrcopy2-nccl2.16-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"126d7dfd71a8e7095baea200c8be9ff9318ee41018fbef9ec6733a54023d6c60\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\n\n# exclude ucx from updates\nsed -i \"$ s/$/ ucx*/\" /etc/dnf/dnf.conf\n\n# Install platform independent MPIs\nHCOLL_PATH=${HPCX_PATH}/hcoll\nUCX_PATH=${HPCX_PATH}/ucx\n\n# MVAPICH2 2.3.7\nMV2_VERSION=\"2.3.7\"\nMV2_DOWNLOAD_URL=http://mvapich.cse.ohio-state.edu/download/mvapich/mv2/mvapich2-${MV2_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $MV2_DOWNLOAD_URL \"c39a4492f4be50df6100785748ba2894e23ce450a94128181d516da5757751ae\"\ntar -xvf mvapich2-${MV2_VERSION}.tar.gz\ncd mvapich2-${MV2_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/mvapich2-${MV2_VERSION} --enable-g=none --enable-fast=yes && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\n\n# OpenMPI 4.1.3\nOMPI_VERSION=\"4.1.3\"\nOMPI_DOWNLOAD_URL=https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-${OMPI_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $OMPI_DOWNLOAD_URL \"9c0fd1f78fc90ca9b69ae4ab704687d5544220005ccd7678bf58cc13135e67e0\"\ntar -xvf openmpi-${OMPI_VERSION}.tar.gz\ncd openmpi-${OMPI_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/openmpi-${OMPI_VERSION} --with-ucx=${UCX_PATH} --with-hcoll=${HCOLL_PATH} --enable-mpirun-prefix-by-default --with-platform=contrib/platform/mellanox/optimized && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\n\n# exclude openmpi, perftest from updates\nsed -i \"$ s/$/ openmpi perftest/\" /etc/dnf/dnf.conf\n\n# Intel MPI 2021 (Update 7)\nIMPI_2021_VERSION=\"2021.7.0\"\nIMPI_2021_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/irc_nas/18926/l_mpi_oneapi_p_${IMPI_2021_VERSION}.8711_offline.sh\n$COMMON_DIR/download_and_verify.sh $IMPI_2021_DOWNLOAD_URL \"4eb1e1487b67b98857bc9b7b37bcac4998e0aa6d1b892b2c87b003bf84fb38e9\"\nbash l_mpi_oneapi_p_${IMPI_2021_VERSION}.8711_offline.sh -s -a -s --eula accept\nmv ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/mpi ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\n$COMMON_DIR/write_component_version.sh \"IMPI_2021\" ${IMPI_2021_VERSION}\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# MVAPICH2\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION}\n#%Module 1.0\n#\n#  MVAPICH2 ${MV2_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/mvapich2-${MV2_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/mvapich2-${MV2_VERSION}/lib\nprepend-path    MANPATH         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_BIN         /opt/mvapich2-${MV2_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/mvapich2-${MV2_VERSION}/include\nsetenv          MPI_LIB         /opt/mvapich2-${MV2_VERSION}/lib\nsetenv          MPI_MAN         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_HOME        /opt/mvapich2-${MV2_VERSION}\nEOF\n\n# OpenMPI\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION}\n#%Module 1.0\n#\n#  OpenMPI ${OMPI_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/openmpi-${OMPI_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/openmpi-${OMPI_VERSION}/lib\nprepend-path    MANPATH         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_BIN         /opt/openmpi-${OMPI_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/openmpi-${OMPI_VERSION}/include\nsetenv          MPI_LIB         /opt/openmpi-${OMPI_VERSION}/lib\nsetenv          MPI_MAN         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_HOME        /opt/openmpi-${OMPI_VERSION}\nEOF\n\n#IntelMPI-v2021\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_2021_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\nsetenv          MPI_BIN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/include\nsetenv          MPI_LIB         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/lib\nsetenv          MPI_MAN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\nln -s /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION} /usr/share/Modules/modulefiles/mpi/mvapich2\nln -s /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION} /usr/share/Modules/modulefiles/mpi/openmpi\nln -s /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION} /usr/share/Modules/modulefiles/mpi/impi-2021\n\n# cleanup downloaded tarball for HPC-x\nrm -rf *.tar.gz *offline.sh *.tbz\nrm -rf -- */\n", "num_lines": 137}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$ALMA_COMMON_DIR/install_nccl.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../alma/alma-8.x/common/install_nvidiagpudriver.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/rhel/8/prod.repo > ./microsoft-prod.repo\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.repo /etc/yum.repos.d/\n\nyum repolist\n\n../common/install_utils.sh\n\n", "num_lines": 14}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport ALMA_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install Lustre client\n$ALMA_COMMON_DIR/install_lustre_client.sh \"8\"\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# cleanup downloaded tarballs - clear some space\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\nrm -rf /tmp/MLNX_OFED_LINUX* /tmp/*conf*\nrm -rf /var/intel/ /var/cache/*\nrm -Rf -- */\n\n# Install NCCL\n./install_nccl.sh\n\n# Install NVIDIA docker container\n$COMMON_DIR/../alma/alma-8.x/common/install_docker.sh\n\n# Install DCGM\n./install_dcgm.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# add udev rule\n$COMMON_DIR/../alma/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../alma/common/network-config.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n#install monitoring tools\n$COMMON_DIR/../alma/common/install_monitoring_tools.sh\n\n# install Azure/NHC Health Checks\n$COMMON_DIR/install_health_checks.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# disable cloud-init\n$ALMA_COMMON_DIR/disable_cloudinit.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 79}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../alma/alma-8.x/common/install_amd_libs.sh\n$ALMA_COMMON_DIR/install_amd_libs.sh\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../alma/alma-8.x/common/install_dcgm.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$ALMA_COMMON_DIR/install_intel_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nDISTRIB_CODENAME=el8\nLUSTRE_VERSION=2.15.1_24_g98d1cac\nREPO_PATH=/etc/yum.repos.d/amlfs.repo\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\necho -e \"[amlfs]\" > ${REPO_PATH}\necho -e \"name=Azure Lustre Packages\" >> ${REPO_PATH}\necho -e \"baseurl=https://packages.microsoft.com/yumrepos/amlfs-${DISTRIB_CODENAME}\" >> ${REPO_PATH}\necho -e \"enabled=1\" >> ${REPO_PATH}\necho -e \"gpgcheck=1\" >> ${REPO_PATH}\necho -e \"gpgkey=https://packages.microsoft.com/keys/microsoft.asc\" >> ${REPO_PATH}\necho -e \"exclude=lustre-client-dkms*\" >> ${REPO_PATH}\n\ndnf install -y kmod-lustre-client-$(uname -r)-${LUSTRE_VERSION}-1.${DISTRIB_CODENAME}.x86_64.rpm lustre-client-${LUSTRE_VERSION}-1.${DISTRIB_CODENAME}.x86_64.rpm\n\n$COMMON_DIR/write_component_version.sh \"LUSTRE\" ${LUSTRE_VERSION}\n", "num_lines": 21}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"23.04-0.5.3.3\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel8.7-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"1b9edbce2c30e62a5bcb5de087411532048b0987fadc62297af3cf9c2c45f444\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update --distro rhel8.7\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# exclude opensm from updates\nsed -i \"$ s/$/ opensm*/\" /etc/dnf/dnf.conf\n\n# cleanup downloaded files\nrm -rf *.tgz\nrm -rf -- */\n", "num_lines": 29}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.15\nHPCX_VERSION=\"v2.15\"\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc-MLNX_OFED_LINUX-5-redhat8-cuda12-gdrcopy2-nccl2.17-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"0ca27ef0d6fa3d6be176f461977875030bc8cc130a784e216b1c23259c733e41\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\n\n# exclude ucx from updates\nsed -i \"$ s/$/ ucx*/\" /etc/dnf/dnf.conf\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n$ALMA_COMMON_DIR/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n\n# cleanup downloaded tarball for HPC-x\nrm -rf *.tbz \n", "num_lines": 50}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$ALMA_COMMON_DIR/install_nccl.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../alma/alma-8.x/common/install_nvidiagpudriver.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/rhel/8/prod.repo > ./microsoft-prod.repo\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.repo /etc/yum.repos.d/\n\nyum repolist\n\n../common/install_utils.sh\n", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport ALMA_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable wpa_supplicant\nsystemctl disable abrtd\n\n../../common/hpc-tuning.sh\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nINSTALL_PREFIX=/opt/amd\nmkdir -p ${INSTALL_PREFIX}\n\nAOCL_VERSION=\"4.0\"\nTARBALL=\"aocl-linux-aocc-${AOCL_VERSION}.tar.gz\"\nAOCL_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\n$COMMON_DIR/download_and_verify.sh $AOCL_DOWNLOAD_URL \"c8000a66aaa2a257252cbb307732b4e66758b72b08f43b3723f4eb5404ba28c8\"\ntar -xvf ${TARBALL}\n\npushd aocl-linux-aocc-${AOCL_VERSION}\n./install.sh -t amd -l blis fftw libflame -i lp64\ncp -r amd/${AOCL_VERSION}/* ${INSTALL_PREFIX}\npopd\n\n# Setup module files for AMD Libraries\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles/amd\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n# fftw\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/aocl-${AOCL_VERSION}\n#%Module 1.0\n#\n#  AOCL\n#\nprepend-path    LD_LIBRARY_PATH   ${INSTALL_PREFIX}/lib\nsetenv          AMD_FFTW_INCLUDE  ${INSTALL_PREFIX}/include\nEOF\n\n# Create symlinks for modulefiles\nln -s ${MODULE_FILES_DIRECTORY}/aocl-${AOCL_VERSION} ${MODULE_FILES_DIRECTORY}/aocl\n$COMMON_DIR/write_component_version.sh \"AOCL\" ${AOCL_VERSION}\n\n# cleanup downloaded files\nrm -rf *tar.gz\n", "num_lines": 38}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install DCGM\n# Reference: https://developer.nvidia.com/dcgm#Downloads\n# the repo is already added during nvidia/ cuda installations\nDCGM_VERSION=3.1.8\ndnf clean expire-cache\ndnf install -y datacenter-gpu-manager-1:${DCGM_VERSION}\n$COMMON_DIR/write_component_version.sh \"DCGM\" ${DCGM_VERSION}\n\n# Enable the dcgm service\nsystemctl --now enable nvidia-dcgm\nsystemctl start nvidia-dcgm\n# Check if the service is active\nsystemctl is-active --quiet nvidia-dcgm\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"DCGM is inactive!\"\n    exit ${error_code}\nfi\n", "num_lines": 23}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Moby Engine + CLI\nyum install -y moby-engine\nyum install -y moby-cli\n\n# Install NVIDIA Docker\n# Reference: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html\n# Setting up NVIDIA Container Toolkit\ncase ${DISTRIBUTION} in\n    \"almalinux8.6\") distribution=\"rhel8.6\"\n        ;;\n    \"almalinux8.7\") distribution=\"rhel8.7\";\n        ;;\n    *) ;;\nesac\n\ncurl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | tee /etc/yum.repos.d/nvidia-docker.repo\n# MIG Capability on A100\n# curl -s -L https://nvidia.github.io/nvidia-container-runtime/experimental/$distribution/nvidia-container-runtime.list | tee /etc/yum.repos.d/nvidia-container-runtime.list\n\nyum clean expire-cache\n# Install nvidia-docker package\n# Install NVIDIA container toolkit and mark NVIDIA packages on hold\nyum install -y nvidia-container-toolkit\n\n# Install NVIDIA container runtime and mark NVIDIA packages on hold\nyum install -y nvidia-container-runtime\n# Mark the installed packages on hold to disable updates\nsed -i \"$ s/$/ *nvidia-container*/\" /etc/dnf/dnf.conf\n\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/nvidia-docker\ncp nvidia-docker /bin/\nchmod +x /bin/nvidia-docker\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/daemon.json\ncp daemon.json /etc/docker/\n\n# Working setup can be tested by running a base CUDA container\n# nvidia-docker run -e NVIDIA_VISIBLE_DEVICES=all nvidia/cuda:11.0-base nvidia-smi\n\n# disabling aufs, btrfs, zfs and devmapper snapshotter plugins\nmkdir -p /etc/containerd\ncat << EOF | tee -a /etc/containerd/config.toml\ndisabled_plugins = [\"cri\", \"zfs\", \"aufs\", \"btrfs\", \"devmapper\"]\nEOF\n\n# restart containerd service\nsystemctl restart containerd\n\n# status of containerd snapshotter plugins\nctr plugin ls\n\n# enable and restart the docker daemon to complete the installation\nsystemctl enable docker\nsystemctl restart docker\n\n# Write the docker version to components file\ndocker_version=$(nvidia-docker --version | awk -F' ' '{print $3}')\n$COMMON_DIR/write_component_version.sh \"NVIDIA-DOCKER\" ${docker_version::-1}\n\n# Clean repos\nrm -rf /etc/yum.repos.d/nvidia-*\nrm -rf /var/cache/yum/x86_64/8/nvidia-*\nrm -rf /var/cache/yum/x86_64/8/libnvidia-container/\n", "num_lines": 66}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nGCC_VERSION=$1\nHPCX_PATH=$2\n\nHCOLL_PATH=${HPCX_PATH}/hcoll\nUCX_PATH=${HPCX_PATH}/ucx\nINSTALL_PREFIX=/opt\n\n# Load gcc\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n# Intel MPI 2018 (update 4)\nIMPI_VERSION=\"2018.4.274\"\n$COMMON_DIR/write_component_version.sh \"IMPI_2018\" ${IMPI_VERSION}\nIMPI_2018_DOWNLOAD_URL=http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/13651/l_mpi_${IMPI_VERSION}.tgz\n$COMMON_DIR/download_and_verify.sh $IMPI_2018_DOWNLOAD_URL \"a1114b3eb4149c2f108964b83cad02150d619e50032059d119ac4ffc9d5dd8e0\"\ntar -xvf l_mpi_${IMPI_VERSION}.tgz\ncd l_mpi_${IMPI_VERSION}\n# Update the silent.cfg file to proceed with installation\nsed -i -e 's/ACCEPT_EULA=decline/ACCEPT_EULA=accept/g' silent.cfg\n./install.sh --silent ./silent.cfg\ncd ..\n\n#IntelMPI-v2018\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/impi_${IMPI_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/impi/${IMPI_VERSION}/intel64/modulefiles/mpi\nsetenv          MPI_BIN         /opt/intel/impi/${IMPI_VERSION}/intel64/bin\nsetenv          MPI_INCLUDE     /opt/intel/impi/${IMPI_VERSION}/intel64/include\nsetenv          MPI_LIB         /opt/intel/impi/${IMPI_VERSION}/intel64/lib\nsetenv          MPI_MAN         /opt/intel/impi/${IMPI_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/impi/${IMPI_VERSION}/intel64\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/impi_${IMPI_VERSION} /usr/share/Modules/modulefiles/mpi/impi\n\n../../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n", "num_lines": 48}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\ncase ${DISTRIBUTION} in\n    \"almalinux8.6\") NVIDIA_VERSION=\"510.85.02\"; \n        CUDA_VERSION=\"11-6\"; \n        CUDA_SAMPLES_VERSION=\"11.6\";\n        NVIDIA_DRIVER_CHECKSUM=\"372427e633f32cff6dd76020e8ed471ef825d38878bd9655308b6efea1051090\";\n        NVIDIA_FABRIC_MANAGER_VERSION=\"510.85.02-1\";\n        NVIDIA_FABRIC_MANAGER_CHECKSUM=\"7f8468e92deb78e427df8b4947c4b0fd7a7b5eedf1e3961e60436b4620b2fa1d\";\n        ;;\n    \"almalinux8.7\") NVIDIA_VERSION=\"525.105.17\"; \n        CUDA_VERSION=\"12-1\"; \n        CUDA_SAMPLES_VERSION=\"12.1\";\n        NVIDIA_DRIVER_CHECKSUM=\"c635a21a282c9b53485f19ebb64a0f4b536a968b94d4d97629e0bc547a58142a\";\n        NVIDIA_FABRIC_MANAGER_VERSION=\"525.105.17-1\";\n        NVIDIA_FABRIC_MANAGER_CHECKSUM=\"4d6a11cbaa2aa278ef3fc9818c77f0f9fdf10e54d0d15b607b5beaae90b119ec\";\n        ;;\n    *) ;;\nesac\n\n# Install Cuda\ndnf config-manager --add-repo https://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/cuda-rhel8.repo\ndnf clean expire-cache\ndnf install cuda-toolkit-${CUDA_VERSION} -y\necho 'export PATH=$PATH:/usr/local/cuda/bin' | tee -a /etc/bash.bashrc\necho 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64' | tee -a /etc/bash.bashrc\n$COMMON_DIR/write_component_version.sh \"CUDA\" ${CUDA_VERSION}\n\n# Download CUDA samples\nTARBALL=\"v${CUDA_SAMPLES_VERSION}.tar.gz\"\nCUDA_SAMPLES_DOWNLOAD_URL=https://github.com/NVIDIA/cuda-samples/archive/refs/tags/${TARBALL}\nwget ${CUDA_SAMPLES_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\npushd ./cuda-samples-${CUDA_SAMPLES_VERSION}\nmake -j $(nproc)\nmv -vT ./Samples /usr/local/cuda-${CUDA_SAMPLES_VERSION}/samples\npopd\n\n# Nvidia driver\nNVIDIA_DRIVER_URL=https://us.download.nvidia.com/tesla/${NVIDIA_VERSION}/NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run\n$COMMON_DIR/download_and_verify.sh $NVIDIA_DRIVER_URL ${NVIDIA_DRIVER_CHECKSUM}\nbash NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run --silent --dkms\ndkms install --no-depmod -m nvidia -v ${NVIDIA_VERSION} -k `uname -r` --force\n$COMMON_DIR/write_component_version.sh \"NVIDIA\" ${NVIDIA_VERSION}\n\n# load the nvidia-peermem coming as a part of NVIDIA GPU driver\n# Reference - https://download.nvidia.com/XFree86/Linux-x86_64/510.85.02/README/nvidia-peermem.html\nmodprobe nvidia-peermem\n# verify if loaded\nlsmod | grep nvidia_peermem\n\n# Install GDRCopy\nGDRCOPY_VERSION=\"2.3\"\nTARBALL=\"v${GDRCOPY_VERSION}.tar.gz\"\nGDRCOPY_DOWNLOAD_URL=https://github.com/NVIDIA/gdrcopy/archive/refs/tags/${TARBALL}\nwget $GDRCOPY_DOWNLOAD_URL\ntar -xvf $TARBALL\n\npushd gdrcopy-${GDRCOPY_VERSION}/packages/\nCUDA=/usr/local/cuda ./build-rpm-packages.sh\nrpm -Uvh gdrcopy-kmod-${GDRCOPY_VERSION}-1dkms.noarch.el8.rpm\nrpm -Uvh gdrcopy-${GDRCOPY_VERSION}-1.x86_64.el8.rpm\nrpm -Uvh gdrcopy-devel-${GDRCOPY_VERSION}-1.noarch.el8.rpm\nsed -i \"$ s/$/ gdrcopy*/\" /etc/dnf/dnf.conf\npopd\n\n$COMMON_DIR/write_component_version.sh \"GDRCOPY\" ${GDRCOPY_VERSION}\n\n# Install Fabric Manager\nNVIDIA_FABRIC_MNGR_URL=http://developer.download.nvidia.com/compute/cuda/repos/rhel8/x86_64/nvidia-fabric-manager-${NVIDIA_FABRIC_MANAGER_VERSION}.x86_64.rpm\n$COMMON_DIR/download_and_verify.sh ${NVIDIA_FABRIC_MNGR_URL} ${NVIDIA_FABRIC_MANAGER_CHECKSUM}\nyum install -y ./nvidia-fabric-manager-${NVIDIA_FABRIC_MANAGER_VERSION}.x86_64.rpm\nsed -i \"$ s/$/ nvidia-fabric-manager/\" /etc/dnf/dnf.conf\n$COMMON_DIR/write_component_version.sh \"NVIDIA_FABRIC_MANAGER\" ${NVIDIA_FABRIC_MANAGER_VERSION}\n\n# cleanup downloaded files\nrm -rf *.run *tar.gz *.rpm\nrm -rf -- */\n", "num_lines": 80}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Kernel dependencies\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nyum install -y https://repo.almalinux.org/almalinux/8.7/BaseOS/x86_64/os/Packages/kernel-devel-${KERNEL}.rpm \\\n    https://repo.almalinux.org/almalinux/8.7/BaseOS/x86_64/os/Packages/kernel-headers-${KERNEL}.rpm \\\n    https://repo.almalinux.org/almalinux/8.7/BaseOS/x86_64/os/Packages/kernel-modules-extra-${KERNEL}.rpm\n\n# Install Python 3.8\nyum install -y python3.8\nln -fs /usr/bin/python3.8 /usr/bin/python3\n\n# install pssh\nPSSH_VER=2.3.1-29\nwget https://dl.fedoraproject.org/pub/epel/8/Everything/aarch64/Packages/p/pssh-$PSSH_VER.el8.noarch.rpm\nyum install -y  pssh-$PSSH_VER.el8.noarch.rpm\nrm -f pssh-$PSSH_VER.el8.noarch.rpm\n\n# Install pre-reqs and development tools\nyum groupinstall -y \"Development Tools\"\nyum install -y numactl \\\n    numactl-devel \\\n    libxml2-devel \\\n    byacc \\\n    environment-modules \\\n    python3-devel \\\n    python3-setuptools \\\n    gtk2 \\\n    atk \\\n    cairo \\\n    tcl \\\n    tk \\\n    m4 \\\n    glibc-devel \\\n    libudev-devel \\\n    binutils \\\n    binutils-devel \\\n    selinux-policy-devel \\\n    nfs-utils \\\n    fuse-libs \\\n    libpciaccess \\\n    cmake \\\n    libnl3-devel \\\n    libsecret \\\n    rpm-build \\\n    make \\\n    check \\\n    check-devel \\\n    lsof \\\n    kernel-rpm-macros \\\n    tcsh \\\n    gcc-gfortran \\\n    perl\n\n## Disable kernel updates\necho \"exclude=kernel* kmod*\" | tee -a /etc/dnf/dnf.conf\n\n# Disable dependencies on kernel core\nsed -i \"$ s/$/ shim*/\" /etc/dnf/dnf.conf\nsed -i \"$ s/$/ grub2*/\" /etc/dnf/dnf.conf\n\n## Install dkms from the EPEL repository\nwget -r --no-parent -A \"dkms-*.el8.noarch.rpm\" https://dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/d/\nyum localinstall ./dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/d/dkms-*.el8.noarch.rpm -y\n\n## Install subunit and subunit-devel from EPEL repository\nwget -r --no-parent -A \"subunit-*.el8.x86_64.rpm\" https://dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/s/\nyum localinstall ./dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/s/subunit-[0-9].*.el8.x86_64.rpm -y\nyum localinstall ./dl.fedoraproject.org/pub/epel/8/Everything/x86_64/Packages/s/subunit-devel-[0-9].*.el8.x86_64.rpm -y\n\n# Download jq utility\nwget -r --no-parent -A \"jq-*.el8.x86_64.rpm\" https://repo.almalinux.org/almalinux/8/AppStream/x86_64/os/Packages/\nyum localinstall ./repo.almalinux.org/almalinux/8/AppStream/x86_64/os/Packages/jq-*.el8.x86_64.rpm -y\n\n# Remove rpm files\nrm -rf ./dl.fedoraproject.org/\nrm -rf ./repo.almalinux.org/\n\n# Install azcopy tool \n# To copy blobs or files to or from a storage account.\nVERSION=\"10.17.0\"\nRELEASE_TAG=\"release20230123\"\nTARBALL=\"azcopy_linux_amd64_${VERSION}.tar.gz\"\nAZCOPY_DOWNLOAD_URL=\"https://azcopyvnext.azureedge.net/${RELEASE_TAG}/${TARBALL}\"\nAZCOPY_FOLDER=$(basename ${AZCOPY_DOWNLOAD_URL} .tgz)\nwget ${AZCOPY_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\n# copy the azcopy to the bin path\npushd azcopy_linux_amd64_${VERSION}\ncp azcopy /usr/bin/\npopd\n\n# Allow execute permissions\nchmod +x /usr/bin/azcopy\n\n# remove tarball from azcopy\nrm -rf *.tar.gz\n\n# copy kvp client file\n$COMMON_DIR/copy_kvp_client.sh\n", "num_lines": 103}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n#cat << EOF >> /etc/udev/rules.d/60-ib.rules\n# SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB)\n# Copyright (c) 2019, Mellanox Technologies. All rights reserved. See COPYING file\n#\n# Rename modes:\n# NAME_FALLBACK - Try to name devices in the following order:\n#                 by-pci -> by-guid -> kernel\n# NAME_KERNEL - leave name as kernel provided\n# NAME_PCI - based on PCI/slot/function location\n# NAME_GUID - based on system image GUID\n#\n# The stable names are combination of device type technology and rename mode.\n# Infiniband - ib*\n# RoCE - roce*\n# iWARP - iw*\n# OPA - opa*\n# Default (unknown protocol) - rdma*\n#\n# Example:\n# * NAME_PCI\n#   pci = 0000:00:0c.4\n#   Device type = IB\n#   mlx5_0 -> ibp0s12f4\n# * NAME_GUID\n#   GUID = 5254:00c0:fe12:3455\n#   Device type = RoCE\n#   mlx5_0 -> rocex525400c0fe123455\n#\n#ACTION==\"add\", SUBSYSTEM==\"infiniband\", PROGRAM=\"rdma_rename %k NAME_PCI\"\n#EOF\n", "num_lines": 34}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Disable Cloud-Init\ncat << EOF >> /etc/cloud/cloud.cfg.d/99-custom-networking.cfg\nnetwork: {config: disabled}\nEOF\n\n# Remove Hardware Mac Address and DHCP Name\ncp /etc/sysconfig/network-scripts/ifcfg-eth0 tempFile\ngrep -v -E \"HWADDR=|DHCP_HOSTNAME=\" /etc/sysconfig/network-scripts/ifcfg-eth0 > tempFile\nmv tempFile /etc/sysconfig/network-scripts/ifcfg-eth0\n", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable firewalld\n\n# Update memory limits\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Enable reclaim mode\necho \"vm.zone_reclaim_mode = 1\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh1 = 4096\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh2 = 8192\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh3 = 16384\" >> /etc/sysctl.conf\necho \"sunrpc.tcp_max_slot_table_entries = 128\" >> /etc/sysctl.conf\n\n## Systemd service for starting sunrpc and adding setting parameters\ncat <<EOF >/usr/sbin/sunrpc_tcp_settings.sh\n#!/bin/bash\n\nmodprobe sunrpc\nsysctl -p\nEOF\n\nchmod 755 /usr/sbin/sunrpc_tcp_settings.sh\n\ncat <<EOF >/etc/systemd/system/sunrpc_tcp_settings.service\n[Unit]\nDescription=Set sunrpc tcp settings\n\n[Service]\nUser=root\nType=oneshot\nExecStart=/usr/sbin/sunrpc_tcp_settings.sh\nRemainAfterExit=true\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable sunrpc_tcp_settings\nsystemctl start sunrpc_tcp_settings\nsystemctl is-active --quiet sunrpc_tcp_settings\n\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"sunrpc_tcp_settings service inactive!\"\n    exit ${error_code}\nfi\n\n# Remove auoms if exists - Prevent CPU utilization by auoms\nif yum list installed azsec-monitor >/dev/null 2>&1; then yum remove -y azsec-monitor; fi\n\n# Update WALinuxAgent - for IPoIB\nyum update -y WALinuxAgent\n\n# Configure WALinuxAgent\nsed -i -e 's/# OS.EnableRDMA=y/OS.EnableRDMA=y/g' /etc/waagent.conf\n\nfunction update_waagent_conf {\n    key=$1\n    value=$2\n\n    # Check if the key exists in the file\n    if grep -q \"^$key=\" /etc/waagent.conf; then\n        # Update the value if the key exists\n        sed -i \"s/^$key=.*/$key=$value/\" /etc/waagent.conf\n    else\n        # Add the key-value pair if the key does not exist\n        echo \"$key=$value\" >> /etc/waagent.conf\n    fi\n}\n\nupdate_waagent_conf \"Extensions.GoalStatePeriod\" \"300\"\nupdate_waagent_conf \"Extensions.InitialGoalStatePeriod\" \"6\"\nupdate_waagent_conf \"OS.EnableFirewallPeriod\" \"300\"\nupdate_waagent_conf \"OS.RemovePersistentNetRulesPeriod\" \"300\"\nupdate_waagent_conf \"OS.RootDeviceScsiTimeoutPeriod\" \"300\"\nupdate_waagent_conf \"OS.MonitorDhcpClientRestartPeriod\" \"60\"\nupdate_waagent_conf \"Provisioning.MonitorHostNamePeriod\" \"60\"\n\nsystemctl restart waagent\n$COMMON_DIR/write_component_version.sh \"WAAGENT\" $(waagent --version | head -n 1 | awk -F' ' '{print $1}' | awk -F- '{print $2}')\n\n# Setting Linux NFS read-ahead limits\n# Reference: \n#    https://learn.microsoft.com/en-us/azure/azure-netapp-files/performance-linux-nfs-read-ahead\n#    https://learn.microsoft.com/en-us/azure/storage/blobs/secure-file-transfer-protocol-support-how-to?tabs=azure-portal\ncat > /etc/udev/rules.d/90-nfs-readahead.rules <<EOM\nSUBSYSTEM==\"bdi\",\nACTION==\"add\",\nPROGRAM=\"/usr/bin/awk -v bdi=$kernel 'BEGIN{ret=1} {if ($4 == bdi) {ret=0}} END{exit ret}' /proc/fs/nfsfs/volumes\",\nATTR{read_ahead_kb}=\"15380\"\nEOM\n\nudevadm control --reload\n", "num_lines": 104}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nAOCC_VERSION=4.0.0-1\n\n# install dependency\nwget https://download.amd.com/developer/eula/aocc-compiler/aocc-compiler-${AOCC_VERSION}.x86_64.rpm\ndnf install -y ./aocc-compiler-${AOCC_VERSION}.x86_64.rpm\n\nrm ./aocc-compiler-${AOCC_VERSION}.x86_64.rpm\n\n$COMMON_DIR/write_component_version.sh \"AOCC\" ${AOCC_VERSION}\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\ncase ${DISTRIBUTION} in\n    \"almalinux8.6\") INTEL_MKL_VERSION=\"2022.1.0.223\";\n        RELEASE_VERSION=\"18721\";\n        CHECKSUM=\"4b325a3c4c56e52f4ce6c8fbb55d7684adc16425000afc860464c0f29ea4563e\";\n        IDENTIFIER=\"irc_nas\";\n        ;;\n    \"almalinux8.7\") INTEL_MKL_VERSION=\"2023.1.0.46342\";\n        RELEASE_VERSION=\"cd17b7fe-500e-4305-a89b-bd5b42bfd9f8\";\n        CHECKSUM=\"cc28c94cab23c185520b93c5a04f3979d8da6b4c90cee8c0681dd89819d76167\";\n        IDENTIFIER=\"IRC_NAS\";\n        ;;\n    *) ;;\nesac\n\n# Intel\u00c2\u00ae oneAPI Math Kernel Library\nONE_MKL_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/${IDENTIFIER}/${RELEASE_VERSION}/l_onemkl_p_${INTEL_MKL_VERSION}_offline.sh\n$COMMON_DIR/write_component_version.sh \"INTEL_ONE_MKL\" ${INTEL_MKL_VERSION}\n$COMMON_DIR/download_and_verify.sh ${ONE_MKL_DOWNLOAD_URL} ${CHECKSUM}\nsh ./l_onemkl_p_${INTEL_MKL_VERSION}_offline.sh -s -a -s --eula accept\n", "num_lines": 23}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nLUSTRE_VERSION=2.15.1_24_gbaa21ca\n\n# Expected params:\n# $1 = the major version of the distro. \"8\" for RHEL/Alma8, \"9\" for RHEL/Alma9.\n\nsource $ALMA_COMMON_DIR/setup_lustre_repo.sh \"$1\"\n\ndnf install -y --disableexcludes=main --refresh amlfs-lustre-client-${LUSTRE_VERSION}-$(uname -r | sed -e \"s/\\.$(uname -p)$//\" | sed -re 's/[-_]/\\./g')-1\nsed -i \"$ s/$/ amlfs*/\" /etc/dnf/dnf.conf\n\n$COMMON_DIR/write_component_version.sh \"LUSTRE\" ${LUSTRE_VERSION}\n", "num_lines": 15}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nMONEO_VERSION=v0.3.1\n\n# Dependencies \npython3 -m pip install --upgrade pip\n\n# Adding path to sudo user\nsed -i 's/.*secure_path.*/Defaults    secure_path = \"\\/usr\\/local\\/sbin:\\/usr\\/local\\/bin:\\/sbin:\\/bin:\\/usr\\/sbin:\\/usr\\/bin\\/\"/' /etc/sudoers\n\nMONITOR_DIR=/opt/azurehpc/tools\n\nmkdir -p $MONITOR_DIR\n\npushd $MONITOR_DIR\n    git clone https://github.com/Azure/Moneo  --branch $MONEO_VERSION\n    \n    chmod 777 Moneo\n\n    pushd Moneo/linux_service\n        ./configure_service.sh $MONITOR_DIR/Moneo       \n    popd\npopd\n\n# add an slias for Moneo\nif ! grep -qxF \"alias moneo='python3 /opt/azurehpc/tools/Moneo/moneo.py'\" /etc/bashrc; then\n    echo \"alias moneo='python3 /opt/azurehpc/tools/Moneo/moneo.py'\" >> /etc/bashrc\nfi\n\n$COMMON_DIR/write_component_version.sh \"MONEO\" ${MONEO_VERSION}\n", "num_lines": 33}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nGCC_VERSION=$1\nHPCX_PATH=$2\n\nHCOLL_PATH=${HPCX_PATH}/hcoll\nUCX_PATH=${HPCX_PATH}/ucx\nINSTALL_PREFIX=/opt\n\n# Load gcc\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n# MVAPICH2 2.3.7\nMV2_VERSION=\"2.3.7\"\nMV2_DOWNLOAD_URL=http://mvapich.cse.ohio-state.edu/download/mvapich/mv2/mvapich2-${MV2_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $MV2_DOWNLOAD_URL \"c39a4492f4be50df6100785748ba2894e23ce450a94128181d516da5757751ae\"\ntar -xvf mvapich2-${MV2_VERSION}.tar.gz\ncd mvapich2-${MV2_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/mvapich2-${MV2_VERSION} --enable-g=none --enable-fast=yes && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\n\n\n# OpenMPI 4.1.5\nOMPI_VERSION=\"4.1.5\"\nOMPI_DOWNLOAD_URL=https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-${OMPI_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $OMPI_DOWNLOAD_URL \"c018b127619d2a2a30c1931f316fc8a245926d0f5b4ebed4711f9695e7f70925\"\ntar -xvf openmpi-${OMPI_VERSION}.tar.gz\ncd openmpi-${OMPI_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/openmpi-${OMPI_VERSION} --with-ucx=${UCX_PATH} --with-hcoll=${HCOLL_PATH} --enable-mpirun-prefix-by-default --with-platform=contrib/platform/mellanox/optimized && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\n\n# exclude openmpi, perftest from updates\nsed -i \"$ s/$/ openmpi perftest/\" /etc/dnf/dnf.conf\n\n# Intel MPI 2021 (Update 9)\nIMPI_2021_VERSION=\"2021.9.0\"\nIMPI_2021_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/IRC_NAS/718d6f8f-2546-4b36-b97b-bc58d5482ebf/l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh\n$COMMON_DIR/download_and_verify.sh $IMPI_2021_DOWNLOAD_URL \"5c170cdf26901311408809ced28498b630a494428703685203ceef6e62735ef8\"\nbash l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh -s -a -s --eula accept\nmv ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/mpi ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\n$COMMON_DIR/write_component_version.sh \"IMPI_2021\" ${IMPI_2021_VERSION}\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# MVAPICH2\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION}\n#%Module 1.0\n#\n#  MVAPICH2 ${MV2_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/mvapich2-${MV2_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/mvapich2-${MV2_VERSION}/lib\nprepend-path    MANPATH         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_BIN         /opt/mvapich2-${MV2_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/mvapich2-${MV2_VERSION}/include\nsetenv          MPI_LIB         /opt/mvapich2-${MV2_VERSION}/lib\nsetenv          MPI_MAN         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_HOME        /opt/mvapich2-${MV2_VERSION}\nEOF\n\n# OpenMPI\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION}\n#%Module 1.0\n#\n#  OpenMPI ${OMPI_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/openmpi-${OMPI_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/openmpi-${OMPI_VERSION}/lib\nprepend-path    MANPATH         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_BIN         /opt/openmpi-${OMPI_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/openmpi-${OMPI_VERSION}/include\nsetenv          MPI_LIB         /opt/openmpi-${OMPI_VERSION}/lib\nsetenv          MPI_MAN         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_HOME        /opt/openmpi-${OMPI_VERSION}\nEOF\n\n#IntelMPI-v2021\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_2021_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\nsetenv          MPI_BIN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/include\nsetenv          MPI_LIB         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/lib\nsetenv          MPI_MAN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION} /usr/share/Modules/modulefiles/mpi/mvapich2\nln -s /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION} /usr/share/Modules/modulefiles/mpi/openmpi\nln -s /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION} /usr/share/Modules/modulefiles/mpi/impi-2021\n\n# cleanup downloaded tarballs and other installation files/folders\nrm -rf *.tar.gz *offline.sh\nrm -rf -- */\n", "num_lines": 111}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\ncase ${DISTRIBUTION} in\n    \"almalinux8.6\") NCCL_VERSION=\"2.14.3-1\";\n        CUDA_VERSION=\"11.6\";\n        ;;\n    \"almalinux8.7\") NCCL_VERSION=\"2.18.1-1\";\n        CUDA_VERSION=\"12.1\";\n        ;;\n    *) ;;\nesac\n\n# Install NCCL\nyum install -y rpm-build rpmdevtools\nTARBALL=\"v${NCCL_VERSION}.tar.gz\"\nNCCL_DOWNLOAD_URL=https://github.com/NVIDIA/nccl/archive/refs/tags/${TARBALL}\npushd /tmp\nwget ${NCCL_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\npushd nccl-${NCCL_VERSION}\nmake -j src.build\nmake pkg.redhat.build\nrpm -i ./build/pkg/rpm/x86_64/libnccl-${NCCL_VERSION}+cuda${CUDA_VERSION}.x86_64.rpm\nrpm -i ./build/pkg/rpm/x86_64/libnccl-devel-${NCCL_VERSION}+cuda${CUDA_VERSION}.x86_64.rpm\nrpm -i ./build/pkg/rpm/x86_64/libnccl-static-${NCCL_VERSION}+cuda${CUDA_VERSION}.x86_64.rpm\nsed -i \"$ s/$/ libnccl*/\" /etc/dnf/dnf.conf\npopd\n\n# Install the nccl rdma sharp plugin\nmkdir -p /usr/local/nccl-rdma-sharp-plugins\ngit clone https://github.com/Mellanox/nccl-rdma-sharp-plugins.git\npushd nccl-rdma-sharp-plugins\n./autogen.sh\n./configure --prefix=/usr/local/nccl-rdma-sharp-plugins --with-cuda=/usr/local/cuda\nmake\nmake install\npopd\npopd\n\n# Build the nccl tests\nsource /etc/profile.d/modules.sh\nmodule load mpi/hpcx\ngit clone https://github.com/NVIDIA/nccl-tests.git\npushd nccl-tests\nmake MPI=1 MPI_HOME=${HPCX_MPI_DIR} CUDA_HOME=/usr/local/cuda\npopd\nmv nccl-tests /opt/.\nmodule unload mpi/hpcx\n$COMMON_DIR/write_component_version.sh \"NCCL\" ${NCCL_VERSION}\n\n# Remove installation files\nrm -rf /tmp/${TARBALL}\nrm -rf /tmp/nccl-${NCCL_VERSION}\n", "num_lines": 56}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nsed -i '/\\[main\\]/a no-auto-default=*' /etc/NetworkManager/NetworkManager.conf\n\n# update network config on reboot\nmkdir -p /lib/systemd/system/cloud-init-local.service.d/\ncat <<EOF > /lib/systemd/system/cloud-init-local.service.d/50-azure-clear-persistent-obj-pkl.conf\n[Service]\nExecStartPre=-/bin/sh -xc 'if [ -e /var/lib/cloud/instance/obj.pkl ]; then echo \"cleaning persistent cloud-init object\"; rm /var/lib/cloud/instance/obj.pkl; fi; exit 0'\nEOF\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Expected params:\n# $1 = the major version of the distro. \"8\" for RHEL/Alma8, \"9\" for RHEL/Alma9.\n\nDISTRIB_CODENAME=\"el$1\"\nREPO_PATH=/etc/yum.repos.d/amlfs.repo\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\necho -e \"[amlfs]\" > ${REPO_PATH}\necho -e \"name=Azure Lustre Packages\" >> ${REPO_PATH}\necho -e \"baseurl=https://packages.microsoft.com/yumrepos/amlfs-${DISTRIB_CODENAME}\" >> ${REPO_PATH}\necho -e \"enabled=1\" >> ${REPO_PATH}\necho -e \"gpgcheck=1\" >> ${REPO_PATH}\necho -e \"gpgkey=https://packages.microsoft.com/keys/microsoft.asc\" >> ${REPO_PATH}\n", "num_lines": 18}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n####\n# @Brief        : GET ADO build info\n# @Param        : ADO Auth token, build url\n# @RetVal       : build json\n####\nget_builds_res () {\n    builds_json=$(curl -s -H \"Authorization: Bearer $SYSTEM_ACCESSTOKEN\" $build_url)\n    echo $builds_json\n}\n\n\n# Queue a build\nres_code=$(curl -s -w \"%{response_code}\\n\" -o post.json -X POST \"https://dev.azure.com/hpc-platform-team/hpc-image-val/_apis/build/builds?api-version=6.0\" \\\n-H \"Authorization: Bearer $SYSTEM_ACCESSTOKEN\" -H \"Content-Type: application/json\" \\\n--data-raw \"{\\\"definition\\\": {\\\"id\\\": 3}, \\\"sourceBranch\\\": \\\"github_pr\\\", \\\"parameters\\\": \\\"{\\\\\\\"PR_NUM\\\\\\\": \\\\\\\"$PR_NUM\\\\\\\"}\\\"}\")\n\nif [ $res_code -ne 200 ]\nthen\n    echo \"Error! Could not queue build. Response code: $res_code\"\n    exit 1\nfi\n\necho \"Queued build!\"\n\n# Get URL for queued AzDo build\npost_build_res=$(cat ./post.json)\nbuild_url=$(echo $post_build_res | jq -r \"._links.self.href\")\necho \"Build url: $(echo $post_build_res | jq -r \"._links.web.href\")\"\n\n# Wait until build finishes\nbuild_status=$(get_builds_res | jq -r \".status\")\n\nwhile [ \"${build_status}\" != \"completed\" ]\ndo\n    build_status=$(get_builds_res | jq -r \".status\")\n  \n    echo \"Build status: ${build_status}\"\n    sleep 300\ndone\n\nbuild_res=$(get_builds_res | jq -r \".result\")\necho \"Build result: ${build_res}\"\n\n# Throw an error if build fails\nif [ \"${build_res}\" != \"succeeded\" ]\nthen\n    echo \"Error! Build failed...\"\n    exit 1\nfi\n", "num_lines": 53}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# lustre client\n#./install_lustre_client.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n", "num_lines": 48}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n\n", "num_lines": 9}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_lustre_client.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.4-1.0.3.0\"\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel7.6-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"ae72826b3b9a57e4560f7f0a2975c0645eb2f31f47f1b3e2f388346e507f4c8b\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n", "num_lines": 26}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.9.0\nMLNX_OFED_VERSION=\"5.4-1.0.3.0\"\nHPCX_VERSION=\"v2.9.0\"\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc9.2.0-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-redhat7.6-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"fb395b656d96d959ab833133163bd023c36b8f6d08808a78e4304c7e1e786f6e\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n\n", "num_lines": 51}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install kernel libs, these should already be installed with Mellanox OFED installation\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-headers-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\nyum install -y kernel-headers-${KERNEL}\n\n$COMMON_DIR/install_nvidiagpudriver.sh", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_utils.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# lustre client\n#./install_lustre_client.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n", "num_lines": 48}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_lustre_client.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.4-1.0.3.0\"\n$COMMON_DIR/write_component_version.sh \"MOFED\" ${VERSION}\nTARBALL=\"MLNX_OFED_LINUX-${VERSION}-rhel7.7-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"e12e7d1606c8ad875c61be261d45e7cd11b0e15258ca29f7a6830077c57c9792\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n", "num_lines": 26}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.9.0\nMLNX_OFED_VERSION=\"5.4-1.0.3.0\"\nHPCX_VERSION=\"v2.9.0\"\n$COMMON_DIR/write_component_version.sh \"HPCX\" ${HPCX_VERSION}\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc9.2.0-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-redhat7.7-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"e8ed81cfb48d65d2111eab5108206b161b626f711336e084c3312297bef118bb\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n\n", "num_lines": 51}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install kernel libs, these should already be installed with Mellanox OFED installation\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-headers-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\nyum install -y kernel-headers-${KERNEL}\n\n$COMMON_DIR/install_nvidiagpudriver.sh", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_utils.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# lustre client\n#./install_lustre_client.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n", "num_lines": 48}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_lustre_client.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.4-1.0.3.0\"\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel7.8-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"c78d9548b550fe2d8d1f217bab0b7697ed23885311c7b82baaf03f7a724cf7e2\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n", "num_lines": 26}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.9.0\nMLNX_OFED_VERSION=\"5.4-1.0.3.0\"\nHPCX_VERSION=\"v2.9.0\"\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc9.2.0-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-redhat7.8-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"7f5d7cc1f53b1f53cd999335a17ce4486898e1a80a37dad6fd15a8a4ab927bbb\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n\n", "num_lines": 51}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install kernel libs, these should already be installed with Mellanox OFED installation\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-headers-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\nyum install -y kernel-headers-${KERNEL}\n\n$COMMON_DIR/install_nvidiagpudriver.sh", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_utils.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Disable Cloud-Init\ncat << EOF >> /etc/cloud/cloud.cfg.d/99-custom-networking.cfg\nnetwork: {config: disabled}\nEOF\n\n# Remove Hardware Mac Address and DHCP Name\ncp /etc/sysconfig/network-scripts/ifcfg-eth0 tempFile\ngrep -v -E \"HWADDR=|DHCP_HOSTNAME=\" /etc/sysconfig/network-scripts/ifcfg-eth0 > tempFile\nmv tempFile /etc/sysconfig/network-scripts/ifcfg-eth0\n", "num_lines": 13}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# cleanup downloaded tarballs\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz\nrm -rf -- */\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# Install NCCL\n./install_nccl.sh\n\n# Install NVIDIA docker container\n$COMMON_DIR/../centos/centos-7.x/common/install_docker.sh\n\n# cleanup downloaded tarballs\nrm -rf *.tar.gz *_offline.sh *.rpm *.run\n\n# Install DCGM\n./install_dcgm.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# Network Optimization\n$COMMON_DIR/network-tuning.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# disable cloud-init\n./disable_cloudinit.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 71}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_dcgm.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.4-3.0.0.0\"\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel7.9-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"b11a653769bb7e05ab67181d6dea1b271d0be759e49ba5e6a64ffcca4a2ab80f\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum -y install http://olcentgbl.trafficmanager.net/centos/${RELEASE}/updates/x86_64/kernel-devel-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n", "num_lines": 26}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.9.0\nMLNX_OFED_VERSION=\"5.4-1.0.3.0\"\nHPCX_VERSION=\"v2.9.0\"\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc9.2.0-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-redhat7.9-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"ed1288376f3296c7dd95edb64984d94f09d1c7e84f91af773f376b24f1b79c9b\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n\n", "num_lines": 51}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/common/install_nccl.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-7.x/common/install_nvidiagpudriver.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/centos/7/prod.repo > ./microsoft-prod.repo\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.repo /etc/yum.repos.d/\n\nyum repolist\n\n../common/install_utils.sh\n\n", "num_lines": 14}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable wpa_supplicant\nsystemctl disable abrtd\n\n../../common/hpc-tuning.sh\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nINSTALL_PREFIX=/opt/amd\nmkdir -p ${INSTALL_PREFIX}\n\nAOCL_VERSION=\"2.2-4\"\n$COMMON_DIR/write_component_version.sh \"AOCL\" ${AOCL_VERSION}\nTARBALL=\"aocl-linux-aocc-${AOCL_VERSION}_centos7.tar.gz\"\nAOCL_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\n$COMMON_DIR/download_and_verify.sh $AOCL_DOWNLOAD_URL \"4bdc5caec0233066ded3e2bfedb1e03bdeec82725361764d8860075f64ff4031\"\ntar -xvf ${TARBALL}\ncd aocl-linux-aocc-${AOCL_VERSION}\n\n./install.sh -t amd -l blis fftw libflame\ncp -r amd/2.2/* ${INSTALL_PREFIX}\ncd .. && rm -rf aocl-linux-aocc-${AOCL_VERSION}\n\n# Setup module files for AMD Libraries\nmkdir -p /usr/share/Modules/modulefiles/amd/\n\n# fftw\ncat << EOF >> /usr/share/Modules/modulefiles/amd/aocl-${AOCL_VERSION}\n#%Module 1.0\n#\n#  AOCL\n#\nprepend-path    LD_LIBRARY_PATH   ${INSTALL_PREFIX}/lib\nsetenv          AMD_FFTW_INCLUDE  ${INSTALL_PREFIX}/include\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/amd/aocl-${AOCL_VERSION} /usr/share/Modules/modulefiles/amd/aocl\n", "num_lines": 34}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install DCGM\nDCGM_VERSION=2.3.1\n$COMMON_DIR/write_component_version.sh \"DCGM\" ${DCGM_VERSION}\nDCGM_URL=https://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\n$COMMON_DIR/download_and_verify.sh $DCGM_URL \"586bf03a7b0c9827c80dc0a82c6e8fe780ff1d76d82b103866906e4cdd191710\"\nsudo rpm -i datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\nsudo rm -f datacenter-gpu-manager-${DCGM_VERSION}-1-x86_64.rpm\n\n# Create service for dcgm to launch on bootup\nsudo bash -c \"cat > /etc/systemd/system/dcgm.service\" <<'EOF'\n[Unit]\nDescription=DCGM service\n\n[Service]\nUser=root\nPrivateTmp=false\nExecStart=/usr/bin/nv-hostengine -n\nRestart=on-abort\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsudo systemctl enable dcgm\nsudo systemctl start dcgm\n", "num_lines": 29}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Moby Engine + CLI\nyum install -y moby-engine\nyum install -y moby-cli\n\n# Install NVIDIA Docker\n# Reference: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html\n# Setting up NVIDIA Container Toolkit\ndistribution=$(. /etc/os-release;echo $ID$VERSION_ID) \\\n   && curl -s -L https://nvidia.github.io/nvidia-docker/$distribution/nvidia-docker.repo | tee /etc/yum.repos.d/nvidia-docker.repo\n# MIG Capability on A100\ncurl -s -L https://nvidia.github.io/nvidia-container-runtime/experimental/$distribution/nvidia-container-runtime.list | tee /etc/yum.repos.d/nvidia-container-runtime.list\n\nyum clean expire-cache\n# Install nvidia-docker package\n# Install NVIDIA container toolkit and mark NVIDIA packages on hold\nyum install -y nvidia-container-toolkit\n# Mark the installed packages on hold to disable updates\necho \"exclude=nvidia-container-toolkit\" | tee -a /etc/yum.conf\necho \"exclude=libnvidia-container-tools\" | tee -a /etc/yum.conf\necho \"exclude=libnvidia-container1\" | tee -a /etc/yum.conf\n\n# Install NVIDIA container runtime and mark NVIDIA packages on hold\nyum install -y nvidia-container-runtime\necho \"exclude=nvidia-container-runtime\" | tee -a /etc/yum.conf\n\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/nvidia-docker\ncp nvidia-docker /bin/\nchmod +x /bin/nvidia-docker\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/daemon.json\ncp daemon.json /etc/docker/\n\n# Working setup can be tested by running a base CUDA container\n# nvidia-docker run -e NVIDIA_VISIBLE_DEVICES=all nvidia/cuda:11.0-base nvidia-smi\n\n# enable and restart the docker daemon to complete the installation\nsystemctl enable docker\nsystemctl restart docker\n\n# Write the docker version to components file\ndocker_version=$(nvidia-docker --version | awk -F' ' '{print $3}')\n$COMMON_DIR/write_component_version.sh \"NVIDIA-DOCKER\" ${docker_version::-1}\n\n# Clean repos\nrm -rf /etc/yum.repos.d/nvidia-*\nrm -rf /etc/yum.repos.d/microsoft-prod.repo\n\nrm -rf /var/cache/yum/x86_64/7/packages-microsoft-com-prod/\nrm -rf /var/cache/yum/x86_64/7/nvidia-*\nrm -rf /var/cache/yum/x86_64/7/libnvidia-container/\n", "num_lines": 53}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install packages required to facilitate DKMS-based installations\nyum install -y asciidoc audit-libs-devel automake bc \\\n               bison device-mapper-devel elfutils-devel \\\n               elfutils-libelf-devel expect flex gcc gcc-c++ git \\\n               glib2 glib2-devel hmaccalc keyutils-libs-devel krb5-devel ksh \\\n               libattr-devel libblkid-devel libselinux-devel libtool \\\n               libuuid-devel libyaml-devel lsscsi make ncurses-devel \\\n               net-snmp-devel net-tools newt-devel \\\n               parted patchutils pciutils-devel perl-ExtUtils-Embed \\\n               pesign redhat-rpm-config rpm-build systemd-devel \\\n               tcl-devel tk-devel wget xmlto yum-utils zlib-devel\n\n# Install the kernel packages\nyum install -y kernel \\\n               kernel-devel \\\n               kernel-headers \\\n               kernel-abi-whitelists \\\n               kernel-tools \\\n               kernel-tools-libs \\\n               kernel-tools-libs-devel\n\n# Install the EPEL repository definition. EPEL provides the DKMS software\nyum install -y epel-release\n\ncat << EOF >> /etc/yum.repos.d/lustre-client.repo\n[lustre-client]\nname=lustre-client\nbaseurl=https://downloads.whamcloud.com/public/lustre/latest-release/el7/client\n# exclude=*debuginfo*\ngpgcheck=0\nEOF\n\n# Install the Lustre client user-space tools and DKMS kernel module package\nyum --nogpgcheck --enablerepo=lustre-client install -y lustre-client-dkms lustre-client\n", "num_lines": 38}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nGCC_VERSION=$1\nHPCX_PATH=$2\n\nHCOLL_PATH=${HPCX_PATH}/hcoll\nUCX_PATH=${HPCX_PATH}/ucx\nINSTALL_PREFIX=/opt\n\n# Load gcc\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n# Intel MPI 2018 (update 4)\nIMPI_VERSION=\"2018.4.274\"\n$COMMON_DIR/write_component_version.sh \"IMPI_2018\" ${IMPI_VERSION}\nIMPI_2018_DOWNLOAD_URL=http://registrationcenter-download.intel.com/akdlm/irc_nas/tec/13651/l_mpi_${IMPI_VERSION}.tgz\n$COMMON_DIR/download_and_verify.sh $IMPI_2018_DOWNLOAD_URL \"a1114b3eb4149c2f108964b83cad02150d619e50032059d119ac4ffc9d5dd8e0\"\ntar -xvf l_mpi_${IMPI_VERSION}.tgz\ncd l_mpi_${IMPI_VERSION}\nsed -i -e 's/ACCEPT_EULA=decline/ACCEPT_EULA=accept/g' silent.cfg\n./install.sh --silent ./silent.cfg\ncd ..\n\n#IntelMPI-v2018\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/impi_${IMPI_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/impi/${IMPI_VERSION}/intel64/modulefiles/mpi\nsetenv          MPI_BIN         /opt/intel/impi/${IMPI_VERSION}/intel64/bin\nsetenv          MPI_INCLUDE     /opt/intel/impi/${IMPI_VERSION}/intel64/include\nsetenv          MPI_LIB         /opt/intel/impi/${IMPI_VERSION}/intel64/lib\nsetenv          MPI_MAN         /opt/intel/impi/${IMPI_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/impi/${IMPI_VERSION}/intel64\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/impi_${IMPI_VERSION} /usr/share/Modules/modulefiles/mpi/impi\n\n../../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n", "num_lines": 47}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n$COMMON_DIR/install_nvidiagpudriver.sh\n\n# Install NV Peer Memory (GPU Direct RDMA)\nNV_PEER_MEMORY_VERSION=\"1.2-0\"\n$COMMON_DIR/write_component_version.sh \"NV_PEER_MEMORY\" ${NV_PEER_MEMORY_VERSION}\ngit clone https://github.com/gpudirect/nv_peer_memory.git\n\npushd nv_peer_memory\nyum install -y rpm-build\n./build_module.sh \nrpmbuild --rebuild /tmp/nvidia_peer_memory-${NV_PEER_MEMORY_VERSION}.src.rpm\nrpm -ivh ~/rpmbuild/RPMS/x86_64/nvidia_peer_memory-${NV_PEER_MEMORY_VERSION}.x86_64.rpm\necho \"exclude=nvidia_peer_memory\" | sudo tee -a /etc/yum.conf\nsudo modprobe nv_peer_mem\nlsmod | grep nv\npopd\n\nsudo bash -c \"cat > /etc/modules-load.d/nv_peer_mem.conf\" <<'EOF'\nnv_peer_mem\nEOF\n\nsudo systemctl enable nv_peer_mem.service\n\n# Install GDRCopy\nGDRCOPY_VERSION=\"2.3\"\n$COMMON_DIR/write_component_version.sh \"GDRCOPY\" ${GDRCOPY_VERSION}\nTARBALL=\"v${GDRCOPY_VERSION}.tar.gz\"\nGDRCOPY_DOWNLOAD_URL=https://github.com/NVIDIA/gdrcopy/archive/refs/tags/${TARBALL}\nwget $GDRCOPY_DOWNLOAD_URL\ntar -xvf $TARBALL\n\npushd gdrcopy-${GDRCOPY_VERSION}/packages/\nCUDA=/usr/local/cuda ./build-rpm-packages.sh\nrpm -Uvh gdrcopy-kmod-${GDRCOPY_VERSION}-1dkms.noarch.el7.rpm\necho \"exclude=gdrcopy-kmod.noarch\" | sudo tee -a /etc/yum.conf\nrpm -Uvh gdrcopy-${GDRCOPY_VERSION}-1.x86_64.el7.rpm\necho \"exclude=gdrcopy\" | sudo tee -a /etc/yum.conf\nrpm -Uvh gdrcopy-devel-${GDRCOPY_VERSION}-1.noarch.el7.rpm\necho \"exclude=gdrcopy-devel.noarch\" | sudo tee -a /etc/yum.conf\npopd\n\n# Install Fabric Manager\nNVIDIA_FABRIC_MANAGER_VERSION=\"470.82.01-1\"\n$COMMON_DIR/write_component_version.sh \"NVIDIA_FABRIC_MANAGER\" ${NVIDIA_FABRIC_MANAGER_VERSION}\nNVIDIA_FABRIC_MNGR_URL=http://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/nvidia-fabric-manager-${NVIDIA_FABRIC_MANAGER_VERSION}.x86_64.rpm\n$COMMON_DIR/download_and_verify.sh ${NVIDIA_FABRIC_MNGR_URL} \"ade1051a189fe84a326b8021d1446eb03d48e0a998e8cada85081b27a89923f1\"\nyum install -y ./nvidia-fabric-manager-${NVIDIA_FABRIC_MANAGER_VERSION}.x86_64.rpm\necho \"exclude=nvidia-fabric-manager\" | sudo tee -a /etc/yum.conf\nsystemctl enable nvidia-fabricmanager\nsystemctl start nvidia-fabricmanager\n", "num_lines": 54}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install pre-reqs and development tools\nyum groupinstall -y \"Development Tools\"\nyum install -y numactl \\\n    numactl-devel \\\n    libxml2-devel \\\n    byacc \\\n    environment-modules \\\n    python-devel \\\n    python-setuptools \\\n    gtk2 \\\n    atk \\\n    cairo \\\n    tcl \\\n    tk \\\n    m4 \\\n    texinfo \\\n    glibc-devel \\\n    glibc-static \\\n    libudev-devel \\\n    binutils \\\n    binutils-devel \\\n    selinux-policy-devel \\\n    kernel-headers \\\n    nfs-utils \\\n    fuse-libs \\\n    libpciaccess \\\n    cmake \\\n    libnl3-devel \\\n    libsecret \\\n    rpm-build \\\n    make \\\n    check \\\n    check-devel \\\n    subunit \\\n    subunit-devel\n\n## Install dkms from the EPEL repository\nwget -r --no-parent -A \"dkms-*.el7.noarch.rpm\" https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/ \nyum localinstall ./dl.fedoraproject.org/pub/epel/7/x86_64/Packages/d/dkms-*.el7.noarch.rpm -y\n\n## Install jq Utility\n# Download dependency libonig.so for jq\nwget -r --no-parent -A \"oniguruma-*.el7.x86_64.rpm\" https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/o/\nyum localinstall ./dl.fedoraproject.org/pub/epel/7/x86_64/Packages/o/oniguruma-*.el7.x86_64.rpm -y\n# Download jq utility\nwget -r --no-parent -A \"jq-*.el7.x86_64.rpm\" https://dl.fedoraproject.org/pub/epel/7/x86_64/Packages/j/\nyum localinstall ./dl.fedoraproject.org/pub/epel/7/x86_64/Packages/j/jq-*.el7.x86_64.rpm -y\n\n# Remove rpm files\nrm -rf ./dl.fedoraproject.org/\n\n# Install azcopy tool \n# To copy blobs or files to or from a storage account.\nwget https://azhpcstor.blob.core.windows.net/azhpc-images-store/azcopy_linux_se_amd64_10.12.2.tar.gz\ntar -xvf azcopy_linux_se_amd64_10.12.2.tar.gz\n\n# copy the azcopy to the bin path\npushd azcopy_linux_se_amd64_10.12.2\ncp azcopy /usr/bin/\npopd\n\n# Allow execute permissions\nchmod +x /usr/bin/azcopy\n\n# remove tarball from azcopy\nrm -rf *.tar.gz\n", "num_lines": 70}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install diagnostic script\n\"$COMMON_DIR/install_hpcdiag.sh\"\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n", "num_lines": 45}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-8.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"5.4-1.0.3.0\"\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-rhel8.1-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"171b304d76f2e88ec62138b01691a5580c5fa3674209f262592669c637891c13\"\ntar zxvf ${TARBALL}\n\n# Uncomment the lines below if you are running this on a VM\n#KERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\n#KERNEL=${KERNEL[-1]}\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum install -y https://packages.microsoft.com/yumrepos/1.0-eval-base-x8664-rpms/Packages/k/kernel-devel-${KERNEL}.rpm\n#yum install -y https://packages.microsoft.com/yumrepos/1.0-eval-base-x8664-rpms/Packages/k/kernel-modules-extra-${KERNEL}.rpm\n\nyum install -y kernel-devel\nyum install -y kernel-modules-extra\nKERNEL=( $(rpm -q kernel-devel | sed 's/kernel-devel\\-//g') )\nKERNEL=${KERNEL[-1]}\n\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo --skip-unsupported-devices-check --without-fw-update\n\n# Issue: Module mlx5_ib belong to a kernel which is not a part of MLNX\n# Resolution: set FORCE=1/ force-restart /etc/init.d/openibd \n# This causes openibd to ignore the kernel difference but relies on weak-updates\n# Restarting openibd\n/etc/init.d/openibd force-restart\n", "num_lines": 32}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.9.0\nMLNX_OFED_VERSION=\"5.4-1.0.3.0\"\nHPCX_VERSION=\"v2.9.0\"\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc9.2.0-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-redhat8.1-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"e47d708f3b89b3fcff169dac15ff2c454bc4bcc07575d8add2a8348f3eabebeb\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n", "num_lines": 50}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Install kernel libs, these should already be installed with Mellanox OFED installation\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\n# Uncomment the lines below if you are running this on a VM\n#RELEASE=( $(cat /etc/centos-release | awk '{print $4}') )\n#yum install -y http://olcentwus.cloudapp.net/centos/${RELEASE}/BaseOS/x86_64/os/kernel-devel-${KERNEL}.rpm\n#yum install -y http://olcentwus.cloudapp.net/centos/${RELEASE}/BaseOS/x86_64/os/kernel-headers-${KERNEL}.rpm\nyum install -y kernel-devel-${KERNEL}\nyum install -y kernel-headers-${KERNEL}\n\n# Install DKMS\nsudo dnf install -y dkms\n\n$COMMON_DIR/install_nvidiagpudriver.sh", "num_lines": 16}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_utils.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../../common/hpc-tuning.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install compilers\n./install_gcc.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n#./install_nvidiagpudriver.sh\n\n# install AMD tuned libraries\n./install_amd_libs.sh\n\n# install Intel libraries\n./install_intel_libs.sh\n\n# add udev rule\n$COMMON_DIR/../centos/common/add-udev-rules.sh\n\n# add interface rules\n$COMMON_DIR/../centos/common/network-config.sh\n\n# optimizations\n./hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install diagnostic script\n\"$COMMON_DIR/install_hpcdiag.sh\"\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n", "num_lines": 45}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/../centos/centos-8.x/common/install_amd_libs.sh\n", "num_lines": 4}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMODULE_FILES_DIRECTORY=/usr/share/Modules/modulefiles\n\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n$COMMON_DIR/install_gcc-9.2.sh ${MODULE_FILES_DIRECTORY}\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n$COMMON_DIR/install_intel_libs.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nMLNX_OFED_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/MLNX_OFED_LINUX-5.2-1.0.4.0-rhel8.3-x86_64.tgz\nTARBALL=$(basename ${MLNX_OFED_DOWNLOAD_URL})\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"dd13ffa54524af9509e3de7288a863aa48ed7016bb3d15446523703020c41715\"\ntar zxvf ${TARBALL}\n\nKERNEL=( $(rpm -q kernel | sed 's/kernel\\-//g') )\nKERNEL=${KERNEL[-1]}\nyum install -y kernel-devel-${KERNEL}\n./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/kernels/${KERNEL} --add-kernel-support --skip-repo\n\n", "num_lines": 16}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.7.4\nHPCX_VERSION=\"v2.7.4\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/hpcx-v2.8.0-gcc-MLNX_OFED_LINUX-5.2-1.0.4.0-redhat8.3-x86_64.tbz\nTARBALL=$(basename ${HPCX_DOWNLOAD_URL})\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"ee1b0f3fe8d295ae662cd08794a890135b4014b9b3e8efa3f00aafe4678bae9c\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n\n# Enable Sharpd\n${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\nsystemctl enable sharpd\nsystemctl start sharpd\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# HPC-X\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/hpcx-${HPCX_VERSION} /usr/share/Modules/modulefiles/mpi/hpcx\n\n# Install platform independent MPIs\n../../common/install_mpis.sh ${GCC_VERSION} ${HPCX_PATH}\n", "num_lines": 48}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n../common/install_utils.sh\n\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nINSTALL_PREFIX=/opt/amd\nmkdir -p ${INSTALL_PREFIX}\n\nAOCL_VERSION=\"2.2.1\"\n$COMMON_DIR/write_component_version.sh \"AOCL\" ${AOCL_VERSION}\nTARBALL=\"aocl-linux-aocc-${AOCL_VERSION}_centos8.tar.gz\"\nAOCL_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\n$COMMON_DIR/download_and_verify.sh $AOCL_DOWNLOAD_URL \"cbe5afbdc241047a9d8814b5557be429aa0d9d2b83408eca8244e1ab9c8e2c87\"\ntar -xvf ${TARBALL}\ncd aocl-linux-aocc-${AOCL_VERSION}_centos8\n\n./install.sh -t amd -l blis fftw libflame\ncp -r amd/${AOCL_VERSION}_centos8/* ${INSTALL_PREFIX}\ncd .. && rm -rf aocl-linux-aocc-${AOCL_VERSION}_centos8\n\n# Setup module files for AMD Libraries\nmkdir -p /usr/share/Modules/modulefiles/amd/\n\n# fftw\ncat << EOF >> /usr/share/Modules/modulefiles/amd/aocl-${AOCL_VERSION}\n#%Module 1.0\n#\n#  AOCL\n#\nprepend-path    LD_LIBRARY_PATH   ${INSTALL_PREFIX}/lib\nsetenv          AMD_FFTW_INCLUDE  ${INSTALL_PREFIX}/include\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/amd/aocl-${AOCL_VERSION} /usr/share/Modules/modulefiles/amd/aocl\n", "num_lines": 34}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install pre-reqs and development tools\nyum groupinstall -y \"Development Tools\"\nyum install -y numactl \\\n    numactl-devel \\\n    libxml2-devel \\\n    byacc \\\n    environment-modules \\\n    gtk2 \\\n    atk \\\n    cairo \\\n    tcl \\\n    tk \\\n    m4 \\\n    tcsh \\\n    gcc-gfortran \\\n    python36-devel \\\n    elfutils-libelf-devel \\\n    kernel-rpm-macros \\\n    glibc-devel \\\n    libudev-devel \\\n    binutils \\\n    binutils-devel \\\n    selinux-policy-devel \\\n    kernel-headers \\\n    nfs-utils \\\n    fuse-libs \\\n    libpciaccess \\\n    cmake \\\n    libnl3-devel \\\n    libarchive \\\n    libsecret\n\n# Install azcopy tool \n# To copy blobs or files to or from a storage account.\nwget https://azhpcstor.blob.core.windows.net/azhpc-images-store/azcopy_linux_se_amd64_10.12.2.tar.gz\ntar -xvf azcopy_linux_se_amd64_10.12.2.tar.gz\n\n# copy the azcopy to the bin path\npushd azcopy_linux_se_amd64_10.12.2\ncp azcopy /usr/bin/\npopd\n\n# Allow execute permissions\nchmod +x /usr/bin/azcopy\n\n# remove tarball from azcopy\nrm -rf *.tar.gz\n", "num_lines": 51}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n#cat << EOF >> /etc/udev/rules.d/60-ib.rules\n# SPDX-License-Identifier: (GPL-2.0 OR Linux-OpenIB)\n# Copyright (c) 2019, Mellanox Technologies. All rights reserved. See COPYING file\n#\n# Rename modes:\n# NAME_FALLBACK - Try to name devices in the following order:\n#                 by-pci -> by-guid -> kernel\n# NAME_KERNEL - leave name as kernel provided\n# NAME_PCI - based on PCI/slot/function location\n# NAME_GUID - based on system image GUID\n#\n# The stable names are combination of device type technology and rename mode.\n# Infiniband - ib*\n# RoCE - roce*\n# iWARP - iw*\n# OPA - opa*\n# Default (unknown protocol) - rdma*\n#\n# Example:\n# * NAME_PCI\n#   pci = 0000:00:0c.4\n#   Device type = IB\n#   mlx5_0 -> ibp0s12f4\n# * NAME_GUID\n#   GUID = 5254:00c0:fe12:3455\n#   Device type = RoCE\n#   mlx5_0 -> rocex525400c0fe123455\n#\n#ACTION==\"add\", SUBSYSTEM==\"infiniband\", PROGRAM=\"rdma_rename %k NAME_PCI\"\n#EOF\n", "num_lines": 34}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable firewalld\n\n# Update memory limits\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Enable reclaim mode\necho \"vm.zone_reclaim_mode = 1\" >> /etc/sysctl.conf\nsysctl -p\n\n# Remove auoms if exists - Prevent CPU utilization by auoms\nif yum list installed azsec-monitor >/dev/null 2>&1; then yum remove -y azsec-monitor; fi\n\n# Update WALinuxAgent - for IPoIB\nyum update -y WALinuxAgent\n\n# Configure WALinuxAgent\nsudo sed -i -e 's/# OS.EnableRDMA=y/OS.EnableRDMA=y/g' /etc/waagent.conf\necho \"Extensions.GoalStatePeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"Extensions.InitialGoalStatePeriod=6\" | sudo tee -a /etc/waagent.conf\necho \"OS.EnableFirewallPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.RemovePersistentNetRulesPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.RootDeviceScsiTimeoutPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.MonitorDhcpClientRestartPeriod=60\" | sudo tee -a /etc/waagent.conf\necho \"Provisioning.MonitorHostNamePeriod=60\" | sudo tee -a /etc/waagent.conf\nsudo systemctl restart waagent\n$COMMON_DIR/write_component_version.sh \"WAAGENT\" $(waagent --version | head -n 1 | awk -F' ' '{print $1}' | awk -F- '{print $2}')\n", "num_lines": 37}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nGCC_VERSION=$1\nHPCX_PATH=$2\n\nHCOLL_PATH=${HPCX_PATH}/hcoll\nUCX_PATH=${HPCX_PATH}/ucx\nINSTALL_PREFIX=/opt\n\n# Load gcc\nexport PATH=/opt/${GCC_VERSION}/bin:$PATH\nexport LD_LIBRARY_PATH=/opt/${GCC_VERSION}/lib64:$LD_LIBRARY_PATH\nset CC=/opt/${GCC_VERSION}/bin/gcc\nset GCC=/opt/${GCC_VERSION}/bin/gcc\n\n# MVAPICH2 2.3.6\nMV2_VERSION=\"2.3.6\"\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\nMV2_DOWNLOAD_URL=http://mvapich.cse.ohio-state.edu/download/mvapich/mv2/mvapich2-${MV2_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $MV2_DOWNLOAD_URL \"b3a62f2a05407191b856485f99da05f5e769d6381cd63e2fcb83ee98fc46a249\"\ntar -xvf mvapich2-${MV2_VERSION}.tar.gz\ncd mvapich2-${MV2_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/mvapich2-${MV2_VERSION} --enable-g=none --enable-fast=yes && make -j$(nproc) && make install\ncd ..\n\n\n# OpenMPI 4.1.1\nOMPI_VERSION=\"4.1.1\"\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\nOMPI_DOWNLOAD_URL=https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-${OMPI_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $OMPI_DOWNLOAD_URL \"d80b9219e80ea1f8bcfe5ad921bd9014285c4948c5965f4156a3831e60776444\"\ntar -xvf openmpi-${OMPI_VERSION}.tar.gz\ncd openmpi-${OMPI_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/openmpi-${OMPI_VERSION} --with-ucx=${UCX_PATH} --with-hcoll=${HCOLL_PATH} --enable-mpirun-prefix-by-default --with-platform=contrib/platform/mellanox/optimized && make -j$(nproc) && make install\ncd ..\n\n# Intel MPI 2021 (Update 2)\nIMPI_2021_VERSION=\"2021.4.0\"\n$COMMON_DIR/write_component_version.sh \"IMPI_2021\" ${IMPI_2021_VERSION}\nIMPI_2021_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/irc_nas/18186/l_mpi_oneapi_p_2021.4.0.441_offline.sh\n$COMMON_DIR/download_and_verify.sh $IMPI_2021_DOWNLOAD_URL \"cc4b7072c61d0bd02b1c431b22d2ea3b84b967b59d2e587e77a9e7b2c24f2a29\"\nbash l_mpi_oneapi_p_2021.4.0.441_offline.sh -s -a -s --eula accept\nmv ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/mpi ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\n\n# Setup module files for MPIs\nmkdir -p /usr/share/Modules/modulefiles/mpi/\n\n# MVAPICH2\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION}\n#%Module 1.0\n#\n#  MVAPICH2 ${MV2_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/mvapich2-${MV2_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/mvapich2-${MV2_VERSION}/lib\nprepend-path    MANPATH         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_BIN         /opt/mvapich2-${MV2_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/mvapich2-${MV2_VERSION}/include\nsetenv          MPI_LIB         /opt/mvapich2-${MV2_VERSION}/lib\nsetenv          MPI_MAN         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_HOME        /opt/mvapich2-${MV2_VERSION}\nEOF\n\n# OpenMPI\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION}\n#%Module 1.0\n#\n#  OpenMPI ${OMPI_VERSION}\n#\nconflict        mpi\nmodule load ${GCC_VERSION}\nprepend-path    PATH            /opt/openmpi-${OMPI_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/openmpi-${OMPI_VERSION}/lib\nprepend-path    MANPATH         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_BIN         /opt/openmpi-${OMPI_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/openmpi-${OMPI_VERSION}/include\nsetenv          MPI_LIB         /opt/openmpi-${OMPI_VERSION}/lib\nsetenv          MPI_MAN         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_HOME        /opt/openmpi-${OMPI_VERSION}\nEOF\n\n#IntelMPI-v2021\ncat << EOF >> /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_2021_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\nsetenv          MPI_BIN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/include\nsetenv          MPI_LIB         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/lib\nsetenv          MPI_MAN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}\nEOF\n\n# Create symlinks for modulefiles\nln -s /usr/share/Modules/modulefiles/mpi/mvapich2-${MV2_VERSION} /usr/share/Modules/modulefiles/mpi/mvapich2\nln -s /usr/share/Modules/modulefiles/mpi/openmpi-${OMPI_VERSION} /usr/share/Modules/modulefiles/mpi/openmpi\nln -s /usr/share/Modules/modulefiles/mpi/impi_${IMPI_2021_VERSION} /usr/share/Modules/modulefiles/mpi/impi-2021\n\n\n", "num_lines": 106}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install NCCL\nyum install -y rpm-build rpmdevtools\nNCCL_VERSION=\"2.11.4-1\"\n$COMMON_DIR/write_component_version.sh \"NCCL\" ${NCCL_VERSION}\nTARBALL=\"v${NCCL_VERSION}.tar.gz\"\nNCCL_DOWNLOAD_URL=https://github.com/NVIDIA/nccl/archive/refs/tags/${TARBALL}\npushd /tmp\nwget ${NCCL_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\npushd nccl-${NCCL_VERSION}\nmake -j src.build\nmake pkg.redhat.build\nrpm -i ./build/pkg/rpm/x86_64/libnccl-${NCCL_VERSION}+cuda11.4.x86_64.rpm\necho \"exclude=libnccl\" | sudo tee -a /etc/yum.conf\nrpm -i ./build/pkg/rpm/x86_64/libnccl-devel-${NCCL_VERSION}+cuda11.4.x86_64.rpm\necho \"exclude=libnccl-devel\" | sudo tee -a /etc/yum.conf\nrpm -i ./build/pkg/rpm/x86_64/libnccl-static-${NCCL_VERSION}+cuda11.4.x86_64.rpm\necho \"exclude=libnccl-static\" | sudo tee -a /etc/yum.conf\npopd\n\n# Install the nccl rdma sharp plugin\nmkdir -p /usr/local/nccl-rdma-sharp-plugins\ngit clone https://github.com/Mellanox/nccl-rdma-sharp-plugins.git\npushd nccl-rdma-sharp-plugins\n./autogen.sh\n./configure --prefix=/usr/local/nccl-rdma-sharp-plugins --with-cuda=/usr/local/cuda\nmake\nmake install\npopd\npopd\n\n# Build the nccl tests\nsource /etc/profile.d/modules.sh\nmodule load mpi/hpcx\nNCCL_TESTS_VERSION=\"2.13.3\"\nTARBALL=\"v${NCCL_TESTS_VERSION}.tar.gz\"\nNCCL_TESTS_DOWNLOAD_URL=\"https://github.com/NVIDIA/nccl-tests/archive/refs/tags/${TARBALL}\"\nwget ${NCCL_TESTS_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\npushd nccl-tests-${NCCL_TESTS_VERSION}\nmake MPI=1 MPI_HOME=${HPCX_MPI_DIR} CUDA_HOME=/usr/local/cuda\npopd\nmv nccl-tests-${NCCL_TESTS_VERSION} /opt/nccl-tests\nmodule unload mpi/hpcx\n\n# Remove installation files\nrm -rf /tmp/${TARBALL}\nrm -rf /tmp/nccl-${NCCL_VERSION}\n", "num_lines": 53}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nsed -i '/\\[main\\]/a no-auto-default=*' /etc/NetworkManager/NetworkManager.conf\n\n# update network config on reboot\nmkdir -p /lib/systemd/system/cloud-init-local.service.d/\ncat <<EOF > /lib/systemd/system/cloud-init-local.service.d/50-azure-clear-persistent-obj-pkl.conf\n[Service]\nExecStartPre=-/bin/sh -xc 'if [ -e /var/lib/cloud/instance/obj.pkl ]; then echo \"cleaning persistent cloud-init object\"; rm /var/lib/cloud/instance/obj.pkl; fi; exit 0'\nEOF\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Find distro\nfind_distro() {\n    local os=`cat /etc/os-release | awk 'match($0, /^NAME=\"(.*)\"/, result) { print result[1] }'`\n    if [[ $os == \"CentOS Linux\" ]]\n    then\n        local centos_distro=`find_centos_distro`\n        echo \"${os} ${centos_distro}\"\n    elif [[ $os == \"AlmaLinux\" ]]\n    then\n        local alma_distro=`find_alma_distro`\n        echo \"${os} ${alma_distro}\"\n    elif [[ $os == \"Ubuntu\" ]]\n    then\n        local ubuntu_distro=`find_ubuntu_distro`\n        echo \"${os} ${ubuntu_distro}\"\n    else\n        echo \"*** Error - invalid distro!\"\n        exit -1\n    fi\n}\n\n# Find CentOS distro\nfind_centos_distro() {\n    echo `cat /etc/redhat-release | awk '{print $4}'`\n}\n\n# Find Alma distro\nfind_alma_distro() {\n    echo `cat /etc/redhat-release | awk '{print $3}'`\n}\n\n# Find Ubuntu distro\nfind_ubuntu_distro() {\n    echo `cat /etc/os-release | awk 'match($0, /^PRETTY_NAME=\"(.*)\"/, result) { print result[1] }' | awk '{print $2}' | cut -d. -f1,2`\n}\n\ndistro=`find_distro`\necho \"Detected distro: ${distro}\"\n\nif [[ $distro == *\"CentOS Linux\"* ]] || [[ $distro == *\"AlmaLinux\"* ]]\nthen\n    # Sync yum and rpmdb after installing rpm's outside yum\n    yum history sync\nfi\n\n# Clear History\n# Stop syslog service\nsystemctl stop syslog.socket rsyslog\n# Delete sensitive log files\nrm -rf /var/log/audit/audit.log /var/log/secure /var/log/messages /var/log/auth.log /var/log/syslog\n# Clear contents of rest of systemd services related log files\nfor log in $(find /var/log/ -type f -name '*.log'); do cat /dev/null > $log; done\n\nrm -rf /var/lib/systemd/random-seed \nrm -rf /var/intel/ /var/cache/* /var/lib/cloud/instances/*\nrm -rf /var/lib/hyperv/.kvp_pool_0\nrm -f /etc/ssh/ssh_host_* /etc/*-\nrm -rf /tmp/ssh-* /tmp/yum* /tmp/tmp* /tmp/*.log* /tmp/*tenant* /tmp/*.gz\nrm -rf /tmp/nvidia* /tmp/MLNX* /tmp/ofed.conf /tmp/dkms* /tmp/*mlnx*\nrm -rf /run/cloud-init\nrm -rf /root/*\nrm -rf /usr/tmp/dnf*\n# rm -rf /etc/sudoers.d/*\n\nif systemctl is-active --quiet sku-customizations\nthen\n    # Stop the sku-customizations service\n    systemctl stop sku-customizations\nfi\n\n# Empty machine information\ncat /dev/null > /etc/machine-id\n\nif [[ $distro == *\"Ubuntu\"* ]]\nthen\n    apt-get clean\nelse\n    yum clean all\nfi\n\n# Zero out unused space to minimize actual disk usage\nfor part in $(awk '$3 == \"xfs\" {print $2}' /proc/mounts)\ndo\n    dd if=/dev/zero of=${part}/EMPTY bs=1M || true;\n    rm -f ${part}/EMPTY\ndone\nsync;\n\ncat /dev/null > ~/.bash_history\nexport HISTSIZE=0 && history -c && sync\n", "num_lines": 94}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nDEST_DIR=/opt/azurehpc/tools\nmkdir -p $DEST_DIR\n\nwget https://raw.githubusercontent.com/microsoft/lis-test/master/WS2012R2/lisa/tools/KVP/kvp_client.c\n\ncp ./kvp_client.c $DEST_DIR\n\ngcc $DEST_DIR/kvp_client.c -o $DEST_DIR/kvp_client\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nDEST_TEST_DIR=/opt/azurehpc/test\n\nmkdir -p $DEST_TEST_DIR\n\ncp $TEST_DIR/run-tests.sh $DEST_TEST_DIR\n\n#Test if nvcc is installed and if so install gpu-copy test.\nif test -f \"/usr/local/cuda/bin/nvcc\"; then\n\t#Compile the gpu-copy benchmark.\n\tNVCC=/usr/local/cuda/bin/nvcc\n\tcufile=\"$TEST_DIR/health_checks/NDv4/gpu-copy.cu\"\n\toutfile=\"$TEST_DIR/health_checks/NDv4/gpu-copy\"\n\n\t#Test if the default gcc compiler is new enough to compile gpu-copy.\n\t#If it is not then use the 9.2 compiler, that should be installed in\n\t#/opt.\n\tif [ $(gcc -dumpversion | cut -d. -f1) -gt 6 ]; then\n\t\t$NVCC -lnuma $cufile -o $outfile\n\telse\n\t\t$NVCC --compiler-bindir /opt/gcc-9.2.0/bin \\\n\t\t\t-lnuma $cufile -o $outfile\n\tfi\nfi\ncp -r $TEST_DIR/health_checks $DEST_TEST_DIR\n\nexit 0\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nDOWNLOAD_URL=$1\nDOWNLOADED_FILE_NAME=$(basename $1)\nFILE_CHECKSUM=$2\n\n# Find and verify checksum\nverify_checksum() {\n    local checksum=`sha256sum $1 | awk '{print $1}'`\n    if [[ $checksum == $2 ]]\n    then\n        echo \"Checksum verified!\"\n    else\n        echo \"*** Error - Checksum verification failed\"\n        exit -1\n    fi\n}\n\nif [ $# -eq 2 ]\nthen\n    wget --retry-connrefused --tries=3 --waitretry=5 $DOWNLOAD_URL\n    verify_checksum $(readlink -f $DOWNLOADED_FILE_NAME) $FILE_CHECKSUM\nelse\n    echo \"*** Error - Invalid inputs!\"\n    exit -1\nfi\n\nexit 0\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Find CentOS distro\nfind_centos_distro() {\n    echo `cat /etc/redhat-release | awk '{print $4}'`\n}\n\n# Find Ubuntu distro\nfind_ubuntu_distro() {\n    echo `cat /etc/os-release | awk 'match($0, /^PRETTY_NAME=\"(.*)\"/, result) { print result[1] }' | awk '{print $2}'`\n}\n\n# Find distro\nos=`cat /etc/os-release | awk 'match($0, /^NAME=\"(.*)\"/, result) { print result[1] }'`\nif [[ $os == \"CentOS Linux\" ]]\nthen\n    centos_distro=`find_centos_distro`\n    echo \"${os} ${centos_distro}\"\nelif [[ $os == \"Ubuntu\" ]]\nthen\n    ubuntu_distro=`find_ubuntu_distro`\n    echo \"${os} ${ubuntu_distro}\"\nelse\n    echo \"*** Error - invalid distro!\"\n    exit -1\nfi\n\nexit 0\n", "num_lines": 29}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n#\n# install rdma_rename with NAME_FIXED option\n#\n\npushd /tmp\nrdma_core_branch=stable-v34\ngit clone -b $rdma_core_branch https://github.com/linux-rdma/rdma-core.git\npushd rdma-core\nbash build.sh\ncp build/bin/rdma_rename /usr/sbin/rdma_rename_$rdma_core_branch\npopd\nrm -rf rdma-core\npopd\n\n#\n# setup systemd service\n#\n\ncat <<EOF >/usr/sbin/azure_persistent_rdma_naming.sh\n#!/bin/bash\n\nrdma_rename=/usr/sbin/rdma_rename_${rdma_core_branch}\n\nan_index=0\nib_index=0\n\nfor old_device in \\$(ibdev2netdev -v | sort -n | cut -f2 -d' '); do\n\n\tlink_layer=\\$(ibv_devinfo -d \\$old_device | sed -n 's/^[\\ \\t]*link_layer:[\\ \\t]*\\([a-zA-Z]*\\)\\$/\\1/p')\n\t\n\tif [ \"\\$link_layer\" = \"InfiniBand\" ]; then\n\t\t\n\t\t\\$rdma_rename \\$old_device NAME_FIXED mlx5_ib\\${ib_index}\n\t\tib_index=\\$((\\$ib_index + 1))\n\t\t\n\telif [ \"\\$link_layer\" = \"Ethernet\" ]; then\n\t\n\t\t\\$rdma_rename \\$old_device NAME_FIXED mlx5_an\\${an_index}\n\t\tan_index=\\$((\\$an_index + 1))\n\t\t\n\telse\n\t\n\t\techo \"Unknown device type for \\$old_device - \\$device_type.\"\n\t\t\n\tfi\n\t\ndone\nEOF\nchmod 755 /usr/sbin/azure_persistent_rdma_naming.sh\n\ncat <<EOF >/etc/systemd/system/azure_persistent_rdma_naming.service\n[Unit]\nDescription=Azure persistent RDMA naming\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart=/usr/sbin/azure_persistent_rdma_naming.sh\nRemainAfterExit=true\nStandardOutput=journal\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable azure_persistent_rdma_naming.service\nsystemctl start azure_persistent_rdma_naming.service\n", "num_lines": 71}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\n# Install gcc 8.2\n\nwget ftp://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2\ntar -xvf gmp-6.1.0.tar.bz2\ncd ./gmp-6.1.0\n./configure && make -j$(nproc) &&  make install\ncd ..\n\nwget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2\ntar -xvf mpfr-3.1.4.tar.bz2\ncd mpfr-3.1.4\n./configure && make -j$(nproc) &&  make install\ncd ..\n\nwget ftp://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz\ntar -xvf mpc-1.0.3.tar.gz\ncd mpc-1.0.3\n./configure && make -j$(nproc) &&  make install\ncd ..\n\n# install gcc 8.2\nwget https://ftp.gnu.org/gnu/gcc/gcc-8.2.0/gcc-8.2.0.tar.gz\ntar -xvf gcc-8.2.0.tar.gz\ncd gcc-8.2.0\n./configure --disable-multilib --prefix=/opt/gcc-8.2.0 && make -j$(nproc) && make install\ncd ..\n\n\n# create modulefile\ncat << EOF >> /usr/share/Modules/modulefiles/gcc-8.2.0\n#%Module 1.0\n#\n#  GCC 8.2.0\n#\n\nprepend-path    PATH            /opt/gcc-8.2.0/bin\nprepend-path    LD_LIBRARY_PATH /opt/gcc-8.2.0/lib64\nsetenv          CC              /opt/gcc-8.2.0/bin/gcc\nsetenv          GCC             /opt/gcc-8.2.0/bin/gcc\nEOF\n\n", "num_lines": 45}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nMODULE_FILES_DIRECTORY=$1\n\n# Install gcc 9.2\nGMP_DOWNLOAD_URL=http://gcc.gnu.org/pub/gcc/infrastructure/gmp-6.1.0.tar.bz2\n$COMMON_DIR/download_and_verify.sh $GMP_DOWNLOAD_URL \"498449a994efeba527885c10405993427995d3f86b8768d8cdf8d9dd7c6b73e8\"\ntar -xvf gmp-6.1.0.tar.bz2\ncd ./gmp-6.1.0\n./configure && make -j$(nproc) &&  make install\ncd ..\n\nMPFR_DOWNLOAD_URL=http://gcc.gnu.org/pub/gcc/infrastructure/mpfr-3.1.4.tar.bz2\n$COMMON_DIR/download_and_verify.sh $MPFR_DOWNLOAD_URL \"d3103a80cdad2407ed581f3618c4bed04e0c92d1cf771a65ead662cc397f7775\"\ntar -xvf mpfr-3.1.4.tar.bz2\ncd mpfr-3.1.4\n./configure && make -j$(nproc) &&  make install\ncd ..\n\nMPC_DOWNLOAD_URL=http://gcc.gnu.org/pub/gcc/infrastructure/mpc-1.0.3.tar.gz\n$COMMON_DIR/download_and_verify.sh $MPC_DOWNLOAD_URL \"617decc6ea09889fb08ede330917a00b16809b8db88c29c31bfbb49cbf88ecc3\"\ntar -xvf mpc-1.0.3.tar.gz\ncd mpc-1.0.3\n./configure && make -j$(nproc) &&  make install\ncd ..\n\n# install gcc 9.2\nGCC_VERSION=\"9.2.0\"\nGCC_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/gcc-${GCC_VERSION}.tar.gz\n$COMMON_DIR/write_component_version.sh \"GCC\" ${GCC_VERSION}\n$COMMON_DIR/download_and_verify.sh $GCC_DOWNLOAD_URL \"a931a750d6feadacbeecb321d73925cd5ebb6dfa7eff0802984af3aef63759f4\"\ntar -xvf gcc-${GCC_VERSION}.tar.gz\ncd gcc-${GCC_VERSION}\n./configure --disable-multilib --prefix=/opt/gcc-${GCC_VERSION} && make -j$(nproc) && make install\ncd ..\n\n# create modulefile\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/gcc-${GCC_VERSION}\n#%Module 1.0\n#\n#  GCC ${GCC_VERSION}\n#\nprepend-path    PATH            /opt/gcc-${GCC_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/gcc-${GCC_VERSION}/lib64\nsetenv          CC              /opt/gcc-${GCC_VERSION}/bin/gcc\nsetenv          GCC             /opt/gcc-${GCC_VERSION}/bin/gcc\nEOF\n\n# cleanup downloaded tarballs\nrm -rf *.tar.gz *tar.bz2\n", "num_lines": 52}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n\nset -e\n\nAZHC_VERSION=v0.2.3\n\nDEST_TEST_DIR=/opt/azurehpc/test\nAZHC_DIR=/opt/azurehpc/test/azurehpc-health-checks\n\nmkdir -p $DEST_TEST_DIR\n\npushd $DEST_TEST_DIR\n\ngit clone https://github.com/Azure/azurehpc-health-checks.git --branch $AZHC_VERSION\n\npushd azurehpc-health-checks\n\n# install NHC\n./install-nhc.sh\n\npopd\npopd\n\n$COMMON_DIR/write_component_version.sh \"AZ_HEALTH_CHECKS\" ${AZHC_VERSION}\n", "num_lines": 26}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nDESTINATION_DIR='/opt/azurehpc/diagnostics'\nLATEST_RELEASE_API_URL=\"https://api.github.com/repos/Azure/azhpc-diagnostics/releases/latest\"\n\n# example (after grep): \n# \"tarball_url\": \"https://api.github.com/repos/Azure/azhpc-diagnostics/tarball/hpcdiag-20201201\",\nDOWNLOAD_URL=$(curl -s \"$LATEST_RELEASE_API_URL\" | grep 'tarball_url' | cut -d\\\" -f4)\n\n# not using download_and_verify.sh because github doesn't provide a checksum\nwget \"$DOWNLOAD_URL\"\nDOWNLOADED_FILE_NAME=$(basename \"$DOWNLOAD_URL\")\n\nTARBALL_FILES=$(tar -xzvf \"$DOWNLOADED_FILE_NAME\")\nUNPACK_DIR=$(echo \"$TARBALL_FILES\" | head -1)\n\nsudo mkdir -p \"$DESTINATION_DIR\"\nsudo cp \"$UNPACK_DIR/Linux/src/gather_azhpc_vm_diagnostics.sh\" \"$DESTINATION_DIR\"\n\nrm -r \"$DOWNLOADED_FILE_NAME\" \"$UNPACK_DIR\"\n", "num_lines": 22}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"2021.1.1.52\"\nMKL_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/irc_nas/17402/l_onemkl_p_${VERSION}_offline.sh\n$COMMON_DIR/write_component_version.sh \"INTEL_oneMKL\" $VERSION\n$COMMON_DIR/download_and_verify.sh $MKL_DOWNLOAD_URL \"818b6bd9a6c116f4578cda3151da0612ec9c3ce8b2c8a64730d625ce5b13cc0c\"\nsudo bash l_onemkl_p_${VERSION}_offline.sh -s -a -s --eula accept\n", "num_lines": 9}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Cuda\nNVIDIA_VERSION=\"470.82.01\"\nCUDA_VERSION=\"11.4.3\"\n$COMMON_DIR/write_component_version.sh \"CUDA\" ${CUDA_VERSION}\nCUDA_URL=https://developer.download.nvidia.com/compute/cuda/${CUDA_VERSION}/local_installers/cuda_${CUDA_VERSION}_${NVIDIA_VERSION}_linux.run\n$COMMON_DIR/download_and_verify.sh $CUDA_URL \"749183821ffc051e123f12ebdeb171b263d55b86f0dd7c8f23611db1802d6c37\"\nchmod +x cuda_${CUDA_VERSION}_${NVIDIA_VERSION}_linux.run\nsh cuda_${CUDA_VERSION}_${NVIDIA_VERSION}_linux.run --silent\necho 'export PATH=$PATH:/usr/local/cuda/bin' | sudo tee -a /etc/bash.bashrc\necho 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64' | sudo tee -a /etc/bash.bashrc\n\n# Nvidia driver\nNVIDIA_DRIVER_URL=https://download.nvidia.com/XFree86/Linux-x86_64/${NVIDIA_VERSION}/NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run\n$COMMON_DIR/download_and_verify.sh $NVIDIA_DRIVER_URL \"ad78fc2b29b8f498015277e30ae42530b61fecc298706bc0e9c193ee5e9c0660\"\nbash NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run --silent --dkms\n$COMMON_DIR/write_component_version.sh \"NVIDIA\" ${NVIDIA_VERSION}\n", "num_lines": 20}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Place the topology file in /opt/microsoft\nsudo mkdir -p /opt/microsoft\nsudo bash -c \"cat > /opt/microsoft/ndv4-topo.xml\" <<'EOF'\n<system version=\"1\">\n  <cpu numaid=\"0\" affinity=\"0000ffff,0000ffff\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"23\" modelid=\"49\">\n    <pci busid=\"ffff:ff:01.0\" class=\"0x060400\" link_speed=\"16 GT/s\" link_width=\"16\">\n      <pci busid=\"0001:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0101:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0002:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0102:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n    </pci>\n  </cpu>\n  <cpu numaid=\"1\" affinity=\"0000ffff,0000ffff\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"23\" modelid=\"49\">\n    <pci busid=\"ffff:ff:02.0\" class=\"0x060400\" link_speed=\"16 GT/s\" link_width=\"16\">\n      <pci busid=\"0003:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0103:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0004:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0104:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n    </pci>\n  </cpu>\n  <cpu numaid=\"2\" affinity=\"0000ffff,0000ffff\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"23\" modelid=\"49\">\n      <pci busid=\"ffff:ff:03.0\" class=\"0x060400\" link_speed=\"16 GT/s\" link_width=\"16\">\n      <pci busid=\"000b:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0105:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"000c:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0106:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n    </pci>\n  </cpu>\n  <cpu numaid=\"3\" affinity=\"0000ffff,0000ffff\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"23\" modelid=\"49\">\n    <pci busid=\"ffff:ff:04.0\" class=\"0x060400\" link_speed=\"16 GT/s\" link_width=\"16\">\n      <pci busid=\"000d:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0107:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"000e:00:00.0\" class=\"0x030200\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n      <pci busid=\"0108:00:00.0\" class=\"0x020700\" link_speed=\"16 GT/s\" link_width=\"16\"/>\n    </pci>\n  </cpu>\n</system>\nEOF\n\n# Link the NDv4 topology file into /opt/microsoft/ndv4/\n# Topology file in /opt/microsoft/ndv4-topo.xml will eventually be deleted\nsudo mkdir -p /opt/microsoft/ndv4\nln -s /opt/microsoft/ndv4-topo.xml /opt/microsoft/ndv4/topo.xml\n\n\n# Place NCv4 topology and graph files under /opt/microsoft/ncv4\nsudo mkdir -p /opt/microsoft/ncv4\nsudo bash -c \"cat > /opt/microsoft/ncv4/topo.xml\" <<'EOF'\n<system version=\"1\">\n  <cpu numaid=\"0\" affinity=\"00000000,00000000,00ffffff\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"175\" modelid=\"1\">\n    <pci busid=\"0001:00:00.0\" class=\"0x030200\" vendor=\"0x10de\" device=\"0x20b5\" subsystem_vendor=\"0x10de\" subsystem_device=\"0x1533\" link_speed=\"\" link_width=\"0\">\n      <gpu dev=\"0\" sm=\"80\" rank=\"0\" gdr=\"1\">\n        <nvlink target=\"0002:00:00.0\" count=\"12\" tclass=\"0x030200\"/>\n      </gpu>\n    </pci>\n    <nic>\n      <net name=\"eth0\" dev=\"0\" speed=\"100000\" port=\"0\" latency=\"0.000000\" guid=\"0x0\" maxconn=\"65536\" gdr=\"0\"/>\n    </nic>\n  </cpu>\n  <cpu numaid=\"1\" affinity=\"00000000,0000ffff,ff000000\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"175\" modelid=\"1\">\n    <pci busid=\"0002:00:00.0\" class=\"0x030200\" vendor=\"0x10de\" device=\"0x20b5\" subsystem_vendor=\"0x10de\" subsystem_device=\"0x1533\" link_speed=\"\" link_width=\"0\">\n      <gpu dev=\"1\" sm=\"80\" rank=\"1\" gdr=\"1\">\n        <nvlink target=\"0001:00:00.0\" count=\"12\" tclass=\"0x030200\"/>\n      </gpu>\n    </pci>\n  </cpu>\n  <cpu numaid=\"2\" affinity=\"000000ff,ffff0000,00000000\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"175\" modelid=\"1\">\n    <pci busid=\"0003:00:00.0\" class=\"0x030200\" vendor=\"0x10de\" device=\"0x20b5\" subsystem_vendor=\"0x10de\" subsystem_device=\"0x1533\" link_speed=\"\" link_width=\"0\">\n      <gpu dev=\"2\" sm=\"80\" rank=\"2\" gdr=\"1\">\n        <nvlink target=\"0004:00:00.0\" count=\"12\" tclass=\"0x030200\"/>\n      </gpu>\n    </pci>\n  </cpu>\n  <cpu numaid=\"3\" affinity=\"ffffff00,00000000,00000000\" arch=\"x86_64\" vendor=\"AuthenticAMD\" familyid=\"175\" modelid=\"1\">\n    <pci busid=\"0004:00:00.0\" class=\"0x030200\" vendor=\"0x10de\" device=\"0x20b5\" subsystem_vendor=\"0x10de\" subsystem_device=\"0x1533\" link_speed=\"\" link_width=\"0\">\n      <gpu dev=\"3\" sm=\"80\" rank=\"3\" gdr=\"1\">\n        <nvlink target=\"0003:00:00.0\" count=\"12\" tclass=\"0x030200\"/>\n      </gpu>\n    </pci>\n  </cpu>\n</system>\nEOF\n\n\nsudo bash -c \"cat > /opt/microsoft/ncv4/graph.xml\" <<'EOF'\n<graphs version=\"1\">\n  <graph id=\"0\" pattern=\"4\" crossnic=\"0\" nchannels=\"2\" speedintra=\"12\" speedinter=\"12\" latencyinter=\"0\" typeintra=\"SYS\" typeinter=\"PIX\" samechannels=\"0\">\n    <channel>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"3\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"1\"/>\n    </channel>\n  </graph>\n  <graph id=\"1\" pattern=\"1\" crossnic=\"0\" nchannels=\"4\" speedintra=\"12\" speedinter=\"12\" latencyinter=\"0\" typeintra=\"SYS\" typeinter=\"PIX\" samechannels=\"0\">\n    <channel>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"3\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"2\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"0\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"1\"/>\n    </channel>\n  </graph>\n  <graph id=\"2\" pattern=\"3\" crossnic=\"0\" nchannels=\"4\" speedintra=\"12\" speedinter=\"12\" latencyinter=\"0\" typeintra=\"SYS\" typeinter=\"PIX\" samechannels=\"0\">\n    <channel>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"3\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"2\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"1\"/>\n      <gpu dev=\"0\"/>\n    </channel>\n    <channel>\n      <gpu dev=\"2\"/>\n      <gpu dev=\"3\"/>\n      <gpu dev=\"0\"/>\n      <gpu dev=\"1\"/>\n    </channel>\n  </graph>\n</graphs>\nEOF\n", "num_lines": 158}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n## Copy customization scripts to /opt/azurehpc/customizations\nmkdir -p /opt/azurehpc/customizations\ncp $COMMON_DIR/../customizations/* /opt/azurehpc/customizations\n\n## Copy topology files to /opt/microsoft\nmkdir -p /opt/microsoft\ncp $COMMON_DIR/../topology/* /opt/microsoft\n\n## Systemd service for setting up appropriate customizations based on SKU\ncat <<EOF >/usr/sbin/setup_sku_customizations.sh\n#!/bin/bash\n\nmetadata_endpoint=\"http://169.254.169.254/metadata/instance?api-version=2019-06-04\"\nvmSize=\\$(curl -H Metadata:true \\$metadata_endpoint | jq -r \".compute.vmSize\")\nvmSize=\\$(echo \"\\$vmSize\" | awk '{print tolower(\\$0)}')\n\n## Topo file setup based on SKU\ncase \\$vmSize in\n    standard_nc*ads_a100_v4)\n        /opt/azurehpc/customizations/ncv4.sh;;\n    \n    standard_nd96*v4)\n        /opt/azurehpc/customizations/ndv4.sh;;\n        \n    standard_nd40rs_v2)\n        /opt/azurehpc/customizations/ndv2.sh;;\n\n    standard_hb176*v4)\n        /opt/azurehpc/customizations/hbv4.sh;;\n\n    standard_nd96is*_h100_v5)\n        /opt/azurehpc/customizations/ndv5.sh;;\n\n    *) echo \"No SKU customization for \\$vmSize\";;\nesac\nEOF\nchmod 755 /usr/sbin/setup_sku_customizations.sh\n\n## Systemd service for removing SKU based customizations\ncat <<EOF >/usr/sbin/remove_sku_customizations.sh\n#!/bin/bash\n\n# Stop nvidia fabric manager\nif systemctl is-active --quiet nvidia-fabricmanager\nthen\n    systemctl stop nvidia-fabricmanager\n    systemctl disable nvidia-fabricmanager\nfi\n\n# Stop nvme raid service\n# if systemctl is-active --quiet nvme-raid\n# then\n#     systemctl stop nvme-raid\n#     systemctl disable nvme-raid\n# fi\n\n# Remove NVIDIA peer memory module\nif lsmod | grep nvidia_peermem &> /dev/null\nthen \n    rmmod nvidia_peermem\nfi\n\n# Clear topo and graph files\nrm -rf /opt/microsoft/ncv4\nrm -rf /opt/microsoft/ndv2\nrm -rf /opt/microsoft/ndv4\nrm -rf /opt/microsoft/ndv5\n\n# Clear contents of nccl.conf\ncat /dev/null > /etc/nccl.conf\n\nEOF\nchmod 755 /usr/sbin/remove_sku_customizations.sh\n\ncat <<EOF >/etc/systemd/system/sku-customizations.service\n[Unit]\nDescription=Customizations based on SKU\nAfter=network.target\n\n[Service]\nType=oneshot\nExecStart=/usr/sbin/setup_sku_customizations.sh\nExecStop=/usr/sbin/remove_sku_customizations.sh\nRemainAfterExit=true\nStandardOutput=journal\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable sku-customizations\nsystemctl start sku-customizations\nsystemctl is-active --quiet sku-customizations\n\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"SKU Customizations service Inactive!\"\n    exit ${error_code}\nfi\n", "num_lines": 104}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n############################################################################\n# @Brief\t: Write the component and its version\n#\n# @Args\t\t: (1) Component Name\n# \t\t\t  (2) Version\n############################################################################\n\nset -e\n\nDEST_DIR=/opt/azurehpc\n\nmkdir -p $DEST_DIR\n\necho $1=$2 | sudo tee -a $DEST_DIR/component_versions.txt\n\nexit 0\n", "num_lines": 18}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n## Setup NVME devices\n# /opt/azurehpc/customizations/setup_nvme.sh\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Place NCv4 topology and graph files under /opt/microsoft/ncv4\nmkdir -p /opt/microsoft/ncv4\n\n# Link the NCv4 topology and graph files into /opt/microsoft/ncv4/\nln -sf /opt/microsoft/ncv4-topo.xml /opt/microsoft/ncv4/topo.xml\nln -sf /opt/microsoft/ncv4-graph.xml /opt/microsoft/ncv4/graph.xml\n\n## Set NCCL configuration file for NCv4\nbash -c \"cat > /etc/nccl.conf\" <<'EOF'\nNCCL_TOPO_FILE=/opt/microsoft/ncv4/topo.xml\nNCCL_GRAPH_FILE=/opt/microsoft/ncv4/graph.xml\nEOF\n\n## Setup NVME devices\n# if [ ! -f /etc/systemd/system/nvme-raid.service ]; then\n#     /opt/azurehpc/customizations/setup_nvme.sh\n# fi\n\n# ## NVME raid service\n# systemctl enable nvme-raid\n# systemctl start nvme-raid\n# systemctl is-active --quiet nvme-raid\n\n# error_code=$?\n# if [ ${error_code} -ne 0 ]\n# then\n#     echo \"Failed to setup/ mount NVMe devices!\"\n#     exit ${error_code}\n# fi\n", "num_lines": 33}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Place NDv2 topology file under /opt/microsoft/ndv2\nmkdir -p /opt/microsoft/ndv2\n\n# Link the NDv2 topology file into /opt/microsoft/ndv2/\nln -sf /opt/microsoft/ndv2-topo.xml /opt/microsoft/ndv2/topo.xml\n\n## Set NCCL configuration file for NDv2\nbash -c \"cat > /etc/nccl.conf\" <<'EOF'\nNCCL_TOPO_FILE=/opt/microsoft/ndv2/topo.xml\nEOF\n", "num_lines": 14}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Place NDv4 topo file under /opt/microsoft/ndv4\nmkdir -p /opt/microsoft/ndv4\n\n# Link the NDv4 topology file into /opt/microsoft/ndv4/\nln -sf /opt/microsoft/ndv4-topo.xml /opt/microsoft/ndv4/topo.xml\n\n## Set NCCL configuration file for NDv4\nbash -c \"cat > /etc/nccl.conf\" <<'EOF'\nNCCL_IB_PCI_RELAXED_ORDERING=1\nNCCL_TOPO_FILE=/opt/microsoft/ndv4/topo.xml\nEOF\n\n## NVIDIA Fabric manager\nsystemctl enable nvidia-fabricmanager\nsystemctl start nvidia-fabricmanager\nsystemctl is-active --quiet nvidia-fabricmanager\n\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"NVIDIA Fabic Manager Inactive!\"\n    exit ${error_code}\nfi\n\n## load nvidia-peermem module\nmodprobe nvidia-peermem\n\n# ## Setup NVME devices\n# if [ ! -f /etc/systemd/system/nvme-raid.service ]; then\n#     /opt/azurehpc/customizations/setup_nvme.sh\n# fi\n\n# ## NVME raid service\n# systemctl enable nvme-raid\n# systemctl start nvme-raid\n# systemctl is-active --quiet nvme-raid\n\n# error_code=$?\n# if [ ${error_code} -ne 0 ]\n# then\n#     echo \"Failed to setup/ mount NVMe devices!\"\n#     exit ${error_code}\n# fi\n", "num_lines": 47}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Place NDv5 customizations under /opt/microsoft/ndv5\nmkdir -p /opt/microsoft/ndv5\n\n# Link the NDv5 topology file into /opt/microsoft/ndv5/\nln -sf /opt/microsoft/ndv5-topo.xml /opt/microsoft/ndv5/topo.xml\n\n## Set NCCL configuration file for NDv5\nbash -c \"cat > /etc/nccl.conf\" <<'EOF'\nNCCL_IB_PCI_RELAXED_ORDERING=1\nNCCL_TOPO_FILE=/opt/microsoft/ndv5/topo.xml\nEOF\n\n## NVIDIA Fabric manager\nsystemctl enable nvidia-fabricmanager\nsystemctl start nvidia-fabricmanager\nsystemctl is-active --quiet nvidia-fabricmanager\n\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"NVIDIA Fabic Manager Inactive!\"\n    exit ${error_code}\nfi\n\n## load nvidia-peermem module\nmodprobe nvidia-peermem\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n## Systemd service for setting up nvme devices\ncat <<EOF >/usr/sbin/nvme_raid_start.sh\n#!/bin/bash\n\nnvme_disks_name=\\`ls /dev/nvme*n1\\`\nnvme_disks=\\`ls -latr /dev/nvme*n1 | wc -l\\`\n\nif [ \"\\$nvme_disks\" == \"0\" ]\nthen\n    exit 1\nfi\n\n# Stop any existing RAID array\nif [ -e /dev/md128 ]; then\n    mdadm --stop /dev/md128\n    for dev in \\$nvme_disks_name; do\n        # Zeroing block for the NVMe device\n        mdadm --zero-superblock \\$dev\n    done\nfi\n\n# Create the RAID array\nmdadm --create /dev/md128 --level=0 --raid-devices=\\$nvme_disks \\$nvme_disks_name\n# Wait until device exists \nudevadm settle\n\n# Create the filesystem if it doesn't exist\nif [ -z \"\\$(blkid -o value -s UUID /dev/md128)\" ]; then\n    echo \"Creating filesystem on /dev/md128...\"\n\n    # Create a file system\n    mkfs.xfs /dev/md128\nfi\n\nmdadm --detail --scan >> /etc/mdadm/mdadm.conf\n\nmkdir -p /mnt/resource_nvme\n\n# Add the entry to /etc/fstab if it doesn't exist\nif ! grep -q \"/dev/md128 /mnt/resource_nvme xfs\" /etc/fstab; then\n    echo \"/dev/md128 /mnt/resource_nvme xfs\" >> /etc/fstab\nfi\n\n# Mount the file system\nmount /dev/md128 /mnt/resource_nvme\nchmod 777 /mnt/resource_nvme\n\nEOF\nchmod 755 /usr/sbin/nvme_raid_start.sh\n\ncat <<EOF >/usr/sbin/nvme_raid_stop.sh\n#!/bin/bash\n\n# Unmount the file system\nif mountpoint -q /mnt/resource_nvme; then\n    umount /mnt/resource_nvme\nfi\n\n# Clear the fstab entry\nsed -i \"/\\/dev\\/md128 \\/mnt\\/resource_nvme xfs/d\" /etc/fstab\n\n\n# Stop the RAID array\nif [ -e /dev/md128 ]; then\n    mdadm --stop /dev/md128\n    \n    nvme_disks_name=\\`ls /dev/nvme*n1\\`\n    for dev in \\$nvme_disks_name; do\n        mdadm --zero-superblock \\$dev\n    done\n\n    sed -i '/ARRAY \\/dev\\/md128/d' /etc/mdadm/mdadm.conf\nfi\n\nEOF\nchmod 755 /usr/sbin/nvme_raid_stop.sh\n\ncat <<EOF >/etc/systemd/system/nvme-raid.service\n[Unit]\nDescription=Setup NVMe RAID array\nAfter=local-fs.target\n\n[Service]\nType=oneshot\nExecStart=/usr/sbin/nvme_raid_start.sh\nExecStop=/usr/sbin/nvme_raid_stop.sh\nRemainAfterExit=yes\nStandardOutput=journal\n\n[Install]\nWantedBy=multi-user.target\nEOF\n", "num_lines": 96}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndistro=`./../common/extract_distro.sh`\nif [ $? -eq 0 ]\nthen\n    echo \"Detected distro: ${distro}\"\nelse\n    echo \"*** Error - invalid distro!\"\n    exit -1\nfi\n\nif [[ $distro == \"CentOS Linux 7.6.1810\" ]]\nthen\n    pushd \"../centos/centos-7.x/centos-7.6-hpc\"\nelif [[ $distro == \"CentOS Linux 7.7.1908\" ]]\nthen\n    pushd \"../centos/centos-7.x/centos-7.7-hpc\"\nelif [[ $distro == \"CentOS Linux 8.1.1911\" ]]\nthen\n    pushd \"../centos/centos-8.x/centos-8.1-hpc\"\nelif [[ $distro == \"Ubuntu 18.04.4\" ]]\nthen\n    pushd \"../ubuntu/ubuntu-18.04-hpc\"\nelse\n    echo \"*** Error - unsupported distro!\"\n    exit -1\nfi\n\n./install_mellanoxofed.sh\npopd\n\nexit 0\n", "num_lines": 33}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndistro=`./../common/extract_distro.sh`\nif [ $? -eq 0 ]\nthen\n    echo \"Detected distro: ${distro}\"\nelse\n    echo \"*** Error - invalid distro!\"\n    exit -1\nfi\n\nif [[ $distro == \"Ubuntu 18.04.4\" ]]\nthen\n    pushd \"../ubuntu/ubuntu-18.04-hpc\"\nelse\n    echo \"*** Error - unsupported distro!\"\n    exit -1\nfi\n\n./install_nvidiagpudriver.sh\npopd\n\nexit 0\n", "num_lines": 24}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable firewalld\n\n# Update memory limits\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\n# Enable reclaim mode\necho \"vm.zone_reclaim_mode = 1\" >> /etc/sysctl.conf\n#echo \"net.ipv4.neigh.default.gc_thresh1 = 4096\" >> /etc/sysctl.conf\n#echo \"net.ipv4.neigh.default.gc_thresh2 = 8192\" >> /etc/sysctl.conf\n#echo \"net.ipv4.neigh.default.gc_thresh3 = 16384\" >> /etc/sysctl.conf\n#echo \"sunrpc.tcp_max_slot_table_entries = 128\" >> /etc/sysctl.conf\nsysctl -p\n\n# on SUSE sunrpc get automatically loaded with nfs-client\n# if you have problems psl. look at https://www.suse.com/support/kb/doc/?id=000019178\n\n# Remove auoms if exists - Prevent CPU utilization by auoms\nif zypper se --installed-only azsec-monitor >/dev/null 2>&1; then zypper --non-interactive remove -y azsec-monitor; fi\n\n# Update WALinuxAgent - for IPoIB\nzypper --non-interactive update -y python-azure-agent\n\n# Configure WALinuxAgent\n# EnableRDMA=y is already set by default within the SLE HPC image\n\ncat << EOF | tee -a /etc/waagent.conf\n# default 6\nExtensions.GoalStatePeriod=300\n# default 30\nOS.RemovePersistentNetRulesPeriod=300\n# default 30\nOS.MonitorDhcpClientRestartPeriod=60\n# default 30\nProvisioning.MonitorHostNamePeriod=60\nEOF\nsystemctl restart waagent\n$COMMON_DIR/write_component_version.sh \"WAAGENT\" $(waagent --version | head -n 1 | awk -F' ' '{print $1}' | awk -F- '{print $2}')\n\n# NFS read-ahead limit should be ok, no need for change\n# check settings with: cat /sys/class/bdi/*/read_ahead_kb\n# https://learn.microsoft.com/en-us/azure/azure-netapp-files/performance-linux-nfs-read-ahead\n\n", "num_lines": 53}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n## AMD provides RPM packages, so in theory no need to use tarballs,\n## but there is no way to get around the licence section at the website\n## https://developer.amd.com/amd-aocl/#downloads\n## there are two options, gcc 11.1 or AOCC3.2\n## aocl-linux-aocc- 3.1.0-1.x86_64.rpm\n## aocl-linux-gcc-3.1.0-1.x86_64.rpm\n## do be able to download you need to agree to licence\n#\n# Additionally, AMD provides the Spack (https://spack.io/) recipes for optimally installing BLIS,\n# libFLAME, ScaLAPACK, LibM, FFTW, and Sparse libraries\n\nINSTALL_PREFIX=/opt/amd\nmkdir -p ${INSTALL_PREFIX}\n\nTARBALL=$(basename $AOCL_DOWNLOAD_URL)\n\n# TODO: this seems a workaround to accept the licence prior download\n# should be fixed in readme and made be more general e.g. prior download of the rpm and not the tarball\n$COMMON_DIR/download_and_verify.sh $AOCL_DOWNLOAD_URL $AOCL_CHKSUM\ntar -xvf ${TARBALL}\n\ncd aocl-linux-aocc-${AOCL_VERSION}\n./install.sh -t amd -l blis fftw libflame -i lp64\ncp -r amd/${AOCL_VERSION}/* ${INSTALL_PREFIX}\ncd .. && rm -rf aocl-linux-aocc-${AOCL_VERSION} ${TARBALL}\n\n$COMMON_DIR/write_component_version.sh \"AOCL\" ${AOCL_VERSION}\n\n# Setup module files for AMD Libraries\n# SUSE HPC uses lmod by default\nmkdir -p ${MODULE_FILES_DIRECTORY}/amd/\n\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/amd/aocl-${AOCL_VERSION}\n\n#%Module 1.0\n#\n#  AOCL\n#\nprepend-path    LD_LIBRARY_PATH   ${INSTALL_PREFIX}/lib\nsetenv          AMD_FFTW_INCLUDE  ${INSTALL_PREFIX}/include\nEOF\n\n# Create symlinks for modulefiles\nln -sf $(readlink --canonicalize ${MODULE_FILES_DIRECTORY}/amd/aocl-${AOCL_VERSION}) ${MODULE_FILES_DIRECTORY}/amd/aocl\n\n", "num_lines": 49}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install DCGM\n\n# workaround to create group for serviceUser=nvidia-dcgm\n# as the package expects that the variable \"USERGROUPS_ENAB\" in /etc/login.defs is set to yes\n# in oder that the useradd create the group too, but the SUSE default is \"no\", so we would change the\n# variable or simply use the parameter -U\n# wrong cmd: useradd -r -M -s /usr/sbin/nologin ${serviceUser}\n# right cmd: useradd -r -M -U -s /usr/sbin/nologin ${serviceUser}\n# see: man useradd\n# bug reported to Nvidia\nserviceUser=\"nvidia-dcgm\"\n\n#check if user exists, if not create it\nif ! id $serviceUser &>/dev/null; then\n   useradd -r -M -U -s /usr/sbin/nologin ${serviceUser}\nfi\nzypper --non-interactive install -y -l datacenter-gpu-manager = ${DCGM_VERSION}\n\nsystemctl --now enable nvidia-dcgm\n\n# Check if the service is active\nsystemctl is-active --quiet nvidia-dcgm\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"DCGM is inactive!\"\n    exit ${error_code}\nfi\n\n# to verify the installation we can query the system\n# You should see a listing of all supported GPUs (and any NVSwitches) found in the system:\n# dcgmi discovery -l\n\n$COMMON_DIR/write_component_version.sh \"DCGM\" ${DCGM_VERSION}\n", "num_lines": 38}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install docker\nzypper --non-interactive in -y -l docker\n\nDOCKER_VERSION=$(rpm -q --qf=\"%{VERSION}\" docker)\n\n# Ensure the Docker service is running\nsystemctl --now enable docker\n\n# if experimental is needed\n#zypper modifyrepo --enable libnvidia-container-experimental\n\nzypper --non-interactive install -y -l --replacefiles nvidia-docker2 nvidia-container-runtime\n\nsystemctl restart docker\n\n# Test with\n#docker run --rm --gpus all nvidia/cuda:11.0.3-base-ubuntu20.04 nvidia-smi\n\n# Write the docker version to components file\n$COMMON_DIR/write_component_version.sh \"NVIDIA-DOCKER\" ${DOCKER_VERSION}\n", "num_lines": 24}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n# With SLE HPC 15 SP4 we have gcc7 and gcc11 provided as the base compiler toolchain\n# and requires lua-lmod to supply environment module support.\n# the default is gnu/7 within package gnu-compilers-hpc, gcc11 is in gnu11-compilers-hpc\n# MODULE_FILES_DIRECTORY=/usr/share/lmod/modulefiles\n\nzypper in -y gnu${GNU_COMPILER_VERSION}-compilers-hpc-devel\n\n$COMMON_DIR/write_component_version.sh \"GCC\" ${GNU_COMPILER_VERSION}\n", "num_lines": 10}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Intel\u00c2\u00ae oneAPI Math Kernel Library\n\n# Intel provides oneapi RPM packages for SUSE\n# and the repository is set up in install_utils.sh\n# so we can simply install the needed package\n\n# workaround for wrong multi-version repos of intel.\n# instead of use the version for a package search and install\n# we need to provide a fixed name including the version\n# so instead of\n# zypper install -y -l intel-oneapi-mkl = $INTEL_ONE_MKL_VERSION\n# we forced to use\nzypper --non-interactive install -y -l intel-oneapi-mkl-$INTEL_ONE_MKL_VERSION\n\n$COMMON_DIR/write_component_version.sh \"INTEL_ONE_MKL\" $INTEL_ONE_MKL_VERSION\n", "num_lines": 19}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# SLES comes with mellanox inbox (kernel) drivers by default, so no need to install anything\n#\n\n# the ibdev2netdev is only in the external mellanox package, so we do not have it with inbox drivers\nwget https://raw.githubusercontent.com/Mellanox/container_scripts/master/ibdev2netdev\nmv ibdev2netdev /usr/local/bin\nchmod +x /usr/local/bin/ibdev2netdev\n\n# IF you want the external drivers provided by https://network.nvidia.com/products/infiniband-drivers/linux/mlnx_ofed/\n# it provides packages for SLES with MLNX_OFED_LINUX-5.7-1.0.2.0-sles15sp4-x86_64.tgz\n# SHA256: f3af9dd691dc07404fa07a1c3819de14361dc292d90a9b81aac6a7c729a2ea0f\n# you need to agree to the eula and provide the file somewhere\n\n#MLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-5.7-1.0.2.0/MLNX_OFED_LINUX-5.7-1.0.2.0-sles15sp4-x86_64.tgz\n#TARBALL=$(basename ${MLNX_OFED_DOWNLOAD_URL})\n#MOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n#$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"f3af9dd691dc07404fa07a1c3819de14361dc292d90a9b81aac6a7c729a2ea0f\"\n#tar zxvf ${TARBALL}\n\n# SUSE - if you use the tarball\n# The tarball contains modules for SLES default kernel already, there is no need for adding additional parameters to the installscript\n# but our default for SLES HPC is the -azure kernel, so we need to add it or switch to kernel-default.\n\n# SUSE default kernel would be simply:\n#./${MOFED_FOLDER}/mlnxofedinstall\n\n# SUSE azure kernel (manual check before if kernel and kernel-src fit together, could be not the same due to updates)\n#KERNEL=$(uname -r)\n#zypper in -y -l kernel-azure-devel kernel-source-azure\n#make -C /usr/src/linux-azure oldconfig\n#./${MOFED_FOLDER}/mlnxofedinstall --kernel $KERNEL --kernel-sources /usr/src/linux-${KERNEL} --add-kernel-support --skip-repo\n", "num_lines": 36}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# SLE HPC 15 SP4 comes with three different implementation of the Message Passing Interface (MPI) standard are provided standard with the HPC module:\n#   Open MPI 4 (and version 3)\n#   MVAPICH2\n#   MPICH 4\n#   MPICH-ofi 4.0.1\n#   openblas\n#   Intel MPI Benchmarks\n# These packages have been built with full environment module support (LMOD).\n# PLEASE have a look at our documentation\n# https://documentation.suse.com/sle-hpc/15-SP4/single-html/hpc-guide/#sec-compute-lib\n\n# https://docs.nvidia.com/networking/category/hpcx\n# https://docs.nvidia.com/networking/display/HPCXv28\n\n\n# Load gcc\nset CC=/usr/bin/gcc\nset GCC=/usr/bin/gcc\n\n#\nINSTALL_PREFIX=/opt\n\n# MVAPICH2\n# shipped with SLE HPC\nzypper --non-interactive install -y mvapich2-gnu-hpc\nMV2_VERSION=$(rpm -q  --qf=\"%{VERSION}\" mvapich2-gnu-hpc)\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\n\n# OpenMPI 4\n# shipped with SLE HPC\nzypper --non-interactive install -y ${OMPI}-gnu-hpc  lib${OMPI}-gnu-hpc\nOMPI_VERSION=$(rpm -q  --qf=\"%{VERSION}\" ${OMPI}-gnu-hpc)\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\n\n# HPC-X\nTARBALL=$(basename ${HPCX_DOWNLOAD_URL})\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n# the web page said checksum is md5 but in reality is sha256\n$COMMON_DIR/download_and_verify.sh ${HPCX_DOWNLOAD_URL} ${HPCX_CHKSUM}\ntar -xvf ${TARBALL}\nrm -rf ${INSTALL_PREFIX}/${HPCX_FOLDER}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\n\n# Enable Sharpd\n#${HPCX_PATH}/sharp/sbin/sharp_daemons_setup.sh -s -d sharpd\n#systemctl enable sharpd\n#systemctl start sharpd\n\n# Intel MPI\n# as there are more versions in the repos we need to select one\n# instead of always get the newest\n# workaround for wrong multi-version repos of intel.\n# instead of use the version for a package search and install\n# we need to provide a fixed name including the version\n# so instead of\n# zypper install -y -l intel-oneapi-mpi = $INTEL_ONE_MKL_VERSION\n# we forced to use\nzypper install -y -l intel-oneapi-mpi-${INTEL_ONE_MPI_VERSION}\n# Create modulesfiles\n/opt/intel/oneapi/modulefiles-setup.sh --force\n\n$COMMON_DIR/write_component_version.sh \"IMPI_${IMPI_MAJOR}\" ${INTEL_ONE_MPI_VERSION}\n\n#\n# # Setup module files for MPIs\n#\n\nmkdir -p $MODULE_FILES_DIRECTORY/mpi/\n\n#\n# # HPC-X\ncat << EOF >> $MODULE_FILES_DIRECTORY/mpi/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\n#module-whatis \"Description: Mellanox HPC-X\u00e2\u201e\u00a2 Software Toolkit\"\nset version ${HPCX_VERSION}\nconflict mpi\nmodule use ${HPCX_PATH}/modulefiles\nmodule load hpcx\nEOF\n\n# libraries are build against gnu-7 and not gnu-11, so we need to have the path hardcoded to gnu-7\n# Cannot use links because we need to load compiler as well.\n# e.g. /usr/share/lmod/moduledeps/gnu-7/mvapich2/2.3.6\n# MVAPICH2 -> already provided by suse package, build with gcc7\ncat <<EOF >> ${MODULE_FILES_DIRECTORY}/mpi/mvapich2-${MV2_VERSION}\n#%Module 1.0\nset version ${MV2_VERSION}\nconflict mpi\nmodule use /usr/share/lmod/modulefiles\nmodule load gnu/7 mvapich2/${MV2_VERSION}\nEOF\n\n# OpenMPI -> already provided by suse package, build with gcc7\ncat <<EOF >> ${MODULE_FILES_DIRECTORY}/mpi/openmpi-${OMPI_VERSION}\n#%Module 1.0\nset version ${OMPI_VERSION}\nconflict mpi\nmodule use /usr/share/lmod/modulefiles\nmodule load gnu/7 openmpi/${OMPI_VERSION}\nEOF\n\n# Intel oneAPI\n# oneapi provides its own modulefiles\nln -sf  $(readlink --canonicalize $INTELLIBS/mpi/${INTEL_ONE_MPI_VERSION}/modulefiles/mpi) ${MODULE_FILES_DIRECTORY}/mpi/impi_${INTEL_ONE_MPI_VERSION}\n\n\n# # Create symlinks for modulefiles\nln -sf  $(readlink --canonicalize ${MODULE_FILES_DIRECTORY}/mpi/hpcx-${HPCX_VERSION}) ${MODULE_FILES_DIRECTORY}/mpi/hpcx\nln -sf  $(readlink --canonicalize ${MODULE_FILES_DIRECTORY}/mpi/mvapich2-${MV2_VERSION}) ${MODULE_FILES_DIRECTORY}/mpi/mvapich2\nln -sf  $(readlink --canonicalize ${MODULE_FILES_DIRECTORY}/mpi/openmpi-${OMPI_VERSION}) ${MODULE_FILES_DIRECTORY}/mpi/openmpi\nln -sf  $(readlink --canonicalize ${MODULE_FILES_DIRECTORY}/mpi/impi_${INTEL_ONE_MPI_VERSION}) ${MODULE_FILES_DIRECTORY}/mpi/impi-${IMPI_MAJOR}\n\n# cleanup downloaded tarballs and other installation files/folders\nrm -rf *.tar.gz *offline.sh\nrm -rf -- */\n", "num_lines": 124}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install NCCL\n# Optimized primitives for inter-GPU communication.\n\n# add rpm build tools\nzypper install -y -l rpm-build rpmdevtools git\n\nCUDA_MAJOR=$( echo ${CUDA_VERSION} | cut -d \".\" -f 1)\nCUDA_MINOR=$( echo ${CUDA_VERSION} | cut -d \".\" -f 2)\n\nTARBALL=$(basename ${NCCL_DOWNLOAD_URL})\n\npushd /tmp\nwget ${NCCL_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\npushd nccl-${NCCL_VERSION}\n\n# if you need to limit the number of parallel runs on smaller machines\n#mem=$(cat /proc/meminfo | head -1 | sed -e \"s/^[^ ]\\+[ ]\\+\\([^ ]\\+\\)[ ]\\+.*/\\\\1/\")\n#core=$(cat /proc/cpuinfo | grep processor | wc -l)\n#cnt=$(( a=mem/(512*1024), a < core ? a : core ))\n#make -j $cnt src.build NVCC_GENCODE=\"-gencode=arch=compute_80,code=sm_80\"\n\n# You should define NVCC_GENCODE in your environment to the minimal set\n# of archs to reduce compile time.\n#make -j src.build NVCC_GENCODE=\"-gencode=arch=compute_80,code=sm_80\"\n\nmake -j src.build\n\n# build rpm packages\nmake pkg.redhat.build\nrpm -i ./build/pkg/rpm/x86_64/libnccl-${NCCL_VERSION}+cuda${CUDA_MAJOR}.${CUDA_MINOR}.x86_64.rpm\nrpm -i ./build/pkg/rpm/x86_64/libnccl-devel-${NCCL_VERSION}+cuda${CUDA_MAJOR}.${CUDA_MINOR}.x86_64.rpm\nrpm -i ./build/pkg/rpm/x86_64/libnccl-static-${NCCL_VERSION}+cuda${CUDA_MAJOR}.${CUDA_MINOR}.x86_64.rpm\npopd\nrm -rf nccl-${NCCL_VERSION} $TARBALL\n\n# Install the nccl rdma sharp plugin\n# we need the packages: autoconf automake libtool rdma-core-devel\nmkdir -p /usr/local/nccl-rdma-sharp-plugins\ngit clone https://github.com/Mellanox/nccl-rdma-sharp-plugins.git\npushd nccl-rdma-sharp-plugins\n./autogen.sh\n./configure --prefix=/usr/local/nccl-rdma-sharp-plugins --with-cuda=/usr/local/cuda\nmake\nmake install\npopd\nrm -rf nccl-rdma-sharp-plugins\n\n\n# Build the nccl tests\nsource /etc/profile.d/lmod.sh\nmodule load mpi/hpcx\ngit clone https://github.com/NVIDIA/nccl-tests.git\npushd nccl-tests\nmake MPI=1 MPI_HOME=${HPCX_MPI_DIR} CUDA_HOME=/usr/local/cuda\npopd\nmv nccl-tests /opt\nmodule purge\npopd\n\n\n$COMMON_DIR/write_component_version.sh \"NCCL\" ${NCCL_VERSION}\n\n# Remove installation files\nrm -rf /tmp/${TARBALL}\nrm -rf /tmp/nccl-${NCCL_VERSION}\n", "num_lines": 71}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n#\n## Nvidia provide certified packages for SLES 15 SP4, so we only need to add the repositories and install the packages\n#\nDRIVER_BRANCH_VERSION=${NVIDIA_VERSION%.*.*} # branch is like main version e.g. 525 from 525.85.12\nCUDA_DASH_VERSION=${CUDA_VERSION/./-}\n\n# to check whats all available in the repo\n# zypper se --repo cuda-sles15-x86_64\n\n# install latest cuda package\n# the repo contains more versions, so for example we want cuda 11.3 the package name is \"cuda-11-3\"\n#\n# cuda \t                    Installs all CUDA Toolkit and Driver packages. Handles upgrading to the next version of the cuda package when it's released.\n# cuda-11-8 \t            Installs all CUDA Toolkit and Driver packages. Remains at version 11.8 until an additional version of CUDA is installed.\n# cuda-toolkit-11-8 \t    Installs all CUDA Toolkit packages required to develop CUDA applications. Does not include the driver.\n# cuda-tools-11-8 \t        Installs all CUDA command line and visual tools.\n# cuda-runtime-11-8      \tInstalls all CUDA Toolkit packages required to run CUDA applications, as well as the Driver packages.\n# cuda-compiler-11-8    \tInstalls all CUDA compiler packages.\n# cuda-libraries-11-8 \t    Installs all runtime CUDA Library packages.\n# cuda-libraries-devel-11-8 \tInstalls all development CUDA Library packages.\n# cuda-drivers \t            Installs all Driver packages. Handles upgrading to the next version of the Driver packages when they're released.\n\n# due to NVIDIA bug in post-install of the nvidia-drivers for kernel-azure, we need to select and install nvidia-gfxG05-kmp-azure manually\n# The cuda dependencies select packages with \"-default\" and then the (wrong) modules for kernel-default instead of kernel-azure got installed\n#\n# Don't install cuda-drivers: this introduces X11 and Wayland - instead install nvidia-computeGXX\n# Don't install cuda-toolkit: this introduces visualization tools\n# - instead install cuda-compilers, cuda-command-line-tools, gds-tools and cuda_libraries\nzypper -n install -y -l --no-recommends cuda-toolkit-${CUDA_DASH_VERSION} cuda-compiler-${CUDA_DASH_VERSION} cuda-command-line-tools-${CUDA_DASH_VERSION} gds-tools-${CUDA_DASH_VERSION} cuda-libraries-${CUDA_DASH_VERSION}  nvidia-fabricmanager = ${NVIDIA_VERSION} \"nvidia-gfxG05-kmp-azure = ${NVIDIA_VERSION}\" \"nvidia-computeG05 = ${NVIDIA_VERSION}\"\n\n\n$COMMON_DIR/write_component_version.sh \"CUDA\" ${CUDA_VERSION}\n$COMMON_DIR/write_component_version.sh \"NVIDIA\" ${NVIDIA_VERSION}\n\n# Post-install tasks (version its set through 'alternatives')\necho 'export PATH=$PATH:/usr/local/cuda/bin' | tee -a /etc/bash.bashrc.local\necho '/usr/local/cuda/lib64' | tee /etc/ld.so.conf.d/cuda.conf\n\n# start the fabricmanager - needed for run-tests on ND96asr_v4\n# systemctl start nvidia-fabricmanager.service\n", "num_lines": 44}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n#-------------------------------------------------------------------\n# Container Repository\n#-------------------------------------------------------------------\n# Docker is shipped with SLES by default\n# with SLE HPC we need to enable the Container repository\nSUSEConnect -p sle-module-containers/${SLE_DOTV}/x86_64\n\n#-------------------------------------------------------------------\n# Add SUSE Package Hub\n# byacc is only in packagehub\nSUSEConnect -p PackageHub/${SLE_DOTV}/x86_64\n#-------------------------------------------------------------------\n\n#-------------------------------------------------------------------\n# Nvidia provide certified packages for SLES 15, so we only need to add the repositories and install the packages\n# add the repo key separately beforehand.\nSUSEConnect -p sle-module-NVIDIA-compute/${SLE_MAJOR}/x86_64 --gpg-auto-import-keys\n#-------------------------------------------------------------------\n\n# Install pre-reqs and development tools\n#\n\n# Add additional repositories\n\n#-------------------------------------------------------------------\n# Intel provides oneapi RPM packages for SUSE, so we only need to add the repositories and install the packages\n#-------------------------------------------------------------------\n# see\n# https://www.intel.com/content/www/us/en/develop/documentation/installation-guide-for-intel-oneapi-toolkits-linux/top/installation/install-using-package-managers/yum-dnf-zypper.html\n\n# import package signing keys\nrpm --import $INTEL_PUBKEY_URI\n# delete if exists\nzypper -n rr oneAPI &>/dev/null || :\n# add repository\nzypper -n addrepo -f -g $INTEL_REPO_URI oneAPI\n# fetch key\nzypper --non-interactive --gpg-auto-import-keys refresh oneAPI\n# disable auto-refresh for the repo (mr -F)\nzypper --non-interactive modifyrepo --no-refresh oneAPI\n\n# list all packages\n# sudo -E zypper pa -ir oneAPI\n#-------------------------------------------------------------------\n\n#-------------------------------------------------------------------\n# Nvidia container repo\n#-------------------------------------------------------------------\n# see https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html\n# Check https://nvidia.github.io/libnvidia-container\nzypper --non-interactive rr libnvidia-container &>/dev/null || :\nzypper addrepo -f -g $NVIDIA_CONTAINER_REPO_URI\n# fetch key\nzypper --non-interactive --gpg-auto-import-keys refresh libnvidia-container\n\n#-------------------------------------------------------------------\n# Add SUSE Package Hub\n# byacc is only in packagehub\nSUSEConnect -p PackageHub/${SLE_DOTV}/x86_64\n#-------------------------------------------------------------------\n\n#\n## SLES HPC ship with many HPC packages already, so no need to build it - simple install is enough\n#\n# Install base compiler (this will pull in packages for HPC and Lmod as well)\nzypper --non-interactive in -y gnu-compilers-hpc-devel\n\n#\n# If you run kernel-default remove \"-azure\" from the kernel package names below\n#\nzypper install -y \\\n    numactl \\\n    byacc \\\n    atk \\\n    m4 \\\n    ${KERNEL_VERSION:+kernel-azure-devel = ${KERNEL_VERSION}} \\\n    ${KERNEL_VERSION:+kernel-source-azure = ${KERNEL_VERSION}} \\\n    binutils \\\n    fuse \\\n    cmake \\\n    libarchive13 \\\n    libsecret-1-0 \\\n    libnuma-devel \\\n    libibverbs-utils \\\n    perftest \\\n    mstflint \\\n    bzip2 \\\n    vim-data \\\n    clone-master-clean-up \\\n    insserv-compat \\\n    rpm-build \\\n    python3-devel\\\n    patch \\\n    python-rpm-macros \\\n    lshw \\\n    autoconf \\\n    automake \\\n    libtool \\\n    nfs-client \\\n    jq \\\n    rdma-core-devel \\\n    wget\n\n# Install azcopy tool\n## To copy blobs or files to or from a storage account.\nwget ${AZCOPY_DOWNLOAD_URL}\ntar -xvf ${AZTARBALL}\n## copy the azcopy to the bin path - better would be ${LOCALBIN}\nmv azcopy_linux_amd64_${AZVERSION}/azcopy ${LOCALBIN}\nchmod +x ${LOCALBIN}/azcopy\n$COMMON_DIR/write_component_version.sh \"azcopy\" ${AZCOPY_VERSION}\n## remove azcopy tarball and directory\nrm -rf *.tar.gz azcopy_linux_amd64_${AZVERSION}\n\n", "num_lines": 118}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get the new SUSEConnect\nzypper --non-interactive install -y suseconnect-ng\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set configuration\nsource ./config\n\n# set properties\nsource ./set_properties.sh\n\n# SLE version specific fixes\n./fixes.sh\n\n# install utils\n../common/install_utils.sh\n\n# install compilers\n../common/install_gcc.sh\n\n# install mellanox ofed\n../common/install_mellanoxofed.sh\n\n# install mpi libraries\n../common/install_mpis.sh\n\n# install nvidia gpu driver\n../common/install_nvidiagpudriver.sh\n\n# Install NCCL\n../common/install_nccl.sh\n\n# install AMD tuned libraries\n../common/install_amd_libs.sh\n\n# install Intel libraries\n../common/install_intel_libs.sh\n\n# Install NVIDIA docker container\n../common/install_docker.sh\n\n# Install Nvidia Datacenter GPU Manager (DCGM)\n../common/install_dcgm.sh\n\n# optimizations\n../common/hpc-tuning.sh\n\n# Network Optimization\n$COMMON_DIR/network-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n#\n# SUSE ships the rdma core userspace and libraries package by default\n# and provides persistent naming through udev rules\n# see for example /usr/lib/udev/rules.d/60-rdma-persistent-naming.rules\n\n# cleanup downloaded tarballs\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\n# cleanup directories\nrm -rf -- */\n\n# if you want to use it as golden-image pls. run\n#\n#/usr/sbin/clone-master-clean-up\n#/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync\n\n", "num_lines": 71}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport TEST_DIR=../../../tests\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# transform long form MOFED-LTS flag to short\nfor arg in \"$@\"; do\n    shift\n    case \"$arg\" in\n        \"--mofed-lts\") set -- \"$@\" \"-l\" ;;\n        *) set -- \"$@\" \"$arg\"\n    esac\ndone\n\n# display the usage of lts flag for user\nusage() { echo \"Usage: $0 [--mofed-lts <true|false>]\"  1>&2; exit 1; }\n\nwhile getopts \":l:\" o; do\n    case \"${o}\" in\n        l)\n            l=${OPTARG}\n            ((l == true || l == false)) || usage\n            ;;\n        *)\n            usage\n            ;;\n    esac\ndone\nshift $((OPTIND-1))\n\nif [ -z \"${l}\" ]; then\n    usage\nfi\n\nMOFED_LTS=${l} # true/ false\n\nsource /etc/profile\n\nGCC_VERSION=\"9.2.0\"\n\n# Find distro\nfind_distro() {\n    local os=`cat /etc/os-release | awk 'match($0, /^NAME=\"(.*)\"/, result) { print result[1] }'`\n    if [[ $os == \"CentOS Linux\" ]]\n    then\n        local centos_distro=`find_centos_distro`\n        echo \"${os} ${centos_distro}\"\n    elif [[ $os == \"AlmaLinux\" ]]\n    then\n        local alma_distro=`find_alma_distro`\n        echo \"${os} ${alma_distro}\"\n    elif [[ $os == \"Ubuntu\" ]]\n    then\n        local ubuntu_distro=`find_ubuntu_distro`\n        echo \"${os} ${ubuntu_distro}\"\n    elif [[ $os == \"SLE_HPC\" ]]\n    then\n        local sle_hpc_distro=`find_sle_hpc_distro`\n        echo ${sle_hpc_distro}\n    else\n        echo \"*** Error - invalid distro!\"\n        exit -1\n    fi\n}\n\n# Find CentOS distro\nfind_centos_distro() {\n    echo `cat /etc/redhat-release | awk '{print $4}'`\n}\n\n# Find Alma distro\nfind_alma_distro() {\n    echo `cat /etc/redhat-release | awk '{print $3}'`\n}\n\n# Find Ubuntu distro\nfind_ubuntu_distro() {\n    echo `cat /etc/os-release | awk 'match($0, /^PRETTY_NAME=\"(.*)\"/, result) { print result[1] }' | awk '{print $2}' | cut -d. -f1,2`\n}\n\n# Find SUSE Linux Enterprise HPC distro\nfind_sle_hpc_distro() {\n    echo $(cat /etc/os-release | awk 'match($0, /^PRETTY_NAME=\"(.*)\"/, result) { print result[1] }')\n}\n\ndistro=`find_distro`\necho \"Detected distro: ${distro}\"\n\nif [ \"${MOFED_LTS}\" = true ]\nthen\n    HPCX_VERSION_UBUNTU=\"v2.7.0\"\n    MOFED_VERSION_UBUNTU=\"MLNX_OFED_LINUX-4.9-6.0.6.0\"\n    HPCX_MOFED_INTEGRATION_VERSION=\"MLNX_OFED_LINUX-4.7-1.0.0.1\"\n    HPCX_OMB_PATH_UBUNTU_1804=\"/opt/hpcx-${HPCX_VERSION_UBUNTU}-gcc-${HPCX_MOFED_INTEGRATION_VERSION}-ubuntu18.04-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\n    IMPI_2021_VERSION_UBUNTU=\"2021.9.0\"\n    OMPI_VERSION_UBUNTU=\"4.1.5\"\nelse\n    OMPI_VERSION_UBUNTU=\"4.1.5\"\n    HPCX_MOFED_INTEGRATION_VERSION=\"MLNX_OFED_LINUX-5.4-1.0.3.0\"\n    case ${distro} in\n        \"Ubuntu 18.04\") HPCX_VERSION_UBUNTU=\"v2.15\";\n            MOFED_VERSION_UBUNTU=\"MLNX_OFED_LINUX-23.04-1.1.3.0\";\n            IMPI_2021_VERSION_UBUNTU=\"2021.9.0\";\n            ;;\n        \"Ubuntu 20.04\") HPCX_VERSION_UBUNTU=\"v2.15\";\n            MOFED_VERSION_UBUNTU=\"MLNX_OFED_LINUX-23.04-1.1.3.0\";\n            IMPI_2021_VERSION_UBUNTU=\"2021.9.0\";\n            ;;\n        \"Ubuntu 22.04\") HPCX_VERSION_UBUNTU=\"v2.15\";\n            MOFED_VERSION_UBUNTU=\"MLNX_OFED_LINUX-23.04-1.1.3.0\";\n            IMPI_2021_VERSION_UBUNTU=\"2021.9.0\";\n            ;;\n        *) ;;\n    esac\n    HPCX_OMB_PATH_UBUNTU_1804=\"/opt/hpcx-${HPCX_VERSION_UBUNTU}-gcc-MLNX_OFED_LINUX-5-ubuntu18.04-cuda12-gdrcopy2-nccl2.17-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nfi\n\nHPCX_VERSION_CENTOS=\"v2.9.0\"\nHPCX_VERSION_SUSE=\"2.12\"\n\nMVAPICH2_VERSION_CENTOS=\"2.3.6\"\nMVAPICH2_VERSION_ALMA=\"2.3.7\"\nMVAPICH2_VERSION_UBUNTU=\"2.3.7-1\"\nMVAPICH2_VERSION_SUSE=\"2.3.6\"\n\nOMPI_VERSION_CENTOS=\"4.1.1\"\nOMPI_VERSION_ALMA_86=\"4.1.3\"\nOMPI_VERSION_ALMA_87=\"4.1.5\"\nOMPI_VERSION_SUSE=\"4.1.1\"\n\nIMPI_2021_VERSION_CENTOS=\"2021.4.0\"\nIMPI_2021_VERSION_ALMA_86=\"2021.7.0\"\nIMPI_2021_VERSION_ALMA_87=\"2021.9.0\"\nIMPI_2021_VERSION_SUSE=\"2021.9.0\"\n\nMVAPICH2X_INSTALLATION_DIRECTORY=\"/opt/mvapich2-x\"\nIMPI2018_PATH=\"/opt/intel/compilers_and_libraries_2018.5.274\"\n\nMOFED_VERSION_CENTOS=\"MLNX_OFED_LINUX-5.4-1.0.3.0\"\nMOFED_VERSION_CENTOS_79=\"MLNX_OFED_LINUX-5.4-3.0.0.0\"\nMOFED_VERSION_CENTOS_83=\"MLNX_OFED_LINUX-5.2-1.0.4.0\"\nMOFED_VERSION_ALMA_86=\"MLNX_OFED_LINUX-5.8-1.0.1.1\"\nMOFED_VERSION_ALMA_87=\"MLNX_OFED_LINUX-23.04-0.5.3.3\"\nMOFED_VERSION_SUSE=\"MLNX_OFED_INBOX_5.14.21-4.0.0\"\n#MOFED_VERSION_SUSE=\"MLNX_OFED-5.7-1.0.2.0\"\n\nHPCX_OMB_PATH_CENTOS_76=\"/opt/hpcx-${HPCX_VERSION_CENTOS}-gcc${GCC_VERSION}-${MOFED_VERSION_CENTOS}-redhat7.6-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nHPCX_OMB_PATH_CENTOS_77=\"/opt/hpcx-${HPCX_VERSION_CENTOS}-gcc${GCC_VERSION}-${MOFED_VERSION_CENTOS}-redhat7.7-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nHPCX_OMB_PATH_CENTOS_78=\"/opt/hpcx-${HPCX_VERSION_CENTOS}-gcc${GCC_VERSION}-${MOFED_VERSION_CENTOS}-redhat7.8-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nHPCX_OMB_PATH_CENTOS_79=\"/opt/hpcx-${HPCX_VERSION_CENTOS}-gcc${GCC_VERSION}-${HPCX_MOFED_INTEGRATION_VERSION}-redhat7.9-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nHPCX_OMB_PATH_CENTOS_81=\"/opt/hpcx-${HPCX_VERSION_CENTOS}-gcc${GCC_VERSION}-${MOFED_VERSION_CENTOS}-redhat8.1-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nHPCX_OMB_PATH_CENTOS_83=\"/opt/hpcx-v2.8.0-gcc-${MOFED_VERSION_CENTOS_83}-redhat8.3-x86_64/ompi/tests/osu-micro-benchmarks-5.6.2\"\nMODULE_FILES_ROOT_CENTOS=\"/usr/share/Modules/modulefiles\"\nIMPI2021_PATH_CENTOS=\"/opt/intel/oneapi/mpi/${IMPI_2021_VERSION_CENTOS}\"\n# added \"libexec\" to the path, as centos and ubuntu use \"libexec\", but SUSE only \"lib\"\nMVAPICH2_PATH_CENTOS=\"/opt/mvapich2-${MVAPICH2_VERSION_CENTOS}/libexec\"\nMVAPICH2X_PATH_CENTOS=\"${MVAPICH2X_INSTALLATION_DIRECTORY}/gnu9.2.0/mofed5.1/azure-xpmem/mpirun\"\nOPENMPI_PATH_CENTOS=\"/opt/openmpi-${OMPI_VERSION_CENTOS}\"\n\nHPCX_OMB_PATH_ALMA_86=\"/opt/hpcx-v2.14-gcc-MLNX_OFED_LINUX-5-redhat8-cuda11-gdrcopy2-nccl2.16-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nHPCX_OMB_PATH_ALMA_87=\"/opt/hpcx-v2.15-gcc-MLNX_OFED_LINUX-5-redhat8-cuda12-gdrcopy2-nccl2.17-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nMODULE_FILES_ROOT_ALMA=\"/usr/share/Modules/modulefiles\"\nIMPI2021_PATH_ALMA_86=\"/opt/intel/oneapi/mpi/${IMPI_2021_VERSION_ALMA_86}\"\nIMPI2021_PATH_ALMA_87=\"/opt/intel/oneapi/mpi/${IMPI_2021_VERSION_ALMA_87}\"\n# added \"libexec\" to the path, as rh+clones and ubuntu use \"libexec\", but SUSE only \"lib\"\nMVAPICH2_PATH_ALMA=\"/opt/mvapich2-${MVAPICH2_VERSION_ALMA}/libexec\"\nOPENMPI_PATH_ALMA_86=\"/opt/openmpi-${OMPI_VERSION_ALMA_86}\"\nOPENMPI_PATH_ALMA_87=\"/opt/openmpi-${OMPI_VERSION_ALMA_87}\"\n\nMODULE_FILES_ROOT_UBUNTU=\"/usr/share/modules/modulefiles\"\nHPCX_OMB_PATH_UBUNTU_2004=\"/opt/hpcx-${HPCX_VERSION_UBUNTU}-gcc-MLNX_OFED_LINUX-5-ubuntu20.04-cuda12-gdrcopy2-nccl2.17-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nHPCX_OMB_PATH_UBUNTU_2204=\"/opt/hpcx-${HPCX_VERSION_UBUNTU}-gcc-MLNX_OFED_LINUX-5-ubuntu22.04-cuda12-gdrcopy2-nccl2.17-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nIMPI2021_PATH_UBUNTU=\"/opt/intel/oneapi/mpi/${IMPI_2021_VERSION_UBUNTU}\"\n# added \"libexec\" to the path, as centos and ubuntu use \"libexec\", but SUSE only \"lib\"\nMVAPICH2_PATH_UBUNTU=\"/opt/mvapich2-${MVAPICH2_VERSION_UBUNTU}/libexec\"\nMVAPICH2X_PATH_UBUNTU=\"${MVAPICH2X_INSTALLATION_DIRECTORY}/gnu9.2.0/mofed5.0/advanced-xpmem/mpirun\"\nOPENMPI_PATH_UBUNTU=\"/opt/openmpi-${OMPI_VERSION_UBUNTU}\"\n\nMODULE_FILES_ROOT_SUSE=\"/usr/share/lmod/modulefiles\"\nHPCX_OMB_PATH_SUSE=\"/opt/hpcx-v${HPCX_VERSION_SUSE}-gcc-inbox-suse15.4-cuda11-gdrcopy2-nccl${HPCX_VERSION_SUSE}-x86_64/ompi/tests/osu-micro-benchmarks-5.8\"\nIMPI2021_PATH_SUSE=\"/opt/intel/oneapi/mpi/${IMPI_2021_VERSION_SUSE}\"\n# SUSE use lib instead of libexec\nMVAPICH2_PATH_SUSE=\"/usr/lib/hpc/gnu7/mpi/mvapich2-psm2/2.3.6/lib\"\nMVAPICH2X_PATH_SUSE=\"\"\nOPENMPI_PATH_SUSE=\"/usr/lib/hpc/gnu7/mpi/openmpi/4.1.1\"\n\nCHECK_HPCX=0\nCHECK_IMPI_2021=0\nCHECK_IMPI_2018=0\nCHECK_OMPI=0\nCHECK_MVAPICH2=0\nCHECK_MVAPICH2X=0\nCHECK_CUDA=0\nCHECK_AOCL=1\nCHECK_NCCL=0\nCHECK_GCC=1\nCHECK_DOCKER=0\n\nif [[ $distro == *\"CentOS Linux\"* ]]\nthen\n    MKL_VERSION=\"2021.1.1\"\nelif [[ $distro == \"Ubuntu\"* ]]\nthen\n    MKL_VERSION=\"2023.1.0\"\nelif [[ $distro == \"AlmaLinux 8.6\" ]]\nthen\n    MKL_VERSION=\"2022.1.0\"\nelse\n    MKL_VERSION=\"2023.1.0\"\nfi\n\nif [[ $distro == \"CentOS Linux 7.6.1810\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_76}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\nelif [[ $distro == \"CentOS Linux 7.7.1908\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_77}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\nelif [[ $distro == \"CentOS Linux 7.8.2003\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_78}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\nelif [[ $distro == \"CentOS Linux 7.9.2009\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_79}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    CHECK_DOCKER=1\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS_79}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\n    CHECK_AOCL=1\n    CHECK_NCCL=1\nelif [[ $distro == \"CentOS Linux 8.1.1911\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_81}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\nelif [[ $distro == \"CentOS Linux 8.3.2011\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_CENTOS_83}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_CENTOS}\n    MOFED_VERSION=${MOFED_VERSION_CENTOS}\n    IMPI2021_PATH=${IMPI2021_PATH_CENTOS}\n    MVAPICH2_PATH=${MVAPICH2_PATH_CENTOS}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_CENTOS}\n    OPENMPI_PATH=${OPENMPI_PATH_CENTOS}\nelif [[ $distro == \"AlmaLinux 8.6\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_ALMA_86}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=0\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_ALMA}\n    MOFED_VERSION=${MOFED_VERSION_ALMA_86}\n    IMPI2021_PATH=${IMPI2021_PATH_ALMA_86}\n    MVAPICH2_PATH=${MVAPICH2_PATH_ALMA}\n    OPENMPI_PATH=${OPENMPI_PATH_ALMA_86}\n    CHECK_AOCL=1\n    CHECK_NCCL=1\n    CHECK_DOCKER=1\nelif [[ $distro == \"AlmaLinux 8.7\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_ALMA_87}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_IMPI_2018=0\n    CHECK_OMPI=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_ALMA}\n    MOFED_VERSION=${MOFED_VERSION_ALMA_87}\n    IMPI2021_PATH=${IMPI2021_PATH_ALMA_87}\n    MVAPICH2_PATH=${MVAPICH2_PATH_ALMA}\n    OPENMPI_PATH=${OPENMPI_PATH_ALMA_87}\n    CHECK_AOCL=1\n    CHECK_NCCL=1\n    CHECK_DOCKER=1\nelif [[ $distro == \"Ubuntu 18.04\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_UBUNTU_1804}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_MVAPICH2=1\n    CHECK_OMPI=1\n    CHECK_BLIS_MT=1\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_UBUNTU}\n    MOFED_VERSION=${MOFED_VERSION_UBUNTU}\n    IMPI2021_PATH=${IMPI2021_PATH_UBUNTU}\n    MVAPICH2_PATH=${MVAPICH2_PATH_UBUNTU}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_UBUNTU}\n    OPENMPI_PATH=${OPENMPI_PATH_UBUNTU}\n    CHECK_AOCL=0\n    CHECK_GCC=0\n    CHECK_NCCL=1\n    CHECK_DOCKER=1\nelif [[ $distro == \"Ubuntu 20.04\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_UBUNTU_2004}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_MVAPICH2=1\n    CHECK_OMPI=1\n    CHECK_BLIS_MT=1\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_UBUNTU}\n    MOFED_VERSION=${MOFED_VERSION_UBUNTU}\n    IMPI2021_PATH=${IMPI2021_PATH_UBUNTU}\n    MVAPICH2_PATH=${MVAPICH2_PATH_UBUNTU}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_UBUNTU}\n    OPENMPI_PATH=${OPENMPI_PATH_UBUNTU}\n    CHECK_AOCL=0\n    CHECK_NCCL=1\n    CHECK_GCC=0\n    CHECK_DOCKER=1\nelif [[ $distro == \"Ubuntu 22.04\" ]]\nthen\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_UBUNTU_2204}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_MVAPICH2=1\n    CHECK_OMPI=1\n    CHECK_BLIS_MT=1\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_UBUNTU}\n    MOFED_VERSION=${MOFED_VERSION_UBUNTU}\n    IMPI2021_PATH=${IMPI2021_PATH_UBUNTU}\n    MVAPICH2_PATH=${MVAPICH2_PATH_UBUNTU}\n    MVAPICH2X_PATH=${MVAPICH2X_PATH_UBUNTU}\n    OPENMPI_PATH=${OPENMPI_PATH_UBUNTU}\n    CHECK_AOCL=0\n    CHECK_NCCL=1\n    CHECK_GCC=0\n    CHECK_DOCKER=1\nelif [[ $distro == \"SUSE Linux Enterprise High Performance Computing 15 SP4\" ]]\nthen\n    # add /sbin and /usr/sbin to the path to allow lscpi and ibstatus called without path\n    # as only UID=0 get it by default\n    export PATH=$PATH:/sbin:/usr/sbin\n    MKL_VERSION=\"2023.1.0\"\n    #\n    CHECK_GCC=0\n    CHECK_ONEAPI=1\n    CHECK_AZURE_HPC_DIAG=1\n\n    HPCX_OMB_PATH=${HPCX_OMB_PATH_SUSE}\n    CHECK_HPCX=1\n    CHECK_IMPI_2021=1\n    CHECK_MVAPICH2=1\n    CHECK_MVAPICH2X=0\n    CHECK_CUDA=1\n    CHECK_OMPI=1\n    CHECK_BLIS_MT=1\n\n    MODULE_FILES_ROOT=${MODULE_FILES_ROOT_SUSE}\n    MOFED_VERSION=${MOFED_VERSION_SUSE}\n    IMPI2021_PATH=${IMPI2021_PATH_SUSE}\n    MVAPICH2_PATH=${MVAPICH2_PATH_SUSE}\n    OPENMPI_PATH=${OPENMPI_PATH_SUSE}\n\n    CHECK_AOCL=1\n    CHECK_NV_PMEM=0\n    CHECK_NCCL=1\nelse\n    echo \"*** Error - invalid distro!\"\n    exit -1\nfi\n\nmodule use ${MODULE_FILES_ROOT}\n\n# check file is present\ncheck_exists() {\n    ls $1\n    if [ $? -eq 0 ]\n    then\n        echo \"$1 [OK]\"\n    else\n        echo \"*** Error - $1 not found!\" >&2\n        exit -1\n    fi\n}\n\n# check exit code\ncheck_exit_code() {\n    if [ $? -eq 0 ]\n    then\n        echo \"[OK] : $1\"\n    else\n        echo \"*** Error - $2!\" >&2\n        exit -1\n    fi\n}\n\n# verify if package updates work\ncase ${distro} in\n    Ubuntu*) sudo apt-get -q --assume-no update;;\n    CentOS* | AlmaLinux*) sudo yum update -y --setopt tsflags=test;;\n    * ) ;;\nesac\ncheck_exit_code \"Package update works\" \"Package update fails!\"\n\n# verify MOFED installation\nif [[ $distro == \"SUSE Linux Enterprise High Performance Computing 15 SP4\" ]]\nthen\n  echo \"ofed inbox driver does miss the ofed_info tool\"\nelse\n  ofed_info | grep ${MOFED_VERSION}\n  check_exit_code \"MOFED installed\" \"MOFED not installed\"\nfi\n\n# verify IB device is listed\nlspci | grep \"Infiniband controller\\|Network controller\"\ncheck_exit_code \"IB device is listed\" \"IB device not found\"\n\n# verify IB device is up\nibstatus | grep \"LinkUp\"\ncheck_exit_code \"IB device state: LinkUp\" \"IB link not up\"\n\n# verify GCC modulefile\nif [ $CHECK_GCC -eq 1 ]\nthen\n    # Not using gcc 9.2.0 in Ubuntu 20.04 (9.3.0 used)\n    check_exists \"${MODULE_FILES_ROOT}/gcc-${GCC_VERSION}\"\nfi\n\n# verify s/w package installations\nif [ $CHECK_GCC -eq 1 ]\nthen\n    # Not using gcc 9.2.0 in Ubuntu 20.04 (9.3.0 used)\n    check_exists \"/opt/gcc-${GCC_VERSION}/\"\nfi\n\ncheck_exists \"/opt/intel/oneapi/mkl/${MKL_VERSION}/\"\n\n# verify hpcdiag installation\ncheck_exists '/opt/azurehpc/diagnostics/gather_azhpc_vm_diagnostics.sh'\n\nif [ $CHECK_AOCL -eq 1 ]\nthen\n    # verify AMD modulefiles\n    check_exists \"${MODULE_FILES_ROOT}/amd/aocl\"\n\n    check_exists \"/opt/amd/lib/\"\n    check_exists \"/opt/amd/include/\"\nfi\n\nif [ $CHECK_DOCKER -eq 1 ] && [ \"${MOFED_LTS}\" = false ]\nthen\n    sudo docker pull hello-world\n    sudo docker run hello-world\n    check_exit_code \"Docker installed and working correctly!\" \"Problem with Docker!\"\nfi\n\n# verify mpi installations and their modulefiles\nmodule avail\n\n# hpcx\nif [ $CHECK_HPCX -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/hpcx\"\n\n    module load mpi/hpcx\n    mpirun -np 2 --map-by ppr:2:node -x UCX_TLS=rc ${HPCX_OMB_PATH}/osu_latency\n    check_exit_code \"HPC-X\" \"Failed to run HPC-X\"\n    module unload mpi/hpcx\nfi\n\n# impi 2021\nif [ $CHECK_IMPI_2021 -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/impi-2021\"\n\n    module load mpi/impi-2021\n    mpiexec -np 2 -ppn 2 -env FI_PROVIDER=mlx -env I_MPI_SHM=0 ${IMPI2021_PATH}/bin/IMB-MPI1 pingpong\n    check_exit_code \"Intel MPI 2021\" \"Failed to run Intel MPI 2021\"\n    module unload mpi/impi-2021\nfi\n\n# impi 2018\nif [ $CHECK_IMPI_2018 -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/impi\"\n\n    module load mpi/impi\n    mpiexec -np 2 -ppn 2 -env I_MPI_FABRICS=ofa ${IMPI2018_PATH}/linux/mpi/intel64/bin/IMB-MPI1 pingpong\n    check_exit_code \"Intel MPI 2018\" \"Failed to run Intel MPI 2018\"\n    module unload mpi/impi\nfi\n\n# mvapich2\nif [ $CHECK_MVAPICH2 -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/mvapich2\"\n    module load mpi/mvapich2\n\n    # Env MV2_FORCE_HCA_TYPE=22 explicitly selects EDR\n    mpiexec -np 2 -ppn 2 -env MV2_USE_SHARED_MEM=0  -env MV2_FORCE_HCA_TYPE=22  ${MVAPICH2_PATH}/osu-micro-benchmarks/mpi/pt2pt/osu_latency\n    check_exit_code \"MVAPICH2\" \"Failed to run MVAPICH2\"\n    module unload mpi/mvapich2\nfi\n\n# mvapich2x\nif [ $CHECK_MVAPICH2X -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/mvapich2x\"\n    check_exists ${MVAPICH2X_PATH}\n\n    module load mpi/mvapich2x\n    mpiexec -np 2 -ppn 2 -env MV2_USE_SHARED_MEM=0  ${MVAPICH2X_INSTALLATION_DIRECTORY}/libexec/osu-micro-benchmarks/mpi/pt2pt/osu_latency\n    check_exit_code \"MVAPICH2X\" \"Failed to run MVAPICH2X\"\n    module unload mpi/mvapich2x\nfi\n\n# Note: no need to run OpenMPI, as it is already covered by HPC-X runs, but make sure it is installed\nif [ $CHECK_OMPI -eq 1 ]\nthen\n    check_exists \"${MODULE_FILES_ROOT}/mpi/openmpi\"\n    check_exists ${OPENMPI_PATH}\nfi\n\n# Check Cuda drivers by running Nvidia SMI\nif [ $CHECK_CUDA -eq 1 ]\nthen\n    nvidia-smi\n    check_exit_code \"Nvidia SMI - Cuda Drivers\" \"Failed to run Nvidia SMI - Cuda Drivers\"\nfi\n\n# Perform Single Node NCCL Test\nif [ $CHECK_NCCL -eq 1 ]\nthen\n    module load mpi/hpcx\n\n    if [ \"${MOFED_LTS}\" = true ]\n    then\n        mpirun -np 4 \\\n        -x LD_LIBRARY_PATH \\\n        --allow-run-as-root \\\n        --map-by ppr:4:node \\\n        -mca coll_hcoll_enable 0 \\\n        -x UCX_TLS=tcp \\\n        -x CUDA_DEVICE_ORDER=PCI_BUS_ID \\\n        -x NCCL_SOCKET_IFNAME=eth0 \\\n        -x NCCL_DEBUG=WARN \\\n        /opt/nccl-tests/build/all_reduce_perf -b1K -f2 -g1 -e 4G\n    else\n        mpirun -np 8 \\\n        --allow-run-as-root \\\n        --map-by ppr:8:node \\\n        -x LD_LIBRARY_PATH=/usr/local/nccl-rdma-sharp-plugins/lib:$LD_LIBRARY_PATH \\\n        -mca coll_hcoll_enable 0 \\\n        -x UCX_TLS=tcp \\\n        -x CUDA_DEVICE_ORDER=PCI_BUS_ID \\\n        -x NCCL_SOCKET_IFNAME=eth0 \\\n        -x NCCL_DEBUG=WARN \\\n        -x NCCL_NET_GDR_LEVEL=5 \\\n        /opt/nccl-tests/build/all_reduce_perf -b1K -f2 -g1 -e 4G\n    fi\n\n    check_exit_code \"Single Node NCCL Test\" \"Failed\"\n\n    module unload mpi/hpcx\nfi\n\necho \"ALL OK!\"\n\nexit 0\n", "num_lines": 619}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##This is a test to verify an NDv4 vm is seeing the expected number of GPUs\n##and NICs.\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message\ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo \"$2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\n\n#Store output from calls passed to catch_error\noutput=\"\"\n\n#Count the number of gpu-name nvidia-smi outputs.\ngpu_names=\"timeout 3m nvidia-smi --query-gpu=name --format=csv,noheader\"\nerror_smi=\"Fail: nvidia-smi failed with error code\"\ncatch_error \"$gpu_names\" \"$error_smi\"\nngpus=$(echo \"$output\" | wc -l)\n\nsmi_warnings=\"timeout 3m nvidia-smi\"\ncatch_error \"$smi_warnings\" \"$error_smi\"\nout_warn=$(echo \"$output\")\nnwarn=$(echo \"$out_warn\" | grep \"WARNING\" | wc -l)\n\n\n#Count the number of nics lshw detects.\nfind_nics=\"sudo timeout 3m lshw -C network\"\nerror_nics=\"Fail: lshw failed with error code\"\ncatch_error \"$find_nics\" \"$error_nics\"\nnnics=$(echo \"$output\" | grep -i ConnectX-6 | wc -l)\n\n#Count the number of nvmedrives.\nfind_nvme=\"sudo timeout 3m lshw -C storage\" \nerror_nvme=\"Fail: lshw failed with error code\"\ncatch_error \"$find_nvme\" \"$error_nvme\"\nnnvme=$(echo \"$output\" | grep nvme | grep logical | wc -l)\n\n#Did either test fail?\npassed=1\nif [ $nwarn -ne 0 ]; then\n\tpassed=0\n\techo \"nvidia-smi reported warnings, see output below:\"\n\techo \"$out_warn\" \nfi\n\nif [ $ngpus -ne 8 ]; then\n\tpassed=0\n\techo \"$ngpus GPUs detected with 8 expected.\"\nfi\n\nif [ $nnics -ne 8 ]; then\n\tpassed=0\n\techo \"$nnics NICs detected with 8 expected.\"\nfi\n\nif [ $nnvme -ne 8 ]; then\n\tpassed=0\n\techo \"$nnvme NVMEs detected with 8 expected.\"\nfi\n\nif [ $passed -ne 1 ]; then\n\techo \"Fail: Error when detecting GPUs, NVMEs, and NICs.\"\n\texit 1;\nelse\n\techo \"Correct number of GPUs, NVMEs, and NICs detected.\"\nfi\n", "num_lines": 73}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##This script runs dcgmi diag -r 1 tests and evaluates if any fail.\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message. \ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo -e \"\\t $2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\n\noutput=\"\"\nerror_smi=\"**Fail** nvidia-smi failed with error code\"\n\necho \"dcgmi diag tests:\"\n\n\n#get the number of GPUs\nexec_names=\"timeout 3m nvidia-smi --query-gpu=name --format=csv,noheader\"\ncatch_error \"$exec_names\" \"$error_smi\"\nngpus=$(echo \"$output\" | wc -l)\n\n#array to hold status of persistence mode for each gpu\ndeclare -a pmvals=()\n\n#Find which GPUs have persistence mode off, record that information in pmvals.\n#Enable persistence mode on GPUs that have it disabled. \nfor i in $(seq 0 $((ngpus-1))); do\n\texec_query=\"timeout 3m nvidia-smi -i $i -q\"\n\tcatch_error \"$exec_query\" \"$error_smi\"\n\tpmvals[$i]=$(echo \"$output\" | grep \"Persistence Mode\" \\\n\t\t| awk '{print $4}')\n\tif [ ${pmvals[$i]} == \"Disabled\" ]; then\n\t\texec_pm=\"timeout 3m sudo nvidia-smi -i $i -pm 1\"\n                catch_error \"$exec_pm\" \"$error_smi\"\n\tfi\t       \ndone\n\n#Turn on persistence mode.\n\n#Run the basic (r=1) dcgmi diag tests.\nexec_dcgmi=\"timeout 3m dcgmi diag -r 1\"\nerror_dcgmi=\"**Fail** dcgmi diag failed with error code\"\ncatch_error \"$exec_dcgmi\" \"$error_dcgmi\"\nfails=$(echo \"$output\" | grep \"Fail\" | wc -l)\n\n#Disable persistence mode on GPUs that started with it disabled.\nfor i in $(seq 0 $((ngpus-1))); do\n\tif [ ${pmvals[$i]} == \"Disabled\" ]; then\n\t\texec_pm=\"timeout 3m sudo nvidia-smi -i $i -pm 0\"\n                catch_error \"$exec_pm\" \"$error_smi\"\n\tfi\t       \ndone\n\nif [ $fails -gt 0 ]; then\n\techo -e \" \\t **Fail** dcgmi tests have hit errors. Execute the\"\\\n\t\t\"command 'dcgmi diag -r 1' to see specific failures\"\n\texit 1\nelse\n\techo -e \" \\t **Pass** All level 1 dcgmi diag tests passed.\"\nfi\n", "num_lines": 66}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#ECC errors are handled by row remapping on A100. This script first counts the\n#row remappings due to ECC errors (correctable and otherwise). If any GPU has\n#512 or  more, the test fails. \n\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message\ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo -e \"\\t $2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\n\n#Store output from calls passed to catch_error\noutput=\"\"\n\necho \"ECC error check:\"\n\npass=1\n\nDRAM_ECC_THRESHOLD=20000000\nSRAM_ECC_THRESHOLD=10000\n\n\n#query the number of gpus\nexec_names=\"timeout 3m nvidia-smi --query-gpu=name --format=csv,noheader\"\nerror_smi=\"**Fail** nvidia-smi failed with error code\"\ncatch_error \"$exec_names\" \"$error_smi\"\nngpus=$(echo \"$output\" | wc -l)\n\n#query nvidia-smi to collect row remap information.\nexec_rows=\"timeout 3m nvidia-smi -q -d ROW_REMAPPER\"\ncatch_error \"$exec_rows\" \"$error_smi\"\nrow_remaps=$(echo \"$output\")\n\n#query nvidia-smi to collect row remap information.\nexec_ecc=\"timeout 3m nvidia-smi -q -d ECC\"\ncatch_error \"$exec_ecc\" \"$error_smi\"\nECC_errors=$(echo \"$output\")\n\n\n#Query the nvidia-smi output to identify any pending row remaps.\npending=$(echo \"$row_remaps\" | grep \"Pending\" | cut -d: -f2)\ngpui=0\n\n#Check if any GPU has a pending remap.\nfor pend in $pending; do\n\tif [ \"$pend\" != \"No\" ]; then\n\t\techo \"$gpui has a pending remap. Reset the GPU.\"\n\t\texit\n\t\tpass=0\n\tfi\n\tgpui=$((gpui+1))\ndone\n\n#Query the nvidia-smi output to identify any row remap failures.\nfails=$(echo \"$row_remaps\" | grep \"Remapping Failure Occurred\" | cut -d: -f2)\ngpui=0\n\n#Check if any GPU has had a row remap failure.\nfor err in $fails; do\n\tif [ \"$err\" != \"No\" ]; then\n\t\techo \"GPU $gpui indicates it has experienced a remap\"\\\n\t       \t\"error.\"\n\t\tgpui=$((gpui+1))\n\t\tpass=0\n\tfi\ndone\n\n#Query the nvidia-smi output to identify remap counts due to correctable \n#and uncorrectable ECC errors.\n\ncorrectable=$(echo \"$row_remaps\" | grep \"Correctable Error\" | cut -d: -f2)\nuncorrectable=$(echo \"$row_remaps\" | grep \"Uncorrectable Error\" | cut -d: -f2)\n\ncorrectable_v=( ${correctable} )\nuncorrectable_v=( ${uncorrectable} )\n\n\n#Identify any GPUs that have experienced more row remaps than allowed.\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((uncorrectable_v[i]))\n\tif [ $val -gt 512 ]; then\n\t\tpass=0\n\t\techo \"GPU $i has $val uncorrectable row remap errors.\"\n\tfi\ndone\n\n#Check the number of uncorrectable volatile SRAM ECC errors. Fail if any are\n#observed\nuncorrectableVS=$(echo \"$ECC_errors\" | grep Volatile -A 4 \\\n\t| grep \"SRAM Uncorrectable\" | cut -d: -f2)\nuncorrectableVS_v=( ${uncorrectableVS} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((uncorrectableVS_v[i]))\n\tif [ $val -gt 0 ]; then\n\t\tpass=0\n\t\techo \"GPU $i has $val uncorrectable volatile SRAM errors.\"\n\tfi\ndone\n\n#Count the number of correctable volatile SRAM ECC errors. Warn if more than\n#SRAM_ECC_THRESHOLD are observed, but don't fail. \ncorrectableVS=$(echo \"$ECC_errors\"  | grep Volatile -A 4 \\\n\t| grep \"SRAM Correctable\" | cut -d: -f2)\ncorrectableVS_v=( ${correctableVS} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((correctableVS_v[i]))\n\tif [ $val -gt $SRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val correctable volatile SRAM errors.\"\n\tfi\ndone\n\n#Count the number of uncorrectable volatile DRAM ECC errors. Warn if more than\n#DRAM_ECC_THRESHOLD are observed but don't fail.\nuncorrectableVD=$(echo \"$ECC_errors\" | grep Volatile -A 4 \\\n\t| grep \"DRAM Uncorrectable\" | cut -d: -f2)\nuncorrectableVD_v=( ${uncorrectableVD} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((uncorrectableVD_v[i]))\n\tif [ $val -gt $DRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val uncorrectable volatile DRAM errors.\"\n\tfi\ndone\n\n#Count the number of correctable volatile DRAM ECC errors. Warn if more than\n#DRAM_ECC_THRESHOLD are observed but don't fail.\ncorrectableVD=$(echo \"$ECC_errors\" | grep Volatile -A 4 \\\n\t| grep \"DRAM Correctable\" | cut -d: -f2)\ncorrectableVD_v=( ${correctableVD} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((correctableVD_v[i]))\n\tif [ $val -gt $DRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val correctable volatile DRAM errors.\"\n\tfi\ndone\n\n#Check the number of uncorrectable aggregate SRAM ECC errors. Fail if any are\n#detected.\nuncorrectableAS=$(echo \"$ECC_errors\" | grep Aggregate -A 4 \\\n\t| grep \"SRAM Uncorrectable\" | cut -d: -f2)\nuncorrectableAS_v=( ${uncorrectableAS} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((uncorrectableAS_v[i]))\n\tif [ $val -gt 0 ]; then\n\t\tpass=0\n\t\techo \"GPU $i has $val uncorrectable aggregate SRAM errors.\"\n\tfi\ndone\n\n#Count the number of correctable aggregate SRAM ECC errors. Warn if more than\n#SRAM_ECC_THRESHOLD are detected but don't fail.\ncorrectableAS=$(echo \"$ECC_errors\" | grep Aggregate -A 4 \\\n\t| grep \"SRAM Correctable\" | cut -d: -f2)\ncorrectableAS_v=( ${correctableAS} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((correctableAS_v[i]))\n\tif [ $val -gt $SRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val correctable aggregate SRAM errors.\"\n\tfi\ndone\n\n#Count the number of uncorrectable aggregate DRAM ECC errors. Warn if more than\n#DRAM_ECC_THRESHOLD are detected but don't fail.\nuncorrectableAD=$(echo \"$ECC_errors\" | grep Aggregate -A 4 \\\n\t| grep \"DRAM Uncorrectable\" | cut -d: -f2)\nuncorrectableAD_v=( ${uncorrectableAD} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((uncorrectableAD_v[i]))\n\tif [ $val -gt $DRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val uncorrectable aggregate DRAM errors.\"\n\tfi\ndone\n\n#Count the number of correctable aggregate DRAM ECC errors. Warn if more than\n#DRAM_ECC_THRESHOLD are detected but don't fail.\ncorrectableAD=$(echo \"$ECC_errors\" | grep Aggregate -A 4 \\\n\t| grep \"DRAM Correctable\" | cut -d: -f2)\ncorrectableAD_v=( ${correctableAD} )\nfor i in $(seq 0 $((ngpus-1))); do\n\tval=$((correctableAD_v[i]))\n\tif [ $val -gt $DRAM_ECC_THRESHOLD ]; then\n\t\techo \"GPU $i has $val correctable aggregate DRAM errors.\"\n\tfi\ndone\n\nif [ $pass -ne 1 ]; then\n\techo -e \"\\t **Fail** According to nvidia-smi at least one GPU had an\"\\\n\t\t\"ECC error status to investigate.\"\n\texit 1\nelse\n\techo -e \"\\t **Pass** The ECC error check passed.\"\nfi\n\t\t\n", "num_lines": 200}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#Users may pass a directory where health checks are located to this script.\n#If no directory is passed the script assumes health checks are in the opt\n#directory.\n\n#Verify if an argument was passed to the script. Test if the argument is\n#a directory that contains all the expected health checks. If no arguments\n#are passed use the default directory.\ndeclare -a files=(\"check-hardware.sh\" \"dcgmi-check.sh\" \"ecc-errors.sh\"\\\n\t   \"test-bandwidth.sh\" \"test-ib.sh\" \"test-nccl.sh\"\\\n\t   \"test-MaxPayLoad.sh\" \"gpu-copy.cu\")\nif [ \"$#\" -gt 1 ]; then\n\techo \"Usage: run-health-checks.sh [DIRECTORY]\"\n\techo \"DIRECTORY is an optional argument that specifies the location of\"\n\techo \"the test scripts to run. It defaults to the install location of\"\n\techo \"this script.\"\n\texit 1;\nfi\nif [ \"$#\" -eq 0 ]; then\n\tpass=1\n\tDIR=$(cd `dirname $0` && pwd)\n\tfor file in \"${files[@]}\"; do\n\t\tif ! test -f \"$DIR/$file\"; then\n\t\t\tpass=0\n\t\tfi\n\tdone\n\t#if tests are located in script dir use those\n\tif [[ $pass -eq 1 ]]; then\n\t\tTEST_DIR=$DIR\n\tfi\n\tif [[ $pass -eq 0 ]]; then\n\t\tDIR=$PWD\n\t\tpass=1\n\t\tfor file in \"${files[@]}\"; do\n\t\t\tif ! test -f \"$DIR/$file\"; then\n\t\t\t\tpass=0\n\t\t\tfi\n\t\tdone\n\t\tif [[ $pass -eq 1 ]]; then\n\t\t\tTEST_DIR=$DIR\n\t\tfi\n\tfi\n\tif [[ $pass -eq 0 ]]; then\n\t\techo \"Not all healch check files found in the working\"\\\n\t\t\t\"directory please specify where they can be found.\"\n\t\texit 1;\n\tfi\nelse\n\tpass=1\n\tfor file in \"${files[@]}\"; do\n\t\tif ! test -f \"$1/$file\"; then\n\t\t\techo \"Directory $1 is missing $file\"\n\t\t\tpass=0\n\t\tfi\n\tdone\n\tif [ $pass -eq 1 ]; then\n\t\tTEST_DIR=$1\n\telse\n\t\techo \"Directory $1 is missing health check files.\"\n\t\texit 1;\n\tfi\n\nfi\n\ncheck_hardware=$($TEST_DIR/check-hardware.sh)\ndetect=$?\n#detect=$(echo \"$check_hardware\" | grep \"Fail:\" | wc -l)\necho \"------------------------------------------------------------------------\"\necho \"**************************Begin Health Checks***************************\"\necho \"------------------------------------------------------------------------\"\nline=\"------------------------------------------------------------------------\"\nif [ $detect -ne 0 ]; then\n\techo \"Failed to detect GPUs and NICs with error code $detect\"\\\n\t\t\", run check-hardware.sh\"\nelse\n\tpass=1\n        #run 'dcgmi diag -r 1' and check for failures\n\t$TEST_DIR/dcgmi-check.sh\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n        #run 'nvidia-smi -q -d ROW_REMAPPER' and check for problems \n\t$TEST_DIR/ecc-errors.sh\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n        #run ibstatus and check all devices are set up as expected\n\t$TEST_DIR/test-ib.sh\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n        #test that host to device/device to host bandwidth meet expectations.\n\t$TEST_DIR/test-bandwidth.sh $TEST_DIR\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n        #test nccl using nvlink and ib\n\t$TEST_DIR/test-nccl.sh\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n\t$TEST_DIR/test-MaxPayLoad.sh\n\tout=$?\n\tif [ $out -ne 0 ]; then\n\t\tpass=0\n\tfi\n        echo \"$line\"\n\n\tif [ $pass -ne 1 ]; then\n                message=\"******************At least one health check failed.\"\n                message+=\"*********************\"\n                echo \"$message\"\n\telse\n                message=\"********************All health checks have passed.\"\n                message+=\"**********************\"\n                echo \"$message\"\n\tfi\n        echo \"$line\"\nfi\n", "num_lines": 136}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##This script tests host to device bandwidth and device to host bandwidth using\n##a script recorded within the test that tests host to device and device to \n##host copy bandwidths between every combination of gpus and numa domains. The\n##test confirms that each GPU is hitting the expected bandwidths to at least\n##one of the numa domains.\n##\n##When this test is first run it will compile the gpu-copy benchmark if it is\n##not detected.\n\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message\ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo -e \"\\t $2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\n\ncreate_benchmark() {\n        file_dir=\"$1\"\n\n        compile_bench=\"nvcc -lnuma $file_dir/gpu-copy.cu -o $file_dir/gpu-copy\"\n\tcompile_error=\"**Fail** Error when attempting to compile benchmark\"\n        catch_error \"$compile_bench\" \"$compile_error\"\n}\n\nlocate_file() {\n        file=\"$1\"\n        exitOnFail=$2\n        pass=1\n\t#File name we want to locate.\n        local file=\"$1\"\n\t#What should  happen if the file isn't located?\n        local exitOnFail=$2\n\t#Write the directory containing the file here, if found.\n        local return_dir=$3\n        local pass=1\n\n\t#Start by testing directory where the script is located\n        local DIR=$(cd `dirname $0` && pwd)\n        DIR=$(cd `dirname $0` && pwd)\n        if ! test -f \"$DIR/$file\"; then\n                pass=0\n        fi\n        #If file is located in script dir use that directory.\n        if [[ $pass -eq 1 ]]; then\n                CHECK_LOC=$DIR\n        fi\n\t#Otherwise check the PWD (in case that is different).\n        if [[ $pass -eq 0 ]]; then\n                DIR=$PWD\n                pass=1\n                if test -f \"$DIR/$file\"; then\n                        CHECK_LOC=$DIR\n                else\n                        pass=0\n                fi\n        fi\n\n\t#If we found the file pass that to return_dir. \n\t#Otherwise either just exit or also fail.\n        if [[ $exitOnFail -eq 0 ]]; then\n                if [[ $pass -eq 0 ]]; then\n                         DIR=$(cd `dirname $0` && pwd)\n                         CHECK_LOC=$DIR\n                fi\n        else\n                if [[ $pass -eq 0 ]]; then\n                        echo \"Cannot find file $file.\"\n                        exit 1;\n                fi\n        fi\n\teval $return_dir=\"'$CHECK_LOC'\"\n}\n\n\necho \"htod and dtoh bandwidth check:\"\n\n#If no arguments are passed to the script assume the gpu-copy test is located\n#in the default location. Otherwise check if it the gpu-copy test is in the \n#location indicated by the argument. \nif [ \"$#\" -eq 0 ]; then\n\tlocate_file \"gpu-copy\" 0 CHECK_DIR\n\tlocate_file \"gpu-copy.cu\" 1 CHECK_DIR\n        create_benchmark \"$CHECK_DIR\"\nelse\n\tpass=1\n\tif test -f \"$1/gpu-copy\"; then\n\t\tCHECK_DIR=$1\n\telse\n                create_benchmark $1\n                CHECK_DIR=$1\n\tfi\nfi\n#Store output from calls passed to catch_error\noutput=\"\"\n\n#Count the number of gpu-name nvidia-smi outputs.\nerror_smi=\"**Fail** nvidia-smi failed with error code\"\n#Lock graphics clocks to 1400 to eliminate any time for the GPUs to boost.\n#This likely isn't important for performance here, but we will do it anyway\n#to be safe.\nlock_clocks=\"sudo nvidia-smi -lgc 1400\"\ncatch_error \"$lock_clocks\" \"$error_smi\"\n\n#Count the GPUs.\ngpu_list=\"timeout 3m nvidia-smi --query-gpu=name --format=csv,noheader\"\ncatch_error \"$gpu_list\" \"$error_smi\"\nngpus=$(echo \"$output\" | wc -l)\n\n\n\n\n#Run the superbench device to host bandwidth test.\nexec_htod=\"timeout 3m $CHECK_DIR/gpu-copy --size 134217728 --htod\"\n\nerror_htod=\"**Fail** The htod gpu_copy test failed to execute.\"\nerror_htod+=\"It exited with error code\"\n\ncatch_error \"$exec_htod\" \"$error_htod\"\nx_htod=$(echo \"$output\")\n\n#Run the superbench host to device bandwidth test.\nexec_dtoh=\"timeout 3m $CHECK_DIR/gpu-copy --size 134217728 --dtoh\"\n\nerror_dtoh=\"**Fail** The dtoh gpu_copy test failed to execute.\"\nerror_dtoh+=\"It exited with error code\"\ncatch_error \"$exec_dtoh\" \"$error_dtoh\"\nx_dtoh=$(echo \"$output\")\n\npass=1\n\n#Loop over all of the detected GPUs.\nfor i in $(seq 0 $((ngpus-1))); do\n\t#Collect host to device bandwidths computed in each numa zone.\n\tbw_htod=$(echo \"$x_htod\" | grep \"gpu$i\" | cut -d' ' -f2 | cut -d. -f1)\n\tmax_htodbw=0\n\tmin_bw=100\n\t#Loop over the bandwidths observed in each numa zone and find max.\n\tfor bw in $bw_htod; do\n\t\tif [ $max_htodbw -lt $bw ]; then\n\t\t\tmax_htodbw=$bw\n\t\tfi\n\tdone\n\n\t#Collect device to host bandwidths computed in each numa zone.\n\tbw_dtoh=$(echo \"$x_dtoh\" | grep \"gpu$i\" | cut -d' ' -f2 | cut -d. -f1)\n\tmax_dtohbw=0\n\t#Loop over bandwidths observed in each numa zone and find max.\n\tfor bw in $bw_dtoh; do\n\t\tif [ $max_dtohbw -lt $bw ]; then\n\t\t\tmax_dtohbw=$bw\n\t\tfi\n\tdone\n\t#Find minimum of the htod and dtoh bandwidths.\n\tif [ $max_htodbw -lt $max_dtohbw ]; then\n\t\tmin_bw=$max_htodbw\n\telse\n\t\tmin_bw=$max_dtohbw\n\tfi\n\n\t#If the min bandwidth is too low the test has failed.\n\tif [ $min_bw -lt 24 ]; then\n\t\techo \"Bandwidth is low on device $i. Reported bandwidth is\"\\\n\t\t\t\"$min_bw GB/s.\"\n\t\tpass=0\n\tfi\ndone\n#Unlock the graphics clock.\nunlock_clocks=\"sudo timeout 3m nvidia-smi -rgc\"\ncatch_error \"$unlock_clocks\" \"$error_smi\"\n\nif [ $pass -ne 1 ]; then\n\techo -e \"\\t **Fail** At least one device reported low htod or dtoh\"\\\n\t\t\"bandwidth.\"\n\texit 1;\nelse\n\techo -e \"\\t **Pass** The htod and dtoh bandwidth checks both passed\"\nfi\n", "num_lines": 185}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##This script examines the output of ibstatus, looking for any problems.\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message\ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo -e \"\\t $2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\necho \"check ibstatus:\"\n\n#Store output from calls passed to catch_error\noutput=\"\"\n\nib=200;\nnum_r=0\nnum_s=0\nnum_ps=0\n\n\n#Check ibstatus Rates and make sure they are all 200.\nexec_ibstat=\"timeout 3m ibstatus\"\nerror_ibstat=\"**Fail** ibstatus exited with error code\"\ncatch_error \"$exec_ibstat\" \"$error_ibstat\"\nibstat_out=$(echo \"$output\")\n\n#make sure we are only checking rates for InfiniBand\ntypes=$(echo \"$ibstat_out\" | grep \"link_layer:\" | awk '{print $2}')\ntypes_v=( ${types} )\n\nfor i in $(echo \"$ibstat_out\" | grep \"rate:\" | awk '{print $2}'); do \n\tnum_r=$((num_r+1));\n\tif [ $i -lt $ib ]; then\n\t\tir=$((num_r-1))\n\t\tif [ \"${types_v[ir]}\" = \"InfiniBand\" ]; then\n\t\t\tib=$i;\n\t\tfi\n\tfi;\ndone\n\n#Check ibstatus to make sure States are set to Active.\nfor i in $(echo \"$ibstat_out\" | grep \"state:\" | grep -v \"phys\" | awk '{print $3}'); do\n\tif [ \"$i\" = \"ACTIVE\" ]; then\n\t\tnum_s=$((num_s+1));\n\tfi\ndone\n\n#Check ibstatus to make sure Physical states are set to LinkUp\nfor i in $(echo \"$ibstat_out\" | grep \"phys state:\" | awk '{print $4}'); do\n\tif [ \"$i\" = \"LinkUp\" ]; then\n\t\tnum_ps=$((num_ps+1));\n\tfi\ndone\n\npass=1\n\n\nif [ $ib -lt 200 ]; then\n\techo \"The minimum ib rate observed is $ib, but it should be 200.\"\n\tpass=0\nfi\n\nif [ $num_s -lt $num_r ]; then\n\techo \"The ib 'State' is not set to 'ACTIVE' for all devices.\"\n\tpass=0\nfi\n\nif [ $num_ps -lt $num_r ]; then\n\techo \"The ib 'Physical state' is not set to LinkUp for all devices.\"\n\tpass=0\nfi\n\nif [ $pass -eq 1 ]; then\n\techo -e \"\\t **Pass** All ibstatus settings are ok.\"\nelse\n\techo -e \"\\t **Fail** The settings returned by ibstatus indicate a problem.\"\n\texit 1;\nfi\n\t\n", "num_lines": 85}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"MaxPayload test:\"\n\npass=1\nids=$(lspci | grep \"3D controller\" | cut -d' ' -f1)\nfor i in $(echo \"$ids\"); do\n\tDevCap=$(sudo lspci -vv -s $i | grep DevCap: \\\n\t\t| cut -d' ' -f2)\n\tDevCtl=$(sudo lspci -vv -s $i | grep DevCtl: -A 2 \\\n\t\t| grep MaxPayload | cut -d' ' -f2)\n\tif [[ $DevCap -ne $DevCtl ]]; then\n\t\techo \"DevCap and DevCtl MaxPayload do not match for device $i\"\n\t\texit 1;\n\tfi\ndone\necho -e \"\\t **Pass** The MaxPayload size check passed.\"\n", "num_lines": 18}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##This script executes two nccl tests, one using ib and one using nvlink.\n##It also checks that the performance on these benchmarks is satisfactory.\n\n#Catch error codes that may be thrown by the executable passed as the first\n#input, and if an error code is tripped throw the second input as a message\ncatch_error() {\n\toutput=$($1)\n\terr_code=$?\n\tif [ $err_code -ne 0 ]; then\n\t\techo -e \"\\t $2 $err_code\" >&2\n\t\texit $err_code;\n\tfi\n}\necho \"NCCL tests:\"\n\n#Store output from calls passed to catch_error\noutput=\"\"\n\npass=1\n\n#Count the number of gpu-name nvidia-smi outputs.\nerror_smi=\"**Fail** nvidia-smi failed with error code\"\n#Load the mpi module.\nmodule load mpi/hpcx > /dev/null\n\n#Lock graphics clocks to 1400.\nlock_clocks=\"sudo nvidia-smi -lgc 1400\"\ncatch_error \"$lock_clocks\" \"$error_smi\"\n\nmpi_text=\"mpirun -np 8 --bind-to numa --map-by ppr:8:node -x LD_LIBRARY_PATH=\"\nmpi_text+=\"/usr/local/nccl-rdma-sharp-plugins/lib:\\$LD_LIBRARY_PATH\"\nmpi_text+=\" -mca coll_hcoll_enable 0 -x NCCL_IB_PCI_RELAXED_ORDERING=1\"\n\nexec_text=\"/opt/nccl-tests/build/all_reduce_perf -c 1 -b4G -f2 -g1 -e 4G\"\n\nexec_nvlink=\"timeout 3m $mpi_text -x UCX_TLS=tcp -x UCX_NET_DEVICES=eth0\"\nexec_nvlink+=\" -x CUDA_DEVICE_ORDER=PCI_BUS_ID -x NCCL_SOCKET_IFNAME=eth0 -x\"\nexec_nvlink+=\" NCCL_DEBUG=WARN -x NCCL_TOPO_FILE=/opt/microsoft/ndv4-topo.xml\"\nexec_nvlink+=\" $exec_text\"\n\nerror_nvlink=\"**Fail** nccl test using nvlink failed with error code\"\n\n#Run a single node nccl test using nvlink.\ncatch_error \"$exec_nvlink\" \"$error_nvlink\"\nnccl_nvlink=$(echo \"$output\")\n\n\n#select the average bandwidth from the nccl output.\nbw=$(echo \"$nccl_nvlink\" | grep \"Avg bus bandwidth\" | awk '{print $6}')\n#the average bandwidth should be above 235 GB/s.\nless=$(echo \"scale=4; 230.0 > $bw\" | bc)\nif [ $less -eq 1 ]; then\n       echo -e \"\\t **Fail** observed bandwidth in nvlink nccl test is $bw.\"\n       pass=0\nfi\n\n#Run a single node nccl test using infiniBand.\nexec_ib=\"timeout 3m $mpi_text -H localhost:8 -x UCX_IB_PCI_RELAXED_ORDERING=on\"\nexec_ib+=\" -x UCX_TLS=tcp -x UCX_NET_DEVICES=eth0 -x\"\nexec_ib+=\" CUDA_DEVICE_ORDER=PCI_BUS_ID -x NCCL_SOCKET_IFNAME=eth0 -x\"\nexec_ib+=\" NCCL_NET_GDR_LEVEL=5 -x NCCL_TOPO_FILE=/opt/microsoft/ndv4-topo.xml\"\nexec_ib+=\" -x NCCL_SHM_DISABLE=1 -x NCCL_P2P_DISABLE=1 $exec_text\"\n\nerror_ib=\"**Fail** the nccl ib test exited with error code\"\n\ncatch_error \"$exec_ib\" \"$error_ib\"\nnccl_ib=$(echo \"$output\")\n\n#select the average bandwidth from the nccl output.\nbw=$(echo \"$nccl_ib\" | grep \"Avg bus bandwidth\" | awk '{print $6}')\n\n#the average bandwidth should be above 20 GB/s.\nless=$(echo \"scale=4; 20.0 > $bw\" | bc)\nif [ $less -eq 1 ]; then\n       echo -e \"\\t **Fail** observed bandwidth in ib nccl test is $bw.\"\n       pass=0\nfi\n\n#Unlock the graphics clock.\nunlock_clocks=\"sudo timeout 3m nvidia-smi -rgc\"\ncatch_error \"$unlock_clocks\" \"$error_smi\"\n\nif [ $pass -eq 1 ]; then\n\techo -e \"\\t **Pass** Both nccl tests pass.\"\nelse\n\texit 1;\nfi\n\n", "num_lines": 91}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nKERNEL_VERSION=$(uname -r) su -c 'echo linux-image-$KERNEL_VERSION hold | dpkg --set-selections'\nsed -i 's/APT::Periodic::Unattended-Upgrade \".*/APT::Periodic::Unattended-Upgrade \"0\";/' /etc/apt/apt.conf.d/20auto-upgrades\n\nsystemctl stop unattended-upgrades.service\nsystemctl disable unattended-upgrades.service\nsystemctl mask unattended-upgrades.service\n", "num_lines": 10}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n# Kernel Parameter to disable predictive network interface naming\nKERNEL_PARAMETER=\"net.ifnames=0\"\nGRUB_CMDLINE_LINUX=\"$GRUB_CMDLINE_LINUX console=tty1 console=ttyS0 earlyprintk=ttyS0\"\n\n# Update 50-cloudimg-settings.cfg with additional kernel parameter\nsed -i \"s/${GRUB_CMDLINE_LINUX}/${GRUB_CMDLINE_LINUX} ${KERNEL_PARAMETER}/\" /etc/default/grub.d/50-cloudimg-settings.cfg\n# Generate grub file with updated parameters \nupdate-grub\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Dependencies\npip3 install -U netifaces\npip3 install -U PyYAML\n\n# Disable some unneeded services by default (administrators can re-enable if desired)\nsystemctl disable ufw\n\n# Disable cloud-init\necho network: {config: disabled} | sudo tee /etc/cloud/cloud.cfg.d/99-disable-network-config.cfg\nbash -c \"cat > /etc/netplan/50-cloud-init.yaml\" <<'EOF'\nnetwork:\n    ethernets:\n        eth0:\n            dhcp4: true\n    version: 2\nEOF\nnetplan apply\n\n# Update memory limits\ncat << EOF >> /etc/security/limits.conf\n*               hard    memlock         unlimited\n*               soft    memlock         unlimited\n*               hard    nofile          65535\n*               soft    nofile          65535\n*               hard    stack           unlimited\n*               soft    stack           unlimited\nEOF\n\necho \"vm.zone_reclaim_mode = 1\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh1 = 4096\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh2 = 8192\" >> /etc/sysctl.conf\necho \"net.ipv4.neigh.default.gc_thresh3 = 16384\" >> /etc/sysctl.conf\necho \"sunrpc.tcp_max_slot_table_entries = 128\" >> /etc/sysctl.conf\n\n\n## Systemd service for starting sunrpc and adding setting parameters\ncat <<EOF >/usr/sbin/sunrpc_tcp_settings.sh\n#!/bin/bash\n\nmodprobe sunrpc\nsysctl -p\nEOF\nchmod 755 /usr/sbin/sunrpc_tcp_settings.sh\n\ncat <<EOF >/etc/systemd/system/sunrpc_tcp_settings.service\n[Unit]\nDescription=Set sunrpc tcp settings\n\n[Service]\nUser=root\nType=oneshot\nExecStart=/usr/sbin/sunrpc_tcp_settings.sh\nRemainAfterExit=true\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsystemctl enable sunrpc_tcp_settings\nsystemctl start sunrpc_tcp_settings\nsystemctl is-active --quiet sunrpc_tcp_settings\n\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"sunrpc_tcp_settings service inactive!\"\n    exit ${error_code}\nfi\n\n# Install WALinuxAgent\napt-get install -y python3-setuptools\npip3 install distro\nWAAGENT_VERSION=2.9.0.4\n$COMMON_DIR/write_component_version.sh \"WAAGENT\" ${WAAGENT_VERSION}\nDOWNLOAD_URL=https://github.com/Azure/WALinuxAgent/archive/refs/tags/v${WAAGENT_VERSION}.tar.gz\nwget ${DOWNLOAD_URL}\ntar -xvf $(basename ${DOWNLOAD_URL})\npushd WALinuxAgent-${WAAGENT_VERSION}/\npython3 setup.py install --register-service\npopd\n\n# Configure WALinuxAgent\nsed -i -e 's/# OS.EnableRDMA=y/OS.EnableRDMA=y/g' /etc/waagent.conf\nsed -i -e 's/Provisioning.MonitorHostName=n/Provisioning.MonitorHostName=y/g' /etc/waagent.conf\necho \"Extensions.GoalStatePeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"Extensions.InitialGoalStatePeriod=6\" | sudo tee -a /etc/waagent.conf\necho \"OS.EnableFirewallPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.RemovePersistentNetRulesPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.RootDeviceScsiTimeoutPeriod=300\" | sudo tee -a /etc/waagent.conf\necho \"OS.MonitorDhcpClientRestartPeriod=60\" | sudo tee -a /etc/waagent.conf\necho \"Provisioning.MonitorHostNamePeriod=60\" | sudo tee -a /etc/waagent.conf\nsystemctl daemon-reload\nsystemctl restart walinuxagent\n\n# Setting Linux NFS read-ahead limits\n# Reference: \n#    https://learn.microsoft.com/en-us/azure/azure-netapp-files/performance-linux-nfs-read-ahead\n#    https://learn.microsoft.com/en-us/azure/storage/blobs/secure-file-transfer-protocol-support-how-to?tabs=azure-portal\ncat > /etc/udev/rules.d/90-nfs-readahead.rules <<EOM\nSUBSYSTEM==\"bdi\",\nACTION==\"add\",\nPROGRAM=\"/usr/bin/awk -v bdi=$kernel 'BEGIN{ret=1} {if ($4 == bdi) {ret=0}} END{exit ret}' /proc/fs/nfsfs/volumes\",\nATTR{read_ahead_kb}=\"15380\"\nEOM\n\nudevadm control --reload\n", "num_lines": 110}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nAOCC_VERSION=4.0.0_1\n\n# install dependency\nwget https://download.amd.com/developer/eula/aocc-compiler/aocc-compiler-${AOCC_VERSION}_amd64.deb\napt install -y ./aocc-compiler-${AOCC_VERSION}_amd64.deb\n\nrm aocc-compiler-${AOCC_VERSION}_amd64.deb \n\n$COMMON_DIR/write_component_version.sh \"AOCC\" ${AOCC_VERSION}\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install DCGM\n# Reference: https://developer.nvidia.com/dcgm#Downloads\n# the repo is already added during nvidia/ cuda installations\nDCGM_VERSION=3.1.8\napt-get install -y datacenter-gpu-manager=1:${DCGM_VERSION}\n$COMMON_DIR/write_component_version.sh \"DCGM\" ${DCGM_VERSION}\n\n# Enable the dcgm service\nsystemctl --now enable nvidia-dcgm\nsystemctl start nvidia-dcgm\n# Check if the service is active\nsystemctl is-active --quiet nvidia-dcgm\nerror_code=$?\nif [ ${error_code} -ne 0 ]\nthen\n    echo \"DCGM is inactive!\"\n    exit ${error_code}\nfi\n", "num_lines": 22}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install Moby Engine and CLI\napt-get install -y moby-engine\n\n# Install NVIDIA Docker\n# Reference: https://docs.nvidia.com/datacenter/cloud-native/container-toolkit/install-guide.html\n# Setting up NVIDIA Container Toolkit\ncurl -s -L https://nvidia.github.io/nvidia-docker/gpgkey | apt-key add - \\\n&& curl -s -L https://nvidia.github.io/nvidia-docker/${DISTRIBUTION}/nvidia-docker.list | tee /etc/apt/sources.list.d/nvidia-docker.list\n# MIG Capability on A100\ncurl -s -L https://nvidia.github.io/nvidia-container-runtime/experimental/${DISTRIBUTION}/nvidia-container-runtime.list | tee /etc/apt/sources.list.d/nvidia-container-runtime.list\n\napt-get update\n# Install nvidia-docker package\n# Install NVIDIA container toolkit and mark NVIDIA packages on hold\napt-get install -y nvidia-container-toolkit\napt-mark hold nvidia-container-toolkit\napt-mark hold libnvidia-container-tools\napt-mark hold libnvidia-container1\n\n# Install NVIDIA container runtime and mark NVIDIA packages on hold\napt-get install -y nvidia-container-runtime\napt-mark hold nvidia-container-runtime\n\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/nvidia-docker\ncp nvidia-docker /bin/\nchmod +x /bin/nvidia-docker\nwget https://raw.githubusercontent.com/NVIDIA/nvidia-docker/master/daemon.json\ncp daemon.json /etc/docker/\n\n# Working setup can be tested by running a base CUDA container\n# nvidia-docker run -e NVIDIA_VISIBLE_DEVICES=all nvidia/cuda:11.0-base nvidia-smi\n\n# disabling aufs, btrfs, zfs and devmapper snapshotter plugins\nmkdir -p /etc/containerd\ncat << EOF | tee -a /etc/containerd/config.toml\ndisabled_plugins = [\"cri\", \"zfs\", \"aufs\", \"btrfs\", \"devmapper\"]\nEOF\n\n# restart containerd service\nsystemctl restart containerd\n\n# status of containerd snapshotter plugins\nctr plugin ls\n\n# enable and restart the docker daemon to complete the installation\nsystemctl enable docker\nsystemctl restart docker\n\n# Write the docker version to components file\nmoby_version=$(apt list --installed | grep moby-engine | awk -F' ' '{print $2}')\ndocker_version=$(nvidia-docker --version | awk -F' ' '{print $3}')\n$COMMON_DIR/write_component_version.sh \"MOBY-ENGINE\" ${moby_version}\n$COMMON_DIR/write_component_version.sh \"NVIDIA-DOCKER\" ${docker_version::-1}\n\n# Remove unwanted repos\nrm -f /etc/apt/sources.list.d/nvidia*\n", "num_lines": 60}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Intel\u00c2\u00ae oneAPI Math Kernel Library\ncase ${DISTRIBUTION} in\n    \"ubuntu18.04\") INTEL_MKL_VERSION=\"2023.1.0.46342\";\n        RELEASE_VERSION=\"cd17b7fe-500e-4305-a89b-bd5b42bfd9f8\";\n        CHECKSUM=\"cc28c94cab23c185520b93c5a04f3979d8da6b4c90cee8c0681dd89819d76167\";; \n    \"ubuntu20.04\") INTEL_MKL_VERSION=\"2023.1.0.46342\";\n        RELEASE_VERSION=\"cd17b7fe-500e-4305-a89b-bd5b42bfd9f8\";\n        CHECKSUM=\"cc28c94cab23c185520b93c5a04f3979d8da6b4c90cee8c0681dd89819d76167\";;\n    \"ubuntu22.04\") INTEL_MKL_VERSION=\"2023.1.0.46342\";\n        RELEASE_VERSION=\"cd17b7fe-500e-4305-a89b-bd5b42bfd9f8\";\n        CHECKSUM=\"cc28c94cab23c185520b93c5a04f3979d8da6b4c90cee8c0681dd89819d76167\";;\n    *) ;;\nesac\n\nONE_MKL_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/IRC_NAS/${RELEASE_VERSION}/l_onemkl_p_${INTEL_MKL_VERSION}_offline.sh\n$COMMON_DIR/write_component_version.sh \"INTEL_ONE_MKL\" ${INTEL_MKL_VERSION}\n$COMMON_DIR/download_and_verify.sh ${ONE_MKL_DOWNLOAD_URL} ${CHECKSUM}\nsh ./l_onemkl_p_${INTEL_MKL_VERSION}_offline.sh -s -a -s --eula accept\n", "num_lines": 22}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nLUSTRE_VERSION=2.15.1-29-gbae0abe\n\nsource $UBUNTU_COMMON_DIR/setup_lustre_repo.sh\n\napt-get update\napt-get install -y amlfs-lustre-client-${LUSTRE_VERSION}=$(uname -r)\n\n$COMMON_DIR/write_component_version.sh \"LUSTRE\" ${LUSTRE_VERSION}\n", "num_lines": 12}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nMONEO_VERSION=v0.3.1\n\n# Dependencies \npython3 -m pip install --upgrade pip\n\nMONITOR_DIR=/opt/azurehpc/tools\n\nmkdir -p $MONITOR_DIR\n\npushd $MONITOR_DIR\n\n    git clone https://github.com/Azure/Moneo  --branch $MONEO_VERSION\n\n    chmod 777 Moneo\n\n    pushd Moneo/linux_service\n        ./configure_service.sh $MONITOR_DIR/Moneo       \n    popd\npopd\n\n# add an slias for Moneo\nif ! grep -qxF \"alias moneo='python3 /opt/azurehpc/tools/Moneo/moneo.py'\" /etc/bash.bashrc; then\n    echo \"alias moneo='python3 /opt/azurehpc/tools/Moneo/moneo.py'\" >> /etc/bash.bashrc\nfi\n\n$COMMON_DIR/write_component_version.sh \"MONEO\" ${MONEO_VERSION}\n", "num_lines": 31}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Parameters\nHPCX_CHECKSUM=$1\n\n# Load gcc\nset CC=/usr/bin/gcc\nset GCC=/usr/bin/gcc\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.15\nHPCX_VERSION=\"v2.15\"\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc-MLNX_OFED_LINUX-5-$DISTRIBUTION-cuda12-gdrcopy2-nccl2.17-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://content.mellanox.com/hpc/hpc-x/${HPCX_VERSION}/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh ${HPCX_DOWNLOAD_URL} ${HPCX_CHECKSUM}\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n$COMMON_DIR/write_component_version.sh \"HPCX\" $HPCX_VERSION\n\n# MVAPICH2 2.3.7-1\nMV2_VERSION=\"2.3.7-1\"\nMV2_DOWNLOAD_URL=http://mvapich.cse.ohio-state.edu/download/mvapich/mv2/mvapich2-${MV2_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $MV2_DOWNLOAD_URL \"fdd971cf36d6476d007b5d63d19414546ca8a2937b66886f24a1d9ca154634e4\"\ntar -xvf mvapich2-${MV2_VERSION}.tar.gz\ncd mvapich2-${MV2_VERSION}\n# Error exclusive to Ubuntu 22.04\n# configure: error: The Fortran compiler gfortran will not compile files that call\n# the same routine with arguments of different types.\n./configure $(if [[ ${DISTRIBUTION} == \"ubuntu22.04\" ]]; then echo \"FFLAGS=-fallow-argument-mismatch\"; fi) --prefix=${INSTALL_PREFIX}/mvapich2-${MV2_VERSION} --enable-g=none --enable-fast=yes && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\n\n# OpenMPI 4.1.5\nOMPI_VERSION=\"4.1.5\"\nOMPI_DOWNLOAD_URL=https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-${OMPI_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $OMPI_DOWNLOAD_URL \"c018b127619d2a2a30c1931f316fc8a245926d0f5b4ebed4711f9695e7f70925\"\ntar -xvf openmpi-${OMPI_VERSION}.tar.gz\ncd openmpi-${OMPI_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/openmpi-${OMPI_VERSION} --with-ucx=${UCX_PATH} --with-hcoll=${HCOLL_PATH} --enable-mpirun-prefix-by-default --with-platform=contrib/platform/mellanox/optimized && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\n\n# Intel MPI 2021 (Update 9)\nIMPI_2021_VERSION=\"2021.9.0\"\nIMPI_2021_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/IRC_NAS/718d6f8f-2546-4b36-b97b-bc58d5482ebf/l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh\n$COMMON_DIR/download_and_verify.sh $IMPI_2021_DOWNLOAD_URL \"5c170cdf26901311408809ced28498b630a494428703685203ceef6e62735ef8\"\nbash l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh -s -a -s --eula accept\nmv ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/mpi ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\n$COMMON_DIR/write_component_version.sh \"IMPI_2021\" ${IMPI_2021_VERSION}\n\n# Module Files\nMODULE_FILES_DIRECTORY=/usr/share/modules/modulefiles/mpi\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n# HPC-X\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# MVAPICH2\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/mvapich2-${MV2_VERSION}\n#%Module 1.0\n#\n#  MVAPICH2 ${MV2_VERSION}\n#\nconflict        mpi\nprepend-path    PATH            /opt/mvapich2-${MV2_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/mvapich2-${MV2_VERSION}/lib\nprepend-path    MANPATH         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_BIN         /opt/mvapich2-${MV2_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/mvapich2-${MV2_VERSION}/include\nsetenv          MPI_LIB         /opt/mvapich2-${MV2_VERSION}/lib\nsetenv          MPI_MAN         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_HOME        /opt/mvapich2-${MV2_VERSION}\nEOF\n\n# OpenMPI\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/openmpi-${OMPI_VERSION}\n#%Module 1.0\n#\n#  OpenMPI ${OMPI_VERSION}\n#\nconflict        mpi\nprepend-path    PATH            /opt/openmpi-${OMPI_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/openmpi-${OMPI_VERSION}/lib\nprepend-path    MANPATH         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_BIN         /opt/openmpi-${OMPI_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/openmpi-${OMPI_VERSION}/include\nsetenv          MPI_LIB         /opt/openmpi-${OMPI_VERSION}/lib\nsetenv          MPI_MAN         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_HOME        /opt/openmpi-${OMPI_VERSION}\nEOF\n\n# Intel 2021\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/impi_${IMPI_2021_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_2021_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\nsetenv          MPI_BIN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/include\nsetenv          MPI_LIB         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/lib\nsetenv          MPI_MAN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}\nEOF\n\n# Softlinks\nln -s ${MODULE_FILES_DIRECTORY}/hpcx-${HPCX_VERSION} ${MODULE_FILES_DIRECTORY}/hpcx\nln -s ${MODULE_FILES_DIRECTORY}/mvapich2-${MV2_VERSION} ${MODULE_FILES_DIRECTORY}/mvapich2\nln -s ${MODULE_FILES_DIRECTORY}/openmpi-${OMPI_VERSION} ${MODULE_FILES_DIRECTORY}/openmpi\nln -s ${MODULE_FILES_DIRECTORY}/impi_${IMPI_2021_VERSION} ${MODULE_FILES_DIRECTORY}/impi-2021\n", "num_lines": 124}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install NCCL\napt install -y build-essential devscripts debhelper fakeroot\n\ncase ${DISTRIBUTION} in\n    \"ubuntu18.04\") NCCL_VERSION=\"2.18.3-1\"; \n        CUDA_VERSION=\"12.1\";;\n    \"ubuntu20.04\") NCCL_VERSION=\"2.18.3-1\"; \n        CUDA_VERSION=\"12.1\";;\n    \"ubuntu22.04\") NCCL_VERSION=\"2.18.3-1\"; \n        CUDA_VERSION=\"12.1\";;\n    *) ;;\nesac\n\nTARBALL=\"v${NCCL_VERSION}.tar.gz\"\nNCCL_DOWNLOAD_URL=https://github.com/NVIDIA/nccl/archive/refs/tags/${TARBALL}\npushd /tmp\nwget ${NCCL_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\npushd nccl-${NCCL_VERSION}\nmake -j src.build\nmake pkg.debian.build\npushd build/pkg/deb/\ndpkg -i libnccl2_${NCCL_VERSION}+cuda${CUDA_VERSION}_amd64.deb\nsudo apt-mark hold libnccl2\ndpkg -i libnccl-dev_${NCCL_VERSION}+cuda${CUDA_VERSION}_amd64.deb\nsudo apt-mark hold libnccl-dev\npopd\npopd\n\n# Install the nccl rdma sharp plugin\nmkdir -p /usr/local/nccl-rdma-sharp-plugins\napt install -y zlib1g-dev\ngit clone https://github.com/Mellanox/nccl-rdma-sharp-plugins.git\npushd nccl-rdma-sharp-plugins\n./autogen.sh\n./configure --prefix=/usr/local/nccl-rdma-sharp-plugins --with-cuda=/usr/local/cuda\nmake\nmake install\npopd\npopd\n\n# Build the nccl tests\nsource /etc/profile.d/modules.sh\nmodule load mpi/hpcx\ngit clone https://github.com/NVIDIA/nccl-tests.git\npushd nccl-tests\nmake MPI=1 MPI_HOME=${HPCX_MPI_DIR} CUDA_HOME=/usr/local/cuda\npopd\nmv nccl-tests /opt/.\nmodule unload mpi/hpcx\n\n$COMMON_DIR/write_component_version.sh \"NCCL\" ${NCCL_VERSION}\n\n# Remove installation files\nrm -rf /tmp/${TARBALL}\nrm -rf /tmp/nccl-${NCCL_VERSION}\n", "num_lines": 61}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Parameters\nVERSION=$1\n\ncase ${VERSION} in\n    1804) NVIDIA_VERSION=\"525.105.17\"; \n        CUDA_VERSION=\"12-1\"; \n        CUDA_SAMPLES_VERSION=\"12.1\";\n        CHECKSUM=\"c635a21a282c9b53485f19ebb64a0f4b536a968b94d4d97629e0bc547a58142a\";; \n    2004) NVIDIA_VERSION=\"525.105.17\"; \n        CUDA_VERSION=\"12-1\"; \n        CUDA_SAMPLES_VERSION=\"12.1\";\n        CHECKSUM=\"c635a21a282c9b53485f19ebb64a0f4b536a968b94d4d97629e0bc547a58142a\";;\n    2204) NVIDIA_VERSION=\"525.105.17\"; \n        CUDA_VERSION=\"12-1\"; \n        CUDA_SAMPLES_VERSION=\"12.1\";\n        CHECKSUM=\"c635a21a282c9b53485f19ebb64a0f4b536a968b94d4d97629e0bc547a58142a\";;\n    *) ;;\nesac\n\n# Reference - https://docs.nvidia.com/cuda/cuda-installation-guide-linux/index.html#ubuntu-installation\n# Install Cuda\nwget https://developer.download.nvidia.com/compute/cuda/repos/ubuntu${VERSION}/x86_64/cuda-keyring_1.0-1_all.deb\ndpkg -i ./cuda-keyring_1.0-1_all.deb\n\napt-get update\napt install -y cuda-toolkit-${CUDA_VERSION}\necho 'export PATH=$PATH:/usr/local/cuda/bin' | tee -a /etc/bash.bashrc\necho 'export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64' | tee -a /etc/bash.bashrc\n$COMMON_DIR/write_component_version.sh \"CUDA\" ${CUDA_VERSION}\n\n# Download CUDA samples\nTARBALL=\"v${CUDA_SAMPLES_VERSION}.tar.gz\"\nCUDA_SAMPLES_DOWNLOAD_URL=https://github.com/NVIDIA/cuda-samples/archive/refs/tags/${TARBALL}\nwget ${CUDA_SAMPLES_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\npushd ./cuda-samples-${CUDA_SAMPLES_VERSION}\nmake\nmv -vT ./Samples /usr/local/cuda-${CUDA_SAMPLES_VERSION}/samples\npopd\n\n# Nvidia driver\nNVIDIA_DRIVER_URL=https://us.download.nvidia.com/tesla/${NVIDIA_VERSION}/NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run\n$COMMON_DIR/download_and_verify.sh $NVIDIA_DRIVER_URL ${CHECKSUM}\nbash NVIDIA-Linux-x86_64-${NVIDIA_VERSION}.run --silent --dkms\n$COMMON_DIR/write_component_version.sh \"NVIDIA\" ${NVIDIA_VERSION}\n", "num_lines": 49}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Parameter\n# Ubuntu Version\nVERSION=$1\n\n# Install nvidia fabric manager\ncase ${VERSION} in\n    1804) NVIDIA_FABRIC_MANAGER_VERSION=\"525_525.105.17-1\"; \n        CHECKSUM=\"b487db5923194ba9f4d7c34891f4f8513a3f633a22a0c9f51fba3ef971681977\";\n        VERSION_PREFIX=\"525\";; \n    2004) NVIDIA_FABRIC_MANAGER_VERSION=\"525_525.105.17-1\"; \n        CHECKSUM=\"b487db5923194ba9f4d7c34891f4f8513a3f633a22a0c9f51fba3ef971681977\";\n        VERSION_PREFIX=\"525\";;\n    2204) NVIDIA_FABRIC_MANAGER_VERSION=\"525_525.105.17-1\"; \n        CHECKSUM=\"b487db5923194ba9f4d7c34891f4f8513a3f633a22a0c9f51fba3ef971681977\";\n        VERSION_PREFIX=\"525\";;\n    *) ;;\nesac\n\nNVIDIA_FABRIC_MNGR_URL=http://developer.download.nvidia.com/compute/cuda/repos/ubuntu${VERSION}/x86_64/nvidia-fabricmanager-${NVIDIA_FABRIC_MANAGER_VERSION}_amd64.deb\n$COMMON_DIR/download_and_verify.sh $NVIDIA_FABRIC_MNGR_URL ${CHECKSUM}\napt install -y ./nvidia-fabricmanager-${NVIDIA_FABRIC_MANAGER_VERSION}_amd64.deb\napt-mark hold nvidia-fabricmanager-${VERSION_PREFIX}\n$COMMON_DIR/write_component_version.sh \"NVIDIA_FABRIC_MANAGER\" ${NVIDIA_FABRIC_MANAGER_VERSION}\n", "num_lines": 27}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install NV Peer Memory (GPU Direct RDMA)\nsudo apt install -y dkms libnuma-dev\nNV_PEER_MEMORY_VERSION=\"1.3-0\"\nNV_PEER_MEMORY_VERSION_PREFIX=$(echo ${NV_PEER_MEMORY_VERSION} | awk -F- '{print $1}')\nTARBALL=\"${NV_PEER_MEMORY_VERSION}.tar.gz\"\nNV_PEER_MEM_DOWNLOAD_URL=\"https://github.com/Mellanox/nv_peer_memory/archive/refs/tags/${TARBALL}\"\nwget ${NV_PEER_MEM_DOWNLOAD_URL}\ntar -xvf $TARBALL\n\npushd nv_peer_memory-${NV_PEER_MEMORY_VERSION}\n./build_module.sh\npopd\n\npushd /tmp\ntar xzf /tmp/nvidia-peer-memory_${NV_PEER_MEMORY_VERSION_PREFIX}.orig.tar.gz\npushd nvidia-peer-memory-${NV_PEER_MEMORY_VERSION_PREFIX}/\n# Fix for issue - https://github.com/Mellanox/nv_peer_memory/issues/106\nsed -i s/1.2-0/${NV_PEER_MEMORY_VERSION}/g ./debian/changelog\ndpkg-buildpackage -us -uc \ndpkg -i ../nvidia-peer-memory_${NV_PEER_MEMORY_VERSION}_all.deb \napt-mark hold nvidia-peer-memory\ndpkg -i ../nvidia-peer-memory-dkms_${NV_PEER_MEMORY_VERSION}_all.deb \napt-mark hold nvidia-peer-memory-dkms\npopd\npopd\n\n# load the nvidia-peermem coming as a part of NVIDIA GPU driver\n# Reference - https://download.nvidia.com/XFree86/Linux-x86_64/510.85.02/README/nvidia-peermem.html\n# Stop nv_peer_mem service\nservice nv_peer_mem stop\n# unload nv_peer_mem\nrmmod nv_peer_mem\n# load nvidia-peermem\nmodprobe nvidia-peermem\n# verify if loaded\nlsmod | grep nvidia_peermem\n\n$COMMON_DIR/write_component_version.sh \"NV_PEER_MEMORY\" ${NV_PEER_MEMORY_VERSION}\n", "num_lines": 42}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\napt-get update\napt-get -y install build-essential\napt-get -y install numactl \\\n                   rpm \\\n                   libnuma-dev \\\n                   libmpc-dev \\\n                   libmpfr-dev \\\n                   libxml2-dev \\\n                   m4 \\\n                   byacc \\\n                   python-setuptools \\\n                   tcl \\\n                   environment-modules \\\n                   tk \\\n                   texinfo \\\n                   libudev-dev \\\n                   binutils \\\n                   binutils-dev \\\n                   selinux-policy-dev \\\n                   flex \\\n                   libnl-3-dev \\\n                   libnl-route-3-dev \\\n                   libnl-3-200 \\\n                   libnl-genl-3-dev \\\n                   libnl-genl-3-200 \\\n                   bison \\\n                   libnl-route-3-200 \\\n                   gfortran \\\n                   cmake \\\n                   libnl-3-dev \\\n                   libnl-route-3-dev \\\n                   net-tools \\\n                   libsecret-1-0 \\\n                   python3-pip \\\n                   dkms \\\n                   jq \\\n                   curl \\\n                   libyaml-dev \\\n                   libreadline-dev \\\n                   libkeyutils1 \\\n                   libkeyutils-dev \\\n                   libmount-dev \\\n                   nfs-common \\\n                   pssh\n\nif [[ $DISTRIBUTION != \"ubuntu22.04\" ]]; then apt-get install -y python-dev; fi\n\n# Install azcopy tool\n# To copy blobs or files to or from a storage account.\n# Parameters - Version, Release Tag\nVERSION=$1\nRELEASE_TAG=$2\nTARBALL=\"azcopy_linux_amd64_${VERSION}.tar.gz\"\nAZCOPY_DOWNLOAD_URL=\"https://azcopyvnext.azureedge.net/${RELEASE_TAG}/${TARBALL}\"\nAZCOPY_FOLDER=$(basename ${AZCOPY_DOWNLOAD_URL} .tgz)\nwget ${AZCOPY_DOWNLOAD_URL}\ntar -xvf ${TARBALL}\n\n# copy the azcopy to the bin path\npushd azcopy_linux_amd64_${VERSION}\ncp azcopy /usr/bin/\npopd\n\n# Allow execute permissions\nchmod +x /usr/bin/azcopy\n\n# remove tarball from azcopy\nrm -rf *.tar.gz\n\n# copy kvp client file\n$COMMON_DIR/copy_kvp_client.sh\n", "num_lines": 75}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nsource /etc/lsb-release\n\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/amlfs-${DISTRIB_CODENAME}/ ${DISTRIB_CODENAME} main\" | sudo tee /etc/apt/sources.list.d/amlfs.list\n\n# Enable these lines if the MS PMC repo was not already setup.\n#curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\n#cp ./microsoft.gpg /etc/apt/trusted.gpg.d/\n", "num_lines": 11}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install Lustre client\n$UBUNTU_COMMON_DIR/install_lustre_client.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# Install NCCL\n$UBUNTU_COMMON_DIR/install_nccl.sh\n\n# Install NVIDIA docker container\n$UBUNTU_COMMON_DIR/install_docker.sh\n\n# cleanup downloaded tarballs - clear some space\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\nrm -rf /tmp/MLNX_OFED_LINUX* /tmp/*conf*\nrm -rf /var/intel/ /var/cache/*\nrm -Rf -- */\n\n# Install DCGM\n$UBUNTU_COMMON_DIR/install_dcgm.sh\n\n# install Intel libraries\n$UBUNTU_COMMON_DIR/install_intel_libs.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# optimizations\n$UBUNTU_COMMON_DIR/hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install monitor tools\n$UBUNTU_COMMON_DIR/install_monitoring_tools.sh\n\n# diable auto kernel updates\n$UBUNTU_COMMON_DIR/disable_auto_upgrade.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 64}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"23.04-1.1.3.0\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-ubuntu18.04-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"634960b96698f845ccc8974987c71dfeced4553ddc5fb0aa1a79071307cbdd45\"\ntar zxvf ${TARBALL}\n\n./${MOFED_FOLDER}/mlnxofedinstall --add-kernel-support --skip-unsupported-devices-check --without-fw-update\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# Restarting openibd\n/etc/init.d/openibd restart\n\n## Fix for systemd-modules-load service failing on boot\nrm -rf /lib/modules/$(uname -r)/kernel/drivers/infiniband/ulp/iser/ib_iser.ko\ndepmod\n", "num_lines": 21}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install common MPIs for Ubuntu\n$UBUNTU_COMMON_DIR/install_mpis.sh \"c8868382a7b93286cd70ac46c63489f176bbfe0d76b3e5b2b91ecc0f93272414\"\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n$UBUNTU_COMMON_DIR/install_nvidiagpudriver.sh 1804\n\n# Install gdrcopy\nsudo apt install -y build-essential devscripts debhelper check libsubunit-dev fakeroot pkg-config dkms\nGDRCOPY_VERSION=\"2.3\"\nTARBALL=\"v${GDRCOPY_VERSION}.tar.gz\"\nGDRCOPY_DOWNLOAD_URL=https://github.com/NVIDIA/gdrcopy/archive/refs/tags/${TARBALL}\nwget $GDRCOPY_DOWNLOAD_URL\ntar -xvf $TARBALL\n\npushd gdrcopy-${GDRCOPY_VERSION}/packages/\nCUDA=/usr/local/cuda ./build-deb-packages.sh \nsudo dpkg -i gdrdrv-dkms_${GDRCOPY_VERSION}-1_amd64.Ubuntu18_04.deb\nsudo apt-mark hold gdrdrv-dkms\nsudo dpkg -i libgdrapi_${GDRCOPY_VERSION}-1_amd64.Ubuntu18_04.deb\nsudo apt-mark hold libgdrapi\nsudo dpkg -i gdrcopy-tests_${GDRCOPY_VERSION}-1_amd64.Ubuntu18_04.deb\nsudo apt-mark hold gdrcopy-tests\nsudo dpkg -i gdrcopy_${GDRCOPY_VERSION}-1_amd64.Ubuntu18_04.deb\nsudo apt-mark hold gdrcopy\npopd\n\n$COMMON_DIR/write_component_version.sh \"GDRCOPY\" ${GDRCOPY_VERSION}\n\n# Install nvidia fabric manager (required for ND96asr_v4)\n$UBUNTU_COMMON_DIR/install_nvidia_fabric_manager.sh 1804\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > ./microsoft-prod.list\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.list /etc/apt/sources.list.d/\n# Install the Microsoft GPG public key\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\ncp ./microsoft.gpg /etc/apt/trusted.gpg.d/\n\n#install apt pckages\nAZCOPY_VERSION=\"10.16.2\"\nAZCOPY_RELEASE_TAG=\"release20221108\"\n$UBUNTU_COMMON_DIR/install_utils.sh ${AZCOPY_VERSION} ${AZCOPY_RELEASE_TAG}\n\napt-get update\napt-get install -y python3.8\nupdate-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.8 1\napt-get -y install --reinstall python3-apt\n\napt-get -y install python3-pip\nDISTPACK=/usr/lib/python3/dist-packages\ncp $DISTPACK/apt_pkg.cpython-36m-x86_64-linux-gnu.so $DISTPACK/apt_pkg.so\napt-get install -y libcairo2-dev\napt-get install -y python3-dev\napt-get install -y libpython3.8-dev\napt-get install -y libgirepository1.0-dev\npython3.8 -m pip install --ignore-installed PyGObject\napt-get install -y software-properties-common\n\n# For networkd-dispatcher + unattended-upgrades services to work correctly. Specific to ubunut 18.04\nln -sf  /usr/lib/python3/dist-packages/_dbus_glib_bindings.cpython-36m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/_dbus_glib_bindings.so\nln -sf  /usr/lib/python3/dist-packages/_dbus_bindings.cpython-36m-x86_64-linux-gnu.so /usr/lib/python3/dist-packages/_dbus_bindings.so\napt-get -y install libglib2.0-dev libdbus-1-3 libdbus-1-dev\n\nsudo python3 -m  pip install meson ninja\nsudo python3 -m pip install pgi dbus-python \n", "num_lines": 40}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport UBUNTU_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install Lustre client\n$UBUNTU_COMMON_DIR/install_lustre_client.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# Install NCCL\n./install_nccl.sh\n\n# cleanup downloaded tarballs\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\nrm -Rf -- */\n\n# Install DCGM\n$UBUNTU_COMMON_DIR/install_dcgm.sh\n\n# install Intel libraries\n$UBUNTU_COMMON_DIR/install_intel_libs.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# optimizations\n$UBUNTU_COMMON_DIR/hpc-tuning.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# diable auto kernel updates\n$UBUNTU_COMMON_DIR/disable_auto_upgrade.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 53}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"4.9-6.0.6.0\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-ubuntu18.04-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"ca56ddf53a22192d2c91d1c410db686a8f8faf339020cfe44ab0c664e63c8b99\"\ntar zxvf ${TARBALL}\n\n./${MOFED_FOLDER}/mlnxofedinstall --add-kernel-support --without-fw-update\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# Restarting openibd\n/etc/init.d/openibd restart\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Load gcc\nGCC_VERSION=gcc-9.2.0\nset CC=/usr/bin/gcc\nset GCC=/usr/bin/gcc\n\nINSTALL_PREFIX=/opt\n\n# HPC-X v2.7.0\nMLNX_OFED_VERSION=\"4.7-1.0.0.1\"\nHPCX_VERSION=\"v2.7.0\"\nTARBALL=\"hpcx-${HPCX_VERSION}-gcc-MLNX_OFED_LINUX-${MLNX_OFED_VERSION}-${DISTRIBUTION}-x86_64.tbz\"\nHPCX_DOWNLOAD_URL=https://azhpcstor.blob.core.windows.net/azhpc-images-store/${TARBALL}\nHPCX_FOLDER=$(basename ${HPCX_DOWNLOAD_URL} .tbz)\n\n$COMMON_DIR/download_and_verify.sh $HPCX_DOWNLOAD_URL \"83f03e2d01cb1e4198e50ed9bdadb742aebf5d247369071bc911096824147d7a\"\ntar -xvf ${TARBALL}\nmv ${HPCX_FOLDER} ${INSTALL_PREFIX}\nHPCX_PATH=${INSTALL_PREFIX}/${HPCX_FOLDER}\n$COMMON_DIR/write_component_version.sh \"HPCX\" ${HPCX_VERSION}\n\n# MVAPICH2 2.3.7\nMV2_VERSION=\"2.3.7\"\nMV2_DOWNLOAD_URL=http://mvapich.cse.ohio-state.edu/download/mvapich/mv2/mvapich2-${MV2_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $MV2_DOWNLOAD_URL \"c39a4492f4be50df6100785748ba2894e23ce450a94128181d516da5757751ae\"\ntar -xvf mvapich2-${MV2_VERSION}.tar.gz\ncd mvapich2-${MV2_VERSION}\n./configure --prefix=${INSTALL_PREFIX}/mvapich2-${MV2_VERSION} --enable-g=none --enable-fast=yes && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"MVAPICH2\" ${MV2_VERSION}\n\n# OpenMPI 4.1.3\nOMPI_VERSION=\"4.1.5\"\nOMPI_DOWNLOAD_URL=https://download.open-mpi.org/release/open-mpi/v4.1/openmpi-${OMPI_VERSION}.tar.gz\n$COMMON_DIR/download_and_verify.sh $OMPI_DOWNLOAD_URL \"c018b127619d2a2a30c1931f316fc8a245926d0f5b4ebed4711f9695e7f70925\"\ntar -xvf openmpi-${OMPI_VERSION}.tar.gz\ncd openmpi-${OMPI_VERSION}\n# disable OpenSHMEM build\nsed -i \"s/enable_oshmem_fortran=yes/enable_oshmem_fortran=no/\" contrib/platform/mellanox/optimized\nsed -i \"s/enable_oshmem=yes/enable_oshmem=no/\" contrib/platform/mellanox/optimized\n./configure --prefix=${INSTALL_PREFIX}/openmpi-${OMPI_VERSION} --with-ucx=${UCX_PATH} --with-hcoll=${HCOLL_PATH} --enable-mpirun-prefix-by-default --disable-oshmem --with-platform=contrib/platform/mellanox/optimized && make -j$(nproc) && make install\ncd ..\n$COMMON_DIR/write_component_version.sh \"OMPI\" ${OMPI_VERSION}\n\n# Intel MPI 2021 (Update 7)\nIMPI_2021_VERSION=\"2021.9.0\"\nIMPI_2021_DOWNLOAD_URL=https://registrationcenter-download.intel.com/akdlm/IRC_NAS/718d6f8f-2546-4b36-b97b-bc58d5482ebf/l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh\n$COMMON_DIR/download_and_verify.sh $IMPI_2021_DOWNLOAD_URL \"5c170cdf26901311408809ced28498b630a494428703685203ceef6e62735ef8\"\nbash l_mpi_oneapi_p_${IMPI_2021_VERSION}.43482_offline.sh -s -a -s --eula accept\nmv ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/mpi ${INSTALL_PREFIX}/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\n$COMMON_DIR/write_component_version.sh \"IMPI_2021\" ${IMPI_2021_VERSION}\n\n# Module Files\nMODULE_FILES_DIRECTORY=/usr/share/modules/modulefiles/mpi\nmkdir -p ${MODULE_FILES_DIRECTORY}\n\n# HPC-X\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/hpcx-${HPCX_VERSION}\n#%Module 1.0\n#\n#  HPCx ${HPCX_VERSION}\n#\nconflict        mpi\nmodule load ${HPCX_PATH}/modulefiles/hpcx\nEOF\n\n# MVAPICH2\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/mvapich2-${MV2_VERSION}\n#%Module 1.0\n#\n#  MVAPICH2 ${MV2_VERSION}\n#\nconflict        mpi\nprepend-path    PATH            /opt/mvapich2-${MV2_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/mvapich2-${MV2_VERSION}/lib\nprepend-path    MANPATH         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_BIN         /opt/mvapich2-${MV2_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/mvapich2-${MV2_VERSION}/include\nsetenv          MPI_LIB         /opt/mvapich2-${MV2_VERSION}/lib\nsetenv          MPI_MAN         /opt/mvapich2-${MV2_VERSION}/share/man\nsetenv          MPI_HOME        /opt/mvapich2-${MV2_VERSION}\nEOF\n\n# OpenMPI\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/openmpi-${OMPI_VERSION}\n#%Module 1.0\n#\n#  OpenMPI ${OMPI_VERSION}\n#\nconflict        mpi\nprepend-path    PATH            /opt/openmpi-${OMPI_VERSION}/bin\nprepend-path    LD_LIBRARY_PATH /opt/openmpi-${OMPI_VERSION}/lib\nprepend-path    MANPATH         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_BIN         /opt/openmpi-${OMPI_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/openmpi-${OMPI_VERSION}/include\nsetenv          MPI_LIB         /opt/openmpi-${OMPI_VERSION}/lib\nsetenv          MPI_MAN         /opt/openmpi-${OMPI_VERSION}/share/man\nsetenv          MPI_HOME        /opt/openmpi-${OMPI_VERSION}\nEOF\n\n# Intel 2021\ncat << EOF >> ${MODULE_FILES_DIRECTORY}/impi_${IMPI_2021_VERSION}\n#%Module 1.0\n#\n#  Intel MPI ${IMPI_2021_VERSION}\n#\nconflict        mpi\nmodule load /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/modulefiles/impi\nsetenv          MPI_BIN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/bin\nsetenv          MPI_INCLUDE     /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/include\nsetenv          MPI_LIB         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/lib\nsetenv          MPI_MAN         /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}/man\nsetenv          MPI_HOME        /opt/intel/oneapi/mpi/${IMPI_2021_VERSION}\nEOF\n\n# Softlinks\nln -s ${MODULE_FILES_DIRECTORY}/hpcx-${HPCX_VERSION} ${MODULE_FILES_DIRECTORY}/hpcx\nln -s ${MODULE_FILES_DIRECTORY}/mvapich2-${MV2_VERSION} ${MODULE_FILES_DIRECTORY}/mvapich2\nln -s ${MODULE_FILES_DIRECTORY}/openmpi-${OMPI_VERSION} ${MODULE_FILES_DIRECTORY}/openmpi\nln -s ${MODULE_FILES_DIRECTORY}/impi_${IMPI_2021_VERSION} ${MODULE_FILES_DIRECTORY}/impi-2021\n", "num_lines": 123}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Skip installation of NCCL RDMA sharp plugin for CX-3 pro\nsed -i '35,43 s/^/#/' $UBUNTU_COMMON_DIR/install_nccl.sh\n$UBUNTU_COMMON_DIR/install_nccl.sh\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n$UBUNTU_COMMON_DIR/install_nvidiagpudriver.sh 1804\n", "num_lines": 5}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/ubuntu/18.04/prod.list > ./microsoft-prod.list\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.list /etc/apt/sources.list.d/\n# Install the Microsoft GPG public key\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\ncp ./microsoft.gpg /etc/apt/trusted.gpg.d/\n\n#apt-get install packages\nAZCOPY_VERSION=\"10.17.0\"\nAZCOPY_RELEASE_TAG=\"release20230123\"\n$UBUNTU_COMMON_DIR/install_utils.sh ${AZCOPY_VERSION} ${AZCOPY_RELEASE_TAG}\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport UBUNTU_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install Lustre client\n$UBUNTU_COMMON_DIR/install_lustre_client.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# Install NCCL\n$UBUNTU_COMMON_DIR/install_nccl.sh\n\n# Install NVIDIA docker container\n$UBUNTU_COMMON_DIR/install_docker.sh\n\n# cleanup downloaded tarballs - clear some space\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\nrm -rf /tmp/MLNX_OFED_LINUX* /tmp/*conf*\nrm -rf /var/intel/ /var/cache/*\nrm -Rf -- */\n\n# Install DCGM\n$UBUNTU_COMMON_DIR/install_dcgm.sh\n\n# install Intel libraries\n$UBUNTU_COMMON_DIR/install_intel_libs.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# optimizations\n$UBUNTU_COMMON_DIR/hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install monitor tools\n$UBUNTU_COMMON_DIR/install_monitoring_tools.sh\n\n# install AMD libs\n$UBUNTU_COMMON_DIR/install_amd_libs.sh\n\n# install Azure/NHC Health Checks\n$COMMON_DIR/install_health_checks.sh\n\n# diable auto kernel updates\n$UBUNTU_COMMON_DIR/disable_auto_upgrade.sh\n\n# Disable Predictive Network interface renaming\n$UBUNTU_COMMON_DIR/disable_predictive_interface_renaming.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 73}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"23.04-1.1.3.0\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-ubuntu20.04-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"a4b35a53100a1bbc806e558838424824039d789062a5a8cdf5589d91d3769ce4\"\ntar zxvf ${TARBALL}\n\n./${MOFED_FOLDER}/mlnxofedinstall --add-kernel-support --skip-unsupported-devices-check --without-fw-update\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# Restarting openibd\n/etc/init.d/openibd restart\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install common MPIs for Ubuntu\n$UBUNTU_COMMON_DIR/install_mpis.sh \"d1a1b73597c96b66b20e16bce880770d659c51f21214cfe1695805c785ed7f18\"\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n$UBUNTU_COMMON_DIR/install_nvidiagpudriver.sh 2004\n\n# Install gdrcopy\nsudo apt install -y build-essential devscripts debhelper check libsubunit-dev fakeroot pkg-config dkms\nGDRCOPY_VERSION=\"2.3\"\nTARBALL=\"v${GDRCOPY_VERSION}.tar.gz\"\nGDRCOPY_DOWNLOAD_URL=https://github.com/NVIDIA/gdrcopy/archive/refs/tags/${TARBALL}\nwget $GDRCOPY_DOWNLOAD_URL\ntar -xvf $TARBALL\n\npushd gdrcopy-${GDRCOPY_VERSION}/packages/\nCUDA=/usr/local/cuda ./build-deb-packages.sh \nsudo dpkg -i gdrdrv-dkms_${GDRCOPY_VERSION}-1_amd64.Ubuntu20_04.deb\nsudo apt-mark hold gdrdrv-dkms\nsudo dpkg -i libgdrapi_${GDRCOPY_VERSION}-1_amd64.Ubuntu20_04.deb\nsudo apt-mark hold libgdrapi\nsudo dpkg -i gdrcopy-tests_${GDRCOPY_VERSION}-1_amd64.Ubuntu20_04.deb\nsudo apt-mark hold gdrcopy-tests\nsudo dpkg -i gdrcopy_${GDRCOPY_VERSION}-1_amd64.Ubuntu20_04.deb\nsudo apt-mark hold gdrcopy\npopd\n\n$COMMON_DIR/write_component_version.sh \"GDRCOPY\" ${GDRCOPY_VERSION}\n\n# Install nvidia fabric manager (required for ND96asr_v4)\n$UBUNTU_COMMON_DIR/install_nvidia_fabric_manager.sh 2004\n", "num_lines": 30}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/ubuntu/20.04/prod.list > ./microsoft-prod.list\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.list /etc/apt/sources.list.d/\n# Install the Microsoft GPG public key\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\ncp ./microsoft.gpg /etc/apt/trusted.gpg.d/\n\n#apt-get install packages\nAZCOPY_VERSION=\"10.17.0\"\nAZCOPY_RELEASE_TAG=\"release20230123\"\n$UBUNTU_COMMON_DIR/install_utils.sh ${AZCOPY_VERSION} ${AZCOPY_RELEASE_TAG}\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport UBUNTU_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# set properties\nsource ./set_properties.sh\n\n# install utils\n./install_utils.sh\n\n# install Lustre client\n$UBUNTU_COMMON_DIR/install_lustre_client.sh\n\n# install mellanox ofed\n./install_mellanoxofed.sh\n\n# install mpi libraries\n./install_mpis.sh\n\n# install nvidia gpu driver\n./install_nvidiagpudriver.sh\n\n# Install NCCL\n$UBUNTU_COMMON_DIR/install_nccl.sh\n\n# Install NVIDIA docker container\n$UBUNTU_COMMON_DIR/install_docker.sh\n\n# cleanup downloaded tarballs - clear some space\nrm -rf *.tgz *.bz2 *.tbz *.tar.gz *.run *.deb *_offline.sh\nrm -rf /tmp/MLNX_OFED_LINUX* /tmp/*conf*\nrm -rf /var/intel/ /var/cache/*\nrm -Rf -- */\n\n# Install DCGM\n$UBUNTU_COMMON_DIR/install_dcgm.sh\n\n# install Intel libraries\n$UBUNTU_COMMON_DIR/install_intel_libs.sh\n\n# install diagnostic script\n$COMMON_DIR/install_hpcdiag.sh\n\n# install persistent rdma naming\n$COMMON_DIR/install_azure_persistent_rdma_naming.sh\n\n# optimizations\n$UBUNTU_COMMON_DIR/hpc-tuning.sh\n\n# copy test file\n$COMMON_DIR/copy_test_file.sh\n\n# install monitor tools\n$UBUNTU_COMMON_DIR/install_monitoring_tools.sh\n\n# install AMD libs\n$UBUNTU_COMMON_DIR/install_amd_libs.sh\n\n# install Azure/NHC Health Checks\n$COMMON_DIR/install_health_checks.sh\n\n# diable auto kernel updates\n$UBUNTU_COMMON_DIR/disable_auto_upgrade.sh\n\n# Disable Predictive Network interface renaming\n$UBUNTU_COMMON_DIR/disable_predictive_interface_renaming.sh\n\n# SKU Customization\n$COMMON_DIR/setup_sku_customizations.sh\n\n# clear history\n# Uncomment the line below if you are running this on a VM\n# $COMMON_DIR/clear_history.sh\n", "num_lines": 73}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\nVERSION=\"23.04-1.1.3.0\"\nTARBALL=\"MLNX_OFED_LINUX-$VERSION-ubuntu22.04-x86_64.tgz\"\nMLNX_OFED_DOWNLOAD_URL=https://content.mellanox.com/ofed/MLNX_OFED-${VERSION}/$TARBALL\nMOFED_FOLDER=$(basename ${MLNX_OFED_DOWNLOAD_URL} .tgz)\n\n$COMMON_DIR/download_and_verify.sh $MLNX_OFED_DOWNLOAD_URL \"8e50a0716081e13a7251d14543a0ea40481d0b3d7e82dda1ed1fc789ce6241cc\"\ntar zxvf ${TARBALL}\n\n./${MOFED_FOLDER}/mlnxofedinstall --add-kernel-support --skip-unsupported-devices-check --without-fw-update\n$COMMON_DIR/write_component_version.sh \"MOFED\" $VERSION\n\n# Restarting openibd\n/etc/init.d/openibd restart\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Install common MPIs for Ubuntu\n$UBUNTU_COMMON_DIR/install_mpis.sh \"c718d0d5339ed60a6479a52054ca9b0718253cadf528ce63ce35b4aced42797c\"\n", "num_lines": 6}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Dependency for nvidia driver installation\napt-get install -y libvulkan1\n\n$UBUNTU_COMMON_DIR/install_nvidiagpudriver.sh 2204\n\n# Install gdrcopy\nsudo apt install -y build-essential devscripts debhelper check libsubunit-dev fakeroot pkg-config dkms\nGDRCOPY_VERSION=\"2.3\"\nTARBALL=\"v${GDRCOPY_VERSION}.tar.gz\"\nGDRCOPY_DOWNLOAD_URL=https://github.com/NVIDIA/gdrcopy/archive/refs/tags/${TARBALL}\nwget $GDRCOPY_DOWNLOAD_URL\ntar -xvf $TARBALL\n\npushd gdrcopy-${GDRCOPY_VERSION}/packages/\nCUDA=/usr/local/cuda ./build-deb-packages.sh \nsudo dpkg -i gdrdrv-dkms_${GDRCOPY_VERSION}-1_amd64.Ubuntu22_04.deb\nsudo apt-mark hold gdrdrv-dkms\nsudo dpkg -i libgdrapi_${GDRCOPY_VERSION}-1_amd64.Ubuntu22_04.deb\nsudo apt-mark hold libgdrapi\nsudo dpkg -i gdrcopy-tests_${GDRCOPY_VERSION}-1_amd64.Ubuntu22_04.deb\nsudo apt-mark hold gdrcopy-tests\nsudo dpkg -i gdrcopy_${GDRCOPY_VERSION}-1_amd64.Ubuntu22_04.deb\nsudo apt-mark hold gdrcopy\npopd\n\n$COMMON_DIR/write_component_version.sh \"GDRCOPY\" ${GDRCOPY_VERSION}\n\n# Install nvidia fabric manager (required for ND96asr_v4)\n$UBUNTU_COMMON_DIR/install_nvidia_fabric_manager.sh 2204\n", "num_lines": 33}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -ex\n\n# Setup microsoft packages repository for moby\n# Download the repository configuration package\ncurl https://packages.microsoft.com/config/ubuntu/22.04/prod.list > ./microsoft-prod.list\n# Copy the generated list to the sources.list.d directory\ncp ./microsoft-prod.list /etc/apt/sources.list.d/\n# Install the Microsoft GPG public key\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\ncp ./microsoft.gpg /etc/apt/trusted.gpg.d/\n\n#apt-get install packages\nAZCOPY_VERSION=\"10.17.0\"\nAZCOPY_RELEASE_TAG=\"release20230123\"\n$UBUNTU_COMMON_DIR/install_utils.sh ${AZCOPY_VERSION} ${AZCOPY_RELEASE_TAG}\n", "num_lines": 17}
{"repo_name": "azhpc-images", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport TOP_DIR=../../..\nexport COMMON_DIR=../../../common\nexport UBUNTU_COMMON_DIR=../../common\nexport TEST_DIR=../../../tests\nexport DISTRIBUTION=$(. /etc/os-release;echo $ID$VERSION_ID)\n", "num_lines": 8}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n./create_ci.sh \\\n    azuredeploy.json \\\n    azuredeploy_template.json \\\n    ciScript \\\n    scripts \\\n    setup_lustre.sh \\\n    name \\\n    instanceCount \\\n    storageAccount \\\n    storageSas \\\n    storageContainer \\\n    ossDiskSetup \\\n    deployPolicyEngine \\\n    mdtStorageSku \\\n    ostStorageSku\n", "num_lines": 18}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nVERSION=$1\n\n./build.sh\ncp azuredeploy.json mainTemplate.json\n\nrm -f azurehpc-lustre-fs-${VERSION}.zip\nzip azurehpc-lustre-fs-${VERSION}.zip mainTemplate.json createUiDefinition.json\n\n", "num_lines": 11}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This generates the embedded scripts for the createUiDefinition file\n\necho \"virtualNetork constraints.allowedValues:\"\necho\necho $(cat <<EOF\n[\n    map(\n        filter(\n            basics('getVnetName').value,\n            (item) => contains(item.location, location())\n        ), \n        (item) => parse(\n            concat(\n                '{\\\"label\\\":\\\"', \n                item.name, \n                '\\\", \\\"description\\\":\\\"', \n                substring(\n                    item.id, \n                    add(indexOf(item.id, 'resourceGroups/'), 15), \n                    sub(\n                        indexOf(item.id, '/providers'), \n                        add(indexOf(item.id, 'resourceGroups/'), 15)\n                    )\n                ),\n                '\\\", \\\"value\\\":\\\"', \n                item.id, \n                '\\\"}'\n            )\n        )\n    )\n]\nEOF\n)\necho\n\necho \"subnet constraints.allowedValues:\"\necho\necho $(cat <<EOF\n[\n    map(\n        first(\n            map(\n                filter(\n                    basics('getVnetName').value,\n                    (item) => equals(item.id, basics('vnet'))\n                ),\n                (item) => item.properties.subnets\n            )\n        ),\n        (item) => parse(\n            concat(\n                '{\\\"label\\\":\\\"', \n                item.name,                 \n                '\\\", \\\"value\\\":\\\"', \n                item.name, \n                '\\\"}'\n            )\n        )\n    )\n]\nEOF\n)\necho\n\necho \"output - existingVnetResourceGroupName\"\necho\necho $(cat <<EOF\n[\n    substring(\n        basics('vnet'), \n        add(indexOf(basics('vnet'), 'resourceGroups/'), 15), \n        sub(\n            indexOf(basics('vnet'), '/providers'), \n            add(indexOf(basics('vnet'), 'resourceGroups/'), 15)\n        )\n    )\n]\nEOF\n)\necho\n\necho \"output - existingVnetName\"\necho\necho $(cat <<EOF\n[\n    substring(\n        basics('vnet'), \n        add(lastIndexOf(basics('vnet'), '/'), 1),\n        sub(\n            length(basics('vnet')),\n            add(lastIndexOf(basics('vnet'), '/'), 1)\n        )\n    )\n]\nEOF\n)\necho", "num_lines": 99}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ \"$1\" = \"-h\" ]; then\n    echo \"Usage:\"\n    echo \"   $0 <new_azure_deploy> <old_azure_deploy> <variable_name> <script_dir> <entry_script> [<parameter>]*\"\n    exit 0\nfi\n\nnew_azure_deploy=$1\nshift\nold_azure_deploy=$1\nshift\nvariable_name=$1\nshift\nscript_dir=$1\nshift\nentry_script=$1\nshift\necho \"new_azure_deploy=$new_azure_deploy\"\necho \"old_azure_deploy=$old_azure_deploy\"\necho \"variable_name=$variable_name\"\necho \"script_dir=$script_dir\"\necho \"entry_script=$entry_script\"\n\nif [ -e $new_azure_deploy ]; then\n    echo \"ERROR: new file already exists\"\n    exit 1\nfi\n\nscript_name=\"cloudinit_$(date +\"%Y-%m-%d_%H-%M-%S\")\"\n\nmakeself --base64 $script_dir ${script_name}.sh \"Cloudinit script\" ./$entry_script\n\nsed -i '1d;4d' ${script_name}.sh\n\necho \"[concat('#!/bin/bash\" >${script_name}.str\necho -n \"set --',\" >>${script_name}.str\n\nwhile test $# -gt 0\ndo\n    echo -n \"' \\\"',parameters('$1'),'\\\"',\" >>${script_name}.str\n    shift\ndone\necho \"'\" >>${script_name}.str\necho -n \"','\" >>${script_name}.str\nsed \"s/'/''/g\" ${script_name}.sh >>${script_name}.str \necho -n \"')]\" >>${script_name}.str\n\njq \".variables.${variable_name} = $(jq -Rs '.' <${script_name}.str)\" $old_azure_deploy >$new_azure_deploy\n\nrm ${script_name}.sh ${script_name}.str\n", "num_lines": 52}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nyum install -y epel-release\nyum install -y dstat\n", "num_lines": 5}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsetenforce 0\nsed -i 's/SELINUX=.*$/SELINUX=disabled/g' /etc/selinux/config\n", "num_lines": 5}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nyum -y install lustre kmod-lustre-osd-ldiskfs lustre-osd-ldiskfs-mount lustre-resource-agents e2fsprogs lustre-tests || exit 1\n\nsed -i 's/ResourceDisk\\.Format=y/ResourceDisk.Format=n/g' /etc/waagent.conf\n\nsystemctl restart waagent\n\nweak-modules --add-kernel --no-initramfs\n\nif [ -f \"/etc/systemd/system/temp-disk-swapfile.service\" ]; then\n    systemctl stop temp-disk-swapfile.service\n    systemctl disable temp-disk-swapfile.service\nfi\n\numount /mnt/resource\n\nsed -i '/^ - disk_setup$/d;/^ - mounts$/d' /etc/cloud/cloud.cfg\nsed -i '/azure_resource-part1/d' /etc/fstab\n", "num_lines": 20}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nlustre_version=${1-2.10}\n\nif [ \"$lustre_version\" = \"2.10\" -o \"$lustre_version\" = \"2.12\" ]; then\n    lustre_dir=latest-${lustre_version}-release\nelse\n    lustre_dir=\"lustre-$lustre_version\"\nfi\n\ncat << EOF >/etc/yum.repos.d/LustrePack.repo\n[lustreserver]\nname=lustreserver\nbaseurl=https://downloads.whamcloud.com/public/lustre/${lustre_dir}/el7/patchless-ldiskfs-server/\nenabled=1\ngpgcheck=0\n\n[e2fs]\nname=e2fs\nbaseurl=https://downloads.whamcloud.com/public/e2fsprogs/latest/el7/\nenabled=1\ngpgcheck=0\n\n[lustreclient]\nname=lustreclient\nbaseurl=https://downloads.whamcloud.com/public/lustre/${lustre_dir}/el7/client/\nenabled=1\ngpgcheck=0\nEOF\n", "num_lines": 29}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = raid_device (e.g. /dev/md10)\n# arg: $* = devices to use (can use globbing)\n\nraid_device=$1\nshift\n\ndevices=\nwhile (( \"$#\" )); do\n    devices=\"$devices $1\"\n    shift\ndone\n\necho \"devices=$devices\"\n\n# print partition information\nparted -s --list 2>/dev/null\n\n# creating the partitions\nfor disk in $devices; do\n    echo \"partitioning $disk\"\n    parted -s $disk \"mklabel gpt\"\n    parted -s $disk -a optimal \"mkpart primary 1 -1\"\n    parted -s $disk print\n    parted -s $disk \"set 1 raid on\"\ndone\n\n# make sure all the partitions are ready\nsleep 10\n# get the partition names\npartitions=\nfor disk in $devices; do\n    partitions=\"$partitions $(lsblk -no kname -p $disk | tail -n1)\"\ndone\necho \"partitions=$partitions\"\n\nndevices=$(echo $partitions | wc -w)\n\necho \"creating raid device\"\nmdadm --create $raid_device --level 0 --raid-devices $ndevices $partitions || exit 1\nsleep 10\n\nmdadm --verbose --detail --scan > /etc/mdadm.conf\n", "num_lines": 45}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nethtool -L eth1 tx 8 rx 8 && ifconfig eth1 down && ifconfig eth1 up\n", "num_lines": 4}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = lfsserver\n# arg: $2 = storage account\n# arg: $3 = storage key\n# arg: $4 = storage container\nmaster=\"$1\"\nstorage_account=\"$2\"\nstorage_sas=\"$3\"\nstorage_container=\"$4\"\n\nmkdir -p /var/run/lhsmd\nchmod 755 /var/run/lhsmd\n\nmkdir -p /etc/lhsmd\nchmod 755 /etc/lhsmd\n\ncat <<EOF >/etc/lhsmd/agent\n# Lustre NID and filesystem name for the front end filesystem, the agent will mount this\nclient_device=\"${master}@tcp:/LustreFS\"\n\n# Do you want to use S3 and POSIX, in this example we use POSIX\nenabled_plugins=[\"lhsm-plugin-az\"]\n\n## Directory to look for the plugins\nplugin_dir=\"/usr/libexec/lhsmd\"\n\n# TBD, I used 16\nhandler_count=16\n\n# TBD\nsnapshots {\n        enabled = false\n}\nEOF\nchmod 600 /etc/lhsmd/agent\n\ncat <<EOF >/etc/lhsmd/lhsm-plugin-az\nnum_threads=16\naz_storage_account=\"$storage_account\"\naz_storage_sas=\"?$storage_sas\"\naz_kv_name=\"\"\naz_kv_secret_name=\"\"\nbandwidth=0\nexportprefix=\"\"\narchive \"archive1\" {\n    id=1\n    num_threads=16\n    root=\"\"\n    compression=\"off\"\n    container=\"$storage_container\"\n}\nEOF\nchmod 600 /etc/lhsmd/lhsm-plugin-az\n\ncat <<EOF >/etc/systemd/system/lhsmd.service\n[Unit]\nDescription=The lhsmd server\nAfter=syslog.target network.target remote-fs.target nss-lookup.target\n\n[Service]\nType=simple\nPIDFile=/run/lhsmd.pid\nExecStartPre=/bin/mkdir -p /var/run/lhsmd\nExecStart=/sbin/lhsmd -config /etc/lhsmd/agent\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\nEOF\nchmod 600 /etc/systemd/system/lhsmd.service\n\nsystemctl daemon-reload\nsystemctl enable lhsmd\nsystemctl start lhsmd\n", "num_lines": 76}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = storage account\n# arg: $2 = storage sas\n# arg: $3 = storage container\n# arg: $3 = lfs mount\n# arg: $4 = lustre mount (default=/lustre)\nstorage_account=\"$1\"\nstorage_sas=\"$2\"\nstorage_container=\"$3\"\nlfs_mount=${4:-/lustre}\n\ncd $lfs_mount\nexport STORAGE_SAS=\"?$storage_sas\"\n/sbin/azure-import -account ${storage_account} -container ${storage_container}\n\n", "num_lines": 17}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = device (e.g. L=/dev/sdb Lv2=/dev/nvme0n1)\ndevice=$1\nnum_oss=$2\n# default of 3 concurrent hsm requests per oss\nreqs_per_oss=${3:-3}\n\nmkfs.lustre --fsname=LustreFS --mgs --mdt --mountfsoptions=\"user_xattr,errors=remount-ro\" --backfstype=ldiskfs --reformat $device --index 0 || exit 1\n\nmkdir /mnt/mgsmds\necho \"$device /mnt/mgsmds lustre noatime,nodiratime,nobarrier 0 2\" >> /etc/fstab\nmount -a\n\n# set up hsm\nlctl set_param -P mdt.*-MDT0000.hsm_control=enabled\nlctl set_param -P mdt.*-MDT0000.hsm.default_archive_id=1\nlctl set_param mdt.*-MDT0000.hsm.max_requests=$(($num_oss * $reqs_per_oss))\n\n# allow any user and group ids to write\nlctl set_param mdt.*-MDT0000.identity_upcall=NONE\n", "num_lines": 22}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = lfsmaster\n# arg: $2 = device (e.g. L=/dev/sdb Lv2=/dev/nvme0n1)\n# arg: $3 = start index\nmaster=$1\ndevices=$2\nindex=$3\n\nndevices=$(wc -w <<<$devices)\n\nfor device in $devices; do\n\n    mkfs.lustre \\\n        --fsname=LustreFS \\\n        --backfstype=ldiskfs \\\n        --reformat \\\n        --ost \\\n        --mgsnode=$master \\\n        --index=$index \\\n        --mountfsoptions=\"errors=remount-ro\" \\\n        $device\n\n    mkdir /mnt/oss${index}\n    echo \"$device /mnt/oss${index} lustre noatime,nodiratime,nobarrier 0 2\" >> /etc/fstab\n\n    index=$(( $index + 1 ))\n\ndone\n\nmount -a\n", "num_lines": 32}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmds=\"$1\"\nstorage_account=\"$2\"\nstorage_sas=\"$3\"\nstorage_container=\"$4\"\n\nlfs_mount=/lustre\n\n# install deps\nyum install -y mariadb-server mariadb-devel jemalloc expect\n\n# install rbh packages\nyum install -y \\\n    https://azurehpc.azureedge.net/rpms/robinhood-adm-3.1.6-1.x86_64.rpm \\\n    https://azurehpc.azureedge.net/rpms/robinhood-tools-3.1.6-1.lustre2.12.el7.x86_64.rpm \\\n    https://azurehpc.azureedge.net/rpms/robinhood-lustre-3.1.6-1.lustre2.12.el7.x86_64.rpm\n\n\n# enable and start DB\nsystemctl enable mariadb\nsystemctl start mariadb\n\n# create DB password\nrbhpass=$(openssl rand -base64 12)\nrbh-config create_db lustre \"%\" \"$rbhpass\" || exit 1\necho \"$rbhpass\" > /etc/robinhood.d/.dbpassword\nchmod 600 /etc/robinhood.d/.dbpassword\n\nrbh_config_file=/etc/robinhood.d/lustre.conf\ncat <<EOF >$rbh_config_file\n# -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil; -*-\n# vim:expandtab:shiftwidth=4:tabstop=4:\n\nGeneral\n{\n    fs_path = \"/lustre\";\n    fs_type = lustre;\n    stay_in_fs = yes;\n    check_mounted = yes;\n    last_access_only_atime = no;\n    uid_gid_as_numbers = no;\n}\n\n# logs configuration\nLog\n{\n    # log levels: CRIT, MAJOR, EVENT, VERB, DEBUG, FULL\n    debug_level = EVENT;\n\n    # Log file\n    log_file = \"/var/log/robinhood.log\";\n\n    # File for reporting purge events\n    report_file = \"/var/log/robinhood_actions.log\";\n    alert_file = \"/var/log/robinhood_alerts.log\";\n    changelogs_file = \"/var/log/robinhood_cl.log\";\n\n    stats_interval = 5min;\n\n    batch_alert_max = 5000;\n    alert_show_attrs = yes;\n    log_procname = yes;\n    log_hostname = yes;\n}\n\n# updt params configuration\ndb_update_params\n{\n    # possible policies for refreshing metadata and path in database:\n    #   never: get the information once, then never refresh it\n    #   always: always update entry info when processing it\n    #   on_event: only update on related event\n    #   periodic(interval): only update periodically\n    #   on_event_periodic(min_interval,max_interval)= on_event + periodic\n\n    # Updating of file metadata\n    md_update = always ;\n    # Updating file path in database\n    path_update = on_event_periodic(0,1h) ;\n    # File classes matching\n    fileclass_update = always ;\n}\n\n# list manager configuration\nListManager\n{\n    # Method for committing information to database.\n    # Possible values are:\n    # - \"autocommit\": weak transactions (more efficient, but database inconsistencies may occur)\n    # - \"transaction\": manage operations in transactions (best consistency, lower performance)\n    # - \"periodic(<nb_transaction>)\": periodically commit (every <n> transactions).\n    commit_behavior = transaction ;\n\n    # Minimum time (in seconds) to wait before trying to reestablish a lost connection.\n    # Then this time is multiplied by 2 until reaching connect_retry_interval_max\n    connect_retry_interval_min = 1 ;\n    connect_retry_interval_max = 30 ;\n    # disable the following options if you are not interested in\n    # user or group stats (to speed up scan)\n    accounting  = enabled ;\n\n    MySQL\n    {\n        server = \"localhost\" ;\n        db     = \"lustre\" ;\n        user   = \"robinhood\" ;\n        password_file = \"/etc/robinhood.d/.dbpassword\" ;\n        # port   = 3306 ;\n        # socket = \"/tmp/mysql.sock\" ;\n        engine = InnoDB ;\n    }\n}\n\n# entry processor configuration\nEntryProcessor\n{\n    # nbr of worker threads for processing pipeline tasks\n    nb_threads = 16 ;\n\n    # Max number of operations in the Entry Processor pipeline.\n    # If the number of pending operations exceeds this limit, \n    # info collectors are suspended until this count decreases\n    max_pending_operations = 100 ;\n\n    # max batched DB operations (1=no batching)\n    max_batch_size = 100;\n\n    # Optionnaly specify a maximum thread count for each stage of the pipeline:\n    # <stagename>_threads_max = <n> (0: use default)\n    # STAGE_GET_FID_threads_max = 4 ;\n    # STAGE_GET_INFO_DB_threads_max     = 4 ;\n    # STAGE_GET_INFO_FS_threads_max     = 4 ;\n    # STAGE_PRE_APPLY_threads_max       = 4 ;\n    # Disable batching (max_batch_size=1) or accounting (accounting=no)\n    # to allow parallelizing the following step:\n    # STAGE_DB_APPLY_threads_max        = 4 ;\n\n    # if set to 'no', classes will only be matched\n    # at policy application time (not during a scan or reading changelog)\n    match_classes = yes;\n\n    # Faking mtime to an old time causes the file to be migrated\n    # with top priority. Enabling this parameter detect this behavior\n    # and doesn't allow  mtime < creation_time\n    detect_fake_mtime = no;\n}\n\n# FS scan configuration\nFS_Scan\n{\n    # simple scan interval (fixed)\n    scan_interval      =   2d ;\n\n    # min/max for adaptive scan interval:\n    # the more the filesystem is full, the more frequently it is scanned.\n    #min_scan_interval      =   24h ;\n    #max_scan_interval      =    7d ;\n\n    # number of threads used for scanning the filesystem\n    nb_threads_scan        =     2 ;\n\n    # when a scan fails, this is the delay before retrying\n    scan_retry_delay       =    1h ;\n\n    # timeout for operations on the filesystem\n    scan_op_timeout        =    1h ;\n    # exit if operation timeout is reached?\n    exit_on_timeout        =    yes ;\n    # external command called on scan termination\n    # special arguments can be specified: {cfg} = config file path,\n    # {fspath} = path to managed filesystem\n    #completion_command     =    \"/path/to/my/script.sh -f {cfg} -p {fspath}\" ;\n\n    # Internal scheduler granularity (for testing and of scan, hangs, ...)\n    spooler_check_interval =  1min ;\n\n    # Memory preallocation parameters\n    nb_prealloc_tasks      =   256 ;\n\n    Ignore\n    {\n        # ignore \".snapshot\" and \".snapdir\" directories (don't scan them)\n        type == directory\n        and\n        ( name == \".snapdir\" or name == \".snapshot\" )\n    }\n}\n\n# changelog reader configuration\n# Parameters for processing MDT changelogs :\nChangeLog\n{\n    # 1 MDT block for each MDT :\n    MDT\n    {\n        # name of the first MDT\n        mdt_name  = \"MDT0000\" ;\n\n        # id of the persistent changelog reader\n        # as returned by \"lctl changelog_register\" command\n        reader_id = \"cl1\" ;\n    }\n\n    # clear changelog every 1024 records:\n    batch_ack_count = 1024 ;\n\n    force_polling    = yes ;\n    polling_interval = 1s ;\n    # changelog batching parameters\n    queue_max_size   = 1000 ;\n    queue_max_age    = 5s ;\n    queue_check_interval = 1s ;\n    # delays to update last committed record in the DB\n    commit_update_max_delay = 5s ;\n    commit_update_max_delta = 10k ;\n\n    # uncomment to dump all changelog records to the file\n}\n\n# policies configuration\n# Load policy definitions for Lustre/HSM\n%include \"includes/lhsm.inc\"\n\n#### Fileclasses definitions ####\n\nFileClass small_files {\n    definition { type == file and size > 0 and size <= 16MB }\n    # report = yes (default)\n}\nFileClass std_files {\n    definition { type == file and size > 16MB and size <= 1GB }\n}\nFileClass big_files {\n    definition { type == file and size > 1GB }\n}\n\nlhsm_config {\n    # used for 'undelete': command to change the fid of an entry in archive\n    rebind_cmd = \"/usr/sbin/lhsmtool_posix --hsm_root=/tmp/backend --archive {archive_id} --rebind {oldfid} {newfid} {fsroot}\";\n}\n\nlhsm_archive_parameters {\n    nb_threads = 1;\n\n    # limit archive rate to avoid flooding the MDT coordinator\n    schedulers = common.rate_limit;\n    rate_limit {\n        # max count per period\n        max_count = 1000;\n        # max size per period: 1GB/s\n        #max_size = 10GB;\n        # period, in milliseconds: 10s\n        period_ms = 10000;\n    }\n\n    # suspend policy run if action error rate > 50% (after 100 errors)\n    suspend_error_pct = 50%;\n    suspend_error_min= 100;\n\n    # overrides policy default action\n    action = cmd(\"lfs hsm_archive --archive {archive_id} /lustre/.lustre/fid/{fid}\");\n\n    # default action parameters\n    action_params {\n        archive_id = 1;\n    }\n}\n\nlhsm_archive_rules {\n    rule archive_small {\n        target_fileclass = small_files;\n        condition { last_mod >= 30min }\n    }\n\n    rule archive_std {\n        target_fileclass = std_files;\n        target_fileclass = big_files;\n        condition { last_mod >= 30min }\n    }\n\n    # fallback rule\n    rule default {\n        condition { last_mod >= 30min }\n    }\n}\n\n# run every 5 min\nlhsm_archive_trigger {\n    trigger_on = periodic;\n    check_interval = 5min;\n}\n\n#### Lustre/HSM release configuration ####\n\nlhsm_release_rules {\n    # keep small files on disk as long as possible\n    rule release_small {\n        target_fileclass = small_files;\n        condition { last_access > 1y }\n    }\n\n    rule release_std {\n        target_fileclass = std_files;\n        target_fileclass = big_files;\n        condition { last_access > 1d }\n    }\n\n    # fallback rule\n    rule default {\n        condition { last_access > 6h }\n    }\n}\n\n# run 'lhsm_release' on full OSTs\nlhsm_release_trigger {\n    trigger_on = ost_usage;\n    high_threshold_pct = 85%;\n    low_threshold_pct  = 80%;\n    check_interval     = 5min;\n}\n\nlhsm_release_parameters {\n    nb_threads = 4;\n## purge 1000 files max at once\n#    max_action_count = 1000;\n#    max_action_volume = 1TB;\n\n    # suspend policy run if action error rate > 50% (after 100 errors)\n    suspend_error_pct = 50%;\n    suspend_error_min= 100;\n}\n\nlhsm_remove_parameters\n{\n    # overrides policy default action\n    action = cmd(\"/usr/sbin/lfs_hsm_remove.sh {fsroot} {fullpath} {archive_id} {fid}\");\n\n    # default action parameters\n    action_params {\n        archive_id = 1;\n    } \n}\n\n#### Lustre/HSM remove configuration ####\nlhsm_remove_rules\n{\n    # cleanup backend files after 5m\n    rule default {\n        condition { rm_time >= 5m }\n    }\n}\n\n# run daily\nlhsm_remove_trigger\n{\n    trigger_on = periodic;\n    check_interval = 5m;\n}\nEOF\nchmod 600 $rbh_config_file\n\n\nrbh_log_rotate_file=\"/etc/logrotate.d/robinhood\"\ncat <<EOF > $rbh_log_rotate_file\n/var/log/robinhood*.log {\n    compress\n    weekly\n    rotate 6\n    notifempty\n    missingok\n}\nEOF\nchmod 644 $rbh_log_rotate_file\n\n\nhsm_remove_script=\"/usr/sbin/lfs_hsm_remove.sh\"\ncat <<EOF > $hsm_remove_script\n#!/bin/bash\n\nfsroot=\"\\$1\"\nfullpath=\"\\$2\"\narchive_id=\"\\$3\"\nfid=\"\\$4\"\n\nlfs hsm_remove --data \"{\\\"file_id\\\":\\\"\\${fullpath#\\${fsroot}/}\\\"}\" --archive \\${archive_id} --mntpath \\${fsroot} \\${fid}\nEOF\nchmod 755 $hsm_remove_script\n\nsystemctl enable robinhood\nsystemctl start robinhood\n\nrobinhood --scan --once\n\n\nlustremetasync_systemd_file=\"/lib/systemd/system/lustremetasync.service\"\ncat <<EOF > $lustremetasync_systemd_file\n[Unit]\nDescription=Handling directory/meta data backup on Lustre filesystem.\nAfter=syslog.target network.target remote-fs.target nss-lookup.target\n\n[Service]\nType=simple\nEnvironment=\"STORAGE_SAS=?$storage_sas\"\nExecStart=/sbin/changelog-reader -account \"$storage_account\" -container \"$storage_container\" -mdt LustreFS-MDT0000 -userid cl2\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\nEOF\nchmod 600 $lustremetasync_systemd_file\n\nsystemctl enable lustremetasync\nsystemctl start lustremetasync\n", "num_lines": 415}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexec > /var/log/setup_lustre.log                                                                      \nexec 2>&1\n\nscript_dir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\necho \"script_dir = $script_dir\"\n\nmds=\"$1\"\nn_oss=\"$2\"\nstorage_account=\"$3\" \nstorage_sas=\"$4\"\nstorage_container=\"$5\"\noss_disk_setup=\"$6\"\ndeploy_policy_engine=\"$7\"\nmdt_storage_sku=\"$8\"\nost_storage_sku=\"$9\"\n\n\nif [ \"$HOSTNAME\" = \"$mds\" ]; then\n\tstorage_sku=\"$mdt_storage_sku\"\nelse\n\tstorage_sku=\"$ost_storage_sku\"\nfi\n\necho mds=\"$1\"\necho n_oss=\"$2\"\necho storage_account=\"$3\" \necho storage_sas=\"${4/sig=*/sig=REDACTED}\"\necho storage_container=\"$5\"\necho oss_disk_setup=\"$6\"\necho deploy_policy_engine=\"$7\"\necho mdt_storage_sku=\"$8\"\necho ost_storage_sku=\"$9\"\necho storage_sku=\"$storage_sku\"\n\n\nrbh=\"${mds}rbh\"\n\nlustre_version=2.12.5\n\nif [ \"$storage_account\" = \"\" ]; then\n\tuse_hsm=false\nelse\n\tuse_hsm=true\nfi\n\nif [ \"$log_analytics_name\" = \"\" ]; then\n\tuse_log_analytics=false\nelse\n\tuse_log_analytics=true\nfi\n\nif [ \"$HOSTNAME\" = \"$rbh\" ]; then\n\n\techo \"wait for the mds to start\"\n\tmodprobe lustre\n\twhile ! lctl ping $mds@tcp; do\n\t\tsleep 2\n\tdone\n\nelse \n\n\t# vars used in script\n\tif [ \"$storage_sku\" = \"Ephemeral\" ]; then\n\t\tif [ -e /dev/nvme0n1 ]; then\n\t\t\tdevices='/dev/nvme*n1'\n\t\t\tn_devices=$(echo $devices | wc -w)\n\t\t\techo \"Using $n_devices NVME devices\"\n\t\telif [ -e /dev/disk/azure/resource ]; then\n\t\t\tdevices='/dev/disk/azure/resource'\n\t\t\tn_devices=1\n\t\t\techo \"Using ephemeral disk on /dev/disk/azure/resource\"\n\t\telse\n\t\t\techo \"ERROR: cannot find devices for storage\"\n\t\t\texit 1\n\t\tfi\n\telse\n\t\tif [ -d /dev/disk/azure/scsi1 ]; then\n\t\t\tdevices='/dev/disk/azure/scsi1/*'\n\t\t\tn_devices=$(echo $devices | wc -w)\n\n\t\t\techo \"Using $n_devices managed disks\"\n\t\telse\n\t\t\techo \"ERROR: cannot find devices for storage\"\n\t\t\texit 1\n\t\tfi\n\tfi\n\n\tif [[ \"$n_devices\" -gt \"1\" && ( \"$oss_disk_setup\" = \"raid\" || \"$HOSTNAME\" = \"$mds\" ) ]]; then\n\t\tdevice=/dev/md10\n\t\techo \"creating raid ($device) from $n_devices devices : $devices\"\n\t\t$script_dir/create_raid0.sh $device $devices\n\t\tdevices=$device\n\t\tn_devices=1\n\tfi\n\n\techo \"using $n_devices device(s) : $devices\"\n\n\n\tif [ \"$HOSTNAME\" = \"$mds\" ]; then\n\n\t\t# SETUP MDS\n\t\t$script_dir/lfsmaster.sh $devices $n_oss\n\n\telse\n\n\t\techo \"wait for the mds to start\"\n\t\tmodprobe lustre\n\t\twhile ! lctl ping $mds@tcp; do\n\t\t\tsleep 2\n\t\tdone\n\n\t\tidx=0\n\t\tfor c in $(echo ${HOSTNAME##$mds} | grep -o .); do\n\t\t\techo $c\t\t\n\t\t\tidx=$(($idx * 36))\n\t\t\tif [ -z \"${c##[0-9]}\" ]; then\n\t\t\t\tidx=$(($idx + $c))\n\t\t\telse\n\t\t\t\tidx=$(($(printf \"$idx + 10 + %d - %d\" \"'${c^^}\" \"'A\")))\n\t\t\tfi\n\t\tdone\n\t\t\n\t\tost_index=$(( ( $idx * $n_devices ) + 1 ))\n\n\t\techo \"starting ost index=$ost_index\"\n\n\t\tmds_ip=$(ping -c 1 $mds | head -1 | sed 's/^[^)]*(//g;s/).*$//g')\n\n\t\t$script_dir/lfsoss.sh $mds_ip \"$(echo $devices)\" $ost_index\n\n\tfi\n\nfi\n\nif [ \"${use_hsm,,}\" = \"true\" ]; then\n\n\tif [ \"$HOSTNAME\" = \"$mds\" ]; then\n\n\t\t# deploy on the MDS if we aren't using a policy engine\n\t\tif [ \"$deploy_policy_engine\" = \"True\" ]; then\n\n\t\t\t# register cl1 - robinhood\n\t\t\tlctl --device LustreFS-MDT0000 changelog_register\n\t\t\t# register cl2 - lustremetasync\n\t\t\tlctl --device LustreFS-MDT0000 changelog_register\n\n\t\telse\n\n\t\t\t# IMPORT CONTAINER (so mount lustre on the mds to import)\n\t\t\tmkdir /lustre\n\t\t\tmount -t lustre ${mds}@tcp0:/LustreFS /lustre\n\t\t\tchmod 770 /lustre\n\n\t\t\t$script_dir/lfsimport.sh \"$storage_account\" \"$storage_sas\" \"$storage_container\" /lustre\n\t\t\n\t\tfi\n\n\telif [ \"$HOSTNAME\" = \"${rbh}\" ]; then\n\n\t\t# IMPORT CONTAINER\n\t\tmkdir /lustre\n\t\techo \"${mds}@tcp0:/LustreFS /lustre lustre flock,defaults,_netdev 0 0\" >> /etc/fstab\n\t\twhile ! mount -a; do\n\t\t\techo \"Sleeping for 10s before retrying\"\n\t\t\tsleep 10\n\t\tdone\n\t\tchmod 770 /lustre\n\t\t\n\t\t$script_dir/lfsimport.sh \"$storage_account\" \"$storage_sas\" \"$storage_container\" /lustre\n\t\t\n\t\t$script_dir/lfsrbh.sh $mds \"$storage_account\" \"$storage_sas\" \"$storage_container\"\n\n\telse\n\n\t\t$script_dir/lfshsm.sh \"$mds\" \"$storage_account\" \"$storage_sas\" \"$storage_container\"\n\n\tfi\n\nfi\n", "num_lines": 182}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nAPP_NAME=ior\nSHARED_APP=${SHARED_APP:-/apps}\nMODULE_DIR=${SHARED_APP}/modulefiles\nMODULE_NAME=${APP_NAME}\nPARALLEL_BUILD=8\nIOR_VERSION=3.2.1\nINSTALL_DIR=${SHARED_APP}/${APP_NAME}-$IOR_VERSION\n\nsource /etc/profile.d/modules.sh # so we can load modules\nexport MODULEPATH=/usr/share/Modules/modulefiles:$MODULE_DIR\nmodule load gcc-9.2.0\nmodule load mpi/impi_2018.4.274\n\nmodule list\nfunction create_modulefile {\nmkdir -p ${MODULE_DIR}\ncat << EOF > ${MODULE_DIR}/${MODULE_NAME}\n#%Module\nprepend-path    PATH            ${INSTALL_DIR}/bin;\nprepend-path    LD_LIBRARY_PATH ${INSTALL_DIR}/lib;\nprepend-path    MAN_PATH        ${INSTALL_DIR}/share/man;\nsetenv          IOR_BIN         ${INSTALL_DIR}/bin\nEOF\n}\n\ncd $SHARED_APP\nIOR_PACKAGE=ior-$IOR_VERSION.tar.gz\nwget https://github.com/hpc/ior/releases/download/$IOR_VERSION/$IOR_PACKAGE\ntar xvf $IOR_PACKAGE\nrm $IOR_PACKAGE\n\ncd ior-$IOR_VERSION\n\nCC=`which mpicc`\n./configure --prefix=${INSTALL_DIR}\nmake -j ${PARALLEL_BUILD}\nmake install\n\ncreate_modulefile\n", "num_lines": 41}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nuser=$1\nhostlist=$2\n\npssh -l $user -i -h $hostlist '/usr/sbin/lspci | grep Mellanox'\n", "num_lines": 7}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nsource ~/azurehpc/install.sh\n\necho \"running from $(pwd)\"\n\necho \"moving up one directory\"\ncd ..\n\necho \"trying the copy\"\nazhpc-scp -- -r 'hpcadmin@headnode:results-*' .\n\n", "num_lines": 13}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nname=$1\ninstanceCount=$2\nrsaPublicKey=$3\nimageResourceGroup=$4\nimageName=$5\nexistingVnetResourceGroupName=$6\nexistingVnetName=$7\nexistingSubnetName=$8\nlustreTier=$9\nossDiskSetup=${10}\n\nif [ \"$lustreTier\" = \"eph\" ]; then\n    mdsSku=Standard_L8s_v2\n    ossSku=Standard_L48s_v2\n    mdtStorageSku=Premium_LRS\n    mdtCacheOption=None\n    mdtDiskSize=0\n    mdtNumDisks=0\n    ostStorageSku=Premium_LRS\n    ostCacheOption=None\n    ostDiskSize=0\n    ostNumDisks=0\nelif [ \"$lustreTier\" = \"prem\" ]; then\n    mdsSku=Standard_D8s_v3\n    ossSku=Standard_D48s_v3\n    mdtStorageSku=Premium_LRS\n    mdtCacheOption=ReadWrite\n    mdtDiskSize=1024\n    mdtNumDisks=2\n    ostStorageSku=Premium_LRS\n    ostCacheOption=None\n    ostDiskSize=1024\n    ostNumDisks=6\nelif [ \"$lustreTier\" = \"std\" ]; then\n    mdsSku=Standard_D8s_v3\n    ossSku=Standard_D48s_v3\n    mdtStorageSku=Standard_LRS\n    mdtCacheOption=ReadWrite\n    mdtDiskSize=1024\n    mdtNumDisks=4\n    ostStorageSku=Standard_LRS\n    ostCacheOption=None\n    ostDiskSize=8192\n    ostNumDisks=4\nelse\n    echo \"Unknown lustre tier ($lustreTier).\"\n    exit 1\nfi\n\naz deployment group create -g $imageResourceGroup --template-file scripts/azuredeploy.json --parameters \\\n    name=\"$name\" \\\n    mdsSku=\"$mdsSku\" \\\n    ossSku=\"$ossSku\" \\\n    instanceCount=\"$instanceCount\" \\\n    rsaPublicKey=\"$rsaPublicKey\" \\\n    imageResourceGroup=\"$imageResourceGroup\" \\\n    imageName=\"$imageName\" \\\n    existingVnetResourceGroupName=\"$existingVnetResourceGroupName\" \\\n    existingVnetName=\"$existingVnetName\" \\\n    existingSubnetName=\"$existingSubnetName\" \\\n    mdtStorageSku=\"$mdtStorageSku\" \\\n    mdtCacheOption=\"$mdtCacheOption\" \\\n    mdtDiskSize=\"$mdtDiskSize\" \\\n    mdtNumDisks=\"$mdtNumDisks\" \\\n    ostStorageSku=\"$ostStorageSku\" \\\n    ostCacheOption=\"$ostCacheOption\" \\\n    ostDiskSize=\"$ostDiskSize\" \\\n    ostNumDisks=\"$ostNumDisks\" \\\n    ossDiskSetup=\"$ossDiskSetup\"\n\n", "num_lines": 73}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ntier=$1\noss_user=$2\noss_hostfile=$3\n\nif [ \"$tier\" = \"eph\" ]; then\n\n    echo \"running 'sudo ethtool -L eth1 tx 8 rx 8 && sudo ifconfig eth1 down && sudo ifconfig eth1 up' on nodes\"\n\n    pssh -t 0 -i -l $oss_user -h $oss_hostfile 'sudo ethtool -L eth1 tx 8 rx 8 && sudo ifconfig eth1 down && sudo ifconfig eth1 up'\n\nfi", "num_lines": 13}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nresource_group=$1\nvmss=$2\noutput_file=$3\n\naz vmss list-instances --resource-group $resource_group --name $vmss -o tsv --query [].osProfile.computerName | tee $output_file\n", "num_lines": 8}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nlustre_dir=latest-2.12-release\n\ncat << EOF >/etc/yum.repos.d/LustrePack.repo\n[lustreserver]\nname=lustreserver\nbaseurl=https://downloads.whamcloud.com/public/lustre/${lustre_dir}/el7/patchless-ldiskfs-server/\nenabled=1\ngpgcheck=0\n\n[e2fs]\nname=e2fs\nbaseurl=https://downloads.whamcloud.com/public/e2fsprogs/latest/el7/\nenabled=1\ngpgcheck=0\n\n[lustreclient]\nname=lustreclient\nbaseurl=https://downloads.whamcloud.com/public/lustre/${lustre_dir}/el7/client/\nenabled=1\ngpgcheck=0\nEOF\n\n# install the right kernel devel if not installed\nrelease_version=$(cat /etc/redhat-release | cut -d' ' -f4)\nkernel_version=$(uname -r)\n\nif ! rpm -q kernel-devel-${kernel_version}; then\n    yum -y install http://olcentgbl.trafficmanager.net/centos/${release_version}/updates/x86_64/kernel-devel-${kernel_version}.rpm\nfi\n\n# install the client RPMs if not already installed\nif ! rpm -q lustre-client lustre-client-dkms; then\n    yum -y install lustre-client lustre-client-dkms || exit 1\nfi\nweak-modules --add-kernel $(uname -r)\n", "num_lines": 38}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# arg: $1 = lfsserver\n# arg: $2 = mount point (default: /lustre)\nmaster=$1\nlfs_mount=${2:-/lustre}\n\nmkdir $lfs_mount\necho \"${master}@tcp0:/LustreFS $lfs_mount lustre flock,defaults,_netdev 0 0\" >> /etc/fstab\nmount -a\nchmod 777 $lfs_mount\n\ndf -h\n", "num_lines": 14}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nhostfile=$1\nnodes=$(wc -l <$hostfile)\nppn=$2\nsz_in_gb=$3\ncores=$(($nodes * $ppn))\noss_user=$4\noss_hostfile=$5\nlustre_tier=$6\noss_disk_setup=$7\nlustre_stripe=$8\nost_per_oss=$9\n\ntimestamp=$(date \"+%Y%m%d-%H%M%S\")\n\nsource /etc/profile.d/modules.sh\nexport MODULEPATH=/usr/share/Modules/modulefiles:/apps/modulefiles\nmodule load gcc-9.2.0\nmodule load mpi/impi_2018.4.274\nmodule load ior\n\ndevice_list=()\nif [[ \"$oss_disk_setup\" = \"raid\" ]]; then\n    device_list+=(md10)\nelif [[ \"$lustre_tier\" = \"eph\" ]]; then\n    for i in $(seq 0 $(( $ost_per_oss - 1 )) ); do\n        device_list+=(nvme${i}n1)\n    done\nelif [[ \"$lustre_tier\" = \"prem\" || \"$lustre_tier\" = \"std\" ]]; then\n    for i in $( seq 0 $(( $ost_per_oss - 1 )) ); do\n        \n        # get the letter for the device\n        c_dec=$(printf \"%d\" \"'c\")\n        dev_dec=$(( $c_dec + $i ))\n        dev_hex=$(printf \"%x\" $dev_dec)\n        dev_char=$(printf \"\\x$dev_hex\")\n        \n        device_list+=(sd${dev_char})\n    done\nelse\n    echo \"unrecognised lustre type ($lustre_tier).\"\n    exit 1\nfi\n\ndevices=$(echo \"${device_list[@]}\" | tr ' ' ',')\n\necho \"Monitoring devices: $devices\"\n\npssh -t 0 -l $oss_user -h $oss_hostfile 'dstat -n -Neth0,eth1 -d -D'$devices' --output $(hostname)-'${timestamp}'.dstat' 2>&1 >/dev/null &\n\ntest_dir=/lustre/test-${timestamp}\nlfs setstripe --stripe-count $lustre_stripe $test_dir\nmpirun -np $cores -ppn $ppn -hostfile $hostfile ior -k -a POSIX -v -i 1 -B -m -d 1 -F -w -r -t 32M -b ${sz_in_gb}G -o $test_dir\n\nlfs df -h\ndf -h /lustre\n\nkill %1\nfor h in $(<${oss_hostfile}); do \n    scp ${oss_user}@${h}:'*'-${timestamp}.dstat .\ndone\n\nresults_dir=~/results-${lustre_tier}-${oss_disk_setup}-${lustre_stripe}-${timestamp}\nmkdir $results_dir\n\nfor i in *-${timestamp}.dstat; do\n    # remove the first value as it is often very high\n    sed '1,5d' $i > ${results_dir}/${i%%-${timestamp}.dstat}.csv\ndone\n", "num_lines": 71}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmount_point=$1\nnum_oss=$2\nost_per_oss=$3\n\n# wait for all the OSS to be present first\nwhile [ \"$(lctl get_param osc.*.ost_conn_uuid | cut -d'=' -f2 | uniq | wc -l)\" != \"$num_oss\" ]; do\n    echo \"    waiting for all $num_oss OSS\"\n    sleep 5\ndone\n\necho \"all $num_ost OSS have started\"\n\nwhile [ \"$(lctl get_param osc.*.ost_conn_uuid | cut -d'=' -f2 | uniq -c | sed 's/^ *//g' | cut -f1 -d' ' | uniq -c | sed 's/^ *//g')\" != \"$num_oss $ost_per_oss\" ]; do\n    echo \"   waiting for all $ost_per_oss OSTs on each OSS\"\n    sleep 5\ndone\n", "num_lines": 19}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmds=$1\n\nmodprobe lustre\nwhile ! lctl ping $mds@tcp; do\n    sleep 2\ndone\n", "num_lines": 9}
{"repo_name": "azlustre", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfor i in {0..9} {a..z}; do echo \"lustre00000${i}\"; done > oss\nfor i in {0..9} {a..z}; do echo \"lustre00001${i}\"; done >> oss\nfor i in {0..9} {a..z}; do echo \"lustre00002${i}\"; done >> oss\nfor i in {0..9} {a..z}; do echo \"lustre00003${i}\"; done >> oss\npssh -l lustre -h oss hostname 2>/dev/null | grep SUCCESS |sed 's/.*\\[SUCCESS\\] //g' | sort | tee oss.real && mv oss.real oss\n\n\n", "num_lines": 10}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "COMPANY=\"InMage\"\nCOMPANYNAME=\"InMage Systems\"\nPRODUCT=\"Scout-CX\"\nVERSION=\"1.0\"\nLINUXHOME=\"/home/svsystems\"\nWINHOME=\"\"\nWEBROOT=\"/var/www/html/admin/web\"\nDBSCHEMA=\"svsdb1\"\nUSER=\"svsystems\"\nLABEL=\"CX\"\nIN_PROFILER=\"InMageProfiler\"\nUSER_MANUAL=\"user_manual.pdf\"\nDIR_NAME=\"InmageAgent\"\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nDBG=\"\"\n\nwdir=/tmp\nbuild_dir=\"/media/builds/db\"\n\npkg_files=\"scripts/vCon/OS_details.sh bin/check_drivers.sh\"\n\ndbg()\n{\n    if [ ! -z $debug ]; then\n        echo $@\n    fi\n}\n\nget_distro()\n{\n    basename $1 | cut -f 4 -d \"_\"\n}\n\nextract_tar()\n{\n    $DBG\n    dbg \"Extracting $1\"\n    tar xf $1 -C $2 >/dev/null 2>&1 || {\n        # Master build server has old version of tar\n        # which does not auto-detect lzma archive\n        tar xJf $1 -C $2 >/dev/null 2>&1 || {\n            echo \"Cannot extract $1\"\n            return 1\n        }\n    }\n\n    return 0\n}\n\nextract_rpm()\n{\n    $DBG\n    cd $2 > /dev/null 2>&1\n    rpm2cpio $1 | cpio --quiet -idm \n    cd - > /dev/null 2>&1\n}\n\nfind_extraction_base_dir()\n{\n    echo \"$(dirname $(find $1 -name bin -type d))\"\n}\n\ncopy_common_files()\n{\n    $DBG\n    local _vxdir=$(find_extraction_base_dir $1)\n    local _file=\"\"\n    local _dir=\"\"\n    \n    for _file in $pkg_files; do\n        _dir=$(dirname $_file)\n        mkdir -p $2/common/$_dir || return 1\n        echo \"Copying common/$_file\"\n        cp -a $_vxdir/$_file $2/common/$_file || return 1\n    done\n}\n\ncopy_drivers()\n{\n    $DBG\n    local _vxdir=$(find_extraction_base_dir $1)\n    local _dir=\"\"\n    local _module=\"\"\n    \n    test -d $_vxdir/bin/drivers && _dir=bin/drivers || _dir=bin\n   \n    mkdir -p $2/$_dir\n\n    for _module in $(find $_vxdir/$_dir -name involflt*.ko*); do\n\t    echo \"Copying $(basename $_module)\"\n        cp $_module $2/$_dir/ || return 1\n    done\n    \n    test -f $1/supported_kernels && {\n        echo \"Copying supported_kernels\"\n        cp $1/supported_kernels $2/ || return 1\n    }\n\n    return 0\n}\n\nmake_drv_pkg()\n{\n    $DBG\n    local _ret=1\n\n    echo \"VERSION: $(grep PROD_VERSION $1/.vx_version | cut -f 2 -d \"=\")\" \n    \n    while [ $_ret -eq 1 ]; do\n        echo -n \"PACKAGE: \"\n        # Extract the archive with driver bianries\n        test -f $1/*Vx*rpm && {\n            echo \"RPM\"\n            extract_rpm $1/*Vx*rpm $1 || break\n        } || { \n            echo \"TAR\"\n            extract_tar $1/*VX*tar $1 || break\n        }\n\n        copy_drivers $@ || break\n\n        _ret=0\n    done\n\n    return $_ret\n}\n\nerror_exit()\n{\n    echo \"Error: $1\"\n    exit 1\n}\n\n$DBG\n\ndebug=\"\"\nif [ \"$1\" = \"-d\" ]; then\n    debug=1\n    shift\nfi\n\nbdate=$(date +%d_%b_%Y)\n\nversion=`ls $build_dir | grep -e ^[9] | sort -rn | sed -n 3p`\nagent_dir=$build_dir/$version/HOST/$bdate/UnifiedAgent_Builds/release\nif [ ! -d $agent_dir ]; then\n    version=`ls $bdir | grep -e ^[9] | sort -rn | sed -n 2p`\n    agent_dir=$build_dir/$version/HOST/$bdate/UnifiedAgent_Builds/release\n    if [ ! -d $agent_dir ]; then\n        echo \"Not Found: $build_dir/HOST/$bdate/UnifiedAgent_Builds/release\"\n        exit -1\n    fi\nfi\n\necho \"Agent Path: $agent_dir\"\n\nendir=$wdir/drivers # Directory where new agents are extracted\ndadir=$wdir/${version}_${bdate}_drivers # Archive directory for all new drivers\n\nfor dir in $endir $dadir; do\n    rm -rf $dir\n    mkdir -p $dir\ndone\n\nls $agent_dir/*.tar.gz |\\\nwhile read pkg\ndo\n    distro=$(get_distro $pkg)\n    \n    echo \"$distro: Clean Old Dir\"\n    sleep 1\n    rm -rf $endir || error_exit \"Cannot cleanup tmp dirs\"\n\n    echo \"$distro: Create New Dir\"\n    sleep 1\n    mkdir -p $endir || error_exit \"Cannot create tmp dirs\"\n    \n    echo \"$distro: Extract agent\"\n    sleep 1\n    extract_tar $pkg $endir || error_exit \"Cannot extract agent\"\n    \n    echo \"$distro: Extract drivers\"\n    sleep 1\n    make_drv_pkg $endir $dadir/$distro || error_exit \"Cannot create diff pkg\"\ndone\n\ncopy_common_files $endir $dadir || error_exit \"Cannot copy common files\"\n\ncp $endir/.vx_version $dadir || error_exit \"Cannot copy .vx_version\"\ncp `dirname $0`/install.sh $dadir || error_exit \"Cannot copy install script\"\n\necho \"Creating tar archive\"\ntar -C $wdir -cJf ${version}_${bdate}_drivers.tar.xz ${version}_${bdate}_drivers || error_exit \"Cannot create driver archive\"\n\necho \"Copying tostaging dir\"\nmv ${version}_${bdate}_drivers.tar.xz $agent_dir/\n\nexit 0\n\n", "num_lines": 188}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nlog()\n{\n    # We use the same log as agent install\n    # so all information is in one place\n    echo $@ | tee -a /var/log/ua_install.log\n}\n\nlog_quiet()\n{\n    # dont echo on screen\n    echo $@ >> /var/log/ua_install.log\n}\n\n#\n# Revert files on error\n#\nrevert_files()\n{\n    local _file=\"\"\n\n    cat $revert_file |\\\n    while read _file; do\n        log \"Revert: $_file\"\n        mv ${_file}.bak ${_file} || log \"Revert Failed: $_file\"\n    done\n\n    log \"Remove: $revert_file\"\n    rm -f $revert_file\n}\n\n#\n# Extract value based on key provided from vx_version\n#\nextract_vxversion()\n{\n    local vxvf=$installed_vxconf\n\n    if [ ! -z \"$2\" ]; then\n        vxvf=\"$2\"\n    fi\n\n    grep -w ^$1 $vxvf | cut -f 2 -d \"=\"\n}\n\n#\n# Take backup of file and copies new version of file\n# if the files differ.\n#\nbackup_copy_file()\n{\n    local _src=\"$1\"\n    local _dest=\"$2\"\n\n    log \"Copy: $_src -> $_dest\"\n    diff -q $_src $_dest > /dev/null 2>&1\n    if [ $? -ne 0 ]; then\n        log \"Backup: ${_dest}.bak\"\n        echo \"${_dest}\" >> $revert_file\n        cp -f \"${_dest}\" \"${_dest}.bak\" || \\\n            exit_error \"Backup Failed: $_dest\"\n        \n        log \"Copying: ${_dest}\"\n        cp -f \"$_src\" \"${_dest}\" || \\\n            exit_error \"Copy Failed: $_dest\"\n    else\n        log \"Skipping as same: $_dest\"\n    fi\n}\n\n#\n# Copy all configurations from old file to new\n#\nconfigure_check_drivers_script()\n{\n    local _file=\"$1\"\n    local _cfgfile=\"$2\"\n    local _bfile=$(echo $_file | cut -f 2- -d \"/\")\n    local _keyval=\"\"\n    local _key=\"\"\n    local _val=\"\"\n\n    log \"Configuring: $_bfile\"\n\n    cp \"$_file\" \"$_cfgfile\" || \\\n        exit_error \"Copy Failed: $_cfgfile\" \n\n    cat \"$install_dir/$(echo $_file | cut -f 2- -d \"/\")\" |\\\n    sed -n \"/Configuration/,/Configuration/p\" |\\\n    grep -v \"^#\" | grep \"=\" |\\\n    while read _keyval; do\n        _key=$(echo $_keyval | cut -f 1 -d \"=\")\n        _val=$(echo $_keyval | cut -f 2 -d \"=\" | sed \"s/\\\"//g\")\n\n        log \"Update: $_key = $_val\"\n        _val=$(echo $_val | sed 's/\\//\\\\\\//g') # sed safe\n        sed -i \"s/$_key=\\\".*\\\"/$_key=\\\"${_val}\\\"/\" \"$_cfgfile\" || {\n            rm -f \"$_cfgfile\"\n            log \"Update Failed: $_cfgfile\"\n            return 1\n        }\n    done\n\n    log \"Diff: $_bfile:\"\n    diff \"$_cfgfile\" \"$install_dir/$_bfile\"\n}\n\n\ncopy_configure_file()\n{\n    local _file=\"\"\n    local _cfgfile=\"\"\n    local _src=\"\"\n    local _dest=\"\"\n    \n    for _file in $(find common -type f); do\n        \n\t_src=$(basename $_file)\n        _dest=$install_dir/$(echo $_file | cut -f 2- -d \"/\")\n\n        if [ \"$_src\" = \"check_drivers.sh\" ]; then \n            _src=\"${_file}.cfg\"\n            configure_check_drivers_script $_file $_src || {\n                test -f $_src && rm -f \"$_src\"\n                exit_error \"Config Failed: $_src\" \n            }\n        else\n            _src=\"$_file\"\n        fi\n        \n        backup_copy_file $_src $_dest \n        \n        if [ \"$_src\" != \"$_file\" ]; then\n            rm -f \"$_src\"\n        fi\n    done\n    \n    return 0\n}\n\ncopy_drivers()\n{\n    local _dir=\"$1\"\n    local _overwrite=\"$2\"\n    local _src=\"\"\n    local _dest=\"\"\n\n    for _src in $(find $_dir -type f -name involflt.*); do\n        _dest=$install_dir/$(echo $_src | cut -f 2- -d \"/\")\n        \n        test -f $_dest && {\n            log_quiet \"Skipping: $_dest\"\n        } || {\n            log \"Copying: $_dest\"\n            cp -n $_src $_dest || error_exit \"Copy Failed: $_dest\"\n        }\n    done\n\n    for _src in $(find $_dir -type f -name supported_kernels); do\n        _dest=$(echo $_src | cut -f 2- -d \"/\")\n        _dest=\"$install_dir/bin/drivers/$_dest\"\n        \n        # On some distros, this file is not copied to install dir\n        test -f $_dest && backup_copy_file $_src $_dest\n    done\n\n    return 0\n}\n\nexit_error()\n{\n    log \"FAIL: $@\"\n    revert_files\n    exit -1\n}\n\ncommon=\"common\"\nupdate_vxconf=\".vx_version\"\ninstalled_vxconf=\"/usr/local/.vx_version\"\nrevert_file=\"backup.log\"\n\n> $revert_file\n\nif [ $EUID -ne 0 ]; then\n   exit_error \"This script must be run as root\" \nfi\n\ninstalled_vx_version=$(extract_vxversion VERSION)\nupdate_vx_version=$(extract_vxversion VERSION $update_vxconf)\n\nlog \"Installing driver package: $update_vx_version\"\n\nif [ \"$installed_vx_version\" != \"$update_vx_version\" ]; then\n    exit_error \"This package should be applied with $update_vx_version\" \\\n               \"version of ASR agent. Installed agent is $installed_vx_version\"\nfi\n\ndistro=$(extract_vxversion OS_BUILT_FOR)\ninstall_dir=$(extract_vxversion INSTALLATION_DIR)\n\nlog \"Distro: $distro\"\nlog \"Install Directory: $install_dir\"\n\necho \"Press Enter to continue\"\nread a\n\nlog \"Copying drivers\"\ncopy_drivers $distro || exit_error \"Cannot copy drivers\"\n\nlog \"Copying common utilities\"\ncopy_configure_file || exit_error \"Cannot copy common files\"\n\nlog \"Installing drivers\"\n$install_dir/bin/check_drivers.sh\n\nlog \"Remove: $revert_file\"\nrm -f $revert_file\n\nlog \"Driver successfully installed\"\n", "num_lines": 221}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\n##\n# Step 1: USAGE\n# This defines the usage and also captures different components to be built\n# This also sets various compiler flags required for building components\n##\n\n# Define the usage\nUSAGE=\"Usage:   ./fx_bld.sh [top build dir] [inmsync,build,unregagent,alert,dspace,remotecli,all]. Parameters must be comma-separated. Default parameter values are current directory and 'all'.\"\n\n# Capture the components to be built\nTOP_BLD_DIR=${1:-`pwd`}\nCOMPONENTS=${2:-all}\nCONFIG=${3:-debug}\n\nCUR_W_D=`pwd`\nCOMPILE=\"g++\"\n\nif [ \"$COMPONENTS\" = \"inmsync\" ]; then\n\tBUILD_INMSYNC=1\nelse\n\tBUILD_INMSYNC=0\nfi\n\nif [ \"$COMPONENTS\" = \"svfrd\" ]; then\n\tBUILD_SVFRD=1\nelse\n\tBUILD_SVFRD=0\nfi\n\nif [ \"$COMPONENTS\" = \"unregagent\" ]; then\n\tBUILD_UNREG=1\nelse\n\tBUILD_UNREG=0\nfi\n\nif [ \"$COMPONENTS\" = \"alert\" ]; then\n        BUILD_ALERT=1\nelse\n        BUILD_ALERT=0\nfi\n\nif [ \"$COMPONENTS\" = \"dspace\" ]; then\n        BUILD_DSPACE=1\nelse\n        BUILD_DSPACE=0\nfi\n\nif [ \"$COMPONENTS\" = \"remotecli\" ]; then\n        BUILD_REMOTECLI=1\nelse\n        BUILD_REMOTECLI=0\nfi\n\nif [ \"$COMPONENTS\" = \"vacp\" ]; then\n\tBUILD_VACP=1\nelse\n\tBUILD_VACP=0\nfi\n\n[ $COMPONENTS = \"all\" ] && BUILD_INMSYNC=1 && BUILD_SVFRD=1 && BUILD_UNREG=1 && BUILD_ALERT=1 && BUILD_DSPACE=1 && BUILD_VACP=1 && BUILD_REMOTECLI=1\n\nif [ $BUILD_INMSYNC -ne 1 -a $BUILD_SVFRD -ne 1 -a $BUILD_UNREG -ne 1 -a $BUILD_ALERT -ne 1 -a $BUILD_DSPACE -ne 1 -a $BUILD_VACP -ne 1 -a $BUILD_REMOTECLI -ne 1 ]\nthen\n\techo $USAGE\n\texit 95\nfi\n\n# Form OP_SYS variable based on platform\ncase `uname` in\n\tAIX)\tOP_SYS=\"aix\";;\n\tSunOS)\tif uname -r | grep 5.8 > /dev/null 2>&1; then\n                        OP_SYS=\"solaris58\"\n\t\telif uname -r | grep 5.9 > /dev/null 2>&1; then\n\t\t\tOP_SYS=\"solaris5-9\"\n                elif uname -r | grep 5.10 > /dev/null 2>&1; then\n                        OP_SYS=\"solaris5-10\"\n                elif uname -r | grep 5.11 > /dev/null 2>&1; then\n                        OP_SYS=\"solaris5-11\"\n                fi;;\n\tHP-UX)\tif ! uname -a | grep -i ia64 > /dev/null 2>&1; then OP_SYS=\"hpux\"; else OP_SYS=\"hpux_itanium\"; fi;;\nesac\n\n. ${TOP_BLD_DIR}/source/build/scripts/general/OS_details.sh\n\n# Set platform-based compiler flags\n\nif [ \"$OP_SYS\" = \"aix\" ]; then\t\t\t\n\n    \tcase $OS in\n\t\tAIX53)\n\t\t\tCURL_INCLUDE=\"-Ithirdparty/aix/lib53/curl-7.59.0/include\"\n\t\t\t;;              \n\tesac\n\n\tunset LD_LIBRARY_PATH\n        LD_FLAGS='-lstdc++ -lgcc_s -lcrypt -lpthread'\n        LIBS='lib/libcurl.a  lib/libz.a  lib/libssl.a  lib/libcrypto.a  lib/libcares.a'\n\tGCC_OPTS_SVFRD=\"-Bstatic -Llib -Wno-deprecated ${CURL_INCLUDE} -I/usr/local/include -Ihost/fr_common \\\n\t\t-Ihost/fr_common/unix -DSV_UNIX \\\n\t\t-DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_STRING_H -DHAVE_SETSID \\\n\t\t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H -DSV_GENUUID \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n\t\thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n\t\thost/frdaemon/daemon.cpp -o svfrd -Llib $LIBS $LD_FLAGS\"\n\n\tGCC_OPTS_UNREGAGENT=\"-Bstatic -Llib -Wno-deprecated -Wno-sign-compare -Wno-conversion ${CURL_INCLUDE} -I/usr/local/include \\\n\t\t-Ihost/fr_common -Ihost/fr_common/unix -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H \\\n\t\t-DHAVE_SIGACTION -DHAVE_STRING_H -DHAVE_SETSID -DHAVE_STRCASECMP \\\n\t\t-DHAVE_NETDB_H -DHAVE_NETINET_H -DSV_GENUUID \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n\t\thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fr_common/unregworker.cpp \\\n\t\thost/fr_unregagent/unixunreg.cpp -o unregfragent -Llib $LIBS $LD_FLAGS\"\n\n\tGCC_OPTS_ALERT=\"-Bstatic -Llib -Wno-deprecated ${CURL_INCLUDE} -I/usr/include \\\n\t\t-I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n        \t-Ihost/fr_config -Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H -DHAVE_STRING_H -DSV_GENUUID \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n        \thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n        \thost/fxalert/fxalert.cpp -o alert -Llib $LIBS $LD_FLAGS\"\n\n\tGCC_OPTS_DSPACE=\"-Bstatic -Llib -Wno-deprecated ${CURL_INCLUDE} -I/usr/include \\\n\t\t-I/usr/local/include  -Ihost/fr_common -Ihost/fr_common/unix \\\n        \t-Ihost/fr_config -Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H -DHAVE_STRING_H -DSV_GENUUID \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n        \thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n        \thost/fxdspace/fxdspace.cpp -o dspace -Llib $LIBS $LD_FLAGS\"\n\n\tGCC_OPTS_REMOTECLI=\"-Bstatic -Wno-deprecated ${CURL_INCLUDE} -I/usr/local/include \\\n\t\t-Ihost/remotecli -Ihost/common -Ihost/cdplibs \\\n\t\t-DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS \\\n\t\t-DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID -DHAVE_STRCASECMP \\\n\t\t-DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n\t\thost/remotecli/main.cpp \\\n\t\thost/remotecli/remotecli.cpp \\\n\t\thost/common/svutilities.cpp  -o remotecli -Llib $LIBS $LD_FLAGS\"\n\nelif [ \"$OP_SYS\" = \"solaris58\" -o \"$OP_SYS\" = \"solaris5-9\" -o \"$OP_SYS\" = \"solaris5-10\" -o \"$OP_SYS\" = \"solaris5-11\" ]; then\n\tunset LD_LIBRARY_PATH\n\tLD_FLAGS='-Llib -lc -lnsl -lsocket -lldap -ldl -lrt -lstdc++ -lgcc_s'\n\tLIBS='lib/libcurl.a  lib/libz.a  lib/libssl.a  lib/libcrypto.a  lib/libcares.a'\n\n\tif [ \"$CONFIG\" = \"release\" ]; then\n\t\tSYMBOL_FLAGS='-O3 -g3 -ggdb' \n\telse\n\t\tSYMBOL_FLAGS='-O0 -gdwarf-2 -g3 -fno-optimize-sibling-calls -fno-omit-frame-pointer'\n\tfi\n\n\tif [ \"$OP_SYS\" = \"solaris58\" ]; then\n           GCC_OPTS_SVFRD=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n                -Ithirdparty/curl-7.59.0/include \\\n                -DSV_UNIX -DSV_GENUUID -DSV_SUN_5DOT8 -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n                -DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n                host/fr_log/logger.cpp \\\n                host/fr_config/svconfig.cpp \\\n                host/fr_common/svtransport.cpp \\\n                host/fr_common/unix/portableunix.cpp \\\n                host/fr_common/unixagenthelpers.cpp \\\n                host/fr_common/svtypes.cpp \\\n                host/fr_common/svutils.cpp \\\n                host/fragent/fragent.cpp \\\n                host/frdaemon/daemon.cpp -o svfrd $LIBS $LD_FLAGS\"\n        elif [ \"$OP_SYS\" = \"solaris5-9\" ]; then\n            GCC_OPTS_SVFRD=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n                -Ithirdparty/curl-7.59.0/include \\\n                -DSV_UNIX -DSV_GENUUID -DSV_SUN_5DOT9 -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n                -DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n                host/fr_log/logger.cpp \\\n                host/fr_config/svconfig.cpp \\\n                host/fr_common/svtransport.cpp \\\n                host/fr_common/unix/portableunix.cpp \\\n                host/fr_common/unixagenthelpers.cpp \\\n                host/fr_common/svtypes.cpp \\\n                host/fr_common/svutils.cpp \\\n                host/fragent/fragent.cpp \\\n                host/frdaemon/daemon.cpp -o svfrd $LIBS $LD_FLAGS\"\n        else\n\t    GCC_OPTS_SVFRD=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n\t\t-Ithirdparty/curl-7.59.0/include \\\n\t\t-DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n\t\t-DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n\t\thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n\t\thost/frdaemon/daemon.cpp -o svfrd $LIBS $LD_FLAGS\"\n\tfi\n\n\tGCC_OPTS_UNREGAGENT=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n\t\t-Ithirdparty/curl-7.59.0/include \\\n\t\t-DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n\t\t-DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n\t\thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unregworker.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_unregagent/unixunreg.cpp -o unregfragent $LIBS $LD_FLAGS\"\n\n\tGCC_OPTS_ALERT=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/include -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n        \t-Ihost/fr_config -Ihost/config -Ithirdparty/curl-7.59.0/include \\\n\t\t-DSV_UNIX -DSV_SUNOS -DSV_GENUUID -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t-DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n        \thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n        \thost/fxalert/fxalert.cpp -o alert $LIBS $LD_FLAGS\"\n\n        GCC_OPTS_DSPACE=\"$SYMBOL_FLAGS -m32 -Bstatic -Rlib -Wno-deprecated -I/usr/include -I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n        \t-Ihost/fr_config -Ihost/config -Ithirdparty/curl-7.59.0/include \\\n\t\t-DSV_UNIX -DSV_SUNOS -DSV_GENUUID -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t-DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\thost/fr_log/logger.cpp \\\n\t\thost/fr_config/svconfig.cpp \\\n        \thost/fr_common/svtransport.cpp \\\n\t\thost/fr_common/unix/portableunix.cpp \\\n\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\thost/fr_common/svtypes.cpp \\\n\t\thost/fr_common/svutils.cpp \\\n\t\thost/fragent/fragent.cpp \\\n\t        host/fxdspace/fxdspace.cpp -o dspace $LIBS $LD_FLAGS\"\n\t\n\tGCC_OPTS_REMOTECLI=\"$SYMBOL_FLAGS -m32 -Bstatic -Wno-deprecated -I/usr/local/include -Ihost/remotecli -Ihost/common -Ihost/cdplibs \\\n\t\t-Ithirdparty/curl-7.59.0/include \\\n\t\t-DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_STRING_H \\\n\t\t-DHAVE_NETINET_H -DHAVE_NETDB_H host/remotecli/main.cpp host/remotecli/remotecli.cpp host/common/svutilities.cpp  -o remotecli \\\n\t\t-Llib $LIBS $LD_FLAGS\"\n\nelif [ \"$OP_SYS\" = \"hpux\" ]; then\n\tunset LD_LIBRARY_PATH\n\tLD_FLAGS='-lstdc++ -lgcc_s -lpthread'\n        LIBS='lib/libcurl.a lib/libz.a lib/libssl.a lib/libcrypto.a lib/libcares.a lib/libidn.a'\n\tGCC_OPTS_SVFRD=\"-Bstatic -Wl,+blib -Wno-deprecated -fno-exceptions -Ithirdparty/curl-7.59.0/config_release/include -I/usr/local/include -Ihost/fr_common \\\n\t\t\t-Ihost/fr_common/unix -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n\t\t\t-DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t\thost/frdaemon/daemon.cpp -o svfrd -Llib $LIBS $LD_FLAGS\"\n\n\t\tGCC_OPTS_UNREGAGENT=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include -I/usr/local/include \\\n\t\t\t-Ihost/fr_common -Ihost/fr_common/unix \\\n\t\t\t-DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n\t\t\t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unregworker.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_unregagent/unixunreg.cpp -o unregfragent -Llib $LIBS $LD_FLAGS\"\n\t\t\n\t\tGCC_OPTS_ALERT=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include -I/usr/include -I/usr/local/include \\\n\t\t\t-Ihost/fr_common -Ihost/fr_common/unix \\\n        \t\t-Ihost/fr_config -Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t\t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n        \t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n        \t\thost/fxalert/fxalert.cpp -o alert -Llib $LIBS $LD_FLAGS\"\n\n\t\t GCC_OPTS_DSPACE=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include\n\t\t\t-I/usr/include -I/usr/local/include  \\\n\t\t\t-Ihost/fr_common -Ihost/fr_common/unix \\\n        \t\t-Ihost/fr_config \\\n\t\t\t-Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n        \t\t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n        \t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t        host/fxdspace/fxdspace.cpp -o dspace -Llib $LIBS $LD_FLAGS\"\n\n\t\tGCC_OPTS_REMOTECLI=\"-Bstatic -Wl,+blib -Wno-deprecated -D _REENTRANT -Ithirdparty/curl-7.59.0/config_release/include \\\n\t\t\t-I/usr/local/include -Ihost/remotecli \\\n\t\t\t-Ihost/common -Ihost/cdplibs \\\n\t\t\t-DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID -DHAVE_STRCASECMP \\\n\t\t\t-DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H \\\n\t\t\thost/remotecli/main.cpp host/remotecli/remotecli.cpp host/common/svutilities.cpp -o remotecli \\\n\t\t\t-Llib $LIBS $LD_FLAGS\"\n\t\t\n\nelif [ \"$OP_SYS\" = \"hpux_itanium\" ]; then\n\t\tunset LD_LIBRARY_PATH\n                LD_FLAGS='-lstdc++ -lgcc_s -lssl -lpthread'\n                LIBS='lib/libcurl.a  lib/libz.a  lib/libssl.a  lib/libcrypto.a  lib/libcares.a lib/libidn.a'\n\t\tGCC_OPTS_SVFRD=\"-Bstatic -Wl,+blib -Wno-deprecated -fno-exceptions -Ithirdparty/curl-7.59.0/config_release/include \\\n\t\t\t-I/usr/local/include -Ihost/fr_common \\\n\t\t\t-Ihost/fr_common/unix -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION \\\n\t\t\t-DHAVE_SETSID -DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t\thost/frdaemon/daemon.cpp -o svfrd \\\n\t\t\t-Llib $LIBS $LD_FLAGS\"\n\n\t\tGCC_OPTS_UNREGAGENT=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include -I/usr/local/include -Ihost/fr_common \\\n\t\t\t-Ihost/fr_common/unix -Llib \\\n\t\t\t-DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n\t\t\t-DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unregworker.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_unregagent/unixunreg.cpp -o unregfragent \\\n\t\t\t-Llib $LIBS $LD_FLAGS\"\n\n\t\tGCC_OPTS_ALERT=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include -I/usr/include \\\n\t\t\t-I/usr/local/include -Ihost/fr_common -Ihost/fr_common/unix \\\n        \t\t-Ihost/fr_config -Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n\t\t        -DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n        \t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t        host/fxalert/fxalert.cpp -o alert -Llib $LIBS $LD_FLAGS\"\n\n                 GCC_OPTS_DSPACE=\"-Bstatic -Wl,+blib -Wno-deprecated -Ithirdparty/curl-7.59.0/config_release/include -I/usr/include -I/usr/local/include \\\n\t\t\t-Ihost/fr_common -Ihost/fr_common/unix \\\n\t\t        -Ihost/fr_config -Ihost/config -DSV_UNIX -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n\t\t        -DHAVE_STRCASECMP -DHAVE_NETDB_H -DHAVE_NETINET_H \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t        host/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t        host/fxdspace/fxdspace.cpp -o dspace -Llib $LIBS $LD_FLAGS\"\n\n\t\tGCC_OPTS_REMOTECLI=\"-Bstatic -Wl,+blib -Wno-deprecated -D _REENTRANT -Ithirdparty/curl-7.59.0/config_release/include -I/usr/local/include \\\n\t\t\t-Ihost/remotecli -Ihost/common \\\n\t\t\t-Ihost/cdplibs -DSV_UNIX -DSV_GENUUID -DSV_SUNOS -DSTDC_HEADERS -DHAVE_UNISTD_H -DHAVE_SIGACTION -DHAVE_SETSID \\\n\t\t\t-DHAVE_STRCASECMP -DHAVE_STRING_H -DHAVE_NETINET_H -DHAVE_NETDB_H host/remotecli/main.cpp \\\n\t\t\thost/remotecli/remotecli.cpp host/common/svutilities.cpp -o remotecli \\\n\t\t\t-Llib $LIBS $LD_FLAGS\"\n\t\t\nfi\n\ncase `uname` in\n        AIX)\n             if [ -n \"$LIBPATH\" ]; then\n               \tunset LIBPATH\n             fi\n\t;;\n\n        SunOS)\n              # Setting the LD_LIBRARY_PATH\n\t      if [ -n \"$LD_LIBRARY_PATH\" ]; then\n                 unset LD_LIBRARY_PATH\n\t      fi\n\t;;\n        HP-UX)\n\t\tif [ -n \"$SHLIB_PATH\" ]; then\n\t\t  unset SHLIB_PATH\n\t\tfi \n\t;;\nesac\n\n##\n# Step 2: BUILD\n# Component: inmsync\n##\n\nwhich gcc | grep \"no gcc\" > /dev/null 2>&1 || GCC_PATH=`dirname \\`which gcc\\``\nPATH=$PATH:/usr/local/bin:$GCC_PATH\nexport PATH\n\nif [ $BUILD_INMSYNC -eq 1 ]; then\n\tif [ -d $TOP_BLD_DIR/source/host/inmsync ]\n\tthen\n\t\tcd $TOP_BLD_DIR/source/host/inmsync\n\n\t\t# Clean up existing binary before attempting to build again\n\t\trm -f inmsync $TOP_BLD_DIR/binaries/FX/inmsync > /dev/null\n\n\t\tgmake -f Makefile\n\n\t\tif [ -s \"inmsync\" ]; then\n\t\t\techo \"inmsync: BUILD SUCCESSFUL!\"\n\t\t\tmv inmsync ../../../binaries/FX/\n\t\t\tcd $CUR_W_D\n\t\telse\n\t\t\techo \"inmsync: BUILD FAILED!\"\n\t\t\tcd $CUR_W_D\n\t\t\texit 96\n\t\tfi\n\telse\n\t\techo \"Directory $TOP_BLD_DIR/source/host/inmsync not found!\"\n\t\texit 97\n\tfi\nfi\n\n##\n# Step 3: BUILD\n# Component: SVFRD\n##\n\nif [ $BUILD_SVFRD -eq 1 ]; then \n\tif [ -d $TOP_BLD_DIR/source ]; then\n\t\t# Change directories to the 'source' directory since compiler flags are set as host/...\n\t\tcd $TOP_BLD_DIR/source\n\n\t\t# Clean up existing binary before attempting to build again\n\t\trm -f  ../binaries/FX/svfrd > /dev/null\n\n\t\t# Compilation of svfrd\n\t\t$COMPILE $GCC_OPTS_SVFRD\n\n\t\tif [ -s \"svfrd\" ]; then\n\t\t\techo \"svfrd: BUILD SUCCESSFUL!\"\n\t\t\tmv svfrd ../binaries/FX/\n\t\t\tcd $CUR_W_D\n\t\telse\n\t\t\techo \"svfrd: BUILD FAILURE!\"\n\t\t\tcd $CUR_W_D\n\t\t\texit 98\n\t\tfi\n\telse\n\t\techo \"Directory $TOP_BLD_DIR/source not found!\"\n\t\texit 99\n\tfi\nfi\n\n\n##\n# Step 4: BUILD\n# Component: UNREGAGAENT\n##\n\nif [ $BUILD_UNREG -eq 1 ]; then\n        if [ -d $TOP_BLD_DIR/source ]; then\n\t\t# Change directories to the 'source' directory since compiler flags are set as host/...\n\t\tcd $TOP_BLD_DIR/source\n\n                # Clean up existing binary before attempting to build again\n                rm -f  ../binaries/FX/unregfragent > /dev/null\n\n\t\t# Compilation of unregfragent\n\t\t$COMPILE $GCC_OPTS_UNREGAGENT\n\n\t\tif [ -s \"unregfragent\" ]\n\t\tthen\n\t\t\techo \"unregfragent: BUILD SUCCESSFUL!\"\n\t\t\tmv unregfragent ../binaries/FX/\n\t\t\tcd $CUR_W_D\n\t\telse\n   \t\t\techo \"unregfragent: BUILD FAILURE!\"\n\t\t\tcd $CUR_W_D\n   \t\t\texit 100\n\t\tfi\n\telse\n\t\techo \"Directory $TOP_BLD_DIR/source not found!\"\n\t\texit 99\n\tfi\nfi\n\n##\n# Component: ALERT\n##\nif [ $BUILD_ALERT -eq 1 ]; then\n        if [ -d $TOP_BLD_DIR/source ]; then\n                # Change directories to the 'source' directory since compiler flags are set as host/...\n                cd $TOP_BLD_DIR/source\n\n                # Clean up existing binary before attempting to build again\n                rm -f  ../binaries/FX/alert > /dev/null\n\n                # Compilation of alert\n                $COMPILE $GCC_OPTS_ALERT\n\n                if [ -s \"alert\" ]\n                then\n                        echo \"alert: BUILD SUCCESSFUL!\"\n                        mv alert ../binaries/FX/\n                        cd $CUR_W_D\n                else\n                        echo \"alert: BUILD FAILURE!\"\n                        cd $CUR_W_D\n                        exit 101\n                fi\n        else\n                echo \"Directory $TOP_BLD_DIR/source not found!\"\n                exit 99\n        fi\nfi\n##\n# Component: DSPACE\n##\n\nif [ $BUILD_DSPACE -eq 1 ]; then\n        if [ -d $TOP_BLD_DIR/source ]; then\n                # Change directories to the 'source' directory since compiler flags are set as host/...\n                cd $TOP_BLD_DIR/source\n\n                # Clean up existing binary before attempting to build again\n                rm -f  ../binaries/FX/dspace > /dev/null\n\n                # Compilation of dspace\n                $COMPILE $GCC_OPTS_DSPACE\n\n                if [ -s \"dspace\" ]\n                then\n                        echo \"dspace: BUILD SUCCESSFUL!\"\n                        mv dspace ../binaries/FX/\n                        cd $CUR_W_D\n                else\n                        echo \"dspace: BUILD FAILURE!\"\n                        cd $CUR_W_D\n                        exit 102\n                fi\n        else\n                echo \"Directory $TOP_BLD_DIR/source not found!\"\n                exit 99\n        fi\nfi\n##\n# Component: REMOTECLI\n##\n\nif [ $BUILD_REMOTECLI -eq 1 ]; then\n        if [ -d $TOP_BLD_DIR/source ]; then\n                # Change directories to the 'source' directory since compiler flags are set as host/...\n                cd $TOP_BLD_DIR/source\n\n                # Clean up existing binary before attempting to build again\n                rm -f  ../binaries/FX/remotecli > /dev/null\n\n                # Compilation of dspace\n                $COMPILE $GCC_OPTS_REMOTECLI\n\n                if [ -s \"remotecli\" ]; then\n                        echo \"remotecli: BUILD SUCCESSFUL!\"\n                        mv remotecli ../binaries/FX/\n                        cd $CUR_W_D\n                else\n                        echo \"remotecli: BUILD FAILURE!\"\n                        cd $CUR_W_D\n                        exit 102\n                fi\n        else\n                echo \"Directory $TOP_BLD_DIR/source not found!\"\n                exit 99\n        fi\nfi\n\n##\n# Component: FX_VACP for UNIX\n##\n\nif [ `uname` = \"SunOS\" -a \"$CONFIG\" = \"debug\" ]; then\n\tDEBUG_OPT=\"debug=yes\"\n\tCONF=\"debug\"\nelse\n\tDEBUG_OPT=\"debug=no\"\n\tCONF=\"release\"\nfi\n\nif [ $BUILD_VACP -eq 1 ]; then\n        if [ -d $TOP_BLD_DIR/source/host ]; then\n                # Change directories to the 'source/host' directory for compiling vacp using make\n                cd $TOP_BLD_DIR/source/host\n\n                # Clean up existing binary before attempting to build again\n                rm -f ../binaries/FX/vacp > /dev/null\n\n                 # Compilation of vacp\n                 gmake vacpunix verbose=yes FX_VACP=yes $DEBUG_OPT\n\n                if [ -s \"fx_vacp/vacpunix/${CONF}/vacp\" ]; then\n                        echo \"vacp: BUILD SUCCESSFUL!\"\n                        cp fx_vacp/vacpunix/${CONF}/vacp ../../binaries/FX/\n                        cd $CUR_W_D\n                else\n                        echo \"vacp: BUILD FAILURE!\"\n                        cd $CUR_W_D\n                        exit 103\n                fi\n        else\n                echo \"Directory $TOP_BLD_DIR/source not found!\"\n                exit 99\n        fi\nfi\n\nif [ `uname` = \"SunOS\" -a \"$CONFIG\" = \"release\" ]; then\n\tcd $TOP_BLD_DIR/binaries/FX/\n\tfor binary in inmsync alert dspace svfrd unregfragent remotecli vacp\t\n\tdo\n\t\tgobjcopy --only-keep-debug ${binary} ${binary}.dbg\n\t\tgobjcopy --strip-debug ${binary}\n\t\tgobjcopy --add-gnu-debuglink=${binary}.dbg ${binary}\n\tdone\n\tcd $CUR_W_D\nfi\n", "num_lines": 664}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\n##\n# Defining the Usage\n##\nUSAGE=\"Usage:   ./fx_bld_env_setup.sh <Top Build Dir> <CVS Username>\"\n[ -z $1 ] && echo $USAGE && exit 65\n[ -z $2 ] && echo $USAGE && exit 65\n\n##\n# Making top dir for build\n##\nif [ ! -d $1 ]\nthen\n\tmkdir -p $1\n\n\tif [ $? -eq 0 ]\n\tthen\n\t\tmkdir -p ${1}/source  ${1}/logs/FX   ${1}/binaries/FX\n\t\techo \"Created directory ${1} and subdirectories source, logs and binaries under it...\"\n\telse\n\t\texit 66\n\tfi\nelse\n\techo \"Directory $1 already exists. Attempting to create subdirectories source, logs and binaries under it...\" \n\tCUR_W_D=`pwd`\n\n\tcd $1\n\n\tif [ $? -eq 0 ]\n\tthen\n\t\tmkdir -p source logs/FX binaries/FX > /dev/null 2>&1\n\t\tcd $CUR_W_D\n\telse\n\t\tcd $CUR_W_D\n\t\texit 67\n\tfi\nfi\n", "num_lines": 39}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\n##\n# Defining the Usage\n##\nUSAGE=\"Usage:   ./fx_checkout.sh <CVS Username> [-t thirdparty path] [Top Bld Dir] [CVS Tag Name]. Default values for parameters in square brackets are to checkout thirdparty under source, use current directory, HEAD.\"\n[ -z \"$1\" ] && echo $USAGE && exit 75\n\n##\n# Setting the required variables\n##\nCVS_USERNAME=$1\nif [ \"$2\" = \"-t\" ]; then\n\tTHIRDPARTY_PATH=$3\n\n\tTOP_BLD_DIR=${4:-`pwd`}\n\tCVS_TAG=${5:-HEAD}\nelse\n\tTOP_BLD_DIR=${2:-`pwd`}\n\tCVS_TAG=${3:-HEAD}\nfi\nCVS_CMD=\"cvs co -r $CVS_TAG\"\nCHKOUT_LOG=\"checkout_$CVS_TAG.log\"\n\n##\n# set the common required shell variables\n##\n\n# CVSROOT: This is required for checking out source code from CVS\nCVSROOT=:pserver:${CVS_USERNAME}@10.150.24.11:/src\nCVSROOT_THIRDPARTY=:pserver:${CVS_USERNAME}@10.150.24.11:/thirdparty\nexport CVSROOT\n\n# PATH: Adding CVS path to PATH variable\nif [ -f /usr/bin/cvs ]; then\n        PATH=$PATH:/usr/bin\nelse\n        PATH=$PATH:/usr/local/bin\nfi\n\nexport PATH\n\n# First, change directories to the source folder where checkout will take place\nif [ -d $TOP_BLD_DIR/source ]; then\n  CUR_W_D=`pwd`\n  cd $TOP_BLD_DIR/source\nelse\n  echo \"Directory $TOP_BLD_DIR/source not found!\"\n  exit 76\nfi\n: > $CHKOUT_LOG\n\n# Guess the OS of the build machine by checking out OS_details.sh and running it\n# Now the variable OS will hold the OS name and bit details\ncvs co -r $CVS_TAG build/scripts/general/OS_details.sh \n\nchmod +x build/scripts/general/OS_details.sh\n. build/scripts/general/OS_details.sh\n\ncase `uname` in\n        AIX)\n\t      if [ `uname -v` -eq 5 ] ; then \n                case `uname -r` in\n                        3) AIX_LIB=\"thirdparty/aix/lib53/st_libs\"; CURL_HEADERS=\"thirdparty/aix/lib53/curl-7.59.0/include/curl\" ;;\n                esac\n\t      elif [ `uname -v` -eq 6 ] ; then\n\t\tcase `uname -r` in\n\t\t\t1)AIX_LIB=\"thirdparty/aix/lib61/st_libs\" ;;\n\t\tesac\n\t      fi\n                FILE_LIST=\"$AIX_LIB $CURL_HEADERS thirdparty/Notices/notices.txt\"\n                ln -s -f $AIX_LIB lib\n                for FILE in $FILE_LIST\n                do\n\t\t\tCVSROOT=$CVSROOT_THIRDPARTY\n\t\t\texport CVSROOT\n                        cvs co $FILE >> $CHKOUT_LOG 2>&1\n                        chmod +x $FILE\n                        [ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n                done\n\t\tchmod -R +x lib\n\t\t;;\n        SunOS)\n                case `uname -r` in\n                        5.8)\n\t\t\t\tFILE_LIST=\"thirdparty/solaris/58/lib/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/solaris/58/lib/st_libs lib\n                                ;;\n\t\t\t5.9)\n\t\t\t\tFILE_LIST=\"thirdparty/solaris/59/lib/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/solaris/59/lib/st_libs lib\n\t\t\t\t;;\n                        5.10)\n\t\t\t    case `uname -p` in\n\t\t\t     sparc)\n\t\t\t\tFILE_LIST=\"thirdparty/solaris/510/lib/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/solaris/510/lib/st_libs lib ;;\n\t\t\t      i386|i86pc)\n\t\t\t\tFILE_LIST=\"thirdparty/solaris/510/lib_x86/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/solaris/510/lib_x86/st_libs lib ;;\n\t\t\t    esac\n\t\t\t    ;;\n\t\t\t5.11)\n\t\t\t\tcase `uname -p` in\n\t\t\t\t    i386|i86pc)\n\t\t\t\t\tFILE_LIST=\"thirdparty/solaris/511/lib_x86/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\t\tln -s -f thirdparty/solaris/511/lib_x86/st_libs lib ;;\n\t\t\t\tesac\n\t\t\t;;\t\n                esac\n                for FILE in $FILE_LIST\n                do\n\t\t\tCVSROOT=$CVSROOT_THIRDPARTY\n\t\t\texport CVSROOT\n                        cvs co $FILE >> $CHKOUT_LOG 2>&1\n                        chmod +x $FILE\n                        [ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n                done\n\t\tchmod -R +x lib\n\t\t;;\n\n        HP-UX)\n                if ! uname -a | grep -iq ia64; then\n                        # PA-RISC architecture\n                        FILE_LIST=\"thirdparty/hpux/lib/st_libs thirdparty/Notices/notices.txt\"\n\n                        for FILE in $FILE_LIST\n                        do\n\t\t\t\tCVSROOT=$CVSROOT_THIRDPARTY\n\t\t\t\texport CVSROOT\n                                cvs co $FILE >> $CHKOUT_LOG 2>&1\n                                chmod +x $FILE\n                                [ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n                        done\n\n                        chmod -R +x thirdparty/hpux/lib/st_libs\n                        ln -s -f thirdparty/hpux/lib/st_libs lib\n\n\t\telse\n\t\t\tcase `uname -r` in\n\t\t\tB.11.23)\n\t\t\t\t# Itanium architecture 11i v2\n\t\t\t\tFILE_LIST=\"thirdparty/hpux_itanium/lib/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/hpux_itanium/lib/st_libs lib\n\t\t\t\tfor FILE in $FILE_LIST\n\t\t\t\tdo\n\t\t\t\t\tCVSROOT=$CVSROOT_THIRDPARTY\n\t\t\t\t\texport CVSROOT\n\t\t\t\t\tcvs co $FILE >> $CHKOUT_LOG 2>&1\n\t\t\t\t\tchmod +x $FILE\n\t\t\t\t\t[ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n\t\t\t\tdone\n\t\t\t\t;;\n\t\t\tB.11.31)\n\t\t\t\t# Itanium architecture 11i v3\n\t\t\t\tFILE_LIST=\"thirdparty/hpux_itanium11iv3/lib/st_libs thirdparty/Notices/notices.txt\"\n\t\t\t\tln -s -f thirdparty/hpux_itanium11iv3/lib/st_libs lib\n\t\t\t\tfor FILE in $FILE_LIST\n\t\t\t\tdo\n\t\t\t\t\tCVSROOT=$CVSROOT_THIRDPARTY\n\t\t\t\t\texport CVSROOT\n\t\t\t\t\tcvs co $FILE >> $CHKOUT_LOG 2>&1\n\t\t\t\t\tchmod +x $FILE\n\t\t\t\t\t[ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n\t\t\t\tdone\n\t\t\t\t;;\n\t\t\tesac\n\t\tfi\n\t\tchmod -R +x lib\n\t\t;;\nesac\n\n# This is the checkout part that's common to all the OSes that FX is built on\nCVSROOT=:pserver:${CVS_USERNAME}@10.150.24.11:/src\nexport CVSROOT\n\n\n# Checkout only required files if the OS is non-linux.\n\t\tfor FILE in \\\n\t\t\tbuild/ \\\n\t\t\thost/branding/branding_parameters.h \\\n\t\t\thost/fr_common/unix/svtypes.h \\\n\t\t\thost/fr_common/unix/portableunix.h \\\n\t\t\thost/fr_common/unix/portableunix.cpp \\\n\t\t\thost/fr_common/defines.h \\\n\t\t\thost/fr_common/svtransport.cpp \\\n\t\t\thost/fr_common/svutils.h \\\n\t\t\thost/fr_common/portable.h \\\n\t\t\thost/fr_common/svmacros.cpp \\\n\t\t\thost/fr_common/svtypes.cpp \\\n\t\t\thost/fr_common/svstatus.h \\\n\t\t\thost/fr_common/hostagenthelpers_ported.h \\\n\t\t\thost/fr_common/svtransport.h \\\n\t\t\thost/fr_common/unixagenthelpers.cpp \\\n\t\t\thost/fr_common/svmacros.h \\\n\t\t\thost/fr_common/svutils.cpp \\\n\t\t\thost/fr_common/svuuid.h \\\n\t\t\thost/fr_common/svuuid.cpp \\\n\t\t\thost/fr_common/unregworker.h \\\n\t\t\thost/fr_common/compatibility.h \\\n\t\t\thost/fr_common/unregworker.cpp \\\n\t\t\thost/fr_common/version.h \\\n\t\t\thost/fr_config/svconfig.cpp \\\n\t\t\thost/fr_config/svconfig.h \\\n\t\t\thost/fragent/fragent.h \\\n\t\t\thost/fragent/fragent.cpp \\\n\t\t\thost/frdaemon/daemon.cpp \\\n\t\t\thost/fr_log/logger.cpp \\\n\t\t\thost/fr_log/logger.h \\\n\t\t\thost/fr_unregagent/unixunreg.cpp \\\n\t\t\thost/fr_unregagent/Makefile \\\n\t\t\thost/inmsync/ \\\n\t\t\thost/conversionlib \\\n\t\t\thost/dataprotection \\\n\t\t\tbuild/inmage \\\n\t\t\tbuild/xiotech \\\n\t\t\thost/vacp/ACM_SCRIPTS/linux/linuxshare_pre.sh \\\n\t\t\thost/vacp/ACM_SCRIPTS/linux/linuxshare_post.sh \\\n\t\t\thost/fxdspace/fxdspace.cpp \\\n\t\t\thost/fxdspace/Makefile \\\n\t\t\thost/fxalert/fxalert.cpp \\\n\t\t\thost/fxalert/Makefile \\\n\t\t\thost/gcc-depend \\\n\t\t\thost/get-generic-version-info \\\n\t\t\thost/get-specific-version-info \\\n\t\t\thost/set-make-env \\\n\t\t\thost/validate-modules-set \\\n\t\t\thost/set-make-os-env \\\n\t\t\thost/is-generated-header \\\n\t\t\thost/depend.sh \\\n\t\t\thost/thirdparty_build.sh \\\n\t\t\thost/thirdparty_links.sh \\\n\t\t\thost/top.mak \\\n\t\t\thost/bottom.mak \\\n\t\t\thost/once.mak  \\\n\t\t\thost/find-dir-deps \\\n\t\t\thost/rules.mak \\\n\t\t\thost/thirdparty.mak \\\n\t\t\thost/Makefile \\\n\t\t\thost/fr_log/Makefile \\\n\t\t\thost/fr_common/Makefile \\\n\t\t\thost/fr_config/Makefile \\\n\t\t\thost/fragent/Makefile \\\n\t\t\thost/frdaemon/Makefile \\\n\t\t\thost/config/transport_settings.h \\\n\t\t\thost/common \\\n\t\t\thost/remotecli \\\n\t\t\thost/cdplibs \\\n\t\t\thost/vacplibs \\\n\t\t\thost/vacpunix \\\n\t\t\thost/fx_vacp-thirdparty.mak \\\n\t\t\thost/fx_vacp.mak \\\n\t\t\thost/fx_vacp-rules.mak \\\n\t\t\thost/AIX_00C14AB24C00-rules.mak \\\n\t\t\thost/AIX_00C14AB24C00-thirdparty.mak \\\n\t\t\thost/AIX_00C14AB24C00.mak \\\n\t\t\thost/AIX_00C4E42C4C00-rules.mak \\\n\t\t\thost/AIX_00C4E42C4C00-thirdparty.mak \\\n\t\t\thost/AIX_00C4E42C4C00.mak \\\n\t\t\thost/AIX_00C4E42C4C00.mak \\\n\t\t\thost/HP-UX_ia64-thirdparty.mak \\\n\t\t\thost/HP-UX_ia64.mak \\\n\t\t\thost/linux-rules.mak \\\n\t\t\thost/once.mak \\\n\t\t\tserver/linux/cx_backup_withfx.sh \\\n\t\t\tSolutions/Fabric/Oracle/FX \\\n\t\t\tSolutions/Oracle/Fx/cx/logrm_applylist.sh \\\n\t\t\tSolutions/Oracle/Fx/cx/logrm_mv_cx.sh \\\n\t\t\tSolutions/Oracle/Fx/source/getDBsize.sh \\\n\t\t\tSolutions/Oracle/Fx/source/prepdump.sh \\\n\t\t\tSolutions/Oracle/Fx/target/preprestore.sh \\\n\t\t\tSolutions/Oracle/Fx/target/recovermain.sh \\\n\t\t\tSolutions/Oracle/Fx/target/recover.sh\n\t\tdo\n\t\t\t$CVS_CMD $FILE >> $CHKOUT_LOG 2>&1\n\t\t\t[ $? -ne 0 ] && echo \"CVS Checkout failed for $FILE\" >> $CHKOUT_LOG\n\t\tdone\n\n# Sometimes dependency checking seems to loop forever seemingly because \n# checked out files are timestamped in the future after checkout\ntouch host/*\n\n# Build uses some of the header files of thirdparty boost.\n# Create a softlink to thirdparty boost.\n\nmkdir -p ${TOP_BLD_DIR}/source/thirdparty/boost\ncd ${TOP_BLD_DIR}/source/thirdparty/boost\nln -s ${THIRDPARTY_PATH}/boost/boost_1_78_0 boost_1_78_0\n\nif grep \"CVS Checkout failed for\" $CHKOUT_LOG 2>/dev/null ; then\n\techo \"CVS checkout failed.\"\n\texit 77\nelse\n\trm -f $CHKOUT_LOG > /dev/null 2>&1\nfi\n\ncd $CUR_W_D\n", "num_lines": 298}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n##\n# Defining different exit codes. This would help track failures better\n##\n\n# Exit code table\nE_SUCCESS=0\nE_GENERIC_FAILURE=1\nE_OS_NOT_SUPPORTED=25\nE_SETUP_ARG_MISSING=65\nE_SETUP_DIRCREATION_FAILURE=66\nE_SETUP_CHANGEDIR_FAILURE=67\nE_CHECKOUT_ARG_MISSING=75\nE_CHECKOUT_SOURCE_DIR_NOT_FOUND=76\nE_CHECKOUT_FAILURE=77\nE_BUILD_INCORRECT_ARG=95\nE_BUILD_INMSYNC_FAILURE=96\nE_BUILD_INMSYNC_DIR_NOT_FOUND=97\nE_BUILD_SVFRD_FAILURE=98\nE_BUILD_SOURCE_DIR_NOT_FOUND=99\nE_BUILD_UNREG_FAILURE=100\nE_BUILD_ALERT_FAILURE=101\nE_BUILD_DSPACE_FAILURE=102\nE_BUILD_VACP_FAILURE=103\nE_VERSION_ARG_MISSING=85\nE_VERSION_BRANCH_MISMATCH=86\nE_VERSION_BIN_DIR_NOT_FOUND=87\nE_VERSION_DCAL_NOT_FOUND=88\nE_PACKAGING_BINARIES_ABSENT=105\nE_PACKAGING_PARTNER_DIR_ABSENT=106\n\n##\n# This function executes a command and logs the output\n##\nDO_AND_LOG()\n{\n\tCMD=$1\n\teval $CMD >> $FLOG\n}\n\n##\n# This function verifies the exit status of a program and print messages accordingly\n##\nVERIFY()\n{\n\tstatus=$1\n\n\tcase $status in\n\n\t\t$E_SUCCESS) ;;\n\n                $E_GENERIC_FAILURE)\n                        echo \"FAILURE WHILE BUILDING. PLEASE SEE ERROR MESSAGES ABOVE!\"\n                        exit $E_GENERIC_FAILURE ;;\n\n                $E_OS_NOT_SUPPORTED)\n                        echo \"THIS PLATFORM IS NOT SUPPORTED YET!\"\n                        exit $E_OS_NOT_SUPPORTED ;;\n\n\t\t$E_SETUP_ARG_MISSING)\n\t\t   \techo \"SOME OR ALL ARGUMENTS FOR fx_bld_env_setup.sh ARE MISSING!\"\n\t\t\texit $E_SETUP_ARG_MISSING ;;\n\n\t\t$E_SETUP_DIRCREATION_FAILURE)\n\t\t\techo \"DIRECTORY $TOP_BLD_DIR COULD NOT BE CREATED!\"\n\t\t\texit $E_SETUP_DIRCREATION_FAILURE ;;\n\n\t\t$E_SETUP_CHANGEDIR_FAILURE)\n\t\t\techo \"FAILED TO CHANGE DIRECTORY TO $TOP_BLD_DIR!\"\n\t\t\texit $E_SETUP_CHANGEDIR_FAILURE ;;\n\n\t\t$E_CHECKOUT_SOURCE_DIR_NOT_FOUND)\n\t\t\techo \"DIRECTORY source NOT FOUND UNDER TOP BUILD DIRECTORY!\"\n\t\t\texit $E_CHECKOUT_SOURCE_DIR_NOT_FOUND ;;\n\n\t\t$E_CHECKOUT_ARG_MISSING)\n\t\t\techo \"SOME OR ALL ARGUMENTS FOR fx_checkout.sh ARE MISSING!\"\n\t\t\texit $E_CHECKOUT_ARG_MISSING ;;\n\n\t\t$E_CHECKOUT_FAILURE)\n\t\t\techo \"CVS CHECKOUT FAILED FOR SOME FILES!\"\n\t\t\texit $E_CHECKOUT_FAILURE ;;\n\n\t\t$E_BUILD_INCORRECT_ARG)\n\t\t\techo \"INCORRECT ARGUMENTS FOR fx_bld.sh!\"\n\t\t\texit $E_BUILD_INCORRECT_ARG ;;\n\n\t\t$E_BUILD_INMSYNC_DIR_NOT_FOUND)\n\t\t\techo \"DIRECTORY host/inmsync NOT FOUND UNDER source DIRECTORY!\"\n\t\t\texit $E_BUILD_INMSYNC_DIR_NOT_FOUND ;;\n\n\t\t$E_BUILD_INMSYNC_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR inmsync!\"\n\t\t\texit $E_BUILD_INMSYNC_FAILURE ;;\n\n\t\t$E_BUILD_SVFRD_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR svfrd!\"\n\t\t\texit $E_BUILD_SVFRD_FAILURE ;;\n\n\t\t$E_BUILD_UNREG_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR unregagent!\"\n\t\t\texit $E_BUILD_UNREG_FAILURE ;;\n\n\t\t$E_BUILD_ALERT_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR alert!\"\n\t\t\texit $E_BUILD_ALERT_FAILURE ;;\n\n\t\t$E_BUILD_DSPACE_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR dspace!\"\n\t\t\texit $E_BUILD_DSPACE_FAILURE ;;\n\n\t\t$E_BUILD_VACP_FAILURE)\n\t\t\techo \"BUILD FAILURE FOR vacp!\"\n\t\t\texit $E_BUILD_VACP_FAILURE ;;\n\n\t\t$E_VERSION_ARG_MISSING)\n\t\t\techo \"INCORRECT ARGUMENTS FOR fx_packaging.sh!\"\n\t\t\texit $E_VERSION_ARG_MISSING ;;\n\n\t\t$E_VERSION_BIN_DIR_NOT_FOUND)\n\t\t\techo \"DIRECTORY binaries/FX NOT FOUND UNDER ${TOP_BLD_DIR}!\"\n\t\t\texit $E_VERSION_BIN_DIR_NOT_FOUND ;;\n\n\t\t$E_VERSION_DCAL_NOT_FOUND)\n\t\t\techo \"FILE dcal NOT FOUND FOR THIS OS!\"\n\t\t\texit $E_VERSION_DCAL_NOT_FOUND ;;\n\n\t\t$E_PACKAGING_BINARIES_ABSENT)\n\t\t\techo \"ALL BINARIES REQUIRED FOR PACKAGING ARE NOT PRESENT!\"\n\t\t\texit $E_PACKAGING_BINARIES_ABSENT ;;\n\n\t\t$E_PACKAGING_PARTNER_DIR_ABSENT)\n\t\t\techo \"DIRECTORY $TOP_BLD_DIR/source/build/$PARTNER NOT FOUND!\"\n\t\t\texit $E_PACKAGING_PARTNER_DIR_ABSENT ;;\n\n\tesac\n}\n\n##\n# Step 1: COMMAND LINE VALIDATION\n# This would capture various parameters passed to this script, validates them and\n# sets them to required variables\n##\n\nUSAGE=\"CORRECT USAGE: $0 <valid CVS username> [-t <thirdparty path>] [top build dir] [partner] [valid CVS branch-name] [valid CVS tag name] [build-phase] [bld-quality] [Major Version] [Minor Version] [Release Number] [CONFIG]\"\n\n[ -z \"$1\" ] && echo $USAGE && exit 1\n\n##\n# Setting the variables\n##\n\nCVS_USERNAME=$1\nif [ \"$2\" = \"-t\" ]; then\n\tTHIRDPARTY_PATH=$3\n\tPARTNER=${5:-inmage}\n\tTOP_BLD_DIR=${4:-`pwd`}\n\tCVS_BRANCH=${6:-HEAD}\n\tCVS_TAG=${7:-HEAD}\n\tBUILDPHASE=${8:-DIT}\n\tBUILDQUALITY=${9:-DAILY}\n\tshift\n\tMAJOR_VERSION=${9:-6}\n\tshift\n\tMINOR_VERSION=${9:-50}\n\tshift\n\tREL_NUM=${9:-1}\n\tshift\n\tCONFIG=${9:-debug}\nelse\n\tPARTNER=${3:-inmage}\n\tTOP_BLD_DIR=${2:-`pwd`}\n\tCVS_BRANCH=${4:-HEAD}\n\tCVS_TAG=${5:-HEAD}\n\tBUILDPHASE=${6:-DIT}\n\tBUILDQUALITY=${7:-DAILY}\n\tMAJOR_VERSION=${8:-6}\n\tMINOR_VERSION=${9:-50}\n\tshift\n\tREL_NUM=${9:-1}\n        shift\n        CONFIG=${9:-debug}\nfi\n\nif [ -n \"$THIRDPARTY_PATH\" ]; then\n    THIRDPARTY_ARG=\"-t $THIRDPARTY_PATH\"\nfi\n\nCVS_CMD=\"cvs co -r $CVS_BRANCH\"\nSUFFIX=`date +%d`_`date +%b`_`date +%H`_`date +%M`_`date +%S`\nFLOG=\"`pwd`/$TOP_BLD_DIR/logs/FX_Build_$SUFFIX.log\"\n\n[ \"$PARTNER\" = \"both\" ] && PARTNER=\"inmage xiotech\"\nBuild_Dir=`echo $TOP_BLD_DIR | sed -e \"s/\\///g\"`\n\nif [ ! -f build_status_${Build_Dir} ]; then\n        touch build_status_${Build_Dir}\n        SETUP=1 CHECKOUT=1 BRANDING=1 VERSIONING=1 BUILD=1 PACKAGING=1\nelse\n        if grep -iq \"setup\" build_status_${Build_Dir} ; then\n                SETUP=0\n        else\n                SETUP=1\n        fi\n\n        if grep -iq \"checkout\" build_status_${Build_Dir} ; then\n                CHECKOUT=0\n        else\n                CHECKOUT=1\n        fi\n\n        if grep -iq \"branding_${PARTNER}\" build_status_${Build_Dir} ; then\n                BRANDING=0\n        else\n                BRANDING=1\n        fi\n\n        if grep -iq \"versioning_${PARTNER}\" build_status_${Build_Dir} ; then\n                VERSIONING=0\n        else\n                VERSIONING=1\n        fi\n\n        if grep -iq \"build_${PARTNER}\" build_status_${Build_Dir} ; then\n                BUILD=0\n        else\n                BUILD=1\n        fi\n\n        if grep -iq \"packaging_${PARTNER}\" build_status_${Build_Dir} ; then\n                PACKAGING=0\n        else\n                PACKAGING=1\n        fi\nfi\n\n##\n# Step 2: BUILD ENVIRONMENT SETUP\n# Making top dir for build\n##\n\nif [ $SETUP -eq 1 ]; then\n    echo\n    echo \"Setting up required directory structure...\"\n    echo\n    ./fx_bld_env_setup.sh $TOP_BLD_DIR $CVS_USERNAME\n    SETUP_EXIT_STATUS=$?\n    VERIFY $SETUP_EXIT_STATUS\n    echo \"setup\" >> build_status_${Build_Dir}\nelse\n    echo \"Build directory structure setup already done for $TOP_BLD_DIR!\"\nfi\n\n##\n# Step 3: CHECKOUT\n# Set variables and checkout files as required on the chosen OS\n##\n\nif [ $CHECKOUT -eq 1 ] ; then\n    echo\n    echo \"Checking out source code now...\"\n    echo\n    ./fx_checkout.sh $CVS_USERNAME $THIRDPARTY_ARG $TOP_BLD_DIR $CVS_TAG \n    CHECKOUT_EXIT_STATUS=$?\n    VERIFY $CHECKOUT_EXIT_STATUS\n    echo \"checkout\" >> build_status_${Build_Dir}\nelse\n    echo \"Source code checkout already done for $TOP_BLD_DIR!\"\nfi\n\n. ${TOP_BLD_DIR}/source/build/scripts/general/OS_details.sh\n\n##\n# Step 4: BRANDING\n##\n\nif [ $BRANDING -eq 1 ] ; then\n        echo\n        echo \"Branding the source code and build environment variables now...\"\n        echo\n\n        # Source the branding parameters script here. Working directory is source which contains the build folder\n        . $TOP_BLD_DIR/source/build/branding/$PARTNER/branding_parameters.sh\n\n        # Copy the branding_parameters.h file to host/branding\n        cp $TOP_BLD_DIR/source/build/branding/$PARTNER/branding_parameters.h $TOP_BLD_DIR/source/host/branding\n\n        echo \"branding_${PARTNER}\" >> build_status_${Build_Dir}\nelse\n        echo \"Source code and build environment branding already done for $TOP_BLD_DIR!\"\nfi\n\n##\n# Step 5: VERSIONING\n# Create a version file which shall also be packaged along with the binaries\n# Also update the build numbers, partner name etc, in the version.h file in <top-dir>/host/common\n# This will help any future installs or upgrades\n##\n\nif [ $VERSIONING -eq 1 ] ; then\n        echo\n        echo \"Changing version.h, generating .fx_version and .fx_build_manifest now...\"\n        echo\n\n        ./fx_versioning.sh $TOP_BLD_DIR $PARTNER $CVS_BRANCH $BUILDQUALITY $BUILDPHASE $MAJOR_VERSION $MINOR_VERSION $REL_NUM\n        VERSIONING_EXIT_STATUS=$?\n        VERIFY $VERSIONING_EXIT_STATUS\n        echo \"versioning_${PARTNER}\" >> build_status_${Build_Dir}\nelse\n        echo \"Generation of .fx_version and .fx_build_manifest, and change of version.h already done for $TOP_BLD_DIR!\"\nfi\n\ncase $OS in\n   RHEL*|SLES*|OPENSUSE*|CITRIX*)\n    if [ $BUILD -eq 1 ] ; then\n        echo\n        echo \"Building and packaging the FX agent now...\"\n        echo\n\tcur_wd=`pwd`\n\tcd $TOP_BLD_DIR/source/host \n\t# If the version is 500 change the version in the spec files and in the build_params_partner.conf file\n\tsed -e \"s/5.50.1/${MAJOR_VERSION}.${MINOR_VERSION}.${REL_NUM}/g\" ../build/scripts/FX/build_params_${PARTNER}.conf >> ../build/scripts/FX/build_params_${PARTNER}.conf.new\n\tmv ../build/scripts/FX/build_params_${PARTNER}.conf.new ../build/scripts/FX/build_params_${PARTNER}.conf\n\n\t# Find the version from the spec file.\n\tversion=`cat ../build/scripts/FX/templates/${PARTNER}.spec | grep \"^Version\" | cut -d\":\" -f2 | tr -d \" \"`\n\trelease=`cat ../build/scripts/FX/templates/${PARTNER}.spec | grep \"^Release\" | cut -d\":\" -f2 | tr -d \" \"`\n\tsed -e \"s/$version/${MAJOR_VERSION}.${MINOR_VERSION}/\" ../build/scripts/FX/templates/${PARTNER}.spec >> ../build/scripts/FX/templates/${PARTNER}.spec.new\n\tmv ../build/scripts/FX/templates/${PARTNER}.spec.new ../build/scripts/FX/templates/${PARTNER}.spec\n\t\n\tsed -e \"s/$release/${REL_NUM}/\" ../build/scripts/FX/templates/${PARTNER}.spec >> ../build/scripts/FX/templates/${PARTNER}.spec.new\n\tmv ../build/scripts/FX/templates/${PARTNER}.spec.new ../build/scripts/FX/templates/${PARTNER}.spec\n\n\tmake clean\t\t\n\tmake X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=$MINOR_VERSION X_VERSION_PHASE=$REL_NUM X_VERSION_QUALITY=$BUILDQUALITY X_VERSION_PHASE=$BUILDPHASE partner=$PARTNER debug=no verbose=yes fx_setup \n\tVERIFY $?\n\tcd ../../binaries/FX \n\tcp ../../source/host/`uname -ms | tr ' ' '_'`/setup/release/*.gz .\n\tVERIFY $?\n\tcd $cur_wd\n\techo \"build_${PARTNER}\" >> build_status_${Build_Dir}\n\techo \"packaging_${PARTNER}\" >> build_status_${Build_Dir}\n\n        # Generating the symbols for FX\n\n        if [ `uname` = \"Linux\" ]; then\n                DATE_TIME_SUFFIX=`date +%d%b%Y`\n                FX_VERSION=${MAJOR_VERSION}.${MINOR_VERSION}.${REL_NUM}\n\n                for file in `find  $TOP_BLD_DIR/source/host -name \"*.dbg\"`\n                do\n                        BaseDir=`dirname $file`\n                        BaseName=`basename $file`\n                        tar --append --file=${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar -C $BaseDir $BaseName\n                done\n\n                gzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar\n                [ $? -eq 0 ] && echo \"FX SYMBOL TAR FILE GENERATION IS SUCCESSFUL FOR $PARTNER on ${OS}...\"\n\n                mv ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILDPHASE}_${DATE_TIME_SUFFIX}_symbols.tar.gz $TOP_BLD_DIR/binaries/FX\n                [ $? -eq 0 ] && echo \"Copied symbol tar to $TOP_BLD_DIR/binaries/FX...\"\n\n        fi\n\n    else\n        echo \"Build and Packaging already done for $TOP_BLD_DIR!\"\n    fi\n\n\t;;\n\n*)\n\n##\n# Step 6: BUILD\n# Default argument is 'all' (i.e. svfrd, unregagent). If you want \n# selective build, pass comma-separated values \n# e.g. ./build_common.sh svfrd,unregagent\n##\n\nif [ $BUILD -eq 1 ] ; then\n    echo\n    echo \"Building the FX agent now...\"\n    echo\n    ./fx_bld.sh $TOP_BLD_DIR all $CONFIG\n    BUILD_EXIT_STATUS=$?\t\n    VERIFY $BUILD_EXIT_STATUS\n    echo \"build_${PARTNER}\" >> build_status_${Build_Dir}\nelse\n    echo \"Build already done for $TOP_BLD_DIR!\"\nfi\n\n##\n# Step 7: PACKAGING\n# The packaging script replaces a lot of placeholder variables in the templates with some values at packaging time\n# and leaves some others to be replaced at install time. It then copies all the required files into a temporary dir\n# and creates an RPM or a TAR based on whether the operating system is Linux or otherwise.\n##\n\nif [ $PACKAGING -eq 1 ] ; then\n    echo\n    echo \"Packaging the FX agent now...\"\n    echo\n    ./fx_packaging.sh $PARTNER $TOP_BLD_DIR/binaries/FX $BUILDPHASE $CONFIG\n    PACKAGING_EXIT_STATUS=$?\n    VERIFY $PACKAGING_EXIT_STATUS\n    echo \"packaging_${PARTNER}\" >> build_status_${Build_Dir}\nelse\n    echo \"Packaging already done for $TOP_BLD_DIR!\"\nfi\n\t;;\nesac\n", "num_lines": 413}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\n##\n# Step 1: USAGE\n# This would define the usage and also checks whether the build is successful\n# or not for starting the packaging\n##\n\n# Define the usage\nUSAGE=\"Usage:   ./fx_packaging.sh [partner] [path of binaries]. Defaults are 'inmage' and current directory.\"\n\n# Set the required variables from the parameters passed as arguments\nPARTNER=${1:-inmage}\nBINARY_PATH=${2:-`pwd`}\nBUILD_PHASE=${3:-DIT}\nCONFIG=${4:-debug}\n\nDATE_TIME_SUFFIX=`date +%d%b%Y`\n\ncase $PARTNER in\n\t\tinmage)\n\t\t\t\tPARTNER_SPECIFIC_STRING=\"InMage\";;\n\t\txiotech)\n\t\t\t\tPARTNER_SPECIFIC_STRING=\"Xiotech\";;\nesac\n\n# Check to see if build succeeded or not!\nif [ -f $BINARY_PATH/svfrd ] && [ -f $BINARY_PATH/unregfragent ] && [ -f $BINARY_PATH/alert ] && [ -f $BINARY_PATH/dspace ] &&  [ -f $BINARY_PATH/remotecli ] && [ -f $BINARY_PATH/vacp ]  \nthen\n\techo \"All required binaries ( svfrd, unregfragent, alert, dspace, remotecli and vacp ) are present. Starting the packaging process now...\"\nelse\n\techo \"Since all or one of the required binaries ( svfrd,alert, dspace, unregfragent, remotecli and vacp) are not present, aborting packaging!\"\n\texit 105\nfi\n\n\n##\n# Step 2: \n# This would define the usage and also checks whether the build is successful\n# or not for starting the packaging\n##\n# Now, if the control reached this point, it means that build was successful, so we can now go on with the packaging stuff\n# Current directory is TOP_DIR/source\n##\n\nCUR_W_D=`pwd`\n\n# Source the build parameters script here\n. ./build_params_${PARTNER}.conf\n\ncd $BINARY_PATH\n\n# Guess the OS\n. $BINARY_PATH/../../source/build/scripts/general/OS_details.sh\n\n\n# Source the branding parameters script here\n. ../../source/build/branding/$PARTNER/branding_parameters.sh\n\n# Replace some placeholders in some of the template files during BUILD time\n# Whatever placeholders remain will be replaced at INSTALL time\n\n# 1. stop\nsed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/stop > stop\n\n# 2. start\nsed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/start > start\n\n# 3. status\nsed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/status > status\n\n# 4. uninstall\n    sed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/uninstall | \\\n    sed -e \"s|BUILDTIME_VALUE_RPM_PACKAGE|$BUILT_RPM_PACKAGE|\" | \\\n    sed -e \"s|BUILDTIME_VALUE_REF_DIR|$METADATA_REF_DIR|\" | \\\n    sed -e \"s|BUILDTIME_VALUE_BLD_MANIFEST_FILE_NAME|$BUILD_MANIFEST_FILE_NAME|\" | \\\n    sed -e \"s|BUILDTIME_VALUE_INST_VERSION_FILE|$VERSION_FILE_NAME|\" > uninstall\n\n# 5. unregister\nsed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/unregister | \\\nsed -e \"s|BUILDTIME_VALUE_REF_DIR|$METADATA_REF_DIR|\" | \\\nsed -e \"s|BUILDTIME_VALUE_INST_VERSION_FILE|$VERSION_FILE_NAME|\" | \\\nsed -e \"s|CX|$LABEL|g\" > unregister\n\n# 6. install\n    sed -e \"s|PARTNER_OR_COMPANY|$COMPANY|g\" ../../source/build/scripts/FX/templates/install | \\\n    sed -e \"s|CX|$LABEL|g\" | sed -e \"s|DEFAULT_PARTNER_INSTALL_DIR|$DEFAULT_INSTALL_DIR|g\" | \\\n    sed -e \"s|BUILDTIME_CURRENT_VERSION|$FX_VERSION|\" | \\\n    sed -e \"s|BUILDTIME_INST_VERSION_FILE|$VERSION_FILE_NAME|\" | \\\n    sed -e \"s|BUILDTIME_BUILD_MANIFEST_FILE|$BUILD_MANIFEST_FILE_NAME|\" | \\\n    sed -e \"s|BUILDTIME_MAIN_RPM_FILE|$BUILT_RPM_FILE|\" | \\\n    sed -e \"s|BUILDTIME_MAIN_RPM_PACKAGE|$BUILT_RPM_PACKAGE|\" | \\\n    sed -e \"s|BUILDTIME_DEFAULT_UPGRADE_DIR|$DEFAULT_UPG_DIR|\" | \\\n    sed -e \"s|BUILDTIME_PARTNER_SPECIFIC_STRING|$PARTNER_SPECIFIC_STRING|\" | \\\n    sed -e \"s|BUILDTIME_REF_DIR|$METADATA_REF_DIR|\" > install\n\ncp ../../source/build/scripts/FX/templates/svagent .\ncp ../../source/build/scripts/FX/templates/config.ini .   \n\n# conf_file\nsed -e \"s|DEFAULT_PARTNER_INSTALL_DIR|$DEFAULT_INSTALL_DIR|g\" ../../source/build/scripts/FX/templates/conf_file > conf_file\n\n# Copy unchanged files from templates folder to the curr dir\n\ncp ../../source/build/scripts/FX/templates/killchildren .\ncp ../../source/host/vacp/ACM_SCRIPTS/linux/linuxshare_pre.sh .\ncp ../../source/host/vacp/ACM_SCRIPTS/linux/linuxshare_post.sh .\ncp ../../source/build/scripts/general/OS_details.sh .\n\n# Get the OS variable\n. ../../source/build/scripts/general/OS_details.sh\n\n\n# Setting the option EnableDeleteOptions = 3255 instead of 0 so that it is enabled by default. \n\nsed -e \"s/EnableDeleteOptions = 0/EnableDeleteOptions = 3255/\" config.ini > config.ini.new\nmv config.ini.new config.ini\nchmod +x config.ini\n\n# Copy the fabric/oracle/fx scripts to curr dir\ncp ../../source/Solutions/Fabric/Oracle/FX/*.sh .\n\n# Copy the oracle/fx scripts to curr dir\ncp ../../source/Solutions/Oracle/Fx/cx/logrm_applylist.sh .\ncp ../../source/Solutions/Oracle/Fx/cx/logrm_mv_cx.sh .\ncp ../../source/Solutions/Oracle/Fx/source/getDBsize.sh .\ncp ../../source/Solutions/Oracle/Fx/source/prepdump.sh .\ncp ../../source/Solutions/Oracle/Fx/target/preprestore.sh .\ncp ../../source/Solutions/Oracle/Fx/target/recovermain.sh .\ncp ../../source/Solutions/Oracle/Fx/target/recover.sh .\n\n# Copy notices.txt here only if OS is not DEBIAN. For DEBIAN we are copying notices.txt in checkout step.\nfind $BINARY_PATH/../../source -name notices.txt -exec cp {} . \\;\n\nif [ -f $BINARY_PATH/notices.txt ]; then\n    :\nelse\n    echo \"notices.txt file is missing ...\"\n    exit 1\nfi\n    \n# Grant execute permissions to the scripts above\nchmod -R 755 *.*\n\n# This is specific to HPUX\n# Giving the chatr enabled for all the binaries svfrd,unregfragent,alert,dspace,remotecli,vacp and inmsync\n[ `uname` = \"HP-UX\" ] && chatr +s enable svfrd unregfragent alert dspace remotecli vacp inmsync\n\n# Now, depending on the target operating system, differentiate the packaging procedure\n# If it is RHEL4 or SuSE9 or SuSE10, use RPM. Otherwise, use a simple tar.gz and build the installing\n# logic into the install script itself.\n\nif [ `uname` = \"SunOS\" -a \"$CONFIG\" = \"release\" ]; then\n\tCONF=\"_release\"\nelif [ `uname` = \"SunOS\" -a \"$CONFIG\" = \"debug\" ]; then\n\tCONF=\"_debug\"\nelse\n\tCONF=\"\"\nfi\n\n# Create temporary directories for building the TAR\nmkdir -p TAR_BUILD/lib TAR_BUILD/scripts TAR_BUILD/fabric/scripts\n# Copy required files to this directory\n\n\t\tcp -f start stop status uninstall svagent svfrd inmsync unregister alert dspace \\\n\t\tremotecli unregfragent vacp config.ini notices.txt killchildren TAR_BUILD/\n\t\n\t\tcp -f ../../source/lib/libgcc_s*  ../../source/lib/libstdc++* TAR_BUILD/lib/\n\n\t\t# Copy the oracle/fx scripts to TAR\n\t\tcp -f logrm_applylist.sh logrm_mv_cx.sh getDBsize.sh prepdump.sh preprestore.sh recovermain.sh recover.sh TAR_BUILD/scripts\n\t\tcp -f application.sh oracle.sh TAR_BUILD/fabric/scripts\n\t\t# Enter tar file name into version file as install script will use it\n\t\techo \"TAR_FILE_NAME=${COMPANY}_FX_${FX_VERSION}_${OS}.tar\" >> $VERSION_FILE_NAME\n\n\t\t# Create the TAR now\n\t\tcd TAR_BUILD/\n\t\ttar -cvf ../${COMPANY}_FX_${FX_VERSION}_${OS}.tar .\n\t\t# If tar created successfully, create the final tar.gz\n\t\tif [ $? -eq 0 ]; then\n\t\t\tcd ..\n\t\t\trm -rf TAR_BUILD/\n\t\t\tchmod +x install\n\t\t\ttar -cvf ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}${CONF}.tar \\\n\t\t\t${COMPANY}_FX_${FX_VERSION}_${OS}.tar install OS_details.sh $VERSION_FILE_NAME \\\n\t\t\t$BUILD_MANIFEST_FILE_NAME conf_file\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\tgzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}${CONF}.tar \n\t\t\t\t[ $? -eq 0 ] && echo \"FX BUILD AND PACKAGING IS SUCCESSFUL FOR $PARTNER on ${OS}...\"\n\t\t\tfi\n\t\tfi\n\n# Package the symbol files (.dbg) also\n\nif [ `uname` = \"SunOS\" -a \"$CONFIG\" = \"release\" ]; then\n    cd $BINARY_PATH\n    tar -cvf ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}_${CONFIG}_symbols.tar *.dbg\n    gzip ${COMPANY}_FX_${FX_VERSION}_${OS}_${BUILD_PHASE}_${DATE_TIME_SUFFIX}_${CONFIG}_symbols.tar\n    [ $? -eq 0 ] && echo \"FX SYMBOL TAR FILE GENERATION IS SUCCESSFUL FOR $PARTNER on ${OS}...\"\nfi\n\n# Change directories back to the original working directory at the start of this script\ncd $CUR_W_D\n", "num_lines": 204}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\nUSAGE=\"Usage:   ./fx_versioning.sh <top build dir> [partner] [branch] [buildquality] [buildphase] [Major Version] [Minor Version] [Release Number]. Default value for arguments in square brackets are 'inmage', 'HEAD', 'DAILY' and 'DIT'.\"\n[ -z \"$1\" ] && echo $USAGE && exit 85\n\n##\n# Setting the required variables\n##\n\nTOP_BLD_DIR=$1\nPARTNER=${2:-inmage}\nbranchName=${3:-HEAD}\nbuildQuality=${4:-DAILY}\nbuildPhase=${5:-DIT}\nverYear=`date +%Y`\nverMonth=`date +%h`\nverDate=`date +%d`\nmaj_ver=${6:-5}\nmin_ver=${7:-50}\n\npatch_set_ver=00\npatch_ver=00\n\nrel_num=${8:-1}\nbld_seq_num=1\nrelTagString=\"${buildQuality}_${maj_ver}-${min_ver}-${rel_num}_${buildPhase}\"\n\ncase $branchName in\n        TRUNK|TRUNC|HEAD|SCOUT_7-2_OSS_SEC_FIXES_BRANCH)\n                refSecs=1104517800 ;;\nesac\n\nPATCH_VERSION=${maj_ver}.${min_ver}.${patch_set_ver}.${patch_ver}\n\n##\n# Calculate the number of seconds elapsed till now from UNIX epoch\n# and thereby the tag name for this particular release\n# There are 2 ways of calculating this figure - either by date +%s\n# command or by compiling and storing in CVS a program called dcal\n# which can return the figure. date +%s seems to be more like\n# a GNU extension than anything else so don't expect all OSes to\n# accommodate this command-argument.\n##\n\n. ${TOP_BLD_DIR}/source/build/scripts/general/OS_details.sh\nDCAL_BIN=\"${TOP_BLD_DIR}/source/build/scripts/general/bin/dcal_${OS}\"\n\nif [ -f $DCAL_BIN ]; then\n\tno_of_secs_now=`$DCAL_BIN`\nelse\n        no_of_secs_now=`date +%s`\nfi\n\ndlybldNum=`expr \\`expr $no_of_secs_now - $refSecs\\` / 86400`\n\ncase $PARTNER in\n        inmage|InMage) PARTNER_VERSION_STRING=\"InMage\" ;;\n        xiotech|Xiotech) PARTNER_VERSION_STRING=\"Xiotech\" ;;\n        *) echo \"$partner not handled yet in this script...aborting!\" && exit 1 ;;\nesac\n\ntagName=\"${relTagString}_${dlybldNum}_${verMonth}_${verDate}_${verYear}_${PARTNER_VERSION_STRING}\"\n\n##################################\n# Source the build param file here\n# All env variables used to hold\n# constants for this build are to\n# be found in that file...\n# This is an attempt to minimise\n# any sort of hardcoding........\n##################################\n\n# Change the version depending on the version that is passed as an argument\n# If the version is 500 change the version in the spec files and in the build_params_partner.conf file\nsed -e \"s/6.50.00.00/${maj_ver}.${min_ver}.00.00/g\" build_params_${PARTNER}.conf >> build_params_${PARTNER}.conf.new\nmv build_params_${PARTNER}.conf.new build_params_${PARTNER}.conf\n\n# Find the version from the spec file.\nversion=`cat templates/${PARTNER}.spec | grep \"^Version\" | cut -d\":\" -f2 | tr -d \" \"`\nrelease=`cat templates/${PARTNER}.spec | grep \"^Release\" | cut -d\":\" -f2 | tr -d \" \"`\nsed -e \"s/$version/${maj_ver}.${min_ver}/\" templates/${PARTNER}.spec >> templates/${PARTNER}.spec.new\nmv templates/${PARTNER}.spec.new templates/${PARTNER}.spec\n\nsed -e \"s/$release/${rel_num}/\" templates/${PARTNER}.spec >> templates/${PARTNER}.spec.new\nmv templates/${PARTNER}.spec.new templates/${PARTNER}.spec\n\n. ./build_params_${PARTNER}.conf\n\n##################################\n# Create the version file here\n##################################\n\nif [ -d $TOP_BLD_DIR/binaries/FX ]; then\n  echo \"VERSION=$FX_VERSION\" > $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"PROD_VERSION=$PATCH_VERSION\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"PARTNER=$PARTNER\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"INSTALLATION_DIR=RUNTIME_INSTALL_PATH\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  if [ `uname` = \"Linux\" ] && [ ! -e /etc/debian_version ] ; then\n  \techo \"RPM_PACKAGE=$BUILT_RPM_PACKAGE\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  \techo \"RPM_NAME=$BUILT_RPM_FILE\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  fi\n  echo \"VERSION_FILE_PARENT_DIR=$METADATA_REF_DIR\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"DEFAULT_UPGRADE_DIR=$DEFAULT_UPG_DIR\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"BUILD_TAG=$tagName\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n  echo \"OS_BUILT_FOR=$OS\" >> $TOP_BLD_DIR/binaries/FX/${VERSION_FILE_NAME}\n\nelse\n  exit 87\nfi\n\n######################################\n# Create the build manifest file here\n######################################\n\nif [ -d $TOP_BLD_DIR/binaries/FX ]; then\n  # 2. List of files\n  # Since CVS/Entries contains entries for files checked out, it's easy to copy its contents to this file without much ado\n  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\n  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\n  echo \"Following is the list of files used in this build:\" >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\n  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\n  echo >> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\n  find $TOP_BLD_DIR/source -type f -name \"Entries\" -exec cat {} \\; | grep -v CVS | grep -v \"^D\" \\\n\t>> $TOP_BLD_DIR/binaries/FX/${BUILD_MANIFEST_FILE_NAME}\nelse\n  exit 87\nfi\n\n\n######################################################################################\n# Version file should be changed to reflect correct release versions and partner names\n######################################################################################\n\nif [ -f $TOP_BLD_DIR/source/host/fr_common/version.h ]; then\n\tsed -n \"s/INMAGE_PRODUCT_VERSION_STR[ ]\\{1,\\}\\\".*\\\"/INMAGE_PRODUCT_VERSION_STR \\\"$tagName\\\"/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h > $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_PRODUCT_VERSION[ ]\\{1,\\}[0-9,]*/INMAGE_PRODUCT_VERSION $maj_ver,${min_ver}${rel_num},\\\n${dlybldNum},${bld_seq_num}/p\" $TOP_BLD_DIR/source/host/fr_common/version.h \\\n\t\t\t>> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_PRODUCT_VERSION_MAJOR[ ]\\{1,\\}[0-9]*/INMAGE_PRODUCT_VERSION_MAJOR $maj_ver/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_PRODUCT_VERSION_MINOR[ ]\\{1,\\}[0-9]*/INMAGE_PRODUCT_VERSION_MINOR ${min_ver}${rel_num}/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_PRODUCT_VERSION_BUILDNUM[ ]\\{1,\\}[0-9]*/INMAGE_PRODUCT_VERSION_BUILDNUM $dlybldNum/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_PRODUCT_VERSION_PRIVATE[ ]\\{1,\\}[0-9]*/INMAGE_PRODUCT_VERSION_PRIVATE $bld_seq_num/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/INMAGE_HOST_AGENT_CONFIG_CAPTION[ ]\\{1,\\}\\\".*\\\"/INMAGE_HOST_AGENT_CONFIG_CAPTION \\\"$tagName\\\"/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\tsed -n \"s/PROD_VERSION[ ]\\{1,\\}\\\".*\\\"/PROD_VERSION \\\"$PATCH_VERSION\\\"/p\" \\\n\t\t$TOP_BLD_DIR/source/host/fr_common/version.h >> $TOP_BLD_DIR/source/host/fr_common/version.h.new\n\n       \tmv $TOP_BLD_DIR/source/host/fr_common/version.h.new $TOP_BLD_DIR/source/host/fr_common/version.h\nfi\n\n######################################################################################\n# End of correcting version file\n######################################################################################\t\t\n", "num_lines": 159}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nif [ `uname` = 'SunOS' ]; then\n        # Export LD_LIBRARY_PATH\n\tLD_LIBRARY_PATH=RUNTIME_INSTALL_PATH/Pillar/lib\n        export LD_LIBRARY_PATH\nfi\n\nRUNTIME_INSTALL_PATH/Pillar/bin1/`basename $0` \"$@\"\n", "num_lines": 10}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nif [ `uname` = 'SunOS' ]; then\n        # Export LD_LIBRARY_PATH\n        LD_LIBRARY_PATH=RUNTIME_INSTALL_PATH/lib64:\n        export LD_LIBRARY_PATH\nfi\n\nif [ `uname` = 'AIX' ]; then\n        # Export LIBPATH\n        LIBPATH=SET_LIBPATH\n        export LIBPATH\nfi\n\n/usr/local/InMage/Fx/bin1/`basename $0` \"$@\"\n", "num_lines": 16}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\necho \"--------------------------------------------\"\necho `date`\n\n# Check whether installation directory is mounted or not. If it is not mounted wait for 60 secs.\n# Repeat the loop for 30 times and exit if installation directory is not mounted even after 30 mins.\n# If installation directory is mounted within 30 mins then invoke soft_removal.sh.\ni=\"1\"\nwhile [ $i -lt 31 ]\ndo\n        echo \"Iteration : $i\"\n        if [ -f RUNTIME_INSTALL_PATH/start ]; then\n                echo \"RUNTIME_INSTALL_PATH/start is available\"\n                sleep 15\n                echo \"Inovking RUNTIME_INSTALL_PATH/start\"\n                RUNTIME_INSTALL_PATH/start\n                break\n        else\n                if [ \"$i\" = \"30\" ]; then\n                        echo \"Installation directory is not mounted even after 30 minutes. Existing...\"\n                        exit\n                fi\n                echo \"Installation directory is not mounted. sleeping for 60 secs\"\n                sleep 60\n        fi\n        i=`expr $i + 1`\ndone\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#####################################################################################\n#Purpose: Used to apply custom configuration changes on CentOS/RHEL 6.6 Master Target\n######################################################################################\n\n\nDO()\n{    \n    eval \"$1 2>> $LOG_FILE | tee -a $LOG_FILE\"\n}\n\nDATE_TIME_SUFFIX=`date +%d_%b_%Y_%H:%M:%S`\nLOG_FILE=/var/log/appliedmtcustomchanges.log\n\n\necho -e \"\\t$DATE_TIME_SUFFIX\" >> $LOG_FILE\necho -e \"\\t####################\\n\" >> $LOG_FILE\n\nif [ -e /etc/.appliedmtcustomchanges ]; then\n    DO 'echo'\n    DO 'echo \"--------------------------------------------------------------------------------\"'\n    DO 'echo \"ApplyCustomChanges.sh script was already invoked. Please re-try the installation\"'\n    DO 'echo \"--------------------------------------------------------------------------------\"'\n    exit 0\nfi\n\nDO 'echo -e \"\\tCustom Configuration\\n\"'\nDO 'echo -e \"\\t####################\\n\"'\n\nDO 'echo \"WARNING: This script is intended to be executed only on Master Target servers. \"'\nDO 'echo \"         If this server is not a Master Target, please do not continue. \"'\nDO 'echo'\nwhile [ \"X$Choice\" = \"X\" ]\ndo\n    DO 'echo -n \"Are you sure you want to continue? [Y|N] [default N] : \"'\n    read Choice\n    if [ -z \"$Choice\" -o \"$Choice\" = \"N\" -o \"$Choice\" = \"n\" ]; then\n        Choice=\"N\" ; exit 1\n    elif [ \"$Choice\" = \"Y\" -o \"$Choice\" = \"y\" ];then\n        Choice=\"Y\" \n    else\n        Choice=\"\"\n        DO 'echo -e \"Invalid answer. Please retry.\\n\"'\n    fi\ndone\n\n# Make sure only root can run our script\nDO 'echo -n \"Checking for root privileges ... \"'\n[[ $EUID -ne 0 ]] && DO 'echo \"FAILED\"' && DO 'echo \"This script must be run as root\"' && exit 1\nDO 'echo \"OK\"'\n\n# Make sure OS is RedHat/CentOS 6.6(64bit)\nDO 'echo -n \"Checking for Ubuntu 16.04(64bit) or Ubuntu 20.04(64bit) ... \"'\nif egrep -q 'DISTRIB_RELEASE=16.04|DISTRIB_RELEASE=20.04' /etc/lsb-release ; then\n\tif uname -a | grep -q x86_64; then\n\t\tOSCheck=0\n\telse\n        OSCheck=1\n    fi\nelse\n    OSCheck=1\nfi\n\n\nif [ $OSCheck -ne 0 ]; then\n   DO 'echo \"FAILED\"' && exit 1\nelse\n   DO 'echo \"OK\"'\nfi\n\n\n# Make sure required packages are available.\nDO 'echo -n \"Checking for required software packages ... \"'\nREQ_PKG_LIST=\"apt multipath-tools lsscsi kpartx python-pyasn1 lvm2\"\nif grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then\n    REQ_PKG_LIST=\"$REQ_PKG_LIST linux-image-generic-hwe-16.04\"\nfi\n\nrm -f /var/log/missing-packages.log /dev/null 2>&1\nfor pkgName in `echo $REQ_PKG_LIST`\ndo\n    if dpkg -l |grep $pkgName > /dev/null 2>&1 ; then\n       PKG_MISSING=0\n    else\n        PKG_MISSING=1\n        echo \"package $pkgName is not installed.\" >>/var/log/missing-packages.log\n    fi\ndone\n[[ $PKG_MISSING -ne 0 ]] && DO 'echo \"FAILED\"' || DO 'echo \"OK\"'\nif [ -s /var/log/missing-packages.log ]; then\n    DO 'echo'\n    DO 'cat /var/log/missing-packages.log'\n\tDO 'echo \"Command to install package: apt-get install package-name\"'\n    DO 'echo \"Please install missing packages and re-try. Aborting...\"'\n    exit 1\nfi\n\n# Set core file size to unlimited\nDO 'echo -n \"Set core file size to unlimited ... \"'\nsed -i -e '/ulimit -c unlimited/d' /etc/bash.bashrc\necho \"ulimit -c unlimited\" >> /etc/bash.bashrc\n[[ $? -ne 0 ]] && DO 'echo \"FAILED\"'|| DO 'echo \"OK\"'\n\n\n# multipath.conf file creation\nDO 'echo -n \"Creating multipath.conf file ... \"'\ncat > /etc/multipath.conf << EOF\ndefaults {\n        user_friendly_names no\n\t\tfind_multipaths no\n}\n\nblacklist {\n#For AT Lun masking\n        device {\n                vendor  \"InMage\"\n        }\ndevnode \"^cciss!c[0-9]d[0-9]*\"\n}\nEOF\n[[ $? -ne 0 ]] && DO 'echo \"FAILED\"'|| DO 'echo \"OK\"'\n\n# Creating default multipath.conf file\nDO 'echo -n \"Configuring multipath to blacklist cciss disk ... \"'\nsed -i -e '/^blacklist[[:space:]]*{/ a devnode \"^cciss!c[0-9]d[0-9]*\"' /etc/multipath.conf\n[[ $? -ne 0 ]] && DO 'echo \"FAILED\"' || DO 'echo \"OK\"'\n\n# Black listing root device and enabled multipath\nDO 'echo -n \"Blacklist root disk and enable multipath... \"'\nBootDevice=`mount | grep \"on / \" | awk '{print $1}'`\nBootDevice=`echo ${BootDevice} | sed -e \"s:[sp]*[0-9]*$::\"`\nWWID=`/lib/udev/scsi_id --whitelisted --device=$BootDevice`\ncat > /usr/sbin/blacklistrootdev.sh << EOF\n[[ -n \"$WWID\" ]] && sed -i -e \"/^blacklist.*{/ a wwid $WWID\" /etc/multipath.conf || exit 1\nif [ -f /.blacklistrootdev ] ; then\n    sed -i \"/^wwid/d\" /etc/multipath.conf ; sed -i -e \"/^blacklist.*{/ a wwid $WWID\" /etc/multipath.conf\nfi\nEOF\nchmod 755 /usr/sbin/blacklistrootdev.sh\n[[ -f /etc/multipath.conf ]] && /usr/sbin/blacklistrootdev.sh > /var/log/blacklistrootdev.log 2>&1\ntouch /.blacklistrootdev > /dev/null 2>&1\n[[ $? -ne 0 ]] && DO 'echo \"FAILED\"' || DO 'echo \"OK\"'\n\n# Creating dummy file to restrict multiple execution\ntouch /etc/.appliedmtcustomchanges >/dev/null 2>&1\n\nDO 'echo -e \"*** NOTE: REBOOT IS REQUIRED FOR CUSTOM CHANGES TO TAKE EFFECT.***\\n\"'\nDO 'echo -e \"\\n\\t********** COMPLETED ************\"'\nDO 'echo -e \"\\t##################################\\n\"'\n\n", "num_lines": 151}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nBRANCHES=\"INT_BRANCH REL_BRANCH INTERIM_REL_BRANCH\"\nTODAY_DAY=`date +%b_%d_%Y`\n\n# Tag host modules for all applicable branches\necho > ./host_status\n\nfor BRANCH_NAME in $BRANCHES\ndo\n\tMODULES=\"admin build host server Solutions\"\n\tcase $BRANCH_NAME in\n        INT_BRANCH)\n                BRANCH_CODE=INT_BRANCH\n                QUALITY=DAILY\n                PHASE=DIT\n                ;;\n        REL_BRANCH)\n                BRANCH_CODE=REL_BRANCH\n                QUALITY=RELEASE\n                PHASE=GA\n                ;;\n        INTERIM_REL_BRANCH)\n                BRANCH_CODE=INTERIM_REL_BRANCH\n                QUALITY=RELEASE\n                PHASE=GA\n                ;;\n\tesac\n\n\t# Export the source CVSROOT\n\texport CVSROOT=:pserver:vegogine@10.150.24.11:/src\n\tTODAY_TAG=${QUALITY}_${BRANCH_CODE}_${PHASE}_${TODAY_DAY}\n\techo \"$BRANCH_NAME Today's Tag\t\t: ${TODAY_TAG}\"\n\n\techo \"Cmd: cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} ${MODULES}\"\n\tcvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} ${MODULES}\n\tif [ $? -eq 0 ]; then\n\t\techo \"Applied ${TODAY_TAG} successfully! ...\"\n                echo \"Source Tagging     : ${BRANCH_NAME} - ${TODAY_TAG} - Successful\" >> ./host_status\n\telse\n\t\techo \"Could not apply ${TODAY_TAG}. Tagging failed...\"\n\t\techo \"Source Tagging     : ${BRANCH_NAME} - ${TODAY_TAG} - Failed\" >> ./host_status\n\tfi\n\techo\n\techo\n\n\techo >> ./host_status\n\techo\n\techo\ndone\n\ngrep -q \"Failed\" ./host_status \nif [ $? -eq 0 ]; then\n\tRESULT=\"FAILED\"\nelse\n\tRESULT=\"SUCCESSFUL\"\nfi \n\n# Send mail to inmiet@microsoft.com about the host tagging status\nmail -s \"SOURCE TAGGING : ${RESULT}\" inmiet@microsoft.com <<DATA\n`cat -v ./host_status`\nDATA\n\n\n# Tag thirdparty modules for all applicable branches\necho > ./tp_status\n\nBRANCHES=\"INT_BRANCH REL_BRANCH INTERIM_REL_BRANCH\"\nTODAY_DAY=`date +%b_%d_%Y`\n\nfor BRANCH_NAME in $BRANCHES\ndo\n        case $BRANCH_NAME in\n        INT_BRANCH)\n                BRANCH_CODE=INT_BRANCH\n                QUALITY=DAILY\n                PHASE=DIT\n                ;;\n        REL_BRANCH)\n                BRANCH_CODE=REL_BRANCH\n                QUALITY=RELEASE\n                PHASE=GA\n                ;;\n        INTERIM_REL_BRANCH)\n                BRANCH_CODE=INTERIM_REL_BRANCH\n                QUALITY=RELEASE\n                PHASE=GA\n                ;;\n        esac\n\n        # Export the Thirpdarty CVSROOT\n        export CVSROOT=:pserver:vegogine@10.150.24.11:/thirdparty\n\n\tTODAY_TAG=${QUALITY}_${BRANCH_CODE}_${PHASE}_${TODAY_DAY}\n\techo \"$BRANCH_NAME Today's Tag\t\t: ${TODAY_TAG}\"\n\n        echo \"Cmd: cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} thirdparty\"\n        cvs rtag -F -r ${BRANCH_NAME} ${TODAY_TAG} thirdparty\n        if [ $? -eq 0 ]; then\n                echo \"Applied ${TODAY_TAG} successfully! ...\"\n                echo \"Thirdparty Tagging : ${BRANCH_NAME} - ${TODAY_TAG} - Successful\" >> ./tp_status\n        else\n                echo \"Could not apply ${TODAY_TAG}. Tagging failed...\"\n                echo \"Thirdparty Tagging : ${BRANCH_NAME} - ${TODAY_TAG} - Failed\" >> ./tp_status\n        fi\n\techo >> ./tp_status\n        echo\n        echo\ndone\n\ngrep -q \"Failed\" ./tp_status\nif [ $? -eq 0 ]; then\n        RESULT=\"FAILED\"\nelse\n        RESULT=\"SUCCESSFUL\"\nfi\n\n# Send mail to inmiet@microsoft.com about the thirdparty status\nmail -s \"THIRDPARTY TAGGING : ${RESULT}\" inmiet@microsoft.com <<DATA\n`cat -v ./tp_status`\nDATA\n", "num_lines": 122}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ -f /etc/oracle-release ]; then\n    if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release; then\n        VERSION=`sed \"s/[^0-9]*//g\" /etc/oracle-release`\n\t    if [ `uname -m` = \"x86_64\" -a $VERSION -ge 64 ]; then\n            OS=\"OL6-64\"\n        fi\n    elif grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"OL7-64\"\n        fi\n    elif grep -q 'Oracle Linux Server release 8.*' /etc/oracle-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"OL8-64\"\n        fi\n    fi\nelif [ -f /etc/redhat-release ]; then\n    if grep -q 'Red Hat Enterprise Linux Server release 5.*' /etc/redhat-release || \\\n        grep -q 'CentOS release 5.*' /etc/redhat-release; then\n\tVERSION=`sed \"s/[^0-9]*//g\" /etc/redhat-release`\n\tif [ `uname -m` = \"x86_64\" -a $VERSION -ge 52 -a $VERSION -le 511 ]; then\n            OS=\"RHEL5-64\"\n        fi\n    elif grep -q 'Red Hat Enterprise Linux Server release 6.*' /etc/redhat-release || \\\n        grep -q 'Red Hat Enterprise Linux Workstation release 6.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 6.*' /etc/redhat-release ||\n        grep -q 'CentOS release 6.*' /etc/redhat-release; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL6-64\"\n        fi\n    elif grep -q 'Red Hat Enterprise Linux Server release 7.*' /etc/redhat-release || \\\n        grep -q 'Red Hat Enterprise Linux Workstation release 7.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 7.*' /etc/redhat-release; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL7-64\"\n        fi\n    elif grep -q 'Red Hat Enterprise Linux release 8.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 8.*' /etc/redhat-release; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL8-64\"\n        fi\n    fi\nelif [ -f /etc/SuSE-release ]; then\n    if grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES11-SP3-64\"\n        fi\n    elif grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES11-SP4-64\"\n        fi\n    fi\n    if grep -q 'VERSION = 12' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES12-64\"\n        fi\n    elif grep -q 'VERSION=\"15' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES15-64\"\n        fi\n    fi\nelif [ -f /etc/os-release ] && grep -q 'SLES' /etc/os-release; then\n    if grep -q 'VERSION=\"15' /etc/os-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES15-64\"\n        fi\n    fi\nelif [ -f /etc/lsb-release ] ; then\n    if grep -q 'DISTRIB_RELEASE=14.04' /etc/lsb-release ; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-14.04-64\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-16.04-64\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=18.04' /etc/lsb-release ; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-18.04-64\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=20.04' /etc/lsb-release ; then\n\tif [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-20.04-64\"\n        fi\n    fi\nelif [ -f /etc/debian_version ]; then\n    if grep -q '^7.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN7-64\"\n        fi\n    elif grep -q '^8.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN8-64\"\n        fi\n    elif grep -q '^9.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN9-64\"\n        fi\n    elif grep -q '^10.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN10-64\"\n        fi\n    fi\nfi\n\nif [ $# -gt 0 ]\nthen\n    echo $OS\nfi\n", "num_lines": 111}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "##################\n# DEFAULT VALUES\n##################\n\nDATE=`date '+%d%h%Y'`\nCALLING_SCRIPT=\"$1\"\nMAIL_ID=\"dl-build-engineering@inmage.net\"\nWRK_DIR=`pwd`\n\n##############\n# VALIDATIONS\n##############\n\nGDB=`which gdb`\n\nif [ -z \"$CALLING_SCRIPT\" ] || [ -z \"$OS\" ] || [ -z \"$GDB\" ]; then\n\techo\n        echo \"Either all the arguments are not defined or GDB is not installed in the setup ...\"\n\techo \"Cannot proceed with the symbol checking ...\"\n\techo\n        exit 1\nfi\n\n###########################\n# Start the sendmail\n###########################\n\ncase $OS in\n\tSLES*|OPENSUSE*)\n\t\tPS=`pgrep -f /usr/lib/postfix/master`\n\t\tif [ -z \"$PS\" ] ; then\n\t\t\t/etc/init.d/postfix start\n\t\tfi\n\t;;\n\t*)\n\t\tPS=`pgrep sendmail`\n\t\tif [ -z \"$PS\" ] ; then\n\t\t\t/etc/init.d/sendmail start\n\t\tfi\n\t;;\nesac\n\n#################################\n# Find the machine Architecture\n#################################\n\ncase `uname -m` in\n        i586|i686)\n                ARCH=Linux_i686\n        ;;\n         x86_64)\n                ARCH=Linux_x86_64\n\t;;\nesac\n\n########################\n# Cleaning the gdb log\n########################\n\nClean_Up()\n{\n  BUILD_TYPE=$1\n\n  if [ -f ${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log ]; then\n  \trm -f ${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log\n  fi\n}\n\n###############################\n# Check if the symbol tar or \n# the build exists or not\n###############################\n\nPre_Check()\n{\n  if [ -z \"$SYMBOL_TAR_FILE\" ] || [ -z \"$BUILD_TAR_FILE\" ]; then\n\techo\n\techo \"Either the symbol file or the build tar is missing ...\"\n\techo \"Cannot proceed with the symbol verification . Aborting ...\"\n\texit 1\n  fi\n}\n\n########################################\n# Execute the GDB here\n# Check if the gdb is matching \n# with the corresponding binary or not \n########################################\n\nFUNC_GDB_TEST()\n{\n  BINARY_FILE=$1\n  GDB_FILE=$2\n  BUILD_TYPE=$3\n  NO_SYMS_FOUND=\"\"\n  if [ `uname -s` = \"SunOS\" ] ;then\n\tGREP='/usr/xpg4/bin/grep'\n  else\n\tGREP=`which grep`\n  fi\n\n  gdb ${BINARY_FILE} --symbols=${GDB_FILE} >gdb.log<<DATA\nq\nDATA\n\n  if $GREP -q 'no debugging symbols found' gdb.log  ; then\n  \tNO_SYMS_FOUND=\"$NO_SYMS_FOUND $file\"\n  fi\n\n  echo \"gdb ${BINARY_FILE} --symbols=${GDB_FILE}\" >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log\n  cat gdb.log >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log\n  echo >>${BIN_DIR}/GDB_${BUILD_TYPE}_${OS}.log\n\n  if [ -n \"$NO_SYMS_FOUND\" ] ; then\n  \tmail -s \"SYMBOL VERIFICATION : Symbol Verification on $OS for ${BINARY_FILE} --- FAILED\" $MAIL_ID <<EOF\nEOF\n  fi\n}\n\n###############################\n# Verifying the symbols for FX\n###############################\n\nFUNC_SYM_FX()\n{\n  BUILD_TYPE=FX\n\n  Clean_Up $BUILD_TYPE\n\n  if [ \"${OS}\" = \"RHEL6-64\" ]; then\n      OS=\"RHEL6U2-64\"\n  fi\n\n  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}*symbols.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_${MAJOR_VERSION}.${MINOR_VERSION}*release.tar.gz`\n\n  Pre_Check\n\n  tar --wildcards -xzvf ${BUILD_TAR_FILE} \"InMageFx-*\"\n  FX_TAR_NAME=`ls -1 InMageFx-*`\n\n  rpm2cpio \"$FX_TAR_NAME\" | cpio -ivd\n  cd $SYM_DIR/InMage/Fx\n\n  tar -xzvf ${SYMBOL_TAR_FILE}\n  CUR_DIR=`pwd`\n\n  for symfile in `find . -name \"*.dbg\"`\n  do\n\tDBG_DIR=`dirname $symfile`\n\tcd $DBG_DIR\n\tbinfile=`basename $symfile`\n\tbinfile=`ls $binfile | awk -F'.' '{ print $1 }'`\n\n        cp $SYM_DIR/InMage/Fx/$binfile .\n        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n        cd $CUR_DIR\t\n  done\n}\n\n##########################################\n# Check for Solaris VX Symbols\n# This includes Pushinstall client also  \n##########################################\n\nFUNC_SYM_VX()\n{\n  BUILD_TYPE=VX\n\n  Clean_Up $BUILD_TYPE\n\n  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_VX_*symbols.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_VX_*release.tar.gz`\n\n  Pre_Check\n\n  cp $SYMBOL_TAR_FILE $BUILD_TAR_FILE .\n  gunzip *.tar.gz\n \t\n  SYMBOL_TAR_FILE=`ls -1 InMage_VX_*${OS}*symbols.tar`\n  BUILD_TAR_FILE=`ls -1 InMage_VX_*release.tar`\n\n  mkdir -p $SYM_DIR/InMage/Vx\n  cd $SYM_DIR/InMage/Vx\n\n  tar -xvf  ${SYM_DIR}/$BUILD_TAR_FILE \n  tar -xvf  InMage_VX_*.tar bin1\n  cd bin1\n\n  tar -xvf ${SYM_DIR}/${SYMBOL_TAR_FILE}\n  CUR_DIR=`pwd`\n\n  for symfile in `find $CUR_DIR -name \"*.dbg\"`\n   do\n\tDBG_DIR=`dirname $symfile`\n\tbinfile=`basename $symfile`\n\tbinfile=`ls $binfile | awk -F'.' '{ print $1 }'`\n\tcd $DBG_DIR\n\n\tif [ \"$binfile\" = \"pushinstallclient\" ]; then\n\t\tcp /BUILDS/SCRIPTS/head_daily_builds/release/pushinstallclient .\n\t\tFUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n\t\tcd $CUR_DIR\n\t\tcontinue\n\tfi\n\n\tcp $SYM_DIR/InMage/Vx/bin1/$binfile .\n\tFUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE \n\tcd $CUR_DIR \n\tcontinue\n  done\n}\n\n\n##########################################\n# Check for Solaris FX Symbols only\n##########################################\n\nFUNC_Unix_SYM_FX()\n{\n  BUILD_TYPE=FX\n\n  Clean_Up $BUILD_TYPE\n\n  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_*symbols.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_FX_*release.tar.gz`\n\n  Pre_Check\n\n  cp $SYMBOL_TAR_FILE $BUILD_TAR_FILE .\n  gunzip *.tar.gz\n\n  SYMBOL_TAR_FILE=`ls -1 InMage_FX_*${OS}*symbols.tar`\n  BUILD_TAR_FILE=`ls -1 InMage_FX_*release.tar`\n\n  mkdir -p $SYM_DIR/InMage/Fx\n  cd $SYM_DIR/InMage/Fx\n\n  tar -xvf  ${SYM_DIR}/$BUILD_TAR_FILE\n  tar -xvf  InMage_FX_*.tar \n\n  tar -xvf ${SYM_DIR}/${SYMBOL_TAR_FILE}\n  CUR_DIR=`pwd`\n\n  for symfile in `find $CUR_DIR -name \"*.dbg\"`\n   do\n        DBG_DIR=`dirname $symfile`\n        binfile=`basename $symfile`\n        binfile=`ls $binfile | awk -F'.' '{ print $1 }'`\n        cd $DBG_DIR\n\n        cp $SYM_DIR/InMage/Fx/$binfile .\n        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n        cd $CUR_DIR\n        continue\n  done\n}\n\n##########################################\n# Do not keep quotes in DEBIAN or UBUNTU\n# While extracting the FX or VX tars\n##########################################\n\nFUNC_SYM_UA()\n{\n  BUILD_TYPE=UA\n\n  Clean_Up $BUILD_TYPE\n\n  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}*symbols.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1 $BIN_DIR/InMage_UA_${MAJOR_VERSION}.${MINOR_VERSION}*release.tar.gz`\n\n  Pre_Check\n\n  case $OS in\n        DEBIAN*|UBUNTU*)\n                mkdir -p InMage/Fx InMage/Vx\n\n                cd $SYM_DIR/InMage/Fx\n\n                tar --wildcards -xzvf $BUILD_TAR_FILE \"InMage_FX_*.tar\"\n                tar --wildcards -xvf InMage_FX_*.tar\n\n                cd $SYM_DIR/InMage/Vx\n\n                tar --wildcards -xzvf $BUILD_TAR_FILE \"InMage_VX_*.tar\"\n                tar --wildcards -xvf InMage_VX_*.tar\n\n                tar -xzvf ${SYMBOL_TAR_FILE}\n                LIST=`find -name *.dbg | egrep  '(storagefailover|unlockVolumes|sendquit|pushinstalld)'`\n\n                rm $LIST\n\n        ;;\n              *)\n                tar --wildcards -xzvf ${BUILD_TAR_FILE} 'InMageVx-*'\n\n                VX_TAR_NAME=`ls -1 InMageVx-*`\n                rpm2cpio \"$VX_TAR_NAME\" | cpio -ivd\n\n                tar --wildcards -xzvf ${BUILD_TAR_FILE} 'InMageFx-*'\n\n                FX_TAR_NAME=`ls -1 InMageFx-*`\n                rpm2cpio \"$FX_TAR_NAME\" | cpio -ivd\n\n                cd $SYM_DIR/InMage/Vx/bin\n\n                tar -xzvf ${SYMBOL_TAR_FILE}\n        ;;\n  esac\n  CUR_DIR=`pwd`\n\n  for symfile in `find . -name *.dbg`\n  do\n        DBG_DIR=`dirname $symfile`\n        cd $DBG_DIR\n        binfile=`ls | awk -F'.' '{ print $1 }'`\n\n\tif [ \"$binfile\" = \"pushinstallclient\" ]; then\n\t\tcd $CUR_DIR\n\t\tcontinue\n\tfi\n\n\tif [ \"$binfile\" = \"fabricagent\" ] ; then\n\t \tcase $OS in\n\t  \t\tRHEL5U1-64)\n\t\t\t\tcp $SYM_DIR/InMage/Vx/bin/$binfile .\n\t\t\t\tFUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE \n                \t\tcd $CUR_DIR \n                \t\tcontinue\n\t   \t\t;;\n\t\t\t*)\n\t\t\t\tcd $CUR_DIR \n                \t\tcontinue\n\t \tesac\n\tfi\n\n\tif [ -f $SYM_DIR/InMage/Vx/bin/$binfile ] ; then\n\t        cp $SYM_DIR/InMage/Vx/bin/$binfile .\n\telif [ -f $SYM_DIR/InMage/Fx/$binfile ] ; then\n\t\tcp $SYM_DIR/InMage/Fx/$binfile .\n\telif [ -f $SYM_DIR/InMage/Fx/transport/$binfile ] ; then\n\t\tcp $SYM_DIR/InMage/Fx/transport/$binfile .\n\telse\n\t \tmail -s \"The corresponding binary $binfile is not found for $OS.\" $MAIL_ID <<EOF\nEOF\n\tfi\n\n\tFUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n\tcd $CUR_DIR\ndone\n}\n\n###############################\n# Verifying the symbols for CX\n###############################\n\nFUNC_SYM_CX()\n{\n  BUILD_TYPE=CX\n\n  Clean_Up $BUILD_TYPE\n\n  if [ \"${OS}\" = \"RHEL6-64\" ]; then\n      OS=\"RHEL6U2-64\"\n  fi\n\n  SYMBOL_TAR_FILE=`ls -1tr $BIN_DIR/SYMBOLS/InMage_Scout_CX_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}_*_${verDate}${verMonth}${verYear}_release_symbol.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1tr $BIN_DIR/InMage_Scout_CX_${MAJOR_VERSION}.${MINOR_VERSION}*_${OS}_*_${verDate}${verMonth}${verYear}.tar.gz`\n\n  Pre_Check\n\n  tar --wildcards -xzvf ${BUILD_TAR_FILE} Scout-CX-*/inmage*.rpm Scout-CX-*/pushinstalld Scout-CX-*/storagefailover\n  cd Scout-CX-*\n  tar -xzvf ${SYMBOL_TAR_FILE} \n\n  rpm2cpio inmagePS-* | cpio -ivd ./home/svsystems/bin/bwm ./home/svsystems/bin/diffdatasort ./home/svsystems/bin/inmtouch ./home/svsystems/bin/svdcheck\n  rpm2cpio inmageCS-* | cpio -ivd ./home/svsystems/bin/inmlicense ./home/svsystems/bin/scheduler\n\n  mv ./home/svsystems/bin/bwm ./home/svsystems/bin/diffdatasort ./home/svsystems/bin/inmtouch  ./home/svsystems/bin/svdcheck ./home/svsystems/bin/inmlicense ./home/svsystems/bin/scheduler .\n\n  for symfile in `ls -1 *.dbg`\n  do\n \tbinfile=`ls $symfile | awk -F'.' '{ print $1 }'`\n\tmkdir ${binfile}_dir\n\tmv $binfile ${binfile}.dbg ${binfile}_dir\n\tcd ${binfile}_dir\n        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n\tcd -\n  done\n}\n\n################################################\n# Verifying the symbols for Push Install Client\n# This will not be verified as part of the UA\n################################################\n\nFUNC_SYM_PUSH()\n{\n  BUILD_TYPE=PUSH\n\n  Clean_Up $BUILD_TYPE\n\n  SYMBOL_TAR_FILE=`ls -1 $BIN_DIR/SYMBOLS/InMage_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}*${OS}_*release_symbol.tar.gz`\n\n  BUILD_TAR_FILE=`ls -1 $BIN_DIR/${OS}_pushinstallclient.tar.gz`\n\n  Pre_Check\n\n  tar -xzvf $BUILD_TAR_FILE\n  tar -xzvf $SYMBOL_TAR_FILE\n\n  for symfile in `ls -1 *.dbg`\n  do\n        binfile=`ls $symfile | awk -F'.' '{ print $1 }'`\n        FUNC_GDB_TEST $binfile ${binfile}.dbg $BUILD_TYPE\n  done\n}\n\n###################\n# MAIN ENTRY POINT\n###################\n\n##################################\n# Find the Calling script and \n# Execute the gdb test accordingly\n#################################\n\ncase \"$CALLING_SCRIPT\" in\n\n\t*UA*.sh)\n\n\t\tcase $OS in\n                        SLES9-32|SLES9-64|RHEL3-32)\n                                BIN_DIR=/BUILDS/$BRANCH/BINARIES/UNIFIED\n\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n                                        rm -rf \"$BIN_DIR/SYM_CHK\"\n                                fi\n\n\t\t\t\tmkdir -p $BIN_DIR/SYM_CHK\n                                cd $BIN_DIR/SYM_CHK\n                                SYM_DIR=`pwd`\n                                FUNC_SYM_FX\n\n\t\t\t\t#Clean up for Linux FX builds after use\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\tcd $WRK_DIR\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\n                                BIN_DIR=\"/BUILDS/$BRANCH/BINARIES/PUSH\"\n\n                                if [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n                                                 rm -rf \"$BIN_DIR/SYM_CHK\"\n                                fi\n\n                                mkdir -p $BIN_DIR/SYM_CHK\n                                cd $BIN_DIR/SYM_CHK\n                                FUNC_SYM_PUSH\n\n\t\t\t\t#Clean up for Linux push builds after use\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\tcd $WRK_DIR\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\t\t\t\t\n\t\t\t;;\n\t\t\t*Solaris*)\n\t\t\t\t# For VX and Push\n\t\t\t\tBIN_DIR=\"/BUILDS/$BRANCH/BINARIES/UNIFIED\"\n\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\t\t\t\tmkdir -p $BIN_DIR/SYM_CHK\n\n\t\t\t\tcd $BIN_DIR/SYM_CHK\n\t\t\t\tSYM_DIR=`pwd`\n\t\t\t\tFUNC_Unix_SYM_FX\n\t\t\t\tcd $BIN_DIR/SYM_CHK\n\t\t\t\tFUNC_SYM_VX\n\t\t\t\t#Clean up for Solaris platforms after use\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\tcd $WRK_DIR\n                                \trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\t\t\t;;\n\t\t\t*)\n\t\t\t\tBIN_DIR=\"/BUILDS/$BRANCH/BINARIES/UNIFIED\"\n\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\n\t\t\t\tmkdir -p $BIN_DIR/SYM_CHK\n\t\t\t\tcd $BIN_DIR/SYM_CHK\n\t\t\t\tSYM_DIR=`pwd`\n                                FUNC_SYM_UA\n\n\t\t\t\t#Clean up for Linux UA builds after us\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\tcd $WRK_DIR\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\n\t\t\t\tBIN_DIR=\"/BUILDS/$BRANCH/BINARIES/PUSH\"\n\n                                if [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\t cd $WRK_DIR\n                                         rm -rf \"$BIN_DIR/SYM_CHK\"\n                                fi\n\n                                mkdir -p $BIN_DIR/SYM_CHK\n                                cd $BIN_DIR/SYM_CHK\n\t\t\t\tFUNC_SYM_PUSH\n\n\t\t\t\t#Clean up for Linux push builds after use\n\t\t\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\t\t\tcd $WRK_DIR\n\t\t\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\t\t\tfi\n\n                esac\n\t;;\n\t*CX*.sh)\n\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n                        rm -rf \"$BIN_DIR/SYM_CHK\"\n                fi\n\n\t\tmkdir -p $BIN_DIR/SYM_CHK\n\t\tcd $BIN_DIR/SYM_CHK\n\t\tFUNC_SYM_CX\t\t\t\n\n\t\t#Clean up for Linux CX builds after use\n\t\tif [ -d \"$BIN_DIR/SYM_CHK\" ] ; then\n\t\t\tcd $WRK_DIR\n\t\t\trm -rf \"$BIN_DIR/SYM_CHK\"\n\t\tfi\n\t;;\n\n\t*)\n\t\techo\n\t\techo \"Either the build type is unknown or there is no symbol support for this type of build\"\n\t\techo\n\t\texit 1\n\t;;\t\nesac\n", "num_lines": 554}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "####################\n# DEFAULT VARIABLES\n####################\n\nTOP_BLD_DIR=${1:?\"Enter the path to the TOP BUILD directory!\"}\nPARTNER=${2:-inmage}\nGIT_BRANCH=${3:-develop}\nGIT_TAG=${4:-develop}\nBUILD_QUALITY=${5:-RELEASE}\nBUILD_PHASE=${6:-GA}\nMAJOR_VERSION=${7:-9}\nMINOR_VERSION=${8:-50}\nPATCH_SET_VERSION=${9:-0}\nshift\nPATCH_VERSION=${9:-0}\nshift\nAGENT_TYPE=${9:-both}\nshift\nCONFIGURATION=${9:-both}\nshift\nFTP_BUILD=${9:-no}\nshift\nTIER_NUMBER=${9:-tier1}\n\nBINARIES_PATH_FOR_UA=/BUILDS/${GIT_BRANCH}/BINARIES/UNIFIED\n\nX_ARCH=`uname -ms | sed \"s/ /_/g\"`\n\nif [ \"$FTP_BUILD\" = \"yes\" ]; then\n    FTP_PATH=\"/DailyBuilds/Daily_Builds/${MAJOR_VERSION}.${MINOR_VERSION}\"\nfi\n\nCWD=`pwd`\nMAIL_ID=\"inmiet@microsoft.com\"\ndate_suffix=`date +%e_%b_%Y | awk '{print $1}'`\nSCP_SERVER=\"10.150.24.13\"\n\nBefore_Build_Tasks()\n{\n\tif [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source ]; then\n\t\trm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build\n\t\tmkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source\n\tfi\n\n\tcd ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/\n\n\t# Update repo if it exists already, otherwise clone it.\n\tif [ -d InMage-Azure-SiteRecovery ]; then\n                echo \"InMage-Azure-SiteRecovery repo already exists.\"\n\t\tcd InMage-Azure-SiteRecovery\n        \t# Checkout code from appropriate branch, update code and remove any local files.\n\t        git checkout ${GIT_BRANCH} && git fetch origin && git reset --hard origin/${GIT_BRANCH} && git clean -xdf\n       \t\tif [ $? -eq 0 ]; then\n\t\t\techo \"Successfully checked out code from ${GIT_BRANCH} and removed local files.\"\n        \telse\n\t\t\techo \"Failed to check out code from ${GIT_BRANCH} and remove local files.\"\n                \texit 1\n        \tfi\n\telse\n                echo \"InMage-Azure-SiteRecovery repo does not exist.\"\n\t\tgit clone -b ${GIT_BRANCH} --single-branch msazure@vs-ssh.visualstudio.com:v3/msazure/One/InMage-Azure-SiteRecovery\n        \tif [ $? -eq 0 ]; then\n                \techo \"Successfully cloned InMage-Azure-SiteRecovery git repo and branch ${GIT_BRANCH}.\"\n                \tcd InMage-Azure-SiteRecovery\n        \telse\n                \techo \"Failed to clone InMage-Azure-SiteRecovery git repo and branch ${GIT_BRANCH}.\"\n                \texit 1\n        \tfi\n\tfi\n\n\t. ./build/scripts/general/OS_details.sh\n\n\tif [ \"$CONFIGURATION\" = \"both\" ]; then\n\t\tCONFIGURATION='release debug'\n\tfi\n\n\tchmod -R +x build/scripts/unifiedagent\n\tcd build/scripts/unifiedagent\n\n\tCLEAN_REPO=\"no\"\n\t./checkout.sh ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build $GIT_TAG $CLEAN_REPO\n\tif [ $? -ne 0 ]; then\n\t\techo \"Failed to setup InMage-Azure-SiteRecovery git repo.\"\n\t\texit 1\n\tfi\n\n\tBuild_Dir=`echo ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build | sed -e \"s/\\///g\"`\n\n\tif [ -e build_status_${Build_Dir} ]; then\n\t\trm -f build_status_${Build_Dir}\n\tfi\n\ttouch build_status_${Build_Dir}\n\techo \"checkout\" >> build_status_${Build_Dir}\n\n\tmkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/\n}\n\n# Package Azure Recovery Utils\nPackage_AzureRecoveryTools()\n{\n    case $OS in\n        UBUNTU-16.04-64)\n            if [ \"${CONFIGURATION}\" = \"release\" ]; then            \n                CUR_DIR=`pwd`\n\n                rm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools\n\n                if [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools ] || [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS ]; then \n                    mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS\n                fi                \n\n                if  [ -e ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil ]; then\n                    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools\n                    cp ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/AzureRecoveryUtil/Scripts/linux/{*.sh,network,CentOS-Base.repo} ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools\n\t\t\t\t\tcp ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/thirdparty/setuptools-31.1.1/{*.py,*.zip} ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools\n                    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/AzureRecoveryUtil/release/AzureRecoveryUtil.dbg ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS\n                    \n                    cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS\t\n                    tar cvfz InMage_AzureRecoveryUtil_${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_SET_VERSION}.${PATCH_VERSION}_${OS}_${BUILD_PHASE}_`date +%d``date +%b``date +%Y`_release_symbol.tar.gz AzureRecoveryUtil.dbg\n                    cd ${CUR_DIR}\n               else\n                    echo \"AzureRecoveryUtil binary is not available.\"\n                    cd ${CUR_DIR}\n                    return 1                \n               fi\n          fi\n     ;;\n     esac\n}\n\n\nPackage_Push_Client()\n{\n    if [ \"${CONFIGURATION}\" = \"release\" ]; then\n        CUR_DIR=`pwd`\n\n        rm -rf ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH\n\n        if [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH ] || [ ! -d ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS ]; then\n            mkdir -p ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS\n        fi\n\n        if [ -e ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient ]; then\n            mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH\n            mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/pushInstallerCli/release/pushinstallclient.dbg ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS\n\n            cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH\n            tar cvfz ${OS}_pushinstallclient.tar.gz pushinstallclient\n            cp ${OS}_pushinstallclient.tar.gz ${OS}_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.tar.gz\n            cd ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS\t\n            tar cvfz InMage_pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.${PATCH_SET_VERSION}.${PATCH_VERSION}_${OS}_${BUILD_PHASE}_`date +%d``date +%b``date +%Y`_release_symbol.tar.gz pushinstallclient.dbg\n            cd ${CUR_DIR}\n        fi\n    fi\n}\n\nUA_Build()\n{\n    for CONFIGURATION in $CONFIGURATION\n    do\n        sh -x ./makefile_complete.sh -d ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build -T /BUILDS/${GIT_BRANCH}/SOURCE/thirdparty -b ${GIT_BRANCH} -B ${GIT_TAG} -p ${PARTNER} -c ${CONFIGURATION} -q ${BUILD_QUALITY} -P ${BUILD_PHASE} -M ${MAJOR_VERSION} -N ${MINOR_VERSION} -S ${PATCH_SET_VERSION} -V ${PATCH_VERSION} -A ${AGENT_TYPE} inmbuild > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA_${OS}_${CONFIGURATION}.log 2>&1\n\t\t\t\n        if [ \"${CONFIGURATION}\" = \"release\" ]; then\n            Package_Push_Client\n            Package_AzureRecoveryTools\n            After_Build_Tasks\n            Symbol_Check\n            if [ \"$FTP_BUILD\" = \"yes\" ]; then\n                Scp_Release \n            fi\n        fi\n\n        if [ \"${CONFIGURATION}\" = \"debug\" ]; then\n            After_Build_Tasks\n            if [ \"$FTP_BUILD\" = \"yes\" ]; then\n                Scp_Debug\n            fi\n        fi\n    done\n}\n\n#######################################################\n# FUNCTION : After_Build_Tasks\n# Copy the required binaries to \n# BINARIES path ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES\n#######################################################\n\nAfter_Build_Tasks()\n{\n    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/\n    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/FX/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/\n    mv ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/VX/*.tar.gz ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/\n\n    ls -1 ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*.tar.gz\n    if [ $? -ne 0 ]; then\n        HOSTNAME=`hostname`\n        mail -s \"UA BUILD FAILURE ON $OS WITH HOSTNAME $HOSTNAME FOR ${GIT_BRANCH} FOR ${CONFIGURATION} CONFIGURATION . PLEASE CHECK THE LOGS FOR COMPLETE RESULTS\" $MAIL_ID <<DATA\nDATA\n    fi\n\n    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/*.gz\n    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/FX/*\n    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/binaries/VX/*\n    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/logs/FX/*\n    rm -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/logs/VX/*\n\n    # Generate OS specific agent version file.\n    AGENT_VERSION=`grep -w INMAGE_PRODUCT_VERSION ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/common/version.h | tr ',' '.' | cut -d\" \" -f3 | tr -d \"\\n\"`\n    echo -n ${AGENT_VERSION} > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion_${AGENT_VERSION}_${OS}.txt\n\n    # Copy supported_kernels file if it has some content.\n    if [ -s ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/supported_kernels ] ; then\n        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt\n    elif [ -s ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels ] ; then \n        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt\n    fi\n\n    # Copy AgentVersion.txt and copy OS_details.sh which will be used by A2A extenstion. Also, copy supported_kernels file.\n    if [ \"$OS\" = \"SLES12-64\" ]; then\n        echo -n ${AGENT_VERSION} > ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion.txt\n        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/build/scripts/general/OS_details.sh ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/\n        cp -f ${TOP_BLD_DIR}/${GIT_BRANCH}/daily_unified_build/source/InMage-Azure-SiteRecovery/host/drivers/InVolFlt/linux/sles_drivers/supported_kernels /BUILDS/${GIT_TAG}/BINARIES/UNIFIED/${OS}_supported_kernels.txt\n    fi\n\n}\n\n#############################################\n# FUNCTIONS : Scp_Release Scp_Debug\n# Used for copying the UA builds to 10.150.24.13\n#############################################\nScp_Debug()\n{\n    # debug builds are not used in ASR\n    return 0\n}\n\nMakeDir_Remote()\n{\n    remotedirpath=$1\n    # retry the remote command for 5 mins\n    starttime=`date +%s`\n    while :\n    do\n        ssh $SCP_SERVER \"mkdir -p $remotedirpath\"\n        if [ $? -eq 0 ]; then\n            break\n        fi\n\n\n        currtime=`date +%s`\n        elapsed=`expr $currtime - $starttime`\n        if [ $elapsed -gt 300 ]; then\n            echo \"Retries of mkdir failed\"\n            return 1\n        fi\n\n        sleep 5\n        echo \"retrying mkdir command\"\n    done\n}\n\nCopy_To_Remote()\n{\n    localfilespath=$1\n    remotedirpath=$2\n\n    for localfilepath in `ls $localfilespath`\n    do\n        # retry the remote command for 5 mins\n        starttime=`date +%s`\n        while :\n        do\n            scp $localfilepath $SCP_SERVER:$remotedirpath\n            if [ $? -eq 0 ]; then\n                break\n            fi\n\n            currtime=`date +%s`\n            elapsed=`expr $currtime - $starttime`\n            if [ $elapsed -gt 300 ]; then\n                echo \"Retries of scp failed\"\n                return 1\n            fi\n\n            sleep 5\n            echo \"retrying scp command\"\n        done\n    done\n}\n\n\n\nScp_Release()\n{\n    DATE_FOLDER=`date +%d_%b_%Y | awk '{print $1}'`\n\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/symbol_tars\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/supported_kernels\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/agent_versions\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/symbol_tars\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClientsRcm\"\n    MakeDir_Remote \"${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/Symbols\"\n\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*release.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*UA*release_symbols.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/symbol_tars/\n\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/OS_details.sh ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/\n\n    #Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/GDB*.log ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA*release.log ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/AgentVersion_*.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/agent_versions/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/*supported_kernels.txt ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/supported_kernels/\n\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/*pushinstallclient.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/SYMBOLS/*.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClients/symbol_tars/\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/PUSH/*pushinstallclient_${MAJOR_VERSION}.${MINOR_VERSION}.tar.gz ${FTP_PATH}/HOST/${DATE_FOLDER}/PushInstallClientsRcm/\n\n    if [ \"$OS\" = \"UBUNTU-16.04-64\" ]; then\n        Copy_To_Remote \"${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/*.sh\" ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/\n        Copy_To_Remote \"${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/*.py\" ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/\n        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/CentOS-Base.repo ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/\n        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/network ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/\n        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/AzureRecoveryUtil ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/\n        Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/AzureRecoveryTools/SYMBOLS/*.tar.gz  ${FTP_PATH}/HOST/${DATE_FOLDER}/release/AzureRecoveryTools/Symbols/\n    fi\n\n    Copy_To_Remote ${TOP_BLD_DIR}/${GIT_BRANCH}/BINARIES/UNIFIED/UA_WRAPPER_log  ${FTP_PATH}/HOST/${DATE_FOLDER}/UnifiedAgent_Builds/release/logs/UA_${OS}_WRAPPER.log\n}\n\n#####################################\n# FUNCTION : Symbol_Check\n# Executing the Symbol check for all\n# the linux platforms\n#####################################\n\nSymbol_Check()\n{\n  cd $CWD\n  # cvs co -r $GIT_TAG build/scripts/general/SYMBOL_CHECK.sh\n  export TOP_BLD_DIR PARTNER GIT_BRANCH GIT_TAG BUILD_QUALITY BUILD_PHASE MAJOR_VERSION MINOR_VERSION AGENT_TYPE OS\n  BRANCH=$GIT_TAG\n  export BRANCH\n  if [ -d InMage-Azure-SiteRecovery ]; then\n      sh -x InMage-Azure-SiteRecovery/build/scripts/general/SYMBOL_CHECK.sh \"$0\"\n  else\n      sh -x build/scripts/general/SYMBOL_CHECK.sh \"$0\"\n  fi\n}\n\n#####################\n# MAIN ENTRY POINT\n#####################\n\nrm -f ${BINARIES_PATH_FOR_UA}/*.tar.gz ${BINARIES_PATH_FOR_UA}/*.log ${BINARIES_PATH_FOR_UA}/*.txt\n\nBefore_Build_Tasks\n\nUA_Build\n", "num_lines": 361}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ -f /etc/oracle-release ]; then\n    if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"OL6-64: `cat /etc/oracle-release`: 0\"\n        fi\n    elif grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"OL7-64: `cat /etc/oracle-release`: 0\"\n        fi\n    elif grep -q 'Oracle Linux Server release 8.*' /etc/oracle-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"OL8-64: `cat /etc/oracle-release`: 0\"\n        fi\n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: `cat /etc/oracle-release` `uname -m`: 1\"\n    fi\nelif [ -f /etc/redhat-release ]; then\n    if grep -q 'Red Hat Enterprise Linux Server release 5.*' /etc/redhat-release || \\\n        grep -q 'CentOS release 5.*' /etc/redhat-release; then\n        VERSION=`sed \"s/[^0-9]*//g\" /etc/redhat-release`\n        if [ `uname -m` = \"x86_64\" -a $VERSION -ge 52 -a $VERSION -le 511 ]; then\n            OS=\"RHEL5-64: `cat /etc/redhat-release`: 0\"\n        fi\n    elif grep -q 'Red Hat Enterprise Linux Server release 6.*' /etc/redhat-release || \\\n        grep -q 'Red Hat Enterprise Linux Workstation release 6.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 6.*' /etc/redhat-release ||\n        grep -q 'CentOS release 6.*' /etc/redhat-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL6-64: `cat /etc/redhat-release`: 0\"\n        fi\n    elif grep -q 'Red Hat Enterprise Linux Server release 7.*' /etc/redhat-release || \\\n        grep -q 'Red Hat Enterprise Linux Workstation release 7.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 7.*' /etc/redhat-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL7-64: `cat /etc/redhat-release`: 0\"\n        fi                \n    elif grep -q 'Red Hat Enterprise Linux release 8.*' /etc/redhat-release || \\\n        grep -q 'CentOS Linux release 8.*' /etc/redhat-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"RHEL8-64: `cat /etc/redhat-release`: 0\"\n        fi                \n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: `cat /etc/redhat-release` `uname -m`: 1\"\n    fi\nelif [ -f /etc/SuSE-release ]; then\n    if grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES11-SP3-64: `cat /etc/SuSE-release`: 0\"\n        fi\n    elif grep -q 'VERSION = 11' /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES11-SP4-64: `cat /etc/SuSE-release`: 0\"\n        fi\n    fi\n    if grep -q 'VERSION = 12' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES12-64: `cat /etc/SuSE-release`: 0\"\n        fi\n    elif grep -q 'VERSION=\"15' /etc/SuSE-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES15-64: `cat /etc/SuSE-release | grep PRETTY | cut -d '\"' -f 2`: 0\"\n        fi\n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: `cat /etc/SuSE-release` `uname -m`: 1\"\n    fi\nelif [ -f /etc/os-release ] && grep -q 'SLES' /etc/os-release; then\n    if grep -q 'VERSION=\"15' /etc/os-release; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"SLES15-64: `cat /etc/os-release | grep PRETTY | cut -d '\"' -f 2`: 0\"\n        fi\n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: `cat /etc/os-release` `uname -m`: 1\"\n    fi\nelif [ -f /etc/lsb-release ] ; then\n    if grep -q 'DISTRIB_RELEASE=14.04' /etc/lsb-release ; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-14.04-64: `cat /etc/lsb-release`: 0\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=16.04' /etc/lsb-release ; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-16.04-64: `cat /etc/lsb-release`: 0\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=18.04' /etc/lsb-release ; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-18.04-64: `cat /etc/lsb-release`: 0\"\n        fi\n    elif grep -q 'DISTRIB_RELEASE=20.04' /etc/lsb-release ; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"UBUNTU-20.04-64: `cat /etc/lsb-release`: 0\"\n        fi\n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: `cat /etc/lsb-release` `uname -m`: 1\"\n    fi\nelif [ -f /etc/debian_version ]; then\n    if grep -q '^7.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN7-64: `cat /etc/debian_version`: 0\"\n        fi\n    elif grep -q '^8.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN8-64: `cat /etc/debian_version`: 0\"\n        fi\n    elif grep -q '^9.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN9-64: `cat /etc/debian_version`: 0\"\n        fi\n    elif grep -q '^10.*' /etc/debian_version; then\n        if [ `uname -m` = \"x86_64\" ]; then\n            OS=\"DEBIAN10-64: `cat /etc/debian_version`: 0\"\n        fi\n    fi\n\n    if [ -z \"$OS\" ]; then\n        OS=\"Unsupported: Debian `cat /etc/debian_version` `uname -m`: 1\"\n    fi\nfi\n\nif [ $# -gt 0 ]\nthen\n    echo $OS\nfi\n", "num_lines": 134}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#################\n# DEFAULT VALUES\n#################\n\nCOMPONENT_TO_BE_BUILT=${1:-UA}\nGIT_BRANCH=${2:-develop}\nMAJOR_VERSION=${3:-9}\nMINOR_VERSION=${4:-50}\nPATCH_SET_VERSION=${5:-0}\nPATCH_VERSION=${6:-0}\nBUILD_QUALITY=${7:-RELEASE}\nBUILD_PHASE=${8:-GA}\nFTP_BUILD=${9:-no}\nshift\nCVS_UPDATE=${9:-yes}\nshift\nGIT_TAG=${9:-develop}\nshift\nTOP_DIR_FOR_UA=${9:-/BUILDS}\nshift\nAGENT_TYPE_FOR_UA=${9:-both}\nshift\nCONFIGURATION_FOR_UA=${9:-both}\nshift\nBINARIES_PATH_FOR_UA=${9:-/BUILDS/develop/BINARIES/UNIFIED}\nshift\nTIER_NUMBER=${9:-tier1}\nSCRIPTS_PATH_FOR_UA=/BUILDS/SCRIPTS/develop/UNIFIED\n\ncase $COMPONENT_TO_BE_BUILT in\n\n\tUA)\n\t\tfor ip in `cat build/scripts/general/iplist`\n\t\tdo\n\t\t    IP=`echo ${ip} | cut -d\":\" -f1`\n\t\t    ssh -f ${IP} \"mkdir -p ${BINARIES_PATH_FOR_UA} ${SCRIPTS_PATH_FOR_UA}\"\n\t\t    sleep 10\n\t\t    scp build/scripts/general/${COMPONENT_TO_BE_BUILT}_TRIGGER.sh ${IP}:${SCRIPTS_PATH_FOR_UA}\n\t\t    ssh -f $IP \"cd ${SCRIPTS_PATH_FOR_UA}; ./${COMPONENT_TO_BE_BUILT}_TRIGGER.sh ${TOP_DIR_FOR_UA} inmage ${GIT_BRANCH} ${GIT_TAG} ${BUILD_QUALITY} ${BUILD_PHASE} ${MAJOR_VERSION} ${MINOR_VERSION} ${PATCH_SET_VERSION} ${PATCH_VERSION} ${AGENT_TYPE_FOR_UA} ${CONFIGURATION_FOR_UA} ${FTP_BUILD} ${TIER_NUMBER} > ${BINARIES_PATH_FOR_UA}/UA_WRAPPER_log 2>&1 \"\n\t\tdone\n\t;;\t\nesac\n", "num_lines": 43}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n##\n# Defining the Usage\n##\nUSAGE=\"Usage:   ./bld_env_setup.sh <Top Build Dir> <type of the agent build>\"\n[ -z \"$1\" ] && echo $USAGE && exit 65\n[ -z \"$2\" ] && echo $USAGE && exit 65\n\n##\n# Making top dir for build\n##\nif [ ! -d \"$1\" ]\nthen\n\tmkdir -p $1\n\n\tif [ $? -eq 0 ]\n\tthen\n\t\tif [ \"$2\" = \"both\" ]; then\n\t\t\tmkdir -p ${1}/source ${1}/logs/VX ${1}/logs/FX ${1}/binaries/VX ${1}/binaries/FX > /dev/null 2>&1\n\t\t\techo \"Created directory ${1} and subdirectories source, logs and binaries under it...\"\n\t\telif [ \"$2\" = \"FX\" ]; then\n\t\t\tmkdir -p ${1}/source ${1}/logs/FX ${1}/binaries/FX > /dev/null 2>&1\n\t\t\techo \"Created directory ${1} and subdirectories source, logs and binaries under it...\"\n\t\telif [ \"$2\" = \"VX\" ]; then\n\t\t\tmkdir -p ${1}/source ${1}/logs/VX ${1}/binaries/VX > /dev/null 2>&1\n\t\t\techo \"Created directory ${1} and subdirectories source, logs and binaries under it...\"\n\t\telse\n\t\t\techo \"Directory creation failed for ${1}!\"\n\t\t\texit 66\n\t\tfi\n\tfi\nelse\n\techo \"Directory $1 already exists. Attempting to create subdirectories source, logs and binaries under it...\" \n\tCUR_W_D=`pwd`\n\n\tcd $1\n\n\tif [ $? -eq 0 ]\n\tthen\n\t\tif [ \"$2\" = \"both\" ]; then\n\t\t\tmkdir -p source logs/VX binaries/VX logs/FX binaries/FX > /dev/null 2>&1\n\t\t\tcd $CUR_W_D\n\t\telif [ \"$2\" = \"FX\" ]; then\n\t\t\tmkdir -p source logs/FX binaries/FX > /dev/null 2>&1\n\t\t\tcd $CUR_W_D\n\t\telif [ \"$2\" = \"VX\" ]; then\n\t\t\tmkdir -p source logs/VX binaries/VX > /dev/null 2>&1\n\t\t\tcd $CUR_W_D\n\t\tfi\n\telse\n\t\techo \"Cannot change directories to ${1}!\"\n\t\tcd $CUR_W_D\n\t\texit 67\n\tfi\nfi\n", "num_lines": 57}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Set the required variables.\nTOP_BLD_DIR=${1:-`pwd`}\nGIT_TAG=${2:-develop}\nCLEAN_REPO=${3:-yes}\nCHKOUT_LOG=\"checkout_$GIT_TAG.log\"\nX_ARCH=`uname -ms | sed -e s\"/ /_/g\"`\ndate_suffix=`date +%e_%b_%Y | awk '{print $1}'`\n\n# Change directories to the source folder where checkout will take place.\nif [ -d $TOP_BLD_DIR/source ]; then\n  CUR_W_D=`pwd`\n  cd $TOP_BLD_DIR/source\nelse\n  echo \"Directory $TOP_BLD_DIR/source not found.\"\n  exit 1\nfi\n\nif [ $CLEAN_REPO == \"yes\" ]; then\n\trm -rf $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery\n\tif [ $? -eq 0 ]; then\n\t\techo \"Successfully deleted $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery directory.\"\n\telse\n\t\techo \"Failed to delete $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery directory.\"\n\t\texit 1\n\tfi\nfi\n\n# checkout workarea if it doesn't exist already.\nif [ ! -d $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery ]; then\n\t: > $CHKOUT_LOG\n\n\tgit clone -b ${GIT_TAG} --single-branch msazure@vs-ssh.visualstudio.com:v3/msazure/One/InMage-Azure-SiteRecovery >> $CHKOUT_LOG 2>&1\n\tif [ $? -eq 0 ]; then\n\t\techo \"Successfully cloned InMage-Azure-SiteRecovery git repo from branch ${GIT_TAG}.\" >> $CHKOUT_LOG 2>&1\n\t\tcd InMage-Azure-SiteRecovery\n\telse\n\t\techo \"Failed to clone InMage-Azure-SiteRecovery git repo and branch ${GIT_TAG}.\" >> $CHKOUT_LOG 2>&1\n\t\texit 1\n\tfi\nelse\n\t\tcd InMage-Azure-SiteRecovery\n\t\tgit checkout ${GIT_TAG}\n\t\tif [ $? -eq 0 ]; then\n\t\t\techo \"Successfully checked out code from ${GIT_TAG}.\" >> $CHKOUT_LOG 2>&1\n\t\telse\n\t\t\techo \"Failed to check out code from ${GIT_TAG}.\" >> $CHKOUT_LOG 2>&1\n\t\texit 1\n\t\tfi\nfi\n\n# Replacing build switch with all in ubuntu.sh script. Build switch is used in cloud build and all switch is used in on-prem builds.\nsed -i -e \"s|user_space/build/ubuntu.sh\\ build|user_space/build/ubuntu.sh\\ all|g\" host/vx_setup.mak\nif [ $? -eq 0 ]; then\n\techo \"Replaced build switch with all in ubuntu.sh script.\" >> $CHKOUT_LOG 2>&1\nelse\n\techo \"Failed to replace build switch with all in ubuntu.sh script.\" >> $CHKOUT_LOG 2>&1\n\texit 1\nfi\n\n# Provide execute permissions to all files.\nfind admin/ build/ host/ server/ Solutions/ -type f -exec chmod 755 {} \\; >> $CHKOUT_LOG 2>&1\nif [ $? -eq 0 ]; then\n\techo \"Gave execute permission to all files successfully.\" >> $CHKOUT_LOG 2>&1\nelse\n\techo \"Failed to give execute permissions to all files.\" >> $CHKOUT_LOG 2>&1\n\texit 1\nfi\n\n# Convert to Unix line endings.\nfind admin/ build/ host/ server/ Solutions/ -type f -exec dos2unix {} \\; >> $CHKOUT_LOG 2>&1\nif [ $? -eq 0 ]; then\n    echo \"Converted to Unix line endings successfully.\" >> $CHKOUT_LOG 2>&1\nelse\n    echo \"Failed to convert to Unix line endings.\" >> $CHKOUT_LOG 2>&1\n    exit 1\nfi\n\n# Temporary workaround till depend.sh is fixed.\nfind admin/ build/ host/ server/ Solutions/ -type f -exec touch {} \\; >> $CHKOUT_LOG 2>&1\nif [ $? -eq 0 ]; then\n    echo \"Touched all the files successfully.\" >> $CHKOUT_LOG 2>&1\nelse\n    echo \"Failed to touch files.\" >> $CHKOUT_LOG 2>&1\n    exit 1\nfi\n\n# Removing the exiting symbolic links so that the make will create the respective symbolic links.\nrm -f ${THIRDPARTY_PATH}/lib/lib ${THIRDPARTY_PATH}/bin/bin\n\ncd $CUR_W_D\n", "num_lines": 93}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n##\n# Defining different exit codes. This would help track failures better\n##\n\n# Exit code table\nE_SUCCESS=0\nE_GENERIC_FAILURE=1\nE_OS_NOT_SUPPORTED=25\nE_SETUP_ARG_MISSING=65\nE_SETUP_DIRCREATION_FAILURE=66\nE_SETUP_CHANGEDIR_FAILURE=67\nE_CHECKOUT_ARG_MISSING=75\nE_CHECKOUT_SOURCE_DIR_NOT_FOUND=76\nE_VERSION_ARG_MISSING=85\nE_VERSION_SCRIPT_NOT_FOR_CODE_BRANCH=86\nE_VERSION_FAILURE_TO_GET_SECS_ELAPSED=88\nE_VERSION_PARTNER_NOT_HANDLED=89\nE_VERSION_BIN_DIR_NOT_FOUND=90\nE_BUILD_VX_FAILURE=94\nE_BUILD_DRIVER_BLD_FAILURE=95\nE_BUILD_INMSHUTNOTIFY_FAILURE=99\nE_BUILD_SVDCHECK_FAILURE=100\nE_BUILD_INMSTKOPSBIN_FAILURE=101\nE_BUILD_DRIVER_MACHINE_DOWN=102\nE_PACKAGING_BINARIES_ABSENT=105\nE_PACKAGING_PARTNER_DIR_ABSENT=106\n\n##\n# This function executes a command and logs the output\n##\nDO_AND_LOG()\n{\n\tCMD=$1\n\teval $CMD >> $FLOG\n}\n\n##\n# This function verifies the exit status of a program and print messages accordingly\n##\nVERIFY()\n{\n\tstatus=$1\n\n\tcase $status in\n\n\t\t$E_SUCCESS) ;;\n\n\t\t$E_OS_NOT_SUPPORTED)\n\t\t\techo \"THIS PLATFORM IS NOT SUPPORTED YET!\"\n\t\t\texit $E_OS_NOT_SUPPORTED ;;\n\n\t\t$E_SETUP_ARG_MISSING)\n\t\t   \techo \"SOME OR ALL ARGUMENTS FOR vx_bld_env_setup.sh ARE MISSING!\"\n\t\t\texit $E_SETUP_ARG_MISSING ;;\n\n\t\t$E_SETUP_DIRCREATION_FAILURE)\n\t\t\techo \"DIRECTORY $TOP_BLD_DIR COULD NOT BE CREATED!\"\n\t\t\texit $E_SETUP_DIRCREATION_FAILURE ;;\n\n\t\t$E_SETUP_CHANGEDIR_FAILURE)\n\t\t\techo \"FAILED TO CHANGE DIRECTORY TO $TOP_BLD_DIR!\"\n\t\t\texit $E_SETUP_CHANGEDIR_FAILURE ;;\n\n\t\t$E_CHECKOUT_ARG_MISSING)\n\t\t\techo \"SOME OR ALL ARGUMENTS FOR vx_checkout.sh ARE MISSING!\"\n\t\t\texit $E_CHECKOUT_ARG_MISSING ;;\n\n\t\t$E_CHECKOUT_SOURCE_DIR_NOT_FOUND)\n\t\t\techo \"DIRECTORY source NOT FOUND UNDER TOP BUILD DIRECTORY!\"\n\t\t\texit $E_CHECKOUT_SOURCE_DIR_NOT_FOUND ;;\n\n\t\t$E_SCRIPT_NOT_FOR_CODE_BRANCH)\n\t\t\techo \"CODE BRANCH SUPPLIED AS ARGUMENT TO vx_versioning.sh IS NOT VALID FOR THIS SCRIPT!\"\n\t\t\texit $E_SCRIPT_NOT_FOR_CODE_BRANCH ;;\n\n\t\t$E_VERSION_PARTNER_NOT_HANDLED)\n\t\t\techo \"PARTNER SUPPLIED TO vx_versioning.sh NOT HANDLED IN THIS SCRIPT!\"\n\t\t\texit $E_VERSION_PARTNER_NOT_HANDLED ;;\n\n\t\t$E_PACKAGING_PARTNER_DIR_ABSENT)\n\t\t\techo \"DIRECTORY $TOP_BLD_DIR/source/build/$PARTNER NOT FOUND!\"\n\t\t\texit $E_PACKAGING_PARTNER_DIR_ABSENT ;;\n\n\tesac\n}\n\nusage()\n{\n\t echo \"usage: ./complete.sh [-s <setup/checkout/build_package>] [-d <top build dir>] -T <thirdparty dirpath> [-b <branch>] [ -B <tagname-for-checkout> ] [-p <partner>] [-x <X_ARCH>] [-c <release|debug>] [-v] [-w <none|warn|error>] [-q <DAILY|RELEASE>] [-P <buildphase|DIT] [ -M <Major version> ] [ -N <Minor Version> ] [ -A <Agent Type> ] [-h] <cvs username>\"\n\t echo \"  <cvs username> required: cvs login id used to check source\"\n\t echo \"  -s <setup/checkout/build_package> --> Quit after the stage is finished\"\n\t echo \"  -d <directory to build in> (optional): directory where you want the build done. default current directory\"\n\t echo \"      $DEFAULT_TOP_BLD_DIR\"\n\t echo \"  -b <branch> (optional): cvs branch to use for checking out source and computing build number. default $DEFAULT_CVS_BRANCH\"\n\t echo \"  -B <tagname-for-checkout> (optional): cvs tag to use when checking out source. default $DEFAULT_GIT_TAG\"\n\t echo \"  -p <partner> (optional): partner the build is for. default $DEFAULT_PARTNER\"\n\t echo \"  -x <X_ARCH> (optional): X_ARCH to use for the build. default $DEFAULT_X_ARCH\"\n\t echo \"  -c <release|debug> (optional): configuration to build. default $DEFAULT_CONFIG\"\n\t echo \"  -q <DAILY|RELEASE> (optional): quality of the build (whether daily or release). default $DEFAULT_BLD_QUALITY\"\n\t echo \"  -P <buildphase|DIT> (optional): phase of the build (whether DIT, BETA, etc). default $DEFAULT_BLD_PHASE\"\n\t echo \"  -M < Major Version > default is 9\"\n\t echo \"  -N < Minor Version > default is 0\"\n\t echo \"  -S < Patch Set Version > default is 0\"\n\t echo \"  -V < Patch Version > default is 0\"\n\t echo \"  -A < Agent Type > If FX or VX or both\"\n\t echo \"  -T <thirdparty path> required: path of thirdparty folder\"\n\t echo \"  -v (optional): turn on verbose during build. default off\"\n\t echo \"  -w <none|warn|error> (optional): compiler warning level to use. default $DEFAULT_WARN_LEVEL\"\n\t echo \"               none: use compiler defaults\"\n\t echo \"               warn: add additional warning checks to compiler\"\n\t echo \"               error: add additional warning checks to compiler and treat warnings as errors\"\n\t echo \"  -h (optional): display this help\"\n\t exit 1\n}\n\n\nparse_cmd_line ()\n{\n\t if test \"$1\" = \"\" ; then\n\t\t  echo \"cvs username required\"\n\t\t  usage\n\t else\n\t\t  while test \"$1\" != \"\" ; do\n\t\t\t\tcase $1 in\t\t\t\t \n\t\t\t\t\t -d)\n\t\t\t\t\t\t  TOP_BLD_DIR=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -s)\n\t\t\t\t\t\t  STAGE=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -b)\n\t\t\t\t\t\t  CVS_BRANCH=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -B)\n\t\t\t\t\t\t  GIT_TAG=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -p)\n\t\t\t\t\t\t  PARTNER=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -c)\n\t\t\t\t\t\t  CONFIG=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -q)\n\t\t\t\t\t\t  BUILD_QUALITY=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -v)\n\t\t\t\t\t\t  VERBOSE=\"-v\"\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -h)\n\t\t\t\t\t\t  usage\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -w)\n\t\t\t\t\t\t  WARN_LEVEL=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -x)\n\t\t\t\t\t\t  X_ARCH=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -P)\n\t\t\t\t\t\t  BUILD_PHASE=\"$2\"\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\n\t\t\t\t\t -M)\n\t\t\t\t\t\t MAJOR_VERSION=\"$2\"\n\t\t\t\t\t\t shift\n\t\t\t\t\t\t ;;\n\t\t\t\t\t-N)\n                                                 MINOR_VERSION=\"$2\"\n                                                 shift\n                                                 ;;\n\t\t\t\t\t-S)\n                                                 PATCH_SET_VERSION=\"$2\"\n                                                 shift\n                                                 ;;\n\n                                        -V)\n                                                 PATCH_VERSION=\"$2\"\n                                                 shift\n                                                 ;;\n                                        -A)\n                                                 AGENT_TYPE=\"$2\"\n                                                 shift\n                                                 ;;\n\n\t\t\t\t\t -T)\n\t\t\t\t\t\t  THIRDPARTY_PATH=\"$2\"\n\t\t\t\t\t\t  if test \"$THIRDPARTY_PATH\" = \"\"; then\n\t\t\t\t\t\t\techo \"Enter thirdparty path\"\n\t\t\t\t\t\t\tusage\n\t\t\t\t\t\t  fi\n\t\t\t\t\t\t  shift\n\t\t\t\t\t\t  ;;\n\t\t\t\t\t -*)\n\t\t\t\t\t\t  echo \"invalid option $1\" \n\t\t\t\t\t\t  usage\n\t\t\t\t\t\t  ;;                  \n\t\t\t\t\t *)\n\t\t\t\t\t\t  if test \"$CVS_USERNAME\" != \"\" ; then \n\t\t\t\t\t\t\techo \"invalid option $1\" \n\t\t\t\t\t\t\tusage\n\t\t\t\t\t\t  fi\n \t\t\t\t\t\t  CVS_USERNAME=\"$1\"\n\t\t\t\t\t\t  ;;\n\t\t\t\tesac\n\t\t\t\tshift\n\t\t  done\n\t fi\n\t \n\t if test \"$CVS_USERNAME\" = \"\" ; then\n\t\t  echo \"cvs username required\"\n\t\t  usage\n\t fi\n\t \n}\t \n\n##\n# DEFAULTS\n# sets up inital default values that can be over ridden by command line options\n# these are used that usage can display the default values even if a command line\n# option has already set the value\n##\nDEFAULT_TOP_BLD_DIR=`pwd`\nDEFAULT_CVS_BRANCH=\"develop\"\nDEFAULT_GIT_TAG=\"develop\"\nDEFAULT_PARTNER=\"inmage\"\nDEFAULT_CONFIG=\"release\"\nDEFAULT_WARN_LEVEL=\"none\"\nDEFAULT_X_ARCH=`uname -ms | sed -e s\"/ /_/g\"`\nDEFAULT_BLD_QUALITY=\"DAILY\"\nDEFAULT_BLD_PHASE=\"DIT\"\nDEFAULT_STAGE=\"\";\nDEFAULT_MAJOR_VERSION=9\nDEFAULT_MINOR_VERSION=0\nDEFAULT_AGENT_TYPE=both\n\n##\n# VARIABLES\n# the variables that will be used \n# set them to their defaults. note: some maybe over ridden by command line options\n##\nTOP_BLD_DIR=\"$DEFAULT_TOP_BLD_DIR\"\nCVS_BRANCH=\"$DEFAULT_CVS_BRANCH\"\nGIT_TAG=\"$DEFAULT_GIT_TAG\"\nPARTNER=\"$DEFAULT_PARTNER\"\nCONFIG=\"$DEFAULT_CONFIG\"\nVERBOSE=yes\nWARN_LEVEL=\"$DEFAULT_WARN_LEVEL\"\nX_ARCH=\"$DEFAULT_X_ARCH\"\nSUFFIX=`date +%d`_`date +%b`_`date +%H`_`date +%M`_`date +%S`\nFLOG=\"$TOP_BLD_DIR/logs/VX_Build_$SUFFIX.log\"\nCVS_USERNAME=\nTHIRDPARTY_PATH=\nBUILD_QUALITY=\"$DEFAULT_BLD_QUALITY\"\nBUILD_PHASE=\"$DEFAULT_BLD_PHASE\"\nSTAGE=$DEFAULT_STAGE\nMAJOR_VERSION=\"$DEFAULT_MAJOR_VERSION\"\nMINOR_VERSION=\"$DEFAULT_MINOR_VERSION\"\nAGENT_TYPE=\"$DEFAULT_AGENT_TYPE\"\n\n##\n# Step 1: COMMAND LINE VALIDATION\n# This would capture various parameters passed to this script, validates them and\n# sets them to required variables\n##\nparse_cmd_line $@\n\n##\n# Step 1.1: Find out how much needs to be done\n# If build_status file is lying around, read it and figure out\n# If file does not exist, do everything\n# A value of 1 for a step's flag means the step's to be done; a value of 0 means leave that step\n# Truncate all slashes in TOP_BLD_DIR so that touch doesn't fail\n##\n\nBuild_Dir=`echo $TOP_BLD_DIR | sed -e \"s/\\///g\"`\n\nif [ ! -e build_status_${Build_Dir} ]; then\n\ttouch build_status_${Build_Dir}\n\tSETUP=1 CHECKOUT=1 BUILD_PACKAGE=1\nelse\n\tif grep -iq \"setup_${AGENT_TYPE}\" build_status_${Build_Dir} ; then\n\t\tSETUP=0\n\telse\n\t\tSETUP=1\n\tfi\n\n\tif grep -iq \"checkout\" build_status_${Build_Dir} ; then\n\t\tCHECKOUT=0\n\telse\n\t\tCHECKOUT=1\n\tfi\n\n\tif grep -iq \"build_package_${PARTNER}_${CONFIG}_${AGENT_TYPE}\" build_status_${Build_Dir} ; then\n\t\tBUILD_PACKAGE=0\n\telse\n\t\tBUILD_PACKAGE=1\n\tfi\n\nfi\n\nif [ \"$AGENT_TYPE\" = \"both\" ]; then\n        argument_for_make=ua_setup\nelif [ \"$AGENT_TYPE\" = \"FX\" ]; then\n        argument_for_make=fx_setup\nelif [ \"$AGENT_TYPE\" = \"VX\" ]; then\n        argument_for_make=vx_setup\nfi\n\n##\n# Step 2: BUILD ENVIRONMENT SETUP\n# Making top dir for build and export common required shell variables\n##\n\nif [ $SETUP -eq 1 ]; then\n\techo\n\techo \"Setting up required directory structure...\"\n\techo\n\t./bld_env_setup.sh $TOP_BLD_DIR $AGENT_TYPE\n\tSETUP_EXIT_STATUS=$?\n\tVERIFY $SETUP_EXIT_STATUS\n\techo \"setup_${AGENT_TYPE}\" >> build_status_${Build_Dir}\nelse\n\techo \"Build directory structure setup already done for $TOP_BLD_DIR!\"\nfi\n\nif [ z\"$STAGE\" = z\"setup\" ]; then exit; fi\n\n##\n# Step 3: CHECKOUT\n# Set variables and checkout files as required on the chosen OS\n##\n\nif [ $CHECKOUT -eq 1 ] ; then\n\techo\n\techo \"Checking out source code now...\"\n\techo\n\t./checkout.sh $TOP_BLD_DIR $GIT_TAG\n\tCHECKOUT_EXIT_STATUS=$?\n\tVERIFY $CHECKOUT_EXIT_STATUS\n\techo \"checkout\" >> build_status_${Build_Dir}\nelse\n\techo \"Source code checkout already done for $TOP_BLD_DIR!\"\nfi\n\nif [ z\"$STAGE\" = z\"checkout\" ]; then exit; fi\n\n##\n# Step 6: BUILD\n##\n\nif [ $BUILD_PACKAGE -eq 1 ] ; then\n\techo\n\techo \"Building the agent now...\"\n\techo\n\tcur_wd=`pwd`\n\tcd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host\n\tmake clean\n        \n        if [ \"$CONFIG\" = \"debug\" ];then\n\t\tBUILD_CONFIG=yes\n\telif [ \"$CONFIG\" = \"release\" ];then\n\t\tBUILD_CONFIG=no\n\tfi\n\tgmake $argument_for_make X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_PATCH_SET_VERSION=${PATCH_SET_VERSION} X_PATCH_VERSION=${PATCH_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER \n        \t\t\n\tBUILD_EXIT_STATUS=$?\n\tVERIFY $BUILD_EXIT_STATUS\n\tcd $cur_wd\n\techo \"build_package_${PARTNER}_${CONFIG}_${AGENT_TYPE}\" >> build_status_${Build_Dir}\n\n\t# Copy the tar files to binaries directory under TOP_BLD_DIR\n\tif [ \"$AGENT_TYPE\" = \"both\" ]; then\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/FX\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_vx/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/VX\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_ua/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries\n\n\telif [ \"$AGENT_TYPE\" = \"FX\" ]; then\n\t\tif [ \"$CONFIG\" = \"release\" ];then\n\t\t\tcd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host\n\t\t\tgmake symbol_generation X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER\n\t\t\tcd $cur_wd\n\t\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries\n\t\tfi\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/FX\n\n\telif [ \"$AGENT_TYPE\" = \"VX\" ]; then\n\t\tif [ \"$CONFIG\" = \"release\" ];then\n\t\t\tcd $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host\n\t\t\tgmake symbol_generation X_VERSION_MAJOR=$MAJOR_VERSION X_VERSION_MINOR=${MINOR_VERSION} X_VERSION_QUALITY=$BUILD_QUALITY X_VERSION_PHASE=$BUILD_PHASE debug=$BUILD_CONFIG warnlevel=$WARN_LEVEL verbose=$VERBOSE partner=$PARTNER\n\t\t\tcd $cur_wd\n\t\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/*.tar.gz $TOP_BLD_DIR/binaries\n\t\tfi\n\t\tmv $TOP_BLD_DIR/source/InMage-Azure-SiteRecovery/host/${X_ARCH}/setup_vx/${CONFIG}/*.tar.gz $TOP_BLD_DIR/binaries/VX\n\tfi\nelse\n\techo \"Build and packaging are already done for $TOP_BLD_DIR!\"\nfi\n\nif [ z\"$STAGE\" = z\"build_package\" ]; then exit; fi\n", "num_lines": 412}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\numask 0002\nVX_VERSION_FILE=\"/usr/local/.vx_version\"\nSCRIPT_DIR=$(readlink -f `dirname \"$0\"`)\nINSTALL_LOG_FILE=\"$SCRIPT_DIR/ua_install.log\"\nUPGRADE_LOG_FILE=\"$SCRIPT_DIR/ua_upgrader.log\"\nCUR_DIR=`pwd`\nINSTALLATION_DIR=$(grep ^INSTALLATION_DIR $VX_VERSION_FILE | cut -d\"=\" -f2 | tr -d \" \")\nINSTALL_ERROR_JSON=\"/var/log/InstallerErrors.json\"\nPAR_DIR=`dirname $SCRIPT_DIR`\nGLOB_LOG_DIR=\"$PAR_DIR/logs\"\nGLOB_INSTALL_LOG_FILE=\"$GLOB_LOG_DIR/ua_install.log\"\nGLOB_UPGRADE_LOG_FILE=\"$GLOB_LOG_DIR/ua_upgrader.log\"\n\ntrace_log_message() {\n    DATE_TIME=`date '+%Y/%m/%d %H:%M:%S'`\n    echo -e \"$@\"\n    echo \"${DATE_TIME} : $@ \" >> ${UPGRADE_LOG_FILE} 2>&1\n}\n\nexit_with_retcode() {\n    #Moving to original directory\n    cd $CUR_DIR\n\n    trace_log_message \"Dumping Job file content in upgrader log file\"\n    cat $JOB_FILE_PATH >> $UPGRADE_LOG_FILE\n\n    #TODO Upload upgrader and AzureRcmCLi log.\n    ${INSTALLATION_DIR}/bin/AzureRcmCli --agentupgradelogsupload --agentupgradelogspath \\\n        \"$SCRIPT_DIR\" --agentupgradejobdetails \"$JOB_FILE_PATH\"\n\n    #Dump data to global log file\n    mkdir -p $GLOB_LOG_DIR\n    cat $INSTALL_LOG_FILE >> $GLOB_INSTALL_LOG_FILE\n    cat $UPGRADE_LOG_FILE >> $GLOB_UPGRADE_LOG_FILE\n\n    exit $1\n}\n\nupgrade_mobility_service() {\n    trace_log_message \"ENTERED $FUNCNAME\"\n\n    $SCRIPT_DIR/install -r MS -v VmWare -q -a Upgrade -c CSPrime -l $INSTALL_LOG_FILE \\\n        -e $INSTALL_ERROR_JSON -j $SCRIPT_DIR/installerjson.json\n    local ret_val=$?\n\n    trace_log_message \"EXITED $FUNCNAME\"\n    return $ret_val\n}\n\nregister_source_agent() {\n    trace_log_message \"ENTERED $FUNCNAME\"\n    local ret_val=1\n    local count=0\n\n    while [ $count -le 2 ]; do\n        trace_log_message \"AzureRcmCli registersourceagent operation - iteration : $count\"\n        trace_log_message \"-------------------------------------------------------------\"\n        trace_log_message \"Executing the command : ${INSTALLATION_DIR}/bin/AzureRcmCli \" \\\n            \"--registersourceagent --errorfilepath $INSTALL_ERROR_JSON\"\n        ${INSTALLATION_DIR}/bin/AzureRcmCli --registersourceagent --errorfilepath \\\n            $INSTALL_ERROR_JSON >> $UPGRADE_LOG_FILE 2>&1\n        ret_val=$?\n        if [ $ret_val -eq 0 ]; then\n            trace_log_message -q \"registersourceagent operation has succeeded.\"\n            break\n        else\n            trace_log_message -q \"registersourceagent failed with exit code - $ret_val\"\n            count=$(expr $count + 1)\n            sleep 5\n        fi\n    done\n\n    trace_log_message \"EXITED $FUNCNAME\"\n    return $ret_val\n}\n\nupgrade_action() {\n    trace_log_message \"ENTERED $FUNCNAME\"\n    upgrade_mobility_service\n    upgrade_ret_val=$?\n\n    if [ $upgrade_ret_val -ne 0 -a $upgrade_ret_val -ne 98 \\\n        -a $upgrade_ret_val -ne 209 ]; then\n        trace_log_message \"Upgrade agent failed with return value : $upgrade_ret_val\"\n        return $upgrade_ret_val\n    fi\n    register_source_agent\n    reg_source_exit_code=$?\n    trace_log_message \"\"\n    if [ $reg_source_exit_code -eq 0 ]; then\n        trace_log_message \"registersourceagent operation has succeeded.\"\n    else\n        trace_log_message \"registersourceagent failed with exit code - $reg_source_exit_code\"\n    fi\n\n    trace_log_message \"EXITED $FUNCNAME\"\n    return $reg_source_exit_code\n}\n\ncomplete_job_to_rcm() {\n    trace_log_message \"ENTERED $FUNCNAME\"\n\n    ${INSTALLATION_DIR}/bin/AzureRcmCli --completeagentupgrade --agentupgradeexitcode \\\n        \"$upgrade_action_return_value\" --agentupgradejobdetails \"$JOB_FILE_PATH\" --errorfilepath \\\n        \"$INSTALL_ERROR_JSON\" >> $UPGRADE_LOG_FILE 2>&1\n    local ret_val=$?\n\n    trace_log_message \"EXITED $FUNCNAME\"\n    return $ret_val\n}\n\npost_action() {\n    trace_log_message \"ENTERED $FUNCNAME\"\n\n    complete_job_to_rcm\n    post_exit_code=$?\n    if [ $post_exit_code -eq 0 ]; then\n        trace_log_message \"Post actions completed successfully\"\n    else\n        trace_log_message \"Post actions failed\"\n    fi\n\n    trace_log_message \"EXITED $FUNCNAME\"\n    return $post_exit_code\n}\n\nmain() {\n    while getopts :j:  opt\n    do\n        case $opt in\n        j)  JOB_FILE_PATH=\"$OPTARG\"\n        ;;\n        *)  trace_log_message \"Incorrect usage\"\n            exit_with_retcode 1\n        ;;\n        esac\n    done\n\n    if [ -z \"$JOB_FILE_PATH\" ]; then\n        trace_log_message \"Job File not provided\"\n        exit_with_retcode 1\n    fi\n    if [ ! -f \"$JOB_FILE_PATH\" ]; then\n        trace_log_message \"File path: $JOB_FILE_PATH doesn't exist\"\n        exit_with_retcode 1\n    fi\n    #installer needs to be invoked from the same directory\n    cd $SCRIPT_DIR\n\n    upgrade_action\n    upgrade_action_return_value=$?\n    post_action || exit_with_retcode $?\n    exit_with_retcode 0\n}\n\nmain \"$@\"\n", "num_lines": 159}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "log_string()\n{\n    # $1 -> the json error file name\n    # $2 -> string to be appended\n    head -q -n -2 $1 > /tmp/out.json\n    head -q -c -1  /tmp/out.json > $1\n    echo -e -n $2 >> $1\n    echo -e \"\\n\\t]\\n}\" >> $1\n    rm -rf /tmp/out.json\n}\n\n# This function will log the error to the output JSON file\n# The format of JSON file is\n#\n# {\n#    \"Errors\":\n#    [\n#        {\n#            \"error_name\":\"err1\",\n#            \"error_params\":{\"l\":\"m\",\"p\":\"q\",\"x\":\"z\"},\n#            \"default_message\": \"error1 occured\"\n#        },\n#        {\n#            \"error_name\":\"err2\",\n#            \"error_params\":{\"l\":\"m\",\"p\":\"q\",\"x\":\"z\"},\n#            \"default_message\": \"error2 occured\"\n#        },\n#        {\n#            \"error_name\":\"err3\",\n#            \"error_params\":{\"l\":\"m\",\"p\":\"q\",\"x\":\"z\"},\n#            \"default_message\": \"error3 occured\"\n#        }\n#    ]\n# }\n\nlog_to_json_errors_file()\n{\n    local json_errors_file=$1\n    error_code=$2\n    error_message=$3\n    nr_args=$#\n\n    if [ ! -f $json_errors_file ]; then\n        echo -e \"{\\n\\t\\\"Errors\\\":\\n\\t[\\n\\t]\\n}\" >> $json_errors_file\n    else\n        log_string $json_errors_file \",\"\n    fi\n    log_string  $json_errors_file \"\\n\\t\\t{\"\n    log_string  $json_errors_file \"\\n\\t\\t\\t\\\"error_name\\\":\\\"${error_code}\\\",\"\n    \n    nr_args=`expr ${nr_args} - 3`\n    shift; shift; shift\n    nr_params=0\n    str=\"\"\n    while [ ${nr_args} -gt \"0\" ]\n    do\n        if [ ${nr_params} -gt \"0\" ]; then\n            str=\"$str,\"\n        fi\n        str=\"$str\\\"$1\\\":\\\"\"\n        shift\n        str=\"$str$1\\\"\"\n        shift\n        nr_params=`expr ${nr_params} + 1`\n        nr_args=`expr ${nr_args} - 2`\n    done\n\n    str=\"\\n\\t\\t\\t\\\"error_params\\\":{$str},\"\n    log_string $json_errors_file $str\n\n    log_string $json_errors_file \"\\n\\t\\t\\t\\\"default_message\\\":\\\"${error_message}\\\"\\n\\t\\t}\"\n\n}\n\nSYSTEMCTL_DISTRO=\"SLES15-64 OL8-64 UBUNTU-20.04-64 DEBIAN9-64 DEBIAN10-64\"\n\n#FUNCTION : check if list contains the element, 0->contains, 1->doesn't contain\nlist_contains()\n{\n    [[ $1 =~ (^|[[:space:]])$2($|[[:space:]]) ]] && return \"0\" || return \"1\"\n}\n", "num_lines": 82}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#//--------------------------------------------------------------------\n#//  <copyright file=\"prereq_check_install.sh company=\"Microsoft\">\n#//      Copyright (c) Microsoft Corporation. All rights reserved.\n#//  </copyright>\n#//\n#//  <summary>\n#//     This script checks pre-requistes to install linux agent\n#//  </summary>\n#//\n#//--------------------------------------------------------------------\n\nTHIS_SCRIPT_DIR=`dirname $0`\nJQ=\"${THIS_SCRIPT_DIR}/jq\"\nGFDISK=\"${THIS_SCRIPT_DIR}/inm_list_part\"\nPREREQ_CONF_FILE=\"${THIS_SCRIPT_DIR}/prereq_check_installer.json\"\nSupported_Kernels=\"${THIS_SCRIPT_DIR}/supported_kernels\"\nLOG_FILE=\"/var/log/ua_install.log\"\nTEMP_FILE=\"${THIS_SCRIPT_DIR}/prereq_check_temp_file\"\nMIN_ROOT_FREESPACE_KB=1048576\nRETURN_VALUE=0\njson_errors_file=\nAGENT_ROLE=\nOS=$(${THIS_SCRIPT_DIR}/OS_details.sh 1)\nPLATFORM=\"VmWare\"\nWORKFLOW=\"VMWARE\"\numask 0002\n\nExisting_Check=(CLocaleAvailable HostNameSet SecureBoot FreeSpaceOnRoot LisDriversAvailable KernelSupported KernelDirectoryExists SystemDiskAvailable BootDiskAvailable LVMPackageInstalled BootOnLVMFromMultipleDisks BootPartitionMounted IsRootFsSupported IsBootFsSupported IsRootFsSupportedAzure IsBootFsSupportedAzure DirsWritable AcpiEqualsToZeroSet DeviceExistInGrubFiles GrubDeviceNameChange DhcpClientAvailable CheckMTKernelVersion OldOnePassEncryption RunlevelCommandCheck)\n\ndeclare -a CheckName\ndeclare -a CheckType\ndeclare -a Params\nNR_CHECKS=0\nIDX=\n\ndeclare -a MULIPATH_DEVICES\ndeclare -a MULIPATH_DEVICES_DEVT\ndeclare -a LINEAR_DEVICES\ndeclare -a LINEAR_DEVICE_TYPE\ndeclare -a DEVICES\nNR_BOOTABLE_DISKS=0\nBOOT_DISKS=\nBOOT_FULL_DISKS=\nSAME_BOOT_DISK=1\nSAME_ROOT_DISK=1\nSAME_PV=\nNR_PVS=\nPVS=\nROOT_DISKS=\nROOT_DEV=\nBOOT_DEV=\nNR_ROOT_DISKS=0\nIS_ROOT_ON_LV=0\nIS_LVM_PACKAGE_AVAILABLE=1\nBOOT_CONFIGURED_ON_EFI_PARTITION=0\nGRUB_FILE=\nBOOT_FS=\nROOT_FS=\nIS_ROOT_LVM=0\nIS_BOOT_LVM=0\n\nsource ${THIS_SCRIPT_DIR}/teleAPIs.sh\nSCENARIO_NAME=\"ProductPreReqChecks\"\n\n\nLOG()\n{\n    DATE_TIME=`date '+%m/%d/%Y %H:%M:%S'`\n    echo \"${DATE_TIME} : $@ \" >> ${LOG_FILE} 2>&1\n}\n\n#\n# Function Name: trace_log_message()\n#\n#  Description  Prints date and time followed by all arguments to\n#               stdout and to LOG_FILE.  If -q is used, only send\n#               message to log file, not to stdout.  If no arguments\n#               are given, a blank line is returned to stdout and to\n#               LOG_FILE.\n#\n#  Usage        trace_log_message [-q] \"Message\"\n#\n#  Notes        If -q is used, it must be the first argument.\n#\ntrace_log_message()\n{\n    QUIET_MODE=FALSE\n\n    if [ $# -gt 0 ]\n    then\n        if [ \"X$1\" = \"X-q\" ]\n        then\n            QUIET_MODE=TRUE\n            shift\n        fi\n    fi\n\n    if [ $# -gt 0 ]\n    then\n        DATE_TIME=`date '+%m/%d/%Y %H:%M:%S'`\n\n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"${DATE_TIME}: $*\" >> ${LOG_FILE}\n        else\n            echo -e \"$@\"\n            echo \"${DATE_TIME} : $@ \" >> ${LOG_FILE} 2>&1\n        fi\n    else\n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"\" >> ${LOG_FILE}\n        else\n            echo \"\" | tee -a ${LOG_FILE}\n        fi\n    fi\n}\n\nmnt_to_dev()\n{\n    df $1 | sed -n 2p | cut -f 1 -d \" \"\n}\n\n_dev_to_fs()\n{\n    blkid -o value -s TYPE $1\n}\n\nnum_dev_in_fs()\n{\n    local _ndev=\"1\"\n    local _fs=\"\"\n\n    _fs=$(_dev_to_fs $1)\n    if [ \"$_fs\" = \"btrfs\" ]; then\n        _ndev=$(btrfs filesystem show $1 | grep devid | wc -l)\n    fi   \n\n    echo $_ndev\n}\n\n# TODO: Should be _dev_to_fs. Remove it once multidisk btrfs support is enabled.\ndev_to_fs()\n{\n    local _fs=\"\"\n    local _ndev=\"\"\n\n    _fs=$(_dev_to_fs $1)\n    if [ \"$_fs\" = \"btrfs\" ]; then\n        _ndev=$(num_dev_in_fs $1)\n        LOG \"BTRFS ($1): Num Disks = $_ndev\"\n        if [ $_ndev -ne 1 ]; then\n            _fs=\"btrfs(multidevice)\"\n        fi\n    fi\n\n    echo $_fs \n}\n\nusage()\n{\n    LOG \"Usage of the program.\"\n    LOG \"prereq_check_install.sh -r <Agent Role, Agent or MasterTarget> -j <Output json file>\"\n}\n\n# This function will detect the VM platform (Azure/VmWare)\ndetect_platform()\n{\n    tag=$(cat /sys/devices/virtual/dmi/id/chassis_asset_tag 2>/dev/null)\n    if [ \"$tag\" = \"7783-7084-3265-9085-8269-3286-77\" ] && [ ! is_azure_stack_platform ] ; then\n        LOG \"The platform is Azure\"\n        PLATFORM=\"Azure\"\n    fi\n}\n\nlog_to_json_file()\n{\n    log_to_json_errors_file $json_errors_file \"$@\"\n}\n# Make sure the required locale is available in host. Abort if does not exists.\ncheck_c_locale_available()\n{\n    LOG \"Checking for C locale availability\"\n\n    locale=`echo ${Params[${IDX}]} | ${JQ} '.Locale' | awk -F\"\\\"\" '{print $2}'`\n    if [ -z \"${locale}\" ]; then\n        LOG \"Locale is not provided in the configuration JSON file\"\n        locale=\"C\"\n    fi\n\n    SetOP \"CheckCLocaleAvailable\"\n    if ! $(locale -a 2>> ${LOG_FILE} | grep -iqw ${locale}); then\n        RETURN_VALUE=1\n        LOG \"C locale is not available. Install the locale and retry enable replication.\"\n        log_to_json_file ASRMobilityServiceCLocaleNotAvailable \"C locale is not available. Install the locale and retry enable replication.\"\n        RecordOP 99 \"C locale is not available. Install the locale and retry enable replication.\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Make sure hostname is set. Otherwise abort.\ncheck_hostname_for_null()\n{\n    LOG \"Checking for Hostname set to NULL\"\n\n    SetOP \"CheckHostNameSet\"\n    HOST_NAME=$(hostname 2>> ${LOG_FILE})\n    if [ -z \"$HOST_NAME\" ]; then\n        RETURN_VALUE=1\n        LOG \"The hostname is NULL. Cannot proceed with the installation.\"\n        log_to_json_file ASRMobilityServiceHostNameNotSet \"Mobility Service  Setup was unable to procced as the hostname on the VM is not set. Set the host name on the VM.\"\n        RecordOP 99 \"Hostname is NULL\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Make sure secure boot is not enabled.\ncheck_secure_boot()\n{\n    LOG \"Checking for secure boot\"\n\n    SetOP \"CheckSecureBoot\"\n    which mokutil\n    if [ $? -eq \"0\" ]; then\n        local mokutil_output=`mokutil --sb-state 2>&1`\n        if [[ $mokutil_output == *\"SecureBoot enabled\"* ]]; then\n            RETURN_VALUE=1\n            LOG \"Secure Boot is enabled for the system. Cannot proceed with the installation.\"\n            log_to_json_file ASRMobilityServiceSecureBootEnabled \"Mobility Service setup was unable to procced as secure boot is enabled on the system.\" VMName $HOST_NAME\n            RecordOP 99 \"Secure Boot is enabled.\"\n            return\n        fi\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check for runlevel. If it is null abort\ncheck_runlevel()\n{\n\tLOG \"Checking Runlevel for null\"\n\t\n\tSetOP \"CheckRunlevel\"\n\t# Check for systemd\n    which systemctl > /dev/null 2>&1\n    if [ $? -eq 0 ]\n    then\n        # The 'runlevel' command in systemd works different than\n        # sysvinit runlevels. On systemd, the a specific runlevel\n        # is only returned when it is reached, while sysvinit would\n        # return it as soon as the switch was requested. IOW, runlevel\n        # is changed at start in sysv init and at the end by systemd\n        # so we cant rely on runlevel command for systemd\n        #\n        # We check if shutdown.target (common for reboot and poweroff)\n        # is currently active to set appropriate runlevel. Current logic\n        # does not distinguish between poweroff and reboot and always\n        # marks runlevel=0 == poweroff. Similarly, it always returns\n        # runlevel=3 == multiuser+nw even for graphical env or single\n        # user mode. This needs to be changed if finer distinction is \n        # required.\n        #\n        systemctl list-units --type=target | grep start | grep -q \"shutdown\\.target\" && RUNLEVEL=0 || RUNLEVEL=3\n    else\n        # RUNLEVEL variable is set only when this control script is invoked by init\n        # Other times, we have to fetch the runlevel ourselves\n        RUNLEVEL=${RUNLEVEL:-`/sbin/runlevel | cut -d' ' -f2`}\n    fi\n\t\n\tif [ -z \"$RUNLEVEL\" ] || [ \"$RUNLEVEL\" -ne 2 -a \"$RUNLEVEL\" -ne 3 -a \"$RUNLEVEL\" -ne 5 ]; then\n\t\tif [ -z \"$RUNLEVEL\" ]; then\n\t\t\trunlevel=\"null\"\n\t\telse runlevel=$RUNLEVEL\n\t\tfi\n\t\tRETURN_VALUE=1\n\t\tLOG \"runlevel cannot be retrived, or is not equal to 2,3 or 5. Cannot proceed with installation. Current runlevel $runlevel\"\n\t\tlog_to_json_file ASRMobilityServiceRunlevelCommandFailure \"Please make sure that runlevel of the system can be retrived and is set to 2, 3 or 5\" Runlevel ${runlevel}\n\t\tRecordOP 99 \"Runlevel is $runlevel\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check sufficient space on root is available or not\ncheck_free_space_on_root()\n{\n    LOG \"Checking for free free space availability\"\n\n    SetOP \"CheckFreeSpaceOnRoot\"\n    free_space=`echo ${Params[${IDX}]} | ${JQ} '.FreeSpace' | awk -F\"\\\"\" '{print $2}'`\n    if [ -z \"${free_space}\" ]; then\n        LOG \"Freespace needed is not specified in the configuration JSON file\"\n        free_space=${MIN_ROOT_FREESPACE_KB}\n    fi\n\n    free_space_on_root=$(df -Pk / 2>> ${LOG_FILE} | sed -n '2p' | awk '{print $4}')\n    LOG \"Free space needed on root file-system is ${free_space}KB and actual free space available is ${free_space_on_root}KB\"\n    if [ ${free_space_on_root} -lt ${free_space} ]; then\n        RETURN_VALUE=1\n        LOG \"At least ${free_space}KB of free space is required on \\\"/\\\"\"\n        log_to_json_file ASRMobilityServiceFreeSpaceOnRootNotSufficient \"Insufficient free space available on the root file-system(/). Ensure that there is at least ${free_space}KB free space available on the root file-system before you try to protect the virtual machine again.\" FreeSpace ${free_space}\n        RecordOP 99 \"Root file-system has less than ${free_space}KB free space\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the LIS components are installed or not\ncheck_lis_drivers_available()\n{\n    LOG \"Checking for LIS drivers availability\"\n\n    SetOP \"CheckLisDriversAvailable\"\n    drivers=`echo ${Params[${IDX}]} | ${JQ} '.Drivers' | awk -F\"\\\"\" '{print $2}'`\n    if [ -z \"${drivers}\" ]; then\n        drivers=\"hv_storvsc.ko\"\n    fi\n\n    if [ ${PLATFORM} = \"Azure\" ]; then\n        LOG \"Check for LIS driver(s) ${drivers} is skipped as the platform is Azure\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    LOG \"Checking for LIS driver(s) ${drivers}\"\n    if [ \"$OS\" = \"RHEL5-64\" -o \"$OS\" = \"RHEL6-64\" ]; then\n        KERNEL=`uname -r`\n        for drv in `echo ${drivers} | sed 's/,/ /g'`\n        do\n            if [ \"$OS\" = \"RHEL5-64\" ]; then\n                (zcat /boot/initrd-${KERNEL}.img | cpio -itv) 2> /dev/null | grep -q ${drv}\n            else\n                lsinitrd /boot/initramfs-${KERNEL}.img | grep -q ${drv}\n            fi\n\n            if [ $? -ne \"0\" ]; then\n                RETURN_VALUE=1\n                LOG \"Linux Integration Services(LIS) components are not installed on this server. Please install them and retry installation. For more details please refer https://aka.ms/asr-os-support\"\n                log_to_json_file ASRMobilityServiceLisDriversNotAvailable \"The necessary Hyper-V Linux Integration Services components are not installed on this machine. Install the Linux Integration service components on this machine and retry the operation. Read more about Linux Integration services https://blogs.technet.microsoft.com/virtualization/2016/07/12/which-linux-integration-services-should-i-use-in-my-linux-vms/\"\n\n                RecordOP 99 \"LIS components are not installed\"\n                return\n            fi\n        done\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if ubuntu 16.04 kernel is upgraded to 4.15 to support RHEL8\ncheck_mt_kernel_version()\n{\n    SetOP \"CheckMTKernelVersion\"\n    CURR_KERNEL=`uname -r`\n\n    if [ \"$OS\" = \"UBUNTU-16.04-64\" ]; then \n        _kernel=`uname -r | cut -f 1-2 -d \".\"`\n        if [ \"$_kernel\" != \"4.15\" ]; then\n            LOG \"FAILED: Please retry after upgrading the kernel using following command and rebooting to new kernel\"\n            LOG \"        apt-get install linux-image-generic-hwe-16.04\"\n            echo \"FAILED: Please retry after upgrading the kernel using following command and rebooting to new kernel\"\n            echo \"        apt-get install linux-image-generic-hwe-16.04\"\n            RecordOP 99 \"Kernel not upgraded\"\n            RETURN_VALUE=1\n            return 1\n        fi\n    fi\n    \n    RecordOP 0 \"\"\n    return 0\n}\n\nis_supported_rhel8_kernel()\n{\n    CURR_KERNEL=$1\n    EXTRA_VER1=$2\n    EXTRA_VER2=$3\n\n    ret=1\n    extra_minor1=`echo ${CURR_KERNEL} | awk -F\".\" '{print $4}'`\n    extra_minor2=`echo ${CURR_KERNEL} | awk -F\".\" '{print $5}'`\n    if [ ! -z $extra_minor1 -a $extra_minor1 -eq $extra_minor1 ] 2> /dev/null; then\n        if [ $extra_minor1 -gt $EXTRA_VER1 ]; then\n            ret=0\n        elif [ $extra_minor1 -eq $EXTRA_VER1 ]; then\n            if [ ! -z $extra_minor2 -a $extra_minor2 -eq $extra_minor2 ] 2> /dev/null; then\n                if [ $extra_minor2 -ge $EXTRA_VER2 ]; then\n                    ret=0\n                fi\n            fi\n        fi\n    fi\n\n    return $ret\n}\n\n# Check if the current running kernel is a supported one or not\ncheck_current_kernel_supported()\n{\n    LOG \"Check if the current running kernel is supported\"\n\n    SetOP \"CheckKernelSupported\"\n    CURR_KERNEL=`uname -r`\n    LOG \"Current running kernel is ${CURR_KERNEL}\"\n\n    ret=1\n    case ${OS} in\n        \"RHEL5-64\")\n            echo ${CURR_KERNEL} | grep -q \"^2.6.18\" && (echo ${CURR_KERNEL} | egrep -q '.el5$|.el5xen$')\n            if [ $? -eq \"0\" ]; then\n                minor_version=`echo ${CURR_KERNEL} | awk -F\"-\" '{print $2}' | awk -F\".\" '{print $1}'`\n                if [ ${minor_version} -ge \"92\" -o ${minor_version} -le \"398\" ]; then\n                    ret=0\n                fi\n            fi\n            ;;\n\n        \"RHEL6-64\")\n            echo ${CURR_KERNEL} | grep -q \"^2.6.32\" && (echo ${CURR_KERNEL} | egrep -q '.el6.x86_64$|.el6.centos.plus.x86_64$')\n            if [ $? -eq \"0\" ]; then\n                minor_version=`echo ${CURR_KERNEL} | awk -F\"-\" '{print $2}' | awk -F\".\" '{print $1}'`\n                if [ ${minor_version} -ge \"71\" -a ${minor_version} -le \"754\" ]; then\n                    ret=0\n                fi\n            fi\n            ;;\n\n        \"RHEL7-64\")\n            echo ${CURR_KERNEL} | grep -q \".el7.x86_64$\"\n            ret=$?\n            ;;\n\n        \"RHEL8-64\")\n            echo ${CURR_KERNEL} | grep -q \".el8.*\"\n            if [ $? -eq \"0\" ]; then\n               minor_version=`echo ${CURR_KERNEL} | awk -F\"-\" '{print $2}' | awk -F\".\" '{print $1}'`\n               case ${minor_version} in\n                   \"305\")\n                       is_supported_rhel8_kernel ${CURR_KERNEL} 30 1\n                       if [ $? -eq \"0\" ]; then\n                           ret=0\n                       fi\n                       ;;\n\n                   \"348\")\n                       is_supported_rhel8_kernel ${CURR_KERNEL} 5 1\n                       if [ $? -eq \"0\" ]; then\n                           ret=0\n                       fi\n                       ;;\n\n                   *)\n                       ret=0\n                       ;;\n               esac\n            fi\n            ;;\n\n        \"OL7-64\")\n            echo ${CURR_KERNEL} | egrep -q \".el7.x86_64$|.el7uek.x86_64\"\n            ret=$?\n            ;;\n\n        \"OL8-64\")\n            echo ${CURR_KERNEL} | grep -q \".el8uek.x86_64\"\n            if [ $? -eq \"0\" ]; then\n                ret=0\n            else\n                echo ${CURR_KERNEL} | grep -q \".el8.*\"\n                if [ $? -eq \"0\" ]; then\n                    minor_version=`echo ${CURR_KERNEL} | awk -F\"-\" '{print $2}' | awk -F\".\" '{print $1}'`\n                    if [ ${minor_version} -ge \"80\" -a ${minor_version} -le \"348\" ]; then\n                        case ${minor_version} in\n                            \"305\")\n                                is_supported_rhel8_kernel ${CURR_KERNEL} 30 1\n                                if [ $? -eq \"0\" ]; then\n                                    ret=0\n                                fi\n                                ;;\n\n                            \"348\")\n                                is_supported_rhel8_kernel ${CURR_KERNEL} 5 1\n                                if [ $? -eq \"0\" ]; then\n                                    ret=0\n                                fi\n                                ;;\n\n                            *)\n                                ret=0\n                                ;;\n                        esac\n                    fi\n                fi\n            fi\n\n            ;;\n\n        \"SLES11-SP3-64\"|\"SLES11-SP4-64\")\n            echo ${CURR_KERNEL} | grep -q \"^3.0\" && (echo ${CURR_KERNEL} | egrep -q '\\-default$|-xen$')\n            ret=$?\n            ;;\n\n        \"OL6-64\")\n            echo ${CURR_KERNEL} | grep -q \"^2.6.32\" && (echo ${CURR_KERNEL} | grep -q \".el6.x86_64$\")\n            if [ $? -eq \"0\" ]; then\n                minor_version=`echo ${CURR_KERNEL} | awk -F\"-\" '{print $2}' | awk -F\".\" '{print $1}'`\n                if [ ${minor_version} -ge \"358\" -a ${minor_version} -le \"754\" ]; then\n                    ret=0\n                fi\n            fi\n\n            if [ ${ret} -eq \"1\" ]; then\n                echo ${CURR_KERNEL} | grep -q \"^3.8.13\" && (echo ${CURR_KERNEL} | grep -q \".el6uek.x86_64\")\n                ret=$?\n            fi\n            \n            if [ ${ret} -eq \"1\" ]; then\n                echo ${CURR_KERNEL} | grep -q \"^4.1.12\" && (echo ${CURR_KERNEL} | grep -q \".el6uek.x86_64\")\n                ret=$?\n            fi\n            ;;\n\n        UBUNTU*|DEBIAN*)\n            if [ -f \"${Supported_Kernels}\" ]; then\n                while read ker\n                do\n                    if [ ${CURR_KERNEL} = \"${ker}\" ]; then\n                        ret=0\n                        break\n                    fi\n                done < ${Supported_Kernels}\n            fi\n            ;;\n\n        \"SLES12-64\"|\"SLES15-64\")\n            echo ${CURR_KERNEL} | grep -q \"\\-default$\"\n            ret=$?\n\n            if [ ${ret} -ne \"0\" -a -f \"${Supported_Kernels}\" ]; then\n                grep -q \"^${CURR_KERNEL}:\" ${Supported_Kernels}\n                ret=$?\n            fi\n    esac\n\n    if [ ${ret} -ne \"0\" ]; then\n        RETURN_VALUE=1\n        LOG \"This version of mobility service doesn't support the operating system kernel version (${CURR_KERNEL}) running on the source machine. Please refer the list of operating systems supported by Azure Site Recovery : https://aka.ms/asr-os-support\"\n        log_to_json_file ASRMobilityServiceKernelNotSupported \"This version of mobility service doesn't support the operating system kernel version (${CURR_KERNEL}) running on the source machine. Please refer the list of operating systems supported by Azure Site Recovery : https://aka.ms/asr-os-support\" KernelVersion ${CURR_KERNEL}\n        RecordOP 99 \"This version of mobility service doesn't support the operating system kernel version (${CURR_KERNEL}) running on the source machine.\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the current running kernel's directory exists under /lib/modules path\ncheck_kernel_directory_exists()\n{\n    LOG \"Checking if the directory for the current running kernel exists under /lib/modules\"\n\n    SetOP \"CheckKernelDirectoryExists\"\n    DRV_PATH=\"/lib/modules/`uname -r`/kernel/drivers/char\"\n    if [ ! -d \"${DRV_PATH}\" ]; then\n        RETURN_VALUE=1\n        LOG \"The directory for the current running kernel (`uname -r`) doesn't exist under /lib/modules/ path. Install the current kernel package forcefully.\"\n        log_to_json_file ASRMobilityServiceKernelDirectoryNotExist \"The directory for the current running kernel (`uname -r`) doesn't exist under /lib/modules/ path. Install the current kernel package forcefully.\" KernelVersion `uname -r`\n        RecordOP 99 \"The directory for the current running kernel (`uname -r`) doesn't exist under /lib/modules/ path.\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Finds all the devices listed by dmsetup with type \"multipath\"\nfind_multipath_devices()\n{\n    LOG \"Finding multipath devices\"\n\n    :> ${TEMP_FILE}\n    (dmsetup table 2>> ${LOG_FILE} | grep -v 'No devices found') > ${TEMP_FILE}\n\n    LOG \"The dmsetup output:\"\n    LOG \"`echo;cat ${TEMP_FILE}`\"\n\n    idx=0\n    while read line\n    do\n        type=`echo ${line} | awk '{print $4}'`\n        if [ ${type} != \"multipath\" ]; then\n            continue\n        fi\n\n        dev=`echo ${line} | awk -F\":\" '{print $1}'`\n        if [ ! -e \"/dev/mapper/${dev}\" ]; then\n            continue\n        fi\n\n        MULIPATH_DEVICES[${idx}]=\"/dev/mapper/${dev}\"\n        MULIPATH_DEVICES_DEVT[${idx}]=`echo ${line} | awk '{print $13}'`\n        idx=`expr ${idx} + 1`\n    done < ${TEMP_FILE}\n\n    if [ ${#MULIPATH_DEVICES[*]} -eq \"0\" ]; then\n        LOG \"No multipath disks found\"\n    else\n        LOG \"Multipath Disks: ${MULIPATH_DEVICES[@]}\"\n        LOG \"Multipath Disk Devt: ${MULIPATH_DEVICES_DEVT[@]}\"\n    fi\n}\n\n# Finds all the linear devices except the ones are the partitions\nfind_linear_devices()\n{\n    LOG \"Finding linear devices\"\n\n    :> ${TEMP_FILE}\n    (dmsetup table 2>> ${LOG_FILE} | grep -v 'No devices found') > ${TEMP_FILE}\n\n    idx=0\n    while read line\n    do\n        type=`echo ${line} | awk '{print $4}'`\n        if [ ${type} != \"linear\" -a ${type} != \"crypt\" ]; then\n            continue\n        fi\n\n        dev=`echo ${line} | awk -F\":\" '{print $1}'`\n        if [ ! -e \"/dev/mapper/${dev}\" ]; then\n            continue\n        fi\n\n\n        skip=0\n        midx=0\n        while [ ${midx} -lt ${#MULIPATH_DEVICES[*]} ]\n        do\n            pnum=\"\"\n            mdev=`basename ${MULIPATH_DEVICES[${midx}]}`\n            echo ${dev} | grep -q \"^${mdev}_part\"\n            if [ $? -eq \"0\" ]; then\n                pnum=`echo ${dev} | awk -F\"_part\" '{print $2}'`\n            else\n                echo ${dev} | grep -q \"^mpath\" && echo ${mdev} | grep -q \"^mpath\"\n                if [ $? -eq \"0\" ]; then\n                    pnum=`echo ${dev} | awk -F\"${mdev}\" '{print $2}'`\n                else\n                    echo ${dev} | grep -q \"^${mdev}p\"\n                    if [ $? -eq \"0\" ]; then\n                        pnum=`echo ${dev} | awk -F\"p\" '{print $2}'`\n                    fi\n                fi\n            fi\n\n            if [ -z \"${pnum}\" ]; then\n                pnum=\"non-digit\"\n                skip=0\n            fi\n\n            if [[ ${pnum} =~ [^[:digit:]] ]]; then\n                skip=0\n            else\n                skip=1\n                break\n            fi\n\n            midx=`expr ${midx} + 1`\n        done\n\n        if [ ${skip} -eq \"1\" ]; then\n            continue\n        fi\n\n        LINEAR_DEVICES[${idx}]=\"/dev/mapper/${dev}\"\n        LINEAR_DEVICE_TYPE[${idx}]=${type}\n        idx=`expr ${idx} + 1`\n    done < ${TEMP_FILE}\n\n    if [ ${#LINEAR_DEVICES[*]} -eq \"0\" ]; then\n        LOG \"No linear devices found\"\n    else\n        LOG \"Linear Devices: ${LINEAR_DEVICES[@]}\"\n        LOG \"Linear Device Type: ${LINEAR_DEVICE_TYPE[@]}\"\n    fi\n}\n\n# Finds all the full disks with its partitions and the boot disk\nfind_devices()\n{\n    LOG \"Finding full disks with partitions and the boot disks\"\n\n    :> ${TEMP_FILE}\n    (sfdisk -luS 2>> ${LOG_FILE} | grep -e '/dev/' | grep -v Empty) > ${TEMP_FILE}\n\n    LOG \"The output of command \\\"sfdisk -luS 2> /dev/null | grep -e '/dev/' | grep -v Empty\\\" is\"\n    LOG \"`echo;cat ${TEMP_FILE}`\"\n\n    boot_disk=\"\"\n    partitions=\"\"\n    bootable=0\n    dev_idx=-1\n    skip=0\n    while read line\n    do\n        echo ${line} | grep -q \"^Disk\"\n        if [ $? -eq \"0\" ]; then\n            if [ ! -z \"${partitions}\" ]; then\n                DEVICES[${dev_idx}]=`echo \"${DEVICES[${dev_idx}]}:${bootable}${partitions}\"`\n            fi\n\n            disk=`echo ${line} | awk '{print $2}' | awk -F\":\" '{print $1}'`\n            bootable=0\n            partitions=\"\"\n            idx=0\n            found=1\n            skip=0\n            while [ ${idx} -lt ${#LINEAR_DEVICES[*]} ]\n            do\n                if [ \"${disk}\" = \"${LINEAR_DEVICES[${idx}]}\" ]; then\n                    found=0\n                    skip=1\n                    break\n                fi\n\n                idx=`expr ${idx} + 1`\n            done\n\n            if [ ${found} -eq \"0\" ]; then\n                continue\n            fi\n\n            disk_base=`basename ${disk}`\n            if [ -e \"/sys/block/${disk_base}/dev\" ]; then\n                devt=`cat /sys/block/${disk_base}/dev`\n            else\n                devt=\"\"\n            fi\n\n            is_multipath_disk=0\n            idx=0\n            while [ ${idx} -lt ${#MULIPATH_DEVICES[*]} ]\n            do\n                if [ \"${disk}\" = \"${MULIPATH_DEVICES[${idx}]}\" ]; then\n                    is_multipath_disk=1\n                    break\n                fi\n\n                if [ ! -z \"${devt}\" -a \"${devt}\" = \"${MULIPATH_DEVICES_DEVT[${idx}]}\" ]; then\n                    found=0\n                    skip=1\n                    break\n                fi\n\n                idx=`expr ${idx} + 1`\n            done\n\n            if [ ${found} -eq \"1\" ]; then\n                partitions=\":\"\n                dev_idx=`expr ${dev_idx} + 1`\n\n                LOG \"Executing the command \\\"${GFDISK} ${disk} 2>> ${LOG_FILE}\\\"\"\n                gpartdevs=`${GFDISK} ${disk} 2>> ${LOG_FILE}`\n                if [ $? -eq \"0\" ]; then\n                    gpartdevs=`echo ${gpartdevs} | sed 's/\\n/ /g'`\n                    LOG \"The disk ${disk} has GPT partitions ${gpartdevs}\"\n                    skip=1\n                    for gpdev in ${gpartdevs}\n                    do\n                        if [ \"${partitions}\" = \":\" ]; then\n                            partitions=`echo \"${partitions}${gpdev}\"`\n                        else\n                            partitions=`echo \"${partitions},${gpdev}\"`\n                        fi\n                    done\n                fi\n\n                DEVICES[${dev_idx}]=\"${disk}\"\n            fi\n\n            continue\n        fi\n\n        if [ ${skip} -eq \"1\" ]; then\n            continue\n        fi\n\n        dev=`echo ${line} | awk '{print $1}'`\n        if [ ! -e \"${dev}\" ]; then\n            LOG \"The partition ${dev} of ${disk} doesn't exist. Checking for _part device.\"\n\n            if [ ${is_multipath_disk} -eq \"1\" ]; then\n                basename ${dev} | grep -q \"^mpath\" && basename ${dev} | grep -q \"^${disk_base}\"\n                if [ $? -eq \"0\" ]; then\n                    basename ${dev} | grep -q \"^${disk_base}\"\n                    pnum=`basename ${dev} | awk -F\"${disk_base}\" '{print $2}'`\n                    base_dev=\"${disk_base}\"\n                else\n                    basename ${dev} | grep -q \"^${disk_base}p\"\n                    if [ $? -eq \"0\" ]; then\n                        pnum=`basename ${dev} | awk -F\"p\" '{print $2}'`\n                        base_dev=`basename ${dev} | awk -F\"p\" '{print $1}'`\n                    else\n                        continue\n                    fi\n                fi\n\n                temp_dev=`dirname ${dev}`\n                dev=\"${temp_dev}/${base_dev}_part${pnum}\"\n                if [ ! -e \"${dev}\" ]; then\n                    LOG \"The _part device partition ${dev} of ${disk} doesn't exist.\"\n                    continue\n                fi\n\n                LOG \"The _part device ${dev} for ${disk} exists.\"\n            else\n                continue\n            fi\n        fi\n\n        if [ \"${partitions}\" = \":\" ]; then\n            partitions=`echo \"${partitions}${dev}\"`\n        else\n            partitions=`echo \"${partitions},${dev}\"`\n        fi\n    done < ${TEMP_FILE}\n\n    if [ ! -z \"${partitions}\" ]; then\n        DEVICES[${dev_idx}]=`echo \"${DEVICES[${dev_idx}]}:${bootable}${partitions}\"`\n    fi\n\n    if [ ${#DEVICES[*]} -eq \"0\" ]; then\n        LOG \"No Full disks found\"\n    else\n        LOG \"Full disks: ${DEVICES[@]}\"\n    fi\n}\n\n# Checks if the command exists\nis_command_exist()\n{\n    command=$1\n    path=$(which ${command} 2>> ${LOG_FILE})\n    if [ -e \"${path}\" ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n# Provided an LV device, finds the associated full disks\nfind_full_disks_of_lv()\n{\n    lv_dev=$1\n    LOG \"Finding full disk for the LV device ${lv_dev}\"\n\n    lv_disk=\"\"\n    SAME_PV=1\n    NR_PVS=0\n    PVS=\"\"\n\n    vg_name=`lvdisplay ${lv_dev} 2>> ${LOG_FILE} | grep \"VG Name\" | awk '{print $3}'`\n    LOG \"VG name for LV ${lv_dev} is ${vg_name}\"\n    LOG \"The output of command \\'vgdisplay -v ${vg_name}\\' is `echo; vgdisplay -v ${vg_name} 2>> ${LOG_FILE}`\"\n    for pv in `vgdisplay -v ${vg_name} 2>> ${LOG_FILE} | grep \"PV Name\" | awk '{print $3}'`\n    do\n        echo ${pv} | grep -q \"^/dev/\"\n        if [ $? -ne \"0\" ]; then\n            continue\n        fi\n\n        idx=0\n        while [ ${idx} -lt ${#DEVICES[*]} ]\n        do\n            disk=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $1}'`\n            parts=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $3}'`\n            parts=`echo ${parts} | sed 's/,/ /g'`\n\n            devices=`echo \"${disk} ${parts}\"`\n\n            for dev in `echo ${devices}`\n            do\n                if [ \"${pv}\" = \"${dev}\" ]; then\n                    if [ -z \"${PVS}\" ]; then\n                        PVS=\"${disk}\"\n                        lv_disk=\"${disk}\"\n                        NR_PVS=1\n                    else\n                        if [ \"${lv_disk}\" != \"${disk}\" ]; then\n                            SAME_PV=0\n                            found=0\n                            for root_dev in `echo ${PVS}`\n                            do\n                                if [ ${root_dev} = \"${disk}\" ]; then\n                                    found=1\n                                    break\n                                fi\n                            done\n\n                            if [ ${found} -eq \"0\" ]; then\n                                NR_PVS=`expr ${NR_PVS} + 1`\n                                PVS=`echo ${PVS},${disk}`\n                            fi\n                        fi\n                    fi\n\n                    break\n                fi\n            done\n\n            idx=`expr ${idx} + 1`\n        done\n    done\n}\n\n# Finds the full disk that hosts the boot-filesystem partition or volume \nfind_boot_disk()\n{\n    LOG \"Finding the boot disk\"\n\n    mount | awk '{print $1,$3,$5}' | grep -v \"/boot/\" | grep -qw \"/boot\"\n    if [ $? -eq \"1\" ]; then\n        if [ -d \"/boot\" ]; then\n            SAME_BOOT_DISK=1\n            BOOT_DISKS=${ROOT_DEV}\n            BOOT_DEV=${ROOT_DEV}\n            NR_BOOTABLE_DISKS=${NR_ROOT_DISKS}\n            BOOT_FULL_DISKS=${ROOT_DISKS}\n            IS_BOOT_LVM=${IS_ROOT_LVM}\n            LOG \"/boot is part of /, NR_BOOTABLE_DISKS=${NR_BOOTABLE_DISKS}, BOOT_FULL_DISKS=${BOOT_FULL_DISKS}, IS_BOOT_LVM=${IS_BOOT_LVM}\"\n        else\n            LOG \"/boot is not a directory\"\n        fi\n\n        return\n    fi\n\n    # For btrfs, same volume can be mounted at different mount points.\n    BOOT_DEV=`mnt_to_dev /boot`\n    boot_link_dev=`readlink -f $BOOT_DEV`\n    root_link_dev=`readlink -f $ROOT_DEV`\n    if [ \"$boot_link_dev\" = \"$root_link_dev\" ]; then\n            SAME_BOOT_DISK=1\n            BOOT_DISKS=${ROOT_DEV}\n            BOOT_DEV=${ROOT_DEV}\n            NR_BOOTABLE_DISKS=${NR_ROOT_DISKS}\n            BOOT_FULL_DISKS=${ROOT_DISKS}\n            IS_BOOT_LVM=${IS_ROOT_LVM}\n            LOG \"/boot is part of /, NR_BOOTABLE_DISKS=${NR_BOOTABLE_DISKS}, BOOT_FULL_DISKS=${BOOT_FULL_DISKS}, IS_BOOT_LVM=${IS_BOOT_LVM}\"\n            return\n    fi\n\n    LOG \"/boot is a mount point not part of /\"\n    for dev in `mount | awk '{print $1,$3}' | grep -w \"/boot\" | grep -v \"/boot/\" | awk '{print $1}'`\n    do\n        if [ -b ${dev} ]; then\n            BOOT_DISKS=${dev}\n            break\n        fi\n    done\n    LOG \"The device mounted on /boot is ${BOOT_DISKS}\"\n    boot_link_dev=`readlink -f ${BOOT_DISKS}`\n\n    idx=0\n    while [ ${idx} -lt ${#DEVICES[*]} ]\n    do\n        parts=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $3}'`\n        if [ -z \"${parts}\" ]; then\n            idx=`expr ${idx} + 1`\n            continue\n        fi\n\n        for dev in `echo ${parts} | sed 's/,/ /g'`\n        do\n            link_dev=`readlink -f ${dev}`\n            if [ \"${boot_link_dev}\" = \"${link_dev}\" ]; then\n                BOOT_FULL_DISKS=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $1}'`\n                BOOT_DEV=${boot_link_dev}\n                NR_BOOTABLE_DISKS=1\n                LOG \"Boot is on partition, SAME_BOOT_DISK=${SAME_BOOT_DISK}, BOOT_DISKS=${BOOT_DISKS}, BOOT_DEV=${BOOT_DEV}, BOOT_FULL_DISKS=${BOOT_FULL_DISKS}, NR_BOOT_DISKS=${NR_BOOTABLE_DISKS}\"\n                return\n            fi\n        done\n\n        idx=`expr ${idx} + 1`\n    done\n\n    idx=0\n    while [ ${idx} -lt ${#LINEAR_DEVICES[*]} ]\n    do\n        lvm_dev=\"${LINEAR_DEVICES[${idx}]}\"\n        linear_link_dev=`readlink -f ${lvm_dev}`\n        if [ \"${boot_link_dev}\" = \"${linear_link_dev}\" ]; then\n            IS_BOOT_ON_LV=1\n            is_command_exist vgdisplay\n            if [ $? -eq \"0\" ]; then\n                IS_LVM_PACKAGE_AVAILABLE=0\n                return\n            fi\n\n            LOG \"The output of \\'lvdisplay ${lvm_dev}\\'\"\n            lvdisplay ${LINEAR_DEVICES[${idx}]} >> ${LOG_FILE} 2>&1\n            if [ $? -ne \"0\" ]; then\n                LOG \"find_boot_disk: lvdisplay failed\"\n                return\n            fi\n\n            find_full_disks_of_lv ${lvm_dev}\n            SAME_BOOT_DISK=${SAME_PV}\n            BOOT_FULL_DISKS=${PVS}\n            NR_BOOTABLE_DISKS=${NR_PVS}\n            BOOT_DEV=${lvm_dev}\n            IS_BOOT_LVM=1\n            LOG \"Boot is on LV, SAME_BOOT_DISK=${SAME_BOOT_DISK}, BOOT_FULL_DISKS=${BOOT_FULL_DISKS}, BOOT_DEV=${BOOT_DEV}, NR_BOOT_DISKS=${NR_BOOTABLE_DISKS}\"\n            return\n        fi\n\n        idx=`expr $idx + 1`\n    done\n}\n\n# Finds the full disk that hosts the root-filesystem partition or volume\nfind_system_disk()\n{\n    LOG \"Finding the system disk\"\n\n    dev=$(mnt_to_dev /)\n    if [ -b ${dev} ]; then\n        ROOT_DEV=${dev}\n        ROOT_FS=`dev_to_fs $dev`\n        LOG \"Root filesystem is ${ROOT_FS}\"\n    fi\n    \n    LOG \"The device mounted on / is ${ROOT_DEV}\"\n    root_link_dev=`readlink -f ${ROOT_DEV}`\n    root_link_dev_uuid=`blkid -s UUID -o value $root_link_dev`\n\n    idx=0\n    while [ ${idx} -lt ${#DEVICES[*]} ]\n    do\n        parts=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $3}'`\n        if [ -z \"${parts}\" ]; then\n            idx=`expr ${idx} + 1`\n            continue\n        fi\n\n        for dev in `echo ${parts} | sed 's/,/ /g'`\n        do\n            link_dev=`readlink -f ${dev}`\n            link_dev_uuid=`blkid -s UUID -o value $link_dev`\n            if [ \"${root_link_dev}\" = \"${link_dev}\" -o \"${root_link_dev_uuid}\" = \"${link_dev_uuid}\" ]; then\n                ROOT_DISKS=`echo ${DEVICES[${idx}]} | awk -F\":\" '{print $1}'`\n                NR_ROOT_DISKS=1\n                LOG \"Root is on partition, SAME_ROOT_DISK=${SAME_ROOT_DISK}, ROOT_DISKS=${ROOT_DISKS}, ROOT_DEV=${root_link_dev}, NR_ROOT_DISKS=${NR_ROOT_DISKS}\"\n                return\n            fi\n        done\n\n        idx=`expr ${idx} + 1`\n    done\n\n    idx=0\n    while [ ${idx} -lt ${#LINEAR_DEVICES[*]} ]\n    do\n        lvm_dev=\"${LINEAR_DEVICES[${idx}]}\"\n        linear_link_dev=`readlink -f ${lvm_dev}`\n        linear_link_dev_uuid=`blkid -s UUID -o value $linear_link_dev`\n        if [ \"${root_link_dev}\" = \"${linear_link_dev}\" -o \"${root_link_dev_uuid}\" = \"${linear_link_dev_uuid}\" ]; then\n            IS_ROOT_ON_LV=1\n            is_command_exist vgdisplay\n            if [ $? -eq \"0\" ]; then\n                IS_LVM_PACKAGE_AVAILABLE=0\n                return\n            fi\n\n            LOG \"The output of \\'lvdisplay ${lvm_dev}\\'\"\n            lvdisplay ${LINEAR_DEVICES[${idx}]} >> ${LOG_FILE} 2>&1\n            if [ $? -ne \"0\" ]; then\n                LOG \"find_system_disk: lvdisplay failed\"\n                return\n            fi\n\n            find_full_disks_of_lv ${lvm_dev}\n            SAME_ROOT_DISK=${SAME_PV}\n            ROOT_DISKS=${PVS}\n            NR_ROOT_DISKS=${NR_PVS}\n            IS_ROOT_LVM=1\n            LOG \"Root is on LV, SAME_ROOT_DISK=${SAME_ROOT_DISK}, ROOT_DISKS=${ROOT_DISKS}, ROOT_DEV=${lvm_dev}, NR_ROOT_DISKS=${NR_ROOT_DISKS}\"\n            return\n        fi\n\n        idx=`expr $idx + 1`\n    done\n\n    LOG \"System disk is not found\"\n}\n\n# Collects the boot and system disks information\ncollect_volume_info()\n{\n    # DON\"T CHNAGE THE ORDER\n    find_multipath_devices\n    find_linear_devices\n    find_devices\n    find_system_disk\n    find_boot_disk\n}\n\n\n# Check if the system disk exists\ncheck_system_disk_available()\n{\n    LOG \"Check if the system disk is available\"\n\n    SetOP \"CheckSystemDiskAvailable\"\n    if [ ${NR_ROOT_DISKS} -eq \"0\" ]; then\n        RETURN_VALUE=1\n        LOG \"The system/root disk is not available. Check if any device is mounted on /.\"\n        log_to_json_file ASRMobilityServiceSystemDiskNotFound \"The system/root disk is not available. Check if any device is mounted on /.\"\n        RecordOP 99 \"The system/root disk is not available\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the boot disk exists\ncheck_boot_disk_available()\n{\n    LOG \"Check if the boot disk is available\"\n\n    SetOP \"CheckBootDiskAvailable\"\n    if [ ${NR_BOOTABLE_DISKS} -eq \"0\" ]; then\n        RETURN_VALUE=1\n        LOG \"The boot disk is not available. Create a bootable partition.\"\n        log_to_json_file ASRMobilityServiceBootDiskNotFound \"The boot disk is not available. Create a bootable partition.\"\n        RecordOP 99 \"The boot disk is not available\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the LVM related commands exist\ncheck_lvm_package_available()\n{\n    LOG \"Check if the LVM package installed\"\n\n    SetOP \"CheckLVMPackageInstalled\"\n    if [ ${IS_ROOT_ON_LV} -eq \"0\" ]; then\n        LOG \"Skipping the check LVMPackageInstalled as root file-system is not laid on an LV\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    is_command_exist vgdisplay\n    if [ $? -eq \"0\" ]; then\n        RETURN_VALUE=1\n        LOG \"LVM package is missing. Install the lvm2 package and reboot the VM before trying to protect again.\"\n        log_to_json_file ASRMobilityServiceLvmPackageMissing \"LVM package is missing. Install the lvm2 package and reboot the VM before trying to protect again.\"\n        RecordOP 99 \"LVM package is missing\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\ncheck_boot_on_lvm_from_multiple_disks()\n{\n    LOG \"Check if the boot is configured on LVM device which is coming from multiple full disks\"\n\n    SetOP \"CheckBootOnLVMFromMultipleDisks\"\n    if [ ${IS_BOOT_LVM} -eq \"1\" -a ${NR_BOOTABLE_DISKS} -gt \"1\" ]; then\n        RETURN_VALUE=1\n        LOG \"The /boot is configured on an LVM device (${BOOT_DEV}) and this LVM device is created using multiple disks (${BOOT_FULL_DISKS})\"\n        log_to_json_file ASRMobilityServiceBootOnLVMFromMultipleDisks \"The /boot is configured on an LVM device (${BOOT_DEV}) and this LVM device is created using multiple disks (${BOOT_FULL_DISKS})\" LVMDevice ${BOOT_DEV} BootDisks ${BOOT_FULL_DISKS}\n        RecordOP 99 \"The boot is configured on LVM device which is created using multiple full disks\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the boot partition is mounted\ncheck_boot_partition_mounted()\n{\n    LOG \"Check if the boot partition is mounted\"\n\n    SetOP \"CheckBootPartitionMounted\"\n    if [ ${NR_BOOTABLE_DISKS} -eq \"1\" ]; then\n        boot_link_dev=`readlink -f ${BOOT_DISKS}`\n        dev=`mnt_to_dev /boot`\n        final_dev=`readlink -f ${dev}`\n        if [ \"${boot_link_dev}\" = \"${final_dev}\" ]; then\n            BOOT_FS=`dev_to_fs $dev`\n            LOG \"Boot filesystem is ${BOOT_FS}\"\n            LOG \"Boot disk (${BOOT_DISKS}) is mounted as ${dev}\"\n            RecordOP 0 \"\"\n            return\n        fi\n\n        RETURN_VALUE=1\n        LOG \"The boot partition (${BOOT_DISKS}) is not mounted. Mount the boot partition.\"\n        log_to_json_file ASRMobilityServiceBootPartitionNotMounted \"The boot partition (${BOOT_DISKS}) is not mounted. Mount the boot partition.\" BootPartition ${BOOT_DISKS}\n        RecordOP 99 \"The boot partition is not mounted\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\ncheck_rootfs_is_supported()\n{\n    LOG \"Check if the root filesysytem is supported\"\n\n    SetOP \"CheckIsRootFsSupported\"\n    filesystems=`echo ${Params[${IDX}]} | ${JQ} '.SupportedFileSystems' | awk -F\"\\\"\" '{print $2}'`\n    for fs in `echo ${filesystems} | sed 's/,/ /g'`\n    do\n        if [ \"${ROOT_FS}\" = \"${fs}\" ]; then\n            RecordOP 0 \"\"\n            return\n        fi\n    done\n\n    RETURN_VALUE=1\n    LOG \"The supported file-systems for root file-system are ${filesystems} and the current root file-system is ${ROOT_FS}\"\n    log_to_json_file ASRMobilityServiceUnsupportedRootFileSystem \"The supported file-systems for root file-system are ${filesystems} and the current root file-system is ${ROOT_FS}\" SupportedRootFileSystems ${filesystems} RootFileSystem ${ROOT_FS}\n    RecordOP 99 \"Unsupported root file-system\"\n}\n\ncheck_dirs_writable()\n{\n    local _dirlist=\"\"\n    local _dir=\"\"\n    local _nwlist=\"\"\n    \n    LOG \"Check if directories is are writeable\"\n    SetOP \"DirsWritable\"\n\n    _dirlist=`echo ${Params[${IDX}]} | ${JQ} '.Dirs' | awk -F\"\\\"\" '{print $2}'`\n    for _dir in `echo ${_dirlist} | sed 's/,/ /g'`\n    do\n        if [ ! -w $_dir ]; then \n            _nwlist=\"$_dir,$_nwlist\"\n        fi\n    done\n\n    if [ \"$_nwlist\" = \"\" ]; then\n        RecordOP 0 \"\"\n    else\n        RETURN_VALUE=1\n        _nwlist=`echo $_nwlist | sed \"s/,$//\"`\n        LOG \"FAIL: $_nwlist is not writable\"\n        log_to_json_file ASRMobilityServiceDirsNotWritable           \\\n            \"The following directories do not have write permission: $_nwlist. Without write access, Site Recovery agent cannot be copied and installed.\" DirList \"$_nwlist\" \n        RecordOP 99 \"FAIL: Dir is not writable: $_nwlist\"\n    fi\n}\n\n\n# Check if the boot filesysytem is supported\ncheck_bootfs_is_supported()\n{\n    LOG \"Check if the boot filesysytem is supported\"\n\n    SetOP \"CheckIsBootFsSupported\"\n    if [ ${NR_BOOTABLE_DISKS} -ne \"1\" ]; then\n        RecordOP 0 \"\"\n        return\n    fi\n\n    filesystems=`echo ${Params[${IDX}]} | ${JQ} '.SupportedFileSystems' | awk -F\"\\\"\" '{print $2}'`\n    for fs in `echo ${filesystems} | sed 's/,/ /g'`\n    do\n        if [ \"${BOOT_FS}\" = \"${fs}\" ]; then\n            RecordOP 0 \"\"\n            return\n        fi\n    done\n\n    RETURN_VALUE=1\n    LOG \"The supported file-systems for boot file-system are ${filesystems} and the current boot file-system is ${BOOT_FS}\"\n    log_to_json_file ASRMobilityServiceUnsupportedBootFileSystem \"The supported file-systems for boot file-system are ${filesystems} and the current boot file-system is ${BOOT_FS}\" SupportedBootFileSystems ${filesystems} BootFileSystem ${BOOT_FS}\n    RecordOP 99 \"Unsupported boot file-system\"\n}\n\n# Points to the Grub configuration file\nfind_grub_config_file()\n{\n    LOG \"Finding the Grub file\"\n\n    GRUB_FILE=\"/boot/grub/grub.cfg\"\n    if [ ! -f \"${GRUB_FILE}\" ]; then\n        GRUB_FILE=\"/boot/grub2/grub.cfg\"\n        if [ ! -f \"${GRUB_FILE}\" ]; then\n            GRUB_FILE=\"/boot/grub/menu.lst\"\n            GRUB_FILE=`readlink -f ${GRUB_FILE}`\n            if [ ! -f \"${GRUB_FILE}\" ]; then\n                LOG \"The Grub file doesn't exist\"\n                GRUB_FILE=\"\"\n                return\n            fi\n        fi\n    fi\n\n    LOG \"The Grub file: ${GRUB_FILE}\"\n}\n\n# Check if the Grub command line contains \"acpi=0\"\ncheck_grub_commandline_for_acpi_set_to_zero()\n{\n    LOG \"Check if the commandline parameter acpi=0 exists\"\n\n    SetOP \"CheckAcpiEqualsToZeroSet\"\n    if [ ${BOOT_CONFIGURED_ON_EFI_PARTITION} -eq \"1\" ]; then\n        LOG \"Skipping the check AcpiEqualsToZeroSet as boot is configured on an EFI partition\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    if [ -z ${GRUB_FILE} ]; then\n        LOG \"Skipping the check AcpiEqualsToZeroSet as Grub configrauion file is missing\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    cat /proc/cmdline | grep -wqi \"acpi=0\"\n    if [ $? -eq \"0\" ]; then\n        RETURN_VALUE=1\n        LOG \"The Grub command line contains 'acpi=0'. Remove the entry and then try to protect the VM.\"\n        log_to_json_file ASRMobilityServiceAcpiEqualsToZeroSet \"The Grub command line contains 'acpi=0'. Remove the entry and then try to protect the VM.\"\n        RecordOP 99 \"The Grub command line contains 'acpi=0'\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the LV devices mentioned in the Grub exist\ncheck_device_in_grub_file_exist()\n{\n    LOG \"Check if the devices mentioned in the Grub exist\"\n\n    SetOP \"CheckDeviceExistInGrubFiles\"\n    if [ ${BOOT_CONFIGURED_ON_EFI_PARTITION} -eq \"1\" ]; then\n        LOG \"Skipping the check DeviceExistInGrubFiles as boot is configured on an EFI partition\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    if [ -z \"${GRUB_FILE}\" ]; then\n        LOG \"Skipping the check DeviceExistInGrubFiles as Grub configrauion file is missing\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    cmdline=`egrep \"rd_LVM_LV|rd.lvm.lv\" ${GRUB_FILE}`\n\n    if [ -f \"/etc/default/grub\" ]; then\n        line=`egrep \"rd_LVM_LV|rd.lvm.lv\" /etc/default/grub`\n        for opt in `echo ${line}`\n        do\n            echo ${opt} | grep -q \"rd_LVM_LV\"\n            if [ $? -eq \"0\" ]; then\n                sep=\"rd_LVM_LV\"\n            else\n                echo ${opt} | grep -q \"rd.lvm.lv\"\n                if [ $? -eq \"0\" ]; then\n                    sep=\"rd.lvm.lv\"\n                else\n                    continue\n                fi\n            fi\n\n            opt=\"${sep}`echo ${opt} | awk -F\"${sep}\" '{print $2}'`\"\n            cmdline=`echo \"${cmdline} ${opt}\"`\n        done\n    fi\n\n    devices=\n    for opt in `echo ${cmdline}`\n    do\n        echo ${opt} | egrep -q \"rd_LVM_LV|rd.lvm.lv\"\n        if [ $? -ne \"0\" ]; then\n            continue\n        fi\n\n        opt=`echo ${opt} | tr -d \\'\\\"`\n        vg_name=`echo ${opt} | awk -F\"=\" '{print $2}' | awk -F\"/\" '{print $1}'`\n        lv_name=`echo ${opt} | awk -F\"=\" '{print $2}' | awk -F\"/\" '{print $2}'`\n        if [ ! -e \"/dev/${vg_name}/${lv_name}\" ]; then\n            if [ -z \"${devices}\" ]; then\n                devices=\"/dev/${vg_name}/${lv_name}\"\n            else\n                for dev in `echo ${devices} | sed 's/,/ /g'`\n                do\n                    found=0\n                    if [ ${dev} = \"/dev/${vg_name}/${lv_name}\" ]; then\n                        found=1\n                        break\n                    fi\n                done\n\n                if [ ${found} -eq \"0\" ]; then\n                    devices=`echo \"${devices},/dev/${vg_name}/${lv_name}\"`\n                fi\n            fi\n        fi\n    done\n\n    if [ ! -z \"${devices}\" ]; then\n        RETURN_VALUE=1\n        LOG \"The Grub configuration has the entry for the device (${devices}) which doesn't exist. Fix the Grub.\"\n        log_to_json_file ASRMobilityServiceDeviceNotExist \"The Grub configuration has the entry for the device (${devices}) which doesn't exist. Fix the Grub.\" Device ${devices}\n        RecordOP 99 \"The Grub configuration has the entry for the device which doesn't exist.\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Reports if the device needs to be replaced by UUID or not.\nreport_device()\n{\n    dev=$1\n    if [ ! -z \"${dev}\" ]; then\n        echo $dev | egrep \"^UUID|^LABEL|^/dev/disk/by-uuid/|^/dev/disk/by-label/\" > /dev/null 2>&1\n        if [ $? -eq 0 ]; then\n            return 0\n        fi\n\n        final_dev=`readlink -f ${dev}`\n        idx=0\n        while [ ${idx} -lt ${#LINEAR_DEVICES[*]} ]\n        do\n            linear_final_dev=`readlink -f ${LINEAR_DEVICES[${idx}]}`\n            if [ \"${final_dev}\" = \"${linear_final_dev}\" ]; then\n                return 0\n            fi\n\n            idx=`expr ${idx} + 1`\n        done\n\n        return 1\n    fi\n\n    return 0\n}\n\n# Check if the device needs to be replaced by UUID or not.\ncheck_device_name_change_in_grub_file()\n{\n    LOG \"Check if the device names mentioned in the Grub instead of UUID\"\n\n    SetOP \"CheckGrubDeviceNameChange\"\n    if [ ${BOOT_CONFIGURED_ON_EFI_PARTITION} -eq \"1\" ]; then\n        LOG \"Skipping the check GrubDeviceNameChange as boot is configured on an EFI partition\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    if [ -z \"${GRUB_FILE}\" ]; then\n        LOG \"Skipping the check GrubDeviceNameChange as Grub configrauion file is missing\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    devices=\n    exec 4<\"${GRUB_FILE}\"\n    while read -u 4 -r _line_\n    do\n        _ret_val_=`echo $_line_ | grep \"^#\"`\n        if [ \"${_ret_val_}\" ]; then\n            continue\n        fi\n\n        _root_dev_name_=`echo $_line_ |  egrep 'kernel.*root[ ]*=[ ]*\\/dev\\/|linux.*root[ ]*=[ ]*\\/dev\\/' | awk -F\"root[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n        report_device ${_root_dev_name_}\n        if [ $? -eq 1 ]; then\n            devices=`echo \"${devices} ${_root_dev_name_}\"`\n        fi\n\n        _resume_dev_name_=`echo $_line_ |  egrep 'kernel.*resume[ ]*=[ ]*\\/dev\\/|linux.*resume[ ]*=[ ]*\\/dev\\/' | awk -F\"resume[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n        report_device ${_resume_dev_name_}\n        if [ $? -eq 1 ]; then\n            devices=`echo \"${devices} ${_resume_dev_name_}\"`\n        fi\n    done\n    4<&-\n\n    if [ ! -z \"${devices}\" ]; then\n        devices=`echo ${devices} | sed 's/ /,/g'`\n        RETURN_VALUE=1\n        LOG \"The Grub has the entry for the device ${devices}. Use the UUID instead of the device name.\"\n        log_to_json_file ASRMobilityServiceGrubDeviceNameChange \"The Grub has the entry for the device ${devices}. Use the UUID instead of the device name.\" Device ${devices}\n        RecordOP 99 \"The Grub has the entry for the device with name instead UUID\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the DHCP client is instaaled or not\ncheck_dhcp_client_available()\n{\n    LOG \"Check if the DHCP client exists\"\n\n    SetOP \"CheckDhcpClientAvailable\"\n    if $(echo \"$OS\" | egrep -q 'RHEL|OL'); then\n        binary=\"dhclient\"\n        pkg_name=\"dhclient\"\n    elif $(echo \"$OS\" | egrep -q \"SLES11\"); then\n        binary=\"dhcpcd\"\n        pkg_name=\"dhcpcd\"\n    elif $(echo \"$OS\" | egrep -q \"SLES12\"); then\n        binary=\"dhclient\"\n        pkg_name=\"dhcp-client\"\n    elif $(echo \"$OS\" | egrep -q \"SLES15\"); then\n        binary=\"/usr/lib/wicked/bin/wickedd-dhcp4\"\n        pkg_name=\"wicked\"\n    elif $(echo \"$OS\" | egrep -q 'UBUNTU|DEBIAN'); then\n        binary=\"dhclient\"\n        pkg_name=\"isc-dhcp-client\"\n    fi\n\n    command=$(which ${binary} 2>> ${LOG_FILE})\n    if [ -z \"${command}\" ] ; then\n        RETURN_VALUE=1\n        LOG \"The DHCP client is not available on the system. Install the package ${pkg_name}.\"\n        log_to_json_file ASRMobilityServiceDhcpClientNotAvailable \"The DHCP client is not available on the system. Install the package ${pkg_name}.\" Package ${pkg_name}\n        RecordOP 99 \"The DHCP client is not available on the system\"\n        return\n    fi\n\n    RecordOP 0 \"\"\n}\n\n# Check if the VM is encrypted using old way of one pass\ncheck_old_one_pass_encryption_enabled()\n{\n    LOG \"Check if the VM is encrypted using old way of one pass\"\n\n    SetOP \"OldOnePassEncryption\"\n    if [ ${PLATFORM} != \"Azure\" ]; then\n        LOG \"Skipping the check if the VM is encrypted using old way of one pass as the platform is not Azure\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    if [ ! -e \"/var/lib/azure_disk_encryption_config/azure_crypt_mount\" ]; then\n        LOG \"The file /var/lib/azure_disk_encryption_config/azure_crypt_mount doesn't exist\"\n        RecordOP 0 \"\"\n        return\n    fi\n\n    idx=0\n    while [ ${idx} -lt ${#LINEAR_DEVICES[*]} ]\n    do\n        if [ ${LINEAR_DEVICE_TYPE[${idx}]} != \"crypt\" ]; then\n            idx=`expr ${idx} + 1`\n            continue\n        fi\n\n        linear_device_basename=`basename ${LINEAR_DEVICES[${idx}]}`\n        grep -qw \"^${linear_device_basename}\" /var/lib/azure_disk_encryption_config/azure_crypt_mount\n        if [ $? -eq \"0\" ]; then\n            RETURN_VALUE=1\n            LOG \"The VM is encrypted using old way of one pass encryption. Disable and enable the one pass encryption again.\"\n            log_to_json_file ASRMobilityServiceInstallerBlockOldOnePassEncryption \"The VM is encrypted using old way of one pass encryption. Disable and enable the one pass encryption again.\"\n            RecordOP 99 \"The VM is encrypted using old way of one pass encryption.\"\n            return\n        fi\n\n        idx=`expr ${idx} + 1`\n    done\n\n    RecordOP 0 \"\"\n}\n\n# This functions checks for\n# a) The Check is \"null\", go for next check\n# b) If agent role is Agent, avoid MasterTarget checks and vice-versa\n# c) Execute the corresponding check\nexecute_prereqs()\n{\n    IDX=0\n\n    while [ ${IDX} -lt \"${NR_CHECKS}\" ]\n    do\n        if [ \"${CheckName[${IDX}]}\" = \"null\" ]; then\n            IDX=`expr ${IDX} + 1`\n            continue\n        fi\n\n        if [ \"${AGENT_ROLE}\" = \"agent\" -a ${CheckType[${IDX}]} = \"MasterTarget\" ]; then\n            IDX=`expr ${IDX} + 1`\n            continue\n        fi\n\n        if [ \"${AGENT_ROLE}\" = \"mastertarget\" -a ${CheckType[${IDX}]} = \"MobilityService\" ]; then\n            IDX=`expr ${IDX} + 1`\n            continue\n        fi\n\n        if [ \"${CheckName[${IDX}]}\" = \"CLocaleAvailable\" ]; then\n            check_c_locale_available\n        elif [ \"${CheckName[${IDX}]}\" = \"HostNameSet\" ]; then\n            check_hostname_for_null\n        elif [ \"${CheckName[${IDX}]}\" = \"SecureBoot\" ]; then\n            check_secure_boot\n        elif [ \"${CheckName[${IDX}]}\" = \"FreeSpaceOnRoot\" ]; then\n            check_free_space_on_root\n        elif [ \"${CheckName[${IDX}]}\" = \"LisDriversAvailable\" ]; then\n            check_lis_drivers_available\n        elif [ \"${CheckName[${IDX}]}\" = \"KernelSupported\" ]; then\n            check_current_kernel_supported\n        elif [ \"${CheckName[${IDX}]}\" = \"KernelDirectoryExists\" ]; then\n            check_kernel_directory_exists\n        elif [ \"${CheckName[${IDX}]}\" = \"SystemDiskAvailable\" ]; then\n            check_system_disk_available\n        elif [ \"${CheckName[${IDX}]}\" = \"BootDiskAvailable\" ]; then\n            check_boot_disk_available\n        elif [ \"${CheckName[${IDX}]}\" = \"LVMPackageInstalled\" ]; then\n            check_lvm_package_available\n        elif [ \"${CheckName[${IDX}]}\" = \"BootOnLVMFromMultipleDisks\" ]; then\n            check_boot_on_lvm_from_multiple_disks\n        elif [ \"${CheckName[${IDX}]}\" = \"BootPartitionMounted\" ]; then\n            check_boot_partition_mounted\n        elif [ \"${CheckName[${IDX}]}\" = \"IsRootFsSupported\" ]; then\n            test \"$WORKFLOW\" = \"AZURE\" || check_rootfs_is_supported\n        elif [ \"${CheckName[${IDX}]}\" = \"IsBootFsSupported\" ]; then\n            test \"$WORKFLOW\" = \"AZURE\" || check_bootfs_is_supported\n        elif [ \"${CheckName[${IDX}]}\" = \"IsRootFsSupportedAzure\" ]; then\n            test \"$WORKFLOW\" = \"AZURE\" && check_rootfs_is_supported\n        elif [ \"${CheckName[${IDX}]}\" = \"IsBootFsSupportedAzure\" ]; then\n            test \"$WORKFLOW\" = \"AZURE\" && check_bootfs_is_supported\n        elif [ \"${CheckName[${IDX}]}\" = \"DirsWritable\" ]; then\n            check_dirs_writable\n        elif [ \"${CheckName[${IDX}]}\" = \"AcpiEqualsToZeroSet\" ]; then\n            check_grub_commandline_for_acpi_set_to_zero\n        elif [ \"${CheckName[${IDX}]}\" = \"DeviceExistInGrubFiles\" ]; then\n            check_device_in_grub_file_exist\n        elif [ \"${CheckName[${IDX}]}\" = \"GrubDeviceNameChange\" ]; then\n            check_device_name_change_in_grub_file\n        elif [ \"${CheckName[${IDX}]}\" = \"DhcpClientAvailable\" ]; then\n            check_dhcp_client_available\n        elif [ \"${CheckName[${IDX}]}\" = \"CheckMTKernelVersion\" ]; then\n            check_mt_kernel_version\n        elif [ \"${CheckName[${IDX}]}\" = \"OldOnePassEncryption\" ]; then\n            check_old_one_pass_encryption_enabled\n\t\telif [ \"${CheckName[${IDX}]}\" = \"RunlevelCommandCheck\" ]; then\n\t\t\tcheck_runlevel\n        fi\n\n        IDX=`expr ${IDX} + 1`\n    done\n}\n\n# This function validates whether the check is a known one or not and type of\n# check has to be Common, MobilityService or MasterTarget\nvalidate_checks()\n{\n    cidx=0\n\n    while [ ${cidx} -lt \"${NR_CHECKS}\" ]\n    do\n        if [ ${CheckName[${cidx}]} = \"null\" ]; then\n            cidx=`expr $cidx + 1`\n            continue\n        fi\n\n        found=0\n        for check in `echo ${Existing_Check[@]}`\n        do\n            if [ \"${check}\" = \"${CheckName[${cidx}]}\" ]; then\n                found=1\n                break\n            fi\n        done\n\n        if [ $found -eq \"0\" ]; then\n            LOG \"The pre-requirement json file ${PREREQ_CONF_FILE} contains an invalid check ${CheckName[${cidx}]}\"\n            log_to_json_file ASRMobilityServiceInternalError \"The pre-requirement json file ${PREREQ_CONF_FILE} contains an invalid check ${CheckName[${cidx}]}\"\n            exit 1\n        fi\n\n        echo ${CheckType[${cidx}]} | egrep -q '^Common$|^MobilityService$|^MasterTarget$'\n        if [ $? -ne \"0\" ]; then\n            LOG \"CheckType ${CheckType[${cidx}]} for ${CheckName[${cidx}]} is wrong. It has to be either Common, MobilityService or MasterTarget\"\n            log_to_json_file ASRMobilityServiceInternalError \"CheckType ${CheckType[${cidx}]} for ${CheckName[${cidx}]} is wrong. It has to be either Common, MobilityService or MasterTarget\"\n            exit 1\n        fi\n\n        cidx=`expr $cidx + 1`\n    done\n}\n\n# This function parses the json configuration file and places the\n# name & type of check and the parameters for the check in the\n# seperate arrays.\nparse_json()\n{\n    cidx=-1\n    pidx=0\n\n    CheckName=($(${JQ} -r '.[] | \"\\(.CheckName)\"' ${PREREQ_CONF_FILE}))\n    CheckType=($(${JQ} -r '.[] | \"\\(.CheckType)\"' ${PREREQ_CONF_FILE}))\n    Params=($(${JQ} -r '.[] | \"\\(.Params)\"' ${PREREQ_CONF_FILE}))\n    NR_CHECKS=${#CheckName[*]}\n}\n\n##Main##\nwrong_usage=0\nwhile getopts :r:j:v:l:h opt\ndo\n    case ${opt} in\n        r) AGENT_ROLE=\"${OPTARG}\" ;;\n        j) json_errors_file=\"${OPTARG}\" ;;\n        v) WORKFLOW=\"${OPTARG}\" ;;\n        l) LOG_FILE=\"${OPTARG}\" ;;\n        *) wrong_usage=1\n           wrong_arg=${opt}\n    esac\ndone\n\nLOG \"*******************************************************************************\"\nLOG \"Prereq check installer is invoked with $@\"\n\n# Check if the output JSON file passed or not\nif [ -z \"${json_errors_file}\" ]; then\n    usage\n    exit 2\nfi\n\n# Check if the parent directory of output JSON file exists\njson_dir=`dirname ${json_errors_file}`\nif [ ! -e \"${json_dir}\" ]; then\n    LOG \"The json file path is wrong. The parent directory of json file ${json_errors_file} doesn't exist\"\n    usage\n    exit 2\nfi\n\n# Remove the Prereq conf file if exists\nif [ -e \"${json_errors_file}\" ]; then\n    rm -f ${json_errors_file}\nfi\n\nif [ -f libcommon.sh ]; then\n. ./libcommon.sh\nelse\n    LOG \"File not found : libcommon.sh\"\n    exit 1\nfi\n\n# Check if any invalid switch is passed as an argument\nif [ ${wrong_usage} -eq \"1\" ]; then\n    LOG \"Wrong argument ${wrong_arg} has passed\"\n    log_to_json_file ASRMobilityServiceInternalError \"Wrong argument ${wrong_arg} has passed\"\n    usage\n    exit 2\nfi\n\n# Agent role has to be MS|MT only\nif [ -z \"${AGENT_ROLE}\" ]; then\n    LOG \"Agent Role can't be empty. It has to be either Agent|MasterTarget only.\"\n    log_to_json_file ASRMobilityServiceInternalError \"Agent Role can't be empty. It has to be either Agent|MasterTarget only.\"\n    usage\n    exit 2\nfi\n\nAGENT_ROLE=$(tr [A-Z] [a-z] <<<${AGENT_ROLE})\nif [ \"${AGENT_ROLE}\" != \"agent\" -a \"${AGENT_ROLE}\" != \"mastertarget\" ] ; then\n    LOG \"Agent Role can have the values either Agent|MasterTarget only.\"\n    log_to_json_file ASRMobilityServiceInternalError \"Agent Role can have the values either MasterTarget only.\"\n    usage\n    exit 2\nfi\n\ndetect_platform\nparse_json\nvalidate_checks\nLOG \"Mount information\"\nLOG \"`echo;mount`\"\nLOG \"df information\"\nLOG \"`echo;df -h`\"\nLOG \"blkid information\"\nLOG \"`echo;blkid`\"\ncollect_volume_info\nfind_grub_config_file\nexecute_prereqs\n\nif [ -f \"${TEMP_FILE}\" ]; then\n    rm -f ${TEMP_FILE}\nfi\n\nexit ${RETURN_VALUE}\n", "num_lines": 1803}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n# Path on CS machine where we upload telemetry files\nCMDLINE_TELEMTRY_PATH_ON_CS=\"/home/svsystems/AgentSetupLogs/CommandLineInstall\"\nINSTALLER_GUID=\"\"\nHOSTID_IN_DRSCOUT=\"\"\nHOSTID_FILE='/usr/local/.vx_host_id'\nagentrole=\"\"\n\nis_azure_platform()\n{\n    local return_value=0\n\n    if [ -n \"$VM_PLATFORM\" ]; then\n        vmplatform=$(tr [A-Z] [a-z] <<<$VM_PLATFORM)\n        if [ \"$vmplatform\" == \"azure\" ] ; then\n            return 1\n        fi\n    fi\n    return 0\n}\n\nis_azure_stack_platform()\n{\n    local return_value=0\n\n    if [ -n \"$VM_PLATFORM\" ]; then\n        vmplatform=$($INSTALLATION_DIR/bin/AzureRcmCli --getimdsmetadata | $INSTALLATION_DIR/bin/jq -r .compute.azEnvironment)\n        if [ \"$vmplatform\" == \"AzureStack\" ] ; then\n            return 1\n        fi\n    fi\n    return 0\n}\n\n# This function sends given file to CS machine using cxpsclient binary\n# After sending, moves the file to uploaded files directory\n# Note: This function is called when invoked from commandline, \n#       Incase of pushinstall, pushinstall service pulls telemetry files\n# input: path of the file to send to CS\n# return code: 0 for success, non-zero for failure\nsend_tele_file()\n{\n    local fname=$1\n    local sendinglogfile=$2\n    local return_code=0\n\n    if [ $sendinglogfile == 1 ]; then\n        cmd=\"$INSTALLATION_DIR/bin/cxpsclient -i $CS_IP_FOR_TELEMETRY -l $CXPS_PORT --put $fname -C -d $CMDLINE_TELEMTRY_PATH_ON_CS/'$INSTALLER_GUID'_'$HOST_NAME' >> /dev/null 2>&1\"\n    else\n        cmd=\"$INSTALLATION_DIR/bin/cxpsclient -i $CS_IP_FOR_TELEMETRY -l $CXPS_PORT --put $fname -C -d $CMDLINE_TELEMTRY_PATH_ON_CS/'$INSTALLER_GUID'_'$HOST_NAME' >> $VERBOSE_LOGFILE 2>&1\"\n        trace_log_message -q \"Executing cmd: $cmd\"\n    fi\n    local count=0\n    while [ $count -le 3 ]; do\n        eval $cmd\n        return_code=$?\n        if [ $return_code -ne 0 ]; then\n            count=$(expr $count + 1)\n            continue\n        fi\n        mv -f $fname $UPLOADED_TELEDIR\n        break\n    done\n    if [ $return_code -ne 0 ]; then\n        trace_log_message -q \"Failed to send telemetry file $fname to CS $CS_IP_FOR_TELEMETRY, Port $CXPS_PORT\"\n    fi\n    return $return_code\n}\n\n# Function to read all files in telemetry directory and send to CS machine\n# Input: nothing\n# return code: nothing\nsend_telemetry()\n{\n    trace_log_message -q \"Sending telemetry files to CS\"\n    mkdir -p $UPLOADED_TELEDIR\n\n    # Send telemetry files\n    find $SETUP_TELEDIR -maxdepth 1 -type f | while read telefile\n    do\n        send_tele_file $telefile 0\n    done\n\n    cp -f $VERBOSE_LOGFILE $televerbose_file\n    send_tele_file $televerbose_file 1\n}\n\nset_scenario()\n{\n    SCENARIO_NAME=$1\n}\n\nSetOP()\n{\n    OP_NAME=$1\n}\n\n# Function to start telemetry, truncates json files\n# This function assumes verbose filename is in VERBOSE_LOGFILE variable\n# TEMP_SUMMARY_FILE is temporary file created to write telemetry records, jq reads\n# this file and creates JSON file\n# input: nothing\n# return code: nothing\nStartSummary()\n{\n    is_azure_platform || return 0\n\n    local operation=$installtype\n\nread -d '' op_details <<EOF\n{ \"ScenarioName\": \"$SCENARIO_NAME\",\n  \"OperationName\": \"$OP_NAME\",\n  \"Result\": \"Success\",\n  \"ErrorCode\": 0\n}\nEOF\n    echo $op_details > $TEMP_SUMMARY_FILE\n\n    if [ -n \"$INVOKER\" ]; then\n        # Convert to lowercase and remove leading spaces\n        INVOKER=$(tr [A-Z] [a-z] <<<$INVOKER) >> $VERBOSE_LOGFILE 2>&1\n        trace_log_message -q \"INVOKER=$INVOKER after translate.\"\n    fi\n\n    trace_log_message -q \"RUNID = $RUNID\"\n    return 0\n}\n\n# Function to record a telemetry operation\n# TEMP_SUMMARY_FILE is temporary file created to write telemetry records, jq reads\n# this file and creates JSON file\n# input: (ScenarioName, OperationName, Result, ErrorCode, Message)\n# return code: nothing\nRecordOP()\n{\n    is_azure_platform || return 0\n\n    nargs=$#\n    if [ $nargs -ne 2 ]; then\n        trace_log_message -q \"telemetry error: Passed $nargs args to RecordOP, expecting 2 args\"\n        trace_log_message -q \"arg1: $1, arg2: $2\"\n    fi\n\n    if [ -z \"$SCENARIO_NAME\" ]; then\n        trace_log_message -q \"Warning: SCENARIO_NAME is empty\"\n    fi\n\n    if [ -z \"$OP_NAME\" ]; then\n        trace_log_message -q \"Warning: OP_NAME is empty\"\n    fi\n\n    errcode=$1\n    message=$2\n    result=\"Success\"\n\n    if [ \"$errcode\" != \"0\" ]; then\n        result=\"Failed\"\n    fi\n\n\nread -d '' op_details <<EOF\n{ \"ScenarioName\": \"$SCENARIO_NAME\",\n  \"OperationName\": \"$OP_NAME\",\n  \"Result\": \"$result\",\n  \"ErrorCode\": \"$errcode\",\n  \"Message\": \"$message\"\n}\nEOF\n\n    echo \", $op_details\" >> $TEMP_SUMMARY_FILE\n    return 0\n}\n\n# Function to generate JSON file and invoke functions to send telemetry to CS\n# input args: $1 install/configuration status\nEndSummaryOP()\n{\n    is_azure_platform\n    ret=$?\n    if [ $ret != 0 ]; then\n        trace_log_message -q \"Not generating telemetry because platform is: $VM_PLATFORM\"\n        return 0\n    fi\n\n    read_unique_GUIDs\n\n    if [ -n \"$AGENT_ROLE\" ]; then            \n        agentrole=$(tr [A-Z] [a-z] <<<$AGENT_ROLE)\n        if [ \"$agentrole\" == \"ms\" -o \"$agentrole\" == \"agent\" ] ; then\n            agentrole=\"MS\"\n        elif [ \"$agentrole\" == \"mt\" -o \"$agentrole\" == \"mastertarget\" ] ; then\n            agentrole=\"MT\"\n        fi\n    fi\n\n    local finalsummary=$(cat $TEMP_SUMMARY_FILE)\n    if [ $OS == \"RHEL5-64\" ]; then\n        biosid=$(dmidecode -t system | grep UUID | awk '{print $2}')\n    else\n        biosid=$(cat /sys/class/dmi/id/product_uuid)\n    fi\n\nread -d '' install_summary <<EOF\n{  \"StartTime\": \"$starttime\",\n   \"ComponentName\": \"Microsoft Azure Site Recovery Unified Agent Setup\",\n   \"ComponentVersion\": \"$tele_current_version\",\n   \"ExistingVersion\": \"$tele_existing_version\",\n   \"InstallType\": \"$installtype\",\n   \"InstallStatus\": \"$1\",\n   \"ExitCode\": \"$exit_code\",\n   \"MachineIdentifier\": \"$INSTALLER_GUID\",\n   \"BIOSid\": \"$biosid\",\n   \"HostName\": \"$HOST_NAME\",\n   \"HostId\": \"$HOSTID_IN_DRSCOUT\",\n   \"InstallScenario\": \"$VM_PLATFORM\",\n   \"InstallRole\": \"$agentrole\",\n   \"InvokerType\": \"$INVOKER\",\n   \"SilentInstall\": \"$SILENT_ACTION\",\n   \"OsType\": \"Linux\",\n   \"OsDistro\": \"$OS\",\n   \"OSkernel\": \"$(uname -r)\",\n   \"RAMtotal\": \"$(cat /proc/meminfo | grep -i memtotal | awk -F' ' '{print $2,$3}')\",\n   \"RAMfree\": \"$(cat /proc/meminfo | grep -i memfree | awk -F' ' '{print $2,$3}')\",\n   \"NumCores\": \"$(grep -c ^processor /proc/cpuinfo)\",\n   \"RUNID\": \"$RUNID\",\n   \"EndTime\": \"$(date -Iseconds)\",\n   \"OperationDetails\":[ $finalsummary ]\n}\nEOF\n\n    mkdir -p $SETUP_TELEDIR >> $VERBOSE_LOGFILE 2>&1\n    echo \"$install_summary\" | $JQPATH . > $json_file\n    return_code=$?\n    if [ $return_code -ne 0 ]; then\n        trace_log_message -q  \"telemetry error: Failed to generate JSON file $json_file\"\n        # Remove empty json file\n        rm -f $json_file\n    fi\n\n    if [ \"$INVOKER\" == \"pushinstall\" ] ||\n       [ \"$INVOKER\" == \"vmtools\" ]; then\n        # Don't send telemetry files, pushinstall service picks them\n        # and puts them on CS machine under category \"PushInstall\" or \"VmTools\"\n        trace_log_message -q  \"Not sending telemetry files, because INVOKER is $INVOKER\"\n        return 0\n    fi\n\n    if [ -z \"$INSTALLATION_DIR\" ]; then\n        trace_log_message -q  \"Not sending telemetry files, because INSTALLATION_DIR is empty\"\n        return 0\n    fi\n\n    if [ \"$installtype\" == \"Configuration\" ] && [ $passphrasevalidated -eq 1 ]; then\n        CS_IP_FOR_TELEMETRY=$CS_IP_ADDRESS\n        get_cxps_port\n        update_csdetails_in_drscout\n    elif [ \"$installtype\" == \"Upgrade\" ]; then\n        # In upgrade case read values from drscout.conf file\n        read_csdetails_from_drscout\n    fi\n\n\n    if [ ! -z \"$CS_IP_FOR_TELEMETRY\" ] && [ ! -z \"$CXPS_PORT\" ]; then\n        # Save verbose file in telemetry directory\n        send_telemetry\n    else\n        trace_log_message -q \"Not sending telemetry files, CS IP: $CS_IP_FOR_TELEMETRY, CXPS port: $CXPS_PORT\"\n        # Save verbose file in telemetry directory for uploading later\n        cp -f $VERBOSE_LOGFILE $televerbose_file\n    fi\n    return 0\n}\n\n\n# Function to generate/read unique host ID to/from persisten file \n# We first read unique hostid stored in drscout.conf file, if doesn't exists\n# then we read unique hostid file, if doesn't exists then we generate new unique host id\n# we update drscout.conf file an hostid file with unique hostid\n# input: nothing\n# return code: nothing\nread_unique_GUIDs()\n{\n    is_azure_platform\n    ret=$?\n    if [ $ret != 0 ]; then\n        trace_log_message -q \"Not reading HostID because platform is: $VM_PLATFORM\"\n        return 0\n    fi\n\n    if [ -f \"$HOSTID_FILE\" ]; then\n        INSTALLER_GUID=$(cat $HOSTID_FILE)\n    else\n        trace_log_message -q \"Generating new HostId\"\n        INSTALLER_GUID=$(cat /proc/sys/kernel/random/uuid)\n        echo $INSTALLER_GUID > $HOSTID_FILE\n    fi\n\n    if [ -f \"$DRSCOUT_CONF\" ]; then\n        HOSTID_IN_DRSCOUT=$(grep ^HostId $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n    fi\n\n    trace_log_message -q \"Installer GUID is: $INSTALLER_GUID\"\n    trace_log_message -q \"HostId value in drscout.conf: $HOSTID_IN_DRSCOUT\"\n\n    return 0\n}\n\n# This function updates CS IP and CXPS port number in drscout.conf for \n# telemetry use later on. Writes CSIPforTelemetry and CxpsPortforTelemetry to drscout\n# input: nothing\n# return code: nothing\nupdate_csdetails_in_drscout()\n{\n    trace_log_message -q \"Writing CSIPforTelemetry=$CS_IP_FOR_TELEMETRY to $DRSCOUT_CONF\"\n    grep -i \"CSIPforTelemetry\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    if [ $? -eq 0 ]; then\n        sed -i -e \"s|^CSIPforTelemetry.*|CSIPforTelemetry=$CS_IP_FOR_TELEMETRY|g\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    else\n        sed -i -e \"/^HostId/ a CSIPforTelemetry=$CS_IP_FOR_TELEMETRY\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    fi\n\n    trace_log_message -q \"Writing CxpsPortforTelemetry=$CXPS_PORT to $DRSCOUT_CONF\"\n    grep -i \"CxpsPortforTelemetry\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    if [ $? -eq 0 ]; then\n        sed -i -e \"s|^CxpsPortforTelemetry.*|CxpsPortforTelemetry=$CXPS_PORT|g\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    else\n        sed -i -e \"/^HostId/ a CxpsPortforTelemetry=$CXPS_PORT\" $DRSCOUT_CONF >> $VERBOSE_LOGFILE 2>&1\n    fi\n}\n\n# This function reads CS IP and CXPS port values from drscout.conf file for\n# sending telemetry to CS machine\n# input: nothing\n# return code: nothing\nread_csdetails_from_drscout()\n{\n    if [ -f \"$DRSCOUT_CONF\" ]; then\n        trace_log_message -q \"Reading CSIPforTelemetry and CxpsPortforTelemetry from drscout.conf file\"\n        CS_IP_FOR_TELEMETRY=$(grep ^CSIPforTelemetry $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n        CXPS_PORT=$(grep ^CxpsPortforTelemetry $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n\n        # Agents installed before 1710 won't have CSIPforTelemetry, CxpsPortforTelemetry\n        if [ -z \"$CS_IP_FOR_TELEMETRY\" ]; then\n            CS_IP_FOR_TELEMETRY=$(grep ^Hostname $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n        fi\n        if [ ! -z \"$CS_IP_FOR_TELEMETRY\" ] && [ -z \"$CXPS_PORT\" ]; then\n            get_cxps_port\n        fi\n    fi\n}\n\n# This function invokes CS API to get CXPS port number from CS\n# Default value for CXPS port is 9443, assumes initialized during\n# begining of the installation/configuration\n# input: nothing\n# return code: nothing\nget_cxps_port()\n{\n    port=`$INSTALLATION_DIR/bin/cxcli -i $CS_IP_FOR_TELEMETRY 2>/dev/null`\n    return_code=$?\n    if [ $return_code -eq 0 ]; then\n        CXPS_PORT=$port\n        trace_log_message -q \"cxps port: $CXPS_PORT\"\n    else\n        CXPS_PORT=\"9443\"\n        trace_log_message -q \"Failed to get cxps port, trying with default value $CXPS_PORT\"\n    fi\n}\n\n", "num_lines": 370}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#//--------------------------------------------------------------------\n#//  <copyright file=\"install\" company=\"Microsoft\">\n#//      Copyright (c) Microsoft Corporation. All rights reserved.\n#//  </copyright>\n#//\n#//  <summary>\n#//     This script uses to install linux agent\n#//  </summary>\n#//\n#//--------------------------------------------------------------------\n\n# exporting LANG variable\nexport LANG=C\n\n# FUNCTION : Carries out a command and logs output into an uninstall log\n#\n# Function Name: trace_log_message()\n# \n#  Description  Prints date and time followed by all arguments to \n#               stdout and to UNINST_LOG.  If -q is used, only send \n#               message to log file, not to stdout.  If no arguments \n#               are given, a blank line is returned to stdout and to \n#               UNINST_LOG.\n#       \n#  Usage        trace_log_message [-q] \"Message\"\n#\n#  Notes        If -q is used, it must be the first argument.\n# \ntrace_log_message()\n{\n    QUIET_MODE=FALSE\n\n    if [ $# -gt 0 ]\n    then\n        if [ \"X$1\" = \"X-q\" ]\n        then\n            QUIET_MODE=TRUE\n            shift\n        fi\n    fi\n\n    if [ $# -gt 0 ]\n    then\n        DATE_TIME=`date '+%m/%d/%Y %H:%M:%S'`\n        \n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"${DATE_TIME}: $*\" >> ${UNINST_LOG}\n        else            \n            echo -e \"$@\"\n            echo \"${DATE_TIME} : $@ \" >> ${UNINST_LOG} 2>&1            \n        fi\n    else\n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"\" >> ${UNINST_LOG}\n        else\n            echo \"\" | tee -a ${UNINST_LOG}\n        fi\n    fi\n}\n\n\n# FUNCTION : Print message and quit\nSEE_LOG()\n{\n local exit_code=$1\n trace_log_message \"Check the log file $UNINST_LOG for detailed diagnostic messages during uninstallation ...\"\n [ -e $LOCK_FILE ] && rm -f $LOCK_FILE >/dev/null 2>&1\n exit $exit_code\n}\n\nUsage() {\n    echo\n    echo \"Usage: $0 [ -Y ] [ -L <Absolute path of the log file (default:/var/log/ua_uninstall.log)> ] [ -h ]\"\n    echo && exit 1\n}\n\nUninstall_FX()\n{\n  \n  trace_log_message \"Uninstalling the FX Agent ...\"\n  CURRENT_INSTALLATION_DIR=`grep INSTALLATION_DIR /usr/local/${FX_INST_VERSION_FILE} | cut -d'=' -f2-`\n  cd $CURRENT_INSTALLATION_DIR\n  ./uninstall -Y -L $UNINST_LOG \n\n}\n\nUninstall_VX()\n{  \n  trace_log_message \"Uninstalling the VX agent ...\"\n  CURRENT_INSTALLATION_DIR=`grep INSTALLATION_DIR /usr/local/${INST_VERSION_FILE} | cut -d'=' -f2-`\n  cd $CURRENT_INSTALLATION_DIR/bin\n  ./uninstall -Y -L $UNINST_LOG \n\n}\n\nStopServices() {\n    local agent_name=$1\n    local return_value=0\n    case $agent_name in\n        Vx)\n            VX_INSTALL_DIR=`grep INSTALLATION_DIR /usr/local/.vx_version | cut -d'=' -f2-`\n\t    UA_INSTALL_DIR=`dirname ${VX_INSTALL_DIR}`\n            # Stopping Vx agent before uninstalling agent            \n            trace_log_message            \n            trace_log_message \"Stopping VX agent service...\"\n            touch /usr/local/.norespawn_vxagent >/dev/null 2>&1\n            ${VX_INSTALL_DIR}/bin/stop uninstall >> ${UNINST_LOG} 2>&1\n            if [ $? -eq 2 ]; then                \n                trace_log_message               \n                trace_log_message \"Could not stop Vx agent service. Please re-try after sometime. Aborting...\"\n                rm -f /usr/local/.norespawn_vxagent >/dev/null 2>&1\n                return_value=1\n            fi\n        ;;\n        \n        Fx)\n            FX_INSTALL_DIR=`grep INSTALLATION_DIR /usr/local/.fx_version | cut -d'=' -f2-`\n            # Stopping Fx agent before uninstalling agent            \n            trace_log_message\n            trace_log_message \"Stopping Fx agent service...\"\n            touch /usr/local/.norespawn_svagent >/dev/null 2>&1\n            ${FX_INSTALL_DIR}/stop >> ${UNINST_LOG} 2>&1\n            if [ $? -eq 2 ]; then\n                trace_log_message\n                trace_log_message \"Could not stop Fx agent service. Please re-try after sometime. Aborting...\"\n                rm -f /usr/local/.norespawn_svagent >/dev/null 2>&1\n                return_value=1\n            fi\n        ;;\n    esac    \n    return $return_value\n}\n\nCheck_FX_Presence()\n{\n\n  FX_INST_VERSION_FILE=.fx_version\n  if [ -e /usr/local/${FX_INST_VERSION_FILE} ]; then\n\tFX_AGENT_FOUND=FX\n  fi\n\n}\n\nCheck_VX_Presence()\n{\n\n  INST_VERSION_FILE=.vx_version\n  if [ -e /usr/local/${INST_VERSION_FILE} ]; then\n  \tVX_AGENT_FOUND=VX\n  fi\n\n}\n\n#\n#  Function     check_instance()\n#\n#  Description  Ensures that no other instances of this script are\n#               running.  The results of more than one insctnace of\n#               this script running simultaneously can produce\n#               unexpected results.\n#\n#  Notes        If the LOCK_FILE exists, but the process ID does not\n#               exist, the LOCK_FILE might be errant.  Manually\n#               confirm that no other instances of the script are\n#               running before deleting the LOCK_FILE.\n#\n#               The output of the ps -fp command will include a\n#               header line.  If the number of lines returned from\n#               the ps command is greater than 1, then the process\n#               is running.\n#\n# Return Value: On successful it returns zero, else returns non-zero\n#\ncheck_instance()\n{\n    trace_log_message -q \"Confirming availability through lock file ${LOCK_FILE}\"\n\n    if [ -f \"${LOCK_FILE}\" ]\n    then\n        prev_pid=`cat ${LOCK_FILE}`\n\n        if [ `ps -fp ${prev_pid} | wc -l` -gt 1 ]\n        then\n            trace_log_message \"Instance of ${SCRIPT} already running under the process:\"\n            ps -fp ${prev_pid} 2>&1 | tee -a ${UNINST_LOG}\n            return_value=1\n        else\n            trace_log_message \"Lock file ${LOCK_FILE} is in an inconsistent state\"\n            trace_log_message \"Manually check for multiple instances of ${SCRIPT}\"\n            return_value=1\n        fi\n    else\n        trace_log_message -q \"Lock file ${LOCK_FILE} is free, locking file\"\n        echo $$ >> ${LOCK_FILE}\n        nice sleep 1\n        sync\n\n\n        if [ `head -1 ${LOCK_FILE}` = $$ ]\n        then\n            trace_log_message -q \"Lock file ${LOCK_FILE} is consistent\"\n        else\n            trace_log_message \"Lock file ${LOCK_FILE} is in an inconsistent state\"\n            trace_log_message \"Manually check for multiple instances of ${SCRIPT}\"\n            return_value=1\n        fi\n    fi\n\n    trace_log_message -q \"Check instance return value: $return_value\"\n    return $return_value\n}\n\n\n#######################\n# MAIN ENTRY POINT\n#######################\nOS=\"SET_OS_PLACE_HOLER\"\nSCRIPT_DIR=`dirname $0`\nSCRIPT=`basename $0`\nLOCK_FILE=\"${SCRIPT_DIR}/.uninstall.lck\"\n\n#// Using trap signal so that if we press Cntrl-C or if we quit the process,\n#// we will remove the file uninstall_running\ntrap \"rm -f $LOCK_FILE; exit\" 1 2 3 6 9 15 30\n\n# Prompt the user to confirm whether to proceed to uninstall the agent really\n#Parse command line options if given\nif echo $1 | grep -q '^-' ; then\n    while getopts :L:hY OPT\n    do\n        case $OPT in\n            L)  LOG_FILE=\"$OPTARG\"\n                if expr \"$LOG_FILE\" : '-.' > /dev/null; then\n                    echo \"Option -$OPT requires an argument.\" && Usage\n                fi\n            ;;\n            Y)  SILENT_UNINSTALL=\"yes\" ;;\n            h|-*|*) Usage ;;\n        esac\n    done\nelif [ \"$1\" = \"\" ]; then\n    SILENT_UNINSTALL=\"no\"\nelse\n    Usage\nfi\n\nif  [ -z \"$SILENT_UNINSTALL\" -o \"$SILENT_UNINSTALL\" = \"no\" ] ; then\n    # If no option is specified, then the default is interactive    \n    echo\n    agree=\"\"\n    while [ \"X$agree\" = \"X\" ]; do\n        echo -n \"Do you really want to uninstall the Unified Agent? (Y/N) [default N] : \"\n        read ans\n        [ -z \"$ans\" ] && ans=\"N\"\n        case $ans in\n            [Yy]) agree=Yes ; SILENT_UNINSTALL=\"no\" ;;\n            [Nn]) \n                [ -f $LOCK_FILE ] && rm -f $LOCK_FILE\n                echo \"Bye...\" && exit 1 ;;\n            *) echo -e \"Error: Invalid input.\\n\"\n            continue\n            ;;\n        esac\n    done\nfi\n\nif [ -z \"$LOG_FILE\" ]; then \n    if [ ! -d /var/log ]; then \n       mkdir -p /var/log >/dev/null 2>&1\n    fi\n    UNINST_LOG=\"/var/log/ua_uninstall.log\"\nelif [ \"`echo $LOG_FILE | cut -c1`\" != \"/\" ]; then\n    trace_log_message\n    trace_log_message \"Error: Unintallation logfile must be an absolute path (i.e. beginning with a \\\"/\\\").\"\n    Usage\nelse\n    LOG_FILE_DIR=`dirname \"$LOG_FILE\"`\n    if [ ! -d \"$LOG_FILE_DIR\" ]; then\n        mkdir -p \"$LOG_FILE_DIR\" >/dev/null 2>&1\n    fi\n    UNINST_LOG=\"$LOG_FILE\"\nfi\n\ntrace_log_message -q \"UA UNINSTALLATION\"\ntrace_log_message -q \"-----------------------------------\"\n\nCheck_FX_Presence\n\nCheck_VX_Presence\n\nif [ -z \"$FX_AGENT_FOUND\" -a -z \"$VX_AGENT_FOUND\" ]; then\n    trace_log_message \"Either FX or VX is not installed in the setup ...\"\n    trace_log_message \"Cannot proceed with uninstallation ...\"\n    SEE_LOG 1\nfi\n\n# Make sure there are no multiple instances are running.\ncheck_instance || SEE_LOG $?\n    \nif [ \"$FX_AGENT_FOUND\" = \"FX\" -a \"$VX_AGENT_FOUND\" = \"VX\" ]; then\n    # Stopping FX/VX Agent Services\n    # Aborting un-installation if it's failed to stop the services\n    StopServices \"Vx\" || SEE_LOG 2\n    StopServices \"Fx\" || SEE_LOG 2\t\n\n    Uninstall_VX\n    Uninstall_FX\n\nelif [ \"$FX_AGENT_FOUND\" = \"FX\" ]; then\n    StopServices \"Fx\" || SEE_LOG 2\n    Uninstall_FX\n\nelif [ \"$VX_AGENT_FOUND\" = \"VX\" ]; then\n    StopServices \"Vx\" || SEE_LOG 2\n    Uninstall_VX\nfi\n\n# Specific to RHEL7 platform\nif [ \"$OS\" = \"RHEL7-64\" -o \"$OS\" = \"RHEL8-64\" ]; then \n    #We need to run the following command after all services including involflt and \n    #all the legacy sysv-init service like vxagent, svagent etc have been disabled/removed.\n\n    trace_log_message -q \"Reload systemd manager configuration\"\n    systemctl daemon-reload >> ${UNINST_LOG} 2>&1\nfi\n\n# Removing fingerprint/certificate directories & other files\nrm -rf /usr/local/InMage/certs /usr/local/InMage/fingerprints /usr/local/InMage/private >/dev/null 2>&1\nrm -f /usr/local/unified_uninstall /usr/local/drscout.conf.lck  /usr/local/.norespawn_* >/dev/null 2>&1\nrm -f /usr/local/InMage/license.txt /etc/.appliedmtcustomchanges  \"${LOCK_FILE}\" >/dev/null 2>&1\nrm -f ${UA_INSTALL_DIR}/Third-Party_Notices.txt ${UA_INSTALL_DIR}/uninstall.sh ${UA_INSTALL_DIR}/.uninstall.lck >/dev/null 2>&1\n\ntrace_log_message -q \"END OF UA UNINSTALLATION\"\ntrace_log_message -q \"************************\"\nSEE_LOG 0\n", "num_lines": 339}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nPATH=/bin:/sbin:/usr/sbin:/usr/bin:$PATH\nexport PATH\n\n# Get the following details during installation\n##### Configuration #####\nACTL_KERNEL_VER=\"SET_ACTL_KERNEL_VER\"\nS_FILE_SUFFIX=\"SET_S_FILE_SUFFIX\"\nSEP=\"SET_SEP\"\nKERNEL_VER_SUFFIX=\"SET_KERNEL_VER_SUFFIX\"\nDEPLOY_DIR=\"SET_DEPLOY_DIR\"\nOS=\"SET_OS\"\nDRIVERS=\"involflt\"\n##### Configuration #####\n\nregenerate_list=\"\"\n\necho >> /var/log/InMage_drivers.log\necho `date` >> /var/log/InMage_drivers.log\necho \"----------------------------\" >> /var/log/InMage_drivers.log\n\nis_supported_rhel8_kernel()\n{\n    CURR_KERNEL=$1\n    EXTRA_VER1=$2\n    EXTRA_VER2=$3\n\n    ret=1\n    extra_minor1=`echo ${CURR_KERNEL} | awk -F\".\" '{print $4}'`\n    extra_minor2=`echo ${CURR_KERNEL} | awk -F\".\" '{print $5}'`\n    if [ ! -z $extra_minor1 -a $extra_minor1 -eq $extra_minor1 ] 2> /dev/null; then\n        if [ $extra_minor1 -gt $EXTRA_VER1 ]; then\n            ret=0\n        elif [ $extra_minor1 -eq $EXTRA_VER1 ]; then\n            if [ ! -z $extra_minor2 -a $extra_minor2 -eq $extra_minor2 ] 2> /dev/null; then\n                if [ $extra_minor2 -ge $EXTRA_VER2 ]; then\n                    ret=0\n                fi\n            fi\n        fi\n    fi\n\n    return $ret\n}\n\ncopy_rhel8_drivers()\n{\n    local _suffix=\"$2\"\n    local _drv_dir=\"$3\"\n\n    RHEL8_KMV_V0=\"80\"\n    RHEL8_KMV_V1=\"147\"\n    RHEL8_KMV_V2=\"193\"\n    RHEL8_KMV_V3=\"240\"\n    RHEL8_KMV_V4=\"305\"\n    RHEL8_KMV_V5=\"348\"\n\n    VER_DIR=$(dirname $(dirname $(dirname $k_dir)))\n    K_VER=${VER_DIR##*/}\n\n    KERNEL_MINOR_VERSION=`echo \"$1\" | cut -d\"-\" -f2 | cut -d\".\" -f1`\n    KERNEL_COPY_VERSION=\"\"\n    ret=1\n    case $KERNEL_MINOR_VERSION in\n        $RHEL8_KMV_V0)\n            KERNEL_COPY_VERSION=$RHEL8_KMV_V0\n        ;;\n        $RHEL8_KMV_V1|$RHEL8_KMV_V2|$RHEL8_KMV_V3)\n            KERNEL_COPY_VERSION=$RHEL8_KMV_V1\n        ;;\n        $RHEL8_KMV_V4)\n            is_supported_rhel8_kernel $K_VER 30 1\n            if [ $? -eq \"0\" ]; then\n                KERNEL_COPY_VERSION=$RHEL8_KMV_V4\n            fi\n        ;;\n        $RHEL8_KMV_V5)\n            is_supported_rhel8_kernel $K_VER 5 1\n            if [ $? -eq \"0\" ]; then\n                KERNEL_COPY_VERSION=$RHEL8_KMV_V5\n            fi\n        ;;\n        *)\n            KERNEL_COPY_VERSION=$RHEL8_KMV_V5\n        ;;\n    esac\n    if [ -z $KERNEL_COPY_VERSION ]; then\n        echo \"Not copying involflt driver to kernel $1\" >> /var/log/InMage_drivers.log\n    else\n        echo \"Copying ${_drv_dir}/involflt.ko.${S_FILE_SUFFIX}-${KERNEL_COPY_VERSION}*${SEP}${_suffix} to ${k_dir}\" >> /var/log/InMage_drivers.log\n        cp -f ${_drv_dir}/involflt.ko.${S_FILE_SUFFIX}-${KERNEL_COPY_VERSION}*${SEP}${_suffix} ${k_dir}/involflt.ko\n        ret=$?\n    fi\n\n    return $ret\n}\n\ncopy_rhel7_drivers()\n{\n    local _suffix=\"$2\"\n    local _drv_dir=\"$3\"\n\n    RHEL7_KMV_BASE=\"123\"\n    RHEL7_KMV_U3=\"514\"\n    RHEL7_KMV_U4=\"693\"\n    \n    KERNEL_MINOR_VERSION=`echo ${1} | cut -d\"-\" -f2 | cut -d\".\" -f1`\n    if [ $KERNEL_MINOR_VERSION -lt \"$RHEL7_KMV_U4\" ]; then\n        if [ $KERNEL_MINOR_VERSION -lt \"$RHEL7_KMV_U3\" ]; then\n            cp -f ${_drv_dir}/involflt.ko.${S_FILE_SUFFIX}-${RHEL7_KMV_BASE}*${SEP}${_suffix} ${k_dir}/involflt.ko\n        else\n            cp -f ${_drv_dir}/involflt.ko.${S_FILE_SUFFIX}-${RHEL7_KMV_U3}*${SEP}${_suffix} ${k_dir}/involflt.ko\n        fi\n    else\n        cp -f ${_drv_dir}/involflt.ko.${S_FILE_SUFFIX}-${RHEL7_KMV_U4}*${SEP}${_suffix} ${k_dir}/involflt.ko\n    fi\n\n    return $?\n}\n\nis_sles_kernel_supported()\n{\n    local ker_ver=$1\n    local deploy_dir=$2\n    local supported_kernels=\"${deploy_dir}/bin/drivers/supported_kernels\"\n    local ret=1\n\n    if [ -f \"${supported_kernels}\" ]; then\n        grep -q \"^${ker_ver}:\" ${supported_kernels}\n        if [ $? -eq \"0\" ]; then\n            ret=0\n            ker=`grep \"^${ker_ver}:\" ${supported_kernels} | awk -F\":\" '{print $1}'`\n            patch_level=`grep \"^${ker_ver}:\" ${supported_kernels} | awk -F\":\" '{print $2}'`\n            echo \"Fetched kernel : $ker and patch level: $patch_level from supported kernels file\" >> /var/log/InMage_drivers.log\n        fi\n    fi\n\n    echo ${ker_ver} | grep -q \"\\-azure$\"\n    if [ $? -eq \"0\" ]; then\n        echo \"Validating for azure kernel\" >> /var/log/InMage_drivers.log\n        if [ ${ret} -eq \"0\" ]; then\n            echo ${ker_ver}\n            echo \"$ker_ver found in supported kernels list\" >> /var/log/InMage_drivers.log\n            return 0\n        fi\n\n        return 1\n    fi\n\n    if [ ${ret} -eq \"0\" ]; then\n        echo \"SP${patch_level}\"\n        return 0\n    fi\n\n    if [ -f /etc/SuSE-release ] ; then\n        patch_level=`grep \"PATCHLEVEL = \" /etc/SuSE-release | awk '{print $3}'`\n        echo \"Fetched patch level: $patch_level from SuSE-release file.\" >> /var/log/InMage_drivers.log\n    else\n        patch_level=`grep \"VERSION=\" /etc/os-release | grep -o SP[0-9] | grep -o [0-9]`\n        echo \"Fetched patch level: $patch_level from os-release file.\" >> /var/log/InMage_drivers.log\n        if [ -z \"${patch_level}\" ]; then\n            echo \"No patch level info obtained, dumping os-release file.\" >> /var/log/InMage_drivers.log\n            cat /etc/os-release >> /var/log/InMage_drivers.log\n            patch_level=`grep \"VERSION=\" /etc/os-release | grep -o \"SP[0-9]\" | grep -o \"[0-9]\"`\n            echo \"Fetched patch level: $patch_level from os-release file.\" >> /var/log/InMage_drivers.log\n        fi\n        if [ -z \"${patch_level}\" ]; then\n            local os_ver=`grep \"VERSION=\" /etc/os-release`\n            local sp_ver=`echo $os_ver | grep -o \"SP[0-9]\"`\n            local sp_num_ver=`echo $sp_ver | grep -o \"[0-9]\"`\n            echo \"os version = $os_ver, sp version = $sp_ver, sp_num version=$sp_num_ver\" >> /var/log/InMage_drivers.log\n            patch_level=`grep \"VERSION=\" /etc/os-release | awk -F '[-\"]' '{print $3}' | tr -d 'SP'`\n            echo \"Fetched patch level: $patch_level from os-release file using awk.\" >> /var/log/InMage_drivers.log\n        fi\n        if [ -z \"${patch_level}\" ]; then\n            echo \"No patch level info obtained from os-release file, marking it as SP0\" >> /var/log/InMage_drivers.log\n            patch_level=0\n        fi\n        echo \"Final patch level = $patch_level\" >> /var/log/InMage_drivers.log\n    fi\n    if [ ! -z \"${patch_level}\" ]; then\n        echo \"SP${patch_level}\"\n        return 0\n    fi\n\n    return 1\n}\n\necho \"OS is $OS\" >> /var/log/InMage_drivers.log\nif echo $OS | grep -q 'RHEL\\|SLES11' ; then\n    for driver in $DRIVERS\n    do\n        case $driver in\n            involflt) driver_dir=\"kernel/drivers/char\" ;;            \n        esac\n\n        for suffix in $KERNEL_VER_SUFFIX\n        do\n            for TOP_DIR in `echo /lib/modules/${ACTL_KERNEL_VER}*${SEP}${suffix}`\n            do\n                base_kdir=`basename $TOP_DIR`\n                test -f /boot/vmlinuz-$base_kdir || continue\n                k_dir=$TOP_DIR/$driver_dir\n                if [ -d ${k_dir} ]; then\n                    echo >> /var/log/InMage_drivers.log\n                    echo \"Kernel Directory : ${k_dir}\" >> /var/log/InMage_drivers.log\n                    if [ -f ${k_dir}/${driver}.ko ]; then\n                        echo \"${driver}.ko already exists in ${k_dir}\" >> /var/log/InMage_drivers.log\n                        RET_VAL=256\n                    else\n                        if [ \"$OS\" = \"RHEL7-64\" ]; then\n                            copy_rhel7_drivers \"$k_dir\" \"$suffix\" \"${DEPLOY_DIR}/bin\"\n                        elif [ \"$OS\" = \"RHEL8-64\" ]; then\n                            copy_rhel8_drivers \"$k_dir\" \"$suffix\" \"${DEPLOY_DIR}/bin\"\n                        else\n                            cp -f ${DEPLOY_DIR}/bin/${driver}.ko.${S_FILE_SUFFIX}*${SEP}${suffix} ${k_dir}/${driver}.ko\n                        fi\n                        RET_VAL=$?\n                    fi\n                    if [ \"${RET_VAL}\" = \"0\" ]; then\n                        echo \"Installed ${driver}.ko successfully under ${k_dir}\" >> /var/log/InMage_drivers.log\n                        VER_DIR=$(dirname $(dirname $(dirname $k_dir)))\n                        K_VER=${VER_DIR##*/}\n                        echo \"Running depmod for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n                        depmod $K_VER\n                        if [ $? -eq 0 ]; then\n                            echo \"depmod successful for above kernel...\" >> /var/log/InMage_drivers.log\n                            regenerate_list=\"$K_VER $regenerate_list\" \n                        else\n                            echo \"depmod did not succeed for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n                            echo \"This may affect loading of drivers when you boot this machine using the kernel $K_VER!\" >> /var/log/InMage_drivers.log\n                        fi\n                    elif [ \"${RET_VAL}\" = \"256\" ]; then\n                        :\n                    else\n                        echo \"Could not install ${driver}.ko under ${k_dir}\" >> /var/log/InMage_drivers.log\n                    fi\n                fi\n            done\n        done\n    done\nelif [ \"${OS}\" = \"OL7-64\" -o \"${OS}\" = \"OL8-64\" ]; then\n\t# RH compatible modules\n    for TOP_DIR in `echo /lib/modules/${ACTL_KERNEL_VER}*${SEP}${KERNEL_VER_SUFFIX}`\n    do\n        base_kdir=`basename $TOP_DIR`\n        test -f /boot/vmlinuz-$base_kdir || continue\n        k_dir=$TOP_DIR/kernel/drivers/char\n        test -f $k_dir/involflt.ko && continue\n        if [ \"$OS\" = \"OL7-64\" ]; then\n            copy_rhel7_drivers \"$k_dir\" \"$KERNEL_VER_SUFFIX\" \"${DEPLOY_DIR}/bin/drivers\"\n        else\n            copy_rhel8_drivers \"$k_dir\" \"$KERNEL_VER_SUFFIX\" \"${DEPLOY_DIR}/bin/drivers\"\n        fi\n        RET_VAL=$?\n        if [ \"${RET_VAL}\" = \"0\" ]; then\n            echo \"Installed involflt.ko successfully under ${k_dir}\" >> /var/log/InMage_drivers.log\n            VER_DIR=$(dirname $(dirname $(dirname $k_dir)))\n            K_VER=${VER_DIR##*/}\n            echo \"Running depmod for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n            depmod $K_VER\n            if [ $? -eq 0 ]; then\n                echo \"depmod successful for above kernel...\" >> /var/log/InMage_drivers.log\n                regenerate_list=\"$K_VER $regenerate_list\" \n            else\n                echo \"depmod did not succeed for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n                echo \"This may affect loading of drivers when you boot this machine using the kernel $K_VER!\" >> /var/log/InMage_drivers.log\n            fi\n        else\n            echo \"Could not install involflt.ko under ${k_dir}\" >> /var/log/InMage_drivers.log\n        fi\n    done\n\n    # UEK kernels\n    for TOP_DIR in `find /lib/modules/*uek.x86_64 -maxdepth 0 -type d 2>/dev/null`; do\n        base_kdir=`basename $TOP_DIR`\n        test -f /boot/vmlinuz-$base_kdir || continue\n        k_dir=$TOP_DIR/kernel/drivers/char\n        test -f $k_dir/involflt.ko && continue\n        kernel=\"`echo $k_dir | cut -f 4 -d \"/\" | cut -f 1 -d \"-\"`\"\n        if [ \"$kernel\" = \"4.14.35\" ]; then\n            echo $k_dir | grep -q \"\\-18\" && kernel=\"${kernel}-1818\" || kernel=\"${kernel}-1902\"\n        fi\n        echo \"Copying involflt.ko.${kernel}*uek.x86_64\" >> /var/log/InMage_drivers.log\n        cp -f ${DEPLOY_DIR}/bin/drivers/involflt.ko.${kernel}*uek.x86_64 ${k_dir}/involflt.ko\n        RET_VAL=$?\n        if [ \"${RET_VAL}\" = \"0\" ]; then\n            echo \"Installed involflt.ko successfully under ${k_dir}\" >> /var/log/InMage_drivers.log\n            VER_DIR=$(dirname $(dirname $(dirname $k_dir)))\n            K_VER=${VER_DIR##*/}\n            echo \"Running depmod for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n            depmod $K_VER\n            if [ $? -eq 0 ]; then\n                echo \"depmod successful for above kernel...\" >> /var/log/InMage_drivers.log\n                regenerate_list=\"$K_VER $regenerate_list\" \n            else\n                echo \"depmod did not succeed for kernel $K_VER ...\" >> /var/log/InMage_drivers.log\n                echo \"This may affect loading of drivers when you boot this machine using the kernel $K_VER!\" >> /var/log/InMage_drivers.log\n            fi\n        else\n            echo \"Could not install involflt.ko under ${k_dir}\" >> /var/log/InMage_drivers.log\n        fi\n    done\nelif [ \"${OS}\" = \"OL6-32\" -o \"${OS}\" = \"OL6-64\" ]; then\n    echo \"OS is OL6-32 or OL6-64. Copying involflt.ko to new kernels which are installed after agent installation.\" >> /var/log/InMage_drivers.log\n    # Copy involflt.ko to RHEL standard kernels matching 2.6.32-*el6.i686 2.6.32-*el6.x86_64\n    # Copy involflt.ko to uek kernels matching 2.6.32-100*el6uek.i686, 2.6.32-200*el6uek.i686, 2.6.32-300*el6uek.i686 and 2.6.32-400.*el6uek.i686\n    # Copy involflt.ko to uek2 kernels matching 2.6.39-100*el6uek.i686, 2.6.39-200*el6uek.i686, 2.6.39-300*el6uek.i686 and 2.6.39-400.*el6uek.i686\n    # Copy involflt.ko to uek kernels matching 2.6.32-100*el6.x86_64, 2.6.32-100*el6uek.x86_64, 2.6.32-200*el6uek.x86_64, 2.6.32-300*el6uek.x86_64 and 2.6.32-400*el6uek.x86_64\n    # Copy involflt.ko to uek2 kernels matching 2.6.39-100*el6uek.x86_64, 2.6.39-200*el6uek.x86_64, 2.6.39-300*el6uek.x86_64 and 2.6.39-400*el6uek.x86_64\n\n    for kernel in 2.6.32-131.0.15.el6.i686 2.6.32-131.0.15.el6.x86_64 \\\n                  2.6.32-100.34.1.el6uek.i686 2.6.32-200.16.1.el6uek.i686 2.6.32-300.3.1.el6uek.i686 2.6.32-400.26.1.el6uek.i686 \\\n                  2.6.39-100.5.1.el6uek.i686 2.6.39-200.24.1.el6uek.i686 2.6.39-300.17.1.el6uek.i686 2.6.39-400.17.1.el6uek.i686 \\\n                  2.6.32-100.28.5.el6.x86_64 2.6.32-100.34.1.el6uek.x86_64 2.6.32-200.16.1.el6uek.x86_64 2.6.32-300.3.1.el6uek.x86_64 2.6.32-400.26.1.el6uek.x86_64 \\\n                  2.6.39-100.5.1.el6uek.x86_64 2.6.39-200.24.1.el6uek.x86_64 2.6.39-300.17.1.el6uek.x86_64 2.6.39-400.17.1.el6uek.x86_64 3.8.13-16.2.1.el6uek.x86_64 \\\n                  4.1.12-32.1.2.el6uek.x86_64\n    do\n        # Based on kernel version decide kernel and suffix\n        if [ \"${kernel}\" = \"2.6.32-131.0.15.el6.i686\" ]; then\n            KER=2.6.32\n            SUF=el6.i686\n        elif [ \"${kernel}\" = \"2.6.32-131.0.15.el6.x86_64\" ]; then\n            KER=2.6.32\n            SUF=el6.x86_64\n        elif [ \"${kernel}\" = \"2.6.32-100.34.1.el6uek.i686\" ]; then\n            KER=2.6.32-100\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.32-200.16.1.el6uek.i686\" ]; then\n            KER=2.6.32-200\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.32-300.3.1.el6uek.i686\" ]; then\n            KER=2.6.32-300\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.32-400.26.1.el6uek.i686\" ]; then\n            KER=2.6.32-400\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.39-100.5.1.el6uek.i686\" ]; then\n            KER=2.6.39-100\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.39-200.24.1.el6uek.i686\" ]; then\n            KER=2.6.39-200\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.39-300.17.1.el6uek.i686\" ]; then\n            KER=2.6.39-300\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.39-400.17.1.el6uek.i686\" ]; then\n            KER=2.6.39-400\n            SUF=el6uek.i686\n        elif [ \"${kernel}\" = \"2.6.32-100.28.5.el6.x86_64\" ]; then\n            KER=2.6.32-100\n            SUF=el6.x86_64\n        elif [ \"${kernel}\" = \"2.6.32-100.34.1.el6uek.x86_64\" ]; then\n            KER=2.6.32-100\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.32-200.16.1.el6uek.x86_64\" ]; then\n            KER=2.6.32-200\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.32-300.3.1.el6uek.x86_64\" ]; then\n            KER=2.6.32-300\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.32-400.26.1.el6uek.x86_64\" ]; then\n            KER=2.6.32-400\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.39-100.5.1.el6uek.x86_64\" ]; then\n            KER=2.6.39-100\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.39-200.24.1.el6uek.x86_64\" ]; then\n            KER=2.6.39-200\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.39-300.17.1.el6uek.x86_64\" ]; then\n            KER=2.6.39-300\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"2.6.39-400.17.1.el6uek.x86_64\" ]; then\n            KER=2.6.39-400\n            SUF=el6uek.x86_64\n        elif [ \"${kernel}\" = \"3.8.13-16.2.1.el6uek.x86_64\" ]; then\n            KER=3.8.13\n            SUF=el6uek.x86_64\n        elif $(echo $kernel | grep -q \"el6uek.x86_64\"); then\n            KER=$(echo $kernel | cut -d. -f1-3 | cut -f 1 -d \"-\")\n            SUF=\"el6uek.x86_64\"\n        fi\n\n        # Find all available kernel directories matching kernel version and suffix\n        for k_dir in `find /lib/modules/${KER}*${SUF} -maxdepth 0 -type d 2>/dev/null`\n        do\n            base_kdir=`basename $k_dir`\n            test -f /boot/vmlinuz-$base_kdir || continue\n            NEW_KERNEL=0\n\n            # Copy involflt.ko to each kernel directory\n            if [ -f ${k_dir}/kernel/drivers/char/involflt.ko ]; then\n                echo \"${k_dir}/kernel/drivers/char/involflt.ko already exists\" >> /var/log/InMage_drivers.log\n            else\n                # Copy involflt.ko to each kernel directory\n                if [ -d ${k_dir}/kernel/drivers/char ]; then\n                    echo \"Copying ${DEPLOY_DIR}/bin/involflt.ko.${kernel} to ${k_dir}/kernel/drivers/char/involflt.ko\" >> /var/log/InMage_drivers.log\n                    cp -f ${DEPLOY_DIR}/bin/involflt.ko.${kernel} ${k_dir}/kernel/drivers/char/involflt.ko\n                    if [ $? -eq 0 ]; then\n                        echo \"Installed involflt.ko successfully under ${k_dir}\" >> /var/log/InMage_drivers.log\n                        NEW_KERNEL=1\n                    fi\n                else\n                    echo \"Could not find ${k_dir}/kernel/drivers/char directory\" >> /var/log/InMage_drivers.log\n                fi\n            fi\n\n            if [ \"${NEW_KERNEL}\" -eq 1 ]; then\n                # Run depmod if it is new kernel\n                echo \"Running depmod for kernel $k_dir ...\" >> /var/log/InMage_drivers.log\n                echo \"\" >> /var/log/InMage_drivers.log\n                depmod `basename $k_dir`\n                regenerate_list=\"`basename $k_dir` $regenerate_list\" \n            fi\n        done\n    done\nelif [ \"${OS}\" = \"SLES12-64\" -o \"${OS}\" = \"SLES15-64\" ]; then\n    echo \"OS is SLES12-64 or SLES15-64. Copying involflt.ko to new kernels which are installed after agent installation.\" >> /var/log/InMage_drivers.log\n    for TOP_DIR in `echo /lib/modules/*`\n    do\n        base_kdir=`basename $TOP_DIR`\n        test -f /boot/vmlinuz-$base_kdir || continue\n        DRV_DIR=$TOP_DIR/kernel/drivers/char\n        if [ -d ${DRV_DIR} ]; then\n            KER_DIR=$(dirname $(dirname $(dirname $DRV_DIR)))\n            KER_VER=${KER_DIR##*/}\n            if [ -f ${DRV_DIR}/involflt.ko ]; then\n                echo \"involflt.ko already exits under ${DRV_DIR}.\" >> /var/log/InMage_drivers.log\n            else\n                vaild_ker=`is_sles_kernel_supported $KER_VER $DEPLOY_DIR`\n                echo \"The kernel returned from is_sles_kernel_supported  is ${vaild_ker} and return value is $?\" >> /var/log/InMage_drivers.log\n                if [ -f ${DEPLOY_DIR}/bin/drivers/involflt.ko.${vaild_ker} ]; then\n                    echo \"Copying ${DEPLOY_DIR}/bin/drivers/involflt.ko.${vaild_ker} as ${DRV_DIR}/involflt.ko\" >> /var/log/InMage_drivers.log\n                    cp -f ${DEPLOY_DIR}/bin/drivers/involflt.ko.${vaild_ker} ${DRV_DIR}/involflt.ko >> /var/log/InMage_drivers.log\n                    if [ $? -eq 0 ]; then\n                        echo \"Installed involflt.ko successfully under ${DRV_DIR}.\" >> /var/log/InMage_drivers.log\n                        echo \"Running depmod for kernel $KER_VER ...\" >> /var/log/InMage_drivers.log\n                        depmod $KER_VER\n                        if [ $? -eq 0 ]; then\n                            echo \"depmod successful for above kernel...\" >> /var/log/InMage_drivers.log\n                            regenerate_list=\"$KER_VER $regenerate_list\" \n                        else\n                            echo \"depmod did not succeed for kernel ${KER_VER}...\" >> /var/log/InMage_drivers.log\n                            echo \"This may affect loading of drivers when you boot this system using the kernel $KER_VER.\" >> /var/log/InMage_drivers.log\n                        fi\n                    else\n                        echo \"---> Couldn't install involflt.ko under ${DRV_DIR}\" >> /var/log/InMage_drivers.log\n                    fi\n                else\n                    echo \"Did not find driver for ${KER_VER}. It is not yet supported.\" >> /var/log/InMage_drivers.log\n                fi\n            fi\n        else\n            echo \"---> Directory $DRV_DIR could not be found on this system - skipping installation of driver involflt.\" >> /var/log/InMage_drivers.log\n        fi\n    done\nelse\n    echo \"Copying involflt.ko to new kernels which are installed after agent installation.\" >> /var/log/InMage_drivers.log\n    # Install involflt driver in new kernels. Skip driver installation when involflt.ko already exists.\n    for TOP_DIR in `echo /lib/modules/*`\n    do\n        base_kdir=`basename $TOP_DIR`\n        test -f /boot/vmlinuz-$base_kdir || continue\n        DRV_DIR=$TOP_DIR/kernel/drivers/char\n        if [ -d ${DRV_DIR} ]; then\n            KER_DIR=$(dirname $(dirname $(dirname $DRV_DIR)))\n            KER_VER=${KER_DIR##*/}\n            if [ -f ${DRV_DIR}/involflt.ko ]; then\n                echo \"involflt.ko already exits under ${DRV_DIR}.\" >> /var/log/InMage_drivers.log\n            else\n                if [ -f ${DEPLOY_DIR}/bin/drivers/involflt.ko.${KER_VER} ]; then\n                    echo \"Copying ${DEPLOY_DIR}/bin/drivers/involflt.ko.${KER_VER} as ${DRV_DIR}/involflt.ko\" >> /var/log/InMage_drivers.log\n                    cp -f ${DEPLOY_DIR}/bin/drivers/involflt.ko.${KER_VER} ${DRV_DIR}/involflt.ko >> /var/log/InMage_drivers.log\n                    if [ $? -eq 0 ]; then\n                        echo \"Installed involflt.ko successfully under ${DRV_DIR}.\" >> /var/log/InMage_drivers.log\n                        echo \"Running depmod for kernel $KER_VER ...\" >> /var/log/InMage_drivers.log\n                        depmod $KER_VER\n                        if [ $? -eq 0 ]; then\n                            echo \"depmod successful for above kernel...\" >> /var/log/InMage_drivers.log\n                            regenerate_list=\"$KER_VER $regenerate_list\" \n                        else\n                            echo \"depmod did not succeed for kernel ${KER_VER}...\" >> /var/log/InMage_drivers.log\n                            echo \"This may affect loading of drivers when you boot this system using the kernel $KER_VER.\" >> /var/log/InMage_drivers.log\n                        fi\n                    else\n                        echo \"---> Couldn't install involflt.ko under ${DRV_DIR}\" >> /var/log/InMage_drivers.log\n                    fi\n                else\n                    echo \"Did not find driver for ${KER_VER}. It is not yet supported.\" >> /var/log/InMage_drivers.log\n                fi\n            fi\n        else\n            echo \"---> Directory $DRV_DIR could not be found on this system - skipping installation of driver involflt.\" >> /var/log/InMage_drivers.log\n        fi\n    done\nfi\n\nif [ \"$1\" != \"noinitrd\" ]; then\n    echo \"Regenerating initrd for $regenerate_list\" >> /var/log/InMage_drivers.log\n    for K_VER in $regenerate_list; do\n        $DEPLOY_DIR/scripts/initrd/install.sh regenerate $K_VER >> /var/log/InMage_drivers.log\n    done\nfi\n", "num_lines": 506}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (c) 2011 InMage\n# This file contains proprietary and confidential information and\n# remains the unpublished property of InMage. Use, disclosure,\n# or reproduction is prohibited except as permitted by express\n# written license aggreement with InMage.\n#\n# File       : collect_support_materials.sh\n#\n# Usage      : collect_support_materials.sh <directory-for-support-materials>\n#\n# Collect support materials for Unix based system\n#\n# Description:\n# Script helps user to collect support materials on a given system based on Unix.\n# It collects following information\n# 1. Agent logs under /var/log\n# 2. System logs user /var/\n# 3. Get list of crash dumps if available\n# 4. Get contents of persistent store\n# 5. Collect release build information\n# 6. drscout.conf\n# 7. Get driver and target context stats \n# 8. Get Bitmap files on the system\n# 9. Get dmesg output to a file\n# 10. Get h/w , s/w configuration information\n# \n# Author - Prashant Kharche (prkharch@inmage.com)\n\n\n# Persisten tstore directory\nLANG=en_US.UTF-8\nexport LANG\nLC_NUMERIC=en_US.UTF-8\nexport LC_NUMERIC\n\npstore=/etc/vxagent/involflt\nprocstore=/proc/involflt\nhostname=\"`hostname`\"\nfilename=\"support-materials-$hostname-`date +'%b_%d_%H_%M_%S'`\"\nvx_dir=`grep INSTALLATION_DIR /usr/local/.vx_version | awk -F'=' '{print $2 }'`\ninm_dmit=$vx_dir/bin/inm_dmit\ninmage_logs=\"/var/log/s2* /var/log/svagent*  /var/log/cdpcli* /var/log/CDPMgr* /var/log/CacheMgr* /var/log/appservice* /var/log/involflt* /var/log/linvsnap* /var/log/InMage_Old_Logs $vx_dir/resync $vx_dir/AppliedInfo  /var/log/Scouttunning* /var/log/failovecommandutil* /var/log/cxpsclient* /var/log/vacps* /var/log/customdevicecli* \n/var/log/fabricagent* /var/log/oradisc* /var/log/db2out* /var/log/ua_uninstall* /var/log/InMage_drivers* /var/log/ua_install* /var/log/svagents*\"\nget_scsid_cmd=/etc/vxagent/bin/inm_scsi_id\nos=`uname -s`\nscript_path=/etc/init.d/\npartition=\"\"\ninm_dbg_str=\"\"\nMirrorFilterDevType=\"5\"\nINVOLFLT_DRVNAME=\"involflt\"\nINVOLFLT_CTRLNODE=\"/dev/involflt\"\nsrc_drv_name=\"\"\ndst_drv_name=\"\"\nDF_COMMAND=\"df -hk\"\n\n# err logger for the script\ninm_log() {\n   inm_dbg_str=\"${inm_dbg_str} |\"\n   inm_date_str=`date +\"%b %d %H:%M:%S\"`\n   inm_dbg_str=\"${inm_dbg_str} ${inm_date_str}\"\n   inm_dbg_str=\"${inm_dbg_str} $*\"\n}\n\n# FUNCTION: Invokes inm_logger to write into kernel ring buffer\ncleanup() {\n   INM_LOGGER=/etc/init.d/inm_logger\n   if [ -f $INM_LOGGER ] ; then\n      $INM_LOGGER \"inm_hotplug: \" $inm_dbg_str\n   else\n      echo $inm_dbg_str\n   fi\n   inm_dbg_str=\"\"\n}\n\nconsistency_log()\n{\n    logPath=`grep -w LogPathname /usr/local/drscout.conf | cut -d= -f2`\n    logDir=\"${logPath}/ApplicationPolicyLogs\"\n    if [ -d $logDir ]\n    then\n        \n        # delete policy log files older than 12 hours\n        find $logDir -mtime +0 -name \"*olicy*.log\" -delete\n\n        echo\n        echo \"consistency_log START\"\n        find $logDir -mtime -0.01 -exec grep -l vacp {} \\; | sort | xargs awk '\n        BEGIN{\n            IGNORECASE = 1\n            fname=\"tmpfile\"\n        }\n        function prtName() {\n            if (fname!=FILENAME){\n                \"stat -c %y \"FILENAME |getline fsize\n                printf \"\\n\\t%s, %s\\n\", FILENAME, fsize\n                fname=FILENAME\n            }\n        }\n        /Command Line/ || /Exiting/ || /failed/ || /Error/ {prtName(); printf \"\\t\\t\"; print}\n        END{\n        }'\n        echo \"consistency_log END\"\n    fi\n}\n\n\nmds_log()\n{\n    local _syslog_=\"/var/log/messages\"\n    local _disk_=\"\"\n\n    # get the run time in local and UTC\n    date &&  date -u\n\n    # Get Driver Stats\n    $inm_dmit --get_drv_stat | cut -f 2- -d \":\" | sed '/^$/d' | sed 's/^[ \\t]*//'\n\n    for _disk_ in `$inm_dmit --get_protected_volume_list`\n    do\n        echo \"#### $_disk_ ####\"\n        $inm_dmit --get_volume_stat $_disk_ | cut -f 2- -d \":\" | sed '/^$/d' | sed 's/^[ \\t]*//'\n    done\n\n    # Extract all driver logs from syslog\n    echo \"#### Syslog ####\"\n\n    if [ ! -f \"$_syslog_\" ]\n    then\n        _syslog_=\"/var/log/syslog\"\n    fi\n\n    echo \"#### HEAD ####\"\n    grep \"involflt\" \"$_syslog_\" | head -50 > /var/log/involflt_head.cur\n    cmp /var/log/involflt_head.cur /var/log/involflt_head.prev > /dev/null 2>&1 && {\n        echo \"Same as before\"\n    } || {\n        cat /var/log/involflt_head.cur\n        cp /var/log/involflt_head.cur /var/log/involflt_head.prev\n    }\n    echo \"#### TAIL ####\"\n    grep \"involflt\" \"$_syslog_\" | tail -50 > /var/log/involflt_tail.cur\n    cmp /var/log/involflt_tail.cur /var/log/involflt_tail.prev > /dev/null 2>&1 && {\n        echo \"Same as before\"\n    } || {\n        cat /var/log/involflt_tail.cur\n        cp /var/log/involflt_tail.cur /var/log/involflt_tail.prev\n    }\n\n    chmod 640 /var/log/involflt_head.cur\n    chmod 640 /var/log/involflt_head.prev\n    chmod 640 /var/log/involflt_tail.cur\n    chmod 640 /var/log/involflt_tail.prev\n\n    cat /var/log/InMage_drivers.log\n    cat /var/log/InMage_drivers.log >> /var/log/InMage_drivers.old.log\n    rm -f /var/log/InMage_drivers.log\n\n}\n\n# Main entry point to the script\nif [ \"$1\" = \"_mds_\" ]\nthen\n    mds_log | tr '\\n' '|'\n    exit\nfi\n\ninm_log \"Executing support material collection script \"\ncleanup\ncase \"${os}\" in\n    SunOS)\n        if /usr/sbin/modinfo | grep -i involflt > /dev/null 2>&1; then\n            inm_log \" ${INVOLFLT_DRVNAME} driver is loaded\"\n            cleanup\n        else\n            echo \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n            inm_log \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n            cleanup\n            exit\n        fi\n    ;;\n    Linux)\n        if ! lsmod | grep -i involflt > /dev/null 2>&1; then\n            inm_log \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n            cleanup\n            echo \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n        fi\n    ;;\n    AIX)\n        DF_COMMAND=\"df -P\"\n        if ! /usr/bin/genkex | grep -i involflt > /dev/null 2>&1; then\n            inm_log \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n            cleanup\n            echo \" ${INVOLFLT_DRVNAME} driver is not loaded\"\n            exit\n        fi\n    ;;\n    *)\n        echo \"OS is not supported\"\n        exit\n    ;;\nesac\n\n# Description:\n# Script helps user to collection support materials on a given system based on Unix.\n# It collects following information\n# 1. Agent logs under /var/log\n# 2. System logs user /var/\n# 3. Get list of crash dumps if available\n# 4. Get contents of persistent store\n# 5. Collect release build information\n# 6. drscout.conf\n# 7. Get driver and target context stats \n# 8. Get Bitmap files on the system\n# 9. Get dmesg output to a file\n# \n\nsupportpath_input=$1\n# Store support materials in directory provided by user\nif [ -d \"${supportpath_input}\" ]\nthen\n    #echo \"User input $supportpath_input\"\n    supportstore=$supportpath_input/$filename\nelse\n    if [ \"${supportpath_input}\" ]\n    then\n        echo \"Path $supportpath_input for support materials is not valid\"\n        exit;\n    fi\n    supportstore=\"/root/$filename\"\nfi\n\n# Scout protection model - currently used only for MaxRep\nif [ \"$2\" != \"MaxRep\" ]\nthen\n    supportmodel_input=\n    echo \"Evaluating free space in chosen support store location $supportstore\"\n    $DF_COMMAND $supportpath_input /root\n    echo\n    echo \"Please press (Y/y) if you think chosen support store location has\"\n    echo \"sufficient free space for generating logs: \"\n    read input\n\n    if [ \"$input\" != \"y\" ] && [ \"$input\" != \"Y\" ]; then\n        echo \"Free up some space on desired location for support materials..\"\n        exit 1\n    fi\n\nelse\n    supportmodel_input=$2\nfi\n\nif [ \"$supportmodel_input\" ]; then\n    echo \"MaxRep configuration..: $supportmodel_input\"\nfi\n\nsupportstore=`echo $supportstore | sed -e \"s: :_:g\"`;\nfilename=`echo $filename | sed -e \"s: :_:g\"`;\nmkdir $supportstore\necho \"Support materials will be stored in temporary directory $supportstore\";\n\nif [ \"${os}\" = \"SunOS\" ]; then\n     ID=/usr/xpg4/bin/id\nelse\n     ID=/usr/bin/id\nfi\n\nuser=`$ID -un`\n\necho \"Collecting agent logs, system logs & dmesg output\"\n# 1. Agent logs under /var/log\n# 2. System logs user /var/\n# 9. Get dmesg output to a file\nmkdir $supportstore/system_logs\nmkdir $supportstore/config\ncase \"${os}\" in\n    SunOS)\n        dmesg > $supportstore/dmesg.log\n        cp /var/adm/message* $inmage_logs $supportstore/system_logs/ > /dev/null 2>&1\n        cp /var/svc/log/InMage* $supportstore/system_logs/ > /dev/null 2>&1\n        acctadm > $supportstore/system_logs/acctadm.log  > /dev/null 2>&1\n        cp /var/log/syslog* $supportstore/system_logs/  > /dev/null 2>&1\n        if [ -f /var/log/vormetric/vmd.log ]; then\n            cp /var/log/vormetric/vmd.log $supportstore/system_logs/  > /dev/null 2>&1\n        fi\n        if [ -f /var/log/vormetric/secfs.log ]; then\n            cp /var/log/vormetric/secfs.log $supportstore/system_logs/  > /dev/null 2>&1\n        fi\n    ;;\n    Linux)\n        dmesg > $supportstore/dmesg.log\n        if [ \"$supportmodel_input\" ]; then\n            echo \"MaxRep configuration..: $supportmodel_input\"\n            cp $vx_dir/resync $vx_dir/AppliedInfo $supportstore/system_logs/ > /dev/null 2>&1\n        else\n            cp /var/log/message* /var/log/syslog* $inmage_logs $vx_dir/resync $vx_dir/AppliedInfo $supportstore/system_logs/ > /dev/null 2>&1\n        fi\n        cp /var/log/syslog* $supportstore/system_logs/  > /dev/null 2>&1\n        #tar -cvf $supportstore/system_logs.tar /var/log/message* $inmage_logs $vx_dir/resync $vx_dir/AppliedInfo > /dev/null 2>&1\n        cat /proc/cpuinfo > $supportstore/cpuinfo.log\n        dmidecode > $supportstore/dmidecode.log\n    ;;\n    AIX)\n        $inm_dmit --op=dmesg  > $supportstore/dmesg.log\n        /usr/bin/cp /var/log/involflt_driver.log* $inmage_logs $supportstore/system_logs/ > /dev/null 2>&1\n        /usr/bin/cp /var/log/.inmboot_log $supportstore/config/ > /dev/null 2>&1\n    ;;\n    *)\n        echo \"OS is not supported\"\n        exit\n    ;;\nesac\n\necho \"Collecting persistent store configuration files\"\n# 4. Get contents of persistent store\n# copy whatever is stored in persistent store /etc/vxagent/involflt\nmkdir $supportstore/persistentstore\ncp -R /etc/vxagent/involflt $supportstore/persistentstore\n#tar -cvf $supportstore/persistentstore.tar /etc/vxagent/involflt > /dev/null 2>&1\n\necho \"Collecting Scout configuration files\"\n# 5. Collect release build information\n# 6. drscout.conf\n# Get configuration logs under config directory\ncp /usr/local/drscout.conf $supportstore/config/\ncp /usr/local/.vx_version $supportstore/config/vx_version\ncp /usr/local/.fx_version $supportstore/config/fx_version\ncp /.vx* $supportstore/config/ > /dev/null 2>&1\ncp /.boottimemirroring* $supportstore/config/ > /dev/null 2>&1\n#tar -cvf $supportstore/config/other.tar /.vx* /.boottimemirroring* > /dev/null 2>&1\ncase \"${os}\" in\n    SunOS)\n        cp /etc/system $supportstore/config/ \n        cp /kernel/drv/involflt.conf /kernel/drv/linvsnap.conf $supportstore/config/\n        ls -l /var/crash/* > $supportstore/crash_dump-list\n    ;;\n    Linux)\n        ls -l /var/crash/* > $supportstore/crash_dump-list\n        /usr/bin/lsscsi > $supportstore/config/lsscsi.txt\n        if [ \"$supportmodel_input\" ]; then\n            cp /proc/scsi_tgt/sessions $supportstore/config/\n            cp /proc/scsi_tgt/scsi_tgt $supportstore/config/\n            cp /proc/scsi_tgt/sgv $supportstore/config/\n            ls -l /proc/scsi_tgt/groups/ > $supportstore/config/groups.list\n        fi\n    ;;\n    AIX)\n        ls -l /var/adm/ras/ > $supportstore/crash_dump-list\n    ;;\n    *)\n        echo \"OS is not supported\"\n        exit\n    ;;\nesac\n\n\n# 7. Get driver and target context stats \nmkdir $supportstore/stats 2>&1\n\necho \"Collecting driver related statistics\";\ncase \"${os}\" in\n      SunOS)\n      $inm_dmit --get_drv_stat > $supportstore/stats/driver-stats\n      $inm_dmit --get_protected_volume_list > $supportstore/stats/pvlist-driver.log\n      for volume in `cat $supportstore/stats/pvlist-driver.log | grep -v \"IOCTL_INMAGE_GET_PROTECTED_VOLUME_LIST\" | awk '{print $1}'`\n      do\n         tmp_fname=`echo $volume | sed -e \"s:/:_:g\"`;\n         $inm_dmit --get_volume_stat $volume > $supportstore/stats/$tmp_fname;\n         $inm_dmit --op=additional_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_bitmap_changes 2>&1 > /dev/null;\n         $inm_dmit --op=latency_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_latency_stats 2>&1 > /dev/null;\n      done\n\n       ;;\n      Linux)\n      if [ -d /proc/involflt ]\n      then\n         ls -l $procstore/* > $supportstore/stats/pvlist-driver.log\n         for file in $procstore/*\n         do\n            echo \"Stats for entry $file\"\n            tmpfilename=`echo $file | sed -e \"s:/:_:g\"`\n            cat $file > $supportstore/stats/$tmpfilename\n         done\n      else\n         $inm_dmit --get_drv_stat > $supportstore/stats/driver-stats\n         $inm_dmit --get_protected_volume_list > $supportstore/stats/pvlist-driver.log\n         for volume in `cat $supportstore/stats/pvlist-driver.log | awk '{print $1}'`\n         do\n            tmp_fname=`echo $volume | sed -e \"s:/:_:g\"`;\n            $inm_dmit --get_volume_stat $volume > $supportstore/stats/$tmp_fname;\n            if [ \"$volume\" != \"DUMMY_LUN_ZERO\" ]; then\n               $inm_dmit --op=additional_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_bitmap_changes 2>&1 > /dev/null;\n               $inm_dmit --op=latency_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_latency_stats 2>&1 > /dev/null;\n            fi\n         done\n      fi\n        # Add vCon logs if any\n        mkdir $supportstore/vCon\n        if [ -d /etc/vxagent/vcon ]; then\n            cp -R /etc/vxagent/vcon $supportstore/vCon/ 2>&1 > /dev/null\n        fi\n        if [ -d /etc/vxagent/logs ]; then\n            cp -R /etc/vxagent/logs $supportstore/vCon/ 2>&1 > /dev/null\n        fi\n\t\tif [ -d $vx_dir/etc ]; then\n            cp -R $vx_dir/etc $supportstore/vCon/ 2>&1 > /dev/null\n\t\tfi\n\t\t\n\t\tif [ -f $vx_dir/scripts/azure/PrepareTarget.log ]; then\n            \tcp  $vx_dir/scripts/azure/PrepareTarget.log $supportstore/vCon/ 2>&1 > /dev/null\n\t\tfi\n        if [ -d $vx_dir/failover_data ]; then\n            cp -R $vx_dir/failover_data/ $supportstore/vCon/ 2>&1 > /dev/null\n            if [ -f $vx_dir/scripts/vCon/PrepareTarget.log ]; then\n            \tcp  $vx_dir/scripts/vCon/PrepareTarget.log $supportstore/vCon/ 2>&1 > /dev/null\n            \techo \"Role: MT\" > $supportstore/vCon/Machine_Role.log 2>&1 > /dev/null\n            fi\n            if [ -f $vx_dir/scripts/vCon/LinuxP2V.log ]; then\n            \tcp  $vx_dir/scripts/vCon/LinuxP2V.log $supportstore/vCon/ 2>&1 > /dev/null\n            \techo \"Role: Source\" > $supportstore/vCon/Machine_Role.log 2>&1 > /dev/null\n            fi\n        fi\n\t\t#Data protection logs \n\t\tif [ -d /var/log/vxlogs ]; then \n\t\t\tmkdir $supportstore/dataProtection\n\t\t\tcp -R /var/log/vxlogs $supportstore/dataProtection/ 2>&1 > /dev/null\n\t\tfi\t\t\t\t\n\t\t\n        mkdir $supportstore/vCon/network\n        if [ -d /etc/sysconfig/network-scripts/ ]\n        then\n            cp -R /etc/sysconfig/network-scripts/*eth* $supportstore/vCon/network 2>&1 > /dev/null\n        fi\n        # Applicable only for vCon protections \n        if [ -f /boot/Configuration.info ]; then\n            mkdir $supportstore/vCon/boot\n            cp /boot/Configuration.info $supportstore/vCon/boot/ 2>&1 > /dev/null\n            md5sum /boot/init*.* 2>&1 > $supportstore/vCon/boot/initrd_md5sum.log\n            stat /boot/init*.* 2>&1 > $supportstore/vCon/boot/init_stat.log\n            if [ -d /boot/init*INMAGE* ]; then\n                cp /boot/init*INMAGE* $supportstore/vCon/boot/ 2>&1 > /dev/null\n            fi\n            if [ -d /boot/init*InMage* ]; then\n                cp /boot/init*InMage* $supportstore/vCon/boot/ 2>&1 > /dev/null\n            fi\n        fi\n\n        if [ -f /etc/vxagent/logs ]; then\n            cp /var/log/inmage_mount.log $supportstore/vCon/ 2>&1 > /dev/null\n        fi\n\t\tif [ -d $fx_dir ]; then\n\t\t    mkdir -p $supportstore/fx_logs/ 2>&1 > /dev/null\n            cp $fx_dir/inmage_job*.log $fx_dir/sv*.log $supportstore/fx_logs/ 2>&1 > /dev/null\n\t\t\t\n\t\t\tcp -R $fx_dir/transport $supportstore/fx_logs/ 2>&1 > /dev/null\n\t\tfi\n\t\t\n\t\tif [ -d /home/svsystems/var/ApplicationPolicyLogs ]; then \n\t\t\tcp -R /home/svsystems/var/ApplicationPolicyLogs  $supportstore/ 2>&1 > /dev/null\n\t\tfi\t\n\t\t\n\t\t\n       ;;\n   AIX)\n      $inm_dmit --get_drv_stat > $supportstore/stats/driver-stats\n      $inm_dmit --get_protected_volume_list > $supportstore/stats/pvlist-driver.log\n      for volume in `cat $supportstore/stats/pvlist-driver.log | awk '{print $1}'`\n      do\n         tmp_fname=`echo $volume | sed -e \"s:/:_:g\"`;\n         $inm_dmit --get_volume_stat $volume > $supportstore/stats/$tmp_fname;\n         $inm_dmit --op=additional_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_bitmap_changes;\n         $inm_dmit --op=latency_stats --src_vol=$volume > $supportstore/stats/${tmp_fname}_latency_stats;\n      done\n       ;;\n      *)\n         echo \"OS is not supported\"\n         return 1\n         ;;\nesac\n\n# 8. Get Bitmap files on the system\nmkdir ${supportstore}/bitmap_files\ncp /root/InMage*.VolumeLog ${supportstore}/bitmap_files/  > /dev/null 2>&1\n\n#10. Get sysyem information..\nmkdir ${supportstore}/sysinfo/\necho \"Collecting system software/hardware configuration information.. \"\ncp /etc/*release ${supportstore}/sysinfo/\ncase \"${os}\" in\n      SunOS)\n          cp /etc/vfstab ${supportstore}/sysinfo/\n          /usr/platform/`uname -i`/sbin/prtdiag -v > ${supportstore}/sysinfo/prtdiag.txt\n          /usr/sbin/modinfo > ${supportstore}/sysinfo/modinfo.log\n          /usr/sbin/prtconf -v > ${supportstore}/sysinfo/prtconf.txt\n          /usr/bin/pkginfo -l > ${supportstore}/sysinfo/pkginfo.log\n          /usr/sbin/patchadd -p > ${supportstore}/sysinfo/patchadd-p.txt\n          ps -eo zone,uid,pid,ppid,time,comm,vsz,osz,pmem,rss > ${supportstore}/sysinfo/ps_detailed.txt\n          /usr/sbin/cryptoadm list -v > ${supportstore}/sysinfo/cryptoadm.txt\n          if [ \"$user\" = \"root\" ]\n          then\n              echo ::nm | /usr/bin/mdb -k > ${supportstore}/sysinfo/mdb-nm.log\n          fi\n          iostat -xdm -e > ${supportstore}/sysinfo/iostat_xdm.txt\n          echo \"Executing sar command. It takes about 15 seconds\"\n          sar -aAbcdgkmpqruvwy 5 3 > ${supportstore}/sysinfo/sar_A_5_3.log\n          uptime > $supportstore/uptime.txt\n          ipcs -a > ${supportstore}/sysinfo/ipcs_a.log\n          fmadm faulty -a -v> ${supportstore}/sysinfo/fmadm_faulty.log\n          svcs > ${supportstore}/sysinfo/svcs.log\n          svcs -xv > ${supportstore}/sysinfo/svcs_xv.log\n          vmstat -p > ${supportstore}/sysinfo/vmstat_p.log\n          vmstat -s > ${supportstore}/sysinfo/vmstat_s.log\n          mpstat > ${supportstore}/sysinfo/mpstat.log\n      ;;\n      Linux)\n          ls -l /boot > ${supportstore}/sysinfo/boot.txt\n          for i in /boot/init*\n          do\n              echo $i > ${supportstore}/sysinfo/initrd.txt\n              echo \"===================\" >> ${supportstore}/sysinfo/initrd.txt\n              which lsinitramfs > /dev/null 2>&1\n              if [ $? -eq 0 ]; then\n                  lsinitramfs $i >> ${supportstore}/sysinfo/initrd.txt\n              else\n                  which lsinitrd > /dev/null 2>&1\n                  if [ $? -eq 0 ]; then\n                      lsinitrd $i >>  ${supportstore}/sysinfo/initrd.txt\n                  else\n                      zcat $i | cpio -itv >> ${supportstore}/sysinfo/initrd.txt\n                  fi\n              fi\n              echo \"===================\" >> ${supportstore}/sysinfo/initrd.txt\n          done\n          /sbin/sfdisk -luS 2> /dev/null | grep -e '/dev/' | grep -v Empty > ${supportstore}/sysinfo/sfdisk.txt\n          dmsetup table > ${supportstore}/sysinfo/dmsetup.txt 2>&1\n          vgdisplay -v > ${supportstore}/sysinfo/vgdisplay_v.txt 2>&1\n          /bin/cp /etc/fstab ${supportstore}/sysinfo/\n          /bin/cp /etc/mtab ${supportstore}/sysinfo/\n          /sbin/lspci  -v > ${supportstore}/sysinfo/lspci.txt\n          /sbin/lsmod > ${supportstore}/sysinfo/lsmod.txt\n          cat /proc/meminfo  > ${supportstore}/sysinfo/meminfo.txt\n          cat /proc/cpuinfo  > ${supportstore}/sysinfo/cpuinfo.txt\n          cat /proc/mounts > ${supportstore}/sysinfo/proc_mounts.txt\n          rpm -qa  > ${supportstore}/sysinfo/rpmlist.txt\n          ps -aef > ${supportstore}/sysinfo/ps.txt\n          ps -eo zone,uid,pid,ppid,time,comm,vsz,osz,pmem,rss > ${supportstore}/sysinfo/ps_detailed.txt\n          mount > ${supportstore}/sysinfo/mount.log\n          last > ${supportstore}/sysinfo/last.log\n          uname -a > ${supportstore}/sysinfo/uname-a.log\n          cp /etc/sysctl.conf  ${supportstore}/sysinfo/\n          sysctl -p  > ${supportstore}/sysinfo/sysctl_p.log\n          ipcs -a > ${supportstore}/sysinfo/ipcs_a.log\n          iostat -xdm > ${supportstore}/sysinfo/iostat_xdm.txt\n          > $supportstore/disk-stats\n          for i in `ls /sys/block/`\n          do\n            echo \"Stats for $i\" >> $supportstore/disk-stats\n            cat /sys/block/$i/stat >> $supportstore/disk-stats\n          done\n          echo \"Executing sar command and it takes about 15 seconds\"\n          sar -A 5 3 2>&1 > ${supportstore}/sysinfo/sar_A_5_3.log\n          uptime > $supportstore/uptime.txt\n          top -b -d 1 -n 3 > $supportstore/sysinfo/top_b_d_1_n_3.log\n          chkconfig --list > ${supportstore}/sysinfo/chkconfig_list.log\n          vmstat -m > ${supportstore}/sysinfo/vmstat_m.log\n          vmstat -s > ${supportstore}/sysinfo/vmstat_s.log\n          vmstat -d > ${supportstore}/sysinfo/vmstat_d.log\n          cat /proc/mdstat > ${supportstore}/sysinfo/mdstat\n\t\t  service --status-all > ${supportstore}/RunningServices_list.log\n\t\t  lsmod | sort > ${supportstore}/LoadedModules_list.log\n\t\t  find /lib/modules -type f -name linvsnap.ko > ${supportstore}/LinuxUA-linvsnapDriver_list.log\n\t\t  find /lib/modules -type f -name involflt.ko > ${supportstore}/LinuxUA-involfltDriver_list.log\n\t\t  which rpm && {\n            rpm -qa | sort > ${supportstore}/InstalledRPMS_list.log\n          } || {\n            dpkg -l | sort > ${supportstore}/InstalledRPMS_list.log\n          }\n\t\t  chkconfig --list > ${supportstore}/AllServices_list.log\n      ;;\n      AIX)\n          /usr/bin/cp /etc/filesystems ${supportstore}/sysinfo/\n          /usr/bin/lslpp -L > ${supportstore}/sysinfo/lslpp.lst\n          /usr/bin/genkex > ${supportstore}/sysinfo/genkex.lst\n          /usr/sbin/lspv > $supportstore/lspv.output\n          /usr/sbin/lsdev > $supportstore/lsdev.output\n          /usr/sbin/lsconf > $supportstore/sysinfo/lsconf.output\n          /usr/bin/mkdir $supportstore/odm_info\n          /usr/bin/odmget Config_Rules > $supportstore/odm_info/Config_Rules.lst\n          /usr/bin/odmget CuVPD > $supportstore/odm_info/CuVPD.lst\n          /usr/bin/odmget CuDv > $supportstore/odm_info/CuDv.lst\n          /usr/bin/odmget CuAt > $supportstore/odm_info/CuAt.lst\n          /usr/bin/odmget CuDvDr > $supportstore/odm_info/CuDvDr.lst\n          /usr/bin/odmget PdDv > $supportstore/odm_info/PdDv.lst\n          /usr/bin/odmget PdAt > $supportstore/odm_info/PdAt.lst\n          /usr/bin/ps -aef > ${supportstore}/sysinfo/ps_aef.txt\n          /usr/bin/ps auxw > ${supportstore}/sysinfo/ps_auxw.txt\n          uptime > $supportstore/uptime.txt\n          sar -A 5 3 > ${supportstore}/sysinfo/sar_A_5_3.log\n          errpt -A > ${supportstore}/sysinfo/errpt_A.log\n          ipcs -a > ${supportstore}/sysinfo/ipcs_a.log\n          vmstat -v > ${supportstore}/sysinfo/vmstat_v.log\n          vmstat -l > ${supportstore}/sysinfo/vmstat_l.log\n          vmstat -s > ${supportstore}/sysinfo/vmstat_s.log\n          svmon -G > ${supportstore}/sysinfo/svmon_G.log\n          svmon -P > ${supportstore}/sysinfo/svmon_P.log\n          mpstat > ${supportstore}/sysinfo/mpstat.log\n          vmo -a > ${supportstore}/sysinfo/vmo_a.log\n          pagesize -af > ${supportstore}/sysinfo/pagesizes.log\n          iostat -alDRT 1 1 > ${supportstore}/sysinfo/iostat_alDRT_1_1.log\n       ;;\n       *)\n         echo \"OS is not supported\"\n         return 1\n         ;;\nesac\n\nmkdir $supportstore/target\n$vx_dir/bin/cdpcli  --listtargetvolumes 2>&1 > $supportstore/target/cdpcli-listtargetvolumes\n$vx_dir/bin/cdpcli  --showreplicationpairs 2>&1 > $supportstore/target/cdpcli-showreplicationpairs\n$vx_dir/bin/cdpcli  --showsnapshotrequests 2>&1 > $supportstore/target/cdpcli-showsnapshotrequests\n\n$vx_dir/bin/cdpcli  --showreplicationpairs |grep Catalogue > $supportstore/target/retentionpath.log 2>&1 \n\ninstall_path=`echo $vx_dir | sed -e \"s/\\/[^\\/]*$//\"`;\ncp $install_path/patch.log $supportstore/\n\nif [ -d $install_path/ApplicationData/etc ]; then\n    cp  $install_path/ApplicationData/etc/*.log $supportstore/ 2>&1 > /dev/null\nfi\nfilename=\"$supportstore/target/retentionpath.log\"\nwhile read -r line\ndo\n    retname=$line\n\tretdbname=`echo $retname | awk -F ':' '{print $2}'`\n\tretpath=`echo $retdbname | awk -F 'cdp' '{print $1}'`\n\tmkdir -p $supportstore/$retpath;\n\tcp $retdbname $supportstore/$retpath\ndone < \"$filename\"\n\n#tar -cvf ${supportstore}/bitmap_files.tar /root/InMage*.VolumeLog  > /dev/null 2>&1\ntar -cvf $supportstore.tar $supportstore > /dev/null 2>&1\ngzip $supportstore.tar > /dev/null 2>&1\nrm -rf $supportstore \necho \"Compressed support materials file $supportstore.tar.gz\"\nexit;\n\n", "num_lines": 648}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ $# -ne 1 ]]; then\n    echo \"Insufficient number of args\"\n    exit 1\nfi\n\nINSTALL_DIR=$1\ninm_dmit=$INSTALL_DIR/inm_dmit\n\nsd_devices=`ls -1 /dev/sd*`\nfor i in $sd_devices; do\n    op=`$inm_dmit --op=get_blk_mq_status --src_vol=$i | grep -i 'enabled'`\n    ret=$?\n    #echo \"i: $i, ret: $ret\"\n    if [[ $ret == 0 ]]; then\n        echo \"blk_mq enabled\"\n        exit 1\n    fi\ndone\n\necho \"blk_mq disabled\"\n", "num_lines": 23}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\n########################\n## DECLARED VARIABLES ##\n########################\n\nLOG_FILE=/var/log/Post_Process_Linux_MT.log\n\nif [ ! -f /usr/local/.vx_version ] && [ ! -f /usr/local/.fx_version ]; then\n    echo \"FX/VX is not installed on this setup. Aborting the Post Process script execution.\"\n    exit 1\nfi\n\nif [ -f /usr/local/.vx_version ]; then\n    VX_INST_DIR=`grep 'INSTALLATION_DIR' /usr/local/.vx_version |awk -F\"=\" '{print $2}'`\nelse\n    echo \"VX is not installed on this setup.\"\nfi\n\nif [ -f /usr/local/.fx_version ]; then\n    FX_INST_DIR=`grep 'INSTALLATION_DIR' /usr/local/.fx_version |awk -F\"=\" '{print $2}'`\nelse\n    echo \"FX is not installed on this setup.\"\nfi\n\n###############\n## FUNCTIONS ##\n###############\n\nDO()\n{\n eval \"$1 2>> $LOG_FILE | tee -a $LOG_FILE\"\n}\n\nLOG()\n{\n echo \"$1\" >> $LOG_FILE\n}\n\nValidate_IP()\n{\n    IP=$1\n    echo $IP | grep \"\\.$\" >/dev/null 2>&1\n    if [ \"$?\" -eq \"0\" ]; then\n        DO 'echo \"Invalid IP:$IP. Try again with the correct IP\"'\n        exit 1\n    else\n\n        FLD1=`echo \"$IP\" | awk -F'.' '{print $1}'`\n        FLD2=`echo \"$IP\" | awk -F'.' '{print $2}'`\n        FLD3=`echo \"$IP\" | awk -F'.' '{print $3}'`\n        FLD4=`echo \"$IP\" | awk -F'.' '{print $4}'`\n        if [ -z \"${FLD1}\" -o -z \"${FLD2}\" -o -z \"${FLD3}\" -o -z \"${FLD4}\" ];then\n            DO 'echo -e \"Invalid IP:$IP. Try again with correct IP \"'\n            exit 1\n        else\n            oldIFS=$IFS\n            IFS=.\n            set -- $IP\n\n            if [ \"$#\" -ne \"4\" ]; then\n                DO 'echo \"Invalid IP:$IP. Try again with the correct IP\"'\n                exit 1\n            elif [ \"$1\" -eq \"0\" ]; then\n                DO 'echo \"Invalid IP:$IP. Try again with the correct IP\"'\n                exit 1\n            fi\n            IFS=$oldIFS\n        fi\n\n        for oct in $FLD1 $FLD2 $FLD3 $FLD4;\n        do\n            echo $oct | egrep \"^[0-9]+$\" >/dev/null 2>&1\n            if [ \"$?\" -ne \"0\" ]; then\n                DO 'echo -e \"Invalid IP:$IP. Try again with correct IP\"'\n                exit 1\n            else\n                if [ \"$oct\" -lt \"0\" -o \"$oct\" -gt \"255\" ]; then\n                    DO 'echo -e \"Invalid IP:$IP. Try again with correct IP\"'\n                    exit 1\n                fi\n            fi\n        done\n    fi\n}\n\nValidate_Port()\n{\n    CX_PORT=$1\n    echo $CX_PORT | grep -q \"^[0-9]\\+$\"\n    if [ $? -ne 0 ]; then\n        DO 'echo \"Invalid port. Try again with correct port in the range 1-65535.\"'\n        exit 1\n    fi\n    if [ \"$CX_PORT\" -lt \"1\" -o \"$CX_PORT\" -gt \"65535\" ]; then\n        DO 'echo \"Invalid port. Try again with correct port in the range 1-65535.\"'\n        exit 1\n    fi\n}\n\nSuccess_Msg()\n{\n    DO 'echo '\n    DO 'echo \"Post Processing steps for Linux MT are successfully completed.\"'\n}\n\nReplace()\n{\n\n    DO 'echo \"Chosen CX IP is $SERVER_IP_ADDRESS\"'\n    DO 'echo \"Chosen CX PORT is $SERVER_PORT_NUMBER\"'\n    DO 'echo \"Chosen Agent is $AGENT_IP\"'\n\n    if [ ! -z \"$VX_INST_DIR\" ]; then\n\tDO 'echo '\n        DO 'echo \"Keeping ${AGENT_IP} in /etc/hosts\"'\n\tsed -i -e \"s|10.80.253.124|${AGENT_IP}|g\" /etc/hosts\n\n\tDO 'echo '\n        DO 'echo \"Changing Hostname key in drscout.conf with chosen CX IP : $SERVER_IP_ADDRESS\"'\n        sed -i -e \"s|^Hostname.*|Hostname=$SERVER_IP_ADDRESS|g\" $VX_INST_DIR/etc/drscout.conf\n        DO 'echo \"Changing Port key in drscout.conf with chosen CX PORT : $SERVER_PORT_NUMBER\"'\n        sed -i -e \"s|^Port.*|Port=$SERVER_PORT_NUMBER|g\" $VX_INST_DIR/etc/drscout.conf\n\n        if [ ! -z \"$GUID\" ];then\n            DO 'echo \"Adding HostId key in drscout.conf\"'\n            sed -i -e \"s|^HostId.*|HostId=$GUID|g\" $VX_INST_DIR/etc/drscout.conf\n        fi\n\n        DO 'echo '\n        DO 'echo \"Enabling vxagent service\"'\n        chkconfig --level 1235 vxagent on \n \n        DO 'echo '\n        DO 'echo \"Starting the vxagent service\"'\n        /etc/init.d/vxagent start \n    fi\n\n    if [ ! -z \"$FX_INST_DIR\" ]; then\n        DO 'echo '\n        DO 'echo \"Changing SVServer key in config.ini with chosen CX IP : $SERVER_IP_ADDRESS\"'\n        sed -i -e \"s|^SVServer =.*|SVServer = $SERVER_IP_ADDRESS|g\" $FX_INST_DIR/config.ini\n\n        DO 'echo \"Changing SVServerPort key in config.ini with chosen CX PORT : $SERVER_PORT_NUMBER\"'\n        sed -i -e \"s|^SVServerPort =.*|SVServerPort = $SERVER_PORT_NUMBER|g\" $FX_INST_DIR/config.ini\n\n        if [ ! -z \"$GUID\" ];then\n            DO 'echo \"Adding HostId key in config.ini\"'\n            sed -i -e \"s|^HostId =.*|HostId = $GUID|g\" $FX_INST_DIR/config.ini\n        fi\n\n        DO 'echo '\n        DO 'echo \"Moving /etc/svagent to /etc/init.d/\"'\n        mv /etc/svagent /etc/init.d/svagent >> $LOG_FILE 2>&1\n\n        DO 'echo \"Starting svagent service\"'\n        /etc/init.d/svagent start \n    fi\n\n    # If HOST_NAME argument is passed, we are changing the hostname and rebooting the system.\n    if [ ! -z \"$HOST_NAME\" ]; then\n        DO 'echo \"Changing the HOSTNAME value in /etc/sysconfig/network and invoking hostname command.\"'\n        sed -i -e \"s|HOSTNAME.*|HOSTNAME=$HOST_NAME|g\" /etc/sysconfig/network\n        hostname \"$HOST_NAME\"\n\n        #Rebooting the system to change the hostname.\n        DO 'echo \"Rebooting the system to change the hostname\"'\n        reboot\n    fi  \n\n}\n\n##########\n## MAIN ##\n##########\n\nDO 'echo '\nLOG \"-------------------------------------------------------------------\"\nLOG \"`date`\" \nLOG \"-------------------------------------------------------------------\"\n \nif [ ! -z $1 ]; then\n    if echo $1 | grep -q ^- ; then\n        while getopts :h:a:i:p:g:H: opt\n        do\n            case $opt in\n                i)SERVER_IP_ADDRESS=\"$OPTARG\";;\n                p)SERVER_PORT_NUMBER=\"$OPTARG\" ;;\n                a)AGENT_IP=\"$OPTARG\";;\n                g)GUID=\"$OPTARG\";;\n                H)HOST_NAME=\"$OPTARG\";;\n                h|-*|*) echo \"Usage: $0 [ -i <IP Address of the CX> ] [ -p <CX Server Port> ] [ -a <IP Address of the Agent> ] [ -g <GUID of CX Server> ] [ -H <HOTNAME> ]\"\n                    exit 1\n                    ;;\n            esac\n        done\n    fi\nelse\n    echo \"Please specify the installation options on the command-line.\"\n    exit 1\nfi\n\n# If SERVER_IP_ADDRESS, SERVER_PORT_NUMBER and AGENT_IP are not empty, we are validating them.\nif [ ! -z \"$SERVER_IP_ADDRESS\" -a ! -z \"$SERVER_PORT_NUMBER\" -a ! -z \"$AGENT_IP\" ]; then\n    Validate_IP \"$SERVER_IP_ADDRESS\"\n\n    Validate_Port \"$SERVER_PORT_NUMBER\"\n\n    Validate_IP \"$AGENT_IP\"\nelse\n    DO 'echo \"please enter -i <IP Address of the CX> -p <CX Server Port> -a <IP Address of the Agent> -g <GUID of CX Server> -H <HOSTNAME> as command line arguments to the script.\"'\n    exit 1\nfi\n\n\nEXISTING_GUID=`grep \"HostId\" $VX_INST_DIR/etc/drscout.conf|awk -F'=' '{print$2}'`\n\nif [ -z \"$EXISTING_GUID\" -a -z \"$GUID\" ];then\n    DO 'echo \"Generating fresh Host Guid.\"'\n    GUID=`uuidgen`\nfi\n\nReplace\n\nSuccess_Msg\n", "num_lines": 226}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\necho\necho \"========================================\" >> /var/log/TuneMaxRep.log\necho `date` >> /var/log/TuneMaxRep.log\n\nHomeLun=`mount |grep -w \"/home\" |awk '{print $1}'`\necho \"HomeLun : ${HomeLun}\" >> /var/log/TuneMaxRep.log\nif [ -n \"${HomeLun}\" ];then\n        blockdev --setra 65536 $HomeLun #32MB  readahead.\n\tmount -o noatime,nodiratime,remount,rw /home\nfi\n\necho \"cat dirty_background_ratio, default is 10\" >> /var/log/TuneMaxRep.log\ncat /proc/sys/vm/dirty_background_ratio >> /var/log/TuneMaxRep.log\n\necho \"cat dirty_ratio, default is 40\" >> /var/log/TuneMaxRep.log\ncat /proc/sys/vm/dirty_ratio >> /var/log/TuneMaxRep.log\n\necho \"cat dirty_writeback_centisecs, default is 499\" >> /var/log/TuneMaxRep.log\ncat /proc/sys/vm/dirty_writeback_centisecs >> /var/log/TuneMaxRep.log\n\necho \"cat dirty_expire_centisecs, default is 2999\" >> /var/log/TuneMaxRep.log\ncat /proc/sys/vm/dirty_expire_centisecs >> /var/log/TuneMaxRep.log\n\necho \"Tuning Linux VM parameters...\" >> /var/log/TuneMaxRep.log\necho \"setting dirty_background_ratio to 100\" >> /var/log/TuneMaxRep.log\necho 100 > /proc/sys/vm/dirty_background_ratio \n\necho \"setting dirty_ratio to 99 on Source\" >> /var/log/TuneMaxRep.log\necho 99 > /proc/sys/vm/dirty_ratio\n\necho \"setting dirty_writeback_centisecs to 499\" >> /var/log/TuneMaxRep.log\necho 499 > /proc/sys/vm/dirty_writeback_centisecs\n\necho \"setting dirty_expire_centisecs to 48000\" >> /var/log/TuneMaxRep.log\necho 48000 > /proc/sys/vm/dirty_expire_centisecs\n\necho \"========================================\" >> /var/log/TuneMaxRep.log\n", "num_lines": 40}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#//--------------------------------------------------------------------\n#//  <copyright file=\"UnifiedAgentConfigurator.sh\" company=\"Microsoft\">\n#//      Copyright (c) Microsoft Corporation. All rights reserved.\n#//  </copyright>\n#//\n#//  <summary>\n#//     This script uses to configure linux agent with CS or RCM service\n#//  </summary>\n#//\n#//--------------------------------------------------------------------\n\n#\n#//--------------------------------------------------------------------\n#\n#  Global Variables:\n#\n#//--------------------------------------------------------------------\n#\n\n# exporting LANG variable\nexport LANG=C\nexport LC_NUMERIC=C\n\nstarttime=$(date -Iseconds)\nexport SETUP_TELEDIR='/var/log/ASRsetuptelemetry'\nexport UPLOADED_TELEDIR='/var/log/ASRsetuptelemetry_uploaded'\nexport json_file=$SETUP_TELEDIR/ASRconfigsummary_`date '+%Y_%m_%d_%H_%M_%S'`.json\nexport televerbose_file=$SETUP_TELEDIR/ASRconfigverbose_`date '+%Y_%m_%d_%H_%M_%S'`.txt\nexport installtype=\"Configuration\"\nexport HOST_NAME=$(hostname)\nexport DRSCOUT_CONF=\"\"\nexport CXPS_PORT=\"9443\"\nTEMP_SUMMARY_FILE=\"/tmp/asrconfigsummary.txt\"\nexport INVOKER=\"CommandLine\"\nexport passphrasevalidated=0\nexport exit_code=0\nexport RUNID=$(cat /proc/sys/kernel/random/uuid)\n\numask 0002\nVX_VERSION_FILE=\"/usr/local/.vx_version\"\nDATE_TIME_STAMP=$(date  +'%d-%b-%Y--%T')\nLOGFILE='/var/log/ua_install.log'\n# Telemetry APIs which are common for install and \n# configurator references VERBOSE_LOGFILE\nVERBOSE_LOGFILE=\"$LOGFILE\"\nSILENT_ACTION=\"\"\nSCRIPT=`basename $0`\nAGENT_INSTALL_DIR=$(grep ^INSTALLATION_DIR $VX_VERSION_FILE | cut -d\"=\" -f2 | tr -d \" \")\nRCMCONFIG_FOLDER=\"/usr/local/InMage/config\"\nJQPATH=\"$AGENT_INSTALL_DIR/bin/jq\"\nsource $AGENT_INSTALL_DIR/bin/teleAPIs.sh\nDEFAULT_CONFIGURE_ERRORS_JSON='/var/log/InstallerErrors.json'\n\n#ErrorCode\nFailedWithErrors=97\nSuccededWithWarnings=98\nSucess=0\n\n# set_scenario and SetOP sets these values, must be set appropriately\n# before calling RecordOP\n# Note: Don't move these variables to common file teleAPIs.sh because\n# in bash child can only read parent script variables\nSCENARIO_NAME=\"PreConfiguration\"\nOP_NAME=\"ConfigurationStarted\"\n\n#\n# Function Name: trace_log_message()\n# \n#  Description  Prints date and time followed by all arguments to \n#               stdout and to LOG_FILE.  If -q is used, only send \n#               message to log file, not to stdout.  If no arguments \n#               are given, a blank line is returned to stdout and to \n#               LOG_FILE.\n#       \n#  Usage        trace_log_message [-q] \"Message\"\n#\n#  Notes        If -q is used, it must be the first argument.\n# \ntrace_log_message()\n{\n    QUIET_MODE=FALSE\n\n    if [ $# -gt 0 ]\n    then\n        if [ \"X$1\" = \"X-q\" ]\n        then\n            QUIET_MODE=TRUE\n            shift\n        fi\n    fi\n\n    if [ $# -gt 0 ]\n    then\n        DATE_TIME=`date '+%m/%d/%Y %H:%M:%S'`\n        \n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"${DATE_TIME}: $*\" >> ${LOGFILE}\n        else            \n            echo -e \"$@\"\n            echo \"${DATE_TIME} : $@ \" >> ${LOGFILE} 2>&1            \n        fi\n    else\n        if [ \"${QUIET_MODE}\" = \"TRUE\" ]\n        then\n            echo \"\" >> ${LOGFILE}\n        else\n            echo \"\" | tee -a ${LOGFILE}\n        fi\n    fi\n}\n\nprocess_configurator_exit_code()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n\n    local val=\"$1\"\n\n    # For CSPrime, configurator should return only 3 values : 0, 97, 98\n    if [ \"$CS_TYPE\" = \"CSPrime\" ]; then\n        if [ \"$val\" -ne \"0\" -a \"$val\" -ne \"$SuccededWithWarnings\" -a \"$val\" -ne \"$FailedWithErrors\" ]; then\n            log_to_json_file ConfiguratorInternalError \"Configurator failing with unknown error.\"\n            val=\"$FailedWithErrors\"\n        fi\n\n        if [ \"$val\" -eq \"$FailedWithErrors\" ]; then\n            trace_log_message \"Configurator failing with exit code : $val\"\n            trace_log_message \"Please check $CONFIGURE_ERRORS_JSON file for more details.\"\n        else\n            trace_log_message \"Configurator succeeding with exit code : $val\"\n            if [ \"$val\" -eq \"$SuccededWithWarnings\" ]; then\n                trace_log_message \"Please check $CONFIGURE_ERRORS_JSON file for more details.\"\n            fi\n        fi\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $val\n}\n\nexit_with_retcode() {\n    exit_code=$1\n    trace_log_message \"Check the log file $LOGFILE for detailed diagnostic messages or configuration success/failures...\"\n\n    process_configurator_exit_code \"$exit_code\"\n    exit_code=$?\n\n    if [ $exit_code = \"0\" ]; then\n        EndSummaryOP \"Success\"\n    else\n        EndSummaryOP \"Failed\"\n    fi\n    trace_log_message \"Configurator exiting with code: $exit_code\"\n    exit $exit_code\n}\n\ncheck_return_code()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local val=\"$1\"\n\n    if [ \"$val\" -ne \"0\" -a \"$val\" -ne \"$SuccededWithWarnings\" ]; then\n        trace_log_message -q \"EXITED $FUNCNAME\"\n        exit_with_retcode $val\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $val\n}\n\ninvoke_deamon_reload() {\n    # Inovke systemctl daemon-reload command if systemctl exists on the system.\n    which systemctl >/dev/null 2>&1\n    if [ $? -eq 0 ];then\n        trace_log_message -q \"systemctl command exists. Invoking the following commnad - systemctl daemon-reload\"\n        systemctl daemon-reload >> $LOGFILE 2>&1\n        if [ $? -eq 0 ];then\n            trace_log_message -q \"systemctl daemon-reload executed successfully.\"\n        else\n            trace_log_message -q \"systemctl daemon-reload execution failed.\"\n        fi\n    else\n       trace_log_message -q \"systemctl command doesn't exist.\"\n    fi\n}\n\n# FUNCTION: Creates softlinks for s2 and svagents binaries.\ncreate_soft_links()\n{\n\tcstype=$(grep ^CSType $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \" )\n    for exe in ${AGENT_INSTALL_DIR}/bin/s2 ${AGENT_INSTALL_DIR}/bin/svagents\n    do\n        # Remove exe if it exists already.\n        if [ -f ${exe} ] || [ -h ${exe} ] ; then\n            trace_log_message -q \"${exe} exists. Removing it.\"\n            rm -f ${exe}\n            if [ $? -eq 0 ]; then\n                trace_log_message -q \"Succesfully removed ${exe}.\"\n            else\n                trace_log_message \"Failed to remove ${exe}.\"\n                return 1\n            fi\n        else\n            trace_log_message -q \"${exe} doesn't exist.\"\n        fi\n\n        # Create softlink based on the VM platform.\n        if [ z\"${VM_PLATFORM}\" = z\"VmWare\" ]; then\n\t\t\tif [ \"$cstype\" = \"CSLegacy\" ]; then\n\t\t\t\tln -f -s ${exe}V2A ${exe} >> $LOGFILE 2>&1\n\t\t\t\tSLC_RET_VAL=$?\n\t\t\telse\n\t\t\t\tln -f -s ${exe}A2A ${exe} >> $LOGFILE 2>&1\n\t\t\t\tSLC_RET_VAL=$?\n\t\t\tfi\n        else\n            trace_log_message -q \"Invalid platform - ${VM_PLATFORM}.\"\n            return 1\n        fi\n\n        if [ ${SLC_RET_VAL} -eq 0 ]; then\n            trace_log_message -q \"Successfully created softlink for ${exe}.\"\n        else\n            trace_log_message \"Failed to create softlink for ${exe}. Exit code returned by ln: ${SLC_RET_VAL}.\"\n            return 1\n        fi\n    done\n    return 0\n}\n\n#\n# Function Name: stop_agent_service\n#\n# Description:\n#    This function stops the Unified agent (Vx) service.\n#\n# Parameters:None\n#\n# Return Value: On success it returns zero, else returns non-zero\n#\n# Exceptions:None\n#\nstop_agent_service() {\n    local return_value=0\n    SetOP \"StopAgentService\"\n    trace_log_message \"Stopping Vx agent service...\"\n\n    if list_contains \"$SYSTEMCTL_DISTRO\" \"$OS\"; then\n        trace_log_message -q \"Invoking following command to stop vxagent service - systemctl stop vxagent.\"\n        systemctl stop vxagent >> $LOGFILE 2>&1\n        SVAGENTS_PID=`pgrep svagents`\n        APP_SERVICE_PID=`pgrep appservice`\n        if [ ! -z \"$SVAGENTS_PID\" ] || [ ! -z \"$APP_SERVICE_PID\" ]; then\n            trace_log_message -q \"SVAGENT_PID: ${SVAGENTS_PID}, APP_SERVICE_PID: ${APP_SERVICE_PID}\"\n            return_value=2\n        fi\n    else\n        trace_log_message -q \"Invoking ${AGENT_INSTALL_DIR}/bin/stop script to stop vxagent service.\"\n        ${AGENT_INSTALL_DIR}/bin/stop >> $LOGFILE 2>&1\n        return_value=$?\n    fi\n\n    if [ $return_value -eq 2 ]; then\n        trace_log_message -q \"Passing force argument to stop script.\"\n        ${AGENT_INSTALL_DIR}/bin/stop force >> $LOGFILE 2>&1\n        return_value=$?\n        if [ $return_value -eq 2 ]; then\n            trace_log_message \"Could not stop Vx agent service. Please re-try after sometime. Aborting...\"\n            return_value=115\n        fi\n    fi\n\n    trace_log_message -q \"stop agent service return value : $return_value\"\n    if [ $return_value -eq 0 ]; then\n        RecordOP 0 \"\"\n    else\n        RecordOP $return_value \"Couldn't stop VX agent service\"\n    fi\n    return $return_value\n}\n\n# \n# Function Name: start_agent_service\n# \n# Description:\n#    This function starts the Unified agent (Vx) services. \n# \n# Parameters:None\n# \n# Return Value: On success it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nstart_agent_service() {\n    local return_value=0    \n    if [ \"${AGENT_ROLE}\" = \"MasterTarget\" ]; then\n        SetOP \"ScoutTuningExe\"\n        trace_log_message -q \"Executing ${INSTALLATION_DIR}/bin/ScoutTuning -version \\\"${VERSION}\\\" -role \\\"vconmt\\\" command\"\n        ${INSTALLATION_DIR}/bin/ScoutTuning -version ${VERSION} -role vconmt >> $LOGFILE 2>&1\n        RecordOP 0 \"\"\n    fi\n\n    SetOP \"StartVxAgent\"\n    trace_log_message -q \"Starting VX agent daemon...\"\n\n    if list_contains \"$SYSTEMCTL_DISTRO\" \"$OS\"; then\n        chmod +x /etc/vxagent/bin/vxagent\n        invoke_deamon_reload\n        trace_log_message -q \"Invoking following command to start vxagent service - systemctl start vxagent.\"\n        systemctl start vxagent >> $LOGFILE 2>&1\n        return_value=$?\n        sleep 5 ;\n        /etc/vxagent/bin/vxagent status >> $LOGFILE 2>&1\n    else\n        chmod +x /etc/init.d/vxagent\n        trace_log_message -q \"Invoking following command to start vxagent service - /etc/init.d/vxagent start.\"\n        /etc/init.d/vxagent start >> $LOGFILE 2>&1\n        return_value=$?\n        /etc/init.d/vxagent status >> $LOGFILE 2>&1\n    fi\n\n    trace_log_message -q \"Start vxagent service return value : $return_value\"\n    if [ $return_value -ne 0 ]; then\n        trace_log_message -q \"Failed to start vxagent service with exit code : 44\"\n        RecordOP 44 \"Couldn't start VX agent service\"\n        stop_agent_service\n        return 44\n    fi\n    RecordOP 0 \"\"\n\t\n    echo \"Starting UA Respawn daemon...\"\n    if list_contains \"$SYSTEMCTL_DISTRO\" \"$OS\"; then\n        systemctl restart uarespawnd >> $LOGFILE 2>&1\n    else\n        /etc/init.d/uarespawnd restart >> $LOGFILE 2>&1\n    fi\n    return_value=$?\n    RecordOP $return_value \"\"\n    \n    return $return_value\n}\n\n# \n# Function Name: set_permissions\n# \n# Description:\n#    This function sets restricted permissions\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero\n# \n# Exceptions:None\n# \n set_permissions() {\n    # Adding 770 permissions to main installation directory.\n    trace_log_message -q \"Adding 770 permissions to main installation directory.\"\n    chmod -R 770 $INSTALLATION_DIR/../ >> $LOGFILE 2>&1\n    chmod 700 $RCMINFO_CONF >> $LOGFILE 2>&1\n    chmod 700 /usr/local/InMage/private/rcm* >> $LOGFILE 2>&1  \n    chmod 700 /usr/local/InMage/certs/rcm* >> $LOGFILE 2>&1      \n    \n    # Setting write permissions for /proc/scsi_tgt/InMageEMD/InMageEMD /proc/scsi_tgt/groups/Default/devices\n    [ -e /proc/scsi_tgt/InMageEMD/InMageEMD ] && \\\n    chmod 666 /proc/scsi_tgt/InMageEMD/InMageEMD /proc/scsi_tgt/groups/Default/devices\n\n    return 0\n}\n\n# \n# Function Name: get_client_cert\n# \n# Description:\n#    This function used to extract the private & public keys from RcmVaultCreds certificate file\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nget_client_cert() {\n    local return_value=0\n    local pfx_cert_file='/usr/local/InMage/private/rcm.pfx'    \n    local public_cert_file='/usr/local/InMage/certs/rcm.crt'      \n    SetOP \"GetAuthCertificate\"\n    local errorstring=\"\"\n\n    # Create a pfx certification file from encoded value\n    cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .aadDetails.authCertificate | base64 -d > $pfx_cert_file\n    \n    # Extract and create public certificate and private key files\n    $INSTALLATION_DIR/bin/gencert -x $pfx_cert_file | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > $public_cert_file     \n    \n    # Generates fingerprint from public certificate\n    if [ -s \"$public_cert_file\" ]; then \n        trace_log_message -q \"Generating fingerprint value from public certificate\"\n        FINGERPRINT=$(openssl x509 -inform PEM -in ${public_cert_file} -fingerprint -noout | cut -d= -f2|tr -d \":\")\n        if [ -z \"$FINGERPRINT\" ]; then\n            trace_log_message \"Failed to fetch fingerprint value from $public_cert_file file.\"\n            errorstring=\"Failed to fetch fingerprint\"\n            return_value=1\n        fi\n    else\n        trace_log_message \"Failed to fetch public certificate from $pfx_cert_file file\"\n        errorstring=\"Failed to fetch public certificate\"\n        return_value=1\n    fi\n    \n    trace_log_message -q \"Get client certificate return value: $return_value\"\n    RecordOP $return_value $errorstring\n    return $return_value        \n}\n\nprocess_azurercmcli_exitcode()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n\n    local cli_val=\"$1\"\n    local ret_val=\"$cli_val\"\n    if [ \"$cli_val\" -eq \"2\" ]; then\n        ret_val=\"$FailedWithErrors\"\n    elif [ \"$cli_val\" -eq \"1\" ]; then\n        ret_val=\"$SuccededWithWarnings\"\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret_val\n}\n\n#\n# Function Name: update_config_general\n#\n# Description:\n#    This function is used to update settings in a conf file\n#\n# Parameters:filename, key, val\n#\n# Return Value: On successful it returns zero, else returns non-zero\n#\n# Exceptions:None\n#\nupdate_config_general()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n\n    if [ \"$#\" -ne \"3\" ]; then\n        trace_log_message -q \"Invalid number of arguments\"\n        return 1\n    fi\n    local file_name=\"$1\"\n    local key=\"$2\"\n    local val=\"$3\"\n    trace_log_message -q \"Updating $key in $file_name\"\n    sed -i -e \"/^${key}/d; /^\\[vxagent\\]/ a ${key}=$val\" $file_name >> $LOGFILE 2>&1\n    local ret=$?\n    if [ \"$ret\" -ne 0 ]; then\n        trace_log_message -q \"Failed to update config file : $file_name\"\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret\n}\n\nupdate_discovery()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local ret=0\n\n    echo \"$IS_CREDENTIAL_LESS_DISCOVERY\" | grep -qi \"true\" && IS_CREDENTIAL_LESS_DISCOVERY=1\n    echo \"$IS_CREDENTIAL_LESS_DISCOVERY\" | grep -qi \"false\" && IS_CREDENTIAL_LESS_DISCOVERY=0\n    local disovery_from_drscout=`cat $DRSCOUT_CONF | grep \"IsCredentialLessDiscovery\" | cut -f2 -d\"=\"`\n\n    local fin_val=\"\"\n    if [ -z \"$IS_CREDENTIAL_LESS_DISCOVERY\" ]; then\n        if [ -z \"$disover_from_drscout\" ]; then\n            fin_val=0\n        else\n            fin_val=\"$disover_from_drscout\"\n        fi\n    elif [ \"$IS_CREDENTIAL_LESS_DISCOVERY\" -eq \"0\" ]; then\n        if [ \"$disover_from_drscout\" = \"1\" ]; then\n            trace_log_message -q \"Change from credential-less discovery to credential-based discovery is not supported.\"\n            trace_log_message -q \"drscout val : $disovery_from_drscout, param passed in configurator : $IS_CREDENTIAL_LESS_DISCOVERY\"\n            ret=1\n        else\n            fin_val=0\n        fi\n    elif [ \"$IS_CREDENTIAL_LESS_DISCOVERY\" -eq \"1\" ]; then\n        if [ \"$disover_from_drscout\" = \"0\" ]; then\n            trace_log_message -q \"Change from credential-based discovery to credential-less discovery is not supported.\"\n            trace_log_message -q \"drscout val : $disovery_from_drscout, param passed in configurator : $IS_CREDENTIAL_LESS_DISCOVERY\"\n            ret=1\n        else\n            fin_val=1\n        fi\n    else\n        trace_log_message -q \"Invalid value for credential less discovery flag : $IS_CREDENTIAL_LESS_DISCOVERY\"\n        ret=1\n    fi\n\n    if [ \"$ret\" -eq \"0\" ]; then\n        update_config_general \"$DRSCOUT_CONF\" \"IsCredentialLessDiscovery\" \"$fin_val\"\n        ret=$?\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret\n}\n\nrcm_exec_with_common_params()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local ret=0\n\n    local params=(\"$@\")\n    trace_log_message -q \"Params passed : ${params[@]}\"\n    params+=(\"--errorfilepath\" \"$CONFIGURE_ERRORS_JSON\")\n    if [ \"$CS_TYPE\" = \"CSPrime\" ]; then\n        params+=(\"--logfile\" \"$LOGFILE\")\n    fi\n\n    trace_log_message -q \"--------------------------------------------------------\"\n    trace_log_message -q \"Executing the command : ${INSTALLATION_DIR}/bin/AzureRcmCli ${params[@]}\"\n    ${INSTALLATION_DIR}/bin/AzureRcmCli \"${params[@]}\" >> $LOGFILE 2>&1\n    ret=$?\n    trace_log_message -q \"AzureRcmCli operation exit code : $ret\"\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret\n}\n\n#\n# Function Name: unregister_agent\n#\n# Description:\n#    Unregisters source agent and machine with RCM server. Proceeds ahead even if they fails.\n#\t It also invokes AzureRcmCli --cleanup operation. \n#\n# Return Value: Returns non-zero exit code when AzureRcmCli cleanup operation fails, otherwise returns zero.\nunregister_agent() {\n    # Unregister source agent.\n    SetOP \"UnregisterSourceAgent\"\n    trace_log_message \"Unregistering source agent with the RCM Server.\"\n    local params=(\"--unregistersourceagent\")\n    rcm_exec_with_common_params \"${params[@]}\"\n    UNREGAGENT_RETVAL=$?\n    trace_log_message -q \"AzureRcmCli --unregistersourceagent exit code : $UNREGAGENT_RETVAL\"\n\n    if [ $UNREGAGENT_RETVAL -eq 0 ] || [ $UNREGAGENT_RETVAL -eq 144 ]; then\n        trace_log_message \"Successfully unregistered source agent with the RCM Server.\"\n    else\n        trace_log_message \"Failed to unregister source agent with the RCM Server.\"\n    fi\n\n\tif [ $UNREGAGENT_RETVAL -eq 0 ] || [ $UNREGAGENT_RETVAL -eq 144 ]; then\n        RecordOP 0 \"\"\n    else\n        RecordOP $UNREGAGENT_RETVAL \"Failed to unregister source agent with RCM\"\n    fi\n\n    # Unregister machine.\n    SetOP \"UnregisterMachine\"\n    trace_log_message \"Unregistering machine  with the RCM Server.\"\n    local params=(\"--unregistermachine\")\n    rcm_exec_with_common_params \"${params[@]}\"\n    UNREGMACHINE_RETVAL=$?\n    trace_log_message -q \"AzureRcmCli --unregistermachine exit code : $UNREGMACHINE_RETVAL\"\n\n    if [ $UNREGMACHINE_RETVAL -eq 0 ] || [ $UNREGMACHINE_RETVAL -eq 144 ]; then\n        trace_log_message \"Successfully unregistered machine with the RCM Server.\"\n    else\n        trace_log_message \"Failed to unregister machine with the RCM Server.\"\n    fi\n\n    if [ $UNREGMACHINE_RETVAL -eq 0 ] || [ $UNREGMACHINE_RETVAL -eq 144 ]; then\n        RecordOP 0 \"\"\n    else\n        RecordOP $UNREGMACHINE_RETVAL \"Failed to unregister machine with RCM\"\n    fi\n\n    # AzureRcmCli cleanup.\n    SetOP \"AzureRcmCliCleanup\"\n    local params=(\"--cleanup\")\n    rcm_exec_with_common_params \"${params[@]}\"\n    CLEANUP_RETVAL=$?\n\ttrace_log_message -q \"AzureRcmCli --cleanup exit code: $CLEANUP_RETVAL\"\n\n    if [ $CLEANUP_RETVAL -eq 0 ]; then\n        RecordOP 0 \"\"\n        trace_log_message -q \"AzureRcmCli --cleanup has succeeded.\"\n    else\n        RecordOP $CLEANUP_RETVAL \"AzureRcmCli cleanup has failed\"\n        trace_log_message -q \"AzureRcmCli --cleanup has failed.\"\n    fi\n\n    if [ $CLEANUP_RETVAL -eq 2 ]; then\n        CLEANUP_RETVAL=$FailedWithErrors\n    fi\n    return $CLEANUP_RETVAL\n}\n\n# \n# Function Name : byteswapped_biosid\n#\n# Description:\n#\t\tThis function converts the biosid to byteswapped bios id\n#\n# Parameters : $original_bios_id, the bios id of the system\n#\n# Return value: None\n#\n# Exceptions : None\n#\nbyteswapped_biosid() {\n\tlocal original_bios_id=\"$1\"\n\t\n\twords=([0]=${original_bios_id:0:2} [1]=${original_bios_id:2:2} [2]=${original_bios_id:4:2} [3]=${original_bios_id:6:2} [4]=${original_bios_id:9:2} [5]=${original_bios_id:11:2} [6]=${original_bios_id:14:2} [7]=${original_bios_id:16:2})\n    BYTESWAPPED_BIOSID=\"${words[3]}${words[2]}${words[1]}${words[0]}-${words[5]}${words[4]}-${words[7]}${words[6]}-${original_bios_id:19:17}\"\n}\n\n\n# \n# Function Name: parse_update_rcm_creds\n# \n# Description:\n#    This function used to parse RCM Creds file and updates RCMInfo.conf\n# \n# Parameters:$rcmcreds_file\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nparse_update_rcm_creds() {\n    local rcmcreds_file=\"$1\"\n    local return_value=0\n\n    SetOP \"ParseRCMcreds\"\n\n    # Parse RCM management details and update RCMInfo.conf\n    RCM_URI=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .rcmUri)\n    RCM_MGMT_ID=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .managementId)\n    RCM_CLIREQ_ID=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .clientRequestId)\n    RCM_ACTIVITY_ID=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .activityId)\n\t\n\t# On RHEL5, the /sys interface is not available so using \"/usr/sbin/dmidecode -s system-uuid\" command to get the BIOS-ID\n\tif [ -e /sys/class/dmi/id/product_uuid ]; then\n\t\tSYSTEM_BIOS_ID=$(cat /sys/class/dmi/id/product_uuid)\n\telse\n\t\tSYSTEM_BIOS_ID=$(/usr/sbin/dmidecode -s system-uuid)\n\tfi\n    SERVICE_CONNECTION_MODE=\"direct\"\n\n   #Check if END_POINT_TYPE_NAME is found in the RCMInfo.conf file or not\n   END_POINT_TYPE_NAME=$(grep ^EndPointType $RCMINFO_CONF | cut -d\"=\" -f1 | tr -d \" \")\n\n   #If EndPointType is not found, then add entry in RCMInfo.conf file\n    if [ -z \"$END_POINT_TYPE_NAME\" ]; then\n        sed -i '/\\[rcm.auth\\]/i EndPointType=' $RCMINFO_CONF\n    fi\n\n   #Read the EndPointType property obtained from creds file from SRS (coming as vmNetworkTypeBasedOnPrivateEndpoint)\n   END_POINT_TYPE_VALUE=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .vmNetworkTypeBasedOnPrivateEndpoint)\n   if [ \"$END_POINT_TYPE_VALUE\" = \"null\" ]; then\n         END_POINT_TYPE_VALUE=\"Public\"\n   fi\n\n    # Clean up existing settings and generate new HostId if ManagementId in RCMCredentials file is different from RCMInfo.conf.\n    RCM_CONF_MGMT_ID=$(grep ^ManagementId $RCMINFO_CONF | cut -d\"=\" -f2 | tr -d \" \")\n\tRCM_CONF_BIOS_ID=$(grep ^BiosId $RCMINFO_CONF | cut -d\"=\" -f2 | tr -d \" \")\n\n    trace_log_message -q \"RCM_MGMT_ID=$RCM_MGMT_ID\"\n    trace_log_message -q \"RCM_CONF_MGMT_ID=$RCM_CONF_MGMT_ID\"\n\ttrace_log_message -q \"RCM_CONF_BIOS_ID=$RCM_CONF_BIOS_ID\"\n\ttrace_log_message -q \"SYSTEM_BIOS_ID=$SYSTEM_BIOS_ID\"\n    trace_log_message -q \"END_POINT_TYPE_VALUE=$END_POINT_TYPE_VALUE\"\t\n\tBYTESWAPPED_BIOSID=$SYSTEM_BIOS_ID\n\tbyteswapped_biosid \"$SYSTEM_BIOS_ID\"\n\t\n\tif [ -n \"$RCM_CONF_MGMT_ID\" ]; then\n\t\tif [[ $(tr [A-Z] [a-z] <<<\"$RCM_MGMT_ID\") != $(tr [A-Z] [a-z] <<<\"$RCM_CONF_MGMT_ID\") ]]; then\n\t\t\ttrace_log_message -q \"Invoking unregister_agent as RCM_MGMT_ID and RCM_CONF_MGMT_ID are different.\"\n\t\t\tunregister_agent || exit_with_retcode $?\n\n\t\t\ttrace_log_message -q \"Generating new HostId as ManagementId in RCMCredentials file is different from RCMInfo.conf\"\n\t\t\tgenerate_host_id \"true\"\n\t\telse\n\t\t\tSetOP \"ValidateBiosId\"\n\t\t\tif [ $(tr [a-z] [A-Z] <<<\"$SYSTEM_BIOS_ID\") != $(tr [a-z] [A-Z] <<<\"$RCM_CONF_BIOS_ID\") ] && [ $(tr [a-z] [A-Z] <<<\"$BYTESWAPPED_BIOSID\") != $(tr [a-z] [A-Z] <<<\"$RCM_CONF_BIOS_ID\") ]; then\n\t\t\t\ttrace_log_message -q \"BiosId of the machine and biosId in the RCM Config are different (and) ManagementID in RCM Credentials file and RCM Conf file are same.\"\n\t\t\t\tRecordOP 118 \"BiosId mismatch found\"\n\t\t\t\treturn 118\n\t\t\tfi\n\t\t\tRecordOP 0 \"\"\n\t\tfi\n\telse\n\t\ttrace_log_message -q \"Generating new hostId as ManagementId in RCM Conf is null.\"\n\t\tgenerate_host_id \"true\"\n    fi\n\n    # Clean up existing settting when ManagementId in RCMCredentials file is empty and PLATFORM_CHANGE value in drscout.conf is VmWareToAzure.\n    PLATFORM_CHANGE=$(grep \"^PlatformChange=\" $INSTALLATION_DIR/etc/drscout.conf | cut -d= -f2)\n    if [ -z \"$RCM_CONF_MGMT_ID\" ] && [ \"${PLATFORM_CHANGE}\" = \"VmWareToAzure\" ]; then\n        trace_log_message -q \"Invoking unregister_agent as RCM_MGMT_ID is empty and PLATFORM_CHANGE value is VmWareToAzure.\"\n        unregister_agent || exit_with_retcode $?\n    fi\n    \n    # Update [rcm] section in RCMInfo.conf file\n    sed -i -e \"s|ServiceUri=.*|ServiceUri=$RCM_URI|g; s|ManagementId=.*|ManagementId=$RCM_MGMT_ID|g; \\\n\ts|ClientRequestId=.*|ClientRequestId=$RCM_CLIREQ_ID|g; s|ActivityId=.*|ActivityId=$RCM_ACTIVITY_ID|g; \\\n        s|BiosId=.*|BiosId=$SYSTEM_BIOS_ID|g; s|EndPointType=.*|EndPointType=$END_POINT_TYPE_VALUE|g; \\\n        s|ServiceConnectionMode=.*|ServiceConnectionMode=$SERVICE_CONNECTION_MODE|g\" $RCMINFO_CONF >> $LOGFILE 2>&1\n    \n    # Parse Authentication details and update RCMInfo.conf\n    get_client_cert || return $? # Get AADAuthCert from rcmCred's pfx certificate\n    AAD_AUTH_CERTIFICATE=$FINGERPRINT\n    AAD_SERVICE_URI=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .aadDetails.serviceUri)\n    AAD_TENANT_ID=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .aadDetails.tenantId)\n    AAD_CLIENT_ID=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .aadDetails.clientId)\n    AAD_AAUDIENCE_URI=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .aadDetails.audienceUri)\n    \n    #Update [rcm.auth] section in RCMInfo.conf file\n    sed -i -e \"s|AADUri=.*|AADUri=$AAD_SERVICE_URI|g; s|AADAuthCert=.*|AADAuthCert=$AAD_AUTH_CERTIFICATE|g;\\\n        s|AADTenantId=.*|AADTenantId=$AAD_TENANT_ID|g; s|AADClientId=.*|AADClientId=$AAD_CLIENT_ID|g;\\\n        s|AADAudienceUri=.*|AADAudienceUri=$AAD_AAUDIENCE_URI|g\" $RCMINFO_CONF  >> $LOGFILE 2>&1\n    \n    # Parse Relay details and update RCMInfo.conf\n    if $(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -e 'has(\"relayDetails\")' >/dev/null 2>&1) && \\\n        [ \"$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .relayDetails)\" != \"null\" ]\n    then\n        RELAY_KEY_NAME=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .relayDetails.relayKeyPolicyName)\n        RELAY_SHARED_KEY=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .relayDetails.relaySharedKey)\n        RELAY_SERVICE_PATH_SUFFIX=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .relayDetails.relayServicePathSuffix)\n        EXPIRY_TIMEOUT_INSECONDS=$(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -r .relayDetails.expiryTimeoutInSeconds)\n        SERVICE_CONNECTION_MODE=\"relay\"\n    \n        #Update [rcm.relay] section in RCMInfo.conf file\n        sed -i -e \"s|RelayKeyPolicyName=.*|RelayKeyPolicyName=$RELAY_KEY_NAME|g; s|RelaySharedKey=.*|RelaySharedKey=$RELAY_SHARED_KEY|g;\\\n            s|RelayServicePathSuffix=.*|RelayServicePathSuffix=$RELAY_SERVICE_PATH_SUFFIX|g;\\\n            s|ExpiryTimeoutInSeconds=.*|ExpiryTimeoutInSeconds=$EXPIRY_TIMEOUT_INSECONDS|g;\\\n            s|ServiceConnectionMode=.*|ServiceConnectionMode=$SERVICE_CONNECTION_MODE|g\" $RCMINFO_CONF  >> $LOGFILE 2>&1\n    fi\n    \n    sed -i -e \"s|^RcmSettingsPath=.*|RcmSettingsPath=$RCMINFO_CONF|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n    sed -i -e \"s/null//g\" $RCMINFO_CONF\n\t\n\trcmConfContent=`cat $RCMINFO_CONF`\n\ttrace_log_message -q \"Rcm info.conf contents are : $rcmConfContent\"\n    \n    trace_log_message -q \"RCM Creds file parse and update RCMInfo.conf return value: $return_value\"\n    if [ $return_value -eq 0 ]; then\n        RecordOP 0 \"\"\n    else\n        RecordOP $return_value \"Parse and update RCM creds failed\"\n    fi\n    return $return_value\n}\n\n#\n# Function Name: generate_host_id\n#\n# Description:\n#    This function will fetch hostid from drscout.conf\n#    New hostId is generated only in case of below conditions. Otherwise, existing HostId in drscout.conf is used.\n#    1) gen_host_id flag is set to true\n#    2) HostId value in drscout.conf is either empty or default value(1234_45466_67689).\n#\n# Parameters:gen_host_id\n#\n# Return Value:None\n#\n# Exceptions:None\n#\ngenerate_host_id()\n{\n\tlocal gen_host_id=\"$1\"\n\tSetOP \"GenerateHostId\"\n\t\n\tif [ \"$gen_host_id\" = \"true\" ]; then\n\t\ttrace_log_message -q \"Generating new HostId\"\n\t\tUNIQUE_HOST_ID=$(cat /proc/sys/kernel/random/uuid)\n\telse\n\t\tDRSCOUT_HOST_ID=$(grep ^HostId $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n\t\ttrace_log_message -q \"HostId value in $DRSCOUT_CONF : $DRSCOUT_HOST_ID\"\n\t\tif [ ! -z \"$DRSCOUT_HOST_ID\" ] && [ \"$DRSCOUT_HOST_ID\" != \"1234_45466_67689\" ]\n\t\tthen\n\t\t\ttrace_log_message -q \"HostId in DRSCOUT Config is not null/default value. Using existing hostId.\"\n\t\t\tUNIQUE_HOST_ID=$DRSCOUT_HOST_ID\n\t\telse\n\t\t\ttrace_log_message -q \"HostId in DRSCOUT Config is either null or default value. Generating new hostId.\"\n\t\t\tUNIQUE_HOST_ID=$(cat /proc/sys/kernel/random/uuid)\n\t\tfi\n\tfi\n\t\n\ttrace_log_message -q \"Writing HostId=${UNIQUE_HOST_ID} to $DRSCOUT_CONF\"\n\tsed -i -e \"s|^HostId.*|HostId=${UNIQUE_HOST_ID}|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\n\tRecordOP 0 \"Generated host ID $UNIQUE_HOST_ID\"\n}\n\nupdate_drscout_config()\n{\n\tgenerate_host_id \"false\"\n\n        SetOP \"UpdatingDrscout\"\n\t\t# On RHEL5, the /sys interface is not available so using \"/usr/sbin/dmidecode -s system-uuid\" command to get the BIOS-ID\n\t\t# Same logic is used for getting BiosID in portablehelpersmajor.cpp GetSystemUUID() function as well\n\t\t# Do not change this order\n\t\tif [ -e /sys/class/dmi/id/product_uuid ]; then\n\t\t\tBIOS_ID=$(cat /sys/class/dmi/id/product_uuid)\n\t\telif [ -x /usr/sbin/dmidecode ]; then\n\t        BIOS_ID=$(/usr/sbin/dmidecode -s system-uuid)\n\t\tfi\n\t\tif [ ! -e \"$RCMINFO_CONF\" ]; then \n\t\t\ttouch $RCMINFO_CONF\n\t\t\techo \"[rcm]\" >> $RCMINFO_CONF\n\t\tfi\n\t\t\n\t\tgrep -i \"BiosId\" $RCMINFO_CONF >> $LOGFILE 2>&1\n\t\tif [ $? -eq 0 ]; then\n\t\t\ttrace_log_message \"Updating bios id in RCMInfo.conf\"\n\t\t    sed -i -e \"s|^BiosId.*|BiosId=$BIOS_ID|g\" $RCMINFO_CONF >> $LOGFILE 2>&1\n\t\telse\n\t\t\ttrace_log_message \"Writing new bios id in RCMInfo.conf\"\n\t\t    sed -i -e \"/rcm/ a BiosId=$BIOS_ID\" $RCMINFO_CONF >> $LOGFILE 2>&1\n\t\tfi\n                \n                if [ ! -z \"$CLIENT_REQUEST_ID\" ]; then\n\t\t\ttrace_log_message \"Updating client request id in RCMInfo.conf\"\n                        sed -i -e \"s|^ClientRequestId.*|ClientRequestId=$CLIENT_REQUEST_ID|g\" $RCMINFO_CONF >> $LOGFILE 2>&1\n\t\tfi\n\t\t\n\t\ttrace_log_message -q \"Writing RcmInfo path to $DRSCOUT_CONF\"\n\t\tsed -i -e \"/^RcmSettingsPath/d; /^HostId/ a RcmSettingsPath=$RCMINFO_CONF\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\n\treturn 0\n}\n\nupdate_drscout_config_for_cs()\n{\n\ttrace_log_message -q \"Writing Hostname = $CS_IP_ADDRESS to $DRSCOUT_CONF\"\n\ttrace_log_message -q \"Writing Port = $CS_PORT_NUMBER to $DRSCOUT_CONF\"\n    sed -i -e \"s|^Hostname.*|Hostname = $CS_IP_ADDRESS|g; s|^Port.*|Port = $CS_PORT_NUMBER|g\" $DRSCOUT_CONF\n\n\tif [ -n \"$EXTERNAL_IP\" ]; then\n\t    trace_log_message -q \"Writing ExternalIpAddress=$EXTERNAL_IP to $DRSCOUT_CONF\"\n\t\tgrep -i \"ExternalIpAddress\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\tif [ $? -eq 0 ]; then\n\t\t    sed -i -e \"s|^ExternalIpAddress.*|ExternalIpAddress=$EXTERNAL_IP|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\telse\n\t\t    sed -i -e \"/^HostId/ a ExternalIpAddress=$EXTERNAL_IP\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\tfi\n\tfi\n\t\n\treturn 0\n}\n\n# \n# Function Name: cs_agent_registration\n# \n# Description:\n#    This function used to invoke cdpcli command to register host with V2A CS\n# \n# Parameters:$agent\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \ncs_agent_registration()\n{\n    local agent=\"$1\"\n    local count=1\n\n    case \"$agent\" in\n        Vx)\n            cstype=$(grep ^CSType $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \" )\n\n            if [ \"${AGENT_ROLE}\" = \"MasterTarget\" -o \"$cstype\" = \"CSLegacy\" ]; then\n                # Making an explicit agent registration call using ${INSTALLATION_DIR}/bin/cdpcli --registerhost command\n                trace_log_message -q \"\"\n                trace_log_message \"\\nInvoking an agent registration call...\"\n                mv -f /var/log/cdpcli.log /var/log/cdpcli.log.$RANDOM >/dev/null 2>&1\n\n                while [ $count -le 3 ]; do\n                    trace_log_message -q \"Trying to make an agent registration call - Count: $count \"\n                    trace_log_message -q \"----------------------------------------------------------\"\n                    trace_log_message -q \"Executing the command : ${INSTALLATION_DIR}/bin/cdpcli --registerhost --loglevel=7\"\n                    ${INSTALLATION_DIR}/bin/cdpcli --registerhost --loglevel=7 >> $LOGFILE 2>&1\n                    REGHOST_RETVAL=$?\n                    if [ $REGHOST_RETVAL -ne 0 ]; then\n                        trace_log_message -q \"\"\n                        trace_log_message -q \"Failed $count attempt of agent registration call.\"\n                        count=$(expr $count + 1)\n                        sleep 30 ; continue\n                    fi\n                    break\n                done\n\n                # Appending /var/log/cdpcli.log contents to agent installation log\n                trace_log_message -q \"\"\n                trace_log_message -q \"****** Beginning of  cdpcli --registerhost --loglevel=7 detailed command output **********\"\n                cat /var/log/cdpcli.log >> $LOGFILE 2>&1\n                trace_log_message -q \"\"\n                trace_log_message -q \"****** End of cdpcli --registerhost --loglevel=7 detailed command output ********\"\n\n                if [ $REGHOST_RETVAL -ne 0 ]; then\n                    trace_log_message\n                    trace_log_message \"Agent registration has failed.\"\n                    trace_log_message -q \"Writing AGENT_CONFIGURATION_STATUS=Failed in $VX_VERSION_FILE\"\n                    echo \"AGENT_CONFIGURATION_STATUS=Failed\" >> \"$VX_VERSION_FILE\"\n\n                    trace_log_message -q \"Replacing Hostname value to null in $DRSCOUT_CONF\"\n                    sed -i -e \"s|^Hostname.*|Hostname = |g\" $DRSCOUT_CONF\n\n                    trace_log_message -q \"Removing ExternalIpAddress value from $DRSCOUT_CONF\"\n                    sed -i -e \"/^ExternalIpAddress/d\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n                    RecordOP $REGHOST_RETVAL \"Agent registration failed\"\n\n                    return 17\n                fi\n\n                trace_log_message \"Agent registration has completed successfully.\"\n                trace_log_message -q \"Writing AGENT_CONFIGURATION_STATUS=Succeeded in $VX_VERSION_FILE\"\n                echo \"AGENT_CONFIGURATION_STATUS=Succeeded\" >> \"$VX_VERSION_FILE\"\n\n                cp $DRSCOUT_CONF ${INSTALLATION_DIR}/drscout.conf.initialbackup\n                RecordOP 0 \"\"\n            else\n                rcm_agent_registration\n                regexitcode=$?\n                if [ $regexitcode -eq 119 ]; then\n                    regexitcode=$FailedWithErrors\n                    log_to_json_file ASRMobilityServiceConfiguratorInternalError \"AzureRcmCli failing with unknown error.\"\n                fi\n                if [ $regexitcode -ne 0 ]; then\n                    return $regexitcode\n                fi\n\n                get_non_cached_settings\n                return $?\n            fi\n            ;;\n    esac\n    return 0\n }\n\nrcm_register_machine()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local exitcode=1\n    local count=0\n\n    # Perform AzureRcmCli registermachine operation\n    while [ $count -le 2 ]; do\n        trace_log_message -q \"AzureRcmCli registermachine operation - iteration:$count\"\n        local params=(\"--registermachine\")\n        rcm_exec_with_common_params \"${params[@]}\"\n        exitcode=$?\n        if [ $exitcode -eq 0 ]; then\n            trace_log_message -q \"\"\n            trace_log_message -q \"registermachine operation has succeeded.\"\n            break\n\t\telif [ $exitcode -eq 129 -a \"$VM_PLATFORM\" != \"Azure\" ]; then\n                trace_log_message -q \"Rcm proxy not configured with rcm\".\n\t\t\t\tsed -i -e \"/^CloudPairingStatus/d; /^HostId/ a CloudPairingStatus=Incomplete\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n                break\n        else\n            trace_log_message -q \"\"\n            trace_log_message -q \"registermachine operation has failed with exit code - $exitcode\"\n            if [ $exitcode -eq 126 ]; then\n                break\n            fi\n            count=$(expr $count + 1)\n            sleep 5 ; continue\n        fi\n    done\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $exitcode\n}\n\nrcm_register_sourceagent()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local exitcode=1\n    local count=0\n\n    while [ $count -le 2 ]; do\n        trace_log_message -q \"AzureRcmCli registersourceagent operation - iteration:$count\"\n        local params=(\"--registersourceagent\")\n        rcm_exec_with_common_params \"${params[@]}\"\n        exitcode=$?\n        if [ $exitcode -eq 0 ]; then\n            trace_log_message -q \"\"\n            trace_log_message -q \"registersourceagent operation has succeeded.\"\n            break\n        else\n            trace_log_message -q \"\"\n            trace_log_message -q \"registersourceagent operation has failed with exit code - $exitcode\"\n            if [ $exitcode -eq 126 ]; then\n                break\n            fi\n            count=$(expr $count + 1)\n            sleep 5 ; continue\n        fi\n    done\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $exitcode\n}\n\n#\n# Function Name: rcm_agent_registration\n#\n# Description:\n#    This function used to invoke AzureRcmCli commands to register host with RCM service\n#\n# Parameters:None\n#\n# Return Value: Returns zero when both registermachine and registersourceagent operations succeeds.\n#\n# Exceptions:None\n#\nrcm_agent_registration()\n{\n    local regmachineexitcode=1\n    local regsourceexitcode=1\n    local regexitcode=1\n    local count=0\n\n    SetOP \"RegisterAgent\"\n\n    rcm_register_machine\n    regmachineexitcode=$?\n\n    # Perform AzureRcmCli registersourceagent operation only when registermachine succeeds.\n    if [ $regmachineexitcode -eq 0 ]; then\n        rcm_register_sourceagent\n        regsourceexitcode=$?\n    else\n        trace_log_message -q \"\"\n        trace_log_message -q \"Skipping registersourceagent operation.\"\n    fi\n\n    trace_log_message -q \"\"\n    trace_log_message -q \"****** Beginning of RCMInfo.conf file content **********\"\n    cat $RCMINFO_CONF >> $LOGFILE 2>&1\n    trace_log_message -q \"\"\n    trace_log_message -q \"****** End of RCMInfo.conf file content ********\"\n\n    # Determine overall registation return code based on registermachine and registersourceagent exit codes.\n    # When registermachine operation fails, registersourceagent operation is not performed. Overall exit code is assigned based on this.\n    # Set regexitcode to 0 when both registermachine and registersourceagent succeeds.\n    # Set regexitcode to 119 when regmachineexitcode is not in 120-149 range. Otherwise set regmachineexitcode as regexitcode.\n    # Set regexitcode to 119 when regsourceexitcode is not in 120-149 range. Otherwise set regsourceexitcode as regexitcode.\n\tif [ $regmachineexitcode -eq 129 -a \"$VM_PLATFORM\" != \"Azure\" ]; then\n\t\tregexitcode=0\n        RecordOP 0 \"\"\n    elif [ $regmachineexitcode -eq 2 ] || [ $regsourceexitcode -eq 2 ]; then\n        regexitcode=2\n    elif [ $regmachineexitcode -eq 0 ] && [ $regsourceexitcode -eq 0 ]; then\n        regexitcode=0\n        RecordOP 0 \"\"\n    elif [ $regmachineexitcode -ne 0 ]; then\n        if [ $regmachineexitcode -lt 120 ] || [ $regmachineexitcode -gt 149 ]; then\n            regmachineexitcode=119\n        fi\n        regexitcode=$regmachineexitcode\n        RecordOP $regexitcode \"Register machine operation failed\"\n    elif [ $regsourceexitcode -ne 0 ]; then\n        if [ $regsourceexitcode -lt 120 ] || [ $regsourceexitcode -gt 149 ]; then\n           regsourceexitcode=119\n        fi\n        regexitcode=$regsourceexitcode\n        RecordOP $regexitcode \"Register agent operation failed\"\n    fi\n\n    if [ $regexitcode -ne 0 ]; then\n        trace_log_message\n        trace_log_message \"Agent registration has failed.\"\n        trace_log_message -q \"Writing AGENT_CONFIGURATION_STATUS=Failed in $VX_VERSION_FILE\"\n        echo \"AGENT_CONFIGURATION_STATUS=Failed\" >> \"$VX_VERSION_FILE\"\n\t\tif [ \"$VM_PLATFORM\" != \"Azure\" ]; then\n\t\t\ttrace_log_message -q \"Replacing Hostname value to null in $DRSCOUT_CONF\"\n\t\t\tsed -i -e \"s|^Hostname.*|Hostname = |g\" $DRSCOUT_CONF\n\n\t\t\ttrace_log_message -q \"Removing ExternalIpAddress value from $DRSCOUT_CONF\"\n\t\t\tsed -i -e \"/^ExternalIpAddress/d\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\tfi\n    else\n        trace_log_message \"RCM agent registration has completed successfully.\"\n        trace_log_message -q \"Writing AGENT_CONFIGURATION_STATUS=Succeeded in $VX_VERSION_FILE\"\n        echo \"AGENT_CONFIGURATION_STATUS=Succeeded\" >> \"$VX_VERSION_FILE\"\n        cp $DRSCOUT_CONF ${INSTALLATION_DIR}/drscout.conf.initialbackup\n    fi\n\t\n    trace_log_message -q \"RCM agent registration exit code: $regexitcode\"\n\n    if [ $regexitcode -ge 120 -a $regexitcode -le 149 -a $regexitcode -ne 128 -a $regexitcode -ne 129 -a $regexitcode -ne 148 -a $regexitcode -ne 126 ]; then\n        regexitcode=$FailedWithErrors\n    fi\n    if [ $regexitcode -eq 2 ]; then\n        regexitcode=$FailedWithErrors\n    fi\n    return $regexitcode\n}\n\nget_non_cached_settings()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local ret=0\n\n    local count=0\n    while [ \"$count\" -le \"3\" ]; do\n        trace_log_message -q \"Get non-cached settings\"\n        local params=(\"--getnoncachedsettings\")\n        rcm_exec_with_common_params \"${params[@]}\"\n        ret=$?\n\n        if [ \"$ret\" -eq \"0\" ]; then\n            break;\n        else\n            count=$(expr $count + 1)\n            trace_log_message -q \"Either the Source Config is invalid or unable to establish a connection with RCM Proxy. Retry count : $count\"\n            sleep 30\n        fi\n    done\n\n    if [ \"$count\" -eq \"4\" ]; then\n        trace_log_message \"Unable to establish a connection with RCM Proxy.\"\n    fi\n\n    trace_log_message -q \"Get non-cached settings for csprime return value: $ret\"\n\n    process_azurercmcli_exitcode \"$ret\"\n    ret=$?\n    trace_log_message -q \"Get non-cached settings return value after processing: $ret\"\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret\n}\n\nvalidate_passphrase_for_cs()\n{\n\tlocal return_value=0\n    local errmessage=\"\"\n\tSetOP \"GetCSfingerprint\"\n\t\n\ttrace_log_message \"Validating the passphrase.\"\n        Count=0\n        while [ \"${Count}\" -le \"3\" ]; do\n            # Invoking csgetfingerprint binary with the server ip, server port for https communication.\n            trace_log_message -q \"Invoking csgetfingerprint binary for https communication.\"\n            $INSTALLATION_DIR/bin/csgetfingerprint -i \"$CS_IP_ADDRESS\" -p \"$CS_PORT_NUMBER\" >> $LOGFILE 2>&1\n            return_code=$?\n\n            if [ \"${return_code}\" = \"0\" ]; then\n                if [ -f /usr/local/InMage/private/connection.passphrase ]; then\n                    trace_log_message -q \"Passphrase file is available at /usr/local/InMage/private/connection.passphrase\"\n                    trace_log_message -q \"Passphrase validation is successful.\"\n                    passphrasevalidated=1\n                    errmessage=\"\"\n                    break;\n                else\n                    trace_log_message -q \"Passphrase file is not available at /usr/local/InMage/private/connection.passphrase\"\n                    errmessage=\"Passphrase file not available\"\n                    return_value=14 \n                    break\n                fi\n            else\n                Count=$(expr $Count + 1)\n                if [ \"${Count}\" = \"4\" ]; then\n                    trace_log_message \"Unable to establish a connection with Configuration server.\"\n                    trace_log_message \"Either wrong FQDN/IP/Passphrase has been provided. Aborting the installation.\"\n                    errmessage=\"Unable to connect CS\"\n                    return_value=14 \n                    break\n                fi\n                trace_log_message -q \"Either the FQDN/IP/Passphrase is invalid or unable to establish a connection with Configuration server. Retry count : $Count\"\n                sleep 30\n            fi\n        done\n\t\t\n\ttrace_log_message -q \"Passphrase validation for cs return value: $return_value\"\n    RecordOP $return_value \"$errmessage\"\n    return $return_value\n}\n\nverify_client_auth()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local ret=0\n\n    local count=0\n    while [ \"$count\" -le \"3\" ]; do\n        trace_log_message -q \"Verifying client auth\"\n        local params=(\"--verifyclientauth\" \"--configfile\" \"$SOURCE_CONFIG_FILE\")\n        rcm_exec_with_common_params \"${params[@]}\"\n        ret=$?\n\n        if [ \"$ret\" -eq \"0\" ]; then\n            break;\n        else\n            count=$(expr $count + 1)\n            trace_log_message -q \"Either the Source Config is invalid or unable to establish a connection with RCM Proxy. Retry count : $count\"\n            sleep 30\n        fi\n    done\n\n    if [ \"$count\" -eq \"4\" ]; then\n        trace_log_message \"Unable to establish a connection with RCM Proxy.\"\n    else\n        update_cstype_in_drscout \"CSPrime\"\n    fi\n    trace_log_message -q \"Verify client auth for csprime return value: $ret\"\n\n    process_azurercmcli_exitcode \"$ret\"\n    ret=$?\n    trace_log_message -q \"Verify client auth return value after processing: $ret\"\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $ret\n}\n\nupdate_s2_path()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local csType=\"$CS_TYPE\"\n    local s2path=\"$AGENT_INSTALL_DIR/bin/s2A2A\"\n    if [ \"$csType\" = \"CSLegacy\" -a \"$VM_PLATFORM\" != \"Azure\" ] ; then\n        s2path=\"$AGENT_INSTALL_DIR/bin/s2V2A\"\n    fi\n    trace_log_message -q \"Adding s2 path : $s2path in drscout.conf\"\n    sed -i -e \"s|^DiffSourceExePathname.*|DiffSourceExePathname=$s2path|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n    trace_log_message -q \"EXITED $FUNCNAME\"\n}\n\nupdate_cstype_in_drscout()\n{\n\tlocal csType=\"$1\"\n\tCS_TYPE=$csType\n\tsed -i -e \"/^CSType/d; /^HostId/ a CSType=$csType\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\t\n\tdppath=\"$AGENT_INSTALL_DIR/bin/dataprotection\"\n\tif [ \"$csType\" = \"CSPrime\" ] ; then\n\t\tdppath=\"$AGENT_INSTALL_DIR/bin/DataProtectionSyncRcm\"\n\tfi\n\ttrace_log_message -q \"Adding dp path in drscout.conf\"\n\tsed -i -e \"s|^OffloadSyncPathname.*|OffloadSyncPathname=$dppath|g; s|^FastSyncExePathname.*|FastSyncExePathname=$dppath|g; s|^DataProtectionExePathname.*|DataProtectionExePathname=$dppath|g; s|^DiffTargetExePathname.*|DiffTargetExePathname=$dppath|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n}\n\n# \n# Function Name: get_cs_fingerprint\n# \n# Description:\n#    This function used to get fingerprint from Configuration Server.\n# \n# Parameters:$agent\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nget_cs_fingerprint()\n{\n    local return_value=0\n    local errmessage=\"\"\n\n    SetOP \"Passphrase validation\"\n    \n    if [ -n \"$PASSPHRASE_FILE\"  ]; then\n        # Creating connection.passphrase file under /usr/local/InMage/private and writing passphrase to it.\n        cp -f $PASSPHRASE_FILE \"/usr/local/InMage/private/connection.passphrase\"\n        chmod 700 \"/usr/local/InMage/private/connection.passphrase\"\n\t\t\n\t\techo \"Value of cstype in csgetfingerprint is $CS_TYPE\"\n        # For Silent installation, invoking csgetfingerprint binary.\n        validate_passphrase_for_cs\n        return_value=$?\n        update_cstype_in_drscout \"CSLegacy\"\n    else\n        # Loop until correct passphrase is entered to communicate with cs.\n        while true\n        do\n            # Writing cs connection passphrase to the connection.passphrase file\n            echo \"$CS_PASSPHRASE\" > /usr/local/InMage/private/connection.passphrase\n            chmod 700 /usr/local/InMage/private/connection.passphrase\n\n            validate_passphrase_for_cs\n            return_code=$?\n            update_cstype_in_drscout \"CSLegacy\"\n\t\t\t\n\t\t\tif [ \"${return_code}\" = \"0\" ]; then\n\t\t\t\ttrace_log_message -q \"Passphrase file is available at /usr/local/InMage/private/connection.passphrase\"\n                trace_log_message -q \"Passphrase validation is successful.\"\n                passphrasevalidated=1\n                errmessage=\"\"\n                break;\n            else\n                trace_log_message \"Wrong Passphrase has been entered.\"\n                errmessage=\"Wrong Passphrase\"\n                get_cs_passphrase\n                rm -f /usr/local/InMage/private/connection.passphrase\n            fi\n        done\n    fi\n    \n    if [ \"${AGENT_ROLE}\" = \"MasterTarget\" -o \"$CS_TYPE\" = \"CSLegacy\" ]; then\n        sed -i -e \"/^RcmSettingsPath/d\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n    fi\n\t\n    trace_log_message -q \"Get CS fingerprint return value: $return_value\"\n    RecordOP $return_value \"$errmessage\"\n    return $return_value\n}\n\n# \n# Function Name: is_agent_installed\n# \n# Description:\n#    This function used to check whether Vx agent is already installed or not\n# \n# Parameters:$agent\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nis_agent_installed() {\n    local agent=\"$1\"\n    local return_value=0\n    \n    case \"$agent\" in\n        Vx)\n            if [ -e $VX_VERSION_FILE ]; then\n                trace_log_message -q \"Vx agent is already installed.\"\n                source $VX_VERSION_FILE\n                OS=$OS_BUILT_FOR\n                DRSCOUT_CONF=\"$INSTALLATION_DIR/etc/drscout.conf\"\n                vx_version=$(grep -w VERSION $VX_VERSION_FILE | cut -d'=' -f2)\n                CURRENT_VERSION=$vx_version\n                VM_PLATFORM=$(grep ^VmPlatform $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n                RCMINFO_CONF=\"/usr/local/InMage/config/RCMInfo.conf\"\n                AGENT_CSIP=$(grep ^Hostname $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n                AGENT_CSPORT=$(grep ^Port $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n                AGENT_ROLE=$(grep ^Role $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n                CURRENT_BLDNUMBER=$(grep -w BUILD_TAG $VX_VERSION_FILE | cut -d'_' -f5)\n                tele_current_version=$(awk -F. -v OFS=. '/^VERSION=/{$3 = \"BLDNO\"}{ print }' $VX_VERSION_FILE | grep -w \"^VERSION\" | sed -e \"s/BLDNO/$CURRENT_BLDNUMBER/g;\"|cut -d= -f2)\n                tele_existing_version=$tele_current_version\n            else\n                trace_log_message -q \"Vx agent is not installed.\"\n                return_value=1\n            fi\n        ;;\n    esac\n    trace_log_message -q \"Is agent installed return value: $return_value\"\n    return $return_value    \n}\n\n# \n# Function Name: is_valid_creds_file\n# \n# Description:\n#    This function used to check whether RCM credential file is valid or not\n# \n# Parameters:$agent\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n#\nis_valid_creds_file() {\n\n    local rcmcreds_file=\"$1\"\n    local return_value=0\n    \n    if [ ! -e \"$rcmcreds_file\" ] || \\\n        grep -q \"false\" <<< $(cat $rcmcreds_file | $INSTALLATION_DIR/bin/jq -e 'has(\"rcmUri\", \"aadDetails\", \"managementId\")')\n    then\n        trace_log_message \"$rcmcreds_file file does not exists or invalid credential file\"\n        return_value=1\n    fi\n\n    trace_log_message -q \"RCM Creds file validation return value: $return_value\"\n    return $return_value\n}\n\n# \n# Function Name: is_valid_ipv4\n# \n# Description:\n#    This function used to validate given cs ip address\n# \n# Parameters:$ip\n# \n# Return Value: On successful it returns zero, else returns non-zero\n# \n# Exceptions:None\n# \nis_valid_ipv4()\n{\n    local ip=$1\n    local return_value=0\n    if [[ $ip =~ ^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$ ]]; then\n        OIFS=$IFS\n        IFS='.'\n        ip=($ip)\n        IFS=$OIFS\n        if [[ ${ip[0]} -le 255 && ${ip[1]} -le 255 && ${ip[2]} -le 255 && ${ip[3]} -le 255 ]]; then\n            trace_log_message -q \"Valid ip address.\"            \n        else\n            trace_log_message \"Invalid ip address. Please retry.\"\n            return_value=3\n        fi\n    else\n        trace_log_message \"Invalid ip address. Please retry.\"\n        return_value=3\n    fi\n    trace_log_message -q \"IP validation return value: $return_value\"\n    return $return_value\n}\n\n# \n# Function Name: get_cs_passphrase\n# \n# Description:\n#    This function used to get Configuration Server passphrase from user\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero\n# \n# Exceptions:None\n# \nget_cs_passphrase() {\n    CS_PASSPHRASE=\"\"\n    SetOP \"GetCSpassphrase\"\n    while [ \"X$CS_PASSPHRASE\" = \"X\" ]\n    do\n            echo -en \"\\nProvide Configuration Server passphrase ? : \"\n            stty -echo\n            read CS_PASSPHRASE\n            stty echo\n            [ -z \"$CS_PASSPHRASE\" ] && echo -e \"\\nInvalid input. Please try again.\"\n        done\n    echo\n    RecordOP 0 \"\"\n    return 0\n}\n\n# Function Name: get_cs_ipaddress\n# \n# Description:\n#    This function used to get Configuration Server IP address from user\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero\n# \n# Exceptions:None\n# \nget_cs_ipaddress() {\n    SetOP \"GetCSipAddr\"\n    while true; do\n        echo -en \"\\nProvide Configuration Server IP address ? : \"\n        read CS_IP_ADDRESS\n        \n        if [ -n \"$CS_IP_ADDRESS\" ]; then\n            break;\n        fi\n        continue\n    done\n    RecordOP 0 \"\"\n    return 0\n}\n\n# Function Name: get_cs_port\n# \n# Description:\n#    This function used to get Configuration Server port from user\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero\n# \n# Exceptions:None\n# \nget_cs_port() {\n\tSetOP \"GetCSPort\"\n\techo -en \"\\nPlease provide CS port number. Default port number is 443. \"\n\tread CS_PORT\n\t\n\tif [ -z \"$CS_PORT\" ]; then\n\t\tCS_PORT=\"443\"\n\tfi\n\t\n\tRecordOP 0 \"\"\n    return 0\n}\n\n#\n# Function Name: get_rcm_creds\n# \n# Description:\n#    This function used to take RCM credential file path from user and do the validation\n# \n# Parameters:None\n# \n# Return Value: On successful it returns zero\n# \n# Exceptions:None\n# \nget_rcm_creds() {\n    RCM_CREDS_FILE=\"\"\n    SetOP \"GetRCMcreds\"\n    while [ \"X$RCM_CREDS_FILE\" = \"X\" ]\n    do\n        echo -en \"\\nProvide RCM Credentials file path ? : \"\n        read RCM_CREDS_FILE\n        if [ -z \"$RCM_CREDS_FILE\" ]; then\n            echo -e \"\\nInvalid input. Please try again.\"\n        elif is_valid_creds_file \"$RCM_CREDS_FILE\" ; then\n            break;\n        else\n            echo -e \"\\nInvalid credential file. Please try again.\"\n            continue\n        fi        \n    done\n    RecordOP 0 \"\"\n    return 0\n}\n\nget_source_config_file() {\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    SetOP \"GetSourceConfigFile\"\n    while :\n    do\n        echo -en \"\\nProvide Source Config File Path : \"\n        read SOURCE_CONFIG_FILE\n        if [ -f \"$SOURCE_CONFIG_FILE\" ]; then\n            break\n        fi\n    done\n    echo\n    RecordOP 0 \"\"\n    trace_log_message -q \"EXITED $FUNCNAME\"\n}\n\nget_discovery_flag() {\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n\n    while true; do\n        echo -en \"\\nSelect if credential-less discovery should be performed for this machine ? [Options: true|false, Default: false ]\"\n        read IS_CREDENTIAL_LESS_DISCOVERY\n        [ -z \"$IS_CREDENTIAL_LESS_DISCOVERY\" ] && IS_CREDENTIAL_LESS_DISCOVERY=\"false\"\n        if [ \"$IS_CREDENTIAL_LESS_DISCOVERY\" = \"true\" -o \"$IS_CREDENTIAL_LESS_DISCOVERY\" = \"false\" ]; then\n            break;\n        else\n            trace_log_message \"Invalid input. Please try again.\"\n        fi\n    done\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n}\n\nlog_to_json_file() {\n    log_to_json_errors_file $json_errors_file \"$@\"\n}\n\nIsAzureVirtualMachine()\n{\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    trace_log_message -q \"Detecting VM Platform.\"\n    local tag=$(cat /sys/devices/virtual/dmi/id/chassis_asset_tag 2>/dev/null)\n    if [ -z \"$tag\" ]; then\n        tag=`dmidecode -t chassis 2>/dev/null | grep \"Asset Tag\" | cut -f2 -d\":\" | tr -d \" \"`\n    fi\n    trace_log_message -q \"dmi chassis asset tag = $tag\"\n    local return_value=1    #VmWare\n    if [ \"$tag\" = \"7783-7084-3265-9085-8269-3286-77\" ] && [ ! is_azure_stack_platform ] ; then\n        return_value=0   #Azure\n    fi\n    trace_log_message -q \"return value: $return_value\"\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $return_value\n}\n\n\nIsFailedOverVm() {\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local return_value=1\n    local platform=`grep ^VmPlatform $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \"`\n    local cs_type=`grep ^CSType $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \"`\n\n    IsAzureVirtualMachine\n    local is_azure_vm=$?\n    if [ \"$platform\" = \"VmWare\" -a \"$cs_type\" = \"CSPrime\" -a $is_azure_vm -eq 0 ]; then\n        return_value=0\n    fi\n    trace_log_message -q \"return value : $return_value\"\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    return $return_value\n}\n\nunconfigure_rcmproxy() {\n    trace_log_message -q \"ENTERED $FUNCNAME\"\n    local ret=0\n\n    if [ \"$CS_TYPE\" = \"CSPrime\" -a \"$UNCONFIGURE\" = \"true\" ]; then\n        stop_agent_service || exit_with_retcode $?\n        unregister_agent\n        rm -f ${AGENT_INSTALL_DIR}/etc/SourceConfig.json ${AGENT_INSTALL_DIR}/etc/SourceConfig.json.lck >> $LOGFILE 2>&1\n\n        #Remove HostId and ResourceId\n        update_config_general \"$DRSCOUT_CONF\" \"HostId\" \"\"\n        update_config_general \"$DRSCOUT_CONF\" \"ResouceId\" \"\"\n        ret=$?\n    fi\n\n    trace_log_message -q \"EXITED $FUNCNAME\"\n    exit_with_retcode $ret\n}\n\n#\n# Function Name: usage\n#\n# Description:\n#    This function will provide script usage.\n#\n# Parameters:None\n#\n# Return Value: It returns zero,\n#\n# Exceptions:None\n#\nusage() {\n    trace_log_message \"Usage:  UnifiedAgentConfigurator.sh [options]\"\n    trace_log_message \"Options:\"\n    trace_log_message \"  -i <Configuration Server IP Address>\"\n    trace_log_message \"  -e <External IP>\"\n    trace_log_message \"  -l <Log file name (absolute path)>\"\n    trace_log_message \"  -P <Passphrase file name(absolute path)>\"\n    trace_log_message \"  -S <Source config file name(absolute path)>\"\n    trace_log_message \"  -C <RCM credential file path(absolute path)>\"\n    trace_log_message \"  -D <Credential Less Discovery(true/false)>\"\n    trace_log_message \"  -U <Unconfigure appliance>\"\n    trace_log_message \"  -c <CSType (CSLegacy/CSPrime)>\"\n    trace_log_message \"  -h <help> \"\n    exit 0\n}\n\nmain() \n{\n    local return_value=0\n    SetOP \"GetCmdArgs\"\n\n    if [ $# -ge 1 ] && $(echo $1 | grep -q ^- ); then\n        while getopts :i:e:l:C:P:S:D:U:m:j:c:p:r:f:qh opt\n        do\n            case $opt in\n                i) CS_IP_ADDRESS=\"$OPTARG\" ;;\n                e) EXTERNAL_IP=\"$OPTARG\" ;;\n                l) CUSTOM_LOGFILE=\"$OPTARG\" ;;\n                P) PASSPHRASE_FILE=\"$OPTARG\" ;;\n                S) SOURCE_CONFIG_FILE=\"$OPTARG\" ;;\n                C) RCM_CREDS_FILE=\"$OPTARG\" ;;\n                D) IS_CREDENTIAL_LESS_DISCOVERY=\"$OPTARG\" ;;\n                U) UNCONFIGURE=\"$OPTARG\" ;;\n                m) INVOKER=\"$OPTARG\" ;;\n                j) json_file=\"$OPTARG\" ;;\n                c) CS_TYPE=\"$OPTARG\"\n                    if [ \"$CS_TYPE\" != \"CSLegacy\" -a \"$CS_TYPE\" != \"CSPrime\" ]; then\n                        usage && exit 96\n                    fi ;;\n                p) CS_PORT=\"$OPTARG\" ;;\n                r) CLIENT_REQUEST_ID=\"$OPTARG\" ;;\n                f) CONFIGURE_ERRORS_JSON=\"$OPTARG\" ;;\n                q) SILENT_ACTION=\"true\" ;;\n                h|-*|*)\n                    trace_log_message -q \"Specify the CS registration options to the command-line!\"\n                    usage && exit 96\n                ;;\n            esac\n        done\n\n        if [ ! -z \"$CUSTOM_LOGFILE\" ] && [ \"$LOGFILE\" != \"$CUSTOM_LOGFILE\" ]; then\n            LOGFILE=$CUSTOM_LOGFILE\n            VERBOSE_LOGFILE=$CUSTOM_LOGFILE\n        fi\n    fi\n\n    if [ -z \"$CS_TYPE\" ]; then\n        CS_TYPE=\"CSLegacy\"\n    fi\n\n    echo \"Value of cstype is $CS_TYPE\"\n\n    if [ \"$CS_TYPE\" = \"CSLegacy\" ]; then\n        if [ -n \"$RCM_CREDS_FILE\" ] ; then\n            SILENT_ACTION=\"true\"\n        elif [ -z \"$CS_IP_ADDRESS\" -o -z \"$PASSPHRASE_FILE\" ]; then\n            SILENT_ACTION=\"false\"\n        else\n            SILENT_ACTION=\"true\"\n        fi\n    fi\n\n    trace_log_message -q\n    trace_log_message -q \"AGENT CONFIGURATION\"\n    trace_log_message -q \"*******************\"\n\n\n    if [ -z \"$CONFIGURE_ERRORS_JSON\" ]; then\n        CONFIGURE_ERRORS_JSON=$DEFAULT_CONFIGURE_ERRORS_JSON\n    fi\n\n    json_errors_file=${CONFIGURE_ERRORS_JSON}\n    if [ -f $AGENT_INSTALL_DIR/bin/libcommon.sh ]; then\n        . $AGENT_INSTALL_DIR/bin/libcommon.sh\n    else\n        trace_log_message \"File not found : libcommon.sh\"\n        exit_with_retcode 1\n    fi\n\n    IsFailedOverVm\n    if [ $? -eq 0 ]; then\n        trace_log_message \"This is a failed over vm in CSPrime stack. Configuration operation is a no op here\"\n        exit_with_retcode $Success\n    fi\n    StartSummary\n    RecordOP 0 \"\"\n\n    SetOP \"GetAgentStatus\"\n    if is_agent_installed \"Vx\" ; then\n        if [ ! -z \"$UNCONFIGURE\" ]; then\n            unconfigure_rcmproxy\n        fi\n        if [ \"$SILENT_ACTION\" = \"true\" ]; then\n            trace_log_message -q \"Silent agent configuration.\"\n            if [ \"$VM_PLATFORM\" = \"Azure\" ] ; then\n                SetOP \"ValidateCredsFile\"\n                is_valid_creds_file \"$RCM_CREDS_FILE\"\n                return_value=$?\n                if [ $return_value -ne 0 ]; then\n                    RecordOP $return_value \"Invalid credential file $RCM_CREDS_FILE\"\n                    exit_with_retcode $return_value \n                fi\n                RecordOP 0 \"\"\n            elif [ \"$VM_PLATFORM\" = \"VmWare\" ]; then\n                SetOP \"ValidateExternalIPaddr\"\n                trace_log_message -q \"EXTERNAL_IP=$EXTERNAL_IP\"\n                if [ -n \"$EXTERNAL_IP\" ]; then\n                    trace_log_message -q \"Performing External IP validation.\"\n                    is_valid_ipv4 \"$EXTERNAL_IP\"\n                    return_value=$?\n                    if [ $return_value -ne 0 ]; then\n                        RecordOP $return_value \"Invalid external IP address $EXTERNAL_IP\"\n                        exit_with_retcode $return_value \n                    fi\n                    RecordOP 0 \"\"\n                fi\n\n                if [ \"$CS_TYPE\" = \"CSLegacy\" ]; then\n                    SetOP \"VerifyPassphraseFile\"\n                    if [ ! -f \"$PASSPHRASE_FILE\" ]; then\n                        trace_log_message \"Passphrase file passed to the installer does not exist.\"\n                        RecordOP 1 \"Passphrase file $PASSPHRASE_FILE doesn't exists\"\n                        exit_with_retcode 1\n                    fi\n                    RecordOP 0 \"\"\n                fi\n            else\n                trace_log_message \"Invalid entry of VM_PLATFORM : \\\"$VM_PLATFORM\\\"\"\n                log_to_json_file ASRMobilityServiceVMPlatformNotSet \"Unable to read the configuration of the source machine.\"\n                exit_with_retcode $FailedWithErrors\n            fi\n        else\n            trace_log_message -q \"Interactive agent configuration.\"\n            if [ \"$VM_PLATFORM\" = \"Azure\" ]; then\n                get_rcm_creds\n            elif [ \"$VM_PLATFORM\" = \"VmWare\" ]; then\n                if [ \"$CS_TYPE\" = \"CSPrime\" ]; then\n                    get_source_config_file\n                    get_discovery_flag\n                else\n                    get_cs_ipaddress\n                    get_cs_passphrase\n                fi\n            else\n                trace_log_message \"Invalid entry of VM_PLATFORM : \\\"$VM_PLATFORM\\\"\"\n                log_to_json_file ASRMobilityServiceVMPlatformNotSet \"Unable to read the configuration of the source machine.\"\n                exit_with_retcode $FailedWithErrors\n            fi\n        fi\n\n        # Adding 443 as the default Configuration server port if no port is given\n        if [ -z \"$CS_PORT\" ]; then\n            CS_PORT_NUMBER=443\n        else\n            CS_PORT_NUMBER=\"$CS_PORT\"\n        fi\n\n        # Fetch VM Platform information from drscout.conf\n        SetOP \"GetVMplatform\"\n        VM_PLATFORM=$(grep ^VmPlatform $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n        trace_log_message \"Platform value in drscout.conf: ${VM_PLATFORM}\"\n        if [ -z \"${VM_PLATFORM}\" ] || [ \"$VM_PLATFORM\" != \"VmWare\" -a \"$VM_PLATFORM\" != \"Azure\" ]; then\n            trace_log_message \"Aborting configuration as VM_PLATFORM value is either null or it is not VmWare/Azure.\"\n            RecordOP 1 \"Invalid VM_PLATFORM value ${VM_PLATFORM}\"\n            exit_with_retcode 1\n        fi\n\n        # Verify whether agent is already registered to configuration server.\n        SetOP \"IsAlreadyRegistered\"\n        PLATFORM_CHANGE_TO_CSPRIME=$(grep ^PlatformChangeToCSPrime $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n        if [ \"$VM_PLATFORM\" = \"VmWare\" ] ; then\n            if [ ! -z \"$AGENT_CSIP\" ] && [ ! -z \"$AGENT_CSPORT\" ]; then\n                if [ \"$AGENT_CSIP\" = \"$CS_IP_ADDRESS\" ] && [ \"$AGENT_CSPORT\" = \"$CS_PORT_NUMBER\" ]; then\n                    trace_log_message -q \"Agent is already registerd to same Configuration server ($AGENT_CSIP:$AGENT_CSPORT).\"\n                elif [ -n \"$PLATFORM_CHANGE_TO_CSPRIME\" ] && [ \"$PLATFORM_CHANGE_TO_CSPRIME\" = \"true\" ]; then\n                    trace_log_message \"Allowing upgrade from CS to CSPRIME.\"\n                else\n                    trace_log_message \"Agent is already registerd to different Configuration server ($AGENT_CSIP:$AGENT_CSPORT).\"\n                    trace_log_message \"return value: 13\"\n                    RecordOP 13 \"Agent already registerd to different Configuration server $AGENT_CSIP:$AGENT_CSPORT\"\n                    exit_with_retcode 13\n                fi\n            fi\n            RecordOP 0 \"\"\n        fi\n\n        # Remove AGENT_CONFIGURATION_STATUS entry from .vx_version\n        sed -i -e '/^AGENT_CONFIGURATION_STATUS/d' $VX_VERSION_FILE\n\n        # Stop the services.\n        stop_agent_service || exit_with_retcode $?\n\n        if [ \"$CS_TYPE\" = \"CSPrime\" ]; then\n            if [ ! -f \"$SOURCE_CONFIG_FILE\" ]; then\n                trace_log_message \"Unable to find Source config file : \"\n                # TODO Add specific error name\n                exit_with_retcode 1\n            fi\n\n            update_discovery || exit_with_retcode $?\n        fi\n\n        set_scenario \"Configuration\"\n\t\t\n\t\tif [ ! -d $RCMCONFIG_FOLDER ]; then\n\t        trace_log_message -q \"Creating $RCMCONFIG_FOLDER\"\n\t        mkdir -p $RCMCONFIG_FOLDER >> $LOGFILE 2>&1\n\t    fi\n\n\t    if [ ! -f $RCMCONFIG_FOLDER/RCMInfo.conf ]; then\n\t\ttrace_log_message -q \"Copying ${AGENT_INSTALL_DIR}/etc/RCMInfo.conf to $RCMCONFIG_FOLDER\"\n\t\tcp ${AGENT_INSTALL_DIR}/etc/RCMInfo.conf $RCMCONFIG_FOLDER >> $LOGFILE 2>&1\n\t    fi\n\n        if [ \"$VM_PLATFORM\" = \"Azure\" ]; then\n            generate_host_id \"false\"\n\n\t\t\t# Set LogLevel to 7 before performing AzureRcmCli operations.\n\t\t\ttrace_log_message -q \"Setting LogLevel to 7 before performing AzureRcmCli operations.\"\n    \t\tsed -i -e \"s|^LogLevel.*|LogLevel = 7|g\" $DRSCOUT_CONF\n    \t\tmv -f /var/log/AzureRcmCli.log /var/log/AzureRcmCli.log.`date '+%Y_%m_%d_%H_%M_%S'` >/dev/null 2>&1\n\n            parse_update_rcm_creds \"$RCM_CREDS_FILE\" || exit $?\n            rcm_agent_registration \"Vx\" || exit $?\n\n\t\t\t# Set LogLevel to 3 after performing AzureRcmCli operations.\n\t\t\ttrace_log_message -q \"Setting LogLevel to 3 after performing AzureRcmCli operations.\"\n    \t\tsed -i -e \"s|^LogLevel.*|LogLevel = 3|g\" $DRSCOUT_CONF\n        else\n\t\t\tupdate_drscout_config || exit_with_retcode $?\n            if [ \"$CS_TYPE\" = \"CSPrime\" ]; then\n                verify_client_auth || exit_with_retcode $?\n            else\n                get_cs_fingerprint || exit_with_retcode $?\n            fi\n\t\t\tupdate_drscout_config_for_cs || exit_with_retcode $?\n            cs_agent_registration \"Vx\" || check_return_code $?\n\t\t\tcreate_soft_links || exit_with_retcode $?\n        fi\n        update_s2_path\n        set_scenario \"PostConfiguration\"\n\n        start_agent_service || exit_with_retcode $?\n        set_permissions || exit_with_retcode $?\n\t\tsed -i -e \"s|^PlatformChangeToCSPrime=.*|PlatformChangeToCSPrime=false|g\" $DRSCOUT_CONF >> $LOGFILE 2>&1\n\ttrace_log_message \"Agent configuration is completed successfully.\"\n\tCLOUD_PAIRING_STATUS=$(grep ^CloudPairingStatus $DRSCOUT_CONF | cut -d\"=\" -f2 | tr -d \" \")\n\tif [ -n \"$CLOUD_PAIRING_STATUS\" -a \"$CLOUD_PAIRING_STATUS\" = \"Incomplete\" ]; then\n\t\techo \"Please register your cs appliance with RCM service for the agent registration to complete.\"\n\t\t# To do\n\t\t# Check if we want to exit with a specific error code for manual install when Rcm proxy is not registered with Rcm during agent registration\n\t\t#if [ \"$SILENT_ACTION\" != \"true\" ]; then\n\t\t#\texit_with_retcode \"NEW ERROR CODE\"\n\t\t#fi\n\tfi\n    else\n        echo \"Vx agent is not installed.\"\n        RecordOP 1 \"Vxagent not installed\"\n        return 1\n    fi\n    return 0\n}\n\ntrap \"trace_log_message 'Program terminated at user request'; EndSummaryOP \"Aborted\"; exit 1\" 1 2 3 6 9 15 30\n\nset_scenario \"PreConfiguration\"\n\n# Read conf values from vx_version file (needed upfront for telemetry)\nis_agent_installed \"Vx\"\n\ntrace_log_message -q\ntrace_log_message -q \"Script initiated with the following command:\"\ntrace_log_message -q \"${SCRIPT} $@\"\ntrace_log_message -q\n\nmain \"$@\"\n\nexit_with_retcode $?\n", "num_lines": 1925}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nrm -rf ./drivers/InVolFlt/sun\nrm -rf ./drivers/lib/sun\ncd ./drivers/InVolFlt; ln -sf solaris sun; cd ../..\ncd ./drivers/lib; ln -sf solaris sun; cd ../..\n", "num_lines": 7}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nDIR=\"$1\"\n\nshift 1\n\ncase \"$DIR\" in \n    \"\" | \".\")\n\t\t  g++ -MM -MG \"$@\" | sed -e 's@^\\(.*\\)\\.o:@\\1.d \\1.o:@'\n\t\t  ;;\n\t *)\n\t\t  g++ -MM -MG \"$@\" | sed -e \"s@^\\(.*\\)\\.o:@$DIR/\\1.d $DIR/\\1.o:@\"\n\t\t  ;;\nesac\n\n", "num_lines": 16}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nCOMPANY=${1:-InMage}\nX_VERSION_DOTTED=${2:-9.00.1}\nX_VERSION_PHASE=${3:-DIT}\nX_CONFIGURATION=${4:-release}\n\n. ../build/scripts/general/OS_details.sh\n\nX_OS=$OS\n\ntar -cvzf ${COMPANY}_UA_${X_VERSION_DOTTED}_${X_OS}_${X_VERSION_PHASE}_`date \"+%d%h%Y\"`_${X_CONFIGURATION}_symbols.tar.gz `find . -name *.dbg -o -name *.dbg.gz`\n", "num_lines": 13}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\necho \"Building thirdparty links to shared libraries and binaries\"\n. ../build/scripts/general/OS_details.sh\n\nTOP_DIR=`dirname $PWD`\nOS_BIN_DIR=\"${TOP_DIR}/thirdparty/bin/bin\"\nX_ARCH=`uname -ms | sed -e s\"/ /_/g\"`\n\nif [ ! -h \"$OS_BIN_DIR\" ]; then\n\tmkdir -p `dirname \"$OS_BIN_DIR\"`\n\tln -s \"$TOP_DIR/thirdparty/bin/`uname | tr A-Z a-z`/$OS\" \"$OS_BIN_DIR\"\nfi\nif [ ! -f \"$X_ARCH/branding/platform-$OS\" ]; then\n\tmkdir -p \"$X_ARCH/branding\"\n\trm -f \"$X_ARCH\"/branding/platform-*\n\ttouch \"$X_ARCH/branding/platform-$OS\"\nfi\n\n", "num_lines": 20}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##+----------------------------------------------------------------------------------+\n##            Copyright(c) Microsoft Corp. 2015\n##+----------------------------------------------------------------------------------+\n## File         :   fix_dhcp.sh\n##\n## Description  :   \n##\n## History      :   10-12-2018 (Venu Sivanadham) - Created\n##\n## Usage        :   fix_dhcp.sh\n##+----------------------------------------------------------------------------------+\n\n###Start: Constants\n_FIX_DHCP_SCRIPT_=\"fix_dhcp.sh\"\n_AM_STARTUP_=\"azure-migrate-startup\"\n_STARTUP_SCRIPT_=\"${_AM_STARTUP_}.sh\"\n_AM_SCRIPT_DIR_=\"/usr/local/azure-migrate\"\n_AM_SCRIPT_LOG_FILE_=\"/var/log/${_AM_STARTUP_}.log\"\n_AZURE_ASSET_TAG_=\"7783-7084-3265-9085-8269-3286-77\"\n###End: Constants\n\n\nunset _DISTRO_\nfind_distro()\n{\nif [ -f /etc/oracle-release ] && [ -f /etc/redhat-release ] ; then\n    if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release ; then\n        _DISTRO_=\"OL6\"\n    elif grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release ; then\n        _DISTRO_=\"OL7\"\n    elif grep -q 'Oracle Linux Server release 8.*' /etc/oracle-release ; then\n        _DISTRO_=\"OL8\"\n    elif grep -q 'Oracle Linux Server release 9.*' /etc/oracle-release ; then\n        _DISTRO_=\"OL9\"\n    fi\nelif [ -f /etc/redhat-release ]; then\n    if grep -q 'Red Hat Enterprise Linux Server release 6.*' /etc/redhat-release || \\\n       grep -q 'Red Hat Enterprise Linux Workstation release 6.*' /etc/redhat-release; then\n            _DISTRO_=\"RHEL6\"\n    elif grep -q 'Red Hat Enterprise Linux Server release 7.*' /etc/redhat-release || \\\n         grep -q 'Red Hat Enterprise Linux Workstation release 7.*' /etc/redhat-release; then\n            _DISTRO_=\"RHEL7\"\n    elif grep -q 'Red Hat Enterprise Linux release 8.*' $mntpath/etc/redhat-release; then\n            _DISTRO_=\"RHEL8\"\n    elif grep -q 'Red Hat Enterprise Linux release 9.*' $mntpath/etc/redhat-release; then\n            _DISTRO_=\"RHEL9\"\n    elif grep -q 'CentOS Linux release 6.*' /etc/redhat-release || \\\n         grep -q 'CentOS release 6.*' /etc/redhat-release; then\n            _DISTRO_=\"CENTOS6\"\n    elif grep -q 'CentOS Linux release 7.*' /etc/redhat-release; then\n            _DISTRO_=\"CENTOS7\"\n    elif grep -q 'CentOS Linux release 8.*' /etc/redhat-release ||\n         grep -q 'CentOS Stream release 8.*' /etc/redhat-release; then\n            _DISTRO_=\"CENTOS8\"\n    elif grep -q 'CentOS Linux release 9.*' /etc/redhat-release ||\n         grep -q 'CentOS Stream release 9.*' /etc/redhat-release; then\n            _DISTRO_=\"CENTOS9\"\n    fi\nelif ( [ -f /etc/SuSE-release ] && ( grep -q 'VERSION = 11' /etc/SuSE-release ||  grep -q 'VERSION = 12' /etc/SuSE-release )); then\n    if grep -q 'VERSION = 11' /etc/SuSE-release; then\n        _DISTRO_=\"SLES11\"\n    fi\n    if grep -q 'VERSION = 12' /etc/SuSE-release; then\n        _DISTRO_=\"SLES12\"\n    fi\nelif [ -f /etc/os-release ] && grep -q 'SLES' /etc/os-release; then\n    if grep -q 'VERSION=\"12' /etc/os-release; then\n        _DISTRO_=\"SLES12\"\n    elif grep -q 'VERSION=\"15' /etc/os-release; then\n        _DISTRO_=\"SLES15\"\n    fi\nelif [ -f /etc/lsb-release ]; then\n    if grep -q 'Ubuntu 14.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU14\"\n    elif grep -q 'Ubuntu 16.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU16\"\n    elif grep -q 'Ubuntu 18.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU18\"\n    elif grep -q 'Ubuntu 19.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU19\"\n    elif grep -q 'Ubuntu 20.*' /etc/lsb-release ; then\n        DISTRO_=\"UBUNTU20\"\n    elif grep -q 'Ubuntu 21.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU21\"\n    elif grep -q 'Ubuntu 22.*' /etc/lsb-release ; then\n        _DISTRO_=\"UBUNTU22\"\n    fi\nelif [ -f /etc/debian_version ]; then\n    if grep -q '^7.*' /etc/debian_version; then\n        _DISTRO_=\"DEBIAN7\"\n    elif grep -q '^8.*' /etc/debian_version; then\n        _DISTRO_=\"DEBIAN8\"\n    elif grep -q '^9.*' /etc/debian_version; then\n        _DISTRO_=\"DEBIAN9\"\n    elif grep -q '^10.*' /etc/debian_version; then\n        _DISTRO_=\"DEBIAN10\"\n    elif grep -q '^11.*' /etc/debian_version; then\n        _DISTRO_=\"DEBIAN11\"\n    elif grep -q '^kali-rolling*' /etc/debian_version; then\n        _DISTRO_=\"KALI-ROLLING\"\n    fi\nfi\n}\n\ndelete()\n{\n    if [[ -e $1 ]] || [[ -d $1 ]]; then\n        rm -rf $1\n        return $?\n    else\n        echo \"$1 does not exist.\"\n        return 0\n    fi\n}\n\nis_vm_running_in_azure()\n{\n    test -d /sys/bus/vmbus/drivers/hv_storvsc || return 1\n    test -f /sys/devices/virtual/dmi/id/chassis_asset_tag || return 1\n    \n    local atag=\"`cat /sys/devices/virtual/dmi/id/chassis_asset_tag`\"\n    if [ \"$atag\" != \"$_AZURE_ASSET_TAG_\" ]; then\n        return 1\n    fi\n    \n    return 0\n}\n\nset_dhcp_ip_for_ubuntu()\n{\n    local _ubuntu_network_interfaces_file=\"/etc/network/interfaces\"\n    \n    echo \"# The loopback network interface\" > $_ubuntu_network_interfaces_file\n    echo \"auto lo\" >> $_ubuntu_network_interfaces_file\n    echo \"iface lo inet loopback\" >> $_ubuntu_network_interfaces_file\n    echo \"\" >> $_ubuntu_network_interfaces_file\n    \n    ip -o link show | awk '{ print $2 }' | sed 's\\:\\\\' | while read _line_\n    do\n        local name=`echo $_line_|awk '{ print $1 }'`\n        \n        if [ \"$name\" = \"lo\" ]\n        then\n            echo \"Skipping loopback nic.\"\n            continue\n        fi\n\n        echo \"Configuring $name ...\"\n        echo \"\" >> $_ubuntu_network_interfaces_file\n        echo \"auto $name\" >> $_ubuntu_network_interfaces_file\n        echo \"iface $name inet dhcp\" >> $_ubuntu_network_interfaces_file\n        \n        #restart the interface\n        echo \"Restarting $name ...\"\n        ifdown \"$name\"\n        ifup \"$name\"\n    done\n}\n\nset_dhcp_ip_for_rhel()\n{\n    local _nw_scripts_dir=\"/etc/sysconfig/network-scripts\"\n    local host_name=`hostname`\n    ip -o link show | awk '{ print $2 }' | sed 's\\:\\\\' | while read _line_\n    do\n        local name=`echo $_line_|awk '{ print $1 }'`\n        \n        if [ \"$name\" = \"lo\" ]; then\n            echo \"Skipping the loopback nic.\"\n            continue\n        fi\n        \n        local _ifconfig_file=\"$_nw_scripts_dir/ifcfg-$name\"\n        \n        echo \"DHCP_HOSTNAME=$host_name\" >$_ifconfig_file\n        echo \"DEVICE=$name\" >> $_ifconfig_file\n        echo \"ONBOOT=yes\" >> $_ifconfig_file\n        echo \"DHCP=yes\" >> $_ifconfig_file\n        echo \"BOOTPROTO=dhcp\" >> $_ifconfig_file\n        echo \"TYPE=Ethernet\" >>  $_ifconfig_file\n        echo \"USERCTL=no\" >>  $_ifconfig_file\n        echo \"PEERDNS=yes\" >>  $_ifconfig_file\n        echo \"IPV6INIT=no\" >> $_ifconfig_file\n        \n        #Restart the interfaces and NetworkManager for RHEL7/CentOS7\n        case $_DISTRO_ in\n            RHEL7|CENTOS7|OL7)\n                echo \"Restarting $name ...\"\n                ifdown \"$name\"\n                ifup \"$name\"\n                \n                echo \"Restarting NetworkManager\"\n                systemctl restart NetworkManager\n                echo \"Exit code: $?\"\n            ;;\n            *)\n                echo \"Skipping $name interface restart\"\n            ;;\n        esac        \n    done\n\n    service network restart \n}\n\nset_dhcp_ip_for_suse() \n{\n    _nw_config_dir=\"/etc/sysconfig/network\"\n\n    #Creating network config files for all the nics\n    ip -o link show | awk '{ print $2 }' | sed 's\\:\\\\' | while read line\n    do\n        name=`echo $line|awk '{ print $1 }'`\n        \n        if [ \"$name\" = \"lo\" ]; then\n            echo \"Skipping the loopback nic entry\"\n            continue\n        fi\n        \n        local _ifconfig_file=\"$_nw_config_dir/ifcfg-$name\"\n        \n        echo \"BOOTPROTO='dhcp'\"  >$_ifconfig_file\n        echo \"MTU='' \" >> $_ifconfig_file\n        echo \"REMOTE_IPADDR='' \" >>$_ifconfig_file\n        echo \"STARTMODE='onboot'\" >>$_ifconfig_file\n    done\n    \n    service network restart\n}\n\nconfigure_nics_to_dhcp()\n{\n    case $_DISTRO_ in\n        CENTOS*|OL*|RHEL*)\n            set_dhcp_ip_for_rhel\n        ;;\n        SLES*)\n            set_dhcp_ip_for_suse\n        ;;\n        UBUNTU14|UBUNTU16|DEBIAN*|KALI*)\n            set_dhcp_ip_for_ubuntu\n        ;;\n        UBUNTU18|UBUNTU20|UBUNTU21|UBUNTU22)\n            echo \"No operation for $_DISTRO_\"\n        ;;\n        *)\n            echo \"ERROR: Unknown distro ${_DISTRO_}.\"\n        ;;\n    esac\n}\n\nremove_systemd_startup_script()\n{\n    echo \"Remove start-up script...\"\n    \n    local script_path=\"${_AM_SCRIPT_DIR_}/${_FIX_DHCP_SCRIPT_}\"\n    local service_file_path=\"/lib/systemd/system/${_AM_STARTUP_}.service\"\n    \n    # Unregister the startup script\n    systemctl disable azure-migrate-startup.service\n\n    # Delete the startup script files.\n    delete $service_file_path\n    delete $_AM_SCRIPT_DIR_\n}\n\nremove_chkconfig_startup_script()\n{\n    echo \"Remove start-up script...\"\n    \n    local script_path=\"${_AM_SCRIPT_DIR_}/${_FIX_DHCP_SCRIPT_}\"\n    local service_file_path=\"/etc/init.d/${_AM_STARTUP_}\"\n    \n    # Unregister the startup script\n    if which chkconfig > /dev/null 2>&1 ;then\n        chkconfig --del \"${_AM_STARTUP_}\"\n    elif which update-rc.d > /dev/null 2>&1 ;then\n        update-rc.d -f \"${_AM_STARTUP_}\" remove\n    else\n        echo \"ERROR: Could not remove startup script.\"\n    fi\n        \n\n    # Delete the startup script files.\n    delete $service_file_path\n    delete $_AM_SCRIPT_DIR_\n}\n\nremove_startup_script()\n{\n    case $_DISTRO_ in\n        RHEL6|CENTOS6|OL6|SLES11|UBUNTU14|DEBIAN7)\n            remove_chkconfig_startup_script\n            ;;\n        RHEL7|CENTOS7|OL7|SLES12|DEBIAN8|UBUNTU16|KALI*|RHEL8|RHEL9|OL8|OL9|CENTOS8|CENTOS9|DEBIAN9|DEBIAN10|DEBIAN11)\n            remove_systemd_startup_script\n            ;;\n        *)\n            echo \"Unknown distro $_DISTRO_\"\n            ;;\n    esac\n}\n\nfix_dhcp_on_startup()\n{\n    is_vm_running_in_azure\n    if [[ $? -eq 0 ]]; then\n        echo \"VM is running in azure. Fixing dhcp ...\"\n        configure_nics_to_dhcp\n        remove_startup_script\n    else\n        echo \"VM is not running in azure. Exiting ...\"\n    fi\n}\n\nmain()\n{\nfind_distro\n\nfix_dhcp_on_startup\n}\n\nmain \"$@\"\n", "num_lines": 325}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##+----------------------------------------------------------------------------------+\n##            Copyright(c) Microsoft Corp. 2021\n##+----------------------------------------------------------------------------------+\n## File         :   InstallLinuxGuestAgent.sh\n##\n## Description  :   Script invoked by asr.installga service on Migrated/Failed-over VM.\n##                  Executes steps to install guest agent on the VM.\n##\n## History      :   29-01-2021 (Shantanu Mishra) - Created\n##\n## Usage        :   bash InstallLinuxGuestAgent.sh <Linux_Distro_Name> <Folder_Path> <install_setuptools>\n##+----------------------------------------------------------------------------------+\n\n# Region: Global Variables\n\nwaagent_servicename=\"waagent\"\n\n# EndRegion\n\n#Region: Functions\n\nunset service_binary\nfunction GetServiceBinaryName\n{\n    service_binary=\"systemctl\"\n    \n    ret=$(systemctl)\n    if [[ $? -ne 0 ]]; then    \n\t\techo \"systemctl is not present on the system.\"\n\t\techo \"Using service commands to run script.\"\n\t\tservice_binary=\"service\"\n    fi\n}\n\n#$1: Operation to perform the service\n#$2: Service Name\nfunction RunServiceCommand\n{\n    if [[ $service_binary == \"systemctl\" ]]; then\n        systemctl $1 $2\n    else\n        service $2 $1\n    fi\n}\n\nunset pythonversion\n# Check for the version of python\nfunction CheckValidPythonVersion\n{\n    # Check for Major Version 3 for python.\n    python3 --version\n    if [[ $? -ne 0 ]] ; then\n        echo \"Python3 is not installed on the VM.\"\n    else\n        pythonversion=3\n\t\treturn\n    fi\n    \n    # Check for Major version 2 and Minor Version >= 6 for Python.\n    python --version\n    if [[ $? -ne 0 ]] ; then        \n        echo \"Failed to install Linux Guest Agent on the VM. \"\n        echo \"Install python version 2.6+ to install Guest Agent. \"\n        exit 0\n    else\n        vermajor=$(python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(major)\")\n        verminor=$(python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(minor)\")\n        if [ $vermajor -eq 2 ] && [ $verminor -ge 6 ]; then\n            pythonversion=2\n\t\t\treturn\n        else\n            echo \"Failed to install Linux Guest Agent on the VM. \"\n            echo \"Install python version 2.6+ to install Guest Agent. \"\n            exit 0\n        fi\n    fi    \n\n    exit 0\n}\n\nunset gaRunningState\nfunction CheckGuestAgentRunningState\n{\n    gaRunningState=1\n    RunServiceCommand stop $1\n    RunServiceCommand start $1\n    checkAzureGAInstalled=$(RunServiceCommand status $waagent_servicename)\n\n    if [[ $checkAzureGAInstalled == *\"active\"* ]] && [[ $checkAzureGAInstalled == *\"running\"* ]]; then\n        echo \"$1 Linux Guest Agent is already installed on the VM and is in running state. \"\n        gaRunningState=0\n        return\n    elif [[ $checkAzureGAInstalled == *\"is running\"* ]]; then\n        gaRunningState=0\n        echo \"$1 Linux Guest Agent is already installed on the VM and is in running state. \"\n        return\n    else\n        gaRunningState=1\n        return\n    fi\n}\n\n# Get the guest agent service name\n# The name is conventionally walinuxagent for Debian/Ubuntu, and waagent for other distributions. \nfunction GetWALinuxAgentServiceName\n{\n    if [[ -f '/usr/lib/systemd/system/walinuxagent.service' ]] || [[ -f '/lib/systemd/system/walinuxagent.service' ]]; then \n        waagent_servicename=\"walinuxagent\"\n    else\n        waagent_servicename=\"waagent\"\n    fi\n}\n\n#EndRegion\n\n# Formatting Logs\necho \"\"\necho \"\"\necho $(date)\necho \"\"\n#End Formatting Logs\n\nunset setup_tools_install\nunset base_linuxga_dir\n\nlinux_distro=$1\nbase_linuxga_dir=\"$2\"\nsetup_tools_install=\"$3\"\n\nGetServiceBinaryName\nCheckValidPythonVersion\necho \"Python version is $pythonversion\"\n\n# Check if ASR pushed guest agent binaries are present on the VM.\n# Files maybe absent if there was a failure in downloading guest agent files from Github,\n# Or if it's the second boot of the VM, before which ASR deletes the installation binaries.\nif [[ ! -d \"/$base_linuxga_dir/WALinuxAgentASR\" ]]; then\n    echo \"Guest agent installation folder not found. \"\n    echo \"This should be second boot of VM since migration to Azure, hence skipping guest agent installation. \"\n    exit 0\nelse\n    echo \"Guest agent installation binaries present on the VM. Installation will proceed. \"\nfi\n\nGetWALinuxAgentServiceName\necho \"Working Directory: $base_linuxga_dir\"\n\n # Check if waagent folders exists\nif [[ -f '/usr/sbin/waagent' ]]; then\n    echo \"Guest Agent is already installed on the virtual machine.\"\n\n    # Try to bring the Guest Agent online. If it comes to active or running state, do not Install\n    # If found otherwise (i.e. agent remains in dead or inactive state), remove the guest agent and reinstall.\n    CheckGuestAgentRunningState $waagent_servicename\n    \n    if [[ $gaRunningState -eq 0 ]]; then\n        echo \"Guest agent is in running state. \"\n        exit 0\n    else\n        # WALinuxAgent is not present in runnable state.\n        # Delete the waagent folder and log files, and reinstall the agent.\n        RunServiceCommand stop $waagent_servicename\n        rm -rf /var/lib/waagent/\n        rm -f /var/log/waagent.log\n    fi\nfi\n\nif [[ $pythonversion -eq 3 ]]; then\n    echo \"Installing using python3\"\n\n    python3 /$base_linuxga_dir/PythonSetupPrereqs.py\n    if [[ $setup_tools_install == *\"install_setup_tools_true\"* ]]; then\n        # Try repository based installation first.\n        if [[ $linux_distro == *\"UBUNTU\"* ]]; then \n            # For CentOS, Redhat python3, setuptools comes pre-installed.\n            apt-get install python3-distutils python3-setuptools -y\n        fi\n\n        cd \"/$base_linuxga_dir/setuptools-33.1.1\"\n        python3 setup.py install\n    fi\n\n    cd /$base_linuxga_dir/WALinuxAgentASR/WALinuxAgent-master\n    python3 setup.py install --register-service --force\n\n    # This is for backward compatibility for Guest agent installation. The service file may exist at 2 locations and 2 possible names.\n    # There are some guest agent installation binaries which fail to replace python version with the appropriate python version (3) after installation.\n    # Replace python with python3 for the python path. The space after ExecStart=/usr/bin/python ensures that \n    # if python3 is already added in the path, python string won't be replaced.\n    cat bin/waagent | sed 's_#!/usr/bin/env python_#!/usr/bin/env python3_' > /usr/sbin/waagent\n    if [ -f '/usr/lib/systemd/system/waagent.service' ]; then\n        cat /usr/lib/systemd/system/waagent.service | sed -i 's_ExecStart=/usr/bin/python _ExecStart=/usr/bin/python3 _' /usr/lib/systemd/system/waagent.service\n    fi\n    if [ -f '/lib/systemd/system/waagent.service' ]; then \n        cat /lib/systemd/system/waagent.service | sed -i 's_ExecStart=/usr/bin/python _ExecStart=/usr/bin/python3 _' /lib/systemd/system/waagent.service\n    fi\n\tif [ -f '/usr/lib/systemd/system/walinuxagent.service' ]; then\n        cat /usr/lib/systemd/system/walinuxagent.service | sed -i 's_ExecStart=/usr/bin/python _ExecStart=/usr/bin/python3 _' /usr/lib/systemd/system/walinuxagent.service\n    fi\n    if [ -f '/lib/systemd/system/walinuxagent.service' ]; then \n        cat /lib/systemd/system/walinuxagent.service | sed -i 's_ExecStart=/usr/bin/python _ExecStart=/usr/bin/python3 _' /lib/systemd/system/walinuxagent.service\n    fi\nfi\n\nif [[ $pythonversion -eq 2 ]]; then\n     # [shamish]: To remove in next release.\n    python /$base_linuxga_dir/PythonSetupPrereqs.py\n\n    # Installing setuptools v33.1.1 using pushed package.\n    # Using setuptools-33.1.1 as it support python 2.6+, which matches Linux guest agent support matrix.\n    if [[ $setup_tools_install == *\"install_setup_tools_true\"* ]]; then\n        cd \"/$base_linuxga_dir/setuptools-33.1.1\"\n        python setup.py install\n    fi\n\n    cd /$base_linuxga_dir/WALinuxAgentASR/WALinuxAgent-master\n    python setup.py install --register-service --force\nfi\n\n# Make waagent as executable file, reload system-daemon and restart waagent\nchmod +x /usr/sbin/waagent\nif [[ $service_binary != *\"systemctl\"* ]]; then\n    chmod +x /etc/init.d/waagent\nfi\n\n# Refresh Guest agent binary name post installation\nGetWALinuxAgentServiceName\n\nsystemctl daemon-reload # Ignorable error if systemctl is absent\nCheckGuestAgentRunningState $waagent_servicename\n\nif [[ $gaRunningState -eq 0 ]]; then\n    echo \"Guest Agent successfully installed.\"\n\trm -f /etc/profile.d/ASRLinuxGAStartup.sh\nelse\n    case $linux_distro in\n    CENTOS*|OL*)\n        CheckGuestAgentRunningState \"waagent\"\n        yum install -y python-pyasn1 WALinuxAgent\n        ;;\n    RHEL*)\n        # [TODO] Needs Subscription Manager changes.\n        # subscription-manager repos --enable=rhel-6-server-extras-rpms\n        # CheckGuestAgentRunningState \"waagent\"\n        # yum install -y WALinuxAgent\n        ;;\n    UBUNTU*)\n        CheckGuestAgentRunningState \"walinuxagent\"\n        apt-get install -y cloud-init gdisk netplan.io walinuxagent\n        apt install -y linux-azure linux-image-azure linux-headers-azure linux-tools-common linux-cloud-tools-common linux-tools-azure linux-cloud-tools-azure\n\n\n# sudo reboot\n        ;;\n    DEBIAN*)\n        CheckGuestAgentRunningState \"walinuxagent\" \n        apt-get install -y waagent\n        ;;\n    SLES*)\n        CheckGuestAgentRunningState \"waagent\"\n        if [[ $linux_distro == *\"SLES15\"* ]]; then\n            zypper ar -f http://download.opensuse.org/repositories/Cloud:Tools/openSUSE_15.2 Cloud:Tools_15.2\n            zypper ar -f https://download.opensuse.org/distribution/15.2/repo/oss openSUSE_15.2_OSS\n            zypper ar -f http://download.opensuse.org/update/15.2 openSUSE_15.2_Updates\n        fi\n        \n        zypper -n refresh\n        zypper -n install python-azure-agent\n        zypper -n install cloud-init\n        ;;\n    esac\nfi\n\n# Remove the folder and file to make subsequent boots faster.\nrm -f /$base_linuxga_dir/PythonSetupPrereqs.py\nexit 0", "num_lines": 278}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n#GENERIC FUNCTIONS WHICH WILL USED FOR LINUX_P2V PROJECT.\n_UUID_=\"\"\n_LABEL_=\"\"\n_disk_name_=\"\" #contains Target device Name, \n_base_diskname_=\"\"\n_dev_name_=\"\" #Contains device name for a UUID or Label. Either it could be a partition or entire device.\n_real_partition_name_=\"\" #It contains partition name corresponding to sym-link.\n_lv_dev_name_=\"\" #Contains alias for an LV.\n\n#FINDS UUID INFORMATION FROM FSTAB-BLKID INFORMATION\nfunction Find_UUID_FSTABINFO\n{\n    _UUID_=\"\"\n    _partition_name_=$1\n    _uuid_=`sed -n  \"/^[=]* FSTAB UUID Information - START [=]*/,/^[=]* FSTAB UUID Information - END [=]*/p\" \"$_INPUT_CONFIG_FILE_\" | grep \"$_partition_name_\" | head -1`\n    if [ \"${_uuid_}\" ]; then\n        _uuid_=`echo $_uuid_ | awk -F\"UUID=\" '{ print $2 }' | awk '{ print $1 }' | sed -e \"s/\\\"//g\"`\n        _UUID_=$_uuid_\n    fi\n    return $_SUCCESS_   \n}\n\n\n#FINDS UUID INFORMATION FROM BLKID INFORMATION\nfunction Find_UUID_BLKID\n{\n    _UUID_=\"\"\n    _partition_name_=$1\n    _uuid_=`sed -n  \"/^[=]* BLKID Information - START [=]*/,/^[=]* BLKID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | grep \"$_partition_name_\"`\n        if [ \"${_uuid_}\" ]; then\n                _uuid_=`echo $_uuid_ | awk -F\"UUID=\" '{ print $2 }' | awk '{ print $1 }' | sed -e \"s/\\\"//g\"`\n                _UUID_=$_uuid_\n        fi\n        if [ -z $_UUID_ ]; then\n            return $_FAILED_\n        fi\n        return $_SUCCESS_\n}\n\n#FINDS LABEL INFORMATION FROM BLKID INFORMATION\nfunction Find_LABEL_BLKID\n{\n    _partition_name_=$1\n    _label_=`sed -n  \"/^[=]* BLKID Information - START [=]*/,/^[=]* BLKID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | grep \"$_partition_name_\"`\n        if [ \"${_label_}\" ]; then\n                _label_=`echo $_label_ | awk -F\"LABEL=\" '{ print $2 }' | awk '{ print $1 }' | sed -e \"s/\\\"//g\"`\n                _LABEL_=$_label_\n        fi\n        if [ -z $_LABEL_ ]; then\n            return $_FAILED_\n        fi\n        return $_SUCCESS_\n}\n\nfunction Get_Partition_Name_BY_ID\n{\n    _partition_name_=$1\n    _real_partition_name_=\"\"\n    echo \"Finding disk for partition : $_partition_name_ using by-id information\"\n\n    _temp_partition_name_=`echo $_partition_name_ | sed 's:\\/dev\\/disk\\/by-id\\/::g'`\n    echo \"temp partition name = $_temp_partition_name_\"\n    _real_partition_name_=`sed -n  \"/^[=]* BY-ID Information - START [=]*/,/^[=]* BY-ID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | egrep -w \"$_temp_partition_name_ \"`\n    echo \"real partition details = $_real_partition_name_\"\n    _real_partition_name_=`echo  $_real_partition_name_ | awk -F\"-> \" '{ print $2 }'| sed -e \"s:\\.\\.\\/::g\"`\n    if [ ! \"${_real_partition_name_}\" ]; then\n        echo \"ERROR :: Failed to find sym link for partition $_partition_name_.\"\n        return $_FAILED_\n    fi\n\n    # Add '/dev/' prefix to _real_partition_name_ if its not already present.\n    [[ \"$_real_partition_name_\" =~ ^\\/dev\\/ ]] || _real_partition_name_=\"/dev/$_real_partition_name_\"\n    echo \"Found sym link for partition $_real_partition_name_ , sym link = $_partition_name_\"\n    return  $_SUCCESS_\n}\n\nfunction Get_Partition_Name_BY_UUID\n{\n    _partition_name_=$1\n    _real_partition_name_=\"\"\n    echo \"Finding disk for partition : $_by_uuid_ using by-uuid information\"\n    \n    #NOW WE HAVE TO REMOVE /DEV/DISK/BY-UUID fROM PARTITION NAME PASSED.\n    _temp_partition_name_=`echo $_partition_name_ | sed 's:\\/dev\\/disk\\/by-uuid\\/::g'`\n        \n     _real_partition_name_=`sed -n  \"/^[=]* BY-UUID Information - START [=]*/,/^[=]* BY-UUID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | egrep -w \"$_temp_partition_name_ \"`\n    \n    _real_partition_name_=`echo  $_real_partition_name_ | awk -F\"-> \" '{ print $2 }'| sed -e \"s:\\.\\.\\/::g\"`\n        if [ ! \"${_real_partition_name_}\" ]; then\n                echo \"ERROR :: Failed to find sym link for partition $_partition_name_.\"\n                return $_FAILED_\n        fi\n    _real_partition_name_=\"/dev/$_real_partition_name_\"\n        echo \"Found sym link for partition $_partition_name_ , sym link = $_real_partition_name_.\"\n        return  $_SUCCESS_\n}\n\nfunction Get_partition_Name_BY_LABEL\n{\n    _partition_name_=$1\n    _real_partition_name_=\"\"\n    echo \"Finding disk for partition : $_by_label_ using by-label information\"\n\n        _temp_partition_name_=`echo $_partition_name_ | sed 's:\\/dev\\/disk\\/by-label\\/::g'`\n\n    _real_partition_name_=`sed -n  \"/^[=]* BY-LABEL Information - START [=]*/,/^[=]* BY-LABEL Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | egrep -w \"$_temp_partition_name_ \"`\n\n    _real_partition_name_=`echo  $_real_partition_name_ | awk -F\"-> \" '{ print $2 }'| sed -e \"s:\\.\\.\\/::g\"`\n        if [ ! \"${_real_partition_name_}\" ]; then\n                echo \"ERROR :: Failed to find sym link for partition $_partition_name_.\"\n                return $_FAILED_\n        fi\n    _real_partition_name_=\"/dev/$_real_partition_name_\"\n        echo \"Found sym link for partition $_partition_name_ , sym link = $_real_partition_name_.\"\n        return  $_SUCCESS_\n}\nfunction Get_Partition_Name_BY_PATH\n{\n    _partition_name_=$1\n    _real_partition_name_=\"\"\n    echo \"Finding disk for partition : $_by_path_ using by-path information\"\n\n        _temp_partition_name_=`echo $_partition_name_ | sed 's:\\/dev\\/disk\\/by-path\\/::g'`\n\n    _real_partition_name_=`sed -n  \"/^[=]* BY-PATH Information - START [=]*/,/^[=]* BY-PATH Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | egrep -w \"$_temp_partition_name_ \"`\n\n    _real_partition_name_=`echo  $_real_partition_name_ | awk -F\"-> \" '{ print $2 }'| sed -e \"s:\\.\\.\\/::g\"`\n        if [ ! \"${_real_partition_name_}\" ]; then\n                echo \"ERROR :: Failed to find sym link for partition $_partition_name_.\"\n                return $_FAILED_\n        fi\n    _real_partition_name_=\"/dev/$_real_partition_name_\"\n        echo \"Found sym link for partition $_partition_name_ , sym link = $_real_partition_name_.\"\n        return  $_SUCCESS_\n}\n\nfunction Deref_SymLink\n{\n    _partition_name_=$1\n\n    _tmp_disk_by_var=`echo $_partition_name_ | grep \"by-id\"`\n    if [ $? -eq 0 ]; then\n        Get_Partition_Name_BY_ID \"$_partition_name_\"\n        \n    else\n        _tmp_disk_by_var=`echo $_partition_name_ | grep \"by-label\"`\n        if [ $? -eq 0 ]; then\n            Get_Partition_Name_BY_LABEL \"$_partition_name_\"\n        else\n            _tmp_disk_by_var=`echo $_partition_name_ | grep \"by-path\"`\n            if [ $? -eq 0 ]; then\n                Get_Partition_Name_BY_PATH \"$_partition_name_\"\n            else\n                _tmp_disk_by_var=`echo $_partition_name_ | grep \"by-uuid\"`\n                if [ $? -eq 0 ]; then\n                    Get_Partition_Name_BY_UUID \"$_partition_name_\"\n                else\n                    echo \"partition sent is a real partition.\"\n                    return $_FAILED_\n                fi\n            fi\n        fi\n    fi\n    return $_SUCCESS_\n}\n\n#IT FINDS UUID. IT JUST MAKES BEST POSSIBLE COMBINATIONS TO FIND UUID FOR A DEVICE PASSED.\nfunction Find_UUID\n{\n    _UUID_=\"\" #CLEAR LAST ITERATION UUID\n    _partition_name_=$1\n\n    #FIRST CHECK IT\"S UUID IN FSTAB -BLKID MAPPING TABLE\n    Find_UUID_FSTABINFO \"$_partition_name_\"\n    \n    #IF NOT FOUND ABOVE,CHECK IN BLKID TABLE\n    if [ -z \"${_UUID_}\" ]; then\n        Find_UUID_BLKID \"$_partition_name_\"\n    fi\n\n    if [ -z \"${_UUID_}\" ]; then\n        #FIRST WE HAVE TO DEREF SYMLINK\n        Deref_SymLink \"$_partition_name_\"       \n        if [ 0 -eq $? ]; then\n            echo \"Found partition name : $_real_partition_name_\"\n            Find_UUID_FSTABINFO \"$_real_partition_name_\"\n            if [ ! \"${_UUID_}\"  ]; then\n                Find_UUID_BLKID \"$_real_partition_name_\"\n            fi\n        fi\n    fi\n\n    if [ -z \"${_UUID_}\" ]; then\n        echo \"ERROR :: Failed to find UUID for partition $_partition_name_.\"\n        return $_FAILED_\n    fi\n    #WE NEED TO CHOP OFF QUOTES TO UUID.\n    echo \"UUID = $_UUID_.\"\n    echo \"Found UUID for partition $_partition_name_, UUID = $_UUID_.\"\n    return $_SUCCESS_\n}\n\n#THIS FUNCTION IS USED TO DETERMINE SOURCE DISK NAME ON TARGET SIDE.\nfunction GetTargetDiskName_old\n{\n    _disk_num_=$1\n    _disk_name_=\"\"\n    echo \"Generating disk name for disk at number $_disk_num_\"\n    #I need to check this Path.Whether it invokes or not.Else better it could be to pass the _VX_INSTALL_PATH_ as second input.\n    if [ -d \"$_FILES_PATH_/bin/\" ]; then\n        _disk_name_=`$_FILES_PATH_/bin/generate_device_name $_disk_num_`\n    else\n        _disk_name_=`$_FILES_PATH_/generate_device_name $_disk_num_`\n    fi\n    echo \"Disk Name = $_disk_name_\"\n    if [ ! -z \"${_disk_name_}\" ]; then\n        _disk_name_=\"/dev/$_disk_name_\"\n    fi\n    return $_SUCCESS_ \n}\n\n#THIS FUNCTION IS USED TO DETERMINE SOURCE DISK NAME ON TARGET SIDE.\nfunction GetTargetDiskName\n{\n    _device_pos_=$1\n    _DEVICE_NAME_=\"\"\n\n        while true; do\n                if [ 0 -gt ${_device_pos_} ]; then\n                        break\n                fi\n\n                _ascii_index_of_a_=$(printf \"%d\" \\'a)\n                if [ 26 -gt ${_device_pos_} ]; then\n                        _ascii_index_of_dev_pos_=$((${_ascii_index_of_a_}+${_device_pos_}))\n                        _DEVICE_NAME_=$(printf 'sd%s' $(printf \"\\x$(printf %x ${_ascii_index_of_dev_pos_})\"))\n                        break\n                elif [ 702 -gt ${_device_pos_} ]; then\n                        _position1_=$(( ${_ascii_index_of_a_} + ${_device_pos_}/26 -1 ))\n                        _position2_=$(( ${_ascii_index_of_a_} + ${_device_pos_}%26 ))\n                        echo ${_position1_} ${_position2_}\n                        _DEVICE_NAME_=$(printf 'sd%s%s' $(printf \"\\x$(printf %x ${_position1_})\") $(printf \"\\x$(printf %x ${_position2_})\"))\n                        break\n                else\n                        break\n                fi\n        done\n\n    _disk_name_=${_DEVICE_NAME_}\n        echo \"Disk Name = $_disk_name_\"\n        if [ ! -z \"${_disk_name_}\" ]; then\n                _disk_name_=\"/dev/$_disk_name_\"\n        fi\n        return $_SUCCESS_\n}\n\n\n# MapDeviceHierarchyToBaseDevice takes two input arguments\n# $1 - Inpout file\n# $2 - Input device name\n# Returns a device name \nfunction MapDeviceHierarchyToBaseDevice\n{\n    _base_diskname_=\"\"\n    dev_hierarchy=$2\n    if [ ! -f $1 ]; then\n        echo \"MapDeviceHierarchyToBaseDevice - input file $1 does not exists\"\n        return $_FAILED_;\n    fi\n\n    # Check if dev_hierarchy is a disk.\n    grep \"Parameter Name=\\\"DiskName\\\" Value=\\\"$dev_hierarchy\\\"\" $1 > /dev/null 2>&1\n    if [ $? -eq 0 ];then\n            echo \"$dev_hierarchy is a disk, and its found in $1.\"\n            _base_diskname_=$dev_hierarchy\n            return $_SUCCESS_\n    fi\n\n    # Check if the $dev_hierarchy exists in host-info, if not then return.\n    grep \"Parameter Name=\\\"Name\\\" Value=\\\"$dev_hierarchy\\\"\" $1 > /dev/null 2>&1\n    if [ $? -ne 0 ]; then\n        echo \"Search device $dev_hierarchy not found in $1.\"\n        return $_SUCCESS_\n    fi\n    \n    # It is possible that multiple dev_hierarchy entries may exists and we can pickup first one.\n    # With above check, there will be at-least one entry with dev_hierarchy in host-info.\n    _search_device_line_number_=`grep -n \"Parameter Name=\\\"Name\\\" Value=\\\"$dev_hierarchy\\\"\" $1 | head -n 1 | awk -F\":\" '{print $1}'`\n\n    # Change the IFS to make deli-meter as '\\n' in for loop.\n    OLDIF=$IFS\n    IFS=$'\\n'\n    for _disk_entry in `grep -n \"DiskName.*\\/dev\\/\" $1 | sort -n`\n    do\n        # Get line number of the current disk entry.\n        _disk_line_number_=`echo $_disk_entry | awk -F\":\" '{print $1}'`\n\n\n        # Get the disk name from the current disk line entry.\n        current_diskname=`echo $_disk_entry | awk -F'Value=' '{ print $2 }'`\n        current_diskname=`echo $current_diskname | sed -e 's:[\"]*::g' | sed -e 's:/>::g' | sed -e 's:\\r::g'`\n\n        # Check if we crossed the required disk section in host-info.\n        if [ $_search_device_line_number_ -lt $_disk_line_number_ ];then\n            # We crossed the search device's disk line.\n            # _base_diskname_ holds the base disk name.\n            echo \"Base device for $dev_hierarchy is $_base_diskname_.\"\n            break\n        fi\n        \n        # Store disk name in _base_diskname_ before going for next disk entry.\n        _base_diskname_=$current_diskname\n    done\n    IFS=$OLDIFS # Restore the IFS\n\n    return $_SUCCESS_\n}\n\n#FINDS DEVICE NAME WITH UUID INFORMATION FROM BLKID INFORMATION\n# $1 - Input UUID\n# Returns a device name\nfunction Find_Device_From_UUID\n{\n    _dev_name_=\"\"\n    _dev_uuid_=$1\n\n    _uuid_=`sed -n  \"/^[=]* BLKID Information - START [=]*/,/^[=]* BLKID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | grep \"$_dev_uuid_\"`\n        if [ \"${_uuid_}\" ]; then\n                _dev_name_=`echo $_uuid_ | awk -F':' '{print $1 }'`\n        fi\n\n    return $_SUCCESS_\n}\n\n#FINDS DEVICE NAME WITH LABEL INFORMATION FROM BLKID INFORMATION\n# $1 - Input LABEL\n# Returns a device name\nfunction Find_Device_From_LABEL\n{\n    _dev_name_=\"\"\n    _dev_label=$1\n\n    _label_=`sed -n  \"/^[=]* BLKID Information - START [=]*/,/^[=]* BLKID Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | grep \"$_dev_label\"`\n        if [ \"${_uuid_}\" ]; then\n                _dev_name_=`echo $_label_ | awk -F':' '{print $1 }'`\n        fi\n\n    return $_SUCCESS_\n}\n\n# FIND IF A GIVEN DEVICE IS A LOGICAL VOLUME\n# $1 - Input block device\n# Returns 0 or 1\nfunction IsDevice_LV\n{\n    _lv_dev_name_=\"\"\n    _is_dev_lv_=$1\n    for _dev_in_dmsetup in `sed -n  \"/^[=]* DMESETUP TABLE Information - START [=]*/,/^[=]* DMSETUP TABLE Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | awk -F':' '{ print $1 }' | grep -v \"=\"`\n    do\n        is_multipath=`echo $_dev_in_dmsetup | awk '{ print $4 }'`\n        if [ \"${is_multipath}\" = \"multipath\" ]; then\n            continue\n        fi\n        _temp_vg=`echo $_dev_in_dmsetup | awk -F'-' '{ print $1 }'` \n        if [ 0 -ne $? ]; then\n            echo \"Device \\\"${_lv_dev_name_}\\\" is not a logical volume.\"\n            return $_FAILED_\n        fi\n        \n        _temp_lv=`echo $_dev_in_dmsetup | awk -F'-' '{ print $2 }'` \n        if [ 0 -ne $? ]; then\n            echo \"Device \\\"${_lv_dev_name_}\\\" is not a logical volume.\"\n            return $_FAILED_\n        fi\n        \n        _temp_dev_name1=\"/dev/$_temp_vg/$_temp_lv\"\n        _temp_dev_name2=\"/dev/mapper/$_temp_vg-$_temp_lv\"\n\n        if [ \"${_temp_dev_name1}\" = \"${_is_dev_lv_}\" ]; then\n            _lv_dev_name_=$_temp_dev_name2\n            break\n        fi\n        if [ \"${_temp_dev_name2}\" = \"${_is_dev_lv_}\" ]; then\n            _lv_dev_name_=$_temp_dev_name1\n            break\n        fi\n    done\n    #Mean to say Device is not an LV.\n    return $_FAILED_;\n}\n\n# FIND IF A GIVEN DEVICE IS A MULTIPATH DEVICE\n# $1 - Input block device\n# Returns 0 or 1\nfunction IsDevice_Multipath\n{\n    _dev_name_=$1\n    for _dev_in_dmsetup in `sed -n  \"/^[=]* DMESETUP TABLE Information - START [=]*/,/^[=]* DMSETUP TABLE Information - END [=]*/p\" $_INPUT_CONFIG_FILE_ | awk -F':' '{ print $1 }' | grep -v \"=\"`\n    do\n        is_multipath=`echo $_dev_in_dmsetup | awk '{ print $4 }'`\n        if [ \"${is_multipath}\" = \"multipath\" ]; then\n            multipath_dev=`echo $_dev_in_dmsetup | awk '{ print $1 }'`\n            # Form a multipath device - TODO other naming schemes\n            multipath_dev=\"/dev/mapper/$multipath_dev\"\n            if [ \"${multipath_dev}\" = \"${_dev_name_}\" ]; then\n                return $_SUCCESS_\n            fi\n        fi\n    done\n    return $_FAILED_;\n}\n# FIND IF A GIVEN DEVICE IS PROTECTED OR NOT\n# $1 - Input block device\n# Returns 0 or 1\nfunction GetProtectedDeviceEntry\n{\n    _dev_name_=$1\n    # Return 0 if the input device name is empty.\n    if [ -z $_dev_name_ ]; then\n        echo \"Invalid input: Empty device name provided.\"\n        return 0\n    fi\n    _protected_disklist=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n    entry=`cat $_protected_disklist | grep -wn \"$_dev_name_\" | awk -F\":\" '{print $1}'`\n    echo \"Entry = $entry\"\n    if [ -z \"${entry}\" ]; then\n        return 0\n    fi\n    return $entry\n}\n\nfunction IsDiskProtected\n{\n    _dev_name_=$1\n    echo \"checking whether device \\\"$_dev_name_\\\" is protected or not.\"\n    _protected_disklist_=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n    _isProtected_=`cat $_protected_disklist_ | grep \"$_dev_name_\"`\n    echo \"is protected = $_isProtected_\"\n    if [ -z \"${_isProtected_}\" ]; then\n        return $_FAILED_\n    fi\n    return $_SUCCESS_\n}\n\nfunction COPY\n{\n    _source_=$1\n    _target_=$2\n\n    echo \"Copying file \\\"$_source_\\\" to \\\"$_target_\\\".\"\n    /bin/cp -f $_source_ $_target_\n    if [ 0 -ne $? ]; then\n        return $?\n    fi\n    return $_SUCCESS_\n}\n    \nfunction MOVE\n{\n    _source_=$1\n    _target_=$2\n\n    echo \"Moving file \\\"$_source_\\\" to \\\"$_target_\\\".\"\n    /bin/mv -f $_source_ $_target_\n    if [ 0 -ne $? ]; then\n        return $?\n    fi\n    return $_SUCCESS_\n}\n\n", "num_lines": 473}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#DBG=\"set -x\"\n\n# TODO: Use Find_Device_From_UUID() from Linux_P2V_Lib.sh\nget_original_dev()\n{\n\tlocal uuid=$(blkid -o value -s UUID $1)\n\tlocal pat=\"FSTAB UUID Information\"\n\n\tsed -n \"/^[=]* $pat - START [=]*/,/^[=]* $pat - END [=]*/p\" $2 |\\\n\tgrep $uuid | cut -f 1 -d \":\" | sort | uniq\n}\n\nget_fs_opt()\n{\n\tlocal pat=\"Filesystem table\"\n\t\n\tsed -n \"/^[=]* $pat - START [=]*/,/^[=]* $pat - END [=]*/p\" $2 |\\\n\tgrep \"$1\\s\" | awk '{print $4}'\n}\n\nis_root_mnt()\n{\n\tlocal rdev=$(df $1 | sed -n 2p | cut -f 1 -d \" \")\n\t\n\trdev=\"$(readlink -f $rdev)\"\n\n\tif [ \"$rdev\" = \"`readlink -f $2`\" ]; then\n\t\techo \"Root Mount\"\n\t\treturn 0\n\telse\n\t\techo \"Non Root Mount\"\n\t\treturn 1\n\tfi\n}\n\nreplace_pat_in_file()\n{\n\t$DBG\n\n\tlocal opat=\"$1\"\n\tlocal npat=\"$2\"\n\tlocal file=\"$3\"\n\n\techo \"Convert $opat to $npat\"\n\t\n\tif [ ! -f \"$file\" ]; then\n\t\treturn 0\n\tfi\n\n\tsed -i \"s/$opat/$npat/\" \"$file\"\t\n}\n\nfstab_convert_label_to_uuid()\n{\n\t$DBG\n\tlocal label=$(blkid -o value -s LABEL $1)\n\tlocal uuid=$(blkid -o value -s UUID $1)\n\n\tif [ \"$label\" = \"\" ]; then\n\t\treturn\n\tfi\n\n\t# LABEL=label -> UUID=uuid\n\treplace_pat_in_file \"LABEL=$label\" \"UUID=$uuid\" \"$2\"\n\t# LABEL=\"label\" -> UUID=uuid\n\treplace_pat_in_file \"LABEL=\\\\\\\"$label\\\\\\\"\" \"UUID=$uuid\" \"$2\"\n}\n\nfstab_convert_uuid_to_uuid()\n{\n\t$DBG\n\tlocal uuid=$(blkid -o value -s UUID $1)\n\n\treplace_pat_in_file \"UUID=\\\\\\\"$uuid\\\\\\\"\" \"UUID=$uuid\" \"$2\"\n}\n\nfstab_convert_dev_to_uuid()\n{\n\t$DBG\n\tlocal uuid=$(blkid -o value -s UUID $1)\n\tlocal odevlist=\"$(get_original_dev $1 $2)\"\n\tlocal odev=\"\"\n\n\techo \"Original Dev: $1 -> $odevlist\"\n\t\n\tfor odev in $odevlist; do\n\t\todev=\"$(echo $odev | sed 's/\\//\\\\\\//g')\"\n\n\t\t# /dev/name... -> UUID=uuid\n\t\treplace_pat_in_file \"$odev\" \"UUID=$uuid\" \"$3\"\n\tdone\n}\n\nfstab_mount_all_uuid()\n{\n\t$DBG\n\tlocal fstab=$1\n\tlocal uuid=\"$2\"\n\tlocal mnt=\"$3\"\n\n\techo \"Mount all FS with UUID = $uuid\"\n\n\tcat $fstab | grep ^\"UUID=$uuid\" | tr -s \" \" | sort -k2,2 |\\\n\twhile read line; do\n\t\tsubmnt=\"$(echo $line | tr -s \" \" | cut -f 2 -d \" \")\"\n\t\topt=\"$(echo $line | tr -s \" \" | cut -f 4 -d \" \")\"\n\n\t\tif [ \"$submnt\" = \"/\" ]; then\n\t\t\techo \"Skipping /\"\n\t\t\tcontinue\n\t\tfi\n\n\t\tsubmnt=\"$(echo $submnt | sed \"s/\\/$//\")\"\n\n\t\techo \"mount -o $opt -U $uuid $mnt$submnt\" \n\t\tmount -o $opt -U $uuid $mnt$submnt\n\tdone\n}\n\ngeneric_mount_all()\n{\n\t$DBG\n\tlocal rootmnt=\"$1\"\n\tlocal dev=\"$2\"\n\n\tlocal ofile=\"$rootmnt/etc/fstab\"\n\tlocal mfile=\"/tmp/fstab.$$\"\n\tlocal cfile=\"$rootmnt/etc/Configuration.info\"\n\n\tlocal uuid=$(blkid -o value -s UUID $dev)\n\n\tcp $ofile $mfile || {\n\t\techo \"Cannot copy fstab\"\n\t\treturn 1\n\t}\n\t\n\tfstab_convert_uuid_to_uuid \"$dev\" \"$mfile\" \n\tfstab_convert_label_to_uuid \"$dev\" \"$mfile\"\n\tfstab_convert_dev_to_uuid \"$dev\" \"$cfile\" \"$mfile\"\n\n\tfstab_mount_all_uuid \"$mfile\" \"$uuid\" \"$rootmnt\"\n\n\tcat $mfile\n\trm -f $mfile\n}\n\nbtrfs_find_mount_root()\n{\n\tlocal vid=\"\"\n\tlocal vidlist=\"\"\n\tlocal cfile=\"$1/etc/Configuration.info\"\n\n\techo \"Trying to find root subvolume\"\n\n\t# Check for subvolumes with \"root\" in name\n\tvidlist=$(btrfs subvolume list $1 | awk '{print $2}')\n\n\tfor vid in $vidlist; do\n\t\techo \"Mounting $vid\"\n\t\tumount -f $1\n\t\tmount -t btrfs -o subvolid=$vid $2 $1\n\t\ttest -f $cfile && {\n\t\t\techo \"Root VID: $vid\"\n\t\t\tbreak\n\t\t}\n\tdone\n}\n\nbtrfs_mount_all()\n{\n\tlocal cfile=\"$1/etc/Configuration.info\"\n\n\ttest -f $cfile || btrfs_find_mount_root $1 $2\n\n\t# In case it is a root snapshot, find the root \n\t# device from Configuration.info\n\tis_root_mnt $1 $2 && {\n\t\tfsopt=$(get_fs_opt \"/\" \"$cfile\")\n\n\t\techo \"Remounting root: -o $fsopt\"\n\t\tumount $1\n\t\tmount -t btrfs -o $fsopt $2 $1\n\t}\n\n    #exec &> >(tee -a \"$1/var/log/MountFS.log\")\n\tgeneric_mount_all $@\n\tdf\n\treturn $?\n}\n\necho \"Mount subvolumes for $2: $1\"\n\nif [ \"`dirname $0`\" != \"/tmp\" -a -x \"$1/MountFS.sh\" ]; then\n    echo \"Executing local script\"\n    cp $1/MountFS.sh /tmp || {\n    \techo \"Cannot copy\"\n\t    exit -1\n    }\n    /tmp/MountFS.sh $@ \nelse\n    fstype=\"$(blkid -o value -s TYPE $2)\"\n    if [ \"$fstype\" = \"btrfs\" ]; then\n\t    ${fstype}_mount_all \"$1\" \"$2\" \n    \texit $?\n    else\n\t    exit 0\n    fi\nfi\n", "num_lines": 211}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n\ncase `uname` in\n  Linux)\n        if [ -f /etc/enterprise-release ] && [ -f /etc/redhat-release ] ; then\n            if grep -q 'Enterprise Linux Enterprise Linux Server release 5.* (Carthage)' /etc/enterprise-release; then \n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"OL5-32\"\n                else\n                    OS=\"OL5-64\"\n                fi\n            fi\n        elif [ -f /etc/oracle-release ] && [ -f /etc/redhat-release ] ; then\n            if grep -q 'Oracle Linux Server release 6.*' /etc/oracle-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"OL6-32\"\n                else\n                    OS=\"OL6-64\"\n                fi\n            fi\n            if grep -q 'Oracle Linux Server release 7.*' /etc/oracle-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"OL7-32\"\n                else\n                    OS=\"OL7-64\"\n                fi\n            fi\n        elif [ -f /etc/redhat-release ]; then\n            if grep -q 'Red Hat Enterprise Linux [AE]S release 4 (Nahant Update [4-9])' /etc/redhat-release || \\\n                grep -q 'CentOS release 4.[4-9] (Final)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"RHEL4-32\"\n                else\n                    OS=\"RHEL4-64\"\n                fi            \n            elif grep -q 'Red Hat Enterprise Linux Server release 5.* (Tikanga)' /etc/redhat-release || \\\n                grep -q 'CentOS release 5.* (Final)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                        OS=\"RHEL5-32\"\n                else\n                        OS=\"RHEL5-64\"\n                fi\n            elif grep -q 'Red Hat Enterprise Linux Server release 6.* (Santiago)' /etc/redhat-release || \\\n                grep -q 'CentOS Linux release 6.* (Final)' /etc/redhat-release || \\\n                grep -q 'CentOS release 6.* (Final)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    # Don't assign OS value if OS is RHEL6U3-32/CentOS6.3-32 as we don't support agent on it.\n                    if grep -q 'Red Hat Enterprise Linux Server release 6.3 (Santiago)' /etc/redhat-release || \\\n                        grep -q 'CentOS Linux release 6.3 (Final)' /etc/redhat-release || \\\n                        grep -q 'CentOS release 6.3 (Final)' /etc/redhat-release; then\n                        :\n                    else\n                        OS=\"RHEL6-32\"\n                    fi\n                else\n                    OS=\"RHEL6-64\"\n                    if grep -q 'CentOS release 6.4 (Final)' /etc/redhat-release || grep -q 'Red Hat Enterprise Linux Server release 6.4 (Santiago)' /etc/redhat-release ; then\n                        if echo `uname -r`| grep -E '2.6.32-358|2.6.32-358.23.2' >/dev/null 2>&1 ; then\n                            OS=\"RHEL6U4-64\"\n                        fi\n                    fi\n                fi\n            elif grep -q 'XenServer release 4.1.0-7843p (xenenterprise)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-4.1.0-7843p-32\"\n                else\n                    OS=\"CITRIX-XEN-4.1.0-7843p-64\"\n                fi            \n            elif grep -q 'XenServer release 5.0.0-10918p (xenenterprise)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.0.0-10918p-32\"\n                else\n                    OS=\"CITRIX-XEN-5.0.0-10918p-64\"\n                fi\n            elif grep -q 'XenServer release 4.0.1-4249p (xenenterprise)' /etc/redhat-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-4.0.1-4249p-32\"\n                else\n                    OS=\"CITRIX-XEN-4.0.1-4249p-64\"\n                fi\n            elif grep -q 'XenServer release 5.5.0-15119p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 5.5.0-15119p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.5.0-15119p-32\"\n                else\n                    OS=\"CITRIX-XEN-5.5.0-15119p-64\"\n                fi\n            elif grep -q 'XenServer release 5.5.0-25727p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 5.5.0-25727p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.5.0-25727p-32\"\n                else\n                    OS=\"CITRIX-XEN-5.5.0-25727p-64\"\n                fi            \n            elif grep -q 'XenServer release 5.6.0-31188p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 5.6.0-31188p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.6.0-31188p-32\"\n                else\n                    OS=\"CITRIX-XEN-5.6.0-31188p-64\"\n                fi \n            elif grep -q 'XenServer release 5.6.100-39265p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 5.6.100-39265p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.6.100-39265p-32\"\n                fi            \n            elif grep -q 'XenServer release 5.6.100-47101p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 5.6.100-47101p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-5.6.100-47101p-32\"\n                fi\n            elif grep -q 'XenServer release 6.0.0-50762p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 6.0.0-50762p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-6.0.0-50762p-32\"\n                fi            \n            elif grep -q 'XenServer release 6.0.2-53456p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 6.0.2-53456p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-6.0.2-53456p-32\"\n                fi            \n            elif grep -q 'XenServer release 6.1.0-59235p (xenenterprise)' /etc/redhat-release ||\n                grep -q 'XenServer SDK release 6.1.0-59235p (xenenterprise)' /etc/redhat-release ; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"CITRIX-XEN-6.1.0-59235p-32\"\n                fi\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && ! grep -q PATCHLEVEL /etc/SuSE-release ; then\t\n            # This one is for SLES10 or OpenSuSE10 series\n            if grep -q \"SUSE LINUX 10.0\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"OPENSUSE10-32\"\n                else\n                    OS=\"OPENSUSE10-64\"\n                fi\n            elif grep -q \"SUSE Linux Enterprise Server 10\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES10-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES10-64\"\n                fi\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 10\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 1' /etc/SuSE-release; then\n            if uname -a | grep -q i[0-9]86; then\n                OS=\"SLES10-SP1-32\"\n            elif uname -a | grep -q x86_64; then\n                OS=\"SLES10-SP1-64\"\n            fi\n        \n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 10\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 2' /etc/SuSE-release; then\n            if uname -a | grep -q i[0-9]86; then\n                OS=\"SLES10-SP2-32\"\n            elif uname -a | grep -q x86_64; then\n                OS=\"SLES10-SP2-64\"\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 10\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then\n            if uname -a | grep -q i[0-9]86; then\n                OS=\"SLES10-SP3-32\"\n            elif uname -a | grep -q x86_64; then\n                OS=\"SLES10-SP3-64\"\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 10\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then\n            if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES10-SP4-32\"\n            elif uname -a | grep -q x86_64; then\n                    OS=\"SLES10-SP4-64\"\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 10' /etc/SuSE-release && \\\n            grep -q 'PATCHLEVEL = 1' /etc/SuSE-release ; then\n            # This one is for SLES10 SP1 or OpenSuSE10 SP1 series\n            if grep -q \"SUSE LINUX 10.0\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"OPENSUSE10-SP1-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"OPENSUSE10-SP1-64\"\n                fi\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 11' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 0' /etc/SuSE-release; then\n            # This one is for SLES11 Base\n            if grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES11-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES11-64\"\n                fi            \n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 11' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 1' /etc/SuSE-release; then\n            # This one is for SLES11 Base with SP1\n            if grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES11-SP1-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES11-SP1-64\"\n                fi\n            fi\n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 11' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 2' /etc/SuSE-release; then\n            # This one is for SLES11 Base with SP2\n            if grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES11-SP2-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES11-SP2-64\"\n                fi\n            fi    \n        elif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 11' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then\n            # This one is for SLES11 Base with SP2\n            if grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES11-SP3-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES11-SP3-64\"\n                fi\n            fi\n\t\telif [ -f /etc/SuSE-release ] && grep -q 'VERSION = 11' /etc/SuSE-release && grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release && grep -q 'PATCHLEVEL = 4' /etc/SuSE-release; then\n            if grep -q \"SUSE Linux Enterprise Server 11\" /etc/SuSE-release; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"SLES11-SP4-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"SLES11-SP4-64\"\n                fi\n            fi\n        elif [ -f /etc/SuSE-release ]; then \n            # This one is for SLES9 with SP3\n            if grep -q 'VERSION = 9' /etc/SuSE-release; then\n                if grep -q 'PATCHLEVEL = 3' /etc/SuSE-release; then\n                    if uname -a | grep -q i[0-9]86; then\n                        OS=\"SLES9-SP3-32\"\n                    elif uname -a | grep -q x86_64; then\n                        OS=\"SLES9-SP3-64\"\n                    fi\n                fi\n            fi\n        elif [ -f /etc/lsb-release ] ; then\n            if grep -q 'Ubuntu 8.04.2' /etc/lsb-release || \n                grep -q 'Ubuntu 8.04.3' /etc/lsb-release ; then\n                if uname -a | grep -q x86_64; then\n                    OS=\"UBUNTU8-64\"\n                fi\n            elif grep -q 'Ubuntu 10.04.4 LTS' /etc/lsb-release ; then\n                if uname -a | grep -q x86_64; then\n                    OS=\"UBUNTU-10.04.4-64\"\n                fi\n\t    elif grep -q 'Ubuntu 12.04.4 LTS' /etc/lsb-release ; then\n                if uname -a | grep -q x86_64; then\n                    OS=\"UBUNTU-12.04.4-64\"\n                fi\n            fi\n        elif [ -f /etc/debian_version ]; then\n            if grep -q '4.0' /etc/debian_version; then\n                if uname -a | grep -q i[0-9]86; then\n                    OS=\"DEBIAN-ETCH-32\"\n                elif uname -a | grep -q x86_64; then\n                    OS=\"DEBIAN-ETCH-64\"\n                fi\n            fi    \n            if grep -q '6.0.1' /etc/debian_version; then\n                if uname -a | grep -q x86_64; then\n                    OS=\"DEBIAN6U1-64\"\n                fi\n            fi\n        fi\n    ;;\n\n HP-UX)\n        # Itanium is identified by 'ia64' in the output of 'uname -a'\n        if [ `uname -r` = \"B.11.11\" ] && [ `uname -m` != \"ia64\" ]; then\n            OS=\"HP-UX-PA-RISC\"\n        elif [ `uname -r` = \"B.11.23\" ] && [ `uname -m` = \"ia64\" ]; then\n            OS=\"HP-UX-Itanium-11iv2\"\n        elif [ `uname -r` = \"B.11.31\" ] && [ `uname -m` = \"ia64\" ]; then\n            OS=\"HP-UX-Itanium-11iv3\"\n        fi\n    ;;\n\n AIX)\n        case `uname -v` in\n            5)\n                if [ `uname -r` = \"3\" ]; then\n                    case `uname -p` in\n                        powerpc*)\n                            if [ `getconf KERNEL_BITMODE` = \"64\" ]; then\n                                OS=\"AIX53\"\n                            fi\n                        ;;\n                    esac\n                fi\n            ;;\n            6)\n                if [ `uname -r` = \"1\" ] ; then\n                    case `uname -p` in\n                        powerpc*)\n                            if [ `getconf KERNEL_BITMODE` = \"64\" ]; then\n                                OS=\"AIX61\"\n                            fi\n                        ;;\n                    esac\n                fi\n            ;;\n            7)\n                if [ `uname -r` = \"1\" ] ; then\n                    case `uname -p` in\n                        powerpc*)\n                            if [ `getconf KERNEL_BITMODE` = \"64\" ]; then\n                                    OS=\"AIX71\"\n                            fi\n                        ;;\n                    esac\n                fi\n            ;;\n        esac\n    ;;\n\n SunOS)\n        if [ `uname -r` = \"5.8\" ]; then\n            case `uname -p` in\n                sparc*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"Solaris-5-8-Sparc\"\n                    fi\n                ;;\n            esac        \n        elif [ `uname -r` = \"5.9\" ]; then\n            case `uname -p` in\n                sparc*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"Solaris-5-9-Sparc\"\n                    fi\n                ;;\n            esac    \n        elif [ `uname -r` = \"5.10\" ]; then\n            case `uname -p` in\n                i386|x86*)\n                    if [ `isainfo -b` = \"64\" ]; then\t\t  \n                        OS=\"Solaris-5-10-x86-64\"\n                    fi\n                ;;\n                sparc*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"Solaris-5-10-Sparc\"\n                    fi\n                ;;\n            esac\n        elif [ `uname -r` = \"5.11\" ] && grep 'Oracle Solaris' /etc/release >/dev/null ; then\n            case `uname -p` in\n                i386|x86*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"Solaris-5-11-x86-64\"\n                    fi\n                ;;\n                sparc*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"Solaris-5-11-Sparc\"\n                    fi\n                ;;\n            esac\n        elif [ `uname -r` = \"5.11\" ] && grep 'OpenIndiana Development oi_151.1.7 X86' /etc/release >/dev/null ; then\n            case `uname -p` in\n                i386|x86*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"OpenIndiana-151a7-x86-64\"\n                    fi\n                ;;\n            esac\n        elif [ `uname -r` = \"5.11\" ] && grep 'OpenSolaris' /etc/release >/dev/null ; then\n            case `uname -p` in\n                i386|x86*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"OpenSolaris-5-11-x86-64\"\n                    fi\n                ;;\n                sparc*)\n                    if [ `isainfo -b` = \"64\" ]; then\n                        OS=\"OpenSolaris-5-11-Sparc\"\n                    fi\n                ;;\n            esac\n        fi\n    ;;\nesac\n\nif [ $# -gt 0 ]\nthen\n    echo $OS\nfi\n\n", "num_lines": 387}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Usage: OS_details_target.sh <root-path> [--formated-output]\n#\n# Formated-output will display below details:\n# os=<detected-os-string>\n# release-file=<release-string-file-path>\n#\n# Default output will display only detected os string.\n# <os>\n#\n\n# 1st argument: root path.\nmntpath=$1\n\n# 2nd argument: formated-output\nformated_output=\"no\"\nos_release_file=\"\"\nif [ \"$2\" = \"--formated-output\" ]; then\n\tformated_output=\"yes\"\nfi\n\nif [ -f $mntpath/etc/enterprise-release ] && [ -f $mntpath/etc/redhat-release ] ; then\n\tif grep -q 'Enterprise Linux Enterprise Linux Server release 5.*' $mntpath/etc/enterprise-release; then\n\t\tOS=\"OL5-64\"\n\tfi\n\tos_release_file=$mntpath/etc/enterprise-release\nelif [ -f $mntpath/etc/oracle-release ] && [ -f $mntpath/etc/redhat-release ] ; then\n\tif grep -q 'Oracle Linux Server release 6.*' $mntpath/etc/oracle-release ; then\n\t\tOS=\"OL6-64\"\n\telif grep -q 'Oracle Linux Server release 7.*' $mntpath/etc/oracle-release ; then\n\t\tOS=\"OL7-64\"\n\telif grep -q 'Oracle Linux Server release 8.*' $mntpath/etc/oracle-release ; then\n\t\tOS=\"OL8-64\"\n    elif grep -q 'Oracle Linux Server release 9.*' $mntpath/etc/oracle-release ; then\n        OS=\"OL9-64\"\n\tfi\n\tos_release_file=$mntpath/etc/oracle-release\nelif [ -f $mntpath/etc/redhat-release ]; then\n\tif grep -q 'Red Hat Enterprise Linux Server release 5.*' $mntpath/etc/redhat-release || \\\n\t   grep -q 'CentOS release 5.*' $mntpath/etc/redhat-release; then\n\t\t\tOS=\"RHEL5-64\"\n\telif grep -q 'Red Hat Enterprise Linux Server release 6.*' $mntpath/etc/redhat-release || \\\n\t\t grep -q 'Red Hat Enterprise Linux Workstation release 6.*' $mntpath/etc/redhat-release || \\\n\t\t grep -q 'CentOS Linux release 6.*' $mntpath/etc/redhat-release || \\\n\t\t grep -q 'CentOS release 6.*' $mntpath/etc/redhat-release; then\n\t\t\tOS=\"RHEL6-64\"\n\telif grep -q 'Red Hat Enterprise Linux Server release 7.*' $mntpath/etc/redhat-release ||\n\t\t grep -q 'Red Hat Enterprise Linux Workstation release 7.*' $mntpath/etc/redhat-release; then\n\t\t\tOS=\"RHEL7-64\"\n\telif grep -q 'CentOS Linux release 7.*' $mntpath/etc/redhat-release; then\n\t\t\tOS=\"CENTOS7-64\"\n\telif grep -q 'Red Hat Enterprise Linux release 8.*' $mntpath/etc/redhat-release; then\n\t\t\tOS=\"RHEL8-64\"\n\telif grep -q 'Red Hat Enterprise Linux release 9.*' $mntpath/etc/redhat-release; then\n            OS=\"RHEL9-64\"\n\telif grep -q 'CentOS Linux release 8.*' $mntpath/etc/redhat-release ||\n         grep -q 'CentOS Stream release 8.*' $mntpath/etc/redhat-release; then\n           OS=\"CENTOS8-64\"\n\telif grep -q 'CentOS Linux release 9.*' $mntpath/etc/redhat-release ||\n         grep -q 'CentOS Stream release 9.*' $mntpath/etc/redhat-release; then\n           OS=\"CENTOS9-64\"\n\tfi\n\tos_release_file=$mntpath/etc/redhat-release\nelif ( [ -f $mntpath/etc/SuSE-release ] && ( grep -q 'VERSION = 11' $mntpath/etc/SuSE-release || grep -q 'VERSION = 12' $mntpath/etc/SuSE-release ) ) ; then\n\tif grep -q 'VERSION = 11' $mntpath/etc/SuSE-release && grep -q 'PATCHLEVEL = 3' $mntpath/etc/SuSE-release; then\n\t\tOS=\"SLES11-SP3-64\"\n\telif grep -q 'VERSION = 11' $mntpath/etc/SuSE-release && grep -q 'PATCHLEVEL = 4' $mntpath/etc/SuSE-release; then\n\t\tOS=\"SLES11-SP4-64\"\n\tfi\n\tif grep -q 'VERSION = 12' $mntpath/etc/SuSE-release; then\n\t\tOS=\"SLES12-64\"\n\tfi\n\tos_release_file=$mntpath/etc/SuSE-release\nelif [ -f $mntpath/etc/os-release ] && grep -q 'SLES' $mntpath/etc/os-release; then\n\tif grep -q 'VERSION=\"12' $mntpath/etc/os-release; then\n\t\tOS=\"SLES12-64\"\n\telif grep -q 'VERSION=\"15' $mntpath/etc/os-release; then\n\t\tOS=\"SLES15-64\"\n\tfi\n\tos_release_file=$mntpath/etc/os-release\nelif [ -f $mntpath/etc/lsb-release ]; then\n\tif grep -q 'Ubuntu 12.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU12-64\"\n\telif grep -q 'Ubuntu 14.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU14-64\"\n\telif grep -q 'Ubuntu 16.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU16-64\"\n\telif grep -q 'Ubuntu 18.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU18-64\"\n\telif grep -q 'Ubuntu 19.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU19-64\"\n\telif grep -q 'Ubuntu 20.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU20-64\"\n\telif grep -q 'Ubuntu 21.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU21-64\"\n\telif grep -q 'Ubuntu 22.*' $mntpath/etc/lsb-release ; then\n\t\tOS=\"UBUNTU22-64\"\n\tfi\n\tos_release_file=$mntpath/etc/lsb-release\nelif [ -f $mntpath/etc/debian_version ]; then\n\tif grep -q '^7.*' $mntpath/etc/debian_version; then\n        OS=\"DEBIAN7-64\"\n    elif grep -q '^8.*' $mntpath/etc/debian_version; then\n        OS=\"DEBIAN8-64\"\n    elif grep -q '^9.*' $mntpath/etc/debian_version; then\n        OS=\"DEBIAN9-64\"\n    elif grep -q '^10.*' $mntpath/etc/debian_version; then\n        OS=\"DEBIAN10-64\"\n    elif grep -q '^11.*' $mntpath/etc/debian_version; then\n        OS=\"DEBIAN11-64\"\n\telif grep -q '^kali-rolling*' $mntpath/etc/debian_version; then\n\t    OS=\"KALI-ROLLING-64\"\n    fi\n\tos_release_file=$mntpath/etc/debian_version\nfi\n\nif [ $# -gt 0 ]\nthen\n\tif [ \"$formated_output\" = \"yes\" ]; then\n\t\techo \"os=$OS\"\n\t\techo \"release-file=$os_release_file\"\n\telse\n\techo $OS\n\tfi\nfi\n", "num_lines": 127}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# root fs mountpoint\nexport mntpath=\"\"\n\nexport working_dir=\"\"\nexport hydration_config_settings=\"\"\n\nexport src_vx_dir=\"\"\n\nexport os_name=\"\"\nexport _firmware_type=\"\"\nexport _grub2_efi_path=\"\"\n\n\nexport RPM=/bin/rpm\nexport COPY=/bin/cp\nexport REMOVE=/bin/rm\nexport MKDIR=/bin/mkdir\n\n_SUCCESS_=0\n_FAILED_=1\n_INMAGE_ORG_=\"-INMAGE-ORG\"\n_INMAGE_MOD_=\"-INMAGE-MOD\"\n_ASR_INSTALLGA_=\"asr-installga\"\n\nfunction PrintDataTime\n{\n    echo \"$1: $(date +\"%a %b %d %Y %T\")\"\n}\n\nfunction CopyFile\n{\n    _source_=$1\n    _target_=$2\n\n    echo \"Copying file \\\"$_source_\\\" to \\\"$_target_\\\".\"\n    /bin/cp -f $_source_ $_target_\n    if [ 0 -ne $? ]; then\n        return $?\n    fi\n    return $_SUCCESS_\n}\n\nunset telemetry_data\n#@1 - Telemetry Data\nfunction add_telemetry_data\n{\n    if [[ -z $telemetrydata ]]; then\n        telemetry_data=\"$1\"\n    else\n        telemetry_data=\"$telemetry_data*#*$1\"\n    fi\n}\n\nfunction MoveFile\n{\n    _source_=$1\n    _target_=$2\n\n    echo \"Moving file \\\"$_source_\\\" to \\\"$_target_\\\".\"\n    /bin/mv -f $_source_ $_target_\n    if [ 0 -ne $? ]; then\n        return $?\n    fi\n    return $_SUCCESS_\n}\n\nfunction BackupFile\n{\n    _source_=$1\n    _target_=\"$1$_INMAGE_ORG_\"\n    \n    if [ -f \"$1\" ]; then\n        CopyFile $_source_ $_target_\n        if [ 0 -ne $? ]; then\n            echo \"Copy error. Could not backup file $1.\"\n            return $_FAILED_\n        else\n            echo \"File $1 backup successful.\"\n        fi\n    else\n        echo \"File $1 does not exist. Nothing to backup.\"\n    fi\n    \n    return $_SUCCESS_\n}\n\n# Recursively copy the folder and contents\nfunction CopyDirectory\n{\n    if [ -d \"$1\" ]; then\n        /bin/cp -r $1 $2\n    else\n        echo \"Folder $1 is absent. Copy failed.\"\n    fi\n    return $_SUCCESS_\n}\n\nfunction AddOrUpdateConfigValue\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n    _setting_value_=\"$3\"\n\n    if grep -q \"^$_setting_name_[[:space:]]*=.*\" \"$_config_file_\" ; then\n        # Line starts with setting key\n        sed -i --follow-symlinks \"s/\\(^$_setting_name_[[:space:]]*=[[:space:]]*[\\\"]\\?\\)\\(.*[\\\"]\\?\\)/\\1$_setting_value_ \\2/\" \"$_config_file_\"\n    elif grep -q \"^[[:space:]][[:space:]]*$_setting_name_[[:space:]]*=.*\" \"$_config_file_\" ; then\n        # Line starts with space(s) and then setting key\n        sed -i --follow-symlinks \"s/\\(^[[:space:]][[:space:]]*$_setting_name_[[:space:]]*=[[:space:]]*[\\\"]\\?\\)\\(.*[\\\"]\\?\\)/\\1$_setting_value_ \\2/\" \"$_config_file_\"\n    else\n        # Setting key not found, adding the setting key=value\n        echo \"$_setting_name_=\\\"$_setting_value_\\\"\" >> \"$_config_file_\"\n    fi\n}\n\nfunction UpdateConfigValue\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n    _setting_value_=\"$3\"\n\n    if grep -q \"^$2=$3\" $1 ; then\n        echo \"$2=$3 config value is already in place.\"\n    elif grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"s/\\(^$2=\\)\\(.*\\?\\)/\\1$3/\" $1\n    else\n        echo \"$2 setting not found, adding $2=$3\"\n        echo \"$2=$3\" >> $1\n    fi\n}\n\nfunction UpdateConfigValueIfExists\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n    _setting_value_=\"$3\"\n\n    if grep -q \"^$2=$3\" $1 ; then\n        echo \"$2=$3 config value is already in place.\"\n    elif grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"s/\\(^$2=\\)\\(.*\\?\\)/\\1$3/\" $1\n    else\n        echo \"$2 setting not found, nothing to update.\"\n    fi\n}\n\nfunction RemoveConfig\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n\n    if grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"/^$2=/d\" $1\n    else\n        echo \"$2 config setting not found, nothing to remove.\"\n    fi\n}\n\nfunction Usage\n{\n    echo \"post-rec-script.sh <src-root-mnt-path> <working-dir>\"\n}\n\n#This handles change requirements in lvm.conf file in initrd image.\n#input : initrd file name.\n#Output : Either SUCCESS or FAILED.\nfunction CheckLvmConfFile\n{\n        _retCode_=$_SUCCESS_\n\n        #filter=[ \"a|^/dev/cciss/c0d0$|\", \"a|^/dev/mapper/*|\", \"r/.*/\" ]\n        #need to split to get initrd file Name.\n        initrd_image_absolutepath=$1\n        initrd_image=`echo $initrd_image_absolutepath | sed -e \"s:[/].*[/]::\"`\n        initrd_image=`echo $initrd_image | sed -e \"s:/::\"`\n        out_initrd_image=\"$initrd_image.out\"\n        DATE_TIME_SUFFIX=`date +%d`_`date +%b`_`date +%Y`_`date +%H`_`date +%M`_`date +%S`\n        initrd_temp_dir=\"/tmp/temp_$DATE_TIME_SUFFIX\"\n        boot_temp_dir=$initrd_temp_dir\n        /bin/mkdir $initrd_temp_dir\n\n        (cd $initrd_temp_dir ; gunzip -9 < $initrd_image_absolutepath > ../$initrd_image.unzipped ; cpio -id < ../$initrd_image.unzipped)\n        cd $initrd_temp_dir\n        _lvm_conf_file_=\"$initrd_temp_dir/etc/lvm/lvm.conf\"\n        if [ ! -f \"$_lvm_conf_file_\" ]; then\n                #mean to say lvm.conf does not exist no need to change any thing...\n                echo \"initrd : $initrd_image, does not contain lvm.conf file.\"\n        else\n                /bin/cp -f \"$_lvm_conf_file_\" \"$_lvm_conf_file_.old\"\n                #cp -f \"${initrd_temp_dir}/init\" \"${_LOGS_}\"\n                #now we have to make in place replacement in lvm.conf file.\n                #First we need to get the Line and then\n                #check if all block devices are allowed?\n                #if not, then check whether sd pattern is already allowed.\n                #if not, then add sd* pattern to list of allowed block devices.\n                _line_=`cat \"$_lvm_conf_file_\" | grep -P \"^(\\s*)filter(\\s*)=(\\s*).*\"`\n                echo $_line_\n                if [ ! -z \"$_line_\" ]; then\n                    _line_number_=`cat \"$_lvm_conf_file_\" | grep -P -n \"^(\\s*)filter(\\s*)=(\\s*).*\" | awk -F\":\" '{print $1}'`\n                    echo \"Updating filter entry in $_lvm_conf_file_ file at line: $_line_number_\"\n                    sed -i \"$_line_number_ c\\filter=\\\"a\\/.*\\/\\\"\" $_lvm_conf_file_\n                else\n                    echo \"filter entry not found. Nothing to update in $_lvm_conf_file_ file\"\n                fi\n\n                #cp -rf \"etc/\" \"${_LOGS_}\"\n                #now again we have zip the file and then replace image file.\n                (cd $initrd_temp_dir/ ; find . | cpio --create --format='newc' > $boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX)\n                (cd $initrd_temp_dir/ ; gzip -9 < $boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX > $boot_temp_dir/../$out_initrd_image)\n                mv -f \"$boot_temp_dir/../$out_initrd_image\" \"$initrd_image_absolutepath\"\n                rm -f \"$boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX\"\n        fi\n\n        rm -f \"/$boot_temp_dir/../$initrd_image.unzipped\"\n        rm -rf \"$initrd_temp_dir\"\n\n\n        return $_retCode_\n}\n\nfunction UpdateVMRepositories()\n{\n    case $src_distro in\n        CENTOS6*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/CentOS-Base.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS6-Base.repo\" \"$sources_list_file\"\n        ;;\n        CENTOS7*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/CentOS-Base.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS7-Base.repo\" \"$sources_list_file\"\n        ;;\n        CENTOS8*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/CentOS-Base.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS7-Base.repo\" \"$sources_list_file\"\n        ;;\n        OL6*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/public-yum-ol6.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol6.repo\" \"$sources_list_file\"\n        ;;\n        OL7*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/public-yum-ol7.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol6.repo\" \"$sources_list_file\"\n        ;;\n        OL8*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/public-yum-ol8.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol8.repo\" \"$sources_list_file\"\n        ;;\n         OL9*)\n            sources_list_file=\"$mntpath/etc/yum.repos.d/public-yum-ol9.repo\"\n            BackupFile $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol9.repo\" \"$sources_list_file\"\n        ;;\n\n        UBUNTU*)\n            sources_list_file=\"$mntpath/etc/apt/sources.list\"\n            BackupFile \"$sources_list_file\"\n            sed -i 's/http:\\/\\/archive\\.ubuntu\\.com\\/ubuntu\\//http:\\/\\/azure\\.archive\\.ubuntu\\.com\\/ubuntu\\//g' \"$sources_list_file\"\n            sed -i 's/http:\\/\\/[a-z][a-z]\\.archive\\.ubuntu\\.com\\/ubuntu\\//http:\\/\\/azure\\.archive\\.ubuntu\\.com\\/ubuntu\\//g' \"$sources_list_file\"\n        ;;\n    esac\n}\n\n# $1: Complete path of zip file.\n# $2: Target directory for extraction of zip file.\nfunction Extract_ZipFile_Using_Python\n{\n    echo \"Extracting zip from $1 to $2\"\n\n    # Create python script to extract the zip file.\n    local unzip_py=\"$mntpath/${base_linuxga_path}/unzip.py\"\n    echo '#!/usr/bin/python' > $unzip_py\n    echo 'import sys' >> $unzip_py\n    echo 'from zipfile import ZipFile' >> $unzip_py\n    echo 'from zipfile import BadZipfile' >> $unzip_py\n    echo 'try:' >> $unzip_py\n    echo \"    zip_file = \\\"$1\\\"\" >> $unzip_py\n    echo \"    dest_dir = \\\"$2\\\"\" >> $unzip_py\n    echo '    pzf = ZipFile(zip_file)' >> $unzip_py\n    echo '    pzf.extractall(dest_dir)' >> $unzip_py\n    echo 'except BadZipfile:' >> $unzip_py\n    echo '    print(\"Error: Bad zip file format.\")' >> $unzip_py\n    echo '    sys.exit(1)' >> $unzip_py\n    echo 'else:' >> $unzip_py\n    echo '    print(\"Successfully extracted the zip file.\")' >> $unzip_py\n    echo '    sys.exit(0)' >> $unzip_py\n    \n    # Run python script using python3 present on hydration VM.\n    python3 $unzip_py >> \"$mntpath/$base_linuxga_path/ASRLinuxGA.log\" 2>&1\n\n    return $?\n}\n\nunset pythonver\ncheck_valid_python_version()\n{\n    # Check for Major Version 3 for python.\n    chroot $mntpath python3 --version\n    if [[ $? -ne 0 ]] ; then\n        echo \"Python3 is not installed on the target VM.\"\n    else\n        pythonver=3\n        return\n    fi\n\n    # Check for Major version 2 and Minor Version >= 6 for Python.\n    chroot $mntpath python --version\n    if [[ $? -ne 0 ]] ; then\n        echo \"Python is not installed on the target VM.\\n\"\n        pythonver=1\n        return\n    else\n        vermajor=$(chroot $mntpath python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(major)\")\n        verminor=$(chroot $mntpath python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(minor)\")\n        echo \"Major Version: $vermajor Minor Version: $verminor\"\n        if [ $vermajor -eq 2 ] && [ $verminor -ge 6 ]; then\n            pythonver=2\n\t\t\treturn\n        else\n            echo \"Failed to install Linux Guest Agent on the VM.\\n\"\n            echo \"Install python version 2.6+ to install Guest Agent.\\n\"\n            pythonver=1\n            return\n        fi\n    fi\n\n    pythonver=1\n}\n\nfunction test_setuptools_prereq\n{\n    setup_uuid=$(uuidgen)\n    setuptools_file_path=\"$mntpath/$base_linuxga_path/setuptools-test-$setup_uuid.py\"\n\n    echo \"import sys\"                   >> $setuptools_file_path\n    echo \"try:\"                         >> $setuptools_file_path\n    echo \"        import setuptools\"    >> $setuptools_file_path\n    echo \"except ImportError:\"          >> $setuptools_file_path\n    echo \"        print(\\\"ABSENT\\\")\"    >> $setuptools_file_path\n    echo \"else:\"                        >> $setuptools_file_path\n    echo \"        print(\\\"PRESENT\\\")\"   >> $setuptools_file_path\n\n    setuptools_output=\"\"\n    if [[ \"$1\" == \"python3\" ]]; then\n        setuptools_output=$(chroot $mntpath python3 \"/$base_linuxga_path/setuptools-test-$setup_uuid.py\")\n    else\n        setuptools_output=$(chroot $mntpath python \"/$base_linuxga_path/setuptools-test-$setup_uuid.py\")\n    fi\n\n\tsetup_tools_package_path=\"/usr/local/AzureRecovery/setuptools-33.1.1.zip\"\n\n    if [[ \"$setuptools_output\" == \"ABSENT\" ]]; then\n        echo \"setuptools is absent on the VM. Trying manual pre-boot installation.\"\n\n        Extract_ZipFile_Using_Python $setup_tools_package_path $mntpath/$base_linuxga_path/\n        add_telemetry_data \"no-setuptools\"\n    else\n        echo \"setuptools is present on the VM.\"\n    fi\n\n    rm -f $setuptools_file_path\n}\n\nfunction validate_guestagent_prereqs\n{\n    check_valid_python_version\n\n    if [[ $pythonver -eq 1 ]]; then\n        echo \"Python not installed/ incompatible with linux guest agent requirements.\"\n        add_telemetry_data \"no-python\"\n    elif [[ $$pythonver -eq 3 ]]; then\n        echo \"Python3 present on the source VM.\"\n        add_telemetry_data \"python2\"\n        test_setuptools_prereq \"python3\"\n    elif [[ $$pythonver -eq 2 ]]; then\n        echo \"Python 2.6+ installed on the source VM.\"\n        add_telemetry_data \"python3\"\n        test_setuptools_prereq \"python\"\n    else\n        echo \"Unsupported Python version\"\n        add_telemetry_data \"no-python\"\n    fi\n\n    chroot $mntpath systemctl\n\n    if [[ $? -eq 127 ]]; then\n        echo \"systemctl is not installed on the source VM\"\n        add_telemetry_data \"systemctl\"\n    fi\n}\n\n#This handles all requirements to make a modification in initrd file..\n#input : either it can be initrd file or virtual initrd file.\n#return SUCCESS or FAILURE.\nfunction ModifyVirtualInitrdFile\n{\n        _retCode_=$_SUCCESS_\n        _initrd_filename_=$1\n        echo \"Checking \\\"$_initrd_filename_\\\" for modifications if required any.\"\n\n        CheckLvmConfFile $_initrd_filename_\n        if [ 0 -ne $? ]; then\n                echo \"ERROR :: Failed to modify lvm.conf file in initrd image : $_initrd_filename_.\"\n                _retCode_=$_FAILED_\n        fi\n\n        return $_retCode_\n}\n#THIS FUNCTION RENAMES INITRD OR INITRAMFS FILES.\nfunction Rename_INITRD_RAMFS_Files\n{\n        _retCode_=$_SUCCESS_\n        #FIRST LIST ALL PATTERNS WHICH ARE IN THE FORM OF \"-InMage-Virtual\"\n        _boot_path_=$1\n        _virtual_initrd_ramfs_files_=`find $_boot_path_ -name \"*-InMage-Virtual\"`\n        echo \"initrd files = $_virtual_initrd_ramfs_files_\"\n        for _virtual_initrd_ramfs_file_ in ${_virtual_initrd_ramfs_files_}\n        do\n                #here we need to check if we have to modify lvm.conf file in virtual Initrd image.\n                ModifyVirtualInitrdFile $_virtual_initrd_ramfs_file_\n                if [ 0 -ne $? ]; then\n                        echo \"Error :: Failed to modify virtual initrd image file for any changes.\"\n                        _retCode_=$_FAILED_\n                fi\n\n                _initrd_ramfs_file_=`echo $_virtual_initrd_ramfs_file_ | sed \"s/-InMage-Virtual$//g\"`\n                echo \"Initrd file = $_initrd_ramfs_file_\"\n                #TAKE COPY OF THIS FILE\n                #CHECK IF THE ORIG FILE ALREADY EXISTS?\n                if [ -f \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\" ]; then\n                    /bin/mv -f  \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\" \"$_initrd_ramfs_file_\"\n                fi\n\n                $COPY -f  \"$_initrd_ramfs_file_\" \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\"\n                $COPY -f  \"$_virtual_initrd_ramfs_file_\" \"$_initrd_ramfs_file_\"\n        done\n        \n        return $_retCode_\n}\n\nfunction Enable_installga_chkconfig\n{\n    echo \"Adding guest agent installation service inside /etc/init.d\"\n    local asr_installga_exfile_path=\"$mntpath/etc/init.d/${_ASR_INSTALLGA_}\"\n    echo \"#!/bin/bash\n# This is for RHEL systems\n# processname: ${_ASR_INSTALLGA_}\n# chkconfig: 2345 90 90\n# description: Azure migrate startup script to configure networks\n\n### BEGIN INIT INFO\n# Provides: ${_ASR_INSTALLGA_}\n# Required-Start: \\$local_fs\n# Required-Stop: \\$local_fs\n# X-Start-Before: \\$network\n# X-Stop-After: \\$network\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Description: Azure migrate startup script to configure networks\n### END INIT INFO \" > $asr_installga_exfile_path\n\n    echo 'case \"$1\" in' >> $asr_installga_exfile_path\n    echo \"start)\" >> $asr_installga_exfile_path\n    echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $src_distro \\\"$base_linuxga_path\\\" $setup_tool_install\" >> $asr_installga_exfile_path\n    echo \";;\" >> $asr_installga_exfile_path\n    echo \"*)\" >> $asr_installga_exfile_path\n    echo \";;\" >> $asr_installga_exfile_path\n    echo \"esac\" >> $asr_installga_exfile_path\n    echo \"\" >> $asr_installga_exfile_path\n    \n    # Execute permissions for the scripts\n    chmod +x $asr_installga_exfile_path\n\n    local _chkconfig_gastartup_file=\"/etc/init.d/${_ASR_INSTALLGA_}\"\n    if [[ -h \"${chroot_path}$_chkconfig_gastartup_file\" ]]; then\n        echo \"Startup script is already configured!\"\n        return;\n    fi\n\n    chroot $mntpath ln -s $asr_installga_exfile_path $_chkconfig_gastartup_file\n    if [[ $? -ne 0 ]]; then\n        echo \"WARNING: Could not create start-up script.\"\n    fi\n    \n    local _config_startup_cmd=\"\"\n    if chroot $mntpath which chkconfig > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $mntpath chkconfig --add ${_ASR_INSTALLGA_}\"\n    elif chroot $mntpath which update-rc.d > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $mntpath update-rc.d ${_ASR_INSTALLGA_} defaults\"\n    else\n        echo \"WARNING: No tools found to configure start-up script.\"\n        add_telemetry_data \"startup\"\n        return 0\n    fi\n    \n    echo \"Adding startup script.\"\n    $_config_startup_cmd > /dev/null 2>&1\n    if [[ $? -ne 0 ]]; then\n        echo \"WARNING: Could not add start-up script.\"\n        add_telemetry_data \"startup\"\n    else\n        echo \"Successfully added startup script!\"\n    fi\n\n    return $?\n}\n\nfunction Enable_installga_Service\n{\n    # Startup script to install azure guest agent.\n    local asr_installga_exfile_path=\"usr/local/${_ASR_INSTALLGA_}/asr.installga\"\n\n    # Create a directory if it doesn't exist.\n    if [[ ! -d \"$mntpath/usr/local/${_ASR_INSTALLGA_}\" ]]; then\n        echo \"Creating a new directory /usr/local/${_ASR_INSTALLGA_}\"\n        mkdir \"$mntpath/usr/local/${_ASR_INSTALLGA_}\"\n    fi\n    \n    if [[ -f $mntpath/$asr_installga_exfile_path ]]; then\n        echo \"/usr/local/${_ASR_INSTALLGA_}/asr.installga exists. Deleting the file.\"\n        rm $mntpath/$asr_installga_exfile_path\n    fi\n\n    setup_tool_install=\"install_setup_tools_false\"\n    if [[ $telemetry_data == *\"no-setuptools\"* ]]; then\n        setup_tool_install=\"install_setup_tools_true\"\n    fi\n\n    # Write execution commands for asr.installga executable.\n    echo \"Creating asr.installga for execution during boot.\"\n\n    echo \"#!/bin/bash\" >> $mntpath/$asr_installga_exfile_path\n    echo \"#This file is generated for execution during boot\" >> $mntpath/$asr_installga_exfile_path\n    echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $os_name  \\\"$base_linuxga_path\\\" $setup_tool_install >> /$base_linuxga_path/ASRLinuxGA.log\"  >> $mntpath/$asr_installga_exfile_path\n    echo \"exit 0\" >> $mntpath/$asr_installga_exfile_path\n\n    # Add executable permissions.\n    chmod +x $mntpath/$asr_installga_exfile_path\n\n    local _systemd_config_file=\"$mntpath/lib/systemd/system/${_ASR_INSTALLGA_}.service\"\n    if [[ ! -d $mntpath/lib/systemd/system ]]; then\n        if [[ -d $mntpath/usr/lib/systemd/system ]]; then\n            _systemd_config_file=\"$mntpath/usr/lib/systemd/system/${_ASR_INSTALLGA_}.service\"\n        elif [[ -d $mntpath/etc/systemd/system ]]; then\n            _systemd_config_file=\"$mntpath/etc/systemd/system/${_ASR_INSTALLGA_}.service\"\n        fi\n    fi\n\n    # Delete the file if it already exists.\n    if [[ -f $_systemd_config_file ]]; then\n        echo \"$_systemd_config_file exists. Deleting the file.\"\n        rm $_systemd_config_file\n    fi\n\n    echo \"Creating systemd config file. $_systemd_config_file\"\n\n    echo \"[Unit]\" >> $_systemd_config_file\n    echo \"Description=Install Azure Linux Guest agent startup script by ASR\" >> $_systemd_config_file\n    echo \"ConditionPathExists=/$asr_installga_exfile_path\" >> $_systemd_config_file\n    echo \"\" >> $_systemd_config_file\n    echo \"[Service]\" >> $_systemd_config_file\n    echo \"Type=forking\" >> $_systemd_config_file\n    echo \"ExecStart=/$asr_installga_exfile_path start\" >> $_systemd_config_file\n    echo \"TimeoutSec=0\" >> $_systemd_config_file\n    echo \"StandardOutput=tty\" >> $_systemd_config_file\n    echo \"RemainAfterExit=yes\" >> $_systemd_config_file\n    echo \"SysVStartPriority=99\" >> $_systemd_config_file\n    echo \"\" >> $_systemd_config_file\n    echo \"[Install]\" >> $_systemd_config_file\n    echo \"WantedBy=multi-user.target\" >> $_systemd_config_file\n\n    chroot $mntpath systemctl enable \"${_ASR_INSTALLGA_}.service\"\n\n    # This part validates presence of Python & whether installga service has properly enabled.\n    echo \"Checking for linux installation prereqs within source vm.\"\n\n    gacheck=$(chroot $mntpath python3 --version)\n    echo \"Python 3 version. Absent if empty or fails: $gacheck\"\n\n    gacheck=$(chroot $mntpath python --version)\n    echo \"Python 2 version. Absent if empty or fails: $gacheck\"\n\n    gacheck=$(cat $_systemd_config_file)\n    echo \"systemd service file: $gacheck\"\n\n    gacheck=$(cat $mntpath/$asr_installga_exfile_path)\n    echo \"asr.installga: $gacheck\"\n}\n\nfunction enable_postlogin_installga\n{\n    target_profiled_file=\"$mntpath/etc/profile.d/ASRLinuxGAStartup.sh\"\n    \n    if [[ ! -d \"$mntpath/etc/profile.d\" ]]; then\n        echo \"/etc/profile.d directory doesn't exist\"\n    else\n        echo \"#!/bin/bash\" >> $target_profiled_file\n        echo \"echo \\\"This is Azure Site Recovery One-Time Guest Agent Installation Setup.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"The service quietly exits if WALinuxAgent is already installed.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"If guest agent installation failed at pre-boot step due to python/installation prereqs not fulfilled, \\\"\" >> $target_profiled_file\n        echo \"echo \\\"this service is triggered post login to install WALinuxAgent using VM's repository.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"The service may prompt you to login using elevated bash shell for installation to proceed.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"You can skip the installation, and can install manually, or retrigger the service by running\\\"\" >> $target_profiled_file\n        echo \"echo \\\"systemctl start asr-installga or service asr-installga start\\\"\" >> $target_profiled_file\n        echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $os_name  \\\"$base_linuxga_path\\\" $setup_tool_install\" >> $target_profiled_file\n        echo \"echo \\\"Installation process completed. Proceed with Login.\\\"\" >> $target_profiled_file\n        echo \"rm -f \\\"/etc/profile.d/ASRLinuxGAStartup.sh\\\"\" >> $target_profiled_file\n\n        echo \"/etc/profile.d post login startup file created.\"\n    fi    \n}\n\nunset base_linuxga_path\nfunction InstallLinuxGuestAgent\n{\n    ga_uuid=$(uuidgen)\n    base_linuxga_path=\"var/ASRLinuxGA-$ga_uuid\"\n\n    if [[ ! -d $mntpath/$base_linuxga_path ]]; then\n        echo \"Base linux guest agent packages directory doesn't exist'. Creating $mntpath/$base_linuxga_path\"\n        mkdir $mntpath/$base_linuxga_path\n    fi\n\n    validate_guestagent_prereqs\n\n    if [[ $telemetry_data != *\"systemctl\"* ]]; then\n        Enable_installga_Service\n    else\n        Enable_installga_chkconfig\n    fi\n\n    UpdateVMRepositories\n    enable_postlogin_installga\n\n    echo \"Hydration Being Performed on the VM. $(date)\" >> \"$mntpath/$base_linuxga_path/ASRLinuxGA.log\"\n\n    linuxgadir=\"/usr/local/AzureRecovery/WALinuxAgentASR/WALinuxAgent-master\"\n    targetgadir=\"$mntpath/$base_linuxga_path/WALinuxAgentASR/\"\n\n    if [[ ! -d \"$linuxgadir\" ]]; then\n        echo \"Folder containing Guest agent binaries is not present.\"\n        return 1;\n    fi\n\n    if [[ ! -d $targetgadir ]]; then\n        echo \"Target guest agent folder doesn't exist. Creating $targetgadir\"\n        mkdir $targetgadir\n    fi\n\n    CopyDirectory $linuxgadir $targetgadir\n    if [[ $? -ne 0 ]]; then\n        echo \"Could not copy LinuxGuestAgent installation directory to target location.\"\n        return 1;\n    fi\n\n    CopyFile \"/usr/local/AzureRecovery/InstallLinuxGuestAgent.sh\" \"$mntpath/$base_linuxga_path/InstallLinuxGuestAgent.sh\"\n    if [[ $? -ne 0 ]]; then\n        echo \"Could not copy LinuxGuestAgent installation file.\"\n        return 1;\n    fi\n\n    CopyFile \"/usr/local/AzureRecovery/PythonSetupPrereqs.py\" \"$mntpath/$base_linuxga_path/PythonSetupPrereqs.py\"\n    if [[ $? -ne 0 ]]; then\n        echo \"Could not copy python setup prereqs file.\"\n        # Don't fail.\n    fi\n\n    chmod +x $mntpath/$base_linuxga_path/*\n}\n\n# This function appends kernel entry in grub with numa=off console=ttyS0 earlyprintk=ttyS0 rootdelay=300\n# Remove rhgb quiet from grub configuration file\nfunction ModifyMenuListFile\n{\n        _grub_path_=\"$1/boot/grub\"\n        _menu_list_file_path_=\"$_grub_path_/menu.lst\"\n\n        if [[ \"$firmware_type\" = \"UEFI\" ]]; then\n            _grub_path_=\"$_grub2_efi_path\";\n            _menu_list_file_path_=\"$_grub_path_/grub.conf\"\n        fi\n        \n        # ensure file exists, it should be either symblink or regular file\n        if [ -h \"$_menu_list_file_path_\" ]; then\n            tmp_file=`ls -l \"${_menu_list_file_path_}\" | awk -F'->' '{ print $2 }'`\n            tmp_file=`echo $tmp_file | sed -e 's: ::g'`\n\n            if [[ \"$firmware_type\" = \"UEFI\" ]]; then\n               echo \"grub.conf sym link points to - ${tmp_file}\"\n                # Only RHEL6/CENTOS6 are supported for UEFI.\n                if [ -f \"$1/boot/efi/EFI/redhat/$tmp_file\" ]; then\n                    # menu.lst sym link points to grub file relative path.\n                    _menu_list_file_path_=\"$1/boot/efi/EFI/redhat/$tmp_file\"\n                elif [ -f \"$1/$tmp_file\" ]; then\n                    # menu.lst sym link points to grub file absolute path.\n                    _menu_list_file_path_=\"$_grub2_efi_path/$tmp_file\"\n                else\n                    echo \"ERROR :: Failed to find file ${_menu_list_file_path_}\"\n                    echo \"ERROR :: Could not modify grub file.\"\n                    return $_FAILED_\n                fi\n            else\n                echo \"menu.lst sym link points to - ${tmp_file}\"\n                        \n                if [ -f \"$1/boot/grub/$tmp_file\" ]; then\n                    # menu.lst sym link points to grub file relative path.\n                    _menu_list_file_path_=\"$1/boot/grub/$tmp_file\"\n                elif [ -f \"$1/$tmp_file\" ]; then\n                    # menu.lst sym link points to grub file absolute path.\n                    _menu_list_file_path_=\"$1/$tmp_file\"\n                else\n                    echo \"ERROR :: Failed to find file ${_menu_list_file_path_}\"\n                    echo \"ERROR :: Could not modify grub file.\"\n                    return $_FAILED_\n                fi\n            fi\n        elif [ ! -f \"$_menu_list_file_path_\" ]; then\n                echo \"ERROR :: Failed to find file \\\"menu.lst\\\" in path \\\"$_grub_path_\\\".\"\n                return $_FAILED_\n        fi\n\n        # backup the original file\n        _menu_list_file_orig_=\"${_menu_list_file_path_}${_INMAGE_ORG_}\"\n        if [ -f \"${_menu_list_file_orig_}\" ]; then\n                /bin/mv -f \"${_menu_list_file_orig_}\" \"$_menu_list_file_path_\"\n        fi\n\n        /bin/cp -f \"$_menu_list_file_path_\" \"${_menu_list_file_orig_}\"\n        sed -i --follow-symlinks \"s/ rhgb / /\" ${_menu_list_file_path_}\n        sed -i --follow-symlinks \"s/quiet/ /\" ${_menu_list_file_path_}\n        grep \"numa=off  console=ttyS0  earlyprintk=ttyS0  rootdelay=300 \" ${_menu_list_file_path_}\n        if [ $? -ne 0 ]; then\n                sed -i  --follow-symlinks  '/[\\t]*[ ]*kernel.*\\/.*root=/s/$/& numa=off  console=ttyS0  earlyprintk=ttyS0  rootdelay=300 /' ${_menu_list_file_path_}\n        fi\n\n        # Temporary workaround for sym link breakages\n        _menu_list_file_path_bak_=\"$_grub_path_/grub.conf\"\n        sed -i --follow-symlinks \"s/ rhgb / /\" ${_menu_list_file_path_bak_}\n        sed -i --follow-symlinks \"s/quiet/ /\" ${_menu_list_file_path_bak_}\n        grep \"numa=off  console=ttyS0  earlyprintk=ttyS0  rootdelay=300 \" ${_menu_list_file_path_bak_}\n        if [ $? -ne 0 ]; then\n                sed -i  --follow-symlinks  '/[\\t]*[ ]*kernel.*\\/.*root=/s/$/& numa=off  console=ttyS0  earlyprintk=ttyS0  rootdelay=300 /' ${_menu_list_file_path_bak_}\n        fi\n        return $_SUCCESS_\n}\n\nfunction ModifyGrubConfig_SLES\n{\n    _grub_conf_file_path=\"$mntpath/boot/grub2/grub.cfg\"\n    [[ \"$firmware_type\" = \"UEFI\" ]] && _grub_conf_file_path=\"$_grub2_efi_path/grub.cfg\"\n\n    # Backup /boot/grub2/grub.cfg file\n    BackupFile \"$_grub_conf_file_path\"\n    \n    # Backup the /etc/default/grub file\n    _grub_options_file_path=\"$mntpath/etc/default/grub\"\n    BackupFile \"$_grub_options_file_path\"\n    \n    # Edit \"/etc/default/grub\" file\n    _grub_config_options=\"$1\"   \n    if [[ -z \"$_grub_config_options\" ]] ; then\n        echo \"Default azure grub options: \"\n        _grub_config_options=\"console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n    fi\n\n    # Filter out the options need to add by excluding existing options\n    _required_grub_config_options=\"\"\n    for option in $_grub_config_options\n    do\n        if grep -q \"^GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\" ||\n           grep -q \"^[[:space:]][[:space:]]*GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\"\n        then\n            echo \"$option is already present. Skipping it...\"\n        else\n            _required_grub_config_options=\"$_required_grub_config_options $option\"\n        fi\n    done\n    \n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more changes to grub.\"\n    else\n        echo \"Required Grub options are: $_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (Before) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (Before) ###\"\n        \n        AddOrUpdateConfigValue \"$_grub_options_file_path\" \"GRUB_CMDLINE_LINUX\" \"$_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (After) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (After) ###\"\n    fi\n        \n    # Temporarily modify grub.cfg for first boot, as part of boot up script \"grub2-mkconfig\" will run\n    # and updates the grub.cfg again.\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more changes to grub.cfg.\"\n    else\n        # This command also inserts the options to recovery mode grub common line, and the grub.cfg will be re-build on first boot\n        # when boot-up script runs 'grub2-mkconfig' command.\n        sed -i --follow-symlinks \"s/^[[:space:]][[:space:]]*linux[[:space:]]\\/.* root=.*[[:space:]] .*/&$_required_grub_config_options /\" \"$_grub_conf_file_path\"\n    fi\n\n    return $_SUCCESS_\n}\n\nfunction ModifyGrubConfig_DEBIAN\n{\n    # Backup the grub & grub.cfg files\n    _grub_conf_file_path=\"$mntpath/boot/grub/grub.cfg\"\n    _grub_options_file_path=\"$mntpath/etc/default/grub\"\n\n    # Change the file path to /boot/efi/efi/debian folder for UEFI scenario.\n    [[ \"$firmware_type\" = \"UEFI\" ]] && _grub_conf_file_path=\"$_grub2_efi_path/grub.cfg\"\n\n    BackupFile \"$_grub_conf_file_path\"\n    BackupFile \"$_grub_options_file_path\"\n    # Edit \"/etc/default/grub\" file\n    #  GRUB_CMDLINE_LINUX=\"console=tty0 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 rootdelay=30\"\n    _grub_config_options=\"console=tty0 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 rootdelay=30\"\n    _required_grub_config_options=\"\"\n    # Filter out the options need to add by excluding existing options\n    for option in $_grub_config_options\n    do\n        if grep -q \"^GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\" ||\n           grep -q \"^[[:space:]][[:space:]]*GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\"\n        then\n            echo \"$option is already present. Skipping it...\"\n        else\n            _required_grub_config_options=\"$_required_grub_config_options $option\"\n        fi\n    done\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more chages to grub.\"\n    else\n        echo \"Required Grub options are: $_required_grub_config_options\"\n        echo \"### BEGIN: $_grub_options_file_path file (Before) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (Before) ###\"\n        AddOrUpdateConfigValue \"$_grub_options_file_path\" \"GRUB_CMDLINE_LINUX\" \"$_required_grub_config_options\"\n        echo \"### BEGIN: $_grub_options_file_path file (After) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (After) ###\"\n    fi\n    # Temporarily modify grub.cfg for first boot, as part of boot up script \"update-grub\" will run\n    # and updates the grub.cfg again.\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more changes to grub.cfg.\"\n    else\n        # This command also inserts the optoins to recovery mode grub common line, and the grub.cfg will be re-build on first boot\n        # when boot-up script runs 'update-grub' command.\n        sed -i --follow-symlinks \"s/^[[:space:]][[:space:]]*linux[[:space:]]\\/.* root=.*[[:space:]]ro.*/&$_required_grub_config_options /\" \"$_grub_conf_file_path\"\n    fi\n    return $_SUCCESS_\n}\n\nfunction ModifyGrubConfig_UBUNTU\n{\n    # Backup the grub & grub.cfg files\n    _grub_conf_file_path=\"$mntpath/boot/grub/grub.cfg\"\n    _grub_options_file_path=\"$mntpath/etc/default/grub\"\n    \n    BackupFile \"$_grub_conf_file_path\"\n    BackupFile \"$_grub_options_file_path\"\n    \n    # Edit \"/etc/default/grub\" file\n    #  GRUB_CMDLINE_LINUX_DEFAULT=\"console=tty1 console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n    _grub_config_options=\"console=ttyS0 console=tty1 earlyprintk=ttyS0 rootdelay=300\"\n    _required_grub_config_options=\"\"\n    \n    # Filter out the options need to add by excluding existing options\n    for option in $_grub_config_options\n    do\n        if grep -q \"^GRUB_CMDLINE_LINUX_DEFAULT[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\" ||\n           grep -q \"^[[:space:]][[:space:]]*GRUB_CMDLINE_LINUX_DEFAULT[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\"\n        then\n            echo \"$option is already present. Skipping it...\"\n        else\n            _required_grub_config_options=\"$_required_grub_config_options $option\"\n        fi\n    done\n    \n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more chages to grub.\"\n    else\n        echo \"Required Grub options are: $_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (Before) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (Before) ###\"\n        \n        AddOrUpdateConfigValue \"$_grub_options_file_path\" \"GRUB_CMDLINE_LINUX_DEFAULT\" \"$_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (After) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (After) ###\"\n    fi\n        \n    # Temporarily modify grub.cfg for first boot, as part of boot up script \"update-grub\" will run\n    # and updates the grub.cfg again.\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more chages to grub.cfg.\"\n    else\n        # This command also inserts the options to recovery mode grub command line, and the grub.cfg will be re-build on first boot\n        # when boot-up script runs 'update-grub' command.\n        sed -i --follow-symlinks \"s/^[[:space:]][[:space:]]*linux[[:space:]]\\/.* root=.*[[:space:]]ro.*/&$_required_grub_config_options /\" \"$_grub_conf_file_path\"\n    fi\n\n    return $_SUCCESS_\n}\n\nfunction ModifyGrubOptions\n{\n    # Backup /boot/grub2/grub.cfg file\n    _grub_options_file_path=\"$mntpath/etc/default/grub\"\n    BackupFile \"$_grub_options_file_path\"\n    \n    # Edit \"/etc/default/grub\" file\n    _grub_config_options=\"$1\"   \n    if [[ -z \"$_grub_config_options\" ]] ; then\n        echo \"Default azure grub options: \"\n        _grub_config_options=\"rootdelay=300 console=ttyS0 earlyprintk=ttyS0\"\n    fi\n\n    # Filter out the options need to add by excluding existing options\n    _required_grub_config_options=\"\"\n    for option in $_grub_config_options\n    do\n        if grep -q \"^GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\" ||\n           grep -q \"^[[:space:]][[:space:]]*GRUB_CMDLINE_LINUX[[:space:]]*=.*[[:space:]\\\"]$option[[:space:]\\\"].*\" \"$_grub_options_file_path\"\n        then\n            echo \"$option is already present. Skipping it...\"\n        else\n            _required_grub_config_options=\"$_required_grub_config_options $option\"\n        fi\n    done\n    \n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more chages to grub.\"\n    else\n        echo \"Required Grub options are: $_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (Before) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (Before) ###\"\n        \n        AddOrUpdateConfigValue \"$_grub_options_file_path\" \"GRUB_CMDLINE_LINUX\" \"$_required_grub_config_options\"\n        \n        echo \"### BEGIN: $_grub_options_file_path file (After) ###\"\n        cat \"$_grub_options_file_path\"\n        echo \"### END: $_grub_options_file_path file (After) ###\"\n    fi\n\n    return $_SUCCESS_\n}\n\nfunction ModifyGrubConfig_RHEL_CENTOS\n{\n    ModifyGrubOptions \"$1\"\n\n    # Temporarily modify grub.cfg for first boot, as part of boot up script \"grub2-mkconfig\" will run\n    # and updates the grub.cfg again.\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"All grub options are already in place. Not making any more chages to grub.cfg.\"\n    else\n        # Backup the /etc/default/grub file\n        _grub_conf_file_path=\"$mntpath/boot/grub2/grub.cfg\"\n\n        # Change the file path to /boot/efi/efi/redhat for UEFI scenario.\n    [[ \"$firmware_type\" = \"UEFI\" ]] && _grub_conf_file_path=\"$_grub2_efi_path/grub.cfg\"\n\n        BackupFile \"$_grub_conf_file_path\"\n\n        # This command also inserts the options to recovery mode grub command line, and the grub.cfg will be re-build on first boot\n        # when boot-up script runs 'update-grub' command.\n        sed -i --follow-symlinks \"s/^[[:space:]][[:space:]]*linux16[[:space:]]\\/.* root=.*[[:space:]]ro.*/&$_required_grub_config_options /\" \"$_grub_conf_file_path\"\n    fi\n\n    return $_SUCCESS_\n}\n\nfunction ModifyGrub_BLS\n{\n    ModifyGrubOptions \"$1\"\n\n    if [[ -z \"$_required_grub_config_options\" ]] ; then\n        echo \"Grub options already in place. Skip chages to grub.cfg.\"\n    else\n        echo \"Add options: $_required_grub_config_options\"\n        blsdir=\"$mntpath/boot/loader/entries\"\n\n        for _efile in `ls $blsdir`; do\n            _grub_conf_file_path=$blsdir/$_efile\n            BackupFile \"$_grub_conf_file_path\"\n            sed -i -e \"/^options/s/$/ $_required_grub_config_options/\" $_grub_conf_file_path\n        done\n    fi\n\n    return $_SUCCESS_\n}\n\nfunction RemovePersistentNetGeneratorRules_CENTOS7\n{\n    BackupFile $mntpath/etc/udev/rules.d/75-persistent-net-generator.rules\n    /bin/rm -f $mntpath/etc/udev/rules.d/75-persistent-net-generator.rules\n}\n\nfunction RemoveNetworkManager\n{\n    /bin/rm -f $mntpath/etc/udev/rules.d/*-persistent-net.rules\n    /bin/rm -f $mntpath/lib/udev/rules.d/*-persistent-net-generator.rules\n    \n    PrintDataTime \"Removing NetworkManager StartTime: \"\n    /sbin/chroot $mntpath /bin/rpm -e --nodeps NetworkManager\n    PrintDataTime \"EndTime: \"\n    \n    # Remove netwokr manager binary if exist.\n    /bin/rm -f $mntpath/etc/init.d/NetworkManager\n}\n\nfunction RemoveNetworkManager_UBUNTU\n{\n    BackupFile $mntpath/lib/udev/rules.d/75-persistent-net-generator.rules\n    /bin/rm -f $mntpath/lib/udev/rules.d/75-persistent-net-generator.rules\n    \n    BackupFile $mntpath/etc/udev/rules.d/70-persistent-net.rules\n    /bin/rm -f $mntpath/etc/udev/rules.d/70-persistent-net.rules\n    \n    # TODO : Verify if the rpm can be able to remove the NetworkManager package.\n    #        if not then need to investigate the similar tool such as : get-apt, apt ...etc.\n}\n\nfunction ConfigureNetworkFile_CentOS_RHEL\n{\n    local gtwdev=$1\n    # /etc/sysconfig/network file modifications\n    local network_file=$mntpath/etc/sysconfig/network\n    if [[ -f $network_file ]]; then\n        # Log the original network file\n        echo \"**** network file ****\"\n        cat $network_file\n        echo \"**** end ****\"\n        \n        BackupFile $network_file\n        UpdateConfigValue $network_file \"NETWORKING\" \"yes\"\n        RemoveConfig $network_file \"GATEWAY\"\n    else\n        echo \"NETWORKING=yes\" > $network_file\n        echo \"HOSTNAME=localhost.localdomain\" >> $network_file\n    fi\n    \n    # Update GATEWAYDEV if provided.\n    if [[ ! -z \"$gtwdev\" ]]; then\n        UpdateConfigValue $network_file \"GATEWAYDEV\" \"$gtwdev\"\n    else\n        UpdateConfigValueIfExists $network_file \"GATEWAYDEV\" \"eth0\"\n    fi\n    \n    # Log the modified network file.\n    echo \"**** updated network file ****\"\n    cat $network_file\n    echo \"**** end ****\"\n}\n\nfunction ConfigureDefaultNICForUBUNTUCloudInit\n{\n    # As a workaround, taking a random filename for netplan dhcp configuration.\n    # As soon as Azure Compute publishes steps for preparing Ubuntu 18.04 LTS\n    # we will follow those instructions to prepare netplan configuration.\n    # NOTE: Change the file name in setazureip.sh when the change is made here\n    local dhcp_netplan_file=\"$mntpath/etc/netplan/50-azure_migrate_dhcp.yaml\"\n    if [[ -f $dhcp_netplan_file ]]; then\n        echo \"DHCP netplan configuration for Azure already exists\"\n        return;\n    fi\n    \n    echo \"# This is generated for ASR to make NICs DHCP in Azure.\" > $dhcp_netplan_file\n    echo \"network:\" >> $dhcp_netplan_file\n    echo \"    version: 2\" >> $dhcp_netplan_file\n    echo \"    ethernets:\" >> $dhcp_netplan_file\n    echo \"        ephemeral:\" >> $dhcp_netplan_file\n    echo \"            dhcp4: true\" >> $dhcp_netplan_file\n    echo \"            match:\" >> $dhcp_netplan_file\n    echo \"                driver: hv_netvsc\" >> $dhcp_netplan_file\n    echo \"                name: '!eth0'\" >> $dhcp_netplan_file\n    echo \"            optional: true\" >> $dhcp_netplan_file\n    echo \"        hotpluggedeth0:\" >> $dhcp_netplan_file\n    echo \"            dhcp4: true\" >> $dhcp_netplan_file\n    echo \"            match:\" >> $dhcp_netplan_file\n    echo \"                driver: hv_netvsc\" >> $dhcp_netplan_file\n    echo \"                name: 'eth0'\" >> $dhcp_netplan_file\n    \n    echo \"Applying the dhcp netplan configuration... \"\n    chroot $mntpath netplan apply\n    if [[ $? -eq 0 ]]; then\n        echo \"netplan with dhcp settings applied!\"\n    else\n        echo \"WARNING: netplan couldn't apply dhcp settings.\"\n    fi\n}\n\n\nfunction ConfigureDefaultNICForUBUNTU\n{\n    _ubuntu_network_interfaces_file=\"$mntpath/etc/network/interfaces\"\n    \n    # Backup the original interfaces file\n    BackupFile \"$_ubuntu_network_interfaces_file\"\n    \n    # Create new interfaces file\n    echo \"# The loopback network interface\" > $_ubuntu_network_interfaces_file\n    echo \"auto lo\" >> $_ubuntu_network_interfaces_file\n    echo \"iface lo inet loopback\" >> $_ubuntu_network_interfaces_file\n    echo \"\" >> $_ubuntu_network_interfaces_file\n    echo \"# The primary network interface\" >> $_ubuntu_network_interfaces_file\n    echo \"auto eth0\" >> $_ubuntu_network_interfaces_file\n    echo \"iface eth0 inet dhcp\" >> $_ubuntu_network_interfaces_file\n    # TODO: Conform below lines are required or not\n    #echo \"\" >> $_ubuntu_network_interfaces_file\n    #echo \"# This is an autoconfigured IPv6 interface\" >> $_ubuntu_network_interfaces_file\n    #echo \"iface eth0 inet6 auto\" >> $_ubuntu_network_interfaces_file\n}\n\nfunction ConfigureDefaultNICForRHEL_CENTOS_OEL \n{\n    #Setting the ipaddress for default NIC ifcfg-eth0\n    NETWORKCONFIGFILESDIR=\"$mntpath/etc/sysconfig/network-scripts\"\n    BACKUP_NETWORKCONFIGFILES=\"$NETWORKCONFIGFILESDIR/asr_nw\"\n    \n    if [ ! -d $BACKUP_NETWORKCONFIGFILES ]\n    then\n        mkdir -p $BACKUP_NETWORKCONFIGFILES\n    fi\n\n    ###Moving all the network config files to backup folder#####\n    mv $NETWORKCONFIGFILESDIR/ifcfg-e* $BACKUP_NETWORKCONFIGFILES/\n\n    name=\"eth0\"\n    ConfigFileName=$NETWORKCONFIGFILESDIR/ifcfg-$name\n    \n    echo \"DEVICE=$name\" > $ConfigFileName\n    echo \"ONBOOT=yes\" >> $ConfigFileName\n    echo \"DHCP=yes\" >> $ConfigFileName\n    echo \"BOOTPROTO=dhcp\" >> $ConfigFileName\n    echo \"TYPE=Ethernet\" >>  $ConfigFileName\n    echo \"USERCTL=no\" >>  $ConfigFileName\n    echo \"PEERDNS=yes\" >>  $ConfigFileName\n    echo \"IPV6INIT=no\" >> $ConfigFileName\n    \n    RefIfcfgFile=$(ls $BACKUP_NETWORKCONFIGFILES/ifcfg-e* | head -n 1)\n    if [ $? -ne 0 ]; then\n        # default permissions. Log permissions for debug purpose\n        ls -lrt $ConfigFileName\n    else\n        # preserve permissions from existing ifcfg-eth* file\n        chown --reference=$RefIfcfgFile $ConfigFileName\n        chmod --reference=$RefIfcfgFile $ConfigFileName\n    fi\n}\n\nfunction ConfigureDefaultNICForSLES \n{\n    #Setting the ipaddress for default NIC ifcfg-eth0\n    \n    NETWORKCONFIGFILESDIR=\"$mntpath/etc/sysconfig/network\"\n    BACKUP_NETWORKCONFIGFILES=\"$NETWORKCONFIGFILESDIR/asr_nw\"\n    \n    if [ ! -d $BACKUP_NETWORKCONFIGFILES ]\n    then\n        mkdir -p $BACKUP_NETWORKCONFIGFILES\n    fi\n    \n    ###Moving all the network config files to backup folder#####\n    mv -f $NETWORKCONFIGFILESDIR/ifcfg-eth* $BACKUP_NETWORKCONFIGFILES/\n    \n    name=\"eth0\"\n    ConfigFileName=$NETWORKCONFIGFILESDIR/ifcfg-$name\n    \n    echo \"BOOTPROTO='dhcp'\"  >$ConfigFileName\n    echo \"MTU='' \" >> $ConfigFileName\n    echo \"REMOTE_IPADDR='' \" >>$ConfigFileName\n    echo \"STARTMODE='onboot'\" >>$ConfigFileName\n\n    RefIfcfgFile=$(ls $BACKUP_NETWORKCONFIGFILES/ifcfg-eth* | head -n 1)\n    if [ $? -ne 0 ]; then\n        # default permissions. Log permissions for debug purpose\n        ls -lrt $ConfigFileName\n    else\n        chown --reference=$RefIfcfgFile $ConfigFileName\n        chmod --reference=$RefIfcfgFile $ConfigFileName\n    fi\n}\n\nfunction AddHyperVDriversToInitrdModules\n{\n    newstr=`sed  -n \"/^INITRD_MODULES*/p \" $mntpath/etc/sysconfig/kernel`\n    echo \"$newstr\"|grep -q \"hv_storvsc\"\n    if [ $? -eq 0 ];then\n        echo \"HyperV drivers are already present\"\n    else\n        echo \"HyperV drivers are not present, adding them to INITRD_MODULES.\"\n        newstr=`echo $newstr|awk -F\\\" ' {print $1\"\\\"\"$2 \" hv_vmbus hv_storvsc hv_netvsc\" \"\\\"\"}'`\n        sed  -i  \"s/^INITRD_MODULES=\\\".*\\\"/$newstr/\"  $mntpath/etc/sysconfig/kernel\n    fi\n}\n\nfunction ResetNetworkResolverAndRoutesCache_SLES\n{\n    # TODO: Remove this code after observing live site data for couple of months.\n    if [ -f $mntpath/etc/asr-reset-resolv-conf ]; then\n        echo \"Resetting resolv.conf file.\"\n        /bin/mv -f $mntpath/etc/resolv.conf $mntpath/etc/resolv.conf\"${_INMAGE_ORG_}\"\n        /bin/touch  $mntpath/etc/resolv.conf\n        chown --reference=$mntpath/etc/resolv.conf\"${_INMAGE_ORG_}\" $mntpath/etc/resolv.conf\n        chmod --reference=$mntpath/etc/resolv.conf\"${_INMAGE_ORG_}\" $mntpath/etc/resolv.conf\n    fi\n    \n    # This is a workaround to skip static routing reset.\n    if [ -f $mntpath/etc/asr-skip-routing-reset ]; then\n        echo \"Skipping the static routing reset.\"\n    else\n        /bin/mv -f $mntpath/etc/sysconfig/network/ifroute-eth0 $mntpath/etc/sysconfig/network/ifroute-eth0\"${_INMAGE_ORG_}\"\n        /bin/mv -f $mntpath/etc/sysconfig/network/routes $mntpath/etc/sysconfig/network/routes\"${_INMAGE_ORG_}\"\n    fi\n}\n\n_DATE_STRING_=`date +'%b_%d_%H_%M_%S'`\necho \"-------------------  $_DATE_STRING_ : Starting post recovery script -------------------\"\n\nif [ ! $1 ]\nthen\n    echo \"Provide Linux Root Filesystem mount point\"\n    exit 1\nelse\n    if [ -d $1 ]\n    then\n        mntpath=$1\n        /bin/mount | grep \"$mntpath\"\n        if [ $? -eq 0 ]; then\n            echo \"Root fs $mntpath is mounted\"\n        else\n            echo \"ERROR - Root Filesystem is not mounted at directory $mntpath\"\n            exit 1\n        fi\n    else\n        echo \"ERROR - Provided Linux Root Filesystem mount point is not a directory $mntpath\"\n        exit 1\n    fi\nfi\n\nif [ ! $2 ]\nthen\n    echo \"Provide working directory\"\n    exit 1\nelse\n    if [ -d $2 ]\n    then\n        working_dir=$2\n    else\n        echo \"ERROR - Provided working directory does not exist : $2\"\n        exit 1\n    fi\nfi\n\nif [ ! $3 ]\nthen\n    echo \"Hydration config settings are empty\"\nelse\n    hydration_config_settings=$3\n    echo \"Hydration config settings: $3\"\nfi\n\n#Get recovering OS Name\nos_details_script=$working_dir/OS_details_target.sh\nos_name=`bash $os_details_script $mntpath`\necho \"-- OS Information --\"\necho \"$os_name is being recovered now\"\ncat $mntpath/etc/*release*\n\n_grub2_efi_path=\"$mntpath/boot/efi/EFI/\"\nconfig_file_name=\"\"\nbootloader_folder_path=\"$mntpath/boot/efi/EFI//boot\"\n\ncase \"$os_name\" in\n    OL7*|RHEL6*|RHEL7*|RHEL8*|RHEL9*)\n        _grub2_efi_path=\"${_grub2_efi_path}redhat\"\n        ;;\n    CENTOS6*|CENTOS7*)\n        _grub2_efi_path=\"${_grub2_efi_path}centos\"\n        ;;\n    SLES12*|SLES15*)\n        _grub2_efi_path=\"${_grub2_efi_path}opensuse\"\n        ;;\n    UBUNTU*)\n        _grub2_efi_path=\"${_grub2_efi_path}ubuntu\"\n        ;;\n    DEBIAN*)\n        _grub2_efi_path=\"${_grub2_efi_path}debian\"\n        ;;\n    *)\n        echo \"Unidentified OS version - $os_name \"\n        ;;\nesac\n\nfirmware_type=\"BIOS\"\nif [[ -d $_grub2_efi_path ]]; then\n    if [[ -f \"$_grub2_efi_path/grub.conf\" ]] || [[ -f \"$_grub2_efi_path/menu.lst\" ]] || [[ -f \"$_grub2_efi_path/grub.cfg\" ]]; then\n        firmware_type=\"UEFI\"\n        echo \"Grub.cfg path in case of UEFI is: $_grub2_efi_path\"\n    fi\nelse\n    echo \"Default grub path applicable in case of BIOS\"\nfi\n\necho \"-- Starting system reconfig --\"\n\n# Menu.lst or grub.cfg configuration changes\ncase $os_name in\n    RHEL5* | OL5* | OL6* | SLES11* | RHEL6* | CENTOS6*)\n        ModifyMenuListFile $mntpath\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying menu.lst file\"\n            exit 1\n        fi\n        echo \"install ata_piix  { /sbin/modprobe hv_storvsc 2>&1 || /sbin/modprobe --ignore-install ata_piix; }\" > $mntpath/etc/modprobe.d/hyperv_pvdrivers.conf\n    ;;\n    SLES12*|SLES15*)\n        _grub_config_options=\"console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n        ModifyGrubConfig_SLES \"$_grub_config_options\"\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n    UBUNTU*)\n        ModifyGrubConfig_UBUNTU\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n    RHEL7*)\n        _grub_config_options=\"rootdelay=300 console=ttyS0 earlyprintk=ttyS0\"\n        ModifyGrubConfig_RHEL_CENTOS \"$_grub_config_options\"\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n    CENTOS7* | OL7*)\n        _grub_config_options=\"rootdelay=300 console=ttyS0 earlyprintk=ttyS0 net.ifnames=0\"\n        ModifyGrubConfig_RHEL_CENTOS \"$_grub_config_options\"\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n    RHEL8* | CENTOS8* | OL8* | RHEL9* | OL9*)\n        _grub_config_options=\"console=tty1 console=ttyS0 earlyprintk=ttyS0 rootdelay=300\"\n        ModifyGrub_BLS \"$_grub_config_options\"\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n\n    DEBIAN*)\n        ModifyGrubConfig_DEBIAN\n        if [ $? -ne $_SUCCESS_ ]; then\n            echo \"Error modifying grub.cfg file\"\n            exit 1\n        fi\n    ;;\n    *)\n        echo \"Incorrect input for os to modify grub entries-  $os_name \"\n        exit 1\n        ;;\nesac\n\nif [ \"$firmware_type\" = \"UEFI\" ]; then\n    if [ ! -f \"$_grub2_efi_path/bootx64.efi\" ]; then\n        if [ -f \"$_grub2_efi_path/shimx64.efi\" ]; then\n            CopyFile \"$_grub2_efi_path/shimx64.efi\" \"$_grub2_efi_path/bootx64.efi\"\n        elif [ -f \"$_grub2_efi_path/grubx64.efi\" ]; then\n            CopyFile \"$_grub2_efi_path/grubx64.efi\" \"$_grub2_efi_path/bootx64.efi\"\n        elif [ -f \"$_grub2_efi_path/grub.efi\" ]; then\n            CopyFile \"$_grub2_efi_path/grub.efi\" \"$_grub2_efi_path/bootx64.efi\"\n        else\n            if [ ! -d \"$bootloader_folder_path\" ] || [ ! -f \"$bootloader_folder_path/bootx64.efi\" ]; then\n                echo \"efi file is absent on source disk which will lead to boot failure in Gen2 vm.\"\n                exit 1\n            fi\n        fi\n    fi\n\n    if [ -f \"$_grub2_efi_path/grub.cfg\" ]; then\n        config_file_name=\"grub.cfg\"\n        CopyFile \"$_grub2_efi_path/grub.cfg\" \"$_grub2_efi_path/bootx64.cfg\"\n    elif [ -f \"$_grub2_efi_path/grub.conf\" ]; then\n        config_file_name=\"grub.conf\"            \n        CopyFile \"$_grub2_efi_path/grub.conf\" \"$_grub2_efi_path/bootx64.conf\"\n    fi\n\n    # Folder needs to be explicitly added for Ubuntu/Debian/RHEL6/CENTOS6.\n    # Checking and adding for other distros too if not added.\n    if [ ! -d \"$bootloader_folder_path\" ]; then\n        CopyDirectory \"$_grub2_efi_path/\" \"$bootloader_folder_path\"\n    else\n        if [ ! -f  \"$bootloader_folder_path/bootx64.efi\" ]; then\n            CopyFile \"$_grub2_efi_path/bootx64.efi\" \"$bootloader_folder_path/bootx64.efi\"\n        fi\n\n        # bootx64.conf required for RHEL6/CENTOS6. Copying for other distros too.\n        if [ $config_file_name = \"grub.cfg\" ] && [ ! -f \"$bootloader_folder_path/bootx64.cfg\" ]; then\n            CopyFile \"$_grub2_efi_path/bootx64.cfg\" \"$bootloader_folder_path/bootx64.cfg\"\n        elif [ $config_file_name = \"grub.conf\" ] && [ ! -f \"$bootloader_folder_path/bootx64.conf\" ]; then\n            CopyFile \"$_grub2_efi_path/bootx64.conf\" \"$bootloader_folder_path/bootx64.conf\"\n        fi\n    fi\nfi\n\necho \"Rootfs mount point:$mntpath\"\n\n# Networking and other configuration changes\ncase $os_name in\n    RHEL5* | RHEL6* | CENTOS6*)\n        touch $mntpath/etc/vxagent/setazureip\n\n        # /etc/sysconfig/network file modifications\n        # Setting GATEWAYDEV to eth0 to handle multi nic on same subnet.\n        ConfigureNetworkFile_CentOS_RHEL \"eth0\"\n        \n        # Remove network manager if exist\n        RemoveNetworkManager\n        \n        # Set default NIC settings\n        ConfigureDefaultNICForRHEL_CENTOS_OEL\n    ;;\n    OL5* | OL6*)\n        hostname=`grep HOSTNAME  $mntpath/etc/sysconfig/network | awk -F= '{ print $2 }'`\n        hostname=`echo $hostname | sed -e 's: ::g'`\n\n        if [ ! ${hostname} ]; then\n                hostname=localhost\n        fi\n        \n        touch $mntpath/etc/vxagent/setazureip\n\n        # /etc/sysconfig/network file modifications\n        ConfigureNetworkFile_CentOS_RHEL\n\n        # Remove network manager if exist\n        RemoveNetworkManager\n        \n        # Set default NIC settings\n        ConfigureDefaultNICForRHEL_CENTOS_OEL\n    ;;\n    SLES11*)\n    \n        touch $mntpath/etc/vxagent/setazureip\n        \n        # Reset network resolver and routing caches.\n        ResetNetworkResolverAndRoutesCache_SLES\n        \n        Rename_INITRD_RAMFS_Files $mntpath/boot/\n        \n        # Add Hyper-V Drivers o INITRD_MODULES if not present.\n        AddHyperVDriversToInitrdModules\n        \n        # Remove network manager if exist.\n        RemoveNetworkManager\n        \n        # Set default NIC settings.\n        ConfigureDefaultNICForSLES\n    ;;\n    SLES12*|SLES15*)\n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        # Reset network resolver and routing caches.\n        ResetNetworkResolverAndRoutesCache_SLES\n        \n        # Add Hyper-V Drivers o INITRD_MODULES if not present.\n        AddHyperVDriversToInitrdModules\n        \n        # Remove network manager if exist\n        RemoveNetworkManager\n        \n        # Set default NIC settings\n        ConfigureDefaultNICForSLES\n    ;;\n    UBUNTU14-* | UBUNTU16-*)\n        \n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        RemoveNetworkManager_UBUNTU\n        \n        ConfigureDefaultNICForUBUNTU\n    ;;\n    UBUNTU18-* | UBUNTU20-* | UBUNTU21-* |UBUNTU22-*)\n        \n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        RemoveNetworkManager_UBUNTU\n        \n        ConfigureDefaultNICForUBUNTUCloudInit\n    ;;\n    DEBIAN*)\n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        # Udev rules files are same for UBUNTU and DEBIAN.\n        RemoveNetworkManager_UBUNTU\n        \n        # /etc/network/interfaces file is same for UBUNTU and DEBIAN.\n        ConfigureDefaultNICForUBUNTU\n        \n        # TODO: Use UBUNTU case block for DEBIAN as well, as the changes are same.\n    ;;\n    RHEL7*|RHEL8*|CENTOS8*|OL8*|RHEL9*|OL9*)\n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        # Configure /etc/sysconfig/network file\n        ConfigureNetworkFile_CentOS_RHEL\n        \n        # Azure image preparation guidlines for RHEL7.X does not mentioned about removing udev rules.\n        # If observer any issue then we need to uncomment below line to remove udev rules.\n        # RemovePersistentNetGeneratorRules_CENTOS7\n        \n        # Set default NIC settings\n        ConfigureDefaultNICForRHEL_CENTOS_OEL\n    ;;\n    CENTOS7* | OL7*)\n        touch $mntpath/etc/vxagent/setazureip\n        touch $mntpath/etc/vxagent/prepareforazure\n        \n        # Configure /etc/sysconfig/network file\n        ConfigureNetworkFile_CentOS_RHEL\n        \n        # Remove udev rules\n        RemovePersistentNetGeneratorRules_CENTOS7\n        \n        # Set default NIC settings\n        ConfigureDefaultNICForRHEL_CENTOS_OEL\n    ;;\n    *)\n        echo \"In correct input for os to modify OS configuration entries-  $os_name \"\n        exit 1\n        ;;\nesac\n\n    InstallLinuxGuestAgent\n    if [[ $? -ne 0 ]]; then\n        echo \"Could not push linux guest agent binaries on target vm.\"\n    fi\n\npid=`ps -aef | grep hv_kvp_daemon | grep -v \"grep\" | awk '{ print $2 }'`\nif [ $pid ]; then\n    kill -9 $pid\nfi\n\necho \"[Sms-Telemetry-Data]:${telemetry_data}\"\n\n_DATE_STRING_=`date +'%b_%d_%H_%M_%S'`\necho \"------------  $_DATE_STRING_: Finishing post recovery script for $os_name ----------\"\nexit 0\n", "num_lines": 1578}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##+----------------------------------------------------------------------------------+\n##            Copyright(c) Microsoft Corp. 2015\n##+----------------------------------------------------------------------------------+\n## File         :   prepare-os-for-azure.sh\n##\n## Description  :   \n##\n## History      :   11-11-2018 (Venu Sivanadham) - Created\n##\n## Usage        :   prepare-os-for-azure.sh <chroot-path>\n##+----------------------------------------------------------------------------------+\n\n###Start: Script error codes.\n_E_AZURE_SMS_INTERNAL=1\n_E_SCRIPT_SYNTAX_ERROR=2\n_E_AZURE_SMS_TOOLS_MISSING=3\n_E_AZURE_SMS_ARGS=4\n_E_AZURE_SMS_OS_UNSUPPORTED=5\n_E_AZURE_SMS_CONF_MISSING=6\n_E_AZURE_SMS_INITRD_IMAGE_GENERATION_FAILED=7\n_E_AZURE_SMS_HV_DRIVERS_MISSING=8\n_E_AZURE_GA_INSTALLATION_FAILED=9\n_E_AZURE_ENABLE_DHCP_FAILED=10\n\n###End: Script error codes.\n\n###Start: Constants\n_FIX_DHCP_SCRIPT_=\"fix_dhcp.sh\"\n_AM_STARTUP_=\"azure-migrate-startup\"\n_STARTUP_SCRIPT_=\"${_AM_STARTUP_}.sh\"\n_AM_SCRIPT_DIR_=\"/usr/local/azure-migrate\"\n_AM_SCRIPT_LOG_FILE_=\"/var/log/${_AM_STARTUP_}.log\"\n_AM_INSTALLGA_=\"asr-installga\"\n_AM_HYDRATION_LOG_=\"/var/log/am-hydration-log\"\n###End: Constants\n\n#@1 - Error Code\n#@2 - Error Data\nthrow_error()\n{\n    local error_code=$_E_AZURE_SMS_INTERNAL\n    [[ $1 =~ [[:digit:]] ]] && error_code=$1\n    \n    local error_data=\"Unavailable\"\n    [[ -z \"$2\" ]] || error_data=\"$2\"\n    \n    echo \"[Sms-Scrip-Error-Data]:${error_data}\"\n    echo \"[Sms-Telemetry-Data]:${telemetry_data}\"\n\n    exit $error_code\n}\n\n# Usage: Add telemetries about utilities absent on source VM.\nunset telemetry_data\n#@1 - Telemetry Data\nadd_telemetry_data()\n{\n    if [[ -z $telemetry_data ]]; then\n        telemetry_data=\"$1\"\n    else\n        telemetry_data=\"$telemetry_data*#*$1\"\n        echo \"New TelemetryData: $telemetry_data\"\n    fi\n}\n\n#@1: Property modified by Azure Migrate\n#@2: Remarks for modification - May contain value/ status if modification was made\nunset am_telem_suffix\nadd_am_hydration_log()\n{\n    if [[ -z $am_telem_suffix ]]; then\n        am_telem_suffix=\"-$(date).log\"\n        echo \"---Hydration Log for Azure Migrate/Site Recovery Begin---\" >> \"${chroot_path}${_AM_HYDRATION_LOG_}$am_telem_suffix\"\n        echo \"Some paths may begin with $chroot_path relative to hydration VM.\" >> \"${chroot_path}${_AM_HYDRATION_LOG_}$am_telem_suffix\"\n    fi\n\n    echo \"$1 :-: $2\" >> \"${chroot_path}${_AM_HYDRATION_LOG_}$am_telem_suffix\"\n}\n\n#@1 - string to log\ntrace()\n{\n    echo \"$(date +\"%a %b %d %Y %T\") : $1\"\n}\n\nunset chroot_path\nunset hydration_config_settings\n#@1 - chroot path\nvalidate_script_input()\n{\n    [[ $# -lt 1 ]] && throw_error $_E_AZURE_SMS_ARGS \"chroot-path missing\"  \n    [[ ! -d \"$1\" ]] && throw_error $_E_AZURE_SMS_ARGS \"$1 invalid\"\n    \n    trace \"chroot: $1\"\n\n    if [[ $# -ge 2 ]]; then\n        trace \"Hydration Config Settings: $2\"\n        hydration_config_settings=\"$2\"\n    fi\n    chroot_path=\"$1\"\n}\n\nunset src_distro\n#@1 - Root path\nfind_src_distro()\n{\n    local root_path=$chroot_path\n    [[ -z \"$1\" ]] || root_path=$1\n    \n    local script_dir=$(cd $(dirname \"$0\") > /dev/null && pwd)\n    [[ -d \"$script_dir\" ]] || script_dir=/usr/local/AzureRecovery\n    \n    src_distro=$($script_dir/OS_details_target.sh \"$chroot_path\")\n    if [[ -z \"src_distro\" ]]; then\n        throw_error $_E_AZURE_SMS_OS_UNSUPPORTED \"unknown\"\n    else\n        trace \"OS : $src_distro\"\n    fi\n}\n\nunset firmware_type\nunset _grub2_efi_path\nget_firmware_type()\n{\n    _grub2_efi_path=\"$chroot_path/boot/efi/EFI/\"\n\n    case \"$src_distro\" in\n        OL7*|RHEL6*|RHEL7*|RHEL8*|RHEL9*|OL8*|OL9*)\n            _grub2_efi_path=\"${_grub2_efi_path}redhat\"\n            ;;\n        CENTOS7*|CENTOS8*|CENTOS9*)\n            _grub2_efi_path=\"${_grub2_efi_path}centos\"\n            ;;\n        SLES11*|SLES12*|SLES15*)\n            _grub2_efi_path=\"${_grub2_efi_path}opensuse\"\n            ;;\n        UBUNTU*)\n            _grub2_efi_path=\"${_grub2_efi_path}ubuntu\"\n            ;;\n        DEBIAN*|KALI-ROLLING*)\n            _grub2_efi_path=\"${_grub2_efi_path}debian\"\n            ;;\n        *)\n            echo \"Unsupported OS version for Migration - $src_distro \"\n            ;;\n    esac\n\n    firmware_type=\"BIOS\"\n    if [[ -d $_grub2_efi_path ]]; then\n        if [[ -f \"$_grub2_efi_path/grub.conf\" ]] || [[ -f \"$_grub2_efi_path/menu.lst\" ]] || [[ -f \"$_grub2_efi_path/grub.cfg\" ]]; then\n            firmware_type=\"UEFI\"\n            echo \"Grub.cfg path in case of UEFI is: $_grub2_efi_path\"\n        fi\n    else\n        echo \"Default grub path applicable in case of BIOS\"\n    fi\n\n    add_am_hydration_log \"Firmware Type\" \"$firmware_type\"\n}\n\n#@1 - Source file path\n#@2 - Target file path\ncopy_file()\n{\n    local _source_=$1\n    local _target_=$2\n\n    /bin/cp -f $_source_ $_target_\n    \n    return $?\n}\n\n# Recursively copy the folder and contents\nfunction CopyDirectory\n{\n    if [ -d \"$1\" ]; then\n        /bin/cp -r $1 $2\n    else\n        echo \"Folder $1 is absent. Copy failed.\"\n    fi\n    return $_SUCCESS_\n}\n\n_BCK_DIR_=\"azure_sms_bck\"\n_BCK_EXT_=\".bck_azure_sms\"\n#@1 - File path\nbackup_file()\n{\n    local _source_=$1\n    local _target_=\"${_source_}${_BCK_EXT_}\"\n    \n    [[ -f $_source_ ]] || { echo \"$_source_ file not found.\"; return 1; }\n    [[ -f $_target_ ]] && { echo \"$_target_ already exist.\"; return 1; }\n    \n    copy_file $_source_ $_target_\n    if [[ $? -ne 0 ]]; then\n        # We ignore error in copy step for migration.\n        # But log a trace so it shows up in logs.\n        trace \"WARNING: Could not backup file $1.\"\n    fi\n\n    return $?\n}\n\n#@1 - File path\nmove_to_backup()\n{\n    local _source_=$1\n    local _target_=\"${_source_}${_BCK_EXT_}\"\n    \n    [[ $_source_ =~ .*${_BCK_EXT_}$ ]] && {\n        echo \"$_source_ is a backup file.\";\n        return 1;\n    }\n    \n    [[ -f $_source_ ]] || { \n        echo \"$_source_ file not found.\";\n        return 1;\n    }\n    \n    mv -f $_source_ $_target_\n    return $?\n}\n\n#@1 - File path\n#@2 - Backup directory (optional)\nmove_to_backup_dir()\n{\n    [[ -z $1 ]] && return 0\n    \n    local _source_=$1\n    [[ -f $_source_ ]] || {\n        echo \"File $_source_ not found\"\n        return 1;\n    }\n    \n    local _target_dir_=$2\n    [[ -z $_target_dir_ ]] && _target_dir_=\"$(dirname $_source_)/$_BCK_DIR_\"\n    \n    [[ -d $_target_dir_ ]] || {\n        echo \"Creating backup directory $_target_dir_\"\n        mkdir $_target_dir_\n    }\n    \n    [[ -d $_target_dir_ ]] || {\n        echo \"Could not create backup directory $_target_dir_\"\n        return 1;\n    }\n    \n    mv -f $_source_ $_target_dir_\n    return $?\n}\n\n#@1 - Tool name\nverify_tools()\n{\n    [[ -z \"$1\" ]] && return 0\n    \n    for tool_name in $1\n    do\n        trace \"Looking for the tool $tool_name\"\n        chroot $chroot_path which $tool_name\n        if [[ $? -ne 0 ]] ; then\n            # Fail with error codes related to usage of the tool\n            # Severity of effect due to tool's absence will be checked later.\n            add_am_hydration_log \"$tool_name\" \"ABSENT\"\n            add_telemetry_data $tool_name\n        else\n            add_am_hydration_log \"$tool_name\" \"PRESENT\"\n            trace \"$tool_name is available on source.\"\n        fi\n    done\n\n    return 0\n}\n\n#@1 - Kernel version\n#@2 - Module list\nverify_kernel_modules()\n{\n    [[ -z \"$1\" ]] && return 1\n    [[ -z \"$2\" ]] && return 0\n    \n    local kernel_name=\"$1\"\n    for $module_name in $2\n    do\n        chroot $chroot_path modinfo -k \"$kernel_name\" $module_name\n        if [[ $? -ne 0 ]] ; then\n            throw_error $_E_AZURE_SMS_HV_DRIVERS_MISSING $kernel_name\n        fi\n    done\n    \n    return 0\n}\n\n#@1 - options to remove\n#@2 - file path\n#@3 - command prefix\nremove_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    [[ -z \"$2\" ]] && return 1\n    [[ -z \"$3\" ]] && return 1\n    \n    local _opts_=$1\n    local _file_=$2\n    local _cmd_=$3\n    \n    trace \"Removing [${_opts_}] options from $_file_\" \n    for _opt_ in $_opts_; do\n        sed -i --follow-symlinks \"/^[[:space:]]*${_cmd_}.*[[:space:]]root=.*/s/[[:space:]]${_opt_}[[:space:]]*/ /\" $_file_\n    done\n    \n    return 0\n}\n\n#@1 - options to add\n#@2 - file path\n#@3 - command prefix\nadd_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    [[ -z \"$2\" ]] && return 1\n    [[ -z \"$3\" ]] && return 1\n    \n    local _opts_=$1\n    local _file_=$2\n    local _cmd_=$3\n    \n    trace \"Adding [${_opts_}] options to $_file_\" \n    for _opt_ in $_opts_; do\n        if grep -q \"^[[:space:]]*${_cmd_}.*[[:space:]]root=.*[[:space:]]${_opt_}\\>.*\" $_file_; then\n            trace \"$_opt_ already present in grub command line.\"\n            continue\n        fi\n        \n        sed -i --follow-symlinks \"s/\\(^[[:space:]]*${_cmd_}.*[[:space:]]root=.*\\)\\($\\)/\\1 ${_opt_}\\2/\" $_file_\n    done\n    \n    return 0\n}\n\n#@1 - File name\n#@2 - Setting name\n#@3 - Setting value\nappend_config_setting_value()\n{\n    if grep -q \"\\<${2}\\>[[:space:]]*=.*\\<${3}\\>.*\" $1 ; then\n        # Setting key with value already present.\n        return 0\n    elif grep -q \"\\<${2}\\>[[:space:]]*=.*\" $1 ; then\n        # setting key present but not the value, append it.\n        sed -i --follow-symlinks \"s/\\(\\<${2}\\>[[:space:]]*=[[:space:]]*[\\\"]\\?\\)\\(.*$\\)/\\1${3} \\2/\" $1\n    else\n        # Setting key not found, adding the setting key=value\n        echo \"${2}=\\\"${3}\\\"\" >> $1\n    fi\n    \n    return 0\n}\n\n#@1 - Grub command options\n#@2 - Grub command setting name\n#@3 - Grub command configuration file path\nadd_grub2_config_options()\n{\n    local grub_cmd_setting=$2\n    local grub_conf_file=$3\n    [[ -z $grub_cmd_setting ]] && grub_cmd_setting=\"GRUB_CMDLINE_LINUX\"\n    [[ -z $grub_conf_file ]] && grub_conf_file=\"$chroot_path/etc/default/grub\"\n    \n    for _opt_ in $1; do\n        append_config_setting_value $grub_conf_file $grub_cmd_setting $_opt_\n    done\n    \n    return 0\n}\n\n#@1 - File name\n#@2 - Setting name\n#@3 - Setting value\nremove_config_setting_value()\n{\n    if grep -q \"\\<$2\\>[[:space:]]*=.*\\<$3\\>.*\" $1 ; then\n        sed -i --follow-symlinks \"s/\\(\\<$2\\>[[:space:]]*=.*\\)\\<$3\\>\\(.*\\)/\\1\\2/\" $1\n    else\n        echo \"Value \\\"$3\\\" not found for the $2.\"\n        return 1\n    fi\n    return 0\n}\n\n#@1 - Setting name\n#@2 - File name\ncomment_config_setting()\n{\n  echo \"Printing line in file $2 containing the pattern $1 if found.\"\n  sed -nr \"/$1/p\" \"$2\"\n\n  # Comment out the entry.\n  sed -i \"/$1/s/^/#/\" \"$2\"\n}\n\n#@1 - Setting name\n#@2 - File name\nuncomment_config_setting()\n{\n  echo \"Printing line in file $2 containing the pattern $1 if found.\"\n  sed -nr \"/$1/p\" \"$2\"\n\n  # Uncomment the entry.\n  sed -i \"/$1/s/^#//\" \"$2\"\n}\n\n#@1 - File name\n#@2 - Setting name\n#@3 - Setting value\nupdate_config_value()\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n    _setting_value_=\"$3\"\n\n    if grep -q \"^$2=$3\" $1 ; then\n        echo \"$2=$3 config value is already in place.\"\n    elif grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"s/\\(^$2=\\)\\(.*\\?\\)/\\1$3/\" $1\n    else\n        # Setting key not found, adding the setting key=value\n        echo \"$2=$3\" >> $1\n    fi\n}\n\n#@1 - File name\n#@2 - Setting name\n#@3 - Setting value\nupdate_config_value_if_exists()\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n    _setting_value_=\"$3\"\n\n    if grep -q \"^$2=$3\" $1 ; then\n        echo \"$2=$3 config value is already in place.\"\n    elif grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"s/\\(^$2=\\)\\(.*\\?\\)/\\1$3/\" $1\n    else\n        echo \"$2 setting not found, nothing to update.\"\n    fi\n}\n\n#@1 - File name\n#@2 - Setting name\nremove_config_entry()\n{\n    _config_file_=\"$1\"\n    _setting_name_=\"$2\"\n\n    if grep -q \"^$2=.*\" $1 ; then\n        sed -i --follow-symlinks \"/^$2=/d\" $1\n    else\n        echo \"$2 config setting not found, nothing to remove.\"\n    fi\n}\n\n#@1 - Grub command options\n#@2 - Grub command setting name\n#@3 - Grub command configuration file path\nremove_grub2_config_options()\n{\n    local grub_cmd_setting=$2\n    local grub_conf_file=$3\n    [[ -z $grub_cmd_setting ]] && grub_cmd_setting=\"GRUB_CMDLINE_LINUX\"\n    [[ -z $grub_conf_file ]] && grub_conf_file=\"$chroot_path/etc/default/grub\"\n    \n    for _opt_ in $1; do\n        remove_config_setting_value $grub_conf_file $grub_cmd_setting $_opt_\n    done\n    \n    return 0\n}\n\n#@1 - options to remove\n#@2 - grub file path\nremove_grub_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local _grub_conf_file=\"$2\"\n    if [[ -z \"$2\" ]]; then\n        if [ \"$firmware_type\" = \"UEFI\" ]; then\n            _grub_conf_file=\"$_grub2_efi_path/grub.conf\"\n        else\n            _grub_conf_file=\"$chroot_path/grub/grub.conf\"\n        fi\n    fi\n    \n    \n    remove_cmd_options \"$1\" \"$_grub_conf_file\" \"kernel\" \n    return $?\n}\n\n#@1 - options to remove\n#@2 - grub file path\nremove_grub2_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local _grub2_conf_file=\"$2\"\n    if [[ -z \"$2\" ]]; then\n        if [ \"$firmware_type\" = \"UEFI\" ]; then\n            _grub_conf_file=\"$_grub2_efi_path/grub.cfg\"\n        else\n            _grub2_conf_file=\"$chroot_path/boot/grub2/grub.cfg\"\n        fi\n    fi\n     \n    remove_cmd_options \"$1\" \"$_grub2_conf_file\" \"linux\"\n    return $?\n}\n\n#@1 - options to add\n#@2 - grub file path\nadd_grub_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local _grub_conf_file=\"$2\"\n    if [[ -z \"$2\" ]]; then\n        if [ \"$firmware_type\" = \"UEFI\" ]; then\n            _grub_conf_file=\"$_grub2_efi_path/grub.conf\"\n        else\n            _grub_conf_file=\"$chroot_path/grub/grub.conf\"\n        fi\n    fi\n    \n    add_cmd_options \"$1\" \"$_grub_conf_file\" \"kernel\"\n    return $?\n}\n\n#@1 - options to add\n#@2 - grub file path\nadd_grub2_cmd_options()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local _grub2_conf_file=\"$2\"\n    if [[ -z \"$2\" ]]; then\n        if [ \"$firmware_type\" = \"UEFI\" ]; then\n            _grub_conf_file=\"$_grub2_efi_path/grub.cfg\"\n        else\n            _grub2_conf_file=\"$chroot_path/boot/grub2/grub.cfg\"\n        fi\n    fi    \n\n    add_cmd_options \"$1\" \"$_grub2_conf_file\" \"linux\"\n    return $?\n}\n\n#@1 - kernel version\nis_kernel_in_use()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local kernel_version=$1\n    local grub_conf_files=\"$chroot_path/boot/grub/menu.lst \\\n            $chroot_path/boot/grub/grub.cfg \\\n            $chroot_path/boot/grub2/grub.cfg \\\n            $_grub2_efi_path/menu.lst \\\n            $_grub2_efi_path/grub.conf \\\n            $_grub2_efi_path/grub.cfg\"\n    \n    for grub_file in $grub_conf_files\n    do\n        if [[ -f $grub_file ]]; then\n            grep -q \"\\<initrd.*[[:space:]].*/initr.*${kernel_version}.*\" $grub_file\n            return $?\n        fi\n    done\n    \n    return 1\n}\n\nmount_runtime_partitions()\n{\n    for partition in proc dev sys\n    do\n        mount --bind \"/$partition\" \"$chroot_path/$partition\"\n    done\n}\n\nremove_persistent_net_rules()\n{\n    local _files=\"${chroot_path}/lib/udev/rules.d/75-persistent-net-generator.rules \\\n    ${chroot_path}/etc/udev/rules.d/70-persistent-net.rules\"\n    \n    for _file in $_files\n    do\n        backup_file $_file\n        rm -f $_file\n    done\n}\n\nreset_persistent_net_gen_rules()\n{\n    move_to_backup \"${chroot_path}/etc/udev/rules.d/75-persistent-net-generator.rules\"\n    chroot ${chroot_path} ln -f -s /dev/null /etc/udev/rules.d/75-persistent-net-generator.rules\n}\n\nremove_network_manager_rpm()\n{\n    trace \"Removing persistent net rules\"\n    \n    reset_persistent_net_gen_rules\n    \n    backup_file \"${chroot_path}/etc/udev/rules.d/70-persistent-net.rules\"\n    rm -f ${chroot_path}/etc/udev/rules.d/70-persistent-net.rules\n    \n    echo \"Removing NetworkManager ...\"\n    chroot ${chroot_path} rpm -e --nodeps NetworkManager\n    \n    # Remove network manager binary if exist.\n    local net_mngr_file=\"${chroot_path}/etc/init.d/NetworkManager\"\n    if [[ -f $net_mngr_file ]]; then\n        rm -f $net_mngr_file\n    fi\n}\n\nupdate_network_dhcp_file()\n{\n    local dhcp_file=\"${chroot_path}/etc/sysconfig/network/dhcp\"\n    if [[ -f $dhcp_file ]]; then\n        update_config_value $dhcp_file DHCLIENT_SET_HOSTNAME '\"no\"'\n        if [[ $telemetry_data != *\"dhclient\"* ]]; then\n            # The default value is empty.\n            # If empty, a linux VM by design searches for dhcpcd, then dhclient\n            update_config_value $dhcp_file DHCLIENT_BIN '\"dhclient\"'\n        fi\n    fi\n}\n\nupdate_network_file()\n{\n    local network_file=\"${chroot_path}/etc/sysconfig/network\"\n    if [[ -f $network_file ]]; then\n        backup_file $network_file\n        update_config_value $network_file \"NETWORKING\" \"yes\"\n        remove_config_entry $network_file \"GATEWAY\"\n        update_config_value_if_exists $network_file \"GATEWAYDEV\" \"eth0\"\n    else\n        echo \"NETWORKING=yes\" > $network_file\n        echo \"HOSTNAME=localhost.localdomain\" >> $network_file\n    fi\n}\n\n#@1 - kernel image name or path\nis_kernel_image_in_use()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local kernel_image=$(basename $1)\n    local grub_conf_files=\"$chroot_path/boot/grub/menu.lst \\\n            $chroot_path/boot/grub/grub.conf \\\n            $chroot_path/boot/grub/grub.cfg \\\n            $chroot_path/boot/grub2/grub.cfg \\\n            $_grub2_efi_path/menu.lst \\\n            $_grub2_efi_path/grub.conf \\\n            $_grub2_efi_path/grub.cfg\"\n    \n    for grub_file in $grub_conf_files\n    do\n        if [[ -f $grub_file ]] && \n        grep -q \"\\<initrd.*[[:space:]].*/${kernel_image}\\>\" $grub_file; then\n            trace \"${kernel_image} found in $grub_file\"\n            return 0\n        fi\n    done\n    \n    return 1\n}\n\n#@1 - module name\nverify_hv_drivers_in_module()\n{\n    [[ -z \"$1\" ]] && return 0\n    \n    local kernel_version=$1\n    trace \"Checking hyper-v drivers in the kernel $kernel_version\"\n    \n    for driver_name in hv_vmbus hv_storvsc hv_netvsc\n    do\n        chroot $chroot_path modinfo -k $kernel_version $driver_name\n        [[ $? -ne 0 ]] && throw_error $_E_AZURE_SMS_HV_DRIVERS_MISSING $kernel_version\n        \n        trace \"$driver_name available in the kernel.\"\n    done\n    \n    return 0\n}\n\n#@1 - kernel image file path\nverify_hv_drivers_in_kernel_image()\n{\n    [[ -z \"$1\" ]] && return 1\n    \n    local kernel_image_name=$(basename $1)\n    local ls_image=$(chroot $chroot_path lsinitrd /boot/$kernel_image_name)\n    \n    trace \"Checking hyper-v drivers in the image $kernel_image_name\"\n    \n    for hv_driver in hv_vmbus hv_storvsc hv_netvsc\n    do\n        echo $ls_image | grep -q \"${hv_driver}.ko\"\n        [[ $? -ne 0 ]] && return 1\n    done\n    \n    add_am_hydration_log \"$kernel_image_name Hyper-V Drivers Status\" \"All Hyper-V drivers already present.\"\n    trace \"hyper-v drivers present in $kernel_image_name\"\n    \n    return 0\n}\n\n#@1 - Kernel version\n#@2 - Kernel image file path\ngenerate_initrd_image()\n{\n    [[ -z \"$1\" ]] && return 1\n    [[ -z \"$2\" ]] && return 1\n    \n    local hv_drivers=\"hv_vmbus hv_storvsc hv_netvsc\"\n    local kernel_image=$(basename $2)\n    local kernel_image_path=/boot/$kernel_image\n\n    trace \"start re-generating kernel image $kernel_image_path with version $1 ...\"\n    chroot $chroot_path dracut -f --add-drivers \"$hv_drivers\" $kernel_image_path $1\n    if [[ $? -ne 0 ]]; then\n        # We throw an error in dracut step for migration.\n        # TODO: Propagate this error up and handle so Migration passes but user\\CSS knows step to take.\n        # This will be a multi phase \\ step error code bitmap. Since steps are independent of \n        # each other.\n        trace \"WARNING: Could not perform dracut and generate image step.\"\n        throw_error $_E_AZURE_SMS_INITRD_IMAGE_GENERATION_FAILED $1\n    else\n        trace \"successfully generated the image!\"\n    fi\n    \n    return 0\n}\n\n#@1 - grub options to add\n#@2 - grub options to remove\nmodify_grub_config()\n{\n    local _grub_path=\"$chroot_path/boot/grub/menu.lst\"\n    local opts_to_comment=\"password --encrypted\"\n\n    if [ \"$firmware_type\" = \"UEFI\" ]; then\n        if [ -f \"$_grub2_efi_path/grub.conf\" ]; then\n            _grub_path=\"$_grub2_efi_path/grub.conf\"\n        elif [ -f \"$_grub2_efi_path/menu.lst\" ]; then\n            _grub_path=\"$_grub2_efi_path/menu.lst\"\n        elif [ -f \"$_grub2_efi_path/grub.cfg\" ]; then\n            _grub_path=\"$_grub2_efi_path/grub.cfg\"\n        fi\n    fi\n\n    [[ ! -f $_grub_path ]] && _grub_path=\"$chroot_path/boot/grub/grub.conf\"\n    echo \"Grub File: $_grub_path\"\n\n    [[ ! -f $_grub_path ]] && throw_error $_E_AZURE_SMS_CONF_MISSING $(basename $_grub_path)\n        \n    remove_grub_cmd_options \"$opts_to_remove\" $_grub_path\n    add_grub_cmd_options \"$opts_to_add\" $_grub_path\n    comment_config_setting \"$opts_to_comment\" $_grub_path\n\n    if [[ $src_distro == *\"SLES11\"* ]]; then\n        echo \"Adding additonal lines for SLES11:\"\n        append_config_line_parameter \"serial --unit=0 --speed=115200 --parity=no\" $_grub_path\n        append_config_line_parameter \"terminal --timeout=15 serial console\" $_grub_path\n    fi\n}\n\n#@1 - grub options to add\n#@2 - grub config setting name\n#@3 - grub options to remove\nmodify_grub2_config()\n{\n    local _grub2_path=\"$chroot_path/boot/grub2/grub.cfg\"\n\n    if [ \"$firmware_type\" = \"UEFI\" ]; then\n        if [ -f \"$_grub2_efi_path/grub.cfg\" ]; then\n            _grub2_path=\"$_grub2_efi_path/grub.cfg\"\n        elif [ -f \"$_grub2_efi_path/menu.lst\" ]; then\n            _grub2_path=\"$_grub2_efi_path/menu.lst\"\n        elif [ -f \"$_grub2_efi_path/grub.conf\" ]; then\n            _grub2_path=\"$_grub2_efi_path/grub.conf\"\n        fi\n    fi\n\n    echo \"Grub File: $_grub2_path Setting Name: $2 Add: $1 Remove: $3\"\n    [[ ! -f $_grub2_path ]] && _grub2_path=\"$chroot_path/boot/grub/grub.cfg\"\n    [[ ! -f $_grub2_path ]] && throw_error $_E_AZURE_SMS_CONF_MISSING $(basename $_grub2_path)\n    \n    modify_grub2_config_helper \"$1\" \"$2\" \"$3\" $_grub2_path\n\n    # Additionally change grub.cfg file located at grub and grub2 folder. \n    if [[ -f \"$chroot_path/boot/grub2/grub.cfg\" && $_grub2_path != \"$chroot_path/boot/grub2/grub.cfg\" ]]; then\n        modify_grub2_config_helper \"$1\" \"$2\" \"$3\" \"$chroot_path/boot/grub2/grub.cfg\"\n    fi\n\n    if [[ -f \"$chroot_path/boot/grub/grub.cfg\" && $_grub2_path != \"$chroot_path/boot/grub/grub.cfg\" ]]; then\n        modify_grub2_config_helper \"$1\" \"$2\" \"$3\" \"$chroot_path/boot/grub/grub.cfg\"\n    fi\n}\n\n#@1 - grub options to add\n#@2 - grub config setting name\n#@3 - grub options to remove\n#@4 - grub config file\nmodify_grub2_config_helper()\n{\n    _grub2_path=\"$4\"\n\n    add_am_hydration_log \"Serial Console - $_grub2_path Remove\" \"$3\"\n    add_am_hydration_log \"Serial Console $_grub2_path Add\" \"$2 - $1\"\n\n    if [[ ! -z \"$3\" ]]; then\n        remove_grub2_cmd_options \"$3\" $_grub2_path\n        remove_grub2_config_options \"$3\" $2\n    fi\n    \n    if [[ ! -z \"$1\" ]]; then\n        add_grub2_config_options \"$1\" \"$2\"\n        add_grub2_cmd_options \"$1\" $_grub2_path\n    fi\n\n    local opts_to_comment=\"password --encrypted\"\n    comment_config_setting \"$opts_to_comment\" $_grub2_path\n}\n\nupdate_vm_repositories()\n{\n    case $src_distro in\n        CENTOS6*)\n            # Bullet 8 - https://docs.microsoft.com/en-us/azure/virtual-machines/linux/create-upload-centos#centos-6x\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/CentOS-Base.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS6-Base.repo\" \"$sources_list_file\"\n        ;;\n        CENTOS7*)\n            # Bullet 6 - https://docs.microsoft.com/en-us/azure/virtual-machines/linux/create-upload-centos#centos-70\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/CentOS-Base.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS7-Base.repo\" \"$sources_list_file\"\n        ;;\n        CENTOS8*)\n            # Not documented. Replicated from VM created through platform image.\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/CentOS-Base.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS8-Base.repo\" \"$sources_list_file\"\n        ;;\n        CENTOS9*)\n        # Not documented. Replicated from VM created through platform image.\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/CentOS-Base.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/CentOS9-Base.repo\" \"$sources_list_file\"\n        ;;\n        OL6*)\n            # https://public-yum.oracle.com/public-yum-ol6.repo\n            # https://docs.microsoft.com/en-us/azure/virtual-machines/linux/oracle-create-upload-vhd#oracle-linux-installation-notes\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/public-yum-ol6.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol6.repo\" \"$sources_list_file\"\n        ;;\n        OL7*)\n            # https://public-yum.oracle.com/public-yum-ol7.repo\n            # https://docs.microsoft.com/en-us/azure/virtual-machines/linux/oracle-create-upload-vhd#oracle-linux-installation-notes\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/public-yum-ol7.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol6.repo\" \"$sources_list_file\"\n        ;;\n        OL8*)\n            # Not documented. Replicated from VM created through platform image.\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/public-yum-ol8.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol8.repo\" \"$sources_list_file\"\n        ;;\n        OL9*)\n            # Not documented. Replicated from VM created through platform image.\n            sources_list_file=\"$chroot_path/etc/yum.repos.d/public-yum-ol9.repo\"\n            backup_file $sources_list_file\n            copy_file \"/usr/local/AzureRecovery/public-yum-ol9.repo\" \"$sources_list_file\"\n        ;;\n        UBUNTU*)\n            # https://docs.microsoft.com/en-us/azure/virtual-machines/linux/create-upload-ubuntu#manual-steps\n            sources_list_file=\"$chroot_path/etc/apt/sources.list\"\n            copy_file \"$sources_list_file\" \"$(sources_list_file)_azr_sms_bak\"\n            sed -i 's/http:\\/\\/archive\\.ubuntu\\.com\\/ubuntu\\//http:\\/\\/azure\\.archive\\.ubuntu\\.com\\/ubuntu\\//g' \"$sources_list_file\"\n            sed -i 's/http:\\/\\/[a-z][a-z]\\.archive\\.ubuntu\\.com\\/ubuntu\\//http:\\/\\/azure\\.archive\\.ubuntu\\.com\\/ubuntu\\//g' \"$sources_list_file\"\n        ;;\n    esac\n}\n\nunset base_linuxga_path\ninstall_linux_guest_agent()\n{\n    ga_uuid=$(uuidgen)\n    base_linuxga_path=\"var/ASRLinuxGA-$ga_uuid\"\n\t\n\tif [[ ! -d $chroot_path/$base_linuxga_path ]]; then\n        trace \"Base linux guest agent packages directory doesn't exist'. Creating $chroot_path/$base_linuxga_path\"\n        mkdir $chroot_path/$base_linuxga_path\n    fi\n\t\n    validate_guestagent_prereqs\n    update_vm_repositories\n\n    echo \"Hydration Being Performed on the VM. $(date)\" >> \"$chroot_path/$base_linuxga_path/ASRLinuxGA.log\"\n\n    # If python is absent, guest agent installation will not work.\n    # We continue to push the script to target VM to facilitate easier installation\n    if [[ $telemetry_data != *\"systemctl\"* ]]; then\n        enable_installga_service\n    else\n        enable_installga_chkconfig\n    fi\n\t\n    enable_postlogin_installga\n\n    add_am_hydration_log \"Guest agent installation logs location\" \"/$base_linuxga_path/ASRLinuxGA.log\"\n\n    linuxgadir=\"/usr/local/AzureRecovery/WALinuxAgentASR/WALinuxAgent-master\"\n    targetgadir=\"$chroot_path/$base_linuxga_path/WALinuxAgentASR/\"\n\n    if [[ ! -d \"$linuxgadir\" ]]; then\n        trace \"Folder containing Guest agent binaries is not present.\"\n        return 1;\n    fi\n\n    if [[ ! -d $targetgadir ]]; then\n        trace \"Target guest agent folder doesn't exist. Creating $targetgadir\"\n        mkdir $targetgadir\n    fi\n\n    CopyDirectory $linuxgadir $targetgadir\n    if [[ $? -ne 0 ]]; then\n        trace \"Could not copy LinuxGuestAgent installation directory to target location.\"\n        return 1;\n    fi\n\n    copy_file \"/usr/local/AzureRecovery/InstallLinuxGuestAgent.sh\" \"$chroot_path/$base_linuxga_path/InstallLinuxGuestAgent.sh\"\n    if [[ $? -ne 0 ]]; then\n        trace \"Could not copy LinuxGuestAgent installation file.\"\n        return 1;\n    fi\n\n    copy_file \"/usr/local/AzureRecovery/PythonSetupPrereqs.py\" \"$chroot_path/$base_linuxga_path/PythonSetupPrereqs.py\"\n    if [[ $? -ne 0 ]]; then\n        trace \"Could not copy python setup prereqs file.\"\n        # Don't fail.\n    fi\n\n    chmod +x $chroot_path/$base_linuxga_path/*\n}\n\nconfigure_dhcp_rhel()\n{\n    local ifcfg_dir=\"$chroot_path/etc/sysconfig/network-scripts\"\n    \n    # move the existing cscfg files to backup.\n    for _file in $(ls $ifcfg_dir/ifcfg-*)\n    do\n        local ifcfg_file=$(basename $_file)\n        \n        # ignore loop back ifcfg.\n        [[ \"$ifcfg_file\" = \"ifcfg-lo\" ]] && continue\n        \n        ifcfg_file=\"$ifcfg_dir/$ifcfg_file\"\n        move_to_backup_dir $ifcfg_file\n    done\n    \n    local default_dhcp_cscfg=\"$ifcfg_dir/ifcfg-eth0\"\n    echo \"DEVICE=eth0\" > $default_dhcp_cscfg\n    echo \"ONBOOT=yes\" >> $default_dhcp_cscfg\n    echo \"DHCP=yes\" >> $default_dhcp_cscfg\n    echo \"BOOTPROTO=dhcp\" >> $default_dhcp_cscfg\n    echo \"TYPE=Ethernet\" >>  $default_dhcp_cscfg\n    echo \"USERCTL=no\" >>  $default_dhcp_cscfg\n    echo \"PEERDNS=yes\" >>  $default_dhcp_cscfg\n    echo \"IPV6INIT=no\" >> $default_dhcp_cscfg\n}\n\nconfigure_dhcp_sles()\n{\n    local ifcfg_dir=\"$chroot_path/etc/sysconfig/network\"\n    \n    # move the existing cscfg files to backup.\n    for _file in $(ls $ifcfg_dir/ifcfg-*)\n    do\n        local ifcfg_file=$(basename $_file)\n        \n        # ignore loop back ifcfg.\n        [[ \"$ifcfg_file\" = \"ifcfg-lo\" ]] && continue\n        \n        ifcfg_file=\"$ifcfg_dir/$ifcfg_file\"\n        move_to_backup_dir $ifcfg_file\n    done\n    \n    local default_dhcp_cscfg=\"$ifcfg_dir/ifcfg-eth0\"\n    echo \"BOOTPROTO='dhcp'\"  >$default_dhcp_cscfg\n    echo \"MTU='' \" >> $default_dhcp_cscfg\n    echo \"REMOTE_IPADDR='' \" >>$default_dhcp_cscfg\n    echo \"STARTMODE='onboot'\" >>$default_dhcp_cscfg\n}\n\nconfigure_dhcp_ubuntu()\n{\n    _interfaces_file=\"$chroot_path/etc/network/interfaces\"\n    \n    # Backup the original interfaces file\n    backup_file \"$_interfaces_file\"\n    \n    # Create new interfaces file\n    echo \"# The loopback network interface\" > $_interfaces_file\n    echo \"auto lo\" >> $_interfaces_file\n    echo \"iface lo inet loopback\" >> $_interfaces_file\n    echo \"\" >> $_interfaces_file\n    echo \"# The primary network interface\" >> $_interfaces_file\n    echo \"auto eth0\" >> $_interfaces_file\n    echo \"iface eth0 inet dhcp\" >> $_interfaces_file\n}\n\ncreate_dhcp_netplan_config_and_apply()\n{\n    # As a workaround, taking a random filename for netplan dhcp configuration.\n    # As soon as Azure Compute publishes steps for preparing Ubuntu 18.04 LTS\n    # we will follow those instructions to prepare netplan configuration.\n    local dhcp_netplan_file=\"$chroot_path/etc/netplan/50-azure_migrate_dhcp.yaml\"\n    if [[ -f $dhcp_netplan_file ]]; then\n        echo \"DHCP netplan configuration for Azure migrate is already exist.\"\n        return;\n    fi\n    \n    echo \"# This is generated for Azure SMS to make NICs DHCP in Azure.\" > $dhcp_netplan_file\n    echo \"network:\" >> $dhcp_netplan_file\n    echo \"    version: 2\" >> $dhcp_netplan_file\n    echo \"    ethernets:\" >> $dhcp_netplan_file\n    echo \"        ephemeral:\" >> $dhcp_netplan_file\n    echo \"            dhcp4: true\" >> $dhcp_netplan_file\n    echo \"            match:\" >> $dhcp_netplan_file\n    echo \"                driver: hv_netvsc\" >> $dhcp_netplan_file\n    echo \"                name: '!eth0'\" >> $dhcp_netplan_file\n    echo \"            optional: true\" >> $dhcp_netplan_file\n    echo \"        hotpluggedeth0:\" >> $dhcp_netplan_file\n    echo \"            dhcp4: true\" >> $dhcp_netplan_file\n    echo \"            match:\" >> $dhcp_netplan_file\n    echo \"                driver: hv_netvsc\" >> $dhcp_netplan_file\n    echo \"                name: 'eth0'\" >> $dhcp_netplan_file\n    \n    trace \"Applying the dhcp netplan configuration... \"\n    chroot $chroot_path netplan apply\n    if [[ $? -eq 0 ]]; then\n        trace \"netplan with dhcp settings applied!\"\n    else\n        trace \"WARNING: netplan couldn't apply dhcp settings.\"\n    fi\n}\n\nenable_network_service()\n{\n    trace \"Making network service to start at boot time.\"\n\n    case $src_distro in\n        RHEL6*|CENTOS6*|OL6*)\n            chroot $chroot_path chkconfig network on\n            ;;\n        RHEL7*|CENTOS7*|RHEL8*|RHEL9*|CENTOS8*|CENTOS9*|OL7*|OL8*|OL9*)\n            chroot $chroot_path systemctl enable network\n            ;;\n        *)\n            # For rest no operation.\n            ;;\n        esac\n}\n\nverify_src_os_version()\n{\n    find_src_distro\n    \n    local supported_distros=\"OL6 OL7 OL8 OL9 \\\n          RHEL6 RHEL7 RHEL8 RHEL9 \\\n          CENTOS6 CENTOS7 CENTOS8 CENTOS9 \\\n          SLES11 SLES12 SLES15 \\\n          UBUNTU14 UBUNTU16 UBUNTU18 UBUNTU19 UBUNTU20 UBUNTU21 UBUNTU22 \\\n          DEBIAN7 DEBIAN8 DEBIAN9 DEBIAN10 DEBIAN11 KALI-ROLLING\"\n\n    add_am_hydration_log \"Identified OS Version\" $src_distro\n\n    for distro in $supported_distros\n    do\n        [[ \"$src_distro\" =~ \"${distro}-\"* ]] && [[ \"$src_distro\" == *\"-64\" ]] && return\n    done\n\n    throw_error $_E_AZURE_SMS_OS_UNSUPPORTED $src_distro\n}\n\nverify_requited_tools()\n{\n    # Prereqs:\n    # Kernel image update with hyper-V drivers: dracut/mkinitrd, lsinitrd, modinfo\n    # Networking Changes: dhclient/dhcpcd\n    # Guest Agent: systemctl/service, python 2.6+ (Python to be checked later as minor version is also verified)\n    # For all the tools absence, errors will be thrown out at a later stage depending on need.\n\n    local tools_to_verify=\"lsinitrd dracut modinfo dhclient systemctl\"\n\n    verify_tools \"$tools_to_verify\"\n\n    # For each tool, check for backup options if primary tool is absent.\n    if [[ $telemetry_data == *\"dracut\"* ]]; then\n        verify_tools \"mkinitrd\"\n        # Don't fail immediately if mkinitrd is also absent.\n        # Check if kernel and kernel image both contain Hyper-V drivers already.\n        # If not, Return ToolsMissing Error. \n    fi\n\n    if [[ $telemetry_data == *\"dhclient\"* ]]; then\n        verify_tools \"dhcpcd\"\n        # Return a soft warning that dhcp might not work if both are absent.\n        # Not sending tools missing error as it will be hard failure.\n    fi\n\n    if [[ $telemetry_data == *\"systemctl\"* ]]; then\n        verify_tools \"service\"\n        # Return a soft warning that guest agent installation might not work if both are absent.\n    fi\n}\n\nverify_uefi_bootloader_files()\n{\n    config_file_name=\"\"\n    bootloader_folder_path=\"$chroot_path/boot/efi/EFI/boot\"\n\n    if [ \"$firmware_type\" = \"UEFI\" ]; then\n        if [ ! -f \"$_grub2_efi_path/bootx64.efi\" ]; then\n            if [ -f \"$_grub2_efi_path/shimx64.efi\" ]; then\n                copy_file \"$_grub2_efi_path/shimx64.efi\" \"$_grub2_efi_path/bootx64.efi\"\n            elif [ -f \"$_grub2_efi_path/grubx64.efi\" ]; then\n                copy_file \"$_grub2_efi_path/grubx64.efi\" \"$_grub2_efi_path/bootx64.efi\"\n            elif [ -f \"$_grub2_efi_path/grub.efi\" ]; then\n                copy_file \"$_grub2_efi_path/grub.efi\" \"$_grub2_efi_path/bootx64.efi\"\n            else\n                if [ ! -d \"$bootloader_folder_path\" ] || [ ! -f \"$bootloader_folder_path/bootx64.efi\" ]; then\n                    echo \"efi file is absent on source disk which will lead to boot failure in Gen2 vm.\"\n                    add_telemetry_data \"bootx64.efi\"\n                    add_am_hydration_log \"Missing UEFI firmware .efi file\" \"$bootloader_folder_path/bootx64.efi\"\n                    # Treat the VM as BIOS to increase chances of boot\n                    # This may happpen for customers who may have accidentally placed grub.cfg \n                    # in /boot/efi/EFI/<distribution> folder. Warn the customer.\n                    firmware_type=\"BIOS\"\n                    return\n                fi\n            fi\n        fi\n\n        if [ -f \"$_grub2_efi_path/grub.cfg\" ]; then\n            config_file_name=\"grub.cfg\"\n            copy_file \"$_grub2_efi_path/grub.cfg\" \"$_grub2_efi_path/bootx64.cfg\"\n        elif [ -f \"$_grub2_efi_path/grub.conf\" ]; then\n            config_file_name=\"grub.conf\"\n            copy_file \"$_grub2_efi_path/grub.conf\" \"$_grub2_efi_path/bootx64.conf\"\n        else\n            echo \"grub config file not found in grub folder.\"\n        fi\n\n        # Folder needs to be explicitly added for Ubuntu/Debian/RHEL6/CENTOS6.\n        # Checking and adding for other distros too if not added.\n        if [ ! -d \"$bootloader_folder_path\" ]; then\n            CopyDirectory \"$_grub2_efi_path/\" \"$bootloader_folder_path\"\n        else\n            trace \"BOOT folder is present on the disk.\"\n            if [ ! -f  \"$bootloader_folder_path/bootx64.efi\" ]; then\n                copy_file \"$_grub2_efi_path/bootx64.efi\" \"$bootloader_folder_path/bootx64.efi\"\n            fi\n\n            # bootx64.conf required for RHEL6/CENTOS6. Copying for other distros too.\n            if [ $config_file_name = \"grub.cfg\" ] && [ ! -f \"$bootloader_folder_path/bootx64.cfg\" ]; then\n                copy_file \"$_grub2_efi_path/bootx64.cfg\" \"$bootloader_folder_path/bootx64.cfg\"\n            elif [ $config_file_name = \"grub.conf\" ] && [ ! -f \"$bootloader_folder_path/bootx64.conf\" ]; then\n                copy_file \"$_grub2_efi_path/bootx64.conf\" \"$bootloader_folder_path/bootx64.conf\"\n            fi\n        fi\n    else\n        trace \"Boot folder verification not required for BIOS.\"\n    fi\n\n}\n\n#@1 - Kernel version\n#@2 - Kernel image file path\nmkinitrd_generate_initrd_image()\n{\n    trace \"Updating $1's image $2\"\n    newstr=`sed  -n \"/^[[:space:]]*INITRD_MODULES*/p \" $chroot_path/etc/sysconfig/kernel`\n\n    hypervdrivers=\"hv_vmbus hv_storvsc hv_netvsc\"\n    for driver_name in $hypervdrivers\n    do\n        echo \"$newstr\"|grep -q \"$driver_name\"\n        if [[ $? -ne 0 ]]; then\n            echo \"HyperV drivers are not present, adding them to INITRD_MODULES.\"\n            newstr=`echo $newstr|awk -F\\\" ' {print $1\"\\\"\"$2 \" hv_vmbus hv_storvsc hv_netvsc\" \"\\\"\"}'`\n            sed  -i  \"s/^[[:space:]]*INITRD_MODULES=\\\".*\\\"/$newstr/\" $chroot_path/etc/sysconfig/kernel\n            break\n        fi\n    done\n\n    mount_runtime_partitions\n    sleep 5\n    chroot $chroot_path mkinitrd\n}\n\nverify_generate_initrd_images()\n{\n    case \"$src_distro\" in\n    UBUNTU14*|UBUNTU16*|UBUNTU18*|UBUNTU19*|UBUNTU20*|UBUNTU21*|UBUNTU22*|DEBIAN*|KALI-ROLLING*)\n        # Supported Ubuntu & Debian distros will have\n        # hyper-v drivers build-in to the kernel image,\n        # so skipping this step for these distros.\n        add_am_hydration_log \"Kernel image Hyper-V updates\" \"Skipped for Ubuntu\"\n        return 0\n        ;;\n    *)\n        # Will verify and regenerate initrd images for rest\n        # of the supported distros, and control won't come\n        # this far for unsupported distros.\n        ;;\n    esac\n    \n    trace \"$(ls -d ${chroot_path}/lib/modules/*)\"\n    \n    # Version sort the kernel images.\n    latest_kernel_in_use=$(ls $chroot_path/boot/vmlinuz* | sed 's/\\/mnt\\/sms_azure_chroot\\/boot\\/vmlinuz-//' | sed 's/[.-][[:alpha:]][[:alnum:][:punct:]]*//' | sort -V | tail -n 1)\n    trace \"Latest Kernel in use: $latest_kernel_in_use\"\n\n    add_am_hydration_log \"Latest Kernel\" \"$latest_kernel_in_use\"\n\n    local last_error_in_generate_initrd_image=0\n    for mod_path in $(ls -d ${chroot_path}/lib/modules/*)\n    do\n        [[ ! -d $mod_path ]] && continue\n        [[ ! -f $mod_path/modules.dep ]] && continue\n        \n        local kernel_version=$(basename $mod_path)\n        is_kernel_in_use $kernel_version\n        if [[ $? -ne 0 ]]; then\n            trace \"$kernel_version not found in grub.cfg\"\n            if [[ $kernel_version != *\"$latest_kernel_in_use\"* ]]; then\n                trace \"Skipping $kernel_version.\"\n                add_am_hydration_log \"$kernel_version\" \"Skipped. Inactive kernel.\"\n                continue\n            else\n                add_am_hydration_log \"$kernel_version\" \"Modified. Latest Kernel\"\n                trace \"Latest kernel $kernel_version is in use. It won't be skipped.\"\n            fi\n        else\n            add_am_hydration_log \"$kernel_version\" \"Modifying. Active Kernel\"\n        fi\n\n        # Checking if hyper-v drivers are available\n        # in the kernel, if not then error will be thrown.\n        verify_hv_drivers_in_module $kernel_version\n        \n        for kernel_image_file in $(ls ${chroot_path}/boot/initr*${kernel_version}*)\n        do\n            is_kernel_image_in_use $kernel_image_file\n            if [[ $? -ne 0 ]] ; then \n                trace \"$kernel_image_file is not present in grub.cfg\"\n                if [[ $kernel_version == *\"$latest_kernel_in_use\"* ]] && [[ $kernel_image_file == *\"initr\"*\"$kernel_version.img\"* ]]; then\n                    # Add hyper-V drivers in the primary image file of the kernel in use.\n                    trace \"$kernel_version seems to be in use and won't be skipped\"\n                    add_am_hydration_log \"$kernel_image_file Kernel Image\" \"Modifying. Kernel in use.\"\n                else\n                    trace \"Skipping $kernel_version's image file $kernel_image_file\"\n                    add_am_hydration_log \"$kernel_image_file Kernel Image\" \"Skipped. Kernel not in use.\"\n                    continue\n                fi\n            fi\n            \n            verify_hv_drivers_in_kernel_image $kernel_image_file\n            [[ $? -eq 0 ]] && continue\n\n            trace \"Re-generating $kernel_image_file with hyper-v drivers\"\n\n            if [[ $telemetry_data != *\"dracut\"* ]]; then\n                generate_initrd_image $kernel_version $kernel_image_file\n            elif [[ $telemetry_data != \"mkinitrd\" ]]; then\n                mkinitrd_generate_initrd_image $kernel_version $kernel_image_file\n            else\n                trace \"Kernel Image doesn't have the necessary drivers.\"\n                trace \"dracut and mkinitrd - tools to update kernel images with hyper-V drivers were found absent\"\n                trace \"Fail the hydration with tools missing error.\"\n\n                add_am_hydration_log \"$kernel_image_file Kernel image update failure\" \"No dracut or mkinitrd.\"\n\n                if [[ $src_distro == *\"SLES11\"* ]]; then\n                    throw_error $_E_AZURE_SMS_TOOLS_MISSING \"mkinitrd\"\n                else\n                    throw_error $_E_AZURE_SMS_TOOLS_MISSING \"dracut\"\n                fi\n            fi\n\n            add_am_hydration_log \"$kernel_image_file Kernel Image\" \"Hyper-V drivers update - Success.\"\n\n        done\n    done\n}\n\n#@1 - Config value\n#@2 - File name\n# Appends an entire line to the file if absent\nappend_config_line_parameter()\n{\n    _line_number=$(sed -n \"/$1/=\" \"$2\")\n    if [[ ! -z $_line_number ]]; then\n        echo \"$1 is already present in $2 at $_line_number\"\n    else\n        echo \"$1 is absent in $2. Appending the line\"\n        sed -i \"2i$1\" \"$2\"\n    fi\n}\n\n# Enable Getty on ttyS0 for SLES11\nset_sles11_inittab()\n{\n    uncomment_config_setting \"S0:12345:respawn\" \"$chroot_path/etc/inittab\"\n    chroot $chroot_path \"telinit q\"\n}\n\nset_serial_console_grub_options()\n{\n    trace \"Updating boot grub options to redirect serial console logs ...\"\n    \n    local opts_to_remove=\"rhgb quiet crashkernel=auto acpi=0\"\n    local opts_to_add=\"rootdelay=300 earlyprintk=ttyS0 console=ttyS0 numa=off\"\n    case $src_distro in\n    RHEL6*|CENTOS6*|OL6*)\n        modify_grub_config \"$opts_to_add\" \"$opts_to_remove\"\n        ;;\n    SLES11*)\n        modify_grub_config \"$opts_to_add\" \"$opts_to_remove\"\n        set_sles11_inittab\n        ;;\n    UBUNTU14*|UBUNTU16*|UBUNTU18*|UBUNTU19|UBUNTU20*|UBUNTU21*|UBUNTU22*)\n        opts_to_add=\"splash quiet rootdelay=300 earlyprintk=ttyS0,115200 console=ttyS0,115200n8 console=tty1\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX_DEFAULT\" \"$opts_to_remove\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX\" \"$opts_to_remove\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL_OUTPUT\" \"\"\n        modify_grub2_config \"--stop=1 --parity=no --word=8 --unit=0 --speed=115200 serial\" \"GRUB_SERIAL_COMMAND\" \"\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL\" \"\"\n        ;;\n    DEBIAN*|KALI-ROLLING*)\n        opts_to_add=\"splash quiet rootdelay=300 earlyprintk=ttyS0,115200 console=ttyS0,115200n8 console=tty1\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX_DEFAULT\" \"$opts_to_remove\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX\" \"$opts_to_remove\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL_OUTPUT\" \"\"\n        modify_grub2_config \"--stop=1 --parity=no --word=8 --unit=0 --speed=115200 serial\" \"GRUB_SERIAL_COMMAND\" \"\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL\" \"\"\n        ;;\n    SLES12*|SLES15*)\n        opts_to_add=\"rootdelay=300 earlyprintk=ttyS0 console=ttyS0\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL_OUTPUT\" \"\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL\" \"\"\n        ;;\n    RHEL7*|CENTOS7*|OL7*|OL8*|OL9*|RHEL8*|RHEL9*|CENTOS8*|CENTOS9*)\n        #Following options are taken from official Azure document for RHEL7.\n        #https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/serial-console-grub-single-user-mode#grub-access-in-rhel\n        #and \n        #https://docs.microsoft.com/en-us/azure/virtual-machines/troubleshooting/serial-console-grub-proactive-configuration\n        opts_to_add=\"rootdelay=300 console=tty1 console=ttyS0,115200n8 earlyprintk=ttyS0,115200 earlyprintk=ttyS0 net.ifnames=0\"\n        modify_grub2_config \"$opts_to_add\" \"GRUB_CMDLINE_LINUX\" \"$opts_to_remove\"\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL_OUTPUT\" \"\"\n        modify_grub2_config \"--stop=1 --parity=no --word=8 --unit=0 --speed=115200 serial\" \"GRUB_SERIAL_COMMAND\" \"\"\n        # This value should be Serial console. But our text replacement code reverses order\n        # So writing console serial which should become serial console when committed.\n        modify_grub2_config \"console serial\" \"GRUB_TERMINAL\" \"\"\n        ;;\n    *)\n        throw_error $_E_AZURE_SMS_OS_UNSUPPORTED $src_distro\n        ;;\n    esac\n    trace \"Successfully updated boot grub options!\"\n}\n\nenable_systemd_on_startupscipt()\n{\n    local _systemd_cofig_file=\"$chroot_path/lib/systemd/system/${_AM_STARTUP_}.service\"\n    if [[ ! -d $chroot_path/lib/systemd ]]; then\n        _systemd_cofig_file=\"$chroot_path/usr/lib/systemd/system/${_AM_STARTUP_}.service\"\n    fi\n    \n    if [[ -f $_systemd_cofig_file ]]; then\n        trace \"Startup script is already configured!\"\n        return 0\n    fi\n        \n    echo \"[Unit]\" > $_systemd_cofig_file\n    echo \"Description=Azure migrate startup script to create nic config.\" >> $_systemd_cofig_file\n    echo \"After=network.target\" >> $_systemd_cofig_file\n    echo \"\" >> $_systemd_cofig_file\n    echo \"[Service]\" >> $_systemd_cofig_file\n    echo \"ExecStart=${_AM_SCRIPT_DIR_}/${_STARTUP_SCRIPT_} start\" >> $_systemd_cofig_file\n    echo \"\" >> $_systemd_cofig_file\n    echo \"[Install]\" >> $_systemd_cofig_file\n    echo \"WantedBy=default.target\" >> $_systemd_cofig_file\n\n    trace \"Adding startup script.\"\n    chroot $chroot_path systemctl enable \"${_AM_STARTUP_}.service\"\n    if [[ $? -eq 0 ]]; then\n        trace \"Successfully added startup script!\"\n    else\n        trace \"WARNING: Could not add startup script for DHCP.\"\n    fi\n\n    return 0\n}\n\nenable_chkconfig_on_startupscript()\n{\n    local _chkconfig_startup_file=\"/etc/init.d/${_AM_STARTUP_}\"\n    if [[ -h \"${chroot_path}$_chkconfig_startup_file\" ]]; then\n        trace \"Startup script is already configured!\"\n        return;\n    fi\n    \n    local _startup_script_path=\"${_AM_SCRIPT_DIR_}/${_STARTUP_SCRIPT_}\"\n    chroot $chroot_path ln -s $_startup_script_path $_chkconfig_startup_file\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Could not create start-up script.\"\n        return 0\n    fi\n    \n    local _config_startup_cmd=\"\"\n    if chroot $chroot_path which chkconfig > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $chroot_path chkconfig --add ${_AM_STARTUP_}\"\n    elif chroot $chroot_path which update-rc.d > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $chroot_path update-rc.d ${_AM_STARTUP_} defaults\"\n    else\n        trace \"WARNING: No tools found to configure start-up script.\"\n        return 0\n    fi\n    \n    trace \"Adding startup script.\"    \n    $_config_startup_cmd > /dev/null 2>&1\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Could not add start-up script.\"\n    else\n        trace \"Successfully added startup script!\"\n    fi\n    \n    return 0\n}\n\ncreate_startup_scripts()\n{\n    trace \"Adding startup script to configure dhcp on migrated azure vm.\"\n    local startup_script_dir=$1\n    [[ -d $startup_script_dir ]] || mkdir $startup_script_dir \n    if [[ ! -d $startup_script_dir ]]; then\n        trace \"WARNING: Could not create ${startup_script_dir} for startup script.\"\n        return 1\n    fi\n    \n    local working_dir=$(cd $(dirname \"$0\") > /dev/null && pwd)\n    [[ -d \"$working_dir\" ]] || working_dir=/usr/local/AzureRecovery\n    \n    copy_file \"$working_dir/$_FIX_DHCP_SCRIPT_\" \"${startup_script_dir}/${_FIX_DHCP_SCRIPT_}\"\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Could not copy scripts to startup script directory.\"\n        return 1\n    fi\n    \n    # Startup script file\n    local _startup_script_path=\"$startup_script_dir/$_STARTUP_SCRIPT_\"\n    echo \"#!/bin/bash\n# This is for RHEL systems\n# processname: ${_AM_STARTUP_}\n# chkconfig: 2345 90 90\n# description: Azure migrate startup script to configure networks\n\n### BEGIN INIT INFO\n# Provides: ${_AM_STARTUP_}\n# Required-Start: \\$local_fs\n# Required-Stop: \\$local_fs\n# X-Start-Before: \\$network\n# X-Stop-After: \\$network\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Description: Azure migrate startup script to configure networks\n### END INIT INFO \" > $_startup_script_path\n\n    echo 'case \"$1\" in' >> $_startup_script_path\n    echo \"start)\" >> $_startup_script_path\n    echo \"${_AM_SCRIPT_DIR_}/${_FIX_DHCP_SCRIPT_} > ${_AM_SCRIPT_LOG_FILE_} 2>&1 ;;\" >> $_startup_script_path\n    echo \"*)\" >> $_startup_script_path\n    echo \";;\" >> $_startup_script_path\n    echo \"esac\" >> $_startup_script_path\n    echo \"\" >> $_startup_script_path\n    \n    # Execute permissions for the scripts\n    chmod +x $startup_script_dir/*\n    return $?\n}\n\nenable_installga_chkconfig()\n{\n    trace \"Adding guest agent installation service inside /etc/init.d\"\n    local asr_installga_exfile_path=\"$chroot_path/etc/init.d/${_AM_INSTALLGA_}\"\n    echo \"#!/bin/bash\n# This is for RHEL systems\n# processname: ${_AM_INSTALLGA_}\n# chkconfig: 2345 90 90\n# description: Azure migrate startup script to configure networks\n\n### BEGIN INIT INFO\n# Provides: ${_AM_INSTALLGA_}\n# Required-Start: \\$local_fs\n# Required-Stop: \\$local_fs\n# X-Start-Before: \\$network\n# X-Stop-After: \\$network\n# Default-Start: 2 3 4 5\n# Default-Stop: 0 1 6\n# Description: Azure migrate startup script to configure networks\n### END INIT INFO \" > $asr_installga_exfile_path\n\n    echo 'case \"$1\" in' >> $asr_installga_exfile_path\n    echo \"start)\" >> $asr_installga_exfile_path\n    echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $src_distro \\\"$base_linuxga_path\\\" $setup_tool_install\" >> $asr_installga_exfile_path\n    echo \";;\" >> $asr_installga_exfile_path\n    echo \"*)\" >> $asr_installga_exfile_path\n    echo \";;\" >> $asr_installga_exfile_path\n    echo \"esac\" >> $asr_installga_exfile_path\n    echo \"\" >> $asr_installga_exfile_path\n    \n    # Execute permissions for the scripts\n    chmod +x $asr_installga_exfile_path\n\n    local _chkconfig_gastartup_file=\"/etc/init.d/${_AM_INSTALLGA_}\"\n    if [[ -h \"${chroot_path}$_chkconfig_gastartup_file\" ]]; then\n        trace \"Startup script is already configured!\"\n        return;\n    fi\n\n    chroot $chroot_path ln -s $asr_installga_exfile_path $_chkconfig_gastartup_file\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Could not create start-up script.\"\n    fi\n    \n    local _config_startup_cmd=\"\"\n    if chroot $chroot_path which chkconfig > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $chroot_path chkconfig --add ${_AM_INSTALLGA_}\"\n    elif chroot $chroot_path which update-rc.d > /dev/null 2>1$ ;then\n        _config_startup_cmd=\"chroot $chroot_path update-rc.d ${_AM_INSTALLGA_} defaults\"\n    else\n        trace \"WARNING: No tools found to configure start-up script.\"\n        add_telemetry_data \"startup\"\n        return 0\n    fi\n    \n    trace \"Adding startup script.\"\n    $_config_startup_cmd > /dev/null 2>&1\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Could not add start-up script.\"\n        add_telemetry_data \"startup\"\n    else\n        trace \"Successfully added startup script!\"\n    fi\n\n    return $?\n}\n\nadd_startup_script_for_dhcp()\n{\n    local startup_script_dir=\"${chroot_path}${_AM_SCRIPT_DIR_}\"\n    create_startup_scripts $startup_script_dir\n    if [[ $? -ne 0 ]]; then\n        trace \"WARNING: Skip configuring startup script.\"\n        return 0;\n    fi\n    \n    case $src_distro in\n        RHEL6*|CENTOS6*|OL6*|SLES11*|UBUNTU14*|DEBIAN7*)\n            enable_chkconfig_on_startupscript\n            ;;\n        SLES12*|SLES15*|DEBIAN8*|DEBIAN9*|DEBIAN10*|DEBIAN11*|KALI-ROLLING*|RHEL7*|RHEL8*|RHEL9*|CENTOS7*|CENTOS8*|CENTOS9*|OL7*|OL8*|OL9*|UBUNTU16*|UBUNTU18*|UBUNTU19*|UBUNTU20*|UBUNTU21*|UBUNTU22*)\n            enable_systemd_on_startupscipt\n            ;;\n        *)\n            trace \"WARNING: Unknown distro '$src_distro' to configure startup script.\"\n            \n            trace \"Removing startup script directory '$startup_script_dir'.\"\n            rm -rf $startup_script_dir\n            ;;\n    esac\n}\n\nenable_postlogin_installga()\n{\n    target_profiled_file=\"$chroot_path/etc/profile.d/ASRLinuxGAStartup.sh\"\n\n    if [[ ! -d \"$chroot_path/etc/profile.d\" ]]; then\n        trace \"/etc/profile.d directory doesn't exist\"\n    else\n        echo \"#!/bin/bash\" >> $target_profiled_file\n        echo \"echo \\\"This is Azure Migrate One-Time Guest Agent Installation Setup.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"The service quietly exits if WALinuxAgent is already installed.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"If guest agent installation failed at pre-boot step due to python/installation prereqs not fulfilled, \\\"\" >> $target_profiled_file\n        echo \"echo \\\"this service is triggered post login to install WALinuxAgent using VM's repository.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"The service may prompt you to login using elevated bash shell for installation to proceed.\\\"\" >> $target_profiled_file\n        echo \"echo \\\"You can skip the installation, and can install manually, or retrigger the service by running\\\"\" >> $target_profiled_file\n        echo \"echo \\\"systemctl start asr-installga or service asr-installga start\\\"\" >> $target_profiled_file\n        echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $src_distro \\\"$base_linuxga_path\\\" $setup_tool_install >> /$base_linuxga_path/ASRLinuxGA.log\" >> $target_profiled_file\n        echo \"echo \\\"Installation process completed. Proceed with Login.\\\"\" >> $target_profiled_file\n        echo \"rm -f \\\"/etc/profile.d/ASRLinuxGAStartup.sh\\\"\" >> $target_profiled_file\n\n        trace \"/etc/profile.d post login startup file created.\"\t\n    fi\n}\n\nenable_installga_service()\n{\n    # Startup script to install azure guest agent.\n    local asr_installga_exfile_path=\"usr/local/${_AM_INSTALLGA_}/asr.installga\"\n\n    # Create a directory if it doesn't exist.\n    if [[ ! -d \"$chroot_path/usr/local/${_AM_INSTALLGA_}\" ]]; then\n        trace \"Creating a new directory /usr/local/${_AM_INSTALLGA_}\"\n        mkdir \"$chroot_path/usr/local/${_AM_INSTALLGA_}\"\n    fi\n    \n    if [[ -f $chroot_path/$asr_installga_exfile_path ]]; then\n        trace \"/usr/local/${_AM_INSTALLGA_}/asr.installga exists. Deleting the file.\"\n        rm $chroot_path/$asr_installga_exfile_path\n    fi\n \n    # Write execution commands for asr.installga executable.\n    trace \"Creating asr.installga for execution during boot.\"\n\n    setup_tool_install=\"install_setup_tools_false\"\n    if [[ $telemetry_data == *\"no-setuptools\"* ]]; then\n        setup_tool_install=\"install_setup_tools_true\"\n    fi\n\n    echo \"#!/bin/bash\" >> $chroot_path/$asr_installga_exfile_path\n    echo \"#This file is generated for execution during boot\" >> $chroot_path/$asr_installga_exfile_path\n    echo \"bash /$base_linuxga_path/InstallLinuxGuestAgent.sh $src_distro \\\"$base_linuxga_path\\\" $setup_tool_install >> /$base_linuxga_path/ASRLinuxGA.log\" >> $chroot_path/$asr_installga_exfile_path\n    echo \"exit 0\" >> $chroot_path/$asr_installga_exfile_path\n\n    # Add executable permissions.\n    chmod +x $chroot_path/$asr_installga_exfile_path\n\n    # Check for systemd path. The path may vary among linux distros.\n    local _systemd_config_file=\"$chroot_path/lib/systemd/system/${_AM_INSTALLGA_}.service\"\n    if [[ ! -d $chroot_path/lib/systemd/system ]]; then\n        if [[ -d $chroot_path/usr/lib/systemd/system ]]; then\n            _systemd_config_file=\"$chroot_path/usr/lib/systemd/system/${_AM_INSTALLGA_}.service\"\n        elif [[ -d $chroot_path/etc/systemd/system ]]; then\n            _systemd_config_file=\"$chroot_path/etc/systemd/system/${_AM_INSTALLGA_}.service\"\n        fi\n    fi\n\n    # Delete the file if it already exists\n    if [[ -f $_systemd_config_file ]]; then\n        trace \"$_systemd_config_file exists. Deleting the file.\"\n        rm $_systemd_config_file\n    fi\n\n    trace \"Creating systemd config file. $_systemd_config_file\"\n\n    echo \"[Unit]\" >> $_systemd_config_file\n    echo \"Description=Install Azure Linux Guest agent startup script by ASR\" >> $_systemd_config_file\n    echo \"ConditionPathExists=/$asr_installga_exfile_path\" >> $_systemd_config_file\n    echo \"\" >> $_systemd_config_file\n    echo \"[Service]\" >> $_systemd_config_file\n    echo \"Type=forking\" >> $_systemd_config_file\n    echo \"ExecStart=/$asr_installga_exfile_path start\" >> $_systemd_config_file\n    echo \"TimeoutSec=0\" >> $_systemd_config_file\n    echo \"StandardOutput=tty\" >> $_systemd_config_file\n    echo \"RemainAfterExit=no\" >> $_systemd_config_file\n    echo \"SysVStartPriority=99\" >> $_systemd_config_file\n    echo \"\" >> $_systemd_config_file\n    echo \"[Install]\" >> $_systemd_config_file\n    echo \"WantedBy=multi-user.target\" >> $_systemd_config_file\n\n    chroot $chroot_path systemctl enable \"${_AM_INSTALLGA_}.service\"\n\n    if [[ $? -ne 0 ]]; then\n        # CommandNotFound case if systemctl is not installed on the VM.\n        chroot $chroot_path service \"${_AM_INSTALLGA_}.service\" start\n    fi\n\n    gacheck=$(cat $_systemd_config_file)\n    trace \"systemd service file: $gacheck\"\n    \n    gacheck=$(cat $chroot_path/$asr_installga_exfile_path)\n    trace \"asr.installga: $gacheck\"\n}\n\nunset pythonver\ncheck_valid_python_version()\n{\n    # Check for Major Version 3 for python.\n    chroot $chroot_path python3 --version\n    if [[ $? -ne 0 ]] ; then\n        trace \"Python3 is not installed on the target VM.\"\n    else\n        pythonver=3\n        add_am_hydration_log \"Python Version\" \"python3\"\n\t\treturn\n    fi\n\n    # Check for Major version 2 and Minor Version >= 6 for Python.\n    chroot $chroot_path python --version\n    if [[ $? -ne 0 ]] ; then\n        trace \"Python is not installed on the target VM.\\n\"\n        pythonver=1\n\t\treturn\n    else\n        vermajor=$(chroot $chroot_path python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(major)\")\n        verminor=$(chroot $chroot_path python -c\"import platform; major, minor, patch = platform.python_version_tuple(); print(minor)\")\n        trace \"Major Version: $vermajor Minor Version: $verminor\"\n        if [ $vermajor -eq 2 ] && [ $verminor -ge 6 ]; then\n            pythonver=2\n            add_am_hydration_log \"Python Version\" \"${vermajor}.${verminor}\"\n            return\n        else\n            trace \"Failed to install Linux Guest Agent on the VM.\\n\"\n            trace \"Install python version 2.6+ to install Guest Agent.\\n\"\n            add_am_hydration_log \"Python Version incompatible for WALinuxAgent\" \"${vermajor}.${verminor}\"\n            pythonver=1\n            return\n        fi\n    fi\n\n    add_am_hydration_log \"Python Version absent\" \"WALinuxAgent installation prereq FAILED.\"\n\n    pythonver=1\n}\n\n# $1: Complete path of zip file.\n# $2: Target directory for extraction of zip file.\nextract_zipFile_using_python()\n{\n    trace \"Extracting zip from $1 to $2\"\n\n    # Create python script to extract the zip file.\n    local unzip_py=\"$chroot_path/${base_linuxga_path}/unzip.py\"\n    echo '#!/usr/bin/python' > $unzip_py\n    echo 'import sys' >> $unzip_py\n    echo 'from zipfile import ZipFile' >> $unzip_py\n    echo 'from zipfile import BadZipfile' >> $unzip_py\n    echo 'try:' >> $unzip_py\n    echo \"    zip_file = \\\"$1\\\"\" >> $unzip_py\n    echo \"    dest_dir = \\\"$2\\\"\" >> $unzip_py\n    echo '    pzf = ZipFile(zip_file)' >> $unzip_py\n    echo '    pzf.extractall(dest_dir)' >> $unzip_py\n    echo 'except BadZipfile:' >> $unzip_py\n    echo '    print(\"Error: Bad zip file format.\")' >> $unzip_py\n    echo '    sys.exit(1)' >> $unzip_py\n    echo 'else:' >> $unzip_py\n    echo '    print(\"Successfully extracted the zip file.\")' >> $unzip_py\n    echo '    sys.exit(0)' >> $unzip_py\n    \n    # Run python script using python3 present on hydration VM.\n    python3 $unzip_py >> \"$chroot_path/$base_linuxga_path/ASRLinuxGA.log\" 2>&1\n\n    return $?\n}\n\n# $1: python version command\ntest_setuptools_prereq()\n{\n    setup_uuid=$(uuidgen)\n    setuptools_file_path=\"$chroot_path/$base_linuxga_path/setuptools-test-$setup_uuid.py\"\n\n    echo \"import sys\"                   >> $setuptools_file_path\n    echo \"try:\"                         >> $setuptools_file_path\n    echo \"        import setuptools\"    >> $setuptools_file_path\n    echo \"except ImportError:\"          >> $setuptools_file_path\n    echo \"        print(\\\"ABSENT\\\")\"    >> $setuptools_file_path\n    echo \"else:\"                        >> $setuptools_file_path\n    echo \"        print(\\\"PRESENT\\\")\"   >> $setuptools_file_path\n\n    setuptools_output=\"\"\n    if [[ \"$1\" == \"python3\" ]]; then\n        setuptools_output=$(chroot $chroot_path python3 \"/$base_linuxga_path/setuptools-test-$setup_uuid.py\")\n    else\n        setuptools_output=$(chroot $chroot_path python \"/$base_linuxga_path/setuptools-test-$setup_uuid.py\")\n    fi\n\n    setup_tools_package_path=\"/usr/local/AzureRecovery/setuptools-33.1.1.zip\"\n\n    if [[ \"$setuptools_output\" == \"ABSENT\" ]]; then\n        add_am_hydration_log \"python setuptools\" \"ABSENT\"\n        trace \"setuptools is absent on the VM. Trying manual pre-boot installation.\"\n\n        extract_zipFile_using_python $setup_tools_package_path $chroot_path/$base_linuxga_path/\n        add_telemetry_data \"no-setuptools\"\n    else\n        trace \"setuptools is present on the VM.\"\n    fi\n\n    rm -f $setuptools_file_path\n}\n\nvalidate_guestagent_prereqs()\n{\n    check_valid_python_version\n\n    if [[ $pythonver -eq 1 ]]; then\n        trace \"Python not installed/ incompatible with linux guest agent requirements.\"\n        add_telemetry_data \"no-python\"\n    elif [[ $pythonver -eq 3 ]]; then\n        trace \"Python3 present on the source VM.\"\n        add_telemetry_data \"python3\"\n        test_setuptools_prereq \"python3\"\n    elif [[ $pythonver -eq 2 ]]; then\n        trace \"Python 2.6+ installed on the source VM.\"\n        add_telemetry_data \"python2\"\n        test_setuptools_prereq \"python\"\n    else\n        trace \"Unsupported Python version\"\n        add_telemetry_data \"no-python\"\n    fi\n}\n\nfix_network_config()\n{\n    if [[ $telemetry_data == *\"dhclient\"* ]] && [[ $telemetry_data == *\"dhcpcd\"* ]]; then\n        trace \"Both dhclient and dhcpcd are absent on the source VM.\"\n        trace \"Unable to find a tool to set dhcp on the Azure VM.\"\n        # Create the ifcfg-eth0 file nevertheless and send warning about consequences.\n    fi\n\n    #TODO: Needs some refactoring. Will add detailed customer logs accordingly.\n    add_am_hydration_log \"Networking Changes\" \"Enabling DHCP for the machine\"\n\n    trace \"Making network changes ...\"\n    case $src_distro in\n    RHEL6*|CENTOS6*|OL6*)\n        remove_network_manager_rpm\n        update_network_file\n        enable_network_service\n        configure_dhcp_rhel\n        add_startup_script_for_dhcp\n    ;;\n    SLES11*|SLES12*|SLES15*)\n        remove_network_manager_rpm\n        update_network_dhcp_file\n        configure_dhcp_sles\n        add_startup_script_for_dhcp\n    ;;\n    UBUNTU14*|DEBIAN*|UBUNTU16*|KALI-ROLLING*)\n        remove_persistent_net_rules\n        configure_dhcp_ubuntu\n        add_startup_script_for_dhcp\n    ;;\n    UBUNTU18*|UBUNTU19*|UBUNTU20*|UBUNTU21*|UBUNTU22*)\n        remove_persistent_net_rules\n        create_dhcp_netplan_config_and_apply\n    ;;\n    RHEL7*|RHEL8*|RHEL9*)\n        update_network_file\n        enable_network_service\n        configure_dhcp_rhel\n        add_startup_script_for_dhcp\n    ;;\n    CENTOS7*|OL7*|OL8*|OL9*|CENTOS8*|CENTOS9*)\n        reset_persistent_net_gen_rules\n        update_network_file\n        configure_dhcp_rhel\n        add_startup_script_for_dhcp\n    ;;\n    *)\n        throw_error $_E_AZURE_SMS_OS_UNSUPPORTED $src_distro\n    ;;\n    esac\n    trace \"Successfully completed network changes!\"\n}\n\nupdate_lvm_conf_to_allow_all_device_types()\n{\n    local _lvm_conf_file_=\"${chroot_path}/etc/lvm/lvm.conf\"\n    \n    if [[ -f $_lvm_conf_file_ ]]; then\n        trace \"$_lvm_conf_file_ not found.\"\n        return 0\n    fi\n    \n    # Modify lvm.conf file to include all devices.\n    local _line_=$(cat \"$_lvm_conf_file_\" | grep -P \"^(\\s*)filter(\\s*)=(\\s*).*\")\n    if [[ ! -z \"$_line_\" ]]; then\n        backup_file $_lvm_conf_file_\n        _line_number_=$(cat \"$_lvm_conf_file_\" | grep -P -n \"^(\\s*)filter(\\s*)=(\\s*).*\" | awk -F\":\" '{print $1}')\n        trace \"Modifying filter in $_lvm_conf_file_ (line: $_line_number_)\"\n        sed -i \"$_line_number_ c\\filter=\\\"a\\/.*\\/\\\"\" $_lvm_conf_file_\n        return $?\n    fi\n\n    return 0\n}\n\nupdate_root_device_uuid_in_boot_cmd()\n{\n    local _boot_cmd_starts_with_=\"linux\"\n    local _grub_file_=\"${chroot_path}/boot/grub2/grub.cfg\"\n    \n    case $src_distro in\n        CENTOS6*|OL6*|RHEL6*|SLES11*)\n            _grub_file_=\"${chroot_path}/boot/grub/menu.lst\"\n            if [ \"$firmware_type\" = \"UEFI\" ]; then\n                _grub_file_=\"$_grub2_efi_path/menu.lst\"\n            fi\n            _boot_cmd_starts_with_=\"kernel\"\n        ;;\n        UBUNTU*|DEBIAN*|KALI-ROLLING*)\n            _grub_file_=\"${chroot_path}/boot/grub/grub.cfg\"\n            if [ \"$firmware_type\" = \"UEFI\" ]; then\n                _grub_file_=\"$_grub2_efi_path/grub.cfg\"\n            fi\n        ;;\n    esac\n\n    if [ \"$firmware_type\" = \"UEFI\" ]; then\n        if [ -f \"$_grub2_efi_path/grub.cfg\" ]; then\n            _grub_file_=\"$_grub2_efi_path/grub.cfg\"\n        elif [ -f \"$_grub2_efi_path/menu.lst\" ]; then\n            _grub_file_=\"$_grub2_efi_path/menu.lst\"\n        elif [ -f \"$_grub2_efi_path/grub.conf\" ]; then\n            _grub_file_=\"$_grub2_efi_path/grub.conf\"\n        fi\n    fi\n    \n    local src_root_uuid=$(findmnt -nf -o UUID $chroot_path)\n    if [[ $? -ne 0 ]]; then\n        trace \"could not find device UUID for the $chroot_path\"\n        return 0\n    elif [[ -z $src_root_uuid ]]; then\n        trace \"root UUID not available, skipping root device update in grub file.\"\n        return 0\n    fi\n    \n    exec 4<$_grub_file_\n    while read -u 4 -r _line_\n    do\n        # Ignore commented lines\n        if [[ $_line_ =~ ^# ]]; then\n            continue\n        fi\n        \n        local _dev_name_=$(echo $_line_ |\\\n                         grep \"${_boot_cmd_starts_with_}.*root=\\/dev\\/\" |\\\n                         awk -F\"root=\" '{print $2}' | awk '{print $1}')\n\n        [[ -z $_dev_name_ ]] && continue\n        \n        if [[ $_dev_name_ =~ /dev/[x]*[svh]d.* ]]; then\n            trace \"Replacing $_dev_name_ with $src_root_uuid\"\n            local safe_device=$(printf \"%s\\n\" \"$_dev_name_\" |\\\n                         sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n            sed -i --follow-symlinks \"s/${safe_device}/UUID=$src_root_uuid/\" $_grub_file_\n        else\n            trace \"$_dev_name_ is not a standard partition name, no need to replace with UUID.\"\n        fi\n        \n        # TODO: Remove \"resume=\" option if its referring to standard device name.\n    done\n    4<&-\n}\n\nmain()\n{\n    local error_in_generate_initrd_image=0\n    validate_script_input \"$@\"\n    \n    verify_src_os_version\n\n    get_firmware_type\n\n    mount_runtime_partitions\n\n    verify_requited_tools\n\n    verify_generate_initrd_images\n    \n    set_serial_console_grub_options\n\n    verify_uefi_bootloader_files\n\n    update_root_device_uuid_in_boot_cmd\n    \n    fix_network_config\n    \n    update_lvm_conf_to_allow_all_device_types\n\n    install_linux_guest_agent\n\n    # Most Hard failures will be immediately thrown.\n    # Return Soft Failures, call failure checks in increasing order of priority\n    # So that most critical failure is shown to the customer.\n\n    final_error_code=\"0\"\n    final_error_data=\"\"\n    if [[ $telemetry_data == *\"systemctl\"* ]] && [[ $telemetry_data == \"service\" ]]; then\n        final_error_code=\"$_E_AZURE_GA_INSTALLATION_FAILED\"\n        final_error_data=\"systemctl\"\n    fi\n\n    if [[ $telemetry_data == *\"no-python\"* ]]; then\n        final_error_code=\"$_E_AZURE_GA_INSTALLATION_FAILED\"\n        final_error_data=\"no-python\"\n    fi\n\n    if [[ $telemetry_data == *\"dhclient\"* ]] && [[ $telemetry_data == *\"dhcpcd\"* ]]; then\n        final_error_code=\"$_E_AZURE_ENABLE_DHCP_FAILED\"\n        final_error_data=\"dhclient\"\n    fi\n\n    if [[ $telemetry_data == *\"bootx64.efi\"* ]]; then\n        final_error_code=\"$_E_AZURE_SMS_CONF_MISSING\"\n        final_error_data=\"bootx64.efi\"\n    fi\n\n    add_am_hydration_log \"---Hydration Log End---\" \"\"\n\n    # Add entire summarized log in HydrationLog\n    cat \"${chroot_path}${_AM_HYDRATION_LOG_}$am_telem_suffix\"\n\n    if [[ $final_error_code -ne 0 ]]; then\n        throw_error $final_error_code $final_error_data\n    else\n        # Log Telemetry Data\n        echo \"[Sms-Telemetry-Data]:${telemetry_data}\"\n    fi\n}\n\nmain \"$@\"", "num_lines": 2050}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_LOG_FILE_=\"PrepareTarget.Log\" #this is not much in use\n_DATE_STRING_=`date +'%b_%d_%H_%M_%S'` #this is also for temporary log generation not used in code.\n_TEMP_LOG_F_=\"PrepareTarget-$_DATE_STRING_.log\" \n_WORK_FLOW_=\"\" #this is used to mention whether it is P2V or V2P.\n\n_LIB_FILE_=\"Linux_P2V_Lib.sh\"\n_INPUT_FILE_=\"\" #Input File for Prepare Target.\n\n_SUCCESS_=0\n_FAILED_=1\n\n#GLOBALVAR#\n_MOUNT_PATH_=\"\" #mount point\n_MOUNT_PATH_FOR_=\"\" #either for boot or etc as of now\n_MACHINE_UUID_=\"\" #_InMage_UUID_\n_PLAN_NAME_=\"\" #Plan Name for Protection/Recover/DrDrill. The actual input for this parameter is path to failover_data-Folder.\n_INSTALL_VMWARE_TOOLS_=1\n_UNINSTALL_VMWARE_TOOLS_=0\n_NEW_GUID_=\"\"\n_VX_INSTALL_PATH_=\"\" #InMage VX Installation Path.\n_VX_FAILOVER_DATA_PATH_=\"\"  #InMage VX Failover Data Folder Path. Should we require this?\n_FILES_PATH_=\"\"\n_TASK_=\"\" #Protect/Add/Recover/DrDrill\n_INPUT_CONFIG_FILE_=\"\"\n_PROTECTED_DISK_LIST_FILE_PATH_=\"\"\n_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_=\"\"\n_MPARTITION_=\"\" #Contains partition in format of multipath.\n_MDEVICE_=\"\" #will be base Multipath Device for a multipath partition.\n_SRC2TGT_MAPPED_DEVICE_=\"\" # contains recovered VM device name after mapping\n_SCSI_DEVICE_NAME_FOR_MPARTITION_=\"\" #SCSI device name for a multipath device.\n_PARTITON_NUMBER_=\"\" #integer which say i'th partition.\n_PARTIION_LIST_ON_A_DEVICE_=\"\" #Holds List of PARTITIONS On a device.\n_INMAGE_ORG_=\"-INMAGE_ORG\"\n_INMAGE_MOD_=\"-INMAGE_MOD\"\n_MULTIPATH_CLEANUP_RETRY_COUNT=10\n_VCON_ACTION_FILE_=\"\"\n_ORIGINAL_ACTIVE_PARTITION_=\"\"\n_SOURCE_CONFIGURATION_DATA_FILE=\"source_configuration.dat\"\n_MOD_PROBE_FILE_NAME_=\"modprobe.conf\"\n_LOGS_=\"\"\n_WORKING_DIRECTORY_=\"\" #Introduced for Azure PAAS model. Holds where all script files and input to scripts are placed.\n_SCRIPTS_PATH_=\"\"\n_GET_HOST_INFO_XML_FILE_NAME_=\"\"\n_PROTECTED_DISKS_LIST_FILE_NAME_=\"\"\n###\n\nfunction ReadInputFile\n{\n\t#check if file exists and it is valid input.\n\t_INPUT_FILE_=$1\n\techo \"Input File = \\\"$_INPUT_FILE_\\\"\"\n\tif [ ! \"${_INPUT_FILE_}\" ];then\n        \techo \"ERROR :: Please pass an input file.\"\n\t        return $_FAILED_\n\tfi\n\n\t#WE have a valid Input, check for the File.\n\tif [ ! -f $_INPUT_FILE_ ] || [ ! -r $_INPUT_FILE_  ]; then #need to check the read permission code.\n\t\techo \"ERROR :: Could not find file \\\"$_INPUT_FILE_\\\".\"\n\t\techo \"ERROR :: Make sure file \\\"$_INPUT_FILE_\\\" exists.\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#We have file as well. Read the file\n\texec 4<\"$_INPUT_FILE_\"\n\twhile read -u 4 _attribute_ _value_\n\tdo \n\t\tcase $_attribute_ in \n\t\t\t_MOUNT_PATH_) _MOUNT_PATH_=$_value_;;\n\t\t\t_MOUNT_PATH_FOR_) _MOUNT_PATH_FOR_=$_value_;;\n\t\t\t_MACHINE_UUID_) _MACHINE_UUID_=$_value_;;\n\t\t\t_PLAN_NAME_) _PLAN_NAME_=$_value_;;\n\t\t\t_VX_INSTALL_PATH_) _VX_INSTALL_PATH_=$_value_;;\n\t\t\t_TASK_) _TASK_=$_value_;;\n\t\t\t_MPARTITION_) _MPARTITION_=$_value_;;\n\t\t\t_INSTALL_VMWARE_TOOLS_) _INSTALL_VMWARE_TOOLS_=$_value_;;\n\t\t\t_NEW_GUID_) _NEW_GUID_=$_value_;;\n\t\t\t_WORKING_DIRECTORY_) _WORKING_DIRECTORY_=$_value_;;\n\t\t\t_UNINSTALL_VMWARE_TOOLS_)_UNINSTALL_VMWARE_TOOLS_=$_value_;;\n\t\t\t*) echo \"Invalid attribute:$_attribute_ , value:$_value_\";;\n\t\tesac\n\tdone\n\t4<&-\n\n\t#When VX installation path and Plan name are defined consider as SCOUT otherwise as PAAS model.\n\tif [ -z $_VX_INSTALL_PATH_ ] && [ -z $_PLAN_NAME_ ] && [ ! -z $_WORKING_DIRECTORY_ ] ; then\n\t\t_FILES_PATH_=$_WORKING_DIRECTORY_\n\t\t_VX_FAILOVER_DATA_PATH_=$_WORKING_DIRECTORY_\n\t\t_PLAN_NAME_=$_WORKING_DIRECTORY_\n\t\t_SCRIPTS_PATH_=$_WORKING_DIRECTORY_\n\t\t_GET_HOST_INFO_XML_FILE_NAME_=\"hostinfo-${_MACHINE_UUID_}.xml\"\n\t\t_PROTECTED_DISKS_LIST_FILE_NAME_=\"${_MACHINE_UUID_}.PROTECTED_DISKS_LIST\"\n\telse\n\t\t_FILES_PATH_=$_VX_INSTALL_PATH_\n\t\t_VX_FAILOVER_DATA_PATH_=\"$_VX_INSTALL_PATH_/failover_data/\"\n\t\t_SCRIPTS_PATH_=\"$_VX_INSTALL_PATH_/scripts/vCon/\"\n\t\t_GET_HOST_INFO_XML_FILE_NAME_=\"${_MACHINE_UUID_}_cx_api.xml\"\n\t\t_PROTECTED_DISKS_LIST_FILE_NAME_=\"${_MACHINE_UUID_}.PROTECTED_DISKS_LIST\"\n\tfi\n\n\n\techo \"MACHINE UUID\t\t= $_MACHINE_UUID_\"\n\techo \"TASK \t\t\t= $_TASK_\"\n\techo \"PLAN NAME \t\t= $_PLAN_NAME_\"\n\techo \"VX INSTALL PATH \t\t= $_VX_INSTALL_PATH_\"\n\techo \"MOUNT PATH \t\t= $_MOUNT_PATH_\"\n\techo \"MOUNT PATH FOR \t\t= $_MOUNT_PATH_FOR_\"\n\techo \"WORKING DIRECTORY \t= $_WORKING_DIRECTORY_\"\n\techo \"FILES PATH \t\t= $_FILES_PATH_\"\n\techo \"VX FAILOVER DATA PATH \t= $_VX_FAILOVER_DATA_PATH_\"\n\t\n\treturn $_SUCCESS_\n}\n\nfunction ExecuteTask\n{\n\t#TASK CAN BE EITHER Protect/ADDPROTECTION/FAILOVER/INSTALLGRUB.\n\t#MAKE SURE A TASK IS PASSED.\n\tif [ ! \"${_TASK_}\" ]; then\n\t\techo \"ERROR :: Failed to determine which task has to be performed from input file \\\"$_input_file_\\\".\"\n\t\techo \"ERROR :: A Task can be either PROTECT/ADDPROTECT/FAILOVER/INSTALLGRUB in file \\\"$_input_file_\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t#We have a TASK.\n\techo \"Task = $_TASK_\"\n\tcase $_TASK_ in \n\t\tPROTECT) \n\t\t\t\t#In Protect scenario we have to Make List of Protected devices in Order..pInfo files does not contain them in order.\n\t\t\t\tExecuteTask_PROTECT\n\t\t\t\t_ret_code_=$?\n\t\t\t\t;;\n\t\tADDPROTECT)\n\t\t\t\t#In this case we have to append information of new disk to already existing List.\n\t\t\t\tExecuteTask_ADDPROTECT\n\t\t\t\t_ret_code_=$?\n\t\t\t\t;;\n\t\tPREPARETARGET)\n\t\t\t\t#In this case All changes for PREPARE TARGET HAS TO BE TAKEN PLACE.\n\t\t\t\t_WORK_FLOW_=\"p2v\"\n\t\t\t\tExecuteTask_PREPARETARGET\n\t\t\t\t_ret_code_=$?\n\t\t\t\t;;\n\t\tINSTALLGRUB)\n\t\t\t\t#In this case GRUB has to be installed.Might be this is one of Old hardware where by default GRUB is not installed.\n\t\t\t\tExecuteTask_INSTALLGRUB\n\t\t\t\t_ret_code_=$?\n\t\t\t\t;;\n\t\tPREPARETARGET_V2P)\n\t\t\t\t#This can be either failback of P2V or direct protection from V -> P. Even is this case this will work.\n\t\t\t\t_WORK_FLOW_=\"v2p\"\n\t\t\t\tExecuteTask_V2P\n\t\t\t\t_ret_code_=$?\n\t\t\t\t;;\t\t\n\t\t\t*)\n\t\t\t\techo \"ERROR ::Invalid Task specified. Task Specified=$_TASK_\"\n\t\t\t\techo \"ERROR ::Task can be either PROTECT/ADDPROTECT/PREPARETARGET.\"\n\t\t\t\t_ret_code_=$_FAILED_\n\t\t\t\t;;\n\tesac\n\n\treturn $_ret_code_\t\n}\n\nfunction ExecuteTask_INSTALLGRUB\n{\n\t_install_grub_flag=0\n\t_returnCode_=$_FAILED_\n\t#Check Whether MACHINE UUID IS SENT\n\techo \"Executing Task INSTALLGRUB.\"\n\tif [ ! \"${_MACHINE_UUID_}\" ]; then\n\t\techo \"ERROR :: A Host ID has to be specified.\"\n\t\techo \"ERROR :: Host ID is required to fetch corresponding configuration file.\"\n\t\treturn $_returnCode_\n\tfi\n\n\t#WE HAVE TO CHECK WHETHER VX INSTALL PATH IS SPECIFIED\n\tif [ -z \"$_FILES_PATH_\" ]; then\n\t\techo \"ERROR :: Working directory where script files exist is not specified.\"\n\t\techo \"ERROR :: Failed to INSTALL GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\n\t_INPUT_CONFIG_FILE_=\"$_VX_FAILOVER_DATA_PATH_/${_MACHINE_UUID_}_Configuration.info\"\n\tif [ ! -f \"${_INPUT_CONFIG_FILE_}\" ]; then\n\t\techo \"ERROR :: Failed to find file \\\"$_INPUT_CONFIG_FILE_\\\".\"\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\n\t#NOW WE HAVE THE FILE WE HAVE TO INSTALL GRUB FOR THIS CONFIGURATION.\n\t#Find the SCSI device for _MPARTITION_\n\tif [ -z \"${_MPARTITION_}\" ]; then\n\t\techo \"ERROR :: Partition information on which GRUB has to be installed is not specified.\"\n\t\techo \"ERROR :: Please pass a multipath partition information in Input file for installing GRUB.\"\n\t\treturn $_returnCode_\n\tfi\n\t\n\techo \"multipath partition on which GRUB has to be installed = $_MPARTITION_.\"\n\tFindMultipathDeviceForPartition \"$_MPARTITION_\"\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\n\tFindSCSIDeviceForAMultipathDevice \"$_MDEVICE_\"\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\n\t_MACHINE_MANUFACTURER_=`grep \"Machine Manufacturer                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_MACHINE_PRODUCT_TYPE_=`cat $_INPUT_CONFIG_FILE_ | grep \"Machine Product Type\" | awk -F\": \" '{print $2}'`\n\t_DISTRIBUTION_DETAILS_=`grep \"Distribution details                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_ROOT_DEVICE_=`grep \"Root device                            : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_BOOT_DEVICE_=`grep \"Boot device                            : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_PROBE_DEVICE=\"\"\n\techo \"Machine Manufacturer = ${_MACHINE_MANUFACTURER_}\"\n\techo \"Machine Product Type = ${_MACHINE_PRODUCT_TYPE_}\"\n\techo \"Distribution details = ${_DISTRIBUTION_DETAILS_}\"\n\techo \"Root device : ${_ROOT_DEVICE_}\"\n\techo \"Boot device : ${_BOOT_DEVICE_}\"\n\n\tcase \"${_DISTRIBUTION_DETAILS_}\" in \n\t\tSLES10*|SLES9*)\n\t\t\t#if [ \"${_MACHINE_MANUFACTURER_}\" = \"HP\" ] || [ \"${_MACHINE_MANUFACTURER_}\" = \"Hewlett-Packard\" ]; then\n        \t\t#\tif [ \"${_MACHINE_PRODUCT_TYPE_}\" = \"ProLiant DL380 G4\" ]; then\n        \t\t#\t\t_install_grub_flag=1\n        \t\t#\tfi\n\t\t\t#fi\n                        if [ -z \"${_BOOT_DEVICE_}\" ]; then\n                        \t_PROBE_DEVICE=\"${_ROOT_DEVICE_}\"\n                        else\n                        \t_PROBE_DEVICE=\"${_BOOT_DEVICE_}\"\n                        fi\n                       \techo \"${_PROBE_DEVICE}\" | grep -i cciss 2>&1 > /dev/null\n                       \tif [ $? -eq 0 ]; then\n                            _install_grub_flag=1\n                       \tfi\n\n\t\t\tif [ $_install_grub_flag -eq 1 ]; then\n\t\t\t\t_first_partition_=\"\"\n\t\t\t\t# Check if first parition is not active then proceed otherewise\n\t\t\t\t# no need to install GRUB in this case.\n\t\t\t\t_active_partition_=`fdisk -l ${_MDEVICE_} | grep \".*.Linux\" | grep \"*\" | awk '{print $1}'`\n\t\t\t\t#FIND THE PARTITION NUMBER FOR ACTIVE PARTITION.\n\t\t\t\tFindPartitionNumber ${_active_partition_} ${_MDEVICE_}\n\t\t\t\tif [ 0 -ne $? ]; then\n\t\t\t\t\techo \"ERROR :: Failed to evaluate GRUB installation procedure = \\\"$_MACHINE_UUID_\\\".\"\n        \t\t\t\t_install_grub_flag=0\n\t\t\t\telse\n\t\t\t\t\t\n\t\t\t\t\t# Make sure GRUB install does not step on LVM partition\n\t\t\t\t\t_first_partition_=`fdisk -l ${_MDEVICE_} | grep -m 1 \"Linux\" | awk '{ print $1 }'`\n\t\t\t\t\t_lvm_partition_=`fdisk -l ${_MDEVICE_} | grep -m 1 \"LVM\" | awk '{ print $1 }'`\n\t\t\t\t\tif [ \"${_lvm_partition_}\" = \"${_first_partition_}\" ]; then\n\t\t\t\t\t\techo \"INFO :: Found LVM as first partition. Skipping GRUB installation procedure = \\\"$_MACHINE_UUID_\\\".\"\n        \t\t\t\t\t_install_grub_flag=0\n\t\t\t\t\tfi\n\t\t\t\t\tif [ ${_PARTITON_NUMBER_} -eq 1 ]; then\n        \t\t\t\t\t# DO NOT INSTALL GRUB\n        \t\t\t\t\t_install_grub_flag=0\n\t\t\t\t\tfi\n\n\t\t\t\tfi\n\t\t\t\t\n\n\t\t\telse\n\t\t\t\techo \"INFO :: GRUB installation is not required = \\\"$_MACHINE_UUID_\\\".\"\n        \t\t\t_install_grub_flag=0\n\t\t\tfi\n\t\t;;\n\t\tSLES11*|SLES12*)\n\t\t\techo \"GRUB Installation is not required for $_MACHINE_MANUFACTURER:$MACHINE_PRODUCT_TYPE\"\n\t\t\techo \"No changes required on ${_DISTRIBUTION_DETAILS_} for GRUB installtion for now\"\n\t\t;;\n\t\tRHEL*)\n\t\t\techo \"GRUB Installation is not required for $_MACHINE_MANUFACTURER:$MACHINE_PRODUCT_TYPE\"\n\t\t\techo \"No changes required on ${_DISTRIBUTION_DETAILS_} for GRUB installtion\"\n\t\t;;\n\t\tOL*)\n\t\t\techo \"GRUB Installation is not required for $_MACHINE_MANUFACTURER:$MACHINE_PRODUCT_TYPE\"\n\t\t\techo \"No changes required on ${_DISTRIBUTION_DETAILS_} for GRUB installtion\"\n\t\t;;\n\t\t*) echo \"Invalid distribution details $_DISTRIBUTION_DETAILS_\"\n                ;;\n\tesac\n\n\tdd bs=512 count=1 if=${_SCSI_DEVICE_NAME_FOR_MPARTITION_} 2>/dev/null | strings | grep GRUB\n\tif [ 0 -ne $?  ]; then\n\t\techo \"GRUB is not found in sector 0.Turning on flag which says to install GRUB.\"\n\t\t_install_grub_flag=1\n\tfi\n\n\tif [ $_install_grub_flag -eq 0 ]; then\n\t\techo \"GRUB Installation is not required.\"\t\t\n\t\treturn $_returnCode_\n\tfi\n\n\t#WE HAVE BASE SCSI DEVICE NAME FOR PARTITION.NOW FIND THE PARTITION NUMBER.\n\tFindListOfMultipathPartitions ${_MDEVICE_}\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\t\n\tFindPartitionNumber ${_MPARTITION_} ${_MDEVICE_}\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_returnCode_\n\tfi\n\t\n\t_wwid_=`echo ${_multipath_device_} | sed -e s:/dev/mapper/:: | sed -e s:/::`\n\t_multipath_org_file_=\"/etc/multipath.conf\"\n\t_multipath_mod_file_=\"${_multipath_org_file_}.BLACKLISTDEVICE\"\n\t_mount_path_=\"/mnt/tempMount_${_wwid_}\"\n\t\n\t_counter_=1\n\t_returnCode_=$_SUCCESS_\n\twhile [ 0 -ne $_counter_ ]\n\tdo\n\t\t_counter_=$((_counter_-1))\n\n\t\tCOPY ${_multipath_org_file_} ${_multipath_mod_file_}\n\n\t\tBlackListAMultipathDevice ${_MDEVICE_} ${_multipath_org_file_} ${_multipath_mod_file_}\n\t\t\n\t\t#NOW WE HAVE THE PARTITON NUMBER AS WELL.REMOVE A MULTIPATH DEVICE\n\t\t_loop_count_=0\n\t\t_returnCode_=$_FAILED_\n\t\twhile [ $_MULTIPATH_CLEANUP_RETRY_COUNT -ne $_loop_count_ ];\n\t\tdo\n\t\t\tRemoveAMultipathDevice $_MDEVICE_\n\t\t\tif [ 0 -ne $? ]; then\n\t\t\t\techo \"ERROR :: Failed to remove multipath device in RemoveAMultipathDevice err:$? host id = \\\"$_MACHINE_UUID_\\\". Retrying now\"\n\t\t\t\t`sleep 2`\n\t\t\t\t_loop_count_=$((_loop_count_+1))\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t_returnCode_=$_SUCCESS_\n\t\t\tbreak\n\t\tdone\n\n\t\tif [ $_FAILED_ -eq $_returnCode_ ]; then\n\t\t\techo \"ERROR :: Failed to remove multipath device in RemoveAMultipathDevice err:$? host id = \\\"$_MACHINE_UUID_\\\". Retry failed\"\n\t\t\tbreak\n\t\tfi\n\t\t\n\t\t_scsi_partition_=\"${_SCSI_DEVICE_NAME_FOR_MPARTITION_}${_PARTITON_NUMBER_}\"\n\t\t\n\t\tif [ 1 != ${_PARTITON_NUMBER_} ]; then\n\t\t\t#MAKE FIRST PARTITION ACTIVE\n\t\t\tMakeFirstPartitionActive \"${_SCSI_DEVICE_NAME_FOR_MPARTITION_}\"\n\t\t\tif [ 0 -ne $? ]; then\n\t\t\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\t\t\t_returnCode_=$_FAILED_\n\t\t\t\tbreak\n\t\t\tfi\n\t\tfi\n\n\t\t/sbin/blockdev --rereadpt \"${_SCSI_DEVICE_NAME_FOR_MPARTITION_}\"\n\t\t_rCode_=$?\n\t\tif [ 0 -ne $_rCode_ ]; then\n\t\t\techo \"ERROR :: Failed to re-read partition table of device ${_SCSI_DEVICE_NAME_FOR_MPARTITION_}.\"\n\t\tfi\n\n\t\tMountAPartition \"${_scsi_partition_}\" \"${_mount_path_}\"\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\t\t_returnCode_=$_FAILED_\n\t\t\tbreak\n\t\tfi\n\t\t\n\t\t#FIRST WE HAVE TO TAKE BACK UP OF device.map file and restore it back.\n\t\t_device_map_file_=\"\"\n\t\t_boot_path_=\"\"\n\t\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\" ] || [ \"all\" = \"${_MOUNT_PATH_FOR_}\" ]; then\n\t\t\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\"  ]; then\n\t\t\t\t_device_map_file_=\"${_mount_path_}/grub/device.map\"\n\t\t\t\t_boot_path_=${_mount_path_}\n\t\t\telif [ -d \"$_MOUNT_PATH_/boot\" ]; then\n\t\t\t\t_device_map_file_=\"${_mount_path_}/boot/grub/device.map\"\n\t\t\t\t_boot_path_=\"${_mount_path_}/boot/\"\n\t\t\telse\n\t\t\t\techo \"ERROR :: Failed to backup device.map file while installing GRUB.\"\n\t\t\tfi\n\t\tfi\n\n\t\t_device_map_file_mod_=\"${_device_map_file_}.MODGRUBINSTALL\"\t\n\t\tif [ \"${_device_map_file_}\" ]; then\n\t\t\t#MOVE\n\t\t\tMOVE \"${_device_map_file_}\" \"${_device_map_file_mod_}\"\n\t\t\t\n\t\t\t#CHANGE CONTENTS\n\t\t\techo \"(hd0)\t${_SCSI_DEVICE_NAME_FOR_MPARTITION_}\" >> ${_device_map_file_}\n\t\tfi\n\n\t\tif [ \"${_boot_path_}\" ]; then\n\t\t\t#write Active Partition file.\n\t\t\techo \"orginal_active_partition=${_ORIGINAL_ACTIVE_PARTITION_}\" > \"${_boot_path_}/${_SOURCE_CONFIGURATION_DATA_FILE}\"\n\t\tfi\n\t\t\t\t\n\t\tInstallGRUB \"${_SCSI_DEVICE_NAME_FOR_MPARTITION_}\" \"${_mount_path_}\"\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\t\t_returnCode_=$_FAILED_\n\t\tfi\n\n\t\techo \"installed_grub_on_target=1\" >> \"${_boot_path_}/${_SOURCE_CONFIGURATION_DATA_FILE}\"\n\t\tif [ \"${_device_map_file_}\" ]; then\n\t\t\tMOVE \"${_device_map_file_mod_}\" \"${_device_map_file_}\"\n\t\tfi\n\n\tdone\n\n\t#UNMOUNT THE PARTITON and REVERT MULTIPATH.CONF FILE.\n\tUnmountAPartition ${_mount_path_}\n\t`/bin/rmdir  ${_mount_path_}`\n\n\tMOVE  ${_multipath_mod_file_} ${_multipath_org_file_}\n\t\n\tif [ ! $_returnCode_ ]; then\n\t\techo \"Successfully Installed GRUB for host with hostid:$_MACHINE_UUID_\"\n\tfi\n\treturn $_returnCode_\n}\n\n#Finds LIST OF PARTITIONS ON A DEVICE.\nfunction FindListOfPartitions \n{\n\t_device_=$1\n\techo \"Finding partitions on device \\\"${_device_}\\\".\"\n\t\n\t_PARTIION_LIST_ON_A_DEVICE_=\"\"\n\t_PARTIION_LIST_ON_A_DEVICE_=`fdisk -l ${_device_} | grep \"^${_device_}\" | awk '{print $1}'`\n\tif [ -z \"${_PARTIION_LIST_ON_A_DEVICE_}\" ]; then\n\t\techo \"ERROR :: Failed to find partitions on device \\\"${_device_}\\\".Might be device is not partitioned at all.\"\n\t\treturn $_FAILED_\n\tfi\t\n\treturn $_SUCCESS_\n}\n\n#Finds LIST OF PARTITIONS ON A MULTIPATH DEVICE.\nfunction FindListOfMultipathPartitions \n{\n\t_device_=$1\n\t_tmp_device_=`echo $_device_ | sed -e \"s:/dev/mapper/::g\"`\n\techo \"Finding partitions on multipath device \\\"${_device_}\\\".\"\n\t\n\t_PARTIION_LIST_ON_A_DEVICE_=\"\"\n\t_PARTIION_LIST_ON_A_DEVICE_=`dmsetup ls | grep \"^${_tmp_device_}\" | awk '{ if ($1 != \"'\"$_tmp_device_\"'\") { print $1 } }'`\n\tif [ -z \"${_PARTIION_LIST_ON_A_DEVICE_}\" ]; then\n\t\techo \"ERROR :: Failed to find partitions on device \\\"${_device_}\\\".Might be device is not partitioned at all.\"\n\t\treturn $_FAILED_\n\tfi\t\n\treturn $_SUCCESS_\n}\n\nfunction RemoveAndAddSingleDevice \n{\n\t#REMOVE AND ADD A SINFLE DEVICE.\n\t_scsi_dev_=$1\n\techo \"trying to remove and add scsi device ${_scsi_dev_}.\"\n\t\n\t#find SCSI id for the device.\n\t_scsi_id_=`lsscsi | grep -w ${_scsi_dev_} | awk '{print $1}' | sed s:[\\[]::g | sed s:[\\]]::g`\n\techo \"scsi id of device \\\"${_scsi_dev_}\\\" is ${_scsi_id_}.\"\n\n\t#REMOVE DEVICE\n\t`echo \"scsi remove-single-device ${_scsi_id_}\" > /proc/scsi/scsi`\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to remove device \\\"${_scsi_id_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t`sleep 1`\n\t#ADD DEVICE\n\t`echo \"scsi add-single-device ${_scsi_id_}\" > /proc/scsi/scsi`\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to add device \\\"${_scsi_id_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t`sleep 1`\n\treturn $_SUCCESS_\n}\n\nfunction MakeFirstPartitionActive\n{\n\t_device_=$1\n\n\t#FIND THE ACTIVE PARTITION FROM BELOW COAMMAND\n\t#fdisk -l /dev/sda | grep \".*.Linux\" | grep \"*\" | awk '{print $1}'\n\n\t_active_partition_=`fdisk -l ${_device_} | grep \".*.Linux\" | grep \"*\" | awk '{print $1}'`\n\t#if [ ! -b \"${_active_partition_}\" ]; then\n\t#\techo \"ERROR :: Failed to find active partition on device \\\"${_device_}\\\".\"\n\t#\treturn $_FAILED_\n\t#fi\n\n\t#FIND THE PARTITION NUMBER FOR ACTIVE PARTITION.\n\tFindPartitionNumber ${_active_partition_} ${_device_}\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t_ORIGINAL_ACTIVE_PARTITION_=${_PARTITON_NUMBER_}\n\t#THEN EXECUTE FDISK COMMAND TO MAKE THE FIRST PARTITION AS ACTIVE INSTEAD OF n'th PARTITION.\n\t_activate_partition_script_=\"${_SCRIPTS_PATH_}/ActivatePartition.sh\"\n\techo \"de-marking \\\"${_PARTITON_NUMBER_}\\\" as active using script \\\"${_activate_partition_script_}\\\" and marking partition 1 as active.\"\n\t${_activate_partition_script_} ${_device_} ${_PARTITON_NUMBER_} 1\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to make first partition as active.\"\n\t\treturn $_FAILED_\n\tfi\n\techo \"Successfully marked first partition as active.\"\n\treturn $_SUCCESS_\t\n}\n\nfunction MakePartitionActive\n{\n\t_device_=$1\n\t_make_partition_num_as_active_=$2\n\t_active_partition_=`fdisk -l ${_device_} | grep \".*.Linux\" | grep \"*\" | awk '{print $1}'`\n\n\t#FIND THE PARTITION NUMBER FOR ACTIVE PARTITION.\n\tFindPartitionNumber ${_active_partition_} ${_device_}\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to Install GRUB on machine with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\n\tif [ ${_make_partition_num_as_active_} = ${_PARTITON_NUMBER_} ]; then\n\t\techo \"Partition ${_make_partition_num_as_active_} is already active.\"\n\t\treturn $_SUCCESS_\n\tfi\n\n\t#THEN EXECUTE FDISK COMMAND TO MAKE THE OTHER PARTITION AS ACTIVE INSTEAD OF n'th PARTITION.\n\t_activate_partition_script_=\"${_VX_INSTALL_PATH_}/scripts/vCon/ActivatePartition.sh\"\n\techo \"de-marking \\\"${_PARTITON_NUMBER_}\\\" as active using script \\\"${_activate_partition_script_}\\\" and marking partition ${_make_partition_num_as_active_} as active.\"\n\t${_activate_partition_script_} ${_device_} ${_PARTITON_NUMBER_} ${_make_partition_num_as_active_}\n\t#if [ 0 -ne $? ]; then\n\t#\techo \"ERROR :: Failed to make ${_make_partition_num_as_active_} partition as active.\"\n\t#\treturn $_FAILED_\n\t#fi\n\techo \"Successfully marked ${_make_partition_num_as_active_} partition as active.\"\n\treturn $_SUCCESS_\n}\n\n\nfunction UnmountAPartition\n{\n\t_partition_=$1\n\n\techo \"Unmounting partition ${_partition_}\"\n\t\n\t`umount ${_partition_}`\n\tif [ 0 -ne $? ]; then\n\t\techo \"Failed to unmount partition \\\"${_partition_}\\\".\"\n\tfi\n\t\n\treturn $_SUCCESS_\n}\n\n#Mounts a Partition\n#_IN_ partition\n#_IN_ mountpath\nfunction MountAPartition\n{\n\t_partition_=$1\n\t_mount_path_=$2\n\techo \"mounting partition $_partition_ at $_mount_path_\"\n\n\t#FIRST CHECK IF ALREADY A MOUNT EXISTS? MIGHT BE AN EMPTY DIRECTORY?\n\tif [ -d \"${_mount_path_}\" ] && [ -b  \"${_mount_path_}\" ]; then\n\t\techo \"ERROR :: Already some device is mounted in path \\\"${_mount_path_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#WE HAVE TO CREATE DIRECTORY.\n\t`/bin/mkdir -p ${_mount_path_}`\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to create mount path \\\"${_mount_path_}\\\" to mount partition \\\"${_partition_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#NOW MOUNT THE PARTITION.WE NEEED TO KNOW THE FILE SYSTEM FOR IT?\n\t`mount ${_partition_} ${_mount_path_}`\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to mount partition \\\"${_partition_}\\\" at \\\"${_mount_path_}\\\"\"\n\t\t`/bin/rmdir  ${_mount_path_}`\n\t\treturn $_FAILED_\n\tfi \n\treturn $_SUCCESS_\n}\n\n#It installs GRUB.\n#_IN_ MOUNT_PATH\n#_IN_ Partition\nfunction InstallGRUB\n{\n\t_device_=$1\n\t_mount_path_=$2\n\t\n\t_active_partition_=\"${_device_}1\" \n\techo \"Install GRUB : ${_device_} , ${_mount_path_}, ${_active_partition_}.\"\n\tgrub-install --force-lba --no-floppy --root-directory=${_mount_path_} ${_active_partition_}\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to install GRUB on partition \\\"${_partition_}\\\".Using option --recheck.\"\n\t\tgrub-install --force-lba --no-floppy --recheck --root-directory=${_mount_path_} ${_active_partition_}\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to install GRUB on partition \\\"${_partition_}\\\".\"\n\t\t\treturn $_FAILED_\n\t\tfi\n\tfi\n\n\t#Performing a check to see whether GRUB exists in sector 0\t\n\tdd bs=512 count=1 if=${_device_} 2>/dev/null | strings | grep GRUB\n\tif [ 0 -ne $?  ]; then\n\t\techo \"GRUB is not found in sector 0.executing command to install it on base device.\"\n\t\techo \"Install GRUB : ${_device_} , ${_mount_path_}, ${_active_partition_}.\"\n\t\tgrub-install --force-lba --no-floppy --root-directory=${_mount_path_} ${_device_}\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to install GRUB on device \\\"${_device_}\\\".Using option --recheck.\"\n\t\t\tgrub-install --force-lba --no-floppy --recheck --root-directory=${_mount_path_} ${_device_}\n\t\t\tif [ 0 -ne $? ]; then\n\t\t\t\techo \"ERROR :: Failed to install GRUB on device \\\"${_device_}\\\".\"\n\t\t\t\treturn $_FAILED_\n\t\t\tfi\n\t\tfi\n\tfi\n\n\treturn $_SUCCESS_\n}\n\n#Finds PartitionNumber\n#_IN_ BASE DEVICE --> either /dev/sda (or) /dev/cciss/c0do (or) /dev/mapper/<id>\n#_IN_ PARTITION --> either /dev/sda1 (or) /dev/cciss/c0d0p1 (or) /dev/mapper/<id>p1\nfunction FindPartitionNumber\n{\n\t_partition_=$1\n\t_device_=$2\n\techo \"finding partition number of partition \\\"${_partition_}\\\" on device \\\"${_device_}\\\".\"\t\n\t#FIRST WE NEED TO CHECK WHETHER PARTITION AND DEVICE CORRESPONDS TO EACH OTHER?\n\techo ${_partition_} | grep ${_device_} > /dev/null 2>&1\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: device \\\"${_device_}\\\" and partition \\\"${_partition_}\\\" does not corresponds to each other.\"\n\t\treturn $_FAILED_\n\tfi\n\n\t_partition_number_=`echo ${_partition_} | sed -e \"s:${_device_}::\"`\t\n\t#CHECK IF PARTITION NUMBER CONTAINS ALPHABETS?\n\t_partition_number_=`echo ${_partition_number_} | sed -e \"s:[a-z|A-Z]*::\"`\n\t\n\techo \"partition \\\"${_partition_}\\\" is $_partition_number_ partition of device \\\"${_device_}\\\".\"\n\t_PARTITON_NUMBER_=${_partition_number_}\n\treturn $_SUCCESS_\n}\n\n#It finds SCSI name for a multipath device\n#_IN_ multipath device --> /dev/mapper/<id>\nfunction FindSCSIDeviceForAMultipathDevice \n{\n\t_multipath_device_=$1\n\techo \"Finding SCSI device for multipath device \\\"${_multipath_device_}\\\".\"\n\n\t_scsi_device_name_=`multipath -l ${_multipath_device_} | awk 'END {print $3}'` >/dev/null 2>&1\n\techo \"scsi device name for multipath device \\\"${_multipath_device_}\\\" is \\\"${_scsi_device_name_}\\\".\"\n\t_scsi_device_name_=\"/dev/${_scsi_device_name_}\"\n\n\tif [ -z \"${_scsi_device_name_}\" ]; then\n\t\techo \"ERROR :: Failed to find scsi device name for partition \\\"${_MPARTITION_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t_SCSI_DEVICE_NAME_FOR_MPARTITION_=$_scsi_device_name_\n\t\n\treturn $_SUCCESS_\n}\n\nfunction BlackListAMultipathDevice\n{\n\t#WE NEED TO BLOCKLIST THE DEVICE FROM MULTIPATH.CONF FILE.\n\t#blacklist {\n\t#       wwid 26353900f02796769\n\t#\tdevnode \"^(ram|raw|loop|fd|md|dm-|sr|scd|st)[0-9]*\"\n\t#\tdevnode \"^hd[a-z]\"\n\t#}\n\t# Assumes that blacklist does not start with #, needs to be handled\n\t_multipath_device_=$1\n\t_multipath_org_file_=$2\n\t_multipath_mod_file_=$3\n\n\t_wwid_=`echo ${_multipath_device_} | sed -e s:/dev/mapper/:: | sed -e s:/::`\n\tsed -e \"/^blacklist.*{/ a wwid ${_wwid_}\" ${_multipath_mod_file_} > ${_multipath_org_file_}\n\treturn $_SUCCESS_\n}\n\n#It Finds the base multipath device for a partition.\n#_IN_ Partition --> Should be in format of /dev/mapper/<ID>\nfunction FindMultipathDeviceForPartition\n{\n\t_multipath_partition_=$1\n\techo \"finding base multipath device for multipath partition ${_multipath_partition_}.\"\t\n\t_multipath_list_=`multipath -ll | grep -i \"Virtual disk\" | awk '{print $1}'` > /dev/null 2>&1\n\techo \"multipath device list = ${_multipath_list_}.\"\n\t_multipath_device_=\"\"\n\tfor _multipath_id_ in ${_multipath_list_}\n\tdo\n\t\t_contains_mpartition_=`fdisk -l /dev/mapper/${_multipath_id_} | grep ${_multipath_partition_}` > /dev/null 2>&1\n\t\tif [ -z \"${_contains_mpartition_}\" ]; then\n\t\t\tcontinue\n\t\tfi\n\t\t\n\t\t_multipath_device_=\"/dev/mapper/${_multipath_id_}\"\n\t\techo \"base multipath device for partition \\\"${_multipath_partition_}\\\" is \\\"${_multipath_device_}\\\".\"\n\tdone\n\t\n\tif [ -z \"${_multipath_device_}\" ]; then\n\t\techo \"ERROR :: Failed to find multipath device for partition \\\"${_multipath_partition_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t_MDEVICE_=${_multipath_device_}\n\treturn $_SUCCESS_\n}\n\nfunction RemoveAMultipathDevice\n{\n\t_MDEVICE_=$1\n\techo \"Cleaning up Multipath device \\\"${_MDEVICE_}\\\"\"\n\tfor _m_partition_ in ${_PARTIION_LIST_ON_A_DEVICE_}\n\tdo\n\t\techo \"Removing partition \\\"${_m_partition_}\\\"\"\n\t\tdmsetup -f remove ${_m_partition_} > /dev/null 2>&1\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to remove partition \\\"${_m_partition_}\\\".\"\n\t\t\tcontinue\n\t\tfi\n\t\t`sleep 3`\n\tdone\n\n\t#RUN REMOVE command\n\t`sleep 10`\n\tif [ ! -b ${_MDEVICE_} ]; then\n\t\techo \"Device \\\"${_MDEVICE_}\\\" is not a block device.\"\n\t\treturn $_FAILED_\n\tfi\n\n\tdmsetup -f remove ${_MDEVICE_} > /dev/null 2>&1\n\tif [ 0 -ne $? ]; then\n\t\tdmsetup clear ${_MDEVICE_} > /dev/null 2>&1\n\t\tdmsetup -f remove ${_MDEVICE_} > /dev/null 2>&1\n\t\tif [ 0 -ne $? ]; then\n\t\t\techo \"ERROR :: Failed to remove multipath device \\\"${_MDEVICE_}\\\".\"\n\t\t\tps -aef\n\t\t\tdmsetup ls | grep \"${_MDEVICE_}\"\n\t\t\tdmsetup info ${_MDEVICE_}\n\t\t\tdmsetup ls --tree\n\t\t\tlsof \"${_MDEVICE_}\"\n\t\t\tfuser \"${_MDEVICE_}\"\n\t\t\t#Remove ALL Partitions using kpartx -d\n\t\t\tkpartx -d ${_MDEVICE_}\n\t\t\treturn $_FAILED_\n\t\tfi\n\tfi\n\n\t#RUN CLEAR command.\n\tdmsetup clear ${_MDEVICE_} > /dev/null 2>&1\n\tif [ 0 -ne $? ]; then\n\t       echo \"ERROR :: Failed to clear multipath device \\\"${_MDEVICE_}\\\".\"\n\tfi\n\n\t`sleep 2`\n\treturn $_SUCCESS_\n}\n\nfunction FindSCSIDeviceForMultipathPartition \n{\n\t#First find the corresponding multipath device for partition.\n\t_multipath_list_=`multipath -ll | grep -i \"Virtual disk\" | awk '{print $1}'` >/dev/null 2>&1\n\techo \"multipath devices = ${_multipath_list_}.\"\n\t_scsi_device_name_=\"\"\n\tfor _multipath_id_ in ${_multipath_list_}\n\tdo\n\t\t_multipath_device_=\"/dev/mapper/${_multipath_id_}\"\n\t\t_contains_mpartition_=`fdisk -l ${_multipath_device_} | grep ${_MPARTITION_}` >/dev/null 2>&1\n\t\tif [ -z \"${_contains_mpartition_}\" ]; then\n\t\t\tcontinue\n\t\tfi\n\t\techo \"base multipath device for partition \\\"${_MPARTITION_}\\\" is \\\"${_multipath_device_}\\\".\"\n\t\t\n\t\t_scsi_device_name_=`multipath -l ${_multipath_device_} | awk 'END {print $3}'` >/dev/null 2>&1\n\t\techo \"scsi device name for multipath device \\\"${_multipath_device_}\\\" is \\\"${_scsi_device_name_}\\\".\"\n\t\t_scsi_device_name_=\"/dev/${_scsi_device_name_}\"\n\t\tbreak\n\tdone\n\n\tif [ -z \"${_scsi_device_name_}\" ]; then\n\t\techo \"ERROR :: Failed to find scsi device name for partition \\\"${_MPARTITION_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t_SCSI_DEVICE_NAME_FOR_MPARTITION_=$_scsi_device_name_\n\t\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION MAKE SURE THAT A NEW FILE IS CREATED FOR HOST SPECIFIED. FILE CONTAINS PROTECTED DEVICES IN ORDER.\n#IT READS INPUT FROM FILE _INPUT_INMAGE_UNIT_DISKS_FILE_ \nfunction ExecuteTask_PROTECT\n{\n\t#MAKE SURE WE HAVE AN INMAGE_HOST_ID\n\techo \"Executing Task PROTECT.\"\n\tif [ ! \"${_MACHINE_UUID_}\" ]; then\n\t\techo \"ERROR :: A Host ID has to be specified.\"\n\t\techo \"ERROR :: Host ID is required to write protected disk list\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#WE HAVE TO CHECK WHETHER VX INSTALL PATH IS SPECIFIED\n\tif [ -z \"$_FILES_PATH_\" ]; then\n\t\techo \"ERROR :: Working directory where script files exist is not specified.\"\n\t\techo \"ERROR :: Failed to write protected disks list for host with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#WE HAVE HOST ID,MAKE SURE INPUT FILE PATH IS SPECIFIED \t\n\t_INMAGE_SCSI_UNITS_FILE_PATH_=\"$_PLAN_NAME_/Inmage_scsi_unit_disks.txt\"\n\t_PROTECTED_DISK_LIST_FILE_PATH_=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n\t_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n\techo \"InMage scsi units file path = $_INMAGE_SCSI_UNITS_FILE_PATH_\"\n\techo \"Protected Disk List File = $_PROTECTED_DISK_LIST_FILE_PATH_\"\n\t\n\t#WE HAVE FILE NAME, CHECK IF FILE EXISTS\n\tif [ ! -f \"$_INMAGE_SCSI_UNITS_FILE_PATH_\" ] || [ ! -r \"${_INMAGE_SCSI_UNITS_FILE_PATH_}\" ]; then\n\t\techo \"ERROR :: Failed to find/read file \\\"$_INMAGE_SCSI_UNITS_FILE_PATH_\\\".\"\n\t\techo \"ERROR :: Please make sure that \\\"$_INMAGE_SCSI_UNITS_FILE_PATH_\\\" exists and is granted permmission to read.\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t#NEED TO DELETE FILE IF ALREADY EXISTS IN /INMAGE_INSTALLATION_PATH/failover_data\n\tif [ -f \"$_PROTECTED_DISK_LIST_FILE_PATH_\" ]; then\n\t\techo \"As Task is PROTECT removing file \\\"$_PROTECTED_DISK_LIST_FILE_PATH_\\\".\"\n\t\trm -rf \"$_PROTECTED_DISK_LIST_FILE_PATH_\"\n\tfi\n\n\t#WE HAVE FILE AS WELL. READ THE FILE AND OUTPUT IT\"S CONTENT IN TO A PROTECTED_DISK_LIST.\n\ttr -d '\\r' < $_INMAGE_SCSI_UNITS_FILE_PATH_ > $_INMAGE_SCSI_UNITS_FILE_PATH_.tmp\n\tcp -f $_INMAGE_SCSI_UNITS_FILE_PATH_.tmp $_INMAGE_SCSI_UNITS_FILE_PATH_\n\t_line_num_=`cat $_INMAGE_SCSI_UNITS_FILE_PATH_ | grep -n \"$_MACHINE_UUID_\" | awk -F\":\" '{print $1}'`\n\techo \"Line Num = $_line_num_\"\n\t_next_line_num_=$((_line_num_+1))\n\techo \"next line number = $_next_line_num_\"\n\t_num_lines_to_read_=`sed -n \"$_next_line_num_ , $_next_line_num_ p\" \"$_INMAGE_SCSI_UNITS_FILE_PATH_\"`\n\t_read_from_line_num_=`echo $_num_lines_to_read_ | sed -e \"s:^M::g\"`\n\t_read_from_line_num_=$((_next_line_num_ + 1))\n\t_read_untill_line_num_=$((_next_line_num_+_num_lines_to_read_))\n\t_lines_=`sed -n \"$_read_from_line_num_ , $_read_untill_line_num_ p\" \"$_INMAGE_SCSI_UNITS_FILE_PATH_\"`\n\tfor _line_ in ${_lines_}\n\tdo\n\t\techo $_line_>>\"$_PROTECTED_DISK_LIST_FILE_PATH_\"\n\tdone\n\n\tif [ -f $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_ ]; then\n\t\trm -f $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\n\tfi\n\n\t_protected_dev_entry=0\n\techo \"Mapping table for protected source devices and target devices under recovered VM\" >> $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\n\techo \"Source device\t\tTarget device in recovered VM\" >> $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\n\tfor _line_ in ${_lines_}\n\tdo\n\t\t# Get protected device name\n\t\t_src_dev_=`echo $_line_ | awk -F'!@!@!' '{ print $1 }'`\n\t\tGetTargetDiskName $_protected_dev_entry \n\t\ttarget_device=$_disk_name_\n\t\techo \"${_src_dev_}\t${target_device}\" >> $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\n\t\t_protected_dev_entry=$((_protected_dev_entry+1))\n\tdone\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION MAKE SURE THAT A NEW PROTECTED DEVICES ARE APPENDED IN ORDER TO FILE.\n#IT READS INPUT FROM FILE _INPUT_INMAGE_UNIT_DISKS_FILE_\nfunction ExecuteTask_ADDPROTECT\n{\n\t#MAKE SURE WE HAVE AN INMAGE_HOST_ID\n\techo \"Executing Task ADDPROTECT.\"\n\tif [ ! \"${_MACHINE_UUID_}\" ]; then\n\t\techo \"ERROR :: A Host ID has to be specified.\"\n\t\techo \"ERROR :: Host ID is required to write protected disk list\"\n\t\treturn $_FAILED_\n\tfi\n\t#WE HAVE TO CHECK WHETHER VX INSTALL PATH IS SPECIFIED\n\tif [ -z \"$_FILES_PATH_\" ]; then\n\t\techo \"ERROR :: Working direcotry where script files exist is not specified.\"\n\t\techo \"ERROR :: Failed to write protected disks list for host with host id = \\\"$_MACHINE_UUID_\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\t#WE HAVE HOST ID,MAKE SURE INPUT FILE PATH IS SPECIFIED\n\t_INMAGE_SCSI_UNITS_FILE_PATH_=\"$_PLAN_NAME_/Inmage_scsi_unit_disks.txt\"\n\t_PROTECTED_DISK_LIST_FILE_PATH_=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n\t_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_=\"$_VX_FAILOVER_DATA_PATH_/${_PROTECTED_DISKS_LIST_FILE_NAME_}\"\n\techo \"InMage scsi units file path = $_INMAGE_SCSI_UNITS_FILE_PATH_\"\n\techo \"Protected Disk List File = $_PROTECTED_DISK_LIST_FILE_PATH_\"\n\n\t#WE HAVE FILE NAME, CHECK IF FILE EXISTS\n\tif [ ! -f \"$_INMAGE_SCSI_UNITS_FILE_PATH_\" ] || [ ! -r \"${_INMAGE_SCSI_UNITS_FILE_PATH_}\" ]; then\n\t\techo \"ERROR :: Failed to find/read file \\\"$_INMAGE_SCSI_UNITS_FILE_PATH_\\\".\"\n\t\techo \"ERROR :: Please make sure that \\\"$_INMAGE_SCSI_UNITS_FILE_PATH_\\\" exists and is granted permmission to read.\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#WE HAVE FILE AS WELL. READ THE FILE AND OUTPUT IT\"S CONTENT IN TO A PROTECTED_DISK_LIST.\n\ttr -d '\\r' < $_INMAGE_SCSI_UNITS_FILE_PATH_ > $_INMAGE_SCSI_UNITS_FILE_PATH_.tmp\n\tcp -f $_INMAGE_SCSI_UNITS_FILE_PATH_.tmp $_INMAGE_SCSI_UNITS_FILE_PATH_\n\t_line_num_=`cat $_INMAGE_SCSI_UNITS_FILE_PATH_ | grep -n \"$_MACHINE_UUID_\" | awk -F\":\" '{print $1}'`\n\techo \"Line Num = $_line_num_\"\n\t_next_line_num_=$((_line_num_+1))\n\techo \"next line number = $_next_line_num_\"\n\t_num_lines_to_read_=`sed -n \"$_next_line_num_ , $_next_line_num_ p\" \"$_INMAGE_SCSI_UNITS_FILE_PATH_\"`\n\t_read_from_line_num_=`echo $_num_lines_to_read_ | sed -e \"s:^M::g\"`\n\t_read_from_line_num_=$((_next_line_num_ + 1))\n\t_read_untill_line_num_=$((_next_line_num_+_num_lines_to_read_))\n\t_lines_=`sed -n \"$_read_from_line_num_ , $_read_untill_line_num_ p\" \"$_INMAGE_SCSI_UNITS_FILE_PATH_\"`\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tfor _line_ in ${_lines_}\n\tdo\n\t\techo $_line_>>\"$_PROTECTED_DISK_LIST_FILE_PATH_\"\n\tdone\n\t_protected_dev_entry=`cat $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_ | wc -l` \n\tfor _line_ in ${_lines_}\n\tdo\n\t\t# Get protected device name\n\t\t_src_dev_=`echo $_line_ | awk -F'!@!@!' '{ print $1 }'`\n\t\tGetTargetDiskName $_protected_dev_entry \n\t\ttarget_device=$_disk_name_\n\t\techo \"${_src_dev_}\t${target_device}\" >> $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\n\t\t_protected_dev_entry=$((_protected_dev_entry+1))\n\tdone\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION PREPARES TARGET INFORMATION AND MAKES NECESSARY CHANGES.\nfunction ExecuteTask_PREPARETARGET\n{\n\t#FIRST THING TO MAKE SURE --> _MOUNT_PATH_ ?? DID WE GET SOME STRING?\n\tif [ ! \"${_MOUNT_PATH_}\" ]; then\n\t\techo \"ERROR :: Mount point is not specified.\"\n\t\techo \"ERROR :: Mount point has to be specfied in order to modify files.\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t#NEED TO CHECK IF MOUNT PATH SPECIFIED IS A BLOCK DEVICE\n\t#if [ ! -b \"$_MOUNT_PATH_\" ]; then\n\t#\techo \"ERROR :: Invalid mount point. Mount point : $_MOUNT_PATH_.\"\n\t#\techo \"ERROR :: Please specify a valid mount point which is of a block device type.\"\n\t#\treturn $_FAILED_\n\t#fi\n\t_LOGS_=\"$_PLAN_NAME_/${_MACHINE_UUID_}-Logs/\"\n\tif [ ! -d \"$_LOGS_\" ]; then\n\t\tmkdir -p \"${_LOGS_}\"\n\tfi\n\n\t_ret_code_boot_=$_SUCCESS_\n\t_ret_code_etc_=$_SUCCESS_\n\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\" ] || [ \"all\" = \"${_MOUNT_PATH_FOR_}\" ]; then\n\t\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\"  ]; then\n\t\t\tBackupConfigFile \"$_MOUNT_PATH_\"\n\t\t\tPrepare_boot \"$_MOUNT_PATH_\"\n\t\t\t_ret_code_boot_=$?\n\t\telif [ -d \"$_MOUNT_PATH_/boot\" ]; then\n\t\t\tBackupConfigFile \"$_MOUNT_PATH_/boot/\"\n\t\t\tPrepare_boot \"$_MOUNT_PATH_/boot/\"\n\t\t\t_ret_code_boot_=$?\n\t\telse\n\t\t\techo \"ERROR :: Cross check whether mounted partition contains boot information or not.\"\n\t\t\t_ret_code_boot_=$_FAILED_\n\t\tfi\n\tfi\n\n\tif [ \"etc\" = \"${_MOUNT_PATH_FOR_}\" ] || [ \"all\" = \"${_MOUNT_PATH_FOR_}\" ]; then\n\t\tif [ -d \"$_MOUNT_PATH_/etc\" ]; then\n\t\t\tPrepare_etc \"$_MOUNT_PATH_/etc\"\n\t\t\t_ret_code_etc_=$?\n\t\telif [ -f \"$_MOUNT_PATH_/fstab\" ]; then\n\t\t\tPrepare_etc \"$_MOUNT_PATH_\"\n\t\t\t_ret_code_etc_=$?\n\t\telse\n\t\t\techo \"ERROR :: Cross check whether mounted partition contains etc information or not.\"\n\t\t\t_ret_code_boot_=$_FAILED_\n\t\tfi\n\tfi\n\t\n\tif [ $_FAILED_ -eq $_ret_code_boot_ ] || [ $_FAILED_ -eq $_ret_code_etc_ ]; then\n\t\treturn $_FAILED_\n\tfi\n\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION MODIFIES INITRD MODULES LIST WHICH ARE LOADED DURING BOOT.\nfunction ModifyInitrdModulesList\n{\n\t_kernel_base_file_path_=$1\n\t_kernel_config_file_path_=\"$_kernel_base_file_path_/kernel\"\n\t_kernel_config_file_orig_=\"${_kernel_config_file_path_}${_INMAGE_ORG_}\"\n\t\n\t#MAKE SURE THAT FILE EXISTS?\n\tif [ ! -f $_kernel_config_file_path_ ]; then\n\t\techo \"WARNING :: Failed to find file \\\"$_kernel_config_file_path_\\\".\"\n\t\treturn $_SUCCESS_\n\tfi\n\n\t#FILE EXISTS TAKE A COPY\n\tif [ -f \"${_kernel_config_file_orig_}\" ]; then\n\t\tMOVE \"${_kernel_config_file_orig_}\" \"$_kernel_config_file_path_\"\n\tfi\n\tCOPY \"$_kernel_config_file_path_\" \"${_kernel_config_file_orig_}\"\n\n\t#MODIFY - valid only for SuSE as INITRD_MODULES exists only on SuSE\n\tsed -i \"/^INITRD_MODULES=\\\"/{\n\t\ts/\\\"$/ sd_mod mptspi\\\"/\n\t}\" $_kernel_config_file_path_\n\treturn $_SUCCESS_\n}\n\n\nfunction MapSrcToTgt\n{\n\t_SRC2TGT_MAPPED_DEVICE_=\"\"\n\t_CX_XML_FILE_=\"$_VX_FAILOVER_DATA_PATH_/${_GET_HOST_INFO_XML_FILE_NAME_}\"\n\t_search_dev_=$1\n\t_lv_alias=\"\"\n\t_base_device=\"\"\n\n\tif [ -z $_search_dev_ ]; then\n\t\t# Empty input\n\t\treturn $_FAILED_\n\tfi\n\n\t# Find if _search_dev_ is a logical volume\n\tIsDevice_LV $_search_dev_\n\t_lv_alias=$_lv_dev_name_\n\n\tDeref_SymLink $_search_dev_\n\t_real_device_name=$_real_partition_name_\n\n\t# Now find the base device from device hierarchy\n\tif [ -z $_lv_alias ]; then\n\t\tif [ -z $_real_device_name ]; then\n\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_search_dev_\n\t\telse\n\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_real_device_name\n\t\tfi\n\t\t_base_device=$_base_diskname_\n\telse\n\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_search_dev_\n\t\t_base_device=$_base_diskname_\n\t\tif [ -z $_base_device ]; then\n\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_lv_alias\n\t\t\t_base_device=$_base_diskname_\n\t\tfi\n\tfi\n\n\tif [ -z $_base_device ]; then\n\t\t\treturn $_FAILED_\n\telse\n\t\tGetProtectedDeviceEntry $_base_device\n\t\t_protected_dev_entry=$?\n\t\techo \"entry = ${_protected_dev_entry}.\"\n\t\tif [ \"${_protected_dev_entry}\" = \"0\" ]; then\n\t\t\treturn $_FAILED_\n\t\tfi\n\tfi\n\t\n\t# _search_dev_ contains device that needs to be replaced with UUID\n\tif [ ${_search_dev_} ]; then\n\t\tif [ -z $_lv_alias ]; then\n\t\t\tpartition_num=\"\"\n\t\t\t_protected_dev_entry=$((_protected_dev_entry-1))\n\t\t\tGetTargetDiskName $_protected_dev_entry \n\t\t\ttarget_device=$_disk_name_\n\t\t\tif [ -z $_real_device_name ]; then\n\t\t\t\ttp_str=`echo ${_search_dev_} | sed \"s:[0-9]*$::\"`\n\t\t\t\tpartition_num=`echo ${_search_dev_} | sed \"s:${tp_str}::\"`\n\t\t\t\ttarget_device=\"${target_device}${partition_num}\"\n\t\t\telse\n\t\t\t\ttp_str=`echo ${_real_device_name} | sed \"s:[0-9]*$::\"`\n\t\t\t\tpartition_num=`echo ${_real_device_name} | sed \"s:${tp_str}::\"`\n\t\t\t\ttarget_device=\"${target_device}${partition_num}\"\n\t\t\tfi\n\t\t\t_SRC2TGT_MAPPED_DEVICE_=$target_device\n\t\telse\n\t\t\t_SRC2TGT_MAPPED_DEVICE_=$_search_dev_\n\t\tfi\n\tfi\n\n\tif [ -z \"${_SRC2TGT_MAPPED_DEVICE_}\" ]; then\n\t\treturn $_FAILED_\n\tfi\n\treturn $_SUCCESS_\n}\nfunction ModifyFstabFile\n{\n\t_fstab_file_=$1\n\t#have a back up of original file.\n\t_CX_XML_FILE_=\"$_VX_FAILOVER_DATA_PATH_/${_GET_HOST_INFO_XML_FILE_NAME_}\"\n\t_fstab_file_orig_=\"${_fstab_file_}${_INMAGE_ORG_}\"\n\t\t\n\t#if [ -f \"${_fstab_file_orig_}\" ]; then\n\t#\tMOVE \"${_fstab_file_orig_}\" \"$_fstab_file_\"\n\t#fi\n\tCOPY \"$_fstab_file_\" \"${_fstab_file_orig_}\"\n\t\n\tcat \"$_fstab_file_orig_\" | while read _line_\n\tdo \n\t\techo \"Line read = ${_line_}.\"\n\t\t_uuid_=\"\"\n\t\t_label_=\"\"\n\t\t_search_dev_=\"\"\n\t\t_lv_alias=\"\"\n\t\t_base_device=\"\"\n\t\t# Find if base device of UUID or LABEL is protected\n\t\ttemp_var=`echo $_line_ | egrep \"^[ ]*UUID|[ ]*LABEL\" | awk -F\"=\" '{print $1 }'`\n\t\tif [ \"${temp_var}\" ]; then\n\t\t\t# Find the device name with UUID or LABEL to see if it protected or not\n\t\t\t_uuid_=`echo $_line_ | awk -F\"UUID=\" '{ print $2 }' | awk '{ print $1 }' | sed -e \"s/\\\"//g\"`\n\t\t\tif [ \"${_uuid_}\" ]; then\n\t\t\t\tFind_Device_From_UUID $_uuid_\n\t\t\t\t_search_dev_=$_dev_name_\n\t\t\telse\n\t\t\t\t_label_=`echo $_line_ | awk -F\"LABEL=\" '{ print $2 }' | awk '{ print $1 }' | sed -e \"s/\\\"//g\"`\n\t\t\t\t\n\t\t\t\tFind_Device_From_LABEL $_label_\n\t\t\t\t_search_dev_=$_dev_name_\n\t\t\tfi\n\t\telse\n\t\t\t# Take care of device name(/dev/*) entries in /etc/fstab\n\t\t\t_fstab_dev_name_=`echo $_line_ | awk '{print $1}'`\n\t\t\techo \"$_INPUT_CONFIG_FILE_\"\n\t\t\techo `sed -n  \"/^[=]* FSTAB UUID Information - START [=]*/,/^[=]* FSTAB UUID Information - END [=]*/p\" \"$_INPUT_CONFIG_FILE_\"`\n\t\t\t_fstab_dev_safe_pattern_=$(printf \"%s\\n\" \"$_fstab_dev_name_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t_temp_search_dev_=`sed -n  \"/^[=]* FSTAB UUID Information - START [=]*/,/^[=]* FSTAB UUID Information - END [=]*/p\" \"$_INPUT_CONFIG_FILE_\" | grep \"${_fstab_dev_safe_pattern_}:\" | head -1 | awk -F': ' '{print $1}'`\n\t\t\techo \"temp_search_dev = ${_temp_search_dev_}.\"\n\t\t\tif [ \"${_temp_search_dev_}\" ]; then\n\t\t\t\t_search_dev_=`echo \"$_temp_search_dev_\" | awk '{ print $1 }'`\n\t\t\t\t_search_dev_=`echo $_search_dev_ | sed -e \"s: ::g\"`\n\t\t\telse\n\t\t\t\t# Entry is not a label or uuid or block device\n\t\t\t\t# or if swap entry is a file, then control would come here.\n\t\t\t\tcontinue\n\t\t\tfi\n\t\tfi\n\n\t\tif [ -z $_search_dev_ ]; then\n\t\t\t# comment out UUID or LABEL entry \n\t\t\t# $_label_ or $_uuid_ or $_search_dev_\n\t\t\tcontinue\n\t\tfi\n\n\t\t# Find if _search_dev_ is a logical volume\n\t\tIsDevice_LV $_search_dev_\n\t\t_lv_alias=$_lv_dev_name_\n\n\t\tDeref_SymLink $_search_dev_\n\t\t_real_device_name=$_real_partition_name_\n\n\t\t# Now find the base device from device hierarchy\n\t\tif [ -z $_lv_alias ]; then\n\t\t\tif [ -z $_real_device_name ]; then\n\t\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_search_dev_\n\t\t\telse\n\t\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_real_device_name\n\t\t\tfi\n\t\t\t_base_device=$_base_diskname_\n\t\telse\n            echo \"${_lv_alias} is an LV.\"\n\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_search_dev_\n\t\t\t_base_device=$_base_diskname_\n\t\t\tif [ -z $_base_device ]; then\n\t\t\t\tMapDeviceHierarchyToBaseDevice $_CX_XML_FILE_ $_lv_alias\n\t\t\t\t_base_device=$_base_diskname_\n\t\t\tfi\n\t\tfi\n\n\t\tif [ -z $_base_device ]; then\n\t\t\t# comment out UUID or LABEL entry \n\t\t\t# $_label_ or $_uuid_ or $_search_dev_\n\t\t\tcontinue\n\t\telse\n\t\t\tGetProtectedDeviceEntry $_base_device\n\t\t\t_protected_dev_entry=$?\n\t\t\techo \"entry = ${_protected_dev_entry}.\"\n\t\t\tif [ \"${_protected_dev_entry}\" = \"0\" ]; then\n\t\t\t\t# comment out UUID or LABEL entry \n\t\t\t\t# $_label_ or $_uuid_ or $_search_dev_\n\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_line_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\tsed -i \"s/${safe_pattern}/#${safe_pattern}/\" \"${_fstab_file_}\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\tif [  \"${_uuid_}\" ] || [ \"${_label_}\" ] || [ \"${_lv_alias}\" ]; then\n\t\t\t\t# It is protected and  if it's a uuid or label or lv entry in fstab file then continue.\n\t\t\t\tcontinue\n\t\t\tfi\n\t\tfi\n\t\t\n\t\t# _search_dev_ contains device that needs to be replaced with UUID\n\t\tif [ ${_search_dev_} ]; then\n\t\t\tFind_UUID_FSTABINFO $_search_dev_\n\t\t\tfinal_uuid=$_UUID_\n\t\t\techo \"Final UUID = $_UUID_\"\t\t \n\t\t\tif [ \"$final_uuid\" ]; then\n\t\t\t\t#Replace with UUID.\n\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_search_dev_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\tsed -i \"s/${safe_pattern}\\s/UUID=$final_uuid /\" \"${_fstab_file_}\"\n\t\t\telse\n\t\t\t\t#Need to take care of swap file.\t\n\t\t\t\t#check if Line contains swap\n\t\t\t\techo $_line_ | grep -i \"swap\" >/dev/null\n\t\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t\techo \"SWAP partition : $_search_dev_\"\n\t\t\t\t\t#now we have to match this partition to target device.\n\t\t\t\t\tif [ -z $_lv_alias ]; then\n\t\t\t\t\t\t# it is a partition, so map it target device on recovered VM\n\t\t\t\t\t\t#_protected_disklist=\"$_VX_INSTALL_PATH_/failover_data/$_MACHINE_UUID_.PROTECTED_DISKS_LIST\"\n\t\t\t\t\t\t#_protected_dev_entry=`GetProtectedDeviceEntry $`\n\t\t\t\t\t\tpartition_num=\"\"\n\t\t\t\t\t\t_protected_dev_entry=$((_protected_dev_entry-1))\n\t\t\t\t\t\tGetTargetDiskName $_protected_dev_entry \n\t\t\t\t\t\ttarget_device=$_disk_name_\n\t\t\t\t\t\tif [ -z $_real_device_name ]; then\n\t\t\t\t\t\t\ttp_str=`echo ${_search_dev_} | sed \"s:[0-9]*$::\"`\n\t\t\t\t\t\t\tpartition_num=`echo ${_search_dev_} | sed \"s:${tp_str}::\"`\n\t\t\t\t\t\t\ttarget_device=\"${target_device}${partition_num}\"\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\ttp_str=`echo ${_real_device_name} | sed \"s:[0-9]*$::\"`\n\t\t\t\t\t\t\tpartition_num=`echo ${_real_device_name} | sed \"s:${tp_str}::\"`\n\t\t\t\t\t\t\ttarget_device=\"${target_device}${partition_num}\"\n\t\t\t\t\t\tfi\n\t\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_search_dev_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\t\tsafe_pattern1=$(printf \"%s\\n\" \"$target_device\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\t\tsed -i \"s/${safe_pattern}/${safe_pattern1}/\" \"${_fstab_file_}\"\n\t\t\t\t\tfi\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\tdone\n\treturn $_SUCCESS_\n}\n\n\n#THIS FUNCTION MODIFIES \"SYSCONFIG/KERNEL\" FILE AND FSTAB FILE.\nfunction Prepare_etc\n{\n\t_etc_path_=\"$1\"\n\t_returnCode_=$_SUCCESS_\n\t\n\t_INPUT_CONFIG_FILE_=\"$_etc_path_/Configuration.info\"\n\t\n\tif [ -d \"${_etc_path_}/sysconfig\" ]; then\n\t\tModifyInitrdModulesList \"$_etc_path_/sysconfig\"\n\t\tif [ 0 -ne $? ]; then\n\t\t    _returnCode_=$_FAILED_\n\t\tfi\n\telse\n\t    echo \"WARNING :: Failed to find \\\"sysconfig\\\" folder under mount point \\\"$_etc_path_\\\".\"\n\t\techo \"Skipping initrd modules list changes.\"\n\tfi\n\n\tif [ ! -f \"$_etc_path_/fstab\" ]; then\n\t\techo \"ERROR :: Failed to find file \\\"fstab\\\" file under path \\\"$_etc_path_\\\".\"\n\t\techo \"ERROR :: Failed to modify fstab file.\"\n\t\t_returnCode_=$_FAILED_\n\t\t#return $_FAILED_\n\tfi\n\n\tModifyFstabFile \"$_etc_path_/fstab\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\t\t#return $?\n\tfi\n\n\tModifyModprobeFile \"$_etc_path_\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\t\t#return $?\n\tfi\n\t\n\t_lvm_conf_file_=\"$_etc_path_/lvm/lvm.conf\"\n\tModifyLvmConfFile \"$_lvm_conf_file_\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\t\t#return $?\n\tfi\n\t\n\tCOPY \"${_etc_path_}/multipath.conf\" \"$_LOGS_\"\n\t/bin/cp -rf \"${_etc_path_}/vxagent/vcon\" \"$_LOGS_\"\n\t/bin/cp -rf \"${_etc_path_}/vxagent/logs\" \"$_LOGS_\"\n\t#if [ -f \"${_MOUNT_PATH_}/var/log/messages\" ]; then\n\t#\tCOPY \"${_MOUNT_PATH_}/var/log/messages\" \"$_LOGS_\"\n\t#fi\n\n\t_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_=\"$_VX_FAILOVER_DATA_PATH_/$_PROTECTED_DISKS_LIST_FILE_NAME_\"\n\tif [ -f \"$_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_\" ]; then\n\t\tCOPY $_PROTECTED_DISK_MAPPING_LIST_FILE_PATH_ $_etc_path_/vxagent/logs/\n\tfi\n\n\t_VCON_ACTION_FILE_=\"$_etc_path_/vxagent/vcon/p2v_actions\"\n\tif [ ! -d \"$_etc_path_/vxagent/vcon/\" ]; then\n\t\tmkdir -p \"$_etc_path_/vxagent/vcon/\"\n\tfi\n\n\techo \"workflow=${_WORK_FLOW_}\" > $_VCON_ACTION_FILE_\n\tif [ 1 -eq ${_INSTALL_VMWARE_TOOLS_} ]; then\n\t\techo \"install_vmware_tools=1\" >> $_VCON_ACTION_FILE_\n\tfi\n\n\tif [ 1 -eq ${_UNINSTALL_VMWARE_TOOLS_} ]; then\n\t\techo \"uninstall_vmware_tools=1\" >> $_VCON_ACTION_FILE_\t\n\tfi\n\n\techo \"New GUID = ${_NEW_GUID_}\"\n\n\tif [ ! -z ${_NEW_GUID_} ]; then\n\t\techo \"new_guid=${_NEW_GUID_}\" >> $_VCON_ACTION_FILE_\n\tfi\n\t\n        echo \"create_initrd_images=1\" >> $_VCON_ACTION_FILE_\n\n\t#set VolumeFilteringDisabled to 1.\n\tsetVolumeFilteringDisabled \"$_etc_path_\" \"1\"\n\t\n\tClearBitMapFiles \"$_etc_path_/..\" \"$_etc_path_\"\n\treturn $_returnCode_\n}\n\nfunction setVolumeFilteringDisabled\n{\n\t_etc_path_=$1\n\t_set_volume_filtering_value_=$2\n\t_return_code_=$_SUCCESS_\n\n\t_involflt_path_=\"$_etc_path_/vxagent/involflt/\"\n\t_dev_directories_=`ls $_involflt_path_`\n\tfor _dev_directory_ in ${_dev_directories_}\n\tdo\n\t\t_check_file_=\"$_involflt_path_/$_dev_directory_/VolumeFilteringDisabled\"\n\t\tif [ -f \"$_check_file_\" ]; then\n\t\t\techo 1 > \"$_check_file_\"\n\t\tfi\n\tdone\n\n\treturn $_return_code_\n}\n\nfunction ModifyLvmConfFile_V2P\n{\n\t_lvm_conf_file_=$1\n\t_return_code_=$_SUCCESS_\n\n\t_lvm_conf_file_orig_=\"${_lvm_conf_file_}${_INMAGE_ORG_}\"\n\t_lvm_conf_file_mod_=\"${_lvm_conf_file_}${_INMAGE_MOD_}\"\n\n\tif [ ! -f \"${_lvm_conf_file_orig_}\" ]; then\n\t\techo \"Failed to find file ${_lvm_conf_file_orig_}.\"\n\t\t_return_code_=$_FAILED_\n\telse\n\t\tCOPY \"${_lvm_conf_file_}\" \"${_lvm_conf_file_mod_}\"\n\t\tMOVE \"${_lvm_conf_file_orig_}\" \"${_lvm_conf_file_}\"\n\tfi\n\n\treturn $_return_code_\n}\n\nfunction ModifyLvmConfFile\n{\n\t_lvm_conf_file_=$1\n\t_return_code_=$_SUCCESS_\n\n\t_lvm_conf_file_orig_=\"${_lvm_conf_file_}${_INMAGE_ORG_}\"\n\n\tif [ ! -f \"${_lvm_conf_file_}\" ]; then\n\t\techo \"lvm.conf file does not exist under /etc/lvm.\"\n\t\treturn $_return_code_\n\tfi\n\n\tif [ -f \"${_lvm_conf_file_orig_}\" ]; then \n\t\tMOVE \"${_lvm_conf_file_orig_}\" \"${_lvm_conf_file_}\"\n\telse\n\t\tCOPY \"${_lvm_conf_file_}\" \"${_lvm_conf_file_orig_}\"\n\tfi\n\t\n\tCOPY \"${_lvm_conf_file_}\" \"$_LOGS_\"\n\t#here we need to call Modify lvm.conf file to include all devices.\n\t_line_=`cat \"$_lvm_conf_file_\" | grep -P \"^(\\s*)filter(\\s*)=(\\s*).*\"`\n    echo $_line_\n    \n    if [ ! -z \"$_line_\" ]; then\n        _line_number_=`cat \"$_lvm_conf_file_\" | grep -P -n \"^(\\s*)filter(\\s*)=(\\s*).*\" | awk -F\":\" '{print $1}'`\n        echo \"Updating filter entry in $_lvm_conf_file_ file at line: $_line_number_\"\n        sed -i \"$_line_number_ c\\filter=\\\"a\\/.*\\/\\\"\" $_lvm_conf_file_\n    else\n        echo \"filter entry not found. Nothing to update in $_lvm_conf_file_ file\"\n    fi\n\n\treturn $_return_code_\n}\n\n#Modified modprobe.conf file under /etc directory.\nfunction  ModifyModprobeFile \n{\n\t_etc_path_=$1\n\t_mod_probe_file_=\"$_etc_path_/$_MOD_PROBE_FILE_NAME_\"\n\t_return_code_=$_SUCCESS_\n\n\t#READ THE OS ENTRY FROM CONFIGURATION FILE.\n\t_DISTRIBUTION_DETAILS_=`grep \"Distribution details                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\techo \"Distribution details = ${_DISTRIBUTION_DETAILS_}\"\n\n\tcase \"${_DISTRIBUTION_DETAILS_}\" in\n                RHEL4*)\n\t\t\t#NEED TO MODIFY MODPROBE FILE.\n\t\t\techo \"Performing modprobe changes for distribution ${_DISTRIBUTION_DETAILS_}.\"\n\t\t\tModifyModprobeFile_RHEL4 \"${_DISTRIBUTION_DETAILS_}\" \"$_mod_probe_file_\"\n\t\t\tif [ 0 -ne $? ]; then\n\t\t\t\t_return_code_=$_FAILED_\n\t\t\tfi\n\t\t\t;;\n\t\t*)\n\t\t\techo \"Skipping modprobes changes for distribution ${_DISTRIBUTION_DETAILS_}.\"\n\t\t\t;;\n\tesac\n\n\treturn $_return_code_\n}\n\nfunction ModifyModprobeFile_RHEL4 \n{\n\t_os_=$1\n\t_mod_probe_file_=$2\n\n\t_modprobe_file_orig_=\"${_mod_probe_file_}${_INMAGE_ORG_}\"\n\t_modprobe_file_mod_=\"${_mod_probe_file_}${_INMAGE_MOD_}\"\n\n\tif [! -f \"${_mod_probe_file_}\" ]; then\n\t\techo \"modprobe.conf file does not exist. OS=${_os_}.\"\n\t\treturn $_SUCCESS_\n\tfi\n\t\n\tif [ -f \"${_modprobe_file_orig_}\" ]; then\n\t\tMOVE \"${_modprobe_file_orig_}\" \"$_mod_probe_file_\"\n\tfi\n\tCOPY \"$_mod_probe_file_\" \"${_modprobe_file_orig_}\"\n\t#alias eth0 e1000\n\t#alias scsi_hostadapter mptbase\n\t#alias scsi_hostadapter1 mptscsi\n\t#alias scsi_hostadapter2 mptfc\n\t#alias scsi_hostadapter3 mptspi\n\t#alias scsi_hostadapter4 mptsas\n\t#alias scsi_hostadapter5 mptscsih\n\tcat \"${_modprobe_file_orig_}\" | grep -i \"scsi_hostadapter\" | grep -v \"involflt\" | while read _line_\n\tdo\n        \techo $_line_\n\t        sed -i \"/$_line_/d\" \"${_mod_probe_file_}\"\n\tdone\n\n\tcat \"${_modprobe_file_orig_}\" | grep -P -i \"eth[0-9]+\" | while read _line_\n\tdo\n        \techo $_line_\n\t        sed -i \"/$_line_/d\" \"${_mod_probe_file_}\"\n\tdone\n\n\techo \"alias eth0 e1000\n\talias scsi_hostadapter mptbase\n\talias scsi_hostadapter1 mptscsi\n\talias scsi_hostadapter2 mptfc\n\talias scsi_hostadapter3 mptspi\n\talias scsi_hostadapter4 mptsas\n\talias scsi_hostadapter5 mptscsih\" > \"$_modprobe_file_mod_\"\n\n\tcat \"${_mod_probe_file_}\" >> \"$_modprobe_file_mod_\"\n\n\tMOVE \"$_modprobe_file_mod_\" \"${_mod_probe_file_}\"\n\treturn $_SUCCESS_\n}\n\n#This handles change requirements in lvm.conf file in initrd image.\n#input : initrd file name.\n#Output : Either SUCCESS or FAILED.\nfunction CheckLvmConfFile\n{\n\t_retCode_=$_SUCCESS_\n\n\t #filter=[ \"a|^/dev/cciss/c0d0$|\", \"a|^/dev/mapper/*|\", \"r/.*/\" ]\n        #need to split to get initrd file Name.\n        initrd_image_absolutepath=$1\n        initrd_image=`echo $initrd_image_absolutepath | sed -e \"s:[/].*[/]::\"`\n        initrd_image=`echo $initrd_image | sed -e \"s:/::\"`\n        out_initrd_image=\"$initrd_image.out\"\n        DATE_TIME_SUFFIX=`date +%d`_`date +%b`_`date +%Y`_`date +%H`_`date +%M`_`date +%S`\n        initrd_temp_dir=\"/tmp/temp_$DATE_TIME_SUFFIX\"\n        boot_temp_dir=$initrd_temp_dir\n        /bin/mkdir $initrd_temp_dir\n\n        (cd $initrd_temp_dir ; gunzip -9 < $initrd_image_absolutepath > ../$initrd_image.unzipped ; cpio -id < ../$initrd_image.unzipped)\n        cd $initrd_temp_dir\n        _lvm_conf_file_=\"$initrd_temp_dir/etc/lvm/lvm.conf\"\n        if [ ! -f \"$_lvm_conf_file_\" ]; then\n                #mean to say lvm.conf does not exist no need to change any thing...\n                echo \"initrd : $initrd_image, does not contain lvm.conf file.\"\n        else\n                cp -f \"$_lvm_conf_file_\" \"$_lvm_conf_file_.old\"\n\t\tcp -f \"${initrd_temp_dir}/init\" \"${_LOGS_}\"\n                #now we have to make in place replacement in lvm.conf file.\n                #First we need to get the Line and then\n                #check if all block devices are allowed?\n                #if not, then check whether sd pattern is already allowed.\n                #if not, then add sd* pattern to list of allowed block devices.\n                _line_=`cat \"$_lvm_conf_file_\" | grep -P \"^(\\s*)filter(\\s*)=(\\s*).*\"`\n                echo $_line_\n                _line_number_=`cat \"$_lvm_conf_file_\" | grep -P -n \"^(\\s*)filter(\\s*)=(\\s*).*\" | awk -F\":\" '{print $1}'`\n                sed -i \"$_line_number_ c\\filter=\\\"a\\/.*\\/\\\"\" $_lvm_conf_file_\n\n\t\tcp -rf \"etc/\" \"${_LOGS_}\"\n                #now again we have zip the file and then replace image file.\n                (cd $initrd_temp_dir/ ; find . | cpio --create --format='newc' > $boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX)\n                (cd $initrd_temp_dir/ ; gzip -9 < $boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX > $boot_temp_dir/../$out_initrd_image)\n                mv -f \"$boot_temp_dir/../$out_initrd_image\" \"$initrd_image_absolutepath\"\n                rm -f \"$boot_temp_dir/../$initrd_image.unzipped_$DATE_TIME_SUFFIX\"\n        fi\n\n        rm -f \"/$boot_temp_dir/../$initrd_image.unzipped\"\n        rm -rf \"$initrd_temp_dir\"\n\t\n\n\treturn $_retCode_\n}\n\n#This handles all requiments to make a modification in initrd file..\n#input : either it can be initrd file or virtual initrd file.\n#return SUCCESS or FAILURE.\nfunction ModifyVirtualInitrdFile\n{\n\t_retCode_=$_SUCCESS_\n\t_initrd_filename_=$1\n\techo \"Checking \\\"$_initrd_filename_\\\" for modifications if required any.\"\n\n\tCheckLvmConfFile $_initrd_filename_\n\tif [ 0 -ne $? ]; then\n\t\techo \"ERROR :: Failed to modify lvm.conf file in initrd image : $_initrd_filename_.\"\n\t\t_retCode_=$_FAILED_\n\tfi\n\n\treturn $_retCode_\n}\n\n\n#THIS FUNCTION RENAMES INITRD OR INITRAMFS FILES.\nfunction Rename_INITRD_RAMFS_Files\n{\n\t#FIRST LIST ALL PATTERNS WHICH ARE IN THE FORM OF \"-InMage-Virtual\"\n\t_boot_path_=$1\n\t_virtual_initrd_ramfs_files_=`find $_boot_path_ -name \"*-InMage-Virtual\"`\n\techo \"initrd files = $_virtual_initrd_ramfs_files_\"\n\tfor _virtual_initrd_ramfs_file_ in ${_virtual_initrd_ramfs_files_}\n\tdo\n\t\t#here we need to check if we have to modify lvm.conf file in virtual Initrd image.\n\t\tModifyVirtualInitrdFile $_virtual_initrd_ramfs_file_\t\t\n\t\tif [ 0 -ne $? ]; then \n\t\t\techo \"Error :: Failed to modify virtual initrd image file for any changes.\"\n\t\tfi\n\n\t\t_initrd_ramfs_file_=`echo $_virtual_initrd_ramfs_file_ | sed \"s/-InMage-Virtual$//g\"`\n\t\techo \"Initrd file = $_initrd_ramfs_file_\"\n\t\t#TAKE COPY OF THIS FILE\n\t\t#CHECK IF THE ORIG FILE ALREADY EXISTS?\n\t\tif [ -f \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\" ]; then\n\t\t\tMOVE \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\" \"$_initrd_ramfs_file_\"\n\t\tfi\n\n\t\tCOPY \"$_initrd_ramfs_file_\" \"${_initrd_ramfs_file_}${_INMAGE_ORG_}\"\n\t\tMOVE \"$_virtual_initrd_ramfs_file_\" \"$_initrd_ramfs_file_\"\n\tdone\n}\n\nfunction ModifyGrubV2Config\n{\n\t_grub_path_=\"$1/grub2/\"\n\t_menu_list_file_path_=\"$_grub_path_/grub.cfg\"\n    if [ ! -f \"$_menu_list_file_path_\" ]\n    then\n\t    _grub_path_=\"$1/grub/\"\n\t    _menu_list_file_path_=\"$_grub_path_/grub.cfg\"\n    fi \n\n\tif [ ! -f \"$_menu_list_file_path_\" ]; then\n\t\techo \"WARNING :: File \\\"grub.cfg\\\" not found in \\\"$_grub_path_\\\".\"\n\t\treturn $_SUCCESS_\n\tfi\n\t\n\t#MAKE COPY OF IT.\n\t_menu_list_file_orig_=\"${_menu_list_file_path_}${_INMAGE_ORG_}\"\n\tif [ -f \"${_menu_list_file_orig_}\" ]; then\n\t\tMOVE \"${_menu_list_file_orig_}\" \"$_menu_list_file_path_\"\n\tfi\n\n    echo \"Grub config -> $_menu_list_file_path_\"\n\tCOPY \"$_menu_list_file_path_\" \"${_menu_list_file_orig_}\"\n\tCOPY \"$_menu_list_file_path_\" \"$_LOGS_\"\n\t\t\n\t#MODIFY ROOT ENTRY WITH UUID VALUE\n\texec 4<\"$_menu_list_file_path_\"\n\twhile read -u 4 -r _line_\n\tdo \n\t\t_ret_val_=`echo $_line_ | grep \"^#\"`\n\t\tif [ \"${_ret_val_}\" ]; then\n\t\t\t#echo $_line_\n\t\t\tcontinue\n\t\tfi\n\n\t\t_root_dev_name_=`echo $_line_ |  grep 'linux.*root[ ]*=[ ]*\\/dev\\/' |\\\n                         awk -F\"root[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n\t\tif [ \"${_root_dev_name_}\" ]; then\n\t\t\t# IF ROOT PARTITION IS GETTING IDENTIFIED UUID OR LABEL? \n            # IF SO LEAVE IT AS IT IS DO NOT CHANGE.\n\t\t\techo $_root_dev_name_ | egrep \"^UUID|^LABEL\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\techo \"Existing Root Dev: $_root_dev_name\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t# CHECK IF IT IS A DEVICE\n\t\t\techo $_root_dev_name_ | grep \"\\/dev\\/\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\t#NOW IT IS A DEVICE : FIND ITS CORRESPONDING UUID.\n\t\t\t\tFind_UUID \"$_root_dev_name_\" \n\t\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t\t_uuid_=$_UUID_ \n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_root_dev_name_\" |\\\n                                 sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n                    echo \"New Root Dev: $_root_dev_name -> $_UUID_\"\n\t\t\t\t\tsed -i \"s/${safe_pattern}/UUID=$_uuid_/\" ${_menu_list_file_path_}\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\n\t\t#MODIFY RESUME AS WELL\n\t\t_resume_dev_name_=`echo $_line_ |  grep 'linux.*resume[ ]*=[ ]*\\/dev\\/' |\\\n                           awk -F\"resume[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n\t\tif [ \"${_resume_dev_name_}\" ]; then\n\t\t\t#IF RESUME PARTITION IS GETTING IDENTIFIED UUID OR LABEL? \n            #IF SO LEAVE IT AS IT IS DO NOT CHANGE.\n\t\t\techo $_resume_dev_name_ | egrep \"^UUID|^LABEL\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\techo \"Existing resume dev: $_resume_dev_name\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t# CHECK IF IT IS A DEVICE\n\t\t\techo $_resume_dev_name_ | grep \"\\/dev\\/\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\t#NOW IT IS A DEVICE : FIND ITS CORRESPONDING UUID.\n\t\t\t\tFind_UUID \"$_resume_dev_name_\" \n\t\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t\t_uuid_=$_UUID_ \n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_resume_dev_name_\" |\\\n                                 sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\tsed -i \"s/${safe_pattern}/UUID=$_uuid_/\" ${_menu_list_file_path_}\n                    echo \"New Root Dev: $_resume_dev_name -> $_UUID_\"\n\t\t\t\telse\n\t\t\t\t\tMapSrcToTgt \"${_resume_dev_name_}\"\n\t\t\t\t\tif [ $? -eq $_FAILED_ ]; then\n\t\t\t\t\t\techo \"ERROR :: Failed to modify resume device.\"\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tfi\n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_resume_dev_name_\" |\\\n                                 sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\techo \"resume device on target side = ${_SRC2TGT_MAPPED_DEVICE_}.\"\n\t\t\t\t\tsafe_pattern1=$(printf \"%s\\n\" \"${_SRC2TGT_MAPPED_DEVICE_}\" |\\\n                                  sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\tsed -i \"s/${safe_pattern}/${safe_pattern1}/\" ${_menu_list_file_path_}\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n                #Removing console Option\n                _console_=`echo $_line_ | awk -F\"console=\" '{print $2}'|awk '{print $1}'`\n                if [ ! -z \"$_console_\" ];then\n                    echo \"console parameter : $_console_\"\n                    _pattern_to_be_removed=\"console=$_console_\"\n                    echo \"Pattern to be removed : $_pattern_to_be_removed\"\n                    sed -i \"s/$_pattern_to_be_removed//\" ${_menu_list_file_path_}\n                fi\n\tdone\n\t4<&-\n\treturn $_SUCCESS_\n}\n#THIS FUNCTION MAKES SURE THAT ROOT ENTRY IN menu.lst FILE IS REPLACED WITH IT\"S UUID\nfunction ModifyMenuListFile\n{\n\t_grub_path_=\"$1/grub/\"\n\t_menu_list_file_path_=\"$_grub_path_/menu.lst\"\n\t_menu_list_file_path_=`readlink -f $_grub_path_/menu.lst`\n\t#FIRST MAKE SURE THAT FILE EXISTS.\n\tif [ ! -f \"$_menu_list_file_path_\" ]; then\n\t\techo \"WARNING :: File \\\"menu.lst\\\" not found in path \\\"$_grub_path_\\\".\"\n\t\techo \"Nothing to modify \\\"menu.lst\\\" file.\"\n\t\t#ModifyGrubV2Config \"$1\"\n\t\treturn $_SUCCESS_\n\tfi\n\t\n\t#MAKE COPY OF IT.\n\t_menu_list_file_orig_=\"${_menu_list_file_path_}${_INMAGE_ORG_}\"\n\tif [ -f \"${_menu_list_file_orig_}\" ]; then\n\t\tMOVE \"${_menu_list_file_orig_}\" \"$_menu_list_file_path_\"\n\tfi\n\n\tCOPY \"$_menu_list_file_path_\" \"${_menu_list_file_orig_}\"\n\t\t\n\tCOPY \"$_menu_list_file_path_\" \"$_LOGS_\"\n\t\t\n\t#WE HAVE FILE.MODIFY ROOT ENTRY WITH IT\"S UUID VALUE\n\texec 4<\"$_menu_list_file_path_\"\n\twhile read -u 4 -r _line_\n\tdo \n\t\t_ret_val_=`echo $_line_ | grep \"^#\"`\n\t\tif [ \"${_ret_val_}\" ]; then\n\t\t\t#echo $_line_\n\t\t\tcontinue\n\t\tfi\n\n\t\t_root_dev_name_=`echo $_line_ |  grep 'kernel.*root[ ]*=[ ]*\\/dev\\/' | awk -F\"root[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n\t\tif [ \"${_root_dev_name_}\" ]; then\n\t\t\t#IF ROOT PARTITION IS GETTING IDENTIFIED UUID OR LABEL? IS SO LEAVE IT AS IT IS DO NOT CHANGE.\n\t\t\techo $_root_dev_name_ | egrep \"^UUID|^LABEL\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\techo \" Appropriate UUID or LABEL entry exists in $_menu_list_file_path_ : $_root_dev_name\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t# CHECK IF IT IS A DEVICE\n\t\t\techo $_root_dev_name_ | grep \"\\/dev\\/\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\t#NOW IT IS A DEVICE : FIND ITS CORRESPONDING UUID.\n\t\t\t\tFind_UUID \"$_root_dev_name_\" \n\t\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t\t_uuid_=$_UUID_ \n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_root_dev_name_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\tsed -i \"s/${safe_pattern}/UUID=$_uuid_/\" ${_menu_list_file_path_}\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\n\t\t#MODIFY RESUME AS WELL\n\t\t_resume_dev_name_=`echo $_line_ |  grep 'kernel.*resume[ ]*=[ ]*\\/dev\\/' | awk -F\"resume[ ]*=[ ]*\" '{print $2}' | awk '{print $1}'`\n\t\tif [ \"${_resume_dev_name_}\" ]; then\n\t\t\t#IF RESUME PARTITION IS GETTING IDENTIFIED UUID OR LABEL? IS SO LEAVE IT AS IT IS DO NOT CHANGE.\n\t\t\techo $_resume_dev_name_ | egrep \"^UUID|^LABEL\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\techo \" Appropriate UUID or LABEL entry exists in $_menu_list_file_path_ : $_resume_dev_name\"\n\t\t\t\tcontinue\n\t\t\tfi\n\t\t\t# CHECK IF IT IS A DEVICE\n\t\t\techo $_resume_dev_name_ | grep \"\\/dev\\/\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\t#NOW IT IS A DEVICE : FIND ITS CORRESPONDING UUID.\n\t\t\t\tFind_UUID \"$_resume_dev_name_\" \n\t\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t\t_uuid_=$_UUID_ \n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_resume_dev_name_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\tsed -i \"s/${safe_pattern}/UUID=$_uuid_/\" ${_menu_list_file_path_}\n\t\t\t\telse\n\t\t\t\t\tMapSrcToTgt \"${_resume_dev_name_}\"\n\t\t\t\t\tif [ $? -eq $_FAILED_ ]; then\n\t\t\t\t\t\techo \"ERROR :: Failed to modify resume device.\"\n\t\t\t\t\t\tcontinue\n\t\t\t\t\tfi\n\t\t\t\t\tsafe_pattern=$(printf \"%s\\n\" \"$_resume_dev_name_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\techo \"resume device on target side = ${_SRC2TGT_MAPPED_DEVICE_}.\"\n\t\t\t\t\tsafe_pattern1=$(printf \"%s\\n\" \"${_SRC2TGT_MAPPED_DEVICE_}\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\t\tsed -i \"s/${safe_pattern}/${safe_pattern1}/\" ${_menu_list_file_path_}\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n                #Removing console Option\n                _console_=`echo $_line_ | awk -F\"console=\" '{print $2}'|awk '{print $1}'`\n                if [ ! -z \"$_console_\" ];then\n                    echo \"console parameter : $_console_\"\n                    _pattern_to_be_removed=\"console=$_console_\"\n                    echo \"Pattern to be removed : $_pattern_to_be_removed\"\n                    sed -i \"s/$_pattern_to_be_removed//\" ${_menu_list_file_path_}\n                fi\n\tdone\n\t4<&-\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION ENSURE THAT IT PLACES ONLY PROTECTED DISK ENTRIES IN DEVICE.MAP\nfunction ModifyDeviceMapFile\n{\n\t#WHILE MODIFYING MAKE SURE THAT WE HAVE READ THE VALUE AND CORRECT AND VERIFY IN PROTECTED DISK LIST.\n\t#IT MIGHT NOT BE DISK NAME?? IT MIGHT CONTAIN BY-PATH, BY-ID, BY-UUID, BY-LABEL?\n\t_grub_path_=\"$1/grub\";\n\t_device_map_file_=\"$_grub_path_/device.map\"\n\t_device_map_file_orig_=\"${_device_map_file_}${_INMAGE_ORG_}\"\n\t\n\t#CHECK IF DEVICE.MAP FILE EXISTS.\n\tif [ ! -f \"$_device_map_file_\" ]; then\n\t\techo \"WARNING :: \\\"device.map\\\" file not found in path \\\"$_grub_path_\\\".\"\n\t\techo \"Nothing to modify \\\"device.map\\\" file.\"\n\t\treturn $_SUCCESS_\n\tfi\n\n\t#WE HAVE TO TAKE COPY OF ORIGINAL\n\tif [ -f \"${_device_map_file_orig_}\" ]; then\n\t\tMOVE \"${_device_map_file_orig_}\" \"$_device_map_file_\"\n\tfi\n\tCOPY \"$_device_map_file_\" \"${_device_map_file_orig_}\"\n\n\t#WE HAVE FILE.\n\t_ret_code_=$_SUCCESS_\n\texec 4<\"$_device_map_file_\"\n\twhile read -u 4 -r _line_\n\tdo\n\t\t_hard_disk_info_=`echo $_line_ | grep \"/dev/*\" | awk -F\"^[ ]*(.*)[ ]+\" '{print $2}'`\n\t\techo \"Hard Disk Info = $_hard_disk_info_\"\n\t\tif [ \"${_hard_disk_info_}\" ]; then\n\t\t\t_device_symlink_=\"\"\n\t\t\t#CHECK IF DISK INFOR  CONTAINS /dev/disk\n\t\t\techo ${_hard_disk_info_} | grep \"\\/dev\\/disk\\/\" > /dev/null 2>&1\n\t\t\tif [ $? -eq 0 ]; then\n\t\t\t\t#NOW THIS HAS TO BE DE-REFERENCED TO BASE DEVICE\n\t\t\t\tDeref_SymLink \"${_hard_disk_info_}\"\t\n\t\t\t\tif [ 0 -ne $? ] || [ -z $_real_partition_name_ ]; then \n\t\t\t\t\techo \"ERROR :: Failed to Find real device name for symlink=${_hard_disk_info_}.\"\n\t\t\t\t\tcontinue\n\t\t\t\tfi\n\t\t\t\techo \"Found real device name for symlink ${_hard_disk_info_} as ${_real_partition_name_}\"\n\t\t\t\t_device_symlink_=$_hard_disk_info_\n\t\t\t\t_hard_disk_info_=$_real_partition_name_\n\t\t\tfi\n\t\t\t\t\n\t\t\t#CHECK IF THE DISK IS PROTECTED? IF PROTECTED GET IT\"S TARGET DRIVE NAME AND REPLACE. IF NOT REMOVE LINE.\n\t\t\tGetProtectedDeviceEntry \"${_hard_disk_info_}\"\n\t\t\t_dev_num_=$?\n\t\t\tif [ 0 -ne $_dev_num_ ]; then\n\t\t\t\techo \"Device $_hard_disk_info_ is protected and device number at target side = $_dev_num_\"\n\t\t\t\t#FIND ITS DISK NAME ON TARGET SIDE.\n\t\t\t\t_dev_num_=$((_dev_num_-1))\n\t\t\t\tGetTargetDiskName $_dev_num_ \n\t\t\t\tif [ 0 -ne $?  ]; then\n\t\t\t\t\techo \"ERROR :: Failed to find target disk name for device \\\"$_hard_disk_info_\\\".\"\t\n\t\t\t\t\t_ret_code_=$_FAILED_\n\t\t\t\t\tcontinue\n\t\t\t\tfi\n\t\t\t\techo \"Disk Name = $_disk_name_\"\n\t\t\t\t\n\t\t\t\t#SAFE LHS PATTERN AND INPUT PATTERN\n\t\t\t\t_safe_input_=$(printf \"%s\\n\" \"$_hard_disk_info_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\tif [ \"${_device_symlink_}\" ]; then\n\t\t\t\t\t_safe_input_=$(printf \"%s\\n\" \"$_device_symlink_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\tfi\n\t\t\t\t_safe_sub_input_=$(printf \"%s\\n\" \"$_disk_name_\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n\t\t\t\techo \"Input = $_safe_input_ , sub = $_safe_sub_input_\"\n\t\t\t\techo $_line_ | sed \"s/${_safe_input_}/${_safe_sub_input_}/\" >>\"${_device_map_file_}.tmp\"\n\t\t\tfi\n\t\tfi\n\tdone\n\t4<&-\n\tMOVE \"${_device_map_file_}.tmp\" \"${_device_map_file_}\"\n\treturn $_SUCCESS_\n}\n\n#THIS FUNCTION CREATES A BACKUP OF CONFIGURATION FILE FOR GRUB INSTALLATION ON CCISS MACHINE H/W\nfunction BackupConfigFile\n{\n\t_boot_path_=$1\n\t_install_grub_flag=0\n\techo \"boot path = $_boot_path_\"\n\tBACKUP_INPUT_CONFIG_FILE_=\"\"\n\n\t_INPUT_CONFIG_FILE_=\"$_boot_path_/Configuration.info\"\n\t#echo \"Machine Manufacturer                   : $machine_manufacturer\"\n\t#echo \"Machine Product Type                   : $machine_product_type\"\n\t#echo \"Distribution details                   : $OS\"\n\t_MACHINE_MANUFACTURER_=`grep \"Machine Manufacturer                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_MACHINE_PRODUCT_TYPE_=`cat $_INPUT_CONFIG_FILE_ | grep \"Machine Product Type\" | awk -F\": \" '{print $2}'`\n\t_DISTRIBUTION_DETAILS_=`grep \"Distribution details                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_ROOT_DEVICE_=`grep \"Root device                            : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_BOOT_DEVICE_=`grep \"Boot device                            : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_PROBE_DEVICE=\"\"\n\tcase \"${_DISTRIBUTION_DETAILS_}\" in \n\t\tSLES10*|SLES9*)\n\t\t\t_first_partition_=\"\"\n\t\t\t#if [ \"${_MACHINE_MANUFACTURER_}\" = \"HP\" ] || [ \"${_MACHINE_MANUFACTURER_}\" = \"Hewlett-Packard\" ]; then\n\t\t\t#\tif [ \"${_MACHINE_PRODUCT_TYPE_}\" = \"ProLiant DL380 G4\" ]; then\n\t\t\t#\t\t_install_grub_flag=1\n\t\t\t#\tfi\n\t\t\t#fi\n                        # Controller type is CCISS\n                        # Check during GRUB installation - if first partition is not active\n                        # then only install GRUB\n                        if [ -z \"${_BOOT_DEVICE_}\" ]; then\n                        \t_PROBE_DEVICE=\"${_ROOT_DEVICE_}\"\n                        else\n                        \t_PROBE_DEVICE=\"${_BOOT_DEVICE_}\"\n                        fi\n                       \techo \"${_PROBE_DEVICE}\" | grep -i cciss 2>&1 > /dev/null\n                       \tif [ $? -eq 0 ]; then\n\t\t\t\t_install_grub_flag=1\n                       \tfi\n\t\t;;\n\t\tSLES11*|SLES12*)\n\t\t\techo \"No changes required on $_DISTRIBUTION_DETAILS_ for GRUB installtion for now\"\n\t\t;;\n\t\tRHEL*)\n\t\t\techo \"No changes required on $_DISTRIBUTION_DETAILS_ for GRUB installtion\"\n\t\t;;\n\t\tOL*)\n\t\t\techo \"No changes required on $_DISTRIBUTION_DETAILS_ for GRUB installtion\"\n\t\t;;\n\t\tUBUNTU*)\n\t\t\techo \"No changes required on $_DISTRIBUTION_DETAILS_ for GRUB installtion\"\n\t\t;;\n\t\t*) echo \"Invalid distribution details $_DISTRIBUTION_DETAILS_\";;\n\tesac\n\tif [ $_install_grub_flag -eq 1 ]; then\n\t\tBACKUP_INPUT_CONFIG_FILE_=\"$_VX_FAILOVER_DATA_PATH_/${_MACHINE_UUID_}_Configuration.info\"\n\t\tCOPY $_INPUT_CONFIG_FILE_ $BACKUP_INPUT_CONFIG_FILE_\n\tfi\n}\n#THIS FUNCTION MAKES SURE THAT ALL CHANGES ARE PERFORMED IN /boot DIRECTORY OF TARGET MACHINE TO BOOT.\nfunction Prepare_boot\n{\n\t_boot_path_=$1\n\t_ret_code_=$_SUCCESS_\n\techo \"boot path = $_boot_path_\"\n\n\t_INPUT_CONFIG_FILE_=\"$_boot_path_/Configuration.info\"\n\t#TODO\n\t#THIS HAS TO CHECK FOR INPUT CONFIGURATION FILE AND PROTECTED DISK LIST FILE.\n\t\n    # Log Configuration.info for debugging purpose.\n    if [ -f $_INPUT_CONFIG_FILE_ ]; then\n        echo \"Logging Configuration.info file for debugging purpose.\"\n        cat $_INPUT_CONFIG_FILE_\n    fi\n\n\tCOPY $_INPUT_CONFIG_FILE_ $_LOGS_\n\t#FIRST WE NEED TO RENAME INITRD/INITRAMFS FILES.\n\tRename_INITRD_RAMFS_Files \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\t\n\t#NOW WE NEED TO MODIFY MENU.LST FILE.\n\tModifyMenuListFile \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\n\t#NOW WE NEED TO MODIFY DEVICE.MAP FILE.\n\tModifyDeviceMapFile \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\n\treturn $_ret_code_\n}\n\nfunction ExecuteTask_V2P\n{\n\t#WE HAVE TO RENAME FILES WHICH ARE EITHER UNDER /boot or /etc.\n\t#under '/boot'\n\t\t#1. Rename back initrd (or) initramfs files.\n\t\t#2. menu.lst file.\n\t\t#3. device.map\n\t#under '/etc'\n\t\t#1. /etc/sysconfig/kernel\n\t\t#2. fstab.\n\t\n\tif [ ! \"${_MOUNT_PATH_}\" ]; then\n\t\techo \"ERROR :: Mount point is not specified.\"\n\t\techo \"ERROR :: Mount point has to be specfied in order to modify files.\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#NEED TO CHECK IF MOUNT PATH SPECIFIED IS A BLOCK DEVICE\n\t#if [ ! -b \"$_MOUNT_PATH_\" ]; then\n\t#       echo \"ERROR :: Invalid mount point. Mount point : $_MOUNT_PATH_.\"\n\t#       echo \"ERROR :: Please specify a valid mount point which is of a block device type.\"\n\t#       return $_FAILED_\n\t#fi\n\n\t#NOW WE HAVE A VALID MOUNT POINT. NOW WE HAVE TO CHECK FOR WHICH THE MOUNT POINT IS?\n\t_ret_code_boot_=$_FAILED_\n\t_ret_code_etc_=$_FAILED_\n\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\" ] || [ \"all\" = \"${_MOUNT_PATH_FOR_}\" ]; then\n\t\tif [ \"boot\" = \"${_MOUNT_PATH_FOR_}\"  ]; then\n\t\t\tPrepare_boot_V2P \"$_MOUNT_PATH_\"\n\t\t\t_ret_code_boot_=$?\n\t\telif [ -d \"$_MOUNT_PATH_/boot\" ]; then\n\t\t\tPrepare_boot_V2P \"$_MOUNT_PATH_/boot/\"\n\t\t\t_ret_code_boot_=$?\n\t\telse\n\t\t\techo \"ERROR :: Mounted partition(${_MOUNT_PATH_}) does not contain /boot information.Failed to replace original files.\"\n\t\tfi\n\tfi\n\n\tif [ \"etc\" = \"${_MOUNT_PATH_FOR_}\" ] || [ \"all\" = \"${_MOUNT_PATH_FOR_}\" ]; then\n\t\tif [ -d \"$_MOUNT_PATH_/etc\" ]; then\n\t\t\tPrepare_etc_V2P \"$_MOUNT_PATH_/etc\"\n\t\t\t_ret_code_etc_=$?\n\t\telif [ -f \"$_MOUNT_PATH_/fstab\" ]; then\n\t\t\tPrepare_etc_V2P \"$_MOUNT_PATH_\"\n\t\t\t_ret_code_etc_=$?\n\t\t\telse\n\t\t    echo \"ERROR :: Mounted partition(${_MOUNT_PATH_}) does not contain /etc information.Failed to replace original files.\"\n\t\tfi\n\tfi\n\tif [ $_ret_code_boot_ ] || [ $_ret_code_etc_ ]; then\n\t\treturn $_FAILED_\n\tfi\n\t\n\techo \"Successfully reverted original configuration files.\"\n\treturn $_SUCCESS_\n}\n\nfunction Prepare_etc_V2P\n{\n\t_etc_path_=\"$1\"\n\t_returnCode_=$_SUCCESS_\n\n\t_INPUT_CONFIG_FILE_=\"$_etc_path_/Configuration.info\"\n\n\tModifyInitrdModulesList_V2P \"$_etc_path_/sysconfig\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\tfi\n\n\tif [ ! -f \"$_etc_path_/fstab\" ]; then\n\t\techo \"ERROR :: Failed to find file \\\"fstab\\\" file under path \\\"$_etc_path_\\\".\"\n\t\techo \"ERROR :: Failed to modify fstab file.\"\n\t\treturn $_FAILED_\n\tfi\n\n\tModifyFstabFile_V2P \"$_etc_path_/fstab\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\tfi\n\n\tModifyModProbeFile_V2P \"$_etc_path_\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\tfi\n\n\t_lvm_conf_file_=\"${_etc_path_}/lvm/lvm.conf\"\n\tModifyLvmConfFile_V2P \"$_lvm_conf_file_\"\n\tif [ 0 -ne $? ]; then\n\t\t_returnCode_=$_FAILED_\n\tfi\n\n\t_VCON_ACTION_FILE_=\"$_etc_path_/vxagent/vcon/p2v_actions\"\n\tif [ ! -d \"$_etc_path_/vxagent/vcon/\" ]; then\n\t\tmkdir -p \"$_etc_path_/vxagent/vcon/\"\n\tfi\n\techo \"workflow=${_WORK_FLOW_}\" > $_VCON_ACTION_FILE_\n\techo \"install_vmware_tools=0\" >> $_VCON_ACTION_FILE_\n\techo \"uninstall_vmware_tools=0\" >> $_VCON_ACTION_FILE_\n        echo \"create_initrd_images=1\" >> $_VCON_ACTION_FILE_\n\t\n\t#If OS=OL and Kernel = UEK and bitness = 32 then configure uninstall_vmware_tools to 1.\n\t_DISTRIBUTION_DETAILS_=`grep \"Distribution details                   : \" $_INPUT_CONFIG_FILE_ | awk '{print $4}'`\n\t_KERNEL_DETAILS_=`grep \"Operating System Kernel Release        : \" $_INPUT_CONFIG_FILE_ | awk '{print $6}'`\n\t\n\techo \"Distribution Details = $_DISTRIBUTION_DETAILS_\"\n\techo \"Kernel = $_KERNEL_DETAILS_\"\n\tcase \"${_DISTRIBUTION_DETAILS_}\" in\n\t\tOL*)\n\t\t\techo $_DISTRIBUTION_DETAILS_ | grep -P \"5\\-32$\" > /dev/null 2>&1\n\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t_is_32_bit_=1\n\t\t\tfi\n\t\t\techo $_KERNEL_DETAILS_ | grep -P \"uek$\" > /dev/null 2>&1 \n\t\t\tif [ 0 -eq $? ]; then\n\t\t\t\t_is_uek_=1\n\t\t\tfi\n\t\t\t\n\t\t\techo \"OEL : is_32_bit = ${_is_32_bit_}\"\n\t\t\techo \"is_uek = ${_is_uek_}\"\n\n\t\t\tif [ $_is_32_bit_ && $_is_uek_ ]; then\n\t\t\t\techo \"setting flag to uninstall VMware tools.\"\n\t\t\t\techo \"uninstall_vmware_tools=1\" >> $_VCON_ACTION_FILE_\n\t\t\tfi\n\t\t\t;;\n\t\t*) \n\t\t\techo \"skipping uninstall of vmware tools for distribution $_DISTRIBUTION_DETAILS_\"\n                \t;;\n\tesac \n\t#set VolumeFilteringDisabled to 1.\n\tsetVolumeFilteringDisabled \"$_etc_path_\" \"1\"\n\n\tClearBitMapFiles \"$_etc_path_/..\" \"$_etc_path_\"\n\n\treturn $_returnCode_\n}\n\nfunction ClearBitMapFiles\n{\t\n\t_root_path_=\"$1\"\n    _etc_path_=\"$2\"\n\n    _bitmap_files_=`ls ${_root_path_}/root/InMage-*.VolumeLog ${_etc_path_}/involflt/*/InMage-*.VolumeLog`\n        for _bitmap_file_ in ${_bitmap_files_}\n        do\n                if [ -f \"${_bitmap_file_}\" ]; then\n\t\t\techo \"Removing file : ${_bitmap_file_}.\"\n                        rm -f \"${_bitmap_file_}\"\n                fi\n        done\n}\n\nfunction ModifyModProbeFile_V2P\n{\n\t_etc_path_=$1\n\t_mod_probe_file_=\"$_etc_path_/$_MOD_PROBE_FILE_NAME_\"\n        _modprobe_file_orig_=\"${_mod_probe_file_}${_INMAGE_ORG_}\"\n        _modprobe_file_mod_=\"${_mod_probe_file_}${_INMAGE_MOD_}\"\n\n        if [ ! -f \"${_modprobe_file_orig_}\" ]; then\n                echo \"ERROR :: Failed to find file \\\"${_modprobe_file_orig_}\\\". Failed to change it with original file.\"\n        else\n                COPY \"${_mod_probe_file_}\" \"${_modprobe_file_mod_}\"\n\n                MOVE \"${_modprobe_file_orig_}\" \"${_mod_probe_file_}\"\n\n                echo \"Successfully changed modprobe file with its original file.\"\n        fi\n\n        return $_SUCCESS_\n}\n\nfunction ModifyFstabFile_V2P\n{\n\t_fstab_file_=$1\n\t_fstab_file_orig_=\"${_fstab_file_}${_INMAGE_ORG_}\"\n\t_fstab_file_mod_=\"${_fstab_file_}${_INMAGE_MOD_}\"\n\n\tif [ ! -f \"${_fstab_file_orig_}\" ]; then\n\t\techo \"ERROR :: Failed to find file \\\"${_fstab_file_orig_}\\\". Failed to change it with original file.\"\n\telse\n\t\tCOPY \"${_fstab_file_}\" \"${_fstab_file_mod_}\"\n\t\t\n\t\tMOVE \"${_fstab_file_orig_}\" \"${_fstab_file_}\"\n\t\t\n\t\techo \"Successfully changed fstab file with its original file.\"\n\tfi\n\t\n\treturn $_SUCCESS_\n}\n\nfunction ModifyInitrdModulesList_V2P\n{\n\t_kernel_base_file_path_=$1\n    \t_kernel_config_file_=\"$_kernel_base_file_path_/kernel\"\n\t_kernel_config_file_orig_=\"${_kernel_config_file_}${_INMAGE_ORG_}\"\n\t_kernel_config_file_mod_=\"${_kernel_config_file_}${_INMAGE_MOD_}\"\n\t\t\n\tif [ ! -f \"${_kernel_config_file_orig_}\" ]; then\n\t\techo \"ERROR :: Failed to find file \\\"${_kernel_config_file_orig_}\\\".Failed to change it with original file.\"\n\t\treturn $_FAILED_\n\tfi\n\t\n\t#COPY\n\tCOPY \"${_kernel_config_file_}\" \"${_kernel_config_file_mod_}\"\n\t\n\tMOVE \"${_kernel_config_file_orig_}\" \"${_kernel_config_file_}\"\n\n\techo \"Successfully modified initrd module list with original list.\"\n\treturn $_SUCCESS_\n}\n\nfunction Prepare_boot_V2P\n{\n\t#WE HAVE TO RENAME FILES WHICH ARE EITHER UNDER /boot or /etc.\n\t#under '/boot'\n\t\t#1. Rename back initrd (or) initramfs files.\n\t\t#2. menu.lst file.\n\t\t#3. device.map\n\n\t_boot_path_=$1\n\t_ret_code_=$_SUCCESS_\n\techo \"boot path = $_boot_path_\"\n\n\t_INPUT_CONFIG_FILE_=\"$_boot_path_/Configuration.info\"\n\n\t#FIRST WE NEED TO RENAME INITRD/INITRAMFS FILES.\n\tRename_INITRD_RAMFS_Files_V2P \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\n\t#NOW WE NEED TO REPLACE menu.lst FILE.\n\tModifyMenuListFile_V2P \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\n\t#NOW WE NEED TO REPLACE DEVICE.MAP FILE.\n\tModifyDeviceMapFile_V2P \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\n\tChangeActivePartition \"$_boot_path_\"\n\t_ret_code_=$((_ret_code_+$?))\n\t\n\treturn $_ret_code_\n}\n\nfunction ChangeActivePartition \n{\n\t_boot_path_=$1\n\t\n\t#CHECK IF FILE EXITS?\n\t_active_partition_file_=\"${_boot_path_}/${_SOURCE_CONFIGURATION_DATA_FILE}\"\n\techo \"Active partiton file = ${_active_partition_file_}.\"\n\tif [ ! -f \"${_active_partition_file_}\" ]; then\n\t\techo \"File ${_active_partition_file_} does not exist. No need to change active partition.\"\n\t\treturn $_SUCCESS_\n\tfi\n\n\t_installed_grub_on_target=`grep installed_grub_on_target $_active_partition_file_ | awk -F= '{ print $2 }'`\n\t_active_partition_number_=`grep orginal_active_partition $_active_partition_file_ | awk -F= '{ print $2 }'`\n\tif [ -z \"${_active_partition_number_}\" ]; then\n\t\techo \"ERROR :: Failed to find the active partition from $_active_partition_file_\"\n\t\techo \"ERROR :: Failed to change active partition.\"\n\t\treturn $_FAILED_ \n\tfi\n    \tif [ $_installed_grub_on_target -eq 1 ]; then\n        \techo \"GRUB was installed on target virtual machine.\"\n\telse\n        \techo \"GRUB was not installed on target virtual machine.\"\n\tfi\n\techo \"Original active partition number = ${_active_partition_number_}\"\n\t#find base device for mount_path.\n\t_mount_device_=`mount | grep \" on ${_MOUNT_PATH_} \" | awk '{print $1}'`\n\techo \"Mount device for mount path ${_MOUNT_PATH_} is ${_mount_device_}.\"\n\t#find base device from it.\n\t_base_device_=\"${_mount_device_}\"\n\t_chars_in_mount_device=`echo \"${_mount_device_}\" | wc -c`\n\t\n\twhile [ 0 -ne $_chars_in_mount_device ]\n\tdo\n\t\t_base_device_=`echo \"${_base_device_}\" | sed -e \"s/[0-9|a-z|A-Z|\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)\\_\\+\\-]$//g\"`\n\n\t\tif [ -z \"${_base_device_}\" ]; then\n\t\t\tbreak;\n\t\telse\n\t\t\tif [ -b ${_base_device_} ]; then\n\t\t\t\tbreak;\n\t\t\tfi\n\t\tfi\n\t\t_chars_in_mount_device=$((_chars_in_mount_device-1))\n\tdone\n\techo \"base device for ${_mount_device_} is ${_base_device_}.\"\n\tif [ -z \"${_base_device_}\" ]; then\n\t\techo \"ERROR :: Failed to find the base deivce\"\n\t\treturn $_FAILED_\n\tfi\n\tMakePartitionActive \"${_base_device_}\" \"${_active_partition_number_}\"\n\tif [ $_FAILED_ -eq $? ]; then\n\t\treturn $_FAILED_\n\tfi\n\t\n\techo \"Successfully changed active partiton.\" \n\treturn $_SUCCESS_\n}\n\nfunction Rename_INITRD_RAMFS_Files_V2P\n{\n\t #FIRST LIST ALL PATTERNS WHICH ARE IN THE FORM OF \".INMAGE_ORG\"\n        _boot_path_=$1\n        _orig_initrd_ramfs_files_=`find $_boot_path_ -name \"init*${_INMAGE_ORG_}\"`\n\n        echo \"initrd files = $_orig_initrd_ramfs_files_\"\n        for _orig_initrd_ramfs_file_ in ${_orig_initrd_ramfs_files_}\n        do\n\t\t#WE HAVE TO USE SAFE PATTERN?PROBABALY WE HAVE TO\n\t\tif [ ! -f \"${_orig_initrd_ramfs_file_}\" ]; then\n\t\t\techo \"ERROR :: Failed to find file \\\"${_orig_initrd_ramfs_file_}\\\". Failed to change it back to original file.\"\n\t\t\tcontinue\n\t\tfi\t\n\t\tsafe_pattern=$(printf \"%s\\n\" \"${_INMAGE_ORG_}\" | sed 's/[][\\.*^$(){}?+|/]/\\\\&/g')\n                _initrd_ramfs_file_=`echo $_orig_initrd_ramfs_file_ | sed \"s/${safe_pattern}$//g\"`\n                echo \"Initrd file = $_initrd_ramfs_file_\"\n                #TAKE COPY OF THIS FILE\n\t\tCOPY \"$_initrd_ramfs_file_\" \"${_initrd_ramfs_file_}${_INMAGE_MOD_}\" \n                MOVE \"$_orig_initrd_ramfs_file_\" \"$_initrd_ramfs_file_\"\n        done\n\t\n\treturn $_SUCCESS_\n}\n\nfunction ModifyMenuListFile_V2P\n{\n\t#first we need to back it up.\n\t_boot_path_=$1\n\t_menu_list_file_=\"${_boot_path_}/grub/menu.lst\"\n\t_menu_list_file_orig_=\"${_menu_list_file_}${_INMAGE_ORG_}\"\n\t_menu_list_file_mod_=\"${_menu_list_file_}${_INMAGE_MOD_}\"\n\n\t#CHECK IF WE HAVE ORG FILE?\n\tif [ ! -f \"${_menu_list_file_orig_}\" ]; then\n\t\techo \"ERROR :: Unable to find file \\\"${_menu_list_file_orig_}\\\".\"\n\t\treturn $_FAILED_\n\tfi\n\n\t#WE HAVE FILE.\n\tCOPY \"${_menu_list_file_}\" \"${_menu_list_file_mod_}\"\n\n\t#REVERT ORIG FILE.\n\tMOVE \"${_menu_list_file_orig_}\" \"${_menu_list_file_}\"\n\n\techo \"Successfully reverted menu.lst configuration.\"\n\treturn $_SUCCESS_\t\n}\n\nfunction ModifyDeviceMapFile_V2P\n{\n\t_boot_path_=$1\n        _device_map_file_=\"${_boot_path_}/grub/device.map\"\n        _device_map_file_orig_=\"${_device_map_file_}${_INMAGE_ORG_}\"\n        _device_map_file_mod_=\"${_device_map_file_}${_INMAGE_MOD_}\"\n\n        #CHECK IF WE HAVE ORG FILE?\n        if [ ! -f \"${_device_map_file_orig_}\" ]; then\n                echo \"ERROR :: Unable to find file \\\"${_device_map_file_orig_}\\\".\"\n                return $_FAILED_\n        fi\n\n        #WE HAVE FILE.\n        COPY \"${_device_map_file_}\" \"${_device_map_file_mod_}\"\n\n        #REVERT ORIG FILE.\n        MOVE \"${_device_map_file_orig_}\" \"${_device_map_file_}\"\n\n        echo \"Successfully reverted device.map configuration.\"\n        return $_SUCCESS_\n}\n\nfunction Usage\n{\n\t#TODO\n\t#NEED TO WRITE USAGE FOR THIS PROGRAM WITH DIFFERENT INPUT\"S POSSIBLE.\n\treturn $_SUCCESS_\n}\n\nfunction EXIT\n{\n\t_exit_code_=$1\n\tdate\n\techo \"-------END-------\"\n#\t3>&-\n#\tcat $_TEMP_LOG_F_ >>\"$_LOG_FILE_\"\n#\trm -rf $_TEMP_LOG_F_\n\texit $_exit_code_\n}\n\n\n#MAIN#\n\n#first we need to validate options passed.\n#This could be at protection/Addition of Disk / failover.\necho \"------- START -------\"\n\ndate\n_return_code_=\"\"\n\nReadInputFile $1\n_return_code_=$?\nif [ 0 -ne $_return_code_ ]; then\n\tEXIT $_return_code_\nfi\n\n#WE NEED TO IMPORT LIB FILE.\nif [ -d \"$_FILES_PATH_/scripts/vCon/\" ]; then\n\t. \"$_FILES_PATH_/scripts/vCon/$_LIB_FILE_\"\nelse\n\t. \"$_FILES_PATH_/$_LIB_FILE_\"\nfi\n\nExecuteTask\n_return_code_=$?\nif [ 0 -ne $_return_code_ ]; then\n\tEXIT $_return_code_\nfi\n\nEXIT $_return_code_\n\n", "num_lines": 2387}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##+----------------------------------------------------------------------------------+\n##            Copyright(c) Microsoft Corp. 2015\n##+----------------------------------------------------------------------------------+\n## File         :   StartupScript.sh\n##\n## Description  :   Start-up script invoked by Azure guest agent when the custom-script\n##                  extension is set for hydration-vm as part of recovery work-flow.\n##\n## History      :   1-6-2015 (Venu Sivanadham) - Created\n##+----------------------------------------------------------------------------------+\n\n#\n# Binaries and command\n#\nexport MKDIR=/bin/mkdir\nexport RM=/bin/rm\nexport COPY=/bin/cp\nexport SET_PERMS=/bin/chmod\nexport UNZIP_CMD=/usr/bin/unzip\n\n#\n# Other global variables\n#\nexport LOGFILE=/usr/local/AzureRecovery/AzureRecoveryUtil.log\nexport WORK_DIR=/usr/local/AzureRecovery\nexport LINUX_GA_DIR=/usr/local/AzureRecovery/WALinuxAgentASR\n\nexport RECOVERY_TOOLS_ZIPFILE=\"AzureRecoveryTools.zip\"\nexport LINUX_GA_TOOLS_ZIPFILE=\"master.zip\"\n\nexport HOSTINFO_PREFIX=\"hostinfo\"\nexport REC_INFO_PREFIX=\"azurerecovery\"\nexport AZURE_RECOVERY_UTIL=\"AzureRecoveryUtil\"\n\n#\n# Info files global variables\n#\nexport RECOVERY_INFO_FILE=\"\"\nexport HOSTINFO_FILE=\"\"\nexport HYDRATION_CONFIG_SETTINGS=\"emptyconfig\"\n\n#\n# Status global variable\n# \nexport EXEC_STATUS=\"Processing\"\nexport EXEC_TASK_DESC=\"Preparing Environment\"\nexport EXEC_ERROR=\"0\"\nexport EXEC_ERROR_MSG=\"Preparing the environment for pre-recovery steps execution\"\nexport EXEC_PROGRESS=\"0\"\n\n_MAX_RETRY_ATTEMPTS_=10\n_TRUE_=1\n_FALSE_=0\n_HOST_ID_=\"\"\n_SCENARIO_=\"\"\n_SCENARIO_RECOVERY_=\"recovery\"\n_SCENARIO_MIGRATION_=\"migration\"\n_SCENARIO_RECOVERY_TEST_=\"testrecovery\";\n_SCENARIO_MIGRATION_TEST_= \"testmigration\";\n\n#\n# Trace functions to log the trace messages to log file.\n#\nfunction Trace\n{\n    echo \"$(date +\"%a %b %d %Y %T\") : $1\" >> $LOGFILE \n\n    # Log to the standard console as well.\n    echo \"$(date +\"%a %b %d %Y %T\") : $1\"\n}\n\nfunction Trace_Error \n{\n    Trace \"Error : $1\"\n}\n\nfunction Trace_Cmd \n{\n    Trace \" Command: $1\"\n}\n\nfunction Verify_User \n{\n    if [ \"$(id -u)\" != \"0\" ]\n    then\n        echo \"Only root user can run this script.\" >2\n        exit 1\n    fi\n}\n\n#\n# Synopsis    : Create_Dir <directory-path>\n#\n# Description : Creates a directory if not exist. If it exist then the existing directory will be\n#               forcefully deleted and then new one will be created.\n#\nfunction Create_Dir \n{\n    if [ -z \"$1\" ] ; then\n        echo \"Create_Dir : Directory argument missing\"\n        return 1\n    fi\n    \n    if [ -d $1 ] ; then\n        echo \"Directory $1 already exist. Deleting it...\"\n        $RM -rf $1\n        if [ $? -ne 0 ] ; then\n            echo \"Could not clean-up old directory\"\n            return 1\n        fi\n    fi\n    \n    echo  \"Creating directory $1\"\n    \n    $MKDIR -p $1 \n    if [ $? -ne 0 ] ; then\n        echo \"Error creating directory. Error $?\"\n        return 1\n    fi\n    \n    return 0\n}\n\n#\n# Synopsis    : Change_Dir <target-directory>\n#\n# Description : Changes the present working directory to target-directory\n#               \n#\nfunction Change_Dir\n{\n    if [ \"$1\" = \"\" ] ; then\n        Trace \"Change_Dir : Directory argument missing\"\n        return 1\n    fi\n    \n    if [ -d $1 ] ; then\n        cd $1 >> $LOGFILE 2>&1\n        \n        if [ $? -ne 0 ] ; then\n            Trace \"Can not change to directory $1\"\n            return 1\n        fi\n    else\n        Trace \"$1 Is not a directory or it does not exist\"\n        return 1\n    fi\n    \n    return 0\n}\n\n#\n# Synopsis    : CopyFiles <file-list> <destination-directory>\n#\n# Description : Copies the list of files to destination directory\n#               \n#\nfunction CopyFiles\n{\n    if [ $# -ne 2 ] ; then\n        Trace_Error \"CopyFiles Invalid arguments. Argument count: $#\"\n        return 1\n    fi\n    \n    if [ \"$1\" = \"\" ] ; then\n        Trace_Error \"CopyFiles Invalid argument. Empty file list\"\n        return 1\n    fi\n    FileList=$1\n    \n    if [ \"$2\" = \"\" ] ; then\n        Trace_Error \"CopyFiles Invalid argument. target-directory path is empty\"\n        return 1\n    fi\n    DestDir=$2\n    \n    Trace \"Copying files $FileList to $DestDir\"\n    \n    for file in $FileList\n    do\n        Trace_Cmd \"$COPY -f $file $DestDir\"\n        $COPY -f $file $DestDir >> $LOGFILE 2>&1\n        if [ $? -ne 0 ] ; then\n            Trace_Error \"Can not copy file $file to $DestDir\"\n            return 1\n        fi\n    done\n}\n\nfunction Extract_ZipFile_Using_Python\n{\n    # Create python script to extract the zip file.\n    local unzip_py=\"${WORK_DIR}/unzip.py\"\n    echo '#!/usr/bin/python' > $unzip_py\n    echo 'import sys' >> $unzip_py\n    echo 'from zipfile import ZipFile' >> $unzip_py\n    echo 'from zipfile import BadZipfile' >> $unzip_py\n    echo 'try:' >> $unzip_py\n    echo \"    zip_file = \\\"$1\\\"\" >> $unzip_py\n    echo \"    dest_dir = \\\"$2\\\"\" >> $unzip_py\n    echo '    pzf = ZipFile(zip_file)' >> $unzip_py\n    echo '    pzf.extractall(dest_dir)' >> $unzip_py\n    echo 'except BadZipfile:' >> $unzip_py\n    echo '    print(\"Error: Bad zip file format.\")' >> $unzip_py\n    echo '    sys.exit(1)' >> $unzip_py\n    echo 'else:' >> $unzip_py\n    echo '    print(\"Successfully extracted the zip file.\")' >> $unzip_py\n    echo '    sys.exit(0)' >> $unzip_py\n    \n    # Run python script\n    python3 $unzip_py >> $LOGFILE 2>&1\n\n    return $?\n}\n\n#\n# Synopsis    : Extract_ZipFile <zipfile_path> <target-directory>\n#\n# Description : Extracts the zip file content to target directory.\n#               \n#\nfunction Extract_ZipFile\n{\n    if [ $# -ne 2 ] ; then\n        Trace_Error \"Extract_ZipFile Invalid arguments. Argument count: $#\"\n        return 1\n    fi\n    \n    if [ \"$1\" = \"\" ] ; then\n        Trace_Error \"Extract_ZipFile Invalid argument. zipfile path is empty\"\n        return 1\n    fi\n    \n    if [ \"$2\" = \"\" ] ; then\n        Trace_Error \"Extract_ZipFile Invalid argument. target-directory path is empty\"\n        return 1\n    fi\n    \n    Trace \"Extracting $1 to $2\"\n    \n    if [[ -f $UNZIP_CMD ]]; then    \n        Trace_Cmd \"$UNZIP_CMD -oq $1 -d $2\"\n        $UNZIP_CMD -oq $1 -d $2 >> $LOGFILE 2>&1\n    else\n        Trace \"Extracting zip file using python...\"\n        Extract_ZipFile_Using_Python $1 $2\n    fi\n    \n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Error extracting $1 to $2\"\n        return 1\n    fi\n    \n    Trace \"Unzip successful\"\n    return 0\n}\n\n#\n# Synopsis    : ScanAllScsiHosts\n#\n# Description : Scans all the hosts buses available to the machine\n#\nfunction ScanAllScsiHosts \n{\n    for host in /sys/class/scsi_host/host*\n    do\n        Trace \"Scanning the $host ...\"\n        echo \"- - -\" > $host/scan\n    done\n}\n\n#\n# Synopsis    : ScanLVM\n#\n# Description : Scans all the VGs\n#\nfunction ScanLVM\n{\n    # Scan PVs\n    Trace \"Scanning PVs ...\"\n    pvscan >> $LOGFILE 2>&1\n    \n    # Scan LVs\n    Trace \"Scanning VGs ...\"\n    vgscan >> $LOGFILE 2>&1\n}\n\n#\n# Synopsis    : ActivateVGs\n#\n# Description : Activate all the VGs visible to the system.\n#\nfunction ActivateVGs\n{\n    for vg in $(vgs -o vg_name --noheadings)\n    do\n        Trace \"Activating VG: $vg\"\n        vgchange -ay \"$vg\" >> $LOGFILE 2>&1\n    done\n    \n    Trace \"VG details:\"\n    vgs -o vg_name,vg_attr,lv_count >> $LOGFILE 2>&1 #Trace purpose.\n}\n\n#\n# Synopsis    : VerifyFiles <file-list>\n#\n# Description : Verifies files existence\n#\nfunction VerifyFiles \n{\n    if [ $# -eq 0 ] ; then\n        Trace_Error \"VerifyFiles invalid argument: Argument missing or empty\"\n        return 1\n    fi\n    \n    for file in $1\n    do\n        Trace \"Verifying file : $file\"\n        \n        if [ -f $file ] ; then\n            Trace \"File exist\"\n        else\n            Trace_Error \"File does not exist\"\n            return 1\n        fi\n    done\n    \n    return 0\n}\n\n#\n# Synopsis    : EnableExe_Permissions Directory\n#\n# Description : Enables the execute permissions to all the files in Directory\n#\nfunction EnableExe_Permissions \n{\n    Trace \"Setting execute permissions for the scripts ...\"\n    \n    if [ $# -eq 0 ] ; then\n        Trace_Error \"EnableExe_Permissions invalid argument: Argument missing or empty\"\n        return 1\n    fi\n    \n    for file in \"$1\"/*\n    do  \n        if [ -f $file ] ; then\n            Trace_Cmd \"$SET_PERMS +x $file\"\n            $SET_PERMS +x $file >> $LOGFILE 2>&1\n            if [ $? -ne 0 ] ; then\n                 return 1\n            fi\n        else\n            Trace_Error \"$file is not a regular file or it does not exist\"\n        fi\n    done\n    \n    Trace \"Successfully enabled permissions.\"\n    \n    return 0\n}\n\n#\n# Synopsis    : Update_Status\n#\n# Description : Invokes recovery utility to update the current status to blob.\n#               \n#\nfunction Update_Status \n{\n    Trace \"Updating execution status : $EXEC_STATUS : $EXEC_TASK_DESC\"\n        \n    StatusArgs=\"--operation updatestatus --recoveryinfofile $RECOVERY_INFO_FILE --status $EXEC_STATUS  --errorcode $EXEC_ERROR --progress $EXEC_PROGRESS\"\n    StatusCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    \n    Trace_Cmd \"$StatusCmd  $StatusArgs --taskdescription $EXEC_TASK_DESC --errormsg $EXEC_ERROR_MSG\"\n    \n    $StatusCmd  $StatusArgs \"--taskdescription\" \"$EXEC_TASK_DESC\" \"--errormsg\" \"$EXEC_ERROR_MSG\" >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if [ $RetCode -ne 0 ] ; then\n        Trace_Error \"Status update failed. Return code $RetCode\"\n        return 1\n    else\n        Trace \"Successfully updated the status.\"\n    fi\n    \n    return 0;\n}\n\n#\n# Synopsis    : Update_Test_Status\n#\n# Description : Invokes recovery utility to update the current status to local file.\n#               \n#\nfunction Update_Test_Status \n{\n    Trace \"Updating execution status : $EXEC_STATUS : $EXEC_TASK_DESC\"\n        \n    StatusArgs=\"--operation statusupdatetest --recoveryinfofile $RECOVERY_INFO_FILE --status $EXEC_STATUS  --errorcode $EXEC_ERROR --progress $EXEC_PROGRESS\"\n    StatusCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    \n    Trace_Cmd \"$StatusCmd  $StatusArgs --taskdescription $EXEC_TASK_DESC --errormsg $EXEC_ERROR_MSG\"\n    \n    $StatusCmd  $StatusArgs \"--taskdescription\" \"$EXEC_TASK_DESC\" \"--errormsg\" \"$EXEC_ERROR_MSG\" >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if [ $RetCode -ne 0 ] ; then\n        Trace_Error \"Status update failed. Return code $RetCode\"\n        # Don't fail.\n    else\n        Trace \"Successfully updated the status.\"\n    fi\n    \n    return 0;\n}\n\n#\n# Synopsis    : Upload_Log\n#\n# Description : Invokes recovery utility for uploading the execution log content to status blob\n#               \n#\nfunction Upload_Log\n{\n    Trace \"Uploading log to status blob ...\"\n    \n    UploadCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    UploadCmdArgs=\"--operation uploadlog --recoveryinfofile $RECOVERY_INFO_FILE --logfile $LOGFILE\"\n    \n    Trace_Cmd \"$UploadCmd $UploadCmdArgs\"\n    \n    $UploadCmd $UploadCmdArgs >> $LOGFILE 2>&1\n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Log upload failed\"\n        return 1\n    else\n        Trace \"Log upload successful\"\n    fi\n    \n    return 0;\n}\n\n#\n# Synopsis    : Prepare_Env <host-id>\n#\n# Description : Prepare the environment for pre-recovery steps execution.\n#\nfunction Prepare_Env\n{\n    Trace \"Preparing the environment for pre-recovery steps execution ...\"\n\n    HostInfoFile=\"$HOSTINFO_PREFIX-$_HOST_ID_.xml\"\n    RecInfoFile=\"$REC_INFO_PREFIX-$_HOST_ID_.conf\"\n    PWD=$(pwd)\n    \n    RECOVERY_INFO_FILE=\"$WORK_DIR/$RecInfoFile\"\n    HOSTINFO_FILE=\"$WORK_DIR/$HostInfoFile\"\n    \n    #\n    # Extract the zip file to working directory\n    #\n    Extract_ZipFile \"$PWD/$RECOVERY_TOOLS_ZIPFILE\" $WORK_DIR\n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Azure recovery files extraction failed.\"\n        return 1\n    fi\n\n    #\n    # Downlaod and extract Linux Guest Agent files.\n    # Timeout: 300 seconds\n    #\n    \n    if curl --silent -LO \"https://github.com/Azure/WALinuxAgent/archive/master.zip\" -m 300; then\n        Trace \"Successfully downloaded WALinuxAgent zip file.\"\n        # Extract master.zip into WALinuxAgentASR\n        Extract_ZipFile \"$PWD/$LINUX_GA_TOOLS_ZIPFILE\" $LINUX_GA_DIR\n        if [ $? -ne 0 ] ; then\n            Trace_Error \"Linux guest agent binaries extraction failed.\"\n        else\n            # Enable execution permissions on downloaded guest agent files.\n            EnableExe_Permissions  $LINUX_GA_DIR\n            if [ $? -ne 0 ] ; then\n                Trace_Error \"Could not enable execute permission for one of the executables/scripts in Linux GA directory\".\n            fi\n        fi        \n    else\n        Trace_Error \"Could not download WALinuxAgent zip file from github.\"\n    fi\n\n    #\n    # Set execute permission to the executables/scripts after extraction\n    #\n    EnableExe_Permissions $WORK_DIR\n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Could not enable execute permission for one of the executables/scripts on working directory.\"\n        return 1\n    fi\n    \n    #\n    # Verify the host-info, recovery-info & executables zip file.\n    #\n    Trace \"Verifying extension files...\"\n    local ext_files=\"$PWD/$RECOVERY_TOOLS_ZIPFILE $PWD/$RecInfoFile\"\n    if [ \"$_SCENARIO_\" = \"$_SCENARIO_RECOVERY_\" ]; then\n        ext_files=\"$ext_files $PWD/$HostInfoFile\"\n    fi\n    \n    VerifyFiles \"$ext_files\"\n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Required files are missing: $ext_files\"\n        return 1\n    fi\n    \n    #\n    # Copy host-info & recovery-info files to working directory\n    #\n    Trace \"Copying configuration files to working directory ...\"\n    \n    local config_files=\"$PWD/$RecInfoFile\"\n    if [ \"$_SCENARIO_\" = \"$_SCENARIO_RECOVERY_\" ]; then\n        config_files=\"$config_files $PWD/$HostInfoFile\"\n    fi\n    CopyFiles \"$config_files\" $WORK_DIR\n    if [ $? -ne 0 ] ; then\n        Trace_Error \"Can not copy configuration files to $WORK_DIR\"\n        return 1\n    fi\n    \n    #\n    # Update Execution Status\n    #\n    Update_Status\n\n    #\n    # Change the directory to working directory\n    #\n    Trace \"Changing current directory to working directory ...\"\n    Change_Dir $WORK_DIR\n    if [ $? -ne 0 ] ; then\n        EXEC_ERROR_MSG=\"Can not change to working directory $WORK_DIR. Error $?\"\n        EXEC_ERROR=\"2\"\n        EXEC_STATUS=\"Failed\"\n        \n        Trace_Error \"$EXEC_ERROR_MSG\"\n        \n        Update_Status\n        Upload_Log\n        \n        return 1\n    fi \n    \n    #\n    # Rescan all scsi host buses\n    #\n    ScanAllScsiHosts\n    \n    #\n    # Rescan VGs\n    #\n    ScanLVM\n    \n    Trace \"Successfully prepared the environment.\"\n    \n    return 0\n}\n\n#\n# Synopsis    : StartRecovery\n#\n# Description : Start recovery utility to execute pre-recovery steps. (Failover and Test Failover)\n#\nfunction StartRecovery\n{\n    #\n    # Update status with Initiating recovery status.\n    #\n    EXEC_TASK_DESC=\"Initiating recovery steps\"\n    EXEC_ERROR_MSG=\"Environment was prepared successfully\"\n    EXEC_PROGRESS=\"20\"\n    \n    Update_Status\n    #not considering update status return code\n    \n    Trace \"Starting pre-recovery steps ...\"\n    \n    RecCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    RecCmdArgs=\"--operation recovery --recoveryinfofile $RECOVERY_INFO_FILE --hostinfofile $HOSTINFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS\"\n    \n    Trace_Cmd \"$RecCmd $RecCmdArgs\"\n    \n    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if (( $RetCode != 0 )) ; then\n        EXEC_ERROR_MSG=\"Recovery tool exited unexpectedly with error code $RetCode\"\n        EXEC_ERROR=\"1\"\n        EXEC_STATUS=\"Failed\"\n        \n        Trace_Error \"$EXEC_ERROR_MSG\"\n        \n        Update_Status\n        Upload_Log\n        \n        return 1\n    fi\n    #\n    # For recovery operation the tool returns 0 even on recovery failures if it can handle\n    # the error status reporting. If its not returning 0 means something wrong happened \n    # where the recovery tool was not able to update status to blob. So on non-zero return\n    # code the script should attempt updating failure status to blob.\n    #\n    Trace \"Pre-Recovery steps executed successfully\"\n    \n    return 0;\n}\n\n#\n# Synopsis    : StartRecoveryTest\n#\n# Description : Start recovery utility to execute pre-recovery steps.\n#               [Note]: Not to be confused with Test Failover in Azure Site Recovery production environment.\n#               Refer StartRecovery for TestFailover flow.\n#\n#\nfunction StartRecoveryTest\n{\n    #\n    # Update status with Initiating recovery status.\n    #\n    EXEC_TASK_DESC=\"Initiating recovery steps\"\n    EXEC_ERROR_MSG=\"Environment was prepared successfully\"\n    EXEC_PROGRESS=\"20\"\n    \n    Trace \"Starting pre-recovery steps ...\"\n    \n    RecCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    RecCmdArgs=\"--operation recoverytest --recoveryinfofile $RECOVERY_INFO_FILE --hostinfofile $HOSTINFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS\"\n    \n    Trace_Cmd \"$RecCmd $RecCmdArgs\"\n    \n    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if (( $RetCode != 0 )) ; then\n        EXEC_ERROR_MSG=\"Recovery tool exited unexpectedly with error code $RetCode\"\n        EXEC_ERROR=\"1\"\n        EXEC_STATUS=\"Failed\"\n        \n        Trace_Error \"$EXEC_ERROR_MSG\"\n        \n        Update_Test_Status\n        \n        return 1\n    fi\n    #\n    # For recovery operation the tool returns 0 even on recovery failures if it can handle\n    # the error status reporting. If its not returning 0 means something wrong happened \n    # where the recovery tool was not able to update status to blob. So on non-zero return\n    # code the script should attempt updating failure status to blob.\n    #\n    Trace \"Pre-Recovery steps executed successfully\"\n    \n    return 0;\n}\n\n#\n# Synopsis    : StartMigration\n#\n# Description : Start recovery utility to execute migration steps. (Migration and Test Migration)\n#\n#\nfunction StartMigration\n{\n    #\n    # Update status with Initiating recovery status.\n    #\n    EXEC_TASK_DESC=\"Initiating migration steps\"\n    EXEC_ERROR_MSG=\"Environment was prepared successfully\"\n    EXEC_PROGRESS=\"20\"\n    \n    Update_Status\n    #not considering update status return code\n    \n    # Activate all the VGs visible to system.\n    Trace \"Activating VGs ...\"\n    ActivateVGs\n    \n    Trace \"Starting migration steps ...\"\n    \n    RecCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    RecCmdArgs=\"--operation migration --recoveryinfofile $RECOVERY_INFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS\"\n    \n    Trace_Cmd \"$RecCmd $RecCmdArgs\"\n    \n    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if (( $RetCode != 0 )) ; then\n        EXEC_ERROR_MSG=\"Recovery tool exited unexpectedly with error code $RetCode\"\n        EXEC_ERROR=\"1\"\n        EXEC_STATUS=\"Failed\"\n        \n        Trace_Error \"$EXEC_ERROR_MSG\"\n        \n        Update_Status\n        Upload_Log\n        \n        return 1\n    fi\n\n    Trace \"Migration steps executed successfully\"\n    \n    return 0;\n}\n\n#\n# Synopsis    : StartMigrationTest\n#\n# Description : Dummy start recovery utility to execute migration steps.\n#               [Note]: Not to be confused with Test Migration in Azure Migrate in production environment.\n#               Refer StartMigration for TestMigration flow.\n#\n#\nfunction StartMigrationTest\n{\n    #\n    # Update status with Initiating recovery status.\n    #\n    EXEC_TASK_DESC=\"Initiating migration steps\"\n    EXEC_ERROR_MSG=\"Environment was prepared successfully\"\n    EXEC_PROGRESS=\"20\"\n\n    # Activate all the VGs visible to system.\n    Trace \"Activating VGs ...\"\n    ActivateVGs\n    \n    Trace \"Starting migration steps ...\"\n    \n    RecCmd=\"$WORK_DIR/$AZURE_RECOVERY_UTIL\"\n    RecCmdArgs=\"--operation migrationtest --recoveryinfofile $RECOVERY_INFO_FILE --workingdir $WORK_DIR --hydrationconfigsettings $HYDRATION_CONFIG_SETTINGS\"\n    \n    Trace_Cmd \"$RecCmd $RecCmdArgs\"\n    \n    $RecCmd $RecCmdArgs >> $LOGFILE 2>&1\n    \n    RetCode=$?\n    \n    if (( $RetCode != 0 )) ; then\n        EXEC_ERROR_MSG=\"Recovery tool exited unexpectedly with error code $RetCode\"\n        EXEC_ERROR=\"1\"\n        EXEC_STATUS=\"Failed\"\n        \n        Trace_Error \"$EXEC_ERROR_MSG\"\n        \n        Update_Test_Status\n\n        return 1\n    fi\n\n    Trace \"Migration steps executed successfully\"\n    \n    return 0;\n}\n\n#\n# Synopsis    : Usage\n#\n# Description : Displays script usage\n#               \n#\nfunction Usage\n{\n    echo \"Usage: $1 <recovery/migration> <host-id>\"\n}\n\n#\n# Synopsis    : ### Main ###\n#\n# Description : Entry point function which starts the work-flow\n#               \n#\nfunction Main\n{\n    if [ $# -eq 1 ] ; then\n        # For backward compatibility.\n        _SCENARIO_=$_SCENARIO_RECOVERY_\n        _HOST_ID_=$1\n    elif [ $# -eq 2 ] ; then\n        _SCENARIO_=$1\n        _HOST_ID_=$2\n    elif [ $# -eq 3 ] ; then\n        _SCENARIO_=$1\n        _HOST_ID_=$2\n        HYDRATION_CONFIG_SETTINGS=${3-emptyconfig}\n    else\n        Usage $0\n        exit 1\n    fi\n    \n    Create_Dir \"$WORK_DIR\"\n    if [ $? -ne 0 ] ; then\n        echo \"Error: Can not create working directory $WORK_DIR\"\n        exit 1\n    fi\n\n    if [[ $HYDRATION_CONFIG_SETTINGS =~ .*$_ENABLE_LINUX_GA_CONFIG_.* ]]; then\n        Create_Dir \"$LINUX_GA_DIR\"\n        if [ $? -ne 0 ] ; then\n            echo \"Error: Can not create linux guest agent directory $LINUX_GA_DIR\"\n            #Don't fail\n        fi\n    fi\n \n    Verify_User\n    \n    #\n    # Don't use Trace before this point because the log file creation may fail\n    # as log file will be created inside the working directory and the working\n    # directory has been created just now.\n    #\n    \n    Prepare_Env\n    if [ $? -ne 0 ] ; then\n        exit 1\n    fi\n    \n    case \"$_SCENARIO_\" in\n        $_SCENARIO_RECOVERY_)\n            StartRecovery\n            if [ $? -ne 0 ] ; then\n                exit 1\n            fi\n            ;;\n        $_SCENARIO_MIGRATION_)\n            StartMigration\n            if [ $? -ne 0 ] ; then\n                exit 1\n            fi\n            ;;\n        $_SCENARIO_MIGRATION_TEST_)\n            StartMigrationTest\n            if [ $? -ne 0 ] ; then\n                exit 1\n            fi\n            ;;\n        $_SCENARIO_RECOVERY_TEST_)\n            StartRecoveryTest\n            if [ $? -ne 0 ] ; then\n                exit 1\n            fi\n            ;;\n        *)\n            Usage $0\n            echo \"$_SCENARIO_ is unsupported for Linux Hydration.\"\n            exit 1\n            ;;\n    esac\n    \n    #\n    # Normal exit\n    #\n    exit 0\n}\n\n#\n# Calling Entry point function for script execution\n#\nMain \"$@\"", "num_lines": 878}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ncat \"/usr/local/AzureRecovery/ErrorCode.log\"", "num_lines": 2}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\n################\n#DEFAULT VALUES#\n################\n\nDIR=`pwd`\ncd ${DIR}\n\n###################\n# CHECKING FOR ACE#\n###################\n\necho \"ACE\" > thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/ace-6.4.6/ACE_wrappers -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n##############################################\n# CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1#\n##############################################\n\necho \"CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1 OR NOT FOR RELEASE\" >> thirdparty_components_check.log\necho \"-------------------------------------------------------------- \" >> thirdparty_components_check.log\ncat ${DIR}/ace-6.4.6/ACE_wrappers/ace/config.h | grep \"ACE_HAS_AIO_CALLS*\" >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\necho \"CHECKING WHETHER ACE_HAS_AIO_CALLS SET TO 1 OR NOT FOR DEBUG\" >> thirdparty_components_check.log\necho \"-------------------------------------------------------------- \" >> thirdparty_components_check.log\ncat ${DIR}/ace-6.4.6/ACE_wrappers/ace/config.h | grep \"ACE_HAS_AIO_CALLS*\" >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n#####################\n# CHECKING FOR BOOST#\n#####################\n\necho \"BOOST\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/boost -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n###################\n# CHECKING FOR CDK#\n###################\n\necho \"CDK\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/cdk-5.0.4 -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n####################\n# CHECKING FOR CURL#\n####################\n\necho \"CURL\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/curl-7.59.0 -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n#######################\n# CHECKING FOR OPENSSL#\n#######################\n\necho \"OPENSSL\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/openssl-1.0.2p -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n######################\n# CHECKING FOR SQLITE#\n######################\n\necho \"SQLITE\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/sqlite-3.8.2 -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n#########################\n# CHECKING FOR SQLITE_3X#\n#########################\n\necho \"SQLITE3X\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/sqlite3x/ -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n####################\n# CHECKING FOR ZLIB#\n####################\n\necho \"ZLIB\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/zlib-1.2.8 -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n#######################\n# CHECKING FOR LIBSSH2#\n#######################\n\necho \"LIBSSH\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/libssh2-1.8.0 -name \"*.a\" -print >> thirdparty_components_check.log\necho \" \" >> thirdparty_components_check.log\n\n#######################\n# CHECKING FOR LIBXML2#\n#######################\n\necho \"LIBXML\" >> thirdparty_components_check.log\necho \"---------\" >> thirdparty_components_check.log\nfind ${DIR}/libxml2/libxml2-2.9.1 -name \"*.a\" -print >> thirdparty_components_check.log\n", "num_lines": 112}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# get configuration\n[ -n \"$WEBSTONEROOT\" ] || WEBSTONEROOT=`pwd`/..\n. $WEBSTONEROOT/conf/testbed\n\ncase $# in\n  1)\n     FILELIST=$1\n     ;;\n  *)\n     FILELIST=$WEBSTONEROOT/conf/filelist\n     ;;\nesac\n\nTIMESTAMP=`date +\"%y%m%d_%H%M\"`\nmkdir $TMPDIR/webstone-genfiles.$TIMESTAMP\ncd $TMPDIR/webstone-genfiles.$TIMESTAMP\n\ncat $FILELIST |\nnawk '\n($3 ~ /^\\#[0-9]*/) {\n  sub(/^\\#/, \"\", $3);\n  cmd = WEBSTONEROOT \"/bin/genrand \" $3 \" .\"$1\n  print cmd;\n  system(cmd);\n  cmd = RCP \" .\" $1 \" \" SERVER \":\" WEBDOCDIR\n  print cmd;\n  system(cmd);\n  cmd = \"rm -f .\" $1\n  print cmd;\n  system(cmd);\n  next\n}\n' $* WEBSTONEROOT=$WEBSTONEROOT RCP=$RCP SERVER=$SERVER WEBDOCDIR=$WEBDOCDIR\n\ncd $TMPDIR\nrm -rf $TMPDIR/webstone-genfiles.$TIMESTAMP\n\n#end\n", "num_lines": 41}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# ", "num_lines": 1}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n\n# This is the UNIX version of the one-button ACE tests.\n# Contributed by Michael Rueger <m_rueger@SYSCOMP.DE>\n# mrm@cisco.com - Change to for loop  script could be more generic if we put\n# this in the bin dir and fed it a file to read from\n\nIFS=\"|\"\ntmp=/tmp\n\n# these patterns should not be included in log file\nERROR_MSGS=\"assertion failed|not supported|No such file or directory|Invalid argument|timeout|Bad file number\"\n\n# these patterns must be included in log file\nSUCCESS_MSGS=\"starting|Ending\"\n\nrun()\n{\n  echo running $1\n  /bin/rm -f core\n\n  ./$1\n  status=$?\n\n  if [ $status -ne 0 ]; then\n    echo \\\"$1\\\" FAILED with exit status $status!!!!\n  fi\n\n  if [ -f core ]; then\n    echo \\\"$1\\\" dumped core!!!!\n  fi\n\n  for i in $SUCCESS_MSGS; do\n    grep $i log/$1.log >/dev/null\n    if [ $? -eq 1 ]; then\n      echo Error in log file no line with $i\n    fi\n  done\n\n  for i in $ERROR_MSGS; do\n    grep $i log/$1.log\n  done\n}\n\necho \"Starting tests...\"\nFILES=`ls *_Test 2>/dev/null`\n\nif [ -z $FILES ]; then\n  echo \"ERROR: no test programs generated matching pattern *_Test.\"\n  echo \"ERROR: Try compiling the test programs first.\"\n  exit 1\nfi\n\nfor i in *_Test\ndo\n  run $i\ndone\n\necho \"Tests complete...\"\n\n\n# EOF\n", "num_lines": 64}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# This script assumes it is being run by bash\n\n# ======= needed functions ======\n# abspath relpath curentpath\nabspath ()\n{\n# treat \"./\" as a special case\nif expr \"$1\" : '\\./' >/dev/null; then\n  b=`echo $1 | sed 's@\\./@@'`\n  echo $2/$b\n  return 0\nfi\nb=$1\na=$2\n# for each \"../\" we remove one directory from the current path\n# and leading \"../\" from the relative path\n# until we have the unique part in b and the abs prefix in a\nwhile expr \"$b\" : '\\.\\./' >/dev/null\ndo\n  b=`echo $b | sed 's@\\.\\./@@'`\n  a=`echo $a | sed 's@/[^/]*$@@'`\ndone\n# return the completed absolute path\necho $a/$b\n}\n\n# relpath abspath curentpath\nrelpath ()\n{\n# take \"/\" off beginning\na=`echo $1 | sed 's@^/@@'`\n# take \"/\" off beginning and add to end\nb=`echo $2 | sed 's@^/@@;s@$@/@'`\nwhile true\ndo\n  if [ \"$b\" = \"\" ]; then\n    break;\n  fi\n  a1=`echo $a | sed 's@\\([^/]*\\)/.*@\\1@'`\n  b1=`echo $b | sed 's@\\([^/]*\\)/.*@\\1@'`\n  if [ \"$a1\" != \"$b1\" ]; then\n    break;\n  fi\n  a=`echo $a | sed 's@[^/]*/@@'`\n  b=`echo $b | sed 's@[^/]*/@@'`\ndone\n# a now has the unique part of the path\nc=\"\"\n# c will have the required number of \"../\"'s\nwhile [ \"$b\" != \"\" ]\ndo\n  c=\"../$c\"\n  b=`echo $b | sed 's@[^/]*/@@'`\ndone\n# return the completed relative path\necho \"$c$a\"\n}\n\n\n# ====== MAIN ======\n# Assume any relative path passed in is relative to the current directory\n# Given $1 is a path to the source file\n# Given $2 is a path of the link to be created\n# Create a link that has the relative path to the source file\n# That is, $1 converted relative to $2\n# Check if $1 is absolute or already relative\n#echo add_rel_link.sh $1 $2\nif expr \"$1\" : '\\/' >/dev/null; then\n  # The source path is absolute, this is the expected case\n  # Check if $2 is absolute or relative\n  if expr \"$2\" : '\\/' >/dev/null; then\n    # The link path is already absolute, so just use it\n    lpath=$2\n  else\n    # The link path is relative, this is the expected case\n    # WARNING: don't use $PWD here, it won't work right\n    # WARNING: pwd may be a shell alias.  Use /bin/pwd.\n    cur=`/bin/pwd`\n    lpath=`abspath $2 $cur`\n  fi\n  # take name off the end of the dest\n  ldir=`echo $lpath | sed 's@/[^/]*$@@'`\n\n  # If the original path and the ldir do not originate in the same\n  # directory tree, we should just use absolute paths\n  if [ \"`echo $1 | cut -d/ -f2`\" != \"`echo $ldir | cut -d/ -f2`\" ]; then\n    spath=$1\n  else\n    spath=`relpath $1 $ldir`\n  fi\n  # use the completed relative path and the given designation path\n  echo ln -s $spath $2\n  ln -s $spath $2\nelse\n  # The source path is already relative, so just use it\n  echo ln -s $1 $2\n  ln -s $1 $2\nfi\n", "num_lines": 100}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -z $1; then CURRENTDATE=YYYY_MM_DD; else CURRENTDATE=$1; fi\n\nwget http://teststat.remedy.nl/teststat/cleanbuild_testfails-$CURRENTDATE.txt -O cleanbuild.txt\n#\ngrep -h \\!FIXED_BUGS_ONLY ${ACE_ROOT}/tests/*.lst ${ACE_ROOT}/bin/*.lst ${TAO_ROOT}/bin/*.lst ${CIAO_ROOT}/bin/*.lst ${DANCE_ROOT}/bin/*.lst | sed -e \"s/^\\([^\\:]*\\).*/\\1/\" | sed -e \"s/\\(\\/run_test.pl\\)\\?\\s*$//\" > Ignore.txt\n#\ncat cleanbuild.txt | grep -v -f Ignore.txt | tee cleanbuildresults.txt\n\n", "num_lines": 11}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nSYSTEM=`uname -s`\nIPCS=\"ipcs\"\nIPCRM=\"ipcrm -s\"\n\nif [ \"$SYSTEM\" = \"Darwin\" ]; then\n  USER=`id | sed 's/(.*//; s/uid=//'`\n  IPCS=\"ngvipc -s\"\n  IPCRM=\"ngvipc -s -R\"\nelif [ -z \"$USER\" ]; then\n  USER=`id | sed 's/).*//; s/.*(//'`\nfi\n\n\ncase \"$SYSTEM\" in\n  \"Linux\" )\n    ipcs -a | grep $USER | awk '{ print ($2) }' | xargs -r ipcrm sem;\n    ;;\n  * )\n    semids=`$IPCS | grep \"^s\" | grep $USER | awk '{ print ($2) }'`\n    for p in $semids\n      do $IPCRM $p\n    done\n    ;;\nesac\n", "num_lines": 27}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nfor i in *.gz *.bz2 *.zip *.md5; do\n  d=`echo $i | sed 's/\\.[tz][ai][rp]/-$1&/'`\n  echo \"Copying $i to $d\"\n  cp -ip $i /export/www/download.dre/previous_versions/$d\ndone\n\n", "num_lines": 9}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -z $1; then newdate=`date -u +%Y_%m_%d`; else newdate=$1; fi\nif test -z $2; then prefix=`date -u +%Y%m%d%a`; else prefix=$2; fi\nif test -z $3; then olddate=2017_09_07; else olddate=$3; fi\nif test -z $ACE_ROOT; then ACE_ROOT=..; fi\nif test -z $TAO_ROOT; then TAO_ROOT=${ACE_ROOT}/TAO; fi\nif test -z $CIAO_ROOT; then CIAO_ROOT=${TAO_ROOT}/CIAO; fi\nif test -z $DANCE_ROOT; then DANCE_ROOT=${TAO_ROOT}/DAnCE; fi\nif test -z $DDS_ROOT; then DDS_ROOT=${TAO_ROOT}/DDS; fi\n#\ngrep -h \\!FIXED_BUGS_ONLY ${ACE_ROOT}/tests/*.lst ${ACE_ROOT}/bin/*.lst ${TAO_ROOT}/bin/*.lst ${CIAO_ROOT}/bin/*.lst ${DANCE_ROOT}/bin/*.lst ${DDS_ROOT}/bin/*.lst | sed -e \"s/^\\([^\\:]*\\).*/\\1/\" | sed -e \"s/\\(\\/run_test.pl\\)\\?\\s*$//\" > ${prefix}-Ignore.txt\n#\nperl ${ACE_ROOT}/bin/diff-builds.pl -r -D $olddate -D $newdate | perl -ne 'print unless /^(\\@\\@|[ \\-][a-zA-Z])/' | grep -v -f ${prefix}-Ignore.txt | tee ${prefix}-Builds.txt | grep '+[a-zA-Z]' | sort | uniq -c | sort -n -r -s | sort -k3 -r -s > ${prefix}-Tests.txt\nperl ${ACE_ROOT}/bin/diff-builds.pl -D $olddate -D $newdate | perl -ne 'print unless /^(\\@\\@|[ \\-][a-zA-Z])/' | grep -v -f ${prefix}-Ignore.txt | grep '+[a-zA-Z]' | sort | uniq -c | sort -n -r -s > ${prefix}-Tests-NoTestRev.txt\n", "num_lines": 16}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\nif [ $# -lt 1 ]; then\n  echo \"Usage: $0 [DEST]\"\n  exit 0\nfi\n\nDEST=$1\nDATE=`date +%Y/%m/%d-%H:%M`\n\nBINS=\"$TAO_ROOT/tests/ORB_init/ORB_init $TAO_ROOT/tests/ORB_destroy/ORB_destroy\"\n\nLIBS=\"$ACE_ROOT/ace/libACE.a \\\n    $TAO_ROOT/tao/libTAO.a \\\n    $TAO_ROOT/tao/PortableServer/libTAO_PortableServer.a \\\n    $TAO_ROOT/tao/Strategies/libTAO_Strategies.a \\\n    $TAO_ROOT/tao/SmartProxies/libTAO_SmartProxies.a \\\n    $TAO_ROOT/tao/DynamicAny/libTAO_DynamicAny.a \\\n    $TAO_ROOT/tao/DynamicInterface/libTAO_DynamicInterface.a \\\n    $TAO_ROOT/tao/IFR_Client/libTAO_IFR_Client.a \\\n    $TAO_ROOT/tao/BiDir_GIOP/libTAO_BiDirGIOP.a \\\n    $TAO_ROOT/tao/IORManipulation/libTAO_IORManip.a \\\n    $TAO_ROOT/tao/IORTable/libTAO_IORTable.a \\\n    $TAO_ROOT/tao/TypeCodeFactory/libTAO_TypeCodeFactory.a \\\n    $TAO_ROOT/tao/RTCORBA/libTAO_RTCORBA.a \\\n    $TAO_ROOT/tao/IORInterceptor/libTAO_IORInterceptor.a \\\n    $TAO_ROOT/tao/Messaging/libTAO_Messaging.a \\\n    $TAO_ROOT/tao/ObjRefTemplate/libTAO_ObjRefTemplate.a \\\n    $TAO_ROOT/tao/Valuetype/libTAO_Valuetype.a \\\n    $TAO_ROOT/tao/RTScheduling/libTAO_RTScheduler.a \\\n    $TAO_ROOT/tao/AnyTypeCode/libTAO_AnyTypeCode.a \\\n    $TAO_ROOT/tao/PI/libTAO_PI.a \\\n    $TAO_ROOT/tao/PI_Server/libTAO_PI_Server.a \\\n    $TAO_ROOT/tao/Codeset/libTAO_Codeset.a \\\n    $TAO_ROOT/tao/CodecFactory/libTAO_CodecFactory.a \\\n    $TAO_ROOT/tao/RTPortableServer/libTAO_RTPortableServer.a\"\n\nmkdir -p $DEST/source\nmkdir -p $DEST/data\nmkdir -p $DEST/images\n\nfor i in $BINS; do\n  b=`basename $i`\n  if [ -x $i ]; then\n    (\n      echo -n $DATE \" \";\n      size $i |\n      grep -v text |\n      awk '{print $4}'\n    ) >> $DEST/source/${b}_size.txt\n  fi\ndone\n\nfor i in $LIBS; do\n  b=`basename $i`;\n  if [ -f $i ]; then\n    (\n      echo -n $DATE \" \";\n      size $i |\n       awk '{s += $4} END {print s}'\n    ) >> $DEST/source/${b}_size.txt\n  fi\ndone\n\ncd $DEST/source\n\nfor i in $LIBS $BINS; do\n b=`basename $i`\n /usr/bin/tac ${b}_size.txt > $DEST/data/${b}_size.txt\n /usr/bin/tail -5 ${b}_size.txt > $DEST/data/LAST_${b}_size.txt\n $ACE_ROOT/bin/generate_footprint_chart.sh ${b}_size.txt $DEST/images/${b}_size.png $b\ndone\n", "num_lines": 74}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# This simple script is used to gather compile time metrics.  You can use\n# it with make like this:\n#\n#  $ make CXX=g++_metric.sh\n#\n\ncommandline=$@\n# find the target and save it to a variable\nuntil [ -z \"$1\" ] # test all command line parameters\ndo\n  if [ \"-o\" = \"$1\" ]\n  then\n    shift\n    target=$1\n    break\n  fi\n  shift\ndone\n\n# echo out \"(%x)\", the return value from g++, so the script processes the output\n#  will only use times for successful compilations, i.e., \"(0)\".\n/usr/bin/time -f \"//compile time(%x): ${PWD#$ACE_ROOT/}/${target} %U %S\" g++ $commandline\n\nretval=$?\n\nexit $retval\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# This script generate metrics html pages for either compile times or\n# footprint.\n#\n# Compile times:\n# Parse the build.txt file from an autobuild that was generated with the\n# g++_metric.sh script, e.g., with CXX=g++_metric.sh which outputs\n# compile times on a per object basis, and use the data to generate time\n# series graphs with gnuplot.\n#\n# Footprint:\n# Parse the build.txt file and and the *.map files, generated with LDFLAGS\n# set to =-Xlinker -M -Xlinker -Map -Xlinker \\$@.map and static_libs_only=1.\n#\n# For use with an autobuild, place a line something like this in the xml file,\n# after the log file is closed, but before it's moved.\n#\n#  <command name=\"shell\"  options=\"$ACE_ROOT/bin/generate_compile_stats.sh <path>/build.txt <destination> Footprint\" />\n#\n\n###############################################################################\n#\n# usage\n#\n###############################################################################\nusage ()\n{\n  echo \"Usage: `basename $0` [--base=<dir>] [--name=<name>] [--compiler=compiler]\"\n  echo \"       <input_file> <destination_directory> [target_file]\"\n  echo \"       [Footprint|Compilation] [<date>] [<fudge_factor>]\"\n  echo \"\"\n  echo \"--base       This option can be used to set the base root directory to\"\n  echo \"             something other than the default \\$ACE_ROOT.\"\n  echo \"--name       This option can be used to set the software title to something\"\n  echo \"             other than the default ACE+TAO+CIAO+DAnCE.\"\n  echo \"--compiler   This option can be used to set the compiler to something\"\n  echo \"             other than the default gcc.\"\n  echo \"input_file   This is the compilation log file.\"\n  echo \"destination_directory This designates the location of the generated html.\"\n  echo \"target_file  This is similar to input_file, but should contain no errors.\"\n  echo \"date         Set the date used in all generated html pages.\"\n  echo \"fudge_factor Add the specified number of seconds to the compilation time\"\n  echo \"             for each target.\"\n  echo \"\"\n  echo \"Options must be specified in the order shown above.\"\n  exit\n}\n\n###############################################################################\n#\n# parse_time\n#\n# this only works for english\n# assumes the date is formatted like this:  Sat Apr 12 18:19:31 UTC 2003\n# and outputs this: 2003/04/12-18:19\n#\n###############################################################################\nparse_time ()\n{\n  # todo: add a format parameter\n  local INDEX=0\n  local PT_MONTH=\"\"\n  local PT_DAY=\"\"\n  local PT_YEAR=\"\"\n  local PT_HOUR=\"\"\n  local PT_MINUTE=\"\"\n  local PT_SECOND=\"\"\n  local PT_TIMEZONE=\"\"\n\n  read -a line\n  for token in \"${line[@]}\"; do\n    #echo \"$INDEX = $token\"\n    case $INDEX in\n      1 ) case $token in\n            Jan ) PT_MONTH=\"01\" ;;\n            Feb ) PT_MONTH=\"02\" ;;\n            Mar ) PT_MONTH=\"03\" ;;\n            Apr ) PT_MONTH=\"04\" ;;\n            May ) PT_MONTH=\"05\" ;;\n            Jun ) PT_MONTH=\"06\" ;;\n            Jul ) PT_MONTH=\"07\" ;;\n            Aug ) PT_MONTH=\"08\" ;;\n            Sep ) PT_MONTH=\"09\" ;;\n            Oct ) PT_MONTH=\"10\" ;;\n            Nov ) PT_MONTH=\"11\" ;;\n            Dec ) PT_MONTH=\"12\" ;;\n          esac ;;\n      2 ) PT_DAY=\"$token\" ;;\n      3 ) PT_HOUR=\"${token%%:*}\"\n          PT_MINUTE=\"${token%:*}\"\n          PT_MINUTE=\"${PT_MINUTE#*:}\"\n          PT_SECOND=\"${token##*:}\" ;;\n      4 ) PT_TIMEZONE=\"$token\" ;;\n      5 ) PT_YEAR=\"$token\" ;;\n    esac\n    let INDEX=$INDEX+1\n  done\n  if [ \"$1\" = \"debug\" ]; then\n    echo \"month = $PT_MONTH\"\n    echo \"day   = $PT_DAY\"\n    echo \"year  = $PT_YEAR\"\n    echo \"hour  = $PT_HOUR\"\n    echo \"min   = $PT_MINUTE\"\n    echo \"sec   = $PT_SECOND\"\n    echo \"tz    = $PT_TIMEZONE\"\n  fi\n  echo \"$PT_YEAR/$PT_MONTH/$PT_DAY-$PT_HOUR:$PT_MINUTE\"\n}\n\n###############################################################################\n#\n# strip_date\n#\n# grab date from line with following format:\n# ################### End [Fri Apr 11 00:18:31 2003 UTC]\n# and return it in this format: Fri Apr 11 00:18:31 UTC 2003 which is\n# what parse_time() expects\n#\n###############################################################################\nstrip_date ()\n{\n  local INDEX=0\n  local TEMP_DATE=\"\"\n  local DATE=\"\"\n  read -a line\n  for token in \"${line[@]}\"; do\n    #echo \"$INDEX = $token\"\n    case $INDEX in\n       2 ) DATE=${token#[} ;;\n       7 ) DATE=\"$DATE ${token%]} $TEMP_DATE\" ;;\n       # this is a hack since the autobuild scripts don't format the date\n       # correctly...  :-(\n       6 ) TEMP_DATE=$token ;;\n       * ) DATE=\"$DATE $token\" ;;\n    esac\n    let INDEX=$INDEX+1\n  done\n  echo $DATE\n}\n\n###############################################################################\n#\n# parse\n#\n# Parse the commandline and validate the inputs\n#\n###############################################################################\nparse ()\n{\n  echo \"parse()\"\n  while [ $# -gt 1 ]; do\n    if [ -n \"`echo $1 | grep '^--base=.*'`\" ]; then\n      BASE_ROOT=`echo $1 | sed 's/^--base=//'`\n      shift\n    elif [ -n \"`echo $1 | grep '^--name=.*'`\" ]; then\n      BASE_TITLE=`echo $1 | sed 's/^--name=//'`\n      shift\n    elif [ -n \"`echo $1 | grep '^--compiler.*'`\" ]; then\n      COMPILER=`echo $1 | sed 's/^--compiler=//'`\n      shift\n    else\n      break\n    fi\n  done\n\n  # set input file and destination (required)\n  if [ $# -gt 1 ]; then\n    INFILE=$1\n    DEST=$2\n\n    if ! [ -e \"$INFILE\" ]; then\n      echo \"input_file $INFILE does not exist.\"\n      usage\n    fi\n  else\n    usage\n  fi\n\n  # set the target file from command line\n  if [ $# -gt 2 ]; then\n    TARGETS=$3\n  else\n   TARGETS=$INFILE\n  fi\n\n  # set type of metric from command line\n  if [ $# -gt 3 ]; then\n    METRIC=$4\n  else\n    METRIC=\"Compilation\"\n  fi\n  echo \"metric = ($METRIC)\"\n\n  # set the date from command line\n  if [ $# -gt 4 ]; then\n    DATE=$5\n  else\n    DATE=`tail -n 1 $INFILE | strip_date | parse_time`\n  fi\n  echo \"date = ($DATE)\"\n\n  # set fudge factor from commandline (for testing)\n  if [ $# -gt 5 ]; then\n    FUDGE_FACTOR=$6\n  else\n    FUDGE_FACTOR=0\n  fi\n}\n\n###############################################################################\n#\n# gen_chart\n#\n# Generate the actual charts and move them to ${DEST}\n#\n###############################################################################\ngen_chart ()\n{\n  local object=$1\n  local DEST=$2\n  local TYPE=$3\n  local EXT=\"txt\"\n  local YLABEL=\"Compile Time (Seconds)\"\n  local FACTOR=1\n  local low=$4\n  local high=$5\n\n  if [ \"$TYPE\" = \"Footprint\" ]; then\n    EXT=\"size\"\n    if [ ${high} -gt 1024 ]; then\n      YLABEL=\"Footprint (KBytes)\"\n      FACTOR=1024\n    else\n      YLABEL=\"Footprint (Bytes)\"\n      FACTOR=1\n    fi\n  fi\n\n  let low=\"${low}/${FACTOR}\"\n  let high=\"${high}/${FACTOR}\"\n\n  sort -t'/' -k1n -k2n -k3n ${DEST}/data/${object}.${EXT} | grep -E ^2 > tmp.txt\n\n  gnuplot <<EOF\n    set data style lp l\n    set time \"$DATE\"\n    set xdata time\n    set timefmt \"%Y/%m/%d-%H:%M\"\n    set format x \"%Y/%m/%d\"\n    set xtics rotate\n    set xlabel 'Date (YYYY/MM/DD)' 0,-3\n    set ylabel \"${YLABEL}\"\n    set terminal png small size 1024,768 color\n    set yrange [0:]\n    set output \"${DEST}/images/${object}_${TYPE}.png\"\n    set title \"${object//___//}\"\n    plot 'tmp.txt' using 1:(\\$2/$FACTOR) notitle w points, 'tmp.txt' using 1:(\\$2/$FACTOR) notitle w l lt 3 lw 4\n    exit\nEOF\n\n  # here's how to reduce the scale\n  #  plot '$1' using 1:(\\$2/1024.0) title '$3' w l\n}\n\n###############################################################################\n#\n# create_dirs\n#\n# Make sure hidden directory tree exists, and create it if it doesn't\n#\n###############################################################################\ncreate_dirs ()\n{\n  echo \"create_dirs() '$1'\"\n  if ! [ -d \"${1}\" ]; then\n    mkdir -p ${1}\n  fi\n  if ! [ -d \"${1}data\" ]; then\n    mkdir -p ${1}data\n  fi\n  if ! [ -d \"${1}images\" ]; then\n    mkdir -p ${1}images\n  fi\n}\n\n###############################################################################\n#\n# process_file\n#\n# Process the the $INPUT file\n#\n###############################################################################\nprocess_file ()\n{\n  echo \"process_file()\"\n\n  local CURRENT_TIME=0\n  local CURRENT_OBJECT=\"\"\n  local CURRENT_PATH=\"\"\n  local seconds=0\n  local hundreths=0\n\n  while read target usertime systemtime; do\n\n    # get path\n    CURRENT_PATH=${target%/*}\n\n    # strip off the hidden directory if needbe\n    CURRENT_PATH=${CURRENT_PATH%/.*}\n\n    # replace all \"/\" with \"___\"\n    # (so we can keep them all in the same directory)\n    CURRENT_PATH=${CURRENT_PATH//\\//___}\n\n    # strip path off of target\n    CURRENT_OBJECT=${CURRENT_PATH}___${target##*/}\n    #echo \"target = $target, object = $CURRENT_OBJECT,  path = $CURRENT_PATH\"\n    #echo \"usertime = $usertime, systemtime = $systemtime\"\n\n    let seconds=\"${usertime%.*}+${systemtime%.*}\"\n\n    # it's just easier to grab the values first, since .0n causes problems...\n    userdec=\"${usertime#*.}\"\n    userdec=${userdec#0}\n    systemdec=\"${systemtime#*.}\"\n    systemdec=${systemdec#0}\n    let hundreths=\"${userdec}+${systemdec}\"\n\n    let CURRENT_TIME=\"(${seconds}*100 + ${hundreths})+$FUDGE_FACTOR\"\n    echo $DATE $CURRENT_TIME >> ${DEST}/data/${CURRENT_OBJECT}.txt\n\n  done # while\n}\n\n###############################################################################\n#\n# composite_list\n#\n###############################################################################\ncomposite_list ()\n{\n  local FOUND_OBJ=0\n  local BASE_OBJ_FLAG=0\n  local BASE_OBJ=\"\"\n  local OBJ_LIST=\"\"\n  local DIR_LINE=0\n  local DIR=\"\"\n  local INDEX=0\n\n  while read -a line; do\n    DIR_LINE=0\n    INDEX=0\n\n    for i in \"${line[@]}\"; do\n      if [ $DIR_LINE -eq 1 ]; then\n\n        # only process when entering a directory\n        if [ $INDEX -eq 1 ] && [ \"$i\" = \"Leaving\" ]; then\n          DIR=\"\"\n          break\n        fi\n\n        if [ $INDEX -eq 3 ]; then\n          DIR=\"${i%?}\"                        # strip off last \"'\"\n          DIR=\"${DIR#*$BASE_ROOT/}\"           # strip off $BASE_ROOT\n          DIR=\"${DIR//\\//___}___\"             # replace \"/\" with \"___\"\n          break\n        else\n          let INDEX=\"$INDEX+1\"\n          continue\n        fi\n      fi\n\n      # if it was a \"make\" line then continue to the next token which will\n      # continue to process above\n      if [ \"${i%[*}\" = \"make\" ] || [ \"${i%:*}\" = \"make\" ]; then\n        DIR=\"\"\n        let DIR_LINE=1\n        let INDEX=\"$INDEX+1\"\n        continue\n      fi\n\n      # not an \"make\" line, so process it here.\n      if [ $BASE_OBJ_FLAG -eq 1 ]; then\n         BASE_OBJ=\"${DIR}${i##.*/}\"\n         # strip off lib numbers\n         if [ \"$BASE_OBJ\" != \"${BASE_OBJ%.so.*}\" ]; then\n           BASE_OBJ=${BASE_OBJ%.so.*}.so\n         fi\n         BASE_OBJ_FLAG=0\n      elif [ \"$i\" = \"-o\" ]; then\n        # found our base object, set flag so we can grab the next one\n        BASE_OBJ_FLAG=1\n      elif [ \"$i\" = \"${i#-}\" -a \"$i\" = \"${i#/}\" -a \"$i\" != \"${i%.o}\" ]; then\n        OBJ_LIST=\"$OBJ_LIST ${DIR}${i##*/}\"\n        FOUND_OBJ=1\n      fi\n    done # for\n    if [ $FOUND_OBJ -eq 1 ]; then\n      echo \"$BASE_OBJ : $OBJ_LIST\"\n      FOUND_OBJ=0\n      OBJ_LIST=\"\"\n      BASE_OBJ=\"\"\n    fi\n  done # while\n}\n\n###############################################################################\n#\n# create_composite_list\n#\n###############################################################################\ncreate_composite_list ()\n{\n  echo \"create_composite_list()\"\n  local INFILE=$1\n\n  # create a pattern file\n  echo \"\\-L\" > ${DEST}/comp_match.txt\n  echo \"Entering directory\" >> ${DEST}/comp_match.txt\n\n  # grep out the entering directory line and all the link lines,\n  # but only keep entering directory lines preceeding link lines.\n  cat $INFILE | grep -f ${DEST}/comp_match.txt | grep -B1 \"\\-L\" \\\n   | grep -ve \"--\" | composite_list > ${DEST}/composites.txt\n}\n\n###############################################################################\n#\n# library_list\n#\n###############################################################################\nlibrary_list ()\n{\n  local FOUND_OBJ=0\n  local BASE_OBJ_FLAG=0\n  local BASE_OBJ=\"\"\n  local OBJ_LIST=\"\"\n  local DIR_LINE=0\n  local DIR=\"\"\n  local INDEX=0\n\n  while read -a line; do\n    DIR_LINE=0\n    INDEX=0\n    for i in \"${line[@]}\"; do\n      if [ $DIR_LINE -eq 1 ]; then\n        if [ $INDEX -eq 3 ]; then\n          DIR=\"${i%?}\"                        # strip off last \"'\"\n          DIR=\"${DIR#*$BASE_ROOT/}\"           # strip off $BASE_ROOT\n          DIR=\"${DIR//\\//___}___\"             # replace \"/\" with \"___\"\n          break\n        else\n          let INDEX=\"$INDEX+1\"\n          continue\n        fi\n      fi\n\n      # if it was a \"make\" line then continue to the next token which will\n      # continue to process above\n      if [ \"${i%[*}\" = \"make\" ]; then\n        let DIR_LINE=1\n        let INDEX=\"$INDEX+1\"\n        continue\n      fi\n\n      # not a \"make\" line, so process it here.  We are interested in the\n      # 3rd, and last,  token, i.e., lib*.a\n      let INDEX=\"$INDEX+1\"\n      if [ $INDEX -eq 3 ]; then\n        echo \"$DIR$i\"\n      fi\n    done # for\n  done # while\n}\n\n###############################################################################\n#\n# create_library_list\n#\n###############################################################################\ncreate_library_list ()\n{\n  echo \"create_library_list()\"\n  local INFILE=$1\n\n  # create a pattern file\n  echo \"chmod\" > ${DEST}/lib_match.txt\n  echo \"Entering directory\" >> ${DEST}/lib_match.txt\n\n  # grep out the entering directory line and all the link lines,\n  # but only keep entering directory lines preceeding link lines.\n  cat $INFILE | grep -f ${DEST}/lib_match.txt | grep -B1 \"chmod\" \\\n   | grep -ve \"--\" | library_list > ${DEST}/libraries.txt\n}\n\n###############################################################################\n#\n# rollup_compile_times\n#\n###############################################################################\nrollup_compile_times ()\n{\n  echo \"process_composite_objects()\"\n  local TOTAL_TIME=0\n  local temp\n  local tdate=\"\"\n  local ttime=0\n  local lpath=\"${DEST}/data/\"\n\n  # rollup compile times\n  while read outfile colon infiles; do\n    #echo \"$outfile ----- $infiles\"\n    for i in $infiles; do\n      temp=`head -n 1 ${lpath}${i}.txt`\n      tdate=${temp%% *}\n      let ttime=\"${temp##* }\"\n\n      if [ \"$tdate\" = \"$DATE\" ]; then\n        let TOTAL_TIME=\"$TOTAL_TIME + ${ttime}\"\n      fi\n    done # for\n    echo \"$DATE $TOTAL_TIME\" >> ${lpath}${outfile}.txt\n    let TOTAL_TIME=0\n  done # while\n}\n\n###############################################################################\n#\n# footprint\n#\n###############################################################################\nfootprint ()\n{\n  echo \"footprint()\"\n  local TYPE=\"$1\"\n  local fpath=\"\"\n  local lpath=\"${DEST}/data/\"\n  local FILE=\"\"\n  local SIZE=\"\"\n\n  # Remove the old size_composites.txt and create a new one since\n  # we have all the info we need from the size command on a library.\n  if [ \"$TYPE\" = \"LIB\" ] && [ -e ${DEST}/size_composites.txt ]; then\n    rm ${DEST}/size_composites.txt\n  fi\n\n  # go through all the targets and get the sizes of the target and\n  # each dependent object and write it to a *.size file.\n  while read outfile colon infiles; do\n    # reconstitue file name\n    FILE=\"$BASE_ROOT/${outfile//___//}\"\n\n    if [ -e $FILE ]; then\n      #echo \"inside if\"\n      SIZE=`size $FILE | grep -v text | awk '{s += \\$4} END {print s}'`\n      echo \"$DATE $SIZE\" >> $lpath/${outfile}.size\n\n      # only process the included objects if it's a library\n      if [ \"$TYPE\" = \"LIB\" ]; then\n        fpath=${FILE%/*}\n        # now, do the same for all the objects in the file (if any)\n        size $FILE |\n        grep -v text |\n        awk '{print $4 \" : \" $6}' | process_included $fpath $lpath $FILE\n      fi\n    fi\n\n  done # while\n}\n\n###############################################################################\n#\n# process_included\n#\n###############################################################################\nprocess_included ()\n{\n  echo \"process_included()\"\n  local fpath=$1\n  local lpath=$2\n  local LIBRARY=$3\n  local FILE=\"\"\n  local OUTFILE=\"\"\n\n  # while we are here, and have the info, go ahead and write out\n  # size dependencies for each library.\n  LIBRARY=\"${LIBRARY#*$BASE_ROOT/}\"   # strip off $BASE_ROOT\n  LIBRARY=\"${LIBRARY//\\//___}\"        # replace \"/\" with \"___\"\n  echo -n  \"$LIBRARY : \" >> ${DEST}/size_composites.txt\n\n  while read size colon file; do\n    FILE=$fpath/$file\n    OUTFILE=\"${FILE#*$BASE_ROOT/}\"     # strip off $BASE_ROOT\n    OUTFILE=\"${OUTFILE//\\//___}\"       # replace \"/\" with \"___\"\n    #echo \"size = ($size)\"\n    echo \"$DATE $size\" >> $lpath/${OUTFILE}.size\n\n    # add the object\n    echo -n \"$OUTFILE \" >> ${DEST}/size_composites.txt\n\n  done\n  # add newline\n  echo \"\" >> ${DEST}/size_composites.txt\n\n}\n\n###############################################################################\n#\n# process_map_file\n#\n###############################################################################\nprocess_map_file ()\n{\n  # this is way too noisy...\n  #echo \"process_map_file()\"\n  local index=0\n  local INFILE=$1\n  local FILE=\"\"\n\n  # Read in the map file.  The first section is all we are interested\n  # in right now.  As soon as we see \"Memory Configuration\" we are done.\n  while read line; do\n    let index=$index+1\n    # Skip the first 2 lines, then read in all the odd lines, they are the\n    # objects that must be loaded.  The following line, even lines, is the\n    # object that caused it to be loaded.\n    if [ $index -lt 3 ] || [ \"$line\" = \"\" ]; then\n      continue\n    fi\n\n    # The line looks like this:\n    #/ace_root_path/ace/libACE.a(Malloc.o)\n    # need to find the real library path, since these libs will\n    # always be in ace/, but the objects will be in the original\n    # location.\n    lib=\"${line##/*/}\"    # strip off path, but only if it starts a line\n    lib=\"${lib%%.a*}\"     # strip off rest of line\n    lib=\"$lib.a\"          # put back the .a to make it unambiguous\n    libpath=`grep $lib ${DEST}/libraries.txt`\n    path=\"${libpath%___lib*}\"         # strip off libname\n    FILE=\"${line#*(}\"             # strip off everything up to object name\n    FILE=\"${FILE%%)*}\"            # strip off rest of line\n    FILE=\"${path}___${FILE}\"\n    echo -n \"$FILE \" >> ${DEST}/size_composites.txt\n  done\n\n  echo \"\" >> ${DEST}/size_composites.txt\n\n}\n\n###############################################################################\n#\n# create_size_composites\n#\n###############################################################################\ncreate_size_composites ()\n{\n  echo \"create_size_composites()\"\n  local FILE=\"\"\n\n  while read outfile colon infiles; do\n    # reconstitue file name\n    FILE=\"$BASE_ROOT/${outfile//___//}.map\"\n    if [ -e $FILE ]; then\n      echo -n \"$outfile : \" >> ${DEST}/size_composites.txt\n      # only process lines that don't begin with a space\n      cat $FILE | sed -e '/Memory Configuration/,$d' \\\n        | sed -e '/Allocating common symbols/,$d' \\\n        | grep -v \"^ \" | process_map_file $FILE\n    fi\n    #break\n  done\n\n}\n\n###############################################################################\n#\n# create_images\n#\n###############################################################################\ncreate_images ()\n{\n  echo \"create_images()\"\n\n  local DEST=$1\n  local TYPE=$2\n  local LOW=0\n  local HIGH=5000\n  local STEP=0\n  local TMP=0\n\n  while read object; do\n    if [ -e $object ] && [ `sort -t'/' -k1n -k2n -k3n $object | grep -E ^2 | tail -n 1 | cut -d' ' -f2` ]; then\n      let TMP=`sort -t'/' -k1n -k2n -k3n $object | grep -E ^2 | tail -n 1 | cut -d' ' -f2`\n      let TMP=$TMP*16/10\n      STEP=100\n      HIGH=0\n      while [ $HIGH -eq 0 ]; do\n        if [ $TMP -lt $STEP ]; then\n          HIGH=$STEP\n        fi\n        let STEP=$STEP*15/10\n      done\n\n      if [ \"$TYPE\" = \"Footprint\" ]; then\n        object=\"${object%.size}\"\n      else\n        object=\"${object%.txt}\"\n      fi\n\n      gen_chart \"${object##*/}\" ${DEST} ${TYPE} ${LOW} ${HIGH} >/dev/null 2>&1\n    fi\n  done\n\n}\n\n###############################################################################\n#\n# create_index_page\n#\n###############################################################################\ncreate_index_page ()\n{\n  local TYPE=\"$1\"\n  local TITLE=\"$TYPE metrics for $BASE_TITLE\"\n\n  echo \"<html>\"\n  echo \"<head><title>$TITLE</title></head>\"\n  echo '<style><!--'\n  echo 'body,td,a,p,.h{font-family:arial,sans-serif;}'\n  echo '.h{font-size: 20px;}'\n  echo '.q{text-decoration:none; color:#0000cc;}'\n  echo '//-->'\n  echo '</style>'\n  echo '<body text = \"#000000\" link=\"#000fff\" vlink=\"#ff0f0f\" bgcolor=\"#ffffff\">'\n  echo \"<br><center><h1>$TITLE</h1></center><br><hr>\"\n  if [ $BASE_TITLE = $DEFAULT_TITLE ]; then\n    echo '<p>We are measuring ACE+TAO+CIAO+DAnCE metrics daily.'\n  else\n    echo '<p>'\n  fi\n  echo '   Metrics are gathered nightly on all\n           objects in the '$BASE_TITLE' distribution and displayed here.'\n  echo '<ul>'\n  if [ $BASE_TITLE = $DEFAULT_TITLE ]; then\n    echo \"<li><a href=\\\"ace_${TYPE}.html\\\">ACE</a>\"\n    echo \"<li><a href=\\\"tao_${TYPE}.html\\\">TAO</a>\"\n    echo \"<li><a href=\\\"ciao_${TYPE}.html\\\">CIAO</a>\"\n    echo \"<li><a href=\\\"dance_${TYPE}.html\\\">DAnCE</a>\"\n  else\n    echo \"<li><a href=\\\"all_${TYPE}.html\\\">ALL</a>\"\n  fi\n  echo '</ul>'\n  echo '<hr>'\n\n  echo '<P>All the experiments run on the system described below. '\n  echo 'The machine is running Linux ('\n\n  if [ -e \"/etc/SuSE-release\" ]; then\n    cat /etc/SuSE-release\n  fi\n\n  if [ -e \"/etc/redhat-release\" ]; then\n    cat /etc/redhat-release\n  fi\n\n  echo \"), and we use \" $COMPILER \" version \"\n\n  $COMPILER -dumpversion > ${DEST}/compilerversion.txt 2>&1\n  cat ${DEST}/compilerversion.txt\n\n  echo ' to compile '$BASE_TITLE'. </P>'\n\n  if [ -z \"$MPC_ROOT\" ]; then\n    MPC_ROOT=$ACE_ROOT/MPC\n  fi\n\n  CFG_FILES=$ACE_ROOT/ace/config.h\n  if [ -r $ACE_ROOT/bin/MakeProjectCreator/config/default.features ]; then\n    CFG_FILES=\"$CFG_FILES $ACE_ROOT/bin/MakeProjectCreator/config/default.features\"\n  elif [ -r $MPC_ROOT/config/default.features ]; then\n    CFG_FILES=\"$CFG_FILES $MPC_ROOT/config/default.features\"\n  fi\n  CFG_FILES=\"$CFG_FILES $ACE_ROOT/include/makeinclude/platform_macros.GNU\"\n\n  echo '<TABLE border=\"2\"><TBODY>'\n  for cfg_file in $CFG_FILES; do\n    if [ -r $cfg_file ]; then\n      echo \"<TR><TD>ACE+TAO+CIAO+DAnCE Configuration</TD><TD>`basename $cfg_file`</TD></TR>\"\n      echo '<TR><TD colspan=\"2\"><PRE>'\n      cat $cfg_file\n      echo '</PRE></TD></TR>'\n    fi\n  done\n\n  echo '<TR><TD>CPU Information</TD><TD>/proc/cpuinfo</TD></TR>'\n  echo '<TR><TD colspan=\"2\"><PRE>'\n\n  cat /proc/cpuinfo\n\n  echo '</PRE></TD></TR><TR><TD>Available Memory</TD><TD>/proc/meminfo</TD></TR>'\n  echo '<TR><TD colspan=\"2\"><PRE>'\n\n  cat /proc/meminfo\n\n  echo '</PRE></TD></TR><TR><TD>OS Version</TD><TD>uname -a</TD></TR>'\n  echo '<TR><TD colspan=\"2\"><PRE>'\n\n  /bin/uname -a\n\n  echo '</PRE></TD></TR><TR><TD>Compiler Version</TD><TD>'$COMPILER' -v</TD></TR>'\n  echo '<TR><TD colspan=\"2\">'\n\n  $COMPILER -v > ${DEST}/compiler.txt 2>&1\n  cat ${DEST}/compiler.txt\n\n  if [ -e \"/lib/libc.so.6\" ]; then\n    echo '</TD></TR><TR><TD>Library Version</TD><TD>/lib/libc.so.6</TD></TR>'\n    echo '<TR><TD colspan=\"2\"><PRE>'\n\n    /lib/libc.so.6 | sed -e 's/</\\&lt;/g' -e 's/>/\\&gt;/g'\n  fi\n\n  echo '</PRE></TD></TR></TBODY></TABLE>'\n  echo '</body></html>'\n}\n\n###############################################################################\n#\n# create_page\n#\n###############################################################################\ncreate_page ()\n{\n  # always strip off \"ACE___\" / \"TAO___\" / \"CIAO___\"\n  local BASE=$1\n  local TYPE=$2\n  local EXT=\"\"\n  local BASE_NAME=${BASE#ACE___}\n  local BASE_NAME=${BASE#TAO___}\n  local BASE_NAME=${BASE#CIAO___}\n  local BASE_NAME=${BASE#DAnCE___}\n  local TITLE=\"${TYPE} metrics for ${BASE_NAME//___//}\"\n\n  if [ \"$TYPE\" = \"Compilation\" ]; then\n    EXT=\"txt\"\n    UNITS=\"100th's of seconds\"\n  else\n    EXT=\"size\"\n    UNITS=\"Bytes\"\n  fi\n\n  # header\n  echo \"<html>\"\n  echo \"<head><title>$TITLE</title></head>\"\n  echo '<style><!--'\n  echo 'body,td,a,p,.h{font-family:arial,sans-serif;}'\n  echo '.h{font-size: 20px;}'\n  echo '.q{text-decoration:none; color:#0000cc;}'\n  echo '//-->'\n  echo '</style>'\n  echo '<body text = \"#000000\" link=\"#000fff\" vlink=\"#ff0f0f\" bgcolor=\"#ffffff\">'\n  echo \"<br><center><h1>$TITLE</h1></center><br>\"\n  if [ -e \"${DEST}/images/${BASE}_${TYPE}.png\" ]; then\n    echo '<DIV align=\"center\"><P>'\n    echo \"<IMG alt=\\\"$BASE\\\" border=0 src=\\\"images/${BASE}_${TYPE}.png\\\"\"\n    echo 'width=\"800\" height=\"600\"></P></DIV>'\n  fi\n\n  echo \"<br><hr><br>\"\n  echo \"<center><h2>Detail (${DATE})</h2></center>\"\n\n  echo '<TABLE border=\"2\"><TBODY><TR><TD rowspan=2><b>Object</b></TD>'\n  echo '<TD colspan=\"4\" align=center><b>Last Compile</b></TD></TR>'\n  echo \"<TR><TD align=center><b>Date</b></TD><TD align=center><b>$UNITS</b></TD>\"\n  echo '<TD align=center><b>%chg</b></TD><TD align=center><b>Data</b></TD></TR>'\n  while read i; do\n    if [ -e \"${DEST}/data/${i}.${EXT}\" ]; then\n      LAST=0 PRE=0 VAL_TMP=0 VAL_INT=0 VAL_SIGN=\"+\"\n      echo '<TR><TD>'\n      if [ -e \"${DEST}/${i}_${TYPE}.html\" ]; then\n        # strip off \"ACE___\" if it exists\n        NAME=${i#ACE___}\n        # strip off \"TAO___\" if it exists\n        NAME=${i#TAO___}\n        # strip off \"CIAO___\" if it exists\n        NAME=${i#CIAO___}\n        # strip off \"DAnCE___\" if it exists\n        NAME=${i#DAnCE___}\n        echo \"<a href=\\\"${i}_${TYPE}.html\\\">${NAME//___//}</a>\"\n      elif [ -e \"${DEST}/images/${i}_${TYPE}.png\" ]; then\n        # since you'll only have images if it's a composite, strip off the\n        # path for the name\n        if [ \"$TYPE\" = \"Footprint\" ]; then\n          # if we are doing footprint, add library\n          llib=`grep -e \"lib.*\\.a\" ${DEST}/size_composites.txt | grep ${i} | awk '{print $1}'`\n          #echo \"lib $llib\"\n          #llib=\"${llib% :}\"\n          llib=\"${llib//___//}\"\n          NAME=\"${llib}(${i##*___})\"\n        else\n          NAME=\"${i##*___}\"\n        fi\n        echo \"<a href=\\\"images/${i}_${TYPE}.png\\\">${NAME}</a>\"\n      else\n        echo \"${i##*___}\"\n      fi\n      echo '</TD><TD>'\n      echo `sort -t'/' -k1n -k2n -k3n  ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n1  | cut -d\" \" -f1`\n      let LAST=`sort -t'/' -k1n -k2n -k3n ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n1 | cut -d\" \" -f2`\n      echo \"</TD><TD align=right>$LAST</TD>\"\n      let PRE=`sort -t'/' -k1n -k2n -k3n ${DEST}/data/${i}.${EXT} | grep -E ^2 | tail -n2 | head -n1 | cut -d\" \" -f2`\n      let VAL_TMP=\"((($LAST+1)-($PRE+1))*1000)/($PRE+1)\"\n      if [ $VAL_TMP -lt 0 ]; then\n        VAL_SIGN=\"-\"\n        let VAL_TMP=\"-1*$VAL_TMP\"\n      elif [ $VAL_TMP -eq 0 ]; then\n        VAL_SIGN=\n      fi\n      let VAL_INT=\"$VAL_TMP/10\"\n      let VAL_TENTH=\"$VAL_TMP-($VAL_INT*10)\"\n      echo \"<TD align=right>${VAL_SIGN}${VAL_INT}.${VAL_TENTH}</TD>\"\n      echo \"<TD align=right><a href=\\\"data/${i}.${EXT}\\\">Data</a></TD>\"\n      echo \"</TR>\"\n    else\n      echo '<TR><TD>'\n      echo \"${i}\"\n      echo '</TD><TD>'\n      echo '?'\n      echo \"</TD><TD align=right>?</TD>\"\n      echo \"<TD align=right>?</TD><TD align=right>?</TD></TR>\"\n    fi\n  done # for\n  echo '</TBODY></TABLE>'\n\n  # footer\n  echo '</body></html>'\n\n}\n\n###############################################################################\n#\n# sort_list\n#\n###############################################################################\nsort_list ()\n{\n  # sort the dependency files\n  if [ -e ${DEST}/tmp_list ]; then\n    rm ${DEST}/tmp_list\n  fi\n\n  touch ${DEST}/tmp_list\n  for i in $@; do\n    echo \"$i\" >> ${DEST}/tmp_list\n    #echo $i\n  done\n\n  sort -f ${DEST}/tmp_list\n}\n\n###############################################################################\n#\n# create_html\n#\n###############################################################################\ncreate_html ()\n{\n  echo \"create_html()\"\n\n  local DEST=$1\n  local TYPE=$2\n  local ALL_OBJS=\"\"\n  local ACE_OBJS=\"\"\n  local TAO_OBJS=\"\"\n  local CIAO_OBJS=\"\"\n  local DAnCE_OBJS=\"\"\n\n  while read base colon files; do\n    # create individual page for app/lib\n\n    sort_list ${files} | create_page ${base} ${TYPE} \\\n      > ${DEST}/${base}_${TYPE}.html\n    if [ \"${base}\" != \"${base#DAnCE}\" ]; then\n      DAnCE_OBJS=\"${DAnCE_OBJS} ${base}\"\n    elif [ \"${base}\" != \"${base#CIAO}\" ]; then\n      CIAO_OBJS=\"${CIAO_OBJS} ${base}\"\n    elif [ \"${base}\" != \"${base#TAO}\" ]; then\n      TAO_OBJS=\"${TAO_OBJS} ${base}\"\n    elif [ \"${base}\" != \"${base#ACE}\" ]; then\n      ACE_OBJS=\"${ACE_OBJS} ${base}\"\n    fi\n    ALL_OBJS=\"${ALL_OBJS} ${base}\"\n  done\n\n  # create main page\n  create_index_page ${TYPE} > ${DEST}/index.html\n\n  if [ \"${TYPE}\" = \"Compilation\" ] || [ \"${TYPE}\" = \"Footprint\" ]; then\n    if [ $BASE_TITLE = $DEFAULT_TITLE ]; then\n      name=\"ace_${TYPE}.html\"\n      sort_list ${ACE_OBJS} | create_page \"ACE\" ${TYPE} > ${DEST}/${name}\n\n      name=\"tao_${TYPE}.html\"\n      sort_list ${TAO_OBJS} | create_page \"TAO\" ${TYPE} > ${DEST}/${name}\n\n      name=\"ciao_${TYPE}.html\"\n      sort_list ${CIAO_OBJS} | create_page \"CIAO\" ${TYPE} > ${DEST}/${name}\n\n      name=\"dance_${TYPE}.html\"\n      sort_list ${DAnCE_OBJS} | create_page \"DAnCE\" ${TYPE} > ${DEST}/${name}\n    else\n      name=\"all_${TYPE}.html\"\n      sort_list ${ALL_OBJS} | create_page $BASE_TITLE ${TYPE} > ${DEST}/${name}\n    fi\n  fi\n}\n\n###############################################################################\n#\n# main program\n#\n###############################################################################\n\nINFILE=\"\"\nDEST=\"\"\nTARGETS=\"\"\nDATE=\"\"\nMETRIC=\"Compilation\"\nFUDGE_FACTOR=0\nBASE_ROOT=$ACE_ROOT\nDEFAULT_TITLE=ACE+TAO+CIAO+DAnCE\nBASE_TITLE=$DEFAULT_TITLE\nCOMPILER=\"gcc\"\n\nparse $@\ncreate_dirs \"${DEST}/\"\ncreate_dirs \"${DEST}/\"\n\nif [ \"$METRIC\" = \"Compilation\" ]; then\n\n  ########################################################\n  # compile times\n\n  # grab the compile time metrics for objects only and process them\n  grep \"compile time(0):\" $INFILE | grep \"\\.o\" | cut -d' ' -f3,4,5 | process_file\n\n  # Create ${DEST}/composites.txt with entries like this:\n  # tests___OS_Test :  tests___OS_Test.o tests___Main.o\n  create_composite_list $TARGETS\n\n  # compile times\n  cat ${DEST}/composites.txt | rollup_compile_times\n  find ${DEST}/data/ -name \"*.txt\" | create_images ${DEST} \"Compilation\"\n  cat ${DEST}/composites.txt | create_html ${DEST} \"Compilation\"\n\nelif [ \"$METRIC\" = \"Footprint\" ]; then\n\n  ########################################################\n  # footprint\n\n  # Create ${DEST}/libraries.txt with entries like this:\n  # ace___libACE.a\n  create_library_list $TARGETS\n\n  # Create ${DEST}/composites.txt with entries like this:\n  # tests___OS_Test :  tests___OS_Test.o tests___Main.o\n  create_composite_list $TARGETS\n\n  # Run size on the executables and append results to *.size file.\n  cat ${DEST}/composites.txt | footprint\n\n  # Run size on the libraries and append results to *.size for the\n  # library and each contained object.\n  # It also creates ${DEST}/size_composites.txt based on size output for\n  # libraries with entries like this:\n  # ace___libACE.a : ace___ACE.o ace___Addr.o\n  cat ${DEST}/libraries.txt | footprint LIB\n\n  # Add executables to ${DEST}/size_composites.txt based on output\n  # from the map files (created with LDFLAGS=-Xlinker -M -Xlinker\n  # -Map -Xlinker $(@).map).  Find the map files of we want based on\n  # entries in ${DEST}/composites.txt.\n  cat ${DEST}/composites.txt | create_size_composites\n\n  find ${DEST}/data/ -name \"*.size\" | create_images ${DEST} \"Footprint\"\n  cat ${DEST}/size_composites.txt | create_html ${DEST} \"Footprint\"\n\nelse\n  echo \"metric type ($METRIC) not recognized\"\n  usage\nfi\n", "num_lines": 1095}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\ngnuplot <<_EOF_ >/dev/null 2>&1\n  set xdata time\n  set xtics rotate\n  set timefmt '%Y/%m/%d-%H:%M'\n  set xlabel 'Date (MM/DD)'  0,-3\n  set ylabel 'Size (KBytes)'\n  set terminal png small size 1024,768 color\n  set output \"$2\"\n  plot '$1' using 1:(\\$2/1024.0) title '$3' w l\n  exit\n_EOF_\n\n", "num_lines": 16}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\ngnuplot <<_EOF_ >/dev/null 2>&1\n    set xdata time\n    set xtics rotate\n    set format x \"%Y/%m/%d\"\n    set timefmt '%Y/%m/%d-%H:%M'\n    set xlabel 'Date (YYYY/MM/DD)' 0,-3\n    set ylabel 'Throughput (Requests/Second)'\n    set terminal png small size $4 color\n    set yrange [0:]\n    set output \"$2\"\n    plot '$1' using 1:2 title '$3' w l\n    exit\n_EOF_\n", "num_lines": 17}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\ngnuplot <<_EOF_ >/dev/null 2>&1\n  set xdata time\n  set xtics rotate\n  set timefmt '%Y/%m/%d-%H:%M'\n  set xlabel 'Date (MM/DD)'\n  set ylabel 'Size (KBytes) $4'\n  set terminal png small size 800,600 color\n  set output \"$2\"\n  plot '$1' using 1:2 title '$3' w l\n  exit\n_EOF_\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -e tmp; then unlink tmp; fi\nif test -e tmp2; then unlink tmp2; fi\ncat t.txt | grep '+[a-z|A-Z]' > tmp\nsort tmp | uniq -c > tmp2\nunlink tmp\nsort -n -r tmp2 > uniq.txt\nunlink tmp2\ncat uniq.txt\n", "num_lines": 11}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif test -z $1; then CURRENTDATE=`date -u +%Y_%m_%d`; else CURRENTDATE=$1; fi\nif test -z $2; then PREFIX=`date -u +%Y%m%d%a`; else PREFIX=$2; fi\nif test -z $3; then MAILTO=\"devo-group@list.isis.vanderbilt.edu\"; else MAILTO=$3; fi\n\ncd $ACE_ROOT/bin\n\n./diff-builds-and-group-fixed-tests-only.sh $CURRENTDATE $PREFIX\n./cleanbuilds.sh $CURRENTDATE\n\nMAIL=\"mail -S smtp=mail.remedy.nl\"\nMAILFROM=\"jwillemsen@remedy.nl\"\n\nMAIL_ATTACHMENTS=\nfor fn in `ls *Tests.txt`; do\n   MAIL_ATTACHMENTS=$MAIL_ATTACHMENTS+\"-a $fn \"\ndone\nfor fn in `ls *NoTestRev.txt`; do\n   MAIL_ATTACHMENTS=$MAIL_ATTACHMENTS+\"-a $fn \"\ndone\nmailfile=\"/tmp/rsmailfile\"\n{\n   echo \"Sending test statistics for\" $CURRENTDATE\n   echo\n   cat *NoTestRev.txt\n   echo\n   echo \"Sending with revision number\"\n   cat *Tests.txt\n   echo\n   echo \"Sending results per build\"\n   cat *Builds.txt\n} > $mailfile\n\n$MAIL -v -r $MAILFROM -s \"ACE/TAO/CIAO/DAnCE test statistics for $CURRENTDATE\" $MAILTO < $mailfile\n\nrm -f $mailfile\n\nmailfile=\"/tmp/rsmailfile\"\n{\n   echo \"Sending failing tests for \" $CURRENTDATE\n   echo\n   cat cleanbuildresults.txt\n} > $mailfile\n\n$MAIL -v -r $MAILFROM -s \"ACE/TAO/CIAO/DAnCE failing tests for $CURRENTDATE\" $MAILTO < $mailfile\n\nrm -f $mailfile\n", "num_lines": 49}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\nif [ $# -lt 1 ]; then\n  echo \"Usage: $0 <DEST>\"\n  exit 0\nfi\n\nDEST=$1\nDATE=`date +%Y/%m/%d-%H:%M`\n\nmkdir -p $DEST/images\nmkdir -p $DEST/data\nmkdir -p $DEST/source\nCOMPILER=\"gcc\"\n\nCOMMON_TESTS=\"AMI DII DSI Deferred Single_Threaded Thread_Per_Connection Thread_Pool AMH_Single_Threaded\"\n\nSEQUENCE_TESTS=\"AMI DII DSI Deferred Single_Threaded Thread_Per_Connection Thread_Pool AMH_Single_Threaded\"\n\nSEQ_TEST_TYPE=\"octet long short char double longlong\"\n\ncd $DEST/source\n\n/bin/sync\nsleep 10\n(\n  cd $ACE_ROOT/performance-tests/TCP;\n  ./run_test.pl\n) >tcp_test.log 2>&1\n\nif grep -q 'Client throughput: ' tcp_test.log; then\n  (\n    echo -n $DATE \" \";\n    awk '/^Client throughput:/ {print $3}' tcp_test.log\n  ) >> TCP.txt;\nfi\n\n/bin/sync\nsleep 10\n(\n   cd $TAO_ROOT/performance-tests/Latency/Single_Threaded;\n   ./default_configuration.pl > $DEST/source/Default.log 2>&1\n)\nif grep -q 'Total throughput: ' Default.log; then\n  (\n    echo -n $DATE \" \";\n    awk '/^Total throughput:/ {print $3}' Default.log\n  ) >> Default.txt\nfi\n\n/bin/sync\nsleep 2\n(\n   cd $TAO_ROOT/performance-tests/Sequence_Latency/Single_Threaded;\n\n   for i in $SEQ_TEST_TYPE; do\n     (\n       ./default_configuration.pl -t $i > $DEST/source/Sequence_Default_${i}.log 2>&1\n       if grep -q 'Total throughput: ' $DEST/source/Sequence_Default_${i}.log; then\n         (\n           echo -n $DATE \" \";\n           awk '/^Total throughput:/ {print $3}' $DEST/source/Sequence_Default_${i}.log\n         ) >> $DEST/source/Sequence_Default_${i}.txt\n       fi\n     )\n   done\n\n)\n\nfor i in $COMMON_TESTS; do\n  /bin/sync\n  sleep 10\n  (\n     cd $TAO_ROOT/performance-tests/Latency/${i};\n     ./run_test.pl > $DEST/source/${i}.log 2>&1\n  )\n  if grep -q 'Total throughput: ' ${i}.log; then\n    (\n       echo -n $DATE \" \";\n       awk '/^Total throughput:/ {print $3}' $DEST/source/${i}.log\n    ) >> ${i}.txt\n  fi\ndone\n\nfor i in $SEQUENCE_TESTS; do\n  /bin/sync\n  sleep 10\n  (\n     cd $TAO_ROOT/performance-tests/Sequence_Latency/${i};\n     for j in $SEQ_TEST_TYPE; do\n         (\n             ./run_test.pl -t $j > $DEST/source/Sequence_${i}_${j}.log 2>&1\n\n             if grep -q 'Total throughput: ' $DEST/source/Sequence_${i}_${j}.log; then\n                 (\n                     echo -n $DATE \" \";\n                     awk '/^Total throughput:/ {print $3}' $DEST/source/Sequence_${i}_${j}.log\n                 ) >> $DEST/source/Sequence_${i}_${j}.txt\n             fi\n         )\n     done\n  )\n\ndone\n\nfor i in $COMMON_TESTS TCP Default; do\n  $ACE_ROOT/bin/generate_performance_chart.sh ${i}.txt ${i}.png \"$i\" 1024,768\n  /bin/cp ${i}.png $DEST/images/${i}.png\n  /usr/bin/tac ${i}.txt > $DEST/data/${i}.txt\n  /usr/bin/tail -5 ${i}.txt > $DEST/data/LAST_${i}.txt\ndone\n\nfor i in $SEQ_TEST_TYPE ; do\n  $ACE_ROOT/bin/generate_performance_chart.sh Sequence_Default_${i}.txt Sequence_Default_${i}.png \"Default Configuration for $i sequences\" 1024,768\n  /bin/cp Sequence_Default_${i}.png $DEST/images/Sequence_Default_${i}.png\n  /usr/bin/tac $DEST/source/Sequence_Default_${i}.txt > $DEST/data/Sequence_Default_${i}.txt\n  /usr/bin/tail -5 $DEST/source/Sequence_Default_${i}.txt > $DEST/data/LAST_Sequence_Default_${i}.txt\ndone\n\nfor i in $SEQUENCE_TESTS; do\nfor j in $SEQ_TEST_TYPE; do\n  $ACE_ROOT/bin/generate_performance_chart.sh Sequence_${i}_${j}.txt Sequence_${i}_${j}.png \"Sequence_$i_$j\" 1024,768\n  /bin/cp Sequence_${i}_${j}.png $DEST/images/Sequence_${i}_${j}.png\n  /usr/bin/tac Sequence_${i}_${j}.txt > $DEST/data/Sequence_${i}_${j}.txt\n  /usr/bin/tail -5 Sequence_${i}_${j}.txt > $DEST/data/LAST_Sequence_${i}_${j}.txt\ndone\ndone\n\ngnuplot <<_EOF_ >/dev/null 2>&1\n    set xdata time\n    set timefmt '%Y/%m/%d-%H:%M'\n    set xlabel 'Date (YYYYMMDD)'\n    set xtics rotate\n    set ylabel 'Throughput (Requests/Second)'\n    set yrange [0:]\n    set terminal png small size 1024,768 color\n    set output \"/dev/null\"\n    plot 'AMI.txt' using 1:2 title 'AMI' w l\n    replot 'DII.txt' using 1:2 title 'DII' w l\n    replot 'DSI.txt' using 1:2 title 'DSI' w l\n    replot 'Deferred.txt' using 1:2 title 'Deferred' w l\n    replot 'Single_Threaded.txt' using 1:2 title 'Single_Threaded' w l\n    replot 'Default.txt' using 1:2 title 'Single_Threaded (Defaults)' w l\n    replot 'Thread_Per_Connection.txt' using 1:2 title 'Thread_Per_Connection' w l\n    replot 'Thread_Pool.txt' using 1:2 title 'Thread_Pool' w l\n    replot 'AMH_Single_Threaded.txt' using 1:2 title 'AMH' w l\n    replot 'TCP.txt' using 1:2 title 'TCP/IP' w l\n    set output \"All.png\"\n    replot\n    exit\n_EOF_\n\ngnuplot <<_EOF_ >/dev/null 2>&1\n    set xdata time\n    set timefmt '%Y/%m/%d-%H:%M'\n    set xlabel 'Date (YYYYMMDD)'\n    set xtics rotate\n    set ylabel 'Throughput (Requests/Second)'\n    set yrange [0:]\n    set terminal png small size 1024,768 color\n    set output \"/dev/null\"\n    plot 'AMI.txt' using 1:2 title 'AMI' w l\n    replot 'DII.txt' using 1:2 title 'DII' w l\n    replot 'DSI.txt' using 1:2 title 'DSI' w l\n    replot 'Deferred.txt' using 1:2 title 'Deferred' w l\n    replot 'Single_Threaded.txt' using 1:2 title 'Single_Threaded' w l\n    replot 'Default.txt' using 1:2 title 'Single_Threaded (Defaults)' w l\n    replot 'Thread_Per_Connection.txt' using 1:2 title 'Thread_Per_Connection' w l\n    replot 'Thread_Pool.txt' using 1:2 title 'Thread_Pool' w l\n    replot 'AMH_Single_Threaded.txt' using 1:2 title 'AMH' w l\n    set output \"CORBA.png\"\n    replot\n    exit\n_EOF_\n\n/bin/cp CORBA.png All.png $DEST/images/\n\ncd $DEST/data\n/bin/uname -a > uname.txt\n$COMPILER -v > gcc.txt 2>&1\n$COMPILER -dumpversion > gccversion.txt 2>&1\n/lib/libc.so.6 | sed -e 's/</\\&lt;/g' -e 's/>/\\&gt;/g' > libc.txt\ncat /proc/cpuinfo > cpuinfo.txt\ncat /proc/meminfo > meminfo.txt\nif [ -e \"/etc/SuSE-release\" ]; then\n  cat /etc/SuSE-release > linuxversion.txt\nfi\nif [ -e \"/etc/redhat-release\" ]; then\n  cat /etc/redhat-release > linuxversion.txt\nfi\nif [ -e \"/etc/fedora-release\" ]; then\n  cat /etc/fedora-release > linuxversion.txt\nfi\n\ncat $ACE_ROOT/ace/config.h > config.h.txt\ncat $ACE_ROOT/include/makeinclude/platform_macros.GNU > platform_macros.GNU.txt\ncat $ACE_ROOT/bin/MakeProjectCreator/config/default.features > default.features.txt\ncp $ACE_ROOT/html/Stats/* $DEST\n", "num_lines": 200}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\nif [ $# -lt 3 ]; then\n  echo \"Usage: $0 [DEST] [USER] [OPTIMIZED]\"\n  exit 0\nfi\n\nDEST=$1\nUS=$2\nOPT=$3\n\nDATE=`date +%Y/%m/%d-%H:%M`\ncd $ACE_ROOT\nLD_LIBRARY_PATH=$ACE_ROOT/ace\nexport LD_LIBRARY_PATH\nPATH=/usr/bin:/bin:$PATH\nexport PATH\ncd $TAO_ROOT/performance-tests/Memory/IORsize\n\n# start the server. If OPT == 1 then start the optimized version, else\n# the non-optimized version\n\nif test $OPT == 1\n    then ./server -ORBSvcConf server.conf &\n    else ./server &\nfi\n\ns_id=$!;\n\nserver_start_size=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;\n\n# Just sleep for 2 seconds.\nsleep 2;\n# Check whether the server has started\nfile=\"test.ior\"\nif test -f $file\n    then\n    # start the client\n    ./client &\n    c_id=$!;\n    # Wait till all the invocations are done\n    sleep 30;\n    # Get the size once the client has made sufficient invocations.\n    s_invocations=`cat /proc/$s_id/status  | grep VmRSS | awk '{print $2}'`;\n    let \"actual_server_growth=${s_invocations}-${server_start_size}\";\n    if test $OPT == 1\n        then\n        echo $DATE $s_invocations >> $DEST/source/server_opt_ior_size.txt\n        echo $DATE $actual_server_growth >> $DEST/source/opt_ior_size.txt\n        else\n        echo $DATE $s_invocations >> $DEST/source/server_ior_size.txt\n        echo $DATE $actual_server_growth >> $DEST/source/actual_ior_size.txt\n    fi\n\n    # Kill the server and client. We will look at better ways of doing\n    # this later.\n    kill -9 $c_id;\n    kill -9 $s_id;\n    rm -f $file\nelse\n    echo $file doesnt exist\nfi\n\n\ncd $DEST/source\nSTRING=\"for 50000 IORs\"\nFILES=\"server_opt opt server actual\"\nfor i in $FILES ; do\n/usr/bin/tac ${i}_ior_size.txt > $DEST/data/${i}_ior_size.txt\n/usr/bin/tail -5 ${i}_ior_size.txt > $DEST/data/LAST_${i}_ior_size.txt\n$ACE_ROOT/bin/generate_topinfo_charts.sh ${i}_ior_size.txt $DEST/images/${i}_ior_size.png ${i}_ior_size.txt\ndone\n", "num_lines": 74}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\n\nif [ $# -lt 2 ]; then\n  echo \"Usage: $0 [DEST] [USER]\"\n  exit 0\nfi\n\nDEST=$1\nUS=$2\n\nDATE=`date +%Y/%m/%d-%H:%M`\ncd $ACE_ROOT\nLD_LIBRARY_PATH=$ACE_ROOT/ace\nexport LD_LIBRARY_PATH\nPATH=/usr/bin:/bin:$PATH\nexport PATH\ncd $TAO_ROOT/performance-tests/Memory/Single_Threaded\n# start the server\n./server &\ns_id=$!;\n# Just sleep for 2 seconds.\nsleep 2;\n# Check whether the server has started\nfile=\"test.ior\"\nif test -f $file\n    then\n    # Just get the size as soon the server is started, ie. the vanilla\n    # server.\n    s_up=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;\n\n    # Write it a file\n    echo $DATE $s_up >> $DEST/source/st_start_size.txt\n    # start the client\n    ./client &\n    c_id=$!;\n    # Wait till all the invocations are done\n    sleep 10;\n    # Get the size once the client has made sufficient invocations.\n    s_invocations=`cat /proc/$s_id/status | grep VmRSS| awk '{print $2}'`;\n\n    echo $DATE $s_invocations >> $DEST/source/st_after_invoke_size.txt\n\n    # Get teh size of the client after all the invocations\n    c_invocations=`cat /proc/$c_id/status | grep VmRSS | awk '{print $2}'`;\n    echo $DATE $c_invocations >> $DEST/source/st_client_size.txt\n\n    # Kill the server and client. We will look at better ways of doing\n    # this later.\n    kill -9 $c_id;\n\n    # Just sleep for the server to release memory etc.\n    sleep 5;\n\n    # Get the size once the client is killed or crashed\n    s_client_death=`cat /proc/$s_id/status | grep VmRSS | awk '{print $2}'`;\n    echo $DATE $s_client_death  >> $DEST/source/st_after_peer_death_size.txt\n    kill -9 $s_id;\n    rm -f $file\nelse\n    echo $file doesnt exist\nfi\n\n\ncd $DEST/source\n\nFILES=\"start after_invoke client after_peer_death\"\nfor i in $FILES ; do\n/usr/bin/tac st_${i}_size.txt > $DEST/data/st_${i}_size.txt\n/usr/bin/tail -5 st_${i}_size.txt > $DEST/data/LAST_st_${i}_size.txt\n$ACE_ROOT/bin/generate_topinfo_charts.sh st_${i}_size.txt $DEST/images/st_${i}_size.png st_${i}_size.txt\ndone\n", "num_lines": 74}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\n\nif [ $# -lt 2 ]; then\n  echo \"Usage: $0 [DEST] [USER]\"\n  exit 0\nfi\n\nDEST=$1\nUS=$2\n\nDATE=`date +%Y/%m/%d-%H:%M`\ncd $ACE_ROOT\nLD_LIBRARY_PATH=$ACE_ROOT/ace\nexport LD_LIBRARY_PATH\nPATH=/usr/bin:$PATH\nexport PATH\ncd $TAO_ROOT/performance-tests/Memory/Single_Threaded\n# start the server\n./server &\ns_id=$!;\n# Just sleep for 2 seconds.\nsleep 2;\n# Check whether the server has started\nfile=\"test.ior\"\nif test -f $file\n    then\n    # Just get the size as soon the server is started, ie. the vanilla\n    # server.\n    s_up=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;\n\n    # Write it a file\n    echo $DATE $s_up >> $DEST/source/st_start_size.txt\n    # start the client\n    ./client &\n    c_id=$!;\n    # Wait till all the invocations are done\n    sleep 10;\n    # Get the size once the client has made sufficient invocations.\n    s_invocations=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;\n\n    echo $DATE $s_invocations >> $DEST/source/st_after_invoke_size.txt\n\n    # Kill the server and client. We will look at better ways of doing\n    # this later.\n    kill -9 $c_id;\n\n    # Just sleep for the server to release memory etc.\n    sleep 5;\n\n    # Get the size once the client is killed or crashed\n    s_client_death=`top -p $s_id -n 1 -b | grep $US| awk '{print $5}'`;\n    echo $DATE $s_client_death  >> $DEST/source/st_after_peer_death_size.txt\n    kill -9 $s_id;\n    rm -f $file\nelse\n    echo $file doesnt exist\nfi\n\n\ncd $DEST/source\nSTRING=\"\"\nFILES=\"start after_invoke after_peer_death\"\nfor i in $FILES ; do\n/usr/bin/tac st_${i}_size.txt > $DEST/data/st_${i}_size.txt\n/usr/bin/tail -5 st_${i}_size.txt > $DEST/data/LAST_st_${i}_size.txt\n$ACE_ROOT/bin/generate_topinfo_charts.sh st_${i}_size.txt $DEST/images/st_${i}_size.png st_${i}_size.txt $STRING\ndone\n", "num_lines": 70}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# This script compares autoconf-based installation against regular builds\n# provided files.\n#\n# This script should be run after `make install DESTDIR=debian/tmp' has been\n# run on autoconf-based build.\n#\n\nset -e\n\nP1=ACE_wrappers\nP2=debian/tmp/usr/include\n\n# Find files\n# ff <from>\nff() {\n  find \"$1\" -name '*.h' -o -name '*.inl' -o -name '*.hpp' -o -name '*.ipp'\n}\n\n# Remove path with examples, tests and tutorial from STDIN\ndrop() {\n  grep -E -v '(examples|tests|tutorials)/'\n}\n\n# Removed unused/unshipped stuff\nunused() {\n  grep -E -v '^/(ASNMP|TAO_IDL|ace/QoS|apps|contrib|utils)'\n}\n\nF1=`mktemp -t ace_regular.XXXXXXXXXX`\nF2=`mktemp -t ace_autoconf.XXXXXXXXXX`\ntrap \"rm $F1 $F2\" 0\n\nff $P1 | sed -e \"s@$P1@@\" -e \"s@/TAO@@\" -e \"s@/protocols@@\" -e \"s@^/orbsvcs@@\" | drop | unused | sort >> $F1\nff $P2 | sed -e \"s@$P2@@\" | sort >> $F2\ndiff -u $F1 $F2\n", "num_lines": 38}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# This script regenerates changes on the Doxygen templates.\n#\nsilent_nothing_to_do() {\n    test $? -eq 2 || false\n}\n\nset -e\nexport QUILT_PATCHES=debian/patches\n\nquilt pop -a || silent_nothing_to_do\nquilt delete reduce-doxygen-doc.diff\nquilt new reduce-doxygen-doc.diff\n\nfor f in $(find $ACE_ROOT -name '*.doxygen')\ndo\n    QUILT_PATCHES=debian/patches quilt add $f\n    sed -e 's#COLLABORATION_GRAPH    = YES#COLLABORATION_GRAPH    = NO#' \\\n        -e 's#SEARCHENGINE           = YES#SEARCHENGINE           = NO#' \\\n        -e 's#DOT_GRAPH_MAX_NODES    = 50#DOT_GRAPH_MAX_NODES     = 15#' \\\n< $f > $f.new\n\n    mv $f.new $f\ndone\n\nquilt refresh --no-timestamps --no-index\n", "num_lines": 28}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n#\n# Spawns CPP-inserver-fancy and CPP-inclient executables on a single host.\n\nusage=\"usage: $0 #client_threads\"\n\nuser=`whoami`\niterations=1000\n\nif [ $# -ne 1 ]; then\n  echo $usage;\n  exit 1\nfi\nthreads=$1;\n\n\n########\n######## Enable signal handler.\n########\ntrap 'kill -1 $server_pid; ' 0 1 2 15\n\n\n########\n######## Start CPP-inserver-fancy and save its pid.\n########\n./CPP-inserver-fancy > \\\n  ${tmp}server.log 2>&1 &\nserver_pid=$!\n\nsleep 2;\n\n########\n######## Start CPP-inclient.\n########\n./CPP-inclient -2 -T 100000 -m 69 -t $threads -i 100  > ${tmp}client-${threads}.log 2>&1\n", "num_lines": 36}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# ******************************************************************\n#      Author: Chad Elliott\n#        Date: 8/13/2009\n# Description: Create an MPC rpm based on the current version number.\n# ******************************************************************\n\n## First find out where this script is located\nif [ \"$0\" != \"`basename $0`\" ]; then\n  if [ \"`echo $0 | cut -c1`\" = \"/\" ]; then\n    loc=\"`dirname $0`\"\n  else\n    loc=\"`pwd`/`dirname $0`\"\n  fi\nelse\n  ## Do my own 'which' here\n  loc=\".\"\n  for i in `echo $PATH | tr ':' '\\012'`; do\n    if [ -x \"$i/$0\" -a ! -d \"$i/$0\" ]; then\n      loc=\"$i\"\n      break\n    fi\n  done\nfi\n\n## Now, get back to where the main MPC script is located\nwhile [ ! -x $loc/mpc.pl ]; do\n  loc=`dirname $loc`\ndone\n\n## Build up the packager name and email address\nif [ -z \"$REPLYTO\" ]; then\n  DOMAIN=`hostname | sed 's/[^\\.][^\\.]*\\.//'`\n  FULLDOMAIN=`echo $DOMAIN | grep '\\.'`\n  if [ -z \"$DOMAIN\" -o -z \"$FULLDOMAIN\" ]; then\n    RESOLVDOMAIN=`grep '^search' /etc/resolv.conf | sed 's/.*\\s//'`\n    FULLDOMAIN=`echo $RESOLVDOMAIN | grep '\\.'`\n    if [ -z \"$DOMAIN\" -o -n \"$FULLDOMAIN\" ]; then\n      DOMAIN=$RESOLVDOMAIN\n    fi\n  fi\n  REPLYTO=\"$LOGNAME@$DOMAIN\"\nfi\nPACKAGER=`getent passwd $LOGNAME | cut -d: -f5`\nif [ -z \"$PACKAGER\" ]; then\n  PACKAGER=$CL_USERNAME\nfi\nif [ -z \"$PACKAGER\" ]; then\n  PACKAGER=\"<$REPLYTO>\"\nelse\n  PACKAGER=\"$PACKAGER <$REPLYTO>\"\nfi\n\n## Save the MPC version\nVERSION=`$loc/mpc.pl --version | sed 's/.*v//'`\n\n## This is where we'll create the spec file and do the work\nWDIR=/tmp/mpc.$$\n\n## This is the directory name that RPM expects\nMDIR=MPC-$VERSION\n\n## This corresponds to BuildRoot in MPC.spec\nBDIR=/tmp/mpc\n\n## This is the final install directory and corresponds to the %files section\n## of MPC.spec\nFDIR=/usr/lib/MPC\n\n##Check if build and work directory already exist\nif [ -d \"$BDIR\" -o -f \"$BDIR\" ]; then\n  echo \"Necessary directory $BDIR already exists.\"\n  echo \"Exiting.\"\n  exit\nfi\n\nif [ -d \"$WDIR\" -o -f \"$WDIR\" ]; then\n  echo \"Necessary directory $WDIR already exists.\"\n  echo \"Exiting.\"\n  exit\nfi\n\n## Create our working directory\nmkdir -p $WDIR\n\n## The directory where RPM will place the resulting file\nif [ -x /usr/src/redhat -a -w /usr/src/redhat ]; then\n  RPMLOC=/usr/src/redhat\nelif [ -x /usr/src/packages -a -w /usr/src/packages ]; then\n  RPMLOC=/usr/src/packages\nelse\n  RPMLOC=$WDIR/rpmbuild\n  mkdir -p $RPMLOC\n  mkdir -p $RPMLOC/BUILD\n  mkdir -p $RPMLOC/RPMS\n  mkdir -p $RPMLOC/SOURCES\nfi\n\n## Make the spec file\ncd $WDIR\nsed \"s/VERSION/$VERSION/; s/PACKAGER/$PACKAGER/; s!FINALDIR!$FDIR!\" $loc/rpm/MPC.templ > MPC.spec\n\n## Make a copy of the original MPC source to the new directory\nmkdir -p $MDIR/$FDIR\ncd $loc\ntar --exclude=.svn -cf - . | (cd $WDIR/$MDIR/$FDIR; tar -xf -)\n\n## Create the build source tar.bz2\ncd $WDIR\ntar --owner root --group root -cf $RPMLOC/SOURCES/$MDIR.tar $MDIR\nbzip2 -9f $RPMLOC/SOURCES/$MDIR.tar\n\n## Perform the RPM creation step\nrm -rf $BDIR\nmkdir -p $BDIR\nrpmbuild --define \"_topdir $RPMLOC\" --define \"_buildrootdir $BDIR\" --define \"buildroot $BDIR\" --define \"__arch_install_post %{nil}\" -bb MPC.spec\n\nif [ \"$RPMLOC\" = \"$WDIR/rpmbuild\" ]; then\n  echo \"Copying rpm to $loc/rpm\"\n  cp $RPMLOC/RPMS/*/*.rpm $loc/rpm\nfi\n\n## Clean everything up\ncd ..\nrm -rf $WDIR $BDIR\n", "num_lines": 127}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n\nfor s in 0 25 50 75 100; do\n  for w in 1 2 3 4 5 6; do\n    echo ================ WORK: $s 1>&2\n    echo ================ THREADS: $w 1>&2\n    ./Queue_Based_Workers/workers -m 100000 -b 100000 -s $s -w $w\n    ./Leader_Follower/leader_follower -m 100000 -b 100000 -s $s -w $w\n  done\ndone\n", "num_lines": 12}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2019-2021 Ren\u00c3\u00a9 Ferdinand Rivera Morell\n# Copyright (C) 2005, 2006 Douglas Gregor.\n# Copyright (C) 2006 The Trustees of Indiana University\n#\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n# boostinspect:notab - Tabs are required for the Makefile.\n\nBJAM=\"\"\nTOOLSET=\"\"\nBJAM_CONFIG=\"\"\nBUILD=\"\"\nPREFIX=/usr/local\nEPREFIX=\nLIBDIR=\nINCLUDEDIR=\nLIBS=\"\"\nPYTHON=python\nPYTHON_VERSION=\nPYTHON_ROOT=\nICU_ROOT=\n\n# Handle case where builtin shell version of echo command doesn't \n# support -n.  Use the installed echo executable if there is one \n# rather than builtin version to ensure -n is supported.\nECHO=`which echo`\nif test \"x$ECHO\" = x; then\n  ECHO=echo\nfi\n\n# Internal flags\nflag_no_python=\nflag_icu=\nflag_show_libraries=\n\nfor option\ndo\n    case $option in\n\n    -help | --help | -h)\n      want_help=yes ;;\n\n    -prefix=* | --prefix=*)\n      PREFIX=`expr \"x$option\" : \"x-*prefix=\\(.*\\)\"`\n      ;;\n\n    -exec-prefix=* | --exec-prefix=*)\n      EPREFIX=`expr \"x$option\" : \"x-*exec-prefix=\\(.*\\)\"`\n      ;;\n\n    -libdir=* | --libdir=*)\n      LIBDIR=`expr \"x$option\" : \"x-*libdir=\\(.*\\)\"`\n      ;;\n\n    -includedir=* | --includedir=*)\n      INCLUDEDIR=`expr \"x$option\" : \"x-*includedir=\\(.*\\)\"`\n      ;;\n\n    -show-libraries | --show-libraries )\n      flag_show_libraries=yes\n      ;;\n\n    -with-bjam=* | --with-bjam=* )\n      BJAM=`expr \"x$option\" : \"x-*with-bjam=\\(.*\\)\"`\n      ;;\n\n    -with-icu | --with-icu )\n      flag_icu=yes\n      ;;\n\n    -with-icu=* | --with-icu=* )\n      flag_icu=yes\n      ICU_ROOT=`expr \"x$option\" : \"x-*with-icu=\\(.*\\)\"`\n      ;;\n\n    -without-icu | --without-icu )\n      flag_icu=no\n      ;;\n\n    -with-libraries=* | --with-libraries=* )\n      library_list=`expr \"x$option\" : \"x-*with-libraries=\\(.*\\)\"`\n      if test \"$library_list\" != \"all\"; then\n          old_IFS=$IFS\n          IFS=,\n          for library in $library_list\n          do\n              LIBS=\"$LIBS --with-$library\"\n\n              if test $library = python; then\n                  requested_python=yes\n              fi\n          done\n          IFS=$old_IFS\n\n          if test \"x$requested_python\" != xyes; then\n              flag_no_python=yes\n          fi\n      fi\n      ;;\n\n    -without-libraries=* | --without-libraries=* )\n      library_list=`expr \"x$option\" : \"x-*without-libraries=\\(.*\\)\"`\n      old_IFS=$IFS\n      IFS=,\n      for library in $library_list\n      do\n          LIBS=\"$LIBS --without-$library\"\n\n          if test $library = python; then\n              flag_no_python=yes\n          fi\n      done\n      IFS=$old_IFS\n      ;;\n\n    -with-python=* | --with-python=* )\n      PYTHON=`expr \"x$option\" : \"x-*with-python=\\(.*\\)\"`\n      ;;\n\n    -with-python-root=* | --with-python-root=* )\n      PYTHON_ROOT=`expr \"x$option\" : \"x-*with-python-root=\\(.*\\)\"`\n      ;;\n\n    -with-python-version=* | --with-python-version=* )\n      PYTHON_VERSION=`expr \"x$option\" : \"x-*with-python-version=\\(.*\\)\"`\n      ;;\n\n    -with-toolset=* | --with-toolset=* )\n      TOOLSET=`expr \"x$option\" : \"x-*with-toolset=\\(.*\\)\"`\n      ;;\n\n    -*)\n      { echo \"error: unrecognized option: $option\nTry \\`$0 --help' for more information.\" >&2\n      { (exit 1); exit 1; }; }\n      ;; \n\n    esac\ndone\n\nif test \"x$want_help\" = xyes; then\n  cat <<EOF\n\\`./bootstrap.sh\\' builds the Boost build system B2 and prepares Boost for\nbuilding. This includes setting defaults in the project-config.jam which you\ncan adjust prior to invoking B2.\n\nUsage: $0 [OPTION]... \n\nDefaults for the options are specified in brackets.\n\nConfiguration:\n  -h, --help                display this help and exit\n  --with-bjam=BJAM          use existing Boost.Jam executable (bjam)\n                            [automatically built]\n  --with-toolset=TOOLSET    use specific TOOLSET to build B2 and as default\n                            for building Boost\n                            [automatically detected]\n  --show-libraries          show the set of libraries that require build\n                            and installation steps (i.e., those libraries\n                            that can be used with --with-libraries or\n                            --without-libraries), then exit\n  --with-libraries=list     build only a particular set of libraries,\n                            describing using either a comma-separated list of\n                            library names or \"all\"\n                            [all]\n  --without-libraries=list  build all libraries except the ones listed []\n  --with-icu                enable Unicode/ICU support in Regex \n                            [automatically detected]\n  --without-icu             disable Unicode/ICU support in Regex\n  --with-icu=DIR            specify the root of the ICU library installation\n                            and enable Unicode/ICU support in Regex\n                            [automatically detected]\n  --with-python=PYTHON      specify the Python executable [python]\n  --with-python-root=DIR    specify the root of the Python installation\n                            [automatically detected]\n  --with-python-version=X.Y specify the Python version as X.Y\n                            [automatically detected]\n\nInstallation directories:\n  --prefix=PREFIX           install Boost into the given PREFIX\n                            [/usr/local]\n  --exec-prefix=EPREFIX     install Boost binaries into the given EPREFIX\n                            [PREFIX]\n\nMore precise control over installation directories:\n  --libdir=DIR              install libraries here [EPREFIX/lib]\n  --includedir=DIR          install headers here [PREFIX/include]\n\nEOF\nfi\ntest -n \"$want_help\" && exit 0\n\nmy_dir=$(dirname \"$0\")\n\n# Determine the toolset, if not already decided\nif test \"x$TOOLSET\" = x; then\n  guessed_toolset=`CXX= CXXFLAGS= $my_dir/tools/build/src/engine/build.sh --guess-toolset`\n  case $guessed_toolset in\n    acc | clang | gcc | como | mipspro | pathscale | pgi | qcc | vacpp )\n    TOOLSET=$guessed_toolset\n    ;;\n    \n    intel-* )\n    TOOLSET=intel\n    ;;\n    \n    mingw )\n    TOOLSET=gcc\n    ;;\n    \n    sun* )\n    TOOLSET=sun\n    ;;\n    \n    * )\n    # Not supported by B2\n    ;;\n  esac\nfi\n\nrm -f config.log\n\n# Build bjam\nif test \"x$BJAM\" = x; then\n  $ECHO \"Building B2 engine..\"\n  pwd=`pwd`\n  CXX= CXXFLAGS= \"$my_dir/tools/build/src/engine/build.sh\" ${TOOLSET}\n  if [ $? -ne 0 ]; then\n      echo\n      echo \"Failed to build B2 build engine\"\n      exit 1\n  fi\n  cd \"$pwd\"\n  BJAM=\"$my_dir/tools/build/src/engine/b2\"\n  echo \"tools/build/src/engine/b2\"\n  cp \"$BJAM\" .\n\nfi\n\n# TBD: Turn BJAM into an absolute path\n\n# If there is a list of libraries \nif test \"x$flag_show_libraries\" = xyes; then\n  cat <<EOF\n\nThe following Boost libraries have portions that require a separate build\nand installation step. Any library not listed here can be used by including\nthe headers only.\n\nThe Boost libraries requiring separate building and installation are:\nEOF\n  $BJAM -d0 --show-libraries | grep '^[[:space:]]*-'\n  exit 0\nfi\n\n# Setup paths\nif test \"x$EPREFIX\" = x; then\n  EPREFIX=\"$PREFIX\"\nfi\n\nif test \"x$LIBDIR\" = x; then\n  LIBDIR=\"$EPREFIX/lib\"\nfi\n\nif test \"x$INCLUDEDIR\" = x; then\n  INCLUDEDIR=\"$PREFIX/include\"\nfi\n\n# Find Python\nif test \"x$flag_no_python\" = x; then\n  result=`$PYTHON -c \"exit\" > /dev/null 2>&1`\n  if [ \"$?\" -ne \"0\" ]; then\n    flag_no_python=yes\n  fi\nfi\n\nif test \"x$flag_no_python\" = x; then\n    if test \"x$PYTHON_VERSION\" = x; then\n        $ECHO -n \"Detecting Python version... \"\n        PYTHON_VERSION=`$PYTHON -c \"import sys; print (\\\"%d.%d\\\" % (sys.version_info[0], sys.version_info[1]))\"`\n        echo $PYTHON_VERSION\n    fi\n\n    if test \"x$PYTHON_ROOT\" = x; then\n        $ECHO -n \"Detecting Python root... \"\n        PYTHON_ROOT=`$PYTHON -c \"import sys; print(sys.prefix)\"`\n        echo $PYTHON_ROOT\n    fi    \nfi\n\n# Configure ICU\n$ECHO -n \"Unicode/ICU support for Boost.Regex?... \"\nif test \"x$flag_icu\" != xno; then\n  if test \"x$ICU_ROOT\" = x; then\n    if command -v pkg-config > /dev/null && pkg-config icu-uc ; then\n      ICU_ROOT=`pkg-config --variable=prefix icu-uc`\n    fi\n  fi\n  if test \"x$ICU_ROOT\" = x; then\n    COMMON_ICU_PATHS=\"/usr /usr/local /sw\"\n    for p in $COMMON_ICU_PATHS; do\n      if test -r $p/include/unicode/utypes.h; then\n        ICU_ROOT=$p\n      fi\n    done\n  \n    if test \"x$ICU_ROOT\" = x; then\n      echo \"not found.\"\n    else      \n      BJAM_CONFIG=\"$BJAM_CONFIG -sICU_PATH=$ICU_ROOT\"\n      echo \"$ICU_ROOT\"\n    fi\n  else\n    BJAM_CONFIG=\"$BJAM_CONFIG -sICU_PATH=$ICU_ROOT\"\n    echo \"$ICU_ROOT\"\n  fi\nelse\n  echo \"disabled.\"\nfi\n\n# Backup the user's existing project-config.jam\nJAM_CONFIG_OUT=\"project-config.jam\"\nif test -r \"project-config.jam\"; then\n  counter=1\n \n  while test -r \"project-config.jam.$counter\"; do\n    counter=`expr $counter + 1`\n  done\n\n  echo \"Backing up existing B2 configuration in project-config.jam.$counter\"\n  mv \"project-config.jam\" \"project-config.jam.$counter\"\nfi\n\n# Generate user-config.jam\necho \"Generating B2 configuration in project-config.jam for $TOOLSET...\"\ncat > project-config.jam <<EOF\n# B2 Configuration\n# Automatically generated by bootstrap.sh\n\nimport option ;\nimport feature ;\n\n# Compiler configuration. This definition will be used unless\n# you already have defined some toolsets in your user-config.jam\n# file.\nif ! $TOOLSET in [ feature.values <toolset> ]\n{\n    using $TOOLSET ; \n}\n\nproject : default-build <toolset>$TOOLSET ;\nEOF\n\n#  - Python configuration\nif test \"x$flag_no_python\" = x; then\n  cat >> project-config.jam <<EOF\n\n# Python configuration\nimport python ;\nif ! [ python.configured ]\n{\n    using python : $PYTHON_VERSION : \"$PYTHON_ROOT\" ;\n}\nEOF\nfi\n\nif test \"x$ICU_ROOT\" != x; then\n  cat >> project-config.jam << EOF\n\npath-constant ICU_PATH : $ICU_ROOT ;\n\nEOF\nfi\n\ncat >> project-config.jam << EOF\n\n# List of --with-<library> and --without-<library>\n# options. If left empty, all libraries will be built.\n# Options specified on the command line completely\n# override this variable.\nlibraries = $LIBS ;\n\n# These settings are equivalent to corresponding command-line\n# options.\noption.set prefix : $PREFIX ;\noption.set exec-prefix : $EPREFIX ;\noption.set libdir : $LIBDIR ;\noption.set includedir : $INCLUDEDIR ;\n\n# Stop on first error\noption.set keep-going : false ;\nEOF\n\ncat << EOF\n\nBootstrapping is done. To build, run:\n\n    ./b2\n    \nTo generate header files, run:\n\n    ./b2 headers\n\nThe configuration generated uses ${TOOLSET} to build by default. If that is\nunintended either use the --with-toolset option or adjust configuration, by\nediting 'project-config.jam'.\n\nFurther information:\n\n   - Command line help:\n     ./b2 --help\n     \n   - Getting started guide: \n     http://www.boost.org/more/getting_started/unix-variants.html\n     \n   - B2 documentation:\n     http://www.boost.org/build/\n\nEOF\n", "num_lines": 422}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (C) 2000 Stephen Cleary\n#\n# Distributed under the Boost Software License, Version 1.0. (See accompany-\n# ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# See http://www.boost.org for updates, documentation, and revision history.\n#\n\nm4 -P -E -DNumberOfArguments=$1 pool_construct.m4 > pool_construct.ipp\n\n", "num_lines": 13}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright (C) 2001 Stephen Cleary\n#\n# Distributed under the Boost Software License, Version 1.0. (See accompany-\n# ing file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# See http://www.boost.org for updates, documentation, and revision history.\n#\n\nm4 -P -E -DNumberOfArguments=$1 pool_construct_simple.m4 > pool_construct_simple.ipp\n\n", "num_lines": 13}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       ZLIB compilation script for the OS/400.\n#\n#\n#       This is a shell script since make is not a standard component of OS/400.\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nTARGETLIB='ZLIB'                # Target OS/400 program library\nSTATBNDDIR='ZLIB_A'             # Static binding directory.\nDYNBNDDIR='ZLIB'                # Dynamic binding directory.\nSRVPGM=\"ZLIB\"                   # Service program.\nIFSDIR='/zlib'                  # IFS support base directory.\nTGTCCSID='500'                  # Target CCSID of objects\nDEBUG='*NONE'                   # Debug level\nOPTIMIZE='40'                   # Optimisation level\nOUTPUT='*NONE'                  # Compilation output option.\nTGTRLS='V6R1M0'                 # Target OS release\n\nexport TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR\nexport TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS\n\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nLIBIFSNAME=\"/QSYS.LIB/${TARGETLIB}.LIB\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       make_module module_name source_name [additional_definitions]\n#\n#       Compile source name into module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n\nmake_module()\n\n{\n    MODULES=\"${MODULES} ${1}\"\n    MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n    CSRC=\"`basename \\\"${2}\\\"`\"\n\n    if action_needed \"${MODIFSNAME}\" \"${2}\"\n    then    :\n    elif [ ! \"`sed -e \\\"/<source name=\\\\\\\"${CSRC}\\\\\\\">/,/<\\\\\\\\/source>/!d\\\" \\\n      -e '/<depend /!d'                                                 \\\n      -e 's/.* name=\\\"\\\\([^\\\"]*\\\\)\\\".*/\\\\1/' < \\\"${TOPDIR}/treebuild.xml\\\" |\n        while read HDR\n        do      if action_needed \\\"${MODIFSNAME}\\\" \\\"${IFSDIR}/include/${HDR}\\\"\n                then    echo recompile\n                        break\n                fi\n        done`\" ]\n    then    return 0\n    fi\n\n    CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('${2}')\"\n    CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST)\"\n    CMD=\"${CMD} LOCALETYPE(*LOCALE) FLAG(10)\"\n    CMD=\"${CMD} INCDIR('${IFSDIR}/include' ${INCLUDES})\"\n    CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n    CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n    CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n    CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n    system \"${CMD}\"\n    LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        basename \"${1}\"                                                 |\n        tr 'a-z-' 'A-Z_'                                                |\n        sed -e 's/\\..*//'                                               \\\n            -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n}\n\n\n#       Force enumeration types to be the same size as integers.\n\ncopy_hfile()\n\n{\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n'\n}\n\n\n################################################################################\n#\n#                             Script initialization.\n#\n################################################################################\n\nSCRIPTDIR=`dirname \"${0}\"`\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in ${TOPDIR}/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nexport SCRIPTDIR TOPDIR\ncd \"${TOPDIR}\"\n\n\n#  Extract the version from the master compilation XML file.\n\nVERSION=`sed -e '/^<package /!d'                                        \\\n            -e 's/^.* version=\"\\([0-9.]*\\)\".*$/\\1/' -e 'q'              \\\n            < treebuild.xml`\nexport VERSION\n\n################################################################################\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB}) TEXT('ZLIB: Data compression API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/ChangeLog\" \"${TOPDIR}/FAQ\"                       \\\n    \"${TOPDIR}/README\" \"${SCRIPTDIR}/README400\"\ndo      MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${TEXT}\\\"`.MBR\"\n\n        if action_needed \"${MEMBER}\" \"${TEXT}\"\n        then    CMD=\"CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})\"\n                CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n\n\n#       Create the OS/400 source program file for the C header files.\n\nSRCPF=\"${LIBIFSNAME}/H.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: C/C++ header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the C header files.\n\nif action_needed \"${IFSDIR}/include\"\nthen    mkdir -p \"${IFSDIR}/include\"\nfi\n\n#       Copy the header files to DB2 library. Link from IFS include directory.\n\nfor HFILE in \"${TOPDIR}/\"*.h\ndo      DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\"`.MBR\"\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    copy_hfile < \"${HFILE}\" > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n                # touch -r \"${HFILE}\" \"${DEST}\"\n                rm -f tmphdrfile\n        fi\n\n        IFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\n        if action_needed \"${IFSFILE}\" \"${DEST}\"\n        then    rm -f \"${IFSFILE}\"\n                ln -s \"${DEST}\" \"${IFSFILE}\"\n        fi\ndone\n\n\n#       Install the ILE/RPG header file.\n\n\nHFILE=\"${SCRIPTDIR}/zlib.inc\"\nDEST=\"${SRCPF}/ZLIB.INC.MBR\"\n\nif action_needed \"${DEST}\" \"${HFILE}\"\nthen    CMD=\"CPY OBJ('${HFILE}') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${HFILE}\" \"${DEST}\"\nfi\n\nIFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\nif action_needed \"${IFSFILE}\" \"${DEST}\"\nthen    rm -f \"${IFSFILE}\"\n        ln -s \"${DEST}\" \"${IFSFILE}\"\nfi\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"ZLIB version '\"${VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nCSOURCES=`sed -e '/<source name=\"/!d'                                   \\\n    -e 's/.* name=\"\\([^\"]*\\)\".*/\\1/' < treebuild.xml`\n\n#       Compile the sources into modules.\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: build tools')\"\n        system \"${CMD}\"\nfi\n\n\nDEST=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\n\nif action_needed \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/bndsrc') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\n        LINK=YES\nfi\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB ${VERSION} dynamic library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\n\n        #       Duplicate the service program for a versioned backup.\n\n        BACKUP=`echo \"${SRVPGM}${VERSION}\"                              |\n                sed -e 's/.*\\(..........\\)$/\\1/' -e 's/\\./_/g'`\n        BACKUP=\"`db2_name \\\"${BACKUP}\\\"`\"\n        BKUPIFSNAME=\"${LIBIFSNAME}/${BACKUP}.SRVPGM\"\n        rm -f \"${BKUPIFSNAME}\"\n        CMD=\"CRTDUPOBJ OBJ(${SRVPGM}) FROMLIB(${TARGETLIB})\"\n        CMD=\"${CMD} OBJTYPE(*SRVPGM) NEWOBJ(${BACKUP})\"\n        system \"${CMD}\"\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n", "num_lines": 367}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# add 'x' for command tracing\nset -eu\n\n#-------------------------------------------------------------------------------\n#\n# Utilities\n#\n\n# For builds not triggered by a pull request TRAVIS_BRANCH is the name of the\n# branch currently being built; whereas for builds triggered by a pull request\n# it is the name of the branch targeted by the pull request (in many cases this\n# will be master).\nMAIN_BRANCH=\"0\"\nif [[ $TRAVIS_BRANCH == \"master\" || $TRAVIS_BRANCH == \"develop\" ]]; then\n    MAIN_BRANCH=\"1\"\nfi\n\nif [[ \"${BEAST_RETRY}\" == \"true\" ]]; then\n  JOBS=1\nelif [[ \"${TRAVIS}\" == \"true\" ]]; then\n  JOBS=\"2\"\nelif [[ $(uname -s) == \"Linux\" ]]; then\n  # Physical cores\n  JOBS=$(lscpu -p | grep -v '^#' | sort -u -t, -k 2,4 | wc -l)\nelif [[ $(uname) == \"Darwin\" ]]; then\n  # Physical cores\n  JOBS=$(sysctl -n hw.physicalcpu)\nelse\n  JOBS=1\nfi\n\n# run with a debugger\nfunction debug_run ()\n{\n  if [[ $TRAVIS_OS_NAME == \"osx\" ]]; then\n    # -o runs after loading the binary\n    # -k runs after any crash\n    # We use a ghetto appromixation of --return-child-result, exiting with\n    # 1 on a crash\n    lldb \\\n      --batch \\\n      -o 'run' \\\n      -k 'thread backtrace all' \\\n      -k 'script import os; os._exit(1)' \\\n      $@\n  else\n    gdb \\\n      --silent \\\n      --batch \\\n      --return-child-result \\\n      -ex=\"set print thread-events off\" \\\n      -ex=run \\\n      -ex=\"thread apply all bt full\" \\\n      --args $@\n  fi\n}\n\nfunction valgrind_run ()\n{\n  valgrind \\\n    --track-origins=yes \\\n    --max-stackframe=16000000 \\\n    --suppressions=$BOOST_ROOT/libs/beast/tools/valgrind.supp \\\n    --error-exitcode=1 \\\n    $@\n}\n\nfunction run_tests_with_debugger ()\n{\n  find \"$1\" -name \"$2\" -print0 | while read -d $'\\0' f\n  do\n    debug_run \"$f\"\n  done\n}\n\nfunction run_tests_with_valgrind ()\n{\n  find \"$1\" -name \"$2\" -print0 | while read -d $'\\0' f\n  do\n    valgrind_run \"$f\"\n  done\n}\n\nfunction run_tests ()\n{\n  find \"$1\" -name \"$2\" -print0 | while read -d $'\\0' f\n  do\n    \"$f\"\n  done\n}\n\n#-------------------------------------------------------------------------------\n\nBIN_DIR=\"$BOOST_ROOT/bin.v2/libs/beast/test\"\nLIB_DIR=\"$BOOST_ROOT/libs/beast\"\nINC_DIR=\"$BOOST_ROOT/boost/beast\"\n\nfunction build_bjam ()\n{\n  if [[ $VARIANT == \"beast_coverage\" ]] || \\\n     [[ $VARIANT == \"beast_valgrind\" ]] || \\\n     [[ $VARIANT == \"beast_ubasan\" ]]; then\n    b2 \\\n      define=BOOST_COROUTINES_NO_DEPRECATION_WARNING=1 \\\n      cxxstd=$CXXSTD \\\n      libs/beast/test/beast/core//fat-tests \\\n      libs/beast/test/beast/http//fat-tests \\\n      libs/beast/test/beast/websocket//fat-tests \\\n      libs/beast/test/beast/zlib//fat-tests \\\n      toolset=$TOOLSET \\\n      variant=$VARIANT \\\n      link=static \\\n      -j${JOBS}\n  elif [[ $VARIANT == \"debug\" ]]; then\n    b2 \\\n      define=BOOST_COROUTINES_NO_DEPRECATION_WARNING=1 \\\n      cxxstd=$CXXSTD \\\n      libs/beast/test//fat-tests \\\n      libs/beast/example \\\n      toolset=$TOOLSET \\\n      variant=$VARIANT \\\n      -j${JOBS}\n  else\n    b2 \\\n      define=BOOST_COROUTINES_NO_DEPRECATION_WARNING=1 \\\n      cxxstd=$CXXSTD \\\n      libs/beast/test//fat-tests \\\n      toolset=$TOOLSET \\\n      variant=$VARIANT \\\n      -j${JOBS}\n  fi\n}\n\nbuild_bjam\n\nif [[ $VARIANT == \"beast_coverage\" ]]; then\n  GCOV=${GCOV:-gcov}\n  # for lcov to work effectively, the paths and includes\n  # passed to the compiler should not contain \".\" or \"..\".\n  # (this runs in $BOOST_ROOT)\n  lcov --version\n  find \"$BOOST_ROOT\" -name \"*.gcda\" | xargs rm -f\n  rm -f \"$BOOST_ROOT/*.info\"\n  lcov --gcov-tool $GCOV --no-external -c -i -d \"$BOOST_ROOT\" -o baseline.info > /dev/null\n  run_tests \"$BIN_DIR\" fat-tests\n  # https://bugs.launchpad.net/ubuntu/+source/lcov/+bug/1163758\n  lcov --gcov-tool $GCOV --no-external -c -d \"$BOOST_ROOT\"  -o testrun-all.info > /dev/null 2>&1\n  lcov --gcov-tool $GCOV -a baseline.info -a testrun-all.info -o lcov-diff.info > /dev/null\n  lcov --gcov-tool $GCOV -e \"lcov-diff.info\" \"$INC_DIR/*\" -o lcov.info > /dev/null\n  lcov --gcov-tool $GCOV --remove \"lcov.info\" \"$INC_DIR/_experimental/*\" -o lcov.info > /dev/null\n  echo \"Change working directory for codecov:\"\n  pwd\n  pushd .\n  cd libs/beast\n  ~/.local/bin/codecov -X gcov -f ../../lcov.info\n  popd\n  find \"$BOOST_ROOT\" -name \"*.gcda\" | xargs rm -f\n\nelif [[ $VARIANT == \"beast_valgrind\" ]]; then\n  run_tests_with_valgrind \"$BIN_DIR\" fat-tests\n\nelse\n  #run_tests_with_debugger \"$BIN_DIR\" fat-tests\n  run_tests \"$BIN_DIR\" fat-tests\n\nfi\n", "num_lines": 169}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -e\nlcov --directory bin.v2 --capture --no-external --directory $(pwd) --output-file coverage.info > /dev/null 2>&1\nlcov --extract coverage.info $(pwd)'/boost/beast/*' --output-file coverage.info > /dev/null\nlcov --remove coverage.info $(pwd)'/boost/beast/_experimental/*' --output-file coverage.info > /dev/null\nlcov --list coverage.info\n# Codecov improperly detects project root in AzP, so we need to upload from beast git repo\ncd libs/beast\ncurl -s https://codecov.io/bash -o codecov && bash ./codecov -X gcov -f ../../coverage.info -t $CODECOV_TOKEN\n", "num_lines": 10}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nset -e\n\nbuild_dir=$2\n\nbranch=\"master\"\n\nif [ \"$1\" != \"master\" -a \"$1\" != \"refs/heads/master\" ]; then\n    branch=\"develop\"\nfi\n\necho \"BUILD_DIR: $build_dir\"\necho \"BRANCH: $branch\"\n\ngit clone -b $branch --depth 1 https://github.com/boostorg/boost.git boost-root\ncd boost-root\n\n# Use a reasonably large depth to prevent intermittent update failures due to\n# commits being on a submodule's master before the superproject is updated.\ngit submodule update --init --depth 20 --jobs 4 \\\n    libs/array \\\n    libs/headers \\\n    tools/build \\\n    tools/boost_install \\\n    tools/boostdep \\\n    libs/align \\\n    libs/asio \\\n    libs/assert \\\n    libs/config \\\n    libs/core \\\n    libs/endian \\\n    libs/filesystem \\\n    libs/intrusive \\\n    libs/locale \\\n    libs/optional \\\n    libs/smart_ptr \\\n    libs/static_assert \\\n    libs/system \\\n    libs/throw_exception \\\n    libs/type_traits \\\n    libs/utility \\\n    libs/winapi \\\n    libs/algorithm \\\n    libs/array \\\n    libs/atomic \\\n    libs/bind \\\n    libs/chrono \\\n    libs/concept_check \\\n    libs/container \\\n    libs/container_hash \\\n    libs/context \\\n    libs/conversion \\\n    libs/coroutine \\\n    libs/date_time \\\n    libs/detail \\\n    libs/exception \\\n    libs/function \\\n    libs/function_types \\\n    libs/functional \\\n    libs/fusion \\\n    libs/integer \\\n    libs/io \\\n    libs/iterator \\\n    libs/lambda \\\n    libs/lexical_cast \\\n    libs/logic \\\n    libs/math \\\n    libs/move \\\n    libs/mp11 \\\n    libs/mpl \\\n    libs/numeric/conversion \\\n    libs/pool \\\n    libs/predef \\\n    libs/preprocessor \\\n    libs/random \\\n    libs/range \\\n    libs/ratio \\\n    libs/rational \\\n    libs/thread \\\n    libs/tuple \\\n    libs/type_index \\\n    libs/typeof \\\n    libs/unordered\n\necho Submodule update complete\n\nrm -rf libs/beast\ncp -r $build_dir libs/beast\n", "num_lines": 90}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Exit if anything fails.\nset -eux\n\nHERE=$PWD\n\n# Override gcc version to $GCC_VER.\n# Put an appropriate symlink at the front of the path.\nmkdir -pv $HOME/bin\nfor g in gcc g++ gcov gcc-ar gcc-nm gcc-ranlib\ndo\n  test -x $( type -p ${g}-$GCC_VER )\n  ln -sv $(type -p ${g}-$GCC_VER) $HOME/bin/${g}\ndone\n\nif [[ -n ${CLANG_VER:-} ]]; then\n    # There are cases where the directory exists, but the exe is not available.\n    # Use this workaround for now.\n    if [[ ! -x llvm-${LLVM_VERSION}/bin/llvm-config ]] && [[ -d llvm-${LLVM_VERSION} ]]; then\n        rm -fr llvm-${LLVM_VERSION}\n    fi\n    if [[ ! -d llvm-${LLVM_VERSION} ]]; then\n        mkdir llvm-${LLVM_VERSION}\n        LLVM_URL=\"http://llvm.org/releases/${LLVM_VERSION}/clang+llvm-${LLVM_VERSION}-x86_64-linux-gnu-ubuntu-14.04.tar.xz\"\n        wget -O - ${LLVM_URL} | tar -Jxvf - --strip 1 -C llvm-${LLVM_VERSION}\n    fi\n    llvm-${LLVM_VERSION}/bin/llvm-config --version;\n    export LLVM_CONFIG=\"llvm-${LLVM_VERSION}/bin/llvm-config\";\nfi\n\n# NOTE, changed from PWD -> HOME\nexport PATH=$HOME/bin:$PATH\n\n# What versions are we ACTUALLY running?\nif [ -x $HOME/bin/g++ ]; then\n    $HOME/bin/g++ -v\nfi\nif [ -x $HOME/bin/clang ]; then\n    $HOME/bin/clang -v\nfi\n\n# Avoid `spurious errors` caused by ~/.npm permission issues\n# Does it already exist? Who owns? What permissions?\nls -lah ~/.npm || mkdir ~/.npm\n\n# Make sure we own it\nchown -Rc $USER ~/.npm\n", "num_lines": 48}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport VARIANT=ubasan\nexport TOOLSET=clang\nexport TRAVIS=0\nexport BOOST_ROOT=\"`pwd`\"\n\n\"$1\"\n", "num_lines": 9}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport LC_COLLATE=C\n\necho \"// string constants\"\necho '            \"<unknown-field>\",'\ncat $1 | sort -f | uniq | sed 's/^/            \\\"/; s/$/\\\",/'\necho\n\necho \"enum class field : unsigned short\"\necho \"{\"\necho \"    unknown = 0,\"\necho\n#cat $1 | uniq | sort -f | sed 's/./\\L&/g; s/^/\\t/; s/$/,/'\ncat $1 | sort -f | uniq | sed 's/\\(.*\\)/    \\L\\1,/; s/-/_/g'\necho \"};\"\necho\n\necho \"// pairs\"\n#cat $1 | uniq | sort -f | sed 's/\\(.*\\)/\\tmatch\\(field::\\L\\1, \\\"\\E\\1\\\"\\);/; s/-/_/'\ncat $1 | sort -f | uniq | perl -nE 'chomp; $a=lc($_); $a=~s/-/_/g; say \"        match(field::$a, \\\"$_\\\");\";' | tr -d \"\\015\"\n\n", "num_lines": 23}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfor i in {1..3}\ndo\n    $1 \"${@:2:99}\" && exit 0;\n    export BEAST_RETRY=\"true\"\ndone\n\nexit 1\n", "num_lines": 10}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngit clone git@github.com:boostorg/boost.git || exit 1\n\npushd boost/libs && git submodule init callable_traits \\\n  algorithm \\\n  align \\\n  any \\\n  array \\\n  array \\\n  assert \\\n  atomic \\\n  bind \\\n  concept_check \\\n  config \\\n  container \\\n  container_hash \\\n  core \\\n  detail \\\n  exception \\\n  filesystem \\\n  format \\\n  function \\\n  functional \\\n  io \\\n  iostreams \\\n  integer \\\n  iterator \\\n  lexical_cast \\\n  move \\\n  mpl \\\n  numeric \\\n  optional \\\n  optional \\\n  predef \\\n  preprocessor \\\n  program_options \\\n  range \\\n  regex \\\n  smart_ptr \\\n  spirit \\\n  static_assert \\\n  system \\\n  throw_exception \\\n  tokenizer \\\n  tuple \\\n  type_index \\\n  type_traits \\\n  unordered \\\n  utility || exit 1\n\npopd\npushd boost && git submodule init tools || exit 1\n\ngit submodule update || exit 1\n./bootstrap.sh || exit 1\n\n./b2 headers\n./b2 tools/quickbook\n./b2 libs/callable_traits/doc && echo \"$PWD/libs/callable_traits/doc/html/index.html\"\n\npopd\n\n", "num_lines": 64}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\n# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\nlibname=\"\"\nsrc=\"\"\nheader=\"\"\nall_dep=\"\"\n\n# current makefile:\nout=\"\"\n# temporary file:\ntout=\"\"\n# install target temp file:\niout=\"\"\n# debug flag:\ndebug=\"no\"\n# compile options:\nopts=\"\"\n# main output sub-directory:\nsubdir=\"\"\n\n#######################################################################\n#\n# section for C++ Builder\n#\n#######################################################################\n\nfunction bcb_gen_lib()\n{\n\tall_dep=\"$all_dep $subdir\\\\$libname $subdir\\\\$libname.lib $subdir\\\\$libname.exe\"\n\techo \"\tcopy $subdir\\\\$libname.lib \\$(BCROOT)\\\\lib\" >> $iout\n#\n# set up section comments:\n\tcat >> $tout << EOF\n########################################################\n#\n# section for $libname.lib\n#\n########################################################\nEOF\n#\n#\tprocess source files:\n\tall_obj=\"\"\n\tall_lib_obj=\"\"\n\tfor file in $src\n\tdo\n\t\tobj=`echo \"$file\" | sed 's/\\(.*\\)cpp/\\1obj/g'`\n\t\tobj=\"$subdir\\\\$libname\\\\$obj\"\n\t\tall_obj=\"$all_obj $obj\"\n\t\tall_lib_obj=\"$all_lib_obj \\\"$obj\\\"\"\n\t\techo \"$obj: $file \\$(ALL_HEADER)\" >> $tout\n\t\techo \"\tbcc32 @&&|\" >> $tout\n\t\techo \"-c \\$(INCLUDES) $opts \\$(CXXFLAGS) -o$obj $file\" >> $tout\n\t\techo \"|\" >> $tout\n\t\techo \"\" >> $tout\n\tdone\n#\n#\t now for the directories for this library:\n\techo \"$subdir\\\\$libname : \" >> $tout\n\techo \"\t-@mkdir $subdir\\\\$libname\" >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the clean options for this library:\n\tall_clean=\"$all_clean $libname\"\"_clean\"\n\techo \"$libname\"_clean : >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.obj' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.il?' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.csm' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.tds' >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the main target for this library:\n\techo $subdir\\\\$libname.lib : $all_obj >> $tout\n\techo \"\ttlib @&&|\" >> $tout\n\techo \"/P128 /C /u /a \\$(XSFLAGS) \\\"$subdir\\\\$libname.lib\\\" $all_lib_obj\" >> $tout\n\techo \"|\" >> $tout\n\techo \"\" >> $tout\n#  now the test program:\n\techo \"$subdir\\\\$libname.exe : main.cpp $subdir\\\\$libname.lib\" >> $tout\n\techo \"\tbcc32 \\$(INCLUDES) $opts /DBOOST_LIB_DIAGNOSTIC=1 \\$(CXXFLAGS) -L./$subdir -e./$subdir/$libname.exe main.cpp\" >> $tout\n\techo \"   echo running test progam $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"   $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"\" >> $tout\n}\n\nfunction bcb_gen_dll()\n{\n\tall_dep=\"$all_dep $subdir\\\\$libname $subdir\\\\$libname.lib $subdir\\\\$libname.exe\"\n\techo \"\tcopy $subdir\\\\$libname.lib \\$(BCROOT)\\\\lib\" >> $iout\n\techo \"\tcopy $subdir\\\\$libname.dll \\$(BCROOT)\\\\bin\" >> $iout\n\techo \"\tcopy $subdir\\\\$libname.tds \\$(BCROOT)\\\\bin\" >> $iout\n#\n# set up section comments:\n\tcat >> $tout << EOF\n########################################################\n#\n# section for $libname.lib\n#\n########################################################\nEOF\n#\n#\tprocess source files:\n\tall_obj=\"\"\n\tfor file in $src\n\tdo\n\t\tobj=`echo \"$file\" | sed 's/\\(.*\\)cpp/\\1obj/g'`\n\t\tobj=\"$subdir\\\\$libname\\\\$obj\"\n\t\tall_obj=\"$all_obj $obj\"\n\t\techo \"$obj: $file \\$(ALL_HEADER)\" >> $tout\n\t\techo \"\tbcc32 @&&|\" >> $tout\n\t\techo \"-c \\$(INCLUDES) $opts \\$(CXXFLAGS) -DBOOST_DYN_LINK -o$obj $file\" >> $tout\n\t\techo \"|\" >> $tout\n\t\techo \"\" >> $tout\n\tdone\n#\n#\t now for the directories for this library:\n\techo \"$subdir\\\\$libname :\" >> $tout\n\techo \"\t-@mkdir $subdir\\\\$libname\" >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the clean options for this library:\n\tall_clean=\"$all_clean $libname\"\"_clean\"\n\techo \"$libname\"_clean : >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.obj' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.il?' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.csm' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.tds' >> $tout\n\techo \"\tdel $subdir\\\\\"'*.tds' >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the main target for this library:\n\techo $subdir\\\\$libname.lib : $all_obj >> $tout\n\techo \"\tbcc32 @&&|\" >> $tout\n\techo \"-lw-dup -lw-dpl $opts -e$subdir\\\\$libname.dll \\$(XLFLAGS) $all_obj \\$(LIBS)\" >> $tout\n\techo \"|\" >> $tout\n\techo \"\timplib -w $subdir\\\\$libname.lib $subdir\\\\$libname.dll\" >> $tout\n\techo \"\" >> $tout\n#  now the test program:\n\techo \"$subdir\\\\$libname.exe : main.cpp $subdir\\\\$libname.lib\" >> $tout\n\techo \"\tbcc32 \\$(INCLUDES) $opts /DBOOST_LIB_DIAGNOSTIC=1 \\$(CXXFLAGS) -DBOOST_DYN_LINK -L./$subdir -e./$subdir/$libname.exe main.cpp\" >> $tout\n\techo \"   echo running test program $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"   $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"\" >> $tout\n}\n\n\n\nfunction bcb_gen()\n{\n\ttout=\"temp\"\n\tiout=\"temp_install\"\n\tall_dep=\"$subdir\"\n\tall_clean=\"\"\n\techo > $out\n\techo > $tout\n\trm -f $iout\n\n\tlibname=\"liblink_test-${subdir}-s-${boost_version}\"\n\topts=\"-tWM- -D_NO_VCL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8037 -w-8057 -DSTRICT; -I\\$(BCROOT)\\include;../../../../\"\n\tbcb_gen_lib\n\n\tlibname=\"liblink_test-${subdir}-mt-s-${boost_version}\"\n\topts=\"-tWM -D_NO_VCL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../\"\n\tbcb_gen_lib\n\t\n\tlibname=\"link_test-${subdir}-mt-${boost_version}\"\n\topts=\"-tWD -tWM -tWR -D_NO_VCL -D_RTLDLL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_dll\n\n\tlibname=\"link_test-${subdir}-${boost_version}\"\n\topts=\"-tWD -tWR -tWM- -D_NO_VCL -D_RTLDLL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_dll\n\t\n\tlibname=\"liblink_test-${subdir}-mt-${boost_version}\"\n\topts=\"-tWD -tWM -tWR -DBOOST_REGEX_STATIC_LINK -D_NO_VCL -D_RTLDLL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_lib\n\n\tlibname=\"liblink_test-${subdir}-${boost_version}\"\n\topts=\"-tWD -tWR -tWM- -DBOOST_REGEX_STATIC_LINK -D_NO_VCL -D_RTLDLL -O2 -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_lib\n\t#\n\t# debug versions:\n\tlibname=\"liblink_test-${subdir}-sd-${boost_version}\"\n\topts=\"-tWM- -D_NO_VCL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8037 -w-8057 -DSTRICT; -I\\$(BCROOT)\\include;../../../../\"\n\tbcb_gen_lib\n\n\tlibname=\"liblink_test-${subdir}-mt-sd-${boost_version}\"\n\topts=\"-tWM -D_NO_VCL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../\"\n\tbcb_gen_lib\n\t\n\tlibname=\"link_test-${subdir}-mt-d-${boost_version}\"\n\topts=\"-tWD -tWM -tWR -D_NO_VCL -D_RTLDLL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_dll\n\n\tlibname=\"link_test-${subdir}-d-${boost_version}\"\n\topts=\"-tWD -tWR -tWM- -D_NO_VCL -D_RTLDLL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_dll\n\t\n\tlibname=\"liblink_test-${subdir}-mt-d-${boost_version}\"\n\topts=\"-tWD -tWM -tWR -DBOOST_REGEX_STATIC_LINK -D_NO_VCL -D_RTLDLL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_lib\n\n\tlibname=\"liblink_test-${subdir}-d-${boost_version}\"\n\topts=\"-tWD -tWR -tWM- -DBOOST_REGEX_STATIC_LINK -D_NO_VCL -D_RTLDLL -v -Ve -Vx -w-inl -w-aus -w-rch -w-8012 -w-8057 -w-8037 -DSTRICT; -I\\$(BCROOT)\\include;../../../../ -L\\$(BCROOT)\\lib;\\$(BCROOT)\\lib\\release;\"\n\tbcb_gen_lib\n\t\n\t\n\tcat > $out << EOF\n# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# auto generated makefile for C++ Builder\n#\n# usage:\n# make\n#   brings libraries up to date\n# make install\n#   brings libraries up to date and copies binaries to your C++ Builder /lib and /bin directories (recomended)\n# make clean\n#   removes all temporary files.\n\n#\n# Add additional compiler options here:\n#\nCXXFLAGS=\n#\n# Add additional include directories here:\n#\nINCLUDES=\n#\n# add additional linker flags here:\n#\nXLFLAGS=\n#\n# add additional libraries to link to here:\n#\nLIBS=\n#\n# add additional static-library creation flags here:\n#\nXSFLAGS=\n\n!ifndef BCROOT\nBCROOT=\\$(MAKEDIR)\\\\..\n!endif\n\nEOF\n\techo \"\" >> $out\n\techo \"ALL_HEADER=$header\" >> $out\n\techo \"\" >> $out\n\techo \"all : $all_dep\" >> $out\n\techo >> $out\n\techo \"clean : $all_clean\" >> $out\n\techo >> $out\n\techo \"install : all\" >> $out\n\tcat $iout >> $out\n\techo >> $out\n\techo $subdir : >> $out\n\techo \"\t-@mkdir $subdir\" >> $out\n\techo \"\" >> $out\n\n\tcat $tout >> $out\n}\n\n. common.sh\n\n#\n# generate C++ Builder 6 files:\nout=\"borland.mak\"\nsubdir=\"borland\"\nhas_stlport=\"yes\"\nbcb_gen\n\n\n\n\n\n\n\n\n", "num_lines": 287}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# locate all the header dependencies:\nheader=\"\"\n#\n# locate all the source files:\nsrc=link_test.cpp\n\nboost_version=$(grep 'define.*BOOST_LIB_VERSION' ../../../../boost/version.hpp | sed 's/.*\"\\([^\"]*\\)\".*/\\1/')\n\n\n\n\n\n\n\n", "num_lines": 20}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\nlibname=\"\"\nsrc=\"\"\nheader=\"\"\nall_dep=\"\"\n\n# current makefile:\nout=\"\"\n# temporary file:\ntout=\"\"\n# install target temp file:\niout=\"\"\n# debug flag:\ndebug=\"no\"\n# compile options:\nopts=\"\"\n# main output sub-directory:\nsubdir=\"\"\n# extra debug /RTc options:\ndebug_extra=\"\"\n\nfunction vc6_gen_lib()\n{\n\tall_dep=\"$all_dep $libname\"\"_dir ./$subdir/$libname.lib ./$subdir/$libname.exe\"\n\techo \"\tcopy $subdir\\\\$libname.lib \"'\"$'\"(MSVCDIR)\\\\lib\"'\"' >> $iout\n\tif test $debug == \"yes\"; then\n\t\techo \"\tcopy $subdir\\\\$libname.pdb \"'\"$'\"(MSVCDIR)\\\\lib\"'\"' >> $iout\n\tfi\n#\n# set up section comments:\n\tcat >> $tout << EOF\n########################################################\n#\n# section for $libname.lib\n#\n########################################################\nEOF\n#\n#\tprocess source files:\n\tall_obj=\"\"\n\tfor file in $src\n\tdo\n\t\tobj=`echo \"$file\" | sed 's/\\(.*\\)cpp/\\1obj/g'`\n\t\tobj=\"$subdir/$libname/$obj\"\n\t\tall_obj=\"$all_obj $obj\"\n\t\techo \"$obj: $file \\$(ALL_HEADER)\" >> $tout\n\t\techo \"\tcl /c \\$(INCLUDES) $opts \\$(CXXFLAGS) -Y- -Fo./$subdir/$libname/ -Fd$subdir/$libname.pdb $file\" >> $tout\n\t\techo \"\" >> $tout\n\tdone\n#\n#\t now for the directories for this library:\n\techo \"$libname\"_dir : >> $tout\n\techo \"\t@if not exist \\\"$subdir\\\\$libname\\\\\\$(NULL)\\\" mkdir $subdir\\\\$libname\" >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the clean options for this library:\n\tall_clean=\"$all_clean $libname\"\"_clean\"\n\techo \"$libname\"_clean : >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.obj' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.idb' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.exp' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.pch' >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the main target for this library:\n\techo ./$subdir/$libname.lib : $all_obj >> $tout\n\techo \"\tlink -lib /nologo /out:$subdir/$libname.lib \\$(XSFLAGS) $all_obj\" >> $tout\n\techo \"\" >> $tout\n#  now the test program:\n\techo ./$subdir/$libname.exe : main.cpp ./$subdir/$libname.lib >> $tout\n\techo \"\tcl \\$(INCLUDES) $opts /DBOOST_LIB_DIAGNOSTIC=1 \\$(CXXFLAGS) -o ./$subdir/$libname.exe main.cpp /link /LIBPATH:./$subdir\" >> $tout\n\techo \"   $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"\" >> $tout\n}\n\nfunction vc6_gen_dll()\n{\n\tall_dep=\"$all_dep $libname\"\"_dir ./$subdir/$libname.lib ./$subdir/$libname.exe\"\n\techo \"\tcopy $subdir\\\\$libname.lib \"'\"$'\"(MSVCDIR)\\\\lib\"'\"' >> $iout\n\techo \"\tcopy $subdir\\\\$libname.dll \"'\"$'\"(MSVCDIR)\\\\bin\"'\"' >> $iout\n\tif test $debug == \"yes\"; then\n\t\techo \"\tcopy $subdir\\\\$libname.pdb \"'\"$'\"(MSVCDIR)\\\\lib\"'\"' >> $iout\n\tfi\n#\n# set up section comments:\n\tcat >> $tout << EOF\n########################################################\n#\n# section for $libname.lib\n#\n########################################################\nEOF\n#\n#\tprocess source files:\n\tall_obj=\"\"\n\tfor file in $src\n\tdo\n\t\tobj=`echo \"$file\" | sed 's/\\(.*\\)cpp/\\1obj/g'`\n\t\tobj=\"$subdir/$libname/$obj\"\n\t\tall_obj=\"$all_obj $obj\"\n\t\techo \"$obj: $file \\$(ALL_HEADER)\" >> $tout\n\t\techo \"\tcl /c \\$(INCLUDES) $opts \\$(CXXFLAGS) -Y- -Fo./$subdir/$libname/ -Fd$subdir/$libname.pdb $file\" >> $tout\n\t\techo \"\" >> $tout\n\tdone\n#\n#\t now for the directories for this library:\n\techo \"$libname\"_dir : >> $tout\n\techo \"\t@if not exist \\\"$subdir\\\\$libname\\\\\\$(NULL)\\\" mkdir $subdir\\\\$libname\" >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the clean options for this library:\n\tall_clean=\"$all_clean $libname\"\"_clean\"\n\techo \"$libname\"_clean : >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.obj' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.idb' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.exp' >> $tout\n\techo \"\tdel $subdir\\\\$libname\\\\\"'*.pch' >> $tout\n\techo \"\" >> $tout\n#\n#\t now for the main target for this library:\n\techo ./$subdir/$libname.lib : $all_obj >> $tout\n\techo \"\tlink kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /incremental:yes /pdb:\\\"$subdir/$libname.pdb\\\" /debug /machine:I386 /out:\\\"$subdir/$libname.dll\\\" /implib:\\\"$subdir/$libname.lib\\\" /LIBPATH:\\$(STLPORT_PATH)\\\\lib \\$(XLFLAGS) $all_obj\" >> $tout\n\techo \"\" >> $tout\n#  now the test program:\n\techo ./$subdir/$libname.exe : main.cpp ./$subdir/$libname.lib >> $tout\n\techo \"\tcl \\$(INCLUDES) $opts /DBOOST_LIB_DIAGNOSTIC=1 \\$(CXXFLAGS) -o ./$subdir/$libname.exe main.cpp /link /LIBPATH:./$subdir\" >> $tout\n\techo \"   $subdir\"'\\'\"$libname.exe\" >> $tout\n\techo \"\" >> $tout\n}\n\nis_stlport=\"no\"\n\nfunction vc6_gen()\n{\n\tdebug=\"no\"\n\ttout=\"temp\"\n\tiout=\"temp_install\"\n\tall_dep=\"main_dir\"\n\tall_clean=\"\"\n\techo > $out\n\techo > $tout\n\trm -f $iout\n\t\n\tlibname=\"liblink_test-${subdir}-s-${boost_version}\"\n\topts='/nologo /ML /W3 /GX /O2 /GB /GF /Gy /I..\\..\\..\\..\\ /DWIN32 /DNDEBUG /D_MBCS /D_LIB /FD'\n\tvc6_gen_lib\n\t\n\tlibname=\"liblink_test-${subdir}-mt-s-${boost_version}\"\n\topts='/nologo /MT /W3 /GX /O2 /GB /GF /Gy /I..\\..\\..\\..\\ /D_MT /DWIN32 /DNDEBUG /D_MBCS /D_LIB /FD '\n\tvc6_gen_lib\n\t\n\tdebug=\"yes\"\n\tlibname=\"liblink_test-${subdir}-sgd-${boost_version}\"\n\topts='/nologo /MLd /W3 /Gm /GX /Zi /Od /I..\\..\\..\\..\\ /DWIN32 /D_DEBUG /D_MBCS /D_LIB /FD '\"$debug_extra\"'  '\n\tvc6_gen_lib\n\t\n\tlibname=\"liblink_test-${subdir}-mt-sgd-${boost_version}\"\n\topts='/nologo /MTd /W3 /Gm /GX /Zi /Od /I..\\..\\..\\..\\ /DWIN32 /D_MT /D_DEBUG /D_MBCS /D_LIB /FD '\"$debug_extra\"' '\n\tvc6_gen_lib\n\t\n\tlibname=\"link_test-${subdir}-mt-gd-${boost_version}\"\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I..\\..\\..\\..\\ /D_DEBUG /DBOOST_DYN_LINK /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL /FD '\"$debug_extra\"' '\n\tvc6_gen_dll\n\t\n\tdebug=\"no\"\n\topts='/nologo /MD /W3 /GX /O2 /GB /GF /Gy /I..\\..\\..\\..\\ /DBOOST_DYN_LINK /DNDEBUG /DWIN32 /D_WINDOWS /D_MBCS /D_USRDLL /FD '\n\tlibname=\"link_test-${subdir}-mt-${boost_version}\"\n\tvc6_gen_dll\n\t\n\tdebug=\"no\"\n\topts='/nologo /MD /W3 /GX /O2 /GB /GF /Gy /I..\\..\\..\\..\\ /DBOOST_REGEX_STATIC_LINK /DNDEBUG /DWIN32 /D_WINDOWS /D_MBCS /D_USRDLL /FD '\n\tlibname=\"liblink_test-${subdir}-mt-${boost_version}\"\n\tvc6_gen_lib\n\t\n\tdebug=\"yes\"\n\tlibname=\"liblink_test-${subdir}-mt-gd-${boost_version}\"\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I..\\..\\..\\..\\ /DBOOST_REGEX_STATIC_LINK /D_DEBUG /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL /FD '\"$debug_extra\"' '\n\tvc6_gen_lib\n\t\n\tcat > $out << EOF\n# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# auto generated makefile for VC6 compiler\n#\n# usage:\n# make\n#   brings libraries up to date\n# make install\n#   brings libraries up to date and copies binaries to your VC6 /lib and /bin directories (recomended)\n#\n\n#\n# Add additional compiler options here:\n#\nCXXFLAGS=\n#\n# Add additional include directories here:\n#\nINCLUDES=\n#\n# add additional linker flags here:\n#\nXLFLAGS=\n#\n# add additional static-library creation flags here:\n#\nXSFLAGS=\n\n!IF \"\\$(OS)\" == \"Windows_NT\"\nNULL=\n!ELSE \nNULL=nul\n!ENDIF \n\n!IF \"\\$(MSVCDIR)\" == \"\"\n!ERROR Variable MSVCDIR not set.\n!ENDIF\n\nEOF\n\techo \"\" >> $out\n\techo \"ALL_HEADER=$header\" >> $out\n\techo \"\" >> $out\n\techo \"all : $all_dep\" >> $out\n\techo >> $out\n\techo \"clean : $all_clean\" >> $out\n\techo >> $out\n\techo \"install : all\" >> $out\n\tcat $iout >> $out\n\techo >> $out\n\techo main_dir : >> $out\n\techo \"\t@if not exist \\\"$subdir\\\\\\$(NULL)\\\" mkdir $subdir\" >> $out\n\techo \"\" >> $out\n\n\tcat $tout >> $out\n}\n\nfunction vc6_stlp_gen()\n{\n\tdebug=\"no\"\n\ttout=\"temp\"\n\tiout=\"temp_install\"\n\tall_dep=\"main_dir\"\n\tall_clean=\"\"\n\techo > $out\n\techo > $tout\n\trm -f $iout\n\t\n\tlibname=\"liblink_test-${subdir}-mt-s-${boost_version}\"\n\topts='/nologo /MT /W3 /GX /O2 /GB /GF /Gy /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /D_MT /DWIN32 /DNDEBUG /D_MBCS /D_LIB '\n\tvc6_gen_lib\n\t\n\tdebug=\"true\"\n\tlibname=\"liblink_test-${subdir}-mt-sgd-${boost_version}\"\n\topts='/nologo /MTd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DWIN32 /D_MT /D_DEBUG /D_MBCS /D_LIB '\"$debug_extra\"' '\n\tvc6_gen_lib\n\t\n\tlibname=\"link_test-${subdir}-mt-gd-${boost_version}\"\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DBOOST_DYN_LINK /D_DEBUG /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL '\"$debug_extra\"' '\n\tvc6_gen_dll\n\t\n\tdebug=\"no\"\n\topts='/nologo /MD /W3 /GX /O2 /GB /GF /I$(STLPORT_PATH)\\stlport /Gy /I..\\..\\..\\..\\ /DBOOST_DYN_LINK /DNDEBUG /DWIN32 /D_WINDOWS /D_MBCS /D_USRDLL '\n\tlibname=\"link_test-${subdir}-mt-${boost_version}\"\n\tvc6_gen_dll\n\t\n\tdebug=\"no\"\n\topts='/nologo /MD /W3 /GX /O2 /GB /GF /Gy /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DBOOST_REGEX_STATIC_LINK /DNDEBUG /DWIN32 /D_WINDOWS /D_MBCS /D_USRDLL '\n\tlibname=\"liblink_test-${subdir}-mt-${boost_version}\"\n\tvc6_gen_lib\n\t\n\tdebug=\"true\"\n\tlibname=\"liblink_test-${subdir}-mt-gd-${boost_version}\"\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DBOOST_REGEX_STATIC_LINK /D_DEBUG /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL '\"$debug_extra\"' '\n\tvc6_gen_lib\n\n#  debug STLPort mode:\n#  not yet supported by bjam?\n\tdebug=\"yes\"\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DBOOST_DYN_LINK /D__STL_DEBUG /D_STLP_DEBUG /D_DEBUG /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL '\"$debug_extra\"' '\n\tlibname=\"link_test-${subdir}-mt-pgd-${boost_version}\"\n\tvc6_gen_dll\n\tlibname=\"liblink_test-${subdir}-mt-spgd-${boost_version}\"\n\topts='/nologo /MTd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /D__STL_DEBUG /D_STLP_DEBUG /DWIN32 /D_MT /D_DEBUG /D_MBCS /D_LIB '\"$debug_extra\"' '\n\tvc6_gen_lib\n\topts='/nologo /MDd /W3 /Gm /GX /Zi /Od /I$(STLPORT_PATH)\\stlport /I..\\..\\..\\..\\ /DBOOST_REGEX_STATIC_LINK /D__STL_DEBUG /D_STLP_DEBUG /D_DEBUG /DWIN32 /D_WINDOWS /D_MBCS /DUSRDLL '\"$debug_extra\"' '\n\tlibname=\"liblink_test-${subdir}-mt-pgd-${boost_version}\"\n\tvc6_gen_lib\n\t\n\tcat > $out << EOF\n# copyright John Maddock 2005\n# Use, modification and distribution are subject to the \n# Boost Software License, Version 1.0. (See accompanying file \n# LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# auto generated makefile for VC6+STLPort\n#\n# usage:\n# make\n#   brings libraries up to date\n# make install\n#   brings libraries up to date and copies binaries to your VC6 /lib and /bin directories (recomended)\n#\n\n#\n# Add additional compiler options here:\n#\nCXXFLAGS=\n#\n# Add additional include directories here:\n#\nINCLUDES=\n#\n# add additional linker flags here:\n#\nXLFLAGS=\n#\n# add additional static-library creation flags here:\n#\nXSFLAGS=\n\n!IF \"\\$(OS)\" == \"Windows_NT\"\nNULL=\n!ELSE \nNULL=nul\n!ENDIF \n\n!IF \"\\$(MSVCDIR)\" == \"\"\n!ERROR Variable MSVCDIR not set.\n!ENDIF\n\n!IF \"\\$(STLPORT_PATH)\" == \"\"\n!ERROR Variable STLPORT_PATH not set.\n!ENDIF\n\nEOF\n\techo \"\" >> $out\n\techo \"ALL_HEADER=$header\" >> $out\n\techo \"\" >> $out\n\techo \"all : $all_dep\" >> $out\n\techo >> $out\n\techo \"clean : $all_clean\" >> $out\n\techo >> $out\n\techo \"install : stlport_check all\" >> $out\n\tcat $iout >> $out\n\techo >> $out\n\techo main_dir : >> $out\n\techo \"\t@if not exist \\\"$subdir\\\\\\$(NULL)\\\" mkdir $subdir\" >> $out\n\techo \"\" >> $out\n\techo 'stlport_check : $(STLPORT_PATH)\\stlport\\string' >> $out\n\techo \"\techo\" >> $out\n\techo \"\" >> $out\n\n\tcat $tout >> $out\n}\n\n\n. common.sh\n\n#\n# generate vc6 makefile:\ndebug_extra=\"/GX\"\nout=\"vc6.mak\"\nsubdir=\"vc6\"\nvc6_gen\n#\n# generate vc6-stlport makefile:\nis_stlport=\"yes\"\nout=\"vc6-stlport.mak\"\nno_single=\"yes\"\nsubdir=\"vc6-stlport\"\nvc6_stlp_gen\n#\n# generate vc7 makefile:\ndebug_extra=\"/GX /RTC1\"\nis_stlport=\"no\"\nout=\"vc7.mak\"\nno_single=\"no\"\nsubdir=\"vc7\"\nvc6_gen\n#\n# generate vc7-stlport makefile:\nis_stlport=\"yes\"\nout=\"vc7-stlport.mak\"\nno_single=\"yes\"\nsubdir=\"vc7-stlport\"\nvc6_stlp_gen\n#\n# generate vc71 makefile:\nis_stlport=\"no\"\nout=\"vc71.mak\"\nno_single=\"no\"\nsubdir=\"vc71\"\nvc6_gen\n#\n# generate vc71-stlport makefile:\nis_stlport=\"yes\"\nout=\"vc71-stlport.mak\"\nno_single=\"yes\"\nsubdir=\"vc71-stlport\"\nvc6_stlp_gen\n\n\n#\n# remove tmep files;\nrm -f $tout $iout\n\n\n\n\n\n\n\n\n\n\n\n", "num_lines": 425}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# boost-no-inspect\n\nif [[ -d \"$BOOST_ROOT\" ]]\nthen\n    echo Using BOOST_ROOT=$BOOST_ROOT\nelse\n    export BOOST_ROOT=$HOME/dev/boost\nfi\n\n$BOOST_ROOT/b2 --toolset=gcc --enable-index\n\nrm -rf convert_reference.xml\nrm -rf bin\n\n\n\n\n", "num_lines": 18}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (C) 2009 The Trustees of Indiana University.\n# Copyright (C) 2010 Daniel Trebbien.\n# Use, modification and distribution is subject to the Boost Software\n# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n# http://www.boost.org/LICENSE_1_0.txt)\n\n# Authors: Jeremiah Willcock, Daniel Trebbien, Andrew Lumsdaine\n\nfor i in read_graphml read_graphviz write_graphml; do\n  rst2html.py -gdt --link-stylesheet --traceback --trim-footnote-reference-space --footnote-references=superscript --stylesheet=../../../rst.css $i.rst > $i.html\ndone\n# Also see grid_graph_export_png.sh for figure conversions\n\n# Stoer-Wagner images from Daniel Trebbien\nfdp -s -n -Tgif -ostoer_wagner_imgs/digraph1.gif stoer_wagner_imgs/digraph1.dot\nfdp -s -n -Tgif -ostoer_wagner_imgs/digraph1-min-cut.gif stoer_wagner_imgs/digraph1-min-cut.dot\nfdp -s -n -Tgif -ostoer_wagner_imgs/stoer_wagner-example.gif stoer_wagner_imgs/stoer_wagner-example.dot\nfdp -s -n -Tgif -ostoer_wagner_imgs/stoer_wagner-example-c1.gif stoer_wagner_imgs/stoer_wagner-example-c1.dot\nfdp -s -n -Tgif -ostoer_wagner_imgs/stoer_wagner-example-min-cut.gif stoer_wagner_imgs/stoer_wagner-example-min-cut.dot\ndot -Tgif -ostoer_wagner_imgs/stoer_wagner.cpp.gif stoer_wagner_imgs/stoer_wagner.cpp.dot\n", "num_lines": 23}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#=======================================================================\n# Copyright 2009 Trustees of Indiana University.\n# Authors: Michael Hansen, Andrew Lumsdaine\n#\n# Distributed under the Boost Software License, Version 1.0. (See\n# accompanying file LICENSE_1_0.txt or copy at\n# http:#www.boost.org/LICENSE_1_0.txt)\n#=======================================================================\n\n# Unindexed, unwrapped\ninkscape --export-png grid_graph_unwrapped.png --export-id g3150 --export-id-only grid_graph_unindexed.svg\n\n# Unindexed, wrapped\ninkscape --export-png grid_graph_wrapped.png grid_graph_unindexed.svg\n\n# Indexed, unwrapped\ninkscape --export-png grid_graph_indexed.png grid_graph_indexed.svg\n", "num_lines": 20}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nPROGNAME=\"$(basename \"${0}\")\"\nfunction usage() {\ncat <<EOF\nUsage:\n${PROGNAME} <next-version>\n\nThis script merges 'develop' to 'master' and tags a release on the 'master'\nbranch. It then bumps the version on 'develop' to the next planned version.\n<next-version> must be of the form X.Y.Z, where X, Y and Z are numbers.\n\nThis script should be run from the root of the repository without any\nuncommitted changes.\nEOF\n}\n\nfor arg in $@; do\n    if [[ \"${arg}\" == \"-h\" || \"${arg}\" == \"--help\" ]]; then\n        usage\n        exit 0\n    fi\ndone\n\nif [[ $# -ne 1 ]]; then\n    echo \"Missing the version\"\n    usage\n    exit 1\nfi\n\nnext_version=\"${1}\"\nnext_major=\"$(echo ${next_version} | cut -d '.' -f 1)\"\nnext_minor=\"$(echo ${next_version} | cut -d '.' -f 2)\"\nnext_patch=\"$(echo ${next_version} | cut -d '.' -f 3)\"\nif [[ -z \"${next_major}\" || -z \"${next_minor}\" || -z \"${next_patch}\" ]]; then\n    echo \"The version was specified incorrectly\"\n    usage\n    exit 1\nfi\n\ncurrent_major=\"$(sed -n -E 's/#define BOOST_HANA_MAJOR_VERSION ([0-9]+)/\\1/p' include/boost/hana/version.hpp)\"\ncurrent_minor=\"$(sed -n -E 's/#define BOOST_HANA_MINOR_VERSION ([0-9]+)/\\1/p' include/boost/hana/version.hpp)\"\ncurrent_patch=\"$(sed -n -E 's/#define BOOST_HANA_PATCH_VERSION ([0-9]+)/\\1/p' include/boost/hana/version.hpp)\"\ncurrent_version=\"${current_major}.${current_minor}.${current_patch}\"\n\ngit checkout --quiet master\ngit merge --quiet develop -m \"Merging 'develop' into 'master' for ${current_version}\"\necho \"Merged 'develop' into 'master' -- you should push 'master' when ready\"\n\ntag=\"v${current_major}.${current_minor}.${current_patch}\"\ngit tag -a --file=RELEASE_NOTES.md \"${tag}\"\necho \"Created tag ${tag} on 'master' -- you should push it when ready\"\n\ngit checkout --quiet develop\nsed -i '' -E \"s/#define BOOST_HANA_MAJOR_VERSION [0-9]+/#define BOOST_HANA_MAJOR_VERSION ${next_major}/\" include/boost/hana/version.hpp\nsed -i '' -E \"s/#define BOOST_HANA_MINOR_VERSION [0-9]+/#define BOOST_HANA_MINOR_VERSION ${next_minor}/\" include/boost/hana/version.hpp\nsed -i '' -E \"s/#define BOOST_HANA_PATCH_VERSION [0-9]+/#define BOOST_HANA_PATCH_VERSION ${next_patch}/\" include/boost/hana/version.hpp\ncat <<EOF > RELEASE_NOTES.md\nRelease notes for Hana ${next_version}\n============================\nEOF\ngit add include/boost/hana/version.hpp RELEASE_NOTES.md\ngit commit --quiet -m \"Bump version of Hana to ${next_version} and clear release notes\"\necho \"Bumped the version of Hana on 'develop' to ${next_version} -- you should push 'develop' when ready\"\n", "num_lines": 67}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Hans Dembinski 2019\n# Distributed under the Boost Software License, Version 1.0.\n# See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt\n\nfor cpu in /sys/devices/system/cpu/cpu? ; do echo performance > $cpu/cpufreq/scaling_governor; done\n", "num_lines": 8}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright Hans Dembinski 2019\n# Distributed under the Boost Software License, Version 1.0.\n# See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt\n\nfor cpu in /sys/devices/system/cpu/cpu? ; do echo powersave > $cpu/cpufreq/scaling_governor; done\n", "num_lines": 8}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright Hans Dembinski 2019\n# Distributed under the Boost Software License, Version 1.0.\n# See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt\n\n# Find files with CRLF: `find <path> -not -type d -exec file \"{}\" \";\" | grep CRLF`\n\nperl -pi -e 's/\\r\\n/\\n/g' $1\n", "num_lines": 10}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright Hans Dembinski 2018-2019\n# Distributed under the Boost Software License, Version 1.0.\n# See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt\n\nexec llvm-cov gcov \"$@\"\n", "num_lines": 8}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright David Abrahams 2006. Distributed under the Boost\n# Software License, Version 1.0. (See accompanying\n# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\nPYTHONPATH=\"c:/src/docutils;c:/src/docutils/extras\"\nexport PYTHONPATH\nrst2html.py -gs --link-stylesheet --traceback --trim-footnote-reference-space --footnote-references=superscript --stylesheet=../../../rst.css $1 `echo $1 | sed 's/\\(.*\\)\\..*/\\1.html/'`\n\n\n\n", "num_lines": 11}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright David Abrahams 2006. Distributed under the Boost\n# Software License, Version 1.0. (See accompanying\n# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\nPYTHONPATH=\"c:/src/docutils;c:/src/docutils/extras\"\nexport PYTHONPATH\npython c:/src/docutils/tools/rst2latex.py --documentoptions pdftex --stylesheet=docutils.sty $1 `echo $1 | sed 's/\\(.*\\)\\..*/\\1.tex/'`\n", "num_lines": 8}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "mkdir -p lib\ncd lib\ngit clone --depth 1 https://github.com/Tencent/rapidjson.git rapidjson\ngit clone --depth 1 https://github.com/nlohmann/json.git nlohmann\n", "num_lines": 5}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# builds the fuzzers, runs old crashes etc\n#\n# Optional: set environment variable CLANG, otherwise clang is auto detected.\n#\n# By Paul Dreik 2019-2020 for the boost json project\n# License: Boost 1.0\n\nset -e\n\nfuzzdir=$(dirname $0)\nme=$(basename $0)\n\ncd $fuzzdir\n\nif [ -z $CLANG ] ; then\n    #see if we can find clang\n    for clangver in -10 -9 -8 -7 -6 -6.0 \"\" ;   do\n\tCLANG=clang++$clangver\n\tif which $CLANG >/dev/null; then\n\t    break\n\tfi\n    done\nfi\n\nif ! which $CLANG >/dev/null; then\n    if ! -x $CLANG; then\n\techo $me: sorry, could not find clang $CLANG\n\texit 1\n    fi\nfi\necho \"$me: will use this compiler: $CLANG\"\n\n# set the maximum size of the input, to avoid\n# big inputs which blow up the corpus size\nMAXLEN=\"-max_len=4000\"\n\n# If doing fuzzing locally (not in CI), adjust this to utilize more\n# of your cpu.\n#JOBS=\"-jobs=32\"\nJOBS=\n\n# set a timelimit (you may want to adjust this if you run locally)\nMAXTIME=\"-max_total_time=30\"\n\nvariants=\"basic_parser parse parser\"\n\nfor variant in $variants; do\n\nsrcfile=fuzz_$variant.cpp\nfuzzer=./fuzzer_$variant\n\nif [ ! -e $fuzzer -o $srcfile -nt $fuzzer ] ; then\n    # explicitly set BOOST_JSON_STACK_BUFFER_SIZE small so interesting\n    # code paths are taken also for small inputs (see https://github.com/CPPAlliance/json/issues/333)\n    $CLANG \\\n        -std=c++17 \\\n        -O3 \\\n        -g \\\n        -fsanitize=fuzzer,address,undefined \\\n        -fno-sanitize-recover=undefined \\\n        -DBOOST_JSON_STANDALONE \\\n        -I../include \\\n        -DBOOST_JSON_STACK_BUFFER_SIZE=64  \\\n        -o $fuzzer \\\n        ../src/src.cpp \\\n        $srcfile\nfi\n\n# make sure ubsan stops in case anything is found\nexport UBSAN_OPTIONS=\"halt_on_error=1\"\n\n# make sure the old crashes pass without problems\nif [ -d old_crashes/$variant ]; then\n  find old_crashes/$variant -type f -print0 |xargs -0 --no-run-if-empty $fuzzer\nfi\n\n# make an initial corpus from the test data already in the repo\nseedcorpus=seedcorpus/$variant\nif [ ! -d $seedcorpus ] ; then\n    mkdir -p $seedcorpus\n    find ../test -name \"*.json\" -type f -print0 |xargs -0 --no-run-if-empty cp -f -t $seedcorpus/\nfi\n\n# if an old corpus exists, use it\n# get it with curl -O --location -J https://bintray.com/pauldreik/boost.json/download_file?file_path=corpus%2Fcorpus.tar\nif [ -e corpus.tar ] ; then\n  mkdir -p oldcorpus\n  tar xf corpus.tar -C oldcorpus || echo \"corpus.tar was broken! ignoring it\"\n  OLDCORPUS=oldcorpus/cmin/$variant\n  # in case the old corpus did not have this variant (when adding/renaming a new fuzzer)\n  mkdir -p $OLDCORPUS\nelse\n  OLDCORPUS=\nfi\n\n\n# run the fuzzer for a short while\nmkdir -p out/$variant\n$fuzzer out/$variant $OLDCORPUS $seedcorpus/ $MAXTIME $MAXLEN $JOBS\n\n# minimize the corpus\nmkdir -p cmin/$variant\n$fuzzer cmin/$variant $OLDCORPUS out/$variant $seedcorpus/ -merge=1 $MAXLEN\ndone\n\n", "num_lines": 108}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "ninja\nrm benchmark.csv\n./deep_stack_leaf\n./deep_stack_tl\n./deep_stack_result\n./deep_stack_outcome\n", "num_lines": 7}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)\n#\n#  Distributed under the Boost Software License, Version 1.0. (See\n#  accompanying file LICENSE_1_0.txt or copy at\n#  http://www.boost.org/LICENSE_1_0.txt)\n#\n\n\nrm html/* && doxygen \n", "num_lines": 12}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)\n#\n#  Distributed under the Boost Software License, Version 1.0. (See\n#  accompanying file LICENSE_1_0.txt or copy at\n#  http://www.boost.org/LICENSE_1_0.txt)\n#\n\nmsgfmt --endianness=big he/LC_MESSAGES/simple.po -o he/LC_MESSAGES/simple.mo\nmsgfmt he/LC_MESSAGES/default.po -o he/LC_MESSAGES/default.mo\nmsgfmt he/LC_MESSAGES/fall.po -o he/LC_MESSAGES/fall.mo\nmsgfmt he_IL/LC_MESSAGES/full.po -o he_IL/LC_MESSAGES/full.mo\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)\n#\n#  Distributed under the Boost Software License, Version 1.0. (See\n#  accompanying file LICENSE_1_0.txt or copy at\n#  http://www.boost.org/LICENSE_1_0.txt)\n#\n\n\n# Small and Fast Cross Compile Script\n\nrm -r build\ncd build\n\nBUILD_TYPE=i586-mingw32msvc\nGETTEXT_VER=0.18.1.1\nICONV_VER=1.13.1\n\nwget http://ftp.gnu.org/pub/gnu/libiconv/libiconv-$ICONV_VER.tar.gz || exit 1\nwget http://ftp.gnu.org/pub/gnu/gettext/gettext-$GETTEXT_VER.tar.gz || exit 1\n\ntar -xzf libiconv-$ICONV_VER.tar.gz || exit 1\ntar -xzf gettext-$GETTEXT_VER.tar.gz || exit 1\n\n\nmkdir win32\nPACKAGE_DIR=gettext-tools-static-$GETTEXT_VER\nmkdir $PACKAGE_DIR\n\nPREFIX=`pwd`/win32\n\ncd libiconv-$ICONV_VER\n\n./configure --disable-shared --host=$BUILD_TYPE --prefix=$PREFIX || exit 1\nmake -j 4 && make install || exit 1\ncp ./COPYING ../$PACKAGE_DIR/COPYING-libiconv.txt\n\ncd ../gettext-$GETTEXT_VER\n\n./configure --disable-shared --host=$BUILD_TYPE --prefix=$PREFIX --with-libiconv-prefix=$PREFIX || exit 1\ncd gettext-tools\nmake -j 4 && make install || exit 1\ncd ..\n\ncp ./gettext-tools/gnulib-lib/libxml/COPYING ../$PACKAGE_DIR/COPYING-libxml.txt\ncp ./COPYING ../$PACKAGE_DIR/COPYING-gettext.txt\n\ncd ..\n\necho http://ftp.gnu.org/pub/gnu/libiconv/libiconv-$ICONV_VER.tar.gz > $PACKAGE_DIR/sources.txt\necho http://ftp.gnu.org/pub/gnu/gettext/gettext-$GETTEXT_VER.tar.gz >> $PACKAGE_DIR/sources.txt\n\ncp win32/bin/*.exe $PACKAGE_DIR\n\nunix2dos $PACKAGE_DIR/*.txt\n\nzip $PACKAGE_DIR.zip $PACKAGE_DIR/*\n\nmv $PACKAGE_DIR.zip ..\n", "num_lines": 61}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#  Copyright John Maddock 2008.\n#  Use, modification and distribution are subject to the\n#  Boost Software License, Version 1.0. (See accompanying file\n#  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# Generates SVG and PNG files from the MML masters.\n#\n# Paths to tools come first, change these to match your system:\n#\nmath2svg='d:\\download\\open\\SVGMath-0.3.3\\math2svg.py'\npython='/cygdrive/c/Python27/python.exe'\ninkscape='/cygdrive/c/Program Files/Inkscape/inkscape.exe'\n# Image DPI:\ndpi=120\n\nfor mmlfile in $*; do\n\tsvgfile=$(basename $mmlfile .mml).svg\n\tpngfile=$(basename $svgfile .svg).png\n\ttempfile=temp.mml\n\t# strip html wrappers put in by MathCast:\n\tcat $mmlfile | tr -d \"\\r\\n\" | sed -e 's/.*\\(<math[^>]*>.*<\\/math>\\).*/\\1/' -e 's/<semantics>//g' -e 's/<\\/semantics>//g' > $tempfile\n\t\n\techo Generating $svgfile\n\t\"$python\" $math2svg $tempfile > $svgfile\n\techo Generating $pngfile\n\t\"$inkscape\" -d $dpi -e $(cygpath -a -w $pngfile) $(cygpath -a -w $svgfile)\n\trm $tempfile\ndone\n\n\n\n\n", "num_lines": 33}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#  Copyright John Maddock 2008.\n#  Use, modification and distribution are subject to the\n#  Boost Software License, Version 1.0. (See accompanying file\n#  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# Generates PNG files from the SVG masters.\n#\n# Paths to tools come first, change these to match your system:\n#\nmath2svg='m:\\download\\open\\SVGMath-0.3.1\\math2svg.py'\npython='/cygdrive/c/program files/Python27/python.exe'\ninkscape='/cygdrive/c/Program Files (x86)/Inkscape/inkscape.exe'\n# Image DPI:\ndpi=96\n\nfor svgfile in $*; do\n\tpngfile=$(basename $svgfile .svg).png\n\techo Generating $pngfile\n\t\"$inkscape\" -d $dpi -e $(cygpath -a -w $pngfile) $(cygpath -a -w $svgfile)\ndone\n\n\n\n\n\n\n\n\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "for file in ../../../../boost/math/tools/*.hpp; do \ncat > tools_$(basename $file .hpp)_inc_test.cpp  << EOF; \n//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/tools/$(basename $file)>\n// #includes all the files that it needs to.\n//\n#include <boost/math/tools/$(basename $file .hpp).hpp>\n\nEOF\ndone\n\nfor file in ../../../../boost/math/distributions/*.hpp; do \ncat > dist_$(basename $file .hpp)_incl_test.cpp  << EOF; \n//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/distributions/$(basename $file)>\n// #includes all the files that it needs to.\n//\n#include <boost/math/distributions/$(basename $file .hpp).hpp>\n\nEOF\ndone\n\nfor file in ../../../../boost/math/special_functions/*.hpp; do \ncat > sf_$(basename $file .hpp)_incl_test.cpp  << EOF; \n//  Copyright John Maddock 2006.\n//  Use, modification and distribution are subject to the\n//  Boost Software License, Version 1.0. (See accompanying file\n//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n//\n// Basic sanity check that header <boost/math/special_functions/$(basename $file)>\n// #includes all the files that it needs to.\n//\n#include <boost/math/special_functions/$(basename $file .hpp).hpp>\n\nEOF\ndone\n\n\n", "num_lines": 47}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nfor svg in *.svg\ndo\n  rsvg-convert -o $(echo $svg | sed 's/\\.svg/\\.png/') -f png $svg\ndone\n\n", "num_lines": 8}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#  Copyright John Maddock 2008.\n#  Use, modification and distribution are subject to the\n#  Boost Software License, Version 1.0. (See accompanying file\n#  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n#\n# Generates SVG and PNG files from the MML masters.\n#\n# Paths to tools come first, change these to match your system:\n#\nmath2svg='m:\\download\\open\\SVGMath-0.3.1\\math2svg.py'\npython=/cygdrive/c/Python26/python.exe\ninkscape=/cygdrive/c/progra~1/Inkscape/inkscape\n# Image DPI:\ndpi=120\n\nfor mmlfile in $*; do\n\tsvgfile=$(basename $mmlfile .mml).svg\n\tpngfile=$(basename $svgfile .svg).png\n\ttempfile=temp.mml\n\t# strip html wrappers put in by MathCast:\n\tcat $mmlfile | tr -d \"\\r\\n\" | sed -e 's/.*\\(<math[^>]*>.*<\\/math>\\).*/\\1/' > $tempfile\n\t\n\techo Generating $svgfile\n\t$python $math2svg $tempfile > $svgfile\n\techo Generating $pngfile\n\t$inkscape -d $dpi -e $(cygpath -a -w $pngfile) $(cygpath -a -w $svgfile)\n\trm $tempfile\ndone\n\n\n\n\n\n", "num_lines": 34}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n#  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)\n#\n#  Distributed under the Boost Software License, Version 1.0. (See\n#  accompanying file LICENSE or copy at\n#  http://www.boost.org/LICENSE_1_0.txt)\n#\n\nset -euo pipefail\n\ncd \"$(dirname \"$0\")\"\nrm -f html/*\ndoxygen\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright 2019 - 2020 Alexander Grund\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt)\n\nset -euo pipefail\n\ncd \"$(dirname \"$0\")/..\"\n\nif ! [ -e \"tools/create_standalone.sh\" ]; then\n  echo \"Could not change to repo root\"\n  exit 1\nfi\n\ntargetFolder=\"${1:-nowide_standalone}\"\n\n# If target folder exists fail, unless it is the default in which case it is removed\nif [ -e \"$targetFolder\" ]; then\n  if [[ \"$targetFolder\" == \"nowide_standalone\" ]]; then\n    rm -r \"$targetFolder\"\n  else\n    echo \"Target folder $targetFolder exists\"\n    exit 1\n  fi\nfi\n\nmkdir -p \"$targetFolder\"/include\n\ncp -r include/boost/nowide \"$targetFolder\"/include\ncp -r config src test cmake CMakeLists.txt LICENSE README.md \"$targetFolder\"\ncp standalone/*.hpp \"$targetFolder\"/include/nowide\nmv \"$targetFolder/cmake/BoostAddWarnings.cmake\" \"$targetFolder/cmake/NowideAddWarnings.cmake\"\nfind \"$targetFolder\" -name 'Jamfile*' -delete\n\nSOURCES=$(find \"$targetFolder\" -name '*.hpp' -or -name '*.cpp')\nSOURCES_NO_BOOST=$(echo \"$SOURCES\" | grep -v 'filesystem.hpp')\n\nsed 's/BOOST_NOWIDE_/NOWIDE_/g' -i $SOURCES\nsed 's/BOOST_/NOWIDE_/g' -i $SOURCES\nsed 's/boost::nowide/nowide/g' -i $SOURCES\nsed 's/boost::/nowide::/g' -i $SOURCES_NO_BOOST\nsed '/namespace boost/d' -i $SOURCES\nsed 's/<boost\\/nowide\\//<nowide\\//g' -i $SOURCES\nsed 's/<boost\\//<nowide\\//g' -i $SOURCES_NO_BOOST\nsed '/config\\/abi_/d' -i $SOURCES\n\nCMLs=$(find \"$targetFolder\" -name 'CMakeLists.txt' -or -name '*.cmake')\n\nsed 's/ BOOST_ALL_NO_LIB//' -i $CMLs\nsed 's/BOOST_NOWIDE_/NOWIDE_/g' -i $CMLs\nsed 's/Boost_NOWIDE_/NOWIDE_/g' -i $CMLs\nsed 's/boost_nowide/nowide/g' -i $CMLs\nsed 's/boost_/nowide_/g' -i $CMLs\nsed 's/Boost::nowide/nowide::nowide/g' -i $CMLs\nsed 's/Boost/Nowide/g' -i $CMLs\nsed 's/ OR BOOST_SUPERPROJECT_SOURCE_DIR//' -i $CMLs\n\nsed '/PUBLIC BOOST_NOWIDE_NO_LIB)/d' -i \"$targetFolder/CMakeLists.txt\"\nsed '/^if(BOOST_SUPERPROJECT_SOURCE_DIR/,/^endif/d' -i \"$targetFolder/CMakeLists.txt\"\nsed '/^elseif(BOOST_SUPERPROJECT_SOURCE_DIR)/,/^else/{/^else(/!d}' -i \"$targetFolder/CMakeLists.txt\"\nsed '/^if(NOT BOOST_SUPERPROJECT_SOURCE_DIR)/,/^endif/{/^if/d;/^endif/d}' -i \"$targetFolder/CMakeLists.txt\"\nsed 's/NAMESPACE Nowide CONFIG_FILE.*$/NAMESPACE nowide)/' -i \"$targetFolder/CMakeLists.txt\"\n\nsed '/^if(NOT BOOST_SUPERPROJECT_SOURCE_DIR)/,/^endif/d' -i \"$targetFolder/test/CMakeLists.txt\"\nsed '/Nowide::filesystem/d' -i \"$targetFolder/test/CMakeLists.txt\"\n\nsed '/^# Those 2 should work the same/,/^elseif/d' -i \"$targetFolder/test/cmake_test/CMakeLists.txt\"\nsed '/^else/,/^endif/d' -i \"$targetFolder/test/cmake_test/CMakeLists.txt\"\n", "num_lines": 70}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Running on ${HOSTNAME}\"\n\nout_dir=perf_${HOSTNAME}\nmkdir -p ${out_dir}\n\nfor N in 256 1024 4096 16384 65536 262144 1048576 4194304 16777216 67108864\ndo\n    steps=`expr 4 \\* 67108864 / ${N}`\n    for exe in \"roessler\" \"roessler_simd\"\n    do\n        rm -f ${out_dir}/${exe}_N${N}.times\n        for i in {0..4}\n        do\n            likwid-pin -cS0:0 ./${exe} ${N} ${steps} >> ${out_dir}/${exe}_N${N}.times\n        done\n        for perf_ctr in \"FLOPS_DP\" \"FLOPS_AVX\" \"L2\" \"L3\" \"MEM\"\n        do\n            likwid-perfctr -CS0:0 -g ${perf_ctr} ./${exe} ${N} ${steps} > ${out_dir}/${exe}_N${N}_${perf_ctr}.perf\n        done\n    done\ndone\n", "num_lines": 23}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) 2021 Antony Polukhin\n#\n# Distributed under the Boost Software License, Version 1.0. (See accompanying\n# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\necho \"***** Making target path\"\nTARGET_PATH=\"`dirname \\\"$0\\\"`/../../pfr_non_boost\"\nrm -rf ${TARGET_PATH}/*\nmkdir -p ${TARGET_PATH}\nTARGET_PATH=`cd \"${TARGET_PATH}\";pwd`\n\nSOURCE_PATH=\"`dirname \\\"$0\\\"`/..\"\nSOURCE_PATH=`cd \"${SOURCE_PATH}\";pwd`\n\necho \"***** Copying from ${SOURCE_PATH} to ${TARGET_PATH}\"\ncp -rf ${SOURCE_PATH}/* ${TARGET_PATH}\n\nmv ${TARGET_PATH}/include/boost/* ${TARGET_PATH}/include/\nrm -rf ${TARGET_PATH}/include/boost\nrm -rf ${TARGET_PATH}/test\nrm ${TARGET_PATH}/misc/strip_boost_namespace.sh\nrm -rf ${TARGET_PATH}/meta\n\necho \"***** Changing sources\"\nfind ${TARGET_PATH} -type f | xargs sed -i 's|namespace boost { ||g'\nfind ${TARGET_PATH} -type f | xargs sed -i 's|namespace boost {||g'\nfind ${TARGET_PATH} -type f | xargs sed -i 's|} // namespace boost::| // namespace |g'\n\nfind ${TARGET_PATH} -type f | xargs sed -i 's/::boost::pfr/::pfr/g'\nfind ${TARGET_PATH} -type f | xargs sed -i 's/boost::pfr/pfr/g'\nfind ${TARGET_PATH} -type f | xargs sed -i 's/BOOST_PFR_/PFR_/g'\nfind ${TARGET_PATH} -type f | xargs sed -i 's|boost/pfr|pfr|g'\n\nfind ${TARGET_PATH}/doc -type f | xargs sed -i 's|boost.pfr.|pfr.|g'\nfind ${TARGET_PATH}/doc -type f | xargs sed -i 's|Boost.PFR|PFR|g'\n\nsed -i  's|# \\[Boost.PFR\\](https://boost.org/libs/pfr)|# [PFR](https://apolukhin.github.io/pfr_non_boost/)|g' ${TARGET_PATH}/README.md\n\necho -n \"***** Testing: \"\nif g++-9 -std=c++17 -DPFR_USE_LOOPHOLE=0 -DPFR_USE_CPP17=1 -I ${TARGET_PATH}/include/ ${TARGET_PATH}/example/motivating_example0.cpp && ./a.out > /dev/null; then\n    echo -n \"OK\"\nelse\n    echo -n \"FAIL\"\n    exit 2\nfi\nif g++-9 -std=c++17 -DPFR_USE_LOOPHOLE=1 -DPFR_USE_CPP17=0 -I ${TARGET_PATH}/include/ ${TARGET_PATH}/example/motivating_example0.cpp && ./a.out > /dev/null; then\n    echo -n \", OK\"\nelse\n    echo -n \", FAIL\"\n    exit 3\nfi\n\nif g++-9 -std=c++17 -DPFR_USE_LOOPHOLE=0 -DPFR_USE_CPP17=0 -I ${TARGET_PATH}/include/ ${TARGET_PATH}/example/get.cpp && ./a.out > /dev/null; then\n    echo -e \", OK\"\nelse\n    echo -e \", FAIL\"\n    exit 4\nfi\n\nrm a.out || :\n\necho \"***** Done\"\n", "num_lines": 65}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Usage:\n# LLVM_OS: LLVM OS release to obtain clang binaries. Only needed for clang install.\n# LLVM_VER: The LLVM toolset version to point the repo at.\n# PACKAGES: Compiler packages to install.\n\nset -e\necho \">>>>>\"\necho \">>>>> APT: REPO..\"\necho \">>>>>\"\nsudo -E apt-add-repository -y \"ppa:ubuntu-toolchain-r/test\"\nif test -n \"${LLVM_OS}\" -a -n \"${LLVM_VER}\" ; then\n\twget -O - https://apt.llvm.org/llvm-snapshot.gpg.key | sudo apt-key add -\n\tsudo -E apt-add-repository \"deb http://apt.llvm.org/${LLVM_OS}/ llvm-toolchain-${LLVM_OS}-${LLVM_VER} main\"\nfi\necho \">>>>>\"\necho \">>>>> APT: UPDATE..\"\necho \">>>>>\"\nsudo -E apt-get -o Acquire::Retries=3 update\necho \">>>>>\"\necho \">>>>> APT: INSTALL ${PACKAGES}..\"\necho \">>>>>\"\nsudo -E apt-get -o Acquire::Retries=3 -yq --no-install-suggests --no-install-recommends install ${PACKAGES}\n\n# Use, modification, and distribution are\n# subject to the Boost Software License, Version 1.0. (See accompanying\n# file LICENSE.txt)\n#\n# Copyright Rene Rivera 2020.\n", "num_lines": 31}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Usage:\n# XCODE_VERSION = Dotted version of Xcode to install and make active.\n# XCODE_INSTALL_USER = Account name for developer.apple.com without TFA.\n# XCODE_INSTALL_PASSWORD = Password for that account.\n\nset -e\nsudo gem install xcode-install\nxcversion update\necho \">>>>>\"\necho \">>>>> AVAILABLE..\"\necho \">>>>>\"\nxcversion list\necho \">>>>>\"\necho \">>>>> INSTALLL: Xcode ${XCODE_VERSION}..\"\necho \">>>>>\"\nxcversion --verbose --no-progress --no-clean --no-show-release-notes install ${XCODE_VERSION}\necho \"\"\necho \">>>>>\"\necho \">>>>> INSTALL: CLI Tools..\"\necho \">>>>>\"\nxcversion --verbose install-cli-tools\necho \"\"\necho \">>>>>\"\necho \">>>>> AVAILABLE..\"\necho \">>>>>\"\nxcversion list\necho \">>>>>\"\necho \">>>>> SELECT: Xcode ${XCODE_VERSION}..\"\necho \">>>>>\"\nxcversion select ${XCODE_VERSION} --symlink\n\n# Use, modification, and distribution are\n# subject to the Boost Software License, Version 1.0. (See accompanying\n# file LICENSE.txt)\n#\n# Copyright Rene Rivera 2020.\n", "num_lines": 39}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2017 James E. King III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform a bjam build\n# cwd should be $BOOST_ROOT/libs/$SELF before running\n#\n\nset -ex\n\n# default language level: c++03\nif [[ -z \"$CXXSTD\" ]]; then\n    CXXSTD=03\nfi\n\n$BOOST_ROOT/b2 . toolset=$TOOLSET cxxstd=$CXXSTD $CXXFLAGS $DEFINES $LINKFLAGS $TESTFLAGS $B2_ADDRESS_MODEL $B2_LINK $B2_THREADING $B2_VARIANT -j3 $*\n", "num_lines": 20}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2017, 2018 James E. King III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform codecov.io integration\n#\n\n###\n### NOTE: Make sure you grab .codecov.yml\n###\n\n# assumes cwd is the top level directory of the boost project\n# assumes an environment variable $SELF is the boost project name\n\nset -ex\n\nB2_VARIANT=debug\nci/build.sh cxxflags=-fprofile-arcs cxxflags=-ftest-coverage linkflags=-fprofile-arcs linkflags=-ftest-coverage\n\n# switch back to the original source code directory\ncd $TRAVIS_BUILD_DIR\n\n# get the version of lcov\nlcov --version\n\n# coverage files are in ../../b2 from this location\nlcov --gcov-tool=gcov-7 --rc lcov_branch_coverage=1 --base-directory \"$BOOST_ROOT/libs/$SELF\" --directory \"$BOOST_ROOT\" --capture --output-file all.info\n\n# all.info contains all the coverage info for all projects - limit to ours\nlcov --gcov-tool=gcov-7 --rc lcov_branch_coverage=1 --extract all.info \"*/boost/$SELF/*\" \"*/libs/$SELF/src/*\" --output-file coverage.info\n\n# dump a summary on the console - helps us identify problems in pathing\nlcov --gcov-tool=gcov-7 --rc lcov_branch_coverage=1 --list coverage.info\n\n#\n# upload to codecov.io\n#\ncurl -s https://codecov.io/bash > .codecov\nchmod +x .codecov\n./.codecov -f coverage.info -X gcov -x \"gcov-7\"\n", "num_lines": 44}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2017 James E. King III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform a Coverity Scan build\n# To skip the coverity integration download (which is huge) if\n# you already have it from a previous run, add --skipdownload\n#\n\n#\n# Environment Variables\n#\n# COVERITY_SCAN_NOTIFICATION_EMAIL  - email address to notify\n# COVERITY_SCAN_TOKEN               - the Coverity Scan token (should be secure)\n# SELF                              - the boost libs directory name\n\nset -ex\n\npushd /tmp\nif [[ \"$1\" != \"--skipdownload\" ]]; then\n  rm -rf coverity_tool.tgz cov-analysis*\n  wget https://scan.coverity.com/download/linux64 --post-data \"token=$COVERITY_SCAN_TOKEN&project=boostorg/$SELF\" -O coverity_tool.tgz\n  tar xzf coverity_tool.tgz\nfi\nCOVBIN=$(echo $(pwd)/cov-analysis*/bin)\nexport PATH=$COVBIN:$PATH\npopd\n\nci/build.sh clean\nrm -rf cov-int/\ncov-build --dir cov-int ci/build.sh\ntar cJf cov-int.tar.xz cov-int/\ncurl --form token=\"$COVERITY_SCAN_TOKEN\" \\\n     --form email=\"$COVERITY_SCAN_NOTIFICATION_EMAIL\" \\\n     --form file=@cov-int.tar.xz \\\n     --form version=\"$(git describe --tags)\" \\\n     --form description=\"boostorg/$SELF\" \\\n     https://scan.coverity.com/builds?project=\"boostorg/$SELF\"\n\n", "num_lines": 43}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2018 James E. King III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform a cppcheck\n# cwd should be $BOOST_ROOT before running\n#\n\nset -ex\n\n# default language level: c++03\nif [[ -z \"$CXXSTD\" ]]; then\n    CXXSTD=03\nfi\n\n# Travis' ubuntu-trusty comes with cppcheck 1.62 which is pretty old\n# default cppcheck version: 1.82\nif [[ -z \"$CPPCHKVER\" ]]; then\n    CPPCHKVER=1.82\nfi\n\npushd ~\nwget https://github.com/danmar/cppcheck/archive/$CPPCHKVER.tar.gz\ntar xzf $CPPCHKVER.tar.gz\nmkdir cppcheck-build\ncd cppcheck-build\ncmake ../cppcheck-$CPPCHKVER -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=OFF -DCMAKE_INSTALL_PREFIX=~/cppcheck\nmake -j3 install\npopd\n\n~/cppcheck/bin/cppcheck -I. --std=c++$CXXSTD --enable=all --error-exitcode=1 \\\n         --force --check-config --suppress=*:boost/preprocessor/tuple/size.hpp \\\n         -UBOOST_USER_CONFIG -UBOOST_COMPILER_CONFIG -UBOOST_STDLIB_CONFIG -UBOOST_PLATFORM_CONFIG \\\n         libs/$SELF 2>&1 | grep -v 'Cppcheck does not need standard library headers'\n\n", "num_lines": 39}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#  Copyright 2012 Eric Niebler\n#\n#  Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\nrsync --delete --rsh=ssh --recursive -p html/* eric_niebler,boost-sandbox@web.sourceforge.net:/home/groups/b/bo/boost-sandbox/htdocs/libs/proto/doc/html\n\nrsync --delete --rsh=ssh --recursive -p src/* eric_niebler,boost-sandbox@web.sourceforge.net:/home/groups/b/bo/boost-sandbox/htdocs/libs/proto/doc/src\n", "num_lines": 11}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nsh comp_ptr_container.sh\nsh comp_reversible_ptr_container.sh\nsh comp_ptr_sequence_adapter.sh\nsh comp_associative_ptr_container.sh\nsh comp_ptr_set_adapter.sh\n\n", "num_lines": 18}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nsh comp_ptr_container.sh\nsh comp_reference.sh\nsh comp_faq.sh\nsh comp_tutorial.sh\nsh comp_guidelines.sh\nsh comp_headers.sh\nsh comp_examples.sh\nsh comp_conventions.sh\nsh comp_rever_ptr_container.sh\nsh comp_ptr_sequence_adapter.sh\nsh comp_assoc_ptr_container.sh\nsh comp_ptr_set_adapter.sh\nsh comp_ptr_multiset_adapter.sh\nsh comp_ptr_map_adapter.sh\nsh comp_ptr_multimap_adapter.sh\nsh comp_ptr_array.sh\nsh comp_ptr_vector.sh\nsh comp_ptr_deque.sh\nsh comp_ptr_list.sh\nsh comp_ptr_map.sh\nsh comp_ptr_multimap.sh\nsh comp_ptr_set.sh\nsh comp_ptr_multiset.sh\nsh comp_indirect_fun.sh\nsh comp_compatible_smart_ptr.sh\n\n\n", "num_lines": 39}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py associative_ptr_container.rst > associative_ptr_container.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py compatible_smart_ptr.rst > compatible_smart_ptr.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py conventions.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > conventions.html\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py examples.rst > examples.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py faq.rst > faq.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py guidelines.rst > guidelines.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py headers.rst > headers.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py indirect_fun.rst > indirect_fun.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_array.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_array.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_container.rst > ptr_container.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_deque.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_deque.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_inserter.rst > ptr_inserter.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_list.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_list.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_map.rst > ptr_map.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_map_adapter.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_map_adapter.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_multimap.rst > ptr_multimap.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_multimap_adapter.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_multimap_adapter.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_multiset.rst > ptr_multiset.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_multiset_adapter.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_multiset_adapter.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_sequence_adapter.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_sequence_adapter.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_set.rst > ptr_set.html\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_set_adapter.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_set_adapter.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py ptr_vector.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > ptr_vector.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py reference.rst > reference.html\n", "num_lines": 13}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py reversible_ptr_container.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > reversible_ptr_container.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#//\n#// Boost.Pointer Container\n#//\n#//  Copyright Thorsten Ottosen 2003-2005. Use, modification and\n#//  distribution is subject to the Boost Software License, Version\n#//  1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#//  http://www.boost.org/LICENSE_1_0.txt)\n#//\n#// For more information, see http://www.boost.org/libs/ptr_container/\n#//\n\nrst2html.py tutorial.rst |\n    sed 's@compatible-smart-ptr@<a class=\"reference external\" href=\"compatible_smart_ptr.html\"><em>compatible-smart-ptr</em></a>@g' > tutorial.html\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test x = x$BOOST_ROOT \nthen\n    echo BOOST_ROOT not set\n    exit 1\nfi\nxsltproc --nonet --xinclude bb2db.xsl safe_numerics.xml | xsltproc --xinclude --nonet --stringparam base.dir ebooktmp db2epub.xsl -\ncp *.png ebooktmp/OEBPS/\nxsltproc --xinclude --nonet opf.xsl ebooktmp/OEBPS/package.opf >ebooktmp/OEBPS/t.opf\n# mv ebooktmp/OEBPS/t.opf ebooktmp/OEBPS/package.opf\ncd ebooktmp\nzip -r -X ../book.epub mimetype META-INF OEBPS \ncd -\n", "num_lines": 13}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test x = x$BOOST_ROOT \nthen\n    echo BOOST_ROOT not set\n    exit 1\nfi\nxsltproc --nonet --xinclude bb2db.xsl safe_numerics.xml | xsltproc --nonet db2html.xsl -\ncp pre-boost.jpg ../html\ncp pre-boost.jpg ../html/eliminate_runtime_penalty\ncp pre-boost.jpg ../html/promotion_policies\ncp pre-boost.jpg ../html/tutorial\ncp StepperMotor.gif ../html/\ncp stepper_profile.png ../html/\ncp $BOOST_ROOT/doc/src/boostbook.css ../html\ncp -R $BOOST_ROOT/doc/html/images ../html\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test x = x$BOOST_ROOT \nthen\n    echo BOOST_ROOT not set\n    exit 1\nfi\n#use -r switch on fop for relaxed validation\nxsltproc --xinclude --nonet bb2db.xsl safe_numerics.xml \\\n| fop -r -dpi 300 -xsl db2fo.xsl -xml - -pdf ../safe_numerics.pdf\n\n# equivalent alternative?\n# xsltproc --xinclude --nonet bb2db.xsl safe_numerics.xml \\\n# | xsltproc --xinclude --nonet db2fo.xsl - \\\n# | fop -r -dpi 300 -fo - -pdf safe_numerics.pdf\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test x = x$BOOST_ROOT \nthen\n    echo BOOST_ROOT not set\n    exit 1\nfi\n#use -r switch on fop for relaxed validation\nxsltproc --xinclude --nonet bb2db.xsl proposal.xml \\\n| fop -r -dpi 300 -xsl db2fo.xsl -xml - -pdf proposal.pdf\n\n# equivalent alternative?\n# xsltproc --xinclude --nonet bb2db.xsl safe_numerics.xml \\\n# | xsltproc --xinclude --nonet db2fo.xsl - \\\n# | fop -r -dpi 300 -fo - -pdf safe_numerics.pdf\n\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "if test x = x$BOOST_ROOT \nthen\n    echo BOOST_ROOT not set\nfi\nmkdir html\nxsltproc --xinclude --nonet bb2db.xsl accu.xml > accudocbook4.xml\nxsltproc --nonet db2html.xsl accudocbook4.xml\ncp accu_logo.png html\ncp $BOOST_ROOT/doc/src/boostbook.css html\ncp -R $BOOST_ROOT/doc/html/images html\n", "num_lines": 11}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#use -r switch on fop for relaxed validation\nxsltproc --xinclude --nonet bb2db.xsl accu.xml > accudocbook4.xml\nfop -r -dpi 300 -xsl db2fo.xsl -xml accudocbook4.xml -pdf accu.pdf\n", "num_lines": 4}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# build and run the tests leaving the executables in place\n\n# (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . \n# Use, modification and distribution is subject to the Boost Software\n# License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n# http://www.boost.org/LICENSE_1_0.txt)\n\n# profile.sh --toolset=gcc preserve-test-targets=on variant=profile\nif test $# -eq 0\nthen\n    echo \"Usage: $0 <bjam arguments>\"\n    echo \"Typical bjam arguements are:\"\n    echo \"  toolset=msvc-7.1,gcc\"\n    echo \"  link=static,shared\"\n    echo \"  threading=single,multi\"\n    echo \"  -sBOOST_ARCHIVE_LIST=<archive name>\"\nelse\n    bjam --dump-tests variant=profile preserve-test-targets=on $@ >bjam.log 2>&1\n    process_jam_log --v2 <bjam.log\n\n    # for each test directory\n\n    for dir in                                                             \\\n        ../../../bin.v2/libs/serialization/performance/*/gcc*/profile   \\\n        ../../../bin.v2/libs/serialization/performance/*/gcc*/*/profile\n    do\n        # execute test\n        for exe in $dir/*.exe\n        do\n            # execute the test\n            echo executing $exe\n            $exe\n            # copy profile to test directory\n            gprof $exe gmon.out >$dir/profile.txt\n        done\n    done\n\n    library_status library_status.html links.html\nfi\n", "num_lines": 40}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   N U M B E R S               ==\"\necho \"==                                                              ==\"\necho \"==              C L A N G      C O M P I L E R                  ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\nclang++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\nclang++ ./benchmark_numbers.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_numbers\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_numbers\ndate\nrm input.bin\nrm file_generator\nrm benchmark_numbers\necho \".\"\n\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   O B J E C T S               ==\"\necho \"==                                                              ==\"\necho \"==              C L A N G      C O M P I L E R                  ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\n\nclang++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\nclang++ ./benchmark_objects.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_objects\necho \".\"\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 60 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_objects\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_objects\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==             B E N C H M A R K   S T R I N G S                ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_strings.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_strings\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_strings\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_strings\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   N U M B E R S               ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_numbers.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_numbers\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_numbers\ndate\nrm input.bin\nrm file_generator\nrm benchmark_numbers\necho \".\"\n\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   O B J E C T S               ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\n\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_objects.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_objects\necho \".\"\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 60 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_objects\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_objects\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==             B E N C H M A R K   S T R I N G S                ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_strings.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -pthread  -s  -lpthread  -o benchmark_strings\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_strings\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_strings\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   N U M B E R S               ==\"\necho \"==                                                              ==\"\necho \"==               C L A N G      C O M P I L E R                 ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\nclang++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\nclang++ ./benchmark_numbers.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s -o benchmark_numbers\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_numbers\necho \".\"\ndate\nrm input.bin\nrm file_generator\nrm benchmark_numbers\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 28}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   O B J E C T S               ==\"\necho \"==                                                              ==\"\necho \"==               C L A N G    C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\n\nclang++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\nclang++ ./benchmark_objects.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s  -o benchmark_objects\necho \".\"\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 45 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_objects\ndate\necho \".\"\nrm input.bin\nrm file_generator\nrm benchmark_objects\n\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==             B E N C H M A R K   S T R I N G S                ==\"\necho \"==                                                              ==\"\necho \"==               C L A N G    C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\nclang++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\nclang++ ./benchmark_strings.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s  -o benchmark_strings\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_strings\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_strings\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   N U M B E R S               ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_numbers.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s -o benchmark_numbers\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_numbers\ndate\nrm input.bin\nrm file_generator\nrm benchmark_numbers\necho \".\"\n\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==              B E N C H M A R K   O B J E C T S               ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\n\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_objects.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s  -o benchmark_objects\necho \".\"\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 45 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_objects\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_objects\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "clear\necho \"==================================================================\"\necho \"==             B E N C H M A R K   S T R I N G S                ==\"\necho \"==                                                              ==\"\necho \"==                 G C C      C O M P I L E R                   ==\"\necho \"==================================================================\"\necho \".\"\necho \"C O M P I L I N G . . . . . . . . . . .\"\necho \".\"\ng++ ./file_generator.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include  -s  -o file_generator\n\ng++ ./benchmark_strings.cpp -std=c++11 -march=native -w -fexceptions -O3 -I../../include -s  -o benchmark_strings\n\necho \"R U N N I N G . . . . . . . . . . .\"\necho \"( The time needed is around 10 minutes depending of your machine )\"\n./file_generator input.bin 125000000\necho \".\"\ndate\n./benchmark_strings\ndate\n\nrm input.bin\nrm file_generator\nrm benchmark_strings\necho \".\"\necho \".\"\necho \"E N D\"\necho \".\"\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#==============================================================================\n#   Copyright (c) 2002 Joel de Guzman\n#   http://spirit.sourceforge.net/\n#\n#   Use, modification and distribution is subject to the Boost Software\n#   License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#   http://www.boost.org/LICENSE_1_0.txt)\n#==============================================================================\n#!/bin/sh\n#./test1 << EOS || exit 1\n#123321\n#EOS\n./binary_tests || exit 1\n./binders_tests || exit 1\n./functors_tests || exit 1\n./iostream_tests << EOS || exit 1\n123321\nEOS\n./mixed_binary_tests || exit 1\n./more_expressions_tests || exit 1\n./primitives_tests || exit 1\n./statements_tests || exit 1\n./stl_tests || exit 1\n./tuples_tests || exit 1\n./unary_tests || exit 1\n", "num_lines": 26}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2017 - 2019 James E. King III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform codecov.io integration\n#\n\n# assumes cwd is the top level directory of the boost project\n# assumes an environment variable $SELF is the boost project name\n\nset -ex\n\n. ci/enforce.sh\n\nif [ -z \"$GCOV\" ]; then\n    if [ \"${B2_TOOLSET%%-*}\" == \"gcc\" ]; then\n        ver=\"${B2_TOOLSET#*-}\"\n        GCOV=gcov-${ver}\n    else\n        GCOV=gcov-7 # default\n    fi\nfi\n\n# lcov after 1.14 needs this\n# sudo apt install --no-install-recommends -y libperlio-gzip-perl libjson-perl\n\n# install the latest lcov we know works\n# some older .travis.yml files install the tip which may be unstable\nrm -rf /tmp/lcov\npushd /tmp\ngit clone -b v1.14 https://github.com/linux-test-project/lcov.git\nexport PATH=/tmp/lcov/bin:$PATH\nwhich lcov\nlcov --version\npopd\n\nB2_VARIANT=variant=debug\nci/travis/build.sh cxxflags=--coverage linkflags=--coverage \n#cxxflags=-fprofile-arcs cxxflags=-ftest-coverage linkflags=-fprofile-arcs linkflags=-ftest-coverage\n\n# switch back to the original source code directory\ncd $TRAVIS_BUILD_DIR\n\n# coverage files are in ../../b2 from this location\nlcov --gcov-tool=$GCOV --rc lcov_branch_coverage=0 --base-directory \"$BOOST_ROOT/libs/$SELF\" --directory \"$BOOST_ROOT\" --capture --output-file all.info\n\n# all.info contains all the coverage info for all projects - limit to ours\n# first we extract the interesting headers for our project then we use that list to extract the right things\nfor f in `for f in include/boost/*; do echo $f; done | cut -f2- -d/`; do echo \"*/$f*\"; done > /tmp/interesting\necho headers that matter:\ncat /tmp/interesting\nxargs -L 999999 -a /tmp/interesting lcov --gcov-tool=$GCOV --rc lcov_branch_coverage=1 --extract all.info {} \"*/libs/$SELF/src/*\" --output-file coverage.info\n\n# dump a summary on the console - helps us identify problems in pathing\nlcov --gcov-tool=$GCOV --rc lcov_branch_coverage=1 --list coverage.info\n\n#\n# upload to codecov.io\n#\ncurl -s https://codecov.io/bash > .codecov\nchmod +x .codecov\n./.codecov -f coverage.info -X gcov -x \"$GCOV\"", "num_lines": 65}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nwhich lcov 1>/dev/null 2>&1\nif [ $? != 0 ]\nthen\n    echo \"You need to have lcov installed in order to generate the test coverage report\"\n    exit 1\nfi\n\nbjam toolset=gcc-4.9.2 clean\nbjam toolset=gcc-4.9.2 runtime-param-test\n\n# Generate html report\nlcov --base-directory . --directory ../../../bin.v2/libs/test/test/runtime-param-test.test/gcc-4.9.2/debug/utils-ts -c -o runtime-param-test.info\nlcov --remove runtime-param-test.info \"/usr*\" -o runtime-param-test.info # remove output for external libraries\nlcov --remove runtime-param-test.info  \"boost\" \"/boost/c*\" \"/boost/d*\"  \"/boost/e*\"  \"/boost/f*\"  \"/boost/l*\" \"/boost/m*\" \"/boost/s*\" -o runtime-param-test.info # remove output for other boost libs\nrm -rf ./coverage\ngenhtml -o ./coverage -t \"runtime-param-test coverage\" --num-spaces 4 runtime-param-test.info\n\n#Clean up\nrm *.info", "num_lines": 21}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n#\n# Copyright 2017 James E. King, III\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n#      http://www.boost.org/LICENSE_1_0.txt)\n#\n# Bash script to run in travis to perform a Coverity Scan build\n#\n\n#\n# Environment Variables\n#\n# COVERITY_SCAN_NOTIFICATION_EMAIL  - email address to notify\n# COVERITY_SCAN_TOKEN               - the Coverity Scan token (should be secure)\n# SELF                              - the boost libs directory name\n\nset -ex\n\npushd /tmp\nrm -rf coverity_tool.tgz cov-analysis*\nwget -nv https://scan.coverity.com/download/linux64 --post-data \"token=$COVERITY_SCAN_TOKEN&project=boostorg/$SELF\" -O coverity_tool.tgz\ntar xzf coverity_tool.tgz\nCOVBIN=$(echo $(pwd)/cov-analysis*/bin)\nexport PATH=$COVBIN:$PATH\npopd\n\ncd libs/$SELF/test\n../../../b2 toolset=gcc clean\nrm -rf cov-int/\ncov-build --dir cov-int ../../../b2 toolset=gcc -q -j3\ntar cJf cov-int.tar.xz cov-int/\ncurl --form token=\"$COVERITY_SCAN_TOKEN\" \\\n     --form email=\"$COVERITY_SCAN_NOTIFICATION_EMAIL\" \\\n     --form file=@cov-int.tar.xz \\\n     --form version=\"$(git describe --tags)\" \\\n     --form description=\"boostorg/$SELF\" \\\n     https://scan.coverity.com/builds?project=\"boostorg/$SELF\"\n", "num_lines": 39}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#   Copyright (c) 2002 Douglas Gregor <doug.gregor -at- gmail.com>\n#\n#   Distributed under the Boost Software License, Version 1.0.\n#   (See accompanying file LICENSE_1_0.txt or copy at\n#   http://www.boost.org/LICENSE_1_0.txt)\n\n# User configuration\n# (MAINTANERS: please, keep in synch with setup_boostbook.py)\nDOCBOOK_XSL_VERSION=1.75.2\nDOCBOOK_DTD_VERSION=4.2\nFOP_VERSION=0.94\nFOP_JDK_VERSION=1.4\n# FOP_MIRROR=http://mirrors.ibiblio.org/pub/mirrors/apache/xmlgraphics/fop/binaries\nFOP_MIRROR=http://archive.apache.org/dist/xmlgraphics/fop/binaries/\nSOURCEFORGE_DOWNLOAD=http://sourceforge.net/projects/docbook/files/\nHTTP_GET_CMD=\"curl -O -L\"\n\n# No user configuration below this point-------------------------------------\n\n# Get the DocBook XSLT Stylesheets\nDOCBOOK_XSL_TARBALL=docbook-xsl-$DOCBOOK_XSL_VERSION.tar.gz\nDOCBOOK_XSL_URL=$SOURCEFORGE_DOWNLOAD/docbook-xsl/$DOCBOOK_XSL_VERSION/$DOCBOOK_XSL_TARBALL\nif test -f $DOCBOOK_XSL_TARBALL; then\n  echo \"Using existing DocBook XSLT Stylesheets (version $DOCBOOK_XSL_VERSION).\"\nelse\n  echo \"Downloading DocBook XSLT Stylesheets version $DOCBOOK_XSL_VERSION...\"\n  $HTTP_GET_CMD $DOCBOOK_XSL_URL\nfi\n\nDOCBOOK_XSL_DIR=\"$PWD/docbook-xsl-$DOCBOOK_XSL_VERSION\"\nif test ! -d docbook-xsl-$DOCBOOK_XSL_VERSION; then\n  echo -n \"Expanding DocBook XSLT Stylesheets into $DOCBOOK_XSL_DIR...\"\n  gunzip -cd $DOCBOOK_XSL_TARBALL | tar xf -\n  echo \"done.\"\nfi\n\n# Get the DocBook DTD\nDOCBOOK_DTD_ZIP=docbook-xml-$DOCBOOK_DTD_VERSION.zip\nDOCBOOK_DTD_URL=http://www.oasis-open.org/docbook/xml/$DOCBOOK_DTD_VERSION/$DOCBOOK_DTD_ZIP\nif test -f $DOCBOOK_DTD_ZIP; then\n  echo \"Using existing DocBook XML DTD (version $DOCBOOK_DTD_VERSION).\"\nelse\n  echo \"Downloading DocBook XML DTD version $DOCBOOK_DTD_VERSION...\"\n  $HTTP_GET_CMD $DOCBOOK_DTD_URL\nfi\n\nDOCBOOK_DTD_DIR=\"$PWD/docbook-dtd-$DOCBOOK_DTD_VERSION\"\nif test ! -d docbook-dtd-$DOCBOOK_DTD_VERSION; then\n  echo -n \"Expanding DocBook XML DTD into $DOCBOOK_DTD_DIR... \"\n  unzip -q $DOCBOOK_DTD_ZIP -d $DOCBOOK_DTD_DIR\n  echo \"done.\"\nfi\n\n# Find xsltproc, doxygen, and java\nOLD_IFS=$IFS\nIFS=:\nfor dir in $PATH; do\n  if test -f $dir/xsltproc && test -x $dir/xsltproc; then\n    XSLTPROC=\"$dir/xsltproc\"\n  fi\n  if test -f $dir/doxygen && test -x $dir/doxygen; then\n    DOXYGEN=\"$dir/doxygen\"\n  fi\n  if test -f $dir/java && test -x $dir/java; then\n    JAVA=\"$dir/java\"\n  fi\ndone\nIFS=$OLD_IFS\n\n# Make sure we have xsltproc\nif test ! -f \"$XSLTPROC\" && test ! -x \"$XSLTPROC\"; then\n  echo \"Searching for xsltproc... NOT FOUND.\";\n  echo \"ERROR: Unable to find xsltproc executable.\"\n  echo \"If you have already installed xsltproc, please set the environment\"\n  echo \"variable XSLTPROC to the xsltproc executable. If you do not have\"\n  echo \"xsltproc, you may download it from http://xmlsoft.org/XSLT/.\"\n  exit 0;\nelse\n  echo \"Searching for xsltproc... $XSLTPROC.\";\nfi\n\n# Just notify the user if we haven't found doxygen.\nif test ! -f \"$DOXYGEN\" && test ! -x \"$DOXYGEN\"; then\n  echo \"Searching for Doxygen... not found.\";\n  echo \"Warning: unable to find Doxygen executable. You will not be able to\"\n  echo \"  use Doxygen to generate BoostBook documentation. If you have Doxygen,\"\n  echo \"  please set the DOXYGEN environment variable to the path of the doxygen\"\n  echo \"  executable.\"\n  HAVE_DOXYGEN=\"no\"\nelse\n  echo \"Searching for Doxygen... $DOXYGEN.\";\n  HAVE_DOXYGEN=\"yes\"\nfi\n\n# Just notify the user if we haven't found Java. Otherwise, go get FOP.\nif test ! -f \"$JAVA\" && test ! -x \"$JAVA\"; then\n  echo \"Searching for Java... not found.\";\n  echo \"Warning: unable to find Java executable. You will not be able to\"\n  echo \"  generate PDF documentation. If you have Java, please set the JAVA\"\n  echo \"  environment variable to the path of the java executable.\"\n  HAVE_FOP=\"no\"\nelse\n  echo \"Searching for Java... $JAVA.\";\n  FOP_TARBALL=\"fop-$FOP_VERSION-bin-jdk$FOP_JDK_VERSION.tar.gz\"\n  FOP_URL=\"$FOP_MIRROR/$FOP_TARBALL\"\n  FOP_DIR=\"$PWD/fop-$FOP_VERSION\"\n  FOP=\"$FOP_DIR/fop\"\n  if test -f $FOP_TARBALL; then\n    echo \"Using existing FOP distribution (version $FOP_VERSION).\"\n  else\n    echo \"Downloading FOP distribution version $FOP_VERSION...\"\n    $HTTP_GET_CMD $FOP_URL\n  fi\n\n  if test ! -d $FOP_DIR; then\n    echo -n \"Expanding FOP distribution into $FOP_DIR... \";\n    gunzip -cd $FOP_TARBALL | tar xf -\n    echo \"done.\";\n  fi\n  HAVE_FOP=\"yes\"\nfi\n\n# Find the input jamfile to configure\nJAM_CONFIG_OUT=\"$HOME/user-config.jam\"\nif test -r \"$HOME/user-config.jam\"; then\n  JAM_CONFIG_IN=\"user-config-backup.jam\"\n  cp $JAM_CONFIG_OUT user-config-backup.jam\n  JAM_CONFIG_IN_TEMP=\"yes\"\n  echo -n \"Updating Boost.Jam configuration in $JAM_CONFIG_OUT... \"\n\nelif test -r \"$BOOST_ROOT/tools/build/user-config.jam\"; then\n  JAM_CONFIG_IN=\"$BOOST_ROOT/tools/build/user-config.jam\";\n  JAM_CONFIG_IN_TEMP=\"no\"\n  echo -n \"Writing Boost.Jam configuration to $JAM_CONFIG_OUT... \"\nelse\n  echo \"ERROR: Please set the BOOST_ROOT environment variable to refer to your\"\n  echo \"Boost installation or copy user-config.jam into your home directory.\"\n  exit 0\nfi\n\ncat > setup_boostbook.awk <<EOF\nBEGIN { using_boostbook = 0; eaten=0 }\n\n/^\\s*using boostbook/ {\n  using_boostbook = 1;\n  print \"using boostbook\";\n  print \"  : $DOCBOOK_XSL_DIR\";\n  print \"  : $DOCBOOK_DTD_DIR\";\n  eaten=1\n}\n\nusing_boostbook==1 && /;/ { using_boostbook = 2 }\nusing_boostbook==1 { eaten=1 }\n\n/^\\s*using xsltproc.*$/ { eaten=1 }\n/^\\s*using doxygen.*$/ { eaten=1 }\n/^\\s*using fop.*$/ { eaten=1 }\n\n/^.*$/             { if (eaten == 0) print; eaten=0 }\n\nEND {\n  if (using_boostbook==0) {\n    print \"using boostbook\";\n    print \"  : $DOCBOOK_XSL_DIR\";\n    print \"  : $DOCBOOK_DTD_DIR\";\n    print \"  ;\"\n  }\n  print \"using xsltproc : $XSLTPROC ;\"\n  if (\"$HAVE_DOXYGEN\" == \"yes\") print \"using doxygen : $DOXYGEN ;\";\n  if (\"$HAVE_FOP\" == \"yes\") print \"using fop : $FOP : : $JAVA ;\";\n}\nEOF\n\nawk -f setup_boostbook.awk $JAM_CONFIG_IN > $JAM_CONFIG_OUT\nrm -f setup_boostbook.awk\necho \"done.\"\n\necho \"Done! Execute \\\"b2\\\" in a documentation directory to generate\"\necho \"documentation with BoostBook. If you have not already, you will need\"\necho \"to compile Boost.Jam.\"\n", "num_lines": 182}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# see the README file for usage etc.\n#\n# ------------------------------------------------------------------\n#  This file is part of bzip2/libbzip2, a program and library for\n#  lossless, block-sorting data compression.\n#\n#  bzip2/libbzip2 version 1.0.8 of 13 July 2019\n#  Copyright (C) 1996-2019 Julian Seward <jseward@acm.org>\n#\n#  Please read the WARNING, DISCLAIMER and PATENTS sections in the \n#  README file.\n#\n#  This program is released under the terms of the license contained\n#  in the file LICENSE.\n# ----------------------------------------------------------------\n\n\nusage() {\n  echo '';\n  echo 'Usage: xmlproc.sh -[option] <filename.xml>';\n  echo 'Specify a target from:';\n  echo '-v      verify xml file conforms to dtd';\n  echo '-html   output in html format (single file)';\n  echo '-ps     output in postscript format';\n  echo '-pdf    output in pdf format';\n  exit;\n}\n\nif test $# -ne 2; then\n  usage\nfi\n# assign the variable for the output type\naction=$1; shift\n# assign the output filename\nxmlfile=$1; shift\n# and check user input it correct\nif !(test -f $xmlfile); then\n  echo \"No such file: $xmlfile\";\n  exit;\nfi\n# some other stuff we will use\nOUT=output\nxsl_fo=bz-fo.xsl\nxsl_html=bz-html.xsl\n\nbasename=$xmlfile\nbasename=${basename//'.xml'/''}\n\nfofile=\"${basename}.fo\"\nhtmlfile=\"${basename}.html\"\npdffile=\"${basename}.pdf\"\npsfile=\"${basename}.ps\"\nxmlfmtfile=\"${basename}.fmt\"\n\n# first process the xmlfile with CDATA tags\n./format.pl $xmlfile $xmlfmtfile\n# so the shell knows where the catalogs live\nexport XML_CATALOG_FILES=/etc/xml/catalog\n\n# post-processing tidy up\ncleanup() {\n  echo \"Cleaning up: $@\" \n  while [ $# != 0 ]\n  do\n    arg=$1; shift;\n    echo \"  deleting $arg\";\n    rm $arg\n  done\n}\n\ncase $action in\n  -v)\n   flags='--noout --xinclude --noblanks --postvalid'\n   dtd='--dtdvalid http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd'\n   xmllint $flags $dtd $xmlfmtfile 2> $OUT \n   egrep 'error' $OUT \n   rm $OUT\n  ;;\n\n  -html)\n   echo \"Creating $htmlfile ...\"\n   xsltproc --nonet --xinclude  -o $htmlfile $xsl_html $xmlfmtfile\n   cleanup $xmlfmtfile\n  ;;\n\n  -pdf)\n   echo \"Creating $pdffile ...\"\n   xsltproc --nonet --xinclude -o $fofile $xsl_fo $xmlfmtfile\n   pdfxmltex $fofile >$OUT </dev/null\n   pdfxmltex $fofile >$OUT </dev/null\n   pdfxmltex $fofile >$OUT </dev/null\n   cleanup $OUT $xmlfmtfile *.aux *.fo *.log *.out\n  ;;\n\n  -ps)\n   echo \"Creating $psfile ...\"\n   xsltproc --nonet --xinclude -o $fofile $xsl_fo $xmlfmtfile\n   pdfxmltex $fofile >$OUT </dev/null\n   pdfxmltex $fofile >$OUT </dev/null\n   pdfxmltex $fofile >$OUT </dev/null\n   pdftops $pdffile $psfile\n   cleanup $OUT $xmlfmtfile $pdffile *.aux *.fo *.log *.out\n#  passivetex is broken, so we can't go this route yet.\n#   xmltex $fofile >$OUT </dev/null\n#   xmltex $fofile >$OUT </dev/null\n#   xmltex $fofile >$OUT </dev/null\n#   dvips -R -q -o bzip-manual.ps *.dvi\n  ;;\n\n  *)\n  usage\n  ;;\nesac\n", "num_lines": 115}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       ZLIB compilation script for the OS/400.\n#\n#\n#       This is a shell script since make is not a standard component of OS/400.\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nTARGETLIB='ZLIB'                # Target OS/400 program library\nSTATBNDDIR='ZLIB_A'             # Static binding directory.\nDYNBNDDIR='ZLIB'                # Dynamic binding directory.\nSRVPGM=\"ZLIB\"                   # Service program.\nIFSDIR='/zlib'                  # IFS support base directory.\nTGTCCSID='500'                  # Target CCSID of objects\nDEBUG='*NONE'                   # Debug level\nOPTIMIZE='40'                   # Optimisation level\nOUTPUT='*NONE'                  # Compilation output option.\nTGTRLS='V6R1M0'                 # Target OS release\n\nexport TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR\nexport TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS\n\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nLIBIFSNAME=\"/QSYS.LIB/${TARGETLIB}.LIB\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       make_module module_name source_name [additional_definitions]\n#\n#       Compile source name into module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n\nmake_module()\n\n{\n    MODULES=\"${MODULES} ${1}\"\n    MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n    CSRC=\"`basename \\\"${2}\\\"`\"\n\n    if action_needed \"${MODIFSNAME}\" \"${2}\"\n    then    :\n    elif [ ! \"`sed -e \\\"/<source name=\\\\\\\"${CSRC}\\\\\\\">/,/<\\\\\\\\/source>/!d\\\" \\\n      -e '/<depend /!d'                                                 \\\n      -e 's/.* name=\\\"\\\\([^\\\"]*\\\\)\\\".*/\\\\1/' < \\\"${TOPDIR}/treebuild.xml\\\" |\n        while read HDR\n        do      if action_needed \\\"${MODIFSNAME}\\\" \\\"${IFSDIR}/include/${HDR}\\\"\n                then    echo recompile\n                        break\n                fi\n        done`\" ]\n    then    return 0\n    fi\n\n    CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('${2}')\"\n    CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST)\"\n    CMD=\"${CMD} LOCALETYPE(*LOCALE) FLAG(10)\"\n    CMD=\"${CMD} INCDIR('${IFSDIR}/include' ${INCLUDES})\"\n    CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n    CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n    CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n    CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n    system \"${CMD}\"\n    LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        basename \"${1}\"                                                 |\n        tr 'a-z-' 'A-Z_'                                                |\n        sed -e 's/\\..*//'                                               \\\n            -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n}\n\n\n#       Force enumeration types to be the same size as integers.\n\ncopy_hfile()\n\n{\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n'\n}\n\n\n################################################################################\n#\n#                             Script initialization.\n#\n################################################################################\n\nSCRIPTDIR=`dirname \"${0}\"`\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in ${TOPDIR}/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nexport SCRIPTDIR TOPDIR\ncd \"${TOPDIR}\"\n\n\n#  Extract the version from the master compilation XML file.\n\nVERSION=`sed -e '/^<package /!d'                                        \\\n            -e 's/^.* version=\"\\([0-9.]*\\)\".*$/\\1/' -e 'q'              \\\n            < treebuild.xml`\nexport VERSION\n\n################################################################################\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB}) TEXT('ZLIB: Data compression API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/ChangeLog\" \"${TOPDIR}/FAQ\"                       \\\n    \"${TOPDIR}/README\" \"${SCRIPTDIR}/README400\"\ndo      MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${TEXT}\\\"`.MBR\"\n\n        if action_needed \"${MEMBER}\" \"${TEXT}\"\n        then    CMD=\"CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})\"\n                CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n\n\n#       Create the OS/400 source program file for the C header files.\n\nSRCPF=\"${LIBIFSNAME}/H.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: C/C++ header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the C header files.\n\nif action_needed \"${IFSDIR}/include\"\nthen    mkdir -p \"${IFSDIR}/include\"\nfi\n\n#       Copy the header files to DB2 library. Link from IFS include directory.\n\nfor HFILE in \"${TOPDIR}/\"*.h\ndo      DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\"`.MBR\"\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    copy_hfile < \"${HFILE}\" > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n                # touch -r \"${HFILE}\" \"${DEST}\"\n                rm -f tmphdrfile\n        fi\n\n        IFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\n        if action_needed \"${IFSFILE}\" \"${DEST}\"\n        then    rm -f \"${IFSFILE}\"\n                ln -s \"${DEST}\" \"${IFSFILE}\"\n        fi\ndone\n\n\n#       Install the ILE/RPG header file.\n\n\nHFILE=\"${SCRIPTDIR}/zlib.inc\"\nDEST=\"${SRCPF}/ZLIB.INC.MBR\"\n\nif action_needed \"${DEST}\" \"${HFILE}\"\nthen    CMD=\"CPY OBJ('${HFILE}') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${HFILE}\" \"${DEST}\"\nfi\n\nIFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\nif action_needed \"${IFSFILE}\" \"${DEST}\"\nthen    rm -f \"${IFSFILE}\"\n        ln -s \"${DEST}\" \"${IFSFILE}\"\nfi\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"ZLIB version '\"${VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nCSOURCES=`sed -e '/<source name=\"/!d'                                   \\\n    -e 's/.* name=\"\\([^\"]*\\)\".*/\\1/' < treebuild.xml`\n\n#       Compile the sources into modules.\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: build tools')\"\n        system \"${CMD}\"\nfi\n\n\nDEST=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\n\nif action_needed \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/bndsrc') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\n        LINK=YES\nfi\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB ${VERSION} dynamic library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\n\n        #       Duplicate the service program for a versioned backup.\n\n        BACKUP=`echo \"${SRVPGM}${VERSION}\"                              |\n                sed -e 's/.*\\(..........\\)$/\\1/' -e 's/\\./_/g'`\n        BACKUP=\"`db2_name \\\"${BACKUP}\\\"`\"\n        BKUPIFSNAME=\"${LIBIFSNAME}/${BACKUP}.SRVPGM\"\n        rm -f \"${BKUPIFSNAME}\"\n        CMD=\"CRTDUPOBJ OBJ(${SRVPGM}) FROMLIB(${TARGETLIB})\"\n        CMD=\"${CMD} OBJTYPE(*SRVPGM) NEWOBJ(${BACKUP})\"\n        system \"${CMD}\"\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n", "num_lines": 367}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright (C) 2005, 2006 Douglas Gregor.\n# Copyright (C) 2006 The Trustees of Indiana University\n# Copyright (C) 2010 Bryce Lelbach\n# Copyright 2018-2020 Rene Rivera\n#\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)\n\n# Build b2\necho \"Building the B2 engine..\"\npwd=`pwd`\n\"${pwd}/src/engine/build.sh\" \"$@\"\nif [ $? -ne 0 ]; then\n    echo\n    echo \"Failed to build the B2 engine.\" 1>&2\n    exit 1\nfi\ncd \"$pwd\"\ncp \"./src/engine/b2\" .\n\ncat << EOF\n\nBuilding is done. To install, run:\n\n    ./b2 install --prefix=<DIR>\n\nEOF\n", "num_lines": 29}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n#~ Copyright 2002-2020 Rene Rivera.\n#~ Distributed under the Boost Software License, Version 1.0.\n#~ (See accompanying file LICENSE_1_0.txt or copy at\n#~ http://www.boost.org/LICENSE_1_0.txt)\n\nFALSE=1\nTRUE=0\n\n# Reset the toolset.\nB2_TOOLSET=\nB2_SETUP=\n\n# Internal options.\nB2_VERBOSE_OPT=${B2_VERBOSE_OPT:=${FALSE}}\nB2_DEBUG_OPT=${B2_DEBUG_OPT:=${FALSE}}\nB2_GUESS_TOOLSET_OPT=${FALSE}\nB2_HELP_OPT=${FALSE}\nB2_CXX_OPT=\nB2_CXXFLAGS_OPT=\n\n# We need to calculate and set SCRIPT_PATH and SCRIPT_DIR to reference this\n# script so that we can refer to file relative to it.\nSCRIPT_PATH=\"\"\nif test \"${BASH_SOURCE}\" ; then\n    SCRIPT_PATH=${BASH_SOURCE}\nfi\nif test \"${SCRIPT_PATH}\" = \"\" ; then\n    SCRIPT_PATH=$0\nfi\nSCRIPT_DIR=\"$( cd \"$( dirname \"${SCRIPT_PATH}\" )\" && pwd )\"\n\n# This script needs to operate at engine source directory.\nSAVED_PWD=\"${PWD}\"\ncd \"${SCRIPT_DIR}\"\n\ntest_true ()\n{\n    if test $1 -eq ${TRUE} ; then\n        return ${TRUE}\n    fi\n    return ${FALSE}\n}\n\n# Run a command, and echo before doing so. Also checks the exit status and quits\n# if there was an error.\necho_run ()\n{\n    if test_true ${B2_VERBOSE_OPT} ; then echo \"> $@\" ; fi\n    $@\n    r=$?\n    if test $r -ne ${TRUE} ; then\n        exit $r\n    fi\n}\n\n# Print an error message, and exit with a status of 1.\nerror_exit ()\n{\n    echo \"\n${@}\n\nYou can specify the toolset as the argument, i.e.:\n    ./build.sh [options] gcc\n\nToolsets supported by this script are:\n    acc, clang, como, gcc, intel-darwin, intel-linux, kcc, kylix, mipspro,\n    pathscale, pgi, qcc, sun, sunpro, tru64cxx, vacpp\n\nFor any toolset you can override the path to the compiler with the '--cxx'\noption. You can also use additional flags for the compiler with the\n'--cxxflags' option.\n\nA special toolset; cxx, is available which is used as a fallback when a more\nspecific toolset is not found and the cxx command is detected. The 'cxx'\ntoolset will use the '--cxx' and '--cxxflags' options, if present.\n\nOptions:\n    --help                  Show this help message.\n    --verbose               Show messages about what this script is doing.\n    --debug                 Build b2 with debug information, and no\n                            optimizations.\n    --guess-toolset         Print the toolset we can detect for building.\n    --cxx=CXX               The compiler exec to use instead of the detected\n                            compiler exec.\n    --cxxflags=CXXFLAGS     The compiler flags to use in addition to the\n                            flags for the detected compiler.\n\n\" 1>&2\n    exit 1\n}\n\n# Check that a command is in the PATH.\ntest_path ()\n{\n    if `command -v command 1>/dev/null 2>/dev/null`; then\n        command -v $1 1>/dev/null 2>/dev/null\n    else\n        hash $1 1>/dev/null 2>/dev/null\n    fi\n}\n\n# Check that the OS name, as returned by \"uname\", is as given.\ntest_uname ()\n{\n    if test_path uname; then\n        test `uname` = $*\n    fi\n}\n\ntest_compiler ()\n{\n    EXE=\"${B2_CXX_OPT:-$1}\"\n    shift\n    CMD=\"${EXE} $@ ${B2_CXXFLAGS_OPT:-}\"\n    SETUP=${B2_SETUP:-true}\n    if test_true ${B2_VERBOSE_OPT} ; then\n        echo \"> ${CMD} check_cxx11.cpp\"\n        ( ${SETUP} ; ${CMD} check_clib.cpp check_cxx11.cpp )\n    else\n        ( ${SETUP} ; ${CMD} check_clib.cpp check_cxx11.cpp ) 1>/dev/null 2>/dev/null\n    fi\n    CHECK_RESULT=$?\n    if test_true ${CHECK_RESULT} ; then\n        B2_CXX=${CMD}\n    fi\n    rm -rf check_cxx11.o* a.out a.exe 1>/dev/null 2>/dev/null\n    return ${CHECK_RESULT}\n}\n\ntest_toolset ()\n{\n    if test \"${TOOLSET}\" = \"\" ; then return ${TRUE} ; fi\n    if test \"${TOOLSET}\" = \"$1\" -o \"${TOOLSET}\" = \"$2\" -o \"${TOOLSET}\" = \"$3\" ; then return ${TRUE} ; fi\n    return 1\n}\n\n# Check the toolset to bootstrap the build with. The one optional argument to\n# the function is a toolset name. This operates as follows based on these\n# contextual vars, if set, and if an arg is given:\n#\n# No vars set:\n#   Checks, in some priority order, possible toolset commands. Upon finding the\n#   first working command sets B2_TOOLSET to the toolset and B2_CXX to the\n#   compile command with any base options.\n#\n# B2_TOOLSET set:\n#   Checks that toolset for possible compile commands and sets B2_CXX to the\n#   command that works for the toolset.\n#\ncheck_toolset ()\n{\n    TOOLSET=${B2_TOOLSET%%-[0-9]*}\n    TOOLSET_SUFFIX=${B2_TOOLSET##$TOOLSET}\n\n    # Prefer Clang (clang) on macOS..\n    if test_toolset clang && test_uname Darwin && test_compiler clang++$TOOLSET_SUFFIX -x c++ -std=c++11 ; then B2_TOOLSET=clang$TOOLSET_SUFFIX ; return ${TRUE} ; fi\n    # GCC (gcc)..\n    if test_toolset gcc && test_compiler g++$TOOLSET_SUFFIX -x c++ -std=c++11 ; then B2_TOOLSET=gcc$TOOLSET_SUFFIX ; return ${TRUE} ; fi\n    if test_toolset gcc && test_compiler g++$TOOLSET_SUFFIX -x c++ -std=c++11 -D_GNU_SOURCE ; then B2_TOOLSET=gcc$TOOLSET_SUFFIX ; return ${TRUE} ; fi\n    # GCC (gcc) with -pthread arg (for AIX)..\n    if test_toolset gcc && test_compiler g++$TOOLSET_SUFFIX -x c++ -std=c++11 -pthread ; then B2_TOOLSET=gcc$TOOLSET_SUFFIX ; return ${TRUE} ; fi\n    # Clang (clang)..\n    if test_toolset clang && test_compiler clang++$TOOLSET_SUFFIX -x c++ -std=c++11 ; then B2_TOOLSET=clang$TOOLSET_SUFFIX ; return ${TRUE} ; fi\n    # Intel macOS (intel-darwin)\n    if test_toolset intel-darwin && test -r \"${HOME}/intel/oneapi/setvars.sh\" && test_uname Darwin ; then\n        B2_SETUP=\"source ${HOME}/intel/oneapi/setvars.sh\"\n        if test_toolset intel-darwin && test_compiler icpx -x c++ -std=c++11 ; then B2_TOOLSET=intel-darwin ; return ${TRUE} ; fi\n        if test_toolset intel-darwin && test_compiler icc -x c++ -std=c++11 ; then B2_TOOLSET=intel-darwin ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    if test_toolset intel-darwin && test -r \"/opt/intel/oneapi/setvars.sh\" && test_uname Darwin ; then\n        B2_SETUP=\"source /opt/intel/oneapi/setvars.sh\"\n        if test_toolset intel-darwin && test_compiler icpx -x c++ -std=c++11 ; then B2_TOOLSET=intel-darwin ; return ${TRUE} ; fi\n        if test_toolset intel-darwin && test_compiler icc -x c++ -std=c++11 ; then B2_TOOLSET=intel-darwin ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    # Intel oneAPI (intel-linux)\n    if test_toolset intel-linux && test_path icpx ; then\n        if test_compiler icpx -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n    fi\n    if test_toolset xyz && test_path icc ; then\n        if test_compiler icc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n    fi\n    if test_toolset intel-linux && test -r \"${HOME}/intel/oneapi/setvars.sh\" ; then\n        B2_SETUP=\"source ${HOME}/intel/oneapi/setvars.sh\"\n        if test_toolset intel-linux && test_compiler icpx -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        if test_toolset intel-linux && test_compiler icc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    if test_toolset intel-linux && test -r \"/opt/intel/oneapi/setvars.sh\" ; then\n        B2_SETUP=\"source /opt/intel/oneapi/setvars.sh\"\n        if test_toolset intel-linux && test_compiler icpx -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        if test_toolset intel-linux && test_compiler icc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    # Intel Pro (intel-linux)\n    if test_toolset intel-linux && test_path icpc ; then\n        if test_compiler icpc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n    fi\n    if test_toolset intel-linux && test -r \"/opt/intel/inteloneapi/setvars.sh\" ; then\n        B2_SETUP=\"source /opt/intel/inteloneapi/setvars.sh\"\n        if test_compiler icpc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    if test_toolset intel-linux && test -r \"/opt/intel/cc/9.0/bin/iccvars.sh\" ; then\n        B2_SETUP=\"source /opt/intel/cc/9.0/bin/iccvars.sh\"\n        if test_compiler icpc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    if test_toolset intel-linux && test -r \"/opt/intel_cc_80/bin/iccvars.sh\" ; then\n        B2_SETUP=\"source /opt/intel_cc_80/bin/iccvars.sh\"\n        if test_compiler icpc -x c++ -std=c++11 ; then B2_TOOLSET=intel-linux ; return ${TRUE} ; fi\n        B2_SETUP=\n    fi\n    # Mips Pro (mipspro)\n    if test_toolset mipspro && test_uname IRIX && test_compiler CC -FE:template_in_elf_section -ptused ; then B2_TOOLSET=mipspro ; return ${TRUE} ; fi\n    if test_toolset mipspro && test_uname IRIX64 && test_compiler CC -FE:template_in_elf_section -ptused ; then B2_TOOLSET=mipspro ; return ${TRUE} ; fi\n    # OSF Tru64 C++ (tru64cxx)\n    if test_toolset tru64cxx && test_uname OSF1 && test_compiler cc ; then B2_TOOLSET=mipspro ; return ${TRUE} ; fi\n    # QNX (qcc)\n    if test_toolset qcc && test_uname QNX && test_compiler QCC ; then B2_TOOLSET=mipspro ; return ${TRUE} ; fi\n    # Linux XL/VA C++ (xlcpp, vacpp)\n    if test_toolset xlcpp vacpp && test_uname Linux && test_compiler xlC_r ; then\n        if /usr/bin/lscpu | grep Byte | grep Little > /dev/null 2>&1 ; then\n            # Little endian linux\n            B2_TOOLSET=xlcpp\n            return ${TRUE}\n        else\n            # Big endian linux\n            B2_TOOLSET=vacpp\n            return ${TRUE}\n        fi\n    fi\n    # AIX VA C++ (vacpp)\n    if test_toolset vacpp && test_uname AIX && test_compiler xlC_r ; then B2_TOOLSET=vacpp ; return ${TRUE} ; fi\n    # PGI (pgi)\n    if test_toolset pgi && test_compiler pgc++ -std=c++11 ; then B2_TOOLSET=pgi ; return ${TRUE} ; fi\n    # Pathscale C++ (pathscale)\n    if test_toolset pathscale && test_compiler pathCC ; then B2_TOOLSET=pathscale ; return ${TRUE} ; fi\n    # Como (como)\n    if test_toolset como && test_compiler como ; then B2_TOOLSET=como ; return ${TRUE} ; fi\n    # Borland C++ (kylix)\n    if test_toolset kylix && test_compiler bc++ -tC -q ; then B2_TOOLSET=kylix ; return ${TRUE} ; fi\n    # aCC (acc)\n    if test_toolset acc && test_compiler aCC -AA ; then B2_TOOLSET=acc ; return ${TRUE} ; fi\n    # Sun Pro C++ (sunpro)\n    if test_toolset sunpro && test_compiler /opt/SUNWspro/bin/CC -std=c++11 ; then B2_TOOLSET=sunpro ; return ${TRUE} ; fi\n    # Generic (cxx)\n    if test_toolset cxx && test_compiler cxx ; then B2_TOOLSET=cxx ; return ${TRUE} ; fi\n    if test_toolset cxx && test_compiler cpp ; then B2_TOOLSET=cxx ; return ${TRUE} ; fi\n    if test_toolset cxx && test_compiler CC ; then B2_TOOLSET=cxx ; return ${TRUE} ; fi\n\n    # Nothing found.\n    if test \"${B2_TOOLSET}\" = \"\" ; then\n        error_exit \"Could not find a suitable toolset.\"\n    fi\n    return ${FALSE}\n}\n\n# Handle command options and args.\nwhile test $# -gt 0\ndo\n    case \"$1\" in\n        --verbose) B2_VERBOSE_OPT=${TRUE} ;;\n        --debug) B2_DEBUG_OPT=${TRUE} ;;\n        --guess-toolset) B2_GUESS_TOOLSET_OPT=${TRUE} ;;\n        --help) B2_HELP_OPT=${TRUE} ;;\n        --cxx=*) B2_CXX_OPT=`expr \"x$1\" : \"x--cxx=\\(.*\\)\"` ;;\n        --cxxflags=*) B2_CXXFLAGS_OPT=`expr \"x$1\" : \"x--cxxflags=\\(.*\\)\"` ;;\n        -*) ;;\n        ?*) B2_TOOLSET=$1 ;;\n    esac\n    shift\ndone\n\n# Show some help, if requested.\nif test_true ${B2_HELP_OPT} ; then\n    error_exit\nfi\n\n# If we have a CXX but no B2_TOOLSET specified by the user we assume they meant\n# \"cxx\" as the toolset.\nif test \"${B2_CXX_OPT}\" != \"\" -a \"${B2_TOOLSET}\" = \"\" ; then\n    B2_TOOLSET=cxx\nfi\n\n# If we have B2_TOOLSET=cxx but no B2_CXX_OPT nor B2_CXXFLAGS_OPT specified by the user\n# we assume they meant $CXX and $CXXFLAGS.\nif test \"${B2_TOOLSET}\" = \"cxx\" -a \"${B2_CXX_OPT}\" = \"\" -a \"${B2_CXXFLAGS_OPT}\" = \"\" ; then\n    B2_CXX_OPT=\"${CXX}\"\n    B2_CXXFLAGS_OPT=\"${CXXFLAGS}\"\nfi\n\n# Guess toolset, or toolset commands.\ncheck_toolset\nTOOLSET_CHECK=$?\n\n# We can bail from the rest of the checks and build if we are just guessing\n# the toolset.\nif test_true ${B2_GUESS_TOOLSET_OPT} ; then\n    echo \"${B2_TOOLSET}\"\n    exit 0\nfi\n\n# We need a viable compiler. Check here and give some feedback about it.\nif ! test_true ${TOOLSET_CHECK} ; then\n    echo \"\nA C++11 capable compiler is required for building the B2 engine.\nToolset '${B2_TOOLSET}' does not appear to support C++11.\n\"\n    (B2_VERBOSE_OPT=${TRUE} check_toolset)\n    error_exit \"\n** Note, the C++11 capable compiler is _only_ required for building the B2\n** engine. The B2 build system allows for using any C++ level and any other\n** supported language and resource in your projects.\n\"\nfi\n\n# Set the additional options needed to build the engine based on the toolset.\ncase \"${B2_TOOLSET}\" in\n\n    gcc|gcc-*)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O2 -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -g\"\n    ;;\n\n    intel-*)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 -s -static\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -g -p -static\"\n    ;;\n\n    vacpp)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:--qversion}\n        B2_CXXFLAGS_RELEASE=\"-O3 -s -qstrict -qinline\"\n        B2_CXXFLAGS_DEBUG=\"-g -qNOOPTimize -qnoinline -pg\"\n    ;;\n\n    xlcpp)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:--qversion}\n        B2_CXXFLAGS_RELEASE=\"-s -O3 -qstrict -qinline\"\n        B2_CXXFLAGS_DEBUG=\"-g -qNOOPTimize -qnoinline -pg\"\n    ;;\n\n    como)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 --inlining\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -g --no_inlining --long_long\"\n    ;;\n\n    kcc)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"+K2 -s\"\n        B2_CXXFLAGS_DEBUG=\"+K0 -g\"\n    ;;\n\n    kylix)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O2 -vi -w-inl -s\"\n        B2_CXXFLAGS_DEBUG=\"-Od -v -vi-\"\n    ;;\n\n    mipspro)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-Ofast -g0 \\\"-INLINE:none\\\" -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -INLINE -g\"\n    ;;\n\n    pathscale)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 -inline -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -noinline -ggdb\"\n    ;;\n\n    pgi)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-fast -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -gopt\"\n    ;;\n\n    sun*)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:--V}\n        B2_CXXFLAGS_RELEASE=\"-xO4 -s\"\n        B2_CXXFLAGS_DEBUG=\"-g\"\n    ;;\n\n    clang|clang-*)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -fno-inline -g\"\n    ;;\n\n    tru64cxx)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O5 -inline speed -s\"\n        B2_CXXFLAGS_DEBUG=\"-O0 -pg -g\"\n    ;;\n\n    acc)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 -s\"\n        B2_CXXFLAGS_DEBUG=\"+d -g\"\n    ;;\n\n    qcc)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n        B2_CXXFLAGS_RELEASE=\"-O3 -Wc,-finline-functions\"\n        B2_CXXFLAGS_DEBUG=\"O0 -Wc,-fno-inline -gstabs+\"\n    ;;\n\n    cxx)\n        CXX_VERSION_OPT=${CXX_VERSION_OPT:---version}\n    ;;\n\n    *)\n        error_exit \"Unknown toolset: ${B2_TOOLSET}\"\n    ;;\nesac\n\nbuild_b2 ()\n{\n    echo \"\n###\n###\n### Using '${B2_TOOLSET}' toolset.\n###\n###\n\"\n    echo_run ${B2_CXX} ${CXX_VERSION_OPT}\necho \"\n###\n###\n\"\n    B2_SOURCES=\"\\\nbuiltins.cpp \\\nclass.cpp \\\ncommand.cpp \\\ncompile.cpp \\\nconstants.cpp \\\ncwd.cpp \\\ndebug.cpp \\\ndebugger.cpp \\\nexeccmd.cpp \\\nexecnt.cpp \\\nexecunix.cpp \\\nfilesys.cpp \\\nfilent.cpp \\\nfileunix.cpp \\\nframes.cpp \\\nfunction.cpp \\\nglob.cpp \\\nhash.cpp \\\nhcache.cpp \\\nhdrmacro.cpp \\\nheaders.cpp \\\njam_strings.cpp \\\njam.cpp \\\njamgram.cpp \\\nlists.cpp \\\nmake.cpp \\\nmake1.cpp \\\nmd5.cpp \\\nmem.cpp \\\nmodules.cpp \\\nnative.cpp \\\nobject.cpp \\\noption.cpp \\\noutput.cpp \\\nparse.cpp \\\npathnt.cpp \\\npathsys.cpp \\\npathunix.cpp \\\nregexp.cpp \\\nrules.cpp \\\nscan.cpp \\\nsearch.cpp \\\nstartup.cpp \\\nsubst.cpp \\\nsysinfo.cpp \\\ntimestamp.cpp \\\nvariable.cpp \\\nw32_getreg.cpp \\\nmodules/order.cpp \\\nmodules/path.cpp \\\nmodules/property-set.cpp \\\nmodules/regex.cpp \\\nmodules/sequence.cpp \\\nmodules/set.cpp \\\n\"\n\n    if test_true ${B2_DEBUG_OPT} ; then B2_CXXFLAGS=\"${B2_CXXFLAGS_DEBUG}\"\n    else B2_CXXFLAGS=\"${B2_CXXFLAGS_RELEASE} -DNDEBUG\"\n    fi\n    ( B2_VERBOSE_OPT=${TRUE} echo_run ${B2_CXX} ${B2_CXXFLAGS} ${B2_SOURCES} -o b2 )\n    ( B2_VERBOSE_OPT=${TRUE} echo_run cp b2 bjam )\n}\n\nif test_true ${B2_VERBOSE_OPT} ; then\n    (\n        ${B2_SETUP}\n        build_b2\n    )\nelse\n    (\n        ${B2_SETUP} 1>/dev/null 2>/dev/null\n        build_b2\n    )\nfi\n", "num_lines": 512}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/bash\n\n# Copyright (c) 2013-2016 Vinnie Falco (vinnie dot falco at gmail dot com)\n#\n# Distributed under the Boost Software License, Version 1.0. (See accompanying\n# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)\n\nmkdir -p temp\ndoxygen source.dox\ncd temp\nxsltproc combine.xslt index.xml > all.xml\nxsltproc ../reference.xsl all.xml > ../reference.qbk\n\n", "num_lines": 14}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script runs a build and compares the scrubbed/normalized\n# results against the scrubbed results of a previous build (run using\n# update-baseline-html.sh). It is primarily used to guard against\n# XSLT regressions in docca.\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\n\n! test -d htmlPREVIOUS_SCRUBBED && echo \"First run update-baseline-html.sh\" && exit\n\nrm -rf html_SCRUBBED\n\necho \"Running clean build...\"\nb2 clean\nb2\n\necho \"Scrubbing results and storing as html_SCRUBBED...\"\ncp -r html html_SCRUBBED\ncd html_SCRUBBED\ngrep -rl -f ${SCRIPT_DIR}/grep-expressions . | xargs sed -i -f ${SCRIPT_DIR}/sed-commands\n\necho \"Showing diffs from previous build (stored in diffs.txt):\"\ncd ..\ndiff -r htmlPREVIOUS_SCRUBBED html_SCRUBBED >diffs.txt\ncat diffs.txt\n", "num_lines": 25}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script runs a new build and moves the results so they\n# can be used as a comparison baseline against subsequent builds\n# that are run using build-and-compare.sh\n\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\"\n\nrm -rf htmlPREVIOUS htmlPREVIOUS_SCRUBBED\n\necho \"Running clean build...\"\nb2 clean\nb2\n\necho \"Moving results to htmlPREVIOUS...\"\nmv html htmlPREVIOUS\n\necho \"Scrubbing htmlPREVIOUS and storing as htmlPREVIOUS_SCRUBBED for use by build-and-compare.sh...\"\ncp -r htmlPREVIOUS htmlPREVIOUS_SCRUBBED\ncd htmlPREVIOUS_SCRUBBED\ngrep -rl -f ${SCRIPT_DIR}/grep-expressions . | xargs sed -i -f ${SCRIPT_DIR}/sed-commands\n", "num_lines": 20}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\n# boost::hs installer\n#\n# Copyright 2006 Matias Capeletto\n# Distributed under the Boost Software License, Version 1.0.\n# (See accompanying file LICENSE_1_0.txt or copy at\n# http://www.boost.org/LICENSE_1_0.txt)\n\n# This script install the .xml kate syntax files in KDE\n\necho \"Installing boost::hs\"\necho \"A few xml files will be copy to the place KDE store katepart sources.\"\necho \"Files to install\"\n\nls syntax/*.xml -1\n\necho \"Installing...\"\n\ncp syntax/*.xml /usr/share/apps/katepart/syntax\n\necho \"Done!\"\necho \"\"\n\n", "num_lines": 25}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#==============================================================================\n#   Copyright (c) 2017-2018 Daniel James\n#\n#   Use, modification and distribution is subject to the Boost Software\n#   License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at\n#   http://www.boost.org/LICENSE_1_0.txt)\n#==============================================================================\n\n#!/usr/bin/env bash\n\ncd $(dirname $0)\n\ncd ..\nb2 -q || exit 1\ncd -\n\nfind . -name \"*.gold\" | while read gold_file\ndo\n    flags=\"--debug\"\n\n    quickbook_file=$(echo $gold_file | sed 's/[.]gold/.quickbook/')\n    html_file=$(echo $gold_file | sed 's/[.]gold/.gold-html/')\n\n    if [[ $gold_file =~ .*xinclude/.*-alt\\.gold ]]\n    then\n        quickbook_file=$(echo $quickbook_file | sed 's/-alt\\.quickbook/.quickbook/')\n        flags=\"$flags --xinclude-base xinclude/sub\"\n    elif [[ $gold_file =~ .*xinclude/.*\\.gold ]]\n    then\n        flags=\"$flags --xinclude-base xinclude/../..\"\n    fi\n\n    if [[ $gold_file =~ .*include/filename[-_]path.* ]]\n    then\n        flags=\"$flags -I include/sub\"\n    fi\n\n    if [[ $gold_file =~ .*command_line_macro.* ]]\n    then\n        flags=\"$flags -D__macro__=*bold* -D__empty__\"\n    fi\n\n    ../../../dist/bin/quickbook $quickbook_file $flags --output-file $gold_file ||\n        echo \"*** Error generating boostbook from $quickbook_file\"\n    ../../../dist/bin/quickbook $quickbook_file $flags --output-file $html_file --output-format onehtml ||\n        echo \"*** Error generating html from $quickbook_file\"\ndone\n", "num_lines": 48}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.6-15\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2015-10-07.11; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    _G_rc_run_hooks=false\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      if eval $_G_hook '\"$@\"'; then\n        # store returned options list back into positional\n        # parameters for next 'cmd' execution.\n        eval _G_hook_result=\\$${_G_hook}_result\n        eval set dummy \"$_G_hook_result\"; shift\n        _G_rc_run_hooks=:\n      fi\n    done\n\n    $_G_rc_run_hooks && func_run_hooks_result=$_G_hook_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, you may remove/edit\n# any options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  In this case you also must return $EXIT_SUCCESS to let the\n# hook's caller know that it should pay attention to\n# '<hooked_function_name>_result'.  Returning $EXIT_FAILURE signalizes that\n# arguments are left untouched by the hook and therefore caller will ignore the\n# result variable.\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  There is\n#        # no need to do the equivalent (but slower) action:\n#        # func_quote_for_eval ${1+\"$@\"}\n#        # my_options_prep_result=$func_quote_for_eval_result\n#        false\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\", we could need that later\n#                         # if $args_changed is true.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        if $args_changed; then\n#          func_quote_for_eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_for_eval_result\n#        fi\n#\n#        $args_changed\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        false\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    _G_func_options_finish_exit=false\n    if func_run_hooks func_options ${1+\"$@\"}; then\n      func_options_finish_result=$func_run_hooks_result\n      _G_func_options_finish_exit=:\n    fi\n\n    $_G_func_options_finish_exit\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_rc_options=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      if eval func_$my_func '${1+\"$@\"}'; then\n        eval _G_res_var='$'\"func_${my_func}_result\"\n        eval set dummy \"$_G_res_var\" ; shift\n        _G_rc_options=:\n      fi\n    done\n\n    # Save modified positional parameters for caller.  As a top-level\n    # options-parser function we always need to set the 'func_options_result'\n    # variable (regardless the $_G_rc_options value).\n    if $_G_rc_options; then\n      func_options_result=$_G_res_var\n    else\n      func_quote_for_eval ${1+\"$@\"}\n      func_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_options\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning $EXIT_SUCCESS (otherwise $EXIT_FAILURE is returned).\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    _G_rc_options_prep=false\n    if func_run_hooks func_options_prep ${1+\"$@\"}; then\n      _G_rc_options_prep=:\n      # save modified positional parameters for caller\n      func_options_prep_result=$func_run_hooks_result\n    fi\n\n    $_G_rc_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    _G_rc_parse_options=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      if func_run_hooks func_parse_options ${1+\"$@\"}; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n        _G_rc_parse_options=:\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_rc_parse_options=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_rc_parse_options=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      $_G_match_parse_options && _G_rc_parse_options=:\n    done\n\n\n    if $_G_rc_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_parse_options\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    _G_rc_validate_options=false\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    if func_run_hooks func_validate_options ${1+\"$@\"}; then\n      # save modified positional parameters for caller\n      func_validate_options_result=$func_run_hooks_result\n      _G_rc_validate_options=:\n    fi\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    $_G_rc_validate_options\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.6-15\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_options_prep\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_parse_options\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -static-*            direct GCC to link specific libraries statically\n      # -fcilkplus           Cilk Plus language extension features for C/C++\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11252}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nset -e\n# Check that all of the base fuzzing corpus parse without errors\n./aresfuzz fuzzinput/*\n./aresfuzzname fuzznames/*\n", "num_lines": 6}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.6-15\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2015-10-07.11; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    _G_rc_run_hooks=false\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      if eval $_G_hook '\"$@\"'; then\n        # store returned options list back into positional\n        # parameters for next 'cmd' execution.\n        eval _G_hook_result=\\$${_G_hook}_result\n        eval set dummy \"$_G_hook_result\"; shift\n        _G_rc_run_hooks=:\n      fi\n    done\n\n    $_G_rc_run_hooks && func_run_hooks_result=$_G_hook_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, you may remove/edit\n# any options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  In this case you also must return $EXIT_SUCCESS to let the\n# hook's caller know that it should pay attention to\n# '<hooked_function_name>_result'.  Returning $EXIT_FAILURE signalizes that\n# arguments are left untouched by the hook and therefore caller will ignore the\n# result variable.\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  There is\n#        # no need to do the equivalent (but slower) action:\n#        # func_quote_for_eval ${1+\"$@\"}\n#        # my_options_prep_result=$func_quote_for_eval_result\n#        false\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\", we could need that later\n#                         # if $args_changed is true.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        if $args_changed; then\n#          func_quote_for_eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_for_eval_result\n#        fi\n#\n#        $args_changed\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        false\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    _G_func_options_finish_exit=false\n    if func_run_hooks func_options ${1+\"$@\"}; then\n      func_options_finish_result=$func_run_hooks_result\n      _G_func_options_finish_exit=:\n    fi\n\n    $_G_func_options_finish_exit\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_rc_options=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      if eval func_$my_func '${1+\"$@\"}'; then\n        eval _G_res_var='$'\"func_${my_func}_result\"\n        eval set dummy \"$_G_res_var\" ; shift\n        _G_rc_options=:\n      fi\n    done\n\n    # Save modified positional parameters for caller.  As a top-level\n    # options-parser function we always need to set the 'func_options_result'\n    # variable (regardless the $_G_rc_options value).\n    if $_G_rc_options; then\n      func_options_result=$_G_res_var\n    else\n      func_quote_for_eval ${1+\"$@\"}\n      func_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_options\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning $EXIT_SUCCESS (otherwise $EXIT_FAILURE is returned).\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    _G_rc_options_prep=false\n    if func_run_hooks func_options_prep ${1+\"$@\"}; then\n      _G_rc_options_prep=:\n      # save modified positional parameters for caller\n      func_options_prep_result=$func_run_hooks_result\n    fi\n\n    $_G_rc_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    _G_rc_parse_options=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      if func_run_hooks func_parse_options ${1+\"$@\"}; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n        _G_rc_parse_options=:\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_rc_parse_options=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_rc_parse_options=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      $_G_match_parse_options && _G_rc_parse_options=:\n    done\n\n\n    if $_G_rc_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_parse_options\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    _G_rc_validate_options=false\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    if func_run_hooks func_validate_options ${1+\"$@\"}; then\n      # save modified positional parameters for caller\n      func_validate_options_result=$func_run_hooks_result\n      _G_rc_validate_options=:\n    fi\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    $_G_rc_validate_options\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.6-15\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_options_prep\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_parse_options\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -static-*            direct GCC to link specific libraries statically\n      # -fcilkplus           Cilk Plus language extension features for C/C++\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11252}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n# $Id: gen-scale.sh,v 1.1 2013/12/24 18:05:46 vegogine Exp $\n#\n# This script generates source variations from scale.c for different datatypes.\n\nUPPER=\"$1\"\nMIXED=\"$2\"\nDTYPE=\"$3\"\nCTYPE=\"$4\"\n\n# The widget provides for setting the digits.  Turn on/off the corresponding\n# ifdef.\ncase $CTYPE in\nfloat|*double)\n\tfloat=1\n\tprint=f\n\t;;\nlong*long)\n\tfloat=0\n\tprint=ll\n\t;;\nunsigned*long)\n\tfloat=0\n\tprint=lu\n\t;;\nunsigned)\n\tfloat=0\n\tprint=u\n\t;;\nlong)\n\tfloat=0\n\tprint=l\n\t;;\n*)\n\tfloat=0\n\tprint=d\n\t;;\nesac\n\nif test \"$print\" = \"d\" ; then\n\tMODEL=\nelif test $CTYPE = double; then\n\tMODEL=\"d\"\nelse\n\tMODEL=$print\nfi\n\nif test $float = 0 ; then\nsed\t-e '/^#if <FLOAT>/,/^#endif <FLOAT>/d' \\\n\t-e '/^#if <INT>/d' \\\n\t-e '/^#endif <INT>/d' \\\n\t-e 's/<UPPER>/'\"$UPPER\"'/g' \\\n\t-e 's/<MIXED>/'\"$MIXED\"'/g' \\\n\t-e 's/<DTYPE>/'\"$DTYPE\"'/g' \\\n\t-e 's/<CTYPE>/'\"$CTYPE\"'/g' \\\n\t-e 's/<MODEL>/'\"$MODEL\"'/g' \\\n\t-e 's/<PRINT>/'\"$print\"'/g' \\\n\t$5\nelse\nsed\t-e '/^#if <INT>/,/^#endif <INT>/d' \\\n\t-e '/^#if <FLOAT>/d' \\\n\t-e '/^#endif <FLOAT>/d' \\\n\t-e 's/<UPPER>/'\"$UPPER\"'/g' \\\n\t-e 's/<MIXED>/'\"$MIXED\"'/g' \\\n\t-e 's/<DTYPE>/'\"$DTYPE\"'/g' \\\n\t-e 's/<CTYPE>/'\"$CTYPE\"'/g' \\\n\t-e 's/<MODEL>/'\"$MODEL\"'/g' \\\n\t-e 's/<PRINT>/'\"$print\"'/g' \\\n\t$5\nfi\n", "num_lines": 71}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n# $Id: headers.sh,v 1.1 2013/12/24 18:05:49 vegogine Exp $\n# vi:ts=4 sw=4\n#\n# Adjust includes for header files that reside in a subdirectory of\n# /usr/include, etc.\n#\n# Options:\n#\t-c CFG\tspecify an alternate name for config.h\n#\t-d DIR\ttarget directory\n#\t-e FILE\textra editing commands, e.g., for manpage references\n#\t-h FILE install the given file in subdirectory DIR rather than parent\n#\t-i    \tcreate/update the headers.sed script\n#\t-p PKG\tspecify the package name\n#\t-s DIR\tsource directory\n#\t-t TYPE renaming for manpage-sections\n#\t-x PRG\tinstall-program (plus options, the whole value in quotes)\n#\n# Other parameters are assumed to be provided only for the install scenario.\n\nSCRIPT=headers.sed\nMYFILE=headers.tmp\n\nOPT_C=config.h\nOPT_D=\nOPT_E=\nOPT_H=\nOPT_I=n\nOPT_P=\nOPT_S=\nOPT_T=\nOPT_X=install\n\nwhile test $# != 0\ndo\n\tcase $1 in\n\t-c)\t# CFG\tspecify an alternate name for config.h\n\t\tshift\n\t\tOPT_C=\"$1\"\n\t\t;;\n\t-d)\t# DIR\ttarget directory\n\t\tshift\n\t\tOPT_D=\"$1\"\n\t\t;;\n\t-e)\t# FILE\textra sed-commands\n\t\tshift\n\t\tOPT_E=\"$OPT_E -f $1\"\n\t\t;;\n\t-h)\t# FILE\tspecial-case of header in subdirectory\n\t\tshift\n\t\tOPT_H=\"$1\"\n\t\t;;\n\t-i)\t# create the headers.sed script\n\t\tif test \"$OPT_I\" = n\n\t\tthen\n\t\t\trm -f $SCRIPT\n\t\tfi\n\t\tOPT_I=y\n\n\t\tif ( test -n \"$OPT_D\" )\n\t\tthen\n\t\t\tif ( test -n \"$OPT_S\" && test -d \"$OPT_S\" )\n\t\t\tthen\n\t\t\t\tLEAF=`basename $OPT_D`\n\t\t\t\tcase $OPT_D in\n\t\t\t\t/*/include/$LEAF)\n\t\t\t\t\tEND=`basename $OPT_D`\n\t\t\t\t\tfor i in $OPT_S/*.h\n\t\t\t\t\tdo\n\t\t\t\t\t\tNAME=`basename $i`\n\t\t\t\t\t\tif test -z \"$OPT_H\" || test \"$OPT_H\" != \"$NAME\"\n\t\t\t\t\t\tthen\n\t\t\t\t\t\t\techo \"s%<$NAME>%<$END/$NAME>%g\" >> $SCRIPT\n\t\t\t\t\t\tfi\n\t\t\t\t\tdone\n\t\t\t\t\t;;\n\t\t\t\t*)\n\t\t\t\t\techo \"\" >> $SCRIPT\n\t\t\t\t\t;;\n\t\t\t\tesac\n\t\t\t\tOPT_S=\n\t\t\t\tif test -f $SCRIPT ; then\n\t\t\t\t\tsort -u $SCRIPT >$MYFILE\n\t\t\t\t\trm -f $SCRIPT\n\t\t\t\t\tmv $MYFILE $SCRIPT\n\t\t\t\tfi\n\t\t\tfi\n\t\tfi\n\n\t\tif test -n \"$OPT_P\"\n\t\tthen\n\t\t\tfor name in `\n\t\t\tegrep \"#define[ \t][ \t]*[A-Z]\" $OPT_C \\\n\t\t\t\t| sed\t-e 's/^#define[ \t][ \t]*//' \\\n\t\t\t\t\t-e 's/[ \t].*//' \\\n\t\t\t\t| fgrep -v GCC_ \\\n\t\t\t\t| sort -u \\\n\t\t\t\t| egrep -v \"^${OPT_P}_\"`\n\t\t\tdo\n\t\t\t\techo \"s%\\\\<$name\\\\>%${OPT_P}_$name%g\" >>$SCRIPT\n\t\t\tdone\n\t\t\tif test -f $SCRIPT ; then\n\t\t\t\tsort -u $SCRIPT >$MYFILE\n\t\t\t\trm -f $SCRIPT\n\t\t\t\tmv $MYFILE $SCRIPT\n\t\t\tfi\n\t\t\tOPT_P=\n\t\tfi\n\t\t;;\n\t-p)\t# PKG\tspecify the package name\n\t\tshift\n\t\tOPT_P=\"$1\"\n\t\t;;\n\t-s)\t# DIR\tsource directory\n\t\tshift\n\t\tOPT_S=\"$1\"\n\t\t;;\n\t-t)\t# rename suffix of target\n\t\tshift\n\t\tOPT_T=\"$1\"\n\t\t;;\n\t-x)\t# PRG\tinstall-program (plus options, the whole value in quotes)\n\t\tshift\n\t\tOPT_X=\"$1\"\n\t\t;;\n\t*)\n\t\tFILE=$1\n\n\t\tSHOW=`basename $FILE`\n\t\tTMPSRC=${TMPDIR-/tmp}/${SHOW}$$\n\n\t\techo \"\t... $SHOW\"\n\t\ttest -f $OPT_S/$FILE && FILE=\"$OPT_S/$FILE\"\n\n\t\tif test -f \"$FILE\"\n\t\tthen\n\t\t\trm -f $TMPSRC\n\t\t\tsed -f $SCRIPT $OPT_E $FILE > $TMPSRC\n\t\t\tNAME=`basename $FILE`\n\t\t\tif test -n \"$OPT_T\" ; then\n\t\t\t\tNAME=`echo \"$NAME\" | sed -e 's/\\.[^.]*$//'`.$OPT_T\n\t\t\tfi\n\n\t\t\t# Just in case someone gzip'd manpages,\n\t\t\t# remove the conflicting copy.\n\t\t\ttest -f $OPT_D/$NAME.gz && rm -f $OPT_D/$NAME.gz\n\n\t\t\teval $OPT_X $TMPSRC $OPT_D/$NAME\n\t\t\trm -f $TMPSRC\n\t\tfi\n\t\t;;\n\tesac\n\tshift\ndone\n", "num_lines": 155}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n# $Id: manlinks.sh,v 1.1 2013/12/24 18:05:53 vegogine Exp $\n# install/uninstall aliases for one or more manpages,\n#\n#  Copyright 2002,2005 Thomas Dickey\n#  All rights reserved.\n#\n#  Redistribution and use in source and binary forms, with or without\n#  modification, are permitted provided that the following conditions\n#  are met:\n#  1. Redistributions of source code must retain the above copyright\n#     notice, this list of conditions and the following disclaimer.\n#  2. Redistributions in binary form must reproduce the above copyright\n#     notice, this list of conditions and the following disclaimer in the\n#     documentation and/or other materials provided with the distribution.\n#  3. All advertising materials mentioning features or use of this software\n#     must display the following acknowledgment:\n#       This product includes software developed by Thomas Dickey\n#       and contributors.\n#  4. Neither the name of Thomas Dickey, nor the names of contributors\n#     may be used to endorse or promote products derived from this software\n#     without specific prior written permission.\n#\n#  THIS SOFTWARE IS PROVIDED BY THOMAS DICKEY AND CONTRIBUTORS ``AS IS'' AND\n#  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n#  ARE DISCLAIMED.  IN NO EVENT SHALL THOMAS DICKEY OR CONTRIBUTORS BE LIABLE\n#  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS\n#  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n#  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n#  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n#  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF\n#  SUCH DAMAGE.\n\nCDPATH=\n\nverb=$1\nshift\n\nsrcdir=$1\nshift\n\nmandir=$1\nshift\n\nmansect=$1\nshift\n\nparent=`pwd`\nscript=$srcdir/manlinks.sed\n\nfor source in $* ; do\ncase $source in #(vi\n*.orig|*.rej) ;; #(vi\n*.[0-9]*)\n\tcd $parent\n\tsection=`expr \"$source\" : '.*\\.\\([0-9]\\)[xm]*'`;\n\taliases=\n\tinalias=$source\n\ttest ! -f $inalias && inalias=\"$srcdir/$inalias\"\n\tif test ! -f $inalias ; then\n\t\techo \"\t.. skipped $source\"\n\t\tcontinue\n\tfi\n\taliases=`sed -f $script $inalias | sort -u`\n\n\tsuffix=`basename $source | sed -e 's/^[^.]*//'`\n\tcd $mandir || exit 1\n\tif test $verb = installing ; then\n\t\ttest -n \"$aliases\" && (\n\t\t\tif test \"$suffix\" = \".$mansect\" ; then\n\t\t\t\ttarget=`basename $source`\n\t\t\telse\n\t\t\t\ttarget=`basename $source $suffix`.$mansect\n\t\t\t\tsuffix=\".$mansect\"\n\t\t\tfi\n\t\t\tfor cf_alias in $aliases\n\t\t\tdo\n\t\t\t\tcf_doit=no\n\t\t\t\tif test -f $cf_alias${suffix} ; then\n\t\t\t\t\tif ( cmp -s $target $cf_alias${suffix} )\n\t\t\t\t\tthen\n\t\t\t\t\t\t:\n\t\t\t\t\telse\n\t\t\t\t\t\tcf_doit=yes\n\t\t\t\t\tfi\n\t\t\t\telse\n\t\t\t\t\tcf_doit=yes\n\t\t\t\tfi\n\t\t\t\tif test $cf_doit = yes ; then\n\t\t\t\t\techo \"\t... alias $cf_alias${suffix}\"\n\t\t\t\t\trm -f $cf_alias${suffix}\n\t\t\t\t\tif (ln -s $target $cf_alias${suffix}) ; then\n\t\t\t\t\t\t:\n\t\t\t\t\telse\n\t\t\t\t\t\techo \".so $target\" > $cf_alias${suffix}\n\t\t\t\t\tfi\n\t\t\t\tfi\n\t\t\tdone\n\t\t)\n\telif test $verb = removing ; then\n\t\tsuffix=\".$mansect\"\n\t\ttest -n \"$aliases\" && (\n\t\t\tfor cf_alias in $aliases\n\t\t\tdo\n\t\t\t\techo \"\t... alias $cf_alias${suffix}\"\n\t\t\t\trm -f $cf_alias${suffix}\n\t\t\tdone\n\t\t)\n\tfi\n\t;;\nesac\ndone\nexit 0\n", "num_lines": 116}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: alphalist.sh,v 1.1 2013/12/24 18:06:16 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the alphalist widget.\n#\n\n#\n# This gets the password file.\n#\ngetPasswordFile()\n{\n   system=$1\n   file=$2\n\n   #\n   # Depeding on the system, get the password file\n   # using nicat, ypcat, or just plain old /etc/passwd\n   #\n   if [ \"$system\" = \"NIS\" ]; then\n      niscat passwd.org_dir > $file\n   elif [ \"$system\" = \"YP\" ]; then\n      ypcat passwd > $file\n   else\n      cp /etc/passwd $file\n   fi\n}\n\n#\n# This displays account information.\n#\ndisplayAccountInformation()\n{\n   userAccount=$1\n   passwordFile=$2\n\n   #\n   # Get the user account information.\n   #\n   line=`grep \"^${userAccount}\" $passwordFile`\n   uid=`echo $line | cut -d: -f3`\n   gid=`echo $line | cut -d: -f4`\n   info=`echo $line | cut -d: -f5`\n   home=`echo $line | cut -d: -f6`\n   shell=`echo $line | cut -d: -f7`\n\n   #\n   # Create the label message information.\n   #\n   accountMessage=\"<C></U>Account\n<C><#HL(30)>\nAccount: </U>${userAccount}\nUID    : </U>${uid}\nGID    : </U>${gid}\nInfo   : </U>${info}\nHome   : </U>${home}\nShell  : </U>${shell}\n<C><#HL(30)>\n<C>Hit </R>space<!R> to continue\"\n\n   #\n   # Create the popup label.\n   #\n   ${CDK_LABEL} -m \"${accountMessage}\" -p \" \"\n}\n\n#\n# Create some global variables.\n#\nCDK_ALPHALIST=\"${CDK_BINDIR=..}/cdkalphalist\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ntmpPass=\"${TMPDIR=/tmp}/sl.$$\"\noutput=\"${TMPDIR=/tmp}/alphalist.$$\"\nuserAccounts=\"${TMPDIR=/tmp}/ua.$$\"\n\n#\n# Create the message for the scrolling list.\n#\ntitle=\"<C>Pick an account\n<C>you want to view.\"\n\n#\n# Get the password file and stick it into the temp file.\n#\n#getPasswordFile \"YP\" \"$tmpPass\"\n#getPasswordFile \"NIS\" \"$tmpPass\"\ngetPasswordFile \"Other\" \"$tmpPass\"\n\n#\n# Get the user account from the password file.\n#\nawk 'BEGIN {FS=\":\"} {printf \"%s\\n\", $1}' $tmpPass | sort > ${userAccounts}\n\n#\n# Create the scrolling list.\n#\n${CDK_ALPHALIST} -T \"${title}\" -f ${userAccounts} -H -10 -W -20 2> ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`sed -e 's/^[ ]*//' -e 's/[ ]*$//' ${output}`\n\n#\n# Display the account information.\n#\nif [ -n \"$answer\" ]; then\n    displayAccountInformation $answer $tmpPass\nfi\n\n#\n# Clean up.\n#\nrm -f ${output} ${tmpPass} ${userAccounts}\n", "num_lines": 117}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: calendar.sh,v 1.1 2013/12/24 18:06:17 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the celendar widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_CALENDAR=\"${CDK_BINDIR=..}/cdkcalendar\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ndate=\"${TMPDIR=/tmp}/cal.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\nxpos=CENTER\nypos=CENTER\n\n#\n# Get today's date.\n#\nday=`date +%d`\nmonth=`date +%m`\nyear=`date +%Y`\n\n#\n# Chop up the command line.\n#\nset -- `getopt d:m:y:X:Y: $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -d) day=$2; shift 2;;\n         -m) month=$2; shift 2;;\n         -y) year=$2; shift 2;;\n         -X) xpos=$2; shift 2;;\n         -Y) ypos=$2; shift 2;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the title and buttons.\n#\ntitle=\"<C><#HL(22)>\n<C>Select a date\n<C><#HL(22)>\"\nbuttons=\" OK \nCancel \"\n\n#\n# Create the calendar widget.\n#\n${CDK_CALENDAR} -B \"${buttons}\" -d ${day} -m ${month} -y ${year} -T \"${title}\" -X ${xpos} -Y ${ypos} -O ${date} -S\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${date}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>You chose the following date\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C><#HL(10)>\" >> ${tmp}\necho \"<C>${answer}\" >> ${tmp}\necho \"<C><#HL(10)>\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${date}\n", "num_lines": 90}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: dialog.sh,v 1.1 2013/12/24 18:06:18 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the dialog widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_DIALOG=\"${CDK_BINDIR=..}/cdkdialog\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/dialog_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the message for the scrolling list.\n#\nmessage=\"<C>Pick which command\n<C>you wish to run.\"\n\n#\n# Create the button labels.\n#\ncommands=\"</B>who\n</B>w\n</B>uptime\n</B>date\n</B>pwd\n</B>whoami\n</B>df\n</B>fortune\"\n\n#\n# Create the dialog box.\n#\n${CDK_DIALOG} -m \"${message}\" -B \"${commands}\" 2> ${output}\nselection=$?\nif [ \"$selection\" -eq 255 ]; then\n   exit;\nfi\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the result of the command\" > ${tmp}\necho \" \" >> ${tmp}\n\n#\n# Determine which command to run.\n#\nif [ \"${selection}\" -eq 0 ]; then\n   who | awk '{printf \"</B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 1 ]; then\n   w | awk '{printf \"</B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 2 ]; then\n   uptime | awk '{printf \"<C></B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 3 ]; then\n   date | awk '{printf \"<C></B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 4 ]; then\n   pwd | awk '{printf \"<C></B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 5 ]; then\n   whoami | awk '{printf \"<C></B>%s\\n\", $0}' >> ${tmp}\nelif [ \"${selection}\" -eq 6 ]; then\n   #\n   # We will use the label demo to do this.\n   #\n   ./label.sh\n   rm -f ${tmp} ${output} ${fileSystemList}\n   exit 0;\nelif [ \"${selection}\" -eq 7 ]; then\n   fortune | awk '{printf \"</B>%s\\n\", $0}' >> ${tmp}\nfi\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output} ${fileSystemList}\n", "num_lines": 89}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: entry.sh,v 1.1 2013/12/24 18:06:19 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the entry widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_ENTRY=\"${CDK_BINDIR=..}/cdkentry\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/entry_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the title.\n#\ntitle=\"<C>  Type a simple string.  \"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the entry box.\n#\n${CDK_ENTRY} -f 20 -T \"${title}\" -B \"${buttons}\" -F \"</5>_ \" -O ${output} -S\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the string you typed in\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C></R>${answer}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output}\n", "num_lines": 55}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: fselect.sh,v 1.1 2013/12/24 18:06:20 vegogine Exp $\n\n#\n# Description:\n#\tThis demonstrates the CDK command line\n#\tinterface to the file selection widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_FSELECT=\"${CDK_BINDIR=..}/cdkfselect\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ndirectory=\".\"\nlabel=\"File: \"\ntitle=\"<C>Select a file\"\n\nbuttons=\" OK \n Cancel \"\n\nxpos=\"CENTER\"\nypos=\"CENTER\"\n\nwidth=0\nheight=-5\n\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\nfile=\"${TMPDIR=/tmp}/fs.$$\"\n\n#\n# Chop up the command line.\n#\nset -- `getopt d:L:T:X:Y:W:H: $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -d) directory=$2; shift 2;;\n         -T) title=$2; shift 2;;\n         -L) label=$2; shift 2;;\n         -X) xpos=$2; shift 2;;\n         -Y) ypos=$2; shift 2;;\n         -W) width=$2; shift 2;;\n         -H) height=$2; shift 2;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the CDK file selector.\n#\n${CDK_FSELECT} -d \"${directory}\" -T \"${title}\" -L \"${label}\" -X ${xpos} -Y ${ypos} -W ${width} -H ${height} -B \"${buttons}\" 2> ${file}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${file}`\n\n#\n# Diplay the file the user selected.\n#\necho \"<C>You selected the following file\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C><#HL(10)>\" >> ${tmp}\necho \"<C></B>${answer}\" >> ${tmp}\necho \"<C><#HL(10)>\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Press </R>space<!R> to continue.\" >> ${tmp}\n\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${file}\n", "num_lines": 83}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: itemlist.sh,v 1.1 2013/12/24 18:06:21 vegogine Exp $\n\n#\n# Description:\n# \t\tThis demonstrates the CDK command line\n# interface to the itemlist list widget.\n#\n\n#\n# This gets the password file.\n#\ngetPasswordFile()\n{\n   system=$1\n   file=$2\n\n   #\n   # Depeding on the system, get the password file\n   # using nicat, ypcat, or just plain old /etc/passwd\n   #\n   if [ \"$system\" = \"NIS\" ]; then\n      niscat passwd.org_dir | sort > $file\n   elif [ \"$system\" = \"YP\" ]; then\n      ypcat passwd | sort > $file\n   else\n      sort /etc/passwd > $file\n   fi\n}\n\n#\n# This displays account information.\n#\ndisplayAccountInformation()\n{\n   userAccount=$1\n   passwordFile=$2\n\n   #\n   # Get the user account information.\n   #\n   line=`grep \"^${userAccount}\" $passwordFile`\n   uid=`echo $line | cut -d: -f3`\n   gid=`echo $line | cut -d: -f4`\n   info=`echo $line | cut -d: -f5`\n   home=`echo $line | cut -d: -f6`\n   shell=`echo $line | cut -d: -f7`\n\n   #\n   # Create the label message information.\n   #\n   accountMessage=\"<C></U>Account\n<C><#HL(30)>\nAccount: </U>${userAccount}\nUID    : </U>${uid}\nGID    : </U>${gid}\nInfo   : </U>${info}\nHome   : </U>${home}\nShell  : </U>${shell}\n<C><#HL(30)>\n<C>Hit </R>space<!R> to continue\"\n\n   #\n   # Create the popup label.\n   #\n   ${CDK_LABEL} -m \"${accountMessage}\" -p \" \"\n}\n\n#\n# Create some global variables.\n#\nCDK_ITEMLIST=\"${CDK_BINDIR=..}/cdkitemlist\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ntmpPass=\"${TMPDIR=/tmp}/sl.$$\"\noutput=\"${TMPDIR=/tmp}/output.$$\"\nuserAccounts=\"${TMPDIR=/tmp}/ua.$$\"\n\nTYPE=\"Other\";\n\n#\n# Chop up the command line.\n#\nset -- `getopt nNh $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -n) TYPE=\"YP\"; shift;;\n         -N) TYPE=\"NIS\"; shift;;\n         -h) echo \"$0 [-n YP] [-N NIS+] [-h]\"; exit 0;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the message for the item list.\n#\ntitle=\"<C>Pick an account you want to view.\"\nlabel=\"Account Name \"\nbuttons=\" OK \n Cancel \"\n\n#\n# Get the password file and stick it into the temp file.\n#\ngetPasswordFile \"${TYPE}\" \"$tmpPass\"\n\n#\n# Get the user account from the password file.\n#\nawk 'BEGIN {FS=\":\"} {printf \"</R>%s\\n\", $1}' $tmpPass | sort > ${userAccounts}\n\n#\n# Create the item list.\n#\n${CDK_ITEMLIST} -d 3 -L \"${label}\" -T \"${title}\" -B \"${buttons}\" -f \"${userAccounts}\" 2> ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Display the account information.\n#\ndisplayAccountInformation $answer $tmpPass\n\n#\n# Clean up.\n#\nrm -f ${output} ${tmpPass} ${userAccounts}\n", "num_lines": 136}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: label.sh,v 1.1 2013/12/24 18:06:22 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the label widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ndfTmp=\"${TMPDIR=/tmp}/label.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\ntop=\"${TMPDIR=/tmp}/dfTop.$$\"\nbottom=\"${TMPDIR=/tmp}/dfBottom.$$\"\n\n#\n# Get the filesystem information.\n#\ngetDiskInfo()\n{\n   fileName=$1;\n   command=\"df\"\n\n   #\n   # Determine the type of operating system.\n   #\n   machine=`uname -s`\n   if [ \"$machine\" = \"SunOS\" ]; then\n      level=`uname -r`\n\n      if [ \"$level\" -gt 4 ]; then\n         command=\"df -kl\"\n      fi\n   else\n      if [ \"$machine\" = \"AIX\" ]; then\n         command=\"df -i\"\n      fi\n   fi\n\n   #\n   # Run the command.\n   #\n   ${command} > ${fileName}\n}\n\n#\n# Get the disk information.\n#\ngetDiskInfo ${dfTmp}\n\n#\n# Bold the first line of the df command.\n#\nhead -1 ${dfTmp} | awk '{printf \"</B>%s\\n\", $0}' > ${top}\ntail +2 ${dfTmp} > ${bottom}\n\n#\n# Create the message for the label widget.\n#\necho \"<C>This is the current\" > ${tmp}\necho \"<C>status of your local filesystems.\" >> ${tmp}\necho \"<C><#HL(2)>\" >> ${tmp}\ncat ${top} >> ${tmp}\ncat ${bottom} >> ${tmp}\necho \"<C><#HL(2)>\" >> ${tmp}\necho \"\" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f \"${tmp}\" -p \" \" -c \"ls\" -S\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output} ${dfTmp} ${top} ${bottom}\n", "num_lines": 82}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: matrix.sh,v 1.4 2005/12/27 17:07:00 tom Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the matrix widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_MATRIX=\"${CDK_BINDIR=..}/cdkmatrix\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\nfileSystemList=\"${TMPDIR=/tmp}/fsList.$$\"\ninfo=\"${TMPDIR=/tmp}/fsInfo.$$\"\ndiskInfo=\"${TMPDIR=/tmp}/diskInfo.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Get the filesystem information.\n#\ngetDiskInfo()\n{\n   fileName=$1;\n   command=\"df\"\n\n   #\n   # Determine the type of operating system.\n   #\n   machine=`uname -s`\n   if [ \"$machine\" = \"SunOS\" ]; then\n      level=`uname -r`\n\n      if [ \"$level\" -gt 4 ]; then\n         command=\"df -kl\"\n      fi\n   else\n      if [ \"$machine\" = \"AIX\" ]; then\n         command=\"df -i\"\n      fi\n   fi\n\n   #\n   # Run the command.\n   #\n   ${command} > ${fileName}\n}\n\n#\n# Get the disk information.\n#\ngetDiskInfo ${diskInfo}\n\n#\n# Create the row titles.\n#\nrowTitles=`tail +2 ${diskInfo} | awk '{printf \"%s\\n\", $1}'`\n\n#\n# Create the column titles.\n#\ncolTitles=\"KBytes\nUsed\nAvail\nCapacity\nMounted on\"\n\n#\n# Define the matrix title.\n#\ntitle=\"<C></U>Current Filesystem Information\"\n\n#\n# Create the data file to fill in the matrix.\n#\ntail +2 ${diskInfo} | awk '{printf \"%s\u0016%s\u0016%s\u0016%s\u0016%s\\n\", $2, $3, $4, $5, $6}' > ${info}\n\n#\n# Set the widths of the columns.\n#\ncolWidths=\"5\n5\n5\n5\n5\"\n\n#\n# Set the cells as uneditable.\n#\ntypes=\"VIEWONLY\nVIEWONLY\nVIEWONLY\nVIEWONLY\nVIEWONLY\"\n\nbuttons=\" OK \n Cancel \"\n\n#\n# Start the matrix.\n#\n${CDK_MATRIX} -r \"${rowTitles}\" -c \"${colTitles}\" -v 3 -w \"${colWidths}\" -d \"${info}\" -t \"${types}\" -T \"${title}\" -B \"${buttons}\" -O\"$tmp\"\nselected=$?\ntest $selected = 255 && exit 1\n\n#\n# Create the message for the label widget.\n#\necho \"<C>You chose button #${selected}\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n \n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f \"${tmp}\" -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${info} ${fileSystemList} ${tmp} ${diskInfo}\n", "num_lines": 124}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: mentry.sh,v 1.1 2013/12/24 18:06:23 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the multiple line entry widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_MENTRY=\"${CDK_BINDIR=..}/cdkmentry\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/mentry_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the title.\n#\ntitle=\"<C>Type in a short message.\"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the mentry box.\n#\n${CDK_MENTRY} -s 5 -v 10 -f 20 -T \"${title}\" -B \"${buttons}\" -F '_' -O ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the message you typed in\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C></R>${answer}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output}\n", "num_lines": 55}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: radio.sh,v 1.1 2013/12/24 18:06:24 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the radio widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_RADIO=\"${CDK_BINDIR=..}/cdkradio\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\nfileSystemList=\"${TMPDIR=/tmp}/fsList.$$\"\ndiskInfo=\"${TMPDIR=/tmp}/diskInfo.$$\"\noutput=\"${TMPDIR=/tmp}/radio_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Get the filesystem information.\n#\ngetDiskInfo()\n{\n   fileName=$1;\n   command=\"df\"\n\n   #\n   # Determine the type of operating system.\n   #\n   machine=`uname -s`\n   if [ \"$machine\" = \"SunOS\" ]; then\n      level=`uname -r`\n\n      if [ \"$level\" -gt 4 ]; then\n         command=\"df -kl\"\n      fi\n   else\n      if [ \"$machine\" = \"AIX\" ]; then\n         command=\"df -i\"\n      fi\n   fi\n\n   #\n   # Run the command.\n   #\n   ${command} > ${fileName}\n}\n\n#\n# Create the title for the scrolling list.\n#\ntitle=\"<C>Pick a filesystem to view.\"\nbuttons=\" OK \n Cancel \"\n\n#\n# Get a list of the local filesystems.\n#\ngetDiskInfo ${diskInfo}\n\n#\n# Create the file system list.\n#\ngrep \"^/\" ${diskInfo} | awk '{printf \"%s\\n\", $1}' > ${fileSystemList}\n\n#\n# Create the radio list.\n#\n${CDK_RADIO} -T \"${title}\" -f \"${fileSystemList}\" -c \"</U>*\" -B \"${buttons}\" 2> $output\nselected=$?\ntest $selected = 255 && exit 1\n\n#\n# The selection is now in the file $output.\n#\nfs=`cat ${output}`\necho \"<C></R>File Statistics on the filesystem ${fs}\" > ${tmp}\necho \" \" >> ${tmp}\ngrep \"${fs}\" ${diskInfo} | awk '{printf \"</B>%s\\n\", $0}' >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output} ${fileSystemList} ${diskInfo}\n", "num_lines": 96}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: scale.sh,v 1.1 2013/12/24 18:06:24 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the scale widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_SCALE=\"${CDK_BINDIR=..}/cdkscale\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/scale_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the title.\n#\ntitle=\"<C>Enter a value using the cursor keys.\"\nlabel=\"</R>Value\"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the scale box.\n#\n${CDK_SCALE} -f 20 -l 0 -h 100 -i 5 -L \"${label}\" -T \"${title}\" -B \"${buttons}\" -O ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the value you selected\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C></R>${answer}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output}\n", "num_lines": 56}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: scroll.sh,v 1.1 2013/12/24 18:06:25 vegogine Exp $\n\n#\n# Description:\n# \t\tThis demonstrates the CDK command line\n# interface to the scrolling list widget.\n#\n\n#\n# This gets the password file.\n#\ngetPasswordFile()\n{\n   system=$1\n   file=$2\n\n   #\n   # Depeding on the system, get the password file\n   # using nicat, ypcat, or just plain old /etc/passwd\n   #\n   if [ \"$system\" = \"NIS\" ]; then\n      niscat passwd.org_dir > $file\n   elif [ \"$system\" = \"YP\" ]; then\n      ypcat passwd > $file\n   else\n      cp /etc/passwd $file\n   fi\n}\n\n#\n# This displays account information.\n#\ndisplayAccountInformation()\n{\n   userAccount=$1\n   passwordFile=$2\n\n   #\n   # Get the user account information.\n   #\n   line=`grep \"^${userAccount}\" $passwordFile`\n   uid=`echo $line | cut -d: -f3`\n   gid=`echo $line | cut -d: -f4`\n   info=`echo $line | cut -d: -f5`\n   home=`echo $line | cut -d: -f6`\n   shell=`echo $line | cut -d: -f7`\n\n   #\n   # Create the label message information.\n   #\n   accountMessage=\"<C></U>Account\n<C><#HL(30)>\nAccount: </U>${userAccount}\nUID    : </U>${uid}\nGID    : </U>${gid}\nInfo   : </U>${info}\nHome   : </U>${home}\nShell  : </U>${shell}\n<C><#HL(30)>\n<C>Hit </R>space<!R> to continue\"\n\n   #\n   # Create the popup label.\n   #\n   ${CDK_LABEL} -m \"${accountMessage}\" -p \" \"\n}\n\n#\n# Create some global variables.\n#\nCDK_SCROLL=\"${CDK_BINDIR=..}/cdkscroll\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\ntmpPass=\"${TMPDIR=/tmp}/sl.$$\"\noutput=\"${TMPDIR=/tmp}/output.$$\"\nuserAccounts=\"${TMPDIR=/tmp}/ua.$$\"\n\nTYPE=\"Other\"\n\n#\n# Chop up the command line.\n#\nset -- `getopt nNh $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -n) TYPE=\"YP\"; shift;;\n         -N) TYPE=\"NIS\"; shift;;\n         -h) echo \"$0 [-n YP] [-N NIS+] [-h]\"; exit 0;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the message for the scrolling list.\n#\ntitle=\"<C><#HL(30)>\n<C>Pick an account you want to view.\n<C><#HL(30)>\"\nbuttons=\" OK \n Cancel \"\n\n#\n# Get the password file and stick it into the temp file.\n#\ngetPasswordFile \"${TYPE}\" \"$tmpPass\"\n\n#\n# Get the user account from the password file.\n#\nawk 'BEGIN {FS=\":\"} {printf \"%s\\n\", $1}' $tmpPass | sort > ${userAccounts}\n\n#\n# Create the scrolling list.\n#\n${CDK_SCROLL} -T \"${title}\" -f ${userAccounts} -n -B \"${buttons}\" 2> ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Display the account information.\n#\ndisplayAccountInformation $answer $tmpPass\n\n#\n# Clean up.\n#\nrm -f ${output} ${tmpPass} ${userAccounts}\n", "num_lines": 137}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: selection.sh,v 1.1 2013/12/24 18:06:25 vegogine Exp $\n\n#\n# Description:\n#\tThis demonstrates the CDK command line\n#\tinterface to the selection widget.\n#\n\n#\n# This gets the password file.\n#\ngetPasswordFile()\n{\n   system=$1\n   file=$2\n\n   #\n   # Depending on the system, get the password file\n   # using nicat, ypcat, or just plain old /etc/passwd\n   #\n   if [ \"$system\" = \"NIS\" ]; then\n      niscat passwd.org_dir > $file\n   elif [ \"$system\" = \"YP\" ]; then\n      ypcat passwd > $file\n   else\n      cp /etc/passwd $file\n   fi\n}\n\n#\n# This displays account information.\n#\ndisplayAccountInformation()\n{\n   totalSelections=$1\n   currentSelection=$2\n   userAccount=$3\n   passwordFile=$4\n\n   #\n   # Get the user account information.\n   #\n   line=`grep \"^${userAccount}\" $passwordFile`\n   uid=`echo $line | cut -d: -f3`\n   gid=`echo $line | cut -d: -f4`\n   info=`echo $line | cut -d: -f5`\n   home=`echo $line | cut -d: -f6`\n   shell=`echo $line | cut -d: -f7`\n\n   #\n   # Create the label message information.\n   #\n   accountMessage=\"<C></U>Account ${currentSelection}/${totalSelections}\n<C><#HL(30)>\nAccount: </U>${userAccount}\nUID    : </U>${uid}\nGID    : </U>${gid}\nInfo   : </U>${info}\nHome   : </U>${home}\nShell  : </U>${shell}\n<C><#HL(30)>\n<C>Hit </R>space<!R> to continue\"\n\n   #\n   # Create the popup label.\n   #\n   ${CDK_LABEL} -m \"${accountMessage}\" -p \" \"\n}\n\n#\n# Define where the CDK widgets are.\n#\nCDK_SELECTION=\"${CDK_BINDIR=..}/cdkselection\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\nTYPE=\"Other\"\n\n#\n# Define the output files.\n#\naccountList=\"${TMPDIR=/tmp}/accList.$$\"\nuserAccounts=\"${TMPDIR=/tmp}/userAccList.$$\"\noutput=\"${TMPDIR=/tmp}/selection_output.$$\"\ntmpPass=\"${TMPDIR=/tmp}/ps.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Chop up the command line.\n#\nset -- `getopt nNh $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -n) TYPE=\"YP\"; shift;;\n         -N) TYPE=\"NIS\"; shift;;\n         -h) echo \"$0 [-n YP] [-N NIS+] [-h]\"; exit 0;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the message for the selection list.\n#\ntitle=\"<C>Pick a user account to view.\"\n\n#\n# Get the password file and stick it into the temp file.\n#\ngetPasswordFile \"${TYPE}\" \"$tmpPass\"\n\n#\n# Create the user account list.\n#\nawk 'BEGIN {FS=\":\"} {printf \"%s\\n\", $1}' $tmpPass | sort > ${userAccounts}\nawk '{printf \"<C></B>%s\\n\", $1}' ${userAccounts} > ${accountList}\naccounts=`cat ${userAccounts}`\n\n#\n# Create the choices list.\n#\nchoices=\"<C></B>No \n<C></B> Yes \"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the selection list.\n#\n${CDK_SELECTION} -T \"${title}\" -f \"${accountList}\" -c \"${choices}\" -B \"${buttons}\"  2> $output\nselected=$?\ntest $selected = 255 && exit 1\n\n#\n# Initialize the variables.\n#\nselection=\"\"\nvalue=\"\"\n\n#\n# Count how many were selected.\n#\ncount=`grep -c \"^1\" ${output}`\ncurrent=0\n\n#\n# Create the label.\n#\nfor i in `cat ${output}`\ndo\n   #\n   # Since every other variable is value/selection, we\n   # store every other value in the correct variable.\n   #\n   if [ \"$value\" = \"\" ]; then\n      value=\"$i\"\n   else\n      selection=\"$i\"\n\n      #\n      # Only display the selected accounts.\n      #\n      if [ \"$value\" -eq 1 ]; then\n         #\n         # Increment our counter.\n         #\n         current=`expr $current + 1`\n\n         #\n         # Display the account information.\n         #\n         displayAccountInformation $count $current $selection $tmpPass\n      fi\n\n      #\n      # Reset the variables.\n      #\n      value=\"\"\n      selection=\"\"\n   fi\ndone\n\n#\n# Clean up.\n#\nrm -f ${accountList} ${userAccounts} ${output} ${tmpPass} ${tmp}\n", "num_lines": 192}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: slider.sh,v 1.1 2013/12/24 18:06:25 vegogine Exp $\n\n#\n# Description:\n#\tThis demonstrates the CDK command line\n#\tinterface to the slider widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_SLIDER=\"${CDK_BINDIR=..}/cdkslider\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/slider_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the title.\n#\ntitle=\"<C>Enter a value using the cursor keys\"\nlabel=\"Value: \"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the slider box.\n#\n${CDK_SLIDER} -f 20 -l 0 -h 100 -i 5 -L \"${label}\" -T \"${title}\" -F \"</R>*\" -B \"${buttons}\" -O ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the value you selected\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C></R>${answer}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output}\n", "num_lines": 56}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: template.sh,v 1.1 2013/12/24 18:06:26 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the template widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_TEMPLATE=\"${CDK_BINDIR=..}/cdktemplate\"\nCDK_LABEL=\"${CDK_BINDIR=..}/cdklabel\"\n\noutput=\"${TMPDIR=/tmp}/template_output.$$\"\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\n\n#\n# Create the title.\n#\ntitle=\"<C>               Type in the                 \n<C>IP Address for this machine.\"\nbuttons=\" OK \n Cancel \"\n\n#\n# Create the template box.\n#\n${CDK_TEMPLATE} -p \"###.###.###.###\" -o \"___.___.___.___\" -T \"${title}\" -P -B \"${buttons}\" 2> ${output}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${output}`\n\n#\n# Create the message for the label widget.\n#\necho \"<C>Here is the IP you typed in\" > ${tmp}\necho \" \" >> ${tmp}\necho \"<C></R>${answer}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>You chose button #${selected}\" >> ${tmp}\necho \" \" >> ${tmp}\necho \"<C>Hit </R>space<!R> to continue.\" >> ${tmp}\n\n#\n# Create the label widget to display the information.\n#\n${CDK_LABEL} -f ${tmp} -p \" \"\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${output}\n", "num_lines": 56}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# $Id: viewer.sh,v 1.1 2013/12/24 18:06:26 vegogine Exp $\n\n#\n# Description:\n#\t\tThis demonstrates the CDK command line\n# interface to the viewer widget.\n#\n\n#\n# Create some global variables.\n#\nCDK_FSELECT=\"${CDK_BINDIR=..}/cdkfselect\"\nCDK_VIEWER=\"${CDK_BINDIR=..}/cdkviewer\"\n\ntmp=\"${TMPDIR=/tmp}/tmp.$$\"\nfile=\"${TMPDIR=/tmp}/fs.$$\"\n\ndirectory=\".\"\nxpos=CENTER\nypos=CENTER\nwidth=\"-2\"\nheight=\"0\"\ninterpret=0\n\n#\n# Chop up the command line.\n#\nset -- `getopt d:x:y:w:h:i $*`\nif [ $? != 0 ]\nthen\n   echo $USAGE\n   exit 2\nfi\nfor c in $*\ndo\n    case $c in\n         -d) directory=$2; shift 2;;\n         -x) xpos=$2; shift 2;;\n         -y) ypos=$2; shift 2;;\n         -w) width=$2; shift 2;;\n         -h) height=$2; shift 2;;\n         -i) interpret=1; shift 1;;\n         --) shift; break;;\n    esac\ndone\n\n#\n# Create the CDK file selector.\n#\n${CDK_FSELECT} -T \"<C>Select a file\" -d \"${directory}\" 2> ${file}\nselected=$?\ntest $selected = 255 && exit 1\n\nanswer=`cat ${file}`\n\n#\n# Create the title and buttons for the viewer.\n#\ntitle=\"<C>CDK File Viewer Widget\n<C></U>${answer}\"\nbuttons=\"OK\"\n\n#\n# Create the file viewer.\n#\nif [ \"$interpret\" -eq 1 ]; then\n   ${CDK_VIEWER} -f \"${answer}\" -T \"${title}\" -B \"${buttons}\" -i -X ${xpos} -Y ${ypos} -H \"${height}\" -W \"${width}\"\nelse\n   ${CDK_VIEWER} -f \"${answer}\" -T \"${title}\" -B \"${buttons}\" -X ${xpos} -Y ${ypos} -H \"${height}\" -W \"${width}\" -B \"${buttons}\"\nfi\n\n#\n# Clean up.\n#\nrm -f ${tmp} ${file}\n", "num_lines": 77}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.6-15\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2015-10-07.11; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    _G_rc_run_hooks=false\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      if eval $_G_hook '\"$@\"'; then\n        # store returned options list back into positional\n        # parameters for next 'cmd' execution.\n        eval _G_hook_result=\\$${_G_hook}_result\n        eval set dummy \"$_G_hook_result\"; shift\n        _G_rc_run_hooks=:\n      fi\n    done\n\n    $_G_rc_run_hooks && func_run_hooks_result=$_G_hook_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, you may remove/edit\n# any options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  In this case you also must return $EXIT_SUCCESS to let the\n# hook's caller know that it should pay attention to\n# '<hooked_function_name>_result'.  Returning $EXIT_FAILURE signalizes that\n# arguments are left untouched by the hook and therefore caller will ignore the\n# result variable.\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  There is\n#        # no need to do the equivalent (but slower) action:\n#        # func_quote_for_eval ${1+\"$@\"}\n#        # my_options_prep_result=$func_quote_for_eval_result\n#        false\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\", we could need that later\n#                         # if $args_changed is true.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        if $args_changed; then\n#          func_quote_for_eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_for_eval_result\n#        fi\n#\n#        $args_changed\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        false\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    _G_func_options_finish_exit=false\n    if func_run_hooks func_options ${1+\"$@\"}; then\n      func_options_finish_result=$func_run_hooks_result\n      _G_func_options_finish_exit=:\n    fi\n\n    $_G_func_options_finish_exit\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_rc_options=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      if eval func_$my_func '${1+\"$@\"}'; then\n        eval _G_res_var='$'\"func_${my_func}_result\"\n        eval set dummy \"$_G_res_var\" ; shift\n        _G_rc_options=:\n      fi\n    done\n\n    # Save modified positional parameters for caller.  As a top-level\n    # options-parser function we always need to set the 'func_options_result'\n    # variable (regardless the $_G_rc_options value).\n    if $_G_rc_options; then\n      func_options_result=$_G_res_var\n    else\n      func_quote_for_eval ${1+\"$@\"}\n      func_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_options\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning $EXIT_SUCCESS (otherwise $EXIT_FAILURE is returned).\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    _G_rc_options_prep=false\n    if func_run_hooks func_options_prep ${1+\"$@\"}; then\n      _G_rc_options_prep=:\n      # save modified positional parameters for caller\n      func_options_prep_result=$func_run_hooks_result\n    fi\n\n    $_G_rc_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    _G_rc_parse_options=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      if func_run_hooks func_parse_options ${1+\"$@\"}; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n        _G_rc_parse_options=:\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_rc_parse_options=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_rc_parse_options=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      $_G_match_parse_options && _G_rc_parse_options=:\n    done\n\n\n    if $_G_rc_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_parse_options\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    _G_rc_validate_options=false\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    if func_run_hooks func_validate_options ${1+\"$@\"}; then\n      # save modified positional parameters for caller\n      func_validate_options_result=$func_run_hooks_result\n      _G_rc_validate_options=:\n    fi\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    $_G_rc_validate_options\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.6-15\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_options_prep\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_parse_options\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -static-*            direct GCC to link specific libraries statically\n      # -fcilkplus           Cilk Plus language extension features for C/C++\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11252}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# ***************************************************************************\n# *                                  _   _ ____  _\n# *  Project                     ___| | | |  _ \\| |\n# *                             / __| | | | |_) | |\n# *                            | (__| |_| |  _ <| |___\n# *                             \\___|\\___/|_| \\_\\_____|\n# *\n# * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n# *\n# * This software is licensed as described in the file COPYING, which\n# * you should have received as part of this distribution. The terms\n# * are also available at https://curl.se/docs/copyright.html.\n# *\n# * You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# * copies of the Software, and permit persons to whom the Software is\n# * furnished to do so, under the terms of the COPYING file.\n# *\n# * This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# * KIND, either express or implied.\n# *\n# ***************************************************************************\n# This shell script creates a fresh ca-bundle.crt file for use with libcurl.\n# It extracts all ca certs it finds in the local Firefox database and converts\n# them all into PEM format.\n#\ndb=`ls -1d $HOME/.mozilla/firefox/*default*`\nout=$1\n\nif test -z \"$out\"; then\n  out=\"ca-bundle.crt\" # use a sensible default\nfi\n\ncurrentdate=`date`\n\ncat >$out <<EOF\n##\n## Bundle of CA Root Certificates\n##\n## Converted at: ${currentdate}\n## These were converted from the local Firefox directory by the db2pem script.\n##\nEOF\n\n\ncertutil -L -h 'Builtin Object Token' -d $db | \\\ngrep ' *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$' | \\\nsed -e 's/ *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$//' -e 's/\\(.*\\)/\"\\1\"/' | \\\nsort | \\\nwhile read nickname; \\\n do echo $nickname | sed -e \"s/Builtin Object Token://g\"; \\\neval certutil -d $db -L -n \"$nickname\" -a ; \\\ndone >> $out\n", "num_lines": 54}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n\n\nsetenv()\n\n{\n        #       Define and export.\n\n        eval ${1}=\"${2}\"\n        export ${1}\n}\n\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in $TOPDIR/packages/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nTOPDIR=`dirname \"${TOPDIR}\"`\nexport SCRIPTDIR TOPDIR\n\n#  Extract the SONAME from the library makefile.\n\nSONAME=`sed -e '/^VERSIONINFO=/!d' -e 's/^.* \\([0-9]*\\):.*$/\\1/' -e 'q' \\\n                                                < \"${TOPDIR}/lib/Makefile.am\"`\nexport SONAME\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nsetenv TARGETLIB        'CURL'                  # Target OS/400 program library.\nsetenv STATBNDDIR       'CURL_A'                # Static binding directory.\nsetenv DYNBNDDIR        'CURL'                  # Dynamic binding directory.\nsetenv SRVPGM           \"CURL.${SONAME}\"        # Service program.\nsetenv TGTCCSID         '500'                   # Target CCSID of objects.\nsetenv DEBUG            '*ALL'                  # Debug level.\nsetenv OPTIMIZE         '10'                    # Optimisation level\nsetenv OUTPUT           '*NONE'                 # Compilation output option.\nsetenv TGTRLS           'V6R1M0'                # Target OS release.\nsetenv IFSDIR           '/curl'                 # Installation IFS directory.\n\n#       Define ZLIB availability and locations.\n\nsetenv WITH_ZLIB        0                       # Define to 1 to enable.\nsetenv ZLIB_INCLUDE     '/zlib/include'         # ZLIB include IFS directory.\nsetenv ZLIB_LIB         'ZLIB'                  # ZLIB library.\nsetenv ZLIB_BNDDIR      'ZLIB_A'                # ZLIB binding directory.\n\n#       Define LIBSSH2 availability and locations.\n\nsetenv WITH_LIBSSH2     0                       # Define to 1 to enable.\nsetenv LIBSSH2_INCLUDE  '/libssh2/include'      # LIBSSH2 include IFS directory.\nsetenv LIBSSH2_LIB      'LIBSSH2'               # LIBSSH2 library.\nsetenv LIBSSH2_BNDDIR   'LIBSSH2_A'             # LIBSSH2 binding directory.\n\n\n################################################################################\n\n#       Need to get the version definitions.\n\nLIBCURL_VERSION=`grep '^#define  *LIBCURL_VERSION '                     \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/.*\"\\(.*\\)\".*/\\1/'`\nLIBCURL_VERSION_MAJOR=`grep '^#define  *LIBCURL_VERSION_MAJOR '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_MAJOR  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_MINOR=`grep '^#define  *LIBCURL_VERSION_MINOR '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_MINOR  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_PATCH=`grep '^#define  *LIBCURL_VERSION_PATCH '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_PATCH  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_NUM=`grep '^#define  *LIBCURL_VERSION_NUM '             \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_NUM  *0x\\([^ ]*\\).*/\\1/'`\nLIBCURL_TIMESTAMP=`grep '^#define  *LIBCURL_TIMESTAMP '                 \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/.*\"\\(.*\\)\".*/\\1/'`\nexport LIBCURL_VERSION\nexport LIBCURL_VERSION_MAJOR LIBCURL_VERSION_MINOR LIBCURL_VERSION_PATCH\nexport LIBCURL_VERSION_NUM LIBCURL_TIMESTAMP\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nLIBIFSNAME=\"/QSYS.LIB/${TARGETLIB}.LIB\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       canonicalize_path path\n#\n#       Return canonicalized path as:\n#       - Absolute\n#       - No . or .. component.\n\ncanonicalize_path()\n\n{\n        if expr \"${1}\" : '^/' > /dev/null\n        then    P=\"${1}\"\n        else    P=\"`pwd`/${1}\"\n        fi\n\n        R=\n        IFSSAVE=\"${IFS}\"\n        IFS=\"/\"\n\n        for C in ${P}\n        do      IFS=\"${IFSSAVE}\"\n                case \"${C}\" in\n                .)      ;;\n                ..)     R=`expr \"${R}\" : '^\\(.*/\\)..*'`\n                        ;;\n                ?*)     R=\"${R}${C}/\"\n                        ;;\n                *)      ;;\n                esac\n        done\n\n        IFS=\"${IFSSAVE}\"\n        echo \"/`expr \"${R}\" : '^\\(.*\\)/'`\"\n}\n\n\n#       make_module module_name source_name [additional_definitions]\n#\n#       Compile source name into ASCII module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n\nmake_module()\n\n{\n        MODULES=\"${MODULES} ${1}\"\n        MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n        action_needed \"${MODIFSNAME}\" \"${2}\" || return 0;\n        SRCDIR=`dirname \\`canonicalize_path \"${2}\"\\``\n\n        #       #pragma convert has to be in the source file itself, i.e.\n        #               putting it in an include file makes it only active\n        #               for that include file.\n        #       Thus we build a temporary file with the pragma prepended to\n        #               the source file and we compile that themporary file.\n\n        echo \"#line 1 \\\"${2}\\\"\" > __tmpsrcf.c\n        echo \"#pragma convert(819)\" >> __tmpsrcf.c\n        echo \"#line 1\" >> __tmpsrcf.c\n        cat \"${2}\" >> __tmpsrcf.c\n        CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('__tmpsrcf.c')\"\n#       CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST *SHOWINC *SHOWSYS)\"\n        CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST)\"\n        CMD=\"${CMD} LOCALETYPE(*LOCALE) FLAG(10)\"\n        CMD=\"${CMD} INCDIR('/qibm/proddata/qadrt/include'\"\n        CMD=\"${CMD} '${TOPDIR}/include/curl' '${TOPDIR}/include' '${SRCDIR}'\"\n        CMD=\"${CMD} '${TOPDIR}/packages/OS400'\"\n\n        if [ \"${WITH_ZLIB}\" != \"0\" ]\n        then    CMD=\"${CMD} '${ZLIB_INCLUDE}'\"\n        fi\n\n        if [ \"${WITH_LIBSSH2}\" != \"0\" ]\n        then    CMD=\"${CMD} '${LIBSSH2_INCLUDE}'\"\n        fi\n\n        CMD=\"${CMD} ${INCLUDES})\"\n        CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n        CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n        CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n        CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n\n        DEFINES=\"${3} BUILDING_LIBCURL\"\n\n        if [ \"${WITH_ZLIB}\" != \"0\" ]\n        then    DEFINES=\"${DEFINES} HAVE_LIBZ HAVE_ZLIB_H\"\n        fi\n\n        if [ \"${WITH_LIBSSH2}\" != \"0\" ]\n        then    DEFINES=\"${DEFINES} USE_LIBSSH2 HAVE_LIBSSH2_H\"\n        fi\n\n        if [ \"${DEFINES}\" ]\n        then    CMD=\"${CMD} DEFINE(${DEFINES})\"\n        fi\n\n        system \"${CMD}\"\n        rm -f __tmpsrcf.c\n        LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        if [ \"${2}\" = 'nomangle' ]\n        then    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        else    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^CURL_*/C/'                                   \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        fi\n}\n\n\n#       Copy IFS file replacing version info.\n\nversioned_copy()\n\n{\n        sed -e \"s/@LIBCURL_VERSION@/${LIBCURL_VERSION}/g\"               \\\n            -e \"s/@LIBCURL_VERSION_MAJOR@/${LIBCURL_VERSION_MAJOR}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_MINOR@/${LIBCURL_VERSION_MINOR}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_PATCH@/${LIBCURL_VERSION_PATCH}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_NUM@/${LIBCURL_VERSION_NUM}/g\"       \\\n            -e \"s/@LIBCURL_TIMESTAMP@/${LIBCURL_TIMESTAMP}/g\"           \\\n                < \"${1}\" > \"${2}\"\n}\n", "num_lines": 283}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       Installation of the header files in the OS/400 library.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/include\"\n\n\n#       Create the OS/400 source program file for the header files.\n\nSRCPF=\"${LIBIFSNAME}/H.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('curl: Header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the header files.\n\nIFSINCLUDE=\"${IFSDIR}/include/curl\"\n\nif action_needed \"${IFSINCLUDE}\"\nthen    mkdir -p \"${IFSINCLUDE}\"\nfi\n\n\n#       Enumeration values are used as va_arg tagfields, so they MUST be\n#               integers.\n\ncopy_hfile()\n\n{\n        destfile=\"${1}\"\n        srcfile=\"${2}\"\n        shift\n        shift\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n' < \"${srcfile}\" > \"${destfile}\"\n}\n\n#       Copy the header files.\n\nfor HFILE in curl/*.h ${SCRIPTDIR}/ccsidcurl.h\ndo      case \"`basename \\\"${HFILE}\\\" .h`\" in\n        stdcheaders|typecheck-gcc)\n                continue;;\n        esac\n\n        DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\" nomangle`.MBR\"\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    copy_hfile \"${DEST}\" \"${HFILE}\"\n                IFSDEST=\"${IFSINCLUDE}/`basename \\\"${HFILE}\\\"`\"\n                rm -f \"${IFSDEST}\"\n                ln -s \"${DEST}\" \"${IFSDEST}\"\n        fi\ndone\n\n\n#       Copy the ILE/RPG header file, setting-up version number.\n\nversioned_copy \"${SCRIPTDIR}/curl.inc.in\" \"${SRCPF}/CURL.INC.MBR\"\nrm -f \"${IFSINCLUDE}/curl.inc.rpgle\"\nln -s \"${SRCPF}/CURL.INC.MBR\" \"${IFSINCLUDE}/curl.inc.rpgle\"\n\n\n#       Duplicate file H as CURL to support more include path forms.\n\nif action_needed \"${LIBIFSNAME}/CURL.FILE\"\nthen    :\nelse    system \"DLTF FILE(${TARGETLIB}/CURL)\"\nfi\n\nCMD=\"CRTDUPOBJ OBJ(H) FROMLIB(${TARGETLIB}) OBJTYPE(*FILE) TOLIB(*FROMLIB)\"\nCMD=\"${CMD} NEWOBJ(CURL) DATA(*YES)\"\nsystem \"${CMD}\"\n", "num_lines": 105}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       libcurl compilation script for the OS/400.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/lib\"\n\n#       Need to have IFS access to the mih/cipher header file.\n\nif action_needed cipher.mih '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR'\nthen    rm -f cipher.mih\n        ln -s '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR' cipher.mih\nfi\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"libcurl version '\"${LIBCURL_VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1998-2016 Daniel Stenberg et al. OS/400 version by P. Monnerat\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nsed -e ':begin'                                                         \\\n    -e '/\\\\$/{'                                                         \\\n    -e 's/\\\\$/ /'                                                       \\\n    -e 'N'                                                              \\\n    -e 'bbegin'                                                         \\\n    -e '}'                                                              \\\n    -e 's/\\n//g'                                                        \\\n    -e 's/[[:space:]]*$//'                                              \\\n    -e 's/^\\([A-Za-z][A-Za-z0-9_]*\\)[[:space:]]*=[[:space:]]*\\(.*\\)/\\1=\"\\2\"/' \\\n    -e 's/\\$(\\([A-Za-z][A-Za-z0-9_]*\\))/${\\1}/g'                        \\\n        < Makefile.inc > tmpscript.sh\n. ./tmpscript.sh\n\n\n#       Compile the sources into modules.\n\nINCLUDES=\"'`pwd`'\"\n\n# Create a small C program to check ccsidcurl.c is up to date\nif action_needed \"${LIBIFSNAME}/CHKSTRINGS.PGM\"\nthen\n  CMD=\"CRTBNDC PGM(${TARGETLIB}/CHKSTRINGS) SRCSTMF('${SCRIPTDIR}/chkstrings.c')\"\n  CMD=\"${CMD} INCDIR('${TOPDIR}/include/curl' '${TOPDIR}/include' '${SRCDIR}' ${INCLUDES})\"\n  system -i \"${CMD}\"\n  if [ $? -ne 0 ]\n  then\n    echo \"ERROR: Failed to build CHKSTRINGS *PGM object!\"\n    exit 2\n  else\n    ${LIBIFSNAME}/CHKSTRINGS.PGM\n    if [ $? -ne 0 ]\n    then\n      echo \"ERROR: CHKSTRINGS failed!\"\n      exit 2\n    fi\n  fi\nfi\n\nmake_module     OS400SYS        \"${SCRIPTDIR}/os400sys.c\"\nmake_module     CCSIDCURL       \"${SCRIPTDIR}/ccsidcurl.c\"\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('LibCurl API static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} TEXT('curl: build tools')\"\n        system \"${CMD}\"\nfi\n\n\n#       Gather the list of symbols to export.\n\nEXPORTS=`grep '^CURL_EXTERN[[:space:]]'                                 \\\n              \"${TOPDIR}\"/include/curl/*.h                              \\\n              \"${SCRIPTDIR}/ccsidcurl.h\"                                |\n         sed -e 's/^.*CURL_EXTERN[[:space:]]\\(.*\\)(.*$/\\1/'             \\\n             -e 's/[[:space:]]*$//'                                     \\\n             -e 's/^.*[[:space:]][[:space:]]*//'                        \\\n             -e 's/^\\*//'                                               \\\n             -e 's/(\\(.*\\))/\\1/'`\n\n#       Create the service program exportation file in DB2 member if needed.\n\nBSF=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\n\nif action_needed \"${BSF}\" Makefile.am\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    echo \" STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('LIBCURL_${SONAME}')\" \\\n            > \"${BSF}\"\n        for EXPORT in ${EXPORTS}\n        do      echo ' EXPORT    SYMBOL(\"'\"${EXPORT}\"'\")' >> \"${BSF}\"\n        done\n\n        echo ' ENDPGMEXP' >> \"${BSF}\"\nfi\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR}\"\n        if [ \"${WITH_ZLIB}\" != 0 ]\n        then    CMD=\"${CMD} ${ZLIB_LIB}/${ZLIB_BNDDIR}\"\n                liblist -a \"${ZLIB_LIB}\"\n        fi\n        if [ \"${WITH_LIBSSH2}\" != 0 ]\n        then    CMD=\"${CMD} ${LIBSSH2_LIB}/${LIBSSH2_BNDDIR}\"\n                liblist -a \"${LIBSSH2_LIB}\"\n        fi\n        CMD=\"${CMD})\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS QGLDCLNT QGLDBRDR)\"\n        CMD=\"${CMD} TEXT('curl API library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('LibCurl API dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n\n\n#       Rebuild the formdata test if needed.\n\nif [ \"${TEST_FORMDATA}\" ]\nthen    MODULES=\n        make_module TFORMDATA   formdata.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TSTREQUAL   strequal.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TMEMDEBUG   memdebug.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TMPRINTF    mprintf.c       \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TSTRERROR   strerror.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        #       The following modules should not be needed (see comment in\n        #               formdata.c. However, there are some unsatisfied\n        #               external references leading in the following\n        #               modules to be (recursively) needed.\n        MODULES=\"${MODULES} EASY STRDUP SSLGEN GSKIT HOSTIP HOSTIP4 HOSTIP6\"\n        MODULES=\"${MODULES} URL HASH TRANSFER GETINFO COOKIE SENDF SELECT\"\n        MODULES=\"${MODULES} INET_NTOP SHARE HOSTTHRE MULTI LLIST FTP HTTP\"\n        MODULES=\"${MODULES} HTTP_DIGES HTTP_CHUNK HTTP_NEGOT TIMEVAL HOSTSYN\"\n        MODULES=\"${MODULES} CONNECT SOCKS PROGRESS ESCAPE INET_PTON GETENV\"\n        MODULES=\"${MODULES} DICT LDAP TELNET FILE TFTP NETRC PARSEDATE\"\n        MODULES=\"${MODULES} SPEEDCHECK SPLAY BASE64 SECURITY IF2IP MD5\"\n        MODULES=\"${MODULES} KRB5 OS400SYS\"\n\n        PGMIFSNAME=\"${LIBIFSNAME}/TFORMDATA.PGM\"\n\n        if action_needed \"${PGMIFSNAME}\"\n        then    LINK=YES\n        fi\n\n        if [ \"${LINK}\" ]\n        then    CMD=\"CRTPGM PGM(${TARGETLIB}/TFORMDATA)\"\n                CMD=\"${CMD} ENTMOD(QADRT/QADRTMAIN2)\"\n                CMD=\"${CMD} MODULE(\"\n\n                for MODULE in ${MODULES}\n                do      CMD=\"${CMD} ${TARGETLIB}/${MODULE}\"\n                done\n\n                CMD=\"${CMD} ) BNDSRVPGM(QADRTTS)\"\n                CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n                system \"${CMD}\"\n        fi\nfi\n", "num_lines": 246}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#\n#       Not implemented yet on OS/400.\n", "num_lines": 26}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       tests compilation script for the OS/400.\n#\n\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/tests\"\n\n\n#       tests directory not implemented yet.\n\n\n#       Process the libtest subdirectory.\n\ncd libtest\n\n#       Get definitions from the Makefile.inc file.\n#       The `sed' statement works as follows:\n#       _ Join \\nl-separated lines.\n#       _ Retain only lines that begins with \"identifier =\".\n#       _ Turn these lines into shell variable assignments.\n\neval \"`sed -e ': begin'                                                 \\\n        -e '/\\\\\\\\$/{'                                                   \\\n        -e 'N'                                                          \\\n        -e 's/\\\\\\\\\\\\n/ /'                                               \\\n        -e 'b begin'                                                    \\\n        -e '}'                                                          \\\n        -e '/^[A-Za-z_][A-Za-z0-9_]*[[:space:]]*[=]/b keep'             \\\n        -e 'd'                                                          \\\n        -e ': keep'                                                     \\\n        -e 's/[[:space:]]*=[[:space:]]*/=/'                             \\\n        -e 's/=\\\\(.*[^[:space:]]\\\\)[[:space:]]*$/=\\\\\"\\\\1\\\\\"/'           \\\n        -e 's/\\\\$(\\\\([^)]*\\\\))/${\\\\1}/g'                                \\\n        < Makefile.inc`\"\n\n#       Special case: redefine chkhostname compilation parameters.\n\nchkhostname_SOURCES=chkhostname.c\nchkhostname_LDADD=curl_gethostname.o\n\n#       Compile all programs.\n#       The list is found in variable \"noinst_PROGRAMS\"\n\nINCLUDES=\"'${TOPDIR}/tests/libtest' '${TOPDIR}/lib'\"\n\nfor PGM in ${noinst_PROGRAMS}\ndo      DB2PGM=`db2_name \"${PGM}\"`\n        PGMIFSNAME=\"${LIBIFSNAME}/${DB2PGM}.PGM\"\n\n        #       Extract preprocessor symbol definitions from compilation\n        #               options for the program.\n\n        PGMCFLAGS=\"`eval echo \\\"\\\\${${PGM}_CFLAGS}\\\"`\"\n        PGMDEFINES=\n\n        for FLAG in ${PGMCFLAGS}\n        do      case \"${FLAG}\" in\n                -D?*)   DEFINE=\"`echo \\\"${FLAG}\\\" | sed 's/^..//'`\"\n                        PGMDEFINES=\"${PGMDEFINES} '${DEFINE}'\"\n                        ;;\n                esac\n        done\n\n        #        Compile all C sources for the program into modules.\n\n        PGMSOURCES=\"`eval echo \\\"\\\\${${PGM}_SOURCES}\\\"`\"\n        LINK=\n        MODULES=\n\n        for SOURCE in ${PGMSOURCES}\n        do      case \"${SOURCE}\" in\n                *.c)    #       Special processing for libxxx.c files: their\n                        #               module name is determined by the target\n                        #               PROGRAM name.\n\n                        case \"${SOURCE}\" in\n                        lib*.c) MODULE=\"${DB2PGM}\"\n                                ;;\n                        *)      MODULE=`db2_name \"${SOURCE}\"`\n                                ;;\n                        esac\n\n                        make_module \"${MODULE}\" \"${SOURCE}\" \"${PGMDEFINES}\"\n                        if action_needed \"${PGMIFSNAME}\" \"${MODIFSNAME}\"\n                        then    LINK=yes\n                        fi\n                        ;;\n                esac\n        done\n\n        #       Link program if needed.\n\n        if [ \"${LINK}\" ]\n        then    PGMLDADD=\"`eval echo \\\"\\\\${${PGM}_LDADD}\\\"`\"\n                for LDARG in ${PGMLDADD}\n                do      case \"${LDARG}\" in\n                        -*)     ;;              # Ignore non-module.\n                        *)      MODULES=\"${MODULES} \"`db2_name \"${LDARG}\"`\n                                ;;\n                        esac\n                done\n                MODULES=\"`echo \\\"${MODULES}\\\" |\n                    sed \\\"s/[^ ][^ ]*/${TARGETLIB}\\/&/g\\\"`\"\n                CMD=\"CRTPGM PGM(${TARGETLIB}/${DB2PGM})\"\n                CMD=\"${CMD} ENTMOD(QADRT/QADRTMAIN2)\"\n                CMD=\"${CMD} MODULE(${MODULES})\"\n                CMD=\"${CMD} BNDSRVPGM(${TARGETLIB}/${SRVPGM} QADRTTS)\"\n                CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n                system \"${CMD}\"\n        fi\ndone\n", "num_lines": 136}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       curl compilation script for the OS/400.\n#\n#\n#       This is a shell script since make is not a standard component of OS/400.\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB}) TEXT('curl: multiprotocol support API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(240)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/COPYING\" \"${SCRIPTDIR}/README.OS400\"             \\\n    \"${TOPDIR}/CHANGES\" \"${TOPDIR}/docs/THANKS\" \"${TOPDIR}/docs/FAQ\"    \\\n    \"${TOPDIR}/docs/FEATURES\" \"${TOPDIR}/docs/SSLCERTS.md\"              \\\n    \"${TOPDIR}/docs/RESOURCES\" \"${TOPDIR}/docs/VERSIONS.md\"             \\\n    \"${TOPDIR}/docs/HISTORY.md\"\ndo      MEMBER=\"`basename \\\"${TEXT}\\\" .OS400`\"\n        MEMBER=\"`basename \\\"${MEMBER}\\\" .md`\"\n        MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${MEMBER}\\\"`.MBR\"\n\n        if action_needed \"${MEMBER}\" \"${TEXT}\"\n        then    CMD=\"CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})\"\n                CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n\n\n#       Build in each directory.\n\n# for SUBDIR in include lib src tests\nfor SUBDIR in include lib src\ndo      \"${SCRIPTDIR}/make-${SUBDIR}.sh\"\ndone\n", "num_lines": 76}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# File: gnv_curl_configure.sh\n#\n# $Id$\n#\n# Set up and run the configure script for Curl so that it can find the\n# proper options for VMS.\n#\n# Copyright 2009 - 2020, John Malmberg\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n# 06-Jun-2009\tJ. Malmberg\n# 28-Dec-2012\tJ. Malmberg\tUpdate for Bash 4.2.39\n#==========================================================================\n#\n# POSIX exit mode is needed for Unix shells.\nexport GNV_CC_MAIN_POSIX_EXIT=1\n#\n# Where to look for the helper files.\nexport GNV_OPT_DIR=.\n#\n# How to find the SSL library files.\nexport LIB_OPENSSL=/SSL_LIB\n#\n# Override configure adding -std1 which is too strict for what curl\n# actually wants.\nexport GNV_CC_QUALIFIERS=/STANDARD=RELAXED\n#\n# Set the directory to where the Configure script actually is.\ncd ../..\n#\n#\n./configure  --prefix=/usr --exec-prefix=/usr --disable-dependency-tracking \\\n --disable-libtool-lock --with-gssapi --disable-ntlm-wb \\\n --with-ca-path=gnv\\$curl_ca_path\n#\n", "num_lines": 47}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# File: make_gnv_curl_install.sh\n#\n# $Id$\n#\n# Set up and run the make script for Curl.\n#\n# This makes the library, the curl binary and attempts an install.\n# A search list should be set up for GNU (GNV$GNU).\n#\n# Copyright 2009 - 2020, John Malmberg\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n# 06-Jun-2009\tJ. Malmberg\n#==========================================================================\n#\n#\n# Needed VMS build setups for GNV.\nexport GNV_OPT_DIR=.\nexport GNV_CC_QUALIFIERS=/DEBUG/OPTIMIZE/STANDARD=RELAXED\\\n/float=ieee_float/ieee_mode=denorm_results\nexport GNV_CXX_QUALIFIERS=/DEBUG/OPTIMIZE/float=ieee/ieee_mode=denorm_results\nexport GNV_CC_NO_INC_PRIMARY=1\n#\n#\n# POSIX exit mode is needed for Unix shells.\nexport GNV_CC_MAIN_POSIX_EXIT=1\nmake\ncd ../..\n# adjust the libcurl.pc file, GNV currently ignores the Lib: line.\n# but is noisy about it, so we just remove it.\nsed -e 's/^Libs:/#Libs:/g' libcurl.pc > libcurl.pc_new\nrm libcurl.pc\nmv libcurl.pc_new libcurl.pc\nmake install\n", "num_lines": 46}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n\n./buildconf\nmkdir -p cvr\ncd cvr\n../configure --disable-shared --enable-debug --enable-maintainer-mode --enable-code-coverage\nmake -sj\n# the regular test run\nmake TFLAGS=-n test-nonflaky\n# make all allocs/file operations fail\n#make TFLAGS=-n test-torture\n# do everything event-based\nmake TFLAGS=-n test-event\nlcov -d . -c -o cov.lcov\ngenhtml cov.lcov --output-directory coverage --title \"curl code coverage\"\ntar -cjf curl-coverage.tar.bz2 coverage\n", "num_lines": 38}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# (c) CopyRight 2000 - 2020, EdelWeb for EdelKey and OpenEvidence\n# Author: Peter Sylvester\n\n# \"libre\" for integration with curl\n\nOPENSSL=openssl\nif [ -f /usr/local/ssl/bin/openssl ] ; then\nOPENSSL=/usr/local/ssl/bin/openssl\nfi\n\nUSAGE=\"echo Usage is genroot.sh \\<name\\>\"\n\nHOME=`pwd`\ncd $HOME\n\nKEYSIZE=2048\nDURATION=6000\n# The -sha256 option was introduced in OpenSSL 1.0.1\nDIGESTALGO=-sha256\n\nPREFIX=$1\nif [ \".$PREFIX\" = . ] ; then\n   echo No configuration prefix\n   NOTOK=1\nelse\n   if [ ! -f $PREFIX-ca.prm ] ; then\n      echo No configuration file $PREFIX-ca.prm\n      NOTOK=1\n   fi\nfi\n\nif [ \".$NOTOK\" != . ] ; then\n   echo \"Sorry, I can't do that for you.\"\n   $USAGE\n   exit\nfi\n\nGETSERIAL=\"\\$t = time ;\\$d =  \\$t . substr(\\$t+$$ ,-4,4)-1;print \\$d\"\nSERIAL=`/usr/bin/env perl -e \"$GETSERIAL\"`\n\necho SERIAL=$SERIAL PREFIX=$PREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE\n\necho \"openssl genrsa -out $PREFIX-ca.key $KEYSIZE -passout XXX\"\nopenssl genrsa -out $PREFIX-ca.key $KEYSIZE -passout pass:secret\n\necho \"openssl req -config $PREFIX-ca.prm -new -key $PREFIX-ca.key -out $PREFIX-ca.csr\"\n$OPENSSL req -config $PREFIX-ca.prm -new -key $PREFIX-ca.key -out $PREFIX-ca.csr -passin pass:secret\n\necho \"openssl x509 -set_serial $SERIAL -extfile $PREFIX-ca.prm -days $DURATION -req -signkey $PREFIX-ca.key -in $PREFIX-ca.csr -out $PREFIX-$SERIAL.ca-cacert $DIGESTALGO \"\n\n$OPENSSL x509  -set_serial $SERIAL -extfile $PREFIX-ca.prm -days $DURATION -req -signkey $PREFIX-ca.key -in $PREFIX-ca.csr -out $PREFIX-$SERIAL-ca.cacert $DIGESTALGO\n\necho \"openssl x509 -text -in $PREFIX-$SERIAL-ca.cacert -nameopt multiline > $PREFIX-ca.cacert \"\n$OPENSSL x509 -text -in $PREFIX-$SERIAL-ca.cacert -nameopt multiline > $PREFIX-ca.cacert\n\necho \"openssl x509 -in $PREFIX-ca.cacert -outform der -out $PREFIX-ca.der \"\n$OPENSSL x509 -in $PREFIX-ca.cacert -outform der -out $PREFIX-ca.der\n\necho \"openssl x509 -in $PREFIX-ca.cacert -text -nameopt multiline > $PREFIX-ca.crt \"\n\n$OPENSSL x509 -in $PREFIX-ca.cacert -text -nameopt multiline > $PREFIX-ca.crt\n\necho \"openssl x509 -noout -text -in $PREFIX-ca.cacert -nameopt multiline\"\n$OPENSSL x509 -noout -text -in $PREFIX-ca.cacert -nameopt multiline\n\n#$OPENSSL rsa -in ../keys/$PREFIX-ca.key -text -noout -pubout\n", "num_lines": 69}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# (c) CopyRight 2000 - 2020, EdelWeb for EdelKey and OpenEvidence\n# Author: Peter Sylvester\n\n# \"libre\" for integration with curl\n\nOPENSSL=openssl\nif [ -f /usr/local/ssl/bin/openssl ] ; then\n   OPENSSL=/usr/local/ssl/bin/openssl\nfi\n\nUSAGE=\"echo Usage is genserv.sh <prefix> <caprefix>\"\n\nHOME=`pwd`\ncd $HOME\n\nKEYSIZE=2048\nDURATION=3000\n# The -sha256 option was introduced in OpenSSL 1.0.1\nDIGESTALGO=-sha256\n\nREQ=YES\nP12=NO\nDHP=NO\n\nPREFIX=$1\nif [ \".$PREFIX\" = . ] ; then\n   echo No configuration prefix\n   NOTOK=1\nelse\n   if [ ! -f $PREFIX-sv.prm ] ; then\n      echo No configuration file $PREFIX-sv.prm\n      NOTOK=1\n   fi\nfi\n\nCAPREFIX=$2\nif [ \".$CAPREFIX\" = . ] ; then\n   echo No CA prefix\n   NOTOK=1\nelse\n   if [ ! -f $CAPREFIX-ca.cacert ] ; then\n      echo No CA certificate file $CAPREFIX-ca.caert\n      NOTOK=1\n   fi\n   if [ ! -f $CAPREFIX-ca.key ] ; then\n      echo No $CAPREFIX key\n      NOTOK=1\n   fi\nfi\n\nif [ \".$NOTOK\" != . ] ; then\n   echo \"Sorry, I can't do that for you.\"\n   $USAGE\n   exit\nfi\n\nif [ \".$SERIAL\" = . ] ; then\n   GETSERIAL=\"\\$t = time ;\\$d =  \\$t . substr(\\$t+$$ ,-4,4)-1;print \\$d\"\n   SERIAL=`/usr/bin/env perl -e \"$GETSERIAL\"`\nfi\n\necho SERIAL=$SERIAL PREFIX=$PREFIX CAPREFIX=$CAPREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE\n\nif [ \"$DHP.\" = YES. ] ; then\n   echo \"openssl dhparam -2 -out $PREFIX-sv.dhp $KEYSIZE\"\n   $OPENSSL dhparam -2 -out $PREFIX-sv.dhp $KEYSIZE\nfi\n\nif [ \"$REQ.\" = YES. ] ; then\n   echo \"openssl req -config $PREFIX-sv.prm -newkey rsa:$KEYSIZE -keyout $PREFIX-sv.key -out $PREFIX-sv.csr -passout XXX\"\n   $OPENSSL req -config $PREFIX-sv.prm -newkey rsa:$KEYSIZE -keyout $PREFIX-sv.key -out $PREFIX-sv.csr -passout pass:secret\nfi\n\necho \"openssl rsa -in $PREFIX-sv.key -out $PREFIX-sv.key\"\n$OPENSSL rsa -in $PREFIX-sv.key -out $PREFIX-sv.key -passin pass:secret\necho pseudo secrets generated\n\necho \"openssl rsa -in $PREFIX-sv.key -pubout -outform DER -out $PREFIX-sv.pub.der\"\n$OPENSSL rsa -in $PREFIX-sv.key -pubout -outform DER -out $PREFIX-sv.pub.der\n\necho \"openssl rsa -in $PREFIX-sv.key -pubout -outform PEM -out $PREFIX-sv.pub.pem\"\n$OPENSSL rsa -in $PREFIX-sv.key -pubout -outform PEM -out $PREFIX-sv.pub.pem\n\necho \"openssl x509 -set_serial $SERIAL -extfile $PREFIX-sv.prm -days $DURATION  -CA $CAPREFIX-ca.cacert -CAkey $CAPREFIX-ca.key -in $PREFIX-sv.csr -req -text -nameopt multiline $DIGESTALGO > $PREFIX-sv.crt \"\n\n$OPENSSL x509 -set_serial $SERIAL -extfile $PREFIX-sv.prm -days $DURATION  -CA $CAPREFIX-ca.cacert -CAkey $CAPREFIX-ca.key -in $PREFIX-sv.csr -req -text -nameopt multiline $DIGESTALGO > $PREFIX-sv.crt\n\nif [ \"$P12.\" = YES. ] ; then\n\n   echo \"$OPENSSL pkcs12 -export -des3 -out $PREFIX-sv.p12 -caname $CAPREFIX -name $PREFIX -inkey $PREFIX-sv.key -in $PREFIX-sv.crt -certfile $CAPREFIX-ca.crt \"\n\n   $OPENSSL pkcs12 -export -des3 -out $PREFIX-sv.p12 -caname $CAPREFIX -name $PREFIX -inkey $PREFIX-sv.key -in $PREFIX-sv.crt -certfile $CAPREFIX-ca.crt\nfi\n\necho \"openssl x509 -noout -text -hash -in $PREFIX-sv.selfcert -nameopt multiline\"\n$OPENSSL x509 -noout -text -hash -in $PREFIX-sv.crt -nameopt multiline\n\n# revoke server cert\ntouch $CAPREFIX-ca.db\necho 01 > $CAPREFIX-ca.cnt\necho \"openssl ca -config $CAPREFIX-ca.cnf -revoke $PREFIX-sv.crt\"\n$OPENSSL ca -config $CAPREFIX-ca.cnf -revoke $PREFIX-sv.crt\n\n# issue CRL\necho \"openssl ca -config $CAPREFIX-ca.cnf -gencrl -out $PREFIX-sv.crl\"\n$OPENSSL ca -config $CAPREFIX-ca.cnf -gencrl -out $PREFIX-sv.crl\n\necho \"openssl x509 -in $PREFIX-sv.crt -outform der -out $PREFIX-sv.der \"\n$OPENSSL x509 -in $PREFIX-sv.crt -outform der -out $PREFIX-sv.der\n\n# all together now\ntouch $PREFIX-sv.dhp\ncat $PREFIX-sv.prm $PREFIX-sv.key  $PREFIX-sv.crt $PREFIX-sv.dhp >$PREFIX-sv.pem\nchmod o-r $PREFIX-sv.prm\n\necho \"$PREFIX-sv.pem done\"\n", "num_lines": 119}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2019-02-19.15\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2019, 2021-2022 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.7-3\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2019-02-19.15; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# This is free software.  There is NO warranty; not even for\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# Copyright (C) 2004-2019, 2021 Bootstrap Authors\n#\n# This file is dual licensed under the terms of the MIT license\n# <https://opensource.org/license/MIT>, and GPL version 2 or later\n# <http://www.gnu.org/licenses/gpl-2.0.html>.  You must apply one of\n# these licenses when using or redistributing this software or any of\n# the files within it.  See the URLs above, or the file `LICENSE`\n# included in the Bootstrap distribution for the full license texts.\n\n# Please report bugs or propose patches to:\n# <https://github.com/gnulib-modules/bootstrap/issues>\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n# These NLS vars are set unconditionally (bootstrap issue #24).  Unset those\n# in case the environment reset is needed later and the $save_* variant is not\n# defined (see the code above).\nLC_ALL=C\nLANGUAGE=C\nexport LANGUAGE LC_ALL\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n# func_unset VAR\n# --------------\n# Portably unset VAR.\n# In some shells, an 'unset VAR' statement leaves a non-zero return\n# status if VAR is already unset, which might be problematic if the\n# statement is used at the end of a function (thus poisoning its return\n# value) or when 'set -e' is active (causing even a spurious abort of\n# the script in this case).\nfunc_unset ()\n{\n    { eval $1=; (eval unset $1) >/dev/null 2>&1 && eval unset $1 || : ; }\n}\n\n\n# Make sure CDPATH doesn't cause `cd` commands to output the target dir.\nfunc_unset CDPATH\n\n# Make sure ${,E,F}GREP behave sanely.\nfunc_unset GREP_OPTIONS\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed \"$PATH:/usr/xpg4/bin\"\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep \"$PATH:/usr/xpg4/bin\"\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n# require_check_ifs_backslash\n# ---------------------------\n# Check if we can use backslash as IFS='\\' separator, and set\n# $check_ifs_backshlash_broken to ':' or 'false'.\nrequire_check_ifs_backslash=func_require_check_ifs_backslash\nfunc_require_check_ifs_backslash ()\n{\n  _G_save_IFS=$IFS\n  IFS='\\'\n  _G_check_ifs_backshlash='a\\\\b'\n  for _G_i in $_G_check_ifs_backshlash\n  do\n  case $_G_i in\n  a)\n    check_ifs_backshlash_broken=false\n    ;;\n  '')\n    break\n    ;;\n  *)\n    check_ifs_backshlash_broken=:\n    break\n    ;;\n  esac\n  done\n  IFS=$_G_save_IFS\n  require_check_ifs_backslash=:\n}\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_arg pretty \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_arg_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_arg pretty \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_arg_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_portable EVAL ARG\n# ----------------------------\n# Internal function to portably implement func_quote_arg.  Note that we still\n# keep attention to performance here so we as much as possible try to avoid\n# calling sed binary (so far O(N) complexity as long as func_append is O(1)).\nfunc_quote_portable ()\n{\n    $debug_cmd\n\n    $require_check_ifs_backslash\n\n    func_quote_portable_result=$2\n\n    # one-time-loop (easy break)\n    while true\n    do\n      if $1; then\n        func_quote_portable_result=`$ECHO \"$2\" | $SED \\\n          -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"`\n        break\n      fi\n\n      # Quote for eval.\n      case $func_quote_portable_result in\n        *[\\\\\\`\\\"\\$]*)\n          # Fallback to sed for $func_check_bs_ifs_broken=:, or when the string\n          # contains the shell wildcard characters.\n          case $check_ifs_backshlash_broken$func_quote_portable_result in\n            :*|*[\\[\\*\\?]*)\n              func_quote_portable_result=`$ECHO \"$func_quote_portable_result\" \\\n                  | $SED \"$sed_quote_subst\"`\n              break\n              ;;\n          esac\n\n          func_quote_portable_old_IFS=$IFS\n          for _G_char in '\\' '`' '\"' '$'\n          do\n            # STATE($1) PREV($2) SEPARATOR($3)\n            set start \"\" \"\"\n            func_quote_portable_result=dummy\"$_G_char$func_quote_portable_result$_G_char\"dummy\n            IFS=$_G_char\n            for _G_part in $func_quote_portable_result\n            do\n              case $1 in\n              quote)\n                func_append func_quote_portable_result \"$3$2\"\n                set quote \"$_G_part\" \"\\\\$_G_char\"\n                ;;\n              start)\n                set first \"\" \"\"\n                func_quote_portable_result=\n                ;;\n              first)\n                set quote \"$_G_part\" \"\"\n                ;;\n              esac\n            done\n          done\n          IFS=$func_quote_portable_old_IFS\n          ;;\n        *) ;;\n      esac\n      break\n    done\n\n    func_quote_portable_unquoted_result=$func_quote_portable_result\n    case $func_quote_portable_result in\n      # double-quote args containing shell metacharacters to delay\n      # word splitting, command substitution and variable expansion\n      # for a subsequent eval.\n      # many bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        func_quote_portable_result=\\\"$func_quote_portable_result\\\"\n        ;;\n    esac\n}\n\n\n# func_quotefast_eval ARG\n# -----------------------\n# Quote one ARG (internal).  This is equivalent to 'func_quote_arg eval ARG',\n# but optimized for speed.  Result is stored in $func_quotefast_eval.\nif test xyes = `(x=; printf -v x %q yes; echo x\"$x\") 2>/dev/null`; then\n  printf -v _GL_test_printf_tilde %q '~'\n  if test '\\~' = \"$_GL_test_printf_tilde\"; then\n    func_quotefast_eval ()\n    {\n      printf -v func_quotefast_eval_result %q \"$1\"\n    }\n  else\n    # Broken older Bash implementations.  Make those faster too if possible.\n    func_quotefast_eval ()\n    {\n      case $1 in\n        '~'*)\n          func_quote_portable false \"$1\"\n          func_quotefast_eval_result=$func_quote_portable_result\n          ;;\n        *)\n          printf -v func_quotefast_eval_result %q \"$1\"\n          ;;\n      esac\n    }\n  fi\nelse\n  func_quotefast_eval ()\n  {\n    func_quote_portable false \"$1\"\n    func_quotefast_eval_result=$func_quote_portable_result\n  }\nfi\n\n\n# func_quote_arg MODEs ARG\n# ------------------------\n# Quote one ARG to be evaled later.  MODEs argument may contain zero or more\n# specifiers listed below separated by ',' character.  This function returns two\n# values:\n#   i) func_quote_arg_result\n#      double-quoted (when needed), suitable for a subsequent eval\n#  ii) func_quote_arg_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.  Available only if 'unquoted' is specified.\n#\n# Available modes:\n# ----------------\n# 'eval' (default)\n#       - escape shell special characters\n# 'expand'\n#       - the same as 'eval';  but do not quote variable references\n# 'pretty'\n#       - request aesthetic output, i.e. '\"a b\"' instead of 'a\\ b'.  This might\n#         be used later in func_quote to get output like: 'echo \"a b\"' instead\n#         of 'echo a\\ b'.  This is slower than default on some shells.\n# 'unquoted'\n#       - produce also $func_quote_arg_unquoted_result which does not contain\n#         wrapping double-quotes.\n#\n# Examples for 'func_quote_arg pretty,unquoted string':\n#\n#   string      | *_result              | *_unquoted_result\n#   ------------+-----------------------+-------------------\n#   \"           | \\\"                    | \\\"\n#   a b         | \"a b\"                 | a b\n#   \"a b\"       | \"\\\"a b\\\"\"             | \\\"a b\\\"\n#   *           | \"*\"                   | *\n#   z=\"${x-$y}\" | \"z=\\\"\\${x-\\$y}\\\"\"     | z=\\\"\\${x-\\$y}\\\"\n#\n# Examples for 'func_quote_arg pretty,unquoted,expand string':\n#\n#   string        |   *_result          |  *_unquoted_result\n#   --------------+---------------------+--------------------\n#   z=\"${x-$y}\"   | \"z=\\\"${x-$y}\\\"\"     | z=\\\"${x-$y}\\\"\nfunc_quote_arg ()\n{\n    _G_quote_expand=false\n    case ,$1, in\n      *,expand,*)\n        _G_quote_expand=:\n        ;;\n    esac\n\n    case ,$1, in\n      *,pretty,*|*,expand,*|*,unquoted,*)\n        func_quote_portable $_G_quote_expand \"$2\"\n        func_quote_arg_result=$func_quote_portable_result\n        func_quote_arg_unquoted_result=$func_quote_portable_unquoted_result\n        ;;\n      *)\n        # Faster quote-for-eval for some shells.\n        func_quotefast_eval \"$2\"\n        func_quote_arg_result=$func_quotefast_eval_result\n        ;;\n    esac\n}\n\n\n# func_quote MODEs ARGs...\n# ------------------------\n# Quote all ARGs to be evaled later and join them into single command.  See\n# func_quote_arg's description for more info.\nfunc_quote ()\n{\n    $debug_cmd\n    _G_func_quote_mode=$1 ; shift\n    func_quote_result=\n    while test 0 -lt $#; do\n      func_quote_arg \"$_G_func_quote_mode\" \"$1\"\n      if test -n \"$func_quote_result\"; then\n        func_append func_quote_result \" $func_quote_arg_result\"\n      else\n        func_append func_quote_result \"$func_quote_arg_result\"\n      fi\n      shift\n    done\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_arg pretty,expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_arg_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_arg expand,pretty \"$_G_cmd\"\n      eval \"func_echo $func_quote_arg_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# This is free software.  There is NO warranty; not even for\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n#\n# Copyright (C) 2010-2019, 2021 Bootstrap Authors\n#\n# This file is dual licensed under the terms of the MIT license\n# <https://opensource.org/license/MIT>, and GPL version 2 or later\n# <http://www.gnu.org/licenses/gpl-2.0.html>.  You must apply one of\n# these licenses when using or redistributing this software or any of\n# the files within it.  See the URLs above, or the file `LICENSE`\n# included in the Bootstrap distribution for the full license texts.\n\n# Please report bugs or propose patches to:\n# <https://github.com/gnulib-modules/bootstrap/issues>\n\n# Set a version string for this script.\nscriptversion=2019-02-19.15; # UTC\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# Copyright'.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug in processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# in the main code.  A hook is just a list of function names that can be\n# run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of hook functions to be called by\n# FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_propagate_result FUNC_NAME_A FUNC_NAME_B\n# ---------------------------------------------\n# If the *_result variable of FUNC_NAME_A _is set_, assign its value to\n# *_result variable of FUNC_NAME_B.\nfunc_propagate_result ()\n{\n    $debug_cmd\n\n    func_propagate_result_result=:\n    if eval \"test \\\"\\${${1}_result+set}\\\" = set\"\n    then\n      eval \"${2}_result=\\$${1}_result\"\n    else\n      func_propagate_result_result=false\n    fi\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It's assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    _G_rc_run_hooks=false\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook functions.\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      func_unset \"${_G_hook}_result\"\n      eval $_G_hook '${1+\"$@\"}'\n      func_propagate_result $_G_hook func_run_hooks\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n      fi\n    done\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list from your hook function.  You may remove\n# or edit any options that you action, and then pass back the remaining\n# unprocessed options in '<hooked_function_name>_result', escaped\n# suitably for 'eval'.\n#\n# The '<hooked_function_name>_result' variable is automatically unset\n# before your hook gets called; for best performance, only set the\n# *_result variable when necessary (i.e. don't call the 'func_quote'\n# function unnecessarily because it can be an expensive operation on some\n# machines).\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  Leave\n#        # my_options_prep_result variable intact.\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that, for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\" in case we need it later,\n#                         # if $args_changed was set to 'true'.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        # Only call 'func_quote' here if we processed at least one argument.\n#        if $args_changed; then\n#          func_quote eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_result\n#        fi\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    func_run_hooks func_options ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_options_finish\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_options_quoted=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      func_unset func_${my_func}_result\n      func_unset func_run_hooks_result\n      eval func_$my_func '${1+\"$@\"}'\n      func_propagate_result func_$my_func func_options\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_options_result\"; shift\n        _G_options_quoted=:\n      fi\n    done\n\n    $_G_options_quoted || {\n      # As we (func_options) are top-level options-parser function and\n      # nobody quoted \"$@\" for us yet, we need to do it explicitly for\n      # caller.\n      func_quote eval ${1+\"$@\"}\n      func_options_result=$func_quote_result\n    }\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before returning.\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    func_run_hooks func_options_prep ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    _G_parse_options_requote=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      func_run_hooks func_parse_options ${1+\"$@\"}\n      func_propagate_result func_run_hooks func_parse_options\n      if $func_propagate_result_result; then\n        eval set dummy \"$func_parse_options_result\"; shift\n        # Even though we may have changed \"$@\", we passed the \"$@\" array\n        # down into the hook and it quoted it for us (because we are in\n        # this if-branch).  No need to quote it again.\n        _G_parse_options_requote=false\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      # We expect that one of the options parsed in this function matches\n      # and thus we remove _G_opt from \"$@\" and need to re-quote.\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\" >&2\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_parse_options_requote=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_parse_options_requote=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      if $_G_match_parse_options; then\n        _G_parse_options_requote=:\n      fi\n    done\n\n    if $_G_parse_options_requote; then\n      # save modified positional parameters for caller\n      func_quote eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_result\n    fi\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    func_run_hooks func_validate_options ${1+\"$@\"}\n    func_propagate_result func_run_hooks func_validate_options\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables\n# after splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      if test \"x$func_split_equals_lhs\" = \"x$1\"; then\n        func_split_equals_rhs=\n      fi\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs=\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x\\(-.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\n# The version message is extracted from the calling file's header\n# comments, with leading '# ' stripped:\n#   1. First display the progname and version\n#   2. Followed by the header comment line matching  /^# Written by /\n#   3. Then a blank line followed by the first following line matching\n#      /^# Copyright /\n#   4. Immediately followed by any lines between the previous matches,\n#      except lines preceding the intervening completely blank line.\n# For example, see the header comments of this file.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /^# Written by /!b\n        s|^# ||; p; n\n\n        :fwd2blnk\n        /./ {\n          n\n          b fwd2blnk\n        }\n        p; n\n\n        :holdwrnt\n        s|^# ||\n        s|^# *$||\n        /^Copyright /!{\n          /./H\n          n\n          b holdwrnt\n        }\n\n        s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n        G\n        s|\\(\\n\\)\\n*|\\1|g\n        p; q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"30/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.7-3\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func_fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_result\n    fi\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_result\n    fi\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_arg pretty \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_arg_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_arg pretty \"$srcfile\"\n    qsrcfile=$func_quote_arg_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG\n  -Xcompiler FLAG   pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wa,FLAG\n  -Xassembler FLAG  pass linker-specific FLAG directly to the assembler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_arg pretty \"$nonopt\"\n      install_prog=\"$func_quote_arg_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_arg pretty \"$arg\"\n    func_append install_prog \"$func_quote_arg_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_arg pretty \"$arg\"\n      func_append install_prog \" $func_quote_arg_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_arg pretty \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_arg_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_arg pretty \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_arg_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_arg expand,pretty \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_arg_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    func_quote_arg pretty \"$ECHO\"\n    qECHO=$func_quote_arg_result\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=$qECHO\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_arg pretty,unquoted \"$arg\"\n      qarg=$func_quote_arg_unquoted_result\n      func_append libtool_args \" $func_quote_arg_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txassembler)\n\t  func_append compiler_flags \" -Xassembler $qarg\"\n\t  prev=\n\t  func_append compile_command \" -Xassembler $qarg\"\n\t  func_append finalize_command \" -Xassembler $qarg\"\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig* | *-*-midnightbsd*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n     # Solaris ld rejects as of 11.4. Refer to Oracle bug 22985199.\n     -pthread)\n\tcase $host in\n\t  *solaris2*) ;;\n\t  *)\n\t    case \"$new_inherited_linker_flags \" in\n\t        *\" $arg \"*) ;;\n\t        * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\t    esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n      -mt|-mthreads|-kthread|-Kthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_arg pretty \"$flag\"\n\t  func_append arg \" $func_quote_arg_result\"\n\t  func_append compiler_flags \" $func_quote_arg_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_arg pretty \"$flag\"\n\t  func_append arg \" $wl$func_quote_arg_result\"\n\t  func_append compiler_flags \" $wl$func_quote_arg_result\"\n\t  func_append linker_flags \" $func_quote_arg_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xassembler)\n        prev=xassembler\n        continue\n        ;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -static-*            direct GCC to link specific libraries statically\n      # -fcilkplus           Cilk Plus language extension features for C/C++\n      # -Wa,*                Pass flags directly to the assembler\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus|-Wa,*)\n        func_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_arg pretty \"$arg\"\n\t  arg=$func_quote_arg_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_arg pretty \"$arg\"\n\targ=$func_quote_arg_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | $SED 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|midnightbsd-elf|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf | midnightbsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-midnightbsd*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_arg expand,pretty \"$cmd\"\n\t\t  eval \"func_echo $func_quote_arg_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_arg expand,pretty \"$cmd\"\n\t    eval \"func_echo $func_quote_arg_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_arg pretty \"$var_value\"\n\t    relink_command=\"$var=$func_quote_arg_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\tfunc_quote eval cd \"`pwd`\"\n\tfunc_quote_arg pretty,unquoted \"($func_quote_result; $relink_command)\"\n\trelink_command=$func_quote_arg_unquoted_result\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_arg pretty,unquoted \"$var_value\"\n\t  relink_command=\"$var=$func_quote_arg_unquoted_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      func_quote eval cd \"`pwd`\"\n      relink_command=\"($func_quote_result; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      func_quote_arg pretty,unquoted \"$relink_command\"\n      relink_command=$func_quote_arg_unquoted_result\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11449}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n\nsystem ()\n{\n    /usr/bin/system \"$@\" || exit 1\n}\n\nsetenv()\n\n{\n        #       Define and export.\n\n        eval ${1}=\"${2}\"\n        export ${1}\n}\n\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in $TOPDIR/packages/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nTOPDIR=`dirname \"${TOPDIR}\"`\nexport SCRIPTDIR TOPDIR\n\n#  Extract the SONAME from the library makefile.\n\nSONAME=`sed -e '/^VERSIONINFO=/!d' -e 's/^.* \\([0-9]*\\):.*$/\\1/' -e 'q' \\\n                                                < \"${TOPDIR}/lib/Makefile.am\"`\nexport SONAME\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nsetenv TARGETLIB        'CURL'                  # Target OS/400 program library.\nsetenv STATBNDDIR       'CURL_A'                # Static binding directory.\nsetenv DYNBNDDIR        'CURL'                  # Dynamic binding directory.\nsetenv SRVPGM           \"CURL.${SONAME}\"        # Service program.\nsetenv TGTCCSID         '500'                   # Target CCSID of objects.\nsetenv DEBUG            '*ALL'                  # Debug level.\nsetenv OPTIMIZE         '10'                    # Optimization level\nsetenv OUTPUT           '*NONE'                 # Compilation output option.\nsetenv TGTRLS           '*CURRENT'              # Target OS release.\nsetenv IFSDIR           '/curl'                 # Installation IFS directory.\n\n#       Define ZLIB availability and locations.\n\nsetenv WITH_ZLIB        0                       # Define to 1 to enable.\nsetenv ZLIB_INCLUDE     '/zlib/include'         # ZLIB include IFS directory.\nsetenv ZLIB_LIB         'ZLIB'                  # ZLIB library.\nsetenv ZLIB_BNDDIR      'ZLIB_A'                # ZLIB binding directory.\n\n#       Define LIBSSH2 availability and locations.\n\nsetenv WITH_LIBSSH2     0                       # Define to 1 to enable.\nsetenv LIBSSH2_INCLUDE  '/libssh2/include'      # LIBSSH2 include IFS directory.\nsetenv LIBSSH2_LIB      'LIBSSH2'               # LIBSSH2 library.\nsetenv LIBSSH2_BNDDIR   'LIBSSH2_A'             # LIBSSH2 binding directory.\n\n\n################################################################################\n\n#       Need to get the version definitions.\n\nLIBCURL_VERSION=`grep '^#define  *LIBCURL_VERSION '                     \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/.*\"\\(.*\\)\".*/\\1/'`\nLIBCURL_VERSION_MAJOR=`grep '^#define  *LIBCURL_VERSION_MAJOR '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_MAJOR  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_MINOR=`grep '^#define  *LIBCURL_VERSION_MINOR '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_MINOR  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_PATCH=`grep '^#define  *LIBCURL_VERSION_PATCH '         \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_PATCH  *\\([^ ]*\\).*/\\1/'`\nLIBCURL_VERSION_NUM=`grep '^#define  *LIBCURL_VERSION_NUM '             \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/^#define  *LIBCURL_VERSION_NUM  *0x\\([^ ]*\\).*/\\1/'`\nLIBCURL_TIMESTAMP=`grep '^#define  *LIBCURL_TIMESTAMP '                 \\\n                        \"${TOPDIR}/include/curl/curlver.h\"              |\n                sed 's/.*\"\\(.*\\)\".*/\\1/'`\nexport LIBCURL_VERSION\nexport LIBCURL_VERSION_MAJOR LIBCURL_VERSION_MINOR LIBCURL_VERSION_PATCH\nexport LIBCURL_VERSION_NUM LIBCURL_TIMESTAMP\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nLIBIFSNAME=\"/QSYS.LIB/${TARGETLIB}.LIB\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       canonicalize_path path\n#\n#       Return canonicalized path as:\n#       - Absolute\n#       - No . or .. component.\n\ncanonicalize_path()\n\n{\n        if expr \"${1}\" : '^/' > /dev/null\n        then    P=\"${1}\"\n        else    P=\"`pwd`/${1}\"\n        fi\n\n        R=\n        IFSSAVE=\"${IFS}\"\n        IFS=\"/\"\n\n        for C in ${P}\n        do      IFS=\"${IFSSAVE}\"\n                case \"${C}\" in\n                .)      ;;\n                ..)     R=`expr \"${R}\" : '^\\(.*/\\)..*'`\n                        ;;\n                ?*)     R=\"${R}${C}/\"\n                        ;;\n                *)      ;;\n                esac\n        done\n\n        IFS=\"${IFSSAVE}\"\n        echo \"/`expr \"${R}\" : '^\\(.*\\)/'`\"\n}\n\n\n#       make_module module_name source_name [additional_definitions]\n#\n#       Compile source name into ASCII module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n\nmake_module()\n\n{\n        MODULES=\"${MODULES} ${1}\"\n        MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n        action_needed \"${MODIFSNAME}\" \"${2}\" || return 0;\n        SRCDIR=`dirname \\`canonicalize_path \"${2}\"\\``\n\n        #       #pragma convert has to be in the source file itself, i.e.\n        #               putting it in an include file makes it only active\n        #               for that include file.\n        #       Thus we build a temporary file with the pragma prepended to\n        #               the source file and we compile that themporary file.\n\n        echo \"#line 1 \\\"${2}\\\"\" > __tmpsrcf.c\n        echo \"#pragma convert(819)\" >> __tmpsrcf.c\n        echo \"#line 1\" >> __tmpsrcf.c\n        cat \"${2}\" >> __tmpsrcf.c\n        CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('__tmpsrcf.c')\"\n#       CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST *SHOWINC *SHOWSYS)\"\n        CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST)\"\n        CMD=\"${CMD} LOCALETYPE(*LOCALE) FLAG(10)\"\n        CMD=\"${CMD} INCDIR('/qibm/proddata/qadrt/include'\"\n        CMD=\"${CMD} '${TOPDIR}/include/curl' '${TOPDIR}/include' '${SRCDIR}'\"\n        CMD=\"${CMD} '${TOPDIR}/packages/OS400'\"\n\n        if [ \"${WITH_ZLIB}\" != \"0\" ]\n        then    CMD=\"${CMD} '${ZLIB_INCLUDE}'\"\n        fi\n\n        if [ \"${WITH_LIBSSH2}\" != \"0\" ]\n        then    CMD=\"${CMD} '${LIBSSH2_INCLUDE}'\"\n        fi\n\n        CMD=\"${CMD} ${INCLUDES})\"\n        CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n        CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n        CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n        CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n\n        DEFINES=\"${3} BUILDING_LIBCURL\"\n\n        if [ \"${WITH_ZLIB}\" != \"0\" ]\n        then    DEFINES=\"${DEFINES} HAVE_LIBZ HAVE_ZLIB_H\"\n        fi\n\n        if [ \"${WITH_LIBSSH2}\" != \"0\" ]\n        then    DEFINES=\"${DEFINES} USE_LIBSSH2 HAVE_LIBSSH2_H\"\n        fi\n\n        if [ \"${DEFINES}\" ]\n        then    CMD=\"${CMD} DEFINE(${DEFINES})\"\n        fi\n\n        system \"${CMD}\"\n        rm -f __tmpsrcf.c\n        LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        if [ \"${2}\" = 'nomangle' ]\n        then    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        else    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^CURL_*/C/'                                   \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        fi\n}\n\n\n#       Copy IFS file replacing version info.\n\nversioned_copy()\n\n{\n        sed -e \"s/@LIBCURL_VERSION@/${LIBCURL_VERSION}/g\"               \\\n            -e \"s/@LIBCURL_VERSION_MAJOR@/${LIBCURL_VERSION_MAJOR}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_MINOR@/${LIBCURL_VERSION_MINOR}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_PATCH@/${LIBCURL_VERSION_PATCH}/g\"   \\\n            -e \"s/@LIBCURL_VERSION_NUM@/${LIBCURL_VERSION_NUM}/g\"       \\\n            -e \"s/@LIBCURL_TIMESTAMP@/${LIBCURL_TIMESTAMP}/g\"           \\\n                < \"${1}\" > \"${2}\"\n}\n", "num_lines": 287}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       Installation of the header files in the OS/400 library.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/include\"\n\n\n#       Create the OS/400 source program file for the header files.\n\nSRCPF=\"${LIBIFSNAME}/H.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('curl: Header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the header files.\n\nIFSINCLUDE=\"${IFSDIR}/include/curl\"\n\nif action_needed \"${IFSINCLUDE}\"\nthen    mkdir -p \"${IFSINCLUDE}\"\nfi\n\n\n#       Enumeration values are used as va_arg tagfields, so they MUST be\n#               integers.\n\ncopy_hfile()\n\n{\n        destfile=\"${1}\"\n        srcfile=\"${2}\"\n        shift\n        shift\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n' < \"${srcfile}\" > \"${destfile}\"\n}\n\n#       Copy the header files.\n\nfor HFILE in curl/*.h ${SCRIPTDIR}/ccsidcurl.h\ndo      case \"`basename \\\"${HFILE}\\\" .h`\" in\n        stdcheaders|typecheck-gcc)\n                continue;;\n        esac\n\n        DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\" nomangle`.MBR\"\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    copy_hfile \"${DEST}\" \"${HFILE}\"\n                IFSDEST=\"${IFSINCLUDE}/`basename \\\"${HFILE}\\\"`\"\n                rm -f \"${IFSDEST}\"\n                ln -s \"${DEST}\" \"${IFSDEST}\"\n        fi\ndone\n\n\n#       Copy the ILE/RPG header file, setting-up version number.\n\nversioned_copy \"${SCRIPTDIR}/curl.inc.in\" \"${SRCPF}/CURL.INC.MBR\"\nrm -f \"${IFSINCLUDE}/curl.inc.rpgle\"\nln -s \"${SRCPF}/CURL.INC.MBR\" \"${IFSINCLUDE}/curl.inc.rpgle\"\n\n\n#       Duplicate file H as CURL to support more include path forms.\n\nif action_needed \"${LIBIFSNAME}/CURL.FILE\"\nthen    :\nelse    system \"DLTF FILE(${TARGETLIB}/CURL)\"\nfi\n\nCMD=\"CRTDUPOBJ OBJ(H) FROMLIB(${TARGETLIB}) OBJTYPE(*FILE) TOLIB(*FROMLIB)\"\nCMD=\"${CMD} NEWOBJ(CURL) DATA(*YES)\"\nsystem \"${CMD}\"\n", "num_lines": 105}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       libcurl compilation script for the OS/400.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/lib\"\n\n#       Need to have IFS access to the mih/cipher header file.\n\nif action_needed cipher.mih '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR'\nthen    rm -f cipher.mih\n        ln -s '/QSYS.LIB/QSYSINC.LIB/MIH.FILE/CIPHER.MBR' cipher.mih\nfi\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"libcurl version '\"${LIBCURL_VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1998-2016 Daniel Stenberg et al. OS/400 version by P. Monnerat\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nsed -e ':begin'                                                         \\\n    -e '/\\\\$/{'                                                         \\\n    -e 's/\\\\$/ /'                                                       \\\n    -e 'N'                                                              \\\n    -e 'bbegin'                                                         \\\n    -e '}'                                                              \\\n    -e 's/\\n//g'                                                        \\\n    -e 's/[[:space:]]*$//'                                              \\\n    -e 's/^\\([A-Za-z][A-Za-z0-9_]*\\)[[:space:]]*=[[:space:]]*\\(.*\\)/\\1=\"\\2\"/' \\\n    -e 's/\\$(\\([A-Za-z][A-Za-z0-9_]*\\))/${\\1}/g'                        \\\n        < Makefile.inc > tmpscript.sh\n. ./tmpscript.sh\n\n\n#       Compile the sources into modules.\n\nINCLUDES=\"'`pwd`'\"\n\n# Create a small C program to check ccsidcurl.c is up to date\nif action_needed \"${LIBIFSNAME}/CHKSTRINGS.PGM\"\nthen\n  CMD=\"CRTBNDC PGM(${TARGETLIB}/CHKSTRINGS) SRCSTMF('${SCRIPTDIR}/chkstrings.c')\"\n  CMD=\"${CMD} INCDIR('${TOPDIR}/include/curl' '${TOPDIR}/include' '${SRCDIR}' ${INCLUDES})\"\n  system -i \"${CMD}\"\n  if [ $? -ne 0 ]\n  then\n    echo \"ERROR: Failed to build CHKSTRINGS *PGM object!\"\n    exit 2\n  else\n    ${LIBIFSNAME}/CHKSTRINGS.PGM\n    if [ $? -ne 0 ]\n    then\n      echo \"ERROR: CHKSTRINGS failed!\"\n      exit 2\n    fi\n  fi\nfi\n\nmake_module     OS400SYS        \"${SCRIPTDIR}/os400sys.c\"\nmake_module     CCSIDCURL       \"${SCRIPTDIR}/ccsidcurl.c\"\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('LibCurl API static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} TEXT('curl: build tools')\"\n        system \"${CMD}\"\nfi\n\n\n#       Gather the list of symbols to export.\n\nEXPORTS=`grep '^CURL_EXTERN[[:space:]]'                                 \\\n              \"${TOPDIR}\"/include/curl/*.h                              \\\n              \"${SCRIPTDIR}/ccsidcurl.h\"                                |\n         sed -e 's/^.*CURL_EXTERN[[:space:]]\\(.*\\)(.*$/\\1/'             \\\n             -e 's/[[:space:]]*$//'                                     \\\n             -e 's/^.*[[:space:]][[:space:]]*//'                        \\\n             -e 's/^\\*//'                                               \\\n             -e 's/(\\(.*\\))/\\1/'`\n\n#       Create the service program exportation file in DB2 member if needed.\n\nBSF=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\n\nif action_needed \"${BSF}\" Makefile.am\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    echo \" STRPGMEXP PGMLVL(*CURRENT) SIGNATURE('LIBCURL_${SONAME}')\" \\\n            > \"${BSF}\"\n        for EXPORT in ${EXPORTS}\n        do      echo ' EXPORT    SYMBOL(\"'\"${EXPORT}\"'\")' >> \"${BSF}\"\n        done\n\n        echo ' ENDPGMEXP' >> \"${BSF}\"\nfi\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR}\"\n        if [ \"${WITH_ZLIB}\" != 0 ]\n        then    CMD=\"${CMD} ${ZLIB_LIB}/${ZLIB_BNDDIR}\"\n                liblist -a \"${ZLIB_LIB}\"\n        fi\n        if [ \"${WITH_LIBSSH2}\" != 0 ]\n        then    CMD=\"${CMD} ${LIBSSH2_LIB}/${LIBSSH2_BNDDIR}\"\n                liblist -a \"${LIBSSH2_LIB}\"\n        fi\n        CMD=\"${CMD})\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS QGLDCLNT QGLDBRDR)\"\n        CMD=\"${CMD} TEXT('curl API library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('LibCurl API dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n\n\n#       Rebuild the formdata test if needed.\n\nif [ \"${TEST_FORMDATA}\" ]\nthen    MODULES=\n        make_module TFORMDATA   formdata.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TSTREQUAL   strequal.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TMEMDEBUG   memdebug.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TMPRINTF    mprintf.c       \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        make_module TSTRERROR   strerror.c      \"'_FORM_DEBUG' 'CURLDEBUG'\"\n        #       The following modules should not be needed (see comment in\n        #               formdata.c. However, there are some unsatisfied\n        #               external references leading in the following\n        #               modules to be (recursively) needed.\n        MODULES=\"${MODULES} EASY STRDUP SSLGEN GSKIT HOSTIP HOSTIP4 HOSTIP6\"\n        MODULES=\"${MODULES} URL HASH TRANSFER GETINFO COOKIE SENDF SELECT\"\n        MODULES=\"${MODULES} INET_NTOP SHARE HOSTTHRE MULTI LLIST FTP HTTP\"\n        MODULES=\"${MODULES} HTTP_DIGES HTTP_CHUNK HTTP_NEGOT TIMEVAL HOSTSYN\"\n        MODULES=\"${MODULES} CONNECT SOCKS PROGRESS ESCAPE INET_PTON GETENV\"\n        MODULES=\"${MODULES} DICT LDAP TELNET FILE TFTP NETRC PARSEDATE\"\n        MODULES=\"${MODULES} SPEEDCHECK SPLAY BASE64 SECURITY IF2IP MD5\"\n        MODULES=\"${MODULES} KRB5 OS400SYS\"\n\n        PGMIFSNAME=\"${LIBIFSNAME}/TFORMDATA.PGM\"\n\n        if action_needed \"${PGMIFSNAME}\"\n        then    LINK=YES\n        fi\n\n        if [ \"${LINK}\" ]\n        then    CMD=\"CRTPGM PGM(${TARGETLIB}/TFORMDATA)\"\n                CMD=\"${CMD} ENTMOD(QADRT/QADRTMAIN2)\"\n                CMD=\"${CMD} MODULE(\"\n\n                for MODULE in ${MODULES}\n                do      CMD=\"${CMD} ${TARGETLIB}/${MODULE}\"\n                done\n\n                CMD=\"${CMD} ) BNDSRVPGM(QADRTTS)\"\n                CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n                system \"${CMD}\"\n        fi\nfi\n", "num_lines": 246}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#\n#       Not implemented yet on OS/400.\n", "num_lines": 26}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       tests compilation script for the OS/400.\n#\n\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/tests\"\n\n\n#       tests directory not implemented yet.\n\n\n#       Process the libtest subdirectory.\n\ncd libtest\n\n#       Get definitions from the Makefile.inc file.\n#       The `sed' statement works as follows:\n#       _ Join \\nl-separated lines.\n#       _ Retain only lines that begins with \"identifier =\".\n#       _ Turn these lines into shell variable assignments.\n\neval \"`sed -e ': begin'                                                 \\\n        -e '/\\\\\\\\$/{'                                                   \\\n        -e 'N'                                                          \\\n        -e 's/\\\\\\\\\\\\n/ /'                                               \\\n        -e 'b begin'                                                    \\\n        -e '}'                                                          \\\n        -e '/^[A-Za-z_][A-Za-z0-9_]*[[:space:]]*[=]/b keep'             \\\n        -e 'd'                                                          \\\n        -e ': keep'                                                     \\\n        -e 's/[[:space:]]*=[[:space:]]*/=/'                             \\\n        -e 's/=\\\\(.*[^[:space:]]\\\\)[[:space:]]*$/=\\\\\"\\\\1\\\\\"/'           \\\n        -e 's/\\\\$(\\\\([^)]*\\\\))/${\\\\1}/g'                                \\\n        < Makefile.inc`\"\n\n#       Special case: redefine chkhostname compilation parameters.\n\nchkhostname_SOURCES=chkhostname.c\nchkhostname_LDADD=curl_gethostname.o\n\n#       Compile all programs.\n#       The list is found in variable \"noinst_PROGRAMS\"\n\nINCLUDES=\"'${TOPDIR}/tests/libtest' '${TOPDIR}/lib'\"\n\nfor PGM in ${noinst_PROGRAMS}\ndo      DB2PGM=`db2_name \"${PGM}\"`\n        PGMIFSNAME=\"${LIBIFSNAME}/${DB2PGM}.PGM\"\n\n        #       Extract preprocessor symbol definitions from compilation\n        #               options for the program.\n\n        PGMCFLAGS=\"`eval echo \\\"\\\\${${PGM}_CFLAGS}\\\"`\"\n        PGMDEFINES=\n\n        for FLAG in ${PGMCFLAGS}\n        do      case \"${FLAG}\" in\n                -D?*)   DEFINE=\"`echo \\\"${FLAG}\\\" | sed 's/^..//'`\"\n                        PGMDEFINES=\"${PGMDEFINES} '${DEFINE}'\"\n                        ;;\n                esac\n        done\n\n        #        Compile all C sources for the program into modules.\n\n        PGMSOURCES=\"`eval echo \\\"\\\\${${PGM}_SOURCES}\\\"`\"\n        LINK=\n        MODULES=\n\n        for SOURCE in ${PGMSOURCES}\n        do      case \"${SOURCE}\" in\n                *.c)    #       Special processing for libxxx.c files: their\n                        #               module name is determined by the target\n                        #               PROGRAM name.\n\n                        case \"${SOURCE}\" in\n                        lib*.c) MODULE=\"${DB2PGM}\"\n                                ;;\n                        *)      MODULE=`db2_name \"${SOURCE}\"`\n                                ;;\n                        esac\n\n                        make_module \"${MODULE}\" \"${SOURCE}\" \"${PGMDEFINES}\"\n                        if action_needed \"${PGMIFSNAME}\" \"${MODIFSNAME}\"\n                        then    LINK=yes\n                        fi\n                        ;;\n                esac\n        done\n\n        #       Link program if needed.\n\n        if [ \"${LINK}\" ]\n        then    PGMLDADD=\"`eval echo \\\"\\\\${${PGM}_LDADD}\\\"`\"\n                for LDARG in ${PGMLDADD}\n                do      case \"${LDARG}\" in\n                        -*)     ;;              # Ignore non-module.\n                        *)      MODULES=\"${MODULES} \"`db2_name \"${LDARG}\"`\n                                ;;\n                        esac\n                done\n                MODULES=\"`echo \\\"${MODULES}\\\" |\n                    sed \\\"s/[^ ][^ ]*/${TARGETLIB}\\/&/g\\\"`\"\n                CMD=\"CRTPGM PGM(${TARGETLIB}/${DB2PGM})\"\n                CMD=\"${CMD} ENTMOD(QADRT/QADRTMAIN2)\"\n                CMD=\"${CMD} MODULE(${MODULES})\"\n                CMD=\"${CMD} BNDSRVPGM(${TARGETLIB}/${SRVPGM} QADRTTS)\"\n                CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n                system \"${CMD}\"\n        fi\ndone\n", "num_lines": 136}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n#\n#       curl compilation script for the OS/400.\n#\n#\n#       This is a shell script since make is not a standard component of OS/400.\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB}) TEXT('curl: multiprotocol support API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(240)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/COPYING\" \"${SCRIPTDIR}/README.OS400\"             \\\n    \"${TOPDIR}/CHANGES\" \"${TOPDIR}/docs/THANKS\" \"${TOPDIR}/docs/FAQ\"    \\\n    \"${TOPDIR}/docs/FEATURES\" \"${TOPDIR}/docs/SSLCERTS.md\"              \\\n    \"${TOPDIR}/docs/RESOURCES\" \"${TOPDIR}/docs/VERSIONS.md\"             \\\n    \"${TOPDIR}/docs/HISTORY.md\"\ndo      MEMBER=\"`basename \\\"${TEXT}\\\" .OS400`\"\n        MEMBER=\"`basename \\\"${MEMBER}\\\" .md`\"\n        MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${MEMBER}\\\"`.MBR\"\n\n        [ -e \"${TEXT}\" ] || continue\n\n        if action_needed \"${MEMBER}\" \"${TEXT}\"\n        then    CMD=\"CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})\"\n                CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n\n\n#       Build in each directory.\n\n# for SUBDIR in include lib src tests\nfor SUBDIR in include lib src\ndo      \"${SCRIPTDIR}/make-${SUBDIR}.sh\"\ndone\n", "num_lines": 78}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# File: gnv_curl_configure.sh\n#\n# $Id$\n#\n# Set up and run the configure script for Curl so that it can find the\n# proper options for VMS.\n#\n# Copyright 2009 - 2020, John Malmberg\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n# 06-Jun-2009\tJ. Malmberg\n# 28-Dec-2012\tJ. Malmberg\tUpdate for Bash 4.2.39\n#==========================================================================\n#\n# POSIX exit mode is needed for Unix shells.\nexport GNV_CC_MAIN_POSIX_EXIT=1\n#\n# Where to look for the helper files.\nexport GNV_OPT_DIR=.\n#\n# How to find the SSL library files.\nexport LIB_OPENSSL=/SSL_LIB\n#\n# Override configure adding -std1 which is too strict for what curl\n# actually wants.\nexport GNV_CC_QUALIFIERS=/STANDARD=RELAXED\n#\n# Set the directory to where the Configure script actually is.\ncd ../..\n#\n#\n./configure  --prefix=/usr --exec-prefix=/usr --disable-dependency-tracking \\\n --disable-libtool-lock --with-gssapi --disable-ntlm-wb \\\n --with-ca-path=gnv\\$curl_ca_path\n#\n", "num_lines": 47}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# File: make_gnv_curl_install.sh\n#\n# $Id$\n#\n# Set up and run the make script for Curl.\n#\n# This makes the library, the curl binary and attempts an install.\n# A search list should be set up for GNU (GNV$GNU).\n#\n# Copyright 2009 - 2020, John Malmberg\n#\n# Permission to use, copy, modify, and/or distribute this software for any\n# purpose with or without fee is hereby granted, provided that the above\n# copyright notice and this permission notice appear in all copies.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\n# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n#\n# 06-Jun-2009\tJ. Malmberg\n#==========================================================================\n#\n#\n# Needed VMS build setups for GNV.\nexport GNV_OPT_DIR=.\nexport GNV_CC_QUALIFIERS=/DEBUG/OPTIMIZE/STANDARD=RELAXED\\\n/float=ieee_float/ieee_mode=denorm_results\nexport GNV_CXX_QUALIFIERS=/DEBUG/OPTIMIZE/float=ieee/ieee_mode=denorm_results\nexport GNV_CC_NO_INC_PRIMARY=1\n#\n#\n# POSIX exit mode is needed for Unix shells.\nexport GNV_CC_MAIN_POSIX_EXIT=1\nmake\ncd ../..\n# adjust the libcurl.pc file, GNV currently ignores the Lib: line.\n# but is noisy about it, so we just remove it.\nsed -e 's/^Libs:/#Libs:/g' libcurl.pc > libcurl.pc_new\nrm libcurl.pc\nmv libcurl.pc_new libcurl.pc\nmake install\n", "num_lines": 46}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#***************************************************************************\n#                                  _   _ ____  _\n#  Project                     ___| | | |  _ \\| |\n#                             / __| | | | |_) | |\n#                            | (__| |_| |  _ <| |___\n#                             \\___|\\___/|_| \\_\\_____|\n#\n# Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.\n#\n# This software is licensed as described in the file COPYING, which\n# you should have received as part of this distribution. The terms\n# are also available at https://curl.se/docs/copyright.html.\n#\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# copies of the Software, and permit persons to whom the Software is\n# furnished to do so, under the terms of the COPYING file.\n#\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# KIND, either express or implied.\n#\n###########################################################################\n\nautoreconf -fi\nmkdir -p cvr\ncd cvr\n../configure --disable-shared --enable-debug --enable-maintainer-mode --enable-code-coverage\nmake -sj\n# the regular test run\nmake TFLAGS=-n test-nonflaky\n# make all allocs/file operations fail\n#make TFLAGS=-n test-torture\n# do everything event-based\nmake TFLAGS=-n test-event\nlcov -d . -c -o cov.lcov\ngenhtml cov.lcov --output-directory coverage --title \"curl code coverage\"\ntar -cjf curl-coverage.tar.bz2 coverage\n", "num_lines": 38}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# ***************************************************************************\n# *                                  _   _ ____  _\n# *  Project                     ___| | | |  _ \\| |\n# *                             / __| | | | |_) | |\n# *                            | (__| |_| |  _ <| |___\n# *                             \\___|\\___/|_| \\_\\_____|\n# *\n# * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al.\n# *\n# * This software is licensed as described in the file COPYING, which\n# * you should have received as part of this distribution. The terms\n# * are also available at https://curl.se/docs/copyright.html.\n# *\n# * You may opt to use, copy, modify, merge, publish, distribute and/or sell\n# * copies of the Software, and permit persons to whom the Software is\n# * furnished to do so, under the terms of the COPYING file.\n# *\n# * This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY\n# * KIND, either express or implied.\n# *\n# ***************************************************************************\n# This shell script creates a fresh ca-bundle.crt file for use with libcurl.\n# It extracts all ca certs it finds in the local Firefox database and converts\n# them all into PEM format.\n#\ndb=$(ls -1d $HOME/.mozilla/firefox/*default*)\nout=$1\n\nif test -z \"$out\"; then\n  out=\"ca-bundle.crt\" # use a sensible default\nfi\n\ncurrentdate=$(date)\n\ncat >$out <<EOF\n##\n## Bundle of CA Root Certificates\n##\n## Converted at: ${currentdate}\n## These were converted from the local Firefox directory by the db2pem script.\n##\nEOF\n\n\ncertutil -L -h 'Builtin Object Token' -d \"$db\" | \\\ngrep ' *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$' | \\\nsed -e 's/ *[CcGTPpu]*,[CcGTPpu]*,[CcGTPpu]* *$//' -e 's/\\(.*\\)/\"\\1\"/' | \\\nsort | \\\nwhile read -r nickname; \\\n do echo \"$nickname\" | sed -e \"s/Builtin Object Token://g\"; \\\neval certutil -d \"$db\" -L -n \"$nickname\" -a ; \\\ndone >> $out\n", "num_lines": 54}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# (c) CopyRight 2000 - 2020, EdelWeb for EdelKey and OpenEvidence\n# Author: Peter Sylvester\n\n# \"libre\" for integration with curl\n\nOPENSSL=openssl\nif [ -f /usr/local/ssl/bin/openssl ] ; then\nOPENSSL=/usr/local/ssl/bin/openssl\nfi\n\nUSAGE=\"echo Usage is genroot.sh \\<name\\>\"\n\nHOME=`pwd`\ncd $HOME\n\nKEYSIZE=2048\nDURATION=6000\n# The -sha256 option was introduced in OpenSSL 1.0.1\nDIGESTALGO=-sha256\n\nPREFIX=$1\nif [ \".$PREFIX\" = . ] ; then\n   echo No configuration prefix\n   NOTOK=1\nelse\n   if [ ! -f $PREFIX-ca.prm ] ; then\n      echo No configuration file $PREFIX-ca.prm\n      NOTOK=1\n   fi\nfi\n\nif [ \".$NOTOK\" != . ] ; then\n   echo \"Sorry, I can't do that for you.\"\n   $USAGE\n   exit\nfi\n\nGETSERIAL=\"\\$t = time ;\\$d =  \\$t . substr(\\$t+$$ ,-4,4)-1;print \\$d\"\nSERIAL=`/usr/bin/env perl -e \"$GETSERIAL\"`\n\necho SERIAL=$SERIAL PREFIX=$PREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE\n\necho \"openssl genrsa -out $PREFIX-ca.key $KEYSIZE -passout XXX\"\nopenssl genrsa -out $PREFIX-ca.key $KEYSIZE -passout pass:secret\n\necho \"openssl req -config $PREFIX-ca.prm -new -key $PREFIX-ca.key -out $PREFIX-ca.csr\"\n$OPENSSL req -config $PREFIX-ca.prm -new -key $PREFIX-ca.key -out $PREFIX-ca.csr -passin pass:secret\n\necho \"openssl x509 -set_serial $SERIAL -extfile $PREFIX-ca.prm -days $DURATION -req -signkey $PREFIX-ca.key -in $PREFIX-ca.csr -out $PREFIX-$SERIAL.ca-cacert $DIGESTALGO \"\n\n$OPENSSL x509  -set_serial $SERIAL -extfile $PREFIX-ca.prm -days $DURATION -req -signkey $PREFIX-ca.key -in $PREFIX-ca.csr -out $PREFIX-$SERIAL-ca.cacert $DIGESTALGO\n\necho \"openssl x509 -text -in $PREFIX-$SERIAL-ca.cacert -nameopt multiline > $PREFIX-ca.cacert \"\n$OPENSSL x509 -text -in $PREFIX-$SERIAL-ca.cacert -nameopt multiline > $PREFIX-ca.cacert\n\necho \"openssl x509 -in $PREFIX-ca.cacert -outform der -out $PREFIX-ca.der \"\n$OPENSSL x509 -in $PREFIX-ca.cacert -outform der -out $PREFIX-ca.der\n\necho \"openssl x509 -in $PREFIX-ca.cacert -text -nameopt multiline > $PREFIX-ca.crt \"\n\n$OPENSSL x509 -in $PREFIX-ca.cacert -text -nameopt multiline > $PREFIX-ca.crt\n\necho \"openssl x509 -noout -text -in $PREFIX-ca.cacert -nameopt multiline\"\n$OPENSSL x509 -noout -text -in $PREFIX-ca.cacert -nameopt multiline\n\n#$OPENSSL rsa -in ../keys/$PREFIX-ca.key -text -noout -pubout\n", "num_lines": 69}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# (c) CopyRight 2000 - 2020, EdelWeb for EdelKey and OpenEvidence\n# Author: Peter Sylvester\n\n# \"libre\" for integration with curl\n\nOPENSSL=openssl\nif [ -f /usr/local/ssl/bin/openssl ] ; then\n   OPENSSL=/usr/local/ssl/bin/openssl\nfi\n\nUSAGE=\"echo Usage is genserv.sh <prefix> <caprefix>\"\n\nHOME=`pwd`\ncd $HOME\n\nKEYSIZE=2048\nDURATION=3000\n# The -sha256 option was introduced in OpenSSL 1.0.1\nDIGESTALGO=-sha256\n\nREQ=YES\nP12=NO\nDHP=NO\n\nPREFIX=$1\nif [ \".$PREFIX\" = . ] ; then\n   echo No configuration prefix\n   NOTOK=1\nelse\n   if [ ! -f $PREFIX-sv.prm ] ; then\n      echo No configuration file $PREFIX-sv.prm\n      NOTOK=1\n   fi\nfi\n\nCAPREFIX=$2\nif [ \".$CAPREFIX\" = . ] ; then\n   echo No CA prefix\n   NOTOK=1\nelse\n   if [ ! -f $CAPREFIX-ca.cacert ] ; then\n      echo No CA certificate file $CAPREFIX-ca.caert\n      NOTOK=1\n   fi\n   if [ ! -f $CAPREFIX-ca.key ] ; then\n      echo No $CAPREFIX key\n      NOTOK=1\n   fi\nfi\n\nif [ \".$NOTOK\" != . ] ; then\n   echo \"Sorry, I can't do that for you.\"\n   $USAGE\n   exit\nfi\n\nif [ \".$SERIAL\" = . ] ; then\n   GETSERIAL=\"\\$t = time ;\\$d =  \\$t . substr(\\$t+$$ ,-4,4)-1;print \\$d\"\n   SERIAL=`/usr/bin/env perl -e \"$GETSERIAL\"`\nfi\n\necho SERIAL=$SERIAL PREFIX=$PREFIX CAPREFIX=$CAPREFIX DURATION=$DURATION KEYSIZE=$KEYSIZE\n\nif [ \"$DHP.\" = YES. ] ; then\n   echo \"openssl dhparam -2 -out $PREFIX-sv.dhp $KEYSIZE\"\n   $OPENSSL dhparam -2 -out $PREFIX-sv.dhp $KEYSIZE\nfi\n\nif [ \"$REQ.\" = YES. ] ; then\n   echo \"openssl req -config $PREFIX-sv.prm -newkey rsa:$KEYSIZE -keyout $PREFIX-sv.key -out $PREFIX-sv.csr -passout XXX\"\n   $OPENSSL req -config $PREFIX-sv.prm -newkey rsa:$KEYSIZE -keyout $PREFIX-sv.key -out $PREFIX-sv.csr -passout pass:secret\nfi\n\necho \"openssl rsa -in $PREFIX-sv.key -out $PREFIX-sv.key\"\n$OPENSSL rsa -in $PREFIX-sv.key -out $PREFIX-sv.key -passin pass:secret\necho pseudo secrets generated\n\necho \"openssl rsa -in $PREFIX-sv.key -pubout -outform DER -out $PREFIX-sv.pub.der\"\n$OPENSSL rsa -in $PREFIX-sv.key -pubout -outform DER -out $PREFIX-sv.pub.der\n\necho \"openssl rsa -in $PREFIX-sv.key -pubout -outform PEM -out $PREFIX-sv.pub.pem\"\n$OPENSSL rsa -in $PREFIX-sv.key -pubout -outform PEM -out $PREFIX-sv.pub.pem\n\necho \"openssl x509 -set_serial $SERIAL -extfile $PREFIX-sv.prm -days $DURATION  -CA $CAPREFIX-ca.cacert -CAkey $CAPREFIX-ca.key -in $PREFIX-sv.csr -req -text -nameopt multiline $DIGESTALGO > $PREFIX-sv.crt \"\n\n$OPENSSL x509 -set_serial $SERIAL -extfile $PREFIX-sv.prm -days $DURATION  -CA $CAPREFIX-ca.cacert -CAkey $CAPREFIX-ca.key -in $PREFIX-sv.csr -req -text -nameopt multiline $DIGESTALGO > $PREFIX-sv.crt\n\nif [ \"$P12.\" = YES. ] ; then\n\n   echo \"$OPENSSL pkcs12 -export -des3 -out $PREFIX-sv.p12 -caname $CAPREFIX -name $PREFIX -inkey $PREFIX-sv.key -in $PREFIX-sv.crt -certfile $CAPREFIX-ca.crt \"\n\n   $OPENSSL pkcs12 -export -des3 -out $PREFIX-sv.p12 -caname $CAPREFIX -name $PREFIX -inkey $PREFIX-sv.key -in $PREFIX-sv.crt -certfile $CAPREFIX-ca.crt\nfi\n\necho \"openssl x509 -noout -text -hash -in $PREFIX-sv.selfcert -nameopt multiline\"\n$OPENSSL x509 -noout -text -hash -in $PREFIX-sv.crt -nameopt multiline\n\n# revoke server cert\ntouch $CAPREFIX-ca.db\necho 01 > $CAPREFIX-ca.cnt\necho \"openssl ca -config $CAPREFIX-ca.cnf -revoke $PREFIX-sv.crt\"\n$OPENSSL ca -config $CAPREFIX-ca.cnf -revoke $PREFIX-sv.crt\n\n# issue CRL\necho \"openssl ca -config $CAPREFIX-ca.cnf -gencrl -out $PREFIX-sv.crl\"\n$OPENSSL ca -config $CAPREFIX-ca.cnf -gencrl -out $PREFIX-sv.crl\n\necho \"openssl x509 -in $PREFIX-sv.crt -outform der -out $PREFIX-sv.der \"\n$OPENSSL x509 -in $PREFIX-sv.crt -outform der -out $PREFIX-sv.der\n\n# all together now\ntouch $PREFIX-sv.dhp\ncat $PREFIX-sv.prm $PREFIX-sv.key  $PREFIX-sv.crt $PREFIX-sv.dhp >$PREFIX-sv.pem\nchmod o-r $PREFIX-sv.prm\n\necho \"$PREFIX-sv.pem done\"\n", "num_lines": 119}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Run this to generate all the initial makefiles, etc.\n\nsrcdir=`dirname $0`\ntest -z \"$srcdir\" && srcdir=. \n\nTHEDIR=`pwd`\ncd $srcdir\nDIE=0\n\n(autoconf --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\techo \"You must have autoconf installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/autoconf\"\n\tDIE=1\n}\n\n(libtoolize --version) < /dev/null > /dev/null 2>&1 ||\n(glibtoolize --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\techo \"You must have libtool installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/libtool\"\n\tDIE=1\n}\n\n(automake --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\tDIE=1\n\techo \"You must have automake installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/automake\"\n}\n\nif test \"$DIE\" -eq 1; then\n\texit 1\nfi\n\ntest -f entities.c || {\n\techo \"You must run this script in the top-level libxml directory\"\n\texit 1\n}\n\nEXTRA_ARGS=\nif test \"x$1\" = \"x--system\"; then\n    shift\n    prefix=/usr\n    libdir=$prefix/lib\n    sysconfdir=/etc\n    localstatedir=/var\n    if [ -d /usr/lib64 ]; then\n      libdir=$prefix/lib64\n    fi\n    EXTRA_ARGS=\"--prefix=$prefix --sysconfdir=$sysconfdir --localstatedir=$localstatedir --libdir=$libdir\"\n    echo \"Running ./configure with $EXTRA_ARGS $@\"\nelse\n    if test -z \"$NOCONFIGURE\" && test -z \"$*\"; then\n        echo \"I am going to run ./configure with no arguments - if you wish \"\n        echo \"to pass any to it, please specify them on the $0 command line.\"\n    fi\nfi\n\nif [ ! -d $srcdir/m4 ]; then\n        mkdir $srcdir/m4\nfi\n\n# Replaced by autoreconf below\nautoreconf -if -Wall\n\nif ! grep -q pkg.m4 aclocal.m4; then\n    cat <<EOF\n\nCouldn't find pkg.m4 from pkg-config. Install the appropriate package for\nyour distribution or set ACLOCAL_PATH to the directory containing pkg.m4.\nEOF\n    exit 1\nfi\n\ncd $THEDIR\n\nif test x$OBJ_DIR != x; then\n    mkdir -p \"$OBJ_DIR\"\n    cd \"$OBJ_DIR\"\nfi\n\nif test -z \"$NOCONFIGURE\"; then\n    $srcdir/configure $EXTRA_ARGS \"$@\"\n    if test \"$?\" -ne 0; then\n        echo\n        echo \"Configure script failed, check config.log for more info.\"\n    else\n        echo\n        echo \"Now type 'make' to compile libxml2.\"\n    fi\nfi\n", "num_lines": 97}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.6-14\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2015-10-07.11; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    _G_rc_run_hooks=false\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      if eval $_G_hook '\"$@\"'; then\n        # store returned options list back into positional\n        # parameters for next 'cmd' execution.\n        eval _G_hook_result=\\$${_G_hook}_result\n        eval set dummy \"$_G_hook_result\"; shift\n        _G_rc_run_hooks=:\n      fi\n    done\n\n    $_G_rc_run_hooks && func_run_hooks_result=$_G_hook_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, you may remove/edit\n# any options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  In this case you also must return $EXIT_SUCCESS to let the\n# hook's caller know that it should pay attention to\n# '<hooked_function_name>_result'.  Returning $EXIT_FAILURE signalizes that\n# arguments are left untouched by the hook and therefore caller will ignore the\n# result variable.\n#\n# Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#        # No change in '$@' (ignored completely by this hook).  There is\n#        # no need to do the equivalent (but slower) action:\n#        # func_quote_for_eval ${1+\"$@\"}\n#        # my_options_prep_result=$func_quote_for_eval_result\n#        false\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        args_changed=false\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=:\n#                         args_changed=:\n#                         ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         args_changed=:\n#                         ;;\n#            *)           # Make sure the first unrecognised option \"$_G_opt\"\n#                         # is added back to \"$@\", we could need that later\n#                         # if $args_changed is true.\n#                         set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n#          esac\n#        done\n#\n#        if $args_changed; then\n#          func_quote_for_eval ${1+\"$@\"}\n#          my_silent_option_result=$func_quote_for_eval_result\n#        fi\n#\n#        $args_changed\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        false\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll also need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options_finish [ARG]...\n# ----------------------------\n# Finishing the option parse loop (call 'func_options' hooks ATM).\nfunc_options_finish ()\n{\n    $debug_cmd\n\n    _G_func_options_finish_exit=false\n    if func_run_hooks func_options ${1+\"$@\"}; then\n      func_options_finish_result=$func_run_hooks_result\n      _G_func_options_finish_exit=:\n    fi\n\n    $_G_func_options_finish_exit\n}\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    _G_rc_options=false\n\n    for my_func in options_prep parse_options validate_options options_finish\n    do\n      if eval func_$my_func '${1+\"$@\"}'; then\n        eval _G_res_var='$'\"func_${my_func}_result\"\n        eval set dummy \"$_G_res_var\" ; shift\n        _G_rc_options=:\n      fi\n    done\n\n    # Save modified positional parameters for caller.  As a top-level\n    # options-parser function we always need to set the 'func_options_result'\n    # variable (regardless the $_G_rc_options value).\n    if $_G_rc_options; then\n      func_options_result=$_G_res_var\n    else\n      func_quote_for_eval ${1+\"$@\"}\n      func_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_options\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propagate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning $EXIT_SUCCESS (otherwise $EXIT_FAILURE is returned).\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    _G_rc_options_prep=false\n    if func_run_hooks func_options_prep ${1+\"$@\"}; then\n      _G_rc_options_prep=:\n      # save modified positional parameters for caller\n      func_options_prep_result=$func_run_hooks_result\n    fi\n\n    $_G_rc_options_prep\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    _G_rc_parse_options=false\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      if func_run_hooks func_parse_options ${1+\"$@\"}; then\n        eval set dummy \"$func_run_hooks_result\"; shift\n        _G_rc_parse_options=:\n      fi\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_match_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      if test $# = 0 && func_missing_arg $_G_opt; then\n                        _G_rc_parse_options=:\n                        break\n                      fi\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           _G_rc_parse_options=: ; break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift\n                      _G_match_parse_options=false\n                      break\n                      ;;\n      esac\n\n      $_G_match_parse_options && _G_rc_parse_options=:\n    done\n\n\n    if $_G_rc_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      func_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_parse_options\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    _G_rc_validate_options=false\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    if func_run_hooks func_validate_options ${1+\"$@\"}; then\n      # save modified positional parameters for caller\n      func_validate_options_result=$func_run_hooks_result\n      _G_rc_validate_options=:\n    fi\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    $_G_rc_validate_options\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.6-14\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    _G_rc_lt_options_prep=:\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    *)\n      _G_rc_lt_options_prep=false\n      ;;\n    esac\n\n    if $_G_rc_lt_options_prep; then\n      # Pass back the list of options.\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_options_prep_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_options_prep\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    _G_rc_lt_parse_options=false\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_match_lt_parse_options=:\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        # An option not handled by this hook function:\n        *)              set dummy \"$_G_opt\" ${1+\"$@\"} ; shift\n                        _G_match_lt_parse_options=false\n                        break\n                        ;;\n      esac\n      $_G_match_lt_parse_options && _G_rc_lt_parse_options=:\n    done\n\n    if $_G_rc_lt_parse_options; then\n      # save modified positional parameters for caller\n      func_quote_for_eval ${1+\"$@\"}\n      libtool_parse_options_result=$func_quote_for_eval_result\n    fi\n\n    $_G_rc_lt_parse_options\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      # -fuse-ld=*           Linker select flags for GCC\n      # -static-*            direct GCC to link specific libraries statically\n      # -fcilkplus           Cilk Plus language extension features for C/C++\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*|-fuse-ld=*|-static-*|-fcilkplus)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11252}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Compilation scripts initialization for the OS/400 implementation.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in $TOPDIR/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nexport SCRIPTDIR TOPDIR\n\n\nsetenv()\n\n{\n        #       Define and export.\n\n        eval ${1}=\"${2}\"\n        export ${1}\n}\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nsetenv TARGETLIB        'LIBXML2'       # Target OS/400 program library.\nsetenv STATBNDDIR       'LIBXML2_A'     # Static binding directory.\nsetenv DYNBNDDIR        'LIBXML2'       # Dynamic binding directory.\nsetenv SRVPGM           \"LIBXML2\"       # Service program.\nsetenv TGTCCSID         '500'           # Target CCSID of objects.\nsetenv DEBUG            '*ALL'          # Debug level.\nsetenv OPTIMIZE         '10'            # Optimisation level.\nsetenv OUTPUT           '*NONE'         # Compilation output option.\nsetenv TGTRLS           'V6R1M0'        # Target OS release.\nsetenv IFSDIR           '/libxml2'      # Installation IFS directory.\n\n\n################################################################################\n#\n#                       Conditional compilation parameters.\n#\n################################################################################\n\nsetenv WITH_TRIO                1    # Configure trio support.\nsetenv WITH_THREADS             1    # Configure thread support.\nsetenv WITH_THREAD_ALLOC        1    # Whether allocation hooks are per-thread.\nsetenv WITH_TREE                1    # Compile DOM tree API.\nsetenv WITH_OUTPUT              1    # Compile serialization/saving support.\nsetenv WITH_PUSH                1    # Compile push parser.\nsetenv WITH_READER              1    # Compile parsing interface.\nsetenv WITH_PATTERN             1    # Compile pattern node selection interface.\nsetenv WITH_WRITER              1    # Compile saving interface.\nsetenv WITH_SAX1                1    # Compile SAX version 1 interface.\nsetenv WITH_FTP                 1    # Compile FTP support.\nsetenv WITH_HTTP                1    # Compile HTTP support.\nsetenv WITH_VALID               1    # Compile DTD validation support.\nsetenv WITH_HTML                1    # Compile HTML support.\nsetenv WITH_LEGACY              1    # Compile deprecated API.\nsetenv WITH_C14N                1    # Compile canonicalization support.\nsetenv WITH_CATALOG             1    # Compile catalog support.\nsetenv WITH_DOCB                1    # Compile SGML Docbook support.\nsetenv WITH_XPATH               1    # Compile XPath support.\nsetenv WITH_XPTR                1    # Compile XPointer support.\nsetenv WITH_XINCLUDE            1    # Compile XInclude support.\nsetenv WITH_ICONV               1    # Whether iconv support is available.\nsetenv WITH_ICU                 0    # Whether icu support is available.\nsetenv WITH_ISO8859X            1    # Compile ISO-8859-* support if no iconv.\nsetenv WITH_DEBUG               1    # Compile debugging module.\nsetenv WITH_MEM_DEBUG           1    # Compile memory debugging module.\nsetenv WITH_RUN_DEBUG           1    # Compile runtime debugging.\nsetenv WITH_REGEXPS             1    # Compile regular expression interfaces.\nsetenv WITH_SCHEMAS             1    # Compile schema validation interface.\nsetenv WITH_SCHEMATRON          1    # Compile schematron validation interface.\nsetenv WITH_MODULES             1    # Compile module interfaces.\nsetenv WITH_ZLIB                0    # Whether zlib is available.\nsetenv WITH_LZMA                0    # Whether LZMA is available.\n\n#       Define ZLIB locations. This is ignored if WITH_ZLIB is 0.\n\nsetenv ZLIB_INCLUDE             '/zlib/include' # ZLIB include IFS directory.\nsetenv ZLIB_LIB                 'ZLIB'          # ZLIB library.\nsetenv ZLIB_BNDDIR              'ZLIB_A'        # ZLIB binding directory.\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nsetenv LIBIFSNAME               \"/QSYS.LIB/${TARGETLIB}.LIB\"\nsetenv MODULE_EXTENSION         '.SRVPGM'\n\n\n################################################################################\n#\n#                       Extract version information.\n#\n################################################################################\n\n\n#       Transitional: get file name of configure script.\n\nAUTOCONFSCRIPT=\"${TOPDIR}/configure.ac\"\n\nif [ ! -f \"${AUTOCONFSCRIPT}\" ]\nthen    AUTOCONFSCRIPT=\"${TOPDIR}/configure.in\"\nfi\n\n#       Need to get the version definitions.\n\neval \"`grep '^LIBXML_[A-Z]*_VERSION=' \\\"${AUTOCONFSCRIPT}\\\"`\"\neval \"`grep '^LIBXML_MICRO_VERSION_SUFFIX=' \\\"${AUTOCONFSCRIPT}\\\"`\"\nLIBXML_VERSION=\"${LIBXML_MAJOR_VERSION}.${LIBXML_MINOR_VERSION}\"\nLIBXML_VERSION=\"${LIBXML_VERSION}.${LIBXML_MICRO_VERSION}\"\nLIBXML_VERSION=\"${LIBXML_VERSION}${LIBXML_MICRO_VERSION_SUFFIX}\"\nLIBXML_VERSION_NUMBER=`expr \"${LIBXML_MAJOR_VERSION}\" \\* 10000 +        \\\n                            \"${LIBXML_MINOR_VERSION}\" \\* 100 +          \\\n                            \"${LIBXML_MICRO_VERSION}\"`\nexport LIBXML_MAJOR_VERSION LIBXML_MINOR_VERSION\nexport LIBXML_MICRO_VERSION LIBXML_MICROVERSION_SUFFIX\nexport LIBXML_VERSION LIBXML_VERSION_NUMBER\nsetenv LIBXML_VERSION_EXTRA ''\nsetenv VERSION  \"${LIBXML_VERSION}\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       make_module [option] module_name source_name\n#\n#       Compile source name into ASCII module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n#       Options are:\n#         --define <additional definitions>\n#         --ebcdic\n#         --sysiconv\n\nmake_module()\n\n{\n        DEFN=\n        EBCDIC=\n        SYSICONV=\n        while true\n        do      case \"${1}\" in\n                --define)\n                        DEFN=\"${2}\"\n                        shift\n                        ;;\n                --ebcdic)\n                        EBCDIC=yes\n                        ;;\n                --sysiconv)\n                        SYSICONV=yes\n                        ;;\n                *)      break\n                esac\n                shift\n        done\n        MODULES=\"${MODULES} ${1}\"\n        MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n        action_needed \"${MODIFSNAME}\" \"${2}\" || return 0;\n\n        #       #pragma convert has to be in the source file itself, i.e.\n        #               putting it in an include file makes it only active\n        #               for that include file.\n        #       Thus we build a temporary file with the pragma prepended to\n        #               the source file and we compile that temporary file.\n\n        rm -f __tmpsrcf.c\n        if [ -z \"${EBCDIC}\" ]\n        then    echo \"#line 1 \\\"${2}\\\"\" >> __tmpsrcf.c\n                echo \"#pragma convert(819)\" >> __tmpsrcf.c\n                echo '#include \"wrappers.h\"' >> __tmpsrcf.c\n        fi\n        echo \"#line 1 \\\"${2}\\\"\" >> __tmpsrcf.c\n        cat \"${2}\" >> __tmpsrcf.c\n        CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('__tmpsrcf.c')\"\n#       CMD=\"${CMD} OPTION(*INCDIRFIRST *SHOWINC *SHOWSYS)\"\n        CMD=\"${CMD} OPTION(*INCDIRFIRST) FLAG(10)\"\n        CMD=\"${CMD} SYSIFCOPT(*IFS64IO) LANGLVL(*EXTENDED) LOCALETYPE(*LOCALE)\"\n        CMD=\"${CMD} INCDIR(\"\n        if [  -z \"${SYSICONV}\" ]\n        then    CMD=\"${CMD} '${TOPDIR}/os400/iconv'\"\n        fi\n        if [ -z \"${EBCDIC}\" ]\n        then    CMD=\"${CMD} '/qibm/proddata/qadrt/include'\"\n        fi\n        CMD=\"${CMD} '${TOPDIR}/os400' '${TOPDIR}/os400/dlfcn'\"\n        CMD=\"${CMD} '${IFSDIR}/include/libxml' '${IFSDIR}/include'\"\n        if [ \"${ZLIB_INCLUDE}\" ]\n        then    CMD=\"${CMD} '${ZLIB_INCLUDE}'\"\n        fi\n        CMD=\"${CMD} '${TOPDIR}' ${INCLUDES})\"\n        CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n        CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n        CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n        CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n        CMD=\"${CMD} DEFINE('_REENTRANT' 'TRIO_HAVE_CONFIG_H' 'NDEBUG' ${DEFN})\"\n\n        system \"${CMD}\"\n        rm -f __tmpsrcf.c\n        LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        if [ \"${2}\" = 'nomangle' ]\n        then    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^\\(..........\\).*$/\\1/'\n        else    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^TEST/T/'                                     \\\n                    -e 's/^XML/X/'                                      \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        fi\n}\n\n\n#       Copy IFS file replacing version & configuration info.\n\nversioned_copy()\n\n{\n    sed -e \"s/@LIBXML_VERSION@/${LIBXML_VERSION}/g\"                     \\\n                                                                        \\\n        -e \"s#@LIBXML_MAJOR_VERSION@#${LIBXML_MAJOR_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MINOR_VERSION@#${LIBXML_MINOR_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MICRO_VERSION@#${LIBXML_MICRO_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MICRO_VERSION_SUFFIX@#${LIBXML_MICRO_VERSION_SUFFIX}#g\" \\\n        -e \"s#@LIBXML_VERSION@#${LIBXML_VERSION}#g\"                     \\\n        -e \"s#@LIBXML_VERSION_NUMBER@#${LIBXML_VERSION_NUMBER}#g\"       \\\n        -e \"s#@LIBXML_VERSION_EXTRA@#${LIBXML_VERSION_EXTRA}#g\"         \\\n        -e \"s#@VERSION@#${VERSION}#g\"                                   \\\n        -e \"s#@WITH_TRIO@#${WITH_TRIO}#g\"                               \\\n        -e \"s#@WITH_THREADS@#${WITH_THREADS}#g\"                         \\\n        -e \"s#@WITH_THREAD_ALLOC@#${WITH_THREAD_ALLOC}#g\"               \\\n        -e \"s#@WITH_TREE@#${WITH_TREE}#g\"                               \\\n        -e \"s#@WITH_OUTPUT@#${WITH_OUTPUT}#g\"                           \\\n        -e \"s#@WITH_PUSH@#${WITH_PUSH}#g\"                               \\\n        -e \"s#@WITH_READER@#${WITH_READER}#g\"                           \\\n        -e \"s#@WITH_PATTERN@#${WITH_PATTERN}#g\"                         \\\n        -e \"s#@WITH_WRITER@#${WITH_WRITER}#g\"                           \\\n        -e \"s#@WITH_SAX1@#${WITH_SAX1}#g\"                               \\\n        -e \"s#@WITH_FTP@#${WITH_FTP}#g\"                                 \\\n        -e \"s#@WITH_HTTP@#${WITH_HTTP}#g\"                               \\\n        -e \"s#@WITH_VALID@#${WITH_VALID}#g\"                             \\\n        -e \"s#@WITH_HTML@#${WITH_HTML}#g\"                               \\\n        -e \"s#@WITH_LEGACY@#${WITH_LEGACY}#g\"                           \\\n        -e \"s#@WITH_C14N@#${WITH_C14N}#g\"                               \\\n        -e \"s#@WITH_CATALOG@#${WITH_CATALOG}#g\"                         \\\n        -e \"s#@WITH_DOCB@#${WITH_DOCB}#g\"                               \\\n        -e \"s#@WITH_XPATH@#${WITH_XPATH}#g\"                             \\\n        -e \"s#@WITH_XPTR@#${WITH_XPTR}#g\"                               \\\n        -e \"s#@WITH_XINCLUDE@#${WITH_XINCLUDE}#g\"                       \\\n        -e \"s#@WITH_ICONV@#${WITH_ICONV}#g\"                             \\\n        -e \"s#@WITH_ICU@#${WITH_ICU}#g\"                                 \\\n        -e \"s#@WITH_ISO8859X@#${WITH_ISO8859X}#g\"                       \\\n        -e \"s#@WITH_DEBUG@#${WITH_DEBUG}#g\"                             \\\n        -e \"s#@WITH_MEM_DEBUG@#${WITH_MEM_DEBUG}#g\"                     \\\n        -e \"s#@WITH_RUN_DEBUG@#${WITH_RUN_DEBUG}#g\"                     \\\n        -e \"s#@WITH_REGEXPS@#${WITH_REGEXPS}#g\"                         \\\n        -e \"s#@WITH_SCHEMAS@#${WITH_SCHEMAS}#g\"                         \\\n        -e \"s#@WITH_SCHEMATRON@#${WITH_SCHEMATRON}#g\"                   \\\n        -e \"s#@WITH_MODULES@#${WITH_MODULES}#g\"                         \\\n        -e \"s#@WITH_ZLIB@#${WITH_ZLIB}#g\"                               \\\n        -e \"s#@WITH_LZMA@#${WITH_LZMA}#g\"\n}\n", "num_lines": 316}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Compilation script for the iconv names DFA builer.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/os400/iconv/bldcsndfa\"\n\n\n# This is for old XML library (bootstrapping).\n#rm -rf xml.h xml\n#ln -s /QSYS.LIB/XML.LIB/H.FILE/XML.MBR xml.h\n#mkdir xml\n#mkdir xml/h\n#ln -s /QSYS.LIB/XML.LIB/H.FILE/UTF8.MBR xml/h/utf8\n\n\n#       Compile.\n\nCMD=\"CRTCMOD MODULE(${TARGETLIB}/BLDCSNDFA) SRCSTMF('bldcsndfa.c')\"\nCMD=\"${CMD} SYSIFCOPT(*IFS64IO) LANGLVL(*EXTENDED) LOCALETYPE(*LOCALE)\"\nCMD=\"${CMD} INCDIR(\"\nCMD=\"${CMD} '${IFSDIR}/include' ${INCLUDES})\"\nCMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\nCMD=\"${CMD} OUTPUT(${OUTPUT})\"\nCMD=\"${CMD} OPTIMIZE(10)\"\nCMD=\"${CMD} DBGVIEW(${DEBUG})\"\n#CMD=\"${CMD} DEFINE('OLDXML' 'xmlXPathSetContextNode=xmlXPathSetCurrentNode')\"\n\nsystem \"${CMD}\"\n\n#       Link\n\nCMD=\"CRTPGM PGM(${TARGETLIB}/BLDCSNDFA) MODULE(${TARGETLIB}/BLDCSNDFA)\"\nCMD=\"${CMD} BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n#CMD=\"${CMD} BNDDIR(XML/XML)\"\nCMD=\"${CMD} TGTRLS(${TGTRLS})\"\nsystem \"${CMD}\"\n", "num_lines": 44}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Installation of the C header files in the OS/400 library.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/include\"\n\n\n#       Create the OS/400 source program file for the C header files.\n\nSRCPF=\"${LIBIFSNAME}/LIBXML.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/LIBXML) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: C/C++ header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the C header files.\n\nif action_needed \"${IFSDIR}/include/libxml\"\nthen    mkdir -p \"${IFSDIR}/include/libxml\"\nfi\n\n\n\n#       Enumeration values may be used as va_arg tagfields, so they MUST be\n#               integers.\n\ncopy_hfile()\n\n{\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n'\n}\n\n#       Copy the header files to DB2 library. Link from IFS include directory.\n\nfor HFILE in \"${TOPDIR}/os400/transcode.h\" libxml/*.h libxml/*.h.in\ndo      CMD=\"cat \\\"${HFILE}\\\"\"\n        DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\" nomangle`.MBR\"\n\n        case \"`basename \\\"${HFILE}\\\"`\" in\n\n        *.in)   CMD=\"${CMD} | versioned_copy\";;\n\n        xmlschemastypes.h)      #       Special case: rename colliding file.\n                DEST=\"${SRCPF}/SCHMTYPES.MBR\";;\n\n        esac\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    eval \"${CMD}\" | copy_hfile > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\n\n        IFSFILE=\"${IFSDIR}/include/libxml/`basename \\\"${HFILE}\\\" .in`\"\n\n        if action_needed \"${IFSFILE}\" \"${DEST}\"\n        then    rm -f \"${IFSFILE}\"\n                ln -s \"${DEST}\" \"${IFSFILE}\"\n        fi\ndone\n", "num_lines": 79}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Installation of the ILE/RPG header files in the OS/400 library.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/os400/libxmlrpg\"\n\n\n#       Create the OS/400 source program file for the ILE/RPG header files.\n\nSRCPF=\"${LIBIFSNAME}/LIBXMLRPG.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/LIBXMLRPG) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: ILE/RPG header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Map file names to DB2 name syntax.\n\nfor HFILE in *.rpgle *.rpgle.in\ndo      NAME=\"`basename \\\"${HFILE}\\\" .in`\"\n        VAR=\"`basename \\\"${NAME}\\\" .rpgle`\"\n        VAL=\"`db2_name \\\"${NAME}\\\" nomangle`\"\n\n        if [ \"${VAR}\" = 'xmlschemastypes' ]\n        then    VAL=SCHMTYPES\n        fi\n\n        eval \"VAR_${VAR}=\\\"${VAL}\\\"\"\n        echo \"${VAR} s/${VAR}/${VAL}/g\"\ndone > tmpsubstfile1\n\n#       Order substitution commands so that a prefix appears after all\n#               file names beginning with the prefix.\n\nsort -r tmpsubstfile1 | sed 's/^[^ ]*[ ]*//' > tmpsubstfile2\n\n\nchange_include()\n\n{\n        sed -e '\\#^....../include  *\"libxmlrpg/#{'                      \\\n            -e 's///'                                                   \\\n            -e 's/\".*//'                                                \\\n            -f tmpsubstfile2                                            \\\n            -e 's#.*#      /include libxmlrpg,&#'                       \\\n            -e '}'\n}\n\n\n#       Create the IFS directory for the ILE/RPG header files.\n\nRPGIFSDIR=\"${IFSDIR}/include/libxmlrpg\"\n\nif action_needed \"${RPGIFSDIR}\"\nthen    mkdir -p \"${RPGIFSDIR}\"\nfi\n\n#       Copy the header files to IFS ILE/RPG include directory.\n#       Copy them with include path editing to the DB2 library.\n\nfor HFILE in *.rpgle *.rpgle.in\ndo      IFSCMD=\"cat \\\"${HFILE}\\\"\"\n        DB2CMD=\"change_include < \\\"${HFILE}\\\"\"\n        IFSFILE=\"`basename \\\"${HFILE}\\\" .in`\"\n\n        case \"${HFILE}\" in\n\n        *.in)   IFSCMD=\"${IFSCMD} | versioned_copy\"\n                DB2CMD=\"${DB2CMD} | versioned_copy\"\n                ;;\n        esac\n\n        IFSDEST=\"${RPGIFSDIR}/${IFSFILE}\"\n\n        if action_needed \"${IFSDEST}\" \"${HFILE}\"\n        then    eval \"${IFSCMD}\" > \"${IFSDEST}\"\n        fi\n\n        eval DB2MBR=\"\\\"\\${VAR_`basename \\\"${IFSDEST}\\\" .rpgle`}\\\"\"\n        DB2DEST=\"${SRCPF}/${DB2MBR}.MBR\"\n\n        if action_needed \"${DB2DEST}\" \"${HFILE}\"\n        then    eval \"${DB2CMD}\" | change_include > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DB2DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n", "num_lines": 101}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       libxml compilation script for the OS/400.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"libxml2 version '\"${LIBXML_VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1998-2017 Daniel Veillard. OS/400 version by P. Monnerat.\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nfoldlines()\n\n{\n        sed -e ':begin'                                                 \\\n            -e '/\\\\$/{'                                                 \\\n            -e 's/\\\\$/ /'                                               \\\n            -e 'N'                                                      \\\n            -e 'bbegin'                                                 \\\n            -e '}'                                                      \\\n            -e 's/\\n//g'                                                \\\n            -e 's/[[:space:]]*$//'\n}\n\n\nget_make_var()\n\n{\n        foldlines < Makefile.am                                         |\n        sed -e \"/^${1}[[:space:]]*=[[:space:]]*/{\"                      \\\n            -e 's///'                                                   \\\n            -e 'q'                                                      \\\n            -e '}'                                                      \\\n            -e 'd'\n}\n\n\ndocb_sources=`get_make_var docb_sources`\ntrio_sources=`get_make_var trio_sources`\nCSOURCES=`eval echo \"\\`get_make_var libxml2_la_SOURCES | tr '()' '{}'\\`\"`\n\n\n#       Compile the sources into modules.\n\nINCLUDES=\"'`pwd`'\"\n\n#       OS/400 specific modules first.\n\nmake_module     --ebcdic        DLFCN           \"${SCRIPTDIR}/dlfcn/dlfcn.c\"\nmake_module     --ebcdic        ICONV           \"${SCRIPTDIR}/iconv/iconv.c\"\nmake_module     --ebcdic        WRAPPERS        \"${SCRIPTDIR}/wrappers.c\"\nmake_module                     TRANSCODE       \"${SCRIPTDIR}/transcode.c\"\nmake_module                     RPGSUPPORT      \"${SCRIPTDIR}/rpgsupport.c\"\n\n#       Regular libxml2 modules.\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('libxml2 static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: build tools')\"\n        system \"${CMD}\"\nfi\n\n\n#       Generate all exported symbol table versions in a binding source file.\n\nBSF=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\nPGMEXPS=\n\nOS400SYMS=`cat os400/transcode.h os400/rpgsupport.h                     |\n           sed -e 'H'                                                   \\\n               -e 'g'                                                   \\\n               -e 's/\\n/ /'                                             \\\n               -e 's/\\\\$/ /'                                            \\\n               -e 's/.*/& /'                                            \\\n               -e 's/\\/\\*.*\\*\\// /g'                                    \\\n               -e 'h'                                                   \\\n               -e ':loop'                                               \\\n               -e 'g'                                                   \\\n               -e '/\\/\\*/d'                                             \\\n               -e '/;/!d'                                               \\\n               -e 's/[^;]*;//'                                          \\\n               -e 'x'                                                   \\\n               -e 's/[[:space:]]*;.*$//'                                \\\n               -e '/XMLPUBFUN/{'                                        \\\n               -e 's/[[:space:]]*(.*$//'                                \\\n               -e 's/.*[[:space:]*]//'                                  \\\n               -e 'p'                                                   \\\n               -e 'bloop'                                               \\\n               -e '}'                                                   \\\n               -e '/XMLPUBVAR/!bloop'                                   \\\n               -e ':loop2'                                              \\\n               -e '/\\[[^][]*\\]/{'                                       \\\n               -e 's///'                                                \\\n               -e 'bloop2'                                              \\\n               -e '}'                                                   \\\n               -e 's/[[:space:]]*,[[:space:]]*/,/g'                     \\\n               -e 's/[^,]*[[:space:]*]//'                               \\\n               -e 's/[^[:alnum:]_,]//g'                                 \\\n               -e 's/,/\\n/g'                                            \\\n               -e 'p'                                                   \\\n               -e 'bloop'`\n\nsed -e 's/#.*//'                                                        \\\n    -e 's/[[:space:]]*$//'                                              \\\n    -e 's/^[[:space:]]*//'                                              \\\n    -e '/^*global:$/d'                                                  \\\n    -e '/^$/d'                                                          \\\n    -e '/[[:space:]]*{$/{'                                              \\\n    -e   's///'                                                         \\\n    -e   'h'                                                            \\\n    -e   's/[^A-Za-z0-9]/_/g'                                           \\\n    -e   's/^[0-9]/_&/'                                                 \\\n    -e   'x'                                                            \\\n    -e   'G'                                                            \\\n    -e   's/\\(.*\\)\\n\\(.*\\)/\\2_SIGNATURE=\"\\1\"/'                          \\\n    -e   'p'                                                            \\\n    -e   's/.*//'                                                       \\\n    -e   'x'                                                            \\\n    -e   \"s/.*/SONAME='&'/\"                                             \\\n    -e   'b'                                                            \\\n    -e '}'                                                              \\\n    -e '/[[:space:]]*;$/!d'                                             \\\n    -e 's///'                                                           \\\n    -e '/^xmlDllMain$/d'                                                \\\n    -e '/^}[[:space:]]*/!{'                                             \\\n    -e   'H'                                                            \\\n    -e   'd'                                                            \\\n    -e '}'                                                              \\\n    -e 's///'                                                           \\\n    -e '/^$/!{'                                                         \\\n    -e   's/[^A-Za-z0-9]/_/g'                                           \\\n    -e   's/^[0-9]/_&/'                                                 \\\n    -e   's/.*/${&}/'                                                   \\\n    -e   'x'                                                            \\\n    -e   'H'                                                            \\\n    -e   's/.*//'                                                       \\\n    -e '}'                                                              \\\n    -e 'x'                                                              \\\n    -e 's/\\n/ /g'                                                       \\\n    -e 's/^[[:space:]]*//'                                              \\\n    -e 's/.*/declare ${SONAME}=\"&\"/'                                    \\\n    -e 's/.*/&; PGMEXPS=\"${SONAME} ${PGMEXPS}\"/'                        \\\n        < \"${TOPDIR}/libxml2.syms\"    > bndvars\n. ./bndvars\n\nPGMLVL=CURRENT\nfor PGMEXP in ${PGMEXPS}\ndo      SIGNATURE=`echo \"${PGMEXP}\" | sed 's/^LIBXML2_//'`\n        eval ENTRIES=\\\"\\${${PGMEXP}}\\\"\n        echo \" STRPGMEXP PGMLVL(*${PGMLVL}) SIGNATURE('${SIGNATURE}')\"\n        for ENTRY in ${ENTRIES} ${OS400SYMS}\n        do      echo \" EXPORT    SYMBOL('${ENTRY}')\"\n        done\n        echo ' ENDPGMEXP'\n        PGMLVL=PRV\ndone            > \"${BSF}\"\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD})\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS)\"\n        CMD=\"${CMD} TEXT('libxml2 dynamic library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('libxml2 dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n\n\n#       Compile the ASCII main() stub.\n\nmake_module     --ebcdic --sysiconv     LIBXMLMAIN  \"${SCRIPTDIR}/libxmlmain.c\"\n\n\n#       Compile and link program xmllint.\n\nif action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"xmllint.c\" ||\n   action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\" ||\n   action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"${LIBIFSNAME}/LIBXMLMAIN.MODULE\"\nthen    make_module XMLLINT xmllint.c\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLLINT) MODULE(${TARGETLIB}/XMLLINT)\"\n        CMD=\"${CMD} ENTMOD(${TARGETLIB}/LIBXMLMAIN)\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS) BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD}) ACTGRP(*NEW) TEXT('XML tool')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLLINT.MODULE\"\nfi\n\n#       Install xmllint in IFS.\n\nif [ ! -d \"${IFSDIR}/bin\" ]\nthen    mkdir -p \"${IFSDIR}/bin\"\nfi\nrm -f \"${IFSDIR}/bin/xmllint\"\nln -s \"${LIBIFSNAME}/XMLLINT.PGM\" \"${IFSDIR}/bin/xmllint\"\n\n#       Prepare the XMLLINT command and its response program.\n\nif action_needed \"${LIBIFSNAME}/XMLLINTCL.PGM\" \"${SCRIPTDIR}/xmllintcl.c\"\nthen    make_module --ebcdic XMLLINTCL \"${SCRIPTDIR}/xmllintcl.c\"\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLLINTCL) MODULE(${TARGETLIB}/XMLLINTCL)\"\n        CMD=\"${CMD} ACTGRP(*NEW) TEXT('XMLLINT command response')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLLINTCL.MODULE\"\nfi\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR\"                 \\\n                 \"${SCRIPTDIR}/xmllint.cmd\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/xmllint.cmd')\"\n        CMD=\"${CMD} TOOBJ('${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\nif action_needed \"${LIBIFSNAME}/XMLLINT.CMD\"                            \\\n                 \"${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR\"\nthen    CMD=\"CRTCMD CMD(${TARGETLIB}/XMLLINT) PGM(${TARGETLIB}/XMLLINTCL)\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(XMLLINT) THDSAFE(*YES)\"\n        CMD=\"${CMD} TEXT('XML tool') REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\n\n#       Compile and link program xmlcatalog.\n\nif action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\" \"xmlcatalog.c\" ||\n   action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\"                         \\\n                 \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\" ||\n   action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\"                         \\\n                 \"${LIBIFSNAME}/LIBXMLMAIN.MODULE\"\nthen    make_module XMLCATALOG xmlcatalog.c\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLCATALOG)\"\n        CMD=\"${CMD}  MODULE(${TARGETLIB}/XMLCATALOG)\"\n        CMD=\"${CMD} ENTMOD(${TARGETLIB}/LIBXMLMAIN)\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS) BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD}) ACTGRP(*NEW) TEXT('XML/SGML catalog tool')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLCATALOG.MODULE\"\nfi\n\n#       Install xmlcatalog in IFS.\n\nrm -f \"${IFSDIR}/bin/xmlcatalog\"\nln -s \"${LIBIFSNAME}/XMLCATALOG.PGM\" \"${IFSDIR}/bin/xmlcatalog\"\n\n#       Prepare the XMLCATALOG command and its response program.\n\nif action_needed \"${LIBIFSNAME}/XMLCATLGCL.PGM\" \"${SCRIPTDIR}/xmlcatlgcl.c\"\nthen    make_module --ebcdic XMLCATLGCL \"${SCRIPTDIR}/xmlcatlgcl.c\"\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} ACTGRP(*NEW) TEXT('XMLCATALOG command response')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLCATLGCL.MODULE\"\nfi\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR\"              \\\n                 \"${SCRIPTDIR}/xmlcatalog.cmd\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/xmlcatalog.cmd')\"\n        CMD=\"${CMD} TOOBJ('${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\nif action_needed \"${LIBIFSNAME}/XMLCATALOG.CMD\"                         \\\n                 \"${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR\"\nthen    CMD=\"CRTCMD CMD(${TARGETLIB}/XMLCATALOG) PGM(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(XMLCATALOG)\"\n        CMD=\"${CMD} THDSAFE(*YES) TEXT('XML/SGML catalog tool') REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n", "num_lines": 356}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       libxml2 compilation script for the OS/400.\n#       This is a shell script since make is not a standard component of OS/400.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB})\"\n        CMD=\"${CMD} TEXT('libxml2: XML parser and toolkit API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/AUTHORS\" \"${TOPDIR}/ChangeLog\"                   \\\n    \"${TOPDIR}/Copyright\" \"${TOPDIR}/CONTRIBUTING\" \"${TOPDIR}/README\"        \\\n    \"${TOPDIR}/MAINTAINERS\" \"${TOPDIR}/NEWS\" \"${TOPDIR}/TODO\"           \\\n    \"${TOPDIR}/TODO_SCHEMAS\" \"${TOPDIR}/os400/README400\"\ndo      if [ -f \"${TEXT}\" ]\n        then    MEMBER=\"`basename \\\"${TEXT}\\\" .OS400`\"\n                MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${MEMBER}\\\"`.MBR\"\n\n                if action_needed \"${MEMBER}\" \"${TEXT}\"\n                then    # Sources are in UTF-8.\n                        rm -f \"${TOPDIR}/tmpfile\"[12]\n                        CMD=\"CPY OBJ('${TEXT}') TOOBJ('${TOPDIR}/tmpfile1')\"\n                        CMD=\"${CMD} FROMCCSID(1208) TOCCSID(${TGTCCSID})\"\n                        CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                        system \"${CMD}\"\n                        # Make sure all lines are < 100 characters.\n                        sed -e 's/.\\{99\\}/&\\\n/g' -e 's/\\n$//' \"${TOPDIR}/tmpfile1\" > \"${TOPDIR}/tmpfile2\"\n                        CMD=\"CPY OBJ('${TOPDIR}/tmpfile2') TOOBJ('${MEMBER}')\"\n                        CMD=\"${CMD} TOCCSID(${TGTCCSID})\"\n                        CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                        system \"${CMD}\"\n                fi\n        fi\ndone\n\n\n#       Build files from template.\n\nconfigFile()\n\n{\n        args=`set | sed -e '/^[A-Za-z_][A-Za-z0-9_]*=/!d'               \\\n                        -e 's/[\\/\\\\\\\\&]/\\\\\\\\&/g'                        \\\n                        -e \"s/'/'\\\\\\\\\\\\''/g\"                            \\\n                        -e 's/^\\([^=]*\\)=\\(.*\\)$/-e '\\''s\\/@\\1@\\/\\2\\/g'\\'/`\n        eval sed ${args} < \"${1}\".in > \"${1}\"\n}\n\nconfigFile include/libxml/xmlversion.h\nconfigFile os400/os400config.h\nmv os400/os400config.h config.h\n\n\n#       Build in each directory.\n\nfor SUBDIR in include rpg src\ndo      \"${SCRIPTDIR}/make-${SUBDIR}.sh\"\ndone\n", "num_lines": 85}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "LIBXML2=$1\nTARGETCPU=$2\nTARGETTYPE=$3\n\nif [ -z \"$2\" ]; then\n\tTARGETCPU=SIMPENTIUMgnu\nfi\n\nif [ -z \"$3\" ]; then\n\tTARGETTYPE=RTP\nfi\n\necho \"LIBXML2 Version:     ${LIBXML2}\"\necho \"LIBXML2 Target CPU:  ${TARGETCPU}\"\necho \"LIBXML2 Target Type: ${TARGETTYPE}\"\n\nrm -fR src\ntar xvzf ${LIBXML2}.tar.gz\nmv ${LIBXML2} src\ncd src\n\n./configure --with-minimum --with-reader --with-writer --with-regexps --with-threads --with-thread-alloc\n\nfind . -name '*.in' -exec rm -fR {} +\nfind . -name '*.am' -exec rm -fR {} +\nrm -fR *.m4\nrm -fR *.pc\nrm -fR *.pl\nrm -fR *.py\nrm -fR *.spec\nrm -fR .deps\nrm -fR AUTHORS\nrm -fR bakefile\nrm -fR ChangeLog\nrm -fR config.guess\nrm -fR config.log\nrm -fR config.status\nrm -fR config.stub\nrm -fR config.sub\nrm -fR configure\nrm -fR COPYING\nrm -fR Copyright\nrm -fR depcomp\nrm -fR doc\nrm -fR example\nrm -fR INSTALL\nrm -fR install-sh\nrm -fR libxml.3\nrm -fR ltmain.sh\nrm -fR Makefile\nrm -fR Makefile.tests\nrm -fR macos\nrm -fR mkinstalldirs\nrm -fR missing\nrm -fR nanoftp.c\nrm -fR nanohttp.c\nrm -fR NEWS\nrm -fR python\nrm -fR README\nrm -fR README.tests\nrm -fR regressions.xml\nrm -fR result\nrm -fR runsuite.c\nrm -fR runtest.c\nrm -fR test\nrm -fR test*.c\nrm -fR TODO*\nrm -fR trio*\nrm -fR vms\nrm -fR win32\nrm -fR xml2*\nrm -fR xmllint.c\nrm -fR xstc\n\ncd ..\n\nmake clean all VXCPU=${TARGETCPU} VXTYPE=${TARGETTYPE}\n\nif [ \"${TARGETTYPE}\" = \"RTP\" ]; then\n\tcp libxml2.so ../../lib/.\nelse\n\tcp xml2.out ../../bin/.\nfi\n\ncp -R src/include/libxml ../../include/.", "num_lines": 85}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Run this to generate all the initial makefiles, etc.\n\nsrcdir=`dirname $0`\ntest -z \"$srcdir\" && srcdir=. \n\nTHEDIR=`pwd`\ncd $srcdir\nDIE=0\n\n(autoconf --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\techo \"You must have autoconf installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/autoconf\"\n\tDIE=1\n}\n\n(libtoolize --version) < /dev/null > /dev/null 2>&1 ||\n(glibtoolize --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\techo \"You must have libtool installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/libtool\"\n\tDIE=1\n}\n\n(automake --version) < /dev/null > /dev/null 2>&1 || {\n\techo\n\tDIE=1\n\techo \"You must have automake installed to compile libxml.\"\n\techo \"Download the appropriate package for your distribution,\"\n\techo \"or see http://www.gnu.org/software/automake\"\n}\n\nif test \"$DIE\" -eq 1; then\n\texit 1\nfi\n\ntest -f entities.c || {\n\techo \"You must run this script in the top-level libxml directory\"\n\texit 1\n}\n\nEXTRA_ARGS=\nif test \"x$1\" = \"x--system\"; then\n    shift\n    prefix=/usr\n    libdir=$prefix/lib\n    sysconfdir=/etc\n    localstatedir=/var\n    if [ -d /usr/lib64 ]; then\n      libdir=$prefix/lib64\n    fi\n    EXTRA_ARGS=\"--prefix=$prefix --sysconfdir=$sysconfdir --localstatedir=$localstatedir --libdir=$libdir\"\n    echo \"Running ./configure with $EXTRA_ARGS $@\"\nelse\n    if test -z \"$NOCONFIGURE\" && test -z \"$*\"; then\n        echo \"I am going to run ./configure with no arguments - if you wish \"\n        echo \"to pass any to it, please specify them on the $0 command line.\"\n    fi\nfi\n\nif [ ! -d $srcdir/m4 ]; then\n        mkdir $srcdir/m4\nfi\n\n# Replaced by autoreconf below\nautoreconf -if -Wall\n\nif ! grep -q pkg.m4 aclocal.m4; then\n    cat <<EOF\n\nCouldn't find pkg.m4 from pkg-config. Install the appropriate package for\nyour distribution or set ACLOCAL_PATH to the directory containing pkg.m4.\nEOF\n    exit 1\nfi\n\ncd $THEDIR\n\nif test x$OBJ_DIR != x; then\n    mkdir -p \"$OBJ_DIR\"\n    cd \"$OBJ_DIR\"\nfi\n\nif test -z \"$NOCONFIGURE\"; then\n    $srcdir/configure $EXTRA_ARGS \"$@\"\n    if test \"$?\" -ne 0; then\n        echo\n        echo \"Configure script failed, check config.log for more info.\"\n    else\n        echo\n        echo \"Now type 'make' to compile libxml2.\"\n    fi\nfi\n", "num_lines": 97}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Compilation scripts initialization for the OS/400 implementation.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in $TOPDIR/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nexport SCRIPTDIR TOPDIR\n\n\nsetenv()\n\n{\n        #       Define and export.\n\n        eval ${1}=\"${2}\"\n        export ${1}\n}\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nsetenv TARGETLIB        'LIBXML2'       # Target OS/400 program library.\nsetenv STATBNDDIR       'LIBXML2_A'     # Static binding directory.\nsetenv DYNBNDDIR        'LIBXML2'       # Dynamic binding directory.\nsetenv SRVPGM           \"LIBXML2\"       # Service program.\nsetenv TGTCCSID         '500'           # Target CCSID of objects.\nsetenv DEBUG            '*ALL'          # Debug level.\nsetenv OPTIMIZE         '10'            # Optimisation level.\nsetenv OUTPUT           '*NONE'         # Compilation output option.\nsetenv TGTRLS           'V6R1M0'        # Target OS release.\nsetenv IFSDIR           '/libxml2'      # Installation IFS directory.\n\n\n################################################################################\n#\n#                       Conditional compilation parameters.\n#\n################################################################################\n\nsetenv WITH_TRIO                1    # Configure trio support.\nsetenv WITH_THREADS             1    # Configure thread support.\nsetenv WITH_THREAD_ALLOC        1    # Whether allocation hooks are per-thread.\nsetenv WITH_TREE                1    # Compile DOM tree API.\nsetenv WITH_OUTPUT              1    # Compile serialization/saving support.\nsetenv WITH_PUSH                1    # Compile push parser.\nsetenv WITH_READER              1    # Compile parsing interface.\nsetenv WITH_PATTERN             1    # Compile pattern node selection interface.\nsetenv WITH_WRITER              1    # Compile saving interface.\nsetenv WITH_SAX1                1    # Compile SAX version 1 interface.\nsetenv WITH_FTP                 1    # Compile FTP support.\nsetenv WITH_HTTP                1    # Compile HTTP support.\nsetenv WITH_VALID               1    # Compile DTD validation support.\nsetenv WITH_HTML                1    # Compile HTML support.\nsetenv WITH_LEGACY              1    # Compile deprecated API.\nsetenv WITH_C14N                1    # Compile canonicalization support.\nsetenv WITH_CATALOG             1    # Compile catalog support.\nsetenv WITH_DOCB                1    # Compile SGML Docbook support.\nsetenv WITH_XPATH               1    # Compile XPath support.\nsetenv WITH_XPTR                1    # Compile XPointer support.\nsetenv WITH_XINCLUDE            1    # Compile XInclude support.\nsetenv WITH_ICONV               1    # Whether iconv support is available.\nsetenv WITH_ICU                 0    # Whether icu support is available.\nsetenv WITH_ISO8859X            1    # Compile ISO-8859-* support if no iconv.\nsetenv WITH_DEBUG               1    # Compile debugging module.\nsetenv WITH_MEM_DEBUG           1    # Compile memory debugging module.\nsetenv WITH_RUN_DEBUG           1    # Compile runtime debugging.\nsetenv WITH_REGEXPS             1    # Compile regular expression interfaces.\nsetenv WITH_SCHEMAS             1    # Compile schema validation interface.\nsetenv WITH_SCHEMATRON          1    # Compile schematron validation interface.\nsetenv WITH_MODULES             1    # Compile module interfaces.\nsetenv WITH_ZLIB                0    # Whether zlib is available.\nsetenv WITH_LZMA                0    # Whether LZMA is available.\n\n#       Define ZLIB locations. This is ignored if WITH_ZLIB is 0.\n\nsetenv ZLIB_INCLUDE             '/zlib/include' # ZLIB include IFS directory.\nsetenv ZLIB_LIB                 'ZLIB'          # ZLIB library.\nsetenv ZLIB_BNDDIR              'ZLIB_A'        # ZLIB binding directory.\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nsetenv LIBIFSNAME               \"/QSYS.LIB/${TARGETLIB}.LIB\"\nsetenv MODULE_EXTENSION         '.SRVPGM'\n\n\n################################################################################\n#\n#                       Extract version information.\n#\n################################################################################\n\n\n#       Transitional: get file name of configure script.\n\nAUTOCONFSCRIPT=\"${TOPDIR}/configure.ac\"\n\nif [ ! -f \"${AUTOCONFSCRIPT}\" ]\nthen    AUTOCONFSCRIPT=\"${TOPDIR}/configure.in\"\nfi\n\n#       Need to get the version definitions.\n\neval \"`grep '^LIBXML_[A-Z]*_VERSION=' \\\"${AUTOCONFSCRIPT}\\\"`\"\neval \"`grep '^LIBXML_MICRO_VERSION_SUFFIX=' \\\"${AUTOCONFSCRIPT}\\\"`\"\nLIBXML_VERSION=\"${LIBXML_MAJOR_VERSION}.${LIBXML_MINOR_VERSION}\"\nLIBXML_VERSION=\"${LIBXML_VERSION}.${LIBXML_MICRO_VERSION}\"\nLIBXML_VERSION=\"${LIBXML_VERSION}${LIBXML_MICRO_VERSION_SUFFIX}\"\nLIBXML_VERSION_NUMBER=`expr \"${LIBXML_MAJOR_VERSION}\" \\* 10000 +        \\\n                            \"${LIBXML_MINOR_VERSION}\" \\* 100 +          \\\n                            \"${LIBXML_MICRO_VERSION}\"`\nexport LIBXML_MAJOR_VERSION LIBXML_MINOR_VERSION\nexport LIBXML_MICRO_VERSION LIBXML_MICROVERSION_SUFFIX\nexport LIBXML_VERSION LIBXML_VERSION_NUMBER\nsetenv LIBXML_VERSION_EXTRA ''\nsetenv VERSION  \"${LIBXML_VERSION}\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       make_module [option] module_name source_name\n#\n#       Compile source name into ASCII module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n#       Options are:\n#         --define <additional definitions>\n#         --ebcdic\n#         --sysiconv\n\nmake_module()\n\n{\n        DEFN=\n        EBCDIC=\n        SYSICONV=\n        while true\n        do      case \"${1}\" in\n                --define)\n                        DEFN=\"${2}\"\n                        shift\n                        ;;\n                --ebcdic)\n                        EBCDIC=yes\n                        ;;\n                --sysiconv)\n                        SYSICONV=yes\n                        ;;\n                *)      break\n                esac\n                shift\n        done\n        MODULES=\"${MODULES} ${1}\"\n        MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n        action_needed \"${MODIFSNAME}\" \"${2}\" || return 0;\n\n        #       #pragma convert has to be in the source file itself, i.e.\n        #               putting it in an include file makes it only active\n        #               for that include file.\n        #       Thus we build a temporary file with the pragma prepended to\n        #               the source file and we compile that temporary file.\n\n        rm -f __tmpsrcf.c\n        if [ -z \"${EBCDIC}\" ]\n        then    echo \"#line 1 \\\"${2}\\\"\" >> __tmpsrcf.c\n                echo \"#pragma convert(819)\" >> __tmpsrcf.c\n                echo '#include \"wrappers.h\"' >> __tmpsrcf.c\n        fi\n        echo \"#line 1 \\\"${2}\\\"\" >> __tmpsrcf.c\n        cat \"${2}\" >> __tmpsrcf.c\n        CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('__tmpsrcf.c')\"\n#       CMD=\"${CMD} OPTION(*INCDIRFIRST *SHOWINC *SHOWSYS)\"\n        CMD=\"${CMD} OPTION(*INCDIRFIRST) FLAG(10)\"\n        CMD=\"${CMD} SYSIFCOPT(*IFS64IO) LANGLVL(*EXTENDED) LOCALETYPE(*LOCALE)\"\n        CMD=\"${CMD} INCDIR(\"\n        if [  -z \"${SYSICONV}\" ]\n        then    CMD=\"${CMD} '${TOPDIR}/os400/iconv'\"\n        fi\n        if [ -z \"${EBCDIC}\" ]\n        then    CMD=\"${CMD} '/qibm/proddata/qadrt/include'\"\n        fi\n        CMD=\"${CMD} '${TOPDIR}/os400' '${TOPDIR}/os400/dlfcn'\"\n        CMD=\"${CMD} '${IFSDIR}/include/libxml' '${IFSDIR}/include'\"\n        if [ \"${ZLIB_INCLUDE}\" ]\n        then    CMD=\"${CMD} '${ZLIB_INCLUDE}'\"\n        fi\n        CMD=\"${CMD} '${TOPDIR}' ${INCLUDES})\"\n        CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n        CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n        CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n        CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n        CMD=\"${CMD} DEFINE('_REENTRANT' 'TRIO_HAVE_CONFIG_H' 'NDEBUG' ${DEFN})\"\n\n        system \"${CMD}\"\n        rm -f __tmpsrcf.c\n        LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        if [ \"${2}\" = 'nomangle' ]\n        then    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^\\(..........\\).*$/\\1/'\n        else    basename \"${1}\"                                         |\n                tr 'a-z-' 'A-Z_'                                        |\n                sed -e 's/\\..*//'                                       \\\n                    -e 's/^TEST/T/'                                     \\\n                    -e 's/^XML/X/'                                      \\\n                    -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n        fi\n}\n\n\n#       Copy IFS file replacing version & configuration info.\n\nversioned_copy()\n\n{\n    sed -e \"s/@LIBXML_VERSION@/${LIBXML_VERSION}/g\"                     \\\n                                                                        \\\n        -e \"s#@LIBXML_MAJOR_VERSION@#${LIBXML_MAJOR_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MINOR_VERSION@#${LIBXML_MINOR_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MICRO_VERSION@#${LIBXML_MICRO_VERSION}#g\"         \\\n        -e \"s#@LIBXML_MICRO_VERSION_SUFFIX@#${LIBXML_MICRO_VERSION_SUFFIX}#g\" \\\n        -e \"s#@LIBXML_VERSION@#${LIBXML_VERSION}#g\"                     \\\n        -e \"s#@LIBXML_VERSION_NUMBER@#${LIBXML_VERSION_NUMBER}#g\"       \\\n        -e \"s#@LIBXML_VERSION_EXTRA@#${LIBXML_VERSION_EXTRA}#g\"         \\\n        -e \"s#@VERSION@#${VERSION}#g\"                                   \\\n        -e \"s#@WITH_TRIO@#${WITH_TRIO}#g\"                               \\\n        -e \"s#@WITH_THREADS@#${WITH_THREADS}#g\"                         \\\n        -e \"s#@WITH_THREAD_ALLOC@#${WITH_THREAD_ALLOC}#g\"               \\\n        -e \"s#@WITH_TREE@#${WITH_TREE}#g\"                               \\\n        -e \"s#@WITH_OUTPUT@#${WITH_OUTPUT}#g\"                           \\\n        -e \"s#@WITH_PUSH@#${WITH_PUSH}#g\"                               \\\n        -e \"s#@WITH_READER@#${WITH_READER}#g\"                           \\\n        -e \"s#@WITH_PATTERN@#${WITH_PATTERN}#g\"                         \\\n        -e \"s#@WITH_WRITER@#${WITH_WRITER}#g\"                           \\\n        -e \"s#@WITH_SAX1@#${WITH_SAX1}#g\"                               \\\n        -e \"s#@WITH_FTP@#${WITH_FTP}#g\"                                 \\\n        -e \"s#@WITH_HTTP@#${WITH_HTTP}#g\"                               \\\n        -e \"s#@WITH_VALID@#${WITH_VALID}#g\"                             \\\n        -e \"s#@WITH_HTML@#${WITH_HTML}#g\"                               \\\n        -e \"s#@WITH_LEGACY@#${WITH_LEGACY}#g\"                           \\\n        -e \"s#@WITH_C14N@#${WITH_C14N}#g\"                               \\\n        -e \"s#@WITH_CATALOG@#${WITH_CATALOG}#g\"                         \\\n        -e \"s#@WITH_DOCB@#${WITH_DOCB}#g\"                               \\\n        -e \"s#@WITH_XPATH@#${WITH_XPATH}#g\"                             \\\n        -e \"s#@WITH_XPTR@#${WITH_XPTR}#g\"                               \\\n        -e \"s#@WITH_XINCLUDE@#${WITH_XINCLUDE}#g\"                       \\\n        -e \"s#@WITH_ICONV@#${WITH_ICONV}#g\"                             \\\n        -e \"s#@WITH_ICU@#${WITH_ICU}#g\"                                 \\\n        -e \"s#@WITH_ISO8859X@#${WITH_ISO8859X}#g\"                       \\\n        -e \"s#@WITH_DEBUG@#${WITH_DEBUG}#g\"                             \\\n        -e \"s#@WITH_MEM_DEBUG@#${WITH_MEM_DEBUG}#g\"                     \\\n        -e \"s#@WITH_RUN_DEBUG@#${WITH_RUN_DEBUG}#g\"                     \\\n        -e \"s#@WITH_REGEXPS@#${WITH_REGEXPS}#g\"                         \\\n        -e \"s#@WITH_SCHEMAS@#${WITH_SCHEMAS}#g\"                         \\\n        -e \"s#@WITH_SCHEMATRON@#${WITH_SCHEMATRON}#g\"                   \\\n        -e \"s#@WITH_MODULES@#${WITH_MODULES}#g\"                         \\\n        -e \"s#@WITH_ZLIB@#${WITH_ZLIB}#g\"                               \\\n        -e \"s#@WITH_LZMA@#${WITH_LZMA}#g\"\n}\n", "num_lines": 316}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Compilation script for the iconv names DFA builer.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/os400/iconv/bldcsndfa\"\n\n\n# This is for old XML library (bootstrapping).\n#rm -rf xml.h xml\n#ln -s /QSYS.LIB/XML.LIB/H.FILE/XML.MBR xml.h\n#mkdir xml\n#mkdir xml/h\n#ln -s /QSYS.LIB/XML.LIB/H.FILE/UTF8.MBR xml/h/utf8\n\n\n#       Compile.\n\nCMD=\"CRTCMOD MODULE(${TARGETLIB}/BLDCSNDFA) SRCSTMF('bldcsndfa.c')\"\nCMD=\"${CMD} SYSIFCOPT(*IFS64IO) LANGLVL(*EXTENDED) LOCALETYPE(*LOCALE)\"\nCMD=\"${CMD} INCDIR(\"\nCMD=\"${CMD} '${IFSDIR}/include' ${INCLUDES})\"\nCMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\nCMD=\"${CMD} OUTPUT(${OUTPUT})\"\nCMD=\"${CMD} OPTIMIZE(10)\"\nCMD=\"${CMD} DBGVIEW(${DEBUG})\"\n#CMD=\"${CMD} DEFINE('OLDXML' 'xmlXPathSetContextNode=xmlXPathSetCurrentNode')\"\n\nsystem \"${CMD}\"\n\n#       Link\n\nCMD=\"CRTPGM PGM(${TARGETLIB}/BLDCSNDFA) MODULE(${TARGETLIB}/BLDCSNDFA)\"\nCMD=\"${CMD} BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n#CMD=\"${CMD} BNDDIR(XML/XML)\"\nCMD=\"${CMD} TGTRLS(${TGTRLS})\"\nsystem \"${CMD}\"\n", "num_lines": 44}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Installation of the C header files in the OS/400 library.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/include\"\n\n\n#       Create the OS/400 source program file for the C header files.\n\nSRCPF=\"${LIBIFSNAME}/LIBXML.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/LIBXML) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: C/C++ header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the C header files.\n\nif action_needed \"${IFSDIR}/include/libxml\"\nthen    mkdir -p \"${IFSDIR}/include/libxml\"\nfi\n\n\n\n#       Enumeration values may be used as va_arg tagfields, so they MUST be\n#               integers.\n\ncopy_hfile()\n\n{\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n'\n}\n\n#       Copy the header files to DB2 library. Link from IFS include directory.\n\nfor HFILE in \"${TOPDIR}/os400/transcode.h\" libxml/*.h libxml/*.h.in\ndo      CMD=\"cat \\\"${HFILE}\\\"\"\n        DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\" nomangle`.MBR\"\n\n        case \"`basename \\\"${HFILE}\\\"`\" in\n\n        *.in)   CMD=\"${CMD} | versioned_copy\";;\n\n        xmlschemastypes.h)      #       Special case: rename colliding file.\n                DEST=\"${SRCPF}/SCHMTYPES.MBR\";;\n\n        esac\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    eval \"${CMD}\" | copy_hfile > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\n\n        IFSFILE=\"${IFSDIR}/include/libxml/`basename \\\"${HFILE}\\\" .in`\"\n\n        if action_needed \"${IFSFILE}\" \"${DEST}\"\n        then    rm -f \"${IFSFILE}\"\n                ln -s \"${DEST}\" \"${IFSFILE}\"\n        fi\ndone\n", "num_lines": 79}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       Installation of the ILE/RPG header files in the OS/400 library.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}/os400/libxmlrpg\"\n\n\n#       Create the OS/400 source program file for the ILE/RPG header files.\n\nSRCPF=\"${LIBIFSNAME}/LIBXMLRPG.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/LIBXMLRPG) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: ILE/RPG header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Map file names to DB2 name syntax.\n\nfor HFILE in *.rpgle *.rpgle.in\ndo      NAME=\"`basename \\\"${HFILE}\\\" .in`\"\n        VAR=\"`basename \\\"${NAME}\\\" .rpgle`\"\n        VAL=\"`db2_name \\\"${NAME}\\\" nomangle`\"\n\n        if [ \"${VAR}\" = 'xmlschemastypes' ]\n        then    VAL=SCHMTYPES\n        fi\n\n        eval \"VAR_${VAR}=\\\"${VAL}\\\"\"\n        echo \"${VAR} s/${VAR}/${VAL}/g\"\ndone > tmpsubstfile1\n\n#       Order substitution commands so that a prefix appears after all\n#               file names beginning with the prefix.\n\nsort -r tmpsubstfile1 | sed 's/^[^ ]*[ ]*//' > tmpsubstfile2\n\n\nchange_include()\n\n{\n        sed -e '\\#^....../include  *\"libxmlrpg/#{'                      \\\n            -e 's///'                                                   \\\n            -e 's/\".*//'                                                \\\n            -f tmpsubstfile2                                            \\\n            -e 's#.*#      /include libxmlrpg,&#'                       \\\n            -e '}'\n}\n\n\n#       Create the IFS directory for the ILE/RPG header files.\n\nRPGIFSDIR=\"${IFSDIR}/include/libxmlrpg\"\n\nif action_needed \"${RPGIFSDIR}\"\nthen    mkdir -p \"${RPGIFSDIR}\"\nfi\n\n#       Copy the header files to IFS ILE/RPG include directory.\n#       Copy them with include path editing to the DB2 library.\n\nfor HFILE in *.rpgle *.rpgle.in\ndo      IFSCMD=\"cat \\\"${HFILE}\\\"\"\n        DB2CMD=\"change_include < \\\"${HFILE}\\\"\"\n        IFSFILE=\"`basename \\\"${HFILE}\\\" .in`\"\n\n        case \"${HFILE}\" in\n\n        *.in)   IFSCMD=\"${IFSCMD} | versioned_copy\"\n                DB2CMD=\"${DB2CMD} | versioned_copy\"\n                ;;\n        esac\n\n        IFSDEST=\"${RPGIFSDIR}/${IFSFILE}\"\n\n        if action_needed \"${IFSDEST}\" \"${HFILE}\"\n        then    eval \"${IFSCMD}\" > \"${IFSDEST}\"\n        fi\n\n        eval DB2MBR=\"\\\"\\${VAR_`basename \\\"${IFSDEST}\\\" .rpgle`}\\\"\"\n        DB2DEST=\"${SRCPF}/${DB2MBR}.MBR\"\n\n        if action_needed \"${DB2DEST}\" \"${HFILE}\"\n        then    eval \"${DB2CMD}\" | change_include > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DB2DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n", "num_lines": 101}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       libxml compilation script for the OS/400.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"libxml2 version '\"${LIBXML_VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1998-2017 Daniel Veillard. OS/400 version by P. Monnerat.\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nfoldlines()\n\n{\n        sed -e ':begin'                                                 \\\n            -e '/\\\\$/{'                                                 \\\n            -e 's/\\\\$/ /'                                               \\\n            -e 'N'                                                      \\\n            -e 'bbegin'                                                 \\\n            -e '}'                                                      \\\n            -e 's/\\n//g'                                                \\\n            -e 's/[[:space:]]*$//'\n}\n\n\nget_make_var()\n\n{\n        foldlines < Makefile.am                                         |\n        sed -e \"/^${1}[[:space:]]*=[[:space:]]*/{\"                      \\\n            -e 's///'                                                   \\\n            -e 'q'                                                      \\\n            -e '}'                                                      \\\n            -e 'd'\n}\n\n\ndocb_sources=`get_make_var docb_sources`\ntrio_sources=`get_make_var trio_sources`\nCSOURCES=`eval echo \"\\`get_make_var libxml2_la_SOURCES | tr '()' '{}'\\`\"`\n\n\n#       Compile the sources into modules.\n\nINCLUDES=\"'`pwd`'\"\n\n#       OS/400 specific modules first.\n\nmake_module     --ebcdic        DLFCN           \"${SCRIPTDIR}/dlfcn/dlfcn.c\"\nmake_module     --ebcdic        ICONV           \"${SCRIPTDIR}/iconv/iconv.c\"\nmake_module     --ebcdic        WRAPPERS        \"${SCRIPTDIR}/wrappers.c\"\nmake_module                     TRANSCODE       \"${SCRIPTDIR}/transcode.c\"\nmake_module                     RPGSUPPORT      \"${SCRIPTDIR}/rpgsupport.c\"\n\n#       Regular libxml2 modules.\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('libxml2 static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('libxml2: build tools')\"\n        system \"${CMD}\"\nfi\n\n\n#       Generate all exported symbol table versions in a binding source file.\n\nBSF=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\nPGMEXPS=\n\nOS400SYMS=`cat os400/transcode.h os400/rpgsupport.h                     |\n           sed -e 'H'                                                   \\\n               -e 'g'                                                   \\\n               -e 's/\\n/ /'                                             \\\n               -e 's/\\\\$/ /'                                            \\\n               -e 's/.*/& /'                                            \\\n               -e 's/\\/\\*.*\\*\\// /g'                                    \\\n               -e 'h'                                                   \\\n               -e ':loop'                                               \\\n               -e 'g'                                                   \\\n               -e '/\\/\\*/d'                                             \\\n               -e '/;/!d'                                               \\\n               -e 's/[^;]*;//'                                          \\\n               -e 'x'                                                   \\\n               -e 's/[[:space:]]*;.*$//'                                \\\n               -e '/XMLPUBFUN/{'                                        \\\n               -e 's/[[:space:]]*(.*$//'                                \\\n               -e 's/.*[[:space:]*]//'                                  \\\n               -e 'p'                                                   \\\n               -e 'bloop'                                               \\\n               -e '}'                                                   \\\n               -e '/XMLPUBVAR/!bloop'                                   \\\n               -e ':loop2'                                              \\\n               -e '/\\[[^][]*\\]/{'                                       \\\n               -e 's///'                                                \\\n               -e 'bloop2'                                              \\\n               -e '}'                                                   \\\n               -e 's/[[:space:]]*,[[:space:]]*/,/g'                     \\\n               -e 's/[^,]*[[:space:]*]//'                               \\\n               -e 's/[^[:alnum:]_,]//g'                                 \\\n               -e 's/,/\\n/g'                                            \\\n               -e 'p'                                                   \\\n               -e 'bloop'`\n\nsed -e 's/#.*//'                                                        \\\n    -e 's/[[:space:]]*$//'                                              \\\n    -e 's/^[[:space:]]*//'                                              \\\n    -e '/^*global:$/d'                                                  \\\n    -e '/^$/d'                                                          \\\n    -e '/[[:space:]]*{$/{'                                              \\\n    -e   's///'                                                         \\\n    -e   'h'                                                            \\\n    -e   's/[^A-Za-z0-9]/_/g'                                           \\\n    -e   's/^[0-9]/_&/'                                                 \\\n    -e   'x'                                                            \\\n    -e   'G'                                                            \\\n    -e   's/\\(.*\\)\\n\\(.*\\)/\\2_SIGNATURE=\"\\1\"/'                          \\\n    -e   'p'                                                            \\\n    -e   's/.*//'                                                       \\\n    -e   'x'                                                            \\\n    -e   \"s/.*/SONAME='&'/\"                                             \\\n    -e   'b'                                                            \\\n    -e '}'                                                              \\\n    -e '/[[:space:]]*;$/!d'                                             \\\n    -e 's///'                                                           \\\n    -e '/^xmlDllMain$/d'                                                \\\n    -e '/^}[[:space:]]*/!{'                                             \\\n    -e   'H'                                                            \\\n    -e   'd'                                                            \\\n    -e '}'                                                              \\\n    -e 's///'                                                           \\\n    -e '/^$/!{'                                                         \\\n    -e   's/[^A-Za-z0-9]/_/g'                                           \\\n    -e   's/^[0-9]/_&/'                                                 \\\n    -e   's/.*/${&}/'                                                   \\\n    -e   'x'                                                            \\\n    -e   'H'                                                            \\\n    -e   's/.*//'                                                       \\\n    -e '}'                                                              \\\n    -e 'x'                                                              \\\n    -e 's/\\n/ /g'                                                       \\\n    -e 's/^[[:space:]]*//'                                              \\\n    -e 's/.*/declare ${SONAME}=\"&\"/'                                    \\\n    -e 's/.*/&; PGMEXPS=\"${SONAME} ${PGMEXPS}\"/'                        \\\n        < \"${TOPDIR}/libxml2.syms\"    > bndvars\n. ./bndvars\n\nPGMLVL=CURRENT\nfor PGMEXP in ${PGMEXPS}\ndo      SIGNATURE=`echo \"${PGMEXP}\" | sed 's/^LIBXML2_//'`\n        eval ENTRIES=\\\"\\${${PGMEXP}}\\\"\n        echo \" STRPGMEXP PGMLVL(*${PGMLVL}) SIGNATURE('${SIGNATURE}')\"\n        for ENTRY in ${ENTRIES} ${OS400SYMS}\n        do      echo \" EXPORT    SYMBOL('${ENTRY}')\"\n        done\n        echo ' ENDPGMEXP'\n        PGMLVL=PRV\ndone            > \"${BSF}\"\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD})\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS)\"\n        CMD=\"${CMD} TEXT('libxml2 dynamic library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('libxml2 dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n\n\n#       Compile the ASCII main() stub.\n\nmake_module     --ebcdic --sysiconv     LIBXMLMAIN  \"${SCRIPTDIR}/libxmlmain.c\"\n\n\n#       Compile and link program xmllint.\n\nif action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"xmllint.c\" ||\n   action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\" ||\n   action_needed \"${LIBIFSNAME}/XMLLINT.PGM\" \"${LIBIFSNAME}/LIBXMLMAIN.MODULE\"\nthen    make_module XMLLINT xmllint.c\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLLINT) MODULE(${TARGETLIB}/XMLLINT)\"\n        CMD=\"${CMD} ENTMOD(${TARGETLIB}/LIBXMLMAIN)\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS) BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD}) ACTGRP(*NEW) TEXT('XML tool')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLLINT.MODULE\"\nfi\n\n#       Install xmllint in IFS.\n\nif [ ! -d \"${IFSDIR}/bin\" ]\nthen    mkdir -p \"${IFSDIR}/bin\"\nfi\nrm -f \"${IFSDIR}/bin/xmllint\"\nln -s \"${LIBIFSNAME}/XMLLINT.PGM\" \"${IFSDIR}/bin/xmllint\"\n\n#       Prepare the XMLLINT command and its response program.\n\nif action_needed \"${LIBIFSNAME}/XMLLINTCL.PGM\" \"${SCRIPTDIR}/xmllintcl.c\"\nthen    make_module --ebcdic XMLLINTCL \"${SCRIPTDIR}/xmllintcl.c\"\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLLINTCL) MODULE(${TARGETLIB}/XMLLINTCL)\"\n        CMD=\"${CMD} ACTGRP(*NEW) TEXT('XMLLINT command response')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLLINTCL.MODULE\"\nfi\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR\"                 \\\n                 \"${SCRIPTDIR}/xmllint.cmd\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/xmllint.cmd')\"\n        CMD=\"${CMD} TOOBJ('${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\nif action_needed \"${LIBIFSNAME}/XMLLINT.CMD\"                            \\\n                 \"${LIBIFSNAME}/TOOLS.FILE/XMLLINT.MBR\"\nthen    CMD=\"CRTCMD CMD(${TARGETLIB}/XMLLINT) PGM(${TARGETLIB}/XMLLINTCL)\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(XMLLINT) THDSAFE(*YES)\"\n        CMD=\"${CMD} TEXT('XML tool') REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\n\n#       Compile and link program xmlcatalog.\n\nif action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\" \"xmlcatalog.c\" ||\n   action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\"                         \\\n                 \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\" ||\n   action_needed \"${LIBIFSNAME}/XMLCATALOG.PGM\"                         \\\n                 \"${LIBIFSNAME}/LIBXMLMAIN.MODULE\"\nthen    make_module XMLCATALOG xmlcatalog.c\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLCATALOG)\"\n        CMD=\"${CMD}  MODULE(${TARGETLIB}/XMLCATALOG)\"\n        CMD=\"${CMD} ENTMOD(${TARGETLIB}/LIBXMLMAIN)\"\n        CMD=\"${CMD} BNDSRVPGM(QADRTTS) BNDDIR((${TARGETLIB}/${STATBNDDIR})\"\n        if [ \"${WITH_ZLIB}\" -ne 0 ]\n        then    CMD=\"${CMD} (${ZLIB_LIB}/${ZLIB_BNDDIR})\"\n        fi\n        CMD=\"${CMD}) ACTGRP(*NEW) TEXT('XML/SGML catalog tool')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLCATALOG.MODULE\"\nfi\n\n#       Install xmlcatalog in IFS.\n\nrm -f \"${IFSDIR}/bin/xmlcatalog\"\nln -s \"${LIBIFSNAME}/XMLCATALOG.PGM\" \"${IFSDIR}/bin/xmlcatalog\"\n\n#       Prepare the XMLCATALOG command and its response program.\n\nif action_needed \"${LIBIFSNAME}/XMLCATLGCL.PGM\" \"${SCRIPTDIR}/xmlcatlgcl.c\"\nthen    make_module --ebcdic XMLCATLGCL \"${SCRIPTDIR}/xmlcatlgcl.c\"\n        CMD=\"CRTPGM PGM(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} ACTGRP(*NEW) TEXT('XMLCATALOG command response')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        rm -f \"${LIBIFSNAME}/XMLCATLGCL.MODULE\"\nfi\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR\"              \\\n                 \"${SCRIPTDIR}/xmlcatalog.cmd\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/xmlcatalog.cmd')\"\n        CMD=\"${CMD} TOOBJ('${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n\nif action_needed \"${LIBIFSNAME}/XMLCATALOG.CMD\"                         \\\n                 \"${LIBIFSNAME}/TOOLS.FILE/XMLCATALOG.MBR\"\nthen    CMD=\"CRTCMD CMD(${TARGETLIB}/XMLCATALOG) PGM(${TARGETLIB}/XMLCATLGCL)\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(XMLCATALOG)\"\n        CMD=\"${CMD} THDSAFE(*YES) TEXT('XML/SGML catalog tool') REPLACE(*YES)\"\n        system \"${CMD}\"\nfi\n", "num_lines": 356}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       libxml2 compilation script for the OS/400.\n#       This is a shell script since make is not a standard component of OS/400.\n#\n#       See Copyright for the status of this software.\n#\n#       Author: Patrick Monnerat <pm@datasphere.ch>, DATASPHERE S.A.\n#\n\nSCRIPTDIR=`dirname \"${0}\"`\n. \"${SCRIPTDIR}/initscript.sh\"\ncd \"${TOPDIR}\"\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB})\"\n        CMD=\"${CMD} TEXT('libxml2: XML parser and toolkit API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/AUTHORS\" \"${TOPDIR}/ChangeLog\"                   \\\n    \"${TOPDIR}/Copyright\" \"${TOPDIR}/CONTRIBUTING\" \"${TOPDIR}/README\"        \\\n    \"${TOPDIR}/MAINTAINERS\" \"${TOPDIR}/NEWS\" \"${TOPDIR}/TODO\"           \\\n    \"${TOPDIR}/TODO_SCHEMAS\" \"${TOPDIR}/os400/README400\"\ndo      if [ -f \"${TEXT}\" ]\n        then    MEMBER=\"`basename \\\"${TEXT}\\\" .OS400`\"\n                MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${MEMBER}\\\"`.MBR\"\n\n                if action_needed \"${MEMBER}\" \"${TEXT}\"\n                then    # Sources are in UTF-8.\n                        rm -f \"${TOPDIR}/tmpfile\"[12]\n                        CMD=\"CPY OBJ('${TEXT}') TOOBJ('${TOPDIR}/tmpfile1')\"\n                        CMD=\"${CMD} FROMCCSID(1208) TOCCSID(${TGTCCSID})\"\n                        CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                        system \"${CMD}\"\n                        # Make sure all lines are < 100 characters.\n                        sed -e 's/.\\{99\\}/&\\\n/g' -e 's/\\n$//' \"${TOPDIR}/tmpfile1\" > \"${TOPDIR}/tmpfile2\"\n                        CMD=\"CPY OBJ('${TOPDIR}/tmpfile2') TOOBJ('${MEMBER}')\"\n                        CMD=\"${CMD} TOCCSID(${TGTCCSID})\"\n                        CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                        system \"${CMD}\"\n                fi\n        fi\ndone\n\n\n#       Build files from template.\n\nconfigFile()\n\n{\n        args=`set | sed -e '/^[A-Za-z_][A-Za-z0-9_]*=/!d'               \\\n                        -e 's/[\\/\\\\\\\\&]/\\\\\\\\&/g'                        \\\n                        -e \"s/'/'\\\\\\\\\\\\''/g\"                            \\\n                        -e 's/^\\([^=]*\\)=\\(.*\\)$/-e '\\''s\\/@\\1@\\/\\2\\/g'\\'/`\n        eval sed ${args} < \"${1}\".in > \"${1}\"\n}\n\nconfigFile include/libxml/xmlversion.h\nconfigFile os400/os400config.h\nmv os400/os400config.h config.h\n\n\n#       Build in each directory.\n\nfor SUBDIR in include rpg src\ndo      \"${SCRIPTDIR}/make-${SUBDIR}.sh\"\ndone\n", "num_lines": 85}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "LIBXML2=$1\nTARGETCPU=$2\nTARGETTYPE=$3\n\nif [ -z \"$2\" ]; then\n\tTARGETCPU=SIMPENTIUMgnu\nfi\n\nif [ -z \"$3\" ]; then\n\tTARGETTYPE=RTP\nfi\n\necho \"LIBXML2 Version:     ${LIBXML2}\"\necho \"LIBXML2 Target CPU:  ${TARGETCPU}\"\necho \"LIBXML2 Target Type: ${TARGETTYPE}\"\n\nrm -fR src\ntar xvzf ${LIBXML2}.tar.gz\nmv ${LIBXML2} src\ncd src\n\n./configure --with-minimum --with-reader --with-writer --with-regexps --with-threads --with-thread-alloc\n\nfind . -name '*.in' -exec rm -fR {} +\nfind . -name '*.am' -exec rm -fR {} +\nrm -fR *.m4\nrm -fR *.pc\nrm -fR *.pl\nrm -fR *.py\nrm -fR *.spec\nrm -fR .deps\nrm -fR AUTHORS\nrm -fR bakefile\nrm -fR ChangeLog\nrm -fR config.guess\nrm -fR config.log\nrm -fR config.status\nrm -fR config.stub\nrm -fR config.sub\nrm -fR configure\nrm -fR COPYING\nrm -fR Copyright\nrm -fR depcomp\nrm -fR doc\nrm -fR example\nrm -fR INSTALL\nrm -fR install-sh\nrm -fR libxml.3\nrm -fR ltmain.sh\nrm -fR Makefile\nrm -fR Makefile.tests\nrm -fR macos\nrm -fR mkinstalldirs\nrm -fR missing\nrm -fR nanoftp.c\nrm -fR nanohttp.c\nrm -fR NEWS\nrm -fR python\nrm -fR README\nrm -fR README.tests\nrm -fR regressions.xml\nrm -fR result\nrm -fR runsuite.c\nrm -fR runtest.c\nrm -fR test\nrm -fR test*.c\nrm -fR TODO*\nrm -fR trio*\nrm -fR vms\nrm -fR win32\nrm -fR xml2*\nrm -fR xmllint.c\nrm -fR xstc\n\ncd ..\n\nmake clean all VXCPU=${TARGETCPU} VXTYPE=${TARGETTYPE}\n\nif [ \"${TARGETTYPE}\" = \"RTP\" ]; then\n\tcp libxml2.so ../../lib/.\nelse\n\tcp xml2.out ../../bin/.\nfi\n\ncp -R src/include/libxml ../../include/.", "num_lines": 85}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nOPENSSL=../../apps/openssl\nOPENSSL_CONF=../../apps/openssl.cnf\nexport OPENSSL_CONF\n\n# Root CA: create certificate directly\nCN=\"Test Root CA\" $OPENSSL req -config ca.cnf -x509 -nodes \\\n\t-keyout root.pem -out root.pem -newkey rsa:2048 -days 3650\n# Intermediate CA: request first\nCN=\"Test Intermediate CA\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout intkey.pem -out intreq.pem -newkey rsa:2048\n# Sign request: CA extensions\n$OPENSSL x509 -req -in intreq.pem -CA root.pem -days 3600 \\\n\t-extfile ca.cnf -extensions v3_ca -CAcreateserial -out intca.pem\n\n# Server certificate: create request first\nCN=\"Test Server Cert\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout skey.pem -out req.pem -newkey rsa:1024\n# Sign request: end entity extensions\n$OPENSSL x509 -req -in req.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial -out server.pem\n\n# Client certificate: request first\nCN=\"Test Client Cert\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout ckey.pem -out creq.pem -newkey rsa:1024\n# Sign using intermediate CA\n$OPENSSL x509 -req -in creq.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial -out client.pem\n\n# Revoked certificate: request first\nCN=\"Test Revoked Cert\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout revkey.pem -out rreq.pem -newkey rsa:1024\n# Sign using intermediate CA\n$OPENSSL x509 -req -in rreq.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial -out rev.pem\n\n# OCSP responder certificate: request first\nCN=\"Test OCSP Responder Cert\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout respkey.pem -out respreq.pem -newkey rsa:1024\n# Sign using intermediate CA and responder extensions\n$OPENSSL x509 -req -in respreq.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile ca.cnf -extensions ocsp_cert -CAcreateserial -out resp.pem\n\n# Example creating a PKCS#3 DH certificate.\n\n# First DH parameters\n\n[ -f dhp.pem ] || $OPENSSL genpkey -genparam -algorithm DH -pkeyopt dh_paramgen_prime_len:1024 -out dhp.pem\n\n# Now a DH private key\n$OPENSSL genpkey -paramfile dhp.pem -out dhskey.pem\n# Create DH public key file\n$OPENSSL pkey -in dhskey.pem -pubout -out dhspub.pem\n# Certificate request, key just reuses old one as it is ignored when the\n# request is signed.\nCN=\"Test Server DH Cert\" $OPENSSL req -config ca.cnf -new \\\n\t-key skey.pem -out dhsreq.pem\n# Sign request: end entity DH extensions\n$OPENSSL x509 -req -in dhsreq.pem -CA root.pem -days 3600 \\\n\t-force_pubkey dhspub.pem \\\n\t-extfile ca.cnf -extensions dh_cert -CAcreateserial -out dhserver.pem\n\n# DH client certificate\n\n$OPENSSL genpkey -paramfile dhp.pem -out dhckey.pem\n$OPENSSL pkey -in dhckey.pem -pubout -out dhcpub.pem\nCN=\"Test Client DH Cert\" $OPENSSL req -config ca.cnf -new \\\n\t-key skey.pem -out dhcreq.pem\n$OPENSSL x509 -req -in dhcreq.pem -CA root.pem -days 3600 \\\n\t-force_pubkey dhcpub.pem \\\n\t-extfile ca.cnf -extensions dh_cert -CAcreateserial -out dhclient.pem\n\n# Examples of CRL generation without the need to use 'ca' to issue\n# certificates.\n# Create zero length index file\n>index.txt\n# Create initial crl number file\necho 01 >crlnum.txt\n# Add entries for server and client certs\n$OPENSSL ca -valid server.pem -keyfile root.pem -cert root.pem \\\n\t\t-config ca.cnf -md sha1\n$OPENSSL ca -valid client.pem -keyfile root.pem -cert root.pem \\\n\t\t-config ca.cnf -md sha1\n$OPENSSL ca -valid rev.pem -keyfile root.pem -cert root.pem \\\n\t\t-config ca.cnf -md sha1\n# Generate a CRL.\n$OPENSSL ca -gencrl -keyfile root.pem -cert root.pem -config ca.cnf \\\n\t\t-md sha1 -crldays 1 -out crl1.pem\n# Revoke a certificate\nopenssl ca -revoke rev.pem -crl_reason superseded \\\n\t\t-keyfile root.pem -cert root.pem -config ca.cnf -md sha1\n# Generate another CRL\n$OPENSSL ca -gencrl -keyfile root.pem -cert root.pem -config ca.cnf \\\n\t\t-md sha1 -crldays 1 -out crl2.pem\n\n", "num_lines": 97}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Example querying OpenSSL test responder. Assumes ocsprun.sh has been\n# called.\n\nOPENSSL=../../apps/openssl\nOPENSSL_CONF=../../apps/openssl.cnf\nexport OPENSSL_CONF\n\n# Send responder queries for each certificate.\n\necho \"Requesting OCSP status for each certificate\"\n$OPENSSL ocsp -issuer intca.pem -cert client.pem -CAfile root.pem \\\n\t\t\t-url http://127.0.0.1:8888/\n$OPENSSL ocsp -issuer intca.pem -cert server.pem -CAfile root.pem \\\n\t\t\t-url http://127.0.0.1:8888/\n$OPENSSL ocsp -issuer intca.pem -cert rev.pem -CAfile root.pem \\\n\t\t\t-url http://127.0.0.1:8888/\n# One query for all three certificates.\necho \"Requesting OCSP status for three certificates in one request\"\n$OPENSSL ocsp -issuer intca.pem \\\n\t-cert client.pem -cert server.pem -cert rev.pem \\\n\t-CAfile root.pem -url http://127.0.0.1:8888/\n", "num_lines": 22}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Example of running an querying OpenSSL test OCSP responder.\n# This assumes \"mkcerts.sh\" or similar has been run to set up the\n# necessary file structure.\n\nOPENSSL=../../apps/openssl\nOPENSSL_CONF=../../apps/openssl.cnf\nexport OPENSSL_CONF\n\n# Run OCSP responder.\n\nPORT=8888\n\n$OPENSSL ocsp -port $PORT -index index.txt -CA intca.pem \\\n\t-rsigner resp.pem -rkey respkey.pem -rother intca.pem $*\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Recreate the demo certificates in the apps directory.\n\nOPENSSL=openssl\n\n# Root CA: create certificate directly\nCN=\"OpenSSL Test Root CA\" $OPENSSL req -config apps.cnf -x509 -nodes \\\n\t-keyout root.pem -out root.pem -key rootkey.pem -new -days 3650\n# Intermediate CA: request first\nCN=\"OpenSSL Test Intermediate CA\" $OPENSSL req -config apps.cnf -nodes \\\n\t-key intkey.pem -out intreq.pem -new\n# Sign request: CA extensions\n$OPENSSL x509 -req -in intreq.pem -CA root.pem -CAkey rootkey.pem -days 3630 \\\n\t-extfile apps.cnf -extensions v3_ca -CAcreateserial -out intca.pem\n# Client certificate: request first\nCN=\"Test Client Cert\" $OPENSSL req -config apps.cnf -nodes \\\n\t-key ckey.pem -out creq.pem -new\n# Sign using intermediate CA\n$OPENSSL x509 -req -in creq.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile apps.cnf -extensions usr_cert -CAcreateserial | \\\n\t$OPENSSL x509 -nameopt oneline -subject -issuer >client.pem\n# Server certificate: request first\nCN=\"Test Server Cert\" $OPENSSL req -config apps.cnf -nodes \\\n\t-key skey.pem -out sreq.pem -new\n# Sign using intermediate CA\n$OPENSSL x509 -req -in sreq.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile apps.cnf -extensions usr_cert -CAcreateserial | \\\n\t$OPENSSL x509 -nameopt oneline -subject -issuer >server.pem\n# Server certificate #2: request first\nCN=\"Test Server Cert #2\" $OPENSSL req -config apps.cnf -nodes \\\n\t-key skey2.pem -out sreq2.pem -new\n# Sign using intermediate CA\n$OPENSSL x509 -req -in sreq2.pem -CA intca.pem -CAkey intkey.pem -days 3600 \\\n\t-extfile apps.cnf -extensions usr_cert -CAcreateserial | \\\n\t$OPENSSL x509 -nameopt oneline -subject -issuer >server2.pem\n\n# Append keys to file.\n\ncat skey.pem >>server.pem\ncat skey2.pem >>server2.pem\ncat ckey.pem >>client.pem\n\n$OPENSSL verify -CAfile root.pem -untrusted intca.pem \\\n\t\t\t\tserver2.pem server.pem client.pem\n", "num_lines": 46}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n# Create certificates using various algorithms to test multi-certificate\n# functionality.\n\nOPENSSL=../../../apps/openssl\nCN=\"OpenSSL Test RSA SHA-1 cert\" $OPENSSL req \\\n\t-config apps.cnf -extensions usr_cert -x509 -nodes \\\n\t-keyout tsha1.pem -out tsha1.pem -new -days 3650 -sha1\nCN=\"OpenSSL Test RSA SHA-256 cert\" $OPENSSL req \\\n\t-config apps.cnf -extensions usr_cert -x509 -nodes \\\n\t-keyout tsha256.pem -out tsha256.pem -new -days 3650 -sha256\nCN=\"OpenSSL Test RSA SHA-512 cert\" $OPENSSL req \\\n\t-config apps.cnf -extensions usr_cert -x509 -nodes \\\n\t-keyout tsha512.pem -out tsha512.pem -new -days 3650 -sha512\n\n# Create EC parameters\n\n$OPENSSL ecparam -name P-256 -out ecp256.pem\n$OPENSSL ecparam -name P-384 -out ecp384.pem\n\nCN=\"OpenSSL Test P-256 SHA-256 cert\" $OPENSSL req \\\n\t-config apps.cnf -extensions ec_cert -x509 -nodes \\\n\t-nodes -keyout tecp256.pem -out tecp256.pem -newkey ec:ecp256.pem \\\n\t-days 3650 -sha256\n\nCN=\"OpenSSL Test P-384 SHA-384 cert\" $OPENSSL req \\\n\t-config apps.cnf -extensions ec_cert -x509 -nodes \\\n\t-nodes -keyout tecp384.pem -out tecp384.pem -newkey ec:ecp384.pem \\\n\t-days 3650 -sha384\n", "num_lines": 30}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -ex\n#\n# Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.\n#\n# Licensed under the OpenSSL license (the \"License\").  You may not use\n# this file except in compliance with the License.  You can obtain a copy\n# in the file LICENSE in the source distribution or at\n# https://www.openssl.org/source/license.html\n\n# krb5's test suite clears LD_LIBRARY_PATH\nLDFLAGS=\"-L`pwd`/$BLDTOP -Wl,-rpath,`pwd`/$BLDTOP\"\nCFLAGS=\"-I`pwd`/$BLDTOP/include -I`pwd`/$SRCTOP/include\"\n\ncd $SRCTOP/krb5/src\nautoreconf\n./configure --with-ldap --with-prng-alg=os --enable-pkinit \\\n            --with-crypto-impl=openssl --with-tls-impl=openssl \\\n            CFLAGS=\"$CFLAGS\" LDFLAGS=\"$LDFLAGS\"\n\n# quiet make so that Travis doesn't overflow\nmake -s\n\nmake check\n", "num_lines": 24}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n# Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.\n# Copyright (c) 2017, Oracle and/or its affiliates.  All rights reserved.\n#\n# Licensed under the OpenSSL license (the \"License\").  You may not use\n# this file except in compliance with the License.  You can obtain a copy\n# in the file LICENSE in the source distribution or at\n# https://www.openssl.org/source/license.html\n\n#\n# OpenSSL external testing using the Python Cryptography module\n#\nset -e\n\nO_EXE=`pwd`/$BLDTOP/apps\nO_BINC=`pwd`/$BLDTOP/include\nO_SINC=`pwd`/$SRCTOP/include\nO_LIB=`pwd`/$BLDTOP\n\nexport PATH=$O_EXE:$PATH\nexport LD_LIBRARY_PATH=$O_LIB:$LD_LIBRARY_PATH\n\n# Check/Set openssl version\nOPENSSL_VERSION=`openssl version | cut -f 2 -d ' '`\n\necho \"------------------------------------------------------------------\"\necho \"Testing OpenSSL using Python Cryptography:\"\necho \"   CWD:                $PWD\"\necho \"   SRCTOP:             $SRCTOP\"\necho \"   BLDTOP:             $BLDTOP\"\necho \"   OpenSSL version:    $OPENSSL_VERSION\"\necho \"------------------------------------------------------------------\"\n\ncd $SRCTOP\n\n# Create a python virtual env and activate\nrm -rf venv-pycrypto\nvirtualenv venv-pycrypto\n. ./venv-pycrypto/bin/activate\n\ncd pyca-cryptography\n\npip install .[test]\n\necho \"------------------------------------------------------------------\"\necho \"Building cryptography\"\necho \"------------------------------------------------------------------\"\npython ./setup.py clean\n\nCFLAGS=\"-I$O_BINC -I$O_SINC -L$O_LIB\" python ./setup.py build\n\necho \"------------------------------------------------------------------\"\necho \"Running tests\"\necho \"------------------------------------------------------------------\"\n\nCFLAGS=\"-I$O_BINC -I$O_SINC -L$O_LIB\" python ./setup.py test\n\ncd ../\ndeactivate\nrm -rf venv-pycrypto\n\nexit 0\n\n", "num_lines": 65}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2013-2016 The OpenSSL Project Authors. All Rights Reserved.\n#\n# Licensed under the OpenSSL license (the \"License\").  You may not use\n# this file except in compliance with the License.  You can obtain a copy\n# in the file LICENSE in the source distribution or at\n# https://www.openssl.org/source/license.html\n\n\n# Utility to recreate S/MIME certificates\n\nOPENSSL=../../apps/openssl\nOPENSSL_CONF=./ca.cnf\nexport OPENSSL_CONF\n\n# Root CA: create certificate directly\nCN=\"Test S/MIME RSA Root\" $OPENSSL req -config ca.cnf -x509 -nodes \\\n\t-keyout smroot.pem -out smroot.pem -newkey rsa:2048 -days 3650\n\n# EE RSA certificates: create request first\nCN=\"Test S/MIME EE RSA #1\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smrsa1.pem -out req.pem -newkey rsa:2048\n# Sign request: end entity extensions\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smrsa1.pem\n\nCN=\"Test S/MIME EE RSA #2\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smrsa2.pem -out req.pem -newkey rsa:2048\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smrsa2.pem\n\nCN=\"Test S/MIME EE RSA #3\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smrsa3.pem -out req.pem -newkey rsa:2048\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smrsa3.pem\n\n# Create DSA parameters\n\n$OPENSSL dsaparam -out dsap.pem 2048\n\nCN=\"Test S/MIME EE DSA #1\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smdsa1.pem -out req.pem -newkey dsa:dsap.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smdsa1.pem\nCN=\"Test S/MIME EE DSA #2\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smdsa2.pem -out req.pem -newkey dsa:dsap.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smdsa2.pem\nCN=\"Test S/MIME EE DSA #3\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smdsa3.pem -out req.pem -newkey dsa:dsap.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smdsa3.pem\n\n# Create EC parameters\n\n$OPENSSL ecparam -out ecp.pem -name P-256\n$OPENSSL ecparam -out ecp2.pem -name K-283\n\nCN=\"Test S/MIME EE EC #1\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smec1.pem -out req.pem -newkey ec:ecp.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smec1.pem\nCN=\"Test S/MIME EE EC #2\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smec2.pem -out req.pem -newkey ec:ecp2.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smec2.pem\nCN=\"Test S/MIME EE EC #3\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smec3.pem -out req.pem -newkey ec:ecp.pem\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smec3.pem\n# Create X9.42 DH parameters.\n$OPENSSL genpkey -genparam -algorithm DH -pkeyopt dh_paramgen_type:2 \\\n\t-out dhp.pem\n# Generate X9.42 DH key.\n$OPENSSL genpkey -paramfile dhp.pem -out smdh.pem\n$OPENSSL pkey -pubout -in smdh.pem -out dhpub.pem\n# Generate dummy request.\nCN=\"Test S/MIME EE DH #1\" $OPENSSL req -config ca.cnf -nodes \\\n\t-keyout smtmp.pem -out req.pem -newkey rsa:2048\n# Sign request but force public key to DH\n$OPENSSL x509 -req -in req.pem -CA smroot.pem -days 3600 \\\n\t-force_pubkey dhpub.pem \\\n\t-extfile ca.cnf -extensions usr_cert -CAcreateserial >>smdh.pem\n# Remove temp files.\nrm -f req.pem ecp.pem ecp2.pem dsap.pem dhp.pem dhpub.pem smtmp.pem smroot.srl\n", "num_lines": 86}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nHERE=\"`echo $0 | sed -e 's|[^/]*$||'`\"\nOPENSSL=\"${HERE}../apps/openssl\"\n\nif [ -d \"${HERE}../engines\" -a \"x$OPENSSL_ENGINES\" = \"x\" ]; then\n\tOPENSSL_ENGINES=\"${HERE}../engines\"; export OPENSSL_ENGINES\nfi\n\nif [ -x \"${OPENSSL}.exe\" ]; then\n\t# The original reason for this script existence is to work around\n\t# certain caveats in run-time linker behaviour. On Windows platforms\n\t# adjusting $PATH used to be sufficient, but with introduction of\n\t# SafeDllSearchMode in XP/2003 the only way to get it right in\n\t# *all* possible situations is to copy newly built .DLLs to apps/\n\t# and test/, which is now done elsewhere... The $PATH is adjusted\n\t# for backward compatibility (and nostagical reasons:-).\n\tif [ \"$OSTYPE\" != msdosdjgpp ]; then\n\t\tPATH=\"${HERE}..:$PATH\"; export PATH\n\tfi\n\texec \"${OPENSSL}.exe\" \"$@\"\nelif [ -x \"${OPENSSL}\" -a -x \"${HERE}shlib_wrap.sh\" ]; then\n\texec \"${HERE}shlib_wrap.sh\" \"${OPENSSL}\" \"$@\"\nelse\n\texec \"${OPENSSL}\" \"$@\"\t# hope for the best...\nfi\n", "num_lines": 27}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n## DO NOT EDIT - This file generated from ./build-aux/ltmain.in\n##               by inline-source v2014-01-03.01\n\n# libtool (GNU libtool) 2.4.6\n# Provide generalized library-building support services.\n# Written by Gordon Matzigkeit <gord@gnu.ai.mit.edu>, 1996\n\n# Copyright (C) 1996-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# GNU Libtool is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 2 of the License, or\n# (at your option) any later version.\n#\n# As a special exception to the GNU General Public License,\n# if you distribute this file as part of a program or library that\n# is built using GNU Libtool, you may include this file under the\n# same distribution terms that you use for the rest of that program.\n#\n# GNU Libtool is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n\nPROGRAM=libtool\nPACKAGE=libtool\nVERSION=\"2.4.6 Debian-2.4.6-2\"\npackage_revision=2.4.6\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Run './libtool --help' for help with using this script from the\n# command line.\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# After configure completes, it has a better idea of some of the\n# shell tools we need than the defaults used by the functions shared\n# with bootstrap, so set those here where they can still be over-\n# ridden by the user, but otherwise take precedence.\n\n: ${AUTOCONF=\"autoconf\"}\n: ${AUTOMAKE=\"automake\"}\n\n\n## -------------------------- ##\n## Source external libraries. ##\n## -------------------------- ##\n\n# Much of our low-level functionality needs to be sourced from external\n# libraries, which are installed to $pkgauxdir.\n\n# Set a version string for this script.\nscriptversion=2015-01-20.17; # UTC\n\n# General shell script boiler plate, and helper functions.\n# Written by Gary V. Vaughan, 2004\n\n# Copyright (C) 2004-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software; you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation; either version 3 of the License, or\n# (at your option) any later version.\n\n# As a special exception to the GNU General Public License, if you distribute\n# this file as part of a program or library that is built using GNU Libtool,\n# you may include this file under the same distribution terms that you use\n# for the rest of that program.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNES FOR A PARTICULAR PURPOSE. See the GNU\n# General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# Evaluate this file near the top of your script to gain access to\n# the functions and variables defined here:\n#\n#   . `echo \"$0\" | ${SED-sed} 's|[^/]*$||'`/build-aux/funclib.sh\n#\n# If you need to override any of the default environment variable\n# settings, do that before evaluating this file.\n\n\n## -------------------- ##\n## Shell normalisation. ##\n## -------------------- ##\n\n# Some shells need a little help to be as Bourne compatible as possible.\n# Before doing anything else, make sure all that help has been provided!\n\nDUALCASE=1; export DUALCASE # for MKS sh\nif test -n \"${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then :\n  emulate sh\n  NULLCMD=:\n  # Pre-4.2 versions of Zsh do word splitting on ${1+\"$@\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '${1+\"$@\"}'='\"$@\"'\n  setopt NO_GLOB_SUBST\nelse\n  case `(set -o) 2>/dev/null` in *posix*) set -o posix ;; esac\nfi\n\n# NLS nuisances: We save the old values in case they are required later.\n_G_user_locale=\n_G_safe_locale=\nfor _G_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\ndo\n  eval \"if test set = \\\"\\${$_G_var+set}\\\"; then\n          save_$_G_var=\\$$_G_var\n          $_G_var=C\n\t  export $_G_var\n\t  _G_user_locale=\\\"$_G_var=\\\\\\$save_\\$_G_var; \\$_G_user_locale\\\"\n\t  _G_safe_locale=\\\"$_G_var=C; \\$_G_safe_locale\\\"\n\tfi\"\ndone\n\n# CDPATH.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\n# Make sure IFS has a sensible default\nsp=' '\nnl='\n'\nIFS=\"$sp\t$nl\"\n\n# There are apparently some retarded systems that use ';' as a PATH separator!\nif test \"${PATH_SEPARATOR+set}\" != set; then\n  PATH_SEPARATOR=:\n  (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && {\n    (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 ||\n      PATH_SEPARATOR=';'\n  }\nfi\n\n\n\n## ------------------------- ##\n## Locate command utilities. ##\n## ------------------------- ##\n\n\n# func_executable_p FILE\n# ----------------------\n# Check that FILE is an executable regular file.\nfunc_executable_p ()\n{\n    test -f \"$1\" && test -x \"$1\"\n}\n\n\n# func_path_progs PROGS_LIST CHECK_FUNC [PATH]\n# --------------------------------------------\n# Search for either a program that responds to --version with output\n# containing \"GNU\", or else returned by CHECK_FUNC otherwise, by\n# trying all the directories in PATH with each of the elements of\n# PROGS_LIST.\n#\n# CHECK_FUNC should accept the path to a candidate program, and\n# set $func_check_prog_result if it truncates its output less than\n# $_G_path_prog_max characters.\nfunc_path_progs ()\n{\n    _G_progs_list=$1\n    _G_check_func=$2\n    _G_PATH=${3-\"$PATH\"}\n\n    _G_path_prog_max=0\n    _G_path_prog_found=false\n    _G_save_IFS=$IFS; IFS=${PATH_SEPARATOR-:}\n    for _G_dir in $_G_PATH; do\n      IFS=$_G_save_IFS\n      test -z \"$_G_dir\" && _G_dir=.\n      for _G_prog_name in $_G_progs_list; do\n        for _exeext in '' .EXE; do\n          _G_path_prog=$_G_dir/$_G_prog_name$_exeext\n          func_executable_p \"$_G_path_prog\" || continue\n          case `\"$_G_path_prog\" --version 2>&1` in\n            *GNU*) func_path_progs_result=$_G_path_prog _G_path_prog_found=: ;;\n            *)     $_G_check_func $_G_path_prog\n\t\t   func_path_progs_result=$func_check_prog_result\n\t\t   ;;\n          esac\n          $_G_path_prog_found && break 3\n        done\n      done\n    done\n    IFS=$_G_save_IFS\n    test -z \"$func_path_progs_result\" && {\n      echo \"no acceptable sed could be found in \\$PATH\" >&2\n      exit 1\n    }\n}\n\n\n# We want to be able to use the functions in this file before configure\n# has figured out where the best binaries are kept, which means we have\n# to search for them ourselves - except when the results are already set\n# where we skip the searches.\n\n# Unless the user overrides by setting SED, search the path for either GNU\n# sed, or the sed that truncates its output the least.\ntest -z \"$SED\" && {\n  _G_sed_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/\n  for _G_i in 1 2 3 4 5 6 7; do\n    _G_sed_script=$_G_sed_script$nl$_G_sed_script\n  done\n  echo \"$_G_sed_script\" 2>/dev/null | sed 99q >conftest.sed\n  _G_sed_script=\n\n  func_check_prog_sed ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo '' >> conftest.nl\n      \"$_G_path_prog\" -f conftest.sed <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"sed gsed\" func_check_prog_sed $PATH:/usr/xpg4/bin\n  rm -f conftest.sed\n  SED=$func_path_progs_result\n}\n\n\n# Unless the user overrides by setting GREP, search the path for either GNU\n# grep, or the grep that truncates its output the least.\ntest -z \"$GREP\" && {\n  func_check_prog_grep ()\n  {\n    _G_path_prog=$1\n\n    _G_count=0\n    _G_path_prog_max=0\n    printf 0123456789 >conftest.in\n    while :\n    do\n      cat conftest.in conftest.in >conftest.tmp\n      mv conftest.tmp conftest.in\n      cp conftest.in conftest.nl\n      echo 'GREP' >> conftest.nl\n      \"$_G_path_prog\" -e 'GREP$' -e '-(cannot match)-' <conftest.nl >conftest.out 2>/dev/null || break\n      diff conftest.out conftest.nl >/dev/null 2>&1 || break\n      _G_count=`expr $_G_count + 1`\n      if test \"$_G_count\" -gt \"$_G_path_prog_max\"; then\n        # Best one so far, save it but keep looking for a better one\n        func_check_prog_result=$_G_path_prog\n        _G_path_prog_max=$_G_count\n      fi\n      # 10*(2^10) chars as input seems more than enough\n      test 10 -lt \"$_G_count\" && break\n    done\n    rm -f conftest.in conftest.tmp conftest.nl conftest.out\n  }\n\n  func_path_progs \"grep ggrep\" func_check_prog_grep $PATH:/usr/xpg4/bin\n  GREP=$func_path_progs_result\n}\n\n\n## ------------------------------- ##\n## User overridable command paths. ##\n## ------------------------------- ##\n\n# All uppercase variable names are used for environment variables.  These\n# variables can be overridden by the user before calling a script that\n# uses them if a suitable command of that name is not already available\n# in the command search PATH.\n\n: ${CP=\"cp -f\"}\n: ${ECHO=\"printf %s\\n\"}\n: ${EGREP=\"$GREP -E\"}\n: ${FGREP=\"$GREP -F\"}\n: ${LN_S=\"ln -s\"}\n: ${MAKE=\"make\"}\n: ${MKDIR=\"mkdir\"}\n: ${MV=\"mv -f\"}\n: ${RM=\"rm -f\"}\n: ${SHELL=\"${CONFIG_SHELL-/bin/sh}\"}\n\n\n## -------------------- ##\n## Useful sed snippets. ##\n## -------------------- ##\n\nsed_dirname='s|/[^/]*$||'\nsed_basename='s|^.*/||'\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='s|\\([`\"$\\\\]\\)|\\\\\\1|g'\n\n# Same as above, but do not quote variable references.\nsed_double_quote_subst='s/\\([\"`\\\\]\\)/\\\\\\1/g'\n\n# Sed substitution that turns a string into a regex matching for the\n# string literally.\nsed_make_literal_regex='s|[].[^$\\\\*\\/]|\\\\&|g'\n\n# Sed substitution that converts a w32 file name or path\n# that contains forward slashes, into one that contains\n# (escaped) backslashes.  A very naive implementation.\nsed_naive_backslashify='s|\\\\\\\\*|\\\\|g;s|/|\\\\|g;s|\\\\|\\\\\\\\|g'\n\n# Re-'\\' parameter expansions in output of sed_double_quote_subst that\n# were '\\'-ed in input to the same.  If an odd number of '\\' preceded a\n# '$' in input to sed_double_quote_subst, that '$' was protected from\n# expansion.  Since each input '\\' is now two '\\'s, look for any number\n# of runs of four '\\'s followed by two '\\'s and then a '$'.  '\\' that '$'.\n_G_bs='\\\\'\n_G_bs2='\\\\\\\\'\n_G_bs4='\\\\\\\\\\\\\\\\'\n_G_dollar='\\$'\nsed_double_backslash=\"\\\n  s/$_G_bs4/&\\\\\n/g\n  s/^$_G_bs2$_G_dollar/$_G_bs&/\n  s/\\\\([^$_G_bs]\\\\)$_G_bs2$_G_dollar/\\\\1$_G_bs2$_G_bs$_G_dollar/g\n  s/\\n//g\"\n\n\n## ----------------- ##\n## Global variables. ##\n## ----------------- ##\n\n# Except for the global variables explicitly listed below, the following\n# functions in the '^func_' namespace, and the '^require_' namespace\n# variables initialised in the 'Resource management' section, sourcing\n# this file will not pollute your global namespace with anything\n# else. There's no portable way to scope variables in Bourne shell\n# though, so actually running these functions will sometimes place\n# results into a variable named after the function, and often use\n# temporary variables in the '^_G_' namespace. If you are careful to\n# avoid using those namespaces casually in your sourcing script, things\n# should continue to work as you expect. And, of course, you can freely\n# overwrite any of the functions or variables defined here before\n# calling anything to customize them.\n\nEXIT_SUCCESS=0\nEXIT_FAILURE=1\nEXIT_MISMATCH=63  # $? = 63 is used to indicate version mismatch to missing.\nEXIT_SKIP=77\t  # $? = 77 is used to indicate a skipped test to automake.\n\n# Allow overriding, eg assuming that you follow the convention of\n# putting '$debug_cmd' at the start of all your functions, you can get\n# bash to show function call trace with:\n#\n#    debug_cmd='eval echo \"${FUNCNAME[0]} $*\" >&2' bash your-script-name\ndebug_cmd=${debug_cmd-\":\"}\nexit_cmd=:\n\n# By convention, finish your script with:\n#\n#    exit $exit_status\n#\n# so that you can set exit_status to non-zero if you want to indicate\n# something went wrong during execution without actually bailing out at\n# the point of failure.\nexit_status=$EXIT_SUCCESS\n\n# Work around backward compatibility issue on IRIX 6.5. On IRIX 6.4+, sh\n# is ksh but when the shell is invoked as \"sh\" and the current value of\n# the _XPG environment variable is not equal to 1 (one), the special\n# positional parameter $0, within a function call, is the name of the\n# function.\nprogpath=$0\n\n# The name of this program.\nprogname=`$ECHO \"$progpath\" |$SED \"$sed_basename\"`\n\n# Make sure we have an absolute progpath for reexecution:\ncase $progpath in\n  [\\\\/]*|[A-Za-z]:\\\\*) ;;\n  *[\\\\/]*)\n     progdir=`$ECHO \"$progpath\" |$SED \"$sed_dirname\"`\n     progdir=`cd \"$progdir\" && pwd`\n     progpath=$progdir/$progname\n     ;;\n  *)\n     _G_IFS=$IFS\n     IFS=${PATH_SEPARATOR-:}\n     for progdir in $PATH; do\n       IFS=$_G_IFS\n       test -x \"$progdir/$progname\" && break\n     done\n     IFS=$_G_IFS\n     test -n \"$progdir\" || progdir=`pwd`\n     progpath=$progdir/$progname\n     ;;\nesac\n\n\n## ----------------- ##\n## Standard options. ##\n## ----------------- ##\n\n# The following options affect the operation of the functions defined\n# below, and should be set appropriately depending on run-time para-\n# meters passed on the command line.\n\nopt_dry_run=false\nopt_quiet=false\nopt_verbose=false\n\n# Categories 'all' and 'none' are always available.  Append any others\n# you will pass as the first argument to func_warning from your own\n# code.\nwarning_categories=\n\n# By default, display warnings according to 'opt_warning_types'.  Set\n# 'warning_func'  to ':' to elide all warnings, or func_fatal_error to\n# treat the next displayed warning as a fatal error.\nwarning_func=func_warn_and_continue\n\n# Set to 'all' to display all warnings, 'none' to suppress all\n# warnings, or a space delimited list of some subset of\n# 'warning_categories' to display only the listed warnings.\nopt_warning_types=all\n\n\n## -------------------- ##\n## Resource management. ##\n## -------------------- ##\n\n# This section contains definitions for functions that each ensure a\n# particular resource (a file, or a non-empty configuration variable for\n# example) is available, and if appropriate to extract default values\n# from pertinent package files. Call them using their associated\n# 'require_*' variable to ensure that they are executed, at most, once.\n#\n# It's entirely deliberate that calling these functions can set\n# variables that don't obey the namespace limitations obeyed by the rest\n# of this file, in order that that they be as useful as possible to\n# callers.\n\n\n# require_term_colors\n# -------------------\n# Allow display of bold text on terminals that support it.\nrequire_term_colors=func_require_term_colors\nfunc_require_term_colors ()\n{\n    $debug_cmd\n\n    test -t 1 && {\n      # COLORTERM and USE_ANSI_COLORS environment variables take\n      # precedence, because most terminfo databases neglect to describe\n      # whether color sequences are supported.\n      test -n \"${COLORTERM+set}\" && : ${USE_ANSI_COLORS=\"1\"}\n\n      if test 1 = \"$USE_ANSI_COLORS\"; then\n        # Standard ANSI escape sequences\n        tc_reset='\u001b[0m'\n        tc_bold='\u001b[1m';   tc_standout='\u001b[7m'\n        tc_red='\u001b[31m';   tc_green='\u001b[32m'\n        tc_blue='\u001b[34m';  tc_cyan='\u001b[36m'\n      else\n        # Otherwise trust the terminfo database after all.\n        test -n \"`tput sgr0 2>/dev/null`\" && {\n          tc_reset=`tput sgr0`\n          test -n \"`tput bold 2>/dev/null`\" && tc_bold=`tput bold`\n          tc_standout=$tc_bold\n          test -n \"`tput smso 2>/dev/null`\" && tc_standout=`tput smso`\n          test -n \"`tput setaf 1 2>/dev/null`\" && tc_red=`tput setaf 1`\n          test -n \"`tput setaf 2 2>/dev/null`\" && tc_green=`tput setaf 2`\n          test -n \"`tput setaf 4 2>/dev/null`\" && tc_blue=`tput setaf 4`\n          test -n \"`tput setaf 5 2>/dev/null`\" && tc_cyan=`tput setaf 5`\n        }\n      fi\n    }\n\n    require_term_colors=:\n}\n\n\n## ----------------- ##\n## Function library. ##\n## ----------------- ##\n\n# This section contains a variety of useful functions to call in your\n# scripts. Take note of the portable wrappers for features provided by\n# some modern shells, which will fall back to slower equivalents on\n# less featureful shells.\n\n\n# func_append VAR VALUE\n# ---------------------\n# Append VALUE onto the existing contents of VAR.\n\n  # We should try to minimise forks, especially on Windows where they are\n  # unreasonably slow, so skip the feature probes when bash or zsh are\n  # being used:\n  if test set = \"${BASH_VERSION+set}${ZSH_VERSION+set}\"; then\n    : ${_G_HAVE_ARITH_OP=\"yes\"}\n    : ${_G_HAVE_XSI_OPS=\"yes\"}\n    # The += operator was introduced in bash 3.1\n    case $BASH_VERSION in\n      [12].* | 3.0 | 3.0*) ;;\n      *)\n        : ${_G_HAVE_PLUSEQ_OP=\"yes\"}\n        ;;\n    esac\n  fi\n\n  # _G_HAVE_PLUSEQ_OP\n  # Can be empty, in which case the shell is probed, \"yes\" if += is\n  # useable or anything else if it does not work.\n  test -z \"$_G_HAVE_PLUSEQ_OP\" \\\n    && (eval 'x=a; x+=\" b\"; test \"a b\" = \"$x\"') 2>/dev/null \\\n    && _G_HAVE_PLUSEQ_OP=yes\n\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1+=\\$2\"\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_append ()\n  {\n    $debug_cmd\n\n    eval \"$1=\\$$1\\$2\"\n  }\nfi\n\n\n# func_append_quoted VAR VALUE\n# ----------------------------\n# Quote VALUE and append to the end of shell variable VAR, separated\n# by a space.\nif test yes = \"$_G_HAVE_PLUSEQ_OP\"; then\n  eval 'func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1+=\\\\ \\$func_quote_for_eval_result\"\n  }'\nelse\n  func_append_quoted ()\n  {\n    $debug_cmd\n\n    func_quote_for_eval \"$2\"\n    eval \"$1=\\$$1\\\\ \\$func_quote_for_eval_result\"\n  }\nfi\n\n\n# func_append_uniq VAR VALUE\n# --------------------------\n# Append unique VALUE onto the existing contents of VAR, assuming\n# entries are delimited by the first character of VALUE.  For example:\n#\n#   func_append_uniq options \" --another-option option-argument\"\n#\n# will only append to $options if \" --another-option option-argument \"\n# is not already present somewhere in $options already (note spaces at\n# each end implied by leading space in second argument).\nfunc_append_uniq ()\n{\n    $debug_cmd\n\n    eval _G_current_value='`$ECHO $'$1'`'\n    _G_delim=`expr \"$2\" : '\\(.\\)'`\n\n    case $_G_delim$_G_current_value$_G_delim in\n      *\"$2$_G_delim\"*) ;;\n      *) func_append \"$@\" ;;\n    esac\n}\n\n\n# func_arith TERM...\n# ------------------\n# Set func_arith_result to the result of evaluating TERMs.\n  test -z \"$_G_HAVE_ARITH_OP\" \\\n    && (eval 'test 2 = $(( 1 + 1 ))') 2>/dev/null \\\n    && _G_HAVE_ARITH_OP=yes\n\nif test yes = \"$_G_HAVE_ARITH_OP\"; then\n  eval 'func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=$(( $* ))\n  }'\nelse\n  func_arith ()\n  {\n    $debug_cmd\n\n    func_arith_result=`expr \"$@\"`\n  }\nfi\n\n\n# func_basename FILE\n# ------------------\n# Set func_basename_result to FILE with everything up to and including\n# the last / stripped.\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  # If this shell supports suffix pattern removal, then use it to avoid\n  # forking. Hide the definitions single quotes in case the shell chokes\n  # on unsupported syntax...\n  _b='func_basename_result=${1##*/}'\n  _d='case $1 in\n        */*) func_dirname_result=${1%/*}$2 ;;\n        *  ) func_dirname_result=$3        ;;\n      esac'\n\nelse\n  # ...otherwise fall back to using sed.\n  _b='func_basename_result=`$ECHO \"$1\" |$SED \"$sed_basename\"`'\n  _d='func_dirname_result=`$ECHO \"$1\"  |$SED \"$sed_dirname\"`\n      if test \"X$func_dirname_result\" = \"X$1\"; then\n        func_dirname_result=$3\n      else\n        func_append func_dirname_result \"$2\"\n      fi'\nfi\n\neval 'func_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n}'\n\n\n# func_dirname FILE APPEND NONDIR_REPLACEMENT\n# -------------------------------------------\n# Compute the dirname of FILE.  If nonempty, add APPEND to the result,\n# otherwise set result to NONDIR_REPLACEMENT.\neval 'func_dirname ()\n{\n    $debug_cmd\n\n    '\"$_d\"'\n}'\n\n\n# func_dirname_and_basename FILE APPEND NONDIR_REPLACEMENT\n# --------------------------------------------------------\n# Perform func_basename and func_dirname in a single function\n# call:\n#   dirname:  Compute the dirname of FILE.  If nonempty,\n#             add APPEND to the result, otherwise set result\n#             to NONDIR_REPLACEMENT.\n#             value returned in \"$func_dirname_result\"\n#   basename: Compute filename of FILE.\n#             value retuned in \"$func_basename_result\"\n# For efficiency, we do not delegate to the functions above but instead\n# duplicate the functionality here.\neval 'func_dirname_and_basename ()\n{\n    $debug_cmd\n\n    '\"$_b\"'\n    '\"$_d\"'\n}'\n\n\n# func_echo ARG...\n# ----------------\n# Echo program name prefixed message.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_echo_all ARG...\n# --------------------\n# Invoke $ECHO with all args, space-separated.\nfunc_echo_all ()\n{\n    $ECHO \"$*\"\n}\n\n\n# func_echo_infix_1 INFIX ARG...\n# ------------------------------\n# Echo program name, followed by INFIX on the first line, with any\n# additional lines not showing INFIX.\nfunc_echo_infix_1 ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    _G_infix=$1; shift\n    _G_indent=$_G_infix\n    _G_prefix=\"$progname: $_G_infix: \"\n    _G_message=$*\n\n    # Strip color escape sequences before counting printable length\n    for _G_tc in \"$tc_reset\" \"$tc_bold\" \"$tc_standout\" \"$tc_red\" \"$tc_green\" \"$tc_blue\" \"$tc_cyan\"\n    do\n      test -n \"$_G_tc\" && {\n        _G_esc_tc=`$ECHO \"$_G_tc\" | $SED \"$sed_make_literal_regex\"`\n        _G_indent=`$ECHO \"$_G_indent\" | $SED \"s|$_G_esc_tc||g\"`\n      }\n    done\n    _G_indent=\"$progname: \"`echo \"$_G_indent\" | $SED 's|.| |g'`\"  \" ## exclude from sc_prohibit_nested_quotes\n\n    func_echo_infix_1_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_infix_1_IFS\n      $ECHO \"$_G_prefix$tc_bold$_G_line$tc_reset\" >&2\n      _G_prefix=$_G_indent\n    done\n    IFS=$func_echo_infix_1_IFS\n}\n\n\n# func_error ARG...\n# -----------------\n# Echo program name prefixed message to standard error.\nfunc_error ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"  $tc_standout${tc_red}error$tc_reset\" \"$*\" >&2\n}\n\n\n# func_fatal_error ARG...\n# -----------------------\n# Echo program name prefixed message to standard error, and exit.\nfunc_fatal_error ()\n{\n    $debug_cmd\n\n    func_error \"$*\"\n    exit $EXIT_FAILURE\n}\n\n\n# func_grep EXPRESSION FILENAME\n# -----------------------------\n# Check whether EXPRESSION matches any line of FILENAME, without output.\nfunc_grep ()\n{\n    $debug_cmd\n\n    $GREP \"$1\" \"$2\" >/dev/null 2>&1\n}\n\n\n# func_len STRING\n# ---------------\n# Set func_len_result to the length of STRING. STRING may not\n# start with a hyphen.\n  test -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=${#1}\n  }'\nelse\n  func_len ()\n  {\n    $debug_cmd\n\n    func_len_result=`expr \"$1\" : \".*\" 2>/dev/null || echo $max_cmd_len`\n  }\nfi\n\n\n# func_mkdir_p DIRECTORY-PATH\n# ---------------------------\n# Make sure the entire path to DIRECTORY-PATH is available.\nfunc_mkdir_p ()\n{\n    $debug_cmd\n\n    _G_directory_path=$1\n    _G_dir_list=\n\n    if test -n \"$_G_directory_path\" && test : != \"$opt_dry_run\"; then\n\n      # Protect directory names starting with '-'\n      case $_G_directory_path in\n        -*) _G_directory_path=./$_G_directory_path ;;\n      esac\n\n      # While some portion of DIR does not yet exist...\n      while test ! -d \"$_G_directory_path\"; do\n        # ...make a list in topmost first order.  Use a colon delimited\n\t# list incase some portion of path contains whitespace.\n        _G_dir_list=$_G_directory_path:$_G_dir_list\n\n        # If the last portion added has no slash in it, the list is done\n        case $_G_directory_path in */*) ;; *) break ;; esac\n\n        # ...otherwise throw away the child directory and loop\n        _G_directory_path=`$ECHO \"$_G_directory_path\" | $SED -e \"$sed_dirname\"`\n      done\n      _G_dir_list=`$ECHO \"$_G_dir_list\" | $SED 's|:*$||'`\n\n      func_mkdir_p_IFS=$IFS; IFS=:\n      for _G_dir in $_G_dir_list; do\n\tIFS=$func_mkdir_p_IFS\n        # mkdir can fail with a 'File exist' error if two processes\n        # try to create one of the directories concurrently.  Don't\n        # stop in that case!\n        $MKDIR \"$_G_dir\" 2>/dev/null || :\n      done\n      IFS=$func_mkdir_p_IFS\n\n      # Bail out if we (or some other process) failed to create a directory.\n      test -d \"$_G_directory_path\" || \\\n        func_fatal_error \"Failed to create '$1'\"\n    fi\n}\n\n\n# func_mktempdir [BASENAME]\n# -------------------------\n# Make a temporary directory that won't clash with other running\n# libtool processes, and avoids race conditions if possible.  If\n# given, BASENAME is the basename for that directory.\nfunc_mktempdir ()\n{\n    $debug_cmd\n\n    _G_template=${TMPDIR-/tmp}/${1-$progname}\n\n    if test : = \"$opt_dry_run\"; then\n      # Return a directory name, but don't create it in dry-run mode\n      _G_tmpdir=$_G_template-$$\n    else\n\n      # If mktemp works, use that first and foremost\n      _G_tmpdir=`mktemp -d \"$_G_template-XXXXXXXX\" 2>/dev/null`\n\n      if test ! -d \"$_G_tmpdir\"; then\n        # Failing that, at least try and use $RANDOM to avoid a race\n        _G_tmpdir=$_G_template-${RANDOM-0}$$\n\n        func_mktempdir_umask=`umask`\n        umask 0077\n        $MKDIR \"$_G_tmpdir\"\n        umask $func_mktempdir_umask\n      fi\n\n      # If we're not in dry-run mode, bomb out on failure\n      test -d \"$_G_tmpdir\" || \\\n        func_fatal_error \"cannot create temporary directory '$_G_tmpdir'\"\n    fi\n\n    $ECHO \"$_G_tmpdir\"\n}\n\n\n# func_normal_abspath PATH\n# ------------------------\n# Remove doubled-up and trailing slashes, \".\" path components,\n# and cancel out any \"..\" path components in PATH after making\n# it an absolute path.\nfunc_normal_abspath ()\n{\n    $debug_cmd\n\n    # These SED scripts presuppose an absolute path with a trailing slash.\n    _G_pathcar='s|^/\\([^/]*\\).*$|\\1|'\n    _G_pathcdr='s|^/[^/]*||'\n    _G_removedotparts=':dotsl\n\t\ts|/\\./|/|g\n\t\tt dotsl\n\t\ts|/\\.$|/|'\n    _G_collapseslashes='s|/\\{1,\\}|/|g'\n    _G_finalslash='s|/*$|/|'\n\n    # Start from root dir and reassemble the path.\n    func_normal_abspath_result=\n    func_normal_abspath_tpath=$1\n    func_normal_abspath_altnamespace=\n    case $func_normal_abspath_tpath in\n      \"\")\n        # Empty path, that just means $cwd.\n        func_stripname '' '/' \"`pwd`\"\n        func_normal_abspath_result=$func_stripname_result\n        return\n        ;;\n      # The next three entries are used to spot a run of precisely\n      # two leading slashes without using negated character classes;\n      # we take advantage of case's first-match behaviour.\n      ///*)\n        # Unusual form of absolute path, do nothing.\n        ;;\n      //*)\n        # Not necessarily an ordinary path; POSIX reserves leading '//'\n        # and for example Cygwin uses it to access remote file shares\n        # over CIFS/SMB, so we conserve a leading double slash if found.\n        func_normal_abspath_altnamespace=/\n        ;;\n      /*)\n        # Absolute path, do nothing.\n        ;;\n      *)\n        # Relative path, prepend $cwd.\n        func_normal_abspath_tpath=`pwd`/$func_normal_abspath_tpath\n        ;;\n    esac\n\n    # Cancel out all the simple stuff to save iterations.  We also want\n    # the path to end with a slash for ease of parsing, so make sure\n    # there is one (and only one) here.\n    func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_removedotparts\" -e \"$_G_collapseslashes\" -e \"$_G_finalslash\"`\n    while :; do\n      # Processed it all yet?\n      if test / = \"$func_normal_abspath_tpath\"; then\n        # If we ascended to the root using \"..\" the result may be empty now.\n        if test -z \"$func_normal_abspath_result\"; then\n          func_normal_abspath_result=/\n        fi\n        break\n      fi\n      func_normal_abspath_tcomponent=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcar\"`\n      func_normal_abspath_tpath=`$ECHO \"$func_normal_abspath_tpath\" | $SED \\\n          -e \"$_G_pathcdr\"`\n      # Figure out what to do with it\n      case $func_normal_abspath_tcomponent in\n        \"\")\n          # Trailing empty path component, ignore it.\n          ;;\n        ..)\n          # Parent dir; strip last assembled component from result.\n          func_dirname \"$func_normal_abspath_result\"\n          func_normal_abspath_result=$func_dirname_result\n          ;;\n        *)\n          # Actual path component, append it.\n          func_append func_normal_abspath_result \"/$func_normal_abspath_tcomponent\"\n          ;;\n      esac\n    done\n    # Restore leading double-slash if one was found on entry.\n    func_normal_abspath_result=$func_normal_abspath_altnamespace$func_normal_abspath_result\n}\n\n\n# func_notquiet ARG...\n# --------------------\n# Echo program name prefixed message only when not in quiet mode.\nfunc_notquiet ()\n{\n    $debug_cmd\n\n    $opt_quiet || func_echo ${1+\"$@\"}\n\n    # A bug in bash halts the script if the last line of a function\n    # fails when set -e is in force, so we need another command to\n    # work around that:\n    :\n}\n\n\n# func_relative_path SRCDIR DSTDIR\n# --------------------------------\n# Set func_relative_path_result to the relative path from SRCDIR to DSTDIR.\nfunc_relative_path ()\n{\n    $debug_cmd\n\n    func_relative_path_result=\n    func_normal_abspath \"$1\"\n    func_relative_path_tlibdir=$func_normal_abspath_result\n    func_normal_abspath \"$2\"\n    func_relative_path_tbindir=$func_normal_abspath_result\n\n    # Ascend the tree starting from libdir\n    while :; do\n      # check if we have found a prefix of bindir\n      case $func_relative_path_tbindir in\n        $func_relative_path_tlibdir)\n          # found an exact match\n          func_relative_path_tcancelled=\n          break\n          ;;\n        $func_relative_path_tlibdir*)\n          # found a matching prefix\n          func_stripname \"$func_relative_path_tlibdir\" '' \"$func_relative_path_tbindir\"\n          func_relative_path_tcancelled=$func_stripname_result\n          if test -z \"$func_relative_path_result\"; then\n            func_relative_path_result=.\n          fi\n          break\n          ;;\n        *)\n          func_dirname $func_relative_path_tlibdir\n          func_relative_path_tlibdir=$func_dirname_result\n          if test -z \"$func_relative_path_tlibdir\"; then\n            # Have to descend all the way to the root!\n            func_relative_path_result=../$func_relative_path_result\n            func_relative_path_tcancelled=$func_relative_path_tbindir\n            break\n          fi\n          func_relative_path_result=../$func_relative_path_result\n          ;;\n      esac\n    done\n\n    # Now calculate path; take care to avoid doubling-up slashes.\n    func_stripname '' '/' \"$func_relative_path_result\"\n    func_relative_path_result=$func_stripname_result\n    func_stripname '/' '/' \"$func_relative_path_tcancelled\"\n    if test -n \"$func_stripname_result\"; then\n      func_append func_relative_path_result \"/$func_stripname_result\"\n    fi\n\n    # Normalisation. If bindir is libdir, return '.' else relative path.\n    if test -n \"$func_relative_path_result\"; then\n      func_stripname './' '' \"$func_relative_path_result\"\n      func_relative_path_result=$func_stripname_result\n    fi\n\n    test -n \"$func_relative_path_result\" || func_relative_path_result=.\n\n    :\n}\n\n\n# func_quote_for_eval ARG...\n# --------------------------\n# Aesthetically quote ARGs to be evaled later.\n# This function returns two values:\n#   i) func_quote_for_eval_result\n#      double-quoted, suitable for a subsequent eval\n#  ii) func_quote_for_eval_unquoted_result\n#      has all characters that are still active within double\n#      quotes backslashified.\nfunc_quote_for_eval ()\n{\n    $debug_cmd\n\n    func_quote_for_eval_unquoted_result=\n    func_quote_for_eval_result=\n    while test 0 -lt $#; do\n      case $1 in\n        *[\\\\\\`\\\"\\$]*)\n\t  _G_unquoted_arg=`printf '%s\\n' \"$1\" |$SED \"$sed_quote_subst\"` ;;\n        *)\n          _G_unquoted_arg=$1 ;;\n      esac\n      if test -n \"$func_quote_for_eval_unquoted_result\"; then\n\tfunc_append func_quote_for_eval_unquoted_result \" $_G_unquoted_arg\"\n      else\n        func_append func_quote_for_eval_unquoted_result \"$_G_unquoted_arg\"\n      fi\n\n      case $_G_unquoted_arg in\n        # Double-quote args containing shell metacharacters to delay\n        # word splitting, command substitution and variable expansion\n        # for a subsequent eval.\n        # Many Bourne shells cannot handle close brackets correctly\n        # in scan sets, so we specify it separately.\n        *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n          _G_quoted_arg=\\\"$_G_unquoted_arg\\\"\n          ;;\n        *)\n          _G_quoted_arg=$_G_unquoted_arg\n\t  ;;\n      esac\n\n      if test -n \"$func_quote_for_eval_result\"; then\n\tfunc_append func_quote_for_eval_result \" $_G_quoted_arg\"\n      else\n        func_append func_quote_for_eval_result \"$_G_quoted_arg\"\n      fi\n      shift\n    done\n}\n\n\n# func_quote_for_expand ARG\n# -------------------------\n# Aesthetically quote ARG to be evaled later; same as above,\n# but do not quote variable references.\nfunc_quote_for_expand ()\n{\n    $debug_cmd\n\n    case $1 in\n      *[\\\\\\`\\\"]*)\n\t_G_arg=`$ECHO \"$1\" | $SED \\\n\t    -e \"$sed_double_quote_subst\" -e \"$sed_double_backslash\"` ;;\n      *)\n        _G_arg=$1 ;;\n    esac\n\n    case $_G_arg in\n      # Double-quote args containing shell metacharacters to delay\n      # word splitting and command substitution for a subsequent eval.\n      # Many Bourne shells cannot handle close brackets correctly\n      # in scan sets, so we specify it separately.\n      *[\\[\\~\\#\\^\\&\\*\\(\\)\\{\\}\\|\\;\\<\\>\\?\\'\\ \\\t]*|*]*|\"\")\n        _G_arg=\\\"$_G_arg\\\"\n        ;;\n    esac\n\n    func_quote_for_expand_result=$_G_arg\n}\n\n\n# func_stripname PREFIX SUFFIX NAME\n# ---------------------------------\n# strip PREFIX and SUFFIX from NAME, and store in func_stripname_result.\n# PREFIX and SUFFIX must not contain globbing or regex special\n# characters, hashes, percent signs, but SUFFIX may contain a leading\n# dot (in which case that matches only a dot).\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_stripname ()\n  {\n    $debug_cmd\n\n    # pdksh 5.2.14 does not do ${X%$Y} correctly if both X and Y are\n    # positional parameters, so assign one to ordinary variable first.\n    func_stripname_result=$3\n    func_stripname_result=${func_stripname_result#\"$1\"}\n    func_stripname_result=${func_stripname_result%\"$2\"}\n  }'\nelse\n  func_stripname ()\n  {\n    $debug_cmd\n\n    case $2 in\n      .*) func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%\\\\\\\\$2\\$%%\"`;;\n      *)  func_stripname_result=`$ECHO \"$3\" | $SED -e \"s%^$1%%\" -e \"s%$2\\$%%\"`;;\n    esac\n  }\nfi\n\n\n# func_show_eval CMD [FAIL_EXP]\n# -----------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.\nfunc_show_eval ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    func_quote_for_expand \"$_G_cmd\"\n    eval \"func_notquiet $func_quote_for_expand_result\"\n\n    $opt_dry_run || {\n      eval \"$_G_cmd\"\n      _G_status=$?\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_show_eval_locale CMD [FAIL_EXP]\n# ------------------------------------\n# Unless opt_quiet is true, then output CMD.  Then, if opt_dryrun is\n# not true, evaluate CMD.  If the evaluation of CMD fails, and FAIL_EXP\n# is given, then evaluate it.  Use the saved locale for evaluation.\nfunc_show_eval_locale ()\n{\n    $debug_cmd\n\n    _G_cmd=$1\n    _G_fail_exp=${2-':'}\n\n    $opt_quiet || {\n      func_quote_for_expand \"$_G_cmd\"\n      eval \"func_echo $func_quote_for_expand_result\"\n    }\n\n    $opt_dry_run || {\n      eval \"$_G_user_locale\n\t    $_G_cmd\"\n      _G_status=$?\n      eval \"$_G_safe_locale\"\n      if test 0 -ne \"$_G_status\"; then\n\teval \"(exit $_G_status); $_G_fail_exp\"\n      fi\n    }\n}\n\n\n# func_tr_sh\n# ----------\n# Turn $1 into a string suitable for a shell variable name.\n# Result is stored in $func_tr_sh_result.  All characters\n# not in the set a-zA-Z0-9_ are replaced with '_'. Further,\n# if $1 begins with a digit, a '_' is prepended as well.\nfunc_tr_sh ()\n{\n    $debug_cmd\n\n    case $1 in\n    [0-9]* | *[!a-zA-Z0-9_]*)\n      func_tr_sh_result=`$ECHO \"$1\" | $SED -e 's/^\\([0-9]\\)/_\\1/' -e 's/[^a-zA-Z0-9_]/_/g'`\n      ;;\n    * )\n      func_tr_sh_result=$1\n      ;;\n    esac\n}\n\n\n# func_verbose ARG...\n# -------------------\n# Echo program name prefixed message in verbose mode only.\nfunc_verbose ()\n{\n    $debug_cmd\n\n    $opt_verbose && func_echo \"$*\"\n\n    :\n}\n\n\n# func_warn_and_continue ARG...\n# -----------------------------\n# Echo program name prefixed warning message to standard error.\nfunc_warn_and_continue ()\n{\n    $debug_cmd\n\n    $require_term_colors\n\n    func_echo_infix_1 \"${tc_red}warning$tc_reset\" \"$*\" >&2\n}\n\n\n# func_warning CATEGORY ARG...\n# ----------------------------\n# Echo program name prefixed warning message to standard error. Warning\n# messages can be filtered according to CATEGORY, where this function\n# elides messages where CATEGORY is not listed in the global variable\n# 'opt_warning_types'.\nfunc_warning ()\n{\n    $debug_cmd\n\n    # CATEGORY must be in the warning_categories list!\n    case \" $warning_categories \" in\n      *\" $1 \"*) ;;\n      *) func_internal_error \"invalid warning category '$1'\" ;;\n    esac\n\n    _G_category=$1\n    shift\n\n    case \" $opt_warning_types \" in\n      *\" $_G_category \"*) $warning_func ${1+\"$@\"} ;;\n    esac\n}\n\n\n# func_sort_ver VER1 VER2\n# -----------------------\n# 'sort -V' is not generally available.\n# Note this deviates from the version comparison in automake\n# in that it treats 1.5 < 1.5.0, and treats 1.4.4a < 1.4-p3a\n# but this should suffice as we won't be specifying old\n# version formats or redundant trailing .0 in bootstrap.conf.\n# If we did want full compatibility then we should probably\n# use m4_version_compare from autoconf.\nfunc_sort_ver ()\n{\n    $debug_cmd\n\n    printf '%s\\n%s\\n' \"$1\" \"$2\" \\\n      | sort -t. -k 1,1n -k 2,2n -k 3,3n -k 4,4n -k 5,5n -k 6,6n -k 7,7n -k 8,8n -k 9,9n\n}\n\n# func_lt_ver PREV CURR\n# ---------------------\n# Return true if PREV and CURR are in the correct order according to\n# func_sort_ver, otherwise false.  Use it like this:\n#\n#  func_lt_ver \"$prev_ver\" \"$proposed_ver\" || func_fatal_error \"...\"\nfunc_lt_ver ()\n{\n    $debug_cmd\n\n    test \"x$1\" = x`func_sort_ver \"$1\" \"$2\" | $SED 1q`\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n#! /bin/sh\n\n# Set a version string for this script.\nscriptversion=2014-01-07.03; # UTC\n\n# A portable, pluggable option parser for Bourne shell.\n# Written by Gary V. Vaughan, 2010\n\n# Copyright (C) 2010-2015 Free Software Foundation, Inc.\n# This is free software; see the source for copying conditions.  There is NO\n# warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\n# Please report bugs or propose patches to gary@gnu.org.\n\n\n## ------ ##\n## Usage. ##\n## ------ ##\n\n# This file is a library for parsing options in your shell scripts along\n# with assorted other useful supporting features that you can make use\n# of too.\n#\n# For the simplest scripts you might need only:\n#\n#   #!/bin/sh\n#   . relative/path/to/funclib.sh\n#   . relative/path/to/options-parser\n#   scriptversion=1.0\n#   func_options ${1+\"$@\"}\n#   eval set dummy \"$func_options_result\"; shift\n#   ...rest of your script...\n#\n# In order for the '--version' option to work, you will need to have a\n# suitably formatted comment like the one at the top of this file\n# starting with '# Written by ' and ending with '# warranty; '.\n#\n# For '-h' and '--help' to work, you will also need a one line\n# description of your script's purpose in a comment directly above the\n# '# Written by ' line, like the one at the top of this file.\n#\n# The default options also support '--debug', which will turn on shell\n# execution tracing (see the comment above debug_cmd below for another\n# use), and '--verbose' and the func_verbose function to allow your script\n# to display verbose messages only when your user has specified\n# '--verbose'.\n#\n# After sourcing this file, you can plug processing for additional\n# options by amending the variables from the 'Configuration' section\n# below, and following the instructions in the 'Option parsing'\n# section further down.\n\n## -------------- ##\n## Configuration. ##\n## -------------- ##\n\n# You should override these variables in your script after sourcing this\n# file so that they reflect the customisations you have added to the\n# option parser.\n\n# The usage line for option parsing errors and the start of '-h' and\n# '--help' output messages. You can embed shell variables for delayed\n# expansion at the time the message is displayed, but you will need to\n# quote other shell meta-characters carefully to prevent them being\n# expanded when the contents are evaled.\nusage='$progpath [OPTION]...'\n\n# Short help message in response to '-h' and '--help'.  Add to this or\n# override it after sourcing this library to reflect the full set of\n# options your script accepts.\nusage_message=\"\\\n       --debug        enable verbose shell tracing\n   -W, --warnings=CATEGORY\n                      report the warnings falling in CATEGORY [all]\n   -v, --verbose      verbosely report processing\n       --version      print version information and exit\n   -h, --help         print short or long help message and exit\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nlong_help_message=\"\nWarning categories include:\n       'all'          show all warnings\n       'none'         turn off all the warnings\n       'error'        warnings are treated as fatal errors\"\n\n# Help message printed before fatal option parsing errors.\nfatal_help=\"Try '\\$progname --help' for more information.\"\n\n\n\n## ------------------------- ##\n## Hook function management. ##\n## ------------------------- ##\n\n# This section contains functions for adding, removing, and running hooks\n# to the main code.  A hook is just a named list of of function, that can\n# be run in order later on.\n\n# func_hookable FUNC_NAME\n# -----------------------\n# Declare that FUNC_NAME will run hooks added with\n# 'func_add_hook FUNC_NAME ...'.\nfunc_hookable ()\n{\n    $debug_cmd\n\n    func_append hookable_fns \" $1\"\n}\n\n\n# func_add_hook FUNC_NAME HOOK_FUNC\n# ---------------------------------\n# Request that FUNC_NAME call HOOK_FUNC before it returns.  FUNC_NAME must\n# first have been declared \"hookable\" by a call to 'func_hookable'.\nfunc_add_hook ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not accept hook functions.\" ;;\n    esac\n\n    eval func_append ${1}_hooks '\" $2\"'\n}\n\n\n# func_remove_hook FUNC_NAME HOOK_FUNC\n# ------------------------------------\n# Remove HOOK_FUNC from the list of functions called by FUNC_NAME.\nfunc_remove_hook ()\n{\n    $debug_cmd\n\n    eval ${1}_hooks='`$ECHO \"\\$'$1'_hooks\" |$SED \"s| '$2'||\"`'\n}\n\n\n# func_run_hooks FUNC_NAME [ARG]...\n# ---------------------------------\n# Run all hook functions registered to FUNC_NAME.\n# It is assumed that the list of hook functions contains nothing more\n# than a whitespace-delimited list of legal shell function names, and\n# no effort is wasted trying to catch shell meta-characters or preserve\n# whitespace.\nfunc_run_hooks ()\n{\n    $debug_cmd\n\n    case \" $hookable_fns \" in\n      *\" $1 \"*) ;;\n      *) func_fatal_error \"'$1' does not support hook funcions.n\" ;;\n    esac\n\n    eval _G_hook_fns=\\$$1_hooks; shift\n\n    for _G_hook in $_G_hook_fns; do\n      eval $_G_hook '\"$@\"'\n\n      # store returned options list back into positional\n      # parameters for next 'cmd' execution.\n      eval _G_hook_result=\\$${_G_hook}_result\n      eval set dummy \"$_G_hook_result\"; shift\n    done\n\n    func_quote_for_eval ${1+\"$@\"}\n    func_run_hooks_result=$func_quote_for_eval_result\n}\n\n\n\n## --------------- ##\n## Option parsing. ##\n## --------------- ##\n\n# In order to add your own option parsing hooks, you must accept the\n# full positional parameter list in your hook function, remove any\n# options that you action, and then pass back the remaining unprocessed\n# options in '<hooked_function_name>_result', escaped suitably for\n# 'eval'.  Like this:\n#\n#    my_options_prep ()\n#    {\n#        $debug_cmd\n#\n#        # Extend the existing usage message.\n#        usage_message=$usage_message'\n#      -s, --silent       don'\\''t print informational messages\n#    '\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_options_prep_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_options_prep my_options_prep\n#\n#\n#    my_silent_option ()\n#    {\n#        $debug_cmd\n#\n#        # Note that for efficiency, we parse as many options as we can\n#        # recognise in a loop before passing the remainder back to the\n#        # caller on the first unrecognised argument we encounter.\n#        while test $# -gt 0; do\n#          opt=$1; shift\n#          case $opt in\n#            --silent|-s) opt_silent=: ;;\n#            # Separate non-argument short options:\n#            -s*)         func_split_short_opt \"$_G_opt\"\n#                         set dummy \"$func_split_short_opt_name\" \\\n#                             \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n#                         shift\n#                         ;;\n#            *)            set dummy \"$_G_opt\" \"$*\"; shift; break ;;\n#          esac\n#        done\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_silent_option_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_parse_options my_silent_option\n#\n#\n#    my_option_validation ()\n#    {\n#        $debug_cmd\n#\n#        $opt_silent && $opt_verbose && func_fatal_help \"\\\n#    '--silent' and '--verbose' options are mutually exclusive.\"\n#\n#        func_quote_for_eval ${1+\"$@\"}\n#        my_option_validation_result=$func_quote_for_eval_result\n#    }\n#    func_add_hook func_validate_options my_option_validation\n#\n# You'll alse need to manually amend $usage_message to reflect the extra\n# options you parse.  It's preferable to append if you can, so that\n# multiple option parsing hooks can be added safely.\n\n\n# func_options [ARG]...\n# ---------------------\n# All the functions called inside func_options are hookable. See the\n# individual implementations for details.\nfunc_hookable func_options\nfunc_options ()\n{\n    $debug_cmd\n\n    func_options_prep ${1+\"$@\"}\n    eval func_parse_options \\\n        ${func_options_prep_result+\"$func_options_prep_result\"}\n    eval func_validate_options \\\n        ${func_parse_options_result+\"$func_parse_options_result\"}\n\n    eval func_run_hooks func_options \\\n        ${func_validate_options_result+\"$func_validate_options_result\"}\n\n    # save modified positional parameters for caller\n    func_options_result=$func_run_hooks_result\n}\n\n\n# func_options_prep [ARG]...\n# --------------------------\n# All initialisations required before starting the option parse loop.\n# Note that when calling hook functions, we pass through the list of\n# positional parameters.  If a hook function modifies that list, and\n# needs to propogate that back to rest of this script, then the complete\n# modified list must be put in 'func_run_hooks_result' before\n# returning.\nfunc_hookable func_options_prep\nfunc_options_prep ()\n{\n    $debug_cmd\n\n    # Option defaults:\n    opt_verbose=false\n    opt_warning_types=\n\n    func_run_hooks func_options_prep ${1+\"$@\"}\n\n    # save modified positional parameters for caller\n    func_options_prep_result=$func_run_hooks_result\n}\n\n\n# func_parse_options [ARG]...\n# ---------------------------\n# The main option parsing loop.\nfunc_hookable func_parse_options\nfunc_parse_options ()\n{\n    $debug_cmd\n\n    func_parse_options_result=\n\n    # this just eases exit handling\n    while test $# -gt 0; do\n      # Defer to hook functions for initial option parsing, so they\n      # get priority in the event of reusing an option name.\n      func_run_hooks func_parse_options ${1+\"$@\"}\n\n      # Adjust func_parse_options positional parameters to match\n      eval set dummy \"$func_run_hooks_result\"; shift\n\n      # Break out of the loop if we already parsed every option.\n      test $# -gt 0 || break\n\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --debug|-x)   debug_cmd='set -x'\n                      func_echo \"enabling shell trace mode\"\n                      $debug_cmd\n                      ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                      set dummy --warnings none ${1+\"$@\"}\n                      shift\n\t\t      ;;\n\n        --warnings|--warning|-W)\n                      test $# = 0 && func_missing_arg $_G_opt && break\n                      case \" $warning_categories $1\" in\n                        *\" $1 \"*)\n                          # trailing space prevents matching last $1 above\n                          func_append_uniq opt_warning_types \" $1\"\n                          ;;\n                        *all)\n                          opt_warning_types=$warning_categories\n                          ;;\n                        *none)\n                          opt_warning_types=none\n                          warning_func=:\n                          ;;\n                        *error)\n                          opt_warning_types=$warning_categories\n                          warning_func=func_fatal_error\n                          ;;\n                        *)\n                          func_fatal_error \\\n                             \"unsupported warning category: '$1'\"\n                          ;;\n                      esac\n                      shift\n                      ;;\n\n        --verbose|-v) opt_verbose=: ;;\n        --version)    func_version ;;\n        -\\?|-h)       func_usage ;;\n        --help)       func_help ;;\n\n\t# Separate optargs to long options (plugins may need this):\n\t--*=*)        func_split_equals \"$_G_opt\"\n\t              set dummy \"$func_split_equals_lhs\" \\\n                          \"$func_split_equals_rhs\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n       # Separate optargs to short options:\n        -W*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        # Separate non-argument short options:\n        -\\?*|-h*|-v*|-x*)\n                      func_split_short_opt \"$_G_opt\"\n                      set dummy \"$func_split_short_opt_name\" \\\n                          \"-$func_split_short_opt_arg\" ${1+\"$@\"}\n                      shift\n                      ;;\n\n        --)           break ;;\n        -*)           func_fatal_help \"unrecognised option: '$_G_opt'\" ;;\n        *)            set dummy \"$_G_opt\" ${1+\"$@\"}; shift; break ;;\n      esac\n    done\n\n    # save modified positional parameters for caller\n    func_quote_for_eval ${1+\"$@\"}\n    func_parse_options_result=$func_quote_for_eval_result\n}\n\n\n# func_validate_options [ARG]...\n# ------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nfunc_hookable func_validate_options\nfunc_validate_options ()\n{\n    $debug_cmd\n\n    # Display all warnings if -W was not given.\n    test -n \"$opt_warning_types\" || opt_warning_types=\" $warning_categories\"\n\n    func_run_hooks func_validate_options ${1+\"$@\"}\n\n    # Bail if the options were screwed!\n    $exit_cmd $EXIT_FAILURE\n\n    # save modified positional parameters for caller\n    func_validate_options_result=$func_run_hooks_result\n}\n\n\n\n## ----------------- ##\n## Helper functions. ##\n## ----------------- ##\n\n# This section contains the helper functions used by the rest of the\n# hookable option parser framework in ascii-betical order.\n\n\n# func_fatal_help ARG...\n# ----------------------\n# Echo program name prefixed message to standard error, followed by\n# a help hint, and exit.\nfunc_fatal_help ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    eval \\$ECHO \\\"\"$fatal_help\"\\\"\n    func_error ${1+\"$@\"}\n    exit $EXIT_FAILURE\n}\n\n\n# func_help\n# ---------\n# Echo long help message to standard output and exit.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\"\n    exit 0\n}\n\n\n# func_missing_arg ARGNAME\n# ------------------------\n# Echo program name prefixed message to standard error and set global\n# exit_cmd.\nfunc_missing_arg ()\n{\n    $debug_cmd\n\n    func_error \"Missing argument for '$1'.\"\n    exit_cmd=exit\n}\n\n\n# func_split_equals STRING\n# ------------------------\n# Set func_split_equals_lhs and func_split_equals_rhs shell variables after\n# splitting STRING at the '=' sign.\ntest -z \"$_G_HAVE_XSI_OPS\" \\\n    && (eval 'x=a/b/c;\n      test 5aa/bb/cc = \"${#x}${x%%/*}${x%/*}${x#*/}${x##*/}\"') 2>/dev/null \\\n    && _G_HAVE_XSI_OPS=yes\n\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=${1%%=*}\n      func_split_equals_rhs=${1#*=}\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        && func_split_equals_rhs=\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_equals ()\n  {\n      $debug_cmd\n\n      func_split_equals_lhs=`expr \"x$1\" : 'x\\([^=]*\\)'`\n      func_split_equals_rhs=\n      test \"x$func_split_equals_lhs\" = \"x$1\" \\\n        || func_split_equals_rhs=`expr \"x$1\" : 'x[^=]*=\\(.*\\)$'`\n  }\nfi #func_split_equals\n\n\n# func_split_short_opt SHORTOPT\n# -----------------------------\n# Set func_split_short_opt_name and func_split_short_opt_arg shell\n# variables after splitting SHORTOPT after the 2nd character.\nif test yes = \"$_G_HAVE_XSI_OPS\"\nthen\n  # This is an XSI compatible shell, allowing a faster implementation...\n  eval 'func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_arg=${1#??}\n      func_split_short_opt_name=${1%\"$func_split_short_opt_arg\"}\n  }'\nelse\n  # ...otherwise fall back to using expr, which is often a shell builtin.\n  func_split_short_opt ()\n  {\n      $debug_cmd\n\n      func_split_short_opt_name=`expr \"x$1\" : 'x-\\(.\\)'`\n      func_split_short_opt_arg=`expr \"x$1\" : 'x-.\\(.*\\)$'`\n  }\nfi #func_split_short_opt\n\n\n# func_usage\n# ----------\n# Echo short help message to standard output and exit.\nfunc_usage ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"Run '$progname --help |${PAGER-more}' for full usage\"\n    exit 0\n}\n\n\n# func_usage_message\n# ------------------\n# Echo short help message to standard output.\nfunc_usage_message ()\n{\n    $debug_cmd\n\n    eval \\$ECHO \\\"\"Usage: $usage\"\\\"\n    echo\n    $SED -n 's|^# ||\n        /^Written by/{\n          x;p;x\n        }\n\th\n\t/^Written by/q' < \"$progpath\"\n    echo\n    eval \\$ECHO \\\"\"$usage_message\"\\\"\n}\n\n\n# func_version\n# ------------\n# Echo version message to standard output and exit.\nfunc_version ()\n{\n    $debug_cmd\n\n    printf '%s\\n' \"$progname $scriptversion\"\n    $SED -n '\n        /(C)/!b go\n        :more\n        /\\./!{\n          N\n          s|\\n# | |\n          b more\n        }\n        :go\n        /^# Written by /,/# warranty; / {\n          s|^# ||\n          s|^# *$||\n          s|\\((C)\\)[ 0-9,-]*[ ,-]\\([1-9][0-9]* \\)|\\1 \\2|\n          p\n        }\n        /^# Written by / {\n          s|^# ||\n          p\n        }\n        /^warranty; /q' < \"$progpath\"\n\n    exit $?\n}\n\n\n# Local variables:\n# mode: shell-script\n# sh-indentation: 2\n# eval: (add-hook 'before-save-hook 'time-stamp)\n# time-stamp-pattern: \"10/scriptversion=%:y-%02m-%02d.%02H; # UTC\"\n# time-stamp-time-zone: \"UTC\"\n# End:\n\n# Set a version string.\nscriptversion='(GNU libtool) 2.4.6'\n\n\n# func_echo ARG...\n# ----------------\n# Libtool also displays the current mode in messages, so override\n# funclib.sh func_echo with this custom definition.\nfunc_echo ()\n{\n    $debug_cmd\n\n    _G_message=$*\n\n    func_echo_IFS=$IFS\n    IFS=$nl\n    for _G_line in $_G_message; do\n      IFS=$func_echo_IFS\n      $ECHO \"$progname${opt_mode+: $opt_mode}: $_G_line\"\n    done\n    IFS=$func_echo_IFS\n}\n\n\n# func_warning ARG...\n# -------------------\n# Libtool warnings are not categorized, so override funclib.sh\n# func_warning with this simpler definition.\nfunc_warning ()\n{\n    $debug_cmd\n\n    $warning_func ${1+\"$@\"}\n}\n\n\n## ---------------- ##\n## Options parsing. ##\n## ---------------- ##\n\n# Hook in the functions to make sure our own options are parsed during\n# the option parsing loop.\n\nusage='$progpath [OPTION]... [MODE-ARG]...'\n\n# Short help message in response to '-h'.\nusage_message=\"Options:\n       --config             show all configuration variables\n       --debug              enable verbose shell tracing\n   -n, --dry-run            display commands without modifying any files\n       --features           display basic configuration information and exit\n       --mode=MODE          use operation mode MODE\n       --no-warnings        equivalent to '-Wnone'\n       --preserve-dup-deps  don't remove duplicate dependency libraries\n       --quiet, --silent    don't print informational messages\n       --tag=TAG            use configuration variables from tag TAG\n   -v, --verbose            print more informational messages than default\n       --version            print version information\n   -W, --warnings=CATEGORY  report the warnings falling in CATEGORY [all]\n   -h, --help, --help-all   print short, long, or detailed help message\n\"\n\n# Additional text appended to 'usage_message' in response to '--help'.\nfunc_help ()\n{\n    $debug_cmd\n\n    func_usage_message\n    $ECHO \"$long_help_message\n\nMODE must be one of the following:\n\n       clean           remove files from the build directory\n       compile         compile a source file into a libtool object\n       execute         automatically set library path, then run a program\n       finish          complete the installation of libtool libraries\n       install         install libraries or executables\n       link            create a library or an executable\n       uninstall       remove libraries from an installed directory\n\nMODE-ARGS vary depending on the MODE.  When passed as first option,\n'--mode=MODE' may be abbreviated as 'MODE' or a unique abbreviation of that.\nTry '$progname --help --mode=MODE' for a more detailed description of MODE.\n\nWhen reporting a bug, please describe a test case to reproduce it and\ninclude the following information:\n\n       host-triplet:   $host\n       shell:          $SHELL\n       compiler:       $LTCC\n       compiler flags: $LTCFLAGS\n       linker:         $LD (gnu? $with_gnu_ld)\n       version:        $progname $scriptversion Debian-2.4.6-2\n       automake:       `($AUTOMAKE --version) 2>/dev/null |$SED 1q`\n       autoconf:       `($AUTOCONF --version) 2>/dev/null |$SED 1q`\n\nReport bugs to <bug-libtool@gnu.org>.\nGNU libtool home page: <http://www.gnu.org/s/libtool/>.\nGeneral help using GNU software: <http://www.gnu.org/gethelp/>.\"\n    exit 0\n}\n\n\n# func_lo2o OBJECT-NAME\n# ---------------------\n# Transform OBJECT-NAME from a '.lo' suffix to the platform specific\n# object suffix.\n\nlo2o=s/\\\\.lo\\$/.$objext/\no2lo=s/\\\\.$objext\\$/.lo/\n\nif test yes = \"$_G_HAVE_XSI_OPS\"; then\n  eval 'func_lo2o ()\n  {\n    case $1 in\n      *.lo) func_lo2o_result=${1%.lo}.$objext ;;\n      *   ) func_lo2o_result=$1               ;;\n    esac\n  }'\n\n  # func_xform LIBOBJ-OR-SOURCE\n  # ---------------------------\n  # Transform LIBOBJ-OR-SOURCE from a '.o' or '.c' (or otherwise)\n  # suffix to a '.lo' libtool-object suffix.\n  eval 'func_xform ()\n  {\n    func_xform_result=${1%.*}.lo\n  }'\nelse\n  # ...otherwise fall back to using sed.\n  func_lo2o ()\n  {\n    func_lo2o_result=`$ECHO \"$1\" | $SED \"$lo2o\"`\n  }\n\n  func_xform ()\n  {\n    func_xform_result=`$ECHO \"$1\" | $SED 's|\\.[^.]*$|.lo|'`\n  }\nfi\n\n\n# func_fatal_configuration ARG...\n# -------------------------------\n# Echo program name prefixed message to standard error, followed by\n# a configuration failure hint, and exit.\nfunc_fatal_configuration ()\n{\n    func__fatal_error ${1+\"$@\"} \\\n      \"See the $PACKAGE documentation for more information.\" \\\n      \"Fatal configuration error.\"\n}\n\n\n# func_config\n# -----------\n# Display the configuration for all the tags in this script.\nfunc_config ()\n{\n    re_begincf='^# ### BEGIN LIBTOOL'\n    re_endcf='^# ### END LIBTOOL'\n\n    # Default configuration.\n    $SED \"1,/$re_begincf CONFIG/d;/$re_endcf CONFIG/,\\$d\" < \"$progpath\"\n\n    # Now print the configurations for the tags.\n    for tagname in $taglist; do\n      $SED -n \"/$re_begincf TAG CONFIG: $tagname\\$/,/$re_endcf TAG CONFIG: $tagname\\$/p\" < \"$progpath\"\n    done\n\n    exit $?\n}\n\n\n# func_features\n# -------------\n# Display the features supported by this script.\nfunc_features ()\n{\n    echo \"host: $host\"\n    if test yes = \"$build_libtool_libs\"; then\n      echo \"enable shared libraries\"\n    else\n      echo \"disable shared libraries\"\n    fi\n    if test yes = \"$build_old_libs\"; then\n      echo \"enable static libraries\"\n    else\n      echo \"disable static libraries\"\n    fi\n\n    exit $?\n}\n\n\n# func_enable_tag TAGNAME\n# -----------------------\n# Verify that TAGNAME is valid, and either flag an error and exit, or\n# enable the TAGNAME tag.  We also add TAGNAME to the global $taglist\n# variable here.\nfunc_enable_tag ()\n{\n    # Global variable:\n    tagname=$1\n\n    re_begincf=\"^# ### BEGIN LIBTOOL TAG CONFIG: $tagname\\$\"\n    re_endcf=\"^# ### END LIBTOOL TAG CONFIG: $tagname\\$\"\n    sed_extractcf=/$re_begincf/,/$re_endcf/p\n\n    # Validate tagname.\n    case $tagname in\n      *[!-_A-Za-z0-9,/]*)\n        func_fatal_error \"invalid tag name: $tagname\"\n        ;;\n    esac\n\n    # Don't test for the \"default\" C tag, as we know it's\n    # there but not specially marked.\n    case $tagname in\n        CC) ;;\n    *)\n        if $GREP \"$re_begincf\" \"$progpath\" >/dev/null 2>&1; then\n\t  taglist=\"$taglist $tagname\"\n\n\t  # Evaluate the configuration.  Be careful to quote the path\n\t  # and the sed script, to avoid splitting on whitespace, but\n\t  # also don't use non-portable quotes within backquotes within\n\t  # quotes we have to do it in 2 steps:\n\t  extractedcf=`$SED -n -e \"$sed_extractcf\" < \"$progpath\"`\n\t  eval \"$extractedcf\"\n        else\n\t  func_error \"ignoring unknown tag $tagname\"\n        fi\n        ;;\n    esac\n}\n\n\n# func_check_version_match\n# ------------------------\n# Ensure that we are using m4 macros, and libtool script from the same\n# release of libtool.\nfunc_check_version_match ()\n{\n    if test \"$package_revision\" != \"$macro_revision\"; then\n      if test \"$VERSION\" != \"$macro_version\"; then\n        if test -z \"$macro_version\"; then\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from an older release.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        else\n          cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, but the\n$progname: definition of this LT_INIT comes from $PACKAGE $macro_version.\n$progname: You should recreate aclocal.m4 with macros from $PACKAGE $VERSION\n$progname: and run autoconf again.\n_LT_EOF\n        fi\n      else\n        cat >&2 <<_LT_EOF\n$progname: Version mismatch error.  This is $PACKAGE $VERSION, revision $package_revision,\n$progname: but the definition of this LT_INIT comes from revision $macro_revision.\n$progname: You should recreate aclocal.m4 with macros from revision $package_revision\n$progname: of $PACKAGE $VERSION and run autoconf again.\n_LT_EOF\n      fi\n\n      exit $EXIT_MISMATCH\n    fi\n}\n\n\n# libtool_options_prep [ARG]...\n# -----------------------------\n# Preparation for options parsed by libtool.\nlibtool_options_prep ()\n{\n    $debug_mode\n\n    # Option defaults:\n    opt_config=false\n    opt_dlopen=\n    opt_dry_run=false\n    opt_help=false\n    opt_mode=\n    opt_preserve_dup_deps=false\n    opt_quiet=false\n\n    nonopt=\n    preserve_args=\n\n    # Shorthand for --mode=foo, only valid as the first argument\n    case $1 in\n    clean|clea|cle|cl)\n      shift; set dummy --mode clean ${1+\"$@\"}; shift\n      ;;\n    compile|compil|compi|comp|com|co|c)\n      shift; set dummy --mode compile ${1+\"$@\"}; shift\n      ;;\n    execute|execut|execu|exec|exe|ex|e)\n      shift; set dummy --mode execute ${1+\"$@\"}; shift\n      ;;\n    finish|finis|fini|fin|fi|f)\n      shift; set dummy --mode finish ${1+\"$@\"}; shift\n      ;;\n    install|instal|insta|inst|ins|in|i)\n      shift; set dummy --mode install ${1+\"$@\"}; shift\n      ;;\n    link|lin|li|l)\n      shift; set dummy --mode link ${1+\"$@\"}; shift\n      ;;\n    uninstall|uninstal|uninsta|uninst|unins|unin|uni|un|u)\n      shift; set dummy --mode uninstall ${1+\"$@\"}; shift\n      ;;\n    esac\n\n    # Pass back the list of options.\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_options_prep_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_options_prep libtool_options_prep\n\n\n# libtool_parse_options [ARG]...\n# ---------------------------------\n# Provide handling for libtool specific options.\nlibtool_parse_options ()\n{\n    $debug_cmd\n\n    # Perform our own loop to consume as many options as possible in\n    # each iteration.\n    while test $# -gt 0; do\n      _G_opt=$1\n      shift\n      case $_G_opt in\n        --dry-run|--dryrun|-n)\n                        opt_dry_run=:\n                        ;;\n\n        --config)       func_config ;;\n\n        --dlopen|-dlopen)\n                        opt_dlopen=\"${opt_dlopen+$opt_dlopen\n}$1\"\n                        shift\n                        ;;\n\n        --preserve-dup-deps)\n                        opt_preserve_dup_deps=: ;;\n\n        --features)     func_features ;;\n\n        --finish)       set dummy --mode finish ${1+\"$@\"}; shift ;;\n\n        --help)         opt_help=: ;;\n\n        --help-all)     opt_help=': help-all' ;;\n\n        --mode)         test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_mode=$1\n                        case $1 in\n                          # Valid mode arguments:\n                          clean|compile|execute|finish|install|link|relink|uninstall) ;;\n\n                          # Catch anything else as an error\n                          *) func_error \"invalid argument for $_G_opt\"\n                             exit_cmd=exit\n                             break\n                             ;;\n                        esac\n                        shift\n                        ;;\n\n        --no-silent|--no-quiet)\n                        opt_quiet=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-warnings|--no-warning|--no-warn)\n                        opt_warning=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --no-verbose)\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --silent|--quiet)\n                        opt_quiet=:\n                        opt_verbose=false\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n        --tag)          test $# = 0 && func_missing_arg $_G_opt && break\n                        opt_tag=$1\n                        func_append preserve_args \" $_G_opt $1\"\n                        func_enable_tag \"$1\"\n                        shift\n                        ;;\n\n        --verbose|-v)   opt_quiet=false\n                        opt_verbose=:\n                        func_append preserve_args \" $_G_opt\"\n                        ;;\n\n\t# An option not handled by this hook function:\n        *)\t\tset dummy \"$_G_opt\" ${1+\"$@\"};\tshift; break  ;;\n      esac\n    done\n\n\n    # save modified positional parameters for caller\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_parse_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_parse_options libtool_parse_options\n\n\n\n# libtool_validate_options [ARG]...\n# ---------------------------------\n# Perform any sanity checks on option settings and/or unconsumed\n# arguments.\nlibtool_validate_options ()\n{\n    # save first non-option argument\n    if test 0 -lt $#; then\n      nonopt=$1\n      shift\n    fi\n\n    # preserve --debug\n    test : = \"$debug_cmd\" || func_append preserve_args \" --debug\"\n\n    case $host in\n      # Solaris2 added to fix http://debbugs.gnu.org/cgi/bugreport.cgi?bug=16452\n      # see also: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=59788\n      *cygwin* | *mingw* | *pw32* | *cegcc* | *solaris2* | *os2*)\n        # don't eliminate duplications in $postdeps and $predeps\n        opt_duplicate_compiler_generated_deps=:\n        ;;\n      *)\n        opt_duplicate_compiler_generated_deps=$opt_preserve_dup_deps\n        ;;\n    esac\n\n    $opt_help || {\n      # Sanity checks first:\n      func_check_version_match\n\n      test yes != \"$build_libtool_libs\" \\\n        && test yes != \"$build_old_libs\" \\\n        && func_fatal_configuration \"not configured to build any kind of library\"\n\n      # Darwin sucks\n      eval std_shrext=\\\"$shrext_cmds\\\"\n\n      # Only execute mode is allowed to have -dlopen flags.\n      if test -n \"$opt_dlopen\" && test execute != \"$opt_mode\"; then\n        func_error \"unrecognized option '-dlopen'\"\n        $ECHO \"$help\" 1>&2\n        exit $EXIT_FAILURE\n      fi\n\n      # Change the help message to a mode-specific one.\n      generic_help=$help\n      help=\"Try '$progname --help --mode=$opt_mode' for more information.\"\n    }\n\n    # Pass back the unparsed argument list\n    func_quote_for_eval ${1+\"$@\"}\n    libtool_validate_options_result=$func_quote_for_eval_result\n}\nfunc_add_hook func_validate_options libtool_validate_options\n\n\n# Process options as early as possible so that --help and --version\n# can return quickly.\nfunc_options ${1+\"$@\"}\neval set dummy \"$func_options_result\"; shift\n\n\n\n## ----------- ##\n##    Main.    ##\n## ----------- ##\n\nmagic='%%%MAGIC variable%%%'\nmagic_exe='%%%MAGIC EXE variable%%%'\n\n# Global variables.\nextracted_archives=\nextracted_serial=0\n\n# If this variable is set in any of the actions, the command in it\n# will be execed at the end.  This prevents here-documents from being\n# left over by shells.\nexec_cmd=\n\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n$1\n_LTECHO_EOF'\n}\n\n# func_generated_by_libtool\n# True iff stdin has been generated by Libtool. This function is only\n# a basic sanity check; it will hardly flush out determined imposters.\nfunc_generated_by_libtool_p ()\n{\n  $GREP \"^# Generated by .*$PACKAGE\" > /dev/null 2>&1\n}\n\n# func_lalib_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_lalib_p ()\n{\n    test -f \"$1\" &&\n      $SED -e 4q \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_lalib_unsafe_p file\n# True iff FILE is a libtool '.la' library or '.lo' object file.\n# This function implements the same check as func_lalib_p without\n# resorting to external programs.  To this end, it redirects stdin and\n# closes it afterwards, without saving the original file descriptor.\n# As a safety measure, use it only where a negative result would be\n# fatal anyway.  Works if 'file' does not exist.\nfunc_lalib_unsafe_p ()\n{\n    lalib_p=no\n    if test -f \"$1\" && test -r \"$1\" && exec 5<&0 <\"$1\"; then\n\tfor lalib_p_l in 1 2 3 4\n\tdo\n\t    read lalib_p_line\n\t    case $lalib_p_line in\n\t\t\\#\\ Generated\\ by\\ *$PACKAGE* ) lalib_p=yes; break;;\n\t    esac\n\tdone\n\texec 0<&5 5<&-\n    fi\n    test yes = \"$lalib_p\"\n}\n\n# func_ltwrapper_script_p file\n# True iff FILE is a libtool wrapper script\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_script_p ()\n{\n    test -f \"$1\" &&\n      $lt_truncate_bin < \"$1\" 2>/dev/null | func_generated_by_libtool_p\n}\n\n# func_ltwrapper_executable_p file\n# True iff FILE is a libtool wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_executable_p ()\n{\n    func_ltwrapper_exec_suffix=\n    case $1 in\n    *.exe) ;;\n    *) func_ltwrapper_exec_suffix=.exe ;;\n    esac\n    $GREP \"$magic_exe\" \"$1$func_ltwrapper_exec_suffix\" >/dev/null 2>&1\n}\n\n# func_ltwrapper_scriptname file\n# Assumes file is an ltwrapper_executable\n# uses $file to determine the appropriate filename for a\n# temporary ltwrapper_script.\nfunc_ltwrapper_scriptname ()\n{\n    func_dirname_and_basename \"$1\" \"\" \".\"\n    func_stripname '' '.exe' \"$func_basename_result\"\n    func_ltwrapper_scriptname_result=$func_dirname_result/$objdir/${func_stripname_result}_ltshwrapper\n}\n\n# func_ltwrapper_p file\n# True iff FILE is a libtool wrapper script or wrapper executable\n# This function is only a basic sanity check; it will hardly flush out\n# determined imposters.\nfunc_ltwrapper_p ()\n{\n    func_ltwrapper_script_p \"$1\" || func_ltwrapper_executable_p \"$1\"\n}\n\n\n# func_execute_cmds commands fail_cmd\n# Execute tilde-delimited COMMANDS.\n# If FAIL_CMD is given, eval that upon failure.\n# FAIL_CMD may read-access the current command in variable CMD!\nfunc_execute_cmds ()\n{\n    $debug_cmd\n\n    save_ifs=$IFS; IFS='~'\n    for cmd in $1; do\n      IFS=$sp$nl\n      eval cmd=\\\"$cmd\\\"\n      IFS=$save_ifs\n      func_show_eval \"$cmd\" \"${2-:}\"\n    done\n    IFS=$save_ifs\n}\n\n\n# func_source file\n# Source FILE, adding directory component if necessary.\n# Note that it is not necessary on cygwin/mingw to append a dot to\n# FILE even if both FILE and FILE.exe exist: automatic-append-.exe\n# behavior happens only for exec(3), not for open(2)!  Also, sourcing\n# 'FILE.' does not work on cygwin managed mounts.\nfunc_source ()\n{\n    $debug_cmd\n\n    case $1 in\n    */* | *\\\\*)\t. \"$1\" ;;\n    *)\t\t. \"./$1\" ;;\n    esac\n}\n\n\n# func_resolve_sysroot PATH\n# Replace a leading = in PATH with a sysroot.  Store the result into\n# func_resolve_sysroot_result\nfunc_resolve_sysroot ()\n{\n  func_resolve_sysroot_result=$1\n  case $func_resolve_sysroot_result in\n  =*)\n    func_stripname '=' '' \"$func_resolve_sysroot_result\"\n    func_resolve_sysroot_result=$lt_sysroot$func_stripname_result\n    ;;\n  esac\n}\n\n# func_replace_sysroot PATH\n# If PATH begins with the sysroot, replace it with = and\n# store the result into func_replace_sysroot_result.\nfunc_replace_sysroot ()\n{\n  case $lt_sysroot:$1 in\n  ?*:\"$lt_sysroot\"*)\n    func_stripname \"$lt_sysroot\" '' \"$1\"\n    func_replace_sysroot_result='='$func_stripname_result\n    ;;\n  *)\n    # Including no sysroot.\n    func_replace_sysroot_result=$1\n    ;;\n  esac\n}\n\n# func_infer_tag arg\n# Infer tagged configuration to use if any are available and\n# if one wasn't chosen via the \"--tag\" command line option.\n# Only attempt this if the compiler in the base compile\n# command doesn't match the default compiler.\n# arg is usually of the form 'gcc ...'\nfunc_infer_tag ()\n{\n    $debug_cmd\n\n    if test -n \"$available_tags\" && test -z \"$tagname\"; then\n      CC_quoted=\n      for arg in $CC; do\n\tfunc_append_quoted CC_quoted \"$arg\"\n      done\n      CC_expanded=`func_echo_all $CC`\n      CC_quoted_expanded=`func_echo_all $CC_quoted`\n      case $@ in\n      # Blanks in the command may have been stripped by the calling shell,\n      # but not from the CC environment variable when configure was run.\n      \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n      \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*) ;;\n      # Blanks at the start of $base_compile will cause this to fail\n      # if we don't check for them as well.\n      *)\n\tfor z in $available_tags; do\n\t  if $GREP \"^# ### BEGIN LIBTOOL TAG CONFIG: $z$\" < \"$progpath\" > /dev/null; then\n\t    # Evaluate the configuration.\n\t    eval \"`$SED -n -e '/^# ### BEGIN LIBTOOL TAG CONFIG: '$z'$/,/^# ### END LIBTOOL TAG CONFIG: '$z'$/p' < $progpath`\"\n\t    CC_quoted=\n\t    for arg in $CC; do\n\t      # Double-quote args containing other shell metacharacters.\n\t      func_append_quoted CC_quoted \"$arg\"\n\t    done\n\t    CC_expanded=`func_echo_all $CC`\n\t    CC_quoted_expanded=`func_echo_all $CC_quoted`\n\t    case \"$@ \" in\n\t    \" $CC \"* | \"$CC \"* | \" $CC_expanded \"* | \"$CC_expanded \"* | \\\n\t    \" $CC_quoted\"* | \"$CC_quoted \"* | \" $CC_quoted_expanded \"* | \"$CC_quoted_expanded \"*)\n\t      # The compiler in the base compile command matches\n\t      # the one in the tagged configuration.\n\t      # Assume this is the tagged configuration we want.\n\t      tagname=$z\n\t      break\n\t      ;;\n\t    esac\n\t  fi\n\tdone\n\t# If $tagname still isn't set, then no tagged configuration\n\t# was found and let the user know that the \"--tag\" command\n\t# line option must be used.\n\tif test -z \"$tagname\"; then\n\t  func_echo \"unable to infer tagged configuration\"\n\t  func_fatal_error \"specify a tag with '--tag'\"\n#\telse\n#\t  func_verbose \"using $tagname tagged configuration\"\n\tfi\n\t;;\n      esac\n    fi\n}\n\n\n\n# func_write_libtool_object output_name pic_name nonpic_name\n# Create a libtool object file (analogous to a \".la\" file),\n# but don't create it if we're doing a dry run.\nfunc_write_libtool_object ()\n{\n    write_libobj=$1\n    if test yes = \"$build_libtool_libs\"; then\n      write_lobj=\\'$2\\'\n    else\n      write_lobj=none\n    fi\n\n    if test yes = \"$build_old_libs\"; then\n      write_oldobj=\\'$3\\'\n    else\n      write_oldobj=none\n    fi\n\n    $opt_dry_run || {\n      cat >${write_libobj}T <<EOF\n# $write_libobj - a libtool object file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# Name of the PIC object.\npic_object=$write_lobj\n\n# Name of the non-PIC object\nnon_pic_object=$write_oldobj\n\nEOF\n      $MV \"${write_libobj}T\" \"$write_libobj\"\n    }\n}\n\n\n##################################################\n# FILE NAME AND PATH CONVERSION HELPER FUNCTIONS #\n##################################################\n\n# func_convert_core_file_wine_to_w32 ARG\n# Helper function used by file name conversion functions when $build is *nix,\n# and $host is mingw, cygwin, or some other w32 environment. Relies on a\n# correctly configured wine environment available, with the winepath program\n# in $build's $PATH.\n#\n# ARG is the $build file name to be converted to w32 format.\n# Result is available in $func_convert_core_file_wine_to_w32_result, and will\n# be empty on error (or when ARG is empty)\nfunc_convert_core_file_wine_to_w32 ()\n{\n  $debug_cmd\n\n  func_convert_core_file_wine_to_w32_result=$1\n  if test -n \"$1\"; then\n    # Unfortunately, winepath does not exit with a non-zero error code, so we\n    # are forced to check the contents of stdout. On the other hand, if the\n    # command is not found, the shell will set an exit code of 127 and print\n    # *an error message* to stdout. So we must check for both error code of\n    # zero AND non-empty stdout, which explains the odd construction:\n    func_convert_core_file_wine_to_w32_tmp=`winepath -w \"$1\" 2>/dev/null`\n    if test \"$?\" -eq 0 && test -n \"$func_convert_core_file_wine_to_w32_tmp\"; then\n      func_convert_core_file_wine_to_w32_result=`$ECHO \"$func_convert_core_file_wine_to_w32_tmp\" |\n        $SED -e \"$sed_naive_backslashify\"`\n    else\n      func_convert_core_file_wine_to_w32_result=\n    fi\n  fi\n}\n# end: func_convert_core_file_wine_to_w32\n\n\n# func_convert_core_path_wine_to_w32 ARG\n# Helper function used by path conversion functions when $build is *nix, and\n# $host is mingw, cygwin, or some other w32 environment. Relies on a correctly\n# configured wine environment available, with the winepath program in $build's\n# $PATH. Assumes ARG has no leading or trailing path separator characters.\n#\n# ARG is path to be converted from $build format to win32.\n# Result is available in $func_convert_core_path_wine_to_w32_result.\n# Unconvertible file (directory) names in ARG are skipped; if no directory names\n# are convertible, then the result may be empty.\nfunc_convert_core_path_wine_to_w32 ()\n{\n  $debug_cmd\n\n  # unfortunately, winepath doesn't convert paths, only file names\n  func_convert_core_path_wine_to_w32_result=\n  if test -n \"$1\"; then\n    oldIFS=$IFS\n    IFS=:\n    for func_convert_core_path_wine_to_w32_f in $1; do\n      IFS=$oldIFS\n      func_convert_core_file_wine_to_w32 \"$func_convert_core_path_wine_to_w32_f\"\n      if test -n \"$func_convert_core_file_wine_to_w32_result\"; then\n        if test -z \"$func_convert_core_path_wine_to_w32_result\"; then\n          func_convert_core_path_wine_to_w32_result=$func_convert_core_file_wine_to_w32_result\n        else\n          func_append func_convert_core_path_wine_to_w32_result \";$func_convert_core_file_wine_to_w32_result\"\n        fi\n      fi\n    done\n    IFS=$oldIFS\n  fi\n}\n# end: func_convert_core_path_wine_to_w32\n\n\n# func_cygpath ARGS...\n# Wrapper around calling the cygpath program via LT_CYGPATH. This is used when\n# when (1) $build is *nix and Cygwin is hosted via a wine environment; or (2)\n# $build is MSYS and $host is Cygwin, or (3) $build is Cygwin. In case (1) or\n# (2), returns the Cygwin file name or path in func_cygpath_result (input\n# file name or path is assumed to be in w32 format, as previously converted\n# from $build's *nix or MSYS format). In case (3), returns the w32 file name\n# or path in func_cygpath_result (input file name or path is assumed to be in\n# Cygwin format). Returns an empty string on error.\n#\n# ARGS are passed to cygpath, with the last one being the file name or path to\n# be converted.\n#\n# Specify the absolute *nix (or w32) name to cygpath in the LT_CYGPATH\n# environment variable; do not put it in $PATH.\nfunc_cygpath ()\n{\n  $debug_cmd\n\n  if test -n \"$LT_CYGPATH\" && test -f \"$LT_CYGPATH\"; then\n    func_cygpath_result=`$LT_CYGPATH \"$@\" 2>/dev/null`\n    if test \"$?\" -ne 0; then\n      # on failure, ensure result is empty\n      func_cygpath_result=\n    fi\n  else\n    func_cygpath_result=\n    func_error \"LT_CYGPATH is empty or specifies non-existent file: '$LT_CYGPATH'\"\n  fi\n}\n#end: func_cygpath\n\n\n# func_convert_core_msys_to_w32 ARG\n# Convert file name or path ARG from MSYS format to w32 format.  Return\n# result in func_convert_core_msys_to_w32_result.\nfunc_convert_core_msys_to_w32 ()\n{\n  $debug_cmd\n\n  # awkward: cmd appends spaces to result\n  func_convert_core_msys_to_w32_result=`( cmd //c echo \"$1\" ) 2>/dev/null |\n    $SED -e 's/[ ]*$//' -e \"$sed_naive_backslashify\"`\n}\n#end: func_convert_core_msys_to_w32\n\n\n# func_convert_file_check ARG1 ARG2\n# Verify that ARG1 (a file name in $build format) was converted to $host\n# format in ARG2. Otherwise, emit an error message, but continue (resetting\n# func_to_host_file_result to ARG1).\nfunc_convert_file_check ()\n{\n  $debug_cmd\n\n  if test -z \"$2\" && test -n \"$1\"; then\n    func_error \"Could not determine host file name corresponding to\"\n    func_error \"  '$1'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback:\n    func_to_host_file_result=$1\n  fi\n}\n# end func_convert_file_check\n\n\n# func_convert_path_check FROM_PATHSEP TO_PATHSEP FROM_PATH TO_PATH\n# Verify that FROM_PATH (a path in $build format) was converted to $host\n# format in TO_PATH. Otherwise, emit an error message, but continue, resetting\n# func_to_host_file_result to a simplistic fallback value (see below).\nfunc_convert_path_check ()\n{\n  $debug_cmd\n\n  if test -z \"$4\" && test -n \"$3\"; then\n    func_error \"Could not determine the host path corresponding to\"\n    func_error \"  '$3'\"\n    func_error \"Continuing, but uninstalled executables may not work.\"\n    # Fallback.  This is a deliberately simplistic \"conversion\" and\n    # should not be \"improved\".  See libtool.info.\n    if test \"x$1\" != \"x$2\"; then\n      lt_replace_pathsep_chars=\"s|$1|$2|g\"\n      func_to_host_path_result=`echo \"$3\" |\n        $SED -e \"$lt_replace_pathsep_chars\"`\n    else\n      func_to_host_path_result=$3\n    fi\n  fi\n}\n# end func_convert_path_check\n\n\n# func_convert_path_front_back_pathsep FRONTPAT BACKPAT REPL ORIG\n# Modifies func_to_host_path_result by prepending REPL if ORIG matches FRONTPAT\n# and appending REPL if ORIG matches BACKPAT.\nfunc_convert_path_front_back_pathsep ()\n{\n  $debug_cmd\n\n  case $4 in\n  $1 ) func_to_host_path_result=$3$func_to_host_path_result\n    ;;\n  esac\n  case $4 in\n  $2 ) func_append func_to_host_path_result \"$3\"\n    ;;\n  esac\n}\n# end func_convert_path_front_back_pathsep\n\n\n##################################################\n# $build to $host FILE NAME CONVERSION FUNCTIONS #\n##################################################\n# invoked via '$to_host_file_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# Result will be available in $func_to_host_file_result.\n\n\n# func_to_host_file ARG\n# Converts the file name ARG from $build format to $host format. Return result\n# in func_to_host_file_result.\nfunc_to_host_file ()\n{\n  $debug_cmd\n\n  $to_host_file_cmd \"$1\"\n}\n# end func_to_host_file\n\n\n# func_to_tool_file ARG LAZY\n# converts the file name ARG from $build format to toolchain format. Return\n# result in func_to_tool_file_result.  If the conversion in use is listed\n# in (the comma separated) LAZY, no conversion takes place.\nfunc_to_tool_file ()\n{\n  $debug_cmd\n\n  case ,$2, in\n    *,\"$to_tool_file_cmd\",*)\n      func_to_tool_file_result=$1\n      ;;\n    *)\n      $to_tool_file_cmd \"$1\"\n      func_to_tool_file_result=$func_to_host_file_result\n      ;;\n  esac\n}\n# end func_to_tool_file\n\n\n# func_convert_file_noop ARG\n# Copy ARG to func_to_host_file_result.\nfunc_convert_file_noop ()\n{\n  func_to_host_file_result=$1\n}\n# end func_convert_file_noop\n\n\n# func_convert_file_msys_to_w32 ARG\n# Convert file name ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_msys_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_w32\n\n\n# func_convert_file_cygwin_to_w32 ARG\n# Convert file name ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_file_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # because $build is cygwin, we call \"the\" cygpath in $PATH; no need to use\n    # LT_CYGPATH in this case.\n    func_to_host_file_result=`cygpath -m \"$1\"`\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_cygwin_to_w32\n\n\n# func_convert_file_nix_to_w32 ARG\n# Convert file name ARG from *nix to w32 format.  Requires a wine environment\n# and a working winepath. Returns result in func_to_host_file_result.\nfunc_convert_file_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_to_host_file_result=$func_convert_core_file_wine_to_w32_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_w32\n\n\n# func_convert_file_msys_to_cygwin ARG\n# Convert file name ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_file_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    func_convert_core_msys_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_msys_to_cygwin\n\n\n# func_convert_file_nix_to_cygwin ARG\n# Convert file name ARG from *nix to Cygwin format.  Requires Cygwin installed\n# in a wine environment, working winepath, and LT_CYGPATH set.  Returns result\n# in func_to_host_file_result.\nfunc_convert_file_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_file_result=$1\n  if test -n \"$1\"; then\n    # convert from *nix to w32, then use cygpath to convert from w32 to cygwin.\n    func_convert_core_file_wine_to_w32 \"$1\"\n    func_cygpath -u \"$func_convert_core_file_wine_to_w32_result\"\n    func_to_host_file_result=$func_cygpath_result\n  fi\n  func_convert_file_check \"$1\" \"$func_to_host_file_result\"\n}\n# end func_convert_file_nix_to_cygwin\n\n\n#############################################\n# $build to $host PATH CONVERSION FUNCTIONS #\n#############################################\n# invoked via '$to_host_path_cmd ARG'\n#\n# In each case, ARG is the path to be converted from $build to $host format.\n# The result will be available in $func_to_host_path_result.\n#\n# Path separators are also converted from $build format to $host format.  If\n# ARG begins or ends with a path separator character, it is preserved (but\n# converted to $host format) on output.\n#\n# All path conversion functions are named using the following convention:\n#   file name conversion function    : func_convert_file_X_to_Y ()\n#   path conversion function         : func_convert_path_X_to_Y ()\n# where, for any given $build/$host combination the 'X_to_Y' value is the\n# same.  If conversion functions are added for new $build/$host combinations,\n# the two new functions must follow this pattern, or func_init_to_host_path_cmd\n# will break.\n\n\n# func_init_to_host_path_cmd\n# Ensures that function \"pointer\" variable $to_host_path_cmd is set to the\n# appropriate value, based on the value of $to_host_file_cmd.\nto_host_path_cmd=\nfunc_init_to_host_path_cmd ()\n{\n  $debug_cmd\n\n  if test -z \"$to_host_path_cmd\"; then\n    func_stripname 'func_convert_file_' '' \"$to_host_file_cmd\"\n    to_host_path_cmd=func_convert_path_$func_stripname_result\n  fi\n}\n\n\n# func_to_host_path ARG\n# Converts the path ARG from $build format to $host format. Return result\n# in func_to_host_path_result.\nfunc_to_host_path ()\n{\n  $debug_cmd\n\n  func_init_to_host_path_cmd\n  $to_host_path_cmd \"$1\"\n}\n# end func_to_host_path\n\n\n# func_convert_path_noop ARG\n# Copy ARG to func_to_host_path_result.\nfunc_convert_path_noop ()\n{\n  func_to_host_path_result=$1\n}\n# end func_convert_path_noop\n\n\n# func_convert_path_msys_to_w32 ARG\n# Convert path ARG from (mingw) MSYS to (mingw) w32 format; automatic\n# conversion to w32 is not available inside the cwrapper.  Returns result in\n# func_to_host_path_result.\nfunc_convert_path_msys_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from ARG.  MSYS\n    # behavior is inconsistent here; cygpath turns them into '.;' and ';.';\n    # and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_msys_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_w32\n\n\n# func_convert_path_cygwin_to_w32 ARG\n# Convert path ARG from Cygwin to w32 format.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_cygwin_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_to_host_path_result=`cygpath -m -p \"$func_to_host_path_tmp1\"`\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_cygwin_to_w32\n\n\n# func_convert_path_nix_to_w32 ARG\n# Convert path ARG from *nix to w32 format.  Requires a wine environment and\n# a working winepath.  Returns result in func_to_host_file_result.\nfunc_convert_path_nix_to_w32 ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_to_host_path_result=$func_convert_core_path_wine_to_w32_result\n    func_convert_path_check : \";\" \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" \";\" \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_w32\n\n\n# func_convert_path_msys_to_cygwin ARG\n# Convert path ARG from MSYS to Cygwin format.  Requires LT_CYGPATH set.\n# Returns result in func_to_host_file_result.\nfunc_convert_path_msys_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # See func_convert_path_msys_to_w32:\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_msys_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_msys_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_msys_to_cygwin\n\n\n# func_convert_path_nix_to_cygwin ARG\n# Convert path ARG from *nix to Cygwin format.  Requires Cygwin installed in a\n# a wine environment, working winepath, and LT_CYGPATH set.  Returns result in\n# func_to_host_file_result.\nfunc_convert_path_nix_to_cygwin ()\n{\n  $debug_cmd\n\n  func_to_host_path_result=$1\n  if test -n \"$1\"; then\n    # Remove leading and trailing path separator characters from\n    # ARG. msys behavior is inconsistent here, cygpath turns them\n    # into '.;' and ';.', and winepath ignores them completely.\n    func_stripname : : \"$1\"\n    func_to_host_path_tmp1=$func_stripname_result\n    func_convert_core_path_wine_to_w32 \"$func_to_host_path_tmp1\"\n    func_cygpath -u -p \"$func_convert_core_path_wine_to_w32_result\"\n    func_to_host_path_result=$func_cygpath_result\n    func_convert_path_check : : \\\n      \"$func_to_host_path_tmp1\" \"$func_to_host_path_result\"\n    func_convert_path_front_back_pathsep \":*\" \"*:\" : \"$1\"\n  fi\n}\n# end func_convert_path_nix_to_cygwin\n\n\n# func_dll_def_p FILE\n# True iff FILE is a Windows DLL '.def' file.\n# Keep in sync with _LT_DLL_DEF_P in libtool.m4\nfunc_dll_def_p ()\n{\n  $debug_cmd\n\n  func_dll_def_p_tmp=`$SED -n \\\n    -e 's/^[\t ]*//' \\\n    -e '/^\\(;.*\\)*$/d' \\\n    -e 's/^\\(EXPORTS\\|LIBRARY\\)\\([\t ].*\\)*$/DEF/p' \\\n    -e q \\\n    \"$1\"`\n  test DEF = \"$func_dll_def_p_tmp\"\n}\n\n\n# func_mode_compile arg...\nfunc_mode_compile ()\n{\n    $debug_cmd\n\n    # Get the compilation command and the source file.\n    base_compile=\n    srcfile=$nonopt  #  always keep a non-empty value in \"srcfile\"\n    suppress_opt=yes\n    suppress_output=\n    arg_mode=normal\n    libobj=\n    later=\n    pie_flag=\n\n    for arg\n    do\n      case $arg_mode in\n      arg  )\n\t# do not \"continue\".  Instead, add this to base_compile\n\tlastarg=$arg\n\targ_mode=normal\n\t;;\n\n      target )\n\tlibobj=$arg\n\targ_mode=normal\n\tcontinue\n\t;;\n\n      normal )\n\t# Accept any command-line options.\n\tcase $arg in\n\t-o)\n\t  test -n \"$libobj\" && \\\n\t    func_fatal_error \"you cannot specify '-o' more than once\"\n\t  arg_mode=target\n\t  continue\n\t  ;;\n\n\t-pie | -fpie | -fPIE)\n          func_append pie_flag \" $arg\"\n\t  continue\n\t  ;;\n\n\t-shared | -static | -prefer-pic | -prefer-non-pic)\n\t  func_append later \" $arg\"\n\t  continue\n\t  ;;\n\n\t-no-suppress)\n\t  suppress_opt=no\n\t  continue\n\t  ;;\n\n\t-Xcompiler)\n\t  arg_mode=arg  #  the next one goes into the \"base_compile\" arg list\n\t  continue      #  The current \"srcfile\" will either be retained or\n\t  ;;            #  replaced later.  I would guess that would be a bug.\n\n\t-Wc,*)\n\t  func_stripname '-Wc,' '' \"$arg\"\n\t  args=$func_stripname_result\n\t  lastarg=\n\t  save_ifs=$IFS; IFS=,\n\t  for arg in $args; do\n\t    IFS=$save_ifs\n\t    func_append_quoted lastarg \"$arg\"\n\t  done\n\t  IFS=$save_ifs\n\t  func_stripname ' ' '' \"$lastarg\"\n\t  lastarg=$func_stripname_result\n\n\t  # Add the arguments to base_compile.\n\t  func_append base_compile \" $lastarg\"\n\t  continue\n\t  ;;\n\n\t*)\n\t  # Accept the current argument as the source file.\n\t  # The previous \"srcfile\" becomes the current argument.\n\t  #\n\t  lastarg=$srcfile\n\t  srcfile=$arg\n\t  ;;\n\tesac  #  case $arg\n\t;;\n      esac    #  case $arg_mode\n\n      # Aesthetically quote the previous argument.\n      func_append_quoted base_compile \"$lastarg\"\n    done # for arg\n\n    case $arg_mode in\n    arg)\n      func_fatal_error \"you must specify an argument for -Xcompile\"\n      ;;\n    target)\n      func_fatal_error \"you must specify a target with '-o'\"\n      ;;\n    *)\n      # Get the name of the library object.\n      test -z \"$libobj\" && {\n\tfunc_basename \"$srcfile\"\n\tlibobj=$func_basename_result\n      }\n      ;;\n    esac\n\n    # Recognize several different file suffixes.\n    # If the user specifies -o file.o, it is replaced with file.lo\n    case $libobj in\n    *.[cCFSifmso] | \\\n    *.ada | *.adb | *.ads | *.asm | \\\n    *.c++ | *.cc | *.ii | *.class | *.cpp | *.cxx | \\\n    *.[fF][09]? | *.for | *.java | *.go | *.obj | *.sx | *.cu | *.cup)\n      func_xform \"$libobj\"\n      libobj=$func_xform_result\n      ;;\n    esac\n\n    case $libobj in\n    *.lo) func_lo2o \"$libobj\"; obj=$func_lo2o_result ;;\n    *)\n      func_fatal_error \"cannot determine name of library object from '$libobj'\"\n      ;;\n    esac\n\n    func_infer_tag $base_compile\n\n    for arg in $later; do\n      case $arg in\n      -shared)\n\ttest yes = \"$build_libtool_libs\" \\\n\t  || func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tcontinue\n\t;;\n\n      -static)\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tcontinue\n\t;;\n\n      -prefer-pic)\n\tpic_mode=yes\n\tcontinue\n\t;;\n\n      -prefer-non-pic)\n\tpic_mode=no\n\tcontinue\n\t;;\n      esac\n    done\n\n    func_quote_for_eval \"$libobj\"\n    test \"X$libobj\" != \"X$func_quote_for_eval_result\" \\\n      && $ECHO \"X$libobj\" | $GREP '[]~#^*{};<>?\"'\"'\"'\t &()|`$[]' \\\n      && func_warning \"libobj name '$libobj' may not contain shell special characters.\"\n    func_dirname_and_basename \"$obj\" \"/\" \"\"\n    objname=$func_basename_result\n    xdir=$func_dirname_result\n    lobj=$xdir$objdir/$objname\n\n    test -z \"$base_compile\" && \\\n      func_fatal_help \"you must specify a compilation command\"\n\n    # Delete any leftover library objects.\n    if test yes = \"$build_old_libs\"; then\n      removelist=\"$obj $lobj $libobj ${libobj}T\"\n    else\n      removelist=\"$lobj $libobj ${libobj}T\"\n    fi\n\n    # On Cygwin there's no \"real\" PIC flag so we must build both object types\n    case $host_os in\n    cygwin* | mingw* | pw32* | os2* | cegcc*)\n      pic_mode=default\n      ;;\n    esac\n    if test no = \"$pic_mode\" && test pass_all != \"$deplibs_check_method\"; then\n      # non-PIC code in shared libraries is not supported\n      pic_mode=default\n    fi\n\n    # Calculate the filename of the output object if compiler does\n    # not support -o with -c\n    if test no = \"$compiler_c_o\"; then\n      output_obj=`$ECHO \"$srcfile\" | $SED 's%^.*/%%; s%\\.[^.]*$%%'`.$objext\n      lockfile=$output_obj.lock\n    else\n      output_obj=\n      need_locks=no\n      lockfile=\n    fi\n\n    # Lock this critical section if it is needed\n    # We use this script file to make the link, it avoids creating a new file\n    if test yes = \"$need_locks\"; then\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    elif test warn = \"$need_locks\"; then\n      if test -f \"$lockfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile exists and contains:\n`cat $lockfile 2>/dev/null`\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n      func_append removelist \" $output_obj\"\n      $ECHO \"$srcfile\" > \"$lockfile\"\n    fi\n\n    $opt_dry_run || $RM $removelist\n    func_append removelist \" $lockfile\"\n    trap '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE' 1 2 15\n\n    func_to_tool_file \"$srcfile\" func_convert_file_msys_to_w32\n    srcfile=$func_to_tool_file_result\n    func_quote_for_eval \"$srcfile\"\n    qsrcfile=$func_quote_for_eval_result\n\n    # Only build a PIC object if we are building libtool libraries.\n    if test yes = \"$build_libtool_libs\"; then\n      # Without this assignment, base_compile gets emptied.\n      fbsd_hideous_sh_bug=$base_compile\n\n      if test no != \"$pic_mode\"; then\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      else\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile\"\n      fi\n\n      func_mkdir_p \"$xdir$objdir\"\n\n      if test -z \"$output_obj\"; then\n\t# Place PIC objects in $objdir\n\tfunc_append command \" -o $lobj\"\n      fi\n\n      func_show_eval_locale \"$command\"\t\\\n          'test -n \"$output_obj\" && $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed, then go on to compile the next one\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$lobj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$lobj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n\n      # Allow error messages only from the first compilation.\n      if test yes = \"$suppress_opt\"; then\n\tsuppress_output=' >/dev/null 2>&1'\n      fi\n    fi\n\n    # Only build a position-dependent object if we build old libraries.\n    if test yes = \"$build_old_libs\"; then\n      if test yes != \"$pic_mode\"; then\n\t# Don't build PIC code\n\tcommand=\"$base_compile $qsrcfile$pie_flag\"\n      else\n\tcommand=\"$base_compile $qsrcfile $pic_flag\"\n      fi\n      if test yes = \"$compiler_c_o\"; then\n\tfunc_append command \" -o $obj\"\n      fi\n\n      # Suppress compiler output if we already did a PIC compilation.\n      func_append command \"$suppress_output\"\n      func_show_eval_locale \"$command\" \\\n        '$opt_dry_run || $RM $removelist; exit $EXIT_FAILURE'\n\n      if test warn = \"$need_locks\" &&\n\t test \"X`cat $lockfile 2>/dev/null`\" != \"X$srcfile\"; then\n\t$ECHO \"\\\n*** ERROR, $lockfile contains:\n`cat $lockfile 2>/dev/null`\n\nbut it should contain:\n$srcfile\n\nThis indicates that another process is trying to use the same\ntemporary object file, and libtool could not work around it because\nyour compiler does not support '-c' and '-o' together.  If you\nrepeat this compilation, it may succeed, by chance, but you had better\navoid parallel builds (make -j) in this platform, or get a better\ncompiler.\"\n\n\t$opt_dry_run || $RM $removelist\n\texit $EXIT_FAILURE\n      fi\n\n      # Just move the object if needed\n      if test -n \"$output_obj\" && test \"X$output_obj\" != \"X$obj\"; then\n\tfunc_show_eval '$MV \"$output_obj\" \"$obj\"' \\\n\t  'error=$?; $opt_dry_run || $RM $removelist; exit $error'\n      fi\n    fi\n\n    $opt_dry_run || {\n      func_write_libtool_object \"$libobj\" \"$objdir/$objname\" \"$objname\"\n\n      # Unlock the critical section if it was locked\n      if test no != \"$need_locks\"; then\n\tremovelist=$lockfile\n        $RM \"$lockfile\"\n      fi\n    }\n\n    exit $EXIT_SUCCESS\n}\n\n$opt_help || {\n  test compile = \"$opt_mode\" && func_mode_compile ${1+\"$@\"}\n}\n\nfunc_mode_help ()\n{\n    # We need to display help for each of the modes.\n    case $opt_mode in\n      \"\")\n        # Generic help is extracted from the usage comments\n        # at the start of this file.\n        func_help\n        ;;\n\n      clean)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=clean RM [RM-OPTION]... FILE...\n\nRemove files from the build directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, object or program, all the files associated\nwith it are deleted. Otherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      compile)\n      $ECHO \\\n\"Usage: $progname [OPTION]... --mode=compile COMPILE-COMMAND... SOURCEFILE\n\nCompile a source file into a libtool library object.\n\nThis mode accepts the following additional options:\n\n  -o OUTPUT-FILE    set the output file name to OUTPUT-FILE\n  -no-suppress      do not suppress compiler output for multiple passes\n  -prefer-pic       try to build PIC objects only\n  -prefer-non-pic   try to build non-PIC objects only\n  -shared           do not build a '.o' file suitable for static linking\n  -static           only build a '.o' file suitable for static linking\n  -Wc,FLAG          pass FLAG directly to the compiler\n\nCOMPILE-COMMAND is a command to be used in creating a 'standard' object file\nfrom the given SOURCEFILE.\n\nThe output file name is determined by removing the directory component from\nSOURCEFILE, then substituting the C source code suffix '.c' with the\nlibrary object suffix, '.lo'.\"\n        ;;\n\n      execute)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=execute COMMAND [ARGS]...\n\nAutomatically set library path, then run a program.\n\nThis mode accepts the following additional options:\n\n  -dlopen FILE      add the directory containing FILE to the library path\n\nThis mode sets the library path environment variable according to '-dlopen'\nflags.\n\nIf any of the ARGS are libtool executable wrappers, then they are translated\ninto their corresponding uninstalled binary, and any of their required library\ndirectories are added to the library path.\n\nThen, COMMAND is executed, with ARGS as arguments.\"\n        ;;\n\n      finish)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=finish [LIBDIR]...\n\nComplete the installation of libtool libraries.\n\nEach LIBDIR is a directory that contains libtool libraries.\n\nThe commands that this mode executes may require superuser privileges.  Use\nthe '--dry-run' option if you just want to see what would be executed.\"\n        ;;\n\n      install)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=install INSTALL-COMMAND...\n\nInstall executables or libraries.\n\nINSTALL-COMMAND is the installation command.  The first component should be\neither the 'install' or 'cp' program.\n\nThe following components of INSTALL-COMMAND are treated specially:\n\n  -inst-prefix-dir PREFIX-DIR  Use PREFIX-DIR as a staging area for installation\n\nThe rest of the components are interpreted as arguments to that command (only\nBSD-compatible install options are recognized).\"\n        ;;\n\n      link)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=link LINK-COMMAND...\n\nLink object files or libraries together to form another library, or to\ncreate an executable program.\n\nLINK-COMMAND is a command using the C compiler that you would use to create\na program from several object files.\n\nThe following components of LINK-COMMAND are treated specially:\n\n  -all-static       do not do any dynamic linking at all\n  -avoid-version    do not add a version suffix if possible\n  -bindir BINDIR    specify path to binaries directory (for systems where\n                    libraries must be found in the PATH setting at runtime)\n  -dlopen FILE      '-dlpreopen' FILE if it cannot be dlopened at runtime\n  -dlpreopen FILE   link in FILE and add its symbols to lt_preloaded_symbols\n  -export-dynamic   allow symbols from OUTPUT-FILE to be resolved with dlsym(3)\n  -export-symbols SYMFILE\n                    try to export only the symbols listed in SYMFILE\n  -export-symbols-regex REGEX\n                    try to export only the symbols matching REGEX\n  -LLIBDIR          search LIBDIR for required installed libraries\n  -lNAME            OUTPUT-FILE requires the installed library libNAME\n  -module           build a library that can dlopened\n  -no-fast-install  disable the fast-install mode\n  -no-install       link a not-installable executable\n  -no-undefined     declare that a library does not refer to external symbols\n  -o OUTPUT-FILE    create OUTPUT-FILE from the specified objects\n  -objectlist FILE  use a list of object files found in FILE to specify objects\n  -os2dllname NAME  force a short DLL name on OS/2 (no effect on other OSes)\n  -precious-files-regex REGEX\n                    don't remove output files matching REGEX\n  -release RELEASE  specify package release information\n  -rpath LIBDIR     the created library will eventually be installed in LIBDIR\n  -R[ ]LIBDIR       add LIBDIR to the runtime path of programs and libraries\n  -shared           only do dynamic linking of libtool libraries\n  -shrext SUFFIX    override the standard shared library file extension\n  -static           do not do any dynamic linking of uninstalled libtool libraries\n  -static-libtool-libs\n                    do not do any dynamic linking of libtool libraries\n  -version-info CURRENT[:REVISION[:AGE]]\n                    specify library version info [each variable defaults to 0]\n  -weak LIBNAME     declare that the target provides the LIBNAME interface\n  -Wc,FLAG\n  -Xcompiler FLAG   pass linker-specific FLAG directly to the compiler\n  -Wl,FLAG\n  -Xlinker FLAG     pass linker-specific FLAG directly to the linker\n  -XCClinker FLAG   pass link-specific FLAG to the compiler driver (CC)\n\nAll other options (arguments beginning with '-') are ignored.\n\nEvery other argument is treated as a filename.  Files ending in '.la' are\ntreated as uninstalled libtool libraries, other files are standard or library\nobject files.\n\nIf the OUTPUT-FILE ends in '.la', then a libtool library is created,\nonly library objects ('.lo' files) may be specified, and '-rpath' is\nrequired, except when creating a convenience library.\n\nIf OUTPUT-FILE ends in '.a' or '.lib', then a standard library is created\nusing 'ar' and 'ranlib', or on Windows using 'lib'.\n\nIf OUTPUT-FILE ends in '.lo' or '.$objext', then a reloadable object file\nis created, otherwise an executable program is created.\"\n        ;;\n\n      uninstall)\n        $ECHO \\\n\"Usage: $progname [OPTION]... --mode=uninstall RM [RM-OPTION]... FILE...\n\nRemove libraries from an installation directory.\n\nRM is the name of the program to use to delete files associated with each FILE\n(typically '/bin/rm').  RM-OPTIONS are options (such as '-f') to be passed\nto RM.\n\nIf FILE is a libtool library, all the files associated with it are deleted.\nOtherwise, only FILE itself is deleted using RM.\"\n        ;;\n\n      *)\n        func_fatal_help \"invalid operation mode '$opt_mode'\"\n        ;;\n    esac\n\n    echo\n    $ECHO \"Try '$progname --help' for more information about other modes.\"\n}\n\n# Now that we've collected a possible --mode arg, show help if necessary\nif $opt_help; then\n  if test : = \"$opt_help\"; then\n    func_mode_help\n  else\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\tfunc_mode_help\n      done\n    } | $SED -n '1p; 2,$s/^Usage:/  or: /p'\n    {\n      func_help noexit\n      for opt_mode in compile link execute install finish uninstall clean; do\n\techo\n\tfunc_mode_help\n      done\n    } |\n    $SED '1d\n      /^When reporting/,/^Report/{\n\tH\n\td\n      }\n      $x\n      /information about other modes/d\n      /more detailed .*MODE/d\n      s/^Usage:.*--mode=\\([^ ]*\\) .*/Description of \\1 mode:/'\n  fi\n  exit $?\nfi\n\n\n# func_mode_execute arg...\nfunc_mode_execute ()\n{\n    $debug_cmd\n\n    # The first argument is the command name.\n    cmd=$nonopt\n    test -z \"$cmd\" && \\\n      func_fatal_help \"you must specify a COMMAND\"\n\n    # Handle -dlopen flags immediately.\n    for file in $opt_dlopen; do\n      test -f \"$file\" \\\n\t|| func_fatal_help \"'$file' is not a file\"\n\n      dir=\n      case $file in\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$lib' is not a valid libtool archive\"\n\n\t# Read the libtool library.\n\tdlname=\n\tlibrary_names=\n\tfunc_source \"$file\"\n\n\t# Skip this library if it cannot be dlopened.\n\tif test -z \"$dlname\"; then\n\t  # Warn if it was a shared library.\n\t  test -n \"$library_names\" && \\\n\t    func_warning \"'$file' was not linked with '-export-dynamic'\"\n\t  continue\n\tfi\n\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\n\tif test -f \"$dir/$objdir/$dlname\"; then\n\t  func_append dir \"/$objdir\"\n\telse\n\t  if test ! -f \"$dir/$dlname\"; then\n\t    func_fatal_error \"cannot find '$dlname' in '$dir' or '$dir/$objdir'\"\n\t  fi\n\tfi\n\t;;\n\n      *.lo)\n\t# Just add the directory containing the .lo file.\n\tfunc_dirname \"$file\" \"\" \".\"\n\tdir=$func_dirname_result\n\t;;\n\n      *)\n\tfunc_warning \"'-dlopen' is ignored for non-libtool libraries and objects\"\n\tcontinue\n\t;;\n      esac\n\n      # Get the absolute pathname.\n      absdir=`cd \"$dir\" && pwd`\n      test -n \"$absdir\" && dir=$absdir\n\n      # Now add the directory to shlibpath_var.\n      if eval \"test -z \\\"\\$$shlibpath_var\\\"\"; then\n\teval \"$shlibpath_var=\\\"\\$dir\\\"\"\n      else\n\teval \"$shlibpath_var=\\\"\\$dir:\\$$shlibpath_var\\\"\"\n      fi\n    done\n\n    # This variable tells wrapper scripts just to set shlibpath_var\n    # rather than running their programs.\n    libtool_execute_magic=$magic\n\n    # Check if any of the arguments is a wrapper script.\n    args=\n    for file\n    do\n      case $file in\n      -* | *.la | *.lo ) ;;\n      *)\n\t# Do a test to see if this is really a libtool program.\n\tif func_ltwrapper_script_p \"$file\"; then\n\t  func_source \"$file\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\telif func_ltwrapper_executable_p \"$file\"; then\n\t  func_ltwrapper_scriptname \"$file\"\n\t  func_source \"$func_ltwrapper_scriptname_result\"\n\t  # Transform arg to wrapped name.\n\t  file=$progdir/$program\n\tfi\n\t;;\n      esac\n      # Quote arguments (to preserve shell metacharacters).\n      func_append_quoted args \"$file\"\n    done\n\n    if $opt_dry_run; then\n      # Display what would be done.\n      if test -n \"$shlibpath_var\"; then\n\teval \"\\$ECHO \\\"\\$shlibpath_var=\\$$shlibpath_var\\\"\"\n\techo \"export $shlibpath_var\"\n      fi\n      $ECHO \"$cmd$args\"\n      exit $EXIT_SUCCESS\n    else\n      if test -n \"$shlibpath_var\"; then\n\t# Export the shlibpath_var.\n\teval \"export $shlibpath_var\"\n      fi\n\n      # Restore saved environment variables\n      for lt_var in LANG LANGUAGE LC_ALL LC_CTYPE LC_COLLATE LC_MESSAGES\n      do\n\teval \"if test \\\"\\${save_$lt_var+set}\\\" = set; then\n                $lt_var=\\$save_$lt_var; export $lt_var\n\t      else\n\t\t$lt_unset $lt_var\n\t      fi\"\n      done\n\n      # Now prepare to actually exec the command.\n      exec_cmd=\\$cmd$args\n    fi\n}\n\ntest execute = \"$opt_mode\" && func_mode_execute ${1+\"$@\"}\n\n\n# func_mode_finish arg...\nfunc_mode_finish ()\n{\n    $debug_cmd\n\n    libs=\n    libdirs=\n    admincmds=\n\n    for opt in \"$nonopt\" ${1+\"$@\"}\n    do\n      if test -d \"$opt\"; then\n\tfunc_append libdirs \" $opt\"\n\n      elif test -f \"$opt\"; then\n\tif func_lalib_unsafe_p \"$opt\"; then\n\t  func_append libs \" $opt\"\n\telse\n\t  func_warning \"'$opt' is not a valid libtool archive\"\n\tfi\n\n      else\n\tfunc_fatal_error \"invalid argument '$opt'\"\n      fi\n    done\n\n    if test -n \"$libs\"; then\n      if test -n \"$lt_sysroot\"; then\n        sysroot_regex=`$ECHO \"$lt_sysroot\" | $SED \"$sed_make_literal_regex\"`\n        sysroot_cmd=\"s/\\([ ']\\)$sysroot_regex/\\1/g;\"\n      else\n        sysroot_cmd=\n      fi\n\n      # Remove sysroot references\n      if $opt_dry_run; then\n        for lib in $libs; do\n          echo \"removing references to $lt_sysroot and '=' prefixes from $lib\"\n        done\n      else\n        tmpdir=`func_mktempdir`\n        for lib in $libs; do\n\t  $SED -e \"$sysroot_cmd s/\\([ ']-[LR]\\)=/\\1/g; s/\\([ ']\\)=/\\1/g\" $lib \\\n\t    > $tmpdir/tmp-la\n\t  mv -f $tmpdir/tmp-la $lib\n\tdone\n        ${RM}r \"$tmpdir\"\n      fi\n    fi\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      for libdir in $libdirs; do\n\tif test -n \"$finish_cmds\"; then\n\t  # Do each command in the finish commands.\n\t  func_execute_cmds \"$finish_cmds\" 'admincmds=\"$admincmds\n'\"$cmd\"'\"'\n\tfi\n\tif test -n \"$finish_eval\"; then\n\t  # Do the single finish_eval.\n\t  eval cmds=\\\"$finish_eval\\\"\n\t  $opt_dry_run || eval \"$cmds\" || func_append admincmds \"\n       $cmds\"\n\tfi\n      done\n    fi\n\n    # Exit here if they wanted silent mode.\n    $opt_quiet && exit $EXIT_SUCCESS\n\n    if test -n \"$finish_cmds$finish_eval\" && test -n \"$libdirs\"; then\n      echo \"----------------------------------------------------------------------\"\n      echo \"Libraries have been installed in:\"\n      for libdir in $libdirs; do\n\t$ECHO \"   $libdir\"\n      done\n      echo\n      echo \"If you ever happen to want to link against installed libraries\"\n      echo \"in a given directory, LIBDIR, you must either use libtool, and\"\n      echo \"specify the full pathname of the library, or use the '-LLIBDIR'\"\n      echo \"flag during linking and do at least one of the following:\"\n      if test -n \"$shlibpath_var\"; then\n\techo \"   - add LIBDIR to the '$shlibpath_var' environment variable\"\n\techo \"     during execution\"\n      fi\n      if test -n \"$runpath_var\"; then\n\techo \"   - add LIBDIR to the '$runpath_var' environment variable\"\n\techo \"     during linking\"\n      fi\n      if test -n \"$hardcode_libdir_flag_spec\"; then\n\tlibdir=LIBDIR\n\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\n\t$ECHO \"   - use the '$flag' linker flag\"\n      fi\n      if test -n \"$admincmds\"; then\n\t$ECHO \"   - have your system administrator run these commands:$admincmds\"\n      fi\n      if test -f /etc/ld.so.conf; then\n\techo \"   - have your system administrator add LIBDIR to '/etc/ld.so.conf'\"\n      fi\n      echo\n\n      echo \"See any operating system documentation about shared libraries for\"\n      case $host in\n\tsolaris2.[6789]|solaris2.1[0-9])\n\t  echo \"more information, such as the ld(1), crle(1) and ld.so(8) manual\"\n\t  echo \"pages.\"\n\t  ;;\n\t*)\n\t  echo \"more information, such as the ld(1) and ld.so(8) manual pages.\"\n\t  ;;\n      esac\n      echo \"----------------------------------------------------------------------\"\n    fi\n    exit $EXIT_SUCCESS\n}\n\ntest finish = \"$opt_mode\" && func_mode_finish ${1+\"$@\"}\n\n\n# func_mode_install arg...\nfunc_mode_install ()\n{\n    $debug_cmd\n\n    # There may be an optional sh(1) argument at the beginning of\n    # install_prog (especially on Windows NT).\n    if test \"$SHELL\" = \"$nonopt\" || test /bin/sh = \"$nonopt\" ||\n       # Allow the use of GNU shtool's install command.\n       case $nonopt in *shtool*) :;; *) false;; esac\n    then\n      # Aesthetically quote it.\n      func_quote_for_eval \"$nonopt\"\n      install_prog=\"$func_quote_for_eval_result \"\n      arg=$1\n      shift\n    else\n      install_prog=\n      arg=$nonopt\n    fi\n\n    # The real first argument should be the name of the installation program.\n    # Aesthetically quote it.\n    func_quote_for_eval \"$arg\"\n    func_append install_prog \"$func_quote_for_eval_result\"\n    install_shared_prog=$install_prog\n    case \" $install_prog \" in\n      *[\\\\\\ /]cp\\ *) install_cp=: ;;\n      *) install_cp=false ;;\n    esac\n\n    # We need to accept at least all the BSD install flags.\n    dest=\n    files=\n    opts=\n    prev=\n    install_type=\n    isdir=false\n    stripme=\n    no_mode=:\n    for arg\n    do\n      arg2=\n      if test -n \"$dest\"; then\n\tfunc_append files \" $dest\"\n\tdest=$arg\n\tcontinue\n      fi\n\n      case $arg in\n      -d) isdir=: ;;\n      -f)\n\tif $install_cp; then :; else\n\t  prev=$arg\n\tfi\n\t;;\n      -g | -m | -o)\n\tprev=$arg\n\t;;\n      -s)\n\tstripme=\" -s\"\n\tcontinue\n\t;;\n      -*)\n\t;;\n      *)\n\t# If the previous option needed an argument, then skip it.\n\tif test -n \"$prev\"; then\n\t  if test X-m = \"X$prev\" && test -n \"$install_override_mode\"; then\n\t    arg2=$install_override_mode\n\t    no_mode=false\n\t  fi\n\t  prev=\n\telse\n\t  dest=$arg\n\t  continue\n\tfi\n\t;;\n      esac\n\n      # Aesthetically quote the argument.\n      func_quote_for_eval \"$arg\"\n      func_append install_prog \" $func_quote_for_eval_result\"\n      if test -n \"$arg2\"; then\n\tfunc_quote_for_eval \"$arg2\"\n      fi\n      func_append install_shared_prog \" $func_quote_for_eval_result\"\n    done\n\n    test -z \"$install_prog\" && \\\n      func_fatal_help \"you must specify an install program\"\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prev' option requires an argument\"\n\n    if test -n \"$install_override_mode\" && $no_mode; then\n      if $install_cp; then :; else\n\tfunc_quote_for_eval \"$install_override_mode\"\n\tfunc_append install_shared_prog \" -m $func_quote_for_eval_result\"\n      fi\n    fi\n\n    if test -z \"$files\"; then\n      if test -z \"$dest\"; then\n\tfunc_fatal_help \"no file or destination specified\"\n      else\n\tfunc_fatal_help \"you must specify a destination\"\n      fi\n    fi\n\n    # Strip any trailing slash from the destination.\n    func_stripname '' '/' \"$dest\"\n    dest=$func_stripname_result\n\n    # Check to see that the destination is a directory.\n    test -d \"$dest\" && isdir=:\n    if $isdir; then\n      destdir=$dest\n      destname=\n    else\n      func_dirname_and_basename \"$dest\" \"\" \".\"\n      destdir=$func_dirname_result\n      destname=$func_basename_result\n\n      # Not a directory, so check to see that there is only one file specified.\n      set dummy $files; shift\n      test \"$#\" -gt 1 && \\\n\tfunc_fatal_help \"'$dest' is not a directory\"\n    fi\n    case $destdir in\n    [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n    *)\n      for file in $files; do\n\tcase $file in\n\t*.lo) ;;\n\t*)\n\t  func_fatal_help \"'$destdir' must be an absolute directory name\"\n\t  ;;\n\tesac\n      done\n      ;;\n    esac\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    staticlibs=\n    future_libdirs=\n    current_libdirs=\n    for file in $files; do\n\n      # Do each installation.\n      case $file in\n      *.$libext)\n\t# Do the static libraries later.\n\tfunc_append staticlibs \" $file\"\n\t;;\n\n      *.la)\n\tfunc_resolve_sysroot \"$file\"\n\tfile=$func_resolve_sysroot_result\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$file\" \\\n\t  || func_fatal_help \"'$file' is not a valid libtool archive\"\n\n\tlibrary_names=\n\told_library=\n\trelink_command=\n\tfunc_source \"$file\"\n\n\t# Add the libdir to current_libdirs if it is the destination.\n\tif test \"X$destdir\" = \"X$libdir\"; then\n\t  case \"$current_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append current_libdirs \" $libdir\" ;;\n\t  esac\n\telse\n\t  # Note the libdir as a future libdir.\n\t  case \"$future_libdirs \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append future_libdirs \" $libdir\" ;;\n\t  esac\n\tfi\n\n\tfunc_dirname \"$file\" \"/\" \"\"\n\tdir=$func_dirname_result\n\tfunc_append dir \"$objdir\"\n\n\tif test -n \"$relink_command\"; then\n\t  # Determine the prefix the user has applied to our future dir.\n\t  inst_prefix_dir=`$ECHO \"$destdir\" | $SED -e \"s%$libdir\\$%%\"`\n\n\t  # Don't allow the user to place us outside of our expected\n\t  # location b/c this prevents finding dependent libraries that\n\t  # are installed to the same prefix.\n\t  # At present, this check doesn't affect windows .dll's that\n\t  # are installed into $libdir/../bin (currently, that works fine)\n\t  # but it's something to keep an eye on.\n\t  test \"$inst_prefix_dir\" = \"$destdir\" && \\\n\t    func_fatal_error \"error: cannot install '$file' to a directory not ending in $libdir\"\n\n\t  if test -n \"$inst_prefix_dir\"; then\n\t    # Stick the inst_prefix_dir data into the link command.\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%-inst-prefix-dir $inst_prefix_dir%\"`\n\t  else\n\t    relink_command=`$ECHO \"$relink_command\" | $SED \"s%@inst_prefix_dir@%%\"`\n\t  fi\n\n\t  func_warning \"relinking '$file'\"\n\t  func_show_eval \"$relink_command\" \\\n\t    'func_fatal_error \"error: relink '\\''$file'\\'' with the above command before installing it\"'\n\tfi\n\n\t# See the names of the shared library.\n\tset dummy $library_names; shift\n\tif test -n \"$1\"; then\n\t  realname=$1\n\t  shift\n\n\t  srcname=$realname\n\t  test -n \"$relink_command\" && srcname=${realname}T\n\n\t  # Install the shared library and build the symlinks.\n\t  func_show_eval \"$install_shared_prog $dir/$srcname $destdir/$realname\" \\\n\t      'exit $?'\n\t  tstripme=$stripme\n\t  case $host_os in\n\t  cygwin* | mingw* | pw32* | cegcc*)\n\t    case $realname in\n\t    *.dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  os2*)\n\t    case $realname in\n\t    *_dll.a)\n\t      tstripme=\n\t      ;;\n\t    esac\n\t    ;;\n\t  esac\n\t  if test -n \"$tstripme\" && test -n \"$striplib\"; then\n\t    func_show_eval \"$striplib $destdir/$realname\" 'exit $?'\n\t  fi\n\n\t  if test \"$#\" -gt 0; then\n\t    # Delete the old symlinks, and create new ones.\n\t    # Try 'ln -sf' first, because the 'ln' binary might depend on\n\t    # the symlink we replace!  Solaris /bin/ln does not understand -f,\n\t    # so we also need to try rm && ln -s.\n\t    for linkname\n\t    do\n\t      test \"$linkname\" != \"$realname\" \\\n\t\t&& func_show_eval \"(cd $destdir && { $LN_S -f $realname $linkname || { $RM $linkname && $LN_S $realname $linkname; }; })\"\n\t    done\n\t  fi\n\n\t  # Do each command in the postinstall commands.\n\t  lib=$destdir/$realname\n\t  func_execute_cmds \"$postinstall_cmds\" 'exit $?'\n\tfi\n\n\t# Install the pseudo-library for information purposes.\n\tfunc_basename \"$file\"\n\tname=$func_basename_result\n\tinstname=$dir/${name}i\n\tfunc_show_eval \"$install_prog $instname $destdir/$name\" 'exit $?'\n\n\t# Maybe install the static library, too.\n\ttest -n \"$old_library\" && func_append staticlibs \" $dir/$old_library\"\n\t;;\n\n      *.lo)\n\t# Install (i.e. copy) a libtool object.\n\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# Deduce the name of the destination old-style object file.\n\tcase $destfile in\n\t*.lo)\n\t  func_lo2o \"$destfile\"\n\t  staticdest=$func_lo2o_result\n\t  ;;\n\t*.$objext)\n\t  staticdest=$destfile\n\t  destfile=\n\t  ;;\n\t*)\n\t  func_fatal_help \"cannot copy a libtool object to '$destfile'\"\n\t  ;;\n\tesac\n\n\t# Install the libtool object if requested.\n\ttest -n \"$destfile\" && \\\n\t  func_show_eval \"$install_prog $file $destfile\" 'exit $?'\n\n\t# Install the old object if enabled.\n\tif test yes = \"$build_old_libs\"; then\n\t  # Deduce the name of the old-style object file.\n\t  func_lo2o \"$file\"\n\t  staticobj=$func_lo2o_result\n\t  func_show_eval \"$install_prog \\$staticobj \\$staticdest\" 'exit $?'\n\tfi\n\texit $EXIT_SUCCESS\n\t;;\n\n      *)\n\t# Figure out destination file name, if it wasn't already specified.\n\tif test -n \"$destname\"; then\n\t  destfile=$destdir/$destname\n\telse\n\t  func_basename \"$file\"\n\t  destfile=$func_basename_result\n\t  destfile=$destdir/$destfile\n\tfi\n\n\t# If the file is missing, and there is a .exe on the end, strip it\n\t# because it is most likely a libtool script we actually want to\n\t# install\n\tstripped_ext=\n\tcase $file in\n\t  *.exe)\n\t    if test ! -f \"$file\"; then\n\t      func_stripname '' '.exe' \"$file\"\n\t      file=$func_stripname_result\n\t      stripped_ext=.exe\n\t    fi\n\t    ;;\n\tesac\n\n\t# Do a test to see if this is really a libtool program.\n\tcase $host in\n\t*cygwin* | *mingw*)\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      wrapper=$func_ltwrapper_scriptname_result\n\t    else\n\t      func_stripname '' '.exe' \"$file\"\n\t      wrapper=$func_stripname_result\n\t    fi\n\t    ;;\n\t*)\n\t    wrapper=$file\n\t    ;;\n\tesac\n\tif func_ltwrapper_script_p \"$wrapper\"; then\n\t  notinst_deplibs=\n\t  relink_command=\n\n\t  func_source \"$wrapper\"\n\n\t  # Check the variables that should have been set.\n\t  test -z \"$generated_by_libtool_version\" && \\\n\t    func_fatal_error \"invalid libtool wrapper script '$wrapper'\"\n\n\t  finalize=:\n\t  for lib in $notinst_deplibs; do\n\t    # Check to see that each library is installed.\n\t    libdir=\n\t    if test -f \"$lib\"; then\n\t      func_source \"$lib\"\n\t    fi\n\t    libfile=$libdir/`$ECHO \"$lib\" | $SED 's%^.*/%%g'`\n\t    if test -n \"$libdir\" && test ! -f \"$libfile\"; then\n\t      func_warning \"'$lib' has not been installed in '$libdir'\"\n\t      finalize=false\n\t    fi\n\t  done\n\n\t  relink_command=\n\t  func_source \"$wrapper\"\n\n\t  outputname=\n\t  if test no = \"$fast_install\" && test -n \"$relink_command\"; then\n\t    $opt_dry_run || {\n\t      if $finalize; then\n\t        tmpdir=`func_mktempdir`\n\t\tfunc_basename \"$file$stripped_ext\"\n\t\tfile=$func_basename_result\n\t        outputname=$tmpdir/$file\n\t        # Replace the output file specification.\n\t        relink_command=`$ECHO \"$relink_command\" | $SED 's%@OUTPUT@%'\"$outputname\"'%g'`\n\n\t        $opt_quiet || {\n\t          func_quote_for_expand \"$relink_command\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t        }\n\t        if eval \"$relink_command\"; then :\n\t          else\n\t\t  func_error \"error: relink '$file' with the above command before installing it\"\n\t\t  $opt_dry_run || ${RM}r \"$tmpdir\"\n\t\t  continue\n\t        fi\n\t        file=$outputname\n\t      else\n\t        func_warning \"cannot relink '$file'\"\n\t      fi\n\t    }\n\t  else\n\t    # Install the binary that we compiled earlier.\n\t    file=`$ECHO \"$file$stripped_ext\" | $SED \"s%\\([^/]*\\)$%$objdir/\\1%\"`\n\t  fi\n\tfi\n\n\t# remove .exe since cygwin /usr/bin/install will append another\n\t# one anyway\n\tcase $install_prog,$host in\n\t*/usr/bin/install*,*cygwin*)\n\t  case $file:$destfile in\n\t  *.exe:*.exe)\n\t    # this is ok\n\t    ;;\n\t  *.exe:*)\n\t    destfile=$destfile.exe\n\t    ;;\n\t  *:*.exe)\n\t    func_stripname '' '.exe' \"$destfile\"\n\t    destfile=$func_stripname_result\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tfunc_show_eval \"$install_prog\\$stripme \\$file \\$destfile\" 'exit $?'\n\t$opt_dry_run || if test -n \"$outputname\"; then\n\t  ${RM}r \"$tmpdir\"\n\tfi\n\t;;\n      esac\n    done\n\n    for file in $staticlibs; do\n      func_basename \"$file\"\n      name=$func_basename_result\n\n      # Set up the ranlib parameters.\n      oldlib=$destdir/$name\n      func_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n      tool_oldlib=$func_to_tool_file_result\n\n      func_show_eval \"$install_prog \\$file \\$oldlib\" 'exit $?'\n\n      if test -n \"$stripme\" && test -n \"$old_striplib\"; then\n\tfunc_show_eval \"$old_striplib $tool_oldlib\" 'exit $?'\n      fi\n\n      # Do each command in the postinstall commands.\n      func_execute_cmds \"$old_postinstall_cmds\" 'exit $?'\n    done\n\n    test -n \"$future_libdirs\" && \\\n      func_warning \"remember to run '$progname --finish$future_libdirs'\"\n\n    if test -n \"$current_libdirs\"; then\n      # Maybe just do a dry run.\n      $opt_dry_run && current_libdirs=\" -n$current_libdirs\"\n      exec_cmd='$SHELL \"$progpath\" $preserve_args --finish$current_libdirs'\n    else\n      exit $EXIT_SUCCESS\n    fi\n}\n\ntest install = \"$opt_mode\" && func_mode_install ${1+\"$@\"}\n\n\n# func_generate_dlsyms outputname originator pic_p\n# Extract symbols from dlprefiles and create ${outputname}S.o with\n# a dlpreopen symbol table.\nfunc_generate_dlsyms ()\n{\n    $debug_cmd\n\n    my_outputname=$1\n    my_originator=$2\n    my_pic_p=${3-false}\n    my_prefix=`$ECHO \"$my_originator\" | $SED 's%[^a-zA-Z0-9]%_%g'`\n    my_dlsyms=\n\n    if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n      if test -n \"$NM\" && test -n \"$global_symbol_pipe\"; then\n\tmy_dlsyms=${my_outputname}S.c\n      else\n\tfunc_error \"not configured to extract global symbols from dlpreopened files\"\n      fi\n    fi\n\n    if test -n \"$my_dlsyms\"; then\n      case $my_dlsyms in\n      \"\") ;;\n      *.c)\n\t# Discover the nlist of each of the dlfiles.\n\tnlist=$output_objdir/$my_outputname.nm\n\n\tfunc_show_eval \"$RM $nlist ${nlist}S ${nlist}T\"\n\n\t# Parse the name list into a source file.\n\tfunc_verbose \"creating $output_objdir/$my_dlsyms\"\n\n\t$opt_dry_run || $ECHO > \"$output_objdir/$my_dlsyms\" \"\\\n/* $my_dlsyms - symbol resolution table for '$my_outputname' dlsym emulation. */\n/* Generated by $PROGRAM (GNU $PACKAGE) $VERSION */\n\n#ifdef __cplusplus\nextern \\\"C\\\" {\n#endif\n\n#if defined __GNUC__ && (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 4)) || (__GNUC__ > 4))\n#pragma GCC diagnostic ignored \\\"-Wstrict-prototypes\\\"\n#endif\n\n/* Keep this code in sync between libtool.m4, ltmain, lt_system.h, and tests.  */\n#if defined _WIN32 || defined __CYGWIN__ || defined _WIN32_WCE\n/* DATA imports from DLLs on WIN32 can't be const, because runtime\n   relocations are performed -- see ld's documentation on pseudo-relocs.  */\n# define LT_DLSYM_CONST\n#elif defined __osf__\n/* This system does not cope well with relocations in const data.  */\n# define LT_DLSYM_CONST\n#else\n# define LT_DLSYM_CONST const\n#endif\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* External symbol declarations for the compiler. */\\\n\"\n\n\tif test yes = \"$dlself\"; then\n\t  func_verbose \"generating symbol list for '$output'\"\n\n\t  $opt_dry_run || echo ': @PROGRAM@ ' > \"$nlist\"\n\n\t  # Add our own program objects to the symbol list.\n\t  progfiles=`$ECHO \"$objs$old_deplibs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\t  for progfile in $progfiles; do\n\t    func_to_tool_file \"$progfile\" func_convert_file_msys_to_w32\n\t    func_verbose \"extracting global C symbols from '$func_to_tool_file_result'\"\n\t    $opt_dry_run || eval \"$NM $func_to_tool_file_result | $global_symbol_pipe >> '$nlist'\"\n\t  done\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  if test -n \"$export_symbols_regex\"; then\n\t    $opt_dry_run || {\n\t      eval '$EGREP -e \"$export_symbols_regex\" \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t    }\n\t  fi\n\n\t  # Prepare the list of exported symbols\n\t  if test -z \"$export_symbols\"; then\n\t    export_symbols=$output_objdir/$outputname.exp\n\t    $opt_dry_run || {\n\t      $RM $export_symbols\n\t      eval \"$SED -n -e '/^: @PROGRAM@ $/d' -e 's/^.* \\(.*\\)$/\\1/p' \"'< \"$nlist\" > \"$export_symbols\"'\n\t      case $host in\n\t      *cygwin* | *mingw* | *cegcc* )\n                eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n                eval 'cat \"$export_symbols\" >> \"$output_objdir/$outputname.def\"'\n\t        ;;\n\t      esac\n\t    }\n\t  else\n\t    $opt_dry_run || {\n\t      eval \"$SED -e 's/\\([].[*^$]\\)/\\\\\\\\\\1/g' -e 's/^/ /' -e 's/$/$/'\"' < \"$export_symbols\" > \"$output_objdir/$outputname.exp\"'\n\t      eval '$GREP -f \"$output_objdir/$outputname.exp\" < \"$nlist\" > \"$nlist\"T'\n\t      eval '$MV \"$nlist\"T \"$nlist\"'\n\t      case $host in\n\t        *cygwin* | *mingw* | *cegcc* )\n\t          eval \"echo EXPORTS \"'> \"$output_objdir/$outputname.def\"'\n\t          eval 'cat \"$nlist\" >> \"$output_objdir/$outputname.def\"'\n\t          ;;\n\t      esac\n\t    }\n\t  fi\n\tfi\n\n\tfor dlprefile in $dlprefiles; do\n\t  func_verbose \"extracting global C symbols from '$dlprefile'\"\n\t  func_basename \"$dlprefile\"\n\t  name=$func_basename_result\n          case $host in\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # if an import library, we need to obtain dlname\n\t      if func_win32_import_lib_p \"$dlprefile\"; then\n\t        func_tr_sh \"$dlprefile\"\n\t        eval \"curr_lafile=\\$libfile_$func_tr_sh_result\"\n\t        dlprefile_dlbasename=\n\t        if test -n \"$curr_lafile\" && func_lalib_p \"$curr_lafile\"; then\n\t          # Use subshell, to avoid clobbering current variable values\n\t          dlprefile_dlname=`source \"$curr_lafile\" && echo \"$dlname\"`\n\t          if test -n \"$dlprefile_dlname\"; then\n\t            func_basename \"$dlprefile_dlname\"\n\t            dlprefile_dlbasename=$func_basename_result\n\t          else\n\t            # no lafile. user explicitly requested -dlpreopen <import library>.\n\t            $sharedlib_from_linklib_cmd \"$dlprefile\"\n\t            dlprefile_dlbasename=$sharedlib_from_linklib_result\n\t          fi\n\t        fi\n\t        $opt_dry_run || {\n\t          if test -n \"$dlprefile_dlbasename\"; then\n\t            eval '$ECHO \": $dlprefile_dlbasename\" >> \"$nlist\"'\n\t          else\n\t            func_warning \"Could not compute DLL name from $name\"\n\t            eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          fi\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe |\n\t            $SED -e '/I __imp/d' -e 's/I __nm_/D /;s/_nm__//' >> '$nlist'\"\n\t        }\n\t      else # not an import lib\n\t        $opt_dry_run || {\n\t          eval '$ECHO \": $name \" >> \"$nlist\"'\n\t          func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t          eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t        }\n\t      fi\n\t    ;;\n\t    *)\n\t      $opt_dry_run || {\n\t        eval '$ECHO \": $name \" >> \"$nlist\"'\n\t        func_to_tool_file \"$dlprefile\" func_convert_file_msys_to_w32\n\t        eval \"$NM \\\"$func_to_tool_file_result\\\" 2>/dev/null | $global_symbol_pipe >> '$nlist'\"\n\t      }\n\t    ;;\n          esac\n\tdone\n\n\t$opt_dry_run || {\n\t  # Make sure we have at least an empty file.\n\t  test -f \"$nlist\" || : > \"$nlist\"\n\n\t  if test -n \"$exclude_expsyms\"; then\n\t    $EGREP -v \" ($exclude_expsyms)$\" \"$nlist\" > \"$nlist\"T\n\t    $MV \"$nlist\"T \"$nlist\"\n\t  fi\n\n\t  # Try sorting and uniquifying the output.\n\t  if $GREP -v \"^: \" < \"$nlist\" |\n\t      if sort -k 3 </dev/null >/dev/null 2>&1; then\n\t\tsort -k 3\n\t      else\n\t\tsort +2\n\t      fi |\n\t      uniq > \"$nlist\"S; then\n\t    :\n\t  else\n\t    $GREP -v \"^: \" < \"$nlist\" > \"$nlist\"S\n\t  fi\n\n\t  if test -f \"$nlist\"S; then\n\t    eval \"$global_symbol_to_cdecl\"' < \"$nlist\"S >> \"$output_objdir/$my_dlsyms\"'\n\t  else\n\t    echo '/* NONE */' >> \"$output_objdir/$my_dlsyms\"\n\t  fi\n\n\t  func_show_eval '$RM \"${nlist}I\"'\n\t  if test -n \"$global_symbol_to_import\"; then\n\t    eval \"$global_symbol_to_import\"' < \"$nlist\"S > \"$nlist\"I'\n\t  fi\n\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n\n/* The mapping between symbol names and symbols.  */\ntypedef struct {\n  const char *name;\n  void *address;\n} lt_dlsymlist;\nextern LT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[];\\\n\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\nstatic void lt_syminit(void)\n{\n  LT_DLSYM_CONST lt_dlsymlist *symbol = lt_${my_prefix}_LTX_preloaded_symbols;\n  for (; symbol->name; ++symbol)\n    {\"\n\t    $SED 's/.*/      if (STREQ (symbol->name, \\\"&\\\")) symbol->address = (void *) \\&&;/' < \"$nlist\"I >> \"$output_objdir/$my_dlsyms\"\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n    }\n}\"\n\t  fi\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\nLT_DLSYM_CONST lt_dlsymlist\nlt_${my_prefix}_LTX_preloaded_symbols[] =\n{ {\\\"$my_originator\\\", (void *) 0},\"\n\n\t  if test -s \"$nlist\"I; then\n\t    echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {\\\"@INIT@\\\", (void *) &lt_syminit},\"\n\t  fi\n\n\t  case $need_lib_prefix in\n\t  no)\n\t    eval \"$global_symbol_to_c_name_address\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  *)\n\t    eval \"$global_symbol_to_c_name_address_lib_prefix\" < \"$nlist\" >> \"$output_objdir/$my_dlsyms\"\n\t    ;;\n\t  esac\n\t  echo >> \"$output_objdir/$my_dlsyms\" \"\\\n  {0, (void *) 0}\n};\n\n/* This works around a problem in FreeBSD linker */\n#ifdef FREEBSD_WORKAROUND\nstatic const void *lt_preloaded_setup() {\n  return lt_${my_prefix}_LTX_preloaded_symbols;\n}\n#endif\n\n#ifdef __cplusplus\n}\n#endif\\\n\"\n\t} # !$opt_dry_run\n\n\tpic_flag_for_symtable=\n\tcase \"$compile_command \" in\n\t*\" -static \"*) ;;\n\t*)\n\t  case $host in\n\t  # compiling the symbol table file with pic_flag works around\n\t  # a FreeBSD bug that causes programs to crash when -lm is\n\t  # linked before any other PIC object.  But we must not use\n\t  # pic_flag when linking with -static.  The problem exists in\n\t  # FreeBSD 2.2.6 and is fixed in FreeBSD 3.1.\n\t  *-*-freebsd2.*|*-*-freebsd3.0*|*-*-freebsdelf3.0*)\n\t    pic_flag_for_symtable=\" $pic_flag -DFREEBSD_WORKAROUND\" ;;\n\t  *-*-hpux*)\n\t    pic_flag_for_symtable=\" $pic_flag\"  ;;\n\t  *)\n\t    $my_pic_p && pic_flag_for_symtable=\" $pic_flag\"\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tsymtab_cflags=\n\tfor arg in $LTCFLAGS; do\n\t  case $arg in\n\t  -pie | -fpie | -fPIE) ;;\n\t  *) func_append symtab_cflags \" $arg\" ;;\n\t  esac\n\tdone\n\n\t# Now compile the dynamic symbol file.\n\tfunc_show_eval '(cd $output_objdir && $LTCC$symtab_cflags -c$no_builtin_flag$pic_flag_for_symtable \"$my_dlsyms\")' 'exit $?'\n\n\t# Clean up the generated files.\n\tfunc_show_eval '$RM \"$output_objdir/$my_dlsyms\" \"$nlist\" \"${nlist}S\" \"${nlist}T\" \"${nlist}I\"'\n\n\t# Transform the symbol file into the correct name.\n\tsymfileobj=$output_objdir/${my_outputname}S.$objext\n\tcase $host in\n\t*cygwin* | *mingw* | *cegcc* )\n\t  if test -f \"$output_objdir/$my_outputname.def\"; then\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$output_objdir/$my_outputname.def $symfileobj%\"`\n\t  else\n\t    compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t    finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  fi\n\t  ;;\n\t*)\n\t  compile_command=`$ECHO \"$compile_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  finalize_command=`$ECHO \"$finalize_command\" | $SED \"s%@SYMFILE@%$symfileobj%\"`\n\t  ;;\n\tesac\n\t;;\n      *)\n\tfunc_fatal_error \"unknown suffix for '$my_dlsyms'\"\n\t;;\n      esac\n    else\n      # We keep going just in case the user didn't refer to\n      # lt_preloaded_symbols.  The linker will fail if global_symbol_pipe\n      # really was required.\n\n      # Nullify the symbol file.\n      compile_command=`$ECHO \"$compile_command\" | $SED \"s% @SYMFILE@%%\"`\n      finalize_command=`$ECHO \"$finalize_command\" | $SED \"s% @SYMFILE@%%\"`\n    fi\n}\n\n# func_cygming_gnu_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is a GNU/binutils-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_gnu_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_gnu_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $EGREP ' (_head_[A-Za-z0-9_]+_[ad]l*|[A-Za-z0-9_]+_[ad]l*_iname)$'`\n  test -n \"$func_cygming_gnu_implib_tmp\"\n}\n\n# func_cygming_ms_implib_p ARG\n# This predicate returns with zero status (TRUE) if\n# ARG is an MS-style import library. Returns\n# with nonzero status (FALSE) otherwise.\nfunc_cygming_ms_implib_p ()\n{\n  $debug_cmd\n\n  func_to_tool_file \"$1\" func_convert_file_msys_to_w32\n  func_cygming_ms_implib_tmp=`$NM \"$func_to_tool_file_result\" | eval \"$global_symbol_pipe\" | $GREP '_NULL_IMPORT_DESCRIPTOR'`\n  test -n \"$func_cygming_ms_implib_tmp\"\n}\n\n# func_win32_libid arg\n# return the library type of file 'arg'\n#\n# Need a lot of goo to handle *both* DLLs and import libs\n# Has to be a shell function in order to 'eat' the argument\n# that is supplied when $file_magic_command is called.\n# Despite the name, also deal with 64 bit binaries.\nfunc_win32_libid ()\n{\n  $debug_cmd\n\n  win32_libid_type=unknown\n  win32_fileres=`file -L $1 2>/dev/null`\n  case $win32_fileres in\n  *ar\\ archive\\ import\\ library*) # definitely import\n    win32_libid_type=\"x86 archive import\"\n    ;;\n  *ar\\ archive*) # could be an import, or static\n    # Keep the egrep pattern in sync with the one in _LT_CHECK_MAGIC_METHOD.\n    if eval $OBJDUMP -f $1 | $SED -e '10q' 2>/dev/null |\n       $EGREP 'file format (pei*-i386(.*architecture: i386)?|pe-arm-wince|pe-x86-64)' >/dev/null; then\n      case $nm_interface in\n      \"MS dumpbin\")\n\tif func_cygming_ms_implib_p \"$1\" ||\n\t   func_cygming_gnu_implib_p \"$1\"\n\tthen\n\t  win32_nmres=import\n\telse\n\t  win32_nmres=\n\tfi\n\t;;\n      *)\n\tfunc_to_tool_file \"$1\" func_convert_file_msys_to_w32\n\twin32_nmres=`eval $NM -f posix -A \\\"$func_to_tool_file_result\\\" |\n\t  $SED -n -e '\n\t    1,100{\n\t\t/ I /{\n\t\t    s|.*|import|\n\t\t    p\n\t\t    q\n\t\t}\n\t    }'`\n\t;;\n      esac\n      case $win32_nmres in\n      import*)  win32_libid_type=\"x86 archive import\";;\n      *)        win32_libid_type=\"x86 archive static\";;\n      esac\n    fi\n    ;;\n  *DLL*)\n    win32_libid_type=\"x86 DLL\"\n    ;;\n  *executable*) # but shell scripts are \"executable\" too...\n    case $win32_fileres in\n    *MS\\ Windows\\ PE\\ Intel*)\n      win32_libid_type=\"x86 DLL\"\n      ;;\n    esac\n    ;;\n  esac\n  $ECHO \"$win32_libid_type\"\n}\n\n# func_cygming_dll_for_implib ARG\n#\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib ()\n{\n  $debug_cmd\n\n  sharedlib_from_linklib_result=`$DLLTOOL --identify-strict --identify \"$1\"`\n}\n\n# func_cygming_dll_for_implib_fallback_core SECTION_NAME LIBNAMEs\n#\n# The is the core of a fallback implementation of a\n# platform-specific function to extract the name of the\n# DLL associated with the specified import library LIBNAME.\n#\n# SECTION_NAME is either .idata$6 or .idata$7, depending\n# on the platform and compiler that created the implib.\n#\n# Echos the name of the DLL associated with the\n# specified import library.\nfunc_cygming_dll_for_implib_fallback_core ()\n{\n  $debug_cmd\n\n  match_literal=`$ECHO \"$1\" | $SED \"$sed_make_literal_regex\"`\n  $OBJDUMP -s --section \"$1\" \"$2\" 2>/dev/null |\n    $SED '/^Contents of section '\"$match_literal\"':/{\n      # Place marker at beginning of archive member dllname section\n      s/.*/====MARK====/\n      p\n      d\n    }\n    # These lines can sometimes be longer than 43 characters, but\n    # are always uninteresting\n    /:[\t ]*file format pe[i]\\{,1\\}-/d\n    /^In archive [^:]*:/d\n    # Ensure marker is printed\n    /^====MARK====/p\n    # Remove all lines with less than 43 characters\n    /^.\\{43\\}/!d\n    # From remaining lines, remove first 43 characters\n    s/^.\\{43\\}//' |\n    $SED -n '\n      # Join marker and all lines until next marker into a single line\n      /^====MARK====/ b para\n      H\n      $ b para\n      b\n      :para\n      x\n      s/\\n//g\n      # Remove the marker\n      s/^====MARK====//\n      # Remove trailing dots and whitespace\n      s/[\\. \\t]*$//\n      # Print\n      /./p' |\n    # we now have a list, one entry per line, of the stringified\n    # contents of the appropriate section of all members of the\n    # archive that possess that section. Heuristic: eliminate\n    # all those that have a first or second character that is\n    # a '.' (that is, objdump's representation of an unprintable\n    # character.) This should work for all archives with less than\n    # 0x302f exports -- but will fail for DLLs whose name actually\n    # begins with a literal '.' or a single character followed by\n    # a '.'.\n    #\n    # Of those that remain, print the first one.\n    $SED -e '/^\\./d;/^.\\./d;q'\n}\n\n# func_cygming_dll_for_implib_fallback ARG\n# Platform-specific function to extract the\n# name of the DLL associated with the specified\n# import library ARG.\n#\n# This fallback implementation is for use when $DLLTOOL\n# does not support the --identify-strict option.\n# Invoked by eval'ing the libtool variable\n#    $sharedlib_from_linklib_cmd\n# Result is available in the variable\n#    $sharedlib_from_linklib_result\nfunc_cygming_dll_for_implib_fallback ()\n{\n  $debug_cmd\n\n  if func_cygming_gnu_implib_p \"$1\"; then\n    # binutils import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$7' \"$1\"`\n  elif func_cygming_ms_implib_p \"$1\"; then\n    # ms-generated import library\n    sharedlib_from_linklib_result=`func_cygming_dll_for_implib_fallback_core '.idata$6' \"$1\"`\n  else\n    # unknown\n    sharedlib_from_linklib_result=\n  fi\n}\n\n\n# func_extract_an_archive dir oldlib\nfunc_extract_an_archive ()\n{\n    $debug_cmd\n\n    f_ex_an_ar_dir=$1; shift\n    f_ex_an_ar_oldlib=$1\n    if test yes = \"$lock_old_archive_extraction\"; then\n      lockfile=$f_ex_an_ar_oldlib.lock\n      until $opt_dry_run || ln \"$progpath\" \"$lockfile\" 2>/dev/null; do\n\tfunc_echo \"Waiting for $lockfile to be removed\"\n\tsleep 2\n      done\n    fi\n    func_show_eval \"(cd \\$f_ex_an_ar_dir && $AR x \\\"\\$f_ex_an_ar_oldlib\\\")\" \\\n\t\t   'stat=$?; rm -f \"$lockfile\"; exit $stat'\n    if test yes = \"$lock_old_archive_extraction\"; then\n      $opt_dry_run || rm -f \"$lockfile\"\n    fi\n    if ($AR t \"$f_ex_an_ar_oldlib\" | sort | sort -uc >/dev/null 2>&1); then\n     :\n    else\n      func_fatal_error \"object name conflicts in archive: $f_ex_an_ar_dir/$f_ex_an_ar_oldlib\"\n    fi\n}\n\n\n# func_extract_archives gentop oldlib ...\nfunc_extract_archives ()\n{\n    $debug_cmd\n\n    my_gentop=$1; shift\n    my_oldlibs=${1+\"$@\"}\n    my_oldobjs=\n    my_xlib=\n    my_xabs=\n    my_xdir=\n\n    for my_xlib in $my_oldlibs; do\n      # Extract the objects.\n      case $my_xlib in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) my_xabs=$my_xlib ;;\n\t*) my_xabs=`pwd`\"/$my_xlib\" ;;\n      esac\n      func_basename \"$my_xlib\"\n      my_xlib=$func_basename_result\n      my_xlib_u=$my_xlib\n      while :; do\n        case \" $extracted_archives \" in\n\t*\" $my_xlib_u \"*)\n\t  func_arith $extracted_serial + 1\n\t  extracted_serial=$func_arith_result\n\t  my_xlib_u=lt$extracted_serial-$my_xlib ;;\n\t*) break ;;\n\tesac\n      done\n      extracted_archives=\"$extracted_archives $my_xlib_u\"\n      my_xdir=$my_gentop/$my_xlib_u\n\n      func_mkdir_p \"$my_xdir\"\n\n      case $host in\n      *-darwin*)\n\tfunc_verbose \"Extracting $my_xabs\"\n\t# Do not bother doing anything if just a dry run\n\t$opt_dry_run || {\n\t  darwin_orig_dir=`pwd`\n\t  cd $my_xdir || exit $?\n\t  darwin_archive=$my_xabs\n\t  darwin_curdir=`pwd`\n\t  func_basename \"$darwin_archive\"\n\t  darwin_base_archive=$func_basename_result\n\t  darwin_arches=`$LIPO -info \"$darwin_archive\" 2>/dev/null | $GREP Architectures 2>/dev/null || true`\n\t  if test -n \"$darwin_arches\"; then\n\t    darwin_arches=`$ECHO \"$darwin_arches\" | $SED -e 's/.*are://'`\n\t    darwin_arch=\n\t    func_verbose \"$darwin_base_archive has multiple architectures $darwin_arches\"\n\t    for darwin_arch in  $darwin_arches; do\n\t      func_mkdir_p \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      $LIPO -thin $darwin_arch -output \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\" \"$darwin_archive\"\n\t      cd \"unfat-$$/$darwin_base_archive-$darwin_arch\"\n\t      func_extract_an_archive \"`pwd`\" \"$darwin_base_archive\"\n\t      cd \"$darwin_curdir\"\n\t      $RM \"unfat-$$/$darwin_base_archive-$darwin_arch/$darwin_base_archive\"\n\t    done # $darwin_arches\n            ## Okay now we've a bunch of thin objects, gotta fatten them up :)\n\t    darwin_filelist=`find unfat-$$ -type f -name \\*.o -print -o -name \\*.lo -print | $SED -e \"$sed_basename\" | sort -u`\n\t    darwin_file=\n\t    darwin_files=\n\t    for darwin_file in $darwin_filelist; do\n\t      darwin_files=`find unfat-$$ -name $darwin_file -print | sort | $NL2SP`\n\t      $LIPO -create -output \"$darwin_file\" $darwin_files\n\t    done # $darwin_filelist\n\t    $RM -rf unfat-$$\n\t    cd \"$darwin_orig_dir\"\n\t  else\n\t    cd $darwin_orig_dir\n\t    func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t  fi # $darwin_arches\n\t} # !$opt_dry_run\n\t;;\n      *)\n        func_extract_an_archive \"$my_xdir\" \"$my_xabs\"\n\t;;\n      esac\n      my_oldobjs=\"$my_oldobjs \"`find $my_xdir -name \\*.$objext -print -o -name \\*.lo -print | sort | $NL2SP`\n    done\n\n    func_extract_archives_result=$my_oldobjs\n}\n\n\n# func_emit_wrapper [arg=no]\n#\n# Emit a libtool wrapper script on stdout.\n# Don't directly open a file because we may want to\n# incorporate the script contents within a cygwin/mingw\n# wrapper executable.  Must ONLY be called from within\n# func_mode_link because it depends on a number of variables\n# set therein.\n#\n# ARG is the value that the WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\n# variable will take.  If 'yes', then the emitted script\n# will assume that the directory where it is stored is\n# the $objdir directory.  This is a cygwin/mingw-specific\n# behavior.\nfunc_emit_wrapper ()\n{\n\tfunc_emit_wrapper_arg1=${1-no}\n\n\t$ECHO \"\\\n#! $SHELL\n\n# $output - temporary wrapper script for $objdir/$outputname\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# The $output program cannot be directly executed until all the libtool\n# libraries that it depends on are installed.\n#\n# This wrapper script should never be moved out of the build directory.\n# If it is, it will not operate correctly.\n\n# Sed substitution that helps us do robust quoting.  It backslashifies\n# metacharacters that are still active within double-quoted strings.\nsed_quote_subst='$sed_quote_subst'\n\n# Be Bourne compatible\nif test -n \\\"\\${ZSH_VERSION+set}\\\" && (emulate sh) >/dev/null 2>&1; then\n  emulate sh\n  NULLCMD=:\n  # Zsh 3.x and 4.x performs word splitting on \\${1+\\\"\\$@\\\"}, which\n  # is contrary to our usage.  Disable this feature.\n  alias -g '\\${1+\\\"\\$@\\\"}'='\\\"\\$@\\\"'\n  setopt NO_GLOB_SUBST\nelse\n  case \\`(set -o) 2>/dev/null\\` in *posix*) set -o posix;; esac\nfi\nBIN_SH=xpg4; export BIN_SH # for Tru64\nDUALCASE=1; export DUALCASE # for MKS sh\n\n# The HP-UX ksh and POSIX shell print the target directory to stdout\n# if CDPATH is set.\n(unset CDPATH) >/dev/null 2>&1 && unset CDPATH\n\nrelink_command=\\\"$relink_command\\\"\n\n# This environment variable determines our operation mode.\nif test \\\"\\$libtool_install_magic\\\" = \\\"$magic\\\"; then\n  # install mode needs the following variables:\n  generated_by_libtool_version='$macro_version'\n  notinst_deplibs='$notinst_deplibs'\nelse\n  # When we are sourced in execute mode, \\$file and \\$ECHO are already set.\n  if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n    file=\\\"\\$0\\\"\"\n\n    qECHO=`$ECHO \"$ECHO\" | $SED \"$sed_quote_subst\"`\n    $ECHO \"\\\n\n# A function that is used when there is no print builtin or printf.\nfunc_fallback_echo ()\n{\n  eval 'cat <<_LTECHO_EOF\n\\$1\n_LTECHO_EOF'\n}\n    ECHO=\\\"$qECHO\\\"\n  fi\n\n# Very basic option parsing. These options are (a) specific to\n# the libtool wrapper, (b) are identical between the wrapper\n# /script/ and the wrapper /executable/ that is used only on\n# windows platforms, and (c) all begin with the string \"--lt-\"\n# (application programs are unlikely to have options that match\n# this pattern).\n#\n# There are only two supported options: --lt-debug and\n# --lt-dump-script. There is, deliberately, no --lt-help.\n#\n# The first argument to this parsing function should be the\n# script's $0 value, followed by \"$@\".\nlt_option_debug=\nfunc_parse_lt_options ()\n{\n  lt_script_arg0=\\$0\n  shift\n  for lt_opt\n  do\n    case \\\"\\$lt_opt\\\" in\n    --lt-debug) lt_option_debug=1 ;;\n    --lt-dump-script)\n        lt_dump_D=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%/[^/]*$%%'\\`\n        test \\\"X\\$lt_dump_D\\\" = \\\"X\\$lt_script_arg0\\\" && lt_dump_D=.\n        lt_dump_F=\\`\\$ECHO \\\"X\\$lt_script_arg0\\\" | $SED -e 's/^X//' -e 's%^.*/%%'\\`\n        cat \\\"\\$lt_dump_D/\\$lt_dump_F\\\"\n        exit 0\n      ;;\n    --lt-*)\n        \\$ECHO \\\"Unrecognized --lt- option: '\\$lt_opt'\\\" 1>&2\n        exit 1\n      ;;\n    esac\n  done\n\n  # Print the debug banner immediately:\n  if test -n \\\"\\$lt_option_debug\\\"; then\n    echo \\\"$outputname:$output:\\$LINENO: libtool wrapper (GNU $PACKAGE) $VERSION\\\" 1>&2\n  fi\n}\n\n# Used when --lt-debug. Prints its arguments to stdout\n# (redirection is the responsibility of the caller)\nfunc_lt_dump_args ()\n{\n  lt_dump_args_N=1;\n  for lt_arg\n  do\n    \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[\\$lt_dump_args_N]: \\$lt_arg\\\"\n    lt_dump_args_N=\\`expr \\$lt_dump_args_N + 1\\`\n  done\n}\n\n# Core function for launching the target application\nfunc_exec_program_core ()\n{\n\"\n  case $host in\n  # Backslashes separate directories on plain windows\n  *-*-mingw | *-*-os2* | *-cegcc*)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir\\\\\\\\\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir\\\\\\\\\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n\n  *)\n    $ECHO \"\\\n      if test -n \\\"\\$lt_option_debug\\\"; then\n        \\$ECHO \\\"$outputname:$output:\\$LINENO: newargv[0]: \\$progdir/\\$program\\\" 1>&2\n        func_lt_dump_args \\${1+\\\"\\$@\\\"} 1>&2\n      fi\n      exec \\\"\\$progdir/\\$program\\\" \\${1+\\\"\\$@\\\"}\n\"\n    ;;\n  esac\n  $ECHO \"\\\n      \\$ECHO \\\"\\$0: cannot exec \\$program \\$*\\\" 1>&2\n      exit 1\n}\n\n# A function to encapsulate launching the target application\n# Strips options in the --lt-* namespace from \\$@ and\n# launches target application with the remaining arguments.\nfunc_exec_program ()\n{\n  case \\\" \\$* \\\" in\n  *\\\\ --lt-*)\n    for lt_wr_arg\n    do\n      case \\$lt_wr_arg in\n      --lt-*) ;;\n      *) set x \\\"\\$@\\\" \\\"\\$lt_wr_arg\\\"; shift;;\n      esac\n      shift\n    done ;;\n  esac\n  func_exec_program_core \\${1+\\\"\\$@\\\"}\n}\n\n  # Parse options\n  func_parse_lt_options \\\"\\$0\\\" \\${1+\\\"\\$@\\\"}\n\n  # Find the directory that this script lives in.\n  thisdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*$%%'\\`\n  test \\\"x\\$thisdir\\\" = \\\"x\\$file\\\" && thisdir=.\n\n  # Follow symbolic links until we get to the real thisdir.\n  file=\\`ls -ld \\\"\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  while test -n \\\"\\$file\\\"; do\n    destdir=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%/[^/]*\\$%%'\\`\n\n    # If there was a directory component, then change thisdir.\n    if test \\\"x\\$destdir\\\" != \\\"x\\$file\\\"; then\n      case \\\"\\$destdir\\\" in\n      [\\\\\\\\/]* | [A-Za-z]:[\\\\\\\\/]*) thisdir=\\\"\\$destdir\\\" ;;\n      *) thisdir=\\\"\\$thisdir/\\$destdir\\\" ;;\n      esac\n    fi\n\n    file=\\`\\$ECHO \\\"\\$file\\\" | $SED 's%^.*/%%'\\`\n    file=\\`ls -ld \\\"\\$thisdir/\\$file\\\" | $SED -n 's/.*-> //p'\\`\n  done\n\n  # Usually 'no', except on cygwin/mingw when embedded into\n  # the cwrapper.\n  WRAPPER_SCRIPT_BELONGS_IN_OBJDIR=$func_emit_wrapper_arg1\n  if test \\\"\\$WRAPPER_SCRIPT_BELONGS_IN_OBJDIR\\\" = \\\"yes\\\"; then\n    # special case for '.'\n    if test \\\"\\$thisdir\\\" = \\\".\\\"; then\n      thisdir=\\`pwd\\`\n    fi\n    # remove .libs from thisdir\n    case \\\"\\$thisdir\\\" in\n    *[\\\\\\\\/]$objdir ) thisdir=\\`\\$ECHO \\\"\\$thisdir\\\" | $SED 's%[\\\\\\\\/][^\\\\\\\\/]*$%%'\\` ;;\n    $objdir )   thisdir=. ;;\n    esac\n  fi\n\n  # Try to get the absolute directory name.\n  absdir=\\`cd \\\"\\$thisdir\\\" && pwd\\`\n  test -n \\\"\\$absdir\\\" && thisdir=\\\"\\$absdir\\\"\n\"\n\n\tif test yes = \"$fast_install\"; then\n\t  $ECHO \"\\\n  program=lt-'$outputname'$exeext\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\n  if test ! -f \\\"\\$progdir/\\$program\\\" ||\n     { file=\\`ls -1dt \\\"\\$progdir/\\$program\\\" \\\"\\$progdir/../\\$program\\\" 2>/dev/null | $SED 1q\\`; \\\\\n       test \\\"X\\$file\\\" != \\\"X\\$progdir/\\$program\\\"; }; then\n\n    file=\\\"\\$\\$-\\$program\\\"\n\n    if test ! -d \\\"\\$progdir\\\"; then\n      $MKDIR \\\"\\$progdir\\\"\n    else\n      $RM \\\"\\$progdir/\\$file\\\"\n    fi\"\n\n\t  $ECHO \"\\\n\n    # relink executable if necessary\n    if test -n \\\"\\$relink_command\\\"; then\n      if relink_command_output=\\`eval \\$relink_command 2>&1\\`; then :\n      else\n\t\\$ECHO \\\"\\$relink_command_output\\\" >&2\n\t$RM \\\"\\$progdir/\\$file\\\"\n\texit 1\n      fi\n    fi\n\n    $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\" 2>/dev/null ||\n    { $RM \\\"\\$progdir/\\$program\\\";\n      $MV \\\"\\$progdir/\\$file\\\" \\\"\\$progdir/\\$program\\\"; }\n    $RM \\\"\\$progdir/\\$file\\\"\n  fi\"\n\telse\n\t  $ECHO \"\\\n  program='$outputname'\n  progdir=\\\"\\$thisdir/$objdir\\\"\n\"\n\tfi\n\n\t$ECHO \"\\\n\n  if test -f \\\"\\$progdir/\\$program\\\"; then\"\n\n\t# fixup the dll searchpath if we need to.\n\t#\n\t# Fix the DLL searchpath if we need to.  Do this before prepending\n\t# to shlibpath, because on Windows, both are PATH and uninstalled\n\t# libraries must come first.\n\tif test -n \"$dllsearchpath\"; then\n\t  $ECHO \"\\\n    # Add the dll search path components to the executable PATH\n    PATH=$dllsearchpath:\\$PATH\n\"\n\tfi\n\n\t# Export our shlibpath_var if we have one.\n\tif test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n\t  $ECHO \"\\\n    # Add our own library path to $shlibpath_var\n    $shlibpath_var=\\\"$temp_rpath\\$$shlibpath_var\\\"\n\n    # Some systems cannot cope with colon-terminated $shlibpath_var\n    # The second colon is a workaround for a bug in BeOS R4 sed\n    $shlibpath_var=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" | $SED 's/::*\\$//'\\`\n\n    export $shlibpath_var\n\"\n\tfi\n\n\t$ECHO \"\\\n    if test \\\"\\$libtool_execute_magic\\\" != \\\"$magic\\\"; then\n      # Run the actual program with our arguments.\n      func_exec_program \\${1+\\\"\\$@\\\"}\n    fi\n  else\n    # The program doesn't exist.\n    \\$ECHO \\\"\\$0: error: '\\$progdir/\\$program' does not exist\\\" 1>&2\n    \\$ECHO \\\"This script is just a wrapper for \\$program.\\\" 1>&2\n    \\$ECHO \\\"See the $PACKAGE documentation for more information.\\\" 1>&2\n    exit 1\n  fi\nfi\\\n\"\n}\n\n\n# func_emit_cwrapperexe_src\n# emit the source code for a wrapper executable on stdout\n# Must ONLY be called from within func_mode_link because\n# it depends on a number of variable set therein.\nfunc_emit_cwrapperexe_src ()\n{\n\tcat <<EOF\n\n/* $cwrappersource - temporary wrapper executable for $objdir/$outputname\n   Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n\n   The $output program cannot be directly executed until all the libtool\n   libraries that it depends on are installed.\n\n   This wrapper executable should never be moved out of the build directory.\n   If it is, it will not operate correctly.\n*/\nEOF\n\t    cat <<\"EOF\"\n#ifdef _MSC_VER\n# define _CRT_SECURE_NO_DEPRECATE 1\n#endif\n#include <stdio.h>\n#include <stdlib.h>\n#ifdef _MSC_VER\n# include <direct.h>\n# include <process.h>\n# include <io.h>\n#else\n# include <unistd.h>\n# include <stdint.h>\n# ifdef __CYGWIN__\n#  include <io.h>\n# endif\n#endif\n#include <malloc.h>\n#include <stdarg.h>\n#include <assert.h>\n#include <string.h>\n#include <ctype.h>\n#include <errno.h>\n#include <fcntl.h>\n#include <sys/stat.h>\n\n#define STREQ(s1, s2) (strcmp ((s1), (s2)) == 0)\n\n/* declarations of non-ANSI functions */\n#if defined __MINGW32__\n# ifdef __STRICT_ANSI__\nint _putenv (const char *);\n# endif\n#elif defined __CYGWIN__\n# ifdef __STRICT_ANSI__\nchar *realpath (const char *, char *);\nint putenv (char *);\nint setenv (const char *, const char *, int);\n# endif\n/* #elif defined other_platform || defined ... */\n#endif\n\n/* portability defines, excluding path handling macros */\n#if defined _MSC_VER\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n# define S_IXUSR _S_IEXEC\n#elif defined __MINGW32__\n# define setmode _setmode\n# define stat    _stat\n# define chmod   _chmod\n# define getcwd  _getcwd\n# define putenv  _putenv\n#elif defined __CYGWIN__\n# define HAVE_SETENV\n# define FOPEN_WB \"wb\"\n/* #elif defined other platforms ... */\n#endif\n\n#if defined PATH_MAX\n# define LT_PATHMAX PATH_MAX\n#elif defined MAXPATHLEN\n# define LT_PATHMAX MAXPATHLEN\n#else\n# define LT_PATHMAX 1024\n#endif\n\n#ifndef S_IXOTH\n# define S_IXOTH 0\n#endif\n#ifndef S_IXGRP\n# define S_IXGRP 0\n#endif\n\n/* path handling portability macros */\n#ifndef DIR_SEPARATOR\n# define DIR_SEPARATOR '/'\n# define PATH_SEPARATOR ':'\n#endif\n\n#if defined _WIN32 || defined __MSDOS__ || defined __DJGPP__ || \\\n  defined __OS2__\n# define HAVE_DOS_BASED_FILE_SYSTEM\n# define FOPEN_WB \"wb\"\n# ifndef DIR_SEPARATOR_2\n#  define DIR_SEPARATOR_2 '\\\\'\n# endif\n# ifndef PATH_SEPARATOR_2\n#  define PATH_SEPARATOR_2 ';'\n# endif\n#endif\n\n#ifndef DIR_SEPARATOR_2\n# define IS_DIR_SEPARATOR(ch) ((ch) == DIR_SEPARATOR)\n#else /* DIR_SEPARATOR_2 */\n# define IS_DIR_SEPARATOR(ch) \\\n\t(((ch) == DIR_SEPARATOR) || ((ch) == DIR_SEPARATOR_2))\n#endif /* DIR_SEPARATOR_2 */\n\n#ifndef PATH_SEPARATOR_2\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR)\n#else /* PATH_SEPARATOR_2 */\n# define IS_PATH_SEPARATOR(ch) ((ch) == PATH_SEPARATOR_2)\n#endif /* PATH_SEPARATOR_2 */\n\n#ifndef FOPEN_WB\n# define FOPEN_WB \"w\"\n#endif\n#ifndef _O_BINARY\n# define _O_BINARY 0\n#endif\n\n#define XMALLOC(type, num)      ((type *) xmalloc ((num) * sizeof(type)))\n#define XFREE(stale) do { \\\n  if (stale) { free (stale); stale = 0; } \\\n} while (0)\n\n#if defined LT_DEBUGWRAPPER\nstatic int lt_debug = 1;\n#else\nstatic int lt_debug = 0;\n#endif\n\nconst char *program_name = \"libtool-wrapper\"; /* in case xstrdup fails */\n\nvoid *xmalloc (size_t num);\nchar *xstrdup (const char *string);\nconst char *base_name (const char *name);\nchar *find_executable (const char *wrapper);\nchar *chase_symlinks (const char *pathspec);\nint make_executable (const char *path);\nint check_executable (const char *path);\nchar *strendzap (char *str, const char *pat);\nvoid lt_debugprintf (const char *file, int line, const char *fmt, ...);\nvoid lt_fatal (const char *file, int line, const char *message, ...);\nstatic const char *nonnull (const char *s);\nstatic const char *nonempty (const char *s);\nvoid lt_setenv (const char *name, const char *value);\nchar *lt_extend_str (const char *orig_value, const char *add, int to_end);\nvoid lt_update_exe_path (const char *name, const char *value);\nvoid lt_update_lib_path (const char *name, const char *value);\nchar **prepare_spawn (char **argv);\nvoid lt_dump_script (FILE *f);\nEOF\n\n\t    cat <<EOF\n#if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 5)\n# define externally_visible volatile\n#else\n# define externally_visible __attribute__((externally_visible)) volatile\n#endif\nexternally_visible const char * MAGIC_EXE = \"$magic_exe\";\nconst char * LIB_PATH_VARNAME = \"$shlibpath_var\";\nEOF\n\n\t    if test yes = \"$shlibpath_overrides_runpath\" && test -n \"$shlibpath_var\" && test -n \"$temp_rpath\"; then\n              func_to_host_path \"$temp_rpath\"\n\t      cat <<EOF\nconst char * LIB_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * LIB_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test -n \"$dllsearchpath\"; then\n              func_to_host_path \"$dllsearchpath:\"\n\t      cat <<EOF\nconst char * EXE_PATH_VARNAME = \"PATH\";\nconst char * EXE_PATH_VALUE   = \"$func_to_host_path_result\";\nEOF\n\t    else\n\t      cat <<\"EOF\"\nconst char * EXE_PATH_VARNAME = \"\";\nconst char * EXE_PATH_VALUE   = \"\";\nEOF\n\t    fi\n\n\t    if test yes = \"$fast_install\"; then\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"lt-$outputname\"; /* hopefully, no .exe */\nEOF\n\t    else\n\t      cat <<EOF\nconst char * TARGET_PROGRAM_NAME = \"$outputname\"; /* hopefully, no .exe */\nEOF\n\t    fi\n\n\n\t    cat <<\"EOF\"\n\n#define LTWRAPPER_OPTION_PREFIX         \"--lt-\"\n\nstatic const char *ltwrapper_option_prefix = LTWRAPPER_OPTION_PREFIX;\nstatic const char *dumpscript_opt       = LTWRAPPER_OPTION_PREFIX \"dump-script\";\nstatic const char *debug_opt            = LTWRAPPER_OPTION_PREFIX \"debug\";\n\nint\nmain (int argc, char *argv[])\n{\n  char **newargz;\n  int  newargc;\n  char *tmp_pathspec;\n  char *actual_cwrapper_path;\n  char *actual_cwrapper_name;\n  char *target_name;\n  char *lt_argv_zero;\n  int rval = 127;\n\n  int i;\n\n  program_name = (char *) xstrdup (base_name (argv[0]));\n  newargz = XMALLOC (char *, (size_t) argc + 1);\n\n  /* very simple arg parsing; don't want to rely on getopt\n   * also, copy all non cwrapper options to newargz, except\n   * argz[0], which is handled differently\n   */\n  newargc=0;\n  for (i = 1; i < argc; i++)\n    {\n      if (STREQ (argv[i], dumpscript_opt))\n\t{\nEOF\n\t    case $host in\n\t      *mingw* | *cygwin* )\n\t\t# make stdout use \"unix\" line endings\n\t\techo \"          setmode(1,_O_BINARY);\"\n\t\t;;\n\t      esac\n\n\t    cat <<\"EOF\"\n\t  lt_dump_script (stdout);\n\t  return 0;\n\t}\n      if (STREQ (argv[i], debug_opt))\n\t{\n          lt_debug = 1;\n          continue;\n\t}\n      if (STREQ (argv[i], ltwrapper_option_prefix))\n        {\n          /* however, if there is an option in the LTWRAPPER_OPTION_PREFIX\n             namespace, but it is not one of the ones we know about and\n             have already dealt with, above (inluding dump-script), then\n             report an error. Otherwise, targets might begin to believe\n             they are allowed to use options in the LTWRAPPER_OPTION_PREFIX\n             namespace. The first time any user complains about this, we'll\n             need to make LTWRAPPER_OPTION_PREFIX a configure-time option\n             or a configure.ac-settable value.\n           */\n          lt_fatal (__FILE__, __LINE__,\n\t\t    \"unrecognized %s option: '%s'\",\n                    ltwrapper_option_prefix, argv[i]);\n        }\n      /* otherwise ... */\n      newargz[++newargc] = xstrdup (argv[i]);\n    }\n  newargz[++newargc] = NULL;\n\nEOF\n\t    cat <<EOF\n  /* The GNU banner must be the first non-error debug message */\n  lt_debugprintf (__FILE__, __LINE__, \"libtool wrapper (GNU $PACKAGE) $VERSION\\n\");\nEOF\n\t    cat <<\"EOF\"\n  lt_debugprintf (__FILE__, __LINE__, \"(main) argv[0]: %s\\n\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__, \"(main) program_name: %s\\n\", program_name);\n\n  tmp_pathspec = find_executable (argv[0]);\n  if (tmp_pathspec == NULL)\n    lt_fatal (__FILE__, __LINE__, \"couldn't find %s\", argv[0]);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (before symlink chase) at: %s\\n\",\n\t\t  tmp_pathspec);\n\n  actual_cwrapper_path = chase_symlinks (tmp_pathspec);\n  lt_debugprintf (__FILE__, __LINE__,\n                  \"(main) found exe (after symlink chase) at: %s\\n\",\n\t\t  actual_cwrapper_path);\n  XFREE (tmp_pathspec);\n\n  actual_cwrapper_name = xstrdup (base_name (actual_cwrapper_path));\n  strendzap (actual_cwrapper_path, actual_cwrapper_name);\n\n  /* wrapper name transforms */\n  strendzap (actual_cwrapper_name, \".exe\");\n  tmp_pathspec = lt_extend_str (actual_cwrapper_name, \".exe\", 1);\n  XFREE (actual_cwrapper_name);\n  actual_cwrapper_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  /* target_name transforms -- use actual target program name; might have lt- prefix */\n  target_name = xstrdup (base_name (TARGET_PROGRAM_NAME));\n  strendzap (target_name, \".exe\");\n  tmp_pathspec = lt_extend_str (target_name, \".exe\", 1);\n  XFREE (target_name);\n  target_name = tmp_pathspec;\n  tmp_pathspec = 0;\n\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(main) libtool target name: %s\\n\",\n\t\t  target_name);\nEOF\n\n\t    cat <<EOF\n  newargz[0] =\n    XMALLOC (char, (strlen (actual_cwrapper_path) +\n\t\t    strlen (\"$objdir\") + 1 + strlen (actual_cwrapper_name) + 1));\n  strcpy (newargz[0], actual_cwrapper_path);\n  strcat (newargz[0], \"$objdir\");\n  strcat (newargz[0], \"/\");\nEOF\n\n\t    cat <<\"EOF\"\n  /* stop here, and copy so we don't have to do this twice */\n  tmp_pathspec = xstrdup (newargz[0]);\n\n  /* do NOT want the lt- prefix here, so use actual_cwrapper_name */\n  strcat (newargz[0], actual_cwrapper_name);\n\n  /* DO want the lt- prefix here if it exists, so use target_name */\n  lt_argv_zero = lt_extend_str (tmp_pathspec, target_name, 1);\n  XFREE (tmp_pathspec);\n  tmp_pathspec = NULL;\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t    cat <<\"EOF\"\n  {\n    char* p;\n    while ((p = strchr (newargz[0], '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n    while ((p = strchr (lt_argv_zero, '\\\\')) != NULL)\n      {\n\t*p = '/';\n      }\n  }\nEOF\n\t    ;;\n\t    esac\n\n\t    cat <<\"EOF\"\n  XFREE (target_name);\n  XFREE (actual_cwrapper_path);\n  XFREE (actual_cwrapper_name);\n\n  lt_setenv (\"BIN_SH\", \"xpg4\"); /* for Tru64 */\n  lt_setenv (\"DUALCASE\", \"1\");  /* for MSK sh */\n  /* Update the DLL searchpath.  EXE_PATH_VALUE ($dllsearchpath) must\n     be prepended before (that is, appear after) LIB_PATH_VALUE ($temp_rpath)\n     because on Windows, both *_VARNAMEs are PATH but uninstalled\n     libraries must come first. */\n  lt_update_exe_path (EXE_PATH_VARNAME, EXE_PATH_VALUE);\n  lt_update_lib_path (LIB_PATH_VARNAME, LIB_PATH_VALUE);\n\n  lt_debugprintf (__FILE__, __LINE__, \"(main) lt_argv_zero: %s\\n\",\n\t\t  nonnull (lt_argv_zero));\n  for (i = 0; i < newargc; i++)\n    {\n      lt_debugprintf (__FILE__, __LINE__, \"(main) newargz[%d]: %s\\n\",\n\t\t      i, nonnull (newargz[i]));\n    }\n\nEOF\n\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n  /* execv doesn't actually work on mingw as expected on unix */\n  newargz = prepare_spawn (newargz);\n  rval = (int) _spawnv (_P_WAIT, lt_argv_zero, (const char * const *) newargz);\n  if (rval == -1)\n    {\n      /* failed to start process */\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"(main) failed to launch target \\\"%s\\\": %s\\n\",\n\t\t      lt_argv_zero, nonnull (strerror (errno)));\n      return 127;\n    }\n  return rval;\nEOF\n\t\t;;\n\t      *)\n\t\tcat <<\"EOF\"\n  execv (lt_argv_zero, newargz);\n  return rval; /* =127, but avoids unused variable warning */\nEOF\n\t\t;;\n\t    esac\n\n\t    cat <<\"EOF\"\n}\n\nvoid *\nxmalloc (size_t num)\n{\n  void *p = (void *) malloc (num);\n  if (!p)\n    lt_fatal (__FILE__, __LINE__, \"memory exhausted\");\n\n  return p;\n}\n\nchar *\nxstrdup (const char *string)\n{\n  return string ? strcpy ((char *) xmalloc (strlen (string) + 1),\n\t\t\t  string) : NULL;\n}\n\nconst char *\nbase_name (const char *name)\n{\n  const char *base;\n\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  /* Skip over the disk name in MSDOS pathnames. */\n  if (isalpha ((unsigned char) name[0]) && name[1] == ':')\n    name += 2;\n#endif\n\n  for (base = name; *name; name++)\n    if (IS_DIR_SEPARATOR (*name))\n      base = name + 1;\n  return base;\n}\n\nint\ncheck_executable (const char *path)\n{\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(check_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if ((stat (path, &st) >= 0)\n      && (st.st_mode & (S_IXUSR | S_IXGRP | S_IXOTH)))\n    return 1;\n  else\n    return 0;\n}\n\nint\nmake_executable (const char *path)\n{\n  int rval = 0;\n  struct stat st;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(make_executable): %s\\n\",\n                  nonempty (path));\n  if ((!path) || (!*path))\n    return 0;\n\n  if (stat (path, &st) >= 0)\n    {\n      rval = chmod (path, st.st_mode | S_IXOTH | S_IXGRP | S_IXUSR);\n    }\n  return rval;\n}\n\n/* Searches for the full path of the wrapper.  Returns\n   newly allocated full path name if found, NULL otherwise\n   Does not chase symlinks, even on platforms that support them.\n*/\nchar *\nfind_executable (const char *wrapper)\n{\n  int has_slash = 0;\n  const char *p;\n  const char *p_next;\n  /* static buffer for getcwd */\n  char tmp[LT_PATHMAX + 1];\n  size_t tmp_len;\n  char *concat_name;\n\n  lt_debugprintf (__FILE__, __LINE__, \"(find_executable): %s\\n\",\n                  nonempty (wrapper));\n\n  if ((wrapper == NULL) || (*wrapper == '\\0'))\n    return NULL;\n\n  /* Absolute path? */\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n  if (isalpha ((unsigned char) wrapper[0]) && wrapper[1] == ':')\n    {\n      concat_name = xstrdup (wrapper);\n      if (check_executable (concat_name))\n\treturn concat_name;\n      XFREE (concat_name);\n    }\n  else\n    {\n#endif\n      if (IS_DIR_SEPARATOR (wrapper[0]))\n\t{\n\t  concat_name = xstrdup (wrapper);\n\t  if (check_executable (concat_name))\n\t    return concat_name;\n\t  XFREE (concat_name);\n\t}\n#if defined HAVE_DOS_BASED_FILE_SYSTEM\n    }\n#endif\n\n  for (p = wrapper; *p; p++)\n    if (*p == '/')\n      {\n\thas_slash = 1;\n\tbreak;\n      }\n  if (!has_slash)\n    {\n      /* no slashes; search PATH */\n      const char *path = getenv (\"PATH\");\n      if (path != NULL)\n\t{\n\t  for (p = path; *p; p = p_next)\n\t    {\n\t      const char *q;\n\t      size_t p_len;\n\t      for (q = p; *q; q++)\n\t\tif (IS_PATH_SEPARATOR (*q))\n\t\t  break;\n\t      p_len = (size_t) (q - p);\n\t      p_next = (*q == '\\0' ? q : q + 1);\n\t      if (p_len == 0)\n\t\t{\n\t\t  /* empty path: current directory */\n\t\t  if (getcwd (tmp, LT_PATHMAX) == NULL)\n\t\t    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n                              nonnull (strerror (errno)));\n\t\t  tmp_len = strlen (tmp);\n\t\t  concat_name =\n\t\t    XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, tmp, tmp_len);\n\t\t  concat_name[tmp_len] = '/';\n\t\t  strcpy (concat_name + tmp_len + 1, wrapper);\n\t\t}\n\t      else\n\t\t{\n\t\t  concat_name =\n\t\t    XMALLOC (char, p_len + 1 + strlen (wrapper) + 1);\n\t\t  memcpy (concat_name, p, p_len);\n\t\t  concat_name[p_len] = '/';\n\t\t  strcpy (concat_name + p_len + 1, wrapper);\n\t\t}\n\t      if (check_executable (concat_name))\n\t\treturn concat_name;\n\t      XFREE (concat_name);\n\t    }\n\t}\n      /* not found in PATH; assume curdir */\n    }\n  /* Relative path | not found in path: prepend cwd */\n  if (getcwd (tmp, LT_PATHMAX) == NULL)\n    lt_fatal (__FILE__, __LINE__, \"getcwd failed: %s\",\n              nonnull (strerror (errno)));\n  tmp_len = strlen (tmp);\n  concat_name = XMALLOC (char, tmp_len + 1 + strlen (wrapper) + 1);\n  memcpy (concat_name, tmp, tmp_len);\n  concat_name[tmp_len] = '/';\n  strcpy (concat_name + tmp_len + 1, wrapper);\n\n  if (check_executable (concat_name))\n    return concat_name;\n  XFREE (concat_name);\n  return NULL;\n}\n\nchar *\nchase_symlinks (const char *pathspec)\n{\n#ifndef S_ISLNK\n  return xstrdup (pathspec);\n#else\n  char buf[LT_PATHMAX];\n  struct stat s;\n  char *tmp_pathspec = xstrdup (pathspec);\n  char *p;\n  int has_symlinks = 0;\n  while (strlen (tmp_pathspec) && !has_symlinks)\n    {\n      lt_debugprintf (__FILE__, __LINE__,\n\t\t      \"checking path component for symlinks: %s\\n\",\n\t\t      tmp_pathspec);\n      if (lstat (tmp_pathspec, &s) == 0)\n\t{\n\t  if (S_ISLNK (s.st_mode) != 0)\n\t    {\n\t      has_symlinks = 1;\n\t      break;\n\t    }\n\n\t  /* search backwards for last DIR_SEPARATOR */\n\t  p = tmp_pathspec + strlen (tmp_pathspec) - 1;\n\t  while ((p > tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    p--;\n\t  if ((p == tmp_pathspec) && (!IS_DIR_SEPARATOR (*p)))\n\t    {\n\t      /* no more DIR_SEPARATORS left */\n\t      break;\n\t    }\n\t  *p = '\\0';\n\t}\n      else\n\t{\n\t  lt_fatal (__FILE__, __LINE__,\n\t\t    \"error accessing file \\\"%s\\\": %s\",\n\t\t    tmp_pathspec, nonnull (strerror (errno)));\n\t}\n    }\n  XFREE (tmp_pathspec);\n\n  if (!has_symlinks)\n    {\n      return xstrdup (pathspec);\n    }\n\n  tmp_pathspec = realpath (pathspec, buf);\n  if (tmp_pathspec == 0)\n    {\n      lt_fatal (__FILE__, __LINE__,\n\t\t\"could not follow symlinks for %s\", pathspec);\n    }\n  return xstrdup (tmp_pathspec);\n#endif\n}\n\nchar *\nstrendzap (char *str, const char *pat)\n{\n  size_t len, patlen;\n\n  assert (str != NULL);\n  assert (pat != NULL);\n\n  len = strlen (str);\n  patlen = strlen (pat);\n\n  if (patlen <= len)\n    {\n      str += len - patlen;\n      if (STREQ (str, pat))\n\t*str = '\\0';\n    }\n  return str;\n}\n\nvoid\nlt_debugprintf (const char *file, int line, const char *fmt, ...)\n{\n  va_list args;\n  if (lt_debug)\n    {\n      (void) fprintf (stderr, \"%s:%s:%d: \", program_name, file, line);\n      va_start (args, fmt);\n      (void) vfprintf (stderr, fmt, args);\n      va_end (args);\n    }\n}\n\nstatic void\nlt_error_core (int exit_status, const char *file,\n\t       int line, const char *mode,\n\t       const char *message, va_list ap)\n{\n  fprintf (stderr, \"%s:%s:%d: %s: \", program_name, file, line, mode);\n  vfprintf (stderr, message, ap);\n  fprintf (stderr, \".\\n\");\n\n  if (exit_status >= 0)\n    exit (exit_status);\n}\n\nvoid\nlt_fatal (const char *file, int line, const char *message, ...)\n{\n  va_list ap;\n  va_start (ap, message);\n  lt_error_core (EXIT_FAILURE, file, line, \"FATAL\", message, ap);\n  va_end (ap);\n}\n\nstatic const char *\nnonnull (const char *s)\n{\n  return s ? s : \"(null)\";\n}\n\nstatic const char *\nnonempty (const char *s)\n{\n  return (s && !*s) ? \"(empty)\" : nonnull (s);\n}\n\nvoid\nlt_setenv (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_setenv) setting '%s' to '%s'\\n\",\n                  nonnull (name), nonnull (value));\n  {\n#ifdef HAVE_SETENV\n    /* always make a copy, for consistency with !HAVE_SETENV */\n    char *str = xstrdup (value);\n    setenv (name, str, 1);\n#else\n    size_t len = strlen (name) + 1 + strlen (value) + 1;\n    char *str = XMALLOC (char, len);\n    sprintf (str, \"%s=%s\", name, value);\n    if (putenv (str) != EXIT_SUCCESS)\n      {\n        XFREE (str);\n      }\n#endif\n  }\n}\n\nchar *\nlt_extend_str (const char *orig_value, const char *add, int to_end)\n{\n  char *new_value;\n  if (orig_value && *orig_value)\n    {\n      size_t orig_value_len = strlen (orig_value);\n      size_t add_len = strlen (add);\n      new_value = XMALLOC (char, add_len + orig_value_len + 1);\n      if (to_end)\n        {\n          strcpy (new_value, orig_value);\n          strcpy (new_value + orig_value_len, add);\n        }\n      else\n        {\n          strcpy (new_value, add);\n          strcpy (new_value + add_len, orig_value);\n        }\n    }\n  else\n    {\n      new_value = xstrdup (add);\n    }\n  return new_value;\n}\n\nvoid\nlt_update_exe_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_exe_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      /* some systems can't cope with a ':'-terminated path #' */\n      size_t len = strlen (new_value);\n      while ((len > 0) && IS_PATH_SEPARATOR (new_value[len-1]))\n        {\n          new_value[--len] = '\\0';\n        }\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nvoid\nlt_update_lib_path (const char *name, const char *value)\n{\n  lt_debugprintf (__FILE__, __LINE__,\n\t\t  \"(lt_update_lib_path) modifying '%s' by prepending '%s'\\n\",\n                  nonnull (name), nonnull (value));\n\n  if (name && *name && value && *value)\n    {\n      char *new_value = lt_extend_str (getenv (name), value, 0);\n      lt_setenv (name, new_value);\n      XFREE (new_value);\n    }\n}\n\nEOF\n\t    case $host_os in\n\t      mingw*)\n\t\tcat <<\"EOF\"\n\n/* Prepares an argument vector before calling spawn().\n   Note that spawn() does not by itself call the command interpreter\n     (getenv (\"COMSPEC\") != NULL ? getenv (\"COMSPEC\") :\n      ({ OSVERSIONINFO v; v.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);\n         GetVersionEx(&v);\n         v.dwPlatformId == VER_PLATFORM_WIN32_NT;\n      }) ? \"cmd.exe\" : \"command.com\").\n   Instead it simply concatenates the arguments, separated by ' ', and calls\n   CreateProcess().  We must quote the arguments since Win32 CreateProcess()\n   interprets characters like ' ', '\\t', '\\\\', '\"' (but not '<' and '>') in a\n   special way:\n   - Space and tab are interpreted as delimiters. They are not treated as\n     delimiters if they are surrounded by double quotes: \"...\".\n   - Unescaped double quotes are removed from the input. Their only effect is\n     that within double quotes, space and tab are treated like normal\n     characters.\n   - Backslashes not followed by double quotes are not special.\n   - But 2*n+1 backslashes followed by a double quote become\n     n backslashes followed by a double quote (n >= 0):\n       \\\" -> \"\n       \\\\\\\" -> \\\"\n       \\\\\\\\\\\" -> \\\\\"\n */\n#define SHELL_SPECIAL_CHARS \"\\\"\\\\ \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\n#define SHELL_SPACE_CHARS \" \\001\\002\\003\\004\\005\\006\\007\\010\\011\\012\\013\\014\\015\\016\\017\\020\\021\\022\\023\\024\\025\\026\\027\\030\\031\\032\\033\\034\\035\\036\\037\"\nchar **\nprepare_spawn (char **argv)\n{\n  size_t argc;\n  char **new_argv;\n  size_t i;\n\n  /* Count number of arguments.  */\n  for (argc = 0; argv[argc] != NULL; argc++)\n    ;\n\n  /* Allocate new argument vector.  */\n  new_argv = XMALLOC (char *, argc + 1);\n\n  /* Put quoted arguments into the new argument vector.  */\n  for (i = 0; i < argc; i++)\n    {\n      const char *string = argv[i];\n\n      if (string[0] == '\\0')\n\tnew_argv[i] = xstrdup (\"\\\"\\\"\");\n      else if (strpbrk (string, SHELL_SPECIAL_CHARS) != NULL)\n\t{\n\t  int quote_around = (strpbrk (string, SHELL_SPACE_CHARS) != NULL);\n\t  size_t length;\n\t  unsigned int backslashes;\n\t  const char *s;\n\t  char *quoted_string;\n\t  char *p;\n\n\t  length = 0;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    length++;\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\tlength += backslashes + 1;\n\t      length++;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    length += backslashes + 1;\n\n\t  quoted_string = XMALLOC (char, length + 1);\n\n\t  p = quoted_string;\n\t  backslashes = 0;\n\t  if (quote_around)\n\t    *p++ = '\"';\n\t  for (s = string; *s != '\\0'; s++)\n\t    {\n\t      char c = *s;\n\t      if (c == '\"')\n\t\t{\n\t\t  unsigned int j;\n\t\t  for (j = backslashes + 1; j > 0; j--)\n\t\t    *p++ = '\\\\';\n\t\t}\n\t      *p++ = c;\n\t      if (c == '\\\\')\n\t\tbackslashes++;\n\t      else\n\t\tbackslashes = 0;\n\t    }\n\t  if (quote_around)\n\t    {\n\t      unsigned int j;\n\t      for (j = backslashes; j > 0; j--)\n\t\t*p++ = '\\\\';\n\t      *p++ = '\"';\n\t    }\n\t  *p = '\\0';\n\n\t  new_argv[i] = quoted_string;\n\t}\n      else\n\tnew_argv[i] = (char *) string;\n    }\n  new_argv[argc] = NULL;\n\n  return new_argv;\n}\nEOF\n\t\t;;\n\t    esac\n\n            cat <<\"EOF\"\nvoid lt_dump_script (FILE* f)\n{\nEOF\n\t    func_emit_wrapper yes |\n\t      $SED -n -e '\ns/^\\(.\\{79\\}\\)\\(..*\\)/\\1\\\n\\2/\nh\ns/\\([\\\\\"]\\)/\\\\\\1/g\ns/$/\\\\n/\ns/\\([^\\n]*\\).*/  fputs (\"\\1\", f);/p\ng\nD'\n            cat <<\"EOF\"\n}\nEOF\n}\n# end: func_emit_cwrapperexe_src\n\n# func_win32_import_lib_p ARG\n# True if ARG is an import lib, as indicated by $file_magic_cmd\nfunc_win32_import_lib_p ()\n{\n    $debug_cmd\n\n    case `eval $file_magic_cmd \\\"\\$1\\\" 2>/dev/null | $SED -e 10q` in\n    *import*) : ;;\n    *) false ;;\n    esac\n}\n\n# func_suncc_cstd_abi\n# !!ONLY CALL THIS FOR SUN CC AFTER $compile_command IS FULLY EXPANDED!!\n# Several compiler flags select an ABI that is incompatible with the\n# Cstd library. Avoid specifying it if any are in CXXFLAGS.\nfunc_suncc_cstd_abi ()\n{\n    $debug_cmd\n\n    case \" $compile_command \" in\n    *\" -compat=g \"*|*\\ -std=c++[0-9][0-9]\\ *|*\" -library=stdcxx4 \"*|*\" -library=stlport4 \"*)\n      suncc_use_cstd_abi=no\n      ;;\n    *)\n      suncc_use_cstd_abi=yes\n      ;;\n    esac\n}\n\n# func_mode_link arg...\nfunc_mode_link ()\n{\n    $debug_cmd\n\n    case $host in\n    *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n      # It is impossible to link a dll without this setting, and\n      # we shouldn't force the makefile maintainer to figure out\n      # what system we are compiling for in order to pass an extra\n      # flag for every libtool invocation.\n      # allow_undefined=no\n\n      # FIXME: Unfortunately, there are problems with the above when trying\n      # to make a dll that has undefined symbols, in which case not\n      # even a static library is built.  For now, we need to specify\n      # -no-undefined on the libtool link line when we can be certain\n      # that all symbols are satisfied, otherwise we get a static library.\n      allow_undefined=yes\n      ;;\n    *)\n      allow_undefined=yes\n      ;;\n    esac\n    libtool_args=$nonopt\n    base_compile=\"$nonopt $@\"\n    compile_command=$nonopt\n    finalize_command=$nonopt\n\n    compile_rpath=\n    finalize_rpath=\n    compile_shlibpath=\n    finalize_shlibpath=\n    convenience=\n    old_convenience=\n    deplibs=\n    old_deplibs=\n    compiler_flags=\n    linker_flags=\n    dllsearchpath=\n    lib_search_path=`pwd`\n    inst_prefix_dir=\n    new_inherited_linker_flags=\n\n    avoid_version=no\n    bindir=\n    dlfiles=\n    dlprefiles=\n    dlself=no\n    export_dynamic=no\n    export_symbols=\n    export_symbols_regex=\n    generated=\n    libobjs=\n    ltlibs=\n    module=no\n    no_install=no\n    objs=\n    os2dllname=\n    non_pic_objects=\n    precious_files_regex=\n    prefer_static_libs=no\n    preload=false\n    prev=\n    prevarg=\n    release=\n    rpath=\n    xrpath=\n    perm_rpath=\n    temp_rpath=\n    thread_safe=no\n    vinfo=\n    vinfo_number=no\n    weak_libs=\n    single_module=$wl-single_module\n    func_infer_tag $base_compile\n\n    # We need to know -static, to get the right output filenames.\n    for arg\n    do\n      case $arg in\n      -shared)\n\ttest yes != \"$build_libtool_libs\" \\\n\t  && func_fatal_configuration \"cannot build a shared library\"\n\tbuild_old_libs=no\n\tbreak\n\t;;\n      -all-static | -static | -static-libtool-libs)\n\tcase $arg in\n\t-all-static)\n\t  if test yes = \"$build_libtool_libs\" && test -z \"$link_static_flag\"; then\n\t    func_warning \"complete static linking is impossible in this configuration\"\n\t  fi\n\t  if test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\t-static)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=built\n\t  ;;\n\t-static-libtool-libs)\n\t  if test -z \"$pic_flag\" && test -n \"$link_static_flag\"; then\n\t    dlopen_self=$dlopen_self_static\n\t  fi\n\t  prefer_static_libs=yes\n\t  ;;\n\tesac\n\tbuild_libtool_libs=no\n\tbuild_old_libs=yes\n\tbreak\n\t;;\n      esac\n    done\n\n    # See if our shared archives depend on static archives.\n    test -n \"$old_archive_from_new_cmds\" && build_old_libs=yes\n\n    # Go through the arguments, transforming them on the way.\n    while test \"$#\" -gt 0; do\n      arg=$1\n      shift\n      func_quote_for_eval \"$arg\"\n      qarg=$func_quote_for_eval_unquoted_result\n      func_append libtool_args \" $func_quote_for_eval_result\"\n\n      # If the previous option needs an argument, assign it.\n      if test -n \"$prev\"; then\n\tcase $prev in\n\toutput)\n\t  func_append compile_command \" @OUTPUT@\"\n\t  func_append finalize_command \" @OUTPUT@\"\n\t  ;;\n\tesac\n\n\tcase $prev in\n\tbindir)\n\t  bindir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tdlfiles|dlprefiles)\n\t  $preload || {\n\t    # Add the symbol object into the linking commands.\n\t    func_append compile_command \" @SYMFILE@\"\n\t    func_append finalize_command \" @SYMFILE@\"\n\t    preload=:\n\t  }\n\t  case $arg in\n\t  *.la | *.lo) ;;  # We handle these cases below.\n\t  force)\n\t    if test no = \"$dlself\"; then\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  self)\n\t    if test dlprefiles = \"$prev\"; then\n\t      dlself=yes\n\t    elif test dlfiles = \"$prev\" && test yes != \"$dlopen_self\"; then\n\t      dlself=yes\n\t    else\n\t      dlself=needless\n\t      export_dynamic=yes\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  *)\n\t    if test dlfiles = \"$prev\"; then\n\t      func_append dlfiles \" $arg\"\n\t    else\n\t      func_append dlprefiles \" $arg\"\n\t    fi\n\t    prev=\n\t    continue\n\t    ;;\n\t  esac\n\t  ;;\n\texpsyms)\n\t  export_symbols=$arg\n\t  test -f \"$arg\" \\\n\t    || func_fatal_error \"symbol file '$arg' does not exist\"\n\t  prev=\n\t  continue\n\t  ;;\n\texpsyms_regex)\n\t  export_symbols_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tframework)\n\t  case $host in\n\t    *-*-darwin*)\n\t      case \"$deplibs \" in\n\t\t*\" $qarg.ltframework \"*) ;;\n\t\t*) func_append deplibs \" $qarg.ltframework\" # this is fixed later\n\t\t   ;;\n\t      esac\n\t      ;;\n\t  esac\n\t  prev=\n\t  continue\n\t  ;;\n\tinst_prefix)\n\t  inst_prefix_dir=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tmllvm)\n\t  # Clang does not use LLVM to link, so we can simply discard any\n\t  # '-mllvm $arg' options when doing the link step.\n\t  prev=\n\t  continue\n\t  ;;\n\tobjectlist)\n\t  if test -f \"$arg\"; then\n\t    save_arg=$arg\n\t    moreargs=\n\t    for fil in `cat \"$save_arg\"`\n\t    do\n#\t      func_append moreargs \" $fil\"\n\t      arg=$fil\n\t      # A libtool-controlled object.\n\n\t      # Check to see that this really is a libtool object.\n\t      if func_lalib_unsafe_p \"$arg\"; then\n\t\tpic_object=\n\t\tnon_pic_object=\n\n\t\t# Read the .lo file\n\t\tfunc_source \"$arg\"\n\n\t\tif test -z \"$pic_object\" ||\n\t\t   test -z \"$non_pic_object\" ||\n\t\t   test none = \"$pic_object\" &&\n\t\t   test none = \"$non_pic_object\"; then\n\t\t  func_fatal_error \"cannot find name of object for '$arg'\"\n\t\tfi\n\n\t\t# Extract subdirectory from the argument.\n\t\tfunc_dirname \"$arg\" \"/\" \"\"\n\t\txdir=$func_dirname_result\n\n\t\tif test none != \"$pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  pic_object=$xdir$pic_object\n\n\t\t  if test dlfiles = \"$prev\"; then\n\t\t    if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\t      func_append dlfiles \" $pic_object\"\n\t\t      prev=\n\t\t      continue\n\t\t    else\n\t\t      # If libtool objects are unsupported, then we need to preload.\n\t\t      prev=dlprefiles\n\t\t    fi\n\t\t  fi\n\n\t\t  # CHECK ME:  I think I busted this.  -Ossama\n\t\t  if test dlprefiles = \"$prev\"; then\n\t\t    # Preload the old-style object.\n\t\t    func_append dlprefiles \" $pic_object\"\n\t\t    prev=\n\t\t  fi\n\n\t\t  # A PIC object.\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  arg=$pic_object\n\t\tfi\n\n\t\t# Non-PIC object.\n\t\tif test none != \"$non_pic_object\"; then\n\t\t  # Prepend the subdirectory the object is found in.\n\t\t  non_pic_object=$xdir$non_pic_object\n\n\t\t  # A standard non-PIC object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\t  if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t\t    arg=$non_pic_object\n\t\t  fi\n\t\telse\n\t\t  # If the PIC object exists, use it instead.\n\t\t  # $xdir was prepended to $pic_object above.\n\t\t  non_pic_object=$pic_object\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t\tfi\n\t      else\n\t\t# Only an error if not doing a dry-run.\n\t\tif $opt_dry_run; then\n\t\t  # Extract subdirectory from the argument.\n\t\t  func_dirname \"$arg\" \"/\" \"\"\n\t\t  xdir=$func_dirname_result\n\n\t\t  func_lo2o \"$arg\"\n\t\t  pic_object=$xdir$objdir/$func_lo2o_result\n\t\t  non_pic_object=$xdir$func_lo2o_result\n\t\t  func_append libobjs \" $pic_object\"\n\t\t  func_append non_pic_objects \" $non_pic_object\"\n\t        else\n\t\t  func_fatal_error \"'$arg' is not a valid libtool object\"\n\t\tfi\n\t      fi\n\t    done\n\t  else\n\t    func_fatal_error \"link input file '$arg' does not exist\"\n\t  fi\n\t  arg=$save_arg\n\t  prev=\n\t  continue\n\t  ;;\n\tos2dllname)\n\t  os2dllname=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tprecious_regex)\n\t  precious_files_regex=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trelease)\n\t  release=-$arg\n\t  prev=\n\t  continue\n\t  ;;\n\trpath | xrpath)\n\t  # We need an absolute path.\n\t  case $arg in\n\t  [\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t  *)\n\t    func_fatal_error \"only absolute run-paths are allowed\"\n\t    ;;\n\t  esac\n\t  if test rpath = \"$prev\"; then\n\t    case \"$rpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append rpath \" $arg\" ;;\n\t    esac\n\t  else\n\t    case \"$xrpath \" in\n\t    *\" $arg \"*) ;;\n\t    *) func_append xrpath \" $arg\" ;;\n\t    esac\n\t  fi\n\t  prev=\n\t  continue\n\t  ;;\n\tshrext)\n\t  shrext_cmds=$arg\n\t  prev=\n\t  continue\n\t  ;;\n\tweak)\n\t  func_append weak_libs \" $arg\"\n\t  prev=\n\t  continue\n\t  ;;\n\txcclinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txcompiler)\n\t  func_append compiler_flags \" $qarg\"\n\t  prev=\n\t  func_append compile_command \" $qarg\"\n\t  func_append finalize_command \" $qarg\"\n\t  continue\n\t  ;;\n\txlinker)\n\t  func_append linker_flags \" $qarg\"\n\t  func_append compiler_flags \" $wl$qarg\"\n\t  prev=\n\t  func_append compile_command \" $wl$qarg\"\n\t  func_append finalize_command \" $wl$qarg\"\n\t  continue\n\t  ;;\n\t*)\n\t  eval \"$prev=\\\"\\$arg\\\"\"\n\t  prev=\n\t  continue\n\t  ;;\n\tesac\n      fi # test -n \"$prev\"\n\n      prevarg=$arg\n\n      case $arg in\n      -all-static)\n\tif test -n \"$link_static_flag\"; then\n\t  # See comment for -static flag below, for more details.\n\t  func_append compile_command \" $link_static_flag\"\n\t  func_append finalize_command \" $link_static_flag\"\n\tfi\n\tcontinue\n\t;;\n\n      -allow-undefined)\n\t# FIXME: remove this flag sometime in the future.\n\tfunc_fatal_error \"'-allow-undefined' must not be used because it is the default\"\n\t;;\n\n      -avoid-version)\n\tavoid_version=yes\n\tcontinue\n\t;;\n\n      -bindir)\n\tprev=bindir\n\tcontinue\n\t;;\n\n      -dlopen)\n\tprev=dlfiles\n\tcontinue\n\t;;\n\n      -dlpreopen)\n\tprev=dlprefiles\n\tcontinue\n\t;;\n\n      -export-dynamic)\n\texport_dynamic=yes\n\tcontinue\n\t;;\n\n      -export-symbols | -export-symbols-regex)\n\tif test -n \"$export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t  func_fatal_error \"more than one -exported-symbols argument is not allowed\"\n\tfi\n\tif test X-export-symbols = \"X$arg\"; then\n\t  prev=expsyms\n\telse\n\t  prev=expsyms_regex\n\tfi\n\tcontinue\n\t;;\n\n      -framework)\n\tprev=framework\n\tcontinue\n\t;;\n\n      -inst-prefix-dir)\n\tprev=inst_prefix\n\tcontinue\n\t;;\n\n      # The native IRIX linker understands -LANG:*, -LIST:* and -LNO:*\n      # so, if we see these flags be careful not to treat them like -L\n      -L[A-Z][A-Z]*:*)\n\tcase $with_gcc/$host in\n\tno/*-*-irix* | /*-*-irix*)\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -L*)\n\tfunc_stripname \"-L\" '' \"$arg\"\n\tif test -z \"$func_stripname_result\"; then\n\t  if test \"$#\" -gt 0; then\n\t    func_fatal_error \"require no space between '-L' and '$1'\"\n\t  else\n\t    func_fatal_error \"need path for '-L' option\"\n\t  fi\n\tfi\n\tfunc_resolve_sysroot \"$func_stripname_result\"\n\tdir=$func_resolve_sysroot_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t*)\n\t  absdir=`cd \"$dir\" && pwd`\n\t  test -z \"$absdir\" && \\\n\t    func_fatal_error \"cannot determine absolute directory name of '$dir'\"\n\t  dir=$absdir\n\t  ;;\n\tesac\n\tcase \"$deplibs \" in\n\t*\" -L$dir \"* | *\" $arg \"*)\n\t  # Will only happen for absolute or sysroot arguments\n\t  ;;\n\t*)\n\t  # Preserve sysroot, but never include relative directories\n\t  case $dir in\n\t    [\\\\/]* | [A-Za-z]:[\\\\/]* | =*) func_append deplibs \" $arg\" ;;\n\t    *) func_append deplibs \" -L$dir\" ;;\n\t  esac\n\t  func_append lib_search_path \" $dir\"\n\t  ;;\n\tesac\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$dir\" | $SED 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$dir:\"*) ;;\n\t  ::) dllsearchpath=$dir;;\n\t  *) func_append dllsearchpath \":$dir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n\tcontinue\n\t;;\n\n      -l*)\n\tif test X-lc = \"X$arg\" || test X-lm = \"X$arg\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # These systems don't actually have a C or math library (as such)\n\t    continue\n\t    ;;\n\t  *-*-os2*)\n\t    # These systems don't actually have a C library (as such)\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C and math libraries are in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    continue\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    test X-lc = \"X$arg\" && continue\n\t    ;;\n\t  esac\n\telif test X-lc_r = \"X$arg\"; then\n\t case $host in\n\t *-*-openbsd* | *-*-freebsd* | *-*-dragonfly* | *-*-bitrig*)\n\t   # Do not include libc_r directly, use -pthread flag.\n\t   continue\n\t   ;;\n\t esac\n\tfi\n\tfunc_append deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      -mllvm)\n\tprev=mllvm\n\tcontinue\n\t;;\n\n      -module)\n\tmodule=yes\n\tcontinue\n\t;;\n\n      # Tru64 UNIX uses -model [arg] to determine the layout of C++\n      # classes, name mangling, and exception handling.\n      # Darwin uses the -arch flag to determine output architecture.\n      -model|-arch|-isysroot|--sysroot)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n      |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\tfunc_append compiler_flags \" $arg\"\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n\tcase \"$new_inherited_linker_flags \" in\n\t    *\" $arg \"*) ;;\n\t    * ) func_append new_inherited_linker_flags \" $arg\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -multi_module)\n\tsingle_module=$wl-multi_module\n\tcontinue\n\t;;\n\n      -no-fast-install)\n\tfast_install=no\n\tcontinue\n\t;;\n\n      -no-install)\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-darwin* | *-cegcc*)\n\t  # The PATH hackery in wrapper scripts is required on Windows\n\t  # and Darwin in order for the loader to find any dlls it needs.\n\t  func_warning \"'-no-install' is ignored for $host\"\n\t  func_warning \"assuming '-no-fast-install' instead\"\n\t  fast_install=no\n\t  ;;\n\t*) no_install=yes ;;\n\tesac\n\tcontinue\n\t;;\n\n      -no-undefined)\n\tallow_undefined=no\n\tcontinue\n\t;;\n\n      -objectlist)\n\tprev=objectlist\n\tcontinue\n\t;;\n\n      -os2dllname)\n\tprev=os2dllname\n\tcontinue\n\t;;\n\n      -o) prev=output ;;\n\n      -precious-files-regex)\n\tprev=precious_regex\n\tcontinue\n\t;;\n\n      -release)\n\tprev=release\n\tcontinue\n\t;;\n\n      -rpath)\n\tprev=rpath\n\tcontinue\n\t;;\n\n      -R)\n\tprev=xrpath\n\tcontinue\n\t;;\n\n      -R*)\n\tfunc_stripname '-R' '' \"$arg\"\n\tdir=$func_stripname_result\n\t# We need an absolute path.\n\tcase $dir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) ;;\n\t=*)\n\t  func_stripname '=' '' \"$dir\"\n\t  dir=$lt_sysroot$func_stripname_result\n\t  ;;\n\t*)\n\t  func_fatal_error \"only absolute run-paths are allowed\"\n\t  ;;\n\tesac\n\tcase \"$xrpath \" in\n\t*\" $dir \"*) ;;\n\t*) func_append xrpath \" $dir\" ;;\n\tesac\n\tcontinue\n\t;;\n\n      -shared)\n\t# The effects of -shared are defined in a previous loop.\n\tcontinue\n\t;;\n\n      -shrext)\n\tprev=shrext\n\tcontinue\n\t;;\n\n      -static | -static-libtool-libs)\n\t# The effects of -static are defined in a previous loop.\n\t# We used to do the same as -all-static on platforms that\n\t# didn't have a PIC flag, but the assumption that the effects\n\t# would be equivalent was wrong.  It would break on at least\n\t# Digital Unix and AIX.\n\tcontinue\n\t;;\n\n      -thread-safe)\n\tthread_safe=yes\n\tcontinue\n\t;;\n\n      -version-info)\n\tprev=vinfo\n\tcontinue\n\t;;\n\n      -version-number)\n\tprev=vinfo\n\tvinfo_number=yes\n\tcontinue\n\t;;\n\n      -weak)\n        prev=weak\n\tcontinue\n\t;;\n\n      -Wc,*)\n\tfunc_stripname '-Wc,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Wl,*)\n\tfunc_stripname '-Wl,' '' \"$arg\"\n\targs=$func_stripname_result\n\targ=\n\tsave_ifs=$IFS; IFS=,\n\tfor flag in $args; do\n\t  IFS=$save_ifs\n          func_quote_for_eval \"$flag\"\n\t  func_append arg \" $wl$func_quote_for_eval_result\"\n\t  func_append compiler_flags \" $wl$func_quote_for_eval_result\"\n\t  func_append linker_flags \" $func_quote_for_eval_result\"\n\tdone\n\tIFS=$save_ifs\n\tfunc_stripname ' ' '' \"$arg\"\n\targ=$func_stripname_result\n\t;;\n\n      -Xcompiler)\n\tprev=xcompiler\n\tcontinue\n\t;;\n\n      -Xlinker)\n\tprev=xlinker\n\tcontinue\n\t;;\n\n      -XCClinker)\n\tprev=xcclinker\n\tcontinue\n\t;;\n\n      # -msg_* for osf cc\n      -msg_*)\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      # Flags to be passed through unchanged, with rationale:\n      # -64, -mips[0-9]      enable 64-bit mode for the SGI compiler\n      # -r[0-9][0-9]*        specify processor for the SGI compiler\n      # -xarch=*, -xtarget=* enable 64-bit mode for the Sun compiler\n      # +DA*, +DD*           enable 64-bit mode for the HP compiler\n      # -q*                  compiler args for the IBM compiler\n      # -m*, -t[45]*, -txscale* architecture-specific flags for GCC\n      # -F/path              path to uninstalled frameworks, gcc on darwin\n      # -p, -pg, --coverage, -fprofile-*  profiling flags for GCC\n      # -fstack-protector*   stack protector flags for GCC\n      # @file                GCC response files\n      # -tp=*                Portland pgcc target processor selection\n      # --sysroot=*          for sysroot support\n      # -O*, -g*, -flto*, -fwhopr*, -fuse-linker-plugin GCC link-time optimization\n      # -specs=*             GCC specs files\n      # -stdlib=*            select c++ std lib with clang\n      # -fsanitize=*         Clang/GCC memory and address sanitizer\n      -64|-mips[0-9]|-r[0-9][0-9]*|-xarch=*|-xtarget=*|+DA*|+DD*|-q*|-m*| \\\n      -t[45]*|-txscale*|-p|-pg|--coverage|-fprofile-*|-F*|@*|-tp=*|--sysroot=*| \\\n      -O*|-g*|-flto*|-fwhopr*|-fuse-linker-plugin|-fstack-protector*|-stdlib=*| \\\n      -specs=*|-fsanitize=*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n        func_append compile_command \" $arg\"\n        func_append finalize_command \" $arg\"\n        func_append compiler_flags \" $arg\"\n        continue\n        ;;\n\n      -Z*)\n        if test os2 = \"`expr $host : '.*\\(os2\\)'`\"; then\n          # OS/2 uses -Zxxx to specify OS/2-specific options\n\t  compiler_flags=\"$compiler_flags $arg\"\n\t  func_append compile_command \" $arg\"\n\t  func_append finalize_command \" $arg\"\n\t  case $arg in\n\t  -Zlinker | -Zstack)\n\t    prev=xcompiler\n\t    ;;\n\t  esac\n\t  continue\n        else\n\t  # Otherwise treat like 'Some other compiler flag' below\n\t  func_quote_for_eval \"$arg\"\n\t  arg=$func_quote_for_eval_result\n        fi\n\t;;\n\n      # Some other compiler flag.\n      -* | +*)\n        func_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n\n      *.$objext)\n\t# A standard object.\n\tfunc_append objs \" $arg\"\n\t;;\n\n      *.lo)\n\t# A libtool-controlled object.\n\n\t# Check to see that this really is a libtool object.\n\tif func_lalib_unsafe_p \"$arg\"; then\n\t  pic_object=\n\t  non_pic_object=\n\n\t  # Read the .lo file\n\t  func_source \"$arg\"\n\n\t  if test -z \"$pic_object\" ||\n\t     test -z \"$non_pic_object\" ||\n\t     test none = \"$pic_object\" &&\n\t     test none = \"$non_pic_object\"; then\n\t    func_fatal_error \"cannot find name of object for '$arg'\"\n\t  fi\n\n\t  # Extract subdirectory from the argument.\n\t  func_dirname \"$arg\" \"/\" \"\"\n\t  xdir=$func_dirname_result\n\n\t  test none = \"$pic_object\" || {\n\t    # Prepend the subdirectory the object is found in.\n\t    pic_object=$xdir$pic_object\n\n\t    if test dlfiles = \"$prev\"; then\n\t      if test yes = \"$build_libtool_libs\" && test yes = \"$dlopen_support\"; then\n\t\tfunc_append dlfiles \" $pic_object\"\n\t\tprev=\n\t\tcontinue\n\t      else\n\t\t# If libtool objects are unsupported, then we need to preload.\n\t\tprev=dlprefiles\n\t      fi\n\t    fi\n\n\t    # CHECK ME:  I think I busted this.  -Ossama\n\t    if test dlprefiles = \"$prev\"; then\n\t      # Preload the old-style object.\n\t      func_append dlprefiles \" $pic_object\"\n\t      prev=\n\t    fi\n\n\t    # A PIC object.\n\t    func_append libobjs \" $pic_object\"\n\t    arg=$pic_object\n\t  }\n\n\t  # Non-PIC object.\n\t  if test none != \"$non_pic_object\"; then\n\t    # Prepend the subdirectory the object is found in.\n\t    non_pic_object=$xdir$non_pic_object\n\n\t    # A standard non-PIC object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t    if test -z \"$pic_object\" || test none = \"$pic_object\"; then\n\t      arg=$non_pic_object\n\t    fi\n\t  else\n\t    # If the PIC object exists, use it instead.\n\t    # $xdir was prepended to $pic_object above.\n\t    non_pic_object=$pic_object\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  fi\n\telse\n\t  # Only an error if not doing a dry-run.\n\t  if $opt_dry_run; then\n\t    # Extract subdirectory from the argument.\n\t    func_dirname \"$arg\" \"/\" \"\"\n\t    xdir=$func_dirname_result\n\n\t    func_lo2o \"$arg\"\n\t    pic_object=$xdir$objdir/$func_lo2o_result\n\t    non_pic_object=$xdir$func_lo2o_result\n\t    func_append libobjs \" $pic_object\"\n\t    func_append non_pic_objects \" $non_pic_object\"\n\t  else\n\t    func_fatal_error \"'$arg' is not a valid libtool object\"\n\t  fi\n\tfi\n\t;;\n\n      *.$libext)\n\t# An archive.\n\tfunc_append deplibs \" $arg\"\n\tfunc_append old_deplibs \" $arg\"\n\tcontinue\n\t;;\n\n      *.la)\n\t# A libtool-controlled library.\n\n\tfunc_resolve_sysroot \"$arg\"\n\tif test dlfiles = \"$prev\"; then\n\t  # This library was specified with -dlopen.\n\t  func_append dlfiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telif test dlprefiles = \"$prev\"; then\n\t  # The library was specified with -dlpreopen.\n\t  func_append dlprefiles \" $func_resolve_sysroot_result\"\n\t  prev=\n\telse\n\t  func_append deplibs \" $func_resolve_sysroot_result\"\n\tfi\n\tcontinue\n\t;;\n\n      # Some other compiler argument.\n      *)\n\t# Unknown arguments in both finalize_command and compile_command need\n\t# to be aesthetically quoted because they are evaled later.\n\tfunc_quote_for_eval \"$arg\"\n\targ=$func_quote_for_eval_result\n\t;;\n      esac # arg\n\n      # Now actually substitute the argument into the commands.\n      if test -n \"$arg\"; then\n\tfunc_append compile_command \" $arg\"\n\tfunc_append finalize_command \" $arg\"\n      fi\n    done # argument parsing loop\n\n    test -n \"$prev\" && \\\n      func_fatal_help \"the '$prevarg' option requires an argument\"\n\n    if test yes = \"$export_dynamic\" && test -n \"$export_dynamic_flag_spec\"; then\n      eval arg=\\\"$export_dynamic_flag_spec\\\"\n      func_append compile_command \" $arg\"\n      func_append finalize_command \" $arg\"\n    fi\n\n    oldlibs=\n    # calculate the name of the file, without its directory\n    func_basename \"$output\"\n    outputname=$func_basename_result\n    libobjs_save=$libobjs\n\n    if test -n \"$shlibpath_var\"; then\n      # get the directories listed in $shlibpath_var\n      eval shlib_search_path=\\`\\$ECHO \\\"\\$$shlibpath_var\\\" \\| \\$SED \\'s/:/ /g\\'\\`\n    else\n      shlib_search_path=\n    fi\n    eval sys_lib_search_path=\\\"$sys_lib_search_path_spec\\\"\n    eval sys_lib_dlsearch_path=\\\"$sys_lib_dlsearch_path_spec\\\"\n\n    # Definition is injected by LT_CONFIG during libtool generation.\n    func_munge_path_list sys_lib_dlsearch_path \"$LT_SYS_LIBRARY_PATH\"\n\n    func_dirname \"$output\" \"/\" \"\"\n    output_objdir=$func_dirname_result$objdir\n    func_to_tool_file \"$output_objdir/\"\n    tool_output_objdir=$func_to_tool_file_result\n    # Create the object directory.\n    func_mkdir_p \"$output_objdir\"\n\n    # Determine the type of output\n    case $output in\n    \"\")\n      func_fatal_help \"you must specify an output file\"\n      ;;\n    *.$libext) linkmode=oldlib ;;\n    *.lo | *.$objext) linkmode=obj ;;\n    *.la) linkmode=lib ;;\n    *) linkmode=prog ;; # Anything else should be a program.\n    esac\n\n    specialdeplibs=\n\n    libs=\n    # Find all interdependent deplibs by searching for libraries\n    # that are linked more than once (e.g. -la -lb -la)\n    for deplib in $deplibs; do\n      if $opt_preserve_dup_deps; then\n\tcase \"$libs \" in\n\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\tesac\n      fi\n      func_append libs \" $deplib\"\n    done\n\n    if test lib = \"$linkmode\"; then\n      libs=\"$predeps $libs $compiler_lib_search_path $postdeps\"\n\n      # Compute libraries that are listed more than once in $predeps\n      # $postdeps and mark them as special (i.e., whose duplicates are\n      # not to be eliminated).\n      pre_post_deps=\n      if $opt_duplicate_compiler_generated_deps; then\n\tfor pre_post_dep in $predeps $postdeps; do\n\t  case \"$pre_post_deps \" in\n\t  *\" $pre_post_dep \"*) func_append specialdeplibs \" $pre_post_deps\" ;;\n\t  esac\n\t  func_append pre_post_deps \" $pre_post_dep\"\n\tdone\n      fi\n      pre_post_deps=\n    fi\n\n    deplibs=\n    newdependency_libs=\n    newlib_search_path=\n    need_relink=no # whether we're linking any uninstalled libtool libraries\n    notinst_deplibs= # not-installed libtool libraries\n    notinst_path= # paths that contain not-installed libtool libraries\n\n    case $linkmode in\n    lib)\n\tpasses=\"conv dlpreopen link\"\n\tfor file in $dlfiles $dlprefiles; do\n\t  case $file in\n\t  *.la) ;;\n\t  *)\n\t    func_fatal_help \"libraries can '-dlopen' only libtool libraries: $file\"\n\t    ;;\n\t  esac\n\tdone\n\t;;\n    prog)\n\tcompile_deplibs=\n\tfinalize_deplibs=\n\talldeplibs=false\n\tnewdlfiles=\n\tnewdlprefiles=\n\tpasses=\"conv scan dlopen dlpreopen link\"\n\t;;\n    *)  passes=\"conv\"\n\t;;\n    esac\n\n    for pass in $passes; do\n      # The preopen pass in lib mode reverses $deplibs; put it back here\n      # so that -L comes before libs that need it for instance...\n      if test lib,link = \"$linkmode,$pass\"; then\n\t## FIXME: Find the place where the list is rebuilt in the wrong\n\t##        order, and fix it there properly\n        tmp_deplibs=\n\tfor deplib in $deplibs; do\n\t  tmp_deplibs=\"$deplib $tmp_deplibs\"\n\tdone\n\tdeplibs=$tmp_deplibs\n      fi\n\n      if test lib,link = \"$linkmode,$pass\" ||\n\t test prog,scan = \"$linkmode,$pass\"; then\n\tlibs=$deplibs\n\tdeplibs=\n      fi\n      if test prog = \"$linkmode\"; then\n\tcase $pass in\n\tdlopen) libs=$dlfiles ;;\n\tdlpreopen) libs=$dlprefiles ;;\n\tlink)\n\t  libs=\"$deplibs %DEPLIBS%\"\n\t  test \"X$link_all_deplibs\" != Xno && libs=\"$libs $dependency_libs\"\n\t  ;;\n\tesac\n      fi\n      if test lib,dlpreopen = \"$linkmode,$pass\"; then\n\t# Collect and forward deplibs of preopened libtool libs\n\tfor lib in $dlprefiles; do\n\t  # Ignore non-libtool-libs\n\t  dependency_libs=\n\t  func_resolve_sysroot \"$lib\"\n\t  case $lib in\n\t  *.la)\tfunc_source \"$func_resolve_sysroot_result\" ;;\n\t  esac\n\n\t  # Collect preopened libtool deplibs, except any this library\n\t  # has declared as weak libs\n\t  for deplib in $dependency_libs; do\n\t    func_basename \"$deplib\"\n            deplib_base=$func_basename_result\n\t    case \" $weak_libs \" in\n\t    *\" $deplib_base \"*) ;;\n\t    *) func_append deplibs \" $deplib\" ;;\n\t    esac\n\t  done\n\tdone\n\tlibs=$dlprefiles\n      fi\n      if test dlopen = \"$pass\"; then\n\t# Collect dlpreopened libraries\n\tsave_deplibs=$deplibs\n\tdeplibs=\n      fi\n\n      for deplib in $libs; do\n\tlib=\n\tfound=false\n\tcase $deplib in\n\t-mt|-mthreads|-kthread|-Kthread|-pthread|-pthreads|--thread-safe \\\n        |-threads|-fopenmp|-openmp|-mp|-xopenmp|-omp|-qsmp=*)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    func_append compiler_flags \" $deplib\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-l*)\n\t  if test lib != \"$linkmode\" && test prog != \"$linkmode\"; then\n\t    func_warning \"'-l' is ignored for archives/objects\"\n\t    continue\n\t  fi\n\t  func_stripname '-l' '' \"$deplib\"\n\t  name=$func_stripname_result\n\t  if test lib = \"$linkmode\"; then\n\t    searchdirs=\"$newlib_search_path $lib_search_path $compiler_lib_search_dirs $sys_lib_search_path $shlib_search_path\"\n\t  else\n\t    searchdirs=\"$newlib_search_path $lib_search_path $sys_lib_search_path $shlib_search_path\"\n\t  fi\n\t  for searchdir in $searchdirs; do\n\t    for search_ext in .la $std_shrext .so .a; do\n\t      # Search the libtool library\n\t      lib=$searchdir/lib$name$search_ext\n\t      if test -f \"$lib\"; then\n\t\tif test .la = \"$search_ext\"; then\n\t\t  found=:\n\t\telse\n\t\t  found=false\n\t\tfi\n\t\tbreak 2\n\t      fi\n\t    done\n\t  done\n\t  if $found; then\n\t    # deplib is a libtool library\n\t    # If $allow_libtool_libs_with_static_runtimes && $deplib is a stdlib,\n\t    # We need to do some special things here, and not later.\n\t    if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t      case \" $predeps $postdeps \" in\n\t      *\" $deplib \"*)\n\t\tif func_lalib_p \"$lib\"; then\n\t\t  library_names=\n\t\t  old_library=\n\t\t  func_source \"$lib\"\n\t\t  for l in $old_library $library_names; do\n\t\t    ll=$l\n\t\t  done\n\t\t  if test \"X$ll\" = \"X$old_library\"; then # only static version available\n\t\t    found=false\n\t\t    func_dirname \"$lib\" \"\" \".\"\n\t\t    ladir=$func_dirname_result\n\t\t    lib=$ladir/$old_library\n\t\t    if test prog,link = \"$linkmode,$pass\"; then\n\t\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t\t    else\n\t\t      deplibs=\"$deplib $deplibs\"\n\t\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t\t    fi\n\t\t    continue\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *) ;;\n\t      esac\n\t    fi\n\t  else\n\t    # deplib doesn't seem to be a libtool library\n\t    if test prog,link = \"$linkmode,$pass\"; then\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      deplibs=\"$deplib $deplibs\"\n\t      test lib = \"$linkmode\" && newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    continue\n\t  fi\n\t  ;; # -l\n\t*.ltframework)\n\t  if test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$deplib $compile_deplibs\"\n\t    finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$deplib $deplibs\"\n\t    if test lib = \"$linkmode\"; then\n\t\tcase \"$new_inherited_linker_flags \" in\n\t\t    *\" $deplib \"*) ;;\n\t\t    * ) func_append new_inherited_linker_flags \" $deplib\" ;;\n\t\tesac\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t-L*)\n\t  case $linkmode in\n\t  lib)\n\t    deplibs=\"$deplib $deplibs\"\n\t    test conv = \"$pass\" && continue\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  prog)\n\t    if test conv = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t      continue\n\t    fi\n\t    if test scan = \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    func_stripname '-L' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t    ;;\n\t  *)\n\t    func_warning \"'-L' is ignored for archives/objects\"\n\t    ;;\n\t  esac # linkmode\n\t  continue\n\t  ;; # -L\n\t-R*)\n\t  if test link = \"$pass\"; then\n\t    func_stripname '-R' '' \"$deplib\"\n\t    func_resolve_sysroot \"$func_stripname_result\"\n\t    dir=$func_resolve_sysroot_result\n\t    # Make sure the xrpath contains only unique directories.\n\t    case \"$xrpath \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append xrpath \" $dir\" ;;\n\t    esac\n\t  fi\n\t  deplibs=\"$deplib $deplibs\"\n\t  continue\n\t  ;;\n\t*.la)\n\t  func_resolve_sysroot \"$deplib\"\n\t  lib=$func_resolve_sysroot_result\n\t  ;;\n\t*.$libext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t    continue\n\t  fi\n\t  case $linkmode in\n\t  lib)\n\t    # Linking convenience modules into shared libraries is allowed,\n\t    # but linking other static libraries is non-portable.\n\t    case \" $dlpreconveniencelibs \" in\n\t    *\" $deplib \"*) ;;\n\t    *)\n\t      valid_a_lib=false\n\t      case $deplibs_check_method in\n\t\tmatch_pattern*)\n\t\t  set dummy $deplibs_check_method; shift\n\t\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t\t  if eval \"\\$ECHO \\\"$deplib\\\"\" 2>/dev/null | $SED 10q \\\n\t\t    | $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t    valid_a_lib=:\n\t\t  fi\n\t\t;;\n\t\tpass_all)\n\t\t  valid_a_lib=:\n\t\t;;\n\t      esac\n\t      if $valid_a_lib; then\n\t\techo\n\t\t$ECHO \"*** Warning: Linking the shared library $output against the\"\n\t\t$ECHO \"*** static library $deplib is not portable!\"\n\t\tdeplibs=\"$deplib $deplibs\"\n\t      else\n\t\techo\n\t\t$ECHO \"*** Warning: Trying to link with static lib archive $deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because the file extensions .$libext of this argument makes me believe\"\n\t\techo \"*** that it is just a static archive that I should not use here.\"\n\t      fi\n\t      ;;\n\t    esac\n\t    continue\n\t    ;;\n\t  prog)\n\t    if test link != \"$pass\"; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    fi\n\t    continue\n\t    ;;\n\t  esac # linkmode\n\t  ;; # *.$libext\n\t*.lo | *.$objext)\n\t  if test conv = \"$pass\"; then\n\t    deplibs=\"$deplib $deplibs\"\n\t  elif test prog = \"$linkmode\"; then\n\t    if test dlpreopen = \"$pass\" || test yes != \"$dlopen_support\" || test no = \"$build_libtool_libs\"; then\n\t      # If there is no dlopen support or we're linking statically,\n\t      # we need to preload.\n\t      func_append newdlprefiles \" $deplib\"\n\t      compile_deplibs=\"$deplib $compile_deplibs\"\n\t      finalize_deplibs=\"$deplib $finalize_deplibs\"\n\t    else\n\t      func_append newdlfiles \" $deplib\"\n\t    fi\n\t  fi\n\t  continue\n\t  ;;\n\t%DEPLIBS%)\n\t  alldeplibs=:\n\t  continue\n\t  ;;\n\tesac # case $deplib\n\n\t$found || test -f \"$lib\" \\\n\t  || func_fatal_error \"cannot find the library '$lib' or unhandled argument '$deplib'\"\n\n\t# Check to see that this really is a libtool archive.\n\tfunc_lalib_unsafe_p \"$lib\" \\\n\t  || func_fatal_error \"'$lib' is not a valid libtool archive\"\n\n\tfunc_dirname \"$lib\" \"\" \".\"\n\tladir=$func_dirname_result\n\n\tdlname=\n\tdlopen=\n\tdlpreopen=\n\tlibdir=\n\tlibrary_names=\n\told_library=\n\tinherited_linker_flags=\n\t# If the library was installed with an old release of libtool,\n\t# it will not redefine variables installed, or shouldnotlink\n\tinstalled=yes\n\tshouldnotlink=no\n\tavoidtemprpath=\n\n\n\t# Read the .la file\n\tfunc_source \"$lib\"\n\n\t# Convert \"-framework foo\" to \"foo.ltframework\"\n\tif test -n \"$inherited_linker_flags\"; then\n\t  tmp_inherited_linker_flags=`$ECHO \"$inherited_linker_flags\" | $SED 's/-framework \\([^ $]*\\)/\\1.ltframework/g'`\n\t  for tmp_inherited_linker_flag in $tmp_inherited_linker_flags; do\n\t    case \" $new_inherited_linker_flags \" in\n\t      *\" $tmp_inherited_linker_flag \"*) ;;\n\t      *) func_append new_inherited_linker_flags \" $tmp_inherited_linker_flag\";;\n\t    esac\n\t  done\n\tfi\n\tdependency_libs=`$ECHO \" $dependency_libs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tif test lib,link = \"$linkmode,$pass\" ||\n\t   test prog,scan = \"$linkmode,$pass\" ||\n\t   { test prog != \"$linkmode\" && test lib != \"$linkmode\"; }; then\n\t  test -n \"$dlopen\" && func_append dlfiles \" $dlopen\"\n\t  test -n \"$dlpreopen\" && func_append dlprefiles \" $dlpreopen\"\n\tfi\n\n\tif test conv = \"$pass\"; then\n\t  # Only check for convenience libraries\n\t  deplibs=\"$lib $deplibs\"\n\t  if test -z \"$libdir\"; then\n\t    if test -z \"$old_library\"; then\n\t      func_fatal_error \"cannot find name of link library for '$lib'\"\n\t    fi\n\t    # It is a libtool convenience library, so add in its objects.\n\t    func_append convenience \" $ladir/$objdir/$old_library\"\n\t    func_append old_convenience \" $ladir/$objdir/$old_library\"\n\t    tmp_libs=\n\t    for deplib in $dependency_libs; do\n\t      deplibs=\"$deplib $deplibs\"\n\t      if $opt_preserve_dup_deps; then\n\t\tcase \"$tmp_libs \" in\n\t\t*\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t\tesac\n\t      fi\n\t      func_append tmp_libs \" $deplib\"\n\t    done\n\t  elif test prog != \"$linkmode\" && test lib != \"$linkmode\"; then\n\t    func_fatal_error \"'$lib' is not a convenience library\"\n\t  fi\n\t  continue\n\tfi # $pass = conv\n\n\n\t# Get the name of the library we link against.\n\tlinklib=\n\tif test -n \"$old_library\" &&\n\t   { test yes = \"$prefer_static_libs\" ||\n\t     test built,no = \"$prefer_static_libs,$installed\"; }; then\n\t  linklib=$old_library\n\telse\n\t  for l in $old_library $library_names; do\n\t    linklib=$l\n\t  done\n\tfi\n\tif test -z \"$linklib\"; then\n\t  func_fatal_error \"cannot find name of link library for '$lib'\"\n\tfi\n\n\t# This library was specified with -dlopen.\n\tif test dlopen = \"$pass\"; then\n\t  test -z \"$libdir\" \\\n\t    && func_fatal_error \"cannot -dlopen a convenience library: '$lib'\"\n\t  if test -z \"$dlname\" ||\n\t     test yes != \"$dlopen_support\" ||\n\t     test no = \"$build_libtool_libs\"\n\t  then\n\t    # If there is no dlname, no dlopen support or we're linking\n\t    # statically, we need to preload.  We also need to preload any\n\t    # dependent libraries so libltdl's deplib preloader doesn't\n\t    # bomb out in the load deplibs phase.\n\t    func_append dlprefiles \" $lib $dependency_libs\"\n\t  else\n\t    func_append newdlfiles \" $lib\"\n\t  fi\n\t  continue\n\tfi # $pass = dlopen\n\n\t# We need an absolute path.\n\tcase $ladir in\n\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs_ladir=$ladir ;;\n\t*)\n\t  abs_ladir=`cd \"$ladir\" && pwd`\n\t  if test -z \"$abs_ladir\"; then\n\t    func_warning \"cannot determine absolute directory name of '$ladir'\"\n\t    func_warning \"passing it literally to the linker, although it might fail\"\n\t    abs_ladir=$ladir\n\t  fi\n\t  ;;\n\tesac\n\tfunc_basename \"$lib\"\n\tlaname=$func_basename_result\n\n\t# Find the relevant object directory and library name.\n\tif test yes = \"$installed\"; then\n\t  if test ! -f \"$lt_sysroot$libdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    func_warning \"library '$lib' was moved.\"\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    libdir=$abs_ladir\n\t  else\n\t    dir=$lt_sysroot$libdir\n\t    absdir=$lt_sysroot$libdir\n\t  fi\n\t  test yes = \"$hardcode_automatic\" && avoidtemprpath=yes\n\telse\n\t  if test ! -f \"$ladir/$objdir/$linklib\" && test -f \"$abs_ladir/$linklib\"; then\n\t    dir=$ladir\n\t    absdir=$abs_ladir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  else\n\t    dir=$ladir/$objdir\n\t    absdir=$abs_ladir/$objdir\n\t    # Remove this search path later\n\t    func_append notinst_path \" $abs_ladir\"\n\t  fi\n\tfi # $installed = yes\n\tfunc_stripname 'lib' '.la' \"$laname\"\n\tname=$func_stripname_result\n\n\t# This library was specified with -dlpreopen.\n\tif test dlpreopen = \"$pass\"; then\n\t  if test -z \"$libdir\" && test prog = \"$linkmode\"; then\n\t    func_fatal_error \"only libraries may -dlpreopen a convenience library: '$lib'\"\n\t  fi\n\t  case $host in\n\t    # special handling for platforms with PE-DLLs.\n\t    *cygwin* | *mingw* | *cegcc* )\n\t      # Linker will automatically link against shared library if both\n\t      # static and shared are present.  Therefore, ensure we extract\n\t      # symbols from the import library if a shared library is present\n\t      # (otherwise, the dlopen module name will be incorrect).  We do\n\t      # this by putting the import library name into $newdlprefiles.\n\t      # We recover the dlopen module name by 'saving' the la file\n\t      # name in a special purpose variable, and (later) extracting the\n\t      # dlname from the la file.\n\t      if test -n \"$dlname\"; then\n\t        func_tr_sh \"$dir/$linklib\"\n\t        eval \"libfile_$func_tr_sh_result=\\$abs_ladir/\\$laname\"\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      fi\n\t    ;;\n\t    * )\n\t      # Prefer using a static library (so that no silly _DYNAMIC symbols\n\t      # are required to link).\n\t      if test -n \"$old_library\"; then\n\t        func_append newdlprefiles \" $dir/$old_library\"\n\t        # Keep a list of preopened convenience libraries to check\n\t        # that they are being used correctly in the link pass.\n\t        test -z \"$libdir\" && \\\n\t          func_append dlpreconveniencelibs \" $dir/$old_library\"\n\t      # Otherwise, use the dlname, so that lt_dlopen finds it.\n\t      elif test -n \"$dlname\"; then\n\t        func_append newdlprefiles \" $dir/$dlname\"\n\t      else\n\t        func_append newdlprefiles \" $dir/$linklib\"\n\t      fi\n\t    ;;\n\t  esac\n\tfi # $pass = dlpreopen\n\n\tif test -z \"$libdir\"; then\n\t  # Link the convenience library\n\t  if test lib = \"$linkmode\"; then\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t  elif test prog,link = \"$linkmode,$pass\"; then\n\t    compile_deplibs=\"$dir/$old_library $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$old_library $finalize_deplibs\"\n\t  else\n\t    deplibs=\"$lib $deplibs\" # used for prog,scan pass\n\t  fi\n\t  continue\n\tfi\n\n\n\tif test prog = \"$linkmode\" && test link != \"$pass\"; then\n\t  func_append newlib_search_path \" $ladir\"\n\t  deplibs=\"$lib $deplibs\"\n\n\t  linkalldeplibs=false\n\t  if test no != \"$link_all_deplibs\" || test -z \"$library_names\" ||\n\t     test no = \"$build_libtool_libs\"; then\n\t    linkalldeplibs=:\n\t  fi\n\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    case $deplib in\n\t    -L*) func_stripname '-L' '' \"$deplib\"\n\t         func_resolve_sysroot \"$func_stripname_result\"\n\t         func_append newlib_search_path \" $func_resolve_sysroot_result\"\n\t\t ;;\n\t    esac\n\t    # Need to link against all dependency_libs?\n\t    if $linkalldeplibs; then\n\t      deplibs=\"$deplib $deplibs\"\n\t    else\n\t      # Need to hardcode shared library paths\n\t      # or/and link against static libraries\n\t      newdependency_libs=\"$deplib $newdependency_libs\"\n\t    fi\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $deplib \"*) func_append specialdeplibs \" $deplib\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $deplib\"\n\t  done # for deplib\n\t  continue\n\tfi # $linkmode = prog...\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  if test -n \"$library_names\" &&\n\t     { { test no = \"$prefer_static_libs\" ||\n\t         test built,yes = \"$prefer_static_libs,$installed\"; } ||\n\t       test -z \"$old_library\"; }; then\n\t    # We need to hardcode the library path\n\t    if test -n \"$shlibpath_var\" && test -z \"$avoidtemprpath\"; then\n\t      # Make sure the rpath contains only unique directories.\n\t      case $temp_rpath: in\n\t      *\"$absdir:\"*) ;;\n\t      *) func_append temp_rpath \"$absdir:\" ;;\n\t      esac\n\t    fi\n\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi # $linkmode,$pass = prog,link...\n\n\t  if $alldeplibs &&\n\t     { test pass_all = \"$deplibs_check_method\" ||\n\t       { test yes = \"$build_libtool_libs\" &&\n\t\t test -n \"$library_names\"; }; }; then\n\t    # We only need to search for static libraries\n\t    continue\n\t  fi\n\tfi\n\n\tlink_static=no # Whether the deplib will be linked statically\n\tuse_static_libs=$prefer_static_libs\n\tif test built = \"$use_static_libs\" && test yes = \"$installed\"; then\n\t  use_static_libs=no\n\tfi\n\tif test -n \"$library_names\" &&\n\t   { test no = \"$use_static_libs\" || test -z \"$old_library\"; }; then\n\t  case $host in\n\t  *cygwin* | *mingw* | *cegcc* | *os2*)\n\t      # No point in relinking DLLs because paths are not encoded\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=no\n\t    ;;\n\t  *)\n\t    if test no = \"$installed\"; then\n\t      func_append notinst_deplibs \" $lib\"\n\t      need_relink=yes\n\t    fi\n\t    ;;\n\t  esac\n\t  # This is a shared library\n\n\t  # Warn about portability, can't link against -module's on some\n\t  # systems (darwin).  Don't bleat about dlopened modules though!\n\t  dlopenmodule=\n\t  for dlpremoduletest in $dlprefiles; do\n\t    if test \"X$dlpremoduletest\" = \"X$lib\"; then\n\t      dlopenmodule=$dlpremoduletest\n\t      break\n\t    fi\n\t  done\n\t  if test -z \"$dlopenmodule\" && test yes = \"$shouldnotlink\" && test link = \"$pass\"; then\n\t    echo\n\t    if test prog = \"$linkmode\"; then\n\t      $ECHO \"*** Warning: Linking the executable $output against the loadable module\"\n\t    else\n\t      $ECHO \"*** Warning: Linking the shared library $output against the loadable module\"\n\t    fi\n\t    $ECHO \"*** $linklib is not portable!\"\n\t  fi\n\t  if test lib = \"$linkmode\" &&\n\t     test yes = \"$hardcode_into_libs\"; then\n\t    # Hardcode the library path.\n\t    # Skip directories that are in the system default run-time\n\t    # search path.\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $absdir \"*) ;;\n\t    *)\n\t      case \"$compile_rpath \" in\n\t      *\" $absdir \"*) ;;\n\t      *) func_append compile_rpath \" $absdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t    case \" $sys_lib_dlsearch_path \" in\n\t    *\" $libdir \"*) ;;\n\t    *)\n\t      case \"$finalize_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append finalize_rpath \" $libdir\" ;;\n\t      esac\n\t      ;;\n\t    esac\n\t  fi\n\n\t  if test -n \"$old_archive_from_expsyms_cmds\"; then\n\t    # figure out the soname\n\t    set dummy $library_names\n\t    shift\n\t    realname=$1\n\t    shift\n\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t    # use dlname if we got it. it's perfectly good, no?\n\t    if test -n \"$dlname\"; then\n\t      soname=$dlname\n\t    elif test -n \"$soname_spec\"; then\n\t      # bleh windows\n\t      case $host in\n\t      *cygwin* | mingw* | *cegcc* | *os2*)\n\t        func_arith $current - $age\n\t\tmajor=$func_arith_result\n\t\tversuffix=-$major\n\t\t;;\n\t      esac\n\t      eval soname=\\\"$soname_spec\\\"\n\t    else\n\t      soname=$realname\n\t    fi\n\n\t    # Make a new name for the extract_expsyms_cmds to use\n\t    soroot=$soname\n\t    func_basename \"$soroot\"\n\t    soname=$func_basename_result\n\t    func_stripname 'lib' '.dll' \"$soname\"\n\t    newlib=libimp-$func_stripname_result.a\n\n\t    # If the library has no export list, then create one now\n\t    if test -f \"$output_objdir/$soname-def\"; then :\n\t    else\n\t      func_verbose \"extracting exported symbol list from '$soname'\"\n\t      func_execute_cmds \"$extract_expsyms_cmds\" 'exit $?'\n\t    fi\n\n\t    # Create $newlib\n\t    if test -f \"$output_objdir/$newlib\"; then :; else\n\t      func_verbose \"generating import library for '$soname'\"\n\t      func_execute_cmds \"$old_archive_from_expsyms_cmds\" 'exit $?'\n\t    fi\n\t    # make sure the library variables are pointing to the new library\n\t    dir=$output_objdir\n\t    linklib=$newlib\n\t  fi # test -n \"$old_archive_from_expsyms_cmds\"\n\n\t  if test prog = \"$linkmode\" || test relink != \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    lib_linked=yes\n\t    case $hardcode_action in\n\t    immediate | unsupported)\n\t      if test no = \"$hardcode_direct\"; then\n\t\tadd=$dir/$linklib\n\t\tcase $host in\n\t\t  *-*-sco3.2v5.0.[024]*) add_dir=-L$dir ;;\n\t\t  *-*-sysv4*uw2*) add_dir=-L$dir ;;\n\t\t  *-*-sysv5OpenUNIX* | *-*-sysv5UnixWare7.[01].[10]* | \\\n\t\t    *-*-unixware7*) add_dir=-L$dir ;;\n\t\t  *-*-darwin* )\n\t\t    # if the lib is a (non-dlopened) module then we cannot\n\t\t    # link against it, someone is ignoring the earlier warnings\n\t\t    if /usr/bin/file -L $add 2> /dev/null |\n\t\t\t $GREP \": [^:]* bundle\" >/dev/null; then\n\t\t      if test \"X$dlopenmodule\" != \"X$lib\"; then\n\t\t\t$ECHO \"*** Warning: lib $linklib is a module, not a shared library\"\n\t\t\tif test -z \"$old_library\"; then\n\t\t\t  echo\n\t\t\t  echo \"*** And there doesn't seem to be a static archive available\"\n\t\t\t  echo \"*** The link will probably fail, sorry\"\n\t\t\telse\n\t\t\t  add=$dir/$old_library\n\t\t\tfi\n\t\t      elif test -n \"$old_library\"; then\n\t\t\tadd=$dir/$old_library\n\t\t      fi\n\t\t    fi\n\t\tesac\n\t      elif test no = \"$hardcode_minus_L\"; then\n\t\tcase $host in\n\t\t*-*-sunos*) add_shlibpath=$dir ;;\n\t\tesac\n\t\tadd_dir=-L$dir\n\t\tadd=-l$name\n\t      elif test no = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    relink)\n\t      if test yes = \"$hardcode_direct\" &&\n\t         test no = \"$hardcode_direct_absolute\"; then\n\t\tadd=$dir/$linklib\n\t      elif test yes = \"$hardcode_minus_L\"; then\n\t\tadd_dir=-L$absdir\n\t\t# Try looking first in the location we're being installed to.\n\t\tif test -n \"$inst_prefix_dir\"; then\n\t\t  case $libdir in\n\t\t    [\\\\/]*)\n\t\t      func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t      ;;\n\t\t  esac\n\t\tfi\n\t\tadd=-l$name\n\t      elif test yes = \"$hardcode_shlibpath_var\"; then\n\t\tadd_shlibpath=$dir\n\t\tadd=-l$name\n\t      else\n\t\tlib_linked=no\n\t      fi\n\t      ;;\n\t    *) lib_linked=no ;;\n\t    esac\n\n\t    if test yes != \"$lib_linked\"; then\n\t      func_fatal_configuration \"unsupported hardcode properties\"\n\t    fi\n\n\t    if test -n \"$add_shlibpath\"; then\n\t      case :$compile_shlibpath: in\n\t      *\":$add_shlibpath:\"*) ;;\n\t      *) func_append compile_shlibpath \"$add_shlibpath:\" ;;\n\t      esac\n\t    fi\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && compile_deplibs=\"$add_dir $compile_deplibs\"\n\t      test -n \"$add\" && compile_deplibs=\"$add $compile_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t      if test yes != \"$hardcode_direct\" &&\n\t\t test yes != \"$hardcode_minus_L\" &&\n\t\t test yes = \"$hardcode_shlibpath_var\"; then\n\t\tcase :$finalize_shlibpath: in\n\t\t*\":$libdir:\"*) ;;\n\t\t*) func_append finalize_shlibpath \"$libdir:\" ;;\n\t\tesac\n\t      fi\n\t    fi\n\t  fi\n\n\t  if test prog = \"$linkmode\" || test relink = \"$opt_mode\"; then\n\t    add_shlibpath=\n\t    add_dir=\n\t    add=\n\t    # Finalize command for both is simple: just hardcode it.\n\t    if test yes = \"$hardcode_direct\" &&\n\t       test no = \"$hardcode_direct_absolute\"; then\n\t      add=$libdir/$linklib\n\t    elif test yes = \"$hardcode_minus_L\"; then\n\t      add_dir=-L$libdir\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_shlibpath_var\"; then\n\t      case :$finalize_shlibpath: in\n\t      *\":$libdir:\"*) ;;\n\t      *) func_append finalize_shlibpath \"$libdir:\" ;;\n\t      esac\n\t      add=-l$name\n\t    elif test yes = \"$hardcode_automatic\"; then\n\t      if test -n \"$inst_prefix_dir\" &&\n\t\t test -f \"$inst_prefix_dir$libdir/$linklib\"; then\n\t\tadd=$inst_prefix_dir$libdir/$linklib\n\t      else\n\t\tadd=$libdir/$linklib\n\t      fi\n\t    else\n\t      # We cannot seem to hardcode it, guess we'll fake it.\n\t      add_dir=-L$libdir\n\t      # Try looking first in the location we're being installed to.\n\t      if test -n \"$inst_prefix_dir\"; then\n\t\tcase $libdir in\n\t\t  [\\\\/]*)\n\t\t    func_append add_dir \" -L$inst_prefix_dir$libdir\"\n\t\t    ;;\n\t\tesac\n\t      fi\n\t      add=-l$name\n\t    fi\n\n\t    if test prog = \"$linkmode\"; then\n\t      test -n \"$add_dir\" && finalize_deplibs=\"$add_dir $finalize_deplibs\"\n\t      test -n \"$add\" && finalize_deplibs=\"$add $finalize_deplibs\"\n\t    else\n\t      test -n \"$add_dir\" && deplibs=\"$add_dir $deplibs\"\n\t      test -n \"$add\" && deplibs=\"$add $deplibs\"\n\t    fi\n\t  fi\n\telif test prog = \"$linkmode\"; then\n\t  # Here we assume that one of hardcode_direct or hardcode_minus_L\n\t  # is not unsupported.  This is valid on all known static and\n\t  # shared platforms.\n\t  if test unsupported != \"$hardcode_direct\"; then\n\t    test -n \"$old_library\" && linklib=$old_library\n\t    compile_deplibs=\"$dir/$linklib $compile_deplibs\"\n\t    finalize_deplibs=\"$dir/$linklib $finalize_deplibs\"\n\t  else\n\t    compile_deplibs=\"-l$name -L$dir $compile_deplibs\"\n\t    finalize_deplibs=\"-l$name -L$dir $finalize_deplibs\"\n\t  fi\n\telif test yes = \"$build_libtool_libs\"; then\n\t  # Not a shared library\n\t  if test pass_all != \"$deplibs_check_method\"; then\n\t    # We're trying link a shared library against a static one\n\t    # but the system doesn't support it.\n\n\t    # Just print a warning and add the library to dependency_libs so\n\t    # that the program can be linked against the static library.\n\t    echo\n\t    $ECHO \"*** Warning: This system cannot link to static lib archive $lib.\"\n\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t    echo \"*** shared version of the library, which you do not appear to have.\"\n\t    if test yes = \"$module\"; then\n\t      echo \"*** But as you try to build a module library, libtool will still create \"\n\t      echo \"*** a static module, that should work as long as the dlopening application\"\n\t      echo \"*** is linked with the -dlopen flag to resolve symbols at runtime.\"\n\t      if test -z \"$global_symbol_pipe\"; then\n\t\techo\n\t\techo \"*** However, this would only work if libtool was able to extract symbol\"\n\t\techo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t\techo \"*** not find such a program.  So, this module is probably useless.\"\n\t\techo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t      fi\n\t      if test no = \"$build_old_libs\"; then\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  else\n\t    deplibs=\"$dir/$old_library $deplibs\"\n\t    link_static=yes\n\t  fi\n\tfi # link shared/static library?\n\n\tif test lib = \"$linkmode\"; then\n\t  if test -n \"$dependency_libs\" &&\n\t     { test yes != \"$hardcode_into_libs\" ||\n\t       test yes = \"$build_old_libs\" ||\n\t       test yes = \"$link_static\"; }; then\n\t    # Extract -R from dependency_libs\n\t    temp_deplibs=\n\t    for libdir in $dependency_libs; do\n\t      case $libdir in\n\t      -R*) func_stripname '-R' '' \"$libdir\"\n\t           temp_xrpath=$func_stripname_result\n\t\t   case \" $xrpath \" in\n\t\t   *\" $temp_xrpath \"*) ;;\n\t\t   *) func_append xrpath \" $temp_xrpath\";;\n\t\t   esac;;\n\t      *) func_append temp_deplibs \" $libdir\";;\n\t      esac\n\t    done\n\t    dependency_libs=$temp_deplibs\n\t  fi\n\n\t  func_append newlib_search_path \" $absdir\"\n\t  # Link against this library\n\t  test no = \"$link_static\" && newdependency_libs=\"$abs_ladir/$laname $newdependency_libs\"\n\t  # ... and its dependency_libs\n\t  tmp_libs=\n\t  for deplib in $dependency_libs; do\n\t    newdependency_libs=\"$deplib $newdependency_libs\"\n\t    case $deplib in\n              -L*) func_stripname '-L' '' \"$deplib\"\n                   func_resolve_sysroot \"$func_stripname_result\";;\n              *) func_resolve_sysroot \"$deplib\" ;;\n            esac\n\t    if $opt_preserve_dup_deps; then\n\t      case \"$tmp_libs \" in\n\t      *\" $func_resolve_sysroot_result \"*)\n                func_append specialdeplibs \" $func_resolve_sysroot_result\" ;;\n\t      esac\n\t    fi\n\t    func_append tmp_libs \" $func_resolve_sysroot_result\"\n\t  done\n\n\t  if test no != \"$link_all_deplibs\"; then\n\t    # Add the search paths of all dependency libraries\n\t    for deplib in $dependency_libs; do\n\t      path=\n\t      case $deplib in\n\t      -L*) path=$deplib ;;\n\t      *.la)\n\t        func_resolve_sysroot \"$deplib\"\n\t        deplib=$func_resolve_sysroot_result\n\t        func_dirname \"$deplib\" \"\" \".\"\n\t\tdir=$func_dirname_result\n\t\t# We need an absolute path.\n\t\tcase $dir in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) absdir=$dir ;;\n\t\t*)\n\t\t  absdir=`cd \"$dir\" && pwd`\n\t\t  if test -z \"$absdir\"; then\n\t\t    func_warning \"cannot determine absolute directory name of '$dir'\"\n\t\t    absdir=$dir\n\t\t  fi\n\t\t  ;;\n\t\tesac\n\t\tif $GREP \"^installed=no\" $deplib > /dev/null; then\n\t\tcase $host in\n\t\t*-*-darwin*)\n\t\t  depdepl=\n\t\t  eval deplibrary_names=`$SED -n -e 's/^library_names=\\(.*\\)$/\\1/p' $deplib`\n\t\t  if test -n \"$deplibrary_names\"; then\n\t\t    for tmp in $deplibrary_names; do\n\t\t      depdepl=$tmp\n\t\t    done\n\t\t    if test -f \"$absdir/$objdir/$depdepl\"; then\n\t\t      depdepl=$absdir/$objdir/$depdepl\n\t\t      darwin_install_name=`$OTOOL -L $depdepl | awk '{if (NR == 2) {print $1;exit}}'`\n                      if test -z \"$darwin_install_name\"; then\n                          darwin_install_name=`$OTOOL64 -L $depdepl  | awk '{if (NR == 2) {print $1;exit}}'`\n                      fi\n\t\t      func_append compiler_flags \" $wl-dylib_file $wl$darwin_install_name:$depdepl\"\n\t\t      func_append linker_flags \" -dylib_file $darwin_install_name:$depdepl\"\n\t\t      path=\n\t\t    fi\n\t\t  fi\n\t\t  ;;\n\t\t*)\n\t\t  path=-L$absdir/$objdir\n\t\t  ;;\n\t\tesac\n\t\telse\n\t\t  eval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $deplib`\n\t\t  test -z \"$libdir\" && \\\n\t\t    func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\t  test \"$absdir\" != \"$libdir\" && \\\n\t\t    func_warning \"'$deplib' seems to be moved\"\n\n\t\t  path=-L$absdir\n\t\tfi\n\t\t;;\n\t      esac\n\t      case \" $deplibs \" in\n\t      *\" $path \"*) ;;\n\t      *) deplibs=\"$path $deplibs\" ;;\n\t      esac\n\t    done\n\t  fi # link_all_deplibs != no\n\tfi # linkmode = lib\n      done # for deplib in $libs\n      if test link = \"$pass\"; then\n\tif test prog = \"$linkmode\"; then\n\t  compile_deplibs=\"$new_inherited_linker_flags $compile_deplibs\"\n\t  finalize_deplibs=\"$new_inherited_linker_flags $finalize_deplibs\"\n\telse\n\t  compiler_flags=\"$compiler_flags \"`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfi\n      fi\n      dependency_libs=$newdependency_libs\n      if test dlpreopen = \"$pass\"; then\n\t# Link the dlpreopened libraries before other libraries\n\tfor deplib in $save_deplibs; do\n\t  deplibs=\"$deplib $deplibs\"\n\tdone\n      fi\n      if test dlopen != \"$pass\"; then\n\ttest conv = \"$pass\" || {\n\t  # Make sure lib_search_path contains only unique directories.\n\t  lib_search_path=\n\t  for dir in $newlib_search_path; do\n\t    case \"$lib_search_path \" in\n\t    *\" $dir \"*) ;;\n\t    *) func_append lib_search_path \" $dir\" ;;\n\t    esac\n\t  done\n\t  newlib_search_path=\n\t}\n\n\tif test prog,link = \"$linkmode,$pass\"; then\n\t  vars=\"compile_deplibs finalize_deplibs\"\n\telse\n\t  vars=deplibs\n\tfi\n\tfor var in $vars dependency_libs; do\n\t  # Add libraries to $var in reverse order\n\t  eval tmp_libs=\\\"\\$$var\\\"\n\t  new_libs=\n\t  for deplib in $tmp_libs; do\n\t    # FIXME: Pedantically, this is the right thing to do, so\n\t    #        that some nasty dependency loop isn't accidentally\n\t    #        broken:\n\t    #new_libs=\"$deplib $new_libs\"\n\t    # Pragmatically, this seems to cause very few problems in\n\t    # practice:\n\t    case $deplib in\n\t    -L*) new_libs=\"$deplib $new_libs\" ;;\n\t    -R*) ;;\n\t    *)\n\t      # And here is the reason: when a library appears more\n\t      # than once as an explicit dependence of a library, or\n\t      # is implicitly linked in more than once by the\n\t      # compiler, it is considered special, and multiple\n\t      # occurrences thereof are not removed.  Compare this\n\t      # with having the same library being listed as a\n\t      # dependency of multiple other libraries: in this case,\n\t      # we know (pedantically, we assume) the library does not\n\t      # need to be listed more than once, so we keep only the\n\t      # last copy.  This is not always right, but it is rare\n\t      # enough that we require users that really mean to play\n\t      # such unportable linking tricks to link the library\n\t      # using -Wl,-lname, so that libtool does not consider it\n\t      # for duplicate removal.\n\t      case \" $specialdeplibs \" in\n\t      *\" $deplib \"*) new_libs=\"$deplib $new_libs\" ;;\n\t      *)\n\t\tcase \" $new_libs \" in\n\t\t*\" $deplib \"*) ;;\n\t\t*) new_libs=\"$deplib $new_libs\" ;;\n\t\tesac\n\t\t;;\n\t      esac\n\t      ;;\n\t    esac\n\t  done\n\t  tmp_libs=\n\t  for deplib in $new_libs; do\n\t    case $deplib in\n\t    -L*)\n\t      case \" $tmp_libs \" in\n\t      *\" $deplib \"*) ;;\n\t      *) func_append tmp_libs \" $deplib\" ;;\n\t      esac\n\t      ;;\n\t    *) func_append tmp_libs \" $deplib\" ;;\n\t    esac\n\t  done\n\t  eval $var=\\\"$tmp_libs\\\"\n\tdone # for var\n      fi\n\n      # Add Sun CC postdeps if required:\n      test CXX = \"$tagname\" && {\n        case $host_os in\n        linux*)\n          case `$CC -V 2>&1 | sed 5q` in\n          *Sun\\ C*) # Sun C++ 5.9\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n\n        solaris*)\n          func_cc_basename \"$CC\"\n          case $func_cc_basename_result in\n          CC* | sunCC*)\n            func_suncc_cstd_abi\n\n            if test no != \"$suncc_use_cstd_abi\"; then\n              func_append postdeps ' -library=Cstd -library=Crun'\n            fi\n            ;;\n          esac\n          ;;\n        esac\n      }\n\n      # Last step: remove runtime libs from dependency_libs\n      # (they stay in deplibs)\n      tmp_libs=\n      for i in $dependency_libs; do\n\tcase \" $predeps $postdeps $compiler_lib_search_path \" in\n\t*\" $i \"*)\n\t  i=\n\t  ;;\n\tesac\n\tif test -n \"$i\"; then\n\t  func_append tmp_libs \" $i\"\n\tfi\n      done\n      dependency_libs=$tmp_libs\n    done # for pass\n    if test prog = \"$linkmode\"; then\n      dlfiles=$newdlfiles\n    fi\n    if test prog = \"$linkmode\" || test lib = \"$linkmode\"; then\n      dlprefiles=$newdlprefiles\n    fi\n\n    case $linkmode in\n    oldlib)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for archives\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for archives\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for archives\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for archives\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info/-version-number' is ignored for archives\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for archives\"\n\n      test -n \"$export_symbols$export_symbols_regex\" && \\\n\tfunc_warning \"'-export-symbols' is ignored for archives\"\n\n      # Now set the variables for building old libraries.\n      build_libtool_libs=no\n      oldlibs=$output\n      func_append objs \"$old_deplibs\"\n      ;;\n\n    lib)\n      # Make sure we only generate libraries of the form 'libNAME.la'.\n      case $outputname in\n      lib*)\n\tfunc_stripname 'lib' '.la' \"$outputname\"\n\tname=$func_stripname_result\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval libname=\\\"$libname_spec\\\"\n\t;;\n      *)\n\ttest no = \"$module\" \\\n\t  && func_fatal_help \"libtool library '$output' must begin with 'lib'\"\n\n\tif test no != \"$need_lib_prefix\"; then\n\t  # Add the \"lib\" prefix for modules if required\n\t  func_stripname '' '.la' \"$outputname\"\n\t  name=$func_stripname_result\n\t  eval shared_ext=\\\"$shrext_cmds\\\"\n\t  eval libname=\\\"$libname_spec\\\"\n\telse\n\t  func_stripname '' '.la' \"$outputname\"\n\t  libname=$func_stripname_result\n\tfi\n\t;;\n      esac\n\n      if test -n \"$objs\"; then\n\tif test pass_all != \"$deplibs_check_method\"; then\n\t  func_fatal_error \"cannot build libtool library '$output' from non-libtool objects on this host:$objs\"\n\telse\n\t  echo\n\t  $ECHO \"*** Warning: Linking the shared library $output against the non-libtool\"\n\t  $ECHO \"*** objects $objs is not portable!\"\n\t  func_append libobjs \" $objs\"\n\tfi\n      fi\n\n      test no = \"$dlself\" \\\n\t|| func_warning \"'-dlopen self' is ignored for libtool libraries\"\n\n      set dummy $rpath\n      shift\n      test 1 -lt \"$#\" \\\n\t&& func_warning \"ignoring multiple '-rpath's for a libtool library\"\n\n      install_libdir=$1\n\n      oldlibs=\n      if test -z \"$rpath\"; then\n\tif test yes = \"$build_libtool_libs\"; then\n\t  # Building a libtool convenience library.\n\t  # Some compilers have problems with a '.al' extension so\n\t  # convenience libraries should have the same extension an\n\t  # archive normally would.\n\t  oldlibs=\"$output_objdir/$libname.$libext $oldlibs\"\n\t  build_libtool_libs=convenience\n\t  build_old_libs=yes\n\tfi\n\n\ttest -n \"$vinfo\" && \\\n\t  func_warning \"'-version-info/-version-number' is ignored for convenience libraries\"\n\n\ttest -n \"$release\" && \\\n\t  func_warning \"'-release' is ignored for convenience libraries\"\n      else\n\n\t# Parse the version information argument.\n\tsave_ifs=$IFS; IFS=:\n\tset dummy $vinfo 0 0 0\n\tshift\n\tIFS=$save_ifs\n\n\ttest -n \"$7\" && \\\n\t  func_fatal_help \"too many parameters to '-version-info'\"\n\n\t# convert absolute version numbers to libtool ages\n\t# this retains compatibility with .la files and attempts\n\t# to make the code below a bit more comprehensible\n\n\tcase $vinfo_number in\n\tyes)\n\t  number_major=$1\n\t  number_minor=$2\n\t  number_revision=$3\n\t  #\n\t  # There are really only two kinds -- those that\n\t  # use the current revision as the major version\n\t  # and those that subtract age and use age as\n\t  # a minor version.  But, then there is irix\n\t  # that has an extra 1 added just for fun\n\t  #\n\t  case $version_type in\n\t  # correct linux to gnu/linux during the next big refactor\n\t  darwin|freebsd-elf|linux|osf|windows|none)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_revision\n\t    ;;\n\t  freebsd-aout|qnx|sunos)\n\t    current=$number_major\n\t    revision=$number_minor\n\t    age=0\n\t    ;;\n\t  irix|nonstopux)\n\t    func_arith $number_major + $number_minor\n\t    current=$func_arith_result\n\t    age=$number_minor\n\t    revision=$number_minor\n\t    lt_irix_increment=no\n\t    ;;\n\t  *)\n\t    func_fatal_configuration \"$modename: unknown library version type '$version_type'\"\n\t    ;;\n\t  esac\n\t  ;;\n\tno)\n\t  current=$1\n\t  revision=$2\n\t  age=$3\n\t  ;;\n\tesac\n\n\t# Check that each of the things are valid numbers.\n\tcase $current in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"CURRENT '$current' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $revision in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"REVISION '$revision' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tcase $age in\n\t0|[1-9]|[1-9][0-9]|[1-9][0-9][0-9]|[1-9][0-9][0-9][0-9]|[1-9][0-9][0-9][0-9][0-9]) ;;\n\t*)\n\t  func_error \"AGE '$age' must be a nonnegative integer\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\t  ;;\n\tesac\n\n\tif test \"$age\" -gt \"$current\"; then\n\t  func_error \"AGE '$age' is greater than the current interface number '$current'\"\n\t  func_fatal_error \"'$vinfo' is not valid version information\"\n\tfi\n\n\t# Calculate the version variables.\n\tmajor=\n\tversuffix=\n\tverstring=\n\tcase $version_type in\n\tnone) ;;\n\n\tdarwin)\n\t  # Like Linux, but with the current version available in\n\t  # verstring for coding it into the library header\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  # Darwin ld doesn't like 0 for these options...\n\t  func_arith $current + 1\n\t  minor_current=$func_arith_result\n\t  xlcverstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n\t  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n          # On Darwin other compilers\n          case $CC in\n              nagfor*)\n                  verstring=\"$wl-compatibility_version $wl$minor_current $wl-current_version $wl$minor_current.$revision\"\n                  ;;\n              *)\n                  verstring=\"-compatibility_version $minor_current -current_version $minor_current.$revision\"\n                  ;;\n          esac\n\t  ;;\n\n\tfreebsd-aout)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\tfreebsd-elf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tirix | nonstopux)\n\t  if test no = \"$lt_irix_increment\"; then\n\t    func_arith $current - $age\n\t  else\n\t    func_arith $current - $age + 1\n\t  fi\n\t  major=$func_arith_result\n\n\t  case $version_type in\n\t    nonstopux) verstring_prefix=nonstopux ;;\n\t    *)         verstring_prefix=sgi ;;\n\t  esac\n\t  verstring=$verstring_prefix$major.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$revision\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $revision - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring_prefix$major.$iface:$verstring\n\t  done\n\n\t  # Before this point, $major must not contain '.'.\n\t  major=.$major\n\t  versuffix=$major.$revision\n\t  ;;\n\n\tlinux) # correct to gnu/linux during the next big refactor\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=$major.$age.$revision\n\t  ;;\n\n\tosf)\n\t  func_arith $current - $age\n\t  major=.$func_arith_result\n\t  versuffix=.$current.$age.$revision\n\t  verstring=$current.$age.$revision\n\n\t  # Add in all the interfaces that we are compatible with.\n\t  loop=$age\n\t  while test 0 -ne \"$loop\"; do\n\t    func_arith $current - $loop\n\t    iface=$func_arith_result\n\t    func_arith $loop - 1\n\t    loop=$func_arith_result\n\t    verstring=$verstring:$iface.0\n\t  done\n\n\t  # Make executables depend on our current version.\n\t  func_append verstring \":$current.0\"\n\t  ;;\n\n\tqnx)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsco)\n\t  major=.$current\n\t  versuffix=.$current\n\t  ;;\n\n\tsunos)\n\t  major=.$current\n\t  versuffix=.$current.$revision\n\t  ;;\n\n\twindows)\n\t  # Use '-' rather than '.', since we only want one\n\t  # extension on DOS 8.3 file systems.\n\t  func_arith $current - $age\n\t  major=$func_arith_result\n\t  versuffix=-$major\n\t  ;;\n\n\t*)\n\t  func_fatal_configuration \"unknown library version type '$version_type'\"\n\t  ;;\n\tesac\n\n\t# Clear the version info if we defaulted, and they specified a release.\n\tif test -z \"$vinfo\" && test -n \"$release\"; then\n\t  major=\n\t  case $version_type in\n\t  darwin)\n\t    # we can't check for \"0.0\" in archive_cmds due to quoting\n\t    # problems, so we reset it completely\n\t    verstring=\n\t    ;;\n\t  *)\n\t    verstring=0.0\n\t    ;;\n\t  esac\n\t  if test no = \"$need_version\"; then\n\t    versuffix=\n\t  else\n\t    versuffix=.0.0\n\t  fi\n\tfi\n\n\t# Remove version info from name if versioning should be avoided\n\tif test yes,no = \"$avoid_version,$need_version\"; then\n\t  major=\n\t  versuffix=\n\t  verstring=\n\tfi\n\n\t# Check to see if the archive will have undefined symbols.\n\tif test yes = \"$allow_undefined\"; then\n\t  if test unsupported = \"$allow_undefined_flag\"; then\n\t    if test yes = \"$build_old_libs\"; then\n\t      func_warning \"undefined symbols not allowed in $host shared libraries; building static only\"\n\t      build_libtool_libs=no\n\t    else\n\t      func_fatal_error \"can't build $host shared library unless -no-undefined is specified\"\n\t    fi\n\t  fi\n\telse\n\t  # Don't allow undefined symbols.\n\t  allow_undefined_flag=$no_undefined_flag\n\tfi\n\n      fi\n\n      func_generate_dlsyms \"$libname\" \"$libname\" :\n      func_append libobjs \" $symfileobj\"\n      test \" \" = \"$libobjs\" && libobjs=\n\n      if test relink != \"$opt_mode\"; then\n\t# Remove our outputs, but don't remove object files since they\n\t# may have been created when compiling PIC objects.\n\tremovelist=\n\ttempremovelist=`$ECHO \"$output_objdir/*\"`\n\tfor p in $tempremovelist; do\n\t  case $p in\n\t    *.$objext | *.gcno)\n\t       ;;\n\t    $output_objdir/$outputname | $output_objdir/$libname.* | $output_objdir/$libname$release.*)\n\t       if test -n \"$precious_files_regex\"; then\n\t\t if $ECHO \"$p\" | $EGREP -e \"$precious_files_regex\" >/dev/null 2>&1\n\t\t then\n\t\t   continue\n\t\t fi\n\t       fi\n\t       func_append removelist \" $p\"\n\t       ;;\n\t    *) ;;\n\t  esac\n\tdone\n\ttest -n \"$removelist\" && \\\n\t  func_show_eval \"${RM}r \\$removelist\"\n      fi\n\n      # Now set the variables for building old libraries.\n      if test yes = \"$build_old_libs\" && test convenience != \"$build_libtool_libs\"; then\n\tfunc_append oldlibs \" $output_objdir/$libname.$libext\"\n\n\t# Transform .lo files to .o files.\n\toldobjs=\"$objs \"`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; $lo2o\" | $NL2SP`\n      fi\n\n      # Eliminate all temporary directories.\n      #for path in $notinst_path; do\n      #\tlib_search_path=`$ECHO \"$lib_search_path \" | $SED \"s% $path % %g\"`\n      #\tdeplibs=`$ECHO \"$deplibs \" | $SED \"s% -L$path % %g\"`\n      #\tdependency_libs=`$ECHO \"$dependency_libs \" | $SED \"s% -L$path % %g\"`\n      #done\n\n      if test -n \"$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\ttemp_xrpath=\n\tfor libdir in $xrpath; do\n\t  func_replace_sysroot \"$libdir\"\n\t  func_append temp_xrpath \" -R$func_replace_sysroot_result\"\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n\tif test yes != \"$hardcode_into_libs\" || test yes = \"$build_old_libs\"; then\n\t  dependency_libs=\"$temp_xrpath $dependency_libs\"\n\tfi\n      fi\n\n      # Make sure dlfiles contains only unique files that won't be dlpreopened\n      old_dlfiles=$dlfiles\n      dlfiles=\n      for lib in $old_dlfiles; do\n\tcase \" $dlprefiles $dlfiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlfiles \" $lib\" ;;\n\tesac\n      done\n\n      # Make sure dlprefiles contains only unique files\n      old_dlprefiles=$dlprefiles\n      dlprefiles=\n      for lib in $old_dlprefiles; do\n\tcase \"$dlprefiles \" in\n\t*\" $lib \"*) ;;\n\t*) func_append dlprefiles \" $lib\" ;;\n\tesac\n      done\n\n      if test yes = \"$build_libtool_libs\"; then\n\tif test -n \"$rpath\"; then\n\t  case $host in\n\t  *-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-*-beos* | *-cegcc* | *-*-haiku*)\n\t    # these systems don't actually have a c library (as such)!\n\t    ;;\n\t  *-*-rhapsody* | *-*-darwin1.[012])\n\t    # Rhapsody C library is in the System framework\n\t    func_append deplibs \" System.ltframework\"\n\t    ;;\n\t  *-*-netbsd*)\n\t    # Don't link with libc until the a.out ld.so is fixed.\n\t    ;;\n\t  *-*-openbsd* | *-*-freebsd* | *-*-dragonfly*)\n\t    # Do not include libc due to us having libc/libc_r.\n\t    ;;\n\t  *-*-sco3.2v5* | *-*-sco5v6*)\n\t    # Causes problems with __ctype\n\t    ;;\n\t  *-*-sysv4.2uw2* | *-*-sysv5* | *-*-unixware* | *-*-OpenUNIX*)\n\t    # Compiler inserts libc in the correct place for threads to work\n\t    ;;\n\t  *)\n\t    # Add libc to deplibs on all other systems if necessary.\n\t    if test yes = \"$build_libtool_need_lc\"; then\n\t      func_append deplibs \" -lc\"\n\t    fi\n\t    ;;\n\t  esac\n\tfi\n\n\t# Transform deplibs into only deplibs that can be linked in shared.\n\tname_save=$name\n\tlibname_save=$libname\n\trelease_save=$release\n\tversuffix_save=$versuffix\n\tmajor_save=$major\n\t# I'm not sure if I'm treating the release correctly.  I think\n\t# release should show up in the -l (ie -lgmp5) so we don't want to\n\t# add it in twice.  Is that correct?\n\trelease=\n\tversuffix=\n\tmajor=\n\tnewdeplibs=\n\tdroppeddeps=no\n\tcase $deplibs_check_method in\n\tpass_all)\n\t  # Don't check for shared/static.  Everything works.\n\t  # This might be a little naive.  We might want to check\n\t  # whether the library exists or not.  But this is on\n\t  # osf3 & osf4 and I'm not really sure... Just\n\t  # implementing what was already the behavior.\n\t  newdeplibs=$deplibs\n\t  ;;\n\ttest_compile)\n\t  # This code stresses the \"libraries are programs\" paradigm to its\n\t  # limits. Maybe even breaks it.  We compile a program, linking it\n\t  # against the deplibs as a proxy for the library.  Then we can check\n\t  # whether they linked in statically or dynamically with ldd.\n\t  $opt_dry_run || $RM conftest.c\n\t  cat > conftest.c <<EOF\n\t  int main() { return 0; }\nEOF\n\t  $opt_dry_run || $RM conftest\n\t  if $LTCC $LTCFLAGS -o conftest conftest.c $deplibs; then\n\t    ldd_output=`ldd conftest`\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\tif test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t  case \" $predeps $postdeps \" in\n\t\t  *\" $i \"*)\n\t\t    func_append newdeplibs \" $i\"\n\t\t    i=\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t\tif test -n \"$i\"; then\n\t\t  libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t  deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t  set dummy $deplib_matches; shift\n\t\t  deplib_match=$1\n\t\t  if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t    func_append newdeplibs \" $i\"\n\t\t  else\n\t\t    droppeddeps=yes\n\t\t    echo\n\t\t    $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t    echo \"*** I have the capability to make that library automatically link in when\"\n\t\t    echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t    echo \"*** shared version of the library, which I believe you do not have\"\n\t\t    echo \"*** because a test_compile did reveal that the linker did not use it for\"\n\t\t    echo \"*** its dynamic dependency list that programs get resolved with at runtime.\"\n\t\t  fi\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  else\n\t    # Error occurred in the first compile.  Let's try to salvage\n\t    # the situation: Compile a separate program for each library.\n\t    for i in $deplibs; do\n\t      case $i in\n\t      -l*)\n\t\tfunc_stripname -l '' \"$i\"\n\t\tname=$func_stripname_result\n\t\t$opt_dry_run || $RM conftest\n\t\tif $LTCC $LTCFLAGS -o conftest conftest.c $i; then\n\t\t  ldd_output=`ldd conftest`\n\t\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\t    case \" $predeps $postdeps \" in\n\t\t    *\" $i \"*)\n\t\t      func_append newdeplibs \" $i\"\n\t\t      i=\n\t\t      ;;\n\t\t    esac\n\t\t  fi\n\t\t  if test -n \"$i\"; then\n\t\t    libname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\t    deplib_matches=`eval \"\\\\$ECHO \\\"$library_names_spec\\\"\"`\n\t\t    set dummy $deplib_matches; shift\n\t\t    deplib_match=$1\n\t\t    if test `expr \"$ldd_output\" : \".*$deplib_match\"` -ne 0; then\n\t\t      func_append newdeplibs \" $i\"\n\t\t    else\n\t\t      droppeddeps=yes\n\t\t      echo\n\t\t      $ECHO \"*** Warning: dynamic linker does not accept needed library $i.\"\n\t\t      echo \"*** I have the capability to make that library automatically link in when\"\n\t\t      echo \"*** you link to this library.  But I can only do this if you have a\"\n\t\t      echo \"*** shared version of the library, which you do not appear to have\"\n\t\t      echo \"*** because a test_compile did reveal that the linker did not use this one\"\n\t\t      echo \"*** as a dynamic dependency that programs can get resolved with at runtime.\"\n\t\t    fi\n\t\t  fi\n\t\telse\n\t\t  droppeddeps=yes\n\t\t  echo\n\t\t  $ECHO \"*** Warning!  Library $i is needed by this library but I was not able to\"\n\t\t  echo \"*** make it link in!  You will probably need to install it or some\"\n\t\t  echo \"*** library that it depends on before this library will be fully\"\n\t\t  echo \"*** functional.  Installing it before continuing would be even better.\"\n\t\tfi\n\t\t;;\n\t      *)\n\t\tfunc_append newdeplibs \" $i\"\n\t\t;;\n\t      esac\n\t    done\n\t  fi\n\t  ;;\n\tfile_magic*)\n\t  set dummy $deplibs_check_method; shift\n\t  file_magic_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tif test -n \"$file_magic_glob\"; then\n\t\t  libnameglob=`func_echo_all \"$libname\" | $SED -e $file_magic_glob`\n\t\telse\n\t\t  libnameglob=$libname\n\t\tfi\n\t\ttest yes = \"$want_nocaseglob\" && nocaseglob=`shopt -p nocaseglob`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  if test yes = \"$want_nocaseglob\"; then\n\t\t    shopt -s nocaseglob\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t    $nocaseglob\n\t\t  else\n\t\t    potential_libs=`ls $i/$libnameglob[.-]* 2>/dev/null`\n\t\t  fi\n\t\t  for potent_lib in $potential_libs; do\n\t\t      # Follow soft links.\n\t\t      if ls -lLd \"$potent_lib\" 2>/dev/null |\n\t\t\t $GREP \" -> \" >/dev/null; then\n\t\t\tcontinue\n\t\t      fi\n\t\t      # The statement above tries to avoid entering an\n\t\t      # endless loop below, in case of cyclic links.\n\t\t      # We might still enter an endless loop, since a link\n\t\t      # loop can be closed while we follow links,\n\t\t      # but so what?\n\t\t      potlib=$potent_lib\n\t\t      while test -h \"$potlib\" 2>/dev/null; do\n\t\t\tpotliblink=`ls -ld $potlib | $SED 's/.* -> //'`\n\t\t\tcase $potliblink in\n\t\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) potlib=$potliblink;;\n\t\t\t*) potlib=`$ECHO \"$potlib\" | $SED 's|[^/]*$||'`\"$potliblink\";;\n\t\t\tesac\n\t\t      done\n\t\t      if eval $file_magic_cmd \\\"\\$potlib\\\" 2>/dev/null |\n\t\t\t $SED -e 10q |\n\t\t\t $EGREP \"$file_magic_regex\" > /dev/null; then\n\t\t\tfunc_append newdeplibs \" $a_deplib\"\n\t\t\ta_deplib=\n\t\t\tbreak 2\n\t\t      fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for file magic test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a file magic. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tmatch_pattern*)\n\t  set dummy $deplibs_check_method; shift\n\t  match_pattern_regex=`expr \"$deplibs_check_method\" : \"$1 \\(.*\\)\"`\n\t  for a_deplib in $deplibs; do\n\t    case $a_deplib in\n\t    -l*)\n\t      func_stripname -l '' \"$a_deplib\"\n\t      name=$func_stripname_result\n\t      if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t\tcase \" $predeps $postdeps \" in\n\t\t*\" $a_deplib \"*)\n\t\t  func_append newdeplibs \" $a_deplib\"\n\t\t  a_deplib=\n\t\t  ;;\n\t\tesac\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tlibname=`eval \"\\\\$ECHO \\\"$libname_spec\\\"\"`\n\t\tfor i in $lib_search_path $sys_lib_search_path $shlib_search_path; do\n\t\t  potential_libs=`ls $i/$libname[.-]* 2>/dev/null`\n\t\t  for potent_lib in $potential_libs; do\n\t\t    potlib=$potent_lib # see symlink-check above in file_magic test\n\t\t    if eval \"\\$ECHO \\\"$potent_lib\\\"\" 2>/dev/null | $SED 10q | \\\n\t\t       $EGREP \"$match_pattern_regex\" > /dev/null; then\n\t\t      func_append newdeplibs \" $a_deplib\"\n\t\t      a_deplib=\n\t\t      break 2\n\t\t    fi\n\t\t  done\n\t\tdone\n\t      fi\n\t      if test -n \"$a_deplib\"; then\n\t\tdroppeddeps=yes\n\t\techo\n\t\t$ECHO \"*** Warning: linker path does not have real file for library $a_deplib.\"\n\t\techo \"*** I have the capability to make that library automatically link in when\"\n\t\techo \"*** you link to this library.  But I can only do this if you have a\"\n\t\techo \"*** shared version of the library, which you do not appear to have\"\n\t\techo \"*** because I did check the linker path looking for a file starting\"\n\t\tif test -z \"$potlib\"; then\n\t\t  $ECHO \"*** with $libname but no candidates were found. (...for regex pattern test)\"\n\t\telse\n\t\t  $ECHO \"*** with $libname and none of the candidates passed a file format test\"\n\t\t  $ECHO \"*** using a regex pattern. Last file checked: $potlib\"\n\t\tfi\n\t      fi\n\t      ;;\n\t    *)\n\t      # Add a -L argument.\n\t      func_append newdeplibs \" $a_deplib\"\n\t      ;;\n\t    esac\n\t  done # Gone through all deplibs.\n\t  ;;\n\tnone | unknown | *)\n\t  newdeplibs=\n\t  tmp_deplibs=`$ECHO \" $deplibs\" | $SED 's/ -lc$//; s/ -[LR][^ ]*//g'`\n\t  if test yes = \"$allow_libtool_libs_with_static_runtimes\"; then\n\t    for i in $predeps $postdeps; do\n\t      # can't use Xsed below, because $i might contain '/'\n\t      tmp_deplibs=`$ECHO \" $tmp_deplibs\" | $SED \"s|$i||\"`\n\t    done\n\t  fi\n\t  case $tmp_deplibs in\n\t  *[!\\\t\\ ]*)\n\t    echo\n\t    if test none = \"$deplibs_check_method\"; then\n\t      echo \"*** Warning: inter-library dependencies are not supported in this platform.\"\n\t    else\n\t      echo \"*** Warning: inter-library dependencies are not known to be supported.\"\n\t    fi\n\t    echo \"*** All declared inter-library dependencies are being dropped.\"\n\t    droppeddeps=yes\n\t    ;;\n\t  esac\n\t  ;;\n\tesac\n\tversuffix=$versuffix_save\n\tmajor=$major_save\n\trelease=$release_save\n\tlibname=$libname_save\n\tname=$name_save\n\n\tcase $host in\n\t*-*-rhapsody* | *-*-darwin1.[012])\n\t  # On Rhapsody replace the C library with the System framework\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t  ;;\n\tesac\n\n\tif test yes = \"$droppeddeps\"; then\n\t  if test yes = \"$module\"; then\n\t    echo\n\t    echo \"*** Warning: libtool could not satisfy all declared inter-library\"\n\t    $ECHO \"*** dependencies of module $libname.  Therefore, libtool will create\"\n\t    echo \"*** a static module, that should work as long as the dlopening\"\n\t    echo \"*** application is linked with the -dlopen flag.\"\n\t    if test -z \"$global_symbol_pipe\"; then\n\t      echo\n\t      echo \"*** However, this would only work if libtool was able to extract symbol\"\n\t      echo \"*** lists from a program, using 'nm' or equivalent, but libtool could\"\n\t      echo \"*** not find such a program.  So, this module is probably useless.\"\n\t      echo \"*** 'nm' from GNU binutils and a full rebuild may help.\"\n\t    fi\n\t    if test no = \"$build_old_libs\"; then\n\t      oldlibs=$output_objdir/$libname.$libext\n\t      build_libtool_libs=module\n\t      build_old_libs=yes\n\t    else\n\t      build_libtool_libs=no\n\t    fi\n\t  else\n\t    echo \"*** The inter-library dependencies that have been dropped here will be\"\n\t    echo \"*** automatically added whenever a program is linked with this library\"\n\t    echo \"*** or is declared to -dlopen it.\"\n\n\t    if test no = \"$allow_undefined\"; then\n\t      echo\n\t      echo \"*** Since this library must not contain undefined symbols,\"\n\t      echo \"*** because either the platform does not support them or\"\n\t      echo \"*** it was explicitly requested with -no-undefined,\"\n\t      echo \"*** libtool will only create a static version of it.\"\n\t      if test no = \"$build_old_libs\"; then\n\t\toldlibs=$output_objdir/$libname.$libext\n\t\tbuild_libtool_libs=module\n\t\tbuild_old_libs=yes\n\t      else\n\t\tbuild_libtool_libs=no\n\t      fi\n\t    fi\n\t  fi\n\tfi\n\t# Done checking deplibs!\n\tdeplibs=$newdeplibs\n      fi\n      # Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n      case $host in\n\t*-*-darwin*)\n\t  newdeplibs=`$ECHO \" $newdeplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  new_inherited_linker_flags=`$ECHO \" $new_inherited_linker_flags\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  deplibs=`$ECHO \" $deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t  ;;\n      esac\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      deplibs=$new_libs\n\n      # All the library-specific variables (install_libdir is set above).\n      library_names=\n      old_library=\n      dlname=\n\n      # Test again, we may have decided not to build it any more\n      if test yes = \"$build_libtool_libs\"; then\n\t# Remove $wl instances when linking with ld.\n\t# FIXME: should test the right _cmds variable.\n\tcase $archive_cmds in\n\t  *\\$LD\\ *) wl= ;;\n        esac\n\tif test yes = \"$hardcode_into_libs\"; then\n\t  # Hardcode the library paths\n\t  hardcode_libdirs=\n\t  dep_rpath=\n\t  rpath=$finalize_rpath\n\t  test relink = \"$opt_mode\" || rpath=$compile_rpath$rpath\n\t  for libdir in $rpath; do\n\t    if test -n \"$hardcode_libdir_flag_spec\"; then\n\t      if test -n \"$hardcode_libdir_separator\"; then\n\t\tfunc_replace_sysroot \"$libdir\"\n\t\tlibdir=$func_replace_sysroot_result\n\t\tif test -z \"$hardcode_libdirs\"; then\n\t\t  hardcode_libdirs=$libdir\n\t\telse\n\t\t  # Just accumulate the unique libdirs.\n\t\t  case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t\t  *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t    ;;\n\t\t  *)\n\t\t    func_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t    ;;\n\t\t  esac\n\t\tfi\n\t      else\n\t\teval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t\tfunc_append dep_rpath \" $flag\"\n\t      fi\n\t    elif test -n \"$runpath_var\"; then\n\t      case \"$perm_rpath \" in\n\t      *\" $libdir \"*) ;;\n\t      *) func_append perm_rpath \" $libdir\" ;;\n\t      esac\n\t    fi\n\t  done\n\t  # Substitute the hardcoded libdirs into the rpath.\n\t  if test -n \"$hardcode_libdir_separator\" &&\n\t     test -n \"$hardcode_libdirs\"; then\n\t    libdir=$hardcode_libdirs\n\t    eval \"dep_rpath=\\\"$hardcode_libdir_flag_spec\\\"\"\n\t  fi\n\t  if test -n \"$runpath_var\" && test -n \"$perm_rpath\"; then\n\t    # We should set the runpath_var.\n\t    rpath=\n\t    for dir in $perm_rpath; do\n\t      func_append rpath \"$dir:\"\n\t    done\n\t    eval \"$runpath_var='$rpath\\$$runpath_var'; export $runpath_var\"\n\t  fi\n\t  test -n \"$dep_rpath\" && deplibs=\"$dep_rpath $deplibs\"\n\tfi\n\n\tshlibpath=$finalize_shlibpath\n\ttest relink = \"$opt_mode\" || shlibpath=$compile_shlibpath$shlibpath\n\tif test -n \"$shlibpath\"; then\n\t  eval \"$shlibpath_var='$shlibpath\\$$shlibpath_var'; export $shlibpath_var\"\n\tfi\n\n\t# Get the real and link names of the library.\n\teval shared_ext=\\\"$shrext_cmds\\\"\n\teval library_names=\\\"$library_names_spec\\\"\n\tset dummy $library_names\n\tshift\n\trealname=$1\n\tshift\n\n\tif test -n \"$soname_spec\"; then\n\t  eval soname=\\\"$soname_spec\\\"\n\telse\n\t  soname=$realname\n\tfi\n\tif test -z \"$dlname\"; then\n\t  dlname=$soname\n\tfi\n\n\tlib=$output_objdir/$realname\n\tlinknames=\n\tfor link\n\tdo\n\t  func_append linknames \" $link\"\n\tdone\n\n\t# Use standard objects if they are pic\n\ttest -z \"$pic_flag\" && libobjs=`$ECHO \"$libobjs\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\ttest \"X$libobjs\" = \"X \" && libobjs=\n\n\tdelfiles=\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  $opt_dry_run || cp \"$export_symbols\" \"$output_objdir/$libname.uexp\"\n\t  export_symbols=$output_objdir/$libname.uexp\n\t  func_append delfiles \" $export_symbols\"\n\tfi\n\n\torig_export_symbols=\n\tcase $host_os in\n\tcygwin* | mingw* | cegcc*)\n\t  if test -n \"$export_symbols\" && test -z \"$export_symbols_regex\"; then\n\t    # exporting using user supplied symfile\n\t    func_dll_def_p \"$export_symbols\" || {\n\t      # and it's NOT already a .def file. Must figure out\n\t      # which of the given symbols are data symbols and tag\n\t      # them as such. So, trigger use of export_symbols_cmds.\n\t      # export_symbols gets reassigned inside the \"prepare\n\t      # the list of exported symbols\" if statement, so the\n\t      # include_expsyms logic still works.\n\t      orig_export_symbols=$export_symbols\n\t      export_symbols=\n\t      always_export_symbols=yes\n\t    }\n\t  fi\n\t  ;;\n\tesac\n\n\t# Prepare the list of exported symbols\n\tif test -z \"$export_symbols\"; then\n\t  if test yes = \"$always_export_symbols\" || test -n \"$export_symbols_regex\"; then\n\t    func_verbose \"generating symbol list for '$libname.la'\"\n\t    export_symbols=$output_objdir/$libname.exp\n\t    $opt_dry_run || $RM $export_symbols\n\t    cmds=$export_symbols_cmds\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd1 in $cmds; do\n\t      IFS=$save_ifs\n\t      # Take the normal branch if the nm_file_list_spec branch\n\t      # doesn't work or if tool conversion is not needed.\n\t      case $nm_file_list_spec~$to_tool_file_cmd in\n\t\t*~func_convert_file_noop | *~func_convert_file_msys_to_w32 | ~*)\n\t\t  try_normal_branch=yes\n\t\t  eval cmd=\\\"$cmd1\\\"\n\t\t  func_len \" $cmd\"\n\t\t  len=$func_len_result\n\t\t  ;;\n\t\t*)\n\t\t  try_normal_branch=no\n\t\t  ;;\n\t      esac\n\t      if test yes = \"$try_normal_branch\" \\\n\t\t && { test \"$len\" -lt \"$max_cmd_len\" \\\n\t\t      || test \"$max_cmd_len\" -le -1; }\n\t      then\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\tskipped_export=false\n\t      elif test -n \"$nm_file_list_spec\"; then\n\t\tfunc_basename \"$output\"\n\t\toutput_la=$func_basename_result\n\t\tsave_libobjs=$libobjs\n\t\tsave_output=$output\n\t\toutput=$output_objdir/$output_la.nm\n\t\tfunc_to_tool_file \"$output\"\n\t\tlibobjs=$nm_file_list_spec$func_to_tool_file_result\n\t\tfunc_append delfiles \" $output\"\n\t\tfunc_verbose \"creating $NM input file list: $output\"\n\t\tfor obj in $save_libobjs; do\n\t\t  func_to_tool_file \"$obj\"\n\t\t  $ECHO \"$func_to_tool_file_result\"\n\t\tdone > \"$output\"\n\t\teval cmd=\\\"$cmd1\\\"\n\t\tfunc_show_eval \"$cmd\" 'exit $?'\n\t\toutput=$save_output\n\t\tlibobjs=$save_libobjs\n\t\tskipped_export=false\n\t      else\n\t\t# The command line is too long to execute in one step.\n\t\tfunc_verbose \"using reloadable object file for export list...\"\n\t\tskipped_export=:\n\t\t# Break out early, otherwise skipped_export may be\n\t\t# set to false by a later but shorter cmd.\n\t\tbreak\n\t      fi\n\t    done\n\t    IFS=$save_ifs\n\t    if test -n \"$export_symbols_regex\" && test : != \"$skipped_export\"; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t  tmp_export_symbols=$export_symbols\n\t  test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t  $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\tfi\n\n\tif test : != \"$skipped_export\" && test -n \"$orig_export_symbols\"; then\n\t  # The given exports_symbols file has to be filtered, so filter it.\n\t  func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t  # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t  # 's' commands, which not all seds can handle. GNU sed should be fine\n\t  # though. Also, the filter scales superlinearly with the number of\n\t  # global variables. join(1) would be nice here, but unfortunately\n\t  # isn't a blessed tool.\n\t  $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t  func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t  export_symbols=$output_objdir/$libname.def\n\t  $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\tfi\n\n\ttmp_deplibs=\n\tfor test_deplib in $deplibs; do\n\t  case \" $convenience \" in\n\t  *\" $test_deplib \"*) ;;\n\t  *)\n\t    func_append tmp_deplibs \" $test_deplib\"\n\t    ;;\n\t  esac\n\tdone\n\tdeplibs=$tmp_deplibs\n\n\tif test -n \"$convenience\"; then\n\t  if test -n \"$whole_archive_flag_spec\" &&\n\t    test yes = \"$compiler_needs_object\" &&\n\t    test -z \"$libobjs\"; then\n\t    # extract the archives, so we have objects to list.\n\t    # TODO: could optimize this to just extract one archive.\n\t    whole_archive_flag_spec=\n\t  fi\n\t  if test -n \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  else\n\t    gentop=$output_objdir/${outputname}x\n\t    func_append generated \" $gentop\"\n\n\t    func_extract_archives $gentop $convenience\n\t    func_append libobjs \" $func_extract_archives_result\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\tfi\n\n\tif test yes = \"$thread_safe\" && test -n \"$thread_safe_flag_spec\"; then\n\t  eval flag=\\\"$thread_safe_flag_spec\\\"\n\t  func_append linker_flags \" $flag\"\n\tfi\n\n\t# Make a backup of the uninstalled library when relinking\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}U && $MV $realname ${realname}U)' || exit $?\n\tfi\n\n\t# Do each of the archive commands.\n\tif test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t  if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$module_expsym_cmds\\\"\n\t    cmds=$module_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$module_cmds\\\"\n\t    cmds=$module_cmds\n\t  fi\n\telse\n\t  if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t    eval test_cmds=\\\"$archive_expsym_cmds\\\"\n\t    cmds=$archive_expsym_cmds\n\t  else\n\t    eval test_cmds=\\\"$archive_cmds\\\"\n\t    cmds=$archive_cmds\n\t  fi\n\tfi\n\n\tif test : != \"$skipped_export\" &&\n\t   func_len \" $test_cmds\" &&\n\t   len=$func_len_result &&\n\t   test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  :\n\telse\n\t  # The command line is too long to link in one step, link piecewise\n\t  # or, if using GNU ld and skipped_export is not :, use a linker\n\t  # script.\n\n\t  # Save the value of $output and $libobjs because we want to\n\t  # use them later.  If we have whole_archive_flag_spec, we\n\t  # want to use save_libobjs as it was before\n\t  # whole_archive_flag_spec was expanded, because we can't\n\t  # assume the linker understands whole_archive_flag_spec.\n\t  # This may have to be revisited, in case too many\n\t  # convenience libraries get linked in and end up exceeding\n\t  # the spec.\n\t  if test -z \"$convenience\" || test -z \"$whole_archive_flag_spec\"; then\n\t    save_libobjs=$libobjs\n\t  fi\n\t  save_output=$output\n\t  func_basename \"$output\"\n\t  output_la=$func_basename_result\n\n\t  # Clear the reloadable object creation command queue and\n\t  # initialize k to one.\n\t  test_cmds=\n\t  concat_cmds=\n\t  objlist=\n\t  last_robj=\n\t  k=1\n\n\t  if test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test yes = \"$with_gnu_ld\"; then\n\t    output=$output_objdir/$output_la.lnkscript\n\t    func_verbose \"creating GNU ld script: $output\"\n\t    echo 'INPUT (' > $output\n\t    for obj in $save_libobjs\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    echo ')' >> $output\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$func_to_tool_file_result\n\t  elif test -n \"$save_libobjs\" && test : != \"$skipped_export\" && test -n \"$file_list_spec\"; then\n\t    output=$output_objdir/$output_la.lnk\n\t    func_verbose \"creating linker input file list: $output\"\n\t    : > $output\n\t    set x $save_libobjs\n\t    shift\n\t    firstobj=\n\t    if test yes = \"$compiler_needs_object\"; then\n\t      firstobj=\"$1 \"\n\t      shift\n\t    fi\n\t    for obj\n\t    do\n\t      func_to_tool_file \"$obj\"\n\t      $ECHO \"$func_to_tool_file_result\" >> $output\n\t    done\n\t    func_append delfiles \" $output\"\n\t    func_to_tool_file \"$output\"\n\t    output=$firstobj\\\"$file_list_spec$func_to_tool_file_result\\\"\n\t  else\n\t    if test -n \"$save_libobjs\"; then\n\t      func_verbose \"creating reloadable object files...\"\n\t      output=$output_objdir/$output_la-$k.$objext\n\t      eval test_cmds=\\\"$reload_cmds\\\"\n\t      func_len \" $test_cmds\"\n\t      len0=$func_len_result\n\t      len=$len0\n\n\t      # Loop over the list of objects to be linked.\n\t      for obj in $save_libobjs\n\t      do\n\t\tfunc_len \" $obj\"\n\t\tfunc_arith $len + $func_len_result\n\t\tlen=$func_arith_result\n\t\tif test -z \"$objlist\" ||\n\t\t   test \"$len\" -lt \"$max_cmd_len\"; then\n\t\t  func_append objlist \" $obj\"\n\t\telse\n\t\t  # The command $test_cmds is almost too long, add a\n\t\t  # command to the queue.\n\t\t  if test 1 -eq \"$k\"; then\n\t\t    # The first file doesn't have a previous command to add.\n\t\t    reload_objs=$objlist\n\t\t    eval concat_cmds=\\\"$reload_cmds\\\"\n\t\t  else\n\t\t    # All subsequent reloadable object files will link in\n\t\t    # the last one created.\n\t\t    reload_objs=\"$objlist $last_robj\"\n\t\t    eval concat_cmds=\\\"\\$concat_cmds~$reload_cmds~\\$RM $last_robj\\\"\n\t\t  fi\n\t\t  last_robj=$output_objdir/$output_la-$k.$objext\n\t\t  func_arith $k + 1\n\t\t  k=$func_arith_result\n\t\t  output=$output_objdir/$output_la-$k.$objext\n\t\t  objlist=\" $obj\"\n\t\t  func_len \" $last_robj\"\n\t\t  func_arith $len0 + $func_len_result\n\t\t  len=$func_arith_result\n\t\tfi\n\t      done\n\t      # Handle the remaining objects by creating one last\n\t      # reloadable object file.  All subsequent reloadable object\n\t      # files will link in the last one created.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      reload_objs=\"$objlist $last_robj\"\n\t      eval concat_cmds=\\\"\\$concat_cmds$reload_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t        eval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t      func_append delfiles \" $output\"\n\n\t    else\n\t      output=\n\t    fi\n\n\t    ${skipped_export-false} && {\n\t      func_verbose \"generating symbol list for '$libname.la'\"\n\t      export_symbols=$output_objdir/$libname.exp\n\t      $opt_dry_run || $RM $export_symbols\n\t      libobjs=$output\n\t      # Append the command to create the export file.\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$export_symbols_cmds\\\"\n\t      if test -n \"$last_robj\"; then\n\t\teval concat_cmds=\\\"\\$concat_cmds~\\$RM $last_robj\\\"\n\t      fi\n\t    }\n\n\t    test -n \"$save_libobjs\" &&\n\t      func_verbose \"creating a temporary reloadable object file: $output\"\n\n\t    # Loop through the commands generated above and execute them.\n\t    save_ifs=$IFS; IFS='~'\n\t    for cmd in $concat_cmds; do\n\t      IFS=$save_ifs\n\t      $opt_quiet || {\n\t\t  func_quote_for_expand \"$cmd\"\n\t\t  eval \"func_echo $func_quote_for_expand_result\"\n\t      }\n\t      $opt_dry_run || eval \"$cmd\" || {\n\t\tlt_exit=$?\n\n\t\t# Restore the uninstalled library and exit\n\t\tif test relink = \"$opt_mode\"; then\n\t\t  ( cd \"$output_objdir\" && \\\n\t\t    $RM \"${realname}T\" && \\\n\t\t    $MV \"${realname}U\" \"$realname\" )\n\t\tfi\n\n\t\texit $lt_exit\n\t      }\n\t    done\n\t    IFS=$save_ifs\n\n\t    if test -n \"$export_symbols_regex\" && ${skipped_export-false}; then\n\t      func_show_eval '$EGREP -e \"$export_symbols_regex\" \"$export_symbols\" > \"${export_symbols}T\"'\n\t      func_show_eval '$MV \"${export_symbols}T\" \"$export_symbols\"'\n\t    fi\n\t  fi\n\n          ${skipped_export-false} && {\n\t    if test -n \"$export_symbols\" && test -n \"$include_expsyms\"; then\n\t      tmp_export_symbols=$export_symbols\n\t      test -n \"$orig_export_symbols\" && tmp_export_symbols=$orig_export_symbols\n\t      $opt_dry_run || eval '$ECHO \"$include_expsyms\" | $SP2NL >> \"$tmp_export_symbols\"'\n\t    fi\n\n\t    if test -n \"$orig_export_symbols\"; then\n\t      # The given exports_symbols file has to be filtered, so filter it.\n\t      func_verbose \"filter symbol list for '$libname.la' to tag DATA exports\"\n\t      # FIXME: $output_objdir/$libname.filter potentially contains lots of\n\t      # 's' commands, which not all seds can handle. GNU sed should be fine\n\t      # though. Also, the filter scales superlinearly with the number of\n\t      # global variables. join(1) would be nice here, but unfortunately\n\t      # isn't a blessed tool.\n\t      $opt_dry_run || $SED -e '/[ ,]DATA/!d;s,\\(.*\\)\\([ \\,].*\\),s|^\\1$|\\1\\2|,' < $export_symbols > $output_objdir/$libname.filter\n\t      func_append delfiles \" $export_symbols $output_objdir/$libname.filter\"\n\t      export_symbols=$output_objdir/$libname.def\n\t      $opt_dry_run || $SED -f $output_objdir/$libname.filter < $orig_export_symbols > $export_symbols\n\t    fi\n\t  }\n\n\t  libobjs=$output\n\t  # Restore the value of output.\n\t  output=$save_output\n\n\t  if test -n \"$convenience\" && test -n \"$whole_archive_flag_spec\"; then\n\t    eval libobjs=\\\"\\$libobjs $whole_archive_flag_spec\\\"\n\t    test \"X$libobjs\" = \"X \" && libobjs=\n\t  fi\n\t  # Expand the library linking commands again to reset the\n\t  # value of $libobjs for piecewise linking.\n\n\t  # Do each of the archive commands.\n\t  if test yes = \"$module\" && test -n \"$module_cmds\"; then\n\t    if test -n \"$export_symbols\" && test -n \"$module_expsym_cmds\"; then\n\t      cmds=$module_expsym_cmds\n\t    else\n\t      cmds=$module_cmds\n\t    fi\n\t  else\n\t    if test -n \"$export_symbols\" && test -n \"$archive_expsym_cmds\"; then\n\t      cmds=$archive_expsym_cmds\n\t    else\n\t      cmds=$archive_cmds\n\t    fi\n\t  fi\n\tfi\n\n\tif test -n \"$delfiles\"; then\n\t  # Append the command to remove temporary files to $cmds.\n\t  eval cmds=\\\"\\$cmds~\\$RM $delfiles\\\"\n\tfi\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append libobjs \" $func_extract_archives_result\"\n\t  test \"X$libobjs\" = \"X \" && libobjs=\n\tfi\n\n\tsave_ifs=$IFS; IFS='~'\n\tfor cmd in $cmds; do\n\t  IFS=$sp$nl\n\t  eval cmd=\\\"$cmd\\\"\n\t  IFS=$save_ifs\n\t  $opt_quiet || {\n\t    func_quote_for_expand \"$cmd\"\n\t    eval \"func_echo $func_quote_for_expand_result\"\n\t  }\n\t  $opt_dry_run || eval \"$cmd\" || {\n\t    lt_exit=$?\n\n\t    # Restore the uninstalled library and exit\n\t    if test relink = \"$opt_mode\"; then\n\t      ( cd \"$output_objdir\" && \\\n\t        $RM \"${realname}T\" && \\\n\t\t$MV \"${realname}U\" \"$realname\" )\n\t    fi\n\n\t    exit $lt_exit\n\t  }\n\tdone\n\tIFS=$save_ifs\n\n\t# Restore the uninstalled library and exit\n\tif test relink = \"$opt_mode\"; then\n\t  $opt_dry_run || eval '(cd $output_objdir && $RM ${realname}T && $MV $realname ${realname}T && $MV ${realname}U $realname)' || exit $?\n\n\t  if test -n \"$convenience\"; then\n\t    if test -z \"$whole_archive_flag_spec\"; then\n\t      func_show_eval '${RM}r \"$gentop\"'\n\t    fi\n\t  fi\n\n\t  exit $EXIT_SUCCESS\n\tfi\n\n\t# Create links to the real library.\n\tfor linkname in $linknames; do\n\t  if test \"$realname\" != \"$linkname\"; then\n\t    func_show_eval '(cd \"$output_objdir\" && $RM \"$linkname\" && $LN_S \"$realname\" \"$linkname\")' 'exit $?'\n\t  fi\n\tdone\n\n\t# If -module or -export-dynamic was specified, set the dlname.\n\tif test yes = \"$module\" || test yes = \"$export_dynamic\"; then\n\t  # On all known operating systems, these are identical.\n\t  dlname=$soname\n\tfi\n      fi\n      ;;\n\n    obj)\n      if test -n \"$dlfiles$dlprefiles\" || test no != \"$dlself\"; then\n\tfunc_warning \"'-dlopen' is ignored for objects\"\n      fi\n\n      case \" $deplibs\" in\n      *\\ -l* | *\\ -L*)\n\tfunc_warning \"'-l' and '-L' are ignored for objects\" ;;\n      esac\n\n      test -n \"$rpath\" && \\\n\tfunc_warning \"'-rpath' is ignored for objects\"\n\n      test -n \"$xrpath\" && \\\n\tfunc_warning \"'-R' is ignored for objects\"\n\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for objects\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for objects\"\n\n      case $output in\n      *.lo)\n\ttest -n \"$objs$old_deplibs\" && \\\n\t  func_fatal_error \"cannot build library object '$output' from non-libtool objects\"\n\n\tlibobj=$output\n\tfunc_lo2o \"$libobj\"\n\tobj=$func_lo2o_result\n\t;;\n      *)\n\tlibobj=\n\tobj=$output\n\t;;\n      esac\n\n      # Delete the old objects.\n      $opt_dry_run || $RM $obj $libobj\n\n      # Objects from convenience libraries.  This assumes\n      # single-version convenience libraries.  Whenever we create\n      # different ones for PIC/non-PIC, this we'll have to duplicate\n      # the extraction.\n      reload_conv_objs=\n      gentop=\n      # if reload_cmds runs $LD directly, get rid of -Wl from\n      # whole_archive_flag_spec and hope we can get by with turning comma\n      # into space.\n      case $reload_cmds in\n        *\\$LD[\\ \\$]*) wl= ;;\n      esac\n      if test -n \"$convenience\"; then\n\tif test -n \"$whole_archive_flag_spec\"; then\n\t  eval tmp_whole_archive_flags=\\\"$whole_archive_flag_spec\\\"\n\t  test -n \"$wl\" || tmp_whole_archive_flags=`$ECHO \"$tmp_whole_archive_flags\" | $SED 's|,| |g'`\n\t  reload_conv_objs=$reload_objs\\ $tmp_whole_archive_flags\n\telse\n\t  gentop=$output_objdir/${obj}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $convenience\n\t  reload_conv_objs=\"$reload_objs $func_extract_archives_result\"\n\tfi\n      fi\n\n      # If we're not building shared, we need to use non_pic_objs\n      test yes = \"$build_libtool_libs\" || libobjs=$non_pic_objects\n\n      # Create the old-style object.\n      reload_objs=$objs$old_deplibs' '`$ECHO \"$libobjs\" | $SP2NL | $SED \"/\\.$libext$/d; /\\.lib$/d; $lo2o\" | $NL2SP`' '$reload_conv_objs\n\n      output=$obj\n      func_execute_cmds \"$reload_cmds\" 'exit $?'\n\n      # Exit if we aren't doing a library object file.\n      if test -z \"$libobj\"; then\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      test yes = \"$build_libtool_libs\" || {\n\tif test -n \"$gentop\"; then\n\t  func_show_eval '${RM}r \"$gentop\"'\n\tfi\n\n\t# Create an invalid libtool object if no PIC, so that we don't\n\t# accidentally link it into a program.\n\t# $show \"echo timestamp > $libobj\"\n\t# $opt_dry_run || eval \"echo timestamp > $libobj\" || exit $?\n\texit $EXIT_SUCCESS\n      }\n\n      if test -n \"$pic_flag\" || test default != \"$pic_mode\"; then\n\t# Only do commands if we really have different PIC objects.\n\treload_objs=\"$libobjs $reload_conv_objs\"\n\toutput=$libobj\n\tfunc_execute_cmds \"$reload_cmds\" 'exit $?'\n      fi\n\n      if test -n \"$gentop\"; then\n\tfunc_show_eval '${RM}r \"$gentop\"'\n      fi\n\n      exit $EXIT_SUCCESS\n      ;;\n\n    prog)\n      case $host in\n\t*cygwin*) func_stripname '' '.exe' \"$output\"\n\t          output=$func_stripname_result.exe;;\n      esac\n      test -n \"$vinfo\" && \\\n\tfunc_warning \"'-version-info' is ignored for programs\"\n\n      test -n \"$release\" && \\\n\tfunc_warning \"'-release' is ignored for programs\"\n\n      $preload \\\n\t&& test unknown,unknown,unknown = \"$dlopen_support,$dlopen_self,$dlopen_self_static\" \\\n\t&& func_warning \"'LT_INIT([dlopen])' not used. Assuming no dlopen support.\"\n\n      case $host in\n      *-*-rhapsody* | *-*-darwin1.[012])\n\t# On Rhapsody replace the C library is the System framework\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's/ -lc / System.ltframework /'`\n\t;;\n      esac\n\n      case $host in\n      *-*-darwin*)\n\t# Don't allow lazy linking, it breaks C++ global constructors\n\t# But is supposedly fixed on 10.4 or later (yay!).\n\tif test CXX = \"$tagname\"; then\n\t  case ${MACOSX_DEPLOYMENT_TARGET-10.0} in\n\t    10.[0123])\n\t      func_append compile_command \" $wl-bind_at_load\"\n\t      func_append finalize_command \" $wl-bind_at_load\"\n\t    ;;\n\t  esac\n\tfi\n\t# Time to change all our \"foo.ltframework\" stuff back to \"-framework foo\"\n\tcompile_deplibs=`$ECHO \" $compile_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\tfinalize_deplibs=`$ECHO \" $finalize_deplibs\" | $SED 's% \\([^ $]*\\).ltframework% -framework \\1%g'`\n\t;;\n      esac\n\n\n      # move library search paths that coincide with paths to not yet\n      # installed libraries to the beginning of the library search list\n      new_libs=\n      for path in $notinst_path; do\n\tcase \" $new_libs \" in\n\t*\" -L$path/$objdir \"*) ;;\n\t*)\n\t  case \" $compile_deplibs \" in\n\t  *\" -L$path/$objdir \"*)\n\t    func_append new_libs \" -L$path/$objdir\" ;;\n\t  esac\n\t  ;;\n\tesac\n      done\n      for deplib in $compile_deplibs; do\n\tcase $deplib in\n\t-L*)\n\t  case \" $new_libs \" in\n\t  *\" $deplib \"*) ;;\n\t  *) func_append new_libs \" $deplib\" ;;\n\t  esac\n\t  ;;\n\t*) func_append new_libs \" $deplib\" ;;\n\tesac\n      done\n      compile_deplibs=$new_libs\n\n\n      func_append compile_command \" $compile_deplibs\"\n      func_append finalize_command \" $finalize_deplibs\"\n\n      if test -n \"$rpath$xrpath\"; then\n\t# If the user specified any rpath flags, then add them.\n\tfor libdir in $rpath $xrpath; do\n\t  # This is the magic to use -rpath.\n\t  case \"$finalize_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_rpath \" $libdir\" ;;\n\t  esac\n\tdone\n      fi\n\n      # Now hardcode the library paths\n      rpath=\n      hardcode_libdirs=\n      for libdir in $compile_rpath $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n\tcase $host in\n\t*-*-cygwin* | *-*-mingw* | *-*-pw32* | *-*-os2* | *-cegcc*)\n\t  testbindir=`$ECHO \"$libdir\" | $SED -e 's*/lib$*/bin*'`\n\t  case :$dllsearchpath: in\n\t  *\":$libdir:\"*) ;;\n\t  ::) dllsearchpath=$libdir;;\n\t  *) func_append dllsearchpath \":$libdir\";;\n\t  esac\n\t  case :$dllsearchpath: in\n\t  *\":$testbindir:\"*) ;;\n\t  ::) dllsearchpath=$testbindir;;\n\t  *) func_append dllsearchpath \":$testbindir\";;\n\t  esac\n\t  ;;\n\tesac\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      compile_rpath=$rpath\n\n      rpath=\n      hardcode_libdirs=\n      for libdir in $finalize_rpath; do\n\tif test -n \"$hardcode_libdir_flag_spec\"; then\n\t  if test -n \"$hardcode_libdir_separator\"; then\n\t    if test -z \"$hardcode_libdirs\"; then\n\t      hardcode_libdirs=$libdir\n\t    else\n\t      # Just accumulate the unique libdirs.\n\t      case $hardcode_libdir_separator$hardcode_libdirs$hardcode_libdir_separator in\n\t      *\"$hardcode_libdir_separator$libdir$hardcode_libdir_separator\"*)\n\t\t;;\n\t      *)\n\t\tfunc_append hardcode_libdirs \"$hardcode_libdir_separator$libdir\"\n\t\t;;\n\t      esac\n\t    fi\n\t  else\n\t    eval flag=\\\"$hardcode_libdir_flag_spec\\\"\n\t    func_append rpath \" $flag\"\n\t  fi\n\telif test -n \"$runpath_var\"; then\n\t  case \"$finalize_perm_rpath \" in\n\t  *\" $libdir \"*) ;;\n\t  *) func_append finalize_perm_rpath \" $libdir\" ;;\n\t  esac\n\tfi\n      done\n      # Substitute the hardcoded libdirs into the rpath.\n      if test -n \"$hardcode_libdir_separator\" &&\n\t test -n \"$hardcode_libdirs\"; then\n\tlibdir=$hardcode_libdirs\n\teval rpath=\\\" $hardcode_libdir_flag_spec\\\"\n      fi\n      finalize_rpath=$rpath\n\n      if test -n \"$libobjs\" && test yes = \"$build_old_libs\"; then\n\t# Transform all the library objects into standard objects.\n\tcompile_command=`$ECHO \"$compile_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n\tfinalize_command=`$ECHO \"$finalize_command\" | $SP2NL | $SED \"$lo2o\" | $NL2SP`\n      fi\n\n      func_generate_dlsyms \"$outputname\" \"@PROGRAM@\" false\n\n      # template prelinking step\n      if test -n \"$prelink_cmds\"; then\n\tfunc_execute_cmds \"$prelink_cmds\" 'exit $?'\n      fi\n\n      wrappers_required=:\n      case $host in\n      *cegcc* | *mingw32ce*)\n        # Disable wrappers for cegcc and mingw32ce hosts, we are cross compiling anyway.\n        wrappers_required=false\n        ;;\n      *cygwin* | *mingw* )\n        test yes = \"$build_libtool_libs\" || wrappers_required=false\n        ;;\n      *)\n        if test no = \"$need_relink\" || test yes != \"$build_libtool_libs\"; then\n          wrappers_required=false\n        fi\n        ;;\n      esac\n      $wrappers_required || {\n\t# Replace the output file specification.\n\tcompile_command=`$ECHO \"$compile_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\tlink_command=$compile_command$compile_rpath\n\n\t# We have no uninstalled library dependencies, so finalize right now.\n\texit_status=0\n\tfunc_show_eval \"$link_command\" 'exit_status=$?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\t# Delete the generated files.\n\tif test -f \"$output_objdir/${outputname}S.$objext\"; then\n\t  func_show_eval '$RM \"$output_objdir/${outputname}S.$objext\"'\n\tfi\n\n\texit $exit_status\n      }\n\n      if test -n \"$compile_shlibpath$finalize_shlibpath\"; then\n\tcompile_command=\"$shlibpath_var=\\\"$compile_shlibpath$finalize_shlibpath\\$$shlibpath_var\\\" $compile_command\"\n      fi\n      if test -n \"$finalize_shlibpath\"; then\n\tfinalize_command=\"$shlibpath_var=\\\"$finalize_shlibpath\\$$shlibpath_var\\\" $finalize_command\"\n      fi\n\n      compile_var=\n      finalize_var=\n      if test -n \"$runpath_var\"; then\n\tif test -n \"$perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  compile_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n\tif test -n \"$finalize_perm_rpath\"; then\n\t  # We should set the runpath_var.\n\t  rpath=\n\t  for dir in $finalize_perm_rpath; do\n\t    func_append rpath \"$dir:\"\n\t  done\n\t  finalize_var=\"$runpath_var=\\\"$rpath\\$$runpath_var\\\" \"\n\tfi\n      fi\n\n      if test yes = \"$no_install\"; then\n\t# We don't need to create a wrapper script.\n\tlink_command=$compile_var$compile_command$compile_rpath\n\t# Replace the output file specification.\n\tlink_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output\"'%g'`\n\t# Delete the old output file.\n\t$opt_dry_run || $RM $output\n\t# Link the executable and exit\n\tfunc_show_eval \"$link_command\" 'exit $?'\n\n\tif test -n \"$postlink_cmds\"; then\n\t  func_to_tool_file \"$output\"\n\t  postlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\t  func_execute_cmds \"$postlink_cmds\" 'exit $?'\n\tfi\n\n\texit $EXIT_SUCCESS\n      fi\n\n      case $hardcode_action,$fast_install in\n        relink,*)\n\t  # Fast installation is not supported\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n\n\t  func_warning \"this platform does not like uninstalled shared libraries\"\n\t  func_warning \"'$output' will be relinked during installation\"\n\t  ;;\n        *,yes)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=`$ECHO \"$compile_var$compile_command$compile_rpath\" | $SED 's%@OUTPUT@%\\$progdir/\\$file%g'`\n          ;;\n\t*,no)\n\t  link_command=$compile_var$compile_command$compile_rpath\n\t  relink_command=$finalize_var$finalize_command$finalize_rpath\n          ;;\n\t*,needless)\n\t  link_command=$finalize_var$compile_command$finalize_rpath\n\t  relink_command=\n          ;;\n      esac\n\n      # Replace the output file specification.\n      link_command=`$ECHO \"$link_command\" | $SED 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g'`\n\n      # Delete the old output files.\n      $opt_dry_run || $RM $output $output_objdir/$outputname $output_objdir/lt-$outputname\n\n      func_show_eval \"$link_command\" 'exit $?'\n\n      if test -n \"$postlink_cmds\"; then\n\tfunc_to_tool_file \"$output_objdir/$outputname\"\n\tpostlink_cmds=`func_echo_all \"$postlink_cmds\" | $SED -e 's%@OUTPUT@%'\"$output_objdir/$outputname\"'%g' -e 's%@TOOL_OUTPUT@%'\"$func_to_tool_file_result\"'%g'`\n\tfunc_execute_cmds \"$postlink_cmds\" 'exit $?'\n      fi\n\n      # Now create the wrapper script.\n      func_verbose \"creating $output\"\n\n      # Quote the relink command for shipping.\n      if test -n \"$relink_command\"; then\n\t# Preserve any variables that may affect compiler behavior\n\tfor var in $variables_saved_for_relink; do\n\t  if eval test -z \\\"\\${$var+set}\\\"; then\n\t    relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\t  elif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t    relink_command=\"$var=; export $var; $relink_command\"\n\t  else\n\t    func_quote_for_eval \"$var_value\"\n\t    relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\t  fi\n\tdone\n\trelink_command=\"(cd `pwd`; $relink_command)\"\n\trelink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      fi\n\n      # Only actually do things if not in dry run mode.\n      $opt_dry_run || {\n\t# win32 will think the script is a binary if it has\n\t# a .exe suffix, so we strip it off here.\n\tcase $output in\n\t  *.exe) func_stripname '' '.exe' \"$output\"\n\t         output=$func_stripname_result ;;\n\tesac\n\t# test for cygwin because mv fails w/o .exe extensions\n\tcase $host in\n\t  *cygwin*)\n\t    exeext=.exe\n\t    func_stripname '' '.exe' \"$outputname\"\n\t    outputname=$func_stripname_result ;;\n\t  *) exeext= ;;\n\tesac\n\tcase $host in\n\t  *cygwin* | *mingw* )\n\t    func_dirname_and_basename \"$output\" \"\" \".\"\n\t    output_name=$func_basename_result\n\t    output_path=$func_dirname_result\n\t    cwrappersource=$output_path/$objdir/lt-$output_name.c\n\t    cwrapper=$output_path/$output_name.exe\n\t    $RM $cwrappersource $cwrapper\n\t    trap \"$RM $cwrappersource $cwrapper; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_cwrapperexe_src > $cwrappersource\n\n\t    # The wrapper executable is built using the $host compiler,\n\t    # because it contains $host paths and files. If cross-\n\t    # compiling, it, like the target executable, must be\n\t    # executed on the $host or under an emulation environment.\n\t    $opt_dry_run || {\n\t      $LTCC $LTCFLAGS -o $cwrapper $cwrappersource\n\t      $STRIP $cwrapper\n\t    }\n\n\t    # Now, create the wrapper script for func_source use:\n\t    func_ltwrapper_scriptname $cwrapper\n\t    $RM $func_ltwrapper_scriptname_result\n\t    trap \"$RM $func_ltwrapper_scriptname_result; exit $EXIT_FAILURE\" 1 2 15\n\t    $opt_dry_run || {\n\t      # note: this script will not be executed, so do not chmod.\n\t      if test \"x$build\" = \"x$host\"; then\n\t\t$cwrapper --lt-dump-script > $func_ltwrapper_scriptname_result\n\t      else\n\t\tfunc_emit_wrapper no > $func_ltwrapper_scriptname_result\n\t      fi\n\t    }\n\t  ;;\n\t  * )\n\t    $RM $output\n\t    trap \"$RM $output; exit $EXIT_FAILURE\" 1 2 15\n\n\t    func_emit_wrapper no > $output\n\t    chmod +x $output\n\t  ;;\n\tesac\n      }\n      exit $EXIT_SUCCESS\n      ;;\n    esac\n\n    # See if we need to build an old-fashioned archive.\n    for oldlib in $oldlibs; do\n\n      case $build_libtool_libs in\n        convenience)\n\t  oldobjs=\"$libobjs_save $symfileobj\"\n\t  addlibs=$convenience\n\t  build_libtool_libs=no\n\t  ;;\n\tmodule)\n\t  oldobjs=$libobjs_save\n\t  addlibs=$old_convenience\n\t  build_libtool_libs=no\n          ;;\n\t*)\n\t  oldobjs=\"$old_deplibs $non_pic_objects\"\n\t  $preload && test -f \"$symfileobj\" \\\n\t    && func_append oldobjs \" $symfileobj\"\n\t  addlibs=$old_convenience\n\t  ;;\n      esac\n\n      if test -n \"$addlibs\"; then\n\tgentop=$output_objdir/${outputname}x\n\tfunc_append generated \" $gentop\"\n\n\tfunc_extract_archives $gentop $addlibs\n\tfunc_append oldobjs \" $func_extract_archives_result\"\n      fi\n\n      # Do each command in the archive commands.\n      if test -n \"$old_archive_from_new_cmds\" && test yes = \"$build_libtool_libs\"; then\n\tcmds=$old_archive_from_new_cmds\n      else\n\n\t# Add any objects from preloaded convenience libraries\n\tif test -n \"$dlprefiles\"; then\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\n\t  func_extract_archives $gentop $dlprefiles\n\t  func_append oldobjs \" $func_extract_archives_result\"\n\tfi\n\n\t# POSIX demands no paths to be encoded in archives.  We have\n\t# to avoid creating archives with duplicate basenames if we\n\t# might have to extract them afterwards, e.g., when creating a\n\t# static archive out of a convenience library, or when linking\n\t# the entirety of a libtool archive into another (currently\n\t# not supported by libtool).\n\tif (for obj in $oldobjs\n\t    do\n\t      func_basename \"$obj\"\n\t      $ECHO \"$func_basename_result\"\n\t    done | sort | sort -uc >/dev/null 2>&1); then\n\t  :\n\telse\n\t  echo \"copying selected object files to avoid basename conflicts...\"\n\t  gentop=$output_objdir/${outputname}x\n\t  func_append generated \" $gentop\"\n\t  func_mkdir_p \"$gentop\"\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  counter=1\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_basename \"$obj\"\n\t    objbase=$func_basename_result\n\t    case \" $oldobjs \" in\n\t    \" \") oldobjs=$obj ;;\n\t    *[\\ /]\"$objbase \"*)\n\t      while :; do\n\t\t# Make sure we don't pick an alternate name that also\n\t\t# overlaps.\n\t\tnewobj=lt$counter-$objbase\n\t\tfunc_arith $counter + 1\n\t\tcounter=$func_arith_result\n\t\tcase \" $oldobjs \" in\n\t\t*[\\ /]\"$newobj \"*) ;;\n\t\t*) if test ! -f \"$gentop/$newobj\"; then break; fi ;;\n\t\tesac\n\t      done\n\t      func_show_eval \"ln $obj $gentop/$newobj || cp $obj $gentop/$newobj\"\n\t      func_append oldobjs \" $gentop/$newobj\"\n\t      ;;\n\t    *) func_append oldobjs \" $obj\" ;;\n\t    esac\n\t  done\n\tfi\n\tfunc_to_tool_file \"$oldlib\" func_convert_file_msys_to_w32\n\ttool_oldlib=$func_to_tool_file_result\n\teval cmds=\\\"$old_archive_cmds\\\"\n\n\tfunc_len \" $cmds\"\n\tlen=$func_len_result\n\tif test \"$len\" -lt \"$max_cmd_len\" || test \"$max_cmd_len\" -le -1; then\n\t  cmds=$old_archive_cmds\n\telif test -n \"$archiver_list_spec\"; then\n\t  func_verbose \"using command file archive linking...\"\n\t  for obj in $oldobjs\n\t  do\n\t    func_to_tool_file \"$obj\"\n\t    $ECHO \"$func_to_tool_file_result\"\n\t  done > $output_objdir/$libname.libcmd\n\t  func_to_tool_file \"$output_objdir/$libname.libcmd\"\n\t  oldobjs=\" $archiver_list_spec$func_to_tool_file_result\"\n\t  cmds=$old_archive_cmds\n\telse\n\t  # the command line is too long to link in one step, link in parts\n\t  func_verbose \"using piecewise archive linking...\"\n\t  save_RANLIB=$RANLIB\n\t  RANLIB=:\n\t  objlist=\n\t  concat_cmds=\n\t  save_oldobjs=$oldobjs\n\t  oldobjs=\n\t  # Is there a better way of finding the last object in the list?\n\t  for obj in $save_oldobjs\n\t  do\n\t    last_oldobj=$obj\n\t  done\n\t  eval test_cmds=\\\"$old_archive_cmds\\\"\n\t  func_len \" $test_cmds\"\n\t  len0=$func_len_result\n\t  len=$len0\n\t  for obj in $save_oldobjs\n\t  do\n\t    func_len \" $obj\"\n\t    func_arith $len + $func_len_result\n\t    len=$func_arith_result\n\t    func_append objlist \" $obj\"\n\t    if test \"$len\" -lt \"$max_cmd_len\"; then\n\t      :\n\t    else\n\t      # the above command should be used before it gets too long\n\t      oldobjs=$objlist\n\t      if test \"$obj\" = \"$last_oldobj\"; then\n\t\tRANLIB=$save_RANLIB\n\t      fi\n\t      test -z \"$concat_cmds\" || concat_cmds=$concat_cmds~\n\t      eval concat_cmds=\\\"\\$concat_cmds$old_archive_cmds\\\"\n\t      objlist=\n\t      len=$len0\n\t    fi\n\t  done\n\t  RANLIB=$save_RANLIB\n\t  oldobjs=$objlist\n\t  if test -z \"$oldobjs\"; then\n\t    eval cmds=\\\"\\$concat_cmds\\\"\n\t  else\n\t    eval cmds=\\\"\\$concat_cmds~\\$old_archive_cmds\\\"\n\t  fi\n\tfi\n      fi\n      func_execute_cmds \"$cmds\" 'exit $?'\n    done\n\n    test -n \"$generated\" && \\\n      func_show_eval \"${RM}r$generated\"\n\n    # Now create the libtool archive.\n    case $output in\n    *.la)\n      old_library=\n      test yes = \"$build_old_libs\" && old_library=$libname.$libext\n      func_verbose \"creating $output\"\n\n      # Preserve any variables that may affect compiler behavior\n      for var in $variables_saved_for_relink; do\n\tif eval test -z \\\"\\${$var+set}\\\"; then\n\t  relink_command=\"{ test -z \\\"\\${$var+set}\\\" || $lt_unset $var || { $var=; export $var; }; }; $relink_command\"\n\telif eval var_value=\\$$var; test -z \"$var_value\"; then\n\t  relink_command=\"$var=; export $var; $relink_command\"\n\telse\n\t  func_quote_for_eval \"$var_value\"\n\t  relink_command=\"$var=$func_quote_for_eval_result; export $var; $relink_command\"\n\tfi\n      done\n      # Quote the link command for shipping.\n      relink_command=\"(cd `pwd`; $SHELL \\\"$progpath\\\" $preserve_args --mode=relink $libtool_args @inst_prefix_dir@)\"\n      relink_command=`$ECHO \"$relink_command\" | $SED \"$sed_quote_subst\"`\n      if test yes = \"$hardcode_automatic\"; then\n\trelink_command=\n      fi\n\n      # Only create the output if not a dry run.\n      $opt_dry_run || {\n\tfor installed in no yes; do\n\t  if test yes = \"$installed\"; then\n\t    if test -z \"$install_libdir\"; then\n\t      break\n\t    fi\n\t    output=$output_objdir/${outputname}i\n\t    # Replace all uninstalled libtool libraries with the installed ones\n\t    newdependency_libs=\n\t    for deplib in $dependency_libs; do\n\t      case $deplib in\n\t      *.la)\n\t\tfunc_basename \"$deplib\"\n\t\tname=$func_basename_result\n\t\tfunc_resolve_sysroot \"$deplib\"\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $func_resolve_sysroot_result`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$deplib' is not a valid libtool archive\"\n\t\tfunc_append newdependency_libs \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      -L*)\n\t\tfunc_stripname -L '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -L$func_replace_sysroot_result\"\n\t\t;;\n\t      -R*)\n\t\tfunc_stripname -R '' \"$deplib\"\n\t\tfunc_replace_sysroot \"$func_stripname_result\"\n\t\tfunc_append newdependency_libs \" -R$func_replace_sysroot_result\"\n\t\t;;\n\t      *) func_append newdependency_libs \" $deplib\" ;;\n\t      esac\n\t    done\n\t    dependency_libs=$newdependency_libs\n\t    newdlfiles=\n\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t      *.la)\n\t        func_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlfiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      *) func_append newdlfiles \" $lib\" ;;\n\t      esac\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t      *.la)\n\t\t# Only pass preopened files to the pseudo-archive (for\n\t\t# eventual linking with the app. that links it) if we\n\t\t# didn't already link the preopened objects directly into\n\t\t# the library:\n\t\tfunc_basename \"$lib\"\n\t\tname=$func_basename_result\n\t\teval libdir=`$SED -n -e 's/^libdir=\\(.*\\)$/\\1/p' $lib`\n\t\ttest -z \"$libdir\" && \\\n\t\t  func_fatal_error \"'$lib' is not a valid libtool archive\"\n\t\tfunc_append newdlprefiles \" ${lt_sysroot:+=}$libdir/$name\"\n\t\t;;\n\t      esac\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  else\n\t    newdlfiles=\n\t    for lib in $dlfiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlfiles \" $abs\"\n\t    done\n\t    dlfiles=$newdlfiles\n\t    newdlprefiles=\n\t    for lib in $dlprefiles; do\n\t      case $lib in\n\t\t[\\\\/]* | [A-Za-z]:[\\\\/]*) abs=$lib ;;\n\t\t*) abs=`pwd`\"/$lib\" ;;\n\t      esac\n\t      func_append newdlprefiles \" $abs\"\n\t    done\n\t    dlprefiles=$newdlprefiles\n\t  fi\n\t  $RM $output\n\t  # place dlname in correct position for cygwin\n\t  # In fact, it would be nice if we could use this code for all target\n\t  # systems that can't hard-code library paths into their executables\n\t  # and that have no shared library path variable independent of PATH,\n\t  # but it turns out we can't easily determine that from inspecting\n\t  # libtool variables, so we have to hard-code the OSs to which it\n\t  # applies here; at the moment, that means platforms that use the PE\n\t  # object format with DLL files.  See the long comment at the top of\n\t  # tests/bindir.at for full details.\n\t  tdlname=$dlname\n\t  case $host,$output,$installed,$module,$dlname in\n\t    *cygwin*,*lai,yes,no,*.dll | *mingw*,*lai,yes,no,*.dll | *cegcc*,*lai,yes,no,*.dll)\n\t      # If a -bindir argument was supplied, place the dll there.\n\t      if test -n \"$bindir\"; then\n\t\tfunc_relative_path \"$install_libdir\" \"$bindir\"\n\t\ttdlname=$func_relative_path_result/$dlname\n\t      else\n\t\t# Otherwise fall back on heuristic.\n\t\ttdlname=../bin/$dlname\n\t      fi\n\t      ;;\n\t  esac\n\t  $ECHO > $output \"\\\n# $outputname - a libtool library file\n# Generated by $PROGRAM (GNU $PACKAGE) $VERSION\n#\n# Please DO NOT delete this file!\n# It is necessary for linking the library.\n\n# The name that we can dlopen(3).\ndlname='$tdlname'\n\n# Names of this library.\nlibrary_names='$library_names'\n\n# The name of the static archive.\nold_library='$old_library'\n\n# Linker flags that cannot go in dependency_libs.\ninherited_linker_flags='$new_inherited_linker_flags'\n\n# Libraries that this one depends upon.\ndependency_libs='$dependency_libs'\n\n# Names of additional weak libraries provided by this library\nweak_library_names='$weak_libs'\n\n# Version information for $libname.\ncurrent=$current\nage=$age\nrevision=$revision\n\n# Is this an already installed library?\ninstalled=$installed\n\n# Should we warn about portability when linking against -modules?\nshouldnotlink=$module\n\n# Files to dlopen/dlpreopen\ndlopen='$dlfiles'\ndlpreopen='$dlprefiles'\n\n# Directory that this library needs to be installed in:\nlibdir='$install_libdir'\"\n\t  if test no,yes = \"$installed,$need_relink\"; then\n\t    $ECHO >> $output \"\\\nrelink_command=\\\"$relink_command\\\"\"\n\t  fi\n\tdone\n      }\n\n      # Do a symbolic link so that the libtool archive can be found in\n      # LD_LIBRARY_PATH before the program is installed.\n      func_show_eval '( cd \"$output_objdir\" && $RM \"$outputname\" && $LN_S \"../$outputname\" \"$outputname\" )' 'exit $?'\n      ;;\n    esac\n    exit $EXIT_SUCCESS\n}\n\nif test link = \"$opt_mode\" || test relink = \"$opt_mode\"; then\n  func_mode_link ${1+\"$@\"}\nfi\n\n\n# func_mode_uninstall arg...\nfunc_mode_uninstall ()\n{\n    $debug_cmd\n\n    RM=$nonopt\n    files=\n    rmforce=false\n    exit_status=0\n\n    # This variable tells wrapper scripts just to set variables rather\n    # than running their programs.\n    libtool_install_magic=$magic\n\n    for arg\n    do\n      case $arg in\n      -f) func_append RM \" $arg\"; rmforce=: ;;\n      -*) func_append RM \" $arg\" ;;\n      *) func_append files \" $arg\" ;;\n      esac\n    done\n\n    test -z \"$RM\" && \\\n      func_fatal_help \"you must specify an RM program\"\n\n    rmdirs=\n\n    for file in $files; do\n      func_dirname \"$file\" \"\" \".\"\n      dir=$func_dirname_result\n      if test . = \"$dir\"; then\n\todir=$objdir\n      else\n\todir=$dir/$objdir\n      fi\n      func_basename \"$file\"\n      name=$func_basename_result\n      test uninstall = \"$opt_mode\" && odir=$dir\n\n      # Remember odir for removal later, being careful to avoid duplicates\n      if test clean = \"$opt_mode\"; then\n\tcase \" $rmdirs \" in\n\t  *\" $odir \"*) ;;\n\t  *) func_append rmdirs \" $odir\" ;;\n\tesac\n      fi\n\n      # Don't error if the file doesn't exist and rm -f was used.\n      if { test -L \"$file\"; } >/dev/null 2>&1 ||\n\t { test -h \"$file\"; } >/dev/null 2>&1 ||\n\t test -f \"$file\"; then\n\t:\n      elif test -d \"$file\"; then\n\texit_status=1\n\tcontinue\n      elif $rmforce; then\n\tcontinue\n      fi\n\n      rmfiles=$file\n\n      case $name in\n      *.la)\n\t# Possibly a libtool archive, so verify it.\n\tif func_lalib_p \"$file\"; then\n\t  func_source $dir/$name\n\n\t  # Delete the libtool libraries and symlinks.\n\t  for n in $library_names; do\n\t    func_append rmfiles \" $odir/$n\"\n\t  done\n\t  test -n \"$old_library\" && func_append rmfiles \" $odir/$old_library\"\n\n\t  case $opt_mode in\n\t  clean)\n\t    case \" $library_names \" in\n\t    *\" $dlname \"*) ;;\n\t    *) test -n \"$dlname\" && func_append rmfiles \" $odir/$dlname\" ;;\n\t    esac\n\t    test -n \"$libdir\" && func_append rmfiles \" $odir/$name $odir/${name}i\"\n\t    ;;\n\t  uninstall)\n\t    if test -n \"$library_names\"; then\n\t      # Do each command in the postuninstall commands.\n\t      func_execute_cmds \"$postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\n\t    if test -n \"$old_library\"; then\n\t      # Do each command in the old_postuninstall commands.\n\t      func_execute_cmds \"$old_postuninstall_cmds\" '$rmforce || exit_status=1'\n\t    fi\n\t    # FIXME: should reinstall the best remaining shared library.\n\t    ;;\n\t  esac\n\tfi\n\t;;\n\n      *.lo)\n\t# Possibly a libtool object, so verify it.\n\tif func_lalib_p \"$file\"; then\n\n\t  # Read the .lo file\n\t  func_source $dir/$name\n\n\t  # Add PIC object to the list of files to remove.\n\t  if test -n \"$pic_object\" && test none != \"$pic_object\"; then\n\t    func_append rmfiles \" $dir/$pic_object\"\n\t  fi\n\n\t  # Add non-PIC object to the list of files to remove.\n\t  if test -n \"$non_pic_object\" && test none != \"$non_pic_object\"; then\n\t    func_append rmfiles \" $dir/$non_pic_object\"\n\t  fi\n\tfi\n\t;;\n\n      *)\n\tif test clean = \"$opt_mode\"; then\n\t  noexename=$name\n\t  case $file in\n\t  *.exe)\n\t    func_stripname '' '.exe' \"$file\"\n\t    file=$func_stripname_result\n\t    func_stripname '' '.exe' \"$name\"\n\t    noexename=$func_stripname_result\n\t    # $file with .exe has already been added to rmfiles,\n\t    # add $file without .exe\n\t    func_append rmfiles \" $file\"\n\t    ;;\n\t  esac\n\t  # Do a test to see if this is a libtool program.\n\t  if func_ltwrapper_p \"$file\"; then\n\t    if func_ltwrapper_executable_p \"$file\"; then\n\t      func_ltwrapper_scriptname \"$file\"\n\t      relink_command=\n\t      func_source $func_ltwrapper_scriptname_result\n\t      func_append rmfiles \" $func_ltwrapper_scriptname_result\"\n\t    else\n\t      relink_command=\n\t      func_source $dir/$noexename\n\t    fi\n\n\t    # note $name still contains .exe if it was in $file originally\n\t    # as does the version of $file that was added into $rmfiles\n\t    func_append rmfiles \" $odir/$name $odir/${name}S.$objext\"\n\t    if test yes = \"$fast_install\" && test -n \"$relink_command\"; then\n\t      func_append rmfiles \" $odir/lt-$name\"\n\t    fi\n\t    if test \"X$noexename\" != \"X$name\"; then\n\t      func_append rmfiles \" $odir/lt-$noexename.c\"\n\t    fi\n\t  fi\n\tfi\n\t;;\n      esac\n      func_show_eval \"$RM $rmfiles\" 'exit_status=1'\n    done\n\n    # Try to remove the $objdir's in the directories where we deleted files\n    for dir in $rmdirs; do\n      if test -d \"$dir\"; then\n\tfunc_show_eval \"rmdir $dir >/dev/null 2>&1\"\n      fi\n    done\n\n    exit $exit_status\n}\n\nif test uninstall = \"$opt_mode\" || test clean = \"$opt_mode\"; then\n  func_mode_uninstall ${1+\"$@\"}\nfi\n\ntest -z \"$opt_mode\" && {\n  help=$generic_help\n  func_fatal_help \"you must specify a MODE\"\n}\n\ntest -z \"$exec_cmd\" && \\\n  func_fatal_help \"invalid operation mode '$opt_mode'\"\n\nif test -n \"$exec_cmd\"; then\n  eval exec \"$exec_cmd\"\n  exit $EXIT_FAILURE\nfi\n\nexit $exit_status\n\n\n# The TAGs below are defined such that we never get into a situation\n# where we disable both kinds of libraries.  Given conflicting\n# choices, we go for a static library, that is the most portable,\n# since we can't tell whether shared libraries were disabled because\n# the user asked for that or because the platform doesn't support\n# them.  This is particularly important on AIX, because we don't\n# support having both static and shared libraries enabled at the same\n# time on that platform, so we default to a shared-only configuration.\n# If a disable-shared tag is given, we'll fallback to a static-only\n# configuration.  But we'll never go from static-only to shared-only.\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-shared\nbuild_libtool_libs=no\nbuild_old_libs=yes\n# ### END LIBTOOL TAG CONFIG: disable-shared\n\n# ### BEGIN LIBTOOL TAG CONFIG: disable-static\nbuild_old_libs=`case $build_libtool_libs in yes) echo no;; *) echo yes;; esac`\n# ### END LIBTOOL TAG CONFIG: disable-static\n\n# Local Variables:\n# mode:shell-script\n# sh-indentation:2\n# End:\n", "num_lines": 11157}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# usage: <progname> <platform>\n# eg: <progname> Linux_i686\n\n#platform=$1\nplatform=`uname -ms | sed -e s\"/ /_/g\"`\n\n#build debug library:\n\nmake -f sqlite3x.mak debug=yes\n\n#build release library:\nmake -f sqlite3x.mak debug=no\n", "num_lines": 15}
{"repo_name": "AzMigrate-Hydration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#       ZLIB compilation script for the OS/400.\n#\n#\n#       This is a shell script since make is not a standard component of OS/400.\n\n\n################################################################################\n#\n#                       Tunable configuration parameters.\n#\n################################################################################\n\nTARGETLIB='ZLIB'                # Target OS/400 program library\nSTATBNDDIR='ZLIB_A'             # Static binding directory.\nDYNBNDDIR='ZLIB'                # Dynamic binding directory.\nSRVPGM=\"ZLIB\"                   # Service program.\nIFSDIR='/zlib'                  # IFS support base directory.\nTGTCCSID='500'                  # Target CCSID of objects\nDEBUG='*NONE'                   # Debug level\nOPTIMIZE='40'                   # Optimisation level\nOUTPUT='*NONE'                  # Compilation output option.\nTGTRLS='V6R1M0'                 # Target OS release\n\nexport TARGETLIB STATBNDDIR DYNBNDDIR SRVPGM IFSDIR\nexport TGTCCSID DEBUG OPTIMIZE OUTPUT TGTRLS\n\n\n################################################################################\n#\n#                       OS/400 specific definitions.\n#\n################################################################################\n\nLIBIFSNAME=\"/QSYS.LIB/${TARGETLIB}.LIB\"\n\n\n################################################################################\n#\n#                               Procedures.\n#\n################################################################################\n\n#       action_needed dest [src]\n#\n#       dest is an object to build\n#       if specified, src is an object on which dest depends.\n#\n#       exit 0 (succeeds) if some action has to be taken, else 1.\n\naction_needed()\n\n{\n        [ ! -e \"${1}\" ] && return 0\n        [ \"${2}\" ] || return 1\n        [ \"${1}\" -ot \"${2}\" ] && return 0\n        return 1\n}\n\n\n#       make_module module_name source_name [additional_definitions]\n#\n#       Compile source name into module if needed.\n#       As side effect, append the module name to variable MODULES.\n#       Set LINK to \"YES\" if the module has been compiled.\n\nmake_module()\n\n{\n    MODULES=\"${MODULES} ${1}\"\n    MODIFSNAME=\"${LIBIFSNAME}/${1}.MODULE\"\n    CSRC=\"`basename \\\"${2}\\\"`\"\n\n    if action_needed \"${MODIFSNAME}\" \"${2}\"\n    then    :\n    elif [ ! \"`sed -e \\\"/<source name=\\\\\\\"${CSRC}\\\\\\\">/,/<\\\\\\\\/source>/!d\\\" \\\n      -e '/<depend /!d'                                                 \\\n      -e 's/.* name=\\\"\\\\([^\\\"]*\\\\)\\\".*/\\\\1/' < \\\"${TOPDIR}/treebuild.xml\\\" |\n        while read HDR\n        do      if action_needed \\\"${MODIFSNAME}\\\" \\\"${IFSDIR}/include/${HDR}\\\"\n                then    echo recompile\n                        break\n                fi\n        done`\" ]\n    then    return 0\n    fi\n\n    CMD=\"CRTCMOD MODULE(${TARGETLIB}/${1}) SRCSTMF('${2}')\"\n    CMD=\"${CMD} SYSIFCOPT(*IFS64IO) OPTION(*INCDIRFIRST)\"\n    CMD=\"${CMD} LOCALETYPE(*LOCALE) FLAG(10)\"\n    CMD=\"${CMD} INCDIR('${IFSDIR}/include' ${INCLUDES})\"\n    CMD=\"${CMD} TGTCCSID(${TGTCCSID}) TGTRLS(${TGTRLS})\"\n    CMD=\"${CMD} OUTPUT(${OUTPUT})\"\n    CMD=\"${CMD} OPTIMIZE(${OPTIMIZE})\"\n    CMD=\"${CMD} DBGVIEW(${DEBUG})\"\n    system \"${CMD}\"\n    LINK=YES\n}\n\n\n#       Determine DB2 object name from IFS name.\n\ndb2_name()\n\n{\n        basename \"${1}\"                                                 |\n        tr 'a-z-' 'A-Z_'                                                |\n        sed -e 's/\\..*//'                                               \\\n            -e 's/^\\(.\\).*\\(.........\\)$/\\1\\2/'\n}\n\n\n#       Force enumeration types to be the same size as integers.\n\ncopy_hfile()\n\n{\n        sed -e '1i\\\n#pragma enum(int)\\\n' \"${@}\" -e '$a\\\n#pragma enum(pop)\\\n'\n}\n\n\n################################################################################\n#\n#                             Script initialization.\n#\n################################################################################\n\nSCRIPTDIR=`dirname \"${0}\"`\n\ncase \"${SCRIPTDIR}\" in\n/*)     ;;\n*)      SCRIPTDIR=\"`pwd`/${SCRIPTDIR}\"\nesac\n\nwhile true\ndo      case \"${SCRIPTDIR}\" in\n        */.)    SCRIPTDIR=\"${SCRIPTDIR%/.}\";;\n        *)      break;;\n        esac\ndone\n\n#  The script directory is supposed to be in ${TOPDIR}/os400.\n\nTOPDIR=`dirname \"${SCRIPTDIR}\"`\nexport SCRIPTDIR TOPDIR\ncd \"${TOPDIR}\"\n\n\n#  Extract the version from the master compilation XML file.\n\nVERSION=`sed -e '/^<package /!d'                                        \\\n            -e 's/^.* version=\"\\([0-9.]*\\)\".*$/\\1/' -e 'q'              \\\n            < treebuild.xml`\nexport VERSION\n\n################################################################################\n\n\n#       Create the OS/400 library if it does not exist.\n\nif action_needed \"${LIBIFSNAME}\"\nthen    CMD=\"CRTLIB LIB(${TARGETLIB}) TEXT('ZLIB: Data compression API')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the DOCS source file if it does not exist.\n\nif action_needed \"${LIBIFSNAME}/DOCS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/DOCS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('Documentation texts')\"\n        system \"${CMD}\"\nfi\n\n#       Copy some documentation files if needed.\n\nfor TEXT in \"${TOPDIR}/ChangeLog\" \"${TOPDIR}/FAQ\"                       \\\n    \"${TOPDIR}/README\" \"${SCRIPTDIR}/README400\"\ndo      MEMBER=\"${LIBIFSNAME}/DOCS.FILE/`db2_name \\\"${TEXT}\\\"`.MBR\"\n\n        if action_needed \"${MEMBER}\" \"${TEXT}\"\n        then    CMD=\"CPY OBJ('${TEXT}') TOOBJ('${MEMBER}') TOCCSID(${TGTCCSID})\"\n                CMD=\"${CMD} DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n        fi\ndone\n\n\n#       Create the OS/400 source program file for the C header files.\n\nSRCPF=\"${LIBIFSNAME}/H.FILE\"\n\nif action_needed \"${SRCPF}\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/H) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: C/C++ header files')\"\n        system \"${CMD}\"\nfi\n\n\n#       Create the IFS directory for the C header files.\n\nif action_needed \"${IFSDIR}/include\"\nthen    mkdir -p \"${IFSDIR}/include\"\nfi\n\n#       Copy the header files to DB2 library. Link from IFS include directory.\n\nfor HFILE in \"${TOPDIR}/\"*.h\ndo      DEST=\"${SRCPF}/`db2_name \\\"${HFILE}\\\"`.MBR\"\n\n        if action_needed \"${DEST}\" \"${HFILE}\"\n        then    copy_hfile < \"${HFILE}\" > tmphdrfile\n\n                #       Need to translate to target CCSID.\n\n                CMD=\"CPY OBJ('`pwd`/tmphdrfile') TOOBJ('${DEST}')\"\n                CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n                system \"${CMD}\"\n                # touch -r \"${HFILE}\" \"${DEST}\"\n                rm -f tmphdrfile\n        fi\n\n        IFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\n        if action_needed \"${IFSFILE}\" \"${DEST}\"\n        then    rm -f \"${IFSFILE}\"\n                ln -s \"${DEST}\" \"${IFSFILE}\"\n        fi\ndone\n\n\n#       Install the ILE/RPG header file.\n\n\nHFILE=\"${SCRIPTDIR}/zlib.inc\"\nDEST=\"${SRCPF}/ZLIB.INC.MBR\"\n\nif action_needed \"${DEST}\" \"${HFILE}\"\nthen    CMD=\"CPY OBJ('${HFILE}') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${HFILE}\" \"${DEST}\"\nfi\n\nIFSFILE=\"${IFSDIR}/include/`basename \\\"${HFILE}\\\"`\"\n\nif action_needed \"${IFSFILE}\" \"${DEST}\"\nthen    rm -f \"${IFSFILE}\"\n        ln -s \"${DEST}\" \"${IFSFILE}\"\nfi\n\n\n#      Create and compile the identification source file.\n\necho '#pragma comment(user, \"ZLIB version '\"${VERSION}\"'\")' > os400.c\necho '#pragma comment(user, __DATE__)' >> os400.c\necho '#pragma comment(user, __TIME__)' >> os400.c\necho '#pragma comment(copyright, \"Copyright (C) 1995-2017 Jean-Loup Gailly, Mark Adler. OS/400 version by P. Monnerat.\")' >> os400.c\nmake_module     OS400           os400.c\nLINK=                           # No need to rebuild service program yet.\nMODULES=\n\n\n#       Get source list.\n\nCSOURCES=`sed -e '/<source name=\"/!d'                                   \\\n    -e 's/.* name=\"\\([^\"]*\\)\".*/\\1/' < treebuild.xml`\n\n#       Compile the sources into modules.\n\nfor SRC in ${CSOURCES}\ndo      MODULE=`db2_name \"${SRC}\"`\n        make_module \"${MODULE}\" \"${SRC}\"\ndone\n\n\n#       If needed, (re)create the static binding directory.\n\nif action_needed \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${STATBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB static binding directory')\"\n        system \"${CMD}\"\n\n        for MODULE in ${MODULES}\n        do      CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n                CMD=\"${CMD} OBJ((${TARGETLIB}/${MODULE} *MODULE))\"\n                system \"${CMD}\"\n        done\nfi\n\n\n#       The exportation file for service program creation must be in a DB2\n#               source file, so make sure it exists.\n\nif action_needed \"${LIBIFSNAME}/TOOLS.FILE\"\nthen    CMD=\"CRTSRCPF FILE(${TARGETLIB}/TOOLS) RCDLEN(112)\"\n        CMD=\"${CMD} CCSID(${TGTCCSID}) TEXT('ZLIB: build tools')\"\n        system \"${CMD}\"\nfi\n\n\nDEST=\"${LIBIFSNAME}/TOOLS.FILE/BNDSRC.MBR\"\n\nif action_needed \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\nthen    CMD=\"CPY OBJ('${SCRIPTDIR}/bndsrc') TOOBJ('${DEST}')\"\n        CMD=\"${CMD} TOCCSID(${TGTCCSID}) DTAFMT(*TEXT) REPLACE(*YES)\"\n        system \"${CMD}\"\n        # touch -r \"${SCRIPTDIR}/bndsrc\" \"${DEST}\"\n        LINK=YES\nfi\n\n\n#       Build the service program if needed.\n\nif action_needed \"${LIBIFSNAME}/${SRVPGM}.SRVPGM\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    CMD=\"CRTSRVPGM SRVPGM(${TARGETLIB}/${SRVPGM})\"\n        CMD=\"${CMD} SRCFILE(${TARGETLIB}/TOOLS) SRCMBR(BNDSRC)\"\n        CMD=\"${CMD} MODULE(${TARGETLIB}/OS400)\"\n        CMD=\"${CMD} BNDDIR(${TARGETLIB}/${STATBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB ${VERSION} dynamic library')\"\n        CMD=\"${CMD} TGTRLS(${TGTRLS})\"\n        system \"${CMD}\"\n        LINK=YES\n\n        #       Duplicate the service program for a versioned backup.\n\n        BACKUP=`echo \"${SRVPGM}${VERSION}\"                              |\n                sed -e 's/.*\\(..........\\)$/\\1/' -e 's/\\./_/g'`\n        BACKUP=\"`db2_name \\\"${BACKUP}\\\"`\"\n        BKUPIFSNAME=\"${LIBIFSNAME}/${BACKUP}.SRVPGM\"\n        rm -f \"${BKUPIFSNAME}\"\n        CMD=\"CRTDUPOBJ OBJ(${SRVPGM}) FROMLIB(${TARGETLIB})\"\n        CMD=\"${CMD} OBJTYPE(*SRVPGM) NEWOBJ(${BACKUP})\"\n        system \"${CMD}\"\nfi\n\n\n#       If needed, (re)create the dynamic binding directory.\n\nif action_needed \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\nthen    LINK=YES\nfi\n\nif [ \"${LINK}\" ]\nthen    rm -rf \"${LIBIFSNAME}/${DYNBNDDIR}.BNDDIR\"\n        CMD=\"CRTBNDDIR BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} TEXT('ZLIB dynamic binding directory')\"\n        system \"${CMD}\"\n        CMD=\"ADDBNDDIRE BNDDIR(${TARGETLIB}/${DYNBNDDIR})\"\n        CMD=\"${CMD} OBJ((*LIBL/${SRVPGM} *SRVPGM))\"\n        system \"${CMD}\"\nfi\n", "num_lines": 367}
{"repo_name": "AZNFS-mount", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n# Exit on error.\nset -e\n\ngenerate_rpm_package()\n{\n\trpm_dir=$1\n\n\t# Overwrite rpm_pkg_dir in case of SUSE.\n\tif [ \"$rpm_dir\" == \"suse\" ]; then\n\t\trpm_pkg_dir=\"${pkg_name}_sles-${RELEASE_NUMBER}-1.x86_64\"\n\tfi\n\n\t# Create the directory to hold the package spec and data files for RPM package.\n\tmkdir -p ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}\n\n\t# Copy static package file(s).\n\tmkdir -p ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}/usr/sbin\n\tcp -avf ${SOURCE_DIR}/src/aznfswatchdog ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}/usr/sbin/\n\n\t# Compile mount.aznfs.c and put the executable into ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}/sbin.\n\tmkdir -p ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}/sbin\n\tgcc -static ${SOURCE_DIR}/src/mount.aznfs.c -o ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}/sbin/mount.aznfs\n\n\tmkdir -p ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}${opt_dir}\n\tcp -avf ${SOURCE_DIR}/lib/common.sh ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}${opt_dir}/\n\tcp -avf ${SOURCE_DIR}/src/mountscript.sh ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}${opt_dir}/\n\n\tmkdir -p ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}${system_dir}\n\tcp -avf ${SOURCE_DIR}/src/aznfswatchdog.service ${STG_DIR}/${rpm_dir}/tmp${rpm_buildroot_dir}/${rpm_pkg_dir}${system_dir}\n\n\t# Create the archive for the package.\n\ttar -cvzf ${rpm_pkg_dir}.tar.gz -C ${STG_DIR}/${rpm_dir}/tmp root\n\n\t# Copy the SPEC file to change the placeholders depending upon the RPM distro.\n\tcp -avf ${SOURCE_DIR}/packaging/${pkg_name}/RPM/aznfs.spec ${STG_DIR}/${rpm_dir}/tmp/\n\n\t# Insert current release number and RPM_DIR value.\n\tsed -i -e \"s/Version: x.y.z/Version: ${RELEASE_NUMBER}/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\tsed -i -e \"s/RPM_DIR/${rpm_dir}/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\n\t# Replace the placeholders for various package names in aznfs.spec file. \n\tif [ \"$rpm_dir\" == \"suse\" ]; then\n\t\tsed -i -e \"s/AZNFS_PACKAGE_NAME/${pkg_name}_sles/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\tsed -i -e \"s/NETCAT_PACKAGE_NAME/netcat-openbsd/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\tsed -i -e \"s/DISTRO/suse/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\telse\n\t\tsed -i -e \"s/AZNFS_PACKAGE_NAME/${pkg_name}/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\tsed -i -e \"s/NETCAT_PACKAGE_NAME/nmap-ncat/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\tsed -i -e \"s/DISTRO/rpm/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\t\tsed -i -e \"s/INSTALL_CMD/yum/g\" ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n\tfi\n\n\t# Create the rpm package.\n\trpmbuild --define \"_topdir ${STG_DIR}/${rpm_dir}${rpmbuild_dir}\" -v -bb ${STG_DIR}/${rpm_dir}/tmp/aznfs.spec\n}\n\n#STG_DIR, RELEASE_NUMBER and SOURCE_DIR will be taken as env var.\npkg_name=\"aznfs\"\npkg_dir=\"${pkg_name}-${RELEASE_NUMBER}-1_amd64\"\nrpm_pkg_dir=\"${pkg_name}-${RELEASE_NUMBER}-1.x86_64\"\nopt_dir=\"/opt/microsoft/${pkg_name}\"\nsystem_dir=\"/lib/systemd/system\"\nrpmbuild_dir=\"/root/rpmbuild\"\nrpm_buildroot_dir=\"${rpmbuild_dir}/BUILDROOT\"\n\n# Insert release number to aznfs_install.sh\nsed -i -e \"s/RELEASE_NUMBER=x.y.z/RELEASE_NUMBER=${RELEASE_NUMBER}/g\" ${SOURCE_DIR}/scripts/aznfs_install.sh\n\n#########################\n# Generate .deb package #\n#########################\n\n# Create the directory to hold the package control and data files for deb package.\nmkdir -p ${STG_DIR}/deb/${pkg_dir}/DEBIAN\n\n# Copy the debian control file(s) and maintainer scripts.\ncp -avf ${SOURCE_DIR}/packaging/${pkg_name}/DEBIAN/* ${STG_DIR}/deb/${pkg_dir}/DEBIAN/\nchmod +x ${STG_DIR}/deb/${pkg_dir}/DEBIAN/*\n\n# Insert current release number.\nsed -i -e \"s/Version: x.y.z/Version: ${RELEASE_NUMBER}/g\" ${STG_DIR}/deb/${pkg_dir}/DEBIAN/control\n\n# Copy other static package file(s).\nmkdir -p ${STG_DIR}/deb/${pkg_dir}/usr/sbin\ncp -avf ${SOURCE_DIR}/src/aznfswatchdog ${STG_DIR}/deb/${pkg_dir}/usr/sbin/\n\n# Compile mount.aznfs.c and put the executable into ${STG_DIR}/deb/${pkg_dir}/sbin.\nmkdir -p ${STG_DIR}/deb/${pkg_dir}/sbin\ngcc -static ${SOURCE_DIR}/src/mount.aznfs.c -o ${STG_DIR}/deb/${pkg_dir}/sbin/mount.aznfs\n\nmkdir -p ${STG_DIR}/deb/${pkg_dir}${opt_dir}\ncp -avf ${SOURCE_DIR}/lib/common.sh ${STG_DIR}/deb/${pkg_dir}${opt_dir}/\ncp -avf ${SOURCE_DIR}/src/mountscript.sh ${STG_DIR}/deb/${pkg_dir}${opt_dir}/\n\nmkdir -p ${STG_DIR}/deb/${pkg_dir}${system_dir}\ncp -avf ${SOURCE_DIR}/src/aznfswatchdog.service ${STG_DIR}/deb/${pkg_dir}${system_dir}\n\n# Create the deb package.\ndpkg-deb --root-owner-group --build $STG_DIR/deb/$pkg_dir\n\n#########################\n# Generate .rpm package #\n#########################\n\ngenerate_rpm_package rpm\ngenerate_rpm_package suse", "num_lines": 113}
{"repo_name": "AZNFS-mount", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nAPPNAME=\"aznfs\"\nOPTDIR=\"/opt/microsoft/${APPNAME}\"\nLOGFILE=\"${OPTDIR}/${APPNAME}.log\"\nRANDBYTES=\"${OPTDIR}/randbytes\"\n\n#\n# This stores the map of local IP and share name and external blob endpoint IP.\n#\nMOUNTMAP=\"${OPTDIR}/mountmap\"\n\nRED=\"\\e[2;31m\"\nGREEN=\"\\e[2;32m\"\nYELLOW=\"\\e[2;33m\"\nNORMAL=\"\\e[0m\"\n\nHOSTNAME=$(hostname)\n\n_log()\n{\n    color=$1\n    msg=$2\n\n    echo -e \"${color}${msg}${NORMAL}\"\n    (\n        flock -e 999\n        echo -e \"$(date -u +\"%a %b %d %G %T.%3N\") $HOSTNAME $$: ${color}${msg}${NORMAL}\" >> $LOGFILE\n    ) 999<$LOGFILE\n}\n\n#\n# Plain echo with file logging.\n#\npecho()\n{\n    color=$NORMAL\n    _log $color \"${*}\"\n}\n\n#\n# Success echo.\n#\nsecho()\n{\n    color=$GREEN\n    _log $color \"${*}\"\n}\n\n#\n# Warning echo.\n#\nwecho()\n{\n    color=$YELLOW\n    _log $color \"${*}\"\n}\n\n#\n# Error echo.\n#\neecho()\n{\n    color=$RED\n    _log $color \"${*}\"\n}\n\n#\n# Verbose echo, no-op unless AZNFS_VERBOSE env variable is set.\n#\nvecho()\n{\n    color=$NORMAL\n\n    # Unless AZNFS_VERBOSE flag is set, do not echo to console.\n    if [ -z \"$AZNFS_VERBOSE\" -o \"$AZNFS_VERBOSE\" == \"0\" ]; then\n        (\n            flock -e 999\n            echo -e \"$(date -u +\"%a %b %d %G %T.%3N\") $HOSTNAME $$: ${color}${*}${NORMAL}\" >> $LOGFILE\n        ) 999<$LOGFILE\n\n        return\n    fi\n\n    _log $color \"${*}\"\n}\n\n#\n# Check if the given string is a valid IPv4 address.\n#\nis_valid_ipv4_address()\n{\n    [[ \"$1\" =~ ^([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})\\.([0-9]{1,3})$ ]] &&\n    [ ${BASH_REMATCH[1]} -le 255 ] &&\n    [ ${BASH_REMATCH[2]} -le 255 ] &&\n    [ ${BASH_REMATCH[3]} -le 255 ] &&\n    [ ${BASH_REMATCH[4]} -le 255 ]\n}\n\n#\n# Check if the given string is a valid IPv4 prefix.\n# 10, 10.10, 10.10.10, 10.10.10.10 are valid prefixes, while\n# 1000, 10.256, 10. are not valid prefixes.\n#\nis_valid_ipv4_prefix()\n{\n    ip -4 route get $1 > /dev/null 2>&1\n}\n\n#\n# Check if a given TCP port is reachable. Uses a 3 secs timeout to bail out if address/port is not reachable.\n#\nis_ip_port_reachable()\n{\n    local ip=$1;\n    local port=$2;\n\n    # 3 secs timeout should be good.\n    nc -w 3 -z $ip $port > /dev/null 2>&1\n}\n\n#\n# Blob fqdn to IPv4 adddress.\n# Caller must make sure that it is called only for hostname and not IP address.\n#\n# Note: Since caller captures its o/p this should not log anything other than\n#       the IP address, in case of success return.\n#\nresolve_ipv4()\n{\n    local hname=\"$1\"\n    local RETRIES=3\n\n    # Some retries for resilience.\n    for((i=0;i<=$RETRIES;i++)) {\n        # Resolve hostname to IPv4 address.\n        host_op=$(host -4 -t A \"$hname\" 2>&1)\n        if [ $? -ne 0 ]; then\n            #\n            # Special case of failure to indicate that the fqdn does not exist.\n            # We convey it to our caller using the special o/p \"NXDOMAIN\".\n            #\n            if [[ \"$host_op\" =~ .*NXDOMAIN.* ]]; then\n                echo \"NXDOMAIN\"\n                return 1\n            fi\n\n            vecho \"Failed to resolve ${hname}: $host_op!\"\n            # Exhausted retries?\n            if [ $i -eq $RETRIES ]; then\n                return 1\n            fi\n            # Mostly some transient issue, retry after some sleep.\n            sleep 1\n            continue\n        fi\n\n        #\n        # For ZRS accounts, we will get 3 IP addresses whose order keeps changing.\n        # We sort the output of host so that we always look at the same address,\n        # also we shuffle it so that different clients balance out across different\n        # zones.\n        #\n        ipv4_addr_all=$(echo \"$host_op\" | grep \" has address \" | awk '{print $4}' |\\\n                        sort | shuf --random-source=$RANDBYTES)\n\n        cnt_ip=$(echo \"$ipv4_addr_all\" | wc -l)\n\n        if [ $cnt_ip -eq 0 ]; then\n            vecho \"host returned 0 address for ${hname}, expected one or more! [$host_op]\"\n            # Exhausted retries?\n            if [ $i -eq $RETRIES ]; then\n                return 1\n            fi\n            # Mostly some transient issue, retry after some sleep.\n            sleep 1\n            continue\n        fi\n\n        break\n    }\n\n    # Use first address from the above curated list.\n    ipv4_addr=$(echo \"$ipv4_addr_all\" | head -n1)\n\n    # For ZRS we need to use the first reachable IP.\n    if [ $cnt_ip -ne 1 ]; then\n        for((i=1;i<=$cnt_ip;i++)) {\n            ipv4_addr=$(echo \"$ipv4_addr_all\" | tail -n +$i | head -n1)\n            if is_ip_port_reachable $ipv4_addr 2048; then\n                break\n            fi\n        }\n    fi\n\n    if ! is_valid_ipv4_address \"$ipv4_addr\"; then\n        eecho \"[FATAL] host returned bad IPv4 address $ipv4_addr for hostname ${hname}!\"\n        return 1\n    fi\n\n    echo $ipv4_addr\n    return 0\n}\n\n#\n# Function to check if an IP is private.\n#\nis_private_ip()\n{\n    local ip=$1\n\n    if ! is_valid_ipv4_address $ip; then\n        return 1\n    fi\n\n    #\n    # Check if the IP belongs to the private IP range (10.0.0.0/8,\n    # 172.16.0.0/12, or 192.168.0.0/16).f\n    #\n    [[ $ip =~ ^10\\..* ]] ||\n    [[ $ip =~ ^172\\.(1[6-9]|2[0-9]|3[0-1])\\..* ]] ||\n    [[ $ip =~ ^192\\.168\\..* ]]\n}\n\n#\n# Mount helper must call this function to grab a timed lease on all MOUNTMAP\n# entries. It should do this if it decides to use any of the entries. Once\n# this is called aznfswatchdog is guaranteed to not delete any MOUNTMAP till\n# the next 5 minutes.\n#\n# Must be called with MOUNTMAP lock held.\n#\ntouch_mountmap()\n{\n    chattr -f -i $MOUNTMAP\n    touch $MOUNTMAP\n    if [ $? -ne 0 ]; then\n        chattr -f +i $MOUNTMAP\n        eecho \"Failed to touch ${MOUNTMAP}!\"\n        return 1\n    fi\n    chattr -f +i $MOUNTMAP\n}\n\n#\n# MOUNTMAP is accessed by both mount.aznfs and aznfswatchdog service. Update it\n# only after taking exclusive lock.\n#\n# Add entry to $MOUNTMAP in case of a new mount or IP change for blob FQDN.\n#\n# This also ensures that the corresponding DNAT rule is created so that MOUNTMAP\n# entry and DNAT rule are always in sync.\n#\nensure_mountmap_exist_nolock()\n{\n    IFS=\" \" read l_host l_ip l_nfsip <<< \"$1\"\n    if ! ensure_iptable_entry $l_ip $l_nfsip; then\n        eecho \"[$1] failed to add to ${MOUNTMAP}!\"\n        return 1\n    fi\n\n    egrep -q \"^${1}$\" $MOUNTMAP\n    if [ $? -ne 0 ]; then\n        chattr -f -i $MOUNTMAP\n        echo \"$1\" >> $MOUNTMAP\n        if [ $? -ne 0 ]; then\n            chattr -f +i $MOUNTMAP\n            eecho \"[$1] failed to add to ${MOUNTMAP}!\"\n            # Could not add MOUNTMAP entry, delete the DNAT rule added above.\n            ensure_iptable_entry_not_exist $l_ip $l_nfsip\n            return 1\n        fi\n        chattr -f +i $MOUNTMAP\n    else\n        pecho \"[$1] already exists in ${MOUNTMAP}.\"\n    fi\n}\n\nensure_mountmap_exist()\n{\n    (\n        flock -e 999\n        ensure_mountmap_exist_nolock \"$1\"\n        return $?\n    ) 999<$MOUNTMAP\n}\n\n#\n# Delete entry from $MOUNTMAP and also the corresponding iptable rule.\n#\nensure_mountmap_not_exist()\n{\n    (\n        flock -e 999\n\n        #\n        # If user wants to delete the entry only if MOUNTMAP has not changed since\n        # he looked up, honour that.\n        #\n        local ifmatch=\"$2\"\n        if [ -n \"$ifmatch\" ]; then\n            local mtime=$(stat -c%Y $MOUNTMAP)\n            if [ \"$mtime\" != \"$ifmatch\" ]; then\n                eecho \"[$1] Refusing to remove from ${MOUNTMAP} as $mtime != $ifmatch!\"\n                return 1\n            fi\n        fi\n\n        # Delete iptable rule corresponding to the outgoing MOUNTMAP entry.\n        IFS=\" \" read l_host l_ip l_nfsip <<< \"$1\"\n        if [ -n \"$l_host\" -a -n \"$l_ip\" -a -n \"$l_nfsip\" ]; then\n            if ! ensure_iptable_entry_not_exist $l_ip $l_nfsip; then\n                eecho \"[$1] Refusing to remove from ${MOUNTMAP} as iptable entry could not be deleted!\"\n                return 1\n            fi\n        fi\n\n        chattr -f -i $MOUNTMAP\n        #\n        # We do this thing instead of inplace update by sed as that has a\n        # very bad side-effect of creating a new MOUNTMAP file. This breaks\n        # any locking that we dependent on the old file.\n        #\n        out=$(sed \"\\%^${1}$%d\" $MOUNTMAP)\n        ret=$?\n        if [ $ret -eq 0 ]; then\n            #\n            # If this echo fails then MOUNTMAP could be truncated. In that case we need\n            # to reconcile it from the mount info and iptable info. That needs to be done\n            # out-of-band.\n            #\n            echo \"$out\" > $MOUNTMAP\n            ret=$?\n            out=\n            if [ $ret -ne 0 ]; then\n                eecho \"*** [FATAL] MOUNTMAP may be in inconsistent state, contact Microsoft support ***\"\n            fi\n        fi\n\n        if [ $ret -ne 0 ]; then\n            chattr -f +i $MOUNTMAP\n            eecho \"[$1] failed to remove from ${MOUNTMAP}!\"\n            # Reinstate DNAT rule deleted above.\n            ensure_iptable_entry $l_ip $l_nfsip\n            return 1\n        fi\n        chattr -f +i $MOUNTMAP\n\n        # Return the mtime after our mods.\n        echo $(stat -c%Y $MOUNTMAP)\n    ) 999<$MOUNTMAP\n}\n\n#\n# Replace a mountmap entry with a new one.\n# This will also update the iptable DNAT rules accordingly, deleting DNAT rule\n# corresponding to old entry and adding the DNAT rule corresponding to the new\n# entry.\n#\nupdate_mountmap_entry()\n{\n    local old=$1\n    local new=$2\n\n    vecho \"Updating mountmap entry [$old -> $new]\"\n\n    (\n        flock -e 999\n\n        IFS=\" \" read l_host l_ip l_nfsip_old <<< \"$old\"\n        if [ -n \"$l_host\" -a -n \"$l_ip\" -a -n \"$l_nfsip_old\" ]; then\n            if ! ensure_iptable_entry_not_exist $l_ip $l_nfsip_old; then\n                eecho \"[$old] Refusing to remove from ${MOUNTMAP} as old iptable entry could not be deleted!\"\n                return 1\n            fi\n        fi\n\n        IFS=\" \" read l_host l_ip l_nfsip_new <<< \"$new\"\n        if [ -n \"$l_host\" -a -n \"$l_ip\" -a -n \"$l_nfsip_new\" ]; then\n            if ! ensure_iptable_entry $l_ip $l_nfsip_new; then\n                eecho \"[$new] Refusing to remove from ${MOUNTMAP} as new iptable entry could not be added!\"\n                # Roll back.\n                ensure_iptable_entry $l_ip $l_nfsip_old\n                return 1\n            fi\n        fi\n\n        chattr -f -i $MOUNTMAP\n        #\n        # We do this thing instead of inplace update by sed as that has a\n        # very bad side-effect of creating a new MOUNTMAP file. This breaks\n        # any locking that we dependent on the old file.\n        #\n        out=$(sed \"s%^${old}$%${new}%g\" $MOUNTMAP)\n        ret=$?\n        if [ $ret -eq 0 ]; then\n            #\n            # If this echo fails then MOUNTMAP could be truncated. In that case we need\n            # to reconcile it from the mount info and iptable info. That needs to be done\n            # out-of-band.\n            #\n            echo \"$out\" > $MOUNTMAP\n            ret=$?\n            out=\n            if [ $ret -ne 0 ]; then\n                eecho \"*** [FATAL] MOUNTMAP may be in inconsistent state, contact Microsoft support ***\"\n            fi\n        fi\n\n        if [ $ret -ne 0 ]; then\n            chattr -f +i $MOUNTMAP\n            eecho \"[$old -> $new] failed to update ${MOUNTMAP}!\"\n            # Roll back.\n            ensure_iptable_entry_not_exist $l_ip $l_nfsip_new\n            ensure_iptable_entry $l_ip $l_nfsip_old\n            return 1\n        fi\n        chattr -f +i $MOUNTMAP\n    ) 999<$MOUNTMAP\n}\n\n#\n# Ensure given DNAT rule exists, if not it creates it else silently exits.\n#\nensure_iptable_entry()\n{\n    iptables -w 60 -t nat -C OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\" > /dev/null 2>&1\n    if [ $? -ne 0 ]; then\n        iptables -w 60 -t nat -I OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\"\n        if [ $? -ne 0 ]; then\n            eecho \"Failed to add DNAT rule [$1 -> $2]!\"\n            return 1\n        fi\n    fi\n}\n\n#\n# Ensure given DNAT rule is deleted, silently exits if the rule doesn't exist.\n# Also removes the corresponding entry from conntrack.\n#\nensure_iptable_entry_not_exist()\n{\n    iptables -w 60 -t nat -C OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\" > /dev/null 2>&1\n    if [ $? -eq 0 ]; then\n        iptables -w 60 -t nat -D OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\"\n        if [ $? -ne 0 ]; then\n            eecho \"Failed to delete DNAT rule [$1 -> $2]!\"\n            return 1\n        fi\n\n        # Ignore status of conntrack because entry may not exist (timed out).\n        output=$(conntrack -D conntrack -p tcp -d \"$1\" -r \"$2\" 2>&1)\n        if [ $? -ne 0 ]; then\n            vecho \"$output\"\n        fi\n    fi\n}\n\n#\n# Verify if the mountmap entry is present but corresponding DNAT rule does not\n# exist. Add it to avoid IOps failure.\n#\nverify_iptable_entry()\n{\n    iptables -w 60 -t nat -C OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\" > /dev/null 2>&1\n    if [ $? -ne 0 ]; then\n        wecho \"DNAT rule [$1 -> $2] does not exist, adding it.\"\n        iptables -w 60 -t nat -I OUTPUT -p tcp -d \"$1\" -j DNAT --to-destination \"$2\"\n        if [ $? -ne 0 ]; then\n            eecho \"Failed to add DNAT rule [$1 -> $2]!\"\n            return 1\n        fi\n    fi\n}\n\n# On some distros mount program doesn't pass correct PATH variable.\nexport PATH=$PATH:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin\n\nmkdir -p $OPTDIR\nif [ $? -ne 0 ]; then\n    eecho \"[FATAL] Not able to create '${OPTDIR}'!\"\n    exit 1\nfi\n\nif [ ! -f $LOGFILE ]; then\n    touch $LOGFILE\n    if [ $? -ne 0 ]; then\n        eecho \"[FATAL] Not able to create '${LOGFILE}'!\"\n        exit 1\n    fi\nfi\n\nif [ ! -f $MOUNTMAP ]; then\n    touch $MOUNTMAP\n    if [ $? -ne 0 ]; then\n        eecho \"[FATAL] Not able to create '${MOUNTMAP}'!\"\n        exit 1\n    fi\n    chattr -f +i $MOUNTMAP\nfi\n\nulimitfd=$(ulimit -n 2>/dev/null)\nif [ -n \"$ulimitfd\" -a $ulimitfd -lt 131072 ]; then\n    ulimit -n 131072\nfi\n\n#\n# In case there are inherited fds, close other than 0,1,2.\n#\nfor fd in $(ls /proc/$$/fd/); do\n    [ $fd -gt 2 ] && exec {fd}<&-\ndone", "num_lines": 517}
{"repo_name": "AZNFS-mount", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nRELEASE_NUMBER=x.y.z\nAZNFS_RELEASE=\"aznfs-${RELEASE_NUMBER}-1\"\nAZNFS_RELEASE_SUSE=\"aznfs_sles-${RELEASE_NUMBER}-1\"\napt_update_done=false\nyum=\"yum\"\napt=0\nzypper=0\ndistro_id=\ninstall_cmd=\n\nRED=\"\\e[2;31m\"\nGREEN=\"\\e[2;32m\"\nYELLOW=\"\\e[2;33m\"\nNORMAL=\"\\e[0m\"\n\n#\n# Core logging function.\n#\n_log()\n{\n    color=$1\n    msg=$2\n\n    echo -e \"${color}${msg}${NORMAL}\"\n}\n\n#\n# Plain echo.\n#\npecho()\n{\n    color=$NORMAL\n    _log $color \"${*}\"\n}\n\n#\n# Success echo.\n#\nsecho()\n{\n    color=$GREEN\n    _log $color \"${*}\"\n}\n\n#\n# Warning echo.\n#\nwecho()\n{\n    color=$YELLOW\n    _log $color \"${*}\"\n}\n\n#\n# Error echo.\n#\neecho()\n{\n    color=$RED\n    _log $color \"${*}\"\n}\n\nuse_dnf_or_yum() \n{\n    yum=\"yum\"\n    if command -v dnf &> /dev/null; then\n        yum=\"dnf\"\n        pecho \"Using 'dnf' instead of 'yum'\"\n    fi\n}\n\n#\n# This returns distro id in a canonical form, that rest of the code understands.\n# We only use lowercase single word names for distro names:\n# ubuntu, centos, redhat, sles.\n#\ncanonicalize_distro_id()\n{\n    local distro_lower=$(echo \"$1\" | tr '[:upper:]' '[:lower:]')\n\n    # Use sles for SUSE/SLES.\n    if [ \"$distro_lower\" == \"suse\" ]; then\n        distro_lower=\"sles\"\n    fi\n\n    echo \"$distro_lower\"\n}\n\n#\n# Install the package appropriately as per the current distro.\n# If distro_id is already detected it uses that else it tries to guess\n# the distro.\n#\nensure_pkg()\n{\n    local pkg=\"$1\"\n    local distro=\"$distro_id\"\n\n    if [ \"$distro\" == \"ubuntu\" ]; then\n        if ! $apt_update_done; then\n            apt -y update\n            if [ $? -ne 0 ]; then\n                echo\n                eecho \"\\\"apt update\\\" failed\"\n                eecho \"Please make sure \\\"apt update\\\" runs successfully and then try again!\"\n                echo\n                exit 1\n            fi\n            # Need to run apt update only once.\n            apt_update_done=true\n        fi\n        apt=1\n        apt install -y $pkg\n    elif [ \"$distro\" == \"centos\" -o \"$distro\" == \"rocky\" -o \"$distro\" == \"rhel\" ]; then\n        # lsb_release package is called redhat-lsb-core in redhat/centos.\n        if [ \"$pkg\" == \"lsb-release\" ]; then\n            pkg=\"redhat-lsb-core\"\n        fi\n        use_dnf_or_yum\n        $yum install -y $pkg\n    elif [ \"$distro\" == \"sles\" ]; then\n        zypper=1\n        zypper install -y $pkg\n    fi\n}\n\nverify_super_user()\n{\n    if [ $(id -u) -ne 0 ]; then\n        eecho \"Run this script as root!\"\n        exit 1\n    fi\n}\n\nif [ \"$RELEASE_NUMBER\" == \"x.y.z\" ]; then\n    eecho \"This script is directly downloaded from the github source code.\"\n    eecho \"Please download the aznfs_install.sh from 'https://github.com/Azure/AZNFS-mount/releases/latest/download/aznfs_install.sh'\"\n    eecho \"If the problem persists, contact Microsoft support.\"\n    exit 1\nfi\n\n#\n# Only super user can install aznfs.\n#\nverify_super_user\n\n#\n# Detect OS and Version.\n#\n__m=$(uname -m 2>/dev/null) || __m=unknown\n__s=$(uname -s 2>/dev/null) || __s=unknown\n\n#\n# Try to detect the distro in a resilient manner and set distro_id\n# global variables.\n#\ncase \"${__m}:${__s}\" in\n    \"x86_64:Linux\")\n        if [ -f /etc/centos-release ]; then\n            pecho \"Retrieving distro info from /etc/centos-release...\"\n            distro_id=\"centos\"\n        elif [ -f /etc/os-release ]; then\n            pecho \"Retrieving distro info from /etc/os-release...\"\n            distro_id=$(grep \"^ID=\" /etc/os-release | awk -F= '{print $2}' | tr -d '\"')\n            distro_id=$(canonicalize_distro_id $distro_id)\n        else\n            eecho \"[FATAL] Unknown linux distro, /etc/os-release not found!\"\n            pecho \"Download .deb/.rpm package based on your distro from 'https://github.com/Azure/AZNFS-mount/releases/latest'\"\n            pecho \"If the problem persists, contact Microsoft support.\"\n        fi\n        ;;\n    *)\n        eecho \"[FATAL] Unsupported platform: ${__m}:${__s}.\"\n        exit 1\n        ;;\nesac\n\nensure_pkg \"wget\"\n\nif [ $apt -eq 1 ]; then\n    install_cmd=\"apt\"\n    package_info=$(apt-cache show aznfs 2>/dev/null)\n    is_uninstalled=$(echo \"$package_info\" | grep \"^Status\" | grep \"\\<deinstall\\>\")\n    current_version=$(apt-cache show aznfs 2>/dev/null | grep \"^Version\" | tr -d \" \" | cut -d ':' -f2)\n    if [ -n \"$current_version\" -a -z \"$is_uninstalled\" ]; then\n        if [ \"$current_version\" == \"$RELEASE_NUMBER\" ]; then\n            secho \"AZNFS version $current_version is already installed.\"\n            exit 0\n        fi\n        read -n 1 -p \"AZNFS version $current_version is already installed. Do you want to install version $RELEASE_NUMBER? [Y/n] \" result < /dev/tty\n        echo\n        if [ -n \"$result\" -a \"$result\" != \"y\" -a \"$result\" != \"Y\" ]; then\n            eecho \"Installation aborted!\"\n            exit 1\n        fi\n    fi\n\n    wget https://github.com/Azure/AZNFS-mount/releases/download/${RELEASE_NUMBER}/${AZNFS_RELEASE}_amd64.deb -P /tmp\n    apt install -y /tmp/${AZNFS_RELEASE}_amd64.deb\n    install_error=$?\n    rm -f /tmp/${AZNFS_RELEASE}_amd64.deb\nelif [ $zypper -eq 1 ]; then\n    install_cmd=\"zypper\"\n    current_version=$(zypper info aznfs_sles 2>/dev/null | grep \"^Version\" | tr -d \" \" | cut -d ':' -f2 | cut -d '-' -f1)\n    if [ -n \"$current_version\" ]; then\n        if [ \"$current_version\" == \"$RELEASE_NUMBER\" ]; then\n            secho \"AZNFS version $current_version is already installed.\"\n            exit 0\n        fi\n        read -n 1 -p \"AZNFS version $current_version is already installed. Do you want to install version $RELEASE_NUMBER? [Y/n] \" result < /dev/tty\n        echo\n        if [ -n \"$result\" -a \"$result\" != \"y\" -a \"$result\" != \"Y\" ]; then\n            eecho \"Installation aborted!\"\n            exit 1\n        fi\n    fi\n\n    wget https://github.com/Azure/AZNFS-mount/releases/download/${RELEASE_NUMBER}/${AZNFS_RELEASE_SUSE}.x86_64.rpm -P /tmp\n    zypper install --allow-unsigned-rpm -y /tmp/${AZNFS_RELEASE_SUSE}.x86_64.rpm\n    install_error=$?\n    rm -f /tmp/${AZNFS_RELEASE_SUSE}.x86_64.rpm\nelse\n    install_cmd=\"yum\"\n    current_version=$(yum info aznfs 2>/dev/null | grep \"^Version\" | tr -d \" \" | cut -d ':' -f2)\n    if [ -n \"$current_version\" ]; then\n        if [ \"$current_version\" == \"$RELEASE_NUMBER\" ]; then\n            secho \"AZNFS version $current_version is already installed.\"\n            exit 0\n        fi\n        read -n 1 -p \"AZNFS version $current_version is already installed. Do you want to install version $RELEASE_NUMBER? [Y/n] \" result < /dev/tty\n        echo\n        if [ -n \"$result\" -a \"$result\" != \"y\" -a \"$result\" != \"Y\" ]; then\n            eecho \"Installation aborted!\"\n            exit 1\n        fi\n    fi\n\n    wget https://github.com/Azure/AZNFS-mount/releases/download/${RELEASE_NUMBER}/${AZNFS_RELEASE}.x86_64.rpm -P /tmp\n    yum install -y /tmp/${AZNFS_RELEASE}.x86_64.rpm\n    install_error=$?\n    rm -f /tmp/${AZNFS_RELEASE}.x86_64.rpm\nfi\n\nif [ $install_error -ne 0 ]; then\n    eecho \"[FATAL] Error installing aznfs (Error: $install_error). See '$install_cmd' command logs for more information.\"\n    exit 1\nfi\n\nsecho \"Version $RELEASE_NUMBER of aznfs mount helper is successfully installed.\"", "num_lines": 255}
{"repo_name": "AZNFS-mount", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\n#\n# Load common aznfs helpers.\n#\n. /opt/microsoft/aznfs/common.sh\n\n#\n# Default order in which we try the network prefixes for a free local IP to use.\n# This can be overriden using AZNFS_IP_PREFIXES environment variable.\n#\nDEFAULT_AZNFS_IP_PREFIXES=\"10.161 192.168 172.16\"\nIP_PREFIXES=\"${AZNFS_IP_PREFIXES:-${DEFAULT_AZNFS_IP_PREFIXES}}\"\n\n# Aznfs port, defaults to 2048.\nAZNFS_PORT=\"${AZNFS_PORT:-2048}\"\n\n# Default to checking azure nconnect support.\nAZNFS_CHECK_AZURE_NCONNECT=\"${AZNFS_CHECK_AZURE_NCONNECT:-1}\"\n\n# Default to fixing mount options passed in to help the user.\nAZNFS_FIX_MOUNT_OPTIONS=\"${AZNFS_FIX_MOUNT_OPTIONS:-1}\"\n\n#\n# Use noresvport mount option to allow using non-reserve ports by client.\n# This allows much higher number of local ports to be used by NFS client and\n# hence may alleviate some issues due to running out of very small resv port range.\n# Blob NFS doesn't require clients to use reserve ports so we can use non-reserve\n# port with Blob NFS but Linux NFS client doesn't reuse source port while reconnecting\n# if noresvport option is used. This does not work will with the DRC cache.\n#\nAZNFS_USE_NORESVPORT=\"${AZNFS_USE_NORESVPORT:-0}\"\n\n#\n# Maximum number of accounts that can be mounted from the same tenant/cluster.\n# Any number of containers on these many accounts can be mounted.\n# With ~350 reserved ports and 16 connections per mount (with nconnect=16) leaving\n# some room, 20 is a reasonable limit.\n#\nMAX_ACCOUNTS_MOUNTABLE_FROM_SINGLE_TENANT=20\n\n#\n# Local IP that is free to use.\n#\nLOCAL_IP=\"\"\n\n#\n# Proccess ID of the current process.\n#\nPID=\"\"\n\n#\n# Choose the local IP based on last used IP in MOUNTMAP if this flag is enabled.\n#\nOPTIMIZE_GET_FREE_LOCAL_IP=true\n\n#\n# Check if the given string is a valid blob FQDN (<accountname>.blob.core.windows.net).\n#\nis_valid_blob_fqdn()\n{\n    [[ $1 =~ ^([a-z0-9]{3,24})(.z[0-9]+)?.blob(.preprod)?.core.windows.net$ ]]\n}\n\n#\n# Check if nconnect mount option can be used. If not bail out failing the mount,\n# else if NFS client supports Azure nconnect but it's not enabled, enable it.\n#\ncheck_nconnect()\n{\n    matchstr=\"\\<nconnect\\>=([0-9]+)\"\n    if [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        value=\"${BASH_REMATCH[1]}\"\n        if [ $value -gt 1 ]; then\n            modprobe sunrpc\n            if [ ! -e /sys/module/sunrpc/parameters/enable_azure_nconnect ]; then\n                eecho \"nconnect option needs NFS client with Azure nconnect support!\"\n                return 1\n            fi\n\n            # Supported, enable if not enabled.\n            enabled=$(cat /sys/module/sunrpc/parameters/enable_azure_nconnect)\n            if ! [[ \"$enabled\" =~ [yY] ]]; then\n                pecho \"Azure nconnect not enabled, enabling!\"\n                echo Y > /sys/module/sunrpc/parameters/enable_azure_nconnect\n            fi\n        fi\n    fi\n}\n\n#\n# Help fix the mount options passed in by user.\n#\nfix_mount_options()\n{\n    matchstr=\"\\<sec\\>=([^,]+)\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,sec=sys\"\n    else\n        value=\"${BASH_REMATCH[1]}\"\n        if [ \"$value\" != \"sys\" ]; then\n            pecho \"Unsupported mount option sec=$value, fixing to sec=sys!\"\n            MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/\\<sec\\>=$value/sec=sys/g\")\n        fi\n    fi\n\n    matchstr=\"\\<nolock\\>\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        pecho \"Adding nolock mount option!\"\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,nolock\"\n    fi\n\n    matchstr=\"\\<proto\\>=([^,]+)\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        pecho \"Adding proto=tcp mount option!\"\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,proto=tcp\"\n    else\n        value=\"${BASH_REMATCH[1]}\"\n        if [ \"$value\" != \"tcp\" ]; then\n            pecho \"Unsupported mount option proto=$value, fixing to proto=tcp!\"\n            MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/\\<proto\\>=$value/proto=tcp/g\")\n        fi\n    fi\n\n    matchstr=\"\\<vers\\>=([0-9]+)\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        pecho \"Adding vers=3 mount option!\"\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,vers=3\"\n    else\n        value=\"${BASH_REMATCH[1]}\"\n        if [ \"$value\" != \"3\" ]; then\n            pecho \"Unsupported mount option vers=$value, fixing to vers=3!\"\n            MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/\\<vers\\>=$value/vers=3/g\")\n        fi\n    fi\n\n    matchstr=\"\\<rsize\\>=([0-9]+)\"\n    if [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        value=\"${BASH_REMATCH[1]}\"\n        if [ $value -ne 1048576 ]; then\n            pecho \"Suboptimal rsize=$value mount option, setting rsize=1048576!\"\n            MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/\\<rsize\\>=$value/rsize=1048576/g\")\n        fi\n    fi\n\n    matchstr=\"\\<wsize\\>=([0-9]+)\"\n    if [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        value=\"${BASH_REMATCH[1]}\"\n        if [ $value -ne 1048576 ]; then\n            pecho \"Suboptimal wsize=$value mount option, setting wsize=1048576!\"\n            MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/\\<wsize\\>=$value/wsize=1048576/g\")\n        fi\n    fi\n\n    if [ \"$AZNFS_USE_NORESVPORT\" == \"1\" ]; then\n        matchstr=\"\\<resvport\\>|\\<noresvport\\>\"\n        if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n            MOUNT_OPTIONS=\"$MOUNT_OPTIONS,noresvport\"\n        fi\n    fi\n\n    MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/^,//g\")\n}\n\n#\n# Check if mounting this new share will exceed the \"max accounts mountable per tenant\" limit.\n#\ncheck_account_count()\n{\n    #\n    # nfs_ip MUST be set before calling this function.\n    #\n    local num=$(grep -c \" ${nfs_ip}$\" $MOUNTMAP)\n    if [ $num -ge $MAX_ACCOUNTS_MOUNTABLE_FROM_SINGLE_TENANT ]; then\n        #\n        # If this is not a new account it will reuse the existing entry and not\n        # cause a new entry to be added to MOUNTMAP, in that case allow the mount.\n        #\n        if ! grep -q \"^${nfs_host} \" $MOUNTMAP; then\n            return 1\n        fi\n    fi\n\n    return 0\n}\n\n#\n# Get blob endpoint from account.blob.core.windows.net:/account/container.\n#\nget_host_from_share()\n{\n    local hostshare=\"$1\"\n    IFS=: read host share <<< \"$hostshare\"\n\n    if [ -z \"$host\" -o -z \"$share\" ]; then\n        eecho \"Bad share name: ${hostshare}.\"\n        eecho \"Share to be mounted must be of the form 'account.blob.core.windows.net:/account/container'.\"\n        return 1\n    fi\n\n    echo \"$host\"\n}\n\n#\n# Get /account/container from account.blob.core.windows.net:/account/container.\n#\nget_dir_from_share()\n{\n    local hostshare=\"$1\"\n    IFS=: read _ share <<< \"$hostshare\"\n    IFS=/ read _ account container extra <<< \"$share\"\n\n    if [ -z \"$account\" -o -z \"$container\" -o -n \"$extra\" ]; then\n        eecho \"Bad share name: ${hostshare}.\"\n        eecho \"Share to be mounted must be of the form 'account.blob.core.windows.net:/account/container'.\"\n        return 1\n    fi\n\n    echo \"$share\"\n}\n\n#\n# Is the given address one of the host addresses?\n#\nis_host_ip()\n{\n    #\n    # Do not make this local as status gathering does not work well when\n    # collecting command o/p to local variables.\n    #\n    route=$(ip -4 route get fibmatch $1 2>/dev/null)\n    if [ $? -ne 0 ]; then\n        return 1\n    fi\n\n    if ! echo \"$route\" | grep -q \"scope host\"; then\n        return 1\n    fi\n\n    return 0\n}\n\n#\n# Is the given address one of the addresses directly reachable from the host?\n#\nis_link_ip()\n{\n    #\n    # Do not make this local as status gathering does not work well when\n    # collecting command o/p to local variables.\n    #\n    route=$(ip -4 route get fibmatch $1 2>/dev/null)\n    if [ $? -ne 0 ]; then\n        return 1\n    fi\n\n    if ! echo \"$route\" | grep -q \"scope link\"; then\n        return 1\n    fi\n\n    return 0\n}\n\n#\n# Check if a given IPv4 address is responding to ICMP pings.\n# Uses a 3 secs timeout to bail out in time if address is not responding.\n#\nis_pinging()\n{\n    #\n    # Unless env var AZNFS_PING_LOCAL_IP_BEFORE_USE is set, pretend IP address\n    # is available.\n    #\n    if [ \"$AZNFS_PING_LOCAL_IP_BEFORE_USE\" != \"1\" ]; then\n        return 1\n    fi\n\n    local ip=$1\n\n    # 3 secs timeout should be good.\n    ping -4 -W3 -c1 $ip > /dev/null 2>&1\n}\n\n#\n# Returns number of octets in an IPv4 prefix.\n# If IP prefix is not valid or is not a private IP address prefix, it returns 0.\n#\n# f.e. For 10 it will return 1, for 10.10 it will return 2, for 10.10.10 it will\n# return 3 and for 10.10.10.10, it will return 4.\n#\noctets_in_ipv4_prefix()\n{\n    local ip=$1\n    local octet=\"[0-9]{1,3}\"\n    local octetdot=\"${octet}\\.\"\n\n    if ! is_valid_ipv4_prefix $ip; then\n        echo 0\n        return\n    fi\n\n    #\n    # Check if the IP prefix belongs to the private IP range (10.0.0.0/8,\n    # 172.16.0.0/12, or 192.168.0.0/16), i.e., will the user provided prefix\n    # result in a private IP address.\n    #\n    [[ $ip =~ ^10(\\.${octet})*$ ]] ||\n    [[ $ip =~ ^172\\.(1[6-9]|2[0-9]|3[0-1])(\\.${octet})*$ ]] ||\n    [[ $ip =~ ^192\\.168(\\.${octet})*$ ]]\n\n    if [ $? -ne 0 ]; then\n        echo 0\n        return\n    fi\n\n    # 4 octets.\n    [[ $ip =~ ^(${octetdot}){3}${octet}$ ]] && echo 4 && return;\n\n    # 3 octets\n    [[ $ip =~ ^(${octetdot}){2}${octet}$ ]] && echo 3 && return;\n\n    # 2 octets.\n    [[ $ip =~ ^(${octetdot}){1}${octet}$ ]] && echo 2 && return;\n\n    # 1 octet.\n    [[ $ip =~ ^${octet}$ ]] && echo 1 && return;\n\n    echo 0\n}\n\nsearch_free_local_ip_with_prefix()\n{\n    initial_ip_prefix=$1\n    num_octets=$(octets_in_ipv4_prefix $ip_prefix)\n\n    if [ $num_octets -ne 2 -a $num_octets -ne 3 ]; then\n        eecho \"Invalid IPv4 prefix: ${ip_prefix}\"\n        eecho \"Valid prefix must have either 2 or 3 octets and must be a valid private IPv4 address prefix.\"\n        eecho \"Examples of valid private IPv4 prefixes are 10.10, 10.10.10, 192.168, 192.168.10 etc.\"\n        return 1\n    fi\n\n    local local_ip=\"\"\n    local optimize_get_free_local_ip=false\n    local used_local_ips_with_same_prefix=$(cat $MOUNTMAP | awk '{print $2}' | grep \"^${initial_ip_prefix}\\.\" | sort -t . -k 1,1n -k 2,2n -k 3,3n -k 4,4n)\n    local iptable_entries=$(iptables-save -t nat)\n\n    _3rdoctet=100\n    ip_prefix=$initial_ip_prefix\n\n    #\n    # Optimize the process to get free local IP by starting the loop to choose\n    # 3rd and 4th octet from the number which was used last and still exist in\n    # MOUNTMAP instead of starting it from 100.\n    #\n    if [ $OPTIMIZE_GET_FREE_LOCAL_IP == true -a -n \"$used_local_ips_with_same_prefix\" ]; then\n\n        last_used_ip=$(echo \"$used_local_ips_with_same_prefix\" | tail -n1)\n\n        IFS=\".\" read _ _ last_used_3rd_octet last_used_4th_octet <<< \"$last_used_ip\"\n\n        if [ $num_octets -eq 2 ]; then\n            if [ \"$last_used_3rd_octet\" == \"254\" -a \"$last_used_4th_octet\" == \"254\" ]; then\n                return 1\n            fi\n\n            _3rdoctet=$last_used_3rd_octet\n            optimize_get_free_local_ip=true\n        else\n            if [ \"$last_used_4th_octet\" == \"254\" ]; then\n                return 1\n            fi\n\n            optimize_get_free_local_ip=true\n        fi\n    fi\n\n    while true; do\n        if [ $num_octets -eq 2 ]; then\n            for ((; _3rdoctet<255; _3rdoctet++)); do\n                ip_prefix=\"${ip_prefix}.$_3rdoctet\"\n\n                if is_link_ip $ip_prefix; then\n                    vecho \"Skipping link network ${ip_prefix}!\"\n                    continue\n                fi\n\n                break\n            done\n\n            if [ $_3rdoctet -eq 255 ]; then\n                #\n                # If the IP prefix had 2 octets and we exhausted all possible\n                # values of the 3rd and 4th octet, then we have failed the\n                # search for free local IP within the given prefix.\n                #\n                return 1\n            fi\n        fi\n\n        if $optimize_get_free_local_ip; then\n            _4thoctet=$(expr ${last_used_4th_octet} + 1)\n            optimize_get_free_local_ip=false\n        else\n            _4thoctet=100\n        fi\n\n        for ((; _4thoctet<255; _4thoctet++)); do\n            local_ip=\"${ip_prefix}.$_4thoctet\"\n\n            is_ip_used_by_aznfs=$(echo \"$used_local_ips_with_same_prefix\" | grep \"^${local_ip}$\")\n            if [ -n \"$is_ip_used_by_aznfs\" ]; then\n                vecho \"$local_ip is in use by aznfs!\"\n                continue\n            fi\n\n            if is_host_ip $local_ip; then\n                vecho \"Skipping host address ${local_ip}!\"\n                continue\n            fi\n\n            if is_link_ip $local_ip; then\n                vecho \"Skipping link network ${local_ip}!\"\n                continue\n            fi\n\n            if [ \"$nfs_ip\" == \"$local_ip\" ]; then\n                vecho \"Skipping private endpoint IP ${nfs_ip}!\"\n                continue\n            fi\n\n            is_present_in_iptables=$(echo \"$iptable_entries\" | grep -c \"\\<${local_ip}\\>\")\n            if [ $is_present_in_iptables -ne 0 ]; then\n                vecho \"$local_ip is already present in iptables!\"\n                continue\n            fi\n\n            #\n            # Try pinging the address to be sure it is not in use in the\n            # client network.\n            #\n            # Note: If the address exists but not responding to ICMP ping then\n            #       we will incorrectly treat it as non-exixtent.\n            #\n            if is_pinging $local_ip; then\n                vecho \"Skipping $local_ip as it appears to be in use on the network!\"\n                continue\n            fi\n\n            vecho \"Using local IP ($local_ip) for aznfs.\"\n            break\n        done\n\n        if [ $_4thoctet -eq 255 ]; then\n            if [ $num_octets -eq 2 ]; then\n                let _3rdoctet++\n                ip_prefix=$initial_ip_prefix\n                continue\n            else\n                #\n                # If the IP prefix had 3 octets and we exhausted all possible\n                # values of the 4th octet, then we have failed the search for\n                # free local IP within the given prefix.\n                #\n                return 1\n            fi\n        fi\n\n        #\n        # Happy path!\n        #\n        # Add this entry to MOUNTMAP while we have the MOUNTMAP lock.\n        # This is to avoid assigning same local ip to parallel mount requests\n        # for different endpoints.\n        # ensure_mountmap_exist will also create a matching iptable DNAT rule.\n        #\n        LOCAL_IP=$local_ip\n        ensure_mountmap_exist_nolock \"$nfs_host $LOCAL_IP $nfs_ip\"\n\n        return 0\n    done\n\n    # We will never reach here.\n}\n\n#\n# Get a local IP that is free to use. Set global variable LOCAL_IP if found.\n#\nget_free_local_ip()\n{\n    for ip_prefix in $IP_PREFIXES; do\n        vecho \"Trying IP prefix ${ip_prefix}.\"\n        if search_free_local_ip_with_prefix \"$ip_prefix\"; then\n            return 0\n        fi\n    done\n\n    #\n    # If the above loop is not able to find a free local IP using optimized way,\n    # do a linear search to get the free local IP.\n    #\n    vecho \"Falling back to linear search for free ip!\"\n    OPTIMIZE_GET_FREE_LOCAL_IP=false\n    for ip_prefix in $IP_PREFIXES; do\n        vecho \"Trying IP prefix ${ip_prefix}.\"\n        if search_free_local_ip_with_prefix \"$ip_prefix\"; then\n            return 0\n        fi\n    done\n\n    # If we come here we did not get a free address to use.\n    return 1\n}\n\n#\n# For the given AZNFS endpoint FQDN return a local IP that should proxy it.\n# If there is at least one mount to the same FQDN it MUST return the local IP\n# used for that, else assign a new free local IP.\n#\nget_local_ip_for_fqdn()\n{\n        local fqdn=$1\n        local mountmap_entry=$(grep -m1 \"^${fqdn} \" $MOUNTMAP)\n        # One local ip per fqdn, so return existing one if already present.\n        IFS=\" \" read _ local_ip _ <<< \"$mountmap_entry\"\n\n        if [ -n \"$local_ip\" ]; then\n            LOCAL_IP=$local_ip\n\n            #\n            # Ask aznfswatchdog to stay away while we are using this proxy IP.\n            # This is similar to holding a timed lease, we can safely use this\n            # proxy IP w/o worrying about aznfswatchdog deleting it for 5 minutes.\n            #\n            touch_mountmap\n\n            #\n            # This is not really needed since iptable entry must also be present,\n            # but it's always better to ensure MOUNTMAP and iptable entries are\n            # in sync.\n            #\n            ensure_iptable_entry $local_ip $nfs_ip\n            return 0\n        fi\n\n        #\n        # First mount of an account on this client.\n        #\n        get_free_local_ip\n}\n\n#\n# Parse mount options from the mount command executed by the user.\n#\nparse_arguments()\n{\n    # Skip share and mountdir.\n    shift\n    shift\n    local next_arg_is_mount_options=false\n\n    OPTIONS=\n    MOUNT_OPTIONS=\n\n    for arg in $*; do\n        if [ \"$arg\" == \"-o\" ]; then\n            next_arg_is_mount_options=true\n            continue\n        fi\n\n        if $next_arg_is_mount_options; then\n            MOUNT_OPTIONS=$arg\n            next_arg_is_mount_options=false\n        else\n            OPTIONS=\"$OPTIONS $arg\"\n        fi\n    done\n}\n\n#\n# Ensure aznfswatchdog service is running, if not bail out with an appropriate\n# error.\n#\nensure_aznfswatchdog()\n{\n    if ! systemctl is-active --quiet aznfswatchdog; then\n        eecho \"aznfswatchdog service not running!\"\n        pecho \"Start the aznfswatchdog service using 'systemctl start aznfswatchdog' and try again.\"\n        pecho \"If the problem persists, contact Microsoft support.\"\n        return 1\n    fi\n}\n\n# [account.blob.core.windows.net:/account/container /mnt/aznfs -o rw,tcp,nolock,nconnect=16]\nvecho \"Got arguments: [$*]\"\n\n# Check if aznfswatchdog service is running.\nif ! ensure_aznfswatchdog; then\n    exit 1\nfi\n\n# MOUNTMAP file must have been created by aznfswatchdog service.\nif [ ! -f \"$MOUNTMAP\" ]; then\n    eecho \"[FATAL] ${MOUNTMAP} not found!\"\n    pecho \"Try restarting the aznfswatchdog service using 'systemctl start aznfswatchdog' and then retry the mount command.\"\n    pecho \"If the problem persists, contact Microsoft support.\"\n    exit 1\nfi\n\nnfs_host=$(get_host_from_share \"$1\")\nif [ $? -ne 0 ]; then\n    echo \"$nfs_host\"\n    exit 1\nfi\n\nif ! is_valid_blob_fqdn \"$nfs_host\"; then\n    eecho \"Not a valid Azure Blob NFS endpoint: ${nfs_host}!\"\n    eecho \"Must be of the form 'account.blob.core.windows.net'!\"\n    exit 1\nfi\n\nnfs_ip=$(resolve_ipv4 \"$nfs_host\")\nif [ $? -ne 0 ]; then\n    echo \"$nfs_ip\"\n    eecho \"Cannot resolve IP address for ${nfs_host}!\"\n    exit 1\nfi\n\nnfs_dir=$(get_dir_from_share \"$1\")\nif [ $? -ne 0 ]; then\n    echo \"$nfs_dir\"\n    exit 1\nfi\n\nif [ -z \"$nfs_dir\" ]; then\n    eecho \"Bad share name: ${1}!\"\n    eecho \"Share to be mounted must be of the form 'account.blob.core.windows.net:/account/container'!\"\n    exit 1\nfi\n\nmount_point=\"$2\"\n\nOPTIONS=\nMOUNT_OPTIONS=\n\nparse_arguments $*\n\n#\n# Check azure nconnect flag.\n#\nif [ \"$AZNFS_CHECK_AZURE_NCONNECT\" == \"1\" ]; then\n    if ! check_nconnect; then\n        eecho \"Mount failed!\"\n        exit 1\n    fi\nfi\n\n#\n# Fix MOUNT_OPTIONS if needed.\n#\nif [ \"$AZNFS_FIX_MOUNT_OPTIONS\" == \"1\" ]; then\n    fix_mount_options\nfi\n\n#\n# Get proxy IP to use for this nfs_ip.\n# It'll ensure an appropriate entry is added to MOUNTMAP if not already added,\n# and an appropriate iptable DNAT rule is added.\n#\nexec {fd}<$MOUNTMAP\nflock -e $fd\n#\n# With the lock held first check if adding a new mountmap entry for this account will\n# cause \"accounts mounted on one client\" to exceed the limit.\n#\nif check_account_count; then\n    get_local_ip_for_fqdn $nfs_host\n    ret=$?\n    account_limit_exceeded=0\nelse\n    account_limit_exceeded=1\nfi\nflock -u $fd\nexec {fd}<&-\n\nif [ \"$account_limit_exceeded\" == \"1\" ]; then\n    eecho \"Mounts to target IP $nfs_ip ($nfs_host) already at max limit ($MAX_ACCOUNTS_MOUNTABLE_FROM_SINGLE_TENANT)!\"\n    eecho \"Mount failed!\"\n    exit 1\nfi\n\nif [ $ret -ne 0 ]; then\n    if [ -z \"$AZNFS_IP_PREFIXES\" ]; then\n        eecho \"Could not find a free local IP to use for aznfs using DEFAULT_AZNFS_IP_PREFIXES=${DEFAULT_AZNFS_IP_PREFIXES}!\"\n        eecho \"Set AZNFS_IP_PREFIXES env variable correctly to provide free addresses for use by aznfs!\"\n    else\n        eecho \"Could not find a free local IP to use for aznfs using AZNFS_IP_PREFIXES=${AZNFS_IP_PREFIXES}!\"\n        eecho \"Ensure AZNFS_IP_PREFIXES env variable is set properly!\"\n    fi\n    exit 1\nfi\n\nvecho \"nfs_host=[$nfs_host], nfs_ip=[$nfs_ip], nfs_dir=[$nfs_dir], mount_point=[$mount_point], options=[$OPTIONS], mount_options=[$MOUNT_OPTIONS], local_ip=[$LOCAL_IP].\"\n\n#\n# AZNFS uses fixed port 2048 for mount and nfs.\n# Avoid portmap calls by default.\n#\nif [ -z \"$AZNFS_PMAP_PROBE\" -o \"$AZNFS_PMAP_PROBE\" == \"0\" ]; then\n    matchstr=\"\\<port\\>=\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,port=$AZNFS_PORT\"\n    fi\n    matchstr=\"\\<mountport\\>=\"\n    if ! [[ \"$MOUNT_OPTIONS\" =~ $matchstr ]]; then\n        MOUNT_OPTIONS=\"$MOUNT_OPTIONS,mountport=$AZNFS_PORT\"\n    fi\n    MOUNT_OPTIONS=$(echo \"$MOUNT_OPTIONS\" | sed \"s/^,//g\")\nfi\n\n# Do the actual mount.\nmount_output=$(mount -t nfs $OPTIONS -o \"$MOUNT_OPTIONS\" \"${LOCAL_IP}:${nfs_dir}\" \"$mount_point\" 2>&1)\nmount_status=$?\n\nif [ -n \"$mount_output\" ]; then\n    pecho \"$mount_output\"\nfi\n\nif [ $mount_status -ne 0 ]; then\n    eecho \"Mount failed!\"\n    #\n    # Don't bother clearing up the mountmap and/or iptable rule, aznfswatchdog\n    # will do it if it's unused (this mount was the one to create it).\n    #\n    exit 1\nfi\n\nvecho \"Mount completed: ${nfs_host}:${nfs_dir} on $mount_point using proxy IP $LOCAL_IP and endpoint IP $nfs_ip\"\n", "num_lines": 744}
{"repo_name": "AzSwaggerSpecsTestClone", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# From https://www.microsoft.com/net/download/linux-package-manager/ubuntu14-04/sdk-2.0.0\n\nwget -q https://packages.microsoft.com/config/ubuntu/14.04/packages-microsoft-prod.deb\nsudo dpkg -i packages-microsoft-prod.deb\nsudo apt-get install apt-transport-https -y\nsudo apt-get update\nsudo apt-get install dotnet-sdk-2.0.0 -y", "num_lines": 9}
{"repo_name": "AzSwaggerSpecsTestClone", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\npython -c \"import os; print('\\n'.join(v for v in os.environ.keys() if v.startswith('TRAVIS') or v.startswith('NODE')))\" > /tmp/env_file\ndocker pull azuresdk/swagger-to-sdk\ndocker run --rm --env-file /tmp/env_file -e GH_TOKEN -v $PWD:/git-restapi/ azuresdk/swagger-to-sdk \"$@\"\n", "num_lines": 6}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n## Cleanup packer SSH key and machine ID generated for this boot\nrm /root/.ssh/authorized_keys\nrm /home/packer/.ssh/authorized_keys\nrm /etc/machine-id\ntouch /etc/machine-id\n", "num_lines": 8}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\ncalico_release_tag=\"v3.1.3\"\ncni_plugins_release_tag=\"v0.7.1\"\n\n# Download CNI networking components\nwget -q --show-progress --https-only --timestamping \\\n\t\"https://github.com/projectcalico/cni-plugin/releases/download/${calico_release_tag}/calico\" \\\n\t\"https://github.com/projectcalico/cni-plugin/releases/download/${calico_release_tag}/calico-ipam\" \\\n\t\"https://github.com/containernetworking/plugins/releases/download/${cni_plugins_release_tag}/cni-plugins-amd64-${cni_plugins_release_tag}.tgz\"\n\n# Create CNI conf and bin directories\nmkdir -p \\\n  /etc/cni/net.d \\\n  /opt/cni/bin\n\n# Install CNI\ntar -xvf cni-plugins-amd64-${cni_plugins_release_tag}.tgz -C /opt/cni/bin/\nmv calico* /opt/cni/bin\n\n\n\n\n", "num_lines": 24}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\nkubernetes_release_tag=\"v1.10.4\"\n\nexport DEBIAN_FRONTEND=noninteractive\napt_flags=(-o \"Dpkg::Options::=--force-confnew\" -qy)\n\napt-get update -q\napt-get upgrade \"${apt_flags[@]}\"\n\napt-get install \"${apt_flags[@]}\" conntrack ipset socat jq traceroute ca-certificates\n", "num_lines": 12}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n# export DEBIAN_FRONTEND=noninteractive\n# apt_flags=(-o \"Dpkg::Options::=--force-confnew\" -qy)\n\n# mkdir /etc/docker\n# mv $HOME/daemon.json /etc/docker/daemon.json\n# apt-get install \"${apt_flags[@]}\" docker.io\n\nwget -q --show-progress --https-only --timestamping \\\n\"https://storage.googleapis.com/cri-containerd-release/cri-containerd-1.1.0.linux-amd64.tar.gz\"\nsudo tar -xvf cri-containerd-1.1.0.linux-amd64.tar.gz -C /\n\n\n", "num_lines": 15}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\nETCD_VER=v3.3.8\n\ngroupadd --system etcd\nuseradd --home-dir \"/var/lib/etcd\" --system \\\n  --shell /bin/false \\\n  -g etcd etcd\n\nmkdir -p /etc/etcd\nchown etcd:etcd /etc/etcd\nmkdir -p /var/lib/etcd\nchown etcd:etcd /var/lib/etcd\n\nrm -rf /tmp/etcd && mkdir -p /tmp/etcd\ncurl -L https://github.com/coreos/etcd/releases/download/${ETCD_VER}/etcd-${ETCD_VER}-linux-amd64.tar.gz -o /tmp/etcd-${ETCD_VER}-linux-amd64.tar.gz\ntar xzvf /tmp/etcd-${ETCD_VER}-linux-amd64.tar.gz -C /tmp/etcd --strip-components=1\ncp /tmp/etcd/etcd /usr/bin/etcd\ncp /tmp/etcd/etcdctl /usr/bin/etcdctl\n", "num_lines": 19}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\nkubernetes_release_tag=\"v1.11.0\"\n\n# Download the official Kubernetes release binaries\nwget -q --show-progress --https-only --timestamping \\\n  \"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kube-apiserver\" \\\n  \"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kube-controller-manager\" \\\n  \"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kube-scheduler\" \\\n\t\"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kube-proxy\" \\\n\t\"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kubelet\" \\\n  \"https://storage.googleapis.com/kubernetes-release/release/${kubernetes_release_tag}/bin/linux/amd64/kubectl\"\n\n# Install the Kubernetes binaries\nchmod +x kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy kubectl\nmv kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy kubectl /usr/local/bin/\n\n## Save release version, so that we can call `kubeadm init --use-kubernetes-version=\"$(cat /etc/kubernetes_community_vhd_version)` and ensure we get the same version\necho \"${kubernetes_release_tag}\" > /etc/kubernetes_community_vhd_version\n", "num_lines": 20}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eu\n\n# create SSL dirs\nmkdir -p /etc/kubernetes/ssl\nmkdir -p /etc/kubernetes/manifests\nmkdir -p /var/lib/kubelet/pki/\n\n# copy TLS certs\nmv /home/ubuntu/{ca,ca-key,kube-apiserver,kube-apiserver-key}.pem /etc/kubernetes/ssl/.\nmv kubelet{.crt,.key} /var/lib/kubelet/pki/\n\n# reinitialize daemons and start etcd + kube components\nsudo systemctl daemon-reload\nsudo systemctl enable kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy\nsudo systemctl start kube-apiserver kube-controller-manager kube-scheduler kubelet kube-proxy\n", "num_lines": 16}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -eux\n\n# create SSL dirs\nmkdir -p /etc/kubernetes/ssl\nmkdir -p /etc/etcd/ssl\n\n# copy TLS certs\ncp /home/ubuntu/{ca,ca-key,kube-apiserver,kube-apiserver-key}.pem /etc/etcd/ssl/.\ncp /home/ubuntu/{ca,ca-key,kube-apiserver,kube-apiserver-key}.pem /etc/kubernetes/ssl/.\nrm /home/ubuntu/*.pem\n\nsystemctl enable etcd.service\nsystemctl start etcd.service\n\nmkdir -p /etc/systemd/system/etcd.service.d\n\ncat <<EOF > /etc/systemd/system/etcd.service.d/local.conf\n[Service]\nEnvironment=\"ETCD_INITIAL_CLUSTER_STATE=existing\"\nEOF\n\nsystemctl daemon-reload\n", "num_lines": 23}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ux\n\nKUBE_API_INTERNAL_FQDN=$1\nBOOTSTRAP_TOKEN=$2\nHOSTNAME=$3\n\n# create SSL dirs\nmkdir -p /etc/kubernetes/ssl\nmkdir -p /var/lib/kubelet/pki\nmkdir -p /var/lib/kube-proxy/pki\n\n# copy TLS certs\ncp /home/ubuntu/ca.pem /etc/kubernetes/ssl/.\ncp /home/ubuntu/kubelet* /var/lib/kubelet/pki\ncp /home/ubuntu/kube-proxy* /var/lib/kube-proxy/pki\nrm /home/ubuntu/*{.pem,.crt,.key}\n\n## Setup kubelet\nsudo kubectl config set-cluster kubernetes \\\n  --certificate-authority=/etc/kubernetes/ssl/ca.pem \\\n  --embed-certs=true \\\n  --server=https://${KUBE_API_INTERNAL_FQDN}:6443 \\\n\t--kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf\n\nsudo kubectl config set-credentials \\\n  tls-bootstrap-token-user --token=${BOOTSTRAP_TOKEN} \\\n  --user=tls-bootstrap-token-user \\\n  --kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf\n\n\nsudo kubectl config set-context default \\\n  --cluster=kubernetes \\\n  --user=tls-bootstrap-token-user \\\n  --kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf\n\nsudo kubectl config use-context default --kubeconfig=/etc/kubernetes/bootstrap-kubelet.conf\n\n## Setup kube-proxy\nkubectl config set-cluster kubernetes \\\n  --certificate-authority=/etc/kubernetes/ssl/ca.pem   --embed-certs=true \\\n\t--server=https://${KUBE_API_INTERNAL_FQDN}:6443 \\\n\t--kubeconfig=/var/lib/kube-proxy/kube-proxy.kubeconfig\n\nkubectl config set-credentials kube-proxy \\\n  --client-certificate=/var/lib/kube-proxy/pki/kube-proxy.crt \\\n\t--client-key=/var/lib/kube-proxy/pki/kube-proxy.key \\\n\t--embed-certs=true \\\n\t--kubeconfig=/var/lib/kube-proxy/kube-proxy.kubeconfig\n\nkubectl config set-context default \\\n  --cluster=kubernetes \\\n\t--user=kube-proxy \\\n\t--kubeconfig=/var/lib/kube-proxy/kube-proxy.kubeconfig\n\nkubectl config use-context default --kubeconfig=/var/lib/kube-proxy/kube-proxy.kubeconfig\n\n# enable IP forwarding\nsudo sysctl -w net.ipv4.ip_forward=1\n\n# reinitialize daemons and start kube components\nsudo systemctl enable kubelet kube-proxy\nsudo systemctl start kubelet kube-proxy\n", "num_lines": 63}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -x\n\nSECRETS_DIR=$PWD/.secrets/${CLUSTER_NAME}\nCFSSL_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n\ncfssl gencert -ca=$SECRETS_DIR/ca.pem \\\n    -ca-key=$SECRETS_DIR/ca-key.pem \\\n    -config=$CFSSL_DIR/ca-config.json \\\n    -profile=kubernetes $CFSSL_DIR/admin-csr.json | cfssljson -bare $SECRETS_DIR/admin\n", "num_lines": 12}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -x\n\nSECRETS_DIR=$PWD/.secrets/${CLUSTER_NAME}\nCFSSL_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n\ncfssl gencert -ca=$SECRETS_DIR/ca.pem \\\n    -ca-key=$SECRETS_DIR/ca-key.pem \\\n    -config=$CFSSL_DIR/ca-config.json \\\n\t-hostname=etcd1.${INTERNAL_TLD},etcd2.${INTERNAL_TLD},etcd3.${INTERNAL_TLD},${ETCD_IPS},${MASTER_IPS},controller1.${INTERNAL_TLD},controller2.${INTERNAL_TLD},controller3.${INTERNAL_TLD},${KUBE_API_PUBLIC_FQDN},${KUBE_API_INTERNAL_IP},10.0.0.1,127.0.0.1,${KUBE_API_INTERNAL_FQDN},kubernetes.default \\\n    -profile=kubernetes $CFSSL_DIR/kube-apiserver-csr.json | cfssljson -bare $SECRETS_DIR/kube-apiserver\n", "num_lines": 13}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -x\n\nSECRETS_DIR=$PWD/.secrets/${CLUSTER_NAME}\nCFSSL_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n\ncfssl gencert -initca $CFSSL_DIR/ca-csr.json | cfssljson -bare $SECRETS_DIR/ca -\n", "num_lines": 9}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -x\n\nSECRETS_DIR=$PWD/.secrets/${CLUSTER_NAME}\nCFSSL_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n\ninstance=$1\n\nCSR=$(cat <<EOF\n{\n  \"CN\": \"system:node:${instance}\",\n  \"key\": {\n    \"algo\": \"rsa\",\n    \"size\": 2048\n  },\n  \"names\": [\n    {\n      \"C\": \"US\",\n      \"L\": \"San Francisco\",\n      \"O\": \"system:nodes\",\n      \"OU\": \"ACS\",\n      \"ST\": \"CA\"\n    }\n  ]\n}\nEOF\n)\n\necho \"$CSR\" > $SECRETS_DIR/$instance-csr.json\n\ncfssl gencert -ca=$SECRETS_DIR/ca.pem \\\n    -ca-key=$SECRETS_DIR/ca-key.pem \\\n    -config=$CFSSL_DIR/ca-config.json \\\n\t\t-hostname=${instance} \\\n    -profile=kubernetes \\\n\t\t $SECRETS_DIR/$instance-csr.json | cfssljson -bare $SECRETS_DIR/${instance}\n\n", "num_lines": 39}
{"repo_name": "aztack", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nset -x\n\nSECRETS_DIR=$PWD/.secrets/${CLUSTER_NAME}\nCFSSL_DIR=$(dirname \"${BASH_SOURCE[0]}\")\n\ncfssl gencert -ca=$SECRETS_DIR/ca.pem \\\n    -ca-key=$SECRETS_DIR/ca-key.pem \\\n    -config=$CFSSL_DIR/ca-config.json \\\n    -profile=kubernetes $CFSSL_DIR/kube-proxy-csr.json | cfssljson -bare $SECRETS_DIR/kube-proxy\n", "num_lines": 12}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nsed -i 's/mirrorlist/#mirrorlist/g' /etc/yum.repos.d/CentOS-*\nsed -i 's|#baseurl=http://mirror.centos.org|baseurl=http://vault.centos.org|g' /etc/yum.repos.d/CentOS-*\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\ndnf install -y https://packages.microsoft.com/config/centos/8/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 22}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/debian/11/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 21}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/debian/10/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 21}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/34/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 24}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/35/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 24}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\n# To accelarate syncing the repo metadatas\nrm -f /etc/yum.repos.d/*\n\ndnf install -y https://packages.microsoft.com/config/fedora/36/packages-microsoft-prod.rpm\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    # See: https://access.redhat.com/solutions/2779441\n    dnf check-update --refresh || [[ $? == 100 ]]  \n    dnf install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 24}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\napt-add-repository https://packages.microsoft.com/ubuntu/18.04/multiarch/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 21}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc > /etc/apt/trusted.gpg.d/microsoft.asc\napt-add-repository https://packages.microsoft.com/ubuntu/20.04/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n(( count <= total ))\n", "num_lines": 21}
{"repo_name": "aztfexport", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nversion=${1:?\"version not specified\"}\n\napt-get update\napt-get install -y curl software-properties-common gpg\ncurl -sSL https://packages.microsoft.com/keys/microsoft.asc > /etc/apt/trusted.gpg.d/microsoft.asc\napt-add-repository https://packages.microsoft.com/ubuntu/22.04/prod\n\ntotal=60\ncount=1\nwhile ((count <= total)); do\n    echo \"Try ($count/$total)\"\n    apt-get update\n    apt-get install -y aztfexport && grep $version <(aztfexport -v) && break\n    sleep 1m\n    ((count++))\ndone\n", "num_lines": 20}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Installing dependencies...\" &&\npip install --force-reinstall --upgrade --user pyyaml==3.12 azure==3.0.0 azure-cli-core==2.0.30 msrestazure==0.4.25 > /dev/null 2>&1 &&\necho \"Finished installing dependencies.\" &&\necho \"Getting account setup script...\" &&\nwget -q https://raw.githubusercontent.com/Azure/aztk/v0.10.3/account_setup.py -O account_setup.py &&\nchmod 755 account_setup.py &&\necho \"Finished getting account setup script.\" &&\necho \"Running account setup script...\" &&\npython3 account_setup.py\n", "num_lines": 12}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This file is the entry point of the docker container.\n\nset -e\nsource ~/.bashrc\necho \"Initializing spark container\"\n\naztk_dir=$AZTK_WORKING_DIR/aztk\n\n# -----------------------\n# Preload jupyter samples\n# -----------------------\nmkdir -p /mnt/samples\n\n# add all files from 'jupyter-samples' to container folder '/pyspark/samples'\nfor file in $(dirname $0)/jupyter-samples/*; do\n    cp $file /mnt/samples\ndone\n\n# ----------------------------\n# Run aztk setup python scripts\n# ----------------------------\n# setup docker container\necho \"Starting setup using Docker\"\n\nexport PYTHONPATH=$PYTHONPATH:$AZTK_WORKING_DIR\necho 'export PYTHONPATH=$PYTHONPATH:$AZTK_WORKING_DIR' >> ~/.bashrc\n\necho \"Running main.py script\"\n$AZTK_WORKING_DIR/.aztk-env/.venv/bin/python $(dirname $0)/main.py setup-spark-container\n\n# sleep to keep container running\nwhile true; do sleep 1; done\n", "num_lines": 35}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Entry point for the start task. It will install all dependencies and start docker.\n# Usage:\n# setup_host.sh [container_name] [docker_repo_name] [docker_run_options]\nset -e\n\nexport AZTK_WORKING_DIR=/mnt/batch/tasks/startup/wd\nexport PYTHONUNBUFFERED=TRUE\n\ncontainer_name=$1\ndocker_repo_name=$2\ndocker_run_options=$3\n\ninstall_prerequisites () {\n    echo \"Installing pre-reqs\"\n\n    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n    add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\n\n    packages=(\n        apt-transport-https\n        curl\n        ca-certificates\n        software-properties-common\n        python3-pip\n        python3-venv\n        docker-ce\n    )\n\n    echo \"running apt-get install -y --no-install-recommends \\\"${packages[@]}\\\"\"\n    apt-get -y update &&\n    apt-get install -y --no-install-recommends \"${packages[@]}\"\n\n    if [ $AZTK_GPU_ENABLED == \"true\" ]; then\n        apt-get install -y nvidia-384 nvidia-modprobe\n        wget -P /tmp https://github.com/NVIDIA/nvidia-docker/releases/download/v1.0.1/nvidia-docker_1.0.1-1_amd64.deb\n        sudo dpkg -i /tmp/nvidia-docker*.deb && rm /tmp/nvidia-docker*.deb\n    fi\n    echo \"Finished installing pre-reqs\"\n}\n\ninstall_docker_compose () {\n    echo \"Installing Docker-Compose\"\n    url=https://github.com/docker/compose/releases/download/1.19.0/docker-compose-`uname -s`-`uname -m`\n    for i in {1..5}; do\n        sudo curl -L $url -o /usr/local/bin/docker-compose && break ||\n        echo \"ERROR: failed to download docker-compose ... retrying in $($i**2) seconds\" &&\n        sleep $i**2;\n    done\n    sudo chmod +x /usr/local/bin/docker-compose\n    echo \"Finished installing Docker-Compose\"\n}\n\npull_docker_container () {\n    echo \"Pulling $docker_repo_name\"\n\n    if [ -z \"$DOCKER_USERNAME\" ]; then\n        echo \"No Credentials provided. No need to login to dockerhub\"\n    else\n        echo \"Docker credentials provided. Login in.\"\n        docker login $DOCKER_ENDPOINT --username $DOCKER_USERNAME --password $DOCKER_PASSWORD\n    fi\n\n    for i in {1..5}; do\n        docker pull $docker_repo_name && break ||\n        echo \"ERROR: docker pull $docker_repo_name failed ... retrying after $($i**2) seconds\" &&\n        sleep $i**2;\n    done\n    echo \"Finished pulling $docker_repo_name\"\n}\n\ninstall_python_dependencies () {\n    echo \"Installing python dependencies\"\n    pipenv install --python /usr/bin/python3.5m --ignore-pipfile\n    pip --version\n    echo \"Finished installing python dependencies\"\n}\n\nrun_docker_container () {\n    echo \"Running docker container\"\n\n    # If the container already exists just restart. Otherwise create it\n    if [ \"$(docker ps -a -q -f name=$container_name)\" ]; then\n        echo \"Docker container is already setup. Restarting it.\"\n        docker restart $container_name\n    else\n        echo \"Creating docker container.\"\n\n        echo \"Running setup python script\"\n        $AZTK_WORKING_DIR/.aztk-env/.venv/bin/python $(dirname $0)/main.py setup-node $docker_repo_name \"$docker_run_options\"\n\n        # wait until container is running\n        until [ \"`/usr/bin/docker inspect -f {{.State.Running}} $container_name`\"==\"true\" ]; do\n            sleep 0.1;\n        done;\n\n        # wait until container setup is complete\n        echo \"Waiting for spark docker container to setup.\"\n        docker exec spark /bin/bash -c '$AZTK_WORKING_DIR/.aztk-env/.venv/bin/python $AZTK_WORKING_DIR/aztk/node_scripts/wait_until_setup_complete.py'\n\n        # Setup symbolic link for the docker logs\n        docker_log=$(docker inspect --format='{{.LogPath}}' $container_name)\n        mkdir -p $AZ_BATCH_TASK_WORKING_DIR/logs\n        ln -s $docker_log $AZ_BATCH_TASK_WORKING_DIR/logs/docker.log\n    fi\n    echo \"Finished running docker container\"\n}\n\n\nmain () {\n    time(\n        install_prerequisites\n    ) 2>&1\n\n    # set hostname in /etc/hosts if dns cannot resolve\n    if ! host $HOSTNAME ; then\n        echo $(hostname -I | awk '{print $1}') $HOSTNAME >> /etc/hosts\n    fi\n\n    time(\n        install_docker_compose\n    ) 2>&1\n\n    time(\n        pull_docker_container\n    ) 2>&1\n\n    # Unzip resource files and set permissions\n    chmod 777 $AZTK_WORKING_DIR/aztk/node_scripts/docker_main.sh\n\n    # Check docker is running\n    docker info > /dev/null 2>&1\n    if [ $? -ne 0 ]; then\n    echo \"UNKNOWN - Unable to talk to the docker daemon\"\n    exit 3\n    fi\n\n    echo \"Node python version:\"\n    python3 --version\n\n    # set up aztk python environment\n    export LC_ALL=C.UTF-8\n    export LANG=C.UTF-8\n    # pin pipenv dependencies (and transitive dependencies) since pipenv does not\n    python3 -m pip install setuptools==\"42.0.2\"\n    python3 -m pip install zipp==\"1.1.0\"\n    python3 -m pip install virtualenv==\"20.0.0\"\n    # ensure these packages (pip, pipenv) are compatibile before upgrading\n    python3 -m pip install pip==\"18.0\" pipenv==\"2018.7.1\"\n    mkdir -p $AZTK_WORKING_DIR/.aztk-env\n    cp $AZTK_WORKING_DIR/aztk/node_scripts/Pipfile $AZTK_WORKING_DIR/.aztk-env\n    cp $AZTK_WORKING_DIR/aztk/node_scripts/Pipfile.lock $AZTK_WORKING_DIR/.aztk-env\n    cd $AZTK_WORKING_DIR/.aztk-env\n    export PIPENV_VENV_IN_PROJECT=true\n\n    time(\n        install_python_dependencies\n    ) 2>&1\n\n    export PYTHONPATH=$PYTHONPATH:$AZTK_WORKING_DIR\n\n    time(\n        run_docker_container\n    ) 2>&1\n}\n\napt-mark hold $(uname -r)\nmain\napt-mark unhold $(uname -r)\n", "num_lines": 171}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# install dependencies\napt update\napt install -y ssh rsync\n\n# configure and run ssh\ncat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys\nchmod 600 /root/.ssh/id_rsa\nchmod 700 /root/.ssh/authorized_keys\nmkdir /var/run/sshd\necho 'root:screencast' | chpasswd\nsed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config\nsed -i 's/Port 22/Port 3022/' /etc/ssh/sshd_config\nsed -i 's/#   Port 22/  Port 3022/' /etc/ssh/ssh_config\nsed -i 's/#   StrictHostKeyChecking ask/StrictHostKeyChecking no/' /etc/ssh/ssh_config\n\n# SSH login fix. Otherwise user is kicked off after login\nsed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd\n\n/usr/sbin/sshd\n\n# install and configure hadoop\nmkdir /home/hadoop-2.8.3\ncurl http://apache.claz.org/hadoop/common/hadoop-2.8.3/hadoop-2.8.3.tar.gz | tar -xz -C /home\n\nexport HADOOP_HOME=/home/hadoop-2.8.3\necho 'export HADOOP_HOME=/home/hadoop-2.8.3' >> ~/.bashrc\n\nexport HADOOP_CONF_DIR=/home/hadoop-2.8.3/etc/hadoop\necho 'export HADOOP_CONF_DIR=/home/hadoop-2.8.3/etc/hadoop' >> ~/.bashrc\n\nexport PATH=$PATH:$HADOOP_HOME/bin\necho 'export PATH=$PATH:$HADOOP_HOME/bin' >> ~/.bashrc\n\n# Create a directory for the hadoop file system\nmkdir -p /batch/hadoop\n\necho '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n<configuration>\n    <property>\n        <name>fs.defaultFS</name>\n        <value>hdfs://'$AZTK_MASTER_IP':8020</value>\n    </property>\n</configuration>' > $HADOOP_HOME/etc/hadoop/core-site.xml\n\necho '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n    <configuration>\n        <property>\n            <name>dfs.namenode.datanode.registration.ip-hostname-check</name>\n            <value>false</value>\n        </property>\n        <property>\n            <name>dfs.datanode.data.dir</name>\n            <value>file:///batch/hadoop</value>\n        </property>\n    </configuration>' > $HADOOP_HOME/etc/hadoop/hdfs-site.xml\n\n# run HDFS\nif [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    echo 'starting namenode and datanode'\n    hdfs namenode -format\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start namenode\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start datanode\nelse\n    echo 'starting datanode - namenode at ' $AZTK_MASTER_IP ':8020'\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start datanode\nfi\n", "num_lines": 71}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\neval $COMMAND $@\n", "num_lines": 4}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This custom script only works on images where jupyter is pre-installed on the Docker image\n#\n# This custom script has been tested to work on the following docker images:\n#  - aztk/python:spark2.2.0-python3.6.2-base\n#  - aztk/python:spark2.2.0-python3.6.2-gpu\n#  - aztk/python:spark2.1.0-python3.6.2-base\n#  - aztk/python:spark2.1.0-python3.6.2-gpu\n\necho \"Is master: $AZTK_IS_MASTER\"\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    pip install jupyter --upgrade\n    pip install notebook --upgrade\n    \n    PYSPARK_DRIVER_PYTHON=\"/opt/conda/bin/jupyter\"\n    JUPYTER_KERNELS=\"/opt/conda/share/jupyter/kernels\"\n\n    # disable password/token on jupyter notebook\n    jupyter notebook --generate-config --allow-root\n    JUPYTER_CONFIG='/root/.jupyter/jupyter_notebook_config.py'\n    echo >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.token=\"\"' >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.password=\"\"' >> $JUPYTER_CONFIG\n\n    # get master ip\n    MASTER_IP=$(hostname -i)\n\n    # remove existing kernels\n    rm -rf $JUPYTER_KERNELS/*\n\n    # set up jupyter to use pyspark\n    mkdir $JUPYTER_KERNELS/pyspark\n    touch $JUPYTER_KERNELS/pyspark/kernel.json\n    cat << EOF > $JUPYTER_KERNELS/pyspark/kernel.json\n{\n    \"display_name\": \"PySpark\",\n    \"language\": \"python\",\n    \"argv\": [\n        \"python\",\n        \"-m\",\n        \"ipykernel\",\n        \"-f\",\n        \"{connection_file}\"\n    ],\n    \"env\": {\n        \"SPARK_HOME\": \"$SPARK_HOME\",\n        \"PYSPARK_PYTHON\": \"python\",\n        \"PYSPARK_SUBMIT_ARGS\": \"--master spark://$AZTK_MASTER_IP:7077 pyspark-shell\"\n    }\n}\nEOF\n\n    # start jupyter notebook from /mnt - this is where we recommend you put your azure files mount point as well\n    cd /mnt\n    (PYSPARK_DRIVER_PYTHON=$PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS=\"notebook --no-browser --port=8888 --allow-root\" pyspark &)\nfi\n\n\n", "num_lines": 61}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This custom script has been tested to work on the following docker images:\n#  - aztk/python:spark2.2.0-python3.6.2-base\n#  - aztk/python:spark2.2.0-python3.6.2-gpu\n#  - aztk/python:spark2.1.0-python3.6.2-base\n#  - aztk/python:spark2.1.0-python3.6.2-gpu\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    conda install -c conda-force jupyterlab\n\n    PYSPARK_DRIVER_PYTHON=\"/opt/conda/bin/jupyter\"\n    JUPYTER_KERNELS=\"/opt/conda/share/jupyter/kernels\"\n\n    # disable password/token on jupyter notebook\n    jupyter lab --generate-config --allow-root\n    JUPYTER_CONFIG='/root/.jupyter/jupyter_notebook_config.py'\n    echo >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.token=\"\"' >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.password=\"\"' >> $JUPYTER_CONFIG\n\n    # get master ip\n    MASTER_IP=$(hostname -i)\n\n    # remove existing kernels\n    rm -rf $JUPYTER_KERNELS/*\n\n    # set up jupyter to use pyspark\n    mkdir $JUPYTER_KERNELS/pyspark\n    touch $JUPYTER_KERNELS/pyspark/kernel.json\n    cat << EOF > $JUPYTER_KERNELS/pyspark/kernel.json\n{\n    \"display_name\": \"PySpark\",\n    \"language\": \"python\",\n    \"argv\": [\n        \"python\",\n        \"-m\",\n        \"ipykernel\",\n        \"-f\",\n        \"{connection_file}\"\n    ],\n    \"env\": {\n        \"SPARK_HOME\": \"$SPARK_HOME\",\n        \"PYSPARK_PYTHON\": \"python\",\n        \"PYSPARK_SUBMIT_ARGS\": \"--master spark://$MASTER_IP:7077 pyspark-shell\"\n    }\n}\nEOF\n\n    # start jupyter notebook from /mnt - this is where we recommend you put your azure files mount point as well\n    cd /mnt\n    (PYSPARK_DRIVER_PYTHON=$PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS=\"lab --no-browser --port=8889 --allow-root\" pyspark &)\nfi\n\n\n", "num_lines": 56}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get update &&\napt-get install -y libblas-dev liblapack-dev &&\nupdate-alternatives --config libblas.so.3\nupdate-alternatives --config liblapack.so.3\n\nexport NVBLAS_CONFIG_FILE=/usr/local/cuda/lib64/nvblas.conf\necho \"export NVBLAS_CONFIG_FILE=/usr/local/cuda/lib64/nvblas.conf\" >> ~/.bashrc\n\necho '# This is the configuration file to use NVBLAS Library\n# Setup the environment variable NVBLAS_CONFIG_FILE to specify your own config file.\n# By default, if NVBLAS_CONFIG_FILE is not defined, \n# NVBLAS Library will try to open the file \"nvblas.conf\" in its current directory\n# Example : NVBLAS_CONFIG_FILE  /home/cuda_user/my_nvblas.conf\n# The config file should have restricted write permissions accesses\n\n# Specify which output log file (default is stderr)\nNVBLAS_LOGFILE  /root/nvblas.log\n\n# Enable trace log of every intercepted BLAS calls\nNVBLAS_TRACE_LOG_ENABLED\n\n#Put here the CPU BLAS fallback Library of your choice\n#It is strongly advised to use full path to describe the location of the CPU Library\nNVBLAS_CPU_BLAS_LIB  /usr/lib/libblas.so\n\n# List of GPU devices Id to participate to the computation \n# Use ALL if you want all your GPUs to contribute\n# Use ALL0, if you want all your GPUs of the same type as device 0 to contribute\n# However, NVBLAS consider that all GPU have the same performance and PCI bandwidth\n# By default if no GPU are listed, only device 0 will be used\n\n#NVBLAS_GPU_LIST 0 2 4\n#NVBLAS_GPU_LIST ALL\nNVBLAS_GPU_LIST ALL0\n\n# Tile Dimension\nNVBLAS_TILE_DIM 2048\n\n# Autopin Memory\nNVBLAS_AUTOPIN_MEM_ENABLED\n\n#List of BLAS routines that are prevented from running on GPU (use for debugging purpose\n# The current list of BLAS routines supported by NVBLAS are\n# GEMM, SYRK, HERK, TRSM, TRMM, SYMM, HEMM, SYR2K, HER2K\n\n#NVBLAS_GPU_DISABLED_SGEMM \n#NVBLAS_GPU_DISABLED_DGEMM \n#NVBLAS_GPU_DISABLED_CGEMM \n#NVBLAS_GPU_DISABLED_ZGEMM \n\n# Computation can be optionally hybridized between CPU and GPU\n# By default, GPU-supported BLAS routines are ran fully on GPU\n# The option NVBLAS_CPU_RATIO_<BLAS_ROUTINE> give the ratio [0,1] \n# of the amount of computation that should be done on CPU\n# CAUTION : this option should be used wisely because it can actually\n# significantly reduced the overall performance if too much work is given to CPU\n\n#NVBLAS_CPU_RATIO_CGEMM 0.07' > $NVBLAS_CONFIG_FILE\n\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/libblas:/usr/local/cuda/lib64\necho \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/lib/libblas:/usr/local/cuda/lib64\" >> ~/.bashrc\nexport LD_PRELOAD=/usr/local/cuda/lib64/libnvblas.so\necho \"export LD_PRELOAD=/usr/local/cuda/lib64/libnvblas.so\" >> ~/.bashrc\n", "num_lines": 66}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get update &&\napt-get install -y libopenblas-base &&\nupdate-alternatives --config libblas.so.3\n", "num_lines": 5}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\ncd $DIR\n\nmkdir /etc/telegraf\ncp ./etc/telegraf.conf /etc/telegraf/telegraf.conf\n\necho \"Install telegraf\"\ncurl -sL https://repos.influxdata.com/influxdb.key | apt-key add -\nsource /etc/lsb-release\necho \"deb https://repos.influxdata.com/${DISTRIB_ID,,} ${DISTRIB_CODENAME} stable\" | tee /etc/apt/sources.list.d/influxdb.list\napt-get update && apt-get install telegraf\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    echo \"Create docker containers\"\n    sudo docker-compose up --no-start\n    echo \"Run the containers\"\n    sudo docker-compose start\nfi\n\necho \"Run telegraf\"\ntelegraf --config ./etc/telegraf.conf &\n", "num_lines": 23}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This custom script only works on images where rstudio server is pre-installed on the Docker image\n#\n# This custom script has been tested to work on the following docker images:\n#  - jiata/aztk-r:0.1.0-spark2.2.0-r3.4.1\n#  - jiata/aztk-r:0.1.0-spark2.1.0-r3.4.1\n#  - jiata/aztk-r:0.1.0-spark1.6.3-r3.4.1\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n\n    ## Download and install Rstudio Server\n    wget https://download2.rstudio.org/rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb\n    apt-get install -y --no-install-recommends gdebi-core\n    gdebi rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb --non-interactive\n    echo \"server-app-armor-enabled=0\" | tee -a /etc/rstudio/rserver.conf\n    rm rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb\n\n    ## Preparing default user for Rstudio Server\n    set -e\n    useradd -m -d /home/rstudio rstudio -g staff\n    echo rstudio:rstudio | chpasswd\n\n    rstudio-server start\n\nfi\n", "num_lines": 27}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Is master: $AZTK_IS_MASTER\"\necho \"Is worker: $AZTK_IS_WORKER\"\necho \"Master node ip: $AZTK_MASTER_IP\"\n", "num_lines": 6}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npython $AZTK_WORKING_DIR/plugins/spark_ui_proxy/spark_ui_proxy.py $1 $2 &\n", "num_lines": 3}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This plugin requires HDFS to be enabled and on the path\n\n# setup TensorFlowOnSpark\ngit clone https://github.com/yahoo/TensorFlowOnSpark.git\ncd TensorFlowOnSpark\nexport TFoS_HOME=$(pwd)\nexport TFoS_HOME=~/TensorFlowOnSpark >> ~/.bashrc\n\nif  [ \"$AZTK_GPU_ENABLED\" = \"true\" ]; then\n    pip install tensorflow-gpu\n    pip install tensorflowonspark\nelse\n    pip install tensorflow-cpu\n    pip install tensorflowonspark\nfi\n\n# add libhdfs.so to path\necho \"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$HADOOP_HOME/lib/native/libhdfs.so\" >> ~/.bashrc\n", "num_lines": 21}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n# This file is sourced when running various Spark programs.\n\n# Options read when launching programs locally with\n# ./bin/run-example or ./bin/spark-submit\n# - HADOOP_CONF_DIR, to point Spark towards Hadoop configuration files\n\n# Options read by executors and drivers running inside the cluster\n# - SPARK_LOCAL_DIRS, storage directories to use on this node for shuffle and RDD data\n\n# Options for the daemons used in the standalone deploy mode\n# - SPARK_MASTER_OPTS, to set config properties only for the master (e.g. \"-Dx=y\")\n# - SPARK_WORKER_CORES, to set the number of cores to use on this machine\n# - SPARK_WORKER_MEMORY, to set how much total memory workers have to give executors (e.g. 1000m, 2\n# - SPARK_WORKER_DIR, to set the working directory of worker processes\n# - SPARK_WORKER_OPTS, to set config properties only for the worker (e.g. \"-Dx=y\")\n# - SPARK_DAEMON_MEMORY, to allocate to the master, worker and history server themselves (default:\n# - SPARK_HISTORY_OPTS, to set config properties only for the history server (e.g. \"-Dx=y\")\n# - SPARK_SHUFFLE_OPTS, to set config properties only for the external shuffle service (e.g. \"-Dx=y\n# - SPARK_DAEMON_JAVA_OPTS, to set config properties for all daemons (e.g. \"-Dx=y\")\n\n# Generic options for the daemons used in the standalone deploy mode\n# - SPARK_CONF_DIR      Alternate conf dir. (Default: ${SPARK_HOME}/conf)\n# - SPARK_LOG_DIR       Where log files are stored.  (Default: ${SPARK_HOME}/logs)\n# - SPARK_PID_DIR       Where the pid file is stored. (Default: /tmp)\n# - SPARK_IDENT_STRING  A string representing this instance of spark. (Default: $USER)\n# - SPARK_NICENESS      The scheduling priority for daemons. (Default: 0)\n# - SPARK_NO_DAEMONIZE  Run the proposed command in the foreground. It will not output a PID file.\n", "num_lines": 47}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# install dependencies\napt update\napt install -y ssh rsync\n\n# configure and run ssh\ncat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys\nchmod 600 /root/.ssh/id_rsa\nchmod 700 /root/.ssh/authorized_keys\nmkdir /var/run/sshd\necho 'root:screencast' | chpasswd\nsed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config\nsed -i 's/Port 22/Port 3022/' /etc/ssh/sshd_config\nsed -i 's/#   Port 22/  Port 3022/' /etc/ssh/ssh_config\nsed -i 's/#   StrictHostKeyChecking ask/StrictHostKeyChecking no/' /etc/ssh/ssh_config\n\n# SSH login fix. Otherwise user is kicked off after login\nsed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd\n\n/usr/sbin/sshd\n\n# install and configure hadoop\nmkdir /home/hadoop-2.8.2\ncurl http://apache.claz.org/hadoop/common/hadoop-2.8.2/hadoop-2.8.2.tar.gz | tar -xz -C /home\n\nexport HADOOP_HOME=/home/hadoop-2.8.2\necho 'export HADOOP_HOME=/home/hadoop-2.8.2' >> ~/.bashrc\n\nexport HADOOP_CONF_DIR=/home/hadoop-2.8.2/etc/hadoop\necho 'export HADOOP_CONF_DIR=/home/hadoop-2.8.2/etc/hadoop' >> ~/.bashrc\n\nexport PATH=$PATH:$HADOOP_HOME/bin\necho 'export PATH=$PATH:$HADOOP_HOME/bin' >> ~/.bashrc\n\n# Create a directory for the hadoop file system\nmkdir -p /batch/hadoop\n\necho '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n<configuration>\n    <property>\n        <name>fs.defaultFS</name>\n        <value>hdfs://'$AZTK_MASTER_IP':8020</value>\n    </property>\n</configuration>' > $HADOOP_HOME/etc/hadoop/core-site.xml\n\necho '<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n    <?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>\n    <configuration>\n        <property>\n            <name>dfs.namenode.datanode.registration.ip-hostname-check</name>\n            <value>false</value>\n        </property>\n        <property>\n            <name>dfs.datanode.data.dir</name>\n            <value>file:///batch/hadoop</value>\n        </property>\n    </configuration>' > $HADOOP_HOME/etc/hadoop/hdfs-site.xml\n\n# run HDFS\nif [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    echo 'starting namenode and datanode'\n    hdfs namenode -format\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start namenode\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start datanode\nelse\n    echo 'starting datanode - namenode at ' $AZTK_MASTER_IP ':8020'\n    $HADOOP_HOME/sbin/hadoop-daemon.sh --config $HADOOP_CONF_DIR --script hdfs start datanode\nfi\n", "num_lines": 71}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This custom script only works on images where jupyter is pre-installed on the Docker image\n#\n# This custom script has been tested to work on the following docker images:\n#  - aztk/python:spark2.2.0-python3.6.2-base\n#  - aztk/python:spark2.2.0-python3.6.2-gpu\n#  - aztk/python:spark2.1.0-python3.6.2-base\n#  - aztk/python:spark2.1.0-python3.6.2-gpu\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    pip install jupyter --upgrade\n    pip install notebook --upgrade\n\n    PYSPARK_DRIVER_PYTHON=\"/opt/conda/bin/jupyter\"\n    JUPYTER_KERNELS=\"/opt/conda/share/jupyter/kernels\"\n\n    # disable password/token on jupyter notebook\n    jupyter notebook --generate-config --allow-root\n    JUPYTER_CONFIG='/root/.jupyter/jupyter_notebook_config.py'\n    echo >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.token=\"\"' >> $JUPYTER_CONFIG\n    echo -e 'c.NotebookApp.password=\"\"' >> $JUPYTER_CONFIG\n\n    # get master ip\n    MASTER_IP=$(hostname -i)\n\n    # remove existing kernels\n    rm -rf $JUPYTER_KERNELS/*\n\n    # set up jupyter to use pyspark\n    mkdir $JUPYTER_KERNELS/pyspark\n    touch $JUPYTER_KERNELS/pyspark/kernel.json\n    cat << EOF > $JUPYTER_KERNELS/pyspark/kernel.json\n{\n    \"display_name\": \"PySpark\",\n    \"language\": \"python\",\n    \"argv\": [\n        \"python\",\n        \"-m\",\n        \"ipykernel\",\n        \"-f\",\n        \"{connection_file}\"\n    ],\n    \"env\": {\n        \"SPARK_HOME\": \"$SPARK_HOME\",\n        \"PYSPARK_PYTHON\": \"python\",\n        \"PYSPARK_SUBMIT_ARGS\": \"--master spark://$AZTK_MASTER_IP:7077 pyspark-shell\"\n    }\n}\nEOF\n\n    # start jupyter notebook from /mnt - this is where we recommend you put your azure files mount point as well\n    cd /mnt\n    (PYSPARK_DRIVER_PYTHON=$PYSPARK_DRIVER_PYTHON PYSPARK_DRIVER_PYTHON_OPTS=\"notebook --no-browser --port=8888 --allow-root\" pyspark &)\nfi\n\n\n", "num_lines": 59}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This custom script only works on images where rstudio server is pre-installed on the Docker image\n#\n# This custom script has been tested to work on the following docker images:\n#  - jiata/aztk-r:0.1.0-spark2.2.0-r3.4.1\n#  - jiata/aztk-r:0.1.0-spark2.1.0-r3.4.1\n#  - jiata/aztk-r:0.1.0-spark1.6.3-r3.4.1\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n\n    ## Download and install Rstudio Server\n    wget https://download2.rstudio.org/rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb\n    gdebi rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb --non-interactive\n    echo \"server-app-armor-enabled=0\" | tee -a /etc/rstudio/rserver.conf\n    rm rstudio-server-$RSTUDIO_SERVER_VERSION-amd64.deb\n\n    ## Preparing default user for Rstudio Server\n    set -e\n    useradd -m -d /home/rstudio rstudio -g staff\n    echo rstudio:rstudio | chpasswd\n\n    rstudio-server start\n\nfi\n", "num_lines": 26}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Demo plugin. Not actually meant to be used.\n\nif  [ \"$AZTK_IS_MASTER\" = \"true\" ]; then\n    echo \"This is a custom script running on just the master!\"\nfi\n\nif  [ \"$AZTK_IS_WORKER\" = \"true\" ]; then\n    echo \"This is a custom script running on just the workers!\"\nfi\n\necho \"This is a custom script running all workers and the master!\"\n\n", "num_lines": 15}
{"repo_name": "aztk", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\n# setup docker to build on /mnt instead of /var/lib/docker\necho '{\n    \"graph\": \"/mnt\",\n    \"storage-driver\": \"overlay\"\n}' > /etc/docker/daemon.json\n\nservice docker restart\n\nmkdir -p out\n\n# base 1.6.3\ndocker build base/spark1.6.3/ --tag aztk/spark:v0.1.0-spark1.6.3-base > out/base-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-base\n\n# base 2.1.0\ndocker build base/spark2.1.0/ --tag aztk/spark:v0.1.0-spark2.1.0-base > out/base-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-base\n\n# base 2.2.0\ndocker build base/spark2.2.0/ --tag aztk/spark:v0.1.0-spark2.2.0-base > out/base-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-base\n\n# base 2.3.0\ndocker build base/spark2.3.0/ --tag aztk/spark:v0.1.0-spark2.3.0-base > out/base-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-base\n\n# miniconda-base 1.6.3\ndocker build miniconda/spark1.6.3/base/ --tag aztk/spark:v0.1.0-spark1.6.3-miniconda-base > out/miniconda-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-miniconda-base\n\n# miniconda-base 2.1.0\ndocker build miniconda/spark2.1.0/base/ --tag aztk/spark:v0.1.0-spark2.1.0-miniconda-base > out/miniconda-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-miniconda-base\n\n# miniconda-base 2.2.0\ndocker build miniconda/spark2.2.0/base --tag aztk/spark:v0.1.0-spark2.2.0-miniconda-base > out/miniconda-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-miniconda-base\n\n# miniconda-base 2.3.0\ndocker build miniconda/spark2.3.0/base/ --tag aztk/spark:v0.1.0-spark2.3.0-miniconda-base > out/miniconda-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-miniconda-base\n\n# anaconda-base 1.6.3\ndocker build anaconda/spark1.6.3/base/ --tag aztk/spark:v0.1.0-spark1.6.3-anaconda-base > out/anaconda-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-anaconda-base\n\n# anaconda-base 2.1.0\ndocker build anaconda/spark2.1.0/base/ --tag aztk/spark:v0.1.0-spark2.1.0-anaconda-base > out/anaconda-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-anaconda-base\n\n# anaconda-base 2.2.0\ndocker build anaconda/spark2.2.0/base/ --tag aztk/spark:v0.1.0-spark2.2.0-anaconda-base > out/anaconda-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-anaconda-base\n\n# anaconda-base 2.3.0\ndocker build anaconda/spark2.3.0/base/ --tag aztk/spark:v0.1.0-spark2.3.0-anaconda-base > out/anaconda-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-anaconda-base\n\n# r-base 1.6.3\ndocker build r/spark1.6.3/base/ --tag aztk/spark:v0.1.0-spark1.6.3-r-base > out/r-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-r-base\n\n# r-base 2.1.0\ndocker build r/spark2.1.0/base/ --tag aztk/spark:v0.1.0-spark2.1.0-r-base > out/r-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-r-base\n\n# r-base 2.2.0\ndocker build r/spark2.2.0/base/ --tag aztk/spark:v0.1.0-spark2.2.0-r-base > out/r-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-r-base\n\n# r-base 2.3.0\ndocker build r/spark2.3.0/base/ --tag aztk/spark:v0.1.0-spark2.3.0-r-base > out/r-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-r-base\n\n##################\n#      GPU       #\n##################\n\n# gpu 1.6.3\ndocker build gpu/spark1.6.3/ --tag aztk/spark:v0.1.0-spark1.6.3-gpu > out/gpu-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-gpu\n\n# gpu 2.1.0\ndocker build gpu/spark2.1.0/ --tag aztk/spark:v0.1.0-spark2.1.0-gpu > out/gpu-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-gpu\n\n# gpu 2.2.0\ndocker build gpu/spark2.2.0/ --tag aztk/spark:v0.1.0-spark2.2.0-gpu > out/gpu-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-gpu\n\n# gpu 2.3.0\ndocker build gpu/spark2.3.0/ --tag aztk/spark:v0.1.0-spark2.3.0-gpu > out/gpu-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-gpu\n\n# miniconda-gpu 1.6.3\ndocker build miniconda/spark1.6.3/gpu/ --tag aztk/spark:v0.1.0-spark1.6.3-miniconda-gpu > out/miniconda-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-miniconda-gpu\n\n# miniconda-gpu 2.1.0\ndocker build miniconda/spark2.1.0/gpu/ --tag aztk/spark:v0.1.0-spark2.1.0-miniconda-gpu > out/miniconda-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-miniconda-gpu\n\n# miniconda-gpu 2.2.0\ndocker build miniconda/spark2.2.0/gpu --tag aztk/spark:v0.1.0-spark2.2.0-miniconda-gpu > out/miniconda-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-miniconda-gpu\n\n# miniconda-gpu 2.3.0\ndocker build miniconda/spark2.3.0/gpu/ --tag aztk/spark:v0.1.0-spark2.3.0-miniconda-gpu > out/miniconda-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-miniconda-gpu\n\n# anaconda-gpu 1.6.3\ndocker build anaconda/spark1.6.3/gpu/ --tag aztk/spark:v0.1.0-spark1.6.3-anaconda-gpu > out/anaconda-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-anaconda-gpu\n\n# anaconda-gpu 2.1.0\ndocker build anaconda/spark2.1.0/gpu/ --tag aztk/spark:v0.1.0-spark2.1.0-anaconda-gpu > out/anaconda-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-anaconda-gpu\n\n# anaconda-gpu 2.2.0\ndocker build anaconda/spark2.2.0/gpu/ --tag aztk/spark:v0.1.0-spark2.2.0-anaconda-gpu > out/anaconda-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-anaconda-gpu\n\n# anaconda-gpu 2.3.0\ndocker build anaconda/spark2.3.0/gpu/ --tag aztk/spark:v0.1.0-spark2.3.0-anaconda-gpu > out/anaconda-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-anaconda-gpu\n\n# r-gpu 1.6.3\ndocker build r/spark1.6.3/gpu/ --tag aztk/spark:v0.1.0-spark1.6.3-r-gpu > out/r-spark1.6.3.out &&\ndocker push aztk/spark:v0.1.0-spark1.6.3-r-gpu\n\n# r-gpu 2.1.0\ndocker build r/spark2.1.0/gpu/ --tag aztk/spark:v0.1.0-spark2.1.0-r-gpu > out/r-spark2.1.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.1.0-r-gpu\n\n# r-gpu 2.2.0\ndocker build r/spark2.2.0/gpu/ --tag aztk/spark:v0.1.0-spark2.2.0-r-gpu > out/r-spark2.2.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.2.0-r-gpu\n\n# r-gpu 2.3.0\ndocker build r/spark2.3.0/gpu/ --tag aztk/spark:v0.1.0-spark2.3.0-r-gpu > out/r-spark2.3.0.out &&\ndocker push aztk/spark:v0.1.0-spark2.3.0-r-gpu\n", "num_lines": 144}
{"repo_name": "Azure-AI-Camp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script is intended as an initialization script used in azuredeploy.json\n# See documentation here: https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-linux#template-deployment\n\n# see abbreviated notes in README.md\n# comments below:\n\nadminUser=$1\n\nWD=/home/$adminUser/notebooks\n\necho WD is $WD\n\nif [ ! -d $WD ]; then\n    echo $WD does not exist - aborting!!\n    exit\nelse\n    cd $WD\n    echo \"Working in $(pwd)\"\nfi\n\n# Clone the content for the workshop in notebooks dir\ngit clone https://github.com/Azure/Azure-AI-Camp.git\nchmod -R ugo+rwx Azure-AI-Camp\n\n## Add user to docker group\nusermod -aG docker $adminUser\n\n## Reboot jupyterhub\nsystemctl restart jupyterhub\n\necho \"Done!\"\n", "num_lines": 34}
{"repo_name": "Azure-AI-Camp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script is intended as an initialization script used in azuredeploy.json\n# See documentation here: https://docs.microsoft.com/en-us/azure/virtual-machines/extensions/custom-script-linux#template-deployment\n\n# see abbreviated notes in README.md\n# comments below:\n\n# Input args\nadminUser=$1\necho $adminUser >> \"/home/userscript.log\"\npublicIP=`dig +short myip.opendns.com @resolver1.opendns.com`\necho $publicIP >> \"/home/userscript.log\"\n\n# Script to update Notbook metadata\ncat << EOF > /tmp/changenbmeta.py\n#!/usr/bin/python\nimport json,sys\nif len(sys.argv) < 2 :\n        print \"Usage: python changenbmeta.py <filename>\"\n        exit()\nwith open(sys.argv[1], \"r\") as jsonFile:\n    data = json.load(jsonFile)\ndata[\"metadata\"][\"kernelspec\"][\"display_name\"] = \"Python 3.6 - PyTorch 1.1\"\ndata[\"metadata\"][\"kernelspec\"][\"name\"] = \"pytorch1_1\"\nwith open(sys.argv[1], \"w\") as jsonFile:\n    json.dump(data, jsonFile)\nEOF\n\n# Clone the content\nmkdir -p /etc/skel/notebooks/AICamp\ncd /etc/skel/notebooks/AICamp\n# git clone <repp>\n\n# Change metadata on notebook to match kernel name in the fast.ai notebooks\nfind . -name \\*.ipynb -exec /usr/bin/python /tmp/changenbmeta.py {} \\;\n\n# Save host public ip address to the users text file\necho $publicIP >> \"/home/usersinfo.csv\"\n\n## declare an array of user names to create on vm\ndeclare -a arr=(\"temp\" \"storm\" \"jeangrey\" \"spiderman\" \"captainmarvel\" \"quake\" \"wolverine\" \"thor\" \"ironman\" \"firestar\" \"rogue\")\n## now loop through the above array\nfor u in \"${arr[@]}\";\n# Create users and generate random password with uppercase and punc chars. Run as root:\ndo\n    sudo useradd -m $u\n    p=`openssl rand -hex 4`\n    p=\"P$p!\"\n    printf \"$p\\n$p\" | sudo passwd $u\n    echo $u, $p >> \"/home/usersinfo.csv\"\n\n    # add user to sudoers\n    sudo adduser $u sudo\n\n    ## now create the env...\n    condapath=/home/$u/.conda/envs\n\n    if [ ! -d $condapath ]; then\n        sudo mkdir -p $condapath\n    fi\n\n    ## Update appropriate permissions\n    sudo chown -R ${u}:${u} ${condapath}\n\n    ## Add user to docker group\n    sudo usermod -aG docker $u\ndone\necho \"Created users\" >> \"/home/userscript.log\"\n\n# # copy the notebooks to the users' profiles\n# for filename in /home/*; do\n#   dir=$filename/notebooks\n#   user=${filename:6}\n#   cp -r /etc/skel/notebooks/Workshop $dir\n#   chown -R $user $dir/Workshop/*\n#   chown $user $dir/Workshop\n# done\n\n# echo \"Copied Workshop notebooks into user directories\" >> \"/home/userscript.log\"\n\n## now create the env...\ncondapath=/home/$adminUser/.conda/envs\n\nif [ ! -d $condapath ]; then\n    mkdir -p $condapath\nfi\n\n#### PYTORCH 1.1 ####\n\n/data/anaconda/bin/conda create --name pytorch1 python=3.6 ipykernel conda\n\n## update appropriate permissions\nchown -R ${adminUser}:${adminUser} ${condapath}\n\n# Install PyTorch 1.x into environment with cuda 9.2 support as DSVM is on this now\n/data/anaconda/envs/pytorch1/bin/python -m conda install pytorch==1.1.0 torchvision cudatoolkit=9.0 -c pytorch -y\n/data/anaconda/envs/pytorch1/bin/python -m pip install --yes bs4 jdc jupyter numpy requests scipy sklearn tqdm\n/data/anaconda/envs/pytorch1/bin/python -m pip install --yes azureml-sdk[automl]==1.0.74\n\n# LibTorch - install into /usr/local/lib\nwget https://download.pytorch.org/libtorch/nightly/cu92/libtorch-shared-with-deps-latest.zip\nunzip libtorch-shared-with-deps-latest.zip\nsudo mv libtorch /usr/local/lib/python3.5/dist-packages/torch\n\n## Install it as a kernel\n/data/anaconda/envs/pytorch1/bin/python -m ipykernel install --name pytorch1_1 --display-name \"Python 3.6 - PyTorch 1.1\"\n\necho \"Done setting up PyTorch 1.1\" >> \"/home/userscript.log\"\n\n## Update appropriate permissions\nchown -R ${adminUser}:${adminUser} ${condapath}\n\n## Reboot jupyterhub\nsystemctl restart jupyterhub\n\necho \"Done!\" >> \"/home/userscript.log\"\n", "num_lines": 118}
{"repo_name": "Azure-AppServices-Diagnostics-Portal", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker build -t applens/portal-dev-env .\n", "num_lines": 2}
{"repo_name": "Azure-AppServices-Diagnostics-Portal", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Discussion, issues and change requests at:\n#   https://github.com/nodesource/distributions\n#\n# Script to install the NodeSource Node.js 14.x repo onto a\n# Debian or Ubuntu system.\n#\n# Run as root or insert `sudo -E` before `bash`:\n#\n# curl -sL https://deb.nodesource.com/setup_14.x | bash -\n#   or\n# wget -qO- https://deb.nodesource.com/setup_14.x | bash -\n#\n# CONTRIBUTIONS TO THIS SCRIPT\n#\n# This script is built from a template in\n# https://github.com/nodesource/distributions/tree/master/deb/src\n# please don't submit pull requests against the built scripts.\n#\n\n\nexport DEBIAN_FRONTEND=noninteractive\nSCRSUFFIX=\"_14.x\"\nNODENAME=\"Node.js 14.x\"\nNODEREPO=\"node_14.x\"\nNODEPKG=\"nodejs\"\n\nprint_status() {\n    echo\n    echo \"## $1\"\n    echo\n}\n\nif test -t 1; then # if terminal\n    ncolors=$(which tput > /dev/null && tput colors) # supports color\n    if test -n \"$ncolors\" && test $ncolors -ge 8; then\n        termcols=$(tput cols)\n        bold=\"$(tput bold)\"\n        underline=\"$(tput smul)\"\n        standout=\"$(tput smso)\"\n        normal=\"$(tput sgr0)\"\n        black=\"$(tput setaf 0)\"\n        red=\"$(tput setaf 1)\"\n        green=\"$(tput setaf 2)\"\n        yellow=\"$(tput setaf 3)\"\n        blue=\"$(tput setaf 4)\"\n        magenta=\"$(tput setaf 5)\"\n        cyan=\"$(tput setaf 6)\"\n        white=\"$(tput setaf 7)\"\n    fi\nfi\n\nprint_bold() {\n    title=\"$1\"\n    text=\"$2\"\n\n    echo\n    echo \"${red}================================================================================${normal}\"\n    echo \"${red}================================================================================${normal}\"\n    echo\n    echo -e \"  ${bold}${yellow}${title}${normal}\"\n    echo\n    echo -en \"  ${text}\"\n    echo\n    echo \"${red}================================================================================${normal}\"\n    echo \"${red}================================================================================${normal}\"\n}\n\nbail() {\n    echo 'Error executing command, exiting'\n    exit 1\n}\n\nexec_cmd_nobail() {\n    echo \"+ $1\"\n    bash -c \"$1\"\n}\n\nexec_cmd() {\n    exec_cmd_nobail \"$1\" || bail\n}\n\nnode_deprecation_warning() {\n    if [[ \"X${NODENAME}\" == \"Xio.js 1.x\" ||\n          \"X${NODENAME}\" == \"Xio.js 2.x\" ||\n          \"X${NODENAME}\" == \"Xio.js 3.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 0.10\" ||\n          \"X${NODENAME}\" == \"XNode.js 0.12\" ||\n          \"X${NODENAME}\" == \"XNode.js 4.x LTS Argon\" ||\n          \"X${NODENAME}\" == \"XNode.js 5.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 6.x LTS Boron\" ||\n          \"X${NODENAME}\" == \"XNode.js 7.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 8.x LTS Carbon\" ||\n          \"X${NODENAME}\" == \"XNode.js 9.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 10.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 11.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 13.x\" ||\n          \"X${NODENAME}\" == \"XNode.js 15.x\" ]]; then\n\n        print_bold \\\n\"                            DEPRECATION WARNING                            \" \"\\\n${bold}${NODENAME} is no longer actively supported!${normal}\n\n  ${bold}You will not receive security or critical stability updates${normal} for this version.\n\n  You should migrate to a supported version of Node.js as soon as possible.\n  Use the installation script that corresponds to the version of Node.js you\n  wish to install. e.g.\n\n   * ${green}https://deb.nodesource.com/setup_12.x \u00e2\u20ac\u201d Node.js 12 LTS \\\"Erbium\\\"${normal}\n   * ${green}https://deb.nodesource.com/setup_14.x \u00e2\u20ac\u201d Node.js 14 LTS \\\"Fermium\\\"${normal} (recommended)\n   * ${green}https://deb.nodesource.com/setup_16.x \u00e2\u20ac\u201d Node.js 16 \\\"Gallium\\\"${normal}\n   * ${green}https://deb.nodesource.com/setup_17.x \u00e2\u20ac\u201d Node.js 17 \\\"Seventeen\\\"${normal} (current)\n\n  Please see ${bold}https://github.com/nodejs/Release${normal} for details about which\n  version may be appropriate for you.\n\n  The ${bold}NodeSource${normal} Node.js distributions repository contains\n  information both about supported versions of Node.js and supported Linux\n  distributions. To learn more about usage, see the repository:\n    ${bold}https://github.com/nodesource/distributions${normal}\n\"\n        echo\n        echo \"Continuing in 20 seconds ...\"\n        echo\n        sleep 20\n    fi\n}\n\nscript_deprecation_warning() {\n    if [ \"X${SCRSUFFIX}\" == \"X\" ]; then\n        print_bold \\\n\"                         SCRIPT DEPRECATION WARNING                         \" \"\\\nThis script, located at ${bold}https://deb.nodesource.com/setup${normal}, used to\n  install Node.js 0.10, is deprecated and will eventually be made inactive.\n\n  You should use the script that corresponds to the version of Node.js you\n  wish to install. e.g.\n\n   * ${green}https://deb.nodesource.com/setup_12.x \u00e2\u20ac\u201d Node.js 12 LTS \\\"Erbium\\\"${normal}\n   * ${green}https://deb.nodesource.com/setup_14.x \u00e2\u20ac\u201d Node.js 14 LTS \\\"Fermium\\\"${normal} (recommended)\n   * ${green}https://deb.nodesource.com/setup_16.x \u00e2\u20ac\u201d Node.js 16 \\\"Gallium\\\"${normal}\n   * ${green}https://deb.nodesource.com/setup_17.x \u00e2\u20ac\u201d Node.js 17 \\\"Seventeen\\\"${normal} (current)\n\n  Please see ${bold}https://github.com/nodejs/Release${normal} for details about which\n  version may be appropriate for you.\n\n  The ${bold}NodeSource${normal} Node.js Linux distributions GitHub repository contains\n  information about which versions of Node.js and which Linux distributions\n  are supported and how to use the install scripts.\n    ${bold}https://github.com/nodesource/distributions${normal}\n\"\n\n        echo\n        echo \"Continuing in 20 seconds (press Ctrl-C to abort) ...\"\n        echo\n        sleep 20\n    fi\n}\n\nsetup() {\n\nscript_deprecation_warning\nnode_deprecation_warning\n\nprint_status \"Installing the NodeSource ${NODENAME} repo...\"\n\nif $(uname -m | grep -Eq ^armv6); then\n    print_status \"You appear to be running on ARMv6 hardware. Unfortunately this is not currently supported by the NodeSource Linux distributions. Please use the 'linux-armv6l' binary tarballs available directly from nodejs.org for Node.js 4 and later.\"\n    exit 1\nfi\n\nPRE_INSTALL_PKGS=\"\"\n\n# Check that HTTPS transport is available to APT\n# (Check snaked from: https://get.docker.io/ubuntu/)\n\nif [ ! -e /usr/lib/apt/methods/https ]; then\n    PRE_INSTALL_PKGS=\"${PRE_INSTALL_PKGS} apt-transport-https\"\nfi\n\nif [ ! -x /usr/bin/lsb_release ]; then\n    PRE_INSTALL_PKGS=\"${PRE_INSTALL_PKGS} lsb-release\"\nfi\n\nif [ ! -x /usr/bin/curl ] && [ ! -x /usr/bin/wget ]; then\n    PRE_INSTALL_PKGS=\"${PRE_INSTALL_PKGS} curl\"\nfi\n\n# Used by apt-key to add new keys\n\nif [ ! -x /usr/bin/gpg ]; then\n    PRE_INSTALL_PKGS=\"${PRE_INSTALL_PKGS} gnupg\"\nfi\n\n# Populating Cache\nprint_status \"Populating apt-get cache...\"\nexec_cmd 'apt-get update'\n\nif [ \"X${PRE_INSTALL_PKGS}\" != \"X\" ]; then\n    print_status \"Installing packages required for setup:${PRE_INSTALL_PKGS}...\"\n    # This next command needs to be redirected to /dev/null or the script will bork\n    # in some environments\n    exec_cmd \"apt-get install -y${PRE_INSTALL_PKGS} > /dev/null 2>&1\"\nfi\n\nIS_PRERELEASE=$(lsb_release -d | grep 'Ubuntu .*development' >& /dev/null; echo $?)\nif [[ $IS_PRERELEASE -eq 0 ]]; then\n    print_status \"Your distribution, identified as \\\"$(lsb_release -d -s)\\\", is a pre-release version of Ubuntu. NodeSource does not maintain official support for Ubuntu versions until they are formally released. You can try using the manual installation instructions available at https://github.com/nodesource/distributions and use the latest supported Ubuntu version name as the distribution identifier, although this is not guaranteed to work.\"\n    exit 1\nfi\n\nDISTRO=$(lsb_release -c -s)\n\ncheck_alt() {\n    if [ \"X${DISTRO}\" == \"X${2}\" ]; then\n        echo\n        echo \"## You seem to be using ${1} version ${DISTRO}.\"\n        echo \"## This maps to ${3} \\\"${4}\\\"... Adjusting for you...\"\n        DISTRO=\"${4}\"\n    fi\n}\n\ncheck_alt \"SolydXK\"       \"solydxk-9\" \"Debian\" \"stretch\"\ncheck_alt \"Kali\"          \"sana\"     \"Debian\" \"jessie\"\ncheck_alt \"Kali\"          \"kali-rolling\" \"Debian\" \"bullseye\"\ncheck_alt \"Sparky Linux\"  \"Tyche\"    \"Debian\" \"stretch\"\ncheck_alt \"Sparky Linux\"  \"Nibiru\"   \"Debian\" \"buster\"\ncheck_alt \"Sparky Linux\"  \"Po-Tolo\"   \"Debian\" \"bullseye\"\ncheck_alt \"MX Linux 17\"   \"Horizon\"  \"Debian\" \"stretch\"\ncheck_alt \"MX Linux 18\"   \"Continuum\" \"Debian\" \"stretch\"\ncheck_alt \"MX Linux 19\"   \"patito feo\" \"Debian\" \"buster\"\ncheck_alt \"MX Linux 21\"   \"wildflower\" \"Debian\" \"bullseye\"\ncheck_alt \"Linux Mint\"    \"maya\"     \"Ubuntu\" \"precise\"\ncheck_alt \"Linux Mint\"    \"qiana\"    \"Ubuntu\" \"trusty\"\ncheck_alt \"Linux Mint\"    \"rafaela\"  \"Ubuntu\" \"trusty\"\ncheck_alt \"Linux Mint\"    \"rebecca\"  \"Ubuntu\" \"trusty\"\ncheck_alt \"Linux Mint\"    \"rosa\"     \"Ubuntu\" \"trusty\"\ncheck_alt \"Linux Mint\"    \"sarah\"    \"Ubuntu\" \"xenial\"\ncheck_alt \"Linux Mint\"    \"serena\"   \"Ubuntu\" \"xenial\"\ncheck_alt \"Linux Mint\"    \"sonya\"    \"Ubuntu\" \"xenial\"\ncheck_alt \"Linux Mint\"    \"sylvia\"   \"Ubuntu\" \"xenial\"\ncheck_alt \"Linux Mint\"    \"tara\"     \"Ubuntu\" \"bionic\"\ncheck_alt \"Linux Mint\"    \"tessa\"    \"Ubuntu\" \"bionic\"\ncheck_alt \"Linux Mint\"    \"tina\"     \"Ubuntu\" \"bionic\"\ncheck_alt \"Linux Mint\"    \"tricia\"   \"Ubuntu\" \"bionic\"\ncheck_alt \"Linux Mint\"    \"ulyana\"   \"Ubuntu\" \"focal\"\ncheck_alt \"Linux Mint\"    \"ulyssa\"   \"Ubuntu\" \"focal\"\ncheck_alt \"Linux Mint\"    \"uma\"      \"Ubuntu\" \"focal\"\ncheck_alt \"Linux Mint\"    \"una\"      \"Ubuntu\" \"focal\"\ncheck_alt \"LMDE\"          \"betsy\"    \"Debian\" \"jessie\"\ncheck_alt \"LMDE\"          \"cindy\"    \"Debian\" \"stretch\"\ncheck_alt \"LMDE\"          \"debbie\"   \"Debian\" \"buster\"\ncheck_alt \"elementaryOS\"  \"luna\"     \"Ubuntu\" \"precise\"\ncheck_alt \"elementaryOS\"  \"freya\"    \"Ubuntu\" \"trusty\"\ncheck_alt \"elementaryOS\"  \"loki\"     \"Ubuntu\" \"xenial\"\ncheck_alt \"elementaryOS\"  \"juno\"     \"Ubuntu\" \"bionic\"\ncheck_alt \"elementaryOS\"  \"hera\"     \"Ubuntu\" \"bionic\"\ncheck_alt \"elementaryOS\"  \"odin\"     \"Ubuntu\" \"focal\"\ncheck_alt \"elementaryOS\"  \"jolnir\"   \"Ubuntu\" \"focal\"\ncheck_alt \"Trisquel\"      \"toutatis\" \"Ubuntu\" \"precise\"\ncheck_alt \"Trisquel\"      \"belenos\"  \"Ubuntu\" \"trusty\"\ncheck_alt \"Trisquel\"      \"flidas\"   \"Ubuntu\" \"xenial\"\ncheck_alt \"Trisquel\"      \"etiona\"   \"Ubuntu\" \"bionic\"\ncheck_alt \"Uruk GNU/Linux\" \"lugalbanda\" \"Ubuntu\" \"xenial\"\ncheck_alt \"BOSS\"          \"anokha\"   \"Debian\" \"wheezy\"\ncheck_alt \"BOSS\"          \"anoop\"    \"Debian\" \"jessie\"\ncheck_alt \"BOSS\"          \"drishti\"  \"Debian\" \"stretch\"\ncheck_alt \"BOSS\"          \"unnati\"   \"Debian\" \"buster\"\ncheck_alt \"bunsenlabs\"    \"bunsen-hydrogen\" \"Debian\" \"jessie\"\ncheck_alt \"bunsenlabs\"    \"helium\"   \"Debian\" \"stretch\"\ncheck_alt \"bunsenlabs\"    \"lithium\"  \"Debian\" \"buster\"\ncheck_alt \"Tanglu\"        \"chromodoris\" \"Debian\" \"jessie\"\ncheck_alt \"PureOS\"        \"green\"    \"Debian\" \"sid\"\ncheck_alt \"PureOS\"        \"amber\"    \"Debian\" \"buster\"\ncheck_alt \"PureOS\"        \"byzantium\" \"Debian\" \"bullseye\"\ncheck_alt \"Devuan\"        \"jessie\"   \"Debian\" \"jessie\"\ncheck_alt \"Devuan\"        \"ascii\"    \"Debian\" \"stretch\"\ncheck_alt \"Devuan\"        \"beowulf\"  \"Debian\" \"buster\"\ncheck_alt \"Devuan\"        \"chimaera\"  \"Debian\" \"bullseye\"\ncheck_alt \"Devuan\"        \"ceres\"    \"Debian\" \"sid\"\ncheck_alt \"Deepin\"        \"panda\"    \"Debian\" \"sid\"\ncheck_alt \"Deepin\"        \"unstable\" \"Debian\" \"sid\"\ncheck_alt \"Deepin\"        \"stable\"   \"Debian\" \"buster\"\ncheck_alt \"Pardus\"        \"onyedi\"   \"Debian\" \"stretch\"\ncheck_alt \"Liquid Lemur\"  \"lemur-3\"  \"Debian\" \"stretch\"\ncheck_alt \"Astra Linux\"   \"orel\"     \"Debian\" \"stretch\"\ncheck_alt \"Ubilinux\"      \"dolcetto\" \"Debian\" \"stretch\"\n\nif [ \"X${DISTRO}\" == \"Xdebian\" ]; then\n  print_status \"Unknown Debian-based distribution, checking /etc/debian_version...\"\n  NEWDISTRO=$([ -e /etc/debian_version ] && cut -d/ -f1 < /etc/debian_version)\n  if [ \"X${NEWDISTRO}\" == \"X\" ]; then\n    print_status \"Could not determine distribution from /etc/debian_version...\"\n  else\n    DISTRO=$NEWDISTRO\n    print_status \"Found \\\"${DISTRO}\\\" in /etc/debian_version...\"\n  fi\nfi\n\nprint_status \"Confirming \\\"${DISTRO}\\\" is supported...\"\n\nif [ -x /usr/bin/curl ]; then\n    exec_cmd_nobail \"curl -sLf -o /dev/null 'https://deb.nodesource.com/${NODEREPO}/dists/${DISTRO}/Release'\"\n    RC=$?\nelse\n    exec_cmd_nobail \"wget -qO /dev/null -o /dev/null 'https://deb.nodesource.com/${NODEREPO}/dists/${DISTRO}/Release'\"\n    RC=$?\nfi\n\nif [[ $RC != 0 ]]; then\n    print_status \"Your distribution, identified as \\\"${DISTRO}\\\", is not currently supported, please contact NodeSource at https://github.com/nodesource/distributions/issues if you think this is incorrect or would like your distribution to be considered for support\"\n    exit 1\nfi\n\nif [ -f \"/etc/apt/sources.list.d/chris-lea-node_js-$DISTRO.list\" ]; then\n    print_status 'Removing Launchpad PPA Repository for NodeJS...'\n\n    exec_cmd_nobail 'add-apt-repository -y -r ppa:chris-lea/node.js'\n    exec_cmd \"rm -f /etc/apt/sources.list.d/chris-lea-node_js-${DISTRO}.list\"\nfi\n\nprint_status 'Adding the NodeSource signing key to your keyring...'\nkeyring='/usr/share/keyrings'\nnode_key_url=\"https://deb.nodesource.com/gpgkey/nodesource.gpg.key\"\nlocal_node_key=\"$keyring/nodesource.gpg\"\n\nif [ -x /usr/bin/curl ]; then\n    exec_cmd \"curl -s $node_key_url | gpg --dearmor | tee $local_node_key >/dev/null\"\nelse\n    exec_cmd \"wget -q -O - $node_key_url | gpg --dearmor | tee $local_node_key >/dev/null\"\nfi\n\nprint_status \"Creating apt sources list file for the NodeSource ${NODENAME} repo...\"\n\nexec_cmd \"echo 'deb [signed-by=$local_node_key] https://deb.nodesource.com/${NODEREPO} ${DISTRO} main' > /etc/apt/sources.list.d/nodesource.list\"\nexec_cmd \"echo 'deb-src [signed-by=$local_node_key] https://deb.nodesource.com/${NODEREPO} ${DISTRO} main' >> /etc/apt/sources.list.d/nodesource.list\"\n\nprint_status 'Running `apt-get update` for you...'\n\nexec_cmd 'apt-get update'\n\nyarn_site='https://dl.yarnpkg.com/debian'\nyarn_key_url=\"$yarn_site/pubkey.gpg\"\nlocal_yarn_key=\"$keyring/yarnkey.gpg\"\n\nprint_status \"\"\"Run \\`${bold}sudo apt-get install -y ${NODEPKG}${normal}\\` to install ${NODENAME} and npm\n## You may also need development tools to build native addons:\n     sudo apt-get install gcc g++ make\n## To install the Yarn package manager, run:\n     curl -sL $yarn_key_url | gpg --dearmor | sudo tee $local_yarn_key >/dev/null\n     echo \\\"deb [signed-by=$local_yarn_key] $yarn_site stable main\\\" | sudo tee /etc/apt/sources.list.d/yarn.list\n     sudo apt-get update && sudo apt-get install yarn\n\"\"\"\n\n}\n\n## Defer setup until we have the complete script\nsetup\n", "num_lines": 361}
{"repo_name": "Azure-AppServices-Diagnostics-Portal", "repo_creator": "Azure", "programming_language": "Shell", "code": "docker run -it -v ${PWD}:/AngularApp -p 0.0.0.0:3000:3000 applens/portal-dev-env bash\n", "num_lines": 2}
{"repo_name": "azure-arc-validation", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Set the following environment variables to run the test suite\n\n# Common Variables\n# Some of the variables need to be populated from the service principal and storage account details provided to you by Microsoft\nAZ_TENANT_ID= # tenant field of the service principal\nAZ_SUBSCRIPTION_ID= # subscription id of the azure subscription (will be provided)\nAZ_CLIENT_ID= # appid field of the service principal\nAZ_CLIENT_SECRET= # password field of the service principal\nAZ_STORAGE_ACCOUNT= # name of your storage account\nAZ_STORAGE_ACCOUNT_SAS=\"\" # sas token for your storage account, please add it within the quotes\nRESOURCE_GROUP= # resource group name; set this to the resource group\nOFFERING_NAME= # name of the partner offering; use this variable to distinguish between the results tar for different offerings\nLOCATION=eastus # location of the arc connected cluster\nNAMESPACE=arc-ds-controller # namespace of the data controller\nCONNECTIVITY_MODE=indirect # choose connectivty mode for data services\nSERVICE_TYPE=NodePort # Using a NodePort gives you the freedom to set up your own load-balancing solution or you can set LoadBalancer service type if your environment supports to generate external IPs.\nCONFIG_PROFILE=azure-arc-aks-default-storage # choose the config profile\nDATA_CONTROLLER_STORAGE_CLASS=default # choose the storage class for data controller\nSQL_MI_STORAGE_CLASS=default # choose the storage class for sql mi\nPSQL_STORAGE_CLASS=default # choose the storage class for postgreSQL\nAZDATA_USERNAME=azureuser # database username\nAZDATA_PASSWORD= # database password\nMEMORY=4Gi # The request for the capacity of the managed instance as an integer number followed by Gi (gigabytes). Example: 4Gi or 8Gi\nSQL_INSTANCE_NAME=arc-sql # sql instance name\nPSQL_SERVERGROUP_NAME=arc-psql # postgreSQL server name\nINFRASTRUCTURE=azure # Allowed values are alibaba, aws, azure, gpc, onpremises, other.\n## For PRE-RELEASE test please uncomment and pass the required values for below parameters.\n#RELEASE_TYPE=PRE-RELEASE\n## Allowed repository names are arcdata/preview or arcdata/test\n#REPOSITORY=arcdata/test\n## Image Tag will be changed based on PRE-RELEASE versions\n#IMAGE_TAG=v1.9.0_2022-07-12\n\n# In case your cluster is behind an outbound proxy, please add the following environment variables in the below command\n# --plugin-env azure-arc-ds-platform.HTTPS_PROXY=\"http://<proxy ip>:<proxy port>\"\n# --plugin-env azure-arc-ds-platform.HTTP_PROXY=\"http://<proxy ip>:<proxy port>\"\n# --plugin-env azure-arc-ds-platform.NO_PROXY=\"kubernetes.default.svc,<ip CIDR etc>\"\n\n# In case your outbound proxy is setup with certificate authentication, follow the below steps:\n# Create a Kubernetes generic secret with the name sonobuoy-proxy-cert with key proxycert in any namespace:\n# kubectl create secret generic sonobuoy-proxy-cert --from-file=proxycert=<path-to-cert-file>\n# By default we check for the secret in the default namespace. In case you have created the secret in some other namespace, please add the following variables in the sonobuoy run command: \n# --plugin-env azure-arc-ds-platform.PROXY_CERT_NAMESPACE=\"<namespace of sonobuoy secret>\"\n\n# Add below variables at sonobuoy run command when running the test suite on an openshift cluster  \n# --dns-namespace openshift-dns --dns-pod-labels dns.operator.openshift.io/daemonset-dns=default\n\necho \"Running the test suite..\"\n\nsonobuoy run --wait --config config.json \\\n--plugin arc-dataservices/dataservices.yaml \\\n--plugin-env azure-arc-ds-platform.NAMESPACE=$NAMESPACE \\\n--plugin-env azure-arc-ds-platform.CONFIG_PROFILE=$CONFIG_PROFILE \\\n--plugin-env azure-arc-ds-platform.DATA_CONTROLLER_STORAGE_CLASS=$DATA_CONTROLLER_STORAGE_CLASS \\\n--plugin-env azure-arc-ds-platform.CONNECTIVITY_MODE=$CONNECTIVITY_MODE \\\n--plugin-env azure-arc-ds-platform.SERVICE_TYPE=$SERVICE_TYPE \\\n--plugin-env azure-arc-ds-platform.SQL_MI_STORAGE_CLASS=$SQL_MI_STORAGE_CLASS \\\n--plugin-env azure-arc-ds-platform.PSQL_STORAGE_CLASS=$PSQL_STORAGE_CLASS \\\n--plugin-env azure-arc-ds-platform.AZDATA_USERNAME=$AZDATA_USERNAME \\\n--plugin-env azure-arc-ds-platform.AZDATA_PASSWORD=$AZDATA_PASSWORD \\\n--plugin-env azure-arc-ds-platform.MEMORY=$MEMORY \\\n--plugin-env azure-arc-ds-platform.SQL_INSTANCE_NAME=$SQL_INSTANCE_NAME \\\n--plugin-env azure-arc-ds-platform.PSQL_SERVERGROUP_NAME=$PSQL_SERVERGROUP_NAME \\\n--plugin-env azure-arc-ds-platform.TENANT_ID=$AZ_TENANT_ID \\\n--plugin-env azure-arc-ds-platform.SUBSCRIPTION_ID=$AZ_SUBSCRIPTION_ID \\\n--plugin-env azure-arc-ds-platform.RESOURCE_GROUP=$RESOURCE_GROUP \\\n--plugin-env azure-arc-ds-platform.LOCATION=$LOCATION \\\n--plugin-env azure-arc-ds-platform.CLIENT_ID=$AZ_CLIENT_ID \\\n--plugin-env azure-arc-ds-platform.CLIENT_SECRET=$AZ_CLIENT_SECRET \\\n--plugin-env azure-arc-ds-platform.INFRASTRUCTURE=$INFRASTRUCTURE \\\n--plugin-env azure-arc-ds-platform.RELEASE_TYPE=$RELEASE_TYPE \\\n--plugin-env azure-arc-ds-platform.REPOSITORY=$REPOSITORY \\\n--plugin-env azure-arc-ds-platform.IMAGE_TAG=$IMAGE_TAG\n\necho \"Test execution completed..Retrieving results\"\n\nsonobuoyResults=$(sonobuoy retrieve)\nsonobuoy results $sonobuoyResults\nmkdir results\nmv $sonobuoyResults results/$sonobuoyResults\ncp partner-metadata.md results/partner-metadata.md\ntar -czvf conformance-results.tar.gz results\nrm -rf results\n\necho \"Publishing results..\"\n\naz login --service-principal --username $AZ_CLIENT_ID --password $AZ_CLIENT_SECRET --tenant $AZ_TENANT_ID\naz account set -s $AZ_SUBSCRIPTION_ID\n\naz storage container create -n conformance-results-ds --account-name $AZ_STORAGE_ACCOUNT --sas-token $AZ_STORAGE_ACCOUNT_SAS\naz storage blob upload --file conformance-results.tar.gz --name conformance-results-$OFFERING_NAME.tar.gz --container-name conformance-results-ds --account-name $AZ_STORAGE_ACCOUNT --sas-token $AZ_STORAGE_ACCOUNT_SAS\n", "num_lines": 92}
{"repo_name": "azure-arm-validator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\nwhile getopts \"a:l:g:s:f:e:uv\" opt; do\n    case $opt in\n        a)\n            artifactsStagingDirectory=$OPTARG #the folder or sample to deploy\n        ;;\n        l)\n            location=$OPTARG #location for the deployed resource group\n        ;;\n        g)\n            resourceGroupName=$OPTARG\n        ;;\n        u)\n            uploadArtifacts='true' #set this switch to upload/stage artifacs\n        ;;\n        s)\n            storageAccountName=$OPTARG #storage account to use for staging, if not supplied one will be created and reused\n        ;;\n        f)\n            templateFile=$OPTARG\n        ;;\n        e)\n            parametersFile=$OPTARG\n        ;;\n        v)\n            validateOnly='true'\n        ;;\n    esac\ndone\n    \n[[ $# -eq 0 || -z $artifactsStagingDirectory || -z $location ]] && { echo \"Usage: $0 <-a foldername> <-l location> [-e parameters-file] [-g resource-group-name] [-u] [-s storageAccountName] [-v]\"; exit 1; }\n\nif [[ -z $templateFile ]]\nthen\n    templateFile=\"$artifactsStagingDirectory/azuredeploy.json\"\nfi\nif [[ -z $parametersFile ]]\nthen\n    parametersFile=\"$artifactsStagingDirectory/azuredeploy.parameters.json\"\nfi\n\ntemplateName=\"$( basename \"${templateFile%.*}\" )\"\ntemplateDirectory=\"$( dirname \"$templateFile\")\"\n\nif [[ -z $resourceGroupName ]]\nthen\n    resourceGroupName=${artifactsStagingDirectory}\nfi\n\nparameterJson=$( cat \"$parametersFile\" | jq '.parameters' )\n\nif [[ $uploadArtifacts ]]\nthen\n\n    if [[ -z $storageAccountName ]]\n    then    \n\n        subscriptionId=$( az account show -o json | jq -r '.id' )\n        subscriptionId=\"${subscriptionId//-/}\" \n        subscriptionId=\"${subscriptionId:0:19}\"\n        artifactsStorageAccountName=\"stage$subscriptionId\"\n        artifactsResourceGroupName=\"ARM_Deploy_Staging\"    \n\n        if [[ -z $( az storage account list -o json | jq -r '.[].name | select(. == '\\\"$artifactsStorageAccountName\\\"')' ) ]]\n        then\n            az group create -n \"$artifactsResourceGroupName\" -l \"$location\"\n            az storage account create -l \"$location\" --sku \"Standard_LRS\" -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" 2>/dev/null\n        fi\n    else\n        artifactsResourceGroupName=$( az storage account list -o json | jq -r '.[] | select(.name == '\\\"$s\\\"') .resourceGroup' )\n        if [[ -z $artifactsResourceGroupName ]] \n        then\n            echo \"Cannot find storageAccount: \"$storageAccountName\n        fi   \n    fi\n    \n    artifactsStorageContainerName=${resourceGroupName}\"-stageartifacts\"\n    artifactsStorageContainerName=$( echo \"$artifactsStorageContainerName\" | awk '{print tolower($0)}')\n    \n    artifactsStorageAccountKey=$( az storage account keys list -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" -o json | jq -r '.[0].value' )\n    az storage container create -n \"$artifactsStorageContainerName\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" >/dev/null 2>&1\n    \n    # Get a 4-hour SAS Token for the artifacts container. Fall back to OSX date syntax if Linux syntax fails.\n    plusFourHoursUtc=$(date -u -v+4H +%Y-%m-%dT%H:%MZ 2>/dev/null)  || plusFourHoursUtc=$(date -u --date \"$dte 4 hour\" +%Y-%m-%dT%H:%MZ)\n\n    sasToken=$( az storage container generate-sas -n \"$artifactsStorageContainerName\" --permissions r --expiry \"$plusFourHoursUtc\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" -o json | sed 's/\"//g')\n\n    blobEndpoint=$( az storage account show -n \"$artifactsStorageAccountName\" -g \"$artifactsResourceGroupName\" -o json | jq -r '.primaryEndpoints.blob' )\n\n    parameterJson=$( echo \"$parameterJson\"  | jq \"{_artifactsLocation: {value: \"\\\"$blobEndpoint$artifactsStorageContainerName\"\\\"}, _artifactsLocationSasToken: {value: \\\"?\"$sasToken\"\\\"}} + .\" )\n\n    artifactsStagingDirectory=$( echo \"$artifactsStagingDirectory\" | sed 's/\\/*$//')\n    artifactsStagingDirectoryLen=$((${#artifactsStagingDirectory} + 1))\n\n    for filepath in $( find \"$artifactsStagingDirectory\" -type f )\n    do\n        relFilePath=${filepath:$artifactsStagingDirectoryLen}\n        echo \"Uploading file $relFilePath...\"\n        az storage blob upload -f $filepath --container $artifactsStorageContainerName -n $relFilePath --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" --verbose\n    done\n\n    templateUri=$blobEndpoint$artifactsStorageContainerName/$(basename $templateFile)?$sasToken\n\nfi\n\naz group create -n \"$resourceGroupName\" -l \"$location\"\n\n# Remove line endings from parameter JSON so it can be passed in to the CLI as a single line\nparameterJson=$( echo \"$parameterJson\" | jq -c '.' )\n\nif [[ $validateOnly ]]\nthen\n    if [[ $uploadArtifacts ]]\n    then\n        az group deployment validate -g \"$resourceGroupName\" --template-uri $templateUri --parameters \"$parameterJson\" --verbose\n    else\n        az group deployment validate -g \"$resourceGroupName\" --template-file $templateFile --parameters \"$parameterJson\" --verbose\n    fi\nelse\n    if [[ $uploadArtifacts ]]\n    then\n        az group deployment create -g \"$resourceGroupName\" -n AzureRMSamples --template-uri $templateUri --parameters \"$parameterJson\" --verbose\n    else\n        az group deployment create -g \"$resourceGroupName\" -n AzureRMSamples --template-file $templateFile --parameters \"$parameterJson\" --verbose\n    fi\nfi\n", "num_lines": 127}
{"repo_name": "azure-arm-validator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#\n# this script is used to set the app up as a service to run in the bg\nsudo forever-service install armvalidator \u00e2\u20ac\u201c-script ./bin/www \n\n#After service installation, you can start service by running following command.\nsudo service armvalidator start\n\n#Check status if app is running or stopped\nsudo service armvalidator status\n\n#You can use other following commands for start/stop/ operations.\n#sudo service armvalidator stop #to stop app\n#sudo service armvalidator start #\n", "num_lines": 14}
{"repo_name": "azure-arm-validator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngit init\ngit config user.name \"Travis CI\"\ngit config user.email \"sedouard@microsoft.com\"\n\necho 'Adding files to local repo '\nls -ltr\ngit add .\ngit commit -m \"Deploy\"\n\nGIT_USERNAME=\"dokku\"\nGIT_TARGET_URL=\"${GIT_USERNAME}@${AZURE_WA_GIT_TARGET}:${DOKKU_APPNAME}\"\n\neval \"$(ssh-agent -s)\"\nssh-agent -s\n\n# write the trusted host to the known hosts file\n# to avoid a prompt when connecting to it via ssh\necho $DOKKU_SSH_PUBLIC_KNOWN_HOST > ~/.ssh/known_hosts\n\nchmod 600 ./dokku-deploy\nssh-add ./dokku-deploy\n\necho 'Private keys added. Starting Dokku Deployment'\ngit remote add $GIT_USERNAME $GIT_TARGET_URL\n\ngit push dokku master\n\necho 'Deployed Latest Version of Arm Validator'\n", "num_lines": 31}
{"repo_name": "azure-arm-validator", "repo_creator": "Azure", "programming_language": "Shell", "code": "# this scripts expects the following args\nuserName=\"$1\" #user name which will be used as the directory to clone the repo - usually the admin\nartifactsLocation=\"$2\"\nartifactsLocationSasToken=\"$3\"\n\n#appPath='/var/www/azure-arm-validator'\nappPath=\"/home/$userName/azure-arm-validator\"\nsudo mkdir $appPath\n\n# install azure cli - signing key has been changed - this will be broken\n#echo \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n#sudo apt-key adv --keyserver packages.microsoft.com --recv-keys 417A0893\n#sudo apt-get install apt-transport-https\n#sudo apt-get update && sudo apt-get install azure-cli\n\n# here is the fix for CLI install\nAZ_REPO=$(lsb_release -cs)\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\ncurl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https\nsudo apt-get update && sudo apt-get install azure-cli\n\n\n#install git\nsudo apt-get update\nsudo apt-get install git\n\n#install npm\nsudo apt-get install npm --assume-yes\nsudo apt-get install nodejs-legacy\nsudo npm install forever -g\nsudo npm install -g forever-service -g\n\n#Import the public key used by the package management system.\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927\n\n#Create a list file for MongoDB\necho \"deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list\n\n#Reload local package database.\nsudo apt-get update\n\n#Install the MongoDB packages.\nsudo apt-get install -y mongodb-org\n\n#Start MongoDB\nsudo service mongod start\n\n#Configure MongoDB to run on system startup automatically by running this command\nsudo systemctl enable mongod.service\n\n#install bits for the app\n#git clone https://github.com/Azure/azure-arm-validator \"/home/$userName/azure-arm-validator\" #should probably pass this in, instead of hardcoding it\ngit clone https://github.com/Azure/azure-arm-validator $appPath #should probably pass this in, instead of hardcoding it\n\n#Create a database where ARM validator will store its information.\n#We need to have at least one document inserted in the db. Use following command to insert document\nmongo 'arm-validator' --eval 'db[\"arm-validator\"].armvalidator.insert({\"name\":\"arm-validator-db\"})'\n\n#enable monog service\nsudo systemctl enable mongod.service\n\n#try to download the config file if it was staged.\necho \"$artifactsLocation.config.json$artifactsLocationSasToken\"\ncurl -v -f -o \"$appPath/.config.json\" \"$artifactsLocation.config.json$artifactsLocationSasToken\"\nrc=$?\nif test \"$rc\" != \"0\"; then\n    echo \"curl failed with: $rc\"\nelse #start the app if the config file was staged\n    echo \"start the service if the config file was installed\"\n    sudo cd \"$appPath\"\n    #sudo npm install\n\n    # copy the service file - not sure which one we need and this isn't working right not anyway\n    #sudo cp \"$appPath/azure-arm-validator.service\" '/etc/systemd/system'\n    #sudo cp \"$appPath/azure-arm-validator.service\" '/lib/systemd/system'\n    #sudo chmod +x \"$appPath/app.js\"\n    #reset the service daemon and start the service\n    #sudo systemctl daemon-reload\n    #sudo systemctl start azure-arm-validator\n    \n    #setup the forever service\n    #-----------------------------------------------------------------\n    # currently this isn't working for some reason, need to run this interactively after deployment finishes\n    npm install\n    sudo forever-service install armvalidator --script ./bin/www\n    sudo service armvalidator start\n\nfi\n\n#change ownership on the app, just to make life easier\nsudo chown -hR $userName \"$appPath\"\n\n\n\n", "num_lines": 96}
{"repo_name": "Azure-Backlog-Generator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nfor d in ./workitems/*/ ; do\n    echo `azbacklog --validate-only \"$d\"`\ndone", "num_lines": 5}
{"repo_name": "azure-batch-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nset -e\n\nscripts_root=$(cd $(dirname $0); pwd)\n\nexport PYTHONPATH=$PATHONPATH:./src\npython -m azure.cli --version\npython -m azure.cli -h --debug\npython -m azure.cli batch -h --debug\naz --version\npip freeze\npython -m azure.cli batch job create -h --debug\n\n# Check readme formatting for PyPI\npython ./setup.py check -r -s\n\n# PyLint crashes on Python 3.6\nLOCAL_PYTHON_VERSION=$(python -c 'import sys; print(\"{0}.{1}\".format(sys.version_info[0], sys.version_info[1]))')\nif [[ \"$TRAVIS_PYTHON_VERSION\" == \"3.6\" || \"$LOCAL_PYTHON_VERSION\" == \"3.6\" ]]; then\n    echo 'Skipping check_style since it is not supported in python 3.6'\nelse\n    check_style --ci;\nfi\n\n\nrun_tests\n\nif [[ \"$CI\" == \"true\" ]]; then\n    $scripts_root/package_verify.sh\nfi\n\npython $scripts_root/license/verify.py\n", "num_lines": 39}
{"repo_name": "azure-batch-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nexport PYTHONPATH=\nvirtualenv package-verify-env\n. package-verify-env/bin/activate\npython -m pip install -I pip==9.0.3\npip install -e scripts\npython -m automation.tests.verify_packages\ndeactivate\n# If we get here, all prev. commands returned 0 exit codes so we are done.\nrm -rf package-verify-env\n", "num_lines": 12}
{"repo_name": "azure-batch-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\npython -m automation.coverage.run\n", "num_lines": 9}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\nyum update -y\nyum install csh\nyum install mesa-libGLU.x86_64 -y\nyum install libXp-1.0.2-2.1.el7.x86_64 -y\nyum install libXmu-1.1.2-2.el7.x86_64 -y\nyum install libXpm -y\nyum install libXi -y\nyum install compat-libtiff3-3.9.4-11.el7.x86_64 -y\nyum install fontconfig -y\nyum install libXinerama-1.1.3-2.1.el7.x86_64 -y\nyum install gamin-0.1.10-16.el7.x86_64 -y\nyum install libpng12-1.2.50-10.el7.x86_64 -y\nyum install libXrender -y\nyum install libXcomposite-0.4.4-4.1.el7.x86_64 -y\nyum install libxslt-1.1.28-5.el7.x86_64 -y\nyum install pulseaudio-libs -y\nyum install libunwind -y\nyum install libicu -y\nyum install wget -y\nyum install which -y\nyum install rsync -y\nyum install tcsh -y\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\nsh -c 'echo -e \"[packages-microsoft-com-prod]\\nname=packages-microsoft-com-prod \\nbaseurl=https://packages.microsoft.com/yumrepos/microsoft-rhel7.3-prod\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/dotnetdev.repo'\nsh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\nyum install libunwind libicu -y\nyum install ImageMagick -y\nyum install dotnet-sdk-2.1.4 -y\nyum install epel-release -y\nyum install p7zip -y\nyum install azure-cli -y\nyum install sudo -y\n\necho 'Installing azcopy'\nwget -O azcopy.tar.gz https://aka.ms/downloadazcopyprlinux\ntar -xf azcopy.tar.gz\n./install.sh\n\nyum install python-pyasn1 WALinuxAgent -y\nyum clean all", "num_lines": 42}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2017 -p\nmkdir -m777 /tmp/maya/Maya2017 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2017_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2017_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2017_Linux_64bit -o/tmp/maya/Maya2017/\nchmod +x /tmp/maya/Maya2017/setup.sh\n/tmp/maya/Maya2017/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2017.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya.sh\nchmod +x /usr/bin/maya2017.sh\n\nrm -rf /tmp/maya2017\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'\n", "num_lines": 28}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2017/bin/Render \"$@\"\nexit $?\n", "num_lines": 4}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2017.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2017.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2017 -o/tmp/mtoa/MtoA2017\n7za x /tmp/mtoa/MtoA2017/package.zip -o/opt/solidangle/mtoa/2017/\n\ncp /opt/solidangle/mtoa/2017/arnoldRenderer.xml /usr/autodesk/mayaIO2017/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2017.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2017.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2017 -o/tmp/mtoa/MtoA2017\n7za x /tmp/mtoa/MtoA2017/package.zip -o/opt/solidangle/mtoa/2017/\n\ncp /opt/solidangle/mtoa/2017/arnoldRenderer.xml /usr/autodesk/mayaIO2017/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2017_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2017_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2017_linux_x64\n/tmp/vray/vray4batch_maya2017_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2017.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2018 -p\nmkdir -m777 /tmp/maya/Maya2018 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit -o/tmp/maya/Maya2018/\nchmod +x /tmp/maya/Maya2018/setup.sh\n/tmp/maya/Maya2018/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2018.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2018.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2018\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 27}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2018/bin/Render \"$@\"\nexit $?", "num_lines": 3}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2018_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2018_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2018_linux_x64\n/tmp/vray/vray4batch_maya2018_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2018.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2018 -p\nmkdir -m777 /tmp/maya/Maya2018 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit -o/tmp/maya/Maya2018/\nchmod +x /tmp/maya/Maya2018/setup.sh\n/tmp/maya/Maya2018/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2018.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2018.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2018\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 27}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2018/bin/Render \"$@\"\nexit $?", "num_lines": 3}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2018_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2018_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2018_linux_x64\n/tmp/vray/vray4batch_maya2018_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2018.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2018 -p\nmkdir -m777 /tmp/maya/Maya2018 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit -o/tmp/maya/Maya2018/\nchmod +x /tmp/maya/Maya2018/setup.sh\n/tmp/maya/Maya2018/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2018.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2018.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2018\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 27}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2018/bin/Render \"$@\"\nexit $?", "num_lines": 3}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2018_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2018_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2018_linux_x64\n/tmp/vray/vray4batch_maya2018_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2018.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2018 -p\nmkdir -m777 /tmp/maya/Maya2018 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit -o/tmp/maya/Maya2018/\nchmod +x /tmp/maya/Maya2018/setup.sh\n/tmp/maya/Maya2018/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2018.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2018.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2018\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 27}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2018/bin/Render \"$@\"\nexit $?", "num_lines": 3}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2018_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2018_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2018_linux_x64\n/tmp/vray/vray4batch_maya2018_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2018.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2018 -p\nmkdir -m777 /tmp/maya/Maya2018 -p\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2018_Linux_64bit -o/tmp/maya/Maya2018/\nchmod +x /tmp/maya/Maya2018/setup.sh\n/tmp/maya/Maya2018/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2018.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2018.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2018\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 27}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/autodesk/mayaIO2018/bin/Render \"$@\"\nexit $?", "num_lines": 3}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2018.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2018.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2018 -o/tmp/mtoa/MtoA2018\n7za x /tmp/mtoa/MtoA2018/package.zip -o/opt/solidangle/mtoa/2018/\n\ncp /opt/solidangle/mtoa/2018/arnoldRenderer.xml /usr/autodesk/mayaIO2018/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\necho '-=Download=-'\necho 'download vray4batch_maya2018_linux_x64'\nazcopy --source $INSTALLER_SAS --destination /tmp/vray/vray4batch_maya2018_linux_x64 \n\necho '-=Extract and Install=-'\nchmod +x /tmp/vray/vray4batch_maya2018_linux_x64\n/tmp/vray/vray4batch_maya2018_linux_x64 -gui=0 -configFile='/tmp/vray/vray_config2018.xml' -ignoreErrors=1\n\nrm -rf /tmp/vray\n\necho '-=Install script complete=-'", "num_lines": 16}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2019 -p\nmkdir -m777 /tmp/maya/Maya2019 -p\n\necho '-=Install Maya2019 specific dependencies=-'\nyum install gstreamer1 -y\nyum install gstreamer1-plugins-base -y\nyum clean all\n\necho '-=Download Installer=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2019_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2019_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2019_Linux_64bit -o/tmp/maya/Maya2019/\nchmod +x /tmp/maya/Maya2019/setup.sh\n/tmp/maya/Maya2019/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2019.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2019.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2019\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 32}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#Below is needed to prevent the following warning:\n#[mtoa] Error loading extension library: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#[mtoa] Error loading extension library: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#unable to load dynamic library /opt/solidangle/mtoa/2019/procedurals/xgen_procedural.so: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#unable to load dynamic library /opt/solidangle/mtoa/2019/procedurals/xgenSpline_procedural.so: libAdskSeExpr.so: cannot open shared object file: No such file or directory\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/autodesk/mayaIO2019/plug-ins/xgen/lib\n\n/usr/autodesk/mayaIO2019/bin/Render \"$@\"\nexit $?", "num_lines": 11}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-linux-2019.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-linux-2019.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-linux-2019 -o/tmp/mtoa/MtoA2019\n7za x /tmp/mtoa/MtoA2019/package.zip -o/opt/solidangle/mtoa/2019/\n\ncp /opt/solidangle/mtoa/2019/arnoldRenderer.xml /usr/autodesk/mayaIO2019/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/maya2019 -p\nmkdir -m777 /tmp/maya/Maya2019 -p\n\necho '-=Install Maya2019 specific dependencies=-'\nyum install gstreamer1 -y\nyum install gstreamer1-plugins-base -y\nyum clean all\n\necho '-=Download Installer=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/maya/Autodesk_MayaIO_2019_1_Update_Linux_64bit.run\n\necho '-=Extract and Install=-'\n7za e /tmp/maya/Autodesk_MayaIO_2019_1_Update_Linux_64bit.run -o/tmp/maya/\n7za e /tmp/maya/Autodesk_MayaIO_2019_1_Update_Linux_64bit -o/tmp/maya/Maya2019/\nchmod +x /tmp/maya/Maya2019/setup.sh\n/tmp/maya/Maya2019/setup.sh 127.0.0.1\n\ncp /usr/bin/maya2019.sh /usr/bin/maya.sh\n\nchmod +x /usr/bin/maya2019.sh\nchmod +x /usr/bin/maya.sh\n\nrm -rf /tmp/maya2019\nrm -rf /tmp/maya\nrm -rf /usr/autodesk/mayaIO\n\necho '-=Install script complete=-'", "num_lines": 32}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#Below is needed to prevent the following warning:\n#[mtoa] Error loading extension library: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#[mtoa] Error loading extension library: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#unable to load dynamic library /opt/solidangle/mtoa/2019/procedurals/xgen_procedural.so: libAdskSeExpr.so: cannot open shared object file: No such file or directory\n#unable to load dynamic library /opt/solidangle/mtoa/2019/procedurals/xgenSpline_procedural.so: libAdskSeExpr.so: cannot open shared object file: No such file or directory\nexport LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/autodesk/mayaIO2019/plug-ins/xgen/lib\n\n/usr/autodesk/mayaIO2019/bin/Render \"$@\"\nexit $?", "num_lines": 11}
{"repo_name": "azure-batch-rendering", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -x\n\necho 'INSTALLER_SAS='$1\nINSTALLER_SAS=$1\n\nmkdir -m777 /tmp/mtoa\n\necho '-=Download=-'\nazcopy --source $INSTALLER_SAS --destination /tmp/mtoa/MtoA-3.2.1.1-linux-2019.run\n\necho '-=Extract and Install=-'\n7za x /tmp/mtoa/MtoA-3.2.1.1-linux-2019.run -o/tmp/mtoa/\n7za x /tmp/mtoa/MtoA-3.2.1.1-linux-2019 -o/tmp/mtoa/MtoA2019\n7za x /tmp/mtoa/MtoA2019/package.zip -o/opt/solidangle/mtoa/2019/\n\ncp /opt/solidangle/mtoa/2019/arnoldRenderer.xml /usr/autodesk/mayaIO2019/bin/rendererDesc/\nchmod 755 -R /opt/solidangle\n\nrm -rf /tmp/mtoa\n\necho '-=Install script complete=-'", "num_lines": 21}
{"repo_name": "azure-blob-storage-file-upload-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# install-deps.sh makes it more convenient to install\n# dependencies for the Azure Blob Storage File Upload Utility.\n# Some dependencies are installed via packages and\n# others are installed from source code.\n\n# Ensure that getopt starts from first option if \". <script.sh>\" was used.\nOPTIND=1\n\n# Ensure we dont end the user's terminal session if invoked from source (\".\").\nif [[ $0 != \"${BASH_SOURCE[0]}\" ]]; then\n    ret=return\nelse\n    ret=exit\nfi\n\n# Use sudo if user is not root\nSUDO=\"\"\nif [ \"$(id -u)\" != \"0\" ]; then\n    SUDO=\"sudo\"\nfi\n\nwarn() { echo -e \"\\033[1;33mWarning:\\033[0m $*\" >&2; }\n\nerror() { echo -e \"\\033[1;31mError:\\033[0m $*\" >&2; }\n\n# Setup defaults\ninstall_all_deps=false\ninstall_packages=false\ninstall_packages_only=false\n# The folder where source code will be placed\n# for building and installing from source.\nwork_folder=/tmp\nkeep_source_code=false\nuse_ssh=false\n\n# Utility Deps\ninstall_abs_file_upload_utility_deps=false\n\nskip_azure_iot_sdk_install=false\ninstall_azure_iot_sdk=false\nazure_sdk_ref=main\n\ninstall_azure_storage_sdk=false\nazure_storage_sdk_branch_ref=main\nazure_storage_sdk_tag_ref=azure-core_1.6.0\n\n# Dependencies packages\nabs_utils_packages=('git' 'make' 'snap' 'build-essential' 'ninja-build' 'libcurl4-openssl-dev' 'uuid-dev' 'libssl-dev' 'lsb-release' 'curl' 'libxml2-dev' 'wget')\n\nprint_help() {\n    echo \"Usage: install-deps.sh [options...]\"\n    echo \"-a, --install-all-deps    Install all dependencies.\"\n    echo \"                          Implies --install-azure-blob-storage-deps and --install-packages.\"\n    echo \"                          Can be used with --install-packages-only.\"\n    echo \"                          This is the default if no options are specified.\"\n    echo \"\"\n    echo \"--install-azure-blob-storage-deps  Install dependencies for the Azure Blob Storage Utility\"\n    echo \"                                   Implies --install-azure-iot-sdk, --install-azure-storage-sdk, and --install-catch2.\"\n    echo \"                                   When used with --install-packages will also install the package dependencies.\"\n    echo \"--skip-azure-iot-sdk-install Skips the installation of the Azure IoT C SDK.\"\n    echo \"                             Used when the caller knows the Azure IoT C SDK has already been installed.\"\n    echo \"--install-azure-iot-sdk   Install the Azure IoT C SDK from source.\"\n    echo \"--azure-iot-sdk-ref <ref> Install the Azure IoT C SDK from a specific branch or tag.\"\n    echo \"                          Default is public-preview.\"\n    echo \"--install-azure-storage-sdk   Install the Azure C++ Lite Blob Storage SDK from source.\"\n    echo \"--azure-storage-sdk-ref <ref> Install the Azure C++ Lite Blob Storage SDK from a specific branch or tag.\"\n    echo \"\"\n    echo \"-p, --install-packages    Indicates that packages should be installed.\"\n    echo \"\"\n    echo \"--install-packages-only   Indicates that only packages should be installed and that dependencies should not be installed from source.\"\n    echo \"\"\n    echo \"-f, --work-folder <work_folder>   Specifies the folder where source code will be cloned or downloaded.\"\n    echo \"                                  Default is /tmp.\"\n    echo \"-k, --keep-source-code            Indicates that source code should not be deleted after install from work_folder.\"\n    echo \"\"\n    echo \"--use-ssh                 Use ssh URLs to clone instead of https URLs.\"\n    echo \"--list-deps               List the states of the dependencies.\"\n    echo \"-h, --help                Show this help message.\"\n    echo \"\"\n    echo \"Example: ${BASH_SOURCE[0]} --install-all-deps --work-folder ~/azure-blob-stroage-utiltiy --keep-source-code\"\n}\n\ndo_install_abs_file_upload_utility_deps() {\n    echo \"Installing dependency packages for the Azure Blob Storage Utility Agent...\"\n\n    $SUDO apt-get install --yes \"${abs_utils_packages[@]}\" || return\n\nif [[ \"$distro\" == \"debian11\" || \"$distro\" == \"ubuntu22.04\" ]]; then\n        $SUDO apt-get install --yes gcc-10 g++-10 || return\n    else\n        $SUDO apt-get install --yes gcc-8 g++-8 || return\n    fi\n\n    # The following is a workaround as IoT SDK references the following paths which don't exist\n    # on our target platforms, and without these folders existing, static analysis will report:\n    # (information) Couldn't find path given by -I '/usr/local/inc/'\n    # (information) Couldn't find path given by -I '/usr/local/pal/linux/'\n    $SUDO mkdir --parents /usr/local/inc /usr/local/pal/linux\n}\n\ndo_install_azure_iot_sdk() {\n    echo \"Installing Azure IoT C SDK ...\"\n    local azure_sdk_dir=$work_folder/azure-iot-sdk-c\n    if [[ $keep_source_code != \"true\" ]]; then\n        $SUDO rm -rf $azure_sdk_dir || return\n    elif [[ -d $azure_sdk_dir ]]; then\n        warn \"$azure_sdk_dir already exists! Skipping Azure IoT C SDK.\"\n        return 0\n    fi\n\n    local azure_sdk_url\n    if [[ $use_ssh == \"true\" ]]; then\n        azure_sdk_url=git@github.com:Azure/azure-iot-sdk-c.git\n    else\n        azure_sdk_url=https://github.com/Azure/azure-iot-sdk-c.git\n    fi\n\n    echo -e \"Building azure-iot-sdk-c ...\\n\\tBranch: $azure_sdk_ref\\n\\tFolder: $azure_sdk_dir\"\n    mkdir -p $azure_sdk_dir || return\n    pushd $azure_sdk_dir > /dev/null\n    git clone --branch $azure_sdk_ref $azure_sdk_url . || return\n    git submodule update --init || return\n\n    mkdir cmake || return\n    pushd cmake > /dev/null\n\n    # use_http is required for uHTTP support.\n    local azureiotsdkc_cmake_options=(\n        \"-Duse_amqp:BOOL=OFF\"\n        \"-Duse_http:BOOL=ON\"\n        \"-Duse_mqtt:BOOL=ON\"\n        \"-Dskip_samples:BOOL=ON\"\n        \"-Dbuild_service_client:BOOL=OFF\"\n        \"-Dbuild_provisioning_service_client:BOOL=OFF\"\n    )\n\n    if [[ $keep_source_code == \"true\" ]]; then\n        # If source is wanted, presumably samples and symbols are useful as well.\n        azureiotsdkc_cmake_options+=(\"-DCMAKE_BUILD_TYPE:STRING=Debug\")\n    else\n        azureiotsdkc_cmake_options+=(\"-Dskip_samples=ON\")\n    fi\n\n    cmake \"${azureiotsdkc_cmake_options[@]}\" .. || return\n\n    cmake --build . || return\n    $SUDO cmake --build . --target install || return\n\n    popd > /dev/null\n    popd > /dev/null\n\n    if [[ $keep_source_code != \"true\" ]]; then\n        $SUDO rm -rf $azure_sdk_dir || return\n    fi\n}\n\ndo_install_azure_storage_sdk() {\n    echo \"Installing azure-storage-sdk\"\n    local azure_storage_sdk_dir=$work_folder/azure_storage_sdk_dir\n\n    if [[ $keep_source_code != \"true\" ]]; then\n        $SUDO rm -rf $azure_storage_sdk_dir || return\n    elif [[ -d $azure_storage_sdk_dir ]]; then\n        warn \"$azure_storage_sdk_dir already exists! Skipping Azure Storage SDK.\"\n        return 0\n    fi\n\n    local azure_storage_sdk_url\n    if [[ $use_ssh == \"true\" ]]; then\n        azure_storage_sdk_url=git@github.com:Azure/azure-sdk-for-cpp.git\n    else\n        azure_storage_sdk_url=https://github.com/Azure/azure-sdk-for-cpp.git\n    fi\n    \n    echo -e \"Building Azure Storage SDK ...\\n\\tBranch: $azure_storage_sdk_branch_ref\\n\\t Folder: $azure_storage_sdk_dir\"\n    mkdir -p $azure_storage_sdk_dir || return\n    pushd $azure_storage_sdk_dir > /dev/null\n    git clone --recursive --single-branch --branch $azure_storage_sdk_branch_ref $azure_storage_sdk_url . || return\n\n    git checkout tags/$azure_storage_sdk_tag_ref\n\n    mkdir cmake || return\n    pushd cmake > /dev/null\n\n    local azure_blob_storage_file_upload_utility_cmake_options\n    if [[ $keep_source_code == \"true\" ]]; then\n        # If source is wanted, presumably samples and symbols are useful as well.\n        azure_blob_storage_file_upload_utility_cmake_options+=(\"-DCMAKE_BUILD_TYPE:STRING=Debug\")\n    else\n        azure_blob_storage_file_upload_utility_cmake_options+=(\"-DCMAKE_BUILD_TYPE:STRING=Release\")\n    fi\n    \n    local architecture \n    architecture=`uname -m`\n    echo \"${architecture}\"\n    local cmake_url\n    local cmake_tar_path\n    local cmake_dir_path\n    local cmake_build_from_source=false\n    if [[ \"${architecture}\" == \"x86_64\" ]]; then\n        echo \"Detected x86_64 architecture\"\n        echo \"Attempting to use existing binary for CMake\"\n        cmake_url=\"https://cmake.org/files/v3.19/cmake-3.19.8-Linux-x86_64.tar.gz\"\n        cmake_tar_path=\"./cmake-3.19.8-Linux-x86_64.tar.gz\"\n        cmake_dir_path=\"./cmake-3.19.8-Linux-x86_64/\"\n        cmake_build_from_source=false\n    elif [ \"${architecture}\" == \"aarch64\" ]; then\n        echo \"Detected aarch64 architecture\"\n        echo \"Attempting to use existing binary for CMake\"\n        cmake_url=\"https://cmake.org/files/v3.19/cmake-3.19.8-Linux-aarch64.tar.gz\"\n        cmake_tar_path=\"./cmake-3.19.8-Linux-aarch64.tar.gz\"\n        cmake_dir_path=\"./cmake-3.19.8-Linux-aarch64/\"\n        cmake_build_from_source=false\n    else\n        echo \"Unknown architecture... Attempting to build from source\"\n        echo \"Attempting to build CMake from source\"\n        cmake_url=\"https://cmake.org/files/v3.21/cmake-3.21.4.tar.gz\"\n        cmake_tar_path=\"./cmake-3.21.4.tar.gz\"\n        cmake_dir_path=\"./cmake-3.21.4/\"\n        cmake_build_from_source=true\n    fi\n\n    wget ${cmake_url}  \n    tar -zxvf ${cmake_tar_path} \n\n    if [[ $cmake_build_from_source == \"true\"  ]]; then\n        echo \"Building CMake from source.\"\n        pushd $cmake_dir_path > /dev/null\n        ./bootstrap  \n        make > /dev/null\n        popd > /dev/null   \n    fi\n    \n    ${cmake_dir_path}/bin/cmake \"${azure_blob_storage_file_upload_utility_cmake_options[@]}\" .. || return\n\n    ${cmake_dir_path}/bin/cmake --build . || return\n    $SUDO ${cmake_dir_path}/bin/cmake --build . --target install || return\n\n    rm -fr ${cmake_dir_path}\n    rm -fr ${cmake_tar_path}\n\n    popd > /dev/null\n    popd > /dev/null\n\n    if [[ $keep_source_code != \"true\" ]]; then\n        $SUDO rm -rf $azure_storage_sdk_dir || return\n    fi\n}\n\ndetermine_machine_architecture() {\n    local arch=''\n    arch=\"$(uname -m)\"\n    local ret_val=$?\n    if [[ $ret_val != 0 ]]; then\n        error \"Failed to get cpu architecture.\"\n        return 1\n    else\n        if [[ $arch == aarch64* || $arch == armv8* ]]; then\n            is_arm64=true\n        elif [[ $arch == armv7* || $arch == 'arm' ]]; then\n            is_arm32=true\n        elif [[ $arch == 'x86_64' || $arch == 'amd64' ]]; then\n            is_amd64=true\n        else\n            error \"Machine architecture '$arch' is not supported.\"\n            return 1\n        fi\n    fi\n}\n\ndetermine_distro_and_arch() {\n    # Checking distro name and version\n    if [ -r /etc/os-release ]; then\n        # freedesktop.org and systemd\n        OS=$(grep \"^ID\\s*=\\s*\" /etc/os-release | sed -e \"s/^ID\\s*=\\s*//\")\n        VER=$(grep \"^VERSION_ID=\" /etc/os-release | sed -e \"s/^VERSION_ID=//\")\n        VER=$(sed -e 's/^\"//' -e 's/\"$//' <<< \"$VER\")\n    elif type lsb_release > /dev/null 2>&1; then\n        # linuxbase.org\n        OS=$(lsb_release -si)\n        VER=$(lsb_release -sr)\n    elif [ -f /etc/lsb-release ]; then\n        # For some versions of Debian/Ubuntu without lsb_release command\n        OS=$(grep DISTRIB_ID /etc/lsb-release | awk -F'=' '{ print $2 }')\n        VER=$(grep DISTRIB_RELEASE /etc/lsb-release | awk -F'=' '{ print $2 }')\n    elif [ -f /etc/debian_version ]; then\n        # Older Debian/Ubuntu/etc.\n        OS=Debian\n        VER=$(cat /etc/debian_version)\n    else\n        # Fall back to uname, e.g. \"Linux <version>\", also works for BSD, etc.\n        OS=$(uname -s)\n        VER=$(uname -r)\n    fi\n\n    # Convert OS to lowercase\n    OS=\"$(echo \"$OS\" | tr '[:upper:]' '[:lower:]')\"\n\n    determine_machine_architecture || return 1\n}\n\ndo_list_all_deps() {\n    declare -a deps_set=()\n    deps_set+=(${abs_utils_packages[@]})\n    deps_set+=(${compiler_packages[@]})\n    echo \"Listing the state of dependencies:\"\n    dpkg-query -W -f='${binary:Package} ${Version} (${Architecture})\\n' \"${deps_set[@]}\"\n    ret_val=$?\n    if [ $ret_val -eq 1 ]; then\n        warn \"dpkg-query failed\"\n        return 0\n    elif [ $ret_val -ge 2 ]; then\n        error \"dpkg-query failed with status $ret_val\"\n        return $ret_val\n    fi\n    return 0\n}\n\n###############################################################################\n\n# Check if no options were specified.\nif [[ $1 == \"\" ]]; then\n    error \"Must specify at least one option.\"\n    $ret 1\nfi\n\n# Parse cmd options\nwhile [[ $1 != \"\" ]]; do\n    case $1 in\n    -a | --install-all-deps)\n        install_all_deps=true\n        ;;\n    --install-azure-blob-storage-deps)\n        install_abs_file_upload_utility_deps=true\n        ;;\n    --install-azure-iot-sdk)\n        install_azure_iot_sdk=true\n        ;;\n    --azure-iot-sdk-ref)\n        shift\n        azure_sdk_ref=$1\n        ;;\n    --skip-azure-iot-sdk-install)\n        shift\n        skip_azure_iot_sdk_install=true\n        ;;\n    --install-azure-storage-sdk)\n        shift\n        install_azure_storage_sdk=true\n        ;;\n    --azure-storage-sdk-ref)\n        shift\n        azure_storage_sdk_ref=$1\n        ;;\n    -p | --install-packages)\n        install_packages=true\n        ;;\n    --install-packages-only)\n        install_packages_only=true\n        ;;\n    -f | --work-folder)\n        shift\n        work_folder=$(realpath \"$1\")\n        ;;\n    -k | --keep-source-code)\n        keep_source_code=true\n        ;;\n    --use-ssh)\n        use_ssh=true\n        ;;\n    --list-deps)\n        do_list_all_deps\n        $ret $?\n        ;;\n    -h | --help)\n        print_help\n        $ret 0\n        ;;\n    *)\n        error \"Invalid argument: $*\"\n        $ret 1\n        ;;\n    esac\n    shift\ndone\n\n# Get OS, VER, machine architecture for use in other parts of the script.\ndetermine_distro_and_arch\ndistro=$OS$VER\nif [[ \"$distro\" == \"debian11\" ]]; then\n    compiler_packages=(gcc-10)\nelse\n    compiler_packages=(gcc-8)\nfi\n\n# If there is no install action specified,\n# assume that we want to install all deps.\nif [[ $install_all_deps != \"true\" && $install_abs_file_upload_utility_deps != \"true\" && $install_azure_iot_sdk != \"true\" ]]; then\n    install_all_deps=true\nfi\n\n# If --all was specified,\n# set all install actions to \"true\".\nif [[ $install_all_deps == \"true\" ]]; then\n    install_abs_file_upload_utility_deps=true\n    install_packages=true\nfi\n\n# Set implied options for aduc deps.\nif [[ $install_abs_file_upload_utility_deps == \"true\" ]]; then\n\n    if [[ $skip_azure_iot_sdk_install == \"true\" ]]; then\n        install_azure_iot_sdk=false\n    else\n        install_azure_iot_sdk=true\n    fi\n    install_azure_storage_sdk=true\nfi\n\n# Set implied options for packages only.\nif [[ $install_packages_only == \"true\" ]]; then\n    install_packages=true\n    install_azure_iot_sdk=false\nfi\n\nif [[ $install_packages == \"true\" ]]; then\n    # Check if we need to install any packages\n    # before we call apt update.\n    if [[ $install_abs_file_upload_utility_deps == \"true\" ]]; then\n        echo \"Updating repository list...\"\n        $SUDO apt-get update --yes --fix-missing --quiet || $ret\n    fi\nfi\n\nif [[ $install_abs_file_upload_utility_deps == \"true\" ]]; then\n    do_install_abs_file_upload_utility_deps || $ret\nfi\n\n# Install dependencies from source\nif [[ $install_packages_only == \"false\" ]]; then\n    if [[ $install_azure_iot_sdk == \"true\" ]]; then\n        do_install_azure_iot_sdk || $ret\n    fi\n\n    if [[ $install_azure_storage_sdk == \"true\" ]]; then\n        do_install_azure_storage_sdk || $ret\n    fi\nfi\n\n# After installation, it prints out the states of dependencies\nif [[ $install_abs_file_upload_utility_deps == \"true\" || $install_packages_only == \"true\" || $install_packages == \"true\" ]]; then\n    do_list_all_deps || $ret $?\nfi\n", "num_lines": 456}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n\nset -e\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/../..\" && pwd)\nrun_unit_tests=ON\nmake_install=\nrun_valgrind=0\nrun_unittests=OFF\n\nusage ()\n{\n    echo \"build.sh [options]\"\n    echo \"options\"\n    echo \" -cl, --compileoption <value>  specify a compile option to be passed to gcc\"\n    echo \"   Example: -cl -O1 -cl ...\"\n    echo \"-rv, --run_valgrind will execute ctest with valgrind\"\n    echo \"--run-unittests run the unit tests\"\n\n    exit 1\n}\n\nprocess_args ()\n{\n    save_next_arg=0\n    extracloptions=\" \"\n\n    for arg in $*\n    do\n      if [ $save_next_arg == 1 ]\n      then\n        # save arg to pass to gcc\n        extracloptions=\"$arg $extracloptions\"\n        save_next_arg=0\n      elif [ $save_next_arg == 2 ]\n\t  then\n        build_root=\"$arg\"\n        save_next_arg=0\n      else\n          case \"$arg\" in\n              \"-cl\" | \"--compileoption\" ) save_next_arg=1;;\n              \"-i\" | \"--install\" ) make_install=1;;\n              \"-rv\" | \"--run_valgrind\" ) run_valgrind=1;;\n              \"--run-unittests\" ) run_unittests=ON;;\n              \"--build-root\" ) save_next_arg=2;;\n              * ) usage;;\n          esac\n      fi\n    done\n}\n\nprocess_args $*\nlog_dir=$build_root\nbuild_folder=$build_root\"/cmake/shared-util_linux\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake -DcompileOption_C:STRING=\"$extracloptions\" -Drun_valgrind:BOOL=$run_valgrind $build_root -Drun_unittests:BOOL=$run_unittests\nmake --jobs=$CORES\nif [[ $make_install == 1 ]] ;\nthen\n    echo \"Installing packaging\" \n    # install the package\n    make install\nfi\n\nif [[ $run_valgrind == 1 ]] ;\nthen\n\t#use doctored openssl\n\texport LD_LIBRARY_PATH=/usr/local/ssl/lib\n\tctest -j $CORES --output-on-failure\n\texport LD_LIBRARY_PATH=\nelse\n\tctest -j $CORES -C \"Debug\" --output-on-failure\nfi\n\npopd\n", "num_lines": 85}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -o errexit # Exit if command failed.\nset -o pipefail # Exit if pipe failed.\n\n# Only for testing E2E behaviour !!! \nTEST_CORES=16\n\n# Refresh dynamic libs to link to\nsudo ldconfig\n\nctest -T test --no-compress-output -C \"Debug\" -V -j $TEST_CORES --schedule-random\n\n", "num_lines": 17}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake -Drun_valgrind:BOOL=ON $build_root -Drun_unittests:BOOL=ON\nmake --jobs=$CORES\n\npopd\n", "num_lines": 22}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_bearssl:BOOL=ON -Drun_unittests:BOOL=ON -Duse_openssl:BOOL=OFF -D CMAKE_C_COMPILER=gcc\ncd cmake\n\nmake --jobs=$CORES\n\nctest -j $CORES --output-on-failure\n", "num_lines": 20}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_bearssl:BOOL=ON -Drun_unittests:BOOL=ON -Duse_openssl:BOOL=OFF -D CMAKE_C_COMPILER=clang -D CMAKE_CXX_COMPILER=clang++\ncd cmake\n\nmake --jobs=$CORES\n\n", "num_lines": 19}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_c_ares:BOOL=ON -Drun_e2e_tests:BOOL=ON\ncd cmake\n\nmake --jobs=$CORES\n", "num_lines": 21}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nMAKE_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\necho \"Initial MAKE_CORES=$MAKE_CORES\"\n\n# Make sure there is enough virtual memory on the device to handle more than one job  \nMINVSPACE=\"1500000\"\n\n# Acquire total memory and total swap space setting them to zero in the event the command fails\nMEMAR=( $(sed -n -e 's/^MemTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' -e 's/^SwapTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' /proc/meminfo) )\n[ -z \"${MEMAR[0]##*[!0-9]*}\" ] && MEMAR[0]=0\n[ -z \"${MEMAR[1]##*[!0-9]*}\" ] && MEMAR[1]=0\n\nlet VSPACE=${MEMAR[0]}+${MEMAR[1]}\n\nif [ \"$VSPACE\" -lt \"$MINVSPACE\" ] ; then\necho \"WARNING: Not enough space.  Setting MAKE_CORES=1\"\nMAKE_CORES=1\nfi\n\ndeclare -a arr=(\n    \"-Dskip_samples=ON\"\n    \"-Dno_logging=ON\"\n    \"-Denable_raw_logging=ON\"\n    \"-Denable_raw_logging=ON -Dno_logging=ON\"\n    \"-Duse_builtin_httpapi=ON\"\n    \"-Duse_default_uuid=ON\"\n    \"-Dno_openssl_engine=ON\"\n    \"-Duse_http=OFF\"\n)\n\nfor item in \"${arr[@]}\"\ndo\n    rm -r -f $build_folder\n    mkdir -p $build_folder\n    pushd $build_folder\n\n    echo \"executing cmake/make with options <<$item>>\"\n    cmake $build_root \"$item\"\n\n    make --jobs=$MAKE_CORES\ndone\npopd\n", "num_lines": 60}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\nclone_root=$(cd \"$(dirname \"$0\")/../..\" && pwd)\ncd $build_root\n\necho \"Build Root $build_root\"\n\nsdk_build_folder=$build_root\"/cmake\"\n\n# Build the SDK\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root\nmake install --jobs=$CORES\npopd\n\n# Now use the deps\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root -Duse_installed_dependencies=ON\nmake --jobs=$CORES\npopd\n", "num_lines": 37}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake -Drun_valgrind:BOOL=ON -Duse_mbedtls=ON -Duse_openssl=OFF $build_root -Drun_unittests:BOOL=ON -D CMAKE_C_COMPILER=gcc -D CMAKE_CXX_COMPILER=g++\nmake --jobs=$CORES\n\nctest -j $CORES --output-on-failure\n\npopd\n", "num_lines": 24}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake -Drun_valgrind:BOOL=ON -Duse_mbedtls=ON -Duse_openssl=OFF $build_root -Drun_unittests:BOOL=ON -D CMAKE_C_COMPILER=clang -D CMAKE_CXX_COMPILER=clang++\nmake --jobs=$CORES\n\npopd\n", "num_lines": 22}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake $build_root -Drun_unittests:BOOL=ON -Duse_wolfssl:BOOL=ON -Duse_openssl:BOOL=OFF -D CMAKE_C_COMPILER=gcc\nmake --jobs=$CORES\n\n#use doctored openssl\nexport LD_LIBRARY_PATH=/usr/local/ssl/lib\nctest -j $CORES --output-on-failure\nexport LD_LIBRARY_PATH=\n\npopd\n", "num_lines": 27}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake $build_root -Drun_unittests:BOOL=ON -Duse_wolfssl:BOOL=ON -Duse_openssl:BOOL=OFF -D CMAKE_C_COMPILER=clang -D CMAKE_CXX_COMPILER=clang++\nmake --jobs=$CORES\n\npopd\n", "num_lines": 22}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n\nset -e\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake .. -DOPENSSL_ROOT_DIR:PATH=/usr/local/opt/openssl -Duse_openssl:bool=ON -Drun_unittests:bool=ON\ncmake --build . -- --jobs=$CORES\n", "num_lines": 19}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n\nset -e\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake .. -Drun_unittests:bool=ON -G Xcode\ncmake --build . -- --jobs=$CORES\nctest -C \"debug\" -V\npopd\n", "num_lines": 21}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved. Licensed under the MIT \n# license. See LICENSE file in the project root for full license \n# information.\n\n# Tested on RPi2 debian verion 7.8\n\ninstall_root=\"/home/jenkins\" \nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd) \ncd $build_root\n\n# ----------------------------------------------------------------------------- \n# -- helper subroutines \n# -----------------------------------------------------------------------------\ncheckExists() {\n    if hash $1 2>/dev/null;\n    then\n        return 1\n    else\n        echo \"$1\" not found. Please make sure that \"$1\" is installed and available in the path.\n        exit 1\n    fi\n}\n\n# ----------------------------------------------------------------------------- \n# -- Check for environment pre-requisites. This script requires -- that \n# the following programs work: -- curl build-essential(g++,gcc,make) \n# cmake git \n# -----------------------------------------------------------------------------\ncheckExists curl \ncheckExists g++ \ncheckExists gcc \ncheckExists make \ncheckExists cmake \ncheckExists git\n\n# ----------------------------------------------------------------------------- \n# -- Check for RPiTools directory.\n# -----------------------------------------------------------------------------\nif [ ! -d \"$install_root/RPiTools\" ];\nthen\n    echo ---------- Raspberry Pi tool-chain absent ----------\n    exit 1\nfi\n\n# ----------------------------------------------------------------------------- \n# -- Set environment variable\n# -----------------------------------------------------------------------------\ncd $install_root/RPiTools/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/arm-linux-gnueabihf \nexport RPI_ROOT=$(pwd)\n\n# ----------------------------------------------------------------------------- \n# -- Create toolchain-rpi.cmake \n# -----------------------------------------------------------------------------\necho ---------- Creating toolchain cmake file ---------- \nFILE=\"$build_root/build_all/linux/toolchain-rpi.cmake\"\n\n/bin/cat <<EOM >$FILE\nINCLUDE(CMakeForceCompiler) \n\nSET(CMAKE_SYSTEM_NAME Linux) # this one is important \nSET(CMAKE_SYSTEM_VERSION 1) # this one not so much\n\n# this is the location of the amd64 toolchain targeting the Raspberry Pi\nSET(CMAKE_C_COMPILER ${RPI_ROOT}/../bin/arm-linux-gnueabihf-gcc)\n\n# this is the file system root of the target\nSET(CMAKE_FIND_ROOT_PATH ${RPI_ROOT})\n\n# search for programs in the build host directories\nSET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n\n# for libraries and headers in the target directories\nSET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) \nSET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) \nEOM\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\n\ncmake -DCMAKE_TOOLCHAIN_FILE=$FILE -DcompileOption_C:STRING=\"--sysroot=$RPI_ROOT\" $build_root -Duse_wsio:BOOL=ON\nmake --jobs=$CORES\n\n[ $? -eq 0 ] || exit $?\n", "num_lines": 91}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# assume directory is root of downloaded repo\nmkdir cmake\ncd cmake\nls -al\n\n# Create a cmake toolchain file on the fly\necho \"SET(CMAKE_SYSTEM_NAME Linux)     # this one is important\" > toolchain.cmake\necho \"SET(CMAKE_SYSTEM_VERSION 1)      # this one not so much\" >> toolchain.cmake\n\necho \"SET(CMAKE_C_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-gcc)\" >> toolchain.cmake\necho \"SET(CMAKE_CXX_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-g++)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH ${TOOLCHAIN_SYSROOT})\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\" >> toolchain.cmake\nls -al\n\n# Build the SDK. This will use the OpenSSL, cURL and uuid binaries that we built before\ncmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake -Duse_prov_client=OFF -DCMAKE_INSTALL_PREFIX=${TOOLCHAIN_PREFIX} -Drun_e2e_tests=ON -Drun_unittests=ON ..\nmake -j 2\nls -al\n", "num_lines": 23}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake $build_root -Drun_unittests:BOOL=ON -Drun_valgrind:BOOL=ON\nmake --jobs=$CORES\n\npopd\n", "num_lines": 22}
{"repo_name": "azure-c-shared-utility", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n\nset -e\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake .. -Drun_valgrind:BOOL=ON -Drun_unittests:bool=ON\ncmake --build . -- --jobs=$(nproc)\n\npopd\n:", "num_lines": 19}
{"repo_name": "azure-capi-cli-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#-------------------------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information.\n#-------------------------------------------------------------------------------------------------------------\n#\n# Create a python 3 virtual environment for developing this Azure CLI extension.\n#\n# Syntax: ./create-dev-env.sh\n#\n\nset -x\n\npython3 -m venv env\n\n# Activate the virtualenv automatically in GitHub Codespace shells\nif [ \"$CODESPACES\" == \"true\" ]; then\n    echo 'if [ -d \"./env\" ]; then source ./env/bin/activate; fi' >> ~/.bashrc\n    echo 'if [ -d \"./env\" ]; then source ./env/bin/activate; fi' >> ~/.zshrc\nfi\n\nsource ./env/bin/activate\npip install --upgrade pip\npip install -r requirements.txt\npip install azdev\nazdev setup --repo . --ext capi --verbose\n", "num_lines": 27}
{"repo_name": "Azure-Center-for-SAP-solutions-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# <copyright file=\"DownloadDeployerVMPackages.sh\" company=\"Microsoft Corporation\">\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# </copyright>\n\n#!/bin/bash\n\n#Exit when any command fails\nset -e\n\n#download packages locally\n\nworkloadWorkdir=DeployerVMPackages\n\nif [[ ! -d \"$workloadWorkdir\" ]]; then\n        mkdir $workloadWorkdir\nfi\n\nif [[ ! -d \"$workloadWorkdir/packages\" ]]; then\n        mkdir $workloadWorkdir/packages\nfi\n\n#download python3-pip\ncd $workloadWorkdir/packages\n\nif [[ ! -f \"pip-21.3.1.tar.gz\" ]]; then\n        wget -nv -q https://files.pythonhosted.org/packages/da/f6/c83229dcc3635cdeb51874184241a9508ada15d8baa337a41093fab58011/pip-21.3.1.tar.gz\n        tar -xvf pip-21.3.1.tar.gz\nfi\n\ncd pip-21.3.1/\n\n#Check if pip3 is already installed\nif [[ -z $(which pip3) ]]; then\n        #Install pip\n        echo \"Installing pip3.\"\n        sudo python3 setup.py install\nfi\n\ncd ../../..\n#download wheel\npip3 download -d $workloadWorkdir/packages wheel==0.37.1\n\n#download netaddr\npip3 download -d $workloadWorkdir/packages netaddr==0.8.0\n\n#download jq 1.6\nif [[ ! -d \"$workloadWorkdir/jq_pkg\" ]]; then\n        mkdir $workloadWorkdir/jq_pkg\nfi\n\ncd $workloadWorkdir/jq_pkg\nwget -O jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64\nchmod +x jq\n\ncd -\n#download ansible\nif [[ ! -d \"$workloadWorkdir/ansible_pkg\" ]]; then\n        mkdir $workloadWorkdir/ansible_pkg\nfi\npip3 download -d $workloadWorkdir/ansible_pkg \"ansible==2.9.27\"\n\n#download azure cli libraries\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg\nfi\n\ncd $workloadWorkdir/azure_cli_pkg\nwget -nv -q https://raw.githubusercontent.com/Azure/azure-cli/azure-cli-2.30.0/src/azure-cli/requirements.py3.Linux.txt\n\ncd -\nif [[ ! -d \"$workloadWorkdir/azure_cli_pkg/azure_cli_requirements\" ]]; then\n        mkdir $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\nfi\n\npip3 download -r $workloadWorkdir/azure_cli_pkg/requirements.py3.Linux.txt -d $workloadWorkdir/azure_cli_pkg/azure_cli_requirements\n\n#Check if zip is already installed\nif [[ -z $(which zip) ]]; then\n        echo \"Installing zip package.\"\n        #Install zip\n        sudo apt-get --assume-yes install zip\nfi\n\nzip -r $workloadWorkdir.zip $workloadWorkdir\n\n#Check if user have an existing storage account\necho \"Do you have an existing storage account?\"\necho -n \"y/n: \"\nread -r userInput\n\nif [[ ${userInput^^} == \"Y\" ]]; then\n        #sapbits_location_base_path  \n        echo \"Enter the SAP storage account base path(sapbits-location-base-path) url copied from storage container properties. This is the storage container where SAP installation bits and deployer vm packages are stored/will be stored.\"\n        read -r sapbits_location_base_path\n\n        #check if customer entered an empty string\n        while [ -z $sapbits_location_base_path ]\n        do    \n            echo \"Empty sapbits-location-base-path given, please re-enter the SAP storage account base path(sapbits-location-base-path) url else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r sapbits_location_base_path\n\n            if [[ ${sapbits_location_base_path^^} == \"EXIT\" ]]; then\n                    exit 1\n            fi\n        done\n        IFS='//'\n        read -ra arr <<< $sapbits_location_base_path \n        container=${arr[3]} \n\n        IFS='.'\n        read -ra arr <<< ${arr[2]}\n        storageAccountName=${arr[0]} \n\n        #Fetch container name\n        IFS='\"'\n        read -ra arr <<< $container\n        containerName=${arr[0]}\nelse\n        #Storage account name\n        echo \"Enter the new storage account name you want to create.\"\n        read -r storageAccountName\n        while [ -z $storageAccountName ]\n        do    \n            echo \"Empty storage account name given, please re-enter the storage account name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r storageAccountName\n\n            if [[ ${storageAccountName^^} == \"EXIT\" ]]; then\n                    exit 2\n            fi\n        done  \n\n        #Check subscription\n        subscription=$(az account show --query name)\n        echo \"Current subscription is $subscription, do you want to change the subscription? This is the subscription where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the new subscription name or id. (Use az account list to get a list of subscriptions for the logged in account).\"\n                read -r subscription\n                az account set --subscription \"$subscription\"\n        fi\n\n        echo \"Do you want to use an existing resource group? This is the resource group where storage account will be created.\"\n        echo -n \"y/n: \"\n        read -r userInput\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                echo \"Enter the resource group name.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 3\n                    fi\n                done\n        else\n                echo \"Enter the new resource group name to create a new resource group.\"\n                read -r resourceGroupName\n                while [ -z $resourceGroupName ]\n                do    \n                    echo \"Empty resource group name given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupName\n\n                    if [[ ${resourceGroupName^^} == \"EXIT\" ]]; then\n                            exit 4\n                    fi\n                done\n\n                echo \"Enter the location where you want to create resource group.\"\n                read -r resourceGroupLocation\n                while [ -z $resourceGroupLocation ]\n                do    \n                    echo \"Empty resource group locaion given, please re-enter the resource group name else press 'Ctrl+C' or type 'exit' to end the process.\"\n                    read -r resourceGroupLocation\n\n                    if [[ ${resourceGroupLocation^^} == \"EXIT\" ]]; then\n                            exit 5\n                    fi\n                done\n                az group create --location $resourceGroupLocation --name $resourceGroupName\n        fi\n\n        echo \"Creating storage account $storageAccountName in resource group $resourceGroupName and subscription $subscription\"\n        az storage account create --name $storageAccountName --resource-group $resourceGroupName\n\n        #Container name\n        echo \"Enter the new container name you want to create.\"\n        read -r containerName\n        while [ -z $containerName ]\n        do    \n            echo \"Empty container name given, please re-enter the container name else press 'Ctrl+C' or type 'exit' to end the process.\"\n            read -r containerName\n\n            if [[ ${containerName^^} == \"EXIT\" ]]; then\n                    exit 6\n            fi\n        done\n        \n        echo \"Create container $containerName in storage account $storageAccountName\"\n        az storage container create --name $containerName --account-name $storageAccountName\nfi\n\n#sapbits-access-key\necho \"Enter the sapbits-access-key copied from storage account 'Access keys'.\"   \nread -r sapbits_access_key\n\n#Repeat while loop until customer enters a non empty sapbits-access-key\nwhile [ -z $sapbits_access_key ]\ndo\n    read -r sapbits_access_key\n    echo \"No sapbits-access-key detected, please re-enter the sapbits-access-key else press 'Ctrl+C' or type 'exit' to end the process.\"\n\n    if [[ ${sapbits_access_key^^} == \"EXIT\" ]]; then\n            exit 7\n    fi\ndone\n    \necho \"Storage account name where deployer vm packages are stored/will be stored: $storageAccountName.\"\necho \"Container name where deployer vm packages are stored/will be stored: $containerName/deployervmpackages.\"\n\nisBlobExists=$(az storage blob exists --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --query exists)\n\nif [[ $isBlobExists == \"false\" ]]; then\n        #upload to storage account\n        az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\nelse\n        echo \"Existing blob $workloadWorkdir.zip found in storage account, do you want to update the blob?\"\n        echo -n \"y/n: \"\n        read -r userInput\n\n        if [[ ${userInput^^} == \"Y\" ]]; then\n                #delete existing blob\n                az storage blob delete --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip\n                az storage blob upload --account-name $storageAccountName --account-key \"$sapbits_access_key\" --container-name $containerName/deployervmpackages --name $workloadWorkdir.zip --file $workloadWorkdir.zip --if-none-match \"*\" --no-progress\n        fi\nfi\n\n", "num_lines": 241}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#######################################################################################################################\n# This script installs all dependencies found in this repository directly, without transitive dependencies, then uses\n# the appropriate requirements.txt file to install all transitive dependencies.\n#\n# NOTE: It should be invoked from an activated virtual environment, unless targeting system python directly is\n# acceptable.\n#\n# The intention is to allow packagers, people working with the RPM spec or debian rules file for example, to not have\n# duplicate that logic required to install from source what is distributed in this repository and via PyPI for items\n# living outside of this repository.\n#######################################################################################################################\n\nREPO_ROOT=\"$(dirname ${BASH_SOURCE[0]})/..\"\n\npushd ${REPO_ROOT} > /dev/null\n\nfind src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip install --no-deps\npip install -r ./src/azure-cli/requirements.$(python ./scripts/get-python-version.py).$(uname).txt\n\npopd > /dev/null\n", "num_lines": 23}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Build wheel and set the $share_folder to the artifacts folder\n\n. $(dirname ${BASH_SOURCE[0]})/build.sh\nshare_folder=$(pwd)/artifacts\n", "num_lines": 6}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build wheel packages containing both CLI product and tests. The script doesn't rely on a pre-existing virtual\n# environment.\n\nset -ev\n\n##############################################\n# clean up and dir search\nmkdir -p ./artifacts\n\n# Current folder (/azure-cli) is mounted from host which has different owner than docker container's\n# current user 0(root).\n# https://github.blog/2022-04-12-git-security-vulnerability-announced/\ngit config --global --add safe.directory $(pwd)\necho `git rev-parse --verify HEAD` > ./artifacts/build.sha\n\nmkdir -p ./artifacts/build\nmkdir -p ./artifacts/source\nmkdir -p ./artifacts/testsrc\n\noutput_dir=$(cd artifacts/build && pwd)\nsdist_dir=$(cd artifacts/source && pwd)\ntestsrc_dir=$(cd artifacts/testsrc && pwd)\nscript_dir=`cd $(dirname $BASH_SOURCE[0]); pwd`\n\ntarget_profile=${AZURE_CLI_TEST_TARGET_PROFILE:-latest}\nif [ \"$target_profile\" != \"latest\" ]; then\n    # example: hybrid-2019-03-01. Python module name can't begin with a digit.\n    target_profile=hybrid_${target_profile//-/_}\nfi\necho Pick up profile: $target_profile\n\n##############################################\n# Define colored output func\nfunction title {\n    LGREEN='\\033[1;32m'\n    CLEAR='\\033[0m'\n\n    echo -e ${LGREEN}$1${CLEAR}\n}\n\n##############################################\n# Update version strings\ntitle 'Determine version'\n. $script_dir/version.sh $1\n# echo -n $version > ./artifacts/version\n\n##############################################\n# build product packages\ntitle 'Build Azure CLI and its command modules'\nfor setup_file in $(find src -name 'setup.py'); do\n    pushd $(dirname ${setup_file}) >/dev/null\n    echo \"Building module at $(pwd) ...\"\n    python setup.py -q bdist_wheel -d $output_dir\n    python setup.py -q sdist -d $sdist_dir\n    popd >/dev/null\ndone\n\n##############################################\n# copy private packages\nif [ -z ./privates ]; then\n    cp ./privates/*.whl $output_dir\nfi\n\n##############################################\n# build test packages\ntitle 'Build Azure CLI tests package'\n\nfor test_src in $(find src/azure-cli/azure/cli/command_modules -name tests -type d); do\n    rel_path=${test_src##src/azure-cli/}\n\n    mkdir -p $testsrc_dir/$rel_path\n    cp -R $test_src/* $testsrc_dir/$rel_path\ndone\n\nif [ \"$target_profile\" == \"latest\" ]; then\n    # don't pack core tests for profiles other than latest\n    for test_src in $(find src -name tests | grep -v command_modules); do\n        rel_path=${test_src##src/}\n        rel_path=(${rel_path/\\// })\n        rel_path=${rel_path[1]}\n\n        mkdir -p $testsrc_dir/$rel_path\n        cp -R $test_src/* $testsrc_dir/$rel_path\n    done\nfi\n\ncat >$testsrc_dir/setup.py <<EOL\n#!/usr/bin/env python\n\nfrom setuptools import setup\n\nVERSION = \"1.0.0.$version\"\n\nCLASSIFIERS = [\n    'Development Status :: 3 - Alpha',\n    'Intended Audience :: Developers',\n    'Programming Language :: Python',\n    'Programming Language :: Python :: 3',\n    'Programming Language :: Python :: 3.7',\n    'Programming Language :: Python :: 3.8',\n    'Programming Language :: Python :: 3.9',\n    'Programming Language :: Python :: 3.10',\n    'License :: OSI Approved :: MIT License',\n]\n\nDEPENDENCIES = [\n    'azure-cli',\n    'azure-cli-testsdk'\n]\n\nsetup(\n    name='azure-cli-fulltest',\n    version=VERSION,\n    description='Microsoft Azure Command-Line Tools Full Tests',\n    license='MIT',\n    author='Microsoft Corporation',\n    author_email='azpycli@microsoft.com',\n    url='https://github.com/Azure/azure-cli',\n    zip_safe=False,\n    classifiers=CLASSIFIERS,\n    packages=[\nEOL\n\nif [ \"$target_profile\" == \"latest\" ]; then\n    echo \"        'azure.cli.core.tests',\" >>$testsrc_dir/setup.py\nfi\n\nfor name in `ls src/azure-cli/azure/cli/command_modules`; do\n    test_folder=src/azure-cli/azure/cli/command_modules/$name/tests\n    if [ -d $test_folder ]; then\n        echo \"        'azure.cli.command_modules.$name.tests',\" >>$testsrc_dir/setup.py\n        if [ -d $test_folder/$target_profile ]; then\n            echo \"        'azure.cli.command_modules.$name.tests.$target_profile',\" >>$testsrc_dir/setup.py\n        fi\n    fi\ndone\n\n\ncat >>$testsrc_dir/setup.py <<EOL\n    ],\n    package_data={'': ['*.bat',\n                       '*.byok',\n                       '*.cer',\n                       '*.gql',  # graphql used by apim\n                       '*.js',\n                       '*.json',\n                       '*.kql',\n                       '*.md',\n                       '*.pem',\n                       '*.pfx',\n                       '*.sql',\n                       '*.txt',\n                       '*.txt',\n                       '*.xml',\n                       '*.yml',\n                       '*.zip',\n                       '**/*.bat',\n                       '**/*.byok',\n                       '**/*.cer',\n                       '**/*.gql',\n                       '**/*.ipynb',\n                       '**/*.jar',\n                       '**/*.js',\n                       '**/*.json',\n                       '**/*.kql',\n                       '**/*.md',\n                       '**/*.pem',\n                       '**/*.pfx',\n                       '**/*.sql',\n                       '**/*.txt',\n                       '**/*.txt',\n                       '**/*.xml',\n                       'data/*',\n                       'recordings/*.yaml']},\n    install_requires=DEPENDENCIES\n)\nEOL\n\ncat >>$testsrc_dir/setup.cfg <<EOL\n[bdist_wheel]\nuniversal=1\nEOL\n\ncat >>$testsrc_dir/README.txt <<EOL\nAzure CLI Test Cases\nEOL\n\npushd $testsrc_dir >/dev/null\npython setup.py -q bdist_wheel -d $output_dir\npython setup.py -q sdist -d $sdist_dir\npopd >/dev/null\n\n##############################################\n# clear afterwards\nrm -rf $testsrc_dir\ngit checkout src\n\n##############################################\n# summary\ntitle 'Results'\necho $(ls $sdist_dir | wc -l) packages created.\n", "num_lines": 204}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nREPO_ROOT=\"$(dirname ${BASH_SOURCE[0]})/../..\"\n\n# Upgrade pip to the latest version\npython -m pip install --upgrade pip\n\n# Uninstall any cruft that can poison the rest of the checks in this script.\npip freeze > baseline_deps.txt\npip uninstall -y -r baseline_deps.txt || true\npip list\npip check\nrm baseline_deps.txt\n\n# Install everything from our repository first.\n${REPO_ROOT}/scripts/install_full.sh\n\npip check\n\npython -m azure.cli --version\n\npython -m azure.cli self-test\n", "num_lines": 25}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# ARM64 image does not have docker, install manually\nset -evx\nif [[ $(dpkg --print-architecture) == \"amd64\" ]]; then\n    echo \"Docker is already installed on AMD64\"\n    exit 0\nfi\n# https://docs.docker.com/engine/security/rootless/\n/bin/bash -c \"$(curl -fsSL https://get.docker.com)\"\nsudo apt-get install -y uidmap\ndockerd-rootless-setuptool.sh install\nexport XDG_RUNTIME_DIR=/home/cloudtest/.docker/run\nPATH=/usr/bin:/sbin:/usr/sbin:$PATH dockerd-rootless.sh &\nsleep 5\ndocker context use rootless\n", "num_lines": 16}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Set the storage credentials for the given travis repo.\n\n# Pre-requisite:\n# 1. Travis CLI https://github.com/travis-ci/travis.rb\n# 2. Azure CLI\n# 3. Login Azure CLI with credential which has access to the target storage account.\n\n# Input:\n# $1 - storage account name\n# $2 - travis CI repo name\n\nset -ev\n\nexport AZURE_STORAGE_ACCOUNT=$1\n\naz storage container create -n store -otsv\naz storage container create -n edge -otsv\n\nexpiry_date=`date -v+6m +'%Y-%m-%dT00:00Z'`\necho \"Set SAS expiry date to $expiry_date\"\n\ntravis env set -r $2 PUBLISH_STORAGE_ACCT $1\ntravis env set -r $2 PUBLISH_STORAGE_SAS $(az storage container generate-sas -n store --permissions w --expiry $expiry_date -otsv)\ntravis env set -r $2 -P PUBLISH_CONTAINER store\n\ntravis env set -r $2 EDGE_STORAGE_ACCT $1\ntravis env set -r $2 EDGE_STORAGE_SAS $(az storage container generate-sas -n edge --permissions lw --expiry $expiry_date -otsv)\ntravis env set -r $2 -P EDGE_CONTAINER edge\n\ntravis env list -r $2\n", "num_lines": 33}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\necho \"Listing Available Extensions:\"\naz extension list-available -otable\n\n# turn off telemetry as it crowds output\nexport AZURE_CLI_DIAGNOSTICS_TELEMETRY=\noutput=$(az extension list-available --query [].name -otsv)\nexit_code=0\n\n# azure-cli-ml: https://github.com/Azure/azure-cli-extensions/issues/826\nignore_list='azure-cli-ml fzf arcappliance arcdata connectedk8s'\n\nfor ext in $output; do\n    echo\n    # Use regex to detect if $ext is in $ignore_list\n    if [[ $ignore_list =~ $ext ]]; then\n        echo \"Ignore extension: $ext\"\n        continue\n    fi\n\n    echo \"Verifying extension:\" $ext\n    az extension add -n $ext\n    if [ $? != 0 ]\n    then\n        exit_code=1\n        echo \"Failed to load:\" $ext\n    fi\ndone\n\npip list -v\n\naz self-test --debug\nif [ $? != 0 ]\nthen\n    exit_code=1\n    echo \"Failed to verify:\" $ext\nfi\n\nexit $exit_code\n", "num_lines": 51}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\necho '=== List installed packages'\npip freeze\n\necho '=== Begin testing'\nunset AZURE_CLI_DIAGNOSTICS_TELEMETRY\nazdev verify package $share_folder/build/\n\nexport AZURE_CORE_COLLECT_TELEMETRY=False\necho '= Verify Commands with -h'\nazdev verify commands\n", "num_lines": 25}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\nset -ev\n\noutput=$(az cloud list-profiles -otsv)\n\nazdev verify package $share_folder/build/\n\nfor profile in $output; do\n    echo\n    echo \"Verifying profile:\" $profile\n    az cloud update --profile $profile\n    azdev verify load-all\n    echo $profile \"profile has been verified.\"\ndone\n\necho \"Successfully loaded all commands in each profile.\"\n", "num_lines": 28}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nwd=`cd $(dirname $0); pwd`\n\n. $wd/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\npip install sphinx==1.6.7 Jinja2==3.0.3\necho \"Installed.\"\n\ncd doc/sphinx; python ./__main__.py\n\npython $wd/test_help_doc_arguments.py \"./_build/xml/ind.xml\"\n\necho \"OK.\"\n", "num_lines": 25}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nfor TOX_FILE in $(find src -name tox.ini); do\n    pwd\n    (cd $(dirname $TOX_FILE) && tox)\ndone", "num_lines": 8}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script is used by release pipeline task \"Release Notes\" to update\n# https://github.com/MicrosoftDocs/azure-docs-cli.\n#\n# It does several things:\n# 1. Transfer release notes from src/azure-cli/HISTORY.rst to docs-ref-conceptual/release-notes-azure-cli.md\n# 2. Update ms.date\n# 3. Update version number in docs-ref-conceptual/includes/current-version.md\n\n# sed manual: https://www.gnu.org/software/sed/manual/sed.html\n\nset -ev\n\nBOT_TOKEN=$(az keyvault secret show --vault-name \"${BOT_VAULT_NAME}\" --name \"${BOT_SECRET_NAME}\" --query value -otsv)\n\ngit clone https://github.com/Azure/azure-cli.git\ncd azure-cli\ngit config --local user.email \"AzPyCLI@microsoft.com\"\ngit config --local user.name \"Azure CLI Team\"\ngit remote rename origin upstream\ngit checkout -b main upstream/main\nPRE_VERSION=$(sed -n -e 's/.*__version__.*\"\\(.*\\)\"/\\1/p' src/azure-cli/azure/cli/__main__.py)\ngit checkout -b release upstream/release\ncd ..\ngit clone https://github.com/MicrosoftDocs/azure-docs-cli.git\ncd azure-docs-cli\ngit config --local user.email \"AzPyCLI@microsoft.com\"\ngit config --local user.name \"Azure CLI Team\"\ngit remote rename origin upstream\ngit remote add origin https://anything:${BOT_TOKEN}@github.com/${BOT_ACCOUNT_NAME}/azure-docs-cli.git\nDOC_BRANCH_NAME=\"cli-release-notes-${CLI_VERSION}\"\ngit checkout -b ${DOC_BRANCH_NAME}\n\n# Copy release notes\n# 2\\.31\\.0\nESCAPED_CLI_VERSION=`echo \"$CLI_VERSION\" | sed 's/\\./\\\\\\./g'`\n# 2\\.30\\.0\nESCAPED_PRE_VERSION=`echo \"$PRE_VERSION\" | sed 's/\\./\\\\\\./g'`\n# The 1st sed finds all lines between (including) 2.31.0 and 2.30.0\n#   1:             2.31.0\n#   2:             ++++++\n#                  ...\n#   2nd last line:\n#   last line:     2.30.0\n# The 2nd sed deletes line 1, 2 and last line\n# The 3rd sed deletes the last line\n# The 4th sed deletes all PR numbers, like (#20233)\nsed -n '/'\"$ESCAPED_CLI_VERSION\"'/,/'\"$ESCAPED_PRE_VERSION\"'/p' ../azure-cli/src/azure-cli/HISTORY.rst| sed '1d;2d;$d'| sed '$d' | sed 's| (#[0-9]\\+)$||' | tee note.tmp\n# December 14, 2021\nRELEASE_DATE=$(date -d \"next tuesday\" '+%B %d, %Y')\n# 12/14/2021\nMODIFY_DATE=$(date -d \"next tuesday\" '+%m/%d/%Y')\n# Update ms.date\nsed -i \"s|^ms.date.*$|ms.date: ${MODIFY_DATE}|g\" docs-ref-conceptual/release-notes-azure-cli.md\n# Find the top level heading '# Azure CLI release notes' and append content of note.tmp after it.\nsed -i '/^# .*$/ r note.tmp' docs-ref-conceptual/release-notes-azure-cli.md\n# Find the top level heading '# Azure CLI release notes' and append lines:\n#   # December 7, 2021\n#\n#   Version 2.31.0\nsed -i '/^# .*$/a \\\\n## '\"${RELEASE_DATE}\"'\\n\\nVersion '\"${CLI_VERSION}\"'' docs-ref-conceptual/release-notes-azure-cli.md\n# Update bold text like '**ARM**' to markdown heading '### ARM'\nsed -i 's/^\\*\\*\\(.*\\)\\*\\*$/### \\1/g' docs-ref-conceptual/release-notes-azure-cli.md\n\n# Update ms.date\nsed -i \"s|^ms.date.*$|ms.date: ${MODIFY_DATE}|g\" docs-ref-conceptual/includes/current-version.md\n# Update current version\nsed -i 's/'\"$PRE_VERSION\"'/'\"$CLI_VERSION\"'/g' docs-ref-conceptual/includes/current-version.md\n\ngit commit -am \"azure-cli release notes ${CLI_VERSION}\"\ngit push origin ${DOC_BRANCH_NAME}\ncurl \\\n  --user \"anything:${BOT_TOKEN}\" \\\n  -d \"{\\\"title\\\":\\\"release note for azure cli ${CLI_VERSION}\\\",\\\"head\\\":\\\"${BOT_ACCOUNT_NAME}:${DOC_BRANCH_NAME}\\\",\\\"base\\\":\\\"main\\\"}\" \\\n  https://api.github.com/repos/MicrosoftDocs/azure-docs-cli/pulls\n", "num_lines": 75}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Update the version strings in the source code\n\n# Input:\n#   $1 - the version string, if omitted, use current time\n\nversion=$1\n\nif [ -z $version ]; then\n    echo 'Use utc timestamp as version'\n    version=dev`date -u '+%Y%m%d%H%M%S'`\nfi\n\necho \"Replace with version: $version\"\n\nplatform=`uname`\n\nfor each in $(find src -name __main__.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\nfor each in $(find src -name __init__.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\nfor each in $(find src -name setup.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^VERSION = [\\\"']\\(.*\\)[\\\"']/VERSION = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^VERSION = [\\\"']\\(.*\\)[\\\"']/VERSION = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\n", "num_lines": 43}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Extract the version of the CLI from azure-cli package's __main__.py file.\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n\nver=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\necho $ver > $BUILD_STAGINGDIRECTORY/version\necho $ver > $BUILD_STAGINGDIRECTORY/azure-cli-${ver}.txt", "num_lines": 7}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\n# This script is expected to be run in a container environment, therefore sudo doesn't present\n# here.\n\nset -exv\n\n: \"${CLI_VERSION:?CLI_VERSION environment variable not set.}\"\n: \"${CLI_VERSION_REVISION:?CLI_VERSION_REVISION environment variable not set.}\"\n\nls -Rl /mnt/artifacts\n\nWORKDIR=`cd $(dirname $0); cd ../../../; pwd`\nPYTHON_VERSION=\"3.10.10\"\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Update APT packages\napt-get update\n# uuid-dev is used to build _uuid module: https://github.com/python/cpython/pull/3796\napt-get install -y libssl-dev libffi-dev python3-dev zlib1g-dev uuid-dev wget\n\n# In Ubuntu 18.04, debhelper 11.1.6 has bug which makes it fail to dpkg-buildpackage. Use backport version instead.\n# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=897569\nif cat /etc/lsb-release | grep 18.04\nthen\n  apt-get install -y debhelper -t bionic-backports\nelse\n  apt-get install -y debhelper\nfi\n\n# Git is not strictly necessary, but it would allow building an experimental package\n# with dependency which is currently only available in its git repo feature branch.\napt-get install -y git\n\n# Download Python source code\nPYTHON_SRC_DIR=$(mktemp -d)\nwget -qO- https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tgz | tar -xz -C \"$PYTHON_SRC_DIR\"\necho \"Python source code is in $PYTHON_SRC_DIR\"\n\n# Build Python\n$PYTHON_SRC_DIR/*/configure --srcdir $PYTHON_SRC_DIR/* --prefix $WORKDIR/python_env\nmake\nmake install\n\n$WORKDIR/python_env/bin/python3 -m pip install --upgrade pip setuptools\n\nexport PATH=$PATH:$WORKDIR/python_env/bin\n\nfind ${WORKDIR}/src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip3 install --no-deps\npip3 install -r ${WORKDIR}/src/azure-cli/requirements.py3.$(uname).txt\n$WORKDIR/python_env/bin/python3 ${WORKDIR}/scripts/trim_sdk.py\n\n# Create create directory for debian build\nmkdir -p $WORKDIR/debian\n$SCRIPT_DIR/prepare.sh $WORKDIR/debian $WORKDIR/az.completion $WORKDIR\n\ncd $WORKDIR\ndpkg-buildpackage -us -uc\n\ndeb_file=$WORKDIR/../azure-cli_${CLI_VERSION}-${CLI_VERSION_REVISION:=1}_*.deb\ncp $deb_file /mnt/output/\n", "num_lines": 66}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#######################################################################################################################\n# This script does three fundamental things:                                                                          #\n#   1. Add Microsoft's GPG Key has a trusted source of apt packages.                                                  #\n#   2. Add Microsoft's repositories as a source for apt packages.                                                     #\n#   3. Installs the Azure CLI from those repositories.                                                                #\n# Given the nature of this script, it must be executed with elevated privileges, i.e. with `sudo`.                    #\n#                                                                                                                     #\n# Remember, with great power comes great responsibility.                                                              #\n#                                                                                                                     #\n# Do not be in the habit of executing scripts from the internet with root-level access to your machine. Only trust    #\n# well-known publishers.                                                                                              #\n#######################################################################################################################\n\nset -e\n\nif [[ $# -ge 1 && $1 == \"-y\" ]]; then\n    global_consent=0\nelse\n    global_consent=1\nfi\n\nfunction assert_consent {\n    if [[ $2 -eq 0 ]]; then\n        return 0\n    fi\n\n    echo -n \"$1 [Y/n] \"\n    read consent\n    if [[ ! \"${consent}\" == \"y\" && ! \"${consent}\" == \"Y\" && ! \"${consent}\" == \"\" ]]; then\n        echo \"'${consent}'\"\n        exit 1\n    fi\n}\n\nglobal_consent=0 # Artificially giving global consent after review-feedback. Remove this line to enable interactive mode\n\nsetup() {\n\n    assert_consent \"Add packages necessary to modify your apt-package sources?\" ${global_consent}\n    set -v\n    export DEBIAN_FRONTEND=noninteractive\n    apt-get update\n    apt-get install -y apt-transport-https lsb-release gnupg curl\n    set +v\n\n    assert_consent \"Add Microsoft as a trusted package signer?\" ${global_consent}\n    set -v\n    curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg\n    set +v\n\n    assert_consent \"Add the Azure CLI Repository to your apt sources?\" ${global_consent}\n    set -v\n    # Use env var DIST_CODE for the package dist name if provided\n    if [[ -z $DIST_CODE ]]; then\n        CLI_REPO=$(lsb_release -cs)\n        shopt -s nocasematch\n        ERROR_MSG=\"Unable to find a package for your system. Please check if an existing package in https://packages.microsoft.com/repos/azure-cli/dists/ can be used in your system and install with the dist name: 'curl -sL https://aka.ms/InstallAzureCLIDeb | sudo DIST_CODE=<dist_code_name> bash'\"\n        if [[ ! $(curl -sL https://packages.microsoft.com/repos/azure-cli/dists/) =~ $CLI_REPO ]]; then\n            DIST=$(lsb_release -is)\n            if [[ $DIST =~ \"Ubuntu\" ]]; then\n                CLI_REPO=\"jammy\"\n            elif [[ $DIST =~ \"Debian\" ]]; then\n                CLI_REPO=\"bullseye\"\n            elif [[ $DIST =~ \"LinuxMint\" ]]; then\n                CLI_REPO=$(cat /etc/os-release | grep -Po 'UBUNTU_CODENAME=\\K.*') || true\n                if [[ -z $CLI_REPO ]]; then\n                    echo $ERROR_MSG\n                    exit 1\n                fi\n            else\n                echo $ERROR_MSG\n                exit 1\n            fi\n        fi\n    else\n        CLI_REPO=$DIST_CODE\n        if [[ ! $(curl -sL https://packages.microsoft.com/repos/azure-cli/dists/) =~ $CLI_REPO ]]; then\n            echo \"Unable to find an azure-cli package with DIST_CODE=$CLI_REPO in https://packages.microsoft.com/repos/azure-cli/dists/.\"\n            exit 1\n        fi\n    fi\n    echo \"deb [arch=$(dpkg --print-architecture)] https://packages.microsoft.com/repos/azure-cli/ ${CLI_REPO} main\" \\\n        > /etc/apt/sources.list.d/azure-cli.list\n    apt-get update\n    set +v\n\n    assert_consent \"Install the Azure CLI?\" ${global_consent}\n    apt-get install -y azure-cli\n\n}\n\nsetup  # ensure the whole file is downloaded before executing\n", "num_lines": 95}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build APT package in an Azure Container Instances\n# This script assumes the Azure CLI is installed and logged in.\n\nset -exv\n\n: ${DISTRO:?\"DISTRO is not set\"}\n: ${DISTRO_BASE_IMAGE:?\"DISTRO_BASE_IMAGE is not set\"}\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\ndocker run --rm \\\n           -v \"$BUILD_SOURCESDIRECTORY\":/mnt/repo \\\n           -v \"$BUILD_STAGINGDIRECTORY\":/mnt/output \\\n           -v \"$SYSTEM_ARTIFACTSDIRECTORY\":/mnt/artifacts \\\n           -e CLI_VERSION=$CLI_VERSION \\\n           -e CLI_VERSION_REVISION=1~$DISTRO \\\n           -e DEBIAN_FRONTEND=noninteractive \\\n           $DISTRO_BASE_IMAGE \\\n           /mnt/repo/scripts/release/debian/build.sh\n", "num_lines": 22}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\nset -evx\n\n# Create the debian/ directory for building the azure-cli Debian package\n\n# This script takes an argument of the empty directory where the files will be placed.\n\nif [ -z \"$1\" ]\n  then\n    echo \"No argument supplied for debian directory.\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]\n  then\n    echo \"No argument supplied for completion script.\"\n    exit 1\nfi\n\nif [ -z \"$3\" ]\n  then\n    echo \"No argument supplied for source directory.\"\n    exit 1\nfi\n\nTAB=$'\\t'\n\ndebian_dir=$1\ncompletion_script=$2\nsource_dir=$3\nmkdir $debian_dir/source\n\necho '1.0' > $debian_dir/source/format\necho '9' > $debian_dir/compat\n\ncat > $debian_dir/changelog <<- EOM\nazure-cli (${CLI_VERSION}-${CLI_VERSION_REVISION:=1}) unstable; urgency=low\n\n  * Debian package release.\n\n -- Azure Python CLI Team <azpycli@microsoft.com>  $(date -R)\n\nEOM\n\ncat > $debian_dir/control <<- EOM\nSource: azure-cli\nSection: python\nPriority: extra\nMaintainer: Azure Python CLI Team <azpycli@microsoft.com>\nBuild-Depends: debhelper (>= 9), libssl-dev, libffi-dev, python3-dev\nStandards-Version: 3.9.5\nHomepage: https://github.com/azure/azure-cli\n\nPackage: azure-cli\nArchitecture: any\nDepends: \\${shlibs:Depends}, \\${misc:Depends}\nDescription: Azure CLI\n A great cloud needs great tools; we're excited to introduce Azure CLI,\n our next generation multi-platform command line experience for Azure.\n\nEOM\n\ncat > $debian_dir/copyright <<- EOM\nFormat: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: azure-cli\nUpstream-Contact: Azure Python CLI Team <azpycli@microsoft.com>\nSource: https://github.com/azure/azure-cli\n\nFiles: *\nCopyright: Copyright (c) Microsoft Corporation\nLicense: MIT\nAzure CLI\n\nCopyright (c) Microsoft Corporation\n\nAll rights reserved.\n\nMIT License\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"\"Software\"\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nEOM\n\n# TODO: Instead of \"_ssl.cpython-310-x86_64-linux-gnu.so\" only, find all .so files with \"find debian/azure-cli/opt/az -type f -name '*.so'\"\n\ncat > $debian_dir/rules << EOM\n#!/usr/bin/make -f\n\n# Uncomment this to turn on verbose mode.\nexport DH_VERBOSE=1\nexport DH_OPTIONS=-v\n\n%:\n${TAB}dh \\$@ --sourcedirectory $source_dir\n\noverride_dh_install:\n${TAB}mkdir -p debian/azure-cli/opt/az\n${TAB}cp -a python_env/* debian/azure-cli/opt/az\n${TAB}mkdir -p debian/azure-cli/usr/bin/\n${TAB}echo \"\\043!/usr/bin/env bash\\nbin_dir=\\140cd \\\"\\044(dirname \\\"\\044BASH_SOURCE[0]\\\")\\\"; pwd\\140\\nAZ_INSTALLER=DEB \\\"\\044bin_dir\\\"/../../opt/az/bin/python3 -Im azure.cli \\\"\\044\\100\\\"\" > debian/azure-cli/usr/bin/az\n${TAB}chmod 0755 debian/azure-cli/usr/bin/az\n${TAB}mkdir -p debian/azure-cli/etc/bash_completion.d/\n${TAB}cat ${completion_script} > debian/azure-cli/etc/bash_completion.d/azure-cli\n${TAB}dpkg-shlibdeps -v --warnings=7 -Tdebian/azure-cli.substvars -dDepends -edebian/azure-cli/opt/az/bin/python3 debian/azure-cli/opt/az/lib/python3.10/lib-dynload/_ssl.cpython-310-*-linux-gnu.so\n\n\noverride_dh_strip:\n${TAB}dh_strip --exclude=_cffi_backend\n\nEOM\n\ncat $debian_dir/rules\n\n# debian/rules should be executable\nchmod 0755 $debian_dir/rules\n", "num_lines": 125}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nbase_images=(\"ubuntu:xenial\" \"ubuntu:bionic\" \"debian:stretch\" \"debian:jessie\" \"debian:buster\")\n\nset -e\n\nfor image in ${base_images[@]}; do\n    docker build --build-arg base=${image} s-t deb-installer:current -f Dockerfile.install_test .\n    docker run -it --rm deb-installer:current\ndone\n", "num_lines": 11}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a ubuntu/debian docker.\nset -exv\n\nexport USERNAME=azureuser\n\napt update\napt install -y apt-transport-https git gcc python3-dev\n\ndpkg -i /mnt/artifacts/azure-cli_$CLI_VERSION-1~${DISTRO}_*.deb\n\ntime az self-test\ntime az --version\n\ncd /azure-cli/\n/opt/az/bin/python3 -m pip install wheel\nln -sf /opt/az/bin/python3 /usr/bin/python\n./scripts/ci/build.sh\n\n/opt/az/bin/python3 -m pip install pytest\n/opt/az/bin/python3 -m pip install pytest-xdist\n/opt/az/bin/python3 -m pip install pytest-forked\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs /opt/az/bin/python3 -m pip install --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs /opt/az/bin/python3 -m pip install --upgrade --ignore-installed --no-deps\n\n/opt/az/bin/python3 /azure-cli/scripts/release/debian/test_deb_package.py\n", "num_lines": 29}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a docker to verify installing deb package from the apt repository.\n\napt update -y\napt install curl -y\ncounter=4\n\nwhile [ $counter -gt 0 ]\ndo\n    curl -sL https://aka.ms/InstallAzureCLIDeb | bash\n    ACTUAL_VERSION=$(az version | sed -n 's|\"azure-cli\": \"\\(.*\\)\",|\\1|p' | sed 's|[[:space:]]||g')\n    echo \"actual version:${ACTUAL_VERSION}\"\n    echo \"expected version:${CLI_VERSION}\"\n\n    if [ \"$ACTUAL_VERSION\" != \"$CLI_VERSION\" ]; then\n        if [ ! -z \"$ACTUAL_VERSION\" ]; then\n            echo \"Latest package is not in the repo.\"\n            exit 1\n        fi\n        echo \"wait 5m\"\n        sleep 300\n        counter=$(( $counter - 1 ))\n    else\n        echo \"Latest package is verified.\"\n        exit 0\n    fi\ndone\necho \"Timeout!\"\nexit 1\n", "num_lines": 31}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\nset -evx\n\nIMAGE_NAME=clibuild$BUILD_BUILDNUMBER\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\ndocker build --no-cache \\\n             --build-arg BUILD_DATE=\"`date -u +\"%Y-%m-%dT%H:%M:%SZ\"`\" \\\n             --build-arg CLI_VERSION=$CLI_VERSION \\\n             --tag $IMAGE_NAME:latest \\\n             $BUILD_SOURCESDIRECTORY\n\ndocker save -o \"$BUILD_STAGINGDIRECTORY/docker-azure-cli-${CLI_VERSION}.tar\" $IMAGE_NAME:latest\n", "num_lines": 19}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nroot=$(cd $(dirname $0); pwd)\n\nset -evx\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\nHOMEBREW_UPSTREAM_URL=`cat $BUILD_STAGINGDIRECTORY/github/upstream_url`\nTAR_NAME=azure-cli-$CLI_VERSION.tar.gz\n\ndocker_files=$(cd $BUILD_SOURCESDIRECTORY/scripts/release/homebrew/docker; pwd)\nsrc_files=$(cd $BUILD_SOURCESDIRECTORY/src; pwd)\n\necho \"Generating formula in docker container ... \"\ndocker run -v $docker_files:/mnt/scripts \\\n           -v $src_files:/mnt/src \\\n           -e CLI_VERSION=$CLI_VERSION \\\n           -e HOMEBREW_UPSTREAM_URL=$HOMEBREW_UPSTREAM_URL \\\n           --name azurecli \\\n           python:3.6 \\\n           /mnt/scripts/run.sh\n\n# clean up\nrm -rf $BUILD_STAGINGDIRECTORY/metadata\n\ndocker cp azurecli:azure-cli.rb $BUILD_STAGINGDIRECTORY/azure-cli.rb\ndocker rm --force azurecli\n", "num_lines": 28}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nset -ev\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\n\necho == Remove pre-installed azure-cli ==\nbrew uninstall azure-cli\n\necho == Install azure-cli.rb formula ==\nbrew install --build-from-source $SYSTEM_ARTIFACTSDIRECTORY/homebrew/azure-cli.rb\n\nAZ_BASE=/usr/local/Cellar/azure-cli/$CLI_VERSION/libexec\nexport PATH=$AZ_BASE/bin:$PATH\nexport OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES\necho $PATH\npip install wheel\n./scripts/ci/build.sh\npip install pytest --prefix $AZ_BASE\npip install pytest-xdist --prefix $AZ_BASE\npip install pytest-forked --prefix $AZ_BASE\n\nfind ./artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix $AZ_BASE --upgrade --ignore-installed\nfind ./artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix $AZ_BASE --upgrade --ignore-installed --no-deps\n\n# workaround for this bug (https://github.com/microsoft/azure-devops-python-api/issues/354)\nmkdir -p ~/.vsts/python-sdk/cache\n\nPYTHON_VERSION=`ls $AZ_BASE/lib/ | head -n 1`\npython ./scripts/release/homebrew/test_homebrew_package.py $AZ_BASE $PYTHON_VERSION", "num_lines": 30}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ev\n\n# Download the release package generated by the Github when a tag of the release is created to storage account\n\n: {AZURE_STORAGE_ACCOUNT:?\"AZURE_STORAGE_ACCOUNT not set\"}\n: {AZURE_STORAGE_KEY:?\"AZURE_STORAGE_KEY not set\"}\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\nTAR_NAME=azure-cli-$CLI_VERSION.tar.gz\n\nmkdir -p $BUILD_STAGINGDIRECTORY/github/ >/dev/null 2>&1\ncurl -sL https://github.com/Azure/azure-cli/archive/$TAR_NAME -o $BUILD_STAGINGDIRECTORY/github/$TAR_NAME\n\naz storage blob upload -c releases -n $TAR_NAME -f $BUILD_STAGINGDIRECTORY/github/$TAR_NAME\n\n# Make sure the URL is publicly available\nHOMEBREW_UPSTREAM_URL=$(az storage blob url -c releases -n $TAR_NAME -otsv)\ncurl -sfS -I $HOMEBREW_UPSTREAM_URL >/dev/null\necho -n $HOMEBREW_UPSTREAM_URL > $BUILD_STAGINGDIRECTORY/github/upstream_url\n", "num_lines": 22}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nroot=$(cd $(dirname $0); pwd)\n\npip install wheel\npip install -U pip\npip install -r $root/requirements.txt\nfind /mnt/src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip install --no-deps\npip install -r /mnt/src/azure-cli/requirements.py3.Darwin.txt\n\npip list\n\n# default option is update_existing to build from homebrew master branch,\n# append '-b use_template' to build from formula_template.txt \npython $root/formula_generate.py\n", "num_lines": 16}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This is the script builds the final wheel packages for shipping. The major difference between this script and the\n# scripts/ci/build.sh is that this script doesn't build testsdk and test packages. It doesn't update version string,\n# either. Therefore this script is shorter and cleaner.\n\nset -ev\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n: \"${BUILD_SOURCESDIRECTORY:=`cd $(dirname $0); cd ../../../; pwd`}\"\n\ncd $BUILD_SOURCESDIRECTORY\n\nbranch=$1\necho \"Branch $branch\"\n\necho \"Search setup files from `pwd`.\"\npython --version\n\npip install -U pip setuptools wheel\npip list\n\nscript_dir=`cd $(dirname $BASH_SOURCE[0]); pwd`\n\nif [[ \"$branch\" != \"release\" ]]; then\n    . $script_dir/../../ci/version.sh post`date -u '+%Y%m%d%H%M%S'`\nfi\n\nfor setup_file in $(find src -name 'setup.py' | grep -v azure-cli-testsdk); do\n    pushd `dirname $setup_file`\n    python setup.py bdist_wheel -d $BUILD_STAGINGDIRECTORY\n    python setup.py sdist -d $BUILD_STAGINGDIRECTORY\n    popd\ndone\n", "num_lines": 35}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n: \"${CLI_VERSION:?CLI_VERSION environment variable not set.}\"\n\nyum check-update\nyum install -y gcc rpm-build rpm-level rpmlint make bash corutils diffutils \\\n               path rpmdevtools python libffi-devel python3-devel openssl-devel \\\n               wget\n\nset -ev\n\nexport REPO_PATH=`cd $(dirname $0); cd ../../../; pwd`\nrpmbuild -v -bb --clean $REPO_PATH/scripts/release/rpm/azure-cli.spec && cp /root/rpmbuild/RPMS/x86_64/* /mnt/output\n", "num_lines": 14}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Checks to see if all RPM files passed to this program are signed.\n# Note: This script must be run as `root` on an RPM based Linux machine.\n\nset -e\n\nif [[ $# -lt 1 ]]; then\n    echo \"no arguments provided\" >&2\n    exit 2\nfi\n\n# For the purpose of this script, we will always want to consider files signed by Microsoft to be valid.\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\nfor file in $@; do\n    rpm --checksig ${file} | grep rsa\ndone", "num_lines": 18}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build assets related to Linux Distributions that use RPM/yum for installation.\n\nset -exv\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set.}\"\n\n# DOCKERFILE should be one of 'ubi' or 'fedora'\n: \"${DOCKERFILE:?DOCKERFILE environment variable not set.}\"\n# IMAGE should be RHEL or Fedora docker image url\n: \"${IMAGE:?IMAGE environment variable not set.}\"\n# PYTHON_PACKAGE should be python package name\n: \"${PYTHON_PACKAGE:?PYTHON_PACKAGE environment variable not set.}\"\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\n# Create a container image that includes the source code and a built RPM using this file.\ndocker build \\\n    --target build-env \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    --build-arg python_package=${PYTHON_PACKAGE} \\\n    -f ./scripts/release/rpm/${DOCKERFILE}.dockerfile \\\n    -t azure/azure-cli:${DOCKERFILE}-builder \\\n    .\n\n# Continue the previous build, and create a container that has the current azure-cli build but not the source code.\ndocker build \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    --build-arg python_package=${PYTHON_PACKAGE} \\\n    -f ./scripts/release/rpm/${DOCKERFILE}.dockerfile \\\n    -t azure/azure-cli:${DOCKERFILE} \\\n    .\n\n# Extract the built RPM so that it can be distributed independently.\n# The RPM file looks like azure-cli-2.32.0-1.el7.x86_64.rpm\nid=$(docker create azure/azure-cli:${DOCKERFILE}-builder)\n# https://docs.docker.com/engine/reference/commandline/cp/\n# Append /. so that the x86_64 folder's content is copied, instead of x86_64 folder itself.\ndocker cp $id:/out/. ${BUILD_STAGINGDIRECTORY}\n\n# Save these too a staging directory so that later build phases can choose to save them as Artifacts or publish them to\n# a registry.\n#\n# The products of `docker save` can be rehydrated using `docker load`.\n# mkdir -p ${BUILD_STAGINGDIRECTORY}/docker\n# docker save azure/azure-cli:${IMAGE}-builder | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_${IMAGE}-builder.tar.gz &\n# docker save azure/azure-cli:${IMAGE} | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_${IMAGE}.tar.gz &\n# wait\n", "num_lines": 52}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build assets related to Linux Distributions that use RPM/yum for installation specific for CBL-Mariner.\n\nset -exv\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set.}\"\n\n# IMAGE should be Mariner docker image url, such as mcr.microsoft.com/cbl-mariner/base/core:2.0\n: \"${IMAGE:?IMAGE environment variable not set.}\"\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\n# Create a container image that includes the source code and a built RPM using this file.\ndocker build \\\n    --target build-env \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    -f ./scripts/release/rpm/mariner.dockerfile \\\n    -t azure/azure-cli:mariner-builder \\\n    .\n\n# Continue the previous build, and create a container that has the current azure-cli build but not the source code.\ndocker build \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    -f ./scripts/release/rpm/mariner.dockerfile \\\n    -t azure/azure-cli:mariner \\\n    .\n\n# Extract the built RPM so that it can be distributed independently.\n# The RPM file looks like azure-cli-2.32.0-1.x86_64.rpm\nid=$(docker create azure/azure-cli:mariner-builder bash)\n# https://docs.docker.com/engine/reference/commandline/cp/\n# Append /. so that the x86_64 folder's content is copied, instead of x86_64 folder itself.\ndocker cp $id:/out/. ${BUILD_STAGINGDIRECTORY}\n\n# Save these too a staging directory so that later build phases can choose to save them as Artifacts or publish them to\n# a registry.\n#\n# The products of `docker save` can be rehydrated using `docker load`.\n# mkdir -p ${BUILD_STAGINGDIRECTORY}/docker\n# docker save azure/azure-cli:mariner-builder | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_mariner-builder.tar.gz &\n# docker save azure/azure-cli:mariner | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_mariner.tar.gz &\n# wait\n", "num_lines": 46}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a Mariner 2.0 docker container.\nset -exv\n\nexport USERNAME=azureuser\n\ntdnf --nogpgcheck install /mnt/rpm/$RPM_NAME -y\n\ntdnf install git gcc python3-devel python3-pip findutils ca-certificates -y\n\nln -s -f /usr/bin/python3 /usr/bin/python\ntime az self-test\ntime az --version\n\ncd /azure-cli/\npip install wheel\n./scripts/ci/build.sh\n\n# From Fedora36, when using `pip install --prefix` with root privileges, the package is installed into `{prefix}/local/lib`.\n# In order to keep the original installation path, I have to set RPM_BUILD_ROOT\n# Ref https://docs.fedoraproject.org/en-US/fedora/latest/release-notes/developers/Development_Python/#_pipsetup_py_installation_with_prefix\nexport RPM_BUILD_ROOT=/\n\npip install pytest --prefix /usr/lib64/az\npip install pytest-xdist --prefix /usr/lib64/az\npip install pytest-forked --prefix /usr/lib64/az\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed --no-deps\n\npython /azure-cli/scripts/release/rpm/test_rpm_package.py\n", "num_lines": 33}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a centos7 docker.\nset -exv\n\nexport USERNAME=azureuser\n\ndnf --nogpgcheck install /mnt/rpm/$RPM_NAME -y\n\ndnf install git gcc $PYTHON_PACKAGE-devel findutils -y\n\nln -s -f /usr/bin/$PYTHON_CMD /usr/bin/python\nln -s -f /usr/bin/$PIP_CMD /usr/bin/pip\ntime az self-test\ntime az --version\n\ncd /azure-cli/\npip install wheel\n./scripts/ci/build.sh\n\n# From Fedora36, when using `pip install --prefix` with root privileges, the package is installed into `{prefix}/local/lib`.\n# In order to keep the original installation path, I have to set RPM_BUILD_ROOT\n# Ref https://docs.fedoraproject.org/en-US/fedora/latest/release-notes/developers/Development_Python/#_pipsetup_py_installation_with_prefix\nexport RPM_BUILD_ROOT=/\n\npip install pytest --prefix /usr/lib64/az\npip install pytest-xdist --prefix /usr/lib64/az\npip install pytest-forked --prefix /usr/lib64/az\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed --no-deps\n\npython /azure-cli/scripts/release/rpm/test_rpm_package.py\n", "num_lines": 34}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a docker to verify installing rpm package from the yum repository.\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\nsh -c 'echo -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n\ncounter=4\n\nwhile [ $counter -gt 0 ]\ndo\n    yum install azure-cli -y\n    ACTUAL_VERSION=$(az version | sed -n 's|\"azure-cli\": \"\\(.*\\)\",|\\1|p' | sed 's|[[:space:]]||g')\n    echo \"actual version:${ACTUAL_VERSION}\"\n    echo \"expected version:${CLI_VERSION}\"\n\n    if [ \"$ACTUAL_VERSION\" != \"$CLI_VERSION\" ]; then\n        if [ ! -z \"$ACTUAL_VERSION\" ]; then\n            echo \"Latest package is not in the repo.\"\n            exit 1\n        fi\n        echo \"wait 5m\"\n        sleep 300\n        counter=$(( $counter - 1 ))\n    else\n        echo \"Latest package is verified.\"\n        exit 0\n    fi\ndone\necho \"Timeout!\"\nexit 1\n", "num_lines": 37}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "case $SHELL in\n*/zsh)\n   # Enable ZSH compatibility mode\n   autoload bashcompinit && bashcompinit\n   ;;\n*/bash)\n   ;;\n*)\nesac\n\neval \"$(register-python-argcomplete az)\"\n", "num_lines": 12}
{"repo_name": "azure-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x\n\necho \"setting up\"\nWORKDIR=\"${1:-$(mktemp -d)}\"\necho \"setting up ${WORKDIR}\"\n\npushd \"$WORKDIR\"\n\napt update -y && apt install -y apt-transport-https curl gnupg make gcc < /dev/null\n\n# add diladele apt key\nwget -qO - https://packages.diladele.com/diladele_pub.asc | apt-key add -\n\n# add new repo\ntee /etc/apt/sources.list.d/squid413-ubuntu20.diladele.com.list <<EOF\ndeb https://squid413-ubuntu20.diladele.com/ubuntu/ focal main\nEOF\n\n# and install\napt-get update && apt-get install -y squid-common squid-openssl squidclient libecap3 libecap3-dev < /dev/null\n\nmkdir -p /var/lib/squid\n\n/usr/lib/squid/security_file_certgen -c -s /var/lib/squid/ssl_db -M 4MB || true\n\nchown -R proxy:proxy /var/lib/squid\n\n# Name of the VM on which Squid is hosted\nHOST=\"cli-proxy-vm\"\n\ntee squidc.pem > /dev/null <<EOF\n-----BEGIN CERTIFICATE-----\nMIIFGzCCAwOgAwIBAgIUOQoj8CLZdselr97rvIwx5OLDsuwwDQYJKoZIhvcNAQEL\nBQAwFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMB4XDTIyMDMwODE2NDQ0N1oXDTMy\nMDMwNTE2NDQ0N1owFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMIICIjANBgkqhkiG\n9w0BAQEFAAOCAg8AMIICCgKCAgEA/MPtV5BTPt6cqi4RdMlmr3yIsa2ujzchxv4h\njsC1DtnRgos5S41PH0ri+3tTSVX32yrwsY+rD1YRupm6lmE7GhU5I0Gi9ozkSF0Z\nKKaJi2oypU/FB+QPqzoCRsMEwGCbmKFVl8VuhyndXK4b4kblr9bl/euwd7M8Sbvz\nWUjneDrQsiIsrzPT4KAZLqctzDe4llPT7YKa33hiEPOfvWiZ+dqkaQA9P64xXSyn\nfHX8uVAJ3uBVJeGxD0pkNJ7jOryaUuHHucU8S9mIjnKjAB5aPjLH5xAs6lmb3122\ny+1tnEAmXM50D+UoEjfS6HOb5rdiqXGvc1KboKjzkPCRxx2a72cvegUj6mgAJLzg\nThE1llcmU4izgxoIMkVpGTVOLLn1VFKuNhMZCvFvKgnKoAv3G0FUnfWEaRRjSNmD\nLYaMDT5H9Zt2pDIUjUGStCl7gRzMEnYwJO3yiDpg43o5dRysUyL9JfE/Nh7Tg618\nn8cJ/W7+QYbYljurap8r7QFSrol3VChFB+Oor5ni+vohSAwJf0UlMpG3xWmy1UI4\nTFKfFGRRTzrP+7bNwX5hIvIy5VtgyaOqJwTxhi/JdxtOr2tA5rCW7+CtgSvzkqNE\nXyr7vkYgp6Y5LZgy4tUjK0K0OUgVdjBOhDpEzy/FF8w1FEVgJ0qY/rWcLkBHDT8R\nvJkhio8CAwEAAaNfMF0wFwYDVR0RBBAwDoIMY2xpLXByb3h5LXZtMBIGA1UdEwEB\n/wQIMAYBAf8CAQAwDwYDVR0PAQH/BAUDAwfngDAdBgNVHSUEFjAUBggrBgEFBQcD\nAgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggIBAAomjCyXvaQOxgYK50sXLB2+\nwAfdsx5nnGdgyfg4urW2Vm15DhGvI7C/ntq0dYy24N/UbG7UDXvlyLIJFq1XP7nf\npZG0VCjZ69bmxKm3Z8m0/AwMvi8e9edy8v9kNBCwLGkHbA8Yo9CIiQgelfpp1vUh\nbnNBhaD+iu6CfiCLwgJb/iw7eo/CyoZqx+tjXaO2zXvm4p/+QIfAOgtGQLFU8cfZ\n/gUrTq5gFq0+P9GyWsATJF6q7L6WZZj0OuTse7f4CSij6MnOMMxA+JoahJz7lsSi\nTJHIwEp5r/RyhpyepQxFYcUH5JJf9rahXLWZi+9TjxSM2YyhxfRPsiUEuGDok78Q\nm/QPiCi9JJb1ocmTjAV8xDShocivXOFyhn6Ln77vLjY+AavtWDhQthpuPxsLtVzm\ne0SH11dELRtb74mqXOrO7fu/+IBs3JqLE/U+xuxQtvG8vG1yDKHHSZqS2h/Ws4l4\nNiAshHgehQDPBcY9wYYzfBgZpOUMzdDf50x+FSlY43WOJJzSuQh4yZ0+3kyguCF8\nrnMLSceyS4ci4LmJ/KCSuGdf6XVYz8BE9gjjjpCP6qy0UlRefWs/ig/wcK+2bF1T\nn/Yv+6gXeCTHJ75qDIPlp7DRUUk0fbMj4bIkaogWWk4zf2u8mxZLa0lePKNKZN/m\nGCvFwr3ei+u/8czp5F7T\n-----END CERTIFICATE-----\nEOF\n\ntee squidk.pem > /dev/null <<EOF\n-----BEGIN PRIVATE KEY-----\nMIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQD8w+1XkFM+3pyq\nLhF0yWavfIixra6PNyHG/iGOwLUO2dGCizlLjU8fSuL7e1NJVffbKvCxj6sPVhG6\nmbqWYTsaFTkjQaL2jORIXRkopomLajKlT8UH5A+rOgJGwwTAYJuYoVWXxW6HKd1c\nrhviRuWv1uX967B3szxJu/NZSOd4OtCyIiyvM9PgoBkupy3MN7iWU9PtgprfeGIQ\n85+9aJn52qRpAD0/rjFdLKd8dfy5UAne4FUl4bEPSmQ0nuM6vJpS4ce5xTxL2YiO\ncqMAHlo+MsfnECzqWZvfXbbL7W2cQCZcznQP5SgSN9Loc5vmt2Kpca9zUpugqPOQ\n8JHHHZrvZy96BSPqaAAkvOBOETWWVyZTiLODGggyRWkZNU4sufVUUq42ExkK8W8q\nCcqgC/cbQVSd9YRpFGNI2YMthowNPkf1m3akMhSNQZK0KXuBHMwSdjAk7fKIOmDj\nejl1HKxTIv0l8T82HtODrXyfxwn9bv5BhtiWO6tqnyvtAVKuiXdUKEUH46ivmeL6\n+iFIDAl/RSUykbfFabLVQjhMUp8UZFFPOs/7ts3BfmEi8jLlW2DJo6onBPGGL8l3\nG06va0DmsJbv4K2BK/OSo0RfKvu+RiCnpjktmDLi1SMrQrQ5SBV2ME6EOkTPL8UX\nzDUURWAnSpj+tZwuQEcNPxG8mSGKjwIDAQABAoICADZwcFbSo8s/oNhaUbIoinAz\nTzGNabI4upKkO1AGmzhWm3QVTkLCbY8czuRA/IAn/tj6V5q2ia4k6G6bG3+180e7\n2HGKenHFiIk5W+jQbYFUXxIRqyr26JUFSmY5LHXOmNR3svqcMCD2WFHUwfarNF75\n1tEoiPpO5SYwT8okFI5lhHtJNvyJGhIgCSxuH0QDoELoTRWzcm28/MoP3pCpzbft\nakmfHpHvj3w02OHKe6Lh5S5WfKBLCppzeD+JFQGai1ZcgGq3WzQu5uVfNVIaN297\n+mf+qN3UbOjfwzYKrffgLSMB6CdgQJAj683a0HIRfzNlY9dfrFse6E6IMa2D59FI\ngdF51d5OOqW02NGoO9fhp6M6dGPNxIUcWpk8hjagQQr/C8ygMljMS0/uXbU904M2\nzyVNNpSndT4sY/Mxihlnl9+Un2672dhCS8TiR0JnQbqxviZprqP9IUnOdEST4OtW\n2xFTYF+bg3PEKcuScgPrix9GhQ77uZw+MwPeyzreXdUBL+9jRAjuPqIE1Cpj+6R6\nzWkme00AeWnuaBBS3AD0xMqst7tMqqgXcTmccEaqNM3Dk/+IUnDJ3AwNxpXBq7UL\nUYrjFiK5mXul6/vDeX2d276Cp5M2LR8Sh83PfDGZdKam5vASiMGAGXdJyJMFZt7S\nZvxXwBrQlysTT6qx0aVRAoIBAQD/IIuWX3ZSXv4lK0x4N1KqqKIwTJjhA8fVDE7Y\n+P0/jh5roRYMXqcEZxERsdd0BT6pYtCaXuf1dR7ynt0Pw5VtxgiOiQWz0Mge7Osh\n+AJULmYsQBOM1wBMMk0n+U6ZHl9rSNGgyXY7LWULT8NjzL74vJTk0RWpQD440Vbd\ni+FQMHvASBeQ+JI6G4XGEZs8vB9Ar7vl/3atLpq7xmoii+j6D5jHgjlMtVRD6Q9h\nBWn7xNSfpQ/teIntjd60ophvQqnVYwa2nN7Hlj0ak6MIIqDG5KiEqDGVA00GarOc\nU6EJDZVx6NeDYaOlt8K2tpzzqX+WXn4manRF09n8qFeM5tn3AoIBAQD9oVAyKpQv\nSzhW6cHBX+kSX623X3S/jLctf2J4otN66sByi2rJNXK7Y68Xu9up55PSuBtyQTzj\nxSnIF+u96PhWQsnyaXyN41pqjypeS5qGA/JqPfsAa23j5LepSZS6aLtDE+y+2HfV\nhPFHzs7/ldp7bLv3B7XzyLSE+2v5reyW52vW4ItaJxHsvukf/6gE3AMYSMaHXaId\ncyeTVxUUs1tIM1J9WBjYzYa+t2QLv20lQTzZL2tZYclX7WQrpMoGilAZT3mTYnPb\npWeudS3422Fy8wH4qp0yt1ouI+KUL6Ri1AFAvDSauWHlznH9SLG4S/0oy/tG+9mh\n6CJBsN8ZY+4pAoIBAQCROjt7W9gEx6IwElezTvq1vsykZdXYsMg+FIWFqSav2Pyk\nE8xzOiYksW7b/bpBhwLGdUN9vGyaIxN81MXNxW34UPRp/sHKPBzOzdqDOaRJuyfa\nJJd8Yp7+wNt+18HQE6QJdCgwOL4erZaJO9xjoRdMjDzNi9+iurkwqqmh75BQj2jC\nacdQdM74WNZri3YsuoGn1uFE6YjqyE64eRfNlosGXX6AgzaO3eGbzr08Y1KTSNYo\nElPgv+7z1QBjHvNa0j3PBFG7/cwrHPCngkcZyGxxC5SJ/xxKUNi1wGOBp3FRr/PU\nJdEYLqpzGQmz7HunkGLae+uffpW1cgTyd/lucbK9AoIBAQDBP/tJ7hVwn6Cy4HNo\nMvr0rABB2zKqjL45pXjTMEVwv5OY80+PNfFQhJixvcqWf8OrZ+pJuRl69wxp0Ign\n8G3f1A3pbaSgu911mdYPeQ2pFTLM7qLkY/acEPY7v7vZ+NjOOE1H8MoF38C0FQi1\nx2lsZ6IkjDSAJqodNTDFUlcVeAk79WVYcLKAr8oTPom4Aic9hp32IErYo5hA9LY0\nSqC/t5MfvFNaRedoQ3WwWdAA9d82IKJrvU1beJ69flcMerCjSGH7AaYDctk4HULE\n/esXWb9jyCP0s627wE3w2Qgo4R5/Q6fVSHEmV5GVCqGXKhcf0aSJJnZhne0UHn8u\n6mxZAoIBAQCB4PwvqtgRAj3bxIyoP65AN6j2n2wk2TpLYUYC8XbgcJXmXuvJBD6f\nywgEc9khMEv/Z3r0vCoP+dW0SyK/+9bjLJozq3BCNrdgRqYrg7cnEaPbesgOPWY9\nR5KgCN8gctivZ8G3zdembR4qFyeyecwZ+96JfyEsk0V1IpRrZZg7soZ4qsDRKZc1\ndkEB7pxAfOl17cOtcZSQHuj8VDtDmUyySzySBGRrF3qoGhWbQ59Wp48Gw9/JZ/th\nwmr7LEnQZNzo3IbLngzUlCiRtRgNl9hCw5vZwfS8yEsS0a72lmKY3qGyXr3xAAhf\n07oi7EDdo42CbbjAFVk2H40iMvVR5d4U\n-----END PRIVATE KEY-----\nEOF\n\nchown proxy:proxy squidc.pem\nchown proxy:proxy squidk.pem\nchmod 400 squidc.pem \nchmod 400 squidk.pem\ncp squidc.pem /etc/squid/squidc.pem\ncp squidk.pem /etc/squid/squidk.pem\ncp squidc.pem /usr/local/share/ca-certificates/squidc.crt\nupdate-ca-certificates \n\nsed -i 's~http_access deny all~http_access allow all~' /etc/squid/squid.conf\nsed -i \"s~http_port 3128~http_port $HOST:3128\\nhttps_port $HOST:3129 tls-cert=/etc/squid/squidc.pem tls-key=/etc/squid/squidk.pem~\" /etc/squid/squid.conf\n\nsystemctl restart squid\nsystemctl status squid\n\n# validation, fails VM creation if commands fail\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I https://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I https://www.google.com\n", "num_lines": 140}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#######################################################################################################################\n# This script installs all dependencies found in this repository directly, without transitive dependencies, then uses\n# the appropriate requirements.txt file to install all transitive dependencies.\n#\n# NOTE: It should be invoked from an activated virtual environment, unless targeting system python directly is\n# acceptable.\n#\n# The intention is to allow packagers, people working with the RPM spec or debian rules file for example, to not have\n# duplicate that logic required to install from source what is distributed in this repository and via PyPI for items\n# living outside of this repository.\n#######################################################################################################################\n\nREPO_ROOT=\"$(dirname ${BASH_SOURCE[0]})/..\"\n\npushd ${REPO_ROOT} > /dev/null\n\nfind src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip install --no-deps\npip install -r ./src/azure-cli/requirements.$(python ./scripts/get-python-version.py).$(uname).txt\n\npopd > /dev/null\n", "num_lines": 23}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Build wheel and set the $share_folder to the artifacts folder\n\n. $(dirname ${BASH_SOURCE[0]})/build.sh\nshare_folder=$(pwd)/artifacts\n", "num_lines": 6}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build wheel packages containing both CLI product and tests. The script doesn't rely on a pre-existing virtual\n# environment.\n\nset -ev\n\n##############################################\n# clean up and dir search\nmkdir -p ./artifacts\n\n# Current folder (/azure-cli) is mounted from host which has different owner than docker container's\n# current user 0(root).\n# https://github.blog/2022-04-12-git-security-vulnerability-announced/\ngit config --global --add safe.directory $(pwd)\necho `git rev-parse --verify HEAD` > ./artifacts/build.sha\n\nmkdir -p ./artifacts/build\nmkdir -p ./artifacts/source\nmkdir -p ./artifacts/testsrc\n\noutput_dir=$(cd artifacts/build && pwd)\nsdist_dir=$(cd artifacts/source && pwd)\ntestsrc_dir=$(cd artifacts/testsrc && pwd)\nscript_dir=`cd $(dirname $BASH_SOURCE[0]); pwd`\n\ntarget_profile=${AZURE_CLI_TEST_TARGET_PROFILE:-latest}\nif [ \"$target_profile\" != \"latest\" ]; then\n    # example: hybrid-2019-03-01. Python module name can't begin with a digit.\n    target_profile=hybrid_${target_profile//-/_}\nfi\necho Pick up profile: $target_profile\n\n##############################################\n# Define colored output func\nfunction title {\n    LGREEN='\\033[1;32m'\n    CLEAR='\\033[0m'\n\n    echo -e ${LGREEN}$1${CLEAR}\n}\n\n##############################################\n# Update version strings\ntitle 'Determine version'\n. $script_dir/version.sh $1\n# echo -n $version > ./artifacts/version\n\n##############################################\n# build product packages\ntitle 'Build Azure CLI and its command modules'\nfor setup_file in $(find src -name 'setup.py'); do\n    pushd $(dirname ${setup_file}) >/dev/null\n    echo \"Building module at $(pwd) ...\"\n    python setup.py -q bdist_wheel -d $output_dir\n    python setup.py -q sdist -d $sdist_dir\n    popd >/dev/null\ndone\n\n##############################################\n# copy private packages\nif [ -z ./privates ]; then\n    cp ./privates/*.whl $output_dir\nfi\n\n##############################################\n# build test packages\ntitle 'Build Azure CLI tests package'\n\nfor test_src in $(find src/azure-cli/azure/cli/command_modules -name tests -type d); do\n    rel_path=${test_src##src/azure-cli/}\n\n    mkdir -p $testsrc_dir/$rel_path\n    cp -R $test_src/* $testsrc_dir/$rel_path\ndone\n\nif [ \"$target_profile\" == \"latest\" ]; then\n    # don't pack core tests for profiles other than latest\n    for test_src in $(find src -name tests | grep -v command_modules); do\n        rel_path=${test_src##src/}\n        rel_path=(${rel_path/\\// })\n        rel_path=${rel_path[1]}\n\n        mkdir -p $testsrc_dir/$rel_path\n        cp -R $test_src/* $testsrc_dir/$rel_path\n    done\nfi\n\ncat >$testsrc_dir/setup.py <<EOL\n#!/usr/bin/env python\n\nfrom setuptools import setup\n\nVERSION = \"1.0.0.$version\"\n\nCLASSIFIERS = [\n    'Development Status :: 3 - Alpha',\n    'Intended Audience :: Developers',\n    'Programming Language :: Python',\n    'Programming Language :: Python :: 3',\n    'Programming Language :: Python :: 3.7',\n    'Programming Language :: Python :: 3.8',\n    'Programming Language :: Python :: 3.9',\n    'Programming Language :: Python :: 3.10',\n    'License :: OSI Approved :: MIT License',\n]\n\nDEPENDENCIES = [\n    'azure-cli',\n    'azure-cli-testsdk'\n]\n\nsetup(\n    name='azure-cli-fulltest',\n    version=VERSION,\n    description='Microsoft Azure Command-Line Tools Full Tests',\n    license='MIT',\n    author='Microsoft Corporation',\n    author_email='azpycli@microsoft.com',\n    url='https://github.com/Azure/azure-cli',\n    zip_safe=False,\n    classifiers=CLASSIFIERS,\n    packages=[\nEOL\n\nif [ \"$target_profile\" == \"latest\" ]; then\n    echo \"        'azure.cli.core.tests',\" >>$testsrc_dir/setup.py\nfi\n\nfor name in `ls src/azure-cli/azure/cli/command_modules`; do\n    test_folder=src/azure-cli/azure/cli/command_modules/$name/tests\n    if [ -d $test_folder ]; then\n        echo \"        'azure.cli.command_modules.$name.tests',\" >>$testsrc_dir/setup.py\n        if [ -d $test_folder/$target_profile ]; then\n            echo \"        'azure.cli.command_modules.$name.tests.$target_profile',\" >>$testsrc_dir/setup.py\n        fi\n    fi\ndone\n\n\ncat >>$testsrc_dir/setup.py <<EOL\n    ],\n    package_data={'': ['*.bat',\n                       '*.byok',\n                       '*.cer',\n                       '*.gql',  # graphql used by apim\n                       '*.js',\n                       '*.json',\n                       '*.kql',\n                       '*.md',\n                       '*.pem',\n                       '*.pfx',\n                       '*.sql',\n                       '*.txt',\n                       '*.txt',\n                       '*.xml',\n                       '*.yml',\n                       '*.zip',\n                       '**/*.bat',\n                       '**/*.byok',\n                       '**/*.cer',\n                       '**/*.gql',\n                       '**/*.ipynb',\n                       '**/*.jar',\n                       '**/*.js',\n                       '**/*.json',\n                       '**/*.kql',\n                       '**/*.md',\n                       '**/*.pem',\n                       '**/*.pfx',\n                       '**/*.sql',\n                       '**/*.txt',\n                       '**/*.txt',\n                       '**/*.xml',\n                       'data/*',\n                       'recordings/*.yaml']},\n    install_requires=DEPENDENCIES\n)\nEOL\n\ncat >>$testsrc_dir/setup.cfg <<EOL\n[bdist_wheel]\nuniversal=1\nEOL\n\ncat >>$testsrc_dir/README.txt <<EOL\nAzure CLI Test Cases\nEOL\n\npushd $testsrc_dir >/dev/null\npython setup.py -q bdist_wheel -d $output_dir\npython setup.py -q sdist -d $sdist_dir\npopd >/dev/null\n\n##############################################\n# clear afterwards\nrm -rf $testsrc_dir\ngit checkout src\n\n##############################################\n# summary\ntitle 'Results'\necho $(ls $sdist_dir | wc -l) packages created.\n", "num_lines": 204}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nREPO_ROOT=\"$(dirname ${BASH_SOURCE[0]})/../..\"\n\n# Uninstall any cruft that can poison the rest of the checks in this script.\npip freeze > baseline_deps.txt\npip uninstall -y -r baseline_deps.txt || true\npip list\npip check\nrm baseline_deps.txt\n\n# Install everything from our repository first.\n${REPO_ROOT}/scripts/install_full.sh\n\npip check\n\npython -m azure.cli --version\n\npython -m azure.cli self-test\n", "num_lines": 22}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# ARM64 image does not have docker, install manually\nset -evx\nif [[ $(dpkg --print-architecture) == \"amd64\" ]]; then\n    echo \"Docker is already installed on AMD64\"\n    exit 0\nfi\n# https://docs.docker.com/engine/security/rootless/\n/bin/bash -c \"$(curl -fsSL https://get.docker.com)\"\nsudo apt-get install -y uidmap\ndockerd-rootless-setuptool.sh install\nexport XDG_RUNTIME_DIR=/home/cloudtest/.docker/run\nPATH=/usr/bin:/sbin:/usr/sbin:$PATH dockerd-rootless.sh &\nsleep 5\ndocker context use rootless\n", "num_lines": 16}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Set the storage credentials for the given travis repo.\n\n# Pre-requisite:\n# 1. Travis CLI https://github.com/travis-ci/travis.rb\n# 2. Azure CLI\n# 3. Login Azure CLI with credential which has access to the target storage account.\n\n# Input:\n# $1 - storage account name\n# $2 - travis CI repo name\n\nset -ev\n\nexport AZURE_STORAGE_ACCOUNT=$1\n\naz storage container create -n store -otsv\naz storage container create -n edge -otsv\n\nexpiry_date=`date -v+6m +'%Y-%m-%dT00:00Z'`\necho \"Set SAS expiry date to $expiry_date\"\n\ntravis env set -r $2 PUBLISH_STORAGE_ACCT $1\ntravis env set -r $2 PUBLISH_STORAGE_SAS $(az storage container generate-sas -n store --permissions w --expiry $expiry_date -otsv)\ntravis env set -r $2 -P PUBLISH_CONTAINER store\n\ntravis env set -r $2 EDGE_STORAGE_ACCT $1\ntravis env set -r $2 EDGE_STORAGE_SAS $(az storage container generate-sas -n edge --permissions lw --expiry $expiry_date -otsv)\ntravis env set -r $2 -P EDGE_CONTAINER edge\n\ntravis env list -r $2\n", "num_lines": 33}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\necho \"Listing Available Extensions:\"\naz extension list-available -otable\n\n# turn off telemetry as it crowds output\nexport AZURE_CLI_DIAGNOSTICS_TELEMETRY=\noutput=$(az extension list-available --query [].name -otsv)\nexit_code=0\n\n# azure-cli-ml: https://github.com/Azure/azure-cli-extensions/issues/826\nignore_list='azure-cli-ml fzf arcappliance arcdata connectedk8s'\n\nfor ext in $output; do\n    echo\n    # Use regex to detect if $ext is in $ignore_list\n    if [[ $ignore_list =~ $ext ]]; then\n        echo \"Ignore extension: $ext\"\n        continue\n    fi\n\n    echo \"Verifying extension:\" $ext\n    az extension add -n $ext\n    if [ $? != 0 ]\n    then\n        exit_code=1\n        echo \"Failed to load:\" $ext\n    fi\ndone\n\npip list -v\n\naz self-test --debug\nif [ $? != 0 ]\nthen\n    exit_code=1\n    echo \"Failed to verify:\" $ext\nfi\n\nexit $exit_code\n", "num_lines": 51}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\necho '=== List installed packages'\npip freeze\n\necho '=== Begin testing'\nunset AZURE_CLI_DIAGNOSTICS_TELEMETRY\nazdev verify package $share_folder/build/\n\nexport AZURE_CORE_COLLECT_TELEMETRY=False\necho '= Verify Commands with -h'\nazdev verify commands\n", "num_lines": 25}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n. $(cd $(dirname $0); pwd)/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\nset -ev\n\noutput=$(az cloud list-profiles -otsv)\n\nazdev verify package $share_folder/build/\n\nfor profile in $output; do\n    echo\n    echo \"Verifying profile:\" $profile\n    az cloud update --profile $profile\n    azdev verify load-all\n    echo $profile \"profile has been verified.\"\ndone\n\necho \"Successfully loaded all commands in each profile.\"\n", "num_lines": 28}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nwd=`cd $(dirname $0); pwd`\n\n. $wd/artifacts.sh\n\nls -la $share_folder/build\n\nALL_MODULES=`find $share_folder/build/ -name \"*.whl\"`\n\npip install -e ./tools\n[ -d privates ] && pip install -qqq privates/*.whl\npip install $ALL_MODULES\n\npip install sphinx==1.6.7 Jinja2==3.0.3\necho \"Installed.\"\n\ncd doc/sphinx; python ./__main__.py\n\npython $wd/test_help_doc_arguments.py \"./_build/xml/ind.xml\"\n\necho \"OK.\"\n", "num_lines": 25}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\nfor TOX_FILE in $(find src -name tox.ini); do\n    pwd\n    (cd $(dirname $TOX_FILE) && tox)\ndone", "num_lines": 8}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script is used by release pipeline task \"Release Notes\" to update\n# https://github.com/MicrosoftDocs/azure-docs-cli.\n#\n# It does several things:\n# 1. Transfer release notes from src/azure-cli/HISTORY.rst to docs-ref-conceptual/release-notes-azure-cli.md\n# 2. Update ms.date\n# 3. Update version number in docs-ref-conceptual/includes/current-version.md\n\n# sed manual: https://www.gnu.org/software/sed/manual/sed.html\n\nset -ev\n\nBOT_TOKEN=$(az keyvault secret show --vault-name \"${BOT_VAULT_NAME}\" --name \"${BOT_SECRET_NAME}\" --query value -otsv)\n\ngit clone https://github.com/Azure/azure-cli.git\ncd azure-cli\ngit config --local user.email \"AzPyCLI@microsoft.com\"\ngit config --local user.name \"Azure CLI Team\"\ngit remote rename origin upstream\ngit checkout -b main upstream/main\nPRE_VERSION=$(sed -n -e 's/.*__version__.*\"\\(.*\\)\"/\\1/p' src/azure-cli/azure/cli/__main__.py)\ngit checkout -b release upstream/release\ncd ..\ngit clone https://github.com/MicrosoftDocs/azure-docs-cli.git\ncd azure-docs-cli\ngit config --local user.email \"AzPyCLI@microsoft.com\"\ngit config --local user.name \"Azure CLI Team\"\ngit remote rename origin upstream\ngit remote add origin https://anything:${BOT_TOKEN}@github.com/${BOT_ACCOUNT_NAME}/azure-docs-cli.git\nDOC_BRANCH_NAME=\"cli-release-notes-${CLI_VERSION}\"\ngit checkout -b ${DOC_BRANCH_NAME}\n\n# Copy release notes\n# 2\\.31\\.0\nESCAPED_CLI_VERSION=`echo \"$CLI_VERSION\" | sed 's/\\./\\\\\\./g'`\n# 2\\.30\\.0\nESCAPED_PRE_VERSION=`echo \"$PRE_VERSION\" | sed 's/\\./\\\\\\./g'`\n# The 1st sed finds all lines between (including) 2.31.0 and 2.30.0\n#   1:             2.31.0\n#   2:             ++++++\n#                  ...\n#   2nd last line:\n#   last line:     2.30.0\n# The 2nd sed deletes line 1, 2 and last line\n# The 3rd sed deletes the last line\n# The 4th sed deletes all PR numbers, like (#20233)\nsed -n '/'\"$ESCAPED_CLI_VERSION\"'/,/'\"$ESCAPED_PRE_VERSION\"'/p' ../azure-cli/src/azure-cli/HISTORY.rst| sed '1d;2d;$d'| sed '$d' | sed 's| (#[0-9]\\+)$||' | tee note.tmp\n# December 14, 2021\nRELEASE_DATE=$(date -d \"next tuesday\" '+%B %d, %Y')\n# 12/14/2021\nMODIFY_DATE=$(date -d \"next tuesday\" '+%m/%d/%Y')\n# Update ms.date\nsed -i \"s|^ms.date.*$|ms.date: ${MODIFY_DATE}|g\" docs-ref-conceptual/release-notes-azure-cli.md\n# Find the top level heading '# Azure CLI release notes' and append content of note.tmp after it.\nsed -i '/^# .*$/ r note.tmp' docs-ref-conceptual/release-notes-azure-cli.md\n# Find the top level heading '# Azure CLI release notes' and append lines:\n#   # December 7, 2021\n#\n#   Version 2.31.0\nsed -i '/^# .*$/a \\\\n## '\"${RELEASE_DATE}\"'\\n\\nVersion '\"${CLI_VERSION}\"'' docs-ref-conceptual/release-notes-azure-cli.md\n# Update bold text like '**ARM**' to markdown heading '### ARM'\nsed -i 's/^\\*\\*\\(.*\\)\\*\\*$/### \\1/g' docs-ref-conceptual/release-notes-azure-cli.md\n\n# Update ms.date\nsed -i \"s|^ms.date.*$|ms.date: ${MODIFY_DATE}|g\" docs-ref-conceptual/includes/current-version.md\n# Update current version\nsed -i 's/'\"$PRE_VERSION\"'/'\"$CLI_VERSION\"'/g' docs-ref-conceptual/includes/current-version.md\n\ngit commit -am \"azure-cli release notes ${CLI_VERSION}\"\ngit push origin ${DOC_BRANCH_NAME}\ncurl \\\n  --user \"anything:${BOT_TOKEN}\" \\\n  -d \"{\\\"title\\\":\\\"release note for azure cli ${CLI_VERSION}\\\",\\\"head\\\":\\\"${BOT_ACCOUNT_NAME}:${DOC_BRANCH_NAME}\\\",\\\"base\\\":\\\"main\\\"}\" \\\n  https://api.github.com/repos/MicrosoftDocs/azure-docs-cli/pulls\n", "num_lines": 75}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Update the version strings in the source code\n\n# Input:\n#   $1 - the version string, if omitted, use current time\n\nversion=$1\n\nif [ -z $version ]; then\n    echo 'Use utc timestamp as version'\n    version=dev`date -u '+%Y%m%d%H%M%S'`\nfi\n\necho \"Replace with version: $version\"\n\nplatform=`uname`\n\nfor each in $(find src -name __main__.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\nfor each in $(find src -name __init__.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^__version__ = [\\\"']\\(.*\\)[\\\"']/__version__ = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\nfor each in $(find src -name setup.py); do\n    if [ \"$platform\" == \"Darwin\" ]; then\n        sed -i \"\" \"s/^VERSION = [\\\"']\\(.*\\)[\\\"']/VERSION = \\\"\\1.$version\\\"/\" $each\n    else\n        sed -i \"s/^VERSION = [\\\"']\\(.*\\)[\\\"']/VERSION = \\\"\\1.$version\\\"/\" $each\n    fi\ndone\n\n", "num_lines": 43}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Extract the version of the CLI from azure-cli package's __main__.py file.\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n\nver=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\necho $ver > $BUILD_STAGINGDIRECTORY/version\necho $ver > $BUILD_STAGINGDIRECTORY/azure-cli-${ver}.txt", "num_lines": 7}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\n# This script is expected to be run in a container environment, therefore sudo doesn't present\n# here.\n\nset -exv\n\n: \"${CLI_VERSION:?CLI_VERSION environment variable not set.}\"\n: \"${CLI_VERSION_REVISION:?CLI_VERSION_REVISION environment variable not set.}\"\n\nls -Rl /mnt/artifacts\n\nWORKDIR=`cd $(dirname $0); cd ../../../; pwd`\nPYTHON_VERSION=\"3.10.10\"\nSCRIPT_DIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Update APT packages\napt-get update\n# uuid-dev is used to build _uuid module: https://github.com/python/cpython/pull/3796\napt-get install -y libssl-dev libffi-dev python3-dev zlib1g-dev uuid-dev wget\n\n# In Ubuntu 18.04, debhelper 11.1.6 has bug which makes it fail to dpkg-buildpackage. Use backport version instead.\n# https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=897569\nif cat /etc/lsb-release | grep 18.04\nthen\n  apt-get install -y debhelper -t bionic-backports\nelse\n  apt-get install -y debhelper\nfi\n\n# Git is not strictly necessary, but it would allow building an experimental package\n# with dependency which is currently only available in its git repo feature branch.\napt-get install -y git\n\n# Download Python source code\nPYTHON_SRC_DIR=$(mktemp -d)\nwget -qO- https://www.python.org/ftp/python/$PYTHON_VERSION/Python-$PYTHON_VERSION.tgz | tar -xz -C \"$PYTHON_SRC_DIR\"\necho \"Python source code is in $PYTHON_SRC_DIR\"\n\n# Build Python\n$PYTHON_SRC_DIR/*/configure --srcdir $PYTHON_SRC_DIR/* --prefix $WORKDIR/python_env\nmake\nmake install\n\n$WORKDIR/python_env/bin/python3 -m pip install --upgrade pip setuptools\n\nexport PATH=$PATH:$WORKDIR/python_env/bin\n\nfind ${WORKDIR}/src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip3 install --no-deps\npip3 install -r ${WORKDIR}/src/azure-cli/requirements.py3.$(uname).txt\n$WORKDIR/python_env/bin/python3 ${WORKDIR}/scripts/trim_sdk.py\n\n# Create create directory for debian build\nmkdir -p $WORKDIR/debian\n$SCRIPT_DIR/prepare.sh $WORKDIR/debian $WORKDIR/az.completion $WORKDIR\n\ncd $WORKDIR\ndpkg-buildpackage -us -uc\n\ndeb_file=$WORKDIR/../azure-cli_${CLI_VERSION}-${CLI_VERSION_REVISION:=1}_*.deb\ncp $deb_file /mnt/output/\n", "num_lines": 66}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#######################################################################################################################\n# This script does three fundamental things:                                                                          #\n#   1. Add Microsoft's GPG Key has a trusted source of apt packages.                                                  #\n#   2. Add Microsoft's repositories as a source for apt packages.                                                     #\n#   3. Installs the Azure CLI from those repositories.                                                                #\n# Given the nature of this script, it must be executed with elevated privileges, i.e. with `sudo`.                    #\n#                                                                                                                     #\n# Remember, with great power comes great responsibility.                                                              #\n#                                                                                                                     #\n# Do not be in the habit of executing scripts from the internet with root-level access to your machine. Only trust    #\n# well-known publishers.                                                                                              #\n#######################################################################################################################\n\nset -e\n\nif [[ $# -ge 1 && $1 == \"-y\" ]]; then\n    global_consent=0\nelse\n    global_consent=1\nfi\n\nfunction assert_consent {\n    if [[ $2 -eq 0 ]]; then\n        return 0\n    fi\n\n    echo -n \"$1 [Y/n] \"\n    read consent\n    if [[ ! \"${consent}\" == \"y\" && ! \"${consent}\" == \"Y\" && ! \"${consent}\" == \"\" ]]; then\n        echo \"'${consent}'\"\n        exit 1\n    fi\n}\n\nglobal_consent=0 # Artificially giving global consent after review-feedback. Remove this line to enable interactive mode\n\nsetup() {\n\n    assert_consent \"Add packages necessary to modify your apt-package sources?\" ${global_consent}\n    set -v\n    export DEBIAN_FRONTEND=noninteractive\n    apt-get update\n    apt-get install -y apt-transport-https lsb-release gnupg curl\n    set +v\n\n    assert_consent \"Add Microsoft as a trusted package signer?\" ${global_consent}\n    set -v\n    curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > /etc/apt/trusted.gpg.d/microsoft.gpg\n    set +v\n\n    assert_consent \"Add the Azure CLI Repository to your apt sources?\" ${global_consent}\n    set -v\n    # Use env var DIST_CODE for the package dist name if provided\n    if [[ -z $DIST_CODE ]]; then\n        CLI_REPO=$(lsb_release -cs)\n        shopt -s nocasematch\n        ERROR_MSG=\"Unable to find a package for your system. Please check if an existing package in https://packages.microsoft.com/repos/azure-cli/dists/ can be used in your system and install with the dist name: 'curl -sL https://aka.ms/InstallAzureCLIDeb | sudo DIST_CODE=<dist_code_name> bash'\"\n        if [[ ! $(curl -sL https://packages.microsoft.com/repos/azure-cli/dists/) =~ $CLI_REPO ]]; then\n            DIST=$(lsb_release -is)\n            if [[ $DIST =~ \"Ubuntu\" ]]; then\n                CLI_REPO=\"jammy\"\n            elif [[ $DIST =~ \"Debian\" ]]; then\n                CLI_REPO=\"bullseye\"\n            elif [[ $DIST =~ \"LinuxMint\" ]]; then\n                CLI_REPO=$(cat /etc/os-release | grep -Po 'UBUNTU_CODENAME=\\K.*') || true\n                if [[ -z $CLI_REPO ]]; then\n                    echo $ERROR_MSG\n                    exit 1\n                fi\n            else\n                echo $ERROR_MSG\n                exit 1\n            fi\n        fi\n    else\n        CLI_REPO=$DIST_CODE\n        if [[ ! $(curl -sL https://packages.microsoft.com/repos/azure-cli/dists/) =~ $CLI_REPO ]]; then\n            echo \"Unable to find an azure-cli package with DIST_CODE=$CLI_REPO in https://packages.microsoft.com/repos/azure-cli/dists/.\"\n            exit 1\n        fi\n    fi\n    echo \"deb [arch=$(dpkg --print-architecture)] https://packages.microsoft.com/repos/azure-cli/ ${CLI_REPO} main\" \\\n        > /etc/apt/sources.list.d/azure-cli.list\n    apt-get update\n    set +v\n\n    assert_consent \"Install the Azure CLI?\" ${global_consent}\n    apt-get install -y azure-cli\n\n}\n\nsetup  # ensure the whole file is downloaded before executing\n", "num_lines": 95}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build APT package in an Azure Container Instances\n# This script assumes the Azure CLI is installed and logged in.\n\nset -exv\n\n: ${DISTRO:?\"DISTRO is not set\"}\n: ${DISTRO_BASE_IMAGE:?\"DISTRO_BASE_IMAGE is not set\"}\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\ndocker run --rm \\\n           -v \"$BUILD_SOURCESDIRECTORY\":/mnt/repo \\\n           -v \"$BUILD_STAGINGDIRECTORY\":/mnt/output \\\n           -v \"$SYSTEM_ARTIFACTSDIRECTORY\":/mnt/artifacts \\\n           -e CLI_VERSION=$CLI_VERSION \\\n           -e CLI_VERSION_REVISION=1~$DISTRO \\\n           -e DEBIAN_FRONTEND=noninteractive \\\n           $DISTRO_BASE_IMAGE \\\n           /mnt/repo/scripts/release/debian/build.sh\n", "num_lines": 22}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\nset -evx\n\n# Create the debian/ directory for building the azure-cli Debian package\n\n# This script takes an argument of the empty directory where the files will be placed.\n\nif [ -z \"$1\" ]\n  then\n    echo \"No argument supplied for debian directory.\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]\n  then\n    echo \"No argument supplied for completion script.\"\n    exit 1\nfi\n\nif [ -z \"$3\" ]\n  then\n    echo \"No argument supplied for source directory.\"\n    exit 1\nfi\n\nTAB=$'\\t'\n\ndebian_dir=$1\ncompletion_script=$2\nsource_dir=$3\nmkdir $debian_dir/source\n\necho '1.0' > $debian_dir/source/format\necho '9' > $debian_dir/compat\n\ncat > $debian_dir/changelog <<- EOM\nazure-cli (${CLI_VERSION}-${CLI_VERSION_REVISION:=1}) unstable; urgency=low\n\n  * Debian package release.\n\n -- Azure Python CLI Team <azpycli@microsoft.com>  $(date -R)\n\nEOM\n\ncat > $debian_dir/control <<- EOM\nSource: azure-cli\nSection: python\nPriority: extra\nMaintainer: Azure Python CLI Team <azpycli@microsoft.com>\nBuild-Depends: debhelper (>= 9), libssl-dev, libffi-dev, python3-dev\nStandards-Version: 3.9.5\nHomepage: https://github.com/azure/azure-cli\n\nPackage: azure-cli\nArchitecture: any\nDepends: \\${shlibs:Depends}, \\${misc:Depends}\nDescription: Azure CLI\n A great cloud needs great tools; we're excited to introduce Azure CLI,\n our next generation multi-platform command line experience for Azure.\n\nEOM\n\ncat > $debian_dir/copyright <<- EOM\nFormat: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\nUpstream-Name: azure-cli\nUpstream-Contact: Azure Python CLI Team <azpycli@microsoft.com>\nSource: https://github.com/azure/azure-cli\n\nFiles: *\nCopyright: Copyright (c) Microsoft Corporation\nLicense: MIT\nAzure CLI\n\nCopyright (c) Microsoft Corporation\n\nAll rights reserved.\n\nMIT License\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"\"Software\"\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nEOM\n\n# TODO: Instead of \"_ssl.cpython-310-x86_64-linux-gnu.so\" only, find all .so files with \"find debian/azure-cli/opt/az -type f -name '*.so'\"\n\ncat > $debian_dir/rules << EOM\n#!/usr/bin/make -f\n\n# Uncomment this to turn on verbose mode.\nexport DH_VERBOSE=1\nexport DH_OPTIONS=-v\n\n%:\n${TAB}dh \\$@ --sourcedirectory $source_dir\n\noverride_dh_install:\n${TAB}mkdir -p debian/azure-cli/opt/az\n${TAB}cp -a python_env/* debian/azure-cli/opt/az\n${TAB}mkdir -p debian/azure-cli/usr/bin/\n${TAB}echo \"\\043!/usr/bin/env bash\\nbin_dir=\\140cd \\\"\\044(dirname \\\"\\044BASH_SOURCE[0]\\\")\\\"; pwd\\140\\nAZ_INSTALLER=DEB \\\"\\044bin_dir\\\"/../../opt/az/bin/python3 -Im azure.cli \\\"\\044\\100\\\"\" > debian/azure-cli/usr/bin/az\n${TAB}chmod 0755 debian/azure-cli/usr/bin/az\n${TAB}mkdir -p debian/azure-cli/etc/bash_completion.d/\n${TAB}cat ${completion_script} > debian/azure-cli/etc/bash_completion.d/azure-cli\n${TAB}dpkg-shlibdeps -v --warnings=7 -Tdebian/azure-cli.substvars -dDepends -edebian/azure-cli/opt/az/bin/python3 debian/azure-cli/opt/az/lib/python3.10/lib-dynload/_ssl.cpython-310-*-linux-gnu.so\n\n\noverride_dh_strip:\n${TAB}dh_strip --exclude=_cffi_backend\n\nEOM\n\ncat $debian_dir/rules\n\n# debian/rules should be executable\nchmod 0755 $debian_dir/rules\n", "num_lines": 125}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nbase_images=(\"ubuntu:xenial\" \"ubuntu:bionic\" \"debian:stretch\" \"debian:jessie\" \"debian:buster\")\n\nset -e\n\nfor image in ${base_images[@]}; do\n    docker build --build-arg base=${image} s-t deb-installer:current -f Dockerfile.install_test .\n    docker run -it --rm deb-installer:current\ndone\n", "num_lines": 11}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a ubuntu/debian docker.\nset -exv\n\nexport USERNAME=azureuser\n\napt update\napt install -y apt-transport-https git gcc python3-dev\n\ndpkg -i /mnt/artifacts/azure-cli_$CLI_VERSION-1~${DISTRO}_*.deb\n\ntime az self-test\ntime az --version\n\ncd /azure-cli/\n/opt/az/bin/python3 -m pip install wheel\nln -sf /opt/az/bin/python3 /usr/bin/python\n./scripts/ci/build.sh\n\n/opt/az/bin/python3 -m pip install pytest\n/opt/az/bin/python3 -m pip install pytest-xdist\n/opt/az/bin/python3 -m pip install pytest-forked\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs /opt/az/bin/python3 -m pip install --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs /opt/az/bin/python3 -m pip install --upgrade --ignore-installed --no-deps\n\n/opt/az/bin/python3 /azure-cli/scripts/release/debian/test_deb_package.py\n", "num_lines": 29}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a docker to verify installing deb package from the apt repository.\n\napt update -y\napt install curl -y\ncounter=4\n\nwhile [ $counter -gt 0 ]\ndo\n    curl -sL https://aka.ms/InstallAzureCLIDeb | bash\n    ACTUAL_VERSION=$(az version | sed -n 's|\"azure-cli\": \"\\(.*\\)\",|\\1|p' | sed 's|[[:space:]]||g')\n    echo \"actual version:${ACTUAL_VERSION}\"\n    echo \"expected version:${CLI_VERSION}\"\n\n    if [ \"$ACTUAL_VERSION\" != \"$CLI_VERSION\" ]; then\n        if [ ! -z \"$ACTUAL_VERSION\" ]; then\n            echo \"Latest package is not in the repo.\"\n            exit 1\n        fi\n        echo \"wait 5m\"\n        sleep 300\n        counter=$(( $counter - 1 ))\n    else\n        echo \"Latest package is verified.\"\n        exit 0\n    fi\ndone\necho \"Timeout!\"\nexit 1\n", "num_lines": 31}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\nset -evx\n\nIMAGE_NAME=clibuild$BUILD_BUILDNUMBER\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\ndocker build --no-cache \\\n             --build-arg BUILD_DATE=\"`date -u +\"%Y-%m-%dT%H:%M:%SZ\"`\" \\\n             --build-arg CLI_VERSION=$CLI_VERSION \\\n             --tag $IMAGE_NAME:latest \\\n             $BUILD_SOURCESDIRECTORY\n\ndocker save -o \"$BUILD_STAGINGDIRECTORY/docker-azure-cli-${CLI_VERSION}.tar\" $IMAGE_NAME:latest\n", "num_lines": 19}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nroot=$(cd $(dirname $0); pwd)\n\nset -evx\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\nHOMEBREW_UPSTREAM_URL=`cat $BUILD_STAGINGDIRECTORY/github/upstream_url`\nTAR_NAME=azure-cli-$CLI_VERSION.tar.gz\n\ndocker_files=$(cd $BUILD_SOURCESDIRECTORY/scripts/release/homebrew/docker; pwd)\nsrc_files=$(cd $BUILD_SOURCESDIRECTORY/src; pwd)\n\necho \"Generating formula in docker container ... \"\ndocker run -v $docker_files:/mnt/scripts \\\n           -v $src_files:/mnt/src \\\n           -e CLI_VERSION=$CLI_VERSION \\\n           -e HOMEBREW_UPSTREAM_URL=$HOMEBREW_UPSTREAM_URL \\\n           --name azurecli \\\n           python:3.6 \\\n           /mnt/scripts/run.sh\n\n# clean up\nrm -rf $BUILD_STAGINGDIRECTORY/metadata\n\ndocker cp azurecli:azure-cli.rb $BUILD_STAGINGDIRECTORY/azure-cli.rb\ndocker rm --force azurecli\n", "num_lines": 28}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nset -ev\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\n\necho == Remove pre-installed azure-cli ==\nbrew uninstall azure-cli\n\necho == Install azure-cli.rb formula ==\nbrew install --build-from-source $SYSTEM_ARTIFACTSDIRECTORY/homebrew/azure-cli.rb\n\nAZ_BASE=/usr/local/Cellar/azure-cli/$CLI_VERSION/libexec\nexport PATH=$AZ_BASE/bin:$PATH\nexport OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES\necho $PATH\npip install wheel\n./scripts/ci/build.sh\npip install pytest --prefix $AZ_BASE\npip install pytest-xdist --prefix $AZ_BASE\npip install pytest-forked --prefix $AZ_BASE\n\nfind ./artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix $AZ_BASE --upgrade --ignore-installed\nfind ./artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix $AZ_BASE --upgrade --ignore-installed --no-deps\n\n# workaround for this bug (https://github.com/microsoft/azure-devops-python-api/issues/354)\nmkdir -p ~/.vsts/python-sdk/cache\n\nPYTHON_VERSION=`ls $AZ_BASE/lib/ | head -n 1`\npython ./scripts/release/homebrew/test_homebrew_package.py $AZ_BASE $PYTHON_VERSION", "num_lines": 30}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -ev\n\n# Download the release package generated by the Github when a tag of the release is created to storage account\n\n: {AZURE_STORAGE_ACCOUNT:?\"AZURE_STORAGE_ACCOUNT not set\"}\n: {AZURE_STORAGE_KEY:?\"AZURE_STORAGE_KEY not set\"}\n\nCLI_VERSION=`cat $SYSTEM_ARTIFACTSDIRECTORY/metadata/version`\nTAR_NAME=azure-cli-$CLI_VERSION.tar.gz\n\nmkdir -p $BUILD_STAGINGDIRECTORY/github/ >/dev/null 2>&1\ncurl -sL https://github.com/Azure/azure-cli/archive/$TAR_NAME -o $BUILD_STAGINGDIRECTORY/github/$TAR_NAME\n\naz storage blob upload -c releases -n $TAR_NAME -f $BUILD_STAGINGDIRECTORY/github/$TAR_NAME\n\n# Make sure the URL is publicly available\nHOMEBREW_UPSTREAM_URL=$(az storage blob url -c releases -n $TAR_NAME -otsv)\ncurl -sfS -I $HOMEBREW_UPSTREAM_URL >/dev/null\necho -n $HOMEBREW_UPSTREAM_URL > $BUILD_STAGINGDIRECTORY/github/upstream_url\n", "num_lines": 22}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nroot=$(cd $(dirname $0); pwd)\n\npip install wheel\npip install -U pip\npip install -r $root/requirements.txt\nfind /mnt/src/ -name setup.py -type f | xargs -I {} dirname {} | grep -v azure-cli-testsdk | xargs pip install --no-deps\npip install -r /mnt/src/azure-cli/requirements.py3.Darwin.txt\n\npip list\n\n# default option is update_existing to build from homebrew master branch,\n# append '-b use_template' to build from formula_template.txt \npython $root/formula_generate.py\n", "num_lines": 16}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This is the script builds the final wheel packages for shipping. The major difference between this script and the\n# scripts/ci/build.sh is that this script doesn't build testsdk and test packages. It doesn't update version string,\n# either. Therefore this script is shorter and cleaner.\n\nset -ev\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n: \"${BUILD_SOURCESDIRECTORY:=`cd $(dirname $0); cd ../../../; pwd`}\"\n\ncd $BUILD_SOURCESDIRECTORY\n\nbranch=$1\necho \"Branch $branch\"\n\necho \"Search setup files from `pwd`.\"\npython --version\n\npip install -U pip setuptools wheel\npip list\n\nscript_dir=`cd $(dirname $BASH_SOURCE[0]); pwd`\n\nif [[ \"$branch\" != \"release\" ]]; then\n    . $script_dir/../../ci/version.sh post`date -u '+%Y%m%d%H%M%S'`\nfi\n\nfor setup_file in $(find src -name 'setup.py' | grep -v azure-cli-testsdk); do\n    pushd `dirname $setup_file`\n    python setup.py bdist_wheel -d $BUILD_STAGINGDIRECTORY\n    python setup.py sdist -d $BUILD_STAGINGDIRECTORY\n    popd\ndone\n", "num_lines": 35}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n: \"${CLI_VERSION:?CLI_VERSION environment variable not set.}\"\n\nyum check-update\nyum install -y gcc rpm-build rpm-level rpmlint make bash corutils diffutils \\\n               path rpmdevtools python libffi-devel python3-devel openssl-devel \\\n               wget\n\nset -ev\n\nexport REPO_PATH=`cd $(dirname $0); cd ../../../; pwd`\nrpmbuild -v -bb --clean $REPO_PATH/scripts/release/rpm/azure-cli.spec && cp /root/rpmbuild/RPMS/x86_64/* /mnt/output\n", "num_lines": 14}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Checks to see if all RPM files passed to this program are signed.\n# Note: This script must be run as `root` on an RPM based Linux machine.\n\nset -e\n\nif [[ $# -lt 1 ]]; then\n    echo \"no arguments provided\" >&2\n    exit 2\nfi\n\n# For the purpose of this script, we will always want to consider files signed by Microsoft to be valid.\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\n\nfor file in $@; do\n    rpm --checksig ${file} | grep rsa\ndone", "num_lines": 18}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build assets related to Linux Distributions that use RPM/yum for installation.\n\nset -exv\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set.}\"\n\n# DOCKERFILE should be one of 'ubi' or 'fedora'\n: \"${DOCKERFILE:?DOCKERFILE environment variable not set.}\"\n# IMAGE should be RHEL or Fedora docker image url\n: \"${IMAGE:?IMAGE environment variable not set.}\"\n# PYTHON_PACKAGE should be python package name\n: \"${PYTHON_PACKAGE:?PYTHON_PACKAGE environment variable not set.}\"\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\n# Create a container image that includes the source code and a built RPM using this file.\ndocker build \\\n    --target build-env \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    --build-arg python_package=${PYTHON_PACKAGE} \\\n    -f ./scripts/release/rpm/${DOCKERFILE}.dockerfile \\\n    -t azure/azure-cli:${DOCKERFILE}-builder \\\n    .\n\n# Continue the previous build, and create a container that has the current azure-cli build but not the source code.\ndocker build \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    --build-arg python_package=${PYTHON_PACKAGE} \\\n    -f ./scripts/release/rpm/${DOCKERFILE}.dockerfile \\\n    -t azure/azure-cli:${DOCKERFILE} \\\n    .\n\n# Extract the built RPM so that it can be distributed independently.\n# The RPM file looks like azure-cli-2.32.0-1.el7.x86_64.rpm\nid=$(docker create azure/azure-cli:${DOCKERFILE}-builder)\n# https://docs.docker.com/engine/reference/commandline/cp/\n# Append /. so that the x86_64 folder's content is copied, instead of x86_64 folder itself.\ndocker cp $id:/out/. ${BUILD_STAGINGDIRECTORY}\n\n# Save these too a staging directory so that later build phases can choose to save them as Artifacts or publish them to\n# a registry.\n#\n# The products of `docker save` can be rehydrated using `docker load`.\n# mkdir -p ${BUILD_STAGINGDIRECTORY}/docker\n# docker save azure/azure-cli:${IMAGE}-builder | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_${IMAGE}-builder.tar.gz &\n# docker save azure/azure-cli:${IMAGE} | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_${IMAGE}.tar.gz &\n# wait\n", "num_lines": 52}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Build assets related to Linux Distributions that use RPM/yum for installation specific for CBL-Mariner.\n\nset -exv\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set.}\"\n\n# IMAGE should be Mariner docker image url, such as mcr.microsoft.com/cbl-mariner/base/core:2.0\n: \"${IMAGE:?IMAGE environment variable not set.}\"\n\nCLI_VERSION=`cat src/azure-cli/azure/cli/__main__.py | grep __version__ | sed s/' '//g | sed s/'__version__='// |  sed s/\\\"//g`\n\n# Create a container image that includes the source code and a built RPM using this file.\ndocker build \\\n    --target build-env \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    -f ./scripts/release/rpm/mariner.dockerfile \\\n    -t azure/azure-cli:mariner-builder \\\n    .\n\n# Continue the previous build, and create a container that has the current azure-cli build but not the source code.\ndocker build \\\n    --build-arg cli_version=${CLI_VERSION} \\\n    --build-arg image=${IMAGE} \\\n    -f ./scripts/release/rpm/mariner.dockerfile \\\n    -t azure/azure-cli:mariner \\\n    .\n\n# Extract the built RPM so that it can be distributed independently.\n# The RPM file looks like azure-cli-2.32.0-1.x86_64.rpm\nid=$(docker create azure/azure-cli:mariner-builder bash)\n# https://docs.docker.com/engine/reference/commandline/cp/\n# Append /. so that the x86_64 folder's content is copied, instead of x86_64 folder itself.\ndocker cp $id:/out/. ${BUILD_STAGINGDIRECTORY}\n\n# Save these too a staging directory so that later build phases can choose to save them as Artifacts or publish them to\n# a registry.\n#\n# The products of `docker save` can be rehydrated using `docker load`.\n# mkdir -p ${BUILD_STAGINGDIRECTORY}/docker\n# docker save azure/azure-cli:mariner-builder | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_mariner-builder.tar.gz &\n# docker save azure/azure-cli:mariner | gzip > ${BUILD_STAGINGDIRECTORY}/docker/azure_azure-cli_mariner.tar.gz &\n# wait\n", "num_lines": 46}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a Mariner 2.0 docker container.\nset -exv\n\nexport USERNAME=azureuser\n\ntdnf --nogpgcheck install /mnt/rpm/$RPM_NAME -y\n\ntdnf install git gcc python3-devel python3-pip findutils ca-certificates -y\n\nln -s -f /usr/bin/python3 /usr/bin/python\ntime az self-test\ntime az --version\n\ncd /azure-cli/\npip install wheel\n./scripts/ci/build.sh\n\n# From Fedora36, when using `pip install --prefix` with root privileges, the package is installed into `{prefix}/local/lib`.\n# In order to keep the original installation path, I have to set RPM_BUILD_ROOT\n# Ref https://docs.fedoraproject.org/en-US/fedora/latest/release-notes/developers/Development_Python/#_pipsetup_py_installation_with_prefix\nexport RPM_BUILD_ROOT=/\n\npip install pytest --prefix /usr/lib64/az\npip install pytest-xdist --prefix /usr/lib64/az\npip install pytest-forked --prefix /usr/lib64/az\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed --no-deps\n\npython /azure-cli/scripts/release/rpm/test_rpm_package.py\n", "num_lines": 33}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a centos7 docker.\nset -exv\n\nexport USERNAME=azureuser\n\ndnf --nogpgcheck install /mnt/rpm/$RPM_NAME -y\n\ndnf install git gcc $PYTHON_PACKAGE-devel findutils -y\n\nln -s -f /usr/bin/$PYTHON_CMD /usr/bin/python\nln -s -f /usr/bin/$PIP_CMD /usr/bin/pip\ntime az self-test\ntime az --version\n\ncd /azure-cli/\npip install wheel\n./scripts/ci/build.sh\n\n# From Fedora36, when using `pip install --prefix` with root privileges, the package is installed into `{prefix}/local/lib`.\n# In order to keep the original installation path, I have to set RPM_BUILD_ROOT\n# Ref https://docs.fedoraproject.org/en-US/fedora/latest/release-notes/developers/Development_Python/#_pipsetup_py_installation_with_prefix\nexport RPM_BUILD_ROOT=/\n\npip install pytest --prefix /usr/lib64/az\npip install pytest-xdist --prefix /usr/lib64/az\npip install pytest-forked --prefix /usr/lib64/az\n\nfind /azure-cli/artifacts/build -name \"azure_cli_testsdk*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed\nfind /azure-cli/artifacts/build -name \"azure_cli_fulltest*\" | xargs pip install --prefix /usr/lib64/az --upgrade --ignore-installed --no-deps\n\npython /azure-cli/scripts/release/rpm/test_rpm_package.py\n", "num_lines": 34}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script should be run in a docker to verify installing rpm package from the yum repository.\n\nrpm --import https://packages.microsoft.com/keys/microsoft.asc\nsh -c 'echo -e \"[azure-cli]\nname=Azure CLI\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n\ncounter=4\n\nwhile [ $counter -gt 0 ]\ndo\n    yum install azure-cli -y\n    ACTUAL_VERSION=$(az version | sed -n 's|\"azure-cli\": \"\\(.*\\)\",|\\1|p' | sed 's|[[:space:]]||g')\n    echo \"actual version:${ACTUAL_VERSION}\"\n    echo \"expected version:${CLI_VERSION}\"\n\n    if [ \"$ACTUAL_VERSION\" != \"$CLI_VERSION\" ]; then\n        if [ ! -z \"$ACTUAL_VERSION\" ]; then\n            echo \"Latest package is not in the repo.\"\n            exit 1\n        fi\n        echo \"wait 5m\"\n        sleep 300\n        counter=$(( $counter - 1 ))\n    else\n        echo \"Latest package is verified.\"\n        exit 0\n    fi\ndone\necho \"Timeout!\"\nexit 1\n", "num_lines": 37}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "case $SHELL in\n*/zsh)\n   # Enable ZSH compatibility mode\n   autoload bashcompinit && bashcompinit\n   ;;\n*/bash)\n   ;;\n*)\nesac\n\neval \"$(register-python-argcomplete az)\"\n", "num_lines": 12}
{"repo_name": "azure-cli-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x\n\necho \"setting up\"\nWORKDIR=\"${1:-$(mktemp -d)}\"\necho \"setting up ${WORKDIR}\"\n\npushd \"$WORKDIR\"\n\napt update -y && apt install -y apt-transport-https curl gnupg make gcc < /dev/null\n\n# add diladele apt key\nwget -qO - https://packages.diladele.com/diladele_pub.asc | apt-key add -\n\n# add new repo\ntee /etc/apt/sources.list.d/squid413-ubuntu20.diladele.com.list <<EOF\ndeb https://squid413-ubuntu20.diladele.com/ubuntu/ focal main\nEOF\n\n# and install\napt-get update && apt-get install -y squid-common squid-openssl squidclient libecap3 libecap3-dev < /dev/null\n\nmkdir -p /var/lib/squid\n\n/usr/lib/squid/security_file_certgen -c -s /var/lib/squid/ssl_db -M 4MB || true\n\nchown -R proxy:proxy /var/lib/squid\n\n# Name of the VM on which Squid is hosted\nHOST=\"cli-proxy-vm\"\n\ntee squidc.pem > /dev/null <<EOF\n-----BEGIN CERTIFICATE-----\nMIIFGzCCAwOgAwIBAgIUOQoj8CLZdselr97rvIwx5OLDsuwwDQYJKoZIhvcNAQEL\nBQAwFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMB4XDTIyMDMwODE2NDQ0N1oXDTMy\nMDMwNTE2NDQ0N1owFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMIICIjANBgkqhkiG\n9w0BAQEFAAOCAg8AMIICCgKCAgEA/MPtV5BTPt6cqi4RdMlmr3yIsa2ujzchxv4h\njsC1DtnRgos5S41PH0ri+3tTSVX32yrwsY+rD1YRupm6lmE7GhU5I0Gi9ozkSF0Z\nKKaJi2oypU/FB+QPqzoCRsMEwGCbmKFVl8VuhyndXK4b4kblr9bl/euwd7M8Sbvz\nWUjneDrQsiIsrzPT4KAZLqctzDe4llPT7YKa33hiEPOfvWiZ+dqkaQA9P64xXSyn\nfHX8uVAJ3uBVJeGxD0pkNJ7jOryaUuHHucU8S9mIjnKjAB5aPjLH5xAs6lmb3122\ny+1tnEAmXM50D+UoEjfS6HOb5rdiqXGvc1KboKjzkPCRxx2a72cvegUj6mgAJLzg\nThE1llcmU4izgxoIMkVpGTVOLLn1VFKuNhMZCvFvKgnKoAv3G0FUnfWEaRRjSNmD\nLYaMDT5H9Zt2pDIUjUGStCl7gRzMEnYwJO3yiDpg43o5dRysUyL9JfE/Nh7Tg618\nn8cJ/W7+QYbYljurap8r7QFSrol3VChFB+Oor5ni+vohSAwJf0UlMpG3xWmy1UI4\nTFKfFGRRTzrP+7bNwX5hIvIy5VtgyaOqJwTxhi/JdxtOr2tA5rCW7+CtgSvzkqNE\nXyr7vkYgp6Y5LZgy4tUjK0K0OUgVdjBOhDpEzy/FF8w1FEVgJ0qY/rWcLkBHDT8R\nvJkhio8CAwEAAaNfMF0wFwYDVR0RBBAwDoIMY2xpLXByb3h5LXZtMBIGA1UdEwEB\n/wQIMAYBAf8CAQAwDwYDVR0PAQH/BAUDAwfngDAdBgNVHSUEFjAUBggrBgEFBQcD\nAgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggIBAAomjCyXvaQOxgYK50sXLB2+\nwAfdsx5nnGdgyfg4urW2Vm15DhGvI7C/ntq0dYy24N/UbG7UDXvlyLIJFq1XP7nf\npZG0VCjZ69bmxKm3Z8m0/AwMvi8e9edy8v9kNBCwLGkHbA8Yo9CIiQgelfpp1vUh\nbnNBhaD+iu6CfiCLwgJb/iw7eo/CyoZqx+tjXaO2zXvm4p/+QIfAOgtGQLFU8cfZ\n/gUrTq5gFq0+P9GyWsATJF6q7L6WZZj0OuTse7f4CSij6MnOMMxA+JoahJz7lsSi\nTJHIwEp5r/RyhpyepQxFYcUH5JJf9rahXLWZi+9TjxSM2YyhxfRPsiUEuGDok78Q\nm/QPiCi9JJb1ocmTjAV8xDShocivXOFyhn6Ln77vLjY+AavtWDhQthpuPxsLtVzm\ne0SH11dELRtb74mqXOrO7fu/+IBs3JqLE/U+xuxQtvG8vG1yDKHHSZqS2h/Ws4l4\nNiAshHgehQDPBcY9wYYzfBgZpOUMzdDf50x+FSlY43WOJJzSuQh4yZ0+3kyguCF8\nrnMLSceyS4ci4LmJ/KCSuGdf6XVYz8BE9gjjjpCP6qy0UlRefWs/ig/wcK+2bF1T\nn/Yv+6gXeCTHJ75qDIPlp7DRUUk0fbMj4bIkaogWWk4zf2u8mxZLa0lePKNKZN/m\nGCvFwr3ei+u/8czp5F7T\n-----END CERTIFICATE-----\nEOF\n\ntee squidk.pem > /dev/null <<EOF\n-----BEGIN PRIVATE KEY-----\nMIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQD8w+1XkFM+3pyq\nLhF0yWavfIixra6PNyHG/iGOwLUO2dGCizlLjU8fSuL7e1NJVffbKvCxj6sPVhG6\nmbqWYTsaFTkjQaL2jORIXRkopomLajKlT8UH5A+rOgJGwwTAYJuYoVWXxW6HKd1c\nrhviRuWv1uX967B3szxJu/NZSOd4OtCyIiyvM9PgoBkupy3MN7iWU9PtgprfeGIQ\n85+9aJn52qRpAD0/rjFdLKd8dfy5UAne4FUl4bEPSmQ0nuM6vJpS4ce5xTxL2YiO\ncqMAHlo+MsfnECzqWZvfXbbL7W2cQCZcznQP5SgSN9Loc5vmt2Kpca9zUpugqPOQ\n8JHHHZrvZy96BSPqaAAkvOBOETWWVyZTiLODGggyRWkZNU4sufVUUq42ExkK8W8q\nCcqgC/cbQVSd9YRpFGNI2YMthowNPkf1m3akMhSNQZK0KXuBHMwSdjAk7fKIOmDj\nejl1HKxTIv0l8T82HtODrXyfxwn9bv5BhtiWO6tqnyvtAVKuiXdUKEUH46ivmeL6\n+iFIDAl/RSUykbfFabLVQjhMUp8UZFFPOs/7ts3BfmEi8jLlW2DJo6onBPGGL8l3\nG06va0DmsJbv4K2BK/OSo0RfKvu+RiCnpjktmDLi1SMrQrQ5SBV2ME6EOkTPL8UX\nzDUURWAnSpj+tZwuQEcNPxG8mSGKjwIDAQABAoICADZwcFbSo8s/oNhaUbIoinAz\nTzGNabI4upKkO1AGmzhWm3QVTkLCbY8czuRA/IAn/tj6V5q2ia4k6G6bG3+180e7\n2HGKenHFiIk5W+jQbYFUXxIRqyr26JUFSmY5LHXOmNR3svqcMCD2WFHUwfarNF75\n1tEoiPpO5SYwT8okFI5lhHtJNvyJGhIgCSxuH0QDoELoTRWzcm28/MoP3pCpzbft\nakmfHpHvj3w02OHKe6Lh5S5WfKBLCppzeD+JFQGai1ZcgGq3WzQu5uVfNVIaN297\n+mf+qN3UbOjfwzYKrffgLSMB6CdgQJAj683a0HIRfzNlY9dfrFse6E6IMa2D59FI\ngdF51d5OOqW02NGoO9fhp6M6dGPNxIUcWpk8hjagQQr/C8ygMljMS0/uXbU904M2\nzyVNNpSndT4sY/Mxihlnl9+Un2672dhCS8TiR0JnQbqxviZprqP9IUnOdEST4OtW\n2xFTYF+bg3PEKcuScgPrix9GhQ77uZw+MwPeyzreXdUBL+9jRAjuPqIE1Cpj+6R6\nzWkme00AeWnuaBBS3AD0xMqst7tMqqgXcTmccEaqNM3Dk/+IUnDJ3AwNxpXBq7UL\nUYrjFiK5mXul6/vDeX2d276Cp5M2LR8Sh83PfDGZdKam5vASiMGAGXdJyJMFZt7S\nZvxXwBrQlysTT6qx0aVRAoIBAQD/IIuWX3ZSXv4lK0x4N1KqqKIwTJjhA8fVDE7Y\n+P0/jh5roRYMXqcEZxERsdd0BT6pYtCaXuf1dR7ynt0Pw5VtxgiOiQWz0Mge7Osh\n+AJULmYsQBOM1wBMMk0n+U6ZHl9rSNGgyXY7LWULT8NjzL74vJTk0RWpQD440Vbd\ni+FQMHvASBeQ+JI6G4XGEZs8vB9Ar7vl/3atLpq7xmoii+j6D5jHgjlMtVRD6Q9h\nBWn7xNSfpQ/teIntjd60ophvQqnVYwa2nN7Hlj0ak6MIIqDG5KiEqDGVA00GarOc\nU6EJDZVx6NeDYaOlt8K2tpzzqX+WXn4manRF09n8qFeM5tn3AoIBAQD9oVAyKpQv\nSzhW6cHBX+kSX623X3S/jLctf2J4otN66sByi2rJNXK7Y68Xu9up55PSuBtyQTzj\nxSnIF+u96PhWQsnyaXyN41pqjypeS5qGA/JqPfsAa23j5LepSZS6aLtDE+y+2HfV\nhPFHzs7/ldp7bLv3B7XzyLSE+2v5reyW52vW4ItaJxHsvukf/6gE3AMYSMaHXaId\ncyeTVxUUs1tIM1J9WBjYzYa+t2QLv20lQTzZL2tZYclX7WQrpMoGilAZT3mTYnPb\npWeudS3422Fy8wH4qp0yt1ouI+KUL6Ri1AFAvDSauWHlznH9SLG4S/0oy/tG+9mh\n6CJBsN8ZY+4pAoIBAQCROjt7W9gEx6IwElezTvq1vsykZdXYsMg+FIWFqSav2Pyk\nE8xzOiYksW7b/bpBhwLGdUN9vGyaIxN81MXNxW34UPRp/sHKPBzOzdqDOaRJuyfa\nJJd8Yp7+wNt+18HQE6QJdCgwOL4erZaJO9xjoRdMjDzNi9+iurkwqqmh75BQj2jC\nacdQdM74WNZri3YsuoGn1uFE6YjqyE64eRfNlosGXX6AgzaO3eGbzr08Y1KTSNYo\nElPgv+7z1QBjHvNa0j3PBFG7/cwrHPCngkcZyGxxC5SJ/xxKUNi1wGOBp3FRr/PU\nJdEYLqpzGQmz7HunkGLae+uffpW1cgTyd/lucbK9AoIBAQDBP/tJ7hVwn6Cy4HNo\nMvr0rABB2zKqjL45pXjTMEVwv5OY80+PNfFQhJixvcqWf8OrZ+pJuRl69wxp0Ign\n8G3f1A3pbaSgu911mdYPeQ2pFTLM7qLkY/acEPY7v7vZ+NjOOE1H8MoF38C0FQi1\nx2lsZ6IkjDSAJqodNTDFUlcVeAk79WVYcLKAr8oTPom4Aic9hp32IErYo5hA9LY0\nSqC/t5MfvFNaRedoQ3WwWdAA9d82IKJrvU1beJ69flcMerCjSGH7AaYDctk4HULE\n/esXWb9jyCP0s627wE3w2Qgo4R5/Q6fVSHEmV5GVCqGXKhcf0aSJJnZhne0UHn8u\n6mxZAoIBAQCB4PwvqtgRAj3bxIyoP65AN6j2n2wk2TpLYUYC8XbgcJXmXuvJBD6f\nywgEc9khMEv/Z3r0vCoP+dW0SyK/+9bjLJozq3BCNrdgRqYrg7cnEaPbesgOPWY9\nR5KgCN8gctivZ8G3zdembR4qFyeyecwZ+96JfyEsk0V1IpRrZZg7soZ4qsDRKZc1\ndkEB7pxAfOl17cOtcZSQHuj8VDtDmUyySzySBGRrF3qoGhWbQ59Wp48Gw9/JZ/th\nwmr7LEnQZNzo3IbLngzUlCiRtRgNl9hCw5vZwfS8yEsS0a72lmKY3qGyXr3xAAhf\n07oi7EDdo42CbbjAFVk2H40iMvVR5d4U\n-----END PRIVATE KEY-----\nEOF\n\nchown proxy:proxy squidc.pem\nchown proxy:proxy squidk.pem\nchmod 400 squidc.pem \nchmod 400 squidk.pem\ncp squidc.pem /etc/squid/squidc.pem\ncp squidk.pem /etc/squid/squidk.pem\ncp squidc.pem /usr/local/share/ca-certificates/squidc.crt\nupdate-ca-certificates \n\nsed -i 's~http_access deny all~http_access allow all~' /etc/squid/squid.conf\nsed -i \"s~http_port 3128~http_port $HOST:3128\\nhttps_port $HOST:3129 tls-cert=/etc/squid/squidc.pem tls-key=/etc/squid/squidk.pem~\" /etc/squid/squid.conf\n\nsystemctl restart squid\nsystemctl status squid\n\n# validation, fails VM creation if commands fail\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I https://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I https://www.google.com\n", "num_lines": 140}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "case $SHELL in\n*/zsh)\n   echo 'Enabling ZSH compatibility mode';\n   autoload bashcompinit && bashcompinit\n   ;;\n*/bash)\n   ;;\n*)\nesac\n\neval \"$(register-python-argcomplete azdev)\"\n", "num_lines": 12}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "[[ -e CLI ]] && rm -rf CLI\nazdev command-change meta-export CLI --meta-output-path ./CLI\nif [ $? -ne 0 ]; then\n\t\techo \"test cli meta generation failed, pass\"\nelse\n\t\techo \"test cli meta generation succeed\"\nfi", "num_lines": 7}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n: \"${BUILD_SOURCESDIRECTORY:=$(cd $(dirname $0); cd ../../; pwd)}\"\n\ncd \"${BUILD_SOURCESDIRECTORY}\"\n\necho \"Build azdev\"\npip install -U pip setuptools wheel\npython setup.py bdist_wheel -d \"${BUILD_STAGINGDIRECTORY}\"\npython setup.py sdist -d \"${BUILD_STAGINGDIRECTORY}\"\n", "num_lines": 14}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Extract the version of the CLI from azdev's __init__.py file.\n: \"${BUILD_STAGINGDIRECTORY:?BUILD_STAGINGDIRECTORY environment variable not set}\"\n\nver=`cat azdev/__init__.py | grep __VERSION__ | sed s/' '//g | sed s/'__VERSION__='// |  sed s/\\\"//g`\necho $ver > $BUILD_STAGINGDIRECTORY/version\necho $ver > $BUILD_STAGINGDIRECTORY/azdev-${ver}.txt", "num_lines": 8}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\necho \"Install azdev into virtual environment\"\npython -m venv env\n. env/bin/activate\npip install -U pip setuptools wheel -q\npip install $(find ${BUILD_ARTIFACTSTAGINGDIRECTORY}/pypi -name *.tar.gz) -q\ngit clone https://github.com/Azure/azure-cli.git\ngit clone https://github.com/Azure/azure-cli-extensions.git\nazdev setup -c -r azure-cli-extensions\n", "num_lines": 13}
{"repo_name": "azure-cli-dev-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -ev\n\npip install tox\npython -m tox\n", "num_lines": 7}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nchanged_content=$(git --no-pager diff --diff-filter=ACMRT HEAD~$AZURE_EXTENSION_COMMIT_NUM -- src/index.json)\nif [[ -z \"$changed_content\" ]]; then\n    echo \"index.json not modified. End task.\"\n    exit 0\nfi\n\npip install azure-cli-core azure-cli requests\npip install azure-storage-blob==1.5.0\necho \"Listing Available Extensions:\"\naz extension list-available -otable\n\n# turn off telemetry as it crowds output\nexport AZURE_CORE_COLLECT_TELEMETRY=False\n\n# use index.json in master branch\nexport AZURE_EXTENSION_INDEX_URL=https://raw.githubusercontent.com/Azure/azure-cli-extensions/master/src/index.json\n\noutput=$(az extension list-available --query [].name -otsv)\n# azure-cli-ml is replaced by ml\n# disable alias which relies on Jinja2 2.10\nblocklist=(\"azure-cli-ml\" \"alias\")\n\nrm -f ~/.azure/extCmdTreeToUpload.json\n\nfilter_exts=\"\"\nfor ext in $output; do\n    ext=${ext%$'\\r'}   # Remove a trailing newline when running on Windows.\n    if [[ \" ${blocklist[@]} \" =~ \" ${ext} \" ]]; then\n        continue\n    fi\n    filter_exts=\"${filter_exts} ${ext}\"\n    echo \"Adding extension:\" $ext\n    az extension add --upgrade -n $ext\n    if [ $? != 0 ]\n    then\n        echo \"Failed to load:\" $ext\n        exit 1\n    fi\ndone\n\npython $(cd $(dirname $0); pwd)/update_ext_cmd_tree.py $filter_exts\n", "num_lines": 44}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -ex\n\n# Install CLI\necho \"Installing azure-cli...\"\n\npip install --pre azure-cli --extra-index-url https://azurecliprod.blob.core.windows.net/edge -q\npip install sphinx==1.7.0 Jinja2==3.0.3\necho \"Installed.\"\n\npython ./scripts/ci/index_ref_doc.py -v\n\necho \"OK.\"\n", "num_lines": 14}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n[[ -z \"${TENANT_ID}\" ]] && (echo \"TENANT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_SUBSCRIPTION_ID}\" ]] && (echo \"AZCLI_ALT_SUBSCRIPTION_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_ID}\" ]] && (echo \"AZCLI_ALT_CLIENT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_SECRET}\" ]] && (echo \"AZCLI_ALT_CLIENT_SECRET is empty\"; exit 1)\n[[ -z \"${LOOKBACK}\" ]] && (echo \"LOOKBACK is empty\"; exit 1)\n[[ -z \"${PREFIX}\" ]] && (echo \"PREFIX is empty\"; exit 1)\n\n# login\naz login --service-principal -u \"${AZCLI_ALT_CLIENT_ID}\" -p \"${AZCLI_ALT_CLIENT_SECRET}\" -t \"${TENANT_ID}\"\naz account set -s \"${AZCLI_ALT_SUBSCRIPTION_ID}\"\naz account show\n\n# get lookback date\ncond_date=$(date -u -d \"${LOOKBACK} hours ago\" '+%Y-%m-%dT%H:%M:%SZ')\n\n# list matched result\naz group list --query \"[? @.tags.date < '${cond_date}'] | [? starts_with(@.name, '${PREFIX}')]\"\necho \"Length:\" $(az group list --query \"[? @.tags.date < '${cond_date}'] | [? starts_with(@.name, '${PREFIX}')] | length(@)\")\n\n# delete\naz group list --query \"[? @.tags.date < '${cond_date}'] | [? starts_with(@.name, '${PREFIX}')].name\" -o tsv | xargs -i az group delete --no-wait -y -n {}\n", "num_lines": 31}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n[[ -z \"${CLI_REPO}\" ]] && (echo \"CLI_REPO is empty\"; exit 1)\n[[ -z \"${CLI_BRANCH}\" ]] && (echo \"CLI_BRANCH is empty\"; exit 1)\n[[ -z \"${EXT_REPO}\" ]] && (echo \"EXT_REPO is empty\"; exit 1)\n[[ -z \"${EXT_BRANCH}\" ]] && (echo \"EXT_BRANCH is empty\"; exit 1)\n[[ -z \"${BUILD_REASON}\" ]] && (echo \"BUILD_REASON is empty\"; exit 1)\n[[ -z \"${LIVE_TEST_BASE_DIR}\" ]] && (echo \"LIVE_TEST_BASE_DIR is empty\"; exit 1)\n\n# clone azure-cli (default is the official repo)\ngit clone \"${CLI_REPO}\"\n\n# ckeckout to a specific azure-cli branch (default is the dev branch)\npushd azure-cli/\ngit branch -a\ngit checkout \"${CLI_BRANCH}\"\npopd\n\n# clone azure-cli-extensions when manually trigger the pipeline\nif [[ ${BUILD_REASON} == \"Manual\" ]]; then\n    echo \"Manually trigger the pipeline, delete the current 'azure-cli-extensions' directory!\"\n    rm -rf azure-cli-extensions/\n    git clone \"${EXT_REPO}\"\n    pushd azure-cli-extensions/\n    git branch -a\n    git checkout \"${EXT_BRANCH}\"\n    popd\nfi\n\n# check current branch & commit logs in azure-cli-extensions\npushd azure-cli-extensions/\ngit branch -a\ngit log -10\npopd\n\n# copy live test related files to the same level as the checkout directory ($(Agent.BuildDirectory)/s)\ncp -rT \"${LIVE_TEST_BASE_DIR}\" ./\nls -alh\n", "num_lines": 46}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n[[ -z \"${IMAGE_PREFIX}\" ]] && (echo \"IMAGE_PREFIX is empty\"; exit 1)\n[[ -z \"${IMAGE_NAME}\" ]] && (echo \"IMAGE_NAME is empty\"; exit 1)\n[[ -z \"${IMAGE_TAG}\" ]] && (echo \"IMAGE_TAG is empty\"; exit 1)\n\n# prepare docker image\necho \"Pulling test image from '${IMAGE_PREFIX}/${IMAGE_NAME}:${IMAGE_TAG}'...\"\ndocker pull \"${IMAGE_PREFIX}\"/\"${IMAGE_NAME}\":\"${IMAGE_TAG}\"\ndocker tag \"${IMAGE_PREFIX}\"/\"${IMAGE_NAME}\":\"${IMAGE_TAG}\" \"${IMAGE_NAME}\":\"${IMAGE_TAG}\"\n", "num_lines": 18}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# check var\n# specify the version of python3, e.g. 3.6\n[[ -z \"${PYTHON_VERSION}\" ]] && (echo \"PYTHON_VERSION is empty\"; exit 1)\n[[ -z \"${ACS_BASE_DIR}\" ]] && (echo \"ACS_BASE_DIR is empty\"; exit 1)\n\nsetupVenv(){\n    # delete existing venv\n    deactivate || true\n    rm -rf azEnv || true\n\n    # create new venv\n    python\"${PYTHON_VERSION}\" -m venv azEnv\n    source azEnv/bin/activate\n    python -m pip install -U pip\n}\n\n# need to be executed in a venv\ninstallBuildTools(){\n    pip install tox coverage\n    pip install -U build\n}\n\n# need to be executed in a venv\nsetupAZ(){\n    cli_repo=${1:-\".\"}\n    ext_repo=${2:-\"\"}\n\n    # install azdev, used later to install azcli and extension\n    # TODO: update to a new version with dependency version fixed\n    pip install azdev==0.1.36\n\n    # pre-install-az: check existing az\n    which az || az version || az extension list || true\n\n    # install-az: from cloned repos with azdev\n    if [[ -z ${ext_repo} ]]; then\n        azdev setup -c \"${cli_repo}\"\n    else\n        azdev setup -c \"${cli_repo}\" -r \"${ext_repo}\"\n    fi\n\n    # fix the issue that vcrpy>=4.3.0 is not compatible with urllib3\n    pip install vcrpy==4.2.1\n\n    # post-install-az: check installation result\n    which az && az version\n}\n\n# need to be executed in a venv\ninstallTestPackages(){\n    # install pytest plugins\n    pip install pytest-json-report==1.5.0 pytest-rerunfailures==11.0 pytest-cov==4.0.0 pytest-forked==1.6.0\n\n    # install coverage for measuring code coverage\n    pip install coverage\n}\n\n# need to be executed in a venv\ninstallAZAKSTOOLFromLocal(){\n    wheel_file=${1}\n    pip install \"${wheel_file}\"\n    pip show az-aks-tool\n}\n\n# need to be executed in a venv\ninstallAZAKSTOOL(){\n    wheel_file=\"az_aks_tool-latest-py3-none-any.whl\"\n    wheel_url=\"https://akspreview.blob.core.windows.net/azakstool/${wheel_file}\"\n    curl -sLO \"${wheel_url}\"\n    installAZAKSTOOLFromLocal \"${wheel_file}\"\n}\n\n# need to be executed in a venv with kusto related modules installed\nremoveKustoPTHFile(){\n    pushd azEnv/lib/python\"${PYTHON_VERSION}\"/site-packages\n    rm azure_kusto_data*nspkg.pth\n    rm azure_kusto_ingest*nspkg.pth\n    popd\n}\n\n# need to be executed in a venv after 'setupAZ'\nigniteAKSPreview(){\n    # use a fake command to force trigger the command index update of azure-cli, in order to load aks-preview commands\n    # otherwise, cold boot execution of azdev test / pytest would only use commands in the acs module\n    az aks fake-command --debug || true\n}\n\n# need to be executed in a venv\nremoveAKSPreview(){\n    # remove extension\n    echo \"Remove existing aks-preview extension (if any)\"\n    if az extension remove --name aks-preview || azdev extension remove aks-preview; then\n        deactivate\n        source azEnv/bin/activate\n    fi\n}\n\n# need to be executed in a venv after 'setupAZ'\nsetupAKSPreview(){\n    # remove extension\n    removeAKSPreview\n\n    # install latest extension\n    echo \"Install the latest aks-preview extension and re-activate the virtualenv\"\n    azdev extension add aks-preview\n    az extension list\n    azdev extension list | grep \"aks-preview\" -C 5\n    deactivate\n    source azEnv/bin/activate\n}\n\ncreateSSHKey(){\n    # create ssh-key in advance to avoid the race condition that is prone to occur when key creation is handled by\n    # azure-cli when performing test cases concurrently, this command will not overwrite the existing ssh-key\n    custom_ssh_dir=${1:-\"${ACS_BASE_DIR}/tests/latest/data/.ssh\"}\n    # remove dir if exists (clean up), otherwise create it\n    if [[ -d ${custom_ssh_dir} ]]; then\n        rm -rf ${custom_ssh_dir}\n    else\n        mkdir -p ${custom_ssh_dir}\n    fi\n    ssh-keygen -t rsa -b 2048 -C \"azcli_aks_live_test@example.com\" -f ${custom_ssh_dir}/id_rsa -N \"\" -q <<< n\n}\n\nsetup_option=${1:-\"\"}\nif [[ -n ${setup_option} ]]; then\n    # bash options\n    set -o errexit\n    set -o nounset\n    set -o pipefail\n    set -o xtrace\n\n    # create new venv if second arg is not \"n\"\n    new_venv=${2:-\"n\"}\n    if [[ ${new_venv} == \"y\" ]]; then\n        echo \"Create new venv!\"\n        setupVenv\n    else\n        source azEnv/bin/activate\n    fi\n\n    if [[ ${setup_option} == \"build\" ]]; then\n        echo \"Start to build az-aks-tool!\"\n        installBuildTools\n    elif [[ ${setup_option} == \"setup-tool\" ]]; then\n        echo \"Start to setup az-aks-tool!\"\n        local_setup=${3:-\"n\"}\n        if [[ ${local_setup} == \"y\" ]]; then\n            wheel_file=${4:-\"/az_aks_tool-latest-py3-none-any.whl\"}\n            installAZAKSTOOLFromLocal \"${wheel_file}\"\n        else\n            installAZAKSTOOL\n        fi\n        removeKustoPTHFile\n    elif [[ ${setup_option} == \"setup-az\" ]]; then\n        echo \"Start to setup azure-cli!\"\n        cli_repo=${3:-\"azure-cli/\"}\n        ext_repo=${4:-\"\"}\n        setupAZ \"${cli_repo}\" \"${ext_repo}\"\n        installTestPackages\n        createSSHKey\n    elif [[ ${setup_option} == \"setup-akspreview\" ]]; then\n        echo \"Start to setup aks-preview!\"\n        setupAKSPreview\n        igniteAKSPreview\n    else\n        echo \"Unsupported setup option '${setup_option}'!\"\n    fi\n    echo \"All Done!\"\nfi\n", "num_lines": 173}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n# take the first arg as container name\ncontainer_name=${1:-\"azcli-aks-live-test-container\"}\n[[ -z \"${MAPPED_AZCLI_ALT_CLIENT_SECRET}\" ]] && (echo \"MAPPED_AZCLI_ALT_CLIENT_SECRET is empty\"; exit 1)\n[[ -z \"${IMAGE_NAME}\" ]] && (echo \"IMAGE_NAME is empty\"; exit 1)\n[[ -z \"${IMAGE_TAG}\" ]] && (echo \"IMAGE_TAG is empty\"; exit 1)\n\n# transcribe environment variables into file 'env.list'\n./scripts/transcribe_env.sh\n\n# start container in backgroud with tty\n# mount current directory ($(Agent.BuildDirectory)/s) to /opt in container\n# set working directory as /opt in container\n# pass secrects as environment variables directly (instead of storing in env.list)\n# pass other environment variables with env.list\ndocker run -t -d -v \"$PWD\":/opt -w /opt \\\n-e AZCLI_ALT_CLIENT_SECRET=\"${MAPPED_AZCLI_ALT_CLIENT_SECRET}\" \\\n-e AZURE_CLI_TEST_DEV_SP_PASSWORD=\"${MAPPED_AZCLI_ALT_CLIENT_SECRET}\" \\\n--env-file ./env.list \\\n--name \"${container_name}\" \"${IMAGE_NAME}\":\"${IMAGE_TAG}\"\n\n# remove env.list\nrm ./env.list\n", "num_lines": 32}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n[[ -z \"${WIKI_LINK}\" ]] && (echo \"WIKI_LINK is empty\"; exit 1)\n[[ -z \"${TENANT_ID}\" ]] && (echo \"TENANT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_SUBSCRIPTION_ID}\" ]] && (echo \"AZCLI_ALT_SUBSCRIPTION_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_ID}\" ]] && (echo \"AZCLI_ALT_CLIENT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_SECRET}\" ]] && (echo \"AZCLI_ALT_CLIENT_SECRET is empty\"; exit 1)\n[[ -z \"${IGNORE_EXIT_CODE}\" ]] && (echo \"IGNORE_EXIT_CODE is empty\")\n[[ -z \"${TEST_MODE}\" ]] && (echo \"TEST_MODE is empty\"; exit 1)\n[[ -z \"${PARALLELISM}\" ]] && (echo \"PARALLELISM is empty\")\n[[ -z \"${RERUNS}\" ]] && (echo \"RERUNS is empty\")\n[[ -z \"${NON_BOXED}\" ]] && (echo \"NON_BOXED is empty\")\n[[ -z \"${LOG_LEVEL}\" ]] && (echo \"LOG_LEVEL is empty\")\n[[ -z \"${CAPTURE}\" ]] && (echo \"CAPTURE is empty\")\n[[ -z \"${NO_EXIT_FIRST}\" ]] && (echo \"NO_EXIT_FIRST is empty\")\n[[ -z \"${LAST_FAILED}\" ]] && (echo \"LAST_FAILED is empty\")\n[[ -z \"${CLI_TEST_MATRIX}\" ]] && (echo \"CLI_TEST_MATRIX is empty\")\n[[ -z \"${CLI_TEST_FILTER}\" ]] && (echo \"CLI_TEST_FILTER is empty\")\n[[ -z \"${CLI_TEST_COVERAGE}\" ]] && (echo \"CLI_TEST_COVERAGE is empty\")\n[[ -z \"${ENABLE_SELECTION}\" ]] && (echo \"ENABLE_SELECTION is empty\")\n[[ -z \"${SELECTION_MODE}\" ]] && (echo \"SELECTION_MODE is empty\")\n[[ -z \"${SELECTION_COUNT}\" ]] && (echo \"SELECTION_COUNT is empty\")\n[[ -z \"${UNFIX_RANDOM_SEED}\" ]] && (echo \"UNFIX_RANDOM_SEED is empty\")\n\n# activate virtualenv\nsource azEnv/bin/activate\n\n# remove aks-preview\nsource ./scripts/setup_venv.sh\nremoveAKSPreview\n\n# login before the recording test to avoid the newly added test case does not include a corresponding\n# recording file and fall back to live mode, otherwise it will prompt `az login`.\naz login --service-principal -u \"${AZCLI_ALT_CLIENT_ID}\" -p \"${AZCLI_ALT_CLIENT_SECRET}\" -t \"${TENANT_ID}\"\naz account set -s \"${AZCLI_ALT_SUBSCRIPTION_ID}\"\naz account show\n\n# prepare running options\n# pytest options\npytest_options=\"-c --report-path ./reports\"\n# parallel\nif [[ -n ${PARALLELISM} ]]; then\n    pytest_options+=\" -j ${PARALLELISM}\"\nelse\n    pytest_options+=\" -s\"\nfi\n# reruns\nif [[ -n ${RERUNS} ]]; then\n    pytest_options+=\" --reruns ${RERUNS}\"\nfi\n# non boxed\nif [[ -n ${NON_BOXED} ]]; then\n    pytest_options+=\" --non-boxed\"\nfi\n# log level\nif [[ -n ${LOG_LEVEL} ]]; then\n    pytest_options+=\" --log-level ${LOG_LEVEL}\"\nfi\n# capture\nif [[ -n ${CAPTURE} ]]; then\n    pytest_options+=\" --capture ${CAPTURE}\"\nfi\n# no exit first\nif [[ -n ${NO_EXIT_FIRST} ]]; then\n    pytest_options+=\" --no-exitfirst\"\nfi\n# last failed\nif [[ -n ${LAST_FAILED} ]]; then\n    pytest_options+=\" --last-failed\"\nfi\n\n# filter options\nfilter_options=\"\"\n# cli matrix\nif [[ -n ${CLI_TEST_MATRIX} ]]; then\n    filter_options+=\" -cm ./configs/${CLI_TEST_MATRIX}\"\nfi\n# cli extra filter\nif [[ -n ${CLI_TEST_FILTER} ]]; then\n    filter_options+=\" -cf ${CLI_TEST_FILTER}\"\nfi\n# cli extra coverage\nif [[ -n ${CLI_TEST_COVERAGE} ]]; then\n    filter_options+=\" -cc ${CLI_TEST_COVERAGE}\"\nfi\n\n# case selection\nselection_options=\"\"\n# enable selection\nif [[ -n ${ENABLE_SELECTION} ]]; then\n    selection_options+=\" --enable-selection\"\nfi\n# selection mode\nif [[ -n ${SELECTION_MODE} ]]; then\n    selection_options+=\" --selection-mode ${SELECTION_MODE}\"\nfi\n# selection count\nif [[ -n ${SELECTION_COUNT} ]]; then\n    selection_options+=\" --selection-count ${SELECTION_COUNT}\"\nfi\n# unfix random seed\nif [[ -n ${UNFIX_RANDOM_SEED} ]]; then\n    selection_options+=\" --unfix-random-seed\"\nfi\n\n# recording test\nif [[ ${TEST_MODE} == \"recording\" || ${TEST_MODE} == \"all\" ]]; then\n    echo \"Test in recording mode!\"\n    coverage_options=\" -cc test_aks_commands.AzureKubernetesServiceScenarioTest\"\n    recording_options=\"${pytest_options}${coverage_options}${selection_options}\"\n    recording_options+=\" --json-report-file=cli_recording_report.json\"\n    recording_options+=\" --xml-file=cli_recording_result.xml\"\n    echo \"Recording test options: ${recording_options}\"\n    test_result=0\n    azaks ${recording_options} || test_result=$?\n    if [[ ${test_result} -ne 0 ]]; then\n        echo \"Recording test failed!\"\n        echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n        if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n            exit ${test_result}\n        fi\n    else\n        echo -e \"Recording test passed!\\n\\n\"\n    fi\nfi\n\n# live test\nif [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n    echo \"Test in live mode!\"\n    live_options=\"${pytest_options}${filter_options}${selection_options}\"\n    live_options+=\" -l --json-report-file=cli_live_report.json\"\n    live_options+=\" --xml-file=cli_live_result.xml\"\n    echo \"Live test options: ${live_options}\"\n    test_result=0\n    azaks ${live_options} || test_result=$?\n    if [[ ${test_result} -ne 0 ]]; then\n        echo \"Live test failed!\"\n        echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n        if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n            exit ${test_result}\n        fi\n    else\n        echo -e \"Live test passed!\\n\\n\"\n    fi\nfi\n\n# live-replay test\nif [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n    echo \"Test in live-replay mode!\"\n    live_replay_options=\"${pytest_options}${filter_options}${selection_options}\"\n    live_replay_options+=\" --json-report-file=cli_live_replay_report.json\"\n    live_replay_options+=\" --xml-file=cli_live_replay_result.xml\"\n    echo \"Live-replay test options: ${live_replay_options}\"\n    test_result=0\n    azaks ${live_replay_options} || test_result=$?\n    if [[ ${test_result} -ne 0 ]]; then\n        echo \"Live-replay test failed!\"\n        echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n        if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n            exit ${test_result}\n        fi\n    else\n        echo -e \"Live-replay test passed!\\n\\n\"\n    fi\nfi\n", "num_lines": 173}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n[[ -z \"${WIKI_LINK}\" ]] && (echo \"WIKI_LINK is empty\"; exit 1)\n[[ -z \"${TENANT_ID}\" ]] && (echo \"TENANT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_SUBSCRIPTION_ID}\" ]] && (echo \"AZCLI_ALT_SUBSCRIPTION_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_ID}\" ]] && (echo \"AZCLI_ALT_CLIENT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_CLIENT_SECRET}\" ]] && (echo \"AZCLI_ALT_CLIENT_SECRET is empty\"; exit 1)\n[[ -z \"${IGNORE_EXIT_CODE}\" ]] && (echo \"IGNORE_EXIT_CODE is empty\")\n[[ -z \"${TEST_MODE}\" ]] && (echo \"TEST_MODE is empty\"; exit 1)\n[[ -z \"${PARALLELISM}\" ]] && (echo \"PARALLELISM is empty\")\n[[ -z \"${RERUNS}\" ]] && (echo \"RERUNS is empty\")\n[[ -z \"${NON_BOXED}\" ]] && (echo \"NON_BOXED is empty\")\n[[ -z \"${LOG_LEVEL}\" ]] && (echo \"LOG_LEVEL is empty\")\n[[ -z \"${CAPTURE}\" ]] && (echo \"CAPTURE is empty\")\n[[ -z \"${NO_EXIT_FIRST}\" ]] && (echo \"NO_EXIT_FIRST is empty\")\n[[ -z \"${LAST_FAILED}\" ]] && (echo \"LAST_FAILED is empty\")\n[[ -z \"${EXT_TEST_MATRIX}\" ]] && (echo \"EXT_TEST_MATRIX is empty\")\n[[ -z \"${EXT_TEST_FILTER}\" ]] && (echo \"EXT_TEST_FILTER is empty\")\n[[ -z \"${EXT_TEST_COVERAGE}\" ]] && (echo \"EXT_TEST_COVERAGE is empty\")\n[[ -z \"${BACKWARD_COMPATIBILITY_TEST}\" ]] && (echo \"BACKWARD_COMPATIBILITY_TEST is empty\")\n[[ -z \"${CLI_TEST_MATRIX}\" ]] && (echo \"CLI_TEST_MATRIX is empty\")\n[[ -z \"${CLI_TEST_FILTER}\" ]] && (echo \"CLI_TEST_FILTER is empty\")\n[[ -z \"${CLI_TEST_COVERAGE}\" ]] && (echo \"CLI_TEST_COVERAGE is empty\")\n[[ -z \"${ENABLE_SELECTION}\" ]] && (echo \"ENABLE_SELECTION is empty\")\n[[ -z \"${SELECTION_MODE}\" ]] && (echo \"SELECTION_MODE is empty\")\n[[ -z \"${SELECTION_COUNT}\" ]] && (echo \"SELECTION_COUNT is empty\")\n[[ -z \"${UNFIX_RANDOM_SEED}\" ]] && (echo \"UNFIX_RANDOM_SEED is empty\")\n\n# activate virtualenv\nsource azEnv/bin/activate\n\n# setup aks-preview\n./scripts/setup_venv.sh setup-akspreview\n\n# login before the recording test to avoid the newly added test case does not include a corresponding\n# recording file and fall back to live mode, otherwise it will prompt `az login`.\naz login --service-principal -u \"${AZCLI_ALT_CLIENT_ID}\" -p \"${AZCLI_ALT_CLIENT_SECRET}\" -t \"${TENANT_ID}\"\naz account set -s \"${AZCLI_ALT_SUBSCRIPTION_ID}\"\naz account show\n\nif [[ -z ${BACKWARD_COMPATIBILITY_TEST} || ${BACKWARD_COMPATIBILITY_TEST} != \"only\" ]]; then\n    # prepare running options\n    # pytest options\n    pytest_options=\"-e --report-path ./reports\"\n    # parallel\n    if [[ -n ${PARALLELISM} ]]; then\n        pytest_options+=\" -j ${PARALLELISM}\"\n    else\n        pytest_options+=\" -s\"\n    fi\n    # reruns\n    if [[ -n ${RERUNS} ]]; then\n        pytest_options+=\" --reruns ${RERUNS}\"\n    fi\n    # non boxed\n    if [[ -n ${NON_BOXED} ]]; then\n        pytest_options+=\" --non-boxed\"\n    fi\n    # log level\n    if [[ -n ${LOG_LEVEL} ]]; then\n        pytest_options+=\" --log-level ${LOG_LEVEL}\"\n    fi\n    # capture\n    if [[ -n ${CAPTURE} ]]; then\n        pytest_options+=\" --capture ${CAPTURE}\"\n    fi\n    # no exit first\n    if [[ -n ${NO_EXIT_FIRST} ]]; then\n        pytest_options+=\" --no-exitfirst\"\n    fi\n    # last failed\n    if [[ -n ${LAST_FAILED} ]]; then\n        pytest_options+=\" --last-failed\"\n    fi\n\n    # filter options\n    filter_options=\"\"\n    # ext matrix\n    if [[ -n ${EXT_TEST_MATRIX} ]]; then\n        filter_options+=\" -em ./configs/${EXT_TEST_MATRIX}\"\n    fi\n    # ext extra filter\n    if [[ -n ${EXT_TEST_FILTER} ]]; then\n        filter_options+=\" -ef ${EXT_TEST_FILTER}\"\n    fi\n    # ext extra coverage\n    if [[ -n ${EXT_TEST_COVERAGE} ]]; then\n        filter_options+=\" -ec ${EXT_TEST_COVERAGE}\"\n    fi\n\n    # case selection\n    selection_options=\"\"\n    # enable selection\n    if [[ -n ${ENABLE_SELECTION} ]]; then\n        selection_options+=\" --enable-selection\"\n    fi\n    # selection mode\n    if [[ -n ${SELECTION_MODE} ]]; then\n        selection_options+=\" --selection-mode ${SELECTION_MODE}\"\n    fi\n    # selection count\n    if [[ -n ${SELECTION_COUNT} ]]; then\n        selection_options+=\" --selection-count ${SELECTION_COUNT}\"\n    fi\n    # unfix random seed\n    if [[ -n ${UNFIX_RANDOM_SEED} ]]; then\n        selection_options+=\" --unfix-random-seed\"\n    fi\n\n    # recording test\n    if [[ ${TEST_MODE} == \"recording\" || ${TEST_MODE} == \"all\" ]]; then\n        echo \"Test in recording mode!\"\n        coverage_options=\" -ec test_aks_commands.AzureKubernetesServiceScenarioTest\"\n        recording_options=\"${pytest_options}${coverage_options}${selection_options}\"\n        recording_options+=\" --json-report-file=ext_recording_report.json\"\n        recording_options+=\" --xml-file=ext_recording_result.xml\"\n        echo \"Recording test options: ${recording_options}\"\n        test_result=0\n        azaks ${recording_options} || test_result=$?\n        if [[ ${test_result} -ne 0 ]]; then\n            echo \"Recording test failed!\"\n            echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n            if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n                exit ${test_result}\n            fi\n        else\n            echo -e \"Recording test passed!\\n\\n\"\n        fi\n    fi\n\n    # live test\n    if [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n        echo \"Test in live mode!\"\n        live_options=\"${pytest_options}${filter_options}${selection_options}\"\n        live_options+=\" -l --json-report-file=ext_live_report.json\"\n        live_options+=\" --xml-file=ext_live_result.xml\"\n        echo \"Live test options: ${live_options}\"\n        test_result=0\n        azaks ${live_options} || test_result=$?\n        if [[ ${test_result} -ne 0 ]]; then\n            echo \"Live test failed!\"\n            echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n            if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n                exit ${test_result}\n            fi\n        else\n            echo -e \"Live test passed!\\n\\n\"\n        fi\n    fi\n\n    # live-replay test\n    if [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n        echo \"Test in live-replay mode!\"\n        live_replay_options=\"${pytest_options}${filter_options}${selection_options}\"\n        live_replay_options+=\" --json-report-file=ext_live_replay_report.json\"\n        live_replay_options+=\" --xml-file=ext_live_replay_result.xml\"\n        echo \"Live-replay test options: ${live_replay_options}\"\n        test_result=0\n        azaks ${live_replay_options} || test_result=$?\n        if [[ ${test_result} -ne 0 ]]; then\n            echo \"Live-replay test failed!\"\n            echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n            if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n                exit ${test_result}\n            fi\n        else\n            echo -e \"Live-replay test passed!\\n\\n\"\n        fi\n    fi\nfi\n\nif [[ -n ${BACKWARD_COMPATIBILITY_TEST} ]]; then\n    # prepare running options\n    # pytest options\n    pytest_options=\"-c --report-path ./reports\"\n    # parallel\n    if [[ -n ${PARALLELISM} ]]; then\n        pytest_options+=\" -j ${PARALLELISM}\"\n    else\n        pytest_options+=\" -s\"\n    fi\n    # reruns\n    if [[ -n ${RERUNS} ]]; then\n        pytest_options+=\" --reruns ${RERUNS}\"\n    fi\n    # non boxed\n    if [[ -n ${NON_BOXED} ]]; then\n        pytest_options+=\" --non-boxed\"\n    fi\n    # log level\n    if [[ -n ${LOG_LEVEL} ]]; then\n        pytest_options+=\" --log-level ${LOG_LEVEL}\"\n    fi\n    # capture\n    if [[ -n ${CAPTURE} ]]; then\n        pytest_options+=\" --capture ${CAPTURE}\"\n    fi\n    # no exit first\n    if [[ -n ${NO_EXIT_FIRST} ]]; then\n        pytest_options+=\" --no-exitfirst\"\n    fi\n    # last failed\n    if [[ -n ${LAST_FAILED} ]]; then\n        pytest_options+=\" --last-failed\"\n    fi\n\n    # filter options\n    filter_options=\"\"\n    # cli matrix\n    if [[ -n ${CLI_TEST_MATRIX} ]]; then\n        filter_options+=\" -cm ./configs/${CLI_TEST_MATRIX}\"\n    fi\n    # cli extra filter\n    if [[ -n ${CLI_TEST_FILTER} ]]; then\n        filter_options+=\" -cf ${CLI_TEST_FILTER}\"\n    fi\n    # cli extra coverage\n    if [[ -n ${CLI_TEST_COVERAGE} ]]; then\n        filter_options+=\" -cc ${CLI_TEST_COVERAGE}\"\n    fi\n\n    # case selection\n    selection_options=\"\"\n    # enable selection\n    if [[ -n ${ENABLE_SELECTION} ]]; then\n        selection_options+=\" --enable-selection\"\n    fi\n    # selection mode\n    if [[ -n ${SELECTION_MODE} ]]; then\n        selection_options+=\" --selection-mode ${SELECTION_MODE}\"\n    fi\n    # selection count\n    if [[ -n ${SELECTION_COUNT} ]]; then\n        selection_options+=\" --selection-count ${SELECTION_COUNT}\"\n    fi\n    # unfix random seed\n    if [[ -n ${UNFIX_RANDOM_SEED} ]]; then\n        selection_options+=\" --unfix-random-seed\"\n    fi\n\n    # live test\n    if [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n        echo \"Backward Compatibility Test in live mode!\"\n        live_options=\"${pytest_options}${filter_options}${selection_options}\"\n        live_options+=\" -l --json-report-file=bc_live_report.json\"\n        live_options+=\" --xml-file=bc_live_result.xml\"\n        echo \"Live test options: ${live_options}\"\n        test_result=0\n        azaks ${live_options} || test_result=$?\n        if [[ ${test_result} -ne 0 ]]; then\n            echo \"Backward Compatibility Live test failed!\"\n            echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n            if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n                exit ${test_result}\n            fi\n        else\n            echo -e \"Backward Compatibility Live test passed!\\n\\n\"\n        fi\n    fi\n\n    # live-replay test\n    if [[ ${TEST_MODE} == \"live\" || ${TEST_MODE} == \"all\" ]]; then\n        echo \"Backward Compatibility Test in live-replay mode!\"\n        live_replay_options=\"${pytest_options}${filter_options}${selection_options}\"\n        live_replay_options+=\" --json-report-file=bc_live_replay_report.json\"\n        live_replay_options+=\" --xml-file=bc_live_replay_result.xml\"\n        echo \"Live-replay test options: ${live_replay_options}\"\n        test_result=0\n        azaks ${live_replay_options} || test_result=$?\n        if [[ ${test_result} -ne 0 ]]; then\n            echo \"Backward Compatibility Live-replay test failed!\"\n            echo \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\n            if [[ -z ${IGNORE_EXIT_CODE} ]]; then\n                exit ${test_result}\n            fi\n        else\n            echo -e \"Backward Compatibility Live-replay test passed!\\n\\n\"\n        fi\n    fi\nfi\n", "num_lines": 288}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n# take the first arg as test mode\nmode=${1:-\"cli\"}\n[[ -z \"${WIKI_LINK}\" ]] && (echo \"WIKI_LINK is empty\"; exit 1)\n[[ -z \"${ACS_BASE_DIR}\" ]] && (echo \"ACS_BASE_DIR is empty\"; exit 1)\n[[ -z \"${AKS_PREVIEW_BASE_DIR}\" ]] && (echo \"AKS_PREVIEW_BASE_DIR is empty\"; exit 1)\n[[ -z \"${IGNORE_EXIT_CODE}\" ]] && (echo \"IGNORE_EXIT_CODE is empty\")\n[[ -z \"${CLI_COVERAGE_CONFIG}\" ]] && (echo \"CLI_COVERAGE_CONFIG is empty\")\n[[ -z \"${EXT_COVERAGE_CONFIG}\" ]] && (echo \"EXT_COVERAGE_CONFIG is empty\")\n\n# activate virtualenv\nsource azEnv/bin/activate\n\n# config aks-preview\nsource ./scripts/setup_venv.sh\nremoveAKSPreview\nif [[ ${mode} == \"ext\" ]]; then\n    setupAKSPreview\n    igniteAKSPreview\nfi\n\n# check mode\nif [[ ${mode} == \"cli\" ]]; then\n    UT_BASE_DIR=${ACS_BASE_DIR}\nelif [[ ${mode} == \"ext\" ]]; then\n    UT_BASE_DIR=${AKS_PREVIEW_BASE_DIR}\nelse\n    echo \"Unsupported coverage mode, please choose \\\"cli\\\" or \\\"ext\\\"\"\n    exit 1\nfi\n\n# unit test & coverage report\npushd ${UT_BASE_DIR}\n\n# clean existing coverage report\n(coverage combine || true) && (coverage erase || true)\n\n# perform unit test with module 'unittest'\ntest_result=0\ncoverage run --source=. --omit=*/vendored_sdks/*,*/tests/* -m pytest tests/latest/ || test_result=$?\n\n# generate coverage report\ncoverage combine || true\ncoverage report -m\ncoverage json -o coverage.json\npopd\n\n# copy coverage report\nmkdir -p reports/ && cp ${UT_BASE_DIR}/coverage.json reports/\n\n# prepare running options\n# unit test result\noptions=\"--unit-test-result ${test_result} --coverage-report ${UT_BASE_DIR}/coverage.json\"\n# ignore exit code\nif [[ -n ${IGNORE_EXIT_CODE} ]]; then\n    options+=\" --ignore-exit-code\"\nfi\nif [[ ${mode} == \"cli\" && -n ${CLI_COVERAGE_CONFIG} ]]; then\n    options+=\" --coverage-config ./configs/${CLI_COVERAGE_CONFIG}\"\nfi\nif [[ ${mode} == \"ext\" && -n ${EXT_COVERAGE_CONFIG} ]]; then\n    options+=\" --coverage-config ./configs/${EXT_COVERAGE_CONFIG}\"\nfi\n\ncombined_result=0\nazaks-cov ${options} || combined_result=$?\necho \"Please refer to this wiki (${WIKI_LINK}) for troubleshooting guidelines.\"\nexit ${combined_result}\n", "num_lines": 77}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# bash options\nset -o errexit\nset -o nounset\nset -o pipefail\nset -o xtrace\n\n# check var\n# azure devops\n[[ -z \"${BUILD_REASON}\" ]] && (echo \"BUILD_REASON is empty\")\n[[ -z \"${SYSTEM_PULLREQUEST_TARGETBRANCH}\" ]] && (echo \"SYSTEM_PULLREQUEST_TARGETBRANCH is empty\")\n\n# client id, secret and tenant id of sp 'azcli-aks-live-test' (from variable group \"azcli-aks-tool\")\n[[ -z \"${AZCLI_ALT_CLIENT_ID}\" ]] && (echo \"AZCLI_ALT_CLIENT_ID is empty\"; exit 1)\n[[ -z \"${AZCLI_ALT_SUBSCRIPTION_ID}\" ]] && (echo \"AZCLI_ALT_SUBSCRIPTION_ID is empty\"; exit 1)\n[[ -z \"${TENANT_ID}\" ]] && (echo \"TENANT_ID is empty\"; exit 1)\n\n# basic ubuntu image with python3 pre-installed, hosted on some container registry (from variable group \"azcli-aks-tool\")\n[[ -z \"${IMAGE_PREFIX}\" ]] && (echo \"IMAGE_PREFIX is empty\"; exit 1)\n[[ -z \"${IMAGE_NAME}\" ]] && (echo \"IMAGE_NAME is empty\"; exit 1)\n[[ -z \"${IMAGE_TAG}\" ]] && (echo \"IMAGE_TAG is empty\"; exit 1)\n\n# specify the version of python3\n[[ -z \"${PYTHON_VERSION}\" ]] && (echo \"PYTHON_VERSION is empty\"; exit 1)\n\n# tsg/wiki link\n[[ -z \"${WIKI_LINK}\" ]] && (echo \"WIKI_LINK is empty\"; exit 1)\n\n# pytest options\n[[ -z \"${PARALLELISM}\" ]] && (echo \"PARALLELISM is empty\")\n[[ -z \"${RERUNS}\" ]] && (echo \"RERUNS is empty\")\n[[ -z \"${NON_BOXED}\" ]] && (echo \"NON_BOXED is empty\")\n[[ -z \"${LOG_LEVEL}\" ]] && (echo \"LOG_LEVEL is empty\")\n[[ -z \"${CAPTURE}\" ]] && (echo \"CAPTURE is empty\")\n[[ -z \"${NO_EXIT_FIRST}\" ]] && (echo \"NO_EXIT_FIRST is empty\")\n[[ -z \"${LAST_FAILED}\" ]] && (echo \"LAST_FAILED is empty\")\n\n# custom\n[[ -z \"${IGNORE_EXIT_CODE}\" ]] && (echo \"IGNORE_EXIT_CODE is empty\")\n[[ -z \"${TEST_LOCATION}\" ]] && (echo \"TEST_LOCATION is empty\"; exit 1)\n[[ -z \"${COVERAGE}\" ]] && (echo \"COVERAGE is empty\"; exit 1)\n[[ -z \"${TEST_MODE}\" ]] && (echo \"TEST_MODE is empty\"; exit 1)\n[[ -z \"${CLI_TEST_MATRIX}\" ]] && (echo \"CLI_TEST_MATRIX is empty\")\n[[ -z \"${CLI_TEST_FILTER}\" ]] && (echo \"CLI_TEST_FILTER is empty\")\n[[ -z \"${CLI_TEST_COVERAGE}\" ]] && (echo \"CLI_TEST_COVERAGE is empty\")\n[[ -z \"${EXT_TEST_MATRIX}\" ]] && (echo \"EXT_TEST_MATRIX is empty\")\n[[ -z \"${EXT_TEST_FILTER}\" ]] && (echo \"EXT_TEST_FILTER is empty\")\n[[ -z \"${EXT_TEST_COVERAGE}\" ]] && (echo \"EXT_TEST_COVERAGE is empty\")\n[[ -z \"${ENABLE_SELECTION}\" ]] && (echo \"ENABLE_SELECTION is empty\")\n[[ -z \"${SELECTION_MODE}\" ]] && (echo \"SELECTION_MODE is empty\")\n[[ -z \"${SELECTION_COUNT}\" ]] && (echo \"SELECTION_COUNT is empty\")\n[[ -z \"${UNFIX_RANDOM_SEED}\" ]] && (echo \"UNFIX_RANDOM_SEED is empty\")\n[[ -z \"${CLI_COVERAGE_CONFIG}\" ]] && (echo \"CLI_COVERAGE_CONFIG is empty\")\n[[ -z \"${EXT_COVERAGE_CONFIG}\" ]] && (echo \"EXT_COVERAGE_CONFIG is empty\")\n[[ -z \"${CLI_REPO}\" ]] && (echo \"CLI_REPO is empty\"; exit 1)\n[[ -z \"${CLI_BRANCH}\" ]] && (echo \"CLI_BRANCH is empty\"; exit 1)\n[[ -z \"${EXT_REPO}\" ]] && (echo \"EXT_REPO is empty\"; exit 1)\n[[ -z \"${EXT_BRANCH}\" ]] && (echo \"EXT_BRANCH is empty\"; exit 1)\n[[ -z \"${BACKWARD_COMPATIBILITY_TEST}\" ]] && (echo \"BACKWARD_COMPATIBILITY_TEST is empty\")\n\n# base directories for acs, aks-preview and live test\n[[ -z \"${ACS_BASE_DIR}\" ]] && (echo \"ACS_BASE_DIR is empty\"; exit 1)\n[[ -z \"${AKS_PREVIEW_BASE_DIR}\" ]] && (echo \"AKS_PREVIEW_BASE_DIR is empty\"; exit 1)\n[[ -z \"${LIVE_TEST_BASE_DIR}\" ]] && (echo \"LIVE_TEST_BASE_DIR is empty\"; exit 1)\n\n# clear\ncat /dev/null > env.list\n\n# azure devops\necho \"BUILD_REASON=${BUILD_REASON}\" >> env.list\necho \"SYSTEM_PULLREQUEST_TARGETBRANCH=${SYSTEM_PULLREQUEST_TARGETBRANCH}\" >> env.list\n\n# tenant, sub, client\necho \"TENANT_ID=${TENANT_ID}\" >> env.list\necho \"AZCLI_ALT_SUBSCRIPTION_ID=${AZCLI_ALT_SUBSCRIPTION_ID}\" >> env.list\necho \"AZCLI_ALT_CLIENT_ID=${AZCLI_ALT_CLIENT_ID}\" >> env.list\n\n# image\necho \"IMAGE_PREFIX=${IMAGE_PREFIX}\" >> env.list\necho \"IMAGE_NAME=${IMAGE_NAME}\" >> env.list\necho \"IMAGE_TAG=${IMAGE_TAG}\" >> env.list\n\n# python version\necho \"PYTHON_VERSION=${PYTHON_VERSION}\" >> env.list\n\n# tsg/wiki link\necho \"WIKI_LINK=${WIKI_LINK}\" >> env.list\n\n# pytest options\necho \"PARALLELISM=${PARALLELISM}\" >> env.list\necho \"RERUNS=${RERUNS}\" >> env.list\necho \"NON_BOXED=${NON_BOXED}\" >> env.list\necho \"LOG_LEVEL=${LOG_LEVEL}\" >> env.list\necho \"CAPTURE=${CAPTURE}\" >> env.list\necho \"NO_EXIT_FIRST=${NO_EXIT_FIRST}\" >> env.list\necho \"LAST_FAILED=${LAST_FAILED}\" >> env.list\n\n# custom - azdev env\necho \"AZURE_CLI_TEST_DEV_SP_NAME=${AZCLI_ALT_CLIENT_ID}\" >> env.list\necho \"AZURE_CLI_TEST_DEV_RESOURCE_GROUP_LOCATION=${TEST_LOCATION}\" >> env.list\n\n# custom - az-aks-tool\necho \"IGNORE_EXIT_CODE=${IGNORE_EXIT_CODE}\" >> env.list\n# live test\necho \"COVERAGE=${COVERAGE}\" >> env.list\necho \"TEST_MODE=${TEST_MODE}\" >> env.list\necho \"CLI_TEST_MATRIX=${CLI_TEST_MATRIX}\" >> env.list\necho \"CLI_TEST_FILTER=${CLI_TEST_FILTER}\" >> env.list\necho \"CLI_TEST_COVERAGE=${CLI_TEST_COVERAGE}\" >> env.list\necho \"EXT_TEST_MATRIX=${EXT_TEST_MATRIX}\" >> env.list\necho \"EXT_TEST_FILTER=${EXT_TEST_FILTER}\" >> env.list\necho \"EXT_TEST_COVERAGE=${EXT_TEST_COVERAGE}\" >> env.list\necho \"ENABLE_SELECTION=${ENABLE_SELECTION}\" >> env.list\necho \"SELECTION_MODE=${SELECTION_MODE}\" >> env.list\necho \"SELECTION_COUNT=${SELECTION_COUNT}\" >> env.list\necho \"UNFIX_RANDOM_SEED=${UNFIX_RANDOM_SEED}\" >> env.list\n# unit test\necho \"CLI_COVERAGE_CONFIG=${CLI_COVERAGE_CONFIG}\" >> env.list\necho \"EXT_COVERAGE_CONFIG=${EXT_COVERAGE_CONFIG}\" >> env.list\n\n# custom - repo\necho \"CLI_REPO=${CLI_REPO}\" >> env.list\necho \"CLI_BRANCH=${CLI_BRANCH}\" >> env.list\necho \"EXT_REPO=${EXT_REPO}\" >> env.list\necho \"EXT_BRANCH=${EXT_BRANCH}\" >> env.list\n\n# custom - backward compatibility\necho \"BACKWARD_COMPATIBILITY_TEST=${BACKWARD_COMPATIBILITY_TEST}\" >> env.list\n\n# base directories\necho \"ACS_BASE_DIR=${ACS_BASE_DIR}\" >> env.list\necho \"AKS_PREVIEW_BASE_DIR=${AKS_PREVIEW_BASE_DIR}\" >> env.list\necho \"LIVE_TEST_BASE_DIR=${LIVE_TEST_BASE_DIR}\" >> env.list\n", "num_lines": 135}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -x\n\necho \"setting up\"\nWORKDIR=\"${1:-$(mktemp -d)}\"\necho \"setting up ${WORKDIR}\"\n\npushd \"$WORKDIR\"\n\napt update -y && apt install -y apt-transport-https curl gnupg make gcc < /dev/null\n\n# add diladele apt key\nwget -qO - https://packages.diladele.com/diladele_pub.asc | apt-key add -\n\n# add new repo\ntee /etc/apt/sources.list.d/squid413-ubuntu20.diladele.com.list <<EOF\ndeb https://squid413-ubuntu20.diladele.com/ubuntu/ focal main\nEOF\n\n# and install\napt-get update && apt-get install -y squid-common squid-openssl squidclient libecap3 libecap3-dev < /dev/null\n\nmkdir -p /var/lib/squid\n\n/usr/lib/squid/security_file_certgen -c -s /var/lib/squid/ssl_db -M 4MB || true\n\nchown -R proxy:proxy /var/lib/squid\n\n# Name of the VM on which Squid is hosted\nHOST=\"cli-proxy-vm\"\n\ntee squidc.pem > /dev/null <<EOF\n-----BEGIN CERTIFICATE-----\nMIIFGzCCAwOgAwIBAgIUOQoj8CLZdselr97rvIwx5OLDsuwwDQYJKoZIhvcNAQEL\nBQAwFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMB4XDTIyMDMwODE2NDQ0N1oXDTMy\nMDMwNTE2NDQ0N1owFzEVMBMGA1UEAwwMY2xpLXByb3h5LXZtMIICIjANBgkqhkiG\n9w0BAQEFAAOCAg8AMIICCgKCAgEA/MPtV5BTPt6cqi4RdMlmr3yIsa2ujzchxv4h\njsC1DtnRgos5S41PH0ri+3tTSVX32yrwsY+rD1YRupm6lmE7GhU5I0Gi9ozkSF0Z\nKKaJi2oypU/FB+QPqzoCRsMEwGCbmKFVl8VuhyndXK4b4kblr9bl/euwd7M8Sbvz\nWUjneDrQsiIsrzPT4KAZLqctzDe4llPT7YKa33hiEPOfvWiZ+dqkaQA9P64xXSyn\nfHX8uVAJ3uBVJeGxD0pkNJ7jOryaUuHHucU8S9mIjnKjAB5aPjLH5xAs6lmb3122\ny+1tnEAmXM50D+UoEjfS6HOb5rdiqXGvc1KboKjzkPCRxx2a72cvegUj6mgAJLzg\nThE1llcmU4izgxoIMkVpGTVOLLn1VFKuNhMZCvFvKgnKoAv3G0FUnfWEaRRjSNmD\nLYaMDT5H9Zt2pDIUjUGStCl7gRzMEnYwJO3yiDpg43o5dRysUyL9JfE/Nh7Tg618\nn8cJ/W7+QYbYljurap8r7QFSrol3VChFB+Oor5ni+vohSAwJf0UlMpG3xWmy1UI4\nTFKfFGRRTzrP+7bNwX5hIvIy5VtgyaOqJwTxhi/JdxtOr2tA5rCW7+CtgSvzkqNE\nXyr7vkYgp6Y5LZgy4tUjK0K0OUgVdjBOhDpEzy/FF8w1FEVgJ0qY/rWcLkBHDT8R\nvJkhio8CAwEAAaNfMF0wFwYDVR0RBBAwDoIMY2xpLXByb3h5LXZtMBIGA1UdEwEB\n/wQIMAYBAf8CAQAwDwYDVR0PAQH/BAUDAwfngDAdBgNVHSUEFjAUBggrBgEFBQcD\nAgYIKwYBBQUHAwEwDQYJKoZIhvcNAQELBQADggIBAAomjCyXvaQOxgYK50sXLB2+\nwAfdsx5nnGdgyfg4urW2Vm15DhGvI7C/ntq0dYy24N/UbG7UDXvlyLIJFq1XP7nf\npZG0VCjZ69bmxKm3Z8m0/AwMvi8e9edy8v9kNBCwLGkHbA8Yo9CIiQgelfpp1vUh\nbnNBhaD+iu6CfiCLwgJb/iw7eo/CyoZqx+tjXaO2zXvm4p/+QIfAOgtGQLFU8cfZ\n/gUrTq5gFq0+P9GyWsATJF6q7L6WZZj0OuTse7f4CSij6MnOMMxA+JoahJz7lsSi\nTJHIwEp5r/RyhpyepQxFYcUH5JJf9rahXLWZi+9TjxSM2YyhxfRPsiUEuGDok78Q\nm/QPiCi9JJb1ocmTjAV8xDShocivXOFyhn6Ln77vLjY+AavtWDhQthpuPxsLtVzm\ne0SH11dELRtb74mqXOrO7fu/+IBs3JqLE/U+xuxQtvG8vG1yDKHHSZqS2h/Ws4l4\nNiAshHgehQDPBcY9wYYzfBgZpOUMzdDf50x+FSlY43WOJJzSuQh4yZ0+3kyguCF8\nrnMLSceyS4ci4LmJ/KCSuGdf6XVYz8BE9gjjjpCP6qy0UlRefWs/ig/wcK+2bF1T\nn/Yv+6gXeCTHJ75qDIPlp7DRUUk0fbMj4bIkaogWWk4zf2u8mxZLa0lePKNKZN/m\nGCvFwr3ei+u/8czp5F7T\n-----END CERTIFICATE-----\nEOF\n\ntee squidk.pem > /dev/null <<EOF\n-----BEGIN PRIVATE KEY-----\nMIIJRAIBADANBgkqhkiG9w0BAQEFAASCCS4wggkqAgEAAoICAQD8w+1XkFM+3pyq\nLhF0yWavfIixra6PNyHG/iGOwLUO2dGCizlLjU8fSuL7e1NJVffbKvCxj6sPVhG6\nmbqWYTsaFTkjQaL2jORIXRkopomLajKlT8UH5A+rOgJGwwTAYJuYoVWXxW6HKd1c\nrhviRuWv1uX967B3szxJu/NZSOd4OtCyIiyvM9PgoBkupy3MN7iWU9PtgprfeGIQ\n85+9aJn52qRpAD0/rjFdLKd8dfy5UAne4FUl4bEPSmQ0nuM6vJpS4ce5xTxL2YiO\ncqMAHlo+MsfnECzqWZvfXbbL7W2cQCZcznQP5SgSN9Loc5vmt2Kpca9zUpugqPOQ\n8JHHHZrvZy96BSPqaAAkvOBOETWWVyZTiLODGggyRWkZNU4sufVUUq42ExkK8W8q\nCcqgC/cbQVSd9YRpFGNI2YMthowNPkf1m3akMhSNQZK0KXuBHMwSdjAk7fKIOmDj\nejl1HKxTIv0l8T82HtODrXyfxwn9bv5BhtiWO6tqnyvtAVKuiXdUKEUH46ivmeL6\n+iFIDAl/RSUykbfFabLVQjhMUp8UZFFPOs/7ts3BfmEi8jLlW2DJo6onBPGGL8l3\nG06va0DmsJbv4K2BK/OSo0RfKvu+RiCnpjktmDLi1SMrQrQ5SBV2ME6EOkTPL8UX\nzDUURWAnSpj+tZwuQEcNPxG8mSGKjwIDAQABAoICADZwcFbSo8s/oNhaUbIoinAz\nTzGNabI4upKkO1AGmzhWm3QVTkLCbY8czuRA/IAn/tj6V5q2ia4k6G6bG3+180e7\n2HGKenHFiIk5W+jQbYFUXxIRqyr26JUFSmY5LHXOmNR3svqcMCD2WFHUwfarNF75\n1tEoiPpO5SYwT8okFI5lhHtJNvyJGhIgCSxuH0QDoELoTRWzcm28/MoP3pCpzbft\nakmfHpHvj3w02OHKe6Lh5S5WfKBLCppzeD+JFQGai1ZcgGq3WzQu5uVfNVIaN297\n+mf+qN3UbOjfwzYKrffgLSMB6CdgQJAj683a0HIRfzNlY9dfrFse6E6IMa2D59FI\ngdF51d5OOqW02NGoO9fhp6M6dGPNxIUcWpk8hjagQQr/C8ygMljMS0/uXbU904M2\nzyVNNpSndT4sY/Mxihlnl9+Un2672dhCS8TiR0JnQbqxviZprqP9IUnOdEST4OtW\n2xFTYF+bg3PEKcuScgPrix9GhQ77uZw+MwPeyzreXdUBL+9jRAjuPqIE1Cpj+6R6\nzWkme00AeWnuaBBS3AD0xMqst7tMqqgXcTmccEaqNM3Dk/+IUnDJ3AwNxpXBq7UL\nUYrjFiK5mXul6/vDeX2d276Cp5M2LR8Sh83PfDGZdKam5vASiMGAGXdJyJMFZt7S\nZvxXwBrQlysTT6qx0aVRAoIBAQD/IIuWX3ZSXv4lK0x4N1KqqKIwTJjhA8fVDE7Y\n+P0/jh5roRYMXqcEZxERsdd0BT6pYtCaXuf1dR7ynt0Pw5VtxgiOiQWz0Mge7Osh\n+AJULmYsQBOM1wBMMk0n+U6ZHl9rSNGgyXY7LWULT8NjzL74vJTk0RWpQD440Vbd\ni+FQMHvASBeQ+JI6G4XGEZs8vB9Ar7vl/3atLpq7xmoii+j6D5jHgjlMtVRD6Q9h\nBWn7xNSfpQ/teIntjd60ophvQqnVYwa2nN7Hlj0ak6MIIqDG5KiEqDGVA00GarOc\nU6EJDZVx6NeDYaOlt8K2tpzzqX+WXn4manRF09n8qFeM5tn3AoIBAQD9oVAyKpQv\nSzhW6cHBX+kSX623X3S/jLctf2J4otN66sByi2rJNXK7Y68Xu9up55PSuBtyQTzj\nxSnIF+u96PhWQsnyaXyN41pqjypeS5qGA/JqPfsAa23j5LepSZS6aLtDE+y+2HfV\nhPFHzs7/ldp7bLv3B7XzyLSE+2v5reyW52vW4ItaJxHsvukf/6gE3AMYSMaHXaId\ncyeTVxUUs1tIM1J9WBjYzYa+t2QLv20lQTzZL2tZYclX7WQrpMoGilAZT3mTYnPb\npWeudS3422Fy8wH4qp0yt1ouI+KUL6Ri1AFAvDSauWHlznH9SLG4S/0oy/tG+9mh\n6CJBsN8ZY+4pAoIBAQCROjt7W9gEx6IwElezTvq1vsykZdXYsMg+FIWFqSav2Pyk\nE8xzOiYksW7b/bpBhwLGdUN9vGyaIxN81MXNxW34UPRp/sHKPBzOzdqDOaRJuyfa\nJJd8Yp7+wNt+18HQE6QJdCgwOL4erZaJO9xjoRdMjDzNi9+iurkwqqmh75BQj2jC\nacdQdM74WNZri3YsuoGn1uFE6YjqyE64eRfNlosGXX6AgzaO3eGbzr08Y1KTSNYo\nElPgv+7z1QBjHvNa0j3PBFG7/cwrHPCngkcZyGxxC5SJ/xxKUNi1wGOBp3FRr/PU\nJdEYLqpzGQmz7HunkGLae+uffpW1cgTyd/lucbK9AoIBAQDBP/tJ7hVwn6Cy4HNo\nMvr0rABB2zKqjL45pXjTMEVwv5OY80+PNfFQhJixvcqWf8OrZ+pJuRl69wxp0Ign\n8G3f1A3pbaSgu911mdYPeQ2pFTLM7qLkY/acEPY7v7vZ+NjOOE1H8MoF38C0FQi1\nx2lsZ6IkjDSAJqodNTDFUlcVeAk79WVYcLKAr8oTPom4Aic9hp32IErYo5hA9LY0\nSqC/t5MfvFNaRedoQ3WwWdAA9d82IKJrvU1beJ69flcMerCjSGH7AaYDctk4HULE\n/esXWb9jyCP0s627wE3w2Qgo4R5/Q6fVSHEmV5GVCqGXKhcf0aSJJnZhne0UHn8u\n6mxZAoIBAQCB4PwvqtgRAj3bxIyoP65AN6j2n2wk2TpLYUYC8XbgcJXmXuvJBD6f\nywgEc9khMEv/Z3r0vCoP+dW0SyK/+9bjLJozq3BCNrdgRqYrg7cnEaPbesgOPWY9\nR5KgCN8gctivZ8G3zdembR4qFyeyecwZ+96JfyEsk0V1IpRrZZg7soZ4qsDRKZc1\ndkEB7pxAfOl17cOtcZSQHuj8VDtDmUyySzySBGRrF3qoGhWbQ59Wp48Gw9/JZ/th\nwmr7LEnQZNzo3IbLngzUlCiRtRgNl9hCw5vZwfS8yEsS0a72lmKY3qGyXr3xAAhf\n07oi7EDdo42CbbjAFVk2H40iMvVR5d4U\n-----END PRIVATE KEY-----\nEOF\n\nchown proxy:proxy squidc.pem\nchown proxy:proxy squidk.pem\nchmod 400 squidc.pem \nchmod 400 squidk.pem\ncp squidc.pem /etc/squid/squidc.pem\ncp squidk.pem /etc/squid/squidk.pem\ncp squidc.pem /usr/local/share/ca-certificates/squidc.crt\nupdate-ca-certificates \n\nsed -i 's~http_access deny all~http_access allow all~' /etc/squid/squid.conf\nsed -i \"s~http_port 3128~http_port $HOST:3128\\nhttps_port $HOST:3129 tls-cert=/etc/squid/squidc.pem tls-key=/etc/squid/squidk.pem~\" /etc/squid/squid.conf\n\nsystemctl restart squid\nsystemctl status squid\n\n# validation, fails VM creation if commands fail\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x http://${HOST}:3128/ -I https://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I http://www.google.com\ncurl -fsSl -o /dev/null -w '%{http_code}\\n' -x https://${HOST}:3129/ -I https://www.google.com\n", "num_lines": 140}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\nif [ -z \"$AzureWebJobsScriptRoot\" ]; then\n    cd /home/site/wwwroot\nelse\n    cd \"$AzureWebJobsScriptRoot\"\nfi\n\necho '{'\necho '\"hostJson\":'\nif [ -f \"host.json\" ]; then\n    cat host.json\nelse\n    echo '{ }'\nfi\n\necho ','\n\necho '\"functionsJson\": {'\n\nfor d in */; do\n    d=$(echo $d | tr -d '/')\n    if [ -f \"${d}/function.json\" ]; then\n        echo \"\\\"${d}\\\": \"\n        cat \"${d}/function.json\"\n        echo ','\n    fi\ndone\necho '}'\necho '}'", "num_lines": 29}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsetlog () {\n\texport logpath=/var/log/vmrepair\n\texport logfile=vmrepair.log\n\tmkdir -p ${logpath}\n\techo \"`date` Initiating vmrepair mount script\" >> ${logpath}/${logfile}\n}\n\ntrapper () {\n\ttrap 'catch $? $LINENO' ERR\n\tcatch () {\n\t\techo \"`date` Trapped error code $1 on line $2\" >> ${logpath}/${logfile}\n\t}\n}\n\nduplication_validation () {\n\ttrapper\n\t#/boot/efi duplication validation\n\techo \"`date` Validating boot/efi\" >> ${logpath}/${logfile}\n\tefi_cnt=`lsblk | grep -i \"/boot/efi\" | wc -l`\n\tif [ \"${efi_cnt}\" -eq 2 ]\n\tthen\n\t\t        umount /boot/efi >> ${logpath}/${logfile}\n\t\tfi\n}\n\nlocatebekvol () {\n\ttrapper\n\techo \"`date` Locating BEK volume\" >> ${logpath}/${logfile}\n\texport bekdisk=`lsblk -l -o LABEL,NAME| grep BEK | awk '{print $NF}'`\n\tif [ -z ${bekdisk} ]\n\tthen\n\t\techo \"`date` No BEK disk found, cannot continue\" >> ${logpath}/${logfile}\n\t\texit\n\telse\n\t\techo \"`date` the BEK Volume is ${bekdisk}\" >> ${logpath}/${logfile}\n\t\texport bekdisk=/dev/${bekdisk}\n\tfi\n}\n\nmountbekvol () {\n\ttrapper\n\techo \"`date` Mounting BEK volume\" >> ${logpath}/${logfile}\n\texport bekmountpath=/mnt/azure_bek_disk/\n\tmkdir -p ${bekmountpath}\n\tmount ${bekdisk} ${bekmountpath}\n\techo \"`date` BEK Volume ${bekdisk} mounted on ${bekmountpath}\"  >> ${logpath}/${logfile}\n}\n\nget_data_disk () {\n\ttrapper\n\techo \"`date` Getting data disk\" >> ${logpath}/${logfile} 2>&1\n\texport data_disk=`ls -la /dev/disk/azure/scsi1/lun0 | awk -F/ '{print \"/dev/\"$NF}'`\n\tif [ -z ${data_disk} ]\n\tthen\n\t\techo \"`date` OS disk attached as data disk was not found, cannot continue\" >> ${logpath}/${logfile}\n\t\texit\n\telse\n\t\techo \"`date` The data disk is ${data_disk}\" >> ${logpath}/${logfile}\n\tfi\n}\n\ncreate_mountpoints () {\n\ttrapper\n\techo \"`date` Creating mountpoints\" >> ${logpath}/${logfile}\n\tmkdir /{investigateboot,investigateroot}\n}\n\nrename_local_lvm () {\n\ttrapper\n\techo \"`date` Renaming Local VG\" >> ${logpath}/${logfile}\n\tvgrename -y ${local_vg_list} rescuevg\n}\n\ncheck_local_lvm () {\n\ttrapper\necho \"`date` Checking Local LVM\" >> ${logpath}/${logfile}\nexport local_vg_list=`vgs --noheadings -o vg_name| tr -d '   '` >> ${logpath}/${logfile}\nlocal_vg_number=`vgs --noheadings -o vg_name | wc -l` >> ${logpath}/${logfile}\nif [ ${local_vg_number} -eq 1 ]\n        then\n                echo \"`date` 1 VG found, renaming it\" >> ${logpath}/${logfile}\n                rename_local_lvm\n        else\n                echo \"`date` VGs found different than 1, we found ${local_vg_number}\" >> ${logpath}/${logfile}\nfi\n}\n\ndata_os_lvm_check () {\n\ttrapper\n\techo \"`date` Looking for LVM on the data disk\" >> ${logpath}/${logfile}\n\texport lvm_part=`fdisk -l ${data_disk} 2>&1 | grep -i lvm | awk '{print $1}'` >> ${logpath}/${logfile}\n\techo ${lvm_part} >> ${logpath}/${logfile}\n\tif [ -z ${lvm_part} ]\n\tthen\n\t\t#Updaing the below command to use lsblk instead of fdisk for accounting for different distros\n\t\t#export root_part=`fdisk -l ${data_disk} 2>&1 | grep ^/ |awk '$4 > 60000000{print $1}'` >> ${logpath}/${logfile}\n\t\texport root_part=`lsblk ${data_disk} -l -n -p -b 2>&1 | grep -w -v ${data_disk} |awk '$4 > 600000000{print $1}'` >> ${logpath}/${logfile}\n\t\techo \"`date` LVM not found on the data disk\" >> ${logpath}/${logfile}\n\t\techo \"`date` The OS partition on the data drive is ${root_part}\" >> ${logpath}/${logfile}\n\telse\n\t\t#adding a check to see if the returned value is just the partition number or partition full path.\n\t\tif grep -q ${data_disk} <<< ${lvm_part}\n\t\tthen\n\t\t\texport root_part=${lvm_part} >> ${logpath}/${logfile}\n\t\telse\n\t\t\texport root_part=${data_disk}${lvm_part} >> ${logpath}/${logfile}\n\t\tfi\n\t\techo \"`date` LVM found on the data disk\" >> ${logpath}/${logfile}\n\t\techo \"`date` The OS partition on the data drive is ${root_part}\" >> ${logpath}/${logfile}\n\tfi\n}\n\nlocate_mount_data_boot () {\n\ttrapper\n\techo \"`date` Locating the partitions on the data drive\" >> ${logpath}/${logfile}\n\t#export data_parts=`fdisk -l ${data_disk} 2>&1 | grep ^/  | awk '{print $1}'` >> ${logpath}/${logfile}\n\t#The below is updated to use lsblk, as fdisk output is diffferent between distros while the lsblk command is the same.\n\texport data_parts=`lsblk ${data_disk} -l -o name -n -p | grep -v -w ${data_disk}` >> ${logpath}/${logfile}\n\techo \"`date` Your data partitions are: ${data_parts}\" >> ${logpath}/${logfile}\n\n\t#create mountpoints for all the data parts\n\techo \"`date` Creating mountpoints for all partitions on the data drive\" >> ${logpath}/${logfile}\n\tfor dpart in ${data_parts} ; do echo \"`date` Creating mountpoint for ${dpart}\" >> ${logpath}/${logfile} ; mkdir -p /tmp${dpart} >> ${logpath}/${logfile} ; done\n\n\t#mount all partitions\n\techo \"`date` Mounting all partitions on the data drive\" >> ${logpath}/${logfile}\n\tfor part in ${data_parts} ; do echo \"`date` Mounting ${part} on /tmp/${part}\" >> ${logpath}/${logfile} ; mount ${part} /tmp${part} >> ${logpath}/${logfile} 2>&1 ; done\n\techo \"`date`Locating luksheader\" >> ${logpath}/${logfile} \n\texport luksheaderpath=`find /tmp -name osluksheader` >> ${logpath}/${logfile} \n\techo \"`date` The luksheader part is ${luksheaderpath}\" >> ${logpath}/${logfile}\n\texport boot_part=`df -h $luksheaderpath | grep ^/ |awk '{print $1}'` >> ${logpath}/${logfile}\n\techo \"`date` The boot partition on the data disk is ${boot_part}\" >> ${logpath}/${logfile}\n}\n\nmount_cmd () {\n\ttrapper\n\techo \"`date` Determine mount command\" >> ${logpath}/${logfile}\n\tmount_cmd=`mount -o nouuid 2> /dev/null` >> ${logpath}/${logfile} 2>&1\n\tif [ $? -gt 0 ]\n\tthen\n\t\t        export mount_cmd=\"mount\"\n\t\telse\n\t\t\t        export mount_cmd=\"mount -o nouuid\"\n\t\t\tfi\n}\n\nmount_lvm () {\n\ttrapper\n\techo \"`date` Mounting LVM structures found on ${root_part}\" >> ${logpath}/${logfile}\n\t#adding below lines to make sure that volume groups are activated before trying to mount.\n\tvgs >>  ${logpath}/${logfile}\n\tvgchange -ay rootvg >> ${logpath}/${logfile}\n\t${mount_cmd} /dev/rootvg/rootlv /investigateroot >> ${logpath}/${logfile}\n\t${mount_cmd} /dev/rootvg/varlv /investigateroot/var/ >> ${logpath}/${logfile}\n\t${mount_cmd} /dev/rootvg/homelv /investigateroot/home >> ${logpath}/${logfile}\n\t${mount_cmd} /dev/rootvg/usrlv /investigateroot/usr >> ${logpath}/${logfile}\n\t${mount_cmd} /dev/rootvg/tmplv /investigateroot/tmp >> ${logpath}/${logfile}\n\tlsblk -f >> ${logpath}/${logfile}\n}\n\nunlock_root () {\n\ttrapper\n\techo \"`date` unlocking root with command: cryptsetup luksOpen --key-file /mnt/azure_bek_disk/LinuxPassPhraseFileName --header /investigateboot/luks/osluksheader ${root_part} osencrypt\" >> ${logpath}/${logfile} \n\tcryptsetup luksOpen --key-file /mnt/azure_bek_disk/LinuxPassPhraseFileName --header /investigateboot/luks/osluksheader ${root_part} osencrypt >> ${logpath}/${logfile}\n}\n\nverify_root_unlock () {\n\ttrapper\n\techo \"`date` Verifying osencrypt unlock\" >> ${logpath}/${logfile}\n\tlsblk -f  | grep osencrypt >> ${logpath}/${logfile}\n\tif [ $? -gt 0 ]\n\tthen\n\t\t        echo \"`date` device osencrypt was not found\" >> ${logpath}/${logfile}\n\t\t\t        exit\n\t\t\telse\n\t\t\t\t        echo \"`date` device osencrypt found\" >> ${logpath}/${logfile}\n\t\t\t\tfi\n}\n\nmount_encrypted () {\n\ttrapper\n\techo \"`date` Mounting root\" >> ${logpath}/${logfile}\n\tif [ -z ${lvm_part} ]\n\tthen\n\t\techo \"`date` Mounting /dev/mapper/osencrypt on /investigateroot\" >> ${logpath}/${logfile}\n\t\t${mount_cmd} /dev/mapper/osencrypt /investigateroot >> ${logpath}/${logfile}\n\telse\n\t\t        sleep 5\n\t\t\t        mount_lvm\n\t\t\tfi\n}\n\nmount_boot () {\n\ttrapper\n\techo \"`date` Unmounting the boot partition ${boot_part} on the data drive from the temp mount\" >> ${logpath}/${logfile}\n\tumount -l ${boot_part} >> ${logpath}/${logfile}\n\techo \"`date` Mounting the boot partition ${boot_part} on /investigateboot\" >> ${logpath}/${logfile}\n\t${mount_cmd} ${boot_part} /investigateboot/ >> ${logpath}/${logfile}\n}\n\nremount_boot () {\n\ttrapper\n\techo \"`date` Unmounting the boot partition ${boot_part} on the data drive from the temp mount\" >> ${logpath}/${logfile}\n\tumount -l ${boot_part} >> ${logpath}/${logfile}\n\techo \"`date` Mounting the boot partition ${boot_part} on /investigateroot/boot\" >> ${logpath}/${logfile}\n\t${mount_cmd} ${boot_part} /investigateroot/boot >> ${logpath}/${logfile}\n}\ninstall_required_packages()\n{\n\techo \"`date` Checking about the required packages and instal the misssing ones\" >> ${logpath}/${logfile}\n\techo \"`date` Checking the distro of the recovery VM ..\" >> ${logpath}/${logfile}\n\toutput=`which apt`\n\tif [ $? -eq 0 ]\n\tthen\n\t\techo \"`date` This is ubuntu VM\" >> ${logpath}/${logfile}\n\t\tapt-get install -y cryptsetup lvm2 >> ${logpath}/${logfile}\n\telse\n\t\toutput=`which zypper`\n\t\tif [ $? -eq 0 ]\n\t\tthen\n\t\t\techo \"`date` This is a sles VM\" >> ${logpath}/${logfile}\n\t\t\tzypper --non-interactive --no-refresh install cryptsetup lvm2\n\t\telse\n\t\t\techo \"`date` This a yum based distro\"  >> ${logpath}/${logfile}\n\t\t\tyum install -y cryptsetup lvm2\n\t\tfi\n\tfi\n}\n\nsetlog\ninstall_required_packages\nduplication_validation\ncreate_mountpoints\nlocatebekvol\nmountbekvol\nget_data_disk\ncheck_local_lvm\ndata_os_lvm_check\nmount_cmd\nlocate_mount_data_boot\nmount_boot\nunlock_root\nverify_root_unlock\nmount_encrypted\nremount_boot", "num_lines": 246}
{"repo_name": "azure-cli-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Work around for Run-Command Shell Script behavior. Have to use 'ls' call to check if we pulled GitHub already.\nif [ $(ls | wc -l) -eq 3 ]; then\n\t# Try, && added to each line to stop on fail and continue to catch block\n\t{\n\t\tcurDate=$(date +%Y%m%d%H%M%S) &&\n\t\tdirname=\"repair-files-$curDate\" &&\n\t\tmkdir $dirname &&\n\t\tcd $dirname &&\n\t\tlogFileName=\"logs-$curDate.txt\" &&\n\t\tlogFile=\"$(pwd)/$line$logFileName\" &&\n\t\t# Log Start\n\t\techo \"[Log-Start  $(date \"+%m/%d/%Y %T\")]\" >> $logFile &&\n\t\tcurl -s -S -L -o repair-script-library.tar.gz https://github.com/Azure/repair-script-library/tarball/master/ &&\n\t\tmkdir repair-script-library &&\n\t\ttar -xf repair-script-library.tar.gz -C repair-script-library &&\n\t\tcd repair-script-library &&\n\t\treponame=$(ls) &&\n\t\tcd $reponame &&\n\t\t# Normal GitHub script scenario\n\t\tif [ \"$1\" != \"no-op\" ]; then\n\t\t\tchmod u+x $1 &&\n\t\t\tcommand_string=\"$*\" &&\n\t\t\tbash -e  $command_string >> $logFile\n\t\telse # Custom script scenario\n\t\t\t# Call the same script but it will only run the appended custom scripts\n\t\t\tbash -e $0 >> $logFile\n\t\tfi &&\n\n\t\t# Add status string to log file\n\t\techo \"status string: $?\" &&\n\t\tif [ $? -eq 0 ]; then\n\t\t\techo \"[STATUS]::SUCCESS\" >> $logFile\n\t\telse\n\t\t\techo \"[STATUS]::ERROR\" >> $logFile\n\t\tfi\n\t} || { # Catch\n\t\terrorMessage=$(cat /dev/stderr)\n\t\techo \"[Error $(date \"+%m/%d/%Y %T\")]$errorMessage\" >> $logFile\n\t} \n\t# Finally\n\techo \"[Log-End $(date \"+%m/%d/%Y %T\")]$logFile\" >> $logFile\n\techo $(cat $logFile)\n\t# Exit and don't run appended scripts from run-command\n\texit\nfi", "num_lines": 45}
{"repo_name": "azure-cli-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "azp=\"/home/pi/bin\"       #Path to Azure CLI binaries. Change if you didn't install at the default location\necho -n \"Please type the Shared Key:\"\nread sharedKey\n\necho $sharedKey\n\n#Retrieve local network information\nactiveInterface=$(ip route get 8.8.8.8 | awk '{print $5; exit}')\nactiveSubnet=$(ip route | grep $activeInterface | grep kernel | awk '{print $1; exit}')\nleftip=$(ip route | grep $activeInterface | grep kernel | awk '{print $9; exit}') \nlocalGatewayIpAddress=$(curl ifconfig.me) # enternal network address if behind a NAT\n\n\nresGroup=\"GWS2SRasp\"        # Resource group name\nlocation='Central US'   # AZR Region to deploy the gateway\nvpnType='RouteBased'\nlocalGatewayName='home'\nlocalAddressPrefix=$activeSubnet\nvirtualNetworkName='azureVNet'\nazureVNetAddressPrefix=\"10.3.0.0/16\"\nsubnetName='Subnet1'\nsubnetPrefix='10.3.0.0/24'\ngatewaySubnetPrefix=\"10.3.254.0/29\"\ngatewayName=\"azrGateway\"\ngatewaySku=\"Basic\"\nconnectName=\"AzureToHome\"\nvmName=\"pingTest\"\nvmSize=\"Standard_A1\"\nadminUserName=\"ubuntu\"\n\n# Hack to randomize the storage account name\nstorageAccountName=$(cat /proc/sys/kernel/random/uuid | md5sum)\nstorageAccountName=\"${storageAccountName:1:23}\" \n\nstorageAccountType=\"Standard_LRS\"\n\n#Parameters to deploy the Azure site to site ARM template\nparams=\"{\\\"vpnType\\\":{\\\"value\\\":\\\"$vpnType\\\"},\\\"localGatewayName\\\":{\\\"value\\\":\\\"$localGatewayName\\\"},\\\"adminUsername\\\":{\\\"value\\\":\\\"$adminUserName\\\"},\\\"localGatewayIpAddress\\\":{\\\"value\\\":\\\"$localGatewayIpAddress\\\"},\\\"localAddressPrefix\\\":{\\\"value\\\":\\\"$localAddressPrefix\\\"},\\\"azureVNetAddressPrefix\\\":{\\\"value\\\":\\\"$azureVNetAddressPrefix\\\"},\\\"subnetPrefix\\\":{\\\"value\\\":\\\"$subnetPrefix\\\"},\\\"gatewaySubnetPrefix\\\":{\\\"value\\\":\\\"$gatewaySubnetPrefix\\\"},\\\"newStorageAccountName\\\":{\\\"value\\\":\\\"$storageAccountName\\\"},\\\"sharedKey\\\":{\\\"value\\\":\\\"$sharedKey\\\"}}\"\n\necho \"Please follow the instructions to login\"\necho \"If the script is run over a SSH connection, you can open the browser locally\"\n$azp/az login\n\n$azp/az group create --name \"$resGroup\" --location \"$location\"\nres=$?\n\n$azp/az group deployment create \\\n    --name ExampleDeployment \\\n    --resource-group \"$resGroup\" \\\n    --template-uri \"https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/201-site-to-site-vpn/azuredeploy.json\" \\\n    --parameters $params\nres=$(( $res + $? ))\n\n#Get the IP Address from the create AZR VPN Gateway\n# jq is used to parse the json results \nid=$($azp/az network  vnet-gateway list --resource-group $resGroup | jq -r '.[].ipConfigurations[].publicIpAddress.id')\nres=$(( $res + $? ))\nip=$($azp/az network public-ip list --resource-group $resGroup | jq -r '.[] | select(.id==\"'$id'\") | .ipAddress')\nres=$(( $res + $? ))\nrightSubnet=$($azp/az network vnet list --resource-group $resGroup | jq -r \".[].addressSpace.addressPrefixes[0]\")\nres=$(( $res + $? ))\n\nif [ $res -ne 0 ] \nthen\n    echo \"Something went wrong... exiting\"\n    exit $res\nelse\n    echo \"Everything went well... Configuring strongSwan\"\nfi\n\n\nsecret=\"'$sharedKey'\"\necho $ip\n\n\n\nswann=\"conn home-to-azure\n        closeaction=restart\n        dpdaction=restart\n        ike=aes256-sha1-modp1024\n        esp=aes256-sha1\n        reauth=no\n        keyexchange=ike\n        mobike=no\n        ikelifetime=28800s\n        keylife=3600s\n        keyingtries=%forever\n        authby=secret\n        left=$leftip            # local instance ip (strongswan)\n        leftsubnet=$activeSubnet\n        leftid=$leftip         # local instance ip (strongswan)\n        right=$ip\n        rightid=$ip      # vpn gateway ip (azure)\n        rightsubnet=$rightSubnet      # private ip segment (azure)\n        auto=route\"\n\nsudo -s -- <<EOF\n\techo \"$swann\" >> /etc/ipsec.conf\nEOF\n\n\n#ip secrets \nipscr=\"$leftip $ip : PSK $secret\"\nsudo -s -- <<EOF\n\techo \"$ipscr\" >> /etc/ipsec.secrets\nEOF\n\necho Restarting IPSec...\nsudo ipsec restart \n", "num_lines": 110}
{"repo_name": "azure-cli-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\necho \"installing prerequisites...\"\necho \"...prerequisites to azure cli\"\nsudo apt-get update\nsudo apt-get install -y libssl-dev libffi-dev python-dev build-essential\n\necho \"...jq\"\nsudo apt-get install jq\n\necho \"...strongswann\"\nsudo apt-get install strongswan\n\necho \"... Azure command line\"\ncurl -L https://aka.ms/InstallAzureCli | bash\n\n", "num_lines": 17}
{"repo_name": "azure-cli-shell", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# --------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# --------------------------------------------------------------------------------------------\n\nset -e\n\n# PyLint does not yet support Python 3.6 https://github.com/PyCQA/pylint/issues/1241\nif [ \"$TRAVIS_PYTHON_VERSION\" != \"3.6\" ]; then\n    python -m unittest discover -s test\n    python -m linter.run \"$@\"\n\nelse\n    python -m unittest discover -s test -p 'test_*.py'\nfi\n\npython license-check/verify.py\n", "num_lines": 20}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function replace-tokens () {\n    envsubst < /cnab/app/values.yaml.template > /cnab/app/values.yaml\n    cat /cnab/app/values.yaml && echo \\n\\n\n}\n\n\"$@\"", "num_lines": 6}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function create-aks {\n    if [[ -z $(az aks show --name $1 --resource-group $2 2> /dev/null) ]]\n    then\n        az aks create \\\n        --name $1 \\\n        --resource-group $2 \\\n        --kubernetes-version $3 \\\n        --node-vm-size $4 \\\n        --node-count $5 \\\n        --service-principal $6 \\\n        --client-secret $7 \\\n        --location $8 \\\n        --vm-set-type $9 \\\n        --generate-ssh-keys\n    else\n        echo \"AKS cluster already exists in specified resource group with specified name\"\n    fi\n}\n\nfunction delete-aks {\n    az aks delete --name $1 --resource-group $2 --yes\n}\n\n\"$@\"", "num_lines": 24}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function create-AAD-app-registration {\n    az ad app create --display-name \"$1\" --identifier-uris \"http://$1\" --password \"$2\" --reply-url \"https://$3/oauth2/callback\"\n    AAD_CLIENT_ID=$(az ad app list --display-name $1 --query \"[0].appId\" -o tsv)\n    az ad app permission add --id $AAD_CLIENT_ID --api 00000002-0000-0000-c000-000000000000 --api-permissions 311a71cc-e848-46a1-bdf8-97ff7156d8e6=Scope\n}\n\nfunction replace-tokens {\n    export AAD_CLIENT_ID=$(az ad app list --display-name $1 --query \"[0].appId\" -o tsv)\n    export COOKIE_SECRET=$(< /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c${1:-32};echo;)\n    envsubst < oauth2-proxy-azure.yaml > manifest.yaml\n    cat manifest.yaml && echo \\n\\n\n}\n\nfunction create-namespace {\n    manifest=\"{\\\"apiVersion\\\": \\\"v1\\\", \\\"kind\\\": \\\"Namespace\\\", \\\"metadata\\\": { \\\"name\\\": \\\"$1\\\" }}\"\n    echo $manifest | kubectl apply -f -\n}\n\nfunction create-oauth2-secret {\n    kubectl create secret generic oauth2-secrets --namespace $1 --from-literal=clientSecret=$2\n}\n\nfunction delete-namespace {\n    kubectl delete namespace $1\n}\n\n\"$@\"", "num_lines": 27}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction configure-dns-name {\n    NAMESPACE=$1\n    INSTALLATION_NAME=$2\n    DNS_NAME=$3\n\n    RETRIES=0\n    while [ -z $IP ]; do\n        if [[ $RETRIES -gt 100 ]]; then\n            echo \"Exceeded number of retries for getting external IP address.\"\n            exit 1    \n        fi\n\n        IP=$(kubectl get service -l app=nginx-ingress,release=$INSTALLATION_NAME --namespace $NAMESPACE -o=jsonpath='{.items[0].status.loadBalancer.ingress[*].ip}')\n\n        if [[ -z $IP ]]; then\n            echo \"External IP address not ready yet. Trying again in 5 seconds.\"\n            sleep 5\n            RETRIES=$((RETRIES + 1))\n        else\n            echo \"Found external IP address.\"\n        fi\n    done\n\n    DNSNAME=$DNS_NAME\n    PUBLICIPID=$(az network public-ip list --query \"[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[id]\" --output tsv)\n    az network public-ip update --ids $PUBLICIPID --dns-name $DNSNAME\n    FQDN=$(az network public-ip list --query \"[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[dnsSettings.fqdn]\" --output tsv)\n    echo $FQDN > FQDN\n}\n\nfunction add-jetstack-helm-repo {\n    helm repo add jetstack https://charts.jetstack.io\n}\n\nfunction run-cert-manage-pre-reqs {\n    kubectl apply -f https://raw.githubusercontent.com/jetstack/cert-manager/release-0.8/deploy/manifests/00-crds.yaml\n    kubectl create namespace $1\n    kubectl label namespace $1 certmanager.k8s.io/disable-validation=true\n}\n\nfunction replace-tokens {\n    envsubst < /cnab/app/cluster-issuer-$1.yaml > /cnab/app/cluster-issuer.yaml\n}\n\nfunction delete-certmanager-namespace {\n    kubectl delete namespace $1\n}\n\n\"$@\"", "num_lines": 51}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction generate-keyfile-from-cred() {\n    # to avoid accidents when testing this script locally, don't clobber an existing key file\n    if [[ -f '/root/.ssh/id_rsa' ]]; then\n        echo \"Keyfile already exists - skipping\"\n    else\n        mkdir /root/.ssh\n        echo $SSH_PRIVATE_KEY_BASE64 | base64 --decode - >/root/.ssh/id_rsa\n        chmod 600 /root/.ssh/id_rsa\n    fi\n}\nfunction run-ansible() {\n    ANSIBLE_CMD=\"ansible-playbook -i ./ansible/environments/$ENVIRONMENT $2 ansible/$1\"\n    echo \"ansible cmd: $ANSIBLE_CMD\"\n    $ANSIBLE_CMD\n}\n\nfunction install() {\n    generate-keyfile-from-cred\n    run-ansible \"install.yml\" \"-e admin_public_key_base64=$ADMIN_PUBLIC_KEY_BASE64\"\n}\nfunction uninstall() {\n    run-ansible \"uninstall.yml\"\n}\nfunction upgrade() {\n    generate-keyfile-from-cred\n    run-ansible \"install.yml\" \"-e skip_provision=true\"\n}\n\nACTION=$1\nENVIRONMENT=$2\n# The public key will contain a space to base64 encode it to make life easier passing it around\nADMIN_PUBLIC_KEY_BASE64=$(echo $3 | base64 --wrap=0)\n\n\"$@\"", "num_lines": 36}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function create-kubernetes-namespace() {\n    manifest=\"{\\\"apiVersion\\\": \\\"v1\\\", \\\"kind\\\": \\\"Namespace\\\", \\\"metadata\\\": { \\\"name\\\": \\\"$1\\\" }}\"\n    echo $manifest | kubectl apply -f -\n}\n\nfunction delete-kubernetes-namespace() {\n    kubectl delete namespace $1\n}\n\n\"$@\"", "num_lines": 10}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function replace-tokens {\n    envsubst < /cnab/app/values.yaml.template > /cnab/app/values.yaml\n    cat /cnab/app/values.yaml && echo \\n\\n\n}\n\n\"$@\"", "num_lines": 6}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ninstall-kubeflow() {\n    export KF_NAME=$1\n    export BASE_DIR=/kubeflow\n    export KF_DIR=${BASE_DIR}/${KF_NAME}\n    export CONFIG_URI=$2\n    mkdir -p ${KF_DIR}\n    cd ${KF_DIR}\n    kfctl apply -V -f ${CONFIG_URI}\n}\n\nuninstall-kubeflow() {\n    export KF_NAME=$1\n    export BASE_DIR=/kubeflow\n    export KF_DIR=${BASE_DIR}/${KF_NAME}\n    export CONFIG_URI=$2\n    mkdir -p ${KF_DIR}\n    cd ${KF_DIR}\n    kfctl delete -f ${CONFIG_URI}\n}\n\n# Call the requested function and pass the arguments as-is\n\"$@\"", "num_lines": 24}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction configure-dns-name {\n    NAMESPACE=$1\n    INSTALLATION_NAME=$2\n    DNS_NAME=$3\n\n    RETRIES=0\n    while [ -z $IP ]; do\n        if [[ $RETRIES -gt 100 ]]; then\n            echo \"Exceeded number of retries for getting external IP address.\"\n            exit 1    \n        fi\n\n        IP=$(kubectl get service -l app.kubernetes.io/component=controller,app.kubernetes.io/name=ingress-nginx,app.kubernetes.io/instance=$INSTALLATION_NAME --namespace $NAMESPACE -o=jsonpath='{.items[0].status.loadBalancer.ingress[*].ip}')\n\n        if [[ -z $IP ]]; then\n            echo \"External IP address not ready yet. Trying again in 5 seconds.\"\n            sleep 5\n            RETRIES=$((RETRIES + 1))\n        else\n            echo \"Found external IP address.\"\n        fi\n    done\n\n    DNSNAME=$DNS_NAME\n    PUBLICIPID=$(az network public-ip list --query \"[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[id]\" --output tsv)\n    az network public-ip update --ids $PUBLICIPID --dns-name $DNSNAME\n    FQDN=$(az network public-ip list --query \"[?ipAddress!=null]|[?contains(ipAddress, '$IP')].[dnsSettings.fqdn]\" --output tsv)\n    echo $FQDN > FQDN\n}\n\nfunction add-helm-repos {\n    helm repo add jetstack https://charts.jetstack.io\n    helm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx\n    helm repo add stable https://kubernetes-charts.storage.googleapis.com/\n    helm repo update\n}\n\nfunction create-cert-manager-namespace {\n    kubectl create namespace $1\n    kubectl label namespace $1 certmanager.k8s.io/disable-validation=true\n}\n\nfunction replace-tokens {\n    envsubst < /cnab/app/cluster-issuer-$1.yaml > /cnab/app/cluster-issuer.yaml\n    cat /cnab/app/cluster-issuer.yaml\n}\n\nfunction delete-certmanager-namespace {\n    kubectl delete namespace $1\n}\n\n\"$@\"", "num_lines": 54}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function create-aks {\n    if [[ -z $(az aks show --name $1 --resource-group $2 2> /dev/null) ]]\n    then\n        az aks create \\\n        --name $1 \\\n        --resource-group $2 \\\n        --kubernetes-version $3 \\\n        --node-vm-size $4 \\\n        --node-count $5 \\\n        --service-principal $6 \\\n        --client-secret $7 \\\n        --location $8 \\\n        --vm-set-type $9 \\\n        --generate-ssh-keys\n    else\n        echo \"AKS cluster already exists in specified resource group with specified name\"\n    fi\n}\n\nfunction delete-aks {\n    az aks delete --name $1 --resource-group $2 --yes\n}\n\n\"$@\"", "num_lines": 24}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function replace-tokens {\n    export INGRESS_HOST=$2\n    export CERT_MANAGER_ISSUER=$3\n\n    if [[ $MATTERMOST_LICENSE == '' ]]\n    then \n        export MATTERMOST_LICENSE='nolicense' # Set to a value, otherwise the Helm template isn't happy\n    fi\n\n    envsubst < /cnab/app/mattermost-$1-values.yaml > /cnab/app/mattermost-values.yaml\n    cat /cnab/app/mattermost-values.yaml\n}\n\n\"$@\"", "num_lines": 14}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function replace-tokens {\n    envsubst < /cnab/app/values.yaml.template > /cnab/app/values.yaml\n    cat /cnab/app/values.yaml && echo \\n\\n\n}\n\n\"$@\"", "num_lines": 6}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmaster_host=$1\nmaster_port=$2\nmaster_username=$3\nworkers_host=$4\nworkers_port=$5\nworkers_username=$6\n\nfunction disableContainerFeatures {\n    username=$1\n    port=$2\n    host=$3\n\n    # Enable container features and reboot\n    ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port /bin/bash << EOF\nsudo sed -i 's/ cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory//g' /boot/cmdline.txt\nEOF\n}\n\n# Update master node\n\ndisableContainerFeatures $master_username $master_port $master_host\n\n# Update worker nodes\n\nIFS=',' read -r -a hosts <<< \"$workers_host\"\nIFS=',' read -r -a ports <<< \"$workers_port\"\nIFS=',' read -r -a usernames <<< \"$workers_username\"\n\nfor index in \"${!hosts[@]}\"\ndo\n    disableContainerFeatures ${usernames[index]} ${ports[index]} ${hosts[index]}\ndone", "num_lines": 34}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmaster_host=$1\nmaster_port=$2\nmaster_username=$3\nworkers_host=$4\nworkers_port=$5\nworkers_username=$6\n\nfunction enableContainerFeatures {\n    username=$1\n    port=$2\n    host=$3\n\n    # Enable container features and reboot\n    ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port /bin/bash << EOF\nsudo sed -i '$ s/$/ cgroup_enable=cpuset cgroup_memory=1 cgroup_enable=memory/' /boot/cmdline.txt\nsudo reboot\nEOF\n}\n\nfunction waitForSsh {\n    username=$1\n    port=$2\n    host=$3\n    \n    ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port echo\n    while test $? -gt 0\n    do\n        echo \"Waiting for reboot on $host:$port...\"\n        sleep 5\n        ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port echo\n    done\n\n    echo \"Node at $host started\"\n}\n\n# Update master node\n\nenableContainerFeatures $master_username $master_port $master_host\n\n# Update worker nodes\n\nIFS=',' read -r -a hosts <<< \"$workers_host\"\nIFS=',' read -r -a ports <<< \"$workers_port\"\nIFS=',' read -r -a usernames <<< \"$workers_username\"\n\nfor index in \"${!hosts[@]}\"\ndo\n    enableContainerFeatures ${usernames[index]} ${ports[index]} ${hosts[index]}\ndone\n\n# Wait for nodes to start up again\n\nwaitForSsh $master_username $master_port $master_host\n\nfor index in \"${!hosts[@]}\"\ndo\n    waitForSsh ${usernames[index]} ${ports[index]} ${hosts[index]}\ndone", "num_lines": 60}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmaster_host=$1\nmaster_port=$2\nmaster_username=$3\nmaster_kubernetes_host=$4\nmaster_kubernetes_port=$5\n\nssh -o StrictHostKeyChecking=no $master_username@$master_host -p $master_port /bin/bash << EOF\nsudo cp /etc/rancher/k3s/k3s.yaml /tmp/config\nsudo chmod 777 /tmp/config\nEOF\n\nmkdir ~/.kube\nscp -P $master_port $master_username@$master_host:/tmp/config ~/.kube\n\nssh -o StrictHostKeyChecking=no $master_username@$master_host -p $master_port /bin/bash << EOF\nsudo rm /tmp/config\nEOF\n\nkubectl config set-cluster default --server=https://$master_kubernetes_host:$master_kubernetes_port\nkubectl config use-context default\nkubectl config view", "num_lines": 23}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmaster_internal_IP=$1\nmaster_host=$2\nmaster_port=$3\nmaster_username=$4\nworkers_host=$5\nworkers_port=$6\nworkers_username=$7\n\n\n# Install master\n\nssh -o StrictHostKeyChecking=no $master_username@$master_host -p $master_port /bin/bash << EOF\ncurl -sfL https://get.k3s.io | sh -\n\nsystemctl is-active --quiet k3s\nwhile test $? -gt 0\ndo\n    echo \"Waiting for k3s service to start...\"\n    sleep 5\n    systemctl is-active --quiet k3s\ndone\necho \"k3s service is active\"\nEOF\n\n\ntoken=$(ssh -o StrictHostKeyChecking=no $master_username@$master_host -p $master_port /bin/bash << EOF\nsudo cat /var/lib/rancher/k3s/server/node-token\nEOF\n)\n\necho \"Join token is: $token\"\n\n# Install workers\n\nIFS=',' read -r -a hosts <<< \"$workers_host\"\nIFS=',' read -r -a ports <<< \"$workers_port\"\nIFS=',' read -r -a usernames <<< \"$workers_username\"\n\nfor index in \"${!hosts[@]}\"\ndo\n    username=${usernames[index]} \n    port=${ports[index]} \n    host=${hosts[index]}\n\n    echo \"Installing worker node at $username@$host:$port\"\n\n    ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port /bin/bash << EOF\nexport K3S_URL=\"https://${master_internal_IP}:6443\"\nexport K3S_TOKEN=\"${token}\"\ncurl -sfL https://get.k3s.io | sh -\nEOF\ndone", "num_lines": 54}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "kubectl create serviceaccount tiller --namespace kube-system --dry-run=true -o yaml | kubectl apply -f -\nkubectl create clusterrolebinding tiller-cluster-rule --clusterrole=cluster-admin --serviceaccount=kube-system:tiller --dry-run=true -o yaml | kubectl apply -f -\nhelm init --tiller-image=jessestuart/tiller --service-account tiller --upgrade", "num_lines": 3}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "chmod 400 /root/.ssh/id_rsa", "num_lines": 1}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmaster_host=$1\nmaster_port=$2\nmaster_username=$3\nworkers_host=$4\nworkers_port=$5\nworkers_username=$6\n\n\n# Uninstall master\n\nssh -o StrictHostKeyChecking=no $master_username@$master_host -p $master_port /bin/bash << EOF\n/usr/local/bin/k3s-killall.sh\n/usr/local/bin/k3s-uninstall.sh\nEOF\n\n\n# Uninstall workers\n\nIFS=',' read -r -a hosts <<< \"$workers_host\"\nIFS=',' read -r -a ports <<< \"$workers_port\"\nIFS=',' read -r -a usernames <<< \"$workers_username\"\n\nfor index in \"${!hosts[@]}\"\ndo\n    username=${usernames[index]} \n    port=${ports[index]} \n    host=${hosts[index]}\n\n    echo \"Uninstalling worker node at $username@$host:$port\"\n\n    ssh -o StrictHostKeyChecking=no -o ProxyCommand=\"ssh -o StrictHostKeyChecking=no -W %h:%p $master_username@$master_host -p $master_port\" $username@$host -p $port /bin/bash << EOF\n/usr/local/bin/k3s-killall.sh\n/usr/local/bin/k3s-agent-uninstall.sh\nEOF\ndone", "num_lines": 37}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function create-aks {\n    if [[ -z $(az aks show --name $1 --resource-group $2 2> /dev/null) ]]\n    then\n        az aks create \\\n        --name $1 \\\n        --resource-group $2 \\\n        --kubernetes-version $3 \\\n        --node-count $4 \\\n        --service-principal $5 \\\n        --client-secret $6 \\\n        --location $7 \\\n        --generate-ssh-keys\n    else\n        echo \"AKS cluster already exists in specified resource group with specified name\"\n    fi\n}\n\nfunction wait-for-sql-custom-resource {\n    crd=''\n    while [[ -z $crd ]]\n        do crd=$(kubectl get crd --field-selector=metadata.name=sqlservers.mssql.microsoft.com --ignore-not-found=true)\n        echo 'Waiting for sql server CRD to be created'\n        sleep 30\n    done\n}\n\nfunction output-primary-ip-address {\n    PRIMARY_IP=''\n    while [[ -z $PRIMARY_IP ]]\n        do PRIMARY_IP=$(kubectl get svc/ag1-primary -n ag1 -o=jsonpath='{.status.loadBalancer.ingress[0].ip}' --ignore-not-found=true)\n        echo 'Waiting for primary AG IP Address' \n        sleep 30\n    done\n    echo Connect to SQL Primary: sqlcmd -S ${PRIMARY_IP} -U sa\n}\n\nfunction delete-resource-group {\n    az group delete --name $1 --yes\n}\n\n\"$@\"", "num_lines": 41}
{"repo_name": "azure-cnab-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "function replace-tokens {\n    envsubst < /cnab/app/values.yaml.template > /cnab/app/values.yaml\n    cat /cnab/app/values.yaml && echo \\n\\n\n}\n\n\"$@\"", "num_lines": 6}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "# NOTE: you may not be able to unzip logs.zip in Linux since it was compressed in Windows\nset -e\ndateString=`date -I` # like 2022-09-24\nfilepath=logs_$dateString\nmkdir $filepath\n\necho \"gathering logs and writing to $filepath/\"\n\nkubectl get pod -A -o wide --show-labels > $filepath/allpods.out\nkubectl get netpol -A -o yaml > $filepath/all-netpol-yamls.out\nkubectl describe netpol -A > $filepath/all-netpol-descriptions.out\n\nnpmPods=()\nnodes=()\nfor npmPodOrNode in `kubectl get pod -n kube-system -owide --output=custom-columns='Name:.metadata.name,Node:spec.nodeName' | grep \"npm-win\"`; do\n    # for loop will go over each item (npm pod, then its node, then the next npm pod, then its node, ...)\n    set +e\n    echo $npmPodOrNode | grep -q azure-npm-win-\n    if [ $? -eq 0 ]; then\n        npmPods+=($npmPodOrNode)\n    else\n        nodes+=($npmPodOrNode)\n    fi\ndone\nset -e\n\necho \"npm pods: ${npmPods[@]}\"\necho \"nodes of npm pods: ${nodes[@]}\"\n\nfor i in $(seq 1 ${#npmPods[*]}); do\n    j=$((i-1))\n    npmPod=${npmPods[$j]}\n    node=${nodes[$j]}\n\n    echo \"gathering logs. npm pod: $npmPod. node: $node\"\n    kubectl logs -n kube-system $npmPod > $filepath/logs_$npmPod.out\n\n    ips=()\n    for ip in `kubectl get pod -A -owide --output=custom-columns='IP:.status.podIP,Node:spec.nodeName' | grep $node | grep -oP \"\\d+\\.\\d+\\.\\d+\\.\\d+\"`; do \n        ips+=($ip)\n    done\n    echo \"node $node has IPs: ${ips[@]}\"\n\n    echo \"copying ps1 file into $npmPod\"\n    kubectl cp ./pod_exec.ps1 kube-system/\"$npmPod\":execw.ps1\n\n    echo \"executing ps1 file on $npmPod\"\n    kubectl exec -it -n kube-system $npmPod -- powershell.exe -Command  .\\\\execw.ps1 \"'${ips[@]}'\"\n\n    echo \"copying logs.zip from $npmPod. NOTE: this will be a windows-based compressed archive (probably need windows to expand it)\"\n    kubectl cp kube-system/\"$npmPod\":npm-exec-logs.zip $filepath/npm-exec-logs_$node.zip\ndone\n\necho \"finished gathering all logs. written to $filepath/\"\n", "num_lines": 55}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCERTS_STAGING_DIR=.\nSAN_CNF_FILE=san.cnf\nCERTIFICATE_VALIDITY_DAYS=3650\nCERT_SUBJ=\"/C=US/ST=Washington/L=Redmond/O=Microsoft/OU=Azure/CN=azure-npm.kube-system.svc.cluster.local\"\n\n# Check if openssl is installed\nif ! command -v openssl &> /dev/null\nthen\n  echo \"openssl could not be found\"\n  exit\nfi\n\n# Check if SAN_CNF_FILE exists\nif [ ! -f \"$SAN_CNF_FILE\" ]\nthen\n  echo \"SAN_CNF_FILE does not exist\"\n  exit\nfi\n\nif [ ! -d \"$CERTS_STAGING_DIR\" ]\nthen\n  echo \"Creating $CERTS_STAGING_DIR\"\n  mkdir -p $CERTS_STAGING_DIR\nfi\n\n# Generate the ca certificate and key\nopenssl req -x509 -newkey rsa:4096 -days $CERTIFICATE_VALIDITY_DAYS -nodes -keyout $CERTS_STAGING_DIR/ca.key -out $CERTS_STAGING_DIR/ca.crt -subj $CERT_SUBJ\n\n# Create a certificate signing request for the server\nopenssl req -newkey rsa:4096 -nodes -keyout $CERTS_STAGING_DIR/tls.key -out $CERTS_STAGING_DIR/server-req.pem -config $SAN_CNF_FILE -extensions v3_req -subj $CERT_SUBJ\n\n# Sign the server certificate with the CA\nopenssl x509 -req -in $CERTS_STAGING_DIR/server-req.pem -CA $CERTS_STAGING_DIR/ca.crt -CAkey $CERTS_STAGING_DIR/ca.key -CAcreateserial -out $CERTS_STAGING_DIR/tls.crt --days $CERTIFICATE_VALIDITY_DAYS --extfile $SAN_CNF_FILE --extensions v3_req\n\n# Remove the secret CA key and signing request\nrm -rf $CERTS_STAGING_DIR/ca.key $CERTS_STAGING_DIR/server-req.pem\n", "num_lines": 39}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Delete a docker container with network namespace cleaned up by the Azure CNI plugin.\n# Example usage: ./docker-run.sh ubuntu default\n\nif [ $# -ne 2 ]; then\n\techo \"usage: docker-run.sh <container-name> <namespace>\"\n\texit 1\nfi\n\npid=$(docker inspect -f '{{ .State.Pid }}' $1)\nnetnspath=/proc/$pid/ns/net\ncontid=$(docker inspect -f '{{ .Id }}' $1)\nexport CNI_CONTAINERID=$contid\n\nnetns=netnspath\nexport CNI_PATH='/opt/cni/bin'\nexport CNI_COMMAND='DEL'\nexport PATH=$CNI_PATH:$PATH\nexport CNI_NETNS=$netns\nargs=$(printf \"K8S_POD_NAMESPACE=%s;K8S_POD_NAME=%s\" $2 $1)\nexport CNI_ARGS=$args\nexport CNI_IFNAME='eth0'\n\n\nconfig=$(jq '.plugins[0]' /etc/cni/net.d/10-azure.conflist)\nname=$(jq -r '.name' /etc/cni/net.d/10-azure.conflist)\nconfig=$(echo $config | jq --arg name $name '. + {name: $name}')\ncniVersion=$(jq -r '.cniVersion' /etc/cni/net.d/10-azure.conflist)\nconfig=$(echo $config | jq --arg cniVersion $cniVersion '. + {cniVersion: $cniVersion}')\n\nres=$(echo $config | azure-vnet)\n\n\nif [ $? -ne 0 ]; then\n\terrmsg=$(echo $res | jq -r '.msg')\n\tif [ -z \"$errmsg\" ]; then\n\t\terrmsg=$res\n\tfi\n\techo \"${name} : error executing $CNI_COMMAND: $errmsg\"\n\texit 1\nelif [[ ${DEBUG} -gt 0 ]]; then\n\techo ${res} | jq -r .\nfi\n\n\ndocker rm -f $1\n", "num_lines": 48}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Run a docker container with network namespace set up by the Azure CNI plugin.\n# Example usage: ./docker-run.sh ubuntu default sushantsharma/ubuntu-s5\n\nif [ $# -ne 3 ]; then\n\techo \"usage: docker-run.sh <container-name> <namespace> <image>\"\n\texit 1\nfi\n\ncontid=$(docker run -d --name $1 --net=none $3 /bin/sleep 10000000)\nexport CNI_CONTAINERID=$contid\npid=$(docker inspect -f '{{ .State.Pid }}' $contid)\nnetns=/proc/$pid/ns/net\n\nexport CNI_PATH='/opt/cni/bin'\nexport CNI_COMMAND='ADD'\nexport PATH=$CNI_PATH:$PATH\nexport CNI_NETNS=$netns\nargs=$(printf \"K8S_POD_NAMESPACE=%s;K8S_POD_NAME=%s\" $2 $1)\nexport CNI_ARGS=$args\nexport CNI_IFNAME='eth0'\n\nconfig=$(jq '.plugins[0]' /etc/cni/net.d/10-azure.conflist)\nname=$(jq -r '.name' /etc/cni/net.d/10-azure.conflist)\nconfig=$(echo $config | jq --arg name $name '. + {name: $name}')\ncniVersion=$(jq -r '.cniVersion' /etc/cni/net.d/10-azure.conflist)\nconfig=$(echo $config | jq --arg cniVersion $cniVersion '. + {cniVersion: $cniVersion}')\n\nres=$(echo $config | azure-vnet)\n\nif [ $? -ne 0 ]; then\n\terrmsg=$(echo $res | jq -r '.msg')\n\tif [ -z \"$errmsg\" ]; then\n\t\terrmsg=$res\n\tfi\n\techo \"${name} : error executing $CNI_COMMAND: $errmsg\"\n\texit 1\nelif [[ ${DEBUG} -gt 0 ]]; then\n\techo ${res} | jq -r .\nfi\n\n", "num_lines": 43}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Installs azure-vnet CNI plugins on a Linux node.\n\n# Arguments.\nPLUGIN_VERSION=$1\nCNI_VERSION=$2\nCNI_BIN_DIR=/opt/cni/bin\nCNI_NETCONF_DIR=/etc/cni/net.d\n\nfunction usage\n{\n    printf \"Installs azure-vnet CNI plugins.\\n\"\n    printf \"Usage: install-cni-plugin version [cniVersion]\\n\"\n}\n\nif [ \"$PLUGIN_VERSION\" = \"\" ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$CNI_VERSION\" = \"\" ]; then\n    CNI_VERSION=v0.4.0\nfi\n\n# Create CNI directories.\nprintf \"Creating CNI directories.\\n\"\nmkdir -p $CNI_BIN_DIR\nmkdir -p $CNI_NETCONF_DIR\n\n# Install ebtables.\nif [ ! -e /sbin/ebtables ]\nthen\n    printf \"Installing ebtables package...\"\n    apt-get update\n    apt-get install -y ebtables\n    printf \"done.\\n\"\nelse\n    echo \"Package ebtables is already installed.\"\nfi\n/sbin/ebtables --list > /dev/null\n\n# Install azure-vnet CNI plugins.\nprintf \"Installing azure-vnet CNI plugin for multitenancy version $PLUGIN_VERSION to $CNI_BIN_DIR...\"\n/usr/bin/curl -sSL https://github.com/Azure/azure-container-networking/releases/download/$PLUGIN_VERSION/azure-vnet-cni-multitenancy-linux-amd64-$PLUGIN_VERSION.tgz > $CNI_BIN_DIR/azure-vnet.tgz\ntar -xzf $CNI_BIN_DIR/azure-vnet.tgz -C $CNI_BIN_DIR\nprintf \"done.\\n\"\n\n# Install azure-vnet CNI network configuration file.\nprintf \"Installing azure-vnet CNI network configuration file to $CNI_NETCONF_DIR...\"\nmv $CNI_BIN_DIR/*.conflist $CNI_NETCONF_DIR\nprintf \"done.\\n\"\n\n# Install loopback plugin.\nprintf \"Installing loopback CNI plugin version $CNI_VERSION to $CNI_BIN_DIR...\"\n/usr/bin/curl -sSL https://github.com/containernetworking/cni/releases/download/$CNI_VERSION/cni-amd64-$CNI_VERSION.tgz > $CNI_BIN_DIR/cni.tgz\ntar -xzf $CNI_BIN_DIR/cni.tgz -C $CNI_BIN_DIR ./loopback\nprintf \"done.\\n\"\n\n# Cleanup.\nrm $CNI_BIN_DIR/*.tgz\nchown root:root $CNI_BIN_DIR/*\n\nprintf \"azure-vnet CNI plugin is successfully installed.\\n\"\n", "num_lines": 65}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Installs azure-vnet CNI plugins on a Linux node.\n\n# Arguments.\nPLUGIN_VERSION=$1\nCNI_VERSION=$2\nCNI_BIN_DIR=/opt/cni/bin\nCNI_NETCONF_DIR=/etc/cni/net.d\n\nfunction usage\n{\n    printf \"Installs azure-vnet CNI plugins.\\n\"\n    printf \"See https://github.com/Azure/azure-container-networking/releases for versions\\n\"\n    printf \"Usage: install-cni-plugin version [pluginVersion]\\n\"\n}\n\nif [ \"$PLUGIN_VERSION\" = \"\" ]; then\n    usage\n    exit 1\nfi\n\nif [ \"$CNI_VERSION\" = \"\" ]; then\n    CNI_VERSION=v1.1.1\nfi\n\n# Create CNI directories.\nprintf \"Creating CNI directories.\\n\"\nmkdir -p $CNI_BIN_DIR\nmkdir -p $CNI_NETCONF_DIR\n\n# Install ebtables.\nif [ ! -e /sbin/ebtables ]\nthen\n    printf \"Installing ebtables package...\"\n    apt-get update\n    apt-get install -y ebtables\n    printf \"done.\\n\"\nelse\n    echo \"Package ebtables is already installed.\"\nfi\n/sbin/ebtables --list > /dev/null\n\n# Install azure-vnet CNI plugins.\nprintf \"Installing azure-vnet CNI plugin version $PLUGIN_VERSION to $CNI_BIN_DIR...\"\n/usr/bin/curl -sSL https://github.com/Azure/azure-container-networking/releases/download/$PLUGIN_VERSION/azure-vnet-cni-linux-amd64-$PLUGIN_VERSION.tgz > $CNI_BIN_DIR/azure-vnet.tgz\ntar -xzf $CNI_BIN_DIR/azure-vnet.tgz -C $CNI_BIN_DIR\nprintf \"done.\\n\"\n\n# Install azure-vnet CNI network configuration file.\nprintf \"Installing azure-vnet CNI network configuration file to $CNI_NETCONF_DIR...\"\nmv $CNI_BIN_DIR/*.conflist $CNI_NETCONF_DIR\nprintf \"done.\\n\"\n\n# Install loopback plugin.\nprintf \"Installing loopback CNI plugin version $CNI_VERSION to $CNI_BIN_DIR...\"\n/usr/bin/curl -sSL https://github.com/containernetworking/plugins/releases/download/$CNI_VERSION/cni-plugins-linux-amd64-$CNI_VERSION.tgz > $CNI_BIN_DIR/cni.tgz\ntar -xzf $CNI_BIN_DIR/cni.tgz -C $CNI_BIN_DIR ./loopback\nprintf \"done.\\n\"\n\n# Cleanup.\nrm $CNI_BIN_DIR/*.tgz\nchown root:root $CNI_BIN_DIR/*\n\nprintf \"azure-vnet CNI plugin is successfully installed.\\n\"\n", "num_lines": 66}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nPROTOBUFF_VERSION=3.19.1\nPB_REL=\"https://github.com/protocolbuffers/protobuf/releases\"\nPROTOC_ZIP_NAME=protoc-${PROTOBUFF_VERSION}-linux-x86_64.zip\nPROTOC_INSTALL_PATH=$HOME/.local\n\n# install unzip on linux if not installed\nif [[ \"$OSTYPE\" == \"linux-gnu\" ]]; then\n\tif ! type \"unzip\" > /dev/null; then\n\t\tsudo apt-get install unzip\n\tfi\nfi\n\n# install protoc and protoc-gen-go\nif [ ! -f ${PROTOC_INSTALL_PATH}/bin/protoc ]; then\n    echo \"Installing protobuf compiler\"\n\t\tcurl -LO ${PB_REL}/download/v${PROTOBUFF_VERSION}/${PROTOC_ZIP_NAME}\n\t\techo \"Unzipping protoc\"\n\t\tunzip -o ${PROTOC_ZIP_NAME} -d ${PROTOC_INSTALL_PATH}\n\t\tchmod +x ${PROTOC_INSTALL_PATH}/bin/protoc \n\t\texport PATH=${PROTOC_INSTALL_PATH}/bin:$PATH\n\t\techo \"Removing protoc zip\"\n\t\trm ${PROTOC_ZIP_NAME}\nelse\n\techo \"Protobuf compiler already installed at ${PROTOC_INSTALL_PATH}/bin/protoc\"\n\techo \"Add protoc to your PATH if you want to use it from anywhere else using the following command:\"\n\texport PATH=${PROTOC_INSTALL_PATH}/bin:$PATH\nfi\n\n# install protoc-gen-go\nif [ ! -f ${GOPATH}/bin/protoc-gen-go ]; then\n\techo \"Installing protoc-gen-go\"\n\tgo install github.com/golang/protobuf/protoc-gen-go@v1.26\nelse\n\techo \"protoc-gen-go already installed at ${GOPATH}/bin/protoc-gen-go\"\nfi\n\n# install protoc-gen-go-grpc\nif [ ! -f ${GOPATH}/bin/protoc-gen-go-grpc ]; then\n\techo \"Installing protoc-gen-go-grpc\"\n\tgo install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1\nelse\n\techo \"protoc-gen-go-grpc already installed at ${GOPATH}/bin/protoc-gen-go-grpc\"\nfi\n", "num_lines": 46}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport MAJOR=0\nexport MINOR=0\nexport PATCH=0\nexport FULL_TAG=\"v0.0.0\"\n\nfunction create_release () {\n    parse_git_tag\n\n    if increment_git_tag\n    then\n        FULL_TAG=\"v${MAJOR}.${MINOR}.${PATCH}\"\n        set_git_tag\n    else\n        echo \"local git tag unchanged\"\n    fi  \n}\n\nfunction get_git_tag () {\n    \n    return echo \"v${MAJOR}${MINOR}${PATCH}\"\n}\n\nfunction set_git_tag () {\n    read -p \"Set git tag to $FULL_TAG? [y/N] \" -n 1 -r\n    echo\n    if [[ $REPLY =~ ^[Yy]$  ]]\n    then\n        git tag $FULL_TAG\n        echo \"git tag set to $FULL_TAG\"\n\n        push_git_tag\n    fi\n    \n    return\n}\n\nfunction push_git_tag {\n    remote=$(git rev-parse --abbrev-ref --symbolic-full-name @{u} | cut -f1 -d\"/\")\n\n    read -p \"Push git tag to remote $remote? [y/N] \" -n 1 \n    echo\n    if [[ $REPLY =~ ^[Yy]$  ]]\n    then\n        git push $remote $FULL_TAG \n    fi\n}\n\nfunction increment_git_tag () {\n    read -p \"Does this release contain incompatible API changes? [y/N] \" -n 1 -r\n    echo\n    if [[ $REPLY =~ ^[Yy]$  ]]\n    then\n        MAJOR=$((MAJOR+1))\n        MINOR=0\n        PATCH=0\n        return \n    fi\n\n    read -p \"Does this release contain added functionality that's backwards compatible? [y/N] \" -n 1 -r\n    echo\n    if [[ $REPLY =~ ^[Yy]$  ]]\n    then\n        MINOR=$((MINOR+1))\n        PATCH=0\n        return \n    fi\n\n    read -p \"Does this release only contain backwards compatible bug fixes [y/N] \" -n 1 -r\n    echo\n    if [[ $REPLY =~ ^[Yy]$  ]]\n    then\n        PATCH=$((PATCH+1))\n        return \n    fi\n\n    false\n}\n\nfunction parse_git_tag () {\n    FULL_TAG=$(git describe --tags --abbrev=0)\n    echo Current git tag: $FULL_TAG\n    echo \"--------\"\n    tagArr=(${FULL_TAG//./ })\n    MAJOR=${tagArr[0]:1}\n    MINOR=${tagArr[1]}\n    PATCH=${tagArr[2]}\n}\n\ncreate_release", "num_lines": 91}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "# this is required so that if a step fails, following steps are not run\nset -o errexit\n\nlog() {\n\tlocal msg=$1\n\techo \"$(date -R): $msg\"\n}\n\n# Installs NPM + a long-running Pod and does the following tests:\n# 1.1. Check if HNS rehydration of endpoints works (filename: rehydration.failed)\n# 1.2. Check VFP is in sync with HNS (filename: vfp-state-prior.success)\n# 2. Run Cyclonus (filename: cyclonus.success)\n# 3. Check VFP is in sync with HNS (filename: vfp-state-after-cyclonus.success)\n# 4. Run Conformance (filename: conformance.success)\n# 5. Check VFP is in sync with HNS (filename: vfp-state-after-conformance.success)\n# 6. Run scale + connectivity test (filename: scale-connectivity.success)\n# 7. Check VFP is in sync with HNS (filename: vfp-state-after-scale.success)\n#\n# NOTE: each step also has a .ran file that is created if the step is run.\n#\n# There is also:\n# - A npm-e2e.ran file that indicates that the npm e2e was run at all\n# - A npm-e2e.success that indicates that all steps succeeded\nnpm_e2e () {\n    local kubeconfigFile=$1\n    if [ -z \"$kubeconfigFile\" ]; then\n        log \"ERROR: kubeconfigFile not set. can't run NPM e2e\"\n        return 1\n    fi\n\n    test -f $kubeconfigFile || {\n        log \"ERROR: kubeconfigFile $kubeconfigFile not found. can't run NPM e2e\"\n        return 1\n    }\n\n    log \"setting up npm e2e test\"\n    anyStepFailed=false\n\n    # make sure there are no previous results\n    log \"cleaning up previous npm e2e results...\"\n    rm *.log *.ran *.success *.failed || true\n    rm -rf npm-hns-state/ || true\n\n    echo \"\" > npm-e2e.ran\n\n    install_npm\n\n    log \"sleeping 8m for NPM to bootup, then verifying VFP tags after bootup...\"\n    sleep 8m\n    verify_vfp_tags_using_npm vfp-state-prior || anyStepFailed=true\n\n    ## NPM cyclonus\n    run_npm_cyclonus && echo \"\" > cyclonus.success || anyStepFailed=true\n\n    log \"sleeping 5m to allow VFP to update tags after cyclonus...\"\n    sleep 5m\n    log \"verifying VFP tags after cyclonus...\"\n    verify_vfp_tags_using_npm vfp-state-after-cyclonus || anyStepFailed=true\n    log \"deleting cyclonus pods...\"\n    kubectl delete ns x y z || true\n\n    ## NPM conformance\n    run_npm_conformance && echo \"\" > conformance.success || anyStepFailed=true\n\n    log \"sleeping 5m to allow VFP to update tags after conformance...\"\n    sleep 5m\n    log \"verifying VFP tags after conformance...\"\n    verify_vfp_tags_using_npm vfp-state-after-conformance || anyStepFailed=true\n    log \"deleting NPM conformance namespaces if they were leftover from a failure...\"\n    kubectl delete ns -l pod-security.kubernetes.io/enforce=baseline || true\n\n    ## NPM scale\n    run_npm_scale $kubeconfigFile && echo \"\" > scale-connectivity.success ||  anyStepFailed=true\n    log \"sleeping 5m to allow VFP to update tags after scale test...\"\n    sleep 5m\n    log \"verifying VFP tags after scale test...\"\n    verify_vfp_tags_using_npm vfp-state-after-scale || anyStepFailed=true\n\n    if [[ $anyStepFailed == false ]]; then\n    \techo \"\" > npm-e2e.success\n    fi\n}\n\ninstall_npm () {\n    ## disable Calico NetPol\n    log \"running helm uninstall on calico (this will remove the tigera-operator and prevent reconciling of the calico-node ClusterRole)...\"\n    helm uninstall calico -n tigera-operator\n    kubectl delete ns tigera-operator\n    log \"disabling Calico NetworkPolicy functionality by removing NetPol permission from calico-node ClusterRole...\"\n    kubectl get clusterrole calico-node -o yaml > original-clusterrole.yaml\n    cat original-clusterrole.yaml | perl -0777 -i.original -pe 's/- apiGroups:\\n  - networking.k8s.io\\n  resources:\\n  - networkpolicies\\n  verbs:\\n  - watch\\n  - list\\n//' > new-clusterrole.yaml\n    originalLineCount=`cat original-clusterrole.yaml | wc -l`\n    newLineCount=`cat new-clusterrole.yaml | wc -l`\n    if [ $originalLineCount != $(($newLineCount + 7)) ]; then\n        # NOTE: this check will only work the first time this script is run, since the original-clusterrole.yaml will be modified\n        log \"ERROR: unable to run NPM e2e. unexpected line count difference between original and new calico-node clusterrole. original: $originalLineCount, new: $newLineCount\"\n        return 1\n    fi\n    kubectl rollout restart ds -n calico-system calico-node-windows\n\n    ## disable scheduling for all but one node for NPM tests, since intra-node connectivity is broken after disabling Calico NetPol\n    kubectl get node -o wide | grep \"Windows Server 2022 Datacenter\" | awk '{print $1}' | tail -n +2 | xargs kubectl cordon\n    kubectl get node -o wide | grep \"Windows Server 2022 Datacenter\" | grep -v SchedulingDisabled | awk '{print $1}' | xargs -n 1 -I {} kubectl label node {} scale-test=true connectivity-test=true\n\n    # sleep for some time to let Calico CNI restart\n    sleep 3m\n\n    ## install Azure NPM\n    log \"installing Azure NPM...\"\n    npmURL=https://raw.githubusercontent.com/Azure/azure-container-networking/0ea4e9ac3d287f7abb15a34a88beb87697fbbcdd/npm/examples/windows/azure-npm-capz.yaml #https://raw.githubusercontent.com/Azure/azure-container-networking/master/npm/examples/windows/azure-npm-capz.yaml\n    kubectl apply -f $npmURL\n\n    # verify VFP tags after NPM boots up\n    # seems like the initial NPM Pods are always deleted and new ones are created (within the first minute of being applied it seems)\n    # sleep for some time to avoid running kubectl wait on pods that get deleted\n    log \"waiting for NPM to start running...\"\n    sleep 3m\n    kubectl wait --for=condition=Ready pod -l k8s-app=azure-npm -n kube-system --timeout=15m\n\n    ## set registry keys for NPM fixes\n    log \"updating registry keys and restarting HNS for NPM fixes...\"\n    npmNode=`kubectl get node -owide | grep \"Windows Server 2022 Datacenter\" | grep -v SchedulingDisabled | grep -v kwok-node | awk '{print $1}' | tail -n 1` || true\n    if [[ -z $npmNode ]]; then\n        log \"ERROR: unable to find uncordoned node for NPM\"\n        return 1\n    fi\n    npmPod=`kubectl get pod -n kube-system -o wide | grep azure-npm-win | grep $npmNode | grep Running | awk '{print $1}'` || true\n    if [[ -z \"$npmPod\" ]]; then\n        log \"ERROR: unable to find running azure-npm-win pod on node $npmNode\"\n        kubectl get pod -n kube-system -o wide\n        kubectl logs -n kube-system -l k8s-app=azure-npm\n        return 1\n    fi\n    cmd=\"reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\hns\\State /v HnsAclUpdateChange /t REG_DWORD /d 1 /f\"\n    cmd=\"$cmd ; reg query HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\hns\\State /v HnsAclUpdateChange\"\n    cmd=\"$cmd ; reg add HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\hns\\State /v HnsNpmRefresh /t REG_DWORD /d 1 /f\"\n    cmd=\"$cmd ; reg query HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Services\\hns\\State /v HnsNpmRefresh\"\n    cmd=\"$cmd ; Restart-Service HNS\"\n    cmd=\"$cmd ; sleep 10\"\n    cmd=\"$cmd ; Restart-Computer\"\n    kubectl exec -n kube-system $npmPod -- powershell.exe \"$cmd\"\n    log \"sleeping 3m to let HNS restart...\"\n    sleep 3m\n\n    ## install long-running pod and restart HNS again (must install after restarting HNS because of a fix in rehydrating Endpoints in one of the registry keys)\n    log \"creating long-runner pod to ensure there's an endpoint for verifying VFP tags...\"\n    kubectl create ns npm-e2e-longrunner\n    kubectl apply -f https://raw.githubusercontent.com/Azure/azure-container-networking/master/npm/examples/windows/long-running-pod-for-capz.yaml\n    sleep 10s\n    log \"making sure long-runner is running\"\n    kubectl wait --for=condition=Ready pod -l app=long-runner -n npm-e2e-longrunner --timeout=15m\n\n    log \"restarting HNS again to make sure Endpoints rehydrate correctly\"\n    kubectl exec -n kube-system $npmPod -- powershell.exe \"Restart-Service HNS\"\n\n    log \"sleeping 3m to let HNS restart...\"\n    sleep 3m\n\n    log \"making sure NPM and long-runner are running...\"\n    kubectl wait --for=condition=Ready pod -l k8s-app=azure-npm -n kube-system --timeout=15m\n    kubectl wait --for=condition=Ready pod -l app=long-runner -n npm-e2e-longrunner --timeout=15m\n}\n\nverify_vfp_tags_using_npm () {\n    local ranFilename=$1\n    if [[ -z $ranFilename ]]; then\n        log \"ERROR: need a filename passed as an argument to verify_vfp_tags_using_npm\"\n        return 1\n    fi\n\n    log \"verifying VFP tags are equal to HNS SetPolicies...\"\n    npmNode=`kubectl get node -owide | grep \"Windows Server 2022 Datacenter\" | grep -v SchedulingDisabled | grep -v kwok-node | awk '{print $1}' | tail -n 1` || true\n    if [[ -z $npmNode ]]; then\n        log \"ERROR: unable to find uncordoned node for NPM\"\n        return 1\n    fi\n    npmPod=`kubectl get pod -n kube-system -o wide | grep azure-npm-win | grep $npmNode | grep Running | awk '{print $1}'` || true\n    if [[ -z \"$npmPod\" ]]; then\n        log \"ERROR: unable to find running azure-npm-win pod on node $npmNode\"\n        kubectl get pod -n kube-system -o wide\n        kubectl logs -n kube-system -l k8s-app=azure-npm\n        return 1\n    fi\n\n    onNodeIPs=() ; for ip in `kubectl get pod -owide -A  | grep $npmNode | grep -oP \"\\d+\\.\\d+\\.\\d+\\.\\d+\" | sort | uniq`; do onNodeIPs+=($ip); done\n    matchString=\"\" ; for ip in ${onNodeIPs[@]}; do matchString+=\" \\\"${ip}\\\"\"; done\n    matchString=`echo $matchString | tr ' ' ','`\n    log \"using matchString: $matchString\"\n    ipsetCount=`kubectl exec -n kube-system $npmPod -- powershell.exe \"(Get-HNSNetwork | ? Name -Like Calico).Policies | convertto-json  > setpols.txt ; (type .\\setpols.txt | select-string '\\\"PolicyType\\\":  \\\"IPSET\\\"').count\" | tr -d '\\r'`\n    log \"HNS IPSET count: $ipsetCount\"\n    kubectl exec -n kube-system $npmPod -- powershell.exe 'echo \"attempting to delete previous results if they exist\" ; Remove-Item -path vfptags -recurse ; mkdir vfptags'\n    kubectl exec -n kube-system $npmPod -- powershell.exe '$endpoints = (Get-HnsEndpoint | ? IPAddress -In '\"$matchString\"').Id ; foreach ($port in $endpoints) { vfpctrl /port $port /list-tag > vfptags\\$port.txt ; (type vfptags\\$port.txt | select-string -context 2 \"TAG :\").count }' > vfp-tag-counts.txt\n\n    hadEndpoints=false\n    hadFailure=false\n    for count in `cat vfp-tag-counts.txt | xargs -n 1 echo`; do\n        hadEndpoints=true\n        count=`echo $count | tr -d '\\r'`\n        log \"VFP tag count: $count\"\n        if [[ $count != $ipsetCount ]]; then\n            log \"WARNING: VFP tag count $count does not match HNS IPSET count $ipsetCount\"\n            hadFailure=true\n        fi\n    done\n\n    echo \"\" > rehydration.ran\n    if [[ $hadEndpoints == false ]]; then\n        log \"ERROR: no Endpoints found in HNS for node IPs $matchString on node $npmNode. Rehydration of Endpoints likely failed\"\n\techo \"\" > rehydration.failed\n        return 1\n    fi\n    \n    echo \"\" > $ranFilename.ran\n    if [[ $hadFailure == true ]]; then\n        log \"ERROR: VFP tags are inconsistent with HNS SetPolicies\"\n        capture_npm_hns_state\n        return 1\n    fi\n\n    echo \"\" > $ranFilename.success\n}\n\n# results in a file called npm-hns-state.zip\ncapture_npm_hns_state () {\n    if [[ -f npm-hns-state.zip ]]; then\n        log \"WARNING: not capturing NPM HNS state since state was previously captured\"\t\n        return 0\t\n    fi\n\n    log \"capturing NPM HNS state...\"\n    kubectl get pod -owide -A\n    mkdir npm-hns-state\n    cd npm-hns-state\n    curl -LO https://raw.githubusercontent.com/Azure/azure-container-networking/master/debug/windows/npm/win-debug.sh\n    chmod u+x ./win-debug.sh\n    curl -LO https://raw.githubusercontent.com/Azure/azure-container-networking/master/debug/windows/npm/pod_exec.ps1\n    ./win-debug.sh\n    cd ..\n    zip -9qr npm-hns-state.zip npm-hns-state\n    # to unzip:\n    # unzip npm-hns-state.zip -d npm-hns-state\n}\n\n# currently takes ~3 hours to run\n# e.g. 19:37:05 to 22:32:44 and 19:16:18 to 22:29:13\nrun_npm_conformance () {\n    ## install NPM e2e binary\n    log \"ensuring NPM e2e binary is installed\"\n    rc=0; test -f npm-e2e.test || rc=$?\n    if [[ $rc == 0 ]]; then\n        log \"NPM e2e binary found, skipping install\"\n    else\n        log \"NPM e2e binary not found, installing...\"\n        test -d npm-kubernetes/ && rm -rf npm-kubernetes/ || true\n        mkdir npm-kubernetes\n        cd npm-kubernetes\n        # NOTE: if this is not downloaded every run, then probably need to sleep before the VFP tag verification\n        git clone https://github.com/huntergregory/kubernetes.git --depth=1 --branch=quit-on-failure\n        cd kubernetes\n        make WHAT=test/e2e/e2e.test\n        cd ../..\n        mv npm-kubernetes/kubernetes/_output/local/bin/linux/amd64/e2e.test ./npm-e2e.test\n        rm -rf npm-kubernetes/\n    fi\n\n    log \"beginning npm conformance test...\"\n\n    toRun=\"NetworkPolicy\"\n\n    nomatch1=\"should enforce policy based on PodSelector or NamespaceSelector\"\n    nomatch2=\"should enforce policy based on NamespaceSelector with MatchExpressions using default ns label\"\n    nomatch3=\"should enforce policy based on PodSelector and NamespaceSelector\"\n    nomatch4=\"should enforce policy based on Multiple PodSelectors and NamespaceSelectors\"\n    cidrExcept1=\"should ensure an IP overlapping both IPBlock.CIDR and IPBlock.Except is allowed\"\n    cidrExcept2=\"should enforce except clause while egress access to server in CIDR block\"\n    namedPorts=\"named port\"\n    wrongK8sVersion=\"Netpol API\"\n    toSkip=\"\\[LinuxOnly\\]|$nomatch1|$nomatch2|$nomatch3|$nomatch4|$cidrExcept1|$cidrExcept2|$namedPorts|$wrongK8sVersion|SCTP\"\n    \n    # to debug with one test case, uncomment this\n    # toRun=\"NetworkPolicy API should support creating NetworkPolicy API operations\"\n\n    echo \"\" > conformance.ran\n    KUBERNETES_SERVICE_PORT=443 ./npm-e2e.test \\\n        --provider=skeleton \\\n        --ginkgo.noColor \\\n        --ginkgo.focus=\"$toRun\" \\\n        --ginkgo.skip=\"$toSkip\" \\\n        --allowed-not-ready-nodes=1 \\\n        --node-os-distro=\"windows\" \\\n        --disable-log-dump \\\n        --ginkgo.progress=true \\\n        --ginkgo.slowSpecThreshold=120.0 \\\n        --ginkgo.flakeAttempts=0 \\\n        --ginkgo.trace=true \\\n        --ginkgo.v=true \\\n        --dump-logs-on-failure=true \\\n        --report-dir=\"${ARTIFACTS}\" \\\n        --prepull-images=true \\\n        --v=5 \"${ADDITIONAL_E2E_ARGS[@]}\" | tee npm-e2e.log || true\n\n    # grep \"FAIL: unable to initialize resources: after 10 tries, 2 HTTP servers are not ready\n\n    log \"finished npm conformance test\"\n    ## report if there's a failure\n    rc=0; cat npm-e2e.log | grep '\"failed\":1' > /dev/null 2>&1 || rc=$?\n    if [ $rc -eq 0 ]; then\n        log \"ERROR: found failure in npm e2e test log\"\n        capture_npm_hns_state\n        return 1\n    fi\n}\n\n# currently takes ~3.5 hours to run\n# e.g. 20:49:05 to 00:21:12\nrun_npm_cyclonus () {\n    log \"installing cyclonus binary...\"\n    curl -fsSL github.com/mattfenwick/cyclonus/releases/latest/download/cyclonus_linux_amd64.tar.gz | tar -zxv\n\n    log \"beginning npm cyclonus test...\"\n    echo \"\" > cyclonus.ran\n    ./cyclonus_linux_amd64/cyclonus generate \\\n        --junit-results-file=cyclonus.xml \\\n        --fail-fast \\\n        --noisy=true \\\n        --retries=7 \\\n        --ignore-loopback=true \\\n        --perturbation-wait-seconds=20 \\\n        --pod-creation-timeout-seconds=480 \\\n        --job-timeout-seconds=15 \\\n        --server-protocol=TCP,UDP \\\n        --exclude sctp,named-port,ip-block-with-except,multi-peer,upstream-e2e,example,end-port,namespaces-by-default-label,update-policy | tee npm-cyclonus.log || true\n\n    # for debugging with a smaller set of tests, use this as the last line instead\n        # --exclude sctp,named-port,ip-block-with-except,multi-peer,upstream-e2e,example,end-port,namespaces-by-default-label,update-policy,all-namespaces,all-pods,allow-all,any-peer,any-port,any-port-protocol,deny-all,ip-block-no-except,multi-port/protocol,namespaces-by-label,numbered-port,pathological,peer-ipblock,peer-pods,pods-by-label,policy-namespace,port,protocol,rule,tcp,udp --include conflict,direction,egress,ingress,miscellaneous  | tee npm-cyclonus.log || true\n\n    rc=0; cat npm-cyclonus.log | grep \"failed\" > /dev/null 2>&1 || rc=$?\n    if [[ $rc == 0 ]]; then\n        echo \"ERROR: failures encountered in npm cyclonus test\"\n        capture_npm_hns_state\n        return 1\n    fi\n\n    rc=0; cat npm-cyclonus.log | grep \"SummaryTable:\" > /dev/null 2>&1 || rc=$?\n    if [[ $rc != 0 ]]; then\n        log \"ERROR: npm cyclonus test did not finish for some reason\"\n        capture_npm_hns_state\n        return 1\n    fi\n}\n\nrun_npm_scale () {\n    local kubeconfigFile=$1\n\n    log \"beginning npm scale test with kubeconfig [$kubeconfigFile]...\"\n\n    rm -rf azure-container-networking/ || true\n    git clone https://github.com/Azure/azure-container-networking.git --depth=1 --branch=master\n\n    cd azure-container-networking/test/scale/\n\n    chmod u+x test-scale.sh\n    cd connectivity/\n    chmod u+x test-connectivity.sh\n    cd ../\n\n    # run kwok\n    kwok --kubeconfig=$kubeconfigFile \\\n        --cidr=155.0.0.0/16 \\\n        --node-ip=155.0.0.1 \\\n        --manage-all-nodes=false \\\n        --manage-nodes-with-annotation-selector=kwok.x-k8s.io/node=fake \\\n        --manage-nodes-with-label-selector= \\\n        --disregard-status-with-annotation-selector=kwok.x-k8s.io/status=custom \\\n        --disregard-status-with-label-selector= > ../../../kwok.log &\n    kwok_pid=$!\n\n    # exact counts output from script\n    # Pod Counts:\n    # - 25 fake Pods\n    # - 5 real Pods\n    # HNS Counts:\n    # - number of ACLs per Pod Endpoint: 6 (6*numNetworkPolicies)\n    # - number of SetPolicies: ~100 (2*numUniqueLabelsPerPod*numFakePods)\n    # - max IPs per SetPolicy: number of total Pods\n    ./test-scale.sh --max-kwok-pods-per-node=50 \\\n        --num-kwok-deployments=5 \\\n        --num-kwok-replicas=5 \\\n        --max-real-pods-per-node=30 \\\n        --num-real-deployments=5 \\\n        --num-real-replicas=1 \\\n        --num-network-policies=1 \\\n        --num-unapplied-network-policies=3 \\\n        --num-unique-labels-per-pod=2 \\\n        --num-unique-labels-per-deployment=2 \\\n        --num-shared-labels-per-pod=10 \\\n        --delete-labels \\\n        --delete-labels-interval=60 \\\n        --delete-labels-times=1 \\\n        --delete-netpols \\\n        --delete-netpols-interval=60 \\\n        --delete-netpols-times=1 \\\n        --delete-kwok-pods=1 \\\n        --delete-real-pods=1 \\\n        --delete-pods-interval=120 \\\n        --delete-pods-times=1 | tee ../../../npm-scale.log || true\n\n    rc=0; cat ../../../npm-scale.log | grep \"FINISHED\" > /dev/null 2>&1 || rc=$?\n    if [[ $rc != 0 ]]; then\n        log \"ERROR: npm scale test did not properly scale\"\n        kill $kwok_pid\n        cd ../../../\n        return 1\n    fi\n\n    log \"beginning npm scale connectivity test...\"\n\n    cd connectivity/\n\n    minutesToWaitForInitialConnectivity=30\n    minutesToWaitAfterAddingNetPol=10\n    echo \"\" > ../../../../scale-connectivity.ran\n    ./test-connectivity.sh --num-scale-pods-to-verify=all --max-wait-for-initial-connectivity=$((60*minutesToWaitForInitialConnectivity)) --max-wait-after-adding-netpol=$((60*minutesToWaitAfterAddingNetPol)) | tee ../../../../npm-scale-connectivity.log || true\n\n    cd ../../../../\n    rc=0; cat npm-scale-connectivity.log | grep \"FINISHED\" > /dev/null 2>&1 || rc=$?\n    if [[ $rc != 0 ]]; then\n        log \"ERROR: npm scale test connectivity failed\"\n        kill $kwok_pid\n        capture_npm_hns_state\n        return 1\n    fi\n\n    echo \"\" > scale-connectivity.success\n    kill $kwok_pid\n}\n", "num_lines": 437}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "LOG_FILE=cyclonus-$CLUSTER_NAME\n\n# curl -fsSL github.com/mattfenwick/cyclonus/releases/latest/download/cyclonus_linux_amd64.tar.gz | tar -zxv\n# ./cyclonus_linux_amd64/cyclonus generate \\\n\n# this branch has double the amount of workers\ngit clone https://github.com/huntergregory/cyclonus.git --branch=slowness --depth=1\ncd cyclonus\nmake cyclonus\ncmd/cyclonus/cyclonus generate \\\n    --noisy=true \\\n    --retries=7 \\\n    --ignore-loopback=true \\\n    --cleanup-namespaces=true \\\n    --perturbation-wait-seconds=17 \\\n    --pod-creation-timeout-seconds=480 \\\n    --job-timeout-seconds=5 \\\n    --server-protocol=TCP,UDP \\\n    --exclude sctp,named-port,ip-block-with-except,multi-peer,upstream-e2e,example,end-port,namespaces-by-default-label,update-policy | tee $LOG_FILE\n\n# might need to redirect to /dev/null 2>&1 instead of just grepping with -q to avoid \"cat: write error: Broken pipe\"\nrc=999\ncat $LOG_FILE | grep \"SummaryTable:\" > /dev/null 2>&1 && rc=$?\necho $rc\nif [ $rc -ne 0 ]; then\n    echo \"FAILING because cyclonus tests did not complete\"\n    exit 2\nfi\n\nrc=0\ncat $LOG_FILE | grep \"failed\" > /dev/null 2>&1 || rc=$?\necho $rc\nif [ $rc -eq 0 ]; then\n    echo \"FAILING because cyclonus completed but failures detected\"\n    exit 3\nfi\n", "num_lines": 37}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -eo pipefail\nset -xv\n\nif [ -z \"$1\" == \"windows\"]\n  then\n    cyclonusProfile=\"./install-cyclonus-windows.yaml\"\n  else\n    cyclonusProfile=\"./install-cyclonus.yaml\"\nfi\n\n\nif [ -z \"$1\" ]\n  then\n    echo \"Running with default profile: $cyclonusProfile\"\nelif [[ $1 == \"extended\" ]]; \nthen\n    # extended will exclude SCTP and will run 214 testcases with cyclonus \n    cyclonusProfile=\"./install-cyclonus-exclude-sctp.yaml\"\n    echo \"Running with exclude SCTP profile with 214 testcases: $cyclonusProfile\"\nfi\n\necho \"Running with cyclonus profile: $cyclonusProfile\"\nkubectl delete --ignore-not-found=true clusterrolebinding cyclonus \nkubectl delete --ignore-not-found=true sa cyclonus -n kube-system\nkubectl delete --ignore-not-found=true -f $cyclonusProfile\nkubectl delete --ignore-not-found=true ns x y z\n\nsleep 5\n\n# set up cyclonus\nkubectl create clusterrolebinding cyclonus --clusterrole=cluster-admin --serviceaccount=kube-system:cyclonus\nkubectl create sa cyclonus -n kube-system\nkubectl create -f $cyclonusProfile\n\nsleep 5\n\ntime kubectl wait --for=condition=ready --timeout=5m pod -n kube-system -l job-name=cyclonus\n\n#!/bin/bash\n{ kubectl logs -f -n kube-system job.batch/cyclonus;  } &\n{ time kubectl wait --for=condition=completed --timeout=600m pod -n kube-system -l job-name=cyclonus;  } &\nwait -n\npkill -P $$\necho done\n\n# grab the job logs\nLOG_FILE=cyclonus-test.txt\nkubectl logs -n kube-system job.batch/cyclonus | tee \"$LOG_FILE\"\ncat \"$LOG_FILE\"\n\nkubectl delete --ignore-not-found=true clusterrolebinding cyclonus \nkubectl delete --ignore-not-found=true sa cyclonus -n kube-system\nkubectl delete --ignore-not-found=true -f $cyclonusProfile\n\n# might need to redirect to /dev/null 2>&1 instead of just grepping with -q to avoid \"cat: write error: Broken pipe\"\nrc=999\ncat $LOG_FILE | grep \"SummaryTable:\" > /dev/null 2>&1 && rc=$?\necho $rc\nif [ $rc -ne 0 ]; then\n    echo \"FAILING because cyclonus tests did not complete\"\n    exit 2\nfi\n\nrc=0\ncat $LOG_FILE | grep \"failed\" > /dev/null 2>&1 || rc=$?\necho $rc\nif [ $rc -eq 0 ]; then\n    echo \"FAILING because cyclonus completed but failures detected\"\n    exit 3\nfi\n", "num_lines": 73}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nMASTER_JSON=$(pwd)/master.json\nEXTERNAL_JSON=$(pwd)/external.json\n\nkubectl create namespace kubemark --kubeconfig=$EXTERNAL_JSON\nkubectl create configmap node-configmap -n kubemark --from-literal=content.type=\"test-cluster\" --kubeconfig=$EXTERNAL_JSON\nkubectl create secret generic kubeconfig --type=Opaque --namespace=kubemark --from-file=kubelet.kubeconfig=$MASTER_JSON --from-file=kubeproxy.kubeconfig=$MASTER_JSON --kubeconfig=$EXTERNAL_JSON", "num_lines": 8}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nargc=$#\n\nif [[ $argc -ne 1 ]]\nthen \n\techo \"cmd [1 (create hollownodes), 2 (clean-up hollownodes), 3 (list hollownodes info), 4 (delete label from hollow-node)]\"\n\texit -1\nfi\n\n\nMASTER_JSON=$(pwd)/master.json\nEXTERNAL_JSON=$(pwd)/external.json\n\ncmd=$1\ncase $cmd in\n\"1\")\n\techo \"Deploy hollow nodes on external cluster\"\n\t# 1. Deploy \"hollow-node\" pods on external K8s cluster\n    kubectl apply -f ./hollow-node.yaml --kubeconfig=$EXTERNAL_JSON\n\t# 2. check whether all \"hollow-node\" pods are running (i.e., Running status) on external K8s cluster\n    watch -n1 kubectl get pods -n kubemark --kubeconfig=$EXTERNAL_JSON\n\t# 3. check whether all \"hollow-node\" pods are registed as \"hollow-node\" nodes on master K8s cluster\n    watch -n1 kubectl get nodes -l \"hollow-node=\" --kubeconfig=$MASTER_JSON\n\t;;\n\"2\")\n\techo \"Delete hollow nodes on external cluster and clean-up them on kubemark cluster\"\n\t# 1. Delete \"hollow-node\" pods on external K8s cluster\n    kubectl delete -f ./hollow-node.yaml --kubeconfig=$EXTERNAL_JSON\n\t# 2. Delete \"hollow-node\" nodes from master K8s cluster\n\t# You may need to run below command multiple times since the node is removed when its status is \"NotReady\"\n    kubectl get nodes --kubeconfig=$MASTER_JSON | grep NotReady | awk '{print $1}' |  xargs kubectl delete node --kubeconfig=$MASTER_JSON\n\t;;\n\"3\")\n\techo \"Get hollow nodes information on kubemark cluster\"\n\tkubectl get nodes -o wide --kubeconfig=$MASTER_JSON\n\techo \"\"\n\tkubectl get nodes -o wide --show-labels --kubeconfig=$MASTER_JSON | grep \"hollow-node\"\n\t;;\n\"4\")\n\t# Need to delete \"kubernetes.io/os\" label not to deploy add-on pods \n\t# (e.g., azure-cni-networkmonitor-cfmgs, csi-secrets-store-cn9dp, kube-proxy-r9lpq, etc)\n\t# Something does not work.. Cannot delete \"kubernetes.io/os\" label on hollownode \n\tnodes=$(kubectl get nodes -l hollow-node= --kubeconfig=$MASTER_JSON | grep hollow | awk '{print $1}')\n\tfor node in ${nodes[@]}\n\tdo\n\t\techo $node\n\t\tkubectl label node $node kubernetes.io/os- --kubeconfig=$MASTER_JSON\n\tdone\n\tkubectl get nodes -l hollow-node= --show-labels --kubeconfig=$MASTER_JSON\n\t;;\n*)\n\techo \"Unknown command :\", $cmd\n\t;;\nesac \n\n", "num_lines": 57}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nargc=$#\n\nif [[ $argc -ne 1 ]]\nthen \n\techo \"cmd [1 (deploy npm on agent), 2 (delete npm), 3 (print npm log), 4 (connect to npm console), 5 [top npm]]\"\n\texit -1\nfi\n\nexport KUBECONFIG=$(pwd)\"/master.json\"\n\ncmd=$1\ncase $cmd in\n\"1\")\n\techo \"Deploy NPM pod on agent of master K8s cluster\"\n\tkubectl apply -f azure-npm-with-kubemark.yaml \n\t;;\t\n\"2\")\n\techo \"Deploy NPM pod on agent of master K8s cluster\"\n\tkubectl delete -f azure-npm-with-kubemark.yaml\n\t;;\t\n\"3\")\n\tNPM_POD=$(kubectl get pods -l k8s-app=azure-npm -n kube-system -o wide --kubeconfig=$MASTER_JSON | grep agentpool | awk '{print $1}')\n\tkubectl logs -f $NPM_POD -n kube-system \n\t;;\t\n\"4\")\n\tNPM_POD=$(kubectl get pods -l k8s-app=azure-npm -n kube-system -o wide --kubeconfig=$MASTER_JSON | grep agentpool | awk '{print $1}')\n\tkubectl exec -it $NPM_POD -n kube-system bash\n\t;;\n\"5\") \n\twatch -n1 kubectl top  pod -l k8s-app=azure-npm -n kube-system \n\t;;\n*)\n\techo \"Unknown command :\", $cmd\n\t;;\nesac \n", "num_lines": 37}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nargc=$#\n\nif [[ $argc -ne 1 ]]\nthen \n\techo \"cmd [1 (create pods), 2 (delete pods), 3 (list pod), 4 (list deployment)]\"\n\texit -1\nfi\n\n# Deploy pods on hollownodes managed by master cluster. \nexport KUBECONFIG=$(pwd)/master.json\n\ncmd=$1\ncase $cmd in\n\"1\")\n\techo \"Deploy pods on hollow nodes of master K8s cluster\"\n\tfor index in {1..10}\n\tdo\n\t\tkubectl apply -f deployments/deploy$index.yaml &\n\tdone\n\t;;\n\"2\")\n\techo \"Delete pods from hollow nodes of master K8s cluster\"\n\tfor index in {1..10}\n\tdo\n\t\tkubectl delete -f deployments/deploy$index.yaml &\n\tdone\n\t;;\n\"3\")\n\techo \"list pods on master K8s cluster\"\n\tkubectl get pods --all-namespaces -o wide\n\t;;\t\n\"4\")\n\techo \"list deployment on master K8s cluster\"\n\twatch -n1 kubectl get deployment --all-namespaces -o wide\n\t;;\t\n*)\n\techo \"Unknown command :\", $cmd\n\t;;\nesac \n", "num_lines": 41}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "kubectl run wget -it --rm --image busybox --restart Never -- wget --timeout=3 --header=Metadata:true \"http://168.63.129.16/machine/plugins?comp=nmagent&type=getinterfaceinfov1\"\nif [ $? -eq 0 ]; then\n    echo \"wireserver connectivity expected to fail but succeeded\"\n    exit 1\nfi\n\nkubectl run wget -it --rm --image busybox --restart Never -- wget --timeout=3 --header=Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2021-02-01\"\nif [ $? -ne 0 ]; then\n    echo \"metadata server connectivity expected to succeed but failed\"\nfi", "num_lines": 10}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "KWOK_REPO=kubernetes-sigs/kwok\nKWOK_LATEST_RELEASE=$(curl \"https://api.github.com/repos/${KWOK_REPO}/releases/latest\" | jq -r '.tag_name')\nwget -O kwok -c \"https://github.com/kubernetes-sigs/kwok/releases/download/${KWOK_LATEST_RELEASE}/kwok-$(go env GOOS)-$(go env GOARCH)\"\nchmod +x kwok\nsudo mv kwok /usr/local/bin/kwok\n", "num_lines": 6}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "###############################################################\n# Schedule kwok nodes/pods and maintain kwok node heartbeats. #\n###############################################################\n# can pass kubeconfig as first arg\nif [[ -z $1 ]]; then\n    kubeconfigFile=~/.kube/config\nelse\n    kubeconfigFile=$1\nfi\necho \"using kubeconfig $kubeconfigFile\"\n\nwhich kwok || {\n    echo \"ERROR: kwok not found. Install via ./install-kwok.sh\"\n    exit 1\n}\n\nset -x\nkwok --kubeconfig $kubeconfigFile \\\n    --cidr=155.0.0.0/16 \\\n    --node-ip=155.0.0.1 \\\n    --manage-all-nodes=false \\\n    --manage-nodes-with-annotation-selector=kwok.x-k8s.io/node=fake \\\n    --manage-nodes-with-label-selector= \\\n    --disregard-status-with-annotation-selector=kwok.x-k8s.io/status=custom \\\n    --disregard-status-with-label-selector=\n", "num_lines": 26}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#exit on error\nset -e\n\nprintHelp() {\n    cat <<EOF\n./test-scale.sh --max-kwok-pods-per-node=<int> --num-kwok-deployments=<int> --num-kwok-replicas=<int> --max-real-pods-per-node=<int> --num-real-deployments=<int> --num-real-replicas=<int> --num-network-policies=<int> --num-unapplied-network-policies=<int> --num-unique-labels-per-pod=<int> --num-unique-labels-per-deployment=<int> --num-shared-labels-per-pod=<int> [--kubeconfig=<path>] [--kubectl-binary=<path>] [--restart-npm] [--debug-exit-after-print-counts] [--debug-exit-after-generation]\n(more optional parameters at end of this message)\n\nScales the number of Pods, Pod labels, and NetworkPolicies in a cluster.\nUses KWOK to create fake nodes and fake pods as needed.\nCan also schedule real Pods. It will NOT scale real nodes.\n\nUSAGE:\n1. Create AKS cluster with --uptime-sla and create any nodepools\n2. If making KWOK Pods, run `run-kwok.sh` in the background\n3. Label node(s) to schedule real Pods: kubectl label node <name> scale-test=true\n4. Run this script with args like number of Deployments, replicas, and NetworkPolicies\n\nSPECIAL NOTES:\n1. Check notes on --max-real-pods-per-node\n2. For Cilium, check notes on --num-unique-labels-per-pod\n3. Check restrictions on --num-shared-labels-per-pod\n\nREQUIRED PARAMETERS:\n    --max-kwok-pods-per-node              limit for fake kwok nodes. 50 works. Not sure if there's a limit\n    --num-kwok-deployments                number of fake deployments\n    --num-kwok-replicas                   per fake deployment\n    --max-real-pods-per-node              check your VMs' --max-pod capacity and set maxRealPodsPerNode accordingly (leave wiggle room for system Pods)\n    --num-real-deployments                deployments scheduled on nodes labeled with scale-test=true\n    --num-real-replicas                   per deployment\n    --num-network-policies                NetPols applied to every Pod\n    --num-unapplied-network-policies      NetPols that do not target any Pods\n    --num-unique-labels-per-pod           creates labels specific to each Pod. Creates numTotalPods*numUniqueLabelsPerPod distinct labels. In Cilium, a value >= 1 results in every Pod having a unique identity (not recommended for scale)\n    --num-unique-labels-per-deployment    create labels shared between replicas of a deployment. Creates numTotalDeployments*numUniqueLabelsPerDeployment distinct labels\n    --num-shared-labels-per-pod           create labels shared between all Pods. Creates numSharedLabelsPerPod distinct labels. Must be >= 3 if numNetworkPolicies > 0 because of the way we generate network policies\n\nOPTIONAL PARAMETERS:\n    --kubeconfig=<path>                   path to kubeconfig file\n    --kubectl-binary=<path>               path to kubectl binary. Default is kubectl\n    --restart-npm                         make sure NPM exists and restart it before running scale test\n    --debug-exit-after-print-counts       skip scale test. Just print out counts of things to be created and counts of IPSets/ACLs that NPM would create\n    --num-real-services                   cluster ip service for the real deployments scheduled. Each svc will point to the respective deployment(having <num-real-replicas> pods) Default is 0\n    --debug-exit-after-generation         skip scale test. Exit after generating templates\n\nOPTIONAL PARAMETERS TO TEST DELETION:\n    --sleep-after-creation=<int>          seconds to sleep after creating everything. Default is 0\n    --delete-kwok-pods=<int>              delete and readd the specified number of fake Pods\n    --delete-real-pods=<int>              delete and readd the specified number of real Pods\n    --delete-pods-interval=<int>          seconds to wait after deleting Pods. Default is 60\n    --delete-pods-times=<int>             number of times to delete and readd. Default is 1\n    --delete-labels                       delete and readd shared labels from all Pods\n    --delete-labels-interval=<int>        seconds to wait after deleting or readding. Default is 60\n    --delete-labels-times=<int>           number of times to delete and readd. Default is 1\n    --delete-netpols                      delete and readd all NetworkPolicies\n    --delete-netpols-interval=<int>       seconds to wait after deleting or readding. Default is 60\n    --delete-netpols-times=<int>          number of times to delete and readd. Default is 1\nEOF\n}\n\n## PARAMETERS\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        -h|--help)\n            printHelp\n            exit 0\n            ;;\n        --max-kwok-pods-per-node=*)\n            maxKwokPodsPerNode=\"${1#*=}\"\n            ;;\n        --num-kwok-deployments=*)\n            numKwokDeployments=\"${1#*=}\"\n            ;;\n        --num-kwok-replicas=*)\n            numKwokReplicas=\"${1#*=}\"\n            ;;\n        --max-real-pods-per-node=*)\n            maxRealPodsPerNode=\"${1#*=}\"\n            ;;\n        --num-real-deployments=*)\n            numRealDeployments=\"${1#*=}\"\n            ;;\n        --num-real-replicas=*)\n            numRealReplicas=\"${1#*=}\"\n            ;;\n        --num-real-services=*)\n            numRealServices=\"${1#*=}\"\n            ;;\n        --num-network-policies=*)\n            numNetworkPolicies=\"${1#*=}\"\n            ;;\n        --num-unapplied-network-policies=*)\n            numUnappliedNetworkPolicies=\"${1#*=}\"\n            ;;\n        --num-unique-labels-per-pod=*)\n            numUniqueLabelsPerPod=\"${1#*=}\"\n            ;;\n        --num-unique-labels-per-deployment=*)\n            numUniqueLabelsPerDeployment=\"${1#*=}\"\n            ;;\n        --num-shared-labels-per-pod=*)\n            numSharedLabelsPerPod=\"${1#*=}\"\n            ;;\n        --kubeconfig=*)\n            file=${1#*=}\n            KUBECONFIG_ARG=\"--kubeconfig $file\"\n            test -f $file || { \n                echo \"ERROR: kubeconfig not found: [$file]\"\n                exit 1\n            }\n            echo \"using kubeconfig: $file\"\n            ;;\n        --kubectl-binary=*)\n            KUBECTL=${1#*=}\n            test -f $KUBECTL || { \n                echo \"ERROR: kubectl binary not found: [$KUBECTL]\"\n                exit 1\n            }\n            echo \"using kubectl binary: $KUBECTL\"\n            ;;\n        --restart-npm)\n            USING_NPM=true\n            ;;\n        --debug-exit-after-print-counts)\n            DEBUG_EXIT_AFTER_PRINT_COUNTS=true\n            ;;\n        --debug-exit-after-generation)\n            DEBUG_EXIT_AFTER_GENERATION=true\n            ;;\n        --sleep-after-creation=*)\n            sleepAfterCreation=\"${1#*=}\"\n            ;;\n        --delete-kwok-pods=*)\n            deleteKwokPods=\"${1#*=}\"\n            ;;\n        --delete-real-pods=*)\n            deleteRealPods=\"${1#*=}\"\n            ;;\n        --delete-pods-interval=*)\n            deletePodsInterval=\"${1#*=}\"\n            ;;\n        --delete-pods-times=*)\n            deletePodsTimes=\"${1#*=}\"\n            ;;\n        --delete-labels)\n            deleteLabels=true\n            ;;\n        --delete-labels-interval=*)\n            deleteLabelsInterval=\"${1#*=}\"\n            ;;\n        --delete-labels-times=*)\n            deleteLabelsTimes=\"${1#*=}\"\n            ;;\n        --delete-netpols)\n            deleteNetpols=true\n            ;;\n        --delete-netpols-interval=*)\n            deleteNetpolsInterval=\"${1#*=}\"\n            ;;\n        --delete-netpols-times=*)\n            deleteNetpolsTimes=\"${1#*=}\"\n            ;;\n        *)\n            echo \"ERROR: unknown parameter $1. Make sure you're using '--key=value' for parameters with values\"\n            exit 1\n            ;;\n    esac\n    shift\ndone\n\nif [[ -z $maxKwokPodsPerNode || -z $numKwokDeployments || -z $numKwokReplicas || -z $maxRealPodsPerNode || -z $numRealDeployments || -z $numRealReplicas || -z $numNetworkPolicies || -z $numUnappliedNetworkPolicies || -z $numUniqueLabelsPerPod || -z $numUniqueLabelsPerDeployment || -z $numSharedLabelsPerPod ]]; then\n    echo \"ERROR: missing required parameter. Check --help for usage\"\n    exit 1\nfi\n\nif [[ $numNetworkPolicies -gt 0 && $numSharedLabelsPerPod -lt 3 ]]; then\n    echo \"ERROR: numSharedLabelsPerPod must be >= 3 if numNetworkPolicies > 0 because of the way we generate network policies\"\n    exit 1\nfi\n\nif [[ -z $KUBECTL ]]; then\n    KUBECTL=\"kubectl\"\nfi\nif [[ -z $numRealServices ]]; then numRealServices=0; fi\nif [[ -z $deletePodsInterval ]]; then deletePodsInterval=60; fi\nif [[ -z $deletePodsTimes ]]; then deletePodsTimes=1; fi\nif [[ -z $deleteLabelsInterval ]]; then deleteLabelsInterval=60; fi\nif [[ -z $deleteLabelsTimes ]]; then deleteLabelsTimes=1; fi\nif [[ -z $deleteNetpolsInterval ]]; then deleteNetpolsInterval=60; fi\nif [[ -z $deleteNetpolsTimes ]]; then deleteNetpolsTimes=1; fi\n\n## CALCULATIONS\nnumKwokPods=$(( $numKwokDeployments * $numKwokReplicas ))\nnumKwokNodes=$(( ($numKwokPods + $maxKwokPodsPerNode - 1) / $maxKwokPodsPerNode))\nnumRealPods=$(( $numRealDeployments * $numRealReplicas ))\nnumRealNodesRequired=$(( ($numRealPods + $maxRealPodsPerNode - 1) / $maxRealPodsPerNode))\nnumTotalPods=$(( $numKwokPods + $numRealPods ))\n\n## NPM CALCULATIONS\n# unique to templates/networkpolicy.yaml\nnumACLsAddedByNPM=$(( 6 * $numNetworkPolicies ))\n# IPSet/member counts can be slight underestimates if there are more than one template-hash labels\n# 4 basic IPSets are [ns-scale-test,kubernetes.io/metadata.name:scale-test,template-hash:xxxx,app:scale-test]\n# for deployments, have [is-real, is-real:true, is-kwok, is-kwok:true]\n# for unapplied netpols, have [non-existent-key, non-existent-key:val]\nextraIPSets=0\nif [[ $numUnappliedNetworkPolicies -gt 0 ]]; then\n    extraIPSets=$(( $extraIPSets + 2 ))\nfi\nif [[ $numKwokPods -gt 0 ]]; then\n    extraIPSets=$(( $extraIPSets + 2 ))\nfi\nif [[ $numRealPods -gt 0 ]]; then\n    extraIPSets=$(( $extraIPSets + 2 ))\nfi\nif [[ $numRealServices -gt 0 ]]; then\n    extraIPSets=$(( $extraIPSets + $numRealDeployments ))\nfi\nnumIPSetsAddedByNPM=$(( 4 + 2*$numTotalPods*$numUniqueLabelsPerPod + 2*$numSharedLabelsPerPod + 2*($numKwokDeployments+$numRealDeployments)*$numUniqueLabelsPerDeployment + $extraIPSets ))\n# 3 basic members are [all-ns,kubernetes.io/metadata.name,kubernetes.io/metadata.name:scale-test]\n# 5*pods members go to [ns-scale-test,kubernetes.io/metadata.name:scale-test,template-hash:xxxx,app:scale-test]\nnumIPSetMembersAddedByNPM=$(( 3 + $numTotalPods*(5 + 2*$numUniqueLabelsPerPod + 2*$numSharedLabelsPerPod) + 2*($numKwokPods+$numRealPods)*$numUniqueLabelsPerDeployment + 2*$numKwokPods + 2*$numRealPods ))\nif [[ $numRealServices -gt 0 ]]; then\n    numIPSetMembersAddedByNPM=$(( $numIPSetMembersAddedByNPM + $numRealPods ))\nfi\n## PRINT OUT COUNTS\ncat <<EOF\nStarting scale script with following arguments:\nmaxKwokPodsPerNode=$maxKwokPodsPerNode\nnumKwokDeployments=$numKwokDeployments\nnumKwokReplicas=$numKwokReplicas\nnumRealServices=$numRealServices\nnumRealDeployments=$numRealDeployments\nnumRealReplicas=$numRealReplicas\nnumSharedLabelsPerPod=$numSharedLabelsPerPod\nnumUniqueLabelsPerPod=$numUniqueLabelsPerPod\nnumUniqueLabelsPerDeployment=$numUniqueLabelsPerDeployment\nnumNetworkPolicies=$numNetworkPolicies\nnumUnappliedNetworkPolicies=$numUnappliedNetworkPolicies\n\nDelete arguments (optional):\ndeleteKwokPods=$deleteKwokPods\ndeleteRealPods=$deleteRealPods\ndeletePodsInterval=$deletePodsInterval\ndeletePodsTimes=$deletePodsTimes\ndeleteLabels=$deleteLabels\ndeleteLabelsInterval=$deleteLabelsInterval\ndeleteLabelsTimes=$deleteLabelsTimes\ndeleteNetpols=$deleteNetpols\ndeleteNetpolsInterval=$deleteNetpolsInterval\ndeleteNetpolsTimes=$deleteNetpolsTimes\n\nThe following will be created:\nkwok Nodes: $numKwokNodes\nkwok Pods: $numKwokPods\nreal Pods: $numRealPods\n\nNPM would create the following:\nACLs (per endpoint in Windows): $numACLsAddedByNPM\nIPSets: $numIPSetsAddedByNPM\nIPSet Members: $numIPSetMembersAddedByNPM\n\n\nEOF\n\nif [[ $DEBUG_EXIT_AFTER_PRINT_COUNTS == true ]]; then\n    echo \"DEBUG: exiting after printing counts...\"\n    exit 0\nfi\n\n## HELPER FUNCTIONS\nwait_for_pods() {\n    # wait for all pods to run\n    minutesToWaitForRealPods=$(( 10 + $numRealPods / 250 ))\n    set -x\n    if [[ $numRealPods -gt 0 ]]; then\n        $KUBECTL $KUBECONFIG_ARG wait --for=condition=Ready pods -n scale-test -l is-real=true --all --timeout=\"${minutesToWaitForRealPods}m\"\n    fi\n    set +x\n\n    # just make sure kwok pods are Running, not necessarily Ready (sometimes kwok pods have NodeNotReady even though the node is ready)\n    minutesToWaitForKwokPods=$(( 1 + $numKwokPods / 500 ))\n    set -x\n    if [[ $numKwokPods -gt 0 ]]; then\n        $KUBECTL $KUBECONFIG_ARG wait --for=condition=Initialized pods -n scale-test -l is-kwok=true --all --timeout=\"${minutesToWaitForKwokPods}m\"\n    fi\n    set +x\n}\n\n## FILE SETUP\necho \"Cleaning up generated/ directory...\"\ntest -d generated && rm -rf generated/\nmkdir -p generated/networkpolicies/applied\nmkdir -p generated/networkpolicies/unapplied\nmkdir -p generated/kwok-nodes\nmkdir -p generated/deployments/real/\nmkdir -p generated/deployments/kwok/\nmkdir -p generated/services/real/\n\ngenerateDeployments() {\n    local numDeployments=$1\n    local numReplicas=$2\n    local depKind=$3\n\n    for i in $(seq -f \"%05g\" 1 $numDeployments); do\n        name=\"$depKind-dep-$i\"\n        labelPrefix=\"$depKind-dep-lab-$i\"\n        outFile=generated/deployments/$depKind/$name.yaml\n\n        sed \"s/TEMP_NAME/$name/g\" templates/$depKind-deployment.yaml > $outFile\n        sed -i \"s/TEMP_REPLICAS/$numReplicas/g\" $outFile\n\n        if [[ $numUniqueLabelsPerDeployment -gt 0 ]]; then\n            depLabels=\"\"\n            for j in $(seq -f \"%05g\" 1 $numUniqueLabelsPerDeployment); do\n                depLabels=\"$depLabels\\n      $labelPrefix-$j: val\"\n            done\n            perl -pi -e \"s/OTHER_LABELS_6_SPACES/$depLabels/g\" $outFile\n\n            depLabels=\"\"\n            for j in $(seq -f \"%05g\" 1 $numUniqueLabelsPerDeployment); do\n                depLabels=\"$depLabels\\n        $labelPrefix-$j: val\"\n            done\n            perl -pi -e \"s/OTHER_LABELS_8_SPACES/$depLabels/g\" $outFile\n        else\n            sed -i \"s/OTHER_LABELS_6_SPACES//g\" $outFile\n            sed -i \"s/OTHER_LABELS_8_SPACES//g\" $outFile\n        fi\n    done\n}\n\ngenerateServices() {\n    local numServices=$1\n    local numDeployments=$2\n    local serviceKind=$3\n\n    for i in $(seq -f \"%05g\" 1 $numServices); do\n        name=\"$serviceKind-svc-$i\"\n        outFile=generated/services/$serviceKind/$name.yaml\n\n        sed \"s/TEMP_NAME/$name/g\" templates/$serviceKind-service.yaml > $outFile\n        sed -i \"s/TEMP_DEPLOYMENT_NAME/$serviceKind-dep-$i/g\" $outFile\n    done\n}\n\necho \"Generating yamls...\"\n\ngenerateDeployments $numKwokDeployments $numKwokReplicas kwok\ngenerateDeployments $numRealDeployments $numRealReplicas real\ngenerateServices $numRealServices $numRealDeployments real\n\nfor j in $(seq 1 $numNetworkPolicies); do\n    valNum=$j\n    i=`printf \"%05d\" $j`\n    fileName=generated/networkpolicies/applied/policy-$i.yaml\n    sed \"s/TEMP_NAME/policy-$i/g\" templates/networkpolicy.yaml > $fileName\n    if [[ $valNum -ge $(( numSharedLabelsPerPod - 2 )) ]]; then\n        valNum=$(( $numSharedLabelsPerPod - 2 ))\n    fi\n    k=`printf \"%05d\" $valNum`\n    sed -i \"s/TEMP_LABEL_NAME/shared-lab-$k/g\" $fileName\n\n    ingressNum=$(( $valNum + 1 ))\n    k=`printf \"%05d\" $ingressNum`\n    sed -i \"s/TEMP_INGRESS_NAME/shared-lab-$k/g\" $fileName\n\n    egressNum=$(( $valNum + 2 ))\n    k=`printf \"%05d\" $ingressNum`\n    sed -i \"s/TEMP_EGRESS_NAME/shared-lab-$k/g\" $fileName\ndone\n\nfor j in $(seq 1 $numUnappliedNetworkPolicies ); do\n    i=`printf \"%05d\" $j`\n    sed \"s/TEMP_NAME/unapplied-policy-$i/g\" templates/unapplied-networkpolicy.yaml > generated/networkpolicies/unapplied/unapplied-policy-$i.yaml\ndone\n\nfor i in $(seq -f \"%05g\" 1 $numKwokNodes); do\n    cat templates/kwok-node.yaml | sed \"s/INSERT_NUMBER/$i/g\" > \"generated/kwok-nodes/node-$i.yaml\"\ndone\n\necho \"Done generating yamls.\"\n\nif [[ $DEBUG_EXIT_AFTER_GENERATION == true ]]; then\n    echo \"DEBUG: exiting after generation...\"\n    exit 0\nfi\n\n## VALIDATE REAL NODES\necho \"checking if there are enough real nodes...\"\nnumRealNodes=$($KUBECTL $KUBECONFIG_ARG get nodes -l scale-test=true | grep -v NAME | wc -l)\nif [[ $numRealNodes -lt $numRealNodesRequired ]]; then\n    $KUBECTL $KUBECONFIG_ARG get nodes\n    echo \"ERROR: need $numRealNodesRequired real nodes to achieve a scale of $numRealPods real Pods. Make sure to label nodes with: kubectl label node <name> scale-test=true\"\n    exit 1\nfi\n\n## DELETE PRIOR STATE\necho \"cleaning up previous scale test state...\"\n$KUBECTL $KUBECONFIG_ARG delete ns scale-test connectivity-test --ignore-not-found\n$KUBECTL $KUBECONFIG_ARG delete node -l type=kwok\n\nif [[ $USING_NPM == true ]]; then\n    echo \"restarting NPM pods...\"\n    $KUBECTL $KUBECONFIG_ARG rollout restart -n kube-system ds azure-npm\n    $KUBECTL $KUBECONFIG_ARG rollout restart -n kube-system ds azure-npm-win\n    echo \"sleeping 3m to allow NPM pods to restart...\"\n    sleep 1m\n    echo \"2m remaining...\"\n    sleep 1m\n    echo \"1m remaining...\"\n    sleep 1m\n\n    echo \"making sure NPM pods are running...\"\n    $KUBECTL $KUBECONFIG_ARG get pod -n kube-system | grep Running | grep -v \"azure-npm-win\" | grep -oP \"azure-npm-[a-z0-9]+\" -m 1\n    if [[ $? != 0 ]]; then\n        echo \"No Linux NPM pod running. Exiting.\"\n        exit 1\n    fi\n\n    $KUBECTL $KUBECONFIG_ARG get pod -n kube-system | grep Running | grep -oP \"azure-npm-win-[a-z0-9]+\" -m 1\n    if [[ $? != 0 ]]; then\n        echo \"No Windows NPM pod running. Exiting.\"\n        exit 1\n    fi\nfi\n\n## RUN\nif [[ $numKwokPods -gt 0 ]]; then\n    echo \"START KWOK COMMAND NOW...\"\n    sleep 10s\nfi\n\nstartDate=`date -u`\necho \"STARTING RUN at $startDate\"\necho\n\nset -x\n$KUBECTL $KUBECONFIG_ARG create ns scale-test\nif [[ $numKwokNodes -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/kwok-nodes/\nfi\nif [[ $numRealPods -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/deployments/real/\nfi\nif [[ $numKwokPods -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/deployments/kwok/\nfi\nif [[ $numServices -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/services/real/\nfi\nset +x\n\nadd_shared_labels() {\n    if [[ $numSharedLabelsPerPod -gt 0 ]]; then\n        sharedLabels=\"\"\n        for i in $(seq -f \"%05g\" 1 $numSharedLabelsPerPod); do\n            sharedLabels=\"$sharedLabels shared-lab-$i=val\"\n        done\n\n        set -x\n        $KUBECTL $KUBECONFIG_ARG label pods -n scale-test --all $sharedLabels --overwrite\n        set +x\n    fi\n}\n\nadd_shared_labels\n\nif [[ $numUniqueLabelsPerPod -gt 0 ]]; then\n    count=1\n    for pod in $($KUBECTL $KUBECONFIG_ARG get pods -n scale-test -o jsonpath='{.items[*].metadata.name}'); do\n        uniqueLabels=\"\"\n        for tmp in $(seq 1 $numUniqueLabelsPerPod); do\n            i=`printf \"%05d\" $count`\n            uniqueLabels=\"$uniqueLabels uni-lab-$i=val\"\n            count=$(( $count + 1 ))\n        done\n\n        set -x\n        $KUBECTL $KUBECONFIG_ARG label pods -n scale-test $pod $uniqueLabels\n        set +x\n    done\nfi\n\nset -x\nif [[ $numUnappliedNetworkPolicies -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/networkpolicies/unapplied\nfi\nif [[ $numNetworkPolicies -gt 0 ]]; then\n    $KUBECTL $KUBECONFIG_ARG apply -f generated/networkpolicies/applied\nfi\nset +x\n\nwait_for_pods\n\necho\necho \"done scaling at $(date -u). Had started at $startDate.\"\necho\n\necho \"performing deletions if configured...\"\n\nif [[ $sleepAfterCreation != \"\" ]]; then\n    echo \"sleeping $sleepAfterCreation seconds after creation...\"\n    sleep $sleepAfterCreation\nfi\n\nif [[ $deleteNetpols == true ]]; then\n    echo \"deleting network policies...\"\n    for i in $(seq 1 $deleteNetpolsTimes); do\n        echo \"deleting network policies. round $i/$deleteNetpolsTimes...\"\n        set -x\n        $KUBECTL $KUBECONFIG_ARG delete netpol -n scale-test --all\n        set +x\n        echo \"sleeping $deleteNetpolsInterval seconds after deleting network policies (round $i/$deleteNetpolsTimes)...\"\n        sleep $deleteNetpolsInterval\n        \n        echo \"re-adding network policies. round $i/$deleteNetpolsTimes...\"\n        set -x\n        if [[ $numUnappliedNetworkPolicies -gt 0 ]]; then\n            $KUBECTL $KUBECONFIG_ARG apply -f generated/networkpolicies/unapplied\n        fi\n        if [[ $numNetworkPolicies -gt 0 ]]; then\n            $KUBECTL $KUBECONFIG_ARG apply -f generated/networkpolicies/applied\n        fi\n        set +x\n        echo \"sleeping $deleteNetpolsInterval seconds after readding network policies (end of round $i/$deleteNetpolsTimes)...\"\n        sleep $deleteNetpolsInterval\n    done\nfi\n\nif [[ ($deleteKwokPods != \"\" && $deleteKwokPods -gt 0) || ($deleteRealPods != \"\" && $deleteRealPods -gt 0) ]]; then\n    for i in $(seq 1 $deletePodsTimes); do\n        if [[ $deleteKwokPods != \"\" && $deleteKwokPods -gt 0 && $numKwokPods -gt 0 ]]; then\n            echo \"deleting kwok pods. round $i/$deletePodsTimes...\"\n            pods=`$KUBECTL $KUBECONFIG_ARG get pods -n scale-test -l is-kwok=\"true\" | grep -v NAME | shuf -n $deleteKwokPods | awk '{print $1}' | tr '\\n' ' '`\n            set -x\n            $KUBECTL $KUBECONFIG_ARG delete pods -n scale-test $pods\n            set +x\n        fi\n\n        if [[ $deleteRealPods != \"\" && $deleteRealPods -gt 0 && $numRealPods -gt 0 ]]; then\n            echo \"deleting real pods. round $i/$deletePodsTimes...\"\n            pods=`$KUBECTL $KUBECONFIG_ARG get pods -n scale-test -l is-real=\"true\" | grep -v NAME | shuf -n $deleteRealPods | awk '{print $1}' | tr '\\n' ' '`\n            set -x\n            $KUBECTL $KUBECONFIG_ARG delete pods -n scale-test $pods\n            set +x\n        fi\n\n        sleep 5s\n        wait_for_pods\n\n        if [[ $i == $deletePodsTimes ]]; then\n            break\n        fi\n        echo \"sleeping $deletePodsInterval seconds after deleting pods (end of round $i/$deletePodsTimes)...\"\n        sleep $deletePodsInterval\n    done\n\n    # make sure all Pods have shared labels\n    add_shared_labels\nfi\n\n\nif [[ $deleteLabels == true && $numSharedLabelsPerPod -gt 2 ]]; then\n    echo \"deleting labels...\"\n    for i in $(seq 1 $deleteLabelsTimes); do\n        echo \"deleting labels. round $i/$deleteLabelsTimes...\"\n        set -x\n        $KUBECTL $KUBECONFIG_ARG label pods -n scale-test --all shared-lab-00001- shared-lab-00002- shared-lab-00003-\n        set +x\n        echo \"sleeping $deleteLabelsInterval seconds after deleting labels (round $i/$deleteLabelsTimes)...\"\n        sleep $deleteLabelsInterval\n        \n        echo \"re-adding labels. round $i/$deleteLabelsTimes...\"\n        set -x\n        $KUBECTL $KUBECONFIG_ARG label pods -n scale-test --all shared-lab-00001=val shared-lab-00002=val shared-lab-00003=val\n        set +x\n        echo \"sleeping $deleteLabelsInterval seconds after readding labels (end of round $i/$deleteLabelsTimes)...\"\n        sleep $deleteLabelsInterval\n    done\nfi\n\necho\necho \"FINISHED at $(date -u). Had started at $startDate.\"\necho\n", "num_lines": 584}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "# exit on error\nset -e\n\n## CONSTANTS\n# agnhost timeout in seconds\nTIMEOUT=5\nCONNECTIVITY_SLEEP=60\n# seconds to wait between failed connectivity checks after adding allow-pinger NetworkPolicy\nNETPOL_SLEEP=5\n\nprintHelp() {\n    cat <<EOF\n./test-connectivity.sh --num-scale-pods-to-verify=all|<int> --max-wait-for-initial-connectivity=<int> --max-wait-after-adding-netpol=<int> [--kubeconfig=<path>] [--kubectl-binary=<path>]\n\nVerifies that scale test Pods can connect to each other, but cannot connect to a new \"pinger\" Pod.\nThen, adds a NetworkPolicy to allow traffic between the scale test Pods and the \"pinger\" Pod, and verifies connectivity.\n\nNOTE: You must run ./test-scale.sh first with --num-network-policies=1 or more, and --num-shared-labels-per-pod=3 or more.\n\nUSAGE:\n1. Follow steps for test-scale.sh\n2. Label a node to schedule \"pinger\" Pods: kubectl label node <name> connectivity-test=true\n3. Run this script\n\nREQUIRED PARAMETERS:\n    --num-scale-pods-to-verify=all|<int>         number of scale Pods to test. Will verify that each scale Pod can connect to each other [(N-1)^2 connections] and that each Scale Pod cannot connect to a \"pinger\" Pod [2N connection attempts with a 3-second timeout]\n    --max-wait-for-initial-connectivity=<int>    maximum time in seconds to wait for initial connectivity after Pinger Pods are running\n    --max-wait-after-adding-netpol=<int>         maximum time in seconds to wait for allowed connections after adding the allow-pinger NetworkPolicy\n\nOPTIONAL PARAMETERS:\n    --kubeconfig=<path>                 path to kubeconfig file\n    --kubectl-binary=<path>               path to kubectl binary. Default is kubectl\n\nEXIT CODES:\n0 - success\n6 - non-retriable error\n7 - potentially retriable error while getting Pods/IPs\n8 - failed on initial connectivity test\n9 - failed after adding allow-pinger NetworkPolicy\nother - script exited from an unhandled error\n\nEOF\n}\n\nlog() {\n    msg=$1\n    # e.g. [2023-05-08 17:16:39-07:00] msg\n    echo \"[$(date --rfc-3339=seconds)] $msg\"\n}\n\n## PARAMETERS\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        -h|--help)\n            printHelp\n            exit 0\n            ;;\n        --num-scale-pods-to-verify=*)\n            numScalePodsToVerify=\"${1#*=}\"\n            ;;\n        --max-wait-for-initial-connectivity=*)\n            maxWaitForInitialConnectivity=\"${1#*=}\"\n            ;;\n        --max-wait-after-adding-netpol=*)\n            maxWaitAfterAddingNetpol=\"${1#*=}\"\n            ;;\n        --kubeconfig=*)\n            file=${1#*=}\n            KUBECONFIG_ARG=\"--kubeconfig $file\"\n            test -f $file || { \n                log \"ERROR: kubeconfig not found: [$file]\"\n                exit 6\n            }\n            log \"using kubeconfig: $file\"\n            ;;\n        --kubectl-binary=*)\n            KUBECTL=${1#*=}\n            test -f $KUBECTL || { \n                log \"ERROR: kubectl binary not found: [$KUBECTL]\"\n                exit 1\n            }\n            log \"using kubectl binary: $KUBECTL\"\n            ;;\n        *)\n            log \"ERROR: unknown parameter $1. Make sure you're using '--key=value' for parameters with values\"\n            exit 6\n            ;;\n    esac\n    shift\ndone\n\nif [[ -z $numScalePodsToVerify || -z $maxWaitForInitialConnectivity || -z $maxWaitAfterAddingNetpol ]]; then\n    log \"ERROR: missing required parameter. Check --help for usage\"\n    exit 6\nfi\n\nif [[ -z $KUBECTL ]]; then\n    KUBECTL=\"kubectl\"\nfi\n\n## PRINT OUT ARGS\ncat <<EOF\nStarting connectivity script with following args.\n\nnumScalePodsToVerify: $numScalePodsToVerify\nmaxWaitAfterAddingNetpol: $maxWaitAfterAddingNetpol\n\nTIMEOUT: $TIMEOUT\nNETPOL_SLEEP: $NETPOL_SLEEP\n\nEOF\n\n## HELPER FUNCTIONS\nconnectFromPinger() {\n    local from=$1\n    local dstIP=$2\n    log \"checking connectivity from $from to $dstIP\"\n    $KUBECTL $KUBECONFIG_ARG exec -n connectivity-test $from -- /agnhost connect --timeout=${TIMEOUT}s $dstIP:80\n}\n\nconnectFromScalePod() {\n    local from=$1\n    local dstIP=$2\n    log \"checking connectivity from $from to $dstIP\"\n    $KUBECTL $KUBECONFIG_ARG exec -n scale-test $from -- /agnhost connect --timeout=${TIMEOUT}s $dstIP:80\n}\n\n## VALIDATE\ntest -f pinger.yaml || {\n    log \"ERROR: change into the connectivity/ directory when running this script\"\n    exit 6\n}\n\nif [[ -z `$KUBECTL $KUBECONFIG_ARG get nodes -l connectivity-test=true | grep -v NAME` ]]; then\n    $KUBECTL $KUBECONFIG_ARG get node\n    log \"ERROR: label a node with: kubectl label node <name> connectivity-test=true\"\n    exit 6\nfi\n\n## RUN\nset -e\nstartDate=`date -u`\nlog \"STARTING CONNECTIVITY TEST at $startDate\"\n\n## GET SCALE PODS\nif [[ $numScalePodsToVerify == \"all\" ]]; then\n    log \"setting numScalePodsToVerify=9999 since 'all' was passed in\"\n    numScalePodsToVerify=9999\nfi\n\nlog \"getting scale Pods...\"\nscalePodNameIPs=(`$KUBECTL $KUBECONFIG_ARG get pods -n scale-test --field-selector=status.phase==Running -l is-real=\"true\" -o jsonpath='{range .items[*]}{@.metadata.name}{\",\"}{@.status.podIP}{\" \"}{end}'`)\nscalePods=()\nscalePodIPs=()\nfor nameIP in \"${scalePodNameIPs[@]}\"; do\n    nameIP=(`echo $nameIP | tr ',' ' '`)\n    name=${nameIP[0]}\n    ip=${nameIP[1]}\n\n    log \"scale Pod: $name, IP: $ip\"\n\n    if [[ -z $name || -z $ip ]]; then\n        log \"ERROR: expected scale Pod name and IP to be non-empty\"\n        exit 7\n    fi\n\n    scalePods+=($name)\n    scalePodIPs+=($ip)\n\n    if [[ ${#scalePods[@]} -eq $numScalePodsToVerify ]]; then\n        break\n    fi\ndone\n\nnumScalePodsFound=${#scalePods[@]}\nif [[ $numScalePodsFound == 0 ]]; then\n    log \"ERROR: expected namespace scale-test to exist with real (non-kwok) Pods. Run test/scale/test-scale.sh with real Pods first.\"\n    kubectl get pod -n scale-test -owide\n    exit 7\nelif [[ $numScalePodsFound -lt $numScalePodsToVerify ]]; then\n    log \"WARNING: there are only $numScalePodsFound real scale Pods running which is less than numScalePodsToVerify=$numScalePodsToVerify. Will verify just these $numScalePodsFound Pods\"\n    numScalePodsToVerify=$numScalePodsFound\nelse\n    log \"will verify connectivity to $numScalePodsToVerify scale Pods\"\nfi\n\n## CREATE PINGERS\n$KUBECTL $KUBECONFIG_ARG create ns connectivity-test || true\n$KUBECTL $KUBECONFIG_ARG apply -f pinger.yaml\nsleep 5s\nlog \"waiting for pingers to be ready...\"\n$KUBECTL $KUBECONFIG_ARG wait --for=condition=Ready pod -n connectivity-test -l app=pinger --timeout=60s || {\n    log \"ERROR: pingers never ran\"\n    exit 7\n}\n\npingerNameIPs=(`$KUBECTL $KUBECONFIG_ARG get pod -n connectivity-test -l app=pinger --field-selector=status.phase==Running -o jsonpath='{range .items[*]}{@.metadata.name}{\",\"}{@.status.podIP}{\" \"}{end}'`)\npinger1NameIP=(`echo \"${pingerNameIPs[0]}\" | tr ',' ' '`)\npinger1=${pinger1NameIP[0]}\npinger1IP=${pinger1NameIP[1]}\nlog \"pinger1: $pinger1, IP: $pinger1IP\"\npinger2NameIP=(`echo \"${pingerNameIPs[1]}\" | tr ',' ' '`)\npinger2=${pinger2NameIP[0]}\npinger2IP=${pinger2NameIP[1]}\nlog \"pinger2: $pinger2, IP: $pinger2IP\"\nif [[ -z $pinger1 || -z $pinger1IP || -z $pinger2 || -z $pinger2IP ]]; then\n    log \"ERROR: expected two pingers to be running with IPs. Exiting.\"\n    exit 7\nfi\n\n## VERIFY CONNECTIVITY\nverifyInitialConnectivity() {\n    connectFromPinger $pinger1 $pinger2IP || {\n        log \"WARNING: expected pinger1 to be able to connect to pinger2. Pods may need more time to bootup\"\n        return 8\n    }\n\n    connectFromPinger $pinger2 $pinger2 || {\n        log \"WARNING: expected pinger2 to be able to connect to pinger1. Pods may need more time to bootup\"\n        return 8\n    }\n\n    for i in $(seq 0 $(( ${#scalePods[@]} - 1 ))); do\n        scalePod=${scalePods[$i]}\n        for j in $(seq 0 $(( ${#scalePods[@]} - 1 ))); do\n            if [[ $i == $j ]]; then\n                continue\n            fi\n\n            dstPod=${scalePods[$j]}\n            dstIP=${scalePodIPs[$j]}\n            connectFromScalePod $scalePod $dstIP || {\n                log \"WARNING: expected scale Pod $scalePod to be able to connect to scale Pod $dstPod\"\n                return 8\n            }\n        done\n    done\n\n    for i in $(seq 0 $(( ${#scalePods[@]} - 1 ))); do\n        scalePod=${scalePods[$i]}\n        scalePodIP=${scalePodIPs[$i]}\n\n        connectFromScalePod $scalePod $pinger1IP && {\n            log \"WARNING: expected scale Pod $scalePod to NOT be able to connect to pinger1\"\n            return 8\n        }\n\n        connectFromPinger $pinger1 $scalePodIP && {\n            log \"WARNING: expected pinger1 to NOT be able to connect to scale Pod $scalePod\"\n            return 8\n        }\n    done\n\n    return 0\n}\n\nlog \"verifying initial connectivity at $(date)...\"\nconnectivityStartDate=`date +%s`\nmaxWaitDate=$(( $connectivityStartDate + $maxWaitForInitialConnectivity ))\nprevTryDate=$connectivityStartDate\nwhile : ; do\n    verifyInitialConnectivity && break\n\n    currDate=`date +%s`\n    if [[ $currDate -gt $maxWaitDate ]]; then\n        log \"ERROR: initial connectivity test timed out. Last try was about $(( $currDate - $connectivityStartDate )) seconds after pinger Pods began running\"\n        exit 8\n    fi\n\n    log \"WARNING: initial connectivity test failed. Retrying in $CONNECTIVITY_SLEEP seconds...\"\n    sleep $CONNECTIVITY_SLEEP\n\n    prevTryDate=$currDate\ndone\n\nlow=0\nif [[ $prevTryDate -gt $connectivityStartDate ]]; then\n    low=$(( $prevTryDate - $connectivityStartDate - $CONNECTIVITY_SLEEP ))\nfi\nhigh=$(( `date +%s` - $connectivityStartDate ))\nlog \"SUCCESS: all initial connectivity tests passed. Took between $low and $high seconds to succeed\"\n\n## ADD NETWORK POLICY AND VERIFY CONNECTIVITY\nlog \"adding allow-pinger NetworkPolicy at $(date)...\"\n$KUBECTL $KUBECONFIG_ARG apply -f allow-pinger.yaml\n\nverifyNetPol() {\n        for i in $(seq 0 $(( ${#scalePods[@]} - 1 ))); do\n        scalePod=${scalePods[$i]}\n        scalePodIP=${scalePodIPs[$i]}\n\n        connectFromScalePod $scalePod $pinger1IP || {\n            log \"WARNING: expected scale Pod $scalePod to be able to connect to pinger1 after adding NetworkPolicy\"\n            return 9\n        }\n\n        connectFromPinger $pinger1 $scalePodIP || {\n            log \"WARNING: expected pinger1 to be able to connect to scale Pod $scalePod after adding NetworkPolicy\"\n            return 9\n        }\n    done\n\n    return 0\n}\n\nlog \"verifying allow-pinger NetworkPolicy at $(date)...\"\nnetpolStartDate=`date +%s`\nmaxWaitDate=$(( $netpolStartDate + $maxWaitAfterAddingNetpol ))\nprevTryDate=$netpolStartDate\nwhile : ; do\n    verifyNetPol && break\n        \n    currDate=`date +%s`\n    if [[ $currDate -gt $maxWaitDate ]]; then\n        log \"ERROR: allow-pinger NetworkPolicy has not taken effact. Last try was at least $(( $prevTryDate - $netpolStartDate )) seconds after creating allow-pinger NetworkPolicy\"\n        exit 9\n    fi\n\n    log \"WARNING: verifying allow-pinger NetworkPolicy failed. Current time: $(date). Retrying in $NETPOL_SLEEP seconds...\"\n    sleep $NETPOL_SLEEP\n\n    prevTryDate=$currDate\ndone\n\nlow=0\nif [[ $prevTryDate -gt $netpolStartDate ]]; then\n    low=$(( $prevTryDate - $netpolStartDate - $NETPOL_SLEEP ))\nfi\nhigh=$(( `date +%s` - $netpolStartDate ))\nlog \"SUCCESS: all connectivity tests passed after adding allow-pinger NetworkPolicy. Took between $low and $high seconds to take effect\"\n\necho\nlog \"FINISHED at $(date -u). Had started at $startDate.\"\necho\n", "num_lines": 335}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#####################################################################################\n# Periodically captures CPU/Memory of Pods/nodes and writes to csvs.                #\n#####################################################################################\nAPPEND_TO_EXISTING_FILES=true\n\nFOLDER=\"captures\"\nRUNNING_PODS_FILE=$FOLDER/cpu-and-mem-running-pods.out\nPOD_MEM_CSV=$FOLDER/cpu-and-mem-pod-results.csv\nNODE_MEM_CSV=$FOLDER/cpu-and-mem-node-results.csv\n\n# kubectl top seems to refresh every minute\nSLEEP_BETWEEN_CAPTURES=65\n\n## RUN\nmkdir -p $FOLDER\n\nif [[ $APPEND_TO_EXISTING_FILES != true ]]; then\n    if [[ -f $RUNNING_PODS_FILE || -f $POD_MEM_CSV || -f $NODE_MEM_CSV ]]; then\n        echo \"ERROR: $RUNNING_PODS_FILE, $POD_MEM_CSV, or $NODE_MEM_CSV already exists. Either 1) set APPEND_TO_EXISTING_FILES=true or 2) move the old files\"\n        exit 1\n    fi\n\n    echo \"time,pod,cpu,mem\" > $POD_MEM_CSV\n    echo \"time,node,cpu,cpuPercent,mem,memPercent\" > $NODE_MEM_CSV\nfi\n\nwhile true; do\n    currentTime=`date -u`\n    echo \"running k top pod\"\n    lines=`kubectl top pod -A | grep -v NAME | grep -v kwok | awk '{$1=$1;print}' | tr ' ' ','`\n    for line in $lines; do\n        echo \"$currentTime,$line\" >> $POD_MEM_CSV\n    done\n\n    currentTime=`date -u`\n    echo \"running k top node\"\n    lines=`kubectl top node | grep -v NAME | grep -v kwok | awk '{$1=$1;print}' | tr ' ' ','`\n    for line in $lines; do\n        echo \"$currentTime,$line\" >> $NODE_MEM_CSV\n    done\n\n    echo `date -u` >> $RUNNING_PODS_FILE\n    kubectl get pod -A -owide | grep npm >> $RUNNING_PODS_FILE\n    echo \" \" >> $RUNNING_PODS_FILE\n\n    echo \"sleeping $SLEEP_BETWEEN_CAPTURES seconds\"\n    sleep $SLEEP_BETWEEN_CAPTURES\ndone\n", "num_lines": 49}
{"repo_name": "azure-container-networking", "repo_creator": "Azure", "programming_language": "Shell", "code": "# exit on error\nset -e\n\nIPTABLES=iptables-nft\nrestoreFile=cleanup-restore-file.txt\n\necho \"cleaning up NPM chains\"\necho \"using iptables command: $IPTABLES\"\n\necho \"*filter\" > $restoreFile\nfor c in `$IPTABLES -vnL | grep \"Chain AZURE-NPM\" | awk '{print $2}'`; do\n    echo \"-F $c\" >> $restoreFile\ndone\necho \"COMMIT\" >> $restoreFile\necho \"\" >> $restoreFile\n\ncat $restoreFile\nread -p \"Will restore with above file. Confirm with [y/N] \" -n 1 -r\necho\nif [[ $REPLY =~ ^[Yy]$  ]]; then\n    echo \"Restore file confirmed.\"\nelse\n    echo \"Press Y or y next time to confirm the restore file\"\n    exit 1\nfi\n\necho \"running restore file. flushing all NPM chains...\"\nset -x\ncat $restoreFile | $IPTABLES-restore -w 60 -T filter --noflush\nset +x\n\necho \"deleting jump to AZURE-NPM chain...\"\nset -x\n$IPTABLES -D FORWARD -j AZURE-NPM -m conntrack --ctstate NEW -w 60\nset +x\n\necho \"deleting all NPM chains...\"\nsleep 5s\nset -x\nfor c in `$IPTABLES -vnL | grep \"Chain AZURE-NPM\" | awk '{print $2}'`; do\n    $IPTABLES -w 60 -X $c\ndone\n\necho \"finished cleaning up NPM chains\"\n", "num_lines": 45}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"n:r:l:s:v:\" flag;do\n    case \"${flag}\" in\n        n) \n            CLUSTER_NAME=$OPTARG\n            echo \"Cluster Name: $CLUSTER_NAME\"\n            ;;\n        r) \n            RESOURCE_GROUP=$OPTARG\n            echo \"Resource Group: $RESOURCE_GROUP\"\n            ;;\n        l) \n            LOCATION=$OPTARG\n            echo \"Location: $LOCATION\"\n            ;;\n        s) \n            SUBSCRIPTION_ID=$OPTARG\n            echo \"Subscription ID: $SUBSCRIPTION_ID\"\n            ;;\n        v) \n            VERSION=$OPTARG\n            echo \"version: $VERSION\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\necho $PWD\n\n#check mandatory flags\nif [ -z $CLUSTER_NAME ]; then\n    echo \"Error: Missing argument Cluster Name (flag -n)\"\n    exit 1\nfi\n\nif [ -z $RESOURCE_GROUP ]; then\n    echo \"Error: Missing argument Resource Group Name (flag -r)\"\n    exit 1\nfi\n\nif [ -z $SUBSCRIPTION_ID ]; then\n    echo \"Subscription ID (flag -s) not given, getting subID from current context\"\n    SUBSCRIPTION_ID=$(az account show --query id --output tsv)\nfi\n\nif [ -z $VERSION ]; then\n    VERSION=\"master\"\nfi\n\necho -e \"\\nChecking if Resource Group $RESOURCE_GROUP Exists\"\nif [ \"$(az group exists -n \"${RESOURCE_GROUP}\")\" = true ];\nthen\n    echo \"$RESOURCE_GROUP exists\"\nelse\n    echo \"$RESOURCE_GROUP does not exist\"\n    echo \"Creating new Resource Group $RESOURCE_GROUP\"\n    if [ -z $LOCATION ]; then\n        echo \"Error: Cannot create Resource group without Location (flag -l)\"\n        exit 1\n    fi\n    az group create -l $LOCATION -n $RESOURCE_GROUP\nfi\n\nif [ $VERSION = \"local\" ] || [ $VERSION = \"push\" ]; \nthen   \n    GIT_ROOT=$(git rev-parse --show-toplevel)\n    if [[ -z ${OUTPUT_DIR:-} ]]; then\n    OUTPUT_DIR=\"$GIT_ROOT/_output\"\n    fi\n    mkdir -p \"$OUTPUT_DIR\"\n\n    AZURE_SP_USERNAME_FILE=\"$OUTPUT_DIR/sp-username\"\n    AZURE_SP_PASSWORD_FILE=\"$OUTPUT_DIR/sp-password\"\nfi\n\nif [ -e \"$AZURE_SP_USERNAME_FILE\" ] && [ -e \"$AZURE_SP_PASSWORD_FILE\" ];\nthen\n    echo -e \"\\nGrabbing Previous Service Principal\"\n    username=$(cat \"$AZURE_SP_USERNAME_FILE\")\n    password=$(cat \"$AZURE_SP_PASSWORD_FILE\")\n    echo -e \"\\nUsername: $username\"\nelse\n    echo -e \"\\nCreating Service Principal\"\n    sp=$(az ad sp create-for-rbac --scopes /subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP --role Contributor)\n    username=$(jq -r '.appId' <<< \"$sp\")\n    password=$(jq -r '.password' <<< \"$sp\")\n    if [ $VERSION = \"local\" ] || [ $VERSION = \"push\" ]; \n    then\n        echo \"$username\" > \"$AZURE_SP_USERNAME_FILE\"\n        echo \"$password\" > \"$AZURE_SP_PASSWORD_FILE\"\n    fi\nfi\n\necho -e \"\\nSpinning up Azure Kubernetes Cluster $CLUSTER_NAME\"\naz aks create --resource-group $RESOURCE_GROUP --name $CLUSTER_NAME --enable-addons monitoring --generate-ssh-keys --service-principal $username --client-secret $password\n\necho -e \"\\nGetting Credentials for Cluster $CLUSTER_NAME\"\naz aks get-credentials --resource-group $RESOURCE_GROUP --name $CLUSTER_NAME --overwrite-existing\necho -e \"\\n\"", "num_lines": 101}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"n:r:\" flag;do\n    case \"${flag}\" in\n        n) \n            CLUSTER_NAME=$OPTARG\n            echo \"Cluster Name: $CLUSTER_NAME\"\n            ;;\n        r) \n            RESOURCE_GROUP=$OPTARG\n            echo \"Resource Group: $RESOURCE_GROUP\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\n#check mandatory flags\nif [ -z $CLUSTER_NAME ]; then\n    echo \"Error: Missing argument Cluster Name (flag -n)\"\n    exit 1\nfi\nif [ -z $RESOURCE_GROUP ]; then\n    echo \"Error: Missing argument Resource Group Name (flag -r)\"\n    exit 1\nfi\n\necho -e \"\\nrunning cosi-uninstall.sh\"\nDRIVER_NAME=$(dirname \"$(realpath ${BASH_SOURCE[0]})\")\nsource \"$DRIVER_NAME/cosi-uninstall.sh\"\n\necho -e \"\\nRunning cluster-down.sh\"\nDRIVER_NAME=$(dirname \"$(realpath ${BASH_SOURCE[0]})\")\nsource \"$DRIVER_NAME/cluster-down.sh\" -n $CLUSTER_NAME -r $RESOURCE_GROUP", "num_lines": 34}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"n:r:\" flag;do\n    case \"${flag}\" in\n        n) \n            CLUSTER_NAME=$OPTARG\n            echo \"Cluster Name: $CLUSTER_NAME\"\n            ;;\n        r) \n            RESOURCE_GROUP=$OPTARG\n            echo \"Resource Group: $RESOURCE_GROUP\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\n#check mandatory flags\nif [ -z $CLUSTER_NAME ]; then\n    echo \"Error: Missing argument Cluster Name (flag -n)\"\n    exit 1\nfi\nif [ -z $RESOURCE_GROUP ]; then\n    echo \"Error: Missing argument Resource Group Name (flag -r)\"\n    exit 1\nfi\n\nservice_principal=$(az aks show --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP --query servicePrincipalProfile.clientId -o tsv)\necho -e \"\\nDeleting Service Principal $service_principal\"\naz ad sp delete --id $service_principal\n\necho -e \"\\nDeleting Cluster $CLUSTER_NAME from Resource Group $RESOURCE_GROUP\"\naz aks delete --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP --yes", "num_lines": 33}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"v:\" flag;do\n    case \"${flag}\" in\n        v) \n            VERSION=$OPTARG\n            echo \"Version: $VERSION\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\nif [ -z $VERSION ]; then\n    VERSION=\"master\"\nfi\necho \"VERSION: $VERSION\\n\"\n\necho \"Getting CRD's for COSI and COSI Controller\"\nkubectl create -k github.com/kubernetes-sigs/container-object-storage-interface-api\nkubectl create -k github.com/kubernetes-sigs/container-object-storage-interface-controller\n\necho -e \"\\nInstalling COSI Driver and Sidecar\"\n\nif [ $VERSION = \"local\" ] || [ $VERSION = \"push\" ];  then\n    DRIVER_NAME=\"$(dirname \"$(dirname \"$(realpath ${BASH_SOURCE[0]})\")\")\"\n    cd $DRIVER_NAME || exit\n    echo \"$(pwd)\"\nfi\n\nif [ $VERSION = \"push\" ]; then\n    echo -e \"\\nVerifying Binaries\"\n    make all\n\n    echo -e \"\\nBuilding COSI Image\"\n    IMAGE_ID=$(docker build -q .)\n    echo \"Image ID: $IMAGE_ID\"\n    PROPERTY_FILE=\"./resources/cosi-driver-azure.properties\"\n    export REGISTRY=`cat $PROPERTY_FILE | grep AZURE_DRIVER_IMAGE_ORG | cut -d'=' -f2`\n    export IMAGE_VERSION=`cat $PROPERTY_FILE | grep AZURE_DRIVER_IMAGE_VERSION | cut -d'=' -f2`\n    echo \"Registry: $REGISTRY\"\n    echo \"Version: $IMAGE_VERSION\"\n    docker tag $IMAGE_ID \"$REGISTRY/azure-cosi-driver:$IMAGE_VERSION\"\n\n    echo -e \"\\nPushing COSI Image $REGISTRY/azure-cosi-driver:$IMAGE_VERSION\"\n    docker push \"$REGISTRY/azure-cosi-driver:$IMAGE_VERSION\"\nfi\n\necho -e \"\\nCreating Kube Resources\"\nif [ $VERSION = \"local\" ] || [ $VERSION = \"push\" ]; \nthen\n    kubectl create -k ./. \nelse\n    kubectl create -k github.com/Azure/azure-cosi-driver/?ref=$VERSION\nfi\necho -e \"\\n\"\n", "num_lines": 57}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"v:\" flag;do\n    case \"${flag}\" in\n        v) \n            VERSION=$OPTARG\n            echo \"Version: $VERSION\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\nif [ -z $VERSION ]; then\n    VERSION=\"remote\"\nfi\n\necho -e \"\\nDeleting Kube Resources\"\nif [ $VERSION = \"local\" ] || [ $VERSION = \"push\" ]; \nthen\n    kubectl delete -k ./. \n    echo -e \"\\nDeleting COSI Driver and Sidecar\"\n    DRIVER_NAME=$(dirname \"$(dirname \"$(realpath \"${BASH_SOURCE[0]}\")\")\")\n    cd $DRIVER_NAME || echo \"Unable to find directory $DRIVER_NAME\"; exit 1\n    echo \"$(pwd)\"\nelse\n    kubectl delete -k github.com/Azure/azure-cosi-driver\nfi\necho -e \"\\n\"\n\nif [ $VERSION = \"push\" ]; then\n    echo -e \"\\nDeleting COSI Image\"\n    PROPERTY_FILE=\"./resources/cosi-driver-azure.properties\"\n    export REGISTRY=`cat \"${PROPERTY_FILE}\" | grep AZURE_DRIVER_IMAGE_ORG | cut -d'=' -f2`\n    export IMAGE_VERSION=`cat \"${PROPERTY_FILE}\" | grep AZURE_DRIVER_IMAGE_VERSION | cut -d'=' -f2`\n    echo \"Registry: $REGISTRY\"\n    echo \"Version: $IMAGE_VERSION\"\n    docker image rm \"$REGISTRY/azure-cosi-driver:$IMAGE_VERSION\"\nfi\n\necho \"Deleting CRD's for COSI and COSI Controller\"\nkubectl delete -k github.com/kubernetes-sigs/container-object-storage-interface-controller\nkubectl delete -k github.com/kubernetes-sigs/container-object-storage-interface-api", "num_lines": 43}
{"repo_name": "azure-cosi-driver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwhile getopts \"n:r:l:s:v:\" flag;do\n    case \"${flag}\" in\n        n) \n            CLUSTER_NAME=$OPTARG\n            echo \"Cluster Name: $CLUSTER_NAME\"\n            ;;\n        r) \n            RESOURCE_GROUP=$OPTARG\n            echo \"Resource Group: $RESOURCE_GROUP\"\n            ;;\n        l) \n            LOCATION=$OPTARG\n            echo \"Location: $LOCATION\"\n            ;;\n        s) \n            SUBSCRIPTION_ID=$OPTARG\n            echo \"Subscription ID: $SUBSCRIPTION_ID\"\n            ;;\n        v) \n            VERSION=$OPTARG\n            echo \"version: $VERSION\"\n            ;;\n        *)\n            echo \"Unknown argument $OPTARG\"\n            ;;\n    esac\ndone\n\n#check mandatory flags\nif [ -z $CLUSTER_NAME ]; then\n    echo \"Error: Missing argument Cluster Name (flag -n)\"\n    exit 1\nfi\nif [ -z $RESOURCE_GROUP ]; then\n    echo \"Error: Missing argument Resource Group Name (flag -r)\"\n    exit 1\nfi\nif [ -z $SUBSCRIPTION_ID ]; then\n    echo \"Subscription ID (flag -s) not given, getting subID from current context\"\n    SUBSCRIPTION_ID=$(az account show --query id --output tsv)\nfi\nif [ -z $VERSION ]; then\n    VERSION=\"local\"\nfi\n\nDRIVER_NAME=$(dirname \"$(realpath ${BASH_SOURCE[0]})\")\n\necho -e \"\\nRunning azure-cluster-up.sh\"\nif [ -z $LOCATION ];\nthen\n    source \"$DRIVER_NAME/azure-cluster-up.sh\" -n $CLUSTER_NAME -r $RESOURCE_GROUP -s $SUBSCRIPTION_ID -v $VERSION\nelse\n    source \"$DRIVER_NAME/azure-cluster-up.sh\" -n $CLUSTER_NAME -r $RESOURCE_GROUP -l $LOCATION -s $SUBSCRIPTION_ID -v $VERSION\nfi\n\necho -e \"\\nrunning cosi-install.sh\"\nsource \"$DRIVER_NAME/cosi-install.sh\" -v $VERSION\n", "num_lines": 59}
{"repo_name": "azure-cosmos-dotnet-v3", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport OSSProjectRef=True\nexport RESULTS_PK=test_runs\nexport PL=18\n\n#These must be configured\nexport ACCOUNT_ENDPOINT=\nexport ACCOUNT_KEY=\nexport TELEMETRY_ENDPOINT=\n\n#Loop forever\ni=0\nwhile :\ndo\n    #Kill any running processes\n    pkill -f run.sh\n    git pull origin master\n\n    # Query operations take a long time\n    # Only run them once every 10 runs\n    if [ $(($i % 10)) -eq 0 ]; then\n        echo Query run is enabled\n        export INCLUDE_QUERY=true\n    else\n        export INCLUDE_QUERY=false\n    fi\n    ((i++))\n\n    ./run.sh\n\n    echo \"====== Waiting for 10Sec =================\"\n    sleep 10 #Wait for 10sec\n    \ndone", "num_lines": 35}
{"repo_name": "azure-cosmos-dotnet-v3", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z \"$ACCOUNT_ENDPOINT\" ]\nthen\n    echo \"Missing ACCOUNT_ENDPOINT\"\n    exit -1\nfi\n\nif [ -z \"$ACCOUNT_KEY\" ]\nthen\n    echo \"Missing ACCOUNT_KEY\"\n    exit -1\nfi\n\nif [ -z \"$RESULTS_PK\" ]\nthen\n    echo \"Missing RESULTS_PK\"\n    exit -1\nfi\n\nif [ -z \"$PL\" ]\nthen\n    echo \"Missing PL\"\n    exit -1\nfi\n\nif [ -z \"$TELEMETRY_ENDPOINT\" ]\nthen\n    echo \"Missing TELEMETRY_ENDPOINT\"\n    exit -1\nfi\n\nif [ -z \"$INCLUDE_QUERY\" ]\nthen\n    echo \"Missing INCLUDE_QUERY\"\n    exit -1\nfi\n\nCOMMIT_ID=$(git log -1 | head -n 1 | cut -d ' ' -f 2)\nCOMMIT_DATE=$(git log -1 --date=format:'%Y-%m-%d %H:%M:%S' | grep Date | cut -f 2- -d ':' | sed 's/^[ \\t]*//;s/[ \\t]*$//' | cut -f 1 -d ' ')\nCOMMIT_TIME=$(git log -1 --date=format:'%Y-%m-%d %H:%M:%S' | grep Date | cut -f 2- -d ':' | sed 's/^[ \\t]*//;s/[ \\t]*$//' | cut -f 2 -d ' ')\nBRANCH_NAME=$(git rev-parse --abbrev-ref HEAD)\n\necho $COMMIT_ID\necho $COMMIT_DATE\necho $COMMIT_TIME\necho $BRANCH_NAME\n\n# Client telemetry disabled ReadStreamExistsV3\ndotnet run -c Release  -- -n 2000000 -w ReadStreamExistsV3 --tcp 10 --pl $PL -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY  --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \nsleep 10 #Wait\n\n# Client telemetry enabled ReadStreamExistsV3. This is needed to see the impact of client telemetry. \ndotnet run -c Release  -- -n 2000000 -w ReadStreamExistsV3 --WorkloadName ReadStreamExistsV3WithTelemetry  --enableTelemetry --telemetryScheduleInSec 60 --telemetryEndpoint $TELEMETRY_ENDPOINT --tcp 10 --pl $PL -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY  --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \nsleep 10 #Wait\n\n# Open telemetry enabled ReadStreamExistsV3. This is needed to see the impact of distributed tracing (without listener) \ndotnet run -c Release  -- -n 2000000 -w ReadStreamExistsV3 --WorkloadName ReadStreamExistsV3WithDistributedTracingWOListener  --enableDistributedTracing --tcp 10 --pl $PL -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY  --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \nsleep 10 #Wait\n\n#Point read operations\nfor WORKLOAD_NAME in ReadNotExistsV3 ReadTExistsV3 ReadStreamExistsWithDiagnosticsV3\ndo\n    dotnet run -c Release  -- -n 2000000 -w $WORKLOAD_NAME --pl $PL --enableTelemetry --telemetryScheduleInSec 60 --telemetryEndpoint $TELEMETRY_ENDPOINT --tcp 10 -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY  --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \n    sleep 10 #Wait\ndone\n\n#Insert operation\ndotnet run -c Release  -- -n 2000000 -w InsertV3 --pl 30 --enableTelemetry --telemetryScheduleInSec 60 --telemetryEndpoint $TELEMETRY_ENDPOINT --tcp 1 -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY  --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \nsleep 45 #Wait\n\nif [ \"$INCLUDE_QUERY\" = true ]\nthen\n    #Query operations\n    # n value is lowered to 200000 because queries are significantly slower. This prevents the runs from taking to long.\n    # pl is 16 because 18 was casuing a small amount of thorrtles.\n    for WORKLOAD_NAME in ReadFeedStreamV3 QueryTSinglePkV3 QueryTSinglePkOrderByWithPaginationV3 QueryTSinglePkOrderByFullDrainV3 QueryTCrossPkV3 QueryTCrossPkOrderByWithPaginationV3 QueryTCrossPkOrderByFullDrainV3 QueryStreamSinglePkV3 QueryStreamSinglePkOrderByWithPaginationV3 QueryStreamSinglePkOrderByFullDrainV3 QueryStreamCrossPkV3 QueryStreamCrossPkOrderByWithPaginationV3 QueryStreamCrossPkOrderByFullDrainV3\n    do\n        dotnet run -c Release  -- -n 200000 -w $WORKLOAD_NAME --pl 16 --enableTelemetry --telemetryScheduleInSec 60 --telemetryEndpoint $TELEMETRY_ENDPOINT --tcp 10 -e $ACCOUNT_ENDPOINT -k $ACCOUNT_KEY --enablelatencypercentiles --disablecoresdklogging --publishresults --resultspartitionkeyvalue $RESULTS_PK --commitid $COMMIT_ID --commitdate $COMMIT_DATE --committime $COMMIT_TIME  --branchname $BRANCH_NAME --database testdb --container testcol --partitionkeypath /pk \n        sleep 10 #Wait\n    done\nfi", "num_lines": 82}
{"repo_name": "azure-cosmos-dotnet-v3", "repo_creator": "Azure", "programming_language": "Shell", "code": "cd ..\ndotnet run -c Release -e ${ENDPOINT} -k ${KEY} -t ${THROUGHPUT} -n ${DOCUMENTS} --pl ${PARALLELISM} --CleanupOnFinish ${CLEANUPFINISH} -w InsertV2BenchmarkOperation", "num_lines": 2}
{"repo_name": "azure-cosmos-dotnet-v3", "repo_creator": "Azure", "programming_language": "Shell", "code": "cd ..\ndotnet run -c Release -e ${ENDPOINT} -k ${KEY} -t ${THROUGHPUT} -n ${DOCUMENTS} --pl ${PARALLELISM} --cleanuponfinish ${CLEANUPFINISH} -w InsertV2BenchmarkOperation\n", "num_lines": 3}
{"repo_name": "azure-cosmos-dotnet-v3", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndotnetparameters=\"$dotnetparameters --ctl_endpoint $ctl_endpoint  --ctl_key $ctl_key\"\n\nif [ -z \"$ctl_operation\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_operation $ctl_operation\"\nfi\n\nif [ -z \"$ctl_concurrency\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_concurrency $ctl_concurrency\"\nfi\n\nif [ -z \"$ctl_consistency_level\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_consistency_level $ctl_consistency_level\"\nfi\n\nif [ -z \"$ctl_throughput\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_throughput $ctl_throughput\"\nfi\n\nif [ -z \"$ctl_read_write_query_pct\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_read_write_query_pct $ctl_read_write_query_pct\"\nfi\n\nif [ -z \"$ctl_number_of_operations\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_number_of_operations $ctl_number_of_operations\"\nfi\n\nif [ -z \"$ctl_max_running_time_duration\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_max_running_time_duration $ctl_max_running_time_duration\"\nfi\n\nif [ -z \"$ctl_number_Of_collection\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_number_Of_collection $ctl_number_Of_collection\"\nfi\n\nif [ -z \"$ctl_diagnostics_threshold_duration\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_diagnostics_threshold_duration $ctl_diagnostics_threshold_duration\"\nfi\n\nif [ -z \"$ctl_database\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_database $ctl_database\"\nfi\n\nif [ -z \"$ctl_collection\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_collection $ctl_collection\"\nfi\n\nif [ -z \"$ctl_graphite_endpoint\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_graphite_endpoint $ctl_graphite_endpoint\"\nfi\n\nif [ -z \"$ctl_graphite_port\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_graphite_port $ctl_graphite_port\"\nfi\n\nif [ -z \"$ctl_reporting_interval\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_reporting_interval $ctl_reporting_interval\"\nfi\n\nif [ -z \"$ctl_content_response_on_write\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_content_response_on_write $ctl_content_response_on_write\"\nfi\n\nif [ -z \"$ctl_output_event_traces\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_output_event_traces $ctl_output_event_traces\"\nfi\n\nif [ -z \"$ctl_gateway_mode\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_gateway_mode $ctl_gateway_mode\"\nfi\n\nif [ -z \"$ctl_logging_context\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_logging_context $ctl_logging_context\"\nfi\n\nif [ -z \"$ctl_telemetry_endpoint\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_telemetry_endpoint $ctl_telemetry_endpoint\"\nfi\n\nif [ -z \"$ctl_telemetry_schedule_in_sec\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_telemetry_schedule_in_sec $ctl_telemetry_schedule_in_sec\"\nfi\n\nif [ -z \"$ctl_precreated_documents\" ]\nthen\ndotnetparameters=\"$dotnetparameters\"\nelse\ndotnetparameters=\"$dotnetparameters --ctl_precreated_documents $ctl_precreated_documents\"\nfi\n\nlog_filename=\"/tmp/dotnetctl.log\"\n\necho \"Log file name is $log_filename\"\n\necho \"$dotnetparameters\" > $log_filename\n\n./CosmosCTL $dotnetparameters 2>&1 | tee -a \"$log_filename\"", "num_lines": 158}
{"repo_name": "azure-databricks-operator", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Find all already running kubectl port-forwards and kill them\nps aux | grep [k]ubectl | awk '{print $2}' | xargs kill > /dev/null 2>&1\n\necho \"-------> Verify all pods up\"\n\n# Json template format\nJSONPATH='{range .items[*]}{@.metadata.name}:{range @.status.conditions[*]}{@.type}={@.status};{end}{end}'\n\n# Ensure there are no Databricks Operator pods not in the Ready state\necho \"-------> Wait for Operator to be ready\"\nuntil kubectl -n azure-databricks-operator-system -lcontrol-plane=controller-manager get pods -o jsonpath=\"$JSONPATH\" 2>&1 | grep -q \"Ready=True\"; do sleep 5;echo \"--------> waiting for all operators to be Ready\"; kubectl get pods -n azure-databricks-operator-system; done\n\n# Ensure there are no MockAPI pods not in the Ready state\necho \"-------> Wait for MockAPI to be ready\"\nuntil kubectl -n databricks-mock-api -lapp=databricks-mock-api get pods -o jsonpath=\"$JSONPATH\" 2>&1 | grep -q \"Ready=True\"; do sleep 5;echo \"--------> waiting for all MockAPIs to be Ready\"; kubectl get pods -n databricks-mock-api; done\n\n# Ensure there are no locust pods not in the Ready state\necho \"-------> Wait for locust to be ready\"\nuntil kubectl -n locust get pods -lapp=locust-loadtest -o jsonpath=\"$JSONPATH\" 2>&1 | grep -q \"Ready=True\"; do sleep 5;echo \"--------> waiting for locust to be available\"; kubectl get pods -n locust; done\n\n# Ensure there are no prometheus pods not in the Ready state\necho \"-------> Wait for prometheus to be ready\"\nuntil kubectl -n default get pods -lapp=prometheus -o jsonpath=\"$JSONPATH\" 2>&1 | grep -q \"Ready=True\"; do sleep 5;echo \"--------> waiting for prometheus to be available\"; kubectl get pods -n default; done\n\necho \"-------> Open port-forwards\"\nkubectl port-forward service/prom-azure-databricks-operator-grafana -n default 8080:80 &\nkubectl port-forward service/prom-azure-databricks-oper-prometheus -n default 9091:9090 &\nkubectl port-forward service/locust-loadtest 8089:8089 9090:9090 -n locust &\n\necho \"Browse to locust webui   -> http://localhost:8089/\"\necho \"Browse to locust metrics -> http://localhost:9090/\"\necho \"Browse to Prometheus     -> http://localhost:9091/targets\"\necho \"Browse to Grafana        -> http://localhost:8080/\"\n", "num_lines": 36}
{"repo_name": "azure-db-benchmarking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nif [ -z \"$workload_type\" ]; then\n    workload=workloada\nelse\n    workload=$workload_type\nfi\n\nif [ -z \"$ycsb_operation\" ]; then\n    operation=load\nelse\n    operation=$ycsb_operation\nfi\n\n# Updating workload file\nif [ ! -z \"$recordcount\" ]; then\n   sed -i \"s/^[#]*\\s*recordcount=.*/recordcount=$recordcount/\" workloads/$workload\nfi\n\nif [ ! -z \"$operationcount\" ]; then\n   sed -i \"s/^[#]*\\s*operationcount=.*/operationcount=$operationcount/\" workloads/$workload\nfi\n\nif [ ! -z \"$insertstart\" ]; then\n   sed -i \"$ ainsertstart=$insertstart\" workloads/$workload\nfi\n\nif [ ! -z \"$insertcount\" ]; then\n   sed -i \"$ ainsertcount=$insertcount\" workloads/$workload\nfi\n\nif [ ! -z \"$insertorder\" ]; then\n   sed -i \"$ ainsertorder=$insertorder\" workloads/$workload\nfi\n\nif [ ! -z \"$fieldcount\" ]; then\n   sed -i \"$ afieldcount=$fieldcount\" workloads/$workload\nfi\n\nif [ ! -z \"$core_workload_insertion_retry_limit\" ]; then\n   sed -i \"$ acore_workload_insertion_retry_limit=$core_workload_insertion_retry_limit\" workloads/$workload\nfi\n\nif [ ! -z \"$readproportion\" ]; then\n   sed -i \"s/^[#]*\\s*readproportion=.*/readproportion=$readproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$updateproportion\" ]; then\n   sed -i \"s/^[#]*\\s*updateproportion=.*/updateproportion=$updateproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$scanproportion\" ]; then\n   sed -i \"s/^[#]*\\s*scanproportion=.*/scanproportion=$scanproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$insertproportion\" ]; then\n   sed -i \"s/^[#]*\\s*insertproportion=.*/insertproportion=$insertproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$requestdistribution\" ]; then\n   sed -i \"s/^[#]*\\s*requestdistribution=.*/requestdistribution=$requestdistribution/\" workloads/$workload\nfi\n\n\n# REQUIRED URI & KEY\nif [ ! -z \"$uri\" ]; then\n   sed -i \"s|^[#]*\\s*azurecosmos.uri\\ =.*|azurecosmos.uri\\ =\\ $uri|\" azurecosmos.properties\nfi\n\nif [ ! -z \"$primaryKey\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.primaryKey\\ =.*/azurecosmos.primaryKey\\ =\\ $primaryKey/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$appInsightConnectionString\" ]; then\n   sed -i \"s|^[#]*\\s*azurecosmos.appInsightConnectionString\\ =.*|azurecosmos.appInsightConnectionString\\ =\\ $appInsightConnectionString|\" azurecosmos.properties\nfi\n\nif [ ! -z \"$databaseName\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.$databaseName\\ =.*/azurecosmos.databaseName\\ =\\ $databaseName/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$useUpsert\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.useUpsert\\ =.*/azurecosmos.useUpsert\\ =\\ $useUpsert/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$includeExceptionStackInLog\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.includeExceptionStackInLog\\ =.*/azurecosmos.includeExceptionStackInLog\\ =\\ $includeExceptionStackInLog/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$diagnosticsLatencyThresholdInMS\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.diagnosticsLatencyThresholdInMS\\ =.*/azurecosmos.diagnosticsLatencyThresholdInMS\\ =\\ $diagnosticsLatencyThresholdInMS/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$userAgent\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.userAgent\\ =.*/azurecosmos.userAgent\\ =\\ $userAgent/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$preferredRegionList\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.preferredRegionList\\ =.*/azurecosmos.preferredRegionList\\ =\\ $preferredRegionList/\" azurecosmos.properties\nfi\n\n# CONNECTION OPTIONS\nif [ ! -z \"$useGateway\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.useGateway\\ =.*/azurecosmos.useGateway\\ =\\ $useGateway/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$consistencyLevel\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.consistencyLevel\\ =.*/azurecosmos.consistencyLevel\\ =\\ $consistencyLevel/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$maxRetryAttemptsOnThrottledRequests\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.maxRetryAttemptsOnThrottledRequests\\ =.*/azurecosmos.maxRetryAttemptsOnThrottledRequests\\ =\\ $maxRetryAttemptsOnThrottledRequests/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$maxRetryWaitTimeInSeconds\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.maxRetryWaitTimeInSeconds\\ =.*/azurecosmos.maxRetryWaitTimeInSeconds\\ =\\ $maxRetryWaitTimeInSeconds/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$gatewayMaxConnectionPoolSize\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.gatewayMaxConnectionPoolSize\\ =.*/azurecosmos.gatewayMaxConnectionPoolSize\\ =\\ $gatewayMaxConnectionPoolSize/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$directMaxConnectionsPerEndpoint\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.directMaxConnectionsPerEndpoint\\ =.*/azurecosmos.directMaxConnectionsPerEndpoint\\ =\\ $directMaxConnectionsPerEndpoint/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$gatewayIdleConnectionTimeoutInSeconds\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.gatewayIdleConnectionTimeoutInSecondst\\ =.*/azurecosmos.gatewayIdleConnectionTimeoutInSeconds\\ =\\ $gatewayIdleConnectionTimeoutInSeconds/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$directIdleConnectionTimeoutInSeconds\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.directIdleConnectionTimeoutInSeconds\\ =.*/azurecosmos.directIdleConnectionTimeoutInSeconds\\ =\\ $directIdleConnectionTimeoutInSeconds/\" azurecosmos.properties\nfi\n\n# QUERY OPTIONS\nif [ ! -z \"$maxDegreeOfParallelism\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.maxDegreeOfParallelism\\ =.*/azurecosmos.maxDegreeOfParallelism\\ =\\ $maxDegreeOfParallelism/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$maxBufferedItemCount\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.maxBufferedItemCount\\ =.*/azurecosmos.maxBufferedItemCount\\ =\\ $maxBufferedItemCount/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$preferredPageSize\" ]; then\n   sed -i \"s/^[#]*\\s*azurecosmos.preferredPageSize\\ =.*/azurecosmos.preferredPageSize\\ =\\ $preferredPageSize/\" azurecosmos.properties\nfi\n\nif [ ! -z \"$exportfile\" ]; then\n   sed -i \"s|^[#]*\\s*exportfile\\ =.*|exportfile\\ =\\ $exportfile|\" azurecosmos.properties\nfi\n\nlog_filename=\"/tmp/ycsb.log\"\n\nif [ ! -z \"$threads\" ] && [ ! -z \"$target\" ]\nthen\n  ./bin/ycsb.sh $operation azurecosmos -P workloads/$workload -P azurecosmos.properties -s -threads $threads -target $target 2>&1 | tee -a \"$log_filename\"\nelif [ ! -z \"$threads\" ]\nthen\n  ./bin/ycsb.sh $operation azurecosmos -P workloads/$workload -P azurecosmos.properties -s -threads $threads 2>&1 | tee -a \"$log_filename\"\nelif [ ! -z \"$target\" ]\nthen\n  ./bin/ycsb.sh $operation azurecosmos -P workloads/$workload -P azurecosmos.properties -s -target $target 2>&1 | tee -a \"$log_filename\"\nelse\n  ./bin/ycsb.sh $operation azurecosmos -P workloads/$workload -P azurecosmos.properties -s 2>&1 | tee -a \"$log_filename\"\nfi\n", "num_lines": 169}
{"repo_name": "azure-db-benchmarking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\necho \"##########VM NAME###########: $DB_BINDING_NAME\"\necho \"##########VM NAME###########: $VM_NAME\"\necho \"##########YCSB_RECORD_COUNT###########: $YCSB_RECORD_COUNT\"\necho \"##########MACHINE_INDEX###########: $MACHINE_INDEX\"\necho \"##########YCSB_OPERATION_COUNT###########: $YCSB_OPERATION_COUNT\"\necho \"##########VM_COUNT###########: $VM_COUNT\"\necho \"##########WRITE_ONLY_OPERATION###########: $WRITE_ONLY_OPERATION\"\n\necho \"##########BENCHMARKING_TOOLS_BRANCH_NAME###########: $BENCHMARKING_TOOLS_BRANCH_NAME\"\necho \"##########BENCHMARKING_TOOLS_URL###########: $BENCHMARKING_TOOLS_URL\"\necho \"##########YCSB_GIT_BRANCH_NAME###########: $YCSB_GIT_BRANCH_NAME\"\necho \"##########YCSB_GIT_REPO_URL###########: $YCSB_GIT_REPO_URL\"\n\n# The index of the record to start at during the Load\ninsertstart=$((YCSB_RECORD_COUNT * (MACHINE_INDEX - 1)))\n# Records already in the DB + records to be added, during load\nrecordcount=$((YCSB_RECORD_COUNT * MACHINE_INDEX))\n# Record count for Run. Since we run read workload after load this is the total number of records loaded by all VMs/clients during load.\ntotalrecordcount=$((YCSB_RECORD_COUNT * VM_COUNT))\nbenchmarkname=ycsbbenchmarking\n\n#Cloning Test Bench Repo\necho \"########## Cloning Test Bench repository ##########\"\ngit clone -b \"$BENCHMARKING_TOOLS_BRANCH_NAME\" --single-branch \"$BENCHMARKING_TOOLS_URL\"\necho \"########## Pulling Latest YCSB TOOLS ##########\"\ngit -C azure-db-benchmarking pull\nmkdir /tmp/ycsb\n# Clearing data from previous run\nrm -rf /tmp/ycsb/*\nrm -rf \"/tmp/$VM_NAME-system-diagnostics\"\ncp -r ./azure-db-benchmarking/cosmos/scripts/* /tmp/ycsb\n#cp -r ./azure-db-benchmarking/core/data/* /tmp/ycsb\n\n#Build YCSB from source\necho \"########## Cloning YCSB repository ##########\"\ngit clone -b \"$YCSB_GIT_BRANCH_NAME\" --single-branch \"$YCSB_GIT_REPO_URL\"\n\ncd YCSB\necho \"########## Pulling Latest YCSB ##########\"\ngit pull\necho \"########## Building YCSB ##########\"\nmvn -pl site.ycsb:$DB_BINDING_NAME-binding -am clean package\ncp -r ./$DB_BINDING_NAME/target/ycsb-$DB_BINDING_NAME-binding*.tar.gz /tmp/ycsb\ncp -r ./$DB_BINDING_NAME/conf/* /tmp/ycsb\ncd /tmp/ycsb/\n\nycsb_folder_name=ycsb-$DB_BINDING_NAME-binding-*-SNAPSHOT\nuser_home=\"/home/${ADMIN_USER_NAME}\"\n\necho \"########## Extracting YCSB ##########\"\ntar xfvz ycsb-$DB_BINDING_NAME-binding*.tar.gz\ncp ./$DB_BINDING_NAME-run.sh ./$ycsb_folder_name\ncp ./*.properties ./$ycsb_folder_name\ncp ./aggregate_multiple_file_results.py ./$ycsb_folder_name\ncp ./converting_log_to_csv.py ./$ycsb_folder_name\ncd ./$ycsb_folder_name\n\nif [[ $DB_BINDING_NAME == \"azurecosmos\" ]]; then\n  tool_api=\"ycsb_sql\"\nelif [[ $DB_BINDING_NAME == \"mongodb\"* ]]; then\n  tool_api=\"ycsb_mongo\"\nelif [[ $DB_BINDING_NAME == \"cassandra\"* ]]; then\n  tool_api=\"ycsb_cassandra\"\nfi\n\nif [ $MACHINE_INDEX -eq 1 ]; then\n  table_exist=$(az storage table exists --name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING | jq '.exists')\n  if [ \"$table_exist\" = true ]; then\n    echo \"${benchmarkname}Metadata already exists\"\n  else\n    az storage table create --name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING\n  fi\n\n  ## Creating SAS URL for result storage container\n  echo \"########## Creating SAS URL for result storage container ###########\"\n  end=$(date -u -d \"30 days\" '+%Y-%m-%dT%H:%MZ')\n  current_time=\"$(date '+%Y-%m-%d-%Hh%Mm%Ss')\"\n  results_container_name=\"$benchmarkname-$current_time\"\n  az storage container create -n $results_container_name --connection-string $RESULT_STORAGE_CONNECTION_STRING\n\n  sas=$(az storage container generate-sas -n $results_container_name --connection-string $RESULT_STORAGE_CONNECTION_STRING --https-only --permissions dlrw --expiry $end -o tsv)\n\n  arr_connection=(${RESULT_STORAGE_CONNECTION_STRING//;/ })\n\n  protocol_string=${arr_connection[0]}\n  arr_protocol_string=(${protocol_string//=/ })\n  protocol=${arr_protocol_string[1]}\n\n  account_string=${arr_connection[1]}\n  arr_account_string=(${account_string//=/ })\n  account_name=${arr_account_string[1]}\n\n  result_storage_url=\"${protocol}://${account_name}.blob.core.windows.net/${results_container_name}?${sas}\"\n  if [ $VM_COUNT -gt 1 ]; then\n    job_start_time=$(date -u -d \"5 minutes\" '+%Y-%m-%dT%H:%M:%SZ') # date in ISO 8601 format\n  else\n    job_start_time=$(date -u '+%Y-%m-%dT%H:%M:%SZ') # date in ISO 8601 format\n  fi\n\n  latest_table_entry=$(az storage entity insert --entity PartitionKey=\"${tool_api}\" RowKey=\"${GUID}\" JobStartTime=$job_start_time JobFinishTime=\"\" JobStatus=\"Started\" NoOfClientsCompleted=0 NoOfClientsStarted=1 SAS_URL=$result_storage_url --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING)\n  if [ -z \"$latest_table_entry\" ]; then\n    echo \"Error while accessing storage account, exiting from this machine\"\n    exit 1\n  fi\nelse\n  for i in $(seq 1 10); do\n    latest_table_entry=$(az storage entity show --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --partition-key \"${tool_api}\" --row-key \"${GUID}\")\n    if [ -z \"$latest_table_entry\" ]; then\n      echo \"sleeping for 1 min, table row not availble yet\"\n      sleep 1m\n      continue\n    fi\n    job_start_time=$(echo $latest_table_entry | jq .JobStartTime)\n    result_storage_url=$(echo $latest_table_entry | jq .SAS_URL)\n    break\n  done\n  if [ -z \"$job_start_time\" ] || [ -z \"$result_storage_url\" ]; then\n    echo \"Error while getting job_start_time/result_storage_url, exiting from this machine\"\n    exit 1\n  fi\n  for j in $(seq 1 60); do\n    etag=$(echo $latest_table_entry | jq .etag)\n    etag=${etag:1:-1}\n    etag=$(echo \"$etag\" | tr -d '\\')\n    no_of_clients_started=$(echo $latest_table_entry | jq .NoOfClientsStarted)\n    no_of_clients_started=$(echo \"$no_of_clients_started\" | tr -d '\"')\n    no_of_clients_started=$((no_of_clients_started + 1))\n    echo \"Updating latest table entry with incremented NoOfClientsStarted\"\n    replace_entry_result=$(az storage entity merge --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --entity PartitionKey=\"${tool_api}\" RowKey=\"${GUID}\" NoOfClientsStarted=$no_of_clients_started --if-match=$etag)\n    if [ -z \"$replace_entry_result\" ]; then\n      echo \"Hit race condition on table entry for updating no_of_clients_started\"\n      sleep 1s\n    else\n      echo \"NoOfClientsStarted updated\"\n      break\n    fi\n    echo \"Reading latest table entry for updating NoOfClientsStarted\"\n    latest_table_entry=$(az storage entity show --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --partition-key \"${tool_api}\" --row-key \"${GUID}\")\n  done\n  ## Removing quotes from the job_start_time and result_storage_url retrieved from table\n  job_start_time=${job_start_time:1:-1}\n  result_storage_url=${result_storage_url:1:-1}\nfi\n\n## converting job_start_time into seconds\njob_start_time=$(date -d \"$job_start_time\" +'%s')\n\n# Clearing log file from last run if applicable\nsudo rm -f /tmp/ycsb.log\n\n#Execute YCSB test\nif [ \"$WRITE_ONLY_OPERATION\" = True ] || [ \"$WRITE_ONLY_OPERATION\" = true ]; then\n  now=$(date +\"%s\")\n  wait_interval=$(($job_start_time - $now))\n  if [ $wait_interval -gt 0 ] && [ $VM_COUNT -gt 1 ]; then\n    echo \"Sleeping for $wait_interval second to sync with other clients\"\n    sleep $wait_interval\n  else\n    echo \"Not sleeping on clients sync time $job_start_time as it already past\"\n  fi\n  ## Records count for write only ops which start with items count created by previous(machine_index -1) client machine\n  recordcountForWriteOps=$((YCSB_OPERATION_COUNT * MACHINE_INDEX))\n  ## Execute run phase for YCSB tests with write only workload\n  echo \"########## Run operation with write only workload for YCSB tests ###########\"\n  uri=$COSMOS_URI primaryKey=$COSMOS_KEY workload_type=$WORKLOAD_TYPE ycsb_operation=\"run\" insertproportion=1 readproportion=0 updateproportion=0 scanproportion=0 recordcount=$recordcountForWriteOps operationcount=$YCSB_OPERATION_COUNT threads=$THREAD_COUNT target=$TARGET_OPERATIONS_PER_SECOND useGateway=$USE_GATEWAY diagnosticsLatencyThresholdInMS=$DIAGNOSTICS_LATENCY_THRESHOLD_IN_MS requestdistribution=$REQUEST_DISTRIBUTION insertorder=$INSERT_ORDER includeExceptionStackInLog=$INCLUDE_EXCEPTION_STACK fieldcount=$FIELD_COUNT appInsightConnectionString=$APP_INSIGHT_CONN_STR preferredRegionList=$PREFERRED_REGION_LIST bash $DB_BINDING_NAME-run.sh\nelse\n  if [ \"$SKIP_LOAD_PHASE\" = False ] || [ \"$SKIP_LOAD_PHASE\" = false ]; then\n    ## Execute load operation for YCSB tests\n    echo \"########## Load operation for YCSB tests ###########\"\n    ## Reducing the load phase RPS by decreasing the number of YCSB threads to eliminate throttling. The Throughput used for transaction phase is generally lesser than that is required for load phase resulting in throttling. \n    loadthreadcount=$((THREAD_COUNT / 5))\n    if [ $loadthreadcount -eq 0 ];then \n      loadthreadcount=1\n    fi\n    echo \"##########loadthreadcount###########: $loadthreadcount\"   \n    uri=$COSMOS_URI primaryKey=$COSMOS_KEY workload_type=$WORKLOAD_TYPE ycsb_operation=\"load\" recordcount=$recordcount insertstart=$insertstart insertcount=$YCSB_RECORD_COUNT threads=$loadthreadcount target=$TARGET_OPERATIONS_PER_SECOND useGateway=$USE_GATEWAY diagnosticsLatencyThresholdInMS=$DIAGNOSTICS_LATENCY_THRESHOLD_IN_MS requestdistribution=$REQUEST_DISTRIBUTION insertorder=$INSERT_ORDER includeExceptionStackInLog=$INCLUDE_EXCEPTION_STACK fieldcount=$FIELD_COUNT appInsightConnectionString=$APP_INSIGHT_CONN_STR core_workload_insertion_retry_limit=5 preferredRegionList=$PREFERRED_REGION_LIST bash $DB_BINDING_NAME-run.sh\n  fi\n  now=$(date +\"%s\")\n  wait_interval=$(($job_start_time - $now))\n  if [ $wait_interval -gt 0 ] && [ $VM_COUNT -gt 1 ]; then\n    echo \"Sleeping for $wait_interval second to sync with other clients\"\n    sleep $wait_interval\n  else\n    echo \"Not sleeping on clients sync time $job_start_time as it already past\"\n  fi\n  sudo rm -f \"$user_home/$VM_NAME-ycsb-load.log\"\n  cp /tmp/ycsb.log $user_home/\"$VM_NAME-ycsb-load.log\"\n  sudo azcopy copy $user_home/\"$VM_NAME-ycsb-load.log\" \"$result_storage_url\"\n  # Clearing log file from above load operation\n  sudo rm -f /tmp/ycsb.log\n\n  ## Execute run phase for YCSB tests\n  echo \"########## Run operation for YCSB tests ###########\"\n  uri=$COSMOS_URI primaryKey=$COSMOS_KEY workload_type=$WORKLOAD_TYPE ycsb_operation=\"run\" recordcount=$totalrecordcount operationcount=$YCSB_OPERATION_COUNT threads=$THREAD_COUNT target=$TARGET_OPERATIONS_PER_SECOND insertproportion=$INSERT_PROPORTION readproportion=$READ_PROPORTION updateproportion=$UPDATE_PROPORTION scanproportion=$SCAN_PROPORTION useGateway=$USE_GATEWAY diagnosticsLatencyThresholdInMS=$DIAGNOSTICS_LATENCY_THRESHOLD_IN_MS requestdistribution=$REQUEST_DISTRIBUTION insertorder=$INSERT_ORDER includeExceptionStackInLog=$INCLUDE_EXCEPTION_STACK fieldcount=$FIELD_COUNT appInsightConnectionString=$APP_INSIGHT_CONN_STR preferredRegionList=$PREFERRED_REGION_LIST bash $DB_BINDING_NAME-run.sh\nfi\n\n#Copy YCSB log to storage account\necho \"########## Copying Results to Storage ###########\"\n# Clearing log file from last run if applicable\nsudo rm -f $user_home/\"$VM_NAME-ycsb.log\"\ncp /tmp/ycsb.log $user_home/\"$VM_NAME-ycsb.log\"\nsudo python3 converting_log_to_csv.py $user_home/\"$VM_NAME-ycsb.log\"\nsudo azcopy copy \"$VM_NAME-ycsb.csv\" \"$result_storage_url\"\nsudo azcopy copy \"$user_home/$VM_NAME-ycsb.log\" \"$result_storage_url\"\nsudo mkdir \"/tmp/$VM_NAME-system-diagnostics\"\nsudo mv /tmp/cosmos_client_logs \"/tmp/$VM_NAME-system-diagnostics\"\nsudo cp \"$user_home/agent.out\" \"$user_home/agent.err\" \"/tmp/$VM_NAME-system-diagnostics\"\nsudo azcopy copy \"/tmp/$VM_NAME-system-diagnostics\" \"$result_storage_url\" --recursive=true\n\nif [ $MACHINE_INDEX -eq 1 ]; then\n  if [ $VM_COUNT -gt 1 ]; then\n    for j in $(seq 1 12); do\n      latest_table_entry=$(az storage entity show --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --partition-key \"${tool_api}\" --row-key \"${GUID}\")\n      no_of_clients_completed=$(echo $latest_table_entry | jq .NoOfClientsCompleted)\n      echo \"Total number of clients completed $no_of_clients_completed\"\n      if [ $no_of_clients_completed -ge $(($VM_COUNT - 1)) ]; then\n        break\n      else\n        echo \"Waiting on Master for 5 min\"\n        sleep 5m\n      fi\n    done\n  fi\n  cd $user_home\n  mkdir \"aggregation\"\n  cd aggregation\n  # Clearing aggregation folder from last run if applicable\n  sudo rm *\n  index_for_regex=$(expr index \"$result_storage_url\" '?')\n  regex_to_append=\"/*\"\n  url_first_part=$(echo $result_storage_url | cut -c 1-$((index_for_regex - 1)))\n  url_second_part=$(echo $result_storage_url | cut -c $((index_for_regex))-${#result_storage_url})\n  new_storage_url=\"$url_first_part$regex_to_append$url_second_part\"\n  aggregation_dir=\"$user_home/aggregation\"\n  sudo azcopy copy $new_storage_url $aggregation_dir --recursive=true\n  sudo rm -rf $aggregation_dir/*load.log\n  sudo python3 /tmp/ycsb/$ycsb_folder_name/aggregate_multiple_file_results.py $aggregation_dir\n  sudo azcopy copy aggregation.csv \"$result_storage_url\"\n\n  #Updating table entry to change JobStatus to 'Finished' and increment NoOfClientsCompleted\n  echo \"Reading latest table entry\"\n  latest_table_entry=$(az storage entity show --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --partition-key \"${tool_api}\" --row-key \"${GUID}\")\n  etag=$(echo $latest_table_entry | jq .etag)\n  etag=${etag:1:-1}\n  etag=$(echo \"$etag\" | tr -d '\\')\n  no_of_clients_completed=$(echo $latest_table_entry | jq .NoOfClientsCompleted)\n  no_of_clients_completed=$(echo \"$no_of_clients_completed\" | tr -d '\"')\n  no_of_clients_completed=$((no_of_clients_completed + 1))\n  finish_time=\"$(date '+%Y-%m-%dT%H:%M:%SZ')\"\n  echo \"Updating latest table entry with incremented NoOfClientsCompleted\"\n  az storage entity merge --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --entity PartitionKey=\"${tool_api}\" RowKey=\"${GUID}\" JobFinishTime=$finish_time JobStatus=\"Finished\" NoOfClientsCompleted=$no_of_clients_completed --if-match=$etag\n  echo \"Job finished sucessfully at $finish_time\"\nelse\n  for j in $(seq 1 60); do\n    echo \"Reading latest table entry for updating NoOfClientsCompleted\"\n    latest_table_entry=$(az storage entity show --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --partition-key \"${tool_api}\" --row-key \"${GUID}\")\n    etag=$(echo $latest_table_entry | jq .etag)\n    etag=${etag:1:-1}\n    etag=$(echo \"$etag\" | tr -d '\\')\n    no_of_clients_completed=$(echo $latest_table_entry | jq .NoOfClientsCompleted)\n    no_of_clients_completed=$(echo \"$no_of_clients_completed\" | tr -d '\"')\n    no_of_clients_completed=$((no_of_clients_completed + 1))\n    echo \"Updating latest table entry with incremented NoOfClientsCompleted\"\n    replace_entry_result=$(az storage entity merge --table-name \"${benchmarkname}Metadata\" --connection-string $RESULT_STORAGE_CONNECTION_STRING --entity PartitionKey=\"${tool_api}\" RowKey=\"${GUID}\" NoOfClientsCompleted=$no_of_clients_completed --if-match=$etag)\n    if [ -z \"$replace_entry_result\" ]; then\n      echo \"Hit race condition on table entry for updating no_of_clients_completed\"\n      sleep 1s\n    else\n      echo \"Task finished sucessfully\"\n      break\n    fi\n  done\nfi\n", "num_lines": 279}
{"repo_name": "azure-db-benchmarking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\ncloud-init status --wait\necho \"##########CUSTOM_SCRIPT_URL###########: $CUSTOM_SCRIPT_URL\"\n# Running custom-script in background, arm template completion wont wait on this\n# stdout and stderr will be logged in <$HOME>/custom-script.out and <$HOME>/custom-script.err\ncurl -o custom-script.sh $CUSTOM_SCRIPT_URL\nnohup bash custom-script.sh > \"/home/${ADMIN_USER_NAME}/agent.out\" 2> \"/home/${ADMIN_USER_NAME}/agent.err\" &\n", "num_lines": 12}
{"repo_name": "azure-db-benchmarking", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT License.\n\nif [ -z \"$workload_type\" ]; then\n    workload=workloada\nelse\n    workload=$workload_type\nfi\n\nif [ -z \"$ycsb_operation\" ]; then\n    operation=load\nelse\n    operation=$ycsb_operation\nfi\n\n# Updating workload file\nif [ ! -z \"$recordcount\" ]; then\n   sed -i \"s/^[#]*\\s*recordcount=.*/recordcount=$recordcount/\" workloads/$workload\nfi\n\nif [ ! -z \"$operationcount\" ]; then\n   sed -i \"s/^[#]*\\s*operationcount=.*/operationcount=$operationcount/\" workloads/$workload\nfi\n\nif [ ! -z \"$insertstart\" ]; then\n   sed -i \"$ ainsertstart=$insertstart\" workloads/$workload\nfi\n\nif [ ! -z \"$insertcount\" ]; then\n   sed -i \"$ ainsertcount=$insertcount\" workloads/$workload\nfi\n\nif [ ! -z \"$insertorder\" ]; then\n   sed -i \"$ ainsertorder=$insertorder\" workloads/$workload\nfi\n\nif [ ! -z \"$fieldcount\" ]; then\n   sed -i \"$ afieldcount=$fieldcount\" workloads/$workload\nfi\n\nif [ ! -z \"$core_workload_insertion_retry_limit\" ]; then\n   sed -i \"$ acore_workload_insertion_retry_limit=$core_workload_insertion_retry_limit\" workloads/$workload\nfi\n\nif [ ! -z \"$readproportion\" ]; then\n   sed -i \"s/^[#]*\\s*readproportion=.*/readproportion=$readproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$updateproportion\" ]; then\n   sed -i \"s/^[#]*\\s*updateproportion=.*/updateproportion=$updateproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$scanproportion\" ]; then\n   sed -i \"s/^[#]*\\s*scanproportion=.*/scanproportion=$scanproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$insertproportion\" ]; then\n   sed -i \"s/^[#]*\\s*insertproportion=.*/insertproportion=$insertproportion/\" workloads/$workload\nfi\n\nif [ ! -z \"$requestdistribution\" ]; then\n   sed -i \"s/^[#]*\\s*requestdistribution=.*/requestdistribution=$requestdistribution/\" workloads/$workload\nfi\n\n\n# REQUIRED URI\nif [ ! -z \"$uri\" ]; then\n   uri_esc=$(sed 's/[\\*\\.&]/\\\\&/g' <<<\"$uri\")\n   sed -i \"s|^[#]*\\s*mongodb.url\\ =.*|mongodb.url\\ =\\ $uri_esc|\" mongodb.properties\nfi\n\n\nlog_filename=\"/tmp/ycsb.log\"\n\nif [ ! -z \"$threads\" ] && [ ! -z \"$target\" ]\nthen\n  ./bin/ycsb.sh $operation mongodbreactivestreams -P workloads/$workload -P mongodb.properties -s -threads $threads -target $target 2>&1 | tee -a \"$log_filename\"\nelif [ ! -z \"$threads\" ]\nthen\n  ./bin/ycsb.sh $operation mongodbreactivestreams -P workloads/$workload -P mongodb.properties -s -threads $threads 2>&1 | tee -a \"$log_filename\"\nelif [ ! -z \"$target\" ]\nthen\n  ./bin/ycsb.sh $operation mongodbreactivestreams -P workloads/$workload -P mongodb.properties -s -target $target 2>&1 | tee -a \"$log_filename\"\nelse\n  ./bin/ycsb.sh $operation mongodbreactivestreams -P workloads/$workload -P mongodb.properties -s 2>&1 | tee -a \"$log_filename\"\nfi\n", "num_lines": 89}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Stop script on non-zero exit code\nset -e\n# Stop script if unbound variable found (use ${var:-} if intentional)\nset -u\n\nsay_error() {\n    printf \"install-azd-report: ERROR: %b\\n\" \"$1\" >&2\n}\n\nsay() {\n    printf \"install-azd-report: %b\\n\" \"$1\"\n}\n\nsay_verbose() {\n    if [ \"$verbose\" = true ]; then\n        say \"$1\"\n    fi\n}\n\nget_platform() {\n    local platform_raw\n    platform_raw=\"$(uname -s)\";\n\n    if [ \"$platform_raw\" = \"Linux\" ]; then\n        echo 'linux';\n        return 0;\n    elif [ \"$platform_raw\" = \"Darwin\" ]; then\n        echo 'darwin';\n        return 0;\n    else\n        say_error \"Platform not supported: $platform_raw\";\n        return 1;\n    fi\n}\n\nget_os() {\n    local platform\n    platform=\"$(get_platform)\"\n\n    if [ \"$platform\" = \"linux\"  ]; then\n        # shellcheck source=/dev/null\n        source /etc/os-release && echo \"$ID\"\n    elif [ \"$platform\" = \"darwin\" ]; then\n        echo \"MacOS\"\n    else\n        echo \"error\"\n    fi\n}\n\nget_os_version() {\n    local platform\n    platform=\"$(get_platform)\"\n    # shellcheck source=/dev/null\n\n    if [ \"$platform\" = \"linux\"  ]; then\n        # shellcheck source=/dev/null\n        source /etc/os-release && echo \"$VERSION_ID\"\n    elif [ \"$platform\" = \"darwin\" ]; then\n        sw_vers -productVersion\n    else\n        echo \"error\"\n    fi\n}\n\nget_is_wsl() {\n    local platform\n    platform=\"$(get_platform)\"\n\n    if [ \"$platform\" != \"linux\" ]; then\n        echo \"false\"\n        return\n    fi \n\n\n    local kernel_release\n    kernel_release=$(uname --kernel-release)\n\n    # Lower-case $kernel_release for a case-insensitive compare\n    # Assumes a\n    if [[ \"${kernel_release,,}\" == *\"wsl\"* ]]; then\n        echo \"true\"\n    else\n        echo \"false\"\n    fi\n}\n\nget_terminal () {\n    if [ -f \"/proc/$$/comm\" ]; then\n        echo \"$(</proc/$$/comm)\"\n    else\n        ps $$ -o comm=\n    fi\n}\n\nget_execution_environment() {\n    local env_gh_actions=${GITHUB_ACTIONS:-}\n    local env_system_teamprojectid=${SYSTEM_TEAMPROJECTID:-}\n\n    local execution_environment=\"Desktop\"\n    if [ -n \"$env_gh_actions\" ]; then\n        execution_environment=\"GitHub Actions\"\n    elif [ -n \"$env_system_teamprojectid\" ]; then\n        execution_environment=\"Azure DevOps\"\n    fi\n    echo \"$execution_environment\"\n}\n\nsend_report() {\n    local event_timestamp=$1\n    local event_name=$2\n    local reason=$3\n    local version=$4\n\n    local has_additional_items=0\n    if [ \"$#\" -gt 4 ]; then\n        has_additional_items=1\n        read -ra additional_items <<< \"$5\"\n    fi\n\n    local IKEY='a9e6fa10-a9ac-4525-8388-22d39336ecc2'\n    # Replace all \"-\" in IKEY with \"\"\n    local AI_EVENT_NAME=\"Microsoft.ApplicationInsights.${IKEY//-/}.Event\"\n\n    local timestamp os os_version is_wsl terminal execution_environment\n    timestamp=$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)\n    os=\"$(get_os)\"\n    os_version=\"$(get_os_version)\"\n    is_wsl=\"$(get_is_wsl)\"\n    terminal=\"$(get_terminal)\"\n    execution_environment=\"$(get_execution_environment)\"\n\n    # If there are additional items, add those to the report outputs\n    local additional_json=\"\"\n    local additional_table=\"\"\n    if [ \"$has_additional_items\" ]; then\n        for entry in \"${additional_items[@]}\"\n        do\n            # \"identifier:value:value_continued\" becomes:\n            # key=\"identifier\"\n            # value=\"value:value_continued\"\n            local key=${entry%%:*}\n            local value=${entry#*:}\n            additional_json=$(printf \"%s, \\\"%s\\\": \\\"%s\\\"\" \"$additional_json\" \"$key\" \"$value\")\n            additional_table=$(printf \"%s%s        \\t%s\\n\" \"$additional_table\" \"$key\" \"$value\")\n        done\n    fi\n\n    local json_template='{\n        \"iKey\": \"%s\",\n        \"name\": \"%s\",\n        \"time\": \"%s\",\n        \"data\": {\n            \"baseType\": \"EventData\",\n            \"baseData\": {\n                \"ver\": 2,\n                \"name\": \"%s\",\n                \"properties\": {\n                    \"installVersion\": \"%s\",\n                    \"reason\": \"%s\",\n                    \"os\": \"%s\",\n                    \"osVersion\": \"%s\",\n                    \"isWsl\": \"%s\",\n                    \"terminal\": \"%s\",\n                    \"executionEnvironment\": \"%s\",\n                    \"eventTimestamp\": \"%s\"\n                    %s\n                }\n            }\n        }\n    }'\n\n    local telemetry_json\n    telemetry_json=$(printf \"$json_template\" \\\n        \"$IKEY\" \\\n        \"$AI_EVENT_NAME\" \\\n        \"$timestamp\" \\\n        \"$event_name\" \\\n        \"$version\" \\\n        \"$reason\" \\\n        \"$os\" \\\n        \"$os_version\" \\\n        \"$is_wsl\" \\\n        \"$terminal\" \\\n        \"$execution_environment\" \\\n        \"$event_timestamp\" \\\n        \"$additional_json\"\n    )\n\n    local table=\"\nItem                  \\tValue\n===============================\ninstallVersion        \\t$version\nreason                \\t$reason\nos                    \\t$os\nosVersion             \\t$os_version\nisWsl                 \\t$is_wsl\nterminal              \\t$terminal\nexecutionEnvironment  \\t$execution_environment\n$additional_table\"\n\n    say \"Sending report for installer error:\"\n    say \"$table\"\n\n    if [ \"$dry_run\" = true ]; then\n        say_verbose \"Dry run. No telemetry posted.\"\n        return 0\n    fi\n\n    if ! curl \\\n        --silent \\\n        --out /dev/null \\\n        --fail \\\n        --show-error \\\n        --header \"Content-Type: application/json\" \\\n        --request POST \\\n        --data \"$telemetry_json\" \\\n        \"https://centralus-2.in.applicationinsights.azure.com/v2/track\";\n    then\n        say_verbose \"curl returned exit code: $?\"\n        return \"$?\"\n    else\n        say_verbose \"Report sent\"\n        return 0\n    fi\n}\n\nverbose=false\nerror_logs_file=\"$HOME/.azd/installer-error.log\"\ndry_run=false\n\nwhile [[ $# -ne 0 ]];\ndo\n  name=\"$1\"\n  case \"$name\" in\n    -f|--file)\n        shift\n        error_logs_file=\"$1\"\n        ;;\n    --dry-run)\n        dry_run=true\n        ;;\n    -v|--verbose)\n        verbose=true\n        ;;\n    -h|-?|--help)\n        script_name=\"$(basename \"$0\")\"\n        echo \"Azure Dev CLI Installer\"\n        echo \"Usage: $script_name [--version <VERSION>] [--install-location <LOCATION>]\"\n        echo \"       $script_name -h|-?|--help\"\n        echo \"\"\n        echo \"$script_name is a simple command for downloading and installing the azd CLI\"\n        echo \"\"\n        echo \"Options:\"\n        echo \"\"\n        echo \"  --file                        Error logging file (default: $error_logs_file)\"\n        echo \"\"\n        echo \"  --verbose                     Enable verbose logging\"\n        exit 0\n        ;;\n    *)\n        say_error \"Unknown argument $name\"\n        exit 1\n        ;;\n  esac\n  shift\ndone\n\n# Lowercase the value of AZURE_DEV_COLLECT_TELEMETRY\nenv_collect_telemetry=${AZURE_DEV_COLLECT_TELEMETRY:-}\ncollect_telemetry=$(echo \"$env_collect_telemetry\" | tr \"[:upper:]\" \"[:lower:]\")\n\n# If user has opted out of telemetry return immediately\nif [ \"$collect_telemetry\" = \"no\" ]; then\n    say \"Telemetry disabled. No error report data will be reported.\"\n    exit 0\nfi\n\nif [ ! -f \"$error_logs_file\" ]; then\n    say \"No log file found at $error_logs_file\"\n    exit 0\nfi\n\n\nerror_count=0\nwhile IFS=\"|\" read -r timestamp event_name reason version additional_items_serialized\ndo\n    if ! send_report \"$timestamp\" \"$event_name\" \"$reason\" \"$version\" \"$additional_items_serialized\"; then\n        say_error \"Could not send report: $event_name at $timestamp.\"\n\n        # Append the failed error report into a file for further investigation.\n        # The file at $error_logs_file will be deleted to prevent\n        # re-sending of events that were successfully posted.\n        echo \"$timestamp|$event_name|$reason|$version|$additional_items_serialized\" >> \"$HOME/.azd/installer-error.err\"\n        say_verbose \"Event written $HOME/.azd/installer-error.err\"\n    fi\ndone < \"$error_logs_file\"\n\n# Done sending errors, delete logs to avoid re-sending errors on another run\nif [ ! \"$dry_run\" = true ]; then\n    say_verbose \"Removing $error_logs_file\"\n    rm \"$error_logs_file\"\nelse\n    say_verbose \"Dry run. Do not remove $error_logs_file\"\nfi\n\nif [ \"$error_count\" -gt 0 ]; then\n    say_error \"Encountered errors sending telemetry events. Log entries which could not be posted are in $HOME/.azd/installer-error.err\"\nfi\n", "num_lines": 311}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Stop script on non-zero exit code\nset -e\n# Stop script if unbound variable found (use ${var:-} if intentional)\nset -u\n\nsave_error_report_if_enabled() {\n    local event_name=$1\n    local reason=$2\n\n    local has_additional_items=0\n    if [ \"$#\" -gt 2 ]; then\n        has_additional_items=1\n        declare -a additional_items=(\"${!3}\")\n    fi\n\n    local timestamp\n    timestamp=$(date -u +%Y-%m-%dT%H:%M:%S.%NZ)\n\n    # Lowercase the value of AZURE_DEV_COLLECT_TELEMETRY\n    local env_collect_telemetry=${AZURE_DEV_COLLECT_TELEMETRY:-}\n    local collect_telemetry\n    collect_telemetry=$(echo \"$env_collect_telemetry\" | tr \"[:upper:]\" \"[:lower:]\")\n\n    # If user has opted out of telemetry return immediately\n    if [ \"$no_telemetry\" = 1 ] || [ \"$collect_telemetry\" = \"no\" ]; then\n        say_verbose \"Telemetry disabled. No error report data stored.\"\n        return\n    fi\n\n\n    local additional_items_serialized=\"\"\n    if [ \"$has_additional_items\" ]; then\n        for entry in \"${!additional_items[@]}\"\n        do\n            local entry_value=${additional_items[$entry]}\n            additional_items_serialized=$(printf \"%s|%s\" \"$additional_items_serialized\" \"$entry_value\")\n        done\n    fi\n\n    mkdir -p ~/.azd\n    echo \"$timestamp|$event_name|$reason|$version$additional_items_serialized\" >> ~/.azd/installer-error.log\n\n    say_error \"An error was encountered during install: $reason\"\n    say_error \"\"\n    say_error \"To send an error report to Microsoft, check that AZURE_DEV_COLLECT_TELEMETRY is not set and then run: \"\n    say_error \"curl -fsSL https://aka.ms/install-azd-report.sh | bash\"\n    say_error \"\"\n    say_error \"Running the above script will send data to Microsoft. To learn more about data collection see:\"\n    say_error \"https://go.microsoft.com/fwlink/?LinkId=521839\"\n    say_error \"\"\n    say_error \"You can also file an issue at https://github.com/Azure/azure-dev/issues/new?assignees=&labels=&template=issue_report.md&title=%5BIssue%5D\"\n}\n\nsay_error() {\n    printf \"install-azd: ERROR: %b\\n\" \"$1\" >&2\n}\n\nsay() {\n    printf \"install-azd: %b\\n\" \"$1\"\n}\n\nsay_verbose() {\n    if [ \"$verbose\" = true ]; then\n        say \"$1\"\n    fi\n}\n\ntrap 'catch_all' ERR\ncatch_all() {\n    say_error \"Unhandled error\"\n    save_error_report_if_enabled \"InstallFailed\" \"UnhandledError\"\n    exit 1\n}\n\nget_platform() {\n    local platform_raw\n    platform_raw=\"$(uname -s)\";\n\n    if [ \"$platform_raw\" = \"Linux\" ]; then\n        echo 'linux';\n        return 0;\n    elif [ \"$platform_raw\" = \"Darwin\" ]; then\n        echo 'darwin';\n        return 0;\n    else\n        say_error \"Platform not supported: $platform_raw\";\n        return 1;\n    fi\n}\n\nget_extension_for_platform() {\n    platform=$1\n\n    if [ \"$platform\" = \"linux\" ]; then\n        echo 'tar.gz';\n        return;\n    elif [ \"$platform\" = \"darwin\" ]; then\n        echo 'zip';\n        return;\n    else\n        say_error \"Platform not supported: $platform\";\n        exit 1;\n    fi;\n}\n\nget_architecture() {\n    local platform=$1\n    local architecture_raw\n    architecture_raw=\"$(uname -m)\"\n\n    if [ \"$architecture_raw\" = \"x86_64\" ]; then\n        echo 'amd64';\n        return;\n    elif [ \"$architecture_raw\" = \"arm64\" ] && [ \"$platform\" = 'darwin' ]; then\n        # In the case of Apple Silicon use the existing ARM64 environment\n        echo 'amd64';\n        return;\n    else\n        say_error \"Architecture not supported: $architecture_raw on platform: $platform\"\n        exit 1;\n    fi;\n}\n\nensure_rosetta() {\n    if [[ $(uname -m) == 'x86_64' ]]; then\n        # The current system is identified as an Intel system (either because it\n        # is running in Rosetta 2 or the system is running on Intel silicon) so\n        # Rosetta 2 is not needed.\n        say_verbose \"Detected x86_64 system. Rosetta 2 is not needed.\"\n        return\n    fi\n\n    if /usr/bin/pgrep oahd >/dev/null 2>&1; then\n        say \"Rosetta 2 is already installed and running. Nothing to do.\"\n    else\n        say \"Rosetta 2 is not installed. You may be prompted to accept terms necessary to install Rosetta 2.\"\n\n        # Ensure that softwareupdate gets input from the terminal\n        if /usr/sbin/softwareupdate --install-rosetta </dev/tty; then\n            say \"Rosetta has been successfully installed.\"\n        else\n            say_error \"Rosetta 2 installation failed!\"\n            save_error_report_if_enabled \"InstallFailed\" \"Rosetta2InstallFailed\"\n            exit 1\n        fi\n    fi\n}\n\nextract() {\n    local compressed_file=$1\n    local extract_location=$2\n\n    if [[ $compressed_file == *.zip ]]; then\n        unzip \"$compressed_file\" -d \"$extract_location\"/\n    elif [[ $compressed_file == *.tar.gz ]]; then\n        tar -zxvf \"$compressed_file\" -C \"$extract_location\"/\n    else\n        say_error \"Target file not supported: $compressed_file\";\n    fi\n}\n\nDEFAULT_BASE_URL=\"https://azure-dev.azureedge.net/azd/standalone/release\"\n\nbase_url=\"$DEFAULT_BASE_URL\"\nplatform=\"$(get_platform)\"\nextension=\"$(get_extension_for_platform \"$platform\")\"\nversion=\"stable\"\ndry_run=false\nskip_verify=false\nsymlink_folder=\"/usr/local/bin\"\ninstall_folder=\"/opt/microsoft/azd\"\nno_telemetry=0\nverbose=false\n\nwhile [[ $# -ne 0 ]];\ndo\n  name=\"$1\"\n  case \"$name\" in\n    -u|--base-url)\n        shift\n        base_url=\"$1\"\n        ;;\n    -e|--extension)\n        shift\n        extension=\"$1\"\n        ;;\n    -p|--platform)\n        shift\n        platform=\"$1\"\n        ;;\n    -a|--architecture)\n        shift\n        architecture=\"$1\"\n        ;;\n    --version)\n        shift\n        version=\"$1\"\n        ;;\n    --dry-run)\n        dry_run=true\n        ;;\n    --skip-verify)\n        skip_verify=true\n        ;;\n    -i|--install-folder)\n        shift\n        install_folder=\"$1\"\n        ;;\n    -s|--symlink-folder)\n        shift\n        symlink_folder=\"$1\"\n        ;;\n    --no-telemetry)\n        shift\n        no_telemetry=true\n        ;;\n    -v|--verbose)\n        verbose=true\n        ;;\n    -h|-?|--help)\n        script_name=\"$(basename \"$0\")\"\n        echo \"Azure Dev CLI Installer\"\n        echo \"Usage: $script_name [--version <VERSION>] [--install-location <LOCATION>]\"\n        echo \"       $script_name -h|-?|--help\"\n        echo \"\"\n        echo \"$script_name is a simple command for downloading and installing the azd CLI\"\n        echo \"\"\n        echo \"Options:\"\n        echo \"  -u, --base-url <URL>          Download from the specific base URL. Defaults to\"\n        echo \"                                $DEFAULT_BASE_URL\"\n        echo \"\"\n        echo \"  -e, --extension <EXTENSION>   Set the extension for the file to download.\"\n        echo \"                                Default is set based on the detected platform.\"\n        echo \"                                Possible values: zip, tar.gz\"\n        echo \"\"\n        echo \"  -p, --platform <PLATFORM>     Download for the specified PLATFORM. Default is\"\n        echo \"                                detected automatically.\"\n        echo \"\"\n        echo \"  -a, --architecture <ARCHITECTURE> Download for the specified ARCHITECTURE.\"\n        echo \"                                    Default is detected automatically.\"\n        echo \"\"\n        echo \"  --version <VERSION>           Download specific version. Default is 'latest'\"\n        echo \"                                which specifies the most recently released\"\n        echo \"                                version (GA or preview).\"\n        echo \"                                Possible values: <version>, latest, daily\"\n        echo \"\"\n        echo \"  --dry-run                     Do not download or install, just display the\"\n        echo \"                                download URL.\"\n        echo \"\"\n        echo \"  --skip-verify                 Skip verification of the downloaded file (macOS only).\"\n        echo \"\"\n        echo \"  -i,--install-folder <FOLDER>  Install azd CLI to FOLDER. Default is\"\n        echo \"                                /usr/local/bin\"\n        echo \"\"\n        echo \"  -t,--no-telemetry             Disable telemetry for failures. The installer\"\n        echo \"                                will prompt before sending any telemetry. In\"\n        echo \"                                non-interactive terminals telemetry will not\"\n        echo \"                                be sent and no prompt will be issued.\"\n        echo \"\"\n        echo \"  --verbose                     Enable verbose logging\"\n        exit 0\n        ;;\n    *)\n        say_error \"Unknown argument $name\"\n        exit 1\n        ;;\n  esac\n  shift\ndone\n\nif [ \"${architecture:-}\" = \"\" ]; then\n    architecture=\"$(get_architecture \"$platform\")\"\nfi\n\nif [ \"$symlink_folder\" != \"\" ] && [ ! -d \"$symlink_folder\" ]; then\n    say_error \"Symlink folder does not exist: $symlink_folder. The symlink folder should exist and be in \\$PATH\"\n    say_error \"Create the folder (and ensure that it is in your \\$PATH), specify a different folder using -s or --symlink-folder, or specify an empty value using -s \\\"\\\" or --symlink-folder \\\"\\\"\"\n    save_error_report_if_enabled \"InstallFailed\" \"SymlinkFolderDoesNotExist\"\n    exit 1\nfi\n\nsay_verbose \"Version: $version\"\nsay_verbose \"Platform: $platform\"\nsay_verbose \"Architecture: $architecture\"\nsay_verbose \"File extension: $extension\"\n\nif [ \"$platform\" = \"darwin\" ] && [ \"$architecture\" = \"amd64\" ]; then\n    say_verbose \"Mac detected, ensuring compatibility with amd64 binaries\"\n    ensure_rosetta\nfi\n\n# ARM64 bits are in beta, and so both the distribution package and the azd binary inside have a `-beta` suffix we\n# need to take into account.\nsuffix=\"\"\nif [ \"$architecture\" = \"arm64\" ]; then\n    suffix=\"-beta\"\nfi\n\nif [ -z \"$version\" ]; then\n    url=\"$base_url/azd-$platform-$architecture$suffix.$extension\"\nelse\n    url=\"$base_url/$version/azd-$platform-$architecture$suffix.$extension\"\nfi\n\nif [ \"$dry_run\" = true ]; then\n    say \"$url\"\n    exit 0;\nfi\n\ntmp_folder=\"$(mktemp -d)\";\ncompressed_file_path=\"$tmp_folder/azd-$platform-$architecture$suffix.$extension\"\nsay_verbose \"Downloading $url to $tmp_folder\"\n\nif ! curl -so \"$compressed_file_path\" \"$url\" --fail; then\n    say_error \"Could not download from $url, ensure platform and architecture are supported\"\n\n    # shellcheck disable=SC2034\n    declare -a additional=( \"downloadUrl:$url\" )\n    save_error_report_if_enabled \"InstallFailed\" \"DownloadFailure\" additional[@]\n    exit 1\nfi\n\nbin_name=\"azd-$platform-$architecture$suffix\"\nextract \"$compressed_file_path\" \"$tmp_folder\"\nrm \"$compressed_file_path\"\nchmod +x \"$tmp_folder/$bin_name\"\n\nsay_verbose \"Writing to $tmp_folder/.installed-by.txt\"\necho \"install-azd.sh\" > \"$tmp_folder/.installed-by.txt\"\n\nif [ \"$platform\" = \"darwin\" ] && [ \"$skip_verify\" = false ]; then\n    say_verbose \"Verifying signature of $bin_name\"\n    if ! output=$( codesign -v \"$tmp_folder/$bin_name\" 2>&1); then\n        say_error \"Could not verify signature of $bin_name, error output:\"\n        say_error \"$output\"\n        save_error_report_if_enabled \"InstallFailed\" \"SignatureVerificationFailure\"\n        exit 1\n    fi\nfi\n\nif [[ ! -d \"$install_folder\" ]]; then\n    say_verbose \"Install folder does not exist: $install_folder. Creating...\" \n\n    if ! mkdir -p \"$install_folder\"; then \n        say \"Creating $install_folder requires elevated permission. You may be prompted to enter credentials.\" \n        if ! sudo mkdir -p \"$install_folder\"; then\n            say_error \"Could not create install folder: $install_folder\"\n            save_error_report_if_enabled \"InstallFailed\" \"SudoMkdirFailure\"\n            exit 1\n        fi\n    fi\nfi\n\nmv_preface=\"\"\nif [ ! -w \"$install_folder/\" ]; then\n    say \"Writing to $install_folder/ requires elevated permission. You may be prompted to enter credentials.\"\n    mv_preface=\"sudo\"\nfi\nif ! $mv_preface mv -f \"$tmp_folder\"/* \"$tmp_folder\"/.*.txt \"$install_folder\"; then\n    say_error \"Could not move files to install location: $install_folder\"\n    save_error_report_if_enabled \"InstallFailed\" \"MoveFailure\"\n    exit 1\nfi\n\nif [ \"$symlink_folder\" != \"\" ]; then\n    ln_preface=\"\"\n    if [ ! -w \"$symlink_folder/\" ]; then\n        say \"Writing to $symlink_folder/ requires elevated permission. You may be prompted to enter credentials.\" \n        ln_preface=\"sudo\"\n    fi\n    if ! $ln_preface ln -fs \"$install_folder/$bin_name\" \"$symlink_folder/azd\"; then\n        say_error \"Could not create symlink to azd in $symlink_folder\"\n        save_error_report_if_enabled \"InstallFailed\" \"SymlinkCreateFailure\"\n        exit 1\n    fi\nfi\n\nsay_verbose \"Cleaning up temp folder: $tmp_folder\"\nrm -rf \"$tmp_folder\"\nsay \"Successfully installed to $install_folder\"\nif [ \"$symlink_folder\" != \"\" ]; then\n    say \"Symlink created at $symlink_folder/azd and pointing to $install_folder/$bin_name\"\nfi\nsay \"\"\nsay \"The Azure Developer CLI collects usage data and sends that usage data to Microsoft in order to help us improve your experience.\"\nsay \"You can opt-out of telemetry by setting the AZURE_DEV_COLLECT_TELEMETRY environment variable to 'no' in the shell you use.\"\nsay \"\"\nsay \"Read more about Azure Developer CLI telemetry: https://github.com/Azure/azure-dev#data-collection\"\n", "num_lines": 391}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# shellcheck disable=SC2002\n\nsay_error() {\n    printf \"test-sh-install-errors: ERROR: %b\\n\" \"$1\" >&2\n}\n\nsay() {\n    printf \"test-sh-install-errors: %b\\n\" \"$1\"\n}\n\necho \"Test install with invalid install folder\"\ninstall_folder_error=$(cat install-azd.sh | \"$1\" -s -- --no-telemetry --verbose --base-url \"$2\" --version \"$3\" --symlink-folder \"/symlink/folder/does/not/exist\" 2>&1)\n\nif [[ \"$install_folder_error\" != *\"Symlink folder does not exist\"* ]]; then\n    say_error \"Install should have notified the user that the folder does not exist\"\n    exit 1\nfi\n\nsay \"Test passed\"\nexit 0\n", "num_lines": 22}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# shellcheck disable=SC2002\n\nsay_error() {\n    printf \"test-sh-install: ERROR: %b\\n\" \"$1\" >&2\n}\n\nsay() {\n    printf \"test-sh-install: %b\\n\" \"$1\"\n}\n\nif ! cat ./install-azd.sh | \"$1\" -s -- --verbose --base-url \"$2\" --version \"$3\"; then\n    say_error \"Install failed\"\n    exit 1\nfi\n\nif ! grep -q \"install-azd.sh\" /opt/microsoft/azd/.installed-by.txt; then\n    echo \".installed-by.txt file content incorrect\" \n    exit 1\nfi\n\nif ! azd version; then\n    say_error \"azd version failed\"\n    exit 1\nfi\n\nif ! cat ./uninstall-azd.sh | \"$1\"; then\n    say_error \"Uninstall failed\"\n    exit 1\nfi\n\nif which azd; then\n    say_error \"Uninstall did not remove azd\"\n    exit 1\nfi\n\nif stat /opt/microsoft/azd; then\n    say_error \"Uninstall did not remove azd installation folder\"\n    exit 1\nfi\n\nsay \"Test passed\"\nexit 0", "num_lines": 43}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nset -u\n\nsay_error() {\n    printf \"test-telemetry-functions: ERROR: %b\\n\" \"$1\" >&2\n}\n\nsay() {\n    printf \"test-telemetry-functions: %b\\n\" \"$1\"\n}\n\n\nexpectation_location=${1:-telemetry.csv}\n\nbash -c './install-azd.sh --base-url \"127.0.0.1/error\" --verbose' | tee install_run.log\n# Use --dry-run to avoid sending test telemetry\nbash -c './install-azd-report.sh --verbose --dry-run' | tee install_report.log\n\nwhile IFS=, read -r expected_item;\ndo\n    IFS=','; read -ra match_params <<< \"$expected_item\"\n    needle=\"${match_params[0]}\"\n    expected=\"${match_params[1]}\"\n    found_item=0\n    while IFS= read -r line;\n    do\n        if [[ \"$line\" == \"$needle\"* ]]; then\n            if [[ \"$line\" == \"$needle\"*\"$expected\" ]]; then\n                found_item=1\n                break\n            else\n                say_error \"MISMATCH\"\n                say_error \"Term: $needle\"\n                say_error \"Expected: $expected\"\n                say_error \"Actual: $line\"\n                exit 1\n            fi\n        fi\n    done < install_report.log\n\n    if [ \"$found_item\" == 0 ]; then\n        say_error \"Could not find: $needle\"\n        exit 1\n    fi\n\ndone < \"$expectation_location\"\n\nsay \"Tests passed\"\n", "num_lines": 50}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsymlink_location=\"/usr/local/bin/azd\"\ninstall_root=\"/opt/microsoft/azd\"\n\nif [ ! -f \"$symlink_location\" ]; then\n    echo \"azd is not installed at $symlink_location. To install run 'curl -fsSL https://aka.ms/install-azd.sh | bash'\"\n    exit 1\nfi\n\nif ! rm \"$symlink_location\"; then\n    echo \"Writing to $symlink_location requires elevated permission. You may be prompted to enter credentials.\"\n    if ! sudo rm \"$symlink_location\"; then \n        echo \"Could not remove $symlink_location\" \n        exit 1\n    fi\nfi\n\nif [ ! -d \"$install_root\" ]; then \n    echo \"azd could not be found at $install_root. To install run 'curl -fsSL https://aka.ms/install-azd.sh | bash'\"\n    exit 1\nfi \n\nif ! rm -rf \"$install_root\"; then\n    echo \"Writing to $install_root requires elevated permission. You may be prompted to enter credentials.\"\n    if ! sudo rm -rf \"$install_root\"; then \n        echo \"Could not remove files from $install_root\" \n        exit 1\n    fi\nfi \n\nif [ -w \"$HOME/.azd/bin\" ]; then\n    if ! rm -rf \"$HOME/.azd/bin\"; then\n        echo \"Could not remove files in $HOME/.azd/bin. These will need to be removed manually\"\n    fi\nfi\n\necho \"\"\necho \"azd may have downloaded binaries to ~/.azd/bin and, depending on how azd was used on this machine,\"\necho \"may have downloaded binaries to other users' home directories in their .azd/bin directory.\"\necho \"These binaries will need to be removed manually.\"\necho \"To remove such binaries from your home directory, run 'rm -rf ~/.azd/bin'.\"\n\nstill_installed_location=\"$(command -v azd)\";\nif [ \"$still_installed_location\" ]; then\n    echo \"Uninstallation may not be complete: azd was still found at an unmanaged location ($still_installed_location). Please remove manually.\"\n    exit 1\nfi\n", "num_lines": 49}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"\"\necho \"====================================\"\necho \" Azure Developer CLI Install Notice \"\necho \"====================================\"\necho \"The Azure Developer CLI collects usage data and sends that usage data to Microsoft in order to help us improve your experience.\"\necho \"You can opt-out of telemetry by setting the AZURE_DEV_COLLECT_TELEMETRY environment variable to 'no' in the shell you use.\"\necho \"\"\necho \"Read more about Azure Developer CLI telemetry: https://github.com/Azure/azure-dev#data-collection\"\necho \"\"\n", "num_lines": 12}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\napt install ./azd_*.deb -f -y && azd version || exit 1\n\nif ! grep -q \"deb\" /opt/microsoft/azd/.installed-by.txt; then\n    echo \".installed-by.txt file content incorrect\" \n    exit 1\nfi\n\ndpkg -r azd || exit 1\n\nif command azd; then\n    echo \"azd NOT UNINSTALLED\"\n    exit 1\nelse \n    echo \"azd uninstall successful\"\nfi\n", "num_lines": 18}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\npwd\n\nyum install -y ./azd-*.rpm && azd version || exit 1\n\nif ! grep -q \"rpm\" /opt/microsoft/azd/.installed-by.txt; then\n    echo \".installed-by.txt file content incorrect\" \n    exit 1\nfi\n\nyum remove -y azd || exit 1\n\nif command azd; then\n    echo \"azd NOT UNINSTALLED\"\n    exit 1\nelse \n    echo \"azd uninstall successful\"\nfi\n", "num_lines": 20}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [ -w \"$HOME/.azd/bin\" ]; then\n    if ! rm -rf \"$HOME/.azd/bin\"; then\n        echo \"Could not remove files in $HOME/.azd/bin. These will need to be removed manually\"\n    fi\nfi\n\necho \"\"\necho \"======================================\"\necho \" Azure Developer CLI Uninstall Notice \"\necho \"======================================\"\necho \"The Azure Developer CLI may have downloaded binaries to ~/.azd/bin and,\"\necho \"depending on how azd was used on this machine, may have downloaded binaries\"\necho \"to other users' home directories in their .azd/bin directory.\"\necho \"These binaries will need to be removed manually.\"\necho \"To remove such binaries from your home directory, run 'rm -rf ~/.azd/bin'.\"\necho \"\"\n", "num_lines": 19}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "DATABASE_FQDN=$1\nAPPLICATION_IDENTITY_APPID=$2\nDATABASE_NAME=$3\nAAD_ADMIN_USER_NAME=$4\nCUSTOM_ROLE=$5\n\nsleep 60;\n\necho \"PostgreSQL Server creating AD role in database ${DATABASE_NAME} on ${DATABASE_FQDN}...\"\n\nif [ \"${ARM_CLIENT_ID}\" != \"\" ] && [ \"${ARM_CLIENT_SECRET}\" != \"\" ] && [ \"${ARM_TENANT_ID}\" != \"\" ];then\n  az login --service-principal -u ${ARM_CLIENT_ID} -p ${ARM_CLIENT_SECRET} --tenant ${ARM_TENANT_ID}\nfi\n\nRDBMS_ACCESS_TOKEN=$(az account get-access-token --resource-type oss-rdbms --output tsv --query accessToken)\n\npsql \"host=${DATABASE_FQDN} user=${AAD_ADMIN_USER_NAME} dbname=postgres port=5432 password=${RDBMS_ACCESS_TOKEN} sslmode=require\" <<EOF\n\nselect * from pgaadauth_create_principal_with_oid('${CUSTOM_ROLE}', '${APPLICATION_IDENTITY_APPID}', 'service', false, false);\n\nEOF", "num_lines": 21}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n# Default to user HOME directory if not specified\nFOLDER_PATH=$HOME\n# Default to current logged in user if not specified\nENV_NAME_PREFIX=$(whoami)\nTEMPLATE_NAME=\"\"\nENV_SUFFIX=\"\"\n\nfunction usage {\n    echo \"Deletes azd template\"\n    echo \"\"\n    echo \"Usage: delete-test-templates -t <template> -b <branch> -e <env_prefix>\" 2>&1\n    echo \"\"\n    echo \"  -u    Sets the environment suffix (required)\"\n    echo \"  -e    Sets the environment name prefix. Environment prefix is used in the azd environment name along with the template name (default: whoami)\"\n    echo \"  -f    Sets the root folder on the local machine for the test projects to be generated (default: User's HOME folder)\"\n    echo \"  -t    Sets the template name. Use values from 'azd template list'. When omitted will run for all templates available in 'azd template list'\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  Deleting all templates with default values (must have environment suffix)\"\n    echo \"      bash ./delete-test-templates.sh -u \\\"<env_suffix>\\\"\"\n\n    exit 1\n}\n\nwhile getopts \"f:t:e:u:h\" arg; do\n    case ${arg} in\n    f) FOLDER_PATH=$OPTARG ;;\n    t) TEMPLATE_NAME=$OPTARG ;;\n    e) ENV_NAME_PREFIX=$OPTARG ;;\n    u) ENV_SUFFIX=$OPTARG ;;\n    h)\n        usage\n        ;;\n    :)\n        echo \"$0: Must supply an argument to -$arg.\" >&2\n        exit 1\n        ;;\n    ?)\n        echo \"Invalid option -$arg.\"\n        exit 2\n        ;;\n    *) usage ;;\n    esac\ndone\n\n# Cleans the specified template\n# $1 - The environment name\nfunction cleanupTemplate {\n    echo \"Deprovisioning infrastructure for $1...\"\n    cd \"$FOLDER_PATH/$1\"\n    azd down -e \"$1\" --force --purge\n\n    echo \"Cleaning up local project @ '$FOLDER_PATH/$1'...\"\n    rm -rf \"$FOLDER_PATH/${1:?}\"\n}\n\nif [[ -z $ENV_SUFFIX ]]; then\n    echo \"Must pass in environment suffix\"\n    echo \"Examples:\"\n    echo \"      bash ./delete-test-templates.sh -u \\\"<env_suffix>\\\"\"\n    exit 0\nelse\n    if [[ -z $TEMPLATE_NAME ]]; then\n        declare -A ENV_TEMPLATE_MAP\n\n        # If a template is not specified, run for all templates from output of 'azd template list'\n        echo \"Getting list of available templates...\"\n        TEMPLATES_JSON=$(azd template list --output json)\n\n        while read -r TEMPLATE; do\n            ENV_NAME=\"${ENV_NAME_PREFIX}-${TEMPLATE:14}-$ENV_SUFFIX\"\n            ENV_TEMPLATE_MAP[$TEMPLATE]=$ENV_NAME\n        done < <(echo \"$TEMPLATES_JSON\" | jq -r '.[].name' | sed 's/\\\\n/\\n/g')\n\n        # Cleanup the templates in parallel\n        for TEMPLATE in \"${!ENV_TEMPLATE_MAP[@]}\"; do\n            (cleanupTemplate \"${ENV_TEMPLATE_MAP[$TEMPLATE]}\" || continue) &\n        done\n\n        wait\n\n        echo \"\"\n        echo \"Done!\"\n\n    else\n        # Delete test for the specified template name\n        ENV_NAME=\"${ENV_NAME_PREFIX}-${TEMPLATE_NAME:14}-$ENV_SUFFIX\"\n        cleanupTemplate \"$ENV_NAME\"\n\n    fi\nfi", "num_lines": 94}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -euo pipefail\n\n# Default to user HOME directory if not specified\nFOLDER_PATH=$HOME\n# Default to 'main' if not specified\nBRANCH_NAME=\"main\"\n# Default to current logged in user if not specified\nENV_NAME_PREFIX=$(whoami)\nTEMPLATE_NAME=\"\"\nPLAYWRIGHT_RETRIES=\"1\"\nPLAYWRIGHT_REPORTER=\"list\"\nLOCATION=\"eastus2\"\nSUBSCRIPTION=\"2cd617ea-1866-46b1-90e3-fffb087ebf9b\"\n# Default to a random value if not specified\nENV_SUFFIX=\"$RANDOM\"\n# When set will only run tests without deployments\nTEST_ONLY=false\n# When set will clean up local and remote resources\nCLEANUP=true\n# Used for internal pipeline testing. When set will skip azd init\nDEVCONTAINER=false\n\nfunction usage {\n    echo \"Tests azd template init, provision & deploy\"\n    echo \"\"\n    echo \"Usage: test-templates -t <template> -b <branch> -s <subscription_id> -u <env_prefix>\" 2>&1\n    echo \"\"\n    echo \"  -f    Sets the root folder on the local machine for the test projects to be generated (default: User's HOME folder)\"\n    echo \"  -b    Sets the template branch name. Override to test a any custom branches (default: main)\"\n    echo \"  -e    Sets the environment name prefix. Environment prefix is used in the azd environment name along with the template name (default: whoami)\"\n    echo \"  -t    Sets the template name. Use values from 'azd template list'. When omitted will run for all templates available in 'azd template list'\"\n    echo \"  -r    Sets the number of retries for playwright tests (default: 1)\"\n    echo \"  -p    Sets the reporter for playwright tests (default: list)\"\n    echo \"  -l    Sets the Azure location for the template tests to run in (default: eastus2)\"\n    echo \"  -s    Sets the Azure subscription name or ID for the template tests to run in. (default: 2cd617ea-1866-46b1-90e3-fffb087ebf9b)\"\n    echo \"  -u    Sets the environment suffix (default: RANDOM)\"\n    echo \"  -n    When set will only run test commands. If true script won't deploy the templates. This is helpful when you already have the environments provisioned and you want to re-run the tests (default: false)\"\n    echo \"  -c    when set will clean up resources (default: true)\"\n    echo \"\"\n    echo \"Examples:\"\n    echo \"  Testing a single template with custom branch\"\n    echo \"      bash ./test-templates.sh -t \\\"Azure-Samples/todo-nodejs-mongo\\\" -b \\\"<custom_branch_name>\\\"\"\n    echo \"\"\n    echo \"  Testing all templates with default values\"\n    echo \"      bash ./test-templates.sh\"\n\n    exit 1\n}\n\nwhile getopts \"f:t:b:e:r:p:l:s:u:n:c:h:d\" arg; do\n    case ${arg} in\n    f) FOLDER_PATH=$OPTARG ;;\n    t) TEMPLATE_NAME=$OPTARG ;;\n    b) BRANCH_NAME=$OPTARG ;;\n    e) ENV_NAME_PREFIX=$OPTARG ;;\n    r) PLAYWRIGHT_RETRIES=$OPTARG ;;\n    p) PLAYWRIGHT_REPORTER=$OPTARG ;;\n    l) LOCATION=$OPTARG ;;\n    s) SUBSCRIPTION=$OPTARG ;;\n    u) ENV_SUFFIX=$OPTARG ;;\n    n) TEST_ONLY=true ;;\n    c) CLEANUP=$OPTARG ;;\n    d) DEVCONTAINER=true ;;\n    h)\n        usage\n        ;;\n    :)\n        echo \"$0: Must supply an argument to -$arg.\" >&2\n        exit 1\n        ;;\n    ?)\n        echo \"Invalid option -$arg.\"\n        exit 2\n        ;;\n    *) usage ;;\n    esac\ndone\n\n# Deploys the specified template\n# $1 - The template name\n# $2 - The branch name\n# $3 - The environment name\n# $4 - The Azure subscription name or ID\n# $5 - The Azure location\n# $6 - The Devcontainer Test\nfunction deployTemplate {\n    if [ $DEVCONTAINER == false ]; then\n        echo \"Creating new project folder @ '$FOLDER_PATH/$3'...\"\n        cd \"$FOLDER_PATH\"\n        mkdir \"$3\"\n        cd \"$3\"\n\n        echo \"Initializing template '$1' with branch '$2'\"\n        azd init -t \"$1\" -b \"$2\" -e \"$3\" --subscription \"$4\" --location \"$5\" --no-prompt\n    else\n        echo \"Setting environment name '$3'\"\n        azd env new \"$3\" --subscription \"$4\" --location \"$5\" --no-prompt\n    fi\n\n    echo \"Provisioning infrastructure for $3...\"\n    azd provision -e \"$3\"\n\n    echo \"Deploying apps for $3...\"\n    azd deploy -e \"$3\"\n}\n\n# Tests the specified template\n# $1 - The template name\n# $2 - The branch name\n# $3 - The environment name\nfunction testTemplate {\n    if [[ \"$1\" == \"azd-starter\"* || \"$1\" == \"Azure-Samples/azd-starter\"* ]]; then\n        echo \"Skipped smoke tests for azd-starter templates\"\n        return\n    fi\n\n    echo \"Running template smoke tests for $3...\"\n    if [ $DEVCONTAINER == false ]; then\n        cd \"$FOLDER_PATH/$3/tests\"\n    else\n        cd \"tests\"\n    fi\n\n    npm i && npx playwright install\n    npx -y playwright test --retries=\"$PLAYWRIGHT_RETRIES\" --reporter=\"$PLAYWRIGHT_REPORTER\"\n\n    if [ $DEVCONTAINER == false ]; then\n        cd \"$FOLDER_PATH/$3\"\n    else\n        cd \"..\"\n    fi\n}\n\n# Cleans the specified template\n# $1 - The template name\n# $2 - The branch name\n# $3 - The environment name\nfunction cleanupTemplate {\n    echo \"Deprovisioning infrastructure for $3...\"\n    azd down -e \"$3\" --force --purge\n\n    echo \"Cleaning up local project @ '$FOLDER_PATH/$3'...\"\n    rm -rf \"$FOLDER_PATH/${3:?}\"\n}\n\nexport AZURE_LOCATION=\"$LOCATION\"\n\nif [[ -z $TEMPLATE_NAME ]]; then\n    declare -A ENV_TEMPLATE_MAP\n\n    # If a template is not specified, run for all templates from output of 'azd template list'\n    echo \"Getting list of available templates...\"\n    TEMPLATES_JSON=$(azd template list --output json)\n\n    while read -r TEMPLATE; do\n        ENV_NAME=\"${ENV_NAME_PREFIX}-${TEMPLATE:14}-$ENV_SUFFIX\"\n        ENV_TEMPLATE_MAP[$TEMPLATE]=$ENV_NAME\n    done < <(echo \"$TEMPLATES_JSON\" | jq -r '.[].repositoryPath' | sed 's/\\\\n/\\n/g')\n\n    if [ $TEST_ONLY == false ]; then\n        # Deploy the templates in parallel\n        for TEMPLATE in \"${!ENV_TEMPLATE_MAP[@]}\"; do\n            (deployTemplate \"$TEMPLATE\" \"$BRANCH_NAME\" \"${ENV_TEMPLATE_MAP[$TEMPLATE]}\" \"${SUBSCRIPTION}\" \"${LOCATION}\" \"$DEVCONTAINER\"|| continue) &\n        done\n\n        wait\n    fi\n\n    # Test the templates serially\n    for TEMPLATE in \"${!ENV_TEMPLATE_MAP[@]}\"; do\n        testTemplate \"$TEMPLATE\" \"$BRANCH_NAME\" \"${ENV_TEMPLATE_MAP[$TEMPLATE]}\" || continue\n    done\n\n    if [ \"$CLEANUP\" == true ]; then\n        # Cleanup the templates in parallel\n        for TEMPLATE in \"${!ENV_TEMPLATE_MAP[@]}\"; do\n            (cleanupTemplate \"$TEMPLATE\" \"$BRANCH_NAME\" \"${ENV_TEMPLATE_MAP[$TEMPLATE]}\" || continue) &\n        done\n\n        wait\n    fi\n\n    echo \"\"\n    echo \"Done!\"\nelse\n    # Run test for the specified template name\n    ENV_NAME=\"${ENV_NAME_PREFIX}-${TEMPLATE_NAME:14}-$ENV_SUFFIX\"\n    if [ $TEST_ONLY == false ]; then\n        deployTemplate \"$TEMPLATE_NAME\" \"$BRANCH_NAME\" \"$ENV_NAME\" \"${SUBSCRIPTION}\" \"${LOCATION}\" \"$DEVCONTAINER\"\n    fi\n\n    testTemplate \"$TEMPLATE_NAME\" \"$BRANCH_NAME\" \"$ENV_NAME\"\n\n    if [ \"$CLEANUP\" == true ]; then\n        cleanupTemplate \"$TEMPLATE_NAME\" \"$BRANCH_NAME\" \"$ENV_NAME\"\n    fi\nfi\n", "num_lines": 199}
{"repo_name": "azure-dev", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nset -eu\n\nENV_FILE_PATH=\".env\"\nCONFIG_ROOT=\"ENV_CONFIG\"\nOUTPUT_FILE=\"./public/env-config.js\"\n\ngenerateOutput() {\n    echo \"Generating JS configuration output to: $OUTPUT_FILE\"\n    echo \"window.$CONFIG_ROOT = {\" >\"$OUTPUT_FILE\"\n    for line in $1; do\n        if beginswith REACT_APP_ \"$line\"; then\n            key=${line%%=*}\n            value=${line#*=}\n            printf \" - Found '%s'\" \"$key\"\n            printf \"\\t%s: '%s',\\n\" \"$key\" \"$value\" >>\"$OUTPUT_FILE\"\n        fi\n    done\n    echo \"}\" >>\"$OUTPUT_FILE\"\n}\n\nbeginswith() { case $2 in \"$1\"*) true;; *) false;; esac; }\n\nusage() {\n    printf\n    printf \"Arguments:\"\n    printf \"\\t-e\\t Sets the .env file to use (default: .env)\"\n    printf \"\\t-o\\t Sets the output filename (default: ./public/env-config.js)\"\n    printf \"\\t-c\\t Sets the JS configuration key (default: ENV_CONFIG)\"\n    printf\n    printf \"Example:\"\n    printf \"\\tbash entrypoint.sh -e .env -o env-config.js\"\n}\n\nwhile getopts \"e:o:c:\" opt; do\n    case $opt in\n    e) ENV_FILE_PATH=$OPTARG ;;\n    o) OUTPUT_FILE=$OPTARG ;;\n    c) CONFIG_ROOT=$OPTARG ;;\n    :)\n        echo \"Error: -${OPTARG} requires a value\"\n        exit 1\n        ;;\n    *)\n        usage\n        exit 1\n        ;;\n    esac\ndone\n\n# Load .env file if supplied\nENV_FILE=\"\"\nif [ -f \"$ENV_FILE_PATH\" ]; then\n    echo \"Loading environment file from '$ENV_FILE_PATH'\"\n    ENV_FILE=\"$(cat \"$ENV_FILE_PATH\")\"\nfi\n\n# Load system environment variables\nENV_VARS=$(printenv)\n\n# Merge .env file with env variables\nALL_VARS=\"$ENV_FILE\\n$ENV_VARS\"\ngenerateOutput \"$ALL_VARS\"\n", "num_lines": 64}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncat <<EOF\n********************************************** WARNING **********************************************\nThis script uses the Azure CLI 1.0 and has been deprecated. Please install the Azure CLI 2.0\n(https://docs.microsoft.com/cli/azure/install-azure-cli) and use these 3 easy commands:\n\n  az login\n  az account set --subscription <Subscription ID>\n  az ad sp create-for-rbac\n\nBy default, the last command creates a Service Principal with the 'Contributor' role scoped to the\ncurrent subscription. Pass the '--help' parameter for more info if you want to change the defaults.\n********************************************** WARNING **********************************************\nEOF\n\nif !(command -v azure >/dev/null); then\n  echo \"ERROR: This script requires Azure CLI 1.0, but it could not be found. Is it installed and on your path?\" 1>&2\n  exit -1\nfi\n\nSUBSCRIPTION_ID=$1\n\n#echo \"\"\n#echo \"  Background article: https://azure.microsoft.com/documentation/articles/resource-group-authenticate-service-principal\"\necho \"\"\n\nmy_app_name_uuid=$(python -c 'import uuid; print (str(uuid.uuid4())[:8])')\nMY_APP_NAME=\"app${my_app_name_uuid}\"\n\nMY_APP_KEY=$(python -c 'import uuid; print (uuid.uuid4().hex)')\n\nmy_app_id_URI=\"${MY_APP_NAME}_id\"\n\n#check if the user has subscriptions. If not she's probably not logged in\nsubscriptions_list=$(azure account list --json)\nsubscriptions_list_count=$(echo $subscriptions_list | jq '. | length' 2>/dev/null)\nif [ $? -ne 0 ] || [ \"$subscriptions_list_count\" -eq \"0\" ]\nthen\n  azure login\nelse\n  echo \"  You are already logged in with an Azure account so we won't ask for credentials again.\"\n  echo \"  If you want to select a subscription from a different account, before running this script you should either log out from all the Azure accounts or login manually with the new account.\"\n  echo \"  azure login\"\n  echo \"\"\nfi\n\nif [ -z \"$SUBSCRIPTION_ID\" ]\nthen\n  #prompt for subscription\n  subscription_index=0\n  subscriptions_list=$(azure account list --json)\n  subscriptions_list_count=$(echo $subscriptions_list | jq '. | length')\n  if [ $subscriptions_list_count -eq 0 ]\n  then\n    echo \"  You need to sign up an Azure Subscription here: https://azure.microsoft.com\"\n    exit 1\n  elif [ $subscriptions_list_count -gt 1 ]\n  then\n    echo $subscriptions_list | jq -r 'keys[] as $i | \"  \\($i+1). \\(.[$i] | .name)\"'\n\n    while read -r -t 0; do read -r; done #clear stdin\n    subscription_idx=0\n    until [ $subscription_idx -ge 1 -a $subscription_idx -le $subscriptions_list_count ]\n    do\n      read -p \"  Select a subscription by typing an index number from above list and press [Enter]: \" subscription_idx\n      if [ $subscription_idx -ne 0 -o $subscription_idx -eq 0 2>/dev/null ]\n      then\n        :\n      else\n        subscription_idx=0\n      fi\n    done\n    subscription_index=$((subscription_idx-1))\n  fi\n\n  SUBSCRIPTION_ID=`echo $subscriptions_list | jq -r '.['$subscription_index'] | .id'`\n  echo \"\"\nfi\n\nazure account set $SUBSCRIPTION_ID >/dev/null\nif [ $? -ne 0 ]\nthen\n  exit 1\nelse\n  echo \"  Using subscription ID $SUBSCRIPTION_ID\"\n  echo \"\"\nfi\n\nMY_SUBSCRIPTION_ID=$(azure account show --json | jq -r '.[0].id')\nMY_TENANT_ID=$(azure account show --json | jq -r '.[0].tenantId')\n\nazure config mode arm >/dev/null\n\nmy_error_check=$(azure ad sp show --search $MY_APP_NAME --json | grep \"displayName\" | grep -c \\\"$MY_APP_NAME\\\" )\n\nif [ $my_error_check -gt 0 ];\nthen\n  echo \"  Found an app id matching the one we are trying to create; we will reuse that instead\"\nelse\n  echo \"  Creating application in active directory:\"\n  echo \"  azure ad app create --name '$MY_APP_NAME' --home-page 'http://$MY_APP_NAME' --identifier-uris 'http://$my_app_id_URI/' --password $MY_APP_KEY\"\n  azure ad app create --name $MY_APP_NAME --home-page http://$MY_APP_NAME --identifier-uris http://$my_app_id_URI/ --password $MY_APP_KEY >/dev/null\n  if [ $? -ne 0 ]\n  then\n    exit 1\n  fi\n  # Give time for operation to complete\n  echo \"  Waiting for operation to complete....\"\n  sleep 20\n  my_error_check=$(azure ad app show --search $MY_APP_NAME --json | grep \"displayName\" | grep -c \\\"$MY_APP_NAME\\\" )\n\n  if [ $my_error_check -gt 0 ];\n  then\n    my_app_object_id=$(azure ad app show --json --search $MY_APP_NAME | jq -r '.[0].objectId')\n    MY_CLIENT_ID=$(azure ad app show --json --search $MY_APP_NAME | jq -r '.[0].appId')\n    echo \" \"\n    echo \"  Creating the service principal in AD\"\n    echo \"  azure ad sp create -a $MY_CLIENT_ID\"\n    azure ad sp create -a $MY_CLIENT_ID >/dev/null\n    # Give time for operation to complete\n    echo \"  Waiting for operation to complete....\"\n    sleep 20\n    my_app_sp_object_id=$(azure ad sp show --search $MY_APP_NAME --json | jq -r '.[0].objectId')\n\n    echo \"  Assign rights to service principle\"\n    echo \"  azure role assignment create --objectId $my_app_sp_object_id -o Owner -c /subscriptions/$MY_SUBSCRIPTION_ID\"\n    azure role assignment create --objectId $my_app_sp_object_id -o Owner -c /subscriptions/$MY_SUBSCRIPTION_ID >/dev/null\n    if [ $? -ne 0 ]\n    then\n      exit 1\n    fi\n  else\n    echo \" \"\n    echo \"  We've encounter an unexpected error; please hit Ctr-C and retry from the beginning\"\n    read my_error\n  fi\nfi\n\nMY_CLIENT_ID=$(azure ad sp show --search $MY_APP_NAME --json | jq -r '.[0].appId')\n\necho \"  \"\necho \"  Your access credentials =============================\"\necho \"  \"\necho \"  Subscription ID:\" $MY_SUBSCRIPTION_ID\necho \"  Client ID:\" $MY_CLIENT_ID\necho \"  Client Secret:\" $MY_APP_KEY\necho \"  OAuth 2.0 Token Endpoint:\" \"https://login.microsoftonline.com/${MY_TENANT_ID}/oauth2/token\"\necho \"  Tenant ID:\" $MY_TENANT_ID\necho \"  \"\necho \"  You can verify the service principal was created properly by running:\"\necho \"  azure login -u \"$MY_CLIENT_ID\" --service-principal --tenant $MY_TENANT_ID\"\necho \"  \"\n", "num_lines": 154}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n#---------------------------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n#---------------------------------------------------------------------------------------------\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  ./deploy-dev-ops.sh\n\nArguments:\n  --subscription_id|-s   : Subscription id, optional if a default is already set in the Azure CLI\n  --deploy_target|-dt    : Deployment target for Spinnaker (either 'k8s' for a Kubernetes cluster or 'vmss' for VM Scale Sets), defaulted to 'k8s'\n  --username|-u          : Username for the DevOps VM, defaulted to 'azureuser'\n  --dns_prefix|-dp       : DNS prefix for the DevOps VM, defaulted to a generated string\n  --resource_group|-rg   : Resource group to deploy to, defaulted to a generated string\n  --location|-l          : Location to deploy to, e.g. 'westus', optional if a default is already set in the Azure CLI\n  --app_id|-ai           : Service Principal App Id (also called client id), defaulted to a generated Service Principal\n  --app_key|-ak          : Service Principal App Key (also called client secret), defaulted to a generated Service Principal\n  --tenant_id|-ti        : Tenant Id (only necessary if you want this script to log in to the cli with the Service Principal credentials)\n  --password|-p          : Password for the DevOps VM (only used for the 'vmss' scenario)\n  --ssh_public_key|-spk  : SSH Public Key for the DevOps VM (only used for the 'k8s' scenario), defaulted to '~/.ssh/id_rsa.pub'\n  --git_repository|-gr   : Git repository with a Dockerfile at the root (only used for the 'k8s' scenario), defaulted to 'https://github.com/azure-devops/spin-kub-demo'\n  --quiet|-q             : If this flag is passed, the script will not prompt for any values. An error will be thrown if a required parameter is not specified.\n\nExample Usage:\n  To run interactively:\n    bash <(curl -sL https://aka.ms/DeployDevOps)\n\n  To run non-interactively:\n    curl -sL https://aka.ms/DeployDevOps | bash -s -- <insert parameters here>\nEOF\n}\n\nfunction exit_on_failure() {\n  \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    exit $return_value\n  fi\n}\n\nfunction log_error() {\n  >&2 echo -e \"\\033[31mError: $1\\033[0m\"\n}\n\nfunction log_info() {\n  >&2 echo \"$1\"\n}\n\nfunction validate_az_cli() {\n  if !(command -v az >/dev/null) && [[ \"$quiet\" != true ]]; then\n    read -rp \"===> Did not find Azure CLI 2.0. Do you want to install? (y/N): \"\n    if [[ $REPLY =~ ^[Yy]$ ]]\n    then\n      curl -L https://aka.ms/InstallAzureCli | bash\n    fi\n  fi\n\n  if !(command -v az >/dev/null); then\n    log_error \"Did not find Azure CLI 2.0. Run 'curl -L https://aka.ms/InstallAzureCli | bash' and verify 'az --verison' succeeds. See here for more information: https://docs.microsoft.com/cli/azure/install-azure-cli\"\n    exit -1\n  fi\n\n  local account=$(az account show 2>/dev/null)\n  if [ -z \"$account\" ]; then\n    if [ -n \"$app_id\" ] && [ -n \"$app_key\" ] && [ -n \"$tenant_id\" ]; then\n      exit_on_failure az login --service-principal -u \"$app_id\" -p \"$app_key\" --tenant \"$tenant_id\"\n    elif [[ \"$quiet\" == true ]]; then\n      log_error \"The 'quiet' flag was passed, but no azure account was found. You must either sign in to the cli before running the script or pass the 'tenant_id', 'app_id' and 'app_key' to sign in with a service principal.\"\n      exit -1\n    else\n      log_info \"You must sign in to Azure to continue...\"\n      exit_on_failure az login >/dev/null\n    fi\n  fi\n}\n\nfunction set_subscription() {\n  local subscription_ids=($(az account list --query [].id 2>/dev/null | tr -d '[],\"'))\n  local count=${#subscription_ids[@]}\n  if [[ $count -gt 1 ]] && [ -z \"$subscription_id\" ] && [[ \"$quiet\" != true ]]; then\n    >&2 echo\n    log_info \"In what Subscription would you like to deploy?\"\n    local i=-2 # Use -2 because there are two lines of headers in the table\n    while read -r line; do\n      if [ $i -lt 0 ]; then\n        log_info \"       $line\"\n      elif [ $i -lt 10 ]; then\n        log_info \"  [$i]  $line\"\n      else\n        log_info \"  [$i] $line\"\n      fi\n      ((i++))\n    done <<< \"$(az account list -o table)\"\n\n    local min=0\n    local max=$((count-1))\n    while [ -z \"$subscription_id\" ]; do\n      read -rp \"===> Enter an integer between $min and $max (leave blank to use the default): \"\n      if [ -z \"$REPLY\" ]; then\n        break\n      elif [[ \"$REPLY\" =~ ^[0-9]+$ ]] && [ \"$REPLY\" -ge $min ] && [ \"$REPLY\" -le $max ]; then\n        subscription_id=\"${subscription_ids[$REPLY]}\"\n      fi\n    done\n  fi\n\n  if [ -n \"$subscription_id\" ]; then\n    exit_on_failure az account set --subscription \"$subscription_id\"\n  fi\n}\n\nfunction validate_deploy_target() {\n  deploy_target=$(echo \"$1\" | awk '{print tolower($0)}')\n\n  if [ -z \"$deploy_target\" ]; then\n    deploy_target=\"k8s\"\n    valid=true\n  elif [ \"$deploy_target\" != \"k8s\" ] && [ \"$deploy_target\" != \"vmss\" ]; then\n    log_error \"The deploy target must be either 'k8s' or 'vmss'.\"\n    valid=false\n  else\n    valid=true\n  fi\n}\n\nfunction validate_username() {\n  username=\"$1\"\n\n  local min=1\n  local max=64\n  # This list is not meant to be exhaustive. It's only the list from here: https://docs.microsoft.com/azure/virtual-machines/linux/usernames\n  local reserved_names=\" adm admin audio backup bin cdrom crontab daemon dialout dip disk fax floppy fuse games gnats irc kmem landscape libuuid list lp mail man messagebus mlocate netdev news nobody nogroup operator plugdev proxy root sasl shadow src ssh sshd staff sudo sync sys syslog tape tty users utmp uucp video voice whoopsie www-data \"\n  if [ -z \"$username\" ]; then\n    username=\"azureuser\"\n    valid=true\n  elif [ ${#username} -lt $min ] || [ ${#username} -gt $max ]; then\n    log_error \"The username must be between $min and $max characters.\"\n    valid=false\n  elif ! [[ \"$username\" =~ ^[a-z][-a-z0-9_]*$ ]]; then\n    log_error \"The username must contain only lowercase letters, numbers, hyphens, and underscores. The first character must be a letter.\"\n    valid=false\n  elif [[ \"$reserved_names\" =~ \" $username \" ]]; then\n    log_error \"The username cannot be an Ubuntu reserved name. See here for more information: https://docs.microsoft.com/azure/virtual-machines/linux/usernames\"\n    valid=false\n  else\n    valid=true\n  fi\n}\n\nfunction validate_dns_prefix() {\n  dns_prefix=\"$1\"\n  local min=3\n  local max=63\n  if [ -z \"$dns_prefix\" ]; then\n    dns_prefix=\"$scenario_name\"\n    valid=true\n  elif [ ${#dns_prefix} -lt $min ] || [ ${#dns_prefix} -gt $max ]; then\n    log_error \"The dns prefix must be between $min and $max characters.\"\n    valid=false\n  elif ! [[ \"$dns_prefix\" =~ ^[a-z][-a-z0-9]*[a-z0-9]$ ]]; then\n    log_error \"The dns prefix must contain only lowercase letters, numbers, and hyphens. The first character must be a letter. The last character must be a letter or number.\"\n    valid=false\n  else\n    valid=true\n  fi\n}\n\nfunction validate_or_create_service_principal() {\n  if [ -z \"$app_id\" ] || [ -z \"$app_key\" ]; then\n    >&2 echo\n    if [[ \"$quiet\" == true ]]; then\n      log_info \"The 'quiet' flag was passed without the app_id and/or app_key, so a new service principal will be created.\"\n    else\n      log_info \"Spinnaker will use a service principal as credentials to dynamically manage resources in your subscription.\"\n      read -rp \"===> Do you have an existing service principal you would like to use? (y/N): \"\n      if [[ $REPLY =~ ^[Yy]$ ]]; then\n        while [ -z \"$app_id\" ]; do\n          read -rp \"===> Enter the app id of your service principal: \"\n          app_id=\"$REPLY\"\n        done\n\n        while [ -z \"$app_key\" ]; do\n          read -srp \"===> Enter the app key of your service principal: \"\n          >&2 echo\n\n          if [ -n \"$REPLY\" ]; then\n            app_key=\"$REPLY\"\n            read -srp \"===> Confirm the app key of your service principal: \"\n            >&2 echo\n            if [ \"$app_key\" != \"$REPLY\" ]; then\n              log_error \"The app keys did not match.\"\n              app_key=\"\"\n            fi\n          fi\n        done\n      fi\n    fi\n  fi\n\n  if [ -z \"$app_id\" ] || [ -z \"$app_key\" ]; then\n    log_info \"Creating service principal...\"\n    local service_principal=$(az ad sp create-for-rbac -n \"$scenario_name\")\n    app_id=$(echo \"$service_principal\" | grep \"appId\" | cut -d '\"' -f4)\n    app_key=$(echo \"$service_principal\" | grep \"password\" | cut -d '\"' -f4)\n    log_info \"Created service principal:\"\n    exit_on_failure az ad sp show --id \"$app_id\" -o table\n  fi\n}\n\nfunction validate_or_create_resource_group() {\n  # Check if resource group already exists\n  local resource_group_data=$(az group show -n \"$resource_group\")\n  if [ -z \"$resource_group_data\" ]; then\n    if [ -z \"$location\" ] && [[ \"$quiet\" != true ]]; then\n      local locations=($(az account list-locations --query [].name | tr -d '[],\"'))\n      local count=${#locations[@]}\n      if [[ $count -lt 1 ]]; then\n        log_error \"Failed to list locations for this subscription.\"\n        exit -1\n      elif [[ $count -eq 1 ]]; then\n        location=\"${locations[0]}\"\n      else\n        >&2 echo\n        log_info \"In what location would you like to deploy?\"\n        for ((i = 0; i < $count; ++i)); do\n          if [ $i -lt 10 ]; then\n            log_info \"  [$i]  ${locations[$i]}\"\n          else\n            log_info \"  [$i] ${locations[$i]}\"\n          fi\n        done\n\n        local min=0\n        local max=$((count-1))\n\n        local default=\"westus\"\n        if [[ \" ${locations[*]} \" != *\" $default \"* ]]; then\n          # Use the first location if westus isn't available\n          local default=${locations[0]}\n        fi\n\n        while [ -z \"$location\" ]; do\n          read -rp \"===> Enter an integer between $min and $max (leave blank to use '$default'): \"\n          if [ -z \"$REPLY\" ]; then\n            location=\"$default\"\n          elif [[ \"$REPLY\" =~ ^[0-9]+$ ]] && [ \"$REPLY\" -ge $min ] && [ \"$REPLY\" -le $max ]; then\n            location=\"${locations[$REPLY]}\"\n          fi\n        done\n      fi\n    fi\n\n    log_info \"Creating resource group...\"\n    if [ -z \"$location\" ]; then\n      # This will only work if the az cli has a default location configured\n      exit_on_failure az group create -n \"$resource_group\" -o table\n    else\n      exit_on_failure az group create -n \"$resource_group\" -l \"$location\" -o table\n    fi\n  fi\n}\n\nfunction validate_password() {\n  password=\"$1\"\n\n  local min=12\n  local max=72\n  if [ ${#password} -lt $min ] || [ ${#password} -gt $max ]; then\n    log_error \"The password must be between $min and $max characters.\"\n    valid=false\n  else\n    valid=true\n  fi\n}\n\nfunction validate_ssh_public_key() {\n  ssh_public_key=\"$1\"\n\n  if [ -z \"$ssh_public_key\" ]; then\n    local key_file_path=\"${default_private_key_file}.pub\"\n\n    if ! [ -e \"$default_private_key_file\" ]; then\n      mkdir -p $(dirname \"$default_private_key_file\")\n      if [[ \"$quiet\" == true ]]; then\n        # If quiet, assume no passphrase because that requires interaction\n        ssh-keygen -t rsa -b 2048 -f \"$default_private_key_file\" -N \"\"\n      else\n        ssh-keygen -t rsa -b 2048 -f \"$default_private_key_file\"\n      fi\n    fi\n  elif [ -e \"$ssh_public_key\" ]; then # User specified a file path\n    if [ ${ssh_public_key: -4} != \".pub\" ]; then\n      local key_file_path=\"${ssh_public_key}.pub\"\n    else\n      local key_file_path=\"$ssh_public_key\"\n    fi\n  else # User specified a public key\n    local temp_file=\"$(mktemp).pub\"\n    echo \"$ssh_public_key\" > \"$temp_file\"\n    local key_file_path=\"$temp_file\"\n  fi\n\n  # This doesn't generate anything, it just validates it's a public key file\n  ssh-keygen -l -f \"$key_file_path\" &>/dev/null\n  if [ $? -ne 0 ]; then\n    log_error \"The public key specified was invalid.\"\n    valid=false\n  else\n    valid=true\n    ssh_public_key=$(cat \"$key_file_path\")\n  fi\n\n  if [ -e \"$temp_file\" ]; then\n    rm \"$temp_file\"\n  fi\n}\n\nscenario_name=$(date +devops-%Y-%m-%d-%H-%M-%S)\nresource_group=\"$scenario_name\"\n\nif [[ \"$-\" == *s* ]]; then\n  # If we don't run in quiet mode, each 'read' operation will take the next line of the script as input\n  log_info \"Defaulting to quiet mode because commands are being read from standard input.\"\n  quiet=true\nelse\n  quiet=false\nfi\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --subscription_id|-si)\n      subscription_id=\"$1\"\n      shift;;\n    --deploy_target|-dt)\n      deploy_target=\"$1\"\n      shift;;\n    --username|-u)\n      username=\"$1\"\n      shift;;\n    --dns_prefix|-dp)\n      dns_prefix=\"$1\"\n      shift;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift;;\n    --location|-l)\n      location=\"$1\"\n      shift;;\n    --app_id|-ai)\n      app_id=\"$1\"\n      shift;;\n    --app_key|-ak)\n      app_key=\"$1\"\n      shift;;\n    --tenant_id|-ti)\n      tenant_id=\"$1\"\n      shift;;\n    --password|-p)\n      password=\"$1\"\n      shift;;\n    --ssh_public_key|-spk)\n      ssh_public_key=\"$1\"\n      shift;;\n    --git_repository|-gr)\n      git_repository=\"$1\"\n      shift;;\n    --quiet|-q)\n      quiet=true;;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      log_error \"Unknown argument '$key'.\"\n      exit -1\n  esac\ndone\n\nvalidate_az_cli\n\nset_subscription\n\nif [ -n \"$deploy_target\" ] || [[ \"$quiet\" == true ]]; then\n  validate_deploy_target \"$deploy_target\"\n  if [[ \"$valid\" != true ]]; then\n    exit -1\n  fi\nelse\n  >&2 echo\n  log_info \"This script will deploy an instance of Jenkins and Spinnaker on an Ubuntu 14.04 VM in Azure.\"\n  log_info \"Do you want Spinnaker to target a Kubernetes Cluster (k8s) or VM Scale Sets (vmss)?\"\n  valid=false\n  while [[ \"$valid\" != true ]]; do\n    read -rp \"===> Enter either 'vmss' or 'k8s' (leave blank to use 'k8s'): \"\n    validate_deploy_target \"$REPLY\"\n  done\nfi\n\nif [ -n \"$username\" ] || [[ \"$quiet\" == true ]]; then\n  validate_username \"$username\"\n  if [[ \"$valid\" != true ]]; then\n    exit -1\n  fi\nelse\n  >&2 echo\n  valid=false\n  while [[ \"$valid\" != true ]]; do\n    read -rp \"===> Enter a username for your VM (leave blank to use 'azureuser'): \"\n    validate_username \"$REPLY\"\n  done\nfi\n\nif [ -n \"$dns_prefix\" ] || [[ \"$quiet\" == true ]]; then\n  validate_dns_prefix \"$dns_prefix\"\n  if [[ \"$valid\" != true ]]; then\n    exit -1\n  fi\nelse\n  >&2 echo\n  valid=false\n  while [[ \"$valid\" != true ]]; do\n    read -rp \"===> Enter a DNS prefix for your VM: (leave blank to use '$scenario_name'): \"\n    validate_dns_prefix \"$REPLY\"\n  done\nfi\n\nvalidate_or_create_resource_group\n\nvalidate_or_create_service_principal\n\nif [ \"$deploy_target\" == \"k8s\" ]; then\n  default_private_key_file=\"$HOME/.ssh/id_rsa\"\n\n  if [ -n \"$ssh_public_key\" ] || [[ \"$quiet\" == true ]]; then\n    validate_ssh_public_key \"$ssh_public_key\"\n    if [[ \"$valid\" != true ]]; then\n      exit -1\n    fi\n  else\n    if [ -e \"$default_private_key_file\" ]; then\n      default_message=\"leave blank to use '$default_private_key_file'\"\n    else\n      default_message=\"leave blank to generate a new key at '$default_private_key_file'\"\n    fi\n\n    >&2 echo\n    valid=false\n    while [[ \"$valid\" != true ]]; do\n      read -rp \"===> Enter an ssh public key or the path to a public key file ($default_message): \"\n      validate_ssh_public_key \"$REPLY\"\n    done\n  fi\n\n  default_git_repository=https://github.com/azure-devops/spin-kub-demo\n  if [ -z \"$git_repository\" ] && [[ \"$quiet\" != true ]]; then\n    >&2 echo\n    read -rp \"===> Enter a git repository with a Dockerfile at the root: (leave blank to use '$default_git_repository'): \"\n    git_repository=\"$REPLY\"\n  fi\n\n  if [ -z \"$git_repository\" ]; then\n    git_repository=\"$default_git_repository\"\n  fi\n\n  template_uri=\"https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/301-jenkins-acr-spinnaker-k8s/azuredeploy.json\"\n  parameters=$(cat <<EOF\n{\n  \"adminUsername\": {\n    \"value\": \"$username\"\n  },\n  \"sshPublicKey\": {\n    \"value\": \"$ssh_public_key\"\n  },\n  \"devopsDnsPrefix\": {\n    \"value\": \"$dns_prefix\"\n  },\n  \"servicePrincipalAppId\": {\n    \"value\": \"$app_id\"\n  },\n  \"servicePrincipalAppKey\": {\n    \"value\": \"$app_key\"\n  },\n  \"gitRepository\": {\n    \"value\": \"$git_repository\"\n  }\n}\nEOF\n)\nelse\n  if [ -n \"$password\" ] || [[ \"$quiet\" == true ]]; then\n    validate_password \"$password\"\n    if [[ \"$valid\" != true ]]; then\n      exit -1\n    fi\n  else\n\n    >&2 echo\n    valid=false\n    while [ -z \"$password\" ] || [[ \"$valid\" != true ]]; do\n      read -srp \"===> Enter a password for your VM: \"\n      >&2 echo\n\n      validate_password \"$REPLY\"\n      if [[ \"$valid\" == true ]]; then\n        read -srp \"===> Confirm your password: \"\n        >&2 echo\n        if [ \"$password\" != \"$REPLY\" ]; then\n          log_error \"The passwords did not match.\"\n          password=\"\"\n        fi\n      fi\n    done\n  fi\n  \n  template_uri=\"https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/301-jenkins-aptly-spinnaker-vmss/azuredeploy.json\"\n  parameters=$(cat <<EOF\n{\n  \"adminUsername\": {\n    \"value\": \"$username\"\n  },\n  \"adminPassword\": {\n    \"value\": \"$password\"\n  },\n  \"devopsDnsPrefix\": {\n    \"value\": \"$dns_prefix\"\n  },\n  \"servicePrincipalAppId\": {\n    \"value\": \"$app_id\"\n  },\n  \"servicePrincipalAppKey\": {\n    \"value\": \"$app_key\"\n  }\n}\nEOF\n)\nfi\n\n>&2 cat <<EOF\n\nStarting deployment...\nThe deployment will take about 15-20 minutes to complete. This is the last step and the deployment will continue even if you exit this script.\nNext steps:\n  1. Run this command to check the status:\n     az group deployment show --name \"$scenario_name\" --resource-group \"$resource_group\" --query properties.provisioningState\n  2. Run this command to view the outputs (after the status is \"Succeeded\"):\n     az group deployment show --name \"$scenario_name\" --resource-group \"$resource_group\" --query properties.outputs\n  3. Copy and run the 'ssh' output variable to connect to your VM\n  4. Navigate to http://localhost:8080 to view your Jenkins dashboard\n  5. Navigate to http://localhost:9000 to view your Spinnaker dashboard\nEOF\n\nexit_on_failure az group deployment create --name \"$scenario_name\" --resource-group \"$resource_group\" --template-uri \"$template_uri\" --parameters \"$parameters\" --query \"{outputs: properties.outputs}\"\n", "num_lines": 559}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --git_url|-g             : Git URL for the build job\n  --repository_name|-rn    : Aptly repository name used to store debian packages\n  --job_short_name|-jsn    : Desired Jenkins job short name\n  --job_display_name|-jdn  : Desired Jenkins job display name\n  --job_description|-jd    : Desired Jenkins job description\n  --artifacts_location|-al : Url used to reference other scripts/artifacts.\n  --sas_token|-st          : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\njob_short_name=\"hello-karyon-rxnetty\"\njob_display_name=\"Sample Aptly Job\"\njob_description=\"A basic pipeline that builds a debian package and pushes it to an Aptly repository hosted on the Jenkins VM.\"\nrepository_name=\"hello-karyon-rxnetty\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\ngit_url=\"https://github.com/azure-devops/hello-karyon-rxnetty.git\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --git_url|-g)\n      git_url=\"$1\";;\n    --repository_name|-rn)\n      repository_name=\"$1\";;\n    --job_short_name|-jsn)\n      job_short_name=\"$1\";;\n    --job_display_name|-jdn)\n      job_display_name=\"$1\";;\n    --job_description|-jd)\n      job_description=\"$1\";;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\";;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty git_url $git_url\nthrow_if_empty repository_name $repository_name\n\n#download dependencies\njob_xml=$(curl -s ${artifacts_location}/jenkins/basic-aptly-build-job.xml${artifacts_location_sas_token})\n\n#prepare job.xml\njob_xml=${job_xml//'{insert-job-display-name}'/${job_display_name}}\njob_xml=${job_xml//'{insert-job-description}'/${job_description}}\njob_xml=${job_xml//'{insert-git-url}'/${git_url}}\njob_xml=${job_xml//'{insert-repository-name}'/${repository_name}}\n\necho \"${job_xml}\" > job.xml\n\necho \"Installing git...\" \nsudo DEBIAN_FRONTEND=noninteractive apt-get install git -y\n\necho \"Installing Java 8...\" \nsudo DEBIAN_FRONTEND=noninteractive apt-get install -y openjdk-8-jdk\n\ngradle_version=\"3.5\"\necho \"Installing Gradlew ${gradle_version}...\" \nwget -nv https://services.gradle.org/distributions/gradle-${gradle_version}-bin.zip\nsudo unzip gradle-${gradle_version}-bin.zip -d /opt/gradle\nsudo ln -s /opt/gradle/gradle-${gradle_version}/bin/gradle /usr/bin/gradle\n\nrun_util_script \"jenkins/run-cli-command.sh\" -c \"install-plugin git -restart\"\n\necho \"Waiting for Jenkins to be back online...\"\nrun_util_script \"jenkins/run-cli-command.sh\" -c \"version\"\n\necho \"Adding basic vmss job...\"\nrun_util_script \"jenkins/run-cli-command.sh\" -cif \"job.xml\" -c \"create-job ${job_short_name}\"\n\n#cleanup\nrm job.xml\nrm jenkins-cli.jar", "num_lines": 112}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --jenkins_url|-j          [Required]: Jenkins URL\n  --jenkins_username|-ju    [Required]: Jenkins user name\n  --jenkins_password|-jp              : Jenkins password. If not specified and the user name is \"admin\", the initialAdminPassword will be used\n  --git_url|-g              [Required]: Git URL with a Dockerfile in it's root\n  --registry|-r             [Required]: Registry url targeted by the pipeline\n  --registry_user_name|-ru  [Required]: Registry user name\n  --registry_password|-rp   [Required]: Registry password\n  --repository|-rr                    : Repository targeted by the pipeline\n  --credentials_id|-ci                : Desired Jenkins credentials id\n  --credentials_desc|-cd              : Desired Jenkins credentials description\n  --job_short_name|-jsn               : Desired Jenkins job short name\n  --job_display_name|-jdn             : Desired Jenkins job display name\n  --job_description|-jd               : Desired Jenkins job description\n  --scm_poll_schedule|-sps            : cron style schedule for SCM polling\n  --scm_poll_ignore_commit_hooks|spi  : Ignore changes notified by SCM post-commit hooks. (Will be ignore if the poll schedule is not defined)\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\ncredentials_id=\"docker_credentials\"\ncredentials_desc=\"Docker Container Registry Credentials\"\njob_short_name=\"basic-docker-build\"\njob_display_name=\"Basic Docker Build\"\njob_description=\"A basic pipeline that builds a Docker container. The job expects a Dockerfile at the root of the git repository\"\nrepository=\"${USER}/myfirstapp\"\nscm_poll_schedule=\"\"\nscm_poll_ignore_commit_hooks=\"0\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_url|-j)\n      jenkins_url=\"$1\"\n      shift\n      ;;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\"\n      shift\n      ;;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\"\n      shift\n      ;;\n    --git_url|-g)\n      git_url=\"$1\"\n      shift\n      ;;\n    --registry|-r)\n      registry=\"$1\"\n      shift\n      ;;\n    --registry_user_name|-ru)\n      registry_user_name=\"$1\"\n      shift\n      ;;\n    --registry_password|-rp)\n      registry_password=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --credentials_id|-ci)\n      credentials_id=\"$1\"\n      shift\n      ;;\n    --credentials_desc|-cd)\n      credentials_desc=\"$1\"\n      shift\n      ;;\n    --job_short_name|-jsn)\n      job_short_name=\"$1\"\n      shift\n      ;;\n    --job_display_name|-jdn)\n      job_display_name=\"$1\"\n      shift\n      ;;\n    --job_description|-jd)\n      job_description=\"$1\"\n      shift\n      ;;\n   --scm_poll_schedule|-sps)\n      scm_poll_schedule=\"$1\"\n      shift\n      ;;\n  --scm_poll_ignore_commit_hooks|-spi)\n      scm_poll_ignore_commit_hooks=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --jenkins_url $jenkins_url\nthrow_if_empty --jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty --jenkins_password $jenkins_password\nfi\nthrow_if_empty --git_url $git_url\nthrow_if_empty --registry $registry\nthrow_if_empty --registry_user_name $registry_user_name\nthrow_if_empty --registry_password $registry_password\n\n#download dependencies\njob_xml=$(curl -s ${artifacts_location}/jenkins/basic-docker-build-job.xml${artifacts_location_sas_token})\ncredentials_xml=$(curl -s ${artifacts_location}/jenkins/basic-user-pwd-credentials.xml${artifacts_location_sas_token})\n\n#prepare credentials.xml\ncredentials_xml=${credentials_xml//'{insert-credentials-id}'/${credentials_id}}\ncredentials_xml=${credentials_xml//'{insert-credentials-description}'/${credentials_desc}}\ncredentials_xml=${credentials_xml//'{insert-user-name}'/${registry_user_name}}\ncredentials_xml=${credentials_xml//'{insert-user-password}'/${registry_password}}\n\n#prepare job.xml\njob_xml=${job_xml//'{insert-job-display-name}'/${job_display_name}}\njob_xml=${job_xml//'{insert-job-description}'/${job_description}}\njob_xml=${job_xml//'{insert-git-url}'/${git_url}}\njob_xml=${job_xml//'{insert-registry}'/${registry}}\njob_xml=${job_xml//'{insert-docker-credentials}'/${credentials_id}}\njob_xml=${job_xml//'{insert-container-repository}'/${repository}}\n\n\nif [ -n \"${scm_poll_schedule}\" ]\nthen\n  scm_poll_ignore_commit_hooks_bool=\"false\"\n  if [[ \"${scm_poll_ignore_commit_hooks}\" == \"1\" ]]\n  then\n    scm_poll_ignore_commit_hooks_bool=\"true\"\n  fi\n  triggers_xml_node=$(cat <<EOF\n<triggers>\n  <hudson.triggers.SCMTrigger>\n  <spec>${scm_poll_schedule}</spec>\n  <ignorePostCommitHooks>${scm_poll_ignore_commit_hooks_bool}</ignorePostCommitHooks>\n  </hudson.triggers.SCMTrigger>\n</triggers>\nEOF\n)\n  job_xml=${job_xml//'<triggers/>'/${triggers_xml_node}}\nfi\n\njob_xml=${job_xml//'{insert-groovy-script}'/\"$(curl -s ${artifacts_location}/jenkins/basic-docker-build.groovy${artifacts_location_sas_token})\"}\necho \"${job_xml}\" > job.xml\n\n#install the required plugins\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin credentials -deploy\"\nplugins=(docker-workflow git)\nfor plugin in \"${plugins[@]}\"; do\n  run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin $plugin -restart\"\ndone\n\n#wait for instance to be back online\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"version\"\n\n#add user/pwd\necho \"${credentials_xml}\" > credentials.xml\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c 'create-credentials-by-xml SystemCredentialsProvider::SystemContextResolver::jenkins (global)' -cif \"credentials.xml\"\n\n#add job\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-job ${job_short_name}\" -cif \"job.xml\"\n\n#cleanup\nrm credentials.xml\nrm job.xml\nrm jenkins-cli.jar", "num_lines": 214}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0 \n\nArguments\n  --vm_fqdn|-vf         [Required]: FQDN for the Jenkins instance hosting the Aptly repository\n  --repository_name|-rn           : Repository name for hosting debian packages, defaulted to 'hello-karyon-rxnetty'\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\n# Set defaults\nrepository_name=\"hello-karyon-rxnetty\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --vm_fqdn|-vf)\n      vm_fqdn=\"$1\";;\n    --repository_name|-rn)\n      repository_name=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty vm_fqdn $vm_fqdn\nthrow_if_empty repository_name $repository_name\n\n# Install aptly\necho \"deb http://repo.aptly.info/ squeeze main\" | sudo tee -a \"/etc/apt/sources.list\" > /dev/null\nsudo apt-key adv --keyserver keys.gnupg.net --recv-keys 9E3E53F19C7DE460\nsudo DEBIAN_FRONTEND=noninteractive apt-get update --yes\nsudo DEBIAN_FRONTEND=noninteractive apt-get install aptly --force-yes --yes\n\n# Create default aptly repository\nsudo su -c \"aptly repo create $repository_name\" jenkins\nsudo su -c \"aptly publish repo -architectures=\\\"amd64\\\" -component=main -distribution=trusty -skip-signing=true $repository_name\" jenkins\n\n# Serve aptly on port 9999\naptly_nginx_config=$(cat <<EOF\nserver {\n  listen 9999;\n  root /var/lib/jenkins/.aptly/public;\n  server_name {vm_fqdn};\n  location / {\n    autoindex on;\n  }\n}\nEOF\n)\naptly_nginx_config=${aptly_nginx_config//'{vm_fqdn}'/${vm_fqdn}}\n\necho \"${aptly_nginx_config}\" | sudo tee -a /etc/nginx/sites-enabled/default > /dev/null\n\n#restart nginx\nsudo service nginx restart", "num_lines": 76}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho $@\nfunction print_usage() {\n  cat <<EOF\nInstalls Jenkins and exposes it to the public through port 80 (login and cli are disabled)\nCommand\n  $0\nArguments\n  --jenkins_fqdn|-jf       [Required] : Jenkins FQDN\n  --vm_private_ip|-pi                 : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead\n  --jenkins_release_type|-jrt         : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS\n  --jenkins_version_location|-jvl     : Url used to specify the version of Jenkins.\n  --service_principal_type|-sp        : The type of service principal: MSI or manual.\n  --service_principal_id|-sid         : The service principal ID.\n  --service_principal_secret|-ss      : The service principal secret.\n  --subscription_id|-subid            : The subscription ID of the SP.\n  --tenant_id|-tid                    : The tenant id of the SP.\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\n  --cloud_agents|-ca                  : The type of the cloud agents: aci, vm or no.\n  --resource_group|-rg                : the resource group name.\n  --location|-lo                      : the resource group location.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nfunction retry_until_successful {\n  counter=0\n  \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    \"${@}\"\n  done;\n}\n\n#defaults\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\njenkins_version_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/jenkins/jenkins-verified-ver\"\nazure_web_page_location=\"/usr/share/nginx/azure\"\njenkins_release_type=\"LTS\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --vm_private_ip|-pi)\n      vm_private_ip=\"$1\"\n      shift\n      ;;\n    --jenkins_release_type|-jrt)\n      jenkins_release_type=\"$1\"\n      shift\n      ;;\n    --jenkins_version_location|-jvl)\n      jenkins_version_location=\"$1\"\n      shift\n      ;;\n    --service_principal_type|-sp)\n      service_principal_type=\"$1\"\n      shift\n      ;;\n    --service_principal_id|-spid)\n      service_principal_id=\"$1\"\n      shift\n      ;;\n    --service_principal_secret|-ss)\n      service_principal_secret=\"$1\"\n      shift\n      ;;\n    --subscription_id|-subid)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-tid)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --cloud_agents|-ca)\n      cloud_agents=\"$1\"\n      shift\n      ;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --location|-lo)\n      location=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\nthrow_if_empty --jenkins_release_type $jenkins_release_type\nif [[ \"$jenkins_release_type\" != \"LTS\" ]] && [[ \"$jenkins_release_type\" != \"weekly\" ]] && [[ \"$jenkins_release_type\" != \"verified\" ]]; then\n  echo \"Parameter jenkins_release_type can only be 'LTS' or 'weekly' or 'verified'! Current value is '$jenkins_release_type'\"\n  exit 1\nfi\n\nif [ -z \"$vm_private_ip\" ]; then\n    #use port 80 for public fqdn\n    jenkins_url=\"http://${jenkins_fqdn}/\"\nelse\n    #use port 8080 for internal\n    jenkins_url=\"http://${vm_private_ip}:8080/\"\nfi\n\njenkins_auth_matrix_conf=$(cat <<EOF\n<authorizationStrategy class=\"hudson.security.ProjectMatrixAuthorizationStrategy\">\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Create:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Delete:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.ManageDomains:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Update:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.View:authenticated</permission>\n    <permission>hudson.model.Computer.Build:authenticated</permission>\n    <permission>hudson.model.Computer.Configure:authenticated</permission>\n    <permission>hudson.model.Computer.Connect:authenticated</permission>\n    <permission>hudson.model.Computer.Create:authenticated</permission>\n    <permission>hudson.model.Computer.Delete:authenticated</permission>\n    <permission>hudson.model.Computer.Disconnect:authenticated</permission>\n    <permission>hudson.model.Hudson.Administer:authenticated</permission>\n    <permission>hudson.model.Hudson.ConfigureUpdateCenter:authenticated</permission>\n    <permission>hudson.model.Hudson.Read:authenticated</permission>\n    <permission>hudson.model.Hudson.RunScripts:authenticated</permission>\n    <permission>hudson.model.Hudson.UploadPlugins:authenticated</permission>\n    <permission>hudson.model.Item.Build:authenticated</permission>\n    <permission>hudson.model.Item.Cancel:authenticated</permission>\n    <permission>hudson.model.Item.Configure:authenticated</permission>\n    <permission>hudson.model.Item.Create:authenticated</permission>\n    <permission>hudson.model.Item.Delete:authenticated</permission>\n    <permission>hudson.model.Item.Discover:authenticated</permission>\n    <permission>hudson.model.Item.Move:authenticated</permission>\n    <permission>hudson.model.Item.Read:authenticated</permission>\n    <permission>hudson.model.Item.Workspace:authenticated</permission>\n    <permission>hudson.model.Run.Delete:authenticated</permission>\n    <permission>hudson.model.Run.Replay:authenticated</permission>\n    <permission>hudson.model.Run.Update:authenticated</permission>\n    <permission>hudson.model.View.Configure:authenticated</permission>\n    <permission>hudson.model.View.Create:authenticated</permission>\n    <permission>hudson.model.View.Delete:authenticated</permission>\n    <permission>hudson.model.View.Read:authenticated</permission>\n    <permission>hudson.scm.SCM.Tag:authenticated</permission>\n    <permission>hudson.model.Hudson.Read:anonymous</permission>\n    <permission>hudson.model.Item.Discover:anonymous</permission>\n    <permission>hudson.model.Item.Read:anonymous</permission>\n</authorizationStrategy>\nEOF\n)\n\njenkins_location_conf=$(cat <<EOF\n<?xml version='1.0' encoding='UTF-8'?>\n<jenkins.model.JenkinsLocationConfiguration>\n    <adminAddress>address not configured yet &lt;nobody@nowhere&gt;</adminAddress>\n    <jenkinsUrl>${jenkins_url}</jenkinsUrl>\n</jenkins.model.JenkinsLocationConfiguration>\nEOF\n)\n\njenkins_disable_reverse_proxy_warning=$(cat <<EOF\n<disabledAdministrativeMonitors>\n    <string>hudson.diagnosis.ReverseProxySetupMonitor</string>\n</disabledAdministrativeMonitors>\nEOF\n)\n\njenkins_agent_port=\"<slaveAgentPort>5378</slaveAgentPort>\"\n\nnginx_reverse_proxy_conf=$(cat <<EOF\nserver {\n    listen 80;\n    server_name ${jenkins_fqdn};\n    error_page 403 /jenkins-on-azure;\n    location / {\n        proxy_set_header        Host \\$host:\\$server_port;\n        proxy_set_header        X-Real-IP \\$remote_addr;\n        proxy_set_header        X-Forwarded-For \\$proxy_add_x_forwarded_for;\n        proxy_set_header        X-Forwarded-Proto \\$scheme;\n\n\n        # Fix the \u00e2\u20ac\u0153It appears that your reverse proxy set up is broken\" error.\n        proxy_pass          http://localhost:8080;\n        proxy_redirect      http://localhost:8080 http://${jenkins_fqdn};\n        proxy_read_timeout  90;\n    }\n    location /cli {\n        rewrite ^ /jenkins-on-azure permanent;\n    }\n\n    location ~ /login* {\n        rewrite ^ /jenkins-on-azure permanent;\n    }\n    location /jenkins-on-azure {\n      alias ${azure_web_page_location};\n    }\n}\nEOF\n)\n\n# Add repositories public keys\nwget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -\nwget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -\n\nif [ \"$jenkins_release_type\" == \"weekly\" ]; then\n  sudo sh -c 'echo deb http://pkg.jenkins.io/debian binary/ > /etc/apt/sources.list.d/jenkins.list'\nelse\n  sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'\nfi\n\nsudo add-apt-repository ppa:openjdk-r/ppa --yes\n\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $(lsb_release -cs) main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\nwget -q -O - https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -\nsudo apt-get install apt-transport-https\nsudo apt-get update --yes\n\n#install openjdk8\nsudo apt-get install openjdk-8-jre openjdk-8-jre-headless openjdk-8-jdk --yes\n\n#install jenkins\nif [[ ${jenkins_release_type} == 'verified' ]]; then\n  jenkins_version=$(curl --silent \"${jenkins_version_location}\")\n  deb_file=jenkins_${jenkins_version}_all.deb\n  wget -q \"https://pkg.jenkins.io/debian-stable/binary/${deb_file}\"\n  if [[ -f ${deb_file} ]]; then\n    sudo dpkg -i ${deb_file}\n    sudo apt-get install -f --yes\n  else\n    echo \"Failed to download ${deb_file}. The initialization is terminated!\"\n    exit -1\n  fi\nelse\n  sudo apt-get install jenkins --yes\n  sudo apt-get install jenkins --yes # sometime the first apt-get install jenkins command fails, so we try it twice\nfi\n\nretry_until_successful sudo test -f /var/lib/jenkins/secrets/initialAdminPassword\nretry_until_successful run_util_script \"jenkins/run-cli-command.sh\" -c \"version\"\n\n#We need to install workflow-aggregator so all the options in the auth matrix are valid\nplugins=(azure-vm-agents windows-azure-storage matrix-auth workflow-aggregator azure-app-service tfs azure-acs azure-container-agents)\nfor plugin in \"${plugins[@]}\"; do\n  run_util_script \"jenkins/run-cli-command.sh\" -c \"install-plugin $plugin -deploy\"\ndone\n\n#allow anonymous read access\ninter_jenkins_config=$(sed -zr -e\"s|<authorizationStrategy.*</authorizationStrategy>|{auth-strategy-token}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{auth-strategy-token}'/${jenkins_auth_matrix_conf}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#set up Jenkins URL to private_ip:8080 so JNLP connections can be established\necho \"${jenkins_location_conf}\" | sudo tee /var/lib/jenkins/jenkins.model.JenkinsLocationConfiguration.xml > /dev/null\n\n#disable 'It appears that your reverse proxy set up is broken' warning.\n# This is visible when connecting through SSH tunneling\ninter_jenkins_config=$(sed -zr -e\"s|<disabledAdministrativeMonitors/>|{disable-reverse-proxy-token}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{disable-reverse-proxy-token}'/${jenkins_disable_reverse_proxy_warning}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#Open a fixed port for JNLP\ninter_jenkins_config=$(sed -zr -e\"s|<slaveAgentPort.*</slaveAgentPort>|{slave-agent-port}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{slave-agent-port}'/${jenkins_agent_port}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#restart jenkins\nsudo service jenkins restart\n\n#install the service principal\nmsi_cred=$(cat <<EOF\n<com.microsoft.azure.util.AzureMsiCredentials>\n  <scope>GLOBAL</scope>\n  <id>azure_service_principal</id>\n  <description>Local MSI</description>\n  <msiPort>50342</msiPort>\n</com.microsoft.azure.util.AzureMsiCredentials>\nEOF\n)\nsp_cred=$(cat <<EOF\n<com.microsoft.azure.util.AzureCredentials>\n  <scope>GLOBAL</scope>\n  <id>azure_service_principal</id>\n  <description>Manual Service Principal</description>\n  <data>\n    <subscriptionId>${subscription_id}</subscriptionId>\n    <clientId>${service_principal_id}</clientId>\n    <clientSecret>${service_principal_secret}</clientSecret>\n    <oauth2TokenEndpoint>https://login.windows.net/${tenant_id}</oauth2TokenEndpoint>\n    <serviceManagementURL>https://management.core.windows.net/</serviceManagementURL>\n    <tenant>${tenant_id}</tenant>\n    <authenticationEndpoint>https://login.microsoftonline.com/</authenticationEndpoint>\n    <resourceManagerEndpoint>https://management.azure.com/</resourceManagerEndpoint>\n    <graphEndpoint>https://graph.windows.net/</graphEndpoint>\n  </data>\n</com.microsoft.azure.util.AzureCredentials>\nEOF\n)\n\nretry_until_successful run_util_script \"jenkins/run-cli-command.sh\" -c \"version\"\n\nif [ \"${service_principal_type}\" == 'msi' ]; then\n  echo \"${msi_cred}\" > msi_cred.xml\n  run_util_script \"jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif msi_cred.xml\n  rm msi_cred.xml\nelse\n  echo \"${sp_cred}\" > sp_cred.xml\n  run_util_script \"jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif sp_cred.xml\n  rm sp_cred.xml\nfi\n\n#add cloud agents\nvm_agent_conf=conf=$(cat <<EOF\n<clouds>\n  <com.microsoft.azure.vmagent.AzureVMCloud>\n    <name>AzureVMAgents</name>\n    <cloudName>AzureVMAgents</cloudName>\n    <credentialsId>azure_service_principal</credentialsId>\n    <maxVirtualMachinesLimit>10</maxVirtualMachinesLimit>\n    <resourceGroupReferenceType>existing</resourceGroupReferenceType>\n    <existingResourceGroupName>${resource_group}</existingResourceGroupName>\n    <vmTemplates>\n      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n        <templateName>win-agent</templateName>\n        <labels>win</labels>\n        <location>${location}</location>\n        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>\n        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>\n        <diskType>managed</diskType>\n        <storageAccountType>Standard_LRS</storageAccountType>\n        <noOfParallelJobs>1</noOfParallelJobs>\n        <usageMode>NORMAL</usageMode>\n        <shutdownOnIdle>false</shutdownOnIdle>\n        <imageTopLevelType>basic</imageTopLevelType>\n        <builtInImage>Windows Server 2016</builtInImage>\n        <credentialsId>agent_admin_account</credentialsId>\n        <retentionTimeInMin>60</retentionTimeInMin>\n      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n        <templateName>linux-agent</templateName>\n        <labels>linux</labels>\n        <location>${location}</location>\n        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>\n        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>\n        <diskType>managed</diskType>\n        <storageAccountType>Standard_LRS</storageAccountType>\n        <noOfParallelJobs>1</noOfParallelJobs>\n        <usageMode>NORMAL</usageMode>\n        <shutdownOnIdle>false</shutdownOnIdle>\n        <imageTopLevelType>basic</imageTopLevelType>\n        <builtInImage>Ubuntu 16.04 LTS</builtInImage>\n        <credentialsId>agent_admin_account</credentialsId>\n        <retentionTimeInMin>60</retentionTimeInMin>\n      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n    </vmTemplates>\n    <deploymentTimeout>1200</deploymentTimeout>\n    <approximateVirtualMachineCount>0</approximateVirtualMachineCount>\n  </com.microsoft.azure.vmagent.AzureVMCloud>\n</clouds>\nEOF\n)\n\naci_agent_conf=$(cat <<EOF\n<clouds>\n  <com.microsoft.jenkins.containeragents.aci.AciCloud>\n    <name>AciAgents</name>\n    <credentialsId>azure_service_principal</credentialsId>\n    <resourceGroup>${resource_group}</resourceGroup>\n    <templates>\n      <com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>\n        <name>aciagents</name>\n        <image>jenkinsci/jnlp-slave</image>\n        <osType>Linux</osType>\n        <command>jenkins-slave -url \\${rootUrl} \\${secret} \\${nodeName}</command>\n        <rootFs>/home/jenkins</rootFs>\n        <timeout>10</timeout>\n        <cpu>1</cpu>\n        <memory>1.5</memory>\n        <retentionStrategy class=\"com.microsoft.jenkins.containeragents.strategy.ContainerOnceRetentionStrategy\" />\n      </com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>\n    </templates>\n  </com.microsoft.jenkins.containeragents.aci.AciCloud>\n</clouds>\nEOF\n)\n\nagent_admin_password=$(head /dev/urandom | tr -dc A-Z | head -c 4)$(head /dev/urandom | tr -dc a-z | head -c 4)$(head /dev/urandom | tr -dc 0-9 | head -c 4)'!@'\nagent_admin_cred=$(cat <<EOF\n<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>\n  <scope>GLOBAL</scope>\n  <id>agent_admin_account</id>\n  <description>the admin account for the vm agents</description>\n  <username>agentadmin</username>\n  <password>${agent_admin_password}</password>\n</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>\nEOF\n)\n\nif [ \"${cloud_agents}\" == 'vm' ]; then\n  echo \"${agent_admin_cred}\" > agent_admin_cred.xml\n  run_util_script \"jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif agent_admin_cred.xml\n  rm agent_admin_cred.xml\n  inter_jenkins_config=$(sed -zr -e\"s|<clouds/>|{clouds}|\" /var/lib/jenkins/config.xml)\n  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${vm_agent_conf}}\n  echo \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\nelif [ \"${cloud_agents}\" == 'aci' ]; then\n  inter_jenkins_config=$(sed -zr -e\"s|<clouds/>|{clouds}|\" /var/lib/jenkins/config.xml)\n  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${aci_agent_conf}}\n  echo \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\nfi\n\n#install nginx\nsudo apt-get install nginx --yes\n\n#configure nginx\necho \"${nginx_reverse_proxy_conf}\" | sudo tee /etc/nginx/sites-enabled/default > /dev/null\n\n#don't show version in headers\nsudo sed -i \"s|.*server_tokens.*|server_tokens off;|\" /etc/nginx/nginx.conf\n\n#install jenkins-on-azure web page\nrun_util_script \"jenkins/jenkins-on-azure/install-web-page.sh\" -u \"${jenkins_fqdn}\"  -l \"${azure_web_page_location}\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\n#restart nginx\nsudo service nginx restart\n\n# Restart Jenkins\n#\n# As of Jenkins 2.107.3, reload-configuration is not sufficient to instruct Jenkins to pick up all the configuration\n# updates gracefully. Jenkins will be trapped in the blank SetupWizard mode after initial user setup, and the user\n# cannot proceed their work on the Jenkins instance.\n#\n# A restart will do the full reloading.\nsudo service jenkins restart\n# Wait until Jenkins is fully startup and functioning.\nretry_until_successful run_util_script \"jenkins/run-cli-command.sh\" -c \"version\"\n\n#install common tools\nsudo apt-get install git --yes\nsudo apt-get install azure-cli --yes\n", "num_lines": 483}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --command|-c             [Required]: Jenkins cli command to run\n  --command_input_file|-cif          : File path containing the input to the CLI command\n  --jenkins_url|-j                   : Jenkins URL, defaulted to \"http://localhost:8080/\"\n  --jenkins_username|-ju             : Jenkins user name, defaulted to \"admin\"\n  --jenkins_password|-jp             : Jenkins password. If not specified and the user name is \"admin\", the initialAdminPassword will be used\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    >&2 echo \"Parameter '$name' cannot be empty.\"\n    print_usage\n    exit -1\n  fi\n}\n\n#set defaults\njenkins_url=\"http://localhost:8080/\"\njenkins_username=\"admin\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --command|-c)\n      command=\"$1\"\n      shift\n      ;;\n    --command_input_file|-cif)\n      command_input_file=\"$1\"\n      shift\n      ;;\n    --jenkins_url|-j)\n      jenkins_url=\"$1\"\n      shift\n      ;;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\"\n      shift\n      ;;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      >&2 echo \"ERROR: Unknown argument '$key' to script '$0'\"\n      exit -1\n  esac\ndone\n\nthrow_if_empty jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty jenkins_password $jenkins_password\nfi\n\nfunction retry_until_successful {\n  counter=0\n  \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    \"${@}\"\n  done;\n}\n\nfunction retry_until_successful_with_input {\n  input_file=$1\n  shift\n  counter=0\n  cat \"$input_file\" | \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    cat \"$input_file\" | \"${@}\"\n  done;\n}\n\nif [ ! -e jenkins-cli.jar ]; then\n  >&2 echo \"Downloading Jenkins CLI...\"\n  retry_until_successful wget ${jenkins_url}jnlpJars/jenkins-cli.jar -O jenkins-cli.jar\nfi\n\nif [ -z \"$jenkins_password\" ]; then\n  # NOTE: Intentionally setting this after the first retry_until_successful to ensure the initialAdminPassword file exists\n  jenkins_password=`sudo cat /var/lib/jenkins/secrets/initialAdminPassword`\nfi\n\n>&2 echo \"Running \\\"${command}\\\"...\"\nif [ -z \"${command_input_file}\" ]; then\n  retry_until_successful java -jar jenkins-cli.jar -s \"${jenkins_url}\" -auth \"${jenkins_username}\":\"${jenkins_password}\" $command\nelse\n  retry_until_successful_with_input \"${command_input_file}\" java -jar jenkins-cli.jar -s \"${jenkins_url}\" -auth \"${jenkins_username}\":\"${jenkins_password}\" $command\nfi", "num_lines": 115}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo echo \"1\" > /var/lib/jenkins/jenkins.install.InstallUtil.lastExecVersion\n\nunsecure_config_xml=$(sed -zr \\\n    -e \"s|<useSecurity>.*</useSecurity>|<useSecurity>false</useSecurity>|\"\\\n    -e \"s|<authorizationStrategy.*</authorizationStrategy>||\"\\\n    -e \"s|<securityRealm.*</securityRealm>||\"\\\n  /var/lib/jenkins/config.xml)\n\necho \"${unsecure_config_xml}\" > /var/lib/jenkins/config.xml\n\nsudo service jenkins restart\n", "num_lines": 14}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --jenkins_url|-j                [Required]: Jenkins URL\n  --jenkins_username|-ju          [Required]: Jenkins user name\n  --jenkins_password|-jp                    : Jenkins password. If not specified and the user name is \"admin\", the initialAdminPassword will be used\n  --aks_resource_group|-ag        [Required]: Resource group for the target Azure Kubernetes Service (AKS)\n  --aks_name|-an                  [Required]: Name of the AKS\n  --sp_credentials_id|-spi                  : Desired Jenkins Azure service principal ID\n  --sp_credentials_desc|-spd                : Desired Jenkins Azure service princiapl description\n  --sp_subscription_id|-sps       [Required]: Subscription ID for the Azure service principal\n  --sp_client_id|-spc             [Required]: Client ID for the Azure service principal\n  --sp_client_password|-spp       [Required]: Client secrets for the Azure service principal\n  --sp_tenant_id|-spt             [Required]: Tenant ID for the Azure service principal\n  --sp_environment|-spe                     : Azure environment for the Azure service principal\n  --job_short_name|-jsn                     : Desired Jenkins job short name\n  --job_display_name|-jdn                   : Desired Jenkins job display name\n  --job_description|-jd                     : Desired Jenkins job description\n  --artifacts_location|-al                  : Url used to reference other scripts/artifacts.\n  --sas_token|-st                           : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\nsp_credentials_id=\"sp\"\nsp_credentials_desc=\"Service Principal to manage Azure resources\"\nsp_environment=\"Azure\"\njob_short_name=\"aks-blue-green-deployment\"\njob_display_name=\"AKS Kubernetes Blue-green Deployment\"\njob_description=\"A pipeline that demonstrates the blue-green deployment to AKS Kubernetes with the azure-acs Jenkins plugin.\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_url|-j)\n      jenkins_url=\"$1\"\n      shift\n      ;;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\"\n      shift\n      ;;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\"\n      shift\n      ;;\n    --aks_resource_group|-ag)\n      aks_resource_group=\"$1\"\n      shift\n      ;;\n    --aks_name|-an)\n      aks_name=\"$1\"\n      shift\n      ;;\n    --sp_credentials_id|-spi)\n      sp_credentials_id=\"$1\"\n      shift\n      ;;\n    --sp_credentials_desc|-spd)\n      sp_credentials_desc=\"$1\"\n      shift\n      ;;\n    --sp_subscription_id|-sps)\n      sp_subscription_id=\"$1\"\n      shift\n      ;;\n    --sp_client_id|-spc)\n      sp_client_id=\"$1\"\n      shift\n      ;;\n    --sp_client_password|-spp)\n      sp_client_password=\"$1\"\n      shift\n      ;;\n    --sp_tenant_id|-spt)\n      sp_tenant_id=\"$1\"\n      shift\n      ;;\n    --sp_environment|-spe)\n      sp_environment=\"$1\"\n      shift\n      ;;\n    --job_short_name|-jsn)\n      job_short_name=\"$1\"\n      shift\n      ;;\n    --job_display_name|-jdn)\n      job_display_name=\"$1\"\n      shift\n      ;;\n    --job_description|-jd)\n      job_description=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --jenkins_url \"$jenkins_url\"\nthrow_if_empty --jenkins_username \"$jenkins_username\"\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty --jenkins_password \"$jenkins_password\"\nfi\nthrow_if_empty --aks_resource_group \"$aks_resource_group\"\nthrow_if_empty --aks_name \"$aks_name\"\nthrow_if_empty --sp_credentials_id \"$sp_credentials_id\"\nthrow_if_empty --sp_subscription_id \"$sp_subscription_id\"\nthrow_if_empty --sp_client_id \"$sp_client_id\"\nthrow_if_empty --sp_client_password \"$sp_client_password\"\nthrow_if_empty --sp_tenant_id \"$sp_tenant_id\"\nthrow_if_empty --sp_environment \"$sp_environment\"\n\n#download dependencies\njob_xml=$(curl -s ${artifacts_location}/jenkins/blue-green/aks-k8s-blue-green-job.xml${artifacts_location_sas_token})\nsp_credentials_xml=$(curl -s ${artifacts_location}/jenkins/blue-green/sp-credentials.xml${artifacts_location_sas_token})\n\n#prepare job.xml\njob_xml=${job_xml//'{insert-job-display-name}'/${job_display_name}}\njob_xml=${job_xml//'{insert-job-description}'/${job_description}}\njob_xml=${job_xml//'{insert-aks-resource-group}'/${aks_resource_group}}\njob_xml=${job_xml//'{insert-aks-name}'/${aks_name}}\njob_xml=${job_xml//'{insert-artifacts-location}'/${artifacts_location}}\njob_xml=${job_xml//'{insert-sas-token}'/${artifacts_location_sas_token}}\n\n#prepare sp-credentials.xml\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-credentials-id}'/${sp_credentials_id}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-credentials-desc}'/${sp_credentials_desc}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-subscription-id}'/${sp_subscription_id}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-client-id}'/${sp_client_id}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-client-password}'/${sp_client_password}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-tenant-id}'/${sp_tenant_id}}\nsp_credentials_xml=${sp_credentials_xml//'{insert-sp-environment}'/${sp_environment}}\n\n#add Azure service principal credentials\necho \"${sp_credentials_xml}\" >sp-credentials.xml\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c 'create-credentials-by-xml SystemCredentialsProvider::SystemContextResolver::jenkins (global)' -cif \"sp-credentials.xml\"\n\n#add job\necho \"${job_xml}\" >job.xml\nrun_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-job ${job_short_name}\" -cif \"job.xml\"\n\n# clean up\nrm -f sp-credentials.xml job.xml\n", "num_lines": 186}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --resource_group|-g             [Required]: Resource group for the target Azure Kubernetes Service (AKS)\n  --aks_name|-n                   [Required]: Name of the AKS\n  --sp_subscription_id|-sps       [Required]: Subscription ID for the Azure service principal\n  --sp_client_id|-spc             [Required]: Client ID for the Azure service principal\n  --sp_client_password|-spp       [Required]: Client secrets for the Azure service principal\n  --sp_tenant_id|-spt             [Required]: Tenant ID for the Azure service principal\n  --sp_environment|-spe                     : Azure environment for the Azure service principal\n  --artifacts_location|-al                  : Url used to reference other scripts/artifacts.\n  --sas_token|-st                           : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\nsp_environment=Azure\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --resource_group|-g)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --aks_name|-n)\n      aks_name=\"$1\"\n      shift\n      ;;\n    --sp_subscription_id|-sps)\n      sp_subscription_id=\"$1\"\n      shift\n      ;;\n    --sp_client_id|-spc)\n      sp_client_id=\"$1\"\n      shift\n      ;;\n    --sp_client_password|-spp)\n      sp_client_password=\"$1\"\n      shift\n      ;;\n    --sp_tenant_id|-spt)\n      sp_tenant_id=\"$1\"\n      shift\n      ;;\n    --sp_environment|-spe)\n      sp_environment=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --resource_group \"$resource_group\"\nthrow_if_empty --aks_name \"$aks_name\"\nthrow_if_empty --sp_subscription_id \"$sp_subscription_id\"\nthrow_if_empty --sp_client_id \"$sp_client_id\"\nthrow_if_empty --sp_client_password \"$sp_client_password\"\nthrow_if_empty --sp_tenant_id \"$sp_tenant_id\"\nthrow_if_empty --sp_environment \"$sp_environment\"\n\nrun_util_script jenkins/blue-green/fetch-k8s-deployment-config.sh \\\n  --artifacts_location \"$artifacts_location\" \\\n  --sas_token \"${artifacts_location_sas_token}\" \\\n  --directory k8s \\\n  -f deployment.yml -f service.yml -f test-endpoint.yml\n\nsed -e 's/\\${TARGET_ROLE}/blue/g; s/\\${TOMCAT_VERSION}/7.0-jre8/g' k8s/deployment.yml >k8s/deployment-blue.yml\nsed -e 's/\\${TARGET_ROLE}/green/g; s/\\${TOMCAT_VERSION}/7.0-jre8/g' k8s/deployment.yml >k8s/deployment-green.yml\nsed -e 's/\\${TARGET_ROLE}/blue/g; s/\\${TOMCAT_VERSION}/7.0-jre8/g' k8s/service.yml >k8s/service-blue.yml\nsed -e 's/\\${TARGET_ROLE}/blue/g' k8s/test-endpoint.yml >k8s/test-endpoint-blue.yml\nsed -e 's/\\${TARGET_ROLE}/green/g' k8s/test-endpoint.yml >k8s/test-endpoint-green.yml\n\naz login --service-principal -u \"$sp_client_id\" -p \"$sp_client_password\" -t \"$sp_tenant_id\"\naz account set --subscription \"$sp_subscription_id\"\naz aks get-credentials --resource-group \"${resource_group}\" --name \"${aks_name}\" --admin --file kubeconfig\n\nkubectl --kubeconfig kubeconfig apply -f k8s/deployment-blue.yml\nkubectl --kubeconfig kubeconfig apply -f k8s/deployment-green.yml\nkubectl --kubeconfig kubeconfig apply -f k8s/service-blue.yml\nkubectl --kubeconfig kubeconfig apply -f k8s/test-endpoint-blue.yml\nkubectl --kubeconfig kubeconfig apply -f k8s/test-endpoint-green.yml\n\nfunction wait_public_ip() {\n  # wait 10 minutes for the service endpoint public IP to be ready\n  # it takes a long time for Azure to provision the frontend load balancer and the public IP address\n  local name=\"$1\"\n  local count=0\n  while true; do\n    count=$(expr $count + 1)\n    endpoint_ip=$(kubectl --kubeconfig=kubeconfig get services \"$name\" --output json | jq -r '.status.loadBalancer.ingress[0].ip')\n    if [ \"$endpoint_ip\" != null ]; then\n      echo \"$name ip: $endpoint_ip\"\n      break\n    fi\n    if [ \"$count\" -gt 60 ]; then\n        echo \"Timeout while waiting for the $name IP\"\n        exit 1\n    fi\n    echo \"$name IP not ready, sleep 10 seconds...\"\n    sleep 10\n  done\n}\n\nwait_public_ip \"tomcat-service\"\nwait_public_ip \"tomcat-test-blue\"\nwait_public_ip \"tomcat-test-green\"\n\n# keep for diagnostics\n#rm -rf k8s\n\naz logout\n", "num_lines": 155}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --file|-f                                 : config file name to be downloaded, may be applied multiple times.\n  --directory|-d                            : directory to store the downloaded files.\n  --artifacts_location|-al                  : Url used to reference other scripts/artifacts.\n  --sas_token|-st                           : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\nconfig_files=()\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\nartifacts_location_sas_token=\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --file|-f)\n      config_files+=(\"$1\")\n      shift\n      ;;\n    --directory|-d)\n      directory=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --artifacts_location \"$artifacts_location\"\nif [[ \"${#config_files[@]}\" == 0 ]]; then\n    config_files=(deployment.yml service.yml test-endpoint.yml)\nfi\n\nif [[ -n \"$directory\" ]]; then\n    mkdir -p \"$directory\"\n    cd \"$directory\"\nfi\n\nfor file in \"${config_files[@]}\"; do\n    wget -O \"$file\" \"${artifacts_location}jenkins/blue-green/k8s/${file}${artifacts_location_sas_token}\"\ndone\n", "num_lines": 85}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --location|-l            [Required] : The web page location\n  --url|-u                 [Required] : Domain URL\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\n#defaults\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --location|-l)\n      location=\"$1\"\n      shift\n      ;;\n    --url|-u)\n      url=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --location $location\nthrow_if_empty --url $url\n\n#install jenkins-on-azure web page\nsudo mkdir ${location}\nartifacts=(\"headshot.png\" \"title.png\" \"azure.svg\" \"copy.png\" \"site.css\" \"site.js\" \"index.html\")\nfor i in \"${artifacts[@]}\"; do\n  if [[ $i =~ .*html.* ]]\n  then\n      raw_resource=$(curl --silent \"${artifacts_location}/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}\")\n      final_resource=${raw_resource//'{domain-name}'/${url}}\n      echo \"${final_resource}\" | sudo tee ${location}/$i > /dev/null\n    else\n      curl --silent \"${artifacts_location}/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}\" -o ${location}/$i\n  fi\ndone\n", "num_lines": 74}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0 \n\nArguments\n  --app_id|-ai                           [Required]: Service principal app id used by Spinnaker to dynamically manage resources\n  --app_key|-ak                          [Required]: Service principal app key used by Spinnaker to dynamically manage resources\n  --username|-u                          [Required]: vm username\n  --tenant_id|-ti                        [Required]: Tenant id\n  --subscription_id|-si                  [Required]: Subscription id\n  --resource_group|-rg                   [Required]: Resource group containing your key vault and packer storage account\n  --vault_name|-vn                       [Required]: Vault used to store default Username/Password for deployed VMSS\n  --storage_account_name|-san            [Required]: Storage account name used for front50\n  --storage_account_key|-sak             [Required]: Storage account key used for front50\n  --aks_cluster_name|-acn                [Required]: AKS Cluster Name for deploy spinnaker\n  --aks_resource_group|-arg              [Required]: Resource group containing your aks\n  --use_ssh_public_key|-uspk             [Required]: Use ssh public key\n  --region|-r                                      : Region for VMSS created by Spinnaker, defaulted to westus\n  --artifacts_location|-al                         : Url used to reference other scripts/artifacts.\n  --sas_token|-st                                  : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nfunction install_az() {\n  if !(command -v az >/dev/null); then\n    sudo apt-get update\n    sudo apt-get install curl apt-transport-https lsb-release gnupg -y\n    curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null\n    AZ_REPO=$(lsb_release -cs)\n    echo \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n    sudo apt-get update\n    sudo apt-get install azure-cli\n  fi\n}\n\n# Set defaults\nartifacts_location=\"https://raw.githubusercontent.com/azure/azure-devops-utils/master/\"\nartifacts_location_sas_token=\"\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --app_id|-ai)\n      app_id=\"$1\";;\n    --app_key|-ak)\n      app_key=\"$1\";;\n    --username|-u)\n      username=\"$1\";;\n    --tenant_id|-ti)\n      tenant_id=\"$1\";;\n    --subscription_id|-si)\n      subscription_id=\"$1\";;\n    --resource_group|-rg)\n      resource_group=\"$1\";;\n    --vault_name|-vn)\n      vault_name=\"$1\";;\n    --storage_account_name|-san)\n      storage_account_name=\"$1\";;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\";;\n    --aks_cluster_name|-acn)\n      aks_cluster_name=\"$1\";;\n    --aks_resource_group|-arg)\n      aks_resource_group=\"$1\";;\n    --use_ssh_public_key|-uspk)\n      use_ssh_public_key=\"$1\";;\n    --region|-r)\n      region=\"$1\";;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\";;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty app_id $app_id\nthrow_if_empty app_key $app_key\nthrow_if_empty username $username\nthrow_if_empty tenant_id $tenant_id\nthrow_if_empty subscription_id $subscription_id\nthrow_if_empty resource_group $resource_group\nthrow_if_empty vault_name $vault_name\nthrow_if_empty storage_account_name $storage_account_name\nthrow_if_empty storage_account_key $storage_account_key\nthrow_if_empty region $region\nthrow_if_empty aks_cluster_name $aks_cluster_name\nthrow_if_empty aks_resource_group $aks_resource_group\nthrow_if_empty use_ssh_public_key $use_ssh_public_key\n\n#install az and hal\ninstall_az\nrun_util_script \"spinnaker/install_halyard/install_halyard.sh\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -u \"$username\"\n\n#get-credentials from aks\naz login --service-principal -u $app_id -p $app_key -t $tenant_id\naz aks get-credentials --resource-group $aks_resource_group --name $aks_cluster_name -f /home/$username/.kube/config\nchmod 777 /home/$username/.kube/config\n\n#install kubectl\ncurl -LO https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl\nchmod +x ./kubectl\nsudo mv ./kubectl /usr/local/bin/kubectl\n\n# Configure Azure provider for Spinnaker\necho \"$app_key\" | hal config provider azure account add my-azure-account \\\n  --client-id \"$app_id\" \\\n  --tenant-id \"$tenant_id\" \\\n  --subscription-id \"$subscription_id\" \\\n  --default-key-vault \"$vault_name\" \\\n  --default-resource-group \"$resource_group\" \\\n  --packer-resource-group \"$resource_group\" \\\n  --useSshPublicKey \"$use_ssh_public_key\" \\\n  --app-key\n\n#change region if region not in eastus or westus\nif [ \"$region\" != eastus ] && [ \"$region\" != westus ]; then\nhal config provider azure account edit my-azure-account \\\n  --regions \"eastus\",\"westus\",\"$region\"\nfi\nhal config provider azure enable\n\n# Configure kubernetes provider for Spinnaker\necho \"$app_key\" | hal config provider kubernetes account add my-k8s-v2-account \\\n  --provider-version v2 \\\n  --context $aks_cluster_name\nhal config provider kubernetes account edit my-k8s-v2-account --kubeconfig-file /home/$username/.kube/config\nhal config provider kubernetes enable\nhal config features edit --artifacts true\nhal config deploy edit --type distributed --account-name my-k8s-v2-account\n\n# Deploy Spinnaker to aks\nsudo hal deploy apply\n\n# Connect to Spinnaker\necho \"Connecting to Spinnaker...\"\nhal deploy connect &>/dev/null &\n# Wait for connection\necho \"while !(nc -z localhost 8084) || !(nc -z localhost 9000); do sleep 1; done\" | timeout 20 bash\nif [ $? -ne 0 ]; then\n  echo \"Failed to connect to Spinnaker.\"\nelse\n  echo \"Successfully connected to Spinnaker.\"\nfi\n", "num_lines": 177}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0 \n\nArguments\n  --app_id|-ai                           [Required]: Service principal app id used by Spinnaker to dynamically manage resources\n  --app_key|-ak                          [Required]: Service principal app key used by Spinnaker to dynamically manage resources\n  --username|-u                          [Required]: username\n  --tenant_id|-ti                        [Required]: Tenant id\n  --subscription_id|-si                  [Required]: Subscription id\n  --resource_group|-rg                   [Required]: Resource group containing your key vault and packer storage account\n  --vault_name|-vn                       [Required]: Vault used to store default Username/Password for deployed VMSS\n  --storage_account_name|-san            [Required]: Storage account name used for front50\n  --storage_account_key|-sak             [Required]: Storage account key used for front50\n  --vm_fqdn|-vf                          [Required]: FQDN for the Jenkins instance hosting the Aptly repository\n  --use_ssh_public_key|-uspk             [Required]: Use ssh public key\n  --jenkins_password|-jp                           : Jenkins password\n  --aks_cluster_name|-acn                          : AKS ClusterName for deploy spinnaker\n  --aks_resource_group|-arg                        : Resource group containing your aks\n  --region|-r                                      : Region for VMSS created by Spinnaker, defaulted to westus\n  --artifacts_location|-al                         : Url used to reference other scripts/artifacts.\n  --sas_token|-st                                  : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n# Set defaults\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\nartifacts_location_sas_token=\"\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --app_id|-ai)\n      app_id=\"$1\";;\n    --app_key|-ak)\n      app_key=\"$1\";;\n    --username|-u)\n      username=\"$1\";;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\";;\n    --tenant_id|-ti)\n      tenant_id=\"$1\";;\n    --subscription_id|-si)\n      subscription_id=\"$1\";;\n    --resource_group|-rg)\n      resource_group=\"$1\";;\n    --vault_name|-vn)\n      vault_name=\"$1\";;\n    --storage_account_name|-san)\n      storage_account_name=\"$1\";;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\";;\n    --aks_cluster_name|-acn)\n      aks_cluster_name=\"$1\";;\n    --aks_resource_group|-arg)\n      aks_resource_group=\"$1\";;\n    --region|-r)\n      region=\"$1\";;\n    --vm_fqdn|-vf)\n      vm_fqdn=\"$1\";;\n    --use_ssh_public_key|-uspk)\n      use_ssh_public_key=\"$1\";;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\";;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty app_id $app_id\nthrow_if_empty app_key $app_key\nthrow_if_empty username $username\nthrow_if_empty tenant_id $tenant_id\nthrow_if_empty subscription_id $subscription_id\nthrow_if_empty resource_group $resource_group\nthrow_if_empty vault_name $vault_name\nthrow_if_empty storage_account_name $storage_account_name\nthrow_if_empty storage_account_key $storage_account_key\nthrow_if_empty vm_fqdn $vm_fqdn\nthrow_if_empty use_ssh_public_key $use_ssh_public_key\n\n#installed on the vmss if there is no aks_cluster_name, otherwise installed on aks\nif [ -z \"$aks_cluster_name\" ]\nthen\n      run_util_script \"quickstart_template/301-jenkins-aptly-spinnaker-vmss.sh\"  -ju \"$username\" -jp \"$jenkins_password\" -ai \"$app_id\" -ak \"$app_key\" -ti \"$tenant_id\" -si \"$subscription_id\" -rg \"$resource_group\" -vn \"$vault_name\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -vf \"$vm_fqdn\" -r \"$region\" -al \"$artifacts_location\" -st \"$artifacts_location_sas_token\" -uspk \"$use_ssh_public_key\"\nelse\n      run_util_script \"quickstart_template/101-spinnaker-aks.sh\"  -u \"$username\" -ai \"$app_id\" -ak \"$app_key\" -ti \"$tenant_id\" -si \"$subscription_id\" -rg \"$resource_group\" -vn \"$vault_name\" -acn \"$aks_cluster_name\" -arg \"$aks_resource_group\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -r \"$region\" -al \"$artifacts_location\" -st \"$artifacts_location_sas_token\" -uspk \"$use_ssh_public_key\"\nfi\n", "num_lines": 122}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --storage_account_name|-san [Required] : Storage Account name used for Spinnaker's persistent storage\n  --storage_account_key|-sak  [Required] : Storage Account key used for Spinnaker's persistent storage\n  --username|-u               [Required] : User for which to install Halyard\n  --artifacts_location|-al               : Url used to reference other scripts/artifacts.\n  --sas_token|-st                        : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --storage_account_name|-san)\n      storage_account_name=\"$1\";;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\";;\n    --username|-u)\n      username=\"$1\";;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\";;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty storage_account_name $storage_account_name\nthrow_if_empty storage_account_key $storage_account_key\nthrow_if_empty username $username\n\nrun_util_script \"spinnaker/install_halyard/install_halyard.sh\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -u \"$username\"\n\nsudo hal deploy apply\n\n# Wait for Spinnaker services to be up before returning\ntimeout=180\necho \"while !(nc -z localhost 8084) || !(nc -z localhost 9000); do sleep 1; done\" | timeout $timeout bash\nreturn_value=$?\nif [ $return_value -ne 0 ]; then\n  >&2 echo \"Failed to connect to Spinnaker within '$timeout' seconds.\"\n  exit $return_value\nfi", "num_lines": 77}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nfunction print_usage() {\n  cat <<EOF\nhttps://github.com/Azure/azure-quickstart-templates/tree/master/201-jenkins-acr\nCommand\n  $0\nArguments\n  --vm_user_name|-u        [Required] : VM user name\n  --git_url|-g             [Required] : Git URL with a Dockerfile in it's root\n  --registry|-r            [Required] : Registry url targeted by the pipeline\n  --registry_user_name|-ru [Required] : Registry user name\n  --registry_password|-rp  [Required] : Registry password\n  --repository|-rr         [Required] : Repository targeted by the pipeline\n  --jenkins_fqdn|-jf       [Required] : Jenkins FQDN\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#defaults\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --vm_user_name|-u)\n      vm_user_name=\"$1\"\n      shift\n      ;;\n    --git_url|-g)\n      git_url=\"$1\"\n      shift\n      ;;\n    --registry|-r)\n      registry=\"$1\"\n      shift\n      ;;\n    --registry_user_name|-ru)\n      registry_user_name=\"$1\"\n      shift\n      ;;\n    --registry_password|-rp)\n      registry_password=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --vm_user_name $vm_user_name\nthrow_if_empty --git_url $git_url\nthrow_if_empty --registry $registry\nthrow_if_empty --registry_user_name $registry_user_name\nthrow_if_empty --registry_password $registry_password\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\n\nif [ -z \"$repository\" ]; then\n  repository=\"${vm_user_name}/myfirstapp\"\nfi\n\n#install jenkins\nrun_util_script \"jenkins/install_jenkins.sh\" -jf \"${jenkins_fqdn}\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\n#install git\nsudo apt-get install git --yes\n\n#install docker if not already installed\nif !(command -v docker >/dev/null); then\n  sudo curl -sSL https://get.docker.com/ | sh\nfi\n\n#make sure jenkins has access to docker cli\nsudo gpasswd -a jenkins docker\nskill -KILL -u jenkins\nsudo service jenkins restart\n\necho \"Including the pipeline\"\nrun_util_script \"jenkins/add-docker-build-job.sh\" -j \"http://localhost:8080/\" -ju \"admin\" -g \"${git_url}\" -r \"${registry}\" -ru \"${registry_user_name}\"  -rp \"${registry_password}\" -rr \"$repository\" -sps \"* * * * *\" -al \"$artifacts_location\" -st \"$artifacts_location_sas_token\"\n", "num_lines": 123}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nhttps://github.com/Azure/azure-quickstart-templates/tree/master/301-jenkins-acr-spinnaker-k8s\nCommand\n  $0\nArguments\n  --app_id|-ai                       [Required] : Service principal app id  used to dynamically manage resource in your subscription\n  --app_key|-ak                      [Required] : Service principal app key used to dynamically manage resource in your subscription\n  --subscription_id|-si              [Required] : Subscription Id\n  --tenant_id|-ti                    [Required] : Tenant Id\n  --user_name|-un                    [Required] : Admin user name for your Spinnaker VM and Kubernetes cluster\n  --git_repository|-gr               [Required] : Git URL with a Dockerfile in it's root\n  --resource_group|-rg               [Required] : Resource group containing your Kubernetes cluster\n  --master_fqdn|-mf                  [Required] : Master FQDN of your Kubernetes cluster\n  --storage_account_name|-san        [Required] : Storage Account name used for Spinnaker's persistent storage\n  --storage_account_key|-sak         [Required] : Storage Account key used for Spinnaker's persistent storage\n  --azure_container_registry|-acr    [Required] : Azure Container Registry url\n  --jenkins_fqdn|-jf                 [Required] : Jenkins FQDN\n  --docker_repository|-dr                       : Name of the docker repository to be created in your ACR\n  --pipeline_port|-pp                           : Port to target in your pipeline\n  --artifacts_location|-al                      : Url used to reference other scripts/artifacts.\n  --sas_token|-st                               : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nfunction add_empty_image_to_acr() {\n  # Install docker if not already installed\n  if !(command -v docker >/dev/null); then\n    sudo curl -sSL https://get.docker.com/ | sh\n  fi\n  sudo gpasswd -a $user_name docker\n\n  # Add (virtually) empty container to ACR to properly initialize Spinnaker. This fixes two bugs:\n  # 1. The pipeline isn't triggered on the first push to the ACR (according to the source code, Igor \"avoids publishing an event if this account has no indexed images (protects against a flushed redis)\")\n  # 2. Some dropdowns in the UI for the pipeline display a 'loading' symbol rather than the repository we configured\n  temp_dir=$(mktemp -d)\n  touch \"$temp_dir/README\"\n  echo \"This container is intentionally empty and only used as a placeholder.\" >\"$temp_dir/README\"\n  touch \"$temp_dir/Dockerfile\"\n  echo -e \"FROM scratch\\nADD . README\" >\"$temp_dir/Dockerfile\"\n  # We added the user to the docker group above, but that doesn't take effect until the next login so we still need to use sudo here\n  sudo docker login \"$azure_container_registry\" -u \"$app_id\" -p \"$app_key\"\n  sudo docker build $temp_dir --tag \"$azure_container_registry/$docker_repository\"\n  sudo docker push \"$azure_container_registry/$docker_repository\"\n  sudo docker rmi \"$azure_container_registry/$docker_repository\"\n  sudo docker logout\n}\n\nfunction install_kubectl() {\n  if !(command -v kubectl >/dev/null); then\n    kubectl_file=\"/usr/local/bin/kubectl\"\n    sudo curl -L -s -o $kubectl_file https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl\n    sudo chmod +x $kubectl_file\n  fi\n}\n\nfunction install_az() {\n  if !(command -v az >/dev/null); then\n    sudo apt-get update && sudo apt-get install -y libssl-dev libffi-dev python-dev\n    echo \"deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n    sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893\n    sudo apt-get install -y apt-transport-https\n    sudo apt-get -y update && sudo apt-get install -y azure-cli\n  fi\n}\n\nfunction add_bash_login() {\n  bash_login=\"/home/${user_name}/.bash_login\"\n  touch \"$bash_login\"\n  cat <<EOF > \"$bash_login\"\n### Connect to Spinnaker ###\necho \"Connecting to Spinnaker...\"\nhal deploy connect --no-validate &>/dev/null &\n\n# Wait for connection\necho \"while !(nc -z localhost 8084) || !(nc -z localhost 9000); do sleep 1; done\" | timeout 20 bash\n\nif [ $? -ne 0 ]; then\n  echo \"Failed to connect to Spinnaker.\"\nelse\n  echo \"Successfully connected to Spinnaker.\"\n  echo \"Enter 'Ctrl-C' in your terminal to exit the connection in the background.\"\nfi\n\necho \"Edit your ~/.bash_login file and remove the 'Connect to Spinnaker' section if you do not want to auto-connect on login.\"\n### Connect to Spinnaker ###\nEOF\n}\n\n#Set defaults\npipeline_port=\"8000\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\ndocker_repository=\"${vm_user_name}/myfirstapp\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --app_id|-ai)\n      app_id=\"$1\"\n      shift\n      ;;\n    --app_key|-ak)\n      app_key=\"$1\"\n      shift\n      ;;\n    --subscription_id|-si)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-ti)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --user_name|-un)\n      user_name=\"$1\"\n      shift\n      ;;\n    --git_repository|-gr)\n      git_repository=\"$1\"\n      shift\n      ;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --master_fqdn|-mf)\n      master_fqdn=\"$1\"\n      shift\n      ;;\n    --storage_account_name|-san)\n      storage_account_name=\"$1\"\n      shift\n      ;;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\"\n      shift\n      ;;\n    --azure_container_registry|-acr)\n      azure_container_registry=\"$1\"\n      shift\n      ;;\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --docker_repository|-dr)\n      docker_repository=\"$1\"\n      shift\n      ;;\n    --pipeline_port|-pp)\n      pipeline_port=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --app_id $app_id\nthrow_if_empty --app_key $app_key\nthrow_if_empty --subscription_id $subscription_id\nthrow_if_empty --tenant_id $tenant_id\nthrow_if_empty --user_name $user_name\nthrow_if_empty --git_repository $git_repository\nthrow_if_empty --resource_group $resource_group\nthrow_if_empty --master_fqdn $master_fqdn\nthrow_if_empty --storage_account_name $storage_account_name\nthrow_if_empty --storage_account_key $storage_account_key\nthrow_if_empty --azure_container_registry $azure_container_registry\nthrow_if_empty --docker_repository $docker_repository\nthrow_if_empty --pipeline_port $pipeline_port\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\n\nadd_empty_image_to_acr\n\ninstall_kubectl\n\ninstall_az\n\nrun_util_script \"spinnaker/install_halyard/install_halyard.sh\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -u \"$user_name\"\n\n# Copy kube config\naz login --service-principal -u \"$app_id\" -p \"$app_key\" --tenant \"$tenant_id\"\naz account set --subscription \"$subscription_id\"\nrun_util_script \"spinnaker/copy_kube_config/copy_kube_config.sh\" -un \"$user_name\" -rg \"$resource_group\" -mf \"$master_fqdn\"\naz logout\n\n# Configure Spinnaker Docker Registry Accounts\ndocker_hub_account=\"docker-hub-registry\"\nhal config provider docker-registry account add $docker_hub_account \\\n  --address \"https://index.docker.io/\" \\\n  --repositories \"library/nginx\" \"library/redis\" \"library/ubuntu\" # Spinnaker can't get the entire catalog for a public registry, so we have to list a few repos\nacr_account=\"azure-container-registry\"\necho \"$app_key\" | hal config provider docker-registry account add $acr_account \\\n  --address \"https://$azure_container_registry/\" \\\n  --username \"$app_id\" \\\n  --password\nhal config provider docker-registry enable\n\n# Configure Spinnaker Kubernetes Account\nkubeconfig_path=\"/home/${user_name}/.kube/config\"\nmy_kubernetes_account=\"my-kubernetes-account\"\nhal config provider kubernetes account add $my_kubernetes_account \\\n  --kubeconfig-file \"$kubeconfig_path\" \\\n  --context $(kubectl config current-context --kubeconfig \"$kubeconfig_path\") \\\n  --docker-registries \"$docker_hub_account\" \"$acr_account\"\nhal config provider kubernetes enable\n\n# Deploy Spinnaker to the Kubernetes cluster\nhal config deploy edit --account-name $my_kubernetes_account --type distributed\nhal deploy apply\n\n# Automatically connect to Spinnaker when logging in to DevOps VM\nadd_bash_login\n\n# Add Kubernetes pipeline\nrun_util_script \"spinnaker/add_k8s_pipeline/add_k8s_pipeline.sh\" \\\n  -an \"$acr_account\" \\\n  -rg \"$azure_container_registry\" \\\n  -rp \"$docker_repository\" \\\n  -p \"$pipeline_port\" \\\n  -al \"$artifacts_location\" \\\n  -st \"$artifacts_location_sas_token\"\n\nrun_util_script \"quickstart_template/201-jenkins-acr.sh\" -u \"$user_name\" \\\n  -g \"$git_repository\" \\\n  -r \"https://$azure_container_registry\" \\\n  -ru \"$app_id\" \\\n  -rp \"$app_key\" \\\n  -rr \"$docker_repository\" \\\n  -jf \"$jenkins_fqdn\" \\\n  -al \"$artifacts_location\" \\\n  -st \"$artifacts_location_sas_token\"", "num_lines": 271}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0 \n\nArguments\n  --app_id|-ai                           [Required]: Service principal app id used by Spinnaker to dynamically manage resources\n  --app_key|-ak                          [Required]: Service principal app key used by Spinnaker to dynamically manage resources\n  --jenkins_username|-ju                 [Required]: Jenkins username\n  --jenkins_password|-jp                 [Required]: Jenkins password\n  --tenant_id|-ti                        [Required]: Tenant id\n  --subscription_id|-si                  [Required]: Subscription id\n  --resource_group|-rg                   [Required]: Resource group containing your key vault and packer storage account\n  --vault_name|-vn                       [Required]: Vault used to store default Username/Password for deployed VMSS\n  --storage_account_name|-san            [Required]: Storage account name used for front50\n  --storage_account_key|-sak             [Required]: Storage account key used for front50\n  --vm_fqdn|-vf                          [Required]: FQDN for the Jenkins instance hosting the Aptly repository\n  --use_ssh_public_key|-uspk             [Required]: Use ssh public key\n  --region|-r                                      : Region for VMSS created by Spinnaker, defaulted to westus\n  --artifacts_location|-al                         : Url used to reference other scripts/artifacts.\n  --sas_token|-st                                  : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n# Set defaults\nregion=\"westus\"\nrepository_name=\"hello-karyon-rxnetty\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\nartifacts_location_sas_token=\"\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --app_id|-ai)\n      app_id=\"$1\";;\n    --app_key|-ak)\n      app_key=\"$1\";;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\";;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\";;\n    --tenant_id|-ti)\n      tenant_id=\"$1\";;\n    --subscription_id|-si)\n      subscription_id=\"$1\";;\n    --resource_group|-rg)\n      resource_group=\"$1\";;\n    --vault_name|-vn)\n      vault_name=\"$1\";;\n    --storage_account_name|-san)\n      storage_account_name=\"$1\";;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\";;\n    --region|-r)\n      region=\"$1\";;\n    --vm_fqdn|-vf)\n      vm_fqdn=\"$1\";;\n    --use_ssh_public_key|-uspk)\n      use_ssh_public_key=\"$1\";;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\";;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty app_id $app_id\nthrow_if_empty app_key $app_key\nthrow_if_empty jenkins_username $jenkins_username\nthrow_if_empty jenkins_password $jenkins_password\nthrow_if_empty tenant_id $tenant_id\nthrow_if_empty subscription_id $subscription_id\nthrow_if_empty resource_group $resource_group\nthrow_if_empty vault_name $vault_name\nthrow_if_empty storage_account_name $storage_account_name\nthrow_if_empty storage_account_key $storage_account_key\nthrow_if_empty vm_fqdn $vm_fqdn\nthrow_if_empty use_ssh_public_key $use_ssh_public_key\nthrow_if_empty region $region\n\ndefault_hal_config=\"/home/$jenkins_username/.hal/default\"\n\nrun_util_script \"spinnaker/install_halyard/install_halyard.sh\" -san \"$storage_account_name\" -sak \"$storage_account_key\" -u \"$jenkins_username\"\n# Change front50 port so it doesn't conflict with Jenkins\nfront50_settings=\"$default_hal_config/service-settings/front50.yml\"\nsudo -u $jenkins_username mkdir -p $(dirname \"$front50_settings\")\nsudo -u $jenkins_username touch \"$front50_settings\"\necho \"port: $front50_port\" > \"$front50_settings\"\n\n# Configure Azure provider for Spinnaker\necho \"$app_key\" | hal config provider azure account add my-azure-account \\\n  --client-id \"$app_id\" \\\n  --tenant-id \"$tenant_id\" \\\n  --subscription-id \"$subscription_id\" \\\n  --default-key-vault \"$vault_name\" \\\n  --default-resource-group \"$resource_group\" \\\n  --packer-resource-group \"$resource_group\" \\\n  --useSshPublicKey \"$use_ssh_public_key\" \\\n  --app-key\n\n#change region if region not in eastus or westus\nif [ \"$region\" != eastus ] && [ \"$region\" != westus ]; then\nhal config provider azure account edit my-azure-account \\\n  --regions \"eastus\",\"westus\",\"$region\" \nfi\nhal config provider azure enable\n\n# Configure Rosco (these params are not supported by Halyard yet)\nrosco_config=\"$default_hal_config/profiles/rosco-local.yml\"\nsudo -u $jenkins_username mkdir -p $(dirname \"$rosco_config\")\nsudo -u $jenkins_username touch \"$rosco_config\"\ncat <<EOF > \"$rosco_config\"\ndebianRepository: http://ppa.launchpad.net/openjdk-r/ppa/ubuntu trusty main;http://$vm_fqdn:9999 trusty main\ndefaultCloudProviderType: azure\nEOF\n\n# Configure Jenkins for Spinnaker\necho \"$jenkins_password\" | hal config ci jenkins master add Jenkins \\\n    --address \"http://localhost:8082\" \\\n    --username \"$jenkins_username\" \\\n    --password\n\nhal config ci jenkins enable\n\nrun_util_script \"jenkins/install_jenkins.sh\" -jf \"${vm_fqdn}\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\nrun_util_script \"jenkins/init-aptly-repo.sh\" -vf \"${vm_fqdn}\" -rn \"${repository_name}\"\n\nrun_util_script \"jenkins/add-aptly-build-job.sh\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\necho \"Setting up initial user...\"\n\n# Using single quote for username and password here to avoid dollar sign being recognized as start of variable\necho \"jenkins.model.Jenkins.instance.securityRealm.createAccount('$jenkins_username', '$jenkins_password')\"  > addUser.groovy\n\nrun_util_script \"jenkins/run-cli-command.sh\" -cif \"addUser.groovy\" -c \"groovy =\"\n\nrm \"addUser.groovy\"\n\n# Change the Jenkins port in order not to conflict with the Spinnaker front50 port\nport=8082\n\nsed -i -e \"s/\\(HTTP_PORT=\\).*/\\1$port/\"  /etc/default/jenkins\n\nservice jenkins restart\n\nsudo hal deploy apply\n\n# If redis is not started, start the redis-server\nnetstat -tln | grep \":6379 \"\n\nif [ $? -eq 1 ]\nthen\n        echo \"Redis is not started. Start the redis-server.\"\n        sudo redis-server /etc/redis/redis.conf\n        sleep 5\nfi\n\n# Double check and log if redis is still not running\nnetstat -tln | grep \":6379 \"\n\nif [ $? -eq 1 ]\nthen\n        echo \"Redis failed to start for second time. Related spinnaker micro-services might fail to start.\"\nfi\n\nnetstat -tln | grep \":8083 \"\nif [ $? -eq 1 ]\nthen\nsudo systemctl restart orca.service\nfi\n\nnetstat -tln | grep \":8080 \"\nif [ $? -eq 1 ]\nthen\nsudo systemctl restart front50.service\nfi\n\nnetstat -tln | grep \":8084 \"\nif [ $? -eq 1 ]\nthen\nsudo systemctl restart gate.service\nfi\n\n# Wait for Spinnaker services to be up before returning\ntimeout=180\necho \"while !(nc -z localhost 8084) || !(nc -z localhost 9000); do sleep 1; done\" | timeout $timeout bash\nreturn_value=$?\nif [ $return_value -ne 0 ]; then\n  >&2 echo \"Failed to connect to Spinnaker within '$timeout' seconds.\"\n  exit $return_value\nfi", "num_lines": 224}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nhttps://github.com/Azure/azure-quickstart-templates/tree/master/301-jenkins-k8s-blue-green\nCommand\n  $0\nArguments\n  --app_id|-ai                       [Required] : Service principal app id  used to dynamically manage resource in your subscription\n  --app_key|-ak                      [Required] : Service principal app key used to dynamically manage resource in your subscription\n  --subscription_id|-si              [Required] : Subscription Id\n  --tenant_id|-ti                    [Required] : Tenant Id\n  --resource_group|-rg               [Required] : Resource group containing your Kubernetes cluster\n  --aks_name|-an                     [Required] : Name of the Azure Kubernetes Service\n  --jenkins_fqdn|-jf                 [Required] : Jenkins FQDN\n  --artifacts_location|-al                      : Url used to reference other scripts/artifacts.\n  --sas_token|-st                               : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nfunction install_kubectl() {\n  if !(command -v kubectl >/dev/null); then\n    kubectl_file=\"/usr/local/bin/kubectl\"\n    sudo curl -L -s -o $kubectl_file https://storage.googleapis.com/kubernetes-release/release/$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)/bin/linux/amd64/kubectl\n    sudo chmod +x $kubectl_file\n  fi\n}\n\nfunction install_az() {\n  if !(command -v az >/dev/null); then\n    sudo apt-get update && sudo apt-get install -y libssl-dev libffi-dev python-dev\n    echo \"deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n    sudo apt-key adv --keyserver apt-mo.trafficmanager.net --recv-keys 417A0893\n    sudo apt-get install -y apt-transport-https\n    sudo apt-get -y update && sudo apt-get install -y azure-cli\n  fi\n}\n\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case \"$key\" in\n    --app_id|-ai)\n      app_id=\"$1\"\n      shift\n      ;;\n    --app_key|-ak)\n      app_key=\"$1\"\n      shift\n      ;;\n    --subscription_id|-si)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-ti)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --aks_name|-an)\n      aks_name=\"$1\"\n      shift\n      ;;\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --app_id \"$app_id\"\nthrow_if_empty --app_key \"$app_key\"\nthrow_if_empty --subscription_id \"$subscription_id\"\nthrow_if_empty --tenant_id \"$tenant_id\"\nthrow_if_empty --resource_group \"$resource_group\"\nthrow_if_empty --aks_name \"$aks_name\"\nthrow_if_empty --jenkins_fqdn \"$jenkins_fqdn\"\n\ninstall_kubectl\n\ninstall_az\n\nsudo apt-get install --yes jq\n\n#install jenkins\n#install jenkins\nrun_util_script \"jenkins/install_jenkins.sh\" \\\n  --jenkins_release_type verified \\\n  --jenkins_version_location \"${artifacts_location}jenkins/blue-green/verified-jenkins-version${artifacts_location_sas_token}\" \\\n  --jenkins_fqdn \"${jenkins_fqdn}\" \\\n  --artifacts_location \"${artifacts_location}\" \\\n  --sas_token \"${artifacts_location_sas_token}\"\n\nrun_util_script \"jenkins/blue-green/bootstrap-k8s-blue-green.sh\" \\\n    --resource_group \"$resource_group\" \\\n    --aks_name \"$aks_name\" \\\n    --sp_subscription_id \"$subscription_id\" \\\n    --sp_client_id \"$app_id\" \\\n    --sp_client_password \"$app_key\" \\\n    --sp_tenant_id \"$tenant_id\" \\\n    --artifacts_location \"$artifacts_location\" \\\n    --sas_token \"$artifacts_location_sas_token\"\n\nrun_util_script \"jenkins/blue-green/add-blue-green-job.sh\" \\\n    -j \"http://localhost:8080/\" \\\n    -ju \"admin\" \\\n    --aks_resource_group \"$resource_group\" \\\n    --aks_name \"$aks_name\" \\\n    --sp_subscription_id \"$subscription_id\" \\\n    --sp_client_id \"$app_id\" \\\n    --sp_client_password \"$app_key\" \\\n    --sp_tenant_id \"$tenant_id\" \\\n    --artifacts_location \"$artifacts_location\" \\\n    --sas_token \"$artifacts_location_sas_token\"\n\nrm -f \"$temp_key_path\"\nrm -f \"$temp_pub_key\"\n", "num_lines": 160}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0 \n\nArguments\n  --account_name|-an       [Required]: Spinnaker account name for registry\n  --registry|-rg           [Required]: Registry url targeted by pipeline\n  --repository|-rp         [Required]: Repository targeted by pipeline\n  --port|-p                          : Port for loadbalancers used in pipeline, defaulted to '8000'\n  --user_name|-un                    : User name for pipeline metadata, defaulted to '[anonymous]'\n  --user_email|-ue                   : User email for pipeline metadata, defaulted to 'anonymous@Fabrikam.com'\n  --artifacts_location|-al           : Url used to reference other scripts/artifacts.\n  --sas_token|-st                    : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\n# Set defaults\nport=\"8000\"\nuser_name=\"[anonymous]\"\nuser_email=\"anonymous@Fabrikam.com\"\nartifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/master/\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --account_name|-an)\n      account_name=\"$1\"\n      shift\n      ;;\n    --registry|-rg)\n      registry=\"$1\"\n      # Remove http prefix and trailing slash from registry if they exist\n      registry=${registry#\"https://\"}\n      registry=${registry#\"http://\"}\n      registry=${registry%\"/\"}\n      shift\n      ;;\n    --repository|-rp)\n      repository=\"$1\"\n      shift\n      ;;\n    --port|-p)\n      port=\"$1\"\n      shift\n      ;;\n    --user_name|-un)\n      user_name=\"$1\"\n      shift\n      ;;\n    --user_email|-ue)\n      user_email=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --account_name $account_name\nthrow_if_empty --registry $registry\nthrow_if_empty --repository $repository\nthrow_if_empty --port $port\nthrow_if_empty --user_name $user_name\nthrow_if_empty --user_email $user_email\n\n# Validate and parse repository\nif [[ \"$repository\" =~ ^([^[:space:]\\/]+)\\/([^[:space:]\\/]+)$ ]]; then\n    organization=\"${BASH_REMATCH[1]}\"\n    app_name=\"${BASH_REMATCH[2]}\"\n    app_name=$(echo \"${app_name,,}\" | tr -cd '[[:alnum:]]') # Convert to lowercase and remove symbols from application name. Kubernetes only supports ^[a-z0-9]+$\nelse\n    echo \"Expected repository to be of the form 'organization/applicationname', but instead received '$repository'.\" 1>&2\n    exit 1\nfi\n\n# Connect to k8s cluster in the background\nhal deploy connect --service-names gate &\ntimeout=30\necho \"while !(nc -z localhost 8084); do sleep 1; done\" | timeout $timeout bash\nreturn_value=$?\nif [ $return_value -ne 0 ]; then\n  >&2 echo \"Failed to connect to Spinnaker within '$timeout' seconds.\"\n  exit $return_value\nfi\n\n# Create application\napplication_data=$(curl -s ${artifacts_location}spinnaker/add_k8s_pipeline/application.json${artifacts_location_sas_token})\napplication_data=${application_data//REPLACE_APP_NAME/$app_name}\napplication_data=${application_data//REPLACE_USER_NAME/$user_name}\napplication_data=${application_data//REPLACE_USER_EMAIL/$user_email}\ncurl -X POST -H \"Content-type: application/json\" --data \"$application_data\" http://localhost:8084/applications/${app_name}/tasks\n\n# Create pipeline\npipeline_data=$(curl -s ${artifacts_location}spinnaker/add_k8s_pipeline/pipeline.json${artifacts_location_sas_token})\npipeline_data=${pipeline_data//REPLACE_APP_NAME/$app_name}\npipeline_data=${pipeline_data//REPLACE_ACCOUNT_NAME/$account_name}\npipeline_data=${pipeline_data//REPLACE_REGISTRY/$registry}\npipeline_data=${pipeline_data//REPLACE_REPOSITORY/$repository}\npipeline_data=${pipeline_data//REPLACE_ORGANIZATION/$organization}\npipeline_data=${pipeline_data//REPLACE_PORT/$port}\ncurl -X POST -H \"Content-type: application/json\" --data \"$pipeline_data\" http://localhost:8084/pipelines\n\n# Create dev load balancer\nload_balancer_data=$(curl -s ${artifacts_location}spinnaker/add_k8s_pipeline/load_balancer.json${artifacts_location_sas_token})\ndev_load_balancer_data=${load_balancer_data//REPLACE_APP_NAME/$app_name}\ndev_load_balancer_data=${dev_load_balancer_data//REPLACE_USER_NAME/$user_name}\ndev_load_balancer_data=${dev_load_balancer_data//REPLACE_PORT/$port}\ndev_load_balancer_data=${dev_load_balancer_data//REPLACE_STACK/\"dev\"}\ndev_load_balancer_data=${dev_load_balancer_data//REPLACE_SERVICE_TYPE/\"ClusterIP\"}\ncurl -X POST -H \"Content-type: application/json\" --data \"$dev_load_balancer_data\" http://localhost:8084/applications/${app_name}/tasks\n\n# Create prod load balancer\nprod_load_balancer_data=${load_balancer_data//REPLACE_APP_NAME/$app_name}\nprod_load_balancer_data=${prod_load_balancer_data//REPLACE_USER_NAME/$user_name}\nprod_load_balancer_data=${prod_load_balancer_data//REPLACE_PORT/$port}\nprod_load_balancer_data=${prod_load_balancer_data//REPLACE_STACK/\"prod\"}\nprod_load_balancer_data=${prod_load_balancer_data//REPLACE_SERVICE_TYPE/\"LoadBalancer\"}\ncurl -X POST -H \"Content-type: application/json\" --data \"$prod_load_balancer_data\" http://localhost:8084/applications/${app_name}/tasks\n\n# Stop background connection to Spinnaker\npkill kubectl", "num_lines": 149}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\n\nArguments\n  --user_name|-un          [Required]: User name for Kubernetes cluster\n  --resource_group|-rg     [Required]: Resource group containing Kubernetes cluster\n  --master_fqdn|-mf        [Required]: Master FQDN of Kubernetes master VMs\n\nNOTE: This script requires the 'az' cli and assumes you have logged in and set the correct subscription\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --user_name|-un)\n      admin_user_name=\"$1\"\n      shift\n      ;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --master_fqdn|-mf)\n      master_fqdn=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --user-name $admin_user_name\nthrow_if_empty --resource_group $resource_group\nthrow_if_empty --master_fqdn $master_fqdn\n\nconfig_path=\"/home/$admin_user_name/.kube/config\"\n\n# Setup temporary credentials to access kubernetes master vms\ntemp_user_name=$(uuidgen | sed 's/-//g')\ntemp_key_path=$(mktemp -d)/temp_key\nssh-keygen -t rsa -N \"\" -f $temp_key_path -V \"+1d\"\ntemp_pub_key=$(cat ${temp_key_path}.pub)\n\nmaster_vm_ids=$(az vm list -g \"$resource_group\" --query \"[].id\" -o tsv | grep \"k8s-master-\")\n>&2 echo \"Master VM ids: $master_vm_ids\"\n\n# Enable temporary credentials on every kubernetes master vm (since we don't know which vm will be used when we scp)\naz vm user update -u \"$temp_user_name\" --ssh-key-value \"$temp_pub_key\" --ids \"$master_vm_ids\"\n\n# Copy kube config over from master kubernetes cluster and mark readable\nsudo mkdir -p $(dirname \"$config_path\")\nsudo sh -c \"ssh -o StrictHostKeyChecking=no -i \\\"$temp_key_path\\\" $temp_user_name@$master_fqdn sudo cat \\\"$config_path\\\" > \\\"$config_path\\\"\"\n\n# Remove temporary credentials on every kubernetes master vm\naz vm user delete -u \"$temp_user_name\" --ids \"$master_vm_ids\"\n\n# Delete temp key on spinnaker vm\nrm $temp_key_path\nrm ${temp_key_path}.pub\n\nif [ ! -s \"$config_path\" ]; then\n  >&2 echo \"Failed to copy kubeconfig for kubernetes cluster.\"\n  exit -1\nfi\n\nsudo chmod +r \"$config_path\"", "num_lines": 88}
{"repo_name": "azure-devops-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --storage_account_name|-san [Required] : Storage Account name used for Spinnaker's persistent storage\n  --storage_account_key|-sak  [Required] : Storage Account key used for Spinnaker's persistent storage\n  --username|-u               [Required] : User for which to install Halyard\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --storage_account_name|-san)\n      storage_account_name=\"$1\";;\n    --storage_account_key|-sak)\n      storage_account_key=\"$1\";;\n    --username|-u)\n      username=\"$1\";;\n    --help|-help|-h)\n      print_usage\n      exit 13;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\n  shift\ndone\n\nthrow_if_empty storage_account_name $storage_account_name\nthrow_if_empty storage_account_key $storage_account_key\nthrow_if_empty username $username\n\n# Install Halyard\ncurl --silent \"https://raw.githubusercontent.com/spinnaker/halyard/master/install/debian/InstallHalyard.sh\" | sudo bash -s -- --user \"$username\" -y\n\n# Get the latest version of spinnaker\nversion=`hal version list | grep -P '\\d+\\.\\d+\\.\\d+' -o | tail -1`\n\n# Set Halyard to use the latest released/validated version of Spinnaker\nhal config version edit --version $version\n\n# Configure Spinnaker persistent store\nhal config storage azs edit --storage-account-name \"$storage_account_name\" --storage-account-key \"$storage_account_key\"\nhal config storage edit --type azs", "num_lines": 60}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script to install packages on Azure DevTest lab Linux VMs via the apt-get package management system.\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux-apt-package.sh --update (true|false) --packages (PACKAGE-LIST) (GLOBAL|LOCAL-PATH) [ADDITIONAL-OPTIONS]\n#\n\n# Default argument values\nDEFAULT_UPDATE_MODE=0\nARGMODE_UPDATE=update\nARGMODE_PACKAGE=packages\nARGMODE_OPTIONS=options\nARGMODE_NONE=none\nREQUIRED_INSTALL_OPTIONS=\"--assume-yes --quiet\"\nREQUIRED_UPDATE_OPTIONS=\"--assume-yes --quiet\"\nUSAGE_STRING=\"Usage:\nlinux-apt-package.sh --update (true|false) --packages (package-list) --options (additional-options)\n\nupdate\n    Only specify true or false here. Default is false.\n\npackages\n    Specify packages to install separated by spaces. Follows the conventions of apt-get (see man apt-get for details).\n\noptions\n    Specify any additional options you want to send to apt-get. These get injected prior to the install command.\n    \nNOTE: The additional options --quiet and --assume-yes are always used for both update and install commands executed as a result of this script.\nNOTE: No additional options are sent into the update command, if that option is specified.\n\n\"\n \nLOGCMD='logger -i -t AZDEVTST_APTPKG --'\nwhich logger\nif [ $? -ne 0 ] ; then\n    LOGCMD='echo [AZDEVTST_APTPKG] '\nfi\n\n$LOGCMD \"Installing apt packages. Command line given:\"\n# Cannot use logger here, as the -- are interpreted by that command\n$LOGCMD \"   $@\"\n\n# Check for minimum number of parameters first - must be at minimum 3\nif [ $# -lt 3 ] ; then\n  $LOGCMD \"ERROR: This script needs at least 3 command-line arguments, update=, packages=[somepackagename], and options=.\"\n  $LOGCMD \"$USAGE_STRING\"\n  exit 1\nfi  \n\nARGMODE=$ARGMODE_NONE\n\nwhile :\ndo\n    $LOGCMD \"Argument mode: $ARGMODE.\"\n    \n    case \"$1\" in\n        \"--$ARGMODE_UPDATE\")\n            ARGMODE=$ARGMODE_UPDATE\n            DO_GLOBAL_UPDATE=$DEFAULT_UPDATE_MODE\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Setting the update mode to default ($DO_GLOBAL_UPDATE), checking for further arguments to set update mode.\"\n            ;;\n        \"--$ARGMODE_PACKAGE\")\n            ARGMODE=$ARGMODE_PACKAGE\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Requirement to get packages begins.\"\n            ;;\n        \"--$ARGMODE_OPTIONS\")\n            ARGMODE=$ARGMODE_OPTIONS\n            shift\n            ;;\n\t\"\")\n\t    $LOGCMD \"Finished parsing through all command line arguments.\"\n\t    break\n\t    ;;\n        *)\n            case \"$ARGMODE\" in\n                $ARGMODE_NONE)\n                    $LOGCMD \"WARNING: Parsing arguments while still in 'none' argument mode. Not supported, but we'll play along... Arg recieved is '$1'\"\n                    shift\n                    ;;\n                $ARGMODE_UPDATE)\n                    $LOGCMD \"Current update-before-install mode is $DO_GLOBAL_UPDATE. Argument recieved is '$1'.\"\n                    if [ \"$1\" = \"true\" ] || [ \"$1\" = \"yes\" ] ; then\n                        DO_GLOBAL_UPDATE=1\n                    else\n                        DO_GLOBAL_UPDATE=0\n                    fi\n                    $LOGCMD \"Set update before install mode to $DO_GLOBAL_UPDATE.\"\n                    shift\n                    ;;\n                $ARGMODE_PACKAGE)\n                    $LOGCMD \"Current packages set to install are '$INSTALL_PACKAGES', adding argument received '$1'\"\n                    INSTALL_PACKAGES=\"$INSTALL_PACKAGES $1\"\n                    $LOGCMD \"...packages to install is now '$INSTALL_PACKAGES'\"\n                    shift\n                    ;;\n                $ARGMODE_OPTIONS)\n                    $LOGCMD \"Current additional options set are $ADDITIONAL_OPTIONS, adding argument received '$1'\"\n                    $ADDITIONAL_OPTIONS = \"$ADDITIONAL_OPTIONS $1\"\n                    $LOGCMD \"...additional options is now '$ADDITIONAL_OPTIONS'\"\n                    shift\n                    ;;\n                *)\n                    $LOGCMD \"ERROR: Got into argument mode '$ARGMODE' somehow, not supported! Argument received is '$1'\"\n                    $LOGCMD \"$USAGE_STRING\"\n                    exit 1\n                    ;;\n            esac\n            ;;\n    esac\ndone\n\nset -e\n\nif [ $DO_GLOBAL_UPDATE -eq 1 ] ; then\n    $LOGCMD \"Updating the system using apt-get update. Command line being used is: 'apt-get $REQUIRED_UPDATE_OPTIONS update'.\"\n    apt-get $REQUIRED_UPDATE_OPTIONS update\n    $LOGCMD \"Update COMPLETED.\"\nelse\n    $LOGCMD \"Skipping apt-get update prior to package install.\"\nfi\n\n$LOGCMD \"Installing packages using apt-get, using command line:\"\n$LOGCMD \"  apt-get $ADDITIONAL_OPTIONS $REQUIRED_INSTALL_OPTIONS install $INSTALL_PACKAGES\"\napt-get $ADDITIONAL_OPTIONS $REQUIRED_INSTALL_OPTIONS install $INSTALL_PACKAGES\n\nset +e\n\n$LOGCMD \"Done installing packages\"\n\n", "num_lines": 134}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n###\n# Arguments:\n#\n# $1    Container name\n# $2    Destination\n# $3    Connection string\n# $4    Deployment script\n#\n###\n\nisApt=`command -v apt-get`\nisYum=`command -v yum`\n\nif [ -n \"$isApt\" ] ; then\n    echo \"Using APT package manager\"\n\n    apt-get -y update\n    \n    curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash -\n    apt-get -y install nodejs\n    apt-get -y install npm\n    \n    nde=\"nodejs\"\n    \nelif [ -n \"$isYum\" ] ; then\n    echo \"Using YUM package manager\"\n\n    yum -y update\n    yum clean all\n    \n    yum install -y epel-release\n    yum install -y nodejs npm\n    \n    nde=\"node\"\nfi\n\nnpm install azure-storage\nnpm install mkdirp\n\nset -e\n\n# clean deployment folder prior to download\nrm -d -f -r $2\n\n# download the container into the destination folder\neval \"$nde ./download_azure_container.js '$1' '$2' '$3'\"\n\n# run the install script if one is provided\nif [ -n \"$4\" ]; then\n\techo \"invoking $2/$4\"\n\tsh \"$2/$4\"\nfi", "num_lines": 54}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nmain () {\n    { # try\n\n        # The script runs as root, try to install at command and return 1 if system not supported\n        isApt=`command -v apt-get`\n        isYum=`command -v yum`\n        isZypper=`command -v zypper`\n        if [ -n \"$isApt\" ] ; then\n            apt-get -y update > /dev/null\n            apt-get -y install at > /dev/null\n        elif [ -n \"$isYum\" ] ; then\n            yum install -y at > /dev/null\n        elif [ -n \"$isZypper\" ] ; then\n            zypper install -y at > /dev/null\n        else\n            echo 'OS type not supported' #> /dev/null 2>&1\n            exit 1\n        fi\n\n        # Make sure that the atd service is running to cover our dependency below.\n        isSystemctl=`command -v systemctl`\n        if [ -n \"$isSystemctl\" ] ; then\n            systemctl enable atd.service && systemctl start atd.service > /dev/null\n        else\n            insserv atd && /etc/init.d/atd start > /dev/null\n        fi\n\n        # chdir to waagent's directory before running it\n        waagentPath=$(command -v waagent)\n        # trim the last 8 characters\n        waagentDir=${waagentPath%????????}\n        echo \"cd $waagentDir && waagent -force -deprovision+user > /tmp/depro.out 2> /tmp/depro.err && poweroff\" | at now + 1 minute > /dev/null 2>&1        \n        exit 0\n    } || { # catch\n        exit 1\n    }\n}\n\nmain \"$@\"\n", "num_lines": 42}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Check if docker is already installed.\ndocker -v\ninstallationStatus=$(echo $?)\n\nif [ $installationStatus -eq 127 ] ; then\n    wget -qO- https://get.docker.com/ | sh\nfi\n", "num_lines": 10}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n###\n# Arguments:\n#\n# $1    Container name\n# $2    Docker run options\n# $3    Image name\n# $4    Additional image arguments\n#\n###\n\n# Check if docker is already installed.\ndocker -v\ninstallationStatus=$(echo $?)\n\nif [ $installationStatus -eq 127 ] ; then\n    wget -qO- https://get.docker.com/ | sh\nfi\n\nif [ -z \"$1\" ] ; then\n    NAME_ARG=\nelse\n    NAME_ARG=\" --name $1\"\nfi\n\n# Docker run syntax: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]\n#                               |__1-2__| |_3_| |_______ 4_______|\n\ncmd=\"docker run $NAME_ARG $2 -d $3 $4\"\n\necho \"Running command: $cmd\"\neval $cmd\n", "num_lines": 34}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Starting MongoDb installation.\"\n\nisApt=`command -v apt-get`\nisYum=`command -v yum`\n\n# Some of the previous commands will fail with an exit code other than zero (intentionally), \n# so we do not set error handling to stop (set e) until after they've run.\nset -e\n\nif [ -n \"$isApt\" ] ; then\n    echo \"Using APT package manager.\"\n    \n    echo \"Updating every installed package.\"\n    apt-get -y update\n\n    echo \"Installing MongoDb.\"\n    apt-get -y install mongodb\nelif [ -n \"$isYum\" ] ; then\n    echo \"Using YUM package manager.\"\n\n    echo \"Preparing MongoDb installation configuration.\"\n    releasever=7\n    cat >/etc/yum.repos.d/mongodb.repo <<-EOF\n[MongoDB]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n    echo \"Installing MongoDb.\"\n    yum install -y mongodb-org\nfi\n\necho \"The artifact was applied successfully.\"", "num_lines": 37}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Installing NodeJs\"\n\nisApt=`command -v apt-get`\nisYum=`command -v yum`\n\n# Some of the previous commands will fail with an exit code other than zero (intentionally), \n# so we do not set error handling to stop (set e) until after they've run\nset -e\n\nif [ -n \"$isApt\" ] ; then\n    echo \"Using APT package manager\"\n\n    apt-get -y update\n    \n    curl --silent --location https://deb.nodesource.com/setup_4.x | bash -\n    apt-get -y install nodejs\n    exit 0\n\nelif [ -n \"$isYum\" ] ; then\n    echo \"Using YUM package manager\"\n\n    yum -y update\n    yum clean all\n    \n    yum install -y epel-release\n    yum install -y nodejs npm\n    exit 0\nfi\n\nexit 1\n", "num_lines": 33}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script to install NVM on Linux package on Azure DevTest lab Linux VMs.\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux_install_nvm_v1.sh TARGET-USER\n#\n\n#!/bin/bash\n\n#Get the input parameter value.\nTARGET_USER=$1\n\n# Check if nvm is already installed.\necho \"Checking if NVM is already installed.\"\necho \"For user $TARGET_USER\"\nrunuser -l $TARGET_USER -c 'nvm -v'\ninstallationStatus=$(echo $?)\n\nif [ $installationStatus -eq 127 ] ; then\n    echo \"Installing NVM...\"\n    runuser -l $TARGET_USER -c 'wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash'\n    echo \"Installed NVM for user $TARGET_USER.\"\nelse\n    echo \"NVM is already installed.\"\nfi\n\necho \"Done.\"", "num_lines": 29}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# script to install Java on Ubuntu (APT) systems or YUM-based systems.\n# \n# Update the package system prior to installing Java to ensure we can get what we need.\n#\n# Version 0.1\n# Author Darren Rich <darrich@microsoft.com>\n# Original version found on VSTS: https://almrangers.visualstudio.com/\n\necho \"Installing Java\"\n\nisApt=`command -v apt-get`\nisYum=`command -v yum`\n\n# Some of the previous commands will fail with an exit code other than zero (intentionally), \n# so we do not set error handling to stop (set e) until after they've run\nset -e\n\nif [ -n \"$isApt\" ] ; then\n    echo \"Using APT package manager\"\n\n    sudo apt-get -y install default-jdk\n    exit 0\nelif [ -n \"$isYum\" ] ; then\n    echo \"Using YUM package manager\"\n\n    yum install -y java-1.8.0-openjdk\n    exit 0\nfi\n\nexit 1\n", "num_lines": 33}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\necho \"Installing Mono runtime\"\n\nisApt=`command -v apt-get`\nisRpm=`command -v rpm`\n\n# Some of the previous commands will fail with an exit code other than zero (intentionally), \n# so we do not set error handling to stop (set e) until after they've run\nset -e\nset -o xtrace\n\nif [ -r /etc/os-release ]; then\n    . /etc/os-release\nelse\n    echo \"Distro without /etc/os-release available\"\n    exit 1\nfi\n\n\nif [ -n \"$isApt\" ]; then\n    # Ubuntu, Debian\n    if [ $ID = \"ubuntu\" ]; then\n        MONO_REPO=\"stable-${UBUNTU_CODENAME}\"\n        \n        if [ $VERSION_ID = \"18.04\" ]; then\n            REQ_PACKAGES=\"gnupg ca-certificates\"\n        else\n            REQ_PACKAGES=\"apt-transport-https\"\n        fi\n    elif [ $ID = \"debian\" ]; then\n        DEB_CODENAME=`echo $VERSION | awk -F\"[()]\"+ '{print $2}'`\n        MONO_REPO=\"stable-${DEB_CODENAME}\"\n\n        if [ $VERSION_ID = \"9\" ]; then\n            REQ_PACKAGES=\"apt-transport-https dirmngr gnupg ca-certificates\"    \n        else\n            REQ_PACKAGES=\"apt-transport-https ca-certificates\"\n        fi\n    else\n        echo \"Not running debian-based distribution. ID=${ID}, VERSION=${VERSION}\"\n        exit 1\n    fi\n\n    sudo apt-get update\n    sudo apt-get install -y $REQ_PACKAGES\n    sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF\n    echo \"deb https://download.mono-project.com/repo/${ID} ${MONO_REPO} main\" | sudo tee /etc/apt/sources.list.d/mono-official-stable.list\n    sudo apt-get update\n    sudo apt-get install -y mono-devel\nelif [ -n \"$isRpm\" ]; then\n    # Fedora, CentOS\n    sudo rpm --import \"https://keyserver.ubuntu.com/pks/lookup?op=get&search=0x3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF\"\n\n    INSTALL_CMD='curl https://download.mono-project.com/repo/centos7-stable.repo | tee /etc/yum.repos.d/mono-centos7-stable.repo'\n\n    if [ $ID = \"centos\" ] && [ $VERSION_ID = \"6\" ]; then\n        INSTALL_CMD='curl https://download.mono-project.com/repo/centos6-stable.repo | tee /etc/yum.repos.d/mono-centos6-stable.repo'\n    fi\n\n    sudo su -c \"$INSTALL_CMD\"\n\n    if [ $ID = \"fedora\" ]; then\n        sudo dnf update\n        dnf install -y mono-devel\n    elif [ $ID = \"centos\" ]; then\n        sudo yum install -y mono-devel\n    else\n        echo \"RPM-based distribution not supported. ID=${ID}, VERSION=${VERSION}\"\n        exit 1\n    fi\nfi\n\necho \"Installed Mono runtime\"\n", "num_lines": 75}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to install NPM packages on Azure DevTest lab VMs.\n#\n# For each package requested to install, runs the currently installed\n# npm to actually perform the install. Every package requested is either\n# installed to the global system or to a specific local path on the VM.\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux-npm-package.sh -packages (PACKAGE-LIST) --install-to (true|false) --options [ADDITIONAL-OPTIONS]\n#\n\n# Constants:\nDEFAULT_INSTALL_GLOBAL=1\nGLOBAL_SWITCH=\"\"\nINSTALL_TO=\"/var/tmp\"\nARGMODE_INSTALLTO=install-to\nARGMODE_PACKAGE=packages\nARGMODE_OPTIONS=options\nARGMODE_NONE=none\nREQUIRED_INSTALL_OPTIONS=\"\"\nUSAGE_STRING=\"Usage:\nlinux-npm-package.sh --packages (package-list) --install-global (boolean) --options (additional-options)\n\npackages\n    Specify packages to install separated by spaces.\n\ninstall-to \n    Path to install the packages to. If this isn't specified (or is given as an empty string/blank) then the packages\n    are installed globally. Also, if the keyword 'global' is specified, the packages are installed globally as well.\n    \noptions\n    Specify any additional options you want to send to npm. All of these are appended to the end of the entire npm command.\n    \nNOTE: The additional options --quiet and --assume-yes are always used for both update and install commands executed as a result of this script.\nNOTE: No additional options are sent into the update command, if that option is specified.\n\n\"\n\nLOGCMD='logger -i -t AZDEVTST_NPMPKG --'\nwhich logger\nif [ $? -ne 0 ] ; then\n    LOGCMD=echo\nfi\n\n$LOGCMD \"Installing packages. Command line given:\"\n$LOGCMD \"   $@\"\n\n# Check for minimum number of parameters first - must be at minimum 3\nif [ $# -lt 3 ] ; then\n  $LOGCMD \"ERROR: This script needs at least 3 command-line arguments, update, packages, and options.\"\n  $LOGCMD \"$USAGE_STRING\"\n  exit 1\nfi\n\nwhich npm\nif [ $? -ne 0 ] ; then\n    $LOGCMD \"ERROR: No npm found in path. Please install npm via apt, yum, or whichever package management system is available and re-run this artifact.\"\n    exit 1\nfi\n\nARGMODE=$ARGMODE_NONE\n\nwhile :\ndo\n    $LOGCMD \"Argument mode: $ARGMODE. Argument being processed is '$1'\"\n    \n    case \"$1\" in\n        \"--$ARGMODE_INSTALLTO\")\n            ARGMODE=$ARGMODE_INSTALLTO\n            INSTALL_GLOBAL=$DEFAULT_INSTALL_GLOBAL\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Setting the $ARGMODE_INSTALLTO mode to default ($INSTALL_GLOBAL), checking for further arguments to set $ARGMODE_INSTALLTO mode.\"\n            ;;\n        \"--$ARGMODE_PACKAGE\")\n            ARGMODE=$ARGMODE_PACKAGE\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Requirement to get packages begins.\"\n            ;;\n        \"--$ARGMODE_OPTIONS\")\n            ARGMODE=$ARGMODE_OPTIONS\n            shift\n            ;;\n        \"\")\n\t        $LOGCMD \"Finished parsing through all command line arguments.\"\n\t        break\n\t        ;;\n        *)\n            case \"$ARGMODE\" in\n                $ARGMODE_NONE)\n                    $LOGCMD \"WARNING: Parsing arguments while still in 'none' argument mode. Not supported, but we'll play along... Arg recieved is '$1'\"\n                    shift\n                    ;;\n                $ARGMODE_INSTALLTO)\n                    $LOGCMD \"Current $ARGMODE mode is $INSTALL_GLOBAL. Argument recieved is '$1'.\"\n                    if [ \"$1\" = \"global\" ] ; then\n                        INSTALL_GLOBAL=1\n                    else\n                        INSTALL_GLOBAL=0\n                        INSTALL_TO=\"$1\"\n                        $LOGCMD \"Setting install location to specified path '$INSTALL_TO'\"\n                    fi\n                    $LOGCMD \"Set update before install mode to $INSTALL_GLOBAL.\"\n                    shift\n                    ;;\n                $ARGMODE_PACKAGE)\n                    $LOGCMD \"Current packages set to install are '$INSTALL_PACKAGES', adding argument received '$1'\"\n                    INSTALL_PACKAGES=\"$INSTALL_PACKAGES $1\"\n                    $LOGCMD \"...packages to install is now '$INSTALL_PACKAGES'\"\n                    shift\n                    ;;\n                $ARGMODE_OPTIONS)\n                    $LOGCMD \"Current additional options set are $ADDITIONAL_OPTIONS, adding argument received '$1'\"\n                    ADDITIONAL_OPTIONS=\"$ADDITIONAL_OPTIONS $1\"\n                    $LOGCMD \"...additional options is now '$ADDITIONAL_OPTIONS'\"\n                    shift\n                    ;;\n                *)\n                    $LOGCMD \"ERROR: Got into argument mode '$ARGMODE' somehow, not supported! Argument received is '$1'\"\n                    $LOGCMD \"$USAGE_STRING\"\n                    exit 1\n                    ;;\n            esac\n            ;;\n    esac\ndone\n$LOGCMD \"Got Arguments: Install Globally='$INSTALL_GLOBAL' InstallLoc='$INSTALL_TO' Install Packages='$INSTALL_PACKAGES' Options='$ADDITIONAL_OPTIONS'\"\n\n# Determine if the package install is for global or local. If local, ensure\n# the local path is available\nif [ $INSTALL_GLOBAL -ne 1 ] ; then\n\n    $LOGCMD \"Testing if the local installation path '$INSTALL_TO' exists...\"\n    \n    if [ ! -d \"$INSTALL_TO\" ] ; then\n        $LOGCMD \"...it does not, creating it:\"\n        \n        mkdir -p \"$INSTALL_TO\"\n        if [ $? -ne 0 ] ; then\n            \n            $LOGCMD \"Could not make folder '$INSTALL_TO'. Failing process.\"\n            \n        fi\n    else\n    \n        $LOGCMD \"...it does exist.\"\n    \n    fi\n    \n    cd \"$INSTALL_TO\"\n\nelse\n\n    GLOBAL_SWITCH=\"--global\"\n    \nfi\n\n# For each package named in the parameter list, install the package and log the \n# install command line for potential diagnosing later\narr=$(echo $PACKAGE_LIST | tr \",\" \"\\n\")\n\nset -e\n\n$LOGCMD \"Installing packages '$INSTALL_PACKAGES', using command line:\"\n$LOGCMD \"npm install $GLOBAL_SWITCH \\\"$INSTALL_PACKAGES\\\" $ADDITIONAL_OPTIONS\"\n    \nnpm install $GLOBAL_SWITCH $INSTALL_PACKAGES $ADDITIONAL_OPTIONS\n    \nset +e\n\n$LOGCMD \"Done installing npm packages '$INSTALL_PACKAGES'.\"\n", "num_lines": 175}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Script to install PowerShell on Linux package on Azure DevTest lab Linux VMs.\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux-powershell.sh PACKAGE-URL\n#\n\n#!/bin/bash\n\nisApt=`command -v apt-get`\nisYum=`command -v yum`\n\nset -e\ncd /tmp\nURL=$1\nFILE_NAME=\"${URL##*/}\"\necho \"Downloading $FILE_NAME\"\nwget $URL\n\nif [ -n \"$isYum\" ] ; then\n    echo \"Using yum package manager\"\n    yum install -y $FILE_NAME\nelif [ -n \"$isApt\" ] ; then\n    echo \"Using apt package manager\"\n    if [ $(lsb_release -r -s) = \"16.04\" ]; then\n        apt-get -q -y install libunwind8 libicu55\n        dpkg -i $FILE_NAME\n    elif [ $(lsb_release -r -s) = \"14.04\" ]; then\n        apt-get -q -y install libunwind8 libicu52\n        dpkg -i $FILE_NAME\n    fi\nfi\n", "num_lines": 35}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to secure MariaDB installation on Linux.\n# Based on mysql_secure_installation.sh found here https://github.com/twitter/mysql/blob/master/scripts/mysql_secure_installation.sh\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux-secure-mariadb.sh [-p password]\n#\n\n# Get parameter value for password\nusage() { echo \"Usage: $0 [-p password]\" 1>&2; exit 1; }\n\nwhile getopts \":p:\" option; do\n    case \"${option}\" in\n        p)\n            p=${OPTARG}\n            ;;\n        *)\n            usage\n            ;;\n    esac\ndone\nshift $((OPTIND-1))\n\nif [ -z \"${p}\" ]; then\n    usage\nfi\n\n\nset -e\n\n# Check if mariadb is running\nrunning=$(pgrep mysql | wc -l)\nif [ \"$running\" -eq 0 ];\nthen\n        echo \"MariaDB not running. Aborting\"\n        exit 1\nelse\n        echo \"Found running MariaDB instance\"\nfi\n\n# Check if mysql is available\necho \"Checking if mysql command is available\"\ncommand -v mysql >/dev/null 2>&1 || { echo >&2 \"mysql command is required but not installed. Aborting\"; exit 1; }\n\n# Set root password and make sure that nobody can access the server without a password\necho \"Updating root password\"\nmysql -e \"UPDATE mysql.user SET Password=PASSWORD('$ROOT_PASSWORD') WHERE User='root';\"\n\n# Remove anonymous users\necho \"Removing anonymous users\"\nmysql -e \"DELETE FROM mysql.user WHERE User='';\"\n\n# Disallow root login remotely\necho \"Disallowing root login remotely\"\nmysql -e \"DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');\"\n\n# Remove test database and access to it. Use IF EXISTS since sometimes\n# test database is not present (e.g. Debian based systems) \necho \"Removing test database and access to it\"\nmysql -e \"DROP DATABASE IF EXISTS test;\"\nmysql -e \"DELETE FROM mysql.db WHERE Db='test' OR Db='test\\\\_%';\"\n\n# Reload privilege tables\necho \"Reloading privilege tables\"\nmysql -e \"FLUSH PRIVILEGES;\"\n\necho \"Done securing MariaDB installation\"\n\nset +e\n", "num_lines": 74}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to install packages on Azure DevTest lab Linux VMs via the yum package management system.\n#\n# NOTE: Intended for use by the Azure DevTest Lab artifact system.\n#\n# Usage: \n#\n# linux-yum-package.sh --update (true|false) --packages (PACKAGE-LIST) --options [ADDITIONAL-OPTIONS]\n#\n\n# Default argument values\nDO_GLOBAL_UPDATE=0\nARGMODE_UPDATE=update\nARGMODE_PACKAGE=packages\nARGMODE_OPTIONS=options\nARGMODE_NONE=none\nREQUIRED_INSTALL_OPTIONS=\"--assumeyes --quiet\"\nREQUIRED_UPDATE_OPTIONS=\"--assumeyes --quiet\"\nUSAGE_STRING=\"\nUsage:\n    linux-yum-package.sh --update (true|false) --packages (package-list) --options (additional-options)\n\nupdate\n    Only specify true or false here. Default is false.\n\npackages\n    Specify packages to install separated by spaces. Follows the conventions of yum (see man yum for details).\n\noptions\n    Specify any additional options you want to send to yum. These get injected prior to the install command.\n    \nNOTE: The additional options '$REQUIRED_INSTALL_OPTIONS' are always used for both update and install commands executed as a result of this script.\nNOTE: No additional options are sent into the update command, if that option is specified.\"\n\nerror() {\n    echo -e \"\\nERROR: $@\\n\"\n    echo 'The artifact failed to apply.'\n    exit 1\n}\n\nLOGCMD='echo -e'\nLOGERR='error'\n\n$LOGCMD \"Preparing to install packages using YUM.\"\n\nISYUM=`command -v yum`\nif [ ! -n \"$ISYUM\" ] ; then\n    $LOGERR \"Missing required package YUM.\"\nfi\n\n# Check for minimum number of parameters first - must be at minimum 3\nif [ $# -lt 3 ] ; then\n    $LOGERR \"This script needs at least 3 command-line arguments, update=, packages=[somepackagename], and options=.\\n$USAGE_STRING\"\nfi  \n\nARGMODE=$ARGMODE_NONE\n\nwhile :\ndo\n    $LOGCMD \"Argument mode: $ARGMODE. Argument being processed is '$1'\"\n    \n    case \"$1\" in\n        \"--$ARGMODE_UPDATE\")\n            ARGMODE=$ARGMODE_UPDATE\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Setting the update mode to default ($DO_GLOBAL_UPDATE), checking for further arguments to set update mode.\"\n            ;;\n        \"--$ARGMODE_PACKAGE\")\n            ARGMODE=$ARGMODE_PACKAGE\n            shift\n            $LOGCMD \"Setting argmode to $ARGMODE. Requirement to get packages begins.\"\n            ;;\n        \"--$ARGMODE_OPTIONS\")\n            ARGMODE=$ARGMODE_OPTIONS\n            shift\n            ;;\n        \"\")\n\t        $LOGCMD \"Finished parsing through all command line arguments.\"\n\t        break\n\t        ;;\n        *)\n            case \"$ARGMODE\" in\n                $ARGMODE_NONE)\n                    $LOGCMD \"WARNING: Parsing arguments while still in 'none' argument mode. Not supported, but we'll play along... Arg recieved is '$1'\"\n                    shift\n                    ;;\n                $ARGMODE_UPDATE)\n                    $LOGCMD \"Current update-before-install mode is $DO_GLOBAL_UPDATE. Argument recieved is '$1'.\"\n                    if [ \"$1\" = \"true\" ] || [ \"$1\" = \"yes\" ] ; then\n                        DO_GLOBAL_UPDATE=1\n                    fi\n                    $LOGCMD \"Set update before install mode to $DO_GLOBAL_UPDATE.\"\n                    shift\n                    ;;\n                $ARGMODE_PACKAGE)\n                    $LOGCMD \"Current packages set to install are '$INSTALL_PACKAGES', adding argument received '$1'\"\n                    INSTALL_PACKAGES=\"$INSTALL_PACKAGES $1\"\n                    $LOGCMD \"...packages to install is now '$INSTALL_PACKAGES'\"\n                    shift\n                    ;;\n                $ARGMODE_OPTIONS)\n                    $LOGCMD \"Current additional options set are $ADDITIONAL_OPTIONS, adding argument received '$1'\"\n                    $ADDITIONAL_OPTIONS = \"$ADDITIONAL_OPTIONS $1\"\n                    $LOGCMD \"...additional options is now '$ADDITIONAL_OPTIONS'\"\n                    shift\n                    ;;\n                *)\n                    $LOGERR \"Got into argument mode '$ARGMODE' somehow, not supported! Argument received is '$1'\\n$USAGE_STRING\"\n                    ;;\n            esac\n            ;;\n    esac\ndone\n\nset -e\n\nif [ $DO_GLOBAL_UPDATE -eq 1 ] ; then\n    $LOGCMD \"Updating the system using yum update. Command line being used is: 'yum $REQUIRED_UPDATE_OPTIONS update'.\"\n    yum $REQUIRED_UPDATE_OPTIONS update\n    $LOGCMD \"Update COMPLETED.\"\nelse\n    $LOGCMD \"Skipping yum update prior to package install.\"\nfi\n\n$LOGCMD \"Installing packages using yum, using command line:\"\n$LOGCMD \"  yum $ADDITIONAL_OPTIONS $REQUIRED_INSTALL_OPTIONS install $INSTALL_PACKAGES\"\nyum $ADDITIONAL_OPTIONS $REQUIRED_INSTALL_OPTIONS install $INSTALL_PACKAGES\n\nset +e\n\n$LOGCMD \"Done installing packages\"\n\n$LOGCMD \"\\nThe artifact was applied successfully.\"\n", "num_lines": 135}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n: ${USERNAME:=testuser}\n: ${USERPASS:=Fedora#123}\n\n__create_rundir() {\n\tmkdir -p /var/run/sshd\n\tchmod 1777 /dev/shm\n}\n\n__create_user() {\n# Create a user\nuseradd $USERNAME\necho -e \"$USERPASS\\n$USERPASS\" | (passwd --stdin $USERNAME)\necho user password: $USERPASS\nusermod -a -G x2gouser $USERNAME\nusermod -a -G wheel $USERNAME\n}\n\n__create_hostkeys() {\nssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key -N '' \n}\n\n__setup_ssh() {\n\necho 'root:Fedora#2020' | chpasswd\nsed -i 's/PermitRootLogin prohibit-password/PermitRootLogin yes/' /etc/ssh/sshd_config\nsed 's@session\\s*required\\s*pam_loginuid.so@session optional pam_loginuid.so@g' -i /etc/pam.d/sshd\necho 'export NOTVISIBLE=\"in users profile\"' >> ~/.bashrc\nroot@containerID$ echo \"export VISIBLE=now\" >> /etc/profile\n\nssh-keygen -A -N ''\nrm -f /run/nologin\n}\n\n# Call all functions\n__create_rundir\n__create_hostkeys\n__setup_ssh\n__create_user\n\nexec \"$@\"", "num_lines": 42}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nerror() {\n    echo ${RED}\"Error: $@\"${RESET} >&2\n}\n\nsetup_color() {\n    # Only use colors if connected to a terminal\n    if [ -t 1 ]; then\n        RED=$(printf '\\033[31m')\n        GREEN=$(printf '\\033[32m')\n        YELLOW=$(printf '\\033[33m')\n        BLUE=$(printf '\\033[34m')\n        BOLD=$(printf '\\033[1m')\n        RESET=$(printf '\\033[m')\n    else\n        RED=\"\"\n        GREEN=\"\"\n        YELLOW=\"\"\n        BLUE=\"\"\n        BOLD=\"\"\n        RESET=\"\"\n    fi\n}\n\n\nmain() {\n\n    setup_color\n\n    echo \"${BLUE}Adding x2go PPA repo...${RESET}\"\n\n    apt-get install -y software-properties-common\n\n    add-apt-repository -y ppa:x2go/stable\n\n    echo \"${BLUE}Updating apt package repository...${RESET}\"\n\n    apt-get update\n\n    sleep 2\n\n    echo \"${BLUE}Installing MATE desktop and x2go server...${RESET}\"\n\n    apt-get install -y ubuntu-mate-desktop x2goserver x2goserver-xsession x2gomatebindings\n\n    echo \"${GREEN}MATE desktop and x2go successfully installed!${RESET}\"\n\n    # The following steps are needed to work around a conflict between MATE desktop and the Azure Linux VM agent.  Specifically, the conflict occurs when MATE installs \n    # ifupdown.  Ifupdown conflicts with netplan/cloud-init which causes the VM to fail to get its IP address during first boot.  As a result, the Azure Linux VM\n    # agent remains in a \"Not Ready\" state when a new VM is provisioned with an image with MATE desktop installed.  \n    # Here is more info about how these tools interact with one another:\n    #   - ifupdown is used by the network management daemon, systemd networkd\n    #   - netplan uses the systemd networkd daemon to provide network information to cloud-init\n    #   - cloud-init runs during a VM's initial boot process to set up the VM\n    # The workaround is to remove netplan and disable the systemd networkd daemon so that instead the Network Manager daemon and ifupdown are used for networking (Note: MATE\n    # prefers using Network Manager).  See the following bug: https://bugs.launchpad.net/ubuntu/+source/cloud-init/+bug/1832381.\n\n    currentversion=$(grep '^VERSION_ID' /etc/os-release)\n    targetversion=\"18.04\"\n\n    case \"$currentversion\" in\n        *\"$targetversion\"*)  \n            echo \"${BLUE}Configuring networking workaround for MATE and Azure Linux VM agent...${RESET}\"\n\n            apt-get remove -y netplan.io\n\n            systemctl disable systemd-networkd\n\n            cat > /etc/network/interfaces <<EOF\n                auto lo\n                iface lo inet loopback\n                source /etc/network/interfaces.d/*.cfg\nEOF\n\n            echo \"${GREEN}Networking workaround is completed!${RESET}\"  ;;\n         *)     echo \"Skipping networking work around\"\n    esac          \n}\nmain", "num_lines": 82}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nerror() {\n    echo ${RED}\"Error: $@\"${RESET} >&2\n}\n\nsetup_color() {\n    # Only use colors if connected to a terminal\n    if [ -t 1 ]; then\n        RED=$(printf '\\033[31m')\n        GREEN=$(printf '\\033[32m')\n        YELLOW=$(printf '\\033[33m')\n        BLUE=$(printf '\\033[34m')\n        BOLD=$(printf '\\033[1m')\n        RESET=$(printf '\\033[m')\n    else\n        RED=\"\"\n        GREEN=\"\"\n        YELLOW=\"\"\n        BLUE=\"\"\n        BOLD=\"\"\n        RESET=\"\"\n    fi\n}\n\n\nmain() {\n\n    setup_color\n\n    \n    echo \"${BLUE}Adding x2go PPA repo...${RESET}\"\n\n    apt-get install -y software-properties-common\n\n    add-apt-repository -y ppa:x2go/stable\n\n\n    echo \"${BLUE}Updating apt package repository...${RESET}\"\n\n    apt-get update\n\n    sleep 2\n\n    \n    echo \"${BLUE}Intalling XFCE4 desktop and x2go server...${RESET}\"\n\n    apt-get install -y xfce4 x2goserver x2goserver-xsession\n\n\n    echo \"${GREEN}XFCE4 desktop and x2go successfully installed!${RESET}\"\n}\n\nmain", "num_lines": 56}
{"repo_name": "azure-devtestlab", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\n\nerror() {\n    echo ${RED}\"Error: $@\"${RESET} >&2\n}\n\nsetup_color() {\n    # Only use colors if connected to a terminal\n    if [ -t 1 ]; then\n        RED=$(printf '\\033[31m')\n        GREEN=$(printf '\\033[32m')\n        YELLOW=$(printf '\\033[33m')\n        BLUE=$(printf '\\033[34m')\n        BOLD=$(printf '\\033[1m')\n        RESET=$(printf '\\033[m')\n    else\n        RED=\"\"\n        GREEN=\"\"\n        YELLOW=\"\"\n        BLUE=\"\"\n        BOLD=\"\"\n        RESET=\"\"\n    fi\n}\n\n\nmain() {\n\n    setup_color\n\n    \n    echo \"${BLUE}Adding x2go PPA repo...${RESET}\"\n\n    apt-get install -y software-properties-common\n\n    add-apt-repository -y ppa:x2go/stable\n\n\n    echo \"${BLUE}Updating apt package repository...${RESET}\"\n\n    apt-get update\n\n    sleep 2\n\n    \n    echo \"${BLUE}Intalling xubuntu desktop and x2go server...${RESET}\"\n\n    apt-get install -y xubuntu-desktop x2goserver x2goserver-xsession\n\n\n    echo \"${GREEN}Xubuntu desktop and x2go successfully installed!${RESET}\"\n}\n\nmain", "num_lines": 56}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Trent Swanson (Full Scale 180 Inc)\n#\n### Remaining work items\n### -Alternate discovery options (Azure Storage)\n### -Implement Idempotency and Configuration Change Support\n### -Implement OS Disk Striping Option (Currently using multiple Elasticsearch data paths)\n### -Implement Non-Durable Option (Put data on resource disk)\n### -Configure Work/Log Paths\n### -Recovery Settings (These can be changed via API)\n\nhelp()\n{\n    #TODO: Add help text here\n    echo \"This script installs Elasticsearch cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-n elasticsearch cluster name\"\n    echo \"-d static discovery endpoints 10.0.0.1-3\"\n    echo \"-v elasticsearch version 1.5.0\"\n    echo \"-l install marvel yes/no\"\n    echo \"-x configure as a dedicated master node\"\n    echo \"-y configure as client only node (no master, no data)\"\n    echo \"-z configure as data node (no master)\"\n    echo \"-h view this help content\"\n}\n\n# Log method to control/redirect log output\nlog()\n{\n    # If you want to enable this logging add a un-comment the line below and add your account id\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nlog \"Begin execution of Elasticsearch script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? == 0 ]\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hsots file if not there\n  echo \"127.0.0.1 ${HOSTNAME}\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etchosts\"\nfi\n\n#Script Parameters\nCLUSTER_NAME=\"elasticsearch\"\nES_VERSION=\"1.5.0\"\nDISCOVERY_ENDPOINTS=\"\"\nINSTALL_MARVEL=\"no\" #We use this because of ARM template limitation\nCLIENT_ONLY_NODE=0\nDATA_NODE=0\nMASTER_ONLY_NODE=0\n\n#Loop through options passed\nwhile getopts :n:d:v:l:xyzsh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    n) #set cluster name\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    d) #static discovery endpoints\n      DISCOVERY_ENDPOINTS=${OPTARG}\n      ;;\n    v) #elasticsearch version number\n      ES_VERSION=${OPTARG}\n      ;;\n    l) #install marvel\n      INSTALL_MARVEL=${OPTARG}\n      ;;\n    x) #master node\n      MASTER_ONLY_NODE=1\n      ;;\n    y) #client node\n      CLIENT_ONLY_NODE=1\n      ;;\n    z) #client node\n      DATA_NODE=1\n      ;;\n    s) #use OS striped disk volumes\n      OS_STRIPED_DISK=1\n      ;;\n    d) #place data on local resource disk\n      NON_DURABLE=1\n      ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Base path for data disk mount points\n# The script assume format /datadisks/disk1 /datadisks/disk2\nDATA_BASE=\"/datadisks\"\n\n# Expand a list of successive ip range and filter my local local ip from the list\n# Ip list is represented as a prefix and that is appended with a zero to N index\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    #Get the IP Addresses on this machine\n    declare -a MY_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}\"\n        if ! [[ \"${MY_IPS[@]}\" =~ \"${HOST}\" ]]; then\n            EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n        fi\n    done\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\n# Configure Elasticsearch Data Disk Folder and Permissions\nsetup_data_disk()\n{\n    log \"Configuring disk $1/elasticsearch/data\"\n\n    mkdir -p \"$1/elasticsearch/data\"\n    chown -R elasticsearch:elasticsearch \"$1/elasticsearch\"\n    chmod 755 \"$1/elasticsearch\"\n}\n\n# Install Oracle Java\ninstall_java()\n{\n    log \"Installing Java\"\n    add-apt-repository -y ppa:webupd8team/java\n    apt-get -y update  > /dev/null\n    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n    apt-get -y install oracle-java7-installer  > /dev/null\n}\n\n# Install Elasticsearch\ninstall_es()\n{\n    # apt-get install approach\n    # This has the added benefit that is simplifies upgrades (user)\n    # Using the debian package because it's easier to explicitly control version and less changes of nodes with different versions\n    #wget -qO - https://packages.elasticsearch.org/GPG-KEY-elasticsearch | sudo apt-key add -\n    #add-apt-repository \"deb http://packages.elasticsearch.org/elasticsearch/1.5/debian stable main\"\n    #apt-get update && apt-get install elasticsearch\n\n    # if [ -z \"$ES_VERSION\" ]; then\n    #     ES_VERSION=\"1.5.0\"\n    # fi\n\n    log \"Installing Elaticsearch Version - $ES_VERSION\"\n    sudo wget -q \"https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-$ES_VERSION.deb\" -O elasticsearch.deb\n    sudo dpkg -i elasticsearch.deb\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n#Format data disks (Find data disks then partition, format, and mount them as seperate drives)\n#------------------------\nbash vm-disk-utils-0.1.sh\n\n#Install Oracle Java\n#------------------------\ninstall_java\n\n#\n#Install Elasticsearch\n#-----------------------\ninstall_es\n\n# Prepare configuration information\n# Configure permissions on data disks for elasticsearch user:group\n#--------------------------\nDATAPATH_CONFIG=\"\"\nif [ -d \"${DATA_BASE}\" ]; then\n    for D in `find /datadisks/ -mindepth 1 -maxdepth 1 -type d`\n    do\n        #Configure disk permissions and folder for storage\n        setup_data_disk ${D}\n        # Add to list for elasticsearch configuration\n        DATAPATH_CONFIG+=\"$D/elasticsearch/data,\"\n    done\n    #Remove the extra trailing comma\n    DATAPATH_CONFIG=\"${DATAPATH_CONFIG%?}\"\nelse\n    #If we do not find folders/disks in our data disk mount directory then use the defaults\n    log \"Configured data directory does not exist for ${HOSTNAME} using defaults\"\nfi\n\n#expand_staticip_range \"$IP_RANGE\"\n\nS=$(expand_ip_range \"$DISCOVERY_ENDPOINTS\")\nHOSTS_CONFIG=\"[\\\"${S// /\\\",\\\"}\\\"]\"\n\n#Format the static discovery host endpoints for Elasticsearch configuration [\"\",\"\"] format\n#HOSTS_CONFIG=\"[\\\"${DISCOVERY_ENDPOINTS//-/\\\",\\\"}\\\"]\"\n\n#Configure Elasticsearch settings\n#---------------------------\n#Backup the current Elasticsearch configuration file\nmv /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.bak\n\n# Set cluster and machine names - just use hostname for our node.name\necho \"cluster.name: $CLUSTER_NAME\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.name: ${HOSTNAME}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure paths - if we have data disks attached then use them\nif [ -n \"$DATAPATH_CONFIG\" ]; then\n    log \"Update configuration with data path list of $DATAPATH_CONFIG\"\n    echo \"path.data: $DATAPATH_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# Configure discovery\nlog \"Update configuration with hosts configuration of $HOSTS_CONFIG\"\necho \"discovery.zen.ping.multicast.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\necho \"discovery.zen.ping.unicast.hosts: $HOSTS_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\n\n\n# Configure Elasticsearch node type\nlog \"Configure master/client/data node type flags mater-$MASTER_ONLY_NODE data-$DATA_NODE\"\n\nif [ ${MASTER_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as master only\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${DATA_NODE} -ne 0 ]; then\n    log \"Configure node as data only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${CLIENT_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as data only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelse\n    log \"Configure node for master and data\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# DNS Retry\necho \"options timeout:1 attempts:5\" >> /etc/resolvconf/resolv.conf.d/head\nresolvconf -u\n\n# Increase maximum mmap count\necho \"vm.max_map_count = 262144\" >> /etc/sysctl.conf\n\n#\"action.disable_delete_all_indices: ${DISABLE_DELETE_ALL}\" >> /etc/elasticsearch/elasticsearch.yml\n#\"action.auto_create_index: ${AUTOCREATE_INDEX}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure Environment\n#----------------------\n#/etc/default/elasticseach\n#Update HEAP Size in this configuration or in upstart service\n#Set Elasticsearch heap size to 50% of system memory\n#TODO: Move this to an init.d script so we can handle instance size increases\nES_HEAP=`free -m |grep Mem | awk '{if ($2/2 >31744)  print 31744;else print $2/2;}'`\nlog \"Configure elasticsearch heap size - $ES_HEAP\"\necho \"ES_HEAP_SIZE=${ES_HEAP}/\" >> /etc/default/elasticseach\n\n#Optionally Install Marvel\nif [ \"${INSTALL_MARVEL}\" == \"yes\" ];\n    then\n    log \"Installing Marvel Plugin\"\n    /usr/share/elasticsearch/bin/plugin -i elasticsearch/marvel/latest\nfi\n\n#Install Monit\n#TODO - Install Monit to monitor the process (Although load balancer probes can accomplish this)\n\n#and... start the service\nlog \"Starting Elasticsearch on ${HOSTNAME}\"\nupdate-rc.d elasticsearch defaults 95 10\nsudo service elasticsearch start\nlog \"complete elasticsearch setup and started\"\nexit 0\n\n#Script Extras\n\n#Configure open file and memory limits\n#Swap is disabled by default in Ubuntu Azure VMs\n#echo \"bootstrap.mlockall: true\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Verify this is necessary on azure\n#echo \"elasticsearch    -    nofile    65536\" >> /etc/security/limits.conf\n#echo \"elasticsearch     -    memlock   unlimited\" >> /etc/security/limits.conf\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/su\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session-noninteractive\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/sudo\n\n#--------------- TEMP (We will use this for the update path yet) ---------------\n#Updating the properties in the existing configuraiton has been a bit sensitve and requires more testing\n#sed -i -e \"/cluster\\.name/s/^#//g;s/^\\(cluster\\.name\\s*:\\s*\\).*\\$/\\1${CLUSTER_NAME}/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/bootstrap\\.mlockall/s/^#//g;s/^\\(bootstrap\\.mlockall\\s*:\\s*\\).*\\$/\\1true/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/path\\.data/s/^#//g;s/^\\(path\\.data\\s*:\\s*\\).*\\$/\\1${DATAPATH_CONFIG}/\" /etc/elasticsearch/elasticsearch.yml\n\n# Minimum master nodes nodes/2+1 (These can be configured via API as well - (_cluster/settings))\n# discovery.zen.minimum_master_nodes: 2\n# gateway.expected_nodes: 10\n# gateway.recover_after_time: 5m\n#----------------------\n\n", "num_lines": 345}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nlog()\n{\n\techo $1\n\tlogger \"elk-simple-on-ubuntu:\" $1\n}\n\n#Loop through options passed\nwhile getopts :n:v:d:e:sh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n\tn)\n\t  ES_CLUSTER_NAME=${OPTARG}\n\t  ;;\n\tv)\n\t  ES_VERSION=${OPTARG}\n\t  ;;\n\td)\n\t  ES_DISCOVERY_HOSTS=${OPTARG}\n\t  ;;\n\te)\n\t  ENCODED_LOGSTASH_CONFIG=${OPTARG}\n\t  ;;\n\ts)  #skip common install steps\n\t  SKIP_COMMON_INSTALL=\"YES\"\n\t  ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n#ELK (Simple) Install Script\nmkdir /opt/elk-simple/\ncd /opt/elk-simple/\nwget https://raw.githubusercontent.com/Azure/azure-diagnostics-tools/master/ELK-Semantic-Logging/ELK/AzureRM/elk-simple-on-ubuntu/elasticsearch-ubuntu-install.sh\nwget https://raw.githubusercontent.com/Azure/azure-diagnostics-tools/master/ELK-Semantic-Logging/ELK/AzureRM/logstash-on-ubuntu/logstash-install-ubuntu.sh\nwget https://raw.githubusercontent.com/Azure/azure-diagnostics-tools/master/ELK-Semantic-Logging/ELK/AzureRM/elk-simple-on-ubuntu/kibana4-install-ubuntu.sh\n\n#Install ELK\nlog \"Installing Elasticsearch\" \nbash ./elasticsearch-ubuntu-install.sh -n $ES_CLUSTER_NAME -v $ES_VERSION -d $ES_DISCOVERY_HOSTS\nlog \"Installing Elasticsearch Completed\"\n\n#Install Logstash\nlog \"Installing Logstash\"\nbash ./logstash-install-ubuntu.sh -e $ENCODED_LOGSTASH_CONFIG\nlog \"Installing Logstash Completed\"\n\nlog \"Installing Kibana 4\"\nbash ./kibana4-install-ubuntu.sh\nlog \"Installing Kiibana 4 Completed\"\n", "num_lines": 82}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nhelp()\n{\n    echo \"\"\n    echo \"\"\n\techo \"This script installs Kibana 4 on Ubuntu, and configures it to be used with a user's elastic search cluster\"\n\techo \"Parameters:\"\n\techo \"p - The kibana package to use\"\n\techo \"s - Skip common install steps (sudo apt-get update/ installing default-jre)\"\n\techo \"\"\n\techo \"\"\n}\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"kibana4-install-ubuntu.sh:\" $1\n}\n\n# Add to Kibana Config\natkcfg()\n{\n\techo \"$1\" >> ./kibana.yml\n}\n\n#Script Parameters\nKIBANA_PACKAGE_URL=\"https://download.elasticsearch.org/kibana/kibana/kibana-4.0.0-linux-x64.tar.gz\"\n\n#Loop through options passed\nwhile getopts :p:sh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    p)  #package url\n      KIBANA_PACKAGE_URL=${OPTARG}\n      ;;\n\ts)  #skip common install steps\n\t  SKIP_COMMON_INSTALL=\"YES\"\n\t  ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Kibana\nif [ -z $SKIP_COMMON_INSTALL ] \nthen\n  log \"Updating apt-get\"\n  sudo apt-get update\n  log \"Installing Java Runtime\"\n  sudo apt-get -f -y install default-jre\nelse\n  log \"Skipping common install\"\nfi\n\nlog \"Downloading Kibana\"\nwget $KIBANA_PACKAGE_URL -O ./kibana.tar.gz\n\nlog \"Download Completed, Installing Kibana\"\nmkdir ./kibana\nsudo tar -xf ./kibana.tar.gz -C ./kibana --strip 1\n\n#Create User Configuration\natkcfg \"port: 80\"\natkcfg \"host: \\\"0.0.0.0\\\"\"\n#TODO: This should be configurable from the script\natkcfg \"elasticsearch_url: \\\"http://localhost:9200\\\"\"\natkcfg \"elasticsearch_preserve_host: true\"\natkcfg \"kibana_index: \\\".kibana\\\"\"\natkcfg \"default_app_id: \\\"discover\\\"\" \natkcfg \"request_timeout: 500000\"\natkcfg \"shard_timeout: 0\"\natkcfg \"verify_ssl: true\"\natkcfg \"bundled_plugin_ids:\"\natkcfg \" - plugins/dashboard/index\"\natkcfg \" - plugins/discover/index\"\natkcfg \" - plugins/doc/index\"\natkcfg \" - plugins/kibana/index\"\natkcfg \" - plugins/markdown_vis/index\"\natkcfg \" - plugins/metric_vis/index\"\natkcfg \" - plugins/settings/index\"\natkcfg \" - plugins/table_vis/index\"\natkcfg \" - plugins/vis_types/index\"\natkcfg \" - plugins/visualize/index\"\n\n#Install User Configuration\nlog \"Installing user configuration file\"\nsudo \\cp ./kibana.yml ./kibana/config/\n\n# Configure Start\nlog \"Starting Kibana\"\nscreen -d -m sh -c \"while :; do sudo ./kibana/bin/kibana; done;\"\n", "num_lines": 122}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nhelp()\n{\n    echo \"\"\n    echo \"\"\n\techo \"This script installs Logstash 1.4.2 on Ubuntu, and configures it to be used with user plugins/configurations\"\n\techo \"Parameters:\"\n\techo \"p - The logstash package url to use. Currently tested to work on Logstash version 1.4.2.\"\n\techo \"e - The encoded configuration string.\"\n\techo \"\"\n\techo \"\"\n\techo \"\"\n}\n\nlog()\n{\n\techo \"$1\"\n}\n\n#Script Parameters\nLOGSTASH_DEBIAN_PACKAGE_URL=\"https://download.elasticsearch.org/logstash/logstash/packages/debian/logstash_1.4.2-1-2c0f5a1_all.deb\"\n\n#Loop through options passed\nwhile getopts :p:e:hs optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    p)  #package url\n      LOGSTASH_DEBIAN_PACKAGE_URL=${OPTARG}\n      ;;\n\ts)  #skip common install steps\n\t  SKIP_COMMON_INSTALL=\"YES\"\n\t  ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    e)  #set the encoded configuration string\n\t  log \"Setting the encoded configuration string\"\n      CONF_FILE_ENCODED_STRING=\"${OPTARG}\"\n      USE_CONF_FILE_FROM_ENCODED_STRING=\"true\"\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Logstash\n\nif [ -z $SKIP_COMMON_INSTALL ] \nthen\n  log \"Updating apt-get\"\n  sudo apt-get update\n  log \"Installing Java Runtime\"\n  sudo apt-get -f -y install default-jre\nelse\n  log \"Skipping common install\"\nfi\n\nlog \"Downloading logstash package\"\nwget ${LOGSTASH_DEBIAN_PACKAGE_URL} -O logstash.deb\nlog \"Download completed, Installing Logstash\"\nsudo dpkg -i logstash.deb\n\n# Install User Configuration from encoded string\nif [ ! -z $USE_CONF_FILE_FROM_ENCODED_STRING ] \nthen\n  log \"Decoding configuration string\"\n  log \"$CONF_FILE_ENCODED_STRING\"\n  echo $CONF_FILE_ENCODED_STRING > logstash.conf.encoded\n  DECODED_STRING=$(base64 -d logstash.conf.encoded)\n  log \"$DECODED_STRING\"\n  echo $DECODED_STRING > ~/logstash.conf\nfi\n\n# Install Azure\nlog \"Installing Azure SDK\"\nsudo env GEM_HOME=/opt/logstash/vendor/bundle/jruby/1.9 GEM_PATH=\\\"\\\" java -jar /opt/logstash/vendor/jar/jruby-complete-1.7.11.jar -S gem install azure\n\n# Install Plugins\nlog \"Installing Plugins\"\nsudo env GEM_HOME=/opt/logstash/vendor/bundle/jruby/1.9 GEM_PATH=\\\"\\\" java -jar /opt/logstash/vendor/jar/jruby-complete-1.7.11.jar -S gem install logstash-input-azurewadtable\n\n# Copy Plugins\nlog \"Copying plugins\"\nsudo \\cp -f /opt/logstash/vendor/bundle/jruby/1.9/gems/logstash-input-azurewadtable-0.9.2/lib/logstash/inputs/azurewadtable.rb /opt/logstash/lib/logstash/inputs/azurewadtable.rb\n\n#log \"Installing user configuration file\"\nlog \"Installing user configuration file\"\nsudo \\cp -f ~/logstash.conf /etc/logstash/conf.d/\n\n# Configure Start\nlog \"Configure start up service\"\nsudo update-rc.d logstash defaults 95 10\nsudo service logstash start\n", "num_lines": 121}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\n# Error out if uninitialized variable is used\nset -u  \n\nusage()\n{\n    cat <<END\nThis script installs ElasticSearch on Ubuntu VM and makes it part of a specified ES cluster\nParameters:\n  -n <ElasticSearch cluster name>\n  -d <Static discovery endpoint start address> e.g. 10.0.1.4\n  -c <Count of cluster nodes>\n  -v <ElasticSearch version> e.g. 2.2.1\n  -k <Kibana version> e.g. 4.1.1. \n  -u <ElasticSearch user name>\n  -p <ElasticSearch user password>\n  -s <ElasticSearch cluster DNS name> (to configure nginx proxy)\n  -h view this help content\nElastic Search user name, user password and cluster DNS name are mandatory\nEND\n}\n\n# Usage: get_discovery_endpoints start_address node_count\n# Example: get_discovery_endpoints 10.0.1.4 3\n# (returns [\"10.0.1.4\", \"10.0.1.5\", \"10.0.1.6\"]\nget_discovery_endpoints()\n{\n    declare start_address=$1\n    declare address_prefix=${start_address%.*}     # Everything up to last dot (not including)\n    declare -i address_suffix_start=${start_address##*.}  # Last part of the address, interpreted as a number\n    declare retval='['\n    declare -i i\n    declare -i suffix\n    \n    for (( i=0; i<$2; ++i )); do\n        suffix=$(( address_suffix_start + i ))\n        retval+=\"\\\"${address_prefix}.${suffix}\\\", \"\n    done\n    \n    retval=${retval:0:-2}               # Remove last comma and space\n    retval+=']'\n    \n    echo $retval\n}\n\nwait_for_elastic_svc()\n{\n    declare cluster_health=''\n    declare -r HEALTHY='\"status\":\"green\"'\n    declare -ri MAX_TRIES=30    # Keep trying for 5 minutes\n    declare -i i=0\n\n    until [[ $cluster_health =~ $HEALTHY || $i -eq $MAX_TRIES ]]; do\n        sleep 10\n        i+=1\n        cluster_health=$(curl --max-time 10 -s http://localhost:9200/_cluster/health)\n    done\n\n    if [[ $i -eq $MAX_TRIES ]]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\necho \"#################### Installing ElasticSearch on ${HOSTNAME} ####################\"\n\ncluster_name=\"kocour\"\nes_version=\"5.1.1\"\nkibana_version=\"5.1.1\"\nstarting_discovery_endpoint=\"10.0.1.4\"\ndeclare -i cluster_node_count=3\nes_user_name=''\nes_user_password=''\nes_dns_name=''\nexport DEBIAN_FRONTEND='noninteractive'\n\nwhile getopts n:d:c:v:u:p:s:k:h optname; do    \n  case $optname in\n    n) \n      cluster_name=${OPTARG}\n      ;;\n    d) \n      starting_discovery_endpoint=${OPTARG}\n      ;;\n    c)\n      cluster_node_count=${OPTARG}\n      ;;\n    v) \n      es_version=${OPTARG}\n      ;;\n    k)\n      kibana_version=${OPTARG}\n      ;;\n    u)\n      es_user_name=${OPTARG}\n      ;;\n    p)\n      es_user_password=${OPTARG}\n      ;;\n    s)\n      es_dns_name=${OPTARG}\n      ;;\n    h) \n      usage\n      exit 1\n      ;;\n    \\?) \n      echo \"Unrecognized option $optname\"\n      usage\n      exit 2\n      ;;\n  esac\ndone\n\nif [[ ! $es_user_name || ! $es_user_password || ! es_dns_name ]]; then\n    echo 'ElasticSearch user name, password, and server DNS name must be provided (not empty)'\n    exit 3\nfi\n\necho \"#################### Installing Java ####################\"\nsudo apt-get update\nsudo apt-get -qy install openjdk-8-jre\nsudo update-ca-certificates -f\n\necho \"#################### Setting up data disks ####################\"\nbash vm-disk-utils-0.1.sh\n\necho \"#################### Installing ES service ####################\"\nsudo wget \"https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-$es_version.deb\" -O elasticsearch.deb\nsudo dpkg -i --force-all elasticsearch.deb\nsudo systemctl daemon-reload\nsudo systemctl enable elasticsearch.service\n\necho \"#################### Configuring data disks for ES ####################\"\ndatapath_config=\"\"\nif [ -d '/datadisks' ]; then\n    for disk_id in `find /datadisks/ -mindepth 1 -maxdepth 1 -type d`\n    do\n        # Configure disk permissions and folder for storage\n        # We rely on ES default user name & group (elasticsearch)\n        mkdir -p \"${disk_id}/elasticsearch/data\"\n        chown -R elasticsearch:elasticsearch \"${disk_id}/elasticsearch\"\n        chmod 755 \"${disk_id}/elasticsearch\"\n        # Add to list for elasticsearch configuration\n        datapath_config+=\"${disk_id}/elasticsearch/data,\"\n    done\n    #Remove the extra trailing comma\n    datapath_config=\"${datapath_config%?}\"\nelse\n    echo \"Data disk directory not found, cannot set up storage for ElasticSearch service\"\n    exit 4\nfi\n\necho \"#################### Configuring ES service ####################\"\necho \"cluster.name: $cluster_name\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.name: ${HOSTNAME}\" >> /etc/elasticsearch/elasticsearch.yml\necho \"gateway.expected_nodes: ${cluster_node_count}\" >> /etc/elasticsearch/elasticsearch.yml\ndiscovery_endpoints=$(get_discovery_endpoints $starting_discovery_endpoint $cluster_node_count)\necho \"Setting ES discovery endpoints to $discovery_endpoints\"\necho \"discovery.zen.ping.unicast.hosts: $discovery_endpoints\" >> /etc/elasticsearch/elasticsearch.yml\necho \"path.data: $datapath_config\" >> /etc/elasticsearch/elasticsearch.yml\ndeclare -i minimum_master_nodes=$(((cluster_node_count / 2) + 1))\necho \"discovery.zen.minimum_master_nodes: $minimum_master_nodes\" >> /etc/elasticsearch/elasticsearch.yml\necho \"gateway.recover_after_time: 1m\" >> /etc/elasticsearch/elasticsearch.yml\necho \"bootstrap.memory_lock: true\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\necho \"network.host: [_site_, _local_]\" >> /etc/elasticsearch/elasticsearch.yml\n\necho \"#################### Installing nginx ####################\"\nsudo apt-get -qy install nginx\nsudo systemctl daemon-reload\nsudo systemctl enable nginx\n\necho \"#################### Configuring nginx ####################\"\nsudo apt-get -qy install apache2-utils\nprintf '%s' \"$es_user_password\" | sudo htpasswd -ic /etc/nginx/conf.d/elasticsearch.pwd $es_user_name\nconfig_fetch_cmd='curl -s https://raw.githubusercontent.com/Azure/azure-diagnostics-tools/master/ES-MultiNode/elasticsearch.nginx | perl -wnlp -e s/__ES_DNS_NAME/'\nconfig_fetch_cmd+=\"$es_dns_name\"\nconfig_fetch_cmd+='/g > elasticsearch.nginx.conf'\neval \"$config_fetch_cmd\"\nsudo cp elasticsearch.nginx.conf /etc/nginx/sites-available/elasticsearch\nsudo ln /etc/nginx/sites-available/elasticsearch /etc/nginx/sites-enabled\nsudo rm /etc/nginx/sites-enabled/default\nsudo systemctl reload nginx\n\n\necho \"#################### Installing Kibana ####################\"\nsudo wget \"https://artifacts.elastic.co/downloads/kibana/kibana-${kibana_version}-linux-x86_64.tar.gz\"\nsudo tar xvf kibana-*.tar.gz 1>/dev/null\nsudo mkdir -p /opt/kibana\nsudo cp -R ./kibana-5*/* /opt/kibana\nsudo wget https://raw.githubusercontent.com/Azure/azure-diagnostics-tools/master/ES-MultiNode/kibana5.service\nsudo cp ./kibana5.service /etc/systemd/system/kibana5.service\nsudo systemctl daemon-reload\nsudo systemctl enable kibana5.service\nsudo mkdir -p /var/log/kibana\nprintf \"\\n\\nlogging.dest: /var/log/kibana/kibana.log\\n\" | sudo tee -a /opt/kibana/config/kibana.yml > /dev/null\n# ES can take a while to start up, so increase the Kibana startup timeout to 2 minutes\nprintf \"elasticsearch.startupTimeout: 120000\\n\" | sudo tee -a /opt/kibana/config/kibana.yml > /dev/null\n\n\necho \"#################### Optimizing the system ####################\"\n# Set Elasticsearch heap size to 50% of system memory\n# Consider: Move this to an init.d script so we can handle instance size increases\nes_heap_size=$(free -m |grep Mem | awk '{if ($2/2 >31744)  print 31744;else print $2/2;}')\nprintf \"\\nES_HEAP_SIZE=%sm\\n\" $es_heap_size | sudo tee -a /etc/default/elasticseach > /dev/null\nprintf \"MAX_LOCKED_MEMORY=unlimited\\n\" | sudo tee -a /etc/default/elasticsearch > /dev/null\nprintf \"\\nelasticsearch - nofile 65536\" | sudo tee -a /etc/security/limits.conf > /dev/null\nprintf \"\\nelasticsearch  - memlock unlimited\" | sudo tee -a /etc/security/limits.conf > /dev/null\nsudo mkdir -p /etc/systemd/system/elasticsearch.service.d\nprintf \"\\n[Service]\\nLimitMEMLOCK=infinity\\n\" | sudo tee -a /etc/systemd/system/elasticsearch.service.d/elasticsearch.conf > /dev/null\n\necho \"#################### Installing X-pack plugin ####################\"\nsudo /usr/share/elasticsearch/bin/elasticsearch-plugin install x-pack --batch\nsudo /opt/kibana/bin/kibana-plugin install x-pack --quiet\n\n# Disable all features that require paid subscription\n# Monitoring is left enabled--requires a free Basic License\nsudo systemctl stop elasticsearch.service\nprintf \"\\nxpack.security.enabled: false\\n\" | sudo tee -a /etc/elasticsearch/elasticsearch.yml | sudo tee -a /opt/kibana/config/kibana.yml > /dev/null\nprintf \"xpack.graph.enabled: false\\n\" | sudo tee -a /etc/elasticsearch/elasticsearch.yml | sudo tee -a /opt/kibana/config/kibana.yml > /dev/null\nprintf \"xpack.watcher.enabled: false\\n\" | sudo tee -a /etc/elasticsearch/elasticsearch.yml > /dev/null\nprintf \"xpack.reporting.enabled: false\\n\" | sudo tee -a /opt/kibana/config/kibana.yml > /dev/null\n\necho \"#################### Starting Elasticsearch and Kibana ####################\"\nsudo systemctl daemon-reload\nsudo systemctl start elasticsearch.service\n\nwait_for_elastic_svc;\nif [[ $? -ne 0 ]]; then\n    echo \"ElasticSearch service has not started within expected time period. Cannot start Kibana service or install ES head plugin.\" >&2\n    exit 5\nfi\n\nsudo systemctl start kibana5.service\n\nexit 0\n", "num_lines": 271}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script Name: vm-disk-utils.sh\n# Author: Trent Swanson - Full Scale 180 Inc github:(trentmswanson)\n# Version: 0.1\n# Last Modified By:       Trent Swanson\n# Description:\n#  This script automates the partitioning and formatting of data disks\n#  Data disks can be partitioned and formatted as seperate disks or in a RAID0 configuration\n#  The scrtip will scan for unpartitioined and unformatted data disks and partition, format, and add fstab entries\n# Parameters :\n#  1 - b: The base directory for mount points (default: /datadisks)\n#  2 - s  Create a striped RAID0 Array (No redundancy)\n#  3 - h  Help \n# Note : \n# This script has only been tested on Ubuntu 12.04 LTS and must be root\n\nhelp()\n{\n    echo \"Usage: $(basename $0) [-b data_base] [-h] [-s]\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"   -b         base directory for mount points (default: /datadisks)\"\n    echo \"   -h         this help message\"\n    echo \"   -s         create a striped RAID array (no redundancy)\"\n}\n\nlog()\n{\n    # Un-comment the following if you would like to enable logging to a service\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n#A set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\n# Base path for data disk mount points\nDATA_BASE=\"/datadisks\"\n\nwhile getopts b:sh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case ${optname} in\n    b)  #set clsuter name\n      DATA_BASE=${OPTARG}\n      ;;\n    s) #Partition and format data disks as raid set\n      RAID_CONFIGURATION=1\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nget_next_md_device() {\n    shopt -s extglob\n    LAST_DEVICE=$(ls -1 /dev/md+([0-9]) 2>/dev/null|sort -n|tail -n1)\n    if [ -z \"${LAST_DEVICE}\" ]; then\n        NEXT=/dev/md0\n    else\n        NUMBER=$((${LAST_DEVICE/\\/dev\\/md/}))\n        NEXT=/dev/md${NUMBER}\n    fi\n    echo ${NEXT}\n}\n\nis_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi    \n}\n\nhas_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_next_mountpoint() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    MAX=$(echo \"${DIRS}\"|tail -n 1 | tr -d \"[a-zA-Z/]\")\n    if [ -z \"${MAX}\" ];\n    then\n        echo \"${DATA_BASE}/disk1\"\n        return\n    fi\n    IDX=1\n    while [ \"${IDX}\" -lt \"${MAX}\" ];\n    do\n        NEXT_DIR=\"${DATA_BASE}/disk${IDX}\"\n        if [ ! -d \"${NEXT_DIR}\" ];\n        then\n            echo \"${NEXT_DIR}\"\n            return\n        fi\n        IDX=$(( ${IDX} + 1 ))\n    done\n    IDX=$(( ${MAX} + 1))\n    echo \"${DATA_BASE}/disk${IDX}\"\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\tnoatime,nodiratime,nodev,noexec,nosuid\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=83\n    fi\n    echo \"n\np\n1\n\n\nt\n${_type}\nw\"| fdisk \"${_disk}\"\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${_disk}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n#end do_partition\n\nscan_partition_format()\n{\n    log \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n\tif [ \"${#DISKS}\" -eq 0 ];\n\tthen\n\t    log \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\techo \"Disks are ${DISKS[@]}\"\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK}\n\t    fi\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n\t    has_filesystem ${PARTITION}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"Creating filesystem on ${PARTITION}.\"\n\t#        echo \"Press Ctrl-C if you don't want to destroy all data on ${PARTITION}\"\n\t#        sleep 10\n\t        mkfs -j -t ext4 ${PARTITION}\n\t    fi\n\t    MOUNTPOINT=$(get_next_mountpoint)\n\t    echo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t    [ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n\t    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\t    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\t    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n\t    mount \"${MOUNTPOINT}\"\n\tdone\n}\n\ncreate_striped_volume()\n{\n    DISKS=(${@})\n\n\tif [ \"${#DISKS[@]}\" -eq 0 ];\n\tthen\n\t    log \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\n\techo \"Disks are ${DISKS[@]}\"\n\n\tdeclare -a PARTITIONS\n\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK} fd\n\t    fi\n\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 2 Device|tail -n 1|awk '{print $1}')\n\t    PARTITIONS+=(\"${PARTITION}\")\n\tdone\n\n    MDDEVICE=$(get_next_md_device)    \n    \n\tmdadm --create ${MDDEVICE} --level 0 --raid-devices ${#PARTITIONS[@]} ${PARTITIONS[*]}\n\n\tMOUNTPOINT=$(get_next_mountpoint)\n\techo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t[ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n\n\t#Make a file system on the new device\n\tSTRIDE=128 #(512kB stripe size) / (4kB block size)\n\tPARTITIONSNUM=${#PARTITIONS[@]}\n\tSTRIPEWIDTH=$((${STRIDE} * ${PARTITIONSNUM}))\n\n\tmkfs.ext4 -b 4096 -E stride=${STRIDE},stripe-width=${STRIPEWIDTH} \"${MDDEVICE}\"\n\n\tread UUID FS_TYPE < <(blkid -u filesystem ${MDDEVICE}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\n\tadd_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\n\tmount \"${MOUNTPOINT}\"\n}\n\ncheck_mdadm() {\n    dpkg -s mdadm >/dev/null 2>&1\n    if [ ${?} -ne 0 ]; then\n        DEBIAN_FRONTEND=noninteractive apt-get -y install mdadm\n    fi\n}\n\n# Create Partitions\nDISKS=$(scan_for_new_disks)\n\nif [ \"$RAID_CONFIGURATION\" -eq 1 ]; then\n    check_mdadm\n    create_striped_volume \"${DISKS[@]}\"\nelse\n    scan_partition_format\nfi\n\n", "num_lines": 317}
{"repo_name": "azure-diagnostics-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\nhelp()\n{\n    echo \"\"\n    echo \"\"\n\techo \"This script installs Java, Logstash, and the Azure WAD plugin\"\n\techo \"Currently requires no parameters\"\n\techo \"\"\n\techo \"\"\n}\n\nlog()\n{\n\techo \"$1\"\n}\n\n# Install Utilities\nlog \"Installing utilities.\" \nsudo apt-get update\nsudo apt-get -y --force-yes install python-software-properties debconf-utils\n\n# Install Java\nlog \"Installing Java.\" \nsudo add-apt-repository -y ppa:webupd8team/java\nsudo apt-get update\necho \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | sudo debconf-set-selections\nsudo apt-get install -y --force-yes oracle-java8-installer\n\n# Install Logstash\nlog \"Installing Logstash.\"\necho 'deb http://packages.elastic.co/logstash/2.2/debian stable main' | sudo tee /etc/apt/sources.list.d/logstash-2.2.x.list\nsudo apt-get update\nsudo apt-get -y --force-yes install logstash\n\n# Install Azure Plugin\nlog \"Installing Azure WAD Table Plugin\"\nsudo /opt/logstash/bin/plugin install logstash-input-azurewadtable\n\nlog \"Complete\"\n\n\n", "num_lines": 64}
{"repo_name": "azure-diskinspect-service", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd ./tools\n# generate current documentation to a temp folder\nif [ ! -d ~/doc_temp ]; then\n    mkdir ~/doc_temp\nfi\npython3 parse_manifest.py ~/doc_temp\n\n# compare with the current check-in\nif ! diff -w --ignore-matching-lines=\"File was created by running\" ../docs/manifest_content.md ~/doc_temp/manifest_content.md; then\n    echo \"Failed validating manifest_content.md!  Check lines above for details and run parse_manifest.py prior to submitting the PR.\"\n    exit 1\nfi \nif ! diff -w --ignore-matching-lines=\"File was created by running\" ../docs/manifest_by_file.md ~/doc_temp/manifest_by_file.md; then\n    echo \"Failed validating manifest_by_file.md!  Check lines above for details and run parse_manifest.py prior to submitting the PR.\"\n    exit 1\nfi \n\ncd ..\nrm -rf ~/doc_temp", "num_lines": 21}
{"repo_name": "azure-docker-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eou pipefail\n\n# Script to generate Docker certificates and keys for testing. These are\n# temporary certificates, and are good for one day only.\n#\n# See https://docs.docker.com/engine/security/https/ for deails.\n\nreadonly DAYS=1\nreadonly KEY_SIZE=2048\nreadonly OUT=./dockercerts\nreadonly EXT_OUT=./extensionconfig\n\nmkdir -p $OUT\n\n# 1. CA private and public keys\nopenssl genrsa -out $OUT/ca-key.pem $KEY_SIZE\nopenssl req -new -x509 -days $DAYS -key $OUT/ca-key.pem -sha256 -out $OUT/ca.pem -subj \"/C=US/ST=Washington/L=Redmond/O=azure-docker-extension/CN=test-ca\"\n\n# 2. Server\n#  a. server key\n#  b. certificate signing request\n#  c. sign the request with our CA\nopenssl genrsa -out $OUT/server-key.pem $KEY_SIZE\nopenssl req -sha256 -new -key $OUT/server-key.pem -out $OUT/server.csr -subj \"/CN=test-server\"\n\necho subjectAltName = IP:127.0.0.1 > $OUT/server-extfile.cnf\nopenssl x509 -req -days $DAYS -sha256 -in $OUT/server.csr -CA $OUT/ca.pem -CAkey $OUT/ca-key.pem -CAcreateserial -out $OUT/server-cert.pem -extfile $OUT/server-extfile.cnf\n\n# 3. Client key, and certificate signing request\n#  a. client key\n#  b. certificate signing request\n#  c. sign the request with our CA\nopenssl genrsa -out $OUT/key.pem $KEY_SIZE\nopenssl req -new -key $OUT/key.pem -out $OUT/client.csr -subj \"/CN=test-client\"\n\necho extendedKeyUsage = clientAuth > $OUT/client-extfile.cnf\nopenssl x509 -req -days $DAYS -sha256 -in $OUT/client.csr -CA $OUT/ca.pem -CAkey $OUT/ca-key.pem -CAcreateserial -out $OUT/cert.pem -extfile $OUT/client-extfile.cnf\n\ncat <<EOF > $EXT_OUT/protected.json\n{\n    \"environment\": {\n        \"SECRET_KEY\": \"SECRET_VALUE\"\n    },\n    \"certs\": {\n        \"ca\":   \"$(base64 -w0 < $OUT/ca.pem)\",\n        \"cert\": \"$(base64 -w0 < $OUT/server-cert.pem)\",\n        \"key\":  \"$(base64 -w0 < $OUT/server-key.pem)\"\n    }\n}\nEOF\n\n# 4. Cleanup\n#  a. .cnf are no longer needed\n#  b. server key, request, and configuration are no longer needed\n#  c. client request, and configuration are no longer needed\n\nrm \\\n    $OUT/ca-key.pem \\\n    $OUT/server-cert.pem \\\n    $OUT/server-key.pem \\\n    $OUT/server.csr \\\n    $OUT/server-extfile.cnf \\\n    $OUT/client.csr \\\n    $OUT/client-extfile.cnf \\\n\n", "num_lines": 67}
{"repo_name": "azure-docker-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eou pipefail\nIFS=$'\\n\\t'\n\n# these flighting values should match Makefile\nreadonly TEST_SUBS_AZURE=\"c3dfd792-49a4-4b06-80fc-6fc6d06c4742\"\nreadonly TEST_REGION_AZURE=\"South Central US\"\n\nreadonly TEST_SUBS_AZURE_CHINA=\"cc1624c7-3f1d-4ed3-a855-668a86e96ad8\"\nreadonly TEST_REGION_AZURE_CHINA=\"China East\"\n\n# make docker-cli send a lower version number so that we can\n# test old images (if client>newer, docker engine rejects the request)\nreadonly DOCKER_REMOTE_API_VERSION=1.20\n\n# supported images (add/update them as new major versions come out)\nreadonly DISTROS_AZURE=(\n        \"2b171e93f07c4903bcad35bda10acf22__CoreOS-Stable-1235.6.0\" \\\n        \"2b171e93f07c4903bcad35bda10acf22__CoreOS-Alpha-1298.1.0\" \\\n        \"b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-14_04_5-LTS-amd64-server-20170110-en-us-30GB\" \\\n        \"b39f27a8b8c64d52b05eac6a62ebad85__Ubuntu-16_04-LTS-amd64-server-20170113-en-us-30GB\" \\\n        \"5112500ae3b842c8b9c604889f8753c3__OpenLogic-CentOS-73-20161221\"\n)\n\nreadonly DISTROS_AZURE_CHINA=(\n\t\"a54f4e2924a249fd94ad761b77c3e83d__CoreOS-Alpha-1192.0.0\" \\\n\t\"a54f4e2924a249fd94ad761b77c3e83d__CoreOS-Stable-1122.2.0\" \\\n\t\"b549f4301d0b4295b8e76ceb65df47d4__Ubuntu-14_04_3-LTS-amd64-server-20160627-en-us-30GB\" \\\n\t\"b549f4301d0b4295b8e76ceb65df47d4__Ubuntu-16_04-LTS-amd64-server-20160627-en-us-30GB\" \\\n\t\"f1179221e23b4dbb89e39d70e5bc9e72__OpenLogic-CentOS-71-20160329\" \\\n\t\"f1179221e23b4dbb89e39d70e5bc9e72__OpenLogic-CentOS-72-20160617\"\n)\n\n# Test constants\nreadonly SCRIPT_DIR=$(dirname $0)\nreadonly CONCURRENCY=10\nreadonly DOCKER_CERTS_DIR=dockercerts\nreadonly VM_PREFIX=dockerextensiontest-\nreadonly VM_USER=azureuser\nreadonly EXTENSION_NAME=DockerExtension\nreadonly EXTENSION_PUBLISHER=Microsoft.Azure.Extensions\nreadonly EXTENSION_CONFIG_AZURE=extensionconfig/public.json\nreadonly EXTENSION_CONFIG_AZURE_CHINA=extensionconfig/public-azurechina.json\nreadonly EXTENSION_CONFIG_PROT=extensionconfig/protected.json\n\n# Global variables\nexpected_extension_version=\ndistros=\nbusybox_image_name=\nextension_public_config=\ndomain_name=\ntest_subs=\ntest_region=\n\n### Functions\n\nlog() {\n\techo \"[$(date +%T)][DEBUG]\" \"$@\"\n}\n\nerr() {\n\techo >&2 \"[$(date +%T)][ERROR]\" \"$@\"\n}\n\ncommand_exists() {\n\tcommand -v \"$@\" > /dev/null 2>&1\n}\n\ncheck_deps() {\n\tlocal deps=(azure jq docker curl parallel)\n\n\tlocal cmd=\n\tfor cmd in \"${deps[@]}\"; do\n\t\tcommand_exists $cmd || { err \"$cmd not installed.\"; exit 1; }\n\tdone\n}\n\ncheck_asm() {\n\t# capture \"Current Mode: arm\" from azure cmd output\n\tif [[ \"$(azure)\" != *\"Current Mode: asm\"* ]]; then\n\t\tcat <<- EOF\n\t\tazure CLI not in ASM mode (required for testing). Run:\n\n\t\t  azure config mode asm\n\n\t\tNOTE: internal versions in PIR don't propogate to ARM stack until they're\n\t\tpublished to PROD globally, hence 'asm')\n\t\tEOF\n\t\texit 1\n\tfi\n}\n\nintro() {\n\tcat <<- EOF\n\t$EXTENSION_NAME integration tests:\n\n\tExecution Plan\n\t==============\n\t1. Create Azure VMs in the first slice region (make sure 'make publish + make replicationstatus').\n\t2. Add VM extension with a config exercising features to the VMs.\n\t3. Make sure the correct version has landed to the VMs.\n\t4. Wait until the VMs reach the goal state provided by $EXTENSION_NAME. \n\t5. Clean up VMs.\n\n\tUsing test subscription: $test_subs\n\tStaging region to deploy VMs: $test_region\n\n\tEOF\n}\n\nset_subs() {\n\tlog \"Setting subscription to $test_subs...\"\n\tazure account set $test_subs 1>/dev/null\n}\n\ntry_cli() {\n\tlog \"Validating Azure CLI credentials\"\n\t(\n\t\tset -x\n\t\tazure network application-gateway list\n\t)\n\tlog \"Azure CLI is authenticated\"\n}\n\nssh_key() {\n\techo \"$SCRIPT_DIR/id_rsa\"\n}\n\nssh_pub_key() {\n\techo \"$(ssh_key).pub\"\n}\n\ngenerate_docker_certs() {\n    ./gen_docker_certs.sh\n}\n\ngenerate_ssh_keys() {\n\tlocal key=$(ssh_key)\n\tlocal pub=$(ssh_pub_key)\n\n\tif [[ -f \"$key\" ]] && [[ -f \"$pub\" ]];then\n\t\t# no need to regenerate keys\n\t\treturn\n\tfi\n\n\tlog \"Generating SSH keys...\"\n\trm -f \"$key\" \"$pub\"\n\tssh-keygen -q -f \"$key\" -N \"\"\n\tlog \"SSH keys generated.\"\n}\n\ntrim_publisher() {\n\t# trims before __ in image name to get rid of publisher GUID\n\techo $1 | sed 's/.*__//g'\n}\n\nprint_distros() {\n\tlog \"Distro images to be tested:\"\n\n\tlocal d\n\tfor d in \"${distros[@]}\"; do\n\t\tlog \" - $(trim_publisher $d)\"\n\tdone\n\tlog \"Total: ${#distros[@]} VM images.\"\n}\n\nvm_fqdn() {\n\tlocal name=$1\n\techo \"$name.$domain_name\"\n}\n\ncreate_vms() {\n\tgenerate_ssh_keys\n\tprint_distros\n\n\tlocal key=$(ssh_pub_key)\n\tlocal vm_count=${#distros[@]}\n\tlocal vm_names=$(parallel -j$CONCURRENCY echo $VM_PREFIX{} ::: $(seq 1 $vm_count))\n\n\n\tlog \"Creating test VMs in parallel...\"\n\n\t# Print commands to be executed, then execute them\n\tlocal cmd=\"azure vm create {1} {2} -e 22 -l '$test_region' --no-ssh-password --ssh-cert '$key' $VM_USER\"\n\tparallel --dry-run -j$CONCURRENCY --xapply $cmd ::: ${vm_names[@]} ::: ${distros[@]}\n\tparallel -j$CONCURRENCY --xapply $cmd 1>/dev/null ::: ${vm_names[@]} ::: ${distros[@]}\n\n\tlog \"Opening up ports in parallel...\"\n\tlocal ports=( 80 2376 )\n\tfor port in \"${ports[@]}\"; do # ports need to be added one by one for a single VM\n\t\tlocal cmd=\"azure vm endpoint create {1} $port $port\"\n\t\tparallel --dry-run -j$CONCURRENCY $cmd ::: ${vm_names[@]}\n\t\tparallel -j$CONCURRENCY $cmd 1>/dev/null ::: ${vm_names[@]}\n\tdone\n}\n\nget_vms() {\n\tlocal list_json=$(azure vm list --json)\n\techo $list_json | jq -r '.[].VMName' | grep \"^$VM_PREFIX\" | sort -n\n}\n\ndelete_vms() {\n\tlog \"Cleaning up test VMs in parallel...\"\n\n\tlocal cmd=\"azure vm delete -b -q {}\"\n\tlocal vms=$(get_vms)\n\n\tif [[ -z \"$vms\" ]]; then\n\t\treturn\n\tfi\n\n\t# Print commands to be executed, then execute them\n\tparallel --dry-run -j$CONCURRENCY \"$cmd\" ::: \"${vms[@]}\"\n\tparallel -j$CONCURRENCY \"$cmd\" 1>/dev/null ::: \"${vms[@]}\"\n\n\tlog \"Cleaned up all test VMs.\"\n}\n\nparse_minor_version() {\n\t# matches to major.minor in major.minor[.patch[.hotfix]]\n\tlocal v=$1\n\techo $v | grep -Po \"\\d+\\.[\\d]+\" | head -1\n}\n\nadd_extension_to_vms() {\n\tlocal pub_config=\"$SCRIPT_DIR/$extension_public_config\"\n\tlocal prot_config=\"$SCRIPT_DIR/$EXTENSION_CONFIG_PROT\"\n\n\t# To use internal version, MAJOR.MINOR must be specified; not '*' or 'MAJOR.*'\n\tlocal minor_version=$(parse_minor_version $expected_extension_ver)\n\tlog \"Adding extension v${minor_version} to VMs in parallel...\"\n\n\tlocal cmd=\"azure vm extension set {} $EXTENSION_NAME $EXTENSION_PUBLISHER '$minor_version' --public-config-path '$pub_config' --private-config-path '$prot_config'\"\n\tlocal vms=$(get_vms)\n\n\t# Print commands to be executed, then execute them\n\tparallel --dry-run -j$CONCURRENCY \"$cmd\" ::: \"${vms[@]}\"\n\tparallel -j$CONCURRENCY \"$cmd\" 1>/dev/null ::: \"${vms[@]}\"\n\n\tlog \"Added $EXTENSION_NAME to all test VMs.\"\n}\n\ndocker_addr() {\n\tlocal fqdn=$1\n\techo \"tcp://$fqdn:2376\"\n}\n\ndocker_cert_path() {\n\techo \"$SCRIPT_DIR/$DOCKER_CERTS_DIR\"\n}\n\ndocker_cli_env() {\n\tlocal fqdn=$1\n\techo \"DOCKER_CERT_PATH=\\\"$(docker_cert_path)\\\" DOCKER_HOST=\\\"$(docker_addr $fqdn)\\\" DOCKER_API_VERSION=$DOCKER_REMOTE_API_VERSION\"\n}\n\nwait_for_docker() {\n\tlocal host=$1\n\tlocal addr=$(docker_addr $host)\n\n\tlocal docker_certs=\"$(docker_cert_path)\"\n\n\t# Validate \"docker info\" works\n\tlocal docker_env=$(docker_cli_env $host)\n\tlocal docker_cmd=\"docker --tls info\"\n\tlog \"Waiting for Docker engine on $addr...\"\n\techo \"+ $docker_env $docker_cmd\"\n\n\twhile true; do\n\t\tset +e # ignore errors b/c the following command will retry\n\t\teval $docker_env $docker_cmd 1>/dev/null 2>&1\n\t\tlocal exit_code=$?\n\t\tset -e\n\n\t\tif [ $exit_code -ne 0 ]; then\n\t\t\tprintf '.'\n\t\t\tsleep 5\n\t\telse\n\t\t\tlog \"Authenticated to docker engine at $addr.\"\n\t\t\t# Check if docker.options in public.json took effect\n\t\t\tlocal docker_info_out=\"$(eval $docker_env $docker_cmd 2>&1)\"\n                        log \"$docker_info_out\"\n\t\t\tif [[ \"$docker_info_out\" != *\"foo=bar\"* ]]; then\n\t\t\t\terr \"Docker engine label (foo=bar) specified in extension configuration did not take effect.\"\n\t\t\t\tlog \"docker info output:\"\n\t\t\t\tlog \"$docker_info_out\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tlog \"Docker configuration took effect.\"\n\t\t\treturn\n\t\tfi\n\tdone\n}\n\nwait_for_container() {\n\tlocal host=$1\n\tlocal addr=\"http://$1:80/\"\n\n\tlog \"Waiting for web container on $addr...\"\n\tlocal curl_cmd=\"curl -sILfo/dev/null $addr\"\n\techo \"+ $curl_cmd\"\n\n\twhile true; do\n\t\tset +e # ignore errors b/c the following command will retry\n\t\teval $curl_cmd 2>&1 1>/dev/null\n\t\tlocal exit_code=$?\n\t\tset -e\n\n\t\tif [ $exit_code -eq 0 ]; then\n\t\t\tlog \"Web server container is up.\"\n\t\t\treturn\n\t\tfi\n\t\tprintf '.'\n\t\tsleep 5\n\tdone\n}\n\nvalidate_extension_version() {\n\tlocal fqdn=$1\n\tlog \"Validating extension version on VM.\"\n\n\t# Search for file Microsoft.Azure.Extensions.DockerExtension-{version}\n\tlocal prefix=\"${EXTENSION_PUBLISHER}.${EXTENSION_NAME}-\"\n\n\t# Find out what version of extension is installed by running\n\t# a Docker container with /var/lib/waagent mounted\n\tlocal docker_env=$(docker_cli_env $fqdn)\n\tlocal docker_cmd=\"docker --tls run --rm -i -v /var/lib/waagent:/agent ${busybox_image_name} ls -1 /agent | grep '^$prefix'\"\n\n\techo \"+ $docker_env $docker_cmd\"\n\tlocal version=\"$(eval $docker_env $docker_cmd 2>/dev/null | sed \"s/^$prefix//g\")\"\n\tif [[ -z \"$version\" ]]; then\n\t\terr \"Could not locate $EXTENSION_NAME version.\"\n\t\texit 1\n\tfi\n\n\tif [[ \"$version\" != \"$expected_extension_ver\" ]]; then\n\t\terr \"Wrong $EXTENSION_NAME encountered: '$version' (expected: '$expected_extension_ver').\"\n\t\texit 1\n\tfi\n\tlog \"VM has the correct version of $EXTENSION_NAME.\"\n}\n\nvalidate_env() {\n\tlocal fqdn=$1\n\tlocal env_key=$2\n\tlocal env_val=$3\n\n\tlocal docker_env=$(docker_cli_env $fqdn)\n\tlocal docker_cmd=\"docker --tls run --rm -i -v /test:/test ${busybox_image_name} cat /test/env.txt\"\n\n\tlog \"Validating environment variable '$env_key'.\"\n\techo \"+ $docker_env $docker_cmd\"\n\tlocal i=0\n\twhile true; do\n\t\tset +e\n\t\tlocal output=\"$(eval $docker_env $docker_cmd 2>&1)\"\n\t\tset -e\n\t\tif [[ \"$output\" == *\"$env_key=$env_val\"* ]]; then\n\t\t\tlog \"Environment variable $env_val found in environment.\"\n\t\t\treturn\n\t\telif [[ $i -gt 5 ]]; then\n\t\t\tlog \"Environment file served does not contain env key: '$env_val':\"\n\t\t\techo \"$output\"\n\t\t\texit 1\n\t\tfi\n\t\ti=$((i+1))\n\t\tprintf '.'\n\t\tsleep 5\n\tdone\n}\n\nget_container_names() {\n\tlocal fqdn=$1\n\n\tlocal docker_env=$(docker_cli_env $fqdn)\n\tlocal docker_cmd=\"docker --tls ps -a --format '{{.Names}}'\"\n\n\techo \"$(eval $docker_env $docker_cmd 2>&1)\"\n}\n\nvalidate_container_prefixes() {\n\tlocal fqdn=$1\n\tlocal prefix=$2\n\n\tlocal out=$(get_container_names $fqdn | grep -v \"^${prefix}_\")\n\tif [[ -n \"$out\" ]]; then\n\t\tlog \"DOCKER_COMPOSE_PROJECT setting is not effective.\"\n\t\tlog \"   Found containers without preconfigured prefix: $out\"\n\t\texit 1\n\tfi\n\tlog \"docker-compose container prefixes are correct.\"\n}\n\nvm_ssh_cmd() {\n\tlocal fqdn=$1\n\techo \"ssh -o \\\"StrictHostKeyChecking no\\\" -i '$(ssh_key)' ${VM_USER}@${fqdn}\"\n}\n\nvalidate_vm() {\n\tlocal name=$1\n\tlocal fqdn=$(vm_fqdn $name)\n\n\tlog \"Validating $EXTENSION_NAME on VM '$name'\"\n\tlog \"    (To debug issues: $(echo $(vm_ssh_cmd $fqdn)))\"\n\twait_for_docker $fqdn\n\tvalidate_extension_version $fqdn\n\twait_for_container $fqdn\n\tvalidate_env $fqdn \"SECRET_KEY\" \"SECRET_VALUE\"\n\tvalidate_env $fqdn \"COMPOSE_PROJECT_NAME\" \"test\"\n\tvalidate_container_prefixes $fqdn \"test\"\n\n\tlog \"VM is O.K.: $name.\"\n\techo\n}\n\nvalidate_vms() {\n\tlog \"Validating VMs...\"\n\tlocal vms=$(get_vms)\n\tfor vm in $vms; do\n\t\tvalidate_vm \"$vm\"\n\tdone\n}\n\nread_version() {\n\tread -p \"Expected $EXTENSION_NAME version in VMs (e.g. 1.2.2): \" expected_extension_ver\n\tif [[ -z \"$expected_extension_ver\" ]]; then\n\t\terr \"Empty string passed\"\n\t\texit 1\n\tfi\n}\n\nread_environment() {\n\tread -p \"Enter the test environment name (e.g. AzureCloud, AzureChinaCloud. The default is AzureCloud): \" test_environment\n\tcase \"$test_environment\" in\n\t\t\"\" | \"AzureCloud\")\n\t\t\tdistros=( \"${DISTROS_AZURE[@]}\" )\n\t\t\textension_public_config=$EXTENSION_CONFIG_AZURE\n\t\t\tbusybox_image_name=\"busybox\"\n\t\t\tdomain_name=\"cloudapp.net\"\n\t\t\ttest_subs=$TEST_SUBS_AZURE\n\t\t\ttest_region=$TEST_REGION_AZURE\n\t\t\t;;\n\t\t\"AzureChinaCloud\")\n\t\t\tdistros=( \"${DISTROS_AZURE_CHINA[@]}\" )\n\t\t\textension_public_config=$EXTENSION_CONFIG_AZURE_CHINA\n\t\t\tbusybox_image_name=\"mirror.azure.cn:5000/library/busybox\"\n\t\t\tdomain_name=\"chinacloudapp.cn\"\n\t\t\ttest_subs=$TEST_SUBS_AZURE_CHINA\n\t\t\ttest_region=$TEST_REGION_AZURE_CHINA\n\t\t\t;;\n\t\t*)\n\t\t\terr \"Invalid environment name\"\n\t\t\texit 1\n\tesac\n}\n\ncheck_deps\nintro\nread_version\nread_environment\ncheck_asm\nset_subs\ntry_cli\n\ndelete_vms\ngenerate_docker_certs\ncreate_vms\nadd_extension_to_vms\nvalidate_vms\n\nlog \"Test run is successful!\"\nlog \"Cleaning up test artifacts...\"\ndelete_vms\nlog \"Success.\"\n", "num_lines": 476}
{"repo_name": "azure-docker-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -eu\nreadonly SCRIPT_DIR=$(dirname $0)\n\n# Script logs its output (stdout/stderr) simultaneously to a file\n# as waagent does not capture output of processes it starts.\nexec > >(tee -ia /var/log/azure-docker-extension-enable.log)\nexec 2>&1\n\n# This script kicks off the ./bin/docker-extension in the\n# background and disowns it with nohup. This is a workaround\n# for the 5-minute time limit for 'enable' step and 15-minute\n# time limit for 'install' step of the Windows Azure VM Extension\n# model which exists by design. By forking and running in the \n# background, the process does not get killed after the timeout\n# and yet still reports its progress through '.status' files to\n# the extension system.\n\n# First, report \"transitioning\" status through .status file before\n# returning from this script so that agent can see the file before\n# the main extension executable starts. Another workaround really.\n\n# status_file returns the .status file path we are supposed to write\n# by determining the highest sequence number from .settings files.\nstatus_file_path() {\n        # normally we'd need to find this config_dir by parsing the\n        # HandlerEnvironment.json, but hey we're in a bash script here,\n        # so assume it's at ../config/.\n        local config_dir=$(readlink -f \"${SCRIPT_DIR}/../config\")\n        local status_dir=$(readlink -f \"${SCRIPT_DIR}/../status\")\n        config_file=$(ls $config_dir | grep -E ^[0-9]+.settings$ | sort -n | tail -n 1)\n        status_file=$(echo $config_file | sed s/settings/status/)\n        readlink -f \"$status_dir/$status_file\"\n}\n\nwrite_status() {\n\tlocal timestamp=\"$(date --utc --iso-8601=seconds)\"\n\tlocal status_file=$(status_file_path)\n\techo \"Writing status to $status_file.\"\n\tcat > \"$status_file\" <<- EOF\n\t\t[\n\t\t\t{\n\t\t\t\t\"version\": 1,\n\t\t\t\t\"timestampUTC\": \"$timestamp\",\n\t\t\t\t\"status\": {\n\t\t\t\t\t\"operation\": \"Enable Docker\",\n\t\t\t\t\t\"status\": \"transitioning\",\n\t\t\t\t\t\"formattedMessage\": {\n\t\t\t\t\t\t\"lang\": \"en\",\n\t\t\t\t\t\t\"message\": \"Enabling Docker\"\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\tEOF\n}\n\n\nwrite_status\nset -x\nnohup $(readlink -f \"$SCRIPT_DIR/../bin/docker-extension\") $@ &\n", "num_lines": 62}
{"repo_name": "azure-dockerdatacenter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#should work for all skus\n#set -x\n#set -xeuo pipefail\n\n#if [[ $(id -u) -ne 0 ]] ; then\n#    echo \"Must be run as root\"\n#   exit 1\n#fi\necho $(date) \" - Starting Script\"\n\nPASSWORD=$1\nMASTERFQDN=$2\n#FILEURI=$3\nMASTERPRIVATEIP=$3\nFQDNDET=$7\n#DTRFQDN=$7\n#NFQDN=$8\nDOCKERDET=$8\n\nDTRFQDN=$( echo \"$7\" |cut -d\\: -f2 )\nNFQDN=$( echo \"$7\" |cut -d\\: -f3 )\nDOCKERVER=$( echo \"$8\" |cut -d\\: -f1 )\nDOCKERCOMPVER=$( echo \"$8\" |cut -d\\: -f2 )\nDOCKERMCVER=$( echo \"$8\" |cut -d\\: -f3 )\nTRUSTYREPO=$( echo \"$8\" |cut -d\\: -f4 )\nDOCKERDCVER=$( echo \"$8\" |cut -d\\: -f5 )\nUCPIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f1|sed 's/ucp\\-/ucp\\:/g')\nDTRIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f2|sed 's/dtr\\-/dtr\\:/g')\n\nif [ ! -z \"$4\" ]; then\nomsworkspaceid=$4\n\nomsworkspacekey=$5\n\nomslnxagentver=$6\n\necho \"All are respectively \" $1 $2 $3 $4 $5 $6\necho  \"MASTER FQDN is\" $MASTERFQDN\necho  \"omsworkspaceid is\" $omsworkspaceid\necho  \"omsworkspacekey is\" $omsworkspacekey\necho  \"omslnxagentver is\" $omslnxagentver\nelse\necho \"All are respectively \" $1 $2 $3\necho  \"MASTER FQDN is\" $MASTERFQDN\nfi\n\ndisable_ufw_iptables()\n{\nufw disable\n\niptables-save > $HOME/firewall.txt\n\niptables -X\n\niptables -t nat -F\n\niptables -t nat -X\n\niptables -t mangle -F\n\niptables -t mangle -X\n\niptables -P INPUT ACCEPT\n\niptables -P FORWARD ACCEPT\n\niptables -P OUTPUT ACCEPT\n\nip6tables-save > $HOME/firewall-6.txt\n\nip6tables -X\n\nip6tables -t mangle -F\n\nip6tables -t mangle -X\n\nip6tables -P INPUT ACCEPT\n\nip6tables -P FORWARD ACCEPT\n\nip6tables -P OUTPUT ACCEPT\n}\n\ninstall_license()\n{\n#copy license key to /opt/ucp/ucp\ncat > /opt/ucp/docker_subscription.lic <<EOF\n'$FILEURI'\nEOF\n\n# removing a special character from subscription.lic\nsed -i -- \"s/'//g\" /opt/ucp/docker_subscription.lic\nsed -i -- \"s/{/{\\\"/g\" /opt/ucp/docker_subscription.lic\nsed -i -- \"s/}/\\\"}/g\" /opt/ucp/docker_subscription.lic\nsed -i -- \"s/:/\\\":/g\" /opt/ucp/docker_subscription.lic\nsed -i -- \"s/,\\ /,\\ \\\"/g\" /opt/ucp/docker_subscription.lic   \n#wget \"$FILEURI\" -O /opt/ucp/docker_subscription.lic\n}\n\ninstallomsagent()\n{\n#wget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent_Ignite2016_v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nwget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent-201610-v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nchmod +x ./omsagent-${omslnxagentver}.universal.x64.sh\nmd5sum ./omsagent-${omslnxagentver}.universal.x64.sh\nsudo sh ./omsagent-${omslnxagentver}.universal.x64.sh --upgrade -w $omsworkspaceid -s $omsworkspacekey\n}\n\ninstrumentfluentd_docker()\n{\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i.bak -e '12d' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '12iEnvironment=\"DOCKER_OPTS=--log-driver=fluentd --log-opt fluentd-address=localhost:25225\"' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '13iExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS' docker.service\nservice docker restart\n}\ninstall_docker_tools()\n{\n# System Update and docker version update\nDEBIAN_FRONTEND=noninteractive apt-mark hold walinuxagent\nDEBIAN_FRONTEND=noninteractive apt-get -y update\napt-get install -y apt-transport-https ca-certificates\n#apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n#echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> /etc/apt/sources.list.d/docker.list\ncurl -s 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | apt-key add --import\n#echo 'deb https://packages.docker.com/1.12/apt/repo ubuntu-trusty testing' >> /etc/apt/sources.list.d/docker.list\necho \"deb https://packages.docker.com/${DOCKERVER}/apt/repo ubuntu-trusty ${TRUSTYREPO}\" >> /etc/apt/sources.list.d/docker.list\napt-cache policy docker-engine\nDEBIAN_FRONTEND=noninteractive apt-get -y update\nDEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n#curl -L https://github.com/docker/compose/releases/download/1.9.0-rc4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n#curl -L https://github.com/docker/machine/releases/download/v0.8.2/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\ncurl -L https://github.com/docker/compose/releases/download/$DOCKERCOMPVER/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\ncurl -L https://github.com/docker/machine/releases/download/v$DOCKERMCVER/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-compose\nexport PATH=$PATH:/usr/local/bin/\ngroupadd docker\nusermod -aG docker ucpadmin\nservice docker restart\n}\ndisable_ufw_iptables;\ninstall_docker_tools;\nif [ ! -z \"$4\" ]; then\nsleep 45;\ninstrumentfluentd_docker;\nsleep 30;\ninstallomsagent;\nfi\n\n# Fix for Docker Daemon when cloning a base image\n# rm  /etc/docker/key.json  \n# service docker restart\n# Load the downloaded Tar File\nsleep 45;\necho  \" - Loading docker install Tar\"\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-2.0.0-beta1_dtr-2.1.0-beta1.tar.gz\n#cd /opt/ucp && wget https://s3.amazonaws.com/packages.docker.com/caas/ucp-2.0.0-beta3_dtr-2.1.0-beta3.tar.gz\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ncd /opt/ucp && wget https://packages.docker.com/caas/$DOCKERDCVER.tar.gz\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-1.1.4_dtr-2.0.3.tar.gz\n#docker load < /opt/ucp/ucp-1.1.2_dtr-2.0.2.tar.gz\n#docker load < /opt/ucp/ucp-1.1.4_dtr-2.0.3.tar.gz\n#docker load < ucp-2.0.0-beta1_dtr-2.1.0-beta1.tar.gz\n#docker load < ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ndocker load < $DOCKERDCVER.tar.gz\n\n# Start installation of UCP with master Controller\n\necho \" - Loading complete.  Starting UCP Install\"\n\n#docker run --rm -i \\\n#    --name ucp \\\n#    -v /var/run/docker.sock:/var/run/docker.sock \\\n#    -v /opt/ucp/docker_subscription.lic:/docker_subscription.lic \\\n#    -e UCP_ADMIN_PASSWORD=$PASSWORD \\\n#    docker/ucp:2.0.0-beta1 \\\n#    install -D --host-address eth0\n    \ndocker run --rm -i \\\n    --name ucp \\\n    -v /var/run/docker.sock:/var/run/docker.sock \\\n    -e UCP_ADMIN_PASSWORD=$PASSWORD \\\n    docker/${UCPIMAGETAG} \\\n    install -D --san $MASTERFQDN --san $DTRFQDN --san $NFQDN --host-address eth0\n#docker run --rm -i \\\n#    --name ucp \\\n#    -v /var/run/docker.sock:/var/run/docker.sock \\\n#    -e UCP_ADMIN_PASSWORD=$PASSWORD \\\n#    docker/ucp:2.0.0-beta4 \\\n#    install -D --san $MASTERFQDN --san $DTRFQDN --san $NFQDN --host-address $MASTERFQDN\nif [ $? -eq 0 ]\nthen\n echo  \" - UCP installed and started on the master Controller\"\nelse\n echo \" -- UCP installation failed\"\nfi\n\n", "num_lines": 199}
{"repo_name": "azure-dockerdatacenter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#should work for all skus\n#set -x\n#set -xeuo pipefail\n\n#if [[ $(id -u) -ne 0 ]] ; then\n#    echo \"Must be run as root\"\n#    exit 1\n#fi\n# We need four params: (1) PASSWORD (2) MASTERFQDN (3) MASTERPRIVATEIP (4) SLEEP\n\necho $(date) \" - Starting Script\"\n\nPASSWORD=$1\nMASTERFQDN=$2\nMASTERPRIVATEIP=$3\n#DTRFQDN=$8\n#NFQDN=$9\nFQDNDET=$8\nDOCKERDET=$9\n\nDTRFQDN=$( echo \"$8\" |cut -d\\: -f2 )\nNFQDN=$( echo \"$8\" |cut -d\\: -f3 )\nDOCKERVER=$( echo \"$9\" |cut -d\\: -f1 )\nDOCKERCOMPVER=$( echo \"$9\" |cut -d\\: -f2 )\nDOCKERMCVER=$( echo \"$9\" |cut -d\\: -f3 )\nTRUSTYREPO=$( echo \"$9\" |cut -d\\: -f4 )\nDOCKERDCVER=$( echo \"$9\" |cut -d\\: -f5 )\nUCPIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f1|sed 's/ucp\\-/ucp\\:/g')\nDTRIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f2|sed 's/dtr\\-/dtr\\:/g')\n\nSLEEP=$4\nif [ ! -z \"$5\" ]; then\nomsworkspaceid=$5\nomsworkspacekey=$6\nomslnxagentver=$7\n\necho \"All are respectively \" $1 $2 $3 $4 $5 $6 $7\necho  \"omsworkspaceid is\" $omsworkspaceid\necho  \"omsworkspacekey is\" $omsworkspacekey\necho  \"omslnxagentver is\" $omslnxagentver\nelse\necho \"All are respectively \" $1 $2 $3 $4\nfi\n\ndisable_ufw_iptables()\n{\nufw disable\n\niptables-save > $HOME/firewall.txt\n\niptables -X\n\niptables -t nat -F\n\niptables -t nat -X\n\niptables -t mangle -F\n\niptables -t mangle -X\n\niptables -P INPUT ACCEPT\n\niptables -P FORWARD ACCEPT\n\niptables -P OUTPUT ACCEPT\n\nip6tables-save > $HOME/firewall-6.txt\n\nip6tables -X\n\nip6tables -t mangle -F\n\nip6tables -t mangle -X\n\nip6tables -P INPUT ACCEPT\n\nip6tables -P FORWARD ACCEPT\n\nip6tables -P OUTPUT ACCEPT\n}\ndisable_ufw_iptables;\n# Implement delay timer to stagger joining of Controller replicas to cluster\n\ninstallomsagent()\n{\n#wget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent_Ignite2016_v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nwget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent-201610-v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nchmod +x ./omsagent-${omslnxagentver}.universal.x64.sh\nmd5sum ./omsagent-${omslnxagentver}.universal.x64.sh\nsudo sh ./omsagent-${omslnxagentver}.universal.x64.sh --upgrade -w $omsworkspaceid -s $omsworkspacekey\n}\n\ninstrumentfluentd_docker()\n{\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i.bak -e '12d' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '12iEnvironment=\"DOCKER_OPTS=--log-driver=fluentd --log-opt fluentd-address=localhost:25225\"' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '13iExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS' docker.service\nservice docker restart\n}\ninstall_docker_tools()\n{\n# System Update and docker version update\nDEBIAN_FRONTEND=noninteractive apt-mark hold walinuxagent\nDEBIAN_FRONTEND=noninteractive apt-get -y update\napt-get install -y apt-transport-https ca-certificates\n#apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n#echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> /etc/apt/sources.list.d/docker.list\ncurl -s 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | apt-key add --import\n#echo 'deb https://packages.docker.com/1.12/apt/repo ubuntu-trusty testing' >> /etc/apt/sources.list.d/docker.list\necho \"deb https://packages.docker.com/${DOCKERVER}/apt/repo ubuntu-trusty ${TRUSTYREPO}\" >> /etc/apt/sources.list.d/docker.list\napt-cache policy docker-engine\nDEBIAN_FRONTEND=noninteractive apt-get -y update\nDEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n#curl -L https://github.com/docker/compose/releases/download/1.9.0-rc4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n#curl -L https://github.com/docker/machine/releases/download/v0.8.2/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\ncurl -L https://github.com/docker/compose/releases/download/$DOCKERCOMPVER/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\ncurl -L https://github.com/docker/machine/releases/download/v$DOCKERMCVER/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-compose\nexport PATH=$PATH:/usr/local/bin/\ngroupadd docker\nusermod -aG docker ucpadmin\nservice docker restart\n}\ninstall_docker_tools;\nif [ ! -z \"$5\" ]; then\nsleep 45;\ninstrumentfluentd_docker;\nsleep 30;\ninstallomsagent;\nfi\n\n\n\necho $(date) \"Sleeping for $SLEEP\"\nsleep $SLEEP\n# Retrieve Fingerprint from Master Controller\ncurl --insecure https://$MASTERFQDN/ca > ca.pem\nFPRINT=$(openssl x509 -in ca.pem -noout -sha256 -fingerprint | awk -F= '{ print $2 }' )\necho $FPRINT\n\n# Load the downloaded Tar File\n\n#cd /opt/ucp && wget https://s3.amazonaws.com/packages.docker.com/caas/ucp-2.0.0-beta3_dtr-2.1.0-beta3.tar.gz\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ncd /opt/ucp && wget https://packages.docker.com/caas/$DOCKERDCVER.tar.gz\n#docker load < ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ndocker load < $DOCKERDCVER.tar.gz\n\n# Start installation of UCP and join Controller replica to master Controller\n\n#docker run --rm -i \\\n#   --name ucp \\\n#    -v /var/run/docker.sock:/var/run/docker.sock \\\n#    -e UCP_ADMIN_USER=admin \\\n#    -e UCP_ADMIN_PASSWORD=$PASSWORD \\\n#    docker/ucp:2.0.0-beta1 \\\n#    join --replica --san $MASTERPRIVATEIP --url https://$MASTERPRIVATEIP --fingerprint \"${FPRINT}\"\n\ndocker run --rm -i \\\n   --name ucp \\\n   -v /var/run/docker.sock:/var/run/docker.sock \\\n   -e UCP_ADMIN_USER=admin \\\n   -e UCP_ADMIN_PASSWORD=$PASSWORD \\\n    docker/${UCPIMAGETAG} \\\n    join --replica --san $MASTERFQDN --san $DTRFQDN --san $NFQDN --url https://$MASTERFQDN --fingerprint \"${FPRINT}\"\n\nif [ $? -eq 0 ]\nthen\necho $(date) \" - UCP installed and started on the master(replica) Controller\"\nelse\n echo $(date) \" -- UCP installation failed\"\nfi\n\necho $(date) \" - Staring Swarm Join as Manager to Leader UCP Controller\"\napt-get -y update && apt-get install -y curl jq\n# Create an environment variable with the user security token\nAUTHTOKEN=$(curl -sk -d '{\"username\":\"admin\",\"password\":\"'\"$PASSWORD\"'\"}' https://$MASTERPRIVATEIP/auth/login | jq -r .auth_token)\necho \"$AUTHTOKEN\"\n# Download the client certificate bundle\ncurl -k -H \"Authorization: Bearer ${AUTHTOKEN}\" https://$MASTERPRIVATEIP/api/clientbundle -o bundle.zip\nunzip bundle.zip && chmod +x env.sh && source env.sh\n#docker swarm join-token manager|sed '1d'|sed '1d'|sed '$ d'>swarmjoin.sh\ndocker swarm join-token manager|sed '1d'|sed '1d'|sed '$ d'> /usr/local/bin/docker-managerswarmjoin\nunset DOCKER_TLS_VERIFY\nunset DOCKER_CERT_PATH\nunset DOCKER_HOST\n#chmod 755 swarmjoin.sh\nchmod +x /usr/local/bin/docker-managerswarmjoin\nexport PATH=$PATH:/usr/local/bin/\ndocker-managerswarmjoin\n#source swarmjoin.sh\n", "num_lines": 194}
{"repo_name": "azure-dockerdatacenter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#should work for all skus\n#set -x\n#set -xeuo pipefail\n\n#if [[ $(id -u) -ne 0 ]] ; then\n#    echo \"Must be run as root\"\n#    exit 1\n#fi\n# We need five params: (1) PASSWORD (2) MASTERFQDN (3) DTR_PUBLIC_IP (4) REPLICA_ID (5) MASTERPRIVATEIP (6) UCP_NODE_REP (7) COUNT (8) SLEEP\n\necho $(date) \" - Starting Script\"\n\nUSER=admin\nPASSWORD=$1\nUCP_NODE=$(hostname)\nFQDNDET=$2\nMASTERFQDN=$( echo \"$2\" |cut -d\\: -f1 )\nDTR_PUBLIC_IP=$( echo \"$2\" |cut -d\\: -f2 )\nUCP_URL=https://$MASTERFQDN\nREPLICA_ID=$3\nMASTERPRIVATEIP=$4\nUCP_NODE_REP=$5\nUCP_NODE_SUF=-ucpdtrnode\nCOUNT=$6\nSLEEP=$7\nDTR_PUBLIC_URL=https://$DTR_PUBLIC_IP\nomsworkspaceid=$( echo \"$8\" |cut -d\\: -f1 )\nomsworkspacekey=$( echo \"$8\" |cut -d\\: -f2 )\nomslnxagentver=$( echo \"$8\" |cut -d\\: -f3 )\n\nDOCKERDET=$9\nDOCKERVER=$( echo \"$9\" |cut -d\\: -f1 )\nDOCKERCOMPVER=$( echo \"$9\" |cut -d\\: -f2 )\nDOCKERMCVER=$( echo \"$9\" |cut -d\\: -f3 )\nTRUSTYREPO=$( echo \"$9\" |cut -d\\: -f4 )\nDOCKERDCVER=$( echo \"$9\" |cut -d\\: -f5 )\nUCPIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f1|sed 's/ucp\\-/ucp\\:/g')\nDTRIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f2|sed 's/dtr\\-/dtr\\:/g')\n\nif [ ! -z \"$omsworkspaceid\" ]; then\n\necho  \"omsworkspaceid is\" $omsworkspaceid\nelse\necho \"All are respectively \" $1 $2 $3 $4\nfi\n\ndisable_ufw_iptables()\n{\nufw disable\n\niptables-save > $HOME/firewall.txt\n\niptables -X\n\niptables -t nat -F\n\niptables -t nat -X\n\niptables -t mangle -F\n\niptables -t mangle -X\n\niptables -P INPUT ACCEPT\n\niptables -P FORWARD ACCEPT\n\niptables -P OUTPUT ACCEPT\n\nip6tables-save > $HOME/firewall-6.txt\n\nip6tables -X\n\nip6tables -t mangle -F\n\nip6tables -t mangle -X\n\nip6tables -P INPUT ACCEPT\n\nip6tables -P FORWARD ACCEPT\n\nip6tables -P OUTPUT ACCEPT\n}\n\ndisable_ufw_iptables;\n\ninstallomsagent()\n{\n#wget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent_Ignite2016_v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nwget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent-201610-v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nchmod +x ./omsagent-${omslnxagentver}.universal.x64.sh\nmd5sum ./omsagent-${omslnxagentver}.universal.x64.sh\nsudo sh ./omsagent-${omslnxagentver}.universal.x64.sh --upgrade -w $omsworkspaceid -s $omsworkspacekey\n}\n\ninstrumentfluentd_docker()\n{\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i.bak -e '12d' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '12iEnvironment=\"DOCKER_OPTS=--log-driver=fluentd --log-opt fluentd-address=localhost:25225\"' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '13iExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS' docker.service\nservice docker restart\n}\ninstall_docker_tools()\n{\n# System Update and docker version update\nDEBIAN_FRONTEND=noninteractive apt-mark hold walinuxagent\nDEBIAN_FRONTEND=noninteractive apt-get -y update\napt-get install -y apt-transport-https ca-certificates\n#apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n#echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> /etc/apt/sources.list.d/docker.list\ncurl -s 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | apt-key add --import\n#echo 'deb https://packages.docker.com/1.12/apt/repo ubuntu-trusty testing' >> /etc/apt/sources.list.d/docker.list\necho \"deb https://packages.docker.com/${DOCKERVER}/apt/repo ubuntu-trusty ${TRUSTYREPO}\" >> /etc/apt/sources.list.d/docker.list\napt-cache policy docker-engine\nDEBIAN_FRONTEND=noninteractive apt-get -y update\nDEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n#curl -L https://github.com/docker/compose/releases/download/1.9.0-rc4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n#curl -L https://github.com/docker/machine/releases/download/v0.8.2/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\ncurl -L https://github.com/docker/compose/releases/download/$DOCKERCOMPVER/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\ncurl -L https://github.com/docker/machine/releases/download/v$DOCKERMCVER/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-compose\nexport PATH=$PATH:/usr/local/bin/\ngroupadd docker\nusermod -aG docker ucpadmin\nservice docker restart\n}\ninstall_docker_tools;\nif [ ! -z \"$omsworkspaceid\" ]; then\nsleep 45;\ninstrumentfluentd_docker;\nsleep 30;\ninstallomsagent;\nfi\n\ninstallbundle ()\n{\n\necho $(date) \"Sleeping for $SLEEP\"\nsleep $SLEEP\necho $(date) \" - Staring Swarm Join as worker UCP Controller\"\napt-get -y update && apt-get install -y curl jq\n# Create an environment variable with the user security token\nAUTHTOKEN=$(curl -sk -d '{\"username\":\"admin\",\"password\":\"'\"$PASSWORD\"'\"}' https://$MASTERPRIVATEIP/auth/login | jq -r .auth_token)\necho \"$AUTHTOKEN\"\n# Download the client certificate bundle\ncurl -k -H \"Authorization: Bearer ${AUTHTOKEN}\" https://$MASTERPRIVATEIP/api/clientbundle -o bundle.zip\nunzip -o bundle.zip && chmod +x env.sh && source env.sh\n}\njoinucp() {\ninstallbundle;\n#docker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'>swarmjoin.sh\ndocker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'> /usr/local/bin/docker-workerswarmjoin\nunset DOCKER_TLS_VERIFY\nunset DOCKER_CERT_PATH\nunset DOCKER_HOST\n#chmod 755 swarmjoin.sh\nchmod +x /usr/local/bin/docker-workerswarmjoin\nexport PATH=$PATH:/usr/local/bin/\ndocker-workerswarmjoin\n#source swarmjoin.sh\n}\n## Insecure TLS as self signed will fail -- Failed to get bootstrap client: Failed to get UCP CA: Get https://blahblah/ca: x509: certificate signed by unknown authority\ninstalldtr() {\ninstallbundle;\necho $(date) \" - Loading docker install Tar\"\n#cd /opt/ucp && wget https://s3.amazonaws.com/packages.docker.com/caas/ucp-2.0.0-beta3_dtr-2.1.0-beta3.tar.gz\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ncd /opt/ucp && wget https://packages.docker.com/caas/$DOCKERDCVER.tar.gz\n#docker load < ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ndocker load < $DOCKERDCVER.tar.gz\n# Implement delay timer to stagger load of the bits - docker.com CDN Dependent\nsleep 45;\necho $(date) \" - Loading complete.  Starting UCP Install\"\n# Start installation of UCP with master Controller\ndocker run --rm  \\\n  docker/${DTRIMAGETAG} install \\\n  --ucp-node $UCP_NODE \\\n  --ucp-insecure-tls \\\n  --dtr-external-url $DTR_PUBLIC_URL  \\\n  --ucp-url https://$MASTERFQDN \\\n  --ucp-username admin --ucp-password $PASSWORD\n  }\njoinucp;\n# Implement delay timer to stagger joining of Agent Nodes to cluster\necho $(date) \"Sleeping for 45\"\nsleep 60;\n# Install DTR\ninstalldtr;\n\n if [ $? -eq 0 ]\n then\n echo $(date) \" - Completed DTR installation on master DTR node\"\n else\n  echo $(date) \" - DTR installation on master DTR node failed\"\n fi\n \n \n # Install DTR for replica placeholder\n #docker run -it --rm \\\n #  dockerhubenterprise/dtr:2.1.0-beta1 install \\\n #  --ucp-node $UCP_NODE \\\n #  --ucp-insecure-tls \\\n #  --dtr-external-url https://dlbpipddcdev01.westeurope.cloudapp.azure.com:443  \\\n #  --ucp-url https://ucpclus0-ucpctrl \\\n #  --ucp-username admin --ucp-password $PASSWORD \\\n # --replica-id $REPLICA_ID\"0\"\n  \n  \n  \n\n\n ###########################\n # WIP - TBC for BETA and/or GA (UCP 2.0.0 and DTR 2.10\n ###########################\n for ((loop=1; loop<=$COUNT; loop++))\n do\n \n echo $(date) \" - Start DTR installation on replica DTR node\"  \n #joinucp()\n # Install DTR Replica\ndocker run -it --rm \\\ndocker/${DTRIMAGETAG} join \\\n --ucp-url $UCP_URL \\\n --ucp-node $UCP_NODE_REP$loop$UCP_NODE_SUF \\\n   --ucp-insecure-tls \\\n --replica-id $REPLICA_ID$loop \\\n --existing-replica-id $REPLICA_ID\"0\" \\\n --ucp-username $USER --ucp-password $PASSWORD \n   \n if [ $? -eq 0 ]\n then\n  echo $(date) \" - Completed DTR installation on replica DTR node - $UCP_NODE_REP$loop$UCP_NODE_SUF\"\n else\n  echo $(date) \" -- DTR installation on replica DTR node - $UCP_NODE_REP$loop$UCP_NODE_SUF failed\"\n fi\n  \n sleep 20\n \n done\n \necho $(date) \" - Completed DTR installation on Master and all replica DTR nodes\"\n\n", "num_lines": 244}
{"repo_name": "azure-dockerdatacenter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# We need four params: (1) PASSWORD (2) MASTERFQDN (3) REPLICA_ID (4) MASTERPRIVATEIP (5) DTRNODE (6) SLEEP\n\necho $(date) \" - Starting Script\"\n\nUSER=admin\nPASSWORD=$1\nMASTERFQDN=$2\nUCP_URL=https://$4\nUCP_NODE=$(hostname)\nREPLICA_ID=$3\nMASTERPRIVATEIP=$4\nDTRNODE=$5\nSLEEP= $6\n\nif [ ! -z \"$6\" ]; then\nomsworkspaceid=$6\nomsworkspacekey=$7\nomslnxagentver=$8\necho  \"omsworkspaceid is\" $omsworkspaceid\nelse\necho \"All are respectively \" $1 $2 $3 $4 $5\nfi\nDOCKERDET=$9\nDOCKERVER=$( echo \"$9\" |cut -d\\: -f1 )\nDOCKERCOMPVER=$( echo \"$9\" |cut -d\\: -f2 )\nDOCKERMCVER=$( echo \"$9\" |cut -d\\: -f3 )\nTRUSTYREPO=$( echo \"$9\" |cut -d\\: -f4 )\nDOCKERDCVER=$( echo \"$9\" |cut -d\\: -f5 )\nUCPIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f1|sed 's/ucp\\-/ucp\\:/g')\nDTRIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f2|sed 's/dtr\\-/dtr\\:/g')\ndisable_ufw_iptables()\n{\nufw disable\n\niptables-save > $HOME/firewall.txt\n\niptables -X\n\niptables -t nat -F\n\niptables -t nat -X\n\niptables -t mangle -F\n\niptables -t mangle -X\n\niptables -P INPUT ACCEPT\n\niptables -P FORWARD ACCEPT\n\niptables -P OUTPUT ACCEPT\n\nip6tables-save > $HOME/firewall-6.txt\n\nip6tables -X\n\nip6tables -t mangle -F\n\nip6tables -t mangle -X\n\nip6tables -P INPUT ACCEPT\n\nip6tables -P FORWARD ACCEPT\n\nip6tables -P OUTPUT ACCEPT\n}\n\ndisable_ufw_iptables;\n\ninstallomsagent()\n{\n#wget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent_Ignite2016_v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nwget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent-201610-v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nchmod +x ./omsagent-${omslnxagentver}.universal.x64.sh\nmd5sum ./omsagent-${omslnxagentver}.universal.x64.sh\nsudo sh ./omsagent-${omslnxagentver}.universal.x64.sh --upgrade -w $omsworkspaceid -s $omsworkspacekey\n}\n\ninstrumentfluentd_docker()\n{\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i.bak -e '12d' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '12iEnvironment=\"DOCKER_OPTS=--log-driver=fluentd --log-opt fluentd-address=localhost:25225\"' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '13iExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS' docker.service\nservice docker restart\n}\ninstall_docker_tools()\n{\n\n# System Update and docker version update\nDEBIAN_FRONTEND=noninteractive apt-mark hold walinuxagent\nDEBIAN_FRONTEND=noninteractive apt-get -y update\napt-get install -y apt-transport-https ca-certificates\n#apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n#echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> /etc/apt/sources.list.d/docker.list\n#echo 'deb https://packages.docker.com/1.12/apt/repo ubuntu-trusty testing' >> /etc/apt/sources.list.d/docker.list\necho \"deb https://packages.docker.com/${DOCKERVER}/apt/repo ubuntu-trusty ${TRUSTYREPO}\" >> /etc/apt/sources.list.d/docker.list\napt-cache policy docker-engine\nDEBIAN_FRONTEND=noninteractive apt-get -y update\nDEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n#curl -L https://github.com/docker/compose/releases/download/1.9.0-rc4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n#curl -L https://github.com/docker/machine/releases/download/v0.8.2/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\ncurl -L https://github.com/docker/compose/releases/download/$DOCKERCOMPVER/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\ncurl -L https://github.com/docker/machine/releases/download/v$DOCKERMCVER/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-compose\nexport PATH=$PATH:/usr/local/bin/\ngroupadd docker\nusermod -aG docker ucpadmin\nservice docker restart\n}\ninstall_docker_tools;\nif [ ! -z \"$6\" ]; then\nsleep 45;\ninstrumentfluentd_docker;\nsleep 30;\ninstallomsagent;\nfi\n\n# Implement delay timer to stagger joining of Agent Nodes to cluster\necho $(date) \" - Loading docker install Tar\"\n#cd /opt/ucp && wget https://s3.amazonaws.com/packages.docker.com/caas/ucp-2.0.0-beta3_dtr-2.1.0-beta3.tar.gz\n#cd /opt/ucp && wget https://packages.docker.com/caas/ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ncd /opt/ucp && wget https://packages.docker.com/caas/$DOCKERDCVER.tar.gz\n#docker load < ucp-2.0.0-beta4_dtr-2.1.0-beta4.tar.gz\ndocker load < $DOCKERDCVER.tar.gz\n\n# Start installation of UCP with master Controller\n\necho $(date) \" - Loading complete.  Starting UCP Install\"\n\ninstallbundle ()\n{\n\necho $(date) \"Sleeping for $SLEEP\"\nsleep $SLEEP\necho $(date) \" - Staring Swarm Join as worker UCP Controller\"\napt-get -y update && apt-get install -y curl jq\n# Create an environment variable with the user security token\nAUTHTOKEN=$(curl -sk -d '{\"username\":\"admin\",\"password\":\"'\"$PASSWORD\"'\"}' https://$MASTERPRIVATEIP/auth/login | jq -r .auth_token)\necho \"$AUTHTOKEN\"\n# Download the client certificate bundle\ncurl -k -H \"Authorization: Bearer ${AUTHTOKEN}\" https://$MASTERPRIVATEIP/api/clientbundle -o bundle.zip\nunzip -o bundle.zip && chmod +x env.sh && source env.sh\n}\njoinucp() {\ninstallbundle;\n#docker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'>swarmjoin.sh\ndocker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'> /usr/local/bin/docker-workerswarmjoin\nunset DOCKER_TLS_VERIFY\nunset DOCKER_CERT_PATH\nunset DOCKER_HOST\n#chmod 755 swarmjoin.sh\nchmod +x /usr/local/bin/docker-workerswarmjoin\nexport PATH=$PATH:/usr/local/bin/\ndocker-workerswarmjoin\n#source swarmjoin.sh\n}\ninstalldtr() {\ninstallbundle;\n## Insecure TLS as self signed will fail -- Failed to get bootstrap client: Failed to get UCP CA: Get https://blablah/ca: x509: certificate signed by unknown authority\ndocker run --rm -i \\\n  docker/${DTRIMAGETAG} install \\\n  --ucp-node $UCP_NODE \\\n  --ucp-insecure-tls \\\n  --dtr-external-url $DTR_PUBLIC_URL  \\\n  --ucp-url https://$MASTERFQDN \\\n  --ucp-username admin --ucp-password $PASSWORD\n  }\nsleep 45;\njoinucp;\n#echo $(date) \"Sleeping for 200\"\n#sleep 200;\n# Install DTR\n#installdtr;\n\nif [ $? -eq 0 ]\nthen\n echo $(date) \" - UCP installed and started on the agent node to be used for DTR replica\"\nelse\n echo $(date) \" -- UCP installation failed on DTR node\"\nfi\n", "num_lines": 184}
{"repo_name": "azure-dockerdatacenter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# We need four params: (1) PASSWORD (2) MASTERFQDN (3) MASTERPRIVATEIP (4) SLEEP\n\necho $(date) \" - Starting Script\"\n\nPASSWORD=$1\nMASTERFQDN=$2\nMASTERPRIVATEIP=$3\nSLEEP=$4\nDOCKERDET=$8\nDOCKERVER=$( echo \"$8\" |cut -d\\: -f1 )\nDOCKERCOMPVER=$( echo \"$8\" |cut -d\\: -f2 )\nDOCKERMCVER=$( echo \"$8\" |cut -d\\: -f3 )\nTRUSTYREPO=$( echo \"$8\" |cut -d\\: -f4 )\nDOCKERDCVER=$( echo \"$8\" |cut -d\\: -f5 )\nUCPIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f1|sed 's/ucp\\-/ucp\\:/g')\nDTRIMAGETAG=$( echo \"$DOCKERDCVER\" |cut -d\\_ -f2|sed 's/dtr\\-/dtr\\:/g')\n\nif [ ! -z \"$5\" ]; then\nomsworkspaceid=$5\nomsworkspacekey=$6\nomslnxagentver=$7\necho  \"omsworkspaceid is\" $omsworkspaceid\nelse\necho \"All are respectively \" $1 $2 $3 $4\nfi\n\ndisable_ufw_iptables()\n{\nufw disable\n\niptables-save > $HOME/firewall.txt\n\niptables -X\n\niptables -t nat -F\n\niptables -t nat -X\n\niptables -t mangle -F\n\niptables -t mangle -X\n\niptables -P INPUT ACCEPT\n\niptables -P FORWARD ACCEPT\n\niptables -P OUTPUT ACCEPT\n\nip6tables-save > $HOME/firewall-6.txt\n\nip6tables -X\n\nip6tables -t mangle -F\n\nip6tables -t mangle -X\n\nip6tables -P INPUT ACCEPT\n\nip6tables -P FORWARD ACCEPT\n\nip6tables -P OUTPUT ACCEPT\n}\n\ndisable_ufw_iptables;\n\ninstallomsagent()\n{\n#wget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent_Ignite2016_v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nwget https://github.com/Microsoft/OMS-Agent-for-Linux/releases/download/OMSAgent-201610-v$omslnxagentver/omsagent-${omslnxagentver}.universal.x64.sh\nchmod +x ./omsagent-${omslnxagentver}.universal.x64.sh\nmd5sum ./omsagent-${omslnxagentver}.universal.x64.sh\nsudo sh ./omsagent-${omslnxagentver}.universal.x64.sh --upgrade -w $omsworkspaceid -s $omsworkspacekey\n}\n\ninstrumentfluentd_docker()\n{\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i.bak -e '12d' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '12iEnvironment=\"DOCKER_OPTS=--log-driver=fluentd --log-opt fluentd-address=localhost:25225\"' docker.service\ncd /etc/systemd/system/multi-user.target.wants/ && sed -i '13iExecStart=/usr/bin/dockerd -H fd:// $DOCKER_OPTS' docker.service\nservice docker restart\n}\ninstall_docker_tools()\n{\n# System Update and docker version update\nDEBIAN_FRONTEND=noninteractive apt-mark hold walinuxagent\nDEBIAN_FRONTEND=noninteractive apt-get -y update\napt-get install -y apt-transport-https ca-certificates\n#apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n#echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' >> /etc/apt/sources.list.d/docker.list\ncurl -s 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | apt-key add --import\n#echo 'deb https://packages.docker.com/1.12/apt/repo ubuntu-trusty testing' >> /etc/apt/sources.list.d/docker.list\necho \"deb https://packages.docker.com/${DOCKERVER}/apt/repo ubuntu-trusty ${TRUSTYREPO}\" >> /etc/apt/sources.list.d/docker.list\napt-cache policy docker-engine\nDEBIAN_FRONTEND=noninteractive apt-get -y update\nDEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n#curl -L https://github.com/docker/compose/releases/download/1.9.0-rc4/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n#curl -L https://github.com/docker/machine/releases/download/v0.8.2/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\ncurl -L https://github.com/docker/compose/releases/download/$DOCKERCOMPVER/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\ncurl -L https://github.com/docker/machine/releases/download/v$DOCKERMCVER/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machin\nchmod +x /usr/local/bin/docker-machine\nchmod +x /usr/local/bin/docker-compose\nexport PATH=$PATH:/usr/local/bin/\ngroupadd docker\nusermod -aG docker ucpadmin\nservice docker restart\n}\ninstall_docker_tools;\nif [ ! -z \"$5\" ]; then\nsleep 45;\ninstrumentfluentd_docker;\nsleep 30;\ninstallomsagent;\nfi\n\n# Implement delay timer to stagger joining of Agent Nodes to cluster\n\necho $(date) \"Sleeping for $SLEEP\"\nsleep $SLEEP\n\necho $(date) \" - Staring Swarm Join as worker UCP Controller\"\napt-get -y update && apt-get install -y curl jq\n# Create an environment variable with the user security token\nAUTHTOKEN=$(curl -sk -d '{\"username\":\"admin\",\"password\":\"'\"$PASSWORD\"'\"}' https://$MASTERPRIVATEIP/auth/login | jq -r .auth_token)\necho \"$AUTHTOKEN\"\n# Download the client certificate bundle\ncurl -k -H \"Authorization: Bearer ${AUTHTOKEN}\" https://$MASTERPRIVATEIP/api/clientbundle -o bundle.zip\nunzip bundle.zip && chmod +x env.sh && source env.sh\n#docker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'>swarmjoin.sh\ndocker swarm join-token worker|sed '1d'|sed '1d'|sed '$ d'> /usr/local/bin/docker-workerswarmjoin\nunset DOCKER_TLS_VERIFY\nunset DOCKER_CERT_PATH\nunset DOCKER_HOST\n#chmod 755 swarmjoin.sh\nchmod +x /usr/local/bin/docker-workerswarmjoin\nexport PATH=$PATH:/usr/local/bin/\ndocker-workerswarmjoin\n#source swarmjoin.sh\n", "num_lines": 140}
{"repo_name": "azure-docs-powershell-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "apt-get update\napt-get install -y nginx\necho $(hostname) | sudo tee /var/www/html/index.html\nsudo mkdir -p /var/www/html/images\necho \"Images: \" $(hostname) | sudo tee /var/www/html/images/test.html\nsudo mkdir -p /var/www/html/video\necho \"Video: \" $(hostname) | sudo tee /var/www/html/video/test.html\n", "num_lines": 8}
{"repo_name": "azure-event-hubs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#Step 1- first step is to get the bearer token using client credential flow. We should set the resource to be URL encoded string for eventhubs.azure.net\nresponse=$(curl -X POST -d  'grant_type=client_credentials&client_id=<Application_ID>&client_secret=<Application_Secret>&resource=https%3A%2F%2Feventhubs.azure.net' https://login.microsoftonline.com/<Tenant_Id>/oauth2/token)\n\n#formatting token to drop \"\" quotes and suffixing bearer for final use\ntoken=\"Bearer `echo $response | jq .\"access_token\" | tr -d '\"'`\"\n\n#Step 2-Making a REST call to dataplane endpoint to add schema to schema groups\ncurl -X PUT -d '{\"namespace\": \"com.azure.schemaregistry.samples\",\"type\": \"record\",\"name\": \"Order\",\"fields\": [{\"name\": \"id\",\"type\": \"string\"},{\"name\": \"amount\",\"type\": \"double\"}]}'  -H \"Content-Type:application/json\" -H \"Authorization:$token\" -H \"Serialization-Type:Avro\" \\\n'https://<Namespace_Name>.servicebus.windows.net/$schemagroups/<SchemaGroup_Name>/schemas/<Schema_Name>?api-version=2020-09-01-preview'", "num_lines": 9}
{"repo_name": "azure-event-hubs-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n\nset -e\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/../..\" && pwd)\nlog_dir=$build_root\nrun_e2e_tests=OFF\nrun_longhaul_tests=OFF\nrun_unittests=OFF\n\nusage ()\n{\n    echo \"build.sh [options]\"\n    echo \"options\"\n    echo \" -cl, --compileoption <value>  specify a compile option to be passed to gcc\"\n    echo \"   Example: -cl -O1 -cl ...\"\n    echo \" --run-e2e-tests               runs the end-to-end tests (e2e tests are not run by default)\"\n    echo \" --run-unittests               run the unit tests\"\n    exit 1\n}\n\nprocess_args ()\n{\n    save_next_arg=0\n    extracloptions=\" \"\n\n    for arg in $*\n    do      \n      if [ $save_next_arg == 1 ]\n      then\n        # save arg to pass to gcc\n        extracloptions=\"$arg $extracloptions\"\n        save_next_arg=0\n      else\n          case \"$arg\" in\n              \"-cl\" | \"--compileoption\" ) save_next_arg=1;;\n              \"--run-e2e-tests\" ) run_e2e_tests=ON;;\n              \"--run-unittests\" ) run_unittests=ON;;\n              * ) usage;;\n          esac\n      fi\n    done\n}\n\nprocess_args $*\n\nrm -r -f ~/cmake\nmkdir ~/cmake\npushd ~/cmake\ncmake -DcompileOption_C:STRING=\"$extracloptions\" -Drun_e2e_tests:BOOL=$run_e2e_tests -Drun_longhaul_tests=$run_longhaul_tests -Drun_unittests:BOOL=$run_unittests $build_root\nmake --jobs=$(nproc)\nctest -C \"Debug\" -V\npopd", "num_lines": 56}
{"repo_name": "azure-event-hubs-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#This script updates a fresh Ubuntu installation with all the dependent\n# components necessary to use the IoT Client SDK for C.\n\n#Make sure temporary Git credentials file is ALWAYS deleted\ntrap 'creds_delete' EXIT\n\nrepo_name_from_uri()\n{\n    echo \"$1\" | sed -e 's|/$||' -e 's|:*/*\\.git$||' -e 's|.*[/:]||g'\n}\n\nscriptdir=$(cd \"$(dirname \"$0\")\" && pwd)\ndeps=\"curl libcurl4-openssl-dev libssl-dev uuid-dev uuid g++ make cmake git\"\nrepo=\"https://github.com/Azure/azure-event-hubs-c.git\"\nrepo_name=$(repo_name_from_uri $repo)\ncred=~/cred.$$\nuser=\npass=\n\npush_dir () { pushd $1 > /dev/null; }\npop_dir () { popd $1 > /dev/null; }\n\nrepo_exists ()\n{\n    push_dir \"$scriptdir\"\n    [ \"$(git rev-parse --is-inside-work-tree)\" == \"true\" ] || return 1\n    origin=$(git config remote.origin.url) || return 1\n    actual_name=$(repo_name_from_uri $origin)\n    [ \"${repo_name,,}\" == \"${actual_name,,}\" ] || return 1\n    pop_dir\n}\n\ncreds_read ()\n{\n    echo \"Enter credentials for $repo:\"\n    read -p \"username: \" user\n    read -p \"password (or access token, for 2FA): \" -s pass\n    echo -e \"\\n\"\n}\n\ncreds_create ()\n{\n    protocol=$(expr \"$repo\" : '\\(.*\\):\\/\\/.*')\n    host=$(expr \"$repo\" : '.*:\\/\\/\\([^/]*\\)/.*')\n\n    #NOTE: tabs in the heredoc are intentional; don't replace them with spaces\n    git credential-store --file $cred store <<-end-credentials\n\tprotocol=$protocol\n\thost=$host\n\tusername=$user\n\tpassword=$pass\n\t\n\tend-credentials\n}\n\ncreds_delete ()\n{\n    rm -f $cred\n}\n\ndeps_install ()\n{\n    sudo apt-get update\n    sudo apt-get install -y $deps\n}\n\nclone_source ()\n{\n    git -c credential.helper=\"store --file $cred\" -c core.askpass=true clone $repo\n}\n\nif ! repo_exists\nthen\n    creds_read #read Git credentials up front, so script can be unattended-ish\nfi\n\ndeps_install\n\nif repo_exists\nthen\n    echo \"Repo $repo_name already cloned\"\n    push_dir \"$(git rev-parse --show-toplevel)\"\nelse\n    creds_create\n    clone_source || exit 1\n    push_dir \"$repo_name\"\n    creds_delete\nfi\n\npop_dir\n", "num_lines": 93}
{"repo_name": "azure-event-hubs-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests \"$@\" #-x\n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 12}
{"repo_name": "azure-event-hubs-for-kafka", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Downloading/installing necessary dependencies\"\nsudo apt-get install git openssl libssl-dev build-essential python-pip python-dev librdkafka-dev\ngit clone https://github.com/edenhill/librdkafka\n\necho \"Setting up librdkafka\"\ncd librdkafka\n./configure\nmake\nsudo make install\ncd ..\n\necho \"Setting up Confluent's Python Kafka library\"\nsudo pip install confluent-kafka\necho \"Try running the samples now!\"\n", "num_lines": 16}
{"repo_name": "azure-event-hubs-reactive", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ \"$1\" == \"PR\" -o \"$1\" == \"pr\" ]; then\n  echo \"Skipping tests requiring encrypted secrets.\"\n  export TRAVIS_PULL_REQUEST=\"true\"\nfi\n\ntravis lint -x && \\\nsbt +clean     && \\\nsbt +compile   && \\\nsbt +package   && \\\nsbt +test\n\nrm -f *.crt\n", "num_lines": 13}
{"repo_name": "azure-event-hubs-reactive", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo \"Select demo to run:\"\necho\necho \" [1] DisplayMessages.Main\"\necho \" [2] SendMessageToDevice.Main\"\necho\nread -p \"Enter number: \" -r opt\n\ncd samples-java\n\nif [ \"$opt\" = \"1\" ]; then\n  mvn clean compile exec:java -Dexec.mainClass=\"DisplayMessages.Main\"\nfi\n\nif [ \"$opt\" = \"2\" ]; then\n  mvn clean compile exec:java -Dexec.mainClass=\"SendMessageToDevice.Main\"\nfi\n", "num_lines": 17}
{"repo_name": "azure-event-hubs-reactive", "repo_creator": "Azure", "programming_language": "Shell", "code": "sbt samplesScala/run\n", "num_lines": 2}
{"repo_name": "azure-event-hubs-reactive", "repo_creator": "Azure", "programming_language": "Shell", "code": "#  Populate the following environment variables, and execute this file before\n#  running the samples.\n#\n#  For more information about where to find these values, more information here:\n#\n#  * https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-create\n#\n#\n#  Example:\n#\n#  export EVENTHUB_NAME=\"my-event-hub\"\n#\n#  export EVENTHUB_ENDPOINT=\"sb://your-namespace.servicebus.windows.net/\"\n#\n#  export EVENTHUB_PARTITIONS=4\n#\n#  export EVENTHUB_ACCESS_POLICY=\"service\"\n#\n#  export EVENTHUB_ACCESS_KEY=\"...\"\n#\n#  export STREAMING_CHECKPOINT_ACCOUNT = 'myazurestorage'\n#\n#  export STREAMING_CHECKPOINT_KEY = \"...\"\n#\n\nexport EVENTHUB_NAME=\"\"\n\nexport EVENTHUB_ENDPOINT=\"\"\n\nexport EVENTHUB_PARTITIONS=\"\"\n\nexport EVENTHUB_ACCESS_POLICY=\"\"\n\nexport EVENTHUB_ACCESS_KEY=\"\"\n\n# When using checkpoints stored in Azure Blob, this is the Azure Storage Account name\nexport STREAMING_CHECKPOINT_ACCOUNT=\"\"\n\n# When using checkpoints stored in Azure Blob, this is the Azure Storage Account secret key\nexport STREAMING_CHECKPOINT_KEY=\"\"\n", "num_lines": 41}
{"repo_name": "azure-event-hubs-spark", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\nmvn clean package -q\n", "num_lines": 3}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nGITBRANCH=`git rev-parse --abbrev-ref HEAD`\n#We intend to only run gas on release branches.\nif [ \"master\" != $GITBRANCH ]; then\n    exit 0\nfi\nREALEXITSTATUS=0\ngo get -u github.com/HewlettPackard/gas\ngas -skip=*/arm/*/models.go -skip=*/management/examples/*.go -skip=*vendor* -skip=*/Gododir/* ./... | tee /dev/stderr\nREALEXITSTATUS=$(($REALEXITSTATUS+$?))\ngas -exclude=G101 ./arm/... ./management/examples/... | tee /dev/stderr\nREALEXITSTATUS=$(($REALEXITSTATUS+$?))\ngas -exclude=G204 ./Gododir/... | tee /dev/stderr\nREALEXITSTATUS=$(($REALEXITSTATUS+$?))\nexit $REALEXITSTATUS", "num_lines": 15}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The plan9 package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nplan9_386)\n\tmkerrors=\n\tmksyscall=\"./mksyscall.pl -l32 -plan9\"\n\tmksysnum=\"./mksysnum_plan9.sh /n/sources/plan9/sys/src/libc/9syscall/sys.h\"\n\tmktypes=\"XXX\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\tplan9)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos syscall_$GOOSARCH.go |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go |gofmt >ztypes_$GOOSARCH.go\"; fi\n) | $run\n", "num_lines": 139}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nCC=${CC:-gcc}\n\nuname=$(uname)\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n'\n\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package plan9\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFP][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 247}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\nCOMMAND=\"mksysnum_plan9.sh $@\"\n\ncat <<EOF\n// $COMMAND\n// MACHINE GENERATED BY THE ABOVE COMMAND; DO NOT EDIT\n\npackage plan9\n\nconst(\nEOF\n\nSP='[ \t]' # space or tab\nsed \"s/^#define${SP}\\\\([A-Z0-9_][A-Z0-9_]*\\\\)${SP}${SP}*\\\\([0-9][0-9]*\\\\)/SYS_\\\\1=\\\\2/g\" \\\n\t< $1 | grep -v SYS__\n\ncat <<EOF\n)\nEOF\n", "num_lines": 24}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# The unix package provides access to the raw system call\n# interface of the underlying operating system.  Porting Go to\n# a new architecture/operating system combination requires\n# some manual effort, though there are tools that automate\n# much of the process.  The auto-generated files have names\n# beginning with z.\n#\n# This script runs or (given -n) prints suggested commands to generate z files\n# for the current system.  Running those commands is not automatic.\n# This script is documentation more than anything else.\n#\n# * asm_${GOOS}_${GOARCH}.s\n#\n# This hand-written assembly file implements system call dispatch.\n# There are three entry points:\n#\n# \tfunc Syscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n# \tfunc Syscall6(trap, a1, a2, a3, a4, a5, a6 uintptr) (r1, r2, err uintptr);\n# \tfunc RawSyscall(trap, a1, a2, a3 uintptr) (r1, r2, err uintptr);\n#\n# The first and second are the standard ones; they differ only in\n# how many arguments can be passed to the kernel.\n# The third is for low-level use by the ForkExec wrapper;\n# unlike the first two, it does not call into the scheduler to\n# let it know that a system call is running.\n#\n# * syscall_${GOOS}.go\n#\n# This hand-written Go file implements system calls that need\n# special handling and lists \"//sys\" comments giving prototypes\n# for ones that can be auto-generated.  Mksyscall reads those\n# comments to generate the stubs.\n#\n# * syscall_${GOOS}_${GOARCH}.go\n#\n# Same as syscall_${GOOS}.go except that it contains code specific\n# to ${GOOS} on one particular architecture.\n#\n# * types_${GOOS}.c\n#\n# This hand-written C file includes standard C headers and then\n# creates typedef or enum names beginning with a dollar sign\n# (use of $ in variable names is a gcc extension).  The hardest\n# part about preparing this file is figuring out which headers to\n# include and which symbols need to be #defined to get the\n# actual data structures that pass through to the kernel system calls.\n# Some C libraries present alternate versions for binary compatibility\n# and translate them on the way in and out of system calls, but\n# there is almost always a #define that can get the real ones.\n# See types_darwin.c and types_linux.c for examples.\n#\n# * zerror_${GOOS}_${GOARCH}.go\n#\n# This machine-generated file defines the system's error numbers,\n# error strings, and signal numbers.  The generator is \"mkerrors.sh\".\n# Usually no arguments are needed, but mkerrors.sh will pass its\n# arguments on to godefs.\n#\n# * zsyscall_${GOOS}_${GOARCH}.go\n#\n# Generated by mksyscall.pl; see syscall_${GOOS}.go above.\n#\n# * zsysnum_${GOOS}_${GOARCH}.go\n#\n# Generated by mksysnum_${GOOS}.\n#\n# * ztypes_${GOOS}_${GOARCH}.go\n#\n# Generated by godefs; see types_${GOOS}.c above.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"./mksyscall.pl\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nrun=\"sh\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksysnum=\"./mksysnum_darwin.pl /usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_darwin.pl $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -dragonfly\"\n\tmksysnum=\"curl -s 'http://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master' | ./mksysnum_dragonfly.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://svn.freebsd.org/base/stable/10/sys/kern/syscalls.master' | ./mksysnum_freebsd.pl\"\n\t# Let the type of C char be singed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32\"\n\tmksysnum=\"./mksysnum_linux.pl /usr/include/asm/unistd_32.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_amd64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd_64.h /usr/include/x86_64-linux-gnu/asm/unistd_64.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"./mksyscall.pl -l32 -arm\"\n\tmksysnum=\"curl -s 'http://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/plain/arch/arm/include/uapi/asm/unistd.h' | ./mksysnum_linux.pl -\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_arm64)\n\tunistd_h=$(ls -1 /usr/include/asm/unistd.h /usr/include/asm-generic/unistd.h 2>/dev/null | head -1)\n\tif [ \"$unistd_h\" = \"\" ]; then\n\t\techo >&2 cannot find unistd_64.h\n\t\texit 1\n\tfi\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\t# Let the type of C char be singed for making the bare syscall\n\t# API consistent across over platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nlinux_ppc64)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nlinux_ppc64le)\n\tGOOSARCH_in=syscall_linux_ppc64x.go\n\tunistd_h=/usr/include/powerpc64le-linux-gnu/asm/unistd.h\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"./mksysnum_linux.pl $unistd_h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -netbsd\"\n\tmksysnum=\"curl -s 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_netbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"./mksyscall.pl -l32 -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"./mksyscall.pl -openbsd\"\n\tmksysctl=\"./mksysctl_openbsd.pl\"\n\tzsysctl=\"zsysctl_openbsd.go\"\n\tmksysnum=\"curl -s 'http://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master' | ./mksysnum_openbsd.pl\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"./mksyscall_solaris.pl\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then echo \"$mksyscall $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\"; fi\n\t\t;;\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then\n\t\techo \"echo // +build $GOARCH,$GOOS > ztypes_$GOOSARCH.go\";\n\t\techo \"$mktypes types_$GOOS.go | gofmt >>ztypes_$GOOSARCH.go\";\n\tfi\n) | $run\n", "num_lines": 275}
{"repo_name": "azure-extensions-cli", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\nCC=${CC:-cc}\n\nif [[ \"$GOOS\" -eq \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/socket.h>\n#include <linux/if.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/filter.h>\n#include <linux/netlink.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <net/route.h>\n#include <asm/termbits.h>\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|EVFILT|NOTE|EV|SHUT|PROT|MAP|PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 ~ /^(MS|MNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|NOFILE|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^CLOCK_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nint errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\techo -E \"\n};\n\nint signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t'$i,\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\nintcmp(const void *a, const void *b)\n{\n\treturn *(int*)a - *(int*)b;\n}\n\nint\nmain(void)\n{\n\tint i, j, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errors = [...]string {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], intcmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i];\n\t\tif(i > 0 && errors[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\t\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signals = [...]string {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], intcmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i];\n\t\tif(i > 0 && signals[i-1] == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t%d: \\\"%s\\\",\\n\", e, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 477}
{"repo_name": "azure-functions-core-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ndotnet build Azure.Functions.Cli.sln\ndotnet publish src/Azure.Functions.Cli/Azure.Functions.Cli.csproj --runtime linux-x64 --output /tmp/cli\n# FUNC_PATH=/tmp/cli/func dotnet test test/Azure.Functions.Cli.Tests/Azure.Functions.Cli.Tests.csproj\n", "num_lines": 5}
{"repo_name": "azure-functions-core-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) .NET Foundation and contributors. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# Original file from https://github.com/dotnet/cli/blob/80d542b8f4eff847a0f72dc8f2c2a29851272778/scripts/obtain/dotnet-install.sh\n\n# Stop script on NZEC\nset -e\n# Stop script if unbound variable found (use ${var:-} if intentional)\nset -u\n# By default cmd1 | cmd2 returns exit code of cmd2 regardless of cmd1 success\n# This is causing it to fail\nset -o pipefail\n\n# Use in the the functions: eval $invocation\ninvocation='say_verbose \"Calling: ${yellow:-}${FUNCNAME[0]} ${green:-}$*${normal:-}\"'\n\n# standard output may be used as a return value in the functions\n# we need a way to write text on the screen in the functions so that\n# it won't interfere with the return value.\n# Exposing stream 3 as a pipe to standard output of the script itself\nexec 3>&1\n\n# Setup some colors to use. These need to work in fairly limited shells, like the Ubuntu Docker container where there are only 8 colors.\n# See if stdout is a terminal\nif [ -t 1 ] && command -v tput > /dev/null; then\n    # see if it supports colors\n    ncolors=$(tput colors)\n    if [ -n \"$ncolors\" ] && [ $ncolors -ge 8 ]; then\n        bold=\"$(tput bold       || echo)\"\n        normal=\"$(tput sgr0     || echo)\"\n        black=\"$(tput setaf 0   || echo)\"\n        red=\"$(tput setaf 1     || echo)\"\n        green=\"$(tput setaf 2   || echo)\"\n        yellow=\"$(tput setaf 3  || echo)\"\n        blue=\"$(tput setaf 4    || echo)\"\n        magenta=\"$(tput setaf 5 || echo)\"\n        cyan=\"$(tput setaf 6    || echo)\"\n        white=\"$(tput setaf 7   || echo)\"\n    fi\nfi\n\nsay_warning() {\n    printf \"%b\\n\" \"${yellow:-}dotnet_install: Warning: $1${normal:-}\"\n}\n\nsay_err() {\n    printf \"%b\\n\" \"${red:-}dotnet_install: Error: $1${normal:-}\" >&2\n}\n\nsay() {\n    # using stream 3 (defined in the beginning) to not interfere with stdout of functions\n    # which may be used as return value\n    printf \"%b\\n\" \"${cyan:-}dotnet-install:${normal:-} $1\" >&3\n}\n\nsay_verbose() {\n    if [ \"$verbose\" = true ]; then\n        say \"$1\"\n    fi\n}\n\n# This platform list is finite - if the SDK/Runtime has supported Linux distribution-specific assets,\n#   then and only then should the Linux distribution appear in this list.\n# Adding a Linux distribution to this list does not imply distribution-specific support.\nget_legacy_os_name_from_platform() {\n    eval $invocation\n\n    platform=\"$1\"\n    case \"$platform\" in\n        \"centos.7\")\n            echo \"centos\"\n            return 0\n            ;;\n        \"debian.8\")\n            echo \"debian\"\n            return 0\n            ;;\n        \"fedora.23\")\n            echo \"fedora.23\"\n            return 0\n            ;;\n        \"fedora.27\")\n            echo \"fedora.27\"\n            return 0\n            ;;\n        \"fedora.24\")\n            echo \"fedora.24\"\n            return 0\n            ;;\n        \"opensuse.13.2\")\n            echo \"opensuse.13.2\"\n            return 0\n            ;;\n        \"opensuse.42.1\")\n            echo \"opensuse.42.1\"\n            return 0\n            ;;\n        \"opensuse.42.3\")\n            echo \"opensuse.42.3\"\n            return 0\n            ;;\n        \"rhel.7\"*)\n            echo \"rhel\"\n            return 0\n            ;;\n        \"ubuntu.14.04\")\n            echo \"ubuntu\"\n            return 0\n            ;;\n        \"ubuntu.16.04\")\n            echo \"ubuntu.16.04\"\n            return 0\n            ;;\n        \"ubuntu.16.10\")\n            echo \"ubuntu.16.10\"\n            return 0\n            ;;\n        \"ubuntu.18.04\")\n            echo \"ubuntu.18.04\"\n            return 0\n            ;;\n        \"alpine.3.4.3\")\n            echo \"alpine\"\n            return 0\n            ;;\n    esac\n    return 1\n}\n\nget_linux_platform_name() {\n    eval $invocation\n\n    if [ -n \"$runtime_id\" ]; then\n        echo \"${runtime_id%-*}\"\n        return 0\n    else\n        if [ -e /etc/os-release ]; then\n            . /etc/os-release\n            echo \"$ID.$VERSION_ID\"\n            return 0\n        elif [ -e /etc/redhat-release ]; then\n            local redhatRelease=$(</etc/redhat-release)\n            if [[ $redhatRelease == \"CentOS release 6.\"* || $redhatRelease == \"Red Hat Enterprise Linux Server release 6.\"* ]]; then\n                echo \"rhel.6\"\n                return 0\n            fi\n        fi\n    fi\n\n    say_verbose \"Linux specific platform name and version could not be detected: UName = $uname\"\n    return 1\n}\n\nget_current_os_name() {\n    eval $invocation\n\n    local uname=$(uname)\n    if [ \"$uname\" = \"Darwin\" ]; then\n        echo \"osx\"\n        return 0\n    elif [ \"$uname\" = \"Linux\" ]; then\n        local linux_platform_name\n        linux_platform_name=\"$(get_linux_platform_name)\" || { echo \"linux\" && return 0 ; }\n\n        if [[ $linux_platform_name == \"rhel.6\" ]]; then\n            echo $linux_platform_name\n            return 0\n        elif [[ $linux_platform_name == alpine* ]]; then\n            echo \"linux-musl\"\n            return 0\n        else\n            echo \"linux\"\n            return 0\n        fi\n    fi\n\n    say_err \"OS name could not be detected: UName = $uname\"\n    return 1\n}\n\nget_legacy_os_name() {\n    eval $invocation\n\n    local uname=$(uname)\n    if [ \"$uname\" = \"Darwin\" ]; then\n        echo \"osx\"\n        return 0\n    elif [ -n \"$runtime_id\" ]; then\n        echo $(get_legacy_os_name_from_platform \"${runtime_id%-*}\" || echo \"${runtime_id%-*}\")\n        return 0\n    else\n        if [ -e /etc/os-release ]; then\n            . /etc/os-release\n            os=$(get_legacy_os_name_from_platform \"$ID.$VERSION_ID\" || echo \"\")\n            if [ -n \"$os\" ]; then\n                echo \"$os\"\n                return 0\n            fi\n        fi\n    fi\n\n    say_verbose \"Distribution specific OS name and version could not be detected: UName = $uname\"\n    return 1\n}\n\nmachine_has() {\n    eval $invocation\n\n    hash \"$1\" > /dev/null 2>&1\n    return $?\n}\n\n\ncheck_min_reqs() {\n    local hasMinimum=false\n    if machine_has \"curl\"; then\n        hasMinimum=true\n    elif machine_has \"wget\"; then\n        hasMinimum=true\n    fi\n\n    if [ \"$hasMinimum\" = \"false\" ]; then\n        say_err \"curl (recommended) or wget are required to download dotnet. Install missing prerequisite to proceed.\"\n        return 1\n    fi\n    return 0\n}\n\ncheck_pre_reqs() {\n    eval $invocation\n\n    if [ \"${DOTNET_INSTALL_SKIP_PREREQS:-}\" = \"1\" ]; then\n        return 0\n    fi\n\n    if [ \"$(uname)\" = \"Linux\" ]; then\n        if [ ! -x \"$(command -v ldconfig)\" ]; then\n            echo \"ldconfig is not in PATH, trying /sbin/ldconfig.\"\n            LDCONFIG_COMMAND=\"/sbin/ldconfig\"\n        else\n            LDCONFIG_COMMAND=\"ldconfig\"\n        fi\n\n        local librarypath=${LD_LIBRARY_PATH:-}\n        LDCONFIG_COMMAND=\"$LDCONFIG_COMMAND -NXv ${librarypath//:/ }\"\n\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libunwind)\" ] && say_warning \"Unable to locate libunwind. Probable prerequisite missing; please install libunwind.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libssl)\" ] && say_warning \"Unable to locate libssl. Probable prerequisite missing; please install libssl.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libicu)\" ] && say_warning \"Unable to locate libicu. Probable prerequisite missing; please install libicu.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep -F libcurl.so)\" ] && say_warning \"Unable to locate libcurl. Probable prerequisite missing; please install libcurl.\"\n    fi\n\n    return 0\n}\n\n# args:\n# input - $1\nto_lowercase() {\n    #eval $invocation\n\n    echo \"$1\" | tr '[:upper:]' '[:lower:]'\n    return 0\n}\n\n# args:\n# input - $1\nremove_trailing_slash() {\n    #eval $invocation\n\n    local input=\"${1:-}\"\n    echo \"${input%/}\"\n    return 0\n}\n\n# args:\n# input - $1\nremove_beginning_slash() {\n    #eval $invocation\n\n    local input=\"${1:-}\"\n    echo \"${input#/}\"\n    return 0\n}\n\n# args:\n# root_path - $1\n# child_path - $2 - this parameter can be empty\ncombine_paths() {\n    eval $invocation\n\n    # TODO: Consider making it work with any number of paths. For now:\n    if [ ! -z \"${3:-}\" ]; then\n        say_err \"combine_paths: Function takes two parameters.\"\n        return 1\n    fi\n\n    local root_path=\"$(remove_trailing_slash \"$1\")\"\n    local child_path=\"$(remove_beginning_slash \"${2:-}\")\"\n    say_verbose \"combine_paths: root_path=$root_path\"\n    say_verbose \"combine_paths: child_path=$child_path\"\n    echo \"$root_path/$child_path\"\n    return 0\n}\n\nget_machine_architecture() {\n    eval $invocation\n\n    if command -v uname > /dev/null; then\n        CPUName=$(uname -m)\n        case $CPUName in\n        armv7l)\n            echo \"arm\"\n            return 0\n            ;;\n        aarch64)\n            echo \"arm64\"\n            return 0\n            ;;\n        esac\n    fi\n\n    # Always default to 'x64'\n    echo \"x64\"\n    return 0\n}\n\n# args:\n# architecture - $1\nget_normalized_architecture_from_architecture() {\n    eval $invocation\n\n    local architecture=\"$(to_lowercase \"$1\")\"\n    case \"$architecture\" in\n        \\<auto\\>)\n            echo \"$(get_normalized_architecture_from_architecture \"$(get_machine_architecture)\")\"\n            return 0\n            ;;\n        amd64|x64)\n            echo \"x64\"\n            return 0\n            ;;\n        arm)\n            echo \"arm\"\n            return 0\n            ;;\n        arm64)\n            echo \"arm64\"\n            return 0\n            ;;\n    esac\n\n    say_err \"Architecture \\`$architecture\\` not supported. If you think this is a bug, please report it at https://github.com/dotnet/cli/issues\"\n    return 1\n}\n\n# version_info is a conceptual two line string representing commit hash and 4-part version\n# format:\n# Line 1: # commit_hash\n# Line 2: # 4-part version\n\n# args:\n# version_text - stdin\nget_version_from_version_info() {\n    eval $invocation\n\n    cat | tail -n 1 | sed 's/\\r$//'\n    return 0\n}\n\n# args:\n# version_text - stdin\nget_commit_hash_from_version_info() {\n    eval $invocation\n\n    cat | head -n 1 | sed 's/\\r$//'\n    return 0\n}\n\n# args:\n# install_root - $1\n# relative_path_to_package - $2\n# specific_version - $3\nis_dotnet_package_installed() {\n    eval $invocation\n\n    local install_root=\"$1\"\n    local relative_path_to_package=\"$2\"\n    local specific_version=\"${3//[$'\\t\\r\\n']}\"\n\n    local dotnet_package_path=\"$(combine_paths \"$(combine_paths \"$install_root\" \"$relative_path_to_package\")\" \"$specific_version\")\"\n    say_verbose \"is_dotnet_package_installed: dotnet_package_path=$dotnet_package_path\"\n\n    if [ -d \"$dotnet_package_path\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# coherent - $4\nget_latest_version_info() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local coherent=\"$4\"\n\n    local version_file_url=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        version_file_url=\"$uncached_feed/Runtime/$channel/latest.version\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        version_file_url=\"$uncached_feed/aspnetcore/Runtime/$channel/latest.version\"\n    elif [ -z \"$runtime\" ]; then\n        if [ \"$coherent\" = true ]; then\n            version_file_url=\"$uncached_feed/Sdk/$channel/latest.coherent.version\"\n        else\n            version_file_url=\"$uncached_feed/Sdk/$channel/latest.version\"\n        fi\n    else\n        say_err \"Invalid value for \\$runtime\"\n        return 1\n    fi\n    say_verbose \"get_latest_version_info: latest url: $version_file_url\"\n\n    download \"$version_file_url\"\n    return $?\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# version - $4\nget_specific_version_from_version() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local version=\"$(to_lowercase \"$4\")\"\n\n    case \"$version\" in\n        latest)\n            local version_info\n            version_info=\"$(get_latest_version_info \"$azure_feed\" \"$channel\" \"$normalized_architecture\" false)\" || return 1\n            say_verbose \"get_specific_version_from_version: version_info=$version_info\"\n            echo \"$version_info\" | get_version_from_version_info\n            return 0\n            ;;\n        coherent)\n            local version_info\n            version_info=\"$(get_latest_version_info \"$azure_feed\" \"$channel\" \"$normalized_architecture\" true)\" || return 1\n            say_verbose \"get_specific_version_from_version: version_info=$version_info\"\n            echo \"$version_info\" | get_version_from_version_info\n            return 0\n            ;;\n        *)\n            echo \"$version\"\n            return 0\n            ;;\n    esac\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# specific_version - $4\nconstruct_download_link() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local specific_version=\"${4//[$'\\t\\r\\n']}\"\n\n    local osname\n    osname=\"$(get_current_os_name)\" || return 1\n\n    local download_link=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        download_link=\"$azure_feed/Runtime/$specific_version/dotnet-runtime-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        download_link=\"$azure_feed/aspnetcore/Runtime/$specific_version/aspnetcore-runtime-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    elif [ -z \"$runtime\" ]; then\n        download_link=\"$azure_feed/Sdk/$specific_version/dotnet-sdk-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    else\n        return 1\n    fi\n\n    echo \"$download_link\"\n    return 0\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# specific_version - $4\nconstruct_legacy_download_link() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local specific_version=\"${4//[$'\\t\\r\\n']}\"\n\n    local distro_specific_osname\n    distro_specific_osname=\"$(get_legacy_os_name)\" || return 1\n\n    local legacy_download_link=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        legacy_download_link=\"$azure_feed/Runtime/$specific_version/dotnet-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz\"\n    elif [ -z \"$runtime\" ]; then\n        legacy_download_link=\"$azure_feed/Sdk/$specific_version/dotnet-dev-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz\"\n    else\n        return 1\n    fi\n\n    echo \"$legacy_download_link\"\n    return 0\n}\n\nget_user_install_path() {\n    eval $invocation\n\n    if [ ! -z \"${DOTNET_INSTALL_DIR:-}\" ]; then\n        echo \"$DOTNET_INSTALL_DIR\"\n    else\n        echo \"$HOME/.dotnet\"\n    fi\n    return 0\n}\n\n# args:\n# install_dir - $1\nresolve_installation_path() {\n    eval $invocation\n\n    local install_dir=$1\n    if [ \"$install_dir\" = \"<auto>\" ]; then\n        local user_install_path=\"$(get_user_install_path)\"\n        say_verbose \"resolve_installation_path: user_install_path=$user_install_path\"\n        echo \"$user_install_path\"\n        return 0\n    fi\n\n    echo \"$install_dir\"\n    return 0\n}\n\n# args:\n# install_root - $1\nget_installed_version_info() {\n    eval $invocation\n\n    local install_root=\"$1\"\n    local version_file=\"$(combine_paths \"$install_root\" \"$local_version_file_relative_path\")\"\n    say_verbose \"Local version file: $version_file\"\n    if [ ! -z \"$version_file\" ] | [ -r \"$version_file\" ]; then\n        local version_info=\"$(cat \"$version_file\")\"\n        echo \"$version_info\"\n        return 0\n    fi\n\n    say_verbose \"Local version file not found.\"\n    return 0\n}\n\n# args:\n# relative_or_absolute_path - $1\nget_absolute_path() {\n    eval $invocation\n\n    local relative_or_absolute_path=$1\n    echo \"$(cd \"$(dirname \"$1\")\" && pwd -P)/$(basename \"$1\")\"\n    return 0\n}\n\n# args:\n# input_files - stdin\n# root_path - $1\n# out_path - $2\n# override - $3\ncopy_files_or_dirs_from_list() {\n    eval $invocation\n\n    local root_path=\"$(remove_trailing_slash \"$1\")\"\n    local out_path=\"$(remove_trailing_slash \"$2\")\"\n    local override=\"$3\"\n    local osname=\"$(get_current_os_name)\"\n    local override_switch=$(\n        if [ \"$override\" = false ]; then\n            if [[ \"$osname\" == \"linux-musl\" ]]; then\n                printf -- \"-u\";\n            else\n                printf -- \"-n\";\n            fi\n        fi)\n\n    cat | uniq | while read -r file_path; do\n        local path=\"$(remove_beginning_slash \"${file_path#$root_path}\")\"\n        local target=\"$out_path/$path\"\n        if [ \"$override\" = true ] || (! ([ -d \"$target\" ] || [ -e \"$target\" ])); then\n            mkdir -p \"$out_path/$(dirname \"$path\")\"\n            cp -R $override_switch \"$root_path/$path\" \"$target\"\n        fi\n    done\n}\n\n# args:\n# zip_path - $1\n# out_path - $2\nextract_dotnet_package() {\n    eval $invocation\n\n    local zip_path=\"$1\"\n    local out_path=\"$2\"\n\n    local temp_out_path=\"$(mktemp -d \"$temporary_file_template\")\"\n\n    local failed=false\n    tar -xzf \"$zip_path\" -C \"$temp_out_path\" > /dev/null || failed=true\n\n    local folders_with_version_regex='^.*/[0-9]+\\.[0-9]+[^/]+/'\n    find \"$temp_out_path\" -type f | grep -Eo \"$folders_with_version_regex\" | sort | copy_files_or_dirs_from_list \"$temp_out_path\" \"$out_path\" false\n    find \"$temp_out_path\" -type f | grep -Ev \"$folders_with_version_regex\" | copy_files_or_dirs_from_list \"$temp_out_path\" \"$out_path\" \"$override_non_versioned_files\"\n\n    rm -rf \"$temp_out_path\"\n\n    if [ \"$failed\" = true ]; then\n        say_err \"Extraction failed\"\n        return 1\n    fi\n}\n\n# args:\n# remote_path - $1\n# [out_path] - $2 - stdout if not provided\ndownload() {\n    eval $invocation\n\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    local failed=false\n    if machine_has \"curl\"; then\n        downloadcurl \"$remote_path\" \"$out_path\" || failed=true\n    elif machine_has \"wget\"; then\n        downloadwget \"$remote_path\" \"$out_path\" || failed=true\n    else\n        failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Download failed: $remote_path\"\n        return 1\n    fi\n    return 0\n}\n\ndownloadcurl() {\n    eval $invocation\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    # Append feed_credential as late as possible before calling curl to avoid logging feed_credential\n    remote_path=\"${remote_path}${feed_credential}\"\n\n    local failed=false\n    if [ -z \"$out_path\" ]; then\n        curl --retry 10 -sSL -f --create-dirs \"$remote_path\" || failed=true\n    else\n        curl --retry 10 -sSL -f --create-dirs -o \"$out_path\" \"$remote_path\" || failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Curl download failed\"\n        return 1\n    fi\n    return 0\n}\n\ndownloadwget() {\n    eval $invocation\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    # Append feed_credential as late as possible before calling wget to avoid logging feed_credential\n    remote_path=\"${remote_path}${feed_credential}\"\n\n    local failed=false\n    if [ -z \"$out_path\" ]; then\n        wget -q --tries 10 -O - \"$remote_path\" || failed=true\n    else\n        wget --tries 10 -O \"$out_path\" \"$remote_path\" || failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Wget download failed\"\n        return 1\n    fi\n    return 0\n}\n\ncalculate_vars() {\n    eval $invocation\n    valid_legacy_download_link=true\n\n    normalized_architecture=\"$(get_normalized_architecture_from_architecture \"$architecture\")\"\n    say_verbose \"normalized_architecture=$normalized_architecture\"\n\n    specific_version=\"$(get_specific_version_from_version \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$version\")\"\n    say_verbose \"specific_version=$specific_version\"\n    if [ -z \"$specific_version\" ]; then\n        say_err \"Could not get version information.\"\n        return 1\n    fi\n\n    download_link=\"$(construct_download_link \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$specific_version\")\"\n    say_verbose \"download_link=$download_link\"\n\n    legacy_download_link=\"$(construct_legacy_download_link \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$specific_version\")\" || valid_legacy_download_link=false\n\n    if [ \"$valid_legacy_download_link\" = true ]; then\n        say_verbose \"legacy_download_link=$legacy_download_link\"\n    else\n        say_verbose \"Cound not construct a legacy_download_link; omitting...\"\n    fi\n\n    install_root=\"$(resolve_installation_path \"$install_dir\")\"\n    say_verbose \"install_root=$install_root\"\n}\n\ninstall_dotnet() {\n    eval $invocation\n    local download_failed=false\n    local asset_name=''\n    local asset_relative_path=''\n\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        asset_relative_path=\"shared/Microsoft.NETCore.App\"\n        asset_name=\".NET Core Runtime\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        asset_relative_path=\"shared/Microsoft.AspNetCore.App\"\n        asset_name=\"ASP.NET Core Runtime\"\n    elif [ -z \"$runtime\" ]; then\n        asset_relative_path=\"sdk\"\n        asset_name=\".NET Core SDK\"\n    else\n        say_err \"Invalid value for \\$runtime\"\n        return 1\n    fi\n\n    #  Check if the SDK version is already installed.\n    if is_dotnet_package_installed \"$install_root\" \"$asset_relative_path\" \"$specific_version\"; then\n        say \"$asset_name version $specific_version is already installed.\"\n        return 0\n    fi\n\n    mkdir -p \"$install_root\"\n    zip_path=\"$(mktemp \"$temporary_file_template\")\"\n    say_verbose \"Zip path: $zip_path\"\n\n    say \"Downloading link: $download_link\"\n\n    # Failures are normal in the non-legacy case for ultimately legacy downloads.\n    # Do not output to stderr, since output to stderr is considered an error.\n    download \"$download_link\" \"$zip_path\" 2>&1 || download_failed=true\n\n    #  if the download fails, download the legacy_download_link\n    if [ \"$download_failed\" = true ]; then\n        say \"Cannot download: $download_link\"\n\n        if [ \"$valid_legacy_download_link\" = true ]; then\n            download_failed=false\n            download_link=\"$legacy_download_link\"\n            zip_path=\"$(mktemp \"$temporary_file_template\")\"\n            say_verbose \"Legacy zip path: $zip_path\"\n            say \"Downloading legacy link: $download_link\"\n            download \"$download_link\" \"$zip_path\" 2>&1 || download_failed=true\n        fi\n    fi\n\n    if [ \"$download_failed\" = true ]; then\n        say_err \"Could not download $asset_name version $specific_version\"\n        return 1\n    fi\n\n    say \"Extracting zip from $download_link\"\n    extract_dotnet_package \"$zip_path\" \"$install_root\"\n\n    #  Check if the SDK version is now installed; if not, fail the installation.\n    if ! is_dotnet_package_installed \"$install_root\" \"$asset_relative_path\" \"$specific_version\"; then\n        say_err \"$asset_name version $specific_version failed to install with an unknown error.\"\n        return 1\n    fi\n\n    return 0\n}\n\nlocal_version_file_relative_path=\"/.version\"\nbin_folder_relative_path=\"\"\ntemporary_file_template=\"${TMPDIR:-/tmp}/dotnet.XXXXXXXXX\"\n\nchannel=\"LTS\"\nversion=\"Latest\"\ninstall_dir=\"<auto>\"\narchitecture=\"<auto>\"\ndry_run=false\nno_path=false\nazure_feed=\"https://dotnetcli.azureedge.net/dotnet\"\nuncached_feed=\"https://dotnetcli.blob.core.windows.net/dotnet\"\nfeed_credential=\"\"\nverbose=false\nruntime=\"\"\nruntime_id=\"\"\noverride_non_versioned_files=true\n\nwhile [ $# -ne 0 ]\ndo\n    name=\"$1\"\n    case \"$name\" in\n        -c|--channel|-[Cc]hannel)\n            shift\n            channel=\"$1\"\n            ;;\n        -v|--version|-[Vv]ersion)\n            shift\n            version=\"$1\"\n            ;;\n        -i|--install-dir|-[Ii]nstall[Dd]ir)\n            shift\n            install_dir=\"$1\"\n            ;;\n        --arch|--architecture|-[Aa]rch|-[Aa]rchitecture)\n            shift\n            architecture=\"$1\"\n            ;;\n        --shared-runtime|-[Ss]hared[Rr]untime)\n            say_warning \"The --shared-runtime flag is obsolete and may be removed in a future version of this script. The recommended usage is to specify '--runtime dotnet'.\"\n            if [ -z \"$runtime\" ]; then\n                runtime=\"dotnet\"\n            fi\n            ;;\n        --runtime|-[Rr]untime)\n            shift\n            runtime=\"$1\"\n            if [[ \"$runtime\" != \"dotnet\" ]] && [[ \"$runtime\" != \"aspnetcore\" ]]; then\n                say_err \"Unsupported value for --runtime: '$1'. Valid values are 'dotnet' and 'aspnetcore'.\"\n                exit 1\n            fi\n            ;;\n        --dry-run|-[Dd]ry[Rr]un)\n            dry_run=true\n            ;;\n        --no-path|-[Nn]o[Pp]ath)\n            no_path=true\n            ;;\n        --verbose|-[Vv]erbose)\n            verbose=true\n            ;;\n        --azure-feed|-[Aa]zure[Ff]eed)\n            shift\n            azure_feed=\"$1\"\n            ;;\n        --uncached-feed|-[Uu]ncached[Ff]eed)\n            shift\n            uncached_feed=\"$1\"\n            ;;\n        --feed-credential|-[Ff]eed[Cc]redential)\n            shift\n            feed_credential=\"$1\"\n            ;;\n        --runtime-id|-[Rr]untime[Ii]d)\n            shift\n            runtime_id=\"$1\"\n            ;;\n        --skip-non-versioned-files|-[Ss]kip[Nn]on[Vv]ersioned[Ff]iles)\n            override_non_versioned_files=false\n            ;;\n        -?|--?|-h|--help|-[Hh]elp)\n            script_name=\"$(basename \"$0\")\"\n            echo \".NET Tools Installer\"\n            echo \"Usage: $script_name [-c|--channel <CHANNEL>] [-v|--version <VERSION>] [-p|--prefix <DESTINATION>]\"\n            echo \"       $script_name -h|-?|--help\"\n            echo \"\"\n            echo \"$script_name is a simple command line interface for obtaining dotnet cli.\"\n            echo \"\"\n            echo \"Options:\"\n            echo \"  -c,--channel <CHANNEL>         Download from the channel specified, Defaults to \\`$channel\\`.\"\n            echo \"      -Channel\"\n            echo \"          Possible values:\"\n            echo \"          - Current - most current release\"\n            echo \"          - LTS - most current supported release\"\n            echo \"          - 2-part version in a format A.B - represents a specific release\"\n            echo \"              examples: 2.0; 1.0\"\n            echo \"          - Branch name\"\n            echo \"              examples: release/2.0.0; Master\"\n            echo \"  -v,--version <VERSION>         Use specific VERSION, Defaults to \\`$version\\`.\"\n            echo \"      -Version\"\n            echo \"          Possible values:\"\n            echo \"          - latest - most latest build on specific channel\"\n            echo \"          - coherent - most latest coherent build on specific channel\"\n            echo \"              coherent applies only to SDK downloads\"\n            echo \"          - 3-part version in a format A.B.C - represents specific version of build\"\n            echo \"              examples: 2.0.0-preview2-006120; 1.1.0\"\n            echo \"  -i,--install-dir <DIR>             Install under specified location (see Install Location below)\"\n            echo \"      -InstallDir\"\n            echo \"  --architecture <ARCHITECTURE>      Architecture of dotnet binaries to be installed, Defaults to \\`$architecture\\`.\"\n            echo \"      --arch,-Architecture,-Arch\"\n            echo \"          Possible values: x64, arm, and arm64\"\n            echo \"  --runtime <RUNTIME>                Installs a shared runtime only, without the SDK.\"\n            echo \"      -Runtime\"\n            echo \"          Possible values:\"\n            echo \"          - dotnet     - the Microsoft.NETCore.App shared runtime\"\n            echo \"          - aspnetcore - the Microsoft.AspNetCore.App shared runtime\"\n            echo \"  --skip-non-versioned-files         Skips non-versioned files if they already exist, such as the dotnet executable.\"\n            echo \"      -SkipNonVersionedFiles\"\n            echo \"  --dry-run,-DryRun                  Do not perform installation. Display download link.\"\n            echo \"  --no-path, -NoPath                 Do not set PATH for the current process.\"\n            echo \"  --verbose,-Verbose                 Display diagnostics information.\"\n            echo \"  --azure-feed,-AzureFeed            Azure feed location. Defaults to $azure_feed, This parameter typically is not changed by the user.\"\n            echo \"  --uncached-feed,-UncachedFeed      Uncached feed location. This parameter typically is not changed by the user.\"\n            echo \"  --feed-credential,-FeedCredential  Azure feed shared access token. This parameter typically is not specified.\"\n            echo \"  --runtime-id                       Installs the .NET Tools for the given platform (use linux-x64 for portable linux).\"\n            echo \"      -RuntimeId\"\n            echo \"  -?,--?,-h,--help,-Help             Shows this help message\"\n            echo \"\"\n            echo \"Obsolete parameters:\"\n            echo \"  --shared-runtime                   The recommended alternative is '--runtime dotnet'.\"\n            echo \"      -SharedRuntime                 Installs just the shared runtime bits, not the entire SDK.\"\n            echo \"\"\n            echo \"Install Location:\"\n            echo \"  Location is chosen in following order:\"\n            echo \"    - --install-dir option\"\n            echo \"    - Environmental variable DOTNET_INSTALL_DIR\"\n            echo \"    - $HOME/.dotnet\"\n            exit 0\n            ;;\n        *)\n            say_err \"Unknown argument \\`$name\\`\"\n            exit 1\n            ;;\n    esac\n\n    shift\ndone\n\ncheck_min_reqs\ncalculate_vars\n\nif [ \"$dry_run\" = true ]; then\n    say \"Payload URL: $download_link\"\n    if [ \"$valid_legacy_download_link\" = true ]; then\n        say \"Legacy payload URL: $legacy_download_link\"\n    fi\n    say \"Repeatable invocation: ./$(basename \"$0\") --version $specific_version --channel $channel --install-dir $install_dir\"\n    exit 0\nfi\n\ncheck_pre_reqs\ninstall_dotnet\n\nbin_path=\"$(get_absolute_path \"$(combine_paths \"$install_root\" \"$bin_folder_relative_path\")\")\"\nif [ \"$no_path\" = false ]; then\n    say \"Adding to current process PATH: \\`$bin_path\\`. Note: This change will be visible only when sourcing script.\"\n    export PATH=\"$bin_path\":\"$PATH\"\nelse\n    say \"Binaries of dotnet can be found in $bin_path\"\nfi\n\nsay \"Installation finished successfully.\"", "num_lines": 976}
{"repo_name": "azure-functions-core-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nif [ -z \"$AzureWebJobsScriptRoot\" ]; then\n    cd /home/site/wwwroot\nelse\n    cd \"$AzureWebJobsScriptRoot\"\nfi\n\necho '{'\necho '\"hostJson\":'\nif [ -f \"host.json\" ]; then\n    cat host.json\nelse\n    echo '{ }'\nfi\n\necho ','\n\necho '\"functionsJson\": {'\n\nfor d in */; do\n    d=$(echo $d | tr -d '/')\n    if [ -f \"${d}/function.json\" ]; then\n        echo \"\\\"${d}\\\": \"\n        cat \"${d}/function.json\"\n        echo ','\n    fi\ndone\necho '}'\necho '}'\n", "num_lines": 31}
{"repo_name": "azure-functions-core-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf#! /bin/bash\n\n# Exit on errors\nset -e\n\nPYTHON_PACKAGE_PATH=\"/.python_packages/lib/site-packages\"\nif [[ \"$PYTHON_VERSION\" == \"3.6\"* ]]; then\n    PYTHON_PACKAGE_PATH=\"/.python_packages/lib/python3.6/site-packages\"\nfi;\n\npip install --target=\"$PYTHON_PACKAGE_PATH\" -r /requirements.txt\n", "num_lines": 12}
{"repo_name": "azure-functions-core-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\nset -e\n\nunzip -n /file.zip -d /tmp/extract/\nchown -R $USER:$USER /tmp/extract\nchmod -R +r /tmp/extract\nmksquashfs /tmp/extract /file.squashfs -noappend", "num_lines": 7}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n\n\nDIR=$(dirname $0)\nIFS=$'\\n'\n\nselect_version() {\n    ## Selects the directory of the version to be generated\n    ## Defaults to v3 for now \n    if [ \"$VERSION\" == \"4\" ]; then\n        echo \"Version 4 selected\"\n        DIR=$(dirname $0)/4/bullseye/amd64/base\n    elif [ \"$VERSION\" == \"3\" ]; then\n        echo \"Version 4 selected\"\n        DIR=$(dirname $0)/3.0/buster/amd64/base\n    else\n        echo \"No valid version selected. Must provide a valid version via -3 or -4 flags\"\n        exit 1\n    fi\n}\n\nglobalize_args() {\n    ## This method is used to bring all args preceding any From statements to the top of the file. \n    ## Allows for ARGs defined globally in composite images to be global in the compiled dockerfile\n    ## list of args in arr with carriage returns at end\n    gblarg=$((sed -n '/FROM/q;p' $1) | grep ARG)\n    if [ ${#gblarg[@]} == 0 ]; then \n        printf \"\\t No global ARGs in $1 \\n\"\n    else\n        printf \"\\t ARGs globalized for $1 : \\n\"\n        for arg in ${gblarg[@]};\n        do\n            printf \"\\t\\t $arg \\n\"\n        done \n    fi\n}\n\ncombine_dockerfile() {\n    printf $\"  Combining $base with $1\\n\"\n    localfile=$(printf $1 | awk -F'\\\\.\\\\.' '{print $2}')\n    runtime=`echo $localfile | cut -d'/' -f 2`\n    runtimeversion=`echo $localfile | cut -d'/' -f 3`\n    printf \"\\t Image Runtime and Version: $runtimeversion \\n\"\n\n    # Output path\n    \n\n    # File structure creation\n    outputdir=$\"$DIR/../out/${runtime}\"\n    if [ \"$RELEASE\" == \"true\" ]; then\n        printf \"\\t Release Mode enabled. Updating release dockerfiles.\\n\"\n        outputdir=$\"$DIR/../release/${runtime}\"\n    fi\n    mkdir -p $outputdir\n    outputfile=\"$outputdir/${runtimeversion}-appservice.Dockerfile\"\n\n    printf $\"\\t Collecting global arguments in $1 to globalize them in the final dockerfile.\\n\"\n    globalize_args $1\n    echo \"${gblarg[@]}\" | cat - $base $1 > $outputfile\n\n    printf $\"\\t Completed compilation of $runtimeversion. Output file available at : $outputfile\\n\"\n}\n\ngenerate_appservice() {\n    base=\"$DIR/host.Dockerfile\"\n    echo $\"Generating Appservice Images for [ $@ ] using base $base\"\n    for lang in $@; \n    do \n        langimgs=($(find $DIR/../$lang/ -name \"*-composite.template\"))\n        if [ -z \"$langimgs\" ]; then\n            echo \"No composite images found for language : $lang. Skipping compilation...\"\n        else\n            echo $\"Found following images for compilation of language $lang: ${langimgs[@]}\"\n            for version in ${langimgs[@]};\n            do\n                combine_dockerfile $version\n                printf \"\\n\"\n            done\n            printf $\"Completed compilation of $lang images \\n\\n\"\n        fi\n    done\n    echo \"Compilation of all images in list: [ $@ ] complete.\"\n    printf \"\\n\"\n}\n\ncopy_shared_config() {\n     \n    \n    echo \"Copying shared config files into the following language output directories: \"\n    for lang in $@;\n    do\n        outputdir=$\"$DIR/../out/${lang}/\"\n        if [ \"$RELEASE\" == \"true\" ]; then\n            outputdir=$\"$DIR/../release/${lang}/\"\n        fi\n        printf \"\\t $outputdir\\n\"\n        cp -R $DIR/sharedconfig/* $outputdir\n    done\n}\n\nclear_outputdir() {\n    ## Seems to not be working currently. Further investigation needed\n    echo \"Clearing output folder...\"\n    rootdir=$\"$DIR/../out/*\"\n    rm -rf rootdir\n}\n\n\n# Defines a flag -r : Release Mode.  Release mode will generate artifacts in a folder titled /release/\n# These .Dockerfile artifacts will be used to create the containers uploaded to ACR. Increases trace-ability.\n# Flags must come before parameters. \nwhile getopts \":r43\" flag;do\n    case ${flag} in\n      r)\n        RELEASE=\"true\"\n        echo \"Release Mode is enabled\"\n        ;;\n      4)\n        VERSION=\"4\"\n        echo \"Version 4 selected\"\n        ;;\n      3)\n        VERSION=\"3\"\n        echo \"Version 3 selected\"\n        ;;\n    esac\ndone\n\nselect_version\n\necho \"Dir is : $DIR\"\n\nif [ -z $RELEASE ]; then\n    clear_outputdir\nfi\n\n# Remove flags from input. Store args in array\ndeclare -a argarray\nfor arg do\n    if [ \"${arg:0:1}\" != '-' ]; then\n        echo $arg\n        argarray+=($arg)\n    fi\ndone\n\nif [ ${#argarray[@]} == 0 ]; then\n    echo \"No language arguments supplied for compilation. Please supply a supported language or 'all' as an input.\"\n    exit 1\nfi\n\nif [ ${#argarray[@]} == 1 ] && [ \"$argarray\" == \"all\" ]; then\n    echo \"All supported languages targetted.\"\n    supportedlangs=(\"java\" \"node\" \"python\" \"dotnet\" \"powershell\")\n    argarray=(${supportedlangs[@]})\nfi\n\ngenerate_appservice ${argarray[@]}\n\ncopy_shared_config ${argarray[@]}", "num_lines": 160}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh -eu\n\n# Copy files from /usr/share/maven/ref into ${MAVEN_CONFIG}\n# So the initial ~/.m2 is set with expected content.\n# Don't override, as this is just a reference setup\n\ncopy_reference_files() {\n  local log=\"$MAVEN_CONFIG/copy_reference_file.log\"\n  local ref=\"/usr/share/maven/ref\"\n\n  if mkdir -p \"${MAVEN_CONFIG}/repository\" && touch \"${log}\" > /dev/null 2>&1 ; then\n      cd \"${ref}\"\n      local reflink=\"\"\n      if cp --help 2>&1 | grep -q reflink ; then\n          reflink=\"--reflink=auto\"\n      fi\n      if [ -n \"$(find \"${MAVEN_CONFIG}/repository\" -maxdepth 0 -type d -empty 2>/dev/null)\" ] ; then\n          # destination is empty...\n          echo \"--- Copying all files to ${MAVEN_CONFIG} at $(date)\" >> \"${log}\"\n          cp -rv ${reflink} . \"${MAVEN_CONFIG}\" >> \"${log}\"\n      else\n          # destination is non-empty, copy file-by-file\n          echo \"--- Copying individual files to ${MAVEN_CONFIG} at $(date)\" >> \"${log}\"\n          find . -type f -exec sh -eu -c '\n              log=\"${1}\"\n              shift\n              reflink=\"${1}\"\n              shift\n              for f in \"$@\" ; do\n                  if [ ! -e \"${MAVEN_CONFIG}/${f}\" ] || [ -e \"${f}.override\" ] ; then\n                      mkdir -p \"${MAVEN_CONFIG}/$(dirname \"${f}\")\"\n                      cp -rv ${reflink} \"${f}\" \"${MAVEN_CONFIG}/${f}\" >> \"${log}\"\n                  fi\n              done\n          ' _ \"${log}\" \"${reflink}\" {} +\n      fi\n      echo >> \"${log}\"\n  else\n    echo \"Can not write to ${log}. Wrong volume permissions? Carrying on ...\"\n  fi\n}\n\nowd=\"$(pwd)\"\ncopy_reference_files\nunset MAVEN_CONFIG\n\ncd \"${owd}\"\nunset owd\n\nexec \"$@\"\n", "num_lines": 51}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nDIR=$(dirname $0)\n\nfunction print_usage {\n  echo -e \"Usage: $0 <MajorVersion> <FullVersion>\\n\"\n  echo -e \"Requires gnu-sed for it to work. Please install it using `brew install gnu-sed --with-default-names`\"\n  echo -e \"Example: $0 3.0 3.1.1\"\n  echo -e \"Example: $0 4.0 4.10.2\"\n}\n\nif [ \"$1\" != \"3\" ] && [ \"$1\" != \"4\" ]; then\n  echo -e \"MajorVersion must be '3', or '4' Got '$1'\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ -z \"$2\" ]; then\n  echo -e \"Please pass the FullVersion. The whole FullVersion is required.\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ \"$1\" == \"3\" ]; then\n   find $DIR/3.0 -name \"*Dockerfile\" -exec gsed -i \"s/\\bHOST_VERSION=$1\\..*/HOST_VERSION=$2/g\" {} \\;\nelse \n   find $DIR/$1 -name \"*Dockerfile\" -exec gsed -i \"s/\\bHOST_VERSION=$1\\..*/HOST_VERSION=$2/g\" {} \\;\nfi\n", "num_lines": 29}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nDIR=$(dirname $0)\n\nfunction print_usage {\n  echo -e \"Usage: $0 <MajorVersion> <FullVersion>\\n\"\n  echo -e \"Example: $0 3.0 3.1.1\"\n  echo -e \"Example: $0 4.0 4.10.2\"\n}\n\nif [ \"$1\" != \"3\" ] && [ \"$1\" != \"4\" ]; then\n  echo -e \"MajorVersion must be '3', or '4' Got '$1'\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ -z \"$2\" ]; then\n  echo -e \"Please pass the FullVersion. The whole FullVersion is required.\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ \"$1\" == \"3\" ]; then\n   find $DIR/3.0 -name \"*Dockerfile\" -exec sed -i \"s/\\bHOST_VERSION=$1\\..*/HOST_VERSION=$2/g\" \"$0\" {} \\;\nelse \n   find $DIR/$1 -name \"*Dockerfile\" -exec sed -i \"s/\\bHOST_VERSION=$1\\..*/HOST_VERSION=$2/g\" \"$0\" {} \\;\nfi", "num_lines": 27}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n\n\nDIR=$(dirname $0)\nIFS=$'\\n'\n\ncheck_sovereign() {\n  sharedimages=($(comm -12 <(printf '%s\\n' \"${stage[@]}\"|sort -u) <(printf '%s\\n' \"${pub[@]}\"|sort -u)))\n  sovereign=($(((grep \"docker push\".*appservice ${TARGET}/publish-appservice-stage-sovereign-clouds.yml) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )\n  diffsovereign=($(comm -3 <(printf '%s\\n' \"${sharedimages[@]}\"|sort -u) <(printf '%s\\n' \"${sovereign[@]}\"|sort -u)))\n  if [ -z \"$diffsovereign\" ]; then\n    echo -e \"Sovereign pipeline verified for ${TARGET}/. Proceed with release.\\n\"\n    exit 0\n  else \n    echo -e \"Sovereign pipeline is invalid. Other than the /base image all pipelines should publish the same -appservice images. The following differences exist for -appservice images in the sovereign pipeline: \"\n    echo -e ${diffsovereign[@]}\n    exit 1\n  fi\n}\n\nif [ \"$1\" != \"2.0\" ] && [ \"$1\" != \"3\" ] && [ \"$1\" != \"4\" ]; then\n  echo -e \"MajorVersion must be 2.0, 3, or 4 Got '$1'\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ \"$1\" == \"2.0\" ]; then\n   echo -e \"MajorVersion 2.0 is not supported by this script. Continuing with NoOp\"\n   exit 0\nfi\n\nif [ \"$1\" == \"3\" ]; then\n   echo -e \"MajorVersion 3 detected. Verifying pipelines in host/3.0/\"\n   TARGET=\"./3.0\"\nelse \n   echo -e \"MajorVersion 4 detected. Verifying pipelines in host/4/\"\n   TARGET=\"./4\"\nfi\n\nstage=($(((grep \"docker push\".*appservice ${TARGET}/publish-appservice-stage.yml) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )\n\npub=($((((grep \"docker push\".*appservice  ${TARGET}/publish.yml)| grep -v quickstart) | awk -F'-appservice' '{print $1}') | awk -F 'TARGET_REGISTRY' '{print $2}') )\n\ndifference=($(comm -3 <(printf '%s\\n' \"${stage[@]}\"|sort -u) <(printf '%s\\n' \"${pub[@]}\"|sort -u)))\n\nif [ -z \"$difference\" ]; then\n  echo -e \"No differences between Stage and Publish pipelines.  Verifying sovereign cloud pipeline.\\n\"\n  check_sovereign\n  exit 0\nfi\n\nif [ ${#difference[@]} == 1 ] && [[ $difference =~ \"base\" ]]; then\n   echo -e \"Stage pipeline excludes base image. This is a known difference. Rollout Safe. Verifying sovereign cloud pipeline.\"\n   check_sovereign\n   exit 0\nelse \n   echo -e \"Publish and stage pipelines inconsistent. Other than the /base image all pipelines should publish the same -appservice images. The following differences exist for -appservice images between the pipelines: \"\n   echo -e ${difference[@]}\n   exit 1\nfi\n", "num_lines": 62}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n\n\nDIR=$(dirname $0)\nIFS=$'\\n'\n\nfullversion=$1\nmajorversion=${fullversion:0:1}\n\nif [ \"$majorversion\" != \"2\" ] && [ \"$majorversion\" != \"3\" ] && [ \"$majorversion\" != \"4\" ]; then\n  echo -e \"MajorVersion must be 2, 3, or 4 Got '$1'\\n\"\n  print_usage\n  exit 1\nfi\n\nif [ \"$majorversion\" == \"2\" ]; then\n   echo -e \"MajorVersion 2 is not supported by this script. Continuing with NoOp\"\n   exit 0\nfi\n\nif [ \"$majorversion\" == \"3\" ]; then\n   echo -e \"MajorVersion 3 detected. Verifying pipelines in host/3.0/\"\n   TARGET=\"./3.0\"\nelse \n   echo -e \"MajorVersion 4 detected. Verifying pipelines in host/4/\"\n   TARGET=\"./4\"\nfi\n\nrepub=($(((grep \"docker push\".* ${TARGET}/republish.yml) | awk -F 'TARGET_REGISTRY' '{print $2}') ))\n\n\npub=($(((((grep \"docker push\".*  ${TARGET}/publish.yml)| grep -v quickstart)| grep -v nanoserver) | awk -F 'TARGET_REGISTRY' '{print $2}') ))\n\ndifference=($(comm -3 <(printf '%s\\n' \"${repub[@]}\"|sort -u) <(printf '%s\\n' \"${pub[@]}\"|sort -u)))\n\nif [ -z \"$difference\" ]; then\n  echo -e \"No differences between Republish and Publish pipelines.\\n\"\n  exit 0\nfi\n\necho ${difference[@]} | tr -d '\\r'\nif [ ${#difference[@]} == 1 ] && [[ $difference == *\"nanoserver\"* ]]; then\n   echo -e \"Republish pipeline excludes nanoserver image. This is a known difference. Redeployment Safe. \\n\"\n   exit 0\nelse \n   echo -e \"Republish and Publish pipelines inconsistent. Other than the /base image all pipelines should publish the same non-quickstart images. The following differences exist for images between the pipelines: \"\n   echo -e ${difference[@]}\n   exit 1\nfi\n", "num_lines": 51}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\n# Get environment variables to show up in SSH session\neval $(printenv | sed -n \"s/^\\([^=]\\+\\)=\\(.*\\)$/export \\1=\\2/p\" | sed 's/\"/\\\\\\\"/g' | sed '/=/s//=\"/' | sed 's/$/\"/' >> /etc/profile)\n\n# starting sshd process\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 32}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\n# Get environment variables to show up in SSH session\neval $(printenv | sed -n \"s/^\\([^=]\\+\\)=\\(.*\\)$/export \\1=\\2/p\" | sed 's/\"/\\\\\\\"/g' | sed '/=/s//=\"/' | sed 's/$/\"/' >> /etc/profile)\n\n# starting sshd process\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 32}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-docker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nexport DOTNET_USE_POLLING_FILE_WATCHER=true\n\nif [ -z $PORT ]; then\n  export ASPNETCORE_URLS=http://*:80\nelse\n  export ASPNETCORE_URLS=http://*:$PORT\nfi\n\nif [ -z $SSH_PORT ]; then\n  export SSH_PORT=2222\nfi\n\nif [ \"$APPSVC_REMOTE_DEBUGGING\" == \"TRUE\" ]; then\n    export languageWorkers__node__arguments=\"--inspect=0.0.0.0:$APPSVC_TUNNEL_PORT\"\n    export languageWorkers__python__arguments=\"-m ptvsd --host localhost --port $APPSVC_TUNNEL_PORT\"\nfi\n\nsed -i \"s/SSH_PORT/$SSH_PORT/g\" /etc/ssh/sshd_config\n\nservice ssh start\n\nif [ -f /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost ]; then\n    /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost\nelse\n    dotnet /azure-functions-host/Microsoft.Azure.WebJobs.Script.WebHost.dll\nfi", "num_lines": 28}
{"repo_name": "azure-functions-durable-python", "repo_creator": "Azure", "programming_language": "Shell", "code": " #!/bin/bash\n\necho \"Checking for prerequisites...\"\nif ! type npm > /dev/null; then\n    echo \"Prerequisite Check 1: Install Node.js and NPM\"\n    exit 1\nfi\n\nif ! type dotnet > /dev/null; then\n    echo \"Prerequisite Check 2: Install .NET Core 2.1 SDK or Runtime\"\n    exit 1\nfi\n\nif ! type func > /dev/null; then\n    echo \"Prerequisite Check 3: Install Azure Functions Core Tools\"\n    exit 1\nfi\n\necho \"Pre-requisites satisfied...\"\n\necho \"Creating sample folders...\"\nDIRECTORY=/tmp/df_test\nif [ ! -d \"$DIRECTORY\" ]; then\n  mkdir /tmp/df_test\nelse\n  rm -rf /tmp/df_test/*\nfi\n\nSAMPLE=function_chaining\ncp -r ../samples/$SAMPLE $DIRECTORY/\ncd $DIRECTORY/$SAMPLE\npython -m venv env\nsource env/bin/activate\n\necho \"Provide local path to azure-functions-durable-python clone:\"\nread lib_path\npip install $lib_path/azure-functions-durable-python\nfunc init .\nfunc extensions install\necho \"Done\"\n\n", "num_lines": 42}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) .NET Foundation and contributors. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# Original file from https://github.com/dotnet/cli/blob/80d542b8f4eff847a0f72dc8f2c2a29851272778/scripts/obtain/dotnet-install.sh\n\n# Stop script on NZEC\nset -e\n# Stop script if unbound variable found (use ${var:-} if intentional)\nset -u\n# By default cmd1 | cmd2 returns exit code of cmd2 regardless of cmd1 success\n# This is causing it to fail\nset -o pipefail\n\n# Use in the the functions: eval $invocation\ninvocation='say_verbose \"Calling: ${yellow:-}${FUNCNAME[0]} ${green:-}$*${normal:-}\"'\n\n# standard output may be used as a return value in the functions\n# we need a way to write text on the screen in the functions so that\n# it won't interfere with the return value.\n# Exposing stream 3 as a pipe to standard output of the script itself\nexec 3>&1\n\n# Setup some colors to use. These need to work in fairly limited shells, like the Ubuntu Docker container where there are only 8 colors.\n# See if stdout is a terminal\nif [ -t 1 ] && command -v tput > /dev/null; then\n    # see if it supports colors\n    ncolors=$(tput colors)\n    if [ -n \"$ncolors\" ] && [ $ncolors -ge 8 ]; then\n        bold=\"$(tput bold       || echo)\"\n        normal=\"$(tput sgr0     || echo)\"\n        black=\"$(tput setaf 0   || echo)\"\n        red=\"$(tput setaf 1     || echo)\"\n        green=\"$(tput setaf 2   || echo)\"\n        yellow=\"$(tput setaf 3  || echo)\"\n        blue=\"$(tput setaf 4    || echo)\"\n        magenta=\"$(tput setaf 5 || echo)\"\n        cyan=\"$(tput setaf 6    || echo)\"\n        white=\"$(tput setaf 7   || echo)\"\n    fi\nfi\n\nsay_warning() {\n    printf \"%b\\n\" \"${yellow:-}dotnet_install: Warning: $1${normal:-}\"\n}\n\nsay_err() {\n    printf \"%b\\n\" \"${red:-}dotnet_install: Error: $1${normal:-}\" >&2\n}\n\nsay() {\n    # using stream 3 (defined in the beginning) to not interfere with stdout of functions\n    # which may be used as return value\n    printf \"%b\\n\" \"${cyan:-}dotnet-install:${normal:-} $1\" >&3\n}\n\nsay_verbose() {\n    if [ \"$verbose\" = true ]; then\n        say \"$1\"\n    fi\n}\n\n# This platform list is finite - if the SDK/Runtime has supported Linux distribution-specific assets,\n#   then and only then should the Linux distribution appear in this list.\n# Adding a Linux distribution to this list does not imply distribution-specific support.\nget_legacy_os_name_from_platform() {\n    eval $invocation\n\n    platform=\"$1\"\n    case \"$platform\" in\n        \"centos.7\")\n            echo \"centos\"\n            return 0\n            ;;\n        \"debian.8\")\n            echo \"debian\"\n            return 0\n            ;;\n        \"fedora.23\")\n            echo \"fedora.23\"\n            return 0\n            ;;\n        \"fedora.27\")\n            echo \"fedora.27\"\n            return 0\n            ;;\n        \"fedora.24\")\n            echo \"fedora.24\"\n            return 0\n            ;;\n        \"opensuse.13.2\")\n            echo \"opensuse.13.2\"\n            return 0\n            ;;\n        \"opensuse.42.1\")\n            echo \"opensuse.42.1\"\n            return 0\n            ;;\n        \"opensuse.42.3\")\n            echo \"opensuse.42.3\"\n            return 0\n            ;;\n        \"rhel.7\"*)\n            echo \"rhel\"\n            return 0\n            ;;\n        \"ubuntu.14.04\")\n            echo \"ubuntu\"\n            return 0\n            ;;\n        \"ubuntu.16.04\")\n            echo \"ubuntu.16.04\"\n            return 0\n            ;;\n        \"ubuntu.16.10\")\n            echo \"ubuntu.16.10\"\n            return 0\n            ;;\n        \"ubuntu.18.04\")\n            echo \"ubuntu.18.04\"\n            return 0\n            ;;\n        \"alpine.3.4.3\")\n            echo \"alpine\"\n            return 0\n            ;;\n    esac\n    return 1\n}\n\nget_linux_platform_name() {\n    eval $invocation\n\n    if [ -n \"$runtime_id\" ]; then\n        echo \"${runtime_id%-*}\"\n        return 0\n    else\n        if [ -e /etc/os-release ]; then\n            . /etc/os-release\n            echo \"$ID.$VERSION_ID\"\n            return 0\n        elif [ -e /etc/redhat-release ]; then\n            local redhatRelease=$(</etc/redhat-release)\n            if [[ $redhatRelease == \"CentOS release 6.\"* || $redhatRelease == \"Red Hat Enterprise Linux Server release 6.\"* ]]; then\n                echo \"rhel.6\"\n                return 0\n            fi\n        fi\n    fi\n\n    say_verbose \"Linux specific platform name and version could not be detected: UName = $uname\"\n    return 1\n}\n\nget_current_os_name() {\n    eval $invocation\n\n    local uname=$(uname)\n    if [ \"$uname\" = \"Darwin\" ]; then\n        echo \"osx\"\n        return 0\n    elif [ \"$uname\" = \"Linux\" ]; then\n        local linux_platform_name\n        linux_platform_name=\"$(get_linux_platform_name)\" || { echo \"linux\" && return 0 ; }\n\n        if [[ $linux_platform_name == \"rhel.6\" ]]; then\n            echo $linux_platform_name\n            return 0\n        elif [[ $linux_platform_name == alpine* ]]; then\n            echo \"linux-musl\"\n            return 0\n        else\n            echo \"linux\"\n            return 0\n        fi\n    fi\n\n    say_err \"OS name could not be detected: UName = $uname\"\n    return 1\n}\n\nget_legacy_os_name() {\n    eval $invocation\n\n    local uname=$(uname)\n    if [ \"$uname\" = \"Darwin\" ]; then\n        echo \"osx\"\n        return 0\n    elif [ -n \"$runtime_id\" ]; then\n        echo $(get_legacy_os_name_from_platform \"${runtime_id%-*}\" || echo \"${runtime_id%-*}\")\n        return 0\n    else\n        if [ -e /etc/os-release ]; then\n            . /etc/os-release\n            os=$(get_legacy_os_name_from_platform \"$ID.$VERSION_ID\" || echo \"\")\n            if [ -n \"$os\" ]; then\n                echo \"$os\"\n                return 0\n            fi\n        fi\n    fi\n\n    say_verbose \"Distribution specific OS name and version could not be detected: UName = $uname\"\n    return 1\n}\n\nmachine_has() {\n    eval $invocation\n\n    hash \"$1\" > /dev/null 2>&1\n    return $?\n}\n\n\ncheck_min_reqs() {\n    local hasMinimum=false\n    if machine_has \"curl\"; then\n        hasMinimum=true\n    elif machine_has \"wget\"; then\n        hasMinimum=true\n    fi\n\n    if [ \"$hasMinimum\" = \"false\" ]; then\n        say_err \"curl (recommended) or wget are required to download dotnet. Install missing prerequisite to proceed.\"\n        return 1\n    fi\n    return 0\n}\n\ncheck_pre_reqs() {\n    eval $invocation\n\n    if [ \"${DOTNET_INSTALL_SKIP_PREREQS:-}\" = \"1\" ]; then\n        return 0\n    fi\n\n    if [ \"$(uname)\" = \"Linux\" ]; then\n        if [ ! -x \"$(command -v ldconfig)\" ]; then\n            echo \"ldconfig is not in PATH, trying /sbin/ldconfig.\"\n            LDCONFIG_COMMAND=\"/sbin/ldconfig\"\n        else\n            LDCONFIG_COMMAND=\"ldconfig\"\n        fi\n\n        local librarypath=${LD_LIBRARY_PATH:-}\n        LDCONFIG_COMMAND=\"$LDCONFIG_COMMAND -NXv ${librarypath//:/ }\"\n\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libunwind)\" ] && say_warning \"Unable to locate libunwind. Probable prerequisite missing; please install libunwind.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libssl)\" ] && say_warning \"Unable to locate libssl. Probable prerequisite missing; please install libssl.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep libicu)\" ] && say_warning \"Unable to locate libicu. Probable prerequisite missing; please install libicu.\"\n        [ -z \"$($LDCONFIG_COMMAND 2>/dev/null | grep -F libcurl.so)\" ] && say_warning \"Unable to locate libcurl. Probable prerequisite missing; please install libcurl.\"\n    fi\n\n    return 0\n}\n\n# args:\n# input - $1\nto_lowercase() {\n    #eval $invocation\n\n    echo \"$1\" | tr '[:upper:]' '[:lower:]'\n    return 0\n}\n\n# args:\n# input - $1\nremove_trailing_slash() {\n    #eval $invocation\n\n    local input=\"${1:-}\"\n    echo \"${input%/}\"\n    return 0\n}\n\n# args:\n# input - $1\nremove_beginning_slash() {\n    #eval $invocation\n\n    local input=\"${1:-}\"\n    echo \"${input#/}\"\n    return 0\n}\n\n# args:\n# root_path - $1\n# child_path - $2 - this parameter can be empty\ncombine_paths() {\n    eval $invocation\n\n    # TODO: Consider making it work with any number of paths. For now:\n    if [ ! -z \"${3:-}\" ]; then\n        say_err \"combine_paths: Function takes two parameters.\"\n        return 1\n    fi\n\n    local root_path=\"$(remove_trailing_slash \"$1\")\"\n    local child_path=\"$(remove_beginning_slash \"${2:-}\")\"\n    say_verbose \"combine_paths: root_path=$root_path\"\n    say_verbose \"combine_paths: child_path=$child_path\"\n    echo \"$root_path/$child_path\"\n    return 0\n}\n\nget_machine_architecture() {\n    eval $invocation\n\n    if command -v uname > /dev/null; then\n        CPUName=$(uname -m)\n        case $CPUName in\n        armv7l)\n            echo \"arm\"\n            return 0\n            ;;\n        aarch64)\n            echo \"arm64\"\n            return 0\n            ;;\n        esac\n    fi\n\n    # Always default to 'x64'\n    echo \"x64\"\n    return 0\n}\n\n# args:\n# architecture - $1\nget_normalized_architecture_from_architecture() {\n    eval $invocation\n\n    local architecture=\"$(to_lowercase \"$1\")\"\n    case \"$architecture\" in\n        \\<auto\\>)\n            echo \"$(get_normalized_architecture_from_architecture \"$(get_machine_architecture)\")\"\n            return 0\n            ;;\n        amd64|x64)\n            echo \"x64\"\n            return 0\n            ;;\n        arm)\n            echo \"arm\"\n            return 0\n            ;;\n        arm64)\n            echo \"arm64\"\n            return 0\n            ;;\n    esac\n\n    say_err \"Architecture \\`$architecture\\` not supported. If you think this is a bug, please report it at https://github.com/dotnet/cli/issues\"\n    return 1\n}\n\n# version_info is a conceptual two line string representing commit hash and 4-part version\n# format:\n# Line 1: # commit_hash\n# Line 2: # 4-part version\n\n# args:\n# version_text - stdin\nget_version_from_version_info() {\n    eval $invocation\n\n    cat | tail -n 1 | sed 's/\\r$//'\n    return 0\n}\n\n# args:\n# version_text - stdin\nget_commit_hash_from_version_info() {\n    eval $invocation\n\n    cat | head -n 1 | sed 's/\\r$//'\n    return 0\n}\n\n# args:\n# install_root - $1\n# relative_path_to_package - $2\n# specific_version - $3\nis_dotnet_package_installed() {\n    eval $invocation\n\n    local install_root=\"$1\"\n    local relative_path_to_package=\"$2\"\n    local specific_version=\"${3//[$'\\t\\r\\n']}\"\n\n    local dotnet_package_path=\"$(combine_paths \"$(combine_paths \"$install_root\" \"$relative_path_to_package\")\" \"$specific_version\")\"\n    say_verbose \"is_dotnet_package_installed: dotnet_package_path=$dotnet_package_path\"\n\n    if [ -d \"$dotnet_package_path\" ]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# coherent - $4\nget_latest_version_info() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local coherent=\"$4\"\n\n    local version_file_url=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        version_file_url=\"$uncached_feed/Runtime/$channel/latest.version\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        version_file_url=\"$uncached_feed/aspnetcore/Runtime/$channel/latest.version\"\n    elif [ -z \"$runtime\" ]; then\n        if [ \"$coherent\" = true ]; then\n            version_file_url=\"$uncached_feed/Sdk/$channel/latest.coherent.version\"\n        else\n            version_file_url=\"$uncached_feed/Sdk/$channel/latest.version\"\n        fi\n    else\n        say_err \"Invalid value for \\$runtime\"\n        return 1\n    fi\n    say_verbose \"get_latest_version_info: latest url: $version_file_url\"\n\n    download \"$version_file_url\"\n    return $?\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# version - $4\nget_specific_version_from_version() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local version=\"$(to_lowercase \"$4\")\"\n\n    case \"$version\" in\n        latest)\n            local version_info\n            version_info=\"$(get_latest_version_info \"$azure_feed\" \"$channel\" \"$normalized_architecture\" false)\" || return 1\n            say_verbose \"get_specific_version_from_version: version_info=$version_info\"\n            echo \"$version_info\" | get_version_from_version_info\n            return 0\n            ;;\n        coherent)\n            local version_info\n            version_info=\"$(get_latest_version_info \"$azure_feed\" \"$channel\" \"$normalized_architecture\" true)\" || return 1\n            say_verbose \"get_specific_version_from_version: version_info=$version_info\"\n            echo \"$version_info\" | get_version_from_version_info\n            return 0\n            ;;\n        *)\n            echo \"$version\"\n            return 0\n            ;;\n    esac\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# specific_version - $4\nconstruct_download_link() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local specific_version=\"${4//[$'\\t\\r\\n']}\"\n\n    local osname\n    osname=\"$(get_current_os_name)\" || return 1\n\n    local download_link=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        download_link=\"$azure_feed/Runtime/$specific_version/dotnet-runtime-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        download_link=\"$azure_feed/aspnetcore/Runtime/$specific_version/aspnetcore-runtime-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    elif [ -z \"$runtime\" ]; then\n        download_link=\"$azure_feed/Sdk/$specific_version/dotnet-sdk-$specific_version-$osname-$normalized_architecture.tar.gz\"\n    else\n        return 1\n    fi\n\n    echo \"$download_link\"\n    return 0\n}\n\n# args:\n# azure_feed - $1\n# channel - $2\n# normalized_architecture - $3\n# specific_version - $4\nconstruct_legacy_download_link() {\n    eval $invocation\n\n    local azure_feed=\"$1\"\n    local channel=\"$2\"\n    local normalized_architecture=\"$3\"\n    local specific_version=\"${4//[$'\\t\\r\\n']}\"\n\n    local distro_specific_osname\n    distro_specific_osname=\"$(get_legacy_os_name)\" || return 1\n\n    local legacy_download_link=null\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        legacy_download_link=\"$azure_feed/Runtime/$specific_version/dotnet-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz\"\n    elif [ -z \"$runtime\" ]; then\n        legacy_download_link=\"$azure_feed/Sdk/$specific_version/dotnet-dev-$distro_specific_osname-$normalized_architecture.$specific_version.tar.gz\"\n    else\n        return 1\n    fi\n\n    echo \"$legacy_download_link\"\n    return 0\n}\n\nget_user_install_path() {\n    eval $invocation\n\n    if [ ! -z \"${DOTNET_INSTALL_DIR:-}\" ]; then\n        echo \"$DOTNET_INSTALL_DIR\"\n    else\n        echo \"$HOME/.dotnet\"\n    fi\n    return 0\n}\n\n# args:\n# install_dir - $1\nresolve_installation_path() {\n    eval $invocation\n\n    local install_dir=$1\n    if [ \"$install_dir\" = \"<auto>\" ]; then\n        local user_install_path=\"$(get_user_install_path)\"\n        say_verbose \"resolve_installation_path: user_install_path=$user_install_path\"\n        echo \"$user_install_path\"\n        return 0\n    fi\n\n    echo \"$install_dir\"\n    return 0\n}\n\n# args:\n# install_root - $1\nget_installed_version_info() {\n    eval $invocation\n\n    local install_root=\"$1\"\n    local version_file=\"$(combine_paths \"$install_root\" \"$local_version_file_relative_path\")\"\n    say_verbose \"Local version file: $version_file\"\n    if [ ! -z \"$version_file\" ] | [ -r \"$version_file\" ]; then\n        local version_info=\"$(cat \"$version_file\")\"\n        echo \"$version_info\"\n        return 0\n    fi\n\n    say_verbose \"Local version file not found.\"\n    return 0\n}\n\n# args:\n# relative_or_absolute_path - $1\nget_absolute_path() {\n    eval $invocation\n\n    local relative_or_absolute_path=$1\n    echo \"$(cd \"$(dirname \"$1\")\" && pwd -P)/$(basename \"$1\")\"\n    return 0\n}\n\n# args:\n# input_files - stdin\n# root_path - $1\n# out_path - $2\n# override - $3\ncopy_files_or_dirs_from_list() {\n    eval $invocation\n\n    local root_path=\"$(remove_trailing_slash \"$1\")\"\n    local out_path=\"$(remove_trailing_slash \"$2\")\"\n    local override=\"$3\"\n    local osname=\"$(get_current_os_name)\"\n    local override_switch=$(\n        if [ \"$override\" = false ]; then\n            if [[ \"$osname\" == \"linux-musl\" ]]; then\n                printf -- \"-u\";\n            else\n                printf -- \"-n\";\n            fi\n        fi)\n\n    cat | uniq | while read -r file_path; do\n        local path=\"$(remove_beginning_slash \"${file_path#$root_path}\")\"\n        local target=\"$out_path/$path\"\n        if [ \"$override\" = true ] || (! ([ -d \"$target\" ] || [ -e \"$target\" ])); then\n            mkdir -p \"$out_path/$(dirname \"$path\")\"\n            cp -R $override_switch \"$root_path/$path\" \"$target\"\n        fi\n    done\n}\n\n# args:\n# zip_path - $1\n# out_path - $2\nextract_dotnet_package() {\n    eval $invocation\n\n    local zip_path=\"$1\"\n    local out_path=\"$2\"\n\n    local temp_out_path=\"$(mktemp -d \"$temporary_file_template\")\"\n\n    local failed=false\n    tar -xzf \"$zip_path\" -C \"$temp_out_path\" > /dev/null || failed=true\n\n    local folders_with_version_regex='^.*/[0-9]+\\.[0-9]+[^/]+/'\n    find \"$temp_out_path\" -type f | grep -Eo \"$folders_with_version_regex\" | sort | copy_files_or_dirs_from_list \"$temp_out_path\" \"$out_path\" false\n    find \"$temp_out_path\" -type f | grep -Ev \"$folders_with_version_regex\" | copy_files_or_dirs_from_list \"$temp_out_path\" \"$out_path\" \"$override_non_versioned_files\"\n\n    rm -rf \"$temp_out_path\"\n\n    if [ \"$failed\" = true ]; then\n        say_err \"Extraction failed\"\n        return 1\n    fi\n}\n\n# args:\n# remote_path - $1\n# [out_path] - $2 - stdout if not provided\ndownload() {\n    eval $invocation\n\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    local failed=false\n    if machine_has \"curl\"; then\n        downloadcurl \"$remote_path\" \"$out_path\" || failed=true\n    elif machine_has \"wget\"; then\n        downloadwget \"$remote_path\" \"$out_path\" || failed=true\n    else\n        failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Download failed: $remote_path\"\n        return 1\n    fi\n    return 0\n}\n\ndownloadcurl() {\n    eval $invocation\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    # Append feed_credential as late as possible before calling curl to avoid logging feed_credential\n    remote_path=\"${remote_path}${feed_credential}\"\n\n    local failed=false\n    if [ -z \"$out_path\" ]; then\n        curl --retry 10 -sSL -f --create-dirs \"$remote_path\" || failed=true\n    else\n        curl --retry 10 -sSL -f --create-dirs -o \"$out_path\" \"$remote_path\" || failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Curl download failed\"\n        return 1\n    fi\n    return 0\n}\n\ndownloadwget() {\n    eval $invocation\n    local remote_path=\"$1\"\n    local out_path=\"${2:-}\"\n\n    # Append feed_credential as late as possible before calling wget to avoid logging feed_credential\n    remote_path=\"${remote_path}${feed_credential}\"\n\n    local failed=false\n    if [ -z \"$out_path\" ]; then\n        wget -q --tries 10 -O - \"$remote_path\" || failed=true\n    else\n        wget --tries 10 -O \"$out_path\" \"$remote_path\" || failed=true\n    fi\n    if [ \"$failed\" = true ]; then\n        say_verbose \"Wget download failed\"\n        return 1\n    fi\n    return 0\n}\n\ncalculate_vars() {\n    eval $invocation\n    valid_legacy_download_link=true\n\n    normalized_architecture=\"$(get_normalized_architecture_from_architecture \"$architecture\")\"\n    say_verbose \"normalized_architecture=$normalized_architecture\"\n\n    specific_version=\"$(get_specific_version_from_version \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$version\")\"\n    say_verbose \"specific_version=$specific_version\"\n    if [ -z \"$specific_version\" ]; then\n        say_err \"Could not get version information.\"\n        return 1\n    fi\n\n    download_link=\"$(construct_download_link \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$specific_version\")\"\n    say_verbose \"download_link=$download_link\"\n\n    legacy_download_link=\"$(construct_legacy_download_link \"$azure_feed\" \"$channel\" \"$normalized_architecture\" \"$specific_version\")\" || valid_legacy_download_link=false\n\n    if [ \"$valid_legacy_download_link\" = true ]; then\n        say_verbose \"legacy_download_link=$legacy_download_link\"\n    else\n        say_verbose \"Cound not construct a legacy_download_link; omitting...\"\n    fi\n\n    install_root=\"$(resolve_installation_path \"$install_dir\")\"\n    say_verbose \"install_root=$install_root\"\n}\n\ninstall_dotnet() {\n    eval $invocation\n    local download_failed=false\n    local asset_name=''\n    local asset_relative_path=''\n\n    if [[ \"$runtime\" == \"dotnet\" ]]; then\n        asset_relative_path=\"shared/Microsoft.NETCore.App\"\n        asset_name=\".NET Core Runtime\"\n    elif [[ \"$runtime\" == \"aspnetcore\" ]]; then\n        asset_relative_path=\"shared/Microsoft.AspNetCore.App\"\n        asset_name=\"ASP.NET Core Runtime\"\n    elif [ -z \"$runtime\" ]; then\n        asset_relative_path=\"sdk\"\n        asset_name=\".NET Core SDK\"\n    else\n        say_err \"Invalid value for \\$runtime\"\n        return 1\n    fi\n\n    #  Check if the SDK version is already installed.\n    if is_dotnet_package_installed \"$install_root\" \"$asset_relative_path\" \"$specific_version\"; then\n        say \"$asset_name version $specific_version is already installed.\"\n        return 0\n    fi\n\n    mkdir -p \"$install_root\"\n    zip_path=\"$(mktemp \"$temporary_file_template\")\"\n    say_verbose \"Zip path: $zip_path\"\n\n    say \"Downloading link: $download_link\"\n\n    # Failures are normal in the non-legacy case for ultimately legacy downloads.\n    # Do not output to stderr, since output to stderr is considered an error.\n    download \"$download_link\" \"$zip_path\" 2>&1 || download_failed=true\n\n    #  if the download fails, download the legacy_download_link\n    if [ \"$download_failed\" = true ]; then\n        say \"Cannot download: $download_link\"\n\n        if [ \"$valid_legacy_download_link\" = true ]; then\n            download_failed=false\n            download_link=\"$legacy_download_link\"\n            zip_path=\"$(mktemp \"$temporary_file_template\")\"\n            say_verbose \"Legacy zip path: $zip_path\"\n            say \"Downloading legacy link: $download_link\"\n            download \"$download_link\" \"$zip_path\" 2>&1 || download_failed=true\n        fi\n    fi\n\n    if [ \"$download_failed\" = true ]; then\n        say_err \"Could not download $asset_name version $specific_version\"\n        return 1\n    fi\n\n    say \"Extracting zip from $download_link\"\n    extract_dotnet_package \"$zip_path\" \"$install_root\"\n\n    #  Check if the SDK version is now installed; if not, fail the installation.\n    if ! is_dotnet_package_installed \"$install_root\" \"$asset_relative_path\" \"$specific_version\"; then\n        say_err \"$asset_name version $specific_version failed to install with an unknown error.\"\n        return 1\n    fi\n\n    return 0\n}\n\nlocal_version_file_relative_path=\"/.version\"\nbin_folder_relative_path=\"\"\ntemporary_file_template=\"${TMPDIR:-/tmp}/dotnet.XXXXXXXXX\"\n\nchannel=\"LTS\"\nversion=\"Latest\"\ninstall_dir=\"<auto>\"\narchitecture=\"<auto>\"\ndry_run=false\nno_path=false\nazure_feed=\"https://dotnetcli.azureedge.net/dotnet\"\nuncached_feed=\"https://dotnetcli.blob.core.windows.net/dotnet\"\nfeed_credential=\"\"\nverbose=false\nruntime=\"\"\nruntime_id=\"\"\noverride_non_versioned_files=true\n\nwhile [ $# -ne 0 ]\ndo\n    name=\"$1\"\n    case \"$name\" in\n        -c|--channel|-[Cc]hannel)\n            shift\n            channel=\"$1\"\n            ;;\n        -v|--version|-[Vv]ersion)\n            shift\n            version=\"$1\"\n            ;;\n        -i|--install-dir|-[Ii]nstall[Dd]ir)\n            shift\n            install_dir=\"$1\"\n            ;;\n        --arch|--architecture|-[Aa]rch|-[Aa]rchitecture)\n            shift\n            architecture=\"$1\"\n            ;;\n        --shared-runtime|-[Ss]hared[Rr]untime)\n            say_warning \"The --shared-runtime flag is obsolete and may be removed in a future version of this script. The recommended usage is to specify '--runtime dotnet'.\"\n            if [ -z \"$runtime\" ]; then\n                runtime=\"dotnet\"\n            fi\n            ;;\n        --runtime|-[Rr]untime)\n            shift\n            runtime=\"$1\"\n            if [[ \"$runtime\" != \"dotnet\" ]] && [[ \"$runtime\" != \"aspnetcore\" ]]; then\n                say_err \"Unsupported value for --runtime: '$1'. Valid values are 'dotnet' and 'aspnetcore'.\"\n                exit 1\n            fi\n            ;;\n        --dry-run|-[Dd]ry[Rr]un)\n            dry_run=true\n            ;;\n        --no-path|-[Nn]o[Pp]ath)\n            no_path=true\n            ;;\n        --verbose|-[Vv]erbose)\n            verbose=true\n            ;;\n        --azure-feed|-[Aa]zure[Ff]eed)\n            shift\n            azure_feed=\"$1\"\n            ;;\n        --uncached-feed|-[Uu]ncached[Ff]eed)\n            shift\n            uncached_feed=\"$1\"\n            ;;\n        --feed-credential|-[Ff]eed[Cc]redential)\n            shift\n            feed_credential=\"$1\"\n            ;;\n        --runtime-id|-[Rr]untime[Ii]d)\n            shift\n            runtime_id=\"$1\"\n            ;;\n        --skip-non-versioned-files|-[Ss]kip[Nn]on[Vv]ersioned[Ff]iles)\n            override_non_versioned_files=false\n            ;;\n        -?|--?|-h|--help|-[Hh]elp)\n            script_name=\"$(basename \"$0\")\"\n            echo \".NET Tools Installer\"\n            echo \"Usage: $script_name [-c|--channel <CHANNEL>] [-v|--version <VERSION>] [-p|--prefix <DESTINATION>]\"\n            echo \"       $script_name -h|-?|--help\"\n            echo \"\"\n            echo \"$script_name is a simple command line interface for obtaining dotnet cli.\"\n            echo \"\"\n            echo \"Options:\"\n            echo \"  -c,--channel <CHANNEL>         Download from the channel specified, Defaults to \\`$channel\\`.\"\n            echo \"      -Channel\"\n            echo \"          Possible values:\"\n            echo \"          - Current - most current release\"\n            echo \"          - LTS - most current supported release\"\n            echo \"          - 2-part version in a format A.B - represents a specific release\"\n            echo \"              examples: 2.0; 1.0\"\n            echo \"          - Branch name\"\n            echo \"              examples: release/2.0.0; Master\"\n            echo \"  -v,--version <VERSION>         Use specific VERSION, Defaults to \\`$version\\`.\"\n            echo \"      -Version\"\n            echo \"          Possible values:\"\n            echo \"          - latest - most latest build on specific channel\"\n            echo \"          - coherent - most latest coherent build on specific channel\"\n            echo \"              coherent applies only to SDK downloads\"\n            echo \"          - 3-part version in a format A.B.C - represents specific version of build\"\n            echo \"              examples: 2.0.0-preview2-006120; 1.1.0\"\n            echo \"  -i,--install-dir <DIR>             Install under specified location (see Install Location below)\"\n            echo \"      -InstallDir\"\n            echo \"  --architecture <ARCHITECTURE>      Architecture of dotnet binaries to be installed, Defaults to \\`$architecture\\`.\"\n            echo \"      --arch,-Architecture,-Arch\"\n            echo \"          Possible values: x64, arm, and arm64\"\n            echo \"  --runtime <RUNTIME>                Installs a shared runtime only, without the SDK.\"\n            echo \"      -Runtime\"\n            echo \"          Possible values:\"\n            echo \"          - dotnet     - the Microsoft.NETCore.App shared runtime\"\n            echo \"          - aspnetcore - the Microsoft.AspNetCore.App shared runtime\"\n            echo \"  --skip-non-versioned-files         Skips non-versioned files if they already exist, such as the dotnet executable.\"\n            echo \"      -SkipNonVersionedFiles\"\n            echo \"  --dry-run,-DryRun                  Do not perform installation. Display download link.\"\n            echo \"  --no-path, -NoPath                 Do not set PATH for the current process.\"\n            echo \"  --verbose,-Verbose                 Display diagnostics information.\"\n            echo \"  --azure-feed,-AzureFeed            Azure feed location. Defaults to $azure_feed, This parameter typically is not changed by the user.\"\n            echo \"  --uncached-feed,-UncachedFeed      Uncached feed location. This parameter typically is not changed by the user.\"\n            echo \"  --feed-credential,-FeedCredential  Azure feed shared access token. This parameter typically is not specified.\"\n            echo \"  --runtime-id                       Installs the .NET Tools for the given platform (use linux-x64 for portable linux).\"\n            echo \"      -RuntimeId\"\n            echo \"  -?,--?,-h,--help,-Help             Shows this help message\"\n            echo \"\"\n            echo \"Obsolete parameters:\"\n            echo \"  --shared-runtime                   The recommended alternative is '--runtime dotnet'.\"\n            echo \"      -SharedRuntime                 Installs just the shared runtime bits, not the entire SDK.\"\n            echo \"\"\n            echo \"Install Location:\"\n            echo \"  Location is chosen in following order:\"\n            echo \"    - --install-dir option\"\n            echo \"    - Environmental variable DOTNET_INSTALL_DIR\"\n            echo \"    - $HOME/.dotnet\"\n            exit 0\n            ;;\n        *)\n            say_err \"Unknown argument \\`$name\\`\"\n            exit 1\n            ;;\n    esac\n\n    shift\ndone\n\ncheck_min_reqs\ncalculate_vars\n\nif [ \"$dry_run\" = true ]; then\n    say \"Payload URL: $download_link\"\n    if [ \"$valid_legacy_download_link\" = true ]; then\n        say \"Legacy payload URL: $legacy_download_link\"\n    fi\n    say \"Repeatable invocation: ./$(basename \"$0\") --version $specific_version --channel $channel --install-dir $install_dir\"\n    exit 0\nfi\n\ncheck_pre_reqs\ninstall_dotnet\n\nbin_path=\"$(get_absolute_path \"$(combine_paths \"$install_root\" \"$bin_folder_relative_path\")\")\"\nif [ \"$no_path\" = false ]; then\n    say \"Adding to current process PATH: \\`$bin_path\\`. Note: This change will be visible only when sourcing script.\"\n    export PATH=\"$bin_path\":\"$PATH\"\nelse\n    say \"Binaries of dotnet can be found in $bin_path\"\nfi\n\nsay \"Installation finished successfully.\"", "num_lines": 976}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmkdir ~/github\ncd ~/github\ngit clone https://github.com/Azure/azure-functions-host.git\ncd azure-functions-host\ngit checkout dev\n\ncd tools/Crank/Agent\nsudo find . -name \"*.sh\" -exec sudo chmod +xr {} \\;\nsudo find . -name \"*.ps1\" -exec sudo chmod +xr {} \\;\n\nLinux/install-powershell.sh\n\n./setup-crank-agent-raw.ps1 $1 -Verbose\n", "num_lines": 16}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Following instructions at https://docs.docker.com/engine/install/ubuntu\n\nsudo apt-get update\n\nsudo apt-get install -y \\\n    apt-transport-https \\\n    ca-certificates \\\n    curl \\\n    gnupg-agent \\\n    software-properties-common\n\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n\nsudo add-apt-repository \\\n   \"deb [arch=amd64] https://download.docker.com/linux/ubuntu \\\n   $(lsb_release -cs) \\\n   stable\"\n\nsudo apt-get update\nsudo apt-get install -y docker-ce docker-ce-cli containerd.io\n\nsudo groupadd docker\nsudo usermod -aG docker Functions\nnewgrp docker\n\nsudo setfacl --modify user:Functions:rw /var/run/docker.sock\n\nsudo systemctl enable docker\n", "num_lines": 31}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# From https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7#ubuntu-1804\n\n# Download the Microsoft repository GPG keys\nwget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb\n\n# Register the Microsoft repository GPG keys\nsudo dpkg -i packages-microsoft-prod.deb\n\n# Update the list of products\nsudo apt-get update\n\n# Enable the \"universe\" repositories\nsudo add-apt-repository universe\n\n# Install PowerShell\nsudo apt-get install -y powershell\n", "num_lines": 19}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ndocker build -t functions-crank-agent -f Dockerfile ../../\n", "num_lines": 4}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ndocker run -it --name functions-crank-agent -d --network host --restart always --privileged \\\n--mount type=bind,source=/home/Functions/FunctionApps/HelloApp,target=/home/Functions/FunctionApps/HelloApp \\\n-v /var/run/docker.sock:/var/run/docker.sock functions-crank-agent \"$@\"", "num_lines": 5}
{"repo_name": "azure-functions-host", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ndocker stop functions-crank-agent\ndocker rm functions-crank-agent\n", "num_lines": 5}
{"repo_name": "azure-functions-jupyter-worker", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Simple tool to help for release\n# when releasing with bash, simple source it to get asked questions. \n\n# misc check before starting\n\npython -c 'import keyring'\npython -c 'import twine'\npython -c 'import sphinx'\npython -c 'import sphinx_rtd_theme'\npython -c 'import nose'\n\n\nBLACK=$(tput setaf 1)\nRED=$(tput setaf 1)\nGREEN=$(tput setaf 2)\nYELLOW=$(tput setaf 3)\nBLUE=$(tput setaf 4)\nMAGENTA=$(tput setaf 5)\nCYAN=$(tput setaf 6)\nWHITE=$(tput setaf 7)\nNOR=$(tput sgr0)\n\n\necho -n \"PREV_RELEASE (X.y.z) [$PREV_RELEASE]: \"\nread input\nPREV_RELEASE=${input:-$PREV_RELEASE}\necho -n \"MILESTONE (X.y) [$MILESTONE]: \"\nread input\nMILESTONE=${input:-$MILESTONE}\necho -n \"VERSION (X.y.z) [$VERSION]:\"\nread input\nVERSION=${input:-$VERSION}\necho -n \"BRANCH (master|X.y) [$BRANCH]:\"\nread input\nBRANCH=${input:-$BRANCH}\n\nask_section(){\n    echo\n    echo $BLUE\"$1\"$NOR \n    echo -n $GREEN\"Press Enter to continue, S to skip: \"$NOR\n    read -n1 value\n    echo \n    if [ -z $value ] || [ $value = 'y' ]  ; then\n        return 0\n    fi\n    return 1\n}\n\n\n\necho \nif ask_section \"Updating what's new with informations from docs/source/whatsnew/pr\"\nthen\n    python tools/update_whatsnew.py\n\n    echo\n    echo $BLUE\"please move the contents of \"docs/source/whatsnew/development.rst\" to version-X.rst\"$NOR\n    echo $GREEN\"Press enter to continue\"$NOR\n    read\nfi\n\nif ask_section \"Gen Stats, and authors\"\nthen\n\n    echo \n    echo $BLUE\"here are all the authors that contributed to this release:\"$NOR\n    git log --format=\"%aN <%aE>\" $PREV_RELEASE... | sort -u -f\n\n    echo \n    echo $BLUE\"If you see any duplicates cancel (Ctrl-C), then edit .mailmap.\"\n    echo $GREEN\"Press enter to continue:\"$NOR\n    read\n\n    echo $BLUE\"generating stats\"$NOR\n    python tools/github_stats.py --milestone $MILESTONE > stats.rst\n\n    echo $BLUE\"stats.rst files generated.\"$NOR\n    echo $GREEN\"Please merge it with the right file (github-stats-X.rst) and commit.\"$NOR\n    echo $GREEN\"press enter to continue.\"$NOR\n    read\n\nfi\n\necho \"Cleaning repository\"\ngit clean -xfdi\n\necho $GREEN\"please update version number in ${RED}IPython/core/release.py${NOR} , Do not commit yet \u00e2\u20ac\u201c\u00c2\u00a0we'll do it later.\"$NOR\n\necho $GREEN\"Press enter to continue\"$NOR\nread\n\nif ask_section \"Build the documentation ?\"\nthen\n    make html -C docs\n    echo \n    echo $GREEN\"Check the docs, press enter to continue\"$NOR\n    read\n\nfi\n\necho\necho $BLUE\"Attempting to build package...\"$NOR\n\ntools/build_release\nrm dist/*\n\nif ask_section \"Should we commit, tag, push... etc ? \"\nthen\n   echo\n   echo $BLUE\"Let's commit : git commit -am \\\"release $VERSION\\\" -S\"\n   echo $GREEN\"Press enter to commit\"$NOR\n   read\n   git commit -am \"release $VERSION\" -S\n   \n   echo\n   echo $BLUE\"git push origin \\$BRANCH ($BRANCH)?\"$NOR\n   echo $GREEN\"Make sure you can push\"$NOR\n   echo $GREEN\"Press enter to continue\"$NOR\n   read\n   git push origin $BRANCH\n   \n   echo\n   echo \"Let's tag : git tag -am \\\"release $VERSION\\\" \\\"$VERSION\\\" -s\"\n   echo $GREEN\"Press enter to tag commit\"$NOR\n   read\n   git tag -am \"release $VERSION\" \"$VERSION\" -s\n   \n   echo\n   echo $BLUE\"And push the tag: git push origin \\$VERSION ?\"$NOR\n   echo $GREEN\"Press enter to continue\"$NOR\n   read\n   git push origin $VERSION\n   \n   \n   echo $GREEN\"please update version number and back to .dev in ${RED}IPython/core/release.py\"\n   echo ${BLUE}\"Do not commit yet \u00e2\u20ac\u201c\u00c2\u00a0we'll do it later.\"$NOR\n   \n   echo $GREEN\"Press enter to continue\"$NOR\n   read\n   \n   echo\n   echo \"Let's commit : \"$BLUE\"git commit -am \\\"back to dev\\\"\"$NOR\n   echo $GREEN\"Press enter to commit\"$NOR\n   read\n   git commit -am \"back to dev\"\n\n   echo\n   echo $BLUE\"git push origin \\$BRANCH ($BRANCH)?\"$NOR\n   echo $GREEN\"Press enter to continue\"$NOR\n   read\n   git push origin $BRANCH\n\n   \n   echo\n   echo $BLUE\"let's : git checkout $VERSION\"$NOR\n   echo $GREEN\"Press enter to continue\"$NOR\n   read\n   git checkout $VERSION\nfi\n\nif ask_section \"Should we build and release ?\"\nthen\n\n    echo\n    echo $BLUE\"Attempting to build package...\"$NOR\n\n    tools/release\n\n    echo $RED\n    echo '$ shasum -a 256 dist/*'\n    shasum -a 256 dist/*\n    echo $NOR\n\n    if ask_section \"upload packages ?\"\n    then \n       tools/release upload\n    fi\nfi\n", "num_lines": 179}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCURRENT_DIR=`pwd`\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\ncd $DIR/..\n\nWORKING_DIR=temp\nif [ -d \"$WORKING_DIR\" ]; then rm -rf $WORKING_DIR; fi\n\ndotnet pack -o temp --include-symbols src/Microsoft.Azure.WebJobs.Extensions.Kafka/Microsoft.Azure.WebJobs.Extensions.Kafka.csproj /p:Version=100.100.100-pre\n\ncd $CURRENT_DIR\n\ndocker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/java/EventHub/Dockerfile -t azure-functions-kafka-java-eventhub .\ndocker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/python/EventHub/Dockerfile -t azure-functions-kafka-python-eventhub .\n\ndocker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/java/Confluent/Dockerfile -t azure-functions-kafka-java-confluent .\ndocker build -f ./test/Microsoft.Azure.WebJobs.Extensions.Kafka.LangEndToEndTests/FunctionApps/python/Confluent/Dockerfile -t azure-functions-kafka-python-confluent .", "num_lines": 18}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport COMPOSE_INTERACTIVE_NO_CLI=1\n\n# start docker compose\ndocker-compose -f ./kafka-singlenode-compose.yaml  up --build -d\n\n# wait until kafka is ready to create topic\n# need to improve, adding a retry instead of a static sleep\nsleep 30", "num_lines": 10}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport COMPOSE_INTERACTIVE_NO_CLI=1\n\n# start docker compose\ndocker-compose -f ./kafka-singlenode-compose.yaml  down\n", "num_lines": 7}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "func start", "num_lines": 1}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "func start", "num_lines": 1}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport COMPOSE_INTERACTIVE_NO_CLI=1\n\n# start docker compose\ndocker-compose up -d\n\n# wait until kafka is ready to create topic\n# need to improve, adding a retry instead of a static sleep\nsleep 30\n\ndocker ps", "num_lines": 12}
{"repo_name": "azure-functions-kafka-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nfunc start", "num_lines": 2}
{"repo_name": "azure-functions-openapi-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nfunction usage() {\n    cat <<USAGE\n    Usage: $0 <options>\n    Options:\n        [-p|--functionapp-path] Function app path, relative to the repository root. It can be the project directory or compiled app directory.\n                                Default: '.'\n        [-u|--base-uri]         Base URI of the function app.\n                                Default: 'http://localhost:7071/api/'\n        [-e|--endpoint]         OpenAPI document endpoint.\n                                Default: 'swagger.json'\n        [-o|--output-path]      Output directory to store the generated OpenAPI document, relative to the repository root.\n                                Default: 'generated'\n        [-f|--output-filename]  Output filename for the generated OpenAPI document.\n                                Default: 'swagger.json'\n        [-d|--delay]            Delay in second between the function app run and document generation.\n                                Default: 30\n        [-c|--use-codespaces]   Switch indicating whether to use GitHub Codespaces or not.\n        [-h|--help]             Show this message.\nUSAGE\n\n    exit 1\n}\n\nfunctionapp_path=\".\"\nbase_uri=\"http://localhost:7071/api/\"\nendpoint=\"swagger.json\"\noutput_path=\"generated\"\noutput_filename=\"swagger.json\"\ndelay=30\nrepository_root=$GITHUB_WORKSPACE\n\nif [[ $# -eq 0 ]]; then\n    functionapp_path=\".\"\n    base_uri=\"http://localhost:7071/api/\"\n    endpoint=\"swagger.json\"\n    output_path=\"generated\"\n    output_filename=\"swagger.json\"\n    delay=30\n    repository_root=$GITHUB_WORKSPACE\nfi\n\nwhile [[ \"$1\" != \"\" ]]; do\n    case $1 in\n    -p | --functionapp-path)\n        shift\n        functionapp_path=$1\n        ;;\n\n    -u | --base-uri)\n        shift\n        base_uri=$1\n        ;;\n\n    -e | --endpoint)\n        shift\n        endpoint=$1\n        ;;\n\n    -o | --output-path)\n        shift\n        output_path=$1\n        ;;\n\n    -f | --output-filename)\n        shift\n        output_filename=$1\n        ;;\n\n    -d | --delay)\n        shift\n        delay=$1\n        ;;\n\n    -c | --use_codespaces)\n        repository_root=$CODESPACE_VSCODE_FOLDER\n        ;;\n\n    -h | --help)\n        usage\n        exit 1\n        ;;\n\n    *)\n        usage\n        exit 1\n        ;;\n    esac\n\n    shift\ndone\n\ncurrent_directory=$(pwd)\n\ncd \"$repository_root/$functionapp_path\"\n\n# Run the function app in the background\nfunc start --verbose false &\n\nsleep $delay\n\nrequest_uri=\"$(echo \"$base_uri\" | sed 's:/*$::')/$(echo \"$endpoint\" | sed 's:^/*::')\"\nfilepath=\"$repository_root/$(echo \"$output_path\" | sed 's:/*$::')/$(echo \"$output_filename\" | sed 's:^/*::')\"\n\nif [ ! -d \"$repository_root/$output_path\" ]; then\n    mkdir \"$repository_root/$output_path\"\nfi\n\n# Download the OpenAPI document\ncurl $request_uri > $filepath\n\n# Stop the function app\nPID=$(lsof -nP -i4TCP:7071 | grep LISTEN | awk '{print $2}')\nif [[ \"\" !=  \"$PID\" ]]; then\n    kill -9 $PID\nfi\n\ncd $current_directory\n", "num_lines": 122}
{"repo_name": "azure-functions-python-worker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\npython -m venv .env\nsource .env/bin/activate\npython -m pip install --upgrade pip==23.0\n\npython -m pip install .\n\npython -m pip install . --no-compile --target \"$BUILD_SOURCESDIRECTORY/deps\"", "num_lines": 9}
{"repo_name": "azure-functions-python-worker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# $1 controls whether we allow reload module (\"true\" or \"false\")\n\nSCRIPT_DIR=\"$(dirname $0)\"\nexport PYTHONPATH=\"$SCRIPT_DIR/namespace_location_a:$SCRIPT_DIR/namespace_location_b\"\n\npython $SCRIPT_DIR/azure_namespace_import.py $1\n\nunset PYTHONPATH", "num_lines": 10}
{"repo_name": "azure-functions-python-worker", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# $2 is sys.path from caller\nexport PYTHONPATH=\"test_module_dir:$2\"\nSCRIPT_DIR=\"$(dirname $0)\"\n\npython $SCRIPT_DIR/path_import.py $1\n\nunset PYTHONPATH", "num_lines": 9}
{"repo_name": "azure-functions-signalrservice-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Call \"sync\" between \"chmod\" and execution to prevent \"text file busy\" error in Docker (aufs)\nchmod +x \"$DIR/run.sh\"; sync\n\"$DIR/run.sh\" default-build \"$@\"\n", "num_lines": 9}
{"repo_name": "azure-functions-signalrservice-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\n#\n# variables\n#\n\nRESET=\"\\033[0m\"\nRED=\"\\033[0;31m\"\nYELLOW=\"\\033[0;33m\"\nMAGENTA=\"\\033[0;95m\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n[ -z \"${DOTNET_HOME:-}\" ] && DOTNET_HOME=\"$HOME/.dotnet\"\nverbose=false\nupdate=false\nreinstall=false\nrepo_path=\"$DIR\"\nchannel=''\ntools_source=''\ntools_source_suffix=''\nci=false\n\n#\n# Functions\n#\n__usage() {\n    echo \"Usage: $(basename \"${BASH_SOURCE[0]}\") command [options] [[--] <Arguments>...]\"\n    echo \"\"\n    echo \"Arguments:\"\n    echo \"    command                The command to be run.\"\n    echo \"    <Arguments>...         Arguments passed to the command. Variable number of arguments allowed.\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"    --verbose                                             Show verbose output.\"\n    echo \"    -c|--channel <CHANNEL>                                The channel of KoreBuild to download. Overrides the value from the config file..\"\n    echo \"    --config-file <FILE>                                  The path to the configuration file that stores values. Defaults to korebuild.json.\"\n    echo \"    -d|--dotnet-home <DIR>                                The directory where .NET Core tools will be stored. Defaults to '\\$DOTNET_HOME' or '\\$HOME/.dotnet.\"\n    echo \"    --path <PATH>                                         The directory to build. Defaults to the directory containing the script.\"\n    echo \"    -s|--tools-source|-ToolsSource <URL>                  The base url where build tools can be downloaded. Overrides the value from the config file.\"\n    echo \"    --tools-source-suffix|-ToolsSourceSuffix <SUFFIX>     The suffix to append to tools-source. Useful for query strings.\"\n    echo \"    -u|--update                                           Update to the latest KoreBuild even if the lock file is present.\"\n    echo \"    --reinstall                                           Reinstall KoreBuild.\"\n    echo \"    --ci                                                  Apply CI specific settings and environment variables.\"\n    echo \"\"\n    echo \"Description:\"\n    echo \"    This function will create a file \\$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be.\"\n    echo \"    When the lockfile is not present, KoreBuild will create one using latest available version from \\$channel.\"\n\n    if [[ \"${1:-}\" != '--no-exit' ]]; then\n        exit 2\n    fi\n}\n\nget_korebuild() {\n    local version\n    local lock_file=\"$repo_path/korebuild-lock.txt\"\n    if [ ! -f \"$lock_file\" ] || [ \"$update\" = true ]; then\n        __get_remote_file \"$tools_source/korebuild/channels/$channel/latest.txt\" \"$lock_file\" \"$tools_source_suffix\"\n    fi\n    version=\"$(grep 'version:*' -m 1 \"$lock_file\")\"\n    if [[ \"$version\" == '' ]]; then\n        __error \"Failed to parse version from $lock_file. Expected a line that begins with 'version:'\"\n        return 1\n    fi\n    version=\"$(echo \"${version#version:}\" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')\"\n    local korebuild_path=\"$DOTNET_HOME/buildtools/korebuild/$version\"\n\n    if [ \"$reinstall\" = true ] && [ -d \"$korebuild_path\" ]; then\n        rm -rf \"$korebuild_path\"\n    fi\n\n    {\n        if [ ! -d \"$korebuild_path\" ]; then\n            mkdir -p \"$korebuild_path\"\n            local remote_path=\"$tools_source/korebuild/artifacts/$version/korebuild.$version.zip\"\n            tmpfile=\"$(mktemp)\"\n            echo -e \"${MAGENTA}Downloading KoreBuild ${version}${RESET}\"\n            if __get_remote_file \"$remote_path\" \"$tmpfile\" \"$tools_source_suffix\"; then\n                unzip -q -d \"$korebuild_path\" \"$tmpfile\"\n            fi\n            rm \"$tmpfile\" || true\n        fi\n        \n        echo \"!!! Hack to use .NET Core SDK 5.0.301\"\n        local filePath=`find $korebuild_path -name sdk.version`\n        echo \"5.0.301\" > $filePath\n\n        source \"$korebuild_path/KoreBuild.sh\"\n    } || {\n        if [ -d \"$korebuild_path\" ]; then\n            echo \"Cleaning up after failed installation\"\n            rm -rf \"$korebuild_path\" || true\n        fi\n        return 1\n    }\n}\n\n__error() {\n    echo -e \"${RED}error: $*${RESET}\" 1>&2\n}\n\n__warn() {\n    echo -e \"${YELLOW}warning: $*${RESET}\"\n}\n\n__machine_has() {\n    hash \"$1\" > /dev/null 2>&1\n    return $?\n}\n\n__get_remote_file() {\n    local remote_path=$1\n    local local_path=$2\n    local remote_path_suffix=$3\n\n    if [[ \"$remote_path\" != 'http'* ]]; then\n        cp \"$remote_path\" \"$local_path\"\n        return 0\n    fi\n\n    local failed=false\n    if __machine_has wget; then\n        wget --tries 10 --quiet -O \"$local_path\" \"${remote_path}${remote_path_suffix}\" || failed=true\n    else\n        failed=true\n    fi\n\n    if [ \"$failed\" = true ] && __machine_has curl; then\n        failed=false\n        curl --retry 10 -sSL -f --create-dirs -o \"$local_path\" \"${remote_path}${remote_path_suffix}\" || failed=true\n    fi\n\n    if [ \"$failed\" = true ]; then\n        __error \"Download failed: $remote_path\" 1>&2\n        return 1\n    fi\n}\n\n#\n# main\n#\n\ncommand=\"${1:-}\"\nshift\n\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        -\\?|-h|--help)\n            __usage --no-exit\n            exit 0\n            ;;\n        -c|--channel|-Channel)\n            shift\n            channel=\"${1:-}\"\n            [ -z \"$channel\" ] && __usage\n            ;;\n        --config-file|-ConfigFile)\n            shift\n            config_file=\"${1:-}\"\n            [ -z \"$config_file\" ] && __usage\n            if [ ! -f \"$config_file\" ]; then\n                __error \"Invalid value for --config-file. $config_file does not exist.\"\n                exit 1\n            fi\n            ;;\n        -d|--dotnet-home|-DotNetHome)\n            shift\n            DOTNET_HOME=\"${1:-}\"\n            [ -z \"$DOTNET_HOME\" ] && __usage\n            ;;\n        --path|-Path)\n            shift\n            repo_path=\"${1:-}\"\n            [ -z \"$repo_path\" ] && __usage\n            ;;\n        -s|--tools-source|-ToolsSource)\n            shift\n            tools_source=\"${1:-}\"\n            [ -z \"$tools_source\" ] && __usage\n            ;;\n        --tools-source-suffix|-ToolsSourceSuffix)\n            shift\n            tools_source_suffix=\"${1:-}\"\n            [ -z \"$tools_source_suffix\" ] && __usage\n            ;;\n        -u|--update|-Update)\n            update=true\n            ;;\n        --reinstall|-[Rr]einstall)\n            reinstall=true\n            ;;\n        --ci|-[Cc][Ii])\n            ci=true\n            ;;\n        --verbose|-Verbose)\n            verbose=true\n            ;;\n        --)\n            shift\n            break\n            ;;\n        *)\n            break\n            ;;\n    esac\n    shift\ndone\n\nif ! __machine_has unzip; then\n    __error 'Missing required command: unzip'\n    exit 1\nfi\n\nif ! __machine_has curl && ! __machine_has wget; then\n    __error 'Missing required command. Either wget or curl is required.'\n    exit 1\nfi\n\n[ -z \"${config_file:-}\" ] && config_file=\"$repo_path/korebuild.json\"\nif [ -f \"$config_file\" ]; then\n    if __machine_has jq ; then\n        if jq '.' \"$config_file\" >/dev/null ; then\n            config_channel=\"$(jq -r 'select(.channel!=null) | .channel' \"$config_file\")\"\n            config_tools_source=\"$(jq -r 'select(.toolsSource!=null) | .toolsSource' \"$config_file\")\"\n        else\n            __error \"$config_file contains invalid JSON.\"\n            exit 1\n        fi\n    elif __machine_has python ; then\n        if python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))\" >/dev/null ; then\n            config_channel=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')\")\"\n            config_tools_source=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')\")\"\n        else\n            __error \"$config_file contains invalid JSON.\"\n            exit 1\n        fi\n    elif __machine_has python3 ; then\n        if python3 -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))\" >/dev/null ; then\n            config_channel=\"$(python3 -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')\")\"\n            config_tools_source=\"$(python3 -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')\")\"\n        else\n            __error \"$config_file contains invalid JSON.\"\n            exit 1\n        fi\n    else\n        __error 'Missing required command: jq or python. Could not parse the JSON file.'\n        exit 1\n    fi\n\n    [ ! -z \"${config_channel:-}\" ] && channel=\"$config_channel\"\n    [ ! -z \"${config_tools_source:-}\" ] && tools_source=\"$config_tools_source\"\nfi\n\n[ -z \"$channel\" ] && channel='master'\n[ -z \"$tools_source\" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools'\n\nget_korebuild\nset_korebuildsettings \"$tools_source\" \"$DOTNET_HOME\" \"$repo_path\" \"$config_file\" \"$ci\"\ninvoke_korebuild_command \"$command\" \"$@\"\n", "num_lines": 261}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -e\n\nchmod 777 *.sh\nsudo apt-get update\nsudo apt-get install -y build-essential libssl-dev libffi-dev libpython3-dev python3-dev python3-pip wget curl\nsudo -H pip3 install --upgrade pip\nsudo -H pip3 install --upgrade blobxfer==1.0.0\nsudo -H pip3 install --upgrade azure-cosmosdb-table==1.0.0\nsudo -H pip3 install --upgrade azure-batch==3.0.0\n", "num_lines": 13}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\nset -e\n\nDATABASE_NAME=$1\nif [ -n \"$AZ_BLAST_DATABASE_NAME\" ]; then\n    DATABASE_NAME=$AZ_BLAST_DATABASE_NAME\nfi\n\nSTORAGE_ACCOUNT=$2\nif [ -n \"$AZ_BLAST_STORAGE_ACCOUNT\" ]; then\n    STORAGE_ACCOUNT=$AZ_BLAST_STORAGE_ACCOUNT\nfi\n\nSTORAGE_KEY=$3\nif [ -n \"$AZ_BLAST_STORAGE_KEY\" ]; then\n    STORAGE_KEY=$AZ_BLAST_STORAGE_KEY\nfi\n\nexport BLOBXFER_STORAGEACCOUNTKEY=$STORAGE_KEY\n\nDATABASE_CONTAINER=$4\nif [ -n \"$AZ_BLAST_DATABASE_CONTAINER\" ]; then\n    DATABASE_CONTAINER=$AZ_BLAST_DATABASE_CONTAINER\nfi\n\nDATABASE_SEGMENT=$5\nif [ -n \"$AZ_BLAST_DATABASE_SEGMENT\" ]; then\n    DATABASE_SEGMENT=$AZ_BLAST_DATABASE_SEGMENT\nfi\n\nALIASED_DATABASES=\"\"\n\nNCBI_URL=\"ftp://ftp.ncbi.nlm.nih.gov/blast/db/\"\n\n# Required for blobxfer\nexport LC_ALL=C.UTF-8\nexport LANG=C.UTF-8\n\nfunction download_db_file()\n{\n    file=$1\n\n    # Fetch the database segment file and md5\n    wget $NCBI_URL/$file\n    wget $NCBI_URL/$file.md5\n\n    # Validate md5\n    md5sum=`md5sum $file | awk -F' ' '{print $1}'`\n    grep -q $md5sum $file.md5\n    if [ $? -ne 0 ]; then\n        echo \"MD5 checksum failed for file $file\"\n        return 1\n    fi\n\n    return 0\n}\n\nfunction import_db_file()\n{\n    file=$1\n    unpack_dir=\"$file.extracted\"\n\n    # Create a tmp dir and unpack the database segment\n    mkdir $unpack_dir\n    cd $unpack_dir\n\n    tar xvfz ../$file\n    if [ $? -ne 0 ]; then\n        echo \"Failed to untar archive $file\"\n    else\n        attempts=0\n        while [ $attempts -lt 3 ]; do\n            retries=$(($attempts+1))\n            # Upload the database segment files to blob\n            blobxfer upload --storage-account $STORAGE_ACCOUNT --storage-account-key \"$BLOBXFER_STORAGEACCOUNTKEY\" --remote-path $DATABASE_CONTAINER --local-path . --include '*.*'\n            if [ $? -ne 0 ]; then\n                echo \"Blob upload failed\"\n                sleep 30 # back off for a bit\n                continue\n            fi\n            break\n        done\n    fi\n\n    # Cleanup tmp files\n    cd ..\n    rm -rf $unpack_dir\n    rm -rf $file*\n\n    return 0\n}\n\nif [ -n \"$DATABASE_SEGMENT\" ]; then\n    db_files=$DATABASE_SEGMENT\nelse\n    # List database files\n    db_files=`curl -s -l $NCBI_URL | grep -v .md5$ | grep ^${DATABASE_NAME}.`\n    if [ $? -ne 0 ]; then\n        echo \"Error listing databases\"\n        exit 1\n    fi\nfi\n\nfor file in $db_files; do\n    download_db_file $file &\ndone\n\nfailures=0\n\nfor job in `jobs -p`; do\n    wait $job || let \"failures+=1\"\ndone\n\nif [ $failures -ne 0 ]; then\n    echo \"One or more database segments failed to download\"\n    exit 1\nfi\n\nfor file in $db_files; do\n    import_db_file $file\ndone\n", "num_lines": 124}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n\nDATABASE_NAME=$1\nif [ -n \"$AZ_BLAST_DATABASE_NAME\" ]; then\n    DATABASE_NAME=$AZ_BLAST_DATABASE_NAME\nfi\n\nSTORAGE_ACCOUNT=$2\nif [ -n \"$AZ_BLAST_STORAGE_ACCOUNT\" ]; then\n    STORAGE_ACCOUNT=$AZ_BLAST_STORAGE_ACCOUNT\nfi\n\nSTORAGE_KEY=$3\nif [ -n \"$AZ_BLAST_STORAGE_KEY\" ]; then\n    STORAGE_KEY=$AZ_BLAST_STORAGE_KEY\nfi\n\nexport BLOBXFER_STORAGEACCOUNTKEY=$STORAGE_KEY\n\nDATABASE_CONTAINER=$4\nif [ -n \"$AZ_BLAST_DATABASE_CONTAINER\" ]; then\n    DATABASE_CONTAINER=$AZ_BLAST_DATABASE_CONTAINER\nfi\n\nDATABASE_LOCATION=/dev/shm\nif [ -n \"$AZ_BLAST_DATABASE_LOCATION\" ]; then\n    DATABASE_LOCATION=$AZ_BLAST_DATABASE_LOCATION\nfi\n\nINCLUDE_PATTERN=\"${DATABASE_NAME}.*\"\nif [ \"$DATABASE_CONTAINER\" != \"blast-databases\" ]; then\n    # We have a dedicated DB container\n    INCLUDE_PATTERN=\"*\"\nfi\n\nOS_MEMORY=4096\nif [ -n \"$AZ_BLAST_OS_MEMORY\" ]; then\n    OS_MEMORY=$$AZ_BLAST_OS_MEMORY\nfi\n\n# Required for blobxfer\nexport LC_ALL=C.UTF-8\nexport LANG=C.UTF-8\n\n# Install pre req packages\nsudo apt-get update\nsudo apt-get install -y build-essential libssl-dev libffi-dev libpython3-dev python3-dev python3-pip wget curl ncbi-blast+\nsudo -H pip3 install --upgrade pip\nsudo -H pip3 install --upgrade blobxfer==1.0.0\nsudo -H pip3 install --upgrade azure-cosmosdb-table==1.0.0\nsudo -H pip3 install --upgrade azure-batch==3.0.0\n\n# Resize the tmpfs ram disk\ntotal_mem=`free -m | awk '/Mem:/ {print $2}'`\ntmpfs_mem=$((total_mem - OS_MEMORY))\nif [ $tmpfs_mem -gt 1024 ]; then\n    sudo mount -o remount,size=${tmpfs_mem}M /dev/shm\n    if [ $? -ne 0 ]; then\n        python3 updatestate.py \"$STORAGE_ACCOUNT\" \"$STORAGE_KEY\" \"allusers\" \"$AZ_BATCH_JOB_ID\" \"Error\" \"Error updating tmpfs\"\n        exit 1\n    fi\n    df -h # debug\nfi\n\npython3 updatestate.py \"$STORAGE_ACCOUNT\" \"$STORAGE_KEY\" \"allusers\" \"$AZ_BATCH_JOB_ID\" \"DownloadingDatabase\"\n\nblobxfer download --storage-account \"$STORAGE_ACCOUNT\" --storage-account-key \"$BLOBXFER_STORAGEACCOUNTKEY\" --remote-path \"$DATABASE_CONTAINER\" --include \"$INCLUDE_PATTERN\" --local-path \"$DATABASE_LOCATION/$DATABASE_NAME\"\n\nresult=$?\n\n# Here we check to see if the database has an alias file, if so\n# then we need to try and download the referenced databases\naliases=\"\"\nif [ -e \"$DATABASE_LOCATION/$DATABASE_NAME/$DATABASE_NAME.nal\" ]; then\n    aliases=\"`cat $DATABASE_LOCATION/$DATABASE_NAME/$DATABASE_NAME.nal | grep '^DBLIST' | sed 's/DBLIST//g' | sed 's/\"//g'`\"\nelif [ -e \"$DATABASE_LOCATION/$DATABASE_NAME/$DATABASE_NAME.pal\" ]; then\n    aliases=\"`cat $DATABASE_LOCATION/$DATABASE_NAME/$DATABASE_NAME.pal | grep '^DBLIST' | sed 's/DBLIST//g' | sed 's/\"//g'`\"\nfi\n\nif [ -n \"$aliases\" ]; then\n    for db in $aliases; do\n        ls $DATABASE_LOCATION/$DATABASE_NAME/$db.* > /dev/null 2>&1\n        if [ $? -ne 0 ]; then\n            # No local database failes, lets download them\n            echo \"Downloading database alias $db\"\n            blobxfer download --storage-account $STORAGE_ACCOUNT --storage-account-key $BLOBXFER_STORAGEACCOUNTKEY --remote-path \"$DATABASE_CONTAINER\" --include \"$db.*\" --local-path \"$DATABASE_LOCATION/$DATABASE_NAME\"\n            result=$?\n            if [ $result -ne 0 ]; then\n                echo \"Failed to download database alias $db\"\n                #break\n            fi\n        fi\n    done\nfi\n\nif [ $result -eq 0 ]; then\n    python3 updatestate.py \"$STORAGE_ACCOUNT\" \"$STORAGE_KEY\" \"allusers\" \"$AZ_BATCH_JOB_ID\" \"Running\"\nelse\n    python3 updatestate.py \"$STORAGE_ACCOUNT\" \"$STORAGE_KEY\" \"allusers\" \"$AZ_BATCH_JOB_ID\" \"Error\" \"Error downloading database\"\nfi\n\nexit $result\n", "num_lines": 105}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexit 0\n", "num_lines": 4}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\n\nnamd_conf=$1\necho Executing $namd_conf...\n\nGFS_DIR=$AZ_BATCH_NODE_SHARED_DIR/gfs/$AZ_BATCH_JOB_ID\ncd $GFS_DIR\n\n# set PEs\nppn=$3\nif [ -z $ppn ]; then\n    ppn=`nproc`\nfi\n\n# calculate total number of processors\nIFS=',' read -ra HOSTS <<< \"$AZ_BATCH_HOST_LIST\"\nnodes=${#HOSTS[@]}\nnp=$(($nodes * $ppn))\n\n# execute NAMD\nsource /opt/intel/compilers_and_libraries/linux/mpi/bin64/mpivars.sh\necho \"Executing namd on $np processors (ppn=$ppn)...\"\nmpirun -np $np -ppn $ppn -hosts $AZ_BATCH_HOST_LIST $NAMD_DIR/namd2 $namd_conf\n\n# move output file to task working directory\nnamd_conf_prefix=${namd_conf%.*}\ncp $namd_conf_prefix*.* $AZ_BATCH_TASK_WORKING_DIR\n", "num_lines": 30}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -x\n\nnamd_conf=$1\necho Executing $namd_conf...\n\nGFS_DIR=$AZ_BATCH_NODE_SHARED_DIR/gfs/$AZ_BATCH_JOB_ID\ncd $GFS_DIR\n\n# set PEs\nppn=$3\nif [ -z $ppn ]; then\n    ppn=`nproc`\nfi\n\n# calculate total number of processors\nIFS=',' read -ra HOSTS <<< \"$AZ_BATCH_HOST_LIST\"\nnodes=${#HOSTS[@]}\nnp=$(($nodes * $ppn))\n\n# create node list\nnodelist=.nodelist.charm\nrm -f $nodelist\ntouch $nodelist\nfor node in \"${HOSTS[@]}\"; do\n    echo host $node >> $nodelist\ndone\n\n# execute NAMD\necho \"Executing namd on $np processors (ppn=$ppn)...\"\n$NAMD_DIR/charmrun ++verbose ++timeout 300 ++batch $ppn ++remote-shell ssh ++p $np ++ppn $ppn ++nodelist $nodelist $NAMD_DIR/namd2 $namd_conf\n\nnamd_conf_prefix=${namd_conf%.*}\ncp $namd_conf_prefix*.* $AZ_BATCH_TASK_WORKING_DIR\n", "num_lines": 36}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\ncd /home/bizdata/fileshare/example ;\n samtools sort -T sorted_reads/B -O bam mapped_reads/B.bam > sorted_reads/B.bam\n", "num_lines": 4}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nsudo rm -r calls\nsudo rm -r sorted_reads\nsudo rm -r mapped_reads\nsudo rm -r report.html\nsnakemake\n", "num_lines": 7}
{"repo_name": "azure-hpc", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n#set -xeuo pipefail\n\nif [[ $(id -u) -ne 0 ]] ; then\n    echo \"Must be run as root\"\n    exit 1\nfi\n\necho \"Script arguments: $@\"\n\nif [ $# != 10 ]; then\n    echo \"Usage: $0 <MasterHostname> <WorkerHostnamePrefix> <WorkerNodeCount> <HPCUserName> <TemplateBaseUrl> <ClusterFilesystem> <ClusterFilesystemStorage> <ImageOffer> <Scheduler> <InstallEasybuild>\"\n    exit 1\nfi\n\n# Set user args\nMASTER_HOSTNAME=$1\nWORKER_HOSTNAME_PREFIX=$2\nWORKER_COUNT=$3\nTEMPLATE_BASE_URL=\"$5\"\nCFS=\"$6\" # None, BeeGFS\nCFS_STORAGE=\"$7\" # None,Storage,SSD\nCFS_STORAGE_LOCATION=\"/data/beegfs/storage\"\nIMAGE_OFFER=\"$8\"\nSCHEDULER=\"$9\"\nINSTALL_EASYBUILD=\"${10}\"\nLAST_WORKER_INDEX=$(($WORKER_COUNT - 1))\n\nif [ \"$CFS_STORAGE\" == \"Storage\" ]; then\n    CFS_STORAGE_LOCATION=\"/data/beegfs/storage\"\nelif [ \"$CFS_STORAGE\" == \"SSD\" ]; then\n    CFS_STORAGE_LOCATION=\"/mnt/resource/storage\"\nfi\n\n# Shares\nSHARE_NFS=/share/nfs\nSHARE_HOME=$SHARE_NFS/home\nSHARE_DATA=$SHARE_NFS/data\nSHARE_CFS=/share/cfs\nBEEGFS_METADATA=/data/beegfs/meta\n\n# Munged\nMUNGE_USER=munge\nMUNGE_GROUP=munge\nMUNGE_VERSION=0.5.11\n\n# SLURM\nSLURM_USER=slurm\nSLURM_UID=6006\nSLURM_GROUP=slurm\nSLURM_GID=6006\nSLURM_VERSION=15-08-1-1\nSLURM_CONF_DIR=$SHARE_DATA/conf\n\n# Hpc User\nHPC_USER=$4\nHPC_UID=7007\nHPC_GROUP=hpc\nHPC_GID=7007\n\n\n# Returns 0 if this node is the master node.\n#\nis_master()\n{\n    hostname | grep \"$MASTER_HOSTNAME\"\n    return $?\n}\n\n\n# Installs all required packages.\n#\ninstall_pkgs()\n{\n    echo \"$IMAGE_OFFER\" | grep -q 'HPC$'\n    if [ $? -eq 0 ]; then\n        rpm --rebuilddb\n        updatedb\n        yum clean all\n        yum -y install epel-release\n        #yum --exclude WALinuxAgent,intel-*,kernel*,*microsoft-*,msft-* -y update\n\n        sed -i.bak -e '28d' /etc/yum.conf\n        sed -i '28i#exclude=kernel*' /etc/yum.conf\n\n        yum -y install zlib zlib-devel bzip2 bzip2-devel bzip2-libs openssl openssl-devel openssl-libs \\\n            nfs-utils rpcbind git libicu libicu-devel make zip unzip mdadm wget gsl bc rpm-build  \\\n            readline-devel pam-devel libXtst.i686 libXtst.x86_64 make.x86_64 sysstat.x86_64 python-pip automake autoconf \\\n            binutils.x86_64 compat-libcap1.x86_64 glibc.i686 glibc.x86_64 \\\n            ksh compat-libstdc++-33 libaio.i686 libaio.x86_64 libaio-devel.i686 libaio-devel.x86_64 \\\n            libgcc.i686 libgcc.x86_64 libstdc++.i686 libstdc++.x86_64 libstdc++-devel.i686 libstdc++-devel.x86_64 \\\n            libXi.i686 libXi.x86_64 gcc gcc-c++ gcc.x86_64 gcc-c++.x86_64 glibc-devel.i686 glibc-devel.x86_64 libtool libxml2-devel mpich-3.2 mpich-3.2-devel\n\n        sed -i.bak -e '28d' /etc/yum.conf\n        sed -i '28iexclude=kernel*' /etc/yum.conf\n    else\n        yum -y install epel-release\n        yum -y install zlib zlib-devel bzip2 bzip2-devel bzip2-libs openssl openssl-devel openssl-libs \\\n            gcc gcc-c++ nfs-utils rpcbind mdadm wget python-pip kernel kernel-devel \\\n            mpich-3.2 mpich-3.2-devel automake autoconf\n    fi\n}\n\n# Partitions all data disks attached to the VM and creates\n# a RAID-0 volume with them.\n#\nsetup_data_disks()\n{\n    mountPoint=\"$1\"\n    filesystem=\"$2\"\n    createdPartitions=\"\"\n\n    # Loop through and partition disks until not found\n    for disk in sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo sdp sdq sdr; do\n        fdisk -l /dev/$disk || break\n        fdisk /dev/$disk << EOF\nn\np\n1\n\n\nt\nfd\nw\nEOF\n        createdPartitions=\"$createdPartitions /dev/${disk}1\"\n    done\n    \n    sleep 30\n\n    # Create RAID-0 volume\n    if [ -n \"$createdPartitions\" ]; then\n        devices=`echo $createdPartitions | wc -w`\n        mdadm --create /dev/md10 --level 0 --raid-devices $devices $createdPartitions\n        if [ \"$filesystem\" == \"xfs\" ]; then\n            mkfs -t $filesystem /dev/md10\n            echo \"/dev/md10 $mountPoint $filesystem rw,noatime,attr2,inode64,nobarrier,sunit=1024,swidth=4096,nofail 0 2\" >> /etc/fstab\n        else\n            mkfs -t $filesystem /dev/md10\n            echo \"/dev/md10 $mountPoint $filesystem defaults,nofail 0 2\" >> /etc/fstab\n        fi\n        \n        sleep 15\n        \n        mount /dev/md10\n    fi\n}\n\n# Creates and exports two shares on the master nodes:\n#\n# /share/home (for HPC user)\n# /share/data\n#\n# These shares are mounted on all worker nodes.\n#\nsetup_shares()\n{\n    mkdir -p $SHARE_NFS\n    mkdir -p $SHARE_CFS\n\n    if is_master; then\n        if [ \"$CFS\" == \"BeeGFS\" ]; then\n            mkdir -p $BEEGFS_METADATA\n            setup_data_disks $BEEGFS_METADATA \"ext4\"\n        else\n            setup_data_disks $SHARE_NFS \"ext4\"\n        fi\n\n        echo \"$SHARE_NFS    *(rw,async)\" >> /etc/exports\n        systemctl enable rpcbind || echo \"Already enabled\"\n        systemctl enable nfs-server || echo \"Already enabled\"\n        systemctl start rpcbind || echo \"Already enabled\"\n        systemctl start nfs-server || echo \"Already enabled\"\n\n        mount -a\n        mount\n    else\n        if [ \"$CFS_STORAGE\" == \"Storage\" ]; then\n            # Format CFS mount point\n            mkdir -p $CFS_STORAGE_LOCATION\n            setup_data_disks $CFS_STORAGE_LOCATION \"xfs\"\n        fi\n\n        # Mount master NFS share\n        echo \"master:$SHARE_NFS $SHARE_NFS    nfs4    rw,auto,_netdev 0 0\" >> /etc/fstab\n        mount -a\n        mount | grep \"^master:$SHARE_HOME\"\n    fi\n}\n\n# Downloads/builds/installs munged on the node.\n# The munge key is generated on the master node and placed\n# in the data share.\n# Worker nodes copy the existing key from the data share.\n#\ninstall_munge()\n{\n    groupadd $MUNGE_GROUP\n\n    useradd -M -c \"Munge service account\" -g munge -s /usr/sbin/nologin munge\n\n    wget https://github.com/dun/munge/archive/munge-${MUNGE_VERSION}.tar.gz\n\n    tar xvfz munge-$MUNGE_VERSION.tar.gz\n\n    cd munge-munge-$MUNGE_VERSION\n\n    mkdir -m 700 /etc/munge\n    mkdir -m 711 /var/lib/munge\n    mkdir -m 700 /var/log/munge\n    mkdir -m 755 /var/run/munge\n\n    ./configure -libdir=/usr/lib64 --prefix=/usr --sysconfdir=/etc --localstatedir=/var && make && make install\n\n    chown -R munge:munge /etc/munge /var/lib/munge /var/log/munge /var/run/munge\n\n    if is_master; then\n        dd if=/dev/urandom bs=1 count=1024 > /etc/munge/munge.key\n        mkdir -p $SLURM_CONF_DIR\n        cp /etc/munge/munge.key $SLURM_CONF_DIR\n    else\n        cp $SLURM_CONF_DIR/munge.key /etc/munge/munge.key\n    fi\n\n    chown munge:munge /etc/munge/munge.key\n    chmod 0400 /etc/munge/munge.key\n\n    /etc/init.d/munge start\n\n    cd ..\n}\n\n# Installs and configures slurm.conf on the node.\n# This is generated on the master node and placed in the data\n# share.  All nodes create a sym link to the SLURM conf\n# as all SLURM nodes must share a common config file.\n#\ninstall_slurm_config()\n{\n    if is_master; then\n\n        mkdir -p $SLURM_CONF_DIR\n\n        if [ -e \"$TEMPLATE_BASE_URL/slurm.template.conf\" ]; then\n            cp \"$TEMPLATE_BASE_URL/slurm.template.conf\" .\n        else\n            wget \"$TEMPLATE_BASE_URL/slurm.template.conf\"\n        fi\n\n        cat slurm.template.conf |\n        sed 's/__MASTER__/'\"$MASTER_HOSTNAME\"'/g' |\n                sed 's/__WORKER_HOSTNAME_PREFIX__/'\"$WORKER_HOSTNAME_PREFIX\"'/g' |\n                sed 's/__LAST_WORKER_INDEX__/'\"$LAST_WORKER_INDEX\"'/g' > $SLURM_CONF_DIR/slurm.conf\n    fi\n\n    ln -s $SLURM_CONF_DIR/slurm.conf /etc/slurm/slurm.conf\n}\n\n# Downloads, builds and installs SLURM on the node.\n# Starts the SLURM control daemon on the master node and\n# the agent on worker nodes.\n#\ninstall_slurm()\n{\n    groupadd -g $SLURM_GID $SLURM_GROUP\n\n    useradd -M -u $SLURM_UID -c \"SLURM service account\" -g $SLURM_GROUP -s /usr/sbin/nologin $SLURM_USER\n\n    mkdir -p /etc/slurm /var/spool/slurmd /var/run/slurmd /var/run/slurmctld /var/log/slurmd /var/log/slurmctld\n\n    chown -R slurm:slurm /var/spool/slurmd /var/run/slurmd /var/run/slurmctld /var/log/slurmd /var/log/slurmctld\n\n    wget https://github.com/SchedMD/slurm/archive/slurm-$SLURM_VERSION.tar.gz\n\n    tar xvfz slurm-$SLURM_VERSION.tar.gz\n\n    cd slurm-slurm-$SLURM_VERSION\n\n    ./configure -libdir=/usr/lib64 --prefix=/usr --sysconfdir=/etc/slurm && make -j 4 && make install\n\n    install_slurm_config\n\n    if is_master; then\n        wget $TEMPLATE_BASE_URL/slurmctld.service\n        mv slurmctld.service /usr/lib/systemd/system\n        systemctl daemon-reload\n        systemctl enable slurmctld\n        systemctl start slurmctld\n        systemctl status slurmctld\n    else\n        wget $TEMPLATE_BASE_URL/slurmd.service\n        mv slurmd.service /usr/lib/systemd/system\n        systemctl daemon-reload\n        systemctl enable slurmd\n        systemctl start slurmd\n        systemctl status slurmd\n    fi\n\n    cd ..\n}\n\n# Downloads and installs PBS Pro OSS on the node.\n# Starts the PBS Pro control daemon on the master node and\n# the mom agent on worker nodes.\n#\ninstall_pbsoss()\n{\n    yum install -y gcc make rpm-build libtool hwloc-devel \\\n      libX11-devel libXt-devel libedit-devel libical-devel \\\n      ncurses-devel perl postgresql-devel python-devel tcl-devel \\\n      tk-devel swig expat-devel openssl-devel libXext libXft \\\n      autoconf automake expat libedit postgresql-server python \\\n      sendmail tcl tk libical perl-Env perl-Switch\n\n    # Required on 7.2 as the libical lib changed\n    ln -s /usr/lib64/libical.so.1 /usr/lib64/libical.so.0\n\n    wget http://wpc.23a7.iotacdn.net/8023A7/origin2/rl/PBS-Open/CentOS_7.zip\n    unzip CentOS_7.zip\n    cd CentOS_7\n    rpm -ivh --nodeps pbspro-server-14.1.0-13.1.x86_64.rpm\n\n    echo 'export PATH=/opt/pbs/default/bin:$PATH' >> /etc/profile.d/pbs.sh\n    echo 'export PATH=/opt/pbs/default/sbin:$PATH' >> /etc/profile.d/pbs.sh\n\n    if is_master; then\n        cat > /etc/pbs.conf << EOF\nPBS_SERVER=$MASTER_HOSTNAME\nPBS_START_SERVER=1\nPBS_START_SCHED=1\nPBS_START_COMM=1\nPBS_START_MOM=0\nPBS_EXEC=/opt/pbs\nPBS_HOME=/var/spool/pbs\nPBS_CORE_LIMIT=unlimited\nPBS_SCP=/bin/scp\nEOF\n\n        /etc/init.d/pbs start\n\n        for i in $(seq 0 $LAST_WORKER_INDEX); do\n            nodeName=${WORKER_HOSTNAME_PREFIX}${i}\n            /opt/pbs/bin/qmgr -c \"c n $nodeName\"\n        done\n\n        # Enable job history\n        /opt/pbs/bin/qmgr -c \"s s job_history_enable = true\"\n        /opt/pbs/bin/qmgr -c \"s s job_history_duration = 336:0:0\"\n    else\n        cat > /etc/pbs.conf << EOF\nPBS_SERVER=$MASTER_HOSTNAME\nPBS_START_SERVER=0\nPBS_START_SCHED=0\nPBS_START_COMM=0\nPBS_START_MOM=1\nPBS_EXEC=/opt/pbs\nPBS_HOME=/var/spool/pbs\nPBS_CORE_LIMIT=unlimited\nPBS_SCP=/bin/scp\nEOF\n\n        /etc/init.d/pbs start\n    fi\n\n    cd ..\n}\n\ninstall_scheduler()\n{\n    if [ \"$SCHEDULER\" == \"Slurm\" ]; then\n        install_munge\n        install_slurm\n    elif [ \"$SCHEDULER\" == \"PBSPro-OS\" ]; then\n        install_pbsoss\n    else\n        echo \"Invalid scheduler specified: $SCHEDULER\"\n        exit 1\n    fi\n}\n\n# Adds a common HPC user to the node and configures public key SSh auth.\n# The HPC user has a shared home directory (NFS share on master) and access\n# to the data share.\n#\nsetup_hpc_user()\n{\n    # disable selinux\n    sed -i 's/enforcing/disabled/g' /etc/selinux/config\n    setenforce permissive\n\n    groupadd -g $HPC_GID $HPC_GROUP\n\n    # Don't require password for HPC user sudo\n    echo \"$HPC_USER ALL=(ALL) NOPASSWD: ALL\" >> /etc/sudoers\n\n    # Disable tty requirement for sudo\n    sed -i 's/^Defaults[ ]*requiretty/# Defaults requiretty/g' /etc/sudoers\n\n    if is_master; then\n        mkdir -p $SHARE_HOME\n\n        useradd -c \"HPC User\" -g $HPC_GROUP -m -d $SHARE_HOME/$HPC_USER -s /bin/bash -u $HPC_UID $HPC_USER\n\n        mkdir -p $SHARE_HOME/$HPC_USER/.ssh\n\n        # Configure public key auth for the HPC user\n        ssh-keygen -t rsa -f $SHARE_HOME/$HPC_USER/.ssh/id_rsa -q -P \"\"\n        cat $SHARE_HOME/$HPC_USER/.ssh/id_rsa.pub > $SHARE_HOME/$HPC_USER/.ssh/authorized_keys\n\n        echo \"Host *\" > $SHARE_HOME/$HPC_USER/.ssh/config\n        echo \"    StrictHostKeyChecking no\" >> $SHARE_HOME/$HPC_USER/.ssh/config\n        echo \"    UserKnownHostsFile /dev/null\" >> $SHARE_HOME/$HPC_USER/.ssh/config\n        echo \"    PasswordAuthentication no\" >> $SHARE_HOME/$HPC_USER/.ssh/config\n\n        # Fix .ssh folder ownership\n        chown -R $HPC_USER:$HPC_GROUP $SHARE_HOME/$HPC_USER\n\n        # Fix permissions\n        chmod 700 $SHARE_HOME/$HPC_USER/.ssh\n        chmod 644 $SHARE_HOME/$HPC_USER/.ssh/config\n        chmod 644 $SHARE_HOME/$HPC_USER/.ssh/authorized_keys\n        chmod 600 $SHARE_HOME/$HPC_USER/.ssh/id_rsa\n        chmod 644 $SHARE_HOME/$HPC_USER/.ssh/id_rsa.pub\n\n    else\n        useradd -c \"HPC User\" -g $HPC_GROUP -d $SHARE_HOME/$HPC_USER -s /bin/bash -u $HPC_UID $HPC_USER\n    fi\n\n    chown $HPC_USER:$HPC_GROUP $SHARE_CFS\n}\n\n# Sets all common environment variables and system parameters.\n#\nsetup_env()\n{\n    # Set unlimited mem lock\n    echo \"$HPC_USER hard memlock unlimited\" >> /etc/security/limits.conf\n    echo \"$HPC_USER soft memlock unlimited\" >> /etc/security/limits.conf\n\n    echo \"$IMAGE_OFFER\" | grep -q 'HPC$'\n    if [ $? -eq 0 ]; then\n        # Intel MPI config for IB\n        echo \"# IB Config for MPI\" > /etc/profile.d/mpi.sh\n        echo \"export I_MPI_FABRICS=shm:dapl\" >> /etc/profile.d/mpi.sh\n        echo \"export I_MPI_DAPL_PROVIDER=ofa-v2-ib0\" >> /etc/profile.d/mpi.sh\n        echo \"export I_MPI_DYNAMIC_CONNECTION=0\" >> /etc/profile.d/mpi.sh\n    fi\n}\n\ninstall_easybuild()\n{\n    if [ \"$INSTALL_EASYBUILD\" != \"Yes\" ]; then\n        echo \"Skipping EasyBuild install...\"\n        return 0\n    fi\n\n    yum -y install Lmod python-devel python-pip gcc gcc-c++ patch unzip tcl tcl-devel libibverbs libibverbs-devel\n    pip install vsc-base\n\n    EASYBUILD_HOME=$SHARE_HOME/$HPC_USER/EasyBuild\n\n    if is_master; then\n        su - $HPC_USER -c \"pip install --install-option --prefix=$EASYBUILD_HOME https://github.com/hpcugent/easybuild-framework/archive/easybuild-framework-v2.5.0.tar.gz\"\n\n        # Add Lmod to the HPC users path\n        echo 'export PATH=/usr/lib64/openmpi/bin:/usr/share/lmod/6.0.15/libexec:$PATH' >> $SHARE_HOME/$HPC_USER/.bashrc\n\n        # Setup Easybuild configuration and paths\n        echo 'export PATH=$HOME/EasyBuild/bin:$PATH' >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo 'export PYTHONPATH=$HOME/EasyBuild/lib/python2.7/site-packages:$PYTHONPATH' >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo \"export MODULEPATH=$EASYBUILD_HOME/modules/all\" >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo \"export EASYBUILD_MODULES_TOOL=Lmod\" >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo \"export EASYBUILD_INSTALLPATH=$EASYBUILD_HOME\" >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo \"export EASYBUILD_DEBUG=1\" >> $SHARE_HOME/$HPC_USER/.bashrc\n        echo \"source /usr/share/lmod/6.0.15/init/bash\" >> $SHARE_HOME/$HPC_USER/.bashrc\n    fi\n}\n\ninstall_cfs()\n{\n    if [ \"$CFS\" == \"BeeGFS\" ]; then\n        wget -O beegfs-rhel7.repo http://www.beegfs.com/release/latest-stable/dists/beegfs-rhel7.repo\n        mv beegfs-rhel7.repo /etc/yum.repos.d/beegfs.repo\n        rpm --import http://www.beegfs.com/release/latest-stable/gpg/RPM-GPG-KEY-beegfs\n\n        yum install -y beegfs-client beegfs-helperd beegfs-utils\n\n        sed -i 's/^sysMgmtdHost.*/sysMgmtdHost = '$MASTER_HOSTNAME'/g' /etc/beegfs/beegfs-client.conf\n        sed -i  's/Type=oneshot.*/Type=oneshot\\nRestart=always\\nRestartSec=5/g' /etc/systemd/system/multi-user.target.wants/beegfs-client.service\n        echo \"$SHARE_CFS /etc/beegfs/beegfs-client.conf\" > /etc/beegfs/beegfs-mounts.conf\n\n        if is_master; then\n            yum install -y beegfs-mgmtd beegfs-meta\n            mkdir -p /data/beegfs/mgmtd\n            sed -i 's|^storeMgmtdDirectory.*|storeMgmtdDirectory = /data/beegfs/mgmt|g' /etc/beegfs/beegfs-mgmtd.conf\n            sed -i 's|^storeMetaDirectory.*|storeMetaDirectory = '$BEEGFS_METADATA'|g' /etc/beegfs/beegfs-meta.conf\n            sed -i 's/^sysMgmtdHost.*/sysMgmtdHost = '$MASTER_HOSTNAME'/g' /etc/beegfs/beegfs-meta.conf\n            /etc/init.d/beegfs-mgmtd start\n            /etc/init.d/beegfs-meta start\n        else\n            yum install -y beegfs-storage\n            sed -i 's|^storeStorageDirectory.*|storeStorageDirectory = '$CFS_STORAGE_LOCATION'|g' /etc/beegfs/beegfs-storage.conf\n            sed -i 's/^sysMgmtdHost.*/sysMgmtdHost = '$MASTER_HOSTNAME'/g' /etc/beegfs/beegfs-storage.conf\n            /etc/init.d/beegfs-storage start\n        fi\n\n        systemctl daemon-reload\n    fi\n}\n\ninstall_pkgs\nsetup_shares\nsetup_hpc_user\ninstall_cfs\ninstall_scheduler\nsetup_env\ninstall_easybuild\nshutdown -r +1 &\nexit 0\n", "num_lines": 522}
{"repo_name": "azure-iot-c-analysis", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\nuname -r\n\ncmake_cmd=\"\"\nrun_binary_strip=0\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nrepo_root=$(cd \"${script_dir}/..\" && pwd)\ncmake_folder=$repo_root\"/cmake/analysis_linux\"\n\nconn_string=\"${IOTHUB_CONNECTION_STRING}\"\nrpt_conn_string=\"${REPORT_CONNECTION_STRING}\"\n\nrun_binary_info()\n{\n    rm -r -f $cmake_folder\n    mkdir -p $cmake_folder\n    pushd $cmake_folder  >/dev/null\n\n    cmake $repo_root $cmake_cmd >/dev/null\n    make -j >/dev/null\n\n    if [ $run_binary_strip -ge 1 ]; then\n        # Run strip from the binaries./\n        strip ./binary_info/lower_layer/mqtt_transport_ll/mqtt_transport_ll\n        strip ./binary_info/lower_layer/mqtt_ws_transport_ll/mqtt_ws_transport_ll\n        strip ./binary_info/lower_layer/amqp_transport_ll/amqp_transport_ll\n        strip ./binary_info/lower_layer/amqp_ws_transport_ll/amqp_ws_transport_ll\n    fi\n\n    ./binary_info/binary_info -c $cmake_folder -s $rpt_conn_string\n    echo \"\"\n    popd  >/dev/null\n}\n\necho \"Running cmake with -DCMAKE_BUILD_TYPE=Release\"\ncmake_cmd=\"-DCMAKE_BUILD_TYPE=Release\"\nrun_binary_info\n\necho \"Running cmake with -DCMAKE_BUILD_TYPE=Release no_logging\"\ncmake_cmd=\"-DCMAKE_BUILD_TYPE=Release -Dno_logging=ON\"\nrun_binary_info\n\necho \"Running cmake with -DCMAKE_BUILD_TYPE=Release no_logging and strip\"\ncmake_cmd=\"-DCMAKE_BUILD_TYPE=Release -Dno_logging=ON\"\nrun_binary_strip=1\nrun_binary_info\n\n# Run the analysis applications\npushd $cmake_folder\n\necho \"retrieving telemetry memory info\"\n./memory/telemetry_memory/telemetry_memory -c $conn_string\necho \"retrieving telemetry network info\"\n./network/telemetry_net_info/telemetry_net_info -c $conn_string\n\n#./memory/prov_net_info/prov_net_info -c $DPS_C_CONNECTION_STRING -s $DPS_C_SCOPE_ID_VALUE\n#./memory/provisioning_mem/provisioning_mem -c $DPS_C_CONNECTION_STRING -s $DPS_C_SCOPE_ID_VALUE\n", "num_lines": 69}
{"repo_name": "azure-iot-c-analysis", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n\nset -e\n\ngcc --version\nopenssl version\nuname -r\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nrepo_root=$(cd \"${script_dir}/..\" && pwd)\ncmake_folder=$repo_root\"/cmake/analysis_multiple\"\n\ndeclare -a arr=(\n    \"lts_10_2018\"\n    \"2018-09-11\"\n    \"master\"\n)\n\nfor item in \"${arr[@]}\"\ndo\n    rm -r -f $cmake_folder\n    # Remove the SDK\n    rm -r -f \"$repo_root/deps/c-sdk\"\n    mkdir -p $cmake_folder\n    pushd $cmake_folder\n\n    echo \"executing cmake/make with options <<$item>>\"\n    cmake $repo_root -DCMAKE_BUILD_TYPE=Release -Dsdk_branch=\"$item\" -Duse_http=OFF >/dev/null\n\n    echo \"building SDK\"\n    # Run make, but don't show the output\n    make -j >/dev/null\n\n    # Run the analysis applications\n    echo \"Retrieving binary info\"\n    ./binary_info/binary_info -c $cmake_folder\ndone\npopd\n", "num_lines": 41}
{"repo_name": "azure-iot-cli-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nls -al\n\n/bin/true\nsleep 0\n\n/bin/true\nsleep 0\n\n/bin/true\nsleep 0\n\n/bin/true\nsleep 0\n", "num_lines": 15}
{"repo_name": "azure-iot-cli-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nmkdir action\n", "num_lines": 3}
{"repo_name": "azure-iot-cli-extension", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nls\n", "num_lines": 3}
{"repo_name": "azure-iot-connected-factory", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash \n\n", "num_lines": 3}
{"repo_name": "azure-iot-connected-factory", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nbuild_root=$(cd \"$(dirname \"$0\")\" && pwd)\ncd $build_root\n\nrestore=0\nassembly=0\ntest=0\npackaging=0\nmes=0\n\n# Package restore\ndotnet restore\n\n# bugbug - dotnet preview2 requires an absolute path for publish or include files are ignored\npublish=$build_root/buildOutput\n\n# clean publish folder \necho Erase publish folder: $publish\nrm -rdf $publish/*\n\n# build station\necho \"build Station\"\ncd ./Station\ndotnet build && echo \"Station built!\" || assembly = $?\ndotnet publish -o $publish && echo \"Station published!\" || assembly = $?\ncd $build_root\n\n# build MES\necho \"build MES\"\ncd ./MES\ndotnet build && echo \"MES built!\" || mes = $?\ndotnet publish -o $publish && echo \"MES published!\" || mes = $?\ncd $build_root\n\n# create log and cert folder\nmkdir ./Logs\nmkdir ./OPC\\ Foundation\n\n# run Factory\necho \"run Factory\"\ncd $publish\nnohup nice dotnet Station.dll Munich/ProductionLine0/Assembly 51210 200 yes 1> ../Logs/AssemblyStation.out 2> ../Logs/AssemblyStation.err < /dev/null &\nnohup nice dotnet Station.dll Munich/ProductionLine0/Test 51214 100 no 1> ../Logs/TestStation.out 2> ../Logs/TestStation.err < /dev/null &\nnohup nice dotnet Station.dll Munich/ProductionLine0/Packaging 51215 150 no 1> ../Logs/PackageStation.out 2> ../Logs/PackageStation.err < /dev/null &\n\n# wait until the OPC servers started fully up\necho \"Waiting 10s for stations to start up\"\nsleep 10\necho \"Start MES\"\n\nnohup nice dotnet MES.dll 1> ../Logs/MES.out 2> ../Logs/MES.err </dev/null &\ncd $build_root\n\necho \"Factory running\"\njobs\n\necho Factory Jobs started\necho Stop factory using: killall -i -I dotnet\n", "num_lines": 62}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=$1\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    ./scripts/devicesimulation.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n    ./scripts/devicesimulation.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \ntag=\"staging\"\ndockeraccount=\"azureiotpcsdev\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run Tests\nrun\n\n#### Tear down test\ntear_down\n\nheader \"$TEST_SUITE Finished\"\n\nset +e\n", "num_lines": 93}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nstart() {\n    ./scripts/storageadapter.sh start\n    ./scripts/devicesimulation.sh start\n}\n\nstop() {\n    ./scripts/storageadapter.sh stop\n    ./scripts/devicesimulation.sh stop\n}\n\n#Script Args\ntag=\"staging\"\nact=\"start\"\ndockeraccount=\"azureiotpcsdev\"\n\nset_up_env() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\t\n    case $opt in\n        -dt|--dockertag) tag=$1; shift;;\n        -act|--action) act=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *) shift;\n    esac\ndone\n\nset_up_env\n\nif [[ \"$act\" == \"start\" ]]; then\n    start\n    exit 0\nfi\n\nif [[ \"$act\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\ntear_down", "num_lines": 58}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_ACCOUNT\" == \"\" ]]; then\n    export DOCKER_ACCOUNT=azureiotpcsdev\nfi\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=staging\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/device-simulation-dotnet:$DOCKER_TAG\"\nDOCKER_PORT=9003\nDOCKER_NAME=\"device-simulation\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_IOTHUB_CONNSTRING}\" ]]; then\n        error \"PCS_IOTHUB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 87}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_ACCOUNT\" == \"\" ]]; then\n    export DOCKER_ACCOUNT=azureiotpcsdev\nfi\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=staging\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/pcs-storage-adapter-dotnet:$DOCKER_TAG\"\nDOCKER_PORT=9022\nDOCKER_NAME=\"storage-adapter\"\nDOCKER_NETWORK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\" ]]; then\n        error \"PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWORK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWORK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 87}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nchmod ugo+x ./scripts/build\nchmod ugo+x ./scripts/git/setup\nchmod ugo+x ./scripts/git/*.sh\nchmod ugo+x ./scripts/devicesimulation.sh\nchmod ugo+x ./scripts/storageadapter.sh\nchmod ugo+x ./DeviceSimulation/run.sh\nchmod ugo+x ./StorageAdapter/run.sh\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\ngit update-index --chmod=+x ./scripts/devicesimulation.sh\ngit update-index --chmod=+x ./scripts/storageadapter.sh\ngit update-index --chmod=+x ./DeviceSimulation/run.sh\ngit update-index --chmod=+x ./StorageAdapter/run.sh\n\nset +e\n", "num_lines": 30}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build --in-sandbox\n    else\n        ./build\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 124}
{"repo_name": "azure-iot-device-simulation-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"Storage Adapter tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \ntag=\"staging\"\ndockeraccount=\"azureiotpcsdev\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run tests based on repo\nrun\n\n#### Tear down test\ntear_down\n\nset +e", "num_lines": 88}
{"repo_name": "azure-iot-dps-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nwhich az > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n   printf \"Azure CLI must be installed and added to PATH\\n\"\n   exit 1\nfi\nset -e\n\nfunction usage {\n    printf \"usage: $0 [flags]\\n\\n\"\n    printf \"flags:\\n\"\n    printf \"    --help, -h        Show this help message\\n\"\n    printf \"    --rg-name, -n     Name of the resource group to use. Will be created if needed. (required)\\n\"\n    printf \"                      Note: A resource group can only hold a single set of E2E resources.\\n\"\n    printf \"    --location, -l    Deploy to specific Azure region (optional, default is westus2)\\n\"\n}\n\n\n# process args\nlocation=westus2\n\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -l | --location)\n            location=$2\n            shift; shift;\n            ;;\n\n        -n | --rg-name)\n            rgName=$2\n            shift; shift;\n            ;;\n\n        -h | --help)\n            usage\n            exit 0\n            ;;\n\n        *)\n            printf \"Unexpected argument: $1\\n\"\n            usage\n            exit 1\n            ;;\n    esac\ndone\n\nif [ \"$rgName\" == \"\" ]; then\n    printf \"Expected argument rg-name is missing\\n\"\n    usage\n    exit 1\nfi\n\n\n# print warning\nprintf \"WARNING\\n\"\nprintf \"This script will deploy Azure resources into\\n\"\nprintf \"Subscription: $(az account show --query \"name\" -o tsv)\\n\"\nprintf \"Resource Group: $rgName\\n\"\nprintf \"Region: $location\\n\"\nprintf \"(Use 'az account list' and 'az account set' to change the subscription.)\\n\"\nread -p 'Press [Enter] to continue or ctrl-c to break'\n\n\n# create certs\nprintf \"Creating certs...\\n\"\nmkdir -p ${script_dir}/secrets/{certs,env}\nopenssl req \\\n    -new \\\n    -newkey rsa:4096 \\\n    -days 730 \\\n    -nodes \\\n    -x509 \\\n    -subj '/CN=Azure IoT Test Only' \\\n    -keyout ${script_dir}/secrets/certs/azure-iot-test-only.key \\\n    -out ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem > /dev/null 2>&1\nroot_cert=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem))\nprivate_key=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.key))\n\n\n# start deployment\ndeploymentName=\"IoT-E2E-$(printf $RANDOM)\"\n\nprintf \"Deploying Azure resources...\\n\"\ndeployment_out=$(az deployment sub create --only-show-errors \\\n    -f ${script_dir}/test-resources.bicep \\\n    -l $location \\\n    -n $deploymentName \\\n    -p \\\n        rgName=$rgName \\\n        alias=$(az account show --query '{user:user.name}' -o tsv) \\\n        userObjectId=$(az ad signed-in-user show --query id -o tsv) \\\n        rootCertValue=$root_cert \\\n        rootCertPrivateKey=$private_key)\n\niot_hub_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubName.value)\ndps_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.dpsName.value)\nkey_vault_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.keyVaultName.value)\niot_provisioning_device_idscope=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotProvisioningDeviceIdScope.value)\niot_provisioning_service_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotProvisioningServiceConnectionString.value)\niothub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubConnectionString.value)\neventhub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.eventHubConnectionString.value)\nstorage_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.storageConnectionString.value)\n\n\n# add cert to IoT Hub\nprintf \"Adding cert to IoT Hub...\\n\"\naz iot hub certificate create --only-show-errors -v \\\n    --hub-name $iot_hub_name \\\n    -g $rgName \\\n    -n azure-iot-test-only \\\n    -p ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem\n\n\n# add cert to DPS\nprintf \"Adding cert to DPS...\\n\"\naz iot dps certificate create --only-show-errors -v \\\n    --dps-name $dps_name \\\n    -g $rgName \\\n    -n azure-iot-test-only \\\n    -p ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem\n\n\n# create activation scripts\nprintf \"Creating activation scripts...\\n\"\n\n# fake secrets\niot_provisioning_device_endpoint=\"global.azure-devices-provisioning.net\"\ndps_conn_string_invalid_cert=\"HostName=invalidcertdps1.westus.cloudapp.azure.com;SharedAccessKeyName=provisioningserviceowner;SharedAccessKey=lGO7OlXNhXlFyYV1rh9F/lUCQC1Owuh5f/1P0I1AFSY=\"\ndps_global_device_endpoint_invalid_cert=\"invalidcertgde1.westus.cloudapp.azure.com\"\niothub_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;SharedAccessKeyName=iothubowner;SharedAccessKey=Fk1H0asPeeAwlRkUMTybJasksTYTd13cgI7SsteB05U=\"\niothub_device_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;DeviceId=DoNotDelete1;SharedAccessKey=zWmeTGWmjcgDG1dpuSCVjc5ZY4TqVnKso5+g1wt/K3E=\"\n\npushd ${script_dir}/secrets/env/ > /dev/null 2>&1\n# PS\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_DEVICE_ENDPOINT -Value '$iot_provisioning_device_endpoint'\\r\\n\" > activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT -Value '$root_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT_KEY -Value '$private_key'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_DEVICE_IDSCOPE -Value '$iot_provisioning_device_idscope'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_ROOT_CERT -Value '$root_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_ROOT_CERT_KEY -Value '$private_key'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_SERVICE_CONNECTION_STRING -Value '$iot_provisioning_service_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONNECTION_STRING -Value '$iothub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:EVENTHUB_CONNECTION_STRING -Value '$eventhub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:STORAGE_CONNECTION_STRING -Value '$storage_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:DPS_CONN_STRING_INVALID_CERT -Value '$dps_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT -Value '$dps_global_device_endpoint_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONN_STRING_INVALID_CERT -Value '$iothub_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_DEVICE_CONN_STRING_INVALID_CERT -Value '$iothub_device_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\n\n# CMD\nprintf \"set IOT_PROVISIONING_DEVICE_ENDPOINT=$iot_provisioning_device_endpoint\\r\\n\" > activate.cmd\nprintf \"set IOTHUB_CA_ROOT_CERT=$root_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CA_ROOT_CERT_KEY=$private_key\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_DEVICE_IDSCOPE=$iot_provisioning_device_idscope\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_ROOT_CERT=$root_cert\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_ROOT_CERT_KEY=$private_key\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_SERVICE_CONNECTION_STRING=$iot_provisioning_service_connection_string\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONNECTION_STRING=$iothub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set EVENTHUB_CONNECTION_STRING=$eventhub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set STORAGE_CONNECTION_STRING=$storage_connection_string\\r\\n\" >> activate.cmd\nprintf \"set DPS_CONN_STRING_INVALID_CERT=$dps_conn_string_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT=$dps_global_device_endpoint_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONN_STRING_INVALID_CERT=$iothub_conn_string_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$iothub_device_conn_string_invalid_cert\\r\\n\" >> activate.cmd\n\n# BASH\nprintf \"#!/bin/bash\\n\" > activate\nprintf \"export IOT_PROVISIONING_DEVICE_ENDPOINT='$iot_provisioning_device_endpoint'\\n\" >> activate\nprintf \"export IOTHUB_CA_ROOT_CERT='$root_cert'\\n\" >> activate\nprintf \"export IOTHUB_CA_ROOT_CERT_KEY='$private_key'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_DEVICE_IDSCOPE='$iot_provisioning_device_idscope'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_ROOT_CERT='$root_cert'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_ROOT_CERT_KEY='$private_key'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_SERVICE_CONNECTION_STRING='$iot_provisioning_service_connection_string'\\n\" >> activate\nprintf \"export IOTHUB_CONNECTION_STRING='$iothub_connection_string'\\n\" >> activate\nprintf \"export EVENTHUB_CONNECTION_STRING='$eventhub_connection_string'\\n\" >> activate\nprintf \"export STORAGE_CONNECTION_STRING='$storage_connection_string'\\n\" >> activate\nprintf \"export DPS_CONN_STRING_INVALID_CERT='$dps_conn_string_invalid_cert'\\n\" >> activate\nprintf \"export DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT='$dps_global_device_endpoint_invalid_cert'\\n\" >> activate\nprintf \"export IOTHUB_CONN_STRING_INVALID_CERT='$iothub_conn_string_invalid_cert'\\n\" >> activate\nprintf \"export IOTHUB_DEVICE_CONN_STRING_INVALID_CERT='$iothub_device_conn_string_invalid_cert'\\n\" >> activate\n\n# JSON\nprintf \"{\\n\" > env.json\nprintf \"    \\\"IOT_PROVISIONING_DEVICE_ENDPOINT\\\": \\\"$iot_provisioning_device_endpoint\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT\\\": \\\"$root_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT_KEY\\\": \\\"$private_key\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_DEVICE_IDSCOPE\\\": \\\"$iot_provisioning_device_idscope\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_ROOT_CERT\\\": \\\"$root_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_ROOT_CERT_KEY\\\": \\\"$private_key\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_SERVICE_CONNECTION_STRING\\\": \\\"$iot_provisioning_service_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONNECTION_STRING\\\": \\\"$iothub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"EVENTHUB_CONNECTION_STRING\\\": \\\"$eventhub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"STORAGE_CONNECTION_STRING\\\": \\\"$storage_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"DPS_CONN_STRING_INVALID_CERT\\\": \\\"$dps_conn_string_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT\\\": \\\"$dps_global_device_endpoint_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_conn_string_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_DEVICE_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_device_conn_string_invalid_cert\\\"\\n\" >> env.json\nprintf \"}\\n\" >> env.json\n\npopd > /dev/null 2>&1\n\nprintf \"Done!\\n\"\nprintf \"WARNING: The secrets directory contains secret values. Do not check-in this directory.\\n\"\nprintf \"Depending on your environment, activate the E2E test environment by running the following\\n\"\nprintf \"Bash: source secrets/env/activate\\n\"\nprintf \"PowerShell: secrets/env/activate.ps1\\n\"\nprintf \"CMD: secrets/env/activate.cmd\\n\"\nprintf \"Alternatively, you can retreive the environment variables from secrets/env/env.json\\n\"\nprintf \"or from the Key Vault named $key_vault_name.\\n\"\n", "num_lines": 214}
{"repo_name": "azure-iot-dps-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\n\nexport IOT_PROVISIONING_DEVICE_ENDPOINT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-DEVICE-ENDPOINT)\nexport IOTHUB_CA_ROOT_CERT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT)\nexport IOTHUB_CA_ROOT_CERT_KEY=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT-KEY)\nexport IOT_PROVISIONING_DEVICE_IDSCOPE=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-DEVICE-IDSCOPE)\nexport IOT_PROVISIONING_ROOT_CERT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-ROOT-CERT)\nexport IOT_PROVISIONING_ROOT_CERT_KEY=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-ROOT-CERT-KEY)\nexport IOT_PROVISIONING_SERVICE_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-SERVICE-CONNECTION-STRING)\nexport IOTHUB_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CONNECTION-STRING)\nexport STORAGE_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name STORAGE-CONNECTION-STRING)\nexport DPS_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name DPS-CONN-STRING-INVALID-CERT)\nexport DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name DPS-GLOBAL-DEVICE-ENDPOINT-INVALID-CERT)\nexport IOTHUB_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-CONN-STRING-INVALID-CERT)\nexport IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-DEVICE-CONN-STRING-INVALID-CERT)", "num_lines": 17}
{"repo_name": "azure-iot-hub-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nwhich az > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n   printf \"Azure CLI must be installed and added to PATH\\n\"\n   exit 1\nfi\nset -e\n\nfunction usage {\n    printf \"usage: $0 [flags]\\n\\n\"\n    printf \"flags:\\n\"\n    printf \"    --help, -h        Show this help message\\n\"\n    printf \"    --rg-name, -n     Name of the resource group to use. Will be created if needed. (required)\\n\"\n    printf \"                      Note: A resource group can only hold a single set of E2E resources.\\n\"\n    printf \"    --location, -l    Deploy to specific Azure region (optional, default is westus2)\\n\"\n}\n\n\n# process args\nlocation=westus2\n\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -l | --location)\n            location=$2\n            shift; shift;\n            ;;\n\n        -n | --rg-name)\n            rgName=$2\n            shift; shift;\n            ;;\n\n        -h | --help)\n            usage\n            exit 0\n            ;;\n\n        *)\n            printf \"Unexpected argument: $1\\n\"\n            usage\n            exit 1\n            ;;\n    esac\ndone\n\nif [ \"$rgName\" == \"\" ]; then\n    printf \"Expected argument rg-name is missing\\n\"\n    usage\n    exit 1\nfi\n\n\n# print warning\nprintf \"WARNING\\n\"\nprintf \"This script will deploy Azure resources into\\n\"\nprintf \"Subscription: $(az account show --query \"name\" -o tsv)\\n\"\nprintf \"Resource Group: $rgName\\n\"\nprintf \"Region: $location\\n\"\nprintf \"(Use 'az account list' and 'az account set' to change the subscription.)\\n\"\nread -p 'Press [Enter] to continue or ctrl-c to break'\n\n\n# create certs\nprintf \"Creating certs...\\n\"\nmkdir -p ${script_dir}/secrets/{certs,env}\nopenssl req \\\n    -new \\\n    -newkey rsa:4096 \\\n    -days 730 \\\n    -nodes \\\n    -x509 \\\n    -subj '/CN=Azure IoT Test Only' \\\n    -keyout ${script_dir}/secrets/certs/azure-iot-test-only.key \\\n    -out ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem > /dev/null 2>&1\nroot_cert=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem))\nprivate_key=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.key))\n\n\n# start deployment\ndeploymentName=\"IoT-E2E-$(printf $RANDOM)\"\n\nprintf \"Deploying Azure resources...\\n\"\ndeployment_out=$(az deployment sub create --only-show-errors \\\n    -f ${script_dir}/test-resources.bicep \\\n    -l $location \\\n    -n $deploymentName \\\n    -p \\\n        rgName=$rgName \\\n        alias=$(az account show --query '{user:user.name}' -o tsv) \\\n        userObjectId=$(az ad signed-in-user show --query id -o tsv) \\\n        rootCertValue=$root_cert \\\n        rootCertPrivateKey=$private_key)\n\niot_hub_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubName.value)\nkey_vault_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.keyVaultName.value)\niothub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubConnectionString.value)\neventhub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.eventHubConnectionString.value)\nstorage_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.storageConnectionString.value)\n\n\n# add cert to IoT Hub\nprintf \"Adding cert to IoT Hub...\\n\"\naz iot hub certificate create --only-show-errors -v \\\n    --hub-name $iot_hub_name \\\n    -g $rgName \\\n    -n azure-iot-test-only \\\n    -p ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem\n\n\n# create activation scripts\nprintf \"Creating activation scripts...\\n\"\n\n# fake secrets\niot_provisioning_device_endpoint=\"global.azure-devices-provisioning.net\"\niothub_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;SharedAccessKeyName=iothubowner;SharedAccessKey=Fk1H0asPeeAwlRkUMTybJasksTYTd13cgI7SsteB05U=\"\niothub_device_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;DeviceId=DoNotDelete1;SharedAccessKey=zWmeTGWmjcgDG1dpuSCVjc5ZY4TqVnKso5+g1wt/K3E=\"\n\npushd ${script_dir}/secrets/env/ > /dev/null 2>&1\n# PS\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT -Value '$root_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT_KEY -Value '$private_key'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONNECTION_STRING -Value '$iothub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:EVENTHUB_CONNECTION_STRING -Value '$eventhub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:STORAGE_CONNECTION_STRING -Value '$storage_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONN_STRING_INVALID_CERT -Value '$iothub_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_DEVICE_CONN_STRING_INVALID_CERT -Value '$iothub_device_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\n\n# CMD\nprintf \"set IOTHUB_CA_ROOT_CERT=$root_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CA_ROOT_CERT_KEY=$private_key\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONNECTION_STRING=$iothub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set EVENTHUB_CONNECTION_STRING=$eventhub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set STORAGE_CONNECTION_STRING=$storage_connection_string\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONN_STRING_INVALID_CERT=$iothub_conn_string_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$iothub_device_conn_string_invalid_cert\\r\\n\" >> activate.cmd\n\n# BASH\nprintf \"#!/bin/bash\\n\" > activate\nprintf \"export IOTHUB_CA_ROOT_CERT='$root_cert'\\n\" >> activate\nprintf \"export IOTHUB_CA_ROOT_CERT_KEY='$private_key'\\n\" >> activate\nprintf \"export IOTHUB_CONNECTION_STRING='$iothub_connection_string'\\n\" >> activate\nprintf \"export EVENTHUB_CONNECTION_STRING='$eventhub_connection_string'\\n\" >> activate\nprintf \"export STORAGE_CONNECTION_STRING='$storage_connection_string'\\n\" >> activate\nprintf \"export IOTHUB_CONN_STRING_INVALID_CERT='$iothub_conn_string_invalid_cert'\\n\" >> activate\nprintf \"export IOTHUB_DEVICE_CONN_STRING_INVALID_CERT='$iothub_device_conn_string_invalid_cert'\\n\" >> activate\n\n# JSON\nprintf \"{\\n\" > env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT\\\": \\\"$root_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT_KEY\\\": \\\"$private_key\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONNECTION_STRING\\\": \\\"$iothub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"EVENTHUB_CONNECTION_STRING\\\": \\\"$eventhub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"STORAGE_CONNECTION_STRING\\\": \\\"$storage_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_conn_string_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_DEVICE_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_device_conn_string_invalid_cert\\\"\\n\" >> env.json\nprintf \"}\\n\" >> env.json\n\npopd > /dev/null 2>&1\n\nprintf \"Done!\\n\"\nprintf \"WARNING: The secrets directory contains secret values. Do not check-in this directory.\\n\"\nprintf \"Depending on your environment, activate the E2E test environment by running the following\\n\"\nprintf \"Bash: source secrets/env/activate\\n\"\nprintf \"PowerShell: secrets/env/activate.ps1\\n\"\nprintf \"CMD: secrets/env/activate.cmd\\n\"\nprintf \"Alternatively, you can retreive the environment variables from secrets/env/env.json\\n\"\nprintf \"or from the Key Vault named $key_vault_name.\\n\"\n", "num_lines": 172}
{"repo_name": "azure-iot-hub-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\n\nexport IOTHUB_CA_ROOT_CERT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT)\nexport IOTHUB_CA_ROOT_CERT_KEY=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT-KEY)\nexport IOTHUB_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CONNECTION-STRING)\nexport STORAGE_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name STORAGE-CONNECTION-STRING)\nexport IOTHUB_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-CONN-STRING-INVALID-CERT)\nexport IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-DEVICE-CONN-STRING-INVALID-CERT)", "num_lines": 10}
{"repo_name": "azure-iot-hub-nodered-nodes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# for a given node version run:\n# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done;\n\nPATTERNS=('nodeuuid.v1()' \"nodeuuid.v1('binary',\" 'nodeuuid.v4()' \"nodeuuid.v4('binary',\" \"uuid()\" \"uuid('binary')\" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte')\nFILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es)\nINDICES=(2 3 2 3 2 2 2 2 2)\nVERSIONS=$( ls bench_*.log | sed -e 's/^bench_\\([0-9\\.]*\\)\\.log/\\1/' | tr \"\\\\n\" \" \" )\nTMPJOIN=\"tmp_join\"\nOUTPUT=\"bench_results.txt\"\n\nfor I in ${!FILES[*]}; do\n  F=${FILES[$I]}\n  P=${PATTERNS[$I]}\n  INDEX=${INDICES[$I]}\n  echo \"version $F\" > $F\n  for V in $VERSIONS; do\n    (VAL=$( grep \"$P\" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F\n  done\n  if [ $I == 0 ]; then\n    cat $F > $TMPJOIN\n  else\n    join $TMPJOIN $F > $OUTPUT\n    cp $OUTPUT $TMPJOIN\n  fi\n  rm $F\ndone\n\nrm $TMPJOIN\n\ngnuplot bench.gnu\nconvert -density 200 -resize 800x560 -flatten bench.eps bench.png\nrm bench.eps\n", "num_lines": 35}
{"repo_name": "azure-iot-hub-nodered-nodes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# for a given node version run:\n# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done;\n\nPATTERNS=('nodeuuid.v1()' \"nodeuuid.v1('binary',\" 'nodeuuid.v4()' \"nodeuuid.v4('binary',\" \"uuid()\" \"uuid('binary')\" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte')\nFILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es)\nINDICES=(2 3 2 3 2 2 2 2 2)\nVERSIONS=$( ls bench_*.log | sed -e 's/^bench_\\([0-9\\.]*\\)\\.log/\\1/' | tr \"\\\\n\" \" \" )\nTMPJOIN=\"tmp_join\"\nOUTPUT=\"bench_results.txt\"\n\nfor I in ${!FILES[*]}; do\n  F=${FILES[$I]}\n  P=${PATTERNS[$I]}\n  INDEX=${INDICES[$I]}\n  echo \"version $F\" > $F\n  for V in $VERSIONS; do\n    (VAL=$( grep \"$P\" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F\n  done\n  if [ $I == 0 ]; then\n    cat $F > $TMPJOIN\n  else\n    join $TMPJOIN $F > $OUTPUT\n    cp $OUTPUT $TMPJOIN\n  fi\n  rm $F\ndone\n\nrm $TMPJOIN\n\ngnuplot bench.gnu\nconvert -density 200 -resize 800x560 -flatten bench.eps bench.png\nrm bench.eps\n", "num_lines": 35}
{"repo_name": "azure-iot-hub-nodered-nodes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# for a given node version run:\n# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done;\n\nPATTERNS=('nodeuuid.v1()' \"nodeuuid.v1('binary',\" 'nodeuuid.v4()' \"nodeuuid.v4('binary',\" \"uuid()\" \"uuid('binary')\" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte')\nFILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es)\nINDICES=(2 3 2 3 2 2 2 2 2)\nVERSIONS=$( ls bench_*.log | sed -e 's/^bench_\\([0-9\\.]*\\)\\.log/\\1/' | tr \"\\\\n\" \" \" )\nTMPJOIN=\"tmp_join\"\nOUTPUT=\"bench_results.txt\"\n\nfor I in ${!FILES[*]}; do\n  F=${FILES[$I]}\n  P=${PATTERNS[$I]}\n  INDEX=${INDICES[$I]}\n  echo \"version $F\" > $F\n  for V in $VERSIONS; do\n    (VAL=$( grep \"$P\" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F\n  done\n  if [ $I == 0 ]; then\n    cat $F > $TMPJOIN\n  else\n    join $TMPJOIN $F > $OUTPUT\n    cp $OUTPUT $TMPJOIN\n  fi\n  rm $F\ndone\n\nrm $TMPJOIN\n\ngnuplot bench.gnu\nconvert -density 200 -resize 800x560 -flatten bench.eps bench.png\nrm bench.eps\n", "num_lines": 35}
{"repo_name": "azure-iot-hub-nodered-nodes", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# for a given node version run:\n# for i in {0..9}; do node benchmark.js >> bench_0.6.2.log; done;\n\nPATTERNS=('nodeuuid.v1()' \"nodeuuid.v1('binary',\" 'nodeuuid.v4()' \"nodeuuid.v4('binary',\" \"uuid()\" \"uuid('binary')\" 'uuidjs.create(1)' 'uuidjs.create(4)' '140byte')\nFILES=(node_uuid_v1_string node_uuid_v1_buf node_uuid_v4_string node_uuid_v4_buf libuuid_v4_string libuuid_v4_binary uuidjs_v1_string uuidjs_v4_string 140byte_es)\nINDICES=(2 3 2 3 2 2 2 2 2)\nVERSIONS=$( ls bench_*.log | sed -e 's/^bench_\\([0-9\\.]*\\)\\.log/\\1/' | tr \"\\\\n\" \" \" )\nTMPJOIN=\"tmp_join\"\nOUTPUT=\"bench_results.txt\"\n\nfor I in ${!FILES[*]}; do\n  F=${FILES[$I]}\n  P=${PATTERNS[$I]}\n  INDEX=${INDICES[$I]}\n  echo \"version $F\" > $F\n  for V in $VERSIONS; do\n    (VAL=$( grep \"$P\" bench_$V.log | LC_ALL=en_US awk '{ sum += $'$INDEX' } END { print sum/NR }' ); echo $V $VAL) >> $F\n  done\n  if [ $I == 0 ]; then\n    cat $F > $TMPJOIN\n  else\n    join $TMPJOIN $F > $OUTPUT\n    cp $OUTPUT $TMPJOIN\n  fi\n  rm $F\ndone\n\nrm $TMPJOIN\n\ngnuplot bench.gnu\nconvert -density 200 -resize 800x560 -flatten bench.eps bench.png\nrm bench.eps\n", "num_lines": 35}
{"repo_name": "azure-iot-middleware-freertos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# This script install dependencies of service side of e2e tests and runs e2e test\n\n# ./run.sh <RTOS connectivity interface> [FreeRTOS Src path]\n# e.g. ./run.sh rtosveth1\n\n# Trace each command by: export DEBUG_SHELL=1\nif [[ ! -z ${DEBUG_SHELL} ]]\nthen\n  set -x # Activate the expand mode if DEBUG is anything but empty.\nfi\n\nset -o errexit # Exit if command failed.\nset -o nounset # Exit if variable not set.\nset -o pipefail # Exit if pipe failed.\n\nabspath () {\n  case \"$1\" in\n  /*)\n    printf\"%s\\n\" \"$1\";;\n  *)\n    printf \"%s\\n\" \"$PWD/$1\";;\n  esac;\n}\n\nfilepath=`abspath $0`\ndir=`dirname $filepath`\ntest_root_dir=$dir/../..\ntest_freertos_src_path=${2:-\"\"}\ntest_ethernet_if=${1:-\"\"}\nUpdateNamePrefix=\"Linux-E2E-Update\"\nUpdateName=$UpdateNamePrefix-$RANDOM\nexport e2eADU_UPDATE_NAME=$UpdateName\n\n[ -n \"$test_ethernet_if\" ] || die \"\\$1=ethernet interface need to be passed; like rtosveth1\"\n[ -n \"$test_freertos_src_path\" ] || die \"\\$2=FreeRTOS source path not set\"\n\npushd \"$dir\"\n\n# Create directory for the update artifacts\nif [ ! -d \"./e2e_build\" ]\nthen\n  mkdir e2e_build\nfi\n\necho -e \"Updating FreeRTOSConfig.h to point to interface $test_ethernet_if\"\nindex=`tcpdump --list-interfaces | grep -Ei \"([0-9]+).$test_ethernet_if\" | sed -E 's/^([0-9]+).*/\\1/g'`\nsed -i \"s/#define configNETWORK_INTERFACE_TO_USE.*/#define configNETWORK_INTERFACE_TO_USE ($index)/g\" $test_root_dir/config_files/FreeRTOSConfig.h\n\n# Build and create new update image\necho -e \"::group::Build update image\"\npushd $dir/device; cmake -Bbuild -DCMAKE_BUILD_TYPE=MinSizeRel -DFREERTOS_DIRECTORY=$test_freertos_src_path -DUSE_COREHTTP=ON ../ ; cmake --build build\ncp ./build/azure_iot_e2e_adu_tests $dir/e2e_build/azure_iot_e2e_adu_tests_v1.1\npopd\n\necho -e \"::group::Clone ADU repo for scripts\"\n# Clone the device update repo for the scripting\nif [ ! -d \"./e2e_build/iot-hub-device-update\" ]\nthen\n  pushd e2e_build\n  git clone https://github.com/Azure/iot-hub-device-update\n  popd\nfi\n\n# Generate the updated executable\npushd service\n\necho -e \"::group::Create, upload, deploy update manifest and payload\"\npwsh -File ./create_and_import_manifest.ps1 -AccountEndpoint \"iotsdk-c-production-adu.api.adu.microsoft.com\" \\\n-InstanceId \"iotsdk-c-production-adu\" \\\n-UpdateVersion \"1.1\" \\\n-AzureAdClientId \"321e2686-c228-4c8d-ac77-d19674cb62b5\" \\\n-AzureAdTenantId \"72f988bf-86f1-41af-91ab-2d7cd011db47\" \\\n-AzureAdApplicationSecret $ADU_AAD_APPLICATION_SECRET \\\n-AzureSubscriptionId \"db2f889d-dd6c-4269-8d41-a38efcdace46\" \\\n-AzureResourceGroupName \"azureiot-euap-e2e\" \\\n-AzureStorageAccountName \"euapuploadacct\" \\\n-AzureBlobContainerName \"adu-e2e\" \\\n-GroupID \"linux-e2e-group\" \\\n-UpdateProvider \"ADU-E2E-Tests\" \\\n-UpdateNamePrefix $UpdateNamePrefix \\\n-UpdateName $UpdateName\n\npopd # service\n\necho -e \"::group::Revert application version | build base image\"\n\n# Revert the device version to build v1.0\nsed -i \"s/#define e2eADU_UPDATE_VERSION .*/#define e2eADU_UPDATE_VERSION \\\"1.0\\\"/g\" $dir/device/e2e_device_commands.c\n\n# Build and create base image\npushd $dir/device; cmake -Bbuild -DCMAKE_BUILD_TYPE=MinSizeRel -DFREERTOS_DIRECTORY=$test_freertos_src_path -DUSE_COREHTTP=ON ../ ; cmake --build build\ncp ./build/azure_iot_e2e_adu_tests ./build/azure_iot_e2e_adu_tests_v1.0\npopd # $dir/device\n\necho -e \"::group::Running E2E tests\"\nexport DEVICE_TEST_EXE=\"$dir/device/build/azure_iot_e2e_adu_tests_v1.0\"\nchown root $DEVICE_TEST_EXE\nchmod u+s $DEVICE_TEST_EXE\ncd $dir/service; stdbuf -o0 ./mocha_exec.sh\n", "num_lines": 105}
{"repo_name": "azure-iot-middleware-freertos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# This script install dependencies of service side of e2e tests and runs e2e test\n\nif [[ ! -z ${DEBUG_SHELL} ]]\nthen\n  set -x # Activate the expand mode if DEBUG is anything but empty.\nfi\n\nset -o errexit # Exit if command failed.\nset -o nounset # Exit if variable not set.\nset -o pipefail # Exit if pipe failed.\n\ndie() {\n    echo \"${1:-\"Unknown Error\"}\" 1>&2\n    exit 1\n}\n\n[ -v ADU_IOTHUB_CONNECTION_STRING ] || die \"ADU_IOTHUB_CONNECTION_STRING is not set!\"\n[ -v DEVICE_TEST_EXE ] || die \"DEVICE_TEST_EXE is not set!. Please set it to device side binary of e2e tests\"\n\necho -e \"Installing node dependencies using npm\"\n\nnpm install\n\necho -e \"Done installing node dependencies\"\n\necho -e \"Compiling typescripts to js\"\nnpm run build\necho -e \"Done compiling typescripts to js\"\n\necho -e \"Cleaning expired e2e resources\"\nADU_IOTHUB_CONNECTION_STRING=$ADU_IOTHUB_CONNECTION_STRING npm run cleanup\necho -e \"Done Cleaning expired e2e resources\"\n\necho -e \"Running tests\"\nADU_IOTHUB_CONNECTION_STRING=$ADU_IOTHUB_CONNECTION_STRING \\\nDEVICE_TEST_EXE=$DEVICE_TEST_EXE \\\nnpm run adu\n", "num_lines": 43}
{"repo_name": "azure-iot-middleware-freertos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# This script install dependencies of service side of e2e tests and runs e2e test\n\n# ./run.sh <RTOS connectivity interface> [FreeRTOS Src path]\n# e.g. ./run.sh rtosveth1\n\n# Trace each command by: export DEBUG_SHELL=1\nif [[ ! -z ${DEBUG_SHELL} ]]\nthen\n  set -x # Activate the expand mode if DEBUG is anything but empty.\nfi\n\nset -o errexit # Exit if command failed.\nset -o nounset # Exit if variable not set.\nset -o pipefail # Exit if pipe failed.\n\ndie() {\n    echo \"${1:-\"Unknown Error\"}\" 1>&2\n    exit 1\n}\n\nabspath () {\n  case \"$1\" in\n  /*)\n    printf\"%s\\n\" \"$1\";;\n  *)\n    printf \"%s\\n\" \"$PWD/$1\";;\n  esac;\n}\n\nfilepath=`abspath $0`\ndir=`dirname $filepath`\ntest_root_dir=$dir/../..\ntest_freertos_src_path=${2:-\"\"}\ntest_ethernet_if=${1:-\"\"}\n\n[ -n \"$test_ethernet_if\" ] || die \"\\$1=ethernet interface need to be passed; like rtosveth1\"\n[ -n \"$test_freertos_src_path\" ] || die \"\\$2=FreeRTOS source path not set\"\n\necho -e \"Updating FreeRTOSConfig.h to point to interface $test_ethernet_if\"\nindex=`tcpdump --list-interfaces | grep -Ei \"([0-9]+).$test_ethernet_if\" | sed -E 's/^([0-9]+).*/\\1/g'`\nsed -i \"s/#define configNETWORK_INTERFACE_TO_USE.*/#define configNETWORK_INTERFACE_TO_USE ($index)/g\" $test_root_dir/config_files/FreeRTOSConfig.h\n\necho -e \"::group::Building E2E tests\"\ncd $dir/device; cmake -Bbuild -DCMAKE_BUILD_TYPE=MinSizeRel -DFREERTOS_DIRECTORY=$test_freertos_src_path ../ ; cmake --build build\n\necho -e \"::group::E2E tests usage of libaz_iot_middleware_freertos.a\"\ngrep -E  \"0x\\w{16}\\s+0x\\w+ .*libaz_iot_middleware_freertos.a\" $dir/device/build/azure_iot_e2e_tests.map\necho -e \"::group::E2E tests Map file\"\ncat $dir/device/build/azure_iot_e2e_tests.map\n\necho -e \"::group::Running E2E tests\"\nexport DEVICE_TEST_EXE=\"$dir/device/build/azure_iot_e2e_tests\"\nchown root $DEVICE_TEST_EXE\nchmod u+s $DEVICE_TEST_EXE\ncd $dir/service; stdbuf -o0 ./mocha_exec.sh\n", "num_lines": 61}
{"repo_name": "azure-iot-middleware-freertos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n#\n# This script install dependencies of service side of e2e tests and runs e2e test\n\nif [[ ! -z ${DEBUG_SHELL} ]]\nthen\n  set -x # Activate the expand mode if DEBUG is anything but empty.\nfi\n\nset -o errexit # Exit if command failed.\nset -o nounset # Exit if variable not set.\nset -o pipefail # Exit if pipe failed.\n\ndie() {\n    echo \"${1:-\"Unknown Error\"}\" 1>&2\n    exit 1\n}\n\n[ -v IOTHUB_CONNECTION_STRING ] || die \"IOTHUB_CONNECTION_STRING is not set!\"\n[ -v DEVICE_TEST_EXE ] || die \"DEVICE_TEST_EXE is not set!. Please set it to device side binary of e2e tests\"\n\necho -e \"Installing node dependencies using npm\"\n\nnpm install\n\necho -e \"Done installing node dependencies\"\n\necho -e \"Compiling typescripts to js\"\nnpm run build\necho -e \"Done compiling typescripts to js\"\n\necho -e \"Cleaning expired e2e resources\"\nIOTHUB_CONNECTION_STRING=$IOTHUB_CONNECTION_STRING npm run cleanup\necho -e \"Done Cleaning expired e2e resources\"\n\n# Github Ubuntu 20.04 runners have issues running `npm run` inside an `npm run` call\n# so we don't use `npm run alltest` here. Call each one individually.\necho -e \"Running tests\"\nIOTHUB_CONNECTION_STRING=$IOTHUB_CONNECTION_STRING DEVICE_TEST_EXE=$DEVICE_TEST_EXE \\\nIOT_PROVISIONING_CONNECTION_STRING=${IOT_PROVISIONING_CONNECTION_STRING:-\"\"} \\\nIOT_PROVISIONING_SCOPE_ID=${IOT_PROVISIONING_SCOPE_ID:-\"\"} \\\nnpm run iothub_e2e_test\nnpm run iothub_e2e_test_using_dm\nnpm run iot_provisioning_e2e_test\nnpm run iot_provisioning_e2e_test_using_dm\n", "num_lines": 49}
{"repo_name": "azure-iot-pal-arduino", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root/sdk/c-utility/build_all/linux\n\n# -- C --\n./build.sh --run-unittests --run_valgrind --build-root $build_root \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 12}
{"repo_name": "azure-iot-pal-esp32", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root/sdk/c-utility/build_all/linux\n\n# -- C --\n./build.sh --run-unittests --run_valgrind --build-root $build_root \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 12}
{"repo_name": "azure-iot-pal-esp32", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root/sdk/c-utility/build_all/linux\n\n# -- C --\n./build.sh --run-unittests --run_valgrind --build-root $build_root \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 12}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\n# Solution: devicesimulation\n\n# Important:\n# 1. The script runs in an environment with old/strict shell support, so don't rely on Bash niceties\n# 2. The script is designed NOT to throw errors, to avoid secrets ending in azureiotsolutions.com logs\n# 3. In case of errors, the script terminates with exit code \"1\" which must be caught by the deployment service to inform the user.\n# 4. The script invokes setup.sh script and checks for errors returned by the script, logging to a file in the VM.\n\n# Enable this for debugging only\n##set -ex\n\nAPP_PATH=\"/app\"\nSETUP_LOG=\"${APP_PATH}/setup.log\"\n\n# Loop through arguments and extract some parameters, without modifying $@ needed later\nfor X in \"$@\"; do\n    case \"$PREVIOUS\" in\n        --release-version) PCS_RELEASE_VERSION=\"$X\" ;;\n    esac\n    PREVIOUS=\"$X\"\ndone\n\nif [ -z \"$PCS_RELEASE_VERSION\" ]; then\n    echo \"Release version not specified (see --release-version)\"\n    exit 1\nfi\n\n# Note: this points to the solution WITH an IoT Hub service\nSETUP_SCRIPTS_URL=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-device-simulation/${PCS_RELEASE_VERSION}/arm-deployment/devicesimulation/single-vm\"\n\nmkdir -p ${APP_PATH}\ncd ${APP_PATH}\n\n# Create log file, make it writable and empty (for local tests)\ntouch ${SETUP_LOG} && chmod 660 ${SETUP_LOG} && echo > ${SETUP_LOG}\nif [ $? -ne 0 ]; then\n    echo \"Unable to create log file '${SETUP_LOG}'\"\n    exit 1\nfi\n\n# Download actual setup script, and exit if the download fails\nrm -f setup.sh                          >> ${SETUP_LOG} 2>&1 \\\n    && wget $SETUP_SCRIPTS_URL/setup.sh >> ${SETUP_LOG} 2>&1 \\\n    && chmod 750 setup.sh               >> ${SETUP_LOG} 2>&1\nif [ $? -ne 0 ]; then\n    echo \"Unable to download '${SETUP_SCRIPTS_URL}/setup.sh'\"\n    cat ${SETUP_LOG}\n    exit 1\nfi\n\n# Invoke setup script\n./setup.sh \"${@}\" >> ${SETUP_LOG} 2>&1\nRESULT=$?\necho \"Exit code: $RESULT\"\nif [ $RESULT -ne 0 ]; then\n    echo \"Setup failed, please see log file '${SETUP_LOG}' for more information\"\n    exit 1\nfi\n", "num_lines": 62}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\n\n# Solution: devicesimulation\n\n# Note: this script is invoked by setup-wrapper.sh and errors are stored in /app/setup.log\nset -ex\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\nENVVARS=\"${APP_PATH}/env-vars\"\nDOCKERCOMPOSE=\"${APP_PATH}/docker-compose.yml\"\nCERTS=\"${APP_PATH}/certs\"\nCERT=\"${CERTS}/tls.crt\"\nPKEY=\"${CERTS}/tls.key\"\n\n# ========================================================================\n\n# Default values\nexport HOST_NAME=\"localhost\"\nexport PCS_LOG_LEVEL=\"Info\"\nexport PCS_WEBUI_AUTH_TYPE=\"aad\"\nexport PCS_IOTHUB_CONNSTRING=\"\"\n\nwhile [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n        --solution-setup-url)      PCS_SOLUTION_SETUP_URL=\"$2\" ;; # e.g. https://raw.githubusercontent.com/Azure/device-simulatio-dotnet/DS-1.0.0/arm-deployment/devicesimulation\n        --release-version)         PCS_RELEASE_VERSION=\"$2\" ;;\n        --docker-tag)              PCS_DOCKER_TAG=\"$2\" ;;\n        --solution-type)           PCS_SOLUTION_TYPE=\"$2\" ;;\n        --solution-name)           PCS_SOLUTION_NAME=\"$2\" ;;\n        --subscription-domain)     PCS_SUBSCRIPTION_DOMAIN=\"$2\" ;;\n        --subscription-id)         PCS_SUBSCRIPTION_ID=\"$2\" ;;\n        --hostname)                HOST_NAME=\"$2\" ;;\n        --log-level)               PCS_LOG_LEVEL=\"$2\" ;;\n        --resource-group)          PCS_RESOURCE_GROUP=\"$2\" ;;\n        --docdb-name)              PCS_DOCDB_NAME=\"$2\" ;;\n        --docdb-connstring)        PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"$2\" ;;\n        --ssl-certificate)         PCS_CERTIFICATE=\"$2\" ;;\n        --ssl-certificate-key)     PCS_CERTIFICATE_KEY=\"$2\" ;;\n        --auth-audience)           PCS_AUTH_AUDIENCE=\"$2\" ;;\n        --auth-issuer)             PCS_AUTH_ISSUER=\"$2\" ;;\n        --auth-type)               PCS_WEBUI_AUTH_TYPE=\"$2\" ;;\n        --aad-appid)               PCS_WEBUI_AUTH_AAD_APPID=\"$2\" ;;\n        --aad-sp-client-id)        PCS_AAD_CLIENT_SP_ID=\"$2\" ;;\n        --aad-app-secret)          PCS_AAD_SECRET=\"$2\" ;;\n        --aad-tenant)              PCS_WEBUI_AUTH_AAD_TENANT=\"$2\" ;;\n        --aad-instance)            PCS_WEBUI_AUTH_AAD_INSTANCE=\"$2\" ;;\n        --cloud-type)              PCS_CLOUD_TYPE=\"$2\" ;;\n        --deployment-id)           PCS_DEPLOYMENT_ID=\"$2\" ;;\n        --resource-group-location) PCS_RESOURCE_GROUP_LOCATION=\"$2\" ;;\n        --vmss-name)               PCS_VMSS_NAME=\"$2\" ;;\n        --storage-connstring)      PCS_AZURE_STORAGE_ACCOUNT=\"$2\" ;;\n        --iothub-name)             PCS_IOHUB_NAME=\"$2\" ;;\n        --iothub-sku)              PCS_IOTHUB_SKU=\"$2\" ;;\n        --iothub-tier)             PCS_IOTHUB_TIER=\"$2\" ;;\n        --iothub-units)            PCS_IOTHUB_UNITS=\"$2\" ;;\n        --iothub-connstring)       PCS_IOTHUB_CONNSTRING=\"$2\" ;;\n        --app-insights-ikey)       PCS_APPINSIGHTS_INSTRUMENTATIONKEY=\"$2\" ;;\n    esac\n    shift\ndone\n\nif [ -z \"$PCS_SOLUTION_SETUP_URL\" ]; then\n    echo \"Setup URL not specified (see --solution-setup-url)\"\n    exit 1\nfi\n\nif [ -z \"$PCS_RELEASE_VERSION\" ]; then\n    echo \"Release version not specified (see --release-version)\"\n    exit 1\nfi\n\n# Note: Solution = devicesimulation\nREPOSITORY=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-device-simulation/${PCS_RELEASE_VERSION}/arm-deployment/devicesimulation/single-vm\"\nSCRIPTS_URL=\"${REPOSITORY}/scripts/\"\nSETUP_URL=\"${REPOSITORY}/setup/\"\n\n# ========================================================================\n\n### Install Docker and Docker Compose\n\ninstall_docker_ce() {\n    apt-get update -o Acquire::CompressionTypes::Order::=gz \\\n        && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y \\\n        && apt-get update \\\n        && apt-get remove docker docker-engine docker.io \\\n        && apt-get -y --allow-downgrades --allow-remove-essential --allow-change-held-packages --no-install-recommends install apt-transport-https ca-certificates curl gnupg2 software-properties-common \\\n        && curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\")/gpg | sudo apt-key add - \\\n        && add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\") $(lsb_release -cs) stable\" \\\n        && apt-get update \\\n        && DEBIAN_FRONTEND=noninteractive apt-get -y --allow-downgrades install docker-ce docker-compose \\\n        && docker run --rm hello-world && docker rmi hello-world\n\n    local RESULT=$?\n    if [ $RESULT -ne 0 ]; then\n        INSTALL_DOCKER_RESULT=\"FAIL\"\n    else\n        INSTALL_DOCKER_RESULT=\"OK\"\n    fi\n}\n\nset +e\nINSTALL_DOCKER_RESULT=\"OK\"\ninstall_docker_ce\nif [ \"$INSTALL_DOCKER_RESULT\" != \"OK\" ]; then\n    set -e\n    echo \"Error: first attempt to install Docker failed, retrying...\"\n    # Retry once, in case apt wasn't ready\n    sleep 30\n    install_docker_ce\n    if [ \"$INSTALL_DOCKER_RESULT\" != \"OK\" ]; then\n        echo \"Error: Docker installation failed\"\n        exit 1\n    fi\nfi\nset -e\n\n# ========================================================================\n\n# Configure Docker registry based on host name\n# ToDo: we may need to add similar parameter to AzureGermanCloud and AzureUSGovernment\nconfig_for_azure_china() {\n    set +e\n    local host_name=$1\n    if (echo $host_name | grep -c  \"\\.cn$\") ; then\n        # If the host name has .cn suffix, dockerhub in China will be used to avoid slow network traffic failure.\n        local config_file='/etc/docker/daemon.json'\n        echo \"{\\\"registry-mirrors\\\": [\\\"https://registry.docker-cn.com\\\"]}\" > ${config_file}\n        service docker restart\n\n        # Rewrite the AAD issuer in Azure China environment\n        export PCS_AUTH_ISSUER=\"https://sts.chinacloudapi.cn/$2/\"\n    fi\n    set -e\n}\n\nconfig_for_azure_china $HOST_NAME $PCS_WEBUI_AUTH_AAD_TENANT\n\n# ========================================================================\n\n# Note: the directory might already exists, with \"-p\" there is no error\nmkdir -p ${APP_PATH}\ncd ${APP_PATH}\n\n# ========================================================================\n\n# Docker compose file\n\nDOCKERCOMPOSE_SOURCE=\"${PCS_SOLUTION_SETUP_URL}/single-vm/docker-compose.yml\"\nwget $DOCKERCOMPOSE_SOURCE -O ${DOCKERCOMPOSE}\nsed -i 's/${PCS_DOCKER_TAG}/'${PCS_DOCKER_TAG}'/g' ${DOCKERCOMPOSE}\n\n# ========================================================================\n\n# HTTPS certificates\nmkdir -p ${CERTS}\ntouch ${CERT} && chmod 550 ${CERT}\ntouch ${PKEY} && chmod 550 ${PKEY}\n# Always have quotes around the certificate and key value to preserve the formatting\necho \"${PCS_CERTIFICATE}\"      > ${CERT}\necho \"${PCS_CERTIFICATE_KEY}\"  > ${PKEY}\n\n# ========================================================================\n\n# Download scripts\nwget $SCRIPTS_URL/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh\nwget $SCRIPTS_URL/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh\nwget $SCRIPTS_URL/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh\nwget $SCRIPTS_URL/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh\nwget $SCRIPTS_URL/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh\n\n# ========================================================================\n\n# Web App configuration\ntouch ${WEBUICONFIG} && chmod 444 ${WEBUICONFIG}\ntouch ${WEBUICONFIG_SAFE} && chmod 444 ${WEBUICONFIG_SAFE}\ntouch ${WEBUICONFIG_UNSAFE} && chmod 444 ${WEBUICONFIG_UNSAFE}\n\necho \"var DeploymentConfig = {\"                        > ${WEBUICONFIG_SAFE}\necho \"  solutionName: '${PCS_SOLUTION_NAME}',\"        >> ${WEBUICONFIG_SAFE}\necho \"  authEnabled: true,\"                           >> ${WEBUICONFIG_SAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_SAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_SAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_SAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_SAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_SAFE}\necho \"  },\"                                           >> ${WEBUICONFIG_SAFE}\necho \"  maxDevicesPerSimulation: 20000,\"              >> ${WEBUICONFIG_SAFE}\necho \"  minTelemetryInterval: 10000\"                  >> ${WEBUICONFIG_SAFE}\necho \"}\"                                              >> ${WEBUICONFIG_SAFE}\n\necho \"var DeploymentConfig = {\"                        > ${WEBUICONFIG_UNSAFE}\necho \"  solutionName: '${PCS_SOLUTION_NAME}',\"        >> ${WEBUICONFIG_UNSAFE}\necho \"  authEnabled: false,\"                          >> ${WEBUICONFIG_UNSAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_UNSAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_UNSAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_UNSAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_UNSAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_UNSAFE}\necho \"  },\"                                           >> ${WEBUICONFIG_UNSAFE}\necho \"  maxDevicesPerSimulation: 20000,\"              >> ${WEBUICONFIG_UNSAFE}\necho \"  minTelemetryInterval: 10000\"                  >> ${WEBUICONFIG_UNSAFE}\necho \"}\"                                              >> ${WEBUICONFIG_UNSAFE}\n\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\n# ========================================================================\n\n# Environment variables\ntouch ${ENVVARS} && chmod 440 ${ENVVARS}\n\necho \"# Valid values: Debug, Info, Warn, Error\"                                                           > ${ENVVARS}\necho \"export PCS_LOG_LEVEL=\\\"${PCS_LOG_LEVEL}\\\"\"                                                         >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"export HOST_NAME=\\\"${HOST_NAME}\\\"\"                                                                 >> ${ENVVARS}\necho \"export PCS_AUTH_ISSUER=\\\"${PCS_AUTH_ISSUER}\\\"\"                                                     >> ${ENVVARS}\necho \"export PCS_AUTH_AUDIENCE=\\\"${PCS_AUTH_AUDIENCE}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_IOTHUB_CONNSTRING=\\\"${PCS_IOTHUB_CONNSTRING}\\\"\"                                         >> ${ENVVARS}\necho \"export PCS_IOHUB_NAME=\\\"${PCS_IOHUB_NAME}\\\"\"                                                       >> ${ENVVARS}\necho \"export PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\\\"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\\\"\"   >> ${ENVVARS}\necho \"export PCS_SUBSCRIPTION_DOMAIN=\\\"${PCS_SUBSCRIPTION_DOMAIN}\\\"\"                                     >> ${ENVVARS}\necho \"export PCS_SUBSCRIPTION_ID=\\\"${PCS_SUBSCRIPTION_ID}\\\"\"                                             >> ${ENVVARS}\necho \"export PCS_WEBUI_AUTH_AAD_APPID=\\\"${PCS_WEBUI_AUTH_AAD_APPID}\\\"\"                                   >> ${ENVVARS}\necho \"export PCS_WEBUI_AUTH_AAD_TENANT=\\\"${PCS_WEBUI_AUTH_AAD_TENANT}\\\"\"                                 >> ${ENVVARS}\necho \"export PCS_AAD_CLIENT_SP_ID=\\\"${PCS_AAD_CLIENT_SP_ID}\\\"\"                                           >> ${ENVVARS}\necho \"export PCS_AAD_SECRET=\\\"${PCS_AAD_SECRET}\\\"\"                                                       >> ${ENVVARS}\necho \"export PCS_RESOURCE_GROUP=\\\"${PCS_RESOURCE_GROUP}\\\"\"                                               >> ${ENVVARS}\necho \"export PCS_SOLUTION_TYPE=\\\"${PCS_SOLUTION_TYPE}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_SOLUTION_NAME=\\\"${PCS_SOLUTION_NAME}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_SEED_TEMPLATE=\\\"multiple-simulations-template\\\"\"                                        >> ${ENVVARS}\necho \"export PCS_CLOUD_TYPE=\\\"${PCS_CLOUD_TYPE}\\\"\"                                                       >> ${ENVVARS}\necho \"export PCS_DEPLOYMENT_ID=\\\"${PCS_DEPLOYMENT_ID}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_AZURE_STORAGE_ACCOUNT=\\\"${PCS_AZURE_STORAGE_ACCOUNT}\\\"\"                                 >> ${ENVVARS}\necho \"export PCS_RESOURCE_GROUP_LOCATION=\\\"${PCS_RESOURCE_GROUP_LOCATION}\\\"\"                             >> ${ENVVARS}\necho \"export PCS_VMSS_NAME=\\\"${PCS_VMSS_NAME}\\\"\"                                                         >> ${ENVVARS}\necho \"export PCS_APPINSIGHTS_INSTRUMENTATIONKEY=\\\"${PCS_APPINSIGHTS_INSTRUMENTATIONKEY}\\\"\"               >> ${ENVVARS}\n\n# Setting some empty vars as these are required vars by Config service\necho \"export PCS_DEVICESIMULATION_WEBSERVICE_URL=\\\"\\\"\"                                                   >> ${ENVVARS}\necho \"export PCS_TELEMETRY_WEBSERVICE_URL=\\\"\\\"\"                                                          >> ${ENVVARS}\necho \"export PCS_IOTHUBMANAGER_WEBSERVICE_URL=\\\"\\\"\"                                                      >> ${ENVVARS}\necho \"export PCS_BINGMAP_KEY=\\\"\\\"\"                                                                       >> ${ENVVARS}\n\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"##########################################################################################\"        >> ${ENVVARS}\necho \"# Development settings, don't change these in Production\"                                          >> ${ENVVARS}\necho \"# You can run 'start.sh --unsafe' to temporarily disable Auth and Cross-Origin protections\"        >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: true | false\"                                                                            >> ${ENVVARS}\necho \"# empty => Auth required\"                                                                          >> ${ENVVARS}\necho \"export PCS_AUTH_REQUIRED=\\\"\\\"\"                                                                     >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: { 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"                                >> ${ENVVARS}\necho \"# empty => CORS support disabled\"                                                                  >> ${ENVVARS}\necho \"export PCS_CORS_WHITELIST=\\\"\\\"\"                                                                    >> ${ENVVARS}\n\n# ========================================================================\n\n# Shell environment enhancements\necho \"### CUSTOMIZATIONS ###\" >> /etc/nanorc\nwget $SETUP_URL/nanorc -O /tmp/nanorc && cat /tmp/nanorc >> /etc/nanorc\n\necho \"### CUSTOMIZATIONS ###\" >> /etc/bash.bashrc\nwget $SETUP_URL/bashrc -O /tmp/bashrc && cat /tmp/bashrc >> /etc/bash.bashrc\n\n# Optional script to customize Bash shell, to be executed manually by the user\nwget https://aka.ms/bashir-setup -O /etc/bashir-script \\\n    && chmod 444 /etc/bashir-script \\\n    && echo 'cat /etc/bashir-script | bash && . ~/.bashir && echo \"Restart Bash to see the changes (e.g. exit and login again).\"' > /usr/local/bin/bashir-setup \\\n    && chmod 755 /usr/local/bin/bashir-setup\n\n# ========================================================================\n\n# Auto-start after reboots\nwget $SETUP_URL/init -O /etc/init.d/azure-iot-solution \\\n    && chmod 755 /etc/init.d/azure-iot-solution \\\n    && update-rc.d azure-iot-solution defaults\n\n# ========================================================================\n\nnohup /app/start.sh > /dev/null 2>&1&\n", "num_lines": 286}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\nif [[ \"$1\" == \"\" ]]; then\n  docker-compose logs\nelse\n  docker logs -f --tail 100 $1\nfi\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Network settings\nsysctl -w net.ipv4.ip_local_port_range=\"1024 65535\"\nsysctl -w net.ipv4.tcp_max_syn_backlog=4096\nsysctl -w net.core.somaxconn=1024\n\ncd /app\n\nsource \"env-vars\"\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_WARN=\"\\033[1;33m\" # light yellow\nCOL_ERR=\"\\033[1;31m\" # light red\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\n\nrm -f ${WEBUICONFIG}\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\nif [[ \"$1\" == \"--unsafe\" || \"$2\" == \"--unsafe\" ]]; then\n  echo -e \"${COL_ERR}WARNING! Starting services in UNSAFE mode!${COL_NO}\"\n  # Disable Auth\n  export PCS_AUTH_REQUIRED=\"false\"\n  # Allow cross-origin requests from anywhere\n  export PCS_CORS_WHITELIST=\"{ 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"\n\n  rm -f ${WEBUICONFIG}\n  cp -p ${WEBUICONFIG_UNSAFE} ${WEBUICONFIG}\nfi\n\nlist=$(docker ps -aq)\nif [ -n \"$list\" ]; then\n    echo -e \"${COL_WARN}Stopping existing services...${COL_NO}\"\n    docker rm -f $list\nfi\n\nif [[ \"$1\" == \"--debug\" || \"$2\" == \"--debug\" ]]; then\n  echo -e \"${COL_WARN}Starting services... Press CTRL+C to exit${COL_NO}\"\n  docker-compose up\n  exit 0\nfi\n\necho -e \"${COL_WARN}Starting services...${COL_NO}\"\nnohup docker-compose up > /dev/null 2>&1&\n\nISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\nwhile [[ \"$ISUP\" == \"0\" ]]; do\n  echo \"Waiting for web site to start...\"\n  sleep 3\n  ISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\ndone\n", "num_lines": 59}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\ndocker stats -a\n", "num_lines": 9}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\necho\n\ndocker-compose ps\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_MARK=\"\\033[1;33m\" # yellow\n\necho -e \"\\n${COL_MARK}Run ./logs.sh <service name> to see the logs of a service.${COL_NO}\"\n", "num_lines": 16}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nlist=$(docker ps -aq)\n\nif [ -n \"$list\" ]; then\n    docker rm -f $list\nfi\n", "num_lines": 11}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\n# Solution: devicesimulation-nohub\n\n# Important:\n# 1. The script runs in an environment with old/strict shell support, so don't rely on Bash niceties\n# 2. The script is designed NOT to throw errors, to avoid secrets ending in azureiotsolutions.com logs\n# 3. In case of errors, the script terminates with exit code \"1\" which must be caught by the deployment service to inform the user.\n# 4. The script invokes setup.sh script and checks for errors returned by the script, logging to a file in the VM.\n\n# Enable this for debugging only\n##set -ex\n\nAPP_PATH=\"/app\"\nSETUP_LOG=\"${APP_PATH}/setup.log\"\n\n# Loop through arguments and extract some parameters, without modifying $@ needed later\nfor X in \"$@\"; do\n    case \"$PREVIOUS\" in\n        --release-version) PCS_RELEASE_VERSION=\"$X\" ;;\n    esac\n    PREVIOUS=\"$X\"\ndone\n\nif [ -z \"$PCS_RELEASE_VERSION\" ]; then\n    echo \"Release version not specified (see --release-version)\"\n    exit 1\nfi\n\n# Note: this points to the solution WITHOUT an IoT Hub service\nSETUP_SCRIPTS_URL=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-device-simulation/${PCS_RELEASE_VERSION}/arm-deployment/devicesimulation-nohub/single-vm/\"\n\nmkdir -p ${APP_PATH}\ncd ${APP_PATH}\n\n# Create log file, make it writable and empty (for local tests)\ntouch ${SETUP_LOG} && chmod 660 ${SETUP_LOG} && echo > ${SETUP_LOG}\nif [ $? -ne 0 ]; then\n    echo \"Unable to create log file '${SETUP_LOG}'\"\n    exit 1\nfi\n\n# Download actual setup script, and exit if the download fails\nrm -f setup.sh                          >> ${SETUP_LOG} 2>&1 \\\n    && wget $SETUP_SCRIPTS_URL/setup.sh >> ${SETUP_LOG} 2>&1 \\\n    && chmod 750 setup.sh               >> ${SETUP_LOG} 2>&1\nif [ $? -ne 0 ]; then\n    echo \"Unable to download '${SETUP_SCRIPTS_URL}/setup.sh'\"\n    cat ${SETUP_LOG}\n    exit 1\nfi\n\n# Invoke setup script\n./setup.sh \"${@}\" >> ${SETUP_LOG} 2>&1\nRESULT=$?\necho \"Exit code: $RESULT\"\nif [ $RESULT -ne 0 ]; then\n    echo \"Setup failed, please see log file '${SETUP_LOG}' for more information\"\n    exit 1\nfi\n", "num_lines": 62}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\n\n# Solution: devicesimulation-nohub\n\n# Note: this script is invoked by setup-wrapper.sh and errors are stored in /app/setup.log\nset -ex\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\nENVVARS=\"${APP_PATH}/env-vars\"\nDOCKERCOMPOSE=\"${APP_PATH}/docker-compose.yml\"\nCERTS=\"${APP_PATH}/certs\"\nCERT=\"${CERTS}/tls.crt\"\nPKEY=\"${CERTS}/tls.key\"\n\n# ========================================================================\n\n# Default values\nexport HOST_NAME=\"localhost\"\nexport PCS_LOG_LEVEL=\"Info\"\nexport PCS_WEBUI_AUTH_TYPE=\"aad\"\nexport PCS_IOTHUB_CONNSTRING=\"\"\n\nwhile [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n        --solution-setup-url)      PCS_SOLUTION_SETUP_URL=\"$2\" ;; # e.g. https://raw.githubusercontent.com/Azure/azure-iot-pcs-device-simulation/DS-1.0.0/arm-deployment/devicesimulation-nohub\n        --release-version)         PCS_RELEASE_VERSION=\"$2\" ;;\n        --docker-tag)              PCS_DOCKER_TAG=\"$2\" ;;\n        --solution-type)           PCS_SOLUTION_TYPE=\"$2\" ;;\n        --solution-name)           PCS_SOLUTION_NAME=\"$2\" ;;\n        --subscription-domain)     PCS_SUBSCRIPTION_DOMAIN=\"$2\" ;;\n        --subscription-id)         PCS_SUBSCRIPTION_ID=\"$2\" ;;\n        --hostname)                HOST_NAME=\"$2\" ;;\n        --log-level)               PCS_LOG_LEVEL=\"$2\" ;;\n        --resource-group)          PCS_RESOURCE_GROUP=\"$2\" ;;\n        --docdb-name)              PCS_DOCDB_NAME=\"$2\" ;;\n        --docdb-connstring)        PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"$2\" ;;\n        --ssl-certificate)         PCS_CERTIFICATE=\"$2\" ;;\n        --ssl-certificate-key)     PCS_CERTIFICATE_KEY=\"$2\" ;;\n        --auth-audience)           PCS_AUTH_AUDIENCE=\"$2\" ;;\n        --auth-issuer)             PCS_AUTH_ISSUER=\"$2\" ;;\n        --auth-type)               PCS_WEBUI_AUTH_TYPE=\"$2\" ;;\n        --aad-appid)               PCS_WEBUI_AUTH_AAD_APPID=\"$2\" ;;\n        --aad-sp-client-id)        PCS_AAD_CLIENT_SP_ID=\"$2\" ;;\n        --aad-app-secret)          PCS_AAD_SECRET=\"$2\" ;;\n        --aad-tenant)              PCS_WEBUI_AUTH_AAD_TENANT=\"$2\" ;;\n        --aad-instance)            PCS_WEBUI_AUTH_AAD_INSTANCE=\"$2\" ;;\n        --cloud-type)              PCS_CLOUD_TYPE=\"$2\" ;;\n        --deployment-id)           PCS_DEPLOYMENT_ID=\"$2\" ;;\n        --resource-group-location) PCS_RESOURCE_GROUP_LOCATION=\"$2\" ;;\n        --vmss-name)               PCS_VMSS_NAME=\"$2\" ;;\n        --storage-connstring)      PCS_AZURE_STORAGE_ACCOUNT=\"$2\" ;;\n        --app-insights-ikey)       PCS_APPINSIGHTS_INSTRUMENTATIONKEY=\"$2\" ;;\n    esac\n    shift\ndone\n\nif [ -z \"$PCS_SOLUTION_SETUP_URL\" ]; then\n    echo \"Setup URL not specified (see --solution-setup-url)\"\n    exit 1\nfi\n\nif [ -z \"$PCS_RELEASE_VERSION\" ]; then\n    echo \"Release version not specified (see --release-version)\"\n    exit 1\nfi\n\n# Note: Solution = devicesimulation-nohub\nREPOSITORY=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-device-simulation/${PCS_RELEASE_VERSION}/arm-deployment/devicesimulation-nohub/single-vm\"\nSCRIPTS_URL=\"${REPOSITORY}/scripts/\"\nSETUP_URL=\"${REPOSITORY}/setup/\"\n\n# ========================================================================\n\n### Install Docker and Docker Compose\n\ninstall_docker_ce() {\n    apt-get update -o Acquire::CompressionTypes::Order::=gz \\\n        && DEBIAN_FRONTEND=noninteractive apt-get upgrade -y \\\n        && apt-get update \\\n        && apt-get remove docker docker-engine docker.io \\\n        && apt-get -y --allow-downgrades --allow-remove-essential --allow-change-held-packages --no-install-recommends install apt-transport-https ca-certificates curl gnupg2 software-properties-common \\\n        && curl -fsSL https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\")/gpg | sudo apt-key add - \\\n        && add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/$(. /etc/os-release; echo \"$ID\") $(lsb_release -cs) stable\" \\\n        && apt-get update \\\n        && DEBIAN_FRONTEND=noninteractive apt-get -y --allow-downgrades install docker-ce docker-compose \\\n        && docker run --rm hello-world && docker rmi hello-world\n\n    local RESULT=$?\n    if [ $RESULT -ne 0 ]; then\n        INSTALL_DOCKER_RESULT=\"FAIL\"\n    else\n        INSTALL_DOCKER_RESULT=\"OK\"\n    fi\n}\n\nset +e\nINSTALL_DOCKER_RESULT=\"OK\"\ninstall_docker_ce\nif [ \"$INSTALL_DOCKER_RESULT\" != \"OK\" ]; then\n    set -e\n    echo \"Error: first attempt to install Docker failed, retrying...\"\n    # Retry once, in case apt wasn't ready\n    sleep 30\n    install_docker_ce\n    if [ \"$INSTALL_DOCKER_RESULT\" != \"OK\" ]; then\n        echo \"Error: Docker installation failed\"\n        exit 1\n    fi\nfi\nset -e\n\n# ========================================================================\n\n# Configure Docker registry based on host name\n# ToDo: we may need to add similar parameter to AzureGermanCloud and AzureUSGovernment\nconfig_for_azure_china() {\n    set +e\n    local host_name=$1\n    if (echo $host_name | grep -c  \"\\.cn$\") ; then\n        # If the host name has .cn suffix, dockerhub in China will be used to avoid slow network traffic failure.\n        local config_file='/etc/docker/daemon.json'\n        echo \"{\\\"registry-mirrors\\\": [\\\"https://registry.docker-cn.com\\\"]}\" > ${config_file}\n        service docker restart\n\n        # Rewrite the AAD issuer in Azure China environment\n        export PCS_AUTH_ISSUER=\"https://sts.chinacloudapi.cn/$2/\"\n    fi\n    set -e\n}\n\nconfig_for_azure_china $HOST_NAME $PCS_WEBUI_AUTH_AAD_TENANT\n\n# ========================================================================\n\n# Note: the directory might already exists, with \"-p\" there is no error\nmkdir -p ${APP_PATH}\ncd ${APP_PATH}\n\n# ========================================================================\n\n# Docker compose file\n\nDOCKERCOMPOSE_SOURCE=\"${PCS_SOLUTION_SETUP_URL}/single-vm/docker-compose.yml\"\nwget $DOCKERCOMPOSE_SOURCE -O ${DOCKERCOMPOSE}\nsed -i 's/${PCS_DOCKER_TAG}/'${PCS_DOCKER_TAG}'/g' ${DOCKERCOMPOSE}\n\n# ========================================================================\n\n# HTTPS certificates\nmkdir -p ${CERTS}\ntouch ${CERT} && chmod 550 ${CERT}\ntouch ${PKEY} && chmod 550 ${PKEY}\n# Always have quotes around the certificate and key value to preserve the formatting\necho \"${PCS_CERTIFICATE}\"      > ${CERT}\necho \"${PCS_CERTIFICATE_KEY}\"  > ${PKEY}\n\n# ========================================================================\n\n# Download scripts\nwget $SCRIPTS_URL/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh\nwget $SCRIPTS_URL/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh\nwget $SCRIPTS_URL/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh\nwget $SCRIPTS_URL/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh\nwget $SCRIPTS_URL/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh\n\n# ========================================================================\n\n# Web App configuration\ntouch ${WEBUICONFIG} && chmod 444 ${WEBUICONFIG}\ntouch ${WEBUICONFIG_SAFE} && chmod 444 ${WEBUICONFIG_SAFE}\ntouch ${WEBUICONFIG_UNSAFE} && chmod 444 ${WEBUICONFIG_UNSAFE}\n\necho \"var DeploymentConfig = {\"                        > ${WEBUICONFIG_SAFE}\necho \"  solutionName: '${PCS_SOLUTION_NAME}',\"        >> ${WEBUICONFIG_SAFE}\necho \"  authEnabled: true,\"                           >> ${WEBUICONFIG_SAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_SAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_SAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_SAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_SAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_SAFE}\necho \"  },\"                                           >> ${WEBUICONFIG_SAFE}\necho \"  maxDevicesPerSimulation: 20000,\"              >> ${WEBUICONFIG_SAFE}\necho \"  minTelemetryInterval: 10000\"                  >> ${WEBUICONFIG_SAFE}\necho \"}\"                                              >> ${WEBUICONFIG_SAFE}\n\necho \"var DeploymentConfig = {\"                        > ${WEBUICONFIG_UNSAFE}\necho \"  solutionName: '${PCS_SOLUTION_NAME}',\"        >> ${WEBUICONFIG_UNSAFE}\necho \"  authEnabled: false,\"                          >> ${WEBUICONFIG_UNSAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_UNSAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_UNSAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_UNSAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_UNSAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_UNSAFE}\necho \"  },\"                                           >> ${WEBUICONFIG_UNSAFE}\necho \"  maxDevicesPerSimulation: 20000,\"              >> ${WEBUICONFIG_UNSAFE}\necho \"  minTelemetryInterval: 10000\"                  >> ${WEBUICONFIG_UNSAFE}\necho \"}\"                                              >> ${WEBUICONFIG_UNSAFE}\n\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\n# ========================================================================\n\n# Environment variables\ntouch ${ENVVARS} && chmod 440 ${ENVVARS}\n\necho \"# Valid values: Debug, Info, Warn, Error\"                                                           > ${ENVVARS}\necho \"export PCS_LOG_LEVEL=\\\"${PCS_LOG_LEVEL}\\\"\"                                                         >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"export HOST_NAME=\\\"${HOST_NAME}\\\"\"                                                                 >> ${ENVVARS}\necho \"export PCS_AUTH_ISSUER=\\\"${PCS_AUTH_ISSUER}\\\"\"                                                     >> ${ENVVARS}\necho \"export PCS_AUTH_AUDIENCE=\\\"${PCS_AUTH_AUDIENCE}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\\\"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\\\"\"   >> ${ENVVARS}\necho \"export PCS_SUBSCRIPTION_DOMAIN=\\\"${PCS_SUBSCRIPTION_DOMAIN}\\\"\"                                     >> ${ENVVARS}\necho \"export PCS_SUBSCRIPTION_ID=\\\"${PCS_SUBSCRIPTION_ID}\\\"\"                                             >> ${ENVVARS}\necho \"export PCS_WEBUI_AUTH_AAD_APPID=\\\"${PCS_WEBUI_AUTH_AAD_APPID}\\\"\"                                   >> ${ENVVARS}\necho \"export PCS_WEBUI_AUTH_AAD_TENANT=\\\"${PCS_WEBUI_AUTH_AAD_TENANT}\\\"\"                                 >> ${ENVVARS}\necho \"export PCS_AAD_CLIENT_SP_ID=\\\"${PCS_AAD_CLIENT_SP_ID}\\\"\"                                           >> ${ENVVARS}\necho \"export PCS_AAD_SECRET=\\\"${PCS_AAD_SECRET}\\\"\"                                                       >> ${ENVVARS}\necho \"export PCS_RESOURCE_GROUP=\\\"${PCS_RESOURCE_GROUP}\\\"\"                                               >> ${ENVVARS}\necho \"export PCS_SOLUTION_TYPE=\\\"${PCS_SOLUTION_TYPE}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_SOLUTION_NAME=\\\"${PCS_SOLUTION_NAME}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_SEED_TEMPLATE=\\\"multiple-simulations-template\\\"\"                                        >> ${ENVVARS}\necho \"export PCS_CLOUD_TYPE=\\\"${PCS_CLOUD_TYPE}\\\"\"                                                       >> ${ENVVARS}\necho \"export PCS_DEPLOYMENT_ID=\\\"${PCS_DEPLOYMENT_ID}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_AZURE_STORAGE_ACCOUNT=\\\"${PCS_AZURE_STORAGE_ACCOUNT}\\\"\"                                 >> ${ENVVARS}\necho \"export PCS_RESOURCE_GROUP_LOCATION=\\\"${PCS_RESOURCE_GROUP_LOCATION}\\\"\"                             >> ${ENVVARS}\necho \"export PCS_VMSS_NAME=\\\"${PCS_VMSS_NAME}\\\"\"                                                         >> ${ENVVARS}\necho \"export PCS_APPINSIGHTS_INSTRUMENTATIONKEY=\\\"${PCS_APPINSIGHTS_INSTRUMENTATIONKEY}\\\"\"               >> ${ENVVARS}\n\n# Setting some empty vars as these are required vars by Config service\necho \"export PCS_DEVICESIMULATION_WEBSERVICE_URL=\\\"\\\"\"                                                   >> ${ENVVARS}\necho \"export PCS_TELEMETRY_WEBSERVICE_URL=\\\"\\\"\"                                                          >> ${ENVVARS}\necho \"export PCS_IOTHUBMANAGER_WEBSERVICE_URL=\\\"\\\"\"                                                      >> ${ENVVARS}\necho \"export PCS_BINGMAP_KEY=\\\"\\\"\"                                                                       >> ${ENVVARS}\n\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"##########################################################################################\"        >> ${ENVVARS}\necho \"# Development settings, don't change these in Production\"                                          >> ${ENVVARS}\necho \"# You can run 'start.sh --unsafe' to temporarily disable Auth and Cross-Origin protections\"        >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: true | false\"                                                                            >> ${ENVVARS}\necho \"# empty => Auth required\"                                                                          >> ${ENVVARS}\necho \"export PCS_AUTH_REQUIRED=\\\"\\\"\"                                                                     >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: { 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"                                >> ${ENVVARS}\necho \"# empty => CORS support disabled\"                                                                  >> ${ENVVARS}\necho \"export PCS_CORS_WHITELIST=\\\"\\\"\"                                                                    >> ${ENVVARS}\n\n# ========================================================================\n\n# Shell environment enhancements\necho \"### CUSTOMIZATIONS ###\" >> /etc/nanorc\nwget $SETUP_URL/nanorc -O /tmp/nanorc && cat /tmp/nanorc >> /etc/nanorc\n\necho \"### CUSTOMIZATIONS ###\" >> /etc/bash.bashrc\nwget $SETUP_URL/bashrc -O /tmp/bashrc && cat /tmp/bashrc >> /etc/bash.bashrc\n\n# Optional script to customize Bash shell, to be executed manually by the user\nwget https://aka.ms/bashir-setup -O /etc/bashir-script \\\n    && chmod 444 /etc/bashir-script \\\n    && echo 'cat /etc/bashir-script | bash && . ~/.bashir && echo \"Restart Bash to see the changes (e.g. exit and login again).\"' > /usr/local/bin/bashir-setup \\\n    && chmod 755 /usr/local/bin/bashir-setup\n\n# ========================================================================\n\n# Auto-start after reboots\nwget $SETUP_URL/init -O /etc/init.d/azure-iot-solution \\\n    && chmod 755 /etc/init.d/azure-iot-solution \\\n    && update-rc.d azure-iot-solution defaults\n\n# ========================================================================\n\nnohup /app/start.sh > /dev/null 2>&1&\n", "num_lines": 279}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\nif [[ \"$1\" == \"\" ]]; then\n  docker-compose logs\nelse\n  docker logs -f --tail 100 $1\nfi\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Network settings\nsysctl -w net.ipv4.ip_local_port_range=\"1024 65535\"\nsysctl -w net.ipv4.tcp_max_syn_backlog=4096\nsysctl -w net.core.somaxconn=1024\n\ncd /app\n\nsource \"env-vars\"\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_WARN=\"\\033[1;33m\" # light yellow\nCOL_ERR=\"\\033[1;31m\" # light red\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\n\nrm -f ${WEBUICONFIG}\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\nif [[ \"$1\" == \"--unsafe\" || \"$2\" == \"--unsafe\" ]]; then\n  echo -e \"${COL_ERR}WARNING! Starting services in UNSAFE mode!${COL_NO}\"\n  # Disable Auth\n  export PCS_AUTH_REQUIRED=\"false\"\n  # Allow cross-origin requests from anywhere\n  export PCS_CORS_WHITELIST=\"{ 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"\n\n  rm -f ${WEBUICONFIG}\n  cp -p ${WEBUICONFIG_UNSAFE} ${WEBUICONFIG}\nfi\n\nlist=$(docker ps -aq)\nif [ -n \"$list\" ]; then\n    echo -e \"${COL_WARN}Stopping existing services...${COL_NO}\"\n    docker rm -f $list\nfi\n\nif [[ \"$1\" == \"--debug\" || \"$2\" == \"--debug\" ]]; then\n  echo -e \"${COL_WARN}Starting services... Press CTRL+C to exit${COL_NO}\"\n  docker-compose up\n  exit 0\nfi\n\necho -e \"${COL_WARN}Starting services...${COL_NO}\"\nnohup docker-compose up > /dev/null 2>&1&\n\nISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\nwhile [[ \"$ISUP\" == \"0\" ]]; do\n  echo \"Waiting for web site to start...\"\n  sleep 3\n  ISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\ndone\n", "num_lines": 59}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\ndocker stats -a\n", "num_lines": 9}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\ncd /app\n\necho\n\ndocker-compose ps\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_MARK=\"\\033[1;33m\" # yellow\n\necho -e \"\\n${COL_MARK}Run ./logs.sh <service name> to see the logs of a service.${COL_NO}\"\n", "num_lines": 16}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nlist=$(docker ps -aq)\n\nif [ -n \"$list\" ]; then\n    docker rm -f $list\nfi\n", "num_lines": 11}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e -x\n\nmkdir -p /app/logs\nnginx -c /app/nginx.conf\n", "num_lines": 7}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nSIM_ID=\"$1\"\nDEVICE_COUNT=\"$2\"\n\nif [ -z \"$SIM_ID\" ]; then\n    echo \"Simulation ID not specified. Usage: <script> <SIM_ID> <COUNT>\"\n    exit 1\nfi\n\nif [ -z \"$DEVICE_COUNT\" ]; then\n    echo \"Simulation ID not specified. Usage: <script> <SIM_ID> <COUNT>\"\n    exit 1\nfi\n\nCONN_STRING=\"default\"\nSIM_ENABLED=\"true\"\nDELETE_DEVICES=\"true\"\n\nJSON='{'\nJSON=$JSON'\"Name\": \"-\",'\nJSON=$JSON'\"Description\": \"-\",'\n#JSON=$JSON'\"StartTime\": \"...\",'\n#JSON=$JSON'\"EndTime\": \"...\",'\nJSON=$JSON'\"Enabled\": '$SIM_ENABLED','\nJSON=$JSON'\"DeleteDevicesWhenSimulationEnds\": '$DELETE_DEVICES','\nJSON=$JSON'\"IoTHubs\": [{ \"ConnectionString\": \"'$CONN_STRING'\" }],'\nJSON=$JSON'\"DeviceModels\": [{\"Id\": \"truck-01\",\"Count\": '$DEVICE_COUNT'}],'\nJSON=$JSON'\"RateLimits\": {'\nJSON=$JSON'\"RegistryOperationsPerMinute\": 100,'\nJSON=$JSON'\"TwinReadsPerSecond\": 10,'\nJSON=$JSON'\"TwinWritesPerSecond\": 10,'\nJSON=$JSON'\"ConnectionsPerSecond\": 120,'\nJSON=$JSON'\"DeviceMessagesPerSecond\": 120'\nJSON=$JSON'}'\nJSON=$JSON'}'\n\ncurl -v -X PUT 'http://localhost:9003/v1/simulations/'$SIM_ID \\\n    -H 'Content-Type: application/json' \\\n    -d \"${JSON}\"", "num_lines": 42}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nSIM_ID=\"$1\"\n\nif [ -z \"$SIM_ID\" ]; then\n    echo \"Simulation ID not specified. Usage: <script> <SIM_ID>\"\n    exit 1\nfi\n\ncurl -v -X DELETE 'http://localhost:9003/v1/simulations/'$SIM_ID", "num_lines": 12}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# You can uncomment and set your connection string here\n# BECAREFUL not to commit this file into the repository\n\n# PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"AccountEndpoint=https://_______.documents.azure.com:443/;AccountKey=_______;\"\n\nif [ ! -z \"$1\" ]; then\n    PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"$1\"\nfi\n\ndocker run -itd \\\n    -p 9022:9022 \\\n    -e PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING \\\n    --name pcs-storage-adapter \\\n    azureiotpcs/pcs-storage-adapter-dotnet:testing\n", "num_lines": 17}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\ncd /app/\n\ncd webservice && dotnet Microsoft.Azure.IoTSolutions.DeviceSimulation.WebService.dll\n", "num_lines": 7}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nchmod ugo+x ./scripts/build\nchmod ugo+x ./scripts/compile\nchmod ugo+x ./scripts/run\nchmod ugo+x ./scripts/clean-up\nchmod ugo+x ./scripts/env-vars-check\nchmod ugo+x ./scripts/env-vars-setup\nchmod ugo+x ./scripts/travis\nchmod ugo+x ./scripts/docker/build\nchmod ugo+x ./scripts/docker/run\nchmod ugo+x ./scripts/docker/publish\nchmod ugo+x ./scripts/docker/content/*.sh 2> /dev/null\nchmod ugo+x ./scripts/git/setup\nchmod ugo+x ./scripts/git/*.sh\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/compile\ngit update-index --chmod=+x ./scripts/run\ngit update-index --chmod=+x ./scripts/clean-up\ngit update-index --chmod=+x ./scripts/env-vars-check\ngit update-index --chmod=+x ./scripts/env-vars-setup\ngit update-index --chmod=+x ./scripts/travis\ngit update-index --chmod=+x ./scripts/docker/build\ngit update-index --chmod=+x ./scripts/docker/run\ngit update-index --chmod=+x ./scripts/docker/publish\ngit update-index --chmod=+x ./scripts/docker/content/*.sh\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\n\nset +e\n", "num_lines": 42}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --no-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --with-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build --in-sandbox\n    else\n        ./build\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 124}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncd /app/\n\ncd webservice\n\ndotnet Microsoft.Azure.IoTSolutions.UIConfig.WebService.dll\n", "num_lines": 8}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nset +e\n\nchmod ugo+x ./scripts/build               2> /dev/null\nchmod ugo+x ./scripts/compile             2> /dev/null\nchmod ugo+x ./scripts/run                 2> /dev/null\nchmod ugo+x ./scripts/clean-up            2> /dev/null\nchmod ugo+x ./scripts/env-vars-check      2> /dev/null\nchmod ugo+x ./scripts/env-vars-setup      2> /dev/null\nchmod ugo+x ./scripts/travis              2> /dev/null\nchmod ugo+x ./scripts/docker/build        2> /dev/null\nchmod ugo+x ./scripts/docker/run          2> /dev/null\nchmod ugo+x ./scripts/docker/publish      2> /dev/null\nchmod ugo+x ./scripts/docker/content/*.sh 2> /dev/null\nchmod ugo+x ./scripts/git/setup           2> /dev/null\nchmod ugo+x ./scripts/git/*.sh            2> /dev/null\n\nif [ -d ./scripts/iothub ]; then\n  chmod ugo+x ./scripts/iothub/*.sh       2> /dev/null\nfi\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/compile\ngit update-index --chmod=+x ./scripts/run\ngit update-index --chmod=+x ./scripts/clean-up\ngit update-index --chmod=+x ./scripts/env-vars-check\ngit update-index --chmod=+x ./scripts/env-vars-setup\ngit update-index --chmod=+x ./scripts/travis\ngit update-index --chmod=+x ./scripts/docker/build\ngit update-index --chmod=+x ./scripts/docker/run\ngit update-index --chmod=+x ./scripts/docker/publish\ngit update-index --chmod=+x ./scripts/docker/content/*.sh\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\n\nif [ -d ./scripts/iothub ]; then\n  git update-index --chmod=+x ./scripts/iothub/*.sh\nfi\n", "num_lines": 47}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --no-sandbox\n\nset +e\n", "num_lines": 12}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --with-sandbox\n\nset +e\n", "num_lines": 12}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build --in-sandbox\n    else\n        ./build\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 122}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\ncd /app/\n\ncd webservice\n\ndotnet Microsoft.Azure.IoTSolutions.Diagnostics.WebService.dll\n", "num_lines": 9}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nset +e\n\nchmod ugo+x ./scripts/build               2> /dev/null\nchmod ugo+x ./scripts/compile             2> /dev/null\nchmod ugo+x ./scripts/run                 2> /dev/null\nchmod ugo+x ./scripts/clean-up            2> /dev/null\nchmod ugo+x ./scripts/env-vars-check      2> /dev/null\nchmod ugo+x ./scripts/env-vars-setup      2> /dev/null\nchmod ugo+x ./scripts/travis              2> /dev/null\nchmod ugo+x ./scripts/docker/build        2> /dev/null\nchmod ugo+x ./scripts/docker/run          2> /dev/null\nchmod ugo+x ./scripts/docker/publish      2> /dev/null\nchmod ugo+x ./scripts/docker/content/*.sh 2> /dev/null\nchmod ugo+x ./scripts/git/setup           2> /dev/null\nchmod ugo+x ./scripts/git/*.sh            2> /dev/null\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/compile\ngit update-index --chmod=+x ./scripts/run\ngit update-index --chmod=+x ./scripts/clean-up\ngit update-index --chmod=+x ./scripts/env-vars-check\ngit update-index --chmod=+x ./scripts/env-vars-setup\ngit update-index --chmod=+x ./scripts/travis\ngit update-index --chmod=+x ./scripts/docker/build\ngit update-index --chmod=+x ./scripts/docker/run\ngit update-index --chmod=+x ./scripts/docker/publish\ngit update-index --chmod=+x ./scripts/docker/content/*.sh\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\n", "num_lines": 42}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --no-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --with-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n\nset -e\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build.cmd --in-sandbox\n    else\n        ./build.cmd\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 123}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -ex\n\n# serve the app via nginx\nmkdir -p /app/logs\nnginx -g 'daemon off;' -c /app/nginx.conf\n", "num_lines": 9}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nset +e\n\nchmod ugo+x ./scripts/build               2> /dev/null\nchmod ugo+x ./scripts/git/setup           2> /dev/null\nchmod ugo+x ./scripts/git/*.sh            2> /dev/null\n\nif [ -d ./scripts/docker ]; then\n  chmod ugo+x ./scripts/docker/build        2> /dev/null\n  chmod ugo+x ./scripts/docker/run          2> /dev/null\n  chmod ugo+x ./scripts/docker/publish      2> /dev/null\n  chmod ugo+x ./scripts/docker/content/*.sh 2> /dev/null\nfi\n\nif [ -d ./scripts/iothub ]; then\n  chmod ugo+x ./scripts/iothub/*.sh       2> /dev/null\nfi\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\n\nif [ -d ./scripts/docker ]; then\n  git update-index --chmod=+x ./scripts/docker/build\n  git update-index --chmod=+x ./scripts/docker/run\n  git update-index --chmod=+x ./scripts/docker/publish\n  git update-index --chmod=+x ./scripts/docker/content/*.sh\nfi\n\nif [ -d ./scripts/iothub ]; then\n  git update-index --chmod=+x ./scripts/iothub/*.sh\nfi\n", "num_lines": 44}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    ./build\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 118}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncd /app/\n\ncd webservice\n\ndotnet Microsoft.Azure.IoTSolutions.StorageAdapter.WebService.dll\n", "num_lines": 8}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nset +e\n\nchmod ugo+x ./scripts/build               2> /dev/null\nchmod ugo+x ./scripts/compile             2> /dev/null\nchmod ugo+x ./scripts/run                 2> /dev/null\nchmod ugo+x ./scripts/clean-up            2> /dev/null\nchmod ugo+x ./scripts/env-vars-check      2> /dev/null\nchmod ugo+x ./scripts/env-vars-setup      2> /dev/null\nchmod ugo+x ./scripts/travis              2> /dev/null\nchmod ugo+x ./scripts/docker/build        2> /dev/null\nchmod ugo+x ./scripts/docker/run          2> /dev/null\nchmod ugo+x ./scripts/docker/publish      2> /dev/null\nchmod ugo+x ./scripts/docker/content/*.sh 2> /dev/null\nchmod ugo+x ./scripts/git/setup           2> /dev/null\nchmod ugo+x ./scripts/git/*.sh            2> /dev/null\n\nif [ -d ./scripts/iothub ]; then\n  chmod ugo+x ./scripts/iothub/*.sh       2> /dev/null\nfi\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/compile\ngit update-index --chmod=+x ./scripts/run\ngit update-index --chmod=+x ./scripts/clean-up\ngit update-index --chmod=+x ./scripts/env-vars-check\ngit update-index --chmod=+x ./scripts/env-vars-setup\ngit update-index --chmod=+x ./scripts/travis\ngit update-index --chmod=+x ./scripts/docker/build\ngit update-index --chmod=+x ./scripts/docker/run\ngit update-index --chmod=+x ./scripts/docker/publish\ngit update-index --chmod=+x ./scripts/docker/content/*.sh\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\n\nif [ -d ./scripts/iothub ]; then\n  git update-index --chmod=+x ./scripts/iothub/*.sh\nfi\n", "num_lines": 50}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --no-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh --with-sandbox\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build --in-sandbox\n    else\n        ./build\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 124}
{"repo_name": "azure-iot-pcs-device-simulation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nwhile [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n        --release_version)              RELEASE_VERSION=\"$2\" ;;\n        --git_access_token)             GIT_ACCESS_TOKEN=\"$2\" ;;\n        --docker_user)                  DOCKER_USER=\"$2\" ;;\n        --docker_pwd)                   DOCKER_PWD=\"$2\" ;;\n        --from_docker_namespace)        FROM_DOCKER_NAMESPACE=\"$2\" ;;\n        --to_docker_namespace)          TO_DOCKER_NAMESPACE=\"$2\" ;;\n        --docker_tag)                   DOCKER_TAG=\"$2\" ;;\n        --description)                  DESCRIPTION=\"$2\" ;;\n        --pre_release)                  PRE_RELEASE=\"$2\" ;;\n        --local)                        LOCAL=\"$2\" ;;\n    esac\n    shift\ndone\n\n# Set default values for optional parameters\nFROM_DOCKER_NAMESPACE=${FROM_DOCKER_NAMESPACE:-azureiotpcs}\nTO_DOCKER_NAMESPACE=${TO_DOCKER_NAMESPACE:-azureiotpcs}\nDOCKER_TAG=${DOCKER_TAG:-testing}\nDESCRIPTION=${DESCRIPTION:-''}\nPRE_RELEASE=${PRE_RELEASE:-false}\nLOCAL=${LOCAL:-''}\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\n\nNC=\"\\033[0m\" # no color\nCYAN=\"\\033[1;36m\" # light cyan\nYELLOW=\"\\033[1;33m\" # yellow\nRED=\"\\033[1;31m\" # light red\n\nfailed() {\n    SUB_MODULE=$1\n    echo -e \"${RED}Cannot find directory $SUB_MODULE${NC}\"\n    exit 1\n}\n\nusage() {\n    echo -e \"${RED}ERROR: $1 is a required option${NC}\"\n    echo \"Usage: ./release\"\n    echo -e 'Options:\n        --release_version       Version of this release (required)\n        --git_access_token      Git access token to push tag (required)\n        --docker_user           Username to login docker hub (required)\n        --docker_pwd            Password to login docker hub (required)\n        --from_docker_namespace Source namespace of docker image (default:azureiotpcs)\n        --to_docker_namespace   Target namespace of docker image (default:azureiotpcs)\n        --docker_tag            Source tag of docker image (default:testing)\n        --description           Description of this release (default:empty)\n        --pre_release           Publish as non-production release on github (default:false)\n        --local                 Clean up the local repo at first (default:empty)\n        '\n    exit 1\n}\n\ncheck_input() {\n    if [ ! -n \"$RELEASE_VERSION\" ]; then\n        usage \"release_version\"\n    fi\n    if [ ! -n \"$DOCKER_USER\" ]; then\n        usage \"docker_user\"\n    fi\n    echo $DOCKER_PWD | docker login -u $DOCKER_USER --password-stdin\n}\n\ntag_build_publish_repo() {\n    SUB_MODULE=$1\n    REPO_NAME=$2\n    DOCKER_CONTAINER_NAME=${3:-$2}\n    DESCRIPTION=$4\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Tagging the $REPO_NAME repo     ====================================${NC}\"\n    echo\n    echo -e \"Current working directory ${CYAN}$APP_HOME$SUB_MODULE${NC}\"\n    echo\n    cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE\n\n    if [ -n \"$LOCAL\" ]; then\n        echo \"Cleaning the repo\"\n        git reset --hard origin/master\n        git clean -xdf\n    fi\n\n    if [ \"$REPO_NAME\" == \"pcs-config-dotnet\" ]; then\n        git checkout RemoveServiceDependency\n    else\n        git checkout master\n    fi\n\n    echo \"set url\"\n    git remote set-url origin https://$GIT_ACCESS_TOKEN@github.com/Azure/$REPO_NAME.git\n\n    echo \"git pull\"\n    git pull --all --prune\n\n    echo \"git tag\"\n    git tag --force $RELEASE_VERSION\n\n    echo \"git push\"\n    git push https://$GIT_ACCESS_TOKEN@github.com/Azure/$REPO_NAME.git $RELEASE_VERSION\n\n    echo\n    echo -e \"${CYAN}====================================     End: Tagging $REPO_NAME repo     ====================================${NC}\"\n    echo\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n\n    # For documentation https://help.github.com/articles/creating-releases/\n    DATA=\"{\n        \\\"tag_name\\\": \\\"$RELEASE_VERSION\\\",\n        \\\"target_commitish\\\": \\\"master\\\",\n        \\\"name\\\": \\\"$RELEASE_VERSION\\\",\n        \\\"body\\\": \\\"$DESCRIPTION\\\",\n        \\\"draft\\\": false,\n        \\\"prerelease\\\": $PRE_RELEASE\n    }\"\n\n    curl -X POST --data \"$DATA\" https://api.github.com/repos/Azure/$REPO_NAME/releases?access_token=$GIT_ACCESS_TOKEN\n    echo\n    echo -e \"${CYAN}====================================     End: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n\n    if [ -n \"$SUB_MODULE\" ] && [ \"$REPO_NAME\" != \"pcs-cli\" ]; then\n        echo\n        echo -e \"${CYAN}====================================     Start: Building $REPO_NAME     ====================================${NC}\"\n        echo\n\n        BUILD_PATH=\"scripts/docker/build\"\n        if [ \"$SUB_MODULE\" == \"api-gateway\" ]; then \n            BUILD_PATH=\"build\"\n        fi\n\n        # Building docker containers\n        echo \"Building docker containers\"\n        echo $APP_HOME$SUB_MODULE/$BUILD_PATH\n        /bin/bash $APP_HOME$SUB_MODULE/$BUILD_PATH\n\n        echo\n        echo -e \"${CYAN}====================================     End: Building $REPO_NAME     ====================================${NC}\"\n        echo\n        \n        # Tag containers\n        echo -e \"${CYAN}Tagging $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG ==> $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$RELEASE_VERSION${NC}\"\n        echo\n        docker tag $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG  $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$RELEASE_VERSION\n\n        # Push containers\n        echo -e \"${CYAN}Pusing container $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$RELEASE_VERSION${NC}\"\n        docker push $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$RELEASE_VERSION\n    fi\n}\n\ncheck_input\n\n# DOTNET Microservices\n# As of DS-2.0.6, only the Web UI and the Simulation service containers are\n# refrenced by a new docker tag for each release (in docker-compse.yaml in the\n# deployed VMs)\ntag_build_publish_repo simulation-service     device-simulation-dotnet\ntag_build_publish_repo webui                  pcs-simulation-webui              device-simulation-webui\ntag_build_publish_repo pcs-diagnostics-dotnet pcs-diagnostics-dotnet\ntag_build_publish_repo storage-service        pcs-storage-adapter-dotnet\ntag_build_publish_repo pcs-config-dotnet      pcs-config-dotnet\n#tag_build_publish_repo api-gateway            azure-iot-pcs-device-simulation   simulation-api-gateway\n\nset +e", "num_lines": 174}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -e\nset -x\n\nmkdir -p /app/logs\nnginx -c /app/config/nginx.conf\n", "num_lines": 7}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\ncd $APP_HOME\n\ngit checkout master\ngit pull\n\nCOL=\"\\e[93m\\e[1m\"\nNOCOL=\"\\e[0m\"\n\necho -e \"${COL}### Auth${NOCOL}\"\ngit submodule update auth              && cd auth              && git checkout master && git pull && cd ..\necho -e \"${COL}### CLI${NOCOL}\"\ngit submodule update cli               && cd cli               && git checkout master && git pull && cd ..\necho -e \"${COL}### Config${NOCOL}\"\ngit submodule update config            && cd config            && git checkout master && git pull && cd ..\necho -e \"${COL}### Device Simulation${NOCOL}\"\ngit submodule update device-simulation && cd device-simulation && git checkout master && git pull && cd ..\necho -e \"${COL}### IoT Hub Manager${NOCOL}\"\ngit submodule update iothub-manager    && cd iothub-manager    && git checkout master && git pull && cd ..\necho -e \"${COL}### Storage Adapter${NOCOL}\"\ngit submodule update storage-adapter   && cd storage-adapter   && git checkout master && git pull && cd ..\necho -e \"${COL}### Telemetry${NOCOL}\"\ngit submodule update telemetry         && cd telemetry         && git checkout master && git pull && cd ..\necho -e \"${COL}### ASA Manager${NOCOL}\"\ngit submodule update asa-manager       && cd asa-manager       && git checkout master && git pull && cd ..\necho -e \"${COL}### Web UI${NOCOL}\"\ngit submodule update webui             && cd webui             && git checkout master && git pull && cd ..\n", "num_lines": 33}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/pre-commit.sh\"\n", "num_lines": 6}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    ./build\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n", "num_lines": 112}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nwhile [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n        --version)                      VERSION=\"$2\" ;;\n        --git_access_token)             GIT_ACCESS_TOKEN=\"$2\" ;;\n        --docker_user)                  DOCKER_USER=\"$2\" ;;\n        --docker_pwd)                   DOCKER_PWD=\"$2\" ;;\n        --from_docker_namespace)        FROM_DOCKER_NAMESPACE=\"$2\" ;;\n        --to_docker_namespace)          TO_DOCKER_NAMESPACE=\"$2\" ;;\n        --docker_tag)                   DOCKER_TAG=\"$2\" ;;\n        --description)                  DESCRIPTION=\"$2\" ;;\n        --pre_release)                  PRE_RELEASE=\"$2\" ;;\n        --local)                        LOCAL=\"$2\" ;;\n    esac\n    shift\ndone\n\n# Set default values for optional parameters\nFROM_DOCKER_NAMESPACE=${FROM_DOCKER_NAMESPACE:-azureiotpcs}\nTO_DOCKER_NAMESPACE=${TO_DOCKER_NAMESPACE:-azureiotpcs}\nDOCKER_TAG=${DOCKER_TAG:-testing}\nDESCRIPTION=${DESCRIPTION:-''}\nPRE_RELEASE=${PRE_RELEASE:-false}\nLOCAL=${LOCAL:-''}\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\n\nNC=\"\\033[0m\" # no color\nCYAN=\"\\033[1;36m\" # light cyan\nYELLOW=\"\\033[1;33m\" # yellow\nRED=\"\\033[1;31m\" # light red\n\nfailed() {\n    SUB_MODULE=$1\n    echo -e \"${RED}Cannot find directory $SUB_MODULE${NC}\"\n    exit 1\n}\n\nusage() {\n    echo -e \"${RED}ERROR: $1 is a required option${NC}\"\n    echo \"Usage: ./release\"\n    echo -e 'Options:\n        --version               Version of this release (required)\n        --git_access_token      Git access token to push tag (required)\n        --docker_user           Username to login docker hub (required)\n        --docker_pwd            Password to login docker hub (required)\n        --from_docker_namespace Source namespace of docker image (default:azureiotpcs)\n        --to_docker_namespace   Target namespace of docker image (default:azureiotpcs)\n        --docker_tag            Source tag of docker image (default:testing)\n        --description           Description of this release (default:empty)\n        --pre_release           Publish as non-production release on github (default:false)\n        --local                 Clean up the local repo at first (default:empty)\n        '\n    exit 1\n}\n\ncheck_input() {\n    if [ ! -n \"$VERSION\" ]; then\n        usage \"version\"\n    fi\n    if [ ! -n \"$GIT_ACCESS_TOKEN\" ]; then\n        usage \"git_access_token\"\n    fi\n    if [ ! -n \"$DOCKER_USER\" ]; then\n        usage \"docker_user\"\n    fi\n    if [ ! -n \"$DOCKER_PWD\" ]; then\n        usage \"docker_pwd\"\n    fi\n    echo $DOCKER_PWD | docker login -u $DOCKER_USER --password-stdin\n}\n\ntag_release_repo() {\n    SUB_MODULE=$1\n    REPO_NAME=$2\n    DESCRIPTION=$3\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Tagging the $REPO_NAME repo     ====================================${NC}\"\n    echo\n    echo -e \"Current working directory ${CYAN}$APP_HOME$SUB_MODULE${NC}\"\n    echo\n    cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE\n\n    if [ -n \"$LOCAL\" ]; then\n        echo \"Cleaning the repo\"\n        git reset --hard origin/master\n        git clean -xdf\n    fi\n    git checkout master\n    git pull --all --prune\n    git fetch --tags\n\n    git tag --force $VERSION\n    git push https://$GIT_ACCESS_TOKEN@github.com/Azure/$REPO_NAME.git $VERSION\n\n    echo\n    echo -e \"${CYAN}====================================     End: Tagging $REPO_NAME repo     ====================================${NC}\"\n    echo\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n\n    # For documentation https://help.github.com/articles/creating-releases/\n    DATA=\"{\n        \\\"tag_name\\\": \\\"$VERSION\\\",\n        \\\"target_commitish\\\": \\\"master\\\",\n        \\\"name\\\": \\\"$VERSION\\\",\n        \\\"body\\\": \\\"$DESCRIPTION\\\",\n        \\\"draft\\\": false,\n        \\\"prerelease\\\": $PRE_RELEASE\n    }\"\n\n    curl -X POST --data \"$DATA\" https://api.github.com/repos/Azure/$REPO_NAME/releases?access_token=$GIT_ACCESS_TOKEN\n    echo\n    echo -e \"${CYAN}====================================     End: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n}\n\npublish_docker_containers()\n{\n    DOCKER_CONTAINER_NAME=$1\n    SUB_MODULE=$2\n\n    if [ \"$SUB_MODULE\" == \"reverse-proxy\" ]; then\n        cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE\n        if [ -n \"$LOCAL\" ]; then\n            echo \"Cleaning the repo\"\n            git reset --hard origin/master\n            git clean -xdf\n        fi\n        git checkout master\n        git pull --all --prune\n\n        echo\n        echo -e \"${CYAN}====================================     Start: Building $DOCKER_CONTAINER_NAME     ====================================${NC}\"\n        echo\n\n        BUILD_PATH=\"build\"\n        # Building docker containers\n        /bin/bash $APP_HOME$SUB_MODULE/$BUILD_PATH\n        \n        echo\n        echo -e \"${CYAN}====================================     End: Building $DOCKER_CONTAINER_NAME     ====================================${NC}\"\n        echo\n    else\n        # Pull containers\n        echo -e \"${CYAN}Pulling $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG${NC}\"\n        echo\n        docker pull $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG\n    fi\n    \n    # Tag containers\n    echo -e \"${CYAN}Tagging $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG ==> $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}\"\n    echo\n    docker tag $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG  $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION\n\n    # Push containers\n    echo -e \"${CYAN}Pusing container $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}\"\n    docker push $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION\n}\n\ncheck_input\n\n# Publish DOTNET Microservices docker containers\npublish_docker_containers pcs-auth-dotnet\npublish_docker_containers pcs-config-dotnet\npublish_docker_containers device-simulation-dotnet\npublish_docker_containers iothub-manager-dotnet\npublish_docker_containers pcs-storage-adapter-dotnet\npublish_docker_containers telemetry-dotnet\npublish_docker_containers asa-manager-dotnet\npublish_docker_containers pcs-remote-monitoring-webui\npublish_docker_containers pcs-diagnostics-dotnet\n# Top Level repo\npublish_docker_containers remote-monitoring-nginx       reverse-proxy\n\n# # Release and Tag all the repositories with latest version\ntag_release_repo          webui                           pcs-remote-monitoring-webui\ntag_release_repo          services                        remote-monitoring-services-dotnet\n# PCS CLI\ntag_release_repo          cli                             pcs-cli\n# Top Level repo\ntag_release_repo          \"\"                              azure-iot-pcs-remote-monitoring-dotnet $DESCRIPTION\n\nset +e\n", "num_lines": 192}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nif [[ \"$1\" == \"-a\" || \"$1\" == \"--all-options\" ]]; then\n    ADVANCED=true\nelse\n    ADVANCED=false\nfi\n\nSUBSCRIPTION=\"\"\nHUB_NAME=\"\"\nRESOURCE_GROUP=\"\"\nNEW_RESOURCE_GROUP=\"false\"\nLOCATION=\"\"\nSKU=\"\"\nMAXUNITS=\"\"\nUNITS=\"\"\nD2C_PARTITIONS=\"\"\nD2C_TTL=\"\"\nC2D_ATTEMPTS=\"\"\nC2D_TTL=\"\"\nC2D_FEEDBACK_LOCK=\"\"\nC2D_FEEDBACK_TTL=\"\"\nC2D_FEEDBACK_ATTEMPTS=\"\"\n\nask_hub_name() {\n    header \"New Azure IoT Hub\"\n    HUB_NAME=\"\"\n\n    while [[ -z \"$HUB_NAME\" ]]; do\n        echo -n \"Enter IoT Hub name: \"\n        read HUB_NAME\n    done\n}\n\nselect_resource_group() {\n    header \"Resource group\"\n\n    echo \"Existing resource groups\"\n\n    azure group list\n\n    echo\n    announce \"You can re-use an existing group or enter a new name to create a new resource group.\"\n    echo\n    RESOURCE_GROUP=\"\"\n    while [[ -z \"$RESOURCE_GROUP\" ]]; do\n        echo -n \"Enter resource group name: \"\n        read RESOURCE_GROUP\n    done\n\n    NEW_RESOURCE_GROUP=\"false\"\n    TEST=$(azure group list | grep -i \"$RESOURCE_GROUP\")\n    if [[ -z \"$TEST\" ]]; then\n        NEW_RESOURCE_GROUP=\"true\"\n    fi\n}\n\nselect_location() {\n    header \"Azure region\"\n\n    # TODO: az account list-locations + filter for IoT Hub\n    echo -e \"Select the location where to create the hub:\"\n    PS3=\">> \"\n    select LOCATION in eastus westus westus2 westcentralus northeurope westeurope eastasia southeastasia japaneast japanwest australiaeast australiasoutheast; do\n        break;\n    done\n}\n\nselect_sku_and_units() {\n    header \"Pricing and Scale Tier\"\n\n    echo \"F1: 8k messages/unit/day (free)\"\n    echo \"S1: 400k messages/unit/day\"\n    echo \"S2: 6M messages/unit/day\"\n    echo \"S3: 300M messages/unit/day\"\n\n    echo -e \"\\nSelect pricing and scale:\"\n    PS3=\">> \"\n    select SKU in F1 S1 S2 S3; do\n        case $SKU in\n            F1 ) MAXUNITS=1; break;;\n            S1 ) MAXUNITS=200; break;;\n            S2 ) MAXUNITS=200; break;;\n            S3 ) MAXUNITS=10; break;;\n        esac\n    done\n\n    UNITS=\"1\"\n    if [[ \"$SKU\" != \"F1\" ]]; then\n        echo -n -e \"\\nHow many units? (1..${MAXUNITS}) [${UNITS}]: \"\n        read TEMP\n        if [[ ! -z \"$TEMP\" ]]; then UNITS=\"$TEMP\"; fi\n    fi\n}\n\nask_d2c_partitions() {\n    D2C_PARTITIONS=\"2\" # 2..128 (2 for F1)\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    if [[ \"$SKU\" != \"F1\" ]]; then\n        echo -n \"How many partitions? (1..128) [${D2C_PARTITIONS}]: \"\n        read TEMP\n        if [[ ! -z \"$TEMP\" ]]; then D2C_PARTITIONS=\"$TEMP\"; fi\n    fi\n}\n\nask_d2c_retention() {\n    D2C_TTL=\"1\" # 1..7 days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many days before device-to-cloud messages expire? (1..7) [${D2C_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then D2C_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_attempts() {\n    C2D_ATTEMPTS=\"10\" # 1..100 count\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many attempts to deliver a cloud-to-device message? (1..100) [${C2D_ATTEMPTS}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_ATTEMPTS=\"$TEMP\"; fi\n}\n\nask_c2d_ttl() {\n    # PnYnMnDTnHnMnS\n    C2D_TTL=\"PT1H\" # 1 min .. 2 days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device messages expire? (ISO8601: 1 min .. 2 days) [${C2D_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_lock() {\n    # PnYnMnDTnHnMnS\n    C2D_FEEDBACK_LOCK=\"PT1M\" # 5 secs .. 5 mins\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device feedback messages lock expire? (ISO8601: 5 secs .. 5 mins) [${C2D_FEEDBACK_LOCK}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_LOCK=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_ttl() {\n    # PnYnMnDTnHnMnS\n    C2D_FEEDBACK_TTL=\"PT1M\" # 1 min .. 2days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device feedback messages expire? (ISO8601: 1 min .. 2days) [${C2D_FEEDBACK_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_attempts() {\n    C2D_FEEDBACK_ATTEMPTS=\"1\" # 1..100 count\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many attempts to deliver a cloud-to-device feedback message? (1..100) [${C2D_FEEDBACK_ATTEMPTS}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_ATTEMPTS=\"$TEMP\"; fi\n}\n\nadvanced() {\n    if [[ \"$ADVANCED\" == \"true\" ]]; then\n        header \"Other settings\";\n    else\n        announce \"Using default settings. Use '--all-options' to manually set all the hub options.\"\n    fi\n\n    ask_d2c_partitions\n    ask_d2c_retention\n    ask_c2d_attempts\n    ask_c2d_ttl\n    ask_c2d_feedback_lock\n    ask_c2d_feedback_ttl\n    ask_c2d_feedback_attempts\n}\n\ncreate_hub() {\n    header \"Create '$HUB_NAME' in '$LOCATION'\"\n\n    if [[ $NEW_RESOURCE_GROUP == \"true\" ]]; then\n        azure group create \"$RESOURCE_GROUP\" \"$LOCATION\" || error_and_exit \"Unable to create resource group.\"\n    fi\n\n    azure iothub create \"$RESOURCE_GROUP\" \"$HUB_NAME\" \"$LOCATION\" \"$SKU\" \"$UNITS\" \\\n        --enable-dm \\\n        --d2c-partitions \"$D2C_PARTITIONS\" \\\n        --d2c-retention-time-in-days \"$D2C_TTL\" \\\n        --c2d-max-delivery-count \"$C2D_ATTEMPTS\" \\\n        --c2d-ttl \"$C2D_TTL\" \\\n        --feedback-lock-duration \"$C2D_FEEDBACK_LOCK\" \\\n        --feedback-ttl \"$C2D_FEEDBACK_TTL\" \\\n        --feedback-max-delivery-count \"$C2D_FEEDBACK_ATTEMPTS\" \\\n        || error_and_exit \"Unable to create IoT Hub\"\n}\n\nconfirm() {\n    header \"Summary\"\n\n    echo \"Azure IoT Hub name:             ${HUB_NAME}\"\n    echo \"Resource group name:            ${RESOURCE_GROUP} (new: ${NEW_RESOURCE_GROUP})\"\n    echo \"Azure region:                   ${LOCATION}\"\n    echo \"Pricing and Scaling SKU         ${SKU}\"\n    echo \"Capacity units:                 ${UNITS}\"\n    echo \"D2C events partitions:          ${D2C_PARTITIONS}\"\n    echo \"D2C events TTL:                 ${D2C_TTL} days\"\n    echo \"C2D messages TTL:               ${C2D_TTL}\"\n    echo \"C2D message delivery attempts:  ${C2D_ATTEMPTS}\"\n    echo \"C2D feedback TTL:               ${C2D_FEEDBACK_TTL}\"\n    echo \"C2D feedback delivery attempts: ${C2D_FEEDBACK_ATTEMPTS}\"\n    echo \"C2D feedback lock TTL:          ${C2D_FEEDBACK_LOCK}\"\n    echo\n\n    echo \"Proceed?\"\n    PS3=\">> \"\n    select SKU in Yes No; do\n        case $SKU in\n            No ) user_exit;;\n            Yes ) break;;\n        esac\n    done\n}\n\nmain() {\n    check_dependencies\n    login\n\n    ask_hub_name\n    select_subscription\n    select_resource_group\n    select_location\n    select_sku_and_units\n    advanced\n    confirm\n    create_hub\n    show_hub_details \"$RESOURCE_GROUP\" \"$HUB_NAME\"\n\n    announce \"Tip: to show the hub details, run: ./show-hub.sh $RESOURCE_GROUP $HUB_NAME\"\n}\n\nmain\n", "num_lines": 248}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nmain() {\n    check_dependencies\n    login\n\n    header \"Azure IoT Hubs in the current subscription\"\n    az iot hub list | jq '.[] | {name: .name, resourcegroup: .resourcegroup, location: .location, subscription: .subscriptionid}' | jq .\n}\n\nmain\n", "num_lines": 16}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nmain() {\n    check_dependencies\n    login\n\n    header \"Azure subscriptions\"\n    azure account list\n    #az account list | jq '.[] | {name: .name, id: .id, current: .isDefault}' | jq .\n}\n\nmain\n", "num_lines": 17}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nSUBSCRIPTION_ID=\"$1\"\n\ncheck_input() {\n    if [[ -z \"$SUBSCRIPTION_ID\" ]]; then\n        announce \"Usage: ./select-subscription.sh SUBSCRIPTION_ID\"\n        echo \"Use './list-subscriptions.sh' to see the list of subscriptions.\"\n    fi\n}\n\nmain() {\n    check_input\n    check_dependencies\n    login\n\n    if [[ ! -z \"$SUBSCRIPTION_ID\" ]]; then\n        header \"Changing current subscription\"\n        #az account set --subscription \"$SUBSCRIPTION_ID\"\n        azure account set \"$SUBSCRIPTION_ID\"\n    else\n        select_subscription\n    fi\n}\n\nmain\n", "num_lines": 31}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nRESOURCE_GROUP=\"$1\"\nHUB_NAME=\"$2\"\n\ncheck_input() {\n    if [[ -z \"$RESOURCE_GROUP\" || -z \"$HUB_NAME\" ]]; then\n        announce \"Usage: ./show-hub.sh RESOURCE_GROUP HUB_NAME\"\n        echo \"Use './list-hubs.sh' to see the list of hubs.\"\n        exit -1\n    fi\n}\n\nmain() {\n    check_input\n    check_dependencies\n    login\n    show_hub_details \"$RESOURCE_GROUP\" \"$HUB_NAME\"\n}\n\nmain\n", "num_lines": 26}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"ASA Manager Tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    ./scripts/telemetry.sh start\n    ./scripts/devicesimulation.sh start\n    ./scripts/config.sh start\n    ./scripts/iothubmanager.sh start\n    ./scripts/asamanager.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n    ./scripts/telemetry.sh stop\n    ./scripts/devicesimulation.sh stop\n    ./scripts/config.sh stop\n    ./scripts/iothubmanager.sh stop\n    ./scripts/asamanager.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n\n    docker logs \"asa-manager\"\n}\n\n#Script options  \nrepo=\"\"\ntag=\"testing\"\ndockeraccount=\"azureiotpcs\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export REPO=dotnet\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *) shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\nset_up\nrun\ntear_down\n\nset +e\n", "num_lines": 97}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"PCS Config Tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    ./scripts/telemetry.sh start\n    ./scripts/devicesimulation.sh start\n    ./scripts/config.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n    ./scripts/telemetry.sh stop\n    ./scripts/devicesimulation.sh stop\n    ./scripts/config.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \nrepo=\"\"\ntag=\"testing\"\ndockeraccount=\"azureiotpcs\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -re|--repo) repo=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run tests based on repo\nif [ \"$repo\" == \"both\" ] || [ \"$repo\" == \"\" ]; then\n    export REPO=dotnet\n    run\n    export REPO=java\n    run\nelif [[ \"$repo\" == \"dotnet\" ]]; then\n    export REPO=dotnet\n    run\nelif [[ \"$repo\" == \"java\" ]]; then\n    export REPO=java\n    run\nelse \n    error \"No build type specified, pass either 'dotnet' or 'java'.\"\n    echo \"eg:- sh containers.sh -re java\"\n    exit 1\nfi\n\n#### Tear down test\ntear_down\n\nset +e\n", "num_lines": 112}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"IOTHub Manager Tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    ./scripts/iothubmanager.sh start\n    ./scripts/devicesimulation.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n    ./scripts/iothubmanager.sh stop\n    ./scripts/devicesimulation.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \nrepo=\"\"\ntag=\"testing\"\ndockeraccount=\"azureiotpcs\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -re|--repo) repo=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run tests based on repo\nif [ \"$repo\" == \"both\" ] || [ \"$repo\" == \"\" ]; then\n    export REPO=dotnet\n    run\n    export REPO=java\n    run\nelif [[ \"$repo\" == \"dotnet\" ]]; then\n    export REPO=dotnet\n    run\nelif [[ \"$repo\" == \"java\" ]]; then\n    export REPO=java\n    run\nelse \n    error \"No build type specified, pass either 'dotnet' or 'java'.\"\n    echo \"eg:- sh containers.sh -re java\"\n    exit 1\nfi\n\n#### Tear down test\ntear_down\n\nset +e\n", "num_lines": 110}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/asa-manager-dotnet:$DOCKER_TAG\"\nDOCKER_PORT=9024\nDOCKER_NAME=\"asa-manager\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    variables_not_found=0\n    if [[ ! -n \"${PCS_ASA_DATA_AZUREBLOB_ACCOUNT}\" ]]; then\n        error \"PCS_ASA_DATA_AZUREBLOB_ACCOUNT is not set\"\n        variables_not_found=1\n    fi\n    if [[ ! -n \"${PCS_ASA_DATA_AZUREBLOB_KEY}\" ]]; then\n        error \"PCS_ASA_DATA_AZUREBLOB_KEY is not set\"\n        variables_not_found=1\n    fi\n    if [[ ! -n \"${PCS_ASA_DATA_AZUREBLOB_ENDPOINT_SUFFIX}\" ]]; then\n        error \"PCS_ASA_DATA_AZUREBLOB_ENDPOINT_SUFFIX is not set\"\n        variables_not_found=1\n    fi\n    if [[ ! -n \"${PCS_EVENTHUB_CONNSTRING}\" ]]; then\n        error \"PCS_EVENTHUB_CONNSTRING is not set\"\n        variables_not_found=1\n    fi\n    if [[ ! -n \"${PCS_EVENTHUB_NAME}\" ]]; then\n        error \"PCS_EVENTHUB_NAME is not set\"\n        variables_not_found=1\n\tfi\n\n    if [[ ! -n \"${PCS_TELEMETRY_DOCUMENTDB_CONNSTRING}\" ]]; then\n        error \"PCS_TELEMETRY_DOCUMENTDB_CONNSTRING is not set\"\n        variables_not_found=1\n    fi\n\n    if [ \"$variables_not_found\" == 1 ]; then\n        error \"Environment variable(s) not found, exiting\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1\n", "num_lines": 111}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/pcs-config-$REPO:$DOCKER_TAG\"\nDOCKER_PORT=9005\nDOCKER_NAME=\"pcs-config\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_IOTHUB_CONNSTRING}\" ]]; then\n        error \"PCS_IOTHUB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 83}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart() {\n    ./scripts/storageadapter.sh start\n    ./scripts/devicesimulation.sh start\n    ./scripts/telemetry.sh start\n    ./scripts/config.sh start\n    ./scripts/iothubmanager.sh start\n    ./scripts/asamanager.sh start\n}\n\nstop() {\n    ./scripts/storageadapter.sh stop\n    ./scripts/devicesimulation.sh stop\n    ./scripts/telemetry.sh stop\n    ./scripts/config.sh stop\n    ./scripts/iothubmanager.sh stop\n    ./scripts/asamanager.sh stop\n}\n\n#Script Args\nrepo=\"\"\ntag=\"testing\"\nact=\"start\"\ndockeraccount=\"azureiotpcs\"\n\nset_up_env() {\n    if [[ \"$repo\" == \"dotnet\" ]]; then\n        export REPO=\"dotnet\"\n    elif [[ \"$repo\" == \"java\" ]]; then\n        export REPO=\"java\"\n    else \n        error \"No microservice type specified, pass either 'dotnet' or 'java'.\"\n        echo \"eg:- sh containers.sh -re java\"\n        exit 1\n    fi\n\texport DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\t\n    case $opt in\n        -dt|--dockertag) tag=$1; shift;;\n        -re|--repo) repo=$1; shift;;\n        -act|--action) act=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *) shift;\n    esac\ndone\n\nset_up_env\n\nif [[ \"$act\" == \"start\" ]]; then\n    start\n    exit 0\nfi\n\nif [[ \"$act\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\ntear_down\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1\n", "num_lines": 82}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nexport DOCKER_TAG=DS-1.0.3\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/device-simulation-dotnet:$DOCKER_TAG\"\nDOCKER_PORT=9003\nDOCKER_NAME=\"device-simulation\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_IOTHUB_CONNSTRING}\" ]]; then\n        error \"PCS_IOTHUB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 81}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/iothub-manager-$REPO:$DOCKER_TAG\"\nDOCKER_PORT=9002\nDOCKER_NAME=\"iothub-manager\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_IOTHUB_CONNSTRING}\" ]]; then\n        error \"PCS_IOTHUB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 83}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/pcs-storage-adapter-$REPO:$DOCKER_TAG\"\nDOCKER_PORT=9022\nDOCKER_NAME=\"storage-adapter\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\" ]]; then\n        error \"PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1\n", "num_lines": 84}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/telemetry-agent-$REPO:$DOCKER_TAG\"\nDOCKER_PORT=9023\nDOCKER_NAME=\"telemetry-agent\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_TELEMETRY_DOCUMENTDB_CONNSTRING}\" ]]; then\n        error \"PCS_TELEMETRY_DOCUMENTDB_CONNSTRING is not set\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        docker logs $DOCKER_NAME\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 84}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nif [[ \"$DOCKER_TAG\" == \"\" ]]; then\n    export DOCKER_TAG=testing\nfi\n\nDOCKER_IMAGE=\"$DOCKER_ACCOUNT/telemetry-$REPO:$DOCKER_TAG\"\nDOCKER_PORT=9004\nDOCKER_NAME=\"telemetry\"\nDOCKER_NETWOK=\"integrationtests\"\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\ncd $APP_HOME\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\ncheck_env_variables()\n{\n    if [[ ! -n \"${PCS_TELEMETRY_DOCUMENTDB_CONNSTRING}\" ]]; then\n        error \"PCS_TELEMETRY_DOCUMENTDB_CONNSTRING is not set\"\n        exit -1\n    fi\n    if [[ -z \"$PCS_AUTH_ISSUER\" ]]; then\n    echo \"Error: the PCS_AUTH_ISSUER environment variable is not defined.\"\n    exit -1\n    fi\n\n    if [[ -z \"$PCS_AUTH_AUDIENCE\" ]]; then\n        echo \"Error: the PCS_AUTH_AUDIENCE environment variable is not defined.\"\n        exit -1\n    fi\n\n    if [[ -z \"$PCS_TELEMETRY_STORAGE_TYPE\" ]]; then\n        echo \"Error: the PCS_TELEMETRY_STORAGE_TYPE environment variable is not defined.\"\n        exit -1\n    fi\n\n    # The settings below are for Time Series Insights. If your deployment does not use\n    # Time Series Insights they are safe to remove.\n\n    if [[ -z \"$PCS_TSI_FQDN\" ]]; then\n        echo \"Error: the PCS_TSI_FQDN environment variable is not defined.\"\n        exit -1\n    fi\n\n    # Settings for actions\n    if [[ -z \"$PCS_ACTION_EVENTHUB_NAME\" ]]; then\n        echo \"Error: the PCS_ACTION_EVENTHUB_NAME environment variable is not defined.\"\n        exit -1\n    fi\n\n    if [[ -z \"$PCS_ACTION_EVENTHUB_CONNSTRING\" ]]; then\n        echo \"Error: the PCS_ACTION_EVENTHUB_CONNSTRING environment variable is not defined.\"\n        exit -1\n    fi\n\n    if [[ -z \"$PCS_LOGICAPP_ENDPOINT_URL\" ]]; then\n        echo \"Error: the PCS_LOGICAPP_ENDPOINT_URL environment variable is not defined.\"\n        exit -1\n    fi\n\n    if [[ -z \"$PCS_AZUREBLOB_CONNSTRING\" ]]; then\n        echo \"Error: the PCS_AZUREBLOB_CONNSTRING environment variable is not defined.\"\n        exit -1\n    fi\n\n    if [[ -z \"$PCS_SOLUTION_WEBSITE_URL\" ]]; then\n        echo \"Error: the PCS_SOLUTION_WEBSITE_URL environment variable is not defined.\"\n        exit -1\n    fi\n\n    header3 \"Connection strings set in environment variables\"\n}\n\nexit_if_running() {\n    ISUP=$(curl -ks http://127.0.0.1:$DOCKER_PORT/v1/status | grep -i \"{\" | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" != \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' is already running\"\n        exit 0\n    fi\n}\n\nfail_if_not_running() {\n    sleep 1\n    ISUP=$(docker ps | grep $DOCKER_NAME | wc -l | tr -d '[:space:]')\n    if [[ \"$ISUP\" == \"0\" ]]; then\n        error \"'$DOCKER_IMAGE' failed to start or crashed\"\n        docker logs $DOCKER_NAME\n        exit -1\n    fi\n}\n\ncreate_network() {\n    set +e\n    docker network create $DOCKER_NETWOK 2> /dev/null\n    set -e\n}\n\nstart() {\n    docker pull $DOCKER_IMAGE\n    header3 \"Starting '$DOCKER_IMAGE'\"\n    docker run --detach --network=$DOCKER_NETWOK -p 127.0.0.1:$DOCKER_PORT:$DOCKER_PORT \\\n        --env-file $APP_HOME/scripts/env.list --rm --name $DOCKER_NAME $DOCKER_IMAGE\n    sleep 1\n    fail_if_not_running\n}\n\nstop() {\n    set +e\n    header3 \"Stopping '$DOCKER_IMAGE'\"\n    docker rm -f $DOCKER_NAME\n    set -e\n}\n\nif [[ \"$1\" == \"start\" ]]; then\n    exit_if_running\n    check_env_variables\n    create_network\n    start\n    exit 0\nfi\n\nif [[ \"$1\" == \"stop\" ]]; then\n    stop\n    exit 0\nfi\n\nerror \"No command specified, pass either 'start' or 'stop'.\"\nexit 1", "num_lines": 132}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Sometimes when creating bash scripts in Windows, bash scripts will not have\n# the +x flag carried over to Linux/MacOS. This script should help setting the\n# permission flags right.\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\nchmod ugo+x ./scripts/build\nchmod ugo+x ./scripts/git/setup\nchmod ugo+x ./scripts/git/*.sh\nchmod ugo+x ./scripts/containers.sh \nchmod ugo+x ./scripts/env-vars-setup \nchmod ugo+x ./scripts/asamanager.sh\nchmod ugo+x ./scripts/devicesimulation.sh\nchmod ugo+x ./scripts/iothubmanager.sh\nchmod ugo+x ./scripts/config.sh\nchmod ugo+x ./scripts/storageadapter.sh\nchmod ugo+x ./scripts/telemetry.sh\nchmod ugo+x ./scripts/telemetry-agent.sh\nchmod ugo+x ./StorageAdapter/run.sh\nchmod ugo+x ./IoTHubManager/run.sh\nchmod ugo+x ./Config/run.sh\nchmod ugo+x ./ASAManager/run.sh\nchmod ugo+x ./Telemetry/run.sh\n\ngit update-index --chmod=+x ./scripts/build\ngit update-index --chmod=+x ./scripts/git/setup\ngit update-index --chmod=+x ./scripts/git/*.sh\ngit update-index --chmod=+x ./scripts/containers.sh \ngit update-index --chmod=+x ./scripts/env-vars-setup \ngit update-index --chmod=+x ./scripts/asamanager.sh\ngit update-index --chmod=+x ./scripts/devicesimulation.sh\ngit update-index --chmod=+x ./scripts/iothubmanager.sh\ngit update-index --chmod=+x ./scripts/config.sh\ngit update-index --chmod=+x ./scripts/storageadapter.sh\ngit update-index --chmod=+x ./scripts/telemetry.sh\ngit update-index --chmod=+x ./scripts/telemetry-agent.sh\ngit update-index --chmod=+x ./StorageAdapter/run.sh\ngit update-index --chmod=+x ./IoTHubManager/run.sh\ngit update-index --chmod=+x ./Config/run.sh\ngit update-index --chmod=+x ./ASAManager/run.sh\ngit update-index --chmod=+x ./Telemetry/run.sh\n\nset +e\n", "num_lines": 50}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\ncd $APP_HOME\n\n./scripts/git/pre-commit.sh\n\nset +e\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\nSANDBOX_MODE=\"$1\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    if [[ \"$SANDBOX_MODE\" == \"--with-sandbox\" ]]; then\n        ./build --in-sandbox\n    else\n        ./build\n    fi\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    else\n        header \"All tests passed\"\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n\nset +e\n", "num_lines": 124}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"Storage Adapter tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \nrepo=\"\"\ntag=\"testing\"\ndockeraccount=\"azureiotpcs\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -re|--repo) repo=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run tests based on repo\nif [ \"$repo\" == \"both\" ] || [ \"$repo\" == \"\" ]; then\n    export REPO=dotnet\n    run\n    export REPO=java\n    run\nelif [[ \"$repo\" == \"dotnet\" ]]; then\n    export REPO=dotnet\n    run\nelif [[ \"$repo\" == \"java\" ]]; then\n    export REPO=java\n    run\nelse \n    error \"No build type specified, pass either 'dotnet' or 'java'.\"\n    echo \"eg:- sh containers.sh -re java\"\n    exit 1\nfi\n\n#### Tear down test\ntear_down\n\nset +e\n", "num_lines": 106}
{"repo_name": "azure-iot-pcs-remote-monitoring-dotnet-tests", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nTEST_SUITE=\"Device Telemetry Tests\"\n\nTEST_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\nsource \"$APP_HOME/scripts/.functions.sh\"\n\nstart_containers() {\n    header2 \"$TEST_SUITE - Starting services...\"\n\n    cd $APP_HOME\n    ./scripts/storageadapter.sh start\n    ./scripts/telemetry.sh start\n    ./scripts/devicesimulation.sh start\n    ./scripts/config.sh start\n    ./scripts/asamanager.sh start\n    docker ps -a\n}\n\nstop_containers() {\n    header2 \"$TEST_SUITE - Stopping services...\"\n\n    cd $APP_HOME\n    docker ps -a\n    ./scripts/storageadapter.sh stop\n    ./scripts/telemetry.sh stop\n    ./scripts/devicesimulation.sh stop\n    ./scripts/config.sh stop\n    ./scripts/asamanager.sh stop\n}\n\nrun_tests() {\n    header2 \"$TEST_SUITE - Downloading dependencies...\"\n\n    cd $APP_HOME\n    dotnet restore\n\n    header2 \"$TEST_SUITE - Compiling tests...\"\n    dotnet build --configuration Release\n\n    header2 \"$TEST_SUITE - Running tests...\"\n    cd $TEST_HOME\n    find . -name *.csproj | xargs dotnet test --configuration Release\n}\n\n#Script options  \nrepo=\"\"\ntag=\"testing\"\ndockeraccount=\"azureiotpcs\"\n\nset_up() {\n    export DOCKER_TAG=$tag\n    export DOCKER_ACCOUNT=$dockeraccount\n    check_dependency_docker\n    check_dependency_dotnet\n}\n\nrun() {\n    start_containers\n    run_tests\n    stop_containers\n}\n\ntear_down() {\n    unset DOCKER_TAG\n    unset DOCKER_ACCOUNT\n}\n\n#### Parse script arguments\nwhile [[ $# -gt 0 ]] ;\ndo\n    opt=$1;\n    shift;\n    case $opt in\n        -t|--tag) tag=$1; shift;;\n        -re|--repo) repo=$1; shift;;\n        -da|--docker-account) dockeraccount=$1; shift;; \n        *)  shift;;\n    esac\ndone\n\nheader \"Running $TEST_SUITE\"\n\n#### Set Up Tests\nset_up\n\n#### Run tests based on repo\nif [ \"$repo\" == \"both\" ] || [ \"$repo\" == \"\" ]; then\n    export REPO=dotnet\n    run\n    export REPO=java\n    run\nelif [[ \"$repo\" == \"dotnet\" ]]; then\n    export REPO=dotnet\n    run\nelif [[ \"$repo\" == \"java\" ]]; then\n    export REPO=java\n    run\nelse \n    error \"No build type specified, pass either 'dotnet' or 'java'.\"\n    echo \"eg:- sh containers.sh -re java\"\n    exit 1\nfi\n\n#### Tear down test\ntear_down\n\nset +e\n", "num_lines": 114}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && pwd )/\"\n\ncd $APP_HOME\n\ngit checkout master\ngit pull\n\nCOL=\"\\e[93m\\e[1m\"\nNOCOL=\"\\e[0m\"\n\necho -e \"${COL}### CLI${NOCOL}\"\ncd $APP_HOME && git submodule update --init cli               && cd cli               && git checkout master && git pull\necho -e \"${COL}### Config${NOCOL}\"\ncd $APP_HOME && git submodule update --init config            && cd config            && git checkout master && git pull\necho -e \"${COL}### Device Simulation${NOCOL}\"\ncd $APP_HOME && git submodule update --init device-simulation && cd device-simulation && git checkout master && git pull\necho -e \"${COL}### IoT Hub Manager${NOCOL}\"\ncd $APP_HOME && git submodule update --init iothub-manager    && cd iothub-manager    && git checkout master && git pull\necho -e \"${COL}### Storage Adapter${NOCOL}\"\ncd $APP_HOME && git submodule update --init storage-adapter   && cd storage-adapter   && git checkout master && git pull\necho -e \"${COL}### Telemetry${NOCOL}\"\ncd $APP_HOME && git submodule update --init telemetry         && cd telemetry         && git checkout master && git pull\necho -e \"${COL}### ASA Manager${NOCOL}\"\ncd $APP_HOME && git submodule update --init asa-manager       && cd asa-manager       && git checkout master && git pull\necho -e \"${COL}### Web UI${NOCOL}\"\ncd $APP_HOME && git submodule update --init webui             && cd webui             && git checkout master && git pull\n\ncd $APP_HOME\n", "num_lines": 33}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\n# Path relative to .git/hooks/\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/pre-commit.sh\"\n", "num_lines": 8}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\nsource \"$APP_HOME/scripts/git/.functions.sh\"\n\ncd $APP_HOME\necho \"Current folder: `pwd`\"\n\nif git rev-parse --verify HEAD >/dev/null 2>&1 ; then\n    against=HEAD\nelse\n    # Initial commit: diff against an empty tree object\n    against=4b825dc642cb6eb9a060e54bf8d69288fbee4904\nfi\n\ncheck_filenames() {\n    header \"Checking filenames...\"\n\n    # Redirect output to stderr.\n    exec 1>&2\n\n    # Cross platform projects tend to avoid non-ASCII filenames; prevent\n    # them from being added to the repository. We exploit the fact that the\n    # printable range starts at the space character and ends with tilde.\n    # Note that the use of brackets around a tr range is ok here, (it's\n    # even required, for portability to Solaris 10's /usr/bin/tr), since\n    # the square bracket bytes happen to fall in the designated range.\n    set +e\n    if test $(git diff --cached --name-only --diff-filter=A -z $against | LC_ALL=C tr -d '[ -~]\\0' | wc -c) != 0 ; then\n        error \"Attempt to add a non-ASCII file name. This can cause problems on other platforms.\"\n        exit 1\n    fi\n    set -e\n}\n\ncheck_whitespaces() {\n    header \"Checking white spaces and line separators...\"\n    git diff-index --check --cached $against --\n}\n\ncheck_do_not_commit() {\n    PATTERN1=\"DONOT\"\n    PATTERN1=\"${PATTERN1}COMMIT\"\n    PATTERN2=\"DO NOT\"\n    PATTERN2=\"${PATTERN2} COMMIT\"\n    PATTERN3=\"DONT\"\n    PATTERN3=\"${PATTERN3}COMMIT\"\n    PATTERN4=\"DONT\"\n    PATTERN4=\"${PATTERN4} COMMIT\"\n    PATTERN5=\"DON'T\"\n    PATTERN5=\"${PATTERN5} COMMIT\"\n\n    header \"Checking diff for comments containing '${PATTERN1}'...\"\n\n    set +e\n\n    PATT=\"^\\+.*${PATTERN1}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN1}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN2}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN2}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN3}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN3}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN4}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN4}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    PATT=\"^\\+.*${PATTERN5}.*$\"\n    diffstr=`git diff --cached $against | grep -ie \"$PATT\"`\n    if [[ -n \"$diffstr\" ]]; then\n        error \"You have left '${PATTERN5}' in your changes, you can't commit until it has been removed.\"\n        exit 1\n    fi\n\n    set -e\n}\n\nverify_build() {\n    header \"Verifying build...\"\n\n    cd $APP_HOME/scripts\n    ./build\n\n    if [ $? -ne 0 ]; then\n        error \"Some tests failed.\"\n        exit 1\n    fi\n}\n\ncheck_filenames\ncheck_whitespaces\ncheck_do_not_commit\nverify_build\n", "num_lines": 112}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright (c) Microsoft. All rights reserved.\n# Note: Windows Bash doesn't support shebang extra params\nset -e\n\nwhile [ \"$#\" -gt 0 ]; do\n    case \"$1\" in\n        --version)                      VERSION=\"$2\" ;;\n        --git_access_token)             GIT_ACCESS_TOKEN=\"$2\" ;;\n        --docker_user)                  DOCKER_USER=\"$2\" ;;\n        --docker_pwd)                   DOCKER_PWD=\"$2\" ;;\n        --from_docker_namespace)        FROM_DOCKER_NAMESPACE=\"$2\" ;;\n        --to_docker_namespace)          TO_DOCKER_NAMESPACE=\"$2\" ;;\n        --docker_tag)                   DOCKER_TAG=\"$2\" ;;\n        --description)                  DESCRIPTION=\"$2\" ;;\n        --pre_release)                  PRE_RELEASE=\"$2\" ;;\n        --local)                        LOCAL=\"$2\" ;;\n    esac\n    shift\ndone\n\n# Set default values for optional parameters\nFROM_DOCKER_NAMESPACE=${FROM_DOCKER_NAMESPACE:-azureiotpcs}\nTO_DOCKER_NAMESPACE=${TO_DOCKER_NAMESPACE:-azureiotpcs}\nDOCKER_TAG=${DOCKER_TAG:-testing}\nDESCRIPTION=${DESCRIPTION:-''}\nPRE_RELEASE=${PRE_RELEASE:-false}\nLOCAL=${LOCAL:-''}\n\nAPP_HOME=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && cd .. && cd .. && pwd )/\"\n\nNC=\"\\033[0m\" # no color\nCYAN=\"\\033[1;36m\" # light cyan\nYELLOW=\"\\033[1;33m\" # yellow\nRED=\"\\033[1;31m\" # light red\n\nfailed() {\n    SUB_MODULE=$1\n    echo -e \"${RED}Cannot find directory $SUB_MODULE${NC}\"\n    exit 1\n}\n\nusage() {\n    echo -e \"${RED}ERROR: $1 is a required option${NC}\"\n    echo \"Usage: ./release\"\n    echo -e 'Options:\n        --version               Version of this release (required)\n        --git_access_token      Git access token to push tag (required)\n        --docker_user           Username to login docker hub (required)\n        --docker_pwd            Password to login docker hub (required)\n        --from_docker_namespace Source namespace of docker image (default:azureiotpcs)\n        --to_docker_namespace   Target namespace of docker image (default:azureiotpcs)\n        --docker_tag            Source tag of docker image (default:testing)\n        --description           Description of this release (default:empty)\n        --pre_release           Publish as non-production release on github (default:false)\n        --local                 Clean up the local repo at first (default:empty)\n        '\n    exit 1\n}\n\ncheck_input() {\n    if [ ! -n \"$VERSION\" ]; then\n        usage \"version\"\n    fi\n    if [ ! -n \"$GIT_ACCESS_TOKEN\" ]; then\n        usage \"git_access_token\"\n    fi\n    if [ ! -n \"$DOCKER_USER\" ]; then\n        usage \"docker_user\"\n    fi\n    if [ ! -n \"$DOCKER_PWD\" ]; then\n        usage \"docker_pwd\"\n    fi\n    echo $DOCKER_PWD | docker login -u $DOCKER_USER --password-stdin\n}\n\ntag_release_repo() {\n    SUB_MODULE=$1\n    REPO_NAME=$2\n    DESCRIPTION=$3\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Tagging the $REPO_NAME repo     ====================================${NC}\"\n    echo\n    echo -e \"Current working directory ${CYAN}$APP_HOME$SUB_MODULE${NC}\"\n    echo\n    cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE\n\n    if [ -n \"$LOCAL\" ]; then\n        echo \"Cleaning the repo\"\n        git reset --hard origin/master\n        git clean -xdf\n    fi\n    git checkout master\n    git pull --all --prune\n    git fetch --tags\n\n    git tag --force $VERSION\n    git push https://$GIT_ACCESS_TOKEN@github.com/Azure/$REPO_NAME.git $VERSION\n\n    echo\n    echo -e \"${CYAN}====================================     End: Tagging $REPO_NAME repo     ====================================${NC}\"\n    echo\n\n    echo\n    echo -e \"${CYAN}====================================     Start: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n\n    # For documentation https://help.github.com/articles/creating-releases/\n    DATA=\"{\n        \\\"tag_name\\\": \\\"$VERSION\\\",\n        \\\"target_commitish\\\": \\\"master\\\",\n        \\\"name\\\": \\\"$VERSION\\\",\n        \\\"body\\\": \\\"$DESCRIPTION\\\",\n        \\\"draft\\\": false,\n        \\\"prerelease\\\": $PRE_RELEASE\n    }\"\n\n    curl -X POST --data \"$DATA\" https://api.github.com/repos/Azure/$REPO_NAME/releases?access_token=$GIT_ACCESS_TOKEN\n    echo\n    echo -e \"${CYAN}====================================     End: Release for $REPO_NAME     ====================================${NC}\"\n    echo\n}\n\npublish_docker_containers()\n{\n    DOCKER_CONTAINER_NAME=$1\n    SUB_MODULE=$2\n\n    if [ \"$SUB_MODULE\" == \"reverse-proxy\" ]; then\n        cd $APP_HOME$SUB_MODULE || failed $SUB_MODULE\n        if [ -n \"$LOCAL\" ]; then\n            echo \"Cleaning the repo\"\n            git reset --hard origin/master\n            git clean -xdf\n        fi\n        git checkout master\n        git pull --all --prune\n\n        echo\n        echo -e \"${CYAN}====================================     Start: Building $DOCKER_CONTAINER_NAME     ====================================${NC}\"\n        echo\n\n        BUILD_PATH=\"build\"\n        # Building docker containers\n        /bin/bash $APP_HOME$SUB_MODULE/$BUILD_PATH\n        \n        echo\n        echo -e \"${CYAN}====================================     End: Building $DOCKER_CONTAINER_NAME     ====================================${NC}\"\n        echo\n    else\n        # Pull containers\n        echo -e \"${CYAN}Pulling $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG${NC}\"\n        echo\n        docker pull $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG\n    fi\n    \n    # Tag containers\n    echo -e \"${CYAN}Tagging $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG ==> $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}\"\n    echo\n    docker tag $FROM_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$DOCKER_TAG  $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION\n\n    # Push containers\n    echo -e \"${CYAN}Pusing container $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION${NC}\"\n    docker push $TO_DOCKER_NAMESPACE/$DOCKER_CONTAINER_NAME:$VERSION\n}\n\ncheck_input\n\n# Publish Java Microservices docker containers\npublish_docker_containers pcs-config-java\npublish_docker_containers iothub-manager-java\npublish_docker_containers pcs-storage-adapter-java\npublish_docker_containers telemetry-java\n\n# Release and tag top-level java repository with latest version\ntag_release_repo          services                        remote-monitoring-services-java\ntag_release_repo          \"\"                              azure-iot-pcs-remote-monitoring-java $DESCRIPTION\n\n# Done through dotnet release script\n# tag_release_repo          webui                           pcs-remote-monitoring-webui\n# PCS CLI\n# tag_release_repo          cli                             pcs-cli\n# Top Level repo\n# publish_docker_containers pcs-remote-monitoring-webui\n# publish_docker_containers remote-monitoring-nginx       reverse-proxy\n\n# Only dotnet exists\n# publish_docker_containers pcs-diagnostics-dotnet\n# publish_docker_containers pcs-auth-dotnet\n# publish_docker_containers device-simulation-dotnet\n# publish_docker_containers asa-manager-dotnet\n\nset +e", "num_lines": 194}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nif [[ \"$1\" == \"-a\" || \"$1\" == \"--all-options\" ]]; then\n    ADVANCED=true\nelse\n    ADVANCED=false\nfi\n\nSUBSCRIPTION=\"\"\nHUB_NAME=\"\"\nRESOURCE_GROUP=\"\"\nNEW_RESOURCE_GROUP=\"false\"\nLOCATION=\"\"\nSKU=\"\"\nMAXUNITS=\"\"\nUNITS=\"\"\nD2C_PARTITIONS=\"\"\nD2C_TTL=\"\"\nC2D_ATTEMPTS=\"\"\nC2D_TTL=\"\"\nC2D_FEEDBACK_LOCK=\"\"\nC2D_FEEDBACK_TTL=\"\"\nC2D_FEEDBACK_ATTEMPTS=\"\"\n\nask_hub_name() {\n    header \"New Azure IoT Hub\"\n    HUB_NAME=\"\"\n\n    while [[ -z \"$HUB_NAME\" ]]; do\n        echo -n \"Enter IoT Hub name: \"\n        read HUB_NAME\n    done\n}\n\nselect_resource_group() {\n    header \"Resource group\"\n\n    echo \"Existing resource groups\"\n\n    azure group list\n\n    echo\n    announce \"You can re-use an existing group or enter a new name to create a new resource group.\"\n    echo\n    RESOURCE_GROUP=\"\"\n    while [[ -z \"$RESOURCE_GROUP\" ]]; do\n        echo -n \"Enter resource group name: \"\n        read RESOURCE_GROUP\n    done\n\n    NEW_RESOURCE_GROUP=\"false\"\n    TEST=$(azure group list | grep -i \"$RESOURCE_GROUP\")\n    if [[ -z \"$TEST\" ]]; then\n        NEW_RESOURCE_GROUP=\"true\"\n    fi\n}\n\nselect_location() {\n    header \"Azure region\"\n\n    # TODO: az account list-locations + filter for IoT Hub\n    echo -e \"Select the location where to create the hub:\"\n    PS3=\">> \"\n    select LOCATION in eastus westus westus2 westcentralus northeurope westeurope eastasia southeastasia japaneast japanwest australiaeast australiasoutheast; do\n        break;\n    done\n}\n\nselect_sku_and_units() {\n    header \"Pricing and Scale Tier\"\n\n    echo \"F1: 8k messages/unit/day (free)\"\n    echo \"S1: 400k messages/unit/day\"\n    echo \"S2: 6M messages/unit/day\"\n    echo \"S3: 300M messages/unit/day\"\n\n    echo -e \"\\nSelect pricing and scale:\"\n    PS3=\">> \"\n    select SKU in F1 S1 S2 S3; do\n        case $SKU in\n            F1 ) MAXUNITS=1; break;;\n            S1 ) MAXUNITS=200; break;;\n            S2 ) MAXUNITS=200; break;;\n            S3 ) MAXUNITS=10; break;;\n        esac\n    done\n\n    UNITS=\"1\"\n    if [[ \"$SKU\" != \"F1\" ]]; then\n        echo -n -e \"\\nHow many units? (1..${MAXUNITS}) [${UNITS}]: \"\n        read TEMP\n        if [[ ! -z \"$TEMP\" ]]; then UNITS=\"$TEMP\"; fi\n    fi\n}\n\nask_d2c_partitions() {\n    D2C_PARTITIONS=\"2\" # 2..128 (2 for F1)\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    if [[ \"$SKU\" != \"F1\" ]]; then\n        echo -n \"How many partitions? (1..128) [${D2C_PARTITIONS}]: \"\n        read TEMP\n        if [[ ! -z \"$TEMP\" ]]; then D2C_PARTITIONS=\"$TEMP\"; fi\n    fi\n}\n\nask_d2c_retention() {\n    D2C_TTL=\"1\" # 1..7 days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many days before device-to-cloud messages expire? (1..7) [${D2C_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then D2C_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_attempts() {\n    C2D_ATTEMPTS=\"10\" # 1..100 count\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many attempts to deliver a cloud-to-device message? (1..100) [${C2D_ATTEMPTS}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_ATTEMPTS=\"$TEMP\"; fi\n}\n\nask_c2d_ttl() {\n    # PnYnMnDTnHnMnS\n    C2D_TTL=\"PT1H\" # 1 min .. 2 days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device messages expire? (ISO8601: 1 min .. 2 days) [${C2D_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_lock() {\n    # PnYnMnDTnHnMnS\n    C2D_FEEDBACK_LOCK=\"PT1M\" # 5 secs .. 5 mins\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device feedback messages lock expire? (ISO8601: 5 secs .. 5 mins) [${C2D_FEEDBACK_LOCK}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_LOCK=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_ttl() {\n    # PnYnMnDTnHnMnS\n    C2D_FEEDBACK_TTL=\"PT1M\" # 1 min .. 2days\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How long before cloud-to-device feedback messages expire? (ISO8601: 1 min .. 2days) [${C2D_FEEDBACK_TTL}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_TTL=\"$TEMP\"; fi\n}\n\nask_c2d_feedback_attempts() {\n    C2D_FEEDBACK_ATTEMPTS=\"1\" # 1..100 count\n    if [[ \"$ADVANCED\" == \"false\" ]]; then return 0; fi\n\n    echo -n \"How many attempts to deliver a cloud-to-device feedback message? (1..100) [${C2D_FEEDBACK_ATTEMPTS}]: \"\n    read TEMP\n    if [[ ! -z \"$TEMP\" ]]; then C2D_FEEDBACK_ATTEMPTS=\"$TEMP\"; fi\n}\n\nadvanced() {\n    if [[ \"$ADVANCED\" == \"true\" ]]; then\n        header \"Other settings\";\n    else\n        announce \"Using default settings. Use '--all-options' to manually set all the hub options.\"\n    fi\n\n    ask_d2c_partitions\n    ask_d2c_retention\n    ask_c2d_attempts\n    ask_c2d_ttl\n    ask_c2d_feedback_lock\n    ask_c2d_feedback_ttl\n    ask_c2d_feedback_attempts\n}\n\ncreate_hub() {\n    header \"Create '$HUB_NAME' in '$LOCATION'\"\n\n    if [[ $NEW_RESOURCE_GROUP == \"true\" ]]; then\n        azure group create \"$RESOURCE_GROUP\" \"$LOCATION\" || error_and_exit \"Unable to create resource group.\"\n    fi\n\n    azure iothub create \"$RESOURCE_GROUP\" \"$HUB_NAME\" \"$LOCATION\" \"$SKU\" \"$UNITS\" \\\n        --enable-dm \\\n        --d2c-partitions \"$D2C_PARTITIONS\" \\\n        --d2c-retention-time-in-days \"$D2C_TTL\" \\\n        --c2d-max-delivery-count \"$C2D_ATTEMPTS\" \\\n        --c2d-ttl \"$C2D_TTL\" \\\n        --feedback-lock-duration \"$C2D_FEEDBACK_LOCK\" \\\n        --feedback-ttl \"$C2D_FEEDBACK_TTL\" \\\n        --feedback-max-delivery-count \"$C2D_FEEDBACK_ATTEMPTS\" \\\n        || error_and_exit \"Unable to create IoT Hub\"\n}\n\nconfirm() {\n    header \"Summary\"\n\n    echo \"Azure IoT Hub name:             ${HUB_NAME}\"\n    echo \"Resource group name:            ${RESOURCE_GROUP} (new: ${NEW_RESOURCE_GROUP})\"\n    echo \"Azure region:                   ${LOCATION}\"\n    echo \"Pricing and Scaling SKU         ${SKU}\"\n    echo \"Capacity units:                 ${UNITS}\"\n    echo \"D2C events partitions:          ${D2C_PARTITIONS}\"\n    echo \"D2C events TTL:                 ${D2C_TTL} days\"\n    echo \"C2D messages TTL:               ${C2D_TTL}\"\n    echo \"C2D message delivery attempts:  ${C2D_ATTEMPTS}\"\n    echo \"C2D feedback TTL:               ${C2D_FEEDBACK_TTL}\"\n    echo \"C2D feedback delivery attempts: ${C2D_FEEDBACK_ATTEMPTS}\"\n    echo \"C2D feedback lock TTL:          ${C2D_FEEDBACK_LOCK}\"\n    echo\n\n    echo \"Proceed?\"\n    PS3=\">> \"\n    select SKU in Yes No; do\n        case $SKU in\n            No ) user_exit;;\n            Yes ) break;;\n        esac\n    done\n}\n\nmain() {\n    check_dependencies\n    login\n\n    ask_hub_name\n    select_subscription\n    select_resource_group\n    select_location\n    select_sku_and_units\n    advanced\n    confirm\n    create_hub\n    show_hub_details \"$RESOURCE_GROUP\" \"$HUB_NAME\"\n\n    announce \"Tip: to show the hub details, run: ./show-hub.sh $RESOURCE_GROUP $HUB_NAME\"\n}\n\nmain\n", "num_lines": 248}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nmain() {\n    check_dependencies\n    login\n\n    header \"Azure IoT Hubs in the current subscription\"\n    az iot hub list | jq '.[] | {name: .name, resourcegroup: .resourcegroup, location: .location, subscription: .subscriptionid}' | jq .\n}\n\nmain\n", "num_lines": 16}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nmain() {\n    check_dependencies\n    login\n\n    header \"Azure subscriptions\"\n    azure account list\n    #az account list | jq '.[] | {name: .name, id: .id, current: .isDefault}' | jq .\n}\n\nmain\n", "num_lines": 17}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nSUBSCRIPTION_ID=\"$1\"\n\ncheck_input() {\n    if [[ -z \"$SUBSCRIPTION_ID\" ]]; then\n        announce \"Usage: ./select-subscription.sh SUBSCRIPTION_ID\"\n        echo \"Use './list-subscriptions.sh' to see the list of subscriptions.\"\n    fi\n}\n\nmain() {\n    check_input\n    check_dependencies\n    login\n\n    if [[ ! -z \"$SUBSCRIPTION_ID\" ]]; then\n        header \"Changing current subscription\"\n        #az account set --subscription \"$SUBSCRIPTION_ID\"\n        azure account set \"$SUBSCRIPTION_ID\"\n    else\n        select_subscription\n    fi\n}\n\nmain\n", "num_lines": 31}
{"repo_name": "azure-iot-pcs-remote-monitoring-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )/\"\nsource \"$DIR/.functions.sh\"\n\nRESOURCE_GROUP=\"$1\"\nHUB_NAME=\"$2\"\n\ncheck_input() {\n    if [[ -z \"$RESOURCE_GROUP\" || -z \"$HUB_NAME\" ]]; then\n        announce \"Usage: ./show-hub.sh RESOURCE_GROUP HUB_NAME\"\n        echo \"Use './list-hubs.sh' to see the list of hubs.\"\n        exit -1\n    fi\n}\n\nmain() {\n    check_input\n    check_dependencies\n    login\n    show_hub_details \"$RESOURCE_GROUP\" \"$HUB_NAME\"\n}\n\nmain\n", "num_lines": 26}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\nENVVARS=\"${APP_PATH}/env-vars\"\nDOCKERCOMPOSE=\"${APP_PATH}/docker-compose.yml\"\nCERTS=\"${APP_PATH}/certs\"\nCERT=\"${CERTS}/tls.crt\"\nPKEY=\"${CERTS}/tls.key\"\n\nSCRIPTS_REPO=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/single-vm-scripts/\"\n\n# ========================================================================\n\nexport HOST_NAME=\"${1:-localhost}\"\nexport APP_RUNTIME=\"${3:-dotnet}\"\nexport PCS_IOTHUB_CONNSTRING=\"$8\"\nexport PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\"$9\"\nexport PCS_TELEMETRY_DOCUMENTDB_CONNSTRING=\"$9\"\nexport PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING=\"$9\"\nexport PCS_IOTHUBREACT_ACCESS_CONNSTRING=\"$8\"\nexport PCS_IOTHUBREACT_HUB_NAME=\"${10}\"\nexport PCS_IOTHUBREACT_HUB_ENDPOINT=\"${11}\"\nexport PCS_IOTHUBREACT_HUB_PARTITIONS=\"${12}\"\nexport PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT=\"${13}\"\nexport PCS_IOTHUBREACT_AZUREBLOB_KEY=\"${14}\"\nexport PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX=\"${15}\"\nexport PCS_CERTIFICATE=\"${16}\"\nexport PCS_CERTIFICATE_KEY=\"${17}\"\nexport PCS_BINGMAP_KEY=\"${18}\"\nexport PCS_AUTH_ISSUER=\"https://sts.windows.net/${5}/\"\nexport PCS_AUTH_AUDIENCE=\"$6\"\nexport PCS_WEBUI_AUTH_TYPE=\"aad\"\nexport PCS_WEBUI_AUTH_AAD_TENANT=\"$5\"\nexport PCS_WEBUI_AUTH_AAD_APPID=\"$6\"\nexport PCS_WEBUI_AUTH_AAD_INSTANCE=\"$7\"\nexport PCS_APPLICATION_SECRET=$(cat /dev/urandom | LC_CTYPE=C tr -dc 'a-zA-Z0-9-,./;:[]\\(\\)_=^!~' | fold -w 64 | head -n 1)\n\n# TODO: remove temporary fix when projects have moved to use PCS_APPLICATION_SECRET\nexport APPLICATION_SECRET=$PCS_APPLICATION_SECRET\n\n# ========================================================================\n\n# Configure Docker registry based on host name\n# ToDo: we may need to add similar parameter to AzureGermanCloud and AzureUSGovernment\nconfig_for_azure_china() {\n    set +e\n    local host_name=$1\n    if (echo $host_name | grep -c  \"\\.cn$\") ; then\n        # If the host name has .cn suffix, dockerhub in China will be used to avoid slow network traffic failure.\n        local config_file='/etc/docker/daemon.json'\n        echo \"{\\\"registry-mirrors\\\": [\\\"https://registry.docker-cn.com\\\"]}\" > ${config_file}\n        service docker restart\n        \n        # Rewrite the AAD issuer in Azure China environment\n        export PCS_AUTH_ISSUER=\"https://sts.chinacloudapi.cn/$2/\"\n    fi\n    set -e\n}\n\nconfig_for_azure_china $HOST_NAME $5\n\n# ========================================================================\n\nmkdir -p ${APP_PATH}\ncd ${APP_PATH}\n\n# ========================================================================\n\n# Docker compose file\nDC_SOURCE=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/docker-compose.${APP_RUNTIME}.yml\"\nwget $DC_SOURCE -O ${DOCKERCOMPOSE}\n\n# ========================================================================\n\n# HTTPS certificates\nmkdir -p ${CERTS}\ntouch ${CERT} && chmod 550 ${CERT}\ntouch ${PKEY} && chmod 550 ${PKEY}\n# Always have quotes around the certificate and key value to preserve the formatting\necho \"${PCS_CERTIFICATE}\"      > ${CERT}\necho \"${PCS_CERTIFICATE_KEY}\"  > ${PKEY}\n\n# ========================================================================\n\n# Download scripts\nwget $SCRIPTS_REPO/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh\nwget $SCRIPTS_REPO/simulate.sh -O /app/simulate.sh && chmod 750 /app/simulate.sh\nwget $SCRIPTS_REPO/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh\nwget $SCRIPTS_REPO/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh\nwget $SCRIPTS_REPO/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh\nwget $SCRIPTS_REPO/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh\n\n# Temporarily disabled - The update scenario requires some work\n# wget $SCRIPTS_REPO/update.sh   -O /app/update.sh   && chmod 750 /app/update.sh\n\n# ========================================================================\n\n# Web App configuration\ntouch ${WEBUICONFIG} && chmod 444 ${WEBUICONFIG}\ntouch ${WEBUICONFIG_SAFE} && chmod 444 ${WEBUICONFIG_SAFE}\ntouch ${WEBUICONFIG_UNSAFE} && chmod 444 ${WEBUICONFIG_UNSAFE}\n\necho \"var DeploymentConfig = {\"                       >> ${WEBUICONFIG_SAFE}\necho \"  authEnabled: true,\"                           >> ${WEBUICONFIG_SAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_SAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_SAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_SAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_SAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_SAFE}\necho \"  }\"                                            >> ${WEBUICONFIG_SAFE}\necho \"}\"                                              >> ${WEBUICONFIG_SAFE}\n\necho \"var DeploymentConfig = {\"                       >> ${WEBUICONFIG_UNSAFE}\necho \"  authEnabled: false,\"                          >> ${WEBUICONFIG_UNSAFE}\necho \"  authType: '${PCS_WEBUI_AUTH_TYPE}',\"          >> ${WEBUICONFIG_UNSAFE}\necho \"  aad : {\"                                      >> ${WEBUICONFIG_UNSAFE}\necho \"    tenant: '${PCS_WEBUI_AUTH_AAD_TENANT}',\"    >> ${WEBUICONFIG_UNSAFE}\necho \"    appId: '${PCS_WEBUI_AUTH_AAD_APPID}',\"      >> ${WEBUICONFIG_UNSAFE}\necho \"    instance: '${PCS_WEBUI_AUTH_AAD_INSTANCE}'\" >> ${WEBUICONFIG_UNSAFE}\necho \"  }\"                                            >> ${WEBUICONFIG_UNSAFE}\necho \"}\"                                              >> ${WEBUICONFIG_UNSAFE}\n\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\n# ========================================================================\n\n# Environment variables\ntouch ${ENVVARS} && chmod 440 ${ENVVARS}\n\necho \"export HOST_NAME=\\\"${HOST_NAME}\\\"\"                                                                 >> ${ENVVARS}\necho \"export APP_RUNTIME=\\\"${APP_RUNTIME}\\\"\"                                                             >> ${ENVVARS}\necho \"export PCS_AUTH_ISSUER=\\\"${PCS_AUTH_ISSUER}\\\"\"                                                     >> ${ENVVARS}\necho \"export PCS_AUTH_AUDIENCE=\\\"${PCS_AUTH_AUDIENCE}\\\"\"                                                 >> ${ENVVARS}\necho \"export PCS_AUTH_AAD_GLOBAL_TENANTID=\\\"${PCS_AUTH_AAD_GLOBAL_TENANTID}\\\"\"                           >> ${ENVVARS}\necho \"export PCS_AUTH_AAD_GLOBAL_CLIENTID=\\\"${PCS_AUTH_AAD_GLOBAL_CLIENTID}\\\"\"                           >> ${ENVVARS}\necho \"export PCS_AUTH_AAD_GLOBAL_LOGINURI=\\\"${PCS_AUTH_AAD_GLOBAL_LOGINURI}\\\"\"                           >> ${ENVVARS}\necho \"export PCS_IOTHUB_CONNSTRING=\\\"${PCS_IOTHUB_CONNSTRING}\\\"\"                                         >> ${ENVVARS}\necho \"export PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING=\\\"${PCS_STORAGEADAPTER_DOCUMENTDB_CONNSTRING}\\\"\"   >> ${ENVVARS}\necho \"export PCS_TELEMETRY_DOCUMENTDB_CONNSTRING=\\\"${PCS_TELEMETRY_DOCUMENTDB_CONNSTRING}\\\"\"             >> ${ENVVARS}\necho \"export PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING=\\\"${PCS_TELEMETRYAGENT_DOCUMENTDB_CONNSTRING}\\\"\"   >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_ACCESS_CONNSTRING=\\\"${PCS_IOTHUBREACT_ACCESS_CONNSTRING}\\\"\"                 >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_HUB_NAME=\\\"${PCS_IOTHUBREACT_HUB_NAME}\\\"\"                                   >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_HUB_ENDPOINT=\\\"${PCS_IOTHUBREACT_HUB_ENDPOINT}\\\"\"                           >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_HUB_PARTITIONS=\\\"${PCS_IOTHUBREACT_HUB_PARTITIONS}\\\"\"                       >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT=\\\"${PCS_IOTHUBREACT_AZUREBLOB_ACCOUNT}\\\"\"                 >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_AZUREBLOB_KEY=\\\"${PCS_IOTHUBREACT_AZUREBLOB_KEY}\\\"\"                         >> ${ENVVARS}\necho \"export PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX=\\\"${PCS_IOTHUBREACT_AZUREBLOB_ENDPOINT_SUFFIX}\\\"\" >> ${ENVVARS}\necho \"export PCS_BINGMAP_KEY=\\\"${PCS_BINGMAP_KEY}\\\"\"                                                     >> ${ENVVARS}\necho \"export PCS_APPLICATION_SECRET=\\\"${PCS_APPLICATION_SECRET}\\\"\"                                       >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"##########################################################################################\"        >> ${ENVVARS}\necho \"# Development settings, don't change these in Production\"                                          >> ${ENVVARS}\necho \"# You can run 'start.sh --unsafe' to temporarily disable Auth and Cross-Origin protections\"        >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: true | false\"                                                                            >> ${ENVVARS}\necho \"# empty => Auth required\"                                                                          >> ${ENVVARS}\necho \"export PCS_AUTH_REQUIRED=\\\"\\\"\"                                                                     >> ${ENVVARS}\necho \"\"                                                                                                  >> ${ENVVARS}\necho \"# Format: { 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"                                >> ${ENVVARS}\necho \"# empty => CORS support disabled\"                                                                  >> ${ENVVARS}\necho \"export PCS_CORS_WHITELIST=\\\"\\\"\"                                                                    >> ${ENVVARS}\n\n# ========================================================================\n\nnohup /app/start.sh &\n", "num_lines": 169}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\ncd /app\n\nif [[ \"$1\" == \"\" ]]; then\n  docker-compose logs\nelse\n  docker logs -f --tail 100 $1\nfi\n", "num_lines": 10}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\ncd /app\n\necho \"Starting simulation...\"\nISUP=$(curl -sk https://localhost/devicesimulation/v1/status | grep \"Alive\" | wc -l)\nwhile [[ \"$ISUP\" == \"0\" ]]; do\n  echo \"Waiting for simulation service to be available...\"\n  sleep 4\n  ISUP=$(curl -sk https://localhost/devicesimulation/v1/status | grep \"Alive\" | wc -l)\ndone\ncurl -sk -X POST \"https://localhost/devicesimulation/v1/simulations?template=default\" -H \"content-type: application/json\" -d \"{}\"\necho\n", "num_lines": 14}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\ncd /app\n\nsource \"env-vars\"\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_ERR=\"\\033[1;31m\" # light red\n\nAPP_PATH=\"/app\"\nWEBUICONFIG=\"${APP_PATH}/webui-config.js\"\nWEBUICONFIG_SAFE=\"${APP_PATH}/webui-config.js.safe\"\nWEBUICONFIG_UNSAFE=\"${APP_PATH}/webui-config.js.unsafe\"\n\nrm -f ${WEBUICONFIG}\ncp -p ${WEBUICONFIG_SAFE} ${WEBUICONFIG}\n\nif [[ \"$1\" == \"--unsafe\" ]]; then\n  echo -e \"${COL_ERR}WARNING! Starting services in UNSAFE mode!${COL_NO}\"\n  # Disable Auth\n  export PCS_AUTH_REQUIRED=\"false\"\n  # Allow cross-origin requests from anywhere\n  export PCS_CORS_WHITELIST=\"{ 'origins': ['*'], 'methods': ['*'], 'headers': ['*'] }\"\n\n  rm -f ${WEBUICONFIG}\n  cp -p ${WEBUICONFIG_UNSAFE} ${WEBUICONFIG}\nfi\n\nlist=$(docker ps -aq)\nif [ -n \"$list\" ]; then\n    docker rm -f $list\nfi\nrm -f nohup.out\n\nnohup docker-compose up &\n\nISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\nwhile [[ \"$ISUP\" == \"0\" ]]; do\n  echo \"Waiting for web site to start...\"\n  sleep 3\n  ISUP=$(curl -ks https://localhost/ | grep -i \"html\" | wc -l)\ndone\n", "num_lines": 43}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\ncd /app\n\ndocker stats -a\n", "num_lines": 6}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\ncd /app\n\necho\n\ndocker-compose ps\n\nCOL_NO=\"\\033[0m\" # no color\nCOL_MARK=\"\\033[1;33m\" # yellow\n\necho -e \"\\n${COL_MARK}Run ./logs.sh <service name> to see the logs of a service.${COL_NO}\"\n", "num_lines": 13}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n\nlist=$(docker ps -aq)\n\nif [ -n \"$list\" ]; then\n    docker rm -f $list\nfi\n", "num_lines": 8}
{"repo_name": "azure-iot-pcs-tools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -ex\n\n# Where to download scripts from\nSCRIPTS_REPO=\"https://raw.githubusercontent.com/Azure/azure-iot-pcs-tools/master/remote-monitoring/single-vm-scripts/\"\n\ncd /app\n\n# Download scripts\nwget $SCRIPTS_REPO/logs.sh     -O /app/logs.sh     && chmod 750 /app/logs.sh\nwget $SCRIPTS_REPO/simulate.sh -O /app/simulate.sh && chmod 750 /app/simulate.sh\nwget $SCRIPTS_REPO/start.sh    -O /app/start.sh    && chmod 750 /app/start.sh\nwget $SCRIPTS_REPO/stats.sh    -O /app/stats.sh    && chmod 750 /app/stats.sh\nwget $SCRIPTS_REPO/status.sh   -O /app/status.sh   && chmod 750 /app/status.sh\nwget $SCRIPTS_REPO/stop.sh     -O /app/stop.sh     && chmod 750 /app/stop.sh\nwget $SCRIPTS_REPO/update.sh   -O /app/update.sh   && chmod 750 /app/update.sh\n\n# Stop the services, so Docker images are not in use\n./stop.sh\n\n# Update Docker images\ndocker-compose pull --ignore-pull-failure\n\n# Start the services\n./start.sh\n", "num_lines": 25}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsdk_root=\"$HOME\"\nopenwrt_folder=\"openwrt\"\nopenwrt_sdk_folder=\"sdk\"\nworking_dir=$PWD\niot_dir=\"azure-iot-sdk-c\"\n\nusage ()\n{\n    echo 'build.sh [options]'\n    echo 'options'\n    echo ' -d, --sdkroot   OpenWRT SDK root directory'\n    echo '                 (default: $HOME)'\n    exit 1\n}\n\nprocess_args ()\n{\n    while [ ! -z \"$1\" ] && [ ! -z \"$2\" ]\n    do\n        if [ \"$1\" == \"-d\" ] || [ \"$1\" == \"--sdkroot\" ]\n        then\n            sdk_root=\"$2\"\n        else\n            usage\n        fi\n\n        shift\n        shift\n    done\n}\n\nbuild_iot()\n{\n    echo \"Building IoT\"\n    rm -d -f -r $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir\n    mkdir $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir\n    mkdir $sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/src\n    cp -f \"$working_dir/Makefile.iot\" \"$sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/Makefile\"\n    cd \"$working_dir/../../..\"\n    cp -R -f . \"$sdk_root/$openwrt_folder/$openwrt_sdk_folder/package/$iot_dir/src\"\n    cd \"$sdk_root/$openwrt_folder/$openwrt_sdk_folder\"\n    make V=s \"package/$iot_dir/compile\"\n}\n\nprocess_args $*\n\nbuild_iot", "num_lines": 51}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ninstall_root=\"$HOME\"\nopenwrt_folder=\"openwrt\"\nopenwrt_sdk_folder=\"sdk\"\nworking_dir=$PWD\npackage_dir=\"package\"\n\niot_dir=\"azure-iot-sdk-c\"\niot_repo=\"https://github.com/Azure/azure-iot-sdk-c.git\"\niot_makefile=\"Makefile.iot\"\n\nusage ()\n{\n    echo 'setup.sh [options]'\n    echo 'options'\n    echo ' -d, --installdir   OpenWRT SDK root directory'\n    echo '                    (default: $HOME)'\n    exit 1\n}\n\nprocess_args ()\n{\n    while [ ! -z \"$1\" ] && [ ! -z \"$2\" ]\n    do\n        if [ \"$1\" == \"-d\" ] || [ \"$1\" == \"--installdir\" ]\n        then\n            install_root=\"$2\"\n        else\n            usage\n        fi\n\n        shift\n        shift\n    done\n}\n\nsetup_sdk()\n{\n  # Check if SDK is installed\n  #if [ ! -d \"$install_root/$openwrt_folder/$openwrt_sdk_folder\" ]\n  #then\n    # Kickoff the SDK installation since it doesn't exists\n    ./setup_sdk.sh -d $install_root\n  #fi\n}\n\nprocess_args $*\n\nsetup_sdk", "num_lines": 52}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\ncd $STAGING_DIR\necho $NEWTIN | sudo -S rm -r azure-iot-pal-arduino\ngit clone https://github.com/Azure/azure-iot-pal-arduino.git \n\ncd azure-iot-pal-arduino\necho \"copying sdk sources path to pal layer now\"\necho $NEWTIN | sudo -S cp -r $SOURCES_DIR/. sdk/\n\ncd build_all\n\npython3 make_sdk.py -o $ARDUINO_LIBRARY_DIR\n\n# input WIFI_SSID, WIFI_PWD, and IOTHUB_CONNECTION_DEVICE_STRING into iot_config.h\n\ncd $ARDUINO_LIBRARY_DIR/AzureIoTHub/examples/esp8266/iothub_ll_telemetry_sample/\necho $NEWTIN | sudo -S sed -i 's/your-wifi-name/'$WIFI_SSID'/g' iot_configs.h\necho $NEWTIN | sudo -S sed -i 's/your-wifi-pwd/'$WIFI_PWD'/g' iot_configs.h\necho $NEWTIN | sudo -S sed -i 's@your-iothub-DEVICE-connection-string@'$IOTHUB_CONNECTION_DEVICE_STRING'@g' iot_configs.h\n\ncd $ARDUINO_LIBRARY_DIR/AzureIoTHub/examples/esp32/iothub_ll_telemetry_sample/\necho $NEWTIN | sudo -S sed -i 's/your-wifi-name/'$WIFI_SSID'/g' iot_configs.h\necho $NEWTIN | sudo -S sed -i 's/your-wifi-pwd/'$WIFI_PWD'/g' iot_configs.h\necho $NEWTIN | sudo -S sed -i 's@your-iothub-DEVICE-connection-string@'$IOTHUB_CONNECTION_DEVICE_STRING'@g' iot_configs.h\n", "num_lines": 27}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\nsdk_repo=\"http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2\"\nsdk_repo_x86=\"http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2\"\nsdk_repo_x64=\"http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-64bit.tar.bz2\"\ninstall_root=\"$HOME\"\nopenwrt_folder=\"openwrt\"\nopenwrt_sdk_folder=\"sdk\"\nworking_dir=$PWD\npackage_dir=\"package\"\n\nMACHINE_TYPE=`uname -m`\n\nusage ()\n{\n    echo 'setup_sdk.sh [options]'\n    echo 'options'\n    echo ' -d, --installdir   destination root directory for OpenWRT SDK installation'\n    echo '                    (default: $HOME)'\n    echo ' -s, --sdk          url of the prebuilt OpenWRT SDK archive'\n    echo '                    (default: http://download.linino.org/linino-utils/OpenWrt-SDK-ar71xx-for-linux-x86_64-gcc-4.6-linaro_uClibc-0.9.33.2-32bit.tar.bz2)'\n    exit 1\n}\n\nprocess_args ()\n{\n    while [ ! -z \"$1\" ] && [ ! -z \"$2\" ]\n    do\n        if [ \"$1\" == \"-d\" ] || [ \"$1\" == \"--installdir\" ]\n        then\n          install_root=\"$2\"\n        elif [ \"$1\" == \"-s\" ] || [ \"$1\" == \"--sdk\" ]\n        then\n          sdk_repo=\"$2\"\n        else\n          usage\n        fi\n\n        shift\n        shift\n    done\n}\n\ndownload_sdk()\n{\n  if [ -d  \"$install_root/$openwrt_folder/$openwrt_sdk_folder\" ]\n\tthen\n    # SDK folder already exists ask to reinstall SDK\n    read -p \"The OpenWRT SDK ($install_root/$openwrt_folder/$openwrt_sdk_folder) already exists. Do you want to delete and reinstall? (Y/N)\" input_var\n    if [ ! \"$input_var\" == \"y\" ] && [ ! \"$input_var\" == \"Y\" ]\n    then\n      return\n    fi\n\tfi\n\n  read -p \"Download and installation of the OpenWRT SDK may take some time. Do you want to continue? (Y/N)\" input_var\n  if [ ! \"$input_var\" == \"y\" ] && [ ! \"$input_var\" == \"Y\" ]\n  then\n    exit 1\n  fi\n\n\techo \"Downloading OpenWRT SDK to $install_root/$openwrt_folder\"\n\n  cd $install_root\n\n\tif [ ! -d  $openwrt_folder ]\n\tthen\n\t\tmkdir $openwrt_folder\n\tfi\n\n  # Download the SDK\n  cd $openwrt_folder\n\n  if [ -d $openwrt_sdk_folder ]\n  then\n    rm -r -f $openwrt_sdk_folder\n  fi\n\n  if [ \"$1\" == \"-s\" ] || [ \"$1\" == \"--sdk\" ]\n  then\n    wget $sdk_repo -O openwrtsdk.tar.bz2\n  elif [ ${MACHINE_TYPE} == 'x86_64' ]\n  then\n    wget $sdk_repo_x64 -O openwrtsdk.tar.bz2\n  else\n    wget $sdk_repo_x86 -O openwrtsdk.tar.bz2\n  fi\n\n  tar xvf openwrtsdk.tar.bz2\n\n  # get folders only\n  folders=(*/)\n\n  # assuming the only and first file is the name of the extracted archive\n  extractedFolder=${folders[0]}\n\n  mv $extractedFolder $openwrt_sdk_folder\n\n  patch_sdk\n}\n\npatch_sdk()\n{\n  #removing cmake from the toolchain\n  mv \"$install_root/$openwrt_folder/$openwrt_sdk_folder/staging_dir/host/bin/cmake\" \"$install_root/$openwrt_folder/$openwrt_sdk_folder/staging_dir/host/bin/cmake.old\"\n}\n\nprocess_args $*\necho \"Installing OpenWRT SDK to $install_root/$openwrt_folder/$openwrt_sdk_folder\"\n\ndownload_sdk\n\necho \"Finished installing the OpenWRT SDK\"\n", "num_lines": 116}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n\nset -e\nset -x\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/../..\" && pwd)\nlog_dir=$build_root\nrun_e2e_tests=OFF\nrun_sfc_tests=OFF\nrun_longhaul_tests=OFF\nbuild_amqp=ON\nbuild_http=ON\nbuild_mqtt=ON\nno_blob=OFF\nrun_unittests=OFF\nrun_valgrind=0\nbuild_folder=$build_root\"/cmake\"\nmake=true\ntoolchainfile=\" \"\ncmake_install_prefix=\" \"\nno_logging=OFF\nprov_auth=OFF\nprov_use_tpm_simulator=OFF\nuse_edge_modules=OFF\nhsm_type_sastoken=OFF\nhsm_type_symm_key=OFF\nhsm_type_x509=OFF\nhsm_type_riot=OFF\nenable_ipv6=OFF\nbuild_config=Debug\n\nusage ()\n{\n    echo \"build.sh [options]\"\n    echo \"options\"\n    echo \" -cl, --compileoption <value>  specify a compile option to be passed to gcc\"\n    echo \"   Example: -cl -O1 -cl ...\"\n    echo \" --run-e2e-tests               run the end-to-end tests (e2e tests are skipped by default)\"\n    echo \" --run-sfc-tests               run the end-to-end tests for Service Faults (sfc tests are skipped by default)\"\n    echo \" --run-unittests               run the unit tests\"\n    echo \" --run-longhaul-tests          run long haul tests (long haul tests are not run by default)\"\n    echo \"\"\n    echo \" --no-amqp                     do no build AMQP transport and samples\"\n    echo \" --no-http                     do no build HTTP transport and samples\"\n    echo \" --no-mqtt                     do no build MQTT transport and samples\"\n    echo \" --no_uploadtoblob             do no build upload to blob\"\n    echo \" --no-make                     do not run make after cmake\"\n    echo \" --toolchain-file <file>       pass cmake a toolchain file for cross compiling\"\n    echo \" --install-path-prefix         alternative prefix for make install\"\n    echo \" -rv, --run_valgrind           will execute ctest with valgrind\"\n    echo \" --no-logging                  Disable logging\"\n    echo \" --provisioning                Use Provisioning with Flow\"\n    echo \" --use-tpm-simulator           Build TPM simulator\"\n    echo \" --use-edge-modules            Build Edge modules\" \n    echo \" --use-hsmsymmkey              Build with HSM for Symmetric Key\" \n    echo \" --use-hsmsas                  Build with HSM for TPM\"  \n    echo \" --use-hsmx509                 Build with HSM for X509 Client Authentication\" \n    echo \" --use-hsmriot                 Build with HSM for RIoT/DICE\" \n    echo \" --use-ipv6-dualstack          Build with IPv6 dual stack support\"\n    echo \" --config <value>              [Debug] build configuration (e.g. Debug, Release)\"\n    exit 1\n}\n\nprocess_args ()\n{\n    save_next_arg=0\n    extracloptions=\" \"\n\n    for arg in $*\n    do      \n      if [ $save_next_arg == 1 ]\n      then\n        # save arg to pass to gcc\n        extracloptions=\"$arg $extracloptions\"\n        save_next_arg=0\n      elif [ $save_next_arg == 2 ]\n      then\n        # save arg to pass as toolchain file\n        toolchainfile=\"$arg\"\n           save_next_arg=0\n      elif [ $save_next_arg == 3 ]\n      then\n        # save arg for install prefix\n        cmake_install_prefix=\"$arg\"\n        save_next_arg=0\n      elif [ $save_next_arg == 4 ]\n      then\n        # save arg for build config type\n        build_config=\"$arg\"\n        save_next_arg=0\n      else\n          case \"$arg\" in\n              \"-cl\" | \"--compileoption\" ) save_next_arg=1;;\n              \"--run-e2e-tests\" ) run_e2e_tests=ON;;\n              \"--run-unittests\" ) run_unittests=ON;;\n              \"--run-longhaul-tests\" ) run_longhaul_tests=ON;;\n              \"--no-amqp\" ) build_amqp=OFF;;\n              \"--no-http\" ) build_http=OFF;;\n              \"--no-mqtt\" ) build_mqtt=OFF;;\n              \"--no_uploadtoblob\" ) no_blob=ON;;\n              \"--no-make\" ) make=false;;\n              \"--toolchain-file\" ) save_next_arg=2;;\n              \"-rv\" | \"--run_valgrind\" ) run_valgrind=1;;\n              \"--no-logging\" ) no_logging=ON;;\n              \"--install-path-prefix\" ) save_next_arg=3;;\n              \"--provisioning\" ) prov_auth=ON;;\n              \"--use-tpm-simulator\" ) prov_use_tpm_simulator=ON;;\n              \"--run-sfc-tests\" ) run_sfc_tests=ON;;\n              \"--use-edge-modules\") use_edge_modules=ON;;\n              \"--use-hsmsymmkey\")  hsm_type_symm_key=ON;;\n              \"--use-hsmsas\")  hsm_type_sastoken=ON;;\n              \"--use-hsmx509\") hsm_type_riot=OFF; hsm_type_x509=ON;;\n              \"--use-hsmriot\") hsm_type_riot=ON; hsm_type_x509=OFF;;\n              \"--use-ipv6-dualstack\") enable_ipv6=ON;;\n              \"--config\") save_next_arg=4;;\n              * ) usage;;\n          esac\n      fi\n    done\n\n    if [ \"$toolchainfile\" != \" \" ]\n    then\n      toolchainfile=$(readlink -f $toolchainfile)\n      toolchainfile=\"-DCMAKE_TOOLCHAIN_FILE=$toolchainfile\"\n    fi\n   \n   if [ \"$cmake_install_prefix\" != \" \" ]\n   then\n     cmake_install_prefix=\"-DCMAKE_INSTALL_PREFIX=$cmake_install_prefix\"\n   fi\n}\n\nprocess_args $*\n\nrm -r -f $build_folder\nmkdir -m777 -p $build_folder\npushd $build_folder\necho \"Generating Build Files\"\ncmake $toolchainfile $cmake_install_prefix $build_root -Drun_valgrind:BOOL=$run_valgrind -DcompileOption_C:STRING=\"$extracloptions\" -Drun_e2e_tests:BOOL=$run_e2e_tests -Drun_sfc_tests:BOOL=$run_sfc_tests -Drun_longhaul_tests=$run_longhaul_tests -Duse_amqp:BOOL=$build_amqp -Duse_http:BOOL=$build_http -Duse_mqtt:BOOL=$build_mqtt -Ddont_use_uploadtoblob:BOOL=$no_blob -Drun_unittests:BOOL=$run_unittests -Dno_logging:BOOL=$no_logging -Duse_prov_client:BOOL=$prov_auth -Duse_tpm_simulator:BOOL=$prov_use_tpm_simulator -Duse_edge_modules=$use_edge_modules -Dhsm_type_riot=$hsm_type_riot -Dhsm_type_x509=$hsm_type_x509 -Dhsm_type_symm_key=$hsm_type_symm_key -Dhsm_type_sastoken=$hsm_type_sastoken -Denable_ipv6=$enable_ipv6 -DCMAKE_BUILD_TYPE=$build_config\nchmod --recursive ugo+rw ../cmake\n\n# Set the default cores\nMAKE_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\necho \"Initial MAKE_CORES=$MAKE_CORES\"\n\n# Make sure there is enough virtual memory on the device to handle more than one job  \nMINVSPACE=\"1500000\"\n\n# Acquire total memory and total swap space setting them to zero in the event the command fails\nMEMAR=( $(sed -n -e 's/^MemTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' -e 's/^SwapTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' /proc/meminfo) )\n[ -z \"${MEMAR[0]##*[!0-9]*}\" ] && MEMAR[0]=0\n[ -z \"${MEMAR[1]##*[!0-9]*}\" ] && MEMAR[1]=0\n\nlet VSPACE=${MEMAR[0]}+${MEMAR[1]}\n\necho \"VSPACE=$VSPACE\"\n\nif [ \"$VSPACE\" -lt \"$MINVSPACE\" ] ; then\n  echo \"WARNING: Not enough space.  Setting MAKE_CORES=1\"\n  MAKE_CORES=1\nfi\n\necho \"Building Project\"\ncmake --build . -- --jobs=$MAKE_CORES\n\npopd\n", "num_lines": 171}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -o errexit # Exit if command failed.\nset -o pipefail # Exit if pipe failed.\n\n# Only for testing E2E behaviour !!! \nTEST_CORES=16\n\n# Refresh dynamic libs to link to\nsudo ldconfig\n\nctest -T test --no-compress-output -C \"Debug\" -V -j $TEST_CORES --schedule-random\n", "num_lines": 16}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -o errexit # Exit if command failed.\nset -o pipefail # Exit if pipe failed.\n\n# Only for testing E2E behaviour !!! \nTEST_CORES=16\n\n# Refresh dynamic libs to link to\nsudo ldconfig\n\nctest --overwrite MemoryCheckCommandOptions=\"--leak-check=full --error-exitcode=100\" -T MemCheck --no-compress-output -C \"Debug\" -V -j $TEST_CORES --schedule-random\n", "num_lines": 16}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#This script updates a fresh Ubuntu installation with all the dependent\n# components necessary to use the IoT Client SDK for C.\n\nrepo_name_from_uri()\n{\n    echo \"$1\" | sed -e 's|/$||' -e 's|:*/*\\.git$||' -e 's|.*[/:]||g'\n}\n\nscriptdir=$(cd \"$(dirname \"$0\")\" && pwd)\ndeps=\"curl build-essential pkg-config libcurl4-openssl-dev git cmake libssl-dev uuid-dev valgrind\"\nrepo=\"https://github.com/Azure/azure-iot-sdk-c.git\"\nrepo_name=$(repo_name_from_uri $repo)\n\npush_dir () { pushd $1 > /dev/null; }\npop_dir () { popd $1 > /dev/null; }\n\nrepo_exists ()\n{\n    push_dir \"$scriptdir\"\n    [ \"$(git rev-parse --is-inside-work-tree)\" == \"true\" ] || return 1\n    origin=$(git config remote.origin.url) || return 1\n    actual_name=$(repo_name_from_uri $origin)\n    [ \"${repo_name,,}\" == \"${actual_name,,}\" ] || return 1\n    pop_dir\n}\n\ndeps_install ()\n{\n    sudo apt-get update\n    sudo apt-get install -y $deps\n}\n\nclone_source ()\n{\n    git clone $repo\n}\n\ndeps_install\n\nif repo_exists\nthen\n    echo \"Repo $repo_name already cloned\"\n    push_dir \"$(git rev-parse --show-toplevel)\"\nelse\n    clone_source || exit 1\n    push_dir \"$repo_name\"\nfi\n\npop_dir", "num_lines": 51}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -o pipefail\n#\n\nazureiot_folder=\"azure-iot-sdk\"\nazureiot_repo=\"https://github.com/Azure/azure-iot-sdk-c\"\nazureiot_c_folder=\"azure-iot-sdk-c-0.1.0\"\nazureiot_c_zip_folder=\"azure-iot-sdk-c-0.1.0.tar.gz\"\nazureiot_c_change_file=\"azure-iot-sdk-c_0.1.0-1_source.changes\"\n\nsync_azureiot()\n{\n\techo Sync Azure IoT SDK\n\techo $azureiot_repo\n\n\tgit clone $azureiot_repo $azureiot_folder\n}\n\nsetup_debian_folder()\n{\n\tcd ~/$azureiot_folder\n\tmv c $azureiot_c_folder\n\ttar czvf $azureiot_c_zip_folder $azureiot_c_folder\n\tcd $azureiot_c_folder\n\tdh_make -y -l -c mit -e aziotsdklinux@outlook.com -f ../$azureiot_c_zip_folder\n\n\t# Remove the debian folder\n\tdh_make -y -l -c mit -e aziotsdklinux@outlook.com -f ../$azureiot_c_zip_folder\n\tcp -r ~/$azureiot_folder/$azureiot_c_folder/build_all/packaging/linux/debian ./\n}\n\nbuild_package()\n{\n\tcd ..\n\techo build package\n\tdpkg-buildpackage -us -uc\n\n\t# Sign the packages\n\tdpkg-buildpackage -S\n}\n\nupload_to_Launchpad()\n{\n\tdput ppa:aziotsdklinux/ppa-azure-iot-sdk-c $azureiot_c_file\n}\n\nsync_azureiot\nbuild_package\n", "num_lines": 49}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nif [ $CORES -eq 1 ]\nthen\n    LOADLIMIT=$CORES\nelse\n    LOADLIMIT=$(perl -e \"print int($CORES * 0.8)\")\nfi\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake -Drun_valgrind:BOOL=ON $build_root -Drun_unittests:BOOL=ON\n\necho \"Running: make --jobs=$CORES --max-load=$LOADLIMIT\"\nmake --jobs=$CORES --max-load=$LOADLIMIT\n\npopd\n", "num_lines": 40}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\nclone_root=$(cd \"$(dirname \"$0\")/../..\" && pwd)\ncd $build_root\n\necho \"Build Root $build_root\"\n\nsdk_build_folder=$build_root\"/cmake\"\n\n# Build the SDK\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root -Duse_prov_client=ON\nmake install --jobs=$CORES\npopd\n\ncd \"$clone_root\"\n\necho \"Clone the back compat repo\"\ngit clone https://github.com/Azure/azure-iot-c-back-compat.git --recursive\n\nback_compat_root=\"$clone_root/azure-iot-c-back-compat\"\n\npushd $back_compat_root\n\n# Now run back compat\nrm -rf cmake\nmkdir -p cmake\npushd cmake\ncmake ..\nmake --jobs=$CORES\n\npopd\n", "num_lines": 50}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_bearssl:BOOL=ON -Drun_e2e_tests:BOOL=ON\ncd cmake\n\nmake --jobs=$CORES\n", "num_lines": 21}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_c_ares:BOOL=ON -Drun_e2e_tests:BOOL=ON\ncd cmake\n\nmake --jobs=$CORES\n", "num_lines": 21}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh \"$@\"\n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 23}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nMAKE_CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\necho \"Initial MAKE_CORES=$MAKE_CORES\"\n\n# Make sure there is enough virtual memory on the device to handle more than one job  \nMINVSPACE=\"1500000\"\n\n# Acquire total memory and total swap space setting them to zero in the event the command fails\nMEMAR=( $(sed -n -e 's/^MemTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' -e 's/^SwapTotal:[^0-9]*\\([0-9][0-9]*\\).*/\\1/p' /proc/meminfo) )\n[ -z \"${MEMAR[0]##*[!0-9]*}\" ] && MEMAR[0]=0\n[ -z \"${MEMAR[1]##*[!0-9]*}\" ] && MEMAR[1]=0\n\nlet VSPACE=${MEMAR[0]}+${MEMAR[1]}\n\nif [ \"$VSPACE\" -lt \"$MINVSPACE\" ] ; then\necho \"WARNING: Not enough space.  Setting MAKE_CORES=1\"\nMAKE_CORES=1\nfi\n\necho \"Create custom HSM library for later\"\nhsm_folder=$build_root\"/build_cust_hsm\"\nrm -r -f $hsm_folder\nmkdir -p $hsm_folder\npushd $hsm_folder\n\ncmake \"$build_root/provisioning_client/samples/custom_hsm_example\"\nmake --jobs=$MAKE_CORES\n\ncustom_hsm_lib=$hsm_folder\"/libcustom_hsm_example.a\"\n\ndeclare -a arr=(\n    \"-Duse_http=OFF\"\n    \"-Duse_amqp=OFF -Duse_http=OFF -Dno_logging=OFF -Ddont_use_uploadtoblob=ON\"\n    \"-Duse_prov_client=ON -Dbuild_provisioning_service_client=OFF\"\n    \"-Dbuild_as_dynamic=ON\"\n    \"-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON\"\n    \"-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON -Duse_prov_client:BOOL=ON\"\n    \"-Dbuild_as_dynamic:BOOL=ON -Ddont_use_uploadtoblob:BOOL=ON -Duse_edge_modules:BOOL=ON\"\n    \"-Drun_longhaul_tests=ON\"\n    \"-Duse_prov_client=ON -Dhsm_custom_lib=$custom_hsm_lib\"\n    \"-Drun_e2e_tests=ON -Drun_sfc_tests=ON -Duse_edge_modules=ON\"\n    \"-Drun_e2e_tests=ON -Duse_azure_cloud_rsa_cert=ON\"\n    \"-Drun_e2e_tests=ON -Duse_azure_cloud_ecc_cert=ON\"\n    \"-Duse_prov_client:BOOL=ON -Dhsm_type_symm_key:BOOL=ON\"\n    \"-Duse_prov_client:BOOL=ON -Dhsm_type_x509:BOOL=ON\"\n    \"-Duse_prov_client:BOOL=ON -Dhsm_type_x509:BOOL=OFF -Dhsm_type_riot:BOOL=ON\"\n    \"-Duse_prov_client:BOOL=ON -Dhsm_type_sastoken:BOOL=ON\"\n    \"-Duse_prov_client:BOOL=ON -Dstrict_prototypes:BOOL=ON\"\n    \"-Duse_prov_client:BOOL=ON -DcompileOption_C=-Wunused-variable\"\n     \"-Duse_prov_client:BOOL=ON -DcompileOption_C=-Wmaybe-uninitialized\"\n)\n\nfor item in \"${arr[@]}\"\ndo\n    rm -r -f $build_folder\n    mkdir -p $build_folder\n    pushd $build_folder\n\n    echo \"executing cmake/make with options <<$item>>\"\n    cmake $build_root $item\n\n    make --jobs=$MAKE_CORES\ndone\npopd\n", "num_lines": 83}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\nclone_root=$(cd \"$(dirname \"$0\")/../..\" && pwd)\ncd $build_root\n\necho \"Build Root $build_root\"\n\nsdk_build_folder=$build_root\"/cmake\"\n\n# Build the SDK\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root\nmake install --jobs=$CORES\npopd\n\n# Now use the deps\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root -Duse_installed_dependencies=ON\nmake --jobs=$CORES\npopd\n\n# Now use the deps for provisioning\nrm -rf $sdk_build_folder\nmkdir -p $sdk_build_folder\npushd $sdk_build_folder\ncmake $build_root -Duse_installed_dependencies=ON -Duse_prov_client:BOOL=ON\nmake --jobs=$CORES\npopd\n", "num_lines": 48}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake $build_root -Duse_mbedtls=ON -Duse_openssl=OFF -Ddont_use_uploadtoblob=ON -Drun_e2e_tests=ON\nmake --jobs=$CORES\n\npopd\n", "num_lines": 30}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\ncmake . -Bcmake -Duse_http=ON -Duse_mqtt=ON -Duse_amqp=ON -Duse_openssl:BOOL=ON -Dhsm_type_x509:BOOL=ON -Duse_prov_client:BOOL=ON -Drun_e2e_tests:BOOL=ON -Drun_e2e_openssl_engine_tests:BOOL=ON -Drun_valgrind:BOOL=ON\ncd cmake\n\nmake --jobs=$CORES\n\n# Configure OpenSSL with PKCS#11 Engine and SoftHSM\n\n## IoT Hub Tests:\n\n# 1. Create new test token.\n#softhsm2-util --delete-token --token test-token > /dev/null\nsofthsm2-util --init-token --slot 0 --label test-token --pin 1234 --so-pin 4321\n# 2. Convert key from PKCS#1 to PKCS#8\necho $IOTHUB_E2E_X509_PRIVATE_KEY_BASE64 | base64 --decode > test-key.pem\nopenssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in test-key.pem -out test-key.p8\n# 3. Import private key into the token.\nsofthsm2-util --pin 1234 --import ./test-key.p8 --token test-token --id b000 --label test-privkey\nrm test-key.pem\n# 4. (Test) List keys associated with slot (should see the private key listed)\npkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so -l -p 1234 --token test-token --list-objects\n\n\n## Provisioning Tests:\n\n# 2. Convert key from PKCS#1 to PKCS#8\necho $IOT_DPS_INDIVIDUAL_X509_KEY | base64 --decode > test-key.pem\nopenssl pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in test-key.pem -out test-key.p8\n# 3. Import private key into the token.\nsofthsm2-util --pin 1234 --import ./test-key.p8 --token test-token --id d000 --label dps-privkey\nrm test-key.pem\n# 4. (Test) List keys associated with slot (should see the private key listed)\npkcs11-tool --module /usr/lib/softhsm/libsofthsm2.so -l -p 1234 --token test-token --list-objects\n\n", "num_lines": 50}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\nbuild_folder=$build_root\"/cmake\"\n\n# Set the default cores\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake $build_root -Duse_wolfssl=ON -Duse_openssl=OFF -Ddont_use_uploadtoblob=ON -Drun_e2e_tests=ON\nmake --jobs=$CORES\n\npopd\n", "num_lines": 30}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-longhaul-tests --run_valgrind --config Debug \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 17}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\nsw_vers\ngcc --version\nopenssl version\ncurl --version\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\ncmake .. -DOPENSSL_ROOT_DIR:PATH=/usr/local/opt/openssl -Duse_openssl:bool=ON -Drun_unittests:bool=ON\ncmake --build . -- --jobs=$CORES\n", "num_lines": 26}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\nsw_vers\nxcodebuild -version\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake\"\n\nCORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu)\nTEST_JOB_COUNT=16\necho \"Building with $CORES cores and running $TEST_JOB_COUNT tests in parallel\"\n\nrm -r -f $build_folder\nmkdir -p $build_folder\npushd $build_folder\n\ncmake .. -Duse_prov_client=OFF -Dhsm_type_x509=OFF -Dhsm_type_sastoken=OFF -Dhsm_type_symm_key=OFF -Drun_e2e_tests=ON -G Xcode -DCMAKE_BUILD_TYPE=Debug\ncmake --build . -- --jobs=$CORES\npopd\n", "num_lines": 28}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\ninstall_root=\"/home/jenkins\" \nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd) \ncd $build_root\n\n# ----------------------------------------------------------------------------- \n# -- helper subroutines \n# -----------------------------------------------------------------------------\ncheckExists() {\n    if hash $1 2>/dev/null;\n    then\n        return 1\n    else\n        echo \"$1\" not found. Please make sure that \"$1\" is installed and available in the path.\n        exit 1\n    fi\n}\n# ----------------------------------------------------------------------------- \n# -- Check for environment pre-requisites. This script requires -- that \n# the following programs work: -- curl build-essential(g++,gcc,make) \n# cmake git \n# -----------------------------------------------------------------------------\ncheckExists curl \ncheckExists g++ \ncheckExists gcc \ncheckExists make \ncheckExists cmake \ncheckExists git\n\n# ----------------------------------------------------------------------------- \n# -- Check for RPiTools directory.\n# -----------------------------------------------------------------------------\nif [ ! -d \"$install_root/RPiTools\" ];\nthen\n   echo ---------- Raspberry Pi tool-chain absent ----------\n   exit 1\nfi\n\n# ----------------------------------------------------------------------------- \n# -- Set environment variable\n# -----------------------------------------------------------------------------\ncd $install_root/RPiTools/tools/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/arm-linux-gnueabihf \nexport RPI_ROOT=$(pwd)\n\n# ----------------------------------------------------------------------------- \n# -- Create toolchain-rpi.cmake \n# -----------------------------------------------------------------------------\necho ---------- Creating toolchain cmake file ---------- \nFILE=\"$build_root/build_all/linux/toolchain-rpi.cmake\" \n\n/bin/cat <<EOM >$FILE\nINCLUDE(CMakeForceCompiler) \n\nSET(CMAKE_SYSTEM_NAME Linux) # this one is important \nSET(CMAKE_SYSTEM_VERSION 1) # this one not so much\nSET(CMAKE_SYSROOT ${RPI_ROOT}/sysroot) # This is how it finds our cross compiled libs (openssl, curl, utilslinux)\n# this is the location of the amd64 toolchain targeting the Raspberry Pi\nSET(CMAKE_C_COMPILER /home/jenkins/RPiTools/arm-bcm2708/arm-rpi-4.9.3-linux-gnueabihf/bin/arm-linux-gnueabihf-gcc)\n\n# this is the file system root of the target\nSET(CMAKE_FIND_ROOT_PATH ${RPI_ROOT}/sysroot)\n\n# search for programs in the build host directories\nSET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\n\n# for libraries and headers in the target directories\nSET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) \nSET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) \nEOM\n\n# ----------------------------------------------------------------------------- \n# -- Modify iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.c \n# -----------------------------------------------------------------------------\necho ---------- Modifying iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.c file ---------- \ncd $build_root \nsed -i 's/\\[device connection string\\]/'$IOTHUB_DEVICE_CONN_STR'/g' iothub_client/samples/iothub_ll_telemetry_sample/iothub_ll_telemetry_sample.c\n\n# ----------------------------------------------------------------------------- \n# -- Build the SDK \n# -----------------------------------------------------------------------------\necho ---------- Building the SDK by executing build.sh script ---------- \ncd $build_root/build_all/linux \n./build.sh --toolchain-file toolchain-rpi.cmake -cl --sysroot=$RPI_ROOT/sysroot\n[ $? -eq 0 ] || exit $?\n", "num_lines": 93}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# assume directory is root of downloaded repo\nmkdir cmake\ncd cmake\nls -al\n\n# Create a cmake toolchain file on the fly\necho \"SET(CMAKE_SYSTEM_NAME Linux)     # this one is important\" > toolchain.cmake\necho \"SET(CMAKE_SYSTEM_VERSION 1)      # this one not so much\" >> toolchain.cmake\n\necho \"SET(CMAKE_C_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-gcc)\" >> toolchain.cmake\necho \"SET(CMAKE_CXX_COMPILER ${TOOLCHAIN_EXES}/${TOOLCHAIN_NAME}-g++)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH ${TOOLCHAIN_SYSROOT})\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)\" >> toolchain.cmake\necho \"SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)\" >> toolchain.cmake\nls -al\n\n# Build the SDK. This will use the OpenSSL, cURL and uuid binaries that we built before\ncmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake -Duse_prov_client:BOOL=OFF -DCMAKE_INSTALL_PREFIX=${TOOLCHAIN_PREFIX} -Drun_e2e_tests:BOOL=ON -Drun_unittests=:BOOL=ON ..\nmake -j 2\nls -al\n", "num_lines": 31}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --config Debug \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 23}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --config Debug \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 22}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --config Release \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 22}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --use-ipv6-dualstack --config Debug \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n", "num_lines": 22}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmx509 --use-edge-modules --config Release \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 23}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o nounset # Exit if variable not set\nset -o pipefail # Exit if pipe failed\n\n# Print version\ncat /etc/*release | grep VERSION*\ngcc --version\nopenssl version\ncurl --version\n\nbuild_root=$(cd \"$(dirname \"$0\")/..\" && pwd)\ncd $build_root\n\n# -- C --\n./build_all/linux/build.sh --run-unittests --run_valgrind --run-e2e-tests --provisioning --use-hsmsymmkey --use-hsmsas --use-hsmriot --use-edge-modules \"$@\" #-x \n[ $? -eq 0 ] || exit $?\n\n", "num_lines": 23}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# single quotes are used to turn off special meaning of $ in variables.\nexport IOTHUB_CONNECTION_STRING=''\nexport IOTHUB_EVENTHUB_CONNECTION_STRING=''\nexport IOTHUB_EVENTHUB_LISTEN_NAME=''\nexport IOTHUB_E2E_X509_THUMBPRINT=''\nexport IOTHUB_E2E_X509_CERT_BASE64=''\nexport IOTHUB_E2E_X509_PRIVATE_KEY_BASE64=''\nexport IOTHUB_EVENTHUB_CONSUMER_GROUP='$Default'\nIOTHUB_PARTITION_COUNT=16\n\n/home/pi/myagent/run.sh", "num_lines": 13}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nchmod -R 777 $PWD/drop\n# we need to cp because of something weird with artifacts\nmkdir -p $PWD/drop/copy/cmake/iothub_client/tests\ncp -r $PWD/drop/source_artifacts/cmake/iothub_client/tests/ $PWD/drop/copy/cmake/iothub_client/\n\nsudo setcap cap_net_raw,cap_net_admin+ep \\\n$PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_mqtt_e2e/iothubclient_mqtt_e2e_exe \\\ncap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_amqp_e2e/iothubclient_amqp_e2e_exe \\\ncap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_mqtt_ws_e2e/iothubclient_mqtt_ws_e2e_exe \\\ncap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_amqp_ws_e2e/iothubclient_amqp_ws_e2e_exe \\\ncap_net_raw,cap_net_admin+ep $PWD/drop/source_artifacts/cmake/iothub_client/tests/iothubclient_uploadtoblob_e2e/iothubclient_uploadtoblob_e2e_exe \n\n\n$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_mqtt_e2e/iothubclient_mqtt_e2e_exe\n$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_amqp_e2e/iothubclient_amqp_e2e_exe\n$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_mqtt_ws_e2e/iothubclient_mqtt_ws_e2e_exe\n$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_amqp_ws_e2e/iothubclient_amqp_ws_e2e_exe\n$PWD/drop/copy/cmake/iothub_client/tests/iothubclient_uploadtoblob_e2e/iothubclient_uploadtoblob_e2e_exe\n", "num_lines": 23}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n###################################################################################################\n################################### PI E2E TEST SETUP GUIDE #######################################\n###################################################################################################\n# This is a guide to setting up you raspberry pi to run E2E tests. Essentially all this stuff is \n# creating the proper toolchain including upgrading cURL to the latest version so that the\n# C Client Library can be able to use cURL without any issues like running out of memory. \n# \n# TO RUN THIS SCRIPT:\n# Get a Raspberry Pi and flash the SD card with Stretch. \n# This script has been tested to work on a brand new Install of Stretch. Don't use it if you care\n# about if your Stretch Image becomes unusable or not. Because it's messing with the curl stuff, \n# it might make things unusable... but it also probably won't. Still be cautious.   \n###################################################################################################\n###################################################################################################\n\n\n# ENABLE SSH BY DEFAULT \nif ! grep -Fxq \"systemctl start ssh\" /etc/rc.local\nthen\n    echo 'Enabling automatic start of ssh on bootup...'\n    #insert systemctl start ssh onto the 19th line of /etc/rc.local\n    sudo sed -i '19i\\systemctl start ssh' /etc/rc.local\n    # code if not found\nfi\n# END ENABLE SSH BY DEFAULT\n\n# GET NECESSARY PACKAGES\nsudo apt-get update -y\nsudo apt-get install -y vim git build-essential pkg-config git cmake libssl-dev uuid-dev valgrind\n\n###################################################################################################\n# DOWNLOAD AND INSTALL LINUX AGENT\n# FOR WALKTHROUGH: https://docs.microsoft.com/azure/devops/pipelines/agents/v2-linux?view=azure-devops\n# NOTE: You need a Azure DevOps PAT Token. Described in the link above. \n###################################################################################################\ncd ~\nwget https://vstsagentpackage.azureedge.net/agent/2.150.0/vsts-agent-linux-arm-2.150.0.tar.gz\nmkdir myagent && cd myagent\nif [[ $? -ne 0 ]]; then\n    echo \"myagent already created, overwriting\"\n    rm -r myagent && mkdir myagent && cd myagent\nfi\ntar zxvf ~/vsts-agent-linux-arm-2.150.0.tar.gz\n# Config will prompt for name of pool and PAT. \n./config.sh\n./run.sh\ncd ~ \n\n###################################################################################################\n# INSTALL NEWEST VERSION OF CURL AND POINT TO THE NEW CURL LIBRARY\n###################################################################################################\nif ! grep -Fxq \"LD_LIBRARY_PATH\" ~/.bashrc\nthen \n    echo 'export LD_LIBRARY_PATH'\n    echo 'export LD_LIBRARY_PATH=/usr/local/lib' >> ~/.bashrc\nfi\n\nprintf 'Setting variables by calling bashrc'\nsource ~/.bashrc\n[ $? -eq 0 ] || { echo \"bashrc source failed\"; exit 1; }\n\n# Install curl new version\nwget https://curl.haxx.se/download/curl-7.64.1.tar.gz\n\ntar -xzvf curl-7.64.1.tar.gz\ncd curl_source/curl-7.64.1/\n./configure --without-zlib --with-ssl\nmake -j\nsudo make install\n\nsudo ln -sf /usr/local/bin/curl /usr/bin/curl\n\necho \"Now you can run the cross compiled E2E tests!\"\n\n\n# ###################################################################################################\n# # UNCOMMENT THE BELOW LINES AND COMMENT OUT THE CURL INSTALL LINES ABOVE IF YOU WANT TO\n# # COMPILE THE SDK ON THE DEVICE AND RUN THE E2E TESTS\n# ###################################################################################################\n# # check if CURL_ROOT is already a variable set in bashrc...\n# if ! grep -Fxq \"CURL_ROOT\" ~/.bashrc\n# then\n#     printf 'Exporting variable CURL_ROOT...'\n#     echo 'export CURL_ROOT=/home/pi/curl_install' >> ~/.bashrc \n#     source ~/.bashrc\n#     # code if not found\n# fi\n\n# if ! grep -Fxq \"LD_LIBRARY_PATH\" ~/.bashrc\n# then \n#     echo 'export LD_LIBRARY_PATH'\n#     echo 'export LD_LIBRARY_PATH=$CURL_ROOT/lib' >> ~/.bashrc\n# fi\n\n# printf 'Setting variables by calling bashrc'\n# source ~/.bashrc\n# [ $? -eq 0 ] || { echo \"bashrc source failed\"; exit 1; }\n\n\n# # BUILD AND INSTALL NEW CURL TO CURL_ROOT\n# # We are commenting this out because it's useful info to have \n# # but for the E2E tests it works when CURL is installed directly on the device.\n# wget https://curl.haxx.se/download/curl-7.64.1.tar.gz\n# mkdir $CURL_ROOT\n# mkdir curl_source\n# tar -C curl_source -xzvf curl-7.64.1.tar.gz\n# cd curl_source/curl-7.64.1/\n# ./configure --prefix=$CURL_ROOT --disable-shared --without-zlib --with-ssl --enable-static\n# make -j\n# sudo make install\n\n# # END GET NECESARY PACKAGES \n\n# # BUILD THE SDK\n# cd ~\n# git clone --recursive https://github.com/Azure/azure-iot-sdk-c\n# cd azure-iot-sdk-c\n# if [ -d cmake ]   # for file \"if [-f /home/rama/file]\" \n# then \n#     echo \"cmake present\"\n#     rm -rf cmake \n# else\n#     echo \"cmake not present\"\n# fi\n# mkdir cmake && cd cmake\n# cmake -Drun_unittests=ON -Drun_e2e_tests=ON -DCMAKE_BUILD_TYPE=Debug -DCURL_LIBRARY=$CURL_ROOT/lib/libcurl.a -DCURL_INCLUDE_DIR=$CURL_ROOT/include  ..\n# cd iothub_client/tests/iothubclient_mqtt_e2e\n# cmake --build .\n# sudo -E su\n# setcap cap_net_raw,cap_net_admin+ep iothubclient_mqtt_e2e_exe\n# ./iothubclient_mqtt_e2e_exe\n# # END RUN THE E2E TEST\n", "num_lines": 137}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n###################################################################################################\n################################### PI E2E TEST SETUP GUIDE #######################################\n###################################################################################################\n# This is a guide to setting up you raspberry pi to run E2E tests. Essentially all this stuff is \n# creating the proper toolchain including upgrading cURL to the latest version so that the\n# C Client Library can be able to use cURL without any issues like running out of memory. \n# \n# TO RUN THIS SCRIPT:\n# Get a Raspberry Pi and flash the SD card with Stretch. \n# This script has been tested to work on a brand new Install of Stretch. Don't use it if you care\n# about if your Stretch Image becomes unusable or not. Because it's messing with the curl stuff, \n# it might make things unusable... but it also probably won't. Still be cautious.   \n###################################################################################################\n###################################################################################################\n\nMYDIR=\"$(dirname \"$0\")\"\n\n# ENABLE SSH BY DEFAULT \nif ! grep -Fxq \"systemctl start ssh\" /etc/rc.local\nthen\n    echo 'Enabling automatic start of ssh on bootup...'\n    #insert systemctl start ssh onto the 19th line of /etc/rc.local\n    sudo sed -i '19i\\systemctl start ssh' /etc/rc.local\n    # code if not found\nfi\n# END ENABLE SSH BY DEFAULT\n\n# GET NECESSARY PACKAGES\nsudo apt-get update -y\nsudo apt-get install -y vim git build-essential pkg-config git cmake libssl-dev uuid-dev valgrind\n\n###################################################################################################\n# DOWNLOAD AND INSTALL LINUX AGENT\n# FOR WALKTHROUGH: https://docs.microsoft.com/azure/devops/pipelines/agents/v2-linux?view=azure-devops\n# NOTE: You need a Azure DevOps PAT Token. Described in the link above. \n###################################################################################################\ncd ~\nwget https://vstsagentpackage.azureedge.net/agent/2.150.0/vsts-agent-linux-arm-2.150.0.tar.gz\nmkdir myagent && cd myagent\nif [[ $? -ne 0 ]]; then\n    echo \"myagent already created, overwriting\"\n    rm -r myagent && mkdir myagent && cd myagent\nfi\ntar zxvf ~/vsts-agent-linux-arm-2.150.0.tar.gz\n# Config will prompt for name of pool and PAT. \n./config.sh\n./run.sh\ncd ~ \n\n# ###################################################################################################\n# # CREATE SYSTEMD SERVICE: devops\n# # Installing the agent as a systemd service.\n# # This needs a manual step of creating the devops-enviroment file in /etc/\n# # Look at the template devops-environment to figure out the necessary credentials\n# ###################################################################################################\n\n\nsudo cp devops.service /lib/systemd/system/devops.service\nmkdir -p \"/home/pi/devops-logs\" && touch \"/home/pi/devops-logs/devopsagent.log\"\n\n# This step redirects the journalctl logs for devops.service to a user log file.\necho \"CREATE DEVOPSAGENT.CONF\"\ntouch /etc/rsyslog.d/devopsagent.conf\necho \"if $programname == '<your program identifier>' then /home/pi/devops-logs/devopsagent.log\" >> /etc/rsyslog.d/devopsagent.conf\necho \"& stop\" >> /etc/rsyslog.d/devopsagent.conf\nsudo chown root:adm /home/pi/devops-logs/devopsagent.log\n\necho \"NOTE: USER INPUT NECESSARY!\"\necho \"add credentials to devops-environment, then copy to /etc/devops-environment\"\necho \"Once you have added /etc/devops-environment file, run:\"\necho \"sudo systemctl daemon-reload\"\n\nread -r -p \"Have you added your credentials to the devops_service.sh file? [y/N] \" response\nif [[ \"$response\" =~ ^([yY][eE][sS]|[yY])+$ ]]\nthen\n    echo \"copying devops_service.sh to /home/pi/myagent/\"\n    cp $MYDIR/devops_service.sh /home/pi/myagent/devops_service.sh\nelse\n    echo \"Before you can run the daemon you must update your credentials.\"\n    echo \"Once the credentials have been updated then copy devops_service into myagent:\"\n    echo 'cp $MYDIR/devops_service.sh /home/pi/myagent/devops_service.sh'\nfi\n\n\n###################################################################################################\n# INSTALL NEWEST VERSION OF CURL AND POINT TO THE NEW CURL LIBRARY\n###################################################################################################\nif ! grep -Fxq \"LD_LIBRARY_PATH\" ~/.bashrc\nthen \n    echo 'export LD_LIBRARY_PATH'\n    echo 'export LD_LIBRARY_PATH=/usr/local/lib' >> ~/.bashrc\nfi\n\nprintf 'Setting variables by calling bashrc'\nsource ~/.bashrc\n[ $? -eq 0 ] || { echo \"bashrc source failed\"; exit 1; }\n\n# Install curl new version\nwget https://curl.haxx.se/download/curl-7.64.1.tar.gz\n\ntar -xzvf curl-7.64.1.tar.gz\ncd curl_source/curl-7.64.1/\n./configure --without-zlib --with-ssl\nmake -j\nsudo make install\n\nsudo ln -sf /usr/local/bin/curl /usr/bin/curl\n\necho \"Now you can run the cross compiled E2E tests!\"\n\n\n# ###################################################################################################\n# # UNCOMMENT THE BELOW LINES AND COMMENT OUT THE CURL INSTALL LINES ABOVE IF YOU WANT TO\n# # COMPILE THE SDK ON THE DEVICE AND RUN THE E2E TESTS\n# ###################################################################################################\n# # check if CURL_ROOT is already a variable set in bashrc...\n# if ! grep -Fxq \"CURL_ROOT\" ~/.bashrc\n# then\n#     printf 'Exporting variable CURL_ROOT...'\n#     echo 'export CURL_ROOT=/home/pi/curl_install' >> ~/.bashrc \n#     source ~/.bashrc\n#     # code if not found\n# fi\n\n# if ! grep -Fxq \"LD_LIBRARY_PATH\" ~/.bashrc\n# then \n#     echo 'export LD_LIBRARY_PATH'\n#     echo 'export LD_LIBRARY_PATH=$CURL_ROOT/lib' >> ~/.bashrc\n# fi\n\n# printf 'Setting variables by calling bashrc'\n# source ~/.bashrc\n# [ $? -eq 0 ] || { echo \"bashrc source failed\"; exit 1; }\n\n\n# # BUILD AND INSTALL NEW CURL TO CURL_ROOT\n# # We are commenting this out because it's useful info to have \n# # but for the E2E tests it works when CURL is installed directly on the device.\n# wget https://curl.haxx.se/download/curl-7.64.1.tar.gz\n# mkdir $CURL_ROOT\n# mkdir curl_source\n# tar -C curl_source -xzvf curl-7.64.1.tar.gz\n# cd curl_source/curl-7.64.1/\n# ./configure --prefix=$CURL_ROOT --disable-shared --without-zlib --with-ssl --enable-static\n# make -j\n# sudo make install\n\n# # END GET NECESARY PACKAGES \n\n# # BUILD THE SDK\n# cd ~\n# git clone https://github.com/Azure/azure-iot-sdk-c\n# git submodule update --init\n# cd azure-iot-sdk-c\n# if [ -d cmake ]   # for file \"if [-f /home/rama/file]\" \n# then \n#     echo \"cmake present\"\n#     rm -rf cmake \n# else\n#     echo \"cmake not present\"\n# fi\n# mkdir cmake && cd cmake\n# cmake -Drun_unittests=ON -Drun_e2e_tests=ON -DCMAKE_BUILD_TYPE=Debug -DCURL_LIBRARY=$CURL_ROOT/lib/libcurl.a -DCURL_INCLUDE_DIR=$CURL_ROOT/include  ..\n# cd iothub_client/tests/iothubclient_mqtt_e2e\n# cmake --build .\n# sudo -E su\n# setcap cap_net_raw,cap_net_admin+ep iothubclient_mqtt_e2e_exe\n# ./iothubclient_mqtt_e2e_exe\n# # END RUN THE E2E TEST\n\n\n", "num_lines": 176}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# basic setup of input script for python, execution steps are as follows:\n# 1. wait until device flashing complete, then send help\n# 2. set the IoT Hub Connection String\n# 3. call exit, resetting the device to ensure mxchip connects to the set IoT Hub\n# 4. call SERIAL_TASK, typically send_telemetry\n# 5. call version, to log versions of software on device\n\necho -e \"\\r\\n\\r\\nexit\\r\\n$SERIAL_TASK\\r\\n\\r\\nversion\" | cat > input.txt\n", "num_lines": 15}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# basic setup of input script for python, execution steps are as follows:\n# 1. wait until device flashing complete, then send help\n# 2. set the IoT Hub Connection String\n# 3. call exit, resetting the device to ensure mxchip connects to the set IoT Hub\n# 4. call SERIAL_TASK, typically send_telemetry\n# 5. call version, to log versions of software on device\n\necho -e \"help\\r\\nset_wifissid $WIFI_SSID\\r\\nset_wifipwd $WIFI_PWD\\r\\nset_az_iothub $IOTHUB_CONNECTION_STRING\\r\\nexit\\r\\n$SERIAL_TASK\\r\\n\\r\\nversion\" | cat > input.txt\n", "num_lines": 15}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\ncat >setup.txt <<EOL\n$RASPI_USER\n$RASPI_PWD\n\nexport IOTHUB_CONNECTION_STRING=\"$IOTHUB_CONNECTION_STRING\"\nexport IOTHUB_EVENTHUB_CONNECTION_STRING=\"$IOTHUB_EVENTHUB_CONNECTION_STRING\"\nexport IOTHUB_PARTITION_COUNT=16\nexport IOTHUB_E2E_X509_CERT_BASE64=\"$IOTHUB_E2E_X509_CERT_BASE64\"\nexport IOTHUB_E2E_X509_PRIVATE_KEY_BASE64=\"$IOTHUB_E2E_X509_PRIVATE_KEY_BASE64\"\nexport IOTHUB_E2E_X509_THUMBPRINT=$IOTHUB_E2E_X509_THUMBPRINT\nexport IOTHUB_POLICY_KEY=$IOTHUB_POLICY_KEY\n\nexport IOT_DPS_CONNECTION_STRING=\"$IOT_DPS_CONNECTION_STRING\"\nexport IOT_DPS_ID_SCOPE=$IOT_DPS_ID_SCOPE\nexport IOTHUB_CA_ROOT_CERT=$IOTHUB_CA_ROOT_CERT\nexport IOTHUB_CA_ROOT_CERT_KEY=$IOTHUB_CA_ROOT_CERT_KEY\nexport IOT_DPS_GLOBAL_ENDPOINT=\"$IOT_DPS_GLOBAL_ENDPOINT\"\nexport IOTHUB_DEVICE_CONN_STRING_INVALIDCERT=\"$IOTHUB_DEVICE_CONN_STRING_INVALIDCERT\"\nexport IOTHUB_CONN_STRING_INVALIDCERT=\"$IOTHUB_CONN_STRING_INVALIDCERT\"\nexport DPS_GLOBALDEVICEENDPOINT_INVALIDCERT=\"$DPS_GLOBALDEVICEENDPOINT_INVALIDCERT\"\nexport PROVISIONING_CONNECTION_STRING_INVALIDCERT=\"$PROVISIONING_CONNECTION_STRING_INVALIDCERT\"\n\nEOL\n", "num_lines": 30}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\nset -e\n\n# basic setup of input script for python\necho -e \"rm $RASPI_TEST_FILE\\nrm e2e_clone\\nsz -a $RASPI_TEST_FILE > $RASPI_PORT < $RASPI_PORT\\n\\ncp $RASPI_TEST_FILE e2e_clone\\n./e2e_clone\\n\\n$RASPI_SERIAL_TASK\\n\\n\" | cat > input.txt\n", "num_lines": 9}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n## Copyright (c) Microsoft. All rights reserved.\n## Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n###############################################################################\n# This script demonstrates creating X.509 certificates for an Azure IoT Hub\n# CA Cert deployment.\n#\n# These certs MUST NOT be used in production.  It is expected that production\n# certificates will be created using a company's proper secure signing process.\n# These certs are intended only to help demonstrate and prototype CA certs.\n###############################################################################\n\nset -x # Set trace on\nset -o errexit # Exit if command failed\nset -o pipefail # Exit if pipe failed\n\nroot_ca_dir=\".\"\nhome_dir=\".\"\nalgorithm=\"genrsa\"\nCOUNTRY=\"US\"\nSTATE=\"WA\"\nLOCALITY=\"Redmond\"\nORGANIZATION_NAME=\"My Organization\"\nroot_ca_password=\"1234\"\nkey_bits_length=\"4096\"\ndays_till_expire=30\nca_chain_prefix=\"azure-iot-test-only.chain.ca\"\nintermediate_ca_dir=\".\"\nopenssl_root_config_file=\"./openssl_root_ca.cnf\"\nopenssl_intermediate_config_file=\"./openssl_device_intermediate_ca.cnf\"\nintermediate_ca_password=\"1234\"\nroot_ca_prefix=\"azure-iot-test-only.root.ca\"\nintermediate_ca_prefix=\"azure-iot-test-only.intermediate\"\n\nfunction makeCNsubject()\n{\n    local result=\"/CN=${1}\"\n    case $OSTYPE in win32) result=\"/${result}\"\n    esac\n    echo \"$result\"\n}\n\nfunction warn_certs_not_for_production()\n{\n    [ ! -z \"$TERM\" ] && tput smso\n    [ ! -z \"$TERM\" ] && tput setaf 3\n    echo \"Certs generated by this script are not for production (e.g. they have hard-coded passwords of '1234'.\"\n    echo \"This script is only to help you understand Azure IoT Hub CA Certificates.\"\n    echo \"Use your official, secure mechanisms for this cert generation.\"\n    echo \"Also note that these certs will expire in ${days_till_expire} days.\"\n    [ ! -z \"$TERM\" ] && tput sgr0\n}\n\nfunction generate_root_ca()\n{\n    local common_name=\"Azure IoT Hub CA Cert Test Only\"\n    local password_cmd=\" -aes256 -passout pass:${root_ca_password} \"\n\n    cd \"${home_dir}\"\n    echo \"Creating the Root CA Private Key\"\n\n    openssl \"${algorithm}\" \\\n            ${password_cmd} \\\n            -out \"${root_ca_dir}/private/${root_ca_prefix}.key.pem\" \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 400 \"${root_ca_dir}/private/${root_ca_prefix}.key.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Creating the Root CA Certificate\"\n    password_cmd=\" -passin pass:${root_ca_password} \"\n\n    openssl req \\\n            -new \\\n            -x509 \\\n            -config \"${openssl_root_config_file}\" \\\n            ${password_cmd} \\\n            -key \"${root_ca_dir}/private/${root_ca_prefix}.key.pem\" \\\n            -subj \"$(makeCNsubject \"${common_name}\")\" \\\n            -days ${days_till_expire} \\\n            -sha256 \\\n            -extensions v3_ca \\\n            -out \"${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n    chmod 444 \"${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"CA Root Certificate Generated At:\"\n    echo \"---------------------------------\"\n    echo \"    ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in \"${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\"\n\n    warn_certs_not_for_production\n\n    [ $? -eq 0 ] || exit $?\n}\n\n\n\n###############################################################################\n# Generate Intermediate CA Cert\n###############################################################################\nfunction generate_intermediate_ca()\n{\n    local common_name=\"Azure IoT Hub Intermediate Cert Test Only\"\n\n    local password_cmd=\" -aes256 -passout pass:${intermediate_ca_password} \"\n    echo \"Creating the Intermediate Device CA\"\n    echo \"-----------------------------------\"\n    cd \"${home_dir}\"\n\n    openssl \"${algorithm}\" \\\n            ${password_cmd} \\\n            -out \"${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem\" \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 400 \"${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem\"\n    [ $? -eq 0 ] || exit $?\n\n\n    echo \"Creating the Intermediate Device CA CSR\"\n    echo \"-----------------------------------\"\n    password_cmd=\" -passin pass:${intermediate_ca_password} \"\n\n    openssl req -new -sha256 \\\n        ${password_cmd} \\\n        -config \"${openssl_intermediate_config_file}\" \\\n        -subj \"$(makeCNsubject \"${common_name}\")\" \\\n        -key \"${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem\" \\\n        -out \"${intermediate_ca_dir}/csr/${intermediate_ca_prefix}.csr.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Signing the Intermediate Certificate with Root CA Cert\"\n    echo \"-----------------------------------\"\n    password_cmd=\" -passin pass:${root_ca_password} \"\n\n    openssl ca -batch \\\n        -config \"${openssl_root_config_file}\" \\\n        ${password_cmd} \\\n        -extensions v3_intermediate_ca \\\n        -days ${days_till_expire} -notext -md sha256 \\\n        -in \"${intermediate_ca_dir}/csr/${intermediate_ca_prefix}.csr.pem\" \\\n        -out \"${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n    chmod 444 \"${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Verify signature of the Intermediate Device Certificate with Root CA\"\n    echo \"-----------------------------------\"\n    openssl verify \\\n            -CAfile \"${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\" \\\n            \"${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Intermediate CA Certificate Generated At:\"\n    echo \"-----------------------------------------\"\n    echo \"    ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in \"${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Create Root + Intermediate CA Chain Certificate\"\n    echo \"-----------------------------------\"\n    cat \"${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\" \\\n        \"${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\" > \\\n        \"${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n    chmod 444 \"${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Root + Intermediate CA Chain Certificate Generated At:\"\n    echo \"------------------------------------------------------\"\n    echo \"    ${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\"\n\n    warn_certs_not_for_production\n}\n\n###############################################################################\n# Generate a Certificate for a device using specific openssl extension and\n# signed with either the root or intermediate cert.\n###############################################################################\nfunction generate_device_certificate_common()\n{\n    local common_name=\"${1}\"\n    local device_prefix=\"${2}\"\n    local certificate_dir=\"${3}\"\n    local ca_password=\"${4}\"\n    local server_pfx_password=\"1234\"\n    local password_cmd=\" -passin pass:${ca_password} \"\n    local openssl_config_file=\"${5}\"\n    local openssl_config_extension=\"${6}\"\n    local cert_type_diagnostic=\"${7}\"\n\n    echo \"Creating ${cert_type_diagnostic} Certificate\"\n    echo \"----------------------------------------\"\n    cd \"${home_dir}\"\n\n    openssl \"${algorithm}\" \\\n            -out \"${certificate_dir}/private/${device_prefix}.key.pem\" \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 444 \"${certificate_dir}/private/${device_prefix}.key.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Create the ${cert_type_diagnostic} Certificate Request\"\n    echo \"----------------------------------------\"\n    openssl req -config \"${openssl_config_file}\" \\\n        -key \"${certificate_dir}/private/${device_prefix}.key.pem\" \\\n        -subj \"$(makeCNsubject \"${common_name}\")\" \\\n        -new -sha256 -out \"${certificate_dir}/csr/${device_prefix}.csr.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    openssl ca -batch -config \"${openssl_config_file}\" \\\n            ${password_cmd} \\\n            -extensions \"${openssl_config_extension}\" \\\n            -days ${days_till_expire} -notext -md sha256 \\\n            -in \"${certificate_dir}/csr/${device_prefix}.csr.pem\" \\\n            -out \"${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n    chmod 444 \"${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Verify signature of the ${cert_type_diagnostic}\" \\\n         \" certificate with the signer\"\n    echo \"-----------------------------------\"\n    openssl verify \\\n            -CAfile \"${certificate_dir}/certs/${ca_chain_prefix}.cert.pem\" \\\n            \"${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n\n    echo \"${cert_type_diagnostic} Certificate Generated At:\"\n    echo \"----------------------------------------\"\n    echo \"    ${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in \"${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    [ $? -eq 0 ] || exit $?\n    echo \"Create the ${cert_type_diagnostic} PFX Certificate\"\n    echo \"----------------------------------------\"\n    openssl pkcs12 -in \"${certificate_dir}/certs/${device_prefix}.cert.pem\" \\\n            -inkey \"${certificate_dir}/private/${device_prefix}.key.pem\" \\\n            -password pass:${server_pfx_password} \\\n            -export -out \"${certificate_dir}/certs/${device_prefix}.cert.pfx\"\n    [ $? -eq 0 ] || exit $?\n    echo \"${cert_type_diagnostic} PFX Certificate Generated At:\"\n    echo \"--------------------------------------------\"\n    echo \"    ${certificate_dir}/certs/${device_prefix}.cert.pfx\"\n    [ $? -eq 0 ] || exit $?\n}\n\n###############################################################################\n# Generate a certificate for a leaf device\n# signed with either the root or intermediate cert.\n###############################################################################\nfunction generate_leaf_certificate()\n{\n    local common_name=\"${1}\"\n    local device_prefix=\"${2}\"\n    local certificate_dir=\"${3}\"\n    local ca_password=\"${4}\"\n    local openssl_config_file=\"${5}\"\n\n    generate_device_certificate_common \"${common_name}\" \"${device_prefix}\" \\\n                                       \"${certificate_dir}\" \"${ca_password}\" \\\n                                       \"${openssl_config_file}\" \"usr_cert\" \\\n                                       \"Leaf Device\"\n}\n\n###############################################################################\n#  Creates required directories and removes left over cert files.\n#  Run prior to creating Root CA; after that these files need to persist.\n###############################################################################\nfunction prepare_filesystem()\n{\n    if [ ! -f ${openssl_root_config_file} ]; then\n        echo \"Missing file ${openssl_root_config_file}\"\n        exit 1\n    fi\n\n    if [ ! -f ${openssl_intermediate_config_file} ]; then\n        echo \"Missing file ${openssl_intermediate_config_file}\"\n        exit 1\n    fi\n\n    rm -rf csr\n    rm -rf private\n    rm -rf certs\n    rm -rf intermediateCerts\n    rm -rf newcerts\n\n    mkdir -p csr\n    mkdir -p private\n    mkdir -p certs\n    mkdir -p intermediateCerts\n    mkdir -p newcerts\n\n    rm -f ./index.txt\n    touch ./index.txt\n\n    rm -f ./serial\n    echo 01 > ./serial\n}\n\n###############################################################################\n# Generates a root and intermediate certificate for CA certs.\n###############################################################################\nfunction initial_cert_generation()\n{\n    prepare_filesystem\n    generate_root_ca\n    generate_intermediate_ca\n}\n\n###############################################################################\n# Generates a certificate for verification, chained directly to the root.\n###############################################################################\nfunction generate_verification_certificate()\n{\n    if [ -z $1 ]; then\n        echo \"Usage: create_verification_certificate <subjectName>\"\n        exit 1\n    fi\n\n    rm -f ./private/verification-code.key.pem\n    rm -f ./certs/verification-code.cert.pem\n    generate_leaf_certificate \"${1}\" \"verification-code\" \\\n                              \"${root_ca_dir}\" \"${root_ca_password}\" \\\n                              \"${openssl_root_config_file}\"\n}\n\n###############################################################################\n# Generates a certificate for a device, chained directly to the root.\n###############################################################################\nfunction generate_device_certificate()\n{\n    if [ -z $1 ]; then\n        echo \"Usage: create_device_certificate <subjectName>\"\n        exit 1\n    fi\n\n    rm -f ./private/new-device.key.pem\n    rm -f ./certs/new-device.key.pem\n    rm -f ./certs/new-device-full-chain.cert.pem\n    generate_leaf_certificate \"${1}\" \"new-device\" \\\n                              \"${root_ca_dir}\" \"${root_ca_password}\" \\\n                              \"${openssl_root_config_file}\"\n}\n\n\n###############################################################################\n# Generates a certificate for a device, chained to the intermediate.\n###############################################################################\nfunction generate_device_certificate_from_intermediate()\n{\n    if [ -z $1 ]; then\n        echo \"Usage: create_device_certificate_from_intermediate <subjectName>\"\n        exit 1\n    fi\n\n    rm -f ./private/new-device.key.pem\n    rm -f ./certs/new-device.key.pem\n    rm -f ./certs/new-device-full-chain.cert.pem\n    generate_leaf_certificate \"${1}\" \"new-device\" \\\n                              \"${intermediate_ca_dir}\" \"${intermediate_ca_password}\" \\\n                              \"${openssl_intermediate_config_file}\"\n}\n\n\n###############################################################################\n# Generates a certificate for a Edge device, chained to the intermediate.\n###############################################################################\nfunction generate_edge_device_certificate()\n{\n    local device_prefix=\"new-edge-device\"\n    if [ -z $1 ]; then\n        echo \"Usage: create_edge_device_certificate <subjectName>\"\n        exit 1\n    fi\n    rm -f ./private/new-edge-device.key.pem\n    rm -f ./certs/new-edge-device.cert.pem\n    rm -f ./certs/new-edge-device-full-chain.cert.pem\n\n    # Note: Appending a '.ca' to the common name is useful in situations\n    # where a user names their hostname as the edge device name.\n    # By doing so we avoid TLS validation errors where we have a server or\n    # client certificate where the hostname is used as the common name\n    # which essentially results in \"loop\" for validation purposes.\n    generate_device_certificate_common \"${1}.ca\" \\\n                                       \"${device_prefix}\" \\\n                                       \"${intermediate_ca_dir}\" \\\n                                       \"${intermediate_ca_password}\" \\\n                                       \"${openssl_intermediate_config_file}\" \\\n                                       \"v3_intermediate_ca\" \"Edge Device\"\n}\n\nset +x\nif [ \"${1}\" == \"create_root_and_intermediate\" ]; then\n    initial_cert_generation\nelif [ \"${1}\" == \"create_verification_certificate\" ]; then\n    generate_verification_certificate \"${2}\"\nelif [ \"${1}\" == \"create_device_certificate\" ]; then\n    generate_device_certificate \"${2}\"\nelif [ \"${1}\" == \"create_device_certificate_from_intermediate\" ]; then\n    generate_device_certificate_from_intermediate \"${2}\"\nelif [ \"${1}\" == \"create_edge_device_certificate\" ]; then\n    generate_edge_device_certificate \"${2}\"\nelse\n    echo \"Usage: create_root_and_intermediate                               # Creates a new root and intermediate certificates\"\n    echo \"       create_verification_certificate <subjectName>              # Creates a verification certificate, signed with <subjectName>\"\n    echo \"       create_device_certificate <subjectName>                    # Creates a device certificate signed by root with <subjectName>\"\n    echo \"       create_device_certificate_from_intermediate <subjectName>  # Creates a device certificate signed by intermediate with <subjectName>\"\n    echo \"       create_edge_device_certificate <subjectName>               # Creates an edge device certificate, signed with <subjectName>\"\n    exit 1\nfi\n\n\n\n\nwarn_certs_not_for_production\n", "num_lines": 425}
{"repo_name": "azure-iot-sdk-c", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\nIOTParametersFilePath=$1\n\nif test -z $IOTParametersFilePath\nthen\n\tIOTParametersFilePath=\"./iot_device_params.txt\"\nfi\n\necho \"Reading parameters from: $IOTParametersFilePath\"\n\nawk 'BEGIN {\n\tTargetFile=\"/etc/environment\"\n\n\tEnvVarsLength = 0;\n\n\twhile ((getline EnvStr < TargetFile) != 0)\n\t{\n\t\tEnvVarsLength++;\n\t\tEnvVars[EnvVarsLength] = EnvStr;\n\t}\n} {\n\tif (length($0) > 0 && substr($0, 1, 1) != \"#\")\n\t{\n\t\tprint \"Writing \" $0;\n\n\t\tif ((i = index($0, \"=\")) != 0)\n\t\t{\n\t\t\t# This gets the string including '='.\n\t\t\tName = substr($0, 1, i);\n\t\t\t# Value = substr($0, i + 1, length($0) - i + 1);\n\n\t\t\tEnvVarIsPresent = 0;\n\t\t\tNewIndex = 1;\n\t\t\tfor (i in EnvVars)\n\t\t\t{\n\t\t\t\tif (index(EnvVars[i], Name) != 0)\n\t\t\t\t{\n\t\t\t\t\tEnvVars[i] = $0;\n\t\t\t\t\tEnvVarIsPresent = 1;\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tNewIndex++;\n\t\t\t}\n\n\t\t\tif (EnvVarIsPresent == 0)\n\t\t\t{\n\t\t\t\tEnvVars[NewIndex] = $0;\n\t\t\t\tEnvVarsLength = NewIndex;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tEnvVarsLength = NewIndex - 1;\n\t\t\t}\n\t\t}\n\t}\n} END {\n        system(\"mv \" TargetFile \" \" TargetFile \".bkp\")\n\n        for (i = 1; i <= EnvVarsLength; i++)\n        {\n\t\t\tprint EnvVars[i] >> TargetFile;\n        }\n\t\t\n\t\tprint \"Writing Environment Variable Complete\"\n}' $IOTParametersFilePath\n\n", "num_lines": 68}
{"repo_name": "azure-iot-sdk-csharp", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nLOG_INFO=\"\\x1b[33;42;1m[INFO]:\\x1b[0m\"\nLOG_TODO=\"\\x1b[37;43;1m[TODO]:\\x1b[0m\"\nLOG_ERR=\"\\x1b[33;41;1m[ERROR]:\\x1b[0m\"\n\necho \"============\"\necho \"Start Docker\"\necho \"============\"\necho \"running from $(pwd)\"\nsudo service docker start\n\necho \"========================\"\necho \"Extract self-signed cert\"\necho \"========================\"\nPROXY_CERT_ZFILE=\"./haproxy/haproxy.bin\"\nPROXY_CERT_FILE=\"./haproxy/haproxy.pem\"\nif [ -f \"$PROXY_CERT_FILE\" ];\nthen\n\techo -e \"$LOG_INFO Use existing Proxy Service Cert found.\"\nelif [ -f \"$PROXY_CERT_ZFILE\" ];\nthen\n\tgzip -d -N -k -q -S \".bin\" ./haproxy/haproxy.bin\n\techo -e \"$LOG_INFO Proxy Service Cert extracted.\"\nelse\n\techo -e \"$LOG_ERR Missing Proxy Service Cert! Check your repo.\"\n\texit\nfi\n\necho \"===============\"\necho \"Inspect network\"\necho \"===============\"\nip -4 addr\nCVTEST_HOST_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_HOST_NETWORK=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+/*\\d.')\nCVTEST_HOST_SUBNET=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | grep -Po '[\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3}')\nCVTEST_HOST_SUBNET_MASK=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+/*\\d.' | grep -Po '/[\\d]{1,2}')\nCVTEST_CONTAINER_GW=$(ip -4 addr show docker0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_HOST_WSL_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_ROUTE_NET=$(route -n | grep 'eth0' | grep -v 'UG' | awk -F\" \" '{print $1}' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4\"/29\"}')\nCVTEST_TST_NET=$CVTEST_HOST_NETWORK\nCVTEST_GDE_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+3}')\nCVTEST_DPS_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+4}')\nCVTEST_HUB_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+5}')\necho \"HOST=$CVTEST_HOST_IP\"\necho \"HOST NETWORK=$CVTEST_HOST_NETWORK\"\necho \"HOST SUBNET=$CVTEST_HOST_SUBNET\"\necho \"HOST SUBNET MASK=$CVTEST_HOST_SUBNET_MASK\"\necho \"Container GW=$CVTEST_CONTAINER_GW\"\necho \"WSL=$CVTEST_HOST_WSL_IP\"\necho \"Container NET=$CVTEST_TST_NET\"\necho \"Container GDE=$CVTEST_GDE_IP\"\necho \"Container DPS=$CVTEST_DPS_IP\"\necho \"Container HUB=$CVTEST_HUB_IP\"\nping -c 2 $CVTEST_HOST_IP\n\necho \"====================\"\necho \"Setup docker network\"\necho \"====================\"\ndocker images\ndocker ps -a\ndocker stop invalid-gde invalid-dps invalid-hub e2etest-tpm e2etest-pxy\ndocker rm invalid-gde invalid-dps invalid-hub e2etest-tpm e2etest-pxy\ndocker network rm testnet\ndocker network create -d ipvlan --subnet=$CVTEST_TST_NET -o ipvlan_mode=l2 -o parent=eth0 testnet\ndocker network ls\n\necho \"======================\"\necho \"Setup docker instances\"\necho \"======================\"\nAZURE_ACR_TOKEN=$(az acr login -n aziotacr -t --output tsv --query accessToken)\necho $AZURE_ACR_TOKEN | docker login aziotacr.azurecr.io --username 00000000-0000-0000-0000-000000000000 --password-stdin\ndocker run -h invalidcertgde1.westus.cloudapp.azure.com --name invalid-gde --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_GDE_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxygde.cfg\ndocker run -h invalidcertdps1.westus.cloudapp.azure.com --name invalid-dps --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_DPS_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxydps.cfg\ndocker run -h invalidcertiothub1.westus.cloudapp.azure.com --name invalid-hub --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_HUB_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxyhub.cfg\ndocker run --name e2etest-tpm -p 127.0.0.1:2321:2321 -p 127.0.0.1:2322:2322 -d aziotacr.azurecr.io/aziotbld/testtpm\ndocker run --name e2etest-pxy -p 127.0.0.1:8888:8888 -d aziotacr.azurecr.io/aziotbld/testproxy\n\necho \"=================\"\necho \"Inspect instances\"\necho \"=================\"\ndocker ps -a\n\necho \"========================================================\"\necho -e \"$LOG_TODO update host file for local E2E Tests\"\necho \"        (on your host Windows OS)\"\necho \"        add/update hosts file with the following entries\"\necho \"        (at C:\\Windows\\System32\\drivers\\etc\\hosts)\"\necho \"========================================================\"\necho \"$(docker inspect invalid-gde | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertgde1.westus.cloudapp.azure.com\"\necho \"$(docker inspect invalid-dps | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertdps1.westus.cloudapp.azure.com\"\necho \"$(docker inspect invalid-hub | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertiothub1.westus.cloudapp.azure.com\"\n", "num_lines": 92}
{"repo_name": "azure-iot-sdk-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nLOG_INFO=\"\\x1b[33;42;1m[INFO]:\\x1b[0m\"\nLOG_TODO=\"\\x1b[37;43;1m[TODO]:\\x1b[0m\"\nLOG_ERR=\"\\x1b[33;41;1m[ERROR]:\\x1b[0m\"\n\necho \"============\"\necho \"Start Docker\"\necho \"============\"\necho \"running from $(pwd)\"\nsudo service docker start\n\necho \"========================\"\necho \"Extract self-signed cert\"\necho \"========================\"\nPROXY_CERT_ZFILE=\"./haproxy/haproxy.bin\"\nPROXY_CERT_FILE=\"./haproxy/haproxy.pem\"\nif [ -f \"$PROXY_CERT_FILE\" ];\nthen\n\techo -e \"$LOG_INFO Use existing Proxy Service Cert found.\"\nelif [ -f \"$PROXY_CERT_ZFILE\" ];\nthen\n\tgzip -d -N -k -q -S \".bin\" ./haproxy/haproxy.bin\n\techo -e \"$LOG_INFO Proxy Service Cert extracted.\"\nelse\n\techo -e \"$LOG_ERR Missing Proxy Service Cert! Check your repo.\"\n\texit\nfi\n\necho \"===============\"\necho \"Inspect network\"\necho \"===============\"\nip -4 addr\nCVTEST_HOST_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_HOST_NETWORK=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+/*\\d.')\nCVTEST_HOST_SUBNET=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | grep -Po '[\\d]{1,3}.[\\d]{1,3}.[\\d]{1,3}')\nCVTEST_HOST_SUBNET_MASK=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+/*\\d.' | grep -Po '/[\\d]{1,2}')\nCVTEST_CONTAINER_GW=$(ip -4 addr show docker0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_HOST_WSL_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+')\nCVTEST_ROUTE_NET=$(route -n | grep 'eth0' | grep -v 'UG' | awk -F\" \" '{print $1}' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4\"/29\"}')\nCVTEST_TST_NET=$CVTEST_HOST_NETWORK\nCVTEST_GDE_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+3}')\nCVTEST_DPS_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+4}')\nCVTEST_HUB_IP=$(ip -4 addr show eth0 | grep -Po 'inet \\K[\\d.]+' | awk -F\".\" '{print $1\".\"$2\".\"$3\".\"$4+5}')\necho \"HOST=$CVTEST_HOST_IP\"\necho \"HOST NETWORK=$CVTEST_HOST_NETWORK\"\necho \"HOST SUBNET=$CVTEST_HOST_SUBNET\"\necho \"HOST SUBNET MASK=$CVTEST_HOST_SUBNET_MASK\"\necho \"Container GW=$CVTEST_CONTAINER_GW\"\necho \"WSL=$CVTEST_HOST_WSL_IP\"\necho \"Container NET=$CVTEST_TST_NET\"\necho \"Container GDE=$CVTEST_GDE_IP\"\necho \"Container DPS=$CVTEST_DPS_IP\"\necho \"Container HUB=$CVTEST_HUB_IP\"\nping -c 2 $CVTEST_HOST_IP\n\necho \"====================\"\necho \"Setup docker network\"\necho \"====================\"\ndocker images\ndocker ps -a\ndocker stop invalid-gde invalid-dps invalid-hub e2etest-tpm e2etest-pxy\ndocker rm invalid-gde invalid-dps invalid-hub e2etest-tpm e2etest-pxy\ndocker network rm testnet\ndocker network create -d ipvlan --subnet=$CVTEST_TST_NET -o ipvlan_mode=l2 -o parent=eth0 testnet\ndocker network ls\n\necho \"======================\"\necho \"Setup docker instances\"\necho \"======================\"\nAZURE_ACR_TOKEN=$(az acr login -n aziotacr -t --output tsv --query accessToken)\necho $AZURE_ACR_TOKEN | docker login aziotacr.azurecr.io --username 00000000-0000-0000-0000-000000000000 --password-stdin\ndocker run -h invalidcertgde1.westus.cloudapp.azure.com --name invalid-gde --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_GDE_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxygde.cfg\ndocker run -h invalidcertdps1.westus.cloudapp.azure.com --name invalid-dps --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_DPS_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxydps.cfg\ndocker run -h invalidcertiothub1.westus.cloudapp.azure.com --name invalid-hub --expose=443 --expose=5671 --expose=8883 --network=testnet --ip=$CVTEST_HUB_IP -v $(pwd)/haproxy:/usr/local/etc/haproxy:ro -d aziotacr.azurecr.io/haproxy haproxy -f /usr/local/etc/haproxy/haproxyhub.cfg\ndocker run --name e2etest-tpm -p 127.0.0.1:2321:2321 -p 127.0.0.1:2322:2322 -d aziotacr.azurecr.io/aziotbld/testtpm\ndocker run --name e2etest-pxy -p 127.0.0.1:8888:8888 -d aziotacr.azurecr.io/aziotbld/testproxy\n\necho \"=================\"\necho \"Inspect instances\"\necho \"=================\"\ndocker ps -a\n\necho \"========================================================\"\necho -e \"$LOG_TODO update host file for local E2E Tests\"\necho \"        (on your host Windows OS)\"\necho \"        add/update hosts file with the following entries\"\necho \"        (at C:\\Windows\\System32\\drivers\\etc\\hosts)\"\necho \"========================================================\"\necho \"$(docker inspect invalid-gde | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertgde1.westus.cloudapp.azure.com\"\necho \"$(docker inspect invalid-dps | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertdps1.westus.cloudapp.azure.com\"\necho \"$(docker inspect invalid-hub | grep -Po -m 1 '\"IPAddress\": \"\\K[\\d.]+') invalidcertiothub1.westus.cloudapp.azure.com\"\n", "num_lines": 92}
{"repo_name": "azure-iot-sdk-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This APK file is generated by the Android build task and then is copied into the android test run task. If the APK file\n# is missing, then either the copy failed, or the APK was never successfully built.\nif [ ! -f \"iot-e2e-tests/android/app/build/outputs/apk/debug/app-debug.apk\" ]; then\n    echo 'Missing expected apk file. Android build task likely failed silently.'\n    exit -1\nfi\n\nif [ ! -f \"iot-e2e-tests/android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk\" ]; then\n    echo 'Missing expected apk file. Android build task likely failed silently.'\n    exit -1\nfi\n\n# -e flag to force this command to run on what should be the only emulator active on this machine\necho 'Installing APKs on emulator'\nadb -e install -r iot-e2e-tests/android/app/build/outputs/apk/debug/app-debug.apk\nadb -e install -r iot-e2e-tests/android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk\n\n#List instrumentation classes, for logging purposes only\necho 'Listing available instrumentations:'\nadb -e shell pm list instrumentation\necho ''\n\nannotationString=\"com.microsoft.azure.sdk.iot.android.helper.${TEST_GROUP_ID}\"\necho 'Running android tests with annotation'\necho $annotationString\n\n#Return code from adb shell isn't returned as one would expect. Need to capture output logs and analyze them to determine if this test run was a success or not\nTestLogs=$(adb -e shell am instrument -w -e annotation $annotationString com.iothub.azure.microsoft.com.androide2e.test/android.support.test.runner.AndroidJUnitRunner)\n\necho 'Result of running tests'\necho \"$TestLogs\"\n\n#This string is always present in the output logs from android testing if a test failed. Hacky, but there is no return code\n# to check instead.\nFailureMessage='FAILURES!!!'\n\nif grep -q \"$FailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Test failures detected, exiting...'\n    exit -1\nfi\n\nInstrumentationFailureMessage='INSTRUMENTATION_STATUS_CODE: -1'\n\nif grep -q \"$InstrumentationFailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Instrumentation failures detected, exiting...'\n    exit -1\nfi\n\nAnotherInstrumentationFailureMessage='INSTRUMENTATION_FAILED'\nif grep -q \"$AnotherInstrumentationFailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Instrumentation failures detected, exiting...'\n    exit -1\nfi\n\n# adb also supports running all tests that do not have a given annotation\n# adb -e shell am instrument -w -e notAnnotation com.microsoft.azure.sdk.iot.android.helper.TestGroup39 com.iothub.azure.microsoft.com.androide2e.test/android.support.test.runner.AndroidJUnitRunner", "num_lines": 58}
{"repo_name": "azure-iot-sdk-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho 'Listing available android sdks for installation'\n$ANDROID_HOME/tools/bin/sdkmanager --list | grep system-images\n\nemulatorImage='system-images;android-28;google_apis;x86_64'\navdName='Pixel_9.0'\n\necho ''\necho \"Installing emulator image ${emulatorImage}\"\necho \"y\" | $ANDROID_HOME/tools/bin/sdkmanager --install $emulatorImage\n\necho ''\necho \"Creating android emulator with name ${avdName}\"\necho \"no\" | $ANDROID_HOME/tools/bin/avdmanager create avd -n $avdName -k $emulatorImage --force\n\necho ''\necho 'Listing active android emulators'\n$ANDROID_HOME/emulator/emulator -list-avds\n\necho ''\necho \"Starting emulator in background thread\"\nnohup $ANDROID_HOME/emulator/emulator -avd $avdName -gpu auto -no-snapshot > /dev/null 2>&1 &\n\necho ''\necho 'Waiting for emulator to boot up...'\n$ANDROID_HOME/platform-tools/adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed | tr -d '\\r') ]]; do sleep 1; done; input keyevent 82'\necho ''\necho \"Emulator started\"\n\n$ANDROID_HOME/platform-tools/adb devices\n\n", "num_lines": 33}
{"repo_name": "azure-iot-sdk-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nwhich az > /dev/null 2>&1\nif [ $? -ne 0 ]; then\n   printf \"Azure CLI must be installed and added to PATH\\n\"\n   exit 1\nfi\nset -e\n\nfunction usage {\n    printf \"usage: $0 [flags]\\n\\n\"\n    printf \"flags:\\n\"\n    printf \"    --help, -h        Show this help message\\n\"\n    printf \"    --rg-name, -n     Name of the resource group to use. Will be created if needed. (required)\\n\"\n    printf \"                      Note: A resource group can only hold a single set of E2E resources.\\n\"\n    printf \"    --location, -l    Deploy to specific Azure region (optional, default is westus2)\\n\"\n}\n\n\n# process args\nlocation=westus2\n\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -l | --location)\n            location=$2\n            shift; shift;\n            ;;\n\n        -n | --rg-name)\n            rgName=$2\n            shift; shift;\n            ;;\n\n        -h | --help)\n            usage\n            exit 0\n            ;;\n\n        *)\n            printf \"Unexpected argument: $1\\n\"\n            usage\n            exit 1\n            ;;\n    esac\ndone\n\nif [ \"$rgName\" == \"\" ]; then\n    printf \"Expected argument rg-name is missing\\n\"\n    usage\n    exit 1\nfi\n\n\n# print warning\nprintf \"WARNING\\n\"\nprintf \"This script will deploy Azure resources into\\n\"\nprintf \"Subscription: $(az account show --query \"name\" -o tsv)\\n\"\nprintf \"Resource Group: $rgName\\n\"\nprintf \"Region: $location\\n\"\nprintf \"(Use 'az account list' and 'az account set' to change the subscription.)\\n\"\nread -p 'Press [Enter] to continue or ctrl-c to break'\n\n\n# create certs\nprintf \"Creating certs...\\n\"\nmkdir -p ${script_dir}/secrets/{certs,env}\nopenssl req \\\n    -new \\\n    -newkey rsa:4096 \\\n    -days 730 \\\n    -nodes \\\n    -x509 \\\n    -subj '/CN=Azure IoT Test Only' \\\n    -keyout ${script_dir}/secrets/certs/azure-iot-test-only.key \\\n    -out ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem > /dev/null 2>&1\nroot_cert=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem))\nprivate_key=$(printf \"%s\" $(base64 -i ${script_dir}/secrets/certs/azure-iot-test-only.key))\n\n\n# start deployment\ndeploymentName=\"IoT-E2E-$(printf $RANDOM)\"\n\nprintf \"Deploying Azure resources...\\n\"\ndeployment_out=$(az deployment sub create --only-show-errors \\\n    -f ${script_dir}/test-resources.bicep \\\n    -l $location \\\n    -n $deploymentName \\\n    -p \\\n        rgName=$rgName \\\n        alias=$(az account show --query '{user:user.name}' -o tsv) \\\n        userObjectId=$(az ad signed-in-user show --query id -o tsv) \\\n        rootCertValue=$root_cert \\\n        rootCertPrivateKey=$private_key)\n\niot_hub_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubName.value)\ndps_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.dpsName.value)\nkey_vault_name=$(printf \"$deployment_out\" | jq -r .properties.outputs.keyVaultName.value)\niot_provisioning_device_idscope=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotProvisioningDeviceIdScope.value)\niot_provisioning_service_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotProvisioningServiceConnectionString.value)\niothub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.iotHubConnectionString.value)\neventhub_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.eventHubConnectionString.value)\nstorage_connection_string=$(printf \"$deployment_out\" | jq -r .properties.outputs.storageConnectionString.value)\n\n\n# add cert to IoT Hub\nprintf \"Adding cert to IoT Hub...\\n\"\naz iot hub certificate create --only-show-errors -v \\\n    --hub-name $iot_hub_name \\\n    -g $rgName \\\n    -n azure-iot-test-only \\\n    -p ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem\n\n\n# add cert to DPS\nprintf \"Adding cert to DPS...\\n\"\naz iot dps certificate create --only-show-errors -v \\\n    --dps-name $dps_name \\\n    -g $rgName \\\n    -n azure-iot-test-only \\\n    -p ${script_dir}/secrets/certs/azure-iot-test-only.cert.pem\n\n\n# create activation scripts\nprintf \"Creating activation scripts...\\n\"\n\n# fake secrets\niot_provisioning_device_endpoint=\"global.azure-devices-provisioning.net\"\ndps_conn_string_invalid_cert=\"HostName=invalidcertdps1.westus.cloudapp.azure.com;SharedAccessKeyName=provisioningserviceowner;SharedAccessKey=lGO7OlXNhXlFyYV1rh9F/lUCQC1Owuh5f/1P0I1AFSY=\"\ndps_global_device_endpoint_invalid_cert=\"invalidcertgde1.westus.cloudapp.azure.com\"\niothub_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;SharedAccessKeyName=iothubowner;SharedAccessKey=Fk1H0asPeeAwlRkUMTybJasksTYTd13cgI7SsteB05U=\"\niothub_device_conn_string_invalid_cert=\"HostName=invalidcertiothub1.westus.cloudapp.azure.com;DeviceId=DoNotDelete1;SharedAccessKey=zWmeTGWmjcgDG1dpuSCVjc5ZY4TqVnKso5+g1wt/K3E=\"\n\npushd ${script_dir}/secrets/env/ > /dev/null 2>&1\n# PS\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_DEVICE_ENDPOINT -Value '$iot_provisioning_device_endpoint'\\r\\n\" > activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT -Value '$root_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CA_ROOT_CERT_KEY -Value '$private_key'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_DEVICE_IDSCOPE -Value '$iot_provisioning_device_idscope'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_ROOT_CERT -Value '$root_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_ROOT_CERT_KEY -Value '$private_key'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOT_PROVISIONING_SERVICE_CONNECTION_STRING -Value '$iot_provisioning_service_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONNECTION_STRING -Value '$iothub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:EVENTHUB_CONNECTION_STRING -Value '$eventhub_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:STORAGE_CONNECTION_STRING -Value '$storage_connection_string'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:DPS_CONN_STRING_INVALID_CERT -Value '$dps_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT -Value '$dps_global_device_endpoint_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_CONN_STRING_INVALID_CERT -Value '$iothub_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\nprintf \"Set-Item -Path Env:IOTHUB_DEVICE_CONN_STRING_INVALID_CERT -Value '$iothub_device_conn_string_invalid_cert'\\r\\n\" >> activate.ps1\n\n# CMD\nprintf \"set IOT_PROVISIONING_DEVICE_ENDPOINT=$iot_provisioning_device_endpoint\\r\\n\" > activate.cmd\nprintf \"set IOTHUB_CA_ROOT_CERT=$root_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CA_ROOT_CERT_KEY=$private_key\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_DEVICE_IDSCOPE=$iot_provisioning_device_idscope\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_ROOT_CERT=$root_cert\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_ROOT_CERT_KEY=$private_key\\r\\n\" >> activate.cmd\nprintf \"set IOT_PROVISIONING_SERVICE_CONNECTION_STRING=$iot_provisioning_service_connection_string\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONNECTION_STRING=$iothub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set EVENTHUB_CONNECTION_STRING=$eventhub_connection_string\\r\\n\" >> activate.cmd\nprintf \"set STORAGE_CONNECTION_STRING=$storage_connection_string\\r\\n\" >> activate.cmd\nprintf \"set DPS_CONN_STRING_INVALID_CERT=$dps_conn_string_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT=$dps_global_device_endpoint_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_CONN_STRING_INVALID_CERT=$iothub_conn_string_invalid_cert\\r\\n\" >> activate.cmd\nprintf \"set IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$iothub_device_conn_string_invalid_cert\\r\\n\" >> activate.cmd\n\n# BASH\nprintf \"#!/bin/bash\\n\" > activate\nprintf \"export IOT_PROVISIONING_DEVICE_ENDPOINT='$iot_provisioning_device_endpoint'\\n\" >> activate\nprintf \"export IOTHUB_CA_ROOT_CERT='$root_cert'\\n\" >> activate\nprintf \"export IOTHUB_CA_ROOT_CERT_KEY='$private_key'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_DEVICE_IDSCOPE='$iot_provisioning_device_idscope'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_ROOT_CERT='$root_cert'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_ROOT_CERT_KEY='$private_key'\\n\" >> activate\nprintf \"export IOT_PROVISIONING_SERVICE_CONNECTION_STRING='$iot_provisioning_service_connection_string'\\n\" >> activate\nprintf \"export IOTHUB_CONNECTION_STRING='$iothub_connection_string'\\n\" >> activate\nprintf \"export EVENTHUB_CONNECTION_STRING='$eventhub_connection_string'\\n\" >> activate\nprintf \"export STORAGE_CONNECTION_STRING='$storage_connection_string'\\n\" >> activate\nprintf \"export DPS_CONN_STRING_INVALID_CERT='$dps_conn_string_invalid_cert'\\n\" >> activate\nprintf \"export DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT='$dps_global_device_endpoint_invalid_cert'\\n\" >> activate\nprintf \"export IOTHUB_CONN_STRING_INVALID_CERT='$iothub_conn_string_invalid_cert'\\n\" >> activate\nprintf \"export IOTHUB_DEVICE_CONN_STRING_INVALID_CERT='$iothub_device_conn_string_invalid_cert'\\n\" >> activate\n\n# JSON\nprintf \"{\\n\" > env.json\nprintf \"    \\\"IOT_PROVISIONING_DEVICE_ENDPOINT\\\": \\\"$iot_provisioning_device_endpoint\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT\\\": \\\"$root_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CA_ROOT_CERT_KEY\\\": \\\"$private_key\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_DEVICE_IDSCOPE\\\": \\\"$iot_provisioning_device_idscope\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_ROOT_CERT\\\": \\\"$root_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_ROOT_CERT_KEY\\\": \\\"$private_key\\\",\\n\" >> env.json\nprintf \"    \\\"IOT_PROVISIONING_SERVICE_CONNECTION_STRING\\\": \\\"$iot_provisioning_service_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONNECTION_STRING\\\": \\\"$iothub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"EVENTHUB_CONNECTION_STRING\\\": \\\"$eventhub_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"STORAGE_CONNECTION_STRING\\\": \\\"$storage_connection_string\\\",\\n\" >> env.json\nprintf \"    \\\"DPS_CONN_STRING_INVALID_CERT\\\": \\\"$dps_conn_string_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT\\\": \\\"$dps_global_device_endpoint_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_conn_string_invalid_cert\\\",\\n\" >> env.json\nprintf \"    \\\"IOTHUB_DEVICE_CONN_STRING_INVALID_CERT\\\": \\\"$iothub_device_conn_string_invalid_cert\\\"\\n\" >> env.json\nprintf \"}\\n\" >> env.json\n\npopd > /dev/null 2>&1\n\nprintf \"Done!\\n\"\nprintf \"WARNING: The secrets directory contains secret values. Do not check-in this directory.\\n\"\nprintf \"Depending on your environment, activate the E2E test environment by running the following\\n\"\nprintf \"Bash: source secrets/env/activate\\n\"\nprintf \"PowerShell: secrets/env/activate.ps1\\n\"\nprintf \"CMD: secrets/env/activate.cmd\\n\"\nprintf \"Alternatively, you can retreive the environment variables from secrets/env/env.json\\n\"\nprintf \"or from the Key Vault named $key_vault_name.\\n\"\n", "num_lines": 214}
{"repo_name": "azure-iot-sdk-node", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Copyright (c) Microsoft. All rights reserved.\n# Licensed under the MIT license. See LICENSE file in the project root for\n# full license information.\n\nexport IOT_PROVISIONING_DEVICE_ENDPOINT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-DEVICE-ENDPOINT)\nexport IOTHUB_CA_ROOT_CERT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT)\nexport IOTHUB_CA_ROOT_CERT_KEY=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CA-ROOT-CERT-KEY)\nexport IOT_PROVISIONING_DEVICE_IDSCOPE=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-DEVICE-IDSCOPE)\nexport IOT_PROVISIONING_ROOT_CERT=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-ROOT-CERT)\nexport IOT_PROVISIONING_ROOT_CERT_KEY=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-ROOT-CERT-KEY)\nexport IOT_PROVISIONING_SERVICE_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOT-PROVISIONING-SERVICE-CONNECTION-STRING)\nexport IOTHUB_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv --vault-name $1 --name IOTHUB-CONNECTION-STRING)\nexport STORAGE_CONNECTION_STRING=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name STORAGE-CONNECTION-STRING)\nexport DPS_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name DPS-CONN-STRING-INVALID-CERT)\nexport DPS_GLOBAL_DEVICE_ENDPOINT_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name DPS-GLOBAL-DEVICE-ENDPOINT-INVALID-CERT)\nexport IOTHUB_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-CONN-STRING-INVALID-CERT)\nexport IOTHUB_DEVICE_CONN_STRING_INVALID_CERT=$(az keyvault secret show --query '{value:value}' --output tsv  --vault-name $1 --name IOTHUB-DEVICE-CONN-STRING-INVALID-CERT)", "num_lines": 17}
{"repo_name": "azure-iot-sdk-python", "repo_creator": "Azure", "programming_language": "Shell", "code": "#-------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#--------------------------------------------------------------------------\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\n\nexport RUNTIMES_TO_INSTALL=\"3.7.1 3.8.10 3.9.9 3.10.2\"\n\necho \"This script will do the following:\"\necho \"1. Use apt to install pre-requisites for pyenv\"\necho \"2. Install pyenv\"\necho \"3. Use pyenv to install the following Python runtimes: ${RUNTIMES_TO_INSTALL}\"\necho \"4. For each runtime, install virtualenv and create a default environment under your home directory\"\necho\n\nread -p \"Are you sure you want to do this? [yn] \" -n 1 -r\necho\nif [[ ! $REPLY =~ ^[Yy]$ ]]\nthen\n    exit 0\nfi\n\nsudo apt-get install -y make build-essential zlib1g-dev libbz2-dev \\\n    libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \\\n    xz-utils tk-dev libffi-dev liblzma-dev dos2unix\n[ $? -eq 0 ] || { echo \"APT failed\"; exit 1; }\n\ncurl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash\n[ $? -eq 0 ] || { echo \"failed installing pyenv\"; exit 1; }\n\ncd ${HOME}/.pyenv\n[ $? -eq 0 ] || { echo \"failed cd ${HOME}/.pyenv\"; exit 1; }\n\n# pyenv-installer gives us CRLF when we just want LF.  Force LF\nfind -type f -a -not \\( -path './versions/*' \\) -print0 | \\\n    xargs -0 -I @@ bash -c 'file \"$@\" | grep ASCII &>/dev/null && dos2unix $@' -- @@\n\nexport PATH=\"${HOME}/.pyenv/bin:${PATH}\"\neval \"$(pyenv init -)\"\neval \"$(pyenv virtualenv-init -)\"\n\nfunction build_failure_help {\n    echo\n    echo \"If you're getting an error: ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?\"\n    echo \"You MAY need to switch out OpenSSL 1.1.x with OpenSSL 1.0.\"\n    echo \"BUT,  doing this will break NPM and other tools that depend on OpenSSL 1.1.x, so BE VERY CAREFUL\"\n    echo \n    echo \"sudo apt install libssl1.0-dev\"\n    echo\n    echo \"Or, to learn more, read the following:\"\n    echo \"https://github.com/pyenv/pyenv/wiki/common-build-problems\"\n    echo \"https://github.com/pyenv/pyenv/issues/945\"\n    echo\n    echo \"The second link has a comment that suggests a private copy of OpenSSL 1.1.x headers to trick the compiler:\"\n    echo \"https://github.com/pyenv/pyenv/issues/945#issuecomment-409627448\"\n    echo\n}\n\nfor RUNTIME in ${RUNTIMES_TO_INSTALL}; do\n    echo calling pyenv install -s $RUNTIME\n    pyenv install -s $RUNTIME\n    [ $? -eq 0 ] || { echo \"failed installing Python $RUNTIME\"; build_failure_help; exit 1; }\n\n    pyenv shell $RUNTIME\n    [ $? -eq 0 ] || { echo \"failed calling pyenv to use Python $RUNTIME for this script\"; exit 1; }\n\n    python -m pip install --upgrade pip\n    [ $? -eq 0 ] || { echo \"failed upgrading PIP for Python $RUNTIME\"; exit 1; }\n\n    python -m pip install virtualenv\n    [ $? -eq 0 ] || { echo \"failed installing virtualenv for Python $RUNTIME\"; exit 1; }\n\n    python -m virtualenv \"${HOME}/env/Python-${RUNTIME}\"\n    [ $? -eq 0 ] || { echo \"failed setting up a virtual environment for Python $RUNTIME\"; exit 1; }\ndone\n\necho Success!\necho\necho \"Use the following commands to switch python versions (or use the aliases below):\"\nfor RUNTIME in $RUNTIMES_TO_INSTALL; do\n    echo \"source ~/env/Python-${RUNTIME}/bin/activate\"\ndone\necho\necho \"Add the following to your .bashrc file:\"\necho \"export PATH=\\\"${HOME}/.pyenv/bin:\\$PATH\\\"\"\necho \"eval \\\"\\$(pyenv init -)\\\"\"\necho \"eval \\\"\\$(pyenv virtualenv-init -)\\\"\"\necho \"alias pip='python -m pip $@'\"\nfor RUNTIME in $RUNTIMES_TO_INSTALL; do\n    echo \"alias py-${RUNTIME}='source ~/env/Python-${RUNTIME}/bin/activate'\"\ndone\n\n\n\n\n\n\n", "num_lines": 100}
{"repo_name": "azure-iot-sdk-python", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n## Copyright (c) Microsoft. All rights reserved.\n## Licensed under the MIT license. See LICENSE file in the project root for full license information.\n\n###############################################################################\n# This script demonstrates creating X.509 certificates for an Azure IoT Hub\n# CA Cert deployment.\n# This script is used to create the python build environment\n# on which our e2e tests run.\n# Currently the root cert will have a duration of 1 year.\n# All other certificates created from this root certificate\n# gets deleted after the tests.\n# NOTE : In case of 401 error during running DPS E2E tests for certificates\n# the certificates produced by this has expired. And the build environment\n# needs to run again.\n#\n# These certs MUST NOT be used in production.  It is expected that production\n# certificates will be created using a company's proper secure signing process.\n# These certs are intended only to help demonstrate and prototype CA certs.\n###############################################################################\nset -e\n\nroot_ca_dir=\".\"\nhome_dir=\".\"\nalgorithm=\"genrsa\"\nCOUNTRY=\"US\"\nSTATE=\"WA\"\nLOCALITY=\"Redmond\"\nORGANIZATION_NAME=\"My Organization\"\nkey_bits_length=\"4096\"\ndays_till_expire=365\nca_chain_prefix=\"azure-iot-test-only.chain.ca\"\nintermediate_ca_dir=\".\"\nopenssl_root_config_file=\"./openssl_root_ca.cnf\"\nopenssl_intermediate_config_file=\"./openssl_device_intermediate_ca.cnf\"\nroot_ca_prefix=\"azure-iot-test-only.root.ca\"\nintermediate_ca_prefix=\"azure-iot-test-only.intermediate\"\n\nfunction makeCNsubject()\n{\n    local result=\"/CN=${1}\"\n    case $OSTYPE in\n        msys|win32) result=\"/${result}\"\n    esac\n    echo \"$result\"\n}\n\nfunction warn_certs_not_for_production()\n{\n    tput smso\n    tput setaf 3\n    echo \"Certs generated by this script are not for production (e.g. they have hard-coded passwords of '1234'.\"\n    echo \"This script is only to help you understand Azure IoT Hub CA Certificates.\"\n    echo \"Use your official, secure mechanisms for this cert generation.\"\n    echo \"Also note that these certs will expire in ${days_till_expire} days.\"\n    tput sgr0\n}\n\nfunction generate_root_ca()\n{\n    if [ $# -ne 1 ]; then\n        echo \"Usage: <root ca password>\"\n        exit 1\n    fi\n\n    root_ca_password=\"${1}\"\n    local common_name=\"Azure IoT Hub CA Cert Test Only\"\n    local password_cmd=\" -aes256 -passout pass:${root_ca_password} \"\n\n    cd ${home_dir}\n    echo \"Creating the Root CA Private Key\"\n\n    openssl ${algorithm} \\\n            ${password_cmd} \\\n            -out ${root_ca_dir}/private/${root_ca_prefix}.key.pem \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 400 ${root_ca_dir}/private/${root_ca_prefix}.key.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Creating the Root CA Certificate\"\n    password_cmd=\" -passin pass:${root_ca_password} \"\n\n    openssl req \\\n            -new \\\n            -x509 \\\n            -config ${openssl_root_config_file} \\\n            ${password_cmd} \\\n            -key ${root_ca_dir}/private/${root_ca_prefix}.key.pem \\\n            -subj \"$(makeCNsubject \"${common_name}\")\" \\\n            -days ${days_till_expire} \\\n            -sha256 \\\n            -extensions v3_ca \\\n            -out ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n    chmod 444 ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"CA Root Certificate Generated At:\"\n    echo \"---------------------------------\"\n    echo \"    ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem\n\n    warn_certs_not_for_production\n\n    [ $? -eq 0 ] || exit $?\n}\n\n\n\n###############################################################################\n# Generate Intermediate CA Cert\n###############################################################################\nfunction generate_intermediate_ca()\n{\n    if [ $# -ne 1 ]; then\n        echo \"Usage: <root ca password>\"\n        exit 1\n    fi\n\n    root_ca_password=\"${1}\"\n    intermediate_ca_password=\"${1}\"\n\n    local common_name=\"Azure IoT Hub Intermediate Cert Test Only\"\n\n    local password_cmd=\" -aes256 -passout pass:${intermediate_ca_password} \"\n    echo \"Creating the Intermediate Device CA\"\n    echo \"-----------------------------------\"\n    cd ${home_dir}\n\n    openssl ${algorithm} \\\n            ${password_cmd} \\\n            -out ${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 400 ${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem\n    [ $? -eq 0 ] || exit $?\n\n\n    echo \"Creating the Intermediate Device CA CSR\"\n    echo \"-----------------------------------\"\n    password_cmd=\" -passin pass:${intermediate_ca_password} \"\n\n    openssl req -new -sha256 \\\n        ${password_cmd} \\\n        -config ${openssl_intermediate_config_file} \\\n        -subj \"$(makeCNsubject \"${common_name}\")\" \\\n        -key ${intermediate_ca_dir}/private/${intermediate_ca_prefix}.key.pem \\\n        -out ${intermediate_ca_dir}/csr/${intermediate_ca_prefix}.csr.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Signing the Intermediate Certificate with Root CA Cert\"\n    echo \"-----------------------------------\"\n    password_cmd=\" -passin pass:${root_ca_password} \"\n\n    openssl ca -batch \\\n        -config ${openssl_root_config_file} \\\n        ${password_cmd} \\\n        -extensions v3_intermediate_ca \\\n        -days ${days_till_expire} -notext -md sha256 \\\n        -in ${intermediate_ca_dir}/csr/${intermediate_ca_prefix}.csr.pem \\\n        -out ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n    chmod 444 ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Verify signature of the Intermediate Device Certificate with Root CA\"\n    echo \"-----------------------------------\"\n    openssl verify \\\n            -CAfile ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem \\\n            ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Intermediate CA Certificate Generated At:\"\n    echo \"-----------------------------------------\"\n    echo \"    ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Create Root + Intermediate CA Chain Certificate\"\n    echo \"-----------------------------------\"\n    cat ${intermediate_ca_dir}/certs/${intermediate_ca_prefix}.cert.pem \\\n        ${root_ca_dir}/certs/${root_ca_prefix}.cert.pem > \\\n        ${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n    chmod 444 ${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Root + Intermediate CA Chain Certificate Generated At:\"\n    echo \"------------------------------------------------------\"\n    echo \"    ${intermediate_ca_dir}/certs/${ca_chain_prefix}.cert.pem\"\n\n    warn_certs_not_for_production\n}\n\n###############################################################################\n# Generate a Certificate for a device using specific openssl extension and\n# signed with either the root or intermediate cert.\n###############################################################################\nfunction generate_device_certificate_common()\n{\n    local common_name=\"${1}\"\n    local device_prefix=\"${2}\"\n    local certificate_dir=\"${3}\"\n    local ca_password=\"${4}\"\n    local server_pfx_password=\"1234\"\n    local password_cmd=\" -passin pass:${ca_password} \"\n    local openssl_config_file=\"${5}\"\n    local openssl_config_extension=\"${6}\"\n    local cert_type_diagnostic=\"${7}\"\n\n    echo \"Creating ${cert_type_diagnostic} Certificate\"\n    echo \"----------------------------------------\"\n    cd ${home_dir}\n\n    openssl ${algorithm} \\\n            -out ${certificate_dir}/private/${device_prefix}.key.pem \\\n            ${key_bits_length}\n    [ $? -eq 0 ] || exit $?\n    chmod 444 ${certificate_dir}/private/${device_prefix}.key.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Create the ${cert_type_diagnostic} Certificate Request\"\n    echo \"----------------------------------------\"\n    openssl req -config ${openssl_config_file} \\\n        -key ${certificate_dir}/private/${device_prefix}.key.pem \\\n        -subj \"$(makeCNsubject \"${common_name}\")\" \\\n        -new -sha256 -out ${certificate_dir}/csr/${device_prefix}.csr.pem\n    [ $? -eq 0 ] || exit $?\n\n    openssl ca -batch -config ${openssl_config_file} \\\n            ${password_cmd} \\\n            -extensions \"${openssl_config_extension}\" \\\n            -days ${days_till_expire} -notext -md sha256 \\\n            -in ${certificate_dir}/csr/${device_prefix}.csr.pem \\\n            -out ${certificate_dir}/certs/${device_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n    chmod 444 ${certificate_dir}/certs/${device_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"Verify signature of the ${cert_type_diagnostic}\" \\\n         \" certificate with the signer\"\n    echo \"-----------------------------------\"\n    openssl verify \\\n            -CAfile ${certificate_dir}/certs/${ca_chain_prefix}.cert.pem \\\n            ${certificate_dir}/certs/${device_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n\n    echo \"${cert_type_diagnostic} Certificate Generated At:\"\n    echo \"----------------------------------------\"\n    echo \"    ${certificate_dir}/certs/${device_prefix}.cert.pem\"\n    echo \"\"\n    openssl x509 -noout -text \\\n            -in ${certificate_dir}/certs/${device_prefix}.cert.pem\n    [ $? -eq 0 ] || exit $?\n    echo \"Create the ${cert_type_diagnostic} PFX Certificate\"\n    echo \"----------------------------------------\"\n    openssl pkcs12 -in ${certificate_dir}/certs/${device_prefix}.cert.pem \\\n            -inkey ${certificate_dir}/private/${device_prefix}.key.pem \\\n            -password pass:${server_pfx_password} \\\n            -export -out ${certificate_dir}/certs/${device_prefix}.cert.pfx\n    [ $? -eq 0 ] || exit $?\n    echo \"${cert_type_diagnostic} PFX Certificate Generated At:\"\n    echo \"--------------------------------------------\"\n    echo \"    ${certificate_dir}/certs/${device_prefix}.cert.pfx\"\n    [ $? -eq 0 ] || exit $?\n}\n\n###############################################################################\n# Generate a certificate for a leaf device\n# signed with either the root or intermediate cert.\n###############################################################################\nfunction generate_leaf_certificate()\n{\n    local common_name=\"${1}\"\n    local device_prefix=\"${2}\"\n    local certificate_dir=\"${3}\"\n    local ca_password=\"${4}\"\n    local openssl_config_file=\"${5}\"\n\n    generate_device_certificate_common \"${common_name}\" \"${device_prefix}\" \\\n                                       \"${certificate_dir}\" \"${ca_password}\" \\\n                                       \"${openssl_config_file}\" \"server_cert\" \\\n                                       \"Leaf Device\"\n}\n\n###############################################################################\n#  Creates required directories and removes left over cert files.\n#  Run prior to creating Root CA; after that these files need to persist.\n###############################################################################\nfunction prepare_filesystem()\n{\n    if [ ! -f ${openssl_root_config_file} ]; then\n        echo \"Missing file ${openssl_root_config_file}\"\n        exit 1\n    fi\n\n    if [ ! -f ${openssl_intermediate_config_file} ]; then\n        echo \"Missing file ${openssl_intermediate_config_file}\"\n        exit 1\n    fi\n\n    rm -rf csr\n    rm -rf private\n    rm -rf certs\n    rm -rf intermediateCerts\n    rm -rf newcerts\n\n    mkdir -p csr\n    mkdir -p private\n    mkdir -p certs\n    mkdir -p intermediateCerts\n    mkdir -p newcerts\n\n    rm -f ./index.txt\n    touch ./index.txt\n\n    rm -f ./serial\n    echo 01 > ./serial\n}\n\n###############################################################################\n# Generates a root and intermediate certificate for CA certs.\n###############################################################################\nfunction initial_cert_generation()\n{\n    prepare_filesystem\n    generate_root_ca \"${1}\"\n    generate_intermediate_ca \"${1}\"\n}\n\n###############################################################################\n# Generates a certificate for verification, chained directly to the root.\n###############################################################################\nfunction generate_verification_certificate()\n{\n    if [ $# -ne 2 ]; then\n        echo \"Usage: <subjectName>\"\n        echo \"Usage: <root ca password>\"\n        exit 1\n    fi\n\n    root_ca_password=\"${2}\"\n\n    rm -f ./private/verification-code.key.pem\n    rm -f ./certs/verification-code.cert.pem\n    generate_leaf_certificate \"${1}\" \"verification-code\" \\\n                              ${root_ca_dir} ${root_ca_password} \\\n                              ${openssl_root_config_file}\n}\n\n###############################################################################\n# Generates a certificate for a device, chained to the intermediate.\n###############################################################################\nfunction generate_device_certificate()\n{\n    if [ $# -ne 2 ]; then\n        echo \"Usage: <subjectName>\"\n        echo \"Usage: <root password>\"\n        exit 1\n    fi\n\n    root_ca_password=\"${2}\"\n\n    rm -f ./private/new-device.key.pem\n    rm -f ./certs/new-device.key.pem\n    rm -f ./certs/new-device-full-chain.cert.pem\n    generate_leaf_certificate \"${1}\" \"new-device\" \\\n                              ${root_ca_dir} ${root_ca_password} \\\n                              ${openssl_root_config_file}\n}\n\n###############################################################################\n# Generates a certificate for a Edge device, chained to the intermediate.\n###############################################################################\nfunction generate_edge_device_certificate()\n{\n    local device_prefix=\"new-edge-device\"\n    if [ $# -ne 1 ]; then\n        echo \"Usage: <subjectName>\"\n        exit 1\n    fi\n    rm -f ./private/new-edge-device.key.pem\n    rm -f ./certs/new-edge-device.cert.pem\n    rm -f ./certs/new-edge-device-full-chain.cert.pem\n\n    # Note: Appending a '.ca' to the common name is useful in situations\n    # where a user names their hostname as the edge device name.\n    # By doing so we avoid TLS validation errors where we have a server or\n    # client certificate where the hostname is used as the common name\n    # which essentially results in \"loop\" for validation purposes.\n    generate_device_certificate_common \"${1}.ca\" \\\n                                       ${device_prefix} \\\n                                       ${intermediate_ca_dir} \\\n                                       ${intermediate_ca_password} \\\n                                       ${openssl_intermediate_config_file} \\\n                                       \"v3_intermediate_ca\" \"Edge Device\"\n}\n\nif [ \"${1}\" == \"create_root_and_intermediate\" ]; then\n    initial_cert_generation \"${2}\"\nelif [ \"${1}\" == \"create_verification_certificate\" ]; then\n    generate_verification_certificate \"${2}\" \"${3}\"\nelif [ \"${1}\" == \"create_device_certificate\" ]; then\n    generate_device_certificate \"${2}\" \"${3}\"\nelif [ \"${1}\" == \"create_edge_device_certificate\" ]; then\n    generate_edge_device_certificate \"${2}\"\nelse\n    echo \"Usage: create_root_and_intermediate                   # Creates a new root and intermediate certificates\"\n    echo \"       create_verification_certificate <subjectName>  # Creates a verification certificate, signed with <subjectName>\"\n    echo \"       create_device_certificate <subjectName>        # Creates a device certificate, signed with <subjectName>\"\n    echo \"       create_edge_device_certificate <subjectName>   # Creates an edge device certificate, signed with <subjectName>\"\n    exit 1\nfi\n\nwarn_certs_not_for_production\n", "num_lines": 422}
{"repo_name": "azure-iot-sdk-python-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "#-------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#--------------------------------------------------------------------------\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\n\nexport RUNTIMES_TO_INSTALL=\"2.7.15 3.4.9 3.5.6 3.6.6 3.7.1\"\n\necho \"This script will do the following:\"\necho \"1. Use apt to install pre-requisites for pyenv\"\necho \"2. Install pyenv\"\necho \"3. Use pyenv to install the following Python runtimes: ${RUNTIMES_TO_INSTALL}\"\necho \"4. For each runtime, install virtualenv and create a default environment under your home directory\"\necho\n\nread -p \"Are you sure you want to do this? [yn] \" -n 1 -r\necho\nif [[ ! $REPLY =~ ^[Yy]$ ]]\nthen\n    exit 0\nfi\n\nsudo apt-get install -y make build-essential zlib1g-dev libbz2-dev \\\n    libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev libncursesw5-dev \\\n    xz-utils tk-dev libffi-dev liblzma-dev dos2unix\n[ $? -eq 0 ] || { echo \"APT failed\"; exit 1; }\n\ncurl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash\n[ $? -eq 0 ] || { echo \"failed installing pyenv\"; exit 1; }\n\ncd ${HOME}/.pyenv\n[ $? -eq 0 ] || { echo \"failed cd ${HOME}/.pyenv\"; exit 1; }\n\n# pyenv-installer gives us CRLF when we just want LF.  Force LF\nfind -type f -a -not \\( -path './versions/*' \\) -print0 | \\\n    xargs -0 -I @@ bash -c 'file \"$@\" | grep ASCII &>/dev/null && dos2unix $@' -- @@\n\nexport PATH=\"${HOME}/.pyenv/bin:${PATH}\"\neval \"$(pyenv init -)\"\neval \"$(pyenv virtualenv-init -)\"\n\nfunction build_failure_help {\n    echo\n    echo \"If you're getting an error: ERROR: The Python ssl extension was not compiled. Missing the OpenSSL lib?\"\n    echo \"You MAY need to switch out OpenSSL 1.1.x with OpenSSL 1.0.\"\n    echo \"BUT,  doing this will break NPM and other tools that depend on OpenSSL 1.1.x, so BE VERY CAREFUL\"\n    echo \n    echo \"sudo apt install libssl1.0-dev\"\n    echo\n    echo \"Or, to learn more, read the following:\"\n    echo \"https://github.com/pyenv/pyenv/wiki/common-build-problems\"\n    echo \"https://github.com/pyenv/pyenv/issues/945\"\n    echo\n    echo \"The second link has a comment that suggests a private copy of OpenSSL 1.1.x headers to trick the compiler:\"\n    echo \"https://github.com/pyenv/pyenv/issues/945#issuecomment-409627448\"\n    echo\n}\n\nfor RUNTIME in ${RUNTIMES_TO_INSTALL}; do\n    echo calling pyenv install -s $RUNTIME\n    pyenv install -s $RUNTIME\n    [ $? -eq 0 ] || { echo \"failed installing Python $RUNTIME\"; build_failure_help; exit 1; }\n\n    pyenv shell $RUNTIME\n    [ $? -eq 0 ] || { echo \"failed calling pyenv to use Python $RUNTIME for this script\"; exit 1; }\n\n    python -m pip install --upgrade pip\n    [ $? -eq 0 ] || { echo \"failed upgrading PIP for Python $RUNTIME\"; exit 1; }\n\n    python -m pip install virtualenv\n    [ $? -eq 0 ] || { echo \"failed installing virtualenv for Python $RUNTIME\"; exit 1; }\n\n    python -m virtualenv \"${HOME}/env/Python-${RUNTIME}\"\n    [ $? -eq 0 ] || { echo \"failed setting up a virtual environment for Python $RUNTIME\"; exit 1; }\ndone\n\necho Success!\necho\necho \"Use the following commands to switch python versions (or use the aliases below):\"\nfor RUNTIME in $RUNTIMES_TO_INSTALL; do\n    echo \"source ~/env/Python-${RUNTIME}/bin/activate\"\ndone\necho\necho \"Add the following to your .bashrc file:\"\necho \"export PATH=\\\"${HOME}/.pyenv/bin:\\$PATH\\\"\"\necho \"eval \\\"\\$(pyenv init -)\\\"\"\necho \"eval \\\"\\$(pyenv virtualenv-init -)\\\"\"\necho \"alias pip='python -m pip $@'\"\nfor RUNTIME in $RUNTIMES_TO_INSTALL; do\n    echo \"alias py-${RUNTIME}='source ~/env/Python-${RUNTIME}/bin/activate'\"\ndone\n\n\n\n\n\n\n", "num_lines": 100}
{"repo_name": "Azure-IoT-Security", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nDIRECTORY=`dirname $0`\nPORT=8888\nTMP_PID_FILE=\".tmp.pid\"\nCOMMAND=\"nc -lkp \"\nBAD_PROCESS_NAME=\"httpsd\"\nNUMERIC_REGEX='^[0-9]+$'\n\n\n_exploit=0\n_remidiate=0\n_malicious=0\n_portsArr=($PORT)\n_portOutput=\"port$PORT.output\"\n\nusage(){\n    echo \"This script creates a vulnerability on your machine.\"\n    echo \"The script opens port $PORT and listens to it.\"\n    echo \"Usage:\"\n    echo \"$0 | flags\"\n    echo \"--exploit (?additional ports)     - open and listen to ports $PORT and additional ports\"\n    echo \"      additional ports            - number of additional ports. i.e `-e 3` will open ports 8888,8889,8900\"\n    echo \"--remidiate                       - closes the port and stops listening\"\n    echo \"--malicious                       - runs a fake malicious process\"\n}\n\nif [ $# -eq 0 ]; then\n    usage\n    exit 1\nfi\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -e | --exploit )\n            _exploit=1\n\n            _endPort=$(($PORT+${2:-0}))\n            if [[ $_endPort =~ $NUMERIC_REGEX ]] && [ \"$_endPort\" != \"$PORT\" ] ; then\n                _portsArr=($(seq $PORT 1 $_endPort))\n                shift\n            fi\n\n            shift\n            ;;\n        -r | --remidiate )\n            _remidiate=1\n            shift\n            ;;\n        -m | --malicious )\n            _malicious=1\n            shift\n            ;;\n        * )\n            usage\n            exit 1\n    esac\ndone\n\nexploit(){\n    CURRENT_PORT=$1\n\n    isPortOpen=$(sudo netstat -ntlp | grep LISTEN | awk '{ print $4}'  | awk -F: '{print $2}' | grep $CURRENT_PORT)\n    if [ ! -z \"$isPortOpen\" ]; then\n        echo \"Port $CURRENT_PORT is already opened on your machine\"\n        return 0\n    fi\n\n    CURRENT_COMMAND=\"nc -lkp $CURRENT_PORT\"\n    PORT_OUTPUT_FILE=\"port$CURRENT_PORT.output\"\n    $CURRENT_COMMAND <&- >>$PORT_OUTPUT_FILE &\n    pid=$!\n    sleep .5\n    ps -p $pid > /dev/null\n\n    if [ $? -eq 0 ]; then\n        echo $! >> .tmp.pid\n        echo \"The process $! is now listening to port $CURRENT_PORT\"\n    else\n        echo \"Couldn't run $CURRENT_COMMAND\"\n    fi\n\n    return\n}\n\nremidiate(){\n    if [ -f \"$TMP_PID_FILE\" ]; then\n        for pid in `cat $TMP_PID_FILE`\n        do\n            isProcessExist=$(ps -aux | grep -e \"$pid.*$COMMAND $pid\")\n            if [ ! -z \"$isProcessExist\" ]; then\n                echo \"Killing process $pid\"\n                kill $pid\n            fi\n        done\n\n        # cleanup\n        rm \"$TMP_PID_FILE\" *.output || true\n    else\n        echo \"Nothing to kill\"\n    fi\n}\n\nrunMaliciousProc(){\n    sh -c \"echo cpuminer-multi\" >/dev/null &\n\n    return\n}\n\n#------Script Begins Here-------\nif [ \"$EUID\" -ne 0 ]\n  then echo \"Please run as root\"\n  exit\nfi\n\ncurrDir=$PWD\ncd $DIRECTORY\nif [ $_exploit -eq 1 ]; then\n    for i in \"${_portsArr[@]}\"\n    do\n        exploit $i\n    done\nfi\n\nif [ $_remidiate -eq 1 ]; then\n    remidiate\nfi\n\nif [ $_malicious -eq 1 ];then\n    runMaliciousProc\nfi\n\ncd $currDir", "num_lines": 132}
{"repo_name": "Azure-IoT-Security-Agent-C", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nprogramname=$0\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake/agent_linux\"\nbuild_debug=\" -DCMAKE_BUILD_TYPE=Release \"\nunit_tests=\" \"\nint_tests=\" \"\nvalgrind=\" \"\nmake_args=\" \"\nprotocol=\" \"\ndisable_sdk_logs=\" \"\n\nprint_usage() {\n    echo \"usage: $programname [--debug] [--unit-tests] [--int-tests] [--valgrind] [--make-args <make arguments>]\"\n    echo \"  --debug           compile in debug mode\"\n    echo \"  --unit-tests      compile unit tests\"\n    echo \"  --int-tests       compile integration tests\"\n    echo \"  --valgrind        compile unit tests with valgrind\"\n    echo \"  --make-args       specify arguments for make\"\n    echo \"  --protocol        specify protocol AMQP or MQTT\"\n    echo \"  --disable-sdk-logs  disable iothub sdk builtin logs\"\n    echo \"example: $programname --debug --unit-tests --make-args -j4\"\n    exit 1\n}\n\nparse_args() {\n  while [ \"$1\" != \"\" ] && [ \"$1\" != \"--make-args\" ]; do\n    case $1 in\n      --debug)        build_debug=\" -DCMAKE_BUILD_TYPE=Debug \"  ;;\n      --unit-tests)   unit_tests=\" -Drun_unittests:BOOL=ON \"    ;;\n      --int-tests)    int_tests=\" -Drun_int_tests:BOOL=ON \"    ;;\n      --valgrind)     valgrind=\" -Drun_valgrind:BOOL=ON \"       ;;\n      --disable-sdk-logs) disable_sdk_logs=\" -Dno_logging=ON\" ;;\n      --protocol)     shift; \n                      if [ $1 = \"AMQP\" ] || [ $1 = \"MQTT\" ]; then\n                        protocol=\" -Dprotocol=$1\"                \n                      else\n                        print_usage\n                        exit 1\n                      fi;;\n      *)              print_usage                                       ;;\n    esac\n    shift\n  done\n  if [ \"$1\" == \"--make-args\" ]; then\n    shift\n    make_args=$@\n  fi\n}\n\nparse_args $*\n\necho $script_dir\necho $build_root\n\nrm -rf $build_folder\nmkdir -p $build_folder\npushd $build_folder\n\ncmake $build_debug $unit_tests $int_tests $valgrind $build_root $protocol $disable_sdk_logs\ncmake_result=$? \nif [[ $cmake_result -ne 0 ]]; then\n  echo \"cmake failed\"\n  exit $cmake_result\nfi\n\ndate\nmake $make_args\nmake_result=$? \ndate\n\nif [[ $make_result -ne 0 ]]; then\n  echo \"make failed\"\n  exit $make_result\nfi\n\npopd\n", "num_lines": 80}
{"repo_name": "Azure-IoT-Security-Agent-C", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho 'build started'\n\nprogramname=$0\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake/agent_linux\"\n\necho 'script dir: ' $script_dir\necho 'build root: '$build_root\necho 'build folder: '$build_folder\n\nrm -rf $build_folder\nmkdir -p $build_folder\npushd $build_folder\n\ncmake -Drun_unittests:BOOL=ON -Drun_int_tests:BOOL=ON -Drun_valgrind:BOOL=ON -DCMAKE_BUILD_TYPE=Release -Dno_logging=ON $build_root\ncmake_result=$? \nif [[ $cmake_result -ne 0 ]]; then\n  echo \"cmake failed\"\n  exit $cmake_result\nfi\n\ndate\nmake -j$(nproc)\nmake_result=$? \ndate\nif [[ $make_result -ne 0 ]]; then\n  echo \"make failed\"\n  exit $make_result\nfi\n\npopd\n\ninstalled_packages_output=$build_root\"/cmake/installed_packages.txt\"\ndpkg -l cmake build-essential uuid-dev libssl-dev libaudit-dev libauparse-dev moreutils iptables-dev valgrind > $installed_packages_output\n\necho 'build finished'\n", "num_lines": 40}
{"repo_name": "Azure-IoT-Security-Agent-C", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake/agent_linux\"\n\necho 'script dir: ' $script_dir\necho 'build root: '$build_root\necho 'build folder: '$build_folder\n\npushd $build_folder\n\nctest --no-compress-output --output-on-failure -j$(nproc) -T test\ntest_result=$?\n\npopd\n\nif [ -f $build_folder/Testing/TAG ] ; then\n   xsltproc $script_dir/ctest2junit.xsl $build_folder/Testing/`head -n 1 < $build_folder/Testing/TAG`/Test.xml > $build_folder/CTestResults.xml\nfi\n\nif [[ $test_result -ne 0 ]]; then\n  echo \"tests failed\"\n  exit $test_result\nfi\n", "num_lines": 26}
{"repo_name": "Azure-IoT-Security-Agent-C", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nscript_dir=$(cd \"$(dirname \"$0\")\" && pwd)\nbuild_root=$(cd \"${script_dir}/..\" && pwd)\nbuild_folder=$build_root\"/cmake/agent_linux\"\n\npushd $build_folder/tests\n\nfailed_tests=0\n\nfor f in *; do\n\n    if [ -d ${f} ]; then\n        if [ ${f} != \"CMakeFiles\" ]; then\n            # Will not run if no directories are available\n            ./${f}/${f}_exe\n            failed_tests=$(expr $failed_tests + $?)\n        fi\n    fi\ndone\n\nif [[ \"$failed_tests\" -eq 0 ]]; then\n    echo \"All test have passed\"\nelse \n    echo  \"$failed_tests test failed\"\nfi\n\npopd\n\nexit $failed_tests", "num_lines": 30}
{"repo_name": "Azure-IoT-Security-Agent-C", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_userName=\"asciotagent\"\n_serviceTemplateName=\"ASCIoTAgent.service\"\n_systemServiceFileLocation=\"/etc/systemd/system\"\n_targetDirectory=\"/var/ASCIoTAgent\"\n_execName=\"ASCIoTAgent\"\n_scriptDir=\n_mode=\"none\"\n_omsBaselineExecutablePath=\"https://ascforiot.blob.core.windows.net/public/\"\n_omsBaselineX64=\"omsbaseline-linux-amd64\"\n_omsBaselineI386=\"omsbaseline-linux-386\"\n_omsBaselineARMv7=\"omsbaseline-linux-arm-v7\"\n_omsBaselineARMv8=\"omsbaseline-linux-arm64-v8\"\n_omsAudits=\"oms_audits.xml\"\n_omsBaseline=\"omsbaseline\"\n_identity=\n_authenticationMethod=\n_filePath=\n_deviceId=\n_hostName=\n_reboot=false\n\nusage()\n{\n    scriptName=`basename \"$0\"`\n\n    echo \"Utility script for installing and uninstalling the agent.\"\n    echo \"\"\n    echo \"Usage:\"\n    echo \"  $scriptName -i -aui <Device | SecurityModule> -aum <authentication method> -f <file path> -hn <host name> -di <device id>\"\n    echo \"  $scriptName -u\"\n    echo \"  $scriptName -h\"\n    echo \"\"\n    echo \"Options:\"\n    echo \" -i   --install                    Install the agent.\"\n    echo \" -u   --uninstall                  Uninstall the agent.\"\n    echo \" -h   --help                       Show this screen.\"\n    echo \" -aui --authentication-identity    The authentication identity used by the agent (SecurityModule or Device).\"\n    echo \" -aum --authentication-method      The authentication method used by the agent (SymmetricKey or SelfSignedCertificate).\"\n    echo \" -f   --file-path                  Path to a file from which data related to the authentication method should be read (the key or certificate).\"\n    echo \" -hn  --host-name                  IoT hub's host name.\"\n    echo \" -di  --device-id                  Id of the device the agent is beind installed on (as defined in the IoT hub).\"\n    echo \" -r   --reboot\t\t\t\t\t Specifies whether to do an automatic reboot when installation finished.\"\n}\n\nwgetAndExitOnFail(){\n    wget \"$1\" -O \"$2\"\n    if [ $? -ne 0 ]; then\n        echo \"Couldn't donwload $1, exiting...\";\n        exit 1;\n    fi\n}\n\nuninstallagent()\n{\n    echo uninstalling agent\n\n    #stop the daemon\n    systemctl stop $_serviceTemplateName\n\n    #disable the service\n    systemctl disable $_serviceTemplateName\n\n    #remove the agent files\n    rm -rf $_targetDirectory\n\n    #remove the service user\n    deluser --remove-home --remove-all-files $_userName\n\n    #remove the service configuration\n    rm $_systemServiceFileLocation/$_serviceTemplateName\n\n    echo agent uninstallation finished\n}\n\ninstallagent()\n{\n    #install dependencies\n    echo installing agent dependencies\n    apt-get update -y && apt-get install -y \\\n        auditd \\\n        uuid-runtime \\\n        libcurl4-openssl-dev\n\n    echo installing agent\n\n    #add the service user\n    echo creating service user\n    adduser --disabled-login --gecos 'ASC IoT Agent' $_userName\n    usermod -a -G sudo $_userName\n\n    #Get oms executables according to systems architecture\n    baselinePath=\"$_scriptDir/$_omsBaseline\"\n\n    #get oms executables:\n    wgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsAudits}\" \"$_scriptDir/$_omsAudits\"\n\n    # download omsbaseline supported architecture\n\tcase $(uname -m) in\n    'x86_64')\n        wgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineX64}\"  $baselinePath\n        ;;\n    'armv7l')\n        wgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineARMv7}\"  $baselinePath\n        ;;\n    'aarch64')\n        wgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineARMv8}\"  $baselinePath\n        ;;\n    'i368')\n        wgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineI386}\" $baselinePath\n\t\t;;\n    *)\n\t\techo \"Not supported architecture\"\n        exit 1\n\t\t;;\n\tesac\n\n    #populate the target directory with the agent files\n    mkdir $_targetDirectory\n    cp -r $_scriptDir/* $_targetDirectory\n\n    #add connection string in app.config\n    sed -i -e \"s|\\\"Identity\\\" : \\\"[^\\\"]*\\\"|\\\"Identity\\\" : \\\"$_identity\\\"|g\" $_targetDirectory/LocalConfiguration.json\n    sed -i -e \"s|\\\"AuthenticationMethod\\\" : \\\"[^\\\"]*\\\"|\\\"AuthenticationMethod\\\" : \\\"$_authenticationMethod\\\"|g\" $_targetDirectory/LocalConfiguration.json\n    sed -i -e \"s|\\\"FilePath\\\" : \\\"[^\\\"]*\\\"|\\\"FilePath\\\" : \\\"$_filePath\\\"|g\" $_targetDirectory/LocalConfiguration.json\n    sed -i -e \"s|\\\"DeviceId\\\" : \\\"[^\\\"]*\\\"|\\\"DeviceId\\\" : \\\"$_deviceId\\\"|g\" $_targetDirectory/LocalConfiguration.json\n    sed -i -e \"s|\\\"HostName\\\" : \\\"[^\\\"]*\\\"|\\\"HostName\\\" : \\\"$_hostName\\\"|g\" $_targetDirectory/LocalConfiguration.json\n\n    #generate agentId GUID\n    agentId=$(uuidgen)\n    sed -i -e \"s|\\\"AgentId\\\" : \\\"[^\\\"]*\\\"|\\\"AgentId\\\" : \\\"$agentId\\\"|g\" $_targetDirectory/LocalConfiguration.json\n\n    #make the agent user owner of the target directory\n    chown -R $_userName:$_userName $_targetDirectory\n\n    #make agent executable\n    chown root $_targetDirectory/$_execName\n    chmod 4755 $_targetDirectory/$_execName\n    chmod +x $_targetDirectory/$_omsBaseline\n\n    #replace variables in the service file template\n    sed -e \"s|{DIRECTORY}|$_targetDirectory|g\" -e \"s|{EXE}|$_execName|g\" -e \"s|{USER}|$_userName|g\" -e \"s|{GROUP}|$_userName|g\" $_serviceTemplateName > $_systemServiceFileLocation/$_serviceTemplateName\n\n    #reload the deamon, in case is was already installed before\n    systemctl daemon-reload\n\n    #enable the service so that it starts on boot\n    systemctl enable $_serviceTemplateName\n\n    #start the service\n    systemctl start $_serviceTemplateName\n    \n    echo agent installation finished\n\n    setupIMAPolicy\n\n}\n\nvalidate_installation_params()\n{\n    shouldExit=false\n\n    if [ -z \"$_authenticationMethod\" ]\n    then\n\t\techo \"authentication-method not provided\"\n        shouldExit=true\n    fi\n\n\tif [ -z \"$_filePath\" ]\n\tthen\n\t\techo \"file-path not provided\"\n        shouldExit=true\n\tfi\n\n\tif [ -z \"$_identity\" ]\n    then\n\t\techo \"authentication-identity not provided\"\n        shouldExit=true\n\telse\n\t\tif [ -z \"$_hostName\" ]\n\t\tthen\n\t\t\techo \"host-name not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\n\t\tif [ -z \"$_deviceId\" ]\n\t\tthen\n\t\t\techo \"device-id not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\tfi\n\n    if $shouldExit\n    then\n        echo \"cannot intall the agent, please check the validity of the supplied parameters\"\n        exit 1\n    fi\n}\n\nsetupIMAPolicy(){\n\tmkdir -p /etc/ima\n\techo \"audit func=BPRM_CHECK mask=MAY_EXEC\" > /etc/ima/ima-policy\n    if [[ $_reboot == true ]]\n    then\n        sudo reboot;\n    else\n        echo \"A reboot is required to complete agent installation.\"\n        read  -p \"Do you wish to do it now?[y/n]\" answer\n        case $answer in\n            [Yy]* ) sudo reboot; break;;\n            [Nn]* ) echo \"To take full advantage of the security agent capabilities, make sure you reboot your device later.\";;\n            * ) echo \"Please answer yes or no.\";;\n        esac\n    fi\n}\n\nsetFilePath(){\n\tfile=$1\n\tdir=$(pwd)\n\tif [[ $file == /* ]]\n\tthen\n\t\t_filePath=$file\n\telse\n\t\t_filePath=$dir/$file\n\n\tfi\n\tif [ ! -f $_filePath ]; then\n\t\techo \"File $_filePath does not exist!\";\n\t\texit 1;\n\tfi\n}\n\n#parse command line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n        -aui | --authentication-identity )  shift\n            if [ \"$1\" = \"SecurityModule\" ] || [ \"$1\" = \"Device\" ]; then\n                _identity=$1\n            else\n                echo \"Possible values for authentication-identity are: SecurityModule or Device\"\n                usage\n                exit 1\n            fi\n                                    ;;\n        -aum | --authentication-method )  shift\n            if [ \"$1\" = \"SymmetricKey\" ] || [ \"$1\" = \"SelfSignedCertificate\" ]; then\n                _authenticationMethod=$1\n            else\n                echo \"Possible values for authentication-method are: SymmetricKey or SelfSignedCertificate\"\n                usage\n                exit 1\n            fi\n                                    ;;\n        -f | --file-path )          shift\n                                    setFilePath $1\n                                    ;;\n\t\t-hn | --host-name )         shift\n\t\t\t\t\t\t\t\t\t_hostName=$1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-di | --device-id)          shift\n\t\t\t\t\t\t\t\t\t_deviceId=$1\n\t\t\t\t\t\t\t\t\t;;\n        -r | --reboot )             shift\n                                    _reboot=true\n                                    ;;\n        -u | --uninstall )          _mode=\"uninstall\"\n                                    ;;\n        -i | --install )            _mode=\"install\"\n                                    ;;\n        -h | --help )               usage\n                                    exit\n                                    ;;\n        * )                         usage\n                                    exit 1\n    esac\n    shift\ndone\n\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\n\n_authenticationMethod=${_authenticationMethod/SymmetricKey/SasToken}\n\nif [[ $_mode == \"uninstall\" ]]; then\n    uninstallagent\nelif [[ $_mode == \"install\" ]]; then\n    validate_installation_params\n    installagent\nelse\n    usage\nfi", "num_lines": 291}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nusage()\n{\n    echo \"usage: setupDevEnv $_usageDescriptionExtension| [-h]]\"\n}\n\nsetupCore()\n{\n    scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\n   \n    generalConfigFile=\"$scriptDir/../General.config\"\n\tagentId=$(uuidgen)\n\tsed -i -e \"s|\\\"agentId\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"agentId\\\" value=\\\"$agentId\\\"|g\" $generalConfigFile\n}\n\n#parse command line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n\t        -h | --help )                shift\n\t\t                             usage\n                                             exit\n    esac\n    shift\ndone\n\n", "num_lines": 27}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\nsource \"$_scriptDir/CoreSetupDevEnv.sh\" \"$@\"\n\nsetupCore\n", "num_lines": 7}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_serviceName=\"MSIoTAgent\"\n_serviceTemplateName=\"$_serviceName.service\"\n_targetDirectory=\"/var/$_serviceName\"\n_userName=\"msiotagent\"\n_serviceDescription=\"Microsoft IoT Agent\"\n_systemServiceFileLocation=\"/etc/systemd/system\"\n_mode=\n_execName=\"Agent.Linux\"\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\n_nice=10\n\nusage()\n{\n    scriptName=`basename \"$0\"`\n\n\techo \"Utility script for installing and uninstalling the agent.\"\n\techo \"\"\n\techo \"Usage:\"\n\techo \"  $scriptName -i$_installUsageExtendedDescription [-n <niceness level>]\"\n\techo \"  $scriptName -u\"\n\techo \"  $scriptName -h\"\n\techo \"\"\n\techo \"Options:\"\n\techo \"  -i   --install                    Install the agent.\"\n\techo \"  -u   --uninstall                  Uninstall the agent.\"\n\techo \"  -h   --help                       Show this screen.\"\n\techo \"  -n   --nice                       Niceness (priority) level of the service.\"\n\n\tif [ \"$_optionsExtendedDescription\" != \"\" ]; then\n\t\techo -e \"$_optionsExtendedDescription\"\n\tfi\n}\n\nwgetAndExitOnFail()\n{\n\twget \"$1\" -O \"$2\"\n\tif [ $? -ne 0 ]; then\n\t\techo \"Error: could not download $1, exiting\"\n\t\texit 1\n\tfi\n}\n\nuninstallagent()\n{\n    echo uninstalling agent [core]\n\n    #stop the daemon\n    systemctl stop $_serviceTemplateName\n\n\t#disable the service\n\tsystemctl disable $_serviceTemplateName\n\n    #remove the agent files\n    rm -rf $_targetDirectory \n\n    #remove the service user\n    deluser --remove-home --remove-all-files $_userName\n\n    #remove the service configuration\n    rm $_systemServiceFileLocation/$_serviceTemplateName\n\n    echo agent uninstallation finished [core]\n}\n\nupdateServiceNameDependentFields()\n{\n     _serviceTemplateName=\"$_serviceName.service\"\n     _targetDirectory=\"/var/$_serviceName\"\n}\n\nprepareEnvironment()\n{\n    #install dependencies\n    echo installing core agent dependencies\n\n\tapt-get install -y libunwind8\n    apt-get install -y libcurl3\n\tapt-get install -y uuid-runtime\n\n    echo preparding core agent environment\n    \n    #add the service user\n    echo creating service user \n    adduser --disabled-login --gecos \"$_serviceName\" $_userName\n\n    #populate the target directory with the agent files \n    mkdir $_targetDirectory\n    cp -r $_scriptDir/../* $_targetDirectory\n\n\t#generate device agent\n\tagentId=$(uuidgen)\n\tsed -i -e \"s|\\\"agentId\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"agentId\\\" value=\\\"$agentId\\\"|g\" $_targetDirectory/General.config\n\t\n    #make the agent user ownder of the target directory\n    chown -R $_userName:$_userName $_targetDirectory\n    \n    #make agent executable\n    chmod +x $_targetDirectory/$_execName\n    \n    #replace variables in the service file template\n    sed -e \"s|{DIRECTORY}|$_targetDirectory|g\" -e \"s|{USER}|$_userName|g\" -e \"s|{GROUP}|$_userName|g\" -e \"s|{DESCRIPTION}|$_serviceDescription|g\" -e \"s|{EXECNAME}|$_execName|g\" -e \"s|{NICENESS}|$_nice|g\" $_scriptDir/Template.service > $_systemServiceFileLocation/$_serviceTemplateName\n}\n\ninstallagent()\n{\n\techo installing agent\n  \n    #reload the deamon, in case is was already installed before    \n    systemctl daemon-reload\n\n\t#enable the service so that it starts on boot\n\tsystemctl enable $_serviceTemplateName\n\n    #start the service\n    systemctl start $_serviceTemplateName\n\n    echo agent installation finished\n}\n\n#parse command line arguments\nwhile [ \"$1\" != \"\" ]; do\n\tcase $1 in\n\t\t-u | --uninstall )          shift\n\t\t\t\t\t\t\t\t\t_mode=\"uninstall\"\n\t\t\t\t\t\t\t\t\t;;\n\t\t-i | --install )            shift\n\t\t\t\t\t\t\t\t\t_mode=\"install\"\n\t\t\t\t\t\t\t\t\t;;\n\t\t-d | --description )        shift\n\t\t\t\t\t\t\t\t\t_serviceDescription=$1\n\t\t\t\t\t\t\t\t\t;;\t\t\t\n    \t-s | --service_name )       shift\n\t\t\t\t\t\t\t\t\t_serviceName=$1\n\t\t\t\t\t\t\t\t\tupdateServiceNameDependentFields\n\t\t\t\t\t\t\t\t\t;;\t\t\n\t    -un | --user_name )\t\t\tshift\n\t\t\t\t\t\t\t\t\t_userName=$1\n\t\t\t\t\t\t\t\t\t;;\t\t\t\n\t\t-n | --nice )\t\t\t\tshift\n\t\t\t\t\t\t\t\t\t_nice=$1\n\t\t\t\t\t\t\t\t\t;;\t\t\t\n\t\t-h | --help )               usage\n\t\t\t\t\t\t\t\t\texit\n\t\t\t\t\t\t\t\t\t;;\n\tesac\n\tshift\ndone", "num_lines": 149}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\nsource \"$_scriptDir/CoreAgentInstallation.sh\" \"$@\"\n\nif [[ $_mode == \"uninstall\" ]] \nthen\n    uninstallagent\nelse\n    installagent\nfi", "num_lines": 11}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_connectionString=\n_sudoersTemplateName=\"asotagentsudoers\"\n_sudoersIncludeDirectory=\"/etc/sudoers.d\"\n_baselineExecutableDir=\"BaselineExecutables\"\n_keyFileName=\"KeyFile\"\n_omsBaselineExecutableGitPath=\"https://raw.githubusercontent.com/Microsoft/OMS-Agent-for-Linux/master/source/code/plugins/\"\n_omsAudits=\"oms_audits.xml\"\n_omsBaselineX64=\"omsbaseline_x64\"\n_omsBaselineX86=\"omsbaseline_x86\"\n_usageDescriptionExtension=\"[[-cs <connection string> ] [[-u <user> ] \"\n\nwgetAndExitOnFail()\n{\n\twget \"$1\" -O \"$2\"\n\tif [ $? -ne 0 ]; then\n\t\techo \"Error: could not download $1, exiting\"\n\t\texit 1\n\tfi\n}\n\nsetupSecurity()\n{\n\tsetupCore\n\n    scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\n\n\t#add authentication configuration in app.config\n    _keyFileAbsPath=\"$scriptDir/../$_keyFileName\"\n    IFS='=;' read -r -a array <<< \"$_connectionString\"\n    hostName=${array[1]}\n\tkey=${array[7]}\n    deviceId=${array[3]}\n\techo $key > $_keyFileAbsPath\n\n\n\tauthenticationConfigFile=\"$scriptDir/../Authentication.config\"\n    sed -i -e \"s|\\\"moduleName\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"moduleName\\\" value=\\\"azureiotsecurity\\\"|g\" $authenticationConfigFile \n    sed -i -e \"s|\\\"deviceId\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"deviceId\\\" value=\\\"$deviceId\\\"|g\" $authenticationConfigFile\n    sed -i -e \"s|\\\"gatewayHostname\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"gatewayHostname\\\" value=\\\"$hostName\\\"|g\" $authenticationConfigFile \n    sed -i -e \"s|\\\"type\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"type\\\" value=\\\"SymmetricKey\\\"|g\" $authenticationConfigFile \n    sed -i -e \"s|\\\"identity\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"identity\\\" value=\\\"Module\\\"|g\" $authenticationConfigFile \n    sed -i -e \"s|\\\"filePath\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"filePath\\\" value=\\\"$_keyFileAbsPath\\\"|g\" $authenticationConfigFile \n\n    username=$1\n    echo user is $username\n\n    #find the architecture of the OS and point to the right baseline executable\n    if [ $(uname -m) == 'x86_64' ]; then\n        baselineExe=\"${_omsBaselineX64}\"\n    else\n        baselineExe=\"${_omsBaselineX86}\"\n    fi\n        \n    absoluteBaselineExecutableDirLocation=\"$scriptDir/../$_baselineExecutableDir\"\n    absoluteBaselineExecutableLocation=\"$absoluteBaselineExecutableDirLocation/$baselineExe\"\n\n    mkdir -p \"$scriptDir/../$_baselineExecutableDir\"\n    wgetAndExitOnFail \"${_omsBaselineExecutableGitPath}${_omsAudits}\" \"$absoluteBaselineExecutableDirLocation/$_omsAudits\"\n    wgetAndExitOnFail \"${_omsBaselineExecutableGitPath}${baselineExe}\" \"$absoluteBaselineExecutableLocation\"\n\n    #make baseline file executable\n    chmod +x $absoluteBaselineExecutableLocation\n\n    #replace variables in the sudoers file template\n    sed -e \"s|{USER}|$username|g\" -e \"s|{PATH_TO_OMSBASELINE_EXECUTABLE}|$absoluteBaselineExecutableLocation|g\" $scriptDir/../Install/$_sudoersTemplateName > $_sudoersIncludeDirectory/$_sudoersTemplateName\n}\n\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\nsource \"$_scriptDir/CoreSetupDevEnv.sh\" \"$@\"\n\n#parse command line arguments\nwhile [ \"$1\" != \"\" ]; do\n    case $1 in\n\t\t\t-cs | --connection_string )  shift\n\t\t\t\t             _connectionString=$1\n  \t\t\t\t             ;;\n        -u | --user )               shift\n                                    setupSecurity $1\n                                    ;;\n    esac\n    shift\ndone\n", "num_lines": 85}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n_sudoersTemplateName=\"asotagentsudoers\"\n_sudoersIncludeDirectory=\"/etc/sudoers.d\"\n_baselineExecutableLocationTemplate=\"/BaselineExecutables/\"\n_omsBaselineExecutablePath=\"https://ascforiot.blob.core.windows.net/public/\"\n_baselineDirName=\"BaselineExecutables\"\n_omsAudits=\"oms_audits.xml\"\n_omsBaseline=\"omsbaseline\"\n_omsBaselineX64=\"omsbaseline-linux-amd64\"\n_omsBaselineI386=\"omsbaseline-linux-386\"\n_omsBaselineARMv7=\"omsbaseline-linux-arm-v7\"\n_absoluteBaselineExecutableLocationTemplate=\n_authenticationIdentity=\n_authenticationType=\n_filePath=\n_gwFqdn=\n_deviceId=\n_certificateLocationKind=\n_idScope=\n_registrationId=\n_reboot=false\n_scriptDir=$( cd \"$(dirname \"${BASH_SOURCE[0]}\")\" ; pwd -P )\n_installUsageExtendedDescription=\" -aui <authentication identity> -aum <authentication method> -f <file path> -hn <host name> -di <device id> [-cl <certificate location kind>]\"\n_optionsExtendedDescription=\"\\\n  -aui --authentication-identity    The authentication identity used by the agent (SecurityModule, Device or DPS).\\n\\\n  -aum --authentication-method      The authentication method used by the agent (SymmetricKey or SelfSignedCertificate).\\n\\\n  -f   --file-path                  Path to a file from which data related to the authentication method should be read (the key, certificate or certificate-from-store-info JSON).\\n\\\n  -hn  --host-name                  IoT hub's host name.\\n\\\n  -di  --device-id                  Id of the device the agent is beind installed on (as defined in the IoT hub).\\n\\\n  -cl  --certificate-location-kind  Location kind of certificate being used (LocalFile or Store). Applicable only when the authentication method is set to SelfSignedCertificate.\\n\\\n  -is  --id-scope                   The ID Scope of the DPS service\\n\\\n  -r   --reboot                     Specifies whether to do an automatic reboot when installation finished\\n\\\n  -ri  --registration-id            The registration ID of the device, as registered in the DPS service\"\n\nuninstallSecurityAgent()\n{\n\tuninstallagent\n\n\techo uninstalling agent [security]\n\n\t#remove the sudoers include file\n    rm $_sudoersIncludeDirectory/$_sudoersTemplateName\n\n\techo agent uninstallation finished [security]\n}\n\ninstallSecurityAgent()\n{\n    shouldExit=false\n    \n\tif [ -z \"$_authenticationIdentity\" ]\n    then\n\t\techo \"authentication-identity not provided\"\n        shouldExit=true\n\tfi\n\n    if [ -z \"$_authenticationType\" ]\n    then\n\t\techo \"authentication-method not provided\"\n        shouldExit=true\n\tfi\n\n\tif [ $_authenticationType == 'SelfSignedCertificate' ]\n\tthen\n\t\tif [ -z \"$_certificateLocationKind\" ]\n\t\tthen \n\t\t\techo \"certificate-location-kind not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\tfi\n\n\tif [ -z \"$_filePath\" ]\n\tthen \n\t\techo \"file-path not provided\"\n        shouldExit=true\n\tfi\n\n\tif [ $_authenticationIdentity == 'DPS' ]\n\tthen\n\t\tif [ -z \"$_idScope\" ]\n\t\tthen \n\t\t\techo \"id-scope not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\n\t\tif [ -z \"$_registrationId\" ]\n\t\tthen \n\t\t\techo \"registration-id not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\telse\n\t\tif [ -z \"$_gwFqdn\" ]\n\t\tthen \n\t\t\techo \"host-name not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\n\t\tif [ -z \"$_deviceId\" ]\n\t\tthen \n\t\t\techo \"device-id not provided\"\n\t\t\tshouldExit=true\n\t\tfi\n\tfi\n\n    if $shouldExit\n    then \n        echo \"cannot intall the agent, please check the validity of the supplied parameters\"\n        exit 1\n    fi\n    \n\t#Get oms executables according to systems architecture\n\tbaselineDir=\"$_scriptDir/../$_baselineDirName\"\n\tbaselinePath=\"$baselineDir/$_omsBaseline\"\n\tmkdir -p $baselineDir\n\n\t# download oms_audits.xml\n\twgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsAudits}\" \"$baselineDir/$_omsAudits\"\n\n\t# download omsbaseline supported architecture\n\tcase $(uname -m) in\n    'x86_64')\n\t\twgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineX64}\"  $baselinePath\n\t\t;;\n\t'armv7l')\n\t\twgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineARMv7}\"  $baselinePath\n\t\t;;\n\t'i368')\n\t\twgetAndExitOnFail \"${_omsBaselineExecutablePath}${_omsBaselineI386}\"  $baselinePath\n\t\t;;\n    *)\n\t\techo \"Not supported architecture\"\n        exit 1\n\t\t;;\n\tesac\n    \n\t_baselineExecutableLocationTemplate=\"${_baselineExecutableLocationTemplate}${_omsBaseline}\"\n    _absoluteBaselineExecutableLocationTemplate=$_targetDirectory$_baselineExecutableLocationTemplate\n\n    prepareEnvironment\n\n\t#install security dependencies\n    echo installing agent dependencies\n    apt-get install -y \\\n\t\tauditd \\\n\t\taudispd-plugins \\\n\t\tnet-tools\n\n    #add authentication configuration in app.config\n    sed -i -e \"s|\\\"identity\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"identity\\\" value=\\\"$_authenticationIdentity\\\"|g\" $_targetDirectory/Authentication.config \n\tsed -i -e \"s|\\\"type\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"type\\\" value=\\\"$_authenticationType\\\"|g\" $_targetDirectory/Authentication.config \n    sed -i -e \"s|\\\"filePath\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"filePath\\\" value=\\\"$_filePath\\\"|g\" $_targetDirectory/Authentication.config \n\tsed -i -e \"s|\\\"moduleName\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"moduleName\\\" value=\\\"azureiotsecurity\\\"|g\" $_targetDirectory/Authentication.config \n\tsed -i -e \"s|\\\"certificateLocationKind\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"certificateLocationKind\\\" value=\\\"$_certificateLocationKind\\\"|g\" $_targetDirectory/Authentication.config\n\tif [ $_authenticationIdentity == 'DPS' ]; then\n\t\tsed -i -e \"s|\\\"idScope\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"idScope\\\" value=\\\"$_idScope\\\"|g\" $_targetDirectory/Authentication.config \n\t\tsed -i -e \"s|\\\"registrationId\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"registrationId\\\" value=\\\"$_registrationId\\\"|g\" $_targetDirectory/Authentication.config\n\telse \n\t\tsed -i -e \"s|\\\"gatewayHostname\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"gatewayHostname\\\" value=\\\"$_gwFqdn\\\"|g\" $_targetDirectory/Authentication.config \n\t\tsed -i -e \"s|\\\"deviceId\\\"\\s*value=\\\"[^\\\"]*\\\"|\\\"deviceId\\\" value=\\\"$_deviceId\\\"|g\" $_targetDirectory/Authentication.config\n\tfi\n\n\ttempSudoersPath=$_scriptDir/sudoerstemp\n\n    #replace variables in the sudoers file template\n    sed -e \"s|{USER}|$_userName|g\" -e \"s|{PATH_TO_OMSBASELINE_EXECUTABLE}|$_absoluteBaselineExecutableLocationTemplate|g\" $_scriptDir/$_sudoersTemplateName > $tempSudoersPath\n\t\t\n    visudo -csf $tempSudoersPath\n\n    if [ $? != 0 ];\n    then \n\techo sudoers editing failed, aborting\n\texit $?\n    fi\n\n    cp $tempSudoersPath $_sudoersIncludeDirectory/$_sudoersTemplateName \n\n\t#make baseline file executable\n    chmod +x $_absoluteBaselineExecutableLocationTemplate\n\n\tinstallagent\n\n\tsetupIMAPolicy\n}\n\noriginalArgs=(\"$@\")\nsource \"$_scriptDir/CoreAgentInstallation.sh\" \"$@\"\n\nsetupIMAPolicy(){\n\tmkdir -p /etc/ima\n\techo \"audit func=BPRM_CHECK mask=MAY_EXEC\" > /etc/ima/ima-policy\n    if [[ $_reboot == true ]]\n    then\n        sudo reboot;\n    else\n        echo \"A reboot is required to complete agent installation.\"\n        read  -p \"Do you wish to do it now?[y/n]\" answer\n        case $answer in\n            [Yy]* ) sudo reboot; break;;\n            [Nn]* ) echo \"To take full advantage of the security agent capabilities, make sure you reboot your device later.\";;\n            * ) echo \"Please answer yes or no.\";;\n        esac\n    fi\n}\n\nsetFilePath(){\n\tfile=$1\n\tdir=$(pwd)\n\tif [[ $file == /* ]]\n\tthen\n\t\t_filePath=$file\n\telse\n\t\t_filePath=$dir/$file\n\t\n\tfi\n\tif [ ! -f $_filePath ]; then\n\t\techo \"File $_filePath does not exist!\";\n\t\texit 1;\n\tfi\n}\n\n#parse command line arguments\nwhile [ \"$1\" != \"\" ]; do\n\tcase $1 in\n\t\t-aui | --authentication-identity )  shift\n\t\t\tif [ \"$1\" = \"SecurityModule\" ] || [ \"$1\" = \"Device\" ] || [ \"$1\" = \"DPS\" ]; then\n\t\t\t\t_authenticationIdentity=$1\n\t\t\telse\n\t\t\t\techo \"Possible values for authentication-identity are: SecurityModule or Device\"\n\t\t\t\tusage\n\t\t\t\texit 1\n\t\t\tfi\t\n\t\t\t\t\t\t\t\t\t;;\n\t\t-aum | --authentication-method )  shift\n\t\t\tif [ \"$1\" = \"SymmetricKey\" ] || [ \"$1\" = \"SelfSignedCertificate\" ]; then\n\t\t\t\t_authenticationType=$1\n\t\t\telse\n\t\t\t\techo \"Possible values for authentication-method are: SymmetricKey or SelfSignedCertificate\"\n\t\t\t\tusage\n\t\t\t\texit 1\n\t\t\tfi\t\n\t\t\t\t\t\t\t\t\t;;\t\t\n\t\t-f | --file-path )  shift\n\t\t\t\t\t\t\t\t\tsetFilePath $1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-hn | --host-name )  shift\n\t\t\t\t\t\t\t\t\t_gwFqdn=$1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-di | --device-id)  shift\n\t\t\t\t\t\t\t\t\t_deviceId=$1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-r | --reboot )     shift\n                                    _reboot=true\n                                    ;;\n\t\t-is | --id-scope)  shift\n\t\t\t\t\t\t\t\t\t_idScope=$1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-ri | --registration-id)  shift\n\t\t\t\t\t\t\t\t\t_registrationId=$1\n\t\t\t\t\t\t\t\t\t;;\n\t\t-cl | --certificate-location-kind ) shift\n\t\t\tif [ \"$1\" = \"LocalFile\" ] || [ \"$1\" = \"Store\" ]; then\n\t\t\t\t\t_certificateLocationKind=$1\n\t\t\telse\n\t\t\t\techo \"Possible values for certificate-location-kind are: LocalFile or Store\"\n\t\t\t\tusage\n\t\t\t\texit 1\n\t\t\tfi\t\n\tesac\n\tshift\ndone\n\n# override defaults\n_serviceName=\"ASCIoTAgent\"\nupdateServiceNameDependentFields\n_userName=\"asciotagent\"\n_serviceDescription=\"Azure Security Center for IoT Agent\"\n_execName=\"ASCIoTAgent\"\n\n_authenticationIdentity=${_authenticationIdentity/SecurityModule/Module}\n\nif [[ $_mode == \"uninstall\" ]] \nthen\n    uninstallSecurityAgent\nelif [[ $_mode == \"install\" ]] \nthen\n    installSecurityAgent\nelse\n\tusage\nfi", "num_lines": 290}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\npushd \"$PWD\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\ncd \"$DIR/../Agent/Linux\"\ndotnet build --no-restore\nagentLinuxEX=$?\n\ncd \"$DIR/../Modules/Security/Linux\"\ndotnet build --no-restore\nsecurityLinuxEX=$?\n\npopd\n\nif [ \"$agentLinuxEX\" -ne \"0\" ] || [ \"$securityLinuxEX\" -ne \"0\" ]; \nthen\n    echo \"Build failed\"\n\texit \"1\"\nelse\n\texit \"0\"\nfi\n", "num_lines": 23}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\npushd \"$PWD\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\ncd \"$DIR/..\"\ndotnet restore --source https://api.nuget.org/v3/index.json\nEX=$?\n\npopd\n\nif [ \"$EX\" -ne \"0\" ]; then\n    echo \"Failed to restore\"\nfi\n\nexit $EX", "num_lines": 16}
{"repo_name": "Azure-IoT-Security-Agent-CS", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\npushd \"$PWD\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\ncd \"$DIR\"\ndotnet test --logger \"trx;LogFileName=AgentCore.trx\" --results-directory TestResults ../Agent/Tests/Core\nagentCoreEX=$?\n\ndotnet test --logger \"trx;LogFileName=SecurityCommon.trx\" --results-directory TestResults ../Modules/Security/Tests/Common\nsecurityCommonEX=$?\n\ndotnet test --logger \"trx;LogFileName=SecurityLinux.trx\" --results-directory TestResults ../Modules/Security/Tests/Linux\nsecurityLinuxEX=$?\n\npopd\n\nif [ \"$agentCoreEX\" -ne \"0\" ] || [ \"$securityCommonEX\" -ne \"0\" ] || [ \"$securityLinuxEX\" -ne \"0\" ]; \nthen\n    echo \"Tests failed\"\n\texit \"1\"\nelse\n\texit \"0\"\nfi\n", "num_lines": 25}
{"repo_name": "azure-iot-service-sdk-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This APK file is generated by the Android build task and then is copied into the android test run task. If the APK file\n# is missing, then either the copy failed, or the APK was never successfully built.\nif [ ! -f \"iot-e2e-tests/android/app/build/outputs/apk/debug/app-debug.apk\" ]; then\n    echo 'Missing expected apk file. Android build task likely failed silently.'\n    exit -1\nfi\n\nif [ ! -f \"iot-e2e-tests/android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk\" ]; then\n    echo 'Missing expected apk file. Android build task likely failed silently.'\n    exit -1\nfi\n\n# -e flag to force this command to run on what should be the only emulator active on this machine\necho 'Installing APKs on emulator'\nadb -e install -r iot-e2e-tests/android/app/build/outputs/apk/debug/app-debug.apk\nadb -e install -r iot-e2e-tests/android/app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk\n\n#List instrumentation classes, for logging purposes only\necho 'Listing available instrumentations:'\nadb -e shell pm list instrumentation\necho ''\n\nannotationString=\"com.microsoft.azure.sdk.iot.android.helper.${TEST_GROUP_ID}\"\necho 'Running android tests with annotation'\necho $annotationString\n\n#Return code from adb shell isn't returned as one would expect. Need to capture output logs and analyze them to determine if this test run was a success or not\nTestLogs=$(adb -e shell am instrument -w -e annotation $annotationString com.iothub.azure.microsoft.com.androide2e.test/android.support.test.runner.AndroidJUnitRunner)\n\necho 'Result of running tests'\necho \"$TestLogs\"\n\n#This string is always present in the output logs from android testing if a test failed. Hacky, but there is no return code\n# to check instead.\nFailureMessage='FAILURES!!!'\n\nif grep -q \"$FailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Test failures detected, exiting...'\n    exit -1\nfi\n\nInstrumentationFailureMessage='INSTRUMENTATION_STATUS_CODE: -1'\n\nif grep -q \"$InstrumentationFailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Instrumentation failures detected, exiting...'\n    exit -1\nfi\n\nAnotherInstrumentationFailureMessage='INSTRUMENTATION_FAILED'\nif grep -q \"$AnotherInstrumentationFailureMessage\" <<< \"$TestLogs\"; then\n    echo 'Instrumentation failures detected, exiting...'\n    exit -1\nfi\n\n# adb also supports running all tests that do not have a given annotation\n# adb -e shell am instrument -w -e notAnnotation com.microsoft.azure.sdk.iot.android.helper.TestGroup39 com.iothub.azure.microsoft.com.androide2e.test/android.support.test.runner.AndroidJUnitRunner", "num_lines": 58}
{"repo_name": "azure-iot-service-sdk-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho 'Listing available android sdks for installation'\n$ANDROID_HOME/tools/bin/sdkmanager --list | grep system-images\n\nemulatorImage='system-images;android-28;google_apis;x86_64'\navdName='Pixel_9.0'\n\necho ''\necho \"Installing emulator image ${emulatorImage}\"\necho \"y\" | $ANDROID_HOME/tools/bin/sdkmanager --install $emulatorImage\n\necho ''\necho \"Creating android emulator with name ${avdName}\"\necho \"no\" | $ANDROID_HOME/tools/bin/avdmanager create avd -n $avdName -k $emulatorImage --force\n\necho ''\necho 'Listing active android emulators'\n$ANDROID_HOME/emulator/emulator -list-avds\n\necho ''\necho \"Starting emulator in background thread\"\nnohup $ANDROID_HOME/emulator/emulator -avd $avdName -gpu auto -no-snapshot > /dev/null 2>&1 &\n\necho ''\necho 'Waiting for emulator to boot up...'\n$ANDROID_HOME/platform-tools/adb wait-for-device shell 'while [[ -z $(getprop sys.boot_completed | tr -d '\\r') ]]; do sleep 1; done; input keyevent 82'\necho ''\necho \"Emulator started\"\n\n$ANDROID_HOME/platform-tools/adb devices\n\n", "num_lines": 33}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# make sure we have correct version of code generator\ncd $GOPATH/src/k8s.io/code-generator/\n\n# https://stackoverflow.com/a/6245587/697126\ncurrentbranch=$(git branch | grep \\* | cut -d ' ' -f2)\n\nif [[ $currentbranch != \"release-1.14\" ]]\nthen\n  git fetch --all\n  git checkout -t origin/release-1.14\nelse \n  echo \"on correct branch\"\nfi\n\n\n\n", "num_lines": 23}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Adapted for this project from cert-manager\n# License: https://github.com/jetstack/cert-manager/blob/master/LICENSE\n# Script: https://github.com/jetstack/cert-manager/blob/master/hack/update-deploy-gen.sh\nset -euo pipefail\nIFS=$'\\n\\t'\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")\nREPO_ROOT=\"${SCRIPT_ROOT}/..\"\n\ngen() {\n\tOUTPUT=$1\n    VALUES_PATH=\"\"\n\tTMP_OUTPUT=$(mktemp)\n\tmkdir -p \"$(dirname ${OUTPUT})\"\n    VALUES=${2:-}\n    if [[ ! -z \"$VALUES\" ]]; then\n        VALUES_PATH=\"--values=${SCRIPT_ROOT}/deploy/values/${VALUES}.yaml\"\n    fi\n    helm template \\\n        \"${REPO_ROOT}/charts/azure-k8s-metrics-adapter/\" \\\n        --namespace \"custom-metrics\" \\\n        --name \"azure-k8s-metrics-adapter\" \\\n        --set \"fullnameOverride=azure-k8s-metrics-adapter\" \\\n\t\t--set \"createNamespaceResource=true\" > \"${TMP_OUTPUT}\" \\\n        ${VALUES_PATH}\n    \n\tmv \"${TMP_OUTPUT}\" \"${OUTPUT}\"\n}\n\n# Additional deployment files can be generated here with the following format:\n#   gen /path/to/deployment-file.yaml [values.yaml file name in deploy/values]\n#   gen ${REPO_ROOT}/deploy/adapter.yaml the-values \ngen \"${REPO_ROOT}/deploy/adapter.yaml\"\n", "num_lines": 36}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\n\nDIVIDER=\"============================================================\"\n\necho \"Checking for a current cluster context\"\nkubectl config current-context\n\necho; echo \"Checking that cluster nodes are ready\"\nJSONPATH='{range .items[*]}{@.metadata.name}{\"\\t\"}Ready={@.status.conditions[?(@.type==\"Ready\")].status}{\"\\n\"}{end}'\nkubectl get nodes -o jsonpath=\"$JSONPATH\"\nif kubectl get nodes -o jsonpath=\"$JSONPATH\" | grep \"Ready=False\"; then\n    exit 1\nfi\n\necho; echo \"Checking helm and tiller install\"\nhelm version\n\necho; echo \"Checking for other pre-reqs\"\nwhich jq        # Used to format some command output\nwhich docker\n\n# If the script fails on error here, the deployment won't be cleaned up properly\nset +o errexit \n\necho; echo \"Running deployment scripts\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/hack/e2e-scripts\nchmod +x *.sh\n\nTEST_FAILED=0\n\n./deploy-adapter-with-sp.sh\nif [[ $? = 0 ]]; then\n    echo \"Testing Queue (Azure Monitor) metrics\"\n    ./configure-queue-metrics.sh\n    ./gen-and-check-queue-messages.sh\n    if [[ $? = 0 ]];\n        then echo $DIVIDER; echo \"PASS\"; echo $DIVIDER\n        else echo $DIVIDER; echo \"FAIL\"; echo $DIVIDER; TEST_FAILED=1;\n    fi\n\n    ./run-queue-consumer.sh\n\n    echo \"Testing Topic Subscriptions metrics\"\n    ./configure-topic-subscriptions-metrics.sh\n    ./gen-and-check-topic-subscriptions-messages.sh\n    if [[ $? = 0 ]];\n        then echo $DIVIDER; echo \"PASS\"; echo $DIVIDER\n        else echo $DIVIDER; echo \"FAIL\"; echo $DIVIDER; TEST_FAILED=1;\n    fi\n\n    ./run-topic-consumer.sh\nelse\n    echo $DIVIDER; echo \"FAIL\"; echo $DIVIDER; TEST_FAILED=1;\nfi\n\necho \"Removing adapter deployment\"\nhelm delete --purge adapter\n\nif [[ $TEST_FAILED == 1 ]]; then\n    echo $DIVIDER; echo \"FAIL\"; echo $DIVIDER;\n    exit 1\nfi\n", "num_lines": 69}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nCGO_ENABLED=0 go test $(go list ./... | grep -v -e '/client/' -e '/samples/' -e '/apis/')\n", "num_lines": 8}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE[0]}\")/..\nCODEGEN_PKG=${CODEGEN_PKG:-$(cd \"${SCRIPT_ROOT}\"; ls -d -1 ./vendor/k8s.io/code-generator 2>/dev/null || echo ../code-generator)}\nchmod +x ${CODEGEN_PKG}/generate-groups.sh\n\n\"${CODEGEN_PKG}\"/generate-groups.sh all \\\n    github.com/Azure/azure-k8s-metrics-adapter/pkg/client \\\n    github.com/Azure/azure-k8s-metrics-adapter/pkg/apis \\\n    metrics:v1alpha2 \\\n    --go-header-file \"${SCRIPT_ROOT}\"/hack/boilerplate.go.txt\n", "num_lines": 16}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n#\n# Modified under license:\n#\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nPROJECT_ROOT=$(dirname \"${BASH_SOURCE}\")/..\n\nDIFFROOT=\"${PROJECT_ROOT}/pkg/apis\"\nTMP_DIFFROOT=\"${PROJECT_ROOT}/_tmp/pkg/apis\"\n_tmp=\"${PROJECT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${PROJECT_ROOT}/hack/update-codegen.sh\"\necho \"diffing ${DIFFROOT} against freshly generated codegen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/update-codegen.sh\"\n  exit 1\nfi\n", "num_lines": 51}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Adapted for this project from cert-manager\n# License: https://github.com/jetstack/cert-manager/blob/master/LICENSE\n# Script: https://github.com/jetstack/cert-manager/blob/master/hack/verify-deploy-gen.sh\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\nSCRIPT_ROOT=$(dirname \"${BASH_SOURCE}\")/..\n\nDIFFROOT=\"${SCRIPT_ROOT}/deploy\"\nTMP_DIFFROOT=\"${SCRIPT_ROOT}/_tmp/deploy/manifests\"\n_tmp=\"${SCRIPT_ROOT}/_tmp\"\n\ncleanup() {\n  rm -rf \"${_tmp}\"\n}\ntrap \"cleanup\" EXIT SIGINT\n\ncleanup\n\nmkdir -p \"${TMP_DIFFROOT}\"\ncp -a \"${DIFFROOT}\"/* \"${TMP_DIFFROOT}\"\n\n\"${SCRIPT_ROOT}/hack/gen-deploy.sh\"\necho \"diffing ${DIFFROOT} against freshly deploy-gen\"\nret=0\ndiff -Naupr \"${DIFFROOT}\" \"${TMP_DIFFROOT}\" || ret=$?\ncp -a \"${TMP_DIFFROOT}\"/* \"${DIFFROOT}\"\nif [[ $ret -eq 0 ]]\nthen\n  echo \"${DIFFROOT} up to date.\"\nelse\n  echo \"${DIFFROOT} is out of date. Please run hack/gen-deploy.sh\"\n  exit 1\nfi", "num_lines": 38}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o errexit\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\nSERVICEBUS_QUEUE_NAME=\"${SERVICEBUS_QUEUE_NAME:-externalq}\"\n\n\necho; echo \"Configuring external metric (queuemessages)...\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/\ncp deploy/externalmetric.yaml deploy/externalmetric.yaml.copy\n\nsed -i 's|sb-external-ns|'${SERVICEBUS_NAMESPACE}'|g' deploy/externalmetric.yaml\nsed -i 's|sb-external-example|'${SERVICEBUS_RESOURCE_GROUP}'|g' deploy/externalmetric.yaml\nsed -i 's|externalq|'${SERVICEBUS_QUEUE_NAME}'|g' deploy/externalmetric.yaml\n\nAGGREGATE_TYPE=( \"average\" \"maximum\" \"minimum\" \"total\" )\n# supported aggregates https://github.com/Azure/azure-sdk-for-go/blob/0acfc1d1083d148a606d380143176e218d437728/services/preview/monitor/mgmt/2018-03-01/insights/models.go#L38\nfor AGGREGATE in \"${AGGREGATE_TYPE[@]}\"\ndo\n    filePath=\"deploy/${AGGREGATE}.externalmetric.yaml\"\n    echo \"Creating ${AGGREGATE} external metric with file: $filePath\"\n    cp deploy/externalmetric.yaml $filePath\n\n    # give a name to the external metric\n    sed -i 's|queuemessages|queuemessages-'${AGGREGATE}'|g' $filePath\n\n    # specify the aggregate type\n    sed -i 's|Total|'${AGGREGATE}'|g' $filePath\n\n    kubectl apply -f $filePath\ndone\n\nrm deploy/*externalmetric.yaml; mv deploy/externalmetric.yaml.copy deploy/externalmetric.yaml", "num_lines": 35}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o errexit\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\nSERVICEBUS_TOPIC_NAME=\"${SERVICEBUS_TOPIC_NAME:-example-topic}\"\nSERVICEBUS_SUBSCRIPTION_NAME=\"${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}\"\n\necho; echo \"Configuring external metric (subscriptionmessages)...\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/resources/externalmetric-examples/\ncp servicebussubscription-example.yaml servicebussubscription-example.yaml.copy\n\nsed -i 's|sb-external-ns|'${SERVICEBUS_NAMESPACE}'|g' servicebussubscription-example.yaml\nsed -i 's|sb-external-example|'${SERVICEBUS_RESOURCE_GROUP}'|g' servicebussubscription-example.yaml\nsed -i 's|example-topic|'${SERVICEBUS_TOPIC_NAME}'|g' servicebussubscription-example.yaml\nsed -i 's|example-sub|'${SERVICEBUS_SUBSCRIPTION_NAME}'|g' servicebussubscription-example.yaml\nkubectl apply -f servicebussubscription-example.yaml\n\nrm servicebussubscription-example.yaml; mv servicebussubscription-example.yaml.copy servicebussubscription-example.yaml\n", "num_lines": 21}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o errexit\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\n\necho; echo \"Deploying metrics adapter...\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter\n# If SP values are set via env vars, use them; otherwise, just use values file\nif [[ -v SP_CLIENT_ID ]]; then\n    helm install --name adapter \\\n        --set azureAuthentication.tenantID=$SP_TENANT_ID \\\n        --set azureAuthentication.clientID=$SP_CLIENT_ID \\\n        --set azureAuthentication.clientSecret=$SP_CLIENT_SECRET \\\n        -f ./local-dev-values.yaml \\\n        ./charts/azure-k8s-metrics-adapter\nelse\n    helm install --name adapter \\\n        -f ./local-dev-values.yaml \\\n        ./charts/azure-k8s-metrics-adapter\nfi\n\necho; echo \"Waiting for deployment to be available...\"\nSTART=`date +%s`\n\nkubectl get deploy/adapter-azure-k8s-metrics-adapter\nwhile [[ ! `kubectl get deploy/adapter-azure-k8s-metrics-adapter -o jsonpath=\"{@.status.availableReplicas}\"` = 1 ]] && \\\n        [[ $(( $(date +%s) - 55 )) -lt $START ]]; do \n    sleep 5\n    kubectl get deploy/adapter-azure-k8s-metrics-adapter --no-headers\ndone\n\nif [[ ! `kubectl get deploy/adapter-azure-k8s-metrics-adapter -o jsonpath=\"{@.status.availableReplicas}\"` = 1 ]]; then\n    echo; echo \"Deployment failed, output debug information\"\n    kubectl describe deploy/adapter-azure-k8s-metrics-adapter\n    echo\n    kubectl logs deploy/adapter-azure-k8s-metrics-adapter\n    exit 1\nfi", "num_lines": 40}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o errexit\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\nSERVICEBUS_QUEUE_NAME=\"${SERVICEBUS_QUEUE_NAME:-externalq}\"\n\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/\n\necho; echo \"Building producer and consumer...\"\nmake\n\necho; echo \"Creating random number for producer...\"\nNUM=$(( ($RANDOM % 30 )  + 1 ))\n\necho; echo \"Sending $NUM messages...\"\n./bin/producer 0 $NUM $SERVICEBUS_QUEUE_NAME> /dev/null\n\necho; echo \"Checking metrics endpoint for 4 minutes...\"\n\nMSGCOUNT=$(kubectl get --raw \"/apis/external.metrics.k8s.io/v1beta1/namespaces/default/queuemessages-total\" | jq .items[0].value)\nSTART=`date +%s`\n\nwhile [[ ! \"$MSGCOUNT\" = \"\\\"$NUM\\\"\" ]] && [[ $(( $(date +%s) - 225 )) -lt $START ]]; do\n  sleep 15\n  MSGCOUNT=$(kubectl get --raw \"/apis/external.metrics.k8s.io/v1beta1/namespaces/default/queuemessages-total\" | jq .items[0].value)\n  echo \"Endpoint returned $MSGCOUNT messages\"\ndone\n\nAGGREGATE_TYPE=( \"average\" \"maximum\" \"minimum\" \"total\" )\nfor AGGREGATE in \"${AGGREGATE_TYPE[@]}\"\ndo\n    METRIC_NAME=\"queuemessages-${AGGREGATE}\"\n    VALUE=$(kubectl get --raw \"/apis/external.metrics.k8s.io/v1beta1/namespaces/default/${METRIC_NAME}\" | jq .items[0].value)\n    if [[ ! \"$VALUE\" = \"\\\"$NUM\\\"\" ]]; then\n        echo \"Timed out, message aggregate type: ${AGGREGATE} value: ${VALUE} not equal to number of messages sent ($NUM)\"\n        exit 1\n    else\n        echo \"message aggregate type: ${AGGREGATE} value: ${VALUE} is equal to number of messages sent ($NUM), metrics adapter working correctly\"\n    fi\ndone\n", "num_lines": 43}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\nset -o errexit\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\nSERVICEBUS_TOPIC_NAME=\"${SERVICEBUS_TOPIC_NAME:-example-topic}\"\nSERVICEBUS_SUBSCRIPTION_NAME=\"${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}\"\n\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/\n\necho; echo \"Building producer and consumer...\"\nmake\n\necho; echo \"Creating random number for producer script...\"\nNUM=$(( ($RANDOM % 30 )  + 1 ))\n\necho; echo \"Sending $NUM messages...\"\n./bin/producer 0 $NUM $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME > /dev/null\n\necho; echo \"Checking metrics endpoint for 4 minutes...\"\n\nMSGCOUNT=$(kubectl get --raw \"/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription\" | jq .items[0].value)\nSTART=`date +%s`\n\nwhile [[ ! \"$MSGCOUNT\" = \"\\\"$NUM\\\"\" ]] && [[ $(( $(date +%s) - 225 )) -lt $START ]]; do\n  sleep 15\n  MSGCOUNT=$(kubectl get --raw \"/apis/external.metrics.k8s.io/v1beta1/namespaces/default/example-external-metric-service-bus-subscription\" | jq .items[0].value)\n  echo \"Endpoint returned $MSGCOUNT messages\"\ndone\n\nif [[ ! \"$MSGCOUNT\" = \"\\\"$NUM\\\"\" ]]; then\n    echo \"Timed out, message count ($MSGCOUNT) not equal to number of messages sent ($NUM)\"\n    exit 1\nelse\n    echo \"Message count equal to number of messages sent, metrics adapter working correctly\"\nfi\n", "num_lines": 38}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\nSERVICEBUS_QUEUE_NAME=\"${SERVICEBUS_QUEUE_NAME:-externalq}\"\n\necho; echo \"Running queue consumer to clear queue\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-queue/\n\ntimeout 30 ./bin/consumer $SERVICEBUS_QUEUE_NAME> /dev/null\n\n# Exit status 124 just means timeout completed, which is what we expect\nif [[ $? = 124 ]]; then \n    echo \"Consumer timed out as expected\"\n    exit 0\nfi\n\n", "num_lines": 19}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -o nounset\n\nGOPATH=\"${GOPATH:-$HOME/go}\"\n\nSERVICEBUS_TOPIC_NAME=\"${SERVICEBUS_TOPIC_NAME:-example-topic}\"\nSERVICEBUS_SUBSCRIPTION_NAME=\"${SERVICEBUS_SUBSCRIPTION_NAME:-externalsub}\"\n\necho; echo \"Running consumer to clear topic\"\ncd $GOPATH/src/github.com/Azure/azure-k8s-metrics-adapter/samples/servicebus-topic/\n\ntimeout 30 ./bin/consumer $SERVICEBUS_TOPIC_NAME $SERVICEBUS_SUBSCRIPTION_NAME> /dev/null\n\n# Exit status 124 just means timeout completed, which is what we expect\nif [[ $? = 124 ]]; then \n    echo \"Consumer timed out as expected\"\n    exit 0\nfi\n\n", "num_lines": 21}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#go test -run=none -file bench_test.go -test.bench . -cpuprofile=bench_test.out\n\ngo test -c\n./go-restful.test -test.run=none -test.cpuprofile=tmp.prof -test.bench=BenchmarkMany\n./go-restful.test -test.run=none -test.cpuprofile=curly.prof -test.bench=BenchmarkManyCurly\n\n#go tool pprof go-restful.test tmp.prof\ngo tool pprof go-restful.test curly.prof\n\n\n", "num_lines": 11}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "go test -coverprofile=coverage.out\ngo tool cover -html=coverage.out", "num_lines": 2}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "go get github.com/golang/protobuf/protoc-gen-go\n\nprotoc \\\n--go_out=Mgoogle/protobuf/any.proto=github.com/golang/protobuf/ptypes/any:. *.proto \n\n", "num_lines": 6}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    echo -e \"TESTS FOR: for \\033[0;35m${d}\\033[0m\"\n    go test -race -v -coverprofile=profile.coverage.out -covermode=atomic $d\n    if [ -f profile.coverage.out ]; then\n        cat profile.coverage.out >> coverage.txt\n        rm profile.coverage.out\n    fi\n    echo \"\"\ndone\n", "num_lines": 15}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nset -x\n\nif [ ! -d /tmp/build-golang/src/github.com/json-iterator ]; then\n    mkdir -p /tmp/build-golang/src/github.com/json-iterator\n    ln -s $PWD /tmp/build-golang/src/github.com/json-iterator/go\nfi\nexport GOPATH=/tmp/build-golang\ngo get -u github.com/golang/dep/cmd/dep\ncd /tmp/build-golang/src/github.com/json-iterator/go\nexec $GOPATH/bin/dep ensure -update\n", "num_lines": 13}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/json-iterator/go $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list ./... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/concurrent $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\necho \"\" > coverage.txt\n\nfor d in $(go list github.com/modern-go/reflect2-tests/... | grep -v vendor); do\n    go test -coverprofile=profile.out -coverpkg=github.com/modern-go/reflect2 $d\n    if [ -f profile.out ]; then\n        cat profile.out >> coverage.txt\n        rm profile.out\n    fi\ndone\n", "num_lines": 13}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# This script runs or (given -n) prints suggested commands to generate files for\n# the Architecture/OS specified by the GOARCH and GOOS environment variables.\n# See README.md for more information about how the build system works.\n\nGOOSARCH=\"${GOOS}_${GOARCH}\"\n\n# defaults\nmksyscall=\"go run mksyscall.go\"\nmkerrors=\"./mkerrors.sh\"\nzerrors=\"zerrors_$GOOSARCH.go\"\nmksysctl=\"\"\nzsysctl=\"zsysctl_$GOOSARCH.go\"\nmksysnum=\nmktypes=\nmkasm=\nrun=\"sh\"\ncmd=\"\"\n\ncase \"$1\" in\n-syscalls)\n\tfor i in zsyscall*go\n\tdo\n\t\t# Run the command line that appears in the first line\n\t\t# of the generated file to regenerate it.\n\t\tsed 1q $i | sed 's;^// ;;' | sh > _$i && gofmt < _$i > $i\n\t\trm _$i\n\tdone\n\texit 0\n\t;;\n-n)\n\trun=\"cat\"\n\tcmd=\"echo\"\n\tshift\nesac\n\ncase \"$#\" in\n0)\n\t;;\n*)\n\techo 'usage: mkall.sh [-n]' 1>&2\n\texit 2\nesac\n\nif [[ \"$GOOS\" = \"linux\" ]]; then\n\t# Use the Docker-based build system\n\t# Files generated through docker (use $cmd so you can Ctl-C the build or run)\n\t$cmd docker build --tag generate:$GOOS $GOOS\n\t$cmd docker run --interactive --tty --volume $(dirname \"$(readlink -f \"$0\")\"):/build generate:$GOOS\n\texit\nfi\n\nGOOSARCH_in=syscall_$GOOSARCH.go\ncase \"$GOOSARCH\" in\n_* | *_ | _)\n\techo 'undefined $GOOS_$GOARCH:' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\naix_ppc)\n\tmkerrors=\"$mkerrors -maix32\"\n\tmksyscall=\"go run mksyscall_aix_ppc.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\naix_ppc64)\n\tmkerrors=\"$mkerrors -maix64\"\n\tmksyscall=\"go run mksyscall_aix_ppc64.go -aix\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\ndarwin_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk macosx)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndarwin_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go $(xcrun --show-sdk-path --sdk iphoneos)/usr/include/sys/syscall.h\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\tmkasm=\"go run mkasm_darwin.go\"\n\t;;\ndragonfly_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -dragonfly\"\n\tmksysnum=\"go run mksysnum.go 'https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nfreebsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -arm\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nfreebsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\"go run mksysnum.go 'https://svn.freebsd.org/base/stable/11/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nnetbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -netbsd -arm\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nnetbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -netbsd\"\n\tmksysnum=\"go run mksysnum.go 'http://cvsweb.netbsd.org/bsdweb.cgi/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_386)\n\tmkerrors=\"$mkerrors -m32\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_amd64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\nopenbsd_arm)\n\tmkerrors=\"$mkerrors\"\n\tmksyscall=\"go run mksyscall.go -l32 -openbsd -arm\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nopenbsd_arm64)\n\tmkerrors=\"$mkerrors -m64\"\n\tmksyscall=\"go run mksyscall.go -openbsd\"\n\tmksysctl=\"go run mksysctl_openbsd.go\"\n\tmksysnum=\"go run mksysnum.go 'https://cvsweb.openbsd.org/cgi-bin/cvsweb/~checkout~/src/sys/kern/syscalls.master'\"\n\t# Let the type of C char be signed for making the bare syscall\n\t# API consistent across platforms.\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs -- -fsigned-char\"\n\t;;\nsolaris_amd64)\n\tmksyscall=\"go run mksyscall_solaris.go\"\n\tmkerrors=\"$mkerrors -m64\"\n\tmksysnum=\n\tmktypes=\"GOARCH=$GOARCH go tool cgo -godefs\"\n\t;;\n*)\n\techo 'unrecognized $GOOS_$GOARCH: ' \"$GOOSARCH\" 1>&2\n\texit 1\n\t;;\nesac\n\n(\n\tif [ -n \"$mkerrors\" ]; then echo \"$mkerrors |gofmt >$zerrors\"; fi\n\tcase \"$GOOS\" in\n\t*)\n\t\tsyscall_goos=\"syscall_$GOOS.go\"\n\t\tcase \"$GOOS\" in\n\t\tdarwin | dragonfly | freebsd | netbsd | openbsd)\n\t\t\tsyscall_goos=\"syscall_bsd.go $syscall_goos\"\n\t\t\t;;\n\t\tesac\n\t\tif [ -n \"$mksyscall\" ]; then\n\t\t\tif [ \"$GOOSARCH\" == \"aix_ppc64\" ]; then\n\t\t\t\t# aix/ppc64 script generates files instead of writing to stdin.\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in && gofmt -w zsyscall_$GOOSARCH.go && gofmt -w zsyscall_\"$GOOSARCH\"_gccgo.go && gofmt -w zsyscall_\"$GOOSARCH\"_gc.go \" ;\n\t\t\telif [ \"$GOOS\" == \"darwin\" ]; then\n\t\t\t        # pre-1.12, direct syscalls\n\t\t\t        echo \"$mksyscall -tags $GOOS,$GOARCH,!go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.1_11.go\";\n\t\t\t        # 1.12 and later, syscalls via libSystem\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH,go1.12 $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\telse\n\t\t\t\techo \"$mksyscall -tags $GOOS,$GOARCH $syscall_goos $GOOSARCH_in |gofmt >zsyscall_$GOOSARCH.go\";\n\t\t\tfi\n\t\tfi\n\tesac\n\tif [ -n \"$mksysctl\" ]; then echo \"$mksysctl |gofmt >$zsysctl\"; fi\n\tif [ -n \"$mksysnum\" ]; then echo \"$mksysnum |gofmt >zsysnum_$GOOSARCH.go\"; fi\n\tif [ -n \"$mktypes\" ]; then echo \"$mktypes types_$GOOS.go | go run mkpost.go > ztypes_$GOOSARCH.go\"; fi\n\tif [ -n \"$mkasm\" ]; then echo \"$mkasm $GOARCH\"; fi\n) | $run\n", "num_lines": 228}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# Copyright 2009 The Go Authors. All rights reserved.\n# Use of this source code is governed by a BSD-style\n# license that can be found in the LICENSE file.\n\n# Generate Go code listing errors and other #defined constant\n# values (ENAMETOOLONG etc.), by asking the preprocessor\n# about the definitions.\n\nunset LANG\nexport LC_ALL=C\nexport LC_CTYPE=C\n\nif test -z \"$GOARCH\" -o -z \"$GOOS\"; then\n\techo 1>&2 \"GOARCH or GOOS not defined in environment\"\n\texit 1\nfi\n\n# Check that we are using the new build system if we should\nif [[ \"$GOOS\" = \"linux\" ]] && [[ \"$GOLANG_SYS_BUILD\" != \"docker\" ]]; then\n\techo 1>&2 \"In the Docker based build system, mkerrors should not be called directly.\"\n\techo 1>&2 \"See README.md\"\n\texit 1\nfi\n\nif [[ \"$GOOS\" = \"aix\" ]]; then\n\tCC=${CC:-gcc}\nelse\n\tCC=${CC:-cc}\nfi\n\nif [[ \"$GOOS\" = \"solaris\" ]]; then\n\t# Assumes GNU versions of utilities in PATH.\n\texport PATH=/usr/gnu/bin:$PATH\nfi\n\nuname=$(uname)\n\nincludes_AIX='\n#include <net/if.h>\n#include <net/netopt.h>\n#include <netinet/ip_mroute.h>\n#include <sys/protosw.h>\n#include <sys/stropts.h>\n#include <sys/mman.h>\n#include <sys/poll.h>\n#include <sys/termio.h>\n#include <termios.h>\n#include <fcntl.h>\n\n#define AF_LOCAL AF_UNIX\n'\n\nincludes_Darwin='\n#define _DARWIN_C_SOURCE\n#define KERNEL\n#define _DARWIN_USE_64_BIT_INODE\n#include <stdint.h>\n#include <sys/attr.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/ptrace.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/utsname.h>\n#include <sys/wait.h>\n#include <sys/xattr.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <termios.h>\n'\n\nincludes_DragonFly='\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <net/ip_mroute/ip_mroute.h>\n'\n\nincludes_FreeBSD='\n#include <sys/capsicum.h>\n#include <sys/param.h>\n#include <sys/types.h>\n#include <sys/event.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <sys/extattr.h>\n\n#if __FreeBSD__ >= 10\n#define IFT_CARP\t0xf8\t// IFT_CARP is deprecated in FreeBSD 10\n#undef SIOCAIFADDR\n#define SIOCAIFADDR\t_IOW(105, 26, struct oifaliasreq)\t// ifaliasreq contains if_data\n#undef SIOCSIFPHYADDR\n#define SIOCSIFPHYADDR\t_IOW(105, 70, struct oifaliasreq)\t// ifaliasreq contains if_data\n#endif\n'\n\nincludes_Linux='\n#define _LARGEFILE_SOURCE\n#define _LARGEFILE64_SOURCE\n#ifndef __LP64__\n#define _FILE_OFFSET_BITS 64\n#endif\n#define _GNU_SOURCE\n\n// <sys/ioctl.h> is broken on powerpc64, as it fails to include definitions of\n// these structures. We just include them copied from <bits/termios.h>.\n#if defined(__powerpc__)\nstruct sgttyb {\n        char    sg_ispeed;\n        char    sg_ospeed;\n        char    sg_erase;\n        char    sg_kill;\n        short   sg_flags;\n};\n\nstruct tchars {\n        char    t_intrc;\n        char    t_quitc;\n        char    t_startc;\n        char    t_stopc;\n        char    t_eofc;\n        char    t_brkc;\n};\n\nstruct ltchars {\n        char    t_suspc;\n        char    t_dsuspc;\n        char    t_rprntc;\n        char    t_flushc;\n        char    t_werasc;\n        char    t_lnextc;\n};\n#endif\n\n#include <bits/sockaddr.h>\n#include <sys/epoll.h>\n#include <sys/eventfd.h>\n#include <sys/inotify.h>\n#include <sys/ioctl.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/prctl.h>\n#include <sys/stat.h>\n#include <sys/types.h>\n#include <sys/time.h>\n#include <sys/signalfd.h>\n#include <sys/socket.h>\n#include <sys/xattr.h>\n#include <linux/bpf.h>\n#include <linux/errqueue.h>\n#include <linux/if.h>\n#include <linux/if_alg.h>\n#include <linux/if_arp.h>\n#include <linux/if_ether.h>\n#include <linux/if_ppp.h>\n#include <linux/if_tun.h>\n#include <linux/if_packet.h>\n#include <linux/if_addr.h>\n#include <linux/falloc.h>\n#include <linux/fanotify.h>\n#include <linux/filter.h>\n#include <linux/fs.h>\n#include <linux/kexec.h>\n#include <linux/keyctl.h>\n#include <linux/magic.h>\n#include <linux/memfd.h>\n#include <linux/module.h>\n#include <linux/netfilter/nfnetlink.h>\n#include <linux/netlink.h>\n#include <linux/net_namespace.h>\n#include <linux/perf_event.h>\n#include <linux/random.h>\n#include <linux/reboot.h>\n#include <linux/rtnetlink.h>\n#include <linux/ptrace.h>\n#include <linux/sched.h>\n#include <linux/seccomp.h>\n#include <linux/sockios.h>\n#include <linux/wait.h>\n#include <linux/icmpv6.h>\n#include <linux/serial.h>\n#include <linux/can.h>\n#include <linux/vm_sockets.h>\n#include <linux/taskstats.h>\n#include <linux/genetlink.h>\n#include <linux/watchdog.h>\n#include <linux/hdreg.h>\n#include <linux/rtc.h>\n#include <linux/if_xdp.h>\n#include <linux/cryptouser.h>\n#include <mtd/ubi-user.h>\n#include <net/route.h>\n\n#if defined(__sparc__)\n// On sparc{,64}, the kernel defines struct termios2 itself which clashes with the\n// definition in glibc. As only the error constants are needed here, include the\n// generic termibits.h (which is included by termbits.h on sparc).\n#include <asm-generic/termbits.h>\n#else\n#include <asm/termbits.h>\n#endif\n\n#ifndef MSG_FASTOPEN\n#define MSG_FASTOPEN    0x20000000\n#endif\n\n#ifndef PTRACE_GETREGS\n#define PTRACE_GETREGS\t0xc\n#endif\n\n#ifndef PTRACE_SETREGS\n#define PTRACE_SETREGS\t0xd\n#endif\n\n#ifndef SOL_NETLINK\n#define SOL_NETLINK\t270\n#endif\n\n#ifdef SOL_BLUETOOTH\n// SPARC includes this in /usr/include/sparc64-linux-gnu/bits/socket.h\n// but it is already in bluetooth_linux.go\n#undef SOL_BLUETOOTH\n#endif\n\n// Certain constants are missing from the fs/crypto UAPI\n#define FS_KEY_DESC_PREFIX              \"fscrypt:\"\n#define FS_KEY_DESC_PREFIX_SIZE         8\n#define FS_MAX_KEY_SIZE                 64\n'\n\nincludes_NetBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/extattr.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n\n// Needed since <sys/param.h> refers to it...\n#define schedppq 1\n'\n\nincludes_OpenBSD='\n#include <sys/types.h>\n#include <sys/param.h>\n#include <sys/event.h>\n#include <sys/mman.h>\n#include <sys/mount.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/sysctl.h>\n#include <sys/termios.h>\n#include <sys/ttycom.h>\n#include <sys/unistd.h>\n#include <sys/wait.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_types.h>\n#include <net/if_var.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <netinet/in_systm.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n#include <netinet/if_ether.h>\n#include <net/if_bridge.h>\n\n// We keep some constants not supported in OpenBSD 5.5 and beyond for\n// the promise of compatibility.\n#define EMUL_ENABLED\t\t0x1\n#define EMUL_NATIVE\t\t0x2\n#define IPV6_FAITH\t\t0x1d\n#define IPV6_OPTIONS\t\t0x1\n#define IPV6_RTHDR_STRICT\t0x1\n#define IPV6_SOCKOPT_RESERVED1\t0x3\n#define SIOCGIFGENERIC\t\t0xc020693a\n#define SIOCSIFGENERIC\t\t0x80206939\n#define WALTSIG\t\t\t0x4\n'\n\nincludes_SunOS='\n#include <limits.h>\n#include <sys/types.h>\n#include <sys/socket.h>\n#include <sys/sockio.h>\n#include <sys/stat.h>\n#include <sys/mman.h>\n#include <sys/wait.h>\n#include <sys/ioctl.h>\n#include <sys/mkdev.h>\n#include <net/bpf.h>\n#include <net/if.h>\n#include <net/if_arp.h>\n#include <net/if_types.h>\n#include <net/route.h>\n#include <netinet/in.h>\n#include <termios.h>\n#include <netinet/ip.h>\n#include <netinet/ip_mroute.h>\n'\n\n\nincludes='\n#include <sys/types.h>\n#include <sys/file.h>\n#include <fcntl.h>\n#include <dirent.h>\n#include <sys/socket.h>\n#include <netinet/in.h>\n#include <netinet/ip.h>\n#include <netinet/ip6.h>\n#include <netinet/tcp.h>\n#include <errno.h>\n#include <sys/signal.h>\n#include <signal.h>\n#include <sys/resource.h>\n#include <time.h>\n'\nccflags=\"$@\"\n\n# Write go tool cgo -godefs input.\n(\n\techo package unix\n\techo\n\techo '/*'\n\tindirect=\"includes_$(uname)\"\n\techo \"${!indirect} $includes\"\n\techo '*/'\n\techo 'import \"C\"'\n\techo 'import \"syscall\"'\n\techo\n\techo 'const ('\n\n\t# The gcc command line prints all the #defines\n\t# it encounters while processing the input\n\techo \"${!indirect} $includes\" | $CC -x c - -E -dM $ccflags |\n\tawk '\n\t\t$1 != \"#define\" || $2 ~ /\\(/ || $3 == \"\" {next}\n\n\t\t$2 ~ /^E([ABCD]X|[BIS]P|[SD]I|S|FL)$/ {next}  # 386 registers\n\t\t$2 ~ /^(SIGEV_|SIGSTKSZ|SIGRT(MIN|MAX))/ {next}\n\t\t$2 ~ /^(SCM_SRCRT)$/ {next}\n\t\t$2 ~ /^(MAP_FAILED)$/ {next}\n\t\t$2 ~ /^ELF_.*$/ {next}# <asm/elf.h> contains ELF_ARCH, etc.\n\n\t\t$2 ~ /^EXTATTR_NAMESPACE_NAMES/ ||\n\t\t$2 ~ /^EXTATTR_NAMESPACE_[A-Z]+_STRING/ {next}\n\n\t\t$2 !~ /^ECCAPBITS/ &&\n\t\t$2 !~ /^ETH_/ &&\n\t\t$2 !~ /^EPROC_/ &&\n\t\t$2 !~ /^EQUIV_/ &&\n\t\t$2 !~ /^EXPR_/ &&\n\t\t$2 ~ /^E[A-Z0-9_]+$/ ||\n\t\t$2 ~ /^B[0-9_]+$/ ||\n\t\t$2 ~ /^(OLD|NEW)DEV$/ ||\n\t\t$2 == \"BOTHER\" ||\n\t\t$2 ~ /^CI?BAUD(EX)?$/ ||\n\t\t$2 == \"IBSHIFT\" ||\n\t\t$2 ~ /^V[A-Z0-9]+$/ ||\n\t\t$2 ~ /^CS[A-Z0-9]/ ||\n\t\t$2 ~ /^I(SIG|CANON|CRNL|UCLC|EXTEN|MAXBEL|STRIP|UTF8)$/ ||\n\t\t$2 ~ /^IGN/ ||\n\t\t$2 ~ /^IX(ON|ANY|OFF)$/ ||\n\t\t$2 ~ /^IN(LCR|PCK)$/ ||\n\t\t$2 !~ \"X86_CR3_PCID_NOFLUSH\" &&\n\t\t$2 ~ /(^FLU?SH)|(FLU?SH$)/ ||\n\t\t$2 ~ /^C(LOCAL|READ|MSPAR|RTSCTS)$/ ||\n\t\t$2 == \"BRKINT\" ||\n\t\t$2 == \"HUPCL\" ||\n\t\t$2 == \"PENDIN\" ||\n\t\t$2 == \"TOSTOP\" ||\n\t\t$2 == \"XCASE\" ||\n\t\t$2 == \"ALTWERASE\" ||\n\t\t$2 == \"NOKERNINFO\" ||\n\t\t$2 ~ /^PAR/ ||\n\t\t$2 ~ /^SIG[^_]/ ||\n\t\t$2 ~ /^O[CNPFPL][A-Z]+[^_][A-Z]+$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)DLY$/ ||\n\t\t$2 ~ /^(NL|CR|TAB|BS|VT|FF)[0-9]$/ ||\n\t\t$2 ~ /^O?XTABS$/ ||\n\t\t$2 ~ /^TC[IO](ON|OFF)$/ ||\n\t\t$2 ~ /^IN_/ ||\n\t\t$2 ~ /^LOCK_(SH|EX|NB|UN)$/ ||\n\t\t$2 ~ /^(AF|SOCK|SO|SOL|IPPROTO|IP|IPV6|ICMP6|TCP|MCAST|EVFILT|NOTE|EV|SHUT|PROT|MAP|MFD|T?PACKET|MSG|SCM|MCL|DT|MADV|PR)_/ ||\n\t\t$2 ~ /^TP_STATUS_/ ||\n\t\t$2 ~ /^FALLOC_/ ||\n\t\t$2 == \"ICMPV6_FILTER\" ||\n\t\t$2 == \"SOMAXCONN\" ||\n\t\t$2 == \"NAME_MAX\" ||\n\t\t$2 == \"IFNAMSIZ\" ||\n\t\t$2 ~ /^CTL_(HW|KERN|MAXNAME|NET|QUERY)$/ ||\n\t\t$2 ~ /^KERN_(HOSTNAME|OS(RELEASE|TYPE)|VERSION)$/ ||\n\t\t$2 ~ /^HW_MACHINE$/ ||\n\t\t$2 ~ /^SYSCTL_VERS/ ||\n\t\t$2 !~ \"MNT_BITS\" &&\n\t\t$2 ~ /^(MS|MNT|UMOUNT)_/ ||\n\t\t$2 ~ /^TUN(SET|GET|ATTACH|DETACH)/ ||\n\t\t$2 ~ /^(O|F|[ES]?FD|NAME|S|PTRACE|PT)_/ ||\n\t\t$2 ~ /^KEXEC_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_CMD_/ ||\n\t\t$2 ~ /^LINUX_REBOOT_MAGIC[12]$/ ||\n\t\t$2 ~ /^MODULE_INIT_/ ||\n\t\t$2 !~ \"NLA_TYPE_MASK\" &&\n\t\t$2 ~ /^(NETLINK|NLM|NLMSG|NLA|IFA|IFAN|RT|RTC|RTCF|RTN|RTPROT|RTNH|ARPHRD|ETH_P|NETNSA)_/ ||\n\t\t$2 ~ /^SIOC/ ||\n\t\t$2 ~ /^TIOC/ ||\n\t\t$2 ~ /^TCGET/ ||\n\t\t$2 ~ /^TCSET/ ||\n\t\t$2 ~ /^TC(FLSH|SBRKP?|XONC)$/ ||\n\t\t$2 !~ \"RTF_BITS\" &&\n\t\t$2 ~ /^(IFF|IFT|NET_RT|RTM|RTF|RTV|RTA|RTAX)_/ ||\n\t\t$2 ~ /^BIOC/ ||\n\t\t$2 ~ /^RUSAGE_(SELF|CHILDREN|THREAD)/ ||\n\t\t$2 ~ /^RLIMIT_(AS|CORE|CPU|DATA|FSIZE|LOCKS|MEMLOCK|MSGQUEUE|NICE|NOFILE|NPROC|RSS|RTPRIO|RTTIME|SIGPENDING|STACK)|RLIM_INFINITY/ ||\n\t\t$2 ~ /^PRIO_(PROCESS|PGRP|USER)/ ||\n\t\t$2 ~ /^CLONE_[A-Z_]+/ ||\n\t\t$2 !~ /^(BPF_TIMEVAL|BPF_FIB_LOOKUP_[A-Z]+)$/ &&\n\t\t$2 ~ /^(BPF|DLT)_/ ||\n\t\t$2 ~ /^(CLOCK|TIMER)_/ ||\n\t\t$2 ~ /^CAN_/ ||\n\t\t$2 ~ /^CAP_/ ||\n\t\t$2 ~ /^ALG_/ ||\n\t\t$2 ~ /^FS_(POLICY_FLAGS|KEY_DESC|ENCRYPTION_MODE|[A-Z0-9_]+_KEY_SIZE|IOC_(GET|SET)_ENCRYPTION)/ ||\n\t\t$2 ~ /^GRND_/ ||\n\t\t$2 ~ /^RND/ ||\n\t\t$2 ~ /^KEY_(SPEC|REQKEY_DEFL)_/ ||\n\t\t$2 ~ /^KEYCTL_/ ||\n\t\t$2 ~ /^PERF_EVENT_IOC_/ ||\n\t\t$2 ~ /^SECCOMP_MODE_/ ||\n\t\t$2 ~ /^SPLICE_/ ||\n\t\t$2 ~ /^SYNC_FILE_RANGE_/ ||\n\t\t$2 !~ /^AUDIT_RECORD_MAGIC/ &&\n\t\t$2 !~ /IOC_MAGIC/ &&\n\t\t$2 ~ /^[A-Z][A-Z0-9_]+_MAGIC2?$/ ||\n\t\t$2 ~ /^(VM|VMADDR)_/ ||\n\t\t$2 ~ /^IOCTL_VM_SOCKETS_/ ||\n\t\t$2 ~ /^(TASKSTATS|TS)_/ ||\n\t\t$2 ~ /^CGROUPSTATS_/ ||\n\t\t$2 ~ /^GENL_/ ||\n\t\t$2 ~ /^STATX_/ ||\n\t\t$2 ~ /^RENAME/ ||\n\t\t$2 ~ /^UBI_IOC[A-Z]/ ||\n\t\t$2 ~ /^UTIME_/ ||\n\t\t$2 ~ /^XATTR_(CREATE|REPLACE|NO(DEFAULT|FOLLOW|SECURITY)|SHOWCOMPRESSION)/ ||\n\t\t$2 ~ /^ATTR_(BIT_MAP_COUNT|(CMN|VOL|FILE)_)/ ||\n\t\t$2 ~ /^FSOPT_/ ||\n\t\t$2 ~ /^WDIOC_/ ||\n\t\t$2 ~ /^NFN/ ||\n\t\t$2 ~ /^XDP_/ ||\n\t\t$2 ~ /^(HDIO|WIN|SMART)_/ ||\n\t\t$2 ~ /^CRYPTO_/ ||\n\t\t$2 !~ \"WMESGLEN\" &&\n\t\t$2 ~ /^W[A-Z0-9]+$/ ||\n\t\t$2 ~/^PPPIOC/ ||\n\t\t$2 ~ /^FAN_|FANOTIFY_/ ||\n\t\t$2 ~ /^BLK[A-Z]*(GET$|SET$|BUF$|PART$|SIZE)/ {printf(\"\\t%s = C.%s\\n\", $2, $2)}\n\t\t$2 ~ /^__WCOREFLAG$/ {next}\n\t\t$2 ~ /^__W[A-Z0-9]+$/ {printf(\"\\t%s = C.%s\\n\", substr($2,3), $2)}\n\n\t\t{next}\n\t' | sort\n\n\techo ')'\n) >_const.go\n\n# Pull out the error names for later.\nerrors=$(\n\techo '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print $2 }' |\n\tsort\n)\n\n# Pull out the signal names for later.\nsignals=$(\n\techo '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print $2 }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort\n)\n\n# Again, writing regexps to a file.\necho '#include <errno.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^E[A-Z0-9_]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tsort >_error.grep\necho '#include <signal.h>' | $CC -x c - -E -dM $ccflags |\n\tawk '$1==\"#define\" && $2 ~ /^SIG[A-Z0-9]+$/ { print \"^\\t\" $2 \"[ \\t]*=\" }' |\n\tegrep -v '(SIGSTKSIZE|SIGSTKSZ|SIGRT|SIGMAX64)' |\n\tsort >_signal.grep\n\necho '// mkerrors.sh' \"$@\"\necho '// Code generated by the command above; see README.md. DO NOT EDIT.'\necho\necho \"// +build ${GOARCH},${GOOS}\"\necho\ngo tool cgo -godefs -- \"$@\" _const.go >_error.out\ncat _error.out | grep -vf _error.grep | grep -vf _signal.grep\necho\necho '// Errors'\necho 'const ('\ncat _error.out | grep -f _error.grep | sed 's/=\\(.*\\)/= syscall.Errno(\\1)/'\necho ')'\n\necho\necho '// Signals'\necho 'const ('\ncat _error.out | grep -f _signal.grep | sed 's/=\\(.*\\)/= syscall.Signal(\\1)/'\necho ')'\n\n# Run C program to print error and syscall strings.\n(\n\techo -E \"\n#include <stdio.h>\n#include <stdlib.h>\n#include <errno.h>\n#include <ctype.h>\n#include <string.h>\n#include <signal.h>\n\n#define nelem(x) (sizeof(x)/sizeof((x)[0]))\n\nenum { A = 'A', Z = 'Z', a = 'a', z = 'z' }; // avoid need for single quotes below\n\nstruct tuple {\n\tint num;\n\tconst char *name;\n};\n\nstruct tuple errors[] = {\n\"\n\tfor i in $errors\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\techo -E \"\n};\n\nstruct tuple signals[] = {\n\"\n\tfor i in $signals\n\tdo\n\t\techo -E '\t{'$i', \"'$i'\" },'\n\tdone\n\n\t# Use -E because on some systems bash builtin interprets \\n itself.\n\techo -E '\n};\n\nstatic int\ntuplecmp(const void *a, const void *b)\n{\n\treturn ((struct tuple *)a)->num - ((struct tuple *)b)->num;\n}\n\nint\nmain(void)\n{\n\tint i, e;\n\tchar buf[1024], *p;\n\n\tprintf(\"\\n\\n// Error table\\n\");\n\tprintf(\"var errorList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Errno\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(errors, nelem(errors), sizeof errors[0], tuplecmp);\n\tfor(i=0; i<nelem(errors); i++) {\n\t\te = errors[i].num;\n\t\tif(i > 0 && errors[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strerror(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, errors[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\tprintf(\"\\n\\n// Signal table\\n\");\n\tprintf(\"var signalList = [...]struct {\\n\");\n\tprintf(\"\\tnum  syscall.Signal\\n\");\n\tprintf(\"\\tname string\\n\");\n\tprintf(\"\\tdesc string\\n\");\n\tprintf(\"} {\\n\");\n\tqsort(signals, nelem(signals), sizeof signals[0], tuplecmp);\n\tfor(i=0; i<nelem(signals); i++) {\n\t\te = signals[i].num;\n\t\tif(i > 0 && signals[i-1].num == e)\n\t\t\tcontinue;\n\t\tstrcpy(buf, strsignal(e));\n\t\t// lowercase first letter: Bad -> bad, but STREAM -> STREAM.\n\t\tif(A <= buf[0] && buf[0] <= Z && a <= buf[1] && buf[1] <= z)\n\t\t\tbuf[0] += a - A;\n\t\t// cut trailing : number.\n\t\tp = strrchr(buf, \":\"[0]);\n\t\tif(p)\n\t\t\t*p = '\\0';\n\t\tprintf(\"\\t{ %d, \\\"%s\\\", \\\"%s\\\" },\\n\", e, signals[i].name, buf);\n\t}\n\tprintf(\"}\\n\\n\");\n\n\treturn 0;\n}\n\n'\n) >_errors.c\n\n$CC $ccflags -o _errors _errors.c && $GORUN ./_errors && rm -f _errors.c _errors _const.go _error.grep _signal.grep _error.out\n", "num_lines": 663}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n#\n# This script rebuilds the generated code for the protocol buffers.\n# To run this you will need protoc and goprotobuf installed;\n# see https://github.com/golang/protobuf for instructions.\n\nPKG=google.golang.org/appengine\n\nfunction die() {\n\techo 1>&2 $*\n\texit 1\n}\n\n# Sanity check that the right tools are accessible.\nfor tool in go protoc protoc-gen-go; do\n\tq=$(which $tool) || die \"didn't find $tool\"\n\techo 1>&2 \"$tool: $q\"\ndone\n\necho -n 1>&2 \"finding package dir... \"\npkgdir=$(go list -f '{{.Dir}}' $PKG)\necho 1>&2 $pkgdir\nbase=$(echo $pkgdir | sed \"s,/$PKG\\$,,\")\necho 1>&2 \"base: $base\"\ncd $base\n\n# Run protoc once per package.\nfor dir in $(find $PKG/internal -name '*.proto' | xargs dirname | sort | uniq); do\n\techo 1>&2 \"* $dir\"\n\tprotoc --go_out=. $dir/*.proto\ndone\n\nfor f in $(find $PKG/internal -name '*.pb.go'); do\n  # Remove proto.RegisterEnum calls.\n  # These cause duplicate registration panics when these packages\n  # are used on classic App Engine. proto.RegisterEnum only affects\n  # parsing the text format; we don't care about that.\n  # https://code.google.com/p/googleappengine/issues/detail?id=11670#c17\n  sed -i '/proto.RegisterEnum/d' $f\ndone\n", "num_lines": 41}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This script serves as an example to demonstrate how to generate the gRPC-Go\n# interface and the related messages from .proto file.\n#\n# It assumes the installation of i) Google proto buffer compiler at\n# https://github.com/google/protobuf (after v2.6.1) and ii) the Go codegen\n# plugin at https://github.com/golang/protobuf (after 2015-02-20). If you have\n# not, please install them first.\n#\n# We recommend running this script at $GOPATH/src.\n#\n# If this is not what you need, feel free to make your own scripts. Again, this\n# script is for demonstration purpose.\n#\nproto=$1\nprotoc --go_out=plugins=grpc:. $proto\n", "num_lines": 18}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nTMP=$(mktemp -d /tmp/sdk.XXX) \\\n&& curl -o $TMP.zip \"https://storage.googleapis.com/appengine-sdks/featured/go_appengine_sdk_linux_amd64-1.9.68.zip\" \\\n&& unzip -q $TMP.zip -d $TMP \\\n&& export PATH=\"$PATH:$TMP/go_appengine\"\n", "num_lines": 7}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [[ `uname -a` = *\"Darwin\"* ]]; then\n  echo \"It seems you are running on Mac. This script does not work on Mac. See https://github.com/grpc/grpc-go/issues/2047\"\n  exit 1\nfi\n\nset -ex  # Exit on error; debugging enabled.\nset -o pipefail  # Fail a pipe if any sub-command fails.\n\ndie() {\n  echo \"$@\" >&2\n  exit 1\n}\n\nfail_on_output() {\n  tee /dev/stderr | (! read)\n}\n\n# Check to make sure it's safe to modify the user's git repo.\ngit status --porcelain | fail_on_output\n\n# Undo any edits made by this script.\ncleanup() {\n  git reset --hard HEAD\n}\ntrap cleanup EXIT\n\nPATH=\"${GOPATH}/bin:${GOROOT}/bin:${PATH}\"\n\nif [[ \"$1\" = \"-install\" ]]; then\n  # Check for module support\n  if go help mod >& /dev/null; then\n    go install \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell \\\n      github.com/golang/protobuf/protoc-gen-go\n  else\n    # Ye olde `go get` incantation.\n    # Note: this gets the latest version of all tools (vs. the pinned versions\n    # with Go modules).\n    go get -u \\\n      golang.org/x/lint/golint \\\n      golang.org/x/tools/cmd/goimports \\\n      honnef.co/go/tools/cmd/staticcheck \\\n      github.com/client9/misspell/cmd/misspell \\\n      github.com/golang/protobuf/protoc-gen-go\n  fi\n  if [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n    if [[ \"${TRAVIS}\" = \"true\" ]]; then\n      PROTOBUF_VERSION=3.3.0\n      PROTOC_FILENAME=protoc-${PROTOBUF_VERSION}-linux-x86_64.zip\n      pushd /home/travis\n      wget https://github.com/google/protobuf/releases/download/v${PROTOBUF_VERSION}/${PROTOC_FILENAME}\n      unzip ${PROTOC_FILENAME}\n      bin/protoc --version\n      popd\n    elif ! which protoc > /dev/null; then\n      die \"Please install protoc into your path\"\n    fi\n  fi\n  exit 0\nelif [[ \"$#\" -ne 0 ]]; then\n  die \"Unknown argument(s): $*\"\nfi\n\n# - Ensure all source files contain a copyright message.\ngit ls-files \"*.go\" | xargs grep -L \"\\(Copyright [0-9]\\{4,\\} gRPC authors\\)\\|DO NOT EDIT\" 2>&1 | fail_on_output\n\n# - Make sure all tests in grpc and grpc/test use leakcheck via Teardown.\n(! grep 'func Test[^(]' *_test.go)\n(! grep 'func Test[^(]' test/*.go)\n\n# - Do not import math/rand for real library code.  Use internal/grpcrand for\n#   thread safety.\ngit ls-files \"*.go\" | xargs grep -l '\"math/rand\"' 2>&1 | (! grep -v '^examples\\|^stress\\|grpcrand\\|wrr_test')\n\n# - Ensure all ptypes proto packages are renamed when importing.\ngit ls-files \"*.go\" | (! xargs grep \"\\(import \\|^\\s*\\)\\\"github.com/golang/protobuf/ptypes/\")\n\n# - Check imports that are illegal in appengine (until Go 1.11).\n# TODO: Remove when we drop Go 1.10 support\ngo list -f {{.Dir}} ./... | xargs go run test/go_vet/vet.go\n\n# - gofmt, goimports, golint (with exceptions for generated code), go vet.\ngofmt -s -d -l . 2>&1 | fail_on_output\ngoimports -l . 2>&1 | (! grep -vE \"(_mock|\\.pb)\\.go:\") | fail_on_output\ngolint ./... 2>&1 | (! grep -vE \"(_mock|\\.pb)\\.go:\")\ngo vet -all .\n\n# - Check that generated proto files are up to date.\nif [[ -z \"${VET_SKIP_PROTO}\" ]]; then\n  PATH=\"/home/travis/bin:${PATH}\" make proto && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Check that our module is tidy.\nif go help mod >& /dev/null; then\n  go mod tidy && \\\n    git status --porcelain 2>&1 | fail_on_output || \\\n    (git status; git --no-pager diff; exit 1)\nfi\n\n# - Collection of static analysis checks\n# TODO(menghanl): fix errors in transport_test.\nstaticcheck -go 1.9 -checks 'inherit,-ST1015' -ignore '\ngoogle.golang.org/grpc/balancer.go:SA1019\ngoogle.golang.org/grpc/balancer/roundrobin/roundrobin_test.go:SA1019\ngoogle.golang.org/grpc/balancer/xds/edsbalancer/balancergroup.go:SA1019\ngoogle.golang.org/grpc/balancer/xds/xds.go:SA1019\ngoogle.golang.org/grpc/balancer_conn_wrappers.go:SA1019\ngoogle.golang.org/grpc/balancer_test.go:SA1019\ngoogle.golang.org/grpc/benchmark/benchmain/main.go:SA1019\ngoogle.golang.org/grpc/benchmark/worker/benchmark_client.go:SA1019\ngoogle.golang.org/grpc/clientconn.go:S1024\ngoogle.golang.org/grpc/clientconn_state_transition_test.go:SA1019\ngoogle.golang.org/grpc/clientconn_test.go:SA1019\ngoogle.golang.org/grpc/internal/transport/handler_server.go:SA1019\ngoogle.golang.org/grpc/internal/transport/handler_server_test.go:SA1019\ngoogle.golang.org/grpc/resolver/dns/dns_resolver.go:SA1019\ngoogle.golang.org/grpc/stats/stats_test.go:SA1019\ngoogle.golang.org/grpc/test/channelz_test.go:SA1019\ngoogle.golang.org/grpc/test/end2end_test.go:SA1019\ngoogle.golang.org/grpc/test/healthcheck_test.go:SA1019\n' ./...\nmisspell -error .\n", "num_lines": 130}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright 2018 gRPC authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -eux -o pipefail\n\nTMP=$(mktemp -d)\n\nfunction finish {\n  rm -rf \"$TMP\"\n}\ntrap finish EXIT\n\npushd \"$TMP\"\nmkdir -p grpc/binarylog/grpc_binarylog_v1\ncurl https://raw.githubusercontent.com/grpc/grpc-proto/master/grpc/binlog/v1/binarylog.proto > grpc/binarylog/grpc_binarylog_v1/binarylog.proto\n\nprotoc --go_out=plugins=grpc,paths=source_relative:. -I. grpc/binarylog/grpc_binarylog_v1/*.proto\npopd\nrm -f ./grpc_binarylog_v1/*.pb.go\ncp \"$TMP\"/grpc/binarylog/grpc_binarylog_v1/*.pb.go ../../binarylog/grpc_binarylog_v1/\n\n", "num_lines": 34}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\nCN_BASE=\"webhook_tests\"\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth, serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=${CN_BASE}_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=${CN_BASE}_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=${CN_BASE}_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2017 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 108}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2016 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -e\n\n# gencerts.sh generates the certificates for the webhook authz plugin tests.\n#\n# It is not expected to be run often (there is no go generate rule), and mainly\n# exists for documentation purposes.\n\ncat > server.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = serverAuth\nsubjectAltName = @alt_names\n[alt_names]\nIP.1 = 127.0.0.1\nEOF\n\ncat > client.conf << EOF\n[req]\nreq_extensions = v3_req\ndistinguished_name = req_distinguished_name\n[req_distinguished_name]\n[ v3_req ]\nbasicConstraints = CA:FALSE\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nextendedKeyUsage = clientAuth\nEOF\n\n# Create a certificate authority\nopenssl genrsa -out caKey.pem 2048\nopenssl req -x509 -new -nodes -key caKey.pem -days 100000 -out caCert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a second certificate authority\nopenssl genrsa -out badCAKey.pem 2048\nopenssl req -x509 -new -nodes -key badCAKey.pem -days 100000 -out badCACert.pem -subj \"/CN=webhook_authz_ca\"\n\n# Create a server certiticate\nopenssl genrsa -out serverKey.pem 2048\nopenssl req -new -key serverKey.pem -out server.csr -subj \"/CN=webhook_authz_server\" -config server.conf\nopenssl x509 -req -in server.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out serverCert.pem -days 100000 -extensions v3_req -extfile server.conf\n\n# Create a client certiticate\nopenssl genrsa -out clientKey.pem 2048\nopenssl req -new -key clientKey.pem -out client.csr -subj \"/CN=webhook_authz_client\" -config client.conf\nopenssl x509 -req -in client.csr -CA caCert.pem -CAkey caKey.pem -CAcreateserial -out clientCert.pem -days 100000 -extensions v3_req -extfile client.conf\n\noutfile=certs_test.go\n\ncat > $outfile << EOF\n/*\nCopyright 2016 The Kubernetes Authors.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// This file was generated using openssl by the gencerts.sh script\n// and holds raw certificates for the webhook tests.\n\npackage webhook\nEOF\n\nfor file in caKey caCert badCAKey badCACert serverKey serverCert clientKey clientCert; do\n\tdata=$(cat ${file}.pem)\n\techo \"\" >> $outfile\n\techo \"var $file = []byte(\\`$data\\`)\" >> $outfile\ndone\n\n# Clean up after we're done.\nrm ./*.pem\nrm ./*.csr\nrm ./*.srl\nrm ./*.conf\n", "num_lines": 103}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# generate-groups generates everything for a project with external types only, e.g. a project based\n# on CustomResourceDefinitions.\n\nif [ \"$#\" -lt 4 ] || [ \"${1}\" == \"--help\" ]; then\n  cat <<EOF\nUsage: $(basename \"$0\") <generators> <output-package> <apis-package> <groups-versions> ...\n\n  <generators>        the generators comma separated to run (deepcopy,defaulter,client,lister,informer) or \"all\".\n  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).\n  <apis-package>      the external types dir (e.g. github.com/example/api or github.com/example/project/pkg/apis).\n  <groups-versions>   the groups and their versions in the format \"groupA:v1,v2 groupB:v1 groupC:v2\", relative\n                      to <api-package>.\n  ...                 arbitrary flags passed to all generator binaries.\n\n\nExamples:\n  $(basename \"$0\") all             github.com/example/project/pkg/client github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\n  $(basename \"$0\") deepcopy,client github.com/example/project/pkg/client github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\nEOF\n  exit 0\nfi\n\nGENS=\"$1\"\nOUTPUT_PKG=\"$2\"\nAPIS_PKG=\"$3\"\nGROUPS_WITH_VERSIONS=\"$4\"\nshift 4\n\n(\n  # To support running this script from anywhere, we have to first cd into this directory\n  # so we can install the tools.\n  cd \"$(dirname \"${0}\")\"\n  go install ./cmd/{defaulter-gen,client-gen,lister-gen,informer-gen,deepcopy-gen}\n)\n\nfunction codegen::join() { local IFS=\"$1\"; shift; echo \"$*\"; }\n\n# enumerate group versions\nFQ_APIS=() # e.g. k8s.io/api/apps/v1\nfor GVs in ${GROUPS_WITH_VERSIONS}; do\n  IFS=: read -r G Vs <<<\"${GVs}\"\n\n  # enumerate versions\n  for V in ${Vs//,/ }; do\n    FQ_APIS+=(\"${APIS_PKG}/${G}/${V}\")\n  done\ndone\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"deepcopy\" <<<\"${GENS}\"; then\n  echo \"Generating deepcopy funcs\"\n  \"${GOPATH}/bin/deepcopy-gen\" --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" -O zz_generated.deepcopy --bounding-dirs \"${APIS_PKG}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"client\" <<<\"${GENS}\"; then\n  echo \"Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\"\n  \"${GOPATH}/bin/client-gen\" --clientset-name \"${CLIENTSET_NAME_VERSIONED:-versioned}\" --input-base \"\" --input \"$(codegen::join , \"${FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"lister\" <<<\"${GENS}\"; then\n  echo \"Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers\"\n  \"${GOPATH}/bin/lister-gen\" --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/listers\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"informer\" <<<\"${GENS}\"; then\n  echo \"Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers\"\n  \"${GOPATH}/bin/informer-gen\" \\\n           --input-dirs \"$(codegen::join , \"${FQ_APIS[@]}\")\" \\\n           --versioned-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}\" \\\n           --listers-package \"${OUTPUT_PKG}/listers\" \\\n           --output-package \"${OUTPUT_PKG}/informers\" \\\n           \"$@\"\nfi\n", "num_lines": 93}
{"repo_name": "azure-k8s-metrics-adapter", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright 2017 The Kubernetes Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nset -o errexit\nset -o nounset\nset -o pipefail\n\n# generate-internal-groups generates everything for a project with internal types, e.g. an\n# user-provided API server based on k8s.io/apiserver.\n\nif [ \"$#\" -lt 5 ] || [ \"${1}\" == \"--help\" ]; then\n  cat <<EOF\nUsage: $(basename \"$0\") <generators> <output-package> <internal-apis-package> <extensiona-apis-package> <groups-versions> ...\n\n  <generators>        the generators comma separated to run (deepcopy,defaulter,conversion,client,lister,informer) or \"all\".\n  <output-package>    the output package name (e.g. github.com/example/project/pkg/generated).\n  <int-apis-package>  the internal types dir (e.g. github.com/example/project/pkg/apis).\n  <ext-apis-package>  the external types dir (e.g. github.com/example/project/pkg/apis or githubcom/example/apis).\n  <groups-versions>   the groups and their versions in the format \"groupA:v1,v2 groupB:v1 groupC:v2\", relative\n                      to <api-package>.\n  ...                 arbitrary flags passed to all generator binaries.\n\nExamples:\n  $(basename \"$0\") all                           github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/pkg/apis \"foo:v1 bar:v1alpha1,v1beta1\"\n  $(basename \"$0\") deepcopy,defaulter,conversion github.com/example/project/pkg/client github.com/example/project/pkg/apis github.com/example/project/apis     \"foo:v1 bar:v1alpha1,v1beta1\"\nEOF\n  exit 0\nfi\n\nGENS=\"$1\"\nOUTPUT_PKG=\"$2\"\nINT_APIS_PKG=\"$3\"\nEXT_APIS_PKG=\"$4\"\nGROUPS_WITH_VERSIONS=\"$5\"\nshift 5\n\ngo install ./\"$(dirname \"${0}\")\"/cmd/{defaulter-gen,conversion-gen,client-gen,lister-gen,informer-gen,deepcopy-gen}\nfunction codegen::join() { local IFS=\"$1\"; shift; echo \"$*\"; }\n\n# enumerate group versions\nALL_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps k8s.io/api/apps/v1\nINT_FQ_APIS=() # e.g. k8s.io/kubernetes/pkg/apis/apps\nEXT_FQ_APIS=() # e.g. k8s.io/api/apps/v1\nfor GVs in ${GROUPS_WITH_VERSIONS}; do\n  IFS=: read -r G Vs <<<\"${GVs}\"\n\n  if [ -n \"${INT_APIS_PKG}\" ]; then\n    ALL_FQ_APIS+=(\"${INT_APIS_PKG}/${G}\")\n    INT_FQ_APIS+=(\"${INT_APIS_PKG}/${G}\")\n  fi\n\n  # enumerate versions\n  for V in ${Vs//,/ }; do\n    ALL_FQ_APIS+=(\"${EXT_APIS_PKG}/${G}/${V}\")\n    EXT_FQ_APIS+=(\"${EXT_APIS_PKG}/${G}/${V}\")\n  done\ndone\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"deepcopy\" <<<\"${GENS}\"; then\n  echo \"Generating deepcopy funcs\"\n  \"${GOPATH}/bin/deepcopy-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" -O zz_generated.deepcopy --bounding-dirs \"${INT_APIS_PKG},${EXT_APIS_PKG}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"defaulter\" <<<\"${GENS}\"; then\n  echo \"Generating defaulters\"\n  \"${GOPATH}/bin/defaulter-gen\"  --input-dirs \"$(codegen::join , \"${EXT_FQ_APIS[@]}\")\" -O zz_generated.defaults \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"conversion\" <<<\"${GENS}\"; then\n  echo \"Generating conversions\"\n  \"${GOPATH}/bin/conversion-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" -O zz_generated.conversion \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"client\" <<<\"${GENS}\"; then\n  echo \"Generating clientset for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\"\n  if [ -n \"${INT_APIS_PKG}\" ]; then\n    IFS=\" \" read -r -a APIS <<< \"$(printf '%s/ ' \"${INT_FQ_APIS[@]}\")\"\n    \"${GOPATH}/bin/client-gen\" --clientset-name \"${CLIENTSET_NAME_INTERNAL:-internalversion}\" --input-base \"\" --input \"$(codegen::join , \"${APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\n  fi\n  \"${GOPATH}/bin/client-gen\" --clientset-name \"${CLIENTSET_NAME_VERSIONED:-versioned}\" --input-base \"\" --input \"$(codegen::join , \"${EXT_FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"lister\" <<<\"${GENS}\"; then\n  echo \"Generating listers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/listers\"\n  \"${GOPATH}/bin/lister-gen\" --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" --output-package \"${OUTPUT_PKG}/listers\" \"$@\"\nfi\n\nif [ \"${GENS}\" = \"all\" ] || grep -qw \"informer\" <<<\"${GENS}\"; then\n  echo \"Generating informers for ${GROUPS_WITH_VERSIONS} at ${OUTPUT_PKG}/informers\"\n  \"${GOPATH}/bin/informer-gen\" \\\n           --input-dirs \"$(codegen::join , \"${ALL_FQ_APIS[@]}\")\" \\\n           --versioned-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_VERSIONED:-versioned}\" \\\n           --internal-clientset-package \"${OUTPUT_PKG}/${CLIENTSET_PKG_NAME:-clientset}/${CLIENTSET_NAME_INTERNAL:-internalversion}\" \\\n           --listers-package \"${OUTPUT_PKG}/listers\" \\\n           --output-package \"${OUTPUT_PKG}/informers\" \\\n           \"$@\"\nfi\n", "num_lines": 111}
{"repo_name": "azure-kubernetes-visualizer", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\n# ========================================================================\n# Copyright 2014 Microsoft Corporation\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========================================================================\n\nnpm install express socket.io flavored-path cli", "num_lines": 19}
{"repo_name": "azure-kubernetes-visualizer", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ========================================================================\n# Copyright 2014 Microsoft Corporation\n\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n\n#     http://www.apache.org/licenses/LICENSE-2.0\n\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ========================================================================\n\n# This script is provided as a shorcut to starting the demo server.\n# It essentially just loads up your kubernetes config and pulls some configuration variables from there.\n# In the future this script may need adjusting as paths to the config scripts change.\n\nif [ -z $KUBERNETES_PROVIDER ]; then\n\texport KUBERNETES_PROVIDER=azure;\nfi\n\nexport KUBERNETES_PATH=../kubernetes\n\nsource $KUBERNETES_PATH/release/${KUBERNETES_PROVIDER}/config.sh\nsource $KUBERNETES_PATH/cluster/${KUBERNETES_PROVIDER}/config-default.sh\n\n./index.js \\\n\t-s ${AZ_CS}.cloudapp.net \\\n\t-m ${NUM_MINIONS} \\\n\t-k ${KUBERNETES_PATH} \\\n\t$@\n", "num_lines": 37}
{"repo_name": "azure-kusto-avro-conv", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -eu\n\ntmpfile=$(mktemp)\ntrap \"rm -f $tmpfile\" EXIT\n\nrun_test() {\n  tfile=\"$1.avro\"\n  efile=\"$2.json\"\n  cfile=\"$2.csv\"\n  shift; shift\n  set +e\n  options=\"$@\"\n\n  echo \"Running: ./avro2json $options ../tests/${tfile}\"\n  ./avro2json $options \"../tests/${tfile}\" > $tmpfile\n  if ! diff -a $tmpfile \"../tests/${efile}\"; then\n    exit 1\n  fi\n\n  if [ -f ../tests/$cfile ]; then\n    ./avro2json $options --csv \"../tests/${tfile}\" > $tmpfile\n    if ! diff -a $tmpfile \"../tests/${cfile}\"; then\n      exit 1\n    fi\n  fi\n}\n\nrun_test file1 file1\nrun_test file1 file1-p --prune\nrun_test reals reals\nrun_test decimals decimals\nrun_test decimals decimals-l --logical-types\nrun_test decimals-bytes decimals-bytes\nrun_test decimals-bytes decimals-bytes-l --logical-types\nrun_test columns columns-1 --columns 1\nrun_test columns columns-2 --columns 2\nrun_test columns columns-3 --columns 1,4\nrun_test columns columns-4 --columns 4,1\nrun_test dates dates-l --logical-types\nrun_test datetimes datetimes-l --logical-types\n", "num_lines": 41}
{"repo_name": "azure-kusto-demos", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /home/\n\ngit clone https://github.com/Azure/azure-kusto-demos.git \n\ncp /home/config/EventHubsConfig.json /home/azure-kusto-demos/eventhub-python/github-events-demo/config/\n\ncd /home/azure-kusto-demos/eventhub-python/github-events-demo/\n\npython crawl_send_eventhub.py &> \"../../../config/$(date +\"%Y_%m_%d_%I_%M_%p\").log\"", "num_lines": 11}
{"repo_name": "azure-kusto-labs", "repo_creator": "Azure", "programming_language": "Shell", "code": "job_name='yem0825-cdtest'\n# list run and cancel run\nrun_list=$(databricks runs list | grep $job_name)\nwhile IFS='  ' read id name status result url\ndo\necho \"run_id - $id $name $status\"\nif [ \"$status\" != 'TERMINATED' ]\nthen\n   databricks runs cancel --run-id $id\n   echo \"cancel run_id - $id\"\nfi\ndone <<< \"$run_list\"\n\n# create a job with the job-meta.json\njob_meta_file=\"./job_meta_simple_test.json\"\njob_id=$(databricks jobs create --json-file \"$job_meta_file\" | python -c \"import sys, json; print(json.load(sys.stdin)['job_id'])\")\necho \"create job $job_name $job_id\"\n\n# load notbook arguments\nnotebook_param_file=\"./notebook_params_simple_test.json\"\nnotebook_params=$(<$notebook_param_file)\n\n# create a run with the job\nrun_id=$(databricks jobs run-now --job-id $job_id --notebook-params  \"$notebook_params\"  | python -c \"import sys, json; print(json.load(sys.stdin)['run_id'])\")\necho \"run job $job_id with run_id $run_id\"", "num_lines": 25}
{"repo_name": "Azure-kusto-opentelemetry-demo", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n\n# This script is used to generate protobuf files for all services.\n# Useful to ensure code can compile without Docker, and provide hints for IDEs.\n# Several dev tools including: cargo, protoc, python grpcio-tools, and rebar3 may be required to run this script.\n\nbase_dir=$(pwd)\n\ngen_proto_dotnet() {\n  echo \"Generating .NET protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  mkdir -p ./src/protos/\n  cp -r \"$base_dir\"/pb/ ./src/protos/\n  cd \"$base_dir\" || return\n}\n\ngen_proto_elixir() {\n  echo \"Generating Elixir protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  mkdir -p proto\n  cp \"$base_dir\"/pb/demo.proto ./proto/demo.proto\n  rebar3 grpc_regen\n  cd \"$base_dir\" || return\n}\n\ngen_proto_go() {\n  echo \"Generating Go protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  protoc -I ../../pb ./../../pb/demo.proto --go_out=./ --go-grpc_out=./\n  cd \"$base_dir\" || return\n}\n\ngen_proto_js() {\n  echo \"Generating Javascript protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  cp \"$base_dir\"/pb/demo.proto .\n  cd \"$base_dir\" || return\n}\n\ngen_proto_python() {\n  echo \"Generating Python protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  python3 -m grpc_tools.protoc -I=../../pb --python_out=./ --grpc_python_out=./ ./../../pb/demo.proto\n  cd \"$base_dir\" || return\n}\n\ngen_proto_rust() {\n  echo \"Generating Rust protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  mkdir -p proto\n  cp \"$base_dir\"/pb/demo.proto proto/demo.proto\n  cargo build\n  cd \"$base_dir\" || return\n}\n\ngen_proto_ts() {\n  echo \"Generating Typescript protobuf files for $1\"\n  cd \"$base_dir\"/src/\"$1\" || return\n  cp -r \"$base_dir\"/pb .\n  mkdir -p ./protos\n  protoc -I ./pb  --plugin=./node_modules/.bin/protoc-gen-ts_proto --ts_proto_opt=esModuleInterop=true --ts_proto_out=./protos --ts_proto_opt=outputServices=grpc-js demo.proto\n  cd \"$base_dir\" || return\n}\n\ngen_proto_go accountingservice\n# gen_proto_java adservice\ngen_proto_dotnet cartservice\ngen_proto_go checkoutservice\n# gen_proto_cpp currencyservice\n# gen_proto_ruby emailservice\ngen_proto_elixir featureflagservice\ngen_proto_ts frontend\ngen_proto_js paymentservice\ngen_proto_go productcatalogservice\n# gen_proto_php quoteservice\ngen_proto_python recommendationservice\ngen_proto_rust shippingservice\n", "num_lines": 81}
{"repo_name": "azure-kusto-orc-conv", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ -z \"$1\" ]; then\n    echo \"Usage: pull_hdfs [path_to_hdfs_git_root]\"\n    exit 1;\nfi\nif [ ! -d \"$1\" ]; then\n    echo \"$1 is not a directory\"\nfi\nif [ ! -d \"$1/hadoop-hdfs-project\" ]; then\n    echo \"$1 is not the root of a hadoop git checkout\"\nfi\n\nHADOOP_ROOT=$1\necho HADOOP_ROOT=$HADOOP_ROOT\nOUT=$(readlink -m `dirname $0`)\necho OUT=$OUT\nTS=$OUT/imported_timestamp\n\n    cd $HADOOP_ROOT &&\n    mvn -pl :hadoop-hdfs-native-client -Pnative compile -Dnative_make_args=\"copy_hadoop_files\"\n    (date > $TS; git rev-parse --abbrev-ref HEAD >> $TS; git log -n 1 >> $TS;  \\\n        echo \"diffs: --------------\" >> $TS; git diff HEAD >> $TS; \\\n        echo \"       --------------\" >> $TS)\n    cd $OUT &&\n    #Delete everything except for pull_hdfs.sh and imported_timestamp\n    find . ! -name 'pull_hdfs.sh' ! -name 'imported_timestamp' ! -name '.' ! -name '..' -exec rm -rf {} + &&\n    cp -R $HADOOP_ROOT/hadoop-hdfs-project/hadoop-hdfs-native-client/src/main/native/libhdfspp . &&\n    cp -R $HADOOP_ROOT/hadoop-hdfs-project/hadoop-hdfs-native-client/target/main/native/libhdfspp/extern libhdfspp/ &&\n    cd libhdfspp &&\n\ttar -czf ../libhdfspp.tar.gz * &&\n\tcd .. &&\n\trm -rf libhdfspp &&\n\tdate >> $TS", "num_lines": 32}
{"repo_name": "azure-kusto-rust", "repo_creator": "Azure", "programming_language": "Shell", "code": "find test -name \"*.json\" -exec bash -c 'jq . {} > {}.tmp && mv {}.tmp {}' \\;", "num_lines": 1}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\n\n# install apache\nsudo apt-get -y install apache2\n\n# restart Apache\nsudo service apache2 restart", "num_lines": 9}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get install -f\n\nsudo apt-get update\n\n# install apache\nsudo apt-get -y install apache2\n\n# restart Apache\nsudo apachectl restart", "num_lines": 11}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n/usr/bin/yes | sudo apt-get update\n/usr/bin/yes | sudo apt install python-pip\n/usr/bin/yes | sudo pip install --upgrade pip\nsudo pip install azure-cli\naz login --msi\naz storage account create -n $1 -g $2 -l $3 --sku Premium_LRS", "num_lines": 8}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\n\n# install apache\nsudo apt-get -y install apache2\n\n# restart Apache\nsudo apachectl restart", "num_lines": 9}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo apt-get install -y openjdk-8-jdk maven git", "num_lines": 4}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#############################################\n# Define colored output func\nfunction title {\n    LGREEN='\\033[1;32m'\n    CLEAR='\\033[0m'\n\n    echo -e ${LGREEN}$1${CLEAR}\n}\n\n#############################################\n\nset -e\n\ntitle 'Generating tasks list'\njava -jar ./ci/java-test-collector-1.0-SNAPSHOT.jar ./\n\ntitle 'Building docker image'\nimage=azuresdk-java:java-$TRAVIS_BUILD_NUMBER\ndocker build -t $image -f ci/Dockerfile .\n\ntitle 'Pushing docker image'\nimage=azuresdk-java:java-$TRAVIS_BUILD_NUMBER\ndocker login azureclidev.azurecr.io -u $AZURESDKDEV_ACR_SP_USERNAME -p $AZURESDK_ACR_SP_PASSWORD\ndocker tag azuresdk-java:java-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-java:java-$TRAVIS_BUILD_NUMBER\ndocker tag azuresdk-java:java-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-java:java-latest\ndocker push azureclidev.azurecr.io/azuresdk-java:java-$TRAVIS_BUILD_NUMBER\ndocker push azureclidev.azurecr.io/azuresdk-java:java-latest\n", "num_lines": 28}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n# ###########################################\n# Define colored output func\nfunction title {\n    LGREEN='\\033[1;32m'\n    CLEAR='\\033[0m'\n\n    echo -e ${LGREEN}$1${CLEAR}\n}\n\n#############################################\nLOG_PARAMS='-Dorg.slf4j.simpleLogger.defaultLogLevel=error -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn --batch-mode' ;\nif [ ${TRAVIS_JDK_VERSION} = \"oraclejdk8\" ]; then\n    title 'Running checkstyle:check'\n    mvn checkstyle:check ;\nfi\ntitle 'Running mvn -pl !azure-samples package javadoc:aggregate -DskipTests=true $LOG_PARAMS'\nmvn -q -pl !azure-samples package javadoc:aggregate -DskipTests=true $LOG_PARAMS ;\necho '==> Starting mvn test ===' ;\nmvn test -q -Dsurefire.rerunFailingTestsCount=3 $LOG_PARAMS -Dparallel=classes -DthreadCount=2 -DforkCount=1C ;\n", "num_lines": 23}
{"repo_name": "azure-libraries-for-java", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"Current limits :\"\nulimit -a\n\nulimit -n\n\nulimit\n\necho \"Setting new limits\"\nulimit -S unlimited\nulimit -H unlimited\n\nulimit -n 65535\n\necho \"updated limits\"\nulimit\n\nulimit -n\n\nulimit -a", "num_lines": 21}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nset -e\nbase=`dirname {BASH_SOURCE[0]}`\nrootdir=\"$( cd \"$base\" && pwd )\"\nnetstd14=\"netstandard1.4\"\nnetstd16=\"netstandard1.6\"\n#netcore11='netcoreapp1.1'\nnetcore20='netcoreapp2.0'\nubuntu1404=\"ubuntu.14.04-x64\"\nnugetOrgSource=\"https://api.nuget.org/v3/index.json\"\n\ndotnet --info\n\ngetBuildTools() {\n    copyFromRootDir=\".\"\n    printf \"Updating Build tools .....\\n\"\n    \n    if [ ! -d ./tools/SdkBuildTools ]; then\n        mkdir ./tools/SdkBuildTools\n    fi\n    if [ ! -d ./tools/SdkBuildTools/targets ]; then\n        mkdir ./tools/SdkBuildTools/targets\n    fi\n\n    if [ ! -d ./tools/SdkBuildTools/targets/core ]; then\n        mkdir ./tools/SdkBuildTools/targets/core\n    fi\n\n    if [ ! -d ./tools/SdkBuildTools/tasks ]; then\n        mkdir ./tools/SdkBuildTools/tasks\n    fi\n\n    if [ ! -d ./tools/SdkBuildTools/tasks/net46 ]; then\n        mkdir ./tools/SdkBuildTools/tasks/net46\n    fi\n\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/additional.targets ./tools/SdkBuildTools/targets/additional.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.Build.props ./tools/SdkBuildTools/targets/common.Build.props\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.NugetPackage.props ./tools/SdkBuildTools/targets/common.NugetPackage.props\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/common.targets ./tools/SdkBuildTools/targets/common.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/signing.targets ./tools/SdkBuildTools/targets/signing.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/ideCmd.targets ./tools/SdkBuildTools/targets/ideCmd.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/utility.targets ./tools/SdkBuildTools/targets/utility.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_AzSdk.props ./tools/SdkBuildTools/targets/core/_AzSdk.props\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_build.proj ./tools/SdkBuildTools/targets/core/_build.proj\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_Directory.Build.props ./tools/SdkBuildTools/targets/core/_Directory.Build.props\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_Directory.Build.targets ./tools/SdkBuildTools/targets/core/_Directory.Build.targets\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/targets/core/_test.props ./tools/SdkBuildTools/targets/core/_test.props\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/common.tasks ./tools/SdkBuildTools/tasks/common.tasks\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Azure.Sdk.Build.Tasks.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Azure.Sdk.Build.Tasks.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Framework.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.Framework.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Tasks.Core.dll ./tools/SdkBuildTools/tasks/net46/Microsoft.Build.Tasks.Core.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/Microsoft.Build.Utilities.Core.dll ./tools/SdkBuildTools/tasks/net46Microsoft.Build.Utilities.Core.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Collections.Immutable.dll ./tools/SdkBuildTools/tasks/net46/System.Collections.Immutable.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Reflection.Metadata.dll ./tools/SdkBuildTools/tasks/net46/System.Reflection.Metadata.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Runtime.InteropServices.RuntimeInformation.dll ./tools/SdkBuildTools/tasks/net46/System.Runtime.InteropServices.RuntimeInformation.dll\n    cp $copyFromRootDir/tools/BuildToolsForSdk/BuildAssets/tasks/net46/System.Threading.Thread.dll ./tools/SdkBuildTools/tasks/net46/System.Threading.Thread.dll\n}\n\n\n\ngetBuildTools\necho Restoring... $ubuntu1404\ndotnet restore Fluent.Tests.sln -r $ubuntu1404\necho Building... $netcore20\n\ndotnet build src/ResourceManagement/ResourceManager/Microsoft.Azure.Management.ResourceManager.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Storage/Microsoft.Azure.Management.Storage.Fluent.csproj -f $netstd14 \n\ndotnet build src/ResourceManagement/Graph.RBAC/Microsoft.Azure.Management.Graph.RBAC.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Network/Microsoft.Azure.Management.Network.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/AppService/Microsoft.Azure.Management.AppService.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Cdn/Microsoft.Azure.Management.Cdn.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Compute/Microsoft.Azure.Management.Compute.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/ContainerRegistry/Microsoft.Azure.Management.ContainerRegistry.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Dns/Microsoft.Azure.Management.Dns.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/CosmosDB/Microsoft.Azure.Management.CosmosDB.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/KeyVault/Microsoft.Azure.Management.KeyVault.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/PrivateDns/Microsoft.Azure.Management.PrivateDns.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/RedisCache/Microsoft.Azure.Management.Redis.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Search/Microsoft.Azure.Management.Search.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/ServiceBus/Microsoft.Azure.Management.ServiceBus.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Sql/Microsoft.Azure.Management.Sql.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/TrafficManager/Microsoft.Azure.Management.TrafficManager.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/ContainerService/Microsoft.Azure.Management.ContainerService.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/ContainerInstance/Microsoft.Azure.Management.ContainerInstance.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Locks/Microsoft.Azure.Management.Locks.Fluent.csproj -f $netstd14\ndotnet build src/ResourceManagement/Azure.Fluent/Microsoft.Azure.Management.Fluent.csproj -f $netstd14\ndotnet build Samples/Samples.csproj  -f $netstd16\ndotnet build Tests/Fluent.Tests/Fluent.Tests.csproj -f $netcore20\ndotnet build Tests/Samples.Tests/Samples.Tests.csproj -f $netcore20\n\necho Running Fluent Tests\ncd $rootdir/Tests/Fluent.Tests\ndotnet test Fluent.Tests.csproj -f $netcore20\n\necho Running Samples Tests\ncd $rootdir/Tests/Samples.Tests\ndotnet test Samples.Tests.csproj -f $netcore20\n\n", "num_lines": 103}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#############################################\n# Define colored output func\nfunction title {\n    LGREEN='\\033[1;32m'\n    CLEAR='\\033[0m'\n\n    echo -e ${LGREEN}$1${CLEAR}\n}\n\n#############################################\n\ntitle 'Generating tasks list'\n./ci/get_tasks_list.sh\n\ntitle 'Building docker image'\nimage=azuresdk-net:net-$TRAVIS_BUILD_NUMBER\ndocker build -t $image -f ci/Dockerfile .\n\ntitle 'Pushing docker image'\ndocker login azureclidev.azurecr.io -u $AZURESDKDEV_ACR_SP_USERNAME -p $AZURESDK_ACR_SP_PASSWORD\ndocker tag azuresdk-net:net-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-net:net-$TRAVIS_BUILD_NUMBER\ndocker tag azuresdk-net:net-$TRAVIS_BUILD_NUMBER azureclidev.azurecr.io/azuresdk-net:net-latest\ndocker push azureclidev.azurecr.io/azuresdk-net:net-$TRAVIS_BUILD_NUMBER\ndocker push azureclidev.azurecr.io/azuresdk-net:net-latest\n", "num_lines": 25}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\nbase=`dirname {BASH_SOURCE[0]}`\nrootdir=\"$( cd \"$base\" && pwd )\"\n\necho $rootdir\n\nsampleTestPath=/azure-libraries-for-net/Tests/Samples.Tests/\nfluentTestPath=/azure-libraries-for-net/Tests/Fluent.Tests/\n\ncd $rootdir/Tests/Samples.Tests/\n\ndotnet test -t --no-build > $rootdir/ci/tasklist\n\necho \"[\" > $rootdir/ci/app/test_index\nwhile read line; do\n    testcase=\"$( echo \"$line\" | cut -d '=' -f 1 )\"\n    if [[ $testcase == Samples* ]] ; then\n        testname=\"$(echo \"$testcase\" | rev | cut -d'.' -f1 | rev)\"\n        recordpath=\"$(echo \"$testcase\" | rev | cut -d'.' -f2-7 | rev)\"\n        sed -e \"s;%testcase%;${testcase};g\" -e \"s|%testpath%|${sampleTestPath}|g\" -e \"s|%recordpath%|${recordpath}|g\" -e \"s|%testname%|${testname}|g\" $rootdir/ci/task_template > $rootdir/ci/file.out\n        task=$(cat $rootdir/ci/file.out)\n        echo $task, >> $rootdir/ci/app/test_index\n    fi\ndone < $rootdir/ci/tasklist\n\ncd $rootdir/Tests/Fluent.Tests/\n\ndotnet test -t --no-build > $rootdir/ci/tasklist\n\nwhile read line; do\n    testcase=\"$( echo \"$line\" | cut -d '=' -f 1 )\"\n    if [[ $testcase == Fluent* ]] ; then\n        testname=\"$(echo \"$testcase\" | rev | cut -d'.' -f1 | rev)\"\n        recordpath=\"$(echo \"$testcase\" | rev | cut -d'.' -f2-7 | rev)\"\n        sed -e \"s/%testcase%/${testcase}/g\" -e \"s|%testpath%|${fluentTestPath}|g\" -e \"s|%recordpath%|${recordpath}|g\" -e \"s|%testname%|${testname}|g\" $rootdir/ci/task_template > $rootdir/ci/file.out\n        task=$(cat $rootdir/ci/file.out)\n        echo $task, >> $rootdir/ci/app/test_index\n    fi\ndone < $rootdir/ci/tasklist\n\n#sed -i '$ s|.$||' ./app/test_index\n\ntruncate -s-2 $rootdir/ci/app/test_index\n\n#sed -i '$! { P; D; }; s|.$||' ./app/test_index\n\necho \"]\" >> $rootdir/ci/app/test_index", "num_lines": 48}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n/usr/bin/yes | sudo apt-get update\n/usr/bin/yes | sudo apt install python-pip\n/usr/bin/yes | sudo pip install --upgrade pip\nsudo pip install azure-cli\naz login --identity -u $1\naz storage account create -n $2 -g $3 -l $4 --sku Premium_LRS\n", "num_lines": 9}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get install -f\n\nsudo apt-get update\n\n# install apache\nsudo apt-get -y install apache2\n\n# restart Apache\nsudo service apache2 restart", "num_lines": 11}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf#!/bin/bash\n\n# install DotNet\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\nsudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg\n\nsudo sh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main\" > /etc/apt/sources.list.d/dotnetdev.list'\nsudo apt-get update\nsudo apt-get install -y dotnet-sdk-2.1.3\n\n# install Git\nsudo apt-get update\nsudo apt-get install -y git\n\n# Refresh environment\nsource /etc/environment", "num_lines": 16}
{"repo_name": "azure-libraries-for-net", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\n\n# install apache\nsudo apt-get -y install apache2\n\n# restart Apache\nsudo service apache2 restart\n", "num_lines": 10}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nnewUser=$newUser\nnewPassword=$newPassword\n\nAddUser()\n{\n\tif [ -e /etc/debian_version ]; then\n\t\techo -e $newPassword'\\n'$newPassword | adduser --gecos \"\" --force-badname -q $newUser\n\t\tisUserAdded=$?\n\telif [ -e /etc/redhat-release ]; then\n\t\t#encryptedPass=$(perl -e 'print crypt($ARGV[0], \"password\")' $newPassword)\n\t\t#adduser $newUser -c \"AutomationUser\" -m -p $encryptedPass\n\t\tadduser $newUser -c \"AutomationUser\" -m\n\t\tisUserAdded=$?\n\t\tif [ $isUserAdded = \"0\" ]; then\n\t\t\techo User added $newUser\n\t\t\techo -e $newPassword'\\n'$newPassword | passwd $newUser\n\t\t\tisUserAdded=$?\n\t\tfi\n\t\t\n\telif [ -e /etc/SuSE-release ]; then\n\t\tuseradd $newUser -c \"AutomationUser\" -m\n\t\tisUserAdded=$?\n\t\tif [ $isUserAdded = \"0\" ]; then\n\t\t\techo User added $newUser\n\t\t\techo -e $newPassword'\\n'$newPassword | passwd $newUser\n\t\t\tisUserAdded=$?\n\t\tfi\n\tfi\n\n\t\n\tif [ $isUserAdded = \"0\" ]; then\n\t    echo \"AUTOMATION_USER_ADDED\"\n\telse\n\t    echo \"AUTOMATION_USER_ADD_FAILED\"\n\tfi\n\n}\nAddUser\nexit 0\n", "num_lines": 51}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nnewUser=$newUser\nnewPassword=$newPassword\n\nAddUser()\n{\n\tegrep \"^$newUser\" /etc/passwd >/dev/null\n    if [ $? -eq 0 ]; then\n        echo \"$newUser exists!\"\n        userdel -r $newUser\n    fi\n\tif [ -e /etc/debian_version ]; then\n\t\techo -e $newPassword'\\n'$newPassword | adduser --gecos \"\" --force-badname -q $newUser\n\t\tisUserAdded=$?\n\telif [ -e /etc/redhat-release ]; then\n\t\tadduser $newUser -c \"AutomationUser\" -m\n\t\tisUserAdded=$?\n\t\tif [ $isUserAdded = \"0\" ]; then\n\t\t\techo User added $newUser\n\t\t\techo -e $newPassword'\\n'$newPassword | passwd $newUser\n\t\t\tisUserAdded=$?\n\t\tfi\n\t\t\n\telif [ -e /etc/SuSE-release ]; then\n\t\tuseradd $newUser -c \"AutomationUser\" -m\n\t\tisUserAdded=$?\n\t\tif [ $isUserAdded = \"0\" ]; then\n\t\t\techo User added $newUser\n\t\t\techo -e $newPassword'\\n'$newPassword | passwd $newUser\n\t\t\tisUserAdded=$?\n\t\tfi\n\telif [ -e /etc/os-release ]; then\n\t\ttmp=`cat /etc/os-release`\n\t\tif [[ \"$tmp\" == *coreos* ]]; then\n\t\t\tuseradd $newUser -c \"AutomationUser\" -m\n\t\t\tisUserAdded=$?\n\t\t\tif [ $isUserAdded = \"0\" ]; then\n\t\t\t\techo User added $newUser\n\t\t\t\techo $newUser:$newPassword | chpasswd\n\t\t\t\tisUserAdded=$?\n\t\t\tfi\n\t\tfi\n\tfi\n\n\t\n\tif [ $isUserAdded = \"0\" ]; then\n        echo \"$newUser ALL=(ALL) ALL\" > /etc/sudoers.d/$newUser\n\t\tchmod 0440 /etc/sudoers.d/$newUser\n\t    echo \"AUTOMATION_USER_ADDED\"\n\telse\n\t    echo \"AUTOMATION_USER_ADD_FAILED\"\n\tfi\n\n}\nAddUser\nexit 0\n", "num_lines": 64}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n############################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n############################################################################\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nusername=$1\nCONSTANTS_FILE=\"constants.sh\"\nStateFile=\"/home/$username/state.txt\"\nSummaryFile=\"/home/$username/summary.log\"\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    echo $1 > $StateFile\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\n#\n# Source the constants.sh file to pickup definitions from\n# the ICA automation\n#\nif [ -e ./$CONSTANTS_FILE ]; then\n    LogMsg \"CONSTANTS FILE: $(cat $CONSTANTS_FILE)\"\n    source $CONSTANTS_FILE\nelse\n    echo \"Warn : no ${CONSTANTS_FILE} found\"\nfi\n\nif [ -e $SummaryFile ]; then\n    LogMsg \"Cleaning up previous copies of summary.log\"\n    rm -f $SummaryFile\nfi\n\n# \n# Create and delete testfile for Trim test\n#\nLogMsg \"Running TRIM test on /mnt/data to Create 5Gb TEST FILE\"\ncd /mnt/data;\ndf -hT | grep /mnt/data\nLogMsg \"Creating 5GB test file in /mnt/data\"\ndd if=/dev/zero of=testfile.txt bs=5G count=1\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in creating test file..\"\n    echo \"Creating test file: Failed\" >> $SummaryFile\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nLogMsg \"Test file is created on /mnt/data and Waiting for Active pages update.\"\nsleep 300\nls -l\ndf -hT | grep /mnt/data\nLogMsg \"Calculate Active pages on TRIM test once test file is created.\"\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED\n\nexit 0", "num_lines": 90}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n############################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n############################################################################\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nusername=$1\nCONSTANTS_FILE=\"constants.sh\"\nStateFile=\"/home/$username/state.txt\"\nSummaryFile=\"/home/$username/summary.log\"\ns\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    echo $1 > $StateFile\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\n#\n# Source the constants.sh file to pickup definitions from\n# the ICA automation\n#\nif [ -e ./$CONSTANTS_FILE ]; then\n    LogMsg \"CONSTANTS FILE: $(cat $CONSTANTS_FILE)\"\n    source $CONSTANTS_FILE\nelse\n    echo \"Warn : no ${CONSTANTS_FILE} found\"\nfi\n\nif [ -e $SummaryFile ]; then\n    LogMsg \"Cleaning up previous copies of summary.log\"\n    rm -f $SummaryFile\nfi\n\n# \n# Verify test file and delete testfile for Trim test\n#\nLogMsg \"Running TRIM test on /mnt/data to Verify created TEST FILE and delete\"\ncd /mnt/data;\nls -l\ndf -hT | grep /mnt/data\nLogMsg \"Deleting 5GB test file in /mnt/data\"\nrm -f testfile.txt\nif [[ $? -eq 0 ]]; then\n    LogMsg \"Test file is deleted successfully..\"\n    echo \"Test file is deleted successfully..\" >> $SummaryFile\nelse\n    LogMsg \"Error in deleting test file..\"\n    echo \"Deleting test file: Failed\" >> $SummaryFile\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nLogMsg \"Waiting for Clear Allocated memory by TRIM.\"\nsleep 600\nls -l\ndf -hT | grep /mnt/data\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED\n\nexit 0", "num_lines": 93}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n############################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n############################################################################\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nusername=$1\nCONSTANTS_FILE=\"constants.sh\"\nStateFile=\"/home/$username/state.txt\"\nSummaryFile=\"/home/$username/summary.log\"\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    #echo $1 > ~/state.txt\n\techo $1 > $StateFile\n}\n\nSetValue()\n{\n    OLD_VALUE=$(cat $1)\n    LogMsg \"$1 's old value is $OLD_VALUE\"\n    if [ \"$OLD_VALUE\" -ne \"$2\" ]; then\n        LogMsg \"Changing $1 to $2\"\n        echo $2 > $1\n    fi\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\n#\n# Source the constants.sh file to pickup definitions from\n# the ICA automation\n#\nif [ -e ./$CONSTANTS_FILE ]; then\n    LogMsg \"CONSTANTS FILE: $(cat $CONSTANTS_FILE)\"\n    source $CONSTANTS_FILE\nelse\n    echo \"Warn : no ${CONSTANTS_FILE} found\"\nfi\n\nif [ -e $SummaryFile ]; then\n    LogMsg \"Cleaning up previous copies of summary.log\"\n    rm -f $SummaryFile\nfi\n\n#DATA_DISK=sdb\nDATA_DISK=$DATA_DISK\nif ! fdisk -l | grep \"Disk /dev/$DATA_DISK\"; then\n    LogMsg \"The /dev/$DATA_DISK not found\"\n    echo \"The /dev/$DATA_DISK not found\" >> $SummaryFile\n    LogMsg \"aborting the test.\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 30\nfi\n\nSetValue /sys/module/scsi_mod/parameters/scsi_logging_level 63\nSetValue /sys/block/$DATA_DISK/device/timeout 180\n\necho \"Test data disk : /dev/$DATA_DISK\" >> $SummaryFile\nDATA_PARTITION=/dev/${DATA_DISK}1\n\n# Create data partition\ndf -hT | grep $DATA_PARTITION && umount $DATA_PARTITION\n[ -b $DATA_PARTITION ] && (echo p; echo d; echo p; echo w) | fdisk /dev/$DATA_DISK\n(echo n; echo p; echo 1; echo; echo; echo w) | fdisk /dev/$DATA_DISK\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in creating data partition..\"\n    echo \"Creating data partition : Failed\" >> $SummaryFile\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nLogMsg \"$DATA_PARTITION data partition is created successfully...\"\n\n# Format DATA_PARTITION\nLogMsg \"File System type is $trimParam\"\nif [ \"$trimParam\" == \"BTRFS\" ]\nthen\n    LogMsg \"Formatting $DATA_PARTITION with BTRFS FS\"\n    mkfs.btrfs -f $DATA_PARTITION || mkfs.btrfs $DATA_PARTITION\nelif [ \"$trimParam\" == \"XFS\" ]\nthen\n    LogMsg \"Formatting $DATA_PARTITION with XFS FS\"\n    mkfs.xfs -f $DATA_PARTITION || mkfs.xfs $DATA_PARTITION\nelif [ \"$trimParam\" == \"EXT4\" ]\nthen\n    if grep -q \"SUSE Linux Enterprise Server 11\" /etc/*-release\n    then\n        LogMsg \"Formatting $DATA_PARTITION with ext3 FS\"\n        mkfs.ext3 -E lazy_itable_init=0 $DATA_PARTITION\n    else\n        LogMsg \"Formatting $DATA_PARTITION with ext4 FS\"\n        mkfs.ext4 -E lazy_itable_init=0 $DATA_PARTITION\n    fi\nelse\n    echo \"Please pass valid File System type\"\n    exit 80\nfi\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in creating file system..\"\n    echo \"Creating file system : Failed\" >> $SummaryFile\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nLogMsg \"$DATA_PARTITION is formatted successfully...\"\n\nfind /sys/devices -name 'provisioning_mode' -exec sh -c 'echo -n unmap > $1' -- {} \\;\n\n# mount DATA_PARTITION\n[ ! -d /mnt/data ] && mkdir /mnt/data\nLogMsg \"Mounting $DATA_PARTITION with discard option\"\nmount -o discard $DATA_PARTITION /mnt/data || mount $DATA_PARTITION /mnt/data\nif [ $? -eq 0 ]; then\n    LogMsg \"Drive mounted successfully...\"    \nelse\n    LogMsg \"Error in mounting drive...\"\n    echo \"Drive mount : Failed\" >> $SummaryFile\n    UpdateTestState $ICA_TESTFAILED\n    exit 70\nfi\n\nif ! grep -q \"SUSE Linux Enterprise Server 11\" /etc/*-release\nthen\n    LogMsg \"Re-mounting / with discard option\"\n    mount -o remount,discard /\nfi\n\n#Block size details\nLogMsg \"Block size used for TRIM test :\"\nblockdev --getbsz /dev/sdb1\n\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED\n\nexit 0", "num_lines": 167}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is library for shell scripts used in Azure Linux Automation.\n# Author: Srikanth Myakam\n# Email\t: v-srm@microsoft.com\n#\n#\n\nfunction get_lis_version ()\n{\n    lis_version=`modinfo hv_vmbus | grep \"^version:\"| awk '{print $2}'`\n    if [ \"$lis_version\" == \"\" ]\n    then\n        lis_version=\"Default_LIS\"\n    fi\n    echo $lis_version\n}\n\nfunction get_host_version ()\n{\n    dmesg | grep \"Host Build\" | sed \"s/.*Host Build://\"| awk '{print  $1}'| sed \"s/;//\"\n}\n\nfunction check_exit_status ()\n{\n    exit_status=$?\n    message=$1\n\n    if [ $exit_status -ne 0 ]; then\n        echo \"$message: Failed (exit code: $exit_status)\" \n        if [ \"$2\" == \"exit\" ]\n        then\n            exit $exit_status\n        fi \n    else\n        echo \"$message: Success\" \n    fi\n}\n\nfunction detect_linux_ditribution_version()\n{\n    local  distro_version=\"Unknown\"\n    if [ -f /etc/centos-release ] ; then\n        distro_version=`cat /etc/centos-release | sed s/.*release\\ // | sed s/\\ .*//`\n    elif [ -f /etc/oracle-release ] ; then\n        distro_version=`cat /etc/oracle-release | sed s/.*release\\ // | sed s/\\ .*//`\n    elif [ -f /etc/redhat-release ] ; then\n        distro_version=`cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//`\n    elif [ -f /etc/os-release ] ; then\n        distro_version=`cat /etc/os-release|sed 's/\"//g'|grep \"VERSION_ID=\"| sed 's/VERSION_ID=//'| sed 's/\\r//'`\n\tfi\n    echo $distro_version\n}\n\nfunction detect_linux_ditribution()\n{\n    local  linux_ditribution=`cat /etc/*release*|sed 's/\"//g'|grep \"^ID=\"| sed 's/ID=//'`\n    local temp_text=`cat /etc/*release*`\n    if [ \"$linux_ditribution\" == \"\" ]\n    then\n        if echo \"$temp_text\" | grep -qi \"ol\"; then\n            linux_ditribution='Oracle'\n        elif echo \"$temp_text\" | grep -qi \"Ubuntu\"; then\n            linux_ditribution='Ubuntu'\n        elif echo \"$temp_text\" | grep -qi \"SUSE Linux\"; then\n            linux_ditribution='SUSE'\n        elif echo \"$temp_text\" | grep -qi \"openSUSE\"; then\n            linux_ditribution='OpenSUSE'\n        elif echo \"$temp_text\" | grep -qi \"centos\"; then\n            linux_ditribution='CentOS'\n        elif echo \"$temp_text\" | grep -qi \"Oracle\"; then\n            linux_ditribution='Oracle'\n        elif echo \"$temp_text\" | grep -qi \"Red Hat\"; then\n            linux_ditribution='RHEL'\n        else\n            linux_ditribution='unknown'\n        fi\n    fi\n    echo \"$(echo \"$linux_ditribution\" | sed 's/.*/\\u&/')\"\n}\n\nfunction updaterepos()\n{\n    ditribution=$(detect_linux_ditribution)\n    case \"$ditribution\" in\n        Oracle|RHEL|CentOS)\n            yum makecache\n            ;;\n    \n        Ubuntu)\n            apt-get update\n            ;;\n        SUSE|openSUSE|sles)\n            zypper refresh\n            ;;\n         \n        *)\n            echo \"Unknown ditribution\"\n            return 1\n    esac\n}\n\nfunction install_rpm ()\n{\n    package_name=$1\n    rpm -ivh --nodeps  $package_name\n    check_exit_status \"install_rpm $package_name\"\n}\n\nfunction install_deb ()\n{\n    package_name=$1\n    dpkg -i  $package_name\n    apt-get install -f\n    check_exit_status \"install_deb $package_name\"\n}\n\nfunction apt_get_install ()\n{\n    package_name=$1\n    DEBIAN_FRONTEND=noninteractive apt-get install -y  --force-yes $package_name\n    check_exit_status \"apt_get_install $package_name\"\n}\n\nfunction yum_install ()\n{\n    package_name=$1\n    yum install -y $package_name\n    check_exit_status \"yum_install $package_name\"\n}\n\nfunction zypper_install ()\n{\n    package_name=$1\n    zypper --non-interactive in $package_name\n    check_exit_status \"zypper_install $package_name\"\n}\n\nfunction install_package ()\n{\n    local package_name=$@\n    ditribution=$(detect_linux_ditribution)\n\tfor i in \"${package_name[@]}\"\n\tdo\n\t    case \"$ditribution\" in\n\t        Oracle|RHEL|CentOS)\n\t            yum_install \"$package_name\"\n\t            ;;\n\n\t        Ubuntu)\n\t            apt_get_install \"$package_name\"\n\t            ;;\n\n\t        SUSE|OpenSUSE|sles)\n\t            zypper_install \"$package_name\"\n\t            ;;\n\n\t        *)\n\t            echo \"Unknown ditribution\"\n\t            return 1\n\t\tesac\n\tdone\n}\n\nfunction creat_partitions ()\n{\n    disk_list=($@)\n    echo \"Creating partitions on ${disk_list[@]}\"\n\n    count=0\n    while [ \"x${disk_list[count]}\" != \"x\" ]\n    do\n       echo ${disk_list[$count]}\n       (echo n; echo p; echo 2; echo; echo; echo t; echo fd; echo w;) | fdisk ${disk_list[$count]}\n       count=$(( $count + 1 ))   \n    done\n}\n\nfunction remove_partitions ()\n{\n    disk_list=($@)\n    echo \"Creating partitions on ${disk_list[@]}\"\n\n    count=0\n    while [ \"x${disk_list[count]}\" != \"x\" ]\n    do\n       echo ${disk_list[$count]}\n       (echo p; echo d; echo w;) | fdisk ${disk_list[$count]}\n       count=$(( $count + 1 ))   \n    done\n}\n\nfunction create_raid_and_mount()\n{\n# Creats RAID using unused data disks attached to the VM.\n    if [[ $# == 3 ]]\n    then\n        local deviceName=$1\n        local mountdir=$2\n        local format=$3\n    else\n        local deviceName=\"/dev/md1\"\n        local mountdir=/data-dir\n        local format=\"ext4\"\n    fi\n\n    local uuid=\"\"\n    local list=\"\"\n\n    echo \"IO test setup started..\"\n    list=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\n    lsblk\n    install_package mdadm\n    echo \"--- Raid $deviceName creation started ---\"\n    (echo y)| mdadm --create $deviceName --level 0 --raid-devices ${#list[@]} ${list[@]}\n    check_exit_status \"$deviceName Raid creation\"\n\n    time mkfs -t $format $deviceName\n    check_exit_status \"$deviceName Raid format\" \n\n    mkdir $mountdir\n    uuid=`blkid $deviceName| sed \"s/.*UUID=\\\"//\"| sed \"s/\\\".*\\\"//\"`\n    echo \"UUID=$uuid $mountdir $format defaults 0 2\" >> /etc/fstab\n    mount $deviceName $mountdir\n    check_exit_status \"RAID ($deviceName) mount on $mountdir as $format\"\n}\n\nfunction remote_copy ()\n{\n    remote_path=\"~\"\n\n    while echo $1 | grep -q ^-; do\n       eval $( echo $1 | sed 's/^-//' )=$2\n       shift\n       shift\n    done\n\n    if [[ `which sshpass` == \"\" ]]\n    then\n        echo \"sshpass not installed\\n Installing now...\" \n        install_package \"sshpass\" \n    fi\n\n    if [ \"x$host\" == \"x\" ] || [ \"x$user\" == \"x\" ] || [ \"x$passwd\" == \"x\" ] || [ \"x$filename\" == \"x\" ] ; then\n       echo \"Usage: remote_copy -user <username> -passwd <user password> -host <host ipaddress> -filename <filename> -remote_path <location of the file on remote vm> -cmd <put/get>\"\n       return\n    fi\n\n    if [ \"$cmd\" == \"get\" ] || [ \"x$cmd\" == \"x\" ]; then\n       source_path=\"$user@$host:$remote_path/$filename\"\n       destination_path=\".\"\n    elif [ \"$cmd\" == \"put\" ]; then\n       source_path=$filename\n       destination_path=$user@$host:$remote_path/\n    fi\n\n    status=`sshpass -p $passwd scp -o StrictHostKeyChecking=no $source_path $destination_path 2>&1`\n    echo $status\n}\n\nfunction remote_exec ()\n{\n    while echo $1 | grep -q ^-; do\n       eval $( echo $1 | sed 's/^-//' )=$2\n       shift\n       shift\n    done\n    cmd=$@\n    if [[ `which sshpass` == \"\" ]]\n    then\n        echo \"sshpass not installed\\n Installing now...\" \n        install_package \"sshpass\" \n    fi\n\n    if [ \"x$host\" == \"x\" ] || [ \"x$user\" == \"x\" ] || [ \"x$passwd\" == \"x\" ] || [ \"x$cmd\" == \"x\" ] ; then\n       echo \"Usage: remote_exec -user <username> -passwd <user password> -host <host ipaddress> <onlycommand>\"\n       return\n    fi\n\n    status=`sshpass -p $passwd ssh -t -o StrictHostKeyChecking=no $user@$host $cmd 2>&1`\n    echo $status\n}\n\nfunction set_user_password {\n    # This routine can set root or any user's password. \n    if [[ $# == 3 ]]\n    then\n        user=$1\n        user_password=$2\n        sudo_password=$3\n    else\n        echo \"Usage: user user_password sudo_password\"\n        return -1\n    fi\n\n    hash=$(openssl passwd -1 $user_password)\n\n    string=`echo $sudo_password | sudo -S cat /etc/shadow | grep $user`\n\n    if [ \"x$string\" == \"x\" ]\n    then\n        echo \"$user not found in /etc/shadow\"\n        return -1\n    fi\n\n    IFS=':' read -r -a array <<< \"$string\"\n    line=\"${array[0]}:$hash:${array[2]}:${array[3]}:${array[4]}:${array[5]}:${array[6]}:${array[7]}:${array[8]}\"\n\n    echo $sudo_password | sudo -S sed -i \"s#^${array[0]}.*#$line#\" /etc/shadow\n\n    if [ `echo $sudo_password | sudo -S cat /etc/shadow| grep $line|wc -l` != \"\" ]\n    then\n        echo \"Password set succesfully\"\n    else\n        echo \"failed to set password\"\n    fi\n}\n\nfunction collect_VM_properties ()\n{\n# This routine collects the information in .csv format.\n# Anyone can expand this with useful details.\n# Better if it can collect details without su permission.\n\n    local output_file=$1\n\n    if [ \"x$output_file\" == \"x\" ]\n    then\n        output_file=\"VM_properties.csv\"\n    fi\n\n    echo \"\" > $output_file\n    echo \",OS type,\"`detect_linux_ditribution` `detect_linux_ditribution_version` >> $output_file\n    echo \",Kernel version,\"`uname -r` >> $output_file\n    echo \",LIS Version,\"`get_lis_version` >> $output_file\n    echo \",Host Version,\"`get_host_version` >> $output_file\n    echo \",Total CPU cores,\"`nproc` >> $output_file\n    echo \",Total Memory,\"`free -h|grep Mem|awk '{print $2}'` >> $output_file\n    echo \",Resource disks size,\"`lsblk|grep \"^sdb\"| awk '{print $4}'`  >> $output_file\n    echo \",Data disks attached,\"`lsblk | grep \"^sd\" | awk '{print $1}' | sort | grep -v \"sd[ab]$\" | wc -l`  >> $output_file\n    echo \",eth0 MTU,\"`ifconfig eth0|grep MTU|sed \"s/.*MTU:\\(.*\\) .*/\\1/\"` >> $output_file\n    echo \",eth1 MTU,\"`ifconfig eth1|grep MTU|sed \"s/.*MTU:\\(.*\\) .*/\\1/\"` >> $output_file\n}\n\nfunction keep_cmd_in_startup ()\n{\n\ttestcommand=$*\n\tstartup_files=\"/etc/rc.d/rc.local /etc/rc.local /etc/SuSE-release\"\n\tcount=0\n\tfor file in $startup_files \n\tdo\n\t\tif [[ -f $file ]]\n\t\tthen\n\t\t\tif ! grep -q \"${testcommand}\" $file\n\t\t\tthen\n\t\t\t\tsed \"/^\\s*exit 0/i ${testcommand}\" $file -i\n\t\t\t\tif ! grep -q \"${testcommand}\" $file\n\t\t\t\tthen\n\t\t\t\t\techo $testcommand >> $file\n\t\t\t\tfi\n\t\t\t\techo \"Added $testcommand >> $file\"\n\t\t\t\t((count++))\n\t\t\tfi\n\t\tfi\t\n\tdone\n\tif [ $count == 0 ]\n\tthen\n\t\techo \"Cannot find $startup_files files\"\n\tfi\n}\n\nfunction remove_cmd_from_startup ()\n{\n\ttestcommand=$*\n\tstartup_files=\"/etc/rc.d/rc.local /etc/rc.local /etc/SuSE-release\"\n\tcount=0\n\tfor file in $startup_files \n\tdo\n\t\tif [[ -f $file ]]\n\t\tthen\n\t\t\tif grep -q \"${testcommand}\" $file\n\t\t\tthen\n\t\t\t\tsed \"s/${testcommand}//\" $file -i\n\t\t\t\t((count++))\n\t\t\t\techo \"Removed $testcommand from $file\"\n\t\t\tfi\n\t\tfi\t\n\tdone\n\tif [ $count == 0 ]\n\tthen\n\t\techo \"Cannot find $testcommand in $startup_files files\"\n\tfi\n}\n\n", "num_lines": 396}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This example script creates bonding network devices based on synthetic NIC\n# (the virtual network adapter usually provided by Hyper-V) and the matching\n# VF NIC (SRIOV virtual function). So the synthetic NIC and VF NIC can\n# function as one network device, and fail over to the synthetic NIC if VF is\n# down.\n#\n# Usage:\n# - After configured vSwitch and vNIC with SRIOV, start Linux virtual\n#   machine (VM)\n# - Run this scripts on the VM. It will create configuration files in\n#   distro specific directory.\n# - Reboot the VM, so that the bonding config are enabled.\n#\n# The config files are DHCP by default. You may edit them if you need to change\n# to Static IP or change other settings.\n#\n\nsysdir=/sys/class/net\nnetvsc_cls={f8615163-df3e-46c5-913f-f2d2f965ed0e}\nbondcnt=0\n\n# Detect Distro\nif [ -f /etc/redhat-release ];\nthen\n\tcfgdir=/etc/sysconfig/network-scripts\n\tdistro=redhat\nelif grep -q 'Ubuntu' /etc/issue\nthen\n\tcfgdir=/etc/network\n\tdistro=ubuntu\nelif grep -q 'SUSE' /etc/issue\nthen\n\tcfgdir=/etc/sysconfig/network\n\tdistro=suse\nelse\n\techo \"Unsupported Distro\"\n\texit 1\nfi\n\necho Detected Distro: $distro, or compatible\n\n# Get a list of ethernet names\nlist_eth=(`cd $sysdir && ls -d */ | cut -d/ -f1 | grep -v bond`)\neth_cnt=${#list_eth[@]}\n\necho List of net devices:\n\n# Get the MAC addresses\nfor (( i=0; i < $eth_cnt; i++ ))\ndo\n\tlist_mac[$i]=`cat $sysdir/${list_eth[$i]}/address`\n\techo ${list_eth[$i]}, ${list_mac[$i]}\ndone\n\n# Find NIC with matching MAC\nfor (( i=0; i < $eth_cnt-1; i++ ))\ndo\n\tfor (( j=i+1; j < $eth_cnt; j++ ))\n\tdo\n\t\tif [ \"${list_mac[$i]}\" = \"${list_mac[$j]}\" ]\n\t\tthen\n\t\t\tlist_match[$i]=${list_eth[$j]}\n\t\t\tbreak\n\t\tfi\n\tdone\ndone\n\nfunction create_eth_cfg_redhat {\n\tlocal fn=$cfgdir/ifcfg-$1\n\n\trm -f $fn\n\techo DEVICE=$1 >>$fn\n\techo TYPE=Ethernet >>$fn\n\techo BOOTPROTO=none >>$fn\n\techo ONBOOT=yes >>$fn\n\techo NM_CONTROLLED=no >>$fn\n\techo PEERDNS=yes >>$fn\n\techo IPV6INIT=yes >>$fn\n\techo MASTER=$2 >>$fn\n\techo SLAVE=yes >>$fn\n}\n\nfunction create_eth_cfg_pri_redhat {\n\tcreate_eth_cfg_redhat $1 $2\n}\n\nfunction create_bond_cfg_redhat {\n\tlocal fn=$cfgdir/ifcfg-$1\n\n\trm -f $fn\n\techo DEVICE=$1 >>$fn\n\techo TYPE=Bond >>$fn\n\techo BOOTPROTO=dhcp >>$fn\n\techo ONBOOT=yes >>$fn\n\techo NM_CONTROLLED=no >>$fn\n\techo PEERDNS=yes >>$fn\n\techo IPV6INIT=yes >>$fn\n\techo BONDING_MASTER=yes >>$fn\n\techo BONDING_OPTS=\\\"mode=active-backup miimon=100 primary=$2\\\" >>$fn\n}\n\nfunction create_eth_cfg_ubuntu {\n\tlocal fn=$cfgdir/interfaces\n\n\techo $'\\n'auto $1 >>$fn\n\techo iface $1 inet manual >>$fn\n\techo bond-master $2 >>$fn\n}\n\nfunction create_eth_cfg_pri_ubuntu {\n\tlocal fn=$cfgdir/interfaces\n\n\tcreate_eth_cfg_ubuntu $1 $2\n\techo bond-primary $1 >>$fn\n}\n\nfunction create_bond_cfg_ubuntu {\n\tlocal fn=$cfgdir/interfaces\n\n\techo $'\\n'auto $1 >>$fn\n\techo iface $1 inet dhcp >>$fn\n\techo bond-mode active-backup >>$fn\n\techo bond-miimon 100 >>$fn\n\techo bond-slaves none >>$fn\n}\n\nfunction create_eth_cfg_suse {\n        local fn=$cfgdir/ifcfg-$1\n\n        rm -f $fn\n\techo BOOTPROTO=none >>$fn\n\techo STARTMODE=auto >>$fn\n}\n\nfunction create_eth_cfg_pri_suse {\n\tcreate_eth_cfg_suse $1\n}\n\nfunction create_bond_cfg_suse {\n\tlocal fn=$cfgdir/ifcfg-$1\n\n\trm -f $fn\n\techo BOOTPROTO=dhcp >>$fn\n\techo STARTMODE=auto >>$fn\n\techo BONDING_MASTER=yes >>$fn\n\techo BONDING_SLAVE_0=$2 >>$fn\n\techo BONDING_SLAVE_1=$3 >>$fn\n\techo BONDING_MODULE_OPTS=\\'mode=active-backup miimon=100 primary=$2\\' >>$fn\n}\n\nfunction create_bond {\n\tlocal bondname=bond$bondcnt\n\tlocal primary\n\tlocal secondary\n\n\tlocal class_id1=`cat $sysdir/$1/device/class_id 2>/dev/null`\n\tlocal class_id2=`cat $sysdir/$2/device/class_id 2>/dev/null`\n\n\tif [ \"$class_id1\" = \"$netvsc_cls\" ]\n\tthen\n\t\tprimary=$2\n\t\tsecondary=$1\n\telif [ \"$class_id2\" = \"$netvsc_cls\" ]\n\tthen\n\t\tprimary=$1\n\t\tsecondary=$2\n\telse\n\t\treturn 0\n\tfi\n\n\techo $'\\nBond name:' $bondname\n\n\techo configuring $primary\n\tcreate_eth_cfg_pri_$distro $primary $bondname\n\n\techo configuring $secondary\n\tcreate_eth_cfg_$distro $secondary $bondname\n\n\techo creating: $bondname with primary slave: $primary\n\tcreate_bond_cfg_$distro $bondname $primary $secondary\n\n\tlet bondcnt=bondcnt+1\n}\n\nfor (( i=0; i < $eth_cnt-1; i++ ))\ndo\n        if [ -n \"${list_match[$i]}\" ]\n        then\n\t\tcreate_bond ${list_eth[$i]} ${list_match[$i]}\n        fi\ndone\n", "num_lines": 194}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script build linuxnext .deb file.  \n# Author: Sivakanth Rebba\n# Email\t: v-sirebb@microsoft.com\n#\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nCONSTANTS_FILE=\"constants.sh\"\n\n#username=`cat /var/log/cloud-init.log | grep Adding| sed \"s/.*user //\"`\nusername=$1\ncurrent_kernel=`uname -r`\ncode_path=\"/home/$username/code\"\n. $code_path/azuremodules.sh\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    echo $1 > $code_path/state.txt\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\nif [ -e $code_path/summary.log ]; then\n    LogMsg \"Cleaning up previous copies of summary.log\"\n    rm -f $code_path/summary.log\nfi\n\necho \"build not is started.. \" > $code_path/build.log\ncd $code_path\n\nupdaterepos\ninstall_package git-core sysstat gcc make libssl-dev kernel-package\nLogMsg \"linux next git clone is RUNNING..\"\ngit clone git://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git  \nif [ $? -ne 0 ]; then\n    LogMsg \"Error in linux next git clone\"\n    echo \"linux next git clone: Failed\" >> $code_path/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\n\ncd linux-next\ntouch Documentation/Changes\n## Make config file\nLogMsg \"Make .config file is RUNNING..\"\ncp /boot/config-$current_kernel .config\n\nCONFIG_FILE=.config\nyes \"\" | make oldconfig\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in mkaing .config file\"\n    echo \"make .config: Failed\" >> $code_path/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nsed --in-place=.orig -e s:\"# CONFIG_HYPERVISOR_GUEST is not set\":\"CONFIG_HYPERVISOR_GUEST=y\\nCONFIG_HYPERV=y\\nCONFIG_HYPERV_UTILS=y\\nCONFIG_HYPERV_BALLOON=y\\nCONFIG_HYPERV_STORAGE=y\\nCONFIG_HYPERV_NET=y\\nCONFIG_HYPERV_KEYBOARD=y\\nCONFIG_FB_HYPERV=y\\nCONFIG_HID_HYPERV_MOUSE=y\": ${CONFIG_FILE}\nsed --in-place -e s:\"CONFIG_PREEMPT_VOLUNTARY=y\":\"# CONFIG_PREEMPT_VOLUNTARY is not set\": ${CONFIG_FILE}\nsed --in-place -e s:\"# CONFIG_EXT4_FS is not set\":\"CONFIG_EXT4_FS=y\\nCONFIG_EXT4_FS_XATTR=y\\nCONFIG_EXT4_FS_POSIX_ACL=y\\nCONFIG_EXT4_FS_SECURITY=y\": ${CONFIG_FILE}\nsed --in-place -e s:\"# CONFIG_REISERFS_FS is not set\":\"CONFIG_REISERFS_FS=y\\nCONFIG_REISERFS_PROC_INFO=y\\nCONFIG_REISERFS_FS_XATTR=y\\nCONFIG_REISERFS_FS_POSIX_ACL=y\\nCONFIG_REISERFS_FS_SECURITY=y\": ${CONFIG_FILE}\nsed --in-place -e s:\"# CONFIG_TULIP is not set\":\"CONFIG_TULIP=y\\nCONFIG_TULIP_MMIO=y\": ${CONFIG_FILE}\n\nsed --in-place -e s:\"CONFIG_STAGING=y\":\"# CONFIG_STAGING is not set\": ${CONFIG_FILE}  #becuase of a recent linux-next build error\n\nyes \"\" | make oldconfig\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in mkaing .config file\"\n    echo \"make .config: Failed\" >> $code_path/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\nexport CONCURRENCY_LEVEL=`nproc`\n\n# Build and Install\nLogMsg \"build STARTED..\"\necho \"build STARTED..\" >> $code_path/build.log\n#make-kpkg --append-to-version=.0001 kernel-image --initrd > $code_path/build.log\nmake-kpkg kernel-image --initrd >> $code_path/build.log\nif [ $? -ne 0 ]; then\n    LogMsg \"Error in making kernel image linux next deb\"\n    echo \"making linux next deb package: Failed\" >> $code_path/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 80\nfi\n\n#copy linux-next.deb to home directory\ncp $code_path/linux-image*.deb /home/$username\n\nLogMsg \"Compressing log files.. \"\ncd $code_path; tar -cvf logs.tar *.*\n\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED\n", "num_lines": 110}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\noldPassword=$oldPassword\nnewPassword=$newPassword\n\nUpdatePassword()\n{\n#echo $newPassword |  passwd $user --stdin\n    if [ -e /etc/debian_version ]; then\n        echo \"Changing Password for : Ubuntu/Debian\"\n        echo -e $oldPassword'\\n'$newPassword'\\n'$newPassword | passwd\n        exitVal=$?\n        if [ $exitVal -ne \"0\" ]; then\n                echo -e $newPassword'\\n'$newPassword | passwd\n                exitVal=$?\n        fi\n    fi\n    if [ -e /etc/redhat-release ]; then\n        echo \"Changing Password for : Redhat/CentOS\"\n        echo -e $oldPassword'\\n'$newPassword'\\n'$newPassword | passwd\n        exitVal=$?\n    fi\n    if [ -e /etc/SuSE-release ]; then\n        echo \"Changing Password for : SUSE/SLES\"\n        echo -e $oldPassword'\\n'$newPassword'\\n'$newPassword | passwd\n        exitVal=$?\n    fi\n#    echo \"exit Code : $exitVal\"\n    if [ $exitVal = \"0\" ]; then\n        echo \"PASSWORD_CHANGED_SUCCESSFULLY\"\n    else\n        echo \"PASSWWORD_CHANGE_FALED_EXIT_CODE_$exitVal\"\n    fi\n}\nUpdatePassword\nexit 0\n", "num_lines": 46}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [[ \"`cat /var/lib/hyperv/.kvp_pool_0`\" =~ NdDriverVersion.*142 ]]; then\n    echo \"NdDriverVersion == 142 found in /var/lib/hyperv/.kvp_pool_0\"\n    echo \"Starting kernel update...\"\n    beforeUpdate=`uname -r`\n    zypper --non-interactive --no-gpg-checks update kernel*\n    afterUpdate=`uname -r`\n    if [ $beforeUpdate == $afterUpdate ];then\n        echo \"Skipping reboot as no update available for kernel $beforeUpdate\"\n    else\n        echo \"Rebooting VM in 60 seconds ... Ctrl+C to abort reboot.\"\n        sleep 60\n        init 6\n    fi\nelse\n    echo \"NdDriverVersion == 142 not found in /var/lib/hyperv/.kvp_pool_0\"\nfi\n", "num_lines": 18}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script serves as iperf client.\n# Author: Srikanth M\n# Email\t: v-srm@microsoft.com\n#\n\nif [[ $# == 4 ]]\nthen\n\tserver_ip=$1\n\tusername=$2\n\ttesttype=$3\n\tbuffersize=$4\n\tif [[ $testtype == \"UDP\" ]]\n\tthen\n\t\ttesttypeOption=\" -u -b 0\"\n\t\tbuffersizeOption=\" -l $buffersize\"\n\telse\n\t\ttesttype=\"\"\n\tfi\nelse\n\techo \"Usage: bash $0 <server_ip> <vm_loginuser>\"\n\texit -1\nfi\n\ncode_path=\"/home/$username/code/\"\n. $code_path/azuremodules.sh\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    echo $1 > $code_path/state.txt\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\n\nif [[ `which iperf3` == \"\" ]]\nthen\n    echo \"iperf3 not installed\\n Installing now...\"\n    install_package \"iperf3\"\nfi\n\necho \"Sleeping 5 mins to get the server ready..\"\nsleep 300\nport_number=8001\nduration=300\ncode_path=\"/home/$username/code\"\nfor number_of_connections in 1 2 4 8 16 32 64 128 256 512 1024\n\ndo\n\tbash $code_path/sar-top.sh $duration $number_of_connections $username $testtype $buffersize&\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"sar-top failed to execute\"\n\t\techo \"sar-top failed to execute\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 80\n\tfi\n\techo \"Starting client with $number_of_connections connections\"\n\twhile [ $number_of_connections -gt 64 ]; do\n\t\tnumber_of_connections=$(($number_of_connections-64))\n\t\tiperf3 -c $server_ip -p $port_number -P 64 -t $duration $testtypeOption $buffersizeOption > /dev/null &\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"iperf3 failed to connect server\"\n\t\t\techo \"iperf3 failed to connect server\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 80\n\t\tfi\n\t\tport_number=$((port_number+1))\n\tdone\n\tif [ $number_of_connections -ne 0 ]\n\tthen\n\t\tiperf3 -c $server_ip -p $port_number -P $number_of_connections -t $duration $testtypeOption $buffersizeOption > /dev/null &\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"iperf3 failed to connect server\"\n\t\t\techo \"iperf3 failed to connect server\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 80\n\t\tfi\n\tfi\n\n\tconnections_count=`netstat -natp | grep iperf | grep ESTA | wc -l`\n\techo \"$connections_count iperf clients are connected to server\"\n\tsleep $(($duration+10))\ndone\n\nlogs_dir=logs-`hostname`-$testtype-$buffersize\n\ncollect_VM_properties $code_path/$logs_dir/VM_properties.csv\n\nbash $code_path/generate_csvs.sh $code_path/$logs_dir $testtype $buffersize\nif [ $? -ne 0 ]; then\n\tLogMsg \"Failed to generate test results .csv file\"\n\techo \"Failed to generate test results .csv file\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 80\nfi\nmv /etc/rc.d/after.local.bkp /etc/rc.d/after.local\nmv /etc/rc.local.bkp /etc/rc.local\nmv /etc/rc.d/rc.local.bkp /etc/rc.d/rc.local\necho \"$testtype $buffersize test is Completed at Client\"\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED", "num_lines": 119}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nduration=$1\nfilename=$2\ncapture_cpu(){\nfor i in $(seq 1 $duration)\ndo\n\tdate_j=`date +\"%x-%T\"`\n\ttop_j=`top -bn1 | grep \"Cpu(s)\" | sed \"s/.*, *\\([0-9.]*\\)%* id.*/\\1/\" | awk '{print 100 - $1}'`\n\techo $date_j,$top_j>> $filename-top.log\n\tsleep 1\ndone\n}\n\ncapture_connections(){\nfor i in $(seq 1 $duration)\ndo\n\tdate_i=`date +\"%x-%T\"`\n\tnetstat_i=`netstat -nat | grep ESTABLISHED | wc -l`\n\techo $date_i,$netstat_i >> $filename-connections.log\n\tsleep 1\ndone\n}\necho $filename-top.log $duration $filename $filename-sar.log \n[ -f $filename-top.log  ] && rm -rf $filename-top.log \n[ -f $filename-sar.log  ] && rm -rf $filename-sar.log \n[ -f $filename-connections.log  ] && rm -rf $filename-connections.log\nsar -n DEV 1 $duration 2>&1 > $filename-sar.log&\nsar_pid=$!\ncapture_cpu &\ncapture_cpu_pid=$!\ncapture_connections &\ncapture_connections_pid=$!\nsleep $duration\nkill -9 $sar_pid $capture_cpu_pid $capture_connections_pid \nexit 0\n\n", "num_lines": 37}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndmesg > `hostname`-dmesg.txt\ncp /var/log/waagent.log `hostname`-waagent.log.txt\nuname -r > `hostname`-kernelVersion.txt\nuptime -s > `hostname`-uptime.txt || echo \"UPTIME_COMMAND_ERROR\" > `hostname`-uptime.txt", "num_lines": 6}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\nbootLogs=`dmesg`\nif [[ $bootLogs =~ \"Data path switched to VF\" ]];\nthen\n\techo \"DATAPATH_SWITCHED_TO_VF\"\nelse\n\tif [[ $DISTRO =~ \"Ubuntu\" ]];\n\tthen\n\t\t#A temporary workaround for SRIOV issue.\n\t\tmacAddr=`cat /sys/class/net/eth0/address`\n\t\techo \"SUBSYSTEM==\\\"net\\\", ACTION==\\\"add\\\", DRIVERS==\\\"hv_netvsc\\\", ATTR{address}==\\\"${macAddr}\\\", NAME=\\\"eth0\\\"\" > /etc/udev/rules.d/70-persistent-net.rules\n\t\techo \"SUBSYSTEM==\\\"net\\\", ACTION==\\\"add\\\", DRIVERS==\\\"mlx4_core\\\", ATTR{address}==\\\"${macAddr}\\\", NAME=\\\"vf0\\\"\" >> /etc/udev/rules.d/70-persistent-net.rules\n\t\t#sed -i '/rename*/c\\vf0' /etc/network/interfaces\n\t\techo \"SYSTEM_RESTART_REQUIRED\"\n\tfi\nfi\nexit 0", "num_lines": 19}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#Reference:  https://docs.microsoft.com/en-us/azure/virtual-network/virtual-network-create-vm-accelerated-networking\nbootLogs=`dmesg`\nif [[ $bootLogs =~ \"Data path switched to VF\" ]];\nthen\n\techo \"DATAPATH_SWITCHED_TO_VF\"\nelse\n\twget https://raw.githubusercontent.com/torvalds/linux/master/tools/hv/bondvf.sh\n\tchmod +x ./bondvf.sh\n\t./bondvf.sh\n\tcp bondvf.sh /etc/init.d\n\tupdate-rc.d bondvf.sh defaults\n\techo \"SYSTEM_RESTART_REQUIRED\"\nfi\nexit 0", "num_lines": 16}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n#\n#\n# Description:\n#######################################################################\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\n\nif [ -z \"$customKernel\" ]; then\n        echo \"Please mention -customKernel next\"\n        exit 1\nfi\nif [ -z \"$logFolder\" ]; then\n        logFolder=\"~\"\n        echo \"-logFolder is not mentioned. Using ~\"\nelse\n        echo \"Using Log Folder $logFolder\"\nfi\n\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> $logFolder/build-customKernel.txt\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > $logFolder/state.txt\n}\n\n\ntouch $logFolder/build-customKernel.txt\n\nCheckInstallLockUbuntu()\n{\n        dpkgPID=$(pidof dpkg)\n        if [ $? -eq 0 ];then\n                LogMsg \"Another install is in progress. Waiting 10 seconds.\"\n                sleep 10\n                CheckInstallLockUbuntu\n        else\n                LogMsg \"No lock on dpkg present.\"\n        fi\n}\n\n\nInstallKernel()\n{\n        sleep 10\n        if [ \"${customKernel}\" == \"linuxnext\" ]; then\n                kernelSource=\"https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git\"\n                sourceDir=\"linux-next\"\n        elif [ \"${customKernel}\" == \"proposed\" ]; then\n                DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n                if [[ $DISTRO =~ \"Xenial\" ]];\n                then\n                        LogMsg \"Enabling proposed repositry...\"\n                        echo \"deb http://archive.ubuntu.com/ubuntu/ xenial-proposed restricted main multiverse universe\" >> /etc/apt/sources.list\n                        rm -rf /etc/apt/preferences.d/proposed-updates\n                        LogMsg \"Installing linux-image-generic from proposed repository.\"\n                        apt -y update >> $logFolder/build-customKernel.txt 2>&1\n                        apt -y --fix-missing upgrade >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                elif [[ $DISTRO =~ \"Trusty\" ]];\n                then\n                        LogMsg \"Enabling proposed repositry...\"\n                        echo \"deb http://archive.ubuntu.com/ubuntu/ trusty-proposed restricted main multiverse universe\" >> /etc/apt/sources.list\n                        rm -rf /etc/apt/preferences.d/proposed-updates\n                        LogMsg \"Installing linux-image-generic from proposed repository.\"\n                        apt -y update >> $logFolder/build-customKernel.txt 2>&1\n                        apt -y --fix-missing upgrade >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                fi\n                UpdateTestState $ICA_TESTCOMPLETED\n                if [ $kernelInstallStatus -ne 0 ]; then\n                        LogMsg \"CUSTOM_KERNEL_FAIL\"\n                        UpdateTestState $ICA_TESTFAILED\n                else\n                        LogMsg \"CUSTOM_KERNEL_SUCCESS\"\n                        UpdateTestState $ICA_TESTCOMPLETED\n                fi\n        elif [ \"${customKernel}\" == \"latest\" ]; then\n                DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n                if [[ $DISTRO =~ \"Ubuntu\" ]];\n                then\n                        LogMsg \"Installing linux-image-generic from repository.\"\n                        apt -y update >> $logFolder/build-customKernel.txt 2>&1\n                        apt -y --fix-missing upgrade >> $logFolder/build-customKernel.txt 2>&1\n                        LogMsg \"Installing linux-image-generic from proposed repository.\"\n                        apt -y update >> $logFolder/build-customKernel.txt 2>&1\n                        apt -y --fix-missing upgrade >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                fi\n                UpdateTestState $ICA_TESTCOMPLETED\n                if [ $kernelInstallStatus -ne 0 ]; then\n                        LogMsg \"CUSTOM_KERNEL_FAIL\"\n                        UpdateTestState $ICA_TESTFAILED\n                else\n                        LogMsg \"CUSTOM_KERNEL_SUCCESS\"\n                        UpdateTestState $ICA_TESTCOMPLETED\n                fi\n        elif [ \"${customKernel}\" == \"netnext\" ]; then\n                kernelSource=\"https://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git\"\n                sourceDir=\"net-next\"\n        elif [[ $customKernel == *.deb ]]; then\n                LogMsg \"Custom Kernel:$customKernel\"\n                apt-get update\n                if [[ $customKernel =~ \"http\" ]];then\n\t\t\t\t\t\tCheckInstallLockUbuntu\n                        apt-get install wget\n                        LogMsg \"Debian package web link detected. Downloading $customKernel\"\n                        wget $customKernel\n                        LogMsg \"Installing ${customKernel##*/}\"\n                        dpkg -i \"${customKernel##*/}\"  >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                else\n                        CheckInstallLockUbuntu\n                        prefix=\"localfile:\"\n                        LogMsg \"Installing ${customKernel#$prefix}\"\n                        dpkg -i \"${customKernel#$prefix}\"  >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                fi\n\n                UpdateTestState $ICA_TESTCOMPLETED\n                if [ $kernelInstallStatus -ne 0 ]; then\n                        LogMsg \"CUSTOM_KERNEL_FAIL\"\n                        UpdateTestState $ICA_TESTFAILED\n                else\n                        LogMsg \"CUSTOM_KERNEL_SUCCESS\"\n                        UpdateTestState $ICA_TESTCOMPLETED\n                fi\n        elif [[ $customKernel == *.rpm ]]; then\n                LogMsg \"Custom Kernel:$customKernel\"\n\n                if [[ $customKernel =~ \"http\" ]];then\n                        yum -y install wget\n                        LogMsg \"RPM package web link detected. Downloading $customKernel\"\n                        wget $customKernel\n                        LogMsg \"Installing ${customKernel##*/}\"\n                        rpm -ivh \"${customKernel##*/}\"  >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                else\n                        prefix=\"localfile:\"\n                        LogMsg \"Installing ${customKernel#$prefix}\"\n                        rpm -ivh \"${customKernel#$prefix}\"  >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n\n                fi\n                UpdateTestState $ICA_TESTCOMPLETED\n                if [ $kernelInstallStatus -ne 0 ]; then\n                        LogMsg \"CUSTOM_KERNEL_FAIL\"\n                        UpdateTestState $ICA_TESTFAILED\n                else\n                        LogMsg \"CUSTOM_KERNEL_SUCCESS\"\n                        UpdateTestState $ICA_TESTCOMPLETED\n                        grub2-set-default 0\n                fi\n        fi\n        if [[ ${customKernel} == \"linuxnext\" ]] || [[ ${customKernel} == \"netnext\" ]]; then\n                LogMsg \"Custom Kernel:$customKernel\"\n                chmod +x $logFolder/DetectLinuxDistro.sh\n                LinuxDistro=`$logFolder/DetectLinuxDistro.sh`\n                if [ $LinuxDistro == \"SLES\" -o $LinuxDistro == \"SUSE\" ]; then\n                        #zypper update\n                        zypper --non-interactive install git-core make tar gcc bc patch dos2unix wget xz\n                        #TBD\n                elif [ $LinuxDistro == \"CENTOS\" -o $LinuxDistro == \"REDHAT\" -o $LinuxDistro == \"FEDORA\" -o $LinuxDistro == \"ORACLELINUX\" ]; then\n                        #yum update\n                        yum install -y git make tar gcc bc patch dos2unix wget xz\n                        #TBD\n                elif [ $LinuxDistro == \"UBUNTU\" ]; then\n                        unset UCF_FORCE_CONFFOLD\n                        export UCF_FORCE_CONFFNEW=YES\n                        export DEBIAN_FRONTEND=noninteractive\n                        ucf --purge /etc/kernel-img.conf\n                        export DEBIAN_FRONTEND=noninteractive\n                        LogMsg \"Updating distro...\"\n\t\t\t\t\t\tCheckInstallLockUbuntu\n                        apt-get update\n                        LogMsg \"Installing packages git make tar gcc bc patch dos2unix wget ...\"\n                        apt-get install -y git make tar gcc bc patch dos2unix wget >> $logFolder/build-customKernel.txt 2>&1\n                        LogMsg \"Installing kernel-package ...\"\n                        apt-get -o Dpkg::Options::=\"--force-confnew\" -y install kernel-package >> $logFolder/build-customKernel.txt 2>&1\n                        rm -rf linux-next\n                        LogMsg \"Downloading kernel source...\"\n                        git clone ${kernelSource} >> $logFolder/build-customKernel.txt 2>&1\n                        cd ${sourceDir}\n                        #Download kernel build shell script...\n                        wget https://raw.githubusercontent.com/simonxiaoss/linux_performance_test/master/git_bisect/build-ubuntu.sh\n                        chmod +x build-ubuntu.sh\n                        #Start installing kernel\n                        LogMsg \"Building and Installing kernel...\"\n                        ./build-ubuntu.sh  >> $logFolder/build-customKernel.txt 2>&1\n                        kernelInstallStatus=$?\n                        if [ $kernelInstallStatus -eq 0 ]; then\n                                LogMsg \"CUSTOM_KERNEL_SUCCESS\"\n                                UpdateTestState $ICA_TESTFAILED\n                        else\n                                LogMsg \"CUSTOM_KERNEL_FAIL\"\n                                UpdateTestState $ICA_TESTFAILED\n                        fi\n                fi\n        fi\n        UpdateTestState $ICA_TESTCOMPLETED\n        return $kernelInstallStatus\n}\nInstallKernel\nexit 0\n", "num_lines": 252}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n# \n# Description: It install the LIS using given LIS source file (.tar.gz or lis-next)\n# Usage: ./customLISInstall.sh -customLIS lisnext or tar file link -LISbranch a specific branch or default is master\n# Author: Sivakanth Rebba\n# Email\t: v-sirebb@microsoft.com \n#\n#######################################################################\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/build-customLIS.txt\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\nif [ -z \"$customLIS\" ]; then\n\techo \"Please mention -customLIS next\"\n\texit 1\nfi\nif [ -z \"$LISbranch\" ]; then\n\techo \"Not mentioned LIS branch, Use Master branch\"\n\tLISbranch=\"master\"\nfi\ntouch ~/build-customLIS.txt\n\n#Detect Distro and it's version\nDistroName=\"Unknown\"\nDistroVersion=\"Unknown\"\nif [ -f /etc/redhat-release ] ; then\n\tDistroName='REDHAT'\n\tDistroVersion=`cat /etc/redhat-release | sed s/.*release\\ // | sed s/\\ .*//`\nelif [ -f /etc/centos-release ] ; then\n\tDistroName==`cat /etc/centos-release | sed s/^\\ // |sed s/\\ .*//`\n\tDistroName='CENTOS'\n\tDistroVersion=`cat /etc/centos-release | sed s/.*release\\ // | sed s/\\ .*//`\nelif [ -f /etc/SuSE-release ] ; then\n\tDistroName=`cat /etc/SuSE-release | tr \"\\n\" ' '| sed s/VERSION.*//`\n\tDistroVersion=`cat /etc/SuSE-release | tr \"\\n\" ' ' | sed s/.*=\\ //`\nelif [ -f /etc/debian_version ] ; then\n\tDistroName=\"Debian `cat /etc/debian_version`\"\n\tDistroVersion=\"\"\nfi\nif [ -f /etc/UnitedLinux-release ] ; then\n\tDistroName=\"${DistroName}[`cat /etc/UnitedLinux-release | tr \"\\n\" ' ' | sed s/VERSION.*//`]\"\nfi\nLogMsg \"*****OS Info*****\"\ncat /etc/*-release >> ~/build-customLIS.txt 2>&1\nLogMsg \"*****Kernen Info*****\"\nuname -r >> ~/build-customLIS.txt 2>&1\nLogMsg \"*****LIS Info*****\"\nmodinfo hv_vmbus >> ~/build-customLIS.txt 2>&1\nkernel=`uname -r`\nif [ \"${customLIS}\" == \"lisnext\" ]; then\n\tLISSource=\"https://github.com/LIS/lis-next.git\"\n\tsourceDir=\"lis-next\"\nelif [ \"${customLIS}\" == \"netnext\" ]; then\n\tLISSource=\"https://git.kernel.org/pub/scm/linux/kernel/git/davem/net-next.git\"\n\tsourceDir=\"net-next\"\nelif [[ $customLIS == *.rpm ]]; then\n\tLogMsg \"Custom LIS:$customLIS\"\n\tsed -i '/^exclude/c\\#exclude' /etc/yum.conf\n\tyum install -y wget tar\n\tLogMsg \"Debian package web link detected. Downloading $customLIS\"\n\twget $customLIS\n\tLogMsg \"Installing ${customLIS##*/}\"\n\trpm -ivh \"${customLIS##*/}\"  >> ~/build-customLIS.txt 2>&1\n\tLISInstallStatus=$?\n\tUpdateTestState $ICA_TESTCOMPLETED\n\tif [ $LISInstallStatus -ne 0 ]; then\n\t\tLogMsg \"CUSTOM_LIS_FAIL\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\telse\n\t\tLogMsg \"CUSTOM_LIS_SUCCESS\"\n\t\tUpdateTestState $ICA_TESTCOMPLETED\n\tfi\n\texit 0\nelif [[ $customLIS == *.tar.gz ]]; then\n\tLogMsg \"Custom LIS:$customLIS\"\n\tsed -i '/^exclude/c\\#exclude' /etc/yum.conf\n\tyum install -y git make tar gcc bc patch dos2unix wget xz >> ~/build-customLIS.txt 2>&1\n\tLogMsg \"LIS tar file web link detected. Downloading $customLIS\"\n\twget $customLIS\n\tLogMsg \"Extracting ${customLIS##*/}\"\n\ttar -xvzf \"${customLIS##*/}\"\n\tLogMsg \"Installing ${customLIS##*/}\"\n\tcd LISISO\n\t./install.sh  >> ~/build-customLIS.txt 2>&1\n\tLISInstallStatus=$?\n\tUpdateTestState $ICA_TESTCOMPLETED\n\tmodinfo hv_vmbus >> ~/build-customLIS.txt 2>&1\n\tif [ $LISInstallStatus -ne 0 ]; then\n\t\tLogMsg \"CUSTOM_LIS_FAIL\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\telse\n\t\tLogMsg \"CUSTOM_LIS_SUCCESS\"\n\t\tUpdateTestState $ICA_TESTCOMPLETED\n\tfi\n\texit 0\nfi\nLogMsg \"Custom LIS:$customLIS\"\n\nif [ $DistroName == \"SLES\" -o $DistroName == \"SUSE\" ]; then\n\tzypper --non-interactive install git-core make tar gcc bc patch dos2unix wget xz \n\tLogMsg \"LIS doesn't support for $DistroName distro...\"\nelif [ $DistroName == \"CENTOS\" -o $DistroName == \"REDHAT\" -o $DistroName == \"FEDORA\" -o $DistroName == \"ORACLELINUX\" ]; then\n\tLogMsg \"Installing packages git make tar gcc bc patch dos2unix wget ...\"\n\tsed -i '/^exclude/c\\#exclude' /etc/yum.conf\n\tyum install -y git make tar gcc bc patch dos2unix wget xz >> ~/build-customLIS.txt 2>&1\n\tLogMsg \"Downloading LIS source from ${LISSource}...\"\n\tgit clone ${LISSource} >> ~/build-customLIS.txt 2>&1\n\tcd ${sourceDir}\n\tgit checkout ${LISbranch}\n\tLogMsg \"Downloaded LIS from this ${LISbranch} branch...\"\n\tif [[ $DistroVersion == *\"5.\"* ]]; then\n\t\tLISsourceDir=hv-rhel5.x/hv\n\telif [[ $DistroVersion == *\"6.\"* ]]; then\n\t\tLISsourceDir=hv-rhel6.x/hv\n\telif [[ $DistroVersion == *\"7.\"* ]]; then\n\t\tLISsourceDir=hv-rhel7.x/hv\n\tfi\n\tcd $LISsourceDir\n\tLISDir=`pwd`\n\tLogMsg \"Installing kernel-devel-${kernel} for LIS...\"\n\tyum install -y \"https://konkasoftpackages.blob.core.windows.net/linuxbinaries/kernel-devel-${kernel}.rpm\" ~/build-customLIS.txt 2>&1\n\tLogMsg \"LIS is installing from this ${LISDir} branch...\"\n\t./*-hv-driver-install >> ~/build-customLIS.txt 2>&1\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"CUSTOM_LIS_FAIL\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 0\n\tfi\nelif [ $DistroName == \"UBUNTU\" ]; then\n\tLogMsg \"LIS doesn't support for $DistroName distro...\"\nfi\nUpdateTestState $ICA_TESTCOMPLETED\nsleep 10\nLogMsg \"CUSTOM_LIS_SUCCESS\"\nsleep 10\nexit 0\n", "num_lines": 167}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nduser=$duser\n\n\nDeleteUser()\n{\n\tif [ -e /etc/debian_version ]; then\n\t\tdeluser $duser\n\t\tisUserDeleted=$?\n\telif [ -e /etc/redhat-release ]; then\n\t\tuserdel $duser\n\t\tisUserDeleted=$?\n\telif [ -e /etc/SuSE-release ]; then\n\t\tuserdel $duser\n\t\tisUserDeleted=$?\n\tfi\n\tif [ $isUserDeleted = \"0\" ]; then\n\t    echo \"AUTOMATION_USER_DELETED\"\n\telse\n\t    echo \"AUTOMATION_USER_DELETE_FAILED\"\n\tfi\n\n}\nDeleteUser\nexit 0\n", "num_lines": 36}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#AUTHOR : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#Description : Enables passwordless authentication for root user.\n#How to use : ./enablePasswordLessRoot.sh\n#In multi VM cluster. Execute this script in one VM. It will create a sshFix.tar\n#Copy this sshFix.tar to other VMs (/root) in your cluster and execute same script. It will extract previously created keys.\n#This way, all VMs will have same public and private keys in .ssh folder.\n\nrm -rf /root/.ssh\ncd /root\nkeyTarFile=sshFix.tar\nif [ -e ${keyTarFile} ]; then\n\techo | ssh-keygen -N ''\n\trm -rf .ssh/*\n\ttar -xvf ${keyTarFile}\n\techo \"KEY_COPIED_SUCCESSFULLY\"\nelse\n\techo | ssh-keygen -N ''\n\tcat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys\n\techo \"Host *\" > /root/.ssh/config\n\techo \"StrictHostKeyChecking no\" >> /root/.ssh/config\n\trm -rf /root/.ssh/known_hosts\n\tcd /root/ && tar -cvf sshFix.tar .ssh/*\n\techo \"KEY_GENERATED_SUCCESSFULLY\"\nfi\n", "num_lines": 26}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#AUTHOR : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#Description : Enables root user and sets password. Needs to run with sudo permissions.\n#How to use : ./enableRoot.sh -password <new_root_password>\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\npassword=$password\nsshd_configFilePath=\"/etc/ssh/sshd_config\"\nsshdServiceName=\"sshd\"\nusermod --password $(echo $password | openssl passwd -1 -stdin) root\nif [ $? == 0 ]; then\n    sed -i 's/.*PermitRootLogin.*/PermitRootLogin yes/g' $sshd_configFilePath\n    if [ $? == 0 ]; then\n        echo \"$sshd_configFilePath verifed for root login.\"\n        echo \"ROOT_PASSWRD_SET\"\n        service $sshdServiceName restart || systemctl restart sshd.service\n        sshdServiceStatus=$?\n        if [ $sshdServiceStatus != 0 ]; then\n                service ssh restart\n                sshdServiceStatus=$?\n        fi\n    else\n        echo \"$sshd_configFilePath verification failed for root login.\"\n        echo \"ROOT_PASSWORD_SET_SSHD_CONFIG_FAIL\"\n    fi\nelse\n    echo \"Unable to set root password.\"\n    echo \"ROOT_PASSWORD_NOT_SET\"\nfi\nif [ $sshdServiceStatus == 0 ]; then\n    echo \"SSHD_RESTART_SUCCESSFUL\"\nelse\n    echo \"SSHD_RESTART_FAIL\"\nfi\nexit 0\n", "num_lines": 41}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script converts Network performance output files into csv files.\n# Author: Srikanth Myakam\n# Email\t: v-srm@microsoft.com\n#\nformat_bites(){\n\ttemp_size=$1\n\ttemp_units=\"Gbps\"\n\ttemp_size=`echo $temp_size 1000| awk '{printf \"%.3f \\n\", $1/$2}'`\n\ttemp_size=`echo $temp_size 1000| awk '{printf \"%.3f \\n\", $1/$2}'`\n\techo $temp_size,$temp_units\n}\n\ngen_csv(){\n\tinput_file=$1\n\tnumber_of_connections=$2\n\tsummary_file=$3\n\n\toutput_file=`echo $input_file |sed s/\\.log$/\\.csv/`\n\ttop_array_file=`echo $output_file |sed s/sar/top/`\n\tconn_array_file=`echo $output_file |sed s/sar/connections/`\n\tcpu_vmstat_file=`echo $input_file |sed s/sar/vmstat/`\n\n\trx_pcks_array_file=$input_file-rxpcks.log\n\ttx_pcks_array_file=$input_file-txpcks.log\n\trx_array_file=$input_file-rxkBps.log\n\ttx_array_file=$input_file-txkBps.log\n\tcpu_vmstat_array_file=$input_file-cpu-vmstat.log\n\n\tcat $cpu_vmstat_file | grep -v [a-z]| awk '{print 100 - $15}' > $cpu_vmstat_array_file\n\tcat $input_file | grep eth0 | awk '{print $4}' > $rx_pcks_array_file\n\tcat $input_file | grep eth0 | awk '{print $5}' > $tx_pcks_array_file\n\tcat $input_file | grep eth0 | awk '{print $6}' > $rx_array_file\n\tcat $input_file | grep eth0 | awk '{print $7}' > $tx_array_file\n\n\trx_pcks_array=(`cat $rx_pcks_array_file`)\n\ttx_pcks_array=(`cat $tx_pcks_array_file`)\n\trx_array=(`cat $rx_array_file`)\n\ttx_array=(`cat $tx_array_file`)\n\ttop_array=(`cat $top_array_file`)\n\tconn_array=(`cat $conn_array_file`)\n\tcpu_array=(`cat $cpu_vmstat_array_file`)\n\n\tlength=$((${#rx_array[@]}-1))\n\tcount=0\n\tsum=0\n\trx_pcks_sum=0\n\ttx_pcks_sum=0\n\trx_sum=0\n\ttx_sum=0\n\tcpu_sum=0\n\n\techo Rx Throughput,Units,TxThroughput,Units,Total,Units,,Time,ActiveConnection,Rx packets,Tx packets,,Time,CPU Usage >> $output_file\n\n\tfor i in `seq 1 $length`;\n\tdo\n\t\tTx_bits=`echo 8 ${tx_array[count]}| awk '{printf \"%.3f \\n\", $1*$2}'`\n\t\tRx_bits=`echo 8 ${rx_array[count]}| awk '{printf \"%.3f \\n\", $1*$2}'`\n\n\t\tTx_data=`format_bites $Tx_bits`\n\t\tRx_data=`format_bites $Rx_bits`\n\t\tTotal_bits=`echo $Tx_bits $Rx_bits| awk '{printf \"%.3f \\n\", $1+$2}'`\n\n\t\tTotal_data=`format_bites $Total_bits`\n\t\tconn_info=${conn_array[count]}\n\t\tif [ \"x$conn_info\" == \"x\" ]\n\t\tthen\n\t\t\tconn_info=\",\"\n\t\tfi\n\n\t\techo $Rx_data,$Tx_data,$Total_data,,$conn_info,${rx_pcks_array[count]},${tx_pcks_array[count]},,$count,${cpu_array[count]}>> $output_file\n\t\trx_pcks_sum=`echo $rx_pcks_sum ${rx_pcks_array[count]}| awk '{printf \"%.3f \\n\", $1+$2}'`\n\t\ttx_pcks_sum=`echo $tx_pcks_sum ${tx_pcks_array[count]}| awk '{printf \"%.3f \\n\", $1+$2}'`\n\t\trx_sum=`echo $rx_sum ${rx_array[count]}| awk '{printf \"%.3f \\n\", $1+$2}'`\n\t\ttx_sum=`echo $tx_sum ${tx_array[count]}| awk '{printf \"%.3f \\n\", $1+$2}'`\n\t\tcpu_sum=`echo $cpu_sum ${cpu_array[count]}| awk '{printf \"%.3f \\n\", $1+$2}'`\n\n\t\t((count++))\n\tdone\n\tsum=`echo $tx_sum $rx_sum| awk '{printf \"%.3f \\n\", $1+$2}'`\n\tpcks_sum=`python -c \"print '%d' % ($tx_pcks_sum+$rx_pcks_sum)\"`\n\tavg_thrpt=`python -c \"print '%.2f' %  ($sum*8/($length*1000*1000))\"`\n\tavg_cpu=`python -c \"print '%d' % ($cpu_sum/$length)\"`\n\n\techo $number_of_connections,$avg_thrpt,$pcks_sum,$avg_cpu >> $summary_file\n\trm -rf $rx_array_file $tx_array_file $cpu_vmstat_array_file.log\n}\n\nlogs_folder=$1\ntesttype=$2\nbuffersize=$3\n#summary_file=$logs_folder/summary_file_`hostname`.csv\nsummary_file=$logs_folder/summary_file_`hostname`_${testtype}_${buffersize}.csv\necho \"\" > $summary_file\necho \"Connections,Avg Throughput,Total packets,Avg CPU\" > $summary_file\nfor number_of_connections in 1 2 4 8 16 32 64 128 256 512 1024\ndo\n\techo \"Converting $number_of_connections logs..\"\n\tgen_csv $logs_folder/$number_of_connections/$number_of_connections-sar.log $number_of_connections $summary_file&\ndone\nwait\n\nmkdir -p $logs_folder/csv_files/\nfor number_of_connections  in 1 2 4 8 16 32 64 128 256 512 1024\ndo\n\tmv $logs_folder/$number_of_connections/$number_of_connections-sar.csv $logs_folder/csv_files/\ndone\n\ncat $summary_file | sort -n > $summary_file.tmp\nmv $summary_file.tmp $summary_file\nlogs_folder=`echo $logs_folder| sed 's/\\/$//'`\ntar -czf $logs_folder.tar.gz $logs_folder/\necho \"Completed!\"\n", "num_lines": 115}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "shared_test_count=`ls xfstests/tests/shared/[0-9][0-9][0-9] |wc -l`\ngeneric_test_count=`ls xfstests/tests/generic/[0-9][0-9][0-9] |wc -l`\ntotal_test_count=$((generic_test_count + shared_test_count))\nran_test_count=`cat xfstests/results/check.log | grep Failed|awk '{print $4;}'`\nfailed_test_count=`cat xfstests/results/check.log | grep Failed|awk '{print $2;}'`\npassed_test_count=$((ran_test_count - failed_test_count))\nnot_run_test_count=$((total_test_count - ran_test_count))\n\necho \"Passed : \"$passed_test_count\necho \"Failed : \"$failed_test_count\necho \"Not run : \"$not_run_test_count\n", "num_lines": 12}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n########################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\t http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n########################################################################\n########################################################################\n#\n# Description:\n#\tThis script installs NVidia GPU drivers.\n#\n#\tSteps:\n#\t1. Installs dependencies\n#\t2. Compiles and installs GPU Drievers\n#\t3. -logFolder parameter is supported (Optional)\n#\t\n#\n########################################################################\n\nwhile echo $1 | grep ^- > /dev/null; do\n\teval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n\tshift\n\tshift\ndone\n\nCUDADriverVersion=\"9.1.85-1\"\nICA_TESTRUNNING=\"TestRunning\"\t  # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"\t  # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"\t\t# Error while performing the test\"\n\nif [ ! ${logFolder} ]; then\n\tlogFolder=\"/root\"\nfi\n\n#######################################################################\n# Adds a timestamp to the log file\n#######################################################################\nLogMsg() {\n\techo $(date \"+%a %b %d %T %Y\") : ${1}\n\techo $(date \"+%a %b %d %T %Y\") : ${1} >> $logFolder/GPU_Test_Logs.txt \n}\n\n#######################################################################\n# Updates the summary.log file\n#######################################################################\nUpdateSummary() {\n\techo $1 >> $logFolder/summary.log\n}\n\n#######################################################################\n# Keeps track of the state of the test\n#######################################################################\nUpdateTestState() {\n\techo $1 > $logFolder/state.txt\n}\n\n#######################################################################\n# Install dependencies and GPU Driver\n#######################################################################\nInstallGPUDrivers() {\n\t\tDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n\t\tif [[ $DISTRO =~ \"Ubuntu 16.04\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected UBUNUT1604\"\n\t\t\t\tCUDA_REPO_PKG=\"cuda-repo-ubuntu1604_${CUDADriverVersion}_amd64.deb\"\n\t\t\t\tLogMsg \"Using ${CUDA_REPO_PKG}\"\n\t\t\t\twget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/${CUDA_REPO_PKG} -O /tmp/${CUDA_REPO_PKG}\n\t\t\t\tdpkg -i /tmp/${CUDA_REPO_PKG}\n\t\t\t\trm -f /tmp/${CUDA_REPO_PKG}\n\t\t\t\tuntil dpkg --force-all --configure -a; sleep 10; do echo 'Trying again...'; done\n\t\t\t\tapt-get -y update\n\t\t\t\tapt-get -y --allow-unauthenticated install linux-tools-generic linux-cloud-tools-generic\n\t\t\t\tapt-get -y --allow-unauthenticated install cuda-drivers\n\t\t\t\t\t\t\t\t\n\t\telif [[ $DISTRO =~ \"Ubuntu 14.04\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected UBUNTU1404\"\n\t\t\t\tCUDA_REPO_PKG=\"cuda-repo-ubuntu1404_${CUDADriverVersion}_amd64.deb\"\n\t\t\t\tLogMsg \"Using ${CUDA_REPO_PKG}\"\t\t\t\t\n\t\t\t\twget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1404/x86_64/${CUDA_REPO_PKG} -O /tmp/${CUDA_REPO_PKG}\n\t\t\t\tdpkg -i /tmp/${CUDA_REPO_PKG}\n\t\t\t\trm -f /tmp/${CUDA_REPO_PKG}\n\t\t\t\tapt-get -y update\n\t\t\t\tapt-get -y --allow-unauthenticated install linux-tools-generic linux-cloud-tools-generic\n\t\t\t\tapt-get -y --allow-unauthenticated install cuda-drivers\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"CentOS Linux release 7.3\" ]] || [[ $DISTRO =~ \"CentOS Linux release 7.4\" ]] || [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 7.4\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected CentOS 7.x / RHEL 7.x\"\n\t\t\t\tsed -i \"/^exclude=kernel/c\\#exclude=kernel*\" /etc/yum.conf\n\t\t\t\tyum -y update\n\t\t\t\tyum -y --nogpgcheck install kernel-devel\n\t\t\t\trpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\t\t\t\t\n\t\t\t\tyum --nogpgcheck -y install dkms\n\t\t\t\tCUDA_REPO_PKG=\"cuda-repo-rhel7-${CUDADriverVersion}.x86_64.rpm\"\n\t\t\t\tLogMsg \"Using ${CUDA_REPO_PKG}\"\t\t\t\t\t\n\t\t\t\twget http://developer.download.nvidia.com/compute/cuda/repos/rhel7/x86_64/${CUDA_REPO_PKG} -O /tmp/${CUDA_REPO_PKG}\n\t\t\t\trpm -ivh /tmp/${CUDA_REPO_PKG}\n\t\t\t\trm -f /tmp/${CUDA_REPO_PKG} \n\t\t\t\tyum --nogpgcheck -y install lshw\n\t\t\t\tyum --nogpgcheck -y install cuda-drivers\n\t\telse\n\t\t\t\tLogMsg \"Unknown Distro\"\n\t\t\t\tUpdateTestState \"TestAborted\"\n\t\t\t\tUpdateSummary \"Unknown Distro, test aborted\"\n\t\t\t\treturn 1\n\t\tfi\n}\n\n######################################################################\n#MAIN\n######################################################################\n\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\nInstallGPUDrivers\nif [[ $? == 0 ]];\nthen\n\tLogMsg \"GPU_DRIVER_INSTALLATION_SUCCESSFUL\"\nelse\n\tLogMsg \"GPU_DRIVER_INSTALLATION_FAIL\"\nfi\nUpdateTestState $ICA_TESTCOMPLETED\nexit 0\n", "num_lines": 143}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#########################################################\n# ICA_VMSetup.sh\n#\n#Description : This script installs packages required for ICA and\n# \t\t\t   Configures test VHD for ICA test run\n# Author : Amit Pawar [ v-ampaw@microsoft.com ]\n\n##############################################################################\n\n#DEBUG_LEVEL=3\n\necho \"***Logs of ICA_VMSetup.sh***\"  \nwithErrors=0\ndbgprint()\n{\n    #if [ $1 -le $DEBUG_LEVEL ]; then\n        #echo \"$1\"\n        \n\t\techo  \"$1\"  \n\t\t\n    #fi\n}\n\n\n\n\ndbgprint \"Preparing the VHD for ICA...\"\n\n\n\n#installing gcc. dos2unix, make and python\n  if [ -e /etc/debian_version ]; then\n\n        dbgprint \"Installing gcc..\"\n\t\t\n\t\techo yes|apt-get install gcc \n\t\tif [ \"$?\" = \"0\" ]; then \n\t\t\tdbgprint \"Install gcc  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install gcc  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\n        dbgprint \"Installing make..\"\n\t\t\n\t\techo yes|apt-get install make\n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install make  : SUCCESS\"\n\t\telse\n\t\t\tdbgprint \"Install  make : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python..\"\n\t\t\n\t\techo yes|apt-get install python \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python-pyasn1..\" \n\t\t\n\t\techo yes|apt-get install python-pyasn1 \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python-pyasn1  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python-pyasn1  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Installing iperf..\"\n\t\t\n\t\techo yes|apt-get install iperf \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install iperf  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install iperf  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Installing bind9 dnsutils..\"\n\t\t\n\t\techo yes|apt-get install bind9 dnsutils \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install bind9 dnsutils  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install bind9 dnsutils  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n         dbgprint \"Removing NetworkManager..\"\n\t\t \n\t\t echo yes | aptitude purge network-manager \n\t\t \n\t\t if [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Remove Network Manager  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Remove Network Manager  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Updating the packages..\"\n\t\t\n\t\techo yes|apt-get update \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Update Packages  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Update Packages  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Upgrading the kernel..\"\n\t\t\n\t\techo yes|apt-get upgrade \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Upgrade Kernel  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Upgrade Kernel  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n  fi\n\n  if [ -e /etc/redhat-release ]; then\n\n        dbgprint \"Installing gcc..\" \n\t\t\n\t\techo yes|yum install gcc \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install gcc  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install gcc  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\n        dbgprint \"Installing make..\"\n\t\t\n\t\techo yes|yum install make \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install make  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install  make  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python..\"\n\t\t\n\t\techo yes|yum install python \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python-pyasn1..\"\n\t\t\n\t\techo yes|yum install python-pyasn1  \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python-pyasn1  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python-pyasn1  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Installing iperf..\"\n\t\t\n\t\techo yes|yum install iperf  \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install iperf  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install iperf  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Removing NetworkManager..\"\n\t\t\n\t\techo yes|yum remove NetworkManager \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Remove Network Manager  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Remove Network Manager  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Updating the packages..\"\n\t\t\n\t\techo yes|yum update \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Update Packages  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Update Packages  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Upgrading the kernel..\"\n\t\t\n\t\techo yes|yum upgrade \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Upgrade kernel  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Upgrade kernel  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\n  fi\n\n  if [ -e /etc/SuSE-release ]; then\n\n        dbgprint \"Installing gcc..\"\n\t\t\n\t\tzypper --non-interactive install gcc \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install gcc  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install gcc  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\n        dbgprint \"Installing make..\"\n\t\t\n\t\tzypper --non-interactive install make \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install make  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install  make  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python..\"\n\t\t\n\t\tzypper --non-interactive install python \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Installing python-pyasn1..\"\n\t\t\n\t\tzypper --non-interactive install python-pyasn1  \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install python-pyasn1  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install python-pyasn1  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\t\tdbgprint \"Installing iperf..\"\n\t\t\n\t\tzypper --non-interactive install iperf  \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install iperf  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install iperf  : FAILED\"\n\t\t\twithErrors=1\n\t\t\t\n\t\tfi\n\t\t\n\t\tdbgprint \"Installing bind-utils..\"\n\t\t\n\t\tzypper --non-interactive install bind-utils  \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Install bind-utils  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Install bind-utils  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\t\t\n\n        dbgprint \"Removing NetworkManager..\"\n\t\t\n\t\tzypper --non-interactive remove NetworkManager \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Remove Network Manager  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Remove Network Manager  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n        dbgprint \"Updating the packages..\"\n\t\t\n\t\tzypper --non-interactive update \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Update Packages  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Update Packages  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\t\tdbgprint \"Upgrading the kernel..\"\n\t\t\n\t\tzypper --non-interactive up \n\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\tdbgprint \"Upgrade kernel  : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"Upgrade kernel  : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\n\n  fi\n\n\n#installing icadaemon, git and lcov\n     \n\ttar -xmf icatest-0.1.tar.gz\n\tchmod 755 ./icatest-0.1/setup.py\n\tdbgprint \"Installing Icadaemon..\"\n   \tcd ./icatest-0.1\n\tpython setup.py install  \n\tif [ \"$?\" = \"0\" ]; then \n\t\tdbgprint \"Icadaemon installed : SUCCESS\"\n\telse \n\t\tdbgprint \"Icadaemon installed : FAILED\"\n\t\twithErrors=1\n\tfi\n\tcd ~\n  \n  \n\n\tif [ -e /etc/debian_version ]; then\n\t\n\t\tdbgprint \"Installing git..\"\n\t\techo yes|apt-get install git \n\t\tif [ \"$?\" = \"0\" ]; then \n\t\t\tdbgprint \"git installed : SUCCESS\"\n\t\telse \n\t\t\tdbgprint \"git installed : FAILED\"\n\t\t\twithErrors=1\n\t\tfi\n\telse\n\t\n\t    dbgprint \"Installing git..\"\n\t\ttar -xmf git-1.7.10.tar.gz\n\t\tcd git-1.7.10 \n\t\t./configure   \n\t\tmake   \n\t\tif [ \"$?\" -ne \"0\" ]; then\n\t\t\tdbgprint \"git installed : FAILED\"\n\t\t\twithErrors=1\n\t\telse\n\t\t\tmake install  \n\t\t\tif [ \"$?\" = \"0\" ]; then\n\t\t\t\tdbgprint \"git installed : SUCCESS\"\n\t\t\telse \n\t\t\t\tdbgprint \"git installed : FAILED\"\n\t\t\t\twithErrors=1\n\t\t\tfi\n    \t\t\t\n\t\tfi\n\t\tcd ~\n\tfi\n\n    \n  \n\n  \n    dbgprint \"Installing Lcov..\"\n    tar -xmzf lcov-1.9.tar.gz\n\tcd lcov-1.9\n\tmake install  \n\tif [ \"$?\" = \"0\" ]; then\n\t\tdbgprint \"Lcov installed : SUCCESS\"\n\telse \n\t\tdbgprint \"Lcov installed : FAILED\"\n\t\twithErrors=1\n\tfi;\n    cd ~\n  \n\n\n  #Enabling essential services\n  if [ -e /etc/redhat-release ]; then\n   chkconfig rpcbind on  && chkconfig sshd on  && chkconfig nfs on \n   fi\n\n  if [ -e /etc/SuSE-release ]; then \n   /sbin/SuSEfirewall2 off \n   fi\n   \n\tif [ $withErrors -ne 0 ]; then\n\t\tdbgprint \"Failed to install some packages!!!\"\n\t\tdbgprint \"Exiting with Errors\"\n\t\texit 10\n\tfi\n", "num_lines": 396}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Install-LIS.sh\n# Description:\n#\t 1. Install LIS from the tarball.\n#\t 2. Verify if LIS is installed.\n#    3. Verify the modules are present in /lib/modules.\n#        \nDEBUG_LEVEL=3\n\n\ndbgprint()\n{\n    if [ $1 -le $DEBUG_LEVEL ]; then\n        echo \"$2\"\n    fi\n}\n\nif [ -e $HOME/constants.sh ]; then\n . $HOME/constants.sh\nelse\n echo \"ERROR: Unable to source the config file.\"\n exit 1\nfi\n\n\nif [ ! ${LIS_TARBALL} ]; then\n  dbgprint 0 \"The TARBALL variable is not defined.\"\n  dbgprint 0 \"Aborting the LIS Installation.\"\n    UpdateTestState \"TestAborted\"\n    exit 20\nfi\n\n\n\n\ndbgprint 3 \"Extracting LIS sources from ${LIS_TARBALL}\"\n\ntar -xmf ${LIS_TARBALL}\nsts=$?\nif [ 0 -ne ${sts} ]; then\n    dbgprint 0 \"tar failed to extract the LIS from the tarball: ${sts}\" \n    exit 40\nfi\n\nROOTDIR=\"hv\"\n#ROOTDIR=(`tar tf hv-rhel6.3-july9-2012.tar | sed -e 's@/.*@@' | uniq`)\nif [ ! -e ${ROOTDIR} ]; then\n    dbgprint 0 \"The tar file did not create the directory: ${ROOTDIR}\"\n    exit 50\nfi\n\ncd ${ROOTDIR} \n\ninstall_ic_rhel6()\n{\n\tdbgprint 0  \"**************************************************************** \"\n        dbgprint 0  \"This is RHEL6 and above LIS installation \"\n        dbgprint 0  \"*****************************************************************\"\n\n\t./rhel6-hv-driver-install >>./Install-LIS.log\n\tsts=$?\n\tif [ 0 -ne ${sts} ]; then\n\t\tdbgprint 0 \"Execution of install script failed: ${sts}\" \n\t    exit 0\n\telse\n\t\tdbgprint 0 \"LIS installation on RHEL 6.x : Success\"\n\tfi\n\n\tcd tools\n\t\n\tgcc -o kvp_daemon hv_kvp_daemon.c\n\tsts=$?\n\tif [ 0 -ne ${sts} ]; then\n\t\tdbgprint 0 \"Execution of install script failed: #${sts}\" \n\t\tdbgprint 0 \"KVP daemon compiled : Failed\"\n\t    exit 0\n\telse\n\t\tdbgprint 0 \"KVP daemon compiled : success\"\n\tfi\n\t\n\t#update rc.local\n\t\n\techo \"./root/${ROOTDIR}/tools/kvp_daemon\" >> /etc/rc.local\n}\n\necho \"**LIS Driver Installation**\"\nif [ -e /etc/redhat-release ]  ; then\n\tinstall_ic_rhel6\t\n\t\nelse\n    echo \"Not a supported distro for LIS Installation\"\n\texit\n\t\nfi\n", "num_lines": 95}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# Installing waagent\necho \"***WA Agent Installation***\"\nif [ -e /root/agent.py ]; then\n\n        dos2unix -q /root/agent.py\n        echo \"Setting Execute bit on agent.py\"\n        chmod +x /root/agent.py\n        mv /root/agent.py /usr/sbin/waagent\n        /usr/sbin/waagent -setup\n        sts=$?\n        if [ 0 -eq ${sts} ]; then\n                echo \"waagent installed : SUCESS\"\n\n        else\n                echo \"waagent installation : FAILED \"\n                exit 1\n\n        fi\n\nelse\n\n        echo \"waagent installation script not found..!!\"\n        echo \"waagent installation : FAILED \"\n\nfi\n\n\n#Verify Installation of waaagent\n\nif [ -e /etc/init.d/waagent ]; then\n\t\n\techo \"Verify Install waagent : SUCESS\"\nelse\n\techo \"Verify Install waagent : FAILED\"\n\texit\n\nfi\n\n\n", "num_lines": 41}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"STARTING_KERNBENCH\"\nnohup ./StartKernbench.sh &\nif [ $? = '0' ]; then\n        echo \"KERNBENCH_STARTED\"\nelse\n        echo \"KERNBENCH_FAILED_TO_START\"\nfi\n", "num_lines": 10}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script does the following:\n# 1. Prepares the RAID with all the data disks attached \n# 2. Places an entry for the created RAID in /etc/fstab.\n# 3. Keep the sysbench test script in the startup for IO performance test.\n#\n# Author: Srikanth M\n# Email\t: v-srm@microsoft.com\n#\n#####\nif [[ $# == 2 ]]\nthen\n\tusername=$1\n\ttest_type=$2\nelse\n\techo \"Usage: bash $0 <vm_loginuser> <LVM / RAID>\"\n\texit -1\nfi\n\nmountdir=\"/dataIOtest\"\ncode_path=\"/home/$username/code\"\ncode_path=\"/home/$username/code/\"\n. $code_path/azuremodules.sh\n\nLOGFILE=\"${code_path}/iotest.log.txt\"\n[ -d $mountdir ] && umount $mountdir && rm -rf $mountdir\nmkdir $mountdir  \necho \"IO test setup started..\" > $LOGFILE\nlist=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\nlsblk  >> $LOGFILE\n\nif [ \"$test_type\" == \"LVM\" ]; then\n\t\n\tinstall_package lvm2\n\n\tdeviceName=\"/dev/vg1/lv1\"\n\techo \"--- LVM $deviceName creation started ---\" >> $LOGFILE\n\n\tyes | pvcreate ${list[@]} >> $LOGFILE\n\tif [ $? -ne 0 ]; then\n\t\techo \"pvcreate: Failed\"  >> $LOGFILE\n\t\texit 80\n\tfi\n\techo \"pvcreate: Success\"  >> $LOGFILE\n\n\tvgcreate vg1 ${list[@]} >> $LOGFILE\n\tif [ $? -ne 0 ]; then\n\t\techo \"vgcreate\u00c2\u00a0: Failed\"  >> $LOGFILE\n\t\texit 80\n\tfi\n\techo \"vgcreate\u00c2\u00a0: Success\"  >> $LOGFILE\n\n\tlvcreate -l 100%FREE -i 32 -I 64 vg1 -n lv1\n\tif [ $? -ne 0 ]; then\n\t\techo \"lvcreate: Failed\"  >> $LOGFILE\n\t\texit 80\n\tfi\n\techo \"lvcreate\u00c2\u00a0: Success\"  >> $LOGFILE\n\n\ttime mkfs.ext4 $deviceName >> $LOGFILE\n\t\n\tmount -o barrier=0 $deviceName $mountdir\n\tif [ $? -ne 0 ]; then\n\t\techo \"$deviceName LVM mount: Failed\"  >> $LOGFILE\n\t\texit 80\t\n\tfi\n\techo \"$deviceName LVM mount: Success on $mountdir\"  >> $LOGFILE\n\tuuid=`blkid $deviceName| sed \"s/.*UUID=\\\"//\"| sed \"s/\\\".*\\\"//\"`\n\techo $uuid\n\techo \"UUID=$uuid $mountdir ext4 defaults,barrier=0 0 2\" >> /etc/fstab\n\nelif [ \"$test_type\" == \"RAID\" ]; then\n\tinstall_package mdadm\n\tcount=0\n\twhile [ \"x${list[count]}\" != \"x\" ]\n\tdo\n\t   echo ${list[$count]}  >> $LOGFILE \n\t   (echo n; echo p; echo 2; echo; echo; echo t; echo fd; echo w;) | fdisk ${list[$count]}  >> $LOGFILE\n\t   count=$(( $count + 1 ))   \n\tdone\n\t\n\tdeviceName=\"/dev/md1\"\n\techo \"--- Raid $deviceName creation started ---\" >> $LOGFILE\n\t(echo y)| mdadm --create $deviceName --level 0 --raid-devices ${#list[@]} ${list[@]} >> $LOGFILE\n\tif [ $? -ne 0 ]; then\n\t\techo \"$deviceName Raid creation: Failed\"  >> $LOGFILE\n\t\texit 80\n\tfi\n\techo \"$deviceName Raid creation: Success\"  >> $LOGFILE\n\n\ttime mkfs.ext4 $deviceName >> $LOGFILE\n\tif [ $? -ne 0 ]; then\n\t\techo \"$deviceName Raid format: Failed\"   >> $LOGFILE\n\t\texit 80\n\tfi\n\techo \"$deviceName Raid format: Success\"  >> $LOGFILE\n\t\n\tmount -o nobarrier $deviceName $mountdir\n\tif [ $? -ne 0 ]; then\n\t\techo \"$deviceName Raid mount: Failed\"  >> $LOGFILE\n\t\texit 80\t\n\tfi\n\techo \"$deviceName Raid mount: Success on $mountdir\"  >> $LOGFILE\n\tuuid=`blkid $deviceName| sed \"s/.*UUID=\\\"//\"| sed \"s/\\\".*\\\"//\"`\n\techo $uuid\n\techo \"UUID=$uuid $mountdir ext4 defaults,barrier=0 0 2\" >> /etc/fstab\nelse\n\techo \"Unknown DiskType $test_type: Aborted\"  >> $LOGFILE\nfi\n\ndf -hT >> $LOGFILE\ncp $code_path/sysbench-full-io-test.sh $mountdir\nbash $code_path/keep_cmds_in_startup.sh \"cd $mountdir ; bash $mountdir/sysbench-full-io-test.sh $username &\" \n", "num_lines": 116}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script places the server and client commands in the startup for the network performance test.\n# Author: Srikanth M\n# Email\t: v-srm@microsoft.com\n#\n#####\n\ntestcommand=$*\n\nif [[ -f /etc/rc.d/rc.local ]]\nthen\n\tif ! grep -q \"${testcommand}\" /etc/rc.d/rc.local\n\tthen\n\t\tsed \"/^\\s*exit 0/i ${testcommand}\" /etc/rc.d/rc.local -i\n\t\tif ! grep -q \"${testcommand}\" /etc/rc.d/rc.local\n\t\tthen\n\t\t\tcp /etc/rc.d/rc.local /etc/rc.d/rc.local.bkp\n\t\t\techo $testcommand >> /etc/rc.d/rc.local\n\t\t\tchmod +x /etc/rc.d/rc.local\n\t\tfi\n\tfi\nfi\n\nif [[ -f /etc/rc.local ]]\nthen\n\tif ! grep -q \"${testcommand}\" /etc/rc.local\n\tthen\n\t\tsed \"/^\\s*exit 0/i ${testcommand}\" /etc/rc.local -i\n\t\tif ! grep -q \"${testcommand}\" /etc/rc.local\n\t\tthen\n\t\t\tcp /etc/rc.local /etc/rc.local.bkp\n\t\t\techo $testcommand >> /etc/rc.local\n\t\t\tchmod +x /etc/rc.local\n\t\tfi\n\tfi\nfi\n\nif [[ -f /etc/SuSE-release ]]\nthen\n\tif ! grep -q \"${testcommand}\" after.local\n\tthen\n\t\tcp /etc/rc.d/after.local /etc/rc.d/after.local.bkp\n\t\techo $testcommand >> /etc/rc.d/after.local\n\t\tchmod +x /etc/rc.d/after.local\n\tfi\nfi \n# ===\n# if [[ -f /etc/rc.d/rc.local ]]\n# then\n# startup_file=\"/etc/rc.d/rc.local\"\n# elif  [[ -f /etc/rc.local ]]\n# then\n# startup_file=\"/etc/rc.local\"\n# elif  [[ -f /etc/SuSE-release ]]\n# then\n# startup_file=\"/etc/rc.d/after.local\"\n# fi\n\n# if ! grep -q \"${testcommand}\" $startup_file\n# then\n\t# sed \"/^\\s*exit 0/i ${testcommand}\" $startup_file -i\n\t# if ! grep -q \"${testcommand}\" $startup_file\n\t# then\n\t\t# echo $testcommand >> $startup_file\n\t# fi\n# fi\n\n", "num_lines": 69}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#Author: Vijay Tripathi <vijayt@microsoft.com>\nLog() {\n        msg=\"echo $1\"\n        cmd=$2\n        file=$3\n        format=\"echo \"---------------------------------------------------\"\"\n\n        $format >> $file\n        $msg >> $file\n        echo \"Command Used:\" $2 >> $3\n        eval $cmd >> $file\n        $format >> $file\n\n        2>/dev/null\n}\n\nintro() {\n##Create the Directory in Which Logs would be stored\ncurrtime=$(date +\"%b%d%Y-%H-%M-%S\");\n#hostnm=$(hostname)\nhostnm=\"\"\n#dirname=\"LIS-Logs-\"${hostnm};\ndirname=\"LIS-Logs\"\nmkdir $dirname;\n}\n\nCollect_Waagent_Logs() {\necho \"Collecting Waagent Details....\"\nLog \"Collecting Waagent Details at\" 'date' $dirname/Waagent.txt\nLog \"Waagent Process Running Status\" 'ps -ef | grep waagent' $dirname/Waagent.txt\nif [ -f /usr/share/oem/bin/waagent ]\nthen\nLog \"Waagent Version is\" '/usr/share/oem/python/bin/python /usr/share/oem/bin/waagent --version' $dirname/Waagent.txt\nelse\nLog \"Waagent Version is\" '/usr/sbin/waagent --version' $dirname/Waagent.txt\nfi\nLog \"Root Device Timeout\" 'cat /sys/block/sda/device/timeout' $dirname/Waagent.txt\nif [[ $dist == *Debian* ]] || [[  $dist == *Ubuntu* ]]\nthen\nLog \"Waagent Package Details\" 'dpkg -p walinuxagent' $dirname/Waagent.txt\nelse\nLog \"Waagent Package Details\" 'rpm -qil WALinuxAgent' $dirname/Waagent.txt\nfi\nLog \"Waagent.log file\" 'cat /var/log/waagent.log' $dirname/Waagent.log\n}\n\nCollect_OS_Logs() {\necho \"Collection Operating System Logs.....\"\nLog \"Collection Operating System Details at\" 'date' $dirname/OS.log \nLog \"Kernel Version\" 'uname -a' $dirname/OS.log \nLog \"Distro Release Details\" 'cat /etc/issue' $dirname/OS.log \nLog \"Additional Kernel Details\" 'cat /proc/version' $dirname/OS.log \nLog \"Mount Points\" 'mount' $dirname/OS.log \nLog \"System Limits\" 'ulimit -a' $dirname/OS.log \n#Log \"NFS Shares on System\" 'showmount -e' $dirname/OS.log \nLog \"Hosts File Details\" 'cat /etc/hosts' $dirname/OS.log \nLog \"Locale Details\" 'locale' $dirname/OS.log \nLog \"Running Process Details\" 'ps -auwwx' $dirname/OS.log \nif [ -e /boot/grub/grub.conf ]; then\n   Log \"Grub File Details\" 'cat /boot/grub/grub.conf' $dirname/grub.log \nelif [ -e /boot/grub/menu.lst ]; then\n   Log \"Grub File Details\" 'cat /boot/grub/menu.lst' $dirname/grub.log \nelif [ -e /etc/grub.conf ]; then\n   Log \"Grub File Details\" 'cat /etc/grub.conf' $dirname/grub.log \nfi\nLog \"Enviornment Variables Settings\"  'env' $dirname/OS.log \nLog \"Dmesg File Details\" 'dmesg' $dirname/dmesg.txt \ndist=`cat /etc/issue`\necho $dist\nif [[ $dist == *Debian* ]] || [[  $dist == *Ubuntu* ]]\nthen\nLog \"Kernel Loaded Packages\" 'dpkg -l | grep kernel' $dirname/KernelPackagess.txt\nelse\nLog \"Kernel Loaded Packages\" 'rpm -qa | grep kernel' $dirname/KernelPackages.txt \nfi\n#Log \"var log messages saved\" 'cat /var/log/messages' $dirname/VarLogMessages.txt \nLog \"System has Been up since\" 'uptime' $dirname/OS.log \necho \"Operating system Log process finished...\"\nLog \"I/O Scheduler Details\" 'cat /sys/block/sda/queue/scheduler ' $dirname/OS.log \n}\n\nCollect_LIS() {\necho \"Collecting Microsoft Linux Integration Service Data...\"\nLog \"LIS Modules Loaded\" 'lsmod | grep vsc' $dirname/LISDetails.txt \nvmbus=`lsmod | grep vmbus | cut -d' ' -f1`\nLog \"LIS Modules version Details\" 'modinfo $vmbus' $dirname/LISDetails.txt\necho \"Collecting Microsoft Linux Integration Service Data Finsished...\"\n}\n\nCollect_DiskandMemory() {\necho \"Collecting Disk and Memory Data\"\nLog \"Disk Partition Details\" 'fdisk -l' $dirname/Disk.txt \nLog \"Filesystem details\" 'df -k' $dirname/Disk.txt \nLog \"Additional Partition Details\" 'cat /proc/partitions' $dirname/Disk.txt \nLog \"Memory Details\" 'cat /proc/meminfo' $dirname/Memory.txt \nLog \"Scsi details\" 'cat /proc/scsi/scsi' $dirname/Disk.txt \nLog \"Memory Usage Details in MB\" 'free -m' $dirname/Memory.txt \nLog \"I/O Memory details\" 'cat /proc/iomem' $dirname/Memory.txt \necho \"Collecting Disk and Memory Data Finished...\"\n}\n\nCollect_Processor() {\necho \"Collecting Processor Data...\"\nLog \"Processor Details\" 'cat /proc/cpuinfo' $dirname/Cpuinfo.txt \nLog \"Processor Count\" 'cat /proc/cpuinfo | grep ^proc' $dirname/Cpuinfo.txt \nLog \"Interrurpts details\" 'cat /proc/interrupts' $dirname/interrupts.txt\nLog \"List of loaded Modules\" 'lsmod' $dirname/Modules.txt \nLog \"List of IO Ports\" 'cat /proc/ioports' $dirname/IOports.txt \nLog \"Processor Real time activity\" 'top -b -n 5' $dirname/Top.txt  \nLog \"Processes consuming most amount of memory\" 'ps -eo pcpu,pid,user,args | sort -k 1 -r | head -10' $dirname/Top.txt \necho \"Collecting Processor Data Finished...\"\n}\n\nCollect_Network() {\necho \"Collecting Network Data...\"\nLog \"Network Interface Details\" 'ifconfig -a' $dirname/Network.txt  \nLog \"Network Status Details by interface\" 'netstat -i' $dirname/Network.txt \nLog \"Network Status Details of all sockets\" 'netstat -a' $dirname/Network.txt \nLog \"Network Status Details Source and Destinations ips and ports\" 'netstat -lan' $dirname/Network.txt \nLog \"Routing Table Details\" 'route' $dirname/Route.txt \necho \"Collecting Network Data Finished...\"\n}\n\nCreate_Compr_Logs() {\necho \"Compressing Logs\"\ntar -czf $dirname.tgz $dirname/*\n}\n\nUpload_Logs() {\nreturn;\n\n}\nintro\nCollect_OS_Logs\nCollect_Waagent_Logs\nCollect_LIS\nCollect_DiskandMemory\nCollect_Processor\nCollect_Network\nCreate_Compr_Logs\n\n", "num_lines": 143}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script will execute either \"Extend logical volume\" or \"Shrink logical volume\" based on given test param.\n# Run the script : ./lvm_extend_shrink_test.sh <username> <testparam>\n# Ex: ./lvm_extend_shrink_test.sh test rootdisk/datadisk Extend\n# ./lvm_extend_shrink_test.sh test rootdisk/datadisk Shrink\n#\n# Author: Ranjith Muthineni\n# Email\t: v-ranmut@microsoft.com\n#\n#####################################################\n\nif [[ $# == 3 ]]\nthen\n\tusername=$1\n\tdiskparam=$2\n\ttestparam=$3\nelse\n\techo \"Usage: bash $0 <username>\"\n\texit -1\nfi\n\n. /home/$username/azuremodules.sh\n\n#Function for LVM setup.\nlvm_setup () {\n\techo \"--- LVM $LV_FULLNAME creation started ---\"\n\n\t#Create a partition of LVM type (Hex 8e) on the new disk\n\t(echo n;echo p;echo 1;echo;echo;echo t;echo 8e;echo p;echo w)|fdisk -c -u $LVM_DISK\n\tfdisk -l $LVM_DISK | grep $LVM_PARTITION\n\tcheck_exit_status \"Create a partition of LVM type on $LVM_DISK data disk\" exit\n\n\tyes | pvcreate $LVM_PARTITION\n\tcheck_exit_status \"Physical volume $LVM_PARTITION create\" exit\n\tpvs\n\n\tvgcreate $VG_NAME $LVM_PARTITION\n\tcheck_exit_status \"Volume group $VG_NAME create\" exit\n\tvgs $VG_NAME\n\n\tlvcreate -l 100%FREE $VG_NAME -n $LV_NAME\n\tcheck_exit_status \"Logical Volume $LV_FULLNAME create\" exit\n\tlvs $LV_FULLNAME\n\n\tif grep -q \"SUSE Linux Enterprise Server 11\" /etc/*-release\n\tthen\n\t\techo \"Formatting $LV_FULLNAME with ext3 FS\"\n\t\ttime mkfs.ext3 $LV_FULLNAME\n\telse\n\t\techo \"Formatting $LV_FULLNAME with ext4 FS\"\n\t\ttime mkfs.ext4 $LV_FULLNAME\n\tfi\n\tcheck_exit_status \"Logical Volume $LV_FULLNAME format\" exit\n\n\tmount -o barrier=0 $LV_FULLNAME $mountdir\n\tcheck_exit_status \"Logical Volume $LV_FULLNAME mount on $mountdir\" exit\n\n\tuuid=`blkid $LV_FULLNAME| sed \"s/.*UUID=\\\"//\"| sed \"s/\\\".*\\\"//\"`\n\techo $uuid\n\techo \"UUID=$uuid $mountdir ext4 defaults,barrier=0 0 2\" >> /etc/fstab\n}\n\n#Function for LVM Extend setup.\nlvm_extend_setup () {\n\t#Create a partition of LVM type (Hex 8e) on the new disk\n\t(echo n;echo p;echo 1;echo;echo;echo t;echo 8e;echo p;echo w)|fdisk -c -u $DATA_DISK\n\tfdisk -l $DATA_DISK | grep $DATA_PARTITION\n\tcheck_exit_status \"Create a partition of LVM type on $DATA_DISK data disk\" exit\n\n\t#Create a physical volume with the new partition\n\tpvcreate $DATA_PARTITION\n\tcheck_exit_status \"Physical volume $DATA_PARTITION create\" exit\n\tpvs\n\n\t#Extend the volume group with the new PV\n\tvgs $VG_NAME\n\tvgextend $VG_NAME $DATA_PARTITION\n\tcheck_exit_status \"Extend the volume group $VG_NAME with $DATA_PARTITION PV\" exit\n\tvgs $VG_NAME\n\n\t#Extend the root LV and resize the file system\n\tlvs $LV_FULLNAME\n\tlvextend -l +100%FREE $LV_FULLNAME --resize\n\tcheck_exit_status \"Extend the root LV $LV_FULLNAME\" exit\n\tresize2fs $LV_FULLNAME\n\tlvs $LV_FULLNAME\n}\n\n#Function for LVM Shrink setup.\nlvm_shrink_setup () {\n\t#Shrink the LV to reduce the size of the data disk\n\tset $(pvs --noheadings -o pv_pe_count,pv_pe_alloc_count $DATA_PARTITION)\n\tTotal_PE=$1\n\tAllocated_PE=$2\n\techo \"Total_PE:$Total_PE\" \"Allocated_PE:$Allocated_PE\"\n\n\tlvdisplay $LV_FULLNAME\n\tlvreduce -l -$Total_PE -f $LV_FULLNAME\n\tcheck_exit_status \"Shrink the root LV $LV_FULLNAME\" exit\n\tresize2fs $LV_FULLNAME\n\tlvdisplay $LV_FULLNAME\n\n\t#Check whether the PV of the data disk partition is Free\n\t#If it\u00e2\u20ac\u2122s not all free, move the data of the partition\n\tpvs -o+pv_used\n\tpvmove $DATA_PARTITION\n\n\t#Remove the PV from VG\n\tvgs $VG_NAME\n\tvgreduce $VG_NAME $DATA_PARTITION\n\tcheck_exit_status \"Remove the $DATA_PARTITION PV from $VG_NAME VG\" exit\n\tvgs $VG_NAME\n\n\t#Remove physical volume\n\tpvremove $DATA_PARTITION\n\tcheck_exit_status \"Physical volume $DATA_PARTITION remove\" exit\n\n\t#Remove attached disk partition\n\t(echo d;echo p;echo w)|fdisk $DATA_DISK\n\t! (fdisk -l $DATA_DISK | grep $DATA_PARTITION)\n\tcheck_exit_status \"Remove attached disk partition $DATA_PARTITION\" exit\n}\n\n#Function for trigger iozone test\niozone_test () {\n\techo \"Running iozone test on $diskparam\"\n\tif [ \"$diskparam\" == \"rootdisk\" ]; then\n\t\tiozone -a -z -g 10g -k 16 -Vazure >> /home/$username/iozone_output.txt &\n\telse\n\t\t(cd $mountdir && iozone -a -z -g 10g -k 16 -Vazure >> /home/$username/iozone_output.txt &)\n\tfi\n\tsleep 30\n\tpgrep iozone\n\tcheck_exit_status \"Make sure iozone test is running\" exit\n}\n\n###########################################################################\n#Main script.\n###########################################################################\necho \"We are running $testparam LVM Functional test on $diskparam.\"\n\n#Collect dmesg logs\necho \"Collect inital system logs\"\ndmesg > dmesg-beforetest.txt\n\n#Get the required variables for test\nsleep 60\nif [ \"$diskparam\" == \"rootdisk\" ]; then\n\tset $(lvs --noheadings -o lv_name,vg_name)\n\tLV_NAME=$1\n\tVG_NAME=$2\n\tLV_FULLNAME=/dev/$VG_NAME/$LV_NAME\n\techo \"LV_NAME:$LV_NAME\" \"VG_NAME:$VG_NAME\" \"LV_FULLNAME:$LV_FULLNAME\"\n\techo \"We are using $DATA_DISK data disk and $LV_FULLNAME Logical volume\"\nelif [ \"$diskparam\" == \"datadisk\" ]; then\n\tLVM_DISK=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\"`\n\tcheck_exit_status \"Datd disk is attached for LVM setup\" exit\n\tLVM_PARTITION=${LVM_DISK}1\n\techo \"LVM_DISK:$LVM_DISK\" \"LVM_PARTITION:$LVM_PARTITION\"\n\tLV_NAME=lv1\n\tVG_NAME=vg1\n\tLV_FULLNAME=/dev/$VG_NAME/$LV_NAME\n\tmountdir=/dataLVM\n\t[ ! -d $mountdir ] && mkdir $mountdir\n\techo \"LV_NAME:$LV_NAME\" \"VG_NAME:$VG_NAME\" \"LV_FULLNAME:$LV_FULLNAME\"\n\techo \"We are using $LVM_DISK data disk for create $LV_FULLNAME Logical volume\"\n\tlvm_setup\nelse\n\techo \"Please pass valid test param for diskparam\"\nfi\n\n#Attach data disk for LVM Extend\ni=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' | wc -l`\nj=$i\necho \"Now Attach data disk for LVM test using powershell\"\nwhile [ $i -eq $j ]\ndo\n\techo \"data disk is not exist, please wait\"\n\tj=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' | wc -l`\n\tsleep 30\ndone\necho \"Data disk is attached successfully for LVM functional test\"\nDATA_DISK=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\"| tail -1`\nDATA_PARTITION=${DATA_DISK}1\necho \"DATA_DISK:$DATA_DISK\" \"DATA_PARTITION:$DATA_PARTITION\"\n\nif [ \"$testparam\" == \"Extend\" ]; then\n\t#Trigger iozone test on $diskparam\n\tiozone_test\n\n\t#Running LVM extend setup.\n\tlvm_extend_setup\nelif [ \"$testparam\" == \"Shrink\" ]; then\n\t#Running LVM extend setup.\n\tlvm_extend_setup\n\n\t#Trigger iozone test on $diskparam\n\tiozone_test\n\n\t#Running LVM shrink setup.\n\tlvm_shrink_setup\n\n\t#Now Deattach the data disk.\n\ti=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' | wc -l`\n\tj=$i\n\techo \"Now Deattach the data disk using powershell\"\n\twhile [ $i -eq $j ]\n\tdo\n\t\techo \"data disk $DATA_DISK is still exist, please wait\"\n\t\tj=`fdisk -l | grep 'Disk.*/dev/sd[a-z]' | wc -l`\n\t\tsleep 30\n\tdone\n\techo \"data disk $DATA_DISK is removed successfully\"\nelse\n\techo \"Please pass valid test param for test\"\nfi\n\n#Check IOZone finished successfully and there\u00e2\u20ac\u2122s no error in system logs\n#Make sure IOZone test is still running after LVM test\npgrep iozone\ncheck_exit_status \"Make sure IOZone test is still running after LVM test\" exit\ncount=0\n#Wait till IOZone finished successfully\nwhile [ `pgrep iozone` ]\ndo\n\techo \"iozone test is still running, please wait\"\n\tcount=$((count+1))\n\tif [ $count -gt 30 ]; then\n\t\techo -e \"\\niozone test complete.\\n\" >> /home/$username/iozone_output.txt\n\t\techo \"Loop count exceeded maximum limit\"\n\t\tkillall iozone\n\t\tbreak\n\tfi\n\techo $count\n\tsleep 60\ndone\n\ngrep \"iozone test complete\" /home/$username/iozone_output.txt\ncheck_exit_status \"IOZone test status\" exit\n\n#Checking errors in system logs\ndmesg > dmesg-aftertest.txt\ndiff dmesg-beforetest.txt dmesg-aftertest.txt | egrep 'fail|error|trace' | egrep -v 'floppy|fd0' > systemerrorlogs.txt\nif [ `cat systemerrorlogs.txt | wc -l` -gt 0 ]; then\n\techo \"we got error logs in system logs\"\n\tcat systemerrorlogs.txt\nelse\n\techo \"no errors in system logs\"\nfi\n\necho \"LVM functionlal test completed\"\n\necho \"Compressing log files.. \"\ncd /home/$username; tar -cvf logs.tar *.txt\n\nexit 0\n", "num_lines": 258}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\ndiskName=$diskName\ndelete=$delete\ncreate=$create\nforRaid=$forRaid\nif [ \"$create\" = \"yes\" ]; then\n    if [ \"$forRaid\" = \"yes\" ]; then\n        (echo n; echo p; echo 1; echo; echo; echo t; echo fd;  echo w) | fdisk $diskName\n        exitVal=$?\n    elif [ \"$forRaid\" = \"no\" ]; then\n        (echo n; echo p; echo 1; echo; echo; echo w) | fdisk $diskName\n        exitVal=$?\n    fi\nfi\nif [ \"$delete\" = \"yes\" ]; then\n    (echo d; echo w;) | fdisk $diskName\n    exitVal=$?\nfi\nexit $exitVal", "num_lines": 28}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\ndiskNames=$diskNames\ncreate=$create\nRaidName=$RaidName\ntotalDisks=$totalDisks\ndiskNames=${diskNames//^/ }\nif [ \"$create\" = \"yes\" ]; then\n\techo y | mdadm --create $RaidName --level 0 --raid-devices $totalDisks $diskNames\n\texitVal=$?\nfi\nexit $exitVal", "num_lines": 20}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# MariaDB performance using sysbench client.\n# Packages needed: sysbench bc\n# usage::-\n# nohup bash sysbench-mariadb-perf-test.sh <vm_loginuser> <vm_loginpasswd> <mariadb_server IP> &\n# or\n#./sysbench-mariadb-perf-test.sh <vm_loginuser> <vm_loginpasswd> <mariadb_server IP> &\n#\n# Author: Srikanth Myakam\n# Email\t: v-srm@microsoft.com\n#\n###########################################################################\n\n\n#set -u\n#set -x\n\nif [[ $# == 3 ]]\nthen\n\tusername=$1\n\tuser_password=$2\n\tmariadb_server=$3\nelse\n\techo \"Usage: bash $0 <vm_loginuser> <vm_loginpasswd> <mariadb_server IP>\"\n\texit -1\nfi\n\nmariadb_user=\"root\" \nmariadb_passwd=\"mariadb_passwd\"\nperf_db=\"iperf_db\"\n\ncode_path=\"/home/$username/code\"\nLOGDIR=\"${code_path}/mysql_perf_log\"\nmv $LOGDIR $LOGDIR-$(date +\"%m%d%Y-%H%M%S\")/\nmkdir $LOGDIR\nLOGFILE=\"${LOGDIR}/mysql_perf_sysbench.log\"\ntouch $LOGFILE\ntail -f $LOGFILE &\n\n. $code_path/azuremodules.sh\n\necho \"Creating code folder on server VM\" >> $LOGFILE\nremote_exec -user $username -passwd $user_password -host $mariadb_server \"mkdir $code_path\"  >> $LOGFILE\necho \"Uploading files to server\" >> $LOGFILE\nremote_copy -user $username -passwd $user_password -host $mariadb_server -filename ${code_path}/azuremodules.sh -remote_path $code_path -cmd \"put\" >> $LOGFILE\nremote_copy -user $username -passwd $user_password -host $mariadb_server -filename ${code_path}/mariadb_perf_server_conf.sh -remote_path $code_path -cmd \"put\" >> $LOGFILE\necho \"Verifying MYSQL server instances on Server VM\"  >> $LOGFILE\nremote_exec -user $username -passwd $user_password -host $mariadb_server \"echo $user_password | sudo -S bash $code_path/mariadb_perf_server_conf.sh $username\" >> $LOGFILE\nreturn_value=`remote_exec -user $username -passwd $user_password -host $mariadb_server \"netstat -napt| grep ':3306 '|wc -l\"`\n\nif [[ $return_value == 0 ]]\nthen\n\techo \"Server configuration failued\" >> $LOGFILE\n\techo \"MYSQL Perf TEST ABORTED\" >> $LOGFILE\n\texit -1\nelse\n\techo \"DB server is running\" >> $LOGFILE\nfi\n\ninstall_package \"sysbench\" >> $LOGFILE\ninstall_package \"mysql-client*\" >> $LOGFILE\n\nFILEIO=\" --test=oltp --db-driver=mysql --mysql-db=$perf_db --mysql-host=$mariadb_server --mysql-user=$mariadb_user --mysql-password=$mariadb_passwd \"\n\necho \"uname: -------------------------------------------------\" >> $LOGFILE\nuname -a 2>&1 >> $LOGFILE\necho \"LIS version: --------------------------------------------\" >> $LOGFILE\nmodinfo hv_vmbus 2>&1 >> $LOGFILE\necho \"----------------------------------------------------------\" >> $LOGFILE\necho \"Number of CPU cores:\" `nproc` >> $LOGFILE\necho \"Memory:\" `free -h| grep Mem| awk '{print $2}'` >> $LOGFILE\necho \"Host Build Version:\" `dmesg | grep \"Host Build\" | sed \"s/.*Host Build://\"| awk '{print  $1}'| sed \"s/;//\"`  >> $LOGFILE\n\nruntime=300\nthreads=990\ntable_size=10000000\n\necho \"Test log created at: ${LOGFILE}\"\necho \"===================================== Starting Run $(date +\"%x %r %Z\") ================================\" >> $LOGFILE\n\nchmod 666 $LOGFILE\necho \"Preparing Files: $FILEIO\" >> $LOGFILE\n# Remove any old files from prior runs (to be safe), then prepare a set of new files.\nsysbench $FILEIO cleanup\n\ntime sysbench $FILEIO --oltp-table-size=$table_size prepare 2>&1 >> $LOGFILE\necho \"=== End Preparation  $(date +\"%x %r %Z\") ===\" >> $LOGFILE\nmysql -u root -p$mariadb_passwd --host=$mariadb_server -e \"SET GLOBAL max_connections = 5000;\"\necho \"------------------------------- mysql_perf, ${table_size} table_size, ${threads} threads, $runtime seconds ------------------ $(date +\"%x %r %Z\") ---\" >> $LOGFILE\nsysbench $FILEIO --max-time=$runtime --max-requests=0 --oltp-table-size=$table_size --num-threads=$threads run >> $LOGFILE\n\necho \"===================================== Completed Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\nsysbench $FILEIO cleanup >> $LOGFILE\n\ncompressedFileName=\"mariadb-db-test\"$(date +\"%m%d%Y-%H%M%S\")\".tar.gz\"\necho \"Please wait...Compressing all results to ${compressedFileName}...\"\ntar -cvf $compressedFileName $LOGDIR/ 2>&1 > /dev/null\n\ntest_run=`tail -150 $LOGFILE | grep \"Test execution summary:\"`\n\nif [[ $test_run != \"\" ]]\nthen\n\techo \"MYSQL_Perf_TEST_COMPLETED\" >> $LOGFILE\nelse\n\techo \"MYSQL_Perf_TEST_ABORTED\" >> $LOGFILE\nfi\n\necho \"Test logs are located at ${LOGDIR}\"\n##\n", "num_lines": 110}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script does the following:\n# 1. Prepares the RAID with all the data disks attached \n# 2. Places an entry for the created RAID in /etc/fstab.\n# 3. Configures mariadb server for sysbench performance test.\n# Usage:-\n# nohup bash mariadb_perf_server_conf.sh vm_loginuser &\n#\n# Author: Srikanth Myakam\n# Email\t: v-srm@microsoft.com\n#\n###########################################################################\n\nif [[ $# == 1 ]]\nthen\n\tusername=$1\nelse\n\techo \"Usage: bash $0 <username>\"\n\texit -1\nfi\ncode_path=\"/home/$username/code\"\n. $code_path/azuremodules.sh\n\nfunction install_mysql_server () \n{\n\tif [[ `detect_linux_ditribution` == \"ubuntu\" ]]\n\tthen\n\t\tmariadb_passwd=$1\n\t\texport DEBIAN_FRONTEND=noninteractive\n\t\techo mysql-server mysql-server/root_password select $mariadb_passwd | debconf-set-selections\n\t\techo mysql-server mysql-server/root_password_again select $mariadb_passwd| debconf-set-selections\n\t\tapt-get install -y  --force-yes mysql-server\n\t\tcheck_exit_status \"Installation of mysql-server\" exit\n\telse\n\t\tinstall_package mariadb-server\n\t\tcheck_exit_status \"Installation of mariadb\" exit\n\tfi\n}\n\nformat=\"ext4\"\nmountdir=\"/dataIOtest\"\ndeviceName=\"/dev/md1\"\nLOGFILE=\"${code_path}/mariadb_perftest.log.txt\"\nmariadb_passwd=\"mariadb_passwd\"\nperf_db=\"iperf_db\"\nmysql_cnf_file=\"\"\n\n\ninstall_mysql_server $mariadb_passwd\n\nif [[ -f /etc/mysql/mariadb.conf.d/mysqld.cnf ]]; then\n\tmysql_cnf_file=/etc/mysql/mariadb.conf.d/mysqld.cnf\nelif [[ -f /etc/mysql/mysql.conf.d/mysqld.cnf ]]; then\n\tmysql_cnf_file=/etc/mysql/mysql.conf.d/mysqld.cnf\nelif [[ -f /etc/mysql/my.cnf ]]; then\n\tmysql_cnf_file=/etc/mysql/my.cnf\nelif [[ -f /etc/my.cnf ]]; then\n\tmysql_cnf_file=/etc/my.cnf \nelse\n\techo \"Cannnot find mariadb configuration file check the installation\"\n\texit -1\nfi\n\necho \"IO test setup started..\" > $LOGFILE\n\n# Verify if there are any unsed disks and creat raid using them and move the db folder to there\nlist=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\nif [[ ${#list[@]} -gt 0 ]]\nthen\n\tcreate_raid_and_mount $deviceName $mountdir $format >> $LOGFILE\n\tdf -hT >> $LOGFILE\n\techo \"## Configuring mariadb\" >> $LOGFILE\n\tmysql_datadir=\"$mountdir/mysql\"\n\tmkdir $mysql_datadir\n\tchmod 755 -R $mysql_datadir\n\tcp -rf /var/lib/mysql/* $mysql_datadir\n#\tsed -i  \"s#datadir.*#datadir         = $mysql_datadir#\" $mysql_cnf_file\n\tsed -i  \"s/\\(.(*datadir.*\\)/#\\1/\" $mysql_cnf_file\n\techo \"datadir         = $mysql_datadir\" >> $mysql_cnf_file\nfi\nsed -i \"s/\\(.*bind-address.*\\)/#\\1/\" $mysql_cnf_file\nsed -i \"s/\\(.*max_connections.*\\)/#\\1/\" $mysql_cnf_file\necho \"bind-address                = 0.0.0.0\" >> $mysql_cnf_file\necho \"max_connections                = 1024\" >> $mysql_cnf_file\n\nservice mysql restart\nservice mariadb restart\n\n#echo \"Mysql secure installation started\" >> $LOGFILE\n#echo -e \"\\ny\\ny\\n$mariadb_passwd\\n$mariadb_passwd\\ny\\ny\\ny\\ny\" |/usr/bin/mysql_secure_installation >> $LOGFILE\n#echo -e \"\\ny\\n$mariadb_passwd\\n$mariadb_passwd\\ny\\nn\\ny\\ny\" |/usr/bin/mysql_secure_installation >> $LOGFILE\n#check_exit_status \"/usr/bin/mysql_secure_installation\"  >> $LOGFILE \nmysql -u root -p$mariadb_passwd -e \"GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '$mariadb_passwd' WITH GRANT OPTION;\" >> $LOGFILE\ncheck_exit_status \"Enabling mysql remote access\"  >> $LOGFILE\nmysql -u root -p$mariadb_passwd -e \"DROP DATABASE $perf_db;\" >> $LOGFILE\nmysql -u root -p$mariadb_passwd -e \"CREATE DATABASE $perf_db;\" >> $LOGFILE\nmysql -u root -p$mariadb_passwd -e \"SET GLOBAL max_connections = 5000;\" >> $LOGFILE\nmysql -u root -p$mariadb_passwd -e \"FLUSH PRIVILEGES;\" >> $LOGFILE\ncheck_exit_status \"Created database for performance\"  >> $LOGFILE\nservice mysql restart\nservice mariadb restart\necho \"done\"\n", "num_lines": 105}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nnc=$1\nduration=$2\necho \"Starting iperf client in `hostname`\"\necho \"Num of Connections: $nc\"\ntotal_no_vms=`cat hostnames.txt | wc -l`\nnc_vm=$(($nc/$((($total_no_vms-1)*2))))\necho \"Num of Connections per VM $nc_vm\"\nmy_hostname=`hostname`\nmy_vm_number=`cat hostnames.txt | grep -n $my_hostname$| sed s/:.*//`\nhostnames=(`cat hostnames.txt`)\n#start sar with nc and time in its name\necho \"stating sar in client `hostname`\"\nsarlog=$nc-`hostname`\nbash collect-stats.sh $duration $sarlog &\nfor server_vm_number in `seq 0 $((${#hostnames[@]}-1))` \ndo\n\tif [ ${hostnames[$server_vm_number]} != $my_hostname ]\n\tthen\t\t\n\t\tnumber_of_connections=$nc_vm\n\t\techo $server_vm_number:$my_vm_number\n\t\tport_number=$((8001+($my_vm_number-1)*6))\n\t\twhile [ $number_of_connections -gt 64 ]; do\n\t\t\tnumber_of_connections=$(($number_of_connections-64))\n\t\t\techo \"iperf3 -c ${hostnames[$server_vm_number]} -p $port_number -P 64 -t $duration >> `hostname`-clientlog.txt &\" # /dev/null  &\n\t\t\tiperf3 -c ${hostnames[$server_vm_number]} -p $port_number -P 64 -t $duration > /dev/null &\n\t\t\tport_number=$((port_number+1))\n\t\tdone\n\t\techo \"iperf3 -c ${hostnames[$server_vm_number]} -p $port_number -P $number_of_connections -t $duration >> `hostname`-clientlog.txt &\" #/dev/null\"\n\t\tiperf3 -c ${hostnames[$server_vm_number]} -p $port_number -P $number_of_connections -t $duration > /dev/null &\n\tfi\ndone\niperf_count=`pgrep iperf3 | wc -l`\nif [ $iperf_count -gt 100 ]; then\n\techo \"iperf clients is running in `hostname`\"\nelse\n\techo \"iperf clients is not running in `hostname`\"\nfi\n\nexit 0\n", "num_lines": 41}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#Prerequisites: iperf3, sysstat(for sar), dos2unix\n\nuser=$1\npasswd=$2\nserver_file=$3\nclient_file=$4\nnum_of_connections=$5\nduration=$6\nhostnames=(`cat hostnames.txt`)\ncount=0\n\nmainlog=\"$num_of_connections\"_main_log.txt\nserverlog=\"$num_of_connections\"_server_status.txt\nclientlog=\"$num_of_connections\"_client_status.txt\n[ -f $mainlog ] && rm -rf $mainlog\n[ -f $serverlog ] && rm -rf $serverlog\n[ -f $clientlog ] && rm -rf $clientlog\n#Process to start server..\nwhile [ \"x${hostnames[count]}\" != \"x\" ]\ndo\n\techo ${hostnames[count]} >> $mainlog\n\tif [ `hostname` == ${hostnames[$count]} ]; then\n\t\techo \"start server in localhost\" >> $mainlog\n\t\tbash $server_file >> $serverlog\n\telse\n\t\techo \"copying server file to ${hostnames[$count]} and start server\" >> $mainlog\n\t\tsshpass -p $passwd scp -o StrictHostKeyChecking=no $server_file $client_file hostnames.txt collect-stats.sh $user@${hostnames[$count]}:/home/$user\n\t\tsshpass -p $passwd ssh -o StrictHostKeyChecking=no $user@${hostnames[$count]} \"bash $server_file\" >> $serverlog\n\tfi\n\tcount=$(( $count + 1 ))\ndone\n\n#Process to start client..\nserver_status=`cat $serverlog | grep \"iperf server is running\" | wc -l`\necho \"Server status: $server_status\" >> $mainlog\nif [ $server_status == `cat hostnames.txt | wc -l` ]; then\n\techo \"iperf server is running in all machines..\" >> $mainlog\n\tcount=0\n\twhile [ \"x${hostnames[count]}\" != \"x\" ]\n\tdo\n\t\techo ${hostnames[count]} >> $mainlog\n\t\tif [ `hostname` == ${hostnames[$count]} ]; then\n\t\t\techo \"starting client in localhost\" >> $mainlog\n\t\t\t\tbash $client_file $num_of_connections $duration >> $clientlog &\n\t\telse\n\t\t\techo \"starting client in ${hostnames[$count]}\" >> $mainlog\n\t\t\t\tsshpass -p $passwd ssh -o StrictHostKeyChecking=no $user@${hostnames[$count]} \"bash $client_file $num_of_connections $duration\" >> $clientlog &\n\t\tfi\n\t\tcount=$(( $count + 1 ))\n\tdone\nelse\n\techo \"iperf server is not running, check server status..\" >> $mainlog\n\techo \"Mesh Network test Failed\"\n\texit 10\nfi\necho \"iperf tests are running please wait\"\nsleep $(( $duration + 120 ))\ncount=0\niperf_status=0\nwhile [ \"x${hostnames[count]}\" != \"x\" ]\ndo\n\techo \"verifying iperf client status in ${hostnames[$count]}\" >> $mainlog\n\tiperfc_count=`sshpass -p $passwd ssh -o StrictHostKeyChecking=no $user@${hostnames[$count]} \"pgrep iperf3| wc -l\"`\n\tif [ $iperfc_count != 100 ]; then\n\t\techo \"IPERF client status in ${hostnames[$count]}:$iperfc_count\" >> $mainlog\n\t\tiperf_status=$(( $iperf_status + 1 ))\n\telse\n\t\techo \"Iperf test completed in ${hostnames[$count]}\" >> $mainlog\n\tfi\n\tcount=$(( $count + 1 ))\ndone\nif [ $iperf_status != 0 ]; then\n\techo \"Mesh Network test Failed\"\nelse\n\techo \"Mesh Network test Success\"\n\t\n#collecting logs..\ncount=0\nwhile [ \"x${hostnames[count]}\" != \"x\" ]\ndo\n\techo ${hostnames[count]} >> $mainlog\n\tif [ `hostname` == ${hostnames[$count]} ]; then\n\t\techo \"copying localhost logs\" >> $mainlog\n\telse\n\t\techo \"copying logs from ${hostnames[$count]} to localhost \" >> $mainlog\n\t\tsshpass -p $passwd scp -o StrictHostKeyChecking=no $user@${hostnames[$count]}:/home/$user/$num_of_connections\"-*.log\" /home/$user/  >> $mainlog\n\tfi\n\tcount=$(( $count + 1 ))\ndone\n\nfi\n\nexit 0\n", "num_lines": 95}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#Running iperf3 server for 8001 to 8100 ports\nkillall iperf3 > /dev/null 2>&1\nfor i in {8001..8100}\ndo\n\tiperf3 -s -D -p $i\ndone\ncount=$(pgrep iperf3 | wc -l)\nif [ $count -eq 100 ]; then\n\techo \"iperf server is running and available from 8001 to 8100 ports in `hostname`\"\nelse\n\techo \"iperf server is not running as a daemon\"\nfi\n\nexit 0\n", "num_lines": 16}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script places the server and client commands in the startup for the network performance test.\n# Author: Sivakanth R\n# Email\t: v-sirebb@microsoft.com\n#\n#####\n\nvm_type=$1\nusername=$2\nserver_ip=$3\ntesttype=$4\nbuffersize=$5\n\ncode_path=\"/home/$username/code\"\nerror_file=\"$code_path/error_file.log\"\ntestcommand=\"\"\n\nif [ \"$vm_type\" = \"server\" ]\nthen\n\ttestcommand=\"bash $code_path/server_start.sh $username $testtype $buffersize >> $code_path/server.log&\" \nelif [ \"$vm_type\" = \"client\" ]\nthen\n\tif [ \"$#\" -ne 5 ]; then\n\t\techo \"Illegal number of parameters passed exiting...\" >> $error_file\n\tfi\n\ttestcommand=\"bash $code_path/client_start.sh $server_ip $username $testtype $buffersize >> $code_path/client.log&\"\nelse\n\techo \"Invalid arguments passed\" >> $error_file\nfi\n\nbash $code_path/keep_cmds_in_startup.sh $testcommand\n", "num_lines": 33}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#Generating different number of tcp connections (from 1 to 6K) and collect the throughput, Cpu usage and number of re-transmitted packet info.\n#And also format the test results using CSV.\n#Prerequisites: iperf3, sysstat(for sar), dos2unix\nserver_ip=$1\nduration=600\nthreads=(1 2 4 8 16 32 64 128 256 512 1024 2000 3000 4000 5000 6000)\ni=0\nlogs_dir=~/logs\n[ -d $logs_dir ] && rm -rf $logs_dir\nmkdir $logs_dir\n[ -f ~/teststatus.txt ] && rm -rf ~/teststatus.txt\nkillall iperf3\necho \"IPERF test started\" > ~/teststatus.txt\nwhile [ \"x${threads[$i]}\" != \"x\" ]\ndo\n\tport=8001\n\tnumber_of_connections=${threads[$i]}\n\techo \"Current no of connections: $number_of_connections\"\n\techo \"IPERF test running for $number_of_connections connections\" >> ~/teststatus.txt\n\tpresenttestlog=$logs_dir/${threads[$i]}\n\tmkdir $presenttestlog\n\tcount=1\n\tbash ./perf-statistics.sh $duration $presenttestlog &\n\twhile [ $number_of_connections -gt 64 ]; do\n\t\tnumber_of_connections=$(($number_of_connections-64))\n\t\toptions=\"-p $port -P 64 -t $duration\"\n\t\tfile_tag=`echo $options| sed s/-//g| sed \"s/ /_/g\"`\n\t\tlog_file=`echo ${threads[$i]}-$count-$file_tag-iperf.log| sed \"s/-/_/g\"`\n\t\techo $log_file\n\t\tiperf3 -c $server_ip $options > $presenttestlog/$log_file &\n\t\tport=$((port+1))\n\t\tcount=$((count+1))\n\tdone\n\toptions=\"-p $port -P $number_of_connections -t $duration\"\n\tfile_tag=`echo $options| sed s/-//g| sed \"s/ /_/g\"`\n\tlog_file=`echo ${threads[$i]}-$count-$file_tag-iperf.log| sed \"s/-/_/g\"`\n\techo $log_file\n\tiperf3 -c $server_ip $options > $presenttestlog/$log_file\n\ti=$(($i + 1))\n\tport=$(($port + 1))\n\tsleep 10\ndone\necho \"IPERF test completed\" >> ~/teststatus.txt\n\n#formatting logs into csv file:\nmkdir $logs_dir/csvs\ncd $logs_dir/\noptions=(`ls */*iperf.log | sed s/\\.log//`)\necho \"CSV test started\" >> ~/teststatus.txt\ncount=0\nwhile [ \"x${options[count]}\" != \"x\" ]\ndo\n\techo \"${options[count]}\"\n\tcat ${options[count]}.log | grep SUM > /dev/null\n\tif [ $? -ne 0 ]; then\n\t\tcat ${options[count]}.log | grep sec | awk '!($1=\"\")' | awk '!($1=\"\")' | awk '{$1=$1}1' OFS=\",\"| sed s/\\(// | sed s/\\)//|sed s/-/,/ | sed s/%//>$logs_dir/csvs/`basename ${options[count]}`.csv\n\telse\n\t\tcat ${options[count]}.log | grep SUM | awk '!($1=\"\")' | awk '{$1=$1}1' OFS=\",\"| sed s/\\(// | sed s/\\)//|sed s/-/,/ | sed s/%//>$logs_dir/csvs/`basename ${options[count]}`.csv\n\tfi\n\tcount=$(( $count + 1 )) \ndone\necho \"CSV test completed\" >> ~/teststatus.txt\ncd ~\ntar -cvf logs.tar logs > /dev/null\necho \"PERF test completed\" >> ~/teststatus.txt\n\nexit 0\n", "num_lines": 69}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#Running iperf3 server for 8001 to 8100 ports\nkillall iperf3\nfor i in {8001..8100}\ndo\n\tiperf3 -s -D -p $i\ndone\ncount=$(pgrep iperf3 | wc -l)\nif [ $count -eq 100 ]; then\n\techo \"iperf server is running and available from 8001 to 8100 ports\"\nelse\n\techo \"iperf server is not running as a daemon\"\nfi\n", "num_lines": 14}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#This script will connect iperf client to server for executing network performance tests using different iperf options \n#And also format the test results using CSV.\nserver_ip=$1\nreadarray  options < perf-cloudharmony-options.txt\nlogs_dir=~/logs\n[ -d $logs_dir ] && rm -rf $logs_dir\nmkdir $logs_dir\ncount=0\nkillall iperf3\necho \"IPERF test started\" > ~/teststatus.txt\nwhile [ \"x${options[count]}\" != \"x\" ]\ndo\n\techo ${options[$count]}\n\techo \"IPERF test ${options[$count]} running\" >> ~/teststatus.txt\n\tfile_tag=`echo ${options[$count]}| sed s/-//g| sed \"s/ /_/g\"`\n\techo $file_tag\n\tiperf3 -c $server_ip ${options[$count]} > $logs_dir/$file_tag.log\n\tcount=$(( $count + 1 )) \n\tsleep 30\ndone\necho \"IPERF test completed\" >> ~/teststatus.txt\n\n#formatting iperf3logs into csv:\nmkdir $logs_dir/csvs\ncd $logs_dir/\noptions=(`ls *.log | grep \"_u_\"|sed s/\\.log//`)\necho \"CSV test started\" >> ~/teststatus.txt\ncount=0\nwhile [ \"x${options[count]}\" != \"x\" ]\ndo\n\techo \"${options[count]}\"\n\ttail -n+5 ${options[count]}.log | awk '!($1=\"\")' | awk '!($1=\"\")' | awk '{$1=$1}1' OFS=\",\"| sed s/\\(// | sed s/\\)//| sed s/-/,/ | sed s/%//>$logs_dir//csvs/${options[count]}.csv\n\tcount=$(( $count + 1 )) \ndone\n\noptions=(`ls *.log | grep -v \"_u_\"|sed s/\\.log//`)\n\ncount=0\nwhile [ \"x${options[count]}\" != \"x\" ]\ndo\n\techo \"${options[count]}\"\n\tcat ${options[count]}.log  | grep SUM |awk '!($1=\"\")'  | awk '{$1=$1}1' OFS=\",\"| sed s/\\(// | sed s/\\)//|sed s/-/,/ | sed s/%//>$logs_dir//csvs/${options[count]}.csv\n\tcount=$(( $count + 1 )) \ndone\necho \"CSV test completed\" >> ~/teststatus.txt\ncd ~\ntar -cvf logs.tar logs\necho \"PERF test completed\" >> ~/teststatus.txt\n\nexit 0", "num_lines": 51}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#starting iperf server as a daemon\nkillall iperf3\niperf3 -s -D -p 8004\n#\n# Verify that the iperf server is running\npgrep iperf3\nif [ $? -ne 0 ]; then\n\techo \"iperf server is not running as a daemon\"\nelse\n\techo \"iperf server is running as a daemon\"\nfi\n", "num_lines": 13}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\npackageName=$install\nisUpdate=$update\nisRemote=$isRemote\nisLocal=$isLocal\nfileName=$file\nCurrentDate=`date`\n\ninstallFromFolder()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\nsourceFolder=$sourceFolder\ncd $sourceFolder\nls\nif [ -e ./configure ]; then\n    chmod +x configure && ./configure && make && make install\n    exitVal=$?\nelif [ -e ./setup.py ]; then\n    python setup.py build && python setup.py install\n    exitVal=$?\nfi\ncd ..\nreturn $exitVal\n}\n\ngetFolderName()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ncompressedFile=$compressedFile\nif [[ \"$compressedFile\" == *.tar.gz ]]; then\n    folderName=${compressedFile%.tar.gz*}\nelif [[ \"$compressedFile\" == *.tar ]]; then\n    folderName=${compressedFile%.tar.bz2*}\nelif [[ \"$compressedFile\" == *.tar ]]; then\n    folderName=${compressedFile%.tar*}\nfi\necho $folderName\n}\n\ninstallFromCompressedFile()\n{\n#{\n#   extract the source code.\n#   invoke : decompressFile -file $fileName\n#   search for installation files in extracted folder. Like - setup.py / configure / make etc.\n#   invoke \"appropriate\" installation method.. [installPythonSourceCode() / installMakeSourceCode() / ...]\n#   return exit code.\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ncompressedFile=$compressedFile\ndecompressFile -fileToDecompress $compressedFile\ninstallFolder=`getFolderName -compressedFile $compressedFile`\necho \"$installFolder\"\ninstallFromFolder -sourceFolder $installFolder\nexitVal=$?\n\nreturn $exitVal\n}\n\ndecompressFile()\n{\n#   determine the extraction method depending on *.tar, *.tar.gz, *.bz2, *.gzip etc.\n#   execute : tar -xzf / gunzip / bzip etc. and untar the compressed file.\n#   return exit code.\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nfileToDecompress=$fileToDecompress\nif [[ \"$installFile\" == *.tar ]]; then\n    tar -xzvf $fileToDecompress\n        #installFromCompressedFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.tar.gz ]]; then\n    tar -xvf $fileToDecompress\n    exitVal=$?\nfi\n\nif [ $exitVal == 0 ]; then\n    echo \"Decompresssion Successfull\"\nelse\n    echo \"Decompresssion Failed\"\nfi\nreturn $exitVal\n\n}\n#other installation methods support can be added depending on requirement.\n\ninstallLocalFile()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ninstallFile=$LocalFile\nif [[ ( \"$installFile\" == *.tar ) || ( \"$installFile\" == *.tar.gz ) || ( \"$installFile\" == *.tar.bz2 ) ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing from copressed file\"\n    installFromCompressedFile -compressedFile $installFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.rpm ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing rpm file\"\n    rpm -ivh $installFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.deb ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing deb file\"\n    dpkg -i $installFile\n    exitVal=$?\nelif [ -z $installFile ]; then\n    echo \"Please provide file with -file <filename> argument\"\n    exitVal=1\nelse\n    echo \"Unknowin file type..\"\n    exitVal=1\nfi\nreturn $exitVal\n}\ninstallRemotePackage()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\npackageName=$install\n        if [ -e /etc/debian_version ]; then\n                apt-get install --force-yes -y $packageName\n                installStatus=$?\n                if [ $installStatus = 0 ]; then\n                        echo \"Install $packageName : SUCCESS\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\n        if [ -e /etc/redhat-release ]; then\n                sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf\n                yum install --nogpgcheck -y $packageName\n                installStatus=$?\n                if [ $installStatus = \"0\" ]; then\n                        echo \"Install $packageName : SUCCESS\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\n        if [ -e /etc/SuSE-release ]; then\n                zypper --non-interactive --no-gpg-checks install $packageName\n                installStatus=$?\n                if [ $installStatus = \"0\" ]; then\n                        echo \"Install $packageName : SUCCESS\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\nreturn $exitVal\n}\nupdateDistro()\n{\n    if [ -e /etc/debian_version ]; then\n        apt-get --force-yes -y update\n        installStatus=$?\n        if [ $installStatus = 0 ]; then\n            echo \"Install Update : SUCCESS\"\n            exitVal=0\n        else\n        echo \"Install Update : FAILED\"\n        exitVal=1\n        fi\n    fi\n    if [ -e /etc/redhat-release ]; then\n            sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf\n        yum --nogpgcheck -y update\n        installStatus=$?\n        if [ $installStatus = \"0\" ]; then\n            echo \"Install Update : SUCCESS\"\n            exitVal=0\n        else\n            echo \"Install Update : FAILED\"\n            exitVal=1\n        fi\n    fi\n    if [ -e /etc/SuSE-release ]; then\n        zypper --non-interactive --no-gpg-checks update\n        installStatus=$?\n        if [ $installStatus = \"0\" ]; then\n            echo \"Install Update : SUCCESS\"\n            exitVal=0\n        else\n            echo \"Install Update : FAILED\"\n            exitVal=1\n        fi\n    fi\n\nreturn $exitVal\n}\n\n# main body starts here..\n\nif [ \"$isUpdate\" = \"yes\" ]; then\n    updateDistro\n    exitVal=$?\n    exit $exitVal\nfi\nif [ -z $packageName ]; then\n    echo \"No packages are given to install. Please use -package <Package Name>\"\n    exitVal=0\nelse\n    if [ -z $isLocal ]; then\n        echo \"Please mention -isLocal yes/no\"\n    elif [ \"$isLocal\" = \"no\" ]; then\n            installRemotePackage -install $packageName\n            exitVal=$?\n    elif [ \"$isLocal\" = \"yes\" ]; then\n            installLocalFile -LocalFile $fileName\n            exitVal=$?\n    else\n        echo \"Please provide -isLocal yes or -isLocal no [CaSe SensitivE]\"\n    fi\nfi\nexit $exitVal\n", "num_lines": 254}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#This script will reports network statistics and CPU usage\nduration=$1\nfilename=$2\n#Displays network devices vital statistics for eth0 and lo\nsar -n DEV 1 $duration 2>&1 >> $filename/sar.log &\nfor i in $(seq 1 $duration)\ndo\n#Displays the CPU usage\ntop -bn1 | grep \"Cpu(s)\" | sed \"s/.*, *\\([0-9.]*\\)%* id.*/\\1/\" | awk '{print 100 - $1\"%\"}' >> $filename/cpu_usage.log\nsleep 1\ndone\n", "num_lines": 13}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n########################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n########################################################################\n\n#######################################################################\n#\n# performance_mc.sh\n#\n# Description:\n#     This tool uses the memslap to Load testing and benchmarking a server\n#     More info : http://docs.libmemcached.org/bin/memaslap.html\n#\n#\n# In general the script does the following:\n#\n# 1.Install memcached server on mentioned servers and starts memcached server service.\n# 2.Benchmarks mem servers with memslap tool.\n#\n# Parameters:\n# MC_VERSION=1.4.25\n# MC_SERVERS=\"Server1:11211,Server2:11211\"\n# MC_CONCURRENCY=10\n# MC_EXECUTE_NUMBER=10000\n# MC_INITIAL_LOAD=1000\n#######################################################################\n\n\n\nICA_TESTRUNNING=\"TestRunning\"\nICA_TESTCOMPLETED=\"TestCompleted\"\nICA_TESTABORTED=\"TestAborted\"\nICA_TESTFAILED=\"TestFailed\"\n\n#\n# Function definitions\n#\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` \": ${1}\"\n}\n\nUpdateTestState()\n{\n    echo $1 > ~/state.txt\n}\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\n\n######################################################################\n#\n#  Description:\n#    Perform distro specific memcached configuratoin and tool installation steps \n#    and then run the benchmark tool\n#\n#######################################################################\nConfigUbuntuMemC()\n{\n    #\n    # Note: A number of steps will use SSH to issue commands to the\n    #       MC_SERVER.  This requires that the SSH keys be provisioned\n    #       in advanced, and strict mode be disabled for both the SSH\n    #       server and client.\n    #\n\n    LogMsg \"Info: Running Ubuntu Config on client VM.\"\n    LogMsg \"Checking if memcached is installed or not..\"\n    memcslapInstalled=`which memcslap`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing memcslap\"\n        apt-get -y install libmemcached-tools\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install memcslap\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi        \n        LogMsg \"memcslap installed on client.\"\n    fi\n    arr=$(echo $MC_SERVERS | tr \",\" \"\\n\")    \n    for MCS in $arr\n    do\n        currentServer=${MCS/:11211/}\n\t\tLogMsg \"Info: -----------------------------------------\"\n\t\tLogMsg \"Info: memcached server installation on server ${currentServer}\"\n\t\tssh root@${currentServer} \"apt-get install -y memcached\"\n        ssh root@${currentServer} \"sed --in-place -e 's/-l 127.0.0.1//g' /etc/memcached.conf\"\n        ssh root@${currentServer} \"service memcached restart\"\n        if [ $? -ne 0 ]; then\n            msg=\"Error: Unable to install package to server ${currentServer}\"\n            LogMsg \"${msg}\"\n            echo \"${msg}\" >> ./summary.log\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n        LogMsg \"Info: memcached Server started successfully on ${currentServer}\"\n\n    done\n}\n\nConfigRHELMemC()\n{\n    LogMsg \"Info: Running CENTOS/RHEL Config on client VM.\"\n    LogMsg \"Checking if memcached is installed or not..\"\n    memslap --help > /dev/null\n    if [ $? -ne 0 ]; then\n        LogMsg \"Installing memslap\"\n        yum install -y libmemcached\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install memcslap\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi        \n        LogMsg \"memslap installed on client.\"\n    fi\n    arr=$(echo $MC_SERVERS | tr \",\" \"\\n\")    \n    for MCS in $arr\n    do\n        currentServer=${MCS/:11211/}\n\t\tLogMsg \"Info: -----------------------------------------\"\n\t\tLogMsg \"Info: memcached server installation on server ${currentServer}\"\n\t\tssh root@${currentServer} \"yum install -y memcached\"\n        ssh root@${currentServer} \"service memcached restart\"\n        if [ $? -ne 0 ]; then\n            msg=\"Error: Unable to install package to server ${currentServer}\"\n            LogMsg \"${msg}\"\n            echo \"${msg}\" >> ./summary.log\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n        LogMsg \"Info: memcached Server started successfully on ${currentServer}\"\n\n    done\n}\n\nConfigRHELMemSlap()\n{\n    #\n    # Note: MemSlap is client for memcached to benchmark memcached server. \n    #        This is long running client so far.\n    #\n\n    LogMsg \"Info: Running RHEL\"    \n    LogMsg \"Info: -----------------------------------------\"\n    LogMsg \"Info: memslap installation\"\n    LogMsg \"Info: Installing required packages first\"\n    yum install -y wget gcc make gcc-c++\n    if [ $? -ne 0 ]; then\n        msg=\"Error: Unable to install client packages\"\n        LogMsg \"${msg}\"\n        echo \"${msg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n    \n    LogMsg \"Info: Download memslap package\"\n    pkg=(`ssh root@${SERVER} \"ls /root/ | grep ${MEMSLAP_VERSION}\"`)\n    echo $pkg\n    if [ -z \"$pkg\" ]; then\n        LogMsg \"Downloading memslap package ${MEMSLAP_VERSION}\"\n        #exit 1    \n            wget https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz\n            if [ $? -ne 0 ]; then\n                    msg=\"Error: Unable to download memslap package\"\n                    LogMsg \"${msg}\"\n                    echo \"${msg}\" >> ./summary.log\n                    UpdateTestState $ICA_TESTFAILED\n                    exit 1\n            fi    \n    fi\n\n    LogMsg \"Info: Untar and Config ZK server\"\n    tar -xvzf libmemcached-1.0.18.tar.gz\n    cd libmemcached-1.0.18/\n    ./configure\n    make \n    make install\n    \n    if [ $? -ne 0 ]; then\n                msg=\"Error: Unable install memslap\"\n                LogMsg \"${msg}\"\n                echo \"${msg}\" >> ./summary.log\n                UpdateTestState $ICA_TESTFAILED\n                exit 1\n        fi\n    LogMsg \"Info: memslap client setup successfully\"\n}\n\n#######################################################################\n#\n# Main script body\n#\n#######################################################################\n\ncd ~\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Starting test\"\n\n#\n# Delete any old summary.log file\n#\nLogMsg \"Cleaning up old summary.log\"\nif [ -e ~/summary.log ]; then\n    rm -f ~/summary.log\nfi\n\ntouch ~/summary.log\n\n#\n# Source the constants.sh file\n#\nLogMsg \"Sourcing constants.sh\"\nif [ -e ~/constants.sh ]; then\n    . ~/constants.sh\nelse\n    msg=\"Error: ~/constants.sh does not exist\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\n#\n# Make sure the required test parameters are defined\n#\n\nif [ \"${MC_VERSION:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the MC_VERSION test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 20\nfi\n\nif [ \"${MC_SERVERS:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the MC_SERVER test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 20\nfi\n\nif [ \"${MC_CONCURRENCY:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the MC_CONCURRENCY test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    MC_CONCURRENCY=100\nfi\n\nif [ \"${MC_EXECUTE_NUMBER:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the MC_EXECUTE_NUMBER test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    MC_EXECUTE_NUMBER=10000\nfi\n\nif [ \"${MC_INITIAL_LOAD:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the MC_INITIAL_LOAD test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    MC_INITIAL_LOAD=10000\nfi\n\nLogMsg \"Info: Test run parameters\"\necho \"MC_VERSION        = ${MC_VERSION}\"\necho \"MC_SERVERS        = ${MC_SERVERS}\"\necho \"MC_CONCURRENCY    = ${MC_CONCURRENCY}\"\necho \"MC_EXECUTE_NUMBER = ${MC_EXECUTE_NUMBER}\"\necho \"MC_INITIAL_LOAD   = ${MC_INITIAL_LOAD}\"\n\n#\n# Configure MC server - this has distro specific behaviour\n#\ndistro=`LinuxRelease`\ncase $distro in\n    \"CENTOS\" | \"RHEL\")\n        ConfigRHELMemC\n\t\ttestString=\"memslap --servers=${MC_SERVERS} --concurrency=${MC_CONCURRENCY} --execute-number=${MC_EXECUTE_NUMBER} --initial-load=${MC_INITIAL_LOAD} --flush\"\n    ;;\n    \"UBUNTU\")\n        ConfigUbuntuMemC\n\t\ttestString=\"memcslap --servers=${MC_SERVERS} --concurrency=${MC_CONCURRENCY} --execute-number=${MC_EXECUTE_NUMBER} --initial-load=${MC_INITIAL_LOAD} --flush\"\n    ;;\n    \"DEBIAN\")\n\t\tLogMsg \"Debian distro not yet supported\"\n        #ConfigDebianMemC\n    ;;\n    \"SLES\")\n\t\tLogMsg \"SLES distro not yet supported\"\n        #ConfigSlesMemC        \n    ;;\n     *)\n        msg=\"Error: Distro '${distro}' not supported\"\n        LogMsg \"${msg}\"\n        echo \"${msg}\" >> ~/summary.log\n        UpdateTestState \"TestAborted\"\n        exit 1\n    ;; \nesac\n\nLogMsg \"Running memslap tests with cmd: ${testString}\"\neval $testString\nif [ $? -ne 0 ]; then\n    msg=\"Error: Error in running tests\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ./summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\n#\n# If we made it here, everything worked.\n# Indicate success\n#\nLogMsg \"Test completed successfully\"\nUpdateTestState $ICA_TESTCOMPLETED\n\nexit 0", "num_lines": 359}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# performance_md.sh\n#\n# Description:\n#    Install and configure mongodb so the mongoperf benchmark can\n#    be run.  This script needs to be run on single VM.\n#\n#    mongo perf needs Java runtime is also installed.\n#\n#    Installing and configuring Hadoop consists of the following\n#    steps:\n#\n#     1. Install a Java JDK\n#     2. Download the MongoDB tar.gz archive\n#     3. Unpackage the Mongo archive\n#     4. Move the mongo directory to /usr/bin/\n#     5. Update the ~/.bashrc file with mongodb specific exports\n#     8. Start mongoperf test\n#######################################################################\n\n\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\nCONSTANTS_FILE=\"/root/constants.sh\"\nSUMMARY_LOG=~/summary.log\n\nMONGODB_VERSION=\"2.4.0\"\nMONGODB_ARCHIVE=\"mongodb-${MONGODB_VERSION}.tar.gz\"\nMONGODB_URL=\"http://apache.cs.utah.edu/mongodb/common/mongodb-${MONGODB_VERSION}/${MONGODB_ARCHIVE}\"\n\nMONGODB_URL=\"https://archive.apache.org/dist/mongodb/core/mongodb-${MONGODB_VERSION}/${MONGODB_ARCHIVE}\"\nCONFIG_SCRIPT=\"/root/perf_mongodbterasort.sh\"\n\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/mongodb.log\n}\n\n\n#######################################################################\n#\n# UpdateTestState()\n#\n#######################################################################\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\n\n#######################################################################\n#\n# UpdateSummary()\n#\n#######################################################################\nUpdateSummary()\n{\n    echo \"${1}\" >> ~/summary.log\n}\n\n\n#######################################################################\n#\n# TimeToSeconds()\n#\n#######################################################################\nTimeToSeconds()\n{\n    read -r h m s <<< $(echo $1 | tr ':' ' ')\n    #echo $(((h*60*60)+(m*60)+s))\n    echo `echo \"${h}*60*60+${m}*60+${s}\" | bc`\n}\n\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\n\n#######################################################################\n#\n# ConfigRhel()\n#\n#######################################################################\nConfigRhel()\n{\n    LogMsg \"ConfigRhel\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        yum -y install java-1.7.0-openjdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install Java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\t\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    LogMsg \"Create JAVA_HOME variable\"\n\n    javaConfig=`echo \"\" | update-alternatives --config java | grep \"*\"`\n    tokens=( $javaConfig )\n    javaPath=${tokens[2]}\n    if [ ! -e $javaPath ]; then\n        LogMsg \"Error: Unable to find the Java install path\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp=`dirname $javaPath`\n    JAVA_HOME=`dirname $temp`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # This is a hack so we can use the same mongodb config on all Linux\n    # distros.  With RHEL, localhost fails.  By setting the hostname\n    # to localhost, then the default config works in RHEL.\n    # Need to revisit this to find a better solution.\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigSles()\n#\n#######################################################################\nConfigSles()\n{\n    LogMsg \"ConfigSles\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        zypper --non-interactive install jre-1.7.0\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    JAVA_HOME=`dirname $temp1`\n\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # Depending on how the user configs the SLES system, we may or may not\n    # need the following workaround to allow mongodb to use localhost\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigUbuntu()\n#\n#######################################################################\nConfigUbuntu()\n{\n    LogMsg \"ConfigUbuntu\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        apt-get -y install default-jdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    temp2=`dirname $temp1`\n    JAVA_HOME=`dirname $temp2`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n}\n\n#######################################################################\n#\n# Main script body\n#\n#######################################################################\n\ncd ~\n\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Updated test case state to running\"\n\nrm -f ~/summary.log\ntouch ~/summary.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${MONGODB_VERSION} ]; then\n    MONGODB_VERSION=3.2.3\n\terrMsg=\"The MONGODB_VERSION test parameter is not defined. Setting as ${MONGODB_VERSION} \"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\nfi\n\nif [ ! ${nThreads} ]; then\n    nThreads=16\n\tLogMsg \"Info : nThreads not defined in constants.sh. Setting as ${nThreads}\"\n    \nfi\nif [ ! ${fileSizeMB} ]; then\n    fileSizeMB=1000\n\tLogMsg \"Info : fileSizeMB not defined in constants.sh. Setting as ${fileSizeMB}\"\nfi\nif [ ! ${readTest} ]; then\n    readTest=true\n    LogMsg \"Info : readTest not defined in constants.sh. Setting as ${readTest}\"\nfi\nif [ ! ${writeTest} ]; then\n    writeTest=true\n    LogMsg \"Info : writeTest not defined in constants.sh. Setting as ${writeTest}\"\nfi\nif [ ! ${recSizeKB} ]; then\n    recSizeKB=8\n    LogMsg \"Info : recSizeKB not defined in constants.sh. Setting as ${recSizeKB}\"\nfi\nif [ ! ${testDurationSeconds} ]; then\n    testDurationSeconds=60\n    LogMsg \"Info : testDurationSeconds not defined in constants.sh. Setting as ${testDurationSeconds}\"\nfi\n\nLogMsg \"Info : MONGODB_VERSION = ${MONGODB_VERSION}\"\nMONGODB_ARCHIVE=\"mongodb-linux-x86_64-${MONGODB_VERSION}.tgz\"\nMONGODB_URL=\"https://fastdl.mongodb.org/linux/${MONGODB_ARCHIVE}\"\nLogMsg \"Info : nThreads = ${nThreads}\"\nLogMsg \"Info : fileSizeMB = ${fileSizeMB}\"\nLogMsg \"Info : readTest = ${readTest}\"\nLogMsg \"Info : writeTest = ${writeTest}\"\nLogMsg \"Info : recSizeKB = ${recSizeKB}\"\nLogMsg \"Info : testDurationSeconds = ${testDurationSeconds}\"\n\n#\n# Install Java\n#\ndistro=`LinuxRelease`\ncase $distro in\n    \"CENTOS\" | \"RHEL\")\n        ConfigRhel\n    ;;\n    \"UBUNTU\")\n        ConfigUbuntu\n    ;;\n    \"DEBIAN\")\n        LogMsg \"Debian is not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \"  Distro '${distro}' is not currently supported\"\n        exit 1\n    ;;\n    \"SLES\")\n        ConfigSles\n    ;;\n     *)\n        LogMsg \"Distro '${distro}' not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \" Distro '${distro}' not supported\"\n        exit 1\n    ;; \nesac\n\n#\n# Download Hadoop\n#\nLogMsg \"Downloading MangoDB if we do not have a local copy\"\n\nif [ ! -e \"/root/${MONGODB_ARCHIVE}\" ]; then\n    LogMsg \"Downloading Hadoop from ${MONGODB_URL}\"\n    wget \"${MONGODB_URL}\"\n    if [ $? -ne 0 ]; then\n        LogMsg \"Error: Unable to download mongodb from ${MONGODB_URL}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    LogMsg \"MangoDB successfully downloaded\"\nfi\n\n#\n# Untar and install Hadoop\n#\nLogMsg \"Extracting the mongodb archive\"\n\ntar -zxvf ./${MONGODB_ARCHIVE}\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to extract mongodb from its archive\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi    \n\nif [ ! -e \"/root/mongodb-linux-x86_64-${MONGODB_VERSION}\" ]; then\n    LogMsg \"Error: The expected mongodb directory '/root/mongodb-linux-x86_64-${MONGODB_VERSION}' was not created when extracting mongodb\"\n    UpdateTestState $sICA_TESTFAILED\n    exit 1\nfi\n\n#\n# Move the mongodb directory to where it should be\n#\nLogMsg \"Move the mongodb directory to /usr/local/mongodb\"\n\nif [ -e /usr/local/mongodb ]; then\n    rm -rf /usr/local/mongodb\nfi\n\nmv \"/root/mongodb-linux-x86_64-${MONGODB_VERSION}\" /usr/local/mongodb\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to move mongodb to the /usr/local/mongodb directory\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Check if MangoDB specific exports are in the .bashrc file\"\n\ngrep -q \"mangodb exports start\" ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"Hadoop exports not found in ~/.bashrc, adding them\"\n    echo \"\" >> ~/.bashrc\n    echo \"# mango exports start\" >> ~/.bashrc\n    echo \"export JAVA_HOME=${JAVA_HOME}\" >> ~/.bashrc\n    echo \"export MONGODB_INSTALL=/usr/local/mongodb\" >> ~/.bashrc\n    echo \"export PATH=\\$PATH:\\$MONGODB_INSTALL/bin\" >> ~/.bashrc\n    echo \"# MangoDB exports end\" >> ~/.bashrc\nfi\n\n#\n# Sourcing the update .bashrc\n#\nsource ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to source .bashrc\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\n#  {\n#    nThreads:8,\n#    fileSizeMB:128,\n#    r:true,\n#    w:false,\n#    recSizeKB:8\n#  }\n\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to mongoperfConfigJSON\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\n#LogMsg \"run mongoperf.\"\n\n#\n# Update the configuration in core-site.xml\n#\nLogMsg \"Updating mongoperfConfigJSON for Write test\"\n\necho \"{\" > ./mongoperfConfigJSON\necho \"    nThreads:${nThreads},\" >> ./mongoperfConfigJSON\necho \"    fileSizeMB:${fileSizeMB},\" >> ./mongoperfConfigJSON\necho \"    r:false,\" >> ./mongoperfConfigJSON\necho \"    w:true,\" >> ./mongoperfConfigJSON\necho \"    recSizeKB:${recSizeKB}\" >> ./mongoperfConfigJSON\necho \"}\" >> ./mongoperfConfigJSON\n\nLogMsg \"Info : Run mongoperf for Write test...\"\n\ntimeout ${testDurationSeconds} /usr/local/mongodb/bin/mongoperf < mongoperfConfigJSON \nif [ $? -ne 124 ]; then\n\tmsg=\"Error: Unable to run mongoperf test data\"\n\tLogMsg \"${msg}\"\n\techo \"${msg}\" >> ~/summary.log\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\n\n#LogMsg \"run mongoperf.\"\n\n#\n# Update the configuration in core-site.xml\n#\nLogMsg \"Updating mongoperfConfigJSON for read test\"\n\necho \"{\" > ./mongoperfConfigJSON\necho \"    nThreads:${nThreads},\" >> ./mongoperfConfigJSON\necho \"    fileSizeMB:${fileSizeMB},\" >> ./mongoperfConfigJSON\necho \"    r:true,\" >> ./mongoperfConfigJSON\necho \"    w:false,\" >> ./mongoperfConfigJSON\necho \"    recSizeKB:${recSizeKB}\" >> ./mongoperfConfigJSON\necho \"}\" >> ./mongoperfConfigJSON\n\nLogMsg \"Info : Run mongoperf for read test...\"\n\ntimeout ${testDurationSeconds} /usr/local/mongodb/bin/mongoperf < mongoperfConfigJSON\nif [ $? -ne 124 ]; then\n        msg=\"Error: Unable to run mongoperf test data\"\n        LogMsg \"${msg}\"\n        echo \"${msg}\" >> ~/summary.log\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\nfi\n\n#LogMsg \"run mongoperf.\"\n#\n# Update the configuration in core-site.xml\n#\nLogMsg \"Updating mongoperfConfigJSON for ReadWrite test\"\n\necho \"{\" > ./mongoperfConfigJSON\necho \"    nThreads:${nThreads},\" >> ./mongoperfConfigJSON\necho \"    fileSizeMB:${fileSizeMB},\" >> ./mongoperfConfigJSON\necho \"    r:${readTest},\" >> ./mongoperfConfigJSON\necho \"    w:${writeTest},\" >> ./mongoperfConfigJSON\necho \"    recSizeKB:${recSizeKB}\" >> ./mongoperfConfigJSON\necho \"}\" >> ./mongoperfConfigJSON\n\nLogMsg \"Info : Run mongoperf  for ReadWrite test...\"\n\ntimeout ${testDurationSeconds} /usr/local/mongodb/bin/mongoperf < mongoperfConfigJSON\nif [ $? -ne 124 ]; then\n        msg=\"Error: Unable to run mongoperf test data\"\n        LogMsg \"${msg}\"\n        echo \"${msg}\" >> ~/summary.log\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\nfi\n\n#\n# If we made it here, everything worked.\n#\nUpdateTestState $ICA_TESTCOMPLETED\nexit 0", "num_lines": 562}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# performance_middleware_fio.sh\n#\n# Description:\n#    Install fio so the fio benchmark can\n#    be run.  This script needs to be run on single VM.\n#\n#    steps:\n#\n#     1. Install a fio\n#     2. Start fio benchmark test on given disk\n#\n# Author: Sivakanth\n# Email: v-sirebb@microsoft.com\n#######################################################################\n\n\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\nCONSTANTS_FILE=\"constants.sh\"\nSUMMARY_LOG=~/summary.log\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/Fio.log\n}\n\n\n#######################################################################\n#\n# UpdateTestState()\n#\n#######################################################################\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\n\n#######################################################################\n#\n# UpdateSummary()\n#\n#######################################################################\nUpdateSummary()\n{\n    echo \"${1}\" >> ~/summary.log\n}\n\n\n#######################################################################\n#\n# TimeToSeconds()\n#\n#######################################################################\nTimeToSeconds()\n{\n    read -r h m s <<< $(echo $1 | tr ':' ' ')\n    #echo $(((h*60*60)+(m*60)+s))\n    echo `echo \"${h}*60*60+${m}*60+${s}\" | bc`\n}\n\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\nset -u\nset -x\n\nRunFIO()\n{\n\ttestfilesize=${testfilesize}\n\tFILEIO=\"--size=$testfilesize --direct=1 --ioengine=libaio --filename=fiodata --overwrite=1  \"\n\n\t####################################\n\t#All run config set here\n\t#\n\n\t#Log Config\n\t\n\tmkdir -p  $HOMEDIR/FIOLog/jsonLog\n\tmkdir -p  $HOMEDIR/FIOLog/iostatLog\n\tmkdir -p  $HOMEDIR/FIOLog/sarLog\n\tmkdir -p  $HOMEDIR/FIOLog/vmstatLog\n\tmkdir -p  $HOMEDIR/FIOLog/blktraceLog\n\n\t#LOGDIR=\"${HOMEDIR}/FIOLog\"\n\tJSONFILELOG=\"${LOGDIR}/jsonLog\"\n\tIOSTATLOGDIR=\"${LOGDIR}/iostatLog\"\n\tVMSTATLOGDIR=\"${LOGDIR}/vmstatLog\"\n\tSAROGDIR=\"${LOGDIR}/sarLog\"\n\tBLKTRACELOGDIR=\"${LOGDIR}/blktraceLog\"\n\tLOGFILE=\"${LOGDIR}/fio-test.log.txt\"\t\n\n\t#redirect blktrace files directory\n\tResource_mount=$(mount -l | grep /sdb1 | awk '{print$3}')\n\tblk_base=\"${Resource_mount}/blk-$(date +\"%m%d%Y-%H%M%S\")\"\n\tmkdir $blk_base\n\t#\n\t#\n\t#Test config\n\t#\n\t#\n\n\t#All possible values for file-test-mode are randread randwrite read write\n\t\n\titeration=0\n\tnumjobs=1\n\ttestmodes=${testmodes}\n\tioSize=${ioSizes}\n\tioDepth=${ioDepths}\n\tioruntime=${ioruntime}\n\n\t####################################\n\techo \"Test log created at: ${LOGFILE}\"\n\tLogMsg \"===================================== Starting Run $(date +\"%x %r %Z\") ================================\"\n\techo \"===================================== Starting Run $(date +\"%x %r %Z\") ================================\" >> $LOGFILE\n\n\tchmod 666 $LOGFILE\n\tLogMsg \"Preparing Files: $FILEIO\"\n\techo \"Preparing Files: $FILEIO\" >> $LOGFILE\n\t# Remove any old files from prior runs (to be safe), then prepare a set of new files.\n\trm fiodata\n\tLogMsg \"--- Kernel Version Information ---\"\n\techo \"--- Kernel Version Information ---\" >> $LOGFILE\n\tuname -a >> $LOGFILE\n\tcat /proc/version >> $LOGFILE\n\tcat /etc/*-release >> $LOGFILE\n\techo \"--- PCI Bus Information ---\" >> $LOGFILE\n\tlspci >> $LOGFILE\n\techo \"--- Drive Mounting Information ---\" >> $LOGFILE\n\tmount >> $LOGFILE\n\techo \"--- Disk Usage Before Generating New Files ---\" >> $LOGFILE\n\tdf -h >> $LOGFILE\n\tfio --cpuclock-test >> $LOGFILE\n\tfio $FILEIO --readwrite=read --bs=1M --runtime=1 --iodepth=128 --numjobs=8 --name=prepare >> $LOGFILE\n\techo \"--- Disk Usage After Generating New Files ---\" >> $LOGFILE\n\tdf -h >> $LOGFILE\n\techo \"=== End Preparation  $(date +\"%x %r %Z\") ===\" >> $LOGFILE\n\n\t####################################\n\t#Trigger run from here\n\tfor testmode in $testmodes; do\n\t\tfor ioSize in $ioSizes; do\n\t\t\tfor ioDepth in $ioDepths; do\n\t\t\t\tif [ $ioDepth -ge 8 ]\n\t\t\t\tthen\n\t\t\t\t\tnumjobs=8\n\t\t\t\telse\n\t\t\t\t\tnumjobs=$ioDepth\n\t\t\t\tfi\n\t\t\t\tiostatfilename=\"${IOSTATLOGDIR}/iostat-fio-${testmode}-${ioSize}K-${ioDepth}td.txt\"\n\t\t\t\tnohup iostat -x $ioruntime -t -y > $iostatfilename &\n\t\t\t\tiostatPID=$!\n\t\t\t\tsarfilename=\"${SAROGDIR}/sar-fio-${testmode}-${ioSize}K-${ioDepth}td.txt\"\n\t\t\t\tnohup sar -n DEV 1 $ioruntime 2>&1 > $sarfilename & \n\t\t\t\tsarPID=$!\n\t\t\t\tvmstatfilename=\"${VMSTATLOGDIR}/vmstat-fio-${testmode}-${ioSize}K-${ioDepth}td.txt\"\n\t\t\t\tnohup vmstat 1 $ioruntime 2>&1 > $vmstatfilename & \n\t\t\t\tvmstatPID=$!\t\t\t\n\t\t\t\techo \"-- iteration ${iteration} ----------------------------- ${testmode} test, ${ioSize}K bs, ${ioDepth} threads, ${numjobs} jobs, $ioruntime seconds ------------------ $(date +\"%x %r %Z\") ---\" >> $LOGFILE\n\t\t\t\tjsonfilename=\"${JSONFILELOG}/fio-result-${testmode}-${ioSize}K-${ioDepth}td.json\"\n\t\t\t\tfio $FILEIO --readwrite=$testmode --bs=${ioSize}K --runtime=$ioruntime --iodepth=$ioDepth --numjobs=$numjobs --output-format=json --output=$jsonfilename --name=\"iteration\"${iteration} >> $LOGFILE\n\t\t\t\tkill -9 $iostatPID $sarPID $vmstatPID\t\t\n\t\t\t\titeration=$(( iteration+1 ))\n\t\t\tdone\n\t\tdone\n\tdone\n\t####################################\n\techo \"===================================== Completed Run $(date +\"%x %r %Z\") ================================\" >> $LOGFILE\n\trm fiodata\n\techo \"Test logs are located at ${LOGDIR}\"\n}\n\nConfigCentOS7()\n{\t\t\t\n\tfioCentOS7pkg=\"fio-2.1.10-1.el7.rf.x86_64.rpm\"\n\tLogMsg \"INFO: CentOS7: installing required packages\"\n\tyum install -y wget sysstat mdadm blktrace\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to install wget tar sysstat mdadm blktrace\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tmount -t debugfs none /sys/kernel/debug\n\t\n\tinstalled=`which fio`\n\tif [ ! $installed ]; then\n        LogMsg \"INFO: Installing fio\"\n\n\t\tfiolPkg=$(ls | grep ${fioCentOS7pkg})\n\t\tif [ -z \"$fiolPkg\" ]; then\n\t\t\twget \"http://pkgs.repoforge.org/fio/${fioCentOS7pkg}\"\n\t\tfi\n\t\tyum install -y ${fioCentOS7pkg}\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"Error: Unable to install fio\"\n\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\texit 1\n\t\tfi\n    fi\t\n}\n\nConfigCentOS6()\n{\t\t\t\n\tfioCentOS6pkg=\"fio-2.1.10-1.el6.rf.x86_64.rpm\"\n\tLogMsg \"INFO: CentOS6: installing required packages\"\n\tyum install -y wget sysstat mdadm blktrace\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to install wget tar sysstat mdadm blktrace\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tmount -t debugfs none /sys/kernel/debug\n\t\n\tinstalled=`which fio`\n\tif [ ! $installed ]; then\n        LogMsg \"INFO: Installing fio\"\n\n\t\tfiolPkg=$(ls | grep ${fioCentOS6pkg})\n\t\tif [ -z \"$fiolPkg\" ]; then\t\t\t\n\t\t\twget \"http://pkgs.repoforge.org/fio/${fioCentOS6pkg}\"\n\t\tfi\n\t\tyum install -y libibverbs.x86_64\n\t\tyum install -y ${fioCentOS6pkg}\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"Error: Unable to install fio\"\n\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\texit 1\n\t\tfi\n    fi\t\n}\n\nConfigUbuntu()\n{\n\tLogMsg \"INFO: Ubuntu installing required packages\"\n\t\n\tapt-get update -y\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to apt-get update\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tapt-get install -y wget tar sysstat blktrace\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to install wget tar sysstat mdadm blktrace\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tmount -t debugfs none /sys/kernel/debug\n\t\n\tinstalled=`which fio`\n\tif [ ! $installed ]; then\n        LogMsg \"INFO: Installing fio\"\n\n\t\tapt-get install -y fio ;\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"Error: Unable to install fio\"\n\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\texit 1\n\t\tfi\n    fi\n}\n\nConfigSLES()\n{\n\tfioCentOS6pkg=\"fio-2.1.2-2.1.3.x86_64.rpm\"\n\tLogMsg \"INFO: SLES: installing required packages\"\n\tzypper --non-interactive install wget sysstat mdadm blktrace\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to install wget tar sysstat mdadm blktrace\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tmount -t debugfs none /sys/kernel/debug\n\t\n\tinstalled=`which fio`\n\tif [ ! $installed ]; then\n        LogMsg \"INFO: Installing fio\"\n\n\t\tfiolPkg=$(ls | grep ${fioCentOS6pkg})\n\t\tif [ -z \"$fiolPkg\" ]; then\t\t\t\n\t\t\twget \"ftp://195.220.108.108/linux/opensuse/distribution/13.1/repo/oss/suse/x86_64/${fioCentOS6pkg}\"\n\t\tfi\t\t\n\t\t(echo i;) | zypper --non-interactive install ${fioCentOS6pkg}\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"Error: Unable to install fio\"\n\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\texit 1\n\t\tfi\n    fi\t\n}\n\nCreateRAID0()\n{\t\n\tdisks=$(ls -l /dev | grep sd[c-z]$ | awk '{print $10}')\n\t#disks=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\t\n\tLogMsg \"INFO: Check and remove RAID first\"\n\tmdvol=$(cat /proc/mdstat | grep \"active raid\" | awk {'print $1'})\n\tif [ -n \"$mdvol\" ]; then\n\t\techo \"/dev/${mdvol} already exist...removing first\"\n\t\tumount /dev/${mdvol}\n\t\tmdadm --stop /dev/${mdvol}\n\t\tmdadm --remove /dev/${mdvol}\n\t\tmdadm --zero-superblock /dev/sd[c-z][1-5]\n\tfi\n\t\n\tLogMsg \"INFO: Creating Partition\"\n\tcount=0\n\tfor disk in ${disks}\n\tdo\t\t\n\t\techo \"formatting disk /dev/${disk}\"\n\t\t(echo d; echo n; echo p; echo 1; echo; echo; echo t; echo fd; echo w;) | fdisk /dev/${disk}\n\t\tcount=$(( $count + 1 )) \n\tdone\n\t\n\tLogMsg \"INFO: Creating RAID\"\n\tmdadm --create ${mdVolume} --level 0 --raid-devices ${count} /dev/sd[c-z][1-5]\n\ttime mkfs -y $1 -F ${mdVolume}\n\tmkdir ${mountDir}\n\tmount -o nobarrier ${mdVolume} ${mountDir}\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to create raid\"\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\t\n\t#LogMsg \"INFO: adding fstab entry\"\n\t#echo \"${mdVolume}\t${mountDir}\text4\tdefaults\t1 1\" >> /etc/fstab\n}\n\nCreateLVM()\n{\t\n\tdisks=$(ls -l /dev | grep sd[c-z]$ | awk '{print $10}')\n\t#disks=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\t\n\t#LogMsg \"INFO: Check and remove LVM first\"\n\tvgExist=$(vgdisplay)\n\tif [ -n \"$vgExist\" ]; then\n\t\tumount ${mountDir}\n\t\tlvremove -A n -f /dev/${vggroup}/lv1\n\t\tvgremove ${vggroup} -f\n\tfi\n\t\n\tLogMsg \"INFO: Creating Partition\"\n\tcount=0\n\tfor disk in ${disks}\n\tdo\t\t\n\t\techo \"formatting disk /dev/${disk}\"\n\t\t(echo d; echo n; echo p; echo 1; echo; echo; echo t; echo fd; echo w;) | fdisk /dev/${disk}\n\t\tcount=$(( $count + 1 )) \n\tdone\n\t\n\tLogMsg \"INFO: Creating LVM with all data disks\"\n\tpvcreate /dev/sd[c-z][1-5]\n\tvgcreate ${vggroup} /dev/sd[c-z][1-5]\n\tlvcreate -l 100%FREE -i 12 -I 64 ${vggroup} -n lv1\n\ttime mkfs -t $1 -F /dev/${vggroup}/lv1\n\tmkdir ${mountDir}\n\tmount -o nobarrier /dev/${vggroup}/lv1 ${mountDir}\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"Error: Unable to create LVM \" \n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\t\n\t#LogMsg \"INFO: adding fstab entry\"\n\t#echo \"${mdVolume}\t${mountDir}\text4\tdefaults\t1 1\" >> /etc/fstab\n}\n\n############################################################\n#\tMain body\n############################################################\n\n#cd ~\n\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Updated test case state to running\"\n\nrm -f ~/summary.log\ntouch ~/summary.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nHOMEDIR=$HOME\nmv $HOMEDIR/FIOLog/ $HOMEDIR/FIOLog-$(date +\"%m%d%Y-%H%M%S\")/\nmkdir -p $HOMEDIR/FIOLog\nLOGDIR=\"${HOMEDIR}/FIOLog\"\ntouch ${LOGDIR}/fio-test.log.txt\n#mdVolume=\"/dev/md1\"\n#vggroup=\"vg1\"\nmountDir=\"/sdc1mnt/fio\"\ntestdisk=${testdisk}\necho \"Disk for FIO benchmark test $testdisk\" && (echo n; echo p; echo 1; echo; echo; echo t; echo 83; echo w;) | fdisk $testdisk && time mkfs.ext4 ${testdisk}1 && echo \"${testdisk}1 disk format: Success\" && mkdir -p $mountDir && mount -o nobarrier ${testdisk}1 $mountDir && echo \"${testdisk}1 disk mount: Success on $mountDir\"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Disk for FIO benchmark test $testdisk: FAILED\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 1\nfi\nLogMsg \"Disk for FIO benchmark test $testdisk is mounted on $mountDir: Success\"\n\ncd ${HOMEDIR}\n\nDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\ncase $DISTRO in\n\tUbuntu*)\n\t\techo \"UBUNTU\"\n\t\tConfigUbuntu\n\t\t;;\n\tFedora*)\n\t\techo \"FEDORA\";;\n\t*release*7.*)\n\t\techo \"CENTOS 7.*\"\n\t\tConfigCentOS7\n\t\t;;\n\t*release*6.*)\n\t\techo \"CENTOS 6.*\"\n\t\tConfigCentOS6\n\t\t;;\n\t*SUSE*)\n\t\techo \"SLES\"\n\t\tConfigSLES\n\t\t;;\n\tRed*Hat*)\n\t\techo \"RHEL\";;\n\tDebian*)\n\t\techo \"DEBIAN\";;\nesac\n#Creating RAID before triggering test\n#CreateRAID0 ext4\n#CreateLVM ext4\n\n#Run test from here\nLogMsg \"*********INFO: Starting test execution*********\"\ncd ${mountDir}\nmkdir sampleDIR\nRunFIO\nif [ $? -ne 0 ]; then\n\tLogMsg \"Error: FIO run: FAILED\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\nLogMsg \"*********INFO: Script execution reach END. Completed !!!*********\"\nUpdateTestState $ICA_TESTCOMPLETED\nexit 0", "num_lines": 513}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# performance_mongodb.sh\n#\n# Description:\n#    Install and configure mongodb so the ycsb benchmark can\n#    be run.  This script needs to be run on single VM.\n#\n#    mongo perf needs Java runtime is also installed.\n#\n#    Installing and configuring Hadoop consists of the following\n#    steps:\n#\n#     1. Install a Java JDK\n#     2. Download the MongoDB tar.gz archive\n#     3. Unpackage the Mongo archive\n#     4. Move the mongo directory to /usr/bin/\n#     5. Update the ~/.bashrc file with mongodb specific exports\n#     8. Start ycsb test\n#######################################################################\n\n\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\nCONSTANTS_FILE=\"/root/constants.sh\"\nSUMMARY_LOG=~/summary.log\n\nMONGODB_VERSION=\"2.4.0\"\nMONGODB_ARCHIVE=\"mongodb-linux-x86_64-${MONGODB_VERSION}.tgz\"\nMONGODB_URL=\"http://fastdl.mongodb.org/linux/${MONGODB_ARCHIVE}\"\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/mongodb.log\n}\n\n\n#######################################################################\n#\n# UpdateTestState()\n#\n#######################################################################\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\n\n#######################################################################\n#\n# UpdateSummary()\n#\n#######################################################################\nUpdateSummary()\n{\n    echo \"${1}\" >> ~/summary.log\n}\n\n\n#######################################################################\n#\n# TimeToSeconds()\n#\n#######################################################################\nTimeToSeconds()\n{\n    read -r h m s <<< $(echo $1 | tr ':' ' ')\n    #echo $(((h*60*60)+(m*60)+s))\n    echo `echo \"${h}*60*60+${m}*60+${s}\" | bc`\n}\n\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        *Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\n\n#######################################################################\n#\n# ConfigRhel()\n#\n#######################################################################\nConfigRhel()\n{\n    LogMsg \"ConfigRhel\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        yum -y install java-1.7.0-openjdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install Java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"yum -y install java-1.7.0-openjdk\"\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    LogMsg \"Create JAVA_HOME variable\"\n\n    javaConfig=`echo \"\" | update-alternatives --config java | grep \"*\"`\n    tokens=( $javaConfig )\n    javaPath=${tokens[3]}\n    javaPath2=${javaPath#\"(\"}\n    javaPath2=${javaPath2%\")\"}\n    if [ ! -e $javaPath2 ]; then\n        LogMsg \"Error: Unable to find the Java install path\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp=`dirname $javaPath2`\n    JAVA_HOME=`dirname $temp`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # This is a hack so we can use the same mongodb config on all Linux\n    # distros.  With RHEL, localhost fails.  By setting the hostname\n    # to localhost, then the default config works in RHEL.\n    # Need to revisit this to find a better solution.\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigSles()\n#\n#######################################################################\nConfigSles()\n{\n    LogMsg \"ConfigSles\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        zypper --non-interactive install jre-1.7.0\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"zypper --non-interactive install jre-1.7.0\"\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    JAVA_HOME=`dirname $temp1`\n\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # Depending on how the user configs the SLES system, we may or may not\n    # need the following workaround to allow mongodb to use localhost\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigUbuntu()\n#\n#######################################################################\nConfigUbuntu()\n{\n    LogMsg \"ConfigUbuntu\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n        apt-get update\n        apt-get -y install default-jdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"apt-get update\"\n\tssh root@${MD_SERVER} \"apt-get -y install default-jdk sysstat\"\n\tapt-get -y install default-jdk sysstat\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    temp2=`dirname $temp1`\n    JAVA_HOME=`dirname $temp2`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n}\n\n#######################################################################\n#\n# Main script body\n#\n#######################################################################\n\ncd ~\n\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Updated test case state to running\"\n\nrm -f ~/summary.log\ntouch ~/summary.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${MONGODB_VERSION} ]; then\n\terrMsg=\"The MONGODB_VERSION test parameter is not defined. Setting as ${MONGODB_VERSION} \"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\nfi\n\nif [ ! ${MD_SERVER} ]; then\n    nThreads=16\n\t#nThreads=8\n\tLogMsg \"Info : nThreads not defined in constants.sh. Setting as ${nThreads}\"\nfi\n\n#\n# Install Java\n#\ndistro=`LinuxRelease`\ncase $distro in\n    \"CENTOS\" | \"RHEL\")\n        ConfigRhel\n    ;;\n    \"UBUNTU\")\n        ConfigUbuntu\n    ;;\n    \"DEBIAN\")\n        LogMsg \"Debian is not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \"  Distro '${distro}' is not currently supported\"\n        exit 1\n    ;;\n    \"SLES\")\n        ConfigSles\n    ;;\n     *)\n        LogMsg \"Distro '${distro}' not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \" Distro '${distro}' not supported\"\n        exit 1\n    ;; \nesac\n\n#\n# Download MongoDB to server and start mongodb server.\n#\nLogMsg \"Downloading MangoDB if we do not have a local copy\"\n\nif [ ! -e \"/root/${MONGODB_ARCHIVE}\" ]; then\n    LogMsg \"Downloading Hadoop from ${MONGODB_URL}\"\n    ssh root@${MD_SERVER} \"wget ${MONGODB_URL}\"\n    if [ $? -ne 0 ]; then\n        LogMsg \"Error: Unable to download mongodb from ${MONGODB_URL}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n    LogMsg \"MangoDB successfully downloaded\"\nfi\n\n\t\n\n#\n# Untar and install Hadoop\n#\nLogMsg \"Extracting the mongodb archive\"\n\nssh root@${MD_SERVER} \"tar xfvz mongodb-linux-x86_64-${MONGODB_VERSION}.tgz\"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to extract mongodb from its archive\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi    \n\nLogMsg \"Download YCSB on client VM\"\ncurl -O --location https://github.com/brianfrankcooper/YCSB/releases/download/0.5.0/ycsb-0.5.0.tar.gz\nif [ $? -ne 0 ]; then\n\tLogMsg \"Error: Unable to download YCSB\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\nLogMsg \"Extract YCSB on client VM\"\ntar xfvz ycsb-0.5.0.tar.gz\nif [ $? -ne 0 ]; then\n\tLogMsg \"Error: Unable to download YCSB\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\n\nLogMsg \"Check if MangoDB specific exports are in the .bashrc file\"\n\ngrep -q \"mangodb exports start\" ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"MongoDB exports not found in ~/.bashrc, adding them\"\n    echo \"\" >> ~/.bashrc\n    echo \"# mango exports start\" >> ~/.bashrc\n    echo \"export JAVA_HOME=${JAVA_HOME}\" >> ~/.bashrc\n    echo \"# MangoDB exports end\" >> ~/.bashrc\nfi\n\n#\n# Sourcing the update .bashrc\n#\nsource ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to source .bashrc\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Starting MongoDB on ${MD_SERVER}\"\n\n#Preparing the mounted disk for mongodb test\ndiskName=`ssh root@server-vm fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\"`\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Disk for mongodb benchmark test $diskName: FAILED\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nmountdir=\"/sdc1mnt/mongodb\"\nssh root@server-vm \"echo \"Disk for mongodb benchmark test $diskName\" && (echo n; echo p; echo 1; echo; echo; echo t; echo 83; echo w;) | fdisk $diskName && time mkfs.ext4 ${diskName}1 && echo \"${diskName}1 disk format: Success\" && mkdir -p $mountdir && mount -o nobarrier ${diskName}1 $mountdir && echo \"${diskName}1 disk mount: Success on $mountdir\"  \"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Disk for mongodb benchmark test $diskName: FAILED\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\nLogMsg \"Disk for mongodb benchmark test $diskName is mounted: Success\"\n\nssh root@${MD_SERVER} \"killall mongod\"\nssh root@${MD_SERVER} \"/root/mongodb-linux-x86_64-${MONGODB_VERSION}/bin/mongod --dbpath $mountdir --fork --logpath mongodServerConsole.txt\"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to start mongod server\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Using the asynchronous driver to load the test data\"\necho \"CMD: /root/ycsb-0.5.0/bin/ycsb load mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0\"\n/root/ycsb-0.5.0/bin/ycsb load mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable load the test data\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\nLogMsg \"Using the asynchronous driver to load the test data: Success\"\n\nLogMsg \"Using the asynchronous driver to run the test on /root/run-ycsb.sh ${MD_SERVER}\"\nLogMsg \"ycsb benchmark test run: Success\"\n\nchmod +x /root/run-ycsb.sh\n/root/run-ycsb.sh\n\n#\n# If we made it here, everything worked.\n#\nUpdateTestState $ICA_TESTCOMPLETED\nexit 0", "num_lines": 475}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# performance_mongodb.sh\n#\n# Description:\n#    Install and configure mongodb so the mongoperf benchmark can\n#    be run.  This script needs to be run on single VM.\n#\n#    mongo perf needs Java runtime is also installed.\n#\n#    Installing and configuring Hadoop consists of the following\n#    steps:\n#\n#     1. Install a Java JDK\n#     2. Download the MongoDB tar.gz archive\n#     3. Unpackage the Mongo archive\n#     4. Move the mongo directory to /usr/bin/\n#     5. Update the ~/.bashrc file with mongodb specific exports\n#     8. Start mongoperf test\n#######################################################################\n\n\n#\n# Constants/Globals\n#\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\n\nCONSTANTS_FILE=\"/root/constants.sh\"\nSUMMARY_LOG=~/summary.log\n\nMONGODB_VERSION=\"2.4.0\"\nMONGODB_ARCHIVE=\"mongodb-linux-x86_64-${MONGODB_VERSION}.tgz\"\nMONGODB_URL=\"http://fastdl.mongodb.org/linux/${MONGODB_ARCHIVE}\"\n\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/mongodb.log\n}\n\n\n#######################################################################\n#\n# UpdateTestState()\n#\n#######################################################################\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\n\n#######################################################################\n#\n# UpdateSummary()\n#\n#######################################################################\nUpdateSummary()\n{\n    echo \"${1}\" >> ~/summary.log\n}\n\n\n#######################################################################\n#\n# TimeToSeconds()\n#\n#######################################################################\nTimeToSeconds()\n{\n    read -r h m s <<< $(echo $1 | tr ':' ' ')\n    #echo $(((h*60*60)+(m*60)+s))\n    echo `echo \"${h}*60*60+${m}*60+${s}\" | bc`\n}\n\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\n\n#######################################################################\n#\n# ConfigRhel()\n#\n#######################################################################\nConfigRhel()\n{\n    LogMsg \"ConfigRhel\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        yum -y install java-1.7.0-openjdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install Java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"yum -y install java-1.7.0-openjdk\"\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    LogMsg \"Create JAVA_HOME variable\"\n\n    javaConfig=`echo \"\" | update-alternatives --config java | grep \"*\"`\n    tokens=( $javaConfig )\n    javaPath=${tokens[2]}\n    if [ ! -e $javaPath ]; then\n        LogMsg \"Error: Unable to find the Java install path\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp=`dirname $javaPath`\n    JAVA_HOME=`dirname $temp`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # This is a hack so we can use the same mongodb config on all Linux\n    # distros.  With RHEL, localhost fails.  By setting the hostname\n    # to localhost, then the default config works in RHEL.\n    # Need to revisit this to find a better solution.\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigSles()\n#\n#######################################################################\nConfigSles()\n{\n    LogMsg \"ConfigSles\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        zypper --non-interactive install jre-1.7.0\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"zypper --non-interactive install jre-1.7.0\"\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    JAVA_HOME=`dirname $temp1`\n\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    #\n    # Depending on how the user configs the SLES system, we may or may not\n    # need the following workaround to allow mongodb to use localhost\n    #\n    #hostname localhost\n}\n\n\n#######################################################################\n#\n# ConfigUbuntu()\n#\n#######################################################################\nConfigUbuntu()\n{\n    LogMsg \"ConfigUbuntu\"\n\n    #\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n        apt-get update\n        apt-get -y install default-jdk\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\tssh root@${MD_SERVER} \"apt-get update\"\n\tssh root@${MD_SERVER} \"apt-get -y install default-jdk\"\n    #\n    # Figure out where Java is installed so we can configure a JAVA_HOME variable\n    #\n    javaConfig=`update-alternatives --config java`\n    tempHome=`echo $javaConfig | cut -f 2 -d ':' | cut -f 2 -d ' '`\n    if [ ! -e $tempHome ]; then\n        LogMsg \"Error: The Java directory '${tempHome}' does not exist\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n\n    temp1=`dirname $tempHome`\n    temp2=`dirname $temp1`\n    JAVA_HOME=`dirname $temp2`\n    if [ ! -e $JAVA_HOME ]; then\n        LogMsg \"Error: Invalid JAVA_HOME computed: ${JAVA_HOME}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n}\n\n#######################################################################\n#\n# Main script body\n#\n#######################################################################\n\ncd ~\n\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Updated test case state to running\"\n\nrm -f ~/summary.log\ntouch ~/summary.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${MONGODB_VERSION} ]; then\n\terrMsg=\"The MONGODB_VERSION test parameter is not defined. Setting as ${MONGODB_VERSION} \"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\nfi\n\nif [ ! ${MD_SERVER} ]; then\n    nThreads=16\n\tLogMsg \"Info : nThreads not defined in constants.sh. Setting as ${nThreads}\"\nfi\n\n#\n# Install Java\n#\ndistro=`LinuxRelease`\ncase $distro in\n    \"CENTOS\" | \"RHEL\")\n        ConfigRhel\n    ;;\n    \"UBUNTU\")\n        ConfigUbuntu\n    ;;\n    \"DEBIAN\")\n        LogMsg \"Debian is not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \"  Distro '${distro}' is not currently supported\"\n        exit 1\n    ;;\n    \"SLES\")\n        ConfigSles\n    ;;\n     *)\n        LogMsg \"Distro '${distro}' not supported\"\n        UpdateTestState \"TestAborted\"\n        UpdateSummary \" Distro '${distro}' not supported\"\n        exit 1\n    ;; \nesac\n\n#\n# Download MongoDB to server and start mongodb server.\n#\nLogMsg \"Downloading MangoDB if we do not have a local copy\"\n\nif [ ! -e \"/root/${MONGODB_ARCHIVE}\" ]; then\n    LogMsg \"Downloading Hadoop from ${MONGODB_URL}\"\n    ssh root@${MD_SERVER} \"wget ${MONGODB_URL}\"\n    if [ $? -ne 0 ]; then\n        LogMsg \"Error: Unable to download mongodb from ${MONGODB_URL}\"\n        UpdateTestState $ICA_TESTFAILED\n        exit 1\n    fi\n    LogMsg \"MangoDB successfully downloaded\"\nfi\n\n\t\n\n#\n# Untar and install Hadoop\n#\nLogMsg \"Extracting the mongodb archive\"\n\nssh root@${MD_SERVER} \"tar xfvz mongodb-linux-x86_64-${MONGODB_VERSION}.tgz\"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to extract mongodb from its archive\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi    \n\nLogMsg \"Download YCSB on client VM\"\ncurl -O --location https://github.com/brianfrankcooper/YCSB/releases/download/0.5.0/ycsb-0.5.0.tar.gz\nif [ $? -ne 0 ]; then\n\tLogMsg \"Error: Unable to download YCSB\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\nLogMsg \"Extract YCSB on client VM\"\ntar xfvz ycsb-0.5.0.tar.gz\nif [ $? -ne 0 ]; then\n\tLogMsg \"Error: Unable to download YCSB\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 1\nfi\n\nLogMsg \"Check if MangoDB specific exports are in the .bashrc file\"\n\ngrep -q \"mangodb exports start\" ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"MongoDB exports not found in ~/.bashrc, adding them\"\n    echo \"\" >> ~/.bashrc\n    echo \"# mango exports start\" >> ~/.bashrc\n    echo \"export JAVA_HOME=${JAVA_HOME}\" >> ~/.bashrc\n    echo \"# MangoDB exports end\" >> ~/.bashrc\nfi\n\n#\n# Sourcing the update .bashrc\n#\nsource ~/.bashrc\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to source .bashrc\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Starting MongoDB on ${MD_SERVER}\"\nssh root@${MD_SERVER} \"killall mongod\"\nssh root@${MD_SERVER} \"mkdir -p /tmp/mongodb\"\n#ssh root@${MD_SERVER} \"nohup /root/mongodb-linux-x86_64-${MONGODB_VERSION}/bin/mongod --dbpath /tmp/mongodb > mongodServerConsole.txt &\"\nssh root@${MD_SERVER} \"/root/mongodb-linux-x86_64-${MONGODB_VERSION}/bin/mongod --dbpath /tmp/mongodb --fork --logpath mongodServerConsole.txt\"\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to start mongod server\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Using the asynchronous driver to load the test data\"\n/root/ycsb-0.5.0/bin/ycsb load mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable load the test data\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\nLogMsg \"Using the asynchronous driver to load the test data\"\n/root/ycsb-0.5.0/bin/ycsb run mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0\nif [ $? -ne 0 ]; then\n    LogMsg \"Error: Unable to run test\"\n    UpdateTestState $ICA_TESTFAILED\n    exit 1\nfi\n\n#\n# If we made it here, everything worked.\n#\nUpdateTestState $ICA_TESTCOMPLETED\nexit 0", "num_lines": 455}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n########################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n########################################################################\n\n#######################################################################\n#\n# performance_zk.sh\n#\n# Description:\n#     This tool uses the ZooKeeper (zk) python binding to test various operation latencies\n#\n#\n# In general the script does the following:\n#\n# 1.create a root znode for the test, i.e. /zk-latencies\n# 2.attach a zk session to each server in the ensemble (the --servers list)\n# 3.run various (create/get/set/delete) operations against each server, note the latencies of operations\n# 4.client then cleans up, removing /zk-latencies znode\n#\n#\n# Parameters:\n#\tZK_VERSION\t\t\tzookeeper-server version\n#      \tZK_SERVERS:               \tcomma separated list of host:port (default localhost:2181)\n#\tZK_TIMEOUT;\t\t\tsession timeout in milliseconds (default 5000)\n#\tZK_ZNODE_SIZE;\t\t\tdata size when creating/setting znodes (default 25)\n#\tZK_ZNODE_COUNT;\t\t\tthe number of znodes to operate on in each performance section (default 10000)\n#\tZK_FORCE; (optional)\t\tforce the test to run, even if root_znode exists -WARNING! don't run this on a real znode or you'll lose it !!!\n#\tZK_SYNCHRONOUS;\t\t\tby default asynchronous ZK api is used, this forces synchronous calls\n#\tZK_VERBOSE;\t\t\tverbose output, include more detail\n#\n#######################################################################\n\n\n\nICA_TESTRUNNING=\"TestRunning\"\nICA_TESTCOMPLETED=\"TestCompleted\"\nICA_TESTABORTED=\"TestAborted\"\nICA_TESTFAILED=\"TestFailed\"\n\n\n#\n# Function definitions\n#\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` \": ${1}\"\n}\n\nUpdateTestState()\n{\n    echo $1 > ~/state.txt\n}\n\n#######################################################################\n#\n# LinuxRelease()\n#\n#######################################################################\nLinuxRelease()\n{\n    DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n    case $DISTRO in\n        *buntu*)\n            echo \"UBUNTU\";;\n        Fedora*)\n            echo \"FEDORA\";;\n        CentOS*)\n            echo \"CENTOS\";;\n        *SUSE*)\n            echo \"SLES\";;\n        Red*Hat*)\n            echo \"RHEL\";;\n        Debian*)\n            echo \"DEBIAN\";;\n    esac\n}\n\n######################################################################\n#\n# DoSlesAB()\n#\n# Description:\n#    Perform distro specific Apache and tool installation steps for SLES\n#    and then run the benchmark tool\n#\n#######################################################################\nConfigSlesZK()\n{\n    #\n    # Note: A number of steps will use SSH to issue commands to the\n    #       APACHE_SERVER.  This requires that the SSH keys be provisioned\n    #       in advanced, and strict mode be disabled for both the SSH\n    #       server and client.\n    #\n\n\tLogMsg \"Info: Running SLES\"\n\tarr=$(echo $ZK_SERVERS | tr \",\" \"\\n\")\n\tfor ZK_SERVER in $arr\n\tdo\n\t#echo \"${ZK_SERVER}\"\n\tSERVER=(`echo \"${ZK_SERVER}\" | awk -F':' '{print $1}'`)\n\t#echo \"${SERVER}\"\n\t#ssh root@${SERVER} \"mkdir /root/kk\"\n\t#exit 1\n\tLogMsg \"Info: -----------------------------------------\"\n\tLogMsg \"Info: Zookeeper-Server installation on server ${SERVER}\"\n    \tLogMsg \"Info: Installing required packages first\"\n\tssh root@${SERVER} \"zypper --non-interactive install wget\"\n\tif [ $? -ne 0 ]; then\n\t\tmsg=\"Error: Unable to install package to server ${SERVER}\"\n\t\tLogMsg \"${msg}\"\n\t\techo \"${msg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\t\n\t#\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        ssh root@${SERVER} \"zypper --non-interactive install jre-1.7.0\"\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n        LogMsg \"Info: Download ZK package\"\n\tpkg=(`ssh root@${SERVER} \"ls /root/ | grep ${ZK_ARCHIVE}\"`)\n\techo $pkg\n\tif [ -z \"$pkg\" ]; then\n\t\tLogMsg \"Downloading ZK package ${ZK_ARCHIVE}\"\n\t\t#exit 1\t\n        \tssh root@${SERVER} \"wget ${ZK_URL}\"\n        \tif [ $? -ne 0 ]; then\n                \tmsg=\"Error: Unable to download ZK package to server ${SERVER}\"\n                \tLogMsg \"${msg}\"\n                \techo \"${msg}\" >> ./summary.log\n                \tUpdateTestState $ICA_TESTFAILED\n                \texit 1\n\t\tfi\t\n        fi\n\n\tLogMsg \"Info: Untar and Config ZK server\"\n        ssh root@${SERVER} \"tar -xzf ./${ZK_ARCHIVE}\"\n        ssh root@${SERVER} \"cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg\"\n\n\tLogMsg \"Info: Starting Zookeeper-Server ${SERVER}\"\n        ssh root@${SERVER} \"zookeeper-${ZK_VERSION}/bin/zkServer.sh start\"\n\tif [ $? -ne 0 ]; then\n                msg=\"Error: Unable to start Zookeeper-Server on ${SERVER}\"\n                LogMsg \"${msg}\"\n                echo \"${msg}\" >> ./summary.log\n                UpdateTestState $ICA_TESTFAILED\n                exit 1\n        fi\n\n\tLogMsg \"Info: Server started successfully\"\n\n\tdone\t\n}\n\nConfigUbuntuZK()\n{\n    #\n    # Note: A number of steps will use SSH to issue commands to the\n    #       ZK_SERVER.  This requires that the SSH keys be provisioned\n    #       in advanced, and strict mode be disabled for both the SSH\n    #       server and client.\n    #\n\n\tLogMsg \"Info: Running Ubuntu\"\n\tarr=$(echo $ZK_SERVERS | tr \",\" \"\\n\")\n\tfor ZK_SERVER in $arr\n\tdo\t\n\tSERVER=(`echo \"${ZK_SERVER}\" | awk -F':' '{print $1}'`)\n\tLogMsg \"Info: -----------------------------------------\"\n\tLogMsg \"Info: Zookeeper-Server installation on server ${SERVER}\"\n    \tLogMsg \"Info: Installing required packages first\"\n\tssh root@${SERVER} \"apt-get install -y wget\"\n\tif [ $? -ne 0 ]; then\n\t\tmsg=\"Error: Unable to install package to server ${SERVER}\"\n\t\tLogMsg \"${msg}\"\n\t\techo \"${msg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\t\n\t#\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        ssh root@${SERVER} \"apt-get -y install default-jdk\"\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\n        LogMsg \"Info: Download ZK package\"\n\tpkg=(`ssh root@${SERVER} \"ls /root/ | grep ${ZK_ARCHIVE}\"`)\n\techo $pkg\n\tif [ -z \"$pkg\" ]; then\n\t\tLogMsg \"Downloading ZK package ${ZK_ARCHIVE}\"\n\t\t#exit 1\t\n        \tssh root@${SERVER} \"wget ${ZK_URL}\"\n        \tif [ $? -ne 0 ]; then\n                \tmsg=\"Error: Unable to download ZK package to server ${SERVER}\"\n                \tLogMsg \"${msg}\"\n                \techo \"${msg}\" >> ./summary.log\n                \tUpdateTestState $ICA_TESTFAILED\n                \texit 1\n\t\tfi\t\n        fi\n\n\tLogMsg \"Info: Untar and Config ZK server\"\n        ssh root@${SERVER} \"tar -xzf ./${ZK_ARCHIVE}\"\n        ssh root@${SERVER} \"cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg\"\n\n\tLogMsg \"Info: Starting Zookeeper-Server ${SERVER}\"\n        ssh root@${SERVER} \"zookeeper-${ZK_VERSION}/bin/zkServer.sh start\"\n\tif [ $? -ne 0 ]; then\n                msg=\"Error: Unable to start Zookeeper-Server on ${SERVER}\"\n                LogMsg \"${msg}\"\n                echo \"${msg}\" >> ./summary.log\n                UpdateTestState $ICA_TESTFAILED\n                exit 1\n        fi\n\n\tLogMsg \"Info: Server started successfully\"\n\n\tdone\t\n}\n\nConfigRHELZK()\n{\n    #\n    # Note: A number of steps will use SSH to issue commands to the\n    #       ZK_SERVER.  This requires that the SSH keys be provisioned\n    #       in advanced, and strict mode be disabled for both the SSH\n    #       server and client.\n    #\n\n\tLogMsg \"Info: Running RHEL\"\n\tarr=$(echo $ZK_SERVERS | tr \",\" \"\\n\")\n\tfor ZK_SERVER in $arr\n\tdo\t\n\tSERVER=(`echo \"${ZK_SERVER}\" | awk -F':' '{print $1}'`)\n\tLogMsg \"Info: -----------------------------------------\"\n\tLogMsg \"Info: Zookeeper-Server installation on server ${SERVER}\"\n    \tLogMsg \"Info: Installing required packages first\"\n\tssh root@${SERVER} \"yum install -y wget\"\n\tif [ $? -ne 0 ]; then\n\t\tmsg=\"Error: Unable to install package to server ${SERVER}\"\n\t\tLogMsg \"${msg}\"\n\t\techo \"${msg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\t\n\t#\n    # Install Java\n    #\n    LogMsg \"Check if Java is installed\"\n\n    javaInstalled=`which java`\n    if [ ! $javaInstalled ]; then\n        LogMsg \"Installing Java\"\n\n        ssh root@${SERVER} \"yum -y install java-1.7.0-openjdk\"\n        if [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to install Java\"\n            UpdateTestState $ICA_TESTFAILED\n            exit 1\n        fi\n    fi\n\t\n        LogMsg \"Info: Download ZK package\"\n\tpkg=(`ssh root@${SERVER} \"ls /root/ | grep ${ZK_ARCHIVE}\"`)\n\techo $pkg\n\tif [ -z \"$pkg\" ]; then\n\t\tLogMsg \"Downloading ZK package ${ZK_ARCHIVE}\"\n\t\t#exit 1\t\n        \tssh root@${SERVER} \"wget ${ZK_URL}\"\n        \tif [ $? -ne 0 ]; then\n                \tmsg=\"Error: Unable to download ZK package to server ${SERVER}\"\n                \tLogMsg \"${msg}\"\n                \techo \"${msg}\" >> ./summary.log\n                \tUpdateTestState $ICA_TESTFAILED\n                \texit 1\n\t\tfi\t\n        fi\n\n\tLogMsg \"Info: Untar and Config ZK server\"\n        ssh root@${SERVER} \"tar -xzf ./${ZK_ARCHIVE}\"\n        ssh root@${SERVER} \"cp zookeeper-${ZK_VERSION}/conf/zoo_sample.cfg zookeeper-${ZK_VERSION}/conf/zoo.cfg\"\n\n\tLogMsg \"Info: Starting Zookeeper-Server ${SERVER}\"\n        ssh root@${SERVER} \"zookeeper-${ZK_VERSION}/bin/zkServer.sh start\"\n\tif [ $? -ne 0 ]; then\n                msg=\"Error: Unable to start Zookeeper-Server on ${SERVER}\"\n                LogMsg \"${msg}\"\n                echo \"${msg}\" >> ./summary.log\n                UpdateTestState $ICA_TESTFAILED\n                exit 1\n        fi\n\n\tLogMsg \"Info: Server started successfully\"\n\n\tdone\t\n}\n\n#######################################################################\n#\n# Main script body\n#\n#######################################################################\n\ncd ~\nUpdateTestState $ICA_TESTRUNNING\nLogMsg \"Starting test\"\n\n#\n# Delete any old summary.log file\n#\nLogMsg \"Cleaning up old summary.log\"\nif [ -e ~/summary.log ]; then\n    rm -f ~/summary.log\nfi\n\ntouch ~/summary.log\n\n#\n# Source the constants.sh file\n#\nLogMsg \"Sourcing constants.sh\"\nif [ -e ~/constants.sh ]; then\n    . ~/constants.sh\nelse\n    msg=\"Error: ~/constants.sh does not exist\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\n#\n# Make sure the required test parameters are defined\n#\nif [ \"${ZK_VERSION:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_VERSION test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 20\nfi\n\nif [ \"${ZK_SERVERS:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_SERVER test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTFAILED\n    exit 20\nfi\n\nif [ \"${ZK_TIMEOUT:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_TIMEOUT test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    ZK_TIMEOUT=100000\nfi\n\nif [ \"${ZK_ZNODE_SIZE:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_ZNODE_SIZE test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    ZK_ZNODE_SIZE=100\nfi\n\nif [ \"${ZK_ZNODE_COUNT:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_ZNODE_COUNT test parameter is missing\"\n    LogMsg \"${msg}\"\n    echo \"${msg}\" >> ~/summary.log\n    ZK_ZNODE_SIZE=100\nfi\n\nif [ \"${ZK_FORCE:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_FORCE test parameter is missing\"\n    LogMsg \"${msg}\"\n    ZK_FORCE=$false\nfi\n\nif [ \"${ZK_VERBOSE:=\"UNDEFINED\"}\" = \"UNDEFINED\" ]; then\n    msg=\"Error: the ZK_VERBOSE test parameter is missing\"\n    LogMsg \"${msg}\"\n    ZK_VERBOSE=$false\nfi\n\nLogMsg \"Info: Test run parameters\"\necho \"ZK_VERSION               = ${ZK_VERSION}\"\necho \"ZK_SERVERS               = ${ZK_SERVERS}\"\necho \"ZK_TIMEOUT    = ${ZK_TIMEOUT}\"\necho \"ZK_ZNODE_SIZE = ${ZK_ZNODE_SIZE}\"\necho \"ZK_ZNODE_COUNT = ${ZK_ZNODE_COUNT}\"\necho \"ZK_FORCE = ${ZK_FORCE}\"\necho \"ZK_SYNCHRONOUS = ${ZK_SYNCHRONOUS}\"\necho \"ZK_VERBOSE = ${ZK_VERBOSE}\"\n\n\nLogMsg \"Info : ZK_VERSION = ${ZK_VERSION}\"\nZK_ARCHIVE=\"zookeeper-${ZK_VERSION}.tar.gz\"\nZK_URL=http://apache.spinellicreations.com/zookeeper/zookeeper-${ZK_VERSION}/${ZK_ARCHIVE}\n\n#\n# Configure ZK server - this has distro specific behaviour\n#\ndistro=`LinuxRelease`\ncase $distro in\n    \"CENTOS\" | \"RHEL\")\n        ConfigRHELZK\n    ;;\n    \"UBUNTU\")\n        ConfigUbuntuZK\n    ;;\n    \"DEBIAN\")\n        ConfigDebianZK\n    ;;\n    \"SLES\")\n        ConfigSlesZK\n    ;;\n     *)\n        msg=\"Error: Distro '${distro}' not supported\"\n        LogMsg \"${msg}\"\n        echo \"${msg}\" >> ~/summary.log\n        UpdateTestState \"TestAborted\"\n        exit 1\n    ;; \nesac\n\nIFS=',' read -ra ADDR <<< \"$ZK_SERVERS\"\nfor zk_server in \"${ADDR[@]}\"; \ndo\n\tLogMsg \"Prepare ZK test cmd for ${zk_server}\"\n\ttestBaseString='PYTHONPATH=\"lib.linux-x86_64-2.6\" LD_LIBRARY_PATH=\"lib.linux-x86_64-2.6\" python ./zk-latencies.py '\n\t#testBaseString='./zk-latencies.py PYTHONPATH=lib.linux-x86_64-2.6 LD_LIBRARY_PATH=lib.linux-x86_64-2.6 '\n\ttestString=\"${testBaseString}\"\"--servers=${zk_server} --timeout=${ZK_TIMEOUT} --znode_count=${ZK_ZNODE_COUNT} --znode_size=${ZK_ZNODE_SIZE}\"\n\n\tif [ \"${ZK_FORCE}\" = true ]; then\n\t\ttestString=\"${testString}\"\" --force\"\n\tfi\n\n\tif [ \"${ZK_SYNCHRONOUS}\" = true ]; then\n\t\t\ttestString=\"${testString}\"\" --synchronous\"\n\tfi\n\n\tif [ \"${ZK_VERBOSE}\" = true ]; then\n\t\ttestString=\"${testString}\"\" --verbose\"\n\tfi\n\n\tLogMsg \"Running zookeeper tests with cmd: ${testString}\"\n\teval $testString\n\tif [ $? -ne 0 ]; then\n\t\tmsg=\"Error: Unable to run test\"\n\t\tLogMsg \"${msg}\"\n\t\techo \"${msg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\ndone\n\n\n#\n# If we made it here, everything worked.\n# Indicate success\n#\nLogMsg \"Test completed successfully\"\nUpdateTestState $ICA_TESTCOMPLETED\n\nexit 0", "num_lines": 511}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n########################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n########################################################################\n\n#######################################################################\n#\n# Description:\n#     This script was created to automate the testing of a Linux\n#     kernel source tree.  It does this by performing the following\n#     steps:\n#    1. Make sure we were given a kernel source. If a linux-next git address is provided, make sure that\n#       the VM has a NIC (eth0) connect to Internet.\n#    2. Configure and build the new kernel\n#\n# The outputs are directed into files named:\n#     Perf_BuildKernel_make.log, \n#     Perf_BuildKernel_makemodulesinstall.log, \n#     Perf_BuildKernel_makeinstall.log\n#\n# This test script requires the below test parameters:\n#     <param>SOURCE_TYPE=ONLINE</param>\n#     <param>LINUX_KERNEL_LOCATION=git://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git</param>\n#     <param>KERNEL_VERSION=linux-next</param>\n#\n# A typical XML test definition for this test case would look\n# similar to the following:\n#\t\t<test>\n#\t\t\t<testName>ICA-BUILD-LINUX-KERNEL</testName>\n#\t\t\t<testScript>Perf_BuildKernel.sh</testScript>\n#\t\t\t<testScriptPs1>ICA-BUILD-LINUX-KERNEL.ps1</testScriptPs1>\n#\t\t\t<files>remote-scripts\\Perf_BuildKernel.sh,remote-scripts\\Packages\\linux-3.18.1.tar.xz,SetupScripts\\DetectLinuxDistro.sh</files>\n#\t\t\t<setupType>MediumVM</setupType>\n#\t\t\t<testParams>\n#\t\t\t\t<param>LINUX_KERNEL_LOCATION=https://git.kernel.org/pub/scm/linux/kernel/git/next/linux-next.git</param>\n#\t\t\t\t<param>KERNEL_VERSION=linux-next</param>\n#\t\t\t\t<!-- <param>SOURCE_TYPE=TARBALL</param>\n#\t\t\t\t<param>TARBALL=linux-3.18.1.tar.xz</param>\n#\t\t\t\t<param>KERNEL_VERSION=linux-3.18.1</param>  -->\n#\t\t\t</testParams>\n#\t\t\t<TestType></TestType>\n#\t\t\t<TestFeature></TestFeature>\n#\t\t\t<TestID></TestID>\n#\t\t</test>\n#\n#######################################################################\n\nDEBUG_LEVEL=3\nCONFIG_FILE=.config\n\nSTART_DIR=$(pwd)\n\n#\n#Detect Distro\n#\nLinuxDistro=`./DetectLinuxDistro.sh`\nif [ $LinuxDistro == \"SLES\" -o $LinuxDistro == \"SUSE\" ]; then\n    #zypper update\n\tzypper --non-interactive install git-core make tar gcc bc patch dos2unix wget xz\nelif [ $LinuxDistro == \"CENTOS\" -o $LinuxDistro == \"REDHAT\" -o $LinuxDistro == \"FEDORA\" -o $LinuxDistro == \"ORACLELINUX\" ]; then\n\t#yum update\n\tyum install -y git make tar gcc bc patch dos2unix wget xz\nelif [ $LinuxDistro == \"UBUNTU\" ]; then\n\tapt-get update\n\tapt-get install -y git make tar gcc bc patch dos2unix wget\nfi\n\n#\n# Source the constants.sh file so we know what files to operate on.\n#\ndos2unix -q constants.sh > /dev/null\nsource ./constants.sh\n\ndbgprint()\n{\n    if [ $1 -le $DEBUG_LEVEL ]; then\n        echo \"$2\"\n    fi\n}\n\nUpdateTestState()\n{\n    echo $1 > ${START_DIR}/state.txt\n}\n\nUpdateSummary()\n{\n    echo $1 >> ${START_DIR}/summary.log\n}\n\n#\n# Create the state.txt file so the ICA script knows\n# we are running\n#\nUpdateTestState \"TestRunning\"\nif [ -e ${START_DIR}/state.txt ]; then\n    dbgprint 0 \"State.txt file is created \"\n    dbgprint 0 \"Content of state is : \" ; echo `cat ${START_DIR}/state.txt`\nfi\n\n#\n# Write some useful info to the log file\n#\ndbgprint 1 \"buildKernel.sh - Script to automate building of the kernel\"\ndbgprint 3 \"\"\ndbgprint 3 \"Global values\"\ndbgprint 3 \"  DEBUG_LEVEL = ${DEBUG_LEVEL}\"\ndbgprint 3 \"  SOURCE_TYPE = ${SOURCE_TYPE}\"\ndbgprint 3 \"  LINUX_KERNEL_LOCATION = ${LINUX_KERNEL_LOCATION}\"\ndbgprint 3 \"  TARBALL = ${TARBALL}\"\ndbgprint 3 \"  KERNEL_VERSION = ${KERNEL_VERSION}\"\ndbgprint 3 \"  CONFIG_FILE = ${CONFIG_FILE}\"\ndbgprint 3 \"\"\n\n#\n# Delete old kernel source tree if it exists.\n# This should not be needed, but check to make sure\n# \n# adding check for summary.log\nif [ -e ${START_DIR}/summary.log ]; then\n    dbgprint 1 \"Cleaning up previous copies of summary.log\"\n    rm -rf ${START_DIR}/summary.log\nfi\n# adding check for old kernel source tree\nif [ -e ${KERNEL_VERSION} ]; then\n    dbgprint 1 \"Cleaning up previous copies of source tree\"\n    dbgprint 3 \"Removing the ${KERNEL_VERSION} directory\"\n    rm -rf ${KERNEL_VERSION}\nfi\n\nif [ \"${SOURCE_TYPE}\" == \"TARBALL\" ]; then\n    dbgprint 1 \"Building linux kernel from tarball...\"\n    #\n    # Make sure we were given the $TARBALL file\n    #\n    if [ ! ${TARBALL} ]; then\n        dbgprint 0 \"The TARBALL variable is not defined.\"\n        dbgprint 0 \"Aborting the test.\"\n        UpdateTestState \"TestAborted\"\n        exit 20\n    fi\n\n    dbgprint 3 \"Extracting Linux kernel sources from ${TARBALL}\"\n    tar -xf ${TARBALL}\n    sts=$?\n    if [ 0 -ne ${sts} ]; then\n        dbgprint 0 \"tar failed to extract the kernel from the tarball: ${sts}\" \n        dbgprint 0 \"Aborting test.\"\n        UpdateTestState \"TestAborted\"\n        exit 40\n    fi\n\n    #\n    # The Linux Kernel is extracted to the folder which is named by the version by default\n    #\n    if [ ! -e ${KERNEL_VERSION} ]; then\n        dbgprint 0 \"The tar file did not create the directory: ${KERNEL_VERSION}\"\n        dbgprint 0 \"Aborting the test.\"\n        UpdateTestState \"TestAborted\"\n        exit 50\n    fi\nelse\n    dbgprint 1 \"Building linux-next kernel from git repository...\"\n    #\n    # Make sure we were given the linux-next git location\n    #\n    if [ ! ${LINUX_KERNEL_LOCATION} ]; then\n        dbgprint 0 \"The LINUX_KERNEL_LOCATION variable is not defined.\"\n        dbgprint 0 \"Aborting the test.\"\n        UpdateTestState \"TestAborted\"\n        exit 20\n    fi\n    git clone ${LINUX_KERNEL_LOCATION}\nfi\n   \ncd ${START_DIR}/${KERNEL_VERSION}\n\n#\n# Start the testing\n#\nproc_count=$(cat /proc/cpuinfo | grep --count processor)\ndbgprint 1 \"Build kernel with $proc_count CPU(s)\"\n\nUpdateSummary \"KernelRelease=$(uname -r)\"\nUpdateSummary \"ProcessorCount=$proc_count\"\n\nUpdateSummary \"$(uname -a)\"\n\n#\n# Create the .config file\n#\ndbgprint 1 \"Creating the .config file.\"\nif [ -f ${START_DIR}/ica/kernel.config.base ]; then\n    # Basing a new kernel config on a previous kernel config file will\n    # provide flexibility in providing know good config files with certain\n    # options enabled/disabled.  Functionality could also potentially be\n    # added here for choosing between multiple old config files depending\n    # on the distro that the kernel is being compiled on (i.g. if Fedora\n    # is detected copy ${START_DIR}/ica/kernel.config.base-fedora to .config before\n    # running 'make oldconfig')\n\n    dbgprint 3 \"Creating new config based on a previous .config file\"\n    cp ${START_DIR}/ica/kernel.config.base .config\n\n    # Base the new config on the old one and select the default config\n    # option for any new options in the newer kernel version\n    yes \"\" | make oldconfig\nelse\n    dbgprint 3 \"Create a default .config file\"\n    yes \"\" | make oldconfig\n    sts=$?\n    if [ 0 -ne ${sts} ]; then\n        dbgprint 0 \"make defconfig failed.\"\n        dbgprint 0 \"Aborting the test.\"\n        UpdateTestState \"TestAborted\"\n        exit 60\n    fi\n\n    if [ ! -e ${CONFIG_FILE} ]; then\n        dbgprint 0 \"make defconfig did not create the '${CONFIG_FILE}'\"\n        dbgprint 0 \"Aborting the test.\"\n        UpdateTestState \"TestAborted\"\n        exit 70\n    fi\n\n    #\n    # Enable HyperV support\n    #\n    dbgprint 3 \"Enabling HyperV support in the ${CONFIG_FILE}\"\n    # On this first 'sed' command use --in-place=.orig to make a backup\n    # of the original .config file created with 'defconfig'\n    sed --in-place=.orig -e s:\"# CONFIG_HYPERVISOR_GUEST is not set\":\"CONFIG_HYPERVISOR_GUEST=y\\nCONFIG_HYPERV=y\\nCONFIG_HYPERV_UTILS=y\\nCONFIG_HYPERV_BALLOON=y\\nCONFIG_HYPERV_STORAGE=m\\nCONFIG_HYPERV_NET=y\\nCONFIG_HYPERV_KEYBOARD=y\\nCONFIG_FB_HYPERV=y\\nCONFIG_HID_HYPERV_MOUSE=m\": ${CONFIG_FILE}\n\n    #\n    # Enable Ext4, Reiser support (ext3 is enabled by default)\n    #\n    sed --in-place -e s:\"# CONFIG_EXT4_FS is not set\":\"CONFIG_EXT4_FS=y\\nCONFIG_EXT4_FS_XATTR=y\\nCONFIG_EXT4_FS_POSIX_ACL=y\\nCONFIG_EXT4_FS_SECURITY=y\": ${CONFIG_FILE}\n    sed --in-place -e s:\"# CONFIG_REISERFS_FS is not set\":\"CONFIG_REISERFS_FS=y\\nCONFIG_REISERFS_PROC_INFO=y\\nCONFIG_REISERFS_FS_XATTR=y\\nCONFIG_REISERFS_FS_POSIX_ACL=y\\nCONFIG_REISERFS_FS_SECURITY=y\": ${CONFIG_FILE}\n\n    #\n    # Enable Tulip network driver support.  This is needed for the \"legacy\"\n    # network adapter provided by Hyper-V\n    #\n    sed --in-place -e s:\"# CONFIG_TULIP is not set\":\"CONFIG_TULIP=m\\nCONFIG_TULIP_MMIO=y\": ${CONFIG_FILE}\n\n    yes \"\" | make oldconfig\nfi\nUpdateSummary \"make oldconfig: Success\"\n\n#\n# Build the kernel\n#\ndbgprint 1 \"Building the kernel.\"\n    \nif [ $proc_count -eq 1 ]; then\n    (time make) > ${START_DIR}/Perf_BuildKernel_make.log 2>&1\nelse\n    (time make -j $proc_count) > ${START_DIR}/Perf_BuildKernel_make.log 2>&1\nfi\n\nsts=$?\nif [ 0 -ne ${sts} ]; then\n    dbgprint 1 \"Kernel make failed: ${sts}\"\n    dbgprint 1 \"Aborting test.\"\n    UpdateTestState \"TestAborted\"\n    UpdateSummary \"make: Failed\"\n    exit 110\nelse\n    UpdateSummary \"make: Success\"\nfi\n\n#\n# Build the kernel modules\n#\ndbgprint 1 \"Building the kernel modules.\"\nif [ $proc_count -eq 1 ]; then\n    (time make modules_install) > ${START_DIR}/Perf_BuildKernel_makemodulesinstall.log 2>&1\nelse\n    (time make modules_install -j $proc_count) > ${START_DIR}/Perf_BuildKernel_makemodulesinstall.log 2>&1\nfi\n\nsts=$?\nif [ 0 -ne ${sts} ]; then\n    dbgprint 1 \"Kernel make failed: ${sts}\"\n    dbgprint 1 \"Aborting test.\"\n    UpdateTestState \"TestAborted\"\n    UpdateSummary \"make modules_install: Failed\"    \n    exit 110\nelse\n    UpdateSummary \"make modules_install: Success\"\nfi\n\n#\n# Install the kernel\n#\ndbgprint 1 \"Installing the kernel.\"\nif [ $proc_count -eq 1 ]; then\n    (time make install) > ${START_DIR}/Perf_BuildKernel_makeinstall.log 2>&1\nelse\n    (time make install -j $proc_count) > ${START_DIR}/Perf_BuildKernel_makeinstall.log 2>&1\nfi\n\nsts=$?\nif [ 0 -ne ${sts} ]; then\n    echo \"kernel build failed: ${sts}\"\n    UpdateTestState \"TestAborted\"\n    UpdateSummary \"make install: Failed\"\n    exit 130\nelse\n    UpdateSummary \"make install: Success\"\nfi\n\n#\n# Save the current Kernel version for comparision with the version\n# of the new kernel after the reboot.\n#\ncd ${START_DIR}\ndbgprint 3 \"Saving version number of current kernel in oldKernelVersion.txt\"\nuname -r > ${START_DIR}/oldKernelVersion.txt\n\n### Grub Modification ###\n# Update grub.conf (we only support v1 right now, grub v2 will have to be added\n# later)\ngrubversion=1\nif [ -e /boot/grub/grub.conf ]; then\n        grubfile=\"/boot/grub/grub.conf\"\nelif [ -e /boot/grub/menu.lst ]; then\n        grubfile=\"/boot/grub/menu.lst\"\nelif [ -e /boot/grub2/grub.cfg ]; then\n        grubversion=2\n        grub2-mkconfig -o /boot/grub2/grub.cfg\n        grub2-set-default 0\nelse\n        echo \"grub v1 files does not appear to be installed on this system. it should use grub v2.\"\n        # the new kernel is the default one to boot next time\n        grubversion=2\nfi\n\nif [ 1 -eq ${grubversion} ]; then\n    echo \"Update grub v1 files.\"\n    new_default_entry_num=\"0\"\n    # added\n    sed --in-place=.bak -e \"s/^default\\([[:space:]]\\+\\|=\\)[[:digit:]]\\+/default\\1$new_default_entry_num/\" $grubfile\n    # Display grub configuration after our change\n    echo \"Here are the new contents of the grub configuration file:\"\n    cat $grubfile\nfi\n\n# edit /etc/rc.local and /etc/rc.d/rc.local to \n# make sure ifup_eth automate run script during boot\n#\nifup_eth=\"ifup eth0 > /dev/null\"\n\n#write script path to /etc/rc.local\nif [[ -f /etc/rc.local ]]\nthen\n\tsed \"/^\\s*exit 0/i ${ifup_eth}\" /etc/rc.local -i\n\t\n\tif ! grep -q \"${ifup_eth}\" /etc/rc.local \n\tthen\n\t\techo \"Add ${ifup_eth} to /etc/rc.local\"\n\t\techo $ifup_eth >> /etc/rc.local\n\tfi\n\tchmod +x /etc/rc.local\nfi\n\n#write script path to /etc/rc.d/rc.local\nif [[ -f /etc/rc.d/rc.local ]]\nthen\n\tsed \"/^\\s*exit 0/i ${ifup_eth}\" /etc/rc.d/rc.local -i\n\t\n\tif ! grep -q \"${ifup_eth}\" /etc/rc.d/rc.local \n\tthen\n\t\techo \"Add ${ifup_eth} to /etc/rc.d/rc.local\"\n\t\techo $ifup_eth >> /etc/rc.d/rc.local\n\tfi\n\tchmod +x /etc/rc.d/rc.local\nfi\n\n#if distro is SUSE then configure /etc/rc.d/after.local\nif [[ -f /etc/SuSE-release ]]\nthen\n\techo \"INFO: the distro is SUSE. update /etc/rc.d/after.local\" >> ~/summary.log\n\techo $ifup_eth >> /etc/rc.d/after.local\n\tchmod +x /etc/rc.d/after.local\nfi\n\n#\n# Let the caller know everything worked\n#\ndbgprint 1 \"Exiting with state: TestCompleted.\"\nUpdateTestState \"TestCompleted\"\n\nexit 0\n", "num_lines": 413}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# \n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n#\n# Sample script to run sysbench.\n# In this script, we want to bench-mark device IO performance on a mounted folder.\n# You can adapt this script to other situations easily like for stripe disks as RAID0.\n# The only thing to keep in mind is that each different configuration you're testing\n# must log its output to a different directory.\n#\n\nHOMEDIR=\"/root\"\nLogMsg()\n{\n    echo \"[$(date +\"%x %r %Z\")] ${1}\"\n\techo \"[$(date +\"%x %r %Z\")] ${1}\" >> \"${HOMEDIR}/runlog.txt\"\n}\nLogMsg \"Sleeping 10 seconds..\"\nsleep 10\n\n#export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/share/oem/bin:/usr/share/oem/python/bin:/opt/bin\nCONSTANTS_FILE=\"$HOMEDIR/constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\ntouch ./fioTest.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    . ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\n\nUpdateTestState()\n{\n    echo \"${1}\" > $HOMEDIR/state.txt\n}\n\nInstallFIO() {\n\t\tDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n\t\tif [[ $DISTRO =~ \"Ubuntu\" ]] || [[ $DISTRO =~ \"Debian\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected UBUNTU/Debian\"\n\t\t\tuntil dpkg --force-all --configure -a; sleep 10; do echo 'Trying again...'; done\n\t\t\tapt-get update\n\t\t\tapt-get install -y pciutils gawk mdadm\n\t\t\tapt-get install -y wget sysstat blktrace bc fio\n\t\t\tif [ $? -ne 0 ]; then\n\t\t\t\tLogMsg \"Error: Unable to install fio\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tmount -t debugfs none /sys/kernel/debug\n\t\t\t\t\t\t\t\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 6\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected RHEL 6.x\"\n\t\t\tLogMsg \"INFO: installing required packages\"\n\t\t\trpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\n\t\t\tyum -y --nogpgcheck install wget sysstat mdadm blktrace libaio fio\n\t\t\tmount -t debugfs none /sys/kernel/debug\n\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 7\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected RHEL 7.x\"\n\t\t\tLogMsg \"INFO: installing required packages\"\n\t\t\trpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n\t\t\tyum -y --nogpgcheck install wget sysstat mdadm blktrace libaio fio\n\t\t\tmount -t debugfs none /sys/kernel/debug\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"CentOS Linux release 6\" ]] || [[ $DISTRO =~ \"CentOS release 6\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected CentOS 6.x\"\n\t\t\tLogMsg \"INFO: installing required packages\"\n\t\t\trpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\n\t\t\tyum -y --nogpgcheck install wget sysstat mdadm blktrace libaio fio\n\t\t\tmount -t debugfs none /sys/kernel/debug\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"CentOS Linux release 7\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected CentOS 7.x\"\n\t\t\tLogMsg \"INFO: installing required packages\"\n\t\t\trpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\n\t\t\tyum -y --nogpgcheck install wget sysstat mdadm blktrace libaio fio\n\t\t\tmount -t debugfs none /sys/kernel/debug\n\n\t\telif [[ $DISTRO =~ \"SUSE Linux Enterprise Server 12\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected SLES12\"\n\t\t\tzypper addrepo http://download.opensuse.org/repositories/benchmark/SLE_12_SP2_Backports/benchmark.repo\n\t\t\tzypper --no-gpg-checks --non-interactive --gpg-auto-import-keys refresh\n\t\t\tzypper --no-gpg-checks --non-interactive --gpg-auto-import-keys remove gettext-runtime-mini-0.19.2-1.103.x86_64\n\t\t\tzypper --no-gpg-checks --non-interactive --gpg-auto-import-keys install sysstat\n\t\t\tzypper --no-gpg-checks --non-interactive --gpg-auto-import-keys install grub2\n\t\t\tzypper --no-gpg-checks --non-interactive --gpg-auto-import-keys install wget mdadm blktrace libaio1 fio\n\t\t\t\n\n\t\telse\n\t\t\t\tLogMsg \"Unknown Distro\"\n\t\t\t\tUpdateTestState \"TestAborted\"\n\t\t\t\tUpdateSummary \"Unknown Distro, test aborted\"\n\t\t\t\treturn 1\n\tfi\n}\n\nRunFIO()\n{\n\tUpdateTestState ICA_TESTRUNNING\n\tFILEIO=\"--size=${fileSize} --direct=1 --ioengine=libaio --filename=fiodata --overwrite=1  \"\n\n\t####################################\n\t#All run config set here\n\t#\n\n\t#Log Config\n\t\n\tmkdir $HOMEDIR/FIOLog/jsonLog\n\tmkdir $HOMEDIR/FIOLog/iostatLog\n\tmkdir $HOMEDIR/FIOLog/blktraceLog\n\n\t#LOGDIR=\"${HOMEDIR}/FIOLog\"\n\tJSONFILELOG=\"${LOGDIR}/jsonLog\"\n\tIOSTATLOGDIR=\"${LOGDIR}/iostatLog\"\n\tBLKTRACELOGDIR=\"${LOGDIR}/blktraceLog\"\n\tLOGFILE=\"${LOGDIR}/fio-test.log.txt\"\t\n\n\t#redirect blktrace files directory\n\tResource_mount=$(mount -l | grep /sdb1 | awk '{print$3}')\n\tblk_base=\"${Resource_mount}/blk-$(date +\"%m%d%Y-%H%M%S\")\"\n\tmkdir $blk_base\n\t#\n\t#\n\t#Test config\n\t#\n\t#\n\n\t#All possible values for file-test-mode are randread randwrite read write\n\t#modes='randread randwrite read write'\n\titeration=0\n\t#startThread=1\n\t#startIO=8\n\t#numjobs=1\n\n\t#Max run config\n\t#ioruntime=300\n\t#maxThread=1024\n\t#maxIO=8\n\tio_increment=128\n\n\t####################################\n\techo \"Test log created at: ${LOGFILE}\"\n\techo \"===================================== Starting Run $(date +\"%x %r %Z\") ================================\"\n\techo \"===================================== Starting Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\n\n\tchmod 666 $LOGFILE\n\techo \"Preparing Files: $FILEIO\"\n\techo \"Preparing Files: $FILEIO\" >> $LOGFILE\n\tLogMsg \"Preparing Files: $FILEIO\"\n\t# Remove any old files from prior runs (to be safe), then prepare a set of new files.\n\trm fiodata\n\techo \"--- Kernel Version Information ---\" >> $LOGFILE\n\tuname -a >> $LOGFILE\n\tcat /proc/version >> $LOGFILE\n\tcat /etc/*-release >> $LOGFILE\n\techo \"--- PCI Bus Information ---\" >> $LOGFILE\n\tlspci >> $LOGFILE\n\techo \"--- Drive Mounting Information ---\" >> $LOGFILE\n\tmount >> $LOGFILE\n\techo \"--- Disk Usage Before Generating New Files ---\" >> $LOGFILE\n\tdf -h >> $LOGFILE\n\tfio --cpuclock-test >> $LOGFILE\n\tfio $FILEIO --readwrite=read --bs=1M --runtime=1 --iodepth=128 --numjobs=8 --name=prepare\n\techo \"--- Disk Usage After Generating New Files ---\" >> $LOGFILE\n\tdf -h >> $LOGFILE\n\techo \"=== End Preparation  $(date +\"%x %r %Z\") ===\" >> $LOGFILE\n\tLogMsg \"Preparing Files: $FILEIO: Finished.\"\n\t####################################\n\t#Trigger run from here\n\tfor testmode in $modes; do\n\t\tio=$startIO\n\t\twhile [ $io -le $maxIO ]\n\t\tdo\n\t\t\tThread=$startThread\t\t\t\n\t\t\twhile [ $Thread -le $maxThread ]\n\t\t\tdo\n\t\t\t\tif [ $Thread -ge 8 ]\n\t\t\t\tthen\n\t\t\t\t\tnumjobs=8\n\t\t\t\telse\n\t\t\t\t\tnumjobs=$Thread\n\t\t\t\tfi\n\t\t\t\tiostatfilename=\"${IOSTATLOGDIR}/iostat-fio-${testmode}-${io}K-${Thread}td.txt\"\n\t\t\t\tnohup iostat -x 5 -t -y > $iostatfilename &\n\t\t\t\t#capture blktrace output during test\n\t\t\t\t#LogMsg \"INFO: start blktrace for 40 sec on device sdd and sdf\"\t\t\t\t\n\t\t\t\t#blk_operation=\"${blk_base}/blktrace-fio-${testmode}-${io}K-${Thread}td/\"\t\t\t\t\t\t\t\n\t\t\t\t#mkdir $blk_operation\n\t\t\t\t#blktrace -w 40 -d /dev/sdf -D $blk_operation &\n\t\t\t\t#blktrace -w 40 -d /dev/sdm -D $blk_operation &\n\t\t\t\techo \"-- iteration ${iteration} ----------------------------- ${testmode} test, ${io}K bs, ${Thread} threads, ${numjobs} jobs, 5 minutes ------------------ $(date +\"%x %r %Z\") ---\" >> $LOGFILE\n\t\t\t\tLogMsg \"Running ${testmode} test, ${io}K bs, ${Thread} threads ...\"\n\t\t\t\tjsonfilename=\"${JSONFILELOG}/fio-result-${testmode}-${io}K-${Thread}td.json\"\n\t\t\t\tfio $FILEIO --readwrite=$testmode --bs=${io}K --runtime=$ioruntime --iodepth=$Thread --numjobs=$numjobs --output-format=json --output=$jsonfilename --name=\"iteration\"${iteration} >> $LOGFILE\n\t\t\t\t#fio $FILEIO --readwrite=$testmode --bs=${io}K --runtime=$ioruntime --iodepth=$Thread --numjobs=$numjobs --name=\"iteration\"${iteration} --group_reporting >> $LOGFILE\n\t\t\t\tiostatPID=`ps -ef | awk '/iostat/ && !/awk/ { print $2 }'`\n\t\t\t\tkill -9 $iostatPID\n\t\t\t\tThread=$(( Thread*2 ))\t\t\n\t\t\t\titeration=$(( iteration+1 ))\n\t\t\tdone\n\t\tio=$(( io * io_increment ))\n\t\tdone\n\tdone\n\t####################################\n\techo \"===================================== Completed Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\n\trm fiodata\n\n\tcompressedFileName=\"${HOMEDIR}/FIOTest-$(date +\"%m%d%Y-%H%M%S\").tar.gz\"\n\tLogMsg \"INFO: Please wait...Compressing all results to ${compressedFileName}...\"\n\ttar -cvzf $compressedFileName $LOGDIR/\n\n\techo \"Test logs are located at ${LOGDIR}\"\n\tUpdateTestState ICA_TESTCOMPLETED\n}\n\n\nCreateRAID0()\n{\t\n\tdisks=$(ls -l /dev | grep sd[c-z]$ | awk '{print $10}')\n\t#disks=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\t\n\tLogMsg \"INFO: Check and remove RAID first\"\n\tmdvol=$(cat /proc/mdstat | grep \"active raid\" | awk {'print $1'})\n\tif [ -n \"$mdvol\" ]; then\n\t\techo \"/dev/${mdvol} already exist...removing first\"\n\t\tumount /dev/${mdvol}\n\t\tmdadm --stop /dev/${mdvol}\n\t\tmdadm --remove /dev/${mdvol}\n\t\tmdadm --zero-superblock /dev/sd[c-z][1-5]\n\tfi\n\t\n\tLogMsg \"INFO: Creating Partitions\"\n\tcount=0\n\tfor disk in ${disks}\n\tdo\t\t\n\t\techo \"formatting disk /dev/${disk}\"\n\t\t(echo d; echo n; echo p; echo 1; echo; echo; echo t; echo fd; echo w;) | fdisk /dev/${disk}\n\t\tcount=$(( $count + 1 ))\n\t\tsleep 1\n\tdone\n\tLogMsg \"INFO: Creating RAID of ${count} devices.\"\n\tsleep 1\n\tmdadm --create ${mdVolume} --level 0 --raid-devices ${count} /dev/sd[c-z][1-5]\n\tsleep 1\n\ttime mkfs -t $1 -F ${mdVolume}\n\tmkdir ${mountDir}\n\tsleep 1\n\tmount -o nobarrier ${mdVolume} ${mountDir}\n\tif [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to create raid\"            \n            exit 1\n\telse\n\t\tLogMsg \"${mdVolume} mounted to ${mountDir} successfully.\"\n\tfi\n\t\n\t#LogMsg \"INFO: adding fstab entry\"\n\t#echo \"${mdVolume}\t${mountDir}\text4\tdefaults\t1 1\" >> /etc/fstab\n}\n\nCreateLVM()\n{\t\n\tdisks=$(ls -l /dev | grep sd[c-z]$ | awk '{print $10}')\n\t#disks=(`fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\" `)\n\t\n\t#LogMsg \"INFO: Check and remove LVM first\"\n\tvgExist=$(vgdisplay)\n\tif [ -n \"$vgExist\" ]; then\n\t\tumount ${mountDir}\n\t\tlvremove -A n -f /dev/${vggroup}/lv1\n\t\tvgremove ${vggroup} -f\n\tfi\n\t\n\tLogMsg \"INFO: Creating Partition\"\n\tcount=0\n\tfor disk in ${disks}\n\tdo\t\t\n\t\techo \"formatting disk /dev/${disk}\"\n\t\t(echo d; echo n; echo p; echo 1; echo; echo; echo t; echo fd; echo w;) | fdisk /dev/${disk}\n\t\tcount=$(( $count + 1 )) \n\tdone\n\t\n\tLogMsg \"INFO: Creating LVM with all data disks\"\n\tpvcreate /dev/sd[c-z][1-5]\n\tvgcreate ${vggroup} /dev/sd[c-z][1-5]\n\tlvcreate -l 100%FREE -i 12 -I 64 ${vggroup} -n lv1\n\ttime mkfs -t $1 -F /dev/${vggroup}/lv1\n\tmkdir ${mountDir}\n\tmount -o nobarrier /dev/${vggroup}/lv1 ${mountDir}\n\tif [ $? -ne 0 ]; then\n            LogMsg \"Error: Unable to create LVM \"            \n            exit 1\n        fi\n\t\n\t#LogMsg \"INFO: adding fstab entry\"\n\t#echo \"${mdVolume}\t${mountDir}\text4\tdefaults\t1 1\" >> /etc/fstab\n}\n\n############################################################\n#\tMain body\n############################################################\n\nHOMEDIR=$HOME\nmv $HOMEDIR/FIOLog/ $HOMEDIR/FIOLog-$(date +\"%m%d%Y-%H%M%S\")/\nmkdir $HOMEDIR/FIOLog\nLOGDIR=\"${HOMEDIR}/FIOLog\"\nDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\nif [[ $DISTRO =~ \"SUSE Linux Enterprise Server 12\" ]];\nthen\n\tmdVolume=\"/dev/md/mdauto0\"\nelse\n\tmdVolume=\"/dev/md0\"\nfi\nvggroup=\"vg1\"\nmountDir=\"/data\"\ncd ${HOMEDIR}\n\nInstallFIO\n\n#Creating RAID before triggering test\nCreateRAID0 ext4\n#CreateLVM ext4\n\n#Run test from here\nLogMsg \"*********INFO: Starting test execution*********\"\ncd ${mountDir}\nmkdir sampleDIR\nRunFIO\nLogMsg \"*********INFO: Script execution reach END. Completed !!!*********\"\n", "num_lines": 348}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\t http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n# \n#######################################################################\n\n#######################################################################\n#\n# perf_IPERF3.sh\n# Author : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#\n# Description:\n#\tDownload and run IPERF3 network performance tests.\n#\tThis script needs to be run on client VM.\n#\n# Supported Distros:\n#\tUbuntu 16.04\n#######################################################################\n\nCONSTANTS_FILE=\"./constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"\t  # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"\t  # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"\t\t# Error occurred during the test\ntouch ./IPERF3Test.log\n\nInstallIPERF3()\n{\n\t\tDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\t\tif [[ $DISTRO =~ \"Ubuntu\" ]];\n\t\tthen\n\t\t\t\n\t\t\tLogMsg \"Detected Ubuntu\"\n\t\t\tssh ${1} \"until dpkg --force-all --configure -a; sleep 10; do echo 'Trying again...'; done\"\n\t\t\tssh ${1} \"apt-get update\"\n\t\t\tssh ${1} \"apt-get -y install iperf3 sysstat bc psmisc\"\n\t\t\tif [ $IPversion -eq 6 ]; then\t\n\t\t\t\tscp ConfigureUbuntu1604IPv6.sh ${1}:\n\t\t\t\tssh ${1} \"chmod +x ConfigureUbuntu1604IPv6.sh\"\n\t\t\t\tssh ${1} \"./ConfigureUbuntu1604IPv6.sh\"\n\t\t\tfi\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 6\" ]] || [[ $DISTRO =~ \"CentOS Linux release 6\" ]] || [[ $DISTRO =~ \"CentOS release 6\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected Redhat/CentOS 6.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install iperf3 sysstat bc psmisc\"\n\t\t\t\tssh ${1} \"iptables -F\"\t\t\t\t\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 7\" ]] || [[ $DISTRO =~ \"CentOS Linux release 7\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected Redhat/CentOS 7.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install iperf3 sysstat bc psmisc\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\t\t\t\t\n\t\telse\n\t\t\t\tLogMsg \"Unknown Distro\"\n\t\t\t\tUpdateTestState \"TestAborted\"\n\t\t\t\tUpdateSummary \"Unknown Distro, test aborted\"\n\t\t\t\treturn 1\n\t\tfi\n}\n\n\nLogMsg()\n{\n\techo `date \"+%b %d %Y %T\"` : \"${1}\"\t# Add the time stamp to the log message\n\techo \"${1}\" >> ./IPERF3Test.log\n}\n\nUpdateTestState()\n{\n\techo \"${1}\" > ./state.txt\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n\tsource ${CONSTANTS_FILE}\nelse\n\terrMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n\tLogMsg \"${errMsg}\"\n\tUpdateTestState $ICA_TESTABORTED\n\texit 10\nfi\n\nif [ ! ${server} ]; then\n\terrMsg=\"Please add/provide value for server in constants.sh. server=<server ip>\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\nif [ ! ${client} ]; then\n\terrMsg=\"Please add/provide value for client in constants.sh. client=<client ip>\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\n\nif [ ! ${testDuration} ]; then\n\terrMsg=\"Please add/provide value for testDuration in constants.sh. testDuration=60\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\n\nif [ ! ${testType} ]; then\n\t\terrMsg=\"Please add/provide value for testType in constants.sh. testType=tcp/udp\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\nfi\n\nif [ ! ${max_parallel_connections_per_instance} ]; then\n\t\terrMsg=\"Please add/provide value for max_parallel_connections_per_instance in constants.sh. max_parallel_connections_per_instance=60\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\nfi\n\nif [ ! ${connections} ]; then\n\t\terrMsg=\"Please add/provide value for connections in constants.sh. connections=(1 2 4 8 ....)\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\nfi\n\nif [ ! ${bufferLengths} ]; then\n\t\terrMsg=\"Please add/provide value for bufferLengths in constants.sh. bufferLengths=(1 8). Note buffer lenghs are in Bytest\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\nfi\n\nif [ ! ${IPversion} ]; then\n\t\terrMsg=\"Please add/provide value for IPversion in constants.sh. IPversion=4/6.\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ./summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\nfi\n\nif [ $IPversion -eq 6 ]; then\n\tif [ ! ${serverIpv6} ]; then\n\t\t\terrMsg=\"Please add/provide value for serverIpv6 in constants.sh\"\n\t\t\tLogMsg \"${errMsg}\"\n\t\t\techo \"${errMsg}\" >> ./summary.log\n\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\texit 1\n\tfi\n\t\tif [ ! ${clientIpv6} ]; then\n\t\t\t\terrMsg=\"Please add/provide value for clientIpv6 in constants.sh.\"\n\t\t\t\tLogMsg \"${errMsg}\"\n\t\t\t\techo \"${errMsg}\" >> ./summary.log\n\t\t\t\tUpdateTestState $ICA_TESTABORTED\n\t\t\t\texit 1\n\t\tfi\n\t\nfi\n\n\n#connections=(64 128)\n#BufferLenghts are in Bytes\n#max_parallel_connections_per_instance=64\n#Make & build IPERF3 on client and server Machine\n\nLogMsg \"Configuring client ${client}...\"\nInstallIPERF3 ${client}\n\nLogMsg \"Configuring server ${server}...\"\nInstallIPERF3 ${server}\n\nssh ${server} \"rm -rf iperf-server-*\"\nssh ${client} \"rm -rf iperf-client-*\"\nssh ${client} \"rm -rf iperf-server-*\"\n\n\n#connections=(1 2 4 8 16 32 64 128 256 512 1024)\n#BufferLenghts are in K\n#bufferLenghs=(1 8)\n\nfor current_buffer in \"${bufferLengths[@]}\"\n\t\tdo\n\t\tfor current_test_connections in \"${connections[@]}\"\n\t\tdo\n\t\tif [ $current_test_connections -lt $max_parallel_connections_per_instance ]\n\t\tthen\n\t\t\tnum_threads_P=$current_test_connections\n\t\t\tnum_threads_n=1\n\t\telse\n\t\t\tnum_threads_P=$max_parallel_connections_per_instance\n\t\t\tnum_threads_n=$(($current_test_connections / $num_threads_P))\n\t\tfi\n\t\t\n\t\tssh ${server} \"killall iperf3\"\n\t\tssh ${client} \"killall iperf3\"\n\t\tLogMsg \"Starting $num_threads_n iperf3 server instances on $server..\"\n\t\tstartPort=750\n\t\tcurrentPort=$startPort\n\t\tcurrentIperfInstanses=0\n\t\twhile [ $currentIperfInstanses -lt $num_threads_n ]\n\t\tdo\n\t\t\tcurrentIperfInstanses=$(($currentIperfInstanses+1))\n\t\t\tserverCommand=\"iperf3 -s -1 -J -i10 -f g -p ${currentPort} > iperf-server-${testType}-IPv${IPversion}-buffer-${current_buffer}-conn-$current_test_connections-instance-${currentIperfInstanses}.txt 2>&1\"\n\t\t\tssh ${server} $serverCommand &\n\t\t\tLogMsg \"Executed: $serverCommand\"\n\t\t\tcurrentPort=$(($currentPort+1))\n\t\t\tsleep 0.1\n\t\tdone\n\n\t\tLogMsg \"$num_threads_n iperf server instances started on $server..\"\n\t\tsleep 5\n\t\tLogMsg \"Starting client..\"\n\t\tstartPort=750\n\t\tcurrentPort=$startPort\n\t\tcurrentIperfInstanses=0\n\t\tif [ $IPversion -eq 4 ]; then\n\t\t\t\ttestServer=$server\n\t\telse\n\t\t\t\ttestServer=$serverIpv6\n\t\tfi\n\t\t#ssh ${client} \"./sar-top.sh ${testDuration} $current_test_connections root\" &\n\t\t#ssh ${server} \"./sar-top.sh ${testDuration} $current_test_connections root\" &\n\t\twhile [ $currentIperfInstanses -lt $num_threads_n ]\n\t\tdo\n\t\t\tcurrentIperfInstanses=$(($currentIperfInstanses+1))\n\n\t\t\tif [[ \"$testType\" == \"udp\" ]];\n\t\t\tthen\n\t\t\t\tclientCommand=\"iperf3 -c $testServer -u -b 0 -J -f g -i10 -l ${current_buffer} -t ${testDuration} -p ${currentPort} -P $num_threads_P -${IPversion} > iperf-client-${testType}-IPv${IPversion}-buffer-${current_buffer}-conn-$current_test_connections-instance-${currentIperfInstanses}.txt 2>&1\"\n\t\t\tfi\n\t\t\t\t\t\tif [[ \"$testType\" == \"tcp\" ]];\n\t\t\t\t\t\tthen\n\t\t\t\t\t\t\t\tclientCommand=\"iperf3 -c $testServer -b 0 -J -f g -i10 -l ${current_buffer} -t ${testDuration} -p ${currentPort} -P $num_threads_P -${IPversion} > iperf-client-${testType}-IPv${IPversion}-buffer-${current_buffer}-conn-$current_test_connections-instance-${currentIperfInstanses}.txt 2>&1\"\n\t\t\t\t\t\tfi\n\t\t\t\n\t\t\tssh ${client} $clientCommand &\n\t\t\tLogMsg \"Executed: $clientCommand\"\n\t\t\tcurrentPort=$(($currentPort+1))\n\t\t\tsleep 0.1\n\t\tdone\n\t\tLogMsg \"Iperf3 running buffer ${current_buffer}Bytes $num_threads_P X $num_threads_n ...\"\n\t\tsleep ${testDuration}\n\t\ttimeoutSeconds=900\n\t\tsleep 5\n\t\tvar=`ps -C \"iperf3 -c\" --no-headers | wc -l`\n\t\techo $var\n\t\twhile [[ $var -gt 0 ]];\n\t\tdo\n\t\t\ttimeoutSeconds=`expr $timeoutSeconds - 1`\n\t\t\tif [ $timeoutSeconds -eq 0 ]; then\n\t\t\t\tLogMsg \"Iperf3 running buffer ${current_buffer}K $num_threads_P X $num_threads_n. Timeout.\"\n\t\t\t\tLogMsg \"killing all iperf3 client threads.\"\n\t\t\t\tkillall iperf3\n\t\t\t\tsleep 1\n\t\t\telse\n\t\t\t\tsleep 1\n\t\t\t\tvar=`ps -C \"iperf3 -c\" --no-headers | wc -l`\n\t\t\t\tLogMsg \"Iperf3 running buffer ${current_buffer}K $num_threads_P X $num_threads_n. Waiting to finish $var instances.\"\n\t\t\tfi\t\t\t\n\t\tdone\n\t\t#Sleep extra 5 seconds.\n\t\tsleep 5\n\t\tLogMsg \"Iperf3 Finished buffer ${current_buffer}  $num_threads_P X $num_threads_n ...\"\n\tdone\ndone\nscp ${server}:iperf-server-* ./\nUpdateTestState ICA_TESTCOMPLETED\n", "num_lines": 291}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n# \n#######################################################################\n\n#######################################################################\n#\n# perf_lagscope.sh\n# Author : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#\n# Description:\n#    Download and run lagscope latency tests.\n#    This script needs to be run on client VM.\n#\n# Supported Distros:\n#    Ubuntu 16.04\n#######################################################################\n\nCONSTANTS_FILE=\"./constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"\t\t# The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"\t# The test completed successfully\nICA_TESTABORTED=\"TestAborted\"\t\t# Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"\t\t\t# Error occurred during the test\ntouch ./lagscopeTest.log\n\n\nInstallLAGSCOPE() {\n\t\tDISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n\t\tif [[ $DISTRO =~ \"Ubuntu\" ]];\n\t\tthen\n\t\t\tLogMsg \"Detected UBUNTU\"\n\t\t\t\tLogMsg \"Configuring ${1} for lagscope test...\"\n\t\t\t\tssh ${1} \"until dpkg --force-all --configure -a; sleep 10; do echo 'Trying again...'; done\"\n\t\t\t\tssh ${1} \"apt-get update\"\n\t\t\t\tssh ${1} \"apt-get -y install libaio1 sysstat git bc make gcc\"\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 6\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected Redhat 6.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install gcc-c++\"\n\n\t\t\t\tssh ${1} \"wget http://ftp.heanet.ie/mirrors/gnu/libc/glibc-2.14.1.tar.gz\"\n\t\t\t\tssh ${1} \"tar xvf glibc-2.14.1.tar.gz\"\n\t\t\t\tssh ${1} \"mv glibc-2.14.1 glibc-2.14 && cd glibc-2.14 && mkdir build && cd build && ../configure --prefix=/opt/glibc-2.14 && make && make install && export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH\"\n\t\t\t\t\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\n\t\telif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 7\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected Redhat 7.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc\"\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"CentOS Linux release 6\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected CentOS 6.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install gcc-c++\"\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\t\t\t\t\n\t\telif [[ $DISTRO =~ \"CentOS Linux release 7\" ]];\n\t\tthen\n\t\t\t\tLogMsg \"Detected CentOS 7.x\"\n\t\t\t\tssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\"\n\t\t\t\tssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc\"\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\n\t\telif [[ $DISTRO =~ \"SUSE Linux Enterprise Server 12\" ]];\n\t\tthen\n\t\tLogMsg \"Detected SLES12\"\n\t\t\t\tssh ${1} \"zypper --no-gpg-checks --non-interactive --gpg-auto-import-keys remove gettext-runtime-mini*\"\n\t\t\t\tssh ${1} \"zypper --no-gpg-checks --non-interactive --gpg-auto-import-keys install sysstat git bc make gcc grub2\"\n\t\t\t\tssh ${1} \"rm -rf lagscope\"\n\t\t\t\tssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n\t\t\t\tssh ${1} \"cd lagscope/src && make && make install\"\n\t\t\t\tssh ${1} \"iptables -F\"\n\t\t\t\t\n\t\telse\n\t\t\t\tLogMsg \"Unknown Distro\"\n\t\t\t\tUpdateTestState \"TestAborted\"\n\t\t\t\tUpdateSummary \"Unknown Distro, test aborted\"\n\t\t\t\treturn 1\n\tfi\n}\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ./ntttcpTest.log\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > ./state.txt\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${server} ]; then\n\terrMsg=\"Please add/provide value for server in constants.sh. server=<server ip>\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\nif [ ! ${client} ]; then\n\terrMsg=\"Please add/provide value for client in constants.sh. client=<client ip>\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\n\nif [ ! ${pingIteration} ]; then\n\terrMsg=\"Please add/provide value for pingIteration in constants.sh. pingIteration=1000000\"\n\tLogMsg \"${errMsg}\"\n\techo \"${errMsg}\" >> ./summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\n\n#Make & build ntttcp on client and server Machine\n\nLogMsg \"Configuring client ${client}...\"\nInstallLAGSCOPE ${client}\n\nLogMsg \"Configuring server ${server}...\"\nInstallLAGSCOPE ${server}\n\n#Now, start the ntttcp client on client VM.\n\nLogMsg \"Now running Lagscope test\"\nLogMsg \"Starting server.\"\nssh root@${server} \"lagscope -r -D\"\nsleep 1\nLogMsg \"lagscope client running...\"\nssh root@${client} \"lagscope -s${server} -i0 -n${pingIteration} -H > lagscope-n${pingIteration}-output.txt\"\nLogMsg \"Test finsished.\"\nUpdateTestState ICA_TESTCOMPLETED\n\n", "num_lines": 185}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# perf_ntttcp.sh\n# Author : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#\n# Description:\n#    Download and run ntttcp network performance tests.\n#    This script needs to be run on client VM.\n#\n# Supported Distros:\n#    Ubuntu 16.04\n#######################################################################\n\nCONSTANTS_FILE=\"./constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"           # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"       # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"           # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"                     # Error occurred during the test\ntouch ./ntttcpTest.log\n\n\nInstallNTTTCP() {\n                DISTRO=`grep -ihs \"buntu\\|Suse\\|Fedora\\|Debian\\|CentOS\\|Red Hat Enterprise Linux\" /etc/{issue,*release,*version}`\n\n                if [[ $DISTRO =~ \"Ubuntu\" ]];\n                then\n                        LogMsg \"Detected UBUNTU\"\n                                LogMsg \"Configuring ${1} for ntttcp test...\"\n                                ssh ${1} \"until dpkg --force-all --configure -a; sleep 10; do echo 'Trying again...'; done\"\n                                ssh ${1} \"apt-get update\"\n                                ssh ${1} \"apt-get -y install libaio1 sysstat git bc make gcc dstat psmisc\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n\n                elif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 6\" ]];\n                then\n                                LogMsg \"Detected Redhat 6.x\"\n                                ssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\"\n                                ssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc dstat psmisc\"\n                                ssh ${1} \"yum -y --nogpgcheck install gcc-c++\"\n\n                                ssh ${1} \"wget http://ftp.heanet.ie/mirrors/gnu/libc/glibc-2.14.1.tar.gz\"\n                                ssh ${1} \"tar xvf glibc-2.14.1.tar.gz\"\n                                ssh ${1} \"mv glibc-2.14.1 glibc-2.14 && cd glibc-2.14 && mkdir build && cd build && ../configure --prefix=/opt/glibc-2.14 && make && make install && export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH\"\n\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n                                ssh ${1} \"iptables -F\"\n\n                elif [[ $DISTRO =~ \"Red Hat Enterprise Linux Server release 7\" ]];\n                then\n                                LogMsg \"Detected Redhat 7.x\"\n                                ssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\"\n                                ssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc dstat psmisc\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n                                ssh ${1} \"iptables -F\"\n\n                elif [[ $DISTRO =~ \"CentOS Linux release 6\" ]] || [[ $DISTRO =~ \"CentOS release 6\" ]];\n                then\n                                LogMsg \"Detected CentOS 6.x\"\n                                ssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\"\n                                ssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc dstat psmisc\"\n                                ssh ${1} \"yum -y --nogpgcheck install gcc-c++\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n                                ssh ${1} \"iptables -F\"\n\n                elif [[ $DISTRO =~ \"CentOS Linux release 7\" ]];\n                then\n                                LogMsg \"Detected CentOS 7.x\"\n                                ssh ${1} \"rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm\"\n                                ssh ${1} \"yum -y --nogpgcheck install libaio1 sysstat git bc make gcc dstat psmisc\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n                                ssh ${1} \"iptables -F\"\n\n                elif [[ $DISTRO =~ \"SUSE Linux Enterprise Server 12\" ]];\n                then\n                LogMsg \"Detected SLES12\"\n                                ssh ${1} \"zypper --no-gpg-checks --non-interactive --gpg-auto-import-keys remove gettext-runtime-mini*\"\n                                ssh ${1} \"zypper --no-gpg-checks --non-interactive --gpg-auto-import-keys install sysstat git bc make gcc grub2 dstat psmisc\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/ntttcp-for-linux.git\"\n                                ssh ${1} \"cd ntttcp-for-linux/src/ && make && make install\"\n                                ssh ${1} \"cp ntttcp-for-linux/src/ntttcp .\"\n                                ssh ${1} \"rm -rf lagscope\"\n                                ssh ${1} \"git clone https://github.com/Microsoft/lagscope\"\n                                ssh ${1} \"cd lagscope/src && make && make install\"\n                                ssh ${1} \"iptables -F\"\n\n                else\n                                LogMsg \"Unknown Distro\"\n                                UpdateTestState \"TestAborted\"\n                                UpdateSummary \"Unknown Distro, test aborted\"\n                                return 1\n        fi\n}\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ./ntttcpTest.log\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > ./state.txt\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${server} ]; then\n        errMsg=\"Please add/provide value for server in constants.sh. server=<server ip>\"\n        LogMsg \"${errMsg}\"\n        echo \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\nif [ ! ${client} ]; then\n        errMsg=\"Please add/provide value for client in constants.sh. client=<client ip>\"\n        LogMsg \"${errMsg}\"\n        echo \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\n\nif [ ! ${testDuration} ]; then\n        errMsg=\"Please add/provide value for testDuration in constants.sh. testDuration=60\"\n        LogMsg \"${errMsg}\"\n        echo \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\n\nif [ ! ${nicName} ]; then\n        errMsg=\"Please add/provide value for nicName in constants.sh. nicName=eth0/bond0\"\n        LogMsg \"${errMsg}\"\n        echo \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\n#Make & build ntttcp on client and server Machine\n\nLogMsg \"Configuring client ${client}...\"\nInstallNTTTCP ${client}\n\nLogMsg \"Configuring server ${server}...\"\nInstallNTTTCP ${server}\n\n#Now, start the ntttcp client on client VM.\n\nssh root@${client} \"wget https://raw.githubusercontent.com/iamshital/linux_performance_test/master/run_ntttcp-for-linux/run-ntttcp-and-tcping.sh\"\nssh root@${client} \"wget https://raw.githubusercontent.com/iamshital/linux_performance_test/master/run_ntttcp-for-linux/report-ntttcp-and-tcping.sh\"\nssh root@${client} \"chmod +x run-ntttcp-and-tcping.sh && chmod +x report-ntttcp-and-tcping.sh\"\nLogMsg \"Now running NTTTCP test\"\nssh root@${client} \"rm -rf ntttcp-test-logs\"\nssh root@${client} \"./run-ntttcp-and-tcping.sh ntttcp-test-logs ${server} root ${testDuration} ${nicName} '$testConnections'\"\nssh root@${client} \"./report-ntttcp-and-tcping.sh ntttcp-test-logs '$testConnections'\"\nssh root@${client} \"cp ntttcp-test-logs/* .\"\n\nUpdateTestState ICA_TESTCOMPLETED", "num_lines": 210}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n# \n#######################################################################\n\n#######################################################################\n#\n# perf_orion.sh\n# Author : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#\n# Description:\n#    Download and run orion disk performance tests.\n#    This script needs to be run on single VM with one data disk attached.\n#    This script requires orion.lun file to be present in pwd. It contains the disk names on which we need to perform the test.\n#    orion.lun:\n#    /dev/sdc\n#\n# Supported Distros:\n#    Ubuntu 16.04\n#######################################################################\n\nCONSTANTS_FILE=\"./constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\ntouch ./orionTest.log\n\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ./orionTest.log\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > ./state.txt\n}\n\nConfigUbuntu1604()\n{\n    LogMsg \"Running ConfigUbuntu...\"\n\tapt-get update\n\tapt-get -y install libaio1 sysstat\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nConfigUbuntu1604\n\nif [ -e orion_x86_64 ]; then\n    LogMsg \"orion binary already exists.\"\nelse\n    wget ${orionBinaryURL}\nfi\nchmod +x ./orion_x86_64\n\nUpdateTestState \"TestRunning\"\n#all read\ntestType=\"oltp\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run oltp -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"dss\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run dss -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"simple\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run simple -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"normal#1\"\nLogMsg \"Running $testType test iteration #1..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run normal -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\n#redo the \"normal\" test\n\ntestType=\"normal#2\"\nLogMsg \"Running $testType test iteration #2..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run normal -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"normal#3\"\nLogMsg \"Running $testType test iteration #3..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run normal -testname orion\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\n#all write\n\ntestType=\"oltpWrite100\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run oltp -testname orion -write 100\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"dssWrite100\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run dss -testname orion -write 100\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite100Basic\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 100 -duration 60 -matrix basic\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite100Detailed#1\"\nLogMsg \"Running $testType test iteration #1..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 100 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\n#redo the \"normal\" test\ntestType=\"advancedWrite100Detailed#2\"\nLogMsg \"Running $testType test iteration #2..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 100 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite100Detailed#3\"\nLogMsg \"Running $testType test iteration #3..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 100 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\n#read50% and write 50%\ntestType=\"oltpWrite50\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run oltp -testname orion -write 50 \npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"dssWrite50\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run dss -testname orion -write 50\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite50Basic\"\nLogMsg \"Running $testType test..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 50 -duration 60 -matrix basic\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite50Detailed#1\"\nLogMsg \"Running $testType test iteration #1..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 50 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\n#redo the \"normal\" test\ntestType=\"advancedWrite50Detailed#2\"\nLogMsg \"Running $testType test iteration #2..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 50 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\ntestType=\"advancedWrite50Detailed#3\"\nLogMsg \"Running $testType test iteration #3..\"\ndateTime=\"$(date +\"%m-%d-%Y-%H-%M-%S\")\"\niostat -x -d 1 4000 2>&1 > \"orion-${testType}-${dateTime}.iostat.diskio.log\"  &\nvmstat 1 4000 2>&1 > \"orion-${testType}-${dateTime}.vmstat.memory.cpu.log\"  &\n./orion_x86_64 -run advanced -size_small 8 -size_large 1024 -type rand -simulate concat -write 50 -duration 60 -matrix detailed\npkill -f iostat\npkill -f vmstat\nmv *_iops.csv \"orion-${testType}-${dateTime}-iops.csv\"\nmv *_lat.csv \"orion-${testType}-${dateTime}-lat.csv\"\nmv *_mbps.csv \"orion-${testType}-${dateTime}-mbps.csv\"\nmv *_summary.txt \"orion-${testType}-${dateTime}-summary.txt\"\nmv *_trace.txt \"orion-${testType}-${dateTime}-trace.txt\"\nLogMsg \"$testType test finished.\"\n\nUpdateTestState \"TestCompleted\"\n", "num_lines": 363}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# perf_redis.sh\n# Author : SHITAL SAVEKAR <v-shisav@microsoft.com>\n#\n# Description:\n#    Download and run redis benchmark tests.\n#    This script needs to be run on client VM.\n#\n# Supported Distros:\n#    Ubuntu 16.04\n#######################################################################\n\nCONSTANTS_FILE=\"./constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\ntouch ./redisTest.log\nConfigureRedisUbuntu()\n{\n        LogMsg \"Configuring ${1} for redis test...\"\n        ssh ${1} \"apt-get update\"\n        ssh ${1} \"apt-get -y install libaio1 sysstat gcc\"\n        ssh ${1} \"wget http://download.redis.io/releases/redis-${redisVersion}.tar.gz\"\n        ssh ${1} \"tar -xvf  redis-${redisVersion}.tar.gz && cd redis-${redisVersion}/ && make && make install\"\n        ssh ${1} \"cp -ar redis-${redisVersion}/src/* .\"\n        LogMsg \"${1} configured for Redis.\"\n}\n\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo `date \"+%b %d %Y %T\"` : \"${1}\" >> ./redisTest.log\n}\n\nUpdateTestState()\n{\n    LogMsg \"${1}\" > ./state.txt\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ ! ${server} ]; then\n        errMsg=\"Please add/provide value for server in constants.sh. server=<server ip>\"\n        LogMsg \"${errMsg}\"\n        LogMsg \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\nLogMsg \"Server=${server}\"\n\nif [ ! ${client} ]; then\n        errMsg=\"Please add/provide value for client in constants.sh. client=<client ip>\"\n        LogMsg \"${errMsg}\"\n        LogMsg \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\n\nLogMsg \"Client=${client}\"\nif [ ! ${test_pipeline_collection} ]; then\n        errMsg=\"Please add/provide value for test_pipeline_collection in constants.sh. test_pipeline_collection=(1 2 4 8 16)\"\n        LogMsg \"${errMsg}\"\n        LogMsg \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\nLogMsg \"test_pipeline_collection=${test_pipeline_collection}\"\n\nif [ ! ${redisVersion} ]; then\n        errMsg=\"Please add/provide value for redisVersion in constants.sh. redisVersion=2.8.17\"\n        LogMsg \"${errMsg}\"\n        LogMsg \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\nLogMsg \"redisVersion=${redisVersion}\"\nif [ ! ${redis_test_suites} ]; then\n        errMsg=\"Please add/provide value for redis_test_suites in constants.sh. redis_test_suites=get,set\"\n        LogMsg \"${errMsg}\"\n        LogMsg \"${errMsg}\" >> ./summary.log\n        UpdateTestState $ICA_TESTABORTED\n        exit 1\nfi\n\n#Make & build Redis on client and server Machine\n\nLogMsg \"Configuring client ${client}...\"\nConfigureRedisUbuntu ${client}\n\nLogMsg \"Configuring server ${server}...\"\nConfigureRedisUbuntu ${server}\n\npkill -f redis-benchmark\nssh root@${server} pkill -f redis-server > /dev/null\n\nt=0\nwhile [ \"x${test_pipeline_collection[$t]}\" != \"x\" ]\ndo\n        pipelines=${test_pipeline_collection[$t]}\n        LogMsg \"NEXT TEST: $pipelines pipelines\"\n\n        # prepare running redis-server\n        LogMsg \"Starting redis-server...\"\n        ssh root@${server} \"sar -n DEV 1 900\"   2>&1 > redis-server-pipelines-${pipelines}.sar.netio.log  &\n        ssh root@${server} \"iostat -x -d 1 900\" 2>&1 > redis-server-pipelines-${pipelines}.iostat.diskio.log  &\n        ssh root@${server} \"vmstat 1 900\"       2>&1 > redis-server-pipelines-${pipelines}.vmstat.memory.cpu.log  &\n\n\t\t#start running the redis-server on server\t\t\n        ssh root@${server} \"./redis-server  > /dev/null  &\"\n        LogMsg \"Server started successfully. Sleeping 10 Secondss..\"\n        sleep 10\n\n        # prepare running redis-benchmark\n        sar -n DEV 1 900   2>&1  > redis-client-pipelines-${pipelines}.sar.netio.log &\n        iostat -x -d 1 900 2>&1  > redis-client-pipelines-${pipelines}.iostat.diskio.log &\n        vmstat 1 900       2>&1  > redis-client-pipelines-${pipelines}.vmstat.memory.cpu.log &\n\n        #start running the redis-benchmark on client\n        LogMsg \"Starting redis-benchmark on client...\"\n        LogMsg \"-> Test running with ${pipelines} pipelines.\"\n        ./redis-benchmark -h $server -c 1000 -P $pipelines -t $redis_test_suites -d 4000 -n 10000000 > redis-client-pipelines-${pipelines}.set.get.log\n        LogMsg \"-> done\"\n\n        #cleanup redis-server\n        LogMsg \"Cleaning Server...\"\n        ssh root@${server} pkill -f sar 2>&1 > /dev/null\n        ssh root@${server} pkill -f iostat 2>&1 > /dev/null\n        ssh root@${server} pkill -f vmstat 2>&1 > /dev/null\n        ssh root@${server} pkill -f redis-server 2>&1 > /dev/null\n\n        #cleanup redis-benchmark\n        LogMsg \"Cleaning Client...\"\n        pkill -f sar 2>&1 > /dev/null\n        pkill -f iostat 2>&1 > /dev/null\n        pkill -f vmstat 2>&1 > /dev/null\n        pkill -f redis-benchmark 2>&1 > /dev/null\n        t=$(($t + 1))\n\t\tLogMsg \"Sleeping 30 Seconds...\"\n\t\tsleep 30\ndone\nUpdateTestState ICA_TESTCOMPLETED", "num_lines": 173}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf#!/bin/bash\n./package-download-test.sh\nif [[ $? == 0 ]]; then\n        echo 'PASS' > Summary.log\nelse\n        echo 'FAIL' > Summary.log\nfi\necho 'TestCompleted' > state.txt", "num_lines": 8}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho 'TestRunning' > state.txt\nsudo bash rhui-rpm-source-check.sh > RHUI-BVT-VERIFY-RPM-SOURCE.sh.log\nif [[ $? == 0 ]]; then\n        echo 'PASS' > Summary.log\nelse\n        echo 'FAIL' > Summary.log\nfi\necho 'TestCompleted' > state.txt\n", "num_lines": 10}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# \n# It runs the ycsb bechmark test on given server\n# ./run-ycsb.sh \n#######\nCONSTANTS_FILE=\"/root/constants.sh\"\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nlog_folder=\"/root/benchmark/mongodb/logs\"\n\necho \"Running ycsb benchmark test on server $MD_SERVER\"\nssh root@${MD_SERVER} mkdir -p $log_folder\n\nt=0\nwhile [ \"x${test_threads_collection[$t]}\" != \"x\" ]\ndo\n\tthreads=${test_threads_collection[$t]}\n\techo \"TEST RUNNING WITH: $threads threads\"\n\t# prepare running mongodb-server\n\techo \"prepare running mongodb-server\"\n\tssh root@${MD_SERVER} \"mkdir -p $log_folder/$threads\"\n\tssh root@${MD_SERVER} \"sar -n DEV 1 ${maxexecutiontime}   2>&1 > $log_folder/$threads/$threads-mongodb-server.sar.netio.log \" & \n\tssh root@${MD_SERVER} \"iostat -x -d 1 ${maxexecutiontime} 2>&1 > $log_folder/$threads/$threads-mongodb-server.iostat.diskio.log \" &\n\tssh root@${MD_SERVER} \"vmstat 1 ${maxexecutiontime} 2>&1 > $log_folder/$threads/$threads-mongodb-server.vmstat.memory.cpu.log \" & \n\t\n\t# prepare running mongodb-benchmark(ycsb)\n\techo \"prepare running mongodb-benchmark(ycsb)\"\n\tmkdir -p $log_folder/$threads\n\tsar -n DEV 1 ${maxexecutiontime}   2>&1 > $log_folder/$threads/$threads-mongodb-client.sar.netio.log  & \n\tiostat -x -d 1 ${maxexecutiontime} 2>&1 > $log_folder/$threads/$threads-mongodb-client.iostat.diskio.log &\n\tvmstat 1 ${maxexecutiontime} 2>&1 > $log_folder/$threads/$threads-mongodb-client.vmstat.memory.cpu.log & \n\t\n\t#start running the mongodb(ycsb)-benchmark on client\n\techo \"-> TEST RUNNING with threads $threads ..\"\n\techo \"CMD: ./ycsb-0.5.0/bin/ycsb  run  mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0 -threads $threads > $log_folder/$threads/$threads.ycsb.run.log\"\n\t./ycsb-0.5.0/bin/ycsb  run  mongodb-async -s -P workloadAzure -p mongodb.url=mongodb://${MD_SERVER}:27017/ycsb?w=0 -threads $threads > $log_folder/$threads/$threads-mongodb.ycsb.run.log\n\techo \"-> TEST END with threads $threads\"\n\t\n\t#cleanup mongodb-server\n\techo \"cleanup mongodb-server\"\n\tssh root@${MD_SERVER} pkill -f sar\n\tssh root@${MD_SERVER} pkill -f iostat\n\tssh root@${MD_SERVER} pkill -f vmstat\n\n\t#cleanup mongodb-benchmark(ycsb)\n\techo \"cleanup mongodb-benchmark(ycsb)\"\n\tpkill -f sar\n\tpkill -f iostat\n\tpkill -f vmstat\n\t\n\techo \"sleep 60 seconds\"\n\tsleep 60\n\tt=$(($t + 1))\n\techo \"$t\"\ndone\n", "num_lines": 65}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script collects all the required logs during the network performance test.\n# Author: Srikanth M\n# Email\t: v-srm@microsoft.com\n#\n\nif [[ $# == 3 ]]\nthen\n\tduration=$1\n\tfilename=$2\n\tusername=$3\n\tlogFolder=\"logs-`hostname`\"\nelif [[ $# == 5 ]]\nthen\n\tduration=$1\n\tfilename=$2\n\tusername=$3\n\ttesttype=$4\n\tbuffersize=$5\n\tlogFolder=\"logs-`hostname`-$testtype-$buffersize\"\nelse\n\techo \"Usage: bash $0 <duration> <filename> <username>\"\n\texit -1\nfi\n\ncode_path=\"/home/$username/code/\"\n. $code_path/azuremodules.sh\n\ncapture_cpu(){\n\tfor i in $(seq 1 $duration)\n\tdo\n\t\tdate_j=`date +\"%T\"`\n\t\ttop_j=`top -bn1 | grep \"Cpu(s)\" | sed \"s/.*, *\\([0-9.]*\\)%* id.*/\\1/\" | awk '{print 100 - $1}'`\n\t\techo $date_j,$top_j>> $filename-top.csv\n\t\tsleep 1\n\tdone\n}\n\ncapture_connections(){\n\tfor i in $(seq 1 $duration)\n\tdo\n\t\tdate_i=`date +\"%T\"`\n\t\tnetstat_i=`netstat -natp | grep iperf | grep ESTA | wc -l`\n\t\techo $date_i,$netstat_i >> $filename-connections.csv\n\t\tsleep 1\n\tdone\n}\n\nif [[ `which iperf3` == \"\" ]]\nthen\n    echo \"iperf3 not installed\\n Installing now...\" \n    install_package \"iperf3\" \nfi\n\nif [[ `which sar` == \"\" ]]\nthen\n    echo \"iperf3 not installed\\n Installing now...\" \n    install_package \"sysstat\" \nfi\n\nvm_bus_ver=`modinfo hv_vmbus| grep ^version| awk '{print $2}'`\n\n#logs_dir=$code_path/logs-`hostname`-`uname -r`-`get_lis_version`/$filename\nlogs_dir=$code_path/$logFolder/$filename\nfilename=$logs_dir/$filename\nmkdir -p  $logs_dir\n\necho $filename-top.csv $duration $filename $filename-sar.log \n[ -f $filename-top.csv  ] && rm -rf $filename-top.csv \n[ -f $filename-sar.log  ] && rm -rf $filename-sar.log \n[ -f $filename-vmstat.log  ] && rm -rf $filename-vmstat.log \n[ -f $filename-connections.csv  ] && rm -rf $filename-connections.csv\n\necho \"uname: -------------------------------------------------\" > $filename-sar.log\nuname -a 2>&1 >> $filename-sar.log\necho \"LIS version: --------------------------------------------\" >> $filename-sar.log\nmodinfo hv_vmbus 2>&1 >> $filename-sar.log\necho \"----------------------------------------------------------\" >> $filename-sar.log\necho \"Number of CPU cores\" `nproc` >> $filename-sar.log\necho \"Memory\" `free -h| grep Mem| awk '{print $2}'` >> $filename-sar.log\necho \"Host Build Version\" `dmesg | grep \"Host Build\" | sed \"s/.*Host Build://\"| awk '{print  $1}'| sed \"s/;//\"`  >> $filename-sar.log\n\nsar -n DEV 1 $duration 2>&1 >> $filename-sar.log&\nsar_pid=$!\nvmstat 1 $duration > $filename-vmstat.log&\nvmstat_pid=$!\ncapture_cpu &\ncapture_cpu_pid=$!\ncapture_connections &\ncapture_connections_pid=$!\n\nsleep $duration\nkill -9 $sar_pid $capture_cpu_pid $capture_connections_pid $vmstat_pid\ndmesg > $filename-dmesg.log \nexit 0\n", "num_lines": 97}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script serves as iperf server.\n# Author: Srikanth M\n# Email\t: v-srm@microsoft.com\n#\n\nif [[ $# == 1 ]]\nthen\n\tusername=$1\nelif [[ $# == 3 ]]\nthen\n\tusername=$1\n\ttesttype=$2\n\tbuffersize=$3\nelse\n\techo \"Usage: bash $0 <vm_loginuser>\"\n\texit -1\nfi\n\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during setup of test\nICA_TESTFAILED=\"TestFailed\"        # Error during running of test\n\nLogMsg()\n{\n    echo `date \"+%a %b %d %T %Y\"` : ${1}    # To add the timestamp to the log file\n}\n\nUpdateTestState()\n{\n    echo $1 > $code_path/state.txt\n}\n\n#\n# Create the state.txt file so ICA knows we are running\n#\nLogMsg \"Updating test case state to running\"\nUpdateTestState $ICA_TESTRUNNING\n\ncode_path=\"/home/$username/code\"\n. $code_path/azuremodules.sh\n\nif [[ `which iperf3` == \"\" ]]\nthen\n    echo \"iperf3 not installed\\n Installing now...\"\n    install_package \"iperf3\"\nfi\n\nfor port_number in `seq 8001 8101`\ndo\n\tiperf3 -s -D -p $port_number\ndone\n\nwhile [ `netstat -natp | grep iperf | grep ESTA | wc -l` -eq 0 ]\ndo\n\tsleep 1\n\techo \"waiting...\"\ndone\n\nduration=300\nfor number_of_connections  in 1 2 4 8 16 32 64 128 256 512 1024\ndo\n\tfor port_number in `seq 8001 8501`\n\tdo\n\t\tiperf3 -s -D -p $port_number\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"iperf3 failed to connect server\"\n\t\t\techo \"iperf3 failed to connect server\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 80\n\t\tfi\n\tdone\n\tbash $code_path/sar-top.sh $duration $number_of_connections $username $testtype $buffersize&\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"sar-top failed to execute\"\n\t\techo \"sar-top failed to execute\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 80\n\tfi\n\tsleep $(($duration+10))\ndone\n\nlogs_dir=logs-`hostname`-$testtype-$buffersize\n\ncollect_VM_properties $code_path/$logs_dir/VM_properties.csv\n\nbash $code_path/generate_csvs.sh $code_path/$logs_dir $testtype $buffersize\nif [ $? -ne 0 ]; then\n\tLogMsg \"Failed to generate test results .csv file\"\n\techo \"Failed to generate test results .csv file\"\n\tUpdateTestState $ICA_TESTFAILED\n\texit 80\nfi\nmv /etc/rc.d/after.local.bkp /etc/rc.d/after.local\nmv /etc/rc.local.bkp /etc/rc.local\nmv /etc/rc.d/rc.local.bkp /etc/rc.d/rc.local\necho \"$testtype $buffersize test is Completed at Server\"\n\n#\n# Let ICA know we completed successfully\n#\nLogMsg \"Updating test case state to completed\"\nUpdateTestState $ICA_TESTCOMPLETED", "num_lines": 105}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"DOWNLOADING_KERNEL\"\nwget https://www.kernel.org/pub/linux/kernel/v3.x/linux-3.14.1.tar.xz\nif [ $? = '0' ]; then\n        echo \"KERNEL_DOWNLOADED\"\n        echo \"EXTRACTING_FILES\"\n        tar -xf linux-3.14.1.tar.xz\n        echo \"COPYING_TO_HOME_DIRECTORY\"\n        cp -ar ./linux-3.14.1/* ~\n        echo \"DOWNLOADING_KERNBENCH\"\n        wget http://ck.kolivas.org/apps/kernbench/kernbench-0.50/kernbench\n        if [ $? = '0' ]; then\n                echo \"KERNBENCH_DOWNLOAD_DONE\"\n                chmod +x kernbench\n                echo \"READY_FOR_KERNBENCH_START\"\n        else\n                echo \"KERNBENCH_DOWNLOAD_FAILED\"\n        fi\nelse\n        echo \"KERNEL_DOWNLOAD_FAILED\"\nfi\n", "num_lines": 23}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ni=1\nwhile [ $i = '1' ]\ndo \n\t./kernbench\ndone", "num_lines": 6}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# \n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n# \n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU General Public License for more details.\n# \n#\n# Sample script to run sysbench.\n# In this script, we want to test 3 different devices, all mounted on the same\n# machine.  You can adapt this script to other situations easily.  The only\n# thing to keep in mind is that each different configuration you're testing\n# must log its output to a different directory.\n#\n# For any info contact v-shisav@microsoft.com\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\nPrepareFiles=$PrepareFiles\nRunTest=$RunTest\nCleanUp=$CleanUp\nCustomLogDir=$CustomLogDir\ntestIO=$testIO\ntestThread=$testThread\nioRuntime=$ioRuntime\ntestMode=$testMode\nfileSize=$fileSize\nset -u\nset -x\n#export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/share/oem/bin:/usr/share/oem/python/bin:/opt/bin\n\nFILEIO=\"--test=fileio --file-total-size=${fileSize} --file-extra-flags=dsync --file-fsync-freq=0\"\n#FILEIO=\"--test=fileio --file-total-size=134G \"\n\n####################################\n#All run config set here\n#\nLOGDIR=$CustomLogDir\nmkdir -p $CustomLogDir\nLOGFILE=\"${LOGDIR}/sysbench.log.txt\"\n#FILE PREPARE\necho \"===================================== Starting Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\nif [ \"$PrepareFiles\" = \"yes\" ]; then\n\techo \"\" > $LOGFILE\n\tchmod 666 $LOGFILE\n\techo \"SYSBENCH-FILE-PREPARE-PROGRESS\" > $LOGDIR/CurrentSysbenchStatus.txt\t\n\techo \"Preparing Files: $FILEIO\"\n\techo \"Preparing Files: $FILEIO\" >> $LOGFILE\n\t# Remove any old files from prior runs (to be safe), then prepare a set of new files.\n\tsysbench $FILEIO cleanup\n\techo \"--- Disk Usage Before Generating New Files ---\" >> $LOGFILE\n\tdf >> $LOGFILE\n\tiostatfilename=\"${LOGDIR}/iostat-sysbench-file-prepare.txt\"\n\tnohup iostat -x 5 -t -y > $iostatfilename &\n\tsysbench $FILEIO prepare\n\techo \"--- Disk Usage After Generating New Files ---\" >> $LOGFILE\n\tdf >> $LOGFILE\t\n\techo \"=== End Preparation  $(date +\"%x %r %Z\") ===\" >> $LOGFILE\n\techo \"SYSBENCH-FILE-PREPARE-FINISH\" > $LOGDIR/CurrentSysbenchStatus.txt\n\tiostatPID=`ps -ef | awk '/iostat/ && !/awk/ { print $2 }'`\n\tkill -9 $iostatPID\t\nfi\n#TEST RUN\nif [ \"$RunTest\" = \"yes\" ]; then\n\tiostatfilename=\"${LOGDIR}/iostat-sysbench-${testMode}-${testIO}-${testThread}.txt\"\n\tnohup iostat -x 5 -t -y > $iostatfilename &\n\techo \"------------------------------- ${testMode}, ${testIO}, ${testThread} threads ${ioRuntime} seconds------------------ $(date +\"%x %r %Z\") ---\" >> $LOGFILE\n\techo \"SYSBENCH-TEST-RUNNING-${testMode}-${testIO}K-${testThread}-${ioRuntime}\" > $LOGDIR/CurrentSysbenchStatus.txt\n\tsysbench $FILEIO --file-test-mode=$testMode --file-block-size=${testIO} --max-requests=0 --max-time=$ioRuntime --num-threads=$testThread run >> $LOGFILE\n\tiostatPID=`ps -ef | awk '/iostat/ && !/awk/ { print $2 }'`\n\tkill -9 $iostatPID\n\techo \"SYSBENCH-TEST-FINISHED\" > $LOGDIR/CurrentSysbenchStatus.txt\nfi\n#CLEANUP\nif [ \"$CleanUp\" = \"yes\" ]; then\n\techo \"===================================== Completed Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\n\tsysbench $FILEIO cleanup >> $LOGFILE\nfi", "num_lines": 86}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# \n# usage::-\n# nohup bash sysbench-full-io-test.sh &\n# or\n#./sysbench-full-io-test.sh &\n#\n# For any info contact v-avchat@microsoft.com\n\nset -u\nset -x\n#export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/share/oem/bin:/usr/share/oem/python/bin:/opt/bin\n\nFILEIO=\"--test=fileio --file-total-size=134G --file-extra-flags=dsync --file-fsync-freq=0\"\n#FILEIO=\"--test=fileio --file-total-size=134G \"\n\n####################################\n#All run config set here\n#\n\nif [[ $# == 1 ]]\nthen\n\tusername=$1\nelse\n\techo \"Usage: bash $0 <vm_loginuser>\"\n\texit -1\nfi\ncode_path=\"/home/$username/code\"\n. $code_path/azuremodules.sh\nmv $code_path/sysbenchlog/ $code_path/sysbenchlog-$(date +\"%m%d%Y-%H%M%S\")/\nsleep 5\nmkdir $code_path/sysbenchlog\nLOGDIR=\"${code_path}/sysbenchlog\"\nLOGFILE=\"${LOGDIR}/sysbench.log.txt\"\n\nif [[ `which sysbench` == \"\" ]]\nthen\n\tinstall_package sysbench\n\tcheck_exit_status \"Sysbench package installation\" exit\nfi\n\nif [[ `which iostat` == \"\" ]]\nthen\n\tinstall_package sysstat\n\tcheck_exit_status \"Sysstat package installation\"\nfi\n\necho \"uname: -------------------------------------------------\" > $LOGFILE\nuname -a 2>&1 >> $LOGFILE\necho \"LIS version: --------------------------------------------\" >> $LOGFILE\nmodinfo hv_vmbus 2>&1 >> $LOGFILE\necho \"----------------------------------------------------------\" >> $LOGFILE\necho \"Number of CPU cores\" `nproc` >> $LOGFILE\necho \"Memory\" `free -h| grep Mem| awk '{print $2}'` >> $LOGFILE\necho \"Host Build Version\" `dmesg | grep \"Host Build\" | sed \"s/.*Host Build://\"| awk '{print  $1}'| sed \"s/;//\"`  >> $LOGFILE\necho \"Data disks attached\" `fdisk -l | grep 'Disk.*/dev/sd[a-z]' |awk  '{print $2}' | sed s/://| sort| grep -v \"/dev/sd[ab]$\"| wc -l`  >> $LOGFILE\n\niteration=0\nioruntime=300\nmaxThread=1024\nmaxIo=32\n\n#All possible values for file-test-mode are rndrd rndwr rndrw seqrd seqwr seqrewr\nmodes='rndrd rndwr rndrw seqrd seqrewr'\n#modes='rndrd rndwr rndrw seqrd seqwr seqrewr'\n\nstartThread=1\nstartIO=4\n####################################\n\necho \"Test log created at: ${LOGFILE}\"\necho \"===================================== Starting Run $(date +\"%x %r %Z\") ================================\"\necho \"===================================== Starting Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\n\nchmod 666 $LOGFILE\necho \"Preparing Files: $FILEIO\"\necho \"Preparing Files: $FILEIO\" >> $LOGFILE\n# Remove any old files from prior runs (to be safe), then prepare a set of new files.\nsysbench $FILEIO cleanup\necho \"--- Disk Usage Before Generating New Files ---\" >> $LOGFILE\ndf >> $LOGFILE\nsysbench $FILEIO prepare\necho \"--- Disk Usage After Generating New Files ---\" >> $LOGFILE\ndf >> $LOGFILE\necho \"=== End Preparation  $(date +\"%x %r %Z\") ===\" >> $LOGFILE\n\n####################################\n#Trigger run from here\nfor testmode in $modes; do\n\tio=$startIO\n\twhile [ $io -le $maxIo ]\n\tdo\n\t\tThread=$startThread\n\t\twhile [ $Thread -le $maxThread ]\n\t\tdo\n\t\t\tiostatfilename=\"${LOGDIR}/iostat-sysbench-${testmode}-${io}K-${Thread}.txt\"\n\t\t\tnohup iostat -x 5 -t -y > $iostatfilename &\n\t\t\techo \"-- iteration ${iteration} ----------------------------- ${testmode}, ${io}K, ${Thread} threads, 5 minutes ------------------ $(date +\"%x %r %Z\") ---\" >> $LOGFILE\n\t\t\tsysbench $FILEIO --file-test-mode=$testmode --file-block-size=${io}\"K\" --max-requests=0 --max-time=$ioruntime --num-threads=$Thread run >> $LOGFILE\n\t\t\tiostatPID=`ps -ef | awk '/iostat/ && !/awk/ { print $2 }'`\n\t\t\tkill -9 $iostatPID\n\t\t\tThread=$(( Thread*2 ))\n\t\t\titeration=$(( iteration+1 ))\n\t\tdone\n\t\tio=$(( io*2 ))\n\tdone\ndone\n####################################\necho \"===================================== Completed Run $(date +\"%x %r %Z\") script generated 2/9/2015 4:24:44 PM ================================\" >> $LOGFILE\nsysbench $FILEIO cleanup >> $LOGFILE\n\n\ncompressedFileName=\"SysbenchIOTest\"$(date +\"%m%d%Y-%H%M%S\")\".tar.gz\"\necho \"Please wait...Compressing all results to ${compressedFileName}...\"\ntar -cvzf $compressedFileName $LOGDIR/*.txt\nmv $compressedFileName $LOGDIR/$compressedFileName\n####################################\nfind_log_diff () {\nLogMax=`(echo \"l($1)/l(2)\" | bc -l| sed 's/\\..*$//')`\nLogMin=`(echo \"l($2)/l(2)\" | bc -l| sed 's/\\..*$//')`\ndiff=$(($LogMax - $LogMin + 1))\necho $diff\n}\n\nIO_difference=`find_log_diff $maxIo $startIO`\nThread_difference=`find_log_diff $maxThread $startThread`\nTotal_Modes=`echo $modes| wc -w`\ntotal_iterations=$(($IO_difference * $Thread_difference *Total_Modes - 1))\necho $total_iterations\n\nlast_iteration=`tail -150 $LOGFILE | grep iteration| tail -1 | awk '{print $3}'`\n\nif [ $last_iteration == $total_iterations ]\nthen\n\techo \"SYSBENCH TEST COMPLETED\" >> $LOGFILE\n\techo \"SYSBENCH TEST COMPLETED\"\nelse\n\techo \"SYSBENCH TEST ABORTED\" >> $LOGFILE\n\techo \"SYSBENCH TEST ABORTED\"\nfi\n\n####################################\nbash $code_path/sysbench-log-parser.sh $LOGFILE\n\necho \"Test logs are located at ${LOGDIR}\"\n\nvm_bus_ver=`modinfo hv_vmbus| grep ^version| awk '{print $2}'`\ntar -cvf $code_path/logs-`hostname`-`uname -r`-$vm_bus_ver.tar $code_path/*\n", "num_lines": 149}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script converts Sysbench IO output file into csv format.\n# Author: Srikanth Myakam\n# Email\t: v-srm@microsoft.com\n####\n\nsyslog_file_name=$1\n\nif [ \"$#\" -ne 1 ]; then\n  echo \"Usage: $0 <sysbench-output.log>\" >&2\n  exit 1\nfi\n\nif [ ! -f $syslog_file_name ]; then\n    echo \"$1: File not found!\"\n\texit 1\nfi\n\ncsv_file=`echo $syslog_file_name | sed s/\\.log\\.txt//`\ncsv_file=$csv_file.csv\necho $csv_file\n\nres_AvgLatency=(`cat $syslog_file_name | grep \"avg:\" | awk '{print $2}' | sed s/ms//`)\nres_BlockSize=(`cat $syslog_file_name | grep \"Block size \"| sed \"s/Block size //\"`)\nres_FileSize=(`cat $syslog_file_name | grep \"total file size\"| sed \"s/ total file size//\"`)\nres_IOMode=(`cat $syslog_file_name | grep \"Using .* I/O mode\" | sed 's/Using \\(.*\\) I\\/O mode/\\1/'`)\nres_IOPS=(`cat $syslog_file_name | grep \"Requests/sec executed\"| awk '{print $1}'`)\nres_Iteration=(`cat $syslog_file_name | grep \"iteration \"| awk '{print $3}'`)\nres_MaxLatency=(`cat $syslog_file_name | grep \"max:\" | awk '{print $2}' | sed s/ms//`)\nres_MinLatency=(`cat $syslog_file_name | grep \"min:\" | awk '{print $2}' | sed s/ms//`)\nres_OtherOperations=(`cat $syslog_file_name | grep \"Operations performed:\"| awk  '{print $7}'`)\nres_PercentileLatency=(`cat $syslog_file_name | grep \"approx.  95 percentile:\" | awk '{print $4}' | sed s/ms//`)\nres_ReadBytes=(`cat $syslog_file_name | grep \"Read \"| awk '{print $2}'`)\nres_ReadOperations=(`cat $syslog_file_name | grep \"Operations performed:\"| awk  '{print $3}'`)\nres_StartTime=(`cat $syslog_file_name | grep \"iteration \"| awk '{print $12 \":\" $13 \":\" $14}'`)\nres_TestType=(`cat $syslog_file_name | grep \"iteration\"| awk  '{print $5}'| sed s/,//`)\nres_Throughput=(`cat $syslog_file_name | grep \"Read \" | awk '{print $8}' | sed s/\\(//| sed s/\\)//`)\nres_TotalEvents=(`cat $syslog_file_name | grep \"total number of events:\"  | awk '{print $5}'`)\nres_TotalOperations=(`cat $syslog_file_name | grep \"Operations performed:\"| awk  '{print $10}'`)\nres_TotalTime=(`cat $syslog_file_name | grep \"total time: \" | awk '{print $3}'| sed s/s//`)\nres_WriteBytes=(`cat $syslog_file_name | grep \"Read \"| awk '{print $4}'`)\nres_WriteOperations=(`cat $syslog_file_name | grep \"Operations performed:\"| awk  '{print $5}'`)\nres_threads=(`cat $syslog_file_name | grep \"Number of threads:\" | sed \"s/Number of threads: //\"`)\nres_TotalBytes=(`cat $syslog_file_name | grep \"Read \"| awk '{print $7}'`)\nres_kernel_version=(`cat $syslog_file_name | grep \"Linux.*x86_64.*GNU\"| awk '{print $3}'`)\nres_total_cpu_cores=(`cat $syslog_file_name| grep \"Number of CPU cores\" | awk '{print $5}'`)\nres_LIS_version=(`cat $syslog_file_name| grep \"^version:\"| awk '{print $2}'`)\nres_Host_version=(`cat $syslog_file_name| grep \"Host Build Version\" | awk '{print $4}'`)\nres_total_memory=(`cat $syslog_file_name |grep \"^Memory\" | awk '{print $2}'`)\nres_total_disks=(`cat $syslog_file_name |grep \"^Data disks attached\" | awk '{print $4}'`)\n\nif [ \"x$res_LIS_version\" == \"x\" ]\nthen\n\tres_LIS_version=\"Default LIS Version\"\nfi\n\necho \"\" > $csv_file-tmp\necho \",VM Properties,\" >> $csv_file-tmp\necho \",Kernel version,\"$res_kernel_version >> $csv_file-tmp\necho \",Total CPU cores,\"$res_total_cpu_cores >> $csv_file-tmp\necho \",Memory,\"$res_total_memory >> $csv_file-tmp\necho \",Disks,\"$res_total_disks >> $csv_file-tmp\necho \",LIS Version,\"$res_LIS_version >> $csv_file-tmp\necho \",Host Version,\"$res_Host_version >> $csv_file-tmp\necho \"\" >> $csv_file-tmp\n\necho \"Iteration,StartTime,Threads,FileSize,BlockSize,IOMode,TestType,ReadOperations,WriteOperations,OtherOperations,TotalOperations,ReadBytes,WriteBytes,TotalBytes,Throughput,IOPS,TotalTime(s),TotalEvents,MinLatency(ms),AvgLatency(ms),MaxLatency(ms), 95% PercentileLatency(ms)\" > $csv_file\n\ncount=0\n\nwhile [ \"x${res_Iteration[$count]}\" != \"x\" ]\ndo\n\techo \"${res_Iteration[$count]}, ${res_StartTime[$count]}, ${res_threads[$count]}, ${res_FileSize[$count]}, ${res_BlockSize[$count]}, ${res_IOMode[$count]},  ${res_TestType[$count]}, ${res_ReadOperations[$count]}, ${res_WriteOperations[$count]}, ${res_OtherOperations[$count]}, ${res_TotalOperations[$count]}, ${res_ReadBytes[$count]}, ${res_WriteBytes[$count]}, ${res_TotalBytes[$count]}, ${res_Throughput[$count]}, ${res_IOPS[$count]}, ${res_TotalTime[$count]}, ${res_TotalEvents[$count]}, ${res_MinLatency[$count]}, ${res_AvgLatency[$count]}, ${res_MaxLatency[$count]}, ${res_PercentileLatency[$count]}, \"  >> $csv_file\n\t((count++))\ndone\n\necho \",Max IOPS of each mode,\" >> $csv_file-tmp\necho \",Test Mode Max IOPS,\" >> $csv_file-tmp\nmodes='rndrd rndwr rndrw seqrd seqwr seqrewr'\nfor testmode in $modes \ndo\n\tmax_iops=`cat $csv_file | grep $testmode | sed 's/.*\\/sec,//'| sed  's/,.*$//'| sed \"s/\\\\..*//\"| sort -g|tail -1`\n\tif  [ \"x$max_iops\" != \"x\" ]\n\tthen\n\t\techo \",$testmode,$max_iops,\" >> $csv_file-tmp\n\tfi\ndone\n\necho \"\" >> $csv_file-tmp\necho \",Max IOPS of each BlockSize,\" >> $csv_file-tmp\nmodes='rndrd rndwr rndrw seqrd seqwr seqrewr'\nblock_sizes='1K 2K 4K 8K 16K 32K'\necho \",Test Mode,Block Size,Max IOPS,\" >> $csv_file-tmp\nfor testmode in $modes \ndo\n\tfor block in $block_sizes \n\tdo\n\t\tmax_iops=`cat $csv_file | grep $testmode | grep \" $block\" | sed 's/.*\\/sec,//'| sed  's/,.*$//'| sed \"s/\\\\..*//\"| sort -g|tail -1`\n\t\tif  [ \"x$max_iops\" != \"x\" ]\n\t\tthen\n\t\t\techo \",$testmode,$block,$max_iops,\" >> $csv_file-tmp\n\t\tfi\n\tdone\ndone\n\necho \"\" >> $csv_file-tmp\ncat $csv_file >> $csv_file-tmp\nmv $csv_file-tmp $csv_file\n\nsed -i  -e  \"s/rndrd/Random Read/\" $csv_file\nsed -i  -e  \"s/rndrw/Random Read Write/\" $csv_file\nsed -i  -e  \"s/rndwr/Random Write/\" $csv_file\nsed -i  -e  \"s/seqrd/Sequential Read/\" $csv_file\nsed -i  -e  \"s/seqrewr/Sequential Read Write/\" $csv_file\nsed -i  -e  \"s/seqwr/Sequential Write/\" $csv_file\n\necho \"Output csv file: $csv_file created successfully.\" >> $syslog_file_name\necho \"LOGPARSER COMPLETED.\" >> $syslog_file_name\n", "num_lines": 120}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved. \n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0  \n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n# \n#\n# Description:\n#######################################################################\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nmaster=$master\nslaves=$slaves\n\n#\n# Constants/Globals\n#\nCONSTANTS_FILE=\"/root/constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\nCurrentMachine=\"\"\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    echo `date \"+%b %d %Y %T\"` : \"${1}\"    # Add the time stamp to the log message\n    echo \"${1}\" >> ~/rdmaPreparation.log\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > ~/state.txt\n}\n\nPrepareForRDMA()\n{\n\tssh root@${1} \"test -e etcHostsEditedSuccessfully\"\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"${1} : Editing /etc/hosts\"\n\t\tscp etc-hosts.txt root@${1}:\n\t\tssh root@${1} \"cat etc-hosts.txt >> /etc/hosts\"\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"${1} : Unable to edit /etc/hosts.\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 1\n\t\tfi\n\tfi\n\tssh root@${1} touch etcHostsEditedSuccessfully\n\n\tLogMsg \"${1} : Installing RDMA package...\"\n\tssh root@${1} yum -y install rdma\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"${1} : Unable to install RDMA package.\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\tLogMsg \"${1} : Enabling RDMA...\"\n\tssh root@${1} chkconfig rdma on\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"${1} : Unable to enable RDMA\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\n\tLogMsg \"${1} : Installing required packages...\"\n\tssh root@${1} yum install -y libmlx4 libibverbs librdmacm\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"${1} : Unable to install some packges.\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\tLogMsg \"${1} : Installing dapl...\"\n\tssh root@${1} yum install -y dapl\n\tif [ $? -ne 0 ]; then\n\t\tLogMsg \"${1} : Unable to install some packges.\"\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\tfi\n\n\tLogMsg \"${1} : Installing IBM binaries..\"\n\tssh root@${1} test -e platform_mpi-09.01.02.00u.x64.bin\n\tif [ $? -eq 0 ]; then\n\t\tLogMsg \"${1} : IBM binary already exists.\"\n\telse\n\t\tLogMsg \"${1} : Downloading https://ciwestus.blob.core.windows.net/linuxbinaries/platform_mpi-09.01.02.00u.x64.bin...\"\n\t\tssh root@${1} wget -q https://ciwestus.blob.core.windows.net/linuxbinaries/platform_mpi-09.01.02.00u.x64.bin\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"${1} : Unable to download platform_mpi-09.01.02.00u.x64.bin\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 1\n\t\tfi\n\tfi\n\t\n\tssh root@${1} test -e /opt/ibm/platform_mpi/bin/mpirun\n\tif [ $? -eq 0 ]; then\n\t\tLogMsg \"${1} : IBM binaries already installed\"\n\telse\n\t\tssh root@${1} chmod +x platform_mpi-09.01.02.00u.x64.bin\n\t\tLogMsg \"${1} : Installing prerequisites...\"\n\t\tssh root@${1} yum -y install gcc-c++\n\t\tssh root@${1} yum -y install libgcc.i686\n\t\tssh root@${1} yum -y install glibc.i686\n\t\tssh root@${1} yum -y install libstdc++-4.8.5-4.el7.i686\n\t\tssh root@${1} yum -y install redhat-lsb redhat-lsb*i686\n\t\tLogMsg \"${1} : Installing platform_mpi-09.01.02.00u.x64.bin...\"\n\t\tssh root@${1} ./platform_mpi-09.01.02.00u.x64.bin -i silent\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"${1} : Unable to install platform_mpi-09.01.02.00u.x64.bin\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 1\n\t\tfi\n\t\tLogMsg \"${1} : IBM binaries installed.\"\n\tfi\n\t\n\tLogMsg \"${1} : Installing Intel MPI binaries on ${1}..\"\n\tssh root@${1} test -e l_mpi_p_5.1.3.181.tgz\n\tif [ $? -eq 0 ]; then\n\t\tLogMsg \"${1} : binary already exists.\"\n\telse\n\t\tLogMsg \"${1} : Downloading https://ciwestus.blob.core.windows.net/linuxbinaries/l_mpi_p_5.1.3.181.tgz...\"\n\t\tssh root@${1} wget -q https://ciwestus.blob.core.windows.net/linuxbinaries/l_mpi_p_5.1.3.181.tgz\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"${1} : Unable to download l_mpi_p_5.1.3.181.tgz\"\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 1\n\t\tfi\n\tfi\n\tssh root@${1} test -d /opt/intel/impi\n\tif [ $? -eq 0 ]; then\n\t\tLogMsg \"${1} : Intel binaries already installed.\"\n\telse\n\n\t\tssh root@${1} tar -xvzf l_mpi_p_5.1.3.181.tgz\n\t\tssh root@${1} sed -i '/ACCEPT_EULA/c\\ACCEPT_EULA=accept' ./l_mpi_p_5.1.3.181/silent.cfg\n\t\tssh root@${1} sed -i '/ACTIVATION_TYPE/c\\ACTIVATION_TYPE=trial_lic' ./l_mpi_p_5.1.3.181/silent.cfg\n\t\tLogMsg \"${1} : Installing l_mpi_p_5.1.3.181...\"\n\t\tssh root@${1} ./l_mpi_p_5.1.3.181/install.sh --silent ./l_mpi_p_5.1.3.181/silent.cfg\n\t\tif [ $? -ne 0 ]; then\n\t\t\tLogMsg \"${1} : Unable to install Intel MPI binaries.\"\n\t\t\tcd /root\n\t\t\tUpdateTestState $ICA_TESTFAILED\n\t\t\texit 1\n\t\tfi\n\t\tLogMsg \"${1} : Intel binaries installed.\"\n\tfi\n\tLogMsg \"${1} : Setting up nfs...\"\n\tssh root@${1} yum -y install nfs-utils.x86_64\n\tssh root@${1} mkdir -p /mirror\n\tssh root@${1} chmod -R 777 /mirror/\n\t#ssh root@${1} test -e limits.conf.editedSuccessfully\n\t#if [ $? -ne 0 ]; then\n\t#\tLogMsg \"${1} : Editing /etc/security/limits.conf\"\n\t#\techo \"* hard    memlock unlimited\" | ssh root@${1} \"cat >> /etc/security/limits.conf\"\n\t#\techo \"* soft    memlock unlimited\" | ssh root@${1} \"cat >> /etc/security/limits.conf\"\n\t#\tif [ $? -ne 0 ]; then\n\t#\t\tLogMsg \"${1} : Unable to edit /etc/security/limits.conf\"\n\t#\t\tUpdateTestState $ICA_TESTFAILED\n\t#\t\texit 1\n\t#\tfi\n\t#fi\n\t#ssh root@${1} touch limits.conf.editedSuccessfully\n\t\n\tssh root@${1} rm -rf /etc/exports\n\techo '/mirror *(rw,sync)' | ssh root@${1} \"cat >> /etc/exports\"\n\n\tssh root@${1} systemctl enable rpcbind\n\tssh root@${1} systemctl enable nfs-server\n\tssh root@${1} systemctl start rpcbind\n\tssh root@${1} systemctl start nfs-server\n\tssh root@${1} systemctl start nfs-lock\n\tssh root@${1} systemctl start nfs-idmap\t\n\n\tssh root@${1} touch rdmaPrepared\n}\n\nrm -f ~/summary.log\ntouch ~/summary.log\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nif [ \"${installLocal}\" != \"yes\" ]; then\n\tif [ ! ${master} ]; then\n\t\terrMsg=\"Please add/provide value for master in constants.sh. master=<Master VM hostname>\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ~/summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\n\tif [ ! ${slaves} ]; then\n\t\terrMsg=\"Please add/provide value for slaves in constants.sh. slaves=<hostname1,hostname2,hostname3>\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ~/summary.log\n\t\tUpdateTestState $ICA_TESTABORTED\n\t\texit 1\n\tfi\nfi\n\nif [ \"${rdmaPrepare}\" != \"yes\" ] && [ \"${rdmaPrepare}\" != \"no\" ]; then\n\terrMsg=\"Please add/provide value for rdmaPrepare in constants.sh. rdmaPrepare=<yes>/<no>\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\nif [ \"${rdmaRun}\" != \"yes\" ] && [ \"${rdmaRun}\" != \"no\" ]; then\n\terrMsg=\"Please add/provide value for rdmaRun in constants.sh. rdmaRun=<yes>/<no>\"\n    LogMsg \"${errMsg}\"\n    echo \"${errMsg}\" >> ~/summary.log\n\tUpdateTestState $ICA_TESTABORTED\n\texit 1\nfi\n\nslavesArr=`echo ${slaves} | tr ',' ' '`\n\nif [ \"${rdmaPrepare}\" == \"yes\" ]; then\n\n\t# master VM preparation for RDMA tests...\n\t\n\tif [ ${installLocal} == \"yes\" ]; then\n\t\tlocalVM=`hostname`\n\t\tssh root@${localVM} test -e rdmaPrepared\n\t\tif [ $? -ne 0 ]; then \n\t\t\tLogMsg \"Info : Running config on current machine : '${localVM}'\"\n\t\t\tPrepareForRDMA \"${localVM}\"\n\t\telse\n\t\t\tLogMsg \"${localVM} is already prepared for RDMA tests.\" \n\t\tfi\n\telse\n\t\tssh root@${master} test -e rdmaPrepared\n\t\tif [ $? -ne 0 ]; then \n\t\t\tLogMsg \"Info : Running config on master : '${master}'\"\n\t\t\tPrepareForRDMA \"${master}\"\n\t\telse\n\t\t\tLogMsg \"${master} is already prepared for RDMA tests.\" \n\t\tfi\n\n\t\t# slave VMs preparation for RDMA tests...\n\t\tfor slave in $slavesArr\n\t\tdo\n\t\t\tssh root@${slave} test -e rdmaPrepared\n\t\t\tif [ $? -ne 0 ]; then \n\t\t\t\tLogMsg \"Info : Running config on slave '${slave}'\"\n\t\t\t\tPrepareForRDMA \"${slave}\"\n\t\t\t\tLogMsg \"Info : mounting ${master}:/mirror NFS directory to /mirror on '${slave}'\"\n\t\t\t\tssh root@${slave} mount ${master}:/mirror /mirror\n\t\t\telse\n\t\t\t\tLogMsg \"${slave} is already prepared for RDMA tests.\" \n\t\t\tfi\n\t\tdone\n\tfi\nelse\n\tLogMsg \"Info : Skipping RDMA preparation. (Source : constants.sh)\"\nfi\n\nif [ \"${rdmaRun}\" == \"yes\" ];\nthen\n\tmpirunPath=`find / -name mpirun | grep intel64`\n\timb_mpi1Path=`find / -name IMB-MPI1 | grep intel64`\n\teth1server=`ifconfig eth1 | grep \"inet \"`\n\teth1ServerStatus=$?\n\teth1client=`ssh root@${slaves} \"ifconfig eth1 | grep 'inet '\"`\n\teth1ClientStatus=$?\n\teth1Status=$(( $eth1ServerStatus + $eth1ClientStatus ))\n\tif [ $eth1Status -eq 0 ];\n\tthen\n\t\tLogMsg \"eth1 IP detected for server and client.\"\n\telse\n\t\tLogMsg \"Error: eth1 failed to get IP address.\"\n\t\tLogMsg \"Checking if NetworkManager is running...\"\n\t\tservice NetworkManager status\n\t\tif [ $? -eq 0 ]; then\n\t\t\tLogMsg \"Info: NetworkManager is running. Stopping it.\"\n\t\t\tservice NetworkManager stop\n\t\t\tsleep 5\n\t\t\tssh root@${slaves} \"service NetworkManager stop\"\n\t\t\tsleep 5\n\t\t\tLogMsg \"Info: restart waagent service...\"\n\t\t\tservice waagent restart\n\t\t\tsleep 5\n\t\t\tservice waagent restart\n\t\t\tssh root@${slaves} \"service waagent restart\"\n\t\t\tsleep 5\n\t\tfi\t\t\n\tfi\n\tLogMsg \"Executing test command : ${mpirunPath} -hosts ${master},${slaves} -ppn 2 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 ${imb_mpi1Path} pingpong > pingPongTestIntraNodeTestOut.txt 2>&1\"\n\t#MPI-pingpong intra node\n\t$mpirunPath -hosts ${master} -ppn 2 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestIntraNodeTestOut.txt 2>&1\n\tmpiStatus1=$?\n\tsleep 20\n\t#MPI-pingpong inter node\n\tLogMsg \"Executing test command : $mpirunPath -hosts ${master},${slaves} -ppn 1 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestInterNodeTestOut.txt 2>&1\"\n\t$mpirunPath -hosts ${master},${slaves} -ppn 1 -n 2 -env I_MPI_FABRICS dapl -env I_MPI_DAPL_PROVIDER=ofa-v2-ib0 $imb_mpi1Path pingpong > pingPongTestInterNodeTestOut.txt 2>&1\n\tmpiStatus2=$?\n\tfinalStatus=$(( $eth1Status + $mpiStatus1 + $mpiStatus2 ))\n\tif [ $finalStatus -ne 0 ];\n\tthen\n\t\terrMsg=\"Failures detected. eth1 Status: $eth1Status, IntraNodeTestStatus: $mpiStatus1, InterNodeTestStatus: $mpiStatus2\"\n\t\tLogMsg \"${errMsg}\"\n\t\techo \"${errMsg}\" >> ~/summary.log\n\t\tUpdateTestState $ICA_TESTFAILED\n\t\texit 1\n\telse\n\t\tUpdateTestState $ICA_TESTCOMPLETED\n\t\tLogMsg \"eth1 Status: $eth1Status, IntraNodeTestStatus: $mpiStatus1, InterNodeTestStatus: $mpiStatus2\"\n\tfi\nfi\n", "num_lines": 347}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#######################################################################\n#\n# Linux on Hyper-V and Azure Test Code, ver. 1.0.0\n# Copyright (c) Microsoft Corporation\n#\n# All rights reserved.\n# Licensed under the Apache License, Version 2.0 (the \"\"License\"\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS\n# OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION\n# ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR\n# PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.\n#\n# See the Apache Version 2.0 License for specific language governing\n# permissions and limitations under the License.\n#\n#######################################################################\n\n#######################################################################\n#\n#\n#\n# Description:\n#######################################################################\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nmaster=$master\nslaves=$slaves\nrm -rf /root/TestRDMALogs.txt\n#\n# Constants/Globals\n#\nCONSTANTS_FILE=\"/root/constants.sh\"\nICA_TESTRUNNING=\"TestRunning\"      # The test is running\nICA_TESTCOMPLETED=\"TestCompleted\"  # The test completed successfully\nICA_TESTABORTED=\"TestAborted\"      # Error during the setup of the test\nICA_TESTFAILED=\"TestFailed\"        # Error occurred during the test\nCurrentMachine=\"\"\nimb_mpi1_finalStatus=0\nimb_rma_finalStatus=0\nimb_nbc_finalStatus=0\n#######################################################################\n#\n# LogMsg()\n#\n#######################################################################\nLogMsg()\n{\n    timeStamp=`date \"+%b %d %Y %T\"`\n    echo \"$timeStamp : ${1}\"    # Add the time stamp to the log message\n    echo \"$timeStamp : ${1}\" >> /root/TestRDMALogs.txt\n}\n\nUpdateTestState()\n{\n    echo \"${1}\" > /root/state.txt\n}\n\nPrepareForRDMA()\n{\n        # TODO\n        echo Doing Nothing\n}\n#Get all the Kernel-Logs from all VMs.\nCollectKernelLogs()\n{\n    slavesArr=`echo ${slaves} | tr ',' ' '`\n    for vm in $master $slavesArr\n    do\n                    LogMsg \"Getting kernel logs from $vm\"\n                    ssh root@${vm} \"dmesg > kernel-logs-${vm}.txt\"\n                    scp root@${vm}:kernel-logs-${vm}.txt .\n                    if [ $? -eq 0 ];\n                    then\n                                    LogMsg \"Kernel Logs collected successfully from ${vm}.\"\n                    else\n                                    LogMsg \"Error: Failed to collect kernel logs from ${vm}.\"\n                    fi\n\n    done\n}\n\nCompressFiles()\n{\n    compressedFileName=$1\n    pattern=$2\n    LogMsg \"Compressing ${pattern} files into ${compressedFileName}\"\n    tar -cvzf ${compressedFileName} ${pattern}*\n    if [ $? -eq 0 ];\n    then\n            LogMsg \"${pattern}* files compresssed successfully.\"\n            LogMsg \"Deleting local copies of ${pattern}* files\"\n            rm -rvf ${pattern}*\n    else\n            LogMsg \"Error: Failed to compress files.\"\n            LogMsg \"Don't worry. Your files are still here.\"\n    fi\n}\n\nif [ -e ${CONSTANTS_FILE} ]; then\n    source ${CONSTANTS_FILE}\nelse\n    errMsg=\"Error: missing ${CONSTANTS_FILE} file\"\n    LogMsg \"${errMsg}\"\n    UpdateTestState $ICA_TESTABORTED\n    exit 10\nfi\n\nslavesArr=`echo ${slaves} | tr ',' ' '`\nmpirunPath=`find / -name mpirun | grep intel64`\nLogMsg \"MPIRUN Path: $mpirunPath\"\nimb_mpi1Path=`find / -name IMB-MPI1 | grep intel64`\nLogMsg \"IMB-MPI1 Path: $imb_mpi1Path\"\nimb_rmaPath=`find / -name IMB-RMA | grep intel64`\nLogMsg \"IMB-RMA Path: $imb_rmaPath\"\nimb_nbcPath=`find / -name IMB-NBC | grep intel64`\nLogMsg \"IMB-NBC Path: $imb_nbcPath\"\n\n#Verify if eth1 got IP address on All VMs in current cluster.\nfinaleth1Status=0\ntotalVMs=0\nslavesArr=`echo ${slaves} | tr ',' ' '`\nfor vm in $master $slavesArr\ndo\n                LogMsg \"Checking eth1 status in $vm\"\n                temp=`ssh root@${vm} \"ifconfig eth1 | grep 'inet '\"`\n                eth1Status=$?\n                ssh root@${vm} \"ifconfig eth1 > eth1-status-${vm}.txt\"\n                scp root@${vm}:eth1-status-${vm}.txt .\n                if [ $eth1Status -eq 0 ];\n                then\n                                LogMsg \"eth1 IP detected for ${vm}.\"\n                else\n                                LogMsg \"Error: eth1 failed to get IP address for ${vm}.\"\n                fi\n                finaleth1Status=$(( $finaleth1Status + $eth1Status ))\n                totalVMs=$(( $totalVMs + 1 ))\ndone\nif [ $finaleth1Status -ne 0 ]; then\n                LogMsg \"ERROR: Some VMs did get IP address for eth1. Aborting Tests\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_ETH1\"               \n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_ETH1\"                \nfi\n\n\n\n##Verify MPI Tests\n\n#Verify PingPong Tests (IntraNode).\nfinalMpiIntranodeStatus=0\nslavesArr=`echo ${slaves} | tr ',' ' '`\nfor vm in $master $slavesArr\ndo\n                LogMsg \"$mpirunPath -hosts $vm -ppn $mpi1_ppn -n $mpi1_ppn $mpi_settings $imb_mpi1Path pingpong\"\n                LogMsg \"Checking IMB-MPI1 Intranode status in $vm\"\n                ssh root@${vm} \"$mpirunPath -hosts $vm -ppn $mpi1_ppn -n $mpi1_ppn $mpi_settings $imb_mpi1Path pingpong > IMB-MPI1-IntraNode-pingpong-output-$vm.txt\"\n                mpiIntranodeStatus=$?\n                scp root@${vm}:IMB-MPI1-IntraNode-pingpong-output-$vm.txt .\n                if [ $mpiIntranodeStatus -eq 0 ];\n                then\n                                LogMsg \"IMB-MPI1 Intranode status in $vm - Succeeded.\"\n                else\n                                LogMsg \"IMB-MPI1 Intranode status in $vm - Failed\"\n                fi\n                finalMpiIntranodeStatus=$(( $finalMpiIntranodeStatus + $mpiIntranodeStatus ))\ndone\n\nif [ $finalMpiIntranodeStatus -ne 0 ]; then\n                LogMsg \"ERROR: IMB-MPI1 Intranode test failed in somes VMs. Aborting further tests.\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_MPI1_INTRANODE\"\n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_MPI1_INTRANODE\"                \nfi\n\n#Verify PingPong Tests (InterNode).\nfinalMpiInternodeStatus=0\nslavesArr=`echo ${slaves} | tr ',' ' '`\nfor vm in $slavesArr\ndo\n        LogMsg \"$mpirunPath -hosts $master,$vm -ppn $mpi1_ppn -n $(( $mpi1_ppn * 2 )) $mpi_settings $imb_mpi1Path pingpong\"\n        LogMsg \"Checking IMB-MPI1 InterNode status in $vm\"\n        $mpirunPath -hosts $master,$vm -ppn $mpi1_ppn -n $(( $mpi1_ppn * 2 )) $mpi_settings $imb_mpi1Path pingpong > IMB-MPI1-InterNode-pingpong-output-${master}-${vm}.txt\n        mpiInternodeStatus=$?\n        if [ $mpiInternodeStatus -eq 0 ];\n        then\n                        LogMsg \"IMB-MPI1 Internode status in $vm - Succeeded.\"\n        else\n                        LogMsg \"IMB-MPI1 Internode status in $vm - Failed\"\n        fi\n        finalMpiInternodeStatus=$(( $finalMpiInternodeStatus + $mpiInternodeStatus ))\ndone\n\nif [ $finalMpiInternodeStatus -ne 0 ]; then\n                LogMsg \"ERROR: IMB-MPI1 Internode test failed in somes VMs. Aborting further tests.\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_MPI1_INTERNODE\"\n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_MPI1_INTERNODE\"                \nfi\n\n#Verify IMB-MPI1 (pingpong & allreduce etc) tests.\nAttempts=`seq 1 1 $imb_mpi1_tests_iterations`\nimb_mpi1_finalStatus=0\nfor i in $Attempts;\ndo\n                if [[ $imb_mpi1_tests == \"all\" ]];\n                then\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path\"\n                    LogMsg \"IMB-MPI1 test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path > IMB-MPI1-AllNodes-output-Attempt-${i}.txt\n                    mpiStatus=$?\n                else\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path $imb_mpi1_tests\"\n                    LogMsg \"IMB-MPI1 test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $mpi1_ppn -n $(( $mpi1_ppn * $totalVMs )) $mpi_settings $imb_mpi1Path $imb_mpi1_tests > IMB-MPI1-AllNodes-output-Attempt-${i}.txt\n                    mpiStatus=$?\n                fi\n                if [ $mpiStatus -eq 0 ];\n                then\n                                LogMsg \"IMB-MPI1 test iteration $i - Succeeded.\"\n                                sleep 1\n                else\n                                LogMsg \"IMB-MPI1 test iteration $i - Failed.\"\n                                imb_mpi1_finalStatus=$(( $imb_mpi1_finalStatus + $mpiStatus ))\n                                sleep 1\n                fi\ndone\n\nif [ $imb_mpi1_tests_iterations -gt 5 ];\nthen\n    CompressFiles \"IMB-MPI1-AllNodes-output.tar.gz\" \"IMB-MPI1-AllNodes-output-Attempt\"\nfi\n\nif [ $imb_mpi1_finalStatus -ne 0 ]; then\n                LogMsg \"ERROR: IMB-MPI1 tests returned non-zero exit code.\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_MPI1_ALLNODES\"\n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_MPI1_ALLNODES\"                \n                \nfi\n\n#Verify IMB-RMA tests.\nAttempts=`seq 1 1 $imb_rma_tests_iterations`\nimb_rma_finalStatus=0\nfor i in $Attempts;\ndo\n                if [[ $imb_rma_tests == \"all\" ]];\n                then\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath\"\n                    LogMsg \"IMB-RMA test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath > IMB-RMA-AllNodes-output-Attempt-${i}.txt\n                    rmaStatus=$?\n                else\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath $imb_rma_tests\"\n                    LogMsg \"IMB-RMA test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $rma_ppn -n $(( $rma_ppn * $totalVMs )) $mpi_settings $imb_rmaPath $imb_rma_tests > IMB-RMA-AllNodes-output-Attempt-${i}.txt\n                    rmaStatus=$?\n                fi\n                if [ $rmaStatus -eq 0 ];\n                then\n                                LogMsg \"IMB-RMA test iteration $i - Succeeded.\"\n                                sleep 1\n                else\n                                LogMsg \"IMB-RMA test iteration $i - Failed.\"\n                                imb_rma_finalStatus=$(( $imb_rma_finalStatus + $rmaStatus ))\n                                sleep 1\n                fi\ndone\n\nif [ $imb_rma_tests_iterations -gt 5 ];\nthen\n    CompressFiles \"IMB-RMA-AllNodes-output.tar.gz\" \"IMB-RMA-AllNodes-output-Attempt\"\nfi\n\nif [ $imb_rma_finalStatus -ne 0 ]; then\n                LogMsg \"ERROR: IMB-RMA tests returned non-zero exit code. Aborting further tests.\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_RMA_ALLNODES\"\n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_RMA_ALLNODES\"                \nfi\n\n#Verify IMB-NBC tests.\nAttempts=`seq 1 1 $imb_nbc_tests_iterations`\nimb_nbc_finalStatus=0\nfor i in $Attempts;\ndo\n                if [[ $imb_nbc_tests == \"all\" ]];\n                then\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath\"\n                    LogMsg \"IMB-NBC test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath > IMB-NBC-AllNodes-output-Attempt-${i}.txt\n                    nbcStatus=$?\n                else\n                    LogMsg \"$mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath $imb_nbc_tests\"\n                    LogMsg \"IMB-NBC test iteration $i - Running.\"\n                    $mpirunPath -hosts $master,$slaves -ppn $nbc_ppn -n $(( $nbc_ppn * $totalVMs )) $mpi_settings $imb_nbcPath $imb_nbc_tests > IMB-NBC-AllNodes-output-Attempt-${i}.txt\n                    nbcStatus=$?\n                fi\n                if [ $nbcStatus -eq 0 ];\n                then\n                                LogMsg \"IMB-NBC test iteration $i - Succeeded.\"\n                                sleep 1\n                else\n                                LogMsg \"IMB-NBC test iteration $i - Failed.\"\n                                imb_nbc_finalStatus=$(( $imb_nbc_finalStatus + $nbcStatus ))\n                                sleep 1\n                fi\ndone\n\nif [ $imb_rma_tests_iterations -gt 5 ];\nthen\n    CompressFiles \"IMB-NBC-AllNodes-output.tar.gz\" \"IMB-NBC-AllNodes-output-Attempt\"\nfi\n\nif [ $imb_nbc_finalStatus -ne 0 ]; then\n                LogMsg \"ERROR: IMB-RMA tests returned non-zero exit code. Aborting further tests.\"\n                UpdateTestState $ICA_TESTFAILED\n                CollectKernelLogs\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED_NBC_ALLNODES\"\n                exit 0\nelse\n                LogMsg \"INFINIBAND_VERIFICATION_SUCCESS_NBC_ALLNODES\"                \nfi\n\nCollectKernelLogs\n\nfinalStatus=$(( $eth1Status +  $finalMpiIntranodeStatus + $finalMpiInternodeStatus + $imb_mpi1_finalStatus + $imb_rma_finalStatus + $imb_nbc_finalStatus ))\nif [ $finalStatus -ne 0 ];\nthen\n                LogMsg LogMsg \"eth1Status: $eth1Status,  finalMpiIntranodeStatus:$finalMpiIntranodeStatus, finalMpiInternodeStatus:$finalMpiInternodeStatus, imb_mpi1_finalStatus:$imb_mpi1_finalStatu, imb_rma_finalStatus:$imb_rma_finalStatus, imb_nbc_finalStatus:$imb_nbc_finalStatus\"\n                UpdateTestState $ICA_TESTFAILED\n                LogMsg \"INFINIBAND_VERIFICATION_FAILED\"\nelse\n                UpdateTestState $ICA_TESTCOMPLETED\n                LogMsg \"INFINIBAND_VERIFIED_SUCCESSFULLY\"\nfi", "num_lines": 363}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "# This script is meant for quick & easy install via:\ncurl -fsSL get.docker.com -o get-docker.sh\nsh get-docker.sh\n\nsystemctl status docker > /dev/null\ndockerServiceStatus=$?\nsystemctl status docker > ./dockerServiceStatusLogs.txt\ndocker version > dockerVersion.txt\n\nif [ $dockerServiceStatus -eq 0 ];then\n\techo \"DOCKER_VERIFIED_SUCCESSFULLY\"\nelse\n\techo \"DOCKER_VERIFICATION_FAILED\"\nfi\n\n#TODO : More Tests\n\n\n#TODO Cleanup\n", "num_lines": 20}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#Verify Installation of waaagent\n\nif [ -e /etc/init.d/waagent ]; then\n\t\n\techo \"Verify Install waagent : Success\"\nelse\n\techo \"Verify Install waagent : Failed\"\n\texit\n\nfi\n", "num_lines": 12}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo 'iface eth0 inet6 auto' >> /etc/network/interfaces.d/50-cloud-init.cfg\necho 'up sleep 5' >> /etc/network/interfaces.d/50-cloud-init.cfg\necho 'up dhclient -1 -6 -cf /etc/dhcp/dhclient6.conf -lf /var/lib/dhcp/dhclient6.eth0.leases -v eth0 || true' >> /etc/network/interfaces.d/50-cloud-init.cfg\nifdown eth0 && ifup eth0", "num_lines": 4}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n# THIS SCRIPT DETECT FOLLOWING DISTROS:\n#  UBUNTU [VERSION INDEPENDANT]\n#  CENTOS [VERSION INDEPENDANT]\n#  SUSE LINUX ENTERPRISE SERVER [VERSION INDEPENDANT]\n#  OPENSUSE [VERSION INDEPENDANT]\n#  REDHAT\n#  ORACLELINUX\n#  FEDORA\nDetectDistro()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n        if [ -e /etc/debian_version ]; then\n\t\t        tmp=`cat /etc/*-release`\n                if [[ \"$tmp\" == *Ubuntu* ]]; then\n                    echo \"UBUNTU\"\n                    exitVal=0\n                else\n                    echo \"DEBIAN\"\n                    exitVal=0\n                fi\n        elif [ -e /etc/redhat-release ]; then\n                tmp=`cat /etc/redhat-release`\n                if [ -e /etc/oracle-release ]; then\n                    tmp=`cat /etc/oracle-release`\n                    if [[ \"$tmp\" == *Oracle* ]]; then\n                        echo \"ORACLELINUX\"\n                        exitVal=0\n                    else\n                        echo \"Unknown\"\n                        exitVal=1\n                    fi\n                elif [[ \"$tmp\" == *CentOS* ]]; then\n                    echo \"CENTOS\"\n                    exitVal=0\n                elif [[ \"$tmp\" == *Fedora* ]]; then\n                    echo \"FEDORA\"\n                    exitVal=0\n                elif [[ \"$tmp\" == *Red* ]]; then\n                    echo \"REDHAT\"\n                    exitVal=0\n                else\n                    echo \"Unknown\"\n                    exitVal=1\n                fi\n        elif [ -e /etc/SuSE-release ]; then\n                tmp=`cat /etc/SuSE-release`\n                if [[ \"$tmp\" == *Enterprise* ]]; then\n                    echo \"SLES\"\n                    exitVal=0\n                elif [[ \"$tmp\" == *open* ]]; then\n                    echo \"SUSE\"\n                    exitVal=0\n                else\n                    echo \"Unknown\"\n                fi\n        elif [ -e /etc/os-release ]; then\n                tmp=`cat /etc/os-release`\n                if [[ \"$tmp\" == *coreos* ]]; then\n                    echo \"COREOS\"\n                    exitVal=0\n                fi\n        elif [ -e /usr/share/clear/version ]; then\n                tmp=`cat /usr/share/clear/version`\n                echo \"CLEARLINUX\"\n                exitVal=0\n        fi\nreturn $exitVal\n}\nDetectDistro", "num_lines": 75}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n#HOW TO PARSE THE ARGUMENTS.. SOURCE - http://stackoverflow.com/questions/4882349/parsing-shell-script-arguments\n\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\npackageName=$install\nisRemote=$isRemote\nisLocal=$isLocal\nfileName=$file\nCurrentDate=`date`\n\ninstallFromFolder()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\nsourceFolder=$sourceFolder\ncd $sourceFolder\nls\nif [ -e ./configure ]; then\n    chmod +x configure && ./configure && make && make install\n    exitVal=$?\nelif [ -e ./setup.py ]; then\n    python setup.py build && python setup.py install\n    exitVal=$?\nfi\ncd ..\nreturn $exitVal\n}\n\ngetFolderName()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ncompressedFile=$compressedFile\nif [[ \"$compressedFile\" == *.tar.gz ]]; then\n    folderName=${compressedFile%.tar.gz*}\nelif [[ \"$compressedFile\" == *.tar ]]; then\n    folderName=${compressedFile%.tar.bz2*}\nelif [[ \"$compressedFile\" == *.tar ]]; then\n    folderName=${compressedFile%.tar*}\nfi\necho $folderName\n}\n\ninstallFromCompressedFile()\n{\n#{\n#   extract the source code.\n#   invoke : decompressFile -file $fileName\n#   search for installation files in extracted folder. Like - setup.py / configure / make etc.\n#   invoke \"appropriate\" installation method.. [installPythonSourceCode() / installMakeSourceCode() / ...]\n#   return exit code.\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ncompressedFile=$compressedFile\ndecompressFile -fileToDecompress $compressedFile\ninstallFolder=`getFolderName -compressedFile $compressedFile`\necho \"$installFolder\"\ninstallFromFolder -sourceFolder $installFolder\nexitVal=$?\n\nreturn $exitVal\n}\n\ndecompressFile()\n{\n#   determine the extraction method depending on *.tar, *.tar.gz, *.bz2, *.gzip etc.\n#   execute : tar -xzf / gunzip / bzip etc. and untar the compressed file.\n#   return exit code.\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\nfileToDecompress=$fileToDecompress\nif [[ \"$installFile\" == *.tar ]]; then\n    tar -xzvf $fileToDecompress\n        #installFromCompressedFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.tar.gz ]]; then\n    tar -xvf $fileToDecompress\n    exitVal=$?\nfi\n\nif [ $exitVal == 0 ]; then\n    echo \"Decompresssion Successfull\"\nelse\n    echo \"Decompresssion Failed\"\nfi\nreturn $exitVal\n\n}\n#other installation methods support can be added depending on requirement.\n\ninstallLocalFile()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\n\ninstallFile=$LocalFile\nif [[ ( \"$installFile\" == *.tar ) || ( \"$installFile\" == *.tar.gz ) || ( \"$installFile\" == *.tar.bz2 ) ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing from copressed file\"\n    installFromCompressedFile -compressedFile $installFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.rpm ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing rpm file\"\n    rpm -ivh $installFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.deb ]]; then\n    echo \"provided file $installFile\"\n    echo \"Installing deb file\"\n    dpkg -i $installFile\n    exitVal=$?\nelif [[ \"$installFile\" == *.sh ]]; then\n    echo \"provided file $installFile\"\n    echo \"Executing shell script ...\"\n    chmod +x $installFile\n\tdos2unix $installFile\n    ./$installFile\n    exitVal=$?\nelif [ -z $installFile ]; then\n    echo \"Please provide file with -file <filename> argument\"\n    exitVal=1\nelse\n    echo \"Unknowin file type..\"\n    exitVal=1\nfi\nreturn $exitVal\n}\ninstallRemotePackage()\n{\nwhile echo $1 | grep ^- > /dev/null; do\n    eval $( echo $1 | sed 's/-//g' | tr -d '\\012')=$2\n    shift\n    shift\ndone\npackageName=$install\n        if [ -e /etc/debian_version ]; then\n                apt-get install --force-yes -y $packageName\n                installStatus=$?\n                if [ $installStatus = 0 ]; then\n                        echo \"Install $packageName : InstallSuccess\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\n        if [ -e /etc/redhat-release ]; then\n                sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf\n                yum install --nogpgcheck -y $packageName\n                installStatus=$?\n                if [ $installStatus = \"0\" ]; then\n                        echo \"Install $packageName : InstallSuccess\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\n        if [ -e /etc/SuSE-release ]; then\n                zypper --non-interactive --no-gpg-checks install $packageName\n                installStatus=$?\n                if [ $installStatus = \"0\" ]; then\n                        echo \"Install $packageName : InstallSuccess\"\n                        exitVal=0\n                else\n                        echo \"Install $packageName : FAILED\"\n                        exitVal=1\n                fi\n        fi\nreturn $exitVal\n}\nupdateDistro()\n{\n    if [ -e /etc/debian_version ]; then\n        apt-get --force-yes -y update\n        installStatus=$?\n        if [ $installStatus = 0 ]; then\n            echo \"Install Update : InstallSuccess\"\n            exitVal=0\n        else\n        echo \"Install Update : FAILED\"\n        exitVal=1\n        fi\n    fi\n    if [ -e /etc/redhat-release ]; then\n            sed -i 's/exclude=kernel/#exclude=kernel/' /etc/yum.conf\n        yum --nogpgcheck -y update\n        installStatus=$?\n        if [ $installStatus = \"0\" ]; then\n            echo \"Install Update : InstallSuccess\"\n            exitVal=0\n        else\n            echo \"Install Update : FAILED\"\n            exitVal=1\n        fi\n    fi\n    if [ -e /etc/SuSE-release ]; then\n        zypper --non-interactive --no-gpg-checks update\n        installStatus=$?\n        if [ $installStatus = \"0\" ]; then\n            echo \"Updated successfully..\"\n            exitVal=0\n        else\n            echo \"Update failed..\"\n            exitVal=1\n        fi\n    fi\n\nreturn $exitVal\n}\n\n# main body starts here..\n\nif [ \"$packageName\" = \"UpdateCurrentDistro\" ]; then\n    updateDistro\n    installStatus=$?\n    if [ $installStatus = \"0\" ]; then\n        echo \"Install $packageName : InstallSuccess\"\n        exitVal=0\n    else\n        echo \"Install $packageName  : FAILED\"\n        exitVal=1\n    fi\n\n    exit $exitVal\nelse\n    if [ -z $packageName ]; then\n        echo \"No packages are given to install. Please use -package <Package Name>\"\n        exitVal=0\n    else\n        if [ -z $isLocal ]; then\n            echo \"Please mention -isLocal yes/no\"\n        elif [ \"$isLocal\" = \"no\" ]; then\n                installRemotePackage -install $packageName\n                exitVal=$?\n        elif [ \"$isLocal\" = \"yes\" ]; then\n                installLocalFile -LocalFile $fileName\n\t\t\t\tinstallStatus=$?\n                if [ $installStatus = \"0\" ]; then\n                    echo \"Install $packageName : InstallSuccess\"\n                    exitVal=0\n                else\n                    echo \"Install packageName : FAILED\"\n                    exitVal=1\n                fi\n        else\n            echo \"Please provide -isLocal yes or -isLocal no [CaSe SensitivE]\"\n        fi\n    fi\nfi\nexit $exitVal\n\n", "num_lines": 277}
{"repo_name": "azure-linux-automation", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#V-SHISAV@MICROSOFT.COM\n\n", "num_lines": 4}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nproj_name=\"aem\"\nproj_version=\"1.0\"\n\nproj_full_name=\"$proj_name-$proj_version\"\n\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\n\nbuild_dir=$root/build\ntarget_dir=$build_dir/$proj_full_name\n\nmkdir -p $build_dir\nmkdir -p $target_dir\n\ncd $root/clib\nmake clean\n\ncp -r $root/nodejs $build_dir\ncd $build_dir/nodejs\nnpm pack\n\ncp -r $root/clib $target_dir\ncp $build_dir/nodejs/*.tgz $target_dir\ncp $root/bin/setup.sh $target_dir\nchmod +x $root/bin/setup.sh\n\n#install.sh is a self-extracting script.\n#The begin of this file is sh script while the end is a tar\necho \"#!/bin/bash\"                              >  $build_dir/install.sh\necho \"#\"                                        >> $build_dir/install.sh\necho \"#Auto-generated. Do NOT edit this file.\"  >> $build_dir/install.sh\necho \"#\"                                        >> $build_dir/install.sh\necho \"root=\\$(dirname \\$0)\"                     >> $build_dir/install.sh\necho \"cd \\$root\"                                >> $build_dir/install.sh\necho \"root=\\`pwd\\`\"                             >> $build_dir/install.sh\necho \"if [ -d $proj_full_name ]; then\"          >> $build_dir/install.sh\necho \"    echo \\\"[INFO]Remove old package...\\\"\" >> $build_dir/install.sh\necho \"    rm $proj_full_name -rf\"               >> $build_dir/install.sh\necho \"fi\"                                       >> $build_dir/install.sh\necho \"echo \\\"[INFO]Unpacking...\\\"\"              >> $build_dir/install.sh\necho \"sed -e '1,/^exit$/d' \"\\$0\" | tar xzf -\"   >> $build_dir/install.sh\necho \"$proj_full_name/setup.sh\"                 >> $build_dir/install.sh\necho \"exit\"                                     >> $build_dir/install.sh\ncd $build_dir\ntar czf - $proj_full_name                       >> $build_dir/install.sh\nchmod +x $build_dir/install.sh\n\n\ncp -r $root/clib $build_dir\ncd $build_dir\ntar czf clib.tar.gz clib/\n\n", "num_lines": 56}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ninstall_log=`pwd`/install.log\nroot=$(dirname $0)\ncd $root\nroot=`pwd`\n\nif [[ $EUID -ne 0 ]]; then\n    echo \"[ERROR]This script must be run as root\" 1>&2\n    exit 1\nfi\n\nfunction install_nodejs_tarball()\n{\n    version=\"v0.10.37\"\n    node_version=\"node-$version-linux-x64\"\n    src=\"$root/$node_version\"\n    target=\"/usr/local\"\n\n    echo \"[INFO]Installing nodejs from http://nodejs.org/dist/$version/${node_version}.tar.gz\"\n    if [ -f ${src}.tar.gz ]; then\n        rm ${src}.tar.gz -f\n    fi\n    if [ -d ${src} ]; then\n        rm ${src} -rf\n    fi\n    wget http://nodejs.org/dist/$version/${node_version}.tar.gz 1>>$install_log 2>&1\n    tar -zxf ${node_version}.tar.gz  1>>$install_log 2>&1\n\n    echo \"[INFO]Install nodejs to $target\"\n    if [ -f $target/bin/node ]; then\n        rm $target/bin/node -f\n    fi\n    cp $src/bin/node $target/bin/node\n    \n    echo \"[INFO]Create link to $target/bin/node\"\n    if [ -f /usr/bin/node ]; then\n        rm /usr/bin/node -f\n    fi\n    ln -s $target/bin/node /usr/bin/node\n   \n    echo \"[INFO]Install npm\"\n    curl -sL https://www.npmjs.org/install.sh | sh 1>>$install_log 2>&1\n\n}\n\nfunction install_nodejs()\n{\n    echo \"[INFO]Installing nodejs and npm\"\n    if [ \"$(type apt-get 2>/dev/null)\" != \"\" ] ; then\n        curl -sL https://deb.nodesource.com/setup | bash - 1>>$install_log 2>&1\n        apt-get -y install nodejs 1>>$install_log 2>&1\n    elif [ \"$(type yum 2>/dev/null)\" != \"\" ] ; then\n        curl -sL https://rpm.nodesource.com/setup | bash - 1>>$install_log 2>&1\n        yum -y install nodejs 1>>$install_log 2>&1\n    else\n        install_nodejs_tarball \n    fi\n    if [ ! $? ]; then\n        echo \"[ERROR]Install nodejs and npm failed. See $install_log.\"\n        exit 1\n    fi\n}\n\necho \"[INFO]Checking dependency...\"\necho \"\" > $install_log\nif [ \"$(type node 2>/dev/null)\" == \"\" ]; then\n    install_nodejs\nfi\necho \"[INFO]  nodejs version: $(node --version)\"\n\nif [ \"$(type npm 2>/dev/null)\" == \"\" ]; then\n    install_nodejs\nfi\necho \"[INFO]  npm version: $(npm -version)\"\n\nif [ \"$(type azure 2> /dev/null)\" == \"\" ]; then\n    echo \"[INFO]Installing azure-cli\"\n    npm install -g azure-cli 1>>$install_log 2>&1\n    if [ ! $? ]; then\n        echo \"[ERROR]Install azure-cli failed. See $install_log.\"\n        exit 1\n    fi\nfi\necho \"[INFO]  azure-cli version: $(azure --version)\"\n\nnpm_pkg=\"azure-linux-tools-1.0.0.tgz\"\necho \"[INFO]Installing Azure Enhanced Monitor tools...\"\nif [ -f ./$npm_pkg ]; then\n    npm install -g ./$npm_pkg 1>>$install_log 2>&1\n    if [ ! $? ]; then\n        echo \"[ERROR]Install Azure Enhanced Monitor tools failed. See $install_log.\"\n        exit 1\n    fi\nelse\n    echo \"[ERROR] Couldn't find npm package $npm_pkg\"\n    exit 1\nfi\n\necho \"[INFO]Finished.\"\n", "num_lines": 101}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource ./agent.version\n\necho \"AGENT_VERSION=$AGENT_VERSION\"\necho \"MDSD_DEB_PACKAGE_NAME=$MDSD_DEB_PACKAGE_NAME\"\necho \"MDSD_RPM_PACKAGE_NAME=$MDSD_RPM_PACKAGE_NAME\"\n\n\n# updating HandlerManifest.json\n# check for \"version\": \"x.x.x\",\nsed -i \"s/\\\"version\\\".*$/\\\"version\\\": \\\"$AGENT_VERSION\\\",/g\" HandlerManifest.json\n\n# updating agent.py\nsed -i \"s/^BundleFileNameDeb = .*$/BundleFileNameDeb = '$MDSD_DEB_PACKAGE_NAME'/\" agent.py\nsed -i \"s/^BundleFileNameRpm = .*$/BundleFileNameRpm = '$MDSD_RPM_PACKAGE_NAME'/\" agent.py\n\n# updating manifest.xml\n# check <Version>...</Version>\nsed -i -e \"s|<Version>[0-9a-z.]\\{1,\\}</Version>|<Version>$AGENT_VERSION</Version>|g\" manifest.xml\n", "num_lines": 21}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -e\nsource agent.version\n\nusage()\n{\n    local basename=`basename $0`\n    echo \"usage: ./$basename <path to mdsd-<version>.{.deb, .rpm}> [path for zip output]\"\n}\n\ninput_path=$1\noutput_path=$2\nPACKAGE_NAME=\"azuremonitor$AGENT_VERSION.zip\"\nif [[ \"$1\" == \"--help\" ]]; then\n    usage\n    exit 0\nelif [[ ! -d $input_path ]]; then\n    echo \"DEB/RPM files path '$input_path' not found\"\n    usage\n    exit 1\nfi\n\nif [[ \"$output_path\" == \"\" ]]; then\n    output_path=\"../\"\nfi\n\n# Packaging starts here\ncp -r ../Utils .\ncp ../Common/WALinuxAgent-2.0.16/waagent .\n\ncp -r  ../LAD-AMA-Common/metrics_ext_utils .\ncp -r  ../LAD-AMA-Common/telegraf_utils .\ncp -r  ../Diagnostic/services .\n\n# cleanup packages, ext\nrm -rf packages MetricsExtensionBin ext/future amaCoreAgentBin agentLauncherBin\nmkdir -p packages MetricsExtensionBin ext/future amaCoreAgentBin agentLauncherBin\n\n# copy shell bundle to packages/\ncp $input_path/azuremonitoragent_$AGENT_VERSION* packages/\ncp $input_path/azuremonitoragent-$AGENT_VERSION* packages/\ncp $input_path/MetricsExtension* MetricsExtensionBin/\ncp $input_path/amacoreagent amaCoreAgentBin/\ncp $input_path/agentlauncher agentLauncherBin/\n\n# copy just the source of python-future\ncp -r ext/python-future/src/* ext/future\n\n# make the shim.sh file executable\nchmod +x shim.sh\n\n# sync the file copy\nsync\n\nif [[ -f $output_path/$PACKAGE_NAME ]]; then\n    echo \"Removing existing $PACKAGE_NAME ...\"\n    rm -f $output_path/$PACKAGE_NAME\nfi\n\necho \"Packaging extension $PACKAGE_NAME to $output_path\"\nexcluded_files=\"agent.version packaging.sh apply_version.sh update_version.sh\"\nzip -r $output_path/$PACKAGE_NAME * -x $excluded_files \"./test/*\" \"./extension-test/*\" \"./references\" \"./ext/python-future/*\" \"./ext/future/future/backports/test/*\"\n\n# cleanup newly added dir or files\nrm -rf Utils/ waagent\n", "num_lines": 66}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This is the main driver file for AMA extension. This file first checks if Python 3 or 2 is available on the VM \n# and if yes then uses that Python (if both are available then, default is set to python3) to run extension operations in agent.py\n# Control arguments passed to the shim are redirected to agent.py without validation.\n\nCOMMAND=\"./agent.py\"\nPYTHON=\"\"\nFUTURE_PATH=\"\"\nARG=\"$@\"\n\nfunction find_python() {\n    local python_exec_command=$1\n    local future_path=$2\n\n    if command -v python3 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python3\"\n        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment\n    elif command -v python2 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python2\"\n        eval ${future_path}=\"${PWD}/ext/future:\"\n    elif command -v /usr/libexec/platform-python >/dev/null 2>&1 ; then\n        # If a user-installed python isn't available, check for a platform-python. This is typically only used in RHEL 8.0.\n        echo \"User-installed python not found. Using /usr/libexec/platform-python as the python interpreter.\"\n        eval ${python_exec_command}=\"/usr/libexec/platform-python\"\n        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment\n    fi\n}\n\nfind_python PYTHON FUTURE_PATH\n\nif [ -z \"$PYTHON\" ] # If python is not installed, we will fail the install with the following error, requiring cx to have python pre-installed\nthen\n    echo \"No Python interpreter found, which is an AMA extension dependency. Please install Python 3, or Python 2 if the former is unavailable.\" >&2\n    exit 52 # Missing Dependency\nelse\n    ${PYTHON} --version 2>&1\nfi\n\nPYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}\nexit $?\n", "num_lines": 42}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -x\n\nif [[ \"$1\" == \"--help\" ]]; then\n    echo \"update_version.sh <AGENT_VERSION> <MDSD_DEB_PACKAGE_NAME> <MDSD_RPM_PACKAGE_NAME>\"\n    exit 0\nfi\n\nUPDATE_DATE=`date +%Y%m%d`\nAGENT_VERSION=$1\nMDSD_DEB_PACKAGE_NAME=$2\nMDSD_RPM_PACKAGE_NAME=$3\n\nif [[ \"$AGENT_VERSION\" == \"\" ]]; then\n    echo \"AGENT_VERSION version is empty\"\n    exit 1\nfi\n\nif [[ \"$MDSD_DEB_PACKAGE_NAME\" == \"\" ]]; then\n    echo \"MDSD_DEB_PACKAGE_NAME is empty\"\n    exit 1\nfi\n\nif [[ \"$MDSD_RPM_PACKAGE_NAME\" == \"\" ]]; then\n    echo \"MDSD_RPM_PACKAGE_NAME is empty\"\n    exit 1\nfi\n\n\nsed -i \"s/^AGENT_VERSION=.*$/AGENT_VERSION=$AGENT_VERSION/\" agent.version\nsed -i \"s/^MDSD_DEB_PACKAGE_NAME=.*$/MDSD_DEB_PACKAGE_NAME=$MDSD_DEB_PACKAGE_NAME/\" agent.version\nsed -i \"s/^MDSD_RPM_PACKAGE_NAME=.*$/MDSD_RPM_PACKAGE_NAME=$MDSD_RPM_PACKAGE_NAME/\" agent.version\nsed -i \"s/^AGENT_VERSION_DATE=.*$/AGENT_VERSION_DATE=$UPDATE_DATE/\" agent.version\n", "num_lines": 34}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nCOMMAND=\"./modules/main.py\"\nPYTHON=\"\"\nFUTURE_PATH=\"\"\nTST_VERSION=\"1.3\"  # update when changes are made to TST\nARG=\"$@\"\n\ndisplay_help() {\n    echo \"OPTIONS\"\n    echo \"  -A              Run All Troubleshooting Tool checks\"\n    echo \"  -L              Run Log Collector\"\n    echo \"  -v, --version   Print Troubleshooting Tool version\"\n}\n\nfind_python() {\n    local python_exec_command=$1\n    local future_path=$2\n\n    if command -v python3 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python3\"\n        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment\n    elif command -v python2 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python2\"\n        eval ${future_path}=\"${PWD}/ext/future:\"\n    elif command -v /usr/libexec/platform-python >/dev/null 2>&1 ; then\n        # If a user-installed python isn't available, check for a platform-python. This is typically only used in RHEL 8.0.\n        echo \"User-installed python not found. Using /usr/libexec/platform-python as the python interpreter.\"\n        eval ${python_exec_command}=\"/usr/libexec/platform-python\"\n        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment\n    fi\n}\n\nfind_python PYTHON FUTURE_PATH\n\nif [ -z \"$PYTHON\" ] # If python is not installed, we will fail the install with the following error, requiring cx to have python pre-installed\nthen\n    echo \"No Python interpreter found, which is an AMA extension dependency. Please install Python 3, or Python 2 if the former is unavailable.\" >&2\n    exit 1\nelse\n    echo \"Python version being used is:\"\n    ${PYTHON} --version 2>&1\n    echo \"\"\nfi\n\nif [ \"$1\" = \"--help\" ] || [ \"$1\" = \"-h\" ]\nthen\n    display_help\nelif [ \"$1\" = \"--version\" ] || [ \"$1\" = \"-v\" ]\nthen\n    echo \"AMA Troubleshooting Tool v.$TST_VERSION\"\nelse\n    echo \"Starting AMA Troubleshooting Tool v.$TST_VERSION...\"\n    echo \"\"\n    PYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}\nfi\nexit $?\n", "num_lines": 58}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# The shim scripts provide a single entry point for CSE and will invoke the customscript.py entry point using the\n# appropriate python interpreter version.\n# Arguments passed to the shim layer are redirected to the invoked script without any validation.\n\nCOMMAND=\"./customscript.py\"\nPYTHON=\"\"\nARG=\"$@\"\n\nfunction find_python(){\n    local python_exec_command=$1\n\n    # Check if there is python defined.\n    if command -v python >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python\"\n    else\n        # Python was not found. Searching for Python3 now.\n        if command -v python3 >/dev/null 2>&1 ; then\n            eval ${python_exec_command}=\"python3\"\n        fi\n    fi\n}\n\nfind_python PYTHON\n\nif [ -z \"$PYTHON\" ]\nthen\n   echo \"No Python interpreter found on the box\" >&2\n   exit 51 # Not Supported\nelse\n    echo \"Found: `${PYTHON} --version`\"\nfi\n\n${PYTHON} ${COMMAND} ${ARG}\nexit $?\n\n# DONE", "num_lines": 38}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to set up a test env for extensions\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nscript=$(dirname $0)\nroot=$script\ncd $root\nroot=`pwd`\n\necho \"Run unit test:\"\nls test_*.py\nls test_*.py | sed -e 's/\\.py//'|xargs python -m unittest\n", "num_lines": 28}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfor i in $(seq 1500)\ndo\n    echo `date` + The script is running...\n    >&2 echo `date` + ERROR:The script is running...\n    sleep 1\ndone\n", "num_lines": 9}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# A shell script utility to decrypt the extension's protected settings for debugging purpose\n# Must be run at /var/lib/waagent/Microsoft.Azure.Diagnostics.LinuxDiagnostic-.../\n# with the settings file path (e.g., config/0.settings) as the only cmdline arg\n\nif [ $# -lt 1 ]; then\n    echo \"Usage: $0 <ext_settings_file_path>\"\n    exit 1\nfi\n\nthumbprint=$(jq -r '.runtimeSettings[].handlerSettings.protectedSettingsCertThumbprint' $1)\njq -r '.runtimeSettings[].handlerSettings.protectedSettings' $1 | base64 --decode | openssl smime -inform DER -decrypt -recip ../$thumbprint.crt -inkey ../$thumbprint.prv | jq .\n", "num_lines": 14}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfor test in watchertests test_commonActions test_lad_logging_config test_lad_config_all test_LadDiagnosticUtil \\\n                test_builtin test_lad_ext_settings; do\n    python -m tests.$test\ndone\n", "num_lines": 7}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# This is the main driver file for LAD extension. This file first checks if Python 2 is available on the VM and exits early if not\n# Control arguments passed to the shim are redirected to diagnostic.py without validation.\n\nCOMMAND=\"./diagnostic.py\"\nPYTHON=\"\"\nARG=\"$@\"\n\nfunction find_python() {\n    local python_exec_command=$1\n\n    if command -v python2 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python2\"\n    fi\n}\n\nfind_python PYTHON\n\nif [ -z \"$PYTHON\" ] # If python2 is not installed, we will fail the install with the following error, requiring cx to have python pre-installed\nthen\n    echo \"No Python 2 interpreter found, which is an LAD extension dependency. Please install Python 2 before retrying LAD extension deployment.\" >&2\n    exit 52 # Missing Dependency\nelse\n    ${PYTHON} --version 2>&1\nfi\n\n${PYTHON} ${COMMAND} ${ARG}\nexit $?", "num_lines": 29}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT license.\n\n# This will build mdsd and its libraries\n# Usage: see Usage()\n#\n\nTotalErrors=0\n\nBuildType=\nCCompiler=gcc\nCXXCompiler=g++\nBuildName=dev\nBUILDDIR=builddir\nMakeFileOnly=0\nParallelism=\"-j4\"\n\n# If CodeCoverage=1, build with code coverage options.\n# NOTE: only gcc is supported and it must be debug build.\nCodeCoverage=OFF\n\nUsage()\n{\n    echo \"Usage: $0 <-a> | <-d|-o> <-c|-g> [-b buildname] [-mC] [-p parallelism] [-s] [-t]\"\n    echo \"    -b: use buildname. Default: timestamp.\"\n    echo \"    -C: capture code coverage.\"\n    echo \"    -d: build debug build.\"\n    echo \"    -m: create makefiles only. After done, run 'make help' for options.\"\n    echo \"    -o: build optimized(release) build.\"\n    echo \"    -p: specify number of parallel compile operations (default 4).\"\n}\n\nif [ \"$#\" == \"0\" ]; then\n    Usage\n    exit 1\nfi\n\nargs=`getopt b:Cdhmop: $*`\nif [ $? != 0 ]; then\n    Usage\n    exit 1\nfi\nset -- $args\n\nfor i; do\n    case \"$i\" in\n        -b)\n            BuildName=$2\n            shift ; shift ;;\n        -C)\n            CodeCoverage=ON\n            shift ;;\n        -d)\n            if [ -z \"${BuildType}\" ]; then\n                BuildType=d\n            else\n                echo \"Error: build type is already set to be ${BuildType}.\"\n                exit 1\n            fi\n            shift ;;\n        -h)\n            Usage\n            exit 0\n            shift ;;\n        -m)\n            MakeFileOnly=1\n            shift ;;\n        -o)\n            if [ -z \"${BuildType}\" ]; then\n                BuildType=o\n            else\n                echo \"Error: build type is already set to be ${BuildType}.\"\n                exit 1\n            fi\n            shift ;;\n        -p)\n            declare -i numJobs  # This variable is an integer, guaranteed by the shell\n            numJobs=$2\n            if [ $numJobs -gt 1 ]; then\n                Parallelism=\"-j$numJobs\"\n                echo \"Setting parallelism to $Parallelism\"\n            else\n                Parallelism=\"\"\n                echo \"Disabling parallel compilation\"\n            fi\n            shift; shift ;;\n        --) shift; break ;;\n    esac\ndone\n\nif [ -z \"${BuildType}\" ]; then\n    echo \"Error: missing build type. -d or -o is required.\"\n    exit 1\nfi\n\nif [ \"${CodeCoverage}\" == \"ON\" ]; then\n    if [ \"${BuildType}\" != \"d\" ]; then\n        echo \"Error: only debug build is supported for code coverage.\"\n        exit 1\n    fi\nfi\n\nBuildWithCMake()\n{\n    echo\n    echo Start to build source code. BuildType=${BuildType} ...\n    BinDropDir=${BUILDDIR}.${BuildType}.${CCompiler}\n    rm -rf ${BUILDDIR} ${BinDropDir}\n    mkdir ${BinDropDir}\n    ln -s ${BinDropDir} ${BUILDDIR}\n\n    pushd ${BinDropDir}\n\n    DefBuildNumber=\n    if [ ! -z \"${BuildName}\" ]; then\n        DefBuildNumber=-DBUILD_NUMBER=${BuildName}\n    fi\n    echo \"BuildName: '${DefBuildNumber}'\"\n\n    CMakeBuildType=\"Release\"\n    if [ ${BuildType} == \"d\" ]; then\n        CMakeBuildType=\"Debug\"\n    fi\n\n    cmake -DCMAKE_C_COMPILER=${CCompiler} -DCMAKE_CXX_COMPILER=${CXXCompiler} \\\n          -DCMAKE_BUILD_TYPE=${CMakeBuildType} ${DefBuildNumber} \\\n          -DBUILD_COV=${CodeCoverage} ../\n\n    CheckCmdError \"cmake\"\n\n    if [ ${MakeFileOnly} != 0 ]; then\n        echo\n        echo Makfiles are created. To make, cd ${BUILDDIR}, run make \\<target\\>.\n        echo\n        make help\n        exit ${TotalErrors}\n    fi\n\n    make ${Parallelism}\n    CheckCmdError \"make ${Parallelism}\"\n\n    make install\n    CheckCmdError \"make install\"\n\n    if [ ${CCompiler} == \"gcc\" ]; then\n        # Make deb/rpm packages for LAD mdsd\n        make -C ../lad-mdsd/deb LABEL=${BuildName}\n        CheckCmdError  \"lad-mdsd/deb\"\n        make -C ../lad-mdsd/rpm LABEL=${BuildName}\n        CheckCmdError  \"lad-mdsd/rpm\"\n    fi\n    tar czf release.tar.gz release\n    popd\n}\n\n# Check whether previous command has error or not.\n# Usage: CheckCmdError \"description\"\nCheckCmdError()\n{\n    if [ $? != 0 ]; then\n        let TotalErrors+=1\n        echo Error: build $1 failed\n        exit ${TotalErrors}\n    else\n        echo Finished building $1 successfully\n    fi\n}\n\n# Usage: ParseGlibcVer <dirname> <filename>(optional)\nParseGlibcVer()\n{\n    # Maximum GLIBC version supported by oldest supported distro\n    glibcver=2.15\n    ParserScript=./parseglibc.py\n    dirname=$1\n    filename=$2  # optional, can be NULL\n    echo\n    if [ -n \"${filename}\" ]; then\n        echo python ${ParserScript} -f ${dirname}/${filename} -v ${glibcver}\n        python ${ParserScript} -f ${dirname}/${filename} -v ${glibcver}\n    else\n        echo python ${ParserScript} -d ${dirname} -v ${glibcver}\n        python ${ParserScript} -d ${dirname} -v ${glibcver}\n    fi\n\n    if [ $? != 0 ]; then\n        let TotalErrors+=1\n        echo Error: ParseGlibcVer failed: maximum supported GLIBC version is ${glibcver}.\n        exit ${TotalErrors}\n    fi\n}\n\n# Download/build/install the appropriate version of openssl.\n#    This is needed because the lib{ssl,crypto}.a that's available through the Ubuntu repo\n#    is causing some link errors at the last stage. We need to use /usr/local/ssl as the\n#    top-level OpenSSL directory for the libraries, to make them work on all distros\n#    (especially SUSE 11, which is already done that way).\nBuildOpenSsl()\n{\n    opensslDir=openssl-1.0.2* # Grab the only (which must be latest) OpenSSL 1.0.2 release\n    tgzFile=$opensslDir.tar.gz\n    wget ftp://ftp.openssl.org/source/$tgzFile || exit 1\n    InstallOpenSSL=1\n    if [ -e /usr/local/lib/libcrypto.a -a -e /usr/local/lib/libssl.a ]; then\n        OpenSSLVersion=$(strings /usr/local/lib/libssl.a | egrep \"^OpenSSL \" | awk '{ print $2 }')\n        DownloadedTGZName=$(ls $tgzFile)\n        if [ \"$DownloadedTGZName\" == \"openssl-$OpenSSLVersion.tar.gz\" ]; then # Already latest\n            InstallOpenSSL=0\n        fi\n    fi\n    if [ \"$InstallOpenSSL\" == \"1\" ]; then\n        tar xfz $tgzFile\n        cd $opensslDir\n         # Need to make the lib*.a linkable to .so as well (for AI SDK lib*.so) by adding -fPIC.\n        export CC=\"gcc -fPIC\"\n        ./config --prefix=/usr/local --openssldir=/usr/lib/ssl zlib\n        make\n        CheckCmdError \"openssl make\"\n        sudo make install_sw\n        CheckCmdError \"openssl make install_sw\"\n        cd ..\n    fi\n}\n\n\necho Start build at `date`. BuildType=${BuildType} CC=${CCompiler} ...\n\nBuildOpenSsl\n\nBuildWithCMake\n\n# Remaining steps should be run only on a non-static build except ParseGlibcVer on bin build.\n\nParseGlibcVer ./${BUILDDIR}/release/bin\nParseGlibcVer ./${BUILDDIR}/release/lib\n\necho\necho Finished all builds at `date`. error = ${TotalErrors}\nexit ${TotalErrors}\n", "num_lines": 242}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Keeping the default command\nCOMMAND=\"\"\nPYTHON=\"\"\n\n# We are writing logs to error stream in extension_shim.sh as the logs written to output stream are being overriden by HandlerUtil.py. This has been done as part of OMIGOD hotfix\n# Default variables for OMI Package Upgrade\nREQUIRED_OMI_VERSION=\"1.6.12.1\"\nINSTALLED_OMI_VERSION=\"\"\nUPGRADED_OMI_VERSION=\"\"\nOPENSSL_VERSION=\"\"\nOMI_PACKAGE_PREFIX='packages/omi-1.6.12-1.ssl_'\nOMI_PACKAGE_PATH=\"\"\nOMI_SERVICE_STATE=\"\"\n\nUSAGE=\"$(basename \"$0\") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update]\n\nProgram to find the installed python on the box and invoke a Python extension script.\n\nwhere:\n    -h|--help       show this help text\n    -i|--install    install the extension\n    -u|--uninstall  uninstall the extension\n    -d|--disable    disable the extension\n    -e|--enable     enable the extension\n    -p|--update     update the extension\n    -c|--command    command to run\n\nexample:\n# Install usage\n$ bash extension_shim.sh -i\npython ./vmaccess.py -install\n\n# Custom executable python file\n$ bash extension_shim.sh -c \"\"hello.py\"\" -i\npython hello.py -install\n\n# Custom executable python file with arguments\n$ bash extension_shim.sh -c \"\"hello.py --install\"\"\npython hello.py --install\n\"\n\nfunction find_python(){\n    local python_exec_command=$1\n\n    # Check if there is python2 defined.\n    if command -v python2 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python2\"\n    else\n        # Python2 was not found. Searching for Python3 now.\n        if command -v python3 >/dev/null 2>&1 ; then\n            eval ${python_exec_command}=\"python3\"\n        fi\n    fi\n}\n\nfunction get_openssl_version(){\n    openssl=`openssl version | awk '{print $2}'`\n    if [[ ${openssl} =~ ^1.0.* ]]; then\n        OPENSSL_VERSION=\"100\"\n    else\n        if [[ ${openssl} =~ ^1.1.* ]]; then\n            OPENSSL_VERSION=\"110\"\n        else\n            if [[ ${openssl} =~ ^0.9.8* ]]; then\n                OPENSSL_VERSION=\"098\"\n            fi\n        fi\n    fi\n}\n\nfunction start_omiservice(){\n    echo \"Attempting to start OMI service\" >&2\n    RESULT=`/opt/omi/bin/service_control start >/dev/null 2>&1`\n    RESULT=`service omid status >/dev/null 2>&1`\n    if [ $? -eq 0 ]; then\n        echo \"OMI service succesfully started.\" >&2\n    else\n        echo \"OMI service could not be started.\" >&2\n    fi\n}\n\nfunction stop_omiservice(){\n    echo \"Attempting to stop OMI service\" >&2\n    RESULT=`/opt/omi/bin/service_control stop >/dev/null 2>&1`\n    RESULT=`service omid status >/dev/null 2>&1`\n    if [ $? -eq 3 ]; then\n        echo \"OMI service succesfully stopped.\" >&2\n    else\n        echo \"OMI service could not be stopped.\" >&2\n    fi\n}\n\nfunction compare_versions(){\n    if [[ $1 == $2 ]]\n    then\n        return 0\n    fi\n    local IFS=.\n    local i v1=($1) v2=($2)\n    for ((i=0; i<${#v1[@]}; i++)) \n    do\n        if ((${v1[i]} > ${v2[i]}))\n        then\n            return 1\n        fi\n        if ((${v1[i]} < ${v2[i]}))\n        then\n            return 2\n        fi\n    done\n    return 0\n}\n\nfunction get_compiler_mitigated_flag() {\n    OS_NAME=`grep '^NAME' /etc/os-release | tr -d 'NAME=' | tr -d '\"' | tr '[:upper:]' '[:lower:]'`\n    echo \"OS: ${OS_NAME}\" >&2\n    OS_VERSION=`grep '^VERSION_ID' /etc/os-release | tr -d 'VERSION_ID=' | tr -d '\"' | tr '[:upper:]' '[:lower:]'`\n    echo \"OS VERSION: ${OS_VERSION}\" >&2\n\n    # Compiler-mitigated OMI is not supported in the following\n    # SLES 11\n    \n    # To be enhanced if there are future distros not supporting compiler-mitigated OMI package\n\t\n\tFLAG=\"\"\n\tif [[ $OS_NAME == sles* && $OS_VERSION == 11* ]]\n\tthen\n\t\tFLAG=\"\"\n\telse\n\t\tFLAG=\".s\"\n\tfi\n\techo $FLAG\n}\n\nfunction ensure_required_omi_version_exists(){\n    # Populate SSL Version\n    get_openssl_version\n\n    echo \"Checking if OMI is installed. Required OMI version: ${REQUIRED_OMI_VERSION};\" >&2\n\n    COMPILER_MITIGATED_VERSION_FLAG=$( get_compiler_mitigated_flag )\n    echo \"OMI compiler-mitigated flag: (${COMPILER_MITIGATED_VERSION_FLAG})\" >&2\n\n    # Check if RPM exists\n    if command -v rpm >/dev/null 2>&1 ; then\n        echo \"Package Manager Type: RPM\" >&2\n        INSTALLED_OMI_VERSION=`rpm -q --queryformat \"%{VERSION}.%{RELEASE}\" omi 2>&1` \n        if [ -z \"$INSTALLED_OMI_VERSION\" -o \"$INSTALLED_OMI_VERSION\" = \"package omi is not installed\" ]; then\n            echo \"OMI is not installed on the machine.\" >&2\n        else\n            RESULT=`service omid status >/dev/null 2>&1`\n            OMI_SERVICE_STATE=$?\n            echo \"OMI is already installed. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};\" >&2 # Add current running status\n            compare_versions ${INSTALLED_OMI_VERSION} ${REQUIRED_OMI_VERSION}\n            if [ $? -eq 2 ]; then\n                OMI_PACKAGE_PATH=\"${OMI_PACKAGE_PREFIX}${OPENSSL_VERSION}.ulinux${COMPILER_MITIGATED_VERSION_FLAG}.x64.rpm\"\n                echo \"Installed OMI version is lower than the Required OMI version. Trying to upgrade.\" >&2\n                if [ -f ${OMI_PACKAGE_PATH} ]; then\n                    echo \"The OMI package exists at ${OMI_PACKAGE_PATH}. Using this to upgrade.\" >&2\n                    stop_omiservice\n                    RESULT=`rpm -Uvh ${OMI_PACKAGE_PATH} >/dev/null 2>&1`\n                    if [ $? -eq 0 ]; then\n                        UPGRADED_OMI_VERSION=`rpm -q --queryformat \"%{VERSION}.%{RELEASE}\" omi 2>&1`\n                        echo \"Succesfully upgraded the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION}; Upgraded: ${UPGRADED_OMI_VERSION};\" >&2\n                    else\n                        echo \"Failed to upgrade the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION};\" >&2\n                    fi\n                    # Start OMI only if previous state was running\n                    if [ $OMI_SERVICE_STATE -eq 0 ]; then\n                        start_omiservice\n                    fi\n                else          \n                    echo \"The OMI package does not exists at ${OMI_PACKAGE_PATH}. Skipping upgrade.\" >&2\n                fi\n            else\n                echo \"Installed OMI version is equal to or greater than the Required OMI version. No action needed.\" >&2\n            fi\n        fi\n        INSTALLED_OMI_VERSION=`rpm -q --queryformat \"%{VERSION}.%{RELEASE}\" omi 2>&1`\n        RESULT=`service omid status >/dev/null 2>&1`\n        OMI_SERVICE_STATE=$?\n        echo \"OMI upgrade is complete. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};\" >&2\n    else \n        # Check if DPKG exists\n        if command -v dpkg >/dev/null 2>&1 ; then\n            echo \"Package Manager Type: DPKG\" >&2\n            INSTALLED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`\n            if [ -z \"$INSTALLED_OMI_VERSION\" -o \"$INSTALLED_OMI_VERSION\" = \"package omi is not installed\" ]; then\n                echo \"OMI is not installed on the machine.\" >&2\n            else\n                RESULT=`service omid status >/dev/null 2>&1`\n                OMI_SERVICE_STATE=$?\n                echo \"OMI is already installed. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};\" >&2\n                compare_versions ${INSTALLED_OMI_VERSION} ${REQUIRED_OMI_VERSION}\n                if [ $? -eq 2 ]; then\n                    OMI_PACKAGE_PATH=\"${OMI_PACKAGE_PREFIX}${OPENSSL_VERSION}.ulinux${COMPILER_MITIGATED_VERSION_FLAG}.x64.deb\"\n                    echo \"Installed OMI version is lower than the Required OMI version. Trying to upgrade.\" >&2\n                    if [ -f ${OMI_PACKAGE_PATH} ]; then\n                        echo \"The OMI package exists at ${OMI_PACKAGE_PATH}. Using this to upgrade.\" >&2\n                        stop_omiservice\n                        RESULT=`dpkg -i --force-confold --force-confdef --refuse-downgrade ${OMI_PACKAGE_PATH} >/dev/null 2>&1`\n                        if [ $? -eq 0 ]; then\n                            UPGRADED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`\n                            echo \"Succesfully upgraded the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION}; Upgraded: ${UPGRADED_OMI_VERSION};\" >&2\n                        else\n                            echo \"Failed to upgrade the OMI. Installed: ${INSTALLED_OMI_VERSION}; Required: ${REQUIRED_OMI_VERSION};\" >&2\n                        fi\n                        # Start OMI only if previous state was running\n                        if [ $OMI_SERVICE_STATE -eq 0 ]; then\n                            start_omiservice\n                        fi\n                    else          \n                        echo \"The OMI package does not exists at ${OMI_PACKAGE_PATH}. Skipping upgrade.\" >&2                 \n                    fi \n                else\n                    echo \"Installed OMI version is equal to or greater than the Required OMI version. No action needed.\" >&2\n                fi\n            fi\n            INSTALLED_OMI_VERSION=`dpkg -s omi 2>&1 | grep Version: | awk '{print $2}'`\n            RESULT=`service omid status >/dev/null 2>&1`\n            OMI_SERVICE_STATE=$?\n            echo \"OMI upgrade is complete. Installed OMI version: ${INSTALLED_OMI_VERSION}; OMI Service State: ${OMI_SERVICE_STATE};\" >&2\n        fi\n    fi\n}\n\n# Transform long options to short ones for getopts support (getopts doesn't support long args)\nfor arg in \"$@\"; do\n  shift\n  case \"$arg\" in\n    \"--help\")       set -- \"$@\" \"-h\" ;;\n    \"--install\")    set -- \"$@\" \"-i\" ;;\n    \"--update\")     set -- \"$@\" \"-p\" ;;\n    \"--enable\")     set -- \"$@\" \"-e\" ;;\n    \"--disable\")    set -- \"$@\" \"-d\" ;;\n    \"--uninstall\")  set -- \"$@\" \"-u\" ;;\n    *)              set -- \"$@\" \"$arg\"\n  esac\ndone\n\nif [ -z \"$arg\" ]\nthen\n   echo \"$USAGE\" >&2\n   exit 1\nfi\n\n# Get the arguments\nwhile getopts \"iudephc:?\" o; do\n    case \"${o}\" in\n        h|\\?)\n            echo \"$USAGE\"\n            exit 0\n            ;;\n        i)\n            operation=\"-install\"\n            ;;\n        u)\n            operation=\"-uninstall\"\n            ;;\n        d)\n            operation=\"-disable\"\n            ;;\n        e)\n            operation=\"-enable\"\n            ;;\n        p)\n            operation=\"-update\"\n            ;;\n        c)\n            COMMAND=\"$OPTARG\"\n            ;;\n        *)\n            echo \"$USAGE\" >&2\n            exit 1\n            ;;\n    esac\ndone\n\nshift $((OPTIND-1))\n\n# Ensure OMI package if exists is of required version.\nensure_required_omi_version_exists\n\n# If find_python is not able to find a python installed, $PYTHON will be null.\nfind_python PYTHON\n\n\nif [ -z \"$PYTHON\" ]; then\n   echo \"No Python interpreter found on the box\" >&2\n   exit 51 # Not Supported\nelse\n    `${PYTHON} --version`\nfi\n\n${PYTHON} ${COMMAND} ${operation}\n# DONE", "num_lines": 298}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\n\nsource ./omsagent.version\n\necho \"OMS_EXTENSION_VERSION=$OMS_EXTENSION_VERSION\"\necho \"OMS_SHELL_BUNDLE_VERSION=$OMS_SHELL_BUNDLE_VERSION\"\n\n\n# updating HandlerManifest.json\n# check for \"version\": \"1.12.5\",\nsed -i \"s/\\\"version\\\".*$/\\\"version\\\": \\\"$OMS_EXTENSION_VERSION\\\",/g\" HandlerManifest.json\n\n# updating watcherutil.py\n# check OMSExtensionVersion = '1.12.5'\nsed -i \"s/^OMSExtensionVersion = .*$/OMSExtensionVersion = '$OMS_EXTENSION_VERSION'/\"  watcherutil.py\n\n# updating omsagent.py\n# check BundleFileName = 'omsagent-0.0.0-0.universal.x64.sh'\nsed -i \"s/^BundleFileName = .*$/BundleFileName = 'omsagent-$OMS_SHELL_BUNDLE_VERSION.universal.x64.sh'/\" omsagent.py\n\n# updating manifest.xml\n# check <Version>...</Version>\nsed -i -e \"s|<Version>[0-9a-z.]\\{1,\\}</Version>|<Version>$OMS_EXTENSION_VERSION</Version>|g\" manifest.xml\n", "num_lines": 24}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nif [ -z \"$1\" ]; then\n    echo \"Usage:\"\n    echo \"   $0 PUBLIC_GPG_KEY\"\n    exit 1\nfi\n\nif [ -z \"$2\" ]; then\n    KEYRING_NAME=\"keyring.gpg\"\nelse\n    KEYRING_NAME=$2\nfi\n\nTARGET_DIR=\"$(dirname $1)\"\nHOME=$TARGET_DIR gpg --no-default-keyring --keyring $TARGET_DIR/$KEYRING_NAME --import $1\nRETVAL=$?\n\n# chown omsagent $TARGET_DIR/$KEYRING_NAME\n\nexit $RETVAL", "num_lines": 21}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# The entry point for the OMS extension through which the correct python version (if any) is used to invoke omsagent.py.\n# We default to python2 and always invoke with the versioned python command to accomodate the RHEL 8+ python strategy.\n# Control arguments passed to the shim are redirected to omsagent.py without validation.\n\nCOMMAND=\"./omsagent.py\"\nPYTHON=\"\"\nFUTURE_PATH=\"\"\nARG=\"$@\"\n\nfunction find_python() {\n    local python_exec_command=$1\n    local future_path=$2\n\n    if command -v python2 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python2\"\n        eval ${future_path}=\"${PWD}/ext/future:\"\n    elif command -v python3 >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python3\"\n        # do not set future_path; future seems to cause interference with preexisting packages in python 3 environment\n    fi\n}\n\nfind_python PYTHON FUTURE_PATH\n\nif [ -z \"$PYTHON\" ]\nthen\n    echo \"No Python interpreter found, which is an OMS extension dependency. Please install either Python 2 or 3.\" >&2\n    exit 52 # Missing Dependency\nelse\n    ${PYTHON} --version 2>&1\nfi\n\nPYTHONPATH=${FUTURE_PATH}${PYTHONPATH} ${PYTHON} ${COMMAND} ${ARG}\nexit $?\n", "num_lines": 37}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -e\nsource omsagent.version\n\nusage()\n{\n    local basename=`basename $0`\n    echo \"usage: ./$basename <path to omsagent-<version>.universal.x64{.sh, .sha256sums, .asc}> [path for zip output]\"\n}\n\ninput_path=$1\noutput_path=$2\nPACKAGE_NAME=\"oms$OMS_EXTENSION_VERSION.zip\"\nif [[ \"$1\" == \"--help\" ]]; then\n    usage\n    exit 0\nelif [[ ! -d $input_path ]]; then\n    echo \"OMS files path '$input_path' not found\"\n    usage\n    exit 1\nfi\n\nif [[ \"$output_path\" == \"\" ]]; then\n    output_path=\"../\"\nfi\n\n# Packaging starts here\ncp -r ../Utils .\ncp ../Common/WALinuxAgent-2.0.16/waagent .\n\n# cleanup packages, ext\nrm -rf packages ext/future\nmkdir -p packages ext/future\n# copy shell bundle to packages/\ncp $input_path/omsagent-$OMS_SHELL_BUNDLE_VERSION.universal.x64.* packages/\n# copy just the source of python-future\ncp -r ext/python-future/src/* ext/future\n# sync the file copy\nsync\n\nif [[ -f $output_path/$PACKAGE_NAME ]]; then\n    echo \"Removing existing $PACKAGE_NAME ...\"\n    rm -f $output_path/$PACKAGE_NAME\nfi\n\necho \"Packaging extension $PACKAGE_NAME to $output_path\"\nexcluded_files=\"omsagent.version packaging.sh apply_version.sh update_version.sh\"\nzip -r $output_path/$PACKAGE_NAME * -x $excluded_files \"./test/*\" \"./extension-test/*\" \"./references\" \"./ext/python-future/*\" \"./ext/future/future/backports/test/*\"\n\n# cleanup newly added dir or files\nrm -rf Utils/ waagent\n", "num_lines": 52}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\nset -x\n\nif [[ \"$1\" == \"--help\" ]]; then\n    echo \"update_version.sh <MAJOR> <MINOR> <PATCH> <BUILDNR>\"\n    exit 0\nfi\n\nUPDATE_DATE=`date +%Y%m%d`\nOMS_BUILDVERSION_MAJOR=$1\nOMS_BUILDVERSION_MINOR=$2\nOMS_BUILDVERSION_PATCH=$3\nOMS_BUILDVERSION_BUILDNR=$4\n\nif [[ \"$OMS_BUILDVERSION_MAJOR\" == \"\" ]]; then\n    echo \"MAJOR version is empty\"\n    exit 1\nfi\n\nif [[ \"$OMS_BUILDVERSION_MINOR\" == \"\" ]]; then\n    echo \"MINOR version is empty\"\n    exit 1\nfi\n\nif [[ \"$OMS_BUILDVERSION_PATCH\" == \"\" ]]; then\n    echo \"PATH version is empty\"\n    exit 1\nfi\n\nif [[ \"$OMS_BUILDVERSION_BUILDNR\" == \"\" ]]; then\n    echo \"BUILDNR version is empty\"\n    exit 1\nfi\n\n\nsed -i \"s/^OMS_VERSION_MAJOR=.*$/OMS_VERSION_MAJOR=$OMS_BUILDVERSION_MAJOR/\" omsagent.version\nsed -i \"s/^OMS_VERSION_MINOR=.*$/OMS_VERSION_MINOR=$OMS_BUILDVERSION_MINOR/\" omsagent.version\nsed -i \"s/^OMS_VERSION_PATCH_EXTENSION=.*$/OMS_VERSION_PATCH_EXTENSION=$OMS_BUILDVERSION_PATCH/\" omsagent.version\nsed -i \"s/^OMS_VERSION_PATCH_SHELL_BUNDLE=.*$/OMS_VERSION_PATCH_SHELL_BUNDLE=$OMS_BUILDVERSION_PATCH/\" omsagent.version\nsed -i \"s/^OMS_VERSION_BUILDNR_SHELL_BUNDLE=.*$/OMS_VERSION_BUILDNR_SHELL_BUNDLE=$OMS_BUILDVERSION_BUILDNR/\" omsagent.version\nsed -i \"s/^OMS_VERSION_DATE=.*$/OMS_VERSION_DATE=$UPDATE_DATE/\" omsagent.version\n", "num_lines": 42}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to set up a test env for extensions\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nif [ $# != 2 ]  ; then\n    echo \"\" \n    echo \"    Usage: $0 <path-to-extension> <version>\"\n    echo \"    Example: $0 SampleExtension 1.0.0.0\"\n    echo \"\"\n    exit 1\nfi\n\nif [ ! -d $1 ]  ; then\n    echo \"\" \n    echo \"    Error: Couldn't find dir: $1\"\n    echo \"\"\n    exit 1\nfi\n\ncurr_dir=`pwd`\next_dir=$1\ncd $ext_dir\next_dir=`pwd`\ncd $curr_dir\n\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\n\nutil_dir=$root/Utils\nbuild_dir=$root/build\n\nif [ ! -d $build_dir ] ; then\n    mkdir $build_dir\nfi\n\next_name=`echo $1 | sed 's/\\/$//'`\next_version=$2\next_full_name=$ext_name-$ext_version\ntmp_dir=$build_dir/$ext_full_name\n\necho \"Create zip for $ext_name version $ext_version\"\n\necho \"Creat tmp dir: $tmp_dir\"\nmkdir $tmp_dir\n\necho \"Copy files...\"\ncp -r $ext_dir/* $tmp_dir\nrm $tmp_dir/references\n\necho \"Copy dependecies...\"\ncat $ext_dir/references\ncat $ext_dir/references | xargs cp -r -t $tmp_dir\n\necho \"Switch to tmp dir...\"\ncd $tmp_dir\n\necho \"Remove test dir...\"\nrm -r test\nrm -r */test\n\necho \"Remove *.pyc...\"\nfind . -name \"*.pyc\" | xargs rm -f\n\necho \"Create zip...\"\nzip -r $build_dir/$ext_full_name.zip .\n\necho \"Delete tmp dir...\"\nrm $tmp_dir -r\necho \"Done!\"\n", "num_lines": 87}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\necho $1\ncurl -v -X 'POST'  -H \"$VERSION\" -H 'Content-Type: application/xml' -E $CERT -d@$1 $ENDPOINT/$SUBSCRIPTION/services/extensions\n", "num_lines": 11}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\necho $1\ncurl -v -X 'GET' --keepalive-time 30 --user-agent ' Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient/0.9.0.0 WindowsAzurePowershell/v0.8.0' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml'  --insecure  -E $CERT --data-binary @$1  $ENDPOINT/$SUBSCRIPTION/operations/$1\n", "num_lines": 11}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\ncurl -v -X 'DELETE'  -H \"$VERSION\" -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/extensions/$1/$2/$3\n", "num_lines": 10}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\ncurl -v -X 'GET'  -H \"$VERSION\" -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/resourceextensions/$1/$2\n", "num_lines": 10}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\necho \"GET $ENDPOINT/$SUBSCRIPTION\"\n\ncurl -v -X 'GET' --keepalive-time 30 --user-agent ' Microsoft.WindowsAzure.Management.Compute.ComputeManagementClient/0.9.0.0 WindowsAzurePowershell/v0.8.0' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml'  --insecure  -E $CERT $ENDPOINT/$SUBSCRIPTION\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\ncurl -v -X 'GET' -H 'x-ms-version: 2014-06-01' -H 'Content-Type: application/xml' -E $CERT $ENDPOINT/$SUBSCRIPTION/services/publisherextensions\n", "num_lines": 10}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script\nsource params\nexport script=`pwd`\ncd $original_dir\n\ncurl -v -X 'PUT' -H \"$VERSION\" -H 'Content-Type: application/xml' -E $CERT -d@$1 $ENDPOINT/$SUBSCRIPTION/services/extensions?action=update\n", "num_lines": 10}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Add extension: $1\"\n$root/api/add-extension.sh 2>/tmp/restoutput $1 | sed -e 's/></>\\n</g'\n\necho \"====================\"\necho \"Check request by running bin/check.sh <request-id>\"\ntail /tmp/restoutput\necho \"====================\"\necho \"More info is saved in /tmp/restoutput\"\n", "num_lines": 18}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Check Request: $1\"\n$root/api/check-request-status.sh 2>>/tmp/restoutput $1 | sed -e 's/></>\\n</g'\n\n", "num_lines": 13}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Delete extension: $1 $2 $3\"\n$root/api/del-extension.sh 2>/tmp/restoutput $1 $2 $3| sed -e 's/></>\\n</g'\n\necho \"====================\"\necho \"Check request by running bin/check.sh <request-id>\"\ntail /tmp/restoutput\necho \"====================\"\necho \"More info is saved in /tmp/restoutput\"\n", "num_lines": 18}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Get extension: $1 $2\"\n$root/api/get-extension.sh 2>/tmp/restoutput $1 $2 | sed -e 's/></>\\n</g'\n\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"List extensions: $1\"\n$root/api/list-extension.sh 2>/tmp/restoutput | sed -e 's/></>\\n</g' | sed -e 's/<\\/ExtensionImage>/<\\/ExtensionImage>\\n/g'\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Get subscription\"\n$root/api/get-subscription.sh 2>>/tmp/restoutput | sed -e 's/></>\\n</g'\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\noriginal_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\ncd $original_dir\n\necho \"Update extension: $1\"\n$root/api/update-extension.sh 2>/tmp/restoutput $1 | sed -e 's/></>\\n</g'\n\necho \"====================\"\necho \"Check request by running bin/check.sh <request-id>\"\ntail /tmp/restoutput\necho \"====================\"\necho \"More info is saved in /tmp/restoutput\"\n", "num_lines": 18}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script/../../api\nsource params\nexport script=`pwd`\ncd $original_dir\n\nazure storage blob list -c $CONN_STR extensions\n", "num_lines": 10}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\noriginal_dir=`pwd`\nscript=`dirname $0`\ncd $script/../../api\nsource params\nexport script=`pwd`\ncd $original_dir\n\nzip_file=$(readlink -f $1)\nif [ ! -f $zip_file ] ; then\n    echo \"File not found: $zip_file\"\n    exit 1\nfi\nfile_name=$(basename $zip_file)\necho \"Uploading $zip_file to azure...\"\nazure storage blob upload -c $CONN_STR $zip_file extensions $file_name\n", "num_lines": 17}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to set up a test env for extensions\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\nif [ ! $1 ]  || [ ! $2 ] || [ ! $3 ]  ; then\n    echo \"\" \n    echo \"    Usage: create_zip.sh <path_to_extension_dir> <name> <version>\"\n    echo \"\"\n    exit 1\nfi\n\nif [ ! -d $1 ]  ; then\n    echo \"\" \n    echo \"    Error: Couldn't find dir: $1>\"\n    echo \"\"\n    exit 1\nfi\n\ncurr_dir=`pwd`\next_dir=$1\next_name=$2\next_version=$3\ncd $ext_dir\next_dir=`pwd`\ncd $curr_dir\n\n\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\n\necho $ext_name\necho $ext_version\n\nutil_dir=$root/Utils\nbuild_dir=$root/build\n\n\nif [ ! $ext_name ] ; then\n    echo \"\"\n    echo \"    Error: Couldn't detect extention name: $ext_name\"\n    echo \"\"\n    exit 1\nfi\n\nif [ ! $ext_version ] ; then\n    echo \"\"\n    echo \"    Error: Couldn't detect extention version: $ext_version\"\n    echo \"\"\n    exit 1\nfi\n\nif [ ! -d $build_dir ] ; then\n    mkdir $build_dir\nfi\n\next_full_name=$ext_name-$ext_version\ntmp_dir=$build_dir/$ext_full_name\n\necho \"Create zip for $ext_name version $ext_version\"\n\necho \"Creat tmp dir: $tmp_dir\"\nmkdir $tmp_dir\n\necho \"Copy files...\"\ncp -r $ext_dir/* $tmp_dir\nrm $tmp_dir/references\n\necho \"Copy dependecies...\"\ncat $ext_dir/references\ncat $ext_dir/references | xargs cp -r -t $tmp_dir\n\necho \"Switch to tmp dir...\"\ncd $tmp_dir\n\necho \"Remove test dir...\"\nrm -r test\nrm -r */test\nrm *.pyc\n\necho \"Create zip...\"\nzip -r $build_dir/$ext_full_name.zip .\n\necho \"Delete tmp dir...\"\nrm $tmp_dir -r\necho \"Done!\"\n", "num_lines": 103}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to create stub for unit test\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\nif [ ! $1 ]  ; then\n    echo \"\" \n    echo \"    Usage: mkstub.sh <path_to_extension_dir>\"\n    echo \"\"\n    exit 1\nfi\n\nif [ ! -d $1 ]  ; then\n    echo \"\" \n    echo \"    Error: Couldn't find dir: $1>\"\n    echo \"\"\n    exit 1\nfi\n\next_dir=$1\next_meta=$ext_dir/HandlerManifest.json\n\nif [ ! -f $ext_meta ] ; then\n    echo \"\"\n    echo \"    Error: Couldn't find \\\"HandlerManifest.json\\\" file under $ext_dir\"\n    echo \"\"\n    exit 1\nfi\n\ncur_dir=`pwd`\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\nwaagent_path='/usr/sbin/waagent'\nwaagent_lib_dir='/var/lib/waagent'\next_log_dir='/var/log/azure'\n\next_name=`grep 'name' $ext_meta | sed 's/[\\\"| |,]//g' |gawk -F ':' '{print $2}'`\next_version=`grep 'version' $ext_meta | sed 's/[\\\"| |,]//g' |gawk -F ':' '{print $2}'`\n\next_full_name=$ext_name-$ext_version\next_dir=$waagent_lib_dir/$ext_full_name\next_status_dir=$ext_dir/status\next_config_dir=$ext_dir/config\next_env_json=$ext_dir/HandlerEnvironment.json\ntest_cert_file=$waagent_lib_dir/TEST.crt\ntest_pk_file=$waagent_lib_dir/TEST.prv\novf_env_file=$waagent_lib_dir/ovf-env.xml\n\nif [ ! -f $waagent_path ] ; then\n    echo \"Download latest waagent code\"\n    wget https://raw.githubusercontent.com/Azure/WALinuxAgent/2.0/waagent -O $waagent_path\n    chmod +x $waagent_path\nfi\n\nif [ ! -d $waagent_lib_dir ] ; then\n    echo \"Create lib dir\"\n    mkdir $waagent_lib_dir\nfi\n\nif [ ! -d $ext_dir ] ; then\n    echo \"Create extension dir\"\n    mkdir $ext_dir\nfi\n\nif [ ! -d $ext_config_dir ] ; then\n    echo \"Create extension config dir\"\n    mkdir $ext_config_dir\nfi\n\nif [ ! -d $ext_status_dir ] ; then\n    echo \"Create extension status dir\"\n    mkdir $ext_status_dir\nfi\n\nif [ ! -f $ext_env_json ] ; then\n    echo \"Create HandlerEnvironment.json file\"\n    cp $script/HandlerEnvironment.json $ext_env_json\nfi\n\nif [ ! -f $test_cert_file ] ; then\n    echo \"Create test cert file\"\n    cp $script/test.crt $test_cert_file\nfi\n\nif [ ! -f $test_pk_file ] ; then\n    echo \"Create test pk file\"\n    cp $script/test.prv $test_pk_file\nfi\n\nif [ ! -f $ovf_env_file ] ; then\n    echo \"Create ovf-env.xml file\"\n    cp $script/ovf-env.xml $ovf_env_file\nfi\n\nif [ ! -f $ext_config_dir/0.settings ] ; then\n    echo \"Create 0.settings\"\n    cp $script/0.settings $ext_config_dir/0.settings\nfi\n\nif [ ! -d $ext_log_dir ] ; then\n    echo \"Create ext log dir\"\n    mkdir $ext_log_dir\nfi\n\nif [ ! -d $ext_log_dir/$ext_name ] ; then\n    echo \"Create ext log dir for $ext_name\"\n    mkdir $ext_log_dir/$ext_name\nfi\n\nif [ ! -d $ext_log_dir/$ext_name/$ext_version ] ; then\n    echo \"Create ext log dir for $ext_name $ext_version\"\n    mkdir $ext_log_dir/$ext_name/$ext_version\nfi\n\necho \"Change permission of waagent lib dir\"\nchmod -R 600 $waagent_lib_dir\n", "num_lines": 132}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# This script is used to set up a test env for extensions\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nscript=$(dirname $0)\nroot=$script/..\ncd $root\nroot=`pwd`\nlib_path=\".\"\n\necho \"\\$PYTHONPATH=$PYTHONPATH\"\n\nif [ ! `echo $PYTHONPATH | grep $root` ] ; then\n    lib_path=$lib_path:$root\nfi\n\nif [ $lib_path != \".\" ] ; then\n    echo \"echo \\\"export PYTHONPATH=\\$PYTHONPATH:$lib_path\\\" >> /etc/bash.bashrc\"\n    echo \"export PYTHONPATH=\\$PYTHONPATH:$lib_path\" >> /etc/bash.bashrc\n    echo \"Enviroment variable PYTHONPATH has been set.\"\n    echo \"Run \\\"bash\\\" to reload bash.\"\nelse\n    echo \"Your enviroment is cool. No action required.\"\nfi\n", "num_lines": 41}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Copyright 2014 Microsoft Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\necho \"Start...\"\nsleep 0.1\necho \"Running\"\n>&2 echo \"Warning\"\nsleep 0.1\necho \"Finished\"\nexit $1\n", "num_lines": 24}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# must run with sudo permissions\n# this file copies the local changes to /var/lib/waagent/Microsoft.OSTCExtensions.VMAccessForLinux-<version>\n\n# remember to update the version number to what you have\ndestdir=\"/var/lib/waagent/Microsoft.OSTCExtensions.VMAccessForLinux-1.5.4\"\nutilsDest=\"$destdir/Utils\"\nvmaccessDest=\"$destdir/vmaccess.py\"\n\ncurrentDir=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" >/dev/null 2>&1 && pwd )\"\n\nutilsSource=\"$currentDir/..\"\nvmaccessSource=\"$currentDir/../../VMAccess/vmaccess.py\"\n\ncp -r -f $utilsSource $utilsDest\ncp -f $vmaccessSource $vmaccessDest\nfind $destdir -name '*.pyc' | xargs rm\n", "num_lines": 18}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Keeping the default command\nCOMMAND=\"\"\nPYTHON=\"\"\n\nUSAGE=\"$(basename \"$0\") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update]\n\nProgram to find the installed python on the box and invoke a Python extension script.\n\nwhere:\n    -h|--help       show this help text\n    -i|--install    install the extension\n    -u|--uninstall  uninstall the extension\n    -d|--disable    disable the extension\n    -e|--enable     enable the extension\n    -p|--update     update the extension\n    -c|--command    command to run\n\nexample:\n# Install usage\n$ bash extension_shim.sh -i\npython ./vmaccess.py -install\n\n# Custom executable python file\n$ bash extension_shim.sh -c \"\"hello.py\"\" -i\npython hello.py -install\n\n# Custom executable python file with arguments\n$ bash extension_shim.sh -c \"\"hello.py --install\"\"\npython hello.py --install\n\"\n\nfunction find_python(){\n    local python_exec_command=$1\n\n    # Check if there is python defined.\n    if command -v python >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python\"\n    else\n        # Python was not found. Searching for Python3 now.\n        if command -v python3 >/dev/null 2>&1 ; then\n            eval ${python_exec_command}=\"python3\"\n        fi\n    fi\n}\n\n# Transform long options to short ones for getopts support (getopts doesn't support long args)\nfor arg in \"$@\"; do\n  shift\n  case \"$arg\" in\n    \"--help\")       set -- \"$@\" \"-h\" ;;\n    \"--install\")    set -- \"$@\" \"-i\" ;;\n    \"--update\")     set -- \"$@\" \"-p\" ;;\n    \"--enable\")     set -- \"$@\" \"-e\" ;;\n    \"--disable\")    set -- \"$@\" \"-d\" ;;\n    \"--uninstall\")  set -- \"$@\" \"-u\" ;;\n    *)              set -- \"$@\" \"$arg\"\n  esac\ndone\n\nif [ -z \"$arg\" ]\nthen\n   echo \"$USAGE\" >&2\n   exit 1\nfi\n\n# Get the arguments\nwhile getopts \"iudephc:?\" o; do\n    case \"${o}\" in\n        h|\\?)\n            echo \"$USAGE\"\n            exit 0\n            ;;\n        i)\n            operation=\"-install\"\n            ;;\n        u)\n            operation=\"-uninstall\"\n            ;;\n        d)\n            operation=\"-disable\"\n            ;;\n        e)\n            operation=\"-enable\"\n            ;;\n        p)\n            operation=\"-update\"\n            ;;\n        c)\n            COMMAND=\"$OPTARG\"\n            ;;\n        *)\n            echo \"$USAGE\" >&2\n            exit 1\n            ;;\n    esac\ndone\n\nshift $((OPTIND-1))\n\n# If find_python is not able to find a python installed, $PYTHON will be null.\nfind_python PYTHON\n\n\nif [ -z \"$PYTHON\" ]; then\n   echo \"No Python interpreter found on the box\" >&2\n   exit 51 # Not Supported\nelse\n   echo `${PYTHON} --version`\nfi\n\n${PYTHON} ${COMMAND} ${operation}\n# DONE", "num_lines": 114}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env sh\npwdcommand=`pwd`\npwdstr=\"$pwdcommand\"\noutput=`cat $pwdstr'/HandlerEnvironment.json'`\noutputstr=\"$output\"\npoststr=${outputstr#*logFolder\\\"}\npostsubstr=${poststr#*\\\"}\npostsubstr1=${postsubstr#*\\\"}\nresultstrlen=`expr ${#postsubstr} - 1 - ${#postsubstr1}`\nlogfolder=$(echo $postsubstr | cut -b 1-$resultstrlen)\nlogfile=$logfolder'/shell.log'\n\nrc=3\narc=0\n\nif [ \"$1\" = \"install\" ]\nthen\n    if [ -f \"/etc/azure/workload.conf\" ]\n    then\n\t\tWorkloadConfEdited=`awk '/(workload_name)([ ]*[=])([ ]*[(^|\\\")a-zA-Z(^|\\\")])/' /etc/azure/workload.conf`\n\t\tif [ \"$WorkloadConfEdited\" != \"\" ]\n\t\t\tthen\n\t\t\t\t#Workload.conf is edited\n\t\t\t\techo \"`date -u`- The command is $1, exiting without conf file copy\" >> $logfile\n\t\t\telse\n\t\t\t\t#workload.conf is not edited\n\t\t\t\tcp main/workloadPatch/WorkloadUtils/workload.conf /etc/azure/workload.conf\n\t\t\t\techo \"`date -u`- The command is $1, exiting with conf file copy\" >> $logfile\t\n\t\tfi\n        exit $arc\n    else\n        mkdir -p /etc/azure\n        cp main/workloadPatch/WorkloadUtils/workload.conf /etc/azure/workload.conf\n        echo \"`date -u`- The command is $1, exiting with conf file copy\" >> $logfile\n        exit $arc\n    fi\nelif [ \"$1\" != \"enable\"  ] && [ \"$1\" != \"daemon\" ]\nthen\n    echo \"`date -u`- The command is $1, exiting\" >> $logfile\n    exit $arc\nfi\n\nconfigSeqNo=\"$(echo `printenv ConfigSequenceNumber`)\"\nif [ -z ${configSeqNo} ]\nthen\n\tconfigSeqNo='seqNo:-1'\n\techo \"`date -u`- ConfigSequenceNumber not found in environment variable ${configSeqNo}\" >> $logfile\nelse\n\tconfigSeqNo='seqNo:'$configSeqNo\n\techo \"`date -u`- ConfigSequenceNumber from environment variable ${configSeqNo}\" >> $logfile\nfi\n\npythonVersionList=\"python3.8 python3.7 python3.6 python3.5 python3.4 python3.3 python3 python2.7 python2.6 python2 python\"\n\nfor pythonVersion in ${pythonVersionList};\ndo\n\tcmnd=\"/usr/bin/${pythonVersion}\"\n\tif [ -f \"${cmnd}\" ]\n    then\n\t\techo \"`date -u`- ${pythonVersion} path exists\" >> $logfile\n\t\t$cmnd main/handle.py -$configSeqNo -$1\n\t\trc=$?\n\tfi\n\tif [ $rc -eq 0 ]\n\tthen\n\t\tbreak\n\tfi\ndone\n\npythonProcess=$(ps -ef | grep waagent | grep python)\npythonPath=$(echo \"${pythonProcess}\" | head -n1 | awk '{print $8;}')\n\nif [ $rc -ne 0 ] && [ -f \"`which python`\" ]\nthen\n\techo \"`date -u`- python path exists\" >> $logfile\n\t/usr/bin/env python main/handle.py -$configSeqNo -$1\n\trc=$?\nfi\n\nif [ $rc -ne 0 ] && [ -f \"${pythonPath}\" ]\nthen\n\techo \"`date -u`- python path exists\" >> $logfile\n\t$pythonPath main/handle.py -$configSeqNo -$1\n\trc=$?\nfi\n\t\nif [ $rc -eq 3 ]\nthen\n\techo \"`date -u`- python version unknown\" >> $logfile\nfi\n\necho \"`date -u`- $rc returned from handle.py\" >> $logfile\n\nexit $rc\n", "num_lines": 95}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ninstance=$1\n\n# variables used for returning the status of the scripts\nsuccess=0\nerror=1\nwarning=2\n\nretVal=$success\nexit $retVal\n\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ninstance=$1\n\n# variables used for returning the status of the scripts\nsuccess=0\nerror=1\nwarning=2\n\nretVal=$success\nexit $retVal\n\n", "num_lines": 12}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env sh\n\narc=0\n\ncomand=\"$2\"\ncred_string=\"$3\"\ntimeout=\"$4\"\nscriptPath=\"$5\"\n\nsleep $timeout\n\nif [ \"$1\" = \"oracle\" ]\nthen\n    cmd=\"$comand/sqlplus -S -R 2 /nolog @$scriptPath/postOracleMaster.sql\"\n    exec $cmd\nelif [ \"$1\" = \"postgres\" ]\nthen\n    cmd=\"$comand/psql $cred_string -f $scriptPath/postPostgresMaster.sql\"\n    exec $cmd\nelse\n    echo \"`date`- incorrect workload name\"\nfi\n\nexit $arc", "num_lines": 24}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Keeping the default command\nCOMMAND=\"\"\nPYTHON=\"\"\n\nUSAGE=\"$(basename \"$0\") [-h] [-i|--install] [-u|--uninstall] [-d|--disable] [-e|--enable] [-p|--update] [-m|--daemon]\n\nProgram to find the installed python on the box and invoke a Python extension script using Python 2.7.\n\nwhere:\n    -h|--help       show this help text\n    -i|--install    install the extension\n    -u|--uninstall  uninstall the extension\n    -d|--disable    disable the extension\n    -e|--enable     enable the extension\n    -p|--update     update the extension\n    -m|--daemon     invoke daemon option\n    -c|--command    command to run\n\nexample:\n# Install usage\n$ bash extension_shim.sh -i\npython ./main/handle.py -install\n\n# Custom executable python file\n$ bash extension_shim.sh -c \"\"hello.py\"\" -i\npython hello.py -install\n\n# Custom executable python file with arguments\n$ bash extension_shim.sh -c \"\"hello.py --install\"\"\npython hello.py --install\n\"\n\nfunction find_python(){\n    local python_exec_command=$1\n\n    # Check if there is python defined.\n    if command -v python >/dev/null 2>&1 ; then\n        eval ${python_exec_command}=\"python\"\n    fi\n}\n\n# Transform long options to short ones for getopts support (getopts doesn't support long args)\nfor arg in \"$@\"; do\n  shift\n  case \"$arg\" in\n    \"--help\")       set -- \"$@\" \"-h\" ;;\n    \"--install\")    set -- \"$@\" \"-i\" ;;\n    \"--update\")     set -- \"$@\" \"-p\" ;;\n    \"--enable\")     set -- \"$@\" \"-e\" ;;\n    \"--disable\")    set -- \"$@\" \"-d\" ;;\n    \"--uninstall\")  set -- \"$@\" \"-u\" ;;\n    \"--daemon\")     set -- \"$@\" \"-m\" ;;\n    *)              set -- \"$@\" \"$arg\"\n  esac\ndone\n\nif [ -z \"$arg\" ]\nthen\n   echo \"$USAGE\" >&2\n   exit 1\nfi\n\n# Get the arguments\nwhile getopts \"iudephc:?\" o; do\n    case \"${o}\" in\n        h|\\?)\n            echo \"$USAGE\"\n            exit 0\n            ;;\n        i)\n            operation=\"-install\"\n            ;;\n        u)\n            operation=\"-uninstall\"\n            ;;\n        d)\n            operation=\"-disable\"\n            ;;\n        e)\n            operation=\"-enable\"\n            ;;\n        p)\n            operation=\"-update\"\n            ;;\n        m)\n            operation=\"-daemon\"\n            ;;\n        c)\n            COMMAND=\"$OPTARG\"\n            ;;\n        *)\n            echo \"$USAGE\" >&2\n            exit 1\n            ;;\n    esac\ndone\n\nshift \"$((OPTIND-1))\"\n\n# If find_python is not able to find a python installed, $PYTHON will be null.\nfind_python PYTHON\n\nif [ -z \"$PYTHON\" ]; then\n   echo \"No Python interpreter found on the box\" >&2\n   exit 51 # Not Supported\nelse\n    PYTHON_VER=`${PYTHON} --version 2>&1`\n    if [[ \"$PYTHON_VER\" =~ \"Python 2.6\" ]] || [[ \"$PYTHON_VER\" =~ \"Python 2.7\" ]]; then\n        echo $PYTHON_VER\n    else\n        echo \"Expected Python 2.7, found $PYTHON_VER\" >&2\n        exit 51 # Not Supported\n    fi\nfi\n\n${PYTHON} ${COMMAND} ${operation} 2>&1\n# DONE", "num_lines": 119}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-\n# ex: ts=8 sw=4 sts=4 et filetype=sh\n\nset -x\n\nPATH=/usr/sbin:/usr/bin:/sbin:/bin\nNEWROOT=${NEWROOT:-\"/sysroot\"}\n\n# do not ask, if we already have root\n[ -f $NEWROOT/proc ] && exit 0\n\n# check if destination already exists\n[ -b /dev/mapper/$2 ] && exit 0\n\n# we already asked for this device\n[ -f /tmp/cryptroot-ade-asked-$2 ] && exit 0\n\n# load dm_crypt if it is not already loaded\n[ -d /sys/module/dm_crypt ] || modprobe dm_crypt\n\n. /lib/dracut-crypt-lib.sh\n\n# default luksname - luks-UUID\nluksname=$2\n\n# fallback to passphrase\nask_passphrase=1\n\n# if device name is /dev/dm-X, convert to /dev/mapper/name\nif [ \"${1##/dev/dm-}\" != \"$1\" ]; then\n    device=\"/dev/mapper/$(dmsetup info -c --noheadings -o name \"$1\")\"\nelse\n    device=\"$1\"\nfi\n\nnumtries=${3:-10}\n\n#\n# Open LUKS device\n#\n\ninfo \"luksOpen $device $luksname\"\n\nls /mnt/azure_bek_disk/LinuxPassPhraseFileName* || (mkdir -p /mnt/azure_bek_disk/ && mount -L \"BEK VOLUME\" /mnt/azure_bek_disk/)\n\nfor luksfile in $(ls /mnt/azure_bek_disk/LinuxPassPhraseFileName*); do\n    break;\ndone\n\ncryptsetupopts=\"--header /osluksheader\"\n\nif [ -n \"$luksfile\" -a \"$luksfile\" != \"none\" -a -e \"$luksfile\" ]; then\n    if cryptsetup --key-file \"$luksfile\" $cryptsetupopts luksOpen \"$device\" \"$luksname\"; then\n        ask_passphrase=0\n    fi\nelse\n\tif [ $numtries -eq 0 ]; then\n\t\twarn \"No key found for $device.  Fallback to passphrase mode.\"\n\telse\n\t\tsleep 1\n\t\tinfo \"No key found for $device.  Will try $numtries time(s) more later.\"\n\t\tinitqueue --unique --onetime --settled \\\n\t\t\t--name cryptroot-ask-ade-$luksname \\\n\t\t\t$(command -v cryptroot-ask-ade) \"$device\" \"$luksname\" \"$(($numtries-1))\"\n\t\texit 0\n\tfi\nfi\n\nif [ $ask_passphrase -ne 0 ]; then\n    luks_open=\"$(command -v cryptsetup) $cryptsetupopts luksOpen\"\n    ask_for_password --ply-tries 5 \\\n        --ply-cmd \"$luks_open -T1 $device $luksname\" \\\n        --ply-prompt \"Password ($device)\" \\\n        --tty-tries 1 \\\n        --tty-cmd \"$luks_open -T5 $device $luksname\"\n    unset luks_open\nfi\n\numount /mnt/azure_bek_disk\n\nunset device luksname luksfile\n\n# mark device as asked\n>> /tmp/cryptroot-ade-asked-$2\n\nneed_shutdown\nudevsettle\n\nexit 0\n", "num_lines": 91}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# vim: set tabstop=8 shiftwidth=4 softtabstop=4 expandtab smarttab colorcolumn=80:\n#\n\ndepends() {\n    echo crypt systemd\n    return 0\n}\n\ninstall() {\n    inst_script \"$moddir\"/cryptroot-ask-ade.sh /sbin/cryptroot-ask-ade\n\n    inst_hook cmdline 30 \"$moddir/parse-crypt-ade.sh\"\n\n    inst_rules \"$moddir/50-udev-ade.rules\"\n\n    inst_multiple /etc/services\n        \n    inst /boot/luks/osluksheader /osluksheader\n   \n    dracut_need_initqueue\n}\n\n", "num_lines": 24}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-\n# ex: ts=8 sw=4 sts=4 et filetype=sh\nset -x\n\n{\n    echo 'SUBSYSTEM!=\"block\", GOTO=\"luks_ade_end\"'\n    echo 'ACTION!=\"add|change\", GOTO=\"luks_ade_end\"'\n} > /etc/udev/rules.d/70-luks-ade.rules.new\n\n{\n    printf -- 'ATTRS{device_id}==\"?00000000-0000-*\", ENV{ID_FS_UUID}==\"osencrypt-locked\",'\n    printf -- 'RUN+=\"%s --settled --unique --onetime ' $(command -v initqueue)\n    printf -- '--name cryptroot-ask-ade-%%k %s ' $(command -v cryptroot-ask-ade)\n    printf -- '$env{DEVNAME} osencrypt\"\\n'\n} >> /etc/udev/rules.d/70-luks-ade.rules.new\n\necho 'LABEL=\"luks_ade_end\"' >> /etc/udev/rules.d/70-luks-ade.rules.new\nmv /etc/udev/rules.d/70-luks-ade.rules.new /etc/udev/rules.d/70-luks-ade.rules\n", "num_lines": 20}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nMountPoint=/tmp-keydisk-mount\nKeyFileName=LinuxPassPhraseFileName\necho \"Trying to get the key from disks ...\" >&2\nmkdir -p $MountPoint\nmodprobe nls_utf8 >/dev/null 2>&1\nmodprobe nls_cp437 >/dev/null 2>&1\nmodprobe vfat >/dev/null 2>&1\nsleep 2\nOPENED=0\ncd /sys/block\nfor DEV in sd*; do\n\techo \"> Trying device: $DEV ...\" >&2\n\tmount -t vfat -r /dev/${DEV}1 $MountPoint >&2 2>&1\n\tif [ -f $MountPoint/$KeyFileName ]; then\n\t\tcat $MountPoint/$KeyFileName && echo \"Success loading keyfile!\" >&2\n\t\tumount $MountPoint 2>/dev/null\n\t\tOPENED=1\n\t\tbreak\n\tfi\n\tumount $MountPoint 2>/dev/null\ndone\nif [ $OPENED -eq 0 ]; then\n\techo \"FAILED to find suitable passphrase file ...\" >&2\n\techo -n \"Try to enter your password: \" >&2\n\tread -r A </dev/console\n\techo -n \"$A\"\nfi\n", "num_lines": 29}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -e\n\nPREREQS=\"\"\n\nprereqs() { echo \"$PREREQS\"; }\n\ncase \"$1\" in\n    prereqs)\n    prereqs\n    exit 0\n    ;;\nesac\n\n. /usr/share/initramfs-tools/hook-functions\n\nmkdir -p ${DESTDIR}/boot/luks\ncopy_exec /boot/luks/osluksheader /boot/luks\n", "num_lines": 18}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nMountPoint=/tmp-keydisk-mount\nKeyFileName=LinuxPassPhraseFileName\necho \"Trying to get the key from disks ...\" >&2\nmkdir -p $MountPoint\nmodprobe nls_utf8 >/dev/null 2>&1\nmodprobe nls_cp437 >/dev/null 2>&1\nmodprobe vfat >/dev/null 2>&1\nsleep 2\nOPENED=0\ncd /sys/block\nfor DEV in sd*; do\n\techo \"> Trying device: $DEV ...\" >&2\n\tmount -t vfat -r /dev/${DEV}1 $MountPoint >&2 2>&1\n\tif [ -f $MountPoint/$KeyFileName ]; then\n\t\tcat $MountPoint/$KeyFileName && echo \"Success loading keyfile!\" >&2\n\t\tumount $MountPoint 2>/dev/null\n\t\tOPENED=1\n\t\tbreak\n\tfi\n\tumount $MountPoint 2>/dev/null\ndone\nif [ $OPENED -eq 0 ]; then\n\techo \"FAILED to find suitable passphrase file ...\" >&2\n\techo -n \"Try to enter your password: \" >&2\n\tread -r A </dev/console\n\techo -n \"$A\"\nfi\n", "num_lines": 29}
{"repo_name": "azure-linux-extensions", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh -e\n\nPREREQS=\"\"\n\nprereqs() { echo \"$PREREQS\"; }\n\ncase \"$1\" in\n    prereqs)\n    prereqs\n    exit 0\n    ;;\nesac\n\n. /usr/share/initramfs-tools/hook-functions\n\nmkdir -p ${DESTDIR}/boot/luks\ncopy_exec /boot/luks/osluksheader /boot/luks\n", "num_lines": 18}
{"repo_name": "azure-linux-utils", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! $# -eq 2 ]; then\n\techo \"Usage: ./find_kaslr_and_physbase.sh <vmlinux file> <coredump file>\"\n\techo \"vmlinux file: such as /usr/lib/debug/boot/vmlinux-4.15.0-88-generic\"\n\techo \"coredump file: coredump file generated by vm2core\"\n\texit 1\nfi\n\ncommand -v pcregrep >/dev/null 2>&1 || { echo \"Command 'pcregrep' not found. Try \\\"sudo apt install pcregrep\\\".  Aborting.\"; exit 1; }\n\necho \"This script takes minutes to hours depending on coredump file size ...\"\n\nstext_vmlinux=0x$(nm $1 | grep _stext | cut -d' ' -f1)\n\nt=\"/tmp/_$(basename $2)\"\nstrings $2 | grep 'VMCOREINFO' -A68 -B2 > $t.vmcoreinfo.1\npcregrep -A65 -M 'VMCOREINFO\\nOSRELEASE=' $t.vmcoreinfo.1 > $t.vmcoreinfo.2\nstext_coredump_count=0x$(grep 'SYMBOL(_stext)=' $t.vmcoreinfo.2 | wc -l)\n[[ $stext_coredump_count -gt 1 ]] && echo \"WARN: More than one _stext match, using the last, if it doesn't work look in file $t.vmcoreinfo.2 and try other matches\"\nstext_coredump=0x$(grep 'SYMBOL(_stext)=' $t.vmcoreinfo.2 | tail -1 | cut -d= -f2)\nkaslr=$((stext_coredump-stext_vmlinux))\necho \"kaslr = $kaslr\"\n\nphys_base_count=$(grep 'NUMBER(phys_base)=' $t.vmcoreinfo.2 | wc -l)\n[[ $phys_base_count -gt 1 ]] && echo \"WARN: More than one phys_base match, using the last, if it doesn't work look in file $t.vmcoreinfo.2 and try other matches\"\nphys_base=$(grep 'NUMBER(phys_base)=' $t.vmcoreinfo.2 | tail -1 | cut -d= -f2)\necho \"phys_base = $phys_base\"\n\necho \"The complete crash command you likely need is:\"\necho \"./crash/crash $1 $2 --kaslr $kaslr -m phys_base=$phys_base\"\n", "num_lines": 32}
{"repo_name": "azure-managedapp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#counter for iterating through definitions\ncounter=0\n\n#Get all applicationDefinitions names at subscription scope\nfor scdn in $(az resource list --resource-type \"Microsoft.Solutions/applicationDefinitions\" --output tsv --query [].name); do \n\n#get resource group of the definition\nscdrg=$(az resource list --resource-type \"Microsoft.Solutions/applicationDefinitions\" --output tsv --query [$counter].resourceGroup)\n\n#get the path to the mainTemplate file\nuriPath=$(az managedapp definition show --name $scdn --resource-group $scdrg --query artifacts[0].uri)\n\n#output the path to the Service Catalog Definition\naz managedapp definition show --name $scdn --resource-group $scdrg --query id\n\n#output the uri to the ARM template the service catalog definition contains\necho \"${uriPath/applicationResourceTemplate/mainTemplate}\"\t\necho\nlet counter+=1\ndone", "num_lines": 22}
{"repo_name": "azure-managedapp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nscript_name=`basename \"$0\"`\necho \"Running $script_name\"\n# Setup error handling\ntempfiles=( )\ncleanup() {\n  rm -f \"${tempfiles[@]}\"\n}\ntrap cleanup 0\n\nerror() {\n  local parent_lineno=\"$1\"\n  local message=\"$2\"\n  local code=\"${3:-1}\"\n  if [[ -n \"$message\" ]] ; then\n    echo \"Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}\"\n  else\n    echo \"Error on or near line ${parent_lineno}; exiting with status ${code}\"\n  fi\n\n  exit \"${code}\"\n}\ntrap 'error ${LINENO}' ERR\n\nrefresh_file() {\n    zipfile=$1\n    dirname=$(dirname $zipfile)\n    filename=$(basename $zipfile)\n    pushd $dirname\n    zip -f $filename\n    popd\n}\n\nexport -f refresh_file\nfind . -name \"*.zip\" -exec bash -c \"refresh_file \\\"{}\\\"\" \\;", "num_lines": 35}
{"repo_name": "azure-managedapp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Running deploy.sh\"\n# Setup error handling\ntempfiles=( )\ncleanup() {\n  rm -f \"${tempfiles[@]}\"\n}\ntrap cleanup 0\n\nerror() {\n  local parent_lineno=\"$1\"\n  local message=\"$2\"\n  local code=\"${3:-1}\"\n  if [[ -n \"$message\" ]] ; then\n    echo \"Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}\"\n  else\n    echo \"Error on or near line ${parent_lineno}; exiting with status ${code}\"\n  fi\n#  az logout\n\n  exit \"${code}\"\n}\ntrap 'error ${LINENO}' ERR\n\n# so repeat runs work, removing terraform state.\n# in production, you'd want one terraform state location per deployment\nif [[  -f \"terraform.tfstate\" ]]; then\n    rm terraform.tfstate\nfi\nif [[  -f \"terraform.tfstate.backup\" ]]; then\n    rm terraform.tfstate.backup\nfi\n\n# Load the config \necho \"Loading config\"\n. variables.conf\nazure_subscription_id=$(IFS='/' read -r -a parts <<< \\\n                          \"$managed_app_id\" \\\n                          && echo \"${parts[2]}\")\naz login --service-principal -u $service_principal_id -p $service_principal_secret --tenant $azure_ad_tenant_id\naz account set -s $azure_subscription_id\n\n# Login as the service principal\nresource_group_location=$(az managedapp show --ids $managed_app_id \\\n                          --query location --output tsv)\n\nmanaged_resource_group_id=$(az managedapp show --ids $managed_app_id \\\n                          --query managedResourceGroupId --output tsv)\n\nmanaged_resource_group_name=$(IFS='/' read -r -a parts <<< \\\n                          \"$managed_resource_group_id\" \\\n                          && echo \"${parts[-1]}\")\necho $managed_resource_group_name\n\n# Copy over the local azurerm provider\n# cp $GOPATH/bin/terraform-provider-azurerm  ./.terraform/plugins/linux_amd64/terraform-provider-azurerm_v2.0.0_x5\n\necho \"Checking terraform\"\nif [[ ! -d \".terraform\" ]]; then\n    terraform init\nfi\nrandom_end=$(head /dev/urandom | tr -dc a-z | head -c 5)\nbase_name=$(echo $base_name)$(echo $random_end)\nstg_account_name=$(echo $base_name)stg\necho $base_name\nterraform apply -auto-approve -var=\"azure_ad_tenant_id=$azure_ad_tenant_id\" \\\n                              -var=\"azure_subscription_id=$azure_subscription_id\" \\\n                              -var=\"service_principal_secret=$service_principal_secret\" \\\n                              -var=\"service_principal_id=$service_principal_client_id\" \\\n                              -var=\"resource_group_name=$managed_resource_group_name\" \\\n                              -var=\"base_name=$base_name\" \\\n                              -var=\"location=$resource_group_location\" \\\n                              -var=\"stg_account_name=$stg_account_name\"\n\n#az logout", "num_lines": 75}
{"repo_name": "azure-managedapp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Running deploy.sh\"\n# Setup error handling\ntempfiles=( )\n\n. variables.conf\nzip_file=simpleApp.zip\n\nazlogin() {\n    az login --service-principal -u $service_principal_client_id -p $service_principal_client_secret --tenant $azure_ad_tenant_id\n    az account set -s $azure_subscription_id\n}\n\nazlogout() {\n    az logout\n}\n\ncleanup() {\n  rm -f \"${tempfiles[@]}\"\n}\ntrap cleanup 0\n\nerror() {\n  local parent_lineno=\"$1\"\n  local message=\"$2\"\n  local code=\"${3:-1}\"\n  if [[ -n \"$message\" ]] ; then\n    echo \"Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}\"\n  else\n    echo \"Error on or near line ${parent_lineno}; exiting with status ${code}\"\n  fi\n  azlogout\n\n  exit \"${code}\"\n}\ntrap 'error ${LINENO}' ERR\n\n\nzip_files() {\n    echo \"Creating zip file\"\n\n    rm $zip_file\n    zip $zip_file createUiDefinition.json mainTemplate.json\n}\n\ninitialize_environment() {\n    echo \"Checking for resource group $managed_app_resource_group\"\n    resource_group_exists=$(az group exists --name $managed_app_resource_group)\n    if [[ $resource_group_exists == \"false\" ]]; then\n      echo \"Creating resource group $managed_app_resource_group\"\n      az group create --name $managed_app_resource_group --location $resource_group_location\n    fi\n\n    echo \"Checking for storage account $storage_account\"\n    storage_account_exists=$(az storage account check-name --name $storage_account --query nameAvailable --output tsv)\n    if [[ $storage_account_exists == \"false\" ]]; then\n        echo \"Creating storage account $storage_account\"\n        az storage account create --name $storage_account \\\n          --location $resource_group_location \\\n          --kind StorageV2 \\\n          --resource-group $managed_app_resource_group \\\n          --sku Standard_LRS\n    fi\n\n    echo \"Checking for storage container $storage_container\"\n    storage_connection_string=$(az storage account show-connection-string --name $storage_account --query connectionString --output tsv)\n    container_exists=$(az storage container exists --name $storage_container --connection-string $storage_connection_string)\n\n    if [[ $container_exists == \"false\" ]]; then\n        echo \"Creating storage container $storage_container\"\n        az storage container create --name $storage_container --connection-string $storage_connection_string\n    fi\n}\n\nupload_file() {\n    storage_connection_string=$(az storage account show-connection-string --name $storage_account --query connectionString --output tsv)\n    blob_exists=$(az storage blob exists --container-name $storage_container --connection-string $storage_connection_string --name $zip_file --output tsv)\n    #echo \"Blob exists: $blob_exists\"\n    if [[ blob_exists == \"True\" ]]; then\n        az storage blob delete --container-name $storage_container --connection-string $storage_connection_string --name $zip_file \n    fi\n\n    az storage blob upload -f $zip_file --container-name $storage_container --connection-string $storage_connection_string -n $zip_file\n}\n\ncreate_managed_app() {\n    if [[ $(az managedapp definition list --resource-group $managed_app_resource_group --output tsv | grep $managed_app_name | wc -c) != 0 ]]; then\n      echo \"Deleting managed app definition $managed_app_name\"\n      az managedapp definition delete --resource-group $managed_app_resource_group --name $managed_app_name\n    fi\n\n    package_location=\"https://$storage_account.blob.core.windows.net/$storage_container/$zip_file\"\n\n    parameters_file=$(cat ./managed-app-definition/parameters.json)\n    parameters_file=$(echo \"${parameters_file/__APPNAME__/$managed_app_name}\")\n    parameters_file=$(echo \"${parameters_file/__LOCATION__/$resource_group_location}\")\n    parameters_file=$(echo \"${parameters_file/__DESCRIPTION__/$managed_app_description}\")\n    parameters_file=$(echo \"${parameters_file/__DISPLAY_NAME__/$managed_app_display_name}\")\n    parameters_file=$(echo \"${parameters_file/__PACKAGE_FILE_URI__/$package_location}\")\n    parameters_file=$(echo \"${parameters_file/__PRINCIPAL_ID__/$managed_app_principal_id}\")\n    parameters_file=$(echo \"${parameters_file/__ROLE_DEFINITION_ID__/$managed_app_role_definition_id}\")\n    parameters_file=$(echo \"${parameters_file/__NOTIFICATION_ENDPOINT__/$managed_app_notification_endpoint}\")\n    echo $parameters_file > ./parameters.json\n    echo \"Deploying the managed app definition $managed_app_name\"\n    az deployment group create -g $managed_app_resource_group --template-file ./managed-app-definition/template.json --parameters @parameters.json\n}\n\nzip_files\nazlogin\ninitialize_environment\nupload_file\ncreate_managed_app\n\nazlogout\n", "num_lines": 115}
{"repo_name": "azure-mariadb", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\napt-get -y install nginx\necho \"stream { upstream mariadb { server $1.mariadb.database.azure.com:3306; } server { listen 3306; proxy_pass mariadb; } }\" >> /etc/nginx/nginx.conf\nservice nginx restart\nupdate-rc.d nginx defaults", "num_lines": 9}
{"repo_name": "azure-mariadb", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# PURPOSE\n# Migrate Azure Database for MariaDB Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\n# \n# DESCRIPTION\n# Pricing tiers in Azure Database for MariaDB\n# https://docs.microsoft.com/en-us/azure/mariadb/concepts-pricing-tiers\n# \n# Currently modifying pricing tier (to and from Basic) is not yet supported. \n# This script helps in migrating an existing database from Basic Pricing Tier to \n# General Purpose/Memory Optimized Pricing Tier. \n# This script uses mysqldump to extract a MariaDB database into a dump file\n# and mysql to restore the MariaDB database from an archive file created by mysqldump.\n#\n# Migrate your MariaDB database using dump and restore\n# https://docs.microsoft.com/en-us/azure/mariadb/howto-migrate-dump-restore\n#\n# PREREQUISITES\n# Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\n# mysql-client tools - mysqldump and mysql (https://dev.mysql.com/downloads/mysql/)\n# \n# NOTE\n# Target server and database are created in this script.\n# Please modify the script to specify different options for creation\n# https://docs.microsoft.com/en-us/cli/azure/mariadb/server?view=azure-cli-latest\n# \n# USAGE\n# bash mariadbmigrate.sh\n#         --source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --source-resource-group-name 'sourceRG'\n#         --source-server-name 'sourcemariadb'\n#         --source-username 'sourceuser'\n#         --source-password 'P@ssw0rd1'\n#         --source-database-name 'sourcedb'\n#         --target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --target-resource-group-name 'targetRG'\n#         --target-region 'eastus'\n#         --target-server-name 'targetmariadb'\n#         --target-username 'targetuser'\n#         --target-password 'P@ssw0rd2'\n#         --target-database-name 'targetdb'\n#         --target-sku 'GP_Gen5_2'\n#\nfunction usage()\n{\n    echo \"\"\n    echo \"PURPOSE\"\n    echo \"Migrate Azure Database for MariaDB Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\"\n    echo \"\"\n    echo \"DESCRIPTION\"\n    echo \"Pricing tiers in Azure Database for MariaDB - Single Server\"\n    echo \"https://docs.microsoft.com/en-us/azure/mariadb/concepts-pricing-tiers\"\n    echo \"\"\n    echo \"Currently modifying pricing tier (to and from Basic) is not yet supported.\"\n    echo \"This script helps in migrating an existing database from Basic Pricing Tier to\"\n    echo \"General Purpose/Memory Optimized Pricing Tier.\"\n    echo \"This script uses mysqldump to extract a MariaDB database into a dump file\"\n    echo \"and mysql to restore the MariaDB database from an archive file created by mysqldump.\"\n    echo \"\"\n    echo \"Migrate your MariaDB database using dump and restore\"\n    echo \"https://docs.microsoft.com/en-us/azure/mariadb/howto-migrate-dump-restore\"\n    echo \"\"\n    echo \"PREREQUISITES\"\n    echo \"Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\"\n    echo \"mysql-client tools - mysqldump and mysql (https://dev.mysql.com/downloads/mysql/)\"\n    echo \"\"\n    echo \"NOTE\"\n    echo \"Target server and database are created in this script.\"\n    echo \"Please modify the script to specify different options for server creation\"\n    echo \"https://docs.microsoft.com/en-us/cli/azure/mariadb/server?view=azure-cli-latest\"\n    echo \"\"\n    echo \"USAGE\"\n    echo \"bash mariadbmigrate.sh\"\n    echo -e \"\\t--source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--source-resource-group-name 'sourceRG'\"\n    echo -e \"\\t--source-server-name 'sourcemariadb'\"\n    echo -e \"\\t--source-username 'sourceuser'\"\n    echo -e \"\\t--source-password 'P@ssw0rd1'\"\n    echo -e \"\\t--source-database-name 'sourcedb'\"\n    echo -e \"\\t--target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--target-resource-group-name 'targetRG'\"\n    echo -e \"\\t--target-region 'eastus'\"\n    echo -e \"\\t--target-server-name 'targetmariadb'\"\n    echo -e \"\\t--target-username 'targetuser'\"\n    echo -e \"\\t--target-password 'P@ssw0rd2'\"\n    echo -e \"\\t--target-database-name 'targetdb'\"\n    echo -e \"\\t--target-sku 'GP_Gen5_2'\"\n    echo \"\"\n}\n\nPARAMS=\"\"\nwhile (( \"$#\" )); do\n  case \"$1\" in\n    -h | --help)\n      usage\n      exit\n      ;;\n    -a|--source-subscription-id)\n      SOURCE_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -b|--source-resource-group-name)\n      SOURCE_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -c|--source-server-name)\n      SOURCE_SERVER_NAME=$2\n      shift 2\n      ;;\n    -d|--source-username)\n      SOURCE_USERNAME=$2\n      shift 2\n      ;;\n    -e|--source-password)\n      SOURCE_PASSWORD=$2\n      shift 2\n      ;;\n    -f|--source-database-name)\n      SOURCE_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -g|--target-subscription-id)\n      TARGET_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -h|--target-resource-group-name)\n      TARGET_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -i|--target-region)\n      TARGET_REGION=$2\n      shift 2\n      ;;\n    -j|--target-server-name)\n      TARGET_SERVER_NAME=$2\n      shift 2\n      ;;\n    -k|--target-username)\n      TARGET_USERNAME=$2\n      shift 2\n      ;;\n    -l|--target-password)\n      TARGET_PASSWORD=$2\n      shift 2\n      ;;\n    -m|--target-database-name)\n      TARGET_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -n|--target-sku)\n      TARGET_SKU=$2\n      shift 2\n      ;;\n    --) # end argument parsing\n      shift\n      break\n      ;;\n    -*|--*=) # unsupported flags\n      echo \"Error: Unsupported flag $1\" >&2\n      exit 1\n      ;;\n    *) # preserve positional arguments\n      PARAMS=\"$PARAMS $1\"\n      shift\n      ;;\n  esac\ndone\n# set positional arguments in their proper place\neval set -- \"$PARAMS\"\n\n# Prerequisites - Install Azure CLI and mysql-client package\nif ! [ -x \"$(command -v az)\" ]; then\n  echo 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysqldump)\" ]; then\n  echo 'Error: mysqldump command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysql)\" ]; then\n  echo 'Error: mysql command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  exit 1\nfi\n\n# Login to source subscription\naz login\naz account set --subscription \"$SOURCE_SUBSCRIPTION_ID\"\n\n# Firewall rule name to allow the current VM\nexport FIREWALLRULENAME=\"AllowAllIps$(date +%s)\"\n\n# Create firewall rule on the source server to allow connections from current VM\naz mariadb server firewall-rule create -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Export mariadb password to be used by the mysqldump command\nexport MYSQL_PWD=$SOURCE_PASSWORD\n\n# Remove dump file if it already exists\n[ -e \"$SOURCE_DATABASE_NAME.sql\" ] && rm -f \"$SOURCE_DATABASE_NAME.sql\"\n\n# Create a dump file of the source db\nmysqldump --ssl-mode=REQUIRED -Fc -v --host=\"$SOURCE_SERVER_NAME.mariadb.database.azure.com\" --user=\"$SOURCE_USERNAME@$SOURCE_SERVER_NAME\" --databases \"$SOURCE_DATABASE_NAME\" >\"$SOURCE_DATABASE_NAME.sql\"\n\n# check that filesize of dump file is greater than 0\nif ! [ -s \"$SOURCE_DATABASE_NAME.sql\" ]; then\n  echo 'Error during mysqldump' >&2\n  exit 1\nfi\n\n# Login to target subscription \naz account set --subscription \"$TARGET_SUBSCRIPTION_ID\"\n\n# Set target server password\nexport MYSQL_PWD=$TARGET_PASSWORD\n\n# Create the target server in the specified region\naz mariadb server create -l \"$TARGET_REGION\" -g \"$TARGET_RESOURCE_GROUP_NAME\" -n \"$TARGET_SERVER_NAME\" -u \"$TARGET_USERNAME\" -p \"$MYSQL_PWD\" --sku-name \"$TARGET_SKU\"\n\n# Create the target database\naz mariadb db create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$TARGET_DATABASE_NAME\"\n\n# Create firewall rule on the target server to allow connections from current VM\naz mariadb server firewall-rule create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Restore the database using source database dump file\nmysql --ssl-mode=REQUIRED -v --host=\"$TARGET_SERVER_NAME.mariadb.database.azure.com\" --port=3306 --user=\"$TARGET_USERNAME@$TARGET_SERVER_NAME\" < \"$SOURCE_DATABASE_NAME.sql\"\n\n# Delete firewall rules and local dump file\naz mariadb server firewall-rule delete -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\naz mariadb server firewall-rule delete -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\nrm -f \"$SOURCE_DATABASE_NAME.sql\"\n\n# Logout\naz logout\n\n# Visit Target Server\necho \"Migration Successful !!\"\necho \"Target Server : https://portal.azure.com/#resource/subscriptions/$TARGET_SUBSCRIPTION_ID/resourceGroups/$TARGET_RESOURCE_GROUP_NAME/providers/Microsoft.DBforMariaDB/servers/$TARGET_SERVER_NAME/overview\"", "num_lines": 241}
{"repo_name": "azure-mobile-engagement-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "\nexport INIDIR=$PWD\ncd AZME/sample\n\n# GENERIC\nexport APP_NAME=AZMECordova\nexport PACKAGE_NAME=<...>\nexport AZME_REDIRECT_URL=myapp\nexport AZME_ENABLE_LOG=true\nexport AZME_LOGO=azme\n\n# IOS\nexport AZME_IOS_CONNECTION_STRING=<...>\n#ANDROID\nexport AZME_ANDROID_GOOGLE_PROJECT_NUMBER=<...>\nexport AZME_ANDROID_CONNECTION_STRING=<...>\n\nexport DST_PATH=~\nexport CURDIR=$PWD\n\nrm -rf $DST_PATH/$APP_NAME\ncd $DST_PATH\ncordova create $APP_NAME $PACKAGE_NAME $APP_NAME\ncd $APP_NAME\n\ncordova platform add ios\ncordova platform add android\ncordova plugin add cordova-plugin-console\ncordova plugin add $CURDIR/../sample/resources\n\ncordova plugin add cordova-plugin-ms-azure-mobile-engagement    --variable AZME_IOS_CONNECTION_STRING=$AZME_IOS_CONNECTION_STRING \\\n                                        --variable AZME_ANDROID_GOOGLE_PROJECT_NUMBER=$AZME_ANDROID_GOOGLE_PROJECT_NUMBER \\\n                                        --variable AZME_REDIRECT_URL=$AZME_REDIRECT_URL \\\n                                        --variable AZME_ANDROID_CONNECTION_STRING=$AZME_ANDROID_CONNECTION_STRING \\\n                                        --variable AZME_ANDROID_REACH_ICON=$AZME_LOGO \\\n                                        --variable AZME_IOS_REACH_ICON=$AZME_LOGO.png  \n\n\ncordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-test-framework.git\ncordova plugin add $CURDIR/../plugin/tests\n\nrm -rf www\ncp -r  $CURDIR/www .\ncp $CURDIR/azure-icon.png .\n\nrm config.xml\ncp $CURDIR/config.xml .\n\ncd $INIDIR\necho \"Sample project successfully created in $DST_PATH/$APP_NAME\"", "num_lines": 50}
{"repo_name": "azure-mobile-engagement-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n# replace with your own IDs \n\n# GENERIC\nexport APP_NAME=CapptainCordova\nexport PACKAGE_NAME=com.del7a.capptaincordova\nexport CAPPTAIN_REDIRECT_URL=mytest\nexport CAPPTAIN_ENABLE_LOG=true\n\n# IOS\nexport CAPPTAIN_IOS_APP_ID=<CAPPTAIN_IOS_APP_ID>\nexport CAPPTAIN_IOS_SDK_KEY=<CAPPTAIN_IOS_SDK_KEY>\nexport CAPPTAIN_IOS_REACH_ICON=icon.png\n\n#ANDROID\nexport CAPPTAIN_ANDROID_REACH_ICON=icon\nexport CAPPTAIN_ANDROID_APP_ID=<CAPPTAIN_ANDROID_APP_ID>\nexport CAPPTAIN_ANDROID_GOOGLE_PROJECT_NUMBER=<CAPPTAIN_ANDROID_GOOGLE_PROJECT_NUMBER>\n\nexport DST_PATH=~\nexport CURDIR=$PWD\n\n\nrm -rf $DST_PATH/$APP_NAME\ncd $DST_PATH\ncordova create $APP_NAME $PACKAGE_NAME $APP_NAME\ncd $APP_NAME\ncordova platform add ios\ncordova platform add android\ncordova plugin add cordova-plugin-console\ncordova plugin add capptain-cordova \t--variable CAPPTAIN_IOS_APP_ID=$CAPPTAIN_IOS_APP_ID \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_IOS_SDK_KEY=$CAPPTAIN_IOS_SDK_KEY \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_IOS_REACH_ICON=$CAPPTAIN_IOS_REACH_ICON \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_ANDROID_APP_ID=$CAPPTAIN_ANDROID_APP_ID \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_ANDROID_GOOGLE_PROJECT_NUMBER=$CAPPTAIN_ANDROID_GOOGLE_PROJECT_NUMBER \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_ANDROID_REACH_ICON=$CAPPTAIN_ANDROID_REACH_ICON \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_REDIRECT_URL=$CAPPTAIN_REDIRECT_URL \\\n\t\t\t\t\t\t\t\t--variable CAPPTAIN_ENABLE_LOG=$CAPPTAIN_ENABLE_LOG\ncordova plugin add http://git-wip-us.apache.org/repos/asf/cordova-plugin-test-framework.git\ncordova plugin add capptain-cordova#:tests\n\nrm -rf www\ncp -r  $CURDIR/www .\n\ncd $CURDIR\necho \"Sample project successfully created in $DST_PATH/$APP_NAME\"", "num_lines": 46}
{"repo_name": "azure-mobile-engagement-unity", "repo_creator": "Azure", "programming_language": "Shell", "code": " \nPACKAGEPATH=\"$PWD/Engagement.unitypackage\"\nrm $PACKAGEPATH\n\nSRCDIR=\"$PWD/src\"\n\n#-1 Create Empty App to receive the package\n\nUNITYPROJECTNAME=\"engagement-project\"\nUNITYPROJECT=\"$PWD/$UNITYPROJECTNAME\"\nrm -rf $UNITYPROJECT\n\necho \"Creating $UNITYPROJECT\"\nUNITYAPP=/Applications/Unity/Unity.app/Contents/MacOS/Unity\n$UNITYAPP -batchmode -quit -createProject $UNITYPROJECTNAME\n\n#-2 Copy the plugin files to the project\n\ncp -r src/EngagementPlugin \"$UNITYPROJECT/Assets\"\n\nTARGETAZME=\"$UNITYPROJECT/Assets/EngagementPlugin\"\n\n#-3 Build the iOS Library\n\nTARGETIOS=\"$TARGETAZME/iOS\"\nSRCIOSDIR=\"$PWD/src/iOS\"\n\nPROJECTFILENAME=\"EngagementUnity.xcodeproj\"\nBUILD_PATH=\"$PWD/~build\"\nBUILD_DIR=\"$BUILD_PATH/build-$TARGETAPP\"\nTMP_DIR=\"$BUILD_PATH/tmp-$TARGETAPP\"\n\nrm -rf \"$BUILD_PATH\"\nrm -rf \"$PROJECTDIR/$PROJECTFILENAME/build\"\nmkdir \"$BUILD_PATH\"\nTARGETAPP=\"EngagementUnity\"\nCONFIG=\"Release\"\nxcodebuild -project \"$SRCIOSDIR/$PROJECTFILENAME\" -target \"$TARGETAPP\" -configuration \"$CONFIG\" BUILD_DIR=\"$BUILD_DIR\" TMP_DIR=\"$TMP_DIR\" \n\n#-4 Copy iOS artefacts\n\nIOSLIBRARYNAME=\"libEngagementUnity.a\"\nrm \"$TARGETIOS/$IOSLIBRARYNAME\"\ncp \"$BUILD_DIR/$CONFIG-iphoneos/$IOSLIBRARYNAME\" \"$TARGETIOS/$IOSLIBRARYNAME\"\n\nrm -rf \"$TARGETIOS/res\"\nmkdir \"$TARGETIOS/res\"\n\ncp \"$SRCIOSDIR/EngagementReach/res/close.png\" \"$TARGETIOS/res\" \ncp \"$SRCIOSDIR/EngagementReach/res/AEDefaultAnnouncementView.xib\" \"$TARGETIOS/res\" \ncp \"$SRCIOSDIR/EngagementReach/res/AEDefaultPollView.xib\" \"$TARGETIOS/res\" \ncp \"$SRCIOSDIR/EngagementReach/res/AENotificationView.xib\" \"$TARGETIOS/res\" \ncp \"$SRCIOSDIR/EngagementSDK/Classes/AEIdfaProvider.h\" \"$TARGETIOS\"\ncp \"$SRCIOSDIR/EngagementSDK/Classes/AEIdfaProvider.m\" \"$TARGETIOS\"\n\n#-5 Build Android library\n\nTARGETANDROID=\"$TARGETAZME/Android\"\nANDROIDLIBRARYNAME=\"libEngagementUnity.aar\"\n\nrm -rf \"$TARGETANDROID\"\nmkdir \"$TARGETANDROID\"\n\nSAVEPWD=$PWD\ncd \"$PWD/src/Android\"\n./gradlew clean\n./gradlew build\ncd \"$SAVEPWD\"\n\ncp \"$SAVEPWD/src/Android/libEngagementUnity/build/outputs/aar/libEngagementUnity-release.aar\" \"$TARGETANDROID/$ANDROIDLIBRARYNAME\"\n\n#-7 Build the package by launching Unity from the command line\n\n\n$UNITYAPP  -batchmode -quit -projectPath \"$UNITYPROJECT\" -exportPackage \"Assets/EngagementPlugin\" \"$PACKAGEPATH\"\n\n#-8 Done\n", "num_lines": 78}
{"repo_name": "azure-mobile-engagement-unity", "repo_creator": "Azure", "programming_language": "Shell", "code": "PROJECTNAME=SampleProject\nUNITY=/Applications/Unity/Unity.app/Contents/MacOS/Unity\nPROJECTPATH=$PWD/$PROJECTNAME\nAZMEPACKAGEPATH=$PWD/../Engagement.unitypackage\n\nrm -rf $PROJECTNAME\n$UNITY -batchmode -quit -createProject $PROJECTNAME\n$UNITY -batchmode -quit -projectPath $PROJECTPATH -importPackage $AZMEPACKAGEPATH\n\nASSETSPATH=\"$PROJECTNAME/Assets\"\nEDITORPATH=\"$ASSETSPATH/Editor\"\nmkdir $EDITORPATH\n\ncp Sample.cs $ASSETSPATH\ncp SampleSetup.cs $EDITORPATH\n\n$UNITY  -projectPath $PROJECTPATH  -executeMethod SampleSetup.CreateSampleScene &", "num_lines": 17}
{"repo_name": "azure-mobile-services", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\necho \"Downloading Google Cloud Messaging R3\"\ncurl -O https://dl-ssl.google.com/android/repository/gcm_r03.zip\n\necho \"Decompressing...\"\nunzip gcm_r03.zip\n\necho \"Removing zip\"\nrm gcm_r03.zip\n\necho \"Move library to destination\"\nmv ./gcm_r03/gcm-client/dist/gcm.jar ./\n\necho \"Remove extra files\"\nrm -rf ./gcm_r03", "num_lines": 16}
{"repo_name": "azure-mobile-services", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ \"$1\" = \"\" ]; then\n  echo Usage: $0 \\<applicationName\\>\n  echo .  Where \\<applicationName\\> is an Azure Mobile Service app.\nelse\n  azure mobile api create $1 admin \u00e2\u20ac\u201d-permissions *=admin\n  azure mobile api create $1 application \u00e2\u20ac\u201d-permissions *=application\n  azure mobile api create $1 user \u00e2\u20ac\u201d-permissions *=user\n  azure mobile api create $1 public \u00e2\u20ac\u201d-permissions *=public\n  azure mobile api create $1 shared \u00e2\u20ac\u201d-permissions *=admin\n  azure mobile api create $1 movieFinder \u00e2\u20ac\u201d-permissions *=application\n  azure mobile api create $1 runtimeInfo \u00e2\u20ac\u201d-permissions GET=public,POST=admin\n\n  azure mobile script upload $1 api/admin.js -f admin.js\n  azure mobile script upload $1 api/application -f application.js\n  azure mobile script upload $1 api/user -f user.js\n  azure mobile script upload $1 api/public -f public.js\n  azure mobile script upload $1 api/shared -f shared.js\n  azure mobile script upload $1 api/movieFinder -f movieFinder.js\n  azure mobile script upload $1 api/runtimeInfo -f runtimeInfo.js\n\nfi\n", "num_lines": 23}
{"repo_name": "azure-mobile-services", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nif [ \"$1\" = \"\" ]; then\n  echo Usage: $0 \\<applicationName\\>\n  echo .  Where \\<applicationName\\> is an Azure Mobile Service app.\n  echo .  To run the login tests, the application needs to be configured\n  echo .    with all four login providers.\nelse\n  azure mobile table create $1 stringIdRoundTripTable\n  azure mobile table create $1 stringIdRoundTripSoftDeleteTable\n  azure mobile table create $1 stringIdMovies\n  azure mobile table create $1 offlineReady\n  azure mobile table create $1 offlineReadyNoVersion\n  azure mobile table update --deleteColumn __version --quiet $1 offlineReadyNoVersion\n  azure mobile table create --integerId $1 public\n  azure mobile table create --integerId $1 admin\n  azure mobile table create --integerId $1 application\n  azure mobile table create --integerId $1 authenticated\n  azure mobile table create --integerId $1 intIdMovies\n  azure mobile table create --integerId $1 ParamsTestTable\n\n  #Tables specific to JS tests\n  azure mobile table create --integerId $1 w8jsRoundTripTable\n  azure mobile table create $1 w8jsServerQueryMovies\n\n  #Tables specific to Managed tests\n  azure mobile table create --integerId $1 w8RoundTripTable\n\n  #Tables specific to iOS tests\n  azure mobile table create --integerId $1 iosRoundTripTable\n\n  #Tables specific to Android tests\n  azure mobile table create --integerId $1 droidRoundTripTable\n\n  #Tables used in push tests\n  azure mobile table create $1 iosPushTest\n  azure mobile table create $1 w8PushTest\n  azure mobile table create $1 wp8PushTest\n  azure mobile table create --integerId $1 droidPushTest\n\n  azure mobile table update -p insert=admin,read=admin,update=admin,delete=admin $1 admin\n  azure mobile table update -p insert=application,read=application,update=application,delete=application $1 application\n  azure mobile table update -p insert=user,read=user,update=user,delete=user $1 authenticated\n  azure mobile table update -p insert=application,read=public,update=public,delete=public $1 public\n  azure mobile table update -p insert=user,read=user,update=user,delete=user $1 offlineReadyNoVersionAuthenticated\n\n  azure mobile script upload $1 table/stringIdRoundTripTable.insert -f stringIdRoundTripTable.insert.js\n  azure mobile script upload $1 table/stringIdRoundTripTable.update -f stringIdRoundTripTable.update.js\n  azure mobile script upload $1 table/stringIdRoundTripTable.read -f stringIdRoundTripTable.read.js\n  azure mobile script upload $1 table/stringIdMovies.insert -f bothIdTypeMovies.insert.js\n  azure mobile script upload $1 table/intIdMovies.insert -f bothIdTypeMovies.insert.js\n  azure mobile script upload $1 table/ParamsTestTable.insert -f ParamsTestTable.insert.js\n  azure mobile script upload $1 table/ParamsTestTable.read -f ParamsTestTable.read.js\n  azure mobile script upload $1 table/ParamsTestTable.delete -f ParamsTestTable.delete.js\n  azure mobile script upload $1 table/ParamsTestTable.update -f ParamsTestTable.update.js\n  azure mobile script upload $1 table/iosAuthenticated.insert -f iosAuthenticated.insert.js\n  azure mobile script upload $1 table/iosAuthenticated.read -f iosAuthenticated.read.js\n  azure mobile script upload $1 table/iosAuthenticated.update -f iosAuthenticated.update.js\n  azure mobile script upload $1 table/iosAuthenticated.delete -f iosAuthenticated.delete.js\n\n  #Tables specific to JS tests\n  azure mobile script upload $1 table/w8jsRoundTripTable.insert -f w8jsRoundTripTable.insert.js\n  azure mobile script upload $1 table/w8jsRoundTripTable.read -f w8jsRoundTripTable.read.js\n  azure mobile script upload $1 table/w8jsRoundTripTable.update -f w8jsRoundTripTable.update.js\n  azure mobile script upload $1 table/w8jsServerQueryMovies.read -f w8jsServerQueryMovies.read.js\n\n  #Tables specific to managed tests\n  azure mobile script upload $1 table/w8RoundTripTable.insert -f w8RoundTripTable.insert.js\n  azure mobile script upload $1 table/w8RoundTripTable.read -f w8RoundTripTable.read.js\n  azure mobile script upload $1 table/w8RoundTripTable.update -f w8RoundTripTable.update.js\n\n  #Tables specific to iOS tests\n  azure mobile script upload $1 table/iosRoundTripTable.insert -f iosRoundTripTable.insert.js\n\n  #Tables specific to Android tests\n  azure mobile script upload $1 table/droidRoundTripTable.insert -f droidRoundTripTable.insert.js\n  azure mobile script upload $1 table/droidRoundTripTable.read -f droidRoundTripTable.read.js\n  azure mobile script upload $1 table/droidRoundTripTable.update -f droidRoundTripTable.update.js\n\n  #Tables used in Push tests\n  azure mobile script upload $1 table/w8PushTest.insert -f w8PushTest.insert.js\n  azure mobile script upload $1 table/wp8PushTest.insert -f wp8PushTest.insert.js\n  azure mobile script upload $1 table/iosPushTest.insert -f iosPushTest.insert.js\n  azure mobile script upload $1 table/droidPushTest.insert -f droidPushTest.insert.js\n\nfi\n", "num_lines": 86}
{"repo_name": "azure-mobile-services-quickstarts", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Check that Python is available\ncommand -v python >/dev/null 2>&1 || {\n    echo >&2 \"Cannot find python. Either:\n      - Install python\n      - Or, serve the quickstart files from an alternative web server such as Apache.\"\n    exit 1\n}\n\n# Go to the directory containing the www files (one level above where this script is)\n# and then start the simple web server\npushd `dirname $0` > /dev/null\ncd ..\npython -m SimpleHTTPServer 8000\n\n# Finally, return to the original directory\npopd > /dev/null\n", "num_lines": 19}
{"repo_name": "azure-mobile-services-test", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\necho \"Downloading Google Gson 2.2.2\"\ncurl -O http://google-gson.googlecode.com/files/google-gson-2.2.2-release.zip\n\necho \"Decompressing...\"\nunzip google-gson-2.2.2-release.zip\n\necho \"Removing zip\"\nrm google-gson-2.2.2-release.zip\n\necho \"Move library to destination\"\nmv ./google-gson-2.2.2/gson-2.2.2.jar ./\n\necho \"Remove extra files\"\nrm -rf ./google-gson-2.2.2\n\necho \"Downloading Google Cloud Messaging R3\"\ncurl -O https://dl-ssl.google.com/android/repository/gcm_r03.zip\n\necho \"Decompressing...\"\nunzip gcm_r03.zip\n\necho \"Removing zip\"\nrm gcm_r03.zip\n\necho \"Move library to destination\"\nmv ./gcm_r03/gcm-client/dist/gcm.jar ./\n\necho \"Remove extra files\"\nrm -rf ./gcm_r03\n\necho \"Downloading Guava Libraries 17.0\"\ncurl -O http://search.maven.org/remotecontent?filepath=com/google/guava/guava/17.0/guava-17.0.jar", "num_lines": 34}
{"repo_name": "azure-mobile-services-test", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -x\n\n# Make sure we are executing in this script's directory\ncd \"$( cd \"$( dirname \"$0\" )\" && pwd )\"\nrm -R Results\nmkdir Results\n\nDIR=\"$( pwd )\"\n\nif [ $# -lt 6 ]\nthen\n  #           $0 $1                  $2                  $3         $4                        $5           $6             $7 (optional)\n  echo Usage: $0 \\<Application URL\\> \\<Application Key\\> \\<device\\> \\<zumotestuser password\\> \\<Blob URL\\> \\<Blob Token\\> \\<iOSsdkZip\\>\n  echo Where\n  echo   \\<Application URL\\> is the URL of the Mobile Service\n  echo   \\<Application key\\> is the app key for that service\n  echo   \\<device\\> is one of the following:\n  echo       - iPad2Sim             - iPadSimAir          - iPadSimAir2\n  echo       - iPadSimPro           - iPadSimRetina       - iPhoneSim4s\n  echo       - iPhoneSim5           - iPhoneSim5s         - iPhoneSim6\n  echo       - iPhoneSim6Plus       - iPhoneSim6s         - iPhoneSim6sWatch\n  echo       - iPhone6sPlus         - iPhone6sPlusWatch\n  echo   \\<loginPassword\\> - the password to use for log in operations \\(for zumotestuser account\\)\n  echo   \\<iOSsdkZip\\> is the zip file location of the framework to test against \\(optional\\)\n  exit 1\nfi\n\necho \"$3\"\nexport DEVICE_ARG=\nexport APP_NAME=\nexport DEVICE_CMD_ARG=$3\n\necho Device: $DEVICE_CMD_ARG\n\n# Build current app to test with\npushd ZumoE2ETestApp\n\nif [ $7 ]\nthen\n  # Copy specified framework\n  cp -f $7 sdk.zip\nelse\n  # Copy in current version of the framework\n  curl --location --output sdk.zip --silent http://aka.ms/gc6fex\nfi\n\nunzip -o sdk.zip\n\nxcodebuild -sdk iphonesimulator9.1 || exit 1\n\npopd\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPad2Sim\" ]; then\n  echo Using iPad 2 Simulator\n  export DEVICE_ARG=iPad\\ 2\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPadSimAir\" ]; then\n  echo Using iPad Air Simulator\n  export DEVICE_ARG=iPad\\ Air\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPadSimAir2\" ]; then\n  echo Using iPad Air 2 Simulator\n  export DEVICE_ARG=iPad\\ Air\\ 2\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPadSimPro\" ]; then\n  echo Using iPad Pro Simulator\n  export DEVICE_ARG=iPad\\ Pro\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPadSimRetina\" ]; then\n  echo Using iPad Retina Simulator\n  export DEVICE_ARG=iPad\\ Retina\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim4s\" ]; then\n  echo Using iPhone 4s Simulator\n  export DEVICE_ARG=iPhone\\ 4s\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim5\" ]; then\n  echo Using iPhone 5 Simulator\n  export DEVICE_ARG=iPhone\\ 5\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim5s\" ]; then\n  echo Using iPhone 5s Simulator\n  export DEVICE_ARG=iPhone\\ 5s\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6\" ]; then\n  echo Using iPhone 6 Simulator\n  export DEVICE_ARG=iPhone\\ 6\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6Plus\" ]; then\n  echo Using iPhone 6 Plus Simulator\n  export DEVICE_ARG=iPhone\\ 6\\ Plus\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6s\" ]; then\n  echo Using iPhone 6s Simulator\n  export DEVICE_ARG=iPhone\\ 6s\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6sWatch\" ]; then\n  echo Using iPhone 6s Simulator + Apple Watch\n  export DEVICE_ARG=iPhone\\ 6s\\ \\(9.1\\)\\ +\\ Apple\\ Watch\\ -\\ 38mm\\ \\(2.0\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6sPlus\" ]; then\n  echo Using iPhone 6s Plus Simulator\n  export DEVICE_ARG=iPhone\\ 6s\\ \\(9.1\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$DEVICE_CMD_ARG\" == \"iPhoneSim6sPlusWatch\" ]; then\n  echo Using iPhone 6s Plus Simulator + Apple Watch\n  export DEVICE_ARG=iPhone\\ 6s\\ Plus\\ \\(9.1\\)\\ +\\ Apple\\ Watch\\ -\\ 42mm\\ \\(2.0\\)\n  APP_NAME=$DIR/ZumoE2ETestApp/build/Release-iphonesimulator/ZumoE2ETestApp.app\nfi\n\nif [ \"$APP_NAME\" == \"\" ]\nthen\n  echo Unsupported device: \"$3\"\n  exit 1\nfi\n\necho DEVICE_ARG: $DEVICE_ARG\necho APP_NAME: $APP_NAME\nEscapedToken=${6//&/\\\\&}\n\nsed -e \"s|--APPLICATION_URL--|$1|g\" ZumoAutomationTemplate.js > ZumoAutomationWithData.js\nsed -e \"s|--APPLICATION_KEY--|$2|g\" -i \"\" ZumoAutomationWithData.js\nsed -e \"s|--BLOB_URL--|$5|g\" -i \"\" ZumoAutomationWithData.js\nsed -e \"s|--BLOB_TOKEN--|$EscapedToken|g\" -i \"\" ZumoAutomationWithData.js\nsed -e \"s|--AUTH_PASSWORD--|$4|g\" -i \"\" ZumoAutomationWithData.js\n\necho Replaced data on template - now running instruments\necho Args: DEVICE_ARG = $DEVICE_ARG\necho APP_NAME = $APP_NAME\n\nexport INSTRUMENT_TEMPLATE=/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate\n\necho Running instruments...\ninstruments -w \"$DEVICE_ARG\" -t \"$INSTRUMENT_TEMPLATE\" \"$APP_NAME\" -e UIASCRIPT \"ZumoAutomationWithData.js\" -e UIARESULTSPATH \"Results\" || exit 1\n\nexit 0\n", "num_lines": 163}
{"repo_name": "azure-mobile-services-test", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngit clean -xdfq\n\n# Make sure we are executing in this script's directory\ncd \"$( cd \"$( dirname \"$0\" )\" && pwd )\"\nrm -R Results\nmkdir Results\n\nDIR=\"$( pwd )\"\n\nif [ $# -lt 9 ]\nthen\n  echo 'Usage:' $0 '<Application URL> <Application key> <Daylight URL> <Daylight Project> <clientId> <clientSecret> <runId> <Tag expression> <Runtime version> <nugetSourceOverride>'\n  echo 'Where'\n  echo '  <Application URL> is the URL of the Mobile Service'\n  echo '  <Application key> is the app key for that service'\n  echo '  <Tag expression> example: !NodeRuntimeOnly*!DotNetRuntimeBug'\n  echo '  <Runtime version> is reported to daylight'\n  echo '  <nugetSourceOverride> will perform a nuget update from the specified location'\n  exit 1\nfi\n\nSLN_FILE=$DIR/../../Microsoft.WindowsAzure.Mobile.Managed_IncludeXamarin.sln\n\nmobileAppUrl=$1\nmobileAppKey=$2\ndayLightUrl=$3\ndayLightProject=$4\nclientId=$5\nclientSecret=$6\nrunId=$7\ntags=$8\nrunTimeVersion=$9\nshift\nnugetSourceOverride=$9\n\necho\necho \"===============================================\"\necho \"=== Input command line parameters:\"\necho \"===    mobileAppUrl:    $mobileAppUrl\"\necho \"===    mobileAppKey:    $mobileAppKey\"\necho \"===    dayLightUrl:     $dayLightUrl\"\necho \"===    dayLightProject: $dayLightProject\"\necho \"===    clientId:        $clientId\"\necho \"===    clientSecret:    $clientSecret\"\necho \"===    runId:           $runId\"\necho \"===    tags:            $tags\"\necho \"===    runTimeVersion:  $runTimeVersion\"\necho \"===    nugetSourceOverride: $nugetSourceOverride\"\necho \"===============================================\"\necho\n\necho\necho Updating NuGet if required ...\nnuget update -self -Verbose\n\necho\necho Restoring Nuget packages...\nnuget restore $SLN_FILE\n\nif [[ $nugetSourceOverride ]]\nthen\n  echo Updating Nuget from $nugetSourceOverride\n  nuget update $SLN_FILE -Source $nugetSourceOverride -Verbose -Prerelease\nelse\n  echo Not updating Nugets\nfi\n\necho\necho Building...\n/Applications/Xamarin\\ Studio.app/Contents/MacOS/mdtool build -t:Build -c:\"Debug|iPhoneSimulator\" $SLN_FILE || exit 1\n\n\nDEVICE_ARG=iPhone\\ 6\\ \\(8.3\\ Simulator\\)\nAPP_NAME=$DIR/bin/iPhoneSimulator/Debug/MicrosoftWindowsAzureMobileiOSE2ETest.app\n\necho APP_NAME: $APP_NAME\n\necho\necho Skipping test CustomAPI_JToken_SupportsAnyFormat...\ntags=\"$tags -CustomAPI_JToken_SupportsAnyFormat\"\necho \"   Adjusted tags to '$tags'\"\n\ncp ZumoAutomationTemplate.js ZumoAutomationWithData.js\nsed -e \"s|--APPLICATION_URL--|$mobileAppUrl|g\"     ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--APPLICATION_KEY--|$mobileAppKey|g\"     ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--DAYLIGHT_URL--|$dayLightUrl|g\"         ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--DAYLIGHT_PROJECT--|$dayLightProject|g\" ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--CLIENT_ID--|$clientId|g\"               ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--CLIENT_SECRET--|$clientSecret|g\"       ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--RUN_ID--|$runId|g\"                     ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--TAG_EXPRESSION--|$tags|g\"              ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\nsed -e \"s|--RUNTIME_VERSION--|$runTimeVersion|g\"   ZumoAutomationWithData.js > tmp.js && mv tmp.js ZumoAutomationWithData.js || exit 1\n\nINSTRUMENT_TEMPLATE=/Applications/Xcode.app/Contents/Applications/Instruments.app/Contents/PlugIns/AutomationInstrument.xrplugin/Contents/Resources/Automation.tracetemplate\n\necho\necho Running instruments...\ninstruments -w \"$DEVICE_ARG\" -t \"$INSTRUMENT_TEMPLATE\" \"$APP_NAME\" -e UIASCRIPT \"ZumoAutomationWithData.js\" -e UIARESULTSPATH \"Results\" || exit 1\n\nexit 0\n", "num_lines": 103}
{"repo_name": "Azure-Monitor-for-SAP-solutions-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "sysctl vm.drop_caches=3\nsystemctl restart purge-kernels.service\necho \"$(grep '^ID=' /etc/*-release)\"\n# ID is \"rhel\" or \"sles\" based on redhat/suse\n\nif [[ \"$(grep '^ID=' /etc/*-release)\" == *\"rhel\"* ]]; then\n    echo \"Running yum install command for RHEL\"\n    yum install pcp pcp-pmda-hacluster -y\n    echo \"Enable and start the required PCP Collector Services.\"\n    systemctl enable pmcd\n    systemctl start pmcd\n    cd /var/lib/pcp/pmdas/hacluster\n    ./Install\n    echo \"Enable and start the pmproxy service.\"\n    systemctl start pmproxy\n    systemctl enable pmproxy\n    echo \"you can check the metrics on http://<IP-Address>:44322/metrics\"\nelse\n    echo \"Running zypper install command\"\n    sudo zypper install prometheus-ha_cluster_exporter -y\n    echo \"starting ha cluster exporter\"\n    ha_cluster_exporter\n    echo \"you can check the metrics on http://<IP-Address>:9664/metrics\"\nfi\necho \"Manual commands execution Completed\"\n", "num_lines": 26}
{"repo_name": "Azure-Monitor-for-SAP-solutions-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Downloading and setting up node exported.\n# You can check the latest version of the node exporter by using the below link and update the references in the script.\n# https://github.com/prometheus/node_exporter/releases\n\necho \"Downloading node exporter 1.3.1\"\nwget 'https://github.com/prometheus/node_exporter/releases/download/v1.3.1/node_exporter-1.3.1.linux-amd64.tar.gz' -O node_exporter-1.3.1.linux-amd64.tar.gz \n\necho \"Starting to unzip node exporter file\"\ntar -zxvf node_exporter-1.3.1.linux-amd64.tar.gz\n\nif [[ \"$(grep '^ID=' /etc/*-release)\" == *\"rhel\"* ]]; then\n    echo \"Open firewall port 9100 on the Linux host\"\n    yum install firewalld -y\n    systemctl start firewalld\n    firewall-cmd --zone=public --permanent --add-port 9100/tcp\nelse\n    sudo ufw allow 9100/tcp\n    sudo ufw reload\nfi\n\necho \"Start listening on port 9100\"\ncd node_exporter-1.3.1.linux-amd64 && nohup ./node_exporter --web.listen-address=\":9100\" &\n", "num_lines": 23}
{"repo_name": "Azure-Monitor-for-SAP-solutions-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# <copyright file=\"GenerateHostfileMappings.sh\" company=\"Microsoft Corporation\">\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# </copyright>\n\n#!/bin/bash\n\n# Replace instance number with the instance number of the Central Server instance\ninstanceNumber=00\n\n# Set the path to the SAP hostctrl executable\ncd \"/usr/sap/hostctrl/exe\"\n\n# Get the hostnames of the SAP system instance\nhosts=$(./sapcontrol -prot PIPE -nr $instanceNumber -format script -function GetSystemInstanceList | grep \"hostname\" | cut -d \" \" -f 3)\n\n# Get the fully qualified domain name\nfqdn=$(./sapcontrol -prot PIPE -nr $instanceNumber -format script -function ParameterValue | grep \"SAPFQDN\" | cut -d \"=\" -f 2 | tr -d '\\r')\n\n# Declare an array to store the host file entries\nhostfile_entries=()\n\n# Loop through each hostname\nfor hostname in $hosts\ndo\n    ip=$(ping -c 1 $hostname | head -n 1 | cut -d \"(\" -f 2 | cut -d \")\" -f 1)\n    hostfile_entries+=\"$ip $hostname.$fqdn $hostname,\"\ndone\n\n# Print the host file entries separated by commas\nhostfile_entries=${hostfile_entries%?}\nIFS=\",\"\necho \"${hostfile_entries[*]}\"", "num_lines": 32}
{"repo_name": "Azure-Monitor-for-SAP-solutions-preview", "repo_creator": "Azure", "programming_language": "Shell", "code": "# <copyright file=\"UnprotectWebMethodsLinux.sh\" company=\"Microsoft Corporation\">\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# </copyright>\n\n#!/bin/bash\n\n# Replace instance number with the instance number of the Central Server instance\ninstanceNumber=00\n# replace siadam with the SIDADM user of the SAP System\nsiadam=l13adm\n\n# update the parameter value and restart the service\nsudo -u $siadam /usr/sap/hostctrl/exe/sapcontrol -nr $instanceNumber -function ParameterValue service/protectedwebmethods = SDEFAULT -GetQueueStatistic -ABAPGetWPTable -EnqGetStatistic -GetProcessList -GetEnvironment -ABAPGetSystemWPTable\nsudo -u $siadam /usr/sap/hostctrl/exe/sapcontrol -nr $instanceNumber -function RestartService\n\necho \"Parameter service/protectedwebmethods updated successfully\"", "num_lines": 16}
{"repo_name": "azure-multiapi-storage-python", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This scripts pull the latest Azure Storage SDK and update this multiapi package accordingly.\n\nworkdir=$(cd $(dirname $0); pwd)\ncd $workdir\n\nif [ ! -d venv ]; then\n    python -m virtualenv venv\n    . venv/bin/activate\n    pip install azure-storage-blob azure-storage-file azure-storage-queue azure-storage-common\nfi\n\nver=$(find venv -name '_constants.py' | grep blob | xargs grep 'X_MS_VERSION')\nver=${ver#X_MS_VERSION = \\'}\nver=${ver%\\'}\nver=${ver//-/_}\n\nsrc_root=$(cd venv/lib/$(ls venv/lib); pwd)/site-packages/azure/storage\ntgt=../azure/multiapi/storage/v$ver\nmkdir -p $tgt\n\nfor service in blob file queue common; do\n    src=$src_root/$service\n    cp -R $src $tgt\n\n    for f in `find $tgt/$service -name '*.py'`; do\n        echo Updating $f\n        # remove BOM\n        sed -i '1s/^\\xEF\\xBB\\xBF//' $f\n\n        if [ \"$service\" != \"common\" ]; then\n            # make relative reference to azure.storage.common\n            sed -i 's/from azure.storage.common./from ..common./g' $f\n        else\n            # make relative reference to azure.storage.common\n            sed -i 's/from azure.storage.common./from ./g' $f\n            sed -i 's/from azure.storage./from ../g' $f\n        fi\n    done\ndone\n", "num_lines": 42}
{"repo_name": "azure-multiapi-storage-python", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This scripts pull the latest Azure Storage SDK and update this multiapi package accordingly.\n\nworkdir=$(cd $(dirname $0); pwd)\ncd $workdir\n\nif [ ! -d venv ]; then\n    python -m virtualenv venv\n    . venv/bin/activate\n    pip install azure-storage-file-datalake azure-storage-blob azure-storage-file-share azure-storage-queue -U\nfi\n\n\n\nsrc_root=$(cd venv/lib/$(ls venv/lib); pwd)/site-packages/azure/storage\n\n\nfor service in blob fileshare filedatalake queue; do\n    ver=$(find venv -name '_serialize.py' | grep $service | xargs grep '[0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\}' | tail -n 1 | cut -d \\' -f 2)\n    ver=${ver//-/_}\n\n    tgt=../azure/multiapi/storagev2/$service/v$ver\n\n    mkdir -p $tgt\n    src=$src_root/$service\n    cp -R $src/. $tgt\n\n    for f in `find $tgt -name '*.py'`; do\n        echo Updating $f\n        # remove BOM\n        sed -i '1s/^\\xEF\\xBB\\xBF//' $f\n\n        if [ \"$service\" = \"filedatalake\" ]; then\n            echo \"filedatalake\"\n            default=\"2019_07_07\"\n            if [[ \"$ver\" > \"$default\" ]]; then\n                default=$ver\n            fi\n\n            sed -i \"s/from azure.storage.blob import/from azure.multiapi.storagev2.blob.v$default import/g\" $f\n            sed -i \"s/from azure.storage.blob./from azure.multiapi.storagev2.blob.v$default./g\" $f\n        fi\n\n        namespace=azure.storage.$service\n        sed -i \"s/from $namespace./from ./g\" $f\n        sed -i \"s/from ...core.exceptions/from azure.core.exceptions/g\" $f\n    done\n\ndone\n", "num_lines": 51}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\napt-get -y install nginx\necho \"stream { upstream mysql { server $1.mysql.database.azure.com:3306; } server { listen 3306; proxy_pass mysql; } }\" >> /etc/nginx/nginx.conf\nservice nginx restart\nupdate-rc.d nginx defaults", "num_lines": 9}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nSERVERNAME=$1\nMySQLUSERNAME=$2\nMySQLUSERLOGINPASSWORD=$3\nMONITORINGUSERNAME=$4\nMONITORINGLOGINPASSWORD=$5\nADMINISTRATORLOGIN=$6\nADMINISTRATORLOGINPASSWORD=$7\nexport DEBIAN_FRONTEND=noninteractive\nwget https://github.com/sysown/proxysql/releases/download/v2.0.6/proxysql_2.0.6-ubuntu18_amd64.deb\nsudo dpkg -i proxysql_* \nsudo apt-get -y update\nsudo apt-get -y install mysql-client\nsudo systemctl start proxysql\nsleep 100\nsed -i -e \"s/SERVERNAME/$SERVERNAME/g\" -e \"s/MySQLUSERNAME/$MySQLUSERNAME/g\" -e \"s/MySQLUSERLOGINPASSWORD/$MySQLUSERLOGINPASSWORD/g\" -e \"s/MONITORINGUSERNAME/$MONITORINGUSERNAME/g\" -e \"s/MONITORINGLOGINPASSWORD/$MONITORINGLOGINPASSWORD/g\" proxysqldb.sql\nmysql -u admin -padmin -h 127.0.0.1 -P 6032 <proxysqldb.sql\nsed -i -e \"s/MySQLUSERNAME/$MySQLUSERNAME/g\" -e \"s/MySQLUSERLOGINPASSWORD/$MySQLUSERLOGINPASSWORD/g\" -e \"s/MONITORINGUSERNAME/$MONITORINGUSERNAME/g\" -e \"s/MONITORINGLOGINPASSWORD/$MONITORINGLOGINPASSWORD/g\" masterdb.sql\nmysql -h \"$SERVERNAME.mysql.database.azure.com\" -u \"$ADMINISTRATORLOGIN@$SERVERNAME\" -p\"$ADMINISTRATORLOGINPASSWORD\"<masterdb.sql", "num_lines": 19}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#Version 1.6\n#--Ability to migrate the following scenario (1. Single-To-Flexible,2.Flexible-To-Flexible,3.Single-To-Single,4.Flexible-To-Single)\n#--Ability to check and act based on target server is Private or public Network Access\n#--Ability to check the pre-req required Azure CLI ,MySQL client mysqldump are there..\n#--Abiity to check the connectivity\n#--Ability to  read variables from a parameter file -Json format\n#--Ability to log to console and to file for debug purpose\n#--Ability to clean the files used\n#--Ability to migrate all databases\n#--Ability to migrate the firewall rules when we have public access\n#--Ability to migrate users to the default password \n#--Ability to migrate the Grants \n#--Ability to migrate Server parameters which were changed from default\n#--Ability to validate the migrate the Database basic and creating validation report\n#--Ability to select databases which you would like to migrate \n#--Ability to select the phase of migration 1) Validation (Yes\\No) 2)Firewall Migration (Yes\\No) 3)Server Parameter (Yes\\No)\n#--Dynamic SSL switch to make it work in both old and new versions of MySQL client. \n\n\n###################Parameter file default######################################\nif [ -z \"$1\" ]\nthen\nexport MY_PARAMETERFILE=\"migrateparameter.json\" #Name of the paramater file\nelse\nMY_PARAMETERFILE=$1\nfi \n\nif ! [[ -f \"$MY_PARAMETERFILE\" ]]; then\n    echo \"Parameter file does not exist $MY_PARAMETERFILE exists.\"\n\texit 1\nfi\n\n#########For Logging################################\nNOW=$(date +\"%m%d%Y%H%M%S\")\nexport MY_LOGFILE=\"migration\"$NOW\".log\"\nexport MY_MYSQLDUMPLOG=\"mysqldump\"$NOW\".log\"\nexport MY_MYSQLVALIDATIONREPORT=\"validation_report\"$NOW\".txt\"\n#############################################################\necho $(date) : \"Migration scenario $MY_MYSCENARIO starting\" >$MY_LOGFILE\necho \"Migration scenario $MY_MYSCENARIO starting ..Log File :$MY_LOGFILE \" \necho $(date) : \"Checking Pre-requisites  Azure CLI ,MySQL client mysqldump are there..\" >>$MY_LOGFILE\necho \"Checking Pre-requisites  Azure CLI ,MySQL client, mysqldump and jq are there..\" \necho  -e \"\\e[1;35mThe Parameter file used is $MY_PARAMETERFILE\\e[0m\" \necho $(date) : \"The Parameter file used is $MY_PARAMETERFILE:\"  >>$MY_LOGFILE\n\n#############################Pre-req Check#########################################\n# Prerequisites - Install Azure CLI and mysql-client package\nif ! [ -x \"$(command -v az)\" ]; then\n  echo 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >&2\n  echo $(date) : 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >>$MY_LOGFILE\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysqldump)\" ]; then\n  echo 'Error: mysqldump command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  echo $(date) :  'Error: mysqldump command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >>$MY_LOGFILE\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysql)\" ]; then\n  echo 'Error: mysql command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  echo $(date) : 'Error: mysqldump command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >>$MY_LOGFILE\n  exit 1\nfi\n\nif ! [ -x \"$(command -v jq)\" ]; then\n  echo 'Error: jq is not installed. Please install from https://www.howtoinstall.me/ubuntu/18-04/jq/ >&2\n  echo 'Error: jq is not installed. Please install from https://www.howtoinstall.me/ubuntu/18-04/jq/ >>$MY_LOGFILE\n  exit 1\nfi\n\nif ! [ -x \"$(command -v cmp)\" ]; then\n  echo 'Error: cmp is not installed. Please install cmp https://command-not-found.com/cmp' >&2\n  echo $(date) : 'Error: cmp is not installed. Please install cmp https://command-not-found.com/cmp' >>$MY_LOGFILE\n  exit 1\nfi\n\n\n######################################SSL Switch###############################################################################\n\nsslcheck=$(mysql --help | grep \"ssl-mode\")\nif [[  -z $sslcheck ]]\nthen\nexport sslswitch=\"--ssl=TRUE\"\nelse \nexport sslswitch=\"--ssl-mode=required\"\nfi\n\n\n#############################Parameter Export#######################################################################\n\n\nexport MY_MYSCENARIO=`jq -r .parameters.MY_MYSCENARIO.value $MY_PARAMETERFILE`\nexport MY_SOURCESUBSCRIPTION=`jq -r .parameters.MY_SOURCESUBSCRIPTION.value $MY_PARAMETERFILE`\nexport MY_TARGETSUBSCRIPTION=`jq -r .parameters.MY_TARGETSUBSCRIPTION.value $MY_PARAMETERFILE`\nexport MY_SOURCEDBSERVER=`jq -r .parameters.MY_SOURCEDBSERVER.value $MY_PARAMETERFILE`\nexport MY_TARGETDBSERVER=`jq -r .parameters.MY_TARGETDBSERVER.value $MY_PARAMETERFILE`\nexport MY_SOURCERG=`jq -r .parameters.MY_SOURCERG.value $MY_PARAMETERFILE`\nexport MY_TARGETRG=`jq -r .parameters.MY_TARGETRG.value $MY_PARAMETERFILE`\nexport MY_SOURCEUSER=`jq -r .parameters.MY_SOURCEUSER.value $MY_PARAMETERFILE`\nexport MY_SOURCEUSERPWD=`jq -r .parameters.MY_SOURCEUSERPWD.value $MY_PARAMETERFILE`\nexport MY_TARGETUSER=`jq -r .parameters.MY_TARGETUSER.value $MY_PARAMETERFILE`\nexport MY_TARGETUSERPWD=`jq -r .parameters.MY_TARGETUSERPWD.value $MY_PARAMETERFILE`\nexport MY_MYSQLDEFAULTPWD=`jq -r .parameters.MY_MYSQLDEFAULTPWD.value $MY_PARAMETERFILE`\n\nexport MY_MYDBSELECTION=`jq -r .parameters.MY_MYDBSELECTION.value $MY_PARAMETERFILE`\nexport MY_MYSELECTIONVALIDATE=`jq -r .parameters.MY_MYSELECTIONVALIDATE.value $MY_PARAMETERFILE`\nexport MY_MYSELECTIONFIREWALLRULE=`jq -r .parameters.MY_MYSELECTIONFIREWALLRULE.value $MY_PARAMETERFILE`\nexport MY_MYSELECTIONSERVERPARAMETER=`jq -r .parameters.MY_MYSELECTIONSERVERPARAMETER.value $MY_PARAMETERFILE`\nexport MY_MYSELECTIONUSER=`jq -r .parameters.MY_MYSELECTIONUSER.value $MY_PARAMETERFILE`\n\n\nexport MY_MYSELECTIONROSTART=`jq -r .parameters.MY_MYSELECTIONROSTART.value $MY_PARAMETERFILE`\nexport MY_MYSELECTIONROAFTER=`jq -r .parameters.MY_MYSELECTIONROAFTER.value $MY_PARAMETERFILE`\n\n\necho \"=================================================\" >>$MY_LOGFILE\necho \"Selected Scenario  :\" $MY_MYSCENARIO >>$MY_LOGFILE\necho \"Source Subscription :\" $MY_SOURCESUBSCRIPTION >>$MY_LOGFILE\necho \"Target Subscription :\" $MY_TARGETSUBSCRIPTION >>$MY_LOGFILE\necho \"Source DB Server  :\" $MY_SOURCEDBSERVER >>$MY_LOGFILE\necho \"Target DB server  :\" $MY_TARGETDBSERVER >>$MY_LOGFILE\necho \"Source Resource Group :\" $MY_SOURCERG >>$MY_LOGFILE\necho \"Target Resource Group :\" $MY_TARGETRG >>$MY_LOGFILE\necho \"Source User Name :\" $MY_SOURCEUSER >>$MY_LOGFILE\necho \"Target User Name :\" $MY_TARGETUSER >>$MY_LOGFILE\n\n####comment this in case you dont want your password to be displayed on screen\necho \"Source Password :\" $MY_SOURCEUSERPWD >>$MY_LOGFILE\necho \"Target password  :\"$MY_TARGETUSERPWD >>$MY_LOGFILE\necho \"Default Passoword for migrated users  :\" $MY_MYSQLDEFAULTPWD >>$MY_LOGFILE\n########################################################################\n\necho \"=================================================\"\necho \"Selected Scenario  :\" $MY_MYSCENARIO\necho \"Source Subscription :\" $MY_SOURCESUBSCRIPTION\necho \"Target Subscription :\" $MY_TARGETSUBSCRIPTION\necho \"Source DB Server  :\" $MY_SOURCEDBSERVER\necho \"Target DB server  :\" $MY_TARGETDBSERVER\necho \"Source Resource Group :\" $MY_SOURCERG\necho \"Target Resource Group :\" $MY_TARGETRG\necho \"Source User Name :\" $MY_SOURCEUSER\necho \"Target User Name :\" $MY_TARGETUSER\n\n####comment this in case you dont want your password to be displayed on screen\necho \"Source User Name :\" $MY_SOURCEUSERPWD\necho \"Target password  :\"$MY_TARGETUSERPWD\necho \"Default Password for migrated users  :\" $MY_MYSQLDEFAULTPWD\n########################################################################\n\n#####################################Flow-Selection#####################\n if [ \"$MY_MYDBSELECTION\" = \"ALL\" ]\nthen \necho -e \"\\e[1;36m You have selected to migrate all databases in the server $MY_SOURCEDBSERVER \\e[0m\"\necho \"You have selected to migrate all databases in the server $MY_SOURCEDBSERVER\" >>$MY_LOGFILE\nelse \necho -e \"\\e[1;33mYou have selected to migrate the following databases  $MY_MYDBSELECTION in server $MY_SOURCEDBSERVER \\e[0m\"\necho \"You have selected to migrate the following databases  $MY_MYDBSELECTION in server $MY_SOURCEDBSERVER\" >>$MY_LOGFILE\nfi\n\n if [ \"$MY_MYSELECTIONVALIDATE\" = \"NO\" ]\nthen \necho -e \"\\e[1;36m Validation report will be generated \\e[0m\" \necho \"Validation report will be generated\" >>$MY_LOGFILE\nelse \necho -e  \"\\e[1;33m Validation report will be skipped \\e[0m\"\necho \"Validation report will be skipped\" >>$MY_LOGFILE\nfi\n\nif [ \"$MY_MYSELECTIONFIREWALLRULE\" = \"NO\" ]\nthen \necho \"Firewall rule will be migrated\"  >>$MY_LOGFILE\necho -e \"\\e[1;36m Firewall rule will be migrated \\e[0m\"\nelse \necho \"Firewall rule migration will be skipped \" >>$MY_LOGFILE\necho -e \"\\e[1;33m Firewall rule migration will be skipped \\e[0m\"\nfi\n\nif [ \"$MY_MYSELECTIONSERVERPARAMETER\" = \"NO\" ]\nthen \necho \"Changed Server Parameter  will be migrated\" >>$MY_LOGFILE\necho -e  \"\\e[1;36m Changed Server Parameter  will be migrated \\e[0m\"\nelse \necho \"Server Parameter migration will be skipped \" >>$MY_LOGFILE\necho -e \"\\e[1;33m Server Parameter migration will be skipped\\e[0m\"\nfi\n\n\nif [ \"$MY_MYSELECTIONUSER\" = \"NO\" ]\nthen \necho \"USER migration will be performed to default password \"  >>$MY_LOGFILE\necho -e \"\\e[1;36m USER migration will be performed to default password \\e[0m\"\nelse \necho \"USER migration will be skipped\" >>$MY_LOGFILE\necho -e \"\\e[1;33m USER migration will be skipped \\e[0m\"\nfi\n\n\nif [ \"$MY_MYSELECTIONROSTART\" = \"NO\" ]\nthen \necho \"The source server will be set to Read-only while migrating\"  >>$MY_LOGFILE\necho -e \"\\e[1;36m The source server will be set to Read-only while migrating \\e[0m\"\nelse \necho \"The source server will be in Read-write mode while migrating\" >>$MY_LOGFILE\necho -e \"\\e[1;33m The source server will be in Read-write mode while migrating\\e[0m\"\nfi\n\n\nif [ \"$MY_MYSELECTIONROAFTER\" = \"NO\" ]\nthen \necho \"The source server will be set to Read-Write after migrating\"  >>$MY_LOGFILE\necho -e \"\\e[1;36m The source server will be set to Read-Write after migrating \\e[0m\"\nelse \necho \"The source server will be in Read-Only for Cutover post migrating\" >>$MY_LOGFILE\necho -e \"\\e[1;33m The source server will be in Read-Only for Cutover post migrating \\e[0m\"\nfi\n\n\necho \"=================================================\"  >>$MY_LOGFILE\necho \"=================================================\"\necho -e \"\\e[1;32m Confirm if displayed details are correct\\e[0m \"\nread -p \"Do you want to Continue (Y/N)? \" -n 1 -r\necho    \nif [[ ! $REPLY =~ ^[Yy]$ ]]\nthen\n    echo -e \"\\e[1;31m Edit your Parameter (json file) : $MY_PARAMETERFILE with correct the details....\\e[0m\"\n    exit 1\nfi\n\n\n\n\n#Connect to source subscription\naz account set --subscription \"$MY_SOURCESUBSCRIPTION\"\necho \"Checking if Target server is Private access if yes firewall rules migration will be skipped\" \necho $(date) :\"Checking if Target server is Private access if yes firewall rules migration will be skipped\" >>$MY_LOGFILE\n############Check if the Target server is Private access if yes skip the firewall rule migration step###########\ncase $MY_MYSCENARIO in\n        \"Single-To-Flexible\")\n        mydbaccess=$(az mysql flexible-server show --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --output json)\n        export MY_TARGACCESS=$(jq -r  '.network.publicNetworkAccess' <<< $mydbaccess)\n        ;;\n        \"Flexible-To-Flexible\")\n        mydbaccess=$(az mysql flexible-server show --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --output json)\n        export MY_TARGACCESS=$(jq -r  '.network.publicNetworkAccess' <<< $mydbaccess)\n        ;;\n        \"Single-To-Single\")\n         mydbaccess=$(az mysql server show --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --output json)\n        export MY_TARGACCESS=$(jq -r  '.publicNetworkAccess' <<< $mydbaccess)\n        ;;\n        \"Flexible-To-Single\")\n        mydbaccess=$(az mysql server show --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --output json)\n        export MY_TARGACCESS=$(jq -r  '.publicNetworkAccess' <<< $mydbaccess)\n        ;;\nesac\nif [ \"$MY_MYSELECTIONFIREWALLRULE\" = \"NO\" ]\nthen \n\tif [ \"$MY_TARGACCESS\" = \"Enabled\" ]\n\tthen \n\t\techo $(date) : \"Server has Public Access migrating Firewall Rules..\" >>$MY_LOGFILE\n\t\techo \"Server has Public Access migrating Firewall Rules..\" \n\t\techo -e \"\\e[1;31m Creating Firewall rule to allow AllowAllWindowsAzureIps in Source -Remove this Post Migration if yo dont need this \\e[0m \"\n\t\techo $(date) : \"Creating Firewall rule to allow AllowAllWindowsAzureIps in Source  -Remove this Post Migration if yo dont need this\" >>$MY_LOGFILE\n\t\t#To help connect to MySQL services from VM or Azure CLI adding firewall rule to allow all ip.You can also add individual IP here\n\t\t\n\t\tcase $MY_MYSCENARIO in\n\t\t\t\"Single-To-Flexible\")\n\t\t\taz mysql server firewall-rule create --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name \"AllowAllWindowsAzureIps\" --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0 >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Flexible-To-Flexible\")\n\t\t\taz mysql flexible-server firewall-rule create --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --rule-name \"AllowAllWindowsAzureIps\" --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0 >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Single-To-Single\")\n\t\t\t az mysql server firewall-rule create --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name \"AllowAllWindowsAzureIps\" --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0 >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Flexible-To-Single\")\n\t\t\taz mysql flexible-server firewall-rule create --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --rule-name \"AllowAllWindowsAzureIps\" --start-ip-address 0.0.0.0 --end-ip-address 0.0.0.0 >>$MY_LOGFILE\n\t\t\t;;\n\t\tesac\n\t\t\n\t\t\n\t\t##########################################################\n\t\t#Firewall Rule Migration\n\t\t##########################################################\n\t\t#Get the list of Firewall rules \n\t\techo $(date) : \"Getting the list of Firewall rules From source\" >>$MY_LOGFILE\n\t\techo \"Getting the list of Firewall rules From source\" \n\t\t\n\t\tcase $MY_MYSCENARIO in\n\t\t\t\"Single-To-Flexible\")\n\t\t\tmyrules=$(az mysql server firewall-rule list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Flexible-To-Flexible\")\n\t\t\tmyrules=$(az mysql flexible-server firewall-rule list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Single-To-Single\")\n\t\t\t myrules=$(az mysql server firewall-rule list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Flexible-To-Single\")\n\t\t\tmyrules=$(az mysql flexible-server firewall-rule list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\tesac\n\t\t\n\t\t#Create the firewall rules in target server\n\t\techo $(date) : \"Migrating the Firewall rules to target\" >>$MY_LOGFILE\n\t\techo \"Migrating the Firewall rules to target\" \n\t\tfor i in $(echo $myrules | jq -c '.[]');do\n\t\t\tfname=$(jq -r '.name' <<< $i)\n\t\t\tfstartip=$(jq -r '.startIpAddress' <<< $i)\n\t\t\tfendip=$(jq -r '.endIpAddress' <<< $i)\n\t\t\tif [ \"$fname\" != \"AllowAllWindowsAzureIps\" ] \n\t\t\tthen\n\t\t\texport fname=\"Mig-\"$fname\n\t\t\tfi\n\t\t\techo $(date) : \"Adding Firewall Rule on target server :$MY_TARGETDBSERVER (Name:$fname Start-ip-address:$fstartip End-ip-address:$fendip)\" >>$MY_LOGFILE\n\t\t\t\n\t\t\tcase $MY_MYSCENARIO in\n\t\t\t\"Single-To-Flexible\")\n\t\t\taz mysql flexible-server firewall-rule create --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --rule-name $fname --start-ip-address $fstartip --end-ip-address $fendip >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Flexible-To-Flexible\")\n\t\t\taz mysql flexible-server firewall-rule create --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --rule-name $fname --start-ip-address $fstartip --end-ip-address $fendip >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Single-To-Single\")\n\t\t\t az mysql server firewall-rule create --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --name $fname --start-ip-address $fstartip --end-ip-address $fendip >>$MY_LOGFILE\n\t\t\t;;\n\t\t\t\"Flexible-To-Single\")\n\t\t\taz mysql server firewall-rule create --resource-group $MY_TARGETRG --name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --name $fname --start-ip-address $fstartip --end-ip-address $fendip >>$MY_LOGFILE\n\t\t\t;;\n\t\t\tesac\n\t\tdone\n\telse \n\techo $(date) : \"Server is Priavte access ..firewall rules migration skipped\" >>$MY_LOGFILE\n\techo \"Server is Private access ..firewall rules migration skipped\" \n\tfi\nfi\n##########################################################\n#connectivity test to source and target \n##########################################################\necho  \"Testing connectivity to source server) $MY_SOURCEDBSERVER.mysql.database.azure.com.......\"\necho $(date) : \"Testing connectivity to source server) $MY_SOURCEDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\nexport MYSQL_PWD=$MY_SOURCEUSERPWD\na=$( mysql $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"select version();\")\nif [ -z \"$a\" ]\nthen\n        echo\n        echo -e \"\\e[1;31m Failed to  connect........... \\e[0m \"\n\t\techo $(date) : \"Failed to connect to source sever $MY_SOURCEDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\n        echo -e \"\\e[1;36m Check the network connectivity from the source to the current vmand then continue...  \\e[0m\"\n        echo -e \"\\e[1;36m Check running -- telnet \"$MY_SOURCEDBSERVER.mysql.database.azure.com\" 3306 -- to check network connectivity\\e[0m\"\n        echo -e \"\\e[1;36m Confirm your username and password is correct....\\e[0m\"\n        exit 1\n    else\n    echo -e \"\\e[1;32m Connected Successfully  to source server $MY_SOURCEDBSERVER.mysql.database.azure.com and MySQL Version Is: \"$a\"\\e[0m\"\n\techo $(date) : \"Connected Successfully  to source sever $MY_SOURCEDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\nfi\n\n    echo  \"Testing connectivity to target server $MY_TARGETDBSERVER.mysql.database.azure.com.......\"\n\techo $(date) : \"Testing connectivity to target server) $MY_TARGETDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\nexport MYSQL_PWD=$MY_TARGETUSERPWD\na=$( mysql $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"select version();\")\nif [ -z \"$a\" ]\nthen\n        echo\n        echo -e \"\\e[1;31m Failed to  connect........... \\e[0m \"\n\t\techo $(date) : \"Faield to connect to target sever $MY_TARGETDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\n        echo -e \"\\e[1;36m Check the network connectivity from the target to the current vmand then continue...  \\e[0m\"\n        echo -e \"\\e[1;36m Check running -- telnet \"$MY_TARGETDBSERVER.mysql.database.azure.com\" 3306 -- to check network connectivity\\e[0m\"\n            echo -e \"\\e[1;36m Confirm your username and password is correct....\\e[0m\"\n        exit 1\n    else\n    echo -e \"\\e[1;32m Connected Successfully  to target server $MY_TARGETDBSERVER.mysql.database.azure.com and MySQL Version Is: \"$a\"\\e[0m\"\n\techo $(date) : \"Connected Successfully  to target sever $MY_TARGETDBSERVER.mysql.database.azure.com.......\" >>$MY_LOGFILE\nfi               \n\n\n##############################################################################################\n#User Migration -The Password will be defaulted and then you would need to change password later.\n##############################################################################################\nif [ \"$MY_MYSELECTIONUSER\" = \"NO\" ]\nthen \n\techo $(date) : \"User Migration Starting.....\" >>$MY_LOGFILE\n\techo \"User Migration Starting.....\" \n\t# Remove dump file if it already exists\n\t[ -e $MY_SOURCEDBSERVER\"_user.sql\" ] && rm -f $MY_SOURCEDBSERVER\"_user.sql\" \n\techo $(date) : \"Gettting the list of users (Azure Managed users will not be migrated ).....\" >>$MY_LOGFILE\n\techo \"Getting the list of users (Azure Managed users will not be migrated ).....\" \n\t#Get the list of users created excluding azure users \n\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\tmysql $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\" -e  \"SELECT CONCAT('\\'', user,'\\'@\\'', host, '\\'') as username   FROM mysql.user WHERE user not in (select user from mysql.user  where length(user) = 16 and user like 'az%') and user != 'azure_superuser' AND user != 'azure_superuser' AND user != 'mysql.session' AND user != 'mysql.sys' AND user != '$MY_TARGETUSER';\" mysql >$MY_SOURCEDBSERVER\"_user.sql\" \n\t# Remove dump file if it already exists $MY_TARGETUSER\n\t[ -e $MY_SOURCEDBSERVER\"_usergrant.sql\" ] && rm -f $MY_SOURCEDBSERVER\"_usergrant.sql\" \n\t#create file for user grants \n\techo $(date) : \"Collecting information for User grants.....\" >>$MY_LOGFILE\n\techo \"Collecting information for User grants.....\" \n\twhile read line;\n\tdo \n\tif [ \"$line\" != \"username\" ] \n\t\tthen\n\tmysql $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\" -e \"show grants for $line\" >>$MY_LOGFILE\n\tfi\n\tdone <$MY_SOURCEDBSERVER\"_user.sql\" >$MY_SOURCEDBSERVER\"_usergrant.sql\"\n\n\t#make the file SQL run ready \n\tsed -i '/Grants for/d' $MY_SOURCEDBSERVER\"_usergrant.sql\"\n\tsed -i 's/$/;/' $MY_SOURCEDBSERVER\"_usergrant.sql\"\n\techo $(date) : \"Migrating user to Target server.....\" >>$MY_LOGFILE\n\techo \"Migrating user to Target server.....\" \n\t#import users to target\n\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t#create users\n\twhile read line;\n\tdo \n\tif [ \"$line\" != \"username\" ] \n\t\tthen\n\tmysql $sslswitch -v --host=$MY_TARGETDBSERVER\".mysql.database.azure.com\" --port=3306 --user=$MY_TARGETUSER -e \"CREATE USER $line IDENTIFIED BY '$MY_MYSQLDEFAULTPWD'\" >>$MY_LOGFILE\n\tfi\n\tdone <$MY_SOURCEDBSERVER\"_user.sql\"\n\t#create  the user grants\n\techo $(date) : \"Creating Grants for users.....\" >>$MY_LOGFILE\n\techo \"Creating Grants for users.....\"\n\tmysql $sslswitch -v --host=$MY_TARGETDBSERVER\".mysql.database.azure.com\" --port=3306 --silent --user=$MY_TARGETUSER <$MY_SOURCEDBSERVER\"_usergrant.sql\" \nfi\n##########################Server Parameter Migration###########################\n\necho $(date) : \"Starting the Data Migration...\" >>$MY_LOGFILE\necho \"Starting the Data Migration...\" \n##########################################################\n#Data and Schema Migration\n##########################################################\nif [ \"$MY_MYSELECTIONROSTART\" = \"NO\" ]\nthen \n\techo $(date) : \"Setting the source server to Read only \" >>$MY_LOGFILE\n\techo \"Setting the source server to Read only \" \n\t#SET the source server to Read only \n\t\tcase $MY_MYSCENARIO in\n\t\t\t\t\"Single-To-Flexible\")\n\t\t\t\taz mysql server configuration set --name read_only --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --value ON >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Flexible\")\n\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name read_only --value ON >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Single-To-Single\")\n\t\t\t\taz mysql server configuration set --name read_only --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --value ON >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Single\")\n\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name read_only --value ON >>$MY_LOGFILE\n\t\t\t\t;;\n\t\tesac\nfi\n#get the list of user databases to be migrated\necho $(date) : \"Getting List of User databases to be migrated\" >>$MY_LOGFILE\necho \"Getting List of User databases to be migrated\" \n\tcase $MY_MYSCENARIO in\n\t\t\t\"Single-To-Flexible\")\n\t\t\tmydbs=$(az mysql db list --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t;;\n\t\t\t\"Flexible-To-Flexible\")\n\t\t\tmydbs=$(az mysql flexible-server db list --resource-group $MY_SOURCERG  --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t;;\n\t\t\t\"Single-To-Single\")\n\t\t\tmydbs=$(az mysql db list --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t;;\n\t\t\t\"Flexible-To-Single\")\n\t\t\tmydbs=$(az mysql flexible-server db list --resource-group $MY_SOURCERG  --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t;;\n\tesac\n\n if ! [ \"$MY_MYDBSELECTION\" = \"ALL\" ]\nthen \n\texport mydbs=$MY_MYDBSELECTION\nfi\n\nfor i in $(echo $mydbs | tr \" \" \"\\n\")\ndo\nif [ \"$i\" == \"information_schema\" -o \"$i\" == \"performance_schema\" -o \"$i\" == \"mysql\" -o \"$i\" == \"sys\" ] \nthen\n\techo $i \":System Database will not be dumped\" >>$MY_LOGFILE\nelse \n\texport SOURCE_DATABASE_NAME=$SOURCE_DATABASE_NAME$i\" \"\nfi\ndone\n\n\necho $(date) : \"The databases which will be migrated  are $SOURCE_DATABASE_NAME \" >>$MY_LOGFILE\necho \"The Following databases will be migrated  are $SOURCE_DATABASE_NAME \" \n# Remove dump file if it already exists\n[ -e $MY_SOURCEDBSERVER\"_backup.sql\" ] && rm -f $MY_SOURCEDBSERVER\"_backup.sql\" \n# Create a dump file of the source db\nexport MYSQL_PWD=$MY_SOURCEUSERPWD\necho $(date) : \"Dumping Databases to file...... \" >>$MY_LOGFILE\nmysqldump $sslswitch -Fc --routines --log-error=$MY_MYSQLDUMPLOG --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\" --databases $SOURCE_DATABASE_NAME >$MY_SOURCEDBSERVER\"_backup.sql\" \n# check that filesize of dump file is greater than 0\nif ! [ -s $MY_SOURCEDBSERVER\"_backup.sql\" ]; then\n  echo 'Error during mysqldump...' >>$MY_LOGFILE\n  echo $(date) : \"For Errors refer to $MY_MYSQLDUMPLOG file...... \" >>$MY_LOGFILE\n  exit 1\nfi\necho $(date) : \"For more details refer to $MY_MYSQLDUMPLOG file...... \" >>$MY_LOGFILE\necho $(date) : \"Restoring the databases $SOURCE_DATABASE_NAME...... \" >>$MY_LOGFILE\n#Restore the dump file to destination\nexport MYSQL_PWD=$MY_TARGETUSERPWD\nmysql $sslswitch --host=$MY_TARGETDBSERVER\".mysql.database.azure.com\" --port=3306 --user=$MY_TARGETUSER < $MY_SOURCEDBSERVER\"_backup.sql\" \n##########Please comment this section if you want to cutover and not use source anymore\nif [ \"$MY_MYSELECTIONROAFTER\" = \"NO\" ]\nthen \n\techo $(date) : \"Making the Source database Read Write\" >>$MY_LOGFILE\n\techo \"Making the Source database Read Write\" \n\t#SET the source server to Read -Write  \n\n\t\tcase $MY_MYSCENARIO in\n\t\t\t\t\"Single-To-Flexible\")\n\t\t\t\taz mysql server configuration set --name read_only --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --value OFF >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Flexible\")\n\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name read_only --value OFF >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Single-To-Single\")\n\t\t\t\taz mysql server configuration set --name read_only --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --value OFF >>$MY_LOGFILE\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Single\")\n\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --name read_only --value OFF >>$MY_LOGFILE\n\t\t\t\t;;\n\t\tesac\nfi\n\n######################End-Section############################################\n\n#Only values modified from the default will be changed\n#get the List of Parameter and the value which is changed from default\nif [ \"$MY_MYSELECTIONSERVERPARAMETER\" = \"NO\" ]\nthen \n\techo $(date) : \"Migrating Server Parameter (Values Changed by the User).....\" >>$MY_LOGFILE\n\techo \"Migrating Server Parameter.....\"\n\techo $(date) : \"Get list of Parameters which does not have Default Value.....\" >>$MY_LOGFILE\n\techo \"Get list of Parameters which does not have Default Value.....\"\n\tcase $MY_MYSCENARIO in\n\t\t\t\"Single-To-Flexible\")\n\t\t\tparameters=$(az mysql server configuration list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Flexible-To-Flexible\")\n\t\t\tparameters=$(az mysql flexible-server configuration list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Single-To-Single\")\n\t\t\tparameters=$(az mysql server configuration list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\t\t\t\"Flexible-To-Single\")\n\t\t\tparameters=$(az mysql flexible-server configuration list --resource-group $MY_SOURCERG --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --output json)\n\t\t\t;;\n\tesac\n\tchangedparameters=$(jq -c '.[] | select(.defaultValue!=.value) | {name: .name, value: .value}' <<<$parameters)\n\n\tfor i in $changedparameters;do\n\t\tpname=$(jq -r '.name' <<< $i)\n\t\tpvalue=$(jq -r '.value' <<< $i)\n\t\tif ! [ \"$pname\" == \"server_id\" -o \"$pname\" == \"read_only\" ] \n\t\tthen\n\t\t\techo $(date) : \"Changing the Server Parameter --$pname-- to --Value-- $pvalue\" >>$MY_LOGFILE\n\t\t\techo \"Changing the Server Parameter --$pname-- to --Value-- $pvalue\"\n\t\t\tcase $MY_MYSCENARIO in\n\t\t\t\t\t\"Single-To-Flexible\")\n\t\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_TARGETRG --server-name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --name $pname --value $pvalue >>$MY_LOGFILE\n\t\t\t\t\t;;\n\t\t\t\t\t\"Flexible-To-Flexible\")\n\t\t\t\t\taz mysql flexible-server parameter set --resource-group $MY_TARGETRG --server-name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --name $pname --value $pvalue >>$MY_LOGFILE\n\t\t\t\t\t;;\n\t\t\t\t\t\"Single-To-Single\")\n\t\t\t\t\taz mysql server configuration set --name $pname --resource-group $MY_TARGETRG --server-name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --value $pvalue >>$MY_LOGFILE\n\t\t\t\t\t;;\n\t\t\t\t\t\"Flexible-To-Single\")\n\t\t\t\t\taz mysql server configuration set --name $pname --resource-group $MY_TARGETRG --server-name $MY_TARGETDBSERVER --subscription $MY_TARGETSUBSCRIPTION --value $pvalue >>$MY_LOGFILE\n\t\t\t\t\t;;\n\t\t\tesac\n\t\tfi\n\tdone\nfi\n\n###########################Database Validation####################################################\n if [ \"$MY_MYSELECTIONVALIDATE\" = \"NO\" ]\nthen \n\techo $(date) : \"Validating the Data Migration.....\" >>$MY_LOGFILE\n\techo \"Validating the Database Migration.....\"\n\techo $(date) : \"Check $MY_MYSQLVALIDATIONREPORT for Database Migration Validation.....\" >>$MY_LOGFILE\n\techo \"Check $MY_MYSQLVALIDATIONREPORT for Databse Migration Validation.....\"\n\t echo -e \"\\e[1;32m Starting Database Migration Validation..... \\e[0m \"\n\techo $(date) : \"Getting List of User databases migrated\" >>$MY_LOGFILE\n\techo \"Getting List of User databases migrated\" \n\t\tcase $MY_MYSCENARIO in\n\t\t\t\t\"Single-To-Flexible\")\n\t\t\t\tmydbs=$(az mysql db list --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Flexible\")\n\t\t\t\tmydbs=$(az mysql flexible-server db list --resource-group $MY_SOURCERG  --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t\t;;\n\t\t\t\t\"Single-To-Single\")\n\t\t\t\tmydbs=$(az mysql db list --resource-group $MY_SOURCERG  --server $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t\t;;\n\t\t\t\t\"Flexible-To-Single\")\n\t\t\t\tmydbs=$(az mysql flexible-server db list --resource-group $MY_SOURCERG  --server-name $MY_SOURCEDBSERVER --subscription $MY_SOURCESUBSCRIPTION --query [].name --output tsv)\n\t\t\t\t;;\n\t\tesac\n\t if ! [ \"$MY_MYDBSELECTION\" = \"ALL\" ]\n\tthen \n\t\texport mydbs=$MY_MYDBSELECTION\n\tfi\n\ttab=$(echo -e \"\\x09\")\n\t########Run the below for each migrated database#################\n\n\techo \"Validation Report $(date) \" >$MY_MYSQLVALIDATIONREPORT\n\tarrcount=0\n\ttbldata[$arrcount]=\"Database Name|Source table Count |Target Table count\"\n\tvtbldata[$arrcount]=\"Database Name|Source View Count |Target View count\"\n\ttrtbldata[$arrcount]=\"Database Name|Source Trigger Count |Target Trigger count\"\n\trotbldata[$arrcount]=\"Database Name|Source routines Count |Target routines count\"\n\tcotbldata[$arrcount]=\"Database Name|Source constraint Count |Target constraint count\"\n\tarrcount=$arrcount+1\n\ttbldata[$arrcount]=\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n\tvtbldata[$arrcount]=\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n\ttrtbldata[$arrcount]=\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n\trotbldata[$arrcount]=\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n\tcotbldata[$arrcount]=\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\"\n\n\tfor i in $(echo $mydbs | tr \" \" \"\\n\")\n\tdo\n\tif ! [ \"$i\" == \"information_schema\" -o \"$i\" == \"performance_schema\" -o \"$i\" == \"mysql\" -o \"$i\" == \"sys\" ]\n\tthen\n\t\tdb=$i\n\t\tarrcount=$arrcount+1\n\t\techo \"Validation Report for database $db \" >>$MY_MYSQLVALIDATIONREPORT\n\t\t# Validating Tables\n\t\techo \"Validating the no of tables in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\tsdbvalue=$( mysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db';  \")\n\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\ttdbvalue=$( mysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db';  \")\n\t\techo \"No of Tables in $MY_SOURCEDBSERVER for $db is $sdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\ttbldata[$arrcount]=\"$db${tab}|$sdbvalue${tab}|$tdbvalue${tab}\"\n\t\techo \"No of Tables in $MY_TARGETDBSERVER for $db is $tdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\tif [ \"$sdbvalue\" == \"$tdbvalue\" ]\n\t\tthen\n\t\techo \"----------Table Count Validated successfully for $db----------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\telse\n\t\techo \"Error: Migration Issue detected on tables in $db please validate running SELECT Count(*)  FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db'\" >>$MY_MYSQLVALIDATIONREPORT\n\t\tfi\n\t\t# Validating Views\n\t\techo \"Validating the no of Views in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\tsdbvalue=$( mysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = '$db';  \")\n\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\ttdbvalue=$( mysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = '$db';  \")\n\t\techo \"No of Views in $MY_SOURCEDBSERVER for $db is $sdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\tvtbldata[$arrcount]=\"$db${tab}|$sdbvalue${tab}|$tdbvalue${tab}\"\n\t\techo \"No of Views in $MY_TARGETDBSERVER for $db is $tdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\tif [ \"$sdbvalue\" == \"$tdbvalue\" ]\n\t\tthen\n\t\techo \"----------View Count Validated successfully  for $db-----------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\telse\n\t\techo \"Error: Migration Issue detected on Views in $db please validate running SELECT Count(*)  FROM INFORMATION_SCHEMA.VIEWS WHERE TABLE_SCHEMA = '$db';\" >>$MY_MYSQLVALIDATIONREPORT\n\t\tfi\n\t\t# Validating Triggers\n\t\techo \"Validating the no of Triggers in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\tsdbvalue=$( mysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA = '$db';  \")\n\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\ttdbvalue=$( mysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA = '$db';  \")\n\t\techo \"No of Triggers in $MY_SOURCEDBSERVER for $db is $sdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\ttrtbldata[$arrcount]=\"$db${tab}|$sdbvalue${tab}|$tdbvalue${tab}\"\n\t\techo \"No of Triggers in $MY_TARGETDBSERVER for $db is $tdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\tif [ \"$sdbvalue\" == \"$tdbvalue\" ]\n\t\tthen\n\t\techo \"-------Trigger Count Validated successfully  for $db----------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\telse\n\t\techo \"Error: Migration Issue detected on Triggers in $db please validate running SELECT Count(*)  FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA = '$db';\" >>$MY_MYSQLVALIDATIONREPORT\n\t\tfi\n\t\t# Validating Routines -- Functions and Procedures \n\t\techo \"Validating the no of Routines -- Functions and Procedures in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\tsdbvalue=$( mysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.routines WHERE routine_SCHEMA = '$db';  \")\n\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\ttdbvalue=$( mysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.routines WHERE routine_SCHEMA = '$db';  \")\n\t\techo \"No of Routines in $MY_SOURCEDBSERVER for $db is $sdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\trotbldata[$arrcount]=\"$db${tab}|$sdbvalue${tab}|$tdbvalue${tab}\"\n\t\techo \"No of Routines in $MY_TARGETDBSERVER for $db is $tdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\tif [ \"$sdbvalue\" == \"$tdbvalue\" ]\n\t\tthen\n\t\techo \"-------Routines Count Validated successfully  for $db-------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\telse\n\t\techo \"Error: Migration Issue detected on routines in $db please validate running SELECT Count(*)  FROM INFORMATION_SCHEMA.routines WHERE routine_SCHEMA = '$db';\" >>$MY_MYSQLVALIDATIONREPORT\n\t\tfi\n\t\t#Validating Constraints \n\t\t\techo \"Validating the no of Constraints in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\t\tsdbvalue=$( mysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = '$db';  \")\n\t\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\t\ttdbvalue=$( mysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT Count(*)  FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = '$db';  \")\n\t\t\techo \"No of Constraints in $MY_SOURCEDBSERVER for $db is $sdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\tcotbldata[$arrcount]=\"$db${tab}|$sdbvalue${tab}|$tdbvalue${tab}\"\n\t\t\techo \"No of Constraints in $MY_TARGETDBSERVER for $db is $tdbvalue \" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\tif [ \"$sdbvalue\" == \"$tdbvalue\" ]\n\t\t\tthen\n\t\t\techo \"--------Constraints Count Validated successfully  for $db--------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\telse\n\t\t\techo \"Error:Migration Issue detected on Constraints in $db please validate running SELECT Count(*)  FROM INFORMATION_SCHEMA.table_constraints WHERE constraint_schema = '$db';\" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\tfi\n\t\t#validating Rows per table for each database \n\t\t\terrflg=\"TRUE\"\n\t\t\techo \"Validating the no of total number of rows in tables in Database $db\" >>$MY_MYSQLVALIDATIONREPORT\n\n\t\t\texport MYSQL_PWD=$MY_SOURCEUSERPWD\n\t\t\tmysql -N $sslswitch --host=\"$MY_SOURCEDBSERVER.mysql.database.azure.com\" --user=\"$MY_SOURCEUSER\"  -e \"SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '$db';\"  >$MY_SOURCEDBSERVER\"_table.sql\"\n\t\t\texport MYSQL_PWD=$MY_TARGETUSERPWD\n\t\t\tmysql -N $sslswitch --host=\"$MY_TARGETDBSERVER.mysql.database.azure.com\" --user=\"$MY_TARGETUSER\"  -e \"SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA ='$db';\" >$MY_TARGETDBSERVER\"_table.sql\"\n\t\t\tif cmp -s $MY_SOURCEDBSERVER\"_table.sql\" $MY_TARGETDBSERVER\"_table.sql\"; then\n\t\t\techo \"--------Validated Rows per Database table successfully  for $db--------\" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\telse\n\t\t\techo \"Error:Migration Issue detected on Table in $db please verify the rows running command : SELECT table_name, table_rows FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA ='$db';\" >>$MY_MYSQLVALIDATIONREPORT\n\t\t\terrflg=\"FALSE\"\n\t\t\tfi\n\t\trm $MY_SOURCEDBSERVER\"_table.sql\"\n\t\trm $MY_TARGETDBSERVER\"_table.sql\"\n\t\techo \"******************************************************************************************\">>$MY_MYSQLVALIDATIONREPORT\n\tfi\n\tdone\n\n\techo \"The Summary Report for the validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\">>$MY_MYSQLVALIDATIONREPORT\n\tif [ \"$errflg\" == \"TRUE\" ] \n\tthen \n\techo \"No of Rows per table for all database is similar\">>$MY_MYSQLVALIDATIONREPORT\n\telse\n\techo \"No of Rows per table for all database is different : run \"cat $MY_MYSQLVALIDATIONREPORT | grep \"Error\"\" for more details\">>$MY_MYSQLVALIDATIONREPORT\n\tfi\n\techo \"Summary of Count of table validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\">>$MY_MYSQLVALIDATIONREPORT\n\tfor data in \"${tbldata[@]}\"\n\tdo\n\t  echo \"$data\" >>$MY_MYSQLVALIDATIONREPORT\n\tdone\n\techo \"Summary of Count of View validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\">>$MY_MYSQLVALIDATIONREPORT\n\tfor data in \"${vtbldata[@]}\"\n\tdo\n\t  echo \"$data\" >>$MY_MYSQLVALIDATIONREPORT\n\tdone\n\techo \"Summary of Count of Triggers validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\">>$MY_MYSQLVALIDATIONREPORT\n\tfor data in \"${trtbldata[@]}\"\n\tdo\n\t  echo \"$data\" >>$MY_MYSQLVALIDATIONREPORT\n\tdone\n\techo \"Summary of Count of Routines validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\" >>$MY_MYSQLVALIDATIONREPORT\n\tfor data in \"${rotbldata[@]}\"\n\tdo\n\t  echo \"$data\" >>$MY_MYSQLVALIDATIONREPORT\n\tdone\n\techo \"Summary of Count of Constraints validation\">>$MY_MYSQLVALIDATIONREPORT\n\techo \"***************************************************************\" >>$MY_MYSQLVALIDATIONREPORT\n\tfor data in \"${cotbldata[@]}\"\n\tdo\n\t  echo \"$data\" >>$MY_MYSQLVALIDATIONREPORT\n\tdone\n\t echo -e \"\\e[1;32m Check $MY_MYSQLVALIDATIONREPORT for Database Migration Validation..... \\e[0m \"\nfi\n###############################################################################\n\t\n\n\n#################################################################################################\necho $(date) : \"Migration Completed successfully.....See $MY_LOGFILE, $MY_MYSQLDUMPLOG for more details\" \necho $(date) : \"Migration Completed successfully.....\" >>$MY_LOGFILE\n\n#Cleanup of files comment these lines if you would like to verify the migration files. \nrm $MY_SOURCEDBSERVER\"_usergrant.sql\"\nrm $MY_SOURCEDBSERVER\"_user.sql\"\nrm $MY_SOURCEDBSERVER\"_backup.sql\"\n\n##############################################################################################\n#############################################END###############################################\n", "num_lines": 782}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo \"Running the PHP Sample App deployment scripts\"\necho \"Downloading composer files.\"\nphp -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\"\nphp -r \"if (hash_file('sha384', 'composer-setup.php') === '906a84df04cea2aa72f40b5f787e49f22d4c2f19492ac310e8cba5b96ac8b64115ac402c8cd292b8a03482574915d1a8') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;\"\nphp composer-setup.php\nphp -r \"unlink('composer-setup.php');\"\n\necho \"Copying files from /home/site/repository/* to /home/site/wwwroot\"\ncp -r /home/site/repository/* /home/site/wwwroot\ncp /home/site/repository/.env.example.azure /home/site/wwwroot/.env\ncp /home/site/repository/htaccess /home/site/wwwroot/.htaccess\n\necho \"Installing composer\"\ncurl -s https://getcomposer.org/installer | php\n", "num_lines": 15}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"Replacing nginx configuration for serving PHP 8.0-based applications\"\ncp /home/site/repository/nginx.conf /etc/nginx/sites-available/default\n\necho \"Reloading nginx to apply new configuration\"\nservice nginx reload\n", "num_lines": 7}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nsed -i \"s/Listen 80/Listen ${PORT:-80}/g\" /etc/apache2/ports.conf\nsed -i \"s/:80/:${PORT:-80}/g\" /etc/apache2/sites-enabled/*\napache2-foreground", "num_lines": 4}
{"repo_name": "azure-mysql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# PURPOSE\n# Migrate Azure Database for MySQL Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\n# \n# DESCRIPTION\n# Pricing tiers in Azure Database for MySQL - Single Server\n# https://docs.microsoft.com/en-us/azure/mysql/concepts-pricing-tiers\n# \n# Currently modifying pricing tier (to and from Basic) is not yet supported. \n# This script helps in migrating an existing database from Basic Pricing Tier to \n# General Purpose/Memory Optimized Pricing Tier. \n# This script uses mysqldump to extract a MySQL database into a dump file\n# and mysql to restore the MySQL database from an archive file created by mysqldump.\n#\n# Migrate your MySQL database using dump and restore\n# https://docs.microsoft.com/en-us/azure/mysql/howto-migrate-using-dump-and-restore\n#\n# PREREQUISITES\n# Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\n# mysql-client tools - mysqldump and mysql (https://dev.mysql.com/downloads/mysql/)\n# \n# NOTE\n# Target server and database are created in this script.\n# Please modify the script to specify different options for creation\n# https://docs.microsoft.com/en-us/cli/azure/mysql/server?view=azure-cli-latest\n# \n# USAGE\n# bash mysqlmigrate.sh\n#         --source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --source-resource-group-name 'sourceRG'\n#         --source-server-name 'sourcemysql'\n#         --source-username 'sourceuser'\n#         --source-password 'P@ssw0rd1'\n#         --source-database-name 'sourcedb'\n#         --target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --target-resource-group-name 'targetRG'\n#         --target-region 'eastus'\n#         --target-server-name 'targetmysql'\n#         --target-username 'targetuser'\n#         --target-password 'P@ssw0rd2'\n#         --target-database-name 'targetdb'\n#         --target-sku 'GP_Gen5_2'\n#\n\nfunction usage()\n{\n    echo \"\"\n    echo \"PURPOSE\"\n    echo \"Migrate Azure Database for MySQL Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\"\n    echo \"\"\n    echo \"DESCRIPTION\"\n    echo \"Pricing tiers in Azure Database for MySQL - Single Server\"\n    echo \"https://docs.microsoft.com/en-us/azure/mysql/concepts-pricing-tiers\"\n    echo \"\"\n    echo \"Currently modifying pricing tier (to and from Basic) is not yet supported.\"\n    echo \"This script helps in migrating an existing database from Basic Pricing Tier to\"\n    echo \"General Purpose/Memory Optimized Pricing Tier.\"\n    echo \"This script uses mysqldump to extract a MySQL database into a dump file\"\n    echo \"and mysql to restore the MySQL database from an archive file created by mysqldump.\"\n    echo \"\"\n    echo \"Migrate your MySQL database using dump and restore\"\n    echo \"https://docs.microsoft.com/en-us/azure/mysql/howto-migrate-using-dump-and-restore\"\n    echo \"\"\n    echo \"PREREQUISITES\"\n    echo \"Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\"\n    echo \"mysql-client tools - mysqldump and mysql (https://dev.mysql.com/downloads/mysql/)\"\n    echo \"\"\n    echo \"NOTE\"\n    echo \"Target server and database are created in this script.\"\n    echo \"Please modify the script to specify different options for server creation\"\n    echo \"https://docs.microsoft.com/en-us/cli/azure/mysql/server?view=azure-cli-latest\"\n    echo \"\"\n    echo \"USAGE\"\n    echo \"bash mysqlmigrate.sh\"\n    echo -e \"\\t--source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--source-resource-group-name 'sourceRG'\"\n    echo -e \"\\t--source-server-name 'sourcemysql'\"\n    echo -e \"\\t--source-username 'sourceuser'\"\n    echo -e \"\\t--source-password 'P@ssw0rd1'\"\n    echo -e \"\\t--source-database-name 'sourcedb'\"\n    echo -e \"\\t--target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--target-resource-group-name 'targetRG'\"\n    echo -e \"\\t--target-region 'eastus'\"\n    echo -e \"\\t--target-server-name 'targetmysql'\"\n    echo -e \"\\t--target-username 'targetuser'\"\n    echo -e \"\\t--target-password 'P@ssw0rd2'\"\n    echo -e \"\\t--target-database-name 'targetdb'\"\n    echo -e \"\\t--target-sku 'GP_Gen5_2'\"\n    echo \"\"\n}\n\nPARAMS=\"\"\nwhile (( \"$#\" )); do\n  case \"$1\" in\n    -h | --help)\n      usage\n      exit\n      ;;\n    -a|--source-subscription-id)\n      SOURCE_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -b|--source-resource-group-name)\n      SOURCE_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -c|--source-server-name)\n      SOURCE_SERVER_NAME=$2\n      shift 2\n      ;;\n    -d|--source-username)\n      SOURCE_USERNAME=$2\n      shift 2\n      ;;\n    -e|--source-password)\n      SOURCE_PASSWORD=$2\n      shift 2\n      ;;\n    -f|--source-database-name)\n      SOURCE_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -g|--target-subscription-id)\n      TARGET_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -h|--target-resource-group-name)\n      TARGET_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -i|--target-region)\n      TARGET_REGION=$2\n      shift 2\n      ;;\n    -j|--target-server-name)\n      TARGET_SERVER_NAME=$2\n      shift 2\n      ;;\n    -k|--target-username)\n      TARGET_USERNAME=$2\n      shift 2\n      ;;\n    -l|--target-password)\n      TARGET_PASSWORD=$2\n      shift 2\n      ;;\n    -m|--target-database-name)\n      TARGET_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -n|--target-sku)\n      TARGET_SKU=$2\n      shift 2\n      ;;\n    --) # end argument parsing\n      shift\n      break\n      ;;\n    -*|--*=) # unsupported flags\n      echo \"Error: Unsupported flag $1\" >&2\n      exit 1\n      ;;\n    *) # preserve positional arguments\n      PARAMS=\"$PARAMS $1\"\n      shift\n      ;;\n  esac\ndone\n# set positional arguments in their proper place\neval set -- \"$PARAMS\"\n\n# Prerequisites - Install Azure CLI and mysql-client package\nif ! [ -x \"$(command -v az)\" ]; then\n  echo 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysqldump)\" ]; then\n  echo 'Error: mysqldump command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v mysql)\" ]; then\n  echo 'Error: mysql command does not exist. Please install from https://dev.mysql.com/downloads/mysql/' >&2\n  exit 1\nfi\n\n# Login to source subscription\naz login\naz account set --subscription \"$SOURCE_SUBSCRIPTION_ID\"\n\n# Firewall rule name to allow the current VM\nexport FIREWALLRULENAME=\"AllowAllIps$(date +%s)\"\n\n# Create firewall rule on the source server to allow connections from current VM\naz mysql server firewall-rule create -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Export mysql password to be used by the mysqldump command\nexport MYSQL_PWD=$SOURCE_PASSWORD\n\n# Remove dump file if it already exists\n[ -e \"$SOURCE_DATABASE_NAME.sql\" ] && rm -f \"$SOURCE_DATABASE_NAME.sql\"\n\n# Create a dump file of the source db\nmysqldump --ssl-mode=REQUIRED -Fc -v --host=\"$SOURCE_SERVER_NAME.mysql.database.azure.com\" --user=\"$SOURCE_USERNAME@$SOURCE_SERVER_NAME\" --databases \"$SOURCE_DATABASE_NAME\" >\"$SOURCE_DATABASE_NAME.sql\"\n\n# check that filesize of dump file is greater than 0\nif ! [ -s \"$SOURCE_DATABASE_NAME.sql\" ]; then\n  echo 'Error during mysqldump' >&2\n  exit 1\nfi\n\n# Login to target subscription \naz account set --subscription \"$TARGET_SUBSCRIPTION_ID\"\n\n# Set target server password\nexport MYSQL_PWD=$TARGET_PASSWORD\n\n# Create the target server in the specified region\naz mysql server create -l \"$TARGET_REGION\" -g \"$TARGET_RESOURCE_GROUP_NAME\" -n \"$TARGET_SERVER_NAME\" -u \"$TARGET_USERNAME\" -p \"$MYSQL_PWD\" --sku-name \"$TARGET_SKU\"\n\n# Create the target database\naz mysql db create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$TARGET_DATABASE_NAME\"\n\n# Create firewall rule on the target server to allow connections from current VM\naz mysql server firewall-rule create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Export MYSQL database name to be used by the mysql command\nexport MYSQL_DATABASE=$TARGET_DATABASE_NAME\n\n# Restore the database using source database dump file\nmysql --ssl-mode=REQUIRED -v --host=\"$TARGET_SERVER_NAME.mysql.database.azure.com\" --port=3306 --user=\"$TARGET_USERNAME@$TARGET_SERVER_NAME\" < \"$SOURCE_DATABASE_NAME.sql\"\n\n# Delete firewall rules and local dump file\naz mysql server firewall-rule delete -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\naz mysql server firewall-rule delete -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\nrm -f \"$SOURCE_DATABASE_NAME.sql\"\n\n# Logout\naz logout\n\n# Visit Target Server\necho \"Migration Successful !!\"\necho \"Target Server : https://portal.azure.com/#resource/subscriptions/$TARGET_SUBSCRIPTION_ID/resourceGroups/$TARGET_RESOURCE_GROUP_NAME/providers/Microsoft.DBforMySQL/servers/$TARGET_SERVER_NAME/overview\"", "num_lines": 245}
{"repo_name": "Azure-Network-Security", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Download BPC API Client from: https://breakingpoint.cloud/ \n# Reference docs: https://breakingpoint.cloud/api-help/BpcDdosAPI.htm \n# Script tested on Ubuntu 18.04 LTS\n# Windows users download bpcddos.zip from https://breakingpoint.cloud/  to root folder\n\nsudo apt install python3-pip\nsudo apt install requests[security]\npip3 install requests-aws4auth\npip3 install boto3\npip3 install bpcddos.zip\n", "num_lines": 11}
{"repo_name": "Azure-Network-Security", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\napt-get update -y && apt-get upgrade -y\napt-get install -y nginx\necho \"Hello World from host\" $HOSTNAME \"!\" | sudo tee -a /var/www/html/index.html\n\ntouch /etc/nginx/nginx.conf\ncat >> /etc/nginx/nginx.conf <<EOF\nstream {\n      upstream dns_servers {\n       server 168.63.129.16:53;\n}\n\nserver {\n listen x.x.x.x:53  udp;\n listen x.x.x.x:53; #tcp\n proxy_pass dns_servers;\n proxy_responses 1;\n error_log  /var/log/nginx/dns.log info;\n}\n}\nEOF\n\nmyip=`hostname -i | awk '{print $1}'`\nsed -i \"s/x.x.x.x/$myip/\" /etc/nginx/nginx.conf\n\n\nsudo nginx -t && sudo service nginx reload\n", "num_lines": 51}
{"repo_name": "Azure-Network-Security", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2021 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Variables\nprivateDnsZoneName=$1\nvmName1=$2\nvmName2=$3\nadlsServicePrimaryEndpoint=$4\nblobServicePrimaryEndpoint=$5\nfileSystemName=${HOSTNAME,,}\ndirectoryName=\"documents\"\nfileName=\"${HOSTNAME,,}.txt\"\nfileContent=\"This file was written by the $HOSTNAME virtual machine via a private endpoint.\"\n\n# Parameter validation\nif [[ -z $privateDnsZoneName ]]; then\n    echo \"privateDnsZoneName cannot be null or empty\"\n    exit 1\nelse\n    echo \"privateDnsZoneName        : $privateDnsZoneName\"\nfi\n\nif [[ -z $vmName1 ]]; then\n    echo \"vmName1 cannot be null or empty\"\n    exit 1\nelse\n    echo \"vmName1                   : $vmName1\"\nfi\n\nif [[ -z $vmName2 ]]; then\n    echo \"vmName2 cannot be null or empty\"\n    exit 1\nelse\n    echo \"vmName2                   : $vmName2\"\nfi\n\nif [[ -z $adlsServicePrimaryEndpoint ]]; then\n    echo \"adlsServicePrimaryEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"adlsServicePrimaryEndpoint: $adlsServicePrimaryEndpoint\"\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"blobServicePrimaryEndpoint: $blobServicePrimaryEndpoint\"\nfi\n\nif [[ -z $fileSystemName ]]; then\n    echo \"fileSystemName parameter cannot be null or empty\"\n    exit 1\nelse\n    echo \"fileSystemName            : $fileSystemName\"\nfi\n\nif [[ -z $directoryName ]]; then\n    echo \"directoryName parameter cannot be null or empty\"\n    exit 1\nelse\n    echo \"directoryName             : $directoryName\"\nfi\n\n# Extract the adls storage account name from the adls service primary endpoint\n# Note: when using the Azure CLI, you have to use both a blob and adls private endpoint\n# because under the cover the tool uses calls to the blob REST API\nstorageAccountName=$(echo \"$adlsServicePrimaryEndpoint\" | awk -F'.' '{print $1}')\n\nif [[ -z $storageAccountName ]]; then\n    echo \"storageAccountName cannot be null or empty\"\n    exit 1\nelse\n    echo \"storageAccountName: $storageAccountName\"\nfi\n\n# Eliminate debconf: warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Install NGINX web server\nsudo apt-get install -y nginx\n\n# Change the default page of the NGINX web server\nsudo echo \"This is [$HOSTNAME] virtual machine\" > /var/www/html/index.html\n\n# Install curl and traceroute\nsudo apt-get install -y curl traceroute\n\n# Install Azure CLI\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Run nslookup to verify that the <vm-name-1>.<private-dns-zone-name> is resolved to the private IP address of the first virtual machine\necho \"nslookup ${vmName1,,}.$privateDnsZoneName\"\nnslookup ${vmName1,,}.$privateDnsZoneName\n\n# Call the NGINX web server on the first virtual machine\necho \"curl http://${vmName1,,}.$privateDnsZoneName\"\ncurl http://${vmName1,,}.$privateDnsZoneName\n\n# Run nslookup to verify that the <vm-name-2>.<private-dns-zone-name> is resolved to the private IP address of the second virtual machine\necho \"nslookup ${vmName2,,}.$privateDnsZoneName\"\nnslookup ${vmName2,,}.$privateDnsZoneName\n\n# Call the NGINX web server on the second virtual machine\necho \"curl http://${vmName2,,}.$privateDnsZoneName\"\ncurl http://${vmName2,,}.$privateDnsZoneName\n\n# Run nslookup to verify that the <storage-account>.dfs.core.windows.net public hostname of the storage account\n# is properly mapped to <storage-account>.privatelink.dfs.core.windows.net by the privatelink.dfs.core.windows.net\n# private DNS zone and the latter is resolved to the private address by the A record\necho \"nslookup $adlsServicePrimaryEndpoint\"\nnslookup $adlsServicePrimaryEndpoint\n\n# Run nslookup to verify that the <storage-account>.blob.core.windows.net public hostname of the storage account\n# is properly mapped to <storage-account>.privatelink.blob.core.windows.net by the privatelink.blob.core.windows.net\n# private DNS zone and the latter is resolved to the private address by the A record\necho \"nslookup $blobServicePrimaryEndpoint\"\nnslookup $blobServicePrimaryEndpoint\n\n# Login using the virtual machine system-assigned managed identity\naz login --identity\n\n# Create file system for the Azure Data Lake Storage Gen2 account\necho \"Checking if the $fileSystemName file system already exists in the $storageAccountName storage account...\"\nname=$(az storage fs show \\\n    --name $fileSystemName \\\n    --account-name $storageAccountName \\\n    --auth-mode login \\\n    --query name \\\n    --output tsv 2>/dev/null)\n\nif [[ -z $name ]]; then\n    echo \"The $fileSystemName file system does not exist in the $storageAccountName storage account\"\n    echo \"Creating the $fileSystemName file system in the $storageAccountName storage account...\"\n\n    az storage fs create \\\n        --name $fileSystemName \\\n        --account-name $storageAccountName \\\n        --auth-mode login\n\n    if [[ $? == 0 ]]; then\n        echo \"The $fileSystemName file system was successfully created in the $storageAccountName storage account\"\n    else\n        echo \"Failed to create the $fileSystemName file system in the $storageAccountName storage account\"\n        exit\n    fi\nelse\n    echo \"The $fileSystemName file system already exists in the $storageAccountName storage account\"\nfi\n\n# Create a directory in the ADLS Gen2 file system\necho \"Checking if the $directoryName directory exists in the $fileSystemName file system under the $storageAccountName storage account...\"\nname=$(az storage fs directory show \\\n    --file-system $fileSystemName \\\n    --name $directoryName \\\n    --account-name $storageAccountName \\\n    --auth-mode login \\\n    --query name \\\n    --output tsv 2>/dev/null)\n\nif [[ -z $name ]]; then\n    echo \"The $directoryName directory does not exist in the $fileSystemName file system under the $storageAccountName storage account\"\n    echo \"Creating the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\n\n    az storage fs directory create \\\n        --file-system $fileSystemName \\\n        --name $directoryName \\\n        --account-name $storageAccountName \\\n        --auth-mode login\n\n    if [[ $? == 0 ]]; then\n        echo \"The directoryName directory was successfully created in the $fileSystemName file system under the $storageAccountName storage account\"\n    else\n        echo \"Failed to create the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\n        exit\n    fi\nelse\n    echo \"The $directoryName directory already exists in the $fileSystemName file system under the $storageAccountName storage account\"\nfi\n\n# Create a file to upload to the ADLS Gen2 file system in the storage account\necho \"$fileContent\" >$fileName\n\n# Upload the file to a file path in ADLS Gen2 file system.\necho \"Uploading the $filename file to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\naz storage fs file upload \\\n    --file-system $fileSystemName \\\n    --path \"$directoryName/$fileName\" \\\n    --source \"./$fileName\" \\\n    --account-name $storageAccountName \\\n    --overwrite true \\\n    --auth-mode login\n\nif [[ $? == 0 ]]; then\n    echo \"The $filename file was successfully uploaded to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\nelse\n    echo \"Failed to upload the $filename file to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\n    exit\nfi\n\n# List files and directories in the directory in the ADLS Gen2 file system.\necho \"Listing the files inside the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\naz storage fs file list \\\n    --file-system $fileSystemName \\\n    --path $directoryName \\\n    --account-name $storageAccountName \\\n    --auth-mode login", "num_lines": 234}
{"repo_name": "azure-notificationhubs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nOUTPUT_PATH=$APPCENTER_SOURCE_DIRECTORY/Android/Samples/notification-hubs-test-app/app/google-services.json\n\necho $GOOGLE_SERVICES_JSON > $OUTPUT_PATH\n\necho \"Writing google-services.json: $OUTPUT_PATH\"\necho \"GOOGLE_SERVICE_JSON: ${GOOGLE_SERVICES_JSON:0:20}...\"\n\n", "num_lines": 10}
{"repo_name": "azure-notificationhubs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n", "num_lines": 2}
{"repo_name": "azure-notificationhubs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash", "num_lines": 1}
{"repo_name": "azure-notificationhubs", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nINFO_PLIST=$APPCENTER_SOURCE_DIRECTORY/iOS/Samples/nhubsample/nhubsample/Info.plist\n\nif [ \"$NHUB_NAME\" != \"\" ]; then\n    plutil -replace NotificationHubName -string \"$NHUB_NAME\" $INFO_PLIST\nfi\n\nif [ \"$NHUB_CONNECTIONSTRING\" != \"\" ]; then\n    plutil -replace NotificationHubConnectionString -string \"$NHUB_CONNECTIONSTRING\" $INFO_PLIST\nfi\n\n# Force sandbox notification environment\nplutil -replace \"aps-environment\" -string \"development\" $APPCENTER_SOURCE_DIRECTORY/iOS/Samples/nhubsample/nhubsample/nhubsample.entitlements\n", "num_lines": 15}
{"repo_name": "azure-notificationhubs-android", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $GOOGLE_SERVICES_JSON  | base64 --decode > \"$APPCENTER_SOURCE_DIRECTORY/notification-hubs-sample-app-java/google-services.json\"\n", "num_lines": 2}
{"repo_name": "azure-notificationhubs-android", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nOUTPUT_PATH=$APPCENTER_SOURCE_DIRECTORY/Android/Samples/notification-hubs-test-app/app/google-services.json\n\necho $GOOGLE_SERVICES_JSON > $OUTPUT_PATH\n\necho \"Writing google-services.json: $OUTPUT_PATH\"\necho \"GOOGLE_SERVICE_JSON: ${GOOGLE_SERVICES_JSON:0:20}...\"\n\n", "num_lines": 10}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "echo $DEV_SETTINGS_PLIST  | base64 --decode > \"$APPCENTER_SOURCE_DIRECTORY/$APPCENTER_XCODE_SCHEME/$APPCENTER_XCODE_SCHEME/DevSettings.plist\"", "num_lines": 1}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "  \n#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n\n# This script runs clang_format on all .h, .m, and .mm files that have changes from main branch.\n# Before running this, ensure that your local main branch is up to date.\nupstream=$(git remote -v | grep -i \"Azure/\" | awk '{print $1}' | uniq)\ngit fetch $upstream\ni=0\nfor modified_file in $(git diff $upstream/main --diff-filter=ACMR --name-only -- *.h *.m *.mm)\ndo\n  if [[ $modified_file != *\"Vendor/\"* ]]\n  then\n    clang-format -i -style=file $modified_file\n    exit_code=$?\n    if [ $exit_code -ne 0 ]\n    then\n      echo \"Failed to format file: \"$modified_file\n    else\n      ((i++))\n    fi\n  fi\ndone\necho \"Formatted \"$i\" file(s).\"", "num_lines": 25}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Builds the framework for the specified target.\n# Usage: build-framework.sh <target> <sdk>\n# Note: it must be run from Xcode's build phase.\n\nset -e\n\n# Print only target name and configuration. Mimic Xcode output to make prettify tools happy.\necho \"=== BUILD TARGET $1 OF PROJECT $PROJECT_NAME WITH CONFIGURATION $CONFIGURATION ===\"\n\n# OBJROOT must be customized to avoid conflicts with the current process.\nif [ \"$2\" == \"maccatalyst\" ]; then\n    # Mac Catalyst is a special case - \"destination\" parameter must be used here.\n    env -i \"PATH=$PATH\" xcodebuild \\\n        SYMROOT=\"$SYMROOT\" OBJROOT=\"$BUILD_DIR/$CONFIGURATION-$2/$PROJECT_NAME\" PROJECT_TEMP_DIR=\"$PROJECT_TEMP_DIR\" \\\n        ONLY_ACTIVE_ARCH=NO \\\n        -project \"$PROJECT_NAME.xcodeproj\" -configuration \"$CONFIGURATION\" \\\n        -scheme \"$1\" -destination 'platform=macOS,variant=Mac Catalyst'\nelse\n    env -i \"PATH=$PATH\" xcodebuild \\\n        SYMROOT=\"$SYMROOT\" OBJROOT=\"$BUILD_DIR/$CONFIGURATION-$2/$PROJECT_NAME\" PROJECT_TEMP_DIR=\"$PROJECT_TEMP_DIR\" \\\n        ONLY_ACTIVE_ARCH=NO \\\n        -project \"$PROJECT_NAME.xcodeproj\" -configuration \"$CONFIGURATION\" \\\n        -target \"$1\" -sdk \"$2\"\nfi\n", "num_lines": 30}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Combines frameworks for device and simulator into universal one.\n# Usage: combine-frameworks.sh <device> <simulator> <output>\n\nset -e\n\necho \"Combining device and simulator frameworks\"\ncp -Rv \"$1\" \"$3\"\n\n# Combining libraries.\nproduct_name=${1##*/}\nproduct_name=${product_name%.*}\n$(dirname \"$0\")/combine-libraries.sh \\\n    \"$1/${product_name}\" \\\n    \"$2/${product_name}\" \\\n    \"$3/${product_name}\"\n\necho \"Appending simulator platform to Info.plist\"\nsimulator_platform=$(plutil -extract CFBundleSupportedPlatforms.0 xml1 \"$2/Info.plist\" -o -| sed -n \"s/.*<string>\\(.*\\)<\\/string>.*/\\1/p\")\nplutil -insert CFBundleSupportedPlatforms.1 -string $simulator_platform \"$3/Info.plist\"\n", "num_lines": 25}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Combines libraries for device and simulator into universal one.\n# Usage: combine-libraries.sh <device> <simulator> <output>\n\nset -e\n\nlibrary_archs_diff() {\n  local device_archs=($(lipo -archs \"$1\"))\n  local simulator_archs=($(lipo -archs \"$2\"))\n  comm -12 <(printf '%s\\n' \"${device_archs[@]}\" | sort) <(printf '%s\\n' \"${simulator_archs[@]}\" | sort)\n}\nduplicate_archs=($(library_archs_diff \"$1\" \"$2\"))\nif [ ${#duplicate_archs[@]} -ne 0 ]; then\n  echo \"Removing duplicate architectures (${duplicate_archs[@]}) from library for simulator\"\n  lipo \"$2\" ${duplicate_archs[@]/#/ -remove } -output \"$3\"\nelif [ \"$2\" != \"$3\" ]; then\n  cp \"$2\" \"$3\"\nfi\n\necho \"Combining device and simulator libraries\"\nlipo \"$1\" \"$3\" -create -output \"$3\"\n\n# Show information of result library.\nlipo -info \"$3\"\n", "num_lines": 29}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Cleaning the previous builds.\nrm -rf \"${BUILT_PRODUCTS_DIR}/${PROJECT_NAME}.xcframework\"\n\n# Create a command to build XCFramework.\nfunction add_framework() {\n  local framework_path=\"$1/${PRODUCT_NAME}.framework\"\n  [ -e \"${framework_path}\" ] && XC_FRAMEWORKS+=( -framework \"${framework_path}\")\n}\nadd_framework \"${BUILD_DIR}/${CONFIGURATION}\"\nfor SDK in iphoneos iphonesimulator appletvos appletvsimulator maccatalyst; do\n  add_framework \"${BUILD_DIR}/${CONFIGURATION}-${SDK}\"\ndone\n\n# Build XCFramework.\nxcodebuild -create-xcframework \"${XC_FRAMEWORKS[@]}\" -output \"${BUILT_PRODUCTS_DIR}/${PROJECT_NAME}.xcframework\"", "num_lines": 20}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\nset -e\n\n# The directory for final output.\nPRODUCTS_DIR=\"${SRCROOT}/../WindowsAzureMessaging-SDK-Apple\"\n\ncopy_framework() {\n  if [ ! -e \"$1/${PROJECT_NAME}.$3\" ]; then\n    return\n  fi\n  rm -rf \"$2/${PROJECT_NAME}.$3\"\n  mkdir -p \"$2\"\n  cp -RHv \"$1/${PROJECT_NAME}.$3\" \"$2\"\n  if [ -e \"$1/${PROJECT_NAME}Resources.bundle\" ]; then\n    rm -rf \"$2/${PROJECT_NAME}Resources.bundle\"\n    cp -Rv \"$1/${PROJECT_NAME}Resources.bundle\" \"$2\"\n  fi\n}\ncopy_framework \"${BUILD_DIR}/${CONFIGURATION}-iphoneuniversal\" \"${PRODUCTS_DIR}/iOS\" \"framework\"\ncopy_framework \"${BUILD_DIR}/${CONFIGURATION}\" \"${PRODUCTS_DIR}/macOS\" \"framework\"\ncopy_framework \"${BUILD_DIR}/${CONFIGURATION}-appletvuniversal\" \"${PRODUCTS_DIR}/tvOS\" \"framework\"\ncopy_framework \"${BUILD_DIR}/${CONFIGURATION}-xcframework\" \"${PRODUCTS_DIR}/XCFramework\" \"xcframework\"\n", "num_lines": 27}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Creates zip archives from frameworks.\n# Usage: create-archive.sh\n\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nPRODUCT_NAME=\"WindowsAzureMessaging-SDK-Apple\"\nPRODUCTS_DIR=\"$PROJECT_DIR/$PRODUCT_NAME\"\n\n# Enable extended globbing.\nshopt -s extglob nullglob\n\n# Check if the frameworks are already built.\nif [ ! -d \"$PRODUCTS_DIR/iOS\" ] || [ ! -d \"$PRODUCTS_DIR/macOS\" ] || \\\n    [ ! -d \"$PRODUCTS_DIR/tvOS\" ] || [ ! -d \"$PRODUCTS_DIR/XCFramework\" ]; then\n  echo \"Cannot find frameworks to archive, please run build first\"\n  exit 1\nfi\n\n# Verify prefix for framework classes.\nframework_classes() {\n  nm -gjoUC \"$1\" | awk '{print $2}' | grep \"_OBJC_CLASS_\" | cut -d_ -f5-\n}\nverify_framework_prefixes() {\n  local name=${1##*/}\n  name=${name%.*}\n  local classes=$(framework_classes \"$1/$name\")\n  for prefix in ${@:2}; do\n    classes=$(echo \"$classes\" | grep -v $prefix)\n  done\n  echo \"$classes\"\n  [ -z \"$classes\" ]\n}\nfor framework in $PRODUCTS_DIR/**/*.framework; do\n  invalid_prefix_classes+=($(verify_framework_prefixes \"$framework\" \"ANH\" \"MS\" \"SB\")) || invalid_prefix_framework+=(${framework#\"$PRODUCTS_DIR\"/})\ndone\nif [ ${#invalid_prefix_framework[@]} -ne 0 ]; then\n  echo \"There are frameworks that contain classes without required prefix: ${invalid_prefix_framework[@]}\"\n  echo \"Please fix the prefix for the following classes:\"\n  printf '%s\\n' \"${invalid_prefix_classes[@]}\" | sort | uniq\n  # TODO uncomment before release.\n  # exit 1\nfi\n\n# Verify bitcode.\nfunction verify_bitcode() {\n  local name=${1##*/}\n  name=${name%.*}\n  otool -l \"$1/$name\" | grep __LLVM > /dev/null\n}\nfor framework in \\\n    $PRODUCTS_DIR/iOS/*.framework \\\n    $PRODUCTS_DIR/tvOS/*.framework \\\n    $PRODUCTS_DIR/XCFramework/*.xcframework/ios-!(*-*)/*.framework \\\n    $PRODUCTS_DIR/XCFramework/*.xcframework/tvos-!(*-*)/*.framework; do\n  verify_bitcode \"$framework\" || invalid_bitcode+=(${framework#\"$PRODUCTS_DIR\"/})\ndone\nif [ ${#invalid_bitcode[@]} -ne 0 ]; then\n  echo \"There are iOS/tvOS binaries without valid bitcode: ${invalid_bitcode[@]}\"\n  exit 1\nfi\nfor framework in \\\n    $PRODUCTS_DIR/macOS/*.framework \\\n    $PRODUCTS_DIR/XCFramework/*.xcframework/macos-*/*.framework \\\n    $PRODUCTS_DIR/XCFramework/*.xcframework/*-maccatalyst/*.framework; do\n  verify_bitcode \"$framework\" && invalid_bitcode+=(${framework#\"$PRODUCTS_DIR\"/})\ndone\nif [ ${#invalid_bitcode[@]} -ne 0 ]; then\n  echo \"There are macOS binaries with bitcode (it should not be there): ${invalid_bitcode[@]}\"\n  exit 1\nfi\n\n# Verify architectures.\nfunction verify_framework_architectures() {\n  local name=${1##*/}\n  name=${name%.*}\n  local archs=($(lipo -archs \"$1/$name\"))\n  archs=($(printf '%s\\n' \"${archs[@]}\" | sort))\n  required=($(printf '%s\\n' \"${@:2}\" | sort))\n  if [[ \"${archs[@]}\" != \"${required[@]}\" ]]; then\n    echo \"${1#$PRODUCTS_DIR/} doesn't contain required architectures. It has '${archs[@]}' but '${required[@]}' are required.\"\n    return 1\n  fi\n}\nfunction verify_architectures() {\n  for framework in $PRODUCTS_DIR/$1; do\n    verify_framework_architectures \"$framework\" ${@:2} || return $?\n  done\n}\nverify_architectures \"iOS/*.framework\" armv7 armv7s arm64 arm64e i386 x86_64 || exit $?\nverify_architectures \"macOS/*.framework\" arm64 x86_64 || exit $?\nverify_architectures \"tvOS/*.framework\" arm64 x86_64 || exit $?\nverify_architectures \"XCFramework/*.xcframework/ios-!(*-*)/*.framework\" armv7 armv7s arm64 arm64e || exit $?\nverify_architectures \"XCFramework/*.xcframework/ios-*-maccatalyst/*.framework\" arm64 x86_64 || exit $?\nverify_architectures \"XCFramework/*.xcframework/ios-*-simulator/*.framework\" arm64 i386 x86_64 || exit $?\nverify_architectures \"XCFramework/*.xcframework/macos-*/*.framework\" arm64 x86_64 || exit $?\nverify_architectures \"XCFramework/*.xcframework/tvos-!(*-*)/*.framework\" arm64 || exit $?\nverify_architectures \"XCFramework/*.xcframework/tvos-*-simulator/*.framework\" arm64 x86_64 || exit $?\n\n# Creates zip archive.\n# Usage: archive <result-name> <list-of-content>\nfunction archive() {\n  echo \"Creating $1 archive from ${@:2}\"\n\n  # Create temporary directory.\n  local temp_dir=$(mktemp -d -t $1)\n  mkdir -p \"$temp_dir/$PRODUCT_NAME\"\n\n  # Copy required files.\n  cp \"$PROJECT_DIR/LICENSE\" \"$temp_dir/$PRODUCT_NAME\"\n  cp \"$PROJECT_DIR/README.md\" \"$temp_dir/$PRODUCT_NAME\"\n  cp \"$PROJECT_DIR/CHANGELOG.md\" \"$temp_dir/$PRODUCT_NAME\"\n  (cd \"$PROJECT_DIR\" && cp -R \"${@:2}\" \"$temp_dir/$PRODUCT_NAME\")\n\n  # Remmove old archive if exists.\n  if [ -f \"$PRODUCTS_DIR/$1\" ]; then\n    rm \"$PRODUCTS_DIR/$1\"\n  fi\n\n  # Zip content.\n  (cd \"$temp_dir\" && zip -ryq9 \"$1\" \"$PRODUCT_NAME\")\n  mv \"$temp_dir/$1\" \"$PRODUCTS_DIR\"\n\n  # Remove temporary directory.\n  rm -rf \"$temp_dir\"\n}\n\n# Get current version.\nVERSION=\"$($(dirname \"$0\")/framework-version.sh)\"\n\n# Archive fat frameworks for Carthage.\narchive \"$PRODUCT_NAME-$VERSION.carthage.framework.zip\" \"$PRODUCT_NAME/iOS\" \"$PRODUCT_NAME/macOS\" \"$PRODUCT_NAME/tvOS\"\n\n# Archive fat frameworks for CocoaPods.\narchive \"$PRODUCT_NAME-$VERSION.zip\" \"$PRODUCT_NAME/iOS\" \"$PRODUCT_NAME/macOS\" \"$PRODUCT_NAME/tvOS\"\n\n# Archive XCFrameworks.\narchive \"$PRODUCT_NAME-XCFramework-$VERSION.zip\" $(cd \"$PROJECT_DIR\" && ls -d \"$PRODUCT_NAME/XCFramework\"/*)\n\n# Verify result archives.\nfunction verify_symlinks() {\n  read symlinks\n  name=${1##*/}\n  name=${name%.*}\n  for symlink in Resources Versions/Current Headers Modules $name; do\n    echo $symlinks | grep -q \"$1/$symlink\" || return $?\n  done\n}\nfunction verify_archive() {\n  echo \"Verify archive: ${1##*/}\"\n  frameworks=$(unzip -Z1 \"$1\" | grep \"^$PRODUCT_NAME/.*\\.framework/$\")\n\n  # Verify symlinks in macOS frameworks.\n  mac_frameworks=$(echo \"$frameworks\" | grep '/macOS/\\|macos-\\|-maccatalyst')\n  symlinks=$(unzip -Z \"$1\" | grep ^l | awk '{print $9}')\n  for framework in $mac_frameworks; do\n    if ! verify_symlinks ${framework%/} <<< $symlinks; then\n      invalid_symlinks+=(${framework%/})\n    fi\n  done\n  if [ ${#invalid_symlinks[@]} -ne 0 ]; then\n    echo \"Archive contains frameworks with invalid symlinks: ${invalid_symlinks[@]}\"\n    return 1\n  fi\n\n  # Verify that there are no invalid files.\n  invalid_files=$(unzip -Z1 \"$1\" | grep \"$(echo \\\\.{a,xconfig,sh,md,txt}$ | sed 's/ /\\\\|/g')\")\n  if [ $? -eq 0 ]; then\n    echo \"Archive contains invalid files: $invalid_files\"\n    return 1\n  fi\n}\nexit_code=0\nverify_archive \"$PRODUCTS_DIR/$PRODUCT_NAME-$VERSION.zip\" || exit_code=$?\nverify_archive \"$PRODUCTS_DIR/$PRODUCT_NAME-$VERSION.carthage.framework.zip\" || exit_code=$?\nverify_archive \"$PRODUCTS_DIR/$PRODUCT_NAME-XCFramework-$VERSION.zip\" || exit_code=$?\nexit $exit_code\n", "num_lines": 181}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Gets or sets framework version.\n# Usage: framework-version.sh               - to get the current version\n#        framework-version.sh <version>     - to set the version\n\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nVERSION_CONFIG=\"$PROJECT_DIR/Config/Version.xcconfig\"\nif [ -z $1 ]; then\n  grep \"VERSION_STRING\" \"$VERSION_CONFIG\" | head -1 | awk -F \"[= ]\" '{print $4}'\nelse\n  sed -i '' 's/\\(VERSION_STRING[[:space:]]*=[[:space:]]*\\).*/\\1'$1'/g' $VERSION_CONFIG\nfi\n", "num_lines": 17}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Generates the documentation for the project.\n# Usage: generate-documentation.sh <os-name>\n# Note: it must be run from Xcode.\n\nOS_NAME=$1\nPRODUCTS_DIR=\"${SRCROOT}/../WindowsAzureMessaging-SDK-Apple/${OS_NAME}\"\nINSTALL_DIR=\"${PRODUCTS_DIR}/${PROJECT_NAME}.framework\"\nDOCUMENTATION_DIR=\"${PRODUCTS_DIR}/Documentation/${PROJECT_NAME}\"\n\n# Check if jazzy installed.\nif [ ! -x \"$(command -v jazzy)\" ]; then\n  echo \"Couldn't find jazzy. Install jazzy before building frameworks\"\n  exit 1\nfi\n\njazzy --config \"${SRCROOT}/../Documentation/${OS_NAME}/${PROJECT_NAME}/.jazzy.yaml\"\n\n# Create Documentation directory within folder.\nif [ ! -d \"${DOCUMENTATION_DIR}\" ]; then\n  mkdir -p \"${DOCUMENTATION_DIR}\"\nfi\n\n# Copy generated documentation into the documentation folder.\ncp -R \"${SRCROOT}/../Documentation/${OS_NAME}/${PROJECT_NAME}/Generated/\" \"${DOCUMENTATION_DIR}\"\n", "num_lines": 30}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n\n# Reads release notes for the release.\n# Usage: get-release-notes.sh [<version>]\n\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nCHANGELOG_FILE=\"$PROJECT_DIR/CHANGELOG.md\"\n\nchange_log_found=false\nwhile IFS='' read -r line || -n \"$line\" ]]; do\n\n# If it is reading change log for the version\nif $change_log_found; then\n\n  # If it reads end of change log for the version\n  if [[ \"$line\" == \"___\" ]]; then\n    break\n\n  # Append the line\n  else\n    echo \"$line\"\n  fi\n\n# If it didn't find changelog for the version\nelse\n\n  # If it is the first line of change log for the version\n  if [[ \"$line\" =~ \"## Version $1\" ]]; then\n    echo \"$line\"\n    change_log_found=true\n  fi\nfi\ndone < $CHANGELOG_FILE\n", "num_lines": 36}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n\n# Run lint to validate podspec\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nPODSPEC_FILE=\"$PROJECT_DIR/AzureNotificationHubs-iOS.podspec\"\n\npod spec lint $PODSPEC_FILE --verbose\nretval=$?\n\nif [ $retval -eq 0 ]; then\n    echo $'\\360\\237\\215\\272 Podspec validated successfully'\nelse\n    echo '\\xf0\\x9f\\x91\\xbf Cannot publish to CocoaPods due to spec validation failure'\n    exit 1\nfi", "num_lines": 17}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n\n# Push podspec to CocoaPods\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nPODSPEC_FILE=\"$PROJECT_DIR/AzureNotificationHubs-iOS.podspec\"\n\npod trunk push $PODSPEC_FILE\nretval=$?\n\nif [ $retval -eq 0 ]; then\n    echo $'\\360\\237\\215\\272 Podspec published to CocoaPods successfully\"'\nelse\n    echo -e '\\xf0\\x9f\\x91\\xbf Cannot publish to CocoaPods'\n    exit 1\nfi", "num_lines": 17}
{"repo_name": "azure-notificationhubs-ios", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License.\n\n# Updates SDK version.\n# Usage: update-version.sh -v <new-version>\n\nhelp() {\n  echo \"Usage: $0 -v <new-version>\"\n}\n\n## Check parameters\nnew_version=\"\"\nwhile getopts 'v:' flag; do\n  case \"${flag}\" in\n    v)\n      new_version=${OPTARG}\n      ;;\n    *)\n      help\n      exit 1\n      ;;\n  esac\ndone\n\nif [ \"$new_version\" == \"\" ]; then\n  help\n  exit 1\nfi\n\nPROJECT_DIR=\"$(dirname \"$0\")/..\"\nDOCUMENT_DIR=\"$PROJECT_DIR/Documentation\"\nPODSPEC_FILE=\"$PROJECT_DIR/AzureNotificationHubs-iOS.podspec\"\nSWIFTPM_FILE=\"$PROJECT_DIR/Package.swift\"\nSWIFTPM_5_3_FILE=\"$PROJECT_DIR/Package@swift-5.3.swift\"\n\n# Update framework version\n$(dirname \"$0\")/framework-version.sh $new_version\n\n# Update documentation version\nfor file in `find $DOCUMENT_DIR -name '.jazzy.yaml' -type f`; do\n  sed -i '' 's/\\(module_version: \\).*/\\1'$new_version'/g' $file\ndone\n\n# Update CocoaPods version\nsed -i '' \"s/\\(\\.version[[:space:]]*= \\)\\'.*\\'$/\\1'$new_version'/1\" $PODSPEC_FILE\n\n# Update SwiftPM version\nupdateSwiftPMVersion() {\n  sed -i '' 's/\\(define(\"NH_C_VERSION\",[[:space:]]*to:*\\).*/\\1''\"\\\\\"'$new_version'\\\\\"\"),''/g' $1\n}\nupdateSwiftPMVersion $SWIFTPM_FILE\nupdateSwiftPMVersion $SWIFTPM_5_3_FILE", "num_lines": 54}
{"repo_name": "azure-oam-solution", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\nset -eux\n\nif [[ \"$#\" -ne 2 ]]\nthen\n  echo \"usage: install-oam-local.sh <resource-group> <cluster-name>\"\n  exit 1\nfi\n\nRESOURCE_GROUP=$1\nCLUSTER_NAME=$2\n\naz aks get-credentials --name $CLUSTER_NAME --resource-group $RESOURCE_GROUP\n\nKUBERNETES_VERSION=\"1.16.9\"\nKUBECTL_VERSION=$(curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt)\nCROSSPLANE_VERSION=\"0.12.0\"\nCROSSPLANE_OAM_LOCAL_VERSION=\"0.1.0\"\n\n# Install kubectl - https://kubernetes.io/docs/tasks/tools/install-kubectl/#install-kubectl-on-linux\ncurl -LO \"https://storage.googleapis.com/kubernetes-release/release/$KUBECTL_VERSION/bin/linux/amd64/kubectl\"\nchmod +x ./kubectl\n./kubectl version --client\n\n# Install helm - https://helm.sh/docs/intro/install/\ncurl https://raw.githubusercontent.com/helm/helm/master/scripts/get-helm-3 | bash\nhelm version\n\n# Install Crossplane - https://crossplane.io/docs/v0.12/getting-started/install-configure.html\n./kubectl apply -f - <<EOF\napiVersion: v1\nkind: Namespace\nmetadata:\n  name: crossplane-system\nEOF\n\nhelm repo add crossplane-alpha https://charts.crossplane.io/alpha\nhelm install crossplane crossplane-alpha/crossplane \\\n  --namespace crossplane-system \\\n  --version \"$CROSSPLANE_VERSION\" \\\n  --wait\n\n# Workaround https://github.com/crossplane/addon-oam-kubernetes-local/issues/50 \n./kubectl create secret generic webhook-server-cert -n crossplane-system\n\nhelm install addon-oam-kubernetes-local crossplane-alpha/oam-core-resources \\\n  --namespace crossplane-system \\\n  --version \"$CROSSPLANE_OAM_LOCAL_VERSION\" \\\n  --wait\n", "num_lines": 50}
{"repo_name": "azure-ocp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf##SETUP##\n#change\n\n#Install Azure CLI\n#https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest\n\n#Login and set Azure Subscription\n\naz login\n\naz account set --subscription \"<SUBSCRIPTION_NAME>\" \n\n\n##DEPLOY CHALLENGE ONE##\n\n\n#https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-deploy-cli\n\naz group create --name P20-RG01 --location \"eastus2\"\n\n#With Inputs\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-01-basic-output.json \\\n    --parameters genericInput=\"Hello World\"\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-01-basic-output.json \\\n    --parameters challenge-01.parameters.json\n\n\n##DEPLOY CHALLENGE TWO##\n\n\n#With Inputs\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-02-vnet-one-subnet.json \\\n    --parameters vnetName=\"P20VNet\" vnetPrefix=\"10.0.0.0/16\" subnetName=\"Default\" subnetPrefix=\"10.0.0.0/24\"\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-02-vnet-one-subnet.json \\\n    --parameters challenge-02.parameters.json\n\n\n##DEPLOY CHALLENGE THREE##\n\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-03-vnet-with-nsg.json \\\n    --parameters challenge-03.parameters.json\n\n\n##DEPLOY CHALLENGE FOUR##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/blob/052db5feeba11f85d57f170d8202123511f72044/apache2-on-ubuntu-vm/azuredeploy.json\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-04-web-server.json \\\n    --parameters challenge-04.parameters.json\n\n\n##DEPLOY CHALLENGE FIVE##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/tree/052db5feeba11f85d57f170d8202123511f72044/201-2-vms-loadbalancer-lbrules\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-05-load-balanced-web-server.json \\\n    --parameters challenge-05.parameters.json\n\n\n##DEPLOY CHALLENGE SIX##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/tree/052db5feeba11f85d57f170d8202123511f72044/101-loadbalancer-with-nat-rule\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG01 \\\n    --template-file challenge-06-load-balanced-nat-rule.json \\\n    --parameters challenge-06.parameters.json\n    \n\n##DEPLOY CHALLENGE SEVEN##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/tree/21c1bf4e90a49e431c85384251e35934bce2a7f4/201-vmss-linux-nat\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG02 \\\n    --template-file challenge-07-vmss-linux.json \\\n    --parameters challenge-07.parameters.json\n\n\n##DEPLOY CHALLENGE EIGHT##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/tree/21c1bf4e90a49e431c85384251e35934bce2a7f4/201-vmss-lapstack-autoscale\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG02 \\\n    --template-file challenge-08-vmss-apache.json \\\n    --parameters challenge-08.parameters.json\n\n\n##DEPLOY CHALLENGE NINE##\n\n\n#Reference - https://github.com/Azure/azure-quickstart-templates/tree/21c1bf4e90a49e431c85384251e35934bce2a7f4/201-vmss-lapstack-autoscale\n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG02 \\\n    --template-file challenge-09-vmss-autoscale.json \\\n    --parameters challenge-09.parameters.json\n\n\n##DEPLOY CHALLENGE TEN##\n\n\n#Reference - \n\n#With Parameters File\naz group deployment create \\\n    --name P20Deployment \\\n    --resource-group P20-RG03 \\\n    --template-file challenge-10-p20-main.json \\\n    --parameters challenge-10.parameters.json", "num_lines": 153}
{"repo_name": "azure-ocp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# install Apache2\napt-get -y install apache2 \n\n# write some HTML\necho \\<center\\>\\<h1\\>Wecome to P20 ARM Training\\</h1\\>\\<br/\\>\\</center\\> > /var/www/html/p20.html\n\n# restart Apache\napachectl restart", "num_lines": 11}
{"repo_name": "azure-ocp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n\n# install Apache (in a loop because a lot of installs happen\n# on VM init, so won't be able to grab the dpkg lock immediately)\nuntil apt-get -y update && apt-get -y install apache2\ndo\n  echo \"Try again\"\n  sleep 2\ndone\n\n# write some HTML\necho \\<center\\>\\<h1\\>Wecome to P20 ARM Training\\</h1\\>\\<br/\\>\\</center\\> > /var/www/html/p20.html\n\n# restart Apache\napachectl restart", "num_lines": 16}
{"repo_name": "azure-ocp-samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "\u00ef\u00bb\u00bf##SETUP##\n\n#Install Azure CLI\n#https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest\n\n#Login and set Azure Subscription\n\naz login\n\n#Get list of all Azure subscriptions current logged in user has access to.\n# Note which one has IsDefault=True to know which subscription the Azure CLI will be executing against!\naz account list\n\n#If the account you want is NOT the default, then you can set the one you want\naz account set --subscription \"<SUBSCRIPTION_NAME>\" OR \"<subscriptionID>\"\n\n#Get a list of core quotas for a given region (important before you start deploying stuff)\n# Note: If the quote is not high enough for you, you must open a support ticket in the portal!\naz vm list-usage -l eastus2\n\n#Get a list of available VM sizes in a region\naz vm list-sizes -l eastus2\n\n#Get a list of top Windows & Linux VM images in the marketplace.\n# Note the \"offer\", \"sku\", and \"publisher\" values. These values allow you to set the VM image used in an ARM template!\naz vm image list\n\n#Get a list of VMs by various search queries\naz vm image list --publisher Oracle -l eastus2 --all  \naz vm image list --publisher MicrosoftSQLServer -l eastus2 --all \n\n#Create a resource group\naz group create --name iac-rg --location eastus2\n\n#Deploy templates to a resource group via Azure CLI\n#https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-template-deploy-cli\n\n##DEPLOY CHALLENGE FOUR##\naz group deployment create --name Challenge4Deployment --resource-group iac-rg --template-file challenge-04-windows-vm.json --parameters @challenge-04.parameters.json\n\n##DEPLOY CHALLENGE FIVE#\naz group deployment create --name Challenge5Deployment --resource-group iac-rg --template-file challenge-05-simple-dsc.json --parameters @challenge-05.parameters.json\n\n##DEPLOY CHALLENGE SIX##\naz group deployment create --name Challenge6Deployment --resource-group iac-rg --template-file challenge-06-file-server-dsc.json --parameters @challenge-06.parameters.json\n\n##Clean up\naz group delete --name iac-rg\n\n", "num_lines": 50}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n# This script creates the required linked service & the spark \n# job definition on the Synapse workspace and should be run \n# prior to executing the pipeline template from Synapse gallery.\n\nset -e\n\nENV_CODE=${1:-${ENV_CODE}}\n\nif [[ -z ${ENV_CODE} ]]\n  then\n    echo \"Missing Environment Code\"\n    exit 1\nfi\n\nbase_dir=\"$(cd \"$(dirname \"$0\")/../../\" && pwd)\"\n\n# Uncompress the custom vision model package\nif ! unzip \"${base_dir}\"/custom-vision-model.zip -d \"${base_dir}\"/custom-vision-model-\"${ENV_CODE}\";\nthen\n    echo \"Unzip failed please check ..\"\n    exit 1\nelse\n    echo \"Unzip completed successfully\"\nfi\n\npkg_dir=${base_dir}/custom-vision-model-${ENV_CODE}\n\n# The following one's are created on the Synapse workspace to run \n# the pipeline template in Synapse gallery.\nservices=(\"linked-service\" \"spark-job-definition\")\n\nfor item in \"${services[@]}\"\ndo\n    if [[ $item == \"linked-service\" ]]\n    then\n       folder_name=\"linkedService\"\n    else\n       folder_name=\"sparkJobDefinition\"\n    fi\n\n    for file in \"${pkg_dir}/${folder_name}\"/*.json\n    do\n        full_name=\"${file}\"\n        file_name=$(basename -s .json \"${file}\")\n        # Edit the json file format to work with Synapse CLI commands\n        if [[ $folder_name == \"sparkJobDefinition\" ]]\n        then\n            contents=\"$(jq '.properties' \"${full_name}\")\" && echo -E \"${contents}\" > \"${full_name}\"\n            sleep 5\n        fi\n        # Create the linked services and spark job definition on Synapse workspace\n        echo \"Creating ${item} please wait..\"\n        SYNAPSE_WORKSPACE_NAME=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g \"${ENV_CODE}-pipeline-rg\")\n        az synapse \"${item}\" create --workspace-name \"${SYNAPSE_WORKSPACE_NAME}\" \\\n            --name \"${file_name}\" --file @\"${full_name}\"\n    done\ndone\n", "num_lines": 63}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n# parameters\nENV_CODE=${1:-\"aoi\"}\n\nAI_MODEL_INFRA_RESOURCE_NAME=${2:-$AI_MODEL_INFRA_RESOURCE_NAME}\nAI_MODEL_INFRA_TYPE=${3:-${AI_MODEL_INFRA_TYPE:-\"batch-account\"}} # Currently supported values are aks and batch-account\n\nNO_DELETE_DATA_RESOURCE_GROUP=${NO_DELETE_DATA_RESOURCE_GROUP:-\"false\"}\nDATA_RESOURCE_GROUP=\"${ENV_CODE}-data-rg\"\n\nNO_DELETE_MONITORING_RESOURCE_GROUP=${NO_DELETE_MONITORING_RESOURCE_GROUP:-\"false\"}\nMONITORING_RESOURCE_GROUP=\"${ENV_CODE}-monitor-rg\"\n\nNO_DELETE_NETWORKING_RESOURCE_GROUP=${NO_DELETE_NETWORKING_RESOURCE_GROUP:-\"false\"}\nNETWORKING_RESOURCE_GROUP=\"${ENV_CODE}-network-rg\"\n\nNO_DELETE_ORCHESTRATION_RESOURCE_GROUP=${NO_DELETE_ORCHESTRATION_RESOURCE_GROUP:-\"false\"}\nORCHESTRATION_RESOURCE_GROUP=\"${ENV_CODE}-orc-rg\"\n\nNO_DELETE_PIPELINE_RESOURCE_GROUP=${NO_DELETE_PIPELINE_RESOURCE_GROUP:-\"false\"}\nPIPELINE_RESOURCE_GROUP=\"${ENV_CODE}-pipeline-rg\"\n\nif [[ ${NO_DELETE_DATA_RESOURCE_GROUP} != \"true\" ]] && [[ ${NO_DELETE_DATA_RESOURCE_GROUP} == \"false\" ]]; then\n    set -x\n    az group delete --name ${DATA_RESOURCE_GROUP} --no-wait --yes\n    az deployment sub delete --name ${DATA_RESOURCE_GROUP} --no-wait\n    set +x\nfi\n\nif [ \"${NO_DELETE_MONITORING_RESOURCE_GROUP}\" != \"true\" ] && [ \"${NO_DELETE_MONITORING_RESOURCE_GROUP}\" == \"false\" ]; then\n    set -x\n    az group delete --name ${MONITORING_RESOURCE_GROUP} --no-wait --yes\n    az deployment sub delete --name ${MONITORING_RESOURCE_GROUP} --no-wait\n    set +x\nfi\n\nif [ \"${NO_DELETE_NETWORKING_RESOURCE_GROUP}\" != \"true\" ] && [ \"${NO_DELETE_NETWORKING_RESOURCE_GROUP}\" == \"false\" ]; then\n    set -x\n    az group delete --name ${NETWORKING_RESOURCE_GROUP} --no-wait --yes\n    az deployment sub delete --name ${NETWORKING_RESOURCE_GROUP} --no-wait\n    set +x\nfi\n\nif [ \"${NO_DELETE_ORCHESTRATION_RESOURCE_GROUP}\" != \"true\" ] && [ \"${NO_DELETE_ORCHESTRATION_RESOURCE_GROUP}\" == \"false\" ]; then\n    set -x\n    az group delete --name ${ORCHESTRATION_RESOURCE_GROUP} --no-wait --yes\n    az deployment sub delete --name ${ORCHESTRATION_RESOURCE_GROUP} --no-wait\n    set +x\nfi\n\nif [ \"${NO_DELETE_PIPELINE_RESOURCE_GROUP}\" != \"true\" ] && [ \"${NO_DELETE_PIPELINE_RESOURCE_GROUP}\" == \"false\" ]; then\n    set -x\n    az group delete --name ${PIPELINE_RESOURCE_GROUP} --no-wait --yes\n    az deployment sub delete --name ${PIPELINE_RESOURCE_GROUP} --no-wait\n    set +x\nfi\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" == \"batch-account\" ]]; then\n    BATCH_ACCOUNT_POOL_NAME=${BATCH_ACCOUNT_POOL_NAME:-\"${ENV_CODE}-data-cpu-pool\"}\n    NO_BATCH_ACCOUNT_POOL_DELETE=${NO_BATCH_ACCOUNT_POOL_DELETE:-\"false\"}\n    if [[ ! -z \"$AI_MODEL_INFRA_RESOURCE_NAME\" ]] && [ \"${NO_BATCH_ACCOUNT_POOL_DELETE}\" != \"true\" ] && [ \"${NO_BATCH_ACCOUNT_POOL_DELETE}\" == \"false\" ]; then\n        echo \"Getting the batch account details\"\n        BATCH_ACCOUNT_ID=$(az batch account list --query \"[?name == '${AI_MODEL_INFRA_RESOURCE_NAME}'].id\" -o tsv)\n        BATCH_ACCOUNT_RG_NAME=$(az resource show --ids ${BATCH_ACCOUNT_ID} --query resourceGroup -o tsv)\n        AZURE_BATCH_ACCESS_KEY=$(az batch account keys list --name ${AI_MODEL_INFRA_RESOURCE_NAME} --resource-group ${BATCH_ACCOUNT_RG_NAME} | jq \".primary\")\n        AZURE_BATCH_ENDPOINT=$(az batch account show --name ${AI_MODEL_INFRA_RESOURCE_NAME} --resource-group ${BATCH_ACCOUNT_RG_NAME} --query accountEndpoint -o tsv)\n\n        echo \"Cleaning the batch job: ${BATCH_ACCOUNT_POOL_NAME}\"\n        az batch job delete --yes \\\n            --job-id ${BATCH_ACCOUNT_POOL_NAME} \\\n            --account-endpoint ${AZURE_BATCH_ENDPOINT} \\\n            --account-key ${AZURE_BATCH_ACCESS_KEY} \\\n            --account-name ${AI_MODEL_INFRA_RESOURCE_NAME}\n        if [[ $? == 0 ]]; then\n            echo \"Cleanup the batch pool: ${BATCH_ACCOUNT_POOL_NAME}\"\n            az batch pool delete --yes \\\n                --pool-id ${BATCH_ACCOUNT_POOL_NAME} \\\n                --account-endpoint ${AZURE_BATCH_ENDPOINT} \\\n                --account-key ${AZURE_BATCH_ACCESS_KEY} \\\n                --account-name ${AI_MODEL_INFRA_RESOURCE_NAME}\n        fi\n    fi\nfi", "num_lines": 87}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\n\nAI_MODEL_INFRA_TYPE=${2:-${AI_MODEL_INFRA_TYPE:-\"batch-account\"}} # Currently supported values are aks and batch-account\n\nAI_MODEL_INFRA_RESOURCE_NAME=${3:-${AI_MODEL_INFRA_RESOURCE_NAME}}\nAI_MODEL_INFRA_RG_NAME=${4:-$AI_MODEL_INFRA_RG_NAME}\n\nBATCH_ACCOUNT_POOL_NAME=${5:-${BATCH_ACCOUNT_POOL_NAME:-\"${ENV_CODE}-data-cpu-pool\"}}\n\nSYNAPSE_WORKSPACE_RG=${6:-${SYNAPSE_WORKSPACE_RG:-\"${ENV_CODE}-pipeline-rg\"}}\nSYNAPSE_WORKSPACE=${7:-${SYNAPSE_WORKSPACE}}\nSYNAPSE_POOL=${8:-${SYNAPSE_POOL}}\nSYNAPSE_STORAGE_ACCOUNT=${9:-${SYNAPSE_STORAGE_ACCOUNT}}\nDATA_RESOURCE_GROUP=${10:-${DATA_RESOURCE_GROUP:-\"${ENV_CODE}-data-rg\"}}\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" != \"batch-account\" ]] && [[ \"$AI_MODEL_INFRA_TYPE\" != \"aks\" ]]; then\n  echo \"Invalid value for AI_MODEL_INFRA_TYPE! Supported values are 'aks' and 'batch-account'.\"\n  exit 1\nfi\n\necho \"configuration started ...\"\nset -ex\n\n# get synapse workspace and pool\nif [[ -z \"$SYNAPSE_WORKSPACE\" ]]; then\n    SYNAPSE_WORKSPACE=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g ${SYNAPSE_WORKSPACE_RG})\nfi\nif [[ -z \"$SYNAPSE_POOL\" ]]; then\n    SYNAPSE_POOL=$(az synapse spark pool list --workspace-name ${SYNAPSE_WORKSPACE} --resource-group ${SYNAPSE_WORKSPACE_RG} --query \"[?tags.poolId && tags.poolId == 'default'].name\" -o tsv)\nfi\nif [[ -n $SYNAPSE_WORKSPACE ]] && [[ -n $SYNAPSE_WORKSPACE_RG ]] && [[ -n $SYNAPSE_POOL ]]; then\n    # upload synapse pool \n    az synapse spark pool update --name ${SYNAPSE_POOL} --workspace-name ${SYNAPSE_WORKSPACE} --resource-group ${SYNAPSE_WORKSPACE_RG} --library-requirements \"${PRJ_ROOT}/deploy/scripts/environment.yml\"\nfi\n\nif [[ -z \"$SYNAPSE_STORAGE_ACCOUNT\" ]]; then\n    SYNAPSE_STORAGE_ACCOUNT=$(az storage account list --query \"[?tags.store && tags.store == 'synapse'].name\" -o tsv -g ${SYNAPSE_WORKSPACE_RG})\nfi\n\nif [[ -n $SYNAPSE_STORAGE_ACCOUNT ]]; then\n    # create a container to upload the spark job python files\n    az storage container create --name \"spark-jobs\" --account-name ${SYNAPSE_STORAGE_ACCOUNT}\n    # uploads the spark job python files\n    az storage blob upload-batch --destination \"spark-jobs\" --account-name ${SYNAPSE_STORAGE_ACCOUNT} --source \"${PRJ_ROOT}/src/transforms/spark-jobs\" --overwrite\nfi\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" == \"batch-account\" ]]; then\n    echo \"Selected AI model processing infra-type: Batch-Account!!!\"\n\n    BATCH_ACCOUNT_NAME=$AI_MODEL_INFRA_RESOURCE_NAME\n    BATCH_ACCOUNT_RG_NAME=$AI_MODEL_INFRA_RG_NAME\n\n    # get batch account\n    if [[ -z \"$BATCH_ACCOUNT_NAME\" ]] && [[ -z \"$BATCH_ACCOUNT_RG_NAME\" ]]; then\n        BATCH_ACCOUNT_RG_NAME=\"${ENV_CODE}-orc-rg\"\n    fi\n    if [[ -z \"$BATCH_ACCOUNT_NAME\" ]]; then\n        BATCH_ACCOUNT_NAME=$(az batch account list --query \"[?tags.type && tags.type == 'batch'].name\" -o tsv -g ${BATCH_ACCOUNT_RG_NAME})\n    fi\n    if [[ -z \"$BATCH_ACCOUNT_RG_NAME\" ]]; then\n        BATCH_ACCOUNT_ID=$(az batch account list --query \"[?name == '${BATCH_ACCOUNT_NAME}'].id\" -o tsv)\n        BATCH_ACCOUNT_RG_NAME=$(az resource show --ids ${BATCH_ACCOUNT_ID} --query resourceGroup -o tsv)\n    fi\n    BATCH_ACCOUNT_KEY=$(az batch account keys list --name ${BATCH_ACCOUNT_NAME} --resource-group ${BATCH_ACCOUNT_RG_NAME} | jq \".primary\")\n    if [[ -n $BATCH_ACCOUNT_NAME ]] && [[ -n $BATCH_ACCOUNT_KEY ]]\n    then\n        az batch account login --name ${BATCH_ACCOUNT_NAME} --resource-group ${BATCH_ACCOUNT_RG_NAME}\n        # create batch job for custom vision model\n        az batch job create --id ${BATCH_ACCOUNT_POOL_NAME} --pool-id ${BATCH_ACCOUNT_POOL_NAME} --account-name ${BATCH_ACCOUNT_NAME} --account-key ${BATCH_ACCOUNT_KEY}\n    fi\nelif [[ \"$AI_MODEL_INFRA_TYPE\" == \"aks\" ]]; then\n    echo \"Selected AI model processing infra-type: AKS!!!\"\n    AKS_NAMESPACE=vision\n    PV_SUFFIX=fileshare\n    PV_NAME=\"${ENV_CODE}-${AKS_NAMESPACE}-${PV_SUFFIX}\"\n\n    RAW_STORAGE_ACCT=$(az storage account list --query \"[?tags.store && tags.store == 'raw'].name\" -o tsv -g $DATA_RESOURCE_GROUP)\n    RAW_STORAGE_KEY=$(az storage account keys list --resource-group $DATA_RESOURCE_GROUP --account-name $RAW_STORAGE_ACCT --query \"[0].value\" -o tsv)\n    FILE_SHARE_NAME=$(az storage share list --account-key $RAW_STORAGE_KEY --account-name $RAW_STORAGE_ACCT --query \"[].name\" -o tsv)\n\n    AKS_CLUSTER_NAME=$(az aks list -g ${ENV_CODE}-orc-rg --query \"[?tags.type && tags.type == 'k8s'].name\" -otsv)\n    counter=0\n    while [[ ${AKS_CLUSTER_NAME} == '' ]];\n    do\n        if [[ $counter -gt 4 ]]; then\n            echo \"Failed to get AKS cluster name\"\n            break\n        fi\n        sleep 60\n        AKS_CLUSTER_NAME=$(az aks list -g ${ENV_CODE}-orc-rg --query \"[?tags.type && tags.type == 'k8s'].name\" -otsv)\n        counter=$((counter+1))\n    done\n    # force to provision aks-command namespace\n    az aks command invoke -g ${ENV_CODE}-orc-rg -n ${AKS_CLUSTER_NAME} -c \"kubectl get ns\"\n    az aks get-credentials --resource-group ${ENV_CODE}-orc-rg --name ${AKS_CLUSTER_NAME} --context ${AKS_CLUSTER_NAME} --overwrite-existing\n    kubectl config set-context ${AKS_CLUSTER_NAME}\n\n    # create vison namespace\n    AKS_NAMESPACE=$AKS_NAMESPACE \\\n      envsubst < \"$PRJ_ROOT/deploy/kube_yaml/namespace.yaml\" | kubectl apply -f -\n    \n    # create storage secret\n    AKS_NAMESPACE=$AKS_NAMESPACE \\\n    RAW_STORAGE_ACCT=$RAW_STORAGE_ACCT \\\n    RAW_STORAGE_KEY=$RAW_STORAGE_KEY \\\n      envsubst < \"$PRJ_ROOT/deploy/kube_yaml/storage_secret.yaml\" | kubectl -n $AKS_NAMESPACE apply -f -\n    \n    # create pv\n    AKS_NAMESPACE=$AKS_NAMESPACE \\\n    PV_NAME=$PV_NAME \\\n    DATA_RESOURCE_GROUP=$DATA_RESOURCE_GROUP \\\n    FILE_SHARE_NAME=$FILE_SHARE_NAME \\\n      envsubst < \"$PRJ_ROOT/deploy/kube_yaml/pv.yaml\" | kubectl -n $AKS_NAMESPACE apply -f -\n    \n    # create pvc\n    AKS_NAMESPACE=$AKS_NAMESPACE \\\n    PV_NAME=$PV_NAME \\\n      envsubst < \"$PRJ_ROOT/deploy/kube_yaml/pvc.yaml\" | kubectl -n $AKS_NAMESPACE apply -f -\nfi # end of \"$AI_MODEL_INFRA_TYPE\" == \"aks\"\n\necho \"configuration completed!\"\n", "num_lines": 128}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n# This script automates the following activities & should be run prior to\n# executing the pipeline template from Synapse gallery.\n#       * Create storage container under \"<envcode>-data-rg\" resource group\n#       * Copy the sample TIF into the newly created storage container\n#       * Copy the configurations required for Object Detection\n\nset -e\n\nENV_CODE=${1:-${ENV_CODE}}\n\nif [[ -z \"$ENV_CODE\" ]]\nthen\n    echo \"Missing Environment Code\"\n    exit 1\nfi\n\n# Default name for the container\ncontainer_name=\"${ENV_CODE}-test-container\"\n\n# Retrieve the respective values for the environment variables\nAZURE_STORAGE_ACCOUNT=$(az storage account list --resource-group \"${ENV_CODE}-data-rg\" --query [0].name -o tsv)\nAZURE_STORAGE_KEY=$(az storage account keys list --account-name \"$AZURE_STORAGE_ACCOUNT\" --query [0].value -o tsv)\nAZURE_STORAGE_AUTH_MODE=key\n\nexport AZURE_STORAGE_ACCOUNT\nexport AZURE_STORAGE_KEY\nexport AZURE_STORAGE_AUTH_MODE\n\n# Declare an associated array for dictionaries\ndeclare -A array\n\nkey1='sample_4326.tif'\nvalue1='https://naipeuwest.blob.core.windows.net/naip/v002/ca/2020/ca_060cm_2020/32117/m_3211716_se_11_060_20200428.tif'\n\nkey2='custom_vision_object_detection.json'\nvalue2='https://raw.githubusercontent.com/Azure/Azure-Orbital-Analytics-Samples/main/src/aimodels/custom_vision_object_detection_offline/specs/custom_vision_object_detection.json'\n\nkey3='config.json'\nvalue3='https://raw.githubusercontent.com/Azure/Azure-Orbital-Analytics-Samples/main/src/aimodels/custom_vision_object_detection_offline/config/config.json'\n\narray[\"raw/$key1\"]=\"$value1\"\narray[\"config/$key2\"]=\"$value2\"\narray[\"config/$key3\"]=\"$value3\"\n\necho \"Creating storage container $container_name..\"\nif ! az storage container create --name \"$container_name\" --fail-on-exist;\nthen\n    echo \"Failed during storage container creation\"\n    exit 1\nelse\n    echo \"Container $container_name created successfully\"\nfi\n\nset -x\n\nfor key in \"${!array[@]}\"; do\n    echo \"Copying $key from source\"\n    az storage blob copy start --destination-blob $key --destination-container \"$container_name\" --source-uri \"${array[$key]}\"\ndone\n", "num_lines": 65}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\n\nset -ex\n\nif [[ -z \"$1\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$2\" ]]\n  then\n    echo \"Location value not supplied\"\n    exit 1\nfi\n\n# Setup parameters\nENV_CODE=${1:-${ENV_CODE}}\nLOCATION=${2:-${LOCATION}}\nENV_TAG=${3:-${ENV_TAG:-\"synapse-${ENV_CODE}\"}}\nDEPLOYMENT_NAME=${4:-${DEPLOYMENT_NAME:-\"${ENV_TAG}-deploy\"}}\nDEPLOY_AI_MODEL_INFRA=${5:-${DEPLOY_AI_MODEL_INFRA:-\"true\"}}\nAI_MODEL_INFRA_TYPE=${6:-${AI_MODEL_INFRA_TYPE:-\"batch-account\"}} # Currently supported values are aks and batch-account\nDEPLOY_PGSQL=${7:-${DEPLOY_PGSQL:-\"true\"}}\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" != \"batch-account\" ]] && [[ \"$AI_MODEL_INFRA_TYPE\" != \"aks\" ]]; then\n  echo \"Invalid value for AI_MODEL_INFRA_TYPE! Supported values are 'aks' and 'batch-account'.\"\n  exit 1\nfi\n\nDEPLOYMENT_SCRIPT=\"az deployment sub create -l $LOCATION -n $DEPLOYMENT_NAME \\\n    -f ${PRJ_ROOT}/deploy/infra/main.bicep \\\n    -p \\\n    location=$LOCATION \\\n    environmentCode=$ENV_CODE \\\n    environment=$ENV_TAG \\\n    deployPgSQL=$DEPLOY_PGSQL \\\n    postgresAdminLoginPass=$POSTGRES_ADMIN_LOGIN_PASS \\\n    aiModelInfraType=$AI_MODEL_INFRA_TYPE \\\n    deployAiModelInfra=$DEPLOY_AI_MODEL_INFRA\"\n$DEPLOYMENT_SCRIPT\nset +x\n\n", "num_lines": 49}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\n\nENV_CODE=${1:-$ENV_CODE}\nPIPELINE_NAME=${2:-${PIPELINE_NAME:-\"custom-vision-model\"}}\n\nAI_MODEL_INFRA_TYPE=${3:-${AI_MODEL_INFRA_TYPE:-\"batch-account\"}} # Currently supported values are aks and batch-account\n\nAI_MODEL_INFRA_RESOURCE_NAME=${4:-$AI_MODEL_INFRA_RESOURCE_NAME}\nAI_MODEL_INFRA_RG_NAME=${5:-$AI_MODEL_INFRA_RG_NAME}\nAI_MODEL_INFRA_STORAGE_ACCOUNT_NAME=${6:-$AI_MODEL_INFRA_STORAGE_ACCOUNT_NAME}\n\nKEY_VAULT_NAME=${7:-$KEY_VAULT_NAME}\n\nRAW_STORAGE_ACCOUNT_RG=${8:-${RAW_STORAGE_ACCOUNT_RG:-\"${ENV_CODE}-data-rg\"}}\nRAW_STORAGE_ACCOUNT_NAME=${9:-$RAW_STORAGE_ACCOUNT_NAME}\n\nSYNAPSE_WORKSPACE_RG=${10:-${SYNAPSE_WORKSPACE_RG:-\"${ENV_CODE}-pipeline-rg\"}}\nSYNAPSE_WORKSPACE_NAME=${11:-$SYNAPSE_WORKSPACE_NAME}\nSYNAPSE_STORAGE_ACCOUNT_NAME=${12:-$SYNAPSE_STORAGE_ACCOUNT_NAME}\nSYNAPSE_POOL=${13:-$SYNAPSE_POOL}\n\nDEPLOY_PGSQL=${14:-${DEPLOY_PGSQL:-\"true\"}}\n\nMODE=\"$AI_MODEL_INFRA_TYPE$([[ $DEPLOY_PGSQL = \"false\" ]] && echo \",no-postgres\" || echo '')\"\n\nset -ex\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" != \"batch-account\" ]] && [[ \"$AI_MODEL_INFRA_TYPE\" != \"aks\" ]]; then\n  echo \"Invalid value for AI_MODEL_INFRA_TYPE! Supported values are 'aks' and 'batch-account'.\"\n  exit 1\nfi\n\nif [[ -z \"$RAW_STORAGE_ACCOUNT_NAME\" ]]; then\n    RAW_STORAGE_ACCOUNT_NAME=$(az storage account list --query \"[?tags.store && tags.store == 'raw'].name\" -o tsv -g $RAW_STORAGE_ACCOUNT_RG)\nfi\n\nif [[ -z \"$SYNAPSE_STORAGE_ACCOUNT_NAME\" ]]; then\n    SYNAPSE_STORAGE_ACCOUNT_NAME=$(az storage account list --query \"[?tags.store && tags.store == 'synapse'].name\" -o tsv -g $SYNAPSE_WORKSPACE_RG)\nfi\n\nif [[ -z \"$KEY_VAULT_NAME\" ]]; then\n    KEY_VAULT_NAME=$(az keyvault list --query \"[?tags.usage && tags.usage == 'linkedService'].name\" -o tsv -g $SYNAPSE_WORKSPACE_RG)\nfi\n\nif [[ -z \"$SYNAPSE_WORKSPACE_NAME\" ]]; then\n    SYNAPSE_WORKSPACE_NAME=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g $SYNAPSE_WORKSPACE_RG)\n    SYNAPSE_WORKSPACE_ID=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].id\" -o tsv -g $SYNAPSE_WORKSPACE_RG)\nelse\n    SYNAPSE_WORKSPACE_ID=$(az synapse workspace list --query \"[?name == '${BATCH_ACCOUNT_NAME}'].id\" -o tsv -g $SYNAPSE_WORKSPACE_RG)\nfi\n\nif [[ -z \"$SYNAPSE_POOL\" ]]; then\n    SYNAPSE_POOL=$(az synapse spark pool list --workspace-name $SYNAPSE_WORKSPACE_NAME --resource-group $SYNAPSE_WORKSPACE_RG --query \"[?tags.poolId && tags.poolId == 'default'].name\" -o tsv)\nfi\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" == \"batch-account\" ]]; then\n    echo \"Selected AI model processing infra-type: Batch-Account!!!\"\n\n    BATCH_ACCOUNT_NAME=$AI_MODEL_INFRA_RESOURCE_NAME\n    BATCH_ACCOUNT_RG_NAME=$AI_MODEL_INFRA_RG_NAME\n    BATCH_STORAGE_ACCOUNT_NAME=$AI_MODEL_INFRA_STORAGE_ACCOUNT_NAME\n\n    if [[ -z \"$BATCH_ACCOUNT_NAME\" ]] && [[ -z \"$BATCH_ACCOUNT_RG_NAME\" ]]; then\n        BATCH_ACCOUNT_RG_NAME=\"${ENV_CODE}-orc-rg\"\n    fi\n    if [[ -z \"$BATCH_ACCOUNT_NAME\" ]]; then\n        BATCH_ACCOUNT_NAME=$(az batch account list --query \"[?tags.type && tags.type == 'batch'].name\" -o tsv -g $BATCH_ACCOUNT_RG_NAME)\n    fi\n    if [[ -z \"$BATCH_ACCOUNT_RG_NAME\" ]]; then\n        BATCH_ACCOUNT_ID=$(az batch account list --query \"[?name == '${BATCH_ACCOUNT_NAME}'].id\" -o tsv)\n        BATCH_ACCOUNT_RG_NAME=$(az resource show --ids ${BATCH_ACCOUNT_ID} --query resourceGroup -o tsv)\n    fi\n    if [[ -z \"$BATCH_STORAGE_ACCOUNT_NAME\" ]]; then\n        BATCH_STORAGE_ACCOUNT_NAME=$(az storage account list --query \"[?tags.store && tags.store == 'batch'].name\" -o tsv -g $BATCH_ACCOUNT_RG_NAME)\n        if [[ -z \"$BATCH_STORAGE_ACCOUNT_NAME\" ]]; then\n            BATCH_STORAGE_ACCOUNT_NAME=$(az storage account list --resource-group $BATCH_ACCOUNT_RG_NAME --query [0].name -o tsv)\n        fi\n    fi\n    if [[ -z \"$BATCH_ACCOUNT_LOCATION\" ]]; then\n        BATCH_ACCOUNT_LOCATION=$(az batch account list --query \"[?name == '${BATCH_ACCOUNT_NAME}'].location\" -o tsv)\n    fi\n\n    echo 'Retrieved resource from Azure and ready to package'\n    PACKAGING_SCRIPT=\"python3 ${PRJ_ROOT}/deploy/scripts/package.py \\\n        --raw_storage_account_name $RAW_STORAGE_ACCOUNT_NAME \\\n        --synapse_storage_account_name $SYNAPSE_STORAGE_ACCOUNT_NAME \\\n        --modes $MODE \\\n        --batch_storage_account_name $BATCH_STORAGE_ACCOUNT_NAME \\\n        --batch_account $BATCH_ACCOUNT_NAME \\\n        --batch_pool_name ${ENV_CODE}-data-cpu-pool \\\n        --linked_key_vault $KEY_VAULT_NAME \\\n        --synapse_pool_name $SYNAPSE_POOL \\\n        --location $BATCH_ACCOUNT_LOCATION \\\n        --pipeline_name $PIPELINE_NAME \\\n        --synapse_workspace $SYNAPSE_WORKSPACE_NAME \\\n        --synapse_workspace_id $SYNAPSE_WORKSPACE_ID\"\n\nelif [[ \"$AI_MODEL_INFRA_TYPE\" == \"aks\" ]]; then\n    echo \"Selected AI model processing infra-type: AKS!!!\"\n    AKS_ID=$(az aks list -g ${ENV_CODE}-orc-rg --query \"[?tags.type && tags.type == 'k8s'].id\" -otsv)\n    counter=0\n    while [[ ${AKS_ID} == '' ]];\n    do\n        if [[ $counter -gt 4 ]]; then\n            echo \"Failed to get AKS ID\"\n            break\n        fi\n        sleep 60\n        AKS_ID=$(az aks list -g ${ENV_CODE}-orc-rg --query \"[?tags.type && tags.type == 'k8s'].id\" -otsv)\n        counter=$((counter+1))\n    done\n\n    PERSISTENT_VOLUME_CLAIM=\"${ENV_CODE}-vision-fileshare\"\n    AKS_MANAGEMENT_REST_URL=\"https://management.azure.com${AKS_ID}/runCommand?api-version=2022-02-01\"\n    BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_HOST=$(az functionapp list -g ${ENV_CODE}-orc-rg \\\n        --query \"[?tags.type && tags.type == 'functionapp'].hostNames[0]\" | jq -r '.[0]')\n    counter=0\n    while [[ ${BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_HOST} == '' ]];\n    do\n        if [[ $counter -gt 4 ]]; then\n            echo \"Failed to get functionapp host\"\n            break\n        fi\n        sleep 60\n        BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_HOST=$(az functionapp list -g ${ENV_CODE}-orc-rg \\\n        --query \"[?tags.type && tags.type == 'functionapp'].hostNames[0]\" | jq -r '.[0]')\n        counter=$((counter+1))\n    done\n    BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_URL=\"https://${BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_HOST}\"\n    PACKAGING_SCRIPT=\"python3 ${PRJ_ROOT}/deploy/scripts/package.py \\\n        --raw_storage_account_name $RAW_STORAGE_ACCOUNT_NAME \\\n        --synapse_storage_account_name $SYNAPSE_STORAGE_ACCOUNT_NAME \\\n        --modes $MODE \\\n        --persistent_volume_claim $PERSISTENT_VOLUME_CLAIM \\\n        --aks_management_rest_url $AKS_MANAGEMENT_REST_URL \\\n        --base64encodedzipcontent_functionapp_url $BASE64ENCODEDZIPCONTENT_FUNCTIONAPP_URL \\\n        --linked_key_vault $KEY_VAULT_NAME \\\n        --synapse_pool_name $SYNAPSE_POOL \\\n        --pipeline_name $PIPELINE_NAME \\\n        --synapse_workspace $SYNAPSE_WORKSPACE_NAME \\\n        --synapse_workspace_id $SYNAPSE_WORKSPACE_ID\"\nfi\n\nif [[ $DEPLOY_PGSQL == \"true\" ]]; then\n    DB_SERVER_NAME=$(az postgres server list --resource-group $RAW_STORAGE_ACCOUNT_RG --query '[].fullyQualifiedDomainName' -o tsv)\n    echo $DB_SERVER_NAME\n    DB_NAME=$(az postgres server list --resource-group $RAW_STORAGE_ACCOUNT_RG --query '[].name' -o tsv)\n    echo $DB_NAME\n    DB_USERNAME=$(az postgres server list --resource-group $RAW_STORAGE_ACCOUNT_RG --query '[].administratorLogin' -o tsv)@$DB_NAME\n    echo $DB_USERNAME\n\n    if [[ -n $DB_USERNAME ]] && [[ -n $DB_SERVER_NAME ]]; then\n        PACKAGING_SCRIPT=$(echo $PACKAGING_SCRIPT \\\n            --pg_db_username $DB_USERNAME \\\n            --pg_db_server_name $DB_SERVER_NAME)\n    fi\nfi\necho $PACKAGING_SCRIPT\necho 'Starting packaging script ...'\n$PACKAGING_SCRIPT\necho 'Packaging script completed'\n", "num_lines": 167}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nENV_CODE=${1:-${ENV_CODE}}\nLOCATION=${2:-${LOCATION}}\nENV_TAG=${3:-${ENV_TAG:-\"synapse-$ENV_CODE\"}}\nPIPELINE_NAME=${4:-${PIPELINE_NAME:-\"custom-vision-model\"}}\nAI_MODEL_INFRA_TYPE=${5:-${AI_MODEL_INFRA_TYPE:-\"batch-account\"}} # Currently supported values are aks and batch-account\nPRE_PROVISIONED_AI_MODEL_INFRA_NAME=${6:-$PRE_PROVISIONED_AI_MODEL_INFRA_NAME}\nDEPLOY_PGSQL=${7:-${DEPLOY_PGSQL:-\"true\"}}\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\n\nset -ex\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$LOCATION\" ]]\n  then\n    echo \"Location value not supplied\"\n    exit 1\nfi\n\nif [[ \"$AI_MODEL_INFRA_TYPE\" != \"batch-account\" ]] && [[ \"$AI_MODEL_INFRA_TYPE\" != \"aks\" ]]; then\n  echo \"Invalid value for AI_MODEL_INFRA_TYPE! Supported values are 'aks' and 'batch-account'.\"\n  exit 1\nfi\n\nif [[ -z \"$PRE_PROVISIONED_AI_MODEL_INFRA_NAME\" ]]\n  then\n    DEPLOY_AI_MODEL_INFRA=\"true\"\n  else\n    DEPLOY_AI_MODEL_INFRA=\"false\"\nfi\n\necho \"Performing bicep template deployment\"\nif [[ -z \"$ENV_TAG\" ]]\n  then\n    DEPLOY_PGSQL=${DEPLOY_PGSQL} \\\n    DEPLOY_AI_MODEL_INFRA=${DEPLOY_AI_MODEL_INFRA} \\\n    AI_MODEL_INFRA_TYPE=${AI_MODEL_INFRA_TYPE} \\\n      ${PRJ_ROOT}/deploy/scripts/install.sh \"$ENV_CODE\" \"$LOCATION\" \n  else\n    DEPLOY_PGSQL=${DEPLOY_PGSQL} \\\n    DEPLOY_AI_MODEL_INFRA=${DEPLOY_AI_MODEL_INFRA} \\\n    AI_MODEL_INFRA_TYPE=${AI_MODEL_INFRA_TYPE} \\\n      ${PRJ_ROOT}/deploy/scripts/install.sh \"$ENV_CODE\" \"$LOCATION\" \"$ENV_TAG\"\nfi\n\nif [[ \"${DEPLOY_AI_MODEL_INFRA}\" == \"false\" ]] && [[ \"${AI_MODEL_INFRA_TYPE}\" == \"batch-account\" ]]; then\n  echo \"Setting up the batch account!!!\"\n  ${PRJ_ROOT}/test/use-pre-provisioned-batch-account.sh \\\n    \"$ENV_CODE\" \\\n    \"$PRE_PROVISIONED_AI_MODEL_INFRA_NAME\" \\\n    \"$PIPELINE_NAME\"\nfi\n\necho \"Performing configuration\"\n${PRJ_ROOT}/deploy/scripts/configure.sh \\\n  \"$ENV_CODE\" \\\n  \"$AI_MODEL_INFRA_TYPE\" \\\n  \"$PRE_PROVISIONED_AI_MODEL_INFRA_NAME\" \n\nif [[ -z \"$PIPELINE_NAME\" ]]\n  then\n    echo \"Skipping pipeline packaging\"\n  else\n    echo \"Performing pipeline packaging\"\n    DEPLOY_PGSQL=${DEPLOY_PGSQL} \\\n      ${PRJ_ROOT}/deploy/scripts/package.sh \\\n      \"$ENV_CODE\" \\\n      \"$PIPELINE_NAME\" \\\n      \"$AI_MODEL_INFRA_TYPE\" \\\n      \"$PRE_PROVISIONED_AI_MODEL_INFRA_NAME\"\nfi\n", "num_lines": 82}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ndocker build -t custom_vision_offline .", "num_lines": 2}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nbase=$(pwd)\n\ndocker run -u 1000:1000 \\\n           -v \"$base/examples/in/:/data/in\" \\\n           -v \"$base/examples/out/:/data/out\" \\\n           -v \"$base/config.mine.json:/data/config.json\" \\\n           custom_vision_offline", "num_lines": 9}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/..; pwd)\"\n\nENV_CODE=${1:-${ENV_CODE}}\nPIPELINE_RUN_ID=${2:-${PIPELINE_RUN_ID}}\nSYNAPSE_WORKSPACE_NAME=${3:-${SYNAPSE_WORKSPACE_NAME}}\nSLEEP_TIME_BETWEEN_CHECK_STATUS=${4:-${SLEEP_TIME_BETWEEN_CHECK_STATUS:-300}}\nSYNAPSE_WORKSPACE_RG=${5:-${SYNAPSE_WORKSPACE_RG:-\"${ENV_CODE}-pipeline-rg\"}}\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$SYNAPSE_WORKSPACE_NAME\" ]]; then\n    SYNAPSE_WORKSPACE_NAME=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g ${SYNAPSE_WORKSPACE_RG})\nfi\nif [[ -z \"$SLEEP_TIME_BETWEEN_CHECK_STATUS\" ]]; then\n    SLEEP_TIME_BETWEEN_CHECK_STATUS=60\nfi\n\nset -ex\n\nPIPELINE_RUN_STATUS=$(az synapse pipeline-run show --workspace-name ${SYNAPSE_WORKSPACE_NAME} --run-id ${PIPELINE_RUN_ID} --query status --output tsv)\nwhile [[ \"$PIPELINE_RUN_STATUS\" != \"Succeeded\" ]] && [[ \"$PIPELINE_RUN_STATUS\" != \"Failed\" ]]\ndo\n    echo \"Pipeline status: ${PIPELINE_RUN_STATUS}\"\n    echo \"Waiting for ${SLEEP_TIME_BETWEEN_CHECK_STATUS} seconds ....\"\n    sleep ${SLEEP_TIME_BETWEEN_CHECK_STATUS}\n    PIPELINE_RUN_STATUS=$(az synapse pipeline-run show --workspace-name ${SYNAPSE_WORKSPACE_NAME} --run-id ${PIPELINE_RUN_ID} --query status --output tsv)\ndone\n\necho \"Pipeline finished with status: ${PIPELINE_RUN_STATUS}\"\n\nif [[ \"$PIPELINE_RUN_STATUS\" == \"Succeeded\" ]]; then\n    exit 0\nfi\nexit 1", "num_lines": 43}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/..; pwd)\"\n\nENV_CODE=${1:-${ENV_CODE}}\n\nBATCH_ACCOUNT_NAME=${2:-${BATCH_ACCOUNT_NAME:-\"pipelinecibatch\"}}\nPIPELINE_NAME=${3:-${PIPELINE_NAME:-\"custom-vision-model\"}}\n\nDESTINATION_CONTAINER_NAME=${4:-${DESTINATION_CONTAINER_NAME:-\"${PIPELINE_NAME}-${ENV_CODE}\"}}\nDESTINATION_STORAGE_ACCOUNT_NAME=${5:-${DESTINATION_STORAGE_ACCOUNT_NAME}}\nDESTINATION_STORAGE_ACCOUNT_RG_NAME=${6:-${DESTINATION_STORAGE_ACCOUNT_RG_NAME:-\"${ENV_CODE}-data-rg\"}}\nSOURCE_CONTAINER_NAME=${7:-${SOURCE_CONTAINER_NAME:-${PIPELINE_NAME}}}\nSOURCE_STORAGE_ACCOUNT_NAME=${8:-${SOURCE_STORAGE_ACCOUNT_NAME:-\"pipelineciresources\"}}\nSOURCE_STORAGE_ACCOUNT_RG_NAME=${9:-${SOURCE_STORAGE_ACCOUNT_RG_NAME:-\"ci-resources\"}}\nSYNAPSE_RESOURCE_GROUP_NAME=${10:-${SYNAPSE_RESOURCE_GROUP_NAME:-\"${ENV_CODE}-pipeline-rg\"}}\nSYNAPSE_WORKSPACE_NAME=${11:-${SYNAPSE_WORKSPACE_NAME}}\nBATCH_JOB_NAME=${12:-${BATCH_JOB_NAME:-\"${ENV_CODE}-data-cpu-pool\"}}\nAOI_PARAMETER_VALUE=${13:-${AOI_PARAMETER_VALUE:-\"-117.063550 32.749467 -116.999386 32.812946\"}}\nPIPELINE_FILE_NAME=${14:-${PIPELINE_FILE_NAME:-\"E2E Custom Vision Model Flow.json\"}}\nPARAMETER_FILE_PATH=${15:-${PARAMETER_FILE_PATH:-\"${PRJ_ROOT}/test/${PIPELINE_NAME}-parameters.json\"}}\nSUBSTITUTE_PARAMS=${16:-${SUBSTITUTE_PARAMS:-\"true\"}}\n\nset -ex\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$DESTINATION_STORAGE_ACCOUNT_NAME\" ]]; then\n    DESTINATION_STORAGE_ACCOUNT_NAME=$(az storage account list --resource-group $DESTINATION_STORAGE_ACCOUNT_RG_NAME --query [0].name -o tsv)\nfi\nif [[ -z \"$STORAGE_ACCOUNT_KEY\" ]]; then\n    STORAGE_ACCOUNT_KEY=$(az storage account keys list --resource-group ${DESTINATION_STORAGE_ACCOUNT_RG_NAME} --account-name ${DESTINATION_STORAGE_ACCOUNT_NAME} --query \"[0].value\" --output tsv)\nfi\nif [[ -z \"$SOURCE_STORAGE_ACCOUNT_KEY\" ]]; then\n    SOURCE_STORAGE_ACCOUNT_KEY=$(az storage account keys list --resource-group ${SOURCE_STORAGE_ACCOUNT_RG_NAME} --account-name ${SOURCE_STORAGE_ACCOUNT_NAME} --query \"[0].value\" --output tsv)\nfi\n\nif [[ -z \"$SYNAPSE_WORKSPACE_NAME\" ]]; then\n    SYNAPSE_WORKSPACE_NAME=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g ${SYNAPSE_RESOURCE_GROUP_NAME})\nfi\n# Create container in destination storage account\necho \"Creating container ${DESTINATION_CONTAINER_NAME} on storage account ${DESTINATION_STORAGE_ACCOUNT_NAME}\"\naz storage container create --name ${DESTINATION_CONTAINER_NAME} --account-name ${DESTINATION_STORAGE_ACCOUNT_NAME} --account-key ${STORAGE_ACCOUNT_KEY}\n\n# Upload test data to destination storage account container\necho \"Copying resources to storage container ${DESTINATION_CONTAINER_NAME} on storage account ${DESTINATION_STORAGE_ACCOUNT_NAME}\"\naz storage blob copy start \\\n  --destination-blob raw/sample_4326.tif \\\n  --destination-container ${DESTINATION_CONTAINER_NAME} \\\n  --account-name ${DESTINATION_STORAGE_ACCOUNT_NAME} \\\n  --account-key ${STORAGE_ACCOUNT_KEY} \\\n  --source-container ${SOURCE_CONTAINER_NAME} \\\n  --source-account-name ${SOURCE_STORAGE_ACCOUNT_NAME} \\\n  --source-account-key ${SOURCE_STORAGE_ACCOUNT_KEY} \\\n  --source-blob raw/sample_4326.tif\n\naz storage blob copy start \\\n  --destination-blob config/config.json \\\n  --destination-container ${DESTINATION_CONTAINER_NAME} \\\n  --account-name ${DESTINATION_STORAGE_ACCOUNT_NAME} \\\n  --account-key ${STORAGE_ACCOUNT_KEY} \\\n  --source-container ${SOURCE_CONTAINER_NAME} \\\n  --source-account-name ${SOURCE_STORAGE_ACCOUNT_NAME} \\\n  --source-account-key ${SOURCE_STORAGE_ACCOUNT_KEY} \\\n  --source-blob config/config.json\n\naz storage blob copy start \\\n  --destination-blob config/custom_vision_object_detection.json \\\n  --destination-container ${DESTINATION_CONTAINER_NAME} \\\n  --account-name ${DESTINATION_STORAGE_ACCOUNT_NAME} \\\n  --account-key ${STORAGE_ACCOUNT_KEY} \\\n  --source-container ${SOURCE_CONTAINER_NAME} \\\n  --source-account-name ${SOURCE_STORAGE_ACCOUNT_NAME} \\\n  --source-account-key ${SOURCE_STORAGE_ACCOUNT_KEY} \\\n  --source-blob config/custom_vision_object_detection.json\n\n# Install Pipeline\necho \"Preparing commands to install pipeline components\"\nmkdir /tmp/packaged-pipeline\nunzip ${PIPELINE_NAME}.zip -d /tmp/packaged-pipeline/\necho \"#!/usr/bin/env bash\" > /tmp/install-pipeline.sh\necho \"set -ex\" >> /tmp/install-pipeline.sh\nchmod +x /tmp/install-pipeline.sh\npython3 ${PRJ_ROOT}/test/create-pipeline-install-commands.py \\\n    --file_name \"/tmp/packaged-pipeline/pipeline/${PIPELINE_FILE_NAME}\" \\\n    --resource_group_name ${SYNAPSE_RESOURCE_GROUP_NAME} \\\n    --workspace_name ${SYNAPSE_WORKSPACE_NAME} >> /tmp/install-pipeline.sh\n\necho \"Installing pipeline components\"\n/tmp/install-pipeline.sh\n\n# Create pipeline parameter file\nif [[ \"${SUBSTITUTE_PARAMS,,}\" == \"true\" ]]; then\n    echo \"Generating parameter file for pipeline execution\"\n    BATCH_ACCOUNT_ID=$(az batch account list --query \"[?name == '${BATCH_ACCOUNT_NAME}'].id\" -o tsv)\n    BATCH_ACCOUNT_RG_NAME=$(az resource show --ids ${BATCH_ACCOUNT_ID} --query resourceGroup -o tsv)\n    BATCH_ACCOUNT_LOCATION=$(az batch account show  --name ${BATCH_ACCOUNT_NAME} --resource-group ${BATCH_ACCOUNT_RG_NAME} --query \"location\" --output tsv)\n\n    export RAW_DATA_STORAGE_ACCOUNT_CONTAINER_NAME=${DESTINATION_CONTAINER_NAME}\n    export RAW_DATA_STORAGE_ACCOUNT_NAME=${DESTINATION_STORAGE_ACCOUNT_NAME}\n    export RAW_DATA_STORAGE_ACCOUNT_KEY=${DESTINATION_STORAGE_ACCOUNT_RG_NAME}\n    export BATCH_ACCOUNT_NAME\n    export BATCH_JOB_NAME\n    export BATCH_ACCOUNT_LOCATION\n    export AOI=${AOI_PARAMETER_VALUE}\n\n    envsubst < ${PARAMETER_FILE_PATH} > /tmp/parameters.json\n    export PARAMETER_FILE_PATH=\"/tmp/parameters.json\"\nfi\n\n# Execute pipeline\necho \"Executing ${PIPELINE_NAME} pipeline\"\nPIPELINE_RUN_ID=$(az synapse pipeline create-run \\\n    --workspace-name ${SYNAPSE_WORKSPACE_NAME} \\\n    --name \"E2E Custom Vision Model Flow\" \\\n    --parameters @\"${PARAMETER_FILE_PATH}\" \\\n    --query runId --output tsv 2>/dev/null)\n\n# Check pipeline run status\n${PRJ_ROOT}/test/check-pipeline-status.sh ${ENV_CODE} ${PIPELINE_RUN_ID}\n", "num_lines": 128}
{"repo_name": "Azure-Orbital-Analytics-Samples", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/..; pwd)\"\n\nENV_CODE=${1:-${ENV_CODE}}\nDESTINATION_BATCH_ACCOUNT_NAME=${2:-${DESTINATION_BATCH_ACCOUNT_NAME}}\n\nPIPELINE_NAME=${3:-${PIPELINE_NAME:-\"custom-vision-model\"}}\nDESTINATION_BATCH_ACCOUNT_ROLE=${4:-${DESTINATION_BATCH_ACCOUNT_ROLE:-\"Contributor\"}}\nDESTINATION_BATCH_ACCOUNT_POOL_NAME=${5:-${DESTINATION_BATCH_ACCOUNT_POOL_NAME:-\"${ENV_CODE}-data-cpu-pool\"}}\nDESTINATION_BATCH_ACCOUNT_STORAGE_ACCOUNT_NAME=${6:-${DESTINATION_BATCH_ACCOUNT_STORAGE_ACCOUNT_NAME}}\n\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME=${7:-${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME}}\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME=${8:-${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME}}\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$DESTINATION_BATCH_ACCOUNT_NAME\" ]]\n  then\n    echo \"Batch Account Name value not supplied\"\n    exit 1\nfi\n\nset -ex\n\nDESTINATION_BATCH_ACCOUNT_ID=$(az batch account list --query \"[?name == '${DESTINATION_BATCH_ACCOUNT_NAME}'].id\" -o tsv)\nDESTINATION_BATCH_ACCOUNT_RG_NAME=$(az resource show --ids ${DESTINATION_BATCH_ACCOUNT_ID} --query resourceGroup -o tsv)\nDESTINATION_BATCH_ACCOUNT_STORAGE_ACCOUNT_NAME=$(az storage account list --resource-group $DESTINATION_BATCH_ACCOUNT_RG_NAME --query [0].name -o tsv)\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME=\"${ENV_CODE}-data-rg\"\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME=$(az storage account list --resource-group $BATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME --query [0].name -o tsv)\nSOURCE_SYNAPSE_WORKSPACE_RG_NAME=\"${ENV_CODE}-pipeline-rg\"\nSOURCE_SYNAPSE_WORKSPACE_NAME=$(az synapse workspace list --query \"[?tags.workspaceId && tags.workspaceId == 'default'].name\" -o tsv -g ${SOURCE_SYNAPSE_WORKSPACE_RG_NAME})\n\n# Verify that infrastructure and batch account are in same location\nBATCH_ACCOUNT_LOCATION=$(az batch account show  --name ${DESTINATION_BATCH_ACCOUNT_NAME} --resource-group ${DESTINATION_BATCH_ACCOUNT_RG_NAME} --query \"location\" --output tsv)\nSYNAPSE_WORKSPACE_LOCATION=$(az synapse workspace show --name ${SOURCE_SYNAPSE_WORKSPACE_NAME} --resource-group ${SOURCE_SYNAPSE_WORKSPACE_RG_NAME} --query \"location\" --output tsv)\nif [[ \"${BATCH_ACCOUNT_LOCATION}\" != ${SYNAPSE_WORKSPACE_LOCATION} ]]; then\n    echo \"Batch Account and Synapse Workspace are not in same location!!!\"\n    exit -1\nfi\n\n# Grant access to batch account for Managed Identities\npython3 ${PRJ_ROOT}/test/batch_account.py \\\n    --env_code ${ENV_CODE} \\\n    --target_batch_account_name ${DESTINATION_BATCH_ACCOUNT_NAME} \\\n    --target_batch_account_resource_group_name ${DESTINATION_BATCH_ACCOUNT_RG_NAME} \\\n    --batch_account_role ${DESTINATION_BATCH_ACCOUNT_ROLE} \\\n    --source_synapse_workspace_name ${SOURCE_SYNAPSE_WORKSPACE_NAME}\n\n# Deploy Batch Pool\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_KEY=$(az storage account keys list --resource-group ${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME} --account-name ${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME} --query \"[0].value\" --output tsv)\nBATCH_POOL_MOUNT_STORAGE_ACCOUNT_FILE_URL=$(az storage account show --resource-group ${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_RG_NAME} --name ${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME}  --query \"primaryEndpoints.file\" --output tsv)\n\necho\necho \"Deploying batch pool \\\"${DESTINATION_BATCH_ACCOUNT_POOL_NAME}\\\" on batch account \\\"${DESTINATION_BATCH_ACCOUNT_NAME}\\\"\"\nACR_NAME=$(az acr list --resource-group \"${ENV_CODE}-orc-rg\" --query \"[0].name\" --output tsv)\naz deployment group create --resource-group \"${ENV_CODE}-orc-rg\" \\\n    --template-file ${PRJ_ROOT}/deploy/infra/create_cpu_batch_account_pool.bicep \\\n    --parameters \\\n        environmentCode=${ENV_CODE} \\\n        projectName=\"orc\" \\\n        acrName=\"${ACR_NAME}\"\\\n        batchAccountName=${DESTINATION_BATCH_ACCOUNT_NAME} \\\n        batchAccountResourceGroup=${DESTINATION_BATCH_ACCOUNT_RG_NAME} \\\n        batchAccountCpuOnlyPoolName=\"${DESTINATION_BATCH_ACCOUNT_POOL_NAME}\" \\\n        batchAccountPoolMountAccountName=${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_NAME} \\\n        batchAccountPoolMountAccountKey=${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_KEY} \\\n        batchAccountPoolMountFileUrl=\"${BATCH_POOL_MOUNT_STORAGE_ACCOUNT_FILE_URL}volume-a\"\n", "num_lines": 76}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nPROJECT_DIR=\"$(dirname -- \"$0\")\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n\necho \"Installing node modules\"\nnpm install\nnpx yarn install --prod=false\n\npopd\n", "num_lines": 15}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\nWORKING_DIR=\"$(dirname \"$0\")\"\n\naz deployment sub create \\\n  --name \"${NAME_PREFIX}-deployment\" \\\n  --location ${AZ_LOCATION} \\\n  --template-file ${WORKING_DIR}/main.bicep \\\n  --parameters \\\n    namePrefix=\"${NAME_PREFIX}\" \\\n    location=\"${AZ_LOCATION}\" \\\n    tcpToBlobRg=\"${TCP_TO_BLOB_RG}\" \\\n    tcpToBlobLawName=\"${TCP_TO_BLOB_LAW_NAME}\" \\\n    aquaRg=\"${AQUA_RG}\" \\\n    aquaLawName=\"${AQUA_LAW_NAME}\"\n", "num_lines": 21}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# The following is a template for the required env vars.\n# Please see the README for more details\nexport AZ_LOCATION=\"westus2\"\nexport NAME_PREFIX=\"aoi-logs\"\nexport TCP_TO_BLOB_RG=\"\"\nexport TCP_TO_BLOB_LAW_NAME=\"\"\nexport AQUA_RG=\"\"\nexport AQUA_LAW_NAME=\"\"\n", "num_lines": 14}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\nWORKING_DIR=\"$(dirname \"$0\")\"\nBLOB_DOWNLOAD_SERVICE_ARTIFACTS_DIR=\"${WORKING_DIR}/artifacts/linux-x64/file-event-service\"\nARTIFACTS_CONTAINER_NAME=\"artifacts\"\n\n# Deploy some prerequisites, capture the outputs from the deployment and create vars from the required outputs\nPREREQ_DEPLOYMENT_OUTPUT=$(az deployment sub create --name \"${NAME_PREFIX}-prereq\" --location ${AZ_LOCATION} --template-file ${WORKING_DIR}/prereq.bicep --parameters location=\"${AZ_LOCATION}\" namePrefix=\"${NAME_PREFIX}\" --query \"properties.outputs\" -o json)\n\nAPPLICATION_INSIGHTS_APP_NAME=$(echo ${PREREQ_DEPLOYMENT_OUTPUT} | jq -r '.applicationInsightsName.value')\nAPPLICATION_INSIGHTS_RG=$(echo ${PREREQ_DEPLOYMENT_OUTPUT} | jq -r '.applicationInsightsRg.value')\nSTORAGE_ACCOUNT_NAME=$(echo ${PREREQ_DEPLOYMENT_OUTPUT} | jq -r '.storageAccountName.value')\n\n# Prepare the settings, scripts and binaries and stage it in the artifacts folder\n${WORKING_DIR}/file-event-service/prepare-artifacts.sh $APPLICATION_INSIGHTS_APP_NAME $APPLICATION_INSIGHTS_RG\n\naz storage container create --account-name ${STORAGE_ACCOUNT_NAME} --name ${ARTIFACTS_CONTAINER_NAME}\naz storage blob upload --account-name ${STORAGE_ACCOUNT_NAME} --container-name ${ARTIFACTS_CONTAINER_NAME} --file ${BLOB_DOWNLOAD_SERVICE_ARTIFACTS_DIR}/file-event-service-artifacts.tar.gz --name file-event-service-artifacts.tar.gz --overwrite\naz storage blob upload --account-name ${STORAGE_ACCOUNT_NAME} --container-name ${ARTIFACTS_CONTAINER_NAME} --file ${WORKING_DIR}/file-event-service/install-file-event-service.sh --name install-file-event-service.sh --overwrite\n\naz deployment sub create \\\n  --name \"${NAME_PREFIX}-deployment\" \\\n  --location ${AZ_LOCATION} \\\n  --template-file ${WORKING_DIR}/main.bicep \\\n  --parameters \\\n    location=\"${AZ_LOCATION}\" \\\n    namePrefix=\"${NAME_PREFIX}\" \\\n    allowedSshIpAddress=\"${ALLOWED_SSH_IP_ADDRESS}\" \\\n    adminPublicKey=\"$(cat ~/.ssh/id_rsa.pub)\"\n", "num_lines": 35}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# The following is a template for the required env vars.\n# Please see the README for more details\n\n########################### *REQUIRED* ##############################\n# Please adjust the following variables as needed for you environment\n#####################################################################\nexport AZ_LOCATION=\"westus2\"\nexport NAME_PREFIX=\"aoi-aqua\"\nexport ALLOWED_SSH_IP_ADDRESS=\"\"\nexport CONTACT_STORAGE_ACCOUNT_NAME=\"\"\nexport CONTACT_STORAGE_ACCOUNT_RESOURCE_GROUP=\"\"\nexport SERVICE_BUS_NAMESPACE=\"\"\nexport SERVICE_BUS_RESOURCE_GROUP=\"\"\n\n############################ OPTIONAL ###############################\n# Please adjust the following variables as needed for you environment\n#####################################################################\nexport SERVICE_BUS_AUTH_RULE_NAME=\"RootManageSharedAccessKey\"\nexport ENVIRONMENT_NAME=\"Aqua-FileEventService\"\nexport AZ_VM_USER_HOME_FOLDER=\"/home/azureuser\"\nexport SERVICE_BUS_QUEUE_NAME=\"contact-data\"\nexport RTSTPS_OUTPUT_CONATINER_NAME=\"pds\"\nexport RTSTPS_OUTPUT_SUBFOLDER_PATH=\"pds_files\"\nexport MODIS_OUTPUT_CONTAINER_NAME=\"modis\"\n#####################################################################\n", "num_lines": 31}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\ncase \"$(pidof FileEventService | wc -w)\" in\n  1) systemctl stop FileEventService\nesac\n\nRUNTIME=\"linux-x64\"\nWORKING_DIR=\"$(dirname \"$0\")\"\nLOCAL_ARTIFACTS_FOLDER=\"file-event-service-artifacts\"\nFES_INSTALL_FOLDER=\"/usr/share/FileEventService\"\n\n# Extract artifacts\nmkdir -p ${LOCAL_ARTIFACTS_FOLDER}\ntar -zvxf ./file-event-service-artifacts.tar.gz -C ${LOCAL_ARTIFACTS_FOLDER}\n\n# Install FileEventService\nyum install -y epel-release\nyum update -y\nyum install -y libicu\nyum install -y jq\nmkdir -p ${FES_INSTALL_FOLDER}\n\ncp ${WORKING_DIR}/${LOCAL_ARTIFACTS_FOLDER}/FileEventService ${FES_INSTALL_FOLDER}\ncp ${WORKING_DIR}/${LOCAL_ARTIFACTS_FOLDER}/appsettings.json ${FES_INSTALL_FOLDER}\ncp ${WORKING_DIR}/${LOCAL_ARTIFACTS_FOLDER}/file-event-service.json ${FES_INSTALL_FOLDER}\ncp ${WORKING_DIR}/${LOCAL_ARTIFACTS_FOLDER}/run-nasa-tools.sh ${FES_INSTALL_FOLDER}\ncp ${WORKING_DIR}/${LOCAL_ARTIFACTS_FOLDER}/FileEventService.service /etc/systemd/system/FileEventService.service\n\nsudo systemctl daemon-reload\n\nsudo systemctl enable FileEventService\n\nsudo systemctl start FileEventService", "num_lines": 38}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\nAPPLICATION_INSIGHTS_APP_NAME=${1}\nAPPLICATION_INSIGHTS_RG=${2}\n\nWORKING_DIR=\"$(dirname \"$0\")\"\nFILE_EVENT_SERVICE_SRC_DIR=\"${WORKING_DIR}/../../../../file-event-service/src\"\nARTIFACTS_DIR=\"${WORKING_DIR}/../artifacts/linux-x64/file-event-service\"\nmkdir -p ${ARTIFACTS_DIR}\n\n# Build the binaries and stage them in the artifacts folder\ndotnet publish ${FILE_EVENT_SERVICE_SRC_DIR}/FileEventService.csproj --configuration Release --runtime linux-x64 --self-contained --output ${ARTIFACTS_DIR}\n\n# Secrets that get retrieved using az cli. The UAMI associated with the\n# VM needs to have Contributor permissions for the folloing 3 resources\nAPP_INSIGHTS_CONNECTION_STRING=$(az monitor app-insights component show --app ${APPLICATION_INSIGHTS_APP_NAME} -g ${APPLICATION_INSIGHTS_RG} --query 'connectionString' -otsv)\nSERVICE_BUS_CONNECTION_STRING=$(az servicebus namespace authorization-rule keys list -g ${SERVICE_BUS_RESOURCE_GROUP} --namespace-name ${SERVICE_BUS_NAMESPACE} -n ${SERVICE_BUS_AUTH_RULE_NAME} --query 'primaryConnectionString' -otsv)\nBLOB_CONNECTION_STRING=$(az storage account show-connection-string -g ${CONTACT_STORAGE_ACCOUNT_RESOURCE_GROUP} -n ${CONTACT_STORAGE_ACCOUNT_NAME} --query 'connectionString' -otsv)\n\ncat ${WORKING_DIR}/appsettings.template.json | \\\n  APP_INSIGHTS_CONNECTION_STRING=${APP_INSIGHTS_CONNECTION_STRING} \\\n  envsubst > ${ARTIFACTS_DIR}/appsettings.json\n\ncat ${WORKING_DIR}/file-event-service.template.json | \\\n  APP_INSIGHTS_CONNECTION_STRING=${APP_INSIGHTS_CONNECTION_STRING} \\\n  FILE_EVENT_SERVICE_ENVIRONMENT_NAME=${FILE_EVENT_SERVICE_ENVIRONMENT_NAME} \\\n  SERVICE_BUS_CONNECTION_STRING=${SERVICE_BUS_CONNECTION_STRING} \\\n  SERVICE_BUS_QUEUE_NAME=${SERVICE_BUS_QUEUE_NAME} \\\n  BLOB_CONNECTION_STRING=${BLOB_CONNECTION_STRING} \\\n  AZ_VM_USER_HOME_FOLDER=${AZ_VM_USER_HOME_FOLDER} \\\n  RTSTPS_OUTPUT_CONATINER_NAME=${RTSTPS_OUTPUT_CONATINER_NAME} \\\n  RTSTPS_OUTPUT_SUBFOLDER_PATH=${RTSTPS_OUTPUT_SUBFOLDER_PATH} \\\n  MODIS_OUTPUT_CONTAINER_NAME=${MODIS_OUTPUT_CONTAINER_NAME} \\\n  envsubst > ${ARTIFACTS_DIR}/file-event-service.json\n\n# Stage other scripts in artifacts folder to be copied over\ncp ${WORKING_DIR}/FileEventService.service ${ARTIFACTS_DIR}\ncp ${WORKING_DIR}/run-nasa-tools.sh ${ARTIFACTS_DIR}\n\ntar -czvf /tmp/file-event-service-artifacts.tar.gz -C ${ARTIFACTS_DIR} .\n\nmv /tmp/file-event-service-artifacts.tar.gz ${ARTIFACTS_DIR}\n\n", "num_lines": 49}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\nRAW_CONTACT_FILE=$(echo ${FES_EVENT_GRID_EVENT} | jq -r '.Data.FullFilePath')\nCORRELATION_ID=$(echo ${FES_EVENT_GRID_EVENT} | jq -r '.Data.CorrelationId')\n\n# Run RT-STPS\n./bin/batch.sh config/aqua.xml ${RAW_CONTACT_FILE} 2>&1 | logger -p local0.info -s -t $CORRELATION_ID\n\n# Copy output PDS files to the IPOPP landing zone to be ingested and processed by IPOPP.\nmkdir -p /home/azureuser/data-staging\ncp /home/azureuser/data/*.PDS  /home/azureuser/drl/data/dsm/ingest/\n\n# Move the files to a staging folder where they will be picked up for blob upload.\nmv /home/azureuser/data/*.PDS /home/azureuser/data-staging/\n\n# Run ingest_ipopp.sh to trigger IPOPP processing.\n/home/azureuser/drl/tools/ingest_ipopp.sh 2>&1 | logger -p local0.info -s -t $CORRELATION_ID", "num_lines": 22}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# The following is a template for the required env vars.\n# Please see the README for more details\nexport AZ_SUBSCRIPTION=\"\"\nexport AZ_LOCATION=\"westus2\"\nexport AZ_RESOURCE_GROUP=\"\"\n\nexport TLE_TITLE=\"\"\n\nexport SPACECRAFT_NAME=\"AQUA\"\nexport GROUND_STATION_NAME=\"microsoft_quincy\"\nexport CONTACT_PROFILE_NAME=\"\"\n\nexport ENDPOINT_NAME=\"\"\nexport ENDPOINT_IP=\"\"\nexport ENDPOINT_PORT=50111\nexport ENDPOINT_SUBNET_ID=\"\"\n", "num_lines": 22}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nif [[ -z \"$DOCKER_TAG\" ]]; then\n    echo \"make_docker_image: Must provide docker tag (DOCKER_TAG).\" 1>&2\n    exit 1\nfi\nif [[ -z \"$DOCKER_FILE\" ]]; then\n    echo \"make_docker_image: Must provide docker file (DOCKER_FILE).\" 1>&2\n    exit 1\nfi\necho \"Adding \\\"${DOCKER_TAG}\\\" image to \\\"${ACR_NAME}\\\" ACR.\";\naz acr build -t \"${DOCKER_TAG}\" -r \"${ACR_NAME}\" -g \"${AZ_RESOURCE_GROUP}\" --file \"${DOCKER_FILE}\" --build-arg BUNDLE_DIR='.' ./dist/bundle;\n", "num_lines": 16}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\necho \"Checking required env vars.\"\ndeclare -a required_env_vars=(\n  \"NAME_PREFIX\"\n)\nfor var_name in \"${required_env_vars[@]}\"\ndo\n  if [[ -z \"${!var_name}\" ]]; then\n      echo \"Must set \\\"${var_name}\\\" env variable.\" 1>&2\n      exit 1\n  fi\ndone\n\n", "num_lines": 20}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n. ./deploy/env-prereq-defaults.sh\necho \"Loading core env defaults.\"\n\n# https://github.com/Azure/azure-orbital-integration/issues/118\nexport CONTACT_DATA_STORAGE_CONTAINER=${CONTACT_DATA_STORAGE_CONTAINER:-\"raw-contact-data\"}\necho \"CONTACT_DATA_STORAGE_CONTAINER = \\\"${CONTACT_DATA_STORAGE_CONTAINER}\\\"\"\n\nexport AKS_VNET=${AKS_VNET:-\"${NAME_PREFIX}-vnet\"}\nexport AKS_VNET_ADDR_PREFIX=${AKS_VNET_ADDR_PREFIX:-'10.0.0.0/8'}\necho \"AKS_VNET = \\\"${AKS_VNET}\\\"\"\n\nexport AKS_VNET_ID=\"/subscriptions/${AZ_SUBSCRIPTION}/resourceGroups/${AZ_RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/${AKS_VNET}\"\necho \"AKS_VNET_ID = \\\"${AKS_VNET_ID}\\\"\"\n\nexport AKS_VNET_SUBNET_ADDR_PREFIX=${AKS_VNET_SUBNET_ADDR_PREFIX:-'10.240.0.0/16'}\necho \"AKS_VNET_SUBNET_ADDR_PREFIX = \\\"${AKS_VNET_SUBNET_ADDR_PREFIX}\\\"\"\n\nexport LB_IP=${LB_IP:-'10.240.11.11'}\necho \"LB_IP = \\\"${LB_IP}\\\"\"\n\nexport AKS_POD_SUBNET_ADDR_PREFIX=${AKS_POD_SUBNET_ADDR_PREFIX:-'10.241.0.0/16'}\necho \"AKS_POD_SUBNET_ADDR_PREFIX = \\\"${AKS_POD_SUBNET_ADDR_PREFIX}\\\"\"\n\nexport AKS_ORBITAL_SUBNET_ADDR_PREFIX=${AKS_ORBITAL_SUBNET_ADDR_PREFIX:-'10.244.0.0/16'}\necho \"AKS_ORBITAL_SUBNET_ADDR_PREFIX = \\\"${AKS_ORBITAL_SUBNET_ADDR_PREFIX}\\\"\"\n\nexport AKS_NUM_REPLICAS=${AKS_NUM_REPLICAS:-2} \necho \"AKS_NUM_REPLICAS = \\\"${AKS_NUM_REPLICAS}\\\"\"\n\nexport HOST=\"0.0.0.0\"\necho \"HOST = \\\"${HOST}\\\"\"\n\nexport PORT=${PORT:-50111}\necho \"PORT = \\\"${PORT}\\\"\"\n\nexport SOCKET_TIMEOUT_SECONDS=${SOCKET_TIMEOUT_SECONDS:-120}\necho \"SOCKET_TIMEOUT_SECONDS = \\\"${SOCKET_TIMEOUT_SECONDS}\\\"\"\n\nexport NUM_BLOCK_LOG_FREQUENCY=${NUM_BLOCK_LOG_FREQUENCY:-4000}\necho \"NUM_BLOCK_LOG_FREQUENCY = \\\"${NUM_BLOCK_LOG_FREQUENCY}\\\"\"\n\nexport CANARY_NUM_LINES=${CANARY_NUM_LINES:-65000}\necho \"CANARY_NUM_LINES = \\\"${CANARY_NUM_LINES}\\\"\"\n\nif [[ -z \"${CONTACT_DATA_STORAGE_CONNECTION_STRING}\" ]]; then\n    echo '\"CONTACT_DATA_STORAGE_CONNECTION_STRING\" env variable not defined. Getting connection string from \"STORAGE_ACCT\".'\n    export CONTACT_DATA_STORAGE_CONNECTION_STRING=$(az storage account show-connection-string --resource-group \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\" -n \"${CONTACT_DATA_STORAGE_ACCT}\" --query \"connectionString\" -otsv)\nfi\necho \"CONTACT_DATA_STORAGE_CONNECTION_STRING = \\\"<MASKED>\\\"\"\n\nexport DEMODULATION_CONFIG=${DEMODULATION_CONFIG:-'aqua_direct_broadcast'}\necho \"DEMODULATION_CONFIG = \\\"${DEMODULATION_CONFIG}\\\"\"\n\nexport RAW_DATA_BLOB_NAME=${RAW_DATA_BLOB_NAME:-''}\necho \"RAW_DATA_BLOB_NAME = \\\"${RAW_DATA_BLOB_NAME}\\\"\"\n", "num_lines": 61}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\necho \"Loading prereq env defaults.\"\n\nexport AZ_LOCATION=${AZ_LOCATION:-\"westus2\"}\necho \"AZ_LOCATION = \\\"${AZ_LOCATION}\\\"\"\n\nexport AZ_SUBSCRIPTION=\"$(az account list --query \"[?isDefault].id\" -o tsv)\"\necho \"AZ_SUBSCRIPTION = \\\"${AZ_SUBSCRIPTION}\\\"\"\n\nexport AZ_RESOURCE_GROUP=${AZ_RESOURCE_GROUP:-\"${NAME_PREFIX}-${AZ_LOCATION}-rg\"}\necho \"AZ_RESOURCE_GROUP = \\\"${AZ_RESOURCE_GROUP}\\\"\"\n\nexport AKS_NAME=${AKS_NAME:-\"${NAME_PREFIX}-aks\"}\necho \"AKS_NAME = \\\"${AKS_NAME}\\\"\"\n\nexport STRIPPED_NAME=\"$(echo \"${NAME_PREFIX}\" | tr -d '-')\"\necho \"STRIPPED_NAME = \\\"${STRIPPED_NAME}\\\"\"\n\nexport ACR_RESOURCE_GROUP=${ACR_RESOURCE_GROUP:-\"${AZ_RESOURCE_GROUP}\"}\necho \"ACR_RESOURCE_GROUP = \\\"${ACR_RESOURCE_GROUP}\\\"\"\n\nexport ACR_NAME=${ACR_NAME:-\"${STRIPPED_NAME}acr\"}\necho \"ACR_NAME = \\\"${ACR_NAME}\\\"\"\n\nexport LOG_ANALYTICS_WORKSPACE_NAME=\"${NAME_PREFIX}-law\"\necho \"LOG_ANALYTICS_WORKSPACE_NAME = \\\"${LOG_ANALYTICS_WORKSPACE_NAME}\\\"\"\n\nexport CONTACT_DATA_STORAGE_ACCT=${CONTACT_DATA_STORAGE_ACCT:-\"${STRIPPED_NAME}\"}\necho \"CONTACT_DATA_STORAGE_ACCT = \\\"${CONTACT_DATA_STORAGE_ACCT}\\\"\"\n\nexport CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP=${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP:-\"${AZ_RESOURCE_GROUP}\"}\necho \"CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP = \\\"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\\\"\"\n\nexport CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY=\"contact-data-storage-account-connection-string\"\necho \"CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY = \\\"${CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY}\\\"\"\n", "num_lines": 40}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# The following is a template for the required env vars.\n# Please see the README for more details\n\n# export AZ_RESOURCE_GROUP=\"\"\nexport AZ_LOCATION=\"westus2\"\nexport NAME_PREFIX=\"aoi-t2b\"\n", "num_lines": 12}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -euo pipefail\n\nif [[ -z \"$NAME_PREFIX\" ]]; then\n  . tcp-to-blob/.env/env-template.sh || (echo \"Set NAME_PREFIX or open a new shell window and run 'docker cp ./tcp-to-blob/.env/ t2b-deploy:/home/azure-orbital-integration/tcp-to-blob/'.\" && exit 1)\nfi\n\naz account show # Fail fast if not logged in.\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n./install-node-modules.sh\nnpx yarn build\ntcp-to-blob/deploy/bicep/deploy.sh\n\npopd\n", "num_lines": 21}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\necho \"Install and compile dependencies\"\nyarn install && yarn compile\n\ncd tcp-to-blob\n\necho Run Build\nyarn build\n\nset -eo pipefail\n./deploy/check-required-env.sh\n. ./deploy/env-defaults.sh\nyarn make-env-files\nset -euo pipefail\n\ncp -r ./dist \"${WORKING_DIR}\"\n\n./deploy/bicep/deploy-core.sh\n", "num_lines": 23}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\ncd tcp-to-blob\n./deploy/bicep/deploy-prereq.sh\n", "num_lines": 8}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\nset -eo pipefail\n\necho \"Deploying service and dashboards.\"\n\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n\n. ./deploy/env-defaults.sh\n\n# Login to AKS\necho \"Getting credentials for \\\"${AKS_NAME}\\\" AKS cluster.\"\naz aks get-credentials --resource-group \"${AZ_RESOURCE_GROUP}\" --name \"${AKS_NAME}\"\n\n# Login to\necho \"Logging into \\\"${ACR_NAME}\\\" ACR.\"\naz acr login -n \"${ACR_NAME}\" --expose-token\n\n# Create storage connection string secret\necho \"Checking for AKS storage secret: \\\"${CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY}\\\"\"\nif [ -n \"$(kubectl get secret \"${CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY}\" --ignore-not-found)\" ];\nthen\n  echo \"Storage connection string secret exists. Deleting before re-creating.\"\n  kubectl delete secret \"${CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY}\" --ignore-not-found\nfi\necho \"Creating storage connection string secrets.\"\nkubectl create secret generic \"${CONTACT_DATA_STORAGE_CONNECTION_STRING_SECRET_KEY}\" \\\n  --from-literal=connection-string=\"${CONTACT_DATA_STORAGE_CONNECTION_STRING}\"\n\nset -euo pipefail\n\n# Build & deploy TCP to BLOB\necho \"Deploying TCP to BLOB service to \\\"${AKS_NAME}\\\".\"\nnpx yarn deploy\n\necho \"Creating dashboard.\"\nnpx yarn deploy-dashboard\n\n# Build & deploy canary\necho \"Publishing canary image.\"\nnpx yarn docker-push-text-canary\n\nnpx yarn make-contact-profile\n\nSLEEP_SECONDS_BEFORE_CANARY=60\necho \"Waiting ${SLEEP_SECONDS_BEFORE_CANARY} seconds for service to initialize before running canary.\"\nsleep $SLEEP_SECONDS_BEFORE_CANARY;\n# TODO: Experiment with wait that works best or better way to run upon service initialization.\necho \"Running Canary Kubernetes Job.\"\nnpx yarn run-text-canary\n\n# If deployed to different cluster, you can use --context:\n# e.g. `kubectl --context tcp-to-blob-canary-dev delete -f ./.env/tcp-to-blob-canary.yaml\n\n# TODO: Write params needed for deploying Orbital contact profile to a file\n#  that can be loaded (as env variable) when (using Orbital Helper for )\n#  creating a contact profile targeting this deployed TCP to BLOB endpoint.\n#  See arm-orbital-helper/src/samples/createSyntheticContactProfile.ts\n#  Need:\n# \u00e2\u20ac\u00a2 endpointName\n# \u00e2\u20ac\u00a2 endpointIP\n# \u00e2\u20ac\u00a2 endpointPort\n# \u00e2\u20ac\u00a2 subnetId\n\npopd\n", "num_lines": 71}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# Source the environment file for the stage you wish to deploy.\n# Use deploy/env-template.sh as a template.\n# Consider putting your \"env-<env-name>.sh\" scripts in the \".env\" directory which is ignored by git.\n# e.g. `. ./.env/env-dev.sh`\n\n###############################################################\n# Note: This script is for demonstration purposes only.       #\n# We recommend using `deploy/bicep/deploy.sh` for deployment. #\n###############################################################\n\nset -eo pipefail\n\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n\n./deploy/check-required-env.sh\n. ./deploy/env-prereq-defaults.sh\n\n# Create resource group if needed\nif [[ $(az group exists -n \"${AZ_RESOURCE_GROUP}\") -eq 'false' ]];\nthen\n  echo \"Creating resource group: \\\"${AZ_RESOURCE_GROUP}\\\"\"\n  az group create --location \"${AZ_LOCATION}\" --name \"${AZ_RESOURCE_GROUP}\"\nfi\n\n# Create ACR resource group if needed\nif  [[ $(az group exists -n \"${ACR_RESOURCE_GROUP}\") -eq 'false' ]];\nthen\n  echo \"Creating resource group: \\\"${ACR_RESOURCE_GROUP}\\\"\"\n  az group create --location \"${AZ_LOCATION}\" --name \"${ACR_RESOURCE_GROUP}\"\nfi\n\n# Create ACR if needed\nif [[ -z $(az acr check-name -n \"${ACR_NAME}\" | grep \"already in use\") ]];\nthen\n    echo \"ACR doesn't exist. Creating ACR: \\\"${ACR_NAME}\\\"\"\n    az acr create --name \"${ACR_NAME}\" --resource-group \"${ACR_RESOURCE_GROUP}\" --sku \"Standard\"\nelse\n  echo \"ACR \\\"${ACR_NAME}\\\"\" exists.\nfi\n\n# Create storage account resource group if needed\nif  [[ $(az group exists -n \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\") -eq 'false' ]];\nthen\n  echo \"Creating resource group: \\\"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\\\"\"\n  az group create --location \"${AZ_LOCATION}\" --name \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\"\nfi\n\n# Create storage account if needed\nif [[ -z $(az storage account list -g \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\"  --query \"[?name=='${CONTACT_DATA_STORAGE_ACCT}'].{name:name,location:location} | [? contains(location,'${AZ_LOCATION}')]\" --output table) ]]\nthen\n    echo \"Storage account doesn't exist. Creating : \\\"${CONTACT_DATA_STORAGE_ACCT}\\\"\"\n    az storage account create --name \"${CONTACT_DATA_STORAGE_ACCT}\" --resource-group \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\"\nelse\n    echo \"Storage account \\\"${CONTACT_DATA_STORAGE_ACCT}\\\" exists.\"\nfi\n\n# Create Log Analytics Workspace if needed\nif [[ -z $(az monitor log-analytics workspace list -g \"${AZ_RESOURCE_GROUP}\" --query \"[?name=='${LOG_ANALYTICS_WORKSPACE_NAME}']\" --query \"[0].id\" -otsv) ]]\nthen\n    echo \"Log Analytics Workspace doesn't exist. Creating : \\\"${LOG_ANALYTICS_WORKSPACE_NAME}\\\"\"\n    LOG_ANALYTICS_WORKSPACE_ID=$(az monitor log-analytics workspace create -g \"${AZ_RESOURCE_GROUP}\" -n \"${LOG_ANALYTICS_WORKSPACE_NAME}\" --query \"id\" -otsv)\nelse\n    echo \"Log Analytics Workspace \\\"${LOG_ANALYTICS_WORKSPACE_NAME}\\\" exists.\"\n    LOG_ANALYTICS_WORKSPACE_ID=$(az monitor log-analytics workspace list -g \"${AZ_RESOURCE_GROUP}\" --query \"[?name=='${LOG_ANALYTICS_WORKSPACE_NAME}']\" --query \"[0].id\" -otsv)\nfi\n\n. ./deploy/env-defaults.sh\nset -euo pipefail\n\n# Create vnet\necho \"Creating AKS_VNET: \\\"${AKS_VNET}\\\" with prefix: \\\"${AKS_VNET_ADDR_PREFIX}\\\"\"\naz network vnet create -g \"${AZ_RESOURCE_GROUP}\" --name \"${AKS_VNET}\" --address-prefixes \"${AKS_VNET_ADDR_PREFIX}\" -o none\n\n# Create subnets\necho \"Creating \\\"vnet-subnet\\\". AKS_VNET_SUBNET_ADDR_PREFIX: \\\"$AKS_VNET_SUBNET_ADDR_PREFIX\\\"\"\naz network vnet subnet create -g \"${AZ_RESOURCE_GROUP}\" --vnet-name \"${AKS_VNET}\" \\\n  --name vnet-subnet --address-prefixes \"${AKS_VNET_SUBNET_ADDR_PREFIX}\" -o none\n\necho \"Creating \\\"pod-subnet\\\". AKS_POD_SUBNET_ADDR_PREFIX: \\\"$AKS_POD_SUBNET_ADDR_PREFIX\\\"\"\naz network vnet subnet create -g \"${AZ_RESOURCE_GROUP}\" --vnet-name \"${AKS_VNET}\" \\\n  --name pod-subnet --address-prefixes \"${AKS_POD_SUBNET_ADDR_PREFIX}\" -o none\n\necho \"Creating \\\"orbital-subnet\\\". AKS_ORBITAL_SUBNET_ADDR_PREFIX: \\\"$AKS_ORBITAL_SUBNET_ADDR_PREFIX\\\"\"\naz network vnet subnet create -g \"${AZ_RESOURCE_GROUP}\" --vnet-name \"${AKS_VNET}\" \\\n  --name orbital-subnet --address-prefixes \"${AKS_ORBITAL_SUBNET_ADDR_PREFIX}\" -o none \\\n  --delegations \"Microsoft.Orbital/orbitalGateways\"\n\nKUBELET_IDENTITY_NAME=\"${NAME_PREFIX}-kubelet-identity\"\necho \"Creating managed identity: \\\"${KUBELET_IDENTITY_NAME}\\\"\"\nKUBELET_IDENTITY_ID=$(az identity create -g \"${AZ_RESOURCE_GROUP}\" -n \"${KUBELET_IDENTITY_NAME}\" --query id --out tsv)\necho \"KUBELET_IDENTITY_ID = \\\"${KUBELET_IDENTITY_ID}\\\"\"\n\nAKS_CONTROL_PLANE_IDENTITY_NAME=\"${NAME_PREFIX}-aks-control-plane-identity\"\necho \"Creating managed identity: \\\"${AKS_CONTROL_PLANE_IDENTITY_NAME}\\\"\"\nAKS_CONTROL_PLANE_IDENTITY_ID=$(az identity create -g \"${AZ_RESOURCE_GROUP}\" -n \"${AKS_CONTROL_PLANE_IDENTITY_NAME}\" --query id --out tsv)\necho \"AKS_CONTROL_PLANE_IDENTITY_ID = \\\"${AKS_CONTROL_PLANE_IDENTITY_ID}\\\"\"\n\n\nSLEEP_SECONDS=60;# TODO: Experiment with wait that works best or better way to run upon identity initialization.\necho \"Sleeping ${SLEEP_SECONDS} seconds for identity/role propagation...\"\nsleep ${SLEEP_SECONDS};\n\necho \"Assigning control plane identity Network Contributor role.\"\nAKS_CONTROL_PLANE_SP_ID=$(az identity show --name \"${AKS_CONTROL_PLANE_IDENTITY_NAME}\" -g \"${AZ_RESOURCE_GROUP}\"  --query principalId --out tsv)\naz role assignment create --assignee \"${AKS_CONTROL_PLANE_SP_ID}\" --role 'Network Contributor' --scope \"/subscriptions/${AZ_SUBSCRIPTION}/resourceGroups/${AZ_RESOURCE_GROUP}/providers/Microsoft.Network/virtualNetworks/${AKS_VNET}\"\n\necho \"Creating AKS cluster: \\\"${AKS_NAME}\\\"\"\naz aks create -n \"${AKS_NAME}\" -g \"${AZ_RESOURCE_GROUP}\"  \\\n  --enable-addons monitoring \\\n  --assign-identity \"${AKS_CONTROL_PLANE_IDENTITY_ID}\" \\\n  --assign-kubelet-identity \"${KUBELET_IDENTITY_ID}\" \\\n  --workspace-resource-id \"${LOG_ANALYTICS_WORKSPACE_ID}\" \\\n  --max-pods 250 \\\n  --node-count 2 \\\n  --network-plugin \"azure\" \\\n  --vnet-subnet-id \"${AKS_VNET_ID}/subnets/vnet-subnet\" \\\n  --pod-subnet-id \"${AKS_VNET_ID}/subnets/pod-subnet\" \\\n  --attach-acr \"${ACR_NAME}\"\n\n./deploy/az-cli/deploy-service-and-dashboards.sh\n\npopd\n", "num_lines": 130}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# Source the environment file for the stage you wish to deploy.\n# Use deploy/env-template.sh as a template.\n# Consider putting your \"env-<env-name>.sh\" scripts in the \".env\" directory which is ignored by git.\n# e.g. `. ./.env/env-dev.sh`\n\nset -eo pipefail\n\necho \"Deploying core using bicep....\"\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n\n./deploy/check-required-env.sh\n. ./deploy/env-defaults.sh\n\n# Create resource group if needed\nif [[ $(az group exists -n \"${AZ_RESOURCE_GROUP}\") -eq 'false' ]];\nthen\n  echo \"Creating resource group: \\\"${AZ_RESOURCE_GROUP}\\\"\"\n  az group create --location \"${AZ_LOCATION}\" --name \"${AZ_RESOURCE_GROUP}\"\nfi\nset -euo pipefail\n\necho \"Deploying AKS \\\"${AKS_NAME}\\\" to \\\"${AZ_RESOURCE_GROUP}\\\" resource group\"\naz deployment group create \\\n  --name \"${NAME_PREFIX}-core-deployment\" \\\n  --resource-group \"${AZ_RESOURCE_GROUP}\" \\\n  --template-file \"./deploy/bicep/aks.bicep\" \\\n  --parameters \\\n      namePrefix=\"${NAME_PREFIX}\" \\\n      acrResourceGroup=\"${ACR_RESOURCE_GROUP}\" \\\n      acrName=\"${ACR_NAME}\"\n\npopd\n", "num_lines": 40}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# Source the environment file for the stage you wish to deploy.\n# Use deploy/env-template.sh as a template.\n# Consider putting your \"env-<env-name>.sh\" scripts in the \".env\" directory which is ignored by git.\n# e.g. `. ./.env/env-dev.sh`\n\nset -eo pipefail\n\necho \"Deploying pre-reqs using bicep....\"\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n\n./deploy/check-required-env.sh\n. ./deploy/env-prereq-defaults.sh\nset -euo pipefail\n\necho \"Creating resource group: \\\"${AZ_RESOURCE_GROUP}\\\"\"\naz group create --location \"${AZ_LOCATION}\" --name \"${AZ_RESOURCE_GROUP}\"\n\necho \"Creating ACR resource group: \\\"${ACR_RESOURCE_GROUP}\\\"\"\naz group create --location \"${AZ_LOCATION}\" --name \"${ACR_RESOURCE_GROUP}\"\n\necho \"Creating storage account resource group: \\\"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\\\"\"\naz group create --location \"${AZ_LOCATION}\" --name \"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\"\n\necho \"Deploying bicep template\"\naz deployment group create --resource-group \"${AZ_RESOURCE_GROUP}\" \\\n  --name \"${NAME_PREFIX}-prereq-deployment\" \\\n  --template-file \"./deploy/bicep/prereq-aks.bicep\" \\\n  --parameters \\\n      namePrefix=\"${NAME_PREFIX}\" \\\n      acrResourceGroup=\"${ACR_RESOURCE_GROUP}\" \\\n      acrName=\"${ACR_NAME}\" \\\n      storageAccountResourceGroup=\"${CONTACT_DATA_STORAGE_ACCT_RESOURCE_GROUP}\" \\\n      storageAccountName=\"${CONTACT_DATA_STORAGE_ACCT}\"\n\npopd\n", "num_lines": 43}
{"repo_name": "azure-orbital-integration", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) 2022 Microsoft Corporation. All rights reserved.\n# Software is licensed under the MIT License. See LICENSE in the project\n# root for license information.\n\n# Source the environment file for the stage you wish to deploy.\n# Use deploy/env-template.sh as a template.\n# Consider putting your \"env-<env-name>.sh\" scripts in the \".env\" directory which is ignored by git.\n# e.g. `. ./.env/env-dev.sh`\n\nset -eo pipefail\n\nPROJECT_DIR=\"$(dirname -- \"$0\")/../..\"\necho \"PROJECT_DIR: \\\"${PROJECT_DIR}\\\"\"\npushd \"${PROJECT_DIR}\"\n./deploy/bicep/deploy-prereq.sh\n./deploy/bicep/deploy-core.sh\n./deploy/az-cli/deploy-service-and-dashboards.sh\n\npopd\n", "num_lines": 21}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\n\n[[ -z \"$ENV_CODE\" ]] && { echo \"Environment Code value not supplied\"; exit 1; }\n\nset -ae\nENV_NAME=${ENV_NAME:-\"stac-${ENV_CODE}\"}\nSTAC_FASTAPI_VERSION=${STAC_FASTAPI_VERSION:-\"2.4.8\"}\nSTAC_BROWSER_VERSION=${STAC_BROWSER_VERSION:-\"3.0.2\"}\nPROCESSING_RESOURCE_GROUP=${PROCESSING_RESOURCE_GROUP:-\"${ENV_CODE}-processing-rg\"}\n\nACR_NAME=$(az acr list -g ${PROCESSING_RESOURCE_GROUP} \\\n    --query \"[?tags.environment && tags.environment == '$ENV_NAME'].name\" -otsv)\n\necho \"Building stac-cli Docker image in ACR\"\naz acr build -o none --no-logs --registry $ACR_NAME --image stac-cli ${PRJ_ROOT}\n\n# build stac-fastapi-pgstac from https://github.com/stac-utils/stac-fastapi-pgstac/archive/refs/tags/${STAC_FASTAPI_VERSION}.tar.gz\nSTAC_FASTAPI_SRC_DIR=${STAC_FASTAPI_SRC_DIR:-\"${PRJ_ROOT}/src/stac_fastapi_pgstac_k8s/src\"}\nSTAC_FASTAPI_RELEASE_URI=${STAC_FASTAPI_RELEASE_URI:-\"https://github.com/stac-utils/stac-fastapi-pgstac/archive/refs/tags/${STAC_FASTAPI_VERSION}.tar.gz\"}\nmkdir -p $STAC_FASTAPI_SRC_DIR\nwget $STAC_FASTAPI_RELEASE_URI -P $STAC_FASTAPI_SRC_DIR\ntar xf ${STAC_FASTAPI_SRC_DIR}/${STAC_FASTAPI_VERSION}.tar.gz -C ${STAC_FASTAPI_SRC_DIR}\necho \"Building stac-fastapi-pgstac Docker image in ACR\"\naz acr build -o none --no-logs --registry $ACR_NAME --image stac-fastapi-pgstac \\\n  --file ${STAC_FASTAPI_SRC_DIR}/stac-fastapi-pgstac-${STAC_FASTAPI_VERSION}/Dockerfile \\\n  ${STAC_FASTAPI_SRC_DIR}/stac-fastapi-pgstac-${STAC_FASTAPI_VERSION}\nrm -rf ${STAC_FASTAPI_SRC_DIR}\n\n# build stac-browser from https://github.com/radiantearth/stac-browser/archive/refs/tags/v${STAC_BROWSER_VERSION}.tar.gz\nFQDN=$(az network public-ip show -g $PROCESSING_RESOURCE_GROUP -n ${ENV_CODE}-stac-ingress-public-ip \\\n    --query dnsSettings.fqdn -o tsv)\nSTAC_BROWSER_SRC_DIR=${STAC_BROWSER_SRC_DIR:-\"${PRJ_ROOT}/src/stac_browser_k8s/src\"}\nSTAC_BROWSER_RELEASE_URI=${STAC_BROWSER_RELEASE_URI:-\"https://github.com/radiantearth/stac-browser/archive/refs/tags/v${STAC_BROWSER_VERSION}.tar.gz\"}\nmkdir -p $STAC_BROWSER_SRC_DIR\nwget $STAC_BROWSER_RELEASE_URI -P $STAC_BROWSER_SRC_DIR\ntar xf ${STAC_BROWSER_SRC_DIR}/v${STAC_BROWSER_VERSION}.tar.gz -C ${STAC_BROWSER_SRC_DIR}\necho \"Building stac-browser Docker image in ACR\"\naz acr build -o none --no-logs --registry $ACR_NAME --image stac-browser \\\n  --build-arg 'catalogURL='\"'\"'https://'$FQDN'/api/ --pathPrefix=\"/browser/\"'\"'\"'' \\\n  ${STAC_BROWSER_SRC_DIR}/stac-browser-${STAC_BROWSER_VERSION}\nrm -rf ${STAC_BROWSER_SRC_DIR}\n", "num_lines": 48}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\n# parameters\nENV_CODE=${1:-${ENV_CODE}}\n\n[[ -z \"$ENV_CODE\" ]] && { echo \"Environment Code value not supplied\"; exit 1; }\n\nENV_TAG=${ENV_TAG:-\"stac-${ENV_CODE}\"}\nDEPLOYMENT_NAME=${DEPLOYMENT_NAME:-\"${ENV_TAG}-deploy\"}\n\n# variables\nMONITORING_RESOURCE_GROUP=\"${ENV_CODE}-monitoring-rg\"\nVNET_RESOURCE_GROUP=\"${ENV_CODE}-vnet-rg\"\nDATA_RESOURCE_GROUP=\"${ENV_CODE}-data-rg\"\nPROCESSING_RESOURCE_GROUP=\"${ENV_CODE}-processing-rg\"\n\nset -x\naz group delete --name ${MONITORING_RESOURCE_GROUP} --no-wait --yes\naz deployment sub delete --name ${MONITORING_RESOURCE_GROUP} --no-wait\naz group delete --name ${VNET_RESOURCE_GROUP} --no-wait --yes\naz deployment sub delete --name ${VNET_RESOURCE_GROUP} --no-wait\naz group delete --name ${DATA_RESOURCE_GROUP} --no-wait --yes\naz deployment sub delete --name ${DATA_RESOURCE_GROUP} --no-wait\naz group delete --name ${PROCESSING_RESOURCE_GROUP} --no-wait --yes\naz deployment sub delete --name ${PROCESSING_RESOURCE_GROUP} --no-wait\naz deployment sub delete --name ${DEPLOYMENT_NAME} --no-wait", "num_lines": 29}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\nLE_EMAIL_ADDRESS=${2:-${LE_EMAIL_ADDRESS}}\n\n[[ -z \"$ENV_CODE\" ]] && { echo \"Environment Code value not supplied\"; exit 1; }\n[[ -z \"$LE_EMAIL_ADDRESS\" ]] && { echo \"Let's Encrypt e-mail address (LE_EMAIL_ADDRESS) not specified\"; exit 1; }\n\nset -a\nset -e\nENV_NAME=${ENV_NAME:-\"stac-${ENV_CODE}\"}\nMONITORING_RESOURCE_GROUP=${MONITORING_RESOURCE_GROUP:-\"${ENV_CODE}-monitoring-rg\"}\nVNET_RESOURCE_GROUP=${VNET_RESOURCE_GROUP:-\"${ENV_CODE}-vnet-rg\"}\nDATA_RESOURCE_GROUP=${DATA_RESOURCE_GROUP:-\"${ENV_CODE}-data-rg\"}\nPROCESSING_RESOURCE_GROUP=${PROCESSING_RESOURCE_GROUP:-\"${ENV_CODE}-processing-rg\"}\nUAMI=${UAMI:-\"${ENV_CODE}-stacaks-mi\"}\n\nAKS_NAMESPACE=${AKS_NAMESPACE:-\"pgstac\"}\nAKS_INGRESS_NAMESPACE=${AKS_INGRESS_NAMESPACE:-\"ingress\"}\nENV_LABEL=${ENV_LABEL:-\"stacpool\"} # aks agent pool name to deploy kubectl deployment yaml files\nAKS_SERVICE_ACCOUNT_NAME=${AKS_SERVICE_ACCOUNT_NAME:-'stac-svc-acct'}\nFEDERATED_IDENTITY_NAME=\"stacaksfederatedidentity\"\n\nSUBSCRIPTION=$(az account show --query id -o tsv)\nAZURE_APP_INSIGHTS=$(az resource list -g $MONITORING_RESOURCE_GROUP --resource-type \"Microsoft.Insights/components\" \\\n    --query \"[?tags.environment && tags.environment == '$ENV_NAME'].name\" -o tsv)\n\nAZURE_LOG_CONNECTION_STRING=$(az resource show \\\n    -g $MONITORING_RESOURCE_GROUP \\\n    --resource-type Microsoft.Insights/components \\\n    -n ${AZURE_APP_INSIGHTS} \\\n    --query \"properties.ConnectionString\" -o tsv)\n\nDATA_STORAGE_ACCOUNT_NAME=$(az storage account list \\\n    --query \"[?tags.store && tags.store == 'data'].name\" -o tsv -g ${DATA_RESOURCE_GROUP})\nDATA_STORAGE_ACCOUNT_KEY=$(az storage account keys list \\\n    --account-name ${DATA_STORAGE_ACCOUNT_NAME} --resource-group ${DATA_RESOURCE_GROUP} \\\n    --query \"[0].value\" -o tsv)\n\nDATA_STORAGE_ACCOUNT_CONNECTION_STRING=$(az storage account show-connection-string \\\n    --resource-group $DATA_RESOURCE_GROUP \\\n    --name $DATA_STORAGE_ACCOUNT_NAME \\\n    | jq -r \".connectionString\")\n\nDATA_STORAGE_ACCOUNT_BLOB_ENDPOINT=$(az storage account show -n $DATA_STORAGE_ACCOUNT_NAME \\\n    --query primaryEndpoints.blob -otsv)\nDATA_STORAGE_ACCOUNT_BLOB_DOMAIN=${DATA_STORAGE_ACCOUNT_BLOB_ENDPOINT#https://}\nDATA_STORAGE_ACCOUNT_BLOB_DOMAIN=${DATA_STORAGE_ACCOUNT_BLOB_DOMAIN%%/*}\n\nAKS_RESOURCE_GROUP=${AKS_RESOURCE_GROUP:-${PROCESSING_RESOURCE_GROUP}}\nAKS_CLUSTER_NAME=$(az aks list -g ${AKS_RESOURCE_GROUP} \\\n    --query \"[?tags.type && tags.type == 'k8s'].name\" -otsv)\nACR_DNS=$(az acr list -g ${PROCESSING_RESOURCE_GROUP} \\\n    --query \"[?tags.environment && tags.environment == '$ENV_NAME'].loginServer\" -otsv)\nAKS_OIDC_ISSUER=\"$(az aks show --resource-group ${AKS_RESOURCE_GROUP} \\\n    --name ${AKS_CLUSTER_NAME} --query \"oidcIssuerProfile.issuerUrl\" -o tsv)\"\nAKS_POD_CIDR=\"$(az aks show -g $AKS_RESOURCE_GROUP -n $AKS_CLUSTER_NAME \\\n    --query networkProfile.podCidr -o tsv)\"\n\nUSER_ASSIGNED_CLIENT_ID=\"$(az identity show -g ${PROCESSING_RESOURCE_GROUP} \\\n    --name $UAMI --query 'clientId' -o tsv)\"\nIDENTITY_TENANT=$(az aks show --name ${AKS_CLUSTER_NAME} \\\n    --resource-group ${PROCESSING_RESOURCE_GROUP} --query identity.tenantId -o tsv)\n\naz identity federated-credential create --name ${FEDERATED_IDENTITY_NAME} \\\n    --identity-name $UAMI \\\n    --resource-group ${PROCESSING_RESOURCE_GROUP} \\\n    --issuer ${AKS_OIDC_ISSUER} \\\n    --subject system:serviceaccount:${AKS_NAMESPACE}:${AKS_SERVICE_ACCOUNT_NAME} \\\n    -o none\n\nSERVICE_BUS_NAMESPACE=$(az servicebus namespace list \\\n    -g ${DATA_RESOURCE_GROUP} --query \"[?tags.environment && tags.environment == '$ENV_NAME'].name\" -otsv)\n\nSTAC_METADATA_TYPE_NAME=${STAC_METADATA_TYPE_NAME:-\"fgdc\"}\nCOLLECTION_ID=${COLLECTION_ID:-\"naip\"}\nJPG_EXTENSION=${JPG_EXTENSION:-\"200.jpg\"}\nXML_EXTENSION=${XML_EXTENSION:-\"aux.xml\"}\nREPLICAS=${REPLICAS:-\"3\"}\nPOD_CPU=${POD_CPU:-\"0.5\"}\nPOD_MEMORY=${POD_MEMORY:-\"2Gi\"}\n\nGENERATE_STAC_JSON_IMAGE_NAME=${GENERATE_STAC_JSON_IMAGE_NAME:-\"generate-stac-json\"}\nDATA_STORAGE_PGSTAC_CONTAINER_NAME=${DATA_STORAGE_PGSTAC_CONTAINER_NAME:-\"pgstac\"}\nENV_LABLE=${ENV_LABLE:-\"stacpool\"} # aks agent pool name to deploy kubectl deployment yaml files\n\nSERVICE_BUS_AUTH_POLICY_NAME=${SERVICE_BUS_AUTH_POLICY_NAME:-\"RootManageSharedAccessKey\"}\nSERVICE_BUS_CONNECTION_STRING=$(az servicebus namespace authorization-rule keys list \\\n    --resource-group ${DATA_RESOURCE_GROUP} \\\n    --namespace-name ${SERVICE_BUS_NAMESPACE} \\\n    --name ${SERVICE_BUS_AUTH_POLICY_NAME} \\\n    --query \"primaryConnectionString\" -otsv)\n\nSTAC_EVENT_CONSUMER_IMAGE_NAME=${STAC_EVENT_CONSUMER_IMAGE_NAME:-\"stac-event-consumer\"}\nPGSTAC_SERVICE_BUS_TOPIC_NAME=${PGSTAC_SERVICE_BUS_TOPIC_NAME:-\"pgstactopic\"}\nPGSTAC_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME=${PGSTAC_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME:-\"pgstacpolicy\"}\nPGSTAC_SERVICE_BUS_SUBSCRIPTION_NAME=${PGSTAC_SERVICE_BUS_SUBSCRIPTION_NAME:-\"pgstacsubscription\"}\nPGSTAC_SERVICE_BUS_CONNECTION_STRING=$(az servicebus topic authorization-rule keys list \\\n    --resource-group ${DATA_RESOURCE_GROUP} \\\n    --namespace-name ${SERVICE_BUS_NAMESPACE} \\\n    --topic ${PGSTAC_SERVICE_BUS_TOPIC_NAME} \\\n    --name ${PGSTAC_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME} \\\n    --query \"primaryConnectionString\" -otsv)\n\nGENERATED_STAC_STORAGE_CONTAINER_NAME=${GENERATED_STAC_STORAGE_CONTAINER_NAME:-\"generatedstacjson\"}\n\nKEY_VAULT_NAME=$(az keyvault list --query \"[?tags.environment && tags.environment == '$ENV_NAME'].name\" -o tsv -g $DATA_RESOURCE_GROUP)\nPGHOST=$(az postgres flexible-server list --resource-group $DATA_RESOURCE_GROUP --query '[].fullyQualifiedDomainName' -o tsv)\nPGHOSTONLY=$(az postgres flexible-server list --resource-group $DATA_RESOURCE_GROUP --query '[].name' -o tsv)\nPGUSER=$(az postgres flexible-server list --resource-group $DATA_RESOURCE_GROUP --query '[].administratorLogin' -o tsv)\nPGPASSWORD_SECRET_NAME=${PGPASSWORD_SECRET_NAME:-\"PGAdminLoginPass\"}\nPGPASSWORD=$(az keyvault secret show --vault-name $KEY_VAULT_NAME --name $PGPASSWORD_SECRET_NAME --query value -o tsv)\nPGDATABASE=${PGDATABASE:-\"postgres\"}\nPGPORT=${PGPORT:-\"5432\"}\n\nSTACIFY_STORAGE_CONTAINER_NAME=${STACIFY_STORAGE_CONTAINER_NAME:-\"stacify\"}\nSTACIFY_SERVICE_BUS_TOPIC_NAME=${STACIFY_SERVICE_BUS_TOPIC_NAME:-\"stacifytopic\"}\nSTACIFY_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME=${STACIFY_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME:-\"stacifypolicy\"}\nSTACIFY_SERVICE_BUS_SUBSCRIPTION_NAME=${STACIFY_SERVICE_BUS_SUBSCRIPTION_NAME:-\"stacifysubscription\"}\nSTACIFY_SERVICE_BUS_CONNECTION_STRING=$(az servicebus topic authorization-rule keys list \\\n    --resource-group ${DATA_RESOURCE_GROUP} \\\n    --namespace-name ${SERVICE_BUS_NAMESPACE} \\\n    --topic ${STACIFY_SERVICE_BUS_TOPIC_NAME} \\\n    --name ${STACIFY_SERVICE_BUS_TOPIC_AUTH_POLICY_NAME} \\\n    --query \"primaryConnectionString\" -otsv)\n\nSTAC_COLLECTION_IMAGE_NAME=${STAC_COLLECTION_IMAGE_NAME:-\"stac-collection\"}\nSTACCOLLECTION_STORAGE_CONTAINER_NAME=${STACCOLLECTION_STORAGE_CONTAINER_NAME:-\"staccollection\"}\nSTACCOLLECTION_SERVICE_BUS_TOPIC_NAME=${STACCOLLECTION_SERVICE_BUS_TOPIC_NAME:-\"staccollectiontopic\"}\nSTACCOLLECTION_SERVICE_BUS_AUTH_POLICY_NAME=${STACCOLLECTION_SERVICE_BUS_AUTH_POLICY_NAME:-\"staccollectionpolicy\"}\nSTACCOLLECTION_SERVICE_BUS_SUBSCRIPTION_NAME=${STACCOLLEcTION_SERVICE_BUS_SUBSCRIPTION_NAME:-\"staccollectionsubscription\"}\nSTACCOLLECTION_SERVICE_BUS_CONNECTION_STRING=$(az servicebus topic authorization-rule keys list \\\n    --resource-group ${DATA_RESOURCE_GROUP} \\\n    --namespace-name ${SERVICE_BUS_NAMESPACE} \\\n    --topic ${STACCOLLECTION_SERVICE_BUS_TOPIC_NAME} \\\n    --name ${STACCOLLECTION_SERVICE_BUS_AUTH_POLICY_NAME} \\\n    --query \"primaryConnectionString\" -otsv)\n\nINGRESS_PUBLIC_IP_ADDR=$(az network public-ip show -g $PROCESSING_RESOURCE_GROUP \\\n    -n ${ENV_CODE}-stac-ingress-public-ip --query ipAddress -o tsv)\nINGRESS_FQDN=$(az network public-ip show -g $PROCESSING_RESOURCE_GROUP -n ${ENV_CODE}-stac-ingress-public-ip \\\n    --query dnsSettings.fqdn -o tsv)\nDNS_LABEL_NAME=${INGRESS_FQDN%%.*}\n\nset +a\n\necho 'enabling POSTGIS,BTREE_GIST in postgres'\naz postgres flexible-server \\\n    parameter set \\\n    --resource-group $DATA_RESOURCE_GROUP --server-name $PGHOSTONLY \\\n    --subscription $SUBSCRIPTION --name azure.extensions --value POSTGIS,BTREE_GIST \\\n    -o none\n\naz aks get-credentials --admin --resource-group ${AKS_RESOURCE_GROUP} \\\n  --name ${AKS_CLUSTER_NAME} --context ${AKS_CLUSTER_NAME} --overwrite-existing \\\n  -o none\nkubectl config set-context ${AKS_CLUSTER_NAME}\n\nNS=$(kubectl get namespace $AKS_NAMESPACE --ignore-not-found);\nif [[ \"$NS\" ]]; then\n    echo \"Skipping creation of ${AKS_NAMESPACE} namespace in k8s cluster as it already exists\"\nelse\n    echo \"Creating ${AKS_NAMESPACE} namespace in k8s cluster\"\n    kubectl create namespace ${AKS_NAMESPACE}\nfi;\n\necho \"Install KEDA\"\nhelm repo add kedacore https://kedacore.github.io/charts || true\nhelm repo update\n[[ -z \"$(kubectl get namespace keda --ignore-not-found)\" ]] && kubectl create namespace keda\nhelm upgrade --install keda kedacore/keda --namespace keda\n\n# Deploy a dummy workload to work around issue https://github.com/kedacore/keda/issues/4224\ncat <<\"EOF\" | kubectl apply -n keda -f -\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: dummy-workload\nspec:\n  replicas: 0\n  selector:\n    matchLabels:\n      app: dummy-workload\n  template:\n    metadata:\n      labels:\n        app: dummy-workload\n    spec:\n      containers:\n      - name: dummy\n        image: busybox\n---\napiVersion: keda.sh/v1alpha1\nkind: ScaledObject\nmetadata:\n  name: dummy-workload\nspec:\n  scaleTargetRef:\n    name: dummy-workload\n  minReplicaCount: 0\n  maxReplicaCount: 1\n  triggers:\n  - type: cron\n    metadata:\n      timezone: Etc/UTC \n      start: 30 * * * *\n      end: 45 * * * *\n      desiredReplicas: \"0\"\nEOF\nkubectl -n keda wait --for=condition=Ready ScaledObject/dummy-workload --timeout=3m\nsleep 10\n\necho \"Deploying stac-scaler chart to Kubernetes Cluster\"\n\nhelm upgrade --install stac-scaler ${PRJ_ROOT}/deploy/helm/stac-scaler \\\n    --namespace ${AKS_NAMESPACE} \\\n    --create-namespace \\\n    --set envCode=${ENV_CODE} \\\n    --set repository=${ACR_DNS} \\\n    --set userAssignedClientId=${USER_ASSIGNED_CLIENT_ID} \\\n    --set serviceAccountName=${AKS_SERVICE_ACCOUNT_NAME} \\\n    --set keyVaultName=${KEY_VAULT_NAME} \\\n    --set tenantId=${IDENTITY_TENANT} \\\n    --set cloudName=$(az cloud show --query name -otsv) \\\n    --set processors.staccollection.env.DATA_STORAGE_ACCOUNT_NAME=${DATA_STORAGE_ACCOUNT_NAME} \\\n    --set processors.staccollection.env.STACCOLLECTION_STORAGE_CONTAINER_NAME=${STACCOLLECTION_STORAGE_CONTAINER_NAME} \\\n    --set processors.staccollection.env.PGHOST=${PGHOST} \\\n    --set processors.staccollection.env.PGUSER=${PGUSER} \\\n    --set processors.staccollection.env.PGDATABASE=${PGDATABASE} \\\n    --set processors.staceventconsumer.env.DATA_STORAGE_ACCOUNT_NAME=${DATA_STORAGE_ACCOUNT_NAME} \\\n    --set processors.staceventconsumer.env.GENERATED_STAC_STORAGE_CONTAINER_NAME=${GENERATED_STAC_STORAGE_CONTAINER_NAME} \\\n    --set processors.staceventconsumer.env.DATA_STORAGE_PGSTAC_CONTAINER_NAME=${DATA_STORAGE_PGSTAC_CONTAINER_NAME} \\\n    --set processors.staceventconsumer.env.PGHOST=${PGHOST} \\\n    --set processors.staceventconsumer.env.PGUSER=${PGUSER} \\\n    --set processors.staceventconsumer.env.PGDATABASE=${PGDATABASE} \\\n    --set processors.generatestacjson.env.DATA_STORAGE_ACCOUNT_NAME=${DATA_STORAGE_ACCOUNT_NAME} \\\n    --set processors.generatestacjson.env.STACIFY_STORAGE_CONTAINER_NAME=${STACIFY_STORAGE_CONTAINER_NAME} \\\n    --set processors.generatestacjson.env.GENERATED_STAC_STORAGE_CONTAINER_NAME=${GENERATED_STAC_STORAGE_CONTAINER_NAME} \\\n    --set processors.generatestacjson.env.DATA_STORAGE_PGSTAC_CONTAINER_NAME=${DATA_STORAGE_PGSTAC_CONTAINER_NAME} \\\n    --set processors.generatestacjson.env.STAC_METADATA_TYPE_NAME=${STAC_METADATA_TYPE_NAME} \\\n    --set stacfastapi.image.repository=${ACR_DNS} \\\n    --set stacfastapi.env.POSTGRES_HOST_READER=${PGHOST} \\\n    --set stacfastapi.env.POSTGRES_HOST_WRITER=${PGHOST} \\\n    --set stacfastapi.env.POSTGRES_USER=${PGUSER} \\\n    --set stacfastapi.env.PGUSER=${PGUSER} \\\n    --set stacfastapi.env.PGHOST=${PGHOST} \\\n    --set stacfastapi.blobStoreEndpoint=${DATA_STORAGE_ACCOUNT_BLOB_ENDPOINT} \\\n    --set stacfastapi.hostname=${INGRESS_FQDN} \\\n    --set stacfastapi.clusterIssuer=letsencrypt\n\necho \"Deploying stac-browser chart to Kubernetes Cluster\"\n\nhelm upgrade --install stac-browser ${PRJ_ROOT}/deploy/helm/stac-browser \\\n    --namespace ${AKS_NAMESPACE} \\\n    --create-namespace \\\n    --set envCode=${ENV_CODE} \\\n    --set repository=${ACR_DNS} \\\n    --set hostname=${INGRESS_FQDN} \\\n    --set clusterIssuer=letsencrypt\n\n# Add helm repos for the nginx ingress controller and cert-manager\nhelm repo add ingress-nginx https://kubernetes.github.io/ingress-nginx\nhelm repo add jetstack https://charts.jetstack.io\nhelm repo update\n\n# Install the cert-manager Helm chart (for letsencrypt certificates)\necho \"Installing cert-manager\"\nkubectl create namespace $AKS_INGRESS_NAMESPACE\nkubectl label namespace $AKS_INGRESS_NAMESPACE cert-manager.io/disable-validation=true\nhelm upgrade --install cert-manager jetstack/cert-manager \\\n  --create-namespace \\\n  --namespace $AKS_INGRESS_NAMESPACE \\\n  --set installCRDs=true \\\n  --set nodeSelector.\"kubernetes\\.io/os\"=linux\n\n# Create a ClusterIssuer to issue certificates from Lets Encrypt\ncat <<EOF | kubectl apply -n $AKS_INGRESS_NAMESPACE -f -\napiVersion: cert-manager.io/v1\nkind: ClusterIssuer\nmetadata:\n  name: letsencrypt\nspec:\n  acme:\n    server: https://acme-v02.api.letsencrypt.org/directory\n    email: $LE_EMAIL_ADDRESS\n    privateKeySecretRef:\n      name: letsencrypt-private-key\n    solvers:\n    - http01:\n        ingress:\n          class: nginx\n          podTemplate:\n            spec:\n              nodeSelector:\n                \"kubernetes.io/os\": linux\nEOF\n\n\n# Wait for the cert-manager pods to be ready\necho \"Waiting for cert-manager deployment to be ready...\"\nkubectl -n $AKS_INGRESS_NAMESPACE wait --timeout=5m \\\n    --for=condition=Ready pod \\\n    --selector=app.kubernetes.io/name=cert-manager\n\n# Create a long-lived SAS token for reading from the storage account and store it in keyvault.\n# The nginx ingress controller will use this for accessing the storage account via proxy\n# by appending the SAS token to the URL when sending to the backend server.\nSAS_TOKEN=$(az storage account generate-sas \\\n    --resource-types sco --services b --permissions flpr \\\n    --expiry \"2037-12-31T23:59Z\" \\\n    --https-only \\\n    --account-name $DATA_STORAGE_ACCOUNT_NAME \\\n    --account-key $DATA_STORAGE_ACCOUNT_KEY \\\n    -otsv)\naz keyvault secret set \\\n    --vault-name $KEY_VAULT_NAME \\\n    --name StorageAccountReadSASToken \\\n    --value $SAS_TOKEN \\\n    -o none\n\n##\n## Install the nginx ingress controller, configured with the CSI secret store\n## driver to access the Azure Storage Account SAS token.\n##\n\n# Create a secret provider to access the Azure Storage Account SAS token\ncat <<EOF | kubectl apply -n $AKS_INGRESS_NAMESPACE -f -\napiVersion: secrets-store.csi.x-k8s.io/v1\nkind: SecretProviderClass\nmetadata:\n  name: k8s-nginx-ingress-secrets\nspec:\n  provider: azure\n  secretObjects:\n  - secretName: azure-secrets\n    type: Opaque\n    data:\n    - key: StorageAccountReadSASToken\n      objectName: StorageAccountReadSASToken\n  parameters:\n    usePodIdentity: \"false\"\n    useVMManagedIdentity: \"false\"\n    # The client ID of the user-assigned managed identity or application that is\n    # used for workload identity, and to access the keyvault.\n    clientID: $USER_ASSIGNED_CLIENT_ID\n    keyvaultName: $KEY_VAULT_NAME\n    tenantID: $IDENTITY_TENANT\n    cloudName: $(az cloud show --query name -otsv)\n    objects:  |\n      array:\n        - |\n          objectName: StorageAccountReadSASToken\n          objectType: secret\nEOF\n\nRELEASE_NAME=ingress-nginx\n\n# Create the credential to allow the ingress controller to use the managed identity\n# to access secrets in the keyvault.\necho \"Creating a federated credential for the ingress controller to access the managed identity $UAMI\"\naz identity federated-credential create --name nginx-ingress-access-$AKS_NAME \\\n    --identity-name $UAMI \\\n    --resource-group $PROCESSING_RESOURCE_GROUP \\\n    --issuer $AKS_OIDC_ISSUER \\\n    --subject system:serviceaccount:$AKS_INGRESS_NAMESPACE:$RELEASE_NAME \\\n    -o none\n\nhelm upgrade --install $RELEASE_NAME ingress-nginx/ingress-nginx \\\n    --namespace $AKS_INGRESS_NAMESPACE \\\n    --create-namespace \\\n    --set controller.replicaCount=2 \\\n    --set controller.nodeSelector.\"kubernetes\\.io/os\"=linux \\\n    --set defaultBackend.nodeSelector.\"kubernetes\\.io/os\"=linux \\\n    --set serviceAccount.annotations.\"azure\\.workload\\.identity/client-id\"=$USER_ASSIGNED_CLIENT_ID \\\n    --set controller.config.proxy-buffer-size=32k \\\n    --set controller.config.main-snippet=\"env STORAGE_SAS_TOKEN;\" \\\n    --set controller.config.http-snippet=\"geo \\$internal_user { $AKS_POD_CIDR 1; }\" \\\n    --set controller.admissionWebhooks.patch.nodeSelector.\"kubernetes\\.io/os\"=linux \\\n    --set controller.service.externalTrafficPolicy=Local \\\n    --set controller.service.annotations.\"service\\.beta\\.kubernetes\\.io/azure-load-balancer-resource-group\"=\"$PROCESSING_RESOURCE_GROUP\" \\\n    --set controller.service.annotations.\"service\\.beta\\.kubernetes\\.io/azure-dns-label-name\"=\"$DNS_LABEL_NAME\" \\\n    --set controller.service.loadBalancerIP=$INGRESS_PUBLIC_IP_ADDR \\\n    --set controller.image.repository=mcr.microsoft.com/oss/kubernetes/ingress/nginx-ingress-controller \\\n    --set controller.image.tag=v1.7.0-3 \\\n    --set controller.image.digest=sha256:29ad700988b2dd3e7b9b130c2625f24d5b5eae7420e3dfd6dee579a730ecbb1c \\\n    --set \"controller.extraVolumeMounts[0].name=secrets-store-inline\" \\\n    --set \"controller.extraVolumeMounts[0].mountPath=/mnt/secrets-store\" \\\n    --set \"controller.extraVolumeMounts[0].readOnly=true\" \\\n    --set \"controller.extraVolumes[0].name=secrets-store-inline\" \\\n    --set \"controller.extraVolumes[0].csi.driver=secrets-store.csi.k8s.io\" \\\n    --set \"controller.extraVolumes[0].csi.readOnly=true\" \\\n    --set \"controller.extraVolumes[0].csi.volumeAttributes.secretProviderClass=k8s-nginx-ingress-secrets\" \\\n    --set \"controller.extraEnvs[0].name=STORAGE_SAS_TOKEN\" \\\n    --set \"controller.extraEnvs[0].valueFrom.secretKeyRef.name=azure-secrets\" \\\n    --set \"controller.extraEnvs[0].valueFrom.secretKeyRef.key=StorageAccountReadSASToken\"\n\n# Helm creates the service account, but there's no way to add the label we need to it.\n# Add that manually after the fact.\nkubectl label -n $AKS_INGRESS_NAMESPACE sa/$RELEASE_NAME azure.workload.identity/use=\"true\"\n\n# Wait for the ingress controller to be ready\necho \"Waiting for ingress controller to be ready...\"\nkubectl -n $AKS_INGRESS_NAMESPACE wait --timeout=5m \\\n    --for=condition=Ready pod \\\n    --selector=app.kubernetes.io/name=$RELEASE_NAME\n\n# Deploy the ingress for the blob store proxy that forwards requests\n# to storage with a SAS token appended.\ncat <<EOF | kubectl -n $AKS_NAMESPACE apply -f -\n---\nkind: Service\napiVersion: v1\nmetadata:\n  name: blobstore-proxy\nspec:\n  type: ExternalName\n  externalName: $DATA_STORAGE_ACCOUNT_BLOB_DOMAIN\n  ports:\n  - port: 443\n---\napiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: blobstore-proxy\n  annotations:\n    cert-manager.io/cluster-issuer: letsencrypt\n    nginx.ingress.kubernetes.io/use-regex: \"true\"\n    nginx.ingress.kubernetes.io/rewrite-target: /\\$1\n    nginx.ingress.kubernetes.io/proxy-request-buffering: \"off\"\n    nginx.ingress.kubernetes.io/backend-protocol: \"HTTPS\"\n    nginx.ingress.kubernetes.io/upstream-vhost: \"$DATA_STORAGE_ACCOUNT_BLOB_DOMAIN\"\n    # Rewrite URI to include SAS token (note, the query separator has to be\n    # in the rewrite statement, and not as part of the SAS token)\n    # TODO: handle URLs that might already have a query string\n    nginx.ingress.kubernetes.io/configuration-snippet: |\n      proxy_cache off;\n      rewrite (.*) \\$1?\\$storage_sas_token;\n    # Reads the SAS token from the STORAGE_SAS_TOKEN environment variable and\n    # sets as an nginx variable so we can use it in the rewrite statement. Note\n    # that this relies on the server configmap containing a main-snippet with an\n    # \"env STORAGE_SAS_TOKEN\" statement to ensure nginx inherits that env variable\n    # from its parent.\n    nginx.ingress.kubernetes.io/server-snippet: |\n      set_by_lua_block \\$storage_sas_token { return os.getenv(\"STORAGE_SAS_TOKEN\") }\nspec:\n  ingressClassName: nginx\n  tls:\n  - hosts:\n    - $INGRESS_FQDN\n    secretName: stac-certificate\n  rules:\n  - host: $INGRESS_FQDN\n    http:\n      paths:\n      - path: /blobstore/(.*)\n        pathType: Prefix\n        backend:\n          service:\n            name: blobstore-proxy\n            port:\n              number: 443\n---\napiVersion: networking.k8s.io/v1\nkind: Ingress\nmetadata:\n  name: stac-browser\n  annotations:\n    cert-manager.io/cluster-issuer: letsencrypt\n    nginx.ingress.kubernetes.io/use-regex: \"true\"\n    nginx.ingress.kubernetes.io/rewrite-target: /\\$2\nspec:\n  ingressClassName: nginx\n  tls:\n  - hosts:\n    - $INGRESS_FQDN\n    secretName: stac-certificate\n  rules:\n  - host: $INGRESS_FQDN\n    http:\n      paths:\n      - path: /browser(/|$)(.*)\n        pathType: Prefix\n        backend:\n          service:\n            name: stac-browser\n            port:\n              number: 8080\nEOF\n\n# Deploy the auth proxy if selected\n[[ -n \"$SECURE_STAC_ENDPOINTS\" ]] && $PRJ_ROOT/deploy/scripts/secure-stac-endpoints.sh\n\ncat <<EOF\n\n\n\n**** The STAC API is available at: https://$INGRESS_FQDN/api/\nThe TLS certificate may not have been issued yet, so you may see a warning in your browser.\nIf you wish to wait, you can run the following command to wait until the certificate is ready:\n  kubectl -n $AKS_NAMESPACE wait --timeout=10m --for=condition=Ready certificate stac-certificate\n\nIf this command times out, then it is possible there was an error with cert generation. You can\ninspect the cert-manager logs to see if there was an error:\n  kubectl -n $AKS_INGRESS_NAMESPACE logs -l app=cert-manager\nEOF\n", "num_lines": 510}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nset -e\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\n\n# Setup required parameters\nENV_CODE=${1:-${ENV_CODE}}\nLOCATION=${2:-${LOCATION}}\nJUMPBOX_PASSWORD=${3:-${JUMPBOX_PASSWORD}}\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$LOCATION\" ]]\n  then\n    echo \"Location value not supplied\"\n    exit 1\nfi\n\nif [[ -z \"$JUMPBOX_PASSWORD\" ]]\n  then\n    echo \"Jumpbox Password not supplied\"\n    exit 1\nfi\n\n# Setup parameters\nJUMPBOX_USERNAME=${4:-${JUMPBOX_USERNAME:-\"adminuser\"}}\nENV_TAG=${5:-${ENV_TAG:-\"stac-${ENV_CODE}\"}}\nDEPLOYMENT_NAME=${6:-${DEPLOYMENT_NAME:-\"${ENV_TAG}-deploy\"}}\nCONFIGURE_POD_IDENTITY=${7:-${CONFIGURE_POD_IDENTITY:-\"false\"}}\nENABLE_PUBLIC_ACCESS=${8:-${ENABLE_PUBLIC_ACCESS:-\"false\"}}\nUSER_OBJ_ID=${USER_OBJ_ID:-\"$(az ad signed-in-user show --query id --output tsv 2> /dev/null || echo '')\"}\nPOSTGRES_PRIVATE_ENDPOINT_DISABLED=${POSTGRES_PRIVATE_ENDPOINT_DISABLED:-false}\nif [[ -n \"$DNS_PREFIX\" ]]; then\n  DNS_ARG=\"ingressPublicIPDnsPrefix=$DNS_PREFIX\"\nfi\n\nif [[ -z \"$USER_OBJ_ID\" ]]; then\n  # If there was no \"id\" field, then try \"objectId\"\n  USER_OBJ_ID=\"$(az ad signed-in-user show --query objectId --output tsv 2> /dev/null || echo '')\"\nfi\nif [[ -z \"$USER_OBJ_ID\" ]]; then\n    echo \"Set USER_OBJ_ID environment variable after retrieving the value from device with an approved MDM provider like Intune\"\n    echo \"To get USER_OBJ_ID, run 'az ad signed-in-user show --query id --output tsv'\"\n    exit 1\nfi\n\n# Register the workload identity feature, and wait for it to be registered.\nif [[ $(az feature show --namespace \"Microsoft.ContainerService\" --name \"EnableWorkloadIdentityPreview\" --query properties.state -otsv) != \"Registered\" ]]; then\n  echo \"Registering workload identity preview with AKS.\"\n  az feature register --namespace \"Microsoft.ContainerService\" --name \"EnableWorkloadIdentityPreview\"\n  workload_identity_registered=true\nfi\nwhile [[ $(az feature show --namespace \"Microsoft.ContainerService\" --name \"EnableWorkloadIdentityPreview\" --query properties.state -otsv) != \"Registered\" ]]; do\n  echo \"Waiting for the workload identity preview feature to be registered.\"\n  sleep 10\ndone\n# If we actually registered the feature, then we need to re-register the provider to get the change to propagate\nif [[ $workload_identity_registered ]]; then\n  az provider register --namespace \"Microsoft.ContainerService\"\nfi\n\n# Captures the Azure cloud endpoints/suffixes\naz cloud show -o json > $PRJ_ROOT/deploy/cloud_endpoints.json\n\n# Minimum required version of Kubernetes is 1.22.0. We assume all regions have atleast 1.22.0 or later version\nAKS_VERSION=$(az aks get-versions -l $LOCATION --query 'orchestrators[?!isPreview].orchestratorVersion' -otsv | sort -rV | head -n1)\n\nDEPLOYMENT_SCRIPT=\"az deployment sub create -o none -l $LOCATION -n $DEPLOYMENT_NAME \\\n    -f $PRJ_ROOT/deploy/bicep/main.bicep \\\n    -p \\\n    location=$LOCATION \\\n    environmentCode=$ENV_CODE \\\n    environment=$ENV_TAG \\\n    kubernetesVersion=$AKS_VERSION \\\n    jumpboxAdminUsername=$JUMPBOX_USERNAME \\\n    jumpboxAdminPassword=$JUMPBOX_PASSWORD \\\n    enablePublicAccess=$ENABLE_PUBLIC_ACCESS \\\n    privateEndpointDisabled=$POSTGRES_PRIVATE_ENDPOINT_DISABLED \\\n    owner_aad_object_id=$USER_OBJ_ID $DNS_ARG\"\n\n$DEPLOYMENT_SCRIPT\n\nfor script in $(az deployment-scripts list -g \"${ENV_CODE}-vnet-rg\" --query \"[].name\" -o tsv); do\n  az deployment-scripts delete -g \"${ENV_CODE}-vnet-rg\" --yes --name $script\ndone", "num_lines": 92}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\n\nif [[ -z \"$ENV_CODE\" ]]\n  then\n    echo \"Environment Code value not supplied\"\n    exit 1\nfi\n\nset -e\n\nENV_NAME=${ENV_NAME:-\"stac-${ENV_CODE}\"}\nVNET_RESOURCE_GROUP=${VNET_RESOURCE_GROUP:-\"${ENV_CODE}-vnet-rg\"}\nDATA_RESOURCE_GROUP=${DATA_RESOURCE_GROUP:-\"${ENV_CODE}-data-rg\"}\nVNET_NAME=${VNET_NAME:-\"${ENV_CODE}-stac-vnet\"}\nJUMPBOX_SUBNET_NAME=${JUMPBOX_SUBNET_NAME:-\"jumpbox-subnet\"}\n\necho \"Getting Jumpbox Subnet ID\"\nJUMPBOX_SUBNET_ID=$(az network vnet subnet show -g ${VNET_RESOURCE_GROUP} --vnet-name ${VNET_NAME} -n ${JUMPBOX_SUBNET_NAME} -o tsv --query 'id')\n\necho \"Getting Keyvault name\"\nKEYVAULT_NAME=$(az keyvault list --resource-group ${DATA_RESOURCE_GROUP} --query '[0].name' -o tsv)\n\necho \"Securing Keyvault to be accessed only on jumpbox subnet\"\naz keyvault network-rule add --name ${KEYVAULT_NAME} --resource-group ${DATA_RESOURCE_GROUP} --subnet ${JUMPBOX_SUBNET_ID} -o none\naz keyvault update --name ${KEYVAULT_NAME} --resource-group ${DATA_RESOURCE_GROUP} --set properties.networkAcls.defaultAction=Deny -o none", "num_lines": 31}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\nAKS_NAMESPACE=${AKS_NAMESPACE:-\"pgstac\"}\nAKS_INGRESS_NAMESPACE=${AKS_INGRESS_NAMESPACE:-\"ingress\"}\n\n[[ -z \"$ENV_CODE\" ]] && { echo \"Environment Code value not supplied\"; exit 1; }\n\nset -a\nset -e\necho \"Retrieving required properties from Azure resources.\"\nPROCESSING_RESOURCE_GROUP=${PROCESSING_RESOURCE_GROUP:-\"${ENV_CODE}-processing-rg\"}\nAAD_ENDPOINT=$(az cloud show --query endpoints.activeDirectory -otsv)\nTENANT_ID=$(az account show --query tenantId -otsv)\n\n# Retrieve the public IP address we created in the deployment\nFQDN=$(az network public-ip show -g $PROCESSING_RESOURCE_GROUP \\\n  -n ${ENV_CODE}-stac-ingress-public-ip --query dnsSettings.fqdn -o tsv)\nDNS_DOMAIN=${FQDN#*.}\n\n# Create an Azure AD application to perform authentication on the STAC endpoints\necho \"Creating Azure AD application to secure the STAC endpoints\"\nAPP_ID=$(az ad app create \\\n  --display-name \"STAC Endpoints for $ENV_CODE\" \\\n  --sign-in-audience AzureADMyOrg \\\n  --web-redirect-uris \"https://$FQDN/oauth2/callback\" \\\n  --optional-claims @$PRJ_ROOT/deploy/data/claims.json \\\n  --required-resource-accesses @$PRJ_ROOT/deploy/data/resource_access.json \\\n  --app-roles @$PRJ_ROOT/deploy/data/roles.json \\\n  --query \"appId\" -otsv)\n# Generate a password for the app\nAPP_PW=$(az ad app credential reset \\\n  --id $APP_ID \\\n  --append \\\n  --display-name \"oauth2-proxy access for STAC endpoints on $(az account show --query name -otsv)\" \\\n  --query \"password\" -otsv)\n\nhelm repo add oauth2-proxy https://oauth2-proxy.github.io/manifests || true\nhelm repo update\n\n# Install the oauth2-proxy Helm chart\necho \"Installing the oauth2-proxy Helm chart\"\nAKS_RESOURCE_GROUP=${AKS_RESOURCE_GROUP:-${PROCESSING_RESOURCE_GROUP}}\nAKS_CLUSTER_NAME=$(az aks list -g ${AKS_RESOURCE_GROUP} --query \"[?tags.type && tags.type == 'k8s'].name\" -otsv)\nAKS_ISSUER_URL=$(az aks show --resource-group $AKS_RESOURCE_GROUP --name $AKS_CLUSTER_NAME --query oidcIssuerProfile.issuerUrl -otsv)\nOAUTH_PROXY_VALUES_FILE=$(mktemp -t oauth2-proxy-values)\ntrap 'rm -f -- \"$OAUTH_PROXY_VALUES_FILE\"' EXIT\ncat > $OAUTH_PROXY_VALUES_FILE <<EOF\nreplicaCount: 2\nconfig:\n  clientID: $APP_ID\n  clientSecret: $APP_PW\n  cookieSecret: $(openssl rand -base64 32 | tr -- '+/' '-_')\n\ningress:\n  enabled: true\n  className: nginx\n  path: /oauth2\n  pathType: Prefix\n  hosts:\n    - $FQDN\n  tls:\n    - hosts:\n        - $FQDN\n      secretName: stac-certificate\n  annotations:\n    cert-manager.io/cluster-issuer: letsencrypt\n\nextraArgs:\n  provider: oidc\n  oidc-issuer-url: $AAD_ENDPOINT/$TENANT_ID/v2.0\n  # Use the next two lines instead to support multi-tenant authentication.\n  # Note that if a tenant does not include an e-mail address in the payload\n  # returned by authentication, then oauth2-proxy will fail to authenticate.\n  # oidc-issuer-url: $AAD_ENDPOINT/common/v2.0\n  # insecure-oidc-skip-issuer-verification: true\n  code-challenge-method: S256\n  # AAD doesn't always return an e-mail address in the email claim. Use\n  # the preferred_username field as it seems to be present in most cases.\n  # If this claim is missing, authentication will fail.\n  oidc-email-claim: preferred_username\n  # Look for \"groups\" in the roles claim, in case we assigned app roles\n  # to the user.\n  oidc-groups-claim: roles\n  cookie-refresh: 10m\n  cookie-expire: 15m\n  cookie-domain: .$DNS_DOMAIN\n  # Pass authentication information to the nginx ingress controller\n  pass-access-token: true\n  set-xauthrequest: true\n  set-authorization-header: true\n  silence-ping-logging: true\n  whitelist-domain: .$FQDN\n  scope: openid email profile\n  # Allow authentication from a JWT Bearer token. Only token issued\n  # by the issuers listed in oidc-issuer-url and extra-jwt-issuers will\n  # be trusted. The aud claim must also match the right-hand side of the\n  # pair in extra-jwt-issuers. In this case, we're trusting tokens issued\n  # by the AKS cluster and the Azure AD app we created above.\n  skip-jwt-bearer-tokens: true\n  extra-jwt-issuers: \"$AKS_ISSUER_URL=$AKS_ISSUER_URL,$AAD_ENDPOINT/$TENANT_ID/v2.0=$APP_ID\"\n  show-debug-on-error: true\n  ##\n  ## Authorization limits. You can limit authorization to certain groups\n  ## and/or e-mail domains.\n  ##\n  # Change this if you want to limit access to certain e-mail domains.\n  email-domain: \"*\"\n  # Uncomment to limit access to certain groups\n  #allowed-group: \"STAC.Read,STAC.Write\"\n\nservice:\n  portNumber: 4180\n\nnodeSelector:\n  kubernetes.io/os: linux\nEOF\n\nhelm upgrade --install oauth2-proxy oauth2-proxy/oauth2-proxy \\\n    --create-namespace \\\n    --namespace $AKS_INGRESS_NAMESPACE \\\n    -f $OAUTH_PROXY_VALUES_FILE\nrm -f $OAUTH_PROXY_VALUES_FILE\n\necho \"Waiting for oauth2-proxy deployment to be ready\"\nkubectl -n $AKS_INGRESS_NAMESPACE wait --for=condition=Ready pod \\\n  -l app.kubernetes.io/name=oauth2-proxy --timeout=5m\n\n# Apply annotations to enable auth on the STAC endpoints\nkubectl -n $AKS_NAMESPACE annotate ingress stac-browser \\\n    nginx.ingress.kubernetes.io/auth-url='https://$host/oauth2/auth' \\\n    nginx.ingress.kubernetes.io/auth-signin='https://$host/oauth2/start?rd=$escaped_request_uri'\nkubectl -n $AKS_NAMESPACE annotate ingress fast-stac-api \\\n    nginx.ingress.kubernetes.io/auth-url='https://$host/oauth2/auth' \\\n    nginx.ingress.kubernetes.io/auth-signin='https://$host/oauth2/start?rd=$escaped_request_uri'\nkubectl -n $AKS_NAMESPACE annotate ingress blobstore-proxy \\\n    nginx.ingress.kubernetes.io/auth-url='https://$host/oauth2/auth' \\\n    nginx.ingress.kubernetes.io/auth-signin='https://$host/oauth2/start?rd=$escaped_request_uri'\nkubectl -n $AKS_NAMESPACE annotate ingress blobstore-proxy nginx.ingress.kubernetes.io/auth-snippet='\n  # Allow internal requests to bypass auth. $internal_user is set up when the\n  # chart is deployed using the main-snippet value in the configmap. The variable\n  # is true if the caller IP is in the k8s cluster pod cidr range.\n  if ($internal_user) {\n    return 200;\n  }'\n", "num_lines": 150}
{"repo_name": "Azure-Orbital-STAC", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\n# Copyright (c) Microsoft Corporation.\n# Licensed under the MIT license.\n\nPRJ_ROOT=\"$(cd `dirname \"${BASH_SOURCE}\"`/../..; pwd)\"\nENV_CODE=${1:-${ENV_CODE}}\nLOCATION=${2:-${LOCATION}}\nLE_EMAIL_ADDRESS=${3:-${LE_EMAIL_ADDRESS}}\nJUMPBOX_PASSWORD=${4:-${JUMPBOX_PASSWORD}}\nJUMPBOX_USERNAME=${5:-${JUMPBOX_USERNAME:-\"adminuser\"}}\n\nset -e\n\n[[ -z \"$ENV_CODE\" ]] && { echo \"Environment Code value not supplied\"; exit 1; }\n[[ -z \"$LOCATION\" ]] && { echo \"Location value not supplied\"; exit 1; }\n[[ -z \"$JUMPBOX_PASSWORD\" ]] && { echo \"Jumpbox Password not supplied\"; exit 1; }\n[[ -z \"$LE_EMAIL_ADDRESS\" ]] && { echo \"Let's Encrypt e-mail address (LE_EMAIL_ADDRESS) not specified\"; exit 1; }\n\necho \"Performing bicep template deployment\"\n$PRJ_ROOT/deploy/scripts/install.sh \"$ENV_CODE\" \"$LOCATION\" \"$JUMPBOX_PASSWORD\" \"$JUMPBOX_USERNAME\"\n\necho \"Building containers and Deploying to Infra\"\n$PRJ_ROOT/deploy/scripts/build.sh \"$ENV_CODE\"\n\necho \"Performing configuration and Deploying Apps\"\nLE_EMAIL_ADDRESS=\"$LE_EMAIL_ADDRESS\" \\\n$PRJ_ROOT/deploy/scripts/configure.sh \"$ENV_CODE\"\n\necho \"Securing Keyvault access\"\n$PRJ_ROOT/deploy/scripts/secure-keyvault.sh \"$ENV_CODE\"\n", "num_lines": 32}
{"repo_name": "azure-osconfig", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# This script requires Azure CLI version 2.25.0 or later. Check version with `az --version`.\n\n# SERVICE_PRINCIPAL_NAME: Must be unique within your AD tenant\nSERVICE_PRINCIPAL_NAME=<service_principal_name>\n# Replace with valid Azure Subscription ID\nSUBSCRIPTION_ID=<subscription_id>\n\n# Create the service principal with rights scoped to the subscription.\nSP_PASSWD=$(az ad sp create-for-rbac --name $SERVICE_PRINCIPAL_NAME --scopes /subscriptions/$SUBSCRIPTION_ID --role Contributor --query password --output tsv)\nSP_APP_ID=$(az ad sp list --display-name $SERVICE_PRINCIPAL_NAME --query [].appId --output tsv)\n\n# Output the service principal's credentials; use these in your services and applications to authenticate.\necho \"Service principal ID: $SP_APP_ID\"\necho \"Service principal password: $SP_PASSWD\"", "num_lines": 15}
{"repo_name": "azure-osconfig", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Generates the binary footprints used to check for binary size issues\n# By default, uses the latest published package (prod/insiders-fast) unless\n# regex filter is given.\n# Usage: ./generate_binary_footprint [filter]\nif ! [ -x \"$(command -v jq)\" ]; then\n  echo 'Error: jq is not installed.' >&2\n  exit 1\nfi\n\n# Absolute path to this script\nSCRIPT=$(readlink -f $0)\nSCRIPTPATH=`dirname $SCRIPT`\nBaseDir=`realpath $SCRIPTPATH/../binary-footprint-baseline`\n\ndistros=(\"ubuntu-18.04\", \"ubuntu-20.04\", \"debian-9\")\ndistroPathUbuntu1804=\"https://packages.microsoft.com/ubuntu/18.04/prod/pool/main/o/osconfig/\"\ndistroPathUbuntu2004=\"https://packages.microsoft.com/ubuntu/20.04/prod/pool/main/o/osconfig/\"\ndistroPathDebian9=\"https://packages.microsoft.com/debian/9/multiarch/prod/pool/main/o/osconfig/\"\nJSON=\"[]\"\nfor distro in ${distros[@]}; do distro=$(echo $distro | tr -d ',');\n\n  case $distro in\n    (\"ubuntu-18.04\") distroPath=$distroPathUbuntu1804;;\n    (\"ubuntu-20.04\") distroPath=$distroPathUbuntu2004;;\n    (\"debian-9\")     distroPath=$distroPathDebian9;;\n  esac\n\n  for arch in \"x86_64\", \"aarch64\", \"armv7l\"; do arch=$(echo $arch | tr -d ',');\n    wget -q -O tmp.html $distroPath\n    size=$((tr -s ' ' <<< `cat tmp.html | grep -E \">osconfig.*$1$arch.deb<\" | tail -1`) | cut -d ' ' -f 5 | tr -d '\\r\\n')\n    file=$((tr -s ' ' <<< `cat tmp.html | grep -E \">osconfig.*$1$arch.deb<\" | tail -1`) | grep -o '>osconfig.*<' | tr -d '<>')\n    rm tmp.html\n    echo \"Generating binary footprint for $file ($distro/$arch): $size bytes\"\n    json=\"[{ \\\"distro\\\": \\\"$distro\\\", \\\"arch\\\": \\\"$arch\\\", \\\"sizeBytes\\\": $size, \\\"file\\\": \\\"$file\\\"}]\"\n    JSON=$(echo $JSON | jq --argjson packageInfo \"$json\" '. |= . + $packageInfo')\n  done\ndone\n\necho $JSON | jq '.' > $BaseDir/baseline.json", "num_lines": 40}
{"repo_name": "azure-policy", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Gets Azure Cosmos DB Resource Provider Aliases that can be used in a custom policy definition\n\nsubscription_id=\"$(az account show -o tsv --query \"id\")\"\n\naz provider show --namespace Microsoft.DocumentDB --expand \"resourceTypes/aliases\" --query \"resourceTypes[].aliases[].name\"\n\naz graph query -q \"Resources | where type=~'microsoft.DocumentDB' | limit 1 | project aliases\" --subscriptions $subscription_id\n", "num_lines": 10}
{"repo_name": "azure-policy", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\nresource_group_name=\"my-resource-group-name\"\ndefinition_name=\"audit-cosmosdb-throughput\"\nassignment_name=\"audit-cosmosdb-throughput-$resource_group_name\"\ndisplay_name=\"Audit Cosmos DB Throughput in Resource Group $resource_group_name\"\nmax_rus=400\n\n# Get the resource group ID so we can set it as policy assignment audit scope\nresource_group_id=\"$(az group show -n \"$resource_group_name\" -o tsv --query \"id\")\"\n\n# Assign policy\naz policy assignment create \\\n\t--sku standard \\\n\t--name \"$assignment_name\" \\\n\t--display-name \"$display_name\" \\\n\t--scope \"$resource_group_id\" \\\n\t--policy \"$definition_name\" \\\n\t--params \"{ \\\"throughputMax\\\": { \\\"type\\\": \\\"integer\\\", \\\"value\\\": $max_rus } }\"\n", "num_lines": 21}
{"repo_name": "azure-policy", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nrules_url=\"https://raw.githubusercontent.com/Azure/azure-policy/master/samples/CosmosDB/audit-cosmosdb-throughput/azurepolicy.rules.json\"\nparams_url=\"https://raw.githubusercontent.com/Azure/azure-policy/master/samples/CosmosDB/audit-cosmosdb-throughput/azurepolicy.parameters.json\"\n\naz policy definition create \\\n\t--name 'audit-cosmosdb-throughput' \\\n\t--display-name 'Audit Cosmos DB Throughput Exceeding Max' \\\n\t--description 'Audit Cosmos DB Throughput Exceeding Max' \\\n\t--rules $rules_url \\\n\t--params $params_url \\\n\t--mode All\n", "num_lines": 13}
{"repo_name": "azure-policy", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nresourceGroupName=\"cosmos\"\ndefinitionName=\"cosmosdb-multiple-write-locations\"\ndefinitionDisplayName=\"Cosmos DB Multiple Write Locations\"\ndefinitionDescription=\"Cosmos DB Multiple Write Locations: Audit or Deny whether setting is as specified\"\ndefinitionRulesUrl=\"https://raw.githubusercontent.com/Azure/azure-policy/master/samples/CosmosDB/cosmos-db-multiple-write-locations/azurepolicy.rules.json\"\ndefinitionParamsUrl=\"https://raw.githubusercontent.com/Azure/azure-policy/master/samples/CosmosDB/cosmos-db-multiple-write-locations/azurepolicy.parameters.json\"\nassignmentName=\"cosmosdb-multiple-write-locations-audit\"\nassignmentDisplayName=\"Cosmos DB Multiple Write Locations - Audit\"\n\naz policy definition create \\\n    --name \"$resourceGroupName\" \\\n    --metadata \"\\\"category\\\"=\\\"Cosmos DB\\\"\" \\\n    --display-name \"$definitionDisplayName\" \\\n    --description \"$definitionDescription\" \\\n    --rules \"$definitionRulesUrl\" \\\n    --params \"$definitionParamsUrl\" \\\n    --mode All\n\nGet the resource group ID so we can set it as policy assignment audit scope\nresourceGroupId=\"$(az group show -n \"$resourceGroupName\" -o tsv --query \"id\")\"\n\naz policy assignment create \\\n    --sku standard \\\n    --name \"$assignmentName\" \\\n    --scope \"$resourceGroupId\" \\\n    --policy \"$definitionName\" \\\n    --params \"{ \\\"multipleWriteLocationsMustBeEnabled\\\": { \\\"type\\\": \\\"boolean\\\", \\\"value\\\": $true } }\"\n", "num_lines": 30}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\napt-get -y install nginx\necho \"stream { upstream postgresql { server $1.postgres.database.azure.com:5432; } server { listen 5432; proxy_pass postgresql; } }\" >> /etc/nginx/nginx.conf\nservice nginx restart\nupdate-rc.d nginx defaults", "num_lines": 9}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nSERVERNAME=$1\nUSERNAME=$2\nPASSWORD=$3\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\napt-get -y install pgbouncer\necho \"\\\"$USERNAME@$SERVERNAME\\\" \\\"$PASSWORD\\\"\" > /etc/pgbouncer/userlist.txt\nwget https://www.digicert.com/CACerts/BaltimoreCyberTrustRoot.crt\nopenssl x509 -inform DER -in BaltimoreCyberTrustRoot.crt -text -out /etc/root.crt\ncp pgbouncer.ini /etc/pgbouncer/pgbouncer.ini\nsed -i \"s/SERVERNAME/$SERVERNAME/g\" /etc/pgbouncer/pgbouncer.ini\nservice pgbouncer restart\nupdate-rc.d pgbouncer defaults\nnetstat -tulpn | grep \"pgbouncer\"\nsleep 60", "num_lines": 18}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nSERVERNAME=$1\nUSERNAME=$2\nPASSWORD=$3\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\n\n# Install Pgpool II and Memcached\napt-get -y install pgpool2 memcached\n\n# Pgpool query cache requires a work directory to record table oids\nmkdir -p /var/log/pgpool/oiddir\nchown postgres:postgres /var/log/pgpool/oiddir\n\n# Before modifying Pgpool and Memcached config files, save them \ncp /etc/pgpool2/pgpool.conf  /etc/pgpool2/pgpool.conf.save\ncp /etc/pgpool2/pool_hba.conf /etc/pgpool2/pool_hba.conf.save\ncp /etc/memcached.conf /etc/memcached.conf.save\n\n# Create self-signed certificate to allow connecting to Pgpool using SSL\n# Note: Adjust this step to meet your security requirements\nopenssl req -new -newkey rsa:4096 -days 3650 -nodes -x509 -subj \"/C=US/ST=Denial/L=Seattle/O=Dis/CN=www.pgpooltest.org\" -keyout /etc/pgpool2/server.key  -out /etc/pgpool2/server.crt\n\n## Modify Pgpool config ##\n\n# Turn SSL on\nsed -i 's/ssl = off/ssl = on/g' /etc/pgpool2/pgpool.conf\n\n# Use SSL key and cert created above\nsed -i \"s/#ssl_key = '.\\/server.key'/ssl_key = '\\/etc\\/pgpool2\\/server.key'/g\" /etc/pgpool2/pgpool.conf\nsed -i \"s/#ssl_cert = '.\\/server.cert'/ssl_cert = '\\/etc\\/pgpool2\\/server.crt'/g\" /etc/pgpool2/pgpool.conf\n\n# Accept all incoming connections \nsed -i \"s/listen_addresses = 'localhost'/listen_addresses = '*'/g\" /etc/pgpool2/pgpool.conf\n\n# Set Azure PostgreSQL backend\nsed -i \"s/backend_hostname0 = 'localhost'/backend_hostname0 = '$SERVERNAME.postgres.database.azure.com'/g\" /etc/pgpool2/pgpool.conf \n\n# Use pool_hba.conf for client authentication\nsed -i 's/enable_pool_hba = off/enable_pool_hba = on/g' /etc/pgpool2/pgpool.conf\n\n# Enable query cache\nsed -i \"s/memory_cache_enabled = off/memory_cache_enabled = on/g\" /etc/pgpool2/pgpool.conf \n\n# Use Memcached as query cache store\nsed -i \"s/memqcache_method = 'shmem'/memqcache_method = 'memcached'/g\" /etc/pgpool2/pgpool.conf\n\n# Require all clients connecting to Pgpool to authenticate with password (scram-sha-256 in this case)\necho \"host all all 0.0.0.0/0 scram-sha-256\" > /etc/pgpool2/pool_hba.conf\n\n# Write pool_passwd used by Pgpool for password authentication with Azure PostgreSQL backend\necho $USERNAME@$SERVERNAME:$PASSWORD > /etc/pgpool2/pool_passwd\nchmod 600 /etc/pgpool2/pool_passwd\nchown postgres:postgres /etc/pgpool2/*\n\n## Modify Memcached config ##\n\n# Allow Memcached to use 1024 MB of memory\nsed -i \"s/m 64/m 1024/g\" /etc/memcached.conf\n\n## Start Pgpool and Memcached services ##\n\n# Start Memcached\nservice memcached restart\n\n# Set defaults for Pgpool service\necho \"PGPOOL_CONFIG_FILE=/etc/pgpool2/pgpool.conf\" >> /etc/default/pgpool2\necho \"PGPOOL_HBA_CONFIG_FILE=/etc/pgpool2/pool_hba.conf\" >> /etc/default/pgpool2\necho \"PGPOOL_PCP_CONFIG_FILE=/etc/pgpool2/pcp.conf\" >> /etc/default/pgpool2\necho \"PGPOOL_PID_FILE=/var/run/postgresql/pgpool.pid\" >> /etc/default/pgpool2\nupdate-rc.d pgpool2 defaults\n\n# Start Pgpool\nservice pgpool2 restart\n\nsleep 60", "num_lines": 78}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nSERVERNAME=$1\nUSERNAME=$2\nPASSWORD=$3\nexport DEBIAN_FRONTEND=noninteractive\nrm /var/lib/apt/lists/* -vrf\napt-get -y update\napt-get -y install postgresql-client\nexport PGSSLMODE=require\nexport PGPASSWORD=$PASSWORD\npsql -h $SERVERNAME.postgres.database.azure.com -p 5432 -U $USERNAME@$SERVERNAME -d postgres -a -f init.sql", "num_lines": 12}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# PURPOSE\n# Migrate Azure Database for PostgreSQL Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\n# \n# DESCRIPTION\n# Pricing tiers in Azure Database for PostgreSQL - Single Server\n# https://docs.microsoft.com/en-us/azure/postgresql/concepts-pricing-tiers\n# \n# Currently modifying pricing tier (to and from Basic) is not yet supported. \n# This script helps in migrating an existing database from Basic Pricing Tier to \n# General Purpose/Memory Optimized Pricing Tier. \n# This script uses pg_dump to extract a PostgreSQL database into a dump file\n# and pg_restore to restore the PostgreSQL database from an archive file created by pg_dump.\n#\n# Migrate your PostgreSQL database using dump and restore\n# https://docs.microsoft.com/en-us/azure/postgresql/howto-migrate-using-dump-and-restore\n#\n# PREREQUISITES\n# Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\n# postgresql-client tools - pg_dump and pg_restore (https://www.postgresql.org/download/linux)\n# \n# NOTE\n# Target server and database are created in this script.\n# Please modify the script to specify different options for creation\n# https://docs.microsoft.com/en-us/cli/azure/postgres/server?view=azure-cli-latest\n# \n# USAGE\n# bash pgmigrate.sh\n#         --source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --source-resource-group-name 'sourceRG'\n#         --source-server-name 'sourcepg'\n#         --source-username 'sourceuser'\n#         --source-password 'P@ssw0rd1'\n#         --source-database-name 'sourcedb'\n#         --target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --target-resource-group-name 'targetRG'\n#         --target-region 'eastus'\n#         --target-server-name 'targetpg'\n#         --target-username 'targetuser'\n#         --target-password 'P@ssw0rd2'\n#         --target-database-name 'targetdb'\n#         --target-sku 'GP_Gen5_2'\n#\n\nfunction usage()\n{\n    echo \"\"\n    echo \"PURPOSE\"\n    echo \"Migrate Azure Database for PostgreSQL Server from Basic Pricing Tier to General Purpose/Memory Optimized Pricing Tier\"\n    echo \"\"\n    echo \"DESCRIPTION\"\n    echo \"Pricing tiers in Azure Database for PostgreSQL - Single Server\"\n    echo \"https://docs.microsoft.com/en-us/azure/postgresql/concepts-pricing-tiers\"\n    echo \"\"\n    echo \"Currently modifying pricing tier (to and from Basic) is not yet supported.\"\n    echo \"This script helps in migrating an existing database from Basic Pricing Tier to\"\n    echo \"General Purpose/Memory Optimized Pricing Tier.\"\n    echo \"This script uses pg_dump to extract a PostgreSQL database into a dump file\"\n    echo \"and pg_restore to restore the PostgreSQL database from an archive file created by pg_dump.\"\n    echo \"\"\n    echo \"Migrate your PostgreSQL database using dump and restore\"\n    echo \"https://docs.microsoft.com/en-us/azure/postgresql/howto-migrate-using-dump-and-restore\"\n    echo \"\"\n    echo \"PREREQUISITES\"\n    echo \"Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\"\n    echo \"postgresql-client tools - pg_dump and pg_restore (https://www.postgresql.org/download/linux)\"\n    echo \"\"\n    echo \"NOTE\"\n    echo \"Target server and database are created in this script.\"\n    echo \"Please modify the script to specify different options for server creation\"\n    echo \"https://docs.microsoft.com/en-us/cli/azure/postgres/server?view=azure-cli-latest\"\n    echo \"\"\n    echo \"USAGE\"\n    echo \"bash pgmigrate.sh\"\n    echo -e \"\\t--source-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--source-resource-group-name 'sourceRG'\"\n    echo -e \"\\t--source-server-name 'sourcepg'\"\n    echo -e \"\\t--source-username 'sourceuser'\"\n    echo -e \"\\t--source-password 'P@ssw0rd1'\"\n    echo -e \"\\t--source-database-name 'sourcedb'\"\n    echo -e \"\\t--target-subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--target-resource-group-name 'targetRG'\"\n    echo -e \"\\t--target-region 'eastus'\"\n    echo -e \"\\t--target-server-name 'targetpg'\"\n    echo -e \"\\t--target-username 'targetuser'\"\n    echo -e \"\\t--target-password 'P@ssw0rd2'\"\n    echo -e \"\\t--target-database-name 'targetdb'\"\n    echo -e \"\\t--target-sku 'GP_Gen5_2'\"\n    echo \"\"\n}\n\nPARAMS=\"\"\nwhile (( \"$#\" )); do\n  case \"$1\" in\n    -h | --help)\n      usage\n      exit\n      ;;\n    -a|--source-subscription-id)\n      SOURCE_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -b|--source-resource-group-name)\n      SOURCE_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -c|--source-server-name)\n      SOURCE_SERVER_NAME=$2\n      shift 2\n      ;;\n    -d|--source-username)\n      SOURCE_USERNAME=$2\n      shift 2\n      ;;\n    -e|--source-password)\n      SOURCE_PASSWORD=$2\n      shift 2\n      ;;\n    -f|--source-database-name)\n      SOURCE_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -g|--target-subscription-id)\n      TARGET_SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -h|--target-resource-group-name)\n      TARGET_RESOURCE_GROUP_NAME=$2\n      shift 2\n      ;;\n    -i|--target-region)\n      TARGET_REGION=$2\n      shift 2\n      ;;\n    -j|--target-server-name)\n      TARGET_SERVER_NAME=$2\n      shift 2\n      ;;\n    -k|--target-username)\n      TARGET_USERNAME=$2\n      shift 2\n      ;;\n    -l|--target-password)\n      TARGET_PASSWORD=$2\n      shift 2\n      ;;\n    -m|--target-database-name)\n      TARGET_DATABASE_NAME=$2\n      shift 2\n      ;;\n    -n|--target-sku)\n      TARGET_SKU=$2\n      shift 2\n      ;;\n    --) # end argument parsing\n      shift\n      break\n      ;;\n    -*|--*=) # unsupported flags\n      echo \"Error: Unsupported flag $1\" >&2\n      exit 1\n      ;;\n    *) # preserve positional arguments\n      PARAMS=\"$PARAMS $1\"\n      shift\n      ;;\n  esac\ndone\n# set positional arguments in their proper place\neval set -- \"$PARAMS\"\n\n# Prerequisites - Install Azure CLI and postgresql-client package\nif ! [ -x \"$(command -v az)\" ]; then\n  echo 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v pg_dump)\" ]; then\n  echo 'Error: pg_dump command does not exist. Please install from https://www.postgresql.org/download' >&2\n  exit 1\nfi\n\nif ! [ -x \"$(command -v pg_restore)\" ]; then\n  echo 'Error: pg_restore command does not exist. Please install from https://www.postgresql.org/download' >&2\n  exit 1\nfi\n\n# Login to source subscription\naz login\naz account set --subscription \"$SOURCE_SUBSCRIPTION_ID\"\n\n# Set PG SSL Mode\nexport PGSSLMODE=require\n\n# Firewall rule name to allow the current VM\nexport FIREWALLRULENAME=\"AllowAllIps$(date +%s)\"\n\n# Create firewall rule on the source server to allow connections from current VM\naz postgres server firewall-rule create -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Export pg password to be used by the pg_dump command\nexport PGPASSWORD=$SOURCE_PASSWORD\n\n# Export PG database name to be used by the pg_dump command\nexport PGDATABASE=$SOURCE_DATABASE_NAME\n\n# Remove dump file if it already exists\n[ -e \"$SOURCE_DATABASE_NAME.dump\" ] && rm -f \"$SOURCE_DATABASE_NAME.dump\"\n\n# Create a dump file of the source db\npg_dump -Fc -v --host=\"$SOURCE_SERVER_NAME.postgres.database.azure.com\" --username=\"$SOURCE_USERNAME@$SOURCE_SERVER_NAME\" --file=\"$SOURCE_DATABASE_NAME.dump\"\n\n# Delete source firewall rule after dump\naz postgres server firewall-rule delete -g \"$SOURCE_RESOURCE_GROUP_NAME\" -s \"$SOURCE_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\n\n# check that filesize of dump file is greater than 0\nif ! [ -s \"$SOURCE_DATABASE_NAME.dump\" ]; then\n  echo 'Error during pg_dump' >&2\n  exit 1\nfi\n\n# Login to target subscription \naz account set --subscription \"$TARGET_SUBSCRIPTION_ID\"\n\n# Set target server password\nexport PGPASSWORD=$TARGET_PASSWORD\n\n# Create the target server in the specified region\naz postgres server create -l \"$TARGET_REGION\" -g \"$TARGET_RESOURCE_GROUP_NAME\" -n \"$TARGET_SERVER_NAME\" -u \"$TARGET_USERNAME\" -p \"$PGPASSWORD\" --sku-name \"$TARGET_SKU\"\n\n# Create the target database\naz postgres db create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$TARGET_DATABASE_NAME\"\n\n# Create firewall rule on the target server to allow connections from current VM\naz postgres server firewall-rule create -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --start-ip-address \"0.0.0.0\" --end-ip-address \"255.255.255.255\"\n\n# Export PG database name to be used by the pg_restore command\nexport PGDATABASE=$TARGET_DATABASE_NAME\n\n# Restore the database using source database dump file\npg_restore -v --no-owner --host=\"$TARGET_SERVER_NAME.postgres.database.azure.com\" --port=5432 --username=\"$TARGET_USERNAME@$TARGET_SERVER_NAME\" \"$SOURCE_DATABASE_NAME.dump\"\n\n# Delete target firewall rule and local dump file\naz postgres server firewall-rule delete -g \"$TARGET_RESOURCE_GROUP_NAME\" -s \"$TARGET_SERVER_NAME\" -n \"$FIREWALLRULENAME\" --yes\nrm -f \"$SOURCE_DATABASE_NAME.dump\"\n\n# Logout\naz logout -u \"$TARGET_SUBSCRIPTION_ID\"\n\n# Visit Target Server\necho \"Migration Successful !!\"\necho \"Target Server : https://portal.azure.com/#resource/subscriptions/$TARGET_SUBSCRIPTION_ID/resourceGroups/$TARGET_RESOURCE_GROUP_NAME/providers/Microsoft.DBforPostgreSQL/servers/$TARGET_SERVER_NAME/overview\"\n", "num_lines": 254}
{"repo_name": "azure-postgresql", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# PURPOSE\n# Create Azure Database for PostgreSQL Server Master and Replica Servers\n#\n# DESCRIPTION\n# This script \n# 1. Creates a Master Server\n# 2. Sets the azure.replication_support parameter to REPLICA on the master server\n# 3. Restarts the master server for the parameter change to take effect \n# 4. Creates Read Replicas\n#\n# PREREQUISITES\n# Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\n# \n# NOTE\n# Please modify the script to specify different options for master server creation\n# https://docs.microsoft.com/en-us/cli/azure/postgres/server?view=azure-cli-latest\n# \n# USAGE\n# bash pgreplica.sh\n#         --subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\n#         --resource-group 'replicaRG'\n#         --region 'northeurope'\n#         --server-name 'mypg'\n#         --admin-user 'azureuser'\n#         --admin-password 'P@ssw0rd1'\n#         --sku-name 'GP_Gen5_2'\n#         --number-of-replicas '5'\n#\n\nfunction usage()\n{\n    echo \"\"\n    echo \"PURPOSE\"\n    echo \"Create Azure Database for PostgreSQL Server Master and Replica Servers\"\n    echo \"\"\n    echo \"DESCRIPTION\"\n    echo \"This script \"\n    echo \" 1. Creates a Master Server\"\n    echo \" 2. Sets the azure.replication_support parameter to REPLICA on the master server\"\n    echo \" 3. Restarts the master server for the parameter change to take effect\"\n    echo \" 4. Creates Read Replicas\"\n    echo \"\"\n    echo \"PREREQUISITES\"\n    echo \"Azure CLI (https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest)\"\n    echo \"\"\n    echo \"NOTE\"\n    echo \"Please modify the script to specify different options for master server creation\"\n    echo \"https://docs.microsoft.com/en-us/cli/azure/postgres/server?view=azure-cli-latest\"\n    echo \"\"\n    echo \"USAGE\"\n    echo \"bash pgreplica.sh\"\n    echo -e \"\\t--subscription-id 'ffffffff-ffff-ffff-ffff-ffffffffffff'\"\n    echo -e \"\\t--resource-group 'replicaRG'\"\n    echo -e \"\\t--region 'northeurope'\"\n    echo -e \"\\t--server-name 'mypg'\"\n    echo -e \"\\t--admin-user 'azureuser'\"\n    echo -e \"\\t--admin-password 'P@ssw0rd1'\"\n    echo -e \"\\t--sku-name 'GP_Gen5_2'\"\n    echo -e \"\\t--number-of-replicas '5'\"\n    echo \"\"\n}\n\nPARAMS=\"\"\nwhile (( \"$#\" )); do\n  case \"$1\" in\n    -h | --help)\n      usage\n      exit\n      ;;\n    -a|--subscription-id)\n      SUBSCRIPTION_ID=$2\n      shift 2\n      ;;\n    -b|--resource-group)\n      RESOURCE_GROUP=$2\n      shift 2\n      ;;\n    -c|--region)\n      REGION=$2\n      shift 2\n      ;;\n    -d|--server-name)\n      SERVER_NAME=$2\n      shift 2\n      ;;\n    -e|--admin-user)\n      ADMIN_USER=$2\n      shift 2\n      ;;\n    -f|--admin-password)\n      ADMIN_PASSWORD=$2\n      shift 2\n      ;;\n    -g|--sku-name)\n      SKU_NAME=$2\n      shift 2\n      ;;\n    -h|--number-of-replicas)\n      NUMBER_OF_REPLICAS=$2\n      shift 2\n      ;;\n    --) # end argument parsing\n      shift\n      break\n      ;;\n    -*|--*=) # unsupported flags\n      echo \"Error: Unsupported flag $1\" >&2\n      exit 1\n      ;;\n    *) # preserve positional arguments\n      PARAMS=\"$PARAMS $1\"\n      shift\n      ;;\n  esac\ndone\n# set positional arguments in their proper place\neval set -- \"$PARAMS\"\n\n# Prerequisites - Install Azure CLI\nif ! [ -x \"$(command -v az)\" ]; then\n  echo 'Error: azure cli is not installed. Please install from https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest' >&2\n  exit 1\nfi\n\n# Login\naz login\n\n# Set Default Subscription\naz account set --subscription \"$SUBSCRIPTION_ID\"\n\n# Set Default Resource Group\naz configure --defaults group=\"$RESOURCE_GROUP\"\n\n# Create Master Server\naz postgres server create --location \"$REGION\" --name \"$SERVER_NAME\" --admin-user \"$ADMIN_USER\" --admin-password \"$ADMIN_PASSWORD\" --sku-name \"$SKU_NAME\"\n\n# Set azure.replication_support to REPLICA\naz postgres server configuration set --name \"azure.replication_support\" --server-name \"$SERVER_NAME\" --value \"REPLICA\"\n\n# Restart Master Server\naz postgres server restart --name \"$SERVER_NAME\"\n\n# Create Replicas\nfor ((i=1; i<=NUMBER_OF_REPLICAS; i++)); do\n  az postgres server replica create --name \"$SERVER_NAME-replica-$i\" --source-server \"$SERVER_NAME\"\ndone\n\n# Logout\naz logout -u \"$SUBSCRIPTION_ID\"\n\n# Visit Master Server Replication Page\necho \"Master and Replicas Creation Successful !!\"\necho \"Master Server : https://portal.azure.com/#resource/subscriptions/$SUBSCRIPTION_ID/resourceGroups/$RESOURCE_GROUP/providers/Microsoft.DBforPostgreSQL/servers/$SERVER_NAME/replication\"\n", "num_lines": 156}
{"repo_name": "azure-powershell", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -i\n\n# This script is created to set up the env to generate Azure PowerShell modules based on swagger. \n\n# Installed required packages\nsudo apt-get update \\\n    && sudo apt-get install -y curl \\\n    && sudo apt-get install -y dotnet-sdk-2.1 \\\n    && curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \\\n    && export NVM_DIR=\"$HOME/.nvm\" \\\n    && [ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" \\\n    && [ -s \"$NVM_DIR/bash_completion\" ] && \\. \"$NVM_DIR/bash_completion\" \\\n    && nvm install 14.15.5 \\\n    && npm config set unsafe-perm true \\\n    && npm install -g autorest\n\n# Write $PATH and some other envs to a file for later usage\n\necho \"{\\\"envs\\\":{\\\"PATH\\\":\\\"$PATH\\\",\\\"DOTNET_SKIP_FIRST_TIME_EXPERIENCE\\\":1}}\" > $2\n", "num_lines": 20}
{"repo_name": "azure-powershell-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -i\n\n# This script is created to set up the env to generate Azure PowerShell modules based on swagger. \n\n# Installed required packages\nsudo apt-get update \\\n    && sudo apt-get install -y curl \\\n    && sudo apt-get install -y dotnet-sdk-2.1 \\\n    && curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \\\n    && export NVM_DIR=\"$HOME/.nvm\" \\\n    && [ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" \\\n    && [ -s \"$NVM_DIR/bash_completion\" ] && \\. \"$NVM_DIR/bash_completion\" \\\n    && nvm install 14.15.5 \\\n    && npm config set unsafe-perm true \\\n    && npm install -g autorest\n\n# Write $PATH and some other envs to a file for later usage\n\necho \"{\\\"envs\\\":{\\\"PATH\\\":\\\"$PATH\\\",\\\"DOTNET_SKIP_FIRST_TIME_EXPERIENCE\\\":1}}\" > $2\n", "num_lines": 20}
{"repo_name": "azure-powershell-2", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -i\n\n# This script is created to set up the env to generate Azure PowerShell modules based on swagger. \n\n# Installed required packages\nsudo apt-get update \\\n    && sudo apt-get install -y curl \\\n    && sudo apt-get install -y dotnet-sdk-2.1 \\\n    && curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash \\\n    && export NVM_DIR=\"$HOME/.nvm\" \\\n    && [ -s \"$NVM_DIR/nvm.sh\" ] && \\. \"$NVM_DIR/nvm.sh\" \\\n    && [ -s \"$NVM_DIR/bash_completion\" ] && \\. \"$NVM_DIR/bash_completion\" \\\n    && nvm install 14.15.5 \\\n    && npm config set unsafe-perm true \\\n    && npm install -g autorest\n\n# Write $PATH and some other envs to a file for later usage\n\necho \"{\\\"envs\\\":{\\\"PATH\\\":\\\"$PATH\\\",\\\"DOTNET_SKIP_FIRST_TIME_EXPERIENCE\\\":1}}\" > $2\n", "num_lines": 20}
{"repo_name": "azure-python-devtools", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\npylint src/azure_devtools\npytest src/azure_devtools/scenario_tests/tests --cov=./", "num_lines": 4}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\nwhile getopts \"a:l:g:s:f:e:uvdb\" opt; do\n    case $opt in\n        a)\n            artifactsStagingDirectory=$OPTARG #the folder or sample to deploy\n        ;;\n        l)\n            location=$OPTARG #location for the deployed resource group\n        ;;\n        g)\n            resourceGroupName=$OPTARG #name of the resource group to create\n        ;;\n        u)\n            uploadArtifacts='true' #set this switch to upload/stage artifacs\n        ;;\n        s)\n            storageAccountName=$OPTARG #storage account to use for staging, if not supplied one will be created and reused\n        ;;\n        f)\n            templateFile=$OPTARG\n        ;;\n        e)\n            parametersFile=$OPTARG\n        ;;\n        v)\n            validateOnly='true' #validate the template without deploying\n        ;;\n        d)\n            devMode='true' #dev mode automatically selects a different parameter file without explicitly specifying it\n        ;;        \n        b)\n            bicep='true' #dev mode automatically selects a different parameter file without explicitly specifying it\n        ;;\n    esac\ndone\n\n[[ $# -eq 0 || -z $artifactsStagingDirectory || -z $location ]] && { echo \"Usage: $0 <-a foldername> <-l location> [-e parameters-file] [-g resource-group-name] [-u] [-s storageAccountName] [-t templateFile] [-v] [-d]\"; exit 1; }\n\nexport AZURE_HTTP_USER_AGENT=\"AzureQuickStarts $AZURE_HTTP_USER_AGENT\"\n\n# if the switch is set or the file is a bicep file\nif [[ $bicep || ($templateFile == *.bicep) ]]\nthen\n    isBicep=true\n    defaultTemplateFile=\"/main.bicep\"\nelse\n    isBicep=false\n    defaultTemplateFile=\"/azuredeploy.json\"\nfi\n\nif [[ -z $templateFile ]]\nthen\n    templateFile=\"$artifactsStagingDirectory$defaultTemplateFile\"\nfi\n\nif [[ $isBicep = true ]]\nthen\n    bicep build $templateFile\n    # after building the script will work with the json file\n    t=\"${templateFile/.bicep/.json}\"\n    templateFile=$t\nfi\n\nif [[ $devMode ]]\nthen\n    parametersFile=\"$artifactsStagingDirectory/azuredeploy.parameters.dev.json\"\n    if [ ! -f $parametersFile ]\n    then\n        parametersFile=\"$artifactsStagingDirectory/azuredeploy.parameters.1.json\"\n    fi\nelse\n    if [[ -z $parametersFile ]]\n    then\n        parametersFile=\"$artifactsStagingDirectory/azuredeploy.parameters.json\"\n    fi\nfi\n\necho \"Using parameters file: \"$parametersFile\n\ntemplateName=\"$( basename \"${templateFile%.*}\" )\"\ntemplateDirectory=\"$( dirname \"$templateFile\")\"\n\nif [[ -z $resourceGroupName ]]\nthen\n    resourceGroupName=$(basename $(cd \"${artifactsStagingDirectory}\" && pwd))\nfi\n\nparameterJson=$( cat \"$parametersFile\" | jq '.parameters' )\n_artifactsLocationParameter=$( cat \"$templateFile\" | jq '.parameters._artifactsLocation' )\n_artifactsLocationSasTokenParameter=$( cat \"$templateFile\" | jq '.parameters._artifactsLocationSasToken' )\n\nif [[ $uploadArtifacts || $_artifactsLocationParameter != null || $_artifactsLocationSasTokenParameter != null ]]\nthen\n\n    if [[ -z $storageAccountName ]]\n    then\n\n        subscriptionId=$( az account show -o json | jq -r '.id' )\n        subscriptionId=\"${subscriptionId//-/}\"\n        subscriptionId=\"${subscriptionId:0:19}\"\n        artifactsStorageAccountName=\"stage$subscriptionId\"\n        artifactsResourceGroupName=\"ARM_Deploy_Staging\"\n\n        if [[ -z $( az storage account list -o json | jq -r '.[].name | select(. == '\\\"$artifactsStorageAccountName\\\"')' ) ]]\n        then\n            az group create -n \"$artifactsResourceGroupName\" -l \"$location\"\n            az storage account create -l \"$location\" --sku \"Standard_LRS\" -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" 2>/dev/null\n        fi\n    else\n        artifactsStorageAccountName=$storageAccountName\n        artifactsResourceGroupName=$( az storage account list -o json | jq -r '.[] | select(.name == '\\\"$storageAccountName\\\"') .resourceGroup' )\n        if [[ -z $artifactsResourceGroupName ]]\n        then\n            echo \"Cannot find storageAccount: \"$storageAccountName\n        fi\n    fi\n\n    artifactsStorageContainerName=${resourceGroupName}\"-stageartifacts\"\n    artifactsStorageContainerName=$( echo \"${artifactsStorageContainerName:0:63}\" | awk '{print tolower($0)}')\n\n    artifactsStorageAccountKey=$( az storage account keys list -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" -o json | jq -r '.[0].value' )\n    az storage container create -n \"$artifactsStorageContainerName\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" >/dev/null 2>&1\n\n    # Get a 4-hour SAS Token for the artifacts container. Fall back to OSX date syntax if Linux syntax fails.\n    plusFourHoursUtc=$(date -u -d @$(($(date +%s)+14400)) +%Y-%m-%dT%H:%MZ 2>/dev/null)  || plusFourHoursUtc=$(date -u --date \"$dte 4 hour\" +%Y-%m-%dT%H:%MZ)\n\n    sasToken=$( az storage container generate-sas -n \"$artifactsStorageContainerName\" --permissions r --expiry \"$plusFourHoursUtc\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" -o json | sed 's/\"//g')\n\n    blobEndpoint=$( az storage account show -n \"$artifactsStorageAccountName\" -g \"$artifactsResourceGroupName\" -o json | jq -r '.primaryEndpoints.blob' )\n\n    defaultValue=$( cat \"$templateFile\" | jq '.parameters._artifactsLocation.defaultValue' )\n\n    if [[ $defaultValue != *\").properties.templateLink.uri\"* ]] # this should really include deployment(). but VS Code has a bug so working around that\n    then #if the template is not using the templateLink.uri, then add the storage location to the parameters\n        parameterJson=$( echo \"$parameterJson\"  | jq \"{_artifactsLocation: {value: \"\\\"$blobEndpoint$artifactsStorageContainerName/\"\\\"}} + .\" )\n    fi\n\n    parameterJson=$( echo \"$parameterJson\"  | jq \"{_artifactsLocationSasToken: {value: \\\"?\"$sasToken\"\\\"}} + .\" )\n\n    artifactsStagingDirectory=$( echo \"$artifactsStagingDirectory\" | sed 's/\\/*$//')\n    artifactsStagingDirectoryLen=$((${#artifactsStagingDirectory} + 1))\n\n    for filepath in $( find \"$artifactsStagingDirectory\" -type f )\n    do\n        relFilePath=${filepath:$artifactsStagingDirectoryLen}\n        echo \"Uploading file $relFilePath...\"\n        az storage blob upload -f $filepath --container $artifactsStorageContainerName -n $relFilePath --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" --verbose\n    done\n\n    templateUri=$blobEndpoint$artifactsStorageContainerName/$(basename $templateFile)?$sasToken\n\nfi\n\n# Create the resource group only if it doesn't already exist\ntargetResourceGroup=$( az group list -o json | jq -r '.[] | select(.name == '\\\"$resourceGroupName\\\"')'.name )\nif [[ -z $targetResourceGroup ]]\nthen\n    az group create -n \"$resourceGroupName\" -l \"$location\"\nfi\n\n# Remove line endings from parameter JSON so it can be passed in to the CLI as a single line\nparameterJson=$( echo \"$parameterJson\" | jq -c '.' )\n\nif [[ $validateOnly ]]\nthen\n    if [[ $uploadArtifacts || $_artifactsLocationParameter != null ]]\n    then\n        az deployment group validate -g \"$resourceGroupName\" --template-uri $templateUri --parameters \"$parameterJson\" --verbose\n    else\n        az deployment group validate -g \"$resourceGroupName\" --template-file $templateFile --parameters \"$parameterJson\" --verbose\n    fi\nelse\n    if [[ $uploadArtifacts || $_artifactsLocationParameter != null ]]\n    then\n        az deployment group create -g \"$resourceGroupName\" -n AzureRMSamples --template-uri $templateUri --parameters \"$parameterJson\" --verbose\n    else\n        az deployment group create -g \"$resourceGroupName\" -n AzureRMSamples --template-file $templateFile --parameters \"$parameterJson\" --verbose\n    fi\nfi\n", "num_lines": 180}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -e\n# Set defaultValues for optional args\nartifactsStagingDirectory='.'\ncreateUIDefFile='createUIDefinition.json'\n\nwhile getopts \"a:l:s:f:g\" opt; do\n    case $opt in\n        a)\n            artifactsStagingDirectory=$OPTARG #the folder for the createUIDefinition.json file\n        ;;\n        l)\n            storageLocation=$OPTARG #location for the staging storage account if it needs to be created\n        ;;\n        f)\n            createUIDefFile=$OPTARG\n        ;;\n        g)\n            gov='false'\n        ;;\n    esac\ndone\n\n#you must be logged into azure before running this script - run \"az login\"\nsubscriptionId=$( az account show -o json | jq -r '.id' )\nsubscriptionId=\"${subscriptionId//-/}\"\nsubscriptionId=\"${subscriptionId:0:19}\"\nartifactsStorageAccountName=\"stage$subscriptionId\"\nartifactsResourceGroupName=\"ARM_Deploy_Staging\"\n\necho \"Checking for storage account...\"\nif [[ -z $( az storage account list -o json | jq -r '.[].name | select(. == '\\\"$artifactsStorageAccountName\\\"')' ) ]]\nthen\n    if [[ -z $storageLocation ]]\n    then\n        echo \"-l (storageLocation) must be specified when storageAccount needs to be created, usually on first run for a subscription.\"\n        exit 1\n    fi\n    echo \"Creating storage account...\"\n    az group create -n \"$artifactsResourceGroupName\" -l \"$storageLocation\"\n    az storage account create -l \"$storageLocation\" --sku \"Standard_LRS\" -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" 2>/dev/null\nfi\n\nartifactsStorageContainerName=\"createuidef-stageartifacts\"\n\nartifactsStorageAccountKey=$( az storage account keys list -g \"$artifactsResourceGroupName\" -n \"$artifactsStorageAccountName\" -o json | jq -r '.[0].value' )\n\naz storage container create -n \"$artifactsStorageContainerName\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" >/dev/null 2>&1\n\nuiDefFilePath=\"$artifactsStagingDirectory/$createUIDefFile\"\n\naz storage blob upload -f \"$uiDefFilePath\" --container $artifactsStorageContainerName -n $createUIDefFile --account-name $artifactsStorageAccountName  >/dev/null\n\n# Get a 4-hour SAS Token for the artifacts container. Fall back to OSX date syntax if Linux syntax fails.\nplusFourHoursUtc=$(date -u -v+4H +%Y-%m-%dT%H:%MZ 2>/dev/null)  || plusFourHoursUtc=$(date -u --date \"$dte 4 hour\" +%Y-%m-%dT%H:%MZ)\nsasToken=$( az storage container generate-sas -n \"$artifactsStorageContainerName\" --permissions r --expiry \"$plusFourHoursUtc\" --account-name \"$artifactsStorageAccountName\" --account-key \"$artifactsStorageAccountKey\" -o json | sed 's/\"//g')\n\nblobEndpoint=$( az storage account show -n \"$artifactsStorageAccountName\" -g \"$artifactsResourceGroupName\" -o json | jq -r '.primaryEndpoints.blob' )\ncreateUIDefUrl=$blobEndpoint$artifactsStorageContainerName/$createUIDefFile?$sasToken\n\ncreateUIDefUrlEncoded=$(printf %s \"$createUIDefUrl\" | jq -s -R -r @uri)\n\nif [[ $gov ]]\nthen\ntarget=\"https://portal.azure.us/#blade/Microsoft_Azure_Compute/CreateMultiVmWizardBlade/internal_bladeCallId/anything/internal_bladeCallerParams/{\"\\\"\"providerConfig\"\\\"\":{\"\\\"\"createUiDefinition\"\\\"\":\"\\\"\"$createUIDefUrlEncoded\"\\\"\"}}\"\nelse\ntarget=\"https://portal.azure.com/#blade/Microsoft_Azure_Compute/CreateMultiVmWizardBlade/internal_bladeCallId/anything/internal_bladeCallerParams/{\"\\\"\"providerConfig\"\\\"\":{\"\\\"\"createUiDefinition\"\\\"\":\"\\\"\"$createUIDefUrlEncoded\"\\\"\"}}\"\nfi\n\necho \"Launch browser with this URL:\"\necho\necho $target\necho\n\n#note chrome will not launch with the encoded url no idea why - copy/paste works (or safari)\npython -mwebbrowser $target\n", "num_lines": 76}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmongoAdminUser=$1\nmongoAdminPasswd=$2\ndnsNamePrefix=$3\nmongoSslCertPswd=$4\n\nGetMongoPackage() {\n\tpackageUri=$1\n\t\n\twhile true; do\n\t#install mongo package\n    wget $packageUri && break || {\n      if [[ $n -lt 3 ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n of 3:\"\n        sleep 15;\n      else\n        echo \"Failed to get the package $packageUri after $n attempts.\"\n\t\texit 1\n      fi\n    }\n  \tdone\n}\n\ninstall_mongo3() {\n    #install\n\trpm -i mongodb-org-server-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\n\tPATH=$PATH:/usr/bin; export PATH\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\t\n}\n\nyum install wget -y\necho \"Generating ssl certificate\"\nopenssl req -newkey rsa:2048 -nodes -keyout /etc/key.pem -x509 -days 365 -out /etc/certificate.pem -subj \"/CN=$dnsNamePrefix\"\nopenssl pkcs12 -inkey /etc/key.pem -in /etc/certificate.pem -export -out /etc/MongoAuthCert.p12 -passout pass:$mongoSslCertPswd\nopenssl pkcs12 -in /etc/MongoAuthCert.p12 -out /etc/MongoAuthCert.pem -passin pass:$mongoSslCertPswd -passout pass:$mongoSslCertPswd\n\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-server-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\"\ninstall_mongo3\n\n\n#start mongod\nmongod --dbpath /var/lib/mongo/ --bind_ip 0.0.0.0 --logpath /var/log/mongodb/mongod.log --fork\n\nsleep 30\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep | wc -l`\nif [[ $n -eq 1 ]];then\n    echo \"mongod started successfully\"\nelse\n    echo \"mongod started failed!\"\n\texit 1\nfi\n\n#create users\nmongo <<EOF\nuse admin\ndb.createUser({user:\"$mongoAdminUser\",pwd:\"$mongoAdminPasswd\",roles:[{role: \"userAdminAnyDatabase\", db: \"admin\" },{role: \"readWriteAnyDatabase\", db: \"admin\" },{role: \"root\", db: \"admin\" }]})\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"mongo user added succeefully.\"\nelse\n    echo \"mongo user added failed!\"\n\texit 1\nfi\n\n#stop mongod\nsleep 15\nMongoPid=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep |awk '{print $2}'`\nkill -2 $MongoPid\n\n\n\n#set keyfile\necho \"vfr4CDE1\" > /etc/mongokeyfile\nchown mongod:mongod /etc/mongokeyfile\nchmod 600 /etc/mongokeyfile\nsed -i 's/^#security/security/' /etc/mongod.conf\nsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\nsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n\nsleep 15\nMongoPid1=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep |awk '{print $2}'`\nif [[ -z $MongoPid1 ]];then\n    echo \"shutdown mongod successfully\"\nelse\n    echo \"shutdown mongod failed!\"\n    kill $MongoPid1\n    sleep 15\nfi\n\n#restart mongod with auth and config replica set\nmongod --configsvr --replSet crepset --bind_ip 0.0.0.0 --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\n\n#initiate config replica set\n\nfor((i=1;i<=3;i++))\ndo\n    sleep 15\n    n=`ps -ef |grep \"mongod --configsvr\"|grep -v grep |wc -l`\n    if [[ $n -eq 1 ]];then\n        echo \"mongo config replica set started successfully\"\n        break\n    else\n        mongod --configsvr --replSet crepset --bind_ip 0.0.0.0 --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n        continue\n    fi\ndone\n\nn=`ps -ef |grep \"mongod --configsvr\"|grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\n    echo \"mongo config replica set tried to start 3 times but failed!\"\n\texit 1\nfi\n\n\nmongo --port 27019 --ssl --sslCAFile /etc/MongoAuthCert.pem --sslAllowInvalidHostnames<<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\",\"$mongoAdminPasswd\")\nconfig={_id: \"crepset\", configsvr: true, members: [{ _id: 0, host: \"10.0.0.240:27019\" },{ _id: 1, host: \"10.0.0.241:27019\" },{ _id: 2, host: \"10.0.0.242:27019\" }]}\nrs.initiate(config)\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"mongod config replica set initiated successfully.\"\nelse\n    echo \"mongod config replica set initiation failed!\"\n\texit 1\nfi\n\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --configsvr --replSet crepset --bind_ip 0.0.0.0 --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 192}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndnsNamePrefix=$1\nmongoSslCertPswd=$2\n\nGetMongoPackage() {\n\tpackageUri=$1\n\t\n\twhile true; do\n\t#install mongo package\n    wget $packageUri && break || {\n      if [[ $n -lt 3 ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n of 3:\"\n        sleep 15;\n      else\n        echo \"Failed to get the package $packageUri after $n attempts.\"\n\t\texit 1\n      fi\n    }\n  \tdone\n}\n\ninstall_mongo3() {\n\t\n\t#install\n\trpm -i mongodb-org-server-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\n\tPATH=$PATH:/usr/bin; export PATH\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\n#yum install wget -y\necho \"Generating ssl certificate\"\nopenssl req -newkey rsa:2048 -nodes -keyout /etc/key.pem -x509 -days 365 -out /etc/certificate.pem -subj \"/CN=$dnsNamePrefix\"\nopenssl pkcs12 -inkey /etc/key.pem -in /etc/certificate.pem -export -out /etc/MongoAuthCert.p12 -passout pass:$mongoSslCertPswd\nopenssl pkcs12 -in /etc/MongoAuthCert.p12 -out /etc/MongoAuthCert.pem -passin pass:$mongoSslCertPswd -passout pass:$mongoSslCertPswd\n\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-server-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\"\ninstall_mongo3\n\n#start config replica set\nmongod --configsvr --replSet crepset --bind_ip 0.0.0.0 --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\n\n#check if mongod started or not\nsleep 15\nn=`ps -ef |grep \"mongod --configsvr\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\n    echo \"mongod config replica set started successfully\"\nelse\n    echo \"mongod config replica set started failed!\"\n\texit 1\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --configsvr --replSet crepset --bind_ip 0.0.0.0 --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 120}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\nstaticIP=$2\nmongoAdminUser=$3\nmongoAdminPasswd=$4\ndnsNamePrefix=$5\nmongoSslCertPswd=$6\n\nGetMongoPackage() {\n\tpackageUri=$1\n\t\n\twhile true; do\n\t#install mongo package\n    wget $packageUri && break || {\n      if [[ $n -lt 3 ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n of 3:\"\n        sleep 15;\n      else\n        echo \"Failed to get the package $packageUri after $n attempts.\"\n\t\texit 1\n      fi\n    }\n  \tdone\n}\n\ninstall_mongo3() {\n\n\t#install\n\trpm -i mongodb-org-server-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\n\tPATH=$PATH:/usr/bin; export PATH\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\nyum install wget -y\necho \"Generating ssl certificate\"\nopenssl req -newkey rsa:2048 -nodes -keyout /etc/key.pem -x509 -days 365 -out /etc/certificate.pem -subj \"/CN=$dnsNamePrefix\"\nopenssl pkcs12 -inkey /etc/key.pem -in /etc/certificate.pem -export -out /etc/MongoAuthCert.p12 -passout pass:$mongoSslCertPswd\nopenssl pkcs12 -in /etc/MongoAuthCert.p12 -out /etc/MongoAuthCert.pem -passin pass:$mongoSslCertPswd -passout pass:$mongoSslCertPswd\n\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-server-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\"\ninstall_mongo3\ndisk_format\n\n#start mongod\nmongod --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\nsleep 30\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\n\techo \"mongod started successfully\"\nelse\n\techo \"mongod started failed!\"\n\texit 1\nfi\n\n\n#create users\nmongo --ssl --sslCAFile /etc/MongoAuthCert.pem --sslAllowInvalidHostnames<<EOF\nuse admin\ndb.createUser({user:\"$mongoAdminUser\",pwd:\"$mongoAdminPasswd\",roles:[{role: \"userAdminAnyDatabase\", db: \"admin\" },{role: \"readWriteAnyDatabase\", db: \"admin\" },{role: \"root\", db: \"admin\" }]})\nexit\nEOF\nif [[ $? -eq 0 ]];then\n\techo \"mongo user added succeefully.\"\nelse\n\techo \"mongo user added failed!\"\n\texit 1\nfi\n\n#stop mongod\nsleep 15\nMongoPid=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |awk '{print $2}'`\nkill -2 $MongoPid\n\n\n\nsleep 15\nMongoPid1=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |awk '{print $2}'`\nif [[ -z $MongoPid1 ]];then\n\techo \"shutdown mongod successfully\"\nelse\n\techo \"shutdown mongod failed!\"\n\tkill $MongoPid1\n\tsleep 15\nfi\n\n#restart mongod with auth and replica set\nmongod --dbpath /var/lib/mongo/ --shardsvr --replSet $replSetName --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --config /etc/mongod.conf --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\n\n#initiate replica set\nfor((i=1;i<=3;i++))\ndo\n\tsleep 15\n\tn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\n\tif [[ $n -eq 1 ]];then\n\t\techo \"mongo replica set started successfully\"\n\t\tbreak\n\telse\n\t\tmongod --dbpath /var/lib/mongo/ --shardsvr --replSet $replSetName --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --config /etc/mongod.conf --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\t\tcontinue\n\tfi\ndone\n\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\n\techo \"mongo replica set tried to start 3 times but failed!\"\n\texit 1\nfi\n\n\n\nmongo --ssl --sslCAFile /etc/MongoAuthCert.pem --sslAllowInvalidHostnames<<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\", \"$mongoAdminPasswd\")\nconfig ={_id:\"$replSetName\",members:[{_id:0,host:\"$staticIP:27017\"}]}\nrs.initiate(config)\nexit\nEOF\nif [[ $? -eq 0 ]];then\n\techo \"replica set initiation succeeded.\"\nelse\n\techo \"replica set initiation failed!\"\n\texit 1\nfi\n\n\n#get replica secondary nodes ips\nnum=`echo $staticIP |awk -F\".\" '{print $NF}'`\nif [[ $num -eq 100 ]];then\n\tlet g=$num-97\nelif [[ $num -eq 110 ]];then\n\tlet g=$num-105\nfi\n\n#add secondary nodes\nfor((i=1;i<=3;i++))\ndo\n\tlet a=$i+$g\n\tmongo -u \"$mongoAdminUser\" -p \"$mongoAdminPasswd\" \"admin\" --ssl --sslCAFile /etc/MongoAuthCert.pem --sslAllowInvalidHostnames --eval \"printjson(rs.add('10.0.0.${a}:27017'))\"\n\tif [[ $? -eq 0 ]];then\n\t\techo \"adding server 10.0.0.${a} successfully\"\n\telse\n\t\techo \"adding server 10.0.0.${a} failed!\"\n\t\texit 1\n\tfi\ndone\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --dbpath /var/lib/mongo/ --shardsvr --replSet $replSetName --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --config /etc/mongod.conf --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n\n\n", "num_lines": 240}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\ndnsNamePrefix=$2\nmongoSslCertPswd=$3\n\nGetMongoPackage() {\n\tpackageUri=$1\n\t\n\twhile true; do\n\t#install mongo package\n    wget $packageUri && break || {\n      if [[ $n -lt 3 ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n of 3:\"\n        sleep 15;\n      else\n        echo \"Failed to get the package $packageUri after $n attempts.\"\n\t\texit 1\n      fi\n    }\n  \tdone\n}\n\ninstall_mongo3() {\n\n\t#install\n\trpm -i mongodb-org-server-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\n\tPATH=$PATH:/usr/bin; export PATH\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\ndisk_format() {\n\tcd /tmp\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\nyum install wget -y\necho \"Generating ssl certificate\"\nopenssl req -newkey rsa:2048 -nodes -keyout /etc/key.pem -x509 -days 365 -out /etc/certificate.pem -subj \"/CN=$dnsNamePrefix\"\nopenssl pkcs12 -inkey /etc/key.pem -in /etc/certificate.pem -export -out /etc/MongoAuthCert.p12 -passout pass:$mongoSslCertPswd\nopenssl pkcs12 -in /etc/MongoAuthCert.p12 -out /etc/MongoAuthCert.pem -passin pass:$mongoSslCertPswd -passout pass:$mongoSslCertPswd\n\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-server-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\"\ninstall_mongo3\ndisk_format\n\n#start replica set\nmongod --dbpath /var/lib/mongo/ --shardsvr --config /etc/mongod.conf --replSet $replSetName --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\n\n#check if mongod started or not\nsleep 15\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\necho \"replica set started successfully\"\nelse\necho \"replica set started failed!\"\nexit 1\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --shardsvr --dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet $replSetName --logpath /var/log/mongodb/mongod.log --bind_ip 0.0.0.0 --fork --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 143}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmongoAdminUser=$1\nmongoAdminPasswd=$2\nfqdn=$3\nmongoSslCertPswd=$4\n\nGetMongoPackage() {\n\tpackageUri=$1\n\t\n\twhile true; do\n\t#install mongo package\n    wget $packageUri && break || {\n      if [[ $n -lt 3 ]]; then\n        ((n++))\n        echo \"Command failed. Attempt $n of 3:\"\n        sleep 15;\n      else\n        echo \"Failed to get the package $packageUri after $n attempts.\"\n\t\texit 1\n      fi\n    }\n  \tdone\n}\n\ninstall_mongo3() {\n\n\t#install\n\trpm -i mongodb-org-mongos-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\n\trpm -i mongodb-org-server-3.6.17-1.el7.x86_64.rpm\n\tPATH=$PATH:/usr/bin; export PATH\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\nyum install wget -y\necho \"Generating ssl certificate\"\nopenssl req -newkey rsa:2048 -nodes -keyout /etc/key.pem -x509 -days 365 -out /etc/certificate.pem -subj \"/CN=$fqdn\"\nopenssl pkcs12 -inkey /etc/key.pem -in /etc/certificate.pem -export -out /etc/MongoAuthCert.p12 -passout pass:$mongoSslCertPswd\nopenssl pkcs12 -in /etc/MongoAuthCert.p12 -out /etc/MongoAuthCert.pem -passin pass:$mongoSslCertPswd -passout pass:$mongoSslCertPswd\n\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-mongos-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-shell-3.6.17-1.el7.x86_64.rpm\"\nGetMongoPackage \"https://repo.mongodb.org/yum/redhat/7/mongodb-org/3.6/x86_64/RPMS/mongodb-org-server-3.6.17-1.el7.x86_64.rpm\"\ninstall_mongo3\n\n#start router server\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --bind_ip 0.0.0.0 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\n\n#check router server starts or not\nfor((i=1;i<=3;i++))\ndo\n\tsleep 30\n\tn=`ps -ef |grep \"mongos --configdb\" |grep -v grep |wc -l`\n\tif [[ $n -eq 1 ]];then\n\t\techo \"mongos started successfully\"\n\t\tbreak\n\telse\n\t\tmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --bind_ip 0.0.0.0 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n\t\tcontinue\n\tfi\ndone\n\nn=`ps -ef |grep \"mongos --configdb\" |grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\necho \"mongos tried to start 3 times but failed!\"\nexit 1\nfi\n\n#add shard\nmongo --ssl --sslCAFile /etc/MongoAuthCert.pem --host $fqdn --port 27017 <<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\",\"$mongoAdminPasswd\")\nsh.addShard(\"repset1/10.0.0.100:27017\")\ndb.runCommand( { listshards : 1 } )\nexit\nEOF\nif [[ $? -eq 0 ]];then\necho \"mongo shard added succeefully.\"\nelse\necho \"mongo shard added failed!\"\nexit 1\nfi\n\n\n#set mongos auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --bind_ip 0.0.0.0 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile --sslMode requireSSL --sslPEMKeyFile /etc/MongoAuthCert.pem --sslPEMKeyPassword $mongoSslCertPswd\n}\nstop() {\npkill mongos\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 149}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ndpkg --configure -a\napt-get -y update\n\n# install Apache2\napt-get -y install apache2\napt-get -y install mysql-server\napt-get -y install php libapache2-mod-php php-mysql\n# write some HTML\necho \\<center\\>\\<h1\\>My Demo App\\</h1\\>\\<br/\\>\\</center\\> > /var/www/html/demo.html\n\n# restart Apache\napachectl restart", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo apt-get install -y apache2\nif [ \"$1\" = \"True\" ]; then\n\tif [ \"$4\" = \"16.04.0-LTS\" ]; then\n\t\tsudo apt-get install -y libapache2-mod-php\n\telse\n\t\tsudo apt-get install -y php5\n\tfi\n\tif [ \"$3\" = \"index.php\" ]; then\n\t\tsudo rm /var/www/html/index.html\n\tfi\n\tsudo service apache2 restart\nfi\necho $2 | sudo tee /var/www/html/$3\n", "num_lines": 17}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Bash script to install Vert.x, OpenJDK 7, Apache and MySQL Server\n\n# Set MySQL Server password\nmysql_password=\"Passw0rd!\"\n\n# Set MySQL Server version to install\nmysql_version=\"5.5\"\n\n# Set Vert.x filename to download. Change the location as necessary\nvertx_version=\"vert.x-2.1.5\"\nvertx_download_location=\"https://bintray.com/artifact/download/vertx/downloads/$vertx_version\".zip\n\n# Install Vert.x, OpenJDK 7, and Apache\napt-get update\napt-get install unzip -y\napt-get install openjdk-7-jdk -y\napt-get install apache2-utils -y\nmkdir /usr/local/vertx && cd /usr/local/vertx\nwget -qO- -O tmp.zip $vertx_download_location && unzip tmp.zip && rm tmp.zip\nln -sT /usr/local/vertx/vert.x-2.1.5/bin/vertx /usr/local/bin/vertx\n\n# Install MySQL Server in non-interactive mode\nexport DEBIAN_FRONTEND=noninteractive\necho \"mysql-server-$mysql_version mysql-server/root_password password $mysql_password\" | debconf-set-selections\necho \"mysql-server-$mysql_version mysql-server/root_password_again password $mysql_password\" | debconf-set-selections\napt-get install mysql-server -y\n\n# Edit crontab to start MySQL Server service automatically on boot\n(crontab -l 2>/dev/null; echo \"@reboot service mysql start\") | crontab -\n", "num_lines": 32}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nwget --no-check-certificate --no-cookies \"https://files-cdn.liferay.com/mirrors/download.oracle.com/otn-pub/java/jdk/7u80-b15/jdk-7u80-linux-x64.tar.gz\"\ntar -xvf jdk-7*\nmkdir /usr/lib/jvm\nmv ./jdk1.7* /usr/lib/jvm/jdk1.7.0\nupdate-alternatives --install \"/usr/bin/java\" \"java\" \"/usr/lib/jvm/jdk1.7.0/bin/java\" 1\nupdate-alternatives --install \"/usr/bin/javac\" \"javac\" \"/usr/lib/jvm/jdk1.7.0/bin/javac\" 1\nupdate-alternatives --install \"/usr/bin/javaws\" \"javaws\" \"/usr/lib/jvm/jdk1.7.0/bin/javaws\" 1\nchmod a+x /usr/bin/java\nchmod a+x /usr/bin/javac\nchmod a+x /usr/bin/javaws\n\ncd /usr/local\n\nwget \"https://archive.apache.org/dist/zookeeper/zookeeper-3.4.12/zookeeper-3.4.12.tar.gz\"\ntar -xvf \"zookeeper-3.4.12.tar.gz\"\n\ntouch zookeeper-3.4.12/conf/zoo.cfg\n\necho \"tickTime=2000\" >> zookeeper-3.4.12/conf/zoo.cfg\necho \"dataDir=/var/lib/zookeeper\" >> zookeeper-3.4.12/conf/zoo.cfg\necho \"clientPort=2181\" >> zookeeper-3.4.12/conf/zoo.cfg\necho \"initLimit=5\" >> zookeeper-3.4.12/conf/zoo.cfg\necho \"syncLimit=2\" >> zookeeper-3.4.12/conf/zoo.cfg\n\ni=1\nwhile [ $i -le $2 ]\ndo\n    echo \"server.$i=10.0.0.$(($i+3)):2888:3888\" >> zookeeper-3.4.12/conf/zoo.cfg\n    i=$(($i+1))\ndone\n\nmkdir -p /var/lib/zookeeper\n\necho $(($1+1)) >> /var/lib/zookeeper/myid\n\nzookeeper-3.4.12/bin/zkServer.sh start\n", "num_lines": 38}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"Initializing Bitcore installation\"\n\n#############\n# Parameters\n#############\nAZUREUSER=$1\nHOME=\"/home/$AZUREUSER\"\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOME\"\n\nyum -y install epel-release\nyum -y install npm git curl which xz tar findutils\nnpm install -g n\nn 4.2.4\ncat >/etc/systemd/system/bitcored.service <<EOL\n[Unit]\nDescription=bitcored.service\nAfter=network.target\n\n[Service]\nType=simple\nUser=$AZUREUSER\nExecStart=/usr/local/bin/bitcored\nExecReload=/bin/kill -2 \\$MAINPID\nKillMode=process\nRestart=on-failure\n\n[Install]\nWantedBy=multi-user.agent\nEOL\n/bin/bash -l -c \"export PATH=/usr/local/bin:\\$PATH; export HOME=$HOME; npm install -g bitcore\"\n/bin/bash -l -c \"parted -s /dev/sdc mklabel gpt unit s mkpart primary `parted -s /dev/sdc mklabel gpt unit s print free | grep 'Free Space' | tail -n 1 | awk '{print $1}'` `parted -s /dev/sdc mklabel gpt unit s print free | grep 'Free Space' | tail -n 1 | awk '{print $2}'` && mkfs.ext4 /dev/sdc1 && mkdir $HOME/.bitcore && mount /dev/sdc1 $HOME/.bitcore\"\n/bin/bash -l -c \"chown -R $AZUREUSER $HOME/.bitcore\"\nsystemctl start bitcored\necho \"Completed Bitcore install $$\"\n", "num_lines": 38}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\ndate\nps axjf\n\nAZUREUSER=$2\nHOMEDIR=\"/home/$AZUREUSER\"\nGROESTLCOINPATH=\"$HOMEDIR/.groestlcoin\"\nVMNAME=`hostname`\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOMEDIR\"\necho \"User Groestlcoin path: $GROESLCOINPATH\"\necho \"vmname: $VMNAME\"\n\nif [[ $1 = 'From_PPA' ]]; then\n\n#################################################################\n# Update Ubuntu and install prerequisites for running Groestlcoin Core   #\n#################################################################\nsudo apt-get update\n\n#################################################################\n# Get CPU count                                                          #\n#################################################################\nNPROC=$(nproc)\necho \"nproc: $NPROC\"\n\n#################################################################\n# Install all necessary packages for building Groestlcoin Core from source  #\n#################################################################\nsudo apt-get -y install build-essential libtool autotools-dev autoconf pkg-config libssl-dev libcrypto++-dev libevent-dev git automake bsdmainutils libboost-all-dev libminiupnpc-dev libzmq3-dev libdb5.3 libdb5.3-dev libdb5.3++-dev libsqlite3-dev libnatpmp-dev\n\n#################################################################\n# Build Groestlcoin Core from source                                     #\n#################################################################\ncd /usr/local\nfile=/usr/local/groestlcoin\nif [ ! -e \"$file\" ]\nthen\n\tsudo git clone https://github.com/groestlcoin/groestlcoin.git\nfi\n\ncd /usr/local/groestlcoin\nfile=/usr/local/groestlcoin/src/groestlcoind\nif [ ! -e \"$file\" ]\nthen\n\tsudo ./autogen.sh\n\tsudo ./configure\n\tsudo make -j$NPROC\nfi\n\n#################################################################\n# Strip executables                                                     #\n#################################################################\nstrip /usr/local/groestlcoin/src/groestlcoind /usr/local/groestlcoin/src/groestlcoin-cli /usr/local/groestlcoin/src/groestlcoin-tx /usr/local/groestlcoin/src/groestlcoin-wallet /usr/local/groestlcoin/src/groestlcoin-util\n\n#################################################################\n# Move executables to /usr/bin                                           #\n#################################################################\nsudo mv /usr/local/groestlcoin/src/groestlcoind /usr/local/groestlcoin/src/groestlcoin-cli /usr/local/groestlcoin/src/groestlcoin-tx /usr/local/groestlcoin/src/groestlcoin-wallet /usr/local/groestlcoin/src/groestlcoin-util /usr/bin\n\nelse\n#################################################################\n# Install Groestlcoin Core from PPA                                      #\n#################################################################\nsudo add-apt-repository -y ppa:groestlcoin/groestlcoin\nsudo apt-get update\nsudo apt-get install -y groestlcoind groestlcoin-tx groestlcoin-wallet\n\nfi\n\n################################################################\n# Create Groestlcoin Core Directory                                      #\n################################################################\nif [ ! -e \"$GROESTLCOINPATH\" ]\nthen\n\tsu - $AZUREUSER -c \"mkdir $GROESTLCOINPATH\"\nfi\n\n#################################################################\n# Install pwgen for generating pronounceable RPC username and password for configuration file #\n#################################################################\nsudo apt-get -y install pwgen\n\n################################################################\n# Create configuration File                                              #\n################################################################\nsu - $AZUREUSER -c \"touch $GROESTLCOINPATH/groestlcoin.conf\"\nrpcu=$(pwgen -ncsB 35 1)\nrpcp=$(pwgen -ncsB 75 1)\necho \"rpcuser=\"$rpcu\"\nrpcpassword=\"$rpcp\"\nserver=1\nlisten=1\ndaemon=1\" > $GROESTLCOINPATH/groestlcoin.conf\n\n################################################################\n# Configure to auto start at boot                                        #\n################################################################\nfile=/etc/init.d/groestlcoin\nif [ ! -e \"$file\" ]\nthen\n\tprintf '%s\\n%s\\n' '#!/bin/sh' '/usr/bin/groestlcoind' | sudo tee /etc/init.d/groestlcoin\n\tsudo chmod +x /etc/init.d/groestlcoin\n\tsudo update-rc.d groestlcoin defaults\nfi\n\n################################################################\n# Start Groestlcoin Core                                                 #\n################################################################\nsu - $AZUREUSER -c \"groestlcoind\"\necho \"Groestlcoin Core has been setup successfully and is running $$\"\nexit 0\n", "num_lines": 116}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nkey=$1\ncert=$2\n\nopenssl genrsa -out $key 2048 >/dev/null 2>&1\nopenssl req -new -x509 -days 365 -key $key -out $cert >/dev/null 2>&1 << EndOfMessage\nAU\nZJU\nZHCN\nLinux\nSoft\nSShKey\ntest@abc.com\nEndOfMessage\n", "num_lines": 18}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\nexport BOSH_INIT_LOG_LEVEL=\"Debug\"\nexport BOSH_INIT_LOG_PATH=\"./run.log\"\nbosh-init deploy ~/bosh.yml\n\nbosh target REPLACE_WITH_BOSH_DIRECOT_IP >/dev/null 2>&1 << EndOfMessage\nadmin\nadmin\nEndOfMessage\n\nsed -i -e \"s/REPLACE_WITH_DIRECTOR_ID/$(bosh status --uuid)/\" ./example_manifests/cross.yml\n", "num_lines": 15}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ $# -ne 1 || -z \"$1\" ]]; then\n    echo \"Usage: ./deploy_cloudfoundry.sh <path-to-your-manifest>\"\n    exit 1\nfi\n\nset -e\n\nbosh upload stemcell REPLACE_WITH_STEMCELL_URL --skip-if-exists\nbosh upload release REPLACE_WITH_CF_RELEASE_URL --skip-if-exists\n\nmanifest=$1\nbosh deployment $manifest\nbosh -n deploy\n", "num_lines": 16}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -e\n\necho \"Start to install prerequisites...\"\nsudo apt-get install -y build-essential ruby2.0 ruby2.0-dev libxml2-dev libsqlite3-dev libxslt1-dev libpq-dev libmysqlclient-dev zlibc zlib1g-dev openssl libxslt-dev libssl-dev libreadline6 libreadline6-dev libyaml-dev sqlite3 libffi-dev\n\n# Update Ruby 1.9 to 2.0\nsudo rm /usr/bin/ruby /usr/bin/gem /usr/bin/irb /usr/bin/rdoc /usr/bin/erb\nsudo ln -s /usr/bin/ruby2.0 /usr/bin/ruby\nsudo ln -s /usr/bin/gem2.0 /usr/bin/gem\nsudo ln -s /usr/bin/irb2.0 /usr/bin/irb\nsudo ln -s /usr/bin/rdoc2.0 /usr/bin/rdoc\nsudo ln -s /usr/bin/erb2.0 /usr/bin/erb\n\nset +e\n\nenvironment=$1\nif [ \"$environment\" == \"AzureChinaCloud\" ]; then\n  sudo gem sources --remove https://rubygems.org/\n  sudo gem sources --add https://ruby.taobao.org/\n  sudo gem sources --add https://gems.ruby-china.org/\nfi\n\nset -e\n\ngem sources -l\nsudo gem update --system\nsudo gem pristine --all\n\necho \"Start to install bosh_cli...\"\nsudo gem install bosh_cli -v 1.3169.0 --no-ri --no-rdoc\n\necho \"Start to install bosh-init...\"\nbosh_init_url=$2\nwget $bosh_init_url\nchmod +x ./bosh-init-*\nsudo mv ./bosh-init-* /usr/local/bin/bosh-init\n\necho \"Finish\"\n", "num_lines": 41}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nif [[ $# -ne 1 || -z \"$1\" ]]; then\n    echo \"Usage: ./update-china-storage-account.sh <template-version>. For example: ./update-china-storage-account.sh v1-0-0\"\n    exit 1\nfi\n\nset -e\n\n# The template version should be same as variables('templateVersion') in azuredeploy.json\ntemplate_version=\"$1\"\ncontainer_name=\"bosh-setup\"\n\n# Upload CPI release\nrelease_name=\"bosh-azure-cpi-release-35.5.0.tgz\"\nwget https://bosh.io/d/github.com/cloudfoundry/bosh-azure-cpi-release?v=35.5.0 -O /tmp/${release_name}\naz storage blob upload -f /tmp/${release_name} -c ${container_name} -n cpi-releases/${release_name}\nrm /tmp/${release_name}\n\n# Upload Stemcell\nstemcell_name=\"bosh-stemcell-170.3-azure-hyperv-ubuntu-xenial-go_agent.tgz\"\nwget https://s3.amazonaws.com/bosh-core-stemcells/azure/${stemcell_name} -O /tmp/${stemcell_name}\naz storage blob upload -f /tmp/${stemcell_name} -c ${container_name} -n bosh-azure-stemcells/${stemcell_name}\nrm /tmp/${stemcell_name}\n\n# Upload DNS release\nrelease_name=\"bosh-dns-release-1.10.0.tgz\"\nwget https://bosh.io/d/github.com/cloudfoundry/bosh-dns-release?v=1.10.0 -O /tmp/${release_name}\naz storage blob upload -f /tmp/${release_name} -c ${container_name} -n dns-releases/${release_name}\nrm /tmp/${release_name}\n\n# Upload releases\npushd manifests\n  file_names=\"bosh.yml uaa.yml credhub.yml\"\n  for file_name in ${file_names}\n  do\n    release_urls=$(grep \"s3.amazonaws.com\" ${file_name} | awk '{print $2}')\n    for release_url in ${release_urls}\n    do\n      release_url=$(sed -e 's/^\"//' -e 's/\"$//' <<< $release_url)\n      IFS='/ ' read -r -a array <<< \"$release_url\"\n      release_name=${array[-1]}\n      wget ${release_url} -O /tmp/${release_name}\n      az storage blob upload -f /tmp/${release_name} -c ${container_name} -n bosh-compiled-release-tarballs/${release_name}\n      rm /tmp/${release_name}\n    done\n  done\n\n  file_names=\"use-compiled-releases.yml\"\n  for file_name in ${file_names}\n  do\n    release_urls=$(grep \"storage.googleapis.com\" ${file_name} | awk '{print $2}')\n    for release_url in ${release_urls}\n    do\n      release_url=$(sed -e 's/^\"//' -e 's/\"$//' <<< $release_url)\n      IFS='/ ' read -r -a array <<< \"$release_url\"\n      release_name=${array[-1]}\n      wget ${release_url} -O /tmp/${release_name}\n      az storage blob upload -f /tmp/${release_name} -c ${container_name} -n cf-deployment-compiled-releases/${release_name}\n      rm /tmp/${release_name}\n    done\n  done\npopd\n\ndirectories=\"scripts manifests\"\nfor directory in $directories; do\n  for file in $directory/*; do\n    if [[ -f $file ]]; then\n      az storage blob upload -f $file -c ${container_name} -n ${template_version}/$file\n    fi\n  done\ndone\n\nbosh_cli_version=\"5.2.2\"\nbosh_cli_name=\"bosh-cli-${bosh_cli_version}-linux-amd64\"\nwget https://s3.amazonaws.com/bosh-cli-artifacts/${bosh_cli_name} -O /tmp/${bosh_cli_name}\naz storage blob upload -f /tmp/${bosh_cli_name} -c ${container_name} -n bosh-cli/${bosh_cli_name}\n\ncf_cli_version=\"6.39.0\"\ncf_cli_name=\"cf-cli-installer_${cf_cli_version}_x86-64.deb\"\nwget https://s3-us-west-1.amazonaws.com/cf-cli-releases/releases/v${cf_cli_version}/${cf_cli_name} -O /tmp/${cf_cli_name}\naz storage blob upload -f /tmp/${cf_cli_name} -c ${container_name} -n cf-cli/${cf_cli_name}\n", "num_lines": 83}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is for development purpose. Run the script when upgrading the manifests of bosh-deployment and cf-deployment.\n\npushd manifests\n  # bosh-deployment\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/bosh.yml -O bosh.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/jumpbox-user.yml -O jumpbox-user.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/uaa.yml -O uaa.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/credhub.yml -O credhub.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/runtime-configs/dns.yml -O dns.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/azure/cpi.yml -O cpi.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/azure/custom-environment.yml -O custom-environment.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/bosh-deployment/master/azure/use-managed-disks.yml -O use-managed-disks.yml\n\n  # cf-deployment\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/cf-deployment.yml -O cf-deployment.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/operations/azure.yml -O azure.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/operations/use-external-blobstore.yml -O use-external-blobstore.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/operations/use-azure-storage-blobstore.yml -O use-azure-storage-blobstore.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/operations/scale-to-one-az.yml -O scale-to-one-az.yml\n  wget https://raw.githubusercontent.com/cloudfoundry/cf-deployment/master/operations/use-compiled-releases.yml -O use-compiled-releases.yml\n  cp use-compiled-releases.yml use-mirror-compiled-releases.yml\n  sed -i 's/storage.googleapis.com/cloudfoundry.blob.core.chinacloudapi.cn\\/bosh-setup/g' use-mirror-compiled-releases.yml\npopd\n", "num_lines": 26}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource utils.sh\n\nset -e\n\necho \"Installing jq\"\nretryop \"apt-get update && apt-get install -y jq\"\n\ncustom_data_file=\"/var/lib/cloud/instance/user-data.txt\"\nsettings=$(cat ${custom_data_file})\nfunction get_setting() {\n  key=$1\n  local value=$(echo $settings | jq \".$key\" -r)\n  echo $value\n}\n\n# Service Principal\nenvironment=$(get_setting ENVIRONMENT)\nservice_principal_type=$(get_setting SERVICE_PRINCIPAL_TYPE)\ntenant_id=$1\nclient_id=$2\nbase64_encoded_client_secret_or_certificate=$3\nfunction client_secret_or_certificate() {\n  echo ${base64_encoded_client_secret_or_certificate} | base64 --decode\n}\n\n# https://bosh.io/docs/cli-v2-install/#additional-dependencies\necho \"Installing OS specified dependencies for bosh create-env command\"\nretryop \"apt-get update && apt-get install -y build-essential zlibc zlib1g-dev ruby ruby-dev openssl libxslt-dev libxml2-dev libssl-dev libreadline6 libreadline6-dev libyaml-dev libsqlite3-dev sqlite3\"\n\necho \"Installing BOSH CLI\"\nbosh_cli_url=$(get_setting BOSH_CLI_URL)\nwget $bosh_cli_url\nchmod +x ./bosh-cli-*\nmv ./bosh-cli-* /usr/local/bin/bosh\n\n# https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-apt?view=azure-cli-latest#install\necho \"Installing Azure CLI\"\nAZ_REPO=$(lsb_release -cs)\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main\" | tee /etc/apt/sources.list.d/azure-cli.list\ncurl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -\nretryop \"apt-get install apt-transport-https\"\nretryop \"apt-get update && apt-get install azure-cli=2.0.33-1~$AZ_REPO\"\n\necho \"Creating the containers (bosh and stemcell) and the table (stemcells) in the default storage account\"\ndefault_storage_account=$(get_setting DEFAULT_STORAGE_ACCOUNT_NAME)\ndefault_storage_access_key=$(get_setting DEFAULT_STORAGE_ACCESS_KEY)\nendpoint_suffix=$(get_setting SERVICE_HOST_BASE)\nconnection_string=\"DefaultEndpointsProtocol=https;AccountName=${default_storage_account};AccountKey=${default_storage_access_key};EndpointSuffix=${endpoint_suffix}\"\nif [ \"$environment\" = \"AzureStack\" ]; then\n  cat /var/lib/waagent/Certificates.pem >> /etc/ssl/certs/ca-certificates.crt\n  export REQUESTS_CA_BUNDLE=/etc/ssl/certs/ca-certificates.crt\n  az cloud update --profile 2017-03-09-profile\nfi\naz storage container create --name bosh --connection-string ${connection_string}\naz storage container create --name stemcell --connection-string ${connection_string}\naz storage table create --name stemcells --connection-string ${connection_string}\n\nusername=$(get_setting ADMIN_USER_NAME)\nhome_dir=\"/home/$username\"\n\nmanifests_dir=\"$home_dir/example_manifests\"\nmkdir -p $manifests_dir\ncp *.yml $manifests_dir\npushd $manifests_dir > /dev/null\n  # Enable availability zones if needed\n  use_availability_zones=$(get_setting USE_AVAILABILITY_ZONES)\n  if [ \"$use_availability_zones\" == \"enabled\" ]; then\n    sed -i '1,5d' cloud-config.yml\n    cat - cloud-config.yml > cloud-config-azs-enabled.yml << EOF\n---\nazs:\n- name: z1\n  cloud_properties:\n    availability_zone: '1'\n- name: z2\n  cloud_properties:\n    availability_zone: '2'\n- name: z3\n  cloud_properties:\n    availability_zone: '3'\nEOF\n    mv cloud-config-azs-enabled.yml cloud-config.yml\n  fi\n  if [ \"${service_principal_type}\" == \"Certificate\" ]; then\n    cat > service-principal-certificate.yml << EOF\ncertificate: |-\n$(client_secret_or_certificate | sed 's/^/  /')\nEOF\n  fi\n  if [ \"$environment\" = \"AzureStack\" ]; then\n    if [ \"$(get_setting AZURE_STACK_CA_ROOT_CERTIFICATE | base64 --decode)\" = \"\" ]; then\n      cat > azure-stack-ca-cert.yml << EOF\nca_cert: |-\n$(cat /var/lib/waagent/Certificates.pem | sed 's/^/  /')\nEOF\n    else\n      cat > azure-stack-ca-cert.yml << EOF\nca_cert: |-\n$(get_setting AZURE_STACK_CA_ROOT_CERTIFICATE | base64 --decode | sed 's/^/  /')\nEOF\n    fi\n  fi\npopd  > /dev/null\nchmod 775 $manifests_dir\nchmod 644 $manifests_dir/*\ndpkg -i cf-cli*\n\ncat > \"$home_dir/deploy_bosh.sh\" << EOF\n#!/usr/bin/env bash\n\nset -e\n\nexport BOSH_LOG_LEVEL=\"$(get_setting LOG_LEVEL_FOR_BOSH)\"\nexport BOSH_LOG_PATH=\"./run.log\"\n\nbosh create-env ~/example_manifests/bosh.yml \\\\\n  --state=state.json \\\\\n  --vars-store=~/bosh-deployment-vars.yml \\\\\n  -o ~/example_manifests/cpi.yml \\\\\n  -o ~/example_manifests/use-location.yml \\\\\n  -o ~/example_manifests/custom-cpi-release.yml \\\\\n  -o ~/example_manifests/custom-environment.yml \\\\\n  -o ~/example_manifests/use-azure-dns.yml \\\\\n  -o ~/example_manifests/jumpbox-user.yml \\\\\n  -o ~/example_manifests/keep-failed-or-unreachable-vms.yml \\\\\n  -o ~/example_manifests/uaa.yml \\\\\n  -o ~/example_manifests/credhub.yml \\\\\n  -v director_name=azure \\\\\n  -v internal_cidr=10.0.0.0/24 \\\\\n  -v internal_gw=10.0.0.1 \\\\\n  -v internal_ip=10.0.0.4 \\\\\n  -v cpi_release_url=$(get_setting BOSH_AZURE_CPI_RELEASE_URL) \\\\\n  -v cpi_release_sha1=$(get_setting BOSH_AZURE_CPI_RELEASE_SHA1) \\\\\n  -v director_vm_instance_type=$(get_setting BOSH_VM_SIZE) \\\\\n  -v resource_group_name=$(get_setting RESOURCE_GROUP_NAME) \\\\\n  -v location=$(get_setting LOCATION) \\\\\n  -v vnet_name=$(get_setting VNET_NAME) \\\\\n  -v subnet_name=$(get_setting SUBNET_NAME_FOR_BOSH) \\\\\n  -v default_security_group=$(get_setting NSG_NAME_FOR_BOSH) \\\\\n  -v environment=$(get_setting ENVIRONMENT) \\\\\n  -v subscription_id=$(get_setting SUBSCRIPTION_ID) \\\\\n  -v tenant_id=${tenant_id} \\\\\n  -v client_id=${client_id} \\\\\nEOF\n\nif [ \"${service_principal_type}\" == \"Password\" ]; then\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -v client_secret=\"$(client_secret_or_certificate)\" \\\\\nEOF\nelif [ \"${service_principal_type}\" == \"Certificate\" ]; then\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -o ~/example_manifests/use-service-principal-with-certificate.yml \\\\\n  -l ~/example_manifests/service-principal-certificate.yml \\\\\nEOF\nfi\n\nif [ \"$environment\" = \"AzureStack\" ]; then\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -o ~/example_manifests/use-trusted-certs.yml \\\\\nEOF\nfi\n\nif [ \"$environment\" = \"AzureChinaCloud\" ]; then\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -o ~/example_manifests/use-managed-disks.yml \\\\\n  -o ~/example_manifests/use-mirror-releases-for-bosh.yml \\\\\n  -o ~/example_manifests/custom-ntp-server.yml\nEOF\nelif [ \"$environment\" = \"AzureStack\" ]; then\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -v storage_account_name=$(get_setting DEFAULT_STORAGE_ACCOUNT_NAME) \\\\\n  -o ~/example_manifests/azure-stack-properties.yml \\\\\n  -v azure_stack_domain=$(get_setting AZURE_STACK_DOMAIN) \\\\\n  -v azure_stack_resource=$(get_setting AZURE_STACK_RESOURCE) \\\\\n  -v azure_stack_authentication=$(get_setting AZURE_STACK_AUTHENTICATION) \\\\\n  -l ~/example_manifests/azure-stack-ca-cert.yml\nEOF\nelse\n  cat >> \"$home_dir/deploy_bosh.sh\" << EOF\n  -o ~/example_manifests/use-managed-disks.yml\nEOF\nfi\n\ncat >> \"$home_dir/deploy_bosh.sh\" << EOF\n\ncat >> \"$home_dir/.profile\" << EndOfFile\n# BOSH CLI\nexport BOSH_ENVIRONMENT=10.0.0.4\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\nEndOfFile\nsource $home_dir/.profile\nEOF\n\nchmod 777 $home_dir/deploy_bosh.sh\n\ncat > \"$home_dir/login_bosh.sh\" << EOF\n#!/usr/bin/env bash\n\nexport BOSH_ENVIRONMENT=10.0.0.4\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\n\nbosh alias-env azure\nbosh -e azure login\nEOF\nchmod 777 $home_dir/login_bosh.sh\n\ncat > \"$home_dir/connect_director_vm.sh\" << EOF\n#!/usr/bin/env bash\n\nbosh int ~/bosh-deployment-vars.yml --path /jumpbox_ssh/private_key > jumpbox.key\nchmod 600 jumpbox.key\nssh jumpbox@10.0.0.4 -i jumpbox.key\nEOF\nchmod 777 $home_dir/connect_director_vm.sh\n\nsystem_domain=$(get_setting SYSTEM_DOMAIN)\nif [ \"${system_domain}\" = \"NotConfigured\" ]; then\n  system_domain=\"$(get_setting CLOUD_FOUNDRY_PUBLIC_IP).xip.io\"\nfi\ncat > \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n#!/usr/bin/env bash\n\nexport BOSH_ENVIRONMENT=10.0.0.4\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\n\nbosh alias-env azure\nbosh -e azure login\n\nbosh -n update-cloud-config ~/example_manifests/cloud-config.yml \\\\\n  -v internal_cidr=10.0.16.0/20 \\\\\n  -v internal_gw=10.0.16.1 \\\\\n  -v vnet_name=$(get_setting VNET_NAME) \\\\\n  -v subnet_name=$(get_setting SUBNET_NAME_FOR_CLOUD_FOUNDRY) \\\\\n  -v security_group=$(get_setting NSG_NAME_FOR_CLOUD_FOUNDRY) \\\\\n  -v load_balancer_name=$(get_setting LOAD_BALANCER_NAME)\nEOF\n\nif [ \"$environment\" = \"AzureChinaCloud\" ]; then\n  cat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\nbosh -n update-runtime-config ~/example_manifests/dns.yml \\\\\n  -o ~/example_manifests/use-mirror-bosh-dns-release.yml \\\\\n  --name=dns\nEOF\nelse\n  cat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\nbosh -n update-runtime-config ~/example_manifests/dns.yml \\\\\n  --name=dns\nEOF\nfi\n\ncat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\nbosh upload-stemcell --sha1=$(get_setting STEMCELL_SHA1) $(get_setting STEMCELL_URL)\n\nbosh -n -d cf deploy ~/example_manifests/cf-deployment.yml \\\\\n  --vars-store=~/cf-deployment-vars.yml \\\\\n  -o ~/example_manifests/azure.yml \\\\\n  -o ~/example_manifests/scale-to-one-az.yml \\\\\nEOF\n\nif [ \"$environment\" = \"AzureChinaCloud\" ]; then\n  cat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n  -o ~/example_manifests/use-mirror-compiled-releases.yml \\\\\nEOF\nelse\n  cat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n  -o ~/example_manifests/use-compiled-releases.yml \\\\\nEOF\nfi\n\ncat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n  -o ~/example_manifests/use-external-blobstore.yml \\\\\n  -v app_package_directory_key=cc-packages \\\\\n  -v buildpack_directory_key=cc-buildpacks \\\\\n  -v droplet_directory_key=cc-droplets \\\\\n  -v resource_directory_key=cc-resources \\\\\n  -o ~/example_manifests/use-azure-storage-blobstore.yml \\\\\n  -v environment=$(get_setting ENVIRONMENT) \\\\\n  -v blobstore_storage_account_name=$(get_setting DEFAULT_STORAGE_ACCOUNT_NAME) \\\\\n  -v blobstore_storage_access_key=$(get_setting DEFAULT_STORAGE_ACCESS_KEY) \\\\\nEOF\nif [ \"$environment\" = \"AzureStack\" ]; then\n  cat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n  -o ~/example_manifests/use-azure-stack-storage-blobstore.yml \\\\\n  -v blobstore_storage_dns_suffix=${endpoint_suffix} \\\\\nEOF\nfi\ncat >> \"$home_dir/deploy_cloud_foundry.sh\" << EOF\n  -v system_domain=${system_domain}\nEOF\nchmod 777 $home_dir/deploy_cloud_foundry.sh\n\ncat > \"$home_dir/login_cloud_foundry.sh\" << EOF\n#!/usr/bin/env bash\n\ncf_admin_password=\"\\$(bosh int ~/cf-deployment-vars.yml --path /cf_admin_password)\"\n\ncf login -a https://api.${system_domain} -u admin -p \"\\${cf_admin_password}\" --skip-ssl-validation\nEOF\nchmod 777 $home_dir/login_cloud_foundry.sh\n\nchown -R $username $home_dir\n\necho \"The devbox is prepared successfully.\"\n\nauto_deploy_bosh=$(get_setting AUTO_DEPLOY_BOSH)\nif [ \"$auto_deploy_bosh\" != \"enabled\" ]; then\n  echo \"The BOSH director won't be deployed automatically. Finish.\"\n  exit 0\nfi\n\necho \"Starting to deploy BOSH director...\"\nsu - $username -c \"./deploy_bosh.sh\"\necho \"The BOSH director is deployed successfully. Please check run.log.\"\n\nauto_deploy_cf=$(get_setting AUTO_DEPLOY_CLOUD_FOUNDRY)\nif [ \"$auto_deploy_cf\" != \"enabled\" ]; then\n  echo \"The Cloud Foundry won't be deployed automatically. Finish.\"\n  exit 0\nfi\n\necho \"Starting to deploy Cloud Foundry, which would take some time...\"\nnohup su - $username -c \"./deploy_cloud_foundry.sh\" &\n\necho \"Finish\"\nexit 0\n", "num_lines": 334}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction retryop()\n{\n  set +e\n  retry=0\n  max_retries=10\n  interval=30\n  while [ ${retry} -lt ${max_retries} ]; do\n    echo \"Operation: $1, Retry #${retry}\"\n    eval $1\n    if [ $? -eq 0 ]; then\n      echo \"Successful\"\n      break\n    else\n      let retry=retry+1\n      echo \"Sleep $interval seconds, then retry...\"\n      sleep $interval\n    fi\n  done\n  if [ ${retry} -eq ${max_retries} ]; then\n    echo \"Operation failed: $1\"\n    exit 1\n  fi\n  set -e\n}\n", "num_lines": 27}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# BE Secondary\ncurl --retry 3 --silent --show-error -o chef-backend-secrets.json \"$1/chef-backend-secrets.json$2\"\n\napt-get install -y apt-transport-https\nwget -qO - https://downloads.chef.io/packages-chef-io-public.key | sudo apt-key add -\necho \"deb https://packages.chef.io/stable-apt trusty main\" > /etc/apt/sources.list.d/chef-stable.list\napt-get update\n\n# store data on external persistent volume\napt-get install lvm2 xfsprogs sysstat atop -y\numount -f /mnt\npvcreate -f /dev/SOMETHING\nvgcreate chef-vg /dev/SOMETHING\nlvcreate -n chef-lv -l 80%VG chef-vg\nmkfs.xfs /dev/chef-vg/chef-lv\nmkdir -p /var/opt/chef-backend\nmount /dev/chef-vg/chef-lv /var/opt/chef-backend\n\n# Chef server setup\napt-get install -y chef-backend\n\n# Grab IP address and prepopulate configuration\nIPADRESS=`ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'`\ncat > /etc/chef-backend/chef-backend.rb <<EOF\npublish_address '${IPADRESS}'\npostgresql.log_min_duration_statement = 500\nelasticsearch.heap_size = 3500\nEOF\n\nchef-backend-ctl join-cluster 10.0.0.10 -s chef-backend-secrets.json --accept-license --yes --verbose --quiet\n\n# enable basic data collection\necho 'ENABLED=\"true\"' > /etc/default/sysstat\nservice sysstat start\n", "num_lines": 35}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Primary BE setup\napt-get install -y apt-transport-https\nwget -qO - https://downloads.chef.io/packages-chef-io-public.key | sudo apt-key add -\necho \"deb https://packages.chef.io/stable-apt trusty main\" > /etc/apt/sources.list.d/chef-stable.list\napt-get update\n\n# store data on persisten, external volume\napt-get install lvm2 xfsprogs sysstat atop -y\numount -f /mnt\npvcreate -f /dev/SOMETHING\nvgcreate chef-vg /dev/SOMETHING\nlvcreate -n chef-lv -l 80%VG chef-vg\nmkfs.xfs /dev/chef-vg/chef-lv\nmkdir -p /var/opt/chef-backend\nmount /dev/chef-vg/chef-lv /var/opt/chef-backend\n\n# Chef server setup\napt-get install -y chef-backend\n\n# Grab IP address and prepopulate configuration\nIPADRESS=`ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'`\ncat > /etc/chef-backend/chef-backend.rb <<EOF\npublish_address '${IPADRESS}'\npostgresql.log_min_duration_statement = 500\nelasticsearch.heap_size = 3500\nEOF\n\nchef-backend-ctl create-cluster --accept-license --yes --quiet --verbose\n\ncurl --retry 3 --silent --show-error --upload-file /etc/chef-backend/chef-backend-secrets.json \"$1/chef-backend-secrets.json$2\" --header \"x-ms-blob-type: BlockBlob\"\nchef-backend-ctl gen-server-config fe0 -f chef-server.rb.fe0\ncurl --retry 3 --silent --show-error --upload-file chef-server.rb.fe0 \"$1/chef-server.rb.fe0$2\" --header \"x-ms-blob-type: BlockBlob\"\nchef-backend-ctl gen-server-config fe1 -f chef-server.rb.fe1\ncurl --retry 3 --silent --show-error --upload-file chef-server.rb.fe1 \"$1/chef-server.rb.fe1$2\" --header \"x-ms-blob-type: BlockBlob\"\nchef-backend-ctl gen-server-config fe2 -f chef-server.rb.fe2\ncurl --retry 3 --silent --show-error --upload-file chef-server.rb.fe2 \"$1/chef-server.rb.fe2$2\" --header \"x-ms-blob-type: BlockBlob\"\n\n# enable basic data collection\necho 'ENABLED=\"true\"' > /etc/default/sysstat\nservice sysstat start\n", "num_lines": 41}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# First FE\n#wget https://packages.chef.io/stable/ubuntu/14.04/chef-server-core_12.8.0-1_amd64.deb\n#dpkg -i chef-server-core_12.8.0-1_amd64.deb\napt-get install -y apt-transport-https\nwget -qO - https://downloads.chef.io/packages-chef-io-public.key | sudo apt-key add -\necho \"deb https://packages.chef.io/stable-apt trusty main\" > /etc/apt/sources.list.d/chef-stable.list\napt-get update\n\n# store data on local ssd\napt-get install lvm2 xfsprogs sysstat atop -y\numount -f /mnt\npvcreate -f /dev/sdb1\nvgcreate chef-vg /dev/sdb1\nlvcreate -n chef-data -l 20%VG chef-vg\nlvcreate -n chef-logs -l 80%VG chef-vg\nmkfs.xfs /dev/chef-vg/chef-data\nmkfs.xfs /dev/chef-vg/chef-logs\nmkdir -p /var/opt/opscode\nmkdir -p /var/log/opscode\nmount /dev/chef-vg/chef-data /var/opt/opscode\nmount /dev/chef-vg/chef-logs /var/log/opscode\n\n# Chef server setup\napt-get install -y chef-server-core chef-manage\ncurl -o /etc/opscode/chef-server.rb \"$1/chef-server.rb.fe0$2\"\n\ncat >> /etc/opscode/chef-server.rb <<EOF\nopscode_erchef['s3_url_expiry_window_size'] = '100%'\nlicense['nodes'] = 999999\noc_chef_authz['http_init_count'] = 100\noc_chef_authz['http_max_count'] = 100\noc_chef_authz['http_queue_max'] = 200\noc_bifrost['db_pool_size'] = 20\noc_bifrost['db_pool_queue_max'] = 40\noc_bifrost['db_pooler_timeout'] = 2000\nopscode_erchef['depsolver_worker_count'] = 4\nopscode_erchef['depsolver_timeout'] = 20000\nopscode_erchef['db_pool_size'] = 20\nopscode_erchef['db_pool_queue_max'] = 40\nopscode_erchef['db_pooler_timeout'] = 2000\nopscode_erchef['authz_pooler_timeout'] = 2000\nEOF\n\n\nchef-server-ctl reconfigure --accept-license\ncurl --retry 3 --silent --show-error --upload-file /etc/opscode/private-chef-secrets.json \"$1/private-chef-secrets.json$2\" --header \"x-ms-blob-type: BlockBlob\"\ncurl --retry 3 --silent --show-error --upload-file /etc/opscode/webui_priv.pem \"$1/webui_priv.pem$2\" --header \"x-ms-blob-type: BlockBlob\"\ncurl --retry 3 --silent --show-error --upload-file /etc/opscode/webui_pub.pem \"$1/webui_pub.pem$2\" --header \"x-ms-blob-type: BlockBlob\"\ncurl --retry 3 --silent --show-error --upload-file /etc/opscode/pivotal.pem \"$1/pivotal.pem$2\" --header \"x-ms-blob-type: BlockBlob\"\ncurl --retry 3 --silent --show-error --upload-file /var/opt/opscode/upgrades/migration-level \"$1/migration-level$2\" --header \"x-ms-blob-type: BlockBlob\"\n\nsudo chef-manage-ctl reconfigure --accept-license\n\n# enable basic data collection\necho 'ENABLED=\"true\"' > /etc/default/sysstat\nservice sysstat start\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Other FEs\napt-get install -y apt-transport-https\nwget -qO - https://downloads.chef.io/packages-chef-io-public.key | sudo apt-key add -\necho \"deb https://packages.chef.io/stable-apt trusty main\" > /etc/apt/sources.list.d/chef-stable.list\napt-get update\n\n# store data on local ssd\napt-get install lvm2 xfsprogs sysstat atop -y\numount -f /mnt\npvcreate -f /dev/sdb1\nvgcreate chef-vg /dev/sdb1\nlvcreate -n chef-data -l 20%VG chef-vg # data is small, because it's only the cookbook cache\nlvcreate -n chef-logs -l 80%VG chef-vg\nmkfs.xfs /dev/chef-vg/chef-data\nmkfs.xfs /dev/chef-vg/chef-logs\nmkdir -p /var/opt/opscode\nmkdir -p /var/log/opscode\nmount /dev/chef-vg/chef-data /var/opt/opscode\nmount /dev/chef-vg/chef-logs /var/log/opscode\n\n# Chef server setup\napt-get install -y chef-server-core chef-manage\ncurl --retry 3 --silent --show-error -o /etc/opscode/chef-server.rb \"$1/chef-server.rb.`hostname`$2\"\n\ncat >> /etc/opscode/chef-server.rb <<EOF\nopscode_erchef['s3_url_expiry_window_size'] = '100%'\nlicense['nodes'] = 999999\noc_chef_authz['http_init_count'] = 100\noc_chef_authz['http_max_count'] = 100\noc_chef_authz['http_queue_max'] = 200\noc_bifrost['db_pool_size'] = 20\noc_bifrost['db_pool_queue_max'] = 40\noc_bifrost['db_pooler_timeout'] = 2000\nopscode_erchef['depsolver_worker_count'] = 4\nopscode_erchef['depsolver_timeout'] = 20000\nopscode_erchef['db_pool_size'] = 20\nopscode_erchef['db_pool_queue_max'] = 40\nopscode_erchef['db_pooler_timeout'] = 2000\nopscode_erchef['authz_pooler_timeout'] = 2000\nEOF\n\ncurl --retry 3 --silent --show-error -o /etc/opscode/private-chef-secrets.json \"$1/private-chef-secrets.json$2\"\ncurl --retry 3 --silent --show-error -o /etc/opscode/webui_priv.pem \"$1/webui_priv.pem$2\"\ncurl --retry 3 --silent --show-error -o /etc/opscode/webui_pub.pem \"$1/webui_pub.pem$2\"\ncurl --retry 3 --silent --show-error -o /etc/opscode/pivotal.pem \"$1/pivotal.pem$2\"\nmkdir -p /var/opt/opscode/upgrades/\ncurl --retry 3 --silent --show-error -o /var/opt/opscode/upgrades/migration-level \"$1/migration-level$2\"\ntouch /var/opt/opscode/bootstrapped\nchef-server-ctl reconfigure --accept-license\nsudo chef-manage-ctl reconfigure --accept-license\n\n# enable basic data collection\necho 'ENABLED=\"true\"' > /etc/default/sysstat\nservice sysstat start\n", "num_lines": 55}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#1 - USER_NAME\n#2 - FIRST_NAME\n#3 - LAST_NAME\n#4 - EMAIL\n#5 - 'PASSWORD'\n#6 - short_name\n#7 - 'full_organization_name'\n#8 - 'FQDN of the orchestrator'\n##Checking availability of file pivotal.pem before creating organisation and user.\n#while [ ! -f /etc/opscode/pivotal.pem ]; do\n#sleep 60s; done\n#while [ ! -f /etc/opscode/pivotal.pem ]\n#do\n#\tsleep 180\n#done\nsleep 600\n##pull files from repo\nwget https://trendmicrop2p.blob.core.windows.net/trendmicropushtopilot/files/validatorkey.txt  -O /tmp/validatorkey.txt\nwget https://trendmicrop2p.blob.core.windows.net/trendmicropushtopilot/files/userkey.txt -O /tmp/userkey.txt\n\n##Assigning variable to construct and update key and key-value\nvalidatorkey=`cat /tmp/validatorkey.txt`\nuserkey=`cat /tmp/userkey.txt`\n##Creating user for Chef Web UI\nsudo /usr/bin/chef-server-ctl user-create $1 $2 $3 $4 $5 --filename /etc/opscode/$1.pem\n##Creating Organization and assigning user.\nsudo /usr/bin/chef-server-ctl org-create $6 $7 --association $1 --filename /etc/opscode/$6-validator.pem\n#Upload key value.\nFINAL=\"\\\"}' \"$8\necho $validatorkey`cat /etc/opscode/${6}-validator.pem | base64 | tr -d '\\n'`$FINAL| bash\necho $userkey`cat /etc/opscode/${1}.pem | base64 | tr -d '\\n'`$FINAL | bash\n", "num_lines": 34}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nkeyName=$1\norchestratorbaseurl=$2\n\nURL=\"http://$orchestratorbaseurl:33001/key/$keyName\"\necho $URL\n\n\n#this API retrieves the validator.pem given a keyname, decodes it and stores it in validator.pem file\nsudo curl -H \"Content-Type: application/json\" -X GET $URL | tr -d \"\\\"\" | base64 --decode > /etc/chef/validation.pem\n\n\n#Next step is run sudo chef-client so that it boot straps to server\nsudo chef-client\n", "num_lines": 15}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script Name: vm-disk-utils.sh\n# Author: Trent Swanson - Full Scale 180 Inc github:(trentmswanson)\n# Version: 0.1\n# Last Modified By: Roy Arsan github:(rarsan)\n# Description:\n#  This script automates the partitioning and formatting of data disks\n#  Data disks can be partitioned and formatted as seperate disks or in a RAID0 configuration\n#  The script will scan for unpartitioned and unformatted data disks and partition, format, and add fstab entries\n# Parameters :\n#  1 - b: The base directory for mount points (default: /datadisks)\n#  2 - s  Create a striped RAID0 Array (No redundancy)\n#  3 - h  Help\n# Note :\n# This script has only been tested on Ubuntu 12.04 LTS and must be root\n\nhelp()\n{\n    echo \"Usage: $(basename $0) [-b data_base | -p data_path] [-h] [-s]\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"   -b         base directory for mount points of separate disks (default: /datadisks). Non-applicable with -s option\"\n    echo \"   -p         path for mount point of RAID0 drive (default: /datadrive). Applicable with -s option\"\n    echo \"   -s         create a striped RAID array (no redundancy)\"\n    echo \"   -h         this help message\"\n}\n\nlog()\n{\n    # Un-comment the following if you would like to enable logging to a service\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n#A set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\n# Base path for data disk mount points\nDATA_BASE=\"/datadisks\"\n# Full path for data drive in case of RAID configuration\nDATA_PATH=\"/datadrive\"\n\n\nwhile getopts b:p:sh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case ${optname} in\n    b)  #set base path for data disks mount points\n      DATA_BASE=${OPTARG}\n      ;;\n    p)  #set path for data drive single point point\n      DATA_PATH=${OPTARG}\n      ;;\n    s) #Partition and format data disks as raid set\n      RAID_CONFIGURATION=1\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nget_next_md_device() {\n    shopt -s extglob\n    LAST_DEVICE=$(ls -1 /dev/md+([0-9]) 2>/dev/null|sort -n|tail -n1)\n    if [ -z \"${LAST_DEVICE}\" ]; then\n        NEXT=/dev/md0\n    else\n        NUMBER=$((${LAST_DEVICE/\\/dev\\/md/}))\n        NEXT=/dev/md${NUMBER}\n    fi\n    echo ${NEXT}\n}\n\nis_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\nhas_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_next_mountpoint() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    MAX=$(echo \"${DIRS}\"|tail -n 1 | tr -d \"[a-zA-Z/]\")\n    if [ -z \"${MAX}\" ];\n    then\n        echo \"${DATA_BASE}/disk1\"\n        return\n    fi\n    IDX=1\n    while [ \"${IDX}\" -lt \"${MAX}\" ];\n    do\n        NEXT_DIR=\"${DATA_BASE}/disk${IDX}\"\n        if [ ! -d \"${NEXT_DIR}\" ];\n        then\n            echo \"${NEXT_DIR}\"\n            return\n        fi\n        IDX=$(( ${IDX} + 1 ))\n    done\n    IDX=$(( ${MAX} + 1))\n    echo \"${DATA_BASE}/disk${IDX}\"\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\tnoatime,nodiratime,nodev,noexec,nosuid\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=83\n    fi\n    echo \"n\np\n1\n2048\n2145386495\nw\"| fdisk \"${_disk}\"\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${_disk}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n#end do_partition\n\nscan_partition_format()\n{\n    log \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n    if [ \"${#DISKS}\" -eq 0 ];\n    then\n        log \"No unpartitioned disks without filesystems detected\"\n        return\n    fi\n    echo \"Disks are ${DISKS[@]}\"\n    for DISK in \"${DISKS[@]}\";\n    do\n        echo \"Working on ${DISK}\"\n        is_partitioned ${DISK}\n        if [ ${?} -ne 0 ];\n        then\n            echo \"${DISK} is not partitioned, partitioning\"\n            do_partition ${DISK}\n        fi\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n        has_filesystem ${PARTITION}\n        if [ ${?} -ne 0 ];\n        then\n            echo \"Creating filesystem on ${PARTITION}.\"\n    #        echo \"Press Ctrl-C if you don't want to destroy all data on ${PARTITION}\"\n    #        sleep 10\n            mkfs -j -t ext4 ${PARTITION}\n        fi\n        MOUNTPOINT=$(get_next_mountpoint)\n        echo \"Next mount point appears to be ${MOUNTPOINT}\"\n        [ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n        read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n        add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n        echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n        mount \"${MOUNTPOINT}\"\n    done\n}\n\ncreate_striped_volume()\n{\n    DISKS=(${@})\n\n    if [ \"${#DISKS[@]}\" -eq 0 ];\n    then\n        log \"No unpartitioned disks without filesystems detected\"\n        return\n    fi\n\n    echo \"Disks are ${DISKS[@]}\"\n\n    declare -a PARTITIONS\n\n    for DISK in \"${DISKS[@]}\";\n    do\n        echo \"Working on ${DISK}\"\n        is_partitioned ${DISK}\n        if [ ${?} -ne 0 ];\n        then\n            echo \"${DISK} is not partitioned, partitioning\"\n            do_partition ${DISK} fd\n        fi\n\n        PARTITION=$(fdisk -l ${DISK}|grep -A 2 Device|tail -n 1|awk '{print $1}')\n        PARTITIONS+=(\"${PARTITION}\")\n    done\n\n    MDDEVICE=$(get_next_md_device)\n\n    udevadm control --stop-exec-queue\n    mdadm --create ${MDDEVICE} --level 0 --raid-devices ${#PARTITIONS[@]} ${PARTITIONS[*]}\n    udevadm control --start-exec-queue\n\n    MOUNTPOINT=\"${DATA_PATH}\"\n    echo \"Mount point appears to be ${MOUNTPOINT}\"\n    [ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n\n    #Make a file system on the new device\n    STRIDE=128 #(512kB stripe size) / (4kB block size)\n    PARTITIONSNUM=${#PARTITIONS[@]}\n    STRIPEWIDTH=$((${STRIDE} * ${PARTITIONSNUM}))\n\n    mkfs -t ext4 -b 4096 -E lazy_itable_init=1,stride=${STRIDE},stripe-width=${STRIPEWIDTH} \"${MDDEVICE}\"\n\n    read UUID FS_TYPE < <(blkid -u filesystem ${MDDEVICE}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\n    mount \"${MOUNTPOINT}\"\n}\n\ncheck_mdadm() {\n    dpkg -s mdadm >/dev/null 2>&1\n    if [ ${?} -ne 0 ]; then\n        apt-get -y update\n        DEBIAN_FRONTEND=noninteractive apt-get -y install mdadm --fix-missing\n    fi\n}\n\n# Create Partitions\nDISKS=$(scan_for_new_disks)\n\nif [ \"$RAID_CONFIGURATION\" -eq 1 ]; then\n    check_mdadm\n    create_striped_volume \"${DISKS[@]}\"\nelse\n    scan_partition_format\nfi\n", "num_lines": 324}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -v\nsudo apt-get update\nsudo apt-get install -y docker.io\nsudo docker run -v /:/host -v /var/run/docker.sock:/var/run/docker.sock --privileged --name cloudlens-agent -d --restart=on-failure --net=host ixiacom/cloudlens-agent --accept_eula yes --apikey $1 --custom_tags Name=\"CloudLens Quick Start Tool Instance\"\nsudo docker run -d --name es --net host elasticsearch:5.2.2-alpine\nsudo docker run --name moloch -d --net host ixiacom/cloudlens-moloch\n", "num_lines": 7}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -v\nsudo apt-get update -y\nsudo apt-get -y install tcpreplay\nsudo apt-get install -y docker.io\nsudo docker run -v /:/host -v /var/run/docker.sock:/var/run/docker.sock --privileged --name cloudlens-agent -d --restart=on-failure --net=host ixiacom/cloudlens-agent --accept_eula yes --apikey $1 --custom_tags Name=\"CloudLens Quick Start Source Instance\"\n", "num_lines": 6}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -v\nsudo apt-get update\nsudo apt-get install git -y\nsudo apt-get install python -y\nsudo apt-get install python-setuptools -y\nsudo apt-get install python-openssl -y\nsudo apt-get install docker-compose -y\nsudo apt-get install -y docker.io\ngit clone https://github.com/StamusNetworks/Amsterdam.git\ncd Amsterdam\nsudo python setup.py install\nsudo docker run -v /:/host -v /var/run/docker.sock:/var/run/docker.sock --privileged --name cloudlens-agent -d --restart=on-failure --net=host ixiacom/cloudlens-agent --accept_eula yes --apikey $1 --custom_tags Name=\"CloudLens Quick Start Tool Instance\"\nsudo amsterdam -d ams -i cloudlens0 setup\nscreen -dmS start_suricata sudo amsterdam -d ams start\n", "num_lines": 15}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash -v\nsudo apt-get update -y\nsudo apt-get -y install tcpreplay\nsudo apt-get install -y docker.io\nsudo ip link add name CloudlensReplay type dummy\nsudo ifconfig CloudlensReplay up\nwget --tries=50 https://s3.amazonaws.com/cloudlens-automation/quickstart/malware.pcap\nsudo docker run -v /:/host -v /var/run/docker.sock:/var/run/docker.sock --privileged --name cloudlens-agent -d --restart=on-failure --net=host ixiacom/cloudlens-agent --accept_eula yes --listen CloudlensReplay --apikey $1 --custom_tags Name=\"CloudLens Quick Start Source Instance\"\nscreen -dmS gen_traffic sudo tcpreplay --loop=0 --intf1=CloudlensReplay /var/lib/waagent/custom-script/download/0/malware.pcap\n", "num_lines": 10}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get update\napt-get install -y openvpn\napt-get install -y ruby\n\ncurl https://s3.amazonaws.com/cohesive-networks/dnld/vnscubed-ruby-cli-20200827.tar.gz | tar xvz\nmv  vnscubed-ruby-cli-20200827 api\n\nchmod 700 api/vnscubed.rb\nchmod 700 api/api.rb\n\nsleep 600\n\nwait_for_api () {\n   while :\n     do\n     apistatus=`curl -k -X GET -u api:VNS3Controller-10.10.10.10 https://10.10.10.10:8000/api/config 2>&1`\n        echo $apistatus | grep \"refused\"\n          if [ $? != 0 ] ; then\n            break\n          fi\n         sleep 2\n     done\n }\n\nwait_for_api\n\nNAME=$(api/vnscubed.rb -K api -S VNS3Controller-10.10.10.10 -H 10.10.10.10 get_next_available_clientpack | grep 'name')\n\nIP=${NAME:7:13}\n\napi/vnscubed.rb -K api -S VNS3Controller-10.10.10.10 -H 10.10.10.10 fetch_clientpack --name \"$IP\" --fileformat \"conf\" -o \"clientpack.conf\"\n\nmv clientpack.conf /etc/openvpn\n\nsystemctl start openvpn@clientpack.service\n\ncurl https://cn-dnld.s3.amazonaws.com/cohesive-ra_1.1.1_x86_64.deb --output cohesive_ra_1.1.1_amd64.deb\n\ndpkg -i cohesive_ra_1.1.1_amd64.deb &> /dev/null", "num_lines": 41}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get update\napt-get install -y openvpn\napt-get install -y ruby\n\ncurl https://s3.amazonaws.com/cohesive-networks/dnld/vnscubed-ruby-cli-20200827.tar.gz | tar xvz\nmv  vnscubed-ruby-cli-20200827 api\n\nchmod 700 api/vnscubed.rb\nchmod 700 api/api.rb\n\nsleep 600\n\nwait_for_api () {\n   while :\n     do\n     apistatus=`curl -k -X GET -u api:VNS3Controller-10.10.10.10 https://10.10.10.10:8000/api/config 2>&1`\n        echo $apistatus | grep \"refused\"\n          if [ $? != 0 ] ; then\n            break\n          fi\n         sleep 2\n     done\n }\n\nwait_for_api\n\nNAME=$(api/vnscubed.rb -K api -S VNS3Controller-10.10.10.10 -H 10.10.10.10 get_next_available_clientpack | grep 'name')\n\nIP=${NAME:7:13}\n\napi/vnscubed.rb -K api -S VNS3Controller-10.10.10.10 -H 10.10.10.10 fetch_clientpack --name \"$IP\" --fileformat \"conf\" -o \"clientpack.conf\"\n\nmv clientpack.conf /etc/openvpn\n\nsystemctl start openvpn@clientpack.service\n\ncurl https://cn-dnld.s3.amazonaws.com/cohesive-ra_1.1.1_x86_64.deb --output cohesive_ra_1.1.1_amd64.deb\n\ndpkg -i cohesive_ra_1.1.1_amd64.deb &> /dev/null", "num_lines": 41}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nfunction retryop()\n{\n  retry=0\n  max_retries=10\n  interval=30\n  while [ ${retry} -lt ${max_retries} ]; do\n    echo \"Operation: $1, Retry #${retry}\"\n    eval $1\n    if [ $? -eq 0 ]; then\n      echo \"Successful\"\n      break\n    else\n      let retry=retry+1\n      echo \"Sleep $interval seconds, then retry...\"\n      sleep $interval\n    fi\n  done\n  if [ ${retry} -eq ${max_retries} ]; then\n    echo \"Operation failed: $1\"\n    exit 1\n  fi\n}\n\nfunction escape_password() {\n  password=$1\n  result=\"\"\n  for char in $(echo $password | sed -e 's/\\(.\\)/\\1\\n/g'); do\n    if [ $char == \"'\" ]; then\n      result=\"${result}'\\\\''\"\n    else\n      result=\"${result}${char}\"\n    fi\n  done\n  echo $result\n}\n\necho \"Installing jq\"\nretryop \"apt-get update && apt-get install -y jq\"\n\nfunction get_setting() {\n  key=$1\n  local value=$(echo $settings | jq \".$key\" -r)\n  echo $value\n}\n\ncustom_data_file=\"/var/lib/cloud/instance/user-data.txt\"\nsettings=$(cat ${custom_data_file})\ntenant_id=$1\nclient_id=$2\nclient_secret=$3\nenvironment=$(get_setting ENVIRONMENT)\nusername=$(get_setting ADMIN_USER_NAME)\nhome_dir=\"/home/$username\"\n\n# https://bosh.io/docs/cli-v2-install/#additional-dependencies\necho \"Installing OS specified dependencies for bosh create-env command\"\nretryop \"apt-get update && apt-get install -y build-essential zlibc zlib1g-dev ruby ruby-dev openssl libxslt-dev libxml2-dev libssl-dev libreadline6 libreadline6-dev libyaml-dev libsqlite3-dev sqlite3\"\n\necho \"Installing BOSH CLI\"\nbosh_cli_url=$(get_setting BOSH_CLI_URL)\nwget $bosh_cli_url\nchmod +x ./bosh-cli-*\nmv ./bosh-cli-* /usr/local/bin/bosh\n\nexport DEBIAN_FRONTEND=noninteractive\n\nsudo pt-get update\nsudo apt-get -y install ca-certificates curl apt-transport-https lsb-release gnupg\n\ncurl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.gpg > /dev/null\n\nAZ_REPO=$(lsb_release -cs)\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\nsudo apt-key adv --keyserver packages.microsoft.com --recv-keys 417A0893\n\nsudo apt get update\n\nsudo apt-get -y install azure-cli\n\necho \"Creating the containers (bosh and stemcell) and the table (stemcells) in the default storage account\"\ndefault_storage_account=$(get_setting DEFAULT_STORAGE_ACCOUNT_NAME)\ndefault_storage_access_key=$(get_setting STORAGE_ACCESS_KEY)\nendpoint_suffix=$(get_setting SERVICE_HOST_BASE)\nconnection_string=\"DefaultEndpointsProtocol=https;AccountName=${default_storage_account};AccountKey=${default_storage_access_key};EndpointSuffix=${endpoint_suffix}\"\naz storage container create --name bosh --connection-string ${connection_string}\naz storage container create --name stemcell --public-access blob --connection-string ${connection_string}\naz storage table create --name stemcells --connection-string ${connection_string}\n\necho \"Prepare manifests\"\nmanifests_dir=\"$home_dir/example_manifests\"\nmkdir -p $manifests_dir\ncp *.yml $manifests_dir\n\necho \"Prepare Bosh deployment script\"\ncat > \"deploy_bosh.sh\" << EOF\n#!/usr/bin/env bash\nset -e\n\nexport BOSH_LOG_LEVEL=\"debug\"\nexport BOSH_LOG_PATH=\"./run.log\"\n\nbosh create-env ~/example_manifests/bosh.yml \\\\\n  --state=state.json \\\\\n  --vars-store=~/bosh-deployment-vars.yml \\\\\n  -o ~/example_manifests/cpi.yml \\\\\n  -o ~/example_manifests/custom-cpi-release.yml \\\\\n  -o ~/example_manifests/custom-environment.yml \\\\\n  -o ~/example_manifests/use-azure-dns.yml \\\\\n  -o ~/example_manifests/jumpbox-user.yml \\\\\n  -o ~/example_manifests/use-managed-disks.yml \\\\\n  -o ~/example_manifests/keep-failed-or-unreachable-vms.yml \\\\\nEOF\n\nif [ $environment = \"AzureChinaCloud\" ]; then\n  cat >> \"deploy_bosh.sh\" <<EOF\n  -o ~/example_manifests/use-mirror-releases-for-bosh.yml \\\\\nEOF\nfi\n\ncat >> \"deploy_bosh.sh\" << EOF\n  -v director_name=azure \\\\\n  -v internal_cidr=$(get_setting SUBNET_ADDRESS_RANGE_FOR_BOSH) \\\\\n  -v internal_gw=$(get_setting SUBNET_GATEWAY_FOR_BOSH) \\\\\n  -v internal_ip=$(get_setting INTERNAL_IP_FOR_BOSH) \\\\\n  -v cpi_release_url=$(get_setting BOSH_AZURE_CPI_RELEASE_URL) \\\\\n  -v cpi_release_sha1=$(get_setting BOSH_AZURE_CPI_RELEASE_SHA1) \\\\\n  -v director_vm_instance_type=$(get_setting BOSH_VM_SIZE) \\\\\n  -v resource_group_name=$(get_setting RESOURCE_GROUP_NAME) \\\\\n  -v vnet_name=$(get_setting VNET_NAME) \\\\\n  -v subnet_name=$(get_setting SUBNET_NAME_FOR_BOSH) \\\\\n  -v default_security_group=$(get_setting NSG_NAME_FOR_BOSH) \\\\\n  -v environment=$(get_setting ENVIRONMENT) \\\\\n  -v subscription_id=$(get_setting SUBSCRIPTION_ID) \\\\\n  -v tenant_id=${tenant_id} \\\\\n  -v client_id=${client_id} \\\\\n  -v client_secret=${client_secret}\n\ncat >> $home_dir/.profile << EndOfFile\nexport BOSH_ENVIRONMENT=$(get_setting INTERNAL_IP_FOR_BOSH)\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\nEndOfFile\nEOF\n\nchmod +x deploy_bosh.sh\ncp deploy_bosh.sh $home_dir\n\necho \"Prepare Concourse deployment script\"\nconcourse_worker_disk_size_in_mb=$(($(get_setting CONCOURSE_WORKER_DISK_SIZE)*1024))\ncat > \"deploy_concourse.sh\" <<EOF\n#!/usr/bin/env bash\nset -e\n\nexport BOSH_ENVIRONMENT=$(get_setting INTERNAL_IP_FOR_BOSH)\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\n\nbosh alias-env azure\nbosh -e azure login\n\nbosh -n update-cloud-config ~/example_manifests/cloud-config.yml \\\\\n  -v internal_cidr=$(get_setting SUBNET_ADDRESS_RANGE_FOR_CONCOURSE) \\\\\n  -v internal_gw=$(get_setting SUBNET_GATEWAY_FOR_CONCOURSE) \\\\\n  -v vnet_name=$(get_setting VNET_NAME) \\\\\n  -v subnet_name=$(get_setting SUBNET_NAME_FOR_CONCOURSE) \\\\\n  -v security_group=$(get_setting NSG_NAME_FOR_CONCOURSE) \\\\\n  -v ephemeral_disk_size=${concourse_worker_disk_size_in_mb}\n\nbosh upload-stemcell --sha1=$(get_setting STEMCELL_SHA1) $(get_setting STEMCELL_URL)\nbosh -e azure -n deploy -d concourse ~/example_manifests/concourse.yml \\\\\nEOF\n\nif [ $environment = \"AzureChinaCloud\" ]; then\n  cat >> \"deploy_concourse.sh\" <<EOF\n  -o ~/example_manifests/use-mirror-releases-for-concourse.yml \\\\\nEOF\nfi\n\ncat >> \"deploy_concourse.sh\" <<EOF\n  --vars-store=~/concourse-deployment-vars.yml \\\\\n  -v deployment_name=concourse \\\\\n  -v network_name=concourse \\\\\n  -v web_vm_type=concourse_web_or_db \\\\\n  -v db_vm_type=concourse_web_or_db \\\\\n  -v db_persistent_disk_type=default \\\\\n  -v worker_vm_type=concourse_worker \\\\\n  -v basic_auth_username=$(get_setting CONCOURSE_USERNAME) \\\\\n  -v basic_auth_password='$(escape_password $(get_setting CONCOURSE_PASSWORD))' \\\\\n  -v web_ip=$(get_setting CONCOURSE_PUBLIC_IP) \\\\\n  -v external_url=\"http://$(get_setting CONCOURSE_PUBLIC_IP):8080\"\nEOF\n\nchmod +x deploy_concourse.sh\ncp deploy_concourse.sh $home_dir\n\necho \"Prepare logging in bosh script\"\ncat > \"login_bosh.sh\" <<EOF\n#!/usr/bin/env bash\n\nexport BOSH_ENVIRONMENT=10.0.0.4\nexport BOSH_CLIENT=admin\nexport BOSH_CLIENT_SECRET=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /admin_password)\"\nexport BOSH_CA_CERT=\"\\$(bosh int ~/bosh-deployment-vars.yml --path /director_ssl/ca)\"\n\nbosh alias-env azure\nbosh -e azure login\nEOF\nchmod +x login_bosh.sh\ncp login_bosh.sh $home_dir\n\nchown -R $username $home_dir\n\nauto_deploy_bosh=$(get_setting AUTO_DEPLOY_BOSH)\nif [ \"$auto_deploy_bosh\" != \"enabled\" ]; then\n  echo \"Finish\"\n  exit 0\nfi\n\necho \"Start to run deploy_bosh.sh...\"\nsu -c \"./deploy_bosh.sh\" - $username\necho \"Finish\"\n\nauto_deploy_concourse=$(get_setting AUTO_DEPLOY_CONCOURSE)\nif [ \"$auto_deploy_concourse\" != \"enabled\" ]; then\n  echo \"Finish\"\n  exit 0\nfi\n\necho \"Start to run deploy_concourse.sh...\"\nsu -c \"./deploy_concourse.sh\" - $username\necho \"Finish\"\n\n", "num_lines": 237}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update && sudo apt-get install -y wget unzip\n\nsudo mkdir -p /opt/consul/data\ncd /opt/consul\n#sudo wget https://releases.hashicorp.com/consul/0.6.3/consul_0.6.3_linux_amd64.zip\nsudo wget https://releases.hashicorp.com/consul/0.7.0/consul_0.7.0_linux_amd64.zip\nsudo unzip consul_0.7.0_linux_amd64.zip\nsudo chmod 755 consul\ncd /opt/consul\nsudo nohup ./consul agent -server -bind 0.0.0.0 -client 0.0.0.0 -data-dir=\"/opt/consul/data\" -bootstrap-expect 3 -atlas=$1 -atlas-join -atlas-token=\"$2\" &\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ \"$#\" -ne 2 ]; then\n    echo \"Execute the CoScale agent deploy command on all servers in a resource group.\"\n    echo \"\"\n    echo \"Usage: $0 <resource-group> <command>\"\n    echo \"   - resource-group: The resource group containing the vms on which you want to deploy CoScale.\"\n    echo \"   - command: The command to install the agent, as provided by the CoScale UI.\"\n    echo \"\"\n    exit 1\nfi\n\nexport GROUP=$1\nexport COMMAND=$2\n\necho \"Getting vm list\"\nSERVERS=`az vm list -g $GROUP -o table | tail -n +3 | awk '{ print $2; }'`\n\nfor SERVER in $SERVERS\ndo\n    echo \"Deploying on server $SERVER\"\n    az vm extension set \\\n        --publisher Microsoft.Azure.Extensions -n CustomScript --version 2.0 \\\n        --vm-name $SERVER --resource-group $GROUP \\\n        --protected-setting '{ \"commandToExecute\": \"'\"$COMMAND\"'\" }'\ndone\n", "num_lines": 27}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nKEY=$1\nEMAIL=$2\nPASSWORD=$3\nDNS=$4\n\n## Initialize the data disk\n\nparted -s /dev/sdc mklabel msdos\nparted -s /dev/sdc mkpart primary ext4 0\\% 100\\%\nmkfs.ext4 /dev/sdc1\nmkdir /data/\nmount /dev/sdc1 /data/\necho \"/dev/sdc1    /data/    ext4    defaults 0 0\" >> /etc/fstab\n\n## Install Docker\n\napt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\nbash -c 'echo \"deb https://apt.dockerproject.org/repo ubuntu-xenial main\" > /etc/apt/sources.list.d/docker.list'\napt-get update\napt-get install -y docker-engine\nusermod -aG docker cs\n\n## Install CoScale\n\ncd /home/cs\n\nURL=`curl -s https://api.github.com/repos/fryckbos/cop/releases | grep browser_download_url | head -n 1 | cut -d '\"' -f 4`\nwget $URL\nmkdir -p cop && cd cop && tar xzf ../cop.tgz\n\ncd azure\n./install-dev.sh $KEY $EMAIL $PASSWORD $DNS\n", "num_lines": 35}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"Running server.sh\"\n\nadminUsername=$1\nadminPassword=$2\nuniqueString=$3\nlocation=$4\n\necho \"Using the settings:\"\necho adminUsername \\'$adminUsername\\'\necho adminPassword \\'$adminPassword\\'\necho uniqueString \\'$uniqueString\\'\necho location \\'$location\\'\n\necho \"Installing Couchbase Server...\"\nwget http://packages.couchbase.com/releases/4.6.3/couchbase-server-enterprise_4.6.3-ubuntu14.04_amd64.deb\ndpkg -i couchbase-server-enterprise_4.6.3-ubuntu14.04_amd64.deb\napt-get update\napt-get -y install couchbase-server\n\necho \"Calling util.sh...\"\nsource util.sh\nformatDataDisk\nturnOffTransparentHugepages\nsetSwappinessToZero\nadjustTCPKeepalive\n\necho \"Configuring Couchbase Server...\"\napt-get -y install jq\nnodeIndex=`curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute?api-version=2017-04-02\" \\\n  | jq \".name\" \\\n  | sed 's/.*_//' \\\n  | sed 's/\"//'`\n\nnodeDNS='vm'$nodeIndex'.server-'$uniqueString'.'$location'.cloudapp.azure.com'\nrallyDNS='vm0.server-'$uniqueString'.'$location'.cloudapp.azure.com'\n\necho \"Adding an entry to /etc/hosts to simulate split brain DNS...\"\necho \"\n# Simulate split brain DNS for Couchbase\n127.0.0.1 ${nodeDNS}\n\" >> /etc/hosts\n\ncd /opt/couchbase/bin/\n\necho \"Running couchbase-cli node-init\"\n./couchbase-cli node-init \\\n  --cluster=$nodeDNS \\\n  --node-init-hostname=$nodeDNS \\\n  --node-init-data-path=/datadisk/data \\\n  --node-init-index-path=/datadisk/index \\\n  --user=$adminUsername \\\n  --pass=$adminPassword\n\nif [[ $nodeIndex == \"0\" ]]\nthen\n  totalRAM=$(grep MemTotal /proc/meminfo | awk '{print $2}')\n  dataRAM=$((50 * $totalRAM / 100000))\n  indexRAM=$((15 * $totalRAM / 100000))\n\n  echo \"Running couchbase-cli cluster-init\"\n  ./couchbase-cli cluster-init \\\n    --cluster=$nodeDNS \\\n    --cluster-ramsize=$dataRAM \\\n    --cluster-index-ramsize=$indexRAM \\\n    --cluster-username=$adminUsername \\\n    --cluster-password=$adminPassword \\\n    --services=data,index,query,fts\n\n  echo \"Running couchbase-cli bucket-create\"\n  ./couchbase-cli bucket-create \\\n    --cluster=$nodeDNS \\\n    --user=$adminUsername \\\n    --pass=$adminPassword \\\n    --bucket=sync_gateway \\\n    --bucket-type=couchbase \\\n    --bucket-ramsize=100\nelse\n  echo \"Running couchbase-cli server-add\"\n  output=\"\"\n  while [[ $output != \"Server $nodeDNS:8091 added\" && ! $output =~ \"Node is already part of cluster.\" ]]\n  do\n    output=`./couchbase-cli server-add \\\n      --cluster=$rallyDNS \\\n      --user=$adminUsername \\\n      --pass=$adminPassword \\\n      --server-add=$nodeDNS \\\n      --server-add-username=$adminUsername \\\n      --server-add-password=$adminPassword \\\n      --services=data,index,query,fts`\n    echo server-add output \\'$output\\'\n    sleep 10\n  done\n\n  echo \"Running couchbase-cli rebalance\"\n  output=\"\"\n  while [[ ! $output =~ \"SUCCESS\" ]]\n  do\n    output=`./couchbase-cli rebalance \\\n      --cluster=$rallyDNS \\\n      --user=$adminUsername \\\n      --pass=$adminPassword`\n    echo rebalance output \\'$output\\'\n    sleep 10\n  done\n\nfi\n", "num_lines": 109}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\necho \"Running syncGateway.sh\"\n\nuniqueString=$1\nlocation=$2\n\necho \"Using the settings:\"\necho uniqueString \\'$uniqueString\\'\necho location \\'$location\\'\n\necho \"Installing Couchbase Sync Gateway...\"\nwget https://packages.couchbase.com/releases/couchbase-sync-gateway/1.4.1/couchbase-sync-gateway-enterprise_1.4.1-3_x86_64.deb\ndpkg -i couchbase-sync-gateway-enterprise_1.4.1-3_x86_64.deb\n\necho \"Calling util.sh...\"\nsource util.sh\nadjustTCPKeepalive\n\necho \"Configuring Couchbase Sync Gateway...\"\nrallyDNS='vm0.server-'$uniqueString'.'$location'.cloudapp.azure.com'\nfile=\"/home/sync_gateway/sync_gateway.json\"\necho '\n{\n  \"interface\": \"0.0.0.0:4984\",\n  \"adminInterface\": \"0.0.0.0:4985\",\n  \"log\": [\"*\"],\n  \"databases\": {\n    \"database\": {\n      \"server\": \"http://'${rallyDNS}':8091\",\n      \"bucket\": \"sync_gateway\",\n      \"users\": {\n        \"GUEST\": { \"disabled\": false, \"admin_channels\": [\"*\"] }\n      }\n    }\n  }\n}\n' > ${file}\nchmod 755 ${file}\nchown sync_gateway ${file}\nchgrp sync_gateway ${file}\n\n# Need to restart to load the changes\nservice sync_gateway stop\nservice sync_gateway start\n", "num_lines": 46}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nadjustTCPKeepalive ()\n{\n# Azure public IPs have some odd keep alive behaviour\n# A summary is available here https://docs.mongodb.org/ecosystem/platforms/windows-azure/\n\necho \"Setting TCP keepalive...\"\nsysctl -w net.ipv4.tcp_keepalive_time=120\n\necho \"Setting TCP keepalive permanently...\"\necho \"net.ipv4.tcp_keepalive_time = 120\" >> /etc/sysctl.conf\necho \"\" >> /etc/sysctl.conf\n}\n\nformatDataDisk ()\n{\n# This script formats and mounts the drive on lun0 as /datadisk\n\nDISK=\"/dev/disk/azure/scsi1/lun0\"\nPARTITION=\"/dev/disk/azure/scsi1/lun0-part1\"\nMOUNTPOINT=\"/datadisk\"\n\necho \"Partitioning the disk.\"\necho \"n\np\n1\n\n\nt\n83\nw\"| fdisk ${DISK}\n\necho \"Waiting for the symbolic link to be created...\"\nudevadm settle --exit-if-exists=$PARTITION\n\necho \"Creating the filesystem.\"\nmkfs -j -t ext4 ${PARTITION}\n\necho \"Updating fstab\"\nLINE=\"${PARTITION}\\t${MOUNTPOINT}\\text4\\tnoatime,nodiratime,nodev,noexec,nosuid\\t1\\t2\"\necho -e ${LINE} >> /etc/fstab\n\necho \"Mounting the disk\"\nmkdir -p $MOUNTPOINT\nmount -a\n\necho \"Changing permissions\"\nchown couchbase $MOUNTPOINT\nchgrp couchbase $MOUNTPOINT\n}\n\nturnOffTransparentHugepages ()\n{\n# Please look at http://bit.ly/1ZAcLjD as for how to PERMANENTLY alter this setting.\n\necho \"#!/bin/bash\n### BEGIN INIT INFO\n# Provides:          disable-thp\n# Required-Start:    $local_fs\n# Required-Stop:\n# X-Start-Before:    couchbase-server\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# Short-Description: Disable THP\n# Description:       disables Transparent Huge Pages (THP) on boot\n### END INIT INFO\n\necho 'never' > /sys/kernel/mm/transparent_hugepage/enabled\necho 'never' > /sys/kernel/mm/transparent_hugepage/defrag\n\" > /etc/init.d/disable-thp\nchmod 755 /etc/init.d/disable-thp\nservice disable-thp start\nupdate-rc.d disable-thp defaults\n}\n\nsetSwappinessToZero ()\n{\n# Please look at http://bit.ly/1k2CtNn as for how to PERMANENTLY alter this setting.\n\nsysctl vm.swappiness=0\necho \"\n# Required for Couchbase\nvm.swappiness = 0\" >> /etc/sysctl.conf\n}\n", "num_lines": 86}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncloud_type=\"azure\"\nlocation=$1 #this is the location of the seed, not necessarily of this node\nunique_string=$2\ndata_center_name=$3\n\nseed_node_dns_name=\"dc0vm0$unique_string.$location.cloudapp.azure.com\"\n\necho \"Configuring nodes with the settings:\"\necho cloud_type $cloud_type\necho location $location\necho unique_string $unique_string\necho data_center_name $data_center_name\necho seed_node_dns_name $seed_node_dns_name\n\nwget https://github.com/DSPN/install-datastax/archive/1.0.zip\napt-get -y install unzip\nunzip 1.0.zip\ncd install-datastax-1.0/bin\n\n./dse.sh $cloud_type $seed_node_dns_name $data_center_name\n", "num_lines": 23}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\ncloud_type=\"azure\"\nlocation=$1 #this is the location of the seed, not necessarily of this node\nunique_string=$2\n\nseed_node_dns_name=\"dc0vm0$unique_string.$location.cloudapp.azure.com\"\n\necho \"Configuring nodes with the settings:\"\necho cloud_type $cloud_type\necho location $location\necho unique_string $unique_string\necho seed_node_dns_name $seed_node_dns_name\n\nwget https://github.com/DSPN/install-datastax/archive/1.0.zip\napt-get -y install unzip\nunzip 1.0.zip\ncd install-datastax-1.0/bin\n\n./opscenter.sh $cloud_type $seed_node_dns_name\n\n", "num_lines": 22}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nexport DEBIAN_FRONTEND=noninteractive\napt-get -y update\n\n# install Python\napt-get -y install python3-pip\n\n# install DJango\npython3 -m pip install django\n\n# install Apache\napt-get -y install apache2 libapache2-mod-wsgi-py3\n\n# create a django app\ncd /var/www\ndjango-admin startproject helloworld\n\n# Create a new file named views.py in the /var/www/helloworld/helloworld directory. This will contain the view\n# that renders the \"hello world\" page\n#echo \"from django.http import HttpResponse\n#def index(request):\n#    return HttpResponse('Hello, world.')\" | tee /var/www/helloworld/helloworld/views.py\n\n# Update urls.py\n#echo \"from django.conf.urls import url\n#from . import views\n\n#urlpatterns = [\n#    url('', views.index, name='index'),\n#]\" | tee /var/www/helloworld/helloworld/urls.py\n\nsed -i \"s|ALLOWED_HOSTS = \\[\\]|ALLOWED_HOSTS = \\['*'\\]|\" /var/www/helloworld/helloworld/settings.py\n\n# Setup Apache\necho \"<VirtualHost *:80>\nServerName $1\n</VirtualHost>\nWSGIScriptAlias / /var/www/helloworld/helloworld/wsgi.py\nWSGIPythonPath /var/www/helloworld\" | tee /etc/apache2/sites-available/helloworld.conf\n\n#enable site\na2ensite helloworld\n\n#restart apache\nservice apache2 reload\n", "num_lines": 46}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nexport DEBIAN_FRONTEND=noninteractive\napt-get update && sudo apt-get upgrade -y\n\n# Install pip\napt-get -y install python3-pip\n\n# Install Django\npip3 install Django\n\n# Install database packages\napt-get install -y freetds-dev freetds-bin\npip3 install pymssql\n\n# Install Apache\napt-get install -y apache2 libapache2-mod-wsgi-py3\n\n# create a django app\ncd /var/www\ndjango-admin startproject helloworld\n\n# Create a new file named views.py in the /var/www/helloworld/helloworld directory. This will contain the view\n# that renders the \"hello world\" page\necho \"from django.http import HttpResponse\nfrom django.shortcuts import render\nfrom django.http import HttpRequest\nfrom django.template import RequestContext\nfrom datetime import datetime\nimport pymssql\n\n\ndef contact(request):\n    html = '<html><body>Contact</body><html>'\n    return HttpResponse(html)\n\n\ndef about(request):\n    html = '<html><body>About</body><html>'\n    return HttpResponse(html)\n\n\ndef home(request):\n    conn = pymssql.connect(server='$2.database.windows.net',user='$3@$2', password='$4', database='$5')\n    cursor = conn.cursor()\n    cursor.execute(\\\"IF OBJECT_ID('votes', 'U') IS NOT NULL DROP TABLE votes\\\")\n    cursor.execute(\\\"CREATE TABLE votes ( name VARCHAR(100), value INT NOT NULL, PRIMARY KEY(name))\\\")\n    cursor.executemany(\n        \\\"INSERT INTO votes VALUES (%s, %d)\\\",\n        [('NodeJS', '2'),\n         ('Python', '33'),\n         ('C#', '2')])\n    # you must call commit() to persist your data if you don't set autocommit to True\n    conn.commit()\n    cursor.execute('SELECT * FROM votes')\n\n    result = '<table style=\\\"width:100%\\\">'\n    row = cursor.fetchone()\n    while row:\n        result += f'<tr><th>{row[0]}: {row[1]} votes</th></tr>'\n        row = cursor.fetchone()\n    result += '</table>'\n    html = f'<html><body>{result}</body><html>'\n    return HttpResponse(html)\" | tee /var/www/helloworld/helloworld/views.py\n\n# Update urls.py\necho \"from django.urls import path\nfrom helloworld import views\nurlpatterns = [\n    path('contact/', views.contact, name='contact'),\n    path('about/', views.about, name='about'),\n    path('', views.home, name='home'),\n]\" | tee /var/www/helloworld/helloworld/urls.py\n\nsed -i \"s|ALLOWED_HOSTS = \\[\\]|ALLOWED_HOSTS = \\['*'\\]|\" /var/www/helloworld/helloworld/settings.py\n\n# Apache Config\necho \"<VirtualHost *:80>\nServerName $1\n</VirtualHost>\nWSGIScriptAlias / /var/www/helloworld/helloworld/wsgi.py\nWSGIPythonPath /var/www/helloworld\" | tee /etc/apache2/sites-available/helloworld.conf\n\n# Enable Site\na2ensite helloworld\n\n# Restart Apache\nservice apache2 reload\n", "num_lines": 88}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo apt-get install -y --no-install-recommends \\\n        apt-utils \\\n        software-properties-common \\\n        git \\\n        curl \\\n        python-pip \\\n        wget \\\n        cpio \\\n        mkisofs \\\n        apt-transport-https \\\n        openssh-client \\\n        ca-certificates \\\n        sshpass\n\n# Install docker\nwhich docker\nif [ $? -eq 0 ]\nthen\ndocker --version\n## docker already installed\nelse\ncurl -q https://get.docker.com/ | sudo bash\nfi\n\nusername=$1\nshift\n\nsudo usermod -aG docker $username\n\nsudo apt-get install -y --no-install-recommends python-yaml python-jinja2 python-setuptools python-tzlocal python-pycurl\n\ngit clone http://github.com/Microsoft/DLWorkspace /home/$username/dlworkspace\ncd /home/$username/dlworkspace\ngit fetch --all\ngit checkout ARMTemplate\n\n# Create configuration files, config.yaml, and cluster.yaml\ncd /home/$username/dlworkspace/src/ClusterBootstrap\n../ARM/createconfig.py genconfig --outfile /home/$username/dlworkspace/src/ClusterBootstrap/config.yaml --admin_username $username \"$@\"\n./az_tools.py --default_admin_username $username --noaz genconfig\n\n# Generate SSH keys\n./deploy.py -y build\n\n# Copy ssh keys\n../ARM/createconfig.py sshkey --admin_username $username \"$@\"\n\n# change owner to $username\nchown -R $username /home/$username/dlworkspace\n\n# run deploy script in docker group, using user $username\nsudo -H -u $username sg docker -c \"bash /home/$username/dlworkspace/src/ARM/deploycluster.sh $username\"\n\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "admin_username=$1\n\n# Go to the home dir of the admin user\ncd /home/${admin_username}\n\n# Download and install DNVM\necho \"Downloading DNVM installation script ...\"\ncurl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | DNX_BRANCH=dev sh && source ~/.dnx/dnvm/dnvm.sh\ndnvm upgrade -r coreclr\n\n# Set up sample hello world application\nmkdir /home/${admin_username}/sampleConsoleApp\ncat > /home/${admin_username}/sampleConsoleApp/main.cs <<EOL\nnamespace DnxApp\n{\n    using System;\n\n    public class Program\n    {\n        public static void Main(string[] args)\n        {\n            Console.WriteLine(\"Hello world from DNX !\");\n        }\n    }\n}\nEOL\n\ncat > /home/${admin_username}/sampleConsoleApp/project.json <<EOL\n{\n  \"version\": \"1.0.0-*\",\n  \"description\": \"DNX Console application\",\n  \"compilationOptions\": {\n    \"emitEntryPoint\": true\n  },\n  \"dependencies\": {\n  },\n  \"commands\": {\n    \"ConsoleApp1\": \"ConsoleApp1\"\n  },\n  \"frameworks\": {\n    \"dnx451\": { },\n    \"dnxcore50\": {\n      \"dependencies\": {\n        \"Microsoft.CSharp\": \"4.0.1-beta-23516\",\n        \"System.Collections\": \"4.0.11-beta-23516\",\n        \"System.Console\": \"4.0.0-beta-23516\",\n      }\n    }\n  }\n}\nEOL\n\n# Restore .NET dependencies and build the application\ncd /home/${admin_username}/sampleConsoleApp\ndnu restore\ndnu build --framework dnxcore50\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nexport DEBIAN_FRONTEND=noninteractive\n\n# This will install ASPNET-Core on an Ubuntu machine\nadmin_username=$1\n\n# Get package dependencies\napt-get -y update\napt-get install -y unzip curl\n\n# Download the DNX pre-reqs\napt-get install -y libunwind8 gettext libssl-dev libcurl4-openssl-dev zlib1g libicu-dev uuid-dev\n\n\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/dnx-on-ubuntu/scripts/install-dnx.sh -P /home/${admin_username}\nsudo -u ${admin_username} /bin/bash /home/${admin_username}/install-dnx.sh ${admin_username}\n\n# Nano syntax highlighting for C#\ncat > /usr/share/nano/csharp.nanorc <<EOL\nsyntax \"C# source\" \"\\.cs$\"\ncolor green \"\\<(bool|byte|sbyte|char|decimal|double|float|int|uint|long|ulong|new|object|short|ushort|string|base|this|void)\\>\"\ncolor red \"\\<(as|break|case|catch|checked|continue|default|do|else|finally|fixed|for|foreach|goto|if|is|lock|return|switch|throw|try|unchecked|while)\\>\"\ncolor cyan \"\\<(abstract|class|const|delegate|enum|event|explicit|extern|implicit|in|internal|interface|namespace|operator|out|override|params|private|protected|public|readonly|ref|sealed|sizeof|static|struct|typeof|using|virtual|volatile)\\>\"\ncolor red \"\"[^\\\"]*\"\"\ncolor yellow \"\\<(true|false|null)\\>\"\ncolor blue \"//.*\"\ncolor blue start=\"/\\*\" end=\"\\*/\"\ncolor brightblue start=\"/\\*\\*\" end=\"\\*/\"\ncolor brightgreen,green \" +$\"\nEOL\n\nsudo echo \"include \\\"/usr/share/nano/csharp.nanorc\\\"\" > /etc/nanorc\n", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# installs dokku via apt-get\nDOKKU_VERSION=$1\nwget https://raw.githubusercontent.com/dokku/dokku/v${DOKKU_VERSION}/bootstrap.sh\nsudo DOKKU_TAG=v${DOKKU_VERSION} bash bootstrap.sh\n", "num_lines": 5}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# set local variables\nGITHUB_CLIENT=$1\nGITHUB_SECRET=$2\n\nexport DEBIAN_FRONTEND=noninteractive\n\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n\n# retrieve latest package updates\napt-get update\nadd-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\napt-get install -y docker-ce\n\n# install dependencies\napt-get install -y linux-image-extra-$(uname -r) libsqlite3-dev\n\n# configure Docker for AUFS\nsed -i 's/^#DOCKER_OPTS.*/DOCKER_OPTS=\"-s aufs\"/' /etc/default/docker\n\n# retrieve and install Drone package\nwget downloads.drone.io/master/drone.deb\ndpkg --install drone.deb\nrm -f drone.deb\n\n# modify drone.toml\necho -e \"\\n\\n[github]\" >> /etc/drone/drone.toml\necho \"client=\\\"$GITHUB_CLIENT\\\"\" >> /etc/drone/drone.toml\necho \"secret=\\\"$GITHUB_SECRET\\\"\" >> /etc/drone/drone.toml\necho \"open=false\" >> /etc/drone/drone.toml\necho \"\\n\\n[worker]\" >> /etc/drone/drone.toml\necho \"nodes=[\" >> /etc/drone/drone.toml\necho \"  \\\"unix:///var/run/docker.sock\\\",\" >> /etc/drone/drone.toml\necho \"  \\\"unix:///var/run/docker.sock\\\"\" >> /etc/drone/drone.toml\necho \"]\" >> /etc/drone/drone.toml\n\n# restart\nreboot\n", "num_lines": 40}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n\n# Variables - Initialize default values\nDRUPAL_VERSION=\"8.1.1\"\nDRUPAL_ADMIN_USER=\"admin\"\nDRUPAL_ADMIN_PASSWORD=\"\"\nIS_FIRST_MEMBER=false\n\nGLUSTER_FIRST_NODE_NAME=\"\"\nGLUSTER_VOLUME_NAME=\"\"\n\nMYSQL_FQDN=\"\"\nEXISTING_MYSQL_FQDN=\"\"\nNEW_MYSQL_FQDN=\"\"\n\nMYSQL_USER=\"admin\"\nEXISTING_MYSQL_USER=\"admin\"\nNEW_MYSQL_USER=\"admin\"\n\nMYSQL_PASSWORD=\"\"\nMYSQL_NEW_DB_NAME=\"drupaldb\"\n\nCREATE_NEW_MYSQL_SERVER=\"no\"\n\nhelp()\n{\n\techo \"This script installs Drupal on the Ubuntu virtual machine image\"\n\techo \"Options:\"\n\techo \"\t\t-d drupal version\"\n\techo \"\t\t-u drupal admin username \"\n\techo \"\t\t-p drupal admin password\"\n  echo \"\t\t-g gluster first node name\"\n  echo \"\t\t-v gluster file system volume name\"\n\techo \"\t\t-s Existing mysql server fqdn\"\n\techo \"\t\t-n mysql root user name\"\n\techo \"\t\t-P mysql root user password\"\n  echo \"\t\t-k new drupal database name\"\n  echo \"\t\t-z if Yes connect to newly created mysql server, else connect to existing mysql server\"\n  echo \"\t\t-S FQDN of the newly created MySQL Server\"\n}\n\nlog()\n{\n\techo \"$1\"\n}\n\nlog \"Begin execution of Drupal installation script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts :d:u:p:g:v:s:n:P:k:z:S:h optname; do\n\n\t# Log input parameters (except the admin password) to facilitate troubleshooting\n\tif [ ! \"$optname\" == \"p\" ] && [ ! \"$optname\" == \"P\" ]; then\n\t\tlog \"Option $optname set with value ${OPTARG}\"\n\tfi\n\n\tcase $optname in\n\td) # drupal version\n\t\tDRUPAL_VERSION=${OPTARG}\n\t\t;;\n\tu) # drupal admin username\n\t\tDRUPAL_ADMIN_USER=${OPTARG}\n\t\t;;\n\tp) # drupal admin password\n\t\tDRUPAL_ADMIN_PASSWORD=${OPTARG}\n\t\t;;\n  g) # gluster first node name\n\t\tGLUSTER_FIRST_NODE_NAME=${OPTARG}\n\t\t;;\n  v) # gluster file system volume name\n\t\tGLUSTER_VOLUME_NAME=${OPTARG}\n\t\t;;\n\ts) # mysql server fqdn\n\t\tEXISTING_MYSQL_FQDN=${OPTARG}\n\t\t;;\n\tn) # mysql root user name\n\t\tEXISTING_MYSQL_USER=${OPTARG}\n\t\t;;\n\tP) # mysql root user password\n\t\tMYSQL_PASSWORD=${OPTARG}\n\t\t;;\n\tk) # new drupal database name\n\t\tMYSQL_NEW_DB_NAME=${OPTARG}\n\t\t;;\n\tz) # \"yes\" or \"no\" value indicating whether new mysql server is to be used (\"yes\") or existing  mysql server is to be used (\"no\")\n\t\tCREATE_NEW_MYSQL_SERVER=${OPTARG}\n\t\t;;\n\tS) # FQDN of the newly created mysql server\n\t\tNEW_MYSQL_FQDN=${OPTARG}\n\t\t;;\n\th) # new drupal database name\n\t\t;;\n\n\t\\?) # Unrecognized option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\n\n#TODO: everything after this needs to be fixed\necho \"installing drupal $HOSTNAME\" >> /mnt/azurefiles-drupal/$HOSTNAME.txt\nexit\n\n# Validate parameters - GLUSTER params have been removed\nif [ \"$GLUSTER_FIRST_NODE_NAME\" == \"\" ] || [ \"$GLUSTER_VOLUME_NAME\" == \"\" ] || [ \"$MYSQL_PASSWORD\" == \"\" ];\nthen\n    log \"Script executed without required parameters\"\n    echo \"You must provide all required parameters.\" >&2\n    exit 3\nfi\n\n\n# set mysql server FQDN to be used (existing or new), and the mysql username to used (existing or \"admin\")\nif [ \"$CREATE_NEW_MYSQL_SERVER\" == \"no\" ]; then\n  MYSQL_FQDN=$EXISTING_MYSQL_FQDN\n  MYSQL_USER=$EXISTING_MYSQL_USER\nelse\n  MYSQL_FQDN=$NEW_MYSQL_FQDN\n  MYSQL_USER=\"admin\"\nfi\n\ninstall_required_packages()\n{\n  # Install required packages\n  echo \"installing required packages\"\n  add-apt-repository ppa:gluster/glusterfs-3.7 -y\n  until apt-get -y update && apt-get -y install apache2 php5 php5-gd php5-mysql glusterfs-client mysql-client git\n  do\n  echo \"installing required packages.....\"\n  sleep 2\n  done\n\n\n  # Install Drush\n  php -r \"readfile('http://files.drush.org/drush.phar');\" > drush\n  chmod +x drush\n  mv drush /usr/local/bin\n\n  # Install Composer\n  curl -sS https://getcomposer.org/installer | php\n  mv composer.phar /usr/local/bin/composer\n}\n\nconfigure_prequisites()\n{\n echo \"configuring prerquisites\"\n\n # uncomments lines below to display errors\n   #  sed -i 's/display_errors = Off/display_errors = On/' /etc/php5/apache2/php.ini\n   #  sed -i 's/display_errors = Off/display_errors = On/' /etc/php5/cli/php.ini\n\n # Set overrides on in apache2.conf\n sed -i 's/AllowOverride None/AllowOverride All/' /etc/apache2/apache2.conf\n\n # override  web root\n sed -i 's/DocumentRoot \\/var\\/www\\/html/DocumentRoot \\/var\\/www\\/html\\/drupal/g' /etc/apache2/sites-enabled/000-default.conf\n\n a2enmod rewrite ssl\n service apache2 restart\n\n # create gluster mount point\n mkdir -p /data\n\n # mount gluster files system\n mount -t glusterfs $GLUSTER_FIRST_NODE_NAME:/$GLUSTER_VOLUME_NAME /data\n\n # Check if this is the first drupal node based on existance of files directory and lockfile, and set IS_FIRST_MEMBER\n # The first member node will be the only one which will install the drupal site using drush site-install.\n # Other member nodes will wait for the drupal site to install\nif [ ! -d /data/files ] && [ ! -f /data/flock.lock ]; then\n  touch /data/flock.lock\n  echo \"first drupal node :\" >> /data/flock.lock\n  echo $(hostname) >> /data/flock.lock\n  IS_FIRST_MEMBER=true\n  echo \"lock created: Now acting as first drupal node\"\nfi\n\n # if first drupal node then create /data/files directory on glusterfs\n if [ \"$IS_FIRST_MEMBER\" = true ]; then\n      mkdir -p /data/files\n\t  echo \"creating files folder on shared mount..\"\n fi\n\n\n}\n\ninstall_drupal()\n{\n echo \"installing drupal\"\n\n # create drupal project will given drupal version\n composer create-project drupal/drupal drupal8-site $DRUPAL_VERSION --keep-vcs\n cd drupal8-site/\n composer install\n cd ..\n\n # Move the drupal directory under html folder\n mv drupal8-site /var/www/html/drupal\n\n # Navigate to the drupal default directory\n cd /var/www/html/drupal/sites/default\n\n # Create Sym Link to the files folder\n ln -s /data/files files\n\n if [ \"$IS_FIRST_MEMBER\" = true ]; then\n     cp default.settings.php /data/settings.php\n     cp default.services.yml /data/services.yml\n\t echo \"copied settings.php and services.yml to shared mount...\"\n\t echo \"copied settings.php and services.yml to shared mount...\" >> /data/flock.lock\n else\n     while [ ! -d /data/files/js ] ;\n     do\n      sleep 30\n\t  echo \"Sleeping, waiting for node 1 to create drupal site\"\n     done\n\t echo \"Directory created, exiting sleep loop..\"\n fi\n\n ln -s /data/settings.php ./settings.php\n ln -s /data/services.yml ./services.yml\n echo \"Created Sym links...\"\n\n if [ \"$IS_FIRST_MEMBER\" = true ];  then\n   chmod -R 777 /var/www/html/drupal/sites/default/files/\n   chmod -R 755 /var/www/html/drupal/sites/default/\n   chmod 777 /var/www/html/drupal/sites/default/settings.php\n   chmod 777 /var/www/html/drupal/sites/default/services.yml\n   echo \"modified permisssions on files for installation...\"\nfi\n\n\n}\n\ninstall_drupal_site()\n{\n echo \"creating drupal site\"\n cd /var/www/html/drupal/\n\n echo \"before execution of drush site-install command\" >> /data/flock.lock\n\ndrush site-install --site-name=\"drupal-site\" --db-url=mysql://$MYSQL_USER:$MYSQL_PASSWORD@$MYSQL_FQDN/$MYSQL_NEW_DB_NAME --account-name=$DRUPAL_ADMIN_USER --account-pass=$DRUPAL_ADMIN_PASSWORD -y\n\nwget localhost\n\nchmod -R 777 /var/www/html/drupal/sites/default/files/\n echo \"drupal site created....\"\n echo \"drupal site created....\"  >> /data/flock.lock\n}\n\nsecure_files()\n{\n chmod 444 /var/www/html/drupal/sites/default/settings.php\n chmod 444 /var/www/html/drupal/sites/default/services.yml\n\n # Set lock file to readonly.\n chmod 444 /data/flock.loc\n\n echo \"Files secured\"\n}\n\nrestart_webserver()\n{\nservice apache2 restart\necho \"Web server restarted....\"\n}\n\n\n\n# Step 1\ninstall_required_packages\n\n# Step 2\nconfigure_prequisites\n\n# Step 3\ninstall_drupal\n\n# Step 4\n# if [ \"$IS_FIRST_MEMBER\" = true ] || [ ! -f /data/startDrupalCreation ];  then\n\nif [ \"$IS_FIRST_MEMBER\" = true ];  then\n  echo \"Invoking Drupal Site Installation routine....\"\n  install_drupal_site\n\nfi\n\n# Step 5\nif [ \"$IS_FIRST_MEMBER\" = true ];  then\n\tsecure_files\nfi\n\n# Step 6\nrestart_webserver\n", "num_lines": 328}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# $1 = Azure storage account name\n# $2 = Azure storage account key\n# $3 = Azure file share name\n# $4 = mountpoint path\n# $5 - username\n# $6 - storageAccount suffix\n\n# For more details refer to https://azure.microsoft.com/en-us/documentation/articles/storage-how-to-use-files-linux/\n\n# update package lists\napt-get -y update\n\n# install cifs-utils and mount file share\napt-get install cifs-utils\nmkdir $4\nmount -t cifs //$1.file.$6/$3 $4 -o vers=3.0,username=$1,password=$2,dir_mode=0755,file_mode=0664\n\n# create a symlink from /mountpath/xxx to ~username/xxx\nlinkpoint=`echo $4 | sed 's/.*\\///'`\neval ln -s $4 ~$5/$linkpoint\n\n# create marker files for testing\necho \"hello from $HOSTNAME\" > $4/$HOSTNAME.txt\n", "num_lines": 25}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Trent Swanson (Full Scale 180 Inc)\n#\nhelp()\n{\n    echo \"This script installs Elasticsearch cluster on CentOS\"\n    echo \"Parameters:\"\n    echo \"-n elasticsearch cluster name\"\n    echo \"-d static discovery endpoints 10.0.0.1-3\"\n    echo \"-v elasticsearch version\"\n    echo \"-a storage account (for AFS)\"\n    echo \"-k access key (for AFS)\"\n    echo \"-c create and mount AFS share\"\n    echo \"-m install marvel yes/no\"\n    echo \"-e export marvel data to a different ip\"\n    echo \"-w configure as a dedicated marvel node\"\n    echo \"-x configure as a dedicated master node\"\n    echo \"-y configure as client only node (no master, no data)\"\n    echo \"-z configure as data node (no master)\"\n    echo \"-s used striped data disk volumes\"\n    echo \"-j install jmeter server agent\"\n    echo \"-p install the cloud-azure plugin\"\n    echo \"-o storage account (for cloud-azure)\"\n    echo \"-r storage key (for cloud-azure)\"\n    echo \"-h view this help content\"\n}\n\n# Log method to control/redirect log output\nlog()\n{\n    # If you want to enable this logging add a un-comment the line below and add your account id\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nlog \"Begin execution of Elasticsearch script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\n#grep -q \"${HOSTNAME}\" /etc/hosts\n#if [ $? == 0 ]\n#then\n#  echo \"${HOSTNAME}found in /etc/hosts\"\n#else\n#  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hosts file if not there\n#  echo \"127.0.0.1 ${HOSTNAME}\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\n#fi\n\n#Script Parameters\nCLUSTER_NAME=\"elasticsearch\"\nES_VERSION=\"2.0.0\"\nMARVEL_ONLY_NODE=0\nDISCOVERY_ENDPOINTS=\"\"\nINSTALL_MARVEL=0\nCLIENT_ONLY_NODE=0\nDATA_NODE=0\nMASTER_ONLY_NODE=0\nUSE_AFS=0\nSTORAGE_ACCOUNT=\"\"\nACCESS_KEY=\"\"\nINSTALL_CLOUD_AZURE=0\nCLOUD_AZURE_ACCOUNT=\"\"\nCLOUD_AZURE_KEY=\"\"\n\n#Loop through options passed\nwhile getopts :n:d:v:a:k:cme:o:r:pwxyzsjh optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    n) #set cluster name\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    d) #static discovery endpoints\n      DISCOVERY_ENDPOINTS=${OPTARG}\n      ;;\n    v) #elasticsearch version number\n      ES_VERSION=${OPTARG}\n      ;;\n    m) #install marvel\n      INSTALL_MARVEL=1\n      ;;\n    e) #export marvel data\n      MARVEL_ENDPOINTS=${OPTARG}\n      ;;\n    w) #marvel node\n      MARVEL_ONLY_NODE=1\n      ;;\n    x) #master node\n      MASTER_ONLY_NODE=1\n      ;;\n    y) #client node\n      CLIENT_ONLY_NODE=1\n      ;;\n    z) #data node\n      DATA_NODE=1\n      ;;\n    s) #use OS striped disk volumes\n      OS_STRIPED_DISK=1\n      ;;\n    a) #set the storage account for AFS\n      STORAGE_ACCOUNT=${OPTARG}\n      ;;\n    k) #set the access key for AFS\n      ACCESS_KEY=${OPTARG}\n      ;;\n    c) #use AFS for the data storage\n      USE_AFS=1\n      ;;\n    d) #place data on local resource disk\n      NON_DURABLE=1\n      ;;\n    j) #install jmeter server agent\n      JMETER_AGENT=1\n      ;;\n    p) #install cloud-azure plugin\n      INSTALL_CLOUD_AZURE=1\n      ;;\n    o) #set cloud-azure account\n      CLOUD_AZURE_ACCOUNT=${OPTARG}\n      ;;\n    r) #set the cloud-azure account key\n      CLOUD_AZURE_KEY=${OPTARG}\n      ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Base path for data disk mount points\n# The script assume format /datadisks/disk1 /datadisks/disk2\nDATA_BASE=\"/datadisks\"\n\n# Max retry count\nMAX_RETRY=5\n\n# Expand a list of successive ip range and filter my local local ip from the list\n# Ip list is represented as a prefix and that is appended with a zero to N index\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    #Get the IP Addresses on this machine\n    declare -a MY_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}\"\n        if ! [[ \"${MY_IPS[@]}\" =~ \"${HOST}\" ]]; then\n            EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n        fi\n    done\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\n# Configure Elasticsearch Data Disk Folder and Permissions\nsetup_data_disk()\n{\n    log \"Configuring disk $1\"\n\n    mkdir -p \"$1\"\n    chown -R elasticsearch:elasticsearch \"$1\"\n    chmod 755 \"$1\"\n}\n\n# Install Oracle Java\ninstall_java()\n{\n    log \"Installing Java\"\n    RETRY=0\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        log \"Retry $RETRY: downloading jdk-8u92-linux-x64.rpm...\"\n        wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" http://download.oracle.com/otn-pub/java/jdk/8u92-b14/jdk-8u92-linux-x64.rpm\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        log \"Failed to download jdk-8u92-linux-x64.rpm.\"\n        exit 1\n    fi\n    yum -y localinstall jdk-8u92-linux-x64.rpm\n#    rm ~/jdk-8u*-linux-x64.rpm\n}\n\n# Install Elasticsearch\ninstall_es()\n{\n\t# Import the Elasticsearch public GPG key into RPM\n    RETRY=0\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        log \"Retry $RETRY: importing GPG-KEY-elasticsearch...\"\n        rpm --import http://packages.elastic.co/GPG-KEY-elasticsearch\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        log \"Failed to import GPG-KEY-elasticsearch.\"\n        exit 1\n    fi\n\n    # Create a new yum repository file for Elasticsearch\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        echo '[elasticsearch-2.x]\nname=Elasticsearch repository for 2.x packages\nbaseurl=http://packages.elastic.co/elasticsearch/2.x/centos\ngpgcheck=1\ngpgkey=http://packages.elastic.co/GPG-KEY-elasticsearch\nenabled=1' | tee /etc/yum.repos.d/elasticsearch.repo\n    fi\n\n    if [[ \"${ES_VERSION}\" == \\1* ]]; then\n        echo '[elasticsearch-1.7]\nname=Elasticsearch repository for 1.7.x packages\nbaseurl=http://packages.elastic.co/elasticsearch/1.7/centos\ngpgcheck=1\ngpgkey=http://packages.elastic.co/GPG-KEY-elasticsearch\nenabled=1' | tee /etc/yum.repos.d/elasticsearch.repo\n    fi\n\n    # Install Elasticsearch\n    RETRY=0\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        log \"Retry $RETRY: installing elasticsearch...\"\n        yum -y install elasticsearch-${ES_VERSION}\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        log \"Failed to install elasticsearch.\"\n        exit 1\n    fi\n\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n\n#if [ ${USE_AFS} -ne 0 ];\n#then\n#    log \"setting up afs\"\n\n    # install cachefilesd\n    # disabled for more extensive testing\n    ##apt-get install cachefilesd\n    ##echo \"RUN=yes\" >> /etc/default/cachefilesd\n    ##service cachefilesd start\n\n    # create and mount an AFS share\n#    bash afs-utils-0.1.sh -cp -a ${STORAGE_ACCOUNT} -k ${ACCESS_KEY}\n#else\n#    log \"setting up disks\"\n\n    #Format data disks (Find data disks then partition, format, and mount them as separate drives)\nbash vm-disk-utils-0.1.sh\n#fi\n\n#Install Oracle Java\n#------------------------\ninstall_java\n\n#\n#Install Elasticsearch\n#-----------------------\ninstall_es\n\n#install jmeter server agent\n#if [ $JMETER_AGENT ];\n#then\n#    install_jmeter_server\n#fi\n\n# Prepare configuration information\n# Configure permissions on data disks for elasticsearch user:group\n#--------------------------\nDATAPATH_CONFIG=\"\"\nif [ -d \"${DATA_BASE}\" ]; then\n    for D in `find /datadisks/ -mindepth 1 -maxdepth 1 -type d`\n    do\n        #Configure disk permissions and folder for storage\n        setup_data_disk ${D}\n        # Add to list for elasticsearch configuration\n        DATAPATH_CONFIG+=\"$D,\"\n    done\n    #Remove the extra trailing comma\n    DATAPATH_CONFIG=\"${DATAPATH_CONFIG%?}\"\nelse\n    #If we do not find folders/disks in our data disk mount directory then use the defaults\n    log \"Configured data directory does not exist for ${HOSTNAME} using defaults\"\nfi\n\n#expand_staticip_range \"$IP_RANGE\"\n\nS=$(expand_ip_range \"$DISCOVERY_ENDPOINTS\")\nHOSTS_CONFIG=\"[\\\"${S// /\\\",\\\"}\\\"]\"\n\n#Format the static discovery host endpoints for Elasticsearch configuration [\"\",\"\"] format\n#HOSTS_CONFIG=\"[\\\"${DISCOVERY_ENDPOINTS//-/\\\",\\\"}\\\"]\"\n\n#Configure Elasticsearch settings\n#---------------------------\n#Backup the current Elasticsearch configuration file\nmv /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.bak\n\n# Set cluster and machine names - just use hostname for our node.name\necho \"cluster.name: $CLUSTER_NAME\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.name: ${HOSTNAME}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure paths - if we have data disks attached then use them\nif [ -n \"$DATAPATH_CONFIG\" ]; then\n    log \"Update configuration with data path list of $DATAPATH_CONFIG\"\n    echo \"path.data: $DATAPATH_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# if we are using AFS, then add that path\n#if [ ${USE_AFS} -ne 0 ];\n#then\n#    echo \"node.enable_custom_paths: true\" >> /etc/elasticsearch/elasticsearch.yml\n#    echo \"node.add_id_to_custom_path: false\" >> /etc/elasticsearch/elasticsearch.yml\n#    echo \"path.shared_data: /sharedfs\" >> /etc/elasticsearch/elasticsearch.yml\n#fi\n\n# Configure discovery\nlog \"Update configuration with hosts configuration of $HOSTS_CONFIG\"\necho \"discovery.zen.ping.multicast.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\necho \"discovery.zen.ping.unicast.hosts: $HOSTS_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure Elasticsearch node type\nlog \"Configure master/client/data node type flags master-$MASTER_ONLY_NODE data-$DATA_NODE\"\n\nif [ ${MASTER_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as master only\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${DATA_NODE} -ne 0 ]; then\n    log \"Configure node as data only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${CLIENT_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as client only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelse\n    log \"Configure node for master and data\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\necho \"discovery.zen.minimum_master_nodes: 2\" >> /etc/elasticsearch/elasticsearch.yml\n\nif [[ \"${ES_VERSION}\" == \\2* ]]; then\n    echo \"network.host: _non_loopback_\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\nif [[ \"${MARVEL_ENDPOINTS}\" ]]; then\n  # non-Marvel node\n  mep=$(expand_ip_range \"$MARVEL_ENDPOINTS\")\n  expanded_marvel_endpoints=\"[\\\"${mep// /\\\",\\\"}\\\"]\"\n\n  if [[ \"${ES_VERSION}\" == \\2* ]]; then\n    # 2.x non-Marvel node\n    echo \"marvel.agent.exporters:\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"  id1:\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"    type: http\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"    host: ${expanded_marvel_endpoints}\" >> /etc/elasticsearch/elasticsearch.yml\n  else\n    # 1.x non-Marvel node\n    echo \"marvel.agent.exporter.hosts: ${expanded_marvel_endpoints}\" >> /etc/elasticsearch/elasticsearch.yml\n  fi\nfi\n\nif [[ ${MARVEL_ONLY_NODE} -ne 0 && \"${ES_VERSION}\" == \\1* ]]; then\n  # 1.x Marvel node\n  echo \"marvel.agent.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# DNS Retry\necho \"options timeout:1 attempts:5\" >> /etc/resolv.conf\n\n# Increase maximum mmap count\necho \"vm.max_map_count = 262144\" >> /etc/sysctl.conf\n\n#\"action.disable_delete_all_indices: ${DISABLE_DELETE_ALL}\" >> /etc/elasticsearch/elasticsearch.yml\n#\"action.auto_create_index: ${AUTOCREATE_INDEX}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure Environment\n#----------------------\n#/etc/default/elasticseach\n#Update HEAP Size in this configuration or in upstart service\n#Set Elasticsearch heap size to 50% of system memory\n#TODO: Move this to an init.d script so we can handle instance size increases\n#TODO: Client nodes should use 75% of the heap\nES_HEAP=`free -m |grep Mem | awk '{if ($2/2 >31744)  print 31744;else print $2/2;}'`\nlog \"Configure elasticsearch heap size - $ES_HEAP\"\necho \"ES_HEAP_SIZE=${ES_HEAP}m\" >> /etc/default/elasticsearch\n\n#Optionally Install Marvel\nif [ ${INSTALL_MARVEL} -ne 0 ]; then\n    log \"Installing Marvel Plugin\"\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        RETRY=0\n        while [ $RETRY -lt $MAX_RETRY ]; do\n            log \"Retry $RETRY: installing plugin license...\"\n            /usr/share/elasticsearch/bin/plugin install license\n            if [ $? -ne 0 ]; then\n                let RETRY=RETRY+1\n            else\n                break\n            fi\n        done\n        if [ $RETRY -eq $MAX_RETRY ]; then\n            log \"Failed to install plugin license.\"\n            exit 1\n        fi\n\n        RETRY=0\n        while [ $RETRY -lt $MAX_RETRY ]; do\n            log \"Retry $RETRY: installing plugin marvel-agent...\"\n            echo y | /usr/share/elasticsearch/bin/plugin install marvel-agent\n            if [ $? -ne 0 ]; then\n                let RETRY=RETRY+1\n            else\n                break\n            fi\n        done\n        if [ $RETRY -eq $MAX_RETRY ]; then\n            log \"Failed to install plugin marvel-agent.\"\n            exit 1\n        fi\n\n    else\n        RETRY=0\n        while [ $RETRY -lt $MAX_RETRY ]; do\n            log \"Retry $RETRY: installing Marvel plugin...\"\n            /usr/share/elasticsearch/bin/plugin -i elasticsearch/marvel/1.3.1\n            if [ $? -ne 0 ]; then\n                let RETRY=RETRY+1\n            else\n                break\n            fi\n        done\n        if [ $RETRY -eq $MAX_RETRY ]; then\n            log \"Failed to install Marvel plugin.\"\n            exit 1\n        fi\n\n\n    fi\nfi\n\n# install the cloud-azure plugin\nif [ ${INSTALL_CLOUD_AZURE} -ne 0 ]; then\n    log \"Installing Cloud-Azure Plugin\"\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        /usr/share/elasticsearch/bin/plugin install cloud-azure\n        echo \"cloud.azure.storage.default.account: ${CLOUD_AZURE_ACCOUNT}\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"cloud.azure.storage.default.key: ${CLOUD_AZURE_KEY}\" >> /etc/elasticsearch/elasticsearch.yml\n    else\n        /usr/share/elasticsearch/bin/plugin -i elasticsearch/elasticsearch-cloud-azure/2.8.2\n        echo \"cloud.azure.storage.account: ${CLOUD_AZURE_ACCOUNT}\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"cloud.azure.storage.key: ${CLOUD_AZURE_KEY}\" >> /etc/elasticsearch/elasticsearch.yml\n    fi\nfi\n\n# start the service\nlog \"Starting Elasticsearch on ${HOSTNAME}\"\nsystemctl start elasticsearch\nsystemctl enable elasticsearch\nlog \"complete elasticsearch setup and started, checking status...\"\n\nservice elasticsearch status\nif [ $? -ne 0 ]; then\n    log \"elasticsearch service is in unhealthy state, exit\"\n    exit 1\nfi\n\nexit 0\n\n#Script Extras\n\n#Configure open file and memory limits\n#Swap is disabled by default in Ubuntu Azure VMs\n#echo \"bootstrap.mlockall: true\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Verify this is necessary on azure\n#echo \"elasticsearch    -    nofile    65536\" >> /etc/security/limits.conf\n#echo \"elasticsearch     -    memlock   unlimited\" >> /etc/security/limits.conf\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/su\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session-noninteractive\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/sudo\n\n#--------------- TEMP (We will use this for the update path yet) ---------------\n#Updating the properties in the existing configuraiton has been a bit sensitve and requires more testing\n#sed -i -e \"/cluster\\.name/s/^#//g;s/^\\(cluster\\.name\\s*:\\s*\\).*\\$/\\1${CLUSTER_NAME}/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/bootstrap\\.mlockall/s/^#//g;s/^\\(bootstrap\\.mlockall\\s*:\\s*\\).*\\$/\\1true/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/path\\.data/s/^#//g;s/^\\(path\\.data\\s*:\\s*\\).*\\$/\\1${DATAPATH_CONFIG}/\" /etc/elasticsearch/elasticsearch.yml\n\n# Minimum master nodes nodes/2+1 (These can be configured via API as well - (_cluster/settings))\n# discovery.zen.minimum_master_nodes: 2\n# gateway.expected_nodes: 10\n# gateway.recover_after_time: 5m\n#----------------------\n", "num_lines": 552}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Trent Swanson (Full Scale 180 Inc)\n#\nhelp()\n{\n    echo \"This script installs Elasticsearch cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-n elasticsearch cluster name\"\n    echo \"-d static discovery endpoints 10.0.0.1-3\"\n    echo \"-v elasticsearch version\"\n    echo \"-a storage account (for AFS)\"\n    echo \"-k access key (for AFS)\"\n    echo \"-c create and mount AFS share\"\n    echo \"-m install marvel yes/no\"\n    echo \"-e export marvel data to a different ip\"\n    echo \"-w configure as a dedicated marvel node\"\n    echo \"-x configure as a dedicated master node\"\n    echo \"-y configure as client only node (no master, no data)\"\n    echo \"-z configure as data node (no master)\"\n    echo \"-s used striped data disk volumes\"\n    echo \"-j install jmeter server agent\"\n    echo \"-p install the cloud-azure plugin\"\n    echo \"-o storage account (for cloud-azure)\"\n    echo \"-r storage key (for cloud-azure)\"\n    echo \"-h view this help content\"\n}\n\n# Log method to control/redirect log output\nlog()\n{\n    # If you want to enable this logging add a un-comment the line below and add your account id\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nlog \"Begin execution of Elasticsearch script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? == 0 ]\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hosts file if not there\n  echo \"127.0.0.1 ${HOSTNAME}\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\nfi\n\n#Script Parameters\nCLUSTER_NAME=\"elasticsearch\"\nES_VERSION=\"2.0.0\"\nMARVEL_ONLY_NODE=0\nDISCOVERY_ENDPOINTS=\"\"\nINSTALL_MARVEL=0\nCLIENT_ONLY_NODE=0\nDATA_NODE=0\nMASTER_ONLY_NODE=0\nUSE_AFS=0\nSTORAGE_ACCOUNT=\"\"\nACCESS_KEY=\"\"\nINSTALL_CLOUD_AZURE=0\nCLOUD_AZURE_ACCOUNT=\"\"\nCLOUD_AZURE_KEY=\"\"\n\n#Loop through options passed\nwhile getopts :n:d:v:a:k:cme:o:r:pwxyzsjh optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    n) #set cluster name\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    d) #static discovery endpoints\n      DISCOVERY_ENDPOINTS=${OPTARG}\n      ;;\n    v) #elasticsearch version number\n      ES_VERSION=${OPTARG}\n      ;;\n    m) #install marvel\n      INSTALL_MARVEL=1\n      ;;\n    e) #export marvel data\n      MARVEL_ENDPOINTS=${OPTARG}\n      ;;\n    w) #marvel node\n      MARVEL_ONLY_NODE=1\n      ;;\n    x) #master node\n      MASTER_ONLY_NODE=1\n      ;;\n    y) #client node\n      CLIENT_ONLY_NODE=1\n      ;;\n    z) #data node\n      DATA_NODE=1\n      ;;\n    s) #use OS striped disk volumes\n      OS_STRIPED_DISK=1\n      ;;\n    a) #set the storage account for AFS\n      STORAGE_ACCOUNT=${OPTARG}\n      ;;\n    k) #set the access key for AFS\n      ACCESS_KEY=${OPTARG}\n      ;;\n    c) #use AFS for the data storage\n      USE_AFS=1\n      ;;\n    d) #place data on local resource disk\n      NON_DURABLE=1\n      ;;\n    j) #install jmeter server agent\n      JMETER_AGENT=1\n      ;;\n    p) #install cloud-azure plugin\n      INSTALL_CLOUD_AZURE=1\n      ;;\n    o) #set cloud-azure account\n      CLOUD_AZURE_ACCOUNT=${OPTARG}\n      ;;\n    r) #set the cloud-azure account key\n      CLOUD_AZURE_KEY=${OPTARG}\n      ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Base path for data disk mount points\n# The script assume format /datadisks/disk1 /datadisks/disk2\nDATA_BASE=\"/datadisks\"\n\n# Expand a list of successive ip range and filter my local local ip from the list\n# Ip list is represented as a prefix and that is appended with a zero to N index\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    #Get the IP Addresses on this machine\n    declare -a MY_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}\"\n        if ! [[ \"${MY_IPS[@]}\" =~ \"${HOST}\" ]]; then\n            EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n        fi\n    done\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\n# Configure Elasticsearch Data Disk Folder and Permissions\nsetup_data_disk()\n{\n    log \"Configuring disk $1\"\n\n    mkdir -p \"$1\"\n    chown -R elasticsearch:elasticsearch \"$1\"\n    chmod 755 \"$1\"\n}\n\n# Install Oracle Java\ninstall_java()\n{\n    log \"Installing Java\"\n    add-apt-repository -y ppa:webupd8team/java\n    apt-get -y update  > /dev/null\n    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n    apt-get -y install oracle-java8-installer  > /dev/null\n}\n\n# Install Elasticsearch\ninstall_es()\n{\n\n\t# Elasticsearch 2.x uses a different download path\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        DOWNLOAD_URL=\"https://download.elasticsearch.org/elasticsearch/release/org/elasticsearch/distribution/deb/elasticsearch/$ES_VERSION/elasticsearch-$ES_VERSION.deb\"\n    else\n        DOWNLOAD_URL=\"https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-$ES_VERSION.deb\"\n    fi\n\n    log \"Installing Elaticsearch Version - $ES_VERSION\"\n\tlog \"Download location - $DOWNLOAD_URL\"\n    sudo wget -q \"$DOWNLOAD_URL\" -O elasticsearch.deb\n    sudo dpkg -i elasticsearch.deb\n}\n\ninstall_jmeter_server()\n{\n    log \"download jmeter server agent\"\n    apt-get -y install unzip\n    wget -O agent.zip http://jmeter-plugins.org/downloads/file/ServerAgent-2.2.1.zip\n    mkdir /opt/jmeter-server-agent\n    unzip agent.zip -d /opt/jmeter-server-agent\n\n    log \"updating iptables\"\n    sudo iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 4444 -j ACCEPT\n\n    log \"setup agent service\"\n    cat << EOF > /etc/init/jmeter-server-agent.conf\n    description \"JMeter Server Agent\"\n\n    start on starting\n    script\n        /opt/jmeter-server-agent/startAgent.sh\n    end script\nEOF\n\n    log \"starting agent service\"\n    service jmeter-server-agent start\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n\nif [ ${USE_AFS} -ne 0 ];\nthen\n    log \"setting up afs\"\n\n    # install cachefilesd\n    # disabled for more extensive testing\n    ##apt-get install cachefilesd\n    ##echo \"RUN=yes\" >> /etc/default/cachefilesd\n    ##service cachefilesd start\n\n    # create and mount an AFS share\n    bash afs-utils-0.1.sh -cp -a ${STORAGE_ACCOUNT} -k ${ACCESS_KEY}\nelse\n    log \"setting up disks\"\n\n    #Format data disks (Find data disks then partition, format, and mount them as separate drives)\n    bash vm-disk-utils-0.1.sh\nfi\n\n#Install Oracle Java\n#------------------------\ninstall_java\n\n#\n#Install Elasticsearch\n#-----------------------\ninstall_es\n\n#install jmeter server agent\nif [ $JMETER_AGENT ];\nthen\n    install_jmeter_server\nfi\n\n# Prepare configuration information\n# Configure permissions on data disks for elasticsearch user:group\n#--------------------------\nDATAPATH_CONFIG=\"\"\nif [ -d \"${DATA_BASE}\" ]; then\n    for D in `find /datadisks/ -mindepth 1 -maxdepth 1 -type d`\n    do\n        #Configure disk permissions and folder for storage\n        setup_data_disk ${D}\n        # Add to list for elasticsearch configuration\n        DATAPATH_CONFIG+=\"$D,\"\n    done\n    #Remove the extra trailing comma\n    DATAPATH_CONFIG=\"${DATAPATH_CONFIG%?}\"\nelse\n    #If we do not find folders/disks in our data disk mount directory then use the defaults\n    log \"Configured data directory does not exist for ${HOSTNAME} using defaults\"\nfi\n\n#expand_staticip_range \"$IP_RANGE\"\n\nS=$(expand_ip_range \"$DISCOVERY_ENDPOINTS\")\nHOSTS_CONFIG=\"[\\\"${S// /\\\",\\\"}\\\"]\"\n\n#Format the static discovery host endpoints for Elasticsearch configuration [\"\",\"\"] format\n#HOSTS_CONFIG=\"[\\\"${DISCOVERY_ENDPOINTS//-/\\\",\\\"}\\\"]\"\n\n#Configure Elasticsearch settings\n#---------------------------\n#Backup the current Elasticsearch configuration file\nmv /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.bak\n\n# Set cluster and machine names - just use hostname for our node.name\necho \"cluster.name: $CLUSTER_NAME\" >> /etc/elasticsearch/elasticsearch.yml\necho \"node.name: ${HOSTNAME}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure paths - if we have data disks attached then use them\nif [ -n \"$DATAPATH_CONFIG\" ]; then\n    log \"Update configuration with data path list of $DATAPATH_CONFIG\"\n    echo \"path.data: $DATAPATH_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# if we are using AFS, then add that path\nif [ ${USE_AFS} -ne 0 ];\nthen\n    echo \"node.enable_custom_paths: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.add_id_to_custom_path: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"path.shared_data: /sharedfs\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# Configure discovery\nlog \"Update configuration with hosts configuration of $HOSTS_CONFIG\"\necho \"discovery.zen.ping.multicast.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\necho \"discovery.zen.ping.unicast.hosts: $HOSTS_CONFIG\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure Elasticsearch node type\nlog \"Configure master/client/data node type flags master-$MASTER_ONLY_NODE data-$DATA_NODE\"\n\nif [ ${MASTER_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as master only\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${DATA_NODE} -ne 0 ]; then\n    log \"Configure node as data only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nelif [ ${CLIENT_ONLY_NODE} -ne 0 ]; then\n    log \"Configure node as client only\"\n    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\nelse\n    log \"Configure node for master and data\"\n    echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\necho \"discovery.zen.minimum_master_nodes: 2\" >> /etc/elasticsearch/elasticsearch.yml\n\nif [[ \"${ES_VERSION}\" == \\2* ]]; then\n    echo \"network.host: _non_loopback_\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\nif [[ \"${MARVEL_ENDPOINTS}\" ]]; then\n  # non-Marvel node\n  mep=$(expand_ip_range \"$MARVEL_ENDPOINTS\")\n  expanded_marvel_endpoints=\"[\\\"${mep// /\\\",\\\"}\\\"]\"\n\n  if [[ \"${ES_VERSION}\" == \\2* ]]; then\n    # 2.x non-Marvel node\n    echo \"marvel.agent.exporters:\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"  id1:\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"    type: http\" >> /etc/elasticsearch/elasticsearch.yml\n    echo \"    host: ${expanded_marvel_endpoints}\" >> /etc/elasticsearch/elasticsearch.yml\n  else\n    # 1.x non-Marvel node\n    echo \"marvel.agent.exporter.hosts: ${expanded_marvel_endpoints}\" >> /etc/elasticsearch/elasticsearch.yml\n  fi\nfi\n\nif [[ ${MARVEL_ONLY_NODE} -ne 0 && \"${ES_VERSION}\" == \\1* ]]; then\n  # 1.x Marvel node\n  echo \"marvel.agent.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\nfi\n\n# DNS Retry\necho \"options timeout:1 attempts:5\" >> /etc/resolvconf/resolv.conf.d/head\nresolvconf -u\n\n# Increase maximum mmap count\necho \"vm.max_map_count = 262144\" >> /etc/sysctl.conf\n\n#\"action.disable_delete_all_indices: ${DISABLE_DELETE_ALL}\" >> /etc/elasticsearch/elasticsearch.yml\n#\"action.auto_create_index: ${AUTOCREATE_INDEX}\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Configure Environment\n#----------------------\n#/etc/default/elasticseach\n#Update HEAP Size in this configuration or in upstart service\n#Set Elasticsearch heap size to 50% of system memory\n#TODO: Move this to an init.d script so we can handle instance size increases\n#TODO: Client nodes should use 75% of the heap\nES_HEAP=`free -m |grep Mem | awk '{if ($2/2 >31744)  print 31744;else print $2/2;}'`\nlog \"Configure elasticsearch heap size - $ES_HEAP\"\necho \"ES_HEAP_SIZE=${ES_HEAP}m\" >> /etc/default/elasticsearch\n\n#Optionally Install Marvel\nif [ ${INSTALL_MARVEL} -ne 0 ]; then\n    log \"Installing Marvel Plugin\"\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        /usr/share/elasticsearch/bin/plugin install license\n        /usr/share/elasticsearch/bin/plugin install marvel-agent\n    else\n        /usr/share/elasticsearch/bin/plugin -i elasticsearch/marvel/1.3.1\n    fi\nfi\n\n# install the cloud-azure plugin\nif [ ${INSTALL_CLOUD_AZURE} -ne 0 ]; then\n    log \"Installing Cloud-Azure Plugin\"\n    if [[ \"${ES_VERSION}\" == \\2* ]]; then\n        /usr/share/elasticsearch/bin/plugin install cloud-azure\n        echo \"cloud.azure.storage.default.account: ${CLOUD_AZURE_ACCOUNT}\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"cloud.azure.storage.default.key: ${CLOUD_AZURE_KEY}\" >> /etc/elasticsearch/elasticsearch.yml\n    else\n        /usr/share/elasticsearch/bin/plugin -i elasticsearch/elasticsearch-cloud-azure/2.8.2\n        echo \"cloud.azure.storage.account: ${CLOUD_AZURE_ACCOUNT}\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"cloud.azure.storage.key: ${CLOUD_AZURE_KEY}\" >> /etc/elasticsearch/elasticsearch.yml\n    fi\nfi\n\n#Install Monit\n#TODO - Install Monit to monitor the process (Although load balancer probes can accomplish this)\n\n#and... start the service\nlog \"Starting Elasticsearch on ${HOSTNAME}\"\nupdate-rc.d elasticsearch defaults 95 10\nsudo service elasticsearch start\nlog \"complete elasticsearch setup and started\"\nexit 0\n\n#Script Extras\n\n#Configure open file and memory limits\n#Swap is disabled by default in Ubuntu Azure VMs\n#echo \"bootstrap.mlockall: true\" >> /etc/elasticsearch/elasticsearch.yml\n\n# Verify this is necessary on azure\n#echo \"elasticsearch    -    nofile    65536\" >> /etc/security/limits.conf\n#echo \"elasticsearch     -    memlock   unlimited\" >> /etc/security/limits.conf\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/su\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/common-session-noninteractive\n#echo \"session    required    pam_limits.so\" >> /etc/pam.d/sudo\n\n#--------------- TEMP (We will use this for the update path yet) ---------------\n#Updating the properties in the existing configuraiton has been a bit sensitve and requires more testing\n#sed -i -e \"/cluster\\.name/s/^#//g;s/^\\(cluster\\.name\\s*:\\s*\\).*\\$/\\1${CLUSTER_NAME}/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/bootstrap\\.mlockall/s/^#//g;s/^\\(bootstrap\\.mlockall\\s*:\\s*\\).*\\$/\\1true/\" /etc/elasticsearch/elasticsearch.yml\n#sed -i -e \"/path\\.data/s/^#//g;s/^\\(path\\.data\\s*:\\s*\\).*\\$/\\1${DATAPATH_CONFIG}/\" /etc/elasticsearch/elasticsearch.yml\n\n# Minimum master nodes nodes/2+1 (These can be configured via API as well - (_cluster/settings))\n# discovery.zen.minimum_master_nodes: 2\n# gateway.expected_nodes: 10\n# gateway.recover_after_time: 5m\n#----------------------\n", "num_lines": 478}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Trent Swanson (Full Scale 180 Inc)\n#\n\nhelp()\n{\n    echo \"Usage: $(basename $0) [-v es_version] [-t target_host] [-m] [-s] [-h]\"\n    echo \"Options:\"\n    echo \"  -v    elasticsearch version to target (default: 2.3.1)\"\n    echo \"  -t    target host (default: http://10.0.1.4:9200)\"\n    echo \"  -m    install marvel (default: no)\"\n    echo \"  -s    install sense (default: no)\"\n    echo \"  -h    this help message\"\n}\n\nerror()\n{\n    echo \"$1\" >&2\n    exit 3\n}\n\nMAX_RETRY=5\n\ninstall_java() {\n    RETRY=0\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        echo \"Retry $RETRY: downloading jdk-8u92-linux-x64.rpm...\"\n        wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" http://download.oracle.com/otn-pub/java/jdk/8u92-b14/jdk-8u92-linux-x64.rpm\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        echo \"Failed to download jdk-8u92-linux-x64.rpm.\"\n        exit 1\n    fi\n    yum -y localinstall jdk-8u92-linux-x64.rpm\n#    rm ~/jdk-8u*-linux-x64.rpm\n}\n\ninstall_kibana() {\n    # create repository files\n    # default - ES 2.3.1\n    KIBANA_VERSION='4.5'\n    if [[ \"${ES_VERSION}\" == \\2.\\2* ]]; then\n        KIBANA_VERSION='4.4'\n    fi\n\n    # TODO: Install Kibana 4.3 for ES 2.1.*\n    if [[ \"${ES_VERSION}\" == \\2.\\1* ]]; then\n        echo \"Kibana installation for ES_VERSION 2.1.* is unimplemented.\"\n        exit 1\n    fi\n\n    if [[ \"${ES_VERSION}\" == \\1.\\7* ]]; then\n        KIBANA_VERSION='4.1'\n    fi\n\n    echo \"[kibana-${KIBANA_VERSION}]\nname=Kibana repository for ${KIBANA_VERSION}.x packages\nbaseurl=http://packages.elastic.co/kibana/${KIBANA_VERSION}/centos\ngpgcheck=1\ngpgkey=http://packages.elastic.co/GPG-KEY-elasticsearch\nenabled=1\" | tee /etc/yum.repos.d/kibana.repo\n\n    RETRY=0\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        echo \"Retry $RETRY: installing kibana...\"\n        yum install -y kibana\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        echo \"Failed to install kibana.\"\n        exit 1\n    fi\n\n    mv /opt/kibana/config/kibana.yml /opt/kibana/config/kibana.yml.bak\n\n    if [[ \"${KIBANA_VERSION}\" == \"4.1\" ]];\n    then\n        cat /opt/kibana/config/kibana.yml.bak | sed \"s|http://localhost:9200|${ELASTICSEARCH_URL}|\" >> /opt/kibana/config/kibana.yml\n    else\n        echo \"elasticsearch.url: \\\"$ELASTICSEARCH_URL\\\"\" >> /opt/kibana/config/kibana.yml\n    fi\n\n    # install the marvel plugin for 2.x\n    if [ ${INSTALL_MARVEL} -ne 0 ];\n    then\n\t\tif [[ \"${ES_VERSION}\" == \\2* ]];\n        then\n            RETRY=0\n            while [ $RETRY -lt $MAX_RETRY ]; do\n                echo \"Retry $RETRY: installing Marvel plugin...\"\n                /opt/kibana/bin/kibana plugin --install elasticsearch/marvel/${ES_VERSION}\n                if [ $? -ne 0 ]; then\n                    let RETRY=RETRY+1\n                else\n                    break\n                fi\n            done\n            if [ $RETRY -eq $MAX_RETRY ]; then\n                echo \"Failed to install Marvel plugin.\"\n                exit 1\n            fi\n        fi\n\n        # for 1.x marvel is installed only within the cluster, not on the kibana node\n    fi\n\n    # install the sense plugin for 2.x\n    if [ ${INSTALL_SENSE} -ne 0 ];\n    then\n        if [[ \"${ES_VERSION}\" == \\2* ]];\n        then\n            RETRY=0\n            while [ $RETRY -lt $MAX_RETRY ]; do\n                echo \"Retry $RETRY: installing sense plugin...\"\n                /opt/kibana/bin/kibana plugin --install elastic/sense\n                if [ $? -ne 0 ]; then\n                    let RETRY=RETRY+1\n                else\n                    break\n                fi\n            done\n            if [ $RETRY -eq $MAX_RETRY ]; then\n                echo \"Failed to install sense plugin.\"\n                exit 1\n            fi\n        fi\n\n        # for 1.x sense is not supported\n    fi\n\n    chown -R kibana: /opt/kibana\n\n    # Add start and enable kibana service\n    systemctl start kibana\n    systemctl enable kibana\n\n    exit 0\n}\n\n###############\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    error \"You must be root to run this script.\"\nfi\n\nES_VERSION=\"2.3.1\"\nINSTALL_MARVEL=0\nINSTALL_SENSE=0\nELASTICSEARCH_URL=\"http://10.0.1.4:9200\"\n\nwhile getopts :v:t:msh optname; do\n  case ${optname} in\n    v) ES_VERSION=${OPTARG};;\n    m) INSTALL_MARVEL=1;;\n    s) INSTALL_SENSE=1;;\n    t) ELASTICSEARCH_URL=${OPTARG};;\n    h) help; exit 1;;\n   \\?) help; error \"Option -${OPTARG} not supported.\";;\n    :) help; error \"Option -${OPTARG} requires an argument.\";;\n  esac\ndone\n\ninstall_java\ninstall_kibana\n", "num_lines": 198}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Trent Swanson (Full Scale 180 Inc)\n#\n\nhelp()\n{\n    echo \"Usage: $(basename $0) [-v es_version] [-t target_host] [-m] [-s] [-h]\"\n    echo \"Options:\"\n    echo \"  -v    elasticsearch version to target (default: 2.3.1)\"\n    echo \"  -t    target host (default: http://10.0.1.4:9200)\"\n    echo \"  -m    install marvel (default: no)\"\n    echo \"  -s    install sense (default: no)\"\n    echo \"  -h    this help message\"\n}\n\nerror()\n{\n    echo \"$1\" >&2\n    exit 3\n}\n\ninstall_java() {\n    add-apt-repository -y ppa:webupd8team/java\n    apt-get -q -y update  > /dev/null\n    echo debconf shared/accepted-oracle-license-v1-1 select true | debconf-set-selections\n    echo debconf shared/accepted-oracle-license-v1-1 seen true | debconf-set-selections\n    apt-get -q -y install oracle-java8-installer  > /dev/null\n}\n\ninstall_kibana() {\n    # default - ES 2.3.1\n\tkibana_url=\"https://download.elastic.co/kibana/kibana/kibana-4.5.0-linux-x64.tar.gz\"\n\n\tif [[ \"${ES_VERSION}\" == \"2.2.2\" ]];\n    then\n\t\tkibana_url=\"https://download.elastic.co/kibana/kibana/kibana-4.4.2-linux-x64.tar.gz\"\n\tfi\n\n    if [[ \"${ES_VERSION}\" == \"2.1.2\" ]];\n    then\n        kibana_url=\"https://download.elastic.co/kibana/kibana/kibana-4.3.3-linux-x64.tar.gz\"\n    fi\n\n    if [[ \"${ES_VERSION}\" == \"1.7.5\" ]];\n    then\n        kibana_url=\"https://download.elastic.co/kibana/kibana/kibana-4.1.6-linux-x64.tar.gz\"\n    fi\n\n    groupadd -g 999 kibana\n    useradd -u 999 -g 999 kibana\n\n    mkdir -p /opt/kibana\n    curl -s -o kibana.tar.gz ${kibana_url}\n    tar xvf kibana.tar.gz -C /opt/kibana/ --strip-components=1 > /dev/null\n\n    chown -R kibana: /opt/kibana\n    mv /opt/kibana/config/kibana.yml /opt/kibana/config/kibana.yml.bak\n\n    if [[ \"${ES_VERSION}\" == \\2* ]];\n    then\n        echo \"elasticsearch.url: \\\"$ELASTICSEARCH_URL\\\"\" >> /opt/kibana/config/kibana.yml\n    else\n        cat /opt/kibana/config/kibana.yml.bak | sed \"s|http://localhost:9200|${ELASTICSEARCH_URL}|\" >> /opt/kibana/config/kibana.yml\n    fi\n\n    # install the marvel plugin for 2.x\n    if [ ${INSTALL_MARVEL} -ne 0 ];\n    then\n\t\tif [[ \"${ES_VERSION}\" == \\2* ]];\n        then\n            /opt/kibana/bin/kibana plugin --install elasticsearch/marvel/${ES_VERSION}\n        fi\n\n        # for 1.x marvel is installed only within the cluster, not on the kibana node\n    fi\n\n    # install the sense plugin for 2.x\n    if [ ${INSTALL_SENSE} -ne 0 ];\n    then\n        if [[ \"${ES_VERSION}\" == \\2* ]];\n        then\n            /opt/kibana/bin/kibana plugin --install elastic/sense\n        fi\n\n        # for 1.x sense is not supported\n    fi\n\n# Add upstart task and start kibana service\ncat << EOF > /etc/init/kibana.conf\n    # kibana\n    description \"Elasticsearch Kibana Service\"\n\n    start on starting\n    script\n        /opt/kibana/bin/kibana\n    end script\nEOF\n\n    chmod +x /etc/init/kibana.conf\n    service kibana start\n}\n\n###############\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    error \"You must be root to run this script.\"\nfi\n\nES_VERSION=\"2.3.1\"\nINSTALL_MARVEL=0\nINSTALL_SENSE=0\nELASTICSEARCH_URL=\"http://10.0.1.4:9200\"\n\nwhile getopts :v:t:msh optname; do\n  case ${optname} in\n    v) ES_VERSION=${OPTARG};;\n    m) INSTALL_MARVEL=1;;\n    s) INSTALL_SENSE=1;;\n    t) ELASTICSEARCH_URL=${OPTARG};;\n    h) help; exit 1;;\n   \\?) help; error \"Option -${OPTARG} not supported.\";;\n    :) help; error \"Option -${OPTARG} requires an argument.\";;\n  esac\ndone\n\ninstall_java\ninstall_kibana\n", "num_lines": 152}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Hans Krijger (MSFT)\n#\n\nhelp()\n{\n    echo \"This script installs JMeter on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"  -h              view this help content\"\n    echo \"  -m              install as a master node\"\n    echo \"  -r <hosts>      set remote hosts (master only)\"\n    echo \"  -j <jarball>    location of the jarball to download and unzip\"\n    echo \"  -t <testpack>   location of the test pack to download and unzip (master only)\"\n}\n\nlog()\n{\n    echo \"$1\"\n}\n\nerror()\n{\n    echo \"$1\" >&2\n    exit 1\n}\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    error \"Script executed without root permissions\"\nfi\n\n# script parameters\nIS_MASTER=0\nREMOTE_HOSTS=\"\"\nCLUSTER_NAME=\"elasticsearch\"\n\nwhile getopts :hmr:j:t: optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    h) # show help\n      help\n      exit 2\n      ;;\n    m) # setup as master\n      IS_MASTER=1\n      ;;\n    r) # provide remote hosts\n      REMOTE_RANGE=${OPTARG}\n      ;;\n    j) # provide jarball\n      JARBALL=${OPTARG}\n      ;;\n    t) # provide testpack\n      TESTPACK=${OPTARG}\n      ;;\n    \\?) # unrecognized option - show help\n      help\n      error \"Option ${OPTARG} not allowed.\"\n      ;;\n  esac\ndone\n\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n    declare -a MY_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}\"\n        if ! [[ \"${MY_IPS[@]}\" =~ \"${HOST}\" ]]; then\n            EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n        fi\n    done\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\ninstall_java()\n{\n    log \"Installing Java\"\n    add-apt-repository -y ppa:webupd8team/java\n    apt-get -y update  > /dev/null\n    echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n    echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n    apt-get -y install oracle-java8-installer  > /dev/null\n}\n\ninstall_jmeter_service()\n{\n    cat << EOF > /etc/init/jmeter.conf\n    description \"JMeter Service\"\n\n    start on starting\n    script\n        /opt/jmeter/apache-jmeter-2.13/bin/jmeter-server\n    end script\nEOF\n\n    chmod +x /etc/init/jmeter.conf\n    service jmeter start\n}\n\nupdate_config_sub()\n{\n    mv /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties.bak\n    cat /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties.bak | sed \"s|#client.rmi.localport=0|client.rmi.localport=4441|\" | sed \"s|#server.rmi.localport=4000|server.rmi.localport=4440|\" > /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties\n}\n\nupdate_config_boss()\n{\n    mv /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties.bak\n    cat /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties.bak | sed \"s|#client.rmi.localport=0|client.rmi.localport=4440|\" | sed \"s|remote_hosts=127.0.0.1|remote_hosts=${REMOTE_HOSTS}|\" > /opt/jmeter/apache-jmeter-2.13/bin/jmeter.properties\n}\n\ninstall_jmeter()\n{\n    log \"Installing JMeter\"\n    apt-get -y install unzip\n\n    mkdir -p /opt/jmeter\n    wget -O jmeter.zip http://apache.mirror.anlx.net/jmeter/binaries/apache-jmeter-2.13.zip\n    wget -O plugins.zip http://jmeter-plugins.org/downloads/file/JMeterPlugins-Standard-1.3.0.zip\n\n    log \"unzipping jmeter\"\n    unzip -q jmeter.zip -d /opt/jmeter/\n\n    log \"unzipping plugins\"\n    unzip -q plugins.zip -d /opt/jmeter/apache-jmeter-2.13/\n\n    chmod u+x /opt/jmeter/apache-jmeter-2.13/bin/jmeter-server\n    chmod u+x /opt/jmeter/apache-jmeter-2.13/bin/jmeter\n\n    if [ ${JARBALL} ];\n    then\n        log \"installing jarball\"\n        wget -O jarball.zip ${JARBALL}\n        unzip -q jarball.zip -d /opt/jmeter/apache-jmeter-2.13/lib/junit/\n    fi\n\n    if [ ${IS_MASTER} -ne 1 ];\n    then\n        log \"setting up sub node\"\n        iptables -A INPUT -m state --state NEW -m tcp -p tcp --dport 4441 -j ACCEPT\n\n        update_config_sub\n        install_jmeter_service\n    else\n        log \"setting up boss node\"\n        iptables -A INPUT -p tcp --match multiport --dports 4440:4445 -j ACCEPT\n        iptables -A OUTPUT -p tcp --match multiport --dports 4440:4445 -j ACCEPT\n\n        update_config_boss\n\n        if [ ${TESTPACK} ];\n        then\n            log \"installing test pack\"\n            wget -O testpack.zip ${TESTPACK}\n            unzip -q testpack.zip -d /opt/jmeter/\n            chmod +x /opt/jmeter/run.sh\n        fi\n    fi\n\n    groupadd -g 999 jmeter\n    useradd -u 999 -g 999 jmeter\n    chown -R jmeter: /opt/jmeter\n}\n\n\nif [ ${REMOTE_RANGE} ];\nthen\n    S=$(expand_ip_range \"$REMOTE_RANGE\")\n    REMOTE_HOSTS=\"${S// /,}\"\n    log \"using remote hosts ${REMOTE_HOSTS}\"\nfi\n\ninstall_java\ninstall_jmeter\n\nlog \"script complete\"\n", "num_lines": 202}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/opt/jmeter/apache-jmeter-2.13/bin/jmeter -n -r -t /opt/jmeter/testplan5nodes.jmx -Grun.properties -Jm1=10.0.1.4 -Jm2=10.0.1.5 -Jm3=10.0.1.6 -Jm4=10.0.1.7 -Jm5=10.0.1.8 -Jreport1=report1 -Jreport2=report2 -Jreport3=report3 -Jreport4=report4 -Jreport5=report5 -Jreport6=report6 -Jreport7=report7 -Jreport8=report8 -Jreport9=report9\n", "num_lines": 3}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n\nhelp()\n{\n    echo \"This script installs Elasticsearch on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"  -n elasticsearch cluster name\"\n    echo \"  -m configure as master node (default: off)\"\n    echo \"  -h view this help content\"\n}\n\n# Log method to control/redirect log output\nlog()\n{\n    echo \"$1\"\n}\n\nlog \"Begin execution of Elasticsearch script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? == 0 ]\nthen\n  echo \"${HOSTNAME} found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hosts file if not there\n  echo \"127.0.0.1 ${HOSTNAME}\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\nfi\n\n#Script Parameters\nCLUSTER_NAME=\"es-azure\"\nES_VERSION=\"5.1.2\"\nIS_DATA_NODE=1\n\n#Loop through options passed\nwhile getopts :n:mh optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    n) #set cluster name\n      CLUSTER_NAME=${OPTARG}\n      ;;\n    m) #set master mode\n      IS_DATA_NODE=0\n      ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Oracle Java\ninstall_java()\n{\n    if [ -f \"jdk-8u291-linux-x64.tar.gz\" ];\n    then\n        log \"Java already downloaded\"\n        return\n    fi\n\n    log \"Installing Java\"\n    RETRY=0\n    MAX_RETRY=5\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        log \"Retry $RETRY: downloading jdk-8u291-linux-x64.tar.gz\"\n        wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" https://download.oracle.com/otn-pub/java/jdk/8u291-b10/d7fc238d0cbf4b0dac67be84580cfb4b/jdk-8u291-linux-x64.tar.gz\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        log \"Failed to download jdk-8u291-linux-x64.tar.gz\"\n        exit 1\n    fi\n\n    tar xzf jdk-8u291-linux-x64.tar.gz -C /var/lib\n    export JAVA_HOME=/var/lib/jdk1.8.0_291\n    export PATH=$PATH:$JAVA_HOME/bin\n    log \"JAVA_HOME: $JAVA_HOME\"\n    log \"PATH: $PATH\"\n\n    java -version\n    if [ $? -ne 0 ]; then\n        log \"Java installation failed\"\n        exit 1\n    fi\n}\n\ninstall_es()\n{\n    wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | apt-key add -\n    apt-get install apt-transport-https\n    echo \"deb https://artifacts.elastic.co/packages/5.x/apt stable main\" | tee -a /etc/apt/sources.list.d/elastic-5.x.list\n    apt-get update -y\n    apt-get install -y elasticsearch\n    pushd /usr/share/elasticsearch/\n    bin/elasticsearch-plugin install x-pack --batch\n    popd\n\n    if [ ${IS_DATA_NODE} -eq 0 ];\n    then\n        apt-get install -y kibana\n        pushd /usr/share/kibana/\n        bin/kibana-plugin install x-pack\n        popd\n    fi\n}\n\nconfigure_es()\n{\n\tlog \"Update configuration\"\n\tmv /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch.bak\n\techo \"cluster.name: $CLUSTER_NAME\" >> /etc/elasticsearch/elasticsearch.yml\n\techo \"node.name: ${HOSTNAME}\" >> /etc/elasticsearch/elasticsearch.yml\n\techo \"discovery.zen.minimum_master_nodes: 2\" >> /etc/elasticsearch/elasticsearch.yml\n\techo 'discovery.zen.ping.unicast.hosts: [\"10.0.0.10\", \"10.0.0.11\", \"10.0.0.12\"]' >> /etc/elasticsearch/elasticsearch.yml\n\techo \"network.host: _site_\" >> /etc/elasticsearch/elasticsearch.yml\n\techo \"bootstrap.memory_lock: true\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"xpack.security.enabled: false\" >> /etc/elasticsearch/elasticsearch.yml\n\n\tif [ ${IS_DATA_NODE} -eq 1 ]; then\n\t    echo \"node.master: false\" >> /etc/elasticsearch/elasticsearch.yml\n\t    echo \"node.data: true\" >> /etc/elasticsearch/elasticsearch.yml\n\telse\n        echo \"node.master: true\" >> /etc/elasticsearch/elasticsearch.yml\n        echo \"node.data: false\" >> /etc/elasticsearch/elasticsearch.yml\n\tfi\n}\n\nconfigure_system()\n{\n\techo \"options timeout:1 attempts:5\" >> /etc/resolvconf/resolv.conf.d/head\n\tresolvconf -u\n\tES_HEAP=`free -m |grep Mem | awk '{if ($2/2 >31744)  print 31744;else printf \"%.0f\", $2/2;}'`\n\techo \"ES_JAVA_OPTS=\\\"-Xms${ES_HEAP}m -Xmx${ES_HEAP}m\\\"\" >> /etc/default/elasticsearch\n    echo \"JAVA_HOME=$JAVA_HOME\" >> /etc/default/elasticsearch\n    echo 'MAX_OPEN_FILES=65536' >> /etc/default/elasticsearch\n    echo 'MAX_LOCKED_MEMORY=unlimited' >> /etc/default/elasticsearch\n\n    #https://www.elastic.co/guide/en/elasticsearch/reference/current/setting-system-settings.html#systemd\n    mkdir -p /etc/systemd/system/elasticsearch.service.d\n    touch /etc/systemd/system/elasticsearch.service.d/override.conf\n    echo '[Service]' >> /etc/systemd/system/elasticsearch.service.d/override.conf\n    echo 'LimitMEMLOCK=infinity' >> /etc/systemd/system/elasticsearch.service.d/override.conf\n    sudo systemctl daemon-reload\n\n    chown -R elasticsearch:elasticsearch /usr/share/elasticsearch\n\n    if [ ${IS_DATA_NODE} -eq 0 ];\n    then\n        # Kibana\n        IP_ADDRESS=$(ip route get 8.8.8.8 | awk -F\"src \" 'NR==1{split($2,a,\" \");print a[1]}')\n        echo \"server.host: \\\"$IP_ADDRESS\\\"\" >> /etc/kibana/kibana.yml\n        echo \"elasticsearch.url: \\\"http://$IP_ADDRESS:9200\\\"\" >> /etc/kibana/kibana.yml\n        echo \"xpack.security.enabled: false\" >> /etc/kibana/kibana.yml\n        chown -R kibana:kibana /usr/share/kibana\n    else\n        # data disk\n        DATA_DIR=\"/datadisks/disk1\"\n        if ! [ -f \"vm-disk-utils-0.1.sh\" ];\n        then\n            DOWNLOAD_SCRIPT=\"https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\"\n            log \"Disk setup script not found in `pwd`, download from $DOWNLOAD_SCRIPT\"\n            wget -q $DOWNLOAD_SCRIPT\n        fi\n\n        bash ./vm-disk-utils-0.1.sh\n        if [ $? -eq 0 ] && [ -d \"$DATA_DIR\" ];\n        then\n            log \"Disk setup successful, using $DATA_DIR\"\n            chown -R elasticsearch:elasticsearch $DATA_DIR\n            echo \"DATA_DIR=$DATA_DIR\" >> /etc/default/elasticsearch\n        else\n            log \"Disk setup failed, using default data storage location\"\n        fi\n    fi\n}\n\nstart_service()\n{\n\tlog \"Starting Elasticsearch on ${HOSTNAME}\"\n    systemctl daemon-reload\n    systemctl enable elasticsearch.service\n    systemctl start elasticsearch.service\n    sleep 60\n\n    if [ `systemctl is-failed elasticsearch.service` == 'failed' ];\n    then\n        log \"Elasticsearch unit failed to start\"\n        exit 1\n    fi\n\n    if [ ${IS_DATA_NODE} -eq 0 ];\n    then\n        log \"Starting Kibana on ${HOSTNAME}\"\n        systemctl enable kibana.service\n        systemctl start kibana.service\n        sleep 10\n\n        if [ `systemctl is-failed kibana.service` == 'failed' ];\n        then\n            log \"Kibana unit failed to start\"\n            exit 1\n        fi\n    fi\n}\n\nlog \"starting elasticsearch setup\"\n\ninstall_java\ninstall_es\nconfigure_es\nconfigure_system\nstart_service\n\nlog \"completed elasticsearch setup\"\n\nexit 0\n", "num_lines": 259}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nhelp()\n{\n    echo \"\"\n    echo \"\"\n    echo \"This script installs Logstash on Ubuntu, and configures it to be used with Event Hub plugin.\"\n    echo \"Parameters:\"\n    echo \"n - Event Hub namespace\"\n\techo \"a - Event Hub shared access key name\"\n\techo \"k - Event Hub shared access key\"\n\techo \"e - Event Hub entity path\"\n\techo \"p - Event Hub partitions\"\n\techo \"i - Elasticsearch IP\"\n    echo \"\"\n    echo \"\"\n    echo \"\"\n}\n\nlog()\n{\n    echo \"$1\"\n}\n\n#Loop through options passed\nwhile getopts :hsn:a:k:e:p:i: optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    h)  #show help\n      help\n      exit 2\n      ;;\n    s)  #skip common install steps\n      SKIP_COMMON_INSTALL=\"YES\"\n      ;;\n    n)\n\t  EH_NAMESPACE=${OPTARG}\n      ;;\n    a)\n      EH_KEY_NAME=${OPTARG}\n      ;;\n    k)\n      EH_KEY=${OPTARG}\n      ;;\n    e)\n      EH_ENTITY=${OPTARG}\n      ;;\n    p)\n      EH_PARTITIONS=${OPTARG}\n      ;;\n    i)\n      ES_CLUSTER_IP=${OPTARG}\n\t  ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Logstash\n\n\nif [ -z $SKIP_COMMON_INSTALL ]\nthen\n\n    # Install Utilities\n    log \"Installing utilities.\"\n    sudo apt-get update\n    sudo apt-get -y --force-yes install python-software-properties debconf-utils\n\n    # Install Java\n    log \"Installing Java.\"\n    sudo add-apt-repository -y ppa:webupd8team/java\n    sudo apt-get update\n    echo \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | sudo debconf-set-selections\n    sudo apt-get install -y --force-yes oracle-java8-installer\n\nelse\n  log \"Skipping common install\"\nfi\n\n# Install Logstash\n# Download and install the Public Signing Key:\nlog \"Installing Logstash.\"\nwget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -\n# Add the repository definition to your /etc/apt/sources.list file:\necho \"deb http://packages.elastic.co/logstash/2.3/debian stable main\" | sudo tee -a /etc/apt/sources.list\n# Get latest package information:\nsudo apt-get update\n# Install logstash package:\nsudo apt-get -y --force-yes install logstash\n\n# Install Azure WAD Event Hub Plugin\nlog \"Installing Azure WAD Event Hub Plugin\"\nsudo /opt/logstash/bin/logstash-plugin install logstash-input-azurewadeventhub\n\n\n# Install Logstash configuration\n\nlog \"Generating Logstash Config\"\necho \"input {\" > ~/logstash.conf\necho \"  azurewadeventhub {key => '$EH_KEY' username => '$EH_KEY_NAME' eventhub => '$EH_ENTITY'  namespace => '$EH_NAMESPACE' partitions => $EH_PARTITIONS}\" >> ~/logstash.conf\necho \"}\" >> ~/logstash.conf\necho \"output {elasticsearch {hosts => ['$ES_CLUSTER_IP:9200'] index => 'wad'}}\" >> ~/logstash.conf\ncat ~/logstash.conf\n\nlog \"Installing user configuration file\"\nsudo \\cp -f ~/logstash.conf /etc/logstash/conf.d/\n\n# Configure Start\nlog \"Configure start up service\"\nsudo update-rc.d logstash defaults 95 10\nsudo service logstash start\n", "num_lines": 138}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nlog()\n{\n\techo $1\n\tlogger \"elk-simple-on-ubuntu:\" $1\n}\n\n#Loop through options passed\nwhile getopts :e:a:k:t:i:sh optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n\te)\n\t  ENCODED_LOGSTASH_CONFIG=${OPTARG}\n\t  ;;\n\ta)\n\t  STORAGE_ACCOUNT_NAME=${OPTARG}\n\t  ;;\n\tk)\n\t  STORAGE_ACCOUNT_KEY=${OPTARG}\n\t  ;;\n\tt)\n\t  STORAGE_ACCOUNT_TABLES=${OPTARG}\n\t  ;;\n\ti)\n\t  ES_CLUSTER_IP=${OPTARG}\n\t  ;;\n\ts)  #skip common install steps\n\t  SKIP_COMMON_INSTALL=\"YES\"\n\t  ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n#ELK (Simple) Install Script\nmkdir /opt/elk-simple/\ncd /opt/elk-simple/\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/diagnostics-with-elk/scripts/logstash-install-ubuntu.sh\n\n#Install Logstash\nlog \"Installing Logstash\"\nbash ./logstash-install-ubuntu.sh -e $ENCODED_LOGSTASH_CONFIG -a $STORAGE_ACCOUNT_NAME -k $STORAGE_ACCOUNT_KEY -t $STORAGE_ACCOUNT_TABLES -i $ES_CLUSTER_IP\nlog \"Installing Logstash Completed\"\n", "num_lines": 74}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# ========================================================================================\n# Microsoft patterns & practices (http://microsoft.com/practices)\n# SEMANTIC LOGGING APPLICATION BLOCK\n# ========================================================================================\n#\n# Copyright (c) Microsoft.  All rights reserved.\n# Microsoft would like to thank its contributors, a list\n# of whom are at http://aka.ms/entlib-contributors\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you\n# may not use this file except in compliance with the License. You may\n# obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n# implied. See the License for the specific language governing permissions\n# and limitations under the License.\n#\n\nhelp()\n{\n    echo \"\"\n    echo \"\"\n    echo \"This script installs Logstash 1.4.2 on Ubuntu, and configures it to be used with user plugins/configurations\"\n    echo \"Parameters:\"\n    echo \"e - The encoded configuration string.\"\n    echo \"\"\n    echo \"\"\n    echo \"\"\n}\n\nlog()\n{\n    echo \"$1\"\n}\n\n#Loop through options passed\nwhile getopts :e:hsa:k:t:i: optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    s)  #skip common install steps\n      SKIP_COMMON_INSTALL=\"YES\"\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    e)  #set the encoded configuration string\n      log \"Setting the encoded configuration string\"\n      CONF_FILE_ENCODED_STRING=\"${OPTARG}\"\n      ;;\n    a)\n      STORAGE_ACCOUNT_NAME=${OPTARG}\n      ;;\n    k)\n      STORAGE_ACCOUNT_KEY=${OPTARG}\n      ;;\n    t)\n      STORAGE_ACCOUNT_TABLES=${OPTARG}\n      ;;\n    i)\n      ES_CLUSTER_IP=${OPTARG}\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Logstash\n\nexport DEBIAN_FRONTEND=noninteractive\n\nif [ -z $SKIP_COMMON_INSTALL ]\nthen\n\n    # Install Utilities\n    log \"Installing utilities.\"\n    apt-get update\n    apt-get -y --force-yes install python-software-properties debconf-utils\n\n    # Install Java\n    log \"Installing Java.\"\n    add-apt-repository -y ppa:webupd8team/java\n    apt-get update\n    echo \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | debconf-set-selections\n    apt-get install -y --force-yes oracle-java8-installer\n\nelse\n  log \"Skipping common install\"\nfi\n\n# Install Logstash\n# Download and install the Public Signing Key:\nlog \"Installing Logstash.\"\nwget -qO - https://packages.elastic.co/GPG-KEY-elasticsearch | apt-key add -\n# Add the repository definition to your /etc/apt/sources.list file:\necho \"deb http://packages.elastic.co/logstash/2.3/debian stable main\" | tee -a /etc/apt/sources.list\n# Get latest package information:\napt-get update\n# Install logstash package:\napt-get -y --force-yes install logstash\n\n# Install Azure WAD Table Plugin\nlog \"Installing Azure WAD Table Plugin\"\n/opt/logstash/bin/logstash-plugin install logstash-input-azurewadtable\n\n\n# Install User Configuration from encoded string\nif [ ! $CONF_FILE_ENCODED_STRING = \"na\" ]\nthen\n  log \"Decoding configuration string\"\n  log \"$CONF_FILE_ENCODED_STRING\"\n  echo $CONF_FILE_ENCODED_STRING > logstash.conf.encoded\n  DECODED_STRING=$(base64 -d logstash.conf.encoded)\n  log \"$DECODED_STRING\"\n  echo $DECODED_STRING > ~/logstash.conf\nelse\n    log \"Generating Logstash Config\"\n    echo \"input {\" > ~/logstash.conf\n    log \"Using specified table names\"\n    TABLE_ARRAY=$(echo $STORAGE_ACCOUNT_TABLES | tr \";\" \"\\n\")\n    for TABLE in $TABLE_ARRAY\n        do\n        echo \"azurewadtable {account_name => '$STORAGE_ACCOUNT_NAME' access_key => '$STORAGE_ACCOUNT_KEY' table_name => '$TABLE'}\" >> ~/logstash.conf\n    done\n    echo \"}\" >> ~/logstash.conf\n    echo \"output {elasticsearch {hosts => ['$ES_CLUSTER_IP:9200'] index => 'wad'}}\" >> ~/logstash.conf\n    cat ~/logstash.conf\nfi\n\nlog \"Installing user configuration file\"\n\\cp -f ~/logstash.conf /etc/logstash/conf.d/\n\n# Configure Start\nlog \"Configure start up service\"\nupdate-rc.d logstash defaults 95 10\nservice logstash start\n", "num_lines": 146}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# print commands and arguments as they are executed\nset -x\n\necho \"initializing (++)Ethereum installation\"\ndate\nps axjf\n\n#############\n# Parameters\n#############\n\nAZUREUSER=$1\nHOMEDIR=\"/home/$AZUREUSER\"\nVMNAME=`hostname`\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOMEDIR\"\necho \"vmname: $VMNAME\"\n\n#####################\n# setup the Azure CLI\n#####################\ntime sudo npm install azure-cli -g\ntime sudo update-alternatives --install /usr/bin/node nodejs /usr/bin/nodejs 100\n\n####################\n# Setup (++)Ethereum\n####################\nsudo add-apt-repository ppa:ethereum/ethereum-qt\nsudo add-apt-repository ppa:ethereum/ethereum\nsudo apt-get update\nsudo apt-get install cpp-ethereum\n\n# Fetch Genesis and Private Key\ncd $HOMEDIR\n\ndate\necho \"completed (++)Ethereum install $$\"\n", "num_lines": 40}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport DEBIAN_FRONTEND=noninteractive\n\napt-get update\n\napt-get -y install \\\n    linux-image-extra-$(uname -r) \\\n    linux-image-extra-virtual\n\napt-get -y install apt-transport-https ca-certificates curl software-properties-common\n\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\n\nsudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\"\n\napt-get update\napt-get -y install docker-ce\n\ndocker run -d --env MODE=standalone -p 80:8181 -p 8555:8555 -p 8080:8080 ethercamp/ide", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# print commands and arguments as they are executed\nset -x\n\necho \"initializing geth installation\"\ndate\nps axjf\n\n#############\n# Parameters\n#############\n\nAZUREUSER=$1\nHOMEDIR=\"/home/$AZUREUSER\"\nVMNAME=`hostname`\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOMEDIR\"\necho \"vmname: $VMNAME\"\n\n#####################\n# setup the Azure CLI\n#####################\ntime sudo npm install azure-cli -g\ntime sudo update-alternatives --install /usr/bin/node nodejs /usr/bin/nodejs 100\n\n####################\n# Setup Geth\n####################\ntime sudo apt-get -y git\ntime sudo apt-get install -y software-properties-common\ntime sudo add-apt-repository -y ppa:ethereum/ethereum\ntime sudo apt-get update\ntime sudo apt-get install -y ethereum\n\n####################\n# Install sol compiler\n####################\ntime sudo add-apt-repository ppa:ethereum/ethereum -y\ntime sudo apt-get update\ntime sudo apt-get install solc -y\n\n# Fetch Genesis and Private Key\ncd $HOMEDIR\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/go-ethereum-on-ubuntu/genesis.json\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/go-ethereum-on-ubuntu/priv_genesis.key\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/go-ethereum-on-ubuntu/start-private-blockchain.sh\nwget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/go-ethereum-on-ubuntu/GuestBook.sol\n\ndate\ngeth init genesis.json\necho \"completed geth install $$\"\n", "num_lines": 53}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngeth --maxpeers 0 --networkid 101010101  --rpc --rpccorsdomain \"*\" console\n", "num_lines": 4}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n# -----------------------------------------------------------------------------\n# PURPOSE\n\n# This script will setup expanse and all of its dependencies. It is primarily meant\n# for running on cloud providers as a setup script.\n\n# Specifically the script will install:\n#   * go+git (useful for quick updates of the expanse tool)\n#   * expanse\n\n# The script assumes that it will be ran by a root user or a user with sudo\n# privileges on the node. Note that it does not currently check that it has\n# elevate privileges on the node.\n\n# Note that the script also assumes that the user will be a bash user.\n\n# -----------------------------------------------------------------------------\n# LICENSE\n\n# The MIT License (MIT)\n# Copyright (c) 2016-Present Expanse Official.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n# IN THE SOFTWARE.\n\n# -----------------------------------------------------------------------------\n# REQUIREMENTS\n\n# Ubuntu\n\n# -----------------------------------------------------------------------------\n# USAGE\n\n# setup.sh USER [SERVICESTOSTART] [CHAINSTOSTART]\n\n# -----------------------------------------------------------------------------\n# Set defaults\n\nexpanseUser=$1\n# -----------------------------------------------------------------------------\n# Defaults\n\nGOVERSION=\"1.5\"\nNODEVERSION=\"4\"\n\n# -----------------------------------------------------------------------------\n# Install dependencies\n\necho \"Hello there! I'm the marmot that installs expanse.\"\necho\necho\necho \"Grabbing necessary dependencies\"\nexport DEBIAN_FRONTEND=noninteractive\ncurl -sSL https://deb.nodesource.com/setup_\"$NODEVERSION\".x | sudo -E bash - &>/dev/null\nsudo apt-get install -y git mercurial binutils bison gcc make libgmp3-dev build-essential &>/dev/null\ncurl -sSL https://storage.googleapis.com/golang/go\"$GOVERSION\".linux-amd64.tar.gz | sudo tar -C /usr/local -xzf - &>/dev/null\necho \"Dependencies Installed.\"\necho\necho\n\n####################\n# Install sol compiler\n####################\ntime sudo add-apt-repository ppa:ethereum/ethereum -y\ntime sudo apt-get update\ntime sudo apt-get install solc -y\n# -----------------------------------------------------------------------------\n# Install expanse\n\necho \"Setting up Go for the user\"\nmkdir --parents $HOME/go\nexport GOPATH=$HOME/go\nexport PATH=$HOME/go/bin:/usr/local/go/bin:$PATH\necho \"export GOROOT=/usr/local/go\" >> $HOME/.bashrc\necho \"export GOPATH=$HOME/go\" >> $HOME/.bashrc\necho \"export PATH=$HOME/go/bin:/usr/local/go/bin:$PATH\" >> $HOME/.bashrc\necho \"Finished Setting up Go.\"\necho\necho\necho \"Version Information\"\necho\ngo version\necho\necho\necho \"Building expanse.\"\ngit clone https://github.com/expanse-project/go-expanse.git\ncd go-expanse\nmake gexp\ncp build/bin/gexp /usr/bin/gexp\n\n# -------------------------------------------------------------------------------\n# Finish\n\necho\necho \"expanse Installed!\"\n", "num_lines": 112}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ngexp --maxpeers 100 --rpc --rpccorsdomain \"*\" console\n", "num_lines": 4}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 6.5\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of powershell script or runbook or Azure Resource Manager CRP template.\n\nNODENAME=$(hostname)\nPEERNODEPREFIX=${1}\nPEERNODEIPPREFIX=${2}\nVOLUMENAME=${3}\nNODEINDEX=${4}\nNODECOUNT=${5}\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=128\n\nRAIDDISK=\"/dev/md127\"\nRAIDPARTITION=\"/dev/md127p1\"\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ncreate_raid0_ubuntu() {\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        wget --no-cache http://mirrors.cat.pdx.edu/ubuntu/pool/main/m/mdadm/mdadm_3.2.5-5ubuntu4_amd64.deb\n        dpkg -i mdadm_3.2.5-5ubuntu4_amd64.deb\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ncreate_raid0_centos() {\n    echo \"Creating raid0\"\n    yes | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n    ls \"${MOUNTPOINT}\"\n    if [ ${?} -eq 0 ]\n    then\n        return\n    fi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT -gt 1 ];\n    then\n        if [ $iscentos -eq 0 ];\n        then\n            create_raid0_centos\n        elif [ $isubuntu -eq 0 ];\n        then\n            create_raid0_ubuntu\n        fi\n        do_partition ${RAIDDISK}\n        PARTITION=\"${RAIDPARTITION}\"\n    else\n        DISK=\"${DISKS[0]}\"\n        do_partition ${DISK}\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nopen_ports() {\n    index=0\n    while [ $index -lt $NODECOUNT ]; do\n        if [ $index -ne $NODEINDEX ]; then\n            iptables -I INPUT -p all -s \"${PEERNODEIPPREFIX}${index}\" -j ACCEPT\n            echo \"${PEERNODEIPPREFIX}${index}    ${PEERNODEPREFIX}${index}\" >> /etc/hosts\n        else\n            echo \"127.0.0.1    ${PEERNODEPREFIX}${index}\" >> /etc/hosts\n        fi\n        let index++\n    done\n    iptables-save\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=disabled/I' /etc/selinux/config\n    setenforce 0\n}\n\nactivate_secondnic_centos() {\n    if [ -n \"$SECONDNIC\" ];\n    then\n        cp /etc/sysconfig/network-scripts/ifcfg-eth0 \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        sed -i \"s/^DEVICE=.*/DEVICE=${SECONDNIC}/I\" \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        defaultgw=$(ip route show |sed -n \"s/^default via //p\")\n        declare -a gateway=(${defaultgw// / })\n        sed -i \"\\$aGATEWAY=${gateway[0]}\" /etc/sysconfig/network\n        service network restart\n    fi\n}\n\nactivate_secondnic_ubuntu() {\n    if [ -n \"$SECONDNIC\" ];\n    then\n        echo \"\" >> /etc/network/interfaces\n        echo \"auto $SECONDNIC\" >> /etc/network/interfaces\n        echo \"iface $SECONDNIC inet dhcp\" >> /etc/network/interfaces\n        defaultgw=$(ip route show |sed -n \"s/^default via //p\")\n        declare -a gateway=(${defaultgw// / })\n        echo \"\" >> /etc/network/interfaces\n        echo \"post-up ip route add default via $gateway\" >> /etc/network/interfaces\n        /etc/init.d/networking restart\n    fi\n}\n\nconfigure_network() {\n    open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        activate_secondnic_centos\n        disable_selinux_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        activate_secondnic_ubuntu\n        disable_apparmor_ubuntu\n    fi\n}\n\ninstall_glusterfs_ubuntu() {\n    dpkg -l | grep glusterfs\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n\n    if [ ! -e /etc/apt/sources.list.d/gluster* ];\n    then\n        echo \"adding gluster ppa\"\n        apt-get  -y install python-software-properties\n        apt-add-repository -y ppa:gluster/glusterfs-3.7\n        apt-get -y update\n    fi\n\n    echo \"installing gluster\"\n    apt-get -y install glusterfs-server\n\n    return\n}\n\ninstall_glusterfs_centos() {\n    yum list installed glusterfs-server\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n\n    if [ ! -e /etc/yum.repos.d/epel.repo ];\n    then\n        echo \"Installing extra packages for enterprise linux\"\n        wget https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\n        rpm -Uvh ./epel-release-latest-6*.rpm\n        rm ./epel-release-latest-6*.rpm\n        yum -y update\n    fi\n\n    echo \"installing gluster\"\n    wget --no-cache http://download.gluster.org/pub/gluster/glusterfs/LATEST/EPEL.repo/glusterfs-epel.repo\n    mv glusterfs-epel.repo  /etc/yum.repos.d/\n    yum -y update\n    yum -y install glusterfs-cli glusterfs-geo-replication glusterfs-fuse glusterfs-server glusterfs\n}\n\nconfigure_gluster() {\n    if [ $iscentos -eq 0 ];\n    then\n        /etc/init.d/glusterd status\n        if [ ${?} -ne 0 ];\n        then\n            install_glusterfs_centos\n        fi\n        /etc/init.d/glusterd start\n    elif [ $isubuntu -eq 0 ];\n    then\n        /etc/init.d/glusterfs-server status\n        if [ ${?} -ne 0 ];\n        then\n            install_glusterfs_ubuntu\n        fi\n        /etc/init.d/glusterfs-server start\n    fi\n\n    GLUSTERDIR=\"${MOUNTPOINT}/brick\"\n    ls \"${GLUSTERDIR}\"\n    if [ ${?} -ne 0 ];\n    then\n        mkdir \"${GLUSTERDIR}\"\n    fi\n\n    if [ $NODEINDEX -lt $(($NODECOUNT-1)) ];\n    then\n        return\n    fi\n\n    allNodes=\"${NODENAME}:${GLUSTERDIR}\"\n    retry=10\n    failed=1\n    while [ $retry -gt 0 ] && [ $failed -gt 0 ]; do\n        failed=0\n        index=0\n        echo retrying $retry >> /tmp/error\n        while [ $index -lt $(($NODECOUNT-1)) ]; do\n            ping -c 3 \"${PEERNODEPREFIX}${index}\" > /tmp/error\n            gluster peer probe \"${PEERNODEPREFIX}${index}\" >> /tmp/error\n            if [ ${?} -ne 0 ];\n            then\n                failed=1\n                echo \"gluster peer probe ${PEERNODEPREFIX}${index} failed\"\n            fi\n            gluster peer status >> /tmp/error\n            gluster peer status | grep \"${PEERNODEPREFIX}${index}\" >> /tmp/error\n            if [ ${?} -ne 0 ];\n            then\n                failed=1\n                echo \"gluster peer status ${PEERNODEPREFIX}${index} failed\"\n            fi\n            if [ $retry -eq 10 ]; then\n                allNodes=\"${allNodes} ${PEERNODEPREFIX}${index}:${GLUSTERDIR}\"\n            fi\n            let index++\n        done\n        sleep 30\n        let retry--\n    done\n\n    sleep 60\n    gluster volume create ${VOLUMENAME} rep 2 transport tcp ${allNodes} 2>> /tmp/error\n    gluster volume info 2>> /tmp/error\n    gluster volume start ${VOLUMENAME} 2>> /tmp/error\n}\n\nallow_passwordssh() {\n    grep -q '^PasswordAuthentication yes' /etc/ssh/sshd_config\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    sed -i \"s/^#PasswordAuthentication.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n    sed -i \"s/^PasswordAuthentication no.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n    if [ $iscentos -eq 0 ];\n    then\n        /etc/init.d/sshd reload\n    elif [ $isubuntu -eq 0 ];\n    then\n        /etc/init.d/ssh reload\n    fi\n}\n\ncheck_os\n\n# temporary workaround form CRP\nallow_passwordssh\n\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_gluster\nfi\n\n", "num_lines": 360}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script parameters from arguments\nconfigfile=$1\nHostIP=$(dig +short myip.opendns.com @resolver1.opendns.com)\n\n\napt-get update\napt-get install software-properties-common -y\napt-add-repository ppa:ansible/ansible -y\napt-get update\napt-get install ansible -y\napt-get install unzip -y\n\ncd /home/\n\nif [ -e Configfiles.* ];\nthen\n  if [ -d /home/Configfiles ];\n  then\n        rm -rf Configfiles.*\n\trm -rf /home/Configfiles\n\techo \"directory delete\"\n  fi\nfi\nwget $configfile\nunzip Configfiles.zip -d /home/Configfiles/\n\n\nHOME=/root ansible-playbook /home/Configfiles/ansible/docker_install.yml  --extra-vars \"HostIP=$HostIP\" -vvv\n\n\n", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# This script waits for MariaDB to be ready to accept connections\n\n# Parameters\nIMAGE_NAME=\"mariadb:10.1\"\nCONTAINER_NAME=\"some-mariadb\"\n\n# Wait at least 60 seconds\nsleep 60\n\n# Keep polling database until ready\nwhile ! docker run --rm --link $CONTAINER_NAME $IMAGE_NAME mysqladmin ping -h $CONTAINER_NAME --silent; do\n    sleep 5\ndone\n\n# Wait 5 more seconds before sending the green light\nsleep 5\n", "num_lines": 19}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Parameters\nIMAGE_NAME=\"mariadb:10.1\"\nCONTAINER_NAME=\"some-mariadb\"\nGUACAMOLE_IMAGE_NAME=\"glyptodon/guacamole:latest\"\nMYSQL_ROOT_PASSWORD=\"my-secret-pw\"\nMYSQL_USER=\"guacamole_user\"\nMYSQL_DATABASE=\"guacamole_db\"\nMYSQL_PASSWORD=\"burrito-guacamole-extra-1dollar\"\n\n# Remove pre-existing containers\ndocker stop $CONTAINER_NAME || true\ndocker rm $CONTAINER_NAME || true\n\n# Pull the latest version of the Docker image\ndocker pull $IMAGE_NAME\n\n# Check if the MySQL database has been prepared already\nif [ ! -e /mnt/data/mysql/mysql ]; then\n    # Initial database contents: generate them from the guacamole image\n    TMP_SQL_FILE=/mnt/resource/initdb.sql\n    rm -rf $TMP_SQL_FILE $TMP_SQL_FILE.tmp\n    docker run --rm $GUACAMOLE_IMAGE_NAME /opt/guacamole/bin/initdb.sh --mysql > $TMP_SQL_FILE\n\n    # Prepend database name to SQL query\n    echo \"USE $MYSQL_DATABASE; \" | cat - $TMP_SQL_FILE > $TMP_SQL_FILE.tmp \\\n        && mv $TMP_SQL_FILE.tmp $TMP_SQL_FILE\n\n    docker run \\\n        --name $CONTAINER_NAME \\\n        -e MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD \\\n        -e MYSQL_DATABASE=$MYSQL_DATABASE \\\n        -e MYSQL_USER=$MYSQL_USER \\\n        -e MYSQL_PASSWORD=$MYSQL_PASSWORD \\\n        -v /mnt/data/mysql:/var/lib/mysql \\\n        -v $TMP_SQL_FILE:/docker-entrypoint-initdb.d/guacamole.sql \\\n        $IMAGE_NAME\nelse\n    # Start Docker container\n    docker run \\\n        --name $CONTAINER_NAME \\\n        -v /mnt/data/mysql:/var/lib/mysql \\\n        $IMAGE_NAME\nfi\n\n# Interactive MySQL session\n# docker run --rm --link some-mariadb -it mariadb:10.1 mysql -h some-mariadb -u root -pmy-secret-pw\n", "num_lines": 49}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nwhile getopts \"r:s\" opt; do\n    case $opt in\n        r)\n            roles=$OPTARG # coma seperated roles\n        ;;\n        s)\n            subscription=$OPTARG #optional subscription ID\n        ;;\n    esac\ndone\n\n[[ $# -eq 0 || -z $roles ]] && { echo \"Usage: $0 -r <comma seperated role(s)>\"; exit 1; }\n\n# install jq if not installed\nif ! command -v jq &> /dev/null\nthen\n    echo \"jq command not found. attempting to download jq binary\"\n    pth=$(pwd)\n    export PATH=$PATH:$pth\n    if [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n        curl -L https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -o jq\n    elif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n        curl -L https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64 -o jq\n    else\n        echo \"Unsupported OS type. Exiting...\"\n        exit 1\n    fi\n    chmod +x jq\nfi\n\nIFS=','; rolesArr=($roles); unset IFS;\nrole1=\"${rolesArr[0]}\"\nsubscriptionId=$( az account show -o json | jq -r '.id' )\n\n# Create service principal with first\nspJson=$(az ad sp create-for-rbac --role=\"$role1\" --scopes=\"/subscriptions/$subscriptionId\")\naadClientId=$(echo $spJson | jq -r '.appId')\naadClientSecret=$(echo $spJson | jq -r '.password')\n\n# Get object object id\nobjectId=$( az ad sp list --filter \"appId eq '$aadClientId'\" | jq '.[0].objectId' -r )\n\n# assign roles \nfor role in \"${rolesArr[@]}\"\ndo\n    echo \"Creating role $role\"\n    az role assignment create --role \"$role\" --assignee-object-id $objectId\ndone\n\necho \" Creation Complete \"\n\necho \" - ClientID => $aadClientId\"\necho \" - ClientSecret => $aadClientSecret\"\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\n    STORAGE_TYPE_KEY=\"storageVendor\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\n    STORAGE_TYPE_KEY=\"storageVendor\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\n    STORAGE_TYPE_KEY=\"storageClass\"\nfi\nSTORAGE_TYPE_VALUE=$STORAGEOPTION\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n\n# Spark (Analytics Engine) subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-analyticsengine-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  labels:\n    app.kubernetes.io/instance: ibm-cpd-ae-operator-subscription\n    app.kubernetes.io/managed-by: ibm-cpd-ae-operator\n    app.kubernetes.io/name: ibm-cpd-ae-operator-subscription\n  name: ibm-cpd-ae-operator-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n    channel: $CHANNEL\n    installPlanApproval: Automatic\n    name: analyticsengine-operator\n    source: ibm-operator-catalog\n    sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-analyticsengine-cr.yaml <<EOF\napiVersion: ae.cpd.ibm.com/v1\nkind: AnalyticsEngine\nmetadata:\n  name: analyticsengine-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  $STORAGE_TYPE_KEY: $STORAGE_TYPE_VALUE\n  license:\n    accept: true\n    license: Enterprise\nEOF\"\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-analyticsengine-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-ae-operator pod status\n\npodname=\"ibm-cpd-ae-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-spark cr\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-analyticsengine-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"AnalyticsEngine\"\nCRNAME=\"analyticsengine-cr\"\nSERVICE_STATUS=\"analyticsengineStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 136}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# CCS subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-ccs-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  annotations: {}\n  name: ibm-cpd-ccs-operator\n  namespace: $OPERATORNAMESPACE\nspec:\n  channel: $CHANNEL\n  config:\n    resources: {}\n  installPlanApproval: Automatic\n  name: ibm-cpd-ccs\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-ccs-cr.yaml <<EOF\napiVersion: ccs.cpd.ibm.com/v1beta1\nkind: CCS\nmetadata:\n  name: ccs-cr\n  namespace: $CPDNAMESPACE\nspec:\n  size: \\\"small\\\"\n  REPLACE_VENDOR_OR_CLASS: REPLACE_SC\n  license:\n    accept: true\n    license: Enterprise\n  docker_registry_prefix: \\\"cp.icr.io/cp/cpd\\\"\nEOF\"\n\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-ccs-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-ccs-operator pod status\n\npodname=\"ibm-cpd-ccs-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-ccs cr\nif [[ $STORAGEOPTION == \"nfs\" ]];then \nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_VENDOR_OR_CLASS#storageClass#g $CPDTEMPLATES/ibm-ccs-cr.yaml\"\nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_SC#nfs#g $CPDTEMPLATES/ibm-ccs-cr.yaml\"\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then \nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_VENDOR_OR_CLASS#storageVendor#g $CPDTEMPLATES/ibm-ccs-cr.yaml\"\nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_SC#$STORAGEVENDOR_VALUE#g $CPDTEMPLATES/ibm-ccs-cr.yaml\"\nfi\n\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-ccs-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"CCS\"\nCRNAME=\"ccs-cr\"\nSERVICE_STATUS=\"ccsStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 140}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# CDE operator and CR creation \n\n# Download cde case package. \nrunuser -l $SUDOUSER -c \"wget https://raw.githubusercontent.com/IBM/cloud-pak/master/repo/case/ibm-cde-2.0.0.tgz -P $CPDTEMPLATES -A 'ibm-cde-2.0.0.tgz'\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-cde-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  labels:\n    app.kubernetes.io/instance: ibm-cde-operator-subscription\n    app.kubernetes.io/managed-by: ibm-cde-operator\n    app.kubernetes.io/name: ibm-cde-operator-subscription\n  name: ibm-cde-operator-subscription\n  namespace: ${OPERATORNAMESPACE}\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-cde-operator\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $OPERATORNAMESPACE; oc create -f $CPDTEMPLATES/ibm-cde-sub.yaml\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for operator to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check ibm-cpd-ae-operator pod status\n\npodname=\"ibm-cde-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-cde cr\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-cde-cr.yaml <<EOF\napiVersion: cde.cpd.ibm.com/v1\nkind: CdeProxyService\nmetadata:\n  name: cde-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: $VERSION\n  size: \\\"small\\\"\n  namespace: \\\"$CPDNAMESPACE\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  cert_manager_enabled: true\n  license:\n    accept: true\n    license: Enterprise\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-cde-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"CdeProxyService\"\nCRNAME=\"cde-cr\"\nSERVICE_STATUS=\"cdeStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 136}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n\n# db2aaservice operator and CR creation \n\n#runuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-db2aaservice-catalogsource.yaml <<EOF\n#apiVersion: operators.coreos.com/v1alpha1\n#kind: CatalogSource\n#metadata:\n#  name: ibm-db2aaservice-cp4d-operator-catalog\n#  namespace: openshift-marketplace\n#spec:\n#  displayName: IBM Db2aaservice CP4D Catalog\n#  image: icr.io/cpopen/ibm-db2aaservice-cp4d-operator-catalog@sha256:a0d9b6c314193795ec1918e4227ede916743381285b719b3d8cfb05c35fec071\n#  imagePullPolicy: Always\n#  publisher: IBM\n#  sourceType: grpc\n#  updateStrategy:\n#    registryPoll:\n#      interval: 45m\n#EOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-db2aaservice-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: ibm-db2aaservice-cp4d-operator\n  namespace: $OPERATORNAMESPACE\nspec:\n  channel: $CHANNEL\n  name: ibm-db2aaservice-cp4d-operator\n  installPlanApproval: Automatic\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-db2aaservice-cr.yaml <<EOF\napiVersion: databases.cpd.ibm.com/v1\nkind: Db2aaserviceService\nmetadata:\n  name: db2aaservice-cr\n  namespace: $CPDNAMESPACE\nspec:\n  storageClass: $STORAGECLASS_VALUE\n  version: \\\"$VERSION\\\"\n  license:\n    accept: true\n    license: \\\"Enterprise\\\"\nEOF\"\n\n# Create Subscription. \n\n#runuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-db2aaservice-catalogsource.yaml\"\n#runuser -l $SUDOUSER -c \"echo 'Sleeping 2m for catalogsource to be created'\"\n#runuser -l $SUDOUSER -c \"sleep 2m\"\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-db2aaservice-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for sub to be created'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for operator to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n\n\n# Check ibm-db2aaservice-cp4d-operator-controller-manager pod status\n\npodname=\"ibm-db2aaservice-cp4d-operator-controller-manager\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-db2aaservice cr\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-db2aaservice-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"Db2aaserviceService\"\nCRNAME=\"db2aaservice-cr\"\nSERVICE_STATUS=\"db2aaserviceStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 154}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# DB2u Catalogsource\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-db2u-cs.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: CatalogSource\nmetadata:\n  name: ibm-db2uoperator-catalog\n  namespace: openshift-marketplace\nspec:\n  sourceType: grpc\n  image: docker.io/ibmcom/ibm-db2uoperator-catalog:latest\n  imagePullPolicy: Always\n  displayName: IBM Db2U Catalog\n  publisher: IBM\n  updateStrategy:\n    registryPoll:\n      interval: 45m\nEOF\"\n\n\n## Creating CS and sub\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-db2u-cs.yaml\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 66}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# DMC Subscription\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-dmc-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: ibm-dmc-operator-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-dmc-operator\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $OPERATORNAMESPACE; oc create -f $CPDTEMPLATES/ibm-dmc-sub.yaml\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for operator to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check ibm-cpd-ae-operator pod status\n\npodname=\"ibm-dmc-controller-manager\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-dmc cr\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-dmc-cr.yaml <<EOF\napiVersion: dmc.databases.ibm.com/v1\nkind: Dmcaddon\nmetadata:\n  name: dmcaddon-cr\n  namespace: $CPDNAMESPACE\nspec:\n  namespace: $CPDNAMESPACE\n  storageClass: $STORAGECLASS_VALUE\n  pullPrefix: cp.icr.io/cp/cpd\n  version: \\\"$VERSION\\\"\n  license:\n    accept: true\n    license: Standard \nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-dmc-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"dmcaddon\"\nCRNAME=\"dmcaddon-cr\"\nSERVICE_STATUS=\"dmcAddonStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 128}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\nrunuser -l $SUDOUSER -c \"oc login \\\"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\\\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\"\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# DV operator and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-dv-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: ibm-dv-operator-catalog-subscription\n  namespace: $OPERATORNAMESPACE        # Pick the project that contains the Cloud Pak for Data operator\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-dv-operator\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $OPERATORNAMESPACE; oc create -f $CPDTEMPLATES/ibm-dv-sub.yaml\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for DV Subscription to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for operator to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check ibm-dv-operator pod status\n\npodname=\"ibm-dv-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-DV cr\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-dv-cr.yaml <<EOF\napiVersion: db2u.databases.ibm.com/v1\nkind: DvService\nmetadata:\n  name: dv-service-cr\n  namespace: $CPDNAMESPACE\nspec:\n  license:\n    accept: true\n    license: Enterprise\n  version: $VERSION\n  size: \"small\"\n  docker_registry_prefix: cp.icr.io/cp/cpd\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc project $OPERATORNAMESPACE; oc create -f $CPDTEMPLATES/ibm-dv-cr.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for DV CR to be created'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n\n# Check CR Status\n\nSERVICE=\"DvService\"\nCRNAME=\"dv-service-cr\"\nSERVICE_STATUS=\"reconcileStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 135}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\nrunuser -l $SUDOUSER -c \"mkdir -p $INSTALLERHOME\"\nrunuser -l $SUDOUSER -c \"mkdir -p $OCPTEMPLATES\"\nrunuser -l $SUDOUSER -c \"mkdir -p $CPDTEMPLATES\"\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/kubecredentials <<EOF\nusername: $OPENSHIFTUSER\npassword: $OPENSHIFTPASSWORD\nEOF\"\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n\n\nrunuser -l $SUDOUSER -c \"oc login \\\"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\\\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\"\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n\n#CPD Config\n\n#runuser -l $SUDOUSER -c \"wget https://github.com/IBM/cloud-pak-cli/releases/download/v3.8.0/cloudctl-linux-amd64.tar.gz -O $CPDTEMPLATES/cloudctl-linux-amd64.tar.gz\"\n#runuser -l $SUDOUSER -c \"https://github.com/IBM/cloud-pak-cli/releases/download/v3.8.0/cloudctl-linux-amd64.tar.gz.sig -O $CPDTEMPLATES/cloudctl-linux-amd64.tar.gz.sig\"\n#runuser -l $SUDOUSER -c \"cd $CPDTEMPLATES && sudo tar -xvf cloudctl-linux-amd64.tar.gz -C /usr/local/bin\"\n#runuser -l $SUDOUSER -c \"chmod +x /usr/local/bin/cloudctl-linux-amd64\"\n#runuser -l $SUDOUSER -c \"sudo mv /usr/local/bin/cloudctl-linux-amd64 /usr/local/bin/cloudctl\"\n\n# Service Account Token for CPD installation\nrunuser -l $SUDOUSER -c \"oc new-project $CPDNAMESPACE\"\nrunuser -l $SUDOUSER -c \"oc create serviceaccount cpdtoken\"\nrunuser -l $SUDOUSER -c \"oc policy add-role-to-user admin system:serviceaccount:$CPDNAMESPACE:cpdtoken\"\n\n# Service Account Token for CPD installation\nrunuser -l $SUDOUSER -c \"oc new-project $OPERATORNAMESPACE\"\nrunuser -l $SUDOUSER -c \"oc create serviceaccount cpdtoken\"\nrunuser -l $SUDOUSER -c \"oc policy add-role-to-user admin system:serviceaccount:$OPERATORNAMESPACE:cpdtoken\"\n\n## Installing jq\nrunuser -l $SUDOUSER -c \"wget https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 -O  $CPDTEMPLATES/jq\"\nrunuser -l $SUDOUSER -c \"sudo mv $CPDTEMPLATES/jq /usr/local/bin\"\nrunuser -l $SUDOUSER -c \"sudo chmod +x /usr/local/bin/jq\"\n\n\n# Update global pull secret and sysctl changes: \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/sysctl-worker.yaml <<EOF\napiVersion: machineconfiguration.openshift.io/v1\nkind: KubeletConfig\nmetadata:\n  name: db2u-kubelet\nspec:\n  machineConfigPoolSelector:\n    matchLabels:\n      db2u-kubelet: sysctl\n  kubeletConfig:\n    systemReserved:\n      cpu: 1000m\n      memory: 1Gi\n    allowedUnsafeSysctls:\n      - \\\"kernel.msg*\\\"\n      - \\\"kernel.shm*\\\"\n      - \\\"kernel.sem\\\"\nEOF\"\n\n\nexport ENTITLEMENT_USER=cp\nexport ENTITLEMENT_KEY=$APIKEY\npull_secret=$(echo -n \"$ENTITLEMENT_USER:$ENTITLEMENT_KEY\" | base64 -w0)\noc get secret/pull-secret -n openshift-config -o jsonpath='{.data.\\.dockerconfigjson}' | base64 -d > $OCPTEMPLATES/dockerconfig.json\nsed -i -e 's|:{|:{\"cp.icr.io\":{\"auth\":\"'$pull_secret'\"\\},|' $OCPTEMPLATES/dockerconfig.json\noc set data secret/pull-secret -n openshift-config --from-file=.dockerconfigjson=$OCPTEMPLATES/dockerconfig.json\n\nrunuser -l $SUDOUSER -c \"oc label machineconfigpool.machineconfiguration.openshift.io worker db2u-kubelet=sysctl\"\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/sysctl-worker.yaml\"\nrunuser -l $SUDOUSER -c \"sleep 3m\"\n\n# Check nodestatus if they are ready.\n\nwhile true; do\n    node_status=$(oc get nodes | grep -E \"SchedulingDisabled|NotReady\")\n    if [[ -z $node_status ]]; then\n        echo -e \"\\n******All nodes are running now.******\"\n        break\n    fi\n        echo -e \"\\n******Waiting for nodes to get ready.******\"\n        oc get nodes --no-headers | awk '{print $1 \" \" $2}'\n        echo -e \"\\n******sleeping for 60Secs******\"\n        sleep 60\n    done\n\n# CPD Bedrock and Platform operator install: \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-operator-catalogsource.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: CatalogSource\nmetadata:\n  name: ibm-operator-catalog\n  namespace: openshift-marketplace\nspec:\n  displayName: \\\"IBM Operator Catalog\\\" \n  publisher: IBM\n  sourceType: grpc\n  image: icr.io/cpopen/ibm-operator-catalog:latest\n  updateStrategy:\n    registryPoll:\n      interval: 45m\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/db2u-catalogsource.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: CatalogSource\nmetadata:\n  name: ibm-db2uoperator-catalog\n  namespace: openshift-marketplace\nspec:\n  sourceType: grpc\n  image: docker.io/ibmcom/ibm-db2uoperator-catalog:latest\n  imagePullPolicy: Always\n  displayName: IBM Db2U Catalog\n  publisher: IBM\n  updateStrategy:\n    registryPoll:\n      interval: 45m\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-operator-og.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha2\nkind: OperatorGroup\nmetadata:\n  name: operatorgroup\n  namespace: ibm-common-services\nspec:\n  targetNamespaces:\n  - ibm-common-services\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/cpd-platform-operator-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: cpd-operator\n  namespace: ibm-common-services    # The project that contains the Cloud Pak for Data operator\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: cpd-platform-operator\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/cpd-platform-operator-operandrequest.yaml <<EOF\napiVersion: operator.ibm.com/v1alpha1\nkind: OperandRequest\nmetadata:\n  name: empty-request\n  namespace: $CPDNAMESPACE        # Replace with the project where you will install Cloud Pak for Data\nspec:\n  requests: []\nEOF\"\n\n\n# Run catalog source \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-operator-catalogsource.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 1m' \"\nrunuser -l $SUDOUSER -c \"sleep 1m\"\n\n# Create DB2U Operator catalog source\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/db2u-catalogsource.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 2m' \"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check ibm-operator-catalog pod status\n\npodname=\"ibm-operator-catalog\"\nname_space=\"openshift-marketplace\"\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n# Create IBM Operator Group\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-operator-og.yaml\"\n\n# Creating CPD Platform operator subscription: \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/cpd-platform-operator-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for ' \"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check cpd-platform-operator-manager pod status\n\npodname=\"cpd-platform-operator-manager\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n# Check ibm-namespace-scope-operator pod status\n\npodname=\"ibm-namespace-scope-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n# Check ibm-common-service-operator pod status\n\npodname=\"ibm-common-service-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n\n# Check operand-deployment-lifecycle-manager pod status\n\npodname=\"operand-deployment-lifecycle-manager\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/cpd-platform-operator-operandrequest.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 2m' \"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Install Lite-cr \nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibmcpd-cr.yaml <<EOF\napiVersion: cpd.ibm.com/v1\nkind: Ibmcpd\nmetadata:\n  name: ibmcpd-cr                                         # This is the recommended name, but you can change it\n  namespace: REPLACE_NAMESPACE                            # Replace with the project where you will install Cloud Pak for Data\nspec:\n  license:\n    accept: true\n    license: Enterprise                                   # Specify the Cloud Pak for Data license you purchased\n  storageClass: \\\"REPLACE_STORAGECLASS\\\"                    # Replace with the name of a RWX storage class\n  zenCoreMetadbStorageClass: \\\"REPLACE_STORAGECLASS\\\"       # (Recommended) Replace with the name of a RWO storage class\n  version: \\\"$VERSION\\\"\nEOF\"\n\nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_STORAGECLASS#$STORAGECLASS_VALUE#g $CPDTEMPLATES/ibmcpd-cr.yaml\"\nrunuser -l $SUDOUSER -c \"sed -i -e s#REPLACE_NAMESPACE#$CPDNAMESPACE#g $CPDTEMPLATES/ibmcpd-cr.yaml\"\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibmcpd-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"ibmcpd\"\nCRNAME=\"ibmcpd-cr\"\nSERVICE_STATUS=\"controlPlaneStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\n# Enable CSV injector patch\n\noc patch namespacescope common-service --type='json' -p='[{\"op\":\"replace\", \"path\": \"/spec/csvInjector/enable\", \"value\":true}]' -n $OPERATORNAMESPACE\n\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 376}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n## Creating IIS SC yaml \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wkc-iis-scc.yaml <<EOF\nallowHostDirVolumePlugin: false\nallowHostIPC: false\nallowHostNetwork: false\nallowHostPID: false\nallowHostPorts: false\nallowPrivilegeEscalation: true\nallowPrivilegedContainer: false\nallowedCapabilities: null\napiVersion: security.openshift.io/v1\ndefaultAddCapabilities: null\nfsGroup:\n  type: RunAsAny\nkind: SecurityContextConstraints\nmetadata:\n  annotations:\n    kubernetes.io/description: WKC/IIS provides all features of the restricted SCC\n      but runs as user 10032.\n  name: wkc-iis-scc\nreadOnlyRootFilesystem: false\nrequiredDropCapabilities:\n- KILL\n- MKNOD\n- SETUID\n- SETGID\nrunAsUser:\n  type: MustRunAs\n  uid: 10032\nseLinuxContext:\n  type: MustRunAs\nsupplementalGroups:\n  type: RunAsAny\nvolumes:\n- configMap\n- downwardAPI\n- emptyDir\n- persistentVolumeClaim\n- projected\n- secret\nusers:\n- system:serviceaccount:$CPDNAMESPACE:wkc-iis-sa\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wkc-iis-scc.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 1m' \"\nrunuser -l $SUDOUSER -c \"sleep 1m\"\n\n# WKC subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wkc-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  labels:\n    app.kubernetes.io/instance:  ibm-cpd-wkc-operator-catalog-subscription\n    app.kubernetes.io/managed-by: ibm-cpd-wkc-operator\n    app.kubernetes.io/name:  ibm-cpd-wkc-operator-catalog-subscription\n  name: ibm-cpd-wkc-operator\n  namespace: ibm-common-services\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-cpd-wkc\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wkc-ocs-pwx-cr.yaml <<EOF\napiVersion: wkc.cpd.ibm.com/v1beta1\nkind: WKC\nmetadata:\n  name: wkc-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  storageVendor: \\\"$STORAGEVENDOR_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\n  docker_registry_prefix: cp.icr.io/cp/cpd\n  useODLM: true\n  install_wkc_core_only: true\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wkc-nfs-cr.yaml <<EOF\napiVersion: wkc.cpd.ibm.com/v1beta1\nkind: WKC\nmetadata:\n  name: wkc-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\n  docker_registry_prefix: cp.icr.io/cp/cpd\n  useODLM: true\n  install_wkc_core_only: true\nEOF\"\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wkc-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-wkc-operator pod status\n\npodname=\"ibm-cpd-wkc-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-wkc cr\n\nif [[ $STORAGEOPTION == \"nfs\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wkc-nfs-cr.yaml\"\n\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wkc-ocs-pwx-cr.yaml\"\nfi\n\n# Check CR Status\n\nSERVICE=\"WKC\"\nCRNAME=\"wkc-cr\"\nSERVICE_STATUS=\"wkcStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 208}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# IIS CR creation\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-iis-ocs-pwx-cr.yaml <<EOF\napiVersion: iis.cpd.ibm.com/v1alpha1\nkind: IIS\nmetadata:\n  name: iis-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  storageVendor: \\\"$STORAGEVENDOR_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\n  docker_registry_prefix: cp.icr.io/cp/cpd\n  use_dynamic_provisioning: true\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-iis-nfs-cr.yaml <<EOF\napiVersion: iis.cpd.ibm.com/v1alpha1\nkind: IIS\nmetadata:\n  name: iis-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\n  docker_registry_prefix: cp.icr.io/cp/cpd\n  use_dynamic_provisioning: true\nEOF\"\n\n## Creating IIS SC yaml \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wkc-iis-scc.yaml <<EOF\nallowHostDirVolumePlugin: false\nallowHostIPC: false\nallowHostNetwork: false\nallowHostPID: false\nallowHostPorts: false\nallowPrivilegeEscalation: true\nallowPrivilegedContainer: false\nallowedCapabilities: null\napiVersion: security.openshift.io/v1\ndefaultAddCapabilities: null\nfsGroup:\n  type: RunAsAny\nkind: SecurityContextConstraints\nmetadata:\n  annotations:\n    kubernetes.io/description: WKC/IIS provides all features of the restricted SCC\n      but runs as user 10032.\n  name: wkc-iis-scc\nreadOnlyRootFilesystem: false\nrequiredDropCapabilities:\n- KILL\n- MKNOD\n- SETUID\n- SETGID\nrunAsUser:\n  type: MustRunAs\n  uid: 10032\nseLinuxContext:\n  type: MustRunAs\nsupplementalGroups:\n  type: RunAsAny\nvolumes:\n- configMap\n- downwardAPI\n- emptyDir\n- persistentVolumeClaim\n- projected\n- secret\nusers:\n- system:serviceaccount:$CPDNAMESPACE:wkc-iis-sa\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wkc-iis-scc.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 1m' \"\nrunuser -l $SUDOUSER -c \"sleep 1m\"\n\n# IIS Subscription\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-iis-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  labels:\n    app.kubernetes.io/instance: ibm-cpd-iis-operator-catalog-subscription\n    app.kubernetes.io/managed-by: ibm-cpd-iis-operator\n    app.kubernetes.io/name: ibm-cpd-iis-operator-catalog-subscription\n  generation: 1\n  name: ibm-cpd-iis-operator-catalog-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n    channel: $CHANNEL\n    installPlanApproval: Automatic\n    name: ibm-cpd-iis\n    source: ibm-operator-catalog\n    sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-iis-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping 2m for operator to install'\"\nrunuser -l $SUDOUSER -c \"sleep 2m\"\n\n# Check ibm-cpd-iis-operator pod status\n\npodname=\"ibm-cpd-iis-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-iis cr\n\nif [[ $STORAGEOPTION == \"nfs\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-iis-nfs-cr.yaml\"\n\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-iis-ocs-pwx-cr.yaml\"\nfi\n\n# Check CR Status\n\nSERVICE=\"IIS\"\nCRNAME=\"iis-cr\"\nSERVICE_STATUS=\"iisStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 205}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# UG CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-ug-ocs-pwx-cr.yaml <<EOF\napiVersion: wkc.cpd.ibm.com/v1beta1\nkind: UG\nmetadata:\n  name: ug-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  size: \\\"small\\\"\n  storageVendor: \\\"$STORAGEVENDOR_VALUE\\\"\n  license:\n    accept: true\n    license: \\\"Enterprise\\\"\n  docker_registry_prefix: cp.icr.io/cp/cpd\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-ug-nfs-cr.yaml <<EOF\napiVersion: wkc.cpd.ibm.com/v1beta1\nkind: UG\nmetadata:\n  name: ug-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  size: \\\"small\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  license:\n    accept: true\n    license: \\\"Enterprise\\\"\n  docker_registry_prefix: cp.icr.io/cp/cpd\nEOF\"\n\n\n## Creating ibm-ug cr\n\nif [[ $STORAGEOPTION == \"nfs\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-ug-nfs-cr.yaml\"\n\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-ug-ocs-pwx-cr.yaml\"\nfi\n\n# Check CR Status\n\nSERVICE=\"UG\"\nCRNAME=\"ug-cr\"\nSERVICE_STATUS=\"ugStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 112}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n\n# WML subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wml-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  labels:\n    app.kubernetes.io/instance: ibm-cpd-wml-operator-subscription\n    app.kubernetes.io/managed-by: ibm-cpd-wml-operator\n    app.kubernetes.io/name: ibm-cpd-wml-operator-subscription\n  name: ibm-cpd-wml-operator-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n    channel: $CHANNEL\n    installPlanApproval: Automatic\n    name: ibm-cpd-wml-operator\n    source: ibm-operator-catalog\n    sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wml-ocs-pwx-cr.yaml <<EOF\napiVersion: wml.cpd.ibm.com/v1beta1\nkind: WmlBase\nmetadata:\n  name: wml-cr\n  namespace: $CPDNAMESPACE\n  labels:\n    app.kubernetes.io/instance: wml-cr\n    app.kubernetes.io/managed-by: ibm-cpd-wml-operator\n    app.kubernetes.io/name: ibm-cpd-wml-operator\nspec:\n  scaleConfig: small\n  is_35_upgrade: false\n  ignoreForMaintenance: false\n  docker_registry_prefix: \\\"cp.icr.io/cp/cpd\\\"\n  storageClass: $STORAGECLASS_VALUE\n  storageVendor: $STORAGEVENDOR_VALUE\n  version: \\\"$VERSION\\\"\n  license:\n    accept: true\n    license: \\\"Enterprise\\\"\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wml-nfs-cr.yaml <<EOF\napiVersion: wml.cpd.ibm.com/v1beta1\nkind: WmlBase\nmetadata:\n  name: wml-cr\n  namespace: $CPDNAMESPACE\n  labels:\n    app.kubernetes.io/instance: wml-cr\n    app.kubernetes.io/managed-by: ibm-cpd-wml-operator\n    app.kubernetes.io/name: ibm-cpd-wml-operator\nspec:\n  scaleConfig: small\n  is_35_upgrade: false\n  ignoreForMaintenance: false\n  docker_registry_prefix: \\\"cp.icr.io/cp/cpd\\\"\n  storageClass: $STORAGECLASS_VALUE\n  version: \\\"$VERSION\\\"\n  license:\n    accept: true\n    license: \\\"Enterprise\\\"\nEOF\"\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wml-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-wml-operator pod status\n\npodname=\"ibm-cpd-wml-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-wml cr\n\nif [[ $STORAGEOPTION == \"nfs\" ]];then \n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wml-nfs-cr.yaml\"\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wml-ocs-pwx-cr.yaml\"\nfi\n\n\n# Check CR Status\n\nSERVICE=\"WmlBase\"\nCRNAME=\"wml-cr\"\nSERVICE_STATUS=\"wmlStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 168}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# WOS subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wos-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: ibm-watson-openscale-operator-subscription\n  labels:\n    app.kubernetes.io/instance: ibm-watson-openscale-operator-subscription\n    app.kubernetes.io/managed-by: ibm-watson-openscale-operator\n    app.kubernetes.io/name: ibm-watson-openscale-operator-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-cpd-wos\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wos-cr.yaml <<EOF\napiVersion: wos.cpd.ibm.com/v1\nkind: WOService\nmetadata:\n  name: aiopenscale-cr\n  namespace: $CPDNAMESPACE\nspec:\n  scaleConfig: small\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  version: $VERSION\n  type: service\n  license:\n    accept: true\n    license: Enterprise\nEOF\"\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wos-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-wos-operator pod status\n\npodname=\"ibm-cpd-wos-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-wos cr\n\nrunuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wos-cr.yaml\"\n\n# Check CR Status\n\nSERVICE=\"WOService\"\nCRNAME=\"aiopenscale-cr\"\nSERVICE_STATUS=\"wosStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 133}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport CPDNAMESPACE=$3\nexport STORAGEOPTION=$4\nexport ASSEMBLY=$5\nexport CLUSTERNAME=$6\nexport DOMAINNAME=$7\nexport OPENSHIFTUSER=$8\nexport APIKEY=$9\nexport CHANNEL=${10}\nexport VERSION=${11}\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OPERATORNAMESPACE=ibm-common-services\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\nexport CPDTEMPLATES=/home/$SUDOUSER/.cpd/templates\n\n# Set parameters\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n    STORAGECLASS_VALUE=\"portworx-shared-gp3\"\n    STORAGEVENDOR_VALUE=\"portworx\"\nelif [[ $STORAGEOPTION == \"ocs\" ]]; then\n    STORAGECLASS_VALUE=\"ocs-storagecluster-cephfs\"\n    STORAGEVENDOR_VALUE=\"ocs\"\nelif [[ $STORAGEOPTION == \"nfs\" ]]; then\n    STORAGECLASS_VALUE=\"nfs\"\n    STORAGEVENDOR_VALUE=\"\"\nfi\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# WSL subscription and CR creation \n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wsl-sub.yaml <<EOF\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  annotations: {}\n  name: ibm-cpd-ws-operator-catalog-subscription\n  namespace: $OPERATORNAMESPACE\nspec:\n  channel: $CHANNEL\n  installPlanApproval: Automatic\n  name: ibm-cpd-wsl\n  source: ibm-operator-catalog\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wsl-ocs-pwx-cr.yaml <<EOF\napiVersion: ws.cpd.ibm.com/v1beta1\nkind: WS\nmetadata:\n  name: ws-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  size: \\\"small\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  storageVendor: \\\"$STORAGEVENDOR_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $CPDTEMPLATES/ibm-wsl-nfs-cr.yaml <<EOF\napiVersion: ws.cpd.ibm.com/v1beta1\nkind: WS\nmetadata:\n  name: ws-cr\n  namespace: $CPDNAMESPACE\nspec:\n  version: \\\"$VERSION\\\"\n  size: \\\"small\\\"\n  storageClass: \\\"$STORAGECLASS_VALUE\\\"\n  license:\n    accept: true\n    license: Enterprise\nEOF\"\n\n## Creating Subscription \n\nrunuser -l $SUDOUSER -c \"oc create -f $CPDTEMPLATES/ibm-wsl-sub.yaml\"\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 5m' \"\nrunuser -l $SUDOUSER -c \"sleep 5m\"\n\n# Check ibm-cpd-ws-operator pod status\n\npodname=\"ibm-cpd-ws-operator\"\nname_space=$OPERATORNAMESPACE\nstatus=\"unknown\"\nwhile [ \"$status\" != \"Running\" ]\ndo\n  pod_name=$(oc get pods -n $name_space | grep $podname | awk '{print $1}' )\n  ready_status=$(oc get pods -n $name_space $pod_name  --no-headers | awk '{print $2}')\n  pod_status=$(oc get pods -n $name_space $pod_name --no-headers | awk '{print $3}')\n  echo $pod_name State - $ready_status, podstatus - $pod_status\n  if [ \"$ready_status\" == \"1/1\" ] && [ \"$pod_status\" == \"Running\" ]\n  then \n  status=\"Running\"\n  else\n  status=\"starting\"\n  sleep 10 \n  fi\n  echo \"$pod_name is $status\"\ndone\n\n## Creating ibm-wsl cr\n\nif [[ $STORAGEOPTION == \"nfs\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wsl-nfs-cr.yaml\"\n\nelif [[ $STORAGEOPTION == \"ocs\" || $STORAGEOPTION == \"portworx\" ]];then \n\n    runuser -l $SUDOUSER -c \"oc project $CPDNAMESPACE; oc create -f $CPDTEMPLATES/ibm-wsl-ocs-pwx-cr.yaml\"\nfi\n\n# Check CR Status\n\nSERVICE=\"WS\"\nCRNAME=\"ws-cr\"\nSERVICE_STATUS=\"wsStatus\"\n\nSTATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n\nwhile  [[ ! $STATUS =~ ^(Completed|Complete)$ ]]; do\n    echo \"$CRNAME is Installing!!!!\"\n    sleep 60 \n    STATUS=$(oc get $SERVICE $CRNAME -n $CPDNAMESPACE -o json | jq .status.$SERVICE_STATUS | xargs) \n    if [ \"$STATUS\" == \"Failed\" ]\n    then\n        echo \"**********************************\"\n        echo \"$CRNAME Installation Failed!!!!\"\n        echo \"**********************************\"\n        exit\n    fi\ndone \necho \"*************************************\"\necho \"$CRNAME Installation Finished!!!!\"\necho \"*************************************\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 152}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho $(date) \" - ############## Starting Script ####################\"\n\nset -e\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport SSHKEY=$3\nexport WORKERCOUNT=$4\nexport MASTERCOUNT=$5\nexport SUBSCRIPTIONID=$6\nexport TENANTID=$7\nexport AADCLIENTID=$8\nexport AADSECRET=$9\nexport RESOURCEGROUPNAME=${10}\nexport LOCATION=${11}\nexport VIRTUALNETWORKNAME=${12}\nexport PXSPECURL=${13}\nexport STORAGEOPTION=${14}\nexport NFSIPADDRESS=${15}\nexport SINGLEORMULTI=${16}\nexport ARTIFACTSLOCATION=${17::-1}\nexport ARTIFACTSTOKEN=\\\"${18}\\\"\nexport BASEDOMAIN=${19}\nexport MASTERINSTANCETYPE=${20}\nexport WORKERINSTANCETYPE=${21}\nexport CLUSTERNAME=${22}\nexport CLUSTERNETWORKCIDR=${23}\nexport HOSTADDRESSPREFIX=${24}\nexport VIRTUALNETWORKCIDR=${25}\nexport SERVICENETWORKCIDR=${26}\nexport BASEDOMAINRG=${27}\nexport NETWORKRG=${28}\nexport MASTERSUBNETNAME=${29}\nexport WORKERSUBNETNAME=${30}\nexport PULLSECRET=${31}\nexport FIPS=${32}\nexport PUBLISH=${33}\nexport OPENSHIFTUSER=${34}\nexport ENABLEAUTOSCALER=${35}\nexport OUTBOUNDTYPE=${36}\nexport EXISTING_RESOURCE_GROUP_NAME=${37}\n\n#Var\nexport INSTALLERHOME=/home/$SUDOUSER/.openshift\n\necho $(date) \" - Disable and enable repo starting\"\nsudo yum update -y --disablerepo=* --enablerepo=\"*microsoft*\"\necho $(date) \" - Disable and enable repo completed\"\n\n# Grow Root File System\nyum -y install cloud-utils-growpart.noarch\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo $(date) \" - Root File System successfully extended\"\nelse\n    echo $(date) \" - Root File System failed to be grown\"\n\texit 20\nfi\n\necho $(date) \" - Install Podman\"\nyum install -y podman\necho $(date) \" - Install Podman Complete\"\n\necho $(date) \" - Install httpd-tools\"\nyum install -y httpd-tools\necho $(date) \" - Install httpd-tools Complete\"\n\necho $(date) \" - Download Binaries\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.openshift\"\n\nrunuser -l $SUDOUSER -c \"wget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.8.11/openshift-install-linux-4.8.11.tar.gz\"\nrunuser -l $SUDOUSER -c \"wget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.8.11/openshift-client-linux-4.8.11.tar.gz\"\nrunuser -l $SUDOUSER -c \"tar -xvf openshift-install-linux-4.8.11.tar.gz -C $INSTALLERHOME\"\nrunuser -l $SUDOUSER -c \"sudo tar -xvf openshift-client-linux-4.8.11.tar.gz -C /usr/bin\"\n\nchmod +x /usr/bin/kubectl\nchmod +x /usr/bin/oc\nchmod +x $INSTALLERHOME/openshift-install\necho $(date) \" - Download Binaries Done.\"\n\necho $(date) \" - Setup Azure Credentials for OCP\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.azure\"\nrunuser -l $SUDOUSER -c \"touch /home/$SUDOUSER/.azure/osServicePrincipal.json\"\ncat > /home/$SUDOUSER/.azure/osServicePrincipal.json <<EOF\n{\"subscriptionId\":\"$SUBSCRIPTIONID\",\"clientId\":\"$AADCLIENTID\",\"clientSecret\":\"$AADSECRET\",\"tenantId\":\"$TENANTID\"}\nEOF\necho $(date) \" - Setup Azure Credentials for OCP - Complete\"\n\necho $(date) \" - Setup Install config\"\nrunuser -l $SUDOUSER -c \"mkdir -p $INSTALLERHOME/openshiftfourx\"\nrunuser -l $SUDOUSER -c \"touch $INSTALLERHOME/openshiftfourx/install-config.yaml\"\nzones=\"\"\nif [[ $SINGLEORMULTI == \"az\" ]]; then\nzones=\"zones:\n      - '1'\n      - '2'\n      - '3'\"\nfi\ncat > $INSTALLERHOME/openshiftfourx/install-config.yaml <<EOF\napiVersion: v1\nbaseDomain: $BASEDOMAIN\ncompute:\n- hyperthreading: Enabled\n  name: worker\n  platform: \n    azure:\n      type: $WORKERINSTANCETYPE\n      osDisk:\n        diskSizeGB: 1024\n      $zones\n  replicas: $WORKERCOUNT\ncontrolPlane:\n  hyperthreading: Enabled\n  name: master\n  platform: \n    azure:\n      type: $MASTERINSTANCETYPE\n      osDisk:\n        diskSizeGB: 1024\n      $zones\n  replicas: $MASTERCOUNT\nmetadata:\n  creationTimestamp: null\n  name: $CLUSTERNAME\nnetworking:\n  clusterNetwork:\n  - cidr: $CLUSTERNETWORKCIDR\n    hostPrefix: $HOSTADDRESSPREFIX\n  machineCIDR: $VIRTUALNETWORKCIDR\n  networkType: OpenShiftSDN\n  serviceNetwork:\n  - $SERVICENETWORKCIDR\nplatform:\n  azure:\n    baseDomainResourceGroupName: $BASEDOMAINRG\n    region: $LOCATION\n    networkResourceGroupName: $NETWORKRG\n    virtualNetwork: $VIRTUALNETWORKNAME\n    controlPlaneSubnet: $MASTERSUBNETNAME\n    computeSubnet: $WORKERSUBNETNAME\n    outboundType: $OUTBOUNDTYPE\n    resourceGroupName: $EXISTING_RESOURCE_GROUP_NAME\npullSecret: '$PULLSECRET'\nfips: $FIPS\npublish: $PUBLISH\nsshKey: |\n  $SSHKEY\nEOF\necho $(date) \" - Setup Install config - Complete\"\n\nrunuser -l $SUDOUSER -c \"cp $INSTALLERHOME/openshiftfourx/install-config.yaml $INSTALLERHOME/openshiftfourx/install-config-backup.yaml\"\n\necho $(date) \" - Install OCP\"\nrunuser -l $SUDOUSER -c \"export ARM_SKIP_PROVIDER_REGISTRATION=true\"\nrunuser -l $SUDOUSER -c \"$INSTALLERHOME/openshift-install create cluster --dir=$INSTALLERHOME/openshiftfourx --log-level=debug\"\nrunuser -l $SUDOUSER -c \"sleep 120\"\necho $(date) \" - OCP Install Complete\"\n\necho $(date) \" - Kube Config setup\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.kube\"\nrunuser -l $SUDOUSER -c \"cp $INSTALLERHOME/openshiftfourx/auth/kubeconfig /home/$SUDOUSER/.kube/config\"\necho $(date) \"Kube Config setup done\"\n\n#Switch to Machine API project\nrunuser -l $SUDOUSER -c \"oc project openshift-machine-api\"\n\necho $(date) \" - Setting up Cluster Autoscaler\"\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/cluster-autoscaler.yaml <<EOF\napiVersion: 'autoscaling.openshift.io/v1'\nkind: 'ClusterAutoscaler'\nmetadata:\n  name: 'default'\nspec:\n  podPriorityThreshold: -10\n  resourceLimits:\n    maxNodesTotal: 24\n    cores:\n      min: 48\n      max: 128\n    memory:\n      min: 128\n      max: 512\n  scaleDown: \n    enabled: true\n    delayAfterAdd: '3m'\n    delayAfterDelete: '2m'\n    delayAfterFailure: '30s'\n    unneededTime: '60s'\nEOF\"\n\necho $(date) \" - Cluster Autoscaler setup complete\"\n\necho $(date) \" - Setting up Machine Autoscaler\"\nclusterid=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}' --kubeconfig /home/$SUDOUSER/.kube/config)\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/machine-autoscaler.yaml <<EOF\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}1\n  namespace: 'openshift-machine-api'\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}1\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}2\n  namespace: openshift-machine-api\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}2\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}3\n  namespace: openshift-machine-api\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}3\nEOF\"\n\necho $(date) \" - Machine Autoscaler setup complete\"\n\necho $(date) \" - Setting up Machine health checks\"\nclusterid=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}' --kubeconfig /home/$SUDOUSER/.kube/config)\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/machine-health-check.yaml <<EOF\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}1\n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}1\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}2 \n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}2\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}3 \n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}3\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\nEOF\"\n\n##Enable/Disable Autoscaler\nif [[ $ENABLEAUTOSCALER == \"true\" || $ENABLEAUTOSCALER == \"True\" ]]; then\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/cluster-autoscaler.yaml\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/machine-autoscaler.yaml\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/machine-health-check.yaml\"\nfi\n\necho $(date) \" - Machine Health Check setup complete\"\n\necho $(date) \" - Setting up $STORAGEOPTION\"\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/px-install.yaml$ARTIFACTSTOKEN -O $INSTALLERHOME/openshiftfourx/px-install.yaml\"\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/px-storageclasses.yaml$ARTIFACTSTOKEN -O $INSTALLERHOME/openshiftfourx/px-storageclasses.yaml\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/px-install.yaml\"\n  runuser -l $SUDOUSER -c \"sleep 30\"\n  runuser -l $SUDOUSER -c \"oc apply -f '$PXSPECURL'\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/px-storageclasses.yaml\"\nfi\n\nif [[ $STORAGEOPTION == \"nfs\" ]]; then\n  runuser -l $SUDOUSER -c \"oc adm policy add-scc-to-user hostmount-anyuid system:serviceaccount:kube-system:nfs-client-provisioner\"\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/nfs-template.yaml$ARTIFACTSTOKEN -O  $INSTALLERHOME/openshiftfourx/nfs-template.yaml\"\n  runuser -l $SUDOUSER -c \"oc process -f $INSTALLERHOME/openshiftfourx/nfs-template.yaml -p NFS_SERVER=$NFSIPADDRESS -p NFS_PATH=/exports/home | oc create -n kube-system -f -\"\nfi\necho $(date) \" - Setting up $STORAGEOPTION - Done\"\n\necho $(date) \" - Creating $OPENSHIFTUSER user\"\nrunuser -l $SUDOUSER -c \"htpasswd -c -B -b /tmp/.htpasswd '$OPENSHIFTUSER' '$OPENSHIFTPASSWORD'\"\nrunuser -l $SUDOUSER -c \"sleep 3\"\nrunuser -l $SUDOUSER -c \"oc create secret generic htpass-secret --from-file=htpasswd=/tmp/.htpasswd -n openshift-config\"\nrunuser -l $SUDOUSER -c \"cat >  $INSTALLERHOME/openshiftfourx/auth.yaml <<EOF\napiVersion: config.openshift.io/v1\nkind: OAuth\nmetadata:\n  name: cluster\nspec:\n  tokenConfig:\n    accessTokenMaxAgeSeconds: 172800\n  identityProviders:\n  - name: htpasswdProvider \n    challenge: true \n    login: true \n    mappingMethod: claim \n    type: HTPasswd\n    htpasswd:\n      fileData:\n        name: htpass-secret\nEOF\"\nrunuser -l $SUDOUSER -c \"oc apply -f $INSTALLERHOME/openshiftfourx/auth.yaml\"\nrunuser -l $SUDOUSER -c \"oc adm policy add-cluster-role-to-user cluster-admin '$OPENSHIFTUSER'\"\n\necho $(date) \" - ############## Script Complete ####################\"", "num_lines": 368}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nexport SUDOUSER=$1\nexport OPENSHIFTUSER=$2\nexport OPENSHIFTPASSWORD=$3\nexport CLUSTERNAME=$4\nexport DOMAINNAME=$5\nexport SINGLEORMULTI=$6\nexport REGION=$7\nexport RESOURCEGROUPNAME=$8\nexport VNETNAME=$9\nexport WORKERSUBNETNAME=${10}\n\nexport MULTIZONE1=1\nexport MULTIZONE2=2\nexport MULTIZONE3=3\n\nexport OCSTEMPLATES=/home/$SUDOUSER/.openshift/ocs/templates\nrunuser -l $SUDOUSER -c \"mkdir -p $OCSTEMPLATES\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCSTEMPLATES/toolbox.yaml <<EOF\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: rook-ceph-tools\n  namespace: openshift-storage\n  labels:\n    app: rook-ceph-tools\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: rook-ceph-tools\n  template:\n    metadata:\n      labels:\n        app: rook-ceph-tools\n    spec:\n      dnsPolicy: ClusterFirstWithHostNet\n      containers:\n      - name: rook-ceph-tools\n        image: rook/ceph:master\n        command: [\\\"/tini\\\"]\n        args: [\\\"-g\\\", \\\"--\\\", \\\"/usr/local/bin/toolbox.sh\\\"]\n        imagePullPolicy: IfNotPresent\n        env:\n          - name: ROOK_CEPH_USERNAME\n            valueFrom:\n              secretKeyRef:\n                name: rook-ceph-mon\n                key: ceph-username\n          - name: ROOK_CEPH_SECRET\n            valueFrom:\n              secretKeyRef:\n                name: rook-ceph-mon\n                key: ceph-secret\n        volumeMounts:\n          - mountPath: /etc/ceph\n            name: ceph-config\n          - name: mon-endpoint-volume\n            mountPath: /etc/rook\n      volumes:\n        - name: mon-endpoint-volume\n          configMap:\n            name: rook-ceph-mon-endpoints\n            items:\n            - key: data\n              path: mon-endpoints\n        - name: ceph-config\n          emptyDir: {}\n      tolerations:\n        - key: \\\"node.kubernetes.io/unreachable\\\"\n          operator: \\\"Exists\\\"\n          effect: \\\"NoExecute\\\"\n          tolerationSeconds: 5\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCSTEMPLATES/ocs-olm.yaml <<EOF\n---\napiVersion: v1\nkind: Namespace\nmetadata:\n  labels:\n    openshift.io/cluster-monitoring: \\\"true\\\"\n  name: openshift-storage\nspec: {}\n---\napiVersion: operators.coreos.com/v1\nkind: OperatorGroup\nmetadata:\n  name: openshift-storage-operatorgroup\n  namespace: openshift-storage\nspec:\n  targetNamespaces:\n  - openshift-storage\n---\napiVersion: operators.coreos.com/v1alpha1\nkind: Subscription\nmetadata:\n  name: ocs-operator\n  namespace: openshift-storage\n  labels:\n    operators.coreos.com/ocs-operator.openshift-storage: ''\nspec:\n  channel: stable-4.8\n  installPlanApproval: Automatic\n  name: ocs-operator\n  source: redhat-operators\n  sourceNamespace: openshift-marketplace\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCSTEMPLATES/ocs-storagecluster.yaml <<EOF\napiVersion: ocs.openshift.io/v1\nkind: StorageCluster\nmetadata:\n  annotations:\n    uninstall.ocs.openshift.io/cleanup-policy: delete\n    uninstall.ocs.openshift.io/mode: graceful\n  name: ocs-storagecluster\n  namespace: openshift-storage\n  finalizers:\n    - storagecluster.ocs.openshift.io\nspec:\n  encryption:\n    enable: true\n  externalStorage: {}\n  managedResources:\n    cephBlockPools: {}\n    cephFilesystems: {}\n    cephObjectStoreUsers: {}\n    cephObjectStores: {}\n  storageDeviceSets:\n    - config: {}\n      count: 1\n      dataPVCTemplate:\n        metadata:\n          creationTimestamp: null\n        spec:\n          accessModes:\n            - ReadWriteOnce\n          resources:\n            requests:\n              storage: 1Ti\n          storageClassName: managed-premium\n          volumeMode: Block\n        status: {}\n      name: ocs-deviceset\n      placement: {}\n      portable: true\n      replica: 3\n      resources: {}\n  version: 4.8.0\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCSTEMPLATES/ocs-machineset-singlezone.yaml <<EOF\napiVersion: machine.openshift.io/v1beta1\nkind: MachineSet\nmetadata:\n  labels:\n    machine.openshift.io/cluster-api-cluster: CLUSTERID\n  name: CLUSTERID-workerocs-$REGION\n  namespace: openshift-machine-api\nspec:\n  replicas: 3\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-cluster: CLUSTERID\n      machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION\n  template:\n    metadata:\n      labels:\n        machine.openshift.io/cluster-api-cluster: CLUSTERID\n        machine.openshift.io/cluster-api-machine-role: worker\n        machine.openshift.io/cluster-api-machine-type: worker\n        machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION\n    spec:\n      taints:\n      - effect: NoSchedule\n        key: node.ocs.openshift.io/storage\n        value: \\\"true\\\"\n      metadata:\n        labels:\n          cluster.ocs.openshift.io/openshift-storage: \\\"\\\"\n          node-role.kubernetes.io/infra: \\\"\\\"\n          node-role.kubernetes.io/worker: \\\"\\\"\n          role: storage-node\n      providerSpec:\n        value:\n          apiVersion: azureproviderconfig.openshift.io/v1beta1\n          credentialsSecret:\n            name: azure-cloud-credentials\n            namespace: openshift-machine-api\n          image:\n            offer: \\\"\\\"\n            publisher: \\\"\\\"\n            resourceID: /resourceGroups/CLUSTERID-rg/providers/Microsoft.Compute/images/CLUSTERID\n            sku: \\\"\\\"\n            version: \\\"\\\"\n          kind: AzureMachineProviderSpec\n          location: $REGION\n          managedIdentity: CLUSTERID-identity\n          metadata:\n            creationTimestamp: null\n          networkResourceGroup: $RESOURCEGROUPNAME\n          osDisk:\n            diskSizeGB: 512\n            managedDisk:\n              storageAccountType: Premium_LRS\n            osType: Linux\n          publicIP: false\n          publicLoadBalancer: CLUSTERID\n          resourceGroup: CLUSTERID-rg\n          subnet: $WORKERSUBNETNAME\n          userDataSecret:\n            name: worker-user-data\n          vmSize: Standard_D16s_v3\n          vnet: $VNETNAME\n          zone: \\\"\\\"\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCSTEMPLATES/ocs-machineset-multizone.yaml <<EOF\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineSet\nmetadata:\n  labels:\n    machine.openshift.io/cluster-api-cluster: CLUSTERID\n  name: CLUSTERID-workerocs-$REGION$MULTIZONE1\n  namespace: openshift-machine-api\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-cluster: CLUSTERID\n      machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE1\n  template:\n    metadata:\n      labels:\n        machine.openshift.io/cluster-api-cluster: CLUSTERID\n        machine.openshift.io/cluster-api-machine-role: worker\n        machine.openshift.io/cluster-api-machine-type: worker\n        machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE1\n    spec:\n      taints:\n      - effect: NoSchedule\n        key: node.ocs.openshift.io/storage\n        value: \\\"true\\\"\n      metadata:\n        labels:\n          cluster.ocs.openshift.io/openshift-storage: \\\"\\\"\n          node-role.kubernetes.io/infra: \\\"\\\"\n          node-role.kubernetes.io/worker: \\\"\\\"\n          role: storage-node\n      providerSpec:\n        value:\n          apiVersion: azureproviderconfig.openshift.io/v1beta1\n          credentialsSecret:\n            name: azure-cloud-credentials\n            namespace: openshift-machine-api\n          image:\n            offer: \\\"\\\"\n            publisher: \\\"\\\"\n            resourceID: /resourceGroups/CLUSTERID-rg/providers/Microsoft.Compute/images/CLUSTERID\n            sku: \\\"\\\"\n            version: \\\"\\\"\n          kind: AzureMachineProviderSpec\n          location: $REGION\n          managedIdentity: CLUSTERID-identity\n          metadata:\n            creationTimestamp: null\n          networkResourceGroup: $RESOURCEGROUPNAME\n          osDisk:\n            diskSizeGB: 512\n            managedDisk:\n              storageAccountType: Premium_LRS\n            osType: Linux\n          publicIP: false\n          publicLoadBalancer: CLUSTERID\n          resourceGroup: CLUSTERID-rg\n          subnet: $WORKERSUBNETNAME\n          userDataSecret:\n            name: worker-user-data\n          vmSize: Standard_D16s_v3\n          vnet: $VNETNAME\n          zone: \\\"1\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineSet\nmetadata:\n  labels:\n    machine.openshift.io/cluster-api-cluster: CLUSTERID\n  name: CLUSTERID-workerocs-$REGION$MULTIZONE2\n  namespace: openshift-machine-api\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-cluster: CLUSTERID\n      machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE2\n  template:\n    metadata:\n      labels:\n        machine.openshift.io/cluster-api-cluster: CLUSTERID\n        machine.openshift.io/cluster-api-machine-role: worker\n        machine.openshift.io/cluster-api-machine-type: worker\n        machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE2\n    spec:\n      taints:\n      - effect: NoSchedule\n        key: node.ocs.openshift.io/storage\n        value: \\\"true\\\"\n      metadata:\n        labels:\n          cluster.ocs.openshift.io/openshift-storage: \\\"\\\"\n          node-role.kubernetes.io/infra: \\\"\\\"\n          node-role.kubernetes.io/worker: \\\"\\\"\n          role: storage-node\n      providerSpec:\n        value:\n          apiVersion: azureproviderconfig.openshift.io/v1beta1\n          credentialsSecret:\n            name: azure-cloud-credentials\n            namespace: openshift-machine-api\n          image:\n            offer: \\\"\\\"\n            publisher: \\\"\\\"\n            resourceID: /resourceGroups/CLUSTERID-rg/providers/Microsoft.Compute/images/CLUSTERID\n            sku: \\\"\\\"\n            version: \\\"\\\"\n          kind: AzureMachineProviderSpec\n          location: $REGION\n          managedIdentity: CLUSTERID-identity\n          metadata:\n            creationTimestamp: null\n          networkResourceGroup: $RESOURCEGROUPNAME\n          osDisk:\n            diskSizeGB: 512\n            managedDisk:\n              storageAccountType: Premium_LRS\n            osType: Linux\n          publicIP: false\n          publicLoadBalancer: CLUSTERID\n          resourceGroup: CLUSTERID-rg\n          subnet: $WORKERSUBNETNAME\n          userDataSecret:\n            name: worker-user-data\n          vmSize: Standard_D16s_v3\n          vnet: $VNETNAME\n          zone: \\\"2\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineSet\nmetadata:\n  labels:\n    machine.openshift.io/cluster-api-cluster: CLUSTERID\n  name: CLUSTERID-workerocs-$REGION$MULTIZONE3\n  namespace: openshift-machine-api\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-cluster: CLUSTERID\n      machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE3\n  template:\n    metadata:\n      labels:\n        machine.openshift.io/cluster-api-cluster: CLUSTERID\n        machine.openshift.io/cluster-api-machine-role: worker\n        machine.openshift.io/cluster-api-machine-type: worker\n        machine.openshift.io/cluster-api-machineset: CLUSTERID-workerocs-$REGION$MULTIZONE3\n    spec:\n      taints:\n      - effect: NoSchedule\n        key: node.ocs.openshift.io/storage\n        value: \\\"true\\\"\n      metadata:\n        labels:\n          cluster.ocs.openshift.io/openshift-storage: \\\"\\\"\n          node-role.kubernetes.io/infra: \\\"\\\"\n          node-role.kubernetes.io/worker: \\\"\\\"\n          role: storage-node\n      providerSpec:\n        value:\n          apiVersion: azureproviderconfig.openshift.io/v1beta1\n          credentialsSecret:\n            name: azure-cloud-credentials\n            namespace: openshift-machine-api\n          image:\n            offer: \\\"\\\"\n            publisher: \\\"\\\"\n            resourceID: /resourceGroups/CLUSTERID-rg/providers/Microsoft.Compute/images/CLUSTERID\n            sku: \\\"\\\"\n            version: \\\"\\\"\n          kind: AzureMachineProviderSpec\n          location: $REGION\n          managedIdentity: CLUSTERID-identity\n          metadata:\n            creationTimestamp: null\n          networkResourceGroup: $RESOURCEGROUPNAME\n          osDisk:\n            diskSizeGB: 512\n            managedDisk:\n              storageAccountType: Premium_LRS\n            osType: Linux\n          publicIP: false\n          publicLoadBalancer: CLUSTERID\n          resourceGroup: CLUSTERID-rg\n          subnet: $WORKERSUBNETNAME\n          userDataSecret:\n            name: worker-user-data\n          vmSize: Standard_D16s_v3\n          vnet: $VNETNAME\n          zone: \\\"3\\\"\nEOF\"\n\n#Login\nvar=1\nwhile [ $var -ne 0 ]; do\necho \"Attempting to login $OPENSHIFTUSER to https://api.${CLUSTERNAME}.${DOMAINNAME}:6443 \"\noc login \"https://api.${CLUSTERNAME}.${DOMAINNAME}:6443\" -u $OPENSHIFTUSER -p $OPENSHIFTPASSWORD --insecure-skip-tls-verify=true\nvar=$?\necho \"exit code: $var\"\ndone\n\n# #OCS Operator will install its components only on nodes labelled for OCS with the key\n# OCS_NODES=$(oc get nodes --show-labels | grep node-role.kubernetes.io/worker= |cut -d' ' -f1)\n# for ocsnode in ${OCS_NODES[@]}; do\n# oc label nodes $ocsnode cluster.ocs.openshift.io/openshift-storage=''\n# done\n## Creating ibm-ccs cr\nif [[ $SINGLEORMULTI == \"noha\" ]];then \n\nCLUSTERID=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}')\nrunuser -l $SUDOUSER -c \"sed -i -e s/CLUSTERID/$CLUSTERID/g $OCSTEMPLATES/ocs-machineset-singlezone.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCSTEMPLATES/ocs-machineset-singlezone.yaml\"\nrunuser -l $SUDOUSER -c \"echo sleeping for 10mins untill the node comes up\"\nrunuser -l $SUDOUSER -c \"sleep 600\"\n\nelif [[ $SINGLEORMULTI == \"az\" ]];then \n\nCLUSTERID=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}')\nrunuser -l $SUDOUSER -c \"sed -i -e s/CLUSTERID/$CLUSTERID/g $OCSTEMPLATES/ocs-machineset-multizone.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCSTEMPLATES/ocs-machineset-multizone.yaml\"\nrunuser -l $SUDOUSER -c \"echo sleeping for 10mins untill the node comes up\"\nrunuser -l $SUDOUSER -c \"sleep 600\"\n\nfi\n\nrunuser -l $SUDOUSER -c \"oc create -f $OCSTEMPLATES/ocs-olm.yaml\"\nrunuser -l $SUDOUSER -c \"echo sleeping for 5mins\"\nrunuser -l $SUDOUSER -c \"sleep 300\"\nrunuser -l $SUDOUSER -c \"oc apply -f $OCSTEMPLATES/ocs-storagecluster.yaml\"\nrunuser -l $SUDOUSER -c \"echo sleeping for 10mins\"\nrunuser -l $SUDOUSER -c \"sleep 600\"\nrunuser -l $SUDOUSER -c \"oc apply -f $OCSTEMPLATES/toolbox.yaml\"\nrunuser -l $SUDOUSER -c \"echo sleeping for 1min\"\nrunuser -l $SUDOUSER -c \"sleep 60\"\n\necho $(date) \" - ############## Script Complete ####################\"", "num_lines": 458}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nexport ARTIFACTSLOCATION=${1::-1}\nexport ARTIFACTSTOKEN=\\\"$2\\\"\nexport SUDOUSER=$3\nexport WORKERNODECOUNT=$4\nexport NAMESPACE=$5\nexport APIKEY=$6\n\nexport INSTALLERHOME=/home/$SUDOUSER/.ibm\nexport OCPTEMPLATES=/home/$SUDOUSER/.openshift/templates\n\nrunuser -l $SUDOUSER -c \"mkdir -p $INSTALLERHOME\"\nrunuser -l $SUDOUSER -c \"mkdir -p $OCPTEMPLATES\"\n\n# Root kube config\nmkdir -p /root/.kube\ncp /home/$SUDOUSER/.kube/config /root/.kube/config\n\n# Create Registry Route\nrunuser -l $SUDOUSER -c \"oc patch configs.imageregistry.operator.openshift.io/cluster --type merge -p '{\\\"spec\\\":{\\\"defaultRoute\\\":true, \\\"replicas\\\":$WORKERNODECOUNT}}'\"\nrunuser -l $SUDOUSER -c \"sleep 20\"\nrunuser -l $SUDOUSER -c \"oc project kube-system\"\nregistryRoute=$(oc get route default-route -n openshift-image-registry --template='{{ .spec.host }}' --kubeconfig /home/$SUDOUSER/.kube/config)\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/registries.conf <<EOF\nunqualified-search-registries = ['registry.access.redhat.com', 'docker.io']\n[[registry]]\nprefix = \\\"${registryRoute}\\\"\ninsecure = true\nblocked = false\nlocation = \\\"${registryRoute}\\\"\nEOF\"\n\n# Machine Configs\ninsecureRegistryData=$(cat $OCPTEMPLATES/registries.conf | base64 -w 0)\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/insecure-registry-mc.yaml <<EOF\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: worker\n  name: 90-worker-container-runtime\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,${insecureRegistryData}\n        filesystem: root\n        mode: 0644\n        path: /etc/containers/registries.conf\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/sysctl-mc.yaml <<EOF\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: worker\n  name: 98-master-worker-sysctl\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,dm0ubWF4X21hcF9jb3VudCA9IDI2MjE0NAprZXJuZWwuc2VtID0gMjUwIDEwMjQwMDAgMTAwIDQwOTYKa2VybmVsLm1zZ21heCA9IDY1NTM2Cmtlcm5lbC5tc2dtbmIgPSA2NTUzNg==\n        filesystem: root\n        mode: 0644\n        path: /etc/sysctl.conf\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/limits-mc.yaml <<EOF\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: worker\n  name: 15-security-limits\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,KiAgICAgICAgICAgICAgIGhhcmQgICAgbm9maWxlICAgICAgICAgNjY1NjAKKiAgICAgICAgICAgICAgIHNvZnQgICAgbm9maWxlICAgICAgICAgNjY1NjA=\n        filesystem: root\n        mode: 0644\n        path: /etc/security/limits.conf\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/crio-mc.yaml <<EOF\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: worker\n  name: 90-worker-crio\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,W2NyaW9dCltjcmlvLmFwaV0Kc3RyZWFtX2FkZHJlc3MgPSAiIgpzdHJlYW1fcG9ydCA9ICIxMDAxMCIKW2NyaW8ucnVudGltZV0KZGVmYXVsdF91bGltaXRzID0gWwogICAgIm5vZmlsZT02NTUzNjo2NTUzNiIKXQpjb25tb24gPSAiL3Vzci9saWJleGVjL2NyaW8vY29ubW9uIgpjb25tb25fY2dyb3VwID0gInBvZCIKYXBwYXJtb3JfcHJvZmlsZSA9ICJjcmlvLWRlZmF1bHQiCmNncm91cF9tYW5hZ2VyID0gInN5c3RlbWQiCmhvb2tzX2RpciA9IFsKICAgICIvZXRjL2NvbnRhaW5lcnMvb2NpL2hvb2tzLmQiLApdCnBpZHNfbGltaXQgPSAxMjAwMApbY3Jpby5pbWFnZV0KZ2xvYmFsX2F1dGhfZmlsZSA9ICIvdmFyL2xpYi9rdWJlbGV0L2NvbmZpZy5qc29uIgpwYXVzZV9pbWFnZSA9ICJxdWF5LmlvL29wZW5zaGlmdC1yZWxlYXNlLWRldi9vY3AtdjQuMC1hcnQtZGV2QHNoYTI1NjoyZGMzYmRjYjJiMGJmMWQ2YzZhZTc0OWJlMDE2M2U2ZDdjYTgxM2VjZmJhNWU1ZjVkODg5NzBjNzNhOWQxMmE5IgpwYXVzZV9pbWFnZV9hdXRoX2ZpbGUgPSAiL3Zhci9saWIva3ViZWxldC9jb25maWcuanNvbiIKcGF1c2VfY29tbWFuZCA9ICIvdXNyL2Jpbi9wb2QiCltjcmlvLm5ldHdvcmtdCm5ldHdvcmtfZGlyID0gIi9ldGMva3ViZXJuZXRlcy9jbmkvbmV0LmQvIgpwbHVnaW5fZGlycyA9IFsKICAgICIvdmFyL2xpYi9jbmkvYmluIiwKXQpbY3Jpby5tZXRyaWNzXQplbmFibGVfbWV0cmljcyA9IHRydWUKbWV0cmljc19wb3J0ID0gOTUzNw==\n        filesystem: root\n        mode: 0644\n        path: /etc/crio/crio.conf\nEOF\"\n\nrunuser -l $SUDOUSER -c \"cat > $OCPTEMPLATES/chrony-mc.yaml <<EOF\n---\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: worker\n  name: 90-worker-chrony\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,cG9vbCAyLnJoZWwucG9vbC5udHAub3JnIGlidXJzdApkcmlmdGZpbGUgL3Zhci9saWIvY2hyb255L2RyaWZ0Cm1ha2VzdGVwIDEuMCAzCnJ0Y3N5bmMKbG9nZGlyIC92YXIvbG9nL2Nocm9ueQpyZWZjbG9jayBQSEMgL2Rldi9wdHAwIHBvbGwgMyBkcG9sbCAtMiBvZmZzZXQgMAo=\n        filesystem: root\n        mode: 0644\n        path: /etc/chrony.conf\n---\napiVersion: machineconfiguration.openshift.io/v1\nkind: MachineConfig\nmetadata:\n  labels:\n    machineconfiguration.openshift.io/role: master\n  name: 90-master-chrony\nspec:\n  config:\n    ignition:\n      version: 2.2.0\n    storage:\n      files:\n      - contents:\n          source: data:text/plain;charset=utf-8;base64,cG9vbCAyLnJoZWwucG9vbC5udHAub3JnIGlidXJzdApkcmlmdGZpbGUgL3Zhci9saWIvY2hyb255L2RyaWZ0Cm1ha2VzdGVwIDEuMCAzCnJ0Y3N5bmMKbG9nZGlyIC92YXIvbG9nL2Nocm9ueQpyZWZjbG9jayBQSEMgL2Rldi9wdHAwIHBvbGwgMyBkcG9sbCAtMiBvZmZzZXQgMAo=\n        filesystem: root\n        mode: 0644\n        path: /etc/chrony.conf\nEOF\"\n\nrunuser -l $SUDOUSER -c \"sudo mv $OCPTEMPLATES/registries.conf /etc/containers/registries.conf\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCPTEMPLATES/insecure-registry-mc.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCPTEMPLATES/sysctl-mc.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCPTEMPLATES/limits-mc.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCPTEMPLATES/crio-mc.yaml\"\nrunuser -l $SUDOUSER -c \"oc create -f $OCPTEMPLATES/chrony-mc.yaml\"\n\nrunuser -l $SUDOUSER -c \"echo 'Sleeping for 12mins while MCs apply and the cluster restarts' \"\nrunuser -l $SUDOUSER -c \"sleep 12m\"\n\necho \"$(date) - ############### Script Complete #############\"", "num_lines": 164}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nyum update -y --disablerepo=* --enablerepo=\"*microsoft*\"\nyum install -y nfs-utils\nyum install -y rpcbind\nsystemctl unmask firewalld\nsystemctl start firewalld\nsystemctl start nfs-server\nsystemctl enable nfs-server\nmkdir -p /exports/home\necho \"/exports/home *(rw,sync,subtree_check,no_root_squash)\" >> /etc/exports\nmkfs.xfs /dev/sdc\nsleep 10\nmount /dev/sdc /exports/home\nchown -R nfsnobody:nfsnobody /exports/home\nchmod -R 777 /exports/home\nexportfs -a\nfirewall-cmd --permanent --add-service=mountd\nfirewall-cmd --permanent --add-service=nfs\nfirewall-cmd --permanent --add-service=rpc-bind\nfirewall-cmd --reload\necho \"$(sudo blkid | grep /dev/sdc | awk '{print $2}') /exports/home        xfs     defaults    0 0\" >> /etc/fstab", "num_lines": 21}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ./lustre_configure.sh -n MDS -i 1 -d 4 -m 10.1.0.4 -l 10.1.0.4 -f scratch\n# ./lustre_configure.sh -n OSS -i 1 -d 4 -m 10.1.0.4 -l 10.1.0.4 -f scratch\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"$1\"\n}\n\n# Initialize local variables\n# Get today's date into YYYYMMDD format\nNOW=$(date +\"%Y%m%d\")\nDEVICES_BLACKLIST=\"/dev/sda|/dev/sdb\"\nDEVICES_LIST=($(ls -1 /dev/sd* | egrep -v \"${DEVICES_BLACKLIST}\" | egrep -v \"[0-9]$\"))\n\n# Get command line parameters\nwhile getopts \"n:i:d:m:l:f:\" opt; do\n\tlog \"Option $opt set with value ${OPTARG})\"\n\tcase \"$opt\" in\n\tn)\tNODETYPE=$OPTARG\n\t\t;;\n\ti)\tNODEINDEX=$OPTARG\n\t\t;;\n\td)\tNODETYPEDISKCOUNT=$OPTARG\n\t\t;;\n\tm)\tMGSIP=$OPTARG\n\t\t;;\n\tl)\tLOCALIP=$OPTARG\n\t\t;;\n\tf)\tFILESYSTEMNAME=$OPTARG\n\t\t;;\n\tesac\ndone\n\nfatal() {\n    msg=${1:-\"Unknown Error\"}\n    log \"FATAL ERROR: $msg\"\n    exit 1\n}\n\n# Retries a command on failure.\n# $1 - the max number of attempts\n# $2... - the command to run\nretry() {\n    local -r -i max_attempts=\"$1\"; shift\n    local -r cmd=\"$@\"\n    local -i attempt_num=1\n\n    until $cmd\n    do\n        if (( attempt_num == max_attempts ))\n        then\n            log \"Command $cmd attempt $attempt_num failed and there are no more attempts left!\"\n\t\t\treturn 1\n        else\n            log \"Command $cmd attempt $attempt_num failed. Trying again in 5 + $attempt_num seconds...\"\n            sleep $(( 5 + attempt_num++ ))\n        fi\n    done\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ]; then\n    fatal \"You must be root to run this script.\"\nfi\n\nif [[ -z ${NODETYPE} ]]; then\n    fatal \"No node type specified, can't proceed.\"\nfi\n\nif [[ -z ${NODEINDEX} ]]; then\n    fatal \"No node index specified, can't proceed.\"\nfi\n\nif [[ -z ${NODETYPEDISKCOUNT} ]]; then\n    fatal \"No node type disk count specified, can't proceed.\"\nfi\n\nif [[ -z ${MGSIP} ]]; then\n    fatal \"No MGS IP specified, can't proceed.\"\nfi\n\nif [[ -z ${LOCALIP} ]]; then\n    fatal \"No local IP specified, can't proceed.\"\nfi\n\nif [[ -z ${FILESYSTEMNAME} ]]; then\n    fatal \"No filesystem name specified, can't proceed.\"\nfi\n\nlog \"NOW=$NOW NODETYPE=$NODETYPE NODEINDEX=$NODEINDEX MGSIP=$MGSIP LOCALIP=$LOCALIP FILESYSTEMNAME=$FILESYSTEMNAME\"\n\nadd_to_fstab() {\n\tdevice=\"${1}\"\n\tmount_point=\"${2}\"\n\tif grep -q \"$device\" /etc/fstab\n\tthen\n\t\tlog \"Not adding $device to /etc/fstab (it's  already there)\"\n\telse\n\t\tline=\"$device $mount_point lustre defaults,_netdev 0 0\"\n\t\tlog \"${line}\"\n\t\techo -e \"${line}\" >> /etc/fstab\n\tfi\n}\n\ncreate_mgs() {\n\tlog \"Create MGS\"\n\n\t# Make MGS filesystem which is always on /dev/sdc of the MGS node\n\tmkfs.lustre --fsname=$FILESYSTEMNAME --mgs --reformat /dev/sdc\n\n\tuuid=$(blkid -o value -s UUID /dev/sdc)\n\tlog \"MGS UUID=$uuid\"\n\n\tlabel=$(blkid -c/dev/null -o value -s LABEL /dev/sdc)\n\tlog \"MGS LABEL=$label\"\n\n\t# Log device info\n\tdumpe2fs -h /dev/sdc | logger\n\n\t# Create mount directory\n\tmount_point=/mnt/targets/$label\n\tmkdir -p $mount_point\n\tlog \"Created mount point directory $mount_point\"\n\n\t# Add to /etc/fstab so that mount persists across reboots\n\tdevice_by_uuid=\"UUID=$uuid\"\n\tadd_to_fstab $device_by_uuid $mount_point\n\n\tretry 5 mount -a\n\tlog \"Mounted /dev/sdc as $mount_point\"\n}\n\ncreate_mds() {\n\tlog \"Create MDS\"\n\n\t((index=$NODEINDEX*$NODETYPEDISKCOUNT))\n\n\tfor device in \"${DEVICES_LIST[@]}\";\n\tdo\n\t\tlog $device $index\n\n\t\tmkfs.lustre --fsname=$FILESYSTEMNAME --mdt --mgsnode=$MGSIP --index=$index --reformat $device\n\n\t\t# Disable MDS check of user being the same on the clients and MDS nodes\n\t\ttunefs.lustre --param mdt.identity_upcall=NONE $device\n\n\t\tuuid=$(blkid -o value -s UUID $device)\n\t\tlog \"MDS UUID=$uuid\"\n\n\t\tlabel=$(blkid -c/dev/null -o value -s LABEL $device)\n\t\tlog \"MDS LABEL=$label\"\n\n\t\tdumpe2fs -h $device | logger\n\n\t\t# Create mount directory\n\t\tmount_point=/mnt/targets/$label\n\t\tmkdir -p $mount_point\n\t\tlog \"Created mount point directory $mount_point\"\n\n\t\t# Mount the current device\n\t\tmount -t lustre $device $mount_point\n\n\t\t# Add to /etc/fstab so that mount persists across reboots\n\t\tdevice_by_uuid=\"UUID=$uuid\"\n\t\tadd_to_fstab $device_by_uuid $mount_point\n\n\t\t((index=index+1))\n\tdone\n\n\t# Mount everything based on what is defined in the /etc/fstab\n\tretry 5 mount -a\n}\n\ncreate_oss() {\n\tlog \"Create OSS\"\n\n\t((index=$NODEINDEX*$NODETYPEDISKCOUNT))\n\n\tfor device in \"${DEVICES_LIST[@]}\";\n\tdo\n\t\tlog $device $index\n\n\t\tmkfs.lustre --fsname=$FILESYSTEMNAME --ost --mgsnode=$MGSIP --index=$index --reformat $device\n\n\t\tuuid=$(blkid -o value -s UUID $device)\n\t\tlog \"OSS UUID=$uuid\"\n\n\t\tlabel=$(blkid -c/dev/null -o value -s LABEL $device)\n\t\tlog \"OSS LABEL=$label\"\n\n\t\tdumpe2fs -h $device | logger\n\n\t\t# Create mount directory\n\t\tmount_point=/mnt/targets/$label\n\t\tmkdir -p $mount_point\n\t\tlog \"Created mount point directory $mount_point\"\n\n\t\t# Mount the current device\n\t\tmount -t lustre $device $mount_point\n\n\t\t# Add to /etc/fstab so that mount persists across reboots\n\t\tdevice_by_uuid=\"UUID=$uuid\"\n\t\tadd_to_fstab $device_by_uuid $mount_point\n\n\t\t((index=index+1))\n\tdone\n\n\t# Random sleep to minimize chance of mount error\n\tsleep $[ ( $RANDOM % 20 ) + 1]s\n\n\t# Mount everything based on what is defined in the /etc/fstab\n\tretry 5 mount -a\n}\n\nif [ \"$NODETYPE\" == \"MGS\" ]; then\n\tcreate_mgs\nfi\n\nif [ \"$NODETYPE\" == \"MDS\" ]; then\n\tcreate_mds\nfi\n\nif [ \"$NODETYPE\" == \"OSS\" ]; then\n\tcreate_oss\nfi\n", "num_lines": 229}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ./lustre_client.sh -n CLIENTCENTOS7.0 -i 0 -d 0 -m 10.1.0.4 -l 10.1.0.7 -f scratch\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"$1\"\n}\n\n# Initialize local variables\n# Get today's date into YYYYMMDD format\nNOW=$(date +\"%Y%m%d\")\nFILESYSTEMSTRIPECOUNT=-1\n\n# Get command line parameters\nwhile getopts \"n:i:d:m:l:f:\" opt; do\n\tlog \"Option $opt set with value ${OPTARG})\"\n\tcase \"$opt\" in\n\tn)\tNODETYPE=$OPTARG\n\t\t;;\n\ti)\tNODEINDEX=$OPTARG\n\t\t;;\n\td)\tNODETYPEDISKCOUNT=$OPTARG\n\t\t;;\n\tm)\tMGSIP=$OPTARG\n\t\t;;\n\tl)\tLOCALIP=$OPTARG\n\t\t;;\n\tf)\tFILESYSTEMNAME=$OPTARG\n\t\t;;\n\tesac\ndone\n\nfatal() {\n    msg=${1:-\"Unknown Error\"}\n    log \"FATAL ERROR: $msg\"\n    exit 1\n}\n\n# Retries a command on failure.\n# $1 - the max number of attempts\n# $2... - the command to run\nretry() {\n    local -r -i max_attempts=\"$1\"; shift\n    local -r cmd=\"$@\"\n    local -i attempt_num=1\n\n    until $cmd\n    do\n        if (( attempt_num == max_attempts ))\n        then\n            log \"Command $cmd attempt $attempt_num failed and there are no more attempts left!\"\n\t\t\treturn 1\n        else\n            log \"Command $cmd attempt $attempt_num failed. Trying again in 5 + $attempt_num seconds...\"\n            sleep $(( 5 + attempt_num++ ))\n        fi\n    done\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ]; then\n    fatal \"You must be root to run this script.\"\nfi\n\nif [[ -z ${NODETYPE} ]]; then\n    fatal \"No node type specified, can't proceed.\"\nfi\n\nif [[ -z ${NODEINDEX} ]]; then\n    fatal \"No node index specified, can't proceed.\"\nfi\n\nif [[ -z ${NODETYPEDISKCOUNT} ]]; then\n    fatal \"No node type disk count specified, can't proceed.\"\nfi\n\nif [[ -z ${MGSIP} ]]; then\n    fatal \"No MGS IP specified, can't proceed.\"\nfi\n\nif [[ -z ${LOCALIP} ]]; then\n    fatal \"No local IP specified, can't proceed.\"\nfi\n\nif [[ -z ${FILESYSTEMNAME} ]]; then\n    fatal \"No filesystem name specified, can't proceed.\"\nfi\n\nlog \"NOW=$NOW NODETYPE=$NODETYPE NODEINDEX=$NODEINDEX MGSIP=$MGSIP LOCALIP=$LOCALIP FILESYSTEMNAME=$FILESYSTEMNAME\"\n\nadd_to_fstab() {\n\tdevice=\"${1}\"\n\tmount_point=\"${2}\"\n\tif grep -q \"$device\" /etc/fstab\n\tthen\n\t\tlog \"Not adding $device to /etc/fstab (it's  already there)\"\n\telse\n\t\tline=\"$device $mount_point lustre defaults,_netdev 0 0\"\n\t\tlog $LINE\n\t\techo -e \"${line}\" >> /etc/fstab\n\tfi\n}\n\ninstall_lustre_centos66()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Install pdsh since it is convenient for managing multiple client hosts later\n\t# RHEL/CentOS 6 64-Bit ##\n\twget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm\n\trpm -ivh epel-release-6-8.noarch.rpm\n\tyum install -y pdsh\n\n\t# Download stable Lustre client source targeting specific CentOS 6.6 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.hpdd.intel.com/public/lustre/lustre-2.7.0/el6.6/client/SRPMS/lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/6.6/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15  http://vault.centos.org/6.6/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. lustre-client-2.7.0-2.6.32_504.30.3.el6.x86_64.x86_64.rpm)\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ninstall_lustre_centos70()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Download stable Lustre client source targeting specific CentOS 7.0 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.hpdd.intel.com/public/lustre/lustre-2.7.0/el7/client/SRPMS/lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. )\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ncreate_client() {\n\tlog \"Create Lustre CLIENT\"\n\n\tdevice=$MGSIP@tcp:/$FILESYSTEMNAME\n\tlog \"DEVICE $device\"\n\n\tmount_point=/mnt/$FILESYSTEMNAME\n\tlog \"MOUNT_POINT $mount_point\"\n\n\tmkdir -p $mount_point\n\tadd_to_fstab $device $mount_point\n\tretry 5 mount -a\n\n\t# Create test file\n\tdd if=/dev/zero of=$mount_point/test_$(hostname).dat bs=1M count=200\n\n\tcd $mount_point\n\tls -lsah\n\n\t# Display stripe configuration\n\tlfs getstripe $mount_point\n\n\t# Display free space\n\tlfs df -h\n}\n\nif [ \"$NODETYPE\" == \"CLIENTCENTOS6.6\" ]; then\n\tinstall_lustre_centos66\n\tcreate_client\nfi\n\nif [ \"$NODETYPE\" == \"CLIENTCENTOS7.0\" ]; then\n\tinstall_lustre_centos70\n\tcreate_client\nfi\n", "num_lines": 225}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ./monitoring_configure.sh -n MGS -i 1 -d 4 -m 10.1.0.4 -l 10.1.0.4 -f scratch -g 10.1.0.5 -h 10.1.0.6\n# ./monitoring_configure.sh -n MDS -i 1 -d 4 -m 10.1.0.4 -l 10.1.0.5 -f scratch -g 10.1.0.5 -h 10.1.0.6\n# ./monitoring_configure.sh -n OSS -i 1 -d 4 -m 10.1.0.4 -l 10.1.0.6 -f scratch -g 10.1.0.5 -h 10.1.0.6\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"$1\"\n}\n\n# Initialize local variables\n# Get today's date into YYYYMMDD format\nNOW=$(date +\"%Y%m%d%H%M\")\n\n# Get command line parameters\nwhile getopts \"n:i:d:m:l:f:g:h:\" opt; do\n\tlog \"Option $opt set with value ${OPTARG})\"\n\tcase \"$opt\" in\n\tn)\tNODETYPE=$OPTARG\n\t\t;;\n\ti)\tNODEINDEX=$OPTARG\n\t\t;;\n\td)\tNODETYPEDISKCOUNT=$OPTARG\n\t\t;;\n\tm)\tMGSIP=$OPTARG\n\t\t;;\n\tl)\tLOCALIP=$OPTARG\n\t\t;;\n\tf)\tFILESYSTEMNAME=$OPTARG\n\t\t;;\n\tg)\tMDSIP0=$OPTARG\n\t\t;;\n\th)\tOSSIP0=$OPTARG\n\t\t;;\n\tesac\ndone\n\nfatal() {\n    msg=${1:-\"Unknown Error\"}\n    log \"FATAL ERROR: $msg\"\n    exit 1\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ]; then\n    fatal \"You must be root to run this script.\"\nfi\n\nif [[ -z ${NODETYPE} ]]; then\n    fatal \"No node type specified, can't proceed.\"\nfi\n\nif [[ -z ${NODEINDEX} ]]; then\n    fatal \"No node index specified, can't proceed.\"\nfi\n\nif [[ -z ${NODETYPEDISKCOUNT} ]]; then\n    fatal \"No node type disk count specified, can't proceed.\"\nfi\n\nif [[ -z ${MGSIP} ]]; then\n    fatal \"No MGS IP specified, can't proceed.\"\nfi\n\nif [[ -z ${LOCALIP} ]]; then\n    fatal \"No local IP specified, can't proceed.\"\nfi\n\nif [[ -z ${FILESYSTEMNAME} ]]; then\n    fatal \"No filesystem name specified, can't proceed.\"\nfi\n\nif [[ -z ${MDSIP0} ]]; then\n    fatal \"No MDSIP0 specified, can't proceed.\"\nfi\n\nif [[ -z ${OSSIP0} ]]; then\n    fatal \"No OSSIP0 specified, can't proceed.\"\nfi\n\nlog \"MONITORING CONFIGURE: NOW=$NOW NODETYPE=$NODETYPE NODEINDEX=$NODEINDEX NODETYPEDISKCOUNT=$NODETYPEDISKCOUNT MGSIP=$MGSIP LOCALIP=$LOCALIP FILESYSTEMNAME=$FILESYSTEMNAME MDSIP0=$MDSIP0 OSSIP0=$OSSIP0\"\n\nadd_to_fstab() {\n\tdevice=\"${1}\"\n\tmount_point=\"${2}\"\n\tfilesystem_type=\"${3}\"\n\n\tif grep -q \"$device\" /etc/fstab\n\tthen\n\t\tlog \"Not adding $device to /etc/fstab (it's  already there)\"\n\telse\n\t\tline=\"$device $mount_point $filesystem_type defaults 0 0\"\n\t\tlog $line\n\t\techo -e \"${line}\" >> /etc/fstab\n\tfi\n}\n\nsetup_ganglia_collector() {\n\n\t# Device /dev/sdd on MGS node is reserved for the Ganglia round-robin database files\n\tdevice=\"/dev/sdd\"\n\tdevice_label=\"GANGLIA_RRDS\"\n\n\t# Format volume (if necessary) as ext4 (i.e. not lustre)\n\tmount_ganglia=\"/mnt/ganglia/\"\n\tmount_rrds=\"/mnt/ganglia/rrds\"\n\n\t# Check device label\n\tlabel=$(blkid -c/dev/null -o value -s LABEL $device)\n\n\tif [ -z \"$label\" ];\n\tthen\n\t\t# Format the device ext4\n\t\tlog \"Formatting $device with label $device_label...\"\n\t\tmke2fs -j -L \"$device_label\" $device\n\telse\n\t\tlog \"Device $device is already formatted with label $label\"\n\tfi\n\n\t# Store ganglia RRDs here in /mnt/ganglia/rrds\n\tmkdir -p $mount_ganglia\n\n\t# Add to /etc/fstab so that mount persists across reboots\n\tadd_to_fstab $device $mount_ganglia \"ext4\"\n\n\t# Mount\n\tmount -a\n\tlog \"Mounted $device with label $device_label as $mount_ganglia\"\n\n\tmkdir -p $mount_rrds\n\tchown ganglia.ganglia $mount_rrds\n\n\tline=\"rrd_rootdir $mount_rrds\"\n\tif grep -q \"$line\" /etc/ganglia/gmetad.conf\n\tthen\n\t\tlog \"Not adding $line to /etc/ganglia/gmetad.conf (it's already there)\"\n\telse\n\t\tlog \"${line}\"\n\t\techo -e  \"${line}\" >> /etc/ganglia/gmetad.conf\n\tfi\n\n\t# Point ganglia_web to the proper RRDs location\n\tif grep -q \"$mount_rrds\" /etc/ganglia/conf.php\n\tthen\n\t\tlog \"Not adding $mount_rrds to /etc/ganglia/conf.php (it's already there)\"\n\telse\n\t\t# Use , instead of / in the sed command since / is used in the $mount_rrds variable\n\t\tsed -i \"s,<?php.*$,<?php\\n\\$conf['rrds'] = \\\"$mount_rrds\\\";,\" /etc/ganglia/conf.php\n\tfi\n}\n\nsetup_ganglia() {\n\tmaster_ip=\"${1}\"\n\tcluster_name=\"${2}\"\n\tis_collector=\"${3}\"\n\n\t# Configure gmond on the local node\n\t# Multicast is disabled and unicast will be used to send metrics to master_ip\n\n\t# Comment out lines that start with \"mcast_join\"\" or \"bind\"\n\tsed -i '/mcast_join/s/^/#/' /etc/ganglia/gmond.conf\n\tsed -i '/bind/s/^/#/' /etc/ganglia/gmond.conf\n\n\t# Replace substrings for cluster name, send interval, and udp send channel host\n\tsed -i \"s/name\\s*=\\s*\\\"unspecified\\\"/name = \\\"$cluster_name\\\"/\" /etc/ganglia/gmond.conf\n\tsed -i \"s/owner\\s*=\\s*\\\"unspecified\\\"/owner = \\\"$cluster_name\\\"/\" /etc/ganglia/gmond.conf\n\tsed -i \"s/send_metadata_interval\\s*=\\s*0/send_metadata_interval = 10/\" /etc/ganglia/gmond.conf\n\tsed -i \"s/udp_send_channel\\s*{.*$/udp_send_channel {\\n host = $master_ip/\" /etc/ganglia/gmond.conf\n\n\t# Disable modules (by appending -disabled to its config file name) that result in many /var/log/messages errors\n\tif [ -e /etc/ganglia/conf.d/netstats.pyconf ]; then\n\t\tmv /etc/ganglia/conf.d/netstats.pyconf /etc/ganglia/conf.d/netstats.pyconf-disabled\n\tfi\n\n\tif [ -e /etc/ganglia/conf.d/diskstat.pyconf ]; then\n\t\tmv /etc/ganglia/conf.d/diskstat.pyconf /etc/ganglia/conf.d/diskstat.pyconf-disabled\n\tfi\n\n\tservice gmond restart\n\tchkconfig gmond on\n\n\t# Allow gmond service time to start before starting the gmetad\n\tsleep 10\n\n\tif [ \"$is_collector\" = true ] ; then\n\t\tservice gmetad restart\n\t\tchkconfig gmetad on\n\tfi\n}\n\nsetup_ganglia_web() {\n\t# Comment out the Deny from all line\n\tsed -i '/Deny from all/s/^/#/' /etc/httpd/conf.d/ganglia.conf\n\n\tif grep -q \"strip_domainname\" /etc/ganglia/conf.php\n\tthen\n\t\tlog \"Not adding strip_domainname to /etc/ganglia/conf.php (it's already there)\"\n\telse\n\t\tsed -i \"s/<?php.*$/<?php\\n\\$conf['strip_domainname'] = true;/\" /etc/ganglia/conf.php\n\tfi\n\n\tservice httpd restart\n\tchkconfig httpd on\n}\n\nganglia_gmetad_add_source() {\n\tip_to_poll=\"${1}\"\n\tcluster_name=\"${2}\"\n\n\tline=\"gridname \\\"$FILESYSTEMNAME\\\"\"\n\tif grep -q \"$line\" /etc/ganglia/gmetad.conf\n\tthen\n\t\tlog \"Not adding $line to /etc/ganglia/gmetad.conf (it's already there)\"\n\telse\n\t\tlog \"${line}\"\n\t\techo -e  \"${line}\" >> /etc/ganglia/gmetad.conf\n\tfi\n\n\tline=\"data_source \\\"$cluster_name\\\" $ip_to_poll\"\n\tif grep -q \"$line\" /etc/ganglia/gmetad.conf\n\tthen\n\t\tlog \"Not adding $line to /etc/ganglia/gmetad.conf (it's already there)\"\n\telse\n\t\tlog \"${line}\"\n\t\techo -e  \"${line}\" >> /etc/ganglia/gmetad.conf\n\n\t\tservice gmetad restart\n\t\tchkconfig gmetad on\n\tfi\n}\n\nsetup_lmt_collector() {\n\tmgs_ip=\"${MGSIP}\"\n\n\t# LMT collector is the MGS node (master LMT server)\n\tline=\"cerebrod_speak_message_config $mgs_ip\"\n\tif grep -q \"$line\" /etc/cerebro.conf\n\tthen\n\t\tlog \"Not adding $line to /etc/cerebro.conf (it's already there)\"\n\telse\n\t\tlog \"${line}\"\n\t\techo -e  \"${line}\" >> /etc/cerebro.conf\n\n\t\tline=\"cerebrod_listen_message_config $mgs_ip\"\n\t\tlog \"${line}\"\n\t\techo -e \"${line}\" >> /etc/cerebro.conf\n\n\t\tservice cerebrod restart\n\t\tchkconfig cerebrod on\n\tfi\n}\n\nsetup_lmt_agent() {\n\tmgs_ip=\"${1}\"\n\n\t# LMT agent is on MDS and OSS nodes\n\tline=\"cerebrod_speak_message_config $mgs_ip\"\n\tif grep -q \"$line\" /etc/cerebro.conf\n\tthen\n\t\tlog \"Not adding $line to /etc/cerebro.conf (it's already there)\"\n\telse\n\t\tlog \"${line}\"\n\t\techo -e  \"${line}\" >> /etc/cerebro.conf\n\n\t\tservice cerebrod restart\n\t\tchkconfig cerebrod on\n\tfi\n}\n\nconfigure_mgs() {\n\tlog \"Configure monitoring on MGS\"\n\n\tsetup_ganglia_collector\n\tsetup_ganglia $MGSIP \"MGS\" false\n\tsetup_ganglia_web\n\tganglia_gmetad_add_source $MDSIP0 \"MDS\"\n\tganglia_gmetad_add_source $OSSIP0 \"OSS\"\n\n\tsetup_lmt_collector $MGSIP\n}\n\nconfigure_mds() {\n\tlog \"Configuring monitoring on MDS\"\n\n\tsetup_ganglia $MDSIP0 \"MDS\" false\n\n\tsetup_lmt_agent $MGSIP\n}\n\nconfigure_oss() {\n\tlog \"Configure monitoring on OSS\"\n\n\tsetup_ganglia $OSSIP0 \"OSS\" false\n\n\tsetup_lmt_agent $MGSIP\n}\n\n# Make a copy of the original files\nlog \"Backup up previous versions of the configuration files with $NOW and .backup extension\"\ncp /etc/httpd/conf.d/ganglia.conf /etc/httpd/conf.d/ganglia.conf_$NOW.backup\ncp /etc/ganglia/conf.php /etc/ganglia/conf.php_$NOW.backup\ncp /etc/ganglia/gmetad.conf /etc/ganglia/gmetad.conf_$NOW.backup\ncp /etc/cerebro.conf /etc/cerebro.conf_$NOW.backup\n\nif [ \"$NODETYPE\" == \"MGS\" ]; then\n\tconfigure_mgs\nfi\n\nif [ \"$NODETYPE\" == \"MDS\" ]; then\n\tconfigure_mds\nfi\n\nif [ \"$NODETYPE\" == \"OSS\" ]; then\n\tconfigure_oss\nfi\n", "num_lines": 318}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ./lustre_client.sh -n CLIENTCENTOS7.0 -i 0 -d 0 -m 10.1.0.4 -l 10.1.0.7 -f scratch\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"$1\"\n}\n\n# Initialize local variables\n# Get today's date into YYYYMMDD format\nNOW=$(date +\"%Y%m%d\")\nFILESYSTEMSTRIPECOUNT=-1\n\n# Get command line parameters\nwhile getopts \"n:i:d:m:l:f:\" opt; do\n\tlog \"Option $opt set with value ${OPTARG})\"\n\tcase \"$opt\" in\n\tn)\tNODETYPE=$OPTARG\n\t\t;;\n\ti)\tNODEINDEX=$OPTARG\n\t\t;;\n\td)\tNODETYPEDISKCOUNT=$OPTARG\n\t\t;;\n\tm)\tMGSIP=$OPTARG\n\t\t;;\n\tl)\tLOCALIP=$OPTARG\n\t\t;;\n\tf)\tFILESYSTEMNAME=$OPTARG\n\t\t;;\n\tesac\ndone\n\nfatal() {\n    msg=${1:-\"Unknown Error\"}\n    log \"FATAL ERROR: $msg\"\n    exit 1\n}\n\n# Retries a command on failure.\n# $1 - the max number of attempts\n# $2... - the command to run\nretry() {\n    local -r -i max_attempts=\"$1\"; shift\n    local -r cmd=\"$@\"\n    local -i attempt_num=1\n\n    until $cmd\n    do\n        if (( attempt_num == max_attempts ))\n        then\n            log \"Command $cmd attempt $attempt_num failed and there are no more attempts left!\"\n\t\t\treturn 1\n        else\n            log \"Command $cmd attempt $attempt_num failed. Trying again in 5 + $attempt_num seconds...\"\n            sleep $(( 5 + attempt_num++ ))\n        fi\n    done\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ]; then\n    fatal \"You must be root to run this script.\"\nfi\n\nif [[ -z ${NODETYPE} ]]; then\n    fatal \"No node type specified, can't proceed.\"\nfi\n\nif [[ -z ${NODEINDEX} ]]; then\n    fatal \"No node index specified, can't proceed.\"\nfi\n\nif [[ -z ${NODETYPEDISKCOUNT} ]]; then\n    fatal \"No node type disk count specified, can't proceed.\"\nfi\n\nif [[ -z ${MGSIP} ]]; then\n    fatal \"No MGS IP specified, can't proceed.\"\nfi\n\nif [[ -z ${LOCALIP} ]]; then\n    fatal \"No local IP specified, can't proceed.\"\nfi\n\nif [[ -z ${FILESYSTEMNAME} ]]; then\n    fatal \"No filesystem name specified, can't proceed.\"\nfi\n\nlog \"NOW=$NOW NODETYPE=$NODETYPE NODEINDEX=$NODEINDEX MGSIP=$MGSIP LOCALIP=$LOCALIP FILESYSTEMNAME=$FILESYSTEMNAME\"\n\nadd_to_fstab() {\n\tdevice=\"${1}\"\n\tmount_point=\"${2}\"\n\tif grep -q \"$device\" /etc/fstab\n\tthen\n\t\tlog \"Not adding $device to /etc/fstab (it's  already there)\"\n\telse\n\t\tline=\"$device $mount_point lustre defaults,_netdev 0 0\"\n\t\tlog $LINE\n\t\techo -e \"${line}\" >> /etc/fstab\n\tfi\n}\n\ninstall_lustre_centos66()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Install pdsh since it is convenient for managing multiple client hosts later\n\t# RHEL/CentOS 6 64-Bit ##\n\twget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm\n\trpm -ivh epel-release-6-8.noarch.rpm\n\tyum install -y pdsh\n\n\t# Download stable Lustre client source targeting specific CentOS 6.6 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.whamcloud.com/public/lustre/lustre-2.7.0/el6.6/client/SRPMS/lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/6.6/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15  http://vault.centos.org/6.6/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. lustre-client-2.7.0-2.6.32_504.30.3.el6.x86_64.x86_64.rpm)\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ninstall_lustre_centos70()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Download stable Lustre client source targeting specific CentOS 7.0 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.whamcloud.com/public/lustre/lustre-2.7.0/el7/client/SRPMS/lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. )\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ninstall_lustre_centos_hpc_65()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Install pdsh since it is convenient for managing multiple client hosts later\n\t# RHEL/CentOS 6 64-Bit ##\n\twget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm\n\trpm -ivh epel-release-6-8.noarch.rpm\n\tyum install -y pdsh\n\n\t# Download stable Lustre client source targeting specific CentOS 6.5 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.whamcloud.com/public/lustre/lustre-2.7.0/el6.6/client/SRPMS/lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/6.5/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/6.5/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Un-exclude kernel updates in /etc/yum.conf\n\tsed \"s/exclude=/#exclude=/g\" -i /etc/yum.conf\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. )\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n\n\t# Again exclude kernel updates in /etc/yum.conf\n\tsed \"s/#exclude=/exclude=/g\" -i /etc/yum.conf\n}\n\ninstall_lustre_centos_hpc_71()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Download stable Lustre client source targeting specific CentOS 7.0 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.whamcloud.com/public/lustre/lustre-2.7.0/el7/client/SRPMS/lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.1.1503/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.1.1503/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Un-exclude kernel updates in /etc/yum.conf\n\tsed \"s/exclude=/#exclude=/g\" -i /etc/yum.conf\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. )\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n\n\t# Again exclude kernel updates in /etc/yum.conf\n\tsed \"s/#exclude=/exclude=/g\" -i /etc/yum.conf\n}\n\ncreate_client() {\n\tlog \"Create Lustre CLIENT\"\n\n\tdevice=$MGSIP@tcp:/$FILESYSTEMNAME\n\tlog \"DEVICE $device\"\n\n\tmount_point=/mnt/$FILESYSTEMNAME\n\tlog \"MOUNT_POINT $mount_point\"\n\n\tmkdir -p $mount_point\n\tadd_to_fstab $device $mount_point\n\tretry 5 mount -a\n\n\t# Create test file\n\tdd if=/dev/zero of=$mount_point/test_$(hostname).dat bs=1M count=200\n\n\tcd $mount_point\n\tls -lsah\n\n\t# Display stripe configuration\n\tlfs getstripe $mount_point\n\n\t# Display free space\n\tlfs df -h\n}\n\nif [ \"$NODETYPE\" == \"OpenLogic:CentOS:6.6\" ]; then\n\tinstall_lustre_centos66\n\tcreate_client\nfi\n\nif [ \"$NODETYPE\" == \"OpenLogic:CentOS:7.0\" ]; then\n\tinstall_lustre_centos70\n\tcreate_client\nfi\n\nif [ \"$NODETYPE\" == \"OpenLogic:CentOS-HPC:6.5\" ]; then\n\tinstall_lustre_centos_hpc_65\n\tcreate_client\nfi\n\nif [ \"$NODETYPE\" == \"OpenLogic:CentOS-HPC:7.1\" ]; then\n\tinstall_lustre_centos_hpc_71\n\tcreate_client\nfi\n", "num_lines": 343}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ./lustre_client.sh -n CLIENTCENTOS7.0 -i 0 -d 0 -m 10.1.0.4 -l 10.1.0.7 -f scratch\n\nlog()\n{\n\techo \"$1\"\n\tlogger \"$1\"\n}\n\n# Initialize local variables\n# Get today's date into YYYYMMDD format\nNOW=$(date +\"%Y%m%d\")\nFILESYSTEMSTRIPECOUNT=-1\n\n# Get command line parameters\nwhile getopts \"n:i:d:m:l:f:\" opt; do\n\tlog \"Option $opt set with value ${OPTARG})\"\n\tcase \"$opt\" in\n\tn)\tNODETYPE=$OPTARG\n\t\t;;\n\ti)\tNODEINDEX=$OPTARG\n\t\t;;\n\td)\tNODETYPEDISKCOUNT=$OPTARG\n\t\t;;\n\tm)\tMGSIP=$OPTARG\n\t\t;;\n\tl)\tLOCALIP=$OPTARG\n\t\t;;\n\tf)\tFILESYSTEMNAME=$OPTARG\n\t\t;;\n\tesac\ndone\n\nfatal() {\n    msg=${1:-\"Unknown Error\"}\n    log \"FATAL ERROR: $msg\"\n    exit 1\n}\n\n# Retries a command on failure.\n# $1 - the max number of attempts\n# $2... - the command to run\nretry() {\n    local -r -i max_attempts=\"$1\"; shift\n    local -r cmd=\"$@\"\n    local -i attempt_num=1\n\n    until $cmd\n    do\n        if (( attempt_num == max_attempts ))\n        then\n            log \"Command $cmd attempt $attempt_num failed and there are no more attempts left!\"\n\t\t\treturn 1\n        else\n            log \"Command $cmd attempt $attempt_num failed. Trying again in 5 + $attempt_num seconds...\"\n            sleep $(( 5 + attempt_num++ ))\n        fi\n    done\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ]; then\n    fatal \"You must be root to run this script.\"\nfi\n\nif [[ -z ${NODETYPE} ]]; then\n    fatal \"No node type specified, can't proceed.\"\nfi\n\nif [[ -z ${NODEINDEX} ]]; then\n    fatal \"No node index specified, can't proceed.\"\nfi\n\nif [[ -z ${NODETYPEDISKCOUNT} ]]; then\n    fatal \"No node type disk count specified, can't proceed.\"\nfi\n\nif [[ -z ${MGSIP} ]]; then\n    fatal \"No MGS IP specified, can't proceed.\"\nfi\n\nif [[ -z ${LOCALIP} ]]; then\n    fatal \"No local IP specified, can't proceed.\"\nfi\n\nif [[ -z ${FILESYSTEMNAME} ]]; then\n    fatal \"No filesystem name specified, can't proceed.\"\nfi\n\nlog \"NOW=$NOW NODETYPE=$NODETYPE NODEINDEX=$NODEINDEX MGSIP=$MGSIP LOCALIP=$LOCALIP FILESYSTEMNAME=$FILESYSTEMNAME\"\n\nadd_to_fstab() {\n\tdevice=\"${1}\"\n\tmount_point=\"${2}\"\n\tif grep -q \"$device\" /etc/fstab\n\tthen\n\t\tlog \"Not adding $device to /etc/fstab (it's  already there)\"\n\telse\n\t\tline=\"$device $mount_point lustre defaults,_netdev 0 0\"\n\t\tlog $LINE\n\t\techo -e \"${line}\" >> /etc/fstab\n\tfi\n}\n\ninstall_lustre_centos66()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Install pdsh since it is convenient for managing multiple client hosts later\n\t# RHEL/CentOS 6 64-Bit ##\n\twget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm\n\trpm -ivh epel-release-6-8.noarch.rpm\n\tyum install -y pdsh\n\n\t# Download stable Lustre client source targeting specific CentOS 6.6 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.hpdd.intel.com/public/lustre/lustre-2.7.0/el6.6/client/SRPMS/lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/6.6/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15  http://vault.centos.org/6.6/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-2.6.32_504.8.1.el6.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. lustre-client-2.7.0-2.6.32_504.30.3.el6.x86_64.x86_64.rpm)\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ninstall_lustre_centos70()\n{\n\t# Install wget and dstat\n\tyum install -y wget dstat\n\n\t# Update certificates to prevent wget download errors\n\tyum update -y ca-certificates\n\n\t# Download stable Lustre client source targeting specific CentOS 7.0 kernel\n\t# This code will be used to create the RPM for the currently running kernel\n\twget https://downloads.hpdd.intel.com/public/lustre/lustre-2.7.0/el7/client/SRPMS/lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Download current kernel-devel package from CentOS vault\n\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/updates/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tif [ ! -f  kernel-devel-$(uname -r).rpm ]; then\n\t\t# Try /os/\n\t\twget --tries 10 --retry-connrefused --waitretry 15 http://vault.centos.org/7.0.1406/os/x86_64/Packages/kernel-devel-$(uname -r).rpm\n\tfi\n\n\t# Install the downloaded kernel-devel package that is needed to recompile the Lustre client modules\n\tyum --nogpgcheck localinstall -y kernel-devel-$(uname -r).rpm\n\n\t# Install the other packages necessary to recompile the Lustre client\n\t# Documentation is here https://wiki.hpdd.intel.com/display/PUB/Rebuilding+the+Lustre-client+rpms+for+a+new+kernel\n\tyum install -y rpm-build make libtool libselinux-devel\n\n\t# Rebuild the downloaded Lustre client RPM for the currently running kernel\n\trpmbuild --define \"_topdir /root/rpmbuild\" --rebuild --without servers lustre-client-2.7.0-3.10.0_123.20.1.el7.x86_64.src.rpm\n\n\t# Install the compiled RPM whose file names are based on the currently running kernel but with - replaced by _ (e.g. )\n\tcd /root/rpmbuild/RPMS/x86_64/\n\tyum --nogpgcheck localinstall -y lustre-client-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm lustre-client-modules-2.7.0-$(uname -r | sed 's/-/_/').x86_64.rpm\n\n\tmodprobe lustre\n\n\t# To prevent the current kernel from being updated, add the following exclude line to [base] and [updates] in CentOS-Base.repo\n\texclude=\"exclude = kernel kernel-headers kernel-devel kernel-debug-devel\"\n\tsed \"/\\[base\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[updates\\]/a ${exclude}\" -i /etc/yum.repos.d/CentOS-Base.repo\n\tsed \"/\\[openlogic\\]/a ${exclude}\" -i /etc/yum.repos.d/OpenLogic.repo\n}\n\ncreate_client() {\n\tlog \"Create Lustre CLIENT\"\n\n\tdevice=$MGSIP@tcp:/$FILESYSTEMNAME\n\tlog \"DEVICE $device\"\n\n\tmount_point=/mnt/$FILESYSTEMNAME\n\tlog \"MOUNT_POINT $mount_point\"\n\n\tmkdir -p $mount_point\n\tadd_to_fstab $device $mount_point\n\tretry 5 mount -a\n\n\t# Create test file\n\tdd if=/dev/zero of=$mount_point/test_$(hostname).dat bs=1M count=200\n\n\tcd $mount_point\n\tls -lsah\n\n\t# Display stripe configuration\n\tlfs getstripe $mount_point\n\n\t# Display free space\n\tlfs df -h\n}\n\nif [ \"$NODETYPE\" == \"CLIENTCENTOS6.6\" ]; then\n\tinstall_lustre_centos66\n\tcreate_client\nfi\n\nif [ \"$NODETYPE\" == \"CLIENTCENTOS7.0\" ]; then\n\tinstall_lustre_centos70\n\tcreate_client\nfi\n", "num_lines": 231}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\napt-get -y install python-software-properties\nadd-apt-repository -y ppa:ondrej/php5-oldstable\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-client mysql-server php5\n\n# install iomad requirements\napt-get -y install graphviz aspell php5-pspell php5-curl php5-gd php5-intl php5-mysql php5-xmlrpc php5-ldap\n\n# Allow remote connection\nsed -i \"s/bind-address.*/bind-address = 0.0.0.0/\" /etc/mysql/my.cnf\n\n# create iomad database\nMYSQL=`which mysql`\n\nQ1=\"CREATE DATABASE moodle DEFAULT CHARACTER SET UTF8 COLLATE utf8_unicode_ci;\"\nQ2=\"GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,CREATE TEMPORARY TABLES,DROP,INDEX,ALTER ON moodle.* TO 'root'@'%' IDENTIFIED BY '$dbpass' WITH GRANT OPTION;\"\nQ3=\"FLUSH PRIVILEGES;\"\nSQL=\"${Q1}${Q2}${Q3}\"\n\n$MYSQL -uroot -p$dbpass -e \"$SQL\"\n\n# Create Azure file share that will be used by front end VM's for moodledata directory\nSharedStorageAccountName=$2\nSharedAzureFileName=$3\nSharedStorageAccountKey=$4\n\napt-get -y install nodejs-legacy\napt-get -y install npm\nnpm install -g azure-cli\n\nsudo azure storage share create $SharedAzureFileName -a $SharedStorageAccountName -k $SharedStorageAccountKey\n\n# restart MySQL\nservice mysql restart\n\n# restart Apache\napachectl restart\n", "num_lines": 49}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\napt-get -y install python-software-properties\nadd-apt-repository -y ppa:ondrej/php5-oldstable\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-client mysql-server php5\n\n# install iomad requirements\napt-get -y install graphviz aspell php5-pspell php5-curl php5-gd php5-intl php5-mysql php5-xmlrpc php5-ldap\n\n# add port 8000 for admin access\nperl -0777 -p -i -e 's/Listen 80/Listen 80\\nListen 8080/ig' /etc/apache2/ports.conf\nperl -0777 -p -i -e 's/\\*:80/*:80 *:8080/g' /etc/apache2/sites-enabled/000-default.conf\n\n# install iomad\ncd /var/www/html\nwget https://github.com/iomad/iomad/archive/IOMAD_29_STABLE.zip -O iomad.zip\napt-get install unzip\nunzip iomad.zip\ncp -r iomad-IOMAD_29_STABLE iomad\n\n# make the iomad directory writable for owner\nchown -R www-data iomad\nchmod -R 770 iomad\n\n# create moodledata directory\nmkdir /var/www/moodledata\nchown -R www-data /var/www/moodledata\nchmod -R 770 /var/www/moodledata\n\n# create cron entry\n# It is scheduled for once per day. It can be changed as needed.\necho '0 0 * * * php /var/www/html/iomad/admin/cli/cron.php > /dev/null 2>&1' > cronjob\ncrontab cronjob\n\n# restart Apache\napachectl restart\n\n# mount share file on /var/www/moodledata\nSharedStorageAccountName=$2\nSharedAzureFileName=$3\nSharedStorageAccountKey=$4\napt-get install cifs-utils\nmount -t cifs //$SharedStorageAccountName.file.core.windows.net/$SharedAzureFileName /var/www/moodledata -o uid=$(id -u www-data),vers=2.1,username=$SharedStorageAccountName,password=$SharedStorageAccountKey,dir_mode=0770,file_mode=0770\n\n#add mount to /etc/fstab to persist across reboots\nchmod 770 /etc/fstab\necho \"//$SharedStorageAccountName.file.core.windows.net/$SharedAzureFileName /var/www/moodledata cifs uid=$(id -u www-data),vers=3.0,username=$SharedStorageAccountName,password=$SharedStorageAccountKey,dir_mode=0770,file_mode=0770\" >> /etc/fstab\n\nLoadbalancerFqdn=$5\nDbFqdn=$6\nFullNameOfSite=$7\nShortNameOfSite=$8\nIomadAdminUser=$9\nIomadAdminPass=$10\nIomadAdminEmail=$11\n\ncd /var/www/html/iomad\n\n#resolve domain name to ip address\nwwwrootval=\"http://$(resolveip -s $LoadbalancerFqdn):80/iomad\"\nDbIpAddress=$(resolveip -s $DbFqdn)\n\n#command line iomad installation\nsudo -u www-data php admin/cli/install.php --chmod=770 --lang=en --wwwroot=$wwwrootval --dataroot='/var/www/moodledata' --dbhost=$DbIpAddress --dbpass=$dbpass --fullname=$FullNameOfSite --shortname=$ShortNameOfSite --adminuser=$IomadAdminUser --adminpass=$IomadAdminPass --adminemail=$IomadAdminEmail --non-interactive --agree-license --allow-unstable || true\n", "num_lines": 75}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\napt-get -y install python-software-properties\nadd-apt-repository -y ppa:ondrej/php5-oldstable\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-client mysql-server php5\n\n# install iomad requirements\napt-get -y install graphviz aspell php5-pspell php5-curl php5-gd php5-intl php5-mysql php5-xmlrpc php5-ldap\n\n# create iomad database\nMYSQL=`which mysql`\n\nQ1=\"CREATE DATABASE moodle DEFAULT CHARACTER SET UTF8 COLLATE utf8_unicode_ci;\"\nQ2=\"GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,CREATE TEMPORARY TABLES,DROP,INDEX,ALTER ON moodle.* TO 'root'@'%' IDENTIFIED BY '$dbpass' WITH GRANT OPTION;\"\nQ3=\"FLUSH PRIVILEGES;\"\nSQL=\"${Q1}${Q2}${Q3}\"\n\n$MYSQL -uroot -p$dbpass -e \"$SQL\"\n\n# install iomad\ncd /var/www/html\nwget https://github.com/iomad/iomad/archive/IOMAD_29_STABLE.zip -O iomad.zip\napt-get install unzip\nunzip iomad.zip\ncp -r iomad-IOMAD_29_STABLE iomad\n\n# make the iomad directory writable for owner\nchown -R www-data iomad\nchmod -R 770 iomad\n\n# create moodledata directory\nmkdir /var/www/moodledata\nchown -R www-data /var/www/moodledata\nchmod -R 770 /var/www/moodledata\n\n# create cron entry\n# It is scheduled for once per day. It can be changed as needed.\necho '0 0 * * * php /var/www/html/iomad/admin/cli/cron.php > /dev/null 2>&1' > cronjob\ncrontab cronjob\n\n# restart MySQL\nservice mysql restart\n\n# restart Apache\napachectl restart\n", "num_lines": 56}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nadddate() {\n    while IFS= read -r line; do\n        printf '%s %s\\n' \"$(date \"+%Y-%m-%d %H:%M:%S\")\" \"$line\";\n    done\n}\n\necho \"Red Hat JBoss EAP Cluster Intallation Start \" | adddate >> jbosseap.install.log\n/bin/date +%H:%M:%S  >> jbosseap.install.log\n\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"' >> ~/.bash_profile\nsource ~/.bash_profile\ntouch /etc/profile.d/eap_env.sh\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"' >> /etc/profile.d/eap_env.sh\n\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToDownload=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation$pathToFile/$fileToDownload$token\"\n\nJBOSS_EAP_USER=$9\nJBOSS_EAP_PASSWORD=${10}\nRHEL_OS_LICENSE_TYPE=${11}\nRHSM_USER=${12}\nRHSM_PASSWORD=${13}\nRHSM_POOL=${14}\nIP_ADDR=$(hostname -I)\nSTORAGE_ACCOUNT_NAME=${15}\nCONTAINER_NAME=${16}\nSTORAGE_ACCESS_KEY=$(echo \"${17}\" | openssl enc -d -base64)\nJAVA_VERSION=${18}\n\necho \"JBoss EAP admin user: \" ${JBOSS_EAP_USER} | adddate >> jbosseap.install.log\necho \"Storage Account Name: \" ${STORAGE_ACCOUNT_NAME} | adddate >> jbosseap.install.log\necho \"Storage Container Name: \" ${CONTAINER_NAME} | adddate >> jbosseap.install.log\necho \"RHSM_USER: \" ${RHSM_USER} | adddate >> jbosseap.install.log\necho \"JAVA VERSION : \" ${JAVA_VERSION} | adddate >> jbosseap.install.log\n\necho \"Configure firewall for ports 8080, 9990, 45700, 7600...\" | adddate >> jbosseap.install.log\n\necho \"firewall-cmd --zone=public --add-port=8080/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=8080/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=9990/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=9990/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=45700/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=45700/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=7600/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=7600/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --reload | adddate >> jbosseap.install.log 2>&1\necho \"iptables-save\" | adddate >> jbosseap.install.log\nsudo iptables-save | adddate >> jbosseap.install.log 2>&1\n\necho \"Initial JBoss EAP setup\" | adddate >> jbosseap.install.log\necho \"subscription-manager register --username RHSM_USER --password RHSM_PASSWORD\" | adddate >> jbosseap.install.log\nsubscription-manager register --username $RHSM_USER --password $RHSM_PASSWORD >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Red Hat Manager Registration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\necho \"subscription-manager attach --pool=EAP_POOL\" | adddate >> jbosseap.install.log\nsubscription-manager attach --pool=${RHSM_POOL} >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Pool Attach for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\nif [ $RHEL_OS_LICENSE_TYPE == \"BYOS\" ]\nthen\n    echo \"Attaching Pool ID for RHEL OS\" | adddate >> jbosseap.install.log\n    echo \"subscription-manager attach --pool=RHEL_POOL\" | adddate  >> jbosseap.install.log\n    subscription-manager attach --pool=${19} >> jbosseap.install.log 2>&1\nfi\necho \"Subscribing the system to get access to JBoss EAP repos\" | adddate >> jbosseap.install.log\n\n# Install JAVA\nif [ $JAVA_VERSION == \"JAVA_8\" ]\nthen\n    echo \"Installing JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-1.8.0-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-1.8.0-openjdk -y | adddate >> jbosseap.install.log\n    echo \"Successfully installed JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nelse\n    echo \"Installing JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-11-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-11-openjdk -y | adddate >> jbosseap.install.log\n    echo \"Successfully installed JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nfi\n\necho \"Install wget, git, unzip, vim\" | adddate >> jbosseap.install.log\necho \"sudo yum install wget unzip vim git -y\" | adddate >> jbosseap.install.log\nsudo yum install wget unzip vim git -y | adddate >> jbosseap.install.log 2>&1\necho \"Subscribing the system to get access to JBoss EAP 7.4 repos\" | adddate >> jbosseap.install.log\n\n# Install JBoss EAP 7.4\necho \"subscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms\" | adddate >> jbosseap.install.log\nsubscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Enabling repos for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"Installing JBoss EAP 7.4 repos\" | adddate >> jbosseap.install.log\necho \"yum groupinstall -y jboss-eap7\" | adddate >> jbosseap.install.log\nyum groupinstall -y jboss-eap7 >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP installation Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\nsed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\necho \"echo \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\necho \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\n\necho \"systemctl restart sshd\" | adddate >> jbosseap.install.log\nsystemctl restart sshd | adddate >> jbosseap.install.log 2>&1\n\necho \"Copy the standalone-azure-ha.xml from EAP_HOME/doc/wildfly/examples/configs folder to EAP_HOME/wildfly/standalone/configuration folder\" | adddate >> jbosseap.install.log\necho \"cp $EAP_HOME/doc/wildfly/examples/configs/standalone-azure-ha.xml $EAP_HOME/wildfly/standalone/configuration/\" | adddate >> jbosseap.install.log\ncp $EAP_HOME/doc/wildfly/examples/configs/standalone-azure-ha.xml $EAP_HOME/wildfly/standalone/configuration/ | adddate >> jbosseap.install.log 2>&1\n\necho \"change the jgroups stack from UDP to TCP \" | adddate >> jbosseap.install.log\necho \"sed -i 's/stack=\"udp\"/stack=\"tcp\"/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/stack=\"udp\"/stack=\"tcp\"/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\n\necho \"Update interfaces section update jboss.bind.address.management, jboss.bind.address and jboss.bind.address.private from 127.0.0.1 to 0.0.0.0\" | adddate >> jbosseap.install.log\necho \"sed -i 's/jboss.bind.address.management:127.0.0.1/jboss.bind.address.management:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address.management:127.0.0.1/jboss.bind.address.management:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\necho \"sed -i 's/jboss.bind.address:127.0.0.1/jboss.bind.address:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address:127.0.0.1/jboss.bind.address:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\necho \"sed -i 's/jboss.bind.address.private:127.0.0.1/jboss.bind.address.private:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address.private:127.0.0.1/jboss.bind.address.private:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\n\necho \"Start JBoss server\" | adddate >> jbosseap.install.log\necho \"$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true &\" | adddate >> jbosseap.install.log\n$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=$STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true | adddate >> jbosseap.install.log 2>&1 &\nsleep 20\n\necho \"export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"\" >> /bin/jbossservice.sh\necho \"$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=$STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true &\" >> /bin/jbossservice.sh\nchmod +x /bin/jbossservice.sh\n\nyum install cronie cronie-anacron | adddate >> jbosseap.install.log 2>&1\nservice crond start | adddate >> jbosseap.install.log 2>&1\nchkconfig crond on | adddate >> jbosseap.install.log 2>&1\necho \"@reboot sleep 90 && /bin/jbossservice.sh\" >>  /var/spool/cron/root\nchmod 600 /var/spool/cron/root\n\necho \"Deploy an application\" | adddate >> jbosseap.install.log\necho \"wget $fileUrl\" | adddate >> jbosseap.install.log\nwget $fileUrl >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Sample Application Download Failed\" | adddate >> jbosseap.install.log; exit $flag; fi\necho \"cp ./eap-session-replication.war $EAP_HOME/wildfly/standalone/deployments/\" | adddate >> jbosseap.install.log\ncp ./eap-session-replication.war $EAP_HOME/wildfly/standalone/deployments/ | adddate >> jbosseap.install.log 2>&1\necho \"touch $EAP_HOME/wildfly/standalone/deployments/eap-session-replication.war.dodeploy\" | adddate >> jbosseap.install.log\ntouch $EAP_HOME/wildfly/standalone/deployments/eap-session-replication.war.dodeploy | adddate >> jbosseap.install.log 2>&1\n\necho \"Configuring JBoss EAP management user...\" | adddate >> jbosseap.install.log\necho \"$EAP_HOME/wildfly/bin/add-user.sh -u JBOSS_EAP_USER -p JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup'\" | adddate >> jbosseap.install.log\n$EAP_HOME/wildfly/bin/add-user.sh  -u $JBOSS_EAP_USER -p $JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup' >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP management user configuration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\n# Seeing a race condition timing error so sleep to delay\nsleep 20\n\necho \"Red Hat JBoss EAP Cluster Intallation End \" | adddate >> jbosseap.install.log\n/bin/date +%H:%M:%S  >> jbosseap.install.log", "num_lines": 174}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nadddate() {\n    while IFS= read -r line; do\n        printf '%s %s\\n' \"$(date \"+%Y-%m-%d %H:%M:%S\")\" \"$line\";\n    done\n}\n\necho \"Red Hat JBoss EAP Cluster Intallation Start \" | adddate >> jbosseap.install.log\n/bin/date +%H:%M:%S >> jbosseap.install.log\n\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"' >> ~/.bash_profile\nsource ~/.bash_profile\ntouch /etc/profile.d/eap_env.sh\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"' >> /etc/profile.d/eap_env.sh\n\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToDownload=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation$pathToFile/$fileToDownload$token\"\n\nJBOSS_EAP_USER=$9\nJBOSS_EAP_PASSWORD=${10}\nRHSM_USER=${11}\nRHSM_PASSWORD=${12}\nRHEL_OS_LICENSE_TYPE=${13}\nRHSM_POOL=${14}\nIP_ADDR=$(hostname -I)\nSTORAGE_ACCOUNT_NAME=${15}\nCONTAINER_NAME=${16}\nSTORAGE_ACCESS_KEY=$(echo \"${17}\" | openssl enc -d -base64)\nJAVA_VERSION=${18}\n\necho \"JBoss EAP admin user: \" ${JBOSS_EAP_USER} | adddate >> jbosseap.install.log\necho \"Storage Account Name: \" ${STORAGE_ACCOUNT_NAME} | adddate >> jbosseap.install.log\necho \"Storage Container Name: \" ${CONTAINER_NAME} | adddate >> jbosseap.install.log\necho \"RHSM_USER: \" ${RHSM_USER} | adddate >> jbosseap.install.log\necho \"JAVA VERSION : \" ${JAVA_VERSION} | adddate >> jbosseap.install.log\n\necho \"Configure firewall for ports 8080, 9990, 45700, 7600...\" | adddate >> jbosseap.install.log\n\necho \"firewall-cmd --zone=public --add-port=8080/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=8080/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=9990/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=9990/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=45700/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=45700/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=7600/tcp --permanent\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --zone=public --add-port=7600/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> jbosseap.install.log\nsudo firewall-cmd --reload | adddate >> jbosseap.install.log 2>&1\necho \"iptables-save\" | adddate >> jbosseap.install.log\nsudo iptables-save | adddate >> jbosseap.install.log 2>&1\n\necho \"Initial JBoss EAP setup\" | adddate >> jbosseap.install.log\necho \"subscription-manager register --username RHSM_USER --password RHSM_PASSWORD\" | adddate >> jbosseap.install.log\nsubscription-manager register --username $RHSM_USER --password $RHSM_PASSWORD >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Red Hat Manager Registration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\necho \"subscription-manager attach --pool=EAP_POOL\" | adddate >> jbosseap.install.log\nsubscription-manager attach --pool=${RHSM_POOL} >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Pool Attach for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\nif [ $RHEL_OS_LICENSE_TYPE == \"BYOS\" ]\nthen\n    echo \"Attaching Pool ID for RHEL OS\" | adddate >> jbosseap.install.log\n    echo \"subscription-manager attach --pool=RHEL_POOL\" | adddate >> jbosseap.install.log\n    subscription-manager attach --pool=${19} >> jbosseap.install.log 2>&1\nfi\necho \"Subscribing the system to get access to JBoss EAP repos\" | adddate >> jbosseap.install.log\n\n# Install JAVA\nif [ $JAVA_VERSION == \"JAVA_8\" ]\nthen\n    echo \"Installing JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-1.8.0-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-1.8.0-openjdk -y | adddate >> jbosseap.install.log\n    echo \"Successfully installed JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nelse\n    echo \"Installing JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-11-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-11-openjdk -y | adddate >> jbosseap.install.log\n    echo \"Successfully installed JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nfi\n\necho \"Install wget, git, unzip, vim\" | adddate >> jbosseap.install.log\necho \"sudo yum install wget unzip vim git -y\" | adddate >> jbosseap.install.log\nsudo yum install wget unzip vim git -y | adddate >> jbosseap.install.log 2>&1\necho \"Subscribing the system to get access to JBoss EAP 7.4 repos\" | adddate >> jbosseap.install.log\n\n# Install JBoss EAP 7.4\necho \"subscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms\" | adddate >> jbosseap.install.log\nsubscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Enabling repos for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"Installing JBoss EAP 7.4 repos\" | adddate >> jbosseap.install.log\necho \"yum groupinstall -y jboss-eap7\" | adddate >> jbosseap.install.log\nyum groupinstall -y jboss-eap7 >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP installation Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\nsed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\necho \"echo \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\necho \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\n\necho \"systemctl restart sshd\" | adddate >> jbosseap.install.log\nsystemctl restart sshd | adddate >> jbosseap.install.log 2>&1\n\necho \"Copy the standalone-azure-ha.xml from EAP_HOME/doc/wildfly/examples/configs folder to EAP_HOME/wildfly/standalone/configuration folder\" | adddate >> jbosseap.install.log\necho \"cp $EAP_HOME/doc/wildfly/examples/configs/standalone-azure-ha.xml $EAP_HOME/wildfly/standalone/configuration/\" | adddate >> jbosseap.install.log\ncp $EAP_HOME/doc/wildfly/examples/configs/standalone-azure-ha.xml $EAP_HOME/wildfly/standalone/configuration/ | adddate >> jbosseap.install.log 2>&1\n\necho \"change the jgroups stack from UDP to TCP \" | adddate >> jbosseap.install.log\necho \"sed -i 's/stack=\"udp\"/stack=\"tcp\"/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/stack=\"udp\"/stack=\"tcp\"/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\n\necho \"Update interfaces section update jboss.bind.address.management, jboss.bind.address and jboss.bind.address.private from 127.0.0.1 to 0.0.0.0\" | adddate >> jbosseap.install.log\necho \"sed -i 's/jboss.bind.address.management:127.0.0.1/jboss.bind.address.management:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address.management:127.0.0.1/jboss.bind.address.management:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\necho \"sed -i 's/jboss.bind.address:127.0.0.1/jboss.bind.address:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address:127.0.0.1/jboss.bind.address:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\necho \"sed -i 's/jboss.bind.address.private:127.0.0.1/jboss.bind.address.private:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml\" | adddate >> jbosseap.install.log\nsed -i 's/jboss.bind.address.private:127.0.0.1/jboss.bind.address.private:0.0.0.0/g'  $EAP_HOME/wildfly/standalone/configuration/standalone-azure-ha.xml | adddate >> jbosseap.install.log 2>&1\n\necho \"Start JBoss server\" | adddate >> jbosseap.install.log\necho \"$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true &\" | adddate >> jbosseap.install.log\n$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=$STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true | adddate >> jbosseap.install.log 2>&1 &\nsleep 20\n\necho \"export EAP_HOME=\"/opt/rh/eap7/root/usr/share\"\" >> /bin/jbossservice.sh\necho \"$EAP_HOME/wildfly/bin/standalone.sh -bprivate $IP_ADDR -b $IP_ADDR -bmanagement $IP_ADDR --server-config=standalone-azure-ha.xml -Djboss.jgroups.azure_ping.storage_account_name=$STORAGE_ACCOUNT_NAME -Djboss.jgroups.azure_ping.storage_access_key=$STORAGE_ACCESS_KEY -Djboss.jgroups.azure_ping.container=$CONTAINER_NAME -Djava.net.preferIPv4Stack=true &\" >> /bin/jbossservice.sh\nchmod +x /bin/jbossservice.sh\n\nyum install cronie cronie-anacron | adddate >> jbosseap.install.log 2>&1\nservice crond start | adddate >> jbosseap.install.log 2>&1\nchkconfig crond on | adddate >> jbosseap.install.log 2>&1\necho \"@reboot sleep 90 && /bin/jbossservice.sh\" >>  /var/spool/cron/root\nchmod 600 /var/spool/cron/root\n\necho \"Deploy an application\" | adddate >> jbosseap.install.log\necho \"wget $fileUrl\" | adddate >> jbosseap.install.log\nwget $fileUrl >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Sample Application Download Failed\" | adddate >> jbosseap.install.log; exit $flag; fi\necho \"cp ./eap-session-replication.war $EAP_HOME/wildfly/standalone/deployments/\" | adddate >> jbosseap.install.log\ncp ./eap-session-replication.war $EAP_HOME/wildfly/standalone/deployments/ | adddate >> jbosseap.install.log 2>&1\necho \"touch $EAP_HOME/wildfly/standalone/deployments/eap-session-replication.war.dodeploy\" | adddate >> jbosseap.install.log\ntouch $EAP_HOME/wildfly/standalone/deployments/eap-session-replication.war.dodeploy | adddate >> jbosseap.install.log 2>&1\n\necho \"Configuring JBoss EAP management user...\" | adddate >> jbosseap.install.log\necho \"$EAP_HOME/wildfly/bin/add-user.sh -u JBOSS_EAP_USER -p JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup'\" | adddate >> jbosseap.install.log\n$EAP_HOME/wildfly/bin/add-user.sh  -u $JBOSS_EAP_USER -p $JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup' >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP management user configuration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\n# Seeing a race condition timing error so sleep to delay\nsleep 20\n\necho \"Red Hat JBoss EAP Cluster Intallation End \" | adddate >> jbosseap.install.log\n/bin/date +%H:%M:%S  >> jbosseap.install.log", "num_lines": 174}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nadddate() {\n    while IFS= read -r line; do\n        printf '%s %s\\n' \"$(date \"+%Y-%m-%d %H:%M:%S\")\" \"$line\";\n    done\n}\n\n/bin/date +%H:%M:%S >> jbosseap.install.log\necho \"ooooo      RED HAT JBoss EAP RPM INSTALL      ooooo\" | adddate >> jbosseap.install.log\n\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share/wildfly\"' >> ~/.bash_profile\nsource ~/.bash_profile\ntouch /etc/profile.d/eap_env.sh\necho 'export EAP_HOME=\"/opt/rh/eap7/root/usr/share/wildfly\"' >> /etc/profile.d/eap_env.sh\n\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToDownload=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation$pathToFile/$fileToDownload$token\"\n\nexport EAP_RPM_CONF_STANDALONE=\"/etc/opt/rh/eap7/wildfly/eap7-standalone.conf\"\nJBOSS_EAP_USER=$9\nJBOSS_EAP_PASSWORD=${10}\nRHSM_USER=${11}\nRHSM_PASSWORD=${12}\nRHEL_OS_LICENSE_TYPE=${13}\nRHSM_POOL=${14}\nIP_ADDR=$(hostname -I)\nJAVA_VERSION=${15}\n\necho \"JBoss EAP admin user : \" ${JBOSS_EAP_USER} | adddate >> jbosseap.install.log\necho \"JAVA VERSION : \" ${JAVA_VERSION} | adddate >> jbosseap.install.log\necho \"Initial JBoss EAP setup\" | adddate >> jbosseap.install.log\necho \"subscription-manager register --username RHSM_USER --password RHSM_PASSWORD\" | adddate >> jbosseap.install.log\nsubscription-manager register --username $RHSM_USER --password $RHSM_PASSWORD >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Red Hat Subscription Manager Registration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\necho \"subscription-manager attach --pool=EAP_POOL\" | adddate >> jbosseap.install.log\nsubscription-manager attach --pool=${RHSM_POOL} >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Pool Attach for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\nif [ $RHEL_OS_LICENSE_TYPE == \"BYOS\" ]\nthen\n    echo \"Attaching Pool ID for RHEL OS\" | adddate >> jbosseap.install.log\n    echo \"subscription-manager attach --pool=RHEL_POOL\" | adddate >> jbosseap.install.log\n    subscription-manager attach --pool=${16} >> jbosseap.install.log 2>&1\nfi\n\n# Install JAVA\nif [ $JAVA_VERSION == \"JAVA_8\" ]\nthen\n    echo \"Installing JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-1.8.0-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-1.8.0-openjdk -y >> jbosseap.install.log\n    echo \"Successfully installed JAVA 8\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nelse\n    echo \"Installing JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"sudo yum install java-11-openjdk -y\" | adddate >> jbosseap.install.log\n    sudo yum install java-11-openjdk -y >> jbosseap.install.log\n    echo \"Successfully installed JAVA 11\" | adddate >> jbosseap.install.log\n    echo \"java -version\" | adddate >> jbosseap.install.log\n    java -version >> jbosseap.install.log 2>&1\nfi\n\n# Install JBoss EAP 7.4\necho \"subscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms\" | adddate >> jbosseap.install.log\nsubscription-manager repos --enable=jb-eap-7.4-for-rhel-8-x86_64-rpms >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Enabling repos for JBoss EAP Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"Installing JBoss EAP 7.4 repos\" | adddate >> jbosseap.install.log\necho \"yum groupinstall -y jboss-eap7\" | adddate >> jbosseap.install.log\nyum groupinstall -y jboss-eap7 >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP installation Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\necho \"sed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\nsed -i 's/PermitRootLogin yes/PermitRootLogin no/g' /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\necho \"echo \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config\" | adddate >> jbosseap.install.log\necho \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config | adddate >> jbosseap.install.log 2>&1\n\necho \"systemctl restart sshd\" | adddate >> jbosseap.install.log\nsystemctl restart sshd | adddate >> jbosseap.install.log 2>&1\n\necho \"Start JBoss-EAP service\" | adddate >> jbosseap.install.log\necho \"systemctl enable eap7-standalone.service\" | adddate >> jbosseap.install.log\nsystemctl enable eap7-standalone.service | adddate >> jbosseap.install.log 2>&1\necho \"echo \"WILDFLY_SERVER_CONFIG=standalone-full.xml\" >> ${EAP_RPM_CONF_STANDALONE}\" | adddate >> jbosseap.install.log\necho \"WILDFLY_SERVER_CONFIG=standalone-full.xml\" >> ${EAP_RPM_CONF_STANDALONE} | adddate >> jbosseap.install.log\necho \"echo 'WILDFLY_BIND='$IP_ADDR >> ${EAP_RPM_CONF_STANDALONE}\" | adddate >> jbosseap.install.log\necho 'WILDFLY_BIND='$IP_ADDR >> ${EAP_RPM_CONF_STANDALONE} | adddate >> jbosseap.install.log 2>&1\necho \"echo \"WILDFLY_OPTS=-Djboss.bind.address.management=$IP_ADDR\" >> ${EAP_RPM_CONF_STANDALONE}\" | adddate >> jbosseap.install.log\necho \"WILDFLY_OPTS=-Djboss.bind.address.management=$IP_ADDR\" >> ${EAP_RPM_CONF_STANDALONE} | adddate >> jbosseap.install.log 2>&1\n\necho \"systemctl restart eap7-standalone.service\" | adddate >> jbosseap.install.log\nsystemctl restart eap7-standalone.service | adddate >> jbosseap.install.log 2>&1\necho \"systemctl status eap7-standalone.service\" | adddate >> jbosseap.install.log\nsystemctl status eap7-standalone.service | adddate >> jbosseap.install.log 2>&1\n\necho \"Getting the sample JBoss-EAP on Azure app to install\" | adddate >> jbosseap.install.log\necho \"wget $fileUrl\" | adddate >> jbosseap.install.log\nwget $fileUrl >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Sample Application Download Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\necho \"mv ./JBoss-EAP_on_Azure.war $EAP_HOME/standalone/deployments/JBoss-EAP_on_Azure.war\" | adddate >> jbosseap.install.log\nmv ./JBoss-EAP_on_Azure.war $EAP_HOME/standalone/deployments/JBoss-EAP_on_Azure.war | adddate >> jbosseap.install.log 2>&1\necho \"cat > $EAP_HOME/standalone/deployments/JBoss-EAP_on_Azure.war.dodeploy\" | adddate >> jbosseap.install.log\ncat > $EAP_HOME/standalone/deployments/JBoss-EAP_on_Azure.war.dodeploy | adddate >> jbosseap.install.log 2>&1\n\necho \"Configuring JBoss EAP management user\" | adddate >> jbosseap.install.log\necho \"$EAP_HOME/bin/add-user.sh -u JBOSS_EAP_USER -p JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup'\" | adddate >> jbosseap.install.log\n$EAP_HOME/bin/add-user.sh -u $JBOSS_EAP_USER -p $JBOSS_EAP_PASSWORD -g 'guest,mgmtgroup' >> jbosseap.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! JBoss EAP management user configuration Failed\" | adddate >> jbosseap.install.log; exit $flag;  fi\n\n# Open Red Hat software firewall for port 8080 and 9990:\necho \"firewall-cmd --zone=public --add-port=8080/tcp --permanent\" | adddate >> jbosseap.install.log\nfirewall-cmd --zone=public --add-port=8080/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=9990/tcp --permanent\" | adddate >> jbosseap.install.log\nfirewall-cmd --zone=public --add-port=9990/tcp --permanent | adddate  >> jbosseap.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> jbosseap.install.log\nfirewall-cmd --reload | adddate >> jbosseap.install.log 2>&1\n\n# Open Red Hat software firewall for port 22:\necho \"firewall-cmd --zone=public --add-port=22/tcp --permanent\" | adddate >> jbosseap.install.log\nfirewall-cmd --zone=public --add-port=22/tcp --permanent | adddate >> jbosseap.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> jbosseap.install.log\nfirewall-cmd --reload | adddate >> jbosseap.install.log 2>&1\n\n# Seeing a race condition timing error so sleep to delay\nsleep 20\n\necho \"ALL DONE!\" | adddate >> jbosseap.install.log\n/bin/date +%H:%M:%S >> jbosseap.install.log", "num_lines": 145}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# $1 - VM Host User Name\n\n/bin/date +%H:%M:%S > /home/$1/install.progress.txt\necho \"ooooo      REDHAT EAP7 RPM INSTALL      ooooo\" >> /home/$1/install.progress.txt\n\nexport EAP_HOME=\"/opt/rh/eap7/root/usr/share/wildfly\"\nexport EAP_RPM_CONF_STANDALONE=\"/etc/opt/rh/eap7/wildfly/eap7-standalone.conf\"\nexport EAP_RPM_CONF_DOMAIN=\"/etc/opt/rh/eap7/wildfly/eap7-domain.conf\"\n\nexport EAP_USER=$2\nexport EAP_PASSWORD=$3\nexport RHSM_USER=$4\nexport RHSM_PASSWORD=$5\nexport RHSM_POOL=$6\n\nPROFILE=standalone\necho \"EAP admin user\"+${EAP_USER} >> /home/$1/install.progress.txt\necho \"Initial EAP7 setup\" >> /home/$1/install.progress.txt\nsubscription-manager register --username $RHSM_USER --password $RHSM_PASSWORD  >> /home/$1/install.progress.txt 2>&1\nsubscription-manager attach --pool=${RHSM_POOL} >> /home/$1/install.progress.txt 2>&1\necho \"Subscribing the system to get access to EAP 7 repos\" >> /home/$1/install.progress.txt\n\n# Install EAP7\nsubscription-manager repos --enable=jb-eap-7-for-rhel-7-server-rpms >> /home/$1/install.out.txt 2>&1\nyum-config-manager --disable rhel-7-server-htb-rpms\n\necho \"Installing EAP7 repos\" >> /home/$1/install.progress.txt\nyum groupinstall -y jboss-eap7 >> /home/$1/install.out.txt 2>&1\n\necho \"Enabling EAP7 service\" >> /home/$1/install.progress.txt\nsystemctl enable eap7-standalone.service\n\necho \"Configure EAP7 RPM file\" >> /home/$1/install.progress.txt\n\necho \"WILDFLY_SERVER_CONFIG=standalone-full.xml\" >> ${EAP_RPM_CONF_STANDALONE}\necho 'WILDFLY_OPTS=\"-Djboss.bind.address.management=0.0.0.0\"' >> ${EAP_RPM_CONF_STANDALONE}\n\necho \"Installing GIT\" >> /home/$1/install.progress.txt\nyum install -y git >> /home/$1/install.out.txt 2>&1\n\ncd /home/$1\necho \"Getting the sample dukes app to install\" >> /home/$1/install.progress.txt\ngit clone https://github.com/MyriamFentanes/dukes.git >> /home/$1/install.out.txt 2>&1\nmv /home/$1/dukes/target/dukes.war $EAP_HOME/standalone/deployments/dukes.war\ncat > $EAP_HOME/standalone/deployments/dukes.war.dodeploy\n\necho \"Configuring EAP managment user\" >> /home/$1/install.progress.txt\n$EAP_HOME/bin/add-user.sh -u $EAP_USER -p $EAP_PASSWORD -g 'guest,mgmtgroup'\n\necho \"Start EAP 7\" >> /home/$1/install.progress.txt\nsystemctl restart eap7-standalone.service\n\n# Open Red Hat software firewall for port 8080 and 9990:\nfirewall-cmd --zone=public --add-port=8080/tcp --permanent  >> /home/$1/install.out.txt 2>&1\nfirewall-cmd --zone=public --add-port=9990/tcp --permanent  >> /home/$1/install.out.txt 2>&1\nfirewall-cmd --reload  >> /home/$1/install.out.txt 2>&1\n\necho \"Done.\" >> /home/$1/install.progress.txt\n/bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\necho \"Configuring SSH\" >> /home/$1/install.progress.txt\necho \"Done.\" >> /home/$1/install.progress.txt\n/bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n# Update SSHd config to not use passwords and set default umask to be 002\ncp /etc/ssh/sshd_config /etc/ssh/ORIG_sshd_config\nsed -i 's,PasswordAuthentication yes,PasswordAuthentication no,g' /etc/ssh/sshd_config\necho \"Match User \"$1 >> /etc/ssh/sshd_config\necho \"    ForceCommand internal-sftp -u 002\" >> /etc/ssh/sshd_config\n\n# Change group of user to same as JBoss\necho \"Changing group of user \"$1  >> /home/$1/install.out.txt 2>&1\n#gpasswd -d $1 jboss >> /home/$1/install.out.txt 2>&1\n#gpasswd -a $1 jboss >> /home/$1/install.out.txt 2>&1\n#usermod -g jboss $1 >> /home/$1/install.out.txt 2>&1\n\n\n# Configure the default umask for SSH to enable RW for user and group\ncp /etc/pam.d/sshd /etc/pam.d/ORIG_sshd\necho \"session optional pam_umask.so umask=002\" >> /etc/pam.d/sshd\n\n# Then start the SSH daemon:\nsystemctl daemon-reload >> /home/$1/install.out.txt 2>&1\nsystemctl start sshd.service >> /home/$1/install.out.txt 2>&1\nsystemctl enable sshd.service >> /home/$1/install.out.txt 2>&1\n\n# Open Red Hat software firewall for port 22:\nfirewall-cmd --zone=public --add-port=22/tcp --permanent >> /home/$1/install.out.txt 2>&1\nfirewall-cmd --reload >> /home/$1/install.out.txt 2>&1\n\n# Create an RSA public and private key for SSH\ncd /home/$1\nmkdir /home/$1/.ssh\nssh-keygen -q -N $4 -f /home/$1/.ssh/id_rsa >> /home/$1/install.out.txt 2>&1\ncd /home/$1/.ssh\ncp id_rsa.pub authorized_keys\nchown -R $1.jboss .\nchown -R $1.jboss *\necho \"SSH User name:  \"$1 > /home/$1/vsts_ssh_info\necho \"SSH passphrase: \"$4 >> /home/$1/vsts_ssh_info\necho \"SSH Private key:\" >> /home/$1/vsts_ssh_info\ncat id_rsa >> /home/$1/vsts_ssh_info\nchown $1.tomcat /home/$1/vsts_ssh_info\n\n\n# Configure SELinux to use Linux ACL's for file protection\nsetsebool -P allow_ftpd_full_access 1 >> /home/$1/install.out.txt 2>&1\n\n# Seeing a race condition timing error so sleep to deplay\nsleep 20\n\necho \"ALL DONE!\" >> /home/$1/install.progress.txt\n/bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n\nchown $1.jboss /home/$1/install.progress.txt\nchown $1.jboss /home/$1/install.out.txt\n\n", "num_lines": 121}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Utility Log Command\nlog()\n{\n    echo \"`date -u +'%Y-%m-%d %H:%M:%S'`: ${1}\"\n}\n\nhelp()\n{\n    echo \"This script installs Grafana cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-A admin password\"\n    echo \"-p port to host grafana-server\"\n    echo \"-S Azure subscription id\"\n    echo \"-T Azure tenant id\"\n    echo \"-i Azure service principal client id\"\n    echo \"-s Azure service principal client secret\"\n    echo \"-r Name of the resource group\"\n    echo \"-c Name of the CosmosDB\"\n    echo \"-k Name of the Kubernetes cluster\"\n    echo \"-l Artifacts location\"\n    echo \"-t Artifacts location sas token\"\n    echo \"-h view this help content\"\n}\n\n#Loop through options passed\nwhile getopts A:p:S:T:i:s:r:c:k:l:t::h optname; do\n  log \"Option $optname set\"\n  case $optname in\n    A)\n      ADMIN_PWD=\"${OPTARG}\"\n      ;;\n    p) #port number for local grafana server\n      GRAFANA_PORT=\"${OPTARG}\"\n      ;;\n    S)\n      SUBSCRIPTION_ID=\"${OPTARG}\"\n      ;;\n    T)\n      TENANT_ID=\"${OPTARG}\"\n      ;;\n    i)\n      CLIENT_ID=\"${OPTARG}\"\n      ;;\n    s)\n      CLIENT_SECRET=\"${OPTARG}\"\n      ;;\n    r)\n      RESOURCE_GROUP=\"${OPTARG}\"\n      ;;\n    c)\n      COMSOSDB_NAME=\"${OPTARG}\"\n      ;;\n    k)\n      CLUSTER_NAME=\"${OPTARG}\"\n      ;;\n    l)\n      ARTIFACTS_LOCATION=\"${OPTARG}\"\n      ;;\n    t)\n      ARTIFACTS_LOCATION_SAS_TOKEN=\"${OPTARG}\"\n      ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nfunction retry_until_successful {\n  counter=0\n  \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 6\n    \"${@}\"\n  done;\n}\n\nfunction post_json() {\n  curl -X POST http://admin:$ADMIN_PWD@localhost:$GRAFANA_PORT$1 \\\n     -H \"Content-Type: application/json\" \\\n     -d \"$2\"\n}\n\n#install azure-cli\necho \"deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EB3E94ADBE1229CF\nsudo apt-get install apt-transport-https\nsudo apt-get update --yes && sudo apt-get install azure-cli --yes\n\n#get vitrual machines\naz login --service-principal -u $CLIENT_ID --password $CLIENT_SECRET --tenant $TENANT_ID\nlocation=$(az group show --name $RESOURCE_GROUP --query location --out tsv)\naks_resource_group=\"MC_${RESOURCE_GROUP}_${CLUSTER_NAME}_${location}\"\n\naz aks wait --n ${CLUSTER_NAME} -g ${aks_resource_group} --interval 30 --custom \"agentPoolProfiles[].provisioningState == ['Succeeded']\"\n\nvirtual_machines=$(az resource list --resource-group ${aks_resource_group} --resource-type Microsoft.Compute/virtualMachines --query [*].name --out tsv)\n\n#wait until Grafana gets started\nretry_until_successful curl http://localhost:$GRAFANA_PORT\n\n#add Azure Monitor data source\npost_json \"/api/datasources\" \"$(cat <<EOF\n{\n    \"name\":\"Azure Monitor\",\n    \"type\":\"grafana-azure-monitor-datasource\",\n    \"url\":\"https://management.azure.com\",\n    \"access\": \"proxy\",\n    \"isDefault\":true,\n    \"jsonData\": {\n        \"subscriptionId\": \"${SUBSCRIPTION_ID}\",\n        \"tenantId\":\"${TENANT_ID}\",\n        \"clientId\":\"${CLIENT_ID}\"\n    },\n    \"secureJsonData\": {\n        \"clientSecret\": \"${CLIENT_SECRET}\"\n    }\n}\nEOF\n)\"\n\n#create dashboard\ndashboard_db=$(curl -s ${ARTIFACTS_LOCATION}scripts/grafana/dashboard-db.json${ARTIFACTS_LOCATION_SAS_TOKEN})\ndashboard_db=${dashboard_db//'{RESOURCE-GROUP-PLACEHOLDER}'/${RESOURCE_GROUP}}\ndashboard_db=${dashboard_db//'{COSMOSDB-NAME-PLACEHOLDER}'/${COMSOSDB_NAME}}\n\ntargets=\"\"\ndashboard_aks_target=$(curl -s ${ARTIFACTS_LOCATION}scripts/grafana/dashboard-aks-target.json${ARTIFACTS_LOCATION_SAS_TOKEN})\nfor virtual_machine in $virtual_machines\ndo\n  target=${dashboard_aks_target//'{RESOURCE-GROUP-PLACEHOLDER}'/${aks_resource_group}}\n  target=${target//'{VM-NAME-PLACEHOLDER}'/${virtual_machine}}\n  target=${target//'{SUBSCRIPTION-ID-PLACEHOLDER}'/${SUBSCRIPTION_ID}}\n  targets=${targets},${target}\ndone\ntargets=${targets:1:${#targets}}\n\ndashboard_aks=$(curl -s ${ARTIFACTS_LOCATION}scripts/grafana/dashboard-aks.json${ARTIFACTS_LOCATION_SAS_TOKEN})\ndashboard_aks=${dashboard_aks//'\"targets\": []'/\"\\\"targets\\\"\": [${targets}]}\n\ndashboard=$(curl -s ${ARTIFACTS_LOCATION}scripts/grafana/dashboard.json${ARTIFACTS_LOCATION_SAS_TOKEN})\ndashboard=${dashboard//'\"panels\": []'/\"\\\"panels\\\"\": [${dashboard_db}, ${dashboard_aks}]}\n\npost_json \"/api/dashboards/db\" \"${dashboard}\"\n", "num_lines": 156}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Command Line Opts\nGRAFANA_VERSION=\"8.3.4\"\nGRAFANA_PORT=\"3000\"\n\n\n# Utility Log Command\nlog()\n{\n    echo \"`date -u +'%Y-%m-%d %H:%M:%S'`: ${1}\"\n}\n\nhelp()\n{\n    echo \"This script installs Grafana cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-A admin password\"\n    echo \"-V version of grafana to use. Default:${GRAFANA_VERSION}\"\n    echo \"-p port to host grafana-server\"\n    echo \"-h view this help content\"\n}\n\n# Parameters\nADMIN_PWD=\"admin\"\n\n#Loop through options passed\nwhile getopts :A:V::h optname; do\n  log \"Option $optname set\"\n  case $optname in\n    A)\n      ADMIN_PWD=\"${OPTARG}\"\n      ;;\n    V) #input desired grafana version\n        GRAFANA_VERSION=\"${OPTARG}\"\n        ;;\n    p) #port number for local grafana server\n        GRAFANA_PORT=\"${OPTARG}\"\n        ;;\n    h) #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Grafana\ninstall_grafana()\n{\n    log \"Downloading grafana with version ${GRAFANA_VERSION}\"\n    local DOWNLOAD_URL=\"https://dl.grafana.com/enterprise/release/grafana-enterprise_${GRAFANA_VERSION}_amd64.deb\"\n    sudo apt-get install -y adduser libfontconfig\n    wget \"${DOWNLOAD_URL}\"\n    sudo dpkg -i \"grafana-enterprise_${GRAFANA_VERSION}_amd64.deb\"\n    systemctl daemon-reload\n}\n\nstart_grafana()\n{\n    log \"Staring the grafana-server\"\n    systemctl start grafana-server\n    sudo systemctl enable grafana-server.service\n}\n\n# Install the Azure Monitor Datasource\ninstall_azure_monitor_plugin()\n{\n    log \"Install grafana-azure-monitor-datasource\"\n    grafana-cli plugins install grafana-azure-monitor-datasource\n    systemctl restart grafana-server\n}\n\n# Update the grafana passord of the admin account\nconfigure_admin_password()\n{\n    sed -i \"s/;admin_password = admin/admin_password = ${ADMIN_PWD}/\" /etc/grafana/grafana.ini\n}\n\ninstall_grafana\nconfigure_admin_password\nstart_grafana", "num_lines": 86}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --jenkins_url|-j                [Required]: Jenkins URL\n  --jenkins_username|-ju          [Required]: Jenkins user name\n  --jenkins_password|-jp                    : Jenkins password. If not specified and the user name is \"admin\", the initialAdminPassword will be used\n  --git_url|-g                    [Required]: Git URL with a Dockerfile in it's root\n  --registry|-r                   [Required]: Registry url targeted by the pipeline\n  --registry_user_name|-ru        [Required]: Registry user name\n  --registry_password|-rp         [Required]: Registry password\n  --repository|-rr                          : Repository targeted by the pipeline\n  --aks_resource_group_name|-agn  [Required]: Name of the resource group which contains the AKS\n  --aks_cluster_name|-acn         [Required]: Name of the AKS cluster\n  --mongodb_uri|-mu               [Required]: URI of the MongoDB\n  --credentials_id|-ci                      : Desired Jenkins credentials id\n  --credentials_desc|-cd                    : Desired Jenkins credentials description\n  --job_short_name|-jsn                     : Desired Jenkins job short name\n  --job_display_name|-jdn                   : Desired Jenkins job display name\n  --job_description|-jd                     : Desired Jenkins job description\n  --scm_poll_schedule|-sps                  : cron style schedule for SCM polling\n  --scm_poll_ignore_commit_hooks|spi        : Ignore changes notified by SCM post-commit hooks. (Will be ignore if the poll schedule is not defined)\n  --artifacts_location|-al                  : Url used to reference other scripts/artifacts.\n  --sas_token|-st                           : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#set defaults\ncredentials_id=\"docker_credentials\"\ncredentials_desc=\"Docker Container Registry Credentials\"\njob_short_name=\"basic-docker-build\"\njob_display_name=\"Basic Docker Build\"\njob_description=\"A basic pipeline that builds a Docker container. The job expects a Dockerfile at the root of the git repository\"\nrepository=\"${USER}/myfirstapp\"\nscm_poll_schedule=\"\"\nscm_poll_ignore_commit_hooks=\"0\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_url|-j)\n      jenkins_url=\"$1\"\n      shift\n      ;;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\"\n      shift\n      ;;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\"\n      shift\n      ;;\n    --git_url|-g)\n      git_url=\"$1\"\n      shift\n      ;;\n    --registry|-r)\n      registry=\"$1\"\n      shift\n      ;;\n    --registry_user_name|-ru)\n      registry_user_name=\"$1\"\n      shift\n      ;;\n    --registry_password|-rp)\n      registry_password=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --aks_resource_group_name|-agn)\n      aks_resource_group_name=\"$1\"\n      shift\n      ;;\n    --aks_cluster_name|-acn)\n      aks_cluster_name=\"$1\"\n      shift\n      ;;\n    --mongodb_uri|-mu)\n      mongodb_uri=\"$1\"\n      shift\n      ;;\n    --credentials_id|-ci)\n      credentials_id=\"$1\"\n      shift\n      ;;\n    --credentials_desc|-cd)\n      credentials_desc=\"$1\"\n      shift\n      ;;\n    --job_short_name|-jsn)\n      job_short_name=\"$1\"\n      shift\n      ;;\n    --job_display_name|-jdn)\n      job_display_name=\"$1\"\n      shift\n      ;;\n    --job_description|-jd)\n      job_description=\"$1\"\n      shift\n      ;;\n   --scm_poll_schedule|-sps)\n      scm_poll_schedule=\"$1\"\n      shift\n      ;;\n  --scm_poll_ignore_commit_hooks|-spi)\n      scm_poll_ignore_commit_hooks=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --jenkins_url $jenkins_url\nthrow_if_empty --jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty --jenkins_password $jenkins_password\nfi\nthrow_if_empty --git_url $git_url\nthrow_if_empty --registry $registry\nthrow_if_empty --registry_user_name $registry_user_name\nthrow_if_empty --registry_password $registry_password\nthrow_if_empty --aks_resource_group_name $aks_resource_group_name\nthrow_if_empty --aks_cluster_name $aks_cluster_name\nthrow_if_empty --mongodb_uri $mongodb_uri\n\n#download dependencies\njob_xml=$(curl -s ${artifacts_location}scripts/jenkins/basic-docker-build-job.xml${artifacts_location_sas_token})\ncredentials_xml=$(curl -s ${artifacts_location}scripts/jenkins/basic-user-pwd-credentials.xml${artifacts_location_sas_token})\n\n#escape xml reserved characters\nescapsed_credentials_id=$(xmlstarlet esc \"$credentials_id\")\nescapsed_credentials_desc=$(xmlstarlet esc \"$credentials_desc\")\nescapsed_registry_user_name=$(xmlstarlet esc \"$registry_user_name\")\nescapsed_registry_password=$(xmlstarlet esc \"$registry_password\")\n\n#prepare credentials.xml\ncredentials_xml=${credentials_xml//'{insert-credentials-id}'/${escapsed_credentials_id}}\ncredentials_xml=${credentials_xml//'{insert-credentials-description}'/${escapsed_credentials_desc}}\ncredentials_xml=${credentials_xml//'{insert-user-name}'/${escapsed_registry_user_name}}\ncredentials_xml=${credentials_xml//'{insert-user-password}'/${escapsed_registry_password}}\n\n#escape xml reserved characters\nescapsed_job_display_name=$(xmlstarlet esc \"$job_display_name\")\nescapsed_job_description=$(xmlstarlet esc \"$job_description\")\nescapsed_git_url=$(xmlstarlet esc \"$git_url\")\nescapsed_registry=$(xmlstarlet esc \"$registry\")\nescapsed_aks_resource_group_name=$(xmlstarlet esc \"$aks_resource_group_name\")\nescapsed_aks_cluster_name=$(xmlstarlet esc \"$aks_cluster_name\")\nescapsed_credentials_id=$(xmlstarlet esc \"$credentials_id\")\nescapsed_repository=$(xmlstarlet esc \"$repository\")\nescapsed_mongodb_uri=$(xmlstarlet esc \"$mongodb_uri\")\n\n#prepare job.xml\njob_xml=${job_xml//'{insert-job-display-name}'/${escapsed_job_display_name}}\njob_xml=${job_xml//'{insert-job-description}'/${escapsed_job_description}}\njob_xml=${job_xml//'{insert-git-url}'/${escapsed_git_url}}\njob_xml=${job_xml//'{insert-registry}'/${escapsed_registry}}\njob_xml=${job_xml//'{insert-aks-resource-group-name}'/${escapsed_aks_resource_group_name}}\njob_xml=${job_xml//'{insert-aks-cluster-name}'/${escapsed_aks_cluster_name}}\njob_xml=${job_xml//'{insert-docker-credentials}'/${escapsed_credentials_id}}\njob_xml=${job_xml//'{insert-container-repository}'/${escapsed_repository}}\njob_xml=${job_xml//'{insert-mongodb-uri}'/${escapsed_mongodb_uri}}\n\nif [ -n \"${scm_poll_schedule}\" ]\nthen\n  scm_poll_ignore_commit_hooks_bool=\"false\"\n  if [[ \"${scm_poll_ignore_commit_hooks}\" == \"1\" ]]\n  then\n    scm_poll_ignore_commit_hooks_bool=\"true\"\n  fi\n  triggers_xml_node=$(cat <<EOF\n<triggers>\n  <hudson.triggers.SCMTrigger>\n  <spec>${scm_poll_schedule}</spec>\n  <ignorePostCommitHooks>${scm_poll_ignore_commit_hooks_bool}</ignorePostCommitHooks>\n  </hudson.triggers.SCMTrigger>\n</triggers>\nEOF\n)\n  job_xml=${job_xml//'<triggers/>'/${triggers_xml_node}}\nfi\n\njob_xml=${job_xml//'{insert-groovy-script}'/\"$(curl -s ${artifacts_location}scripts/jenkins/basic-docker-build.groovy${artifacts_location_sas_token})\"}\necho \"${job_xml}\" > job.xml\n\n#install the required plugins\nrun_util_script \"scripts/jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin credentials -deploy\"\nplugins=(docker-workflow git)\nfor plugin in \"${plugins[@]}\"; do\n  run_util_script \"scripts/jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin $plugin -restart\"\ndone\n\n#wait for instance to be back online\nrun_util_script \"scripts/jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"version\"\n\necho \"${credentials_xml}\" > credentials.xml\n\n#add user/pwd\nrun_util_script \"scripts/jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c 'create-credentials-by-xml SystemCredentialsProvider::SystemContextResolver::jenkins (global)' -cif \"credentials.xml\"\n\n#add job\nrun_util_script \"scripts/jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-job ${job_short_name}\" -cif \"job.xml\"\n\n#cleanup\nrm credentials.xml\nrm job.xml\nrm jenkins-cli.jar\n", "num_lines": 252}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho $@\nfunction print_usage() {\n  cat <<EOF\nInstalls Jenkins and exposes it to the public through port 80 (login and cli are disabled)\nCommand\n  $0\nArguments\n  --jenkins_fqdn|-jf       [Required] : Jenkins FQDN\n  --cluster_name|-cn       [Required] : Jenkins cluster name\n  --cluster_version|-cv    [Required] : Jenkins cluster version\n  --vm_private_ip|-pi                 : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead\n  --jenkins_release_type|-jrt         : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS\n  --jenkins_version_location|-jvl     : Url used to specify the version of Jenkins.\n  --service_principal_type|-sp        : The type of service principal: MSI or manual.\n  --service_principal_id|-spid        : The service principal ID.\n  --service_principal_secret|-ss      : The service principal secret.\n  --subscription_id|-subid            : The subscription ID of the SP.\n  --tenant_id|-tid                    : The tenant id of the SP.\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\n  --cloud_agents|-ca                  : The type of the cloud agents: aci, vm or no.\n  --resource_group|-rg                : the resource group name.\n  --location|-lo                      : the resource group location.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\nfunction retry_until_successful {\n  counter=0\n  \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    \"${@}\"\n  done;\n}\n\n#defaults\njenkins_version_location=\"${artifacts_location}scripts/jenkins/jenkins-verified-ver${artifacts_location_sas_token}\"\nazure_web_page_location=\"/usr/share/nginx/azure\"\njenkins_release_type=\"LTS\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --cluster_name|-cn)\n      cluster_name=\"$1\"\n      shift\n      ;;\n    --cluster_version|-cv)\n      cluster_version=\"$1\"\n      shift\n      ;;\n    --vm_private_ip|-pi)\n      vm_private_ip=\"$1\"\n      shift\n      ;;\n    --jenkins_release_type|-jrt)\n      jenkins_release_type=\"$1\"\n      shift\n      ;;\n    --jenkins_version_location|-jvl)\n      jenkins_version_location=\"$1\"\n      shift\n      ;;\n    --service_principal_type|-sp)\n      service_principal_type=\"$1\"\n      shift\n      ;;\n    --service_principal_id|-spid)\n      service_principal_id=\"$1\"\n      shift\n      ;;\n    --service_principal_secret|-ss)\n      service_principal_secret=\"$1\"\n      shift\n      ;;\n    --subscription_id|-subid)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-tid)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --cloud_agents|-ca)\n      cloud_agents=\"$1\"\n      shift\n      ;;\n    --resource_group|-rg)\n      resource_group=\"$1\"\n      shift\n      ;;\n    --location|-lo)\n      location=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\nthrow_if_empty --jenkins_release_type $jenkins_release_type\nif [[ \"$jenkins_release_type\" != \"LTS\" ]] && [[ \"$jenkins_release_type\" != \"weekly\" ]] && [[ \"$jenkins_release_type\" != \"verified\" ]]; then\n  echo \"Parameter jenkins_release_type can only be 'LTS' or 'weekly' or 'verified'! Current value is '$jenkins_release_type'\"\n  exit 1\nfi\n\nif [ -z \"$vm_private_ip\" ]; then\n    #use port 80 for public fqdn\n    jenkins_url=\"http://${jenkins_fqdn}/\"\nelse\n    #use port 8080 for internal\n    jenkins_url=\"http://${vm_private_ip}:8080/\"\nfi\n\njenkins_auth_matrix_conf=$(cat <<EOF\n<authorizationStrategy class=\"hudson.security.ProjectMatrixAuthorizationStrategy\">\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Create:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Delete:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.ManageDomains:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.Update:authenticated</permission>\n    <permission>com.cloudbees.plugins.credentials.CredentialsProvider.View:authenticated</permission>\n    <permission>hudson.model.Computer.Build:authenticated</permission>\n    <permission>hudson.model.Computer.Configure:authenticated</permission>\n    <permission>hudson.model.Computer.Connect:authenticated</permission>\n    <permission>hudson.model.Computer.Create:authenticated</permission>\n    <permission>hudson.model.Computer.Delete:authenticated</permission>\n    <permission>hudson.model.Computer.Disconnect:authenticated</permission>\n    <permission>hudson.model.Hudson.Administer:authenticated</permission>\n    <permission>hudson.model.Hudson.ConfigureUpdateCenter:authenticated</permission>\n    <permission>hudson.model.Hudson.Read:authenticated</permission>\n    <permission>hudson.model.Hudson.RunScripts:authenticated</permission>\n    <permission>hudson.model.Hudson.UploadPlugins:authenticated</permission>\n    <permission>hudson.model.Item.Build:authenticated</permission>\n    <permission>hudson.model.Item.Cancel:authenticated</permission>\n    <permission>hudson.model.Item.Configure:authenticated</permission>\n    <permission>hudson.model.Item.Create:authenticated</permission>\n    <permission>hudson.model.Item.Delete:authenticated</permission>\n    <permission>hudson.model.Item.Discover:authenticated</permission>\n    <permission>hudson.model.Item.Move:authenticated</permission>\n    <permission>hudson.model.Item.Read:authenticated</permission>\n    <permission>hudson.model.Item.Workspace:authenticated</permission>\n    <permission>hudson.model.Run.Delete:authenticated</permission>\n    <permission>hudson.model.Run.Replay:authenticated</permission>\n    <permission>hudson.model.Run.Update:authenticated</permission>\n    <permission>hudson.model.View.Configure:authenticated</permission>\n    <permission>hudson.model.View.Create:authenticated</permission>\n    <permission>hudson.model.View.Delete:authenticated</permission>\n    <permission>hudson.model.View.Read:authenticated</permission>\n    <permission>hudson.scm.SCM.Tag:authenticated</permission>\n    <permission>hudson.model.Hudson.Read:anonymous</permission>\n    <permission>hudson.model.Item.Discover:anonymous</permission>\n    <permission>hudson.model.Item.Read:anonymous</permission>\n</authorizationStrategy>\nEOF\n)\n\njenkins_location_conf=$(cat <<EOF\n<?xml version='1.0' encoding='UTF-8'?>\n<jenkins.model.JenkinsLocationConfiguration>\n    <adminAddress>address not configured yet &lt;nobody@nowhere&gt;</adminAddress>\n    <jenkinsUrl>${jenkins_url}</jenkinsUrl>\n</jenkins.model.JenkinsLocationConfiguration>\nEOF\n)\n\njenkins_disable_reverse_proxy_warning=$(cat <<EOF\n<disabledAdministrativeMonitors>\n    <string>hudson.diagnosis.ReverseProxySetupMonitor</string>\n</disabledAdministrativeMonitors>\nEOF\n)\n\njenkins_agent_port=\"<slaveAgentPort>5378</slaveAgentPort>\"\n\nnginx_reverse_proxy_conf=$(cat <<EOF\nserver {\n    listen 80;\n    server_name ${jenkins_fqdn};\n    error_page 403 /jenkins-on-azure;\n    location / {\n        proxy_set_header        Host \\$host:\\$server_port;\n        proxy_set_header        X-Real-IP \\$remote_addr;\n        proxy_set_header        X-Forwarded-For \\$proxy_add_x_forwarded_for;\n        proxy_set_header        X-Forwarded-Proto \\$scheme;\n\n\n        # Fix the \"It appears that your reverse proxy set up is broken\" error.\n        proxy_pass          http://localhost:8080;\n        proxy_redirect      http://localhost:8080 http://${jenkins_fqdn};\n        proxy_read_timeout  90;\n    }\n    location /cli {\n        rewrite ^ /jenkins-on-azure permanent;\n    }\n\n    location ~ /login* {\n        rewrite ^ /jenkins-on-azure permanent;\n    }\n    location /jenkins-on-azure {\n      alias ${azure_web_page_location};\n    }\n}\nEOF\n)\n\n#update apt repositories\nwget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -\n\nif [ \"$jenkins_release_type\" == \"weekly\" ]; then\n  sudo sh -c 'echo deb http://pkg.jenkins.io/debian binary/ > /etc/apt/sources.list.d/jenkins.list'\nelse\n  sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ > /etc/apt/sources.list.d/jenkins.list'\nfi\n\nsudo add-apt-repository ppa:openjdk-r/ppa --yes\n\necho \"deb [arch=amd64] https://apt-mo.trafficmanager.net/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 417A0893\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EB3E94ADBE1229CF\nsudo apt-get install apt-transport-https\nsudo apt-get update --yes\n\n#install openjdk8\nsudo apt-get install openjdk-8-jre openjdk-8-jre-headless openjdk-8-jdk --yes\n\n#install jenkins\nif [[ ${jenkins_release_type} == 'verified' ]]; then\n  jenkins_version=$(curl --silent \"${jenkins_version_location}\")\n  deb_file=jenkins_${jenkins_version}_all.deb\n  wget -q \"https://pkg.jenkins.io/debian-stable/binary/${deb_file}\"\n  if [[ -f ${deb_file} ]]; then\n    sudo dpkg -i ${deb_file}\n    sudo apt-get install -f --yes\n  else\n    echo \"Failed to download ${deb_file}. The initialization is terminated!\"\n    exit -1\n  fi\nelse\n  sudo apt-get install jenkins --yes\n  sudo apt-get install jenkins --yes # sometime the first apt-get install jenkins command fails, so we try it twice\nfi\n\nretry_until_successful sudo test -f /var/lib/jenkins/secrets/initialAdminPassword\nretry_until_successful run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"version\"\n\n#We need to install workflow-aggregator so all the options in the auth matrix are valid\nplugins=(azure-vm-agents windows-azure-storage matrix-auth workflow-aggregator azure-app-service azure-acs azure-container-agents)\nfor plugin in \"${plugins[@]}\"; do\n  run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"install-plugin $plugin -deploy\"\ndone\n\n#allow anonymous read access\ninter_jenkins_config=$(sed -zr -e\"s|<authorizationStrategy.*</authorizationStrategy>|{auth-strategy-token}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{auth-strategy-token}'/${jenkins_auth_matrix_conf}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#set up Jenkins URL to private_ip:8080 so JNLP connections can be established\necho \"${jenkins_location_conf}\" | sudo tee /var/lib/jenkins/jenkins.model.JenkinsLocationConfiguration.xml > /dev/null\n\n#disable 'It appears that your reverse proxy set up is broken' warning.\n# This is visible when connecting through SSH tunneling\ninter_jenkins_config=$(sed -zr -e\"s|<disabledAdministrativeMonitors/>|{disable-reverse-proxy-token}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{disable-reverse-proxy-token}'/${jenkins_disable_reverse_proxy_warning}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#Open a fixed port for JNLP\ninter_jenkins_config=$(sed -zr -e\"s|<slaveAgentPort.*</slaveAgentPort>|{slave-agent-port}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{slave-agent-port}'/${jenkins_agent_port}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n#restart jenkins\nsudo service jenkins restart\n\n#install the service principal\nmsi_cred=$(cat <<EOF\n<com.microsoft.azure.util.AzureMsiCredentials>\n  <scope>GLOBAL</scope>\n  <id>azure_service_principal</id>\n  <description>Local MSI</description>\n  <msiPort>50342</msiPort>\n</com.microsoft.azure.util.AzureMsiCredentials>\nEOF\n)\nsp_cred=$(cat <<EOF\n<com.microsoft.azure.util.AzureCredentials>\n  <scope>GLOBAL</scope>\n  <id>azure_service_principal</id>\n  <description>Manual Service Principal</description>\n  <data>\n    <subscriptionId>${subscription_id}</subscriptionId>\n    <clientId>${service_principal_id}</clientId>\n    <clientSecret>${service_principal_secret}</clientSecret>\n    <oauth2TokenEndpoint>https://login.windows.net/${tenant_id}</oauth2TokenEndpoint>\n    <serviceManagementURL>https://management.core.windows.net/</serviceManagementURL>\n    <tenant>${tenant_id}</tenant>\n    <authenticationEndpoint>https://login.microsoftonline.com/</authenticationEndpoint>\n    <resourceManagerEndpoint>https://management.azure.com/</resourceManagerEndpoint>\n    <graphEndpoint>https://graph.windows.net/</graphEndpoint>\n  </data>\n</com.microsoft.azure.util.AzureCredentials>\nEOF\n)\n\nretry_until_successful run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"version\"\n\nif [ \"${service_principal_type}\" == 'msi' ]; then\n  echo \"${msi_cred}\" > msi_cred.xml\n  run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif msi_cred.xml\n  rm msi_cred.xml\nelse\n  echo \"${sp_cred}\" > sp_cred.xml\n  run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif sp_cred.xml\n  rm sp_cred.xml\nfi\n\n#add cloud agents\nvm_agent_conf=conf=$(cat <<EOF\n<clouds>\n  <com.microsoft.azure.vmagent.AzureVMCloud>\n    <name>AzureVMAgents</name>\n    <cloudName>AzureVMAgents</cloudName>\n    <credentialsId>azure_service_principal</credentialsId>\n    <maxVirtualMachinesLimit>10</maxVirtualMachinesLimit>\n    <resourceGroupReferenceType>existing</resourceGroupReferenceType>\n    <existingResourceGroupName>${resource_group}</existingResourceGroupName>\n    <vmTemplates>\n      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n        <templateName>win-agent</templateName>\n        <labels>win</labels>\n        <location>${location}</location>\n        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>\n        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>\n        <diskType>managed</diskType>\n        <storageAccountType>Standard_LRS</storageAccountType>\n        <noOfParallelJobs>1</noOfParallelJobs>\n        <usageMode>NORMAL</usageMode>\n        <shutdownOnIdle>false</shutdownOnIdle>\n        <imageTopLevelType>basic</imageTopLevelType>\n        <builtInImage>Windows Server 2016</builtInImage>\n        <credentialsId>agent_admin_account</credentialsId>\n        <retentionTimeInMin>60</retentionTimeInMin>\n      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n      <com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n        <templateName>linux-agent</templateName>\n        <labels>linux</labels>\n        <location>${location}</location>\n        <virtualMachineSize>Standard_D1_v2</virtualMachineSize>\n        <storageAccountNameReferenceType>new</storageAccountNameReferenceType>\n        <diskType>managed</diskType>\n        <storageAccountType>Standard_LRS</storageAccountType>\n        <noOfParallelJobs>1</noOfParallelJobs>\n        <usageMode>NORMAL</usageMode>\n        <shutdownOnIdle>false</shutdownOnIdle>\n        <imageTopLevelType>basic</imageTopLevelType>\n        <builtInImage>Ubuntu 16.04 LTS</builtInImage>\n        <credentialsId>agent_admin_account</credentialsId>\n        <retentionTimeInMin>60</retentionTimeInMin>\n      </com.microsoft.azure.vmagent.AzureVMAgentTemplate>\n    </vmTemplates>\n    <deploymentTimeout>1200</deploymentTimeout>\n    <approximateVirtualMachineCount>0</approximateVirtualMachineCount>\n  </com.microsoft.azure.vmagent.AzureVMCloud>\n</clouds>\nEOF\n)\n\naci_agent_conf=$(cat <<EOF\n<clouds>\n  <com.microsoft.jenkins.containeragents.aci.AciCloud>\n    <name>AciAgents</name>\n    <credentialsId>azure_service_principal</credentialsId>\n    <resourceGroup>${resource_group}</resourceGroup>\n    <templates>\n      <com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>\n        <name>aciagents</name>\n        <image>jenkinsci/jnlp-slave</image>\n        <osType>Linux</osType>\n        <command>jenkins-slave -url \\${rootUrl} \\${secret} \\${nodeName}</command>\n        <rootFs>/home/jenkins</rootFs>\n        <timeout>10</timeout>\n        <cpu>1</cpu>\n        <memory>1.5</memory>\n        <retentionStrategy class=\"com.microsoft.jenkins.containeragents.strategy.ContainerOnceRetentionStrategy\" />\n      </com.microsoft.jenkins.containeragents.aci.AciContainerTemplate>\n    </templates>\n  </com.microsoft.jenkins.containeragents.aci.AciCloud>\n</clouds>\nEOF\n)\n\nagent_admin_password=$(head /dev/urandom | tr -dc A-Z | head -c 4)$(head /dev/urandom | tr -dc a-z | head -c 4)$(head /dev/urandom | tr -dc 0-9 | head -c 4)'!@'\nagent_admin_cred=$(cat <<EOF\n<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>\n  <scope>GLOBAL</scope>\n  <id>agent_admin_account</id>\n  <description>the admin account for the vm agents</description>\n  <username>agentadmin</username>\n  <password>${agent_admin_password}</password>\n</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>\nEOF\n)\n\nif [ \"${cloud_agents}\" == 'vm' ]; then\n  echo \"${agent_admin_cred}\" > agent_admin_cred.xml\n  run_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif agent_admin_cred.xml\n  rm agent_admin_cred.xml\n  inter_jenkins_config=$(sed -zr -e\"s|<clouds/>|{clouds}|\" /var/lib/jenkins/config.xml)\n  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${vm_agent_conf}}\n  echo \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\nelif [ \"${cloud_agents}\" == 'aci' ]; then\n  inter_jenkins_config=$(sed -zr -e\"s|<clouds/>|{clouds}|\" /var/lib/jenkins/config.xml)\n  final_jenkins_config=${inter_jenkins_config//'{clouds}'/${aci_agent_conf}}\n  echo \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\nfi\n\nrun_util_script \"scripts/jenkins/run-cli-command.sh\" -c \"reload-configuration\"\n\n\n#install nginx\nsudo apt-get install nginx --yes\n\n#configure nginx\necho \"${nginx_reverse_proxy_conf}\" | sudo tee /etc/nginx/sites-enabled/default > /dev/null\n\n#don't show version in headers\nsudo sed -i \"s|.*server_tokens.*|server_tokens off;|\" /etc/nginx/nginx.conf\n\n#install jenkins-on-azure web page\nrun_util_script \"scripts/jenkins/jenkins-on-azure/install-web-page.sh\" -u \"${jenkins_fqdn}\"  -l \"${azure_web_page_location}\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\n#restart nginx\nsudo service nginx restart\n\n#install common tools\nsudo apt-get install git --yes\nsudo apt-get install azure-cli --yes\nsudo az aks install-cli --client-version ${cluster_version}\nsudo apt-get install xmlstarlet", "num_lines": 485}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --vm_user_name|-u               [Required] : VM user name\n  --git_url|-g                    [Required] : Git URL with a Dockerfile in it's root\n  --registry|-r                   [Required] : Registry url targeted by the pipeline\n  --registry_user_name|-ru        [Required] : Registry user name\n  --registry_password|-rp         [Required] : Registry password\n  --repository|-rr                [Required] : Repository targeted by the pipeline\n  --resource_group_name|-gn       [Required] : Name of the resource group which contains the AKS\n  --cluster_name|-cn              [Required] : Name of the AKS cluster\n  --cluster_version|-cv           [Required] : Version of the AKS cluster\n  --jenkins_fqdn|-jf              [Required] : Jenkins FQDN\n  --service_principal_id|-spid    [Required] : The service principal ID.\n  --service_principal_secret|-ss  [Required] : The service principal secret.\n  --subscription_id|-subid        [Required] : The subscription ID of the SP.\n  --tenant_id|-tid                [Required] : The tenant id of the SP.\n  --mongodb_uri|-mu               [Required] : URI of the MongoDB\n  --artifacts_location|-al                   : Url used to reference other scripts/artifacts.\n  --sas_token|-st                            : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nfunction run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${artifacts_location}${script_path}${artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n#defaults\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --vm_user_name|-u)\n      vm_user_name=\"$1\"\n      shift\n      ;;\n    --git_url|-g)\n      git_url=\"$1\"\n      shift\n      ;;\n    --registry|-r)\n      registry=\"$1\"\n      shift\n      ;;\n    --registry_user_name|-ru)\n      registry_user_name=\"$1\"\n      shift\n      ;;\n    --registry_password|-rp)\n      registry_password=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --resource_group_name|-gn)\n      resource_group_name=\"$1\"\n      shift\n      ;;\n    --cluster_name|-cn)\n      cluster_name=\"$1\"\n      shift\n      ;;\n    --cluster_version|-cv)\n      cluster_version=\"$1\"\n      shift\n      ;;\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --service_principal_id|-spid)\n      service_principal_id=\"$1\"\n      shift\n      ;;\n    --service_principal_secret|-ss)\n      service_principal_secret=\"$1\"\n      shift\n      ;;\n    --subscription_id|-subid)\n      subscription_id=\"$1\"\n      shift\n      ;;\n    --tenant_id|-tid)\n      tenant_id=\"$1\"\n      shift\n      ;;\n    --mongodb_uri|-mu)\n      mongodb_uri=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --vm_user_name $vm_user_name\nthrow_if_empty --git_url $git_url\nthrow_if_empty --registry $registry\nthrow_if_empty --registry_user_name $registry_user_name\nthrow_if_empty --registry_password $registry_password\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\nthrow_if_empty --service_principal_id $service_principal_id\nthrow_if_empty --service_principal_secret $service_principal_secret\nthrow_if_empty --subscription_id $subscription_id\nthrow_if_empty --tenant_id $tenant_id\nthrow_if_empty --resource_group_name $resource_group_name\nthrow_if_empty --cluster_name $cluster_name\nthrow_if_empty --mongodb_uri $mongodb_uri\n\n#install jenkins\nrun_util_script \"scripts/jenkins/install_jenkins.sh\" -jf \"${jenkins_fqdn}\" -cn \"${cluster_name}\" -cv \"${cluster_version}\" -spid \"${service_principal_id}\" -ss \"${service_principal_secret}\" -subid \"${subscription_id}\" -tid \"${tenant_id}\" -al \"${artifacts_location}\" -st \"${artifacts_location_sas_token}\"\n\n#install git\nsudo apt-get install git --yes\n\n#install docker if not already installed\nif !(command -v docker >/dev/null); then\n  sudo curl -sSL https://get.docker.com/ | sh\nfi\n\n#make sure jenkins has access to docker cli\nsudo gpasswd -a jenkins docker\nskill -KILL -u jenkins\nsudo service jenkins restart\n\nif [ -z \"$repository\" ]; then\n  repository=\"hello-world\"\nfi\n\njob_short_name=\"hello-world\"\njob_display_name=\"Hello World Build & Deploy\"\njob_description=\"A pipeline that builds a Docker image, pushed built image to ACR, and deploy configurations to AKS.\"\n\necho \"Including the pipeline\"\nrun_util_script \"scripts/jenkins/add-docker-build-job.sh\" -j \"http://localhost:8080/\" -ju \"admin\" -jsn \"${job_short_name}\" -jdn \"${job_display_name}\" -jd \"${job_description}\" -g \"${git_url}\" -r \"${registry}\" -ru \"${registry_user_name}\" -rp \"${registry_password}\" -rr \"$repository\" -agn \"${resource_group_name}\" -acn \"${cluster_name}\" -mu \"${mongodb_uri}\" -sps \"* * * * *\" -al \"$artifacts_location\" -st \"$artifacts_location_sas_token\"\n", "num_lines": 172}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --command|-c             [Required]: Jenkins cli command to run\n  --command_input_file|-cif          : File path containing the input to the CLI command\n  --jenkins_url|-j                   : Jenkins URL, defaulted to \"http://localhost:8080/\"\n  --jenkins_username|-ju             : Jenkins user name, defaulted to \"admin\"\n  --jenkins_password|-jp             : Jenkins password. If not specified and the user name is \"admin\", the initialAdminPassword will be used\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    >&2 echo \"Parameter '$name' cannot be empty.\"\n    print_usage\n    exit -1\n  fi\n}\n\n#set defaults\njenkins_url=\"http://localhost:8080/\"\njenkins_username=\"admin\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --command|-c)\n      command=\"$1\"\n      shift\n      ;;\n    --command_input_file|-cif)\n      command_input_file=\"$1\"\n      shift\n      ;;\n    --jenkins_url|-j)\n      jenkins_url=\"$1\"\n      shift\n      ;;\n    --jenkins_username|-ju)\n      jenkins_username=\"$1\"\n      shift\n      ;;\n    --jenkins_password|-jp)\n      jenkins_password=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      >&2 echo \"ERROR: Unknown argument '$key' to script '$0'\"\n      exit -1\n  esac\ndone\n\nthrow_if_empty jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty jenkins_password $jenkins_password\nfi\n\nfunction retry_until_successful {\n  counter=0\n  \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    \"${@}\"\n  done;\n}\n\nfunction retry_until_successful_with_input {\n  input_file=$1\n  shift\n  counter=0\n  cat \"$input_file\" | \"${@}\"\n  while [ $? -ne 0 ]; do\n    if [[ \"$counter\" -gt 20 ]]; then\n        exit 1\n    else\n        let counter++\n    fi\n    sleep 5\n    cat \"$input_file\" | \"${@}\"\n  done;\n}\n\nif [ ! -e jenkins-cli.jar ]; then\n  >&2 echo \"Downloading Jenkins CLI...\"\n  retry_until_successful wget ${jenkins_url}jnlpJars/jenkins-cli.jar -O jenkins-cli.jar\nfi\n\nif [ -z \"$jenkins_password\" ]; then\n  # NOTE: Intentionally setting this after the first retry_until_successful to ensure the initialAdminPassword file exists\n  jenkins_password=`sudo cat /var/lib/jenkins/secrets/initialAdminPassword`\nfi\n\n>&2 echo \"Running \\\"${command}\\\"...\"\nif [ -z \"${command_input_file}\" ]; then\n  retry_until_successful java -jar jenkins-cli.jar -s \"${jenkins_url}\" -auth \"${jenkins_username}\":\"${jenkins_password}\" $command\nelse\n  retry_until_successful_with_input \"${command_input_file}\" java -jar jenkins-cli.jar -s \"${jenkins_url}\" -auth \"${jenkins_username}\":\"${jenkins_password}\" $command\nfi\n", "num_lines": 116}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --location|-l            [Required] : The web page location\n  --url|-u                 [Required] : Domain URL\n  --artifacts_location|-al            : Url used to reference other scripts/artifacts.\n  --sas_token|-st                     : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    echo \"Parameter '$name' cannot be empty.\" 1>&2\n    print_usage\n    exit -1\n  fi\n}\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --location|-l)\n      location=\"$1\"\n      shift\n      ;;\n    --url|-u)\n      url=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      echo \"ERROR: Unknown argument '$key' to script '$0'\" 1>&2\n      exit -1\n  esac\ndone\n\nthrow_if_empty --location $location\nthrow_if_empty --url $url\n\n#install jenkins-on-azure web page\nsudo mkdir ${location}\nartifacts=(\"headshot.png\" \"title.png\" \"azure.svg\" \"copy.png\" \"site.css\" \"site.js\" \"index.html\")\nfor i in \"${artifacts[@]}\"; do\n  if [[ $i =~ .*html.* ]]\n  then\n      raw_resource=$(curl --silent \"${artifacts_location}scripts/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}\")\n      final_resource=${raw_resource//'{domain-name}'/${url}}\n      echo \"${final_resource}\" | sudo tee ${location}/$i > /dev/null\n    else\n      curl --silent \"${artifacts_location}scripts/jenkins/jenkins-on-azure/$i${artifacts_location_sas_token}\" -o ${location}/$i\n  fi\ndone\n\n", "num_lines": 72}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --jenkins_fqdn|-jf               [Required] : Jenkins FQDN\n  --jenkins_private_ip|-jpi                   : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead\n  --jenkins_release_type|-jrt                 : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS\n  --jenkins_version_location|-jvl             : Url used to specify the version of Jenkins.\n  --subscription|-su               [Required] : Azure subscription id\n  --tenant|-t                      [Required] : Azure tenant id\n  --clientid|-i                    [Required] : Azure service principal client id\n  --clientsecret|-s                [Required] : Azure service principal client secret\n  --resourcegroup|-rg              [Required] : Azure resource group for the components\n  --location|-l                    [Required] : Azure resource group location for the components\n  --image_resourcegroup|-irg       [Required] : Azure resource group for the VM image\n  --image|-im                                 : VM image name\n  --vm_dns|-vd                     [Required] : Unique DNS name for the Virtual Machine\n  --vm_username|-vu                [Required] : Username for the Virtual Machine\n  --vm_password|-vp                [Required] : Password for the Virtual Machine\n  --repository|-rr                 [Required] : Repository targeted by the build\n  --oms_workspace_id|-wi           [Required] : OMS workspace id\n  --oms_workspace_key|-wk          [Required] : OMS workspace key\n  --artifacts_location|-al                    : Url used to reference other scripts/artifacts.\n  --sas_token|-st                             : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    >&2 echo \"Parameter '$name' cannot be empty.\"\n    print_usage\n    exit -1\n  fi\n}\n\nfunction ms_run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${ms_artifacts_location}${script_path}${ms_artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n# set defaults\njenkins_url=\"http://localhost:8080/\"\njenkins_username=\"admin\"\njenkins_password=\"\"\nimage=\"myPackerLinuxImage\"\njob_short_name=\"BuildVM\"\ncredential_id=\"vmCred\"\ncredential_description=\"VM credential\"\nms_artifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/v0.28.1/\"\nms_artifacts_location_sas_token=\"\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --jenkins_private_ip|-jpi)\n      jenkins_private_ip=\"$1\"\n      shift\n      ;;\n    --jenkins_release_type|-jrt)\n      jenkins_release_type=\"$1\"\n      shift\n      ;;\n    --jenkins_version_location|-jvl)\n      jenkins_version_location=\"$1\"\n      shift\n      ;;\n    --subscription|-su)\n      subscription=\"$1\"\n      shift\n      ;;\n    --tenant|-t)\n      tenant=\"$1\"\n      shift\n      ;;\n    --clientid|-i)\n      clientid=\"$1\"\n      shift\n      ;;\n    --clientsecret|-s)\n      clientsecret=\"$1\"\n      shift\n      ;;\n    --resourcegroup|-rg)\n      resourcegroup=\"$1\"\n      shift\n      ;;\n    --location|-l)\n      location=\"$1\"\n      shift\n      ;;\n    --image_resourcegroup|-irg)\n      image_resourcegroup=\"$1\"\n      shift\n      ;;\n    --image|-im)\n      image=\"$1\"\n      shift\n      ;;\n    --vm_dns|-vd)\n      vm_dns=\"$1\"\n      shift\n      ;;\n    --vm_username|-vu)\n      vm_username=\"$1\"\n      shift\n      ;;\n    --vm_password|-vp)\n      vm_password=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --oms_workspace_id|-wi)\n      oms_workspace_id=\"$1\"\n      shift\n      ;;\n    --oms_workspace_key|-wk)\n      oms_workspace_key=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      >&2 echo \"ERROR: Unknown argument '$key' to script '$0'\"\n      exit -1\n  esac\ndone\n\nthrow_if_empty jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty jenkins_password $jenkins_password\nfi\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\nthrow_if_empty --subscription $subscription\nthrow_if_empty --tenant $tenant\nthrow_if_empty --clientid $clientid\nthrow_if_empty --clientsecret $clientsecret\nthrow_if_empty --resourcegroup $resourcegroup\nthrow_if_empty --location $location\nthrow_if_empty --image_resourcegroup $image_resourcegroup\nthrow_if_empty --vm_dns $vm_dns\nthrow_if_empty --vm_username $vm_username\nthrow_if_empty --vm_password $vm_password\nthrow_if_empty --repository $repository\nthrow_if_empty --oms_workspace_id $oms_workspace_id\nthrow_if_empty --oms_workspace_key $oms_workspace_key\n\n# install jenkins\nms_run_util_script \"jenkins/install_jenkins.sh\" -jf \"${jenkins_fqdn}\" -pi \"${jenkins_private_ip}\" -jrt \"${jenkins_release_type}\" -jvl \"${jenkins_version_location}\" -al \"${ms_artifacts_location}\" -st \"${ms_artifacts_location_sas_token}\"\n\n# install required plugins\nplugins=(credentials envinject)\nfor plugin in \"${plugins[@]}\"; do\n  ms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin $plugin -deploy\"\ndone\n\n# restart jenkins\nsudo service jenkins restart\n\n# wait for instance to be back online\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"version\"\n\n# download dependencies\njob_xml=$(curl -s ${artifacts_location}/scripts/jenkins/jobs-build-vm.xml${artifacts_location_sas_token})\ncredentials_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-basic.xml${artifacts_location_sas_token})\n\n# prepare job xml\njob_xml=${job_xml//'{insert-repository-url}'/${repository}}\njob_xml=${job_xml//'{insert-credentials-id}'/${credential_id}}\njob_xml=${job_xml//'{insert-subscription-id}'/${subscription}}\njob_xml=${job_xml//'{insert-tenant-id}'/${tenant}}\njob_xml=${job_xml//'{insert-client-id}'/${clientid}}\njob_xml=${job_xml//'{insert-client-secret}'/${clientsecret}}\njob_xml=${job_xml//'{insert-resource-group}'/${resourcegroup}}\njob_xml=${job_xml//'{insert-location}'/${location}}\njob_xml=${job_xml//'{insert-image-resource-group}'/${image_resourcegroup}}\njob_xml=${job_xml//'{insert-image-name}'/${image}}\njob_xml=${job_xml//'{insert-dns-name}'/${vm_dns}}\njob_xml=${job_xml//'{insert-repository-url}'/${repository}}\njob_xml=${job_xml//'{insert-oms-workspace-id}'/${oms_workspace_id}}\njob_xml=${job_xml//'{insert-oms-workspace-key}'/${oms_workspace_key}}\n\n# prepare credential xml\ncredentials_xml=${credentials_xml//'{insert-credentials-id}'/${credential_id}}\ncredentials_xml=${credentials_xml//'{insert-credentials-description}'/${credential_description}}\ncredentials_xml=${credentials_xml//'{insert-user-name}'/${vm_username}}\ncredentials_xml=${credentials_xml//'{insert-user-password}'/${vm_password}}\n\n# add job\necho \"${job_xml}\" > job.xml\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-job ${job_short_name}\" -cif \"job.xml\"\n\n# add credential\necho \"${credentials_xml}\" > credentials.xml\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif \"credentials.xml\"\n\n# install tools\nsudo apt-get install unzip --yes\n\nwget https://releases.hashicorp.com/packer/1.1.3/packer_1.1.3_linux_amd64.zip\nunzip packer_1.1.3_linux_amd64.zip -d /usr/bin\n\nwget https://releases.hashicorp.com/terraform/0.11.1/terraform_0.11.1_linux_amd64.zip\nunzip terraform_0.11.1_linux_amd64.zip -d /usr/bin\n\n# cleanup\nrm job.xml\nrm credentials.xml\nrm jenkins-cli.jar\nrm packer_1.1.3_linux_amd64.zip\nrm terraform_0.11.1_linux_amd64.zip\n", "num_lines": 241}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Update apt-get package list\napt-get update\n\n# Install Java\napt-get -y install openjdk-8-jdk\n\n# https://devops.profitbricks.com/tutorials/how-to-install-and-configure-tomcat-8-on-ubuntu-1604/\n\n# Create a tomcat group\ngroupadd tomcat\n# Create a new tomcat user and make this user member of the tomcat group with home directory /opt/tomcat\nuseradd -s /bin/false -g tomcat -d /opt/tomcat tomcat\n\n# Install Tomcat\nwget https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.24/bin/apache-tomcat-8.5.24.tar.gz\ntar -xzvf apache-tomcat-8.5.24.tar.gz\nmv apache-tomcat-8.5.24 /opt/tomcat\n\n# Give proper permission to the tomcat user to access to the Tomcat installation.\nchgrp -R tomcat /opt/tomcat\nchown -R tomcat /opt/tomcat\nchmod -R 755 /opt/tomcat\n\nif [ ! -z \"$repository_url\" ];\nthen\n    # Clone code\n    cd /tmp\n    git clone $repository_url\n\n    # Deploy code to ROOT\n    rm -rf /opt/tomcat/webapps/ROOT/*\n    cp -r /tmp/azure-quickstart-templates/jenkins-cicd-vmss/HelloWorld/WebContent/* /opt/tomcat/webapps/ROOT\nelse\n    echo 'ERROR: Repository URL is not provided'\nfi\n\n#echo 'export CATALINA_HOME=\"/opt/tomcat9\"' >> /etc/environment\n#echo 'export JAVA_HOME=\"/usr/lib/jvm/java-8-openjdk-amd64\"' >> /etc/environment\n#echo 'export JRE_HOME=\"/usr/lib/jvm/java-8-openjdk-amd64/jre\"' >> /etc/environment\n\n# Create a systemd Service File\necho \"[Unit]\nDescription=Apache Tomcat Web Server\nAfter=network.target\n\n[Service]\nType=forking\n\nEnvironment=JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64/jre\nEnvironment=CATALINA_PID=/opt/tomcat/temp/tomcat.pid\nEnvironment=CATALINA_HOME=/opt/tomcat\nEnvironment=CATALINA_BASE=/opt/tomcat\nEnvironment='CATALINA_OPTS=-Xms512M -Xmx1024M -server -XX:+UseParallelGC'\nEnvironment='JAVA_OPTS=-Djava.awt.headless=true -Djava.security.egd=file:/dev/./urandom'\n\nExecStart=/opt/tomcat/bin/startup.sh\nExecStop=/opt/tomcat/bin/shutdown.sh\n\nUser=tomcat\nGroup=tomcat\nUMask=0007\nRestartSec=15\nRestart=always\n\n[Install]\nWantedBy=multi-user.target\" >> /etc/systemd/system/tomcat.service\n\n# Reload the systemd daemon for the new service file above\nsystemctl daemon-reload\n# Start the Tomcat service\nsystemctl start tomcat\n# Configure the Tomcat service to start during boot\nsystemctl enable tomcat\n\n# https://stackoverflow.com/questions/4756039/how-to-change-the-port-of-tomcat-from-8080-to-80\n# https://dzone.com/articles/running-tomcat-port-80-user\n# http://2ality.blogspot.com/2010/07/running-tomcat-on-port-80-in-user.html\n\n# Change default port to 80 from 8080\nsed -i 's/Connector port=\"8080\"/Connector port=\"80\"/g' /opt/tomcat/conf/server.xml\napt-get install authbind\ntouch /etc/authbind/byport/80\nchmod 500 /etc/authbind/byport/80\nchown tomcat /etc/authbind/byport/80\necho 'CATALINA_OPTS=\"-Djava.net.preferIPv4Stack=true\"' >> /opt/tomcat/bin/setenv.sh\nsed -i 's/exec \"$PRGDIR\"\\/\"$EXECUTABLE\" start \"$@\"/exec authbind --deep \"$PRGDIR\"\\/\"$EXECUTABLE\" start \"$@\"/g' /opt/tomcat/bin/startup.sh\n\n/usr/sbin/waagent -force -deprovision+user && export HISTSIZE=0 && sync\n\nif [ ! -z \"$oms_workspace_id\" -a ! -z \"$oms_workspace_key\" ];\nthen\n    wget https://raw.githubusercontent.com/Microsoft/OMS-Agent-for-Linux/master/installer/scripts/onboard_agent.sh && sh onboard_agent.sh -w $oms_workspace_id -s $oms_workspace_key -d opinsights.azure.com\nelse\n    echo 'ERROR: OMS workspace id or key is not provided'\nfi\n", "num_lines": 98}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction print_usage() {\n  cat <<EOF\nCommand\n  $0\nArguments\n  --jenkins_fqdn|-jf              [Required] : Jenkins FQDN\n  --jenkins_private_ip|-jpi                  : The VM private ip used to configure Jenkins URL. If missing, jenkins_fqdn will be used instead\n  --jenkins_release_type|-jrt                : The Jenkins release type (LTS or weekly or verified). By default it's set to LTS\n  --jenkins_version_location|-jvl            : Url used to specify the version of Jenkins.\n  --subscription|-su               [Required]: Azure subscription id\n  --tenant|-t                      [Required]: Azure tenant id\n  --clientid|-i                    [Required]: Azure service principal client id\n  --clientsecret|-s                [Required]: Azure service principal client secret\n  --storage_account_name|-sn       [Required]: Azure storage account name\n  --storage_account_key|-sk        [Required]: Azure storage account key\n  --resourcegroup|-rg              [Required]: Azure resource group for the components\n  --webapp|-w                      [Required]: Azure web app name\n  --repository|-rr                 [Required]: Repository targeted by the build\n  --artifacts_location|-al                   : Url used to reference other scripts/artifacts.\n  --sas_token|-st                            : A sas token needed if the artifacts location is private.\nEOF\n}\n\nfunction throw_if_empty() {\n  local name=\"$1\"\n  local value=\"$2\"\n  if [ -z \"$value\" ]; then\n    >&2 echo \"Parameter '$name' cannot be empty.\"\n    print_usage\n    exit -1\n  fi\n}\n\nfunction ms_run_util_script() {\n  local script_path=\"$1\"\n  shift\n  curl --silent \"${ms_artifacts_location}${script_path}${ms_artifacts_location_sas_token}\" | sudo bash -s -- \"$@\"\n  local return_value=$?\n  if [ $return_value -ne 0 ]; then\n    >&2 echo \"Failed while executing script '$script_path'.\"\n    exit $return_value\n  fi\n}\n\n# set defaults\njenkins_url=\"http://localhost:8080/\"\njenkins_username=\"admin\"\njenkins_password=\"\"\njenkins_agent_port=5378\njob_short_name=\"BuildWebApp\"\ncredential_sp_id='mySP'\ncredential_sp_description='Azure Service Principal'\ncredential_storage_id='myStorage'\ncredential_storage_description='Microsoft Azure Storage\t'\naci_container_name='ACI-container'\naci_container_image='cloudbees/jnlp-slave-with-java-build-tools'\nms_artifacts_location=\"https://raw.githubusercontent.com/Azure/azure-devops-utils/v0.28.1/\"\nms_artifacts_location_sas_token=\"\"\n\nwhile [[ $# > 0 ]]\ndo\n  key=\"$1\"\n  shift\n  case $key in\n    --jenkins_fqdn|-jf)\n      jenkins_fqdn=\"$1\"\n      shift\n      ;;\n    --jenkins_private_ip|-jpi)\n      jenkins_private_ip=\"$1\"\n      shift\n      ;;\n    --jenkins_release_type|-jrt)\n      jenkins_release_type=\"$1\"\n      shift\n      ;;\n    --jenkins_version_location|-jvl)\n      jenkins_version_location=\"$1\"\n      shift\n      ;;\n    --subscription|-su)\n      subscription=\"$1\"\n      shift\n      ;;\n    --tenant|-t)\n      tenant=\"$1\"\n      shift\n      ;;\n    --clientid|-i)\n      clientid=\"$1\"\n      shift\n      ;;\n    --clientsecret|-s)\n      clientsecret=\"$1\"\n      shift\n      ;;\n    --storage_account_name|-sn)\n      storage_account_name=\"$1\"\n      shift\n      ;;\n    --storage_account_key|-sk)\n      storage_account_key=\"$1\"\n      shift\n      ;;\n    --resourcegroup|-rg)\n      resourcegroup=\"$1\"\n      shift\n      ;;\n    --webapp|-w)\n      webapp=\"$1\"\n      shift\n      ;;\n    --repository|-rr)\n      repository=\"$1\"\n      shift\n      ;;\n    --artifacts_location|-al)\n      artifacts_location=\"$1\"\n      shift\n      ;;\n    --sas_token|-st)\n      artifacts_location_sas_token=\"$1\"\n      shift\n      ;;\n    --help|-help|-h)\n      print_usage\n      exit 13\n      ;;\n    *)\n      >&2 echo \"ERROR: Unknown argument '$key' to script '$0'\"\n      exit -1\n  esac\ndone\n\n# ==================================== VALIDATION ====================================\nthrow_if_empty jenkins_username $jenkins_username\nif [ \"$jenkins_username\" != \"admin\" ]; then\n  throw_if_empty jenkins_password $jenkins_password\nfi\nthrow_if_empty --jenkins_fqdn $jenkins_fqdn\nthrow_if_empty --subscription $subscription\nthrow_if_empty --tenant $tenant\nthrow_if_empty --clientid $clientid\nthrow_if_empty --clientsecret $clientsecret\nthrow_if_empty --storage_account_name $storage_account_name\nthrow_if_empty --storage_account_key $storage_account_key\nthrow_if_empty --resourcegroup $resourcegroup\nthrow_if_empty --webapp $webapp\nthrow_if_empty --repository $repository\n\n# ==================================== INSTALL JENKINS ====================================\nms_run_util_script \"jenkins/install_jenkins.sh\" -jf \"${jenkins_fqdn}\" -pi \"${jenkins_private_ip}\" -jrt \"${jenkins_release_type}\" -jvl \"${jenkins_version_location}\" -al \"${ms_artifacts_location}\" -st \"${ms_artifacts_location_sas_token}\"\n\n# ==================================== PLUGIN ====================================\n# install required plugins\nplugins=(credentials envinject)\nfor plugin in \"${plugins[@]}\"; do\n  ms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"install-plugin $plugin -deploy\"\ndone\n\n# ==================================== JNLP ====================================\n# open a fixed port for JNLP\ninter_jenkins_config=$(sed -zr -e\"s|<slaveAgentPort.*</slaveAgentPort>|<slaveAgentPort>{slave-agent-port}</slaveAgentPort>|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{slave-agent-port}'/${jenkins_agent_port}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n# ==================================== RESTART JENKINS ====================================\n# restart jenkins\nsudo service jenkins restart\n\n# wait for instance to be back online\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"version\"\n\n# ==================================== CREDENTIAL ====================================\n# download credential dependencies\ncredentials_sp_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-sp.xml${artifacts_location_sas_token})\ncredentials_storage_xml=$(curl -s ${artifacts_location}/scripts/jenkins/credentials-storage.xml${artifacts_location_sas_token})\n\n# prepare credentials_sp.xml (service principal)\ncredentials_sp_xml=${credentials_sp_xml//'{insert-credentials-id}'/${credential_sp_id}}\ncredentials_sp_xml=${credentials_sp_xml//'{insert-credentials-description}'/${credential_sp_description}}\ncredentials_sp_xml=${credentials_sp_xml//'{insert-subscription-id}'/${subscription}}\ncredentials_sp_xml=${credentials_sp_xml//'{insert-client-id}'/${clientid}}\ncredentials_sp_xml=${credentials_sp_xml//'{insert-client-secret}'/${clientsecret}}\ncredentials_sp_xml=${credentials_sp_xml//'{insert-tenant-id}'/${tenant}}\n\n# prepare credentials_storage.xml (storage account)\ncredentials_storage_xml=${credentials_storage_xml//'{insert-credentials-id}'/${credential_storage_id}}\ncredentials_storage_xml=${credentials_storage_xml//'{insert-credentials-description}'/${credential_storage_description}}\ncredentials_storage_xml=${credentials_storage_xml//'{insert-credentials-account-name}'/${storage_account_name}}\ncredentials_storage_xml=${credentials_storage_xml//'{insert-credentials-account-key}'/${storage_account_key}}\n\n# add credentials\necho \"${credentials_sp_xml}\" > credentials_sp.xml\necho \"${credentials_storage_xml}\" > credentials_storage.xml\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif \"credentials_sp.xml\"\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-credentials-by-xml system::system::jenkins _\" -cif \"credentials_storage.xml\"\n\n# ==================================== ACI AGENT ====================================\n# download aci agent dependencies\nconfigs_agent_aci_xml=$(curl -s ${artifacts_location}/scripts/jenkins/configs-agent-aci.xml${artifacts_location_sas_token})\n\n# configure Azure Container Instance\nconfigs_agent_aci_xml=${configs_agent_aci_xml//'{insert-credentials-id}'/${credential_sp_id}}\nconfigs_agent_aci_xml=${configs_agent_aci_xml//'{insert-resourcegroup-name}'/${resourcegroup}}\nconfigs_agent_aci_xml=${configs_agent_aci_xml//'{insert-aci-container-name}'/${aci_container_name}}\nconfigs_agent_aci_xml=${configs_agent_aci_xml//'{insert-aci-container-image}'/${aci_container_image}}\n\ninter_jenkins_config=$(sed -zr -e\"s|<clouds/>|{clouds}|\" /var/lib/jenkins/config.xml)\nfinal_jenkins_config=${inter_jenkins_config//'{clouds}'/${configs_agent_aci_xml}}\necho \"${final_jenkins_config}\" | sudo tee /var/lib/jenkins/config.xml > /dev/null\n\n# ==================================== RELOAD CONFIG ====================================\nms_run_util_script \"jenkins/run-cli-command.sh\" -c \"reload-configuration\"\n\n# ==================================== JOB ====================================\n# download job dependencies\njob_xml=$(curl -s ${artifacts_location}/scripts/jenkins/jobs-build-webapp.xml${artifacts_location_sas_token})\n\n# prepare job.xml\njob_xml=${job_xml//'{insert-repository-url}'/${repository}}\njob_xml=${job_xml//'{insert-aci-container}'/${aci_container_name}}\njob_xml=${job_xml//'{insert-credentials-storage-id}'/${credential_storage_id}}\njob_xml=${job_xml//'{insert-credentials-sp-id}'/${credential_sp_id}}\njob_xml=${job_xml//'{insert-resourcegroup-name}'/${resourcegroup}}\njob_xml=${job_xml//'{insert-webapp-name}'/${webapp}}\n\n# add job\necho \"${job_xml}\" > job.xml\nms_run_util_script \"jenkins/run-cli-command.sh\" -j \"$jenkins_url\" -ju \"$jenkins_username\" -jp \"$jenkins_password\" -c \"create-job ${job_short_name}\" -cif \"job.xml\"\n\n# ==================================== CLEANUP ====================================\nrm job.xml\nrm credentials_sp.xml\nrm credentials_storage.xml\nrm jenkins-cli.jar\n", "num_lines": 239}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "wget -q -O - https://pkg.jenkins.io/debian-stable/jenkins.io.key | sudo apt-key add -\nsh -c 'echo deb https://pkg.jenkins.io/debian-stable binary/ >  /etc/apt/sources.list.d/jenkins.list'\napt update -y\napt install openjdk-8-jdk git maven docker.io  -y\napt install jenkins -y\nsystemctl enable jenkins\nsystemctl enable docker\nusermod -aG docker jenkins\n## Create the TOOLS directory \n## Create TOOLS directory for jenkins\nmkdir /opt/tools/\ncd /opt/tools\n## Install solar scanner\nwget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.2.0.1873-linux.zip\njar -xvf sonar-scanner-cli-4.2.0.1873-linux.zip\nmv sonar-scanner-4.2.0.1873-linux/ sonar/\nrm sonar-scanner-cli-4.2.0.1873-linux.zip\n### SONARQUBE SETUP\n# Update kernel memory page limits and max files limits (MANDATORY FOR SONARQUBE)\nsysctl -w vm.max_map_count=262144\nsysctl -w fs.file-max=65536\nulimit -n 65536\nulimit -u 4096\n# Download SonarQube 7.1 (Compatible with JDK 8)\nwget https://binaries.sonarsource.com/Distribution/sonarqube/sonarqube-7.1.zip\njar -xvf sonarqube-7.1.zip\ngroupadd sonar\nsudo useradd -c \"user to run SonarQube\" -d /opt/tools/sonarqube-7.1 -g sonar sonar \ncd sonarqube-7.1/bin/linux-x86-64\n# set RUN_AS_USER=sonar\nsed -i 's/#RUN_AS_USER=/RUN_AS_USER=sonar/g' sonar.sh\nchown -R jenkins:jenkins /opt/tools/", "num_lines": 32}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "apt update -y\n## Install JDK8, Git & Maven\napt install openjdk-8-jdk git maven  -y\n## Install Docker-CE\napt install docker.io -y\n## create new jenkins user\nuseradd -m -s /bin/bash jenkins\n## Allow JENKINS user to access docker\nusermod -aG docker jenkins\n## Create TOOLS directory for jenkins\nmkdir /opt/tools/\ncd /opt/tools\n## install solar-scanner\nwget https://binaries.sonarsource.com/Distribution/sonar-scanner-cli/sonar-scanner-cli-4.2.0.1873-linux.zip\njar -xvf sonar-scanner-cli-4.2.0.1873-linux.zip\nmv sonar-scanner-4.2.0.1873-linux/ sonar/\nrm sonar-scanner-cli-4.2.0.1873-linux.zip\n## Change OWNER of tools to \"jenkins\"\nchown -R jenkins:jenkins /opt/tools/", "num_lines": 19}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script: jenkMstrInstall.sh\n#\n# Author: Dennis Angeline (Full Scale 180 Inc)\n#\n# Description:\n#    This script install Jenkins master on an Ubuntu VM image\n#    and optionally configures tohe master with multiple dumb slave nodes.\n#\n# Parameters :\n#    -n number of dumb slave nodes to configure\n#    -h view this help content\n#\n# Note :\n#    This script has only been tested on Ubuntu 14.04 LTS\n#\n\nhelp()\n{\n\n    echo \"This script install Jenkins master on an Ubuntu VM image\"\n    echo \"Parameters:\"\n    echo \"-n number of slave nodes to configure on the master\"\n    echo \"-h view this help content\"\n}\n\n#Log method to control/redirect log output\nlog()\n{\n    echo \"$1\"\n}\n\n\n#Script Parameters\nNODECNT=0\n\n#Loop through options passed\nwhile getopts :n:h optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n\n  case $optname in\n    n)  #set number of slave nodes\n      NODECNT=${OPTARG}\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nlog \"Begin execution of Jenkins install script on ${HOSTNAME} with ${NODECNT} slave nodes\"\n\n\n# Install openjdk-7\ninstall_java()\n{\n    log \"Installing openjdk-7\"\n    apt-get -y update > /dev/null\n    apt-get -y install openjdk-7-jdk > /dev/null\n    apt-get -y update > /dev/null\n}\n\n\n# Install jenkins master\ninstall_jenkins()\n{\n    log \"Installing Jenkins master\"\n    wget -q -O - https://jenkins-ci.org/debian/jenkins-ci.org.key | sudo apt-key add -\n    sh -c 'echo deb http://pkg.jenkins-ci.org/debian binary/ > /etc/apt/sources.list.d/jenkins.list'\n    apt-get -y update > /dev/null\n    apt-get -y install jenkins > /dev/null\n\n    log \"Waiting for Jenkins master to start...\"\n    sleep 60\n}\n\n\n# Configure jenkins slave nodes\nconfigure_slave_nodes()\n{\n    log \"Configuring Jenkins master with $NODECNT dumb slave node(s)\"\n\n    if [ $NODECNT -gt 0 ]; then\n        # Run groovy script to configure master with $NODECNT dumb slave node(s)\n        sudo java -jar /var/cache/jenkins/war/WEB-INF/jenkins-cli.jar -s http://localhost:8080 groovy jenkAddNode.groovy $NODECNT\n    fi\n}\n\n# Primary Install Tasks\ninstall_java\ninstall_jenkins\nconfigure_slave_nodes\nexit 0\n\n", "num_lines": 124}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script: jenkSlaveInstall.sh\n#\n# Author: Dennis Angeline (Full Scale 180 Inc)\n#\n# Description:\n#    This script install Jenkins slave on an Ubuntu VM image\n#\n# Parameters :\n#    -m The ip address of the master node\n#    -s The name of THIS slave node as configured on the master\n#    -h view this help content\n#\n# Note :\n#    This script has only been tested on Ubuntu 14.04 LTS\n#\n\nhelp()\n{\n\n    echo \"This script install Jenkins slave on an Ubuntu VM\"\n    echo \"Parameters:\"\n    echo \"-m The ip address of the master node\"\n    echo \"-s The name of THIS slave node as configured on the master\"\n    echo \"-h view this help content\"\n}\n\n#Log method to control/redirect log output\nlog()\n{\n    echo \"$1\"\n}\n\nlog \"Begin execution of Jenkins slave install script on ${HOSTNAME}\"\n\n#Script Parameters\nMASTERNODE=\"missing\"\nSLAVENAME=\"missing\"\n\n#Loop through options passed\nwhile getopts :m:s:h optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n\n  case $optname in\n    m)  #set the ip address of the master\n      MASTERNODE=${OPTARG}\n      ;;\n    s)  #set the name of this slave node\n      SLAVENAME=${OPTARG}\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install openjdk-7\ninstall_java()\n{\n    log \"Installing openjdk-7\"\n    apt-get -y update > /dev/null\n    apt-get -y install openjdk-7-jdk > /dev/null\n    apt-get -y update > /dev/null\n}\n\ndownload_slave_jar()\n{\n    log \"Downloading slave.jar from $MASTERNODE\"\n    wget http://$MASTERNODE:8080/jnlpJars/slave.jar -O ~/slave.jar > /dev/null\n    chmod 777 ~/slave.jar\n}\n\ncreate_upstart_task()\n{\n    upstart_conf=\"/etc/init/jenkins_slave.conf\"\n\n    log \"Creating Upstart conf file $upstart_conf\"\n    echo \"# Jenkin Slave\"                                                                                     > $upstart_conf\n    echo \"description \\\"slave node for Jenkins Continuous Integration Service\\\"\"                             >> $upstart_conf\n    echo \"\"                                                                                                  >> $upstart_conf\n    echo \"start on starting\"                                                                                 >> $upstart_conf\n    echo \"script\"                                                                                            >> $upstart_conf\n    echo \"  java -jar /root/slave.jar -jnlpUrl http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp\" >> $upstart_conf\n    echo \"end script\"                                                                                        >> $upstart_conf\n\n    chmod +x $upstart_conf\n}\n\nstart_slave()\n{\n    log \"Executing slave.jar with http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp\"\n    service jenkins_slave start\n    # nohup java -jar ~/slave.jar -jnlpUrl http://$MASTERNODE:8080/computer/$SLAVENAME/slave-agent.jnlp &\n}\n\n# Primary Install Tasks\n\nif [ $MASTERNODE == \"missing\" ]; then\n    log \"Master node not specified\"\n    exit 1\nfi\n\nif [ $SLAVENAME == \"missing\" ]; then\n    log \"Slave name not specified\"\n    exit 2\nfi\n\n\ninstall_java\ndownload_slave_jar\ncreate_upstart_task\nstart_slave\nexit 0\n\n\n", "num_lines": 145}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nbootstrap.py | sudo python3 - --admin $1 >> /var/log/TLJH_install.log 2>&1\n", "num_lines": 4}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# Author: Cognosys Technologies\n\n###\n### Warning! This script partitions and formats disk information be careful where you run it\n###          This script is currently under development and has only been tested on Ubuntu images in Azure\n###          This script is not currently idempotent and only works for provisioning at the moment\n\n### Remaining work items\n### -Alternate discovery options (Azure Storage)\n### -Implement Idempotency and Configuration Change Support\n### -Recovery Settings (These can be changed via API)\n\nhelp()\n{\n    #TODO: Add help text here\n    echo \"This script installs kafka cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-k kafka version like 0.8.2.1\"\n    echo \"-b broker id\"\n    echo \"-h view this help content\"\n    echo \"-z zookeeper not kafka\"\n    echo \"-i zookeeper Private IP address prefix\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n    \t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/[account-key]/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of kafka script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? -eq $SUCCESS ];\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hsots file if not there\n  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\nfi\n\n#Script Parameters\nKF_VERSION=\"0.8.2.1\"\nBROKER_ID=0\nZOOKEEPER1KAFKA0=\"0\"\n\nZOOKEEPER_IP_PREFIX=\"10.0.0.4\"\nINSTANCE_COUNT=1\nZOOKEEPER_PORT=\"2181\"\n\n#Loop through options passed\nwhile getopts :k:b:z:i:c:p:h optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    k)  #kafka version\n      KF_VERSION=${OPTARG}\n      ;;\n    b)  #broker id\n      BROKER_ID=${OPTARG}\n      ;;\n    z)  #zookeeper not kafka\n      ZOOKEEPER1KAFKA0=${OPTARG}\n      ;;\n    i)  #zookeeper Private IP address prefix\n      ZOOKEEPER_IP_PREFIX=${OPTARG}\n      ;;\n    c) # Number of instances\n\tINSTANCE_COUNT=${OPTARG}\n\t;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Oracle Java\ninstall_java()\n{\n    log \"Installing Java\"\n    apt-get update\n    apt-get -y install openjdk-8-jdk\n    export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\n}\n\n# Expand a list of successive IP range defined by a starting address prefix (e.g. 10.0.0.1) and the number of machines in the range\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\n\nexpand_ip_range_for_server_properties() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        echo \"server.$(expr ${n} + 1)=${HOST_IPS[0]}${n}:2888:3888\" >> apache-zookeeper-3.6.3/conf/zoo.cfg\n    done\n}\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\n\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}:${ZOOKEEPER_PORT}\"\n                EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n    done\n\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\n# Install Zookeeper - can expose zookeeper version\ninstall_zookeeper()\n{\n  apt-get update\n\tapt-get -y install zookeeperd\n  mkdir /usr/local/zookeeper/data\n  chmod -R 755 /usr/local/zookeeper/data\n\n\techo \"tickTime=2000\" > /etc/zookeeper/conf/zoo.cfg\n\techo \"dataDir=/usr/local/zookeeper/data\" > /etc/zookeeper/conf/zoo.cfg\n\techo \"clientPort=2181\" > /etc/zookeeper/conf/zoo.cfg\n\techo \"initLimit=5\" > /etc/zookeeper/conf/zoo.cfg\n\techo \"syncLimit=2\" > /etc/zookeeper/conf/zoo.cfg\n\t$(expand_ip_range_for_server_properties \"${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}\")\n\n\techo $(($1+1)) >> /usr/share/zookeeper/myid\n\n\t/usr/share/zookeeper/bin/zkServer.sh start\n}\n\n# Install kafka\ninstall_kafka()\n{\n\tcd /usr/local\n\tname=kafka\n\tversion=${KF_VERSION}\n\t#this Kafka version is prefix same used for all versions\n\tkafkaversion=2.10\n\tdescription=\"Apache Kafka is a distributed publish-subscribe messaging system.\"\n\turl=\"https://kafka.apache.org/\"\n\tarch=\"all\"\n\tsection=\"misc\"\n\tlicense=\"Apache Software License 2.0\"\n\tpackage_version=\"-1\"\n\tsrc_package=\"kafka_${kafkaversion}-${version}.tgz\"\n\tdownload_url=http://mirror.sdunix.com/apache/kafka/${version}/${src_package}\n\n\trm -rf kafka\n\tmkdir -p kafka\n\tcd kafka\n\t#_ MAIN _#\n\tif [[ ! -f \"${src_package}\" ]]; then\n\t  wget ${download_url}\n\tfi\n\ttar zxf ${src_package}\n\tcd kafka_${kafkaversion}-${version}\n\n\tsed -r -i \"s/(broker.id)=(.*)/\\1=${BROKER_ID}/g\" config/server.properties\n\tsed -r -i \"s/(zookeeper.connect)=(.*)/\\1=$(join , $(expand_ip_range \"${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}\"))/g\" config/server.properties\n#\tcp config/server.properties config/server-1.properties\n#\tsed -r -i \"s/(broker.id)=(.*)/\\1=1/g\" config/server-1.properties\n#\tsed -r -i \"s/^(port)=(.*)/\\1=9093/g\" config/server-1.properties````\n\tchmod u+x /usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh\n\t/usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh /usr/local/kafka/kafka_${kafkaversion}-${version}/config/server.properties &\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n#Install Oracle Java\n#------------------------\ninstall_java\n\nif [ ${ZOOKEEPER1KAFKA0} -eq \"1\" ];\nthen\n\t#\n\t#Install zookeeper\n\t#-----------------------\n\tinstall_zookeeper\nelse\n\t#\n\t#Install kafka\n\t#-----------------------\n\tinstall_kafka\nfi\n\n", "num_lines": 231}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# Author: Cognosys Technologies\n\n###\n### Warning! This script partitions and formats disk information be careful where you run it\n###          This script is currently under development and has only been tested on Ubuntu images in Azure\n###          This script is not currently idempotent and only works for provisioning at the moment\n\n### Remaining work items\n### -Alternate discovery options (Azure Storage)\n### -Implement Idempotency and Configuration Change Support\n### -Recovery Settings (These can be changed via API)\n\nhelp()\n{\n    #TODO: Add help text here\n    echo \"This script installs kafka cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-k kafka version like 0.8.2.1\"\n    echo \"-b broker id\"\n    echo \"-h view this help content\"\n    echo \"-z zookeeper not kafka\"\n    echo \"-i zookeeper Private IP address prefix\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n    \t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/[account-key]/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of kafka script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n#Format the data disk\nbash vm-disk-utils-0.1.sh -s\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? -eq $SUCCESS ];\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hsots file if not there\n  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\nfi\n\n#Script Parameters\nKF_VERSION=\"0.8.2.1\"\nBROKER_ID=0\nZOOKEEPER1KAFKA0=\"0\"\n\nZOOKEEPER_IP_PREFIX=\"10.0.1.10\"\nINSTANCE_COUNT=1\nZOOKEEPER_PORT=\"2181\"\nKAFKADIR=\"/var/lib/kafkadir\"\n# sed command issues need escape character \\\nKAFKADIRSED=\"\\/var\\/lib\\/kafkadir\"\n\n#Loop through options passed\nwhile getopts :k:b:z:i:c:p:h optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    k)  #kafka version\n      KF_VERSION=${OPTARG}\n      ;;\n    b)  #broker id\n      BROKER_ID=${OPTARG}\n      ;;\n    z)  #zookeeper not kafka\n      ZOOKEEPER1KAFKA0=${OPTARG}\n      ;;\n    i)  #zookeeper Private IP address prefix\n      ZOOKEEPER_IP_PREFIX=${OPTARG}\n      ;;\n    c) # Number of instances\n\tINSTANCE_COUNT=${OPTARG}\n\t;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\n# Install Oracle Java\n\n# install_java()\n# {\n#     log \"Installing Java\"\n#     add-apt-repository -y ppa:webupd8team/java\n#     apt-get -y update\n#     echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n#     echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n#     apt-get -y install oracle-java7-installer\n# \tjava -version\n# }\n\ninstall_java()\n{\n    if [ -f \"jdk-8u291-linux-x64.tar.gz\" ];\n    then\n        log \"Java already downloaded\"\n        return\n    fi\n\n    log \"Installing Java\"\n    RETRY=0\n    MAX_RETRY=5\n    while [ $RETRY -lt $MAX_RETRY ]; do\n        log \"Retry $RETRY: downloading jdk-8u291-linux-x64.tar.gz\"\n        wget --no-check-certificate --no-cookies --header \"Cookie: oraclelicense=accept-securebackup-cookie\" https://download.oracle.com/otn-pub/java/jdk/8u291-b10/d7fc238d0cbf4b0dac67be84580cfb4b/jdk-8u291-linux-x64.tar.gz\n        if [ $? -ne 0 ]; then\n            let RETRY=RETRY+1\n        else\n            break\n        fi\n    done\n    if [ $RETRY -eq $MAX_RETRY ]; then\n        log \"Failed to download jdk-8u291-linux-x64.tar.gz\"\n        exit 1\n    fi\n\n    tar xzf jdk-8u291-linux-x64.tar.gz -C /var/lib\n    export JAVA_HOME=/var/lib/jdk1.8.0_291\n    export PATH=$PATH:$JAVA_HOME/bin\n    log \"JAVA_HOME: $JAVA_HOME\"\n    log \"PATH: $PATH\"\n\n    java -version\n    if [ $? -ne 0 ]; then\n        log \"Java installation failed\"\n        exit 1\n    fi\n}\n\n\n# Expand a list of successive IP range defined by a starting address prefix (e.g. 10.0.0.1) and the number of machines in the range\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\n\nexpand_ip_range_for_server_properties() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        echo \"server.$(expr ${n} + 1)=${HOST_IPS[0]}${n}:2888:3888\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n    done\n}\n\nfunction join { local IFS=\"$1\"; shift; echo \"$*\"; }\n\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}:${ZOOKEEPER_PORT}\"\n                EXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n    done\n\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\n# Install Zookeeper - can expose zookeeper version\ninstall_zookeeper()\n{\n\tmkdir -p /var/lib/zookeeper\n\tcd /var/lib/zookeeper\n\twget \"http://mirrors.ukfast.co.uk/sites/ftp.apache.org/zookeeper/zookeeper-3.5.9/apache-zookeeper-3.5.9.tar.gz\"\n\ttar -xvf \"apache-zookeeper-3.5.9.tar.gz\"\n\n\ttouch apache-zookeeper-3.5.9/conf/zoo.cfg\n\n\techo \"tickTime=2000\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n\techo \"dataDir=/var/lib/zookeeper\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n\techo \"clientPort=2181\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n\techo \"initLimit=5\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n\techo \"syncLimit=2\" >> apache-zookeeper-3.5.9/conf/zoo.cfg\n\t# OLD Test echo \"server.1=${ZOOKEEPER_IP_PREFIX}:2888:3888\" >> zookeeper-3.4.6/conf/zoo.cfg\n\t$(expand_ip_range_for_server_properties \"${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}\")\n\n\techo $(($1+1)) >> /var/lib/zookeeper/myid\n\n\tapache-zookeeper-3.5.9/bin/zkServer.sh start\n}\n\n# Setup datadisks\nsetup_datadisks() {\n\n\tMOUNTPOINT=\"/datadisks/disk1\"\n\n\t# Move database files to the striped disk\n\tif [ -L ${KAFKADIR} ];\n\tthen\n\t\tlogger \"Symbolic link from ${KAFKADIR} already exists\"\n\t\techo \"Symbolic link from ${KAFKADIR} already exists\"\n\telse\n\t\tlogger \"Moving  data to the $MOUNTPOINT/kafkadir\"\n\t\techo \"Moving Kafka data to the $MOUNTPOINT/kafkadir\"\n\t\tmv ${KAFKADIR} $MOUNTPOINT/kafkadir\n\n\t\t# Create symbolic link so that configuration files continue to use the default folders\n\t\tlogger \"Create symbolic link from ${KAFKADIR} to $MOUNTPOINT/kafkadir\"\n\t\tln -s $MOUNTPOINT/kafkadir ${KAFKADIR}\n\tfi\n}\n\n# Install kafka\ninstall_kafka()\n{\n\tcd /usr/local\n\tname=kafka\n\tversion=${KF_VERSION}\n\t#this Kafka version is prefix same used for all versions\n\tkafkaversion=2.10\n\tdescription=\"Apache Kafka is a distributed publish-subscribe messaging system.\"\n\turl=\"https://kafka.apache.org/\"\n\tarch=\"all\"\n\tsection=\"misc\"\n\tlicense=\"Apache Software License 2.0\"\n\tpackage_version=\"-1\"\n\tsrc_package=\"kafka_${kafkaversion}-${version}.tgz\"\n\tdownload_url=http://mirror.sdunix.com/apache/kafka/${version}/${src_package}\n\n\trm -rf kafka\n\tmkdir -p kafka\n\tcd kafka\n\t#_ MAIN _#\n\tif [[ ! -f \"${src_package}\" ]]; then\n\t  wget ${download_url}\n\tfi\n\ttar zxf ${src_package}\n\tcd kafka_${kafkaversion}-${version}\n\n\tsed -r -i \"s/(broker.id)=(.*)/\\1=${BROKER_ID}/g\" config/server.properties\n\tsed -r -i \"s/(zookeeper.connect)=(.*)/\\1=$(join , $(expand_ip_range \"${ZOOKEEPER_IP_PREFIX}-${INSTANCE_COUNT}\"))/g\" config/server.properties\n\tsed -r -i \"s/(log.dirs)=(.*)/\\1=${KAFKADIR}/g\" config/server.properties\n\n\tchmod u+x /usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh\n\t/usr/local/kafka/kafka_${kafkaversion}-${version}/bin/kafka-server-start.sh /usr/local/kafka/kafka_${kafkaversion}-${version}/config/server.properties &\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n#Install Oracle Java\n#------------------------\ninstall_java\n\nif [ ${ZOOKEEPER1KAFKA0} -eq \"1\" ];\nthen\n\t#\n\t#Install zookeeper\n\t#-----------------------\n\tinstall_zookeeper\nelse\n\t#\n\t#Install kafka\n\t#-----------------------\n\tmkdir ${KAFKADIR}\n\tsetup_datadisks\n\tinstall_kafka\nfi\n", "num_lines": 304}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nREMOTEMYSQLIP=$1\n\napt-get -y update\n\n#no password prompt while installing mysql server\nexport DEBIAN_FRONTEND=noninteractive\n\n#install php mysql apache\napt-get -y install apache2 php5 libapache2-mod-php5 mysql-server libapache2-mod-auth-mysql php5-mysql\n\n#php test file\ncat > /var/www/html/info.php <<EOF\n<?php\nphpinfo();\n?>\nEOF\n\n#mysql connection test file\ncat > /var/www/html/mysql.php <<EOF\n<?php\n\\$link = mysql_connect('localhost', 'root', '');\nif (!\\$link) {\n    die('Could not connect:' . mysql_error());\n}\necho 'Connected sucessfully';\n?>\nEOF\n\ncat > /var/www/html/remotemysql.php <<EOF\n<?php\n\\$link = mysql_connect('$REMOTEMYSQLIP', 'root', '');\nif (!\\$link) {\n    die('Could not connect:' . mysql_error());\n}\necho 'Connected sucessfully';\n?>\nEOF\n", "num_lines": 40}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nLAPIP=$1\n\napt-get -y update\n\n#no password prompt while installing mysql server\nexport DEBIAN_FRONTEND=noninteractive\n\n#install mysql server\napt-get -y install mysql-server\ncp -p /etc/mysql/my.cnf /etc/mysql/my.cnf.bak\nsed -i 's/\\(bind-address\\)/#\\1/' /etc/mysql/my.cnf\nservice mysql restart\n#allow $LAPIP to access\nmysql -u root -e \"use mysql;grant all privileges on *.* to 'root'@'$LAPIP';flush privileges\"\n\n\n\n", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get -y update\n\n#no password prompt while installing neo4j server\nexport DEBIAN_FRONTEND=noninteractive\n\n#install php apache\napt-get -y install apache2\n\napt-get -y install php\n\napt-get -y install libapache2-mod-php\n\n#install composer\n#curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer\n#curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/var/www/html\n#echo \"starting to install composer\"\n#php -r \"copy('https://getcomposer.org/installer', 'composer-setup.php');\"\n#php -r \"if (hash_file('SHA384', 'composer-setup.php') === '070854512ef404f16bac87071a6db9fd9721da1684cd4589b1196c3faf71b9a2682e2311b36a5079825e155ac7ce150d') { echo 'Installer verified'; } else { echo 'Installer corrupt'; unlink('composer-setup.php'); } echo PHP_EOL;\"\n#php composer-setup.php\n#php -r \"unlink('composer-setup.php');\"\n#echo \"Composer is installed\"\ncurl -sS https://getcomposer.org/installer | php\nmv composer.phar /usr/local/bin/composer\n\n\n#php test file\ncat > /var/www/html/info.php <<EOF\n<?php\nphpinfo();\n?>\nEOF\n\n#neo4j code test\n#creating the composer.json file which uses the neoclient\ncat > /var/www/html/composer.json <<EOF\n{\n  \"require\": {\n    \"neoxygen/neoclient\":\"~2.1\"\n  }\n}\nEOF\n\n#creating the neo4jtest php file\ncat > /var/www/html/neo4jtest.php <<EOF\n<?php\n\nrequire_once 'vendor/autoload.php';\n\nuse Neoxygen\\NeoClient\\ClientBuilder;\n\n\\$client = ClientBuilder::create()\n  ->addConnection('default', 'http', '10.0.0.10', 7474,true,'neo4j','neo4j')\n  ->build();\n\nif (!\\$client) {\n    die('Could not connect with neo4j database');\n}\necho 'Connected sucessfully';\nEOF\n\necho \"everything installed successfully, lets install composer dependecies\"\n\n#composer install\ncd /var/www/html\ncomposer install\n", "num_lines": 68}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwget -O - http://debian.neo4j.org/neotechnology.gpg.key | apt-key add -\n\necho 'deb http://debian.neo4j.org/repo stable/' > /etc/apt/sources.list.d/neo4j.list\n\napt-get -y update\n#no password prompt while installing neo4j server\nexport DEBIAN_FRONTEND=noninteractive\n\n#install java\napt-get install -y python-software-properties debconf-utils\nadd-apt-repository -y ppa:webupd8team/java\napt-get update\necho \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | debconf-set-selections\napt-get install -y oracle-java8-installer\n\n#install neo4j server\napt-get -y install neo4j\n#make a copy of the config file\ncp -p /etc/neo4j/neo4j.conf /etc/neo4j/neo4j.conf.bak\n#open the http access at port 7474 to apache node\nsed -i -e '/dbms.connector.http.address/s/^#//' /etc/neo4j/neo4j.conf\nservice neo4j restart\n\n\n", "num_lines": 27}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Common functions definitions\n\nfunction check_fileServerType_param\n{\n    local fileServerType=$1\n    if [ \"$fileServerType\" != \"gluster\" -a \"$fileServerType\" != \"azurefiles\" -a \"$fileServerType\" != \"nfs\" ]; then\n        echo \"Invalid fileServerType ($fileServerType) given. Only 'gluster', 'azurefiles' or 'nfs' are allowed. Exiting\"\n        exit 1\n    fi\n}\n\nfunction create_azure_files_mahara_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n    local logFilePath=$3\n\n    az storage share create \\\n        --name mahara \\\n        --account-name $storageAccountName \\\n        --account-key $storageAccountKey \\\n        --fail-on-exist >> $logFilePath\n}\n\nfunction setup_and_mount_azure_files_mahara_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n\n    cat <<EOF > /etc/mahara_azure_files.credential\nusername=$storageAccountName\npassword=$storageAccountKey\nEOF\n    chmod 600 /etc/mahara_azure_files.credential\n\n    grep \"^//$storageAccountName.file.core.windows.net/mahara\\s\\s*/mahara\\s\\s*cifs\" /etc/fstab\n    if [ $? != \"0\" ]; then\n        echo -e \"\\n//$storageAccountName.file.core.windows.net/mahara   /mahara cifs    credentials=/etc/mahara_azure_files.credential,uid=www-data,gid=www-data,nofail,vers=3.0,dir_mode=0770,file_mode=0660,serverino,mfsymlinks\" >> /etc/fstab\n    fi\n    mkdir -p /mahara\n    mount /mahara\n}\n\n# Functions for making NFS share available\n# TODO refactor these functions with the same ones in install_gluster.sh\nfunction scan_for_new_disks\n{\n    local BLACKLIST=${1}    # E.g., /dev/sda|/dev/sdb\n    declare -a RET\n    local DEVS=$(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\")\n    for DEV in ${DEVS};\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nfunction create_raid0_ubuntu {\n    local RAIDDISK=${1}       # E.g., /dev/md1\n    local RAIDCHUNKSIZE=${2}  # E.g., 128\n    local DISKCOUNT=${3}      # E.g., 4\n    shift\n    shift\n    shift\n    local DISKS=\"$@\"\n\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        sudo apt-get -y -q install mdadm\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create $RAIDDISK --name=data --level=0 --chunk=$RAIDCHUNKSIZE --raid-devices=$DISKCOUNT $DISKS\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm/mdadm.conf\n}\n\nfunction do_partition {\n    # This function creates one (1) primary partition on the\n    # disk device, using all available space\n    local DISK=${1}   # E.g., /dev/sdc\n\n    echo \"Partitioning disk $DISK\"\n    echo -ne \"n\\np\\n1\\n\\n\\nw\\n\" | fdisk \"${DISK}\"\n    #> /dev/null 2>&1\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from fdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${DISK}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\nfunction add_local_filesystem_to_fstab {\n    local UUID=${1}\n    local MOUNTPOINT=${2}   # E.g., /mahara\n\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"\\nUUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nfunction create_filesystem_with_raid {\n    local MOUNTPOINT=${1}     # E.g., /mahara\n    local RAIDDISK=${2}       # E.g., /dev/md1\n    local RAIDPARTITION=${3}  # E.g., /dev/md1p1\n\n    mkdir -p $MOUNTPOINT\n\n    local DISKS=$(scan_for_new_disks \"/dev/sda|/dev/sdb\")\n    echo \"Disks are ${DISKS}\"\n    declare -i DISKCOUNT\n    local DISKCOUNT=$(echo \"$DISKS\" | wc -w)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT = \"0\" ];\n    then\n        echo \"No new (unpartitioned) disks available... Returning...\"\n        return\n    elif [ $DISKCOUNT -gt 1 ];\n    then\n        create_raid0_ubuntu /dev/md1 128 $DISKCOUNT $DISKS\n        do_partition ${RAIDDISK}\n        local PARTITION=\"${RAIDPARTITION}\"\n    else\n        do_partition ${DISKS}\n        local PARTITION=$(fdisk -l ${DISKS}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 ${PARTITION}\n    mkdir -p \"${MOUNTPOINT}\"\n    local UUID=$(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3}'|tr -d \"\\\"\")\n    add_local_filesystem_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nfunction configure_nfs_server_and_export {\n    local MOUNTPOINT=${1}     # E.g., /mahara\n\n    echo \"Installing nfs server...\"\n    apt install -y nfs-kernel-server\n\n    echo \"Exporting ${MOUNTPOINT}...\"\n    grep \"^${MOUNTPOINT}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${MOUNTPOINT} is already exported. Returning...\"\n    else\n        echo -e \"\\n${MOUNTPOINT}   *(rw,sync,no_root_squash)\" >> /etc/exports\n        systemctl restart nfs-kernel-server.service\n    fi\n}\n\n#This function will set Mahara's siteurl variable\n#to either the user supplied URL or will default\n#to the Azure LB public dns\nfunction configure_site_url {\n    local SITE_URL=${1}\n    local AZ_FQDN=${2}\n    if [ \"${SITE_URL}\" = \"www.example.com\" ]; then\n       siteFQDN=${AZ_FQDN}\n    fi\n}\n\n\nfunction configure_nfs_client_and_mount {\n    local NFS_SERVER=${1}     # E.g., controller-vm-ab12cd\n    local NFS_DIR=${2}        # E.g., /mahara\n    local MOUNTPOINT=${3}     # E.g., /mahara\n\n    apt install -y nfs-common\n    mkdir -p ${MOUNTPOINT}\n\n    grep \"^${NFS_SERVER}:${NFS_DIR}\" /etc/fstab > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${NFS_SERVER}:${NFS_DIR} already in /etc/fstab... skipping to add\"\n    else\n        echo -e \"\\n${NFS_SERVER}:${NFS_DIR}    ${MOUNTPOINT}    nfs    auto    0    0\" >> /etc/fstab\n    fi\n    mount ${MOUNTPOINT}\n}\n\nSERVER_TIMESTAMP_FULLPATH=\"/mahara/html/mahara/.last_modified_time.mahara_on_azure\"\nLOCAL_TIMESTAMP_FULLPATH=\"/var/www/html/mahara/.last_modified_time.mahara_on_azure\"\n\n# Create a script to sync /mahara/html/mahara (gluster/NFS) and /var/www/html/mahara (local) and set up a minutely cron job\n# Should be called by root and only on a VMSS web frontend VM\nfunction setup_html_local_copy_cron_job {\n  if [ \"$(whoami)\" != \"root\" ]; then\n    echo \"${0}: Must be run as root!\"\n    return 1\n  fi\n\n  local SYNC_SCRIPT_FULLPATH=\"/usr/local/bin/sync_mahara_html_local_copy_if_modified.sh\"\n  mkdir -p $(dirname ${SYNC_SCRIPT_FULLPATH})\n\n  local SYNC_LOG_FULLPATH=\"/var/log/mahara-html-sync.log\"\n\n  cat <<EOF > ${SYNC_SCRIPT_FULLPATH}\n#!/bin/bash\n\nsleep \\$((\\$RANDOM%30))\n\nif [ -f \"$SERVER_TIMESTAMP_FULLPATH\" ]; then\n  SERVER_TIMESTAMP=\\$(cat $SERVER_TIMESTAMP_FULLPATH)\n  if [ -f \"$LOCAL_TIMESTAMP_FULLPATH\" ]; then\n    LOCAL_TIMESTAMP=\\$(cat $LOCAL_TIMESTAMP_FULLPATH)\n  else\n    logger -p local2.notice -t mahara \"Local timestamp file ($LOCAL_TIMESTAMP_FULLPATH) does not exist. Probably first time syncing? Continuing to sync.\"\n    mkdir -p /var/www/html\n  fi\n  if [ \"\\$SERVER_TIMESTAMP\" != \"\\$LOCAL_TIMESTAMP\" ]; then\n    logger -p local2.notice -t mahara \"Server time stamp (\\$SERVER_TIMESTAMP) is different from local time stamp (\\$LOCAL_TIMESTAMP). Start syncing...\"\n    if [[ \\$(find $SYNC_LOG_FULLPATH -type f -size +20M 2> /dev/null) ]]; then\n      truncate -s 0 $SYNC_LOG_FULLPATH\n    fi\n    echo \\$(date +%Y%m%d%H%M%S) >> $SYNC_LOG_FULLPATH\n    rsync -av --delete /mahara/html/mahara /var/www/html >> $SYNC_LOG_FULLPATH\n  fi\nelse\n  logger -p local2.notice -t mahara \"Remote timestamp file ($SERVER_TIMESTAMP_FULLPATH) does not exist. Is /mahara mounted? Exiting with error.\"\n  exit 1\nfi\nEOF\n  chmod 500 ${SYNC_SCRIPT_FULLPATH}\n\n  local CRON_DESC_FULLPATH=\"/etc/cron.d/sync-mahara-html-local-copy\"\n  cat <<EOF > ${CRON_DESC_FULLPATH}\n* * * * * root ${SYNC_SCRIPT_FULLPATH}\nEOF\n  chmod 644 ${CRON_DESC_FULLPATH}\n}\n\nLAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH=\"/usr/local/bin/update_last_modified_time_update.mahara_on_azure.sh\"\n\n# Create a script to modify the last modified timestamp file (/mahara/html/mahara/last_modified_time.mahara_on_azure)\n# Should be called by root and only on the controller VM.\n# The mahara admin should run the generated script everytime the /mahara/html/mahara directory content is updated (e.g., mahara upgrade, config change or plugin install/upgrade)\nfunction create_last_modified_time_update_script {\n  if [ \"$(whoami)\" != \"root\" ]; then\n    echo \"${0}: Must be run as root!\"\n    return 1\n  fi\n\n  mkdir -p $(dirname $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH)\n  cat <<EOF > $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n#!/bin/bash\necho \\$(date +%Y%m%d%H%M%S) > $SERVER_TIMESTAMP_FULLPATH\nEOF\n\n  chmod +x $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n}\n\nfunction run_once_last_modified_time_update_script {\n  $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n}\n\n\n# Long fail2ban config command moved here\nfunction config_fail2ban\n{\n    cat <<EOF > /etc/fail2ban/jail.conf\n# Fail2Ban configuration file.\n#\n# This file was composed for Debian systems from the original one\n# provided now under /usr/share/doc/fail2ban/examples/jail.conf\n# for additional examples.\n#\n# Comments: use '#' for comment lines and ';' for inline comments\n#\n# To avoid merges during upgrades DO NOT MODIFY THIS FILE\n# and rather provide your changes in /etc/fail2ban/jail.local\n#\n\n# The DEFAULT allows a global definition of the options. They can be overridden\n# in each jail afterwards.\n\n[DEFAULT]\n\n# \"ignoreip\" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not\n# ban a host which matches an address in this list. Several addresses can be\n# defined using space separator.\nignoreip = 127.0.0.1/8\n\n# \"bantime\" is the number of seconds that a host is banned.\nbantime  = 600\n\n# A host is banned if it has generated \"maxretry\" during the last \"findtime\"\n# seconds.\nfindtime = 600\nmaxretry = 3\n\n# \"backend\" specifies the backend used to get files modification.\n# Available options are \"pyinotify\", \"gamin\", \"polling\" and \"auto\".\n# This option can be overridden in each jail as well.\n#\n# pyinotify: requires pyinotify (a file alteration monitor) to be installed.\n#            If pyinotify is not installed, Fail2ban will use auto.\n# gamin:     requires Gamin (a file alteration monitor) to be installed.\n#            If Gamin is not installed, Fail2ban will use auto.\n# polling:   uses a polling algorithm which does not require external libraries.\n# auto:      will try to use the following backends, in order:\n#            pyinotify, gamin, polling.\nbackend = auto\n\n# \"usedns\" specifies if jails should trust hostnames in logs,\n#   warn when reverse DNS lookups are performed, or ignore all hostnames in logs\n#\n# yes:   if a hostname is encountered, a reverse DNS lookup will be performed.\n# warn:  if a hostname is encountered, a reverse DNS lookup will be performed,\n#        but it will be logged as a warning.\n# no:    if a hostname is encountered, will not be used for banning,\n#        but it will be logged as info.\nusedns = warn\n\n#\n# Destination email address used solely for the interpolations in\n# jail.{conf,local} configuration files.\ndestemail = root@localhost\n\n#\n# Name of the sender for mta actions\nsendername = Fail2Ban\n\n#\n# ACTIONS\n#\n\n# Default banning action (e.g. iptables, iptables-new,\n# iptables-multiport, shorewall, etc) It is used to define\n# action_* variables. Can be overridden globally or per\n# section within jail.local file\nbanaction = iptables-multiport\n\n# email action. Since 0.8.1 upstream fail2ban uses sendmail\n# MTA for the mailing. Change mta configuration parameter to mail\n# if you want to revert to conventional 'mail'.\nmta = sendmail\n\n# Default protocol\nprotocol = tcp\n\n# Specify chain where jumps would need to be added in iptables-* actions\nchain = INPUT\n\n#\n# Action shortcuts. To be used to define action parameter\n\n# The simplest action to take: ban only\naction_ = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n\n# ban & send an e-mail with whois report to the destemail.\naction_mw = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n              %(mta)s-whois[name=%(__name__)s, dest=\"%(destemail)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# ban & send an e-mail with whois report and relevant log lines\n# to the destemail.\naction_mwl = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n               %(mta)s-whois-lines[name=%(__name__)s, dest=\"%(destemail)s\", logpath=%(logpath)s, chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# Choose default action.  To change, just override value of 'action' with the\n# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local\n# globally (section [DEFAULT]) or per specific section\naction = %(action_)s\n\n#\n# JAILS\n#\n\n# Next jails corresponds to the standard configuration in Fail2ban 0.6 which\n# was shipped in Debian. Enable any defined here jail by including\n#\n# [SECTION_NAME]\n# enabled = true\n\n#\n# in /etc/fail2ban/jail.local.\n#\n# Optionally you may override any other parameter (e.g. banaction,\n# action, port, logpath, etc) in that section within jail.local\n\n[ssh]\n\nenabled  = true\nport     = ssh\nfilter   = sshd\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[dropbear]\n\nenabled  = false\nport     = ssh\nfilter   = dropbear\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n# Generic filter for pam. Has to be used with action which bans all ports\n# such as iptables-allports, shorewall\n[pam-generic]\n\nenabled  = false\n# pam-generic filter can be customized to monitor specific subset of 'tty's\nfilter   = pam-generic\n# port actually must be irrelevant but lets leave it all for some possible uses\nport     = all\nbanaction = iptables-allports\nport     = anyport\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[xinetd-fail]\n\nenabled   = false\nfilter    = xinetd-fail\nport      = all\nbanaction = iptables-multiport-log\nlogpath   = /var/log/daemon.log\nmaxretry  = 2\n\n\n[ssh-ddos]\n\nenabled  = false\nport     = ssh\nfilter   = sshd-ddos\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n\n# Here we use blackhole routes for not requiring any additional kernel support\n# to store large volumes of banned IPs\n\n[ssh-route]\n\nenabled = false\nfilter = sshd\naction = route\nlogpath = /var/log/sshd.log\nmaxretry = 6\n\n# Here we use a combination of Netfilter/Iptables and IPsets\n# for storing large volumes of banned IPs\n#\n# IPset comes in two versions. See ipset -V for which one to use\n# requires the ipset package and kernel support.\n[ssh-iptables-ipset4]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto4\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n[ssh-iptables-ipset6]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto6\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n\n#\n# HTTP servers\n#\n\n[apache]\n\nenabled  = false\nport     = http,https\nfilter   = apache-auth\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n# default action is now multiport, so apache-multiport jail was left\n# for compatibility with previous (<0.7.6-2) releases\n[apache-multiport]\n\nenabled   = false\nport      = http,https\nfilter    = apache-auth\nlogpath   = /var/log/apache*/*error.log\nmaxretry  = 6\n\n[apache-noscript]\n\nenabled  = false\nport     = http,https\nfilter   = apache-noscript\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n[apache-overflows]\n\nenabled  = false\nport     = http,https\nfilter   = apache-overflows\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 2\n\n# Ban attackers that try to use PHP's URL-fopen() functionality\n# through GET/POST variables. - Experimental, with more than a year\n# of usage in production environments.\n\n[php-url-fopen]\n\nenabled = false\nport    = http,https\nfilter  = php-url-fopen\nlogpath = /var/www/*/logs/access_log\n\n# A simple PHP-fastcgi jail which works with lighttpd.\n# If you run a lighttpd server, then you probably will\n# find these kinds of messages in your error_log:\n#   ALERT \u00e2\u20ac\u201c tried to register forbidden variable \u00e2\u20ac\u02dcGLOBALS\u00e2\u20ac\u2122\n#   through GET variables (attacker '1.2.3.4', file '/var/www/default/htdocs/index.php')\n\n[lighttpd-fastcgi]\n\nenabled = false\nport    = http,https\nfilter  = lighttpd-fastcgi\nlogpath = /var/log/lighttpd/error.log\n\n# Same as above for mod_auth\n# It catches wrong authentifications\n\n[lighttpd-auth]\n\nenabled = false\nport    = http,https\nfilter  = suhosin\nlogpath = /var/log/lighttpd/error.log\n\n[nginx-http-auth]\n\nenabled = false\nfilter  = nginx-http-auth\nport    = http,https\nlogpath = /var/log/nginx/error.log\n\n# Monitor roundcube server\n\n[roundcube-auth]\n\nenabled  = false\nfilter   = roundcube-auth\nport     = http,https\nlogpath  = /var/log/roundcube/userlogins\n\n\n[sogo-auth]\n\nenabled  = false\nfilter   = sogo-auth\nport     = http, https\n# without proxy this would be:\n# port    = 20000\nlogpath  = /var/log/sogo/sogo.log\n\n\n#\n# FTP servers\n#\n\n[vsftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = vsftpd\nlogpath  = /var/log/vsftpd.log\n# or overwrite it in jails.local to be\n# logpath = /var/log/auth.log\n# if you want to rely on PAM failed login attempts\n# vsftpd's failregex should match both of those formats\nmaxretry = 6\n\n\n[proftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = proftpd\nlogpath  = /var/log/proftpd/proftpd.log\nmaxretry = 6\n\n\n[pure-ftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = pure-ftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n[wuftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = wuftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n#\n# Mail servers\n#\n\n[postfix]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = postfix\nlogpath  = /var/log/mail.log\n\n\n[couriersmtp]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = couriersmtp\nlogpath  = /var/log/mail.log\n\n\n#\n# Mail servers authenticators: might be used for smtp,ftp,imap servers, so\n# all relevant ports get banned\n#\n\n[courierauth]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = courierlogin\nlogpath  = /var/log/mail.log\n\n\n[sasl]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = postfix-sasl\n# You might consider monitoring /var/log/mail.warn instead if you are\n# running postfix since it would provide the same log lines at the\n# \"warn\" level but overall at the smaller filesize.\nlogpath  = /var/log/mail.log\n\n[dovecot]\n\nenabled = false\nport    = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter  = dovecot\nlogpath = /var/log/mail.log\n\n# To log wrong MySQL access attempts add to /etc/my.cnf:\n# log-error=/var/log/mysqld.log\n# log-warning = 2\n[mysqld-auth]\n\nenabled  = false\nfilter   = mysqld-auth\nport     = 3306\nlogpath  = /var/log/mysqld.log\n\n\n# DNS Servers\n\n\n# These jails block attacks against named (bind9). By default, logging is off\n# with bind9 installation. You will need something like this:\n#\n# logging {\n#     channel security_file {\n#         file \"/var/log/named/security.log\" versions 3 size 30m;\n#         severity dynamic;\n#         print-time yes;\n#     };\n#     category security {\n#         security_file;\n#     };\n# };\n#\n# in your named.conf to provide proper logging\n\n# !!! WARNING !!!\n#   Since UDP is connection-less protocol, spoofing of IP and imitation\n#   of illegal actions is way too simple.  Thus enabling of this filter\n#   might provide an easy way for implementing a DoS against a chosen\n#   victim. See\n#    http://nion.modprobe.de/blog/archives/690-fail2ban-+-dns-fail.html\n#   Please DO NOT USE this jail unless you know what you are doing.\n#[named-refused-udp]\n#\n#enabled  = false\n#port     = domain,953\n#protocol = udp\n#filter   = named-refused\n#logpath  = /var/log/named/security.log\n\n[named-refused-tcp]\n\nenabled  = false\nport     = domain,953\nprotocol = tcp\nfilter   = named-refused\nlogpath  = /var/log/named/security.log\n\n# Multiple jails, 1 per protocol, are necessary ATM:\n# see https://github.com/fail2ban/fail2ban/issues/37\n[asterisk-tcp]\n\nenabled  = false\nfilter   = asterisk\nport     = 5060,5061\nprotocol = tcp\nlogpath  = /var/log/asterisk/messages\n\n[asterisk-udp]\n\nenabled  = false\nfilter\t = asterisk\nport     = 5060,5061\nprotocol = udp\nlogpath  = /var/log/asterisk/messages\n\n\n# Jail for more extended banning of persistent abusers\n# !!! WARNING !!!\n#   Make sure that your loglevel specified in fail2ban.conf/.local\n#   is not at DEBUG level -- which might then cause fail2ban to fall into\n#   an infinite loop constantly feeding itself with non-informative lines\n[recidive]\n\nenabled  = false\nfilter   = recidive\nlogpath  = /var/log/fail2ban.log\naction   = iptables-allports[name=recidive]\n           sendmail-whois-lines[name=recidive, logpath=/var/log/fail2ban.log]\nbantime  = 604800  ; 1 week\nfindtime = 86400   ; 1 day\nmaxretry = 5\nEOF\n}\n", "num_lines": 766}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Custom Script for Linux\n#\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nesClusterName=$1\nelasticvm1ip=$2\nelasticvm2ip=$3\nelasticvm3ip=$4\n\necho $esClusterName    >> /tmp/vars.txt\necho $elasticvm1ip     >> /tmp/vars.txt\necho $elasticvm2ip     >> /tmp/vars.txt\necho $elasticvm3ip     >> /tmp/vars.txt\n\n{\n\n  # make sure the system does automatic update\n  sudo apt-get -y update\n  sudo apt-get -y install unattended-upgrades\n\n  # configure elastic search repository & install elastic search\n  wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -\n  echo \"deb https://artifacts.elastic.co/packages/5.x/apt stable main\" | sudo tee -a /etc/apt/sources.list.d/elastic-5.x.list\n  sudo apt-get -y update\n  sudo apt-get -y install elasticsearch=5.5.0\n\n  # install the required packages\n  sudo apt-get install -y openjdk-8-jre openjdk-8-jdk default-jre default-jdk\n\n  # Configure elasticsearch\n  cat <<EOF > /etc/elasticsearch/elasticsearch.yml\n# ======================== Elasticsearch Configuration =========================\n#\n# NOTE: Elasticsearch comes with reasonable defaults for most settings.\n#       Before you set out to tweak and tune the configuration, make sure you\n#       understand what are you trying to accomplish and the consequences.\n#\n# The primary way of configuring a node is via this file. This template lists\n# the most important settings you may want to configure for a production cluster.\n#\n# Please consult the documentation for further information on configuration options:\n# https://www.elastic.co/guide/en/elasticsearch/reference/index.html\n#\n# ---------------------------------- Cluster -----------------------------------\n#\n# Use a descriptive name for your cluster:\n#\ncluster.name: ${esClusterName}\n#\n# ------------------------------------ Node ------------------------------------\n#\n# Use a descriptive name for the node:\n#\nnode.name: \\${HOSTNAME}\n#\n# Add custom attributes to the node:\n#\n#node.attr.rack: r1\n#\n# ----------------------------------- Paths ------------------------------------\n#\n# Path to directory where to store the data (separate multiple locations by comma):\n#\n#path.data: /path/to/data\n#\n# Path to log files:\n#\n#path.logs: /path/to/logs\n#\n# ----------------------------------- Memory -----------------------------------\n#\n# Lock the memory on startup:\n#\n#bootstrap.memory_lock: true\n#\n# Make sure that the heap size is set to about half the memory available\n# on the system and that the owner of the process is allowed to use this\n# limit.\n#\n# Elasticsearch performs poorly when the system is swapping the memory.\n#\n# ---------------------------------- Network -----------------------------------\n#\n# Set the bind address to a specific IP (IPv4 or IPv6):\n#\nnetwork.host: [_eth0_, _local_]\n#\n# Set a custom port for HTTP:\n#\n#http.port: 9200\n#\n# For more information, consult the network module documentation.\n#\n# --------------------------------- Discovery ----------------------------------\n#\n# Pass an initial list of hosts to perform discovery when new node is started:\n# The default list of hosts is [\"127.0.0.1\", \"[::1]\"]\n#\ndiscovery.zen.ping.unicast.hosts: [\"$elasticvm1ip\", \"$elasticvm2ip\", \"$elasticvm3ip\"]\n#\n# Prevent the \"split brain\" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):\n#\ndiscovery.zen.minimum_master_nodes: 3\n#\n# For more information, consult the zen discovery module documentation.\n#\n# ---------------------------------- Gateway -----------------------------------\n#\n# Block initial recovery after a full cluster restart until N nodes are started:\n#\n#gateway.recover_after_nodes: 3\n#\n# For more information, consult the gateway module documentation.\n#\n# ---------------------------------- Various -----------------------------------\n#\n# Require explicit names when deleting indices:\n#\n#action.destructive_requires_name: true\nEOF\n\n  service elasticsearch restart\n\n}  > /tmp/setup.log\n", "num_lines": 144}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script built for Ubuntu Server 16.04 LTS\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of powershell script or runbook or Azure Resource Manager CRP template.\n\nAZUREVMOFFSET=4\n\nNODENAME=$(hostname)\nPEERNODEPREFIX=${1}\nPEERNODEIPPREFIX=${2}\nVOLUMENAME=${3}\nNODEINDEX=${4}\nNODECOUNT=${5}\n\necho $NODENAME          >> /tmp/vars.txt\necho $PEERNODEPREFIX    >> /tmp/vars.txt\necho $PEERNODEIPPREFIX  >> /tmp/vars.txt\necho $VOLUMENAME        >> /tmp/vars.txt\necho $NODEINDEX         >> /tmp/vars.txt\necho $NODECOUNT         >> /tmp/vars.txt\n\n\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=128\n\nRAIDDISK=\"/dev/md1\"\nRAIDPARTITION=\"/dev/md1p1\"\n\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\n# make sure the system does automatic update\nsudo apt-get -y update\nsudo apt-get -y install unattended-upgrades\n\n{\n        check_os() {\n            grep ubuntu /proc/version > /dev/null 2>&1\n            isubuntu=${?}\n        }\n\n        scan_for_new_disks() {\n            # Looks for unpartitioned disks\n            declare -a RET\n            DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n            for DEV in \"${DEVS[@]}\";\n            do\n                # Check each device if there is a \"1\" partition.  If not,\n                # \"assume\" it is not partitioned.\n                if [ ! -b ${DEV}1 ];\n                then\n                    RET+=\"${DEV} \"\n                fi\n            done\n            echo \"${RET}\"\n        }\n\n        get_disk_count() {\n            DISKCOUNT=0\n            for DISK in \"${DISKS[@]}\";\n            do\n                DISKCOUNT+=1\n            done;\n            echo \"$DISKCOUNT\"\n        }\n\n        create_raid0_ubuntu() {\n            dpkg -s mdadm\n            if [ ${?} -eq 1 ];\n            then\n                echo \"installing mdadm\"\n                sudo apt-get -y -q install mdadm\n            fi\n            echo \"Creating raid0\"\n            udevadm control --stop-exec-queue\n            echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n            udevadm control --start-exec-queue\n            mdadm --detail --verbose --scan > /etc/mdadm.conf\n        }\n\n\n        do_partition() {\n        # This function creates one (1) primary partition on the\n        # disk, using all available space\n            DISK=${1}\n            echo \"Partitioning disk $DISK\"\n            echo -ne \"n\\np\\n1\\n\\n\\nw\\n\" | fdisk \"${DISK}\"\n        #> /dev/null 2>&1\n\n        #\n        # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n        # from fdisk and not from echo\n        if [ ${PIPESTATUS[1]} -ne 0 ];\n        then\n            echo \"An error occurred partitioning ${DISK}\" >&2\n            echo \"I cannot continue\" >&2\n            exit 2\n        fi\n        }\n\n        add_to_fstab() {\n            UUID=${1}\n            MOUNTPOINT=${2}\n            grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n            if [ ${?} -eq 0 ];\n            then\n                echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n            else\n                LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n                echo -e \"${LINE}\" >> /etc/fstab\n            fi\n        }\n\n        configure_disks() {\n            ls \"${MOUNTPOINT}\"\n            if [ ${?} -eq 0 ]\n            then\n                return\n            fi\n            DISKS=($(scan_for_new_disks))\n            echo \"Disks are ${DISKS[@]}\"\n            declare -i DISKCOUNT\n            DISKCOUNT=$(get_disk_count)\n            echo \"Disk count is $DISKCOUNT\"\n            if [ $DISKCOUNT -gt 1 ];\n            then\n                create_raid0_ubuntu\n                do_partition ${RAIDDISK}\n                PARTITION=\"${RAIDPARTITION}\"\n            else\n                DISK=\"${DISKS[0]}\"\n                do_partition ${DISK}\n                PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n            fi\n\n            echo \"Creating filesystem on ${PARTITION}.\"\n            mkfs -t ext4 ${PARTITION}\n            mkdir \"${MOUNTPOINT}\"\n            read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n            add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n            echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n            mount \"${MOUNTPOINT}\"\n        }\n\n        open_ports() {\n            index=0\n            while [ $index -lt $NODECOUNT ]; do\n\t\t\t    echo \"Node ${index}\"\n\t\t\t\tthisNode=\"${PEERNODEIPPREFIX}.$(($index+$AZUREVMOFFSET))\"\n\t\t\t    echo \"Node ${thisNode}\"\n\n                if [ $index -ne $NODEINDEX ]; then\n\t\t\t\t    echo \"Node ${thisNode} is a peer\"\n                    iptables -I INPUT -p all -s \"${thisNode}\" -j ACCEPT\n                    echo \"${thisNode}    ${thisNode}\" >> /etc/hosts\n                else\n\t\t\t\t    echo \"Node ${thisNode} is me\"\n                    echo \"127.0.0.1    ${thisNode}\" >> /etc/hosts\n                fi\n                let index++\n            done\n            iptables-save\n        }\n\n        disable_apparmor_ubuntu() {\n            /etc/init.d/apparmor teardown\n            update-rc.d -f apparmor remove\n        }\n\n        configure_network() {\n            open_ports\n            disable_apparmor_ubuntu\n        }\n\n        install_glusterfs_ubuntu() {\n            dpkg -l | grep glusterfs\n            if [ ${?} -eq 0 ];\n            then\n                return\n            fi\n\n            if [ ! -e /etc/apt/sources.list.d/gluster* ];\n            then\n                echo \"adding gluster ppa\"\n                apt-get  -y install python-software-properties\n                apt-add-repository -y ppa:gluster/glusterfs-3.8\n                apt-get -y update\n            fi\n\n            echo \"installing gluster\"\n            apt-get -y install glusterfs-server\n\n            return\n        }\n\n        configure_gluster() {\n            echo \"gluster step1\"\n\n            if [ $isubuntu -eq 0 ];\n            then\n                /etc/init.d/glusterfs-server status\n                if [ ${?} -ne 0 ];\n                then\n                    install_glusterfs_ubuntu\n                fi\n                /etc/init.d/glusterfs-server start\n            fi\n\n\t\t\techo \"gluster step2\"\n            GLUSTERDIR=\"${MOUNTPOINT}/brick\"\n            ls \"${GLUSTERDIR}\"\n\n            if [ ${?} -ne 0 ];\n            then\n                mkdir \"${GLUSTERDIR}\"\n            fi\n\n            if [ $NODEINDEX -lt $(($NODECOUNT-1)) ];\n            then\n                return\n            fi\n\n            echo \"gluster step3\"\n            allNodes=\"${NODENAME}:${GLUSTERDIR}\"\n\t\t\techo $allNodes\n            retry=10\n            failed=1\n\n            while [ $retry -gt 0 ] && [ $failed -gt 0 ]; do\n                failed=0\n                index=0\n                echo retrying $retry\n                while [ $index -lt $(($NODECOUNT-1)) ]; do\n\t\t\t\t\tglustervm=${PEERNODEPREFIX}${index}\n\t\t\t\t\techo $glustervm\n\n                    ping -c 3 $glustervm\n                    gluster peer probe $glustervm\n                    if [ ${?} -ne 0 ];\n                    then\n                        failed=1\n                        echo \"gluster peer probe $glustervm failed\"\n                    fi\n\n                    gluster peer status\n                    gluster peer status | grep $glustervm\n\n\t\t\t\t\tif [ ${?} -ne 0 ];\n                    then\n                        failed=1\n                        echo \"gluster peer status $glustervm failed\"\n                    fi\n\n\t\t\t\t\tif [ $retry -eq 10 ]; then\n                        allNodes=\"${allNodes} $glustervm:${GLUSTERDIR}\"\n                    fi\n                    let index++\n                done\n                sleep 30\n                let retry--\n            done\n\n            echo \"gluster step4\"\n\t\t\techo $allnodes\n            sleep 60\n            gluster volume create ${VOLUMENAME} rep 2 transport tcp ${allNodes}\n            gluster volume info\n            gluster volume start ${VOLUMENAME}\n            echo \"gluster complete\"\n        }\n\n        # \"main routine\"\n        check_os\n        configure_network\n        configure_disks\n        configure_gluster\n\n}  > /tmp/gluster-setup.log\n", "num_lines": 284}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#parameters\n{\n    maharaVersion=${1}\n    glusterNode=${2}\n    glusterVolume=${3}\n    siteFQDN=${4}\n    httpsTermination=${5}\n    dbIP=${6}\n    maharadbname=${7}\n    maharadbuser=${8}\n    maharadbpass=${9}\n    adminpass=${10}\n    dbadminlogin=${11}\n    dbadminpass=${12}\n    wabsacctname=${13}\n    wabsacctkey=${14}\n    azuremaharadbuser=${15}\n    elasticVm1IP=${16}\n    dbServerType=${17}\n    fileServerType=${18}\n    thumbprintSslCert=${19}\n    thumbprintCaCert=${20}\n    searchType=${21}\n    azFQDN=${22}\n\n    echo $maharaVersion        >> /tmp/vars.txt\n    echo $glusterNode          >> /tmp/vars.txt\n    echo $glusterVolume        >> /tmp/vars.txt\n    echo $siteFQDN             >> /tmp/vars.txt\n    echo $httpsTermination     >> /tmp/vars.txt\n    echo $dbIP                 >> /tmp/vars.txt\n    echo $maharadbname         >> /tmp/vars.txt\n    echo $maharadbuser         >> /tmp/vars.txt\n    echo $maharadbpass         >> /tmp/vars.txt\n    echo $adminpass            >> /tmp/vars.txt\n    echo $dbadminlogin         >> /tmp/vars.txt\n    echo $dbadminpass          >> /tmp/vars.txt\n    echo $wabsacctname         >> /tmp/vars.txt\n    echo $wabsacctkey          >> /tmp/vars.txt\n    echo $azuremaharadbuser    >> /tmp/vars.txt\n    echo $elasticVm1IP         >> /tmp/vars.txt\n    echo $installElasticSearchSwitch  >> /tmp/vars.txt\n    echo $dbServerType                >> /tmp/vars.txt\n    echo $fileServerType              >> /tmp/vars.txt\n    echo $thumbprintSslCert >> /tmp/vars.txt\n    echo $thumbprintCaCert >> /tmp/vars.txt\n    echo $searchType >> /tmp/vars.txt\n    echo $azFQDN >> /tmp/vars.txt\n\n\n    . ./helper_functions.sh\n    check_fileServerType_param $fileServerType\n    configure_site_url ${siteFQDN} ${azFQDN}\n\n    if [ \"$dbServerType\" = \"mysql\" ]; then\n      mysqlIP=$dbIP\n      mysqladminlogin=$dbadminlogin\n      mysqladminpass=$dbadminpass\n\n    elif [ \"$dbServerType\" = \"postgres\" ]; then\n      postgresIP=$dbIP\n      pgadminlogin=$dbadminlogin\n      pgadminpass=$dbadminpass\n    else\n      echo \"Invalid dbServerType ($dbServerType) given. Only 'mysql' or 'postgres' is allowed. Exiting\"\n      exit 1\n    fi\n\n    # make sure system does automatic updates and fail2ban\n    sudo apt-get -y update\n    sudo apt-get -y install unattended-upgrades fail2ban pwgen\n    config_fail2ban\n\n    # create gluster mount point\n    mkdir -p /mahara\n\n    export DEBIAN_FRONTEND=noninteractive\n\n    if [ $fileServerType = \"gluster\" ]; then\n        # configure gluster repository & install gluster client\n        sudo add-apt-repository ppa:gluster/glusterfs-3.8 -y                 >> /tmp/apt1.log\n    elif [ $fileServerType = \"nfs\" ]; then\n        # configure NFS server and export\n        create_filesystem_with_raid /mahara /dev/md1 /dev/md1p1\n        configure_nfs_server_and_export /mahara\n    fi\n\n    sudo apt-get -y update                                                   >> /tmp/apt2.log\n    sudo apt-get -y --force-yes install rsyslog git                          >> /tmp/apt3.log\n\n    if [ $fileServerType = \"gluster\" ]; then\n        sudo apt-get -y --force-yes install glusterfs-client                 >> /tmp/apt3.log\n    else # \"azurefiles\"\n        sudo apt-get -y --force-yes install cifs-utils                       >> /tmp/apt3.log\n    fi\n\n    if [ $dbServerType = \"mysql\" ]; then\n        sudo apt-get -y --force-yes install mysql-client >> /tmp/apt3.log\n    else\n        sudo apt-get -y --force-yes install postgresql-client >> /tmp/apt3.log\n    fi\n\n    # install azure cli & setup container\n    echo \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main\" | \\\n        sudo tee /etc/apt/sources.list.d/azure-cli.list\n\n    sudo apt-key adv --keyserver packages.microsoft.com --recv-keys 52E16F86FEE04B979B07E28DB02C46DF417A0893 >> /tmp/apt4.log\n    sudo apt-get -y install apt-transport-https >> /tmp/apt4.log\n    sudo apt-get -y update > /dev/null\n    sudo apt-get -y install azure-cli >> /tmp/apt4.log\n\n    if [ $fileServerType = \"gluster\" ]; then\n        # mount gluster files system\n        echo -e '\\n\\rInstalling GlusterFS on '$glusterNode':/'$glusterVolume '/mahara\\n\\r'\n        sudo mount -t glusterfs $glusterNode:/$glusterVolume /mahara\n    fi\n\n    # install pre-requisites\n    sudo apt-get install -y --fix-missing python-software-properties unzip\n\n    # install the entire stack\n    sudo apt-get -y  --force-yes install nginx php-fpm varnish >> /tmp/apt5a.log\n    sudo apt-get -y  --force-yes install php php-cli php-curl php-zip >> /tmp/apt5b.log\n\n    # Mahara requirements\n    sudo apt-get -y update > /dev/null\n    sudo apt-get install -y --force-yes graphviz aspell php-common php-soap php-json > /tmp/apt6.log\n    sudo apt-get install -y --force-yes php-mbstring php-bcmath php-gd php-mysql php-xmlrpc php-intl php-xml php-bz2 >> /tmp/apt6.log\n    sudo apt-get install -y --force-yes npm nodejs-legacy\n    if [ $dbServerType = \"mysql\" ]; then\n        sudo apt-get install -y --force-yes php-mysql\n    else\n        sudo apt-get install -y --force-yes php-pgsql\n    fi\n\n\n\n\n    # Set up initial mahara dirs\n    mkdir -p /mahara/html/mahara\n    mkdir -p /mahara/certs\n    mkdir -p /mahara/maharadata\n    chown -R www-data.www-data /mahara\n\n    # install Mahara\n    echo '#!/bin/bash\n    cd /tmp\n\n    # downloading mahara\n    /usr/bin/curl -k --max-redirs 10 https://github.com/MaharaProject/mahara/archive/'$maharaVersion'.zip -L -o mahara.zip\n    /usr/bin/unzip -q mahara.zip\n    # setup theme files\n    cd mahara-'$maharaVersion'\n    /bin/mv -v * /mahara/html/mahara\n    ' > /tmp/setup-mahara.sh\n\n    chmod 755 /tmp/setup-mahara.sh\n    sudo -u www-data /tmp/setup-mahara.sh  >> /tmp/setupmahara.log\n    cd  /mahara/html/mahara\n    npm install -g gulp\n    make css\n\n\n    # create cron entry\n    # It is scheduled for once per day. It can be changed as needed.\n    echo '* * * * * www-data /usr/bin/php /mahara/html/mahara/htdocs/lib/cron.php 2>&1 | /usr/bin/logger -plocal2.notice -t mahara' > /etc/cron.d/mahara-cron\n\n\n    # Build nginx config\n    cat <<EOF > /etc/nginx/nginx.conf\nuser www-data;\nworker_processes 2;\npid /run/nginx.pid;\n\nevents {\n\tworker_connections 768;\n}\n\nhttp {\n\n  sendfile on;\n  tcp_nopush on;\n  tcp_nodelay on;\n  keepalive_timeout 65;\n  types_hash_max_size 2048;\n  client_max_body_size 0;\n  proxy_max_temp_file_size 0;\n  server_names_hash_bucket_size  128;\n  fastcgi_buffers 16 16k;\n  fastcgi_buffer_size 32k;\n  proxy_buffering off;\n  include /etc/nginx/mime.types;\n  default_type application/octet-stream;\n\n  access_log /var/log/nginx/access.log;\n  error_log /var/log/nginx/error.log;\n\n  set_real_ip_from   127.0.0.1;\n  real_ip_header      X-Forwarded-For;\n  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE\n  ssl_prefer_server_ciphers on;\n\n  gzip on;\n  gzip_disable \"msie6\";\n  gzip_vary on;\n  gzip_proxied any;\n  gzip_comp_level 6;\n  gzip_buffers 16 8k;\n  gzip_http_version 1.1;\n  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;\n\n  map \\$http_x_forwarded_proto \\$fastcgi_https {\n    default \\$https;\n    http '';\n    https on;\n  }\n\n  log_format mahara_combined '\\$remote_addr - \\$upstream_http_x_maharauser [\\$time_local] '\n                             '\"\\$request\" \\$status \\$body_bytes_sent '\n                             '\"\\$http_referer\" \"\\$http_user_agent\"';\n\n\n  include /etc/nginx/conf.d/*.conf;\n  include /etc/nginx/sites-enabled/*;\n}\nEOF\n\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 81 default;\n        server_name ${siteFQDN};\n        root /mahara/html/mahara/htdocs;\n\tindex index.php index.html index.htm;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=mahara;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=mahara mahara_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n\n        # Redirect to https\n        if (\\$http_x_forwarded_proto != https) {\n                return 301 https://\\$server_name\\$request_uri;\n        }\n        rewrite ^/(.*\\.php)(/)(.*)$ /\\$1?file=/\\$3 last;\n\n\n        # Filter out php-fpm status page\n        location ~ ^/server-status {\n            return 404;\n        }\n\n\tlocation / {\n\t\ttry_files \\$uri \\$uri/index.php?\\$query_string;\n\t}\n\n        location ~ [^/]\\.php(/|$) {\n          fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n          if (!-f \\$document_root\\$fastcgi_script_name) {\n                  return 404;\n          }\n\n          fastcgi_buffers 16 16k;\n          fastcgi_buffer_size 32k;\n          fastcgi_param   SCRIPT_FILENAME \\$document_root\\$fastcgi_script_name;\n          fastcgi_pass unix:/run/php/php7.0-fpm.sock;\n          fastcgi_read_timeout 3600;\n          fastcgi_index index.php;\n          include fastcgi_params;\n        }\n}\n\nserver {\n        listen 443 ssl;\n        root /mahara/html/mahara/htdocs;\n\tindex index.php index.html index.htm;\n\n        ssl on;\n        ssl_certificate /mahara/certs/nginx.crt;\n        ssl_certificate_key /mahara/certs/nginx.key;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=mahara;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=mahara mahara_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n        location / {\n          proxy_set_header Host \\$host;\n          proxy_set_header HTTP_REFERER \\$http_referer;\n          proxy_set_header X-Forwarded-Host \\$host;\n          proxy_set_header X-Forwarded-Server \\$host;\n          proxy_set_header X-Forwarded-Proto https;\n          proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n          proxy_pass http://localhost:80;\n        }\n}\nEOF\n\n    echo -e \"Generating SSL self-signed certificate\"\n    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /mahara/certs/nginx.key -out /mahara/certs/nginx.crt -subj \"/C=BR/ST=SP/L=SaoPaulo/O=IT/CN=$siteFQDN\"\n\n   # php config\n   PhpIni=/etc/php/7.0/fpm/php.ini\n   sed -i \"s/memory_limit.*/memory_limit = 512M/\" $PhpIni\n   sed -i \"s/max_execution_time.*/max_execution_time = 18000/\" $PhpIni\n   sed -i \"s/max_input_vars.*/max_input_vars = 100000/\" $PhpIni\n   sed -i \"s/max_input_time.*/max_input_time = 600/\" $PhpIni\n   sed -i \"s/upload_max_filesize.*/upload_max_filesize = 1024M/\" $PhpIni\n   sed -i \"s/post_max_size.*/post_max_size = 1056M/\" $PhpIni\n   sed -i \"s/;opcache.use_cwd.*/opcache.use_cwd = 1/\" $PhpIni\n   sed -i \"s/;opcache.validate_timestamps.*/opcache.validate_timestamps = 1/\" $PhpIni\n   sed -i \"s/;opcache.save_comments.*/opcache.save_comments = 1/\" $PhpIni\n   sed -i \"s/;opcache.enable_file_override.*/opcache.enable_file_override = 0/\" $PhpIni\n   sed -i \"s/;opcache.enable.*/opcache.enable = 1/\" $PhpIni\n   sed -i \"s/;opcache.memory_consumption.*/opcache.memory_consumption = 256/\" $PhpIni\n   sed -i \"s/;opcache.max_accelerated_files.*/opcache.max_accelerated_files = 8000/\" $PhpIni\n\n   # fpm config - overload this\n   cat <<EOF > /etc/php/7.0/fpm/pool.d/www.conf\n[www]\nuser = www-data\ngroup = www-data\nlisten = /run/php/php7.0-fpm.sock\nlisten.owner = www-data\nlisten.group = www-data\npm = dynamic\npm.max_children = 3000\npm.start_servers = 20\npm.min_spare_servers = 22\npm.max_spare_servers = 30\nEOF\n\n   # Remove the default site. Mahara is the only site we want\n   rm -f /etc/nginx/sites-enabled/default\n\n   # restart Nginx\n    sudo service nginx restart\n\n   # Configure varnish startup for 16.04\n   VARNISHSTART=\"ExecStart=\\/usr\\/sbin\\/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f \\/etc\\/varnish\\/mahara.vcl -S \\/etc\\/varnish\\/secret -s malloc,1024m -p thread_pool_min=200 -p thread_pool_max=4000 -p thread_pool_add_delay=2 -p timeout_linger=100 -p timeout_idle=30 -p send_timeout=1800 -p thread_pools=4 -p http_max_hdr=512 -p workspace_backend=512k\"\n   sed -i \"s/^ExecStart.*/${VARNISHSTART}/\" /lib/systemd/system/varnish.service\n\n   # Configure varnish VCL for mahara\n   cat <<EOF >> /etc/varnish/mahara.vcl\nvcl 4.0;\n\nimport std;\nimport directors;\nbackend default {\n    .host = \"localhost\";\n    .port = \"81\";\n    .first_byte_timeout = 3600s;\n    .connect_timeout = 600s;\n    .between_bytes_timeout = 600s;\n}\n\nsub vcl_recv {\n    # Varnish does not support SPDY or HTTP/2.0 untill we upgrade to Varnish 5.0\n    if (req.method == \"PRI\") {\n        return (synth(405));\n    }\n\n    if (req.restarts == 0) {\n      if (req.http.X-Forwarded-For) {\n        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + \", \" + client.ip;\n      } else {\n        set req.http.X-Forwarded-For = client.ip;\n      }\n    }\n\n    # Non-RFC2616 or CONNECT HTTP requests methods filtered. Pipe requests directly to backend\n    if (req.method != \"GET\" &&\n        req.method != \"HEAD\" &&\n        req.method != \"PUT\" &&\n        req.method != \"POST\" &&\n        req.method != \"TRACE\" &&\n        req.method != \"OPTIONS\" &&\n        req.method != \"DELETE\") {\n      return (pipe);\n    }\n\n    # Varnish don't mess with healthchecks\n    if (req.url ~ \"^/admin/tool/heartbeat\" || req.url ~ \"^/healthcheck.php\")\n    {\n        return (pass);\n    }\n\n    # Pipe requests to backup.php straight to backend - prevents problem with progress bar long polling 503 problem\n    # This is here because backup.php is POSTing to itself - Filter before !GET&&!HEAD\n    if (req.url ~ \"^/backup/backup.php\")\n    {\n        return (pipe);\n    }\n\n    # Varnish only deals with GET and HEAD by default. If request method is not GET or HEAD, pass request to backend\n    if (req.method != \"GET\" && req.method != \"HEAD\") {\n      return (pass);\n    }\n\n    ### Rules for Mahara sites ###\n    if (req.url ~ \"^/theme/\" ||\n        req.url ~ \"^/js/\" ||\n        req.url ~ \"^/lib/\" ||\n        req.url ~ \"^/libs/\"\n      ) {\n        return(hash);\n    }\n\n    # Perform lookup for selected assets that we know are static but Mahara still needs a Cookie\n    if(  req.url ~ \"^/theme/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/lib/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/pluginfile.php/[0-9]+/course/overviewfiles/.+\\.(?i)(png|jpg)$\"\n      )\n    {\n         # Set internal temporary header, based on which we will do things in vcl_backend_response\n         set req.http.X-Long-TTL = \"86400\";\n         return (hash);\n    }\n\n    # Serve requests to SCORM checknet.txt from varnish. Have to remove get parameters. Response body always contains \"1\"\n    if ( req.url ~ \"^/lib/yui/build/mahara-core-checknet/assets/checknet.txt\" )\n    {\n        set req.url = regsub(req.url, \"(.*)\\?.*\", \"\\1\");\n        unset req.http.Cookie; # Will go to hash anyway at the end of vcl_recv\n        set req.http.X-Long-TTL = \"86400\";\n        return(hash);\n    }\n\n    # Requests containing \"Cookie\" or \"Authorization\" headers will not be cached\n    if (req.http.Authorization || req.http.Cookie) {\n        return (pass);\n    }\n\n    # Almost everything in Mahara correctly serves Cache-Control headers, if\n    # needed, which varnish will honor, but there are some which don't. Rather\n    # than explicitly finding them all and listing them here we just fail safe\n    # and don't cache unknown urls that get this far.\n    return (pass);\n}\n\nsub vcl_backend_response {\n    # Happens after we have read the response headers from the backend.\n    #\n    # Here you clean the response headers, removing silly Set-Cookie headers\n    # and other mistakes your backend does.\n\n    # We know these assest are static, let's set TTL >0 and allow client caching\n    if ( beresp.http.Cache-Control && bereq.http.X-Long-TTL && beresp.ttl < std.duration(bereq.http.X-Long-TTL + \"s\", 1s) && !beresp.http.WWW-Authenticate )\n    { # If max-age < defined in X-Long-TTL header\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.X-Orig-Cache-Control = beresp.http.Cache-Control;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else if( !beresp.http.Cache-Control && bereq.http.X-Long-TTL && !beresp.http.WWW-Authenticate ) {\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else { # Don't touch headers if max-age > defined in X-Long-TTL header\n        unset bereq.http.X-Long-TTL;\n    }\n\n    # Here we set X-Trace header, prepending it to X-Trace header received from backend. Useful for troubleshooting\n    if(beresp.http.x-trace && !beresp.was_304) {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\")+\"->\"+beresp.http.X-Trace;\n    }\n    else {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\");\n    }\n\n    # Gzip JS, CSS is done at the ngnix level doing it here dosen't respect the no buffer requsets\n    # if (beresp.http.content-type ~ \"application/javascript.*\" || beresp.http.content-type ~ \"text\") {\n    #    set beresp.do_gzip = true;\n    #}\n}\n\nsub vcl_deliver {\n\n    # Revert back to original Cache-Control header before delivery to client\n    if (resp.http.X-Orig-Cache-Control)\n    {\n        set resp.http.Cache-Control = resp.http.X-Orig-Cache-Control;\n        unset resp.http.X-Orig-Cache-Control;\n    }\n\n    # Revert back to original Pragma header before delivery to client\n    if (resp.http.X-Orig-Pragma)\n    {\n        set resp.http.Pragma = resp.http.X-Orig-Pragma;\n        unset resp.http.X-Orig-Pragma;\n    }\n\n    # (Optional) X-Cache HTTP header will be added to responce, indicating whether object was retrieved from backend, or served from cache\n    if (obj.hits > 0) {\n        set resp.http.X-Cache = \"HIT\";\n    } else {\n        set resp.http.X-Cache = \"MISS\";\n    }\n\n    # Set X-AuthOK header when totara/varnsih authentication succeeded\n    if (req.http.X-AuthOK) {\n        set resp.http.X-AuthOK = req.http.X-AuthOK;\n    }\n\n    # If desired \"Via: 1.1 Varnish-v4\" response header can be removed from response\n    unset resp.http.Via;\n    unset resp.http.Server;\n\n    return(deliver);\n}\n\nsub vcl_backend_error {\n    # More comprehensive varnish error page. Display time, instance hostname, host header, url for easier troubleshooting.\n    set beresp.http.Content-Type = \"text/html; charset=utf-8\";\n    set beresp.http.Retry-After = \"5\";\n    synthetic( {\"\n  <!DOCTYPE html>\n  <html>\n    <head>\n      <title>\"} + beresp.status + \" \" + beresp.reason + {\"</title>\n    </head>\n    <body>\n      <h1>Error \"} + beresp.status + \" \" + beresp.reason + {\"</h1>\n      <p>\"} + beresp.reason + {\"</p>\n      <h3>Guru Meditation:</h3>\n      <p>Time: \"} + now + {\"</p>\n      <p>Node: \"} + server.hostname + {\"</p>\n      <p>Host: \"} + bereq.http.host + {\"</p>\n      <p>URL: \"} + bereq.url + {\"</p>\n      <p>XID: \"} + bereq.xid + {\"</p>\n      <hr>\n      <p>Varnish cache server\n    </body>\n  </html>\n  \"} );\n   return (deliver);\n}\n\nsub vcl_synth {\n\n    #Redirect using '301 - Permanent Redirect', permanent redirect\n    if (resp.status == 851) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 301;\n        return (deliver);\n    }\n\n    #Redirect using '302 - Found', temporary redirect\n    if (resp.status == 852) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 302;\n        return (deliver);\n    }\n\n    #Redirect using '307 - Temporary Redirect', !GET&&!HEAD requests, dont change method on redirected requests\n    if (resp.status == 857) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 307;\n        return (deliver);\n    }\n\n    #Respond with 403 - Forbidden\n    if (resp.status == 863) {\n        set resp.http.X-Varnish-Error = true;\n        set resp.status = 403;\n        return (deliver);\n    }\n}\nEOF\n\n    # Restart Varnish\n    systemctl daemon-reload\n    service varnish restart\n\n    if [ $dbServerType = \"mysql\" ]; then\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \"CREATE DATABASE ${maharadbname} CHARACTER SET utf8;\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \"GRANT ALL ON ${maharadbname}.* TO ${maharadbuser} IDENTIFIED BY '${maharadbpass}';\"\n\n        echo \"mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \\\"CREATE DATABASE ${maharadbname};\\\"\" >> /tmp/debug\n        echo \"mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \\\"GRANT ALL ON ${maharadbname}.* TO ${maharadbuser} IDENTIFIED BY '${maharadbpass}';\\\"\" >> /tmp/debug\n    else\n        # Create postgres db\n        echo \"${postgresIP}:5432:postgres:${pgadminlogin}:${pgadminpass}\" > /root/.pgpass\n        chmod 600 /root/.pgpass\n        psql -h $postgresIP -U $pgadminlogin -c \"CREATE DATABASE ${maharadbname};\" postgres\n        psql -h $postgresIP -U $pgadminlogin -c \"CREATE USER ${maharadbuser} WITH PASSWORD '${maharadbpass}';\" postgres\n        psql -h $postgresIP -U $pgadminlogin -c \"GRANT ALL ON DATABASE ${maharadbname} TO ${maharadbuser};\" postgres\n        # Need to preserve pg auth file for updating database later, if elasticsearch option was set.\n        if [ $searchType = \"none\" ]; then\n           rm -f /root/.pgpass\n        fi\n    fi\n\n    # Master config for syslog\n    mkdir /var/log/sitelogs\n    chown syslog.adm /var/log/sitelogs\n    cat <<EOF >> /etc/rsyslog.conf\n\\$ModLoad imudp\n\\$UDPServerRun 514\nEOF\n    cat <<EOF >> /etc/rsyslog.d/40-sitelogs.conf\nlocal1.*   /var/log/sitelogs/mahara/access.log\nlocal1.err   /var/log/sitelogs/mahara/error.log\nlocal2.*   /var/log/sitelogs/mahara/cron.log\nEOF\n    service rsyslog restart\n\n# Fire off mahara setup\nPWGEN=`which pwgen`\nSALT=`${PWGEN} 32 1`\nURLSECRET=`${PWGEN} 8 1`\n\n    cat <<EOF >> /mahara/html/mahara/htdocs/config.php\n<?php\n\\$cfg = new stdClass();\n\\$cfg->dbtype   = '$dbServerType';\n\\$cfg->dbhost   = '$dbIP';\n\\$cfg->dbport   = null;\n\\$cfg->dbname   = '$maharadbname';\n\\$cfg->dbuser   = '$azuremaharadbuser';\n\\$cfg->dbpass   = '$maharadbpass';\n\\$cfg->dataroot = '/mahara/maharadata';\n\\$cfg->wwwroot  = 'https://$siteFQDN';\n\\$cfg->passwordsaltmain = '$SALT';\n\\$cfg->productionmode = true;\n\\$cfg->sslproxy = true;\n\\$cfg->sendemail = true;\n\\$cfg->urlsecret = '$URLSECRET';\n\\$cfg->directorypermissions = 0750;\n\nEOF\n\ncd /tmp; sudo -u www-data /usr/bin/php /mahara/html/mahara/htdocs/admin/cli/install.php --adminpassword=\"$adminpass\" --adminemail=admin@\"$siteFQDN\" --sitename='Mahara Portfolio' || true\n\nif [ $searchType = \"elastic\" ]; then\n   echo \"\\$cfg->plugin_search_elasticsearch_indexname = 'mahara';\" >> /mahara/html/mahara/htdocs/config.php\n   echo \"\\$cfg->plugin_search_elasticsearch_host = '$elasticVm1IP';\" >> /mahara/html/mahara/htdocs/config.php\n\n   if [ $dbServerType = \"mysql\" ]; then\n       mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass}  ${maharadbname} -e \"update config set value = 'elasticsearch' where field = 'searchplugin';\"\n\n   else\n       psql -h $postgresIP -U $pgadminlogin -d ${maharadbname} -c \"update config set value = 'elasticsearch' where field = 'searchplugin';\" postgres\n      rm -f /root/.pgpass\n   fi\nfi\n\n    echo -e \"\\n\\rDone! Installation completed!\\n\\r\"\n\n   # Set up cronned sql dump\n   cat <<EOF > /etc/cron.d/sql-backup\n   22 02 * * * root /usr/bin/mysqldump -h $dbIP -u ${azuremaharadbuser} -p'${maharadbpass}' --databases ${maharadbname} | gzip > /mahara/db-backup.sql.gz\nEOF\n\n   # Turning off services we don't need the jumpbox running\n   service nginx stop\n   service php7.0-fpm stop\n   service varnish stop\n   service varnishncsa stop\n   service varnishlog stop\n\n   if [ $fileServerType = \"gluster\" -o $fileServerType = \"nfs\" ]; then\n      # make sure Mahara can read its code directory but not write\n      sudo chown -R root.root /mahara/html/mahara\n      sudo find /mahara/html/mahara -type f -exec chmod 644 '{}' \\;\n      sudo find /mahara/html/mahara -type d -exec chmod 755 '{}' \\;\n   fi\n\n   if [ $fileServerType = \"azurefiles\" ]; then\n      # Delayed copy of mahara installation to the Azure Files share\n\n      # First rename mahara directory to something else\n      mv /mahara /mahara_old_delete_me\n      # Then create the mahara share\n      echo -e '\\n\\rCreating an Azure Files share for mahara'\n      create_azure_files_mahara_share $wabsacctname $wabsacctkey /tmp/wabs.log\n      # Set up and mount Azure Files share. Must be done after nginx is installed because of www-data user/group\n      echo -e '\\n\\rSetting up and mounting Azure Files share on //'$wabsacctname'.file.core.windows.net/mahara on /mahara\\n\\r'\n      setup_and_mount_azure_files_mahara_share $wabsacctname $wabsacctkey\n      # Move the local installation over to the Azure Files\n      echo -e '\\n\\rMoving locally installed mahara over to Azure Files'\n      cp -a /mahara_old_delete_me/* /mahara || true # Ignore case sensitive directory copy failure\n      # rm -rf /mahara_old_delete_me || true # Keep the files just in case\n   fi\n\n   create_last_modified_time_update_script\n   run_once_last_modified_time_update_script\n\n}  > /tmp/install.log\n", "num_lines": 732}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Custom Script for Linux for Mahara/Azure\n\n#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nglusterNode=${1}\nglusterVolume=${2}\nsiteFQDN=${3}\nhttpsTermination=${4}\nsyslogserver=${5}\nwebServerType=${6}\nfileServerType=${7}\nstorageAccountName=${8}\nstorageAccountKey=${9}\nnfsVmName=${10}\nhtmlLocalCopySwitch=${11}\nazFQDN=${12}\n\necho $glusterNode    >> /tmp/vars.txt\necho $glusterVolume  >> /tmp/vars.txt\necho $siteFQDN >> /tmp/vars.txt\necho $httpsTermination >> /tmp/vars.txt\necho $syslogserver >> /tmp/vars.txt\necho $webServerType >> /tmp/vars.txt\necho $fileServerType >> /tmp/vars.txt\necho $storageAccountName >> /tmp/vars.txt\necho $storageAccountKey >> /tmp/vars.txt\necho $nfsVmName >> /tmp/vars.txt\necho $htmlLocalCopySwitch >> /tmp/vars.txt\necho $azFQDN >> /tmp/vars.txt\n\n. ./helper_functions.sh\n\nconfigure_site_url ${siteFQDN} ${azFQDN}\n\ncheck_fileServerType_param $fileServerType\n\n{\n  export DEBIAN_FRONTEND=noninteractive\n\n  sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 4F4EA0AAE5267A6C\n\n  sudo apt clean\n  sudo add-apt-repository universe\n  sudo add-apt-repository ppa:ondrej/php\n  sudo apt-get install -y php5.6\n\n  # make sure the system does automatic update\n  sudo apt-get update\n  sudo apt-get -y install unattended-upgrades\n\n  # install pre-requisites\n  sudo apt-get -y install software-properties-common unzip rsyslog postgresql-client mysql-client git\n\n  if [ $fileServerType = \"gluster\" ]; then\n    #configure gluster repository & install gluster client\n    sudo add-apt-repository ppa:gluster/glusterfs-3.8 -y\n    sudo apt-get update\n    sudo apt-get -y install glusterfs-client\n  elif [ \"$fileServerType\" = \"azurefiles\" ]; then\n    sudo apt-get -y install cifs-utils\n  fi\n\n  # install the base stack\n  sudo apt-get -y install varnish php5.6-cli php5.6-curl php5.6-zip php5.6-mbstring php5.6-dev php5.6-mcrypt\n\n  if [ \"$webServerType\" = \"nginx\" -o \"$httpsTermination\" = \"VMSS\" ]; then\n    sudo apt-get -y install nginx\n  fi\n\n  if [ \"$webServerType\" = \"apache\" ]; then\n    # install apache pacakges\n    sudo apt-get -y install apache2 libapache2-mod-php\n  else\n    # for nginx-only option\n    sudo apt-get -y install php5.6-fpm\n  fi\n\n  # Mahara requirements\n  sudo apt-get install -y graphviz aspell php5.6-soap php5.6-json php5.6-bcmath php5.6-gd php5.6-pgsql php5.6-mysql php5.6-xmlrpc php5.6-intl php5.6-xml php5.6-bz2\n\n  if [ $fileServerType = \"gluster\" ]; then\n    # Mount gluster fs for /mahara\n    sudo mkdir -p /mahara\n    sudo chown www-data /mahara\n    sudo chmod 770 /mahara\n    sudo echo -e 'mount -t glusterfs '$glusterNode':/'$glusterVolume' /mahara'\n    sudo mount -t glusterfs $glusterNode:/$glusterVolume /mahara\n    sudo echo -e $glusterNode':/'$glusterVolume'   /mahara         glusterfs       defaults,_netdev,log-level=WARNING,log-file=/var/log/gluster.log 0 0' >> /etc/fstab\n    sudo mount -a\n  elif [ $fileServerType = \"nfs\" ]; then\n    configure_nfs_client_and_mount $nfsVmName /mahara /mahara\n  else # \"azurefiles\"\n    setup_and_mount_azure_files_mahara_share $storageAccountName $storageAccountKey\n  fi\n\n  # Configure syslog to forward\n  cat <<EOF >> /etc/rsyslog.conf\n\\$ModLoad imudp\n\\$UDPServerRun 514\nEOF\n  cat <<EOF >> /etc/rsyslog.d/40-remote.conf\nlocal1.*   @${syslogserver}:514\nlocal2.*   @${syslogserver}:514\nEOF\n  service syslog restart\n\n  if [ \"$webServerType\" = \"nginx\" -o \"$httpsTermination\" = \"VMSS\" ]; then\n    # Build nginx config\n    cat <<EOF > /etc/nginx/nginx.conf\nuser www-data;\nworker_processes 2;\npid /run/nginx.pid;\n\nevents {\n\tworker_connections 2048;\n}\n\nhttp {\n\n  sendfile on;\n  tcp_nopush on;\n  tcp_nodelay on;\n  keepalive_timeout 65;\n  types_hash_max_size 2048;\n  client_max_body_size 0;\n  proxy_max_temp_file_size 0;\n  server_names_hash_bucket_size  128;\n  fastcgi_buffers 16 16k;\n  fastcgi_buffer_size 32k;\n  proxy_buffering off;\n  include /etc/nginx/mime.types;\n  default_type application/octet-stream;\n\n  access_log /var/log/nginx/access.log;\n  error_log /var/log/nginx/error.log;\n\n  set_real_ip_from   127.0.0.1;\n  real_ip_header      X-Forwarded-For;\n  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE\n  ssl_prefer_server_ciphers on;\n\n  gzip on;\n  gzip_disable \"msie6\";\n  gzip_vary on;\n  gzip_proxied any;\n  gzip_comp_level 6;\n  gzip_buffers 16 8k;\n  gzip_http_version 1.1;\n  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;\nEOF\n    if [ \"$httpsTermination\" != \"None\" ]; then\n      cat <<EOF >> /etc/nginx/nginx.conf\n  map \\$http_x_forwarded_proto \\$fastcgi_https {\n    default \\$https;\n    http '';\n    https on;\n  }\nEOF\n    fi\n\n    cat <<EOF >> /etc/nginx/nginx.conf\n  log_format mahara_combined '\\$remote_addr - \\$upstream_http_x_maharauser [\\$time_local] '\n                             '\"\\$request\" \\$status \\$body_bytes_sent '\n                             '\"\\$http_referer\" \"\\$http_user_agent\"';\n\n\n  include /etc/nginx/conf.d/*.conf;\n  include /etc/nginx/sites-enabled/*;\n}\nEOF\n  fi # if [ \"$webServerType\" = \"nginx\" -o \"$httpsTermination\" = \"VMSS\" ];\n\n  # Set up html dir local copy if specified\n  htmlRootDir=\"/mahara/html/mahara/htdocs\"\n  if [ \"$htmlLocalCopySwitch\" = \"True\" ]; then\n    mkdir -p /var/www/html\n    rsync -av --delete /mahara/html/mahara /var/www/html\n    htmlRootDir=\"/var/www/html/mahara/htdocs\"\n    setup_html_local_copy_cron_job\n  fi\n\n  if [ \"$httpsTermination\" = \"VMSS\" ]; then\n    # Configure nginx/https\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 443 ssl;\n        root ${htmlRootDir};\n\tindex index.php index.html index.htm;\n\n        ssl on;\n        ssl_certificate /mahara/certs/nginx.crt;\n        ssl_certificate_key /mahara/certs/nginx.key;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=mahara;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=mahara mahara_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n        location / {\n          proxy_set_header Host \\$host;\n          proxy_set_header HTTP_REFERER \\$http_referer;\n          proxy_set_header X-Forwarded-Host \\$host;\n          proxy_set_header X-Forwarded-Server \\$host;\n          proxy_set_header X-Forwarded-Proto https;\n          proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n          proxy_pass http://localhost:80;\n\n          proxy_connect_timeout       3600;\n          proxy_send_timeout          3600;\n          proxy_read_timeout          3600;\n          send_timeout                3600;\n        }\n}\nEOF\n  fi\n\n  if [ \"$webServerType\" = \"nginx\" ]; then\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 81 default;\n        server_name ${siteFQDN};\n        root ${htmlRootDir};\n\tindex index.php index.html index.htm;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=mahara;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=mahara mahara_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\nEOF\n    if [ \"$httpsTermination\" != \"None\" ]; then\n      cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\n        # Redirect to https\n        if (\\$http_x_forwarded_proto != https) {\n                return 301 https://\\$server_name\\$request_uri;\n        }\n        rewrite ^/(.*\\.php)(/)(.*)$ /\\$1?file=/\\$3 last;\nEOF\n    fi\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\n        # Filter out php-fpm status page\n        location ~ ^/server-status {\n            return 404;\n        }\n\n\tlocation / {\n\t\ttry_files \\$uri \\$uri/index.php?\\$query_string;\n\t}\n\n        location ~ [^/]\\.php(/|$) {\n          fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n          if (!-f \\$document_root\\$fastcgi_script_name) {\n                  return 404;\n          }\n\n          fastcgi_buffers 16 16k;\n          fastcgi_buffer_size 32k;\n          fastcgi_param   SCRIPT_FILENAME \\$document_root\\$fastcgi_script_name;\n          fastcgi_pass unix:/run/php/php7.0-fpm.sock;\n          fastcgi_read_timeout 3600;\n          fastcgi_index index.php;\n          include fastcgi_params;\n        }\n}\n\nEOF\n  fi # if [ \"$webServerType\" = \"nginx\" ];\n\n  if [ \"$webServerType\" = \"apache\" ]; then\n    # Configure Apache/php\n    sed -i \"s/Listen 80/Listen 81/\" /etc/apache2/ports.conf\n    a2enmod rewrite && a2enmod remoteip && a2enmod headers\n\n    cat <<EOF >> /etc/apache2/sites-enabled/${siteFQDN}.conf\n<VirtualHost *:81>\n\tServerName ${siteFQDN}\n\n\tServerAdmin webmaster@localhost\n\tDocumentRoot ${htmlRootDir}\n\n\t<Directory ${htmlRootDir}>\n\t\tOptions FollowSymLinks\n\t\tAllowOverride All\n\t\tRequire all granted\n\t</Directory>\nEOF\n    if [ \"$httpsTermination\" != \"None\" ]; then\n      cat <<EOF >> /etc/apache2/sites-enabled/${siteFQDN}.conf\n    # Redirect unencrypted direct connections to HTTPS\n    <IfModule mod_rewrite.c>\n      RewriteEngine on\n      RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]\n      RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]\n    </IFModule>\nEOF\n    fi\n    cat <<EOF >> /etc/apache2/sites-enabled/${siteFQDN}.conf\n    # Log X-Forwarded-For IP address instead of varnish (127.0.0.1)\n    SetEnvIf X-Forwarded-For \"^.*\\..*\\..*\\..*\" forwarded\n    LogFormat \"%h %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\" combined\n    LogFormat \"%{X-Forwarded-For}i %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\" forwarded\n\tErrorLog \"|/usr/bin/logger -t mahara -p local1.error\"\n    CustomLog \"|/usr/bin/logger -t mahara -p local1.notice\" combined env=!forwarded\n    CustomLog \"|/usr/bin/logger -t mahara -p local1.notice\" forwarded env=forwarded\n\n</VirtualHost>\nEOF\n  fi # if [ \"$webServerType\" = \"apache\" ];\n\n   # php config\n   if [ \"$webServerType\" = \"apache\" ]; then\n     PhpIni=/etc/php/7.0/apache2/php.ini\n   else\n     PhpIni=/etc/php/7.0/fpm/php.ini\n   fi\n   sed -i \"s/memory_limit.*/memory_limit = 512M/\" $PhpIni\n   sed -i \"s/max_execution_time.*/max_execution_time = 18000/\" $PhpIni\n   sed -i \"s/max_input_vars.*/max_input_vars = 100000/\" $PhpIni\n   sed -i \"s/max_input_time.*/max_input_time = 600/\" $PhpIni\n   sed -i \"s/upload_max_filesize.*/upload_max_filesize = 1024M/\" $PhpIni\n   sed -i \"s/post_max_size.*/post_max_size = 1056M/\" $PhpIni\n   sed -i \"s/;opcache.use_cwd.*/opcache.use_cwd = 1/\" $PhpIni\n   sed -i \"s/;opcache.validate_timestamps.*/opcache.validate_timestamps = 1/\" $PhpIni\n   sed -i \"s/;opcache.save_comments.*/opcache.save_comments = 1/\" $PhpIni\n   sed -i \"s/;opcache.enable_file_override.*/opcache.enable_file_override = 0/\" $PhpIni\n   sed -i \"s/;opcache.enable.*/opcache.enable = 1/\" $PhpIni\n   sed -i \"s/;opcache.memory_consumption.*/opcache.memory_consumption = 256/\" $PhpIni\n   sed -i \"s/;opcache.max_accelerated_files.*/opcache.max_accelerated_files = 8000/\" $PhpIni\n\n   # Remove the default site. Mahara is the only site we want\n   rm -f /etc/nginx/sites-enabled/default\n   if [ \"$webServerType\" = \"apache\" ]; then\n     rm -f /etc/apache2/sites-enabled/000-default.conf\n   fi\n\n   if [ \"$webServerType\" = \"nginx\" -o \"$httpsTermination\" = \"VMSS\" ]; then\n     # restart Nginx\n     sudo service nginx restart\n   fi\n\n   if [ \"$webServerType\" = \"nginx\" ]; then\n     # fpm config - overload this\n     cat <<EOF > /etc/php/7.0/fpm/pool.d/www.conf\n[www]\nuser = www-data\ngroup = www-data\nlisten = /run/php/php7.0-fpm.sock\nlisten.owner = www-data\nlisten.group = www-data\npm = dynamic\npm.max_children = 3000\npm.start_servers = 20\npm.min_spare_servers = 20\npm.max_spare_servers = 30\nEOF\n\n     # Restart fpm\n     service php7.0-fpm restart\n   fi\n\n   if [ \"$webServerType\" = \"apache\" ]; then\n     sudo service apache2 restart\n   fi\n\n   # Configure varnish startup for 16.04\n   VARNISHSTART=\"ExecStart=\\/usr\\/sbin\\/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f \\/etc\\/varnish\\/mahara.vcl -S \\/etc\\/varnish\\/secret -s malloc,1024m -p thread_pool_min=200 -p thread_pool_max=4000 -p thread_pool_add_delay=2 -p timeout_linger=100 -p timeout_idle=30 -p send_timeout=1800 -p thread_pools=4 -p http_max_hdr=512 -p workspace_backend=512k\"\n   sed -i \"s/^ExecStart.*/${VARNISHSTART}/\" /lib/systemd/system/varnish.service\n\n   # Configure varnish VCL for Mahara\n   cat <<EOF >> /etc/varnish/mahara.vcl\nvcl 4.0;\n\nimport std;\nimport directors;\nbackend default {\n    .host = \"localhost\";\n    .port = \"81\";\n    .first_byte_timeout = 3600s;\n    .connect_timeout = 600s;\n    .between_bytes_timeout = 600s;\n}\n\nsub vcl_recv {\n    # Varnish does not support SPDY or HTTP/2.0 untill we upgrade to Varnish 5.0\n    if (req.method == \"PRI\") {\n        return (synth(405));\n    }\n\n    if (req.restarts == 0) {\n      if (req.http.X-Forwarded-For) {\n        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + \", \" + client.ip;\n      } else {\n        set req.http.X-Forwarded-For = client.ip;\n      }\n    }\n\n    # Non-RFC2616 or CONNECT HTTP requests methods filtered. Pipe requests directly to backend\n    if (req.method != \"GET\" &&\n        req.method != \"HEAD\" &&\n        req.method != \"PUT\" &&\n        req.method != \"POST\" &&\n        req.method != \"TRACE\" &&\n        req.method != \"OPTIONS\" &&\n        req.method != \"DELETE\") {\n      return (pipe);\n    }\n\n    # Varnish don't mess with healthchecks\n    if (req.url ~ \"^/admin/tool/heartbeat\" || req.url ~ \"^/healthcheck.php\")\n    {\n        return (pass);\n    }\n\n    # Pipe requests to backup.php straight to backend - prevents problem with progress bar long polling 503 problem\n    # This is here because backup.php is POSTing to itself - Filter before !GET&&!HEAD\n    if (req.url ~ \"^/backup/backup.php\")\n    {\n        return (pipe);\n    }\n\n    # Varnish only deals with GET and HEAD by default. If request method is not GET or HEAD, pass request to backend\n    if (req.method != \"GET\" && req.method != \"HEAD\") {\n      return (pass);\n    }\n\n    ### Rules for Mahara and Totara sites ###\n    # Mahara doesn't require Cookie to serve following assets. Remove Cookie header from request, so it will be looked up.\n    if ( req.url ~ \"^/altlogin/.+/.+\\.(png|jpg|jpeg|gif|css|js|webp)$\" ||\n         req.url ~ \"^/pix/.+\\.(png|jpg|jpeg|gif)$\" ||\n         req.url ~ \"^/theme/font.php\" ||\n         req.url ~ \"^/theme/image.php\" ||\n         req.url ~ \"^/theme/javascript.php\" ||\n         req.url ~ \"^/theme/jquery.php\" ||\n         req.url ~ \"^/theme/styles.php\" ||\n         req.url ~ \"^/theme/yui\" ||\n         req.url ~ \"^/lib/javascript.php/-1/\" ||\n         req.url ~ \"^/lib/requirejs.php/-1/\"\n        )\n    {\n        set req.http.X-Long-TTL = \"86400\";\n        unset req.http.Cookie;\n        return(hash);\n    }\n\n    # Perform lookup for selected assets that we know are static but Mahara still needs a Cookie\n    if(  req.url ~ \"^/theme/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/lib/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/pluginfile.php/[0-9]+/course/overviewfiles/.+\\.(?i)(png|jpg)$\"\n      )\n    {\n         # Set internal temporary header, based on which we will do things in vcl_backend_response\n         set req.http.X-Long-TTL = \"86400\";\n         return (hash);\n    }\n\n    # Serve requests to SCORM checknet.txt from varnish. Have to remove get parameters. Response body always contains \"1\"\n    if ( req.url ~ \"^/lib/yui/build/mahara-core-checknet/assets/checknet.txt\" )\n    {\n        set req.url = regsub(req.url, \"(.*)\\?.*\", \"\\1\");\n        unset req.http.Cookie; # Will go to hash anyway at the end of vcl_recv\n        set req.http.X-Long-TTL = \"86400\";\n        return(hash);\n    }\n\n    # Requests containing \"Cookie\" or \"Authorization\" headers will not be cached\n    if (req.http.Authorization || req.http.Cookie) {\n        return (pass);\n    }\n\n    # Almost everything in Mahara correctly serves Cache-Control headers, if\n    # needed, which varnish will honor, but there are some which don't. Rather\n    # than explicitly finding them all and listing them here we just fail safe\n    # and don't cache unknown urls that get this far.\n    return (pass);\n}\n\nsub vcl_backend_response {\n    # Happens after we have read the response headers from the backend.\n    #\n    # Here you clean the response headers, removing silly Set-Cookie headers\n    # and other mistakes your backend does.\n\n    # We know these assest are static, let's set TTL >0 and allow client caching\n    if ( beresp.http.Cache-Control && bereq.http.X-Long-TTL && beresp.ttl < std.duration(bereq.http.X-Long-TTL + \"s\", 1s) && !beresp.http.WWW-Authenticate )\n    { # If max-age < defined in X-Long-TTL header\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.X-Orig-Cache-Control = beresp.http.Cache-Control;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else if( !beresp.http.Cache-Control && bereq.http.X-Long-TTL && !beresp.http.WWW-Authenticate ) {\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else { # Don't touch headers if max-age > defined in X-Long-TTL header\n        unset bereq.http.X-Long-TTL;\n    }\n\n    # Here we set X-Trace header, prepending it to X-Trace header received from backend. Useful for troubleshooting\n    if(beresp.http.x-trace && !beresp.was_304) {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\")+\"->\"+beresp.http.X-Trace;\n    }\n    else {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\");\n    }\n\n    # Gzip JS, CSS is done at the ngnix level doing it here dosen't respect the no buffer requsets\n    # if (beresp.http.content-type ~ \"application/javascript.*\" || beresp.http.content-type ~ \"text\") {\n    #    set beresp.do_gzip = true;\n    #}\n}\n\nsub vcl_deliver {\n\n    # Revert back to original Cache-Control header before delivery to client\n    if (resp.http.X-Orig-Cache-Control)\n    {\n        set resp.http.Cache-Control = resp.http.X-Orig-Cache-Control;\n        unset resp.http.X-Orig-Cache-Control;\n    }\n\n    # Revert back to original Pragma header before delivery to client\n    if (resp.http.X-Orig-Pragma)\n    {\n        set resp.http.Pragma = resp.http.X-Orig-Pragma;\n        unset resp.http.X-Orig-Pragma;\n    }\n\n    # (Optional) X-Cache HTTP header will be added to responce, indicating whether object was retrieved from backend, or served from cache\n    if (obj.hits > 0) {\n        set resp.http.X-Cache = \"HIT\";\n    } else {\n        set resp.http.X-Cache = \"MISS\";\n    }\n\n    # Set X-AuthOK header when totara/varnsih authentication succeeded\n    if (req.http.X-AuthOK) {\n        set resp.http.X-AuthOK = req.http.X-AuthOK;\n    }\n\n    # If desired \"Via: 1.1 Varnish-v4\" response header can be removed from response\n    unset resp.http.Via;\n    unset resp.http.Server;\n\n    return(deliver);\n}\n\nsub vcl_backend_error {\n    # More comprehensive varnish error page. Display time, instance hostname, host header, url for easier troubleshooting.\n    set beresp.http.Content-Type = \"text/html; charset=utf-8\";\n    set beresp.http.Retry-After = \"5\";\n    synthetic( {\"\n  <!DOCTYPE html>\n  <html>\n    <head>\n      <title>\"} + beresp.status + \" \" + beresp.reason + {\"</title>\n    </head>\n    <body>\n      <h1>Error \"} + beresp.status + \" \" + beresp.reason + {\"</h1>\n      <p>\"} + beresp.reason + {\"</p>\n      <h3>Guru Meditation:</h3>\n      <p>Time: \"} + now + {\"</p>\n      <p>Node: \"} + server.hostname + {\"</p>\n      <p>Host: \"} + bereq.http.host + {\"</p>\n      <p>URL: \"} + bereq.url + {\"</p>\n      <p>XID: \"} + bereq.xid + {\"</p>\n      <hr>\n      <p>Varnish cache server\n    </body>\n  </html>\n  \"} );\n   return (deliver);\n}\n\nsub vcl_synth {\n\n    #Redirect using '301 - Permanent Redirect', permanent redirect\n    if (resp.status == 851) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 301;\n        return (deliver);\n    }\n\n    #Redirect using '302 - Found', temporary redirect\n    if (resp.status == 852) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 302;\n        return (deliver);\n    }\n\n    #Redirect using '307 - Temporary Redirect', !GET&&!HEAD requests, dont change method on redirected requests\n    if (resp.status == 857) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 307;\n        return (deliver);\n    }\n\n    #Respond with 403 - Forbidden\n    if (resp.status == 863) {\n        set resp.http.X-Varnish-Error = true;\n        set resp.status = 403;\n        return (deliver);\n    }\n}\n#this is a comment\nEOF\n\n  # Restart Varnish\n  systemctl daemon-reload\n  service varnish restart\n\n}  > /tmp/setup.log\n", "num_lines": 652}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Custom Minecraft server install script for Ubuntu 15.04\n# $1 = Minecraft user name\n# $2 = difficulty\n# $3 = level-name\n# $4 = gamemode\n# $5 = white-list\n# $6 = enable-command-block\n# $7 = spawn-monsters\n# $8 = generate-structures\n# $9 = level-seed\n# $10 = location of the Minecraft server launcher\n\n# basic service and API settings\nminecraft_server_path=/srv/minecraft_server\nminecraft_user=minecraft\nminecraft_group=minecraft\nUUID_URL=https://api.mojang.com/users/profiles/minecraft/$1\n\nserver_jar=server.jar\n\n# add and update repos\nsudo apt-get update\n\n# install jre\nsudo apt-get -y install default-jre\n\n# create user and install folder\nadduser --system --no-create-home --home $minecraft_server_path $minecraft_user\naddgroup --system $minecraft_group\nmkdir $minecraft_server_path\ncd $minecraft_server_path\n\n# download the server jar\nwget -O $10\n\n# set permissions on install folder\nchown -R $minecraft_user $minecraft_server_path\n\n# adjust memory usage depending on VM size\ntotalMem=$(free -m | awk '/Mem:/ { print $2 }')\nif [ $totalMem -lt 2048 ]; then\n    memoryAllocs=512m\n    memoryAllocx=1g\nelse\n    memoryAllocs=1g\n    memoryAllocx=2g\nfi\n\n# create the eula file\ntouch $minecraft_server_path/eula.txt\necho 'eula=true' >> $minecraft_server_path/eula.txt\n\n# create a service\ntouch /etc/systemd/system/minecraft-server.service\nprintf '[Unit]\\nDescription=Minecraft Service\\nAfter=rc-local.service\\n' >> /etc/systemd/system/minecraft-server.service\nprintf '[Service]\\nWorkingDirectory=%s\\n' $minecraft_server_path >> /etc/systemd/system/minecraft-server.service\nprintf 'ExecStart=/usr/bin/java -Xms%s -Xmx%s -jar %s/%s nogui\\n' $memoryAllocs $memoryAllocx $minecraft_server_path $server_jar >> /etc/systemd/system/minecraft-server.service\nprintf 'ExecReload=/bin/kill -HUP $MAINPID\\nKillMode=process\\nRestart=on-failure\\n' >> /etc/systemd/system/minecraft-server.service\nprintf '[Install]\\nWantedBy=multi-user.target\\nAlias=minecraft-server.service' >> /etc/systemd/system/minecraft-server.service\nchmod +x /etc/systemd/system/minecraft-server.service\n\n# create a valid operators file using the Mojang API\ntouch $minecraft_server_path/ops.json\nmojang_output=\"`wget -qO- $UUID_URL`\"\nrawUUID=${mojang_output:7:32}\nUUID=${rawUUID:0:8}-${rawUUID:8:4}-${rawUUID:12:4}-${rawUUID:16:4}-${rawUUID:20:12}\nprintf '[\\n {\\n  \\\"uuid\\\":\\\"%s\\\",\\n  \\\"name\\\":\\\"%s\\\",\\n  \\\"level\\\":4\\n }\\n]' $UUID $1 >> $minecraft_server_path/ops.json\nchown $minecraft_user:$minecraft_group $minecraft_server_path/ops.json\n\n# set user preferences in server.properties\ntouch $minecraft_server_path/server.properties\nchown $minecraft_user:$minecraft_group $minecraft_server_path/server.properties\n# echo 'max-tick-time=-1' >> $minecraft_server_path/server.properties\nprintf 'difficulty=%s\\n' $2 >> $minecraft_server_path/server.properties\nprintf 'level-name=%s\\n' $3 >> $minecraft_server_path/server.properties\nprintf 'gamemode=%s\\n' $4 >> $minecraft_server_path/server.properties\nprintf 'white-list=%s\\n' $5 >> $minecraft_server_path/server.properties\nprintf 'enable-command-block=%s\\n' $6 >> $minecraft_server_path/server.properties\nprintf 'spawn-monsters=%s\\n' $7 >> $minecraft_server_path/server.properties\nprintf 'generate-structures=%s\\n' $8 >> $minecraft_server_path/server.properties\nprintf 'level-seed=%s\\n' $9 >> $minecraft_server_path/server.properties\n\nsystemctl start minecraft-server\n", "num_lines": 85}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Download and install Helm\nwget -O helm.tgz https://get.helm.sh/helm-v3.4.1-linux-amd64.tar.gz\ntar -zxvf helm.tgz\nmv linux-amd64/helm /usr/local/bin/helm\n# Install kubectl\naz aks install-cli\n# Get minio cluster credentials\naz aks get-credentials -g $RESOURCEGROUP -n minio-cluster\n# Install minio helm chart\nhelm repo add minio https://helm.min.io/\nwget -O values.yaml $HELMVALUES\nhelm upgrade --install --wait minio minio/minio --set azuregateway.enabled=true --set accessKey=$STORAGEACCOUNTNAME --set secretKey=$STORAGEACCOUNTKEY --set service.type=LoadBalancer --values values.yaml\n# Get load balancer IP, once available\nuntil [ $(kubectl get service minio -o=jsonpath='{...ip}') != \"\" ]; do sleep 15; done\nserviceIp=$(kubectl get service minio -o=jsonpath='{...ip}')\n#Configure Pod Autoscaler\nkubectl autoscale deployment minio --cpu-percent=60 --min=3 --max=50\n# Create output for S3 endpoint IP \necho \\{\\\"loadBalancerIP\\\":\\\"$serviceIp\\\"\\} > $AZ_SCRIPTS_OUTPUT_PATH", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#--------------------------------------------------------------------------------------------------\n# MongoDB Template for Azure Resource Manager (brought to you by Full Scale 180 Inc)\n#\n# This script installs MongoDB on each Azure virtual machine. The script will be supplied with\n# runtime parameters declared from within the corresponding ARM template.\n#--------------------------------------------------------------------------------------------------\n\nPACKAGE_URL=http://repo.mongodb.org/apt/ubuntu\nPACKAGE_NAME=mongodb-org\nPACKAGE_VERSION=\"4.0.2\"\nREPLICA_SET_KEY_DATA=\"\"\nREPLICA_SET_NAME=\"\"\nREPLICA_SET_KEY_FILE=\"/etc/mongo-replicaset-key\"\nDATA_DISKS=\"/datadisks\"\nDATA_MOUNTPOINT=\"$DATA_DISKS/disk1\"\nMONGODB_DATA=\"$DATA_MOUNTPOINT/mongodb\"\nMONGODB_PORT=27017\nIS_ARBITER=false\nIS_LAST_MEMBER=false\nJOURNAL_ENABLED=true\nADMIN_USER_NAME=\"\"\nADMIN_USER_PASSWORD=\"\"\nINSTANCE_COUNT=1\nNODE_IP_PREFIX=\"10.0.0.1\"\nLOGGING_KEY=\"[logging-key]\"\n\nhelp()\n{\n\techo \"This script installs MongoDB on the Ubuntu virtual machine image\"\n\techo \"Options:\"\n\techo \"\t\t-i Installation package URL\"\n\techo \"\t\t-b Installation package name\"\n\techo \"\t\t-v Installation package version\"\n\techo \"\t\t-r Replica set name\"\n\techo \"\t\t-k Replica set key\"\n\techo \"\t\t-u System administrator's user name\"\n\techo \"\t\t-p System administrator's password\"\n\techo \"\t\t-x Member node IP prefix\"\n\techo \"\t\t-n Number of member nodes\"\n\techo \"\t\t-a (arbiter indicator)\"\n\techo \"\t\t-l (last member indicator)\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n\t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/${LOGGING_KEY}/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of MongoDB installation script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts :i:b:v:r:k:u:p:x:n:alh optname; do\n\n\t# Log input parameters (except the admin password) to facilitate troubleshooting\n\tif [ ! \"$optname\" == \"p\" ] && [ ! \"$optname\" == \"k\" ]; then\n\t\tlog \"Option $optname set with value ${OPTARG}\"\n\tfi\n\n\tcase $optname in\n\ti) # Installation package location\n\t\tPACKAGE_URL=${OPTARG}\n\t\t;;\n\tb) # Installation package name\n\t\tPACKAGE_NAME=${OPTARG}\n\t\t;;\n\tv) # Installation package version\n\t\tPACKAGE_VERSION=${OPTARG}\n\t\t;;\n\tr) # Replica set name\n\t\tREPLICA_SET_NAME=${OPTARG}\n\t\t;;\n\tk) # Replica set key\n\t\tREPLICA_SET_KEY_DATA=${OPTARG}\n\t\t;;\n\tu) # Administrator's user name\n\t\tADMIN_USER_NAME=${OPTARG}\n\t\t;;\n\tp) # Administrator's user name\n\t\tADMIN_USER_PASSWORD=${OPTARG}\n\t\t;;\n\tx) # Private IP address prefix\n\t\tNODE_IP_PREFIX=${OPTARG}\n\t\t;;\n\tn) # Number of instances\n\t\tINSTANCE_COUNT=${OPTARG}\n\t\t;;\n\ta) # Arbiter indicator\n\t\tIS_ARBITER=true\n\t\t;;\n\tl) # Last member indicator\n\t\tIS_LAST_MEMBER=true\n\t\t;;\n    h)  # Helpful hints\n\t\thelp\n\t\texit 2\n\t\t;;\n    \\?) # Unrecognized option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\n# Validate parameters\nif [ \"$ADMIN_USER_NAME\" == \"\" ] || [ \"$ADMIN_USER_PASSWORD\" == \"\" ];\nthen\n    log \"Script executed without admin credentials\"\n    echo \"You must provide a name and password for the system administrator.\" >&2\n    exit 3\nfi\n\n#############################################################################\ntune_memory()\n{\n\t# Disable THP on a running system\n\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\n\t# Disable THP upon reboot\n\tcp -p /etc/rc.local /etc/rc.local.`date +%Y%m%d-%H:%M`\n\tsed -i -e '$i \\ if test -f /sys/kernel/mm/transparent_hugepage/enabled; then \\\n \t\t\t echo never > /sys/kernel/mm/transparent_hugepage/enabled \\\n\t\t  fi \\ \\\n\t\tif test -f /sys/kernel/mm/transparent_hugepage/defrag; then \\\n\t\t   echo never > /sys/kernel/mm/transparent_hugepage/defrag \\\n\t\tfi \\\n\t\t\\n' /etc/rc.local\n}\n\ntune_system()\n{\n\t# Add local machine name to the hosts file to facilitate IP address resolution\n\tif grep -q \"${HOSTNAME}\" /etc/hosts\n\tthen\n\t  echo \"${HOSTNAME} was found in /etc/hosts\"\n\telse\n\t  echo \"${HOSTNAME} was not found in and will be added to /etc/hosts\"\n\t  # Append it to the hsots file if not there\n\t  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n\t  log \"Hostname ${HOSTNAME} added to /etc/hosts\"\n\tfi\n}\n\n#############################################################################\ninstall_mongodb()\n{\n\tlog \"Downloading MongoDB package $PACKAGE_NAME from $PACKAGE_URL\"\n\n\t# Configure mongodb.list file with the correct location\n\tapt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4\n\techo \"deb ${PACKAGE_URL} \"$(lsb_release -sc)\"/mongodb-org/4.0 multiverse\" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list\n\n\t# Install updates\n\tapt-get -y update\n\n\t# Remove any previously created configuration file to avoid a prompt\n\tif [ -f /etc/mongod.conf ]; then\n\t\trm /etc/mongod.conf\n\tfi\n\n\t#Install Mongo DB\n\tlog \"Installing MongoDB package $PACKAGE_NAME=$PACKAGE_VERSION\"\n\tapt-get -y install $PACKAGE_NAME=$PACKAGE_VERSION\n\n\t# Stop Mongod as it may be auto-started during the above step (which is not desirable)\n\tstop_mongodb\n}\n\n#############################################################################\nconfigure_datadisks()\n{\n\t# Stripe all of the data\n\tlog \"Formatting and configuring the data disks\"\n\n\tbash ./vm-disk-utils-0.1.sh -b $DATA_DISKS -s\n}\n\n#############################################################################\nconfigure_replicaset()\n{\n\tlog \"Configuring a replica set $REPLICA_SET_NAME\"\n\n\techo \"$REPLICA_SET_KEY_DATA\" | tee \"$REPLICA_SET_KEY_FILE\" > /dev/null\n\tchown -R mongodb:mongodb \"$REPLICA_SET_KEY_FILE\"\n\tchmod 600 \"$REPLICA_SET_KEY_FILE\"\n\n\t# Enable replica set in the configuration file\n\tsed -i \"s|#keyFile: \\\"\\\"$|keyFile: \\\"${REPLICA_SET_KEY_FILE}\\\"|g\" /etc/mongod.conf\n\tsed -i \"s|authorization: \\\"disabled\\\"$|authorization: \\\"enabled\\\"|g\" /etc/mongod.conf\n\tsed -i \"s|#replication:|replication:|g\" /etc/mongod.conf\n\tsed -i \"s|#replSetName:|replSetName:|g\" /etc/mongod.conf\n\n\t# Stop the currently running MongoDB daemon as we will need to reload its configuration\n\tstop_mongodb\n\n\t# Attempt to start the MongoDB daemon so that configuration changes take effect\n\tstart_mongodb\n\n\t# Initiate a replica set (only run this section on the very last node)\n\tif [ \"$IS_LAST_MEMBER\" = true ]; then\n\t\t# Log a message to facilitate troubleshooting\n\t\tlog \"Initiating a replica set $REPLICA_SET_NAME with $INSTANCE_COUNT members\"\n\n\t\t# Initiate a replica set\n\t\tmongo --authenticationDatabase \"admin\" -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.initiate())\"\n\n\t\t# Add all members except this node as it will be included into the replica set after the above command completes\n\t\tfor (( n=0 ; n<($INSTANCE_COUNT-1) ; n++))\n\t\tdo\n\t\t\tMEMBER_HOST=\"${NODE_IP_PREFIX}${n}:${MONGODB_PORT}\"\n\n\t\t\tlog \"Adding member $MEMBER_HOST to replica set $REPLICA_SET_NAME\"\n\t\t\tmongo --authenticationDatabase \"admin\" -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.add('${MEMBER_HOST}'))\"\n\t\tdone\n\n\t\t# Print the current replica set configuration\n\t\tmongo --authenticationDatabase \"admin\" -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.conf())\"\n\t\tmongo --authenticationDatabase \"admin\" -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.status())\"\n\tfi\n\n\t# Register an arbiter node with the replica set\n\tif [ \"$IS_ARBITER\" = true ]; then\n\n\t\t# Work out the IP address of the last member node where we initiated a replica set\n\t\tlet \"PRIMARY_MEMBER_INDEX=$INSTANCE_COUNT-1\"\n\t\tPRIMARY_MEMBER_HOST=\"${NODE_IP_PREFIX}${PRIMARY_MEMBER_INDEX}:${MONGODB_PORT}\"\n\t\tCURRENT_NODE_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n\t\tCURRENT_NODE_IP=${CURRENT_NODE_IPS[@]}\n\n\t\tlog \"Adding an arbiter ${HOSTNAME} ($CURRENT_NODE_IP) node to the replica set $REPLICA_SET_NAME\"\n\t\tmongo --authenticationDatabase \"admin\" -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host $PRIMARY_MEMBER_HOST --eval \"printjson(rs.addArb('${CURRENT_NODE_IP}'))\"\n\tfi\n}\n\n#############################################################################\nconfigure_mongodb()\n{\n\tlog \"Configuring MongoDB\"\n\n\tmkdir -p \"$MONGODB_DATA\"\n\tmkdir \"$MONGODB_DATA/log\"\n\tmkdir \"$MONGODB_DATA/db\"\n\n\tchown -R mongodb:mongodb \"$MONGODB_DATA/db\"\n\tchown -R mongodb:mongodb \"$MONGODB_DATA/log\"\n\tchmod 755 \"$MONGODB_DATA\"\n\n\ttee /etc/mongod.conf > /dev/null <<EOF\nsystemLog:\n    destination: file\n    path: \"$MONGODB_DATA/log/mongod.log\"\n    quiet: true\n    logAppend: true\nprocessManagement:\n    fork: true\n    pidFilePath: \"/var/run/mongodb/mongod.pid\"\nnet:\n    bindIpAll: true\n    port: $MONGODB_PORT\nsecurity:\n    #keyFile: \"\"\n    authorization: \"disabled\"\nstorage:\n    dbPath: \"$MONGODB_DATA/db\"\n    directoryPerDB: true\n    journal:\n        enabled: $JOURNAL_ENABLED\n#replication:\n    #replSetName: \"$REPLICA_SET_NAME\"\nEOF\n\n\t# Fixing an issue where the mongod will not start after reboot where when /run is tmpfs the /var/run/mongodb directory will be deleted at reboot\n\t# After reboot, mongod wouldn't start since the pidFilePath is defined as /var/run/mongodb/mongod.pid in the configuration and path doesn't exist\n\tsed -i \"s|pre-start script|pre-start script\\n  if [ ! -d /var/run/mongodb ]; then\\n    mkdir -p /var/run/mongodb \\&\\& touch /var/run/mongodb/mongod.pid \\&\\& chmod 777 /var/run/mongodb/mongod.pid \\&\\& chown mongodb:mongodb /var/run/mongodb/mongod.pid\\n  fi\\n|\" /etc/init/mongod.conf\n\n\n}\n\nstart_mongodb()\n{\n\tlog \"Starting MongoDB daemon processes\"\n\tservice mongod start\n\n\t# Wait for MongoDB daemon to start and initialize for the first time (this may take up to a minute or so)\n\twhile ! timeout 1 bash -c \"echo > /dev/tcp/localhost/$MONGODB_PORT\"; do sleep 10; done\n}\n\nstop_mongodb()\n{\n\t# Find out what PID the MongoDB instance is running as (if any)\n\tMONGOPID=`ps -ef | grep '/usr/bin/mongod' | grep -v grep | awk '{print $2}'`\n\n\tif [ ! -z \"$MONGOPID\" ]; then\n\t\tlog \"Stopping MongoDB daemon processes (PID $MONGOPID)\"\n\n\t\tkill -15 $MONGOPID\n\tfi\n\n\t# Important not to attempt to start the daemon immediately after it was stopped as unclean shutdown may be wrongly perceived\n\tsleep 15s\n}\n\nconfigure_db_users()\n{\n\t# Create a system administrator\n\tlog \"Creating a system administrator\"\n\tmongo admin --host 127.0.0.1 --eval \"db.createUser({user: '${ADMIN_USER_NAME}', pwd: '${ADMIN_USER_PASSWORD}', roles:[{ role: 'userAdminAnyDatabase', db: 'admin' }, { role: 'clusterAdmin', db: 'admin' }, { role: 'readWriteAnyDatabase', db: 'admin' }, { role: 'dbAdminAnyDatabase', db: 'admin' } ]})\"\n}\n\n# Step 1\nconfigure_datadisks\n\n# Step 2\ntune_memory\ntune_system\n\n# Step 3\ninstall_mongodb\n\n# Step 4\nconfigure_mongodb\n\n# Step 5\nstart_mongodb\n\n# Step 6\nconfigure_db_users\n\n# Step 7\nconfigure_replicaset\n\n# Exit (proudly)\nexit 0\n", "num_lines": 368}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#--------------------------------------------------------------------------------------------------\n# MongoDB Template for Azure Resource Manager (brought to you by Full Scale 180 Inc)\n#\n# This script installs MongoDB on each Azure virtual machine. The script will be supplied with\n# runtime parameters declared from within the corresponding ARM template.\n#--------------------------------------------------------------------------------------------------\n\nPACKAGE_URL=http://repo.mongodb.org/apt/ubuntu\nPACKAGE_NAME=mongodb-org\nREPLICA_SET_KEY_DATA=\"\"\nREPLICA_SET_NAME=\"\"\nREPLICA_SET_KEY_FILE=\"/etc/mongo-replicaset-key\"\nDATA_DISKS=\"/datadisks\"\nDATA_MOUNTPOINT=\"$DATA_DISKS/disk1\"\nMONGODB_DATA=\"$DATA_MOUNTPOINT/mongodb\"\nMONGODB_PORT=27017\nIS_ARBITER=false\nIS_LAST_MEMBER=false\nJOURNAL_ENABLED=true\nADMIN_USER_NAME=\"\"\nADMIN_USER_PASSWORD=\"\"\nINSTANCE_COUNT=1\nNODE_IP_PREFIX=\"10.0.0.1\"\nLOGGING_KEY=\"[logging-key]\"\n\nhelp()\n{\n\techo \"This script installs MongoDB on the Ubuntu virtual machine image\"\n\techo \"Options:\"\n\techo \"\t\t-i Installation package URL\"\n\techo \"\t\t-b Installation package name\"\n\techo \"\t\t-r Replica set name\"\n\techo \"\t\t-k Replica set key\"\n\techo \"\t\t-u System administrator's user name\"\n\techo \"\t\t-p System administrator's password\"\n\techo \"\t\t-x Member node IP prefix\"\n\techo \"\t\t-n Number of member nodes\"\n\techo \"\t\t-a (arbiter indicator)\"\n\techo \"\t\t-l (last member indicator)\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n\t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/${LOGGING_KEY}/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of MongoDB installation script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts :i:b:r:k:u:p:x:n:alh optname; do\n\n\t# Log input parameters (except the admin password) to facilitate troubleshooting\n\tif [ ! \"$optname\" == \"p\" ] && [ ! \"$optname\" == \"k\" ]; then\n\t\tlog \"Option $optname set with value ${OPTARG}\"\n\tfi\n\n\tcase $optname in\n\ti) # Installation package location\n\t\tPACKAGE_URL=${OPTARG}\n\t\t;;\n\tb) # Installation package name\n\t\tPACKAGE_NAME=${OPTARG}\n\t\t;;\n\tr) # Replica set name\n\t\tREPLICA_SET_NAME=${OPTARG}\n\t\t;;\n\tk) # Replica set key\n\t\tREPLICA_SET_KEY_DATA=${OPTARG}\n\t\t;;\n\tu) # Administrator's user name\n\t\tADMIN_USER_NAME=${OPTARG}\n\t\t;;\n\tp) # Administrator's user name\n\t\tADMIN_USER_PASSWORD=${OPTARG}\n\t\t;;\n\tx) # Private IP address prefix\n\t\tNODE_IP_PREFIX=${OPTARG}\n\t\t;;\n\tn) # Number of instances\n\t\tINSTANCE_COUNT=${OPTARG}\n\t\t;;\n\ta) # Arbiter indicator\n\t\tIS_ARBITER=true\n\t\tJOURNAL_ENABLED=false\n\t\t;;\n\tl) # Last member indicator\n\t\tIS_LAST_MEMBER=true\n\t\t;;\n    h)  # Helpful hints\n\t\thelp\n\t\texit 2\n\t\t;;\n    \\?) # Unrecognized option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\n# Validate parameters\nif [ \"$ADMIN_USER_NAME\" == \"\" ] || [ \"$ADMIN_USER_PASSWORD\" == \"\" ];\nthen\n    log \"Script executed without admin credentials\"\n    echo \"You must provide a name and password for the system administrator.\" >&2\n    exit 3\nfi\n\n#############################################################################\ntune_memory()\n{\n\t# Disable THP on a running system\n\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\n\t# Disable THP upon reboot\n\tcp -p /etc/rc.local /etc/rc.local.`date +%Y%m%d-%H:%M`\n\tsed -i -e '$i \\ if test -f /sys/kernel/mm/transparent_hugepage/enabled; then \\\n \t\t\t echo never > /sys/kernel/mm/transparent_hugepage/enabled \\\n\t\t  fi \\ \\\n\t\tif test -f /sys/kernel/mm/transparent_hugepage/defrag; then \\\n\t\t   echo never > /sys/kernel/mm/transparent_hugepage/defrag \\\n\t\tfi \\\n\t\t\\n' /etc/rc.local\n}\n\ntune_system()\n{\n\t# Add local machine name to the hosts file to facilitate IP address resolution\n\tif grep -q \"${HOSTNAME}\" /etc/hosts\n\tthen\n\t  echo \"${HOSTNAME} was found in /etc/hosts\"\n\telse\n\t  echo \"${HOSTNAME} was not found in and will be added to /etc/hosts\"\n\t  # Append it to the hsots file if not there\n\t  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n\t  log \"Hostname ${HOSTNAME} added to /etc/hosts\"\n\tfi\n}\n\n#############################################################################\ninstall_mongodb()\n{\n\tlog \"Downloading MongoDB package $PACKAGE_NAME from $PACKAGE_URL\"\n\n\t# Configure mongodb.list file with the correct location\n\tapt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10\n\techo \"deb ${PACKAGE_URL} \"$(lsb_release -sc)\"/mongodb-org/3.0 multiverse\" | tee /etc/apt/sources.list.d/mongodb-org-3.0.list\n\n\t# Install updates\n\tapt-get -y update\n\n\t# Remove any previously created configuration file to avoid a prompt\n\tif [ -f /etc/mongod.conf ]; then\n\t\trm /etc/mongod.conf\n\tfi\n\n\t#Install Mongo DB\n\tlog \"Installing MongoDB package $PACKAGE_NAME\"\n\tapt-get -y install $PACKAGE_NAME\n\n\t# Stop Mongod as it may be auto-started during the above step (which is not desirable)\n\tstop_mongodb\n}\n\n#############################################################################\nconfigure_datadisks()\n{\n\t# Stripe all of the data\n\tlog \"Formatting and configuring the data disks\"\n\n\tbash ./vm-disk-utils-0.1.sh -b $DATA_DISKS -s\n}\n\n#############################################################################\nconfigure_replicaset()\n{\n\tlog \"Configuring a replica set $REPLICA_SET_NAME\"\n\n\techo \"$REPLICA_SET_KEY_DATA\" | tee \"$REPLICA_SET_KEY_FILE\" > /dev/null\n\tchown -R mongodb:mongodb \"$REPLICA_SET_KEY_FILE\"\n\tchmod 600 \"$REPLICA_SET_KEY_FILE\"\n\n\t# Enable replica set in the configuration file\n\tsed -i \"s|#keyFile: \\\"\\\"$|keyFile: \\\"${REPLICA_SET_KEY_FILE}\\\"|g\" /etc/mongod.conf\n\tsed -i \"s|authorization: \\\"disabled\\\"$|authorization: \\\"enabled\\\"|g\" /etc/mongod.conf\n\tsed -i \"s|#replication:|replication:|g\" /etc/mongod.conf\n\tsed -i \"s|#replSetName:|replSetName:|g\" /etc/mongod.conf\n\n\t# Stop the currently running MongoDB daemon as we will need to reload its configuration\n\tstop_mongodb\n\n\t# Attempt to start the MongoDB daemon so that configuration changes take effect\n\tstart_mongodb\n\n\t# Initiate a replica set (only run this section on the very last node)\n\tif [ \"$IS_LAST_MEMBER\" = true ]; then\n\t\t# Log a message to facilitate troubleshooting\n\t\tlog \"Initiating a replica set $REPLICA_SET_NAME with $INSTANCE_COUNT members\"\n\n\t\t# Initiate a replica set\n\t\tmongo master -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.initiate())\"\n\n\t\t# Add all members except this node as it will be included into the replica set after the above command completes\n\t\tfor (( n=0 ; n<($INSTANCE_COUNT-1) ; n++))\n\t\tdo\n\t\t\tMEMBER_HOST=\"${NODE_IP_PREFIX}${n}:${MONGODB_PORT}\"\n\n\t\t\tlog \"Adding member $MEMBER_HOST to replica set $REPLICA_SET_NAME\"\n\t\t\tmongo master -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.add('${MEMBER_HOST}'))\"\n\t\tdone\n\n\t\t# Print the current replica set configuration\n\t\tmongo master -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.conf())\"\n\t\tmongo master -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host 127.0.0.1 --eval \"printjson(rs.status())\"\n\tfi\n\n\t# Register an arbiter node with the replica set\n\tif [ \"$IS_ARBITER\" = true ]; then\n\n\t\t# Work out the IP address of the last member node where we initiated a replica set\n\t\tlet \"PRIMARY_MEMBER_INDEX=$INSTANCE_COUNT-1\"\n\t\tPRIMARY_MEMBER_HOST=\"${NODE_IP_PREFIX}${PRIMARY_MEMBER_INDEX}:${MONGODB_PORT}\"\n\t\tCURRENT_NODE_IPS=`ifconfig | grep -Eo 'inet (addr:)?([0-9]*\\.){3}[0-9]*' | grep -Eo '([0-9]*\\.){3}[0-9]*' | grep -v '127.0.0.1'`\n\t\tCURRENT_NODE_IP=${CURRENT_NODE_IPS[@]}\n\n\t\tlog \"Adding an arbiter ${HOSTNAME} ($CURRENT_NODE_IP) node to the replica set $REPLICA_SET_NAME\"\n\t\tmongo master -u $ADMIN_USER_NAME -p $ADMIN_USER_PASSWORD --host $PRIMARY_MEMBER_HOST --eval \"printjson(rs.addArb('${CURRENT_NODE_IP}'))\"\n\tfi\n}\n\n#############################################################################\nconfigure_mongodb()\n{\n\tlog \"Configuring MongoDB\"\n\n\tmkdir -p \"$MONGODB_DATA\"\n\tmkdir \"$MONGODB_DATA/log\"\n\tmkdir \"$MONGODB_DATA/db\"\n\n\tchown -R mongodb:mongodb \"$MONGODB_DATA/db\"\n\tchown -R mongodb:mongodb \"$MONGODB_DATA/log\"\n\tchmod 755 \"$MONGODB_DATA\"\n\n\tmkdir /var/run/mongodb\n\ttouch /var/run/mongodb/mongod.pid\n\tchmod 777 /var/run/mongodb/mongod.pid\n\n\ttee /etc/mongod.conf > /dev/null <<EOF\nsystemLog:\n    destination: file\n    path: \"$MONGODB_DATA/log/mongod.log\"\n    quiet: true\n    logAppend: true\nprocessManagement:\n    fork: true\n    pidFilePath: \"/var/run/mongodb/mongod.pid\"\nnet:\n    port: $MONGODB_PORT\nsecurity:\n    #keyFile: \"\"\n    authorization: \"disabled\"\nstorage:\n    dbPath: \"$MONGODB_DATA/db\"\n    directoryPerDB: true\n    journal:\n        enabled: $JOURNAL_ENABLED\n#replication:\n    #replSetName: \"$REPLICA_SET_NAME\"\nEOF\n}\n\nstart_mongodb()\n{\n\tlog \"Starting MongoDB daemon processes\"\n\tservice mongod start\n\n\t# Wait for MongoDB daemon to start and initialize for the first time (this may take up to a minute or so)\n\twhile ! timeout 1 bash -c \"echo > /dev/tcp/localhost/$MONGODB_PORT\"; do sleep 10; done\n}\n\nstop_mongodb()\n{\n\t# Find out what PID the MongoDB instance is running as (if any)\n\tMONGOPID=`ps -ef | grep '/usr/bin/mongod' | grep -v grep | awk '{print $2}'`\n\n\tif [ ! -z \"$MONGOPID\" ]; then\n\t\tlog \"Stopping MongoDB daemon processes (PID $MONGOPID)\"\n\n\t\tkill -15 $MONGOPID\n\tfi\n\n\t# Important not to attempt to start the daemon immediately after it was stopped as unclean shutdown may be wrongly perceived\n\tsleep 15s\n}\n\nconfigure_db_users()\n{\n\t# Create a system administrator\n\tlog \"Creating a system administrator\"\n\tmongo master --host 127.0.0.1 --eval \"db.createUser({user: '${ADMIN_USER_NAME}', pwd: '${ADMIN_USER_PASSWORD}', roles:[{ role: 'userAdminAnyDatabase', db: 'admin' }, { role: 'clusterAdmin', db: 'admin' }, { role: 'readWriteAnyDatabase', db: 'admin' }, { role: 'dbAdminAnyDatabase', db: 'admin' } ]})\"\n\tmongo tasks --host 127.0.0.1 --eval \"db.createUser({user: '${ADMIN_USER_NAME}', pwd: '${ADMIN_USER_PASSWORD}', roles:[{ role: 'userAdminAnyDatabase', db: 'admin' }, { role: 'clusterAdmin', db: 'admin' }, { role: 'readWriteAnyDatabase', db: 'admin' }, { role: 'dbAdminAnyDatabase', db: 'admin' } ]})\"\n\n}\n\n# Step 1\nconfigure_datadisks\n\n# Step 2\ntune_memory\ntune_system\n\n# Step 3\ninstall_mongodb\n\n# Step 4\nconfigure_mongodb\n\n# Step 5\nstart_mongodb\n\n# Step 6\nconfigure_db_users\n\n# Step 7\nconfigure_replicaset\n\n# Exit (proudly)\nexit 0\n", "num_lines": 363}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "\ncd /\nsudo mv /var/lib/waagent/Microsoft.Azure.Extensions.CustomScript-2.0.0/download/0/app.js /opt/app.js\n\n\nsudo DEBIAN_FRONTEND=noninteractive apt-get -y update\n\n\nsudo apt-get -y install nodejs\nsudo apt-get -y install npm\nsudo npm -y install express\nsudo npm -y install mongodb\n\n\n\n\n\n\n\n", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#Modify Sudoers file to not require tty for shell script execution on CentOS\n# sudo sed -i '/Defaults[[:space:]]\\+requiretty/s/^/#/' /etc/sudoers\n\n# Enable write access to the mongodb.repo and configure it for installation\n\n#sudo chmod 777 /etc/yum.repos.d/mongodb.repo\ntouch /etc/yum.repos.d/mongodb.repo\necho \"[mongodb-org-3.2]\" >> /etc/yum.repos.d/mongodb.repo\necho \"name=MongoDB Repository\" >> /etc/yum.repos.d/mongodb.repo\necho \"baseurl=http://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\" >> /etc/yum.repos.d/mongodb.repo\necho \"gpgcheck=1\" >> /etc/yum.repos.d/mongodb.repo\necho \"enabled=1\" >> /etc/yum.repos.d/mongodb.repo\necho \"gpgkey=https://www.mongodb.org/static/pgp/server-3.2.asc\" >> /etc/yum.repos.d/mongodb.repo\n\n# Install updates\nyum -y update\n\n# Install SELinux management tools and add rule for default port for mongod service\nyum install -y policycoreutils-python\nsemanage port -a -t mongod_port_t -p tcp 27017\n\n# Install Mongo DB and start service\nyum install -y mongodb-org\nservice mongod start\n", "num_lines": 26}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Configure mongodb.list file with the correct location\nsudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4\necho \"deb http://repo.mongodb.org/apt/ubuntu \"$(lsb_release -sc)\"/mongodb-org/4.0 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.0.list\n\n# Disable THP\nsudo echo never > /sys/kernel/mm/transparent_hugepage/enabled\nsudo echo never > /sys/kernel/mm/transparent_hugepage/defrag\nsudo grep -q -F 'transparent_hugepage=never' /etc/default/grub || echo 'transparent_hugepage=never' >> /etc/default/grub\n\n# Install updates\nsudo apt-get -y update\n\n# Modified tcp keepalive according to https://docs.mongodb.org/ecosystem/platforms/windows-azure/\nsudo bash -c \"sudo echo net.ipv4.tcp_keepalive_time = 120 >> /etc/sysctl.conf\"\n\n#Install Mongo DB\nsudo apt-get install -y mongodb-org\n\n# Uncomment this to bind to all ip addresses\n# sudo sed -i -e 's/bindIp: 127.0.0.1/bindIp: 0.0.0.0/g' /etc/mongod.conf\n# sudo service mongod restart\n", "num_lines": 22}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\nsecondaryNodes=$2\nmongoAdminUser=$3\nmongoAdminPasswd=$4\nstaticIp=$5\nzabbixServer=$6\n\ninstall_mongo3() {\n\n\t#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n}\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null 2>&1\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\n\ninstall_mongo3\ndisk_format\ninstall_zabbix\n\n\n#start mongod\nmongod --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/mongod.log --fork\n\nsleep 30\nps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep\nn=$(ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep |wc -l)\necho \"the number of mongod process is: $n\"\nif [[ $n -eq 1 ]];then\n    echo \"mongod started successfully\"\nelse\n    echo \"Error: The number of mongod processes is 2+ or mongod failed to start because of the db path issue!\"\nfi\n\n#create users\nmongo <<EOF\nuse admin\ndb.createUser({user:\"$mongoAdminUser\",pwd:\"$mongoAdminPasswd\",roles:[{role: \"userAdminAnyDatabase\", db: \"admin\" },{role: \"readWriteAnyDatabase\", db: \"admin\" },{role: \"root\", db: \"admin\" }]})\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"mongo user added succeefully.\"\nelse\n    echo \"mongo user added failed!\"\nfi\n\n#stop mongod\nsleep 15\necho \"the running mongo process id is below:\"\nps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep |awk '{print $2}'\nMongoPid=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep |awk '{print $2}'`\nkill -2 $MongoPid\n\n\n#set keyfile\necho \"vfr4CDE1\" > /etc/mongokeyfile\nchown mongod:mongod /etc/mongokeyfile\nchmod 600 /etc/mongokeyfile\nsed -i 's/^#security/security/' /etc/mongod.conf\nsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\nsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n\nsleep 15\nMongoPid1=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep |awk '{print $2}'`\nif [[ -z $MongoPid1 ]];then\n    echo \"shutdown mongod successfully\"\nelse\n    echo \"shutdown mongod failed!\"\n    kill $MongoPid1\n    sleep 15\nfi\n\n#restart mongod with auth and replica set\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n\n#initiate replica set\nfor((i=1;i<=3;i++))\n    do\n        sleep 15\n        n=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep  |wc -l`\n        if [[ $n -eq 1 ]];then\n            echo \"mongo replica set started successfully\"\n            break\n        else\n            mongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n            continue\n        fi\n    done\n\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" | grep -v grep  |wc -l`\nif [[ $n -ne 1 ]];then\n    echo \"mongo replica set tried to start 3 times but failed!\"\nfi\n\n\necho \"start initiating the replica set\"\npublicIp=`curl -s ip.cn|grep -Po '\\d+.\\d+.\\d+.\\d+'`\nif [[ -z $publicIp ]];then\n\tfinalIp=$staticIp\nelse\n\tfinalIp=$publicIp\nfi\n\necho \"the ip address is $finalIp\"\n\n\nmongo<<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\", \"$mongoAdminPasswd\")\nconfig ={_id:\"$replSetName\",members:[{_id:0,host:\"$finalIp:27017\"}]}\nrs.initiate(config)\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"replica set initiation succeeded.\"\nelse\n    echo \"replica set initiation failed!\"\nfi\n\n\n#add secondary nodes\nfor((i=1;i<=$secondaryNodes;i++))\n    do\n        let a=3+$i\n        mongo -u \"$mongoAdminUser\" -p \"$mongoAdminPasswd\" \"admin\" --eval \"printjson(rs.add('10.0.1.${a}:27017'))\"\n        if [[ $? -eq 0 ]];then\n            echo \"adding server 10.0.1.${a} successfully\"\n        else\n            echo \"adding server 10.0.1.${a} failed!\"\n        fi\n    done\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n\n\n", "num_lines": 257}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\nzabbixServer=$2\n\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\ninstall_mongo3\ndisk_format\ninstall_zabbix\n\n#start replica set\nmongod --dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork\n\n\n#check if mongod started or not\nsleep 15\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep|wc -l`\nif [[ $n -eq 1 ]];then\n    echo \"replica set started successfully\"\nelse\n    echo \"replica set started failed!\"\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 164}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmongoAdminUser=$1\nmongoAdminPasswd=$2\nzabbixServer=$3\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\ninstall_mongo3\ninstall_zabbix\n\n\n\n#start mongod\nmongod --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/mongod.log --fork\n\nsleep 30\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep | wc -l`\nif [[ $n -eq 1 ]];then\n    echo \"mongod started successfully\"\nelse\n    echo \"mongod started failed!\"\nfi\n\n#create users\nmongo <<EOF\nuse admin\ndb.createUser({user:\"$mongoAdminUser\",pwd:\"$mongoAdminPasswd\",roles:[{role: \"userAdminAnyDatabase\", db: \"admin\" },{role: \"readWriteAnyDatabase\", db: \"admin\" },{role: \"root\", db: \"admin\" }]})\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"mongo user added succeefully.\"\nelse\n    echo \"mongo user added failed!\"\nfi\n\n#stop mongod\nsleep 15\nMongoPid=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep |awk '{print $2}'`\nkill -2 $MongoPid\n\n\n\n#set keyfile\necho \"vfr4CDE1\" > /etc/mongokeyfile\nchown mongod:mongod /etc/mongokeyfile\nchmod 600 /etc/mongokeyfile\nsed -i 's/^#security/security/' /etc/mongod.conf\nsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\nsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n\nsleep 15\nMongoPid1=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\"|grep -v grep |awk '{print $2}'`\nif [[ -z $MongoPid1 ]];then\n    echo \"shutdown mongod successfully\"\nelse\n    echo \"shutdown mongod failed!\"\n    kill $MongoPid1\n    sleep 15\nfi\n\n#restart mongod with auth and config replica set\nmongod --configsvr --replSet crepset --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf\n\n\n\n#initiate config replica set\n\nfor((i=1;i<=3;i++))\ndo\n    sleep 15\n    n=`ps -ef |grep \"mongod --configsvr\"|grep -v grep |wc -l`\n    if [[ $n -eq 1 ]];then\n        echo \"mongo config replica set started successfully\"\n        break\n    else\n        mongod --configsvr --replSet crepset --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf\n        continue\n    fi\ndone\n\nn=`ps -ef |grep \"mongod --configsvr\"|grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\n    echo \"mongo config replica set tried to start 3 times but failed!\"\nfi\n\n\nmongo --port 27019 <<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\",\"$mongoAdminPasswd\")\nconfig={_id: \"crepset\", configsvr: true, members: [{ _id: 0, host: \"10.0.0.240:27019\" },{ _id: 1, host: \"10.0.0.241:27019\" },{ _id: 2, host: \"10.0.0.242:27019\" }]}\nrs.initiate(config)\nexit\nEOF\nif [[ $? -eq 0 ]];then\n    echo \"mongod config replica set initiated succeefully.\"\nelse\n    echo \"mongod config replica set initiated failed!\"\nfi\n\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --configsvr --replSet crepset --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 206}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nzabbixServer=$1\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\n\ninstall_mongo3\ninstall_zabbix\n\n#start config replica set\nmongod --configsvr --replSet crepset --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf\n\n\n\n\n#check if mongod started or not\nsleep 15\nn=`ps -ef |grep \"mongod --configsvr\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\n    echo \"mongod config replica set started successfully\"\nelse\n    echo \"mongod config replica set started failed!\"\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --configsvr --replSet crepset --port 27019 --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/config.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 138}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\nstaticIP=$2\nmongoAdminUser=$3\nmongoAdminPasswd=$4\nzabbixServer=$5\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\n\ninstall_mongo3\ndisk_format\ninstall_zabbix\n\n\n#start mongod\nmongod --dbpath /var/lib/mongo/ --logpath /var/log/mongodb/mongod.log --fork\n\nsleep 30\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\n\techo \"mongod started successfully\"\nelse\n\techo \"mongod started failed!\"\nfi\n\n\n\n#create users\nmongo <<EOF\nuse admin\ndb.createUser({user:\"$mongoAdminUser\",pwd:\"$mongoAdminPasswd\",roles:[{role: \"userAdminAnyDatabase\", db: \"admin\" },{role: \"readWriteAnyDatabase\", db: \"admin\" },{role: \"root\", db: \"admin\" }]})\nexit\nEOF\nif [[ $? -eq 0 ]];then\n\techo \"mongo user added succeefully.\"\nelse\n\techo \"mongo user added failed!\"\nfi\n\n#stop mongod\nsleep 15\nMongoPid=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |awk '{print $2}'`\nkill -2 $MongoPid\n\n\n\n#set keyfile\necho \"vfr4CDE1\" > /etc/mongokeyfile\nchown mongod:mongod /etc/mongokeyfile\nchmod 600 /etc/mongokeyfile\nsed -i 's/^#security/security/' /etc/mongod.conf\nsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\nsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n\nsleep 15\nMongoPid1=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |awk '{print $2}'`\nif [[ -z $MongoPid1 ]];then\n\techo \"shutdown mongod successfully\"\nelse\n\techo \"shutdown mongod failed!\"\n\tkill $MongoPid1\n\tsleep 15\nfi\n\n#restart mongod with auth and replica set\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n\n\n\n\n\n#initiate replica set\nfor((i=1;i<=3;i++))\ndo\n\tsleep 15\n\tn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\n\tif [[ $n -eq 1 ]];then\n\t\techo \"mongo replica set started successfully\"\n\t\tbreak\n\telse\n\t\tmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n\t\tcontinue\n\tfi\ndone\n\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\n\techo \"mongo replica set tried to start 3 times but failed!\"\nfi\n\n\n\nmongo<<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\", \"$mongoAdminPasswd\")\nconfig ={_id:\"$replSetName\",members:[{_id:0,host:\"$staticIP:27017\"}]}\nrs.initiate(config)\nexit\nEOF\nif [[ $? -eq 0 ]];then\n\techo \"replica set initiation succeeded.\"\nelse\n\techo \"replica set initiation failed!\"\nfi\n\n\n#get replica secondary nodes ips\nnum=`echo $staticIP |awk -F\".\" '{print $NF}'`\nif [[ $num -eq 100 ]];then\n\tlet g=$num-97\nelif [[ $num -eq 110 ]];then\n\tlet g=$num-105\nfi\n\n#add secondary nodes\nfor((i=1;i<=2;i++))\ndo\n\tlet a=$i+$g\n\tmongo -u \"$mongoAdminUser\" -p \"$mongoAdminPasswd\" \"admin\" --eval \"printjson(rs.add('10.0.0.${a}:27017'))\"\n\tif [[ $? -eq 0 ]];then\n\t\techo \"adding server 10.0.0.${a} successfully\"\n\telse\n\t\techo \"adding server 10.0.0.${a} failed!\"\n\tfi\ndone\n\n\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n\n\n", "num_lines": 260}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nreplSetName=$1\nzabbixServer=$2\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mongo -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mongo/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mongo\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\n\ninstall_mongo3\ndisk_format\ninstall_zabbix\n\n\n#start replica set\nmongod --dbpath /var/lib/mongo/ --config /etc/mongod.conf --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork\n\n\n\n\n#check if mongod started or not\nsleep 15\nn=`ps -ef |grep \"mongod --dbpath /var/lib/mongo/\" |grep -v grep |wc -l`\nif [[ $n -eq 1 ]];then\necho \"replica set started successfully\"\nelse\necho \"replica set started failed!\"\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongod --dbpath /var/lib/mongo/ --replSet $replSetName --logpath /var/log/mongodb/mongod.log --fork --config /etc/mongod.conf\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 163}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmongoAdminUser=$1\nmongoAdminPasswd=$2\nzabbixServer=$3\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\n\ninstall_mongo3\ninstall_zabbix\n\n\n#start router server\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n\n\n#check router server starts or not\nfor((i=1;i<=3;i++))\ndo\n\tsleep 30\n\tn=`ps -ef |grep \"mongos --configdb\" |grep -v grep |wc -l`\n\tif [[ $n -eq 1 ]];then\n\t\techo \"mongos started successfully\"\n\t\tbreak\n\telse\n\t\tmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n\t\tcontinue\n\tfi\ndone\n\nn=`ps -ef |grep \"mongos --configdb\" |grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\necho \"mongos tried to start 3 times but failed!\"\nfi\n\n#add shard\nmongo --port 27017 <<EOF\nuse admin\ndb.auth(\"$mongoAdminUser\",\"$mongoAdminPasswd\")\nsh.addShard(\"repset1/10.0.0.100:27017\")\nsh.addShard(\"repset2/10.0.0.110:27017\")\ndb.runCommand( { listshards : 1 } )\nexit\nEOF\nif [[ $? -eq 0 ]];then\necho \"mongo shard added succeefully.\"\nelse\necho \"mongo shard added failed!\"\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 163}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nzabbixServer=$1\n\ninstall_mongo3() {\n#create repo\ncat > /etc/yum.repos.d/mongodb-org-3.2.repo <<EOF\n[mongodb-org-3.2]\nname=MongoDB Repository\nbaseurl=https://repo.mongodb.org/yum/redhat/\\$releasever/mongodb-org/3.2/x86_64/\ngpgcheck=0\nenabled=1\nEOF\n\n\t#install\n\tyum install -y mongodb-org\n\n\t#ignore update\n\tsed -i '$a exclude=mongodb-org,mongodb-org-server,mongodb-org-shell,mongodb-org-mongos,mongodb-org-tools' /etc/yum.conf\n\n\t#disable selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n\t#kernel settings\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/enabled ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/enabled\n\tfi\n\tif [[ -f /sys/kernel/mm/transparent_hugepage/defrag ]];then\n\t\techo never > /sys/kernel/mm/transparent_hugepage/defrag\n\tfi\n\n\t#configure\n\tsed -i 's/\\(bindIp\\)/#\\1/' /etc/mongod.conf\n\n\t#set keyfile\n\techo \"vfr4CDE1\" > /etc/mongokeyfile\n\tchown mongod:mongod /etc/mongokeyfile\n\tchmod 600 /etc/mongokeyfile\n\tsed -i 's/^#security/security/' /etc/mongod.conf\n\tsed -i '/^security/akeyFile: /etc/mongokeyfile' /etc/mongod.conf\n\tsed -i 's/^keyFile/  keyFile/' /etc/mongod.conf\n}\n\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz > /dev/null\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n}\n\ninstall_mongo3\ninstall_zabbix\n\n\n#start router server\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n\n\n#check router server starts or not\nfor((i=1;i<=3;i++))\ndo\n\tsleep 30\n\tn=`ps -ef |grep \"mongos --configdb\" | grep -v grep |wc -l`\n\tif [[ $n -eq 1 ]];then\n\t\techo \"mongos started successfully\"\n\t\tbreak\n\telse\n\t\tmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n\t\tcontinue\n\tfi\ndone\n\nn=`ps -ef |grep \"mongos --configdb\" | grep -v grep |wc -l`\nif [[ $n -ne 1 ]];then\necho \"mongos tried to start 3 times but failed!\"\nfi\n\n\n#set mongod auto start\ncat > /etc/init.d/mongod1 <<EOF\n#!/bin/bash\n#chkconfig: 35 84 15\n#description: mongod auto start\n. /etc/init.d/functions\n\nName=mongod1\nstart() {\nif [[ ! -d /var/run/mongodb ]];then\nmkdir /var/run/mongodb\nchown -R mongod:mongod /var/run/mongodb\nfi\nmongos --configdb crepset/10.0.0.240:27019,10.0.0.241:27019,10.0.0.242:27019 --port 27017 --logpath /var/log/mongodb/mongos.log --fork --keyFile /etc/mongokeyfile\n}\nstop() {\npkill mongod\n}\nrestart() {\nstop\nsleep 15\nstart\n}\n\ncase \"\\$1\" in\n    start)\n\tstart;;\n\tstop)\n\tstop;;\n\trestart)\n\trestart;;\n\tstatus)\n\tstatus \\$Name;;\n\t*)\n\techo \"Usage: service mongod1 start|stop|restart|status\"\nesac\nEOF\nchmod +x /etc/init.d/mongod1\nchkconfig mongod1 on\n", "num_lines": 147}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Common functions definitions\n\nfunction check_fileServerType_param\n{\n    local fileServerType=$1\n    if [ \"$fileServerType\" != \"gluster\" -a \"$fileServerType\" != \"azurefiles\" -a \"$fileServerType\" != \"nfs\" ]; then\n        echo \"Invalid fileServerType ($fileServerType) given. Only 'gluster', 'azurefiles' or 'nfs' are allowed. Exiting\"\n        exit 1\n    fi\n}\n\nfunction create_azure_files_moodle_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n    local logFilePath=$3\n\n    az storage share create \\\n        --name moodle \\\n        --account-name $storageAccountName \\\n        --account-key $storageAccountKey \\\n        --fail-on-exist >> $logFilePath\n}\n\nfunction setup_and_mount_azure_files_moodle_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n\n    cat <<EOF > /etc/moodle_azure_files.credential\nusername=$storageAccountName\npassword=$storageAccountKey\nEOF\n    chmod 600 /etc/moodle_azure_files.credential\n\n    grep \"^//$storageAccountName.file.core.windows.net/moodle\\s\\s*/moodle\\s\\s*cifs\" /etc/fstab\n    if [ $? != \"0\" ]; then\n        echo -e \"\\n//$storageAccountName.file.core.windows.net/moodle   /moodle cifs    credentials=/etc/moodle_azure_files.credential,uid=www-data,gid=www-data,nofail,vers=3.0,dir_mode=0770,file_mode=0660,serverino,mfsymlinks\" >> /etc/fstab\n    fi\n    mkdir -p /moodle\n    mount /moodle\n}\n\n# Functions for making NFS share available\n# TODO refactor these functions with the same ones in install_gluster.sh\nfunction scan_for_new_disks\n{\n    local BLACKLIST=${1}    # E.g., /dev/sda|/dev/sdb\n    declare -a RET\n    local DEVS=$(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\")\n    for DEV in ${DEVS};\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nfunction create_raid0_ubuntu {\n    local RAIDDISK=${1}       # E.g., /dev/md1\n    local RAIDCHUNKSIZE=${2}  # E.g., 128\n    local DISKCOUNT=${3}      # E.g., 4\n    shift\n    shift\n    shift\n    local DISKS=\"$@\"\n\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        sudo apt-get -y -q install mdadm\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create $RAIDDISK --name=data --level=0 --chunk=$RAIDCHUNKSIZE --raid-devices=$DISKCOUNT $DISKS\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm/mdadm.conf\n}\n\nfunction do_partition {\n    # This function creates one (1) primary partition on the\n    # disk device, using all available space\n    local DISK=${1}   # E.g., /dev/sdc\n\n    echo \"Partitioning disk $DISK\"\n    echo -ne \"n\\np\\n1\\n\\n\\nw\\n\" | fdisk \"${DISK}\"\n    #> /dev/null 2>&1\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from fdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${DISK}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\nfunction add_local_filesystem_to_fstab {\n    local UUID=${1}\n    local MOUNTPOINT=${2}   # E.g., /moodle\n\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"\\nUUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nfunction create_filesystem_with_raid {\n    local MOUNTPOINT=${1}     # E.g., /moodle\n    local RAIDDISK=${2}       # E.g., /dev/md1\n    local RAIDPARTITION=${3}  # E.g., /dev/md1p1\n\n    mkdir -p $MOUNTPOINT\n\n    local DISKS=$(scan_for_new_disks \"/dev/sda|/dev/sdb\")\n    echo \"Disks are ${DISKS}\"\n    declare -i DISKCOUNT\n    local DISKCOUNT=$(echo \"$DISKS\" | wc -w)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT = \"0\" ];\n    then\n        echo \"No new (unpartitioned) disks available... Returning...\"\n        return\n    elif [ $DISKCOUNT -gt 1 ];\n    then\n        create_raid0_ubuntu /dev/md1 128 $DISKCOUNT $DISKS\n        do_partition ${RAIDDISK}\n        local PARTITION=\"${RAIDPARTITION}\"\n    else\n        do_partition ${DISKS}\n        local PARTITION=$(fdisk -l ${DISKS}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 ${PARTITION}\n    mkdir -p \"${MOUNTPOINT}\"\n    local UUID=$(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3}'|tr -d \"\\\"\")\n    add_local_filesystem_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nfunction configure_nfs_server_and_export {\n    local MOUNTPOINT=${1}     # E.g., /moodle\n\n    echo \"Installing nfs server...\"\n    apt install -y nfs-kernel-server\n\n    echo \"Exporting ${MOUNTPOINT}...\"\n    grep \"^${MOUNTPOINT}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${MOUNTPOINT} is already exported. Returning...\"\n    else\n        echo -e \"\\n${MOUNTPOINT}   *(rw,sync,no_root_squash)\" >> /etc/exports\n        systemctl restart nfs-kernel-server.service\n    fi\n}\n\nfunction configure_nfs_client_and_mount {\n    local NFS_SERVER=${1}     # E.g., jumpbox-vm-ab12cd\n    local NFS_DIR=${2}        # E.g., /moodle\n    local MOUNTPOINT=${3}     # E.g., /moodle\n\n    apt install -y nfs-common\n    mkdir -p ${MOUNTPOINT}\n\n    grep \"^${NFS_SERVER}:${NFS_DIR}\" /etc/fstab > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${NFS_SERVER}:${NFS_DIR} already in /etc/fstab... skipping to add\"\n    else\n        echo -e \"\\n${NFS_SERVER}:${NFS_DIR}    ${MOUNTPOINT}    nfs    auto    0    0\" >> /etc/fstab\n    fi\n    mount ${MOUNTPOINT}\n}\n\n# Long Redis cache Moodle config file generation code moved here\nfunction create_redis_configuration_in_moodledata_muc_config_php\n{\n    # create redis configuration in /moodle/moodledata/muc/config.php\n    cat <<EOF > /moodle/moodledata/muc/config.php\n<?php defined('MOODLE_INTERNAL') || die();\n \\$configuration = array (\n  'siteidentifier' => '7a142be09ea65699e4a6f6ef91c0773c',\n  'stores' =>\n  array (\n    'default_application' =>\n    array (\n      'name' => 'default_application',\n      'plugin' => 'file',\n      'configuration' =>\n      array (\n      ),\n      'features' => 30,\n      'modes' => 3,\n      'default' => true,\n      'class' => 'cachestore_file',\n      'lock' => 'cachelock_file_default',\n    ),\n    'default_session' =>\n    array (\n      'name' => 'default_session',\n      'plugin' => 'session',\n      'configuration' =>\n      array (\n      ),\n      'features' => 14,\n      'modes' => 2,\n      'default' => true,\n      'class' => 'cachestore_session',\n      'lock' => 'cachelock_file_default',\n    ),\n    'default_request' =>\n    array (\n      'name' => 'default_request',\n      'plugin' => 'static',\n      'configuration' =>\n      array (\n      ),\n      'features' => 31,\n      'modes' => 4,\n      'default' => true,\n      'class' => 'cachestore_static',\n      'lock' => 'cachelock_file_default',\n    ),\n    'redis' =>\n    array (\n      'name' => 'redis',\n      'plugin' => 'redis',\n      'configuration' =>\n      array (\n        'server' => '$redisDns',\n        'prefix' => 'moodle_prod',\n        'password' => '$redisAuth',\n        'serializer' => '1',\n      ),\n      'features' => 26,\n      'modes' => 3,\n      'mappingsonly' => false,\n      'class' => 'cachestore_redis',\n      'default' => false,\n      'lock' => 'cachelock_file_default',\n    ),\n    'local_file' =>\n    array (\n      'name' => 'local_file',\n      'plugin' => 'file',\n      'configuration' =>\n      array (\n        'path' => '/tmp/muc/moodle_prod',\n        'autocreate' => 1,\n      ),\n      'features' => 30,\n      'modes' => 3,\n      'mappingsonly' => false,\n      'class' => 'cachestore_file',\n      'default' => false,\n      'lock' => 'cachelock_file_default',\n    ),\n  ),\n  'modemappings' =>\n  array (\n    0 =>\n    array (\n      'store' => 'redis',\n      'mode' => 1,\n      'sort' => 0,\n    ),\n    1 =>\n    array (\n      'store' => 'default_session',\n      'mode' => 2,\n      'sort' => 0,\n    ),\n    2 =>\n    array (\n      'store' => 'default_request',\n      'mode' => 4,\n      'sort' => 0,\n    ),\n  ),\n  'definitions' =>\n  array (\n    'core/string' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'string',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/langmenu' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'langmenu',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/databasemeta' =>\n    array (\n      'mode' => 1,\n      'requireidentifiers' =>\n      array (\n        0 => 'dbfamily',\n      ),\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 15,\n      'component' => 'core',\n      'area' => 'databasemeta',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/eventinvalidation' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'requiredataguarantee' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'eventinvalidation',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/questiondata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'requiredataguarantee' => false,\n      'datasource' => 'question_finder',\n      'datasourcefile' => 'question/engine/bank.php',\n      'component' => 'core',\n      'area' => 'questiondata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/htmlpurifier' =>\n    array (\n      'mode' => 1,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'htmlpurifier',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/config' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'config',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/groupdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'groupdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/calendar_subscriptions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'calendar_subscriptions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/capabilities' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'capabilities',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/yuimodules' =>\n    array (\n      'mode' => 1,\n      'component' => 'core',\n      'area' => 'yuimodules',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/observers' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'observers',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/plugin_manager' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'plugin_manager',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecattree' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n      ),\n      'component' => 'core',\n      'area' => 'coursecattree',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecat' =>\n    array (\n      'mode' => 2,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n        1 => 'changesincourse',\n      ),\n      'ttl' => 600,\n      'component' => 'core',\n      'area' => 'coursecat',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/coursecatrecords' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n      ),\n      'component' => 'core',\n      'area' => 'coursecatrecords',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/coursecontacts' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'simplekeys' => true,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'coursecontacts',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/repositories' =>\n    array (\n      'mode' => 4,\n      'component' => 'core',\n      'area' => 'repositories',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/externalbadges' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'externalbadges',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursemodinfo' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'coursemodinfo',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/userselections' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'userselections',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/completion' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'ttl' => 3600,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'completion',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecompletion' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'ttl' => 3600,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'core',\n      'area' => 'coursecompletion',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/navigation_expandcourse' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'navigation_expandcourse',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/suspended_userids' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'suspended_userids',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/roledefs' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'core',\n      'area' => 'roledefs',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/plugin_functions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 5,\n      'component' => 'core',\n      'area' => 'plugin_functions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/tags' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'tags',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/grade_categories' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesingradecategories',\n      ),\n      'component' => 'core',\n      'area' => 'grade_categories',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/temp_tables' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'temp_tables',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/tagindexbuilder' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simplevalues' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'ttl' => 900,\n      'invalidationevents' =>\n      array (\n        0 => 'resettagindexbuilder',\n      ),\n      'component' => 'core',\n      'area' => 'tagindexbuilder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/contextwithinsights' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'core',\n      'area' => 'contextwithinsights',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/message_processors_enabled' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 3,\n      'component' => 'core',\n      'area' => 'message_processors_enabled',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/message_time_last_message_between_users' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simplevalues' => true,\n      'datasource' => '\\\\core_message\\\\time_last_message_between_users',\n      'component' => 'core',\n      'area' => 'message_time_last_message_between_users',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/fontawesomeiconmapping' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'core',\n      'area' => 'fontawesomeiconmapping',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/postprocessedcss' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => false,\n      'component' => 'core',\n      'area' => 'postprocessedcss',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/user_group_groupings' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'user_group_groupings',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'availability_grade/scores' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'ttl' => 3600,\n      'component' => 'availability_grade',\n      'area' => 'scores',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'availability_grade/items' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'ttl' => 3600,\n      'component' => 'availability_grade',\n      'area' => 'items',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'mod_glossary/concepts' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => false,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'mod_glossary',\n      'area' => 'concepts',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_googledocs/folder' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => false,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'canuselocalstore' => true,\n      'component' => 'repository_googledocs',\n      'area' => 'folder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_onedrive/folder' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => false,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'canuselocalstore' => true,\n      'component' => 'repository_onedrive',\n      'area' => 'folder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_skydrive/foldername' =>\n    array (\n      'mode' => 2,\n      'component' => 'repository_skydrive',\n      'area' => 'foldername',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'tool_mobile/plugininfo' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_mobile',\n      'area' => 'plugininfo',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_monitor/eventsubscriptions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'component' => 'tool_monitor',\n      'area' => 'eventsubscriptions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_uploadcourse/helper' =>\n    array (\n      'mode' => 4,\n      'component' => 'tool_uploadcourse',\n      'area' => 'helper',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'tool_usertours/tourdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_usertours',\n      'area' => 'tourdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_usertours/stepdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_usertours',\n      'area' => 'stepdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n  ),\n  'definitionmappings' =>\n  array (\n    0 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/coursemodinfo',\n      'sort' => 1,\n    ),\n    1 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/groupdata',\n      'sort' => 1,\n    ),\n    2 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/roledefs',\n      'sort' => 1,\n    ),\n    3 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_usertours/tourdata',\n      'sort' => 1,\n    ),\n    4 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'repository_onedrive/folder',\n      'sort' => 1,\n    ),\n    5 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/message_processors_enabled',\n      'sort' => 1,\n    ),\n    6 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecontacts',\n      'sort' => 1,\n    ),\n    7 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'repository_googledocs/folder',\n      'sort' => 1,\n    ),\n    8 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/questiondata',\n      'sort' => 1,\n    ),\n    9 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecat',\n      'sort' => 1,\n    ),\n    10 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/databasemeta',\n      'sort' => 1,\n    ),\n    11 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/eventinvalidation',\n      'sort' => 1,\n    ),\n    12 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecattree',\n      'sort' => 1,\n    ),\n    13 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecompletion',\n      'sort' => 1,\n    ),\n    14 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/user_group_groupings',\n      'sort' => 1,\n    ),\n    15 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/capabilities',\n      'sort' => 1,\n    ),\n    16 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/yuimodules',\n      'sort' => 1,\n    ),\n    17 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/observers',\n      'sort' => 1,\n    ),\n    18 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'mod_glossary/concepts',\n      'sort' => 1,\n    ),\n    19 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/fontawesomeiconmapping',\n      'sort' => 1,\n    ),\n    20 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/config',\n      'sort' => 1,\n    ),\n    21 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_mobile/plugininfo',\n      'sort' => 1,\n    ),\n    22 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/plugin_functions',\n      'sort' => 1,\n    ),\n    23 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/postprocessedcss',\n      'sort' => 1,\n    ),\n    24 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/plugin_manager',\n      'sort' => 1,\n    ),\n    25 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_usertours/stepdata',\n      'sort' => 1,\n    ),\n    26 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'availability_grade/items',\n      'sort' => 1,\n    ),\n    27 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/string',\n      'sort' => 1,\n    ),\n    28 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/externalbadges',\n      'sort' => 1,\n    ),\n    29 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/langmenu',\n      'sort' => 1,\n    ),\n    30 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/htmlpurifier',\n      'sort' => 1,\n    ),\n    31 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/completion',\n      'sort' => 1,\n    ),\n    32 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/calendar_subscriptions',\n      'sort' => 1,\n    ),\n    33 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/contextwithinsights',\n      'sort' => 1,\n    ),\n    34 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_monitor/eventsubscriptions',\n      'sort' => 1,\n    ),\n    35 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/message_time_last_message_between_users',\n      'sort' => 1,\n    ),\n    36 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'availability_grade/scores',\n      'sort' => 1,\n    ),\n  ),\n  'locks' =>\n  array (\n    'cachelock_file_default' =>\n    array (\n      'name' => 'cachelock_file_default',\n      'type' => 'cachelock_file',\n      'dir' => 'filelocks',\n      'default' => true,\n    ),\n  ),\n);\nEOF\n}\n", "num_lines": 1132}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Custom Script for Linux\n\n#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nesClusterName=$1\nelasticvm1ip=$2\nelasticvm2ip=$3\nelasticvm3ip=$4\n\necho $esClusterName    >> /tmp/vars.txt\necho $elasticvm1ip     >> /tmp/vars.txt\necho $elasticvm2ip     >> /tmp/vars.txt\necho $elasticvm3ip     >> /tmp/vars.txt\n\n{\n\n  # make sure the system does automatic update\n  sudo apt-get -y update\n  sudo apt-get -y install unattended-upgrades\n\n  # configure elastic search repository & install elastic search\n  wget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -\n  echo \"deb https://artifacts.elastic.co/packages/5.x/apt stable main\" | sudo tee -a /etc/apt/sources.list.d/elastic-5.x.list\n  sudo apt-get -y update\n  sudo apt-get -y install elasticsearch=5.5.0\n\n  # install the required packages\n  sudo apt-get install -y openjdk-8-jre openjdk-8-jdk default-jre default-jdk\n\n  # Configure elasticsearch\n  cat <<EOF > /etc/elasticsearch/elasticsearch.yml\n# ======================== Elasticsearch Configuration =========================\n#\n# NOTE: Elasticsearch comes with reasonable defaults for most settings.\n#       Before you set out to tweak and tune the configuration, make sure you\n#       understand what are you trying to accomplish and the consequences.\n#\n# The primary way of configuring a node is via this file. This template lists\n# the most important settings you may want to configure for a production cluster.\n#\n# Please consult the documentation for further information on configuration options:\n# https://www.elastic.co/guide/en/elasticsearch/reference/index.html\n#\n# ---------------------------------- Cluster -----------------------------------\n#\n# Use a descriptive name for your cluster:\n#\ncluster.name: ${esClusterName}\n#\n# ------------------------------------ Node ------------------------------------\n#\n# Use a descriptive name for the node:\n#\nnode.name: \\${HOSTNAME}\n#\n# Add custom attributes to the node:\n#\n#node.attr.rack: r1\n#\n# ----------------------------------- Paths ------------------------------------\n#\n# Path to directory where to store the data (separate multiple locations by comma):\n#\n#path.data: /path/to/data\n#\n# Path to log files:\n#\n#path.logs: /path/to/logs\n#\n# ----------------------------------- Memory -----------------------------------\n#\n# Lock the memory on startup:\n#\n#bootstrap.memory_lock: true\n#\n# Make sure that the heap size is set to about half the memory available\n# on the system and that the owner of the process is allowed to use this\n# limit.\n#\n# Elasticsearch performs poorly when the system is swapping the memory.\n#\n# ---------------------------------- Network -----------------------------------\n#\n# Set the bind address to a specific IP (IPv4 or IPv6):\n#\nnetwork.host: [_eth0_, _local_]\n#\n# Set a custom port for HTTP:\n#\n#http.port: 9200\n#\n# For more information, consult the network module documentation.\n#\n# --------------------------------- Discovery ----------------------------------\n#\n# Pass an initial list of hosts to perform discovery when new node is started:\n# The default list of hosts is [\"127.0.0.1\", \"[::1]\"]\n#\ndiscovery.zen.ping.unicast.hosts: [\"$elasticvm1ip\", \"$elasticvm2ip\", \"$elasticvm3ip\"]\n#\n# Prevent the \"split brain\" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):\n#\ndiscovery.zen.minimum_master_nodes: 3\n#\n# For more information, consult the zen discovery module documentation.\n#\n# ---------------------------------- Gateway -----------------------------------\n#\n# Block initial recovery after a full cluster restart until N nodes are started:\n#\n#gateway.recover_after_nodes: 3\n#\n# For more information, consult the gateway module documentation.\n#\n# ---------------------------------- Various -----------------------------------\n#\n# Require explicit names when deleting indices:\n#\n#action.destructive_requires_name: true\nEOF\n\n  service elasticsearch restart\n\n}  > /tmp/setup.log\n", "num_lines": 145}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script built for Ubuntu Server 16.04 LTS\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of powershell script or runbook or Azure Resource Manager CRP template.\n\nAZUREVMOFFSET=4\n\nNODENAME=$(hostname)\nPEERNODEPREFIX=${1}\nPEERNODEIPPREFIX=${2}\nVOLUMENAME=${3}\nNODEINDEX=${4}\nNODECOUNT=${5}\n\necho $NODENAME          >> /tmp/vars.txt\necho $PEERNODEPREFIX    >> /tmp/vars.txt\necho $PEERNODEIPPREFIX  >> /tmp/vars.txt\necho $VOLUMENAME        >> /tmp/vars.txt\necho $NODEINDEX         >> /tmp/vars.txt\necho $NODECOUNT         >> /tmp/vars.txt\n\n\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=128\n\nRAIDDISK=\"/dev/md1\"\nRAIDPARTITION=\"/dev/md1p1\"\n\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\n# make sure the system does automatic update\nsudo apt-get -y update\nsudo apt-get -y install unattended-upgrades\n\n{\n        check_os() {\n            grep ubuntu /proc/version > /dev/null 2>&1\n            isubuntu=${?}\n        }\n\n        scan_for_new_disks() {\n            # Looks for unpartitioned disks\n            declare -a RET\n            DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n            for DEV in \"${DEVS[@]}\";\n            do\n                # Check each device if there is a \"1\" partition.  If not,\n                # \"assume\" it is not partitioned.\n                if [ ! -b ${DEV}1 ];\n                then\n                    RET+=\"${DEV} \"\n                fi\n            done\n            echo \"${RET}\"\n        }\n\n        get_disk_count() {\n            DISKCOUNT=0\n            for DISK in \"${DISKS[@]}\";\n            do\n                DISKCOUNT+=1\n            done;\n            echo \"$DISKCOUNT\"\n        }\n\n        create_raid0_ubuntu() {\n            dpkg -s mdadm\n            if [ ${?} -eq 1 ];\n            then\n                echo \"installing mdadm\"\n                sudo apt-get -y -q install mdadm\n            fi\n            echo \"Creating raid0\"\n            udevadm control --stop-exec-queue\n            echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n            udevadm control --start-exec-queue\n            mdadm --detail --verbose --scan > /etc/mdadm.conf\n        }\n\n\n        do_partition() {\n        # This function creates one (1) primary partition on the\n        # disk, using all available space\n            DISK=${1}\n            echo \"Partitioning disk $DISK\"\n            echo -ne \"n\\np\\n1\\n\\n\\nw\\n\" | fdisk \"${DISK}\"\n        #> /dev/null 2>&1\n\n        #\n        # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n        # from fdisk and not from echo\n        if [ ${PIPESTATUS[1]} -ne 0 ];\n        then\n            echo \"An error occurred partitioning ${DISK}\" >&2\n            echo \"I cannot continue\" >&2\n            exit 2\n        fi\n        }\n\n        add_to_fstab() {\n            UUID=${1}\n            MOUNTPOINT=${2}\n            grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n            if [ ${?} -eq 0 ];\n            then\n                echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n            else\n                LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n                echo -e \"${LINE}\" >> /etc/fstab\n            fi\n        }\n\n        configure_disks() {\n            ls \"${MOUNTPOINT}\"\n            if [ ${?} -eq 0 ]\n            then\n                return\n            fi\n            DISKS=($(scan_for_new_disks))\n            echo \"Disks are ${DISKS[@]}\"\n            declare -i DISKCOUNT\n            DISKCOUNT=$(get_disk_count)\n            echo \"Disk count is $DISKCOUNT\"\n            if [ $DISKCOUNT -gt 1 ];\n            then\n                create_raid0_ubuntu\n                do_partition ${RAIDDISK}\n                PARTITION=\"${RAIDPARTITION}\"\n            else\n                DISK=\"${DISKS[0]}\"\n                do_partition ${DISK}\n                PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n            fi\n\n            echo \"Creating filesystem on ${PARTITION}.\"\n            mkfs -t ext4 ${PARTITION}\n            mkdir \"${MOUNTPOINT}\"\n            read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n            add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n            echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n            mount \"${MOUNTPOINT}\"\n        }\n\n        open_ports() {\n            index=0\n            while [ $index -lt $NODECOUNT ]; do\n\t\t\t    echo \"Node ${index}\"\n\t\t\t\tthisNode=\"${PEERNODEIPPREFIX}.$(($index+$AZUREVMOFFSET))\"\n\t\t\t    echo \"Node ${thisNode}\"\n\n                if [ $index -ne $NODEINDEX ]; then\n\t\t\t\t    echo \"Node ${thisNode} is a peer\"\n                    iptables -I INPUT -p all -s \"${thisNode}\" -j ACCEPT\n                    echo \"${thisNode}    ${thisNode}\" >> /etc/hosts\n                else\n\t\t\t\t    echo \"Node ${thisNode} is me\"\n                    echo \"127.0.0.1    ${thisNode}\" >> /etc/hosts\n                fi\n                let index++\n            done\n            iptables-save\n        }\n\n        disable_apparmor_ubuntu() {\n            /etc/init.d/apparmor teardown\n            update-rc.d -f apparmor remove\n        }\n\n        configure_network() {\n            open_ports\n            disable_apparmor_ubuntu\n        }\n\n        install_glusterfs_ubuntu() {\n            dpkg -l | grep glusterfs\n            if [ ${?} -eq 0 ];\n            then\n                return\n            fi\n\n            if [ ! -e /etc/apt/sources.list.d/gluster* ];\n            then\n                echo \"adding gluster ppa\"\n                apt-get  -y install python-software-properties\n                apt-add-repository -y ppa:gluster/glusterfs-3.8\n                apt-get -y update\n            fi\n\n            echo \"installing gluster\"\n            apt-get -y install glusterfs-server\n\n            return\n        }\n\n        configure_gluster() {\n            echo \"gluster step1\"\n\n            if [ $isubuntu -eq 0 ];\n            then\n                /etc/init.d/glusterfs-server status\n                if [ ${?} -ne 0 ];\n                then\n                    install_glusterfs_ubuntu\n                fi\n                /etc/init.d/glusterfs-server start\n            fi\n\n\t\t\techo \"gluster step2\"\n            GLUSTERDIR=\"${MOUNTPOINT}/brick\"\n            ls \"${GLUSTERDIR}\"\n\n            if [ ${?} -ne 0 ];\n            then\n                mkdir \"${GLUSTERDIR}\"\n            fi\n\n            if [ $NODEINDEX -lt $(($NODECOUNT-1)) ];\n            then\n                return\n            fi\n\n            echo \"gluster step3\"\n            allNodes=\"${NODENAME}:${GLUSTERDIR}\"\n\t\t\techo $allNodes\n            retry=10\n            failed=1\n\n            while [ $retry -gt 0 ] && [ $failed -gt 0 ]; do\n                failed=0\n                index=0\n                echo retrying $retry\n                while [ $index -lt $(($NODECOUNT-1)) ]; do\n\t\t\t\t\tglustervm=${PEERNODEPREFIX}${index}\n\t\t\t\t\techo $glustervm\n\n                    ping -c 3 $glustervm\n                    gluster peer probe $glustervm\n                    if [ ${?} -ne 0 ];\n                    then\n                        failed=1\n                        echo \"gluster peer probe $glustervm failed\"\n                    fi\n\n                    gluster peer status\n                    gluster peer status | grep $glustervm\n\n\t\t\t\t\tif [ ${?} -ne 0 ];\n                    then\n                        failed=1\n                        echo \"gluster peer status $glustervm failed\"\n                    fi\n\n\t\t\t\t\tif [ $retry -eq 10 ]; then\n                        allNodes=\"${allNodes} $glustervm:${GLUSTERDIR}\"\n                    fi\n                    let index++\n                done\n                sleep 30\n                let retry--\n            done\n\n            echo \"gluster step4\"\n\t\t\techo $allnodes\n            sleep 60\n            gluster volume create ${VOLUMENAME} rep 2 transport tcp ${allNodes}\n            gluster volume info\n            gluster volume start ${VOLUMENAME}\n            echo \"gluster complete\"\n        }\n\n        # \"main routine\"\n        check_os\n        configure_network\n        configure_disks\n        configure_gluster\n\n}  > /tmp/gluster-setup.log\n", "num_lines": 284}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n#parameters\n{\n    moodleVersion=${1}\n    glusterNode=${2}\n    glusterVolume=${3}\n    siteFQDN=${4}\n    dbIP=${5}\n    moodledbname=${6}\n    moodledbuser=${7}\n    moodledbpass=${8}\n    adminpass=${9}\n    dbadminlogin=${10}\n    dbadminpass=${11}\n    wabsacctname=${12}\n    wabsacctkey=${13}\n    azuremoodledbuser=${14}\n    redisDns=${15}\n    redisAuth=${16}\n    elasticVm1IP=${17}\n    installO365pluginsSwitch=${18}\n    installElasticSearchSwitch=${19}\n    dbServerType=${20}\n    fileServerType=${21}\n\n    echo $moodleVersion        >> /tmp/vars.txt\n    echo $glusterNode          >> /tmp/vars.txt\n    echo $glusterVolume        >> /tmp/vars.txt\n    echo $siteFQDN             >> /tmp/vars.txt\n    echo $dbIP                 >> /tmp/vars.txt\n    echo $moodledbname         >> /tmp/vars.txt\n    echo $moodledbuser         >> /tmp/vars.txt\n    echo $moodledbpass         >> /tmp/vars.txt\n    echo $adminpass            >> /tmp/vars.txt\n    echo $dbadminlogin         >> /tmp/vars.txt\n    echo $dbadminpass          >> /tmp/vars.txt\n    echo $wabsacctname         >> /tmp/vars.txt\n    echo $wabsacctkey          >> /tmp/vars.txt\n    echo $azuremoodledbuser    >> /tmp/vars.txt\n    echo $redisDns             >> /tmp/vars.txt\n    echo $redisAuth            >> /tmp/vars.txt\n    echo $elasticVm1IP         >> /tmp/vars.txt\n    echo $installO365pluginsSwitch    >> /tmp/vars.txt\n    echo $installElasticSearchSwitch  >> /tmp/vars.txt\n    echo $dbServerType                >> /tmp/vars.txt\n    echo $fileServerType              >> /tmp/vars.txt\n\n    . ./helper_functions.sh\n    check_fileServerType_param $fileServerType\n\n    if [ \"$dbServerType\" = \"mysql\" ]; then\n      mysqlIP=$dbIP\n      mysqladminlogin=$dbadminlogin\n      mysqladminpass=$dbadminpass\n    elif [ \"$dbServerType\" = \"postgres\" ]; then\n      postgresIP=$dbIP\n      pgadminlogin=$dbadminlogin\n      pgadminpass=$dbadminpass\n    else\n      echo \"Invalid dbServerType ($dbServerType) given. Only 'mysql' or 'postgres' is allowed. Exiting\"\n      exit 1\n    fi\n\n    # make sure system does automatic updates and fail2ban\n    sudo apt-get -y update\n    sudo apt-get -y install unattended-upgrades fail2ban\n\n    # configure fail2ban\n    cat <<EOF > /etc/fail2ban/jail.conf\n# Fail2Ban configuration file.\n#\n# This file was composed for Debian systems from the original one\n# provided now under /usr/share/doc/fail2ban/examples/jail.conf\n# for additional examples.\n#\n# Comments: use '#' for comment lines and ';' for inline comments\n#\n# To avoid merges during upgrades DO NOT MODIFY THIS FILE\n# and rather provide your changes in /etc/fail2ban/jail.local\n#\n\n# The DEFAULT allows a global definition of the options. They can be overridden\n# in each jail afterwards.\n\n[DEFAULT]\n\n# \"ignoreip\" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not\n# ban a host which matches an address in this list. Several addresses can be\n# defined using space separator.\nignoreip = 127.0.0.1/8\n\n# \"bantime\" is the number of seconds that a host is banned.\nbantime  = 600\n\n# A host is banned if it has generated \"maxretry\" during the last \"findtime\"\n# seconds.\nfindtime = 600\nmaxretry = 3\n\n# \"backend\" specifies the backend used to get files modification.\n# Available options are \"pyinotify\", \"gamin\", \"polling\" and \"auto\".\n# This option can be overridden in each jail as well.\n#\n# pyinotify: requires pyinotify (a file alteration monitor) to be installed.\n#            If pyinotify is not installed, Fail2ban will use auto.\n# gamin:     requires Gamin (a file alteration monitor) to be installed.\n#            If Gamin is not installed, Fail2ban will use auto.\n# polling:   uses a polling algorithm which does not require external libraries.\n# auto:      will try to use the following backends, in order:\n#            pyinotify, gamin, polling.\nbackend = auto\n\n# \"usedns\" specifies if jails should trust hostnames in logs,\n#   warn when reverse DNS lookups are performed, or ignore all hostnames in logs\n#\n# yes:   if a hostname is encountered, a reverse DNS lookup will be performed.\n# warn:  if a hostname is encountered, a reverse DNS lookup will be performed,\n#        but it will be logged as a warning.\n# no:    if a hostname is encountered, will not be used for banning,\n#        but it will be logged as info.\nusedns = warn\n\n#\n# Destination email address used solely for the interpolations in\n# jail.{conf,local} configuration files.\ndestemail = root@localhost\n\n#\n# Name of the sender for mta actions\nsendername = Fail2Ban\n\n#\n# ACTIONS\n#\n\n# Default banning action (e.g. iptables, iptables-new,\n# iptables-multiport, shorewall, etc) It is used to define\n# action_* variables. Can be overridden globally or per\n# section within jail.local file\nbanaction = iptables-multiport\n\n# email action. Since 0.8.1 upstream fail2ban uses sendmail\n# MTA for the mailing. Change mta configuration parameter to mail\n# if you want to revert to conventional 'mail'.\nmta = sendmail\n\n# Default protocol\nprotocol = tcp\n\n# Specify chain where jumps would need to be added in iptables-* actions\nchain = INPUT\n\n#\n# Action shortcuts. To be used to define action parameter\n\n# The simplest action to take: ban only\naction_ = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n\n# ban & send an e-mail with whois report to the destemail.\naction_mw = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n              %(mta)s-whois[name=%(__name__)s, dest=\"%(destemail)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# ban & send an e-mail with whois report and relevant log lines\n# to the destemail.\naction_mwl = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n               %(mta)s-whois-lines[name=%(__name__)s, dest=\"%(destemail)s\", logpath=%(logpath)s, chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# Choose default action.  To change, just override value of 'action' with the\n# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local\n# globally (section [DEFAULT]) or per specific section\naction = %(action_)s\n\n#\n# JAILS\n#\n\n# Next jails corresponds to the standard configuration in Fail2ban 0.6 which\n# was shipped in Debian. Enable any defined here jail by including\n#\n# [SECTION_NAME]\n# enabled = true\n\n#\n# in /etc/fail2ban/jail.local.\n#\n# Optionally you may override any other parameter (e.g. banaction,\n# action, port, logpath, etc) in that section within jail.local\n\n[ssh]\n\nenabled  = true\nport     = ssh\nfilter   = sshd\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[dropbear]\n\nenabled  = false\nport     = ssh\nfilter   = dropbear\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n# Generic filter for pam. Has to be used with action which bans all ports\n# such as iptables-allports, shorewall\n[pam-generic]\n\nenabled  = false\n# pam-generic filter can be customized to monitor specific subset of 'tty's\nfilter   = pam-generic\n# port actually must be irrelevant but lets leave it all for some possible uses\nport     = all\nbanaction = iptables-allports\nport     = anyport\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[xinetd-fail]\n\nenabled   = false\nfilter    = xinetd-fail\nport      = all\nbanaction = iptables-multiport-log\nlogpath   = /var/log/daemon.log\nmaxretry  = 2\n\n\n[ssh-ddos]\n\nenabled  = false\nport     = ssh\nfilter   = sshd-ddos\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n\n# Here we use blackhole routes for not requiring any additional kernel support\n# to store large volumes of banned IPs\n\n[ssh-route]\n\nenabled = false\nfilter = sshd\naction = route\nlogpath = /var/log/sshd.log\nmaxretry = 6\n\n# Here we use a combination of Netfilter/Iptables and IPsets\n# for storing large volumes of banned IPs\n#\n# IPset comes in two versions. See ipset -V for which one to use\n# requires the ipset package and kernel support.\n[ssh-iptables-ipset4]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto4\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n[ssh-iptables-ipset6]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto6\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n\n#\n# HTTP servers\n#\n\n[apache]\n\nenabled  = false\nport     = http,https\nfilter   = apache-auth\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n# default action is now multiport, so apache-multiport jail was left\n# for compatibility with previous (<0.7.6-2) releases\n[apache-multiport]\n\nenabled   = false\nport      = http,https\nfilter    = apache-auth\nlogpath   = /var/log/apache*/*error.log\nmaxretry  = 6\n\n[apache-noscript]\n\nenabled  = false\nport     = http,https\nfilter   = apache-noscript\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n[apache-overflows]\n\nenabled  = false\nport     = http,https\nfilter   = apache-overflows\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 2\n\n# Ban attackers that try to use PHP's URL-fopen() functionality\n# through GET/POST variables. - Experimental, with more than a year\n# of usage in production environments.\n\n[php-url-fopen]\n\nenabled = false\nport    = http,https\nfilter  = php-url-fopen\nlogpath = /var/www/*/logs/access_log\n\n# A simple PHP-fastcgi jail which works with lighttpd.\n# If you run a lighttpd server, then you probably will\n# find these kinds of messages in your error_log:\n#   ALERT \u00e2\u20ac\u201c tried to register forbidden variable \u00e2\u20ac\u02dcGLOBALS\u00e2\u20ac\u2122\n#   through GET variables (attacker '1.2.3.4', file '/var/www/default/htdocs/index.php')\n\n[lighttpd-fastcgi]\n\nenabled = false\nport    = http,https\nfilter  = lighttpd-fastcgi\nlogpath = /var/log/lighttpd/error.log\n\n# Same as above for mod_auth\n# It catches wrong authentifications\n\n[lighttpd-auth]\n\nenabled = false\nport    = http,https\nfilter  = suhosin\nlogpath = /var/log/lighttpd/error.log\n\n[nginx-http-auth]\n\nenabled = false\nfilter  = nginx-http-auth\nport    = http,https\nlogpath = /var/log/nginx/error.log\n\n# Monitor roundcube server\n\n[roundcube-auth]\n\nenabled  = false\nfilter   = roundcube-auth\nport     = http,https\nlogpath  = /var/log/roundcube/userlogins\n\n\n[sogo-auth]\n\nenabled  = false\nfilter   = sogo-auth\nport     = http, https\n# without proxy this would be:\n# port    = 20000\nlogpath  = /var/log/sogo/sogo.log\n\n\n#\n# FTP servers\n#\n\n[vsftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = vsftpd\nlogpath  = /var/log/vsftpd.log\n# or overwrite it in jails.local to be\n# logpath = /var/log/auth.log\n# if you want to rely on PAM failed login attempts\n# vsftpd's failregex should match both of those formats\nmaxretry = 6\n\n\n[proftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = proftpd\nlogpath  = /var/log/proftpd/proftpd.log\nmaxretry = 6\n\n\n[pure-ftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = pure-ftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n[wuftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = wuftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n#\n# Mail servers\n#\n\n[postfix]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = postfix\nlogpath  = /var/log/mail.log\n\n\n[couriersmtp]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = couriersmtp\nlogpath  = /var/log/mail.log\n\n\n#\n# Mail servers authenticators: might be used for smtp,ftp,imap servers, so\n# all relevant ports get banned\n#\n\n[courierauth]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = courierlogin\nlogpath  = /var/log/mail.log\n\n\n[sasl]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = postfix-sasl\n# You might consider monitoring /var/log/mail.warn instead if you are\n# running postfix since it would provide the same log lines at the\n# \"warn\" level but overall at the smaller filesize.\nlogpath  = /var/log/mail.log\n\n[dovecot]\n\nenabled = false\nport    = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter  = dovecot\nlogpath = /var/log/mail.log\n\n# To log wrong MySQL access attempts add to /etc/my.cnf:\n# log-error=/var/log/mysqld.log\n# log-warning = 2\n[mysqld-auth]\n\nenabled  = false\nfilter   = mysqld-auth\nport     = 3306\nlogpath  = /var/log/mysqld.log\n\n\n# DNS Servers\n\n\n# These jails block attacks against named (bind9). By default, logging is off\n# with bind9 installation. You will need something like this:\n#\n# logging {\n#     channel security_file {\n#         file \"/var/log/named/security.log\" versions 3 size 30m;\n#         severity dynamic;\n#         print-time yes;\n#     };\n#     category security {\n#         security_file;\n#     };\n# };\n#\n# in your named.conf to provide proper logging\n\n# !!! WARNING !!!\n#   Since UDP is connection-less protocol, spoofing of IP and imitation\n#   of illegal actions is way too simple.  Thus enabling of this filter\n#   might provide an easy way for implementing a DoS against a chosen\n#   victim. See\n#    http://nion.modprobe.de/blog/archives/690-fail2ban-+-dns-fail.html\n#   Please DO NOT USE this jail unless you know what you are doing.\n#[named-refused-udp]\n#\n#enabled  = false\n#port     = domain,953\n#protocol = udp\n#filter   = named-refused\n#logpath  = /var/log/named/security.log\n\n[named-refused-tcp]\n\nenabled  = false\nport     = domain,953\nprotocol = tcp\nfilter   = named-refused\nlogpath  = /var/log/named/security.log\n\n# Multiple jails, 1 per protocol, are necessary ATM:\n# see https://github.com/fail2ban/fail2ban/issues/37\n[asterisk-tcp]\n\nenabled  = false\nfilter   = asterisk\nport     = 5060,5061\nprotocol = tcp\nlogpath  = /var/log/asterisk/messages\n\n[asterisk-udp]\n\nenabled  = false\nfilter\t = asterisk\nport     = 5060,5061\nprotocol = udp\nlogpath  = /var/log/asterisk/messages\n\n\n# Jail for more extended banning of persistent abusers\n# !!! WARNING !!!\n#   Make sure that your loglevel specified in fail2ban.conf/.local\n#   is not at DEBUG level -- which might then cause fail2ban to fall into\n#   an infinite loop constantly feeding itself with non-informative lines\n[recidive]\n\nenabled  = false\nfilter   = recidive\nlogpath  = /var/log/fail2ban.log\naction   = iptables-allports[name=recidive]\n           sendmail-whois-lines[name=recidive, logpath=/var/log/fail2ban.log]\nbantime  = 604800  ; 1 week\nfindtime = 86400   ; 1 day\nmaxretry = 5\nEOF\n\n    # create gluster, nfs or Azure Files mount point\n    mkdir -p /moodle\n\n    export DEBIAN_FRONTEND=noninteractive\n\n    if [ $fileServerType = \"gluster\" ]; then\n        # configure gluster repository & install gluster client\n        sudo add-apt-repository ppa:gluster/glusterfs-3.8 -y                 >> /tmp/apt1.log\n    elif [ $fileServerType = \"nfs\" ]; then\n        # configure NFS server and export\n        create_filesystem_with_raid /moodle /dev/md1 /dev/md1p1\n        configure_nfs_server_and_export /moodle\n    fi\n\n    sudo apt-get -y update                                                   >> /tmp/apt2.log\n    sudo apt-get -y --force-yes install rsyslog git                          >> /tmp/apt3.log\n\n    if [ $fileServerType = \"gluster\" ]; then\n        sudo apt-get -y --force-yes install glusterfs-client                 >> /tmp/apt3.log\n    else # \"azurefiles\"\n        sudo apt-get -y --force-yes install cifs-utils                       >> /tmp/apt3.log\n    fi\n\n    if [ $dbServerType = \"mysql\" ]; then\n        sudo apt-get -y --force-yes install mysql-client >> /tmp/apt3.log\n    else\n        sudo apt-get -y --force-yes install postgresql-client >> /tmp/apt3.log\n    fi\n\n    # install azure cli & setup container\n    echo \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main\" | \\\n        sudo tee /etc/apt/sources.list.d/azure-cli.list\n\n    sudo apt-key adv --keyserver packages.microsoft.com --recv-keys 52E16F86FEE04B979B07E28DB02C46DF417A0893 >> /tmp/apt4.log\n    sudo apt-get -y install apt-transport-https >> /tmp/apt4.log\n    sudo apt-get -y update > /dev/null\n    sudo apt-get -y install azure-cli >> /tmp/apt4.log\n\n    az storage container create \\\n        --name objectfs \\\n        --account-name $wabsacctname \\\n        --account-key $wabsacctkey \\\n        --public-access off \\\n        --fail-on-exist >> /tmp/wabs.log\n\n    az storage container policy create \\\n        --account-name $wabsacctname \\\n        --account-key $wabsacctkey \\\n        --container-name objectfs \\\n        --name readwrite \\\n        --start $(date --date=\"1 day ago\" +%F) \\\n        --expiry $(date --date=\"2199-01-01\" +%F) \\\n        --permissions rw >> /tmp/wabs.log\n\n    sas=$(az storage container generate-sas \\\n        --account-name $wabsacctname \\\n        --account-key $wabsacctkey \\\n        --name objectfs \\\n        --policy readwrite \\\n        --output tsv)\n\n    if [ $fileServerType = \"gluster\" ]; then\n        # mount gluster files system\n        echo -e '\\n\\rInstalling GlusterFS on '$glusterNode':/'$glusterVolume '/moodle\\n\\r'\n        sudo mount -t glusterfs $glusterNode:/$glusterVolume /moodle\n    fi\n\n    # install pre-requisites\n    sudo apt-get install -y --fix-missing python-software-properties unzip\n\n    # install the entire stack\n    sudo apt-get -y  --force-yes install nginx php-fpm varnish >> /tmp/apt5a.log\n    sudo apt-get -y  --force-yes install php php-cli php-curl php-zip >> /tmp/apt5b.log\n\n    # Moodle requirements\n    sudo apt-get -y update > /dev/null\n    sudo apt-get install -y --force-yes graphviz aspell php-common php-soap php-json php-redis > /tmp/apt6.log\n    sudo apt-get install -y --force-yes php-bcmath php-gd php-xmlrpc php-intl php-xml php-bz2 >> /tmp/apt6.log\n    if [ $dbServerType = \"mysql\" ]; then\n        sudo apt-get install -y --force-yes php-mysql\n    else\n        sudo apt-get install -y --force-yes php-pgsql\n    fi\n\n    # Set up initial moodle dirs\n    mkdir -p /moodle/html\n    mkdir -p /moodle/certs\n    mkdir -p /moodle/moodledata\n    chown -R www-data.www-data /moodle\n\n    # install Moodle\n    echo '#!/bin/bash\n    cd /tmp\n\n    # downloading moodle\n    /usr/bin/curl -k --max-redirs 10 https://github.com/moodle/moodle/archive/'$moodleVersion'.zip -L -o moodle.zip\n    /usr/bin/unzip -q moodle.zip\n    /bin/mv -v moodle-'$moodleVersion' /moodle/html/moodle\n\n    if [ \"'$installO365pluginsSwitch'\" = \"True\" ]; then\n        # install Office 365 plugins\n        curl -k --max-redirs 10 https://github.com/Microsoft/o365-moodle/archive/'$moodleVersion'.zip -L -o o365.zip\n        unzip -q o365.zip\n        cp -r o365-moodle-'$moodleVersion'/* /moodle/html/moodle\n        rm -rf o365-moodle-'$moodleVersion'\n    fi\n\n    if [ \"'$installElasticSearchSwitch'\" = \"True\" ]; then\n        # Install ElasticSearch plugin\n        /usr/bin/curl -k --max-redirs 10 https://github.com/catalyst/moodle-search_elastic/archive/master.zip -L -o plugin-elastic.zip\n        /usr/bin/unzip -q plugin-elastic.zip\n        /bin/mkdir -p /moodle/html/moodle/search/engine/elastic\n        /bin/cp -r moodle-search_elastic-master/* /moodle/html/moodle/search/engine/elastic\n        /bin/rm -rf moodle-search_elastic-master\n\n        # Install ElasticSearch plugin dependency\n        /usr/bin/curl -k --max-redirs 10 https://github.com/catalyst/moodle-local_aws/archive/master.zip -L -o local-aws.zip\n        /usr/bin/unzip -q local-aws.zip\n        /bin/mkdir -p /moodle/html/moodle/local/aws\n        /bin/cp -r moodle-local_aws-master/* /moodle/html/moodle/local/aws\n    fi\n\n    # Install the ObjectFS plugin\n    /usr/bin/curl -k --max-redirs 10 https://github.com/catalyst/moodle-tool_objectfs/archive/master.zip -L -o plugin-objectfs.zip\n    /usr/bin/unzip -q plugin-objectfs.zip\n    /bin/mkdir -p /moodle/html/moodle/admin/tool/objectfs\n    /bin/cp -r moodle-tool_objectfs-master/* /moodle/html/moodle/admin/tool/objectfs\n    /bin/rm -rf moodle-tool_objectfs-master\n\n    # Install the ObjectFS Azure library\n    /usr/bin/curl -k --max-redirs 10 https://github.com/catalyst/moodle-local_azure_storage/archive/master.zip -L -o plugin-azurelibrary.zip\n    /usr/bin/unzip -q plugin-azurelibrary.zip\n    /bin/mkdir -p /moodle/html/moodle/local/azure_storage\n    /bin/cp -r moodle-local_azure_storage-master/* /moodle/html/moodle/local/azure_storage\n    /bin/rm -rf moodle-local_azure_storage-master\n    ' > /tmp/setup-moodle.sh\n\n    chmod 755 /tmp/setup-moodle.sh\n    sudo -u www-data /tmp/setup-moodle.sh >> /tmp/setupmoodle.log\n\n    # Build nginx config\n    cat <<EOF > /etc/nginx/nginx.conf\nuser www-data;\nworker_processes 2;\npid /run/nginx.pid;\n\nevents {\n\tworker_connections 768;\n}\n\nhttp {\n\n  sendfile on;\n  tcp_nopush on;\n  tcp_nodelay on;\n  keepalive_timeout 65;\n  types_hash_max_size 2048;\n  client_max_body_size 0;\n  proxy_max_temp_file_size 0;\n  server_names_hash_bucket_size  128;\n  fastcgi_buffers 16 16k;\n  fastcgi_buffer_size 32k;\n  proxy_buffering off;\n  include /etc/nginx/mime.types;\n  default_type application/octet-stream;\n\n  access_log /var/log/nginx/access.log;\n  error_log /var/log/nginx/error.log;\n\n  set_real_ip_from   127.0.0.1;\n  real_ip_header      X-Forwarded-For;\n  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE\n  ssl_prefer_server_ciphers on;\n\n  gzip on;\n  gzip_disable \"msie6\";\n  gzip_vary on;\n  gzip_proxied any;\n  gzip_comp_level 6;\n  gzip_buffers 16 8k;\n  gzip_http_version 1.1;\n  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;\n\n  map \\$http_x_forwarded_proto \\$fastcgi_https {\n    default \\$https;\n    http '';\n    https on;\n  }\n\n  log_format moodle_combined '\\$remote_addr - \\$upstream_http_x_moodleuser [\\$time_local] '\n                             '\"\\$request\" \\$status \\$body_bytes_sent '\n                             '\"\\$http_referer\" \"\\$http_user_agent\"';\n\n\n  include /etc/nginx/conf.d/*.conf;\n  include /etc/nginx/sites-enabled/*;\n}\nEOF\n\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 81 default;\n        server_name ${siteFQDN};\n        root /moodle/html/moodle;\n\tindex index.php index.html index.htm;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=moodle;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=moodle moodle_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n\n        # Redirect to https\n        if (\\$http_x_forwarded_proto != https) {\n                return 301 https://\\$server_name\\$request_uri;\n        }\n        rewrite ^/(.*\\.php)(/)(.*)$ /\\$1?file=/\\$3 last;\n\n\n        # Filter out php-fpm status page\n        location ~ ^/server-status {\n            return 404;\n        }\n\n\tlocation / {\n\t\ttry_files \\$uri \\$uri/index.php?\\$query_string;\n\t}\n\n        location ~ [^/]\\.php(/|$) {\n          fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n          if (!-f \\$document_root\\$fastcgi_script_name) {\n                  return 404;\n          }\n\n          fastcgi_buffers 16 16k;\n          fastcgi_buffer_size 32k;\n          fastcgi_param   SCRIPT_FILENAME \\$document_root\\$fastcgi_script_name;\n          fastcgi_pass unix:/run/php/php7.0-fpm.sock;\n          fastcgi_read_timeout 3600;\n          fastcgi_index index.php;\n          include fastcgi_params;\n        }\n}\n\nserver {\n        listen 443 ssl;\n        root /moodle/html/moodle;\n\tindex index.php index.html index.htm;\n\n        ssl on;\n        ssl_certificate /moodle/certs/nginx.crt;\n        ssl_certificate_key /moodle/certs/nginx.key;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=moodle;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=moodle moodle_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n        location / {\n          proxy_set_header Host \\$host;\n          proxy_set_header HTTP_REFERER \\$http_referer;\n          proxy_set_header X-Forwarded-Host \\$host;\n          proxy_set_header X-Forwarded-Server \\$host;\n          proxy_set_header X-Forwarded-Proto https;\n          proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n          proxy_pass http://localhost:80;\n        }\n}\nEOF\n\n    echo -e \"Generating SSL self-signed certificate\"\n    openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /moodle/certs/nginx.key -out /moodle/certs/nginx.crt -subj \"/C=BR/ST=SP/L=SaoPaulo/O=IT/CN=$siteFQDN\"\n\n   # php config\n   PhpIni=/etc/php/7.0/fpm/php.ini\n   sed -i \"s/memory_limit.*/memory_limit = 512M/\" $PhpIni\n   sed -i \"s/max_execution_time.*/max_execution_time = 18000/\" $PhpIni\n   sed -i \"s/max_input_vars.*/max_input_vars = 100000/\" $PhpIni\n   sed -i \"s/max_input_time.*/max_input_time = 600/\" $PhpIni\n   sed -i \"s/upload_max_filesize.*/upload_max_filesize = 1024M/\" $PhpIni\n   sed -i \"s/post_max_size.*/post_max_size = 1056M/\" $PhpIni\n   sed -i \"s/;opcache.use_cwd.*/opcache.use_cwd = 1/\" $PhpIni\n   sed -i \"s/;opcache.validate_timestamps.*/opcache.validate_timestamps = 1/\" $PhpIni\n   sed -i \"s/;opcache.save_comments.*/opcache.save_comments = 1/\" $PhpIni\n   sed -i \"s/;opcache.enable_file_override.*/opcache.enable_file_override = 0/\" $PhpIni\n   sed -i \"s/;opcache.enable.*/opcache.enable = 1/\" $PhpIni\n   sed -i \"s/;opcache.memory_consumption.*/opcache.memory_consumption = 256/\" $PhpIni\n   sed -i \"s/;opcache.max_accelerated_files.*/opcache.max_accelerated_files = 8000/\" $PhpIni\n\n   # fpm config - overload this\n   cat <<EOF > /etc/php/7.0/fpm/pool.d/www.conf\n[www]\nuser = www-data\ngroup = www-data\nlisten = /run/php/php7.0-fpm.sock\nlisten.owner = www-data\nlisten.group = www-data\npm = dynamic\npm.max_children = 3000\npm.start_servers = 20\npm.min_spare_servers = 22\npm.max_spare_servers = 30\nEOF\n\n   # Remove the default site. Moodle is the only site we want\n   rm -f /etc/nginx/sites-enabled/default\n\n   # restart Nginx\n    sudo service nginx restart\n\n   # Configure varnish startup for 16.04\n   VARNISHSTART=\"ExecStart=\\/usr\\/sbin\\/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f \\/etc\\/varnish\\/moodle.vcl -S \\/etc\\/varnish\\/secret -s malloc,1024m -p thread_pool_min=200 -p thread_pool_max=4000 -p thread_pool_add_delay=2 -p timeout_linger=100 -p timeout_idle=30 -p send_timeout=1800 -p thread_pools=4 -p http_max_hdr=512 -p workspace_backend=512k\"\n   sed -i \"s/^ExecStart.*/${VARNISHSTART}/\" /lib/systemd/system/varnish.service\n\n   # Configure varnish VCL for moodle\n   cat <<EOF >> /etc/varnish/moodle.vcl\nvcl 4.0;\n\nimport std;\nimport directors;\nbackend default {\n    .host = \"localhost\";\n    .port = \"81\";\n    .first_byte_timeout = 3600s;\n    .connect_timeout = 600s;\n    .between_bytes_timeout = 600s;\n}\n\nsub vcl_recv {\n    # Varnish does not support SPDY or HTTP/2.0 untill we upgrade to Varnish 5.0\n    if (req.method == \"PRI\") {\n        return (synth(405));\n    }\n\n    if (req.restarts == 0) {\n      if (req.http.X-Forwarded-For) {\n        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + \", \" + client.ip;\n      } else {\n        set req.http.X-Forwarded-For = client.ip;\n      }\n    }\n\n    # Non-RFC2616 or CONNECT HTTP requests methods filtered. Pipe requests directly to backend\n    if (req.method != \"GET\" &&\n        req.method != \"HEAD\" &&\n        req.method != \"PUT\" &&\n        req.method != \"POST\" &&\n        req.method != \"TRACE\" &&\n        req.method != \"OPTIONS\" &&\n        req.method != \"DELETE\") {\n      return (pipe);\n    }\n\n    # Varnish don't mess with healthchecks\n    if (req.url ~ \"^/admin/tool/heartbeat\" || req.url ~ \"^/healthcheck.php\")\n    {\n        return (pass);\n    }\n\n    # Pipe requests to backup.php straight to backend - prevents problem with progress bar long polling 503 problem\n    # This is here because backup.php is POSTing to itself - Filter before !GET&&!HEAD\n    if (req.url ~ \"^/backup/backup.php\")\n    {\n        return (pipe);\n    }\n\n    # Varnish only deals with GET and HEAD by default. If request method is not GET or HEAD, pass request to backend\n    if (req.method != \"GET\" && req.method != \"HEAD\") {\n      return (pass);\n    }\n\n    ### Rules for Moodle and Totara sites ###\n    # Moodle doesn't require Cookie to serve following assets. Remove Cookie header from request, so it will be looked up.\n    if ( req.url ~ \"^/altlogin/.+/.+\\.(png|jpg|jpeg|gif|css|js|webp)$\" ||\n         req.url ~ \"^/pix/.+\\.(png|jpg|jpeg|gif)$\" ||\n         req.url ~ \"^/theme/font.php\" ||\n         req.url ~ \"^/theme/image.php\" ||\n         req.url ~ \"^/theme/javascript.php\" ||\n         req.url ~ \"^/theme/jquery.php\" ||\n         req.url ~ \"^/theme/styles.php\" ||\n         req.url ~ \"^/theme/yui\" ||\n         req.url ~ \"^/lib/javascript.php/-1/\" ||\n         req.url ~ \"^/lib/requirejs.php/-1/\"\n        )\n    {\n        set req.http.X-Long-TTL = \"86400\";\n        unset req.http.Cookie;\n        return(hash);\n    }\n\n    # Perform lookup for selected assets that we know are static but Moodle still needs a Cookie\n    if(  req.url ~ \"^/theme/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/lib/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/pluginfile.php/[0-9]+/course/overviewfiles/.+\\.(?i)(png|jpg)$\"\n      )\n    {\n         # Set internal temporary header, based on which we will do things in vcl_backend_response\n         set req.http.X-Long-TTL = \"86400\";\n         return (hash);\n    }\n\n    # Serve requests to SCORM checknet.txt from varnish. Have to remove get parameters. Response body always contains \"1\"\n    if ( req.url ~ \"^/lib/yui/build/moodle-core-checknet/assets/checknet.txt\" )\n    {\n        set req.url = regsub(req.url, \"(.*)\\?.*\", \"\\1\");\n        unset req.http.Cookie; # Will go to hash anyway at the end of vcl_recv\n        set req.http.X-Long-TTL = \"86400\";\n        return(hash);\n    }\n\n    # Requests containing \"Cookie\" or \"Authorization\" headers will not be cached\n    if (req.http.Authorization || req.http.Cookie) {\n        return (pass);\n    }\n\n    # Almost everything in Moodle correctly serves Cache-Control headers, if\n    # needed, which varnish will honor, but there are some which don't. Rather\n    # than explicitly finding them all and listing them here we just fail safe\n    # and don't cache unknown urls that get this far.\n    return (pass);\n}\n\nsub vcl_backend_response {\n    # Happens after we have read the response headers from the backend.\n    #\n    # Here you clean the response headers, removing silly Set-Cookie headers\n    # and other mistakes your backend does.\n\n    # We know these assest are static, let's set TTL >0 and allow client caching\n    if ( beresp.http.Cache-Control && bereq.http.X-Long-TTL && beresp.ttl < std.duration(bereq.http.X-Long-TTL + \"s\", 1s) && !beresp.http.WWW-Authenticate )\n    { # If max-age < defined in X-Long-TTL header\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.X-Orig-Cache-Control = beresp.http.Cache-Control;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else if( !beresp.http.Cache-Control && bereq.http.X-Long-TTL && !beresp.http.WWW-Authenticate ) {\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else { # Don't touch headers if max-age > defined in X-Long-TTL header\n        unset bereq.http.X-Long-TTL;\n    }\n\n    # Here we set X-Trace header, prepending it to X-Trace header received from backend. Useful for troubleshooting\n    if(beresp.http.x-trace && !beresp.was_304) {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\")+\"->\"+beresp.http.X-Trace;\n    }\n    else {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\");\n    }\n\n    # Gzip JS, CSS is done at the ngnix level doing it here dosen't respect the no buffer requsets\n    # if (beresp.http.content-type ~ \"application/javascript.*\" || beresp.http.content-type ~ \"text\") {\n    #    set beresp.do_gzip = true;\n    #}\n}\n\nsub vcl_deliver {\n\n    # Revert back to original Cache-Control header before delivery to client\n    if (resp.http.X-Orig-Cache-Control)\n    {\n        set resp.http.Cache-Control = resp.http.X-Orig-Cache-Control;\n        unset resp.http.X-Orig-Cache-Control;\n    }\n\n    # Revert back to original Pragma header before delivery to client\n    if (resp.http.X-Orig-Pragma)\n    {\n        set resp.http.Pragma = resp.http.X-Orig-Pragma;\n        unset resp.http.X-Orig-Pragma;\n    }\n\n    # (Optional) X-Cache HTTP header will be added to responce, indicating whether object was retrieved from backend, or served from cache\n    if (obj.hits > 0) {\n        set resp.http.X-Cache = \"HIT\";\n    } else {\n        set resp.http.X-Cache = \"MISS\";\n    }\n\n    # Set X-AuthOK header when totara/varnsih authentication succeeded\n    if (req.http.X-AuthOK) {\n        set resp.http.X-AuthOK = req.http.X-AuthOK;\n    }\n\n    # If desired \"Via: 1.1 Varnish-v4\" response header can be removed from response\n    unset resp.http.Via;\n    unset resp.http.Server;\n\n    return(deliver);\n}\n\nsub vcl_backend_error {\n    # More comprehensive varnish error page. Display time, instance hostname, host header, url for easier troubleshooting.\n    set beresp.http.Content-Type = \"text/html; charset=utf-8\";\n    set beresp.http.Retry-After = \"5\";\n    synthetic( {\"\n  <!DOCTYPE html>\n  <html>\n    <head>\n      <title>\"} + beresp.status + \" \" + beresp.reason + {\"</title>\n    </head>\n    <body>\n      <h1>Error \"} + beresp.status + \" \" + beresp.reason + {\"</h1>\n      <p>\"} + beresp.reason + {\"</p>\n      <h3>Guru Meditation:</h3>\n      <p>Time: \"} + now + {\"</p>\n      <p>Node: \"} + server.hostname + {\"</p>\n      <p>Host: \"} + bereq.http.host + {\"</p>\n      <p>URL: \"} + bereq.url + {\"</p>\n      <p>XID: \"} + bereq.xid + {\"</p>\n      <hr>\n      <p>Varnish cache server\n    </body>\n  </html>\n  \"} );\n   return (deliver);\n}\n\nsub vcl_synth {\n\n    #Redirect using '301 - Permanent Redirect', permanent redirect\n    if (resp.status == 851) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 301;\n        return (deliver);\n    }\n\n    #Redirect using '302 - Found', temporary redirect\n    if (resp.status == 852) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 302;\n        return (deliver);\n    }\n\n    #Redirect using '307 - Temporary Redirect', !GET&&!HEAD requests, dont change method on redirected requests\n    if (resp.status == 857) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 307;\n        return (deliver);\n    }\n\n    #Respond with 403 - Forbidden\n    if (resp.status == 863) {\n        set resp.http.X-Varnish-Error = true;\n        set resp.status = 403;\n        return (deliver);\n    }\n}\nEOF\n\n    # Restart Varnish\n    systemctl daemon-reload\n    service varnish restart\n\n    if [ $dbServerType = \"mysql\" ]; then\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \"CREATE DATABASE ${moodledbname} CHARACTER SET utf8;\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \"GRANT ALL ON ${moodledbname}.* TO ${moodledbuser} IDENTIFIED BY '${moodledbpass}';\"\n\n        echo \"mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \\\"CREATE DATABASE ${moodledbname};\\\"\" >> /tmp/debug\n        echo \"mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} -e \\\"GRANT ALL ON ${moodledbname}.* TO ${moodledbuser} IDENTIFIED BY '${moodledbpass}';\\\"\" >> /tmp/debug\n    else\n        # Create postgres db\n        echo \"${postgresIP}:5432:postgres:${pgadminlogin}:${pgadminpass}\" > /root/.pgpass\n        chmod 600 /root/.pgpass\n        psql -h $postgresIP -U $pgadminlogin -c \"CREATE DATABASE ${moodledbname};\" postgres\n        psql -h $postgresIP -U $pgadminlogin -c \"CREATE USER ${moodledbuser} WITH PASSWORD '${moodledbpass}';\" postgres\n        psql -h $postgresIP -U $pgadminlogin -c \"GRANT ALL ON DATABASE ${moodledbname} TO ${moodledbuser};\" postgres\n        rm -f /root/.pgpass\n    fi\n\n    # Master config for syslog\n    mkdir /var/log/sitelogs\n    chown syslog.adm /var/log/sitelogs\n    cat <<EOF >> /etc/rsyslog.conf\n\\$ModLoad imudp\n\\$UDPServerRun 514\nEOF\n    cat <<EOF >> /etc/rsyslog.d/40-sitelogs.conf\nlocal1.*   /var/log/sitelogs/moodle/access.log\nlocal1.err   /var/log/sitelogs/moodle/error.log\nlocal2.*   /var/log/sitelogs/moodle/cron.log\nEOF\n    service rsyslog restart\n\n    # Fire off moodle setup\n    if [ $dbServerType = \"mysql\" ]; then\n        echo -e \"cd /tmp; sudo -u www-data /usr/bin/php /moodle/html/moodle/admin/cli/install.php --chmod=770 --lang=en_us --wwwroot=https://\"$siteFQDN\" --dataroot=/moodle/moodledata --dbhost=\"$mysqlIP\" --dbname=\"$moodledbname\" --dbuser=\"$azuremoodledbuser\" --dbpass=\"$moodledbpass\" --dbtype=mysqli --fullname='Moodle LMS' --shortname='Moodle' --adminuser=admin --adminpass=\"$adminpass\" --adminemail=admin@\"$siteFQDN\" --non-interactive --agree-license --allow-unstable || true \"\n        cd /tmp; sudo -u www-data /usr/bin/php /moodle/html/moodle/admin/cli/install.php --chmod=770 --lang=en_us --wwwroot=https://$siteFQDN   --dataroot=/moodle/moodledata --dbhost=$mysqlIP   --dbname=$moodledbname   --dbuser=$azuremoodledbuser   --dbpass=$moodledbpass   --dbtype=mysqli --fullname='Moodle LMS' --shortname='Moodle' --adminuser=admin --adminpass=$adminpass   --adminemail=admin@$siteFQDN   --non-interactive --agree-license --allow-unstable || true\n\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} ${moodledbname} -e \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'enabletasks', 1);\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} ${moodledbname} -e \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'filesystem', '\\\\\\tool_objectfs\\\\\\azure_file_system');\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} ${moodledbname} -e \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_accountname', '${wabsacctname}');\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} ${moodledbname} -e \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_container', 'objectfs');\"\n        mysql -h $mysqlIP -u $mysqladminlogin -p${mysqladminpass} ${moodledbname} -e \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_sastoken', '${sas}');\"\n    else\n        echo -e \"cd /tmp; sudo -u www-data /usr/bin/php /moodle/html/moodle/admin/cli/install.php --chmod=770 --lang=en_us --wwwroot=https://\"$siteFQDN\" --dataroot=/moodle/moodledata --dbhost=\"$postgresIP\" --dbname=\"$moodledbname\" --dbuser=\"$azuremoodledbuser\" --dbpass=\"$moodledbpass\" --dbtype=pgsql --fullname='Moodle LMS' --shortname='Moodle' --adminuser=admin --adminpass=\"$adminpass\" --adminemail=admin@\"$siteFQDN\" --non-interactive --agree-license --allow-unstable || true \"\n        cd /tmp; sudo -u www-data /usr/bin/php /moodle/html/moodle/admin/cli/install.php --chmod=770 --lang=en_us --wwwroot=https://$siteFQDN   --dataroot=/moodle/moodledata --dbhost=$postgresIP   --dbname=$moodledbname   --dbuser=$azuremoodledbuser   --dbpass=$moodledbpass   --dbtype=pgsql --fullname='Moodle LMS' --shortname='Moodle' --adminuser=admin --adminpass=$adminpass   --adminemail=admin@$siteFQDN   --non-interactive --agree-license --allow-unstable || true\n\n        # Add the ObjectFS configuration to Moodle.\n        echo \"${postgresIP}:5432:${moodledbname}:${azuremoodledbuser}:${moodledbpass}\" > /root/.pgpass\n        chmod 600 /root/.pgpass\n        psql -h $postgresIP -U $azuremoodledbuser -c \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'enabletasks', 1);\" $moodledbname\n        psql -h $postgresIP -U $azuremoodledbuser -c \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'filesystem', '\\tool_objectfs\\azure_file_system');\" $moodledbname\n        psql -h $postgresIP -U $azuremoodledbuser -c \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_accountname', '$wabsacctname');\" $moodledbname\n        psql -h $postgresIP -U $azuremoodledbuser -c \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_container', 'objectfs');\" $moodledbname\n        psql -h $postgresIP -U $azuremoodledbuser -c \"INSERT INTO mdl_config_plugins (plugin, name, value) VALUES ('tool_objectfs', 'azure_sastoken', '$sas');\" $moodledbname\n    fi\n\n    echo -e \"\\n\\rDone! Installation completed!\\n\\r\"\n\n    create_redis_configuration_in_moodledata_muc_config_php\n\n    # redis configuration in /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_lock_expire = 7200;\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_acquire_lock_timeout = 120;\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_prefix = 'moodle_prod'; // Optional, default is don't set one.\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_database = 0;  // Optional, default is db 0.\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_port = 6379;  // Optional.\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_host = '$redisDns';\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_redis_auth = '$redisAuth';\" /moodle/html/moodle/config.php\n    sed -i \"23 a \\$CFG->session_handler_class = '\\\\\\core\\\\\\session\\\\\\redis';\" /moodle/html/moodle/config.php\n\n    # We proxy ssl, so moodle needs to know this\n    sed -i \"23 a \\$CFG->sslproxy  = 'true';\" /moodle/html/moodle/config.php\n\n    if [ \"$installElasticSearchSwitch\" = \"True\" ]; then\n        # Set up elasticsearch plugin\n        sed -i \"23 a \\$CFG->forced_plugin_settings = ['search_elastic' => ['hostname' => 'http://$elasticVm1IP']];\" /moodle/html/moodle/config.php\n        sed -i \"23 a \\$CFG->searchengine = 'elastic';\" /moodle/html/moodle/config.php\n        sed -i \"23 a \\$CFG->enableglobalsearch = 'true';\" /moodle/html/moodle/config.php\n    fi\n\n    # Set the ObjectFS alternate filesystem\n    sed -i \"23 a \\$CFG->alternative_file_system_class = '\\\\\\tool_objectfs\\\\\\azure_file_system';\" /moodle/html/moodle/config.php\n\n   if [ \"$dbServerType\" = \"postgres\" ]; then\n     # Get a new version of Postgres to match Azure version\n     add-apt-repository \"deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main\"\n     wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -\n     apt-get update\n     apt-get install postgresql-client-9.6\n   fi\n\n   # create cron entry\n   # It is scheduled for once per minute. It can be changed as needed.\n   echo '* * * * * www-data /usr/bin/php /moodle/html/moodle/admin/cli/cron.php 2>&1 | /usr/bin/logger -p local2.notice -t moodle' > /etc/cron.d/moodle-cron\n\n   # Set up cronned sql dump\n   if [ \"$dbServerType\" = \"mysql\" ]; then\n      cat <<EOF > /etc/cron.d/sql-backup\n22 02 * * * root /usr/bin/mysqldump -h $mysqlIP -u ${azuremoodledbuser} -p'${moodledbpass}' --databases ${moodledbname} | gzip > /moodle/db-backup.sql.gz\nEOF\n   else\n      cat <<EOF > /etc/cron.d/sql-backup\n22 02 * * * root /usr/bin/pg_dump -Fc -h $postgresIP -U ${azuremoodledbuser} ${moodledbname} > /moodle/db-backup.sql\nEOF\n   fi\n\n   # Turning off services we don't need the jumpbox running\n   service nginx stop\n   service php7.0-fpm stop\n   service varnish stop\n   service varnishncsa stop\n   service varnishlog stop\n\n   if [ $fileServerType = \"gluster\" -o $fileServerType = \"nfs\" ]; then\n      # make sure Moodle can read its code directory but not write\n      sudo chown -R root.root /moodle/html/moodle\n      sudo find /moodle/html/moodle -type f -exec chmod 644 '{}' \\;\n      sudo find /moodle/html/moodle -type d -exec chmod 755 '{}' \\;\n   fi\n\n   if [ $fileServerType = \"azurefiles\" ]; then\n      # Delayed copy of moodle installation to the Azure Files share\n\n      # First rename moodle directory to something else\n      mv /moodle /moodle_old_delete_me\n      # Then create the moodle share\n      echo -e '\\n\\rCreating an Azure Files share for moodle'\n      create_azure_files_moodle_share $wabsacctname $wabsacctkey /tmp/wabs.log\n      # Set up and mount Azure Files share. Must be done after nginx is installed because of www-data user/group\n      echo -e '\\n\\rSetting up and mounting Azure Files share on //'$wabsacctname'.file.core.windows.net/moodle on /moodle\\n\\r'\n      setup_and_mount_azure_files_moodle_share $wabsacctname $wabsacctkey\n      # Move the local installation over to the Azure Files\n      echo -e '\\n\\rMoving locally installed moodle over to Azure Files'\n      cp -a /moodle_old_delete_me/* /moodle || true # Ignore case sensitive directory copy failure\n      # rm -rf /moodle_old_delete_me || true # Keep the files just in case\n   fi\n\n}  > /tmp/install.log\n", "num_lines": 1288}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Custom Script for Linux\n\n#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\nglusterNode=$1\nglusterVolume=$2\nsiteFQDN=$3\nsyslogserver=$4\nwebServerType=$5\nfileServerType=$6\nstorageAccountName=$7\nstorageAccountKey=$8\nnfsVmName=$9\n\necho $glusterNode    >> /tmp/vars.txt\necho $glusterVolume  >> /tmp/vars.txt\necho $siteFQDN >> /tmp/vars.txt\necho $syslogserver >> /tmp/vars.txt\necho $webServerType >> /tmp/vars.txt\necho $fileServerType >> /tmp/vars.txt\necho $storageAccountName >> /tmp/vars.txt\necho $storageAccountKey >> /tmp/vars.txt\necho $nfsVmName >> /tmp/vars.txt\n\n. ./helper_functions.sh\ncheck_fileServerType_param $fileServerType\n\n{\n  # make sure the system does automatic update\n  sudo apt-get -y update\n  sudo apt-get -y install unattended-upgrades\n\n  # install pre-requisites\n  sudo apt-get -y install python-software-properties unzip rsyslog\n\n  sudo apt-get -y install postgresql-client mysql-client git\n\n  if [ $fileServerType = \"gluster\" ]; then\n    #configure gluster repository & install gluster client\n    sudo add-apt-repository ppa:gluster/glusterfs-3.8 -y\n    sudo apt-get -y update\n    sudo apt-get -y install glusterfs-client\n  else # \"azurefiles\"\n    sudo apt-get -y install cifs-utils\n  fi\n\n  # install the base stack\n  sudo apt-get -y install nginx varnish php php-cli php-curl php-zip\n\n  if [ \"$webServerType\" = \"apache\" ]; then\n    # install apache pacakges\n    sudo apt-get -y install apache2 libapache2-mod-php\n  else\n    # for nginx-only option\n    sudo apt-get -y install php-fpm\n  fi\n\n  # Moodle requirements\n  sudo apt-get install -y graphviz aspell php-soap php-json php-redis php-bcmath php-gd php-pgsql php-mysql php-xmlrpc php-intl php-xml php-bz2\n\n  if [ $fileServerType = \"gluster\" ]; then\n    # Mount gluster fs for /moodle\n    sudo mkdir -p /moodle\n    sudo chown www-data /moodle\n    sudo chmod 770 /moodle\n    sudo echo -e 'mount -t glusterfs '$glusterNode':/'$glusterVolume' /moodle'\n    sudo mount -t glusterfs $glusterNode:/$glusterVolume /moodle\n    sudo echo -e $glusterNode':/'$glusterVolume'   /moodle         glusterfs       defaults,_netdev,log-level=WARNING,log-file=/var/log/gluster.log 0 0' >> /etc/fstab\n    sudo mount -a\n  elif [ $fileServerType = \"nfs\" ]; then\n    configure_nfs_client_and_mount $nfsVmName /moodle /moodle\n  else # \"azurefiles\"\n    setup_and_mount_azure_files_moodle_share $storageAccountName $storageAccountKey\n  fi\n\n  # Configure syslog to forward\n  cat <<EOF >> /etc/rsyslog.conf\n\\$ModLoad imudp\n\\$UDPServerRun 514\nEOF\n  cat <<EOF >> /etc/rsyslog.d/40-remote.conf\nlocal1.*   @${syslogserver}:514\nlocal2.*   @${syslogserver}:514\nEOF\n  service syslog restart\n\n  # Build nginx config\n  cat <<EOF > /etc/nginx/nginx.conf\nuser www-data;\nworker_processes 2;\npid /run/nginx.pid;\n\nevents {\n\tworker_connections 2048;\n}\n\nhttp {\n\n  sendfile on;\n  tcp_nopush on;\n  tcp_nodelay on;\n  keepalive_timeout 65;\n  types_hash_max_size 2048;\n  client_max_body_size 0;\n  proxy_max_temp_file_size 0;\n  server_names_hash_bucket_size  128;\n  fastcgi_buffers 16 16k;\n  fastcgi_buffer_size 32k;\n  proxy_buffering off;\n  include /etc/nginx/mime.types;\n  default_type application/octet-stream;\n\n  access_log /var/log/nginx/access.log;\n  error_log /var/log/nginx/error.log;\n\n  set_real_ip_from   127.0.0.1;\n  real_ip_header      X-Forwarded-For;\n  ssl_protocols TLSv1 TLSv1.1 TLSv1.2; # Dropping SSLv3, ref: POODLE\n  ssl_prefer_server_ciphers on;\n\n  gzip on;\n  gzip_disable \"msie6\";\n  gzip_vary on;\n  gzip_proxied any;\n  gzip_comp_level 6;\n  gzip_buffers 16 8k;\n  gzip_http_version 1.1;\n  gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;\n\n  map \\$http_x_forwarded_proto \\$fastcgi_https {\n    default \\$https;\n    http '';\n    https on;\n  }\n\n  log_format moodle_combined '\\$remote_addr - \\$upstream_http_x_moodleuser [\\$time_local] '\n                             '\"\\$request\" \\$status \\$body_bytes_sent '\n                             '\"\\$http_referer\" \"\\$http_user_agent\"';\n\n\n  include /etc/nginx/conf.d/*.conf;\n  include /etc/nginx/sites-enabled/*;\n}\nEOF\n\n  # Configure nginx/https\n  cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 443 ssl;\n        root /moodle/html/moodle;\n\tindex index.php index.html index.htm;\n\n        ssl on;\n        ssl_certificate /moodle/certs/nginx.crt;\n        ssl_certificate_key /moodle/certs/nginx.key;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=moodle;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=moodle moodle_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n        location / {\n          proxy_set_header Host \\$host;\n          proxy_set_header HTTP_REFERER \\$http_referer;\n          proxy_set_header X-Forwarded-Host \\$host;\n          proxy_set_header X-Forwarded-Server \\$host;\n          proxy_set_header X-Forwarded-Proto https;\n          proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\n          proxy_pass http://localhost:80;\n\n          proxy_connect_timeout       3600;\n          proxy_send_timeout          3600;\n          proxy_read_timeout          3600;\n          send_timeout                3600;\n        }\n}\nEOF\n\n  if [ \"$webServerType\" = \"nginx\" ]; then\n    cat <<EOF >> /etc/nginx/sites-enabled/${siteFQDN}.conf\nserver {\n        listen 81 default;\n        server_name ${siteFQDN};\n        root /moodle/html/moodle;\n\tindex index.php index.html index.htm;\n\n        # Log to syslog\n        error_log syslog:server=localhost,facility=local1,severity=error,tag=moodle;\n        access_log syslog:server=localhost,facility=local1,severity=notice,tag=moodle moodle_combined;\n\n        # Log XFF IP instead of varnish\n        set_real_ip_from    10.0.0.0/8;\n        set_real_ip_from    127.0.0.1;\n        set_real_ip_from    172.16.0.0/12;\n        set_real_ip_from    192.168.0.0/16;\n        real_ip_header      X-Forwarded-For;\n        real_ip_recursive   on;\n\n\n        # Redirect to https\n        if (\\$http_x_forwarded_proto != https) {\n                return 301 https://\\$server_name\\$request_uri;\n        }\n        rewrite ^/(.*\\.php)(/)(.*)$ /\\$1?file=/\\$3 last;\n\n\n        # Filter out php-fpm status page\n        location ~ ^/server-status {\n            return 404;\n        }\n\n\tlocation / {\n\t\ttry_files \\$uri \\$uri/index.php?\\$query_string;\n\t}\n\n        location ~ [^/]\\.php(/|$) {\n          fastcgi_split_path_info ^(.+?\\.php)(/.*)$;\n          if (!-f \\$document_root\\$fastcgi_script_name) {\n                  return 404;\n          }\n\n          fastcgi_buffers 16 16k;\n          fastcgi_buffer_size 32k;\n          fastcgi_param   SCRIPT_FILENAME \\$document_root\\$fastcgi_script_name;\n          fastcgi_pass unix:/run/php/php7.0-fpm.sock;\n          fastcgi_read_timeout 3600;\n          fastcgi_index index.php;\n          include fastcgi_params;\n        }\n}\n\nEOF\n  fi\n\n  if [ \"$webServerType\" = \"apache\" ]; then\n    # Configure Apache/php\n    sed -i \"s/Listen 80/Listen 81/\" /etc/apache2/ports.conf\n    a2enmod rewrite && a2enmod remoteip && a2enmod headers\n\n    cat <<EOF >> /etc/apache2/sites-enabled/${siteFQDN}.conf\n<VirtualHost *:81>\n\tServerName ${siteFQDN}\n\n\tServerAdmin webmaster@localhost\n\tDocumentRoot /moodle/html/moodle\n\n\t<Directory /moodle/html/moodle>\n\t\tOptions FollowSymLinks\n\t\tAllowOverride All\n\t\tRequire all granted\n\t</Directory>\n\n    # Redirect unencrypted direct connections to HTTPS\n    <IfModule mod_rewrite.c>\n      RewriteEngine on\n      RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]\n      RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [L,R=301]\n    </IFModule>\n\n    # Log X-Forwarded-For IP address instead of varnish (127.0.0.1)\n    SetEnvIf X-Forwarded-For \"^.*\\..*\\..*\\..*\" forwarded\n    LogFormat \"%h %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\" combined\n    LogFormat \"%{X-Forwarded-For}i %l %u %t \\\"%r\\\" %>s %b \\\"%{Referer}i\\\" \\\"%{User-Agent}i\\\"\" forwarded\n\tErrorLog \"|/usr/bin/logger -t moodle -p local1.error\"\n    CustomLog \"|/usr/bin/logger -t moodle -p local1.notice\" combined env=!forwarded\n    CustomLog \"|/usr/bin/logger -t moodle -p local1.notice\" forwarded env=forwarded\n\n</VirtualHost>\nEOF\n  fi\n\n   # php config\n   if [ \"$webServerType\" = \"apache\" ]; then\n     PhpIni=/etc/php/7.0/apache2/php.ini\n   else\n     PhpIni=/etc/php/7.0/fpm/php.ini\n   fi\n   sed -i \"s/memory_limit.*/memory_limit = 512M/\" $PhpIni\n   sed -i \"s/max_execution_time.*/max_execution_time = 18000/\" $PhpIni\n   sed -i \"s/max_input_vars.*/max_input_vars = 100000/\" $PhpIni\n   sed -i \"s/max_input_time.*/max_input_time = 600/\" $PhpIni\n   sed -i \"s/upload_max_filesize.*/upload_max_filesize = 1024M/\" $PhpIni\n   sed -i \"s/post_max_size.*/post_max_size = 1056M/\" $PhpIni\n   sed -i \"s/;opcache.use_cwd.*/opcache.use_cwd = 1/\" $PhpIni\n   sed -i \"s/;opcache.validate_timestamps.*/opcache.validate_timestamps = 1/\" $PhpIni\n   sed -i \"s/;opcache.save_comments.*/opcache.save_comments = 1/\" $PhpIni\n   sed -i \"s/;opcache.enable_file_override.*/opcache.enable_file_override = 0/\" $PhpIni\n   sed -i \"s/;opcache.enable.*/opcache.enable = 1/\" $PhpIni\n   sed -i \"s/;opcache.memory_consumption.*/opcache.memory_consumption = 256/\" $PhpIni\n   sed -i \"s/;opcache.max_accelerated_files.*/opcache.max_accelerated_files = 8000/\" $PhpIni\n\n   # Remove the default site. Moodle is the only site we want\n   rm -f /etc/nginx/sites-enabled/default\n   if [ \"$webServerType\" = \"apache\" ]; then\n     rm -f /etc/apache2/sites-enabled/000-default.conf\n   fi\n\n   # restart Nginx\n   sudo service nginx restart\n\n   if [ \"$webServerType\" = \"nginx\" ]; then\n     # fpm config - overload this\n     cat <<EOF > /etc/php/7.0/fpm/pool.d/www.conf\n[www]\nuser = www-data\ngroup = www-data\nlisten = /run/php/php7.0-fpm.sock\nlisten.owner = www-data\nlisten.group = www-data\npm = dynamic\npm.max_children = 3000\npm.start_servers = 20\npm.min_spare_servers = 20\npm.max_spare_servers = 30\nEOF\n\n     # Restart fpm\n     service php7.0-fpm restart\n   fi\n\n   if [ \"$webServerType\" = \"apache\" ]; then\n     sudo service apache2 restart\n   fi\n\n   # Configure varnish startup for 16.04\n   VARNISHSTART=\"ExecStart=\\/usr\\/sbin\\/varnishd -j unix,user=vcache -F -a :80 -T localhost:6082 -f \\/etc\\/varnish\\/moodle.vcl -S \\/etc\\/varnish\\/secret -s malloc,1024m -p thread_pool_min=200 -p thread_pool_max=4000 -p thread_pool_add_delay=2 -p timeout_linger=100 -p timeout_idle=30 -p send_timeout=1800 -p thread_pools=4 -p http_max_hdr=512 -p workspace_backend=512k\"\n   sed -i \"s/^ExecStart.*/${VARNISHSTART}/\" /lib/systemd/system/varnish.service\n\n   # Configure varnish VCL for moodle\n   cat <<EOF >> /etc/varnish/moodle.vcl\nvcl 4.0;\n\nimport std;\nimport directors;\nbackend default {\n    .host = \"localhost\";\n    .port = \"81\";\n    .first_byte_timeout = 3600s;\n    .connect_timeout = 600s;\n    .between_bytes_timeout = 600s;\n}\n\nsub vcl_recv {\n    # Varnish does not support SPDY or HTTP/2.0 untill we upgrade to Varnish 5.0\n    if (req.method == \"PRI\") {\n        return (synth(405));\n    }\n\n    if (req.restarts == 0) {\n      if (req.http.X-Forwarded-For) {\n        set req.http.X-Forwarded-For = req.http.X-Forwarded-For + \", \" + client.ip;\n      } else {\n        set req.http.X-Forwarded-For = client.ip;\n      }\n    }\n\n    # Non-RFC2616 or CONNECT HTTP requests methods filtered. Pipe requests directly to backend\n    if (req.method != \"GET\" &&\n        req.method != \"HEAD\" &&\n        req.method != \"PUT\" &&\n        req.method != \"POST\" &&\n        req.method != \"TRACE\" &&\n        req.method != \"OPTIONS\" &&\n        req.method != \"DELETE\") {\n      return (pipe);\n    }\n\n    # Varnish don't mess with healthchecks\n    if (req.url ~ \"^/admin/tool/heartbeat\" || req.url ~ \"^/healthcheck.php\")\n    {\n        return (pass);\n    }\n\n    # Pipe requests to backup.php straight to backend - prevents problem with progress bar long polling 503 problem\n    # This is here because backup.php is POSTing to itself - Filter before !GET&&!HEAD\n    if (req.url ~ \"^/backup/backup.php\")\n    {\n        return (pipe);\n    }\n\n    # Varnish only deals with GET and HEAD by default. If request method is not GET or HEAD, pass request to backend\n    if (req.method != \"GET\" && req.method != \"HEAD\") {\n      return (pass);\n    }\n\n    ### Rules for Moodle and Totara sites ###\n    # Moodle doesn't require Cookie to serve following assets. Remove Cookie header from request, so it will be looked up.\n    if ( req.url ~ \"^/altlogin/.+/.+\\.(png|jpg|jpeg|gif|css|js|webp)$\" ||\n         req.url ~ \"^/pix/.+\\.(png|jpg|jpeg|gif)$\" ||\n         req.url ~ \"^/theme/font.php\" ||\n         req.url ~ \"^/theme/image.php\" ||\n         req.url ~ \"^/theme/javascript.php\" ||\n         req.url ~ \"^/theme/jquery.php\" ||\n         req.url ~ \"^/theme/styles.php\" ||\n         req.url ~ \"^/theme/yui\" ||\n         req.url ~ \"^/lib/javascript.php/-1/\" ||\n         req.url ~ \"^/lib/requirejs.php/-1/\"\n        )\n    {\n        set req.http.X-Long-TTL = \"86400\";\n        unset req.http.Cookie;\n        return(hash);\n    }\n\n    # Perform lookup for selected assets that we know are static but Moodle still needs a Cookie\n    if(  req.url ~ \"^/theme/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/lib/.+\\.(png|jpg|jpeg|gif|css|js|webp)\" ||\n         req.url ~ \"^/pluginfile.php/[0-9]+/course/overviewfiles/.+\\.(?i)(png|jpg)$\"\n      )\n    {\n         # Set internal temporary header, based on which we will do things in vcl_backend_response\n         set req.http.X-Long-TTL = \"86400\";\n         return (hash);\n    }\n\n    # Serve requests to SCORM checknet.txt from varnish. Have to remove get parameters. Response body always contains \"1\"\n    if ( req.url ~ \"^/lib/yui/build/moodle-core-checknet/assets/checknet.txt\" )\n    {\n        set req.url = regsub(req.url, \"(.*)\\?.*\", \"\\1\");\n        unset req.http.Cookie; # Will go to hash anyway at the end of vcl_recv\n        set req.http.X-Long-TTL = \"86400\";\n        return(hash);\n    }\n\n    # Requests containing \"Cookie\" or \"Authorization\" headers will not be cached\n    if (req.http.Authorization || req.http.Cookie) {\n        return (pass);\n    }\n\n    # Almost everything in Moodle correctly serves Cache-Control headers, if\n    # needed, which varnish will honor, but there are some which don't. Rather\n    # than explicitly finding them all and listing them here we just fail safe\n    # and don't cache unknown urls that get this far.\n    return (pass);\n}\n\nsub vcl_backend_response {\n    # Happens after we have read the response headers from the backend.\n    #\n    # Here you clean the response headers, removing silly Set-Cookie headers\n    # and other mistakes your backend does.\n\n    # We know these assest are static, let's set TTL >0 and allow client caching\n    if ( beresp.http.Cache-Control && bereq.http.X-Long-TTL && beresp.ttl < std.duration(bereq.http.X-Long-TTL + \"s\", 1s) && !beresp.http.WWW-Authenticate )\n    { # If max-age < defined in X-Long-TTL header\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.X-Orig-Cache-Control = beresp.http.Cache-Control;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else if( !beresp.http.Cache-Control && bereq.http.X-Long-TTL && !beresp.http.WWW-Authenticate ) {\n        set beresp.http.X-Orig-Pragma = beresp.http.Pragma; unset beresp.http.Pragma;\n        set beresp.http.Cache-Control = \"public, max-age=\"+bereq.http.X-Long-TTL+\", no-transform\";\n        set beresp.ttl = std.duration(bereq.http.X-Long-TTL + \"s\", 1s);\n        unset bereq.http.X-Long-TTL;\n    }\n    else { # Don't touch headers if max-age > defined in X-Long-TTL header\n        unset bereq.http.X-Long-TTL;\n    }\n\n    # Here we set X-Trace header, prepending it to X-Trace header received from backend. Useful for troubleshooting\n    if(beresp.http.x-trace && !beresp.was_304) {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\")+\"->\"+beresp.http.X-Trace;\n    }\n    else {\n        set beresp.http.X-Trace = regsub(server.identity, \"^([^.]+),?.*$\", \"\\1\")+\"->\"+regsub(beresp.backend.name, \"^(.+)\\((?:[0-9]{1,3}\\.){3}([0-9]{1,3})\\)\",\"\\1(\\2)\");\n    }\n\n    # Gzip JS, CSS is done at the ngnix level doing it here dosen't respect the no buffer requsets\n    # if (beresp.http.content-type ~ \"application/javascript.*\" || beresp.http.content-type ~ \"text\") {\n    #    set beresp.do_gzip = true;\n    #}\n}\n\nsub vcl_deliver {\n\n    # Revert back to original Cache-Control header before delivery to client\n    if (resp.http.X-Orig-Cache-Control)\n    {\n        set resp.http.Cache-Control = resp.http.X-Orig-Cache-Control;\n        unset resp.http.X-Orig-Cache-Control;\n    }\n\n    # Revert back to original Pragma header before delivery to client\n    if (resp.http.X-Orig-Pragma)\n    {\n        set resp.http.Pragma = resp.http.X-Orig-Pragma;\n        unset resp.http.X-Orig-Pragma;\n    }\n\n    # (Optional) X-Cache HTTP header will be added to responce, indicating whether object was retrieved from backend, or served from cache\n    if (obj.hits > 0) {\n        set resp.http.X-Cache = \"HIT\";\n    } else {\n        set resp.http.X-Cache = \"MISS\";\n    }\n\n    # Set X-AuthOK header when totara/varnsih authentication succeeded\n    if (req.http.X-AuthOK) {\n        set resp.http.X-AuthOK = req.http.X-AuthOK;\n    }\n\n    # If desired \"Via: 1.1 Varnish-v4\" response header can be removed from response\n    unset resp.http.Via;\n    unset resp.http.Server;\n\n    return(deliver);\n}\n\nsub vcl_backend_error {\n    # More comprehensive varnish error page. Display time, instance hostname, host header, url for easier troubleshooting.\n    set beresp.http.Content-Type = \"text/html; charset=utf-8\";\n    set beresp.http.Retry-After = \"5\";\n    synthetic( {\"\n  <!DOCTYPE html>\n  <html>\n    <head>\n      <title>\"} + beresp.status + \" \" + beresp.reason + {\"</title>\n    </head>\n    <body>\n      <h1>Error \"} + beresp.status + \" \" + beresp.reason + {\"</h1>\n      <p>\"} + beresp.reason + {\"</p>\n      <h3>Guru Meditation:</h3>\n      <p>Time: \"} + now + {\"</p>\n      <p>Node: \"} + server.hostname + {\"</p>\n      <p>Host: \"} + bereq.http.host + {\"</p>\n      <p>URL: \"} + bereq.url + {\"</p>\n      <p>XID: \"} + bereq.xid + {\"</p>\n      <hr>\n      <p>Varnish cache server\n    </body>\n  </html>\n  \"} );\n   return (deliver);\n}\n\nsub vcl_synth {\n\n    #Redirect using '301 - Permanent Redirect', permanent redirect\n    if (resp.status == 851) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 301;\n        return (deliver);\n    }\n\n    #Redirect using '302 - Found', temporary redirect\n    if (resp.status == 852) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 302;\n        return (deliver);\n    }\n\n    #Redirect using '307 - Temporary Redirect', !GET&&!HEAD requests, dont change method on redirected requests\n    if (resp.status == 857) {\n        set resp.http.Location = req.http.x-redir;\n        set resp.http.X-Varnish-Redirect = true;\n        set resp.status = 307;\n        return (deliver);\n    }\n\n    #Respond with 403 - Forbidden\n    if (resp.status == 863) {\n        set resp.http.X-Varnish-Error = true;\n        set resp.status = 403;\n        return (deliver);\n    }\n}\nEOF\n\n  # Restart Varnish\n  systemctl daemon-reload\n  service varnish restart\n\n}  > /tmp/setup.log\n", "num_lines": 605}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 6.5 and Ubuntu 12.04 LTS with Percona XtraDB Cluster 5.6.\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of DeployPXC powershell script or runbook or Azure Resource Manager CRP template.\n\nCLUSTERADDRESS=${1}\nNODEADDRESS=${2}\nNODENAME=$(hostname)\nMYSQLSTARTUP=${3}\nMYCNFTEMPLATE=${4}\nSECONDNIC=${5}\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=512\n\nRAIDDISK=\"/dev/md127\"\nRAIDPARTITION=\"/dev/md127p1\"\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ncreate_raid0_ubuntu() {\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        wget --no-cache http://mirrors.cat.pdx.edu/ubuntu/pool/main/m/mdadm/mdadm_3.2.5-5ubuntu4_amd64.deb\n        dpkg -i mdadm_3.2.5-5ubuntu4_amd64.deb\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ncreate_raid0_centos() {\n    echo \"Creating raid0\"\n    yes | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n\tls \"${MOUNTPOINT}\"\n\tif [ ${?} -eq 0 ]\n\tthen\n\t\treturn\n\tfi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT -gt 1 ];\n    then\n    \tif [ $iscentos -eq 0 ];\n    \tthen\n       \t    create_raid0_centos\n    \telif [ $isubuntu -eq 0 ];\n    \tthen\n            create_raid0_ubuntu\n    \tfi\n        do_partition ${RAIDDISK}\n        PARTITION=\"${RAIDPARTITION}\"\n    else\n        DISK=\"${DISKS[0]}\"\n        do_partition ${DISK}\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 lazy_itable_init=1 ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nopen_ports() {\n    iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4444 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4567 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4568 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 9200 -j ACCEPT\n    iptables-save\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=disabled/I' /etc/selinux/config\n    setenforce 0\n}\n\nactivate_secondnic_centos() {\n    if [ -n \"$SECONDNIC\" ];\n    then\n        cp /etc/sysconfig/network-scripts/ifcfg-eth0 \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        sed -i \"s/^DEVICE=.*/DEVICE=${SECONDNIC}/I\" \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        defaultgw=$(ip route show |sed -n \"s/^default via //p\")\n        declare -a gateway=(${defaultgw// / })\n        sed -i \"\\$aGATEWAY=${gateway[0]}\" /etc/sysconfig/network\n        service network restart\n    fi\n}\n\nconfigure_network() {\n    open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        activate_secondnic_centos\n        disable_selinux_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        disable_apparmor_ubuntu\n    fi\n}\n\ncreate_mycnf() {\n    wget \"${MYCNFTEMPLATE}\" -O /etc/my.cnf\n    sed -i \"s/^wsrep_cluster_address=.*/wsrep_cluster_address=gcomm:\\/\\/${CLUSTERADDRESS}/I\" /etc/my.cnf\n    sed -i \"s/^wsrep_node_address=.*/wsrep_node_address=${NODEADDRESS}/I\" /etc/my.cnf\n    sed -i \"s/^wsrep_node_name=.*/wsrep_node_name=${NODENAME}/I\" /etc/my.cnf\n    if [ $isubuntu -eq 0 ];\n    then\n        sed -i \"s/^wsrep_provider=.*/wsrep_provider=\\/usr\\/lib\\/libgalera_smm.so/I\" /etc/my.cnf\n    fi\n}\n\ninstall_mysql_ubuntu() {\n    dpkg -s percona-xtradb-cluster-56\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    apt-key adv --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A\n    grep \"repo.percona.com\" /etc/apt/sources.list >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        echo \"deb http://repo.percona.com/apt precise main\" >> /etc/apt/sources.list\n        echo \"deb-src http://repo.percona.com/apt precise main\" >> /etc/apt/sources.list\n    fi\n    apt-get update\n    export DEBIAN_FRONTEND=noninteractive\n    apt-get -q -y install percona-xtradb-cluster-56\n    apt-get -y install xinetd\n}\n\ninstall_mysql_centos() {\n    yum list installed Percona-XtraDB-Cluster-56\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    yum -y install http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1-3.noarch.rpm\n\twget --no-cache https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\n\trpm -Uvh epel-release-latest-6.noarch.rpm\n\tyum -y install libev\n    yum -y install Percona-XtraDB-Cluster-56\n    yum -y install xinetd\n}\n\nconfigure_mysql() {\n    /etc/init.d/mysql status\n\tif [ ${?} -eq 0 ];\n    then\n\t   return\n\tfi\n    create_mycnf\n\n    mkdir \"${MOUNTPOINT}/mysql\"\n    ln -s \"${MOUNTPOINT}/mysql\" /var/lib/mysql\n    chmod o+x /var/lib/mysql\n    if [ $iscentos -eq 0 ];\n    then\n        install_mysql_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        install_mysql_ubuntu\n    fi\n    /etc/init.d/mysql stop\n    chmod o+x \"${MOUNTPOINT}/mysql\"\n\n    grep \"mysqlchk\" /etc/services >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        sed -i \"\\$amysqlchk  9200\\/tcp  #mysqlchk\" /etc/services\n    fi\n    service xinetd restart\n\n    sstmethod=$(sed -n \"s/^wsrep_sst_method=//p\" /etc/my.cnf)\n    sst=$(sed -n \"s/^wsrep_sst_auth=//p\" /etc/my.cnf | cut -d'\"' -f2)\n    declare -a sstauth=(${sst//:/ })\n    if [ $sstmethod == \"mysqldump\" ]; #requires root privilege for sstuser on every node\n    then\n        /etc/init.d/mysql bootstrap-pxc\n        echo \"CREATE USER '${sstauth[0]}'@'localhost' IDENTIFIED BY '${sstauth[1]}';\" > /tmp/mysqldump-pxc.sql\n        echo \"GRANT ALL PRIVILEGES ON *.* TO '${sstauth[0]}'@'localhost' with GRANT OPTION;\" >> /tmp/mysqldump-pxc.sql\n        echo \"CREATE USER '${sstauth[0]}'@'%' IDENTIFIED BY '${sstauth[1]}';\" >> /tmp/mysqldump-pxc.sql\n        echo \"GRANT ALL PRIVILEGES ON *.* TO '${sstauth[0]}'@'%' with GRANT OPTION;\" >> /tmp/mysqldump-pxc.sql\n        echo \"FLUSH PRIVILEGES;\" >> /tmp/mysqldump-pxc.sql\n        mysql < /tmp/mysqldump-pxc.sql\n        /etc/init.d/mysql stop\n    fi\n    /etc/init.d/mysql $MYSQLSTARTUP\n    if [ $MYSQLSTARTUP == \"bootstrap-pxc\" ];\n    then\n        if [ $sstmethod != \"mysqldump\" ];\n        then\n            echo \"CREATE USER '${sstauth[0]}'@'localhost' IDENTIFIED BY '${sstauth[1]}';\" > /tmp/bootstrap-pxc.sql\n            echo \"GRANT RELOAD, LOCK TABLES, REPLICATION CLIENT ON *.* TO '${sstauth[0]}'@'localhost';\" >> /tmp/bootstrap-pxc.sql\n        fi\n        echo \"CREATE USER 'clustercheckuser'@'localhost' identified by 'clustercheckpassword!';\" >> /tmp/bootstrap-pxc.sql\n        echo \"GRANT PROCESS on *.* to 'clustercheckuser'@'localhost';\" >> /tmp/bootstrap-pxc.sql\n        echo \"CREATE USER 'test'@'%' identified by '${sstauth[1]}';\" >> /tmp/bootstrap-pxc.sql\n        echo \"GRANT select on *.* to 'test'@'%';\" >> /tmp/bootstrap-pxc.sql\n        echo \"FLUSH PRIVILEGES;\" >> /tmp/bootstrap-pxc.sql\n        mysql < /tmp/bootstrap-pxc.sql\n    fi\n}\n\nallow_passwordssh() {\n\tgrep -q '^PasswordAuthentication yes' /etc/ssh/sshd_config\n    if [ ${?} -eq 0 ];\n    then\n\t\treturn\n\tfi\n    sed -i \"s/^#PasswordAuthentication.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n    sed -i \"s/^PasswordAuthentication no.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n\t/etc/init.d/sshd reload\n}\n\n# temporary workaround form CRP\nallow_passwordssh\n\ncheck_os\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0 ];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_mysql\nfi\n\n", "num_lines": 326}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 6.5 and Ubuntu 12.04 LTS with Percona XtraDB Cluster 5.6.\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of DeployPXC powershell script or runbook or Azure Resource Manager CRP template.\n\nCLUSTERADDRESS=${1}\nNODEADDRESS=${2}\nNODENAME=$(hostname)\nMYSQLSTARTUP=${3}\nMYCNFTEMPLATE=${4}\nSECONDNIC=${5}\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=512\n\nRAIDDISK=\"/dev/md127\"\nRAIDPARTITION=\"/dev/md127p1\"\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ncreate_raid0_ubuntu() {\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        wget --no-cache http://mirrors.cat.pdx.edu/ubuntu/pool/main/m/mdadm/mdadm_3.2.5-5ubuntu4_amd64.deb\n        dpkg -i mdadm_3.2.5-5ubuntu4_amd64.deb\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ncreate_raid0_centos() {\n    echo \"Creating raid0\"\n    yes | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n\tls \"${MOUNTPOINT}\"\n\tif [ ${?} -eq 0 ]\n\tthen\n\t\treturn\n\tfi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT -gt 1 ];\n    then\n    \tif [ $iscentos -eq 0 ];\n    \tthen\n       \t    create_raid0_centos\n    \telif [ $isubuntu -eq 0 ];\n    \tthen\n            create_raid0_ubuntu\n    \tfi\n        do_partition ${RAIDDISK}\n        PARTITION=\"${RAIDPARTITION}\"\n    else\n        DISK=\"${DISKS[0]}\"\n        do_partition ${DISK}\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 lazy_itable_init=1 ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nopen_ports() {\n    iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4444 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4567 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 4568 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 9200 -j ACCEPT\n    iptables-save\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=disabled/I' /etc/selinux/config\n    setenforce 0\n}\n\nactivate_secondnic_centos() {\n    if [ -n \"$SECONDNIC\" ];\n    then\n        cp /etc/sysconfig/network-scripts/ifcfg-eth0 \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        sed -i \"s/^DEVICE=.*/DEVICE=${SECONDNIC}/I\" \"/etc/sysconfig/network-scripts/ifcfg-${SECONDNIC}\"\n        defaultgw=$(ip route show |sed -n \"s/^default via //p\")\n        declare -a gateway=(${defaultgw// / })\n        sed -i \"\\$aGATEWAY=${gateway[0]}\" /etc/sysconfig/network\n        service network restart\n    fi\n}\n\nconfigure_network() {\n    open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        activate_secondnic_centos\n        disable_selinux_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        disable_apparmor_ubuntu\n    fi\n}\n\ncreate_mycnf() {\n    wget \"${MYCNFTEMPLATE}\" -O /etc/my.cnf\n    sed -i \"s/^wsrep_cluster_address=.*/wsrep_cluster_address=gcomm:\\/\\/${CLUSTERADDRESS}/I\" /etc/my.cnf\n    sed -i \"s/^wsrep_node_address=.*/wsrep_node_address=${NODEADDRESS}/I\" /etc/my.cnf\n    sed -i \"s/^wsrep_node_name=.*/wsrep_node_name=${NODENAME}/I\" /etc/my.cnf\n    if [ $isubuntu -eq 0 ];\n    then\n        sed -i \"s/^wsrep_provider=.*/wsrep_provider=\\/usr\\/lib\\/libgalera_smm.so/I\" /etc/my.cnf\n    fi\n}\n\ninstall_mysql_ubuntu() {\n    dpkg -s percona-xtradb-cluster-56\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    apt-key adv --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A\n    grep \"repo.percona.com\" /etc/apt/sources.list >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        echo \"deb http://repo.percona.com/apt precise main\" >> /etc/apt/sources.list\n        echo \"deb-src http://repo.percona.com/apt precise main\" >> /etc/apt/sources.list\n    fi\n    apt-get update\n    export DEBIAN_FRONTEND=noninteractive\n    apt-get -q -y install percona-xtradb-cluster-56\n    apt-get -y install xinetd\n}\n\ninstall_mysql_centos() {\n    yum list installed Percona-XtraDB-Cluster-56\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    yum -y install http://www.percona.com/downloads/percona-release/redhat/0.1-3/percona-release-0.1-3.noarch.rpm\n\twget --no-cache https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm\n\trpm -Uvh epel-release-latest-6.noarch.rpm\n\tyum -y install libev\n    yum -y install Percona-XtraDB-Cluster-56\n    yum -y install xinetd\n}\n\nconfigure_mysql() {\n    /etc/init.d/mysql status\n\tif [ ${?} -eq 0 ];\n    then\n\t   return\n\tfi\n    create_mycnf\n\n    mkdir \"${MOUNTPOINT}/mysql\"\n    ln -s \"${MOUNTPOINT}/mysql\" /var/lib/mysql\n    chmod o+x /var/lib/mysql\n    if [ $iscentos -eq 0 ];\n    then\n        install_mysql_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        install_mysql_ubuntu\n    fi\n    /etc/init.d/mysql stop\n    chmod o+x \"${MOUNTPOINT}/mysql\"\n\n    grep \"mysqlchk\" /etc/services >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        sed -i \"\\$amysqlchk  9200\\/tcp  #mysqlchk\" /etc/services\n    fi\n    service xinetd restart\n\n    sstmethod=$(sed -n \"s/^wsrep_sst_method=//p\" /etc/my.cnf)\n    sst=$(sed -n \"s/^wsrep_sst_auth=//p\" /etc/my.cnf | cut -d'\"' -f2)\n    declare -a sstauth=(${sst//:/ })\n    if [ $sstmethod == \"mysqldump\" ]; #requires root privilege for sstuser on every node\n    then\n        /etc/init.d/mysql bootstrap-pxc\n        echo \"CREATE USER '${sstauth[0]}'@'localhost' IDENTIFIED BY '${sstauth[1]}';\" > /tmp/mysqldump-pxc.sql\n        echo \"GRANT ALL PRIVILEGES ON *.* TO '${sstauth[0]}'@'localhost' with GRANT OPTION;\" >> /tmp/mysqldump-pxc.sql\n        echo \"CREATE USER '${sstauth[0]}'@'%' IDENTIFIED BY '${sstauth[1]}';\" >> /tmp/mysqldump-pxc.sql\n        echo \"GRANT ALL PRIVILEGES ON *.* TO '${sstauth[0]}'@'%' with GRANT OPTION;\" >> /tmp/mysqldump-pxc.sql\n        echo \"FLUSH PRIVILEGES;\" >> /tmp/mysqldump-pxc.sql\n        mysql < /tmp/mysqldump-pxc.sql\n        /etc/init.d/mysql stop\n    fi\n    /etc/init.d/mysql $MYSQLSTARTUP\n    if [ $MYSQLSTARTUP == \"bootstrap-pxc\" ];\n    then\n        if [ $sstmethod != \"mysqldump\" ];\n        then\n            echo \"CREATE USER '${sstauth[0]}'@'localhost' IDENTIFIED BY '${sstauth[1]}';\" > /tmp/bootstrap-pxc.sql\n            echo \"GRANT RELOAD, LOCK TABLES, REPLICATION CLIENT ON *.* TO '${sstauth[0]}'@'localhost';\" >> /tmp/bootstrap-pxc.sql\n        fi\n        echo \"CREATE USER 'clustercheckuser'@'localhost' identified by 'clustercheckpassword!';\" >> /tmp/bootstrap-pxc.sql\n        echo \"GRANT PROCESS on *.* to 'clustercheckuser'@'localhost';\" >> /tmp/bootstrap-pxc.sql\n        echo \"CREATE USER 'test'@'%' identified by '${sstauth[1]}';\" >> /tmp/bootstrap-pxc.sql\n        echo \"GRANT select on *.* to 'test'@'%';\" >> /tmp/bootstrap-pxc.sql\n        echo \"FLUSH PRIVILEGES;\" >> /tmp/bootstrap-pxc.sql\n        mysql < /tmp/bootstrap-pxc.sql\n    fi\n}\n\nallow_passwordssh() {\n\tgrep -q '^PasswordAuthentication yes' /etc/ssh/sshd_config\n    if [ ${?} -eq 0 ];\n    then\n\t\treturn\n\tfi\n    sed -i \"s/^#PasswordAuthentication.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n    sed -i \"s/^PasswordAuthentication no.*/PasswordAuthentication yes/I\" /etc/ssh/sshd_config\n\t/etc/init.d/sshd reload\n}\n\n# temporary workaround form CRP\nallow_passwordssh\n\ncheck_os\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0 ];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_mysql\nfi\n\n", "num_lines": 326}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmysqlPassword=$1\nosUser=$2\n\n#install mha manager\ncd /tmp/\nwget http://mysql-master-ha.googlecode.com/files/mha4mysql-node_0.53_all.deb > /dev/null 2>&1\nwget http://mysql-master-ha.googlecode.com/files/mha4mysql-manager_0.53_all.deb > /dev/null 2>&1\napt-get update > /dev/null 2>&1\napt-get install libdbd-mysql-perl -y > /dev/null 2>&1\napt-get install libconfig-tiny-perl -y > /dev/null 2>&1\napt-get install liblog-dispatch-perl -y > /dev/null 2>&1\napt-get install libparallel-forkmanager-perl -y > /dev/null 2>&1\ndpkg -i mha4mysql-node_0.53_all.deb > /dev/null 2>&1\ndpkg -i mha4mysql-manager_0.53_all.deb > /dev/null 2>&1\n\n#install mysql-client\napt-get install mysql-client -y > /dev/null 2>&1\n\n#configure mha manager\nmkdir -p /var/log/masterha/app1\nmkdir -p /script/masterha\ncat > /etc/app1.cnf <<EOF\n[server default]\n# mysql user and password\nuser=root\npassword=$mysqlPassword\nssh_user=$osUser\nmaster_binlog_dir= /var/log/mysql\n# working directory on the manager\nmanager_workdir=/var/log/masterha/app1\n# manager log file\nmanager_log=/var/log/masterha/app1/app1.log\n# working directory on MySQL servers\nremote_workdir=/var/log/masterha/app1\nsecondary_check_script= masterha_secondary_check -s 10.0.0.11 -s 10.0.0.12\nping_interval=1\n#master_ip_failover_script=/script/masterha/master_ip_failover\n#shutdown_script= /script/masterha/power_manager\n#report_script= /script/masterha/send_report\n\n[server1]\nhostname=10.0.0.10\n\n[server2]\nhostname=10.0.0.11\ncandidate_master=1\n\n[server3]\nhostname=10.0.0.12\nno_master=1\nEOF\n\n\n#install haproxy\ncd /tmp\nwget http://www.haproxy.org/download/1.6/src/haproxy-1.6.3.tar.gz > /dev/null 2>&1\ntar zxvf haproxy-1.6.3.tar.gz\ncd haproxy-1.6.3\napt-get install make gcc -y > /dev/null 2>&1\n\nmake TARGET=linux2628 PREFIX=/usr/local/haproxy\nmake install PREFIX=/usr/local/haproxy\ncat > /usr/local/haproxy/haproxy.cfg <<EOF\nglobal\n       maxconn 4096\n       chroot /usr/local/haproxy\n        uid 99\n        gid 99\n       daemon\n       pidfile /usr/local/haproxy/haproxy.pid\n\ndefaults\n       log    global\n        log     127.0.0.1       local3\n       mode    tcp\n       option  tcplog\n        option  dontlognull\n        option  httpclose\n       retries 3\n       option  redispatch\n       maxconn 2000\n       timeout connect     5000\n       timeout client     50000\n       timeout server     50000\n\nfrontend mysqlwrite-in\n       bind *:3306\n        mode    tcp\n        option  tcplog\n        log     global\n        default_backend mysqlwritepool\n\nfrontend mysqlread-in\n      bind *:3307\n      mode tcp\n      option tcplog\n      log global\n      default_backend mysqlreadpool\n\nbackend mysqlwritepool\n       balance roundrobin\n       server  mysql01 10.0.0.10:3306  weight 5 check inter 2000 rise 2 fall 3\n\nbackend mysqlreadpool\n       balance roundrobin\n        server  10.0.0.11 10.0.0.11:3306  weight 5 check inter 2000 rise 2 fall 3\n        server  10.0.0.12 10.0.0.12:3306  weight 5 check inter 2000 rise 2 fall 3\nEOF\n\n\n#master ip check script\ncat > /usr/local/haproxy/master_ip_check.sh <<EOF\n#!/usr/bin/env bash\nhaproxyDir=/usr/local/haproxy\nhaproxyConFile=/usr/local/haproxy/haproxy.cfg\nhaproxyPidFile=/usr/local/haproxy/haproxy.pid\nmasterIP=\\$1\ncandiMasterIP=\\$2\nmysqlUser=root\nmysqlPass=$mysqlPassword\nusage() {\n\necho \"execution method: \\`basename \\$0\\` masterip candimasterip\n\nMost import thing is the 1st parameter should be the mysql running master ip address; the 2nd parameter is the candidate master ip address\n\"\n}\nif [[ \\$# -ne 2 ]] ;then\nusage\nexit\nfi\nwhile :\ndo\nresult=\\`mysql -u\\$mysqlUser -p\\$mysqlPass -h \\$candiMasterIP -e \"show slave status\\G\"\\`\nif [[ -n \\$result ]];then   #the candidate master is still slave\n\nslaveRunningNumber=\\`mysql -u\\$mysqlUser -p\\$mysqlPass -h \\$candiMasterIP -e \"show slave status\\G\" |grep -i \"running: Yes\" |wc -l\\`\n  if [[ \\$slaveRunningNumber -ne 2 ]];then                     #master-slave has problem\n     echo \"checked at \\$(date +\"%F %H:%M:%S\"):candidate master \\$candiMasterIP slave status is not OK, please check ! \"\n  fi\nelse              #the candidate master is no longer slave\nsed -i \"s/\\$masterIP:3306/\\$candiMasterIP:3306/\" \\$haproxyConFile         #master ip failover\n\\$haproxyDir/sbin/haproxy -f \\$haproxyConFile -st \\`cat \\$haproxyPidFile\\`   #reload\n  if [[ \\$? -eq 0 ]];then\n    echo \"at \\$(date +\"%F %H:%M:%S\"): master ip failover, \\$candiMasterIP becomes the master, reloaded haproxy process. \"\n    exit  #quit with mha manager the same time\n  else\n    echo \"at \\$(date +\"%F %H:%M:%S\"): reloaded haproxy process failed. Please check haproxy ! quit the shell script ! \"\n    exit\n  fi\nfi\nsleep 1\ndone\nEOF\n\n\n\n#slave ip check script\ncat > /usr/local/haproxy/slave_ip_check.sh <<EOF\n#!/usr/bin/env bash\nhaproxyDir=/usr/local/haproxy\nhaproxyConFile=/usr/local/haproxy/haproxy.cfg\nhaproxyPidFile=/usr/local/haproxy/haproxy.pid\nmysqlBackendReadPool=mysqlreadpool\nmysqlUser=root\nmysqlPass=$mysqlPassword\n\nusage() {\n\necho \"execution method: \\`basename \\$0\\` slaveip1 slaveip2 ...\n\n\"\n}\n\nrestartHaproxy() {\n\\$haproxyDir/sbin/haproxy -f \\$haproxyConFile -st \\`cat \\$haproxyPidFile\\`   #reload\nif [[ \\$? -eq 0 ]];then\n  echo \"at \\$(date +\"%F %H:%M:%S\"): reloaded haproxy process. \"\nelse\n  echo \"at \\$(date +\"%F %H:%M:%S\"): reloaded haproxy process failed. Please check haproxy ! \"\nfi\n}\n\nif [[ \\$# -eq 0 ]] ;then\nusage\nexit\nfi\n\n\nwhile :\ndo\nfor slaveIP in \"\\$@\"\ndo\nresult=\\`mysql -u\\$mysqlUser -p\\$mysqlPass -h \\$slaveIP -e \"show slave status\\G\"\\`\nslaveResult=\\`sed -n \"/^backend.*\\$mysqlBackendReadPool/,/^backend/{/\\$slaveIP/p}\" \\$haproxyConFile\\`\nif [[ -n \\$result ]];then   #the slave is still slave\n\nslaveRunningNumber=\\`mysql -u\\$mysqlUser -p\\$mysqlPass -h \\$slaveIP -e \"show slave status\\G\" |grep -i \"running: Yes\" |wc -l\\`\n  if [[ \\$slaveRunningNumber -ne 2 ]];then                      #master-slave has problem\n     echo \"checked at \\$(date +\"%F %H:%M:%S\"):MySQL \\$slaveIP slave status is not OK, please check ! \"\n  elif [[ -z \\$slaveResult ]];then  #slave is not in the read pool\n      #add the slave in the read pool\n      sed -i \"/^backend.*\\$mysqlBackendReadPool/,/^backend/{:a;N;s/balance.*/&\\n        server  \\$slaveIP \\$slaveIP:3306  weight 5 check inter 2000 rise 2 fall 3/}\" \\$haproxyConFile\n      restartHaproxy\n  fi\nelse              #the slave is no longer slave\n  sed -i \"/^backend.*\\$mysqlBackendReadPool/,/^backend/{/\\$slaveIP/d}\" \\$haproxyConFile         #remove from the read pool\n  restartHaproxy\n  exit   #quit with mha manager the same time\nfi\nsleep 1\ndone\ndone\nEOF\n\nsed -i '/my \\$msg  = \\$args{message};$/a $msg = \\\"\\\" unless($msg);' /usr/share/perl5/MHA/ManagerConst.pm\nsed -i 's/^\\($msg = \"\" unless($msg);\\)$/  \\1/' /usr/share/perl5/MHA/ManagerConst.pm\nchown ${osUser}:${osUser} /etc/app1.cnf\nchmod 600 /etc/app1.cnf\nchown ${osUser}:${osUser} -R /var/log/masterha/\nchown ${osUser}:${osUser} /usr/local/haproxy/master_ip_check.sh\nchown ${osUser}:${osUser} /usr/local/haproxy/slave_ip_check.sh\nchmod 700 /usr/local/haproxy/master_ip_check.sh\nchmod 700 /usr/local/haproxy/slave_ip_check.sh\n\n", "num_lines": 228}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmysqlPassword=$1\nosUser=$2\n\napt-get update\n\n#another way of installing mysql server in a Non-Interactive mode\necho \"mysql-server-5.6 mysql-server/root_password password $mysqlPassword\" | sudo debconf-set-selections\necho \"mysql-server-5.6 mysql-server/root_password_again password $mysqlPassword\" | sudo debconf-set-selections\n\n#install mysql-server 5.5\napt-get -y install mysql-server\n\n#configure mysql\nsed -i 's/^bind-address/#bind-address/' /etc/mysql/my.cnf\nsed -i 's/^#server-id/server-id/' /etc/mysql/my.cnf\nsed -i 's/#log_bin/log_bin/' /etc/mysql/my.cnf\nmysql -uroot -p$mysqlPassword -e \"grant replication slave on *.* to 'repluser'@'%' identified by 'replpass';grant all privileges on *.* to 'root'@'%' identified by '$mysqlPassword';flush privileges;\"\nservice mysql restart\n\n#install mha node\ncd /tmp/\nwget http://mysql-master-ha.googlecode.com/files/mha4mysql-node_0.53_all.deb > /dev/null 2>&1\napt-get update\napt-get install libdbd-mysql-perl -y\ndpkg -i mha4mysql-node_0.53_all.deb\n\n\nmkdir /var/log/masterha/\nchown ${osUser}:${osUser} -R /var/log/masterha/\napt-get install acl -y\nsetfacl -m u:${osUser}:rx /var/lib/mysql\nsetfacl -Rdm u:${osUser}:r /var/lib/mysql\nsetfacl -m u:${osUser}:r /var/lib/mysql/*\n\n\n\n", "num_lines": 39}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmysqlPassword=$1\nosUser=$2\n\napt-get update\n\n#another way of installing mysql server in a Non-Interactive mode\necho \"mysql-server-5.6 mysql-server/root_password password $mysqlPassword\" | sudo debconf-set-selections\necho \"mysql-server-5.6 mysql-server/root_password_again password $mysqlPassword\" | sudo debconf-set-selections\n\n#install mysql-server 5.5\napt-get -y install mysql-server\n\n#configure mysql\nsed -i 's/^bind-address/#bind-address/' /etc/mysql/my.cnf\nsed -i 's/^#server-id/server-id/' /etc/mysql/my.cnf\nsed -i 's/#log_bin/log_bin/' /etc/mysql/my.cnf\nsed -i 's/server-id.*/server-id = 2/' /etc/mysql/my.cnf\nsed -i '/\\[mysqld\\]/a replicate-ignore-db = mysql' /etc/mysql/my.cnf    #ignore db mysql replication\nmysql -uroot -p$mysqlPassword -e \"grant replication slave on *.* to 'repluser'@'%' identified by 'replpass';grant all privileges on *.* to 'root'@'%' identified by '$mysqlPassword';flush privileges;\"\nservice mysql restart\n\n#master-slave replication\nmysql -uroot -p$mysqlPassword -e \"change master to master_host='10.0.0.10',master_user='repluser',master_password='replpass';start slave;\"\nslaveStatus=`mysql -uroot -p$mysqlPassword -e \"show slave status\\G\" |grep -i \"Running: Yes\"|wc -l`\nif [[ $slaveStatus -ne 2 ]];then\necho \"master-slave replication issue!\"\nfi\n\n#install mha node\ncd /tmp/\nwget http://mysql-master-ha.googlecode.com/files/mha4mysql-node_0.53_all.deb > /dev/null 2>&1\napt-get update\napt-get install libdbd-mysql-perl -y\ndpkg -i mha4mysql-node_0.53_all.deb\n\n\nmkdir /var/log/masterha/\nchown ${osUser}:${osUser} -R /var/log/masterha/\napt-get install acl -y\nsetfacl -m u:${osUser}:rx /var/lib/mysql\nsetfacl -Rdm u:${osUser}:r /var/lib/mysql\nsetfacl -m u:${osUser}:r /var/lib/mysql/*\n", "num_lines": 45}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmysqlPassword=$1\nosUser=$2\n\napt-get update\n\n#another way of installing mysql server in a Non-Interactive mode\necho \"mysql-server-5.6 mysql-server/root_password password $mysqlPassword\" | sudo debconf-set-selections\necho \"mysql-server-5.6 mysql-server/root_password_again password $mysqlPassword\" | sudo debconf-set-selections\n\n#install mysql-server 5.5\napt-get -y install mysql-server\n\n#configure mysql\nsed -i 's/^bind-address/#bind-address/' /etc/mysql/my.cnf\nsed -i 's/^#server-id/server-id/' /etc/mysql/my.cnf\nsed -i 's/#log_bin/log_bin/' /etc/mysql/my.cnf\nsed -i 's/server-id.*/server-id = 3/' /etc/mysql/my.cnf\nsed -i '/\\[mysqld\\]/a replicate-ignore-db = mysql' /etc/mysql/my.cnf    #ignore db mysql replication\nmysql -uroot -p$mysqlPassword -e \"grant replication slave on *.* to 'repluser'@'%' identified by 'replpass';grant all privileges on *.* to 'root'@'%' identified by '$mysqlPassword';flush privileges;\"\nservice mysql restart\n\n#master-slave replication\nmysql -uroot -p$mysqlPassword -e \"change master to master_host='10.0.0.10',master_user='repluser',master_password='replpass';start slave;\"\nslaveStatus=`mysql -uroot -p$mysqlPassword -e \"show slave status\\G\" |grep -i \"Running: Yes\"|wc -l`\nif [[ $slaveStatus -ne 2 ]];then\necho \"master-slave replication issue!\"\nfi\n\n#install mha node\ncd /tmp/\nwget http://mysql-master-ha.googlecode.com/files/mha4mysql-node_0.53_all.deb > /dev/null 2>&1\napt-get update\napt-get install libdbd-mysql-perl -y\ndpkg -i mha4mysql-node_0.53_all.deb\n\nmkdir /var/log/masterha/\nchown ${osUser}:${osUser} -R /var/log/masterha/\napt-get install acl -y\nsetfacl -m u:${osUser}:rx /var/lib/mysql\nsetfacl -Rdm u:${osUser}:r /var/lib/mysql\nsetfacl -m u:${osUser}:r /var/lib/mysql/*\n", "num_lines": 44}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 6.5 and Ubuntu 12.04 LTS with Percona XtraDB Cluster 5.6.\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of DeployPXC powershell script or runbook or Azure Resource Manager CRP template.\n\nNODEID=${1}\nNODEADDRESS=${2}\nMYCNFTEMPLATE=${3}\nRPLPWD=${4}\nROOTPWD=${5}\nPROBEPWD=${6}\nMASTERIP=${7}\nVERSION=5.5\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=512\n\nRAIDDISK=\"/dev/md127\"\nRAIDPARTITION=\"/dev/md127p1\"\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ncreate_raid0_ubuntu() {\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        wget --no-cache http://mirrors.cat.pdx.edu/ubuntu/pool/main/m/mdadm/mdadm_3.2.5-5ubuntu4_amd64.deb\n        dpkg -i mdadm_3.2.5-5ubuntu4_amd64.deb\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ncreate_raid0_centos() {\n    echo \"Creating raid0\"\n    yes | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n\tls \"${MOUNTPOINT}\"\n\tif [ ${?} -eq 0 ]\n\tthen\n\t\treturn\n\tfi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT -gt 1 ];\n    then\n    \tif [ $iscentos -eq 0 ];\n    \tthen\n       \t    create_raid0_centos\n    \telif [ $isubuntu -eq 0 ];\n    \tthen\n            create_raid0_ubuntu\n    \tfi\n        do_partition ${RAIDDISK}\n        PARTITION=\"${RAIDPARTITION}\"\n    else\n        DISK=\"${DISKS[0]}\"\n        do_partition ${DISK}\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 -E lazy_itable_init=1 ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nopen_ports() {\n    iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 9200 -j ACCEPT\n    iptables-save\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor stop\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n    apt-get remove apparmor apparmor-utils -y\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=disabled/I' /etc/selinux/config\n    setenforce 0\n}\n\nconfigure_network() {\n    open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        disable_selinux_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        disable_apparmor_ubuntu\n    fi\n}\n\ncreate_mycnf() {\n    wget \"${MYCNFTEMPLATE}\" -O /etc/my.cnf\n    sed -i \"s/^server_id=.*/server_id=${NODEID}/I\" /etc/my.cnf\n    sed -i \"s/^report-host=.*/report-host=${NODEADDRESS}/I\" /etc/my.cnf\n    sed -i \"s/^bind-address.*/bind-address=0.0.0.0/I\" /etc/mysql/my.cnf\n}\n\ninstall_mysql_ubuntu() {\n    dpkg -s mysql-$VERSION\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    apt-get update\n    export DEBIAN_FRONTEND=noninteractive\n\tapt-get install -y mysql-server-$VERSION\n\tchown -R mysql:mysql \"${MOUNTPOINT}/mysql/mysql\"\n\tapt-get install -y mysql-server-$VERSION\n\twget http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python_2.1.3-1ubuntu14.04_all.deb\n\tdpkg -i mysql-connector-python_2.1.3-1ubuntu14.04_all.deb\n\twget http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-utilities_1.6.4-1ubuntu14.04_all.deb\n    dpkg -i mysql-utilities_1.6.4-1ubuntu14.04_all.deb\n    apt-get -y install xinetd\n}\n\ninstall_mysql_centos() {\n    rpm -qa |grep MySQL-server-5.6.26-1.el6.x86_64\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    wget https://dev.mysql.com/get/Downloads/MySQL-5.6/MySQL-5.6.26-1.el6.x86_64.rpm-bundle.tar\n    tar -xvf MySQL-5.6.26-1.el6.x86_64.rpm-bundle.tar\n\tcurlib=$(rpm -qa |grep mysql-libs-)\n    rpm -e --nodeps $curlib\n    rpm -ivh MySQL-server-5.6.26-1.el6.x86_64.rpm\n    rpm -ivh MySQL-client-5.6.26-1.el6.x86_64.rpm\n\twget http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.0.4-1.el6.noarch.rpm\n\trpm -ivh mysql-connector-python-2.0.4-1.el6.noarch.rpm\n\twget http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-utilities-1.5.5-1.el6.noarch.rpm\n\trpm -ivh mysql-utilities-1.5.5-1.el6.noarch.rpm\n    yum -y install xinetd\n}\n\ncreate_mysql_probe() {\nif [ ${NODEID} -eq 1 ];\nthen\n# create a probe user with minimum privilege\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nCREATE USER 'probeuser'@'%' IDENTIFIED BY '${PROBEPWD}';\nGRANT SELECT ON *.* TO 'probeuser'@'%';\nFLUSH PRIVILEGES;\nEOF\nfi\n\n# create a probe script\n    cat <<EOF >/usr/bin/mysqlprobe\n#!/bin/bash\n\nMYSQL_HOST=\"${NODEADDRESS}\"\nMYSQL_USERNAME=\"probeuser\"\nMYSQL_PASSWORD='${PROBEPWD}'\n\nERROR_MSG=\\`/usr/bin/mysqladmin --host=\\${MYSQL_HOST} --port=3306 --user=\\${MYSQL_USERNAME} --password=\\${MYSQL_PASSWORD} status 2>/dev/null\\`\n#ERROR_MSG=\\`/usr/bin/mysql --host=\\${MYSQL_HOST} --port=3306 --user=\\${MYSQL_USERNAME} --password=\\${MYSQL_PASSWORD} -e \"show databases;\" 2>/dev/null\\`\n\nif [ \"\\$ERROR_MSG\" != \"\" ]\nthen\n        # mysql is fine, return http 200\n        echo -en \"HTTP/1.1 200 OK\\r\\n\"\n        echo -en \"Content-Type: text/plain\\r\\n\"\n        echo -en \"Connection: close\\r\\n\"\n        echo -en \"Content-Length: 19\\r\\n\"\n        echo -en \"\\r\\n\"\n        echo -en \"MySQL is running.\\r\\n\"\n        sleep 0.1\n        exit 0\nelse\n        # mysql is down, return http 503\n        echo -en \"HTTP/1.1 503 Service Unavailable\\r\\n\"\n        echo -en \"Content-Type: text/plain\\r\\n\"\n        echo -en \"Connection: close\\r\\n\"\n        echo -en \"Content-Length: 16\\r\\n\"\n        echo -en \"\\r\\n\"\n        echo -en \"MySQL is down.\\r\\n\"\n        sleep 0.1\n        exit 1\nfi\nEOF\n\nchmod 755 /usr/bin/mysqlprobe\n\n# create a http service that runs the script\n    cat <<EOF >/etc/xinetd.d/mysqlprobe\n# default: on\n# description: mysqlprobe\nservice mysqlprobe\n{\n        disable = no\n        flags = REUSE\n        socket_type = stream\n        port = 9200\n        wait = no\n        user = nobody\n        server = /usr/bin/mysqlprobe\n        log_on_failure += USERID\n        only_from = 0.0.0.0/0\n        per_source = UNLIMITED\n}\nEOF\n\n# add the service to xinet\n    grep \"mysqlprobe\" /etc/services >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        sed -i \"\\$amysqlprobe  9200\\/tcp  #mysqlprobe\" /etc/services\n    fi\n    service xinetd restart\n}\n\nconfigure_mysql_replication() {\nif [ ${NODEID} -eq 1 ];\nthen\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nCREATE USER 'rpluser'@'%' IDENTIFIED BY '${RPLPWD}';\nGRANT REPLICATION SLAVE ON *.* TO 'rpluser'@'%';\nFLUSH PRIVILEGES;\nEOF\nelse\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nchange master to master_host='${MASTERIP}', master_port=3306, master_user='rpluser', master_password='${RPLPWD}', master_auto_position=1;\nSTART slave;\nEOF\nfi\n}\n\nconfigure_mysql() {\n    /etc/init.d/mysql status\n    if [ ${?} -eq 0 ];\n    then\n       return\n    fi\n\n    mkdir \"${MOUNTPOINT}/mysql\"\n    ln -s \"${MOUNTPOINT}/mysql\" /var/lib/mysql\n    chmod o+x /var/lib/mysql\n    groupadd mysql\n    useradd -r -g mysql mysql\n    chmod o+x \"${MOUNTPOINT}/mysql\"\n    chown -R mysql:mysql \"${MOUNTPOINT}/mysql\"\n\n    if [ $iscentos -eq 0 ];\n    then\n        install_mysql_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        install_mysql_ubuntu\n    fi\n\n    create_mycnf\n    /etc/init.d/mysql restart\n    mysql_secret=$(awk '/password/{print $NF}' ${HOME}/.mysql_secret)\n    mysqladmin -u root --password=${mysql_secret} password ${ROOTPWD}\nif [ ${NODEID} -eq 1 ];\nthen\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nSET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('${ROOTPWD}');\nSET PASSWORD FOR 'root'@'::1' = PASSWORD('${ROOTPWD}');\nCREATE USER 'admin'@'%' IDENTIFIED BY '${ROOTPWD}';\nGRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' with grant option;\nFLUSH PRIVILEGES;\nEOF\nfi\n    configure_mysql_replication\n    create_mysql_probe\n}\n\ncheck_os\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0 ];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_mysql\n\t#yum -y erase hypervkvpd.x86_64\n\t#yum -y install microsoft-hyper-v\n#\techo \"/sbin/reboot\" | /usr/bin/at now + 3 min >/dev/null 2>&1\nfi\n\n", "num_lines": 377}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmysqlPassword=$1\nsudo apt-get update\n#no password prompt while installing mysql server\n#export DEBIAN_FRONTEND=noninteractive\n\n#another way of installing mysql server in a Non-Interactive mode\necho \"mysql-server-5.6 mysql-server/root_password password $mysqlPassword\" | sudo debconf-set-selections\necho \"mysql-server-5.6 mysql-server/root_password_again password $mysqlPassword\" | sudo debconf-set-selections\n\n#install mysql-server 5.6\nsudo apt-get -y install mysql-server-5.6\n\n#set the password\n#sudo mysqladmin -u root password \"$mysqlPassword\"   #without -p means here the initial password is empty\n\n#alternative update mysql root password method\n#sudo mysql -u root -e \"set password for 'root'@'localhost' = PASSWORD('$mysqlPassword')\"\n#without -p here means the initial password is empty\n\n#sudo service mysql restart\n", "num_lines": 23}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Script parameters and their defaults\nSERVICE_USERNAME=\"nagios\"\nADMIN_USERNAME=\"nagios\"\nADMIN_PASSWORD=\"Zk8LgLeR4ZimcgipTNzJKUBXVABDpYH63B9bzMbh2uRm8gYwRFPhSz8AvYspz3vs\" # Don't worry, this is not the actual password. The real password will be supplied by the ARM template.\nCORE_VERSION=\"4.0.8\"\nPLUGINS_VERSION=\"2.0.3\"\nLOGGING_KEY=\"[logging-key]\"\n\n########################################################\n# This script will install and configure Nagios Core\n########################################################\nhelp()\n{\n\techo \"This script installs and configures Nagios Core on the Ubuntu virtual machine image\"\n\techo \"Available parameters:\"\n\techo \"-u Admin_User_Name\"\n\techo \"-p Admin_User_Password\"\n\techo \"-v Core_Package_Version\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n\t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/${LOGGING_KEY}/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of Nagios Core installation script on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts \":u:p:v:h\" optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n\n  case \"$optname\" in\n\tu) # Admin user name\n\t\tADMIN_USERNAME=${OPTARG}\n\t\t;;\n\tp) # Admin user name\n\t\tADMIN_PASSWORD=${OPTARG}\n\t\t;;\n\tv) # Core package version\n\t\tCORE_VERSION=${OPTARG}\n\t\t;;\n    h)  # Helpful hints\n\t\thelp\n\t\texit 2\n\t\t;;\n    \\?) # Unrecognised option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\n# Install essentials\nlog \"Installing system essentials...\"\napt-get -y update\n\n#  Install Apache (a pre-requisite for Nagios)\nlog \"Installing Apache...\"\napt-get -y install apache2\n\n# Install MySQL (a pre-requisite for Nagios)\nlog \"Installing MySQL...\"\nexport DEBIAN_FRONTEND=noninteractive\napt-get -q -y install mysql-server mysql-client\nmysqladmin -u root password $ADMIN_PASSWORD\n\n# Install PHP (a pre-requisite for Nagios)\nlog \"Installing PHP...\"\napt-get -y install php5 php5-mysql libapache2-mod-php5\n\n# Install LAMP prerequisites\nlog \"Installing other LAMP prerequisites...\"\napt-get -y install build-essential libgd2-xpm-dev apache2-utils\n\n# Restart apache2 service\nlog \"Restarting apache2 service...\"\nservice apache2 restart\n\n# Create a new Nagios user account and give it a password\nlog \"Creating and configuring the Nagios service user account...\"\nuseradd -m $SERVICE_USERNAME\necho '$SERVICE_USERNAME:$ADMIN_PASSWORD' | chpasswd -m\n\n# Create a new nagcmd group for allowing external commands to be submitted through the web interface. Add both the nagios user and the apache user to the group.\nlog \"Creating and configuring the Nagios security group for external access...\"\ngroupadd nagcmd\nusermod -a -G nagcmd $SERVICE_USERNAME\nusermod -a -G nagcmd www-data\n\n# Download Nagios and plugins\nlog \"Downloading Nagios package and plugins...\"\nwget http://prdownloads.sourceforge.net/sourceforge/nagios/nagios-$CORE_VERSION.tar.gz\nwget http://nagios-plugins.org/download/nagios-plugins-$PLUGINS_VERSION.tar.gz\n\n# Install Nagios and plugins\nlog \"Configuring Nagios packages...\"\ntar xzf nagios-$CORE_VERSION.tar.gz\ncd nagios-$CORE_VERSION\n./configure --with-command-group=nagcmd\n\n# Compile and install nagios modules\nlog \"Compiling Nagios packages...\"\nmake all\nmake install\nmake install-init\nmake install-config\nmake install-commandmode\n\n# Install Nagios Web interface\nlog \"Installing the Nagios Web interface...\"\n/usr/bin/install -c -m 644 sample-config/httpd.conf /etc/apache2/sites-enabled/nagios.conf\n\n# Create a nagios admin account for logging into the Nagios web interface.\nlog \"Creating the admin account for logging into the Nagios web interface...\"\nhtpasswd -cb /usr/local/nagios/etc/htpasswd.users $ADMIN_USERNAME $ADMIN_PASSWORD\n\n# Install Nagios plugins\nlog \"Configuring Nagios plugins...\"\ntar xzf nagios-plugins-$PLUGINS_VERSION.tar.gz\ncd nagios-plugins-$PLUGINS_VERSION\n./configure --with-nagios-user=nagios --with-nagios-group=nagios\n\nlog \"Compiling Nagios plugins...\"\nmake\nmake install\n\n# Enable Apache\u00e2\u20ac\u2122s rewrite and cgi modules\nlog \"Enabling Apache modules...\"\na2enmod rewrite\na2enmod cgi\nservice apache2 restart\n\n# Check nagios.conf file for any syntax errors\n/usr/local/nagios/bin/nagios -v /usr/local/nagios/etc/nagios.cfg\n\n# Start nagios service and make it to start automatically on every boot\nlog \"Starting the Nagios service...\"\nservice nagios start\nln -s /etc/init.d/nagios /etc/rcS.d/S99nagios\n\nlog \"Nagios Core was installed successfully\"\n", "num_lines": 176}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is necessary to set up the data disk that will\n# be passed into the Neo4j docker instance and used as the\n# mount point for the Neo4J data.\n\n# The ARM script only mounts a single data disk.  It is safe\n# to assume that on a new VM, this data disk is located at /dev/sdc.\n\n# If you have a more complicated setup, then do examine what this\n# script is doing and modify accordingly.\n\n# create a partition table for the disk\nparted -s /dev/sdc mklabel msdos\n\n# create a single large partition\nparted -s /dev/sdc mkpart primary ext4 0\\% 100\\%\n\n# install the file system\nmkfs.ext4 /dev/sdc1\n\n# create the mount point\nmkdir /datadisk\n\n# mount the disk\nsudo mount /dev/sdc1 /datadisk/\n\n# add mount to /etc/fstab to persist across reboots\necho \"/dev/sdc1    /datadisk/    ext4    defaults 0 0\" >> /etc/fstab\n", "num_lines": 30}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Setting frontend to noninteractive to avoid password prompts\nexport DEBIAN_FRONTEND=noninteractive\n# Installing debconf-utils for handeling interactive installations (mainly for java 8 prompts)\napt-get install -y python-software-properties debconf-utils\n# Adding repository for Oracle Java 8\nadd-apt-repository -y ppa:webupd8team/java\n# Updating the repository\napt-get -y update\n# Installing Oracle Java 8 while skipping any prompts\necho \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | debconf-set-selections\napt-get -y install oracle-java8-installer\n# Adding Neo4j repository\nwget -O - https://debian.neo4j.org/neotechnology.gpg.key | apt-key add -\necho 'deb http://debian.neo4j.org/repo stable/' | tee -a /etc/apt/sources.list.d/neo4j.list\n# Updating repository\napt-get -y  update\n# Installing Neo4j. Neo4j version and edition passed as parameter\n# Example: neo4j=3.3.0 or neo4j-enterprise=3.3.0\n# Version can be skipped to get latest version on repository. Example: neo4j\napt-get -y  install $1\n# Backup for original configuration file\ncp -p /etc/neo4j/neo4j.conf /etc/neo4j/neo4j.conf.bak\n# Manually setting Neo4j configuration by manipulating values in neo4j.conf\n# First, we allow incoming connections from outside of localhost. By default neo4j rejects connections from non-local clients\nsed -i -e 's@#dbms.connectors.default_listen_address=0.0.0.0@dbms.connectors.default_listen_address=0.0.0.0@g' /etc/neo4j/neo4j.conf\n# enabling Neo4j to start when the Ubuntu starts\nsystemctl enable neo4j\n#manually starting Neo4j for the first time\nsystemctl restart neo4j\n", "num_lines": 54}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n## Script to Setup NetApp OnCommand Cloud Manager and Deploy Working Environment NetApp ONTAP Cloud on Azure ##\n\n## Arguments : To be passed by Azure Custom Script Extension\nregion=${1}\notcName=${2}\nadminEmail=${3}\nencodedadminPassword=${4}\nencodedOTCPassword=${5}\nsubscriptionId=${6}\nazureTenantId=${7}\napplicationId=${8}\napplicationKey=${9}\nvnetID=${10}\ncidr=${11}\nsubnetID=${12}\nnsgID=${13}\nlicenseType=${14}\ninstanceType=${15}\nstorageType=${16}\nQuickstartNameTagValue=${17}\nQuickstartProviderTagValue=${18}\nnetappOntapVersion=${19}\n\nadminPassword=`echo $encodedadminPassword| base64 --decode`\nOTCPassword=`echo $encodedOTCPassword| base64 --decode`\n\n\n##Variable Values for Setting up OnCommand Manager\ntenantName=\"azurenetappqs_tenant\"\nroleID=\"Role-1\"\nsiteName=\"AzureQS\"\nsiteCompany=\"AzureQS\"\nautoVsaCapacityManagement=true\nautoUpgrade=false\n## Variable Values for Deploying Working Environment on Azure\nunit=\"GB\"\n\n\n#Outputing the variables\ntouch /tmp/inputlog.txt\necho region $region >> /tmp/inputlog.txt\necho otcName $otcName >> /tmp/inputlog.txt\necho adminEmail $adminEmail >> /tmp/inputlog.txt\necho subscriptionId $subscriptionId >> /tmp/inputlog.txt\necho azureTenantId $azureTenantId >> /tmp/inputlog.txt\necho applicationId $applicationId >> /tmp/inputlog.txt\necho vnetID $vnetID >> /tmp/inputlog.txt\necho cidr $cidr >> /tmp/inputlog.txt\necho subnetID $subnetID >> /tmp/inputlog.txt\necho nsgID $nsgID >> /tmp/inputlog.txt\necho licenseType $licenseType >> /tmp/inputlog.txt\necho instanceType $instanceType >> /tmp/inputlog.txt\necho storageType $storageType >> /tmp/inputlog.txt\necho QuickstartNameTagValue $QuickstartNameTagValue >> /tmp/inputlog.txt\necho QuickstartProviderTagValue $QuickstartProviderTagValue >> /tmp/inputlog.txt\n\n## Downloading jQuery\nsudo wget -O /usr/bin/jq http://stedolan.github.io/jq/download/linux64/jq\nsleep 5\nsudo chmod +x /usr/bin/jq\n\n## Setup NetApp OnCommand Cloud Manager\ncurl http://localhost/occm/api/occm/setup/init -X POST --header 'Content-Type:application/json' --header 'Referer:AzureQS1' --data '{ \"tenantRequest\": { \"name\": \"'${tenantName}'\", \"description\": \"\", \"costCenter\": \"\", \"nssKeys\": {} }, \"proxyUrl\": { \"uri\": \"\" }, \"userRequest\":{  \"email\": \"'${adminEmail}'\",\"lastName\": \"user\", \"firstName\":\"admin\",\"roleId\": \"'${roleID}'\",\"password\": \"'${adminPassword}'\", \"ldap\": \"false\", \"azureCredentials\": { \"subscriptionId\": \"'${subscriptionId}'\", \"tenantId\": \"'${azureTenantId}'\", \"applicationId\": \"'${applicationId}'\", \"applicationKey\": \"'${applicationKey}'\" }  }, \"site\": \"'${siteName}'\", \"company\": \"'${siteCompany}'\", \"autoVsaCapacityManagement\": \"'${autoVsaCapacityManagement}'\",   \"autoUpgrade\": \"'${autoUpgrade}'\" }}'\nsleep 40\n\nuntil sudo wget http://localhost/occmui > /dev/null 2>&1; do sudo wget http://localhost > /dev/null 2>&1 ; done\nsleep 60\n\n## Authenticate to NetApp OnCommand CloudManager\ncurl http://localhost/occm/api/auth/login --header 'Content-Type:application/json' --header 'Referer:AzureQS1' --data '{\"email\":\"'${adminEmail}'\",\"password\":\"'${adminPassword}'\"}' --cookie-jar cookies.txt\nsleep 5\n\n## Getting the NetApp Tenant ID, to deploy the ONTAP Cloud\ntenantId=\"\"\nuntil [ \"$tenantId\" != \"\" ]; do\ncurl http://localhost/occm/api/auth/login --header 'Content-Type:application/json' --header 'Referer:AzureQS1' --data '{\"email\":\"'${adminEmail}'\",\"password\":\"'${adminPassword}'\"}' --cookie-jar cookies.txt\ntenantId=`sudo curl http://localhost/occm/api/tenants -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt | jq -r .[0].publicId`\nsleep 10\ndone\n\n## Create a ONTAP Cloud working environment on Azure\ncurl http://localhost/occm/api/azure/vsa/working-environments -X POST  --header 'Content-Type:application/json' --cookie cookies.txt --data '{ \"name\": \"'${otcName}'\", \"svmPassword\": \"'${OTCPassword}'\",  \"vnetId\": \"'${vnetID}'\",   \"cidr\": \"'${cidr}'\", \"vsaMetadata\": { \"ontapVersion\": \"'${netappOntapVersion}'\", \"licenseType\": \"'${licenseType}'\", \"instanceType\": \"'${instanceType}'\" },\"tenantId\": \"'${tenantId}'\",\"region\": \"'${region}'\", \"subnetId\":\"'${subnetID}'\", \"dataEncryptionType\":\"NONE\", \"skipSnapshots\": \"false\", \"diskSize\": { \"size\": \"1\",\"unit\": \"TB\" }, \"storageType\": \"'${storageType}'\", \"azureTags\": [ { \"tagKey\" : \"provider\", \"tagValue\" : \"'${QuickstartProviderTagValue}'\"}, { \"tagKey\" : \"quickstartName\", \"tagValue\" : \"'${QuickstartNameTagValue}'\"}],\"writingSpeedState\": \"NORMAL\" }' > /tmp/createnetappotc.txt\n\nOtcPublicId=`cat /tmp/createnetappotc.txt | jq -r .publicId`\nif [ ${OtcPublicId} = null ] ; then\n  message=`cat /tmp/createnetappotc.txt| jq -r .message`\n  echo \"OCCM setup failed: $message\" > /tmp/occmError.txt\n  exit 1\nfi\nsleep 2\n\n## Getting the NetApp Ontap Cloud Cluster Properties\n\ncurl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=status' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt > /tmp/envdetails.json\notcstatus=`cat /tmp/envdetails.json | jq -r .status.status`\n\ncheck_deploymentstatus()\n{\ncurl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=status' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt > /tmp/envdetails.json\notcstatus=`cat /tmp/envdetails.json | jq -r .status.status`\n}\n\nuntil  [ ${otcstatus} = ON ]\ndo\n  message=\"OTC not deployed yet, Checking again in 60 seconds\"\n  echo  ${message}\n  sleep 60\n  check_deploymentstatus\ndone\nsleep 5\n\ncurl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=ontapClusterProperties' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt > /tmp/ontapClusterProperties.json\n\n## grab the Cluster managment LIF IP address and save in /tmp for refrence\nclusterLif=`curl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=ontapClusterProperties' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt |jq -r .ontapClusterProperties.nodes[].lifs[] |grep \"Cluster Management\" -a2|head -1|cut -f4 -d '\"'`\necho \"${clusterLif}\" > /tmp/clusterLif.txt\n## grab the iSCSI data LIF IP address\ndataLif=`curl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=ontapClusterProperties' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt |jq -r .ontapClusterProperties.nodes[].lifs[] |grep iscsi -a4|head -1|cut -f4 -d '\"'`\necho \"${dataLif}\" > /tmp/iscsiLif.txt\n## grab the NFS and CIFS data LIF IP address\ndataLif2=`curl 'http://localhost/occm/api/azure/vsa/working-environments/'${OtcPublicId}'?fields=ontapClusterProperties' -X GET --header 'Content-Type:application/json' --header 'Referer:AzureQS' --cookie cookies.txt |jq -r .ontapClusterProperties.nodes[].lifs[] |grep nfs -a4|head -1|cut -f4 -d '\"'`\necho \"${dataLif2}\" > /tmp/nasLif.txt\n\n# Cluster Ip Addresses Exported in tmp Files\n", "num_lines": 126}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# ShellCheck is used for styling and static checking: https://github.com/koalaman/shellcheck\n# The script is split into functions to aid readability and maintainance.\n# Functions starting with an '_' child functions.\n# See the end of the file for flow.\n\nAZURE_STORAGE_NAME=$1\nAZURE_STORAGE_KEY=$2\nAZURE_FILESHARE_NAME=$3\nAZURE_STORAGE_ENDPOINT=$4\nMOUNTPOINT_PATH=$5\nIS_RUNNING_ON_NODE=$6\nUSERNAME=$7\nCLUSTER_MAXCPUS=$8\nNEXTFLOW_INSTALL_URL=$9\nADDITIONAL_INSTALL_SCRIPT_URL=${10}\nADDITIONAL_INSTALL_SCRIPT_ARGUMENT=${11}\n\n\nlog () {\n    echo \"-------------------------\" | tee -a \"$2\"\n    date -Is | tee -a \"$2\"\n    echo \"$1\" | tee -a \"$2\"\n    echo \"-------------------------\" | tee -a \"$2\"\n}\n\nlog \"storageSuffix: $AZURE_STORAGE_ENDPOINT\"\n\ninstallUtils() {\n    #Install CIFS and JQ (used by this script)\n    log \"Installing CIFS and JQ\" /tmp/nfinstall.log\n    apt-get -y update | tee /tmp/nfinstall.log\n    apt-get install cifs-utils sudo apt-transport-https wget graphviz -y | tee -a /tmp/nfinstall.log\n\n    #Create azure share if it doesn't already exist\n    log \"Installing AzureCLI and Mounting Azure Files Share\" /tmp/nfinstall.log\n    curl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash #TODO: simplify CLI install - this one command will do\n\n\n\n    az storage share create --name \"$AZURE_FILESHARE_NAME\" --quota 2048 --connection-string \"DefaultEndpointsProtocol=https;EndpointSuffix=$AZURE_STORAGE_ENDPOINT;AccountName=$AZURE_STORAGE_NAME;AccountKey=$AZURE_STORAGE_KEY\" | tee -a /tmp/nfinstall.log\n\n    #Wait for the file share to be available.\n    sleep 10\n}\n\nformatDataDisks() {\n    DATA_DIR=\"/datadisks/disk1\"\n\n    if bash ./vm-disk-utils-0.1.sh && [ -d \"$DATA_DIR\" ];\n    then\n        log \"Disk setup successful, using $DATA_DIR\" /tmp/nfinstall.log\n    else\n        log \"Disk setup failed, using default data storage location\" /tmp/nfinstall.log\n    fi\n\n    #Format data disks\n    mkdir -p $DATA_DIR\n    chmod 777 $DATA_DIR\n    chmod 777 /datadisks\n}\n\nmountCifs() {\n    log \"Mounting CIFS\" /tmp/nfinstall.log\n\n    #Mount the share with symlink and fifo support: see https://wiki.samba.org/index.php/SMB3-Linux\n    mkdir -p \"$MOUNTPOINT_PATH/cifs\" | tee -a /tmp/nfinstall.log\n    #TODO - hard coded endpoint\n    echo \"//$AZURE_STORAGE_NAME.file.$AZURE_STORAGE_ENDPOINT/$AZURE_FILESHARE_NAME $MOUNTPOINT_PATH/cifs cifs vers=3.0,username=$AZURE_STORAGE_NAME,password=$AZURE_STORAGE_KEY,dir_mode=0777,file_mode=0777,mfsymlinks,sfu\" >> /etc/fstab\n    mount -a  | tee -a /tmp/nfinstall.log\n    CIFS_SHAREPATH=\"$MOUNTPOINT_PATH/cifs\"\n}\n\n_setupNfsServer() {\n    log \"MASTER: Creating NFS share\" /tmp/nfinstall.log\n\n    #Variables\n    ALLOWEDSUBNET=10.0.0.0/24\n\n    #Install CIFS and JQ (used by this script)\n    log \"MASTER: Installing NFS Server\" /tmp/nfinstall.log\n    apt-get install nfs-kernel-server -y | tee -a /tmp/nfinstall.log\n\n    #TODO: Review permissions and security\n    mkdir \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n    chown nobody:nogroup \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n    chmod 777 \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n\n    echo \"$NFS_SHAREPATH    $ALLOWEDSUBNET(rw,sync,no_subtree_check,all_squash,anonuid=1000,anongid=100)\" > /etc/exports\n\n    systemctl restart nfs-kernel-server | tee -a /tmp/nfinstall.log\n\n    touch \"$CIFS_SHAREPATH/.done_creating_nfs_share\" | tee -a /tmp/nfinstall.log\n}\n\n_setupNfsClient() {\n    log \"NODE: Install NFS client tools\" /tmp/nfinstall.log\n    apt-get install nfs-kernel-server -y | tee -a /tmp/nfinstall.log\n\n    log \"NODE: Mounting NFS share\" /tmp/nfinstall.log\n    mkdir -p \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n    echo \"jumpboxvm:$NFS_SHAREPATH $NFS_SHAREPATH nfs rw,soft,intr\" >> /etc/fstab\n    mount -a | tee -a /tmp/nfinstall.log\n    chmod 777 \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n}\n\nsetupNfs() {\n    #Variables\n    #Location NFS share will be mounted at\n    NFS_SHAREPATH=\"$MOUNTPOINT_PATH\"/nfs\n\n    mkdir -p \"$NFS_SHAREPATH\" | tee -a /tmp/nfinstall.log\n    if [ \"$IS_RUNNING_ON_NODE\" != true ]; then\n        _setupNfsServer\n    fi\n\n    while [ ! -f \"$CIFS_SHAREPATH/.done_creating_nfs_share\" ]\n    do\n        log \"NODE: Waiting for NFS share to be created\" /tmp/nfinstall.log\n        sleep 5\n    done\n\n    if [ \"$IS_RUNNING_ON_NODE\" = true ]; then\n        _setupNfsClient\n    fi\n}\n\ncopyLogsToCifsShareForDebugging() {\n    log \"Get machine metadata and copy logs to share\"\n\n    apt-get install curl -y | tee -a /tmp/nfinstall.log\n\n    #Get node name and other instance metadata and write details into share log folder for debugging\n    #see https://docs.microsoft.com/en-us/azure/virtual-machines/windows/instance-metadata-service\n    METADATA=$(curl -H Metadata:true \"http://169.254.169.254/metadata/instance?api-version=2017-04-02\")\n    NODENAME=$(curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/name?api-version=2017-04-02&format=text\")\n\n    #Create a log folder for each node\n    mkdir -p \"$CIFS_SHAREPATH/logs/$NODENAME\" | tee -a /tmp/nfinstall.log\n\n    #Copy logs used so far\n    cp /tmp/nfinstall.log \"$CIFS_SHAREPATH/logs/$NODENAME/\"\n    LOGFOLDER=\"$CIFS_SHAREPATH/logs/$NODENAME/\"\n    LOGFILE=\"$CIFS_SHAREPATH/logs/$NODENAME/nfinstall.log\"\n\n    #Track the metadata for the node for debugging\n    echo \"$METADATA\" > \"$CIFS_SHAREPATH/logs/$NODENAME/node.metadata\"\n}\n\ninstallNextflowDeps() {\n    log \"Add Singularity repo to apt\" \"$LOGFILE\"\n    wget -O- http://neuro.debian.net/lists/xenial.us-ca.full | tee /etc/apt/sources.list.d/neurodebian.sources.list\n    wget -qO - http://neuro.debian.net/_static/neuro.debian.net.asc | apt-key add -\n\n    log \"Add Docker repo to apt\" \"$LOGFILE\"\n    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add - | tee -a \"$LOGFILE\"\n    add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable\" | tee -a \"$LOGFILE\"\n\n    apt-get update -y | tee -a \"$LOGFILE\"\n\n    log \"Installing JAVA\" \"$LOGFILE\"\n    apt-get install openjdk-8-jdk -y | tee -a \"$LOGFILE\"\n\n    log \"Install Singularity\" \"$LOGFILE\"\n    apt-get install -y singularity-container | tee -a \"$LOGFILE\"\n    echo \"bind path = $MOUNTPOINT_PATH\" >> /etc/singularity/singularity.conf\n    echo \"bind path = /mnt\" >> /etc/singularity/singularity.conf\n\n    log \"Install Docker\" \"$LOGFILE\"\n    apt-get install -y docker-ce | tee -a \"$LOGFILE\"\n    #Add the nextflow user to the docker group.\n    usermod -aG docker \"$USERNAME\" | tee -a \"$LOGFILE\"\n    #Nextflow creates files with write permissions only allowed by user that created them\n    #As we run nextflow under user/group nextflow/nextlow but the docker containers run under root\n    #We need to add root to the nextflow user group to give it the correct permissions\n    usermod -aG \"$USERNAME\" root | tee -a \"$LOGFILE\"\n    usermod -aG nogroup root | tee -a \"$LOGFILE\"\n}\n\nsetNextflowEnvironmentVars() {\n    log \"Setup Filesystem and Environment Variables\" \"$LOGFILE\"\n\n    mkdir -p \"$NFS_SHAREPATH/work\"\n    chmod 777 \"$NFS_SHAREPATH/work\"\n    mkdir -p \"$NFS_SHAREPATH/assets\"\n    chmod 777 \"$NFS_SHAREPATH/assets\"\n\n    #Configure nextflow environment vars\n    {\n        echo \"export NXF_WORK=$NFS_SHAREPATH/work\"\n        echo \"export NXF_ASSETS=$NFS_SHAREPATH/assets\"\n\n        #Added for debugging\n        echo export \"NXF_AZ_USER=$USERNAME\"\n        echo export \"NXF_AZ_LOGFILE=$LOGFILE\"\n        echo export \"NXF_AZ_CIFSPATH=$CIFS_SHAREPATH\"\n        echo export \"NXF_AZ_NFSPATH=$NFS_SHAREPATH\"\n    } >> /etc/environment\n\n    #Use azure epherical instance drive for tmp\n    mkdir -p /mnt/nextflow_temp\n    echo export NXF_TEMP=/mnt/nextflow_temp >> /etc/environment\n\n    #Allow user access to temporary drive\n    chmod -f 777 /mnt/nextflow_temp\n}\n\ninstallNextflow() {\n    #Install nextflow\n    log \"Installing nextflow\" \"$LOGFILE\"\n    curl -s \"$NEXTFLOW_INSTALL_URL\" | bash | tee -a \"$LOGFILE\"\n\n    #Copy the binary to the path to be accessed by users\n    cp ./nextflow /usr/local/bin\n    chmod -f 777 /usr/local/bin/nextflow\n\n    log \"Invoke nextflow to install dependencies\" \"$LOGFILE\"\n    sudo -H -u \"$USERNAME\" bash -c 'nextflow' | tee -a \"$LOGFILE\"\n}\n\n_smokeTestFailed() {\n    echo \"Shutting down node....\" | tee -a \"$LOGFILE\"\n    if [ \"$IS_RUNNING_ON_NODE\" != true ]; then\n        #If we're the master this fail the deployment\n        exit 1\n    fi\n\n    #If we're just a faulty node then shutdown\n    shutdown -h now | tee -a \"$LOGFILE\"\n    exit 0\n}\n\nrunSmokeTest() {\n    log \"Run smoke test. Validate machine is setup\" \"$LOGFILE\"\n\n    log \"Check Installed programs\" \"$LOGFILE\"\n    if ! [ -x \"$(command -v docker)\" ] || ! [ -x \"$(command -v singularity)\" ] || ! [ -x \"$(command -v nextflow)\" ]; then\n        log \"FAIL: Missing commands\" \"$LOGFILE\"\n        echo \"Docker\" | tee -a \"$LOGFILE\"\n        command -v docker | tee -a \"$LOGFILE\"\n\n        echo \"Singularity\" | tee -a \"$LOGFILE\"\n        command -v singularity | tee -a \"$LOGFILE\"\n\n        echo \"Nextflow\" | tee -a \"$LOGFILE\"\n        command -v nextflow | tee -a \"$LOGFILE\"\n\n        _smokeTestFailed\n    else\n        echo \"Success: Nextflow, docker and singularity installed\" >> \"$LOGFILE\"\n    fi\n\n    log \"Check mount points setup\" \"$LOGFILE\"\n    if mountpoint -q \"$MOUNTPOINT_PATH\"/cifs; then\n        echo \"CIFS Mounted\" | tee -a \"$LOGFILE\"\n    else\n        echo \"FAILED CIFS not mounted\" | tee -a \"$LOGFILE\"\n        _smokeTestFailed\n    fi\n\n    #NFS mount point only present on nodes as jumpbox is the NFS server.\n    # so only perform the check on nodes not jumpbox.\n    if [ \"$IS_RUNNING_ON_NODE\" = true ]; then\n        if mountpoint -q \"$MOUNTPOINT_PATH\"/nfs\n        then\n            echo \"NFS Mounted\" | tee -a \"$LOGFILE\"\n        else\n            echo \"FAILED NFS not mounted\" | tee -a \"$LOGFILE\"\n            _smokeTestFailed\n        fi\n    fi\n}\n\nrunAdditionalInstallScriptIfProvided() {\n    if [[ \"$ADDITIONAL_INSTALL_SCRIPT_URL\" ]]; then\n        log \"Run additional install script\" \"$LOGFILE\"\n        log \"Additional script url: $ADDITIONAL_INSTALL_SCRIPT_URL / argument: $ADDITIONAL_INSTALL_SCRIPT_ARGUMENT\" \"$LOGFILE\"\n        curl -s \"$ADDITIONAL_INSTALL_SCRIPT_URL\" -o additional_script.sh\n        bash additional_script.sh \"$ADDITIONAL_INSTALL_SCRIPT_ARGUMENT\" | tee -a \"$LOGFILE\"\n    fi\n}\n\nstartNextflowServiceIfNode() {\n    #If we're a node run the daemon\n    if [ \"$IS_RUNNING_ON_NODE\" = true ]; then\n\n    #Create a systemd unit\n    cat >/etc/systemd/system/nextflow.service <<EOL\n[Unit]\nDescription=Nextflow Node service\nAfter=network-online.target\n\n[Service]\nType=forking\nExecStart=/usr/local/bin/nextflow node -bg -cluster.join path:$CIFS_SHAREPATH/cluster -cluster.interface eth0 -cluster.maxCpus \"$CLUSTER_MAXCPUS\"\nRestart=always\nWorkingDirectory=$LOGFOLDER\n\n[Install]\nWantedBy=multi-user.target\nEOL\n\n    log \"NODE: Starting cluster nextflow cluster node\" \"$LOGFILE\"\n    systemctl enable nextflow.service | tee -a \"$LOGFILE\"\n    systemctl start nextflow.service | tee -a \"$LOGFILE\"\n    log \"NODE: Cluster node started\" \"$LOGFILE\"\n\n    fi\n\n}\n\n# This is the install flow, invoking each of the functions.\ninstallUtils\nformatDataDisks\nmountCifs\nsetupNfs\ncopyLogsToCifsShareForDebugging\ninstallNextflowDeps\nsetNextflowEnvironmentVars\ninstallNextflow\nrunSmokeTest\nrunAdditionalInstallScriptIfProvided\nstartNextflowServiceIfNode\n", "num_lines": 325}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"Initializing Nylas Open Source Sync Engine installation\"\n\n#############\n# Parameters\n#############\nAZUREUSER=$1\nHOME=\"/home/$AZUREUSER\"\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOME\"\n\n# update os\napt-get update\n\n# install git\napt-get install -y git\n\n# clone the sync engine repo\ncd $HOME\n\ngit clone https://github.com/singhkay/sync-engine.git\n/bin/bash -l -c \"chown -R $AZUREUSER $HOME/sync-engine\"\n\ncd $HOME/sync-engine/\n\n# kick off the setup script\nchmod +x ./setup.sh\nsudo ./setup.sh\nchown -R $AZUREUSER /etc/inboxapp\n\nrunuser -l $AZUREUSER -c \"nohup /home/$AZUREUSER/sync-engine/bin/inbox-start &\"\n", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nhname=$1\nsmtp_email=$2\npostpass=$3\nadmin_email=$4\nadmin_pass=$5\nadmin_acct_name=$6\nlms_stat_coll=$7\nsmtp_type=$8\nsmtp_port=$9\nsmtp_pass=${10}\necho \"sudo update\"\nsudo apt-get --assume-yes update\necho \"Postgres\"\nsudo apt-get --assume-yes install postgresql-9.5\nsudo -u postgres createdb canvas_production --owner=postgres\necho \"Changing the postgres user password\"\nsudo -u postgres psql -c \"ALTER USER postgres WITH PASSWORD '$postpass';\"\necho \"git install\"\nsudo apt-get install git-core\necho \"clone canvas\"\ngit clone https://github.com/instructure/canvas-lms.git canvas\ncd canvas\ngit checkout stable\ngit branch --set-upstream-to origin/stable\ncd ../\necho \"making canvas dir in var folder\"\nsudo mkdir -p /var/canvas\nsudo chown -R $USER /var/canvas\ncd canvas\necho \"copying files\"\ncp -av . /var/canvas\ncd /var/canvas\necho \"External dependencies\"\nsudo apt-get install software-properties-common\nsudo add-apt-repository -y ppa:brightbox/ruby-ng\nsudo apt-get --assume-yes update\necho \"Ruby installation\"\nsudo apt-get --assume-yes install ruby2.4 ruby2.4-dev zlib1g-dev libxml2-dev \\\n                       libsqlite3-dev postgresql libpq-dev \\\n                       libxmlsec1-dev curl make g++\necho \"Node JS\"\ncurl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash -\nsudo apt-get --assume-yes install nodejs\necho \"postgres create\"\nsudo -u postgres createuser $USER\nsudo -u postgres psql -c \"alter user $USER with superuser\" postgres\necho \"Bundler and Canvas dependencies\"\nsudo gem install bundler --version 1.13.6\nbundle install --path vendor/bundle\necho \"Yarn Installation\"\ncurl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -\necho \"deb https://dl.yarnpkg.com/debian/ stable main\" | sudo tee /etc/apt/sources.list.d/yarn.list\nsudo apt-get update && sudo apt-get install yarn\nsudo apt-get install python\n\necho \"Yarn Installation\"\nyarn install\necho \"Copying the config files for changing\"\nfor config in amazon_s3 database \\\n  delayed_jobs domain file_store outgoing_mail security external_migration; \\\n  do cp config/$config.yml.example config/$config.yml; done\necho \"Creating a dynamic setting file\"\ncp config/dynamic_settings.yml.example config/dynamic_settings.yml\n#vim config/dynamic_settings.yml #Comment this line as we cant edit it.\necho \"database file\"\ncp config/database.yml.example config/database.yml\nsed -e \"s/database: canvas_development/database: canvas_production/\" config/database.yml > config/database_new.yml\nmv config/database_new.yml config/database.yml\nsed -e \"s/username: canvas/username: postgres/\" config/database.yml > config/database_new.yml\nmv config/database_new.yml config/database.yml\nsed -e \"s/password: your_password/password: $postpass/\" config/database.yml > config/database_new.yml\nmv config/database_new.yml config/database.yml\necho \"Outgoing email\"\ncp config/outgoing_mail.yml.example config/outgoing_mail.yml\nsed -e \"s/smtp.example.com/$smtp_type/\" config/outgoing_mail.yml > config/outgoing_mail_new.yml\nmv config/outgoing_mail_new.yml config/outgoing_mail.yml\nsed -e \"s/example.com/$hname/\" config/outgoing_mail.yml > config/outgoing_mail_new.yml\nmv config/outgoing_mail_new.yml config/outgoing_mail.yml\nsed -e 's/\"user\"/\"'\"$smtp_email\"'\"/' config/outgoing_mail.yml > config/outgoing_mail_new.yml\nmv config/outgoing_mail_new.yml config/outgoing_mail.yml\nsed -e \"s/25/$smtp_port/\" config/outgoing_mail.yml > config/outgoing_mail_new.yml\nmv config/outgoing_mail_new.yml config/outgoing_mail.yml\nsed -e 's/\"password\"/\"'\"$smtp_pass\"'\"/' config/outgoing_mail.yml > config/outgoing_mail_new.yml\nmv config/outgoing_mail_new.yml config/outgoing_mail.yml\necho \"domain changes\"\ncp config/domain.yml.example config/domain.yml\nsed -e \"s/canvas.example.com/$hname/\" config/domain.yml > config/domain_new.yml\nmv config/domain_new.yml config/domain.yml\necho \"Security Changes\"\ncp config/security.yml.example config/security.yml\nsed -e \"s/encryption_key: 12345/encryption_key: facdd3a131ddd8988b14f6e4e01039c93cfa0160/\" config/security.yml > config/security_new.yml\nmv config/security_new.yml config/security.yml\necho \"Public Assests\"\nmkdir -p log tmp/pids public/assets app/stylesheets/brandable_css_brands\ntouch app/stylesheets/_brandable_variables_defaults_autogenerated.scss\ntouch Gemfile.lock\ntouch log/production.log\nsudo chown -R $USER config/environment.rb log tmp public/assets \\\n                              app/stylesheets/_brandable_variables_defaults_autogenerated.scss \\\n                              app/stylesheets/brandable_css_brands Gemfile.lock config.ru\necho \"Yarn Installation\"\nyarn install\ncd /var/canvas\necho \"Complie Assests\"\nsudo RAILS_ENV=production bundle exec rake canvas:compile_assets\nsudo chown -R $USER public/dist/brandable_css\necho \"loading initial database\"\ncd /var/canvas\nRAILS_ENV=production bundle exec rake db:initial_setup\nexport CANVAS_LMS_ADMIN_EMAIL=\"$admin_email\"\nexport CANVAS_LMS_ADMIN_PASSWORD=\"$admin_pass\"\nexport CANVAS_LMS_ACCOUNT_NAME=\"$admin_acct_name\"\nexport CANVAS_LMS_STATS_COLLECTION=\"$lms_stat_coll\"\nRAILS_ENV=production bundle exec rake db:initial_setup\nsudo chown $USER config/*.yml\nsudo chmod 400 config/*.yml\necho \"Install Passenger\"\nsudo apt-get --assume-yes install passenger libapache2-mod-passenger apache2\nsudo a2enmod rewrite\nsudo a2enmod passenger\nsudo a2enmod ssl\nsudo service apache2 restart\necho \"CANVAS CONF FILE\"\ncat > canvas.conf << EOF\n<VirtualHost *:80>\n  ServerName canvas.example.com\n  ServerAlias files.canvas.example.com\n  ServerAdmin youremail@example.com\n  DocumentRoot /var/canvas/public\n  RewriteEngine On\n  RewriteCond %{HTTP:X-Forwarded-Proto} !=https\n  RewriteCond %{REQUEST_URI} !^/health_check\n  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [L]\n  ErrorLog /var/log/apache2/canvas_errors.log\n  LogLevel warn\n  CustomLog /var/log/apache2/canvas_access.log combined\n  SetEnv RAILS_ENV production\n   <Directory /var/canvas/public>\n    Options All\n    AllowOverride All\n    Require all granted\n  </Directory>\n</VirtualHost>\n<VirtualHost *:443>\n  ServerName canvas.example.com\n  ServerAlias files.canvas.example.com\n  ServerAdmin youremail@example.com\n  DocumentRoot /var/canvas/public\n  ErrorLog /var/log/apache2/canvas_errors.log\n  LogLevel warn\n  CustomLog /var/log/apache2/canvas_ssl_access.log combined\n  SSLEngine on\n  BrowserMatch \"MSIE [2-6]\" nokeepalive ssl-unclean-shutdown downgrade-1.0 force-response-1.0\n  BrowserMatch \"MSIE [17-9]\" ssl-unclean-shutdown\n  # the following ssl certificate files are generated for you from the ssl-cert package.\n  SSLCertificateFile /etc/ssl/certs/ssl-cert-snakeoil.pem\n  SSLCertificateKeyFile /etc/ssl/private/ssl-cert-snakeoil.key\n  SetEnv RAILS_ENV production\n   <Directory /var/canvas/public>\n    Options All\n    AllowOverride All\n    Require all granted\n  </Directory>\n</VirtualHost>\nEOF\nsed -e \"s/canvas.example.com/$hname/\" canvas.conf > canvas_new.conf\nmv canvas_new.conf canvas.conf\nsed -e \"s/files.$hname/$hname/\" canvas.conf > canvas_new.conf\nmv canvas_new.conf canvas.conf\nsed -e \"s/youremail@example.com/$smtp_email/\" canvas.conf > canvas_new.conf\nmv canvas_new.conf canvas.conf\nsudo mv canvas.conf /etc/apache2/sites-available/\nsudo a2ensite canvas\necho \"APACHE RESTART\"\nsudo service apache2 restart\ncd /var/canvas\necho \"INSTALL REDIS SERVER\"\nsudo apt-add-repository -y ppa:chris-lea/redis-server\nsudo apt-get --assume-yes update\nsudo apt-get --assume-yes install redis-server\nsudo systemctl start redis\necho \"CACHE STORE\"\ncd /var/canvas/\ncp config/cache_store.yml.example config/cache_store.yml\nsed -e '/development/ s/^#*/#/' -i config/cache_store.yml\ncat >> config/cache_store.yml << EOF\n test:\n    cache_store: redis_store\ndevelopment:\n    cache_store: redis_store\nproduction:\n    cache_store: redis_store\nEOF\nsudo chown $USER config/cache_store.yml\nsudo chmod 400 config/cache_store.yml\necho \"REDIS\"\ncd /var/canvas/\ncp config/redis.yml.example config/redis.yml #redis localhost\ncat >> config/redis.yml << EOF\nproduction:\n  servers:\n    - redis://localhost\nEOF\nsudo chown $USER config/redis.yml\nsudo chmod 400 config/redis.yml\necho \"Canvas demon jobs\"\nsudo ln -s /var/canvas/script/canvas_init /etc/init.d/canvas_init\necho \"Canvas init start\"\nsudo update-rc.d canvas_init defaults\nsudo /etc/init.d/canvas_init start\necho \"Restart apache2\"\nsudo /etc/init.d/apache2 restart\necho \"START RAILS SERVER\"\nbundle exec rails server &\n", "num_lines": 216}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft Corporation. All Rights Reserved.\n# Licensed under the MIT license. See LICENSE file on the project webpage for details.\n\nset -x\nexport OPENEDX_RELEASE=$1\nCONFIG_REPO=https://github.com/edx/configuration.git\nANSIBLE_ROOT=/edx/app/edx_ansible\n\nwget https://raw.githubusercontent.com/edx/configuration/master/util/install/ansible-bootstrap.sh -O- | bash\n\nbash -c \"cat <<EOF >extra-vars.yml\n---\nedx_platform_version: \\\"$OPENEDX_RELEASE\\\"\ncerts_version: \\\"$OPENEDX_RELEASE\\\"\nforum_version: \\\"$OPENEDX_RELEASE\\\"\nxqueue_version: \\\"$OPENEDX_RELEASE\\\"\nconfiguration_version: \\\"$OPENEDX_RELEASE\\\"\nedx_ansible_source_repo: \\\"$CONFIG_REPO\\\"\nEOF\"\ncp *.yml $ANSIBLE_ROOT\nchown edx-ansible:edx-ansible $ANSIBLE_ROOT/*.yml\n\ncd /tmp\ngit clone $CONFIG_REPO\n\ncd configuration\ngit checkout $OPENEDX_RELEASE\npip install -r requirements.txt\n\ncd playbooks\nansible-playbook -i localhost, -c local vagrant-devstack.yml -e@$ANSIBLE_ROOT/extra-vars.yml\n", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft Corporation. All Rights Reserved.\n# Licensed under the MIT license. See LICENSE file on the project webpage for details.\n\nset -xe\n\n# Provide default if no parameter is passed.\nexport OPENEDX_RELEASE=${1:-\"open-release/ficus.master\"}\nexport CONFIGURATION_VERSION=$OPENEDX_RELEASE\nCONFIG_REPO=https://github.com/edx/configuration.git\nANSIBLE_ROOT=/edx/app/edx_ansible\nCONFIGURATION_ROOT=/tmp/configuration\nCURRENT_SCRIPT_PATH=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\nupdate_packages()\n{\n    for (( b=1; b<=3; b++ ))\n    do\n        echo\n        echo \"$1 packages...\"\n        echo\n        sudo apt-get $1 -y -qq --fix-missing\n        if [ $? -eq 0 ]; then\n            break\n        else\n            echo \"$1 failed\"\n        fi\n    done\n}\nverify_ssh()\n{\n    if [ ! -f \"/etc/ssh/sshd_config\" ]; then\n        echo \"installing ssh...\"\n        apt-get install -y -qq ssh\n    fi\n}\n\ninstall_ansible()\n{\n    # This URL structure works when $OPENEDX_RELEASE is a branch or tag in the configuration repo.\n    wget https://raw.githubusercontent.com/edx/configuration/$OPENEDX_RELEASE/util/install/ansible-bootstrap.sh -O ansible-bootstrap.sh\n    source ansible-bootstrap.sh\n}\n\nwrite_settings_to_file()\n{\n    pushd $CURRENT_SCRIPT_PATH\n\n    bash -c \"cat <<EOF >extra-vars.yml\n---\nedx_platform_version: \\\"$OPENEDX_RELEASE\\\"\ncerts_version: \\\"$OPENEDX_RELEASE\\\"\nforum_version: \\\"$OPENEDX_RELEASE\\\"\nxqueue_version: \\\"$OPENEDX_RELEASE\\\"\nconfiguration_version: \\\"$CONFIGURATION_VERSION\\\"\nPROGRAMS_VERSION: \\\"$OPENEDX_RELEASE\\\"\ndemo_version: \\\"$OPENEDX_RELEASE\\\"\nedx_ansible_source_repo: \\\"$CONFIG_REPO\\\"\nCOMMON_SSH_PASSWORD_AUTH: \\\"yes\\\"\nEDXAPP_SITE_NAME: \\\"$HOSTNAME\\\"\nEOF\"\n\n    cp *.yml $ANSIBLE_ROOT\n    chown edx-ansible:edx-ansible $ANSIBLE_ROOT/*.yml\n}\n\n# Execution start\n\n# Disable \"immediate exit\" on errors to allow for retry\nset +e\nupdate_packages update\nupdate_packages upgrade\n# Enable \"immediate exit\" on error\nset -e\n\nverify_ssh\ninstall_ansible\nwrite_settings_to_file\n\nif [ ! -d $CONFIGURATION_ROOT ]; then\n    git clone $CONFIG_REPO $CONFIGURATION_ROOT\nfi\n\ncd $CONFIGURATION_ROOT\ngit checkout $CONFIGURATION_VERSION\npip install -r requirements.txt\n\ncd playbooks\n\n# Disable \"immediate exit\" on errors to allow for retry\nset +e\n\n#retry transient failures\nMAX_ATTEMPTS=10\nretry_count=1\nuntil [ $retry_count -gt $MAX_ATTEMPTS ]\ndo\n    echo\n    echo \"starting attempt number: $retry_count\"\n    echo\n    ansible-playbook -i localhost, -c local vagrant-fullstack.yml -e@$ANSIBLE_ROOT/server-vars.yml -e@$ANSIBLE_ROOT/extra-vars.yml\n\n    if [ $? -eq 0 ]; then\n        echo \"attempt number: $retry_count succeeded!\"\n        break\n    else\n        echo \"attempt number: $retry_count failed\"\n        update_packages update\n        update_packages upgrade\n    fi\n    $retry_count=$retry_count+1\ndone\n\n# Enable \"immediate exit\" on error\nset -e\n\n", "num_lines": 117}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Copyright (c) Microsoft Corporation. All Rights Reserved.\n# Licensed under the MIT license. See LICENSE file on the project webpage for details.\n\nset -x\n\nAPP_VM_COUNT=$1\nADMIN_USER=$2\nADMIN_PASS=$3\nADMIN_HOME=/home/$ADMIN_USER\n\nEDX_VERSION=\"named-release/dogwood.rc\"\n\n# Run edX bootstrap\nANSIBLE_ROOT=/edx/app/edx_ansible\nCONFIGURATION_REPO=https://github.com/Microsoft/edx-configuration.git\nCONFIGURATION_VERSION=\"lex/scalable-dogwood\"\nwget https://raw.githubusercontent.com/edx/configuration/master/util/install/ansible-bootstrap.sh -O- | bash\n\n# Stage configuration files\nPLATFORM_REPO=https://github.com/edx/edx-platform.git\nPLATFORM_VERSION=$EDX_VERSION\n\nfor i in `seq 1 $(($APP_VM_COUNT-1))`; do\n  echo \"openedx-app$i\" >> inventory.ini\ndone\n\nbash -c \"cat <<EOF >extra-vars.yml\n---\nedx_platform_repo: \\\"$PLATFORM_REPO\\\"\nedx_platform_version: \\\"$PLATFORM_VERSION\\\"\nedx_ansible_source_repo: \\\"$CONFIGURATION_REPO\\\"\nconfiguration_version: \\\"$CONFIGURATION_VERSION\\\"\ncerts_version: \\\"$EDX_VERSION\\\"\nforum_version: \\\"$EDX_VERSION\\\"\nxqueue_version: \\\"$EDX_VERSION\\\"\nCOMMON_SSH_PASSWORD_AUTH: \\\"yes\\\"\nEOF\"\ncp *.{ini,yml} $ANSIBLE_ROOT\nchown edx-ansible:edx-ansible $ANSIBLE_ROOT/*.{ini,yml}\n\n\n# Setup SSH for remote installation\napt-get -y install sshpass\nfunction send-ssh-key {\n    host=$1;user=$2;pass=$3;\n    cat /home/$user/.ssh/id_rsa.pub | sshpass -p $pass ssh -o \"StrictHostKeyChecking no\" $user@$host 'cat >> .ssh/authorized_keys';\n}\n\nif [ ! -f $ADMIN_HOME/.ssh/id_rsa ]\nthen\n    ssh-keygen -f $ADMIN_HOME/.ssh/id_rsa -t rsa -N ''\n    chown -R $ADMIN_USER:$ADMIN_USER $ADMIN_HOME/.ssh/\nfi\n\nfor i in `seq 0 $(($APP_VM_COUNT-1))`; do\n  send-ssh-key openedx-app$i $ADMIN_USER $ADMIN_PASS\ndone\nsend-ssh-key openedx-mysql $ADMIN_USER $ADMIN_PASS\nsend-ssh-key openedx-mongo $ADMIN_USER $ADMIN_PASS\n\n# Install edX platform\ncd /tmp\ngit clone $CONFIGURATION_REPO configuration\n\ncd configuration\ngit checkout $CONFIGURATION_VERSION\npip install -r requirements.txt\n\ncd playbooks\nexport ANSIBLE_OPT_VARS=\"-e@$ANSIBLE_ROOT/server-vars.yml -e@$ANSIBLE_ROOT/extra-vars.yml\"\nexport ANSIBLE_OPT_SSH=\"-u $ADMIN_USER --private-key=$ADMIN_HOME/.ssh/id_rsa\"\n\nsudo ansible-playbook edx_mongo.yml -i \"openedx-mongo,\" $ANSIBLE_OPT_SSH $ANSIBLE_OPT_VARS\nrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi\n\nsudo ansible-playbook edx_mysql.yml -i \"openedx-mysql,\" $ANSIBLE_OPT_SSH $ANSIBLE_OPT_VARS\nrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi\n\nsudo ansible-playbook edx_sandbox.yml -i \"localhost,\" -c local $ANSIBLE_OPT_VARS -e \"migrate_db=yes\"\nrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi\n\nsudo ansible-playbook edx_sandbox.yml -i $ANSIBLE_ROOT/inventory.ini $ANSIBLE_OPT_SSH $ANSIBLE_OPT_VARS --limit app\nrc=$?; if [[ $rc != 0 ]]; then exit $rc; fi\n", "num_lines": 85}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"deploy tutor\"\n#configure tutor\ntutor local quickstart\n\nread -p \"what's your admin user email: \" EMAIL\ntutor local createuser --staff --superuser admin $EMAIL\necho \"create admin user, can log in with email\"\n\n\n", "num_lines": 11}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"start\"\nadminUsername=$1\nsudo apt update\n\necho \"install Docker\"\n\n#Install Docker\nyes Y | sudo apt install apt-transport-https ca-certificates curl software-properties-common\ncurl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -\nsudo add-apt-repository \"deb [arch=amd64] https://download.docker.com/linux/ubuntu focal stable\"\nsudo apt update\nyes Y | apt-cache policy docker-ce\nyes Y | sudo apt install docker-ce\n\necho \"docker compose\"\nyes Y | sudo curl -L \"https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose\nyes Y | sudo chmod +x /usr/local/bin/docker-compose\n\necho \"Enable Docker without Sudo\"\n#Enable Docker without Sudo (for user 'openadmin')\nsudo usermod -aG docker $adminUsername\n\nyes Y | sudo curl -L \"https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)\" -o /usr/local/bin/docker-compose\nyes Y | sudo chmod +x /usr/local/bin/docker-compose\n\necho \"install tutor\"\n#install tutor\nsudo curl -L \"https://github.com/overhangio/tutor/releases/download/v12.0.2/tutor-$(uname -s)_$(uname -m)\" -o /usr/local/bin/tutor\nsudo chmod 0755 /usr/local/bin/tutor\n\necho \"install tutor deployment script\"\nsudo curl -L \"https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/application-workloads/opendx/openedx-tutor-lilac-ubuntu/script/deploy_tutor.sh\" -o ./deploy_tutor.sh\nsudo chmod 777 deploy_tutor.sh\nmv deploy_tutor.sh /home/\"$adminUsername\"\n", "num_lines": 36}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# parameters\nvmadminuser=$1\nvmadminpass=$2\ndirectoryadminpass=$3\nsubdomain=$4\nlocation=$5\norganization=$6\nprivateIPAddressPrefix=$7\nvmCount=$8\nindex=$9\n\n# variables\nlet \"index+=1\" # index is 0-based, but we want 1-based\ndomain=$subdomain.$location.cloudapp.azure.com\nbase=\"dc=$subdomain,dc=$location,dc=cloudapp,dc=azure,dc=com\"\nlocaldomain=ldap$index.$subdomain.local\n\n# install debconf\napt-get -y update\napt-get install debconf\n\necho \"===== Set up siltent install of slapd =====\"\n# silent install of slapd\nexport DEBIAN_FRONTEND=noninteractive\necho slapd slapd/password1 password $directoryadminpass | debconf-set-selections\necho slapd slapd/password2 password $directoryadminpass | debconf-set-selections\necho slapd slapd/allow_ldap_v2 boolean false | debconf-set-selections\necho slapd slapd/domain string $domain | debconf-set-selections\necho slapd slapd/no_configuration boolean false | debconf-set-selections\necho slapd slapd/move_old_database boolean true | debconf-set-selections\n# echo slapd slapd/dump_database_destdir string /var/backups/slapd-VERSION | debconf-set-selections\necho slapd slapd/purge_database boolean false | debconf-set-selections\necho slapd shared/organization string $organization | debconf-set-selections\necho slapd slapd/backend select HDB | debconf-set-selections\n\necho \"===== Install slapd =====\"\napt-get -y install slapd ldap-utils\n\necho \"===== Set up TLS support =====\"\napt-get -y install gnutls-bin ssl-cert sshpass\n\necho \"===== Create entries in hosts file =====\"\nfor i in `seq 1 $vmCount`; do\n    let \"j=i-1\"\n    echo \"$privateIPAddressPrefix$j ldap$i.$subdomain.local ldap$i\" >> /etc/hosts\ndone\n\necho \"===== Modify slapd default configuration =====\"\nsed -i \"s/SLAPD_SERVICES=\\\"ldap:\\/\\/\\/ ldapi:\\/\\/\\/\\\"/SLAPD_SERVICES=\\\"ldapi:\\/\\/\\/ ldap:\\/\\/$localdomain\\\"/\" /etc/default/slapd\n\necho \"===== Create dir for certificates =====\"\nmkdir /etc/ssl/slapd\n\n# Create CA certificate (only on the first server - the other servers will just copy it from here)\nif [ \"$index\" = \"1\" ]; then\n    echo \"===== Generate a private key for the CA certificate =====\"\n    certtool --generate-privkey > /etc/ssl/slapd/cakey.pem\n\n    echo \"===== Create ca.info =====\"\n    echo \"cn = $localdomain\" > /etc/ssl/slapd/ca.info\n    echo \"ca\" >> /etc/ssl/slapd/ca.info\n    echo \"cert_signing_key\" >> /etc/ssl/slapd/ca.info\n\n    echo \"===== Create CA cert =====\"\n    certtool --generate-self-signed --load-privkey /etc/ssl/slapd/cakey.pem --template /etc/ssl/slapd/ca.info --outfile /etc/ssl/slapd/cacert.pem\nelse\n    echo \"===== Copy the CA certificate from the first server =====\"\n    sshpass -p \"$vmadminpass\" scp -o \"StrictHostKeyChecking no\" $vmadminuser@ldap1.$subdomain.local:/etc/ssl/slapd/cacert.pem /etc/ssl/slapd\n    while [ ! -f /etc/ssl/slapd/cacert.pem ]; do\n        sleep 2\n        sshpass -p \"$vmadminpass\" scp -o \"StrictHostKeyChecking no\" $vmadminuser@ldap1.$subdomain.local:/etc/ssl/slapd/cacert.pem /etc/ssl/slapd\n    done\n\n    sshpass -p \"$vmadminpass\" scp -o \"StrictHostKeyChecking no\" $vmadminuser@ldap1.$subdomain.local:/etc/ssl/slapd/cakey.pem /etc/ssl/slapd\nfi\n\necho \"===== Generate private key for the server =====\"\ncerttool --generate-privkey --bits 2048 --outfile /etc/ssl/slapd/ldaps_slapd_key.pem\n\necho \"===== Create template for server certificate =====\"\necho \"organization = $organization\" > /etc/ssl/slapd/ldaps.info\necho \"cn = $domain\" >> /etc/ssl/slapd/ldaps.info\necho \"tls_www_server\" >> /etc/ssl/slapd/ldaps.info\necho \"encryption_key\" >> /etc/ssl/slapd/ldaps.info\necho \"signing_key\" >> /etc/ssl/slapd/ldaps.info\necho \"expiration_days = 3650\" >> /etc/ssl/slapd/ldaps.info\n\necho \"===== Create the certificate =====\"\ncerttool --generate-certificate \\\n--load-privkey /etc/ssl/slapd/ldaps_slapd_key.pem \\\n--load-ca-certificate /etc/ssl/slapd/cacert.pem \\\n--load-ca-privkey /etc/ssl/slapd/cakey.pem \\\n--template /etc/ssl/slapd/ldaps.info \\\n--outfile /etc/ssl/slapd/ldaps_slapd_cert.pem\n\necho \"===== Add TLS settings to the config =====\"\nldapmodify -Y EXTERNAL -H ldapi:/// -f ./setTLSConfig.ldif\n\necho \"===== Secure the keys =====\"\nadduser openldap ssl-cert\nchgrp ssl-cert /etc/ssl/slapd/ldaps_slapd_key.pem\nchmod g+r /etc/ssl/slapd/ldaps_slapd_key.pem\nchmod o-r /etc/ssl/slapd/ldaps_slapd_key.pem\n\necho \"===== Give apparmor access to cert files =====\"\n# TODO: This regex could be made more robust\nsed -i \"/\\/usr\\/sbin\\/slapd mr,/ s/$/\\n\\n  \\/etc\\/ssl\\/slapd\\/ r,\\n  \\/etc\\/ssl\\/slapd\\/* r,/\" /etc/apparmor.d/usr.sbin.slapd\nservice apparmor reload\n/etc/init.d/slapd restart\n\necho \"===== Backup existing ldap.config and create new one =====\"\ncp /etc/ldap/ldap.conf /etc/ldap/ldap.conf.old\necho \"BASE $base\" > /etc/ldap/ldap.conf\necho \"ldap:// ldaps:// ldapi://\" >> /etc/ldap/ldap.conf\necho \"TLS_CACERT /etc/ssl/slapd/cacert.pem\" >> /etc/ldap/ldap.conf\necho \"TLS_REQCERT allow\" >> /etc/ldap/ldap.conf\n\necho \"===== Install phpldapadmin =====\"\n# Install phpldapadmin\nsudo apt-get -y install phpldapadmin\n\necho \"===== Configure phpldapadmin =====\"\n# Backup existing config.php file for phpldapadmin and create a new one\ncp /etc/phpldapadmin/config.php /etc/phpldapadmin/config.php.old\necho \"<?php \" > /etc/phpldapadmin/config.php\necho \"\\$servers = new Datastore();\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->newServer('ldap_pla');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','name','$organization');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','host','$domain');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','base',array('$base'));\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('login','bind_id','cn=admin,$base');\" >> /etc/phpldapadmin/config.php\necho \"\\$config->custom->appearance['hide_template_warning'] = true;\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','tls',true);\" >> /etc/phpldapadmin/config.php\necho \"?>\" >> /etc/phpldapadmin/config.php\n\n# Backup existing /usr/share/phpldapadmin/lib/TemplateRender.php and change password_hash to password_hash_custom (to take care of template error)\ncp /usr/share/phpldapadmin/lib/TemplateRender.php /usr/share/phpldapadmin/lib/TemplateRender.php.old\nsed -i \"s/password_hash/password_hash_custom/\" /usr/share/phpldapadmin/lib/TemplateRender.php\n\necho \"===== Enable SSL on Apache =====\"\na2enmod ssl\n\necho \"===== edit default-ssl.conf =====\"\nsed -i '/^[[:space:]]*SSLCertificateFile[[:space:]]/ s/^.*/SSLCertificateFile \\/etc\\/ssl\\/slapd\\/ldaps_slapd_cert.pem/' /etc/apache2/sites-available/default-ssl.conf\nsed -i '/^[[:space:]]*SSLCertificateKeyFile[[:space:]]/ s/^.*/SSLCertificateKeyFile \\/etc\\/ssl\\/slapd\\/ldaps_slapd_key.pem/' /etc/apache2/sites-available/default-ssl.conf\n\na2ensite default-ssl\n\necho \"===== Set up master-master replication =====\"\n\necho \"===== Install ntp package =====\"\napt-get -y install ntp\n/etc/init.d/ntp restart\n\necho \"===== Generate password =====\"\n# SLAPPASSWD=$(slappasswd -s $directoryadminpass)\nSLAPPASSWD=$directoryadminpass\nSLAPPASSWDEscaped=\"$(sed 's/[&/\\]/\\\\&/g' <<< \"$SLAPPASSWD\")\"\n\necho \"===== Load syncProv module =====\"\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_1_loadSyncProvModule.ldif\n\necho \"===== Set server ID =====\"\nsed -i \"s/{serverID}/$index/\" config_2_setServerID.ldif\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_2_setServerID.ldif\n\necho \"===== Set password =====\"\n\nsed -i \"s@{password}@$SLAPPASSWDEscaped@\" config_3_setConfigPW.ldif\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_3_setConfigPW.ldif\n\necho \"===== Add Root DN =====\"\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_3a_addOlcRootDN.ldif\n\necho \"===== Add configuration replication =====\"\nfor i in `seq 1 $vmCount`; do\n    echo \"olcServerID: $i ldap://ldap$i.$subdomain.local\" >> config_4_addConfigReplication.ldif\ndone\n\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_4_addConfigReplication.ldif\n\necho \"===== Add syncProv to the configuration =====\"\nldapmodify -Y EXTERNAL -H ldapi:/// -f config_5_addSyncProv.ldif\n\n# Force TLS\nldapmodify -Y EXTERNAL -H ldapi:/// -f ./forceTLS.ldif\n\necho \"===== Add syncRepl among servers =====\"\nsyncRepl=\"\"\nfor i in `seq 1 $vmCount`; do\n    syncRepl=$syncRepl\"olcSyncRepl: rid=00$i provider=ldap://ldap$i.$subdomain.local binddn=\\\"cn=admin,cn=config\\\" bindmethod=simple credentials=$SLAPPASSWDEscaped searchbase=\\\"cn=config\\\" type=refreshAndPersist retry=\\\"5 5 300 5\\\" timeout=1 starttls=critical tls_reqcert=allow\\n\"\ndone\n\nsed -i \"s@{syncRepl}@$syncRepl@\" config_6_addSyncRepl.ldif\n# ldapmodify -Y EXTERNAL -H ldapi:/// -f config_6_addSyncRepl.ldif\nldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f config_6_addSyncRepl.ldif\n\n# test replication\n# ldapmodify -Y EXTERNAL -H ldapi:/// -f config_7_testConfigReplication.ldif\n\n# Since configuration is expected to be replicating at this point, we only need to do this on the first server.\nif [ \"$index\" = \"1\" ]; then\n\n    echo \"===== Modify HDB config =====\"\n\n    echo \"===== Add syncProv to HDB =====\"\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_1_addSyncProvToHDB.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_1_addSyncProvToHDB.ldif\n\n    echo \"===== Add suffix =====\"\n    sed -i \"s@{dn}@$base@\" hdb_2_addOlcSuffix.ldif\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_2_addOlcSuffix.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_2_addOlcSuffix.ldif\n\n    echo \"===== Add Root DN =====\"\n    sed -i \"s@{dn}@$base@\" hdb_3_addOlcRootDN.ldif\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_3_addOlcRootDN.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_3_addOlcRootDN.ldif\n\n    echo \"===== Add Root password =====\"\n    sed -i \"s@{password}@$SLAPPASSWDEscaped@\" hdb_4_addOlcRootPW.ldif\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_4_addOlcRootPW.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_4_addOlcRootPW.ldif\n\n    echo \"===== Add  syncRepl among servers =====\"\n    for i in `seq 1 $vmCount`; do\n        let \"rid=i+vmCount\"\n        echo \"olcSyncRepl: rid=10$rid provider=ldap://ldap$i.$subdomain.local binddn=\\\"cn=admin,$base\\\" bindmethod=simple credentials=$SLAPPASSWD searchbase=\\\"$base\\\" type=refreshAndPersist interval=00:00:00:10 retry=\\\"5 5 300 5\\\" timeout=1\" >> hdb_5_addOlcSyncRepl.ldif\n    done\n\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_5_addOlcSyncRepl.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_5_addOlcSyncRepl.ldif\n\n    echo \"===== Add mirror mode =====\"\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_6_addOlcMirrorMode.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_6_addOlcMirrorMode.ldif\n\n    echo \"===== Add index to the database =====\"\n    # ldapmodify -Y EXTERNAL -H ldapi:/// -f hdb_7_addIndexHDB.ldif\n    ldapmodify -ZZ -h $localdomain -D \"cn=admin,cn=config\" -w $SLAPPASSWD -f hdb_7_addIndexHDB.ldif\n\nfi\n\necho \"===== Restart Apache =====\"\napachectl restart\n", "num_lines": 248}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# parameters\nadminpass=$1\nsubdomain=$2\nlocation=$3\norganization=$4\n\n# variables\ndomain=$subdomain.$location.cloudapp.azure.com\nbase=\"dc=$subdomain,dc=$location,dc=cloudapp,dc=azure,dc=com\"\n\n# install debconf\napt-get -y update\napt-get install debconf\n\n# silent install of slapd\nexport DEBIAN_FRONTEND=noninteractive\necho slapd slapd/password1 password $adminpass | debconf-set-selections\necho slapd slapd/password2 password $adminpass | debconf-set-selections\necho slapd slapd/allow_ldap_v2 boolean false | debconf-set-selections\necho slapd slapd/domain string $domain | debconf-set-selections\necho slapd slapd/no_configuration boolean false | debconf-set-selections\necho slapd slapd/move_old_database boolean true | debconf-set-selections\n# echo slapd slapd/dump_database_destdir string /var/backups/slapd-VERSION | debconf-set-selections\necho slapd slapd/purge_database boolean false | debconf-set-selections\necho slapd shared/organization string $organization | debconf-set-selections\necho slapd slapd/backend select HDB | debconf-set-selections\n\napt-get -y install slapd ldap-utils\n\n# Install for TLS support\napt-get -y install gnutls-bin ssl-cert\n\n# Create dir for certificates\nmkdir /etc/ssl/slapd\n\n# Generate a private key for the certificate\ncerttool --generate-privkey > /etc/ssl/slapd/cakey.pem\n\n# Create ca.info\necho \"cn = $domain\" > /etc/ssl/slapd/ca.info\necho \"ca\" >> /etc/ssl/slapd/ca.info\necho \"cert_signing_key\" >> /etc/ssl/slapd/ca.info\n\n# Create CA certificate\ncerttool --generate-self-signed --load-privkey /etc/ssl/slapd/cakey.pem --template /etc/ssl/slapd/ca.info --outfile /etc/ssl/slapd/cacert.pem\n\n# Generate private key for the server\ncerttool --generate-privkey --bits 2048 --outfile /etc/ssl/slapd/ldaps_slapd_key.pem\n\n# Create template for server certificate\necho \"organization = $organization\" > /etc/ssl/slapd/ldaps.info\necho \"cn = $domain\" >> /etc/ssl/slapd/ldaps.info\necho \"tls_www_server\" >> /etc/ssl/slapd/ldaps.info\necho \"encryption_key\" >> /etc/ssl/slapd/ldaps.info\necho \"signing_key\" >> /etc/ssl/slapd/ldaps.info\necho \"expiration_days = 3650\" >> /etc/ssl/slapd/ldaps.info\n\n# Create the certificate\ncerttool --generate-certificate \\\n--load-privkey /etc/ssl/slapd/ldaps_slapd_key.pem \\\n--load-ca-certificate /etc/ssl/slapd/cacert.pem \\\n--load-ca-privkey /etc/ssl/slapd/cakey.pem \\\n--template /etc/ssl/slapd/ldaps.info \\\n--outfile /etc/ssl/slapd/ldaps_slapd_cert.pem\n\n# Add TLS settings to the config\nldapmodify -Y EXTERNAL -H ldapi:/// -f ./setTLSConfig.ldif\n\n# Secure the keys\nadduser openldap ssl-cert\nchgrp ssl-cert /etc/ssl/slapd/ldaps_slapd_key.pem\nchmod g+r /etc/ssl/slapd/ldaps_slapd_key.pem\nchmod o-r /etc/ssl/slapd/ldaps_slapd_key.pem\n\n# Give apparmor access to cert files\n# TODO: This regex could be made more robust\nsed -i \"/\\/usr\\/sbin\\/slapd mr,/ s/$/\\n\\n  \\/etc\\/ssl\\/slapd\\/ r,\\n  \\/etc\\/ssl\\/slapd\\/* r,/\" /etc/apparmor.d/usr.sbin.slapd\nservice apparmor reload\n/etc/init.d/slapd restart\n\n# force TLS\nldapmodify -Y EXTERNAL -H ldapi:/// -f ./forceTLS.ldif\n\n# Backup existing ldap.config and create new one\ncp /etc/ldap/ldap.conf /etc/ldap/ldap.conf.old\necho \"BASE $base\" > /etc/ldap/ldap.conf\necho \"ldap:// ldaps:// ldapi://\" >> /etc/ldap/ldap.conf\necho \"TLS_CACERT /etc/ssl/slapd/cacert.pem\" >> /etc/ldap/ldap.conf\necho \"TLS_REQCERT demand\" >> /etc/ldap/ldap.conf\n\n# Install phpldapadmin\nsudo apt-get -y install phpldapadmin\n\n# Backup existing config.php file for phpldapadmin and create a new one\ncp /etc/phpldapadmin/config.php /etc/phpldapadmin/config.php.old\necho \"<?php \" > /etc/phpldapadmin/config.php\necho \"\\$servers = new Datastore();\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->newServer('ldap_pla');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','name','$organization');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','host','$domain');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','base',array('$base'));\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('login','bind_id','cn=admin,$base');\" >> /etc/phpldapadmin/config.php\necho \"\\$servers->setValue('server','tls',true);\" >> /etc/phpldapadmin/config.php\necho \"\\$config->custom->appearance['hide_template_warning'] = true;\" >> /etc/phpldapadmin/config.php\necho \"?>\" >> /etc/phpldapadmin/config.php\n\n# Backup existing /usr/share/phpldapadmin/lib/TemplateRender.php and change password_hash to password_hash_custom (to take care of template error)\ncp /usr/share/phpldapadmin/lib/TemplateRender.php /usr/share/phpldapadmin/lib/TemplateRender.php.old\nsed -i \"s/password_hash/password_hash_custom/\" /usr/share/phpldapadmin/lib/TemplateRender.php\n\n# Enable SSL on Apache\na2enmod ssl\n\n# edit default-ssl.conf\nsed -i '/^[[:space:]]*SSLCertificateFile[[:space:]]/ s/^.*/SSLCertificateFile \\/etc\\/ssl\\/slapd\\/ldaps_slapd_cert.pem/' /etc/apache2/sites-available/default-ssl.conf\nsed -i '/^[[:space:]]*SSLCertificateKeyFile[[:space:]]/ s/^.*/SSLCertificateKeyFile \\/etc\\/ssl\\/slapd\\/ldaps_slapd_key.pem/' /etc/apache2/sites-available/default-ssl.conf\n\na2ensite default-ssl\n\n# restart Apache\napachectl restart\n", "num_lines": 124}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "mysql_pass=$1\ndatabase_name=$2\nsudo apt-get update\necho \"Installing Apache\"\nsudo apt-get --yes install apache2\nsudo systemctl start apache2\nsudo systemctl enable apache2\nsudo apt-get --yes install python-software-properties\necho \"Installing Mariadb\"\nsudo apt-key adv --recv-keys --keyserver hkp://keyserver.ubuntu.com:80 0xF1656F24C74CD1D8\nsudo apt-get --yes install mariadb-server mariadb-client\nsudo mysql_secure_installation << EOF\n\ny\n$mysql_pass\n$mysql_pass\ny\ny\ny\ny\nEOF\necho \"Create database named openScholar\"\nsudo mysql -u root -p$mysql_pass -e \"create database $database_name\";\nsudo mysql -u root -p$mysql_pass -e \"grant all privileges on $database_name.* to 'root'@'localhost' identified by '$mysql_pass';\";\nsudo mysql -u root -p$mysql_pass -e \"flush privileges;\";\necho \"Installing the php version 5.6\"\nsudo add-apt-repository -y ppa:ondrej/php\nsudo apt-get update\nsudo apt-get --yes upgrade\nsudo apt-get --yes install php5.6\necho \"Installing php extensions for drupal\"\nsudo apt-get --yes install php5.6-gd php5.6-mysql php5.6-dom php5.6-cli php5.6-json php5.6-common php5.6-mbstring php5.6-opcache php5.6-readline\nsudo systemctl start apache2\ncd /var/www\necho \"Download the openscholar drupal profile, increase memory enable mod rewrite and change in apache config for htaccess\"\nsudo su <<EOF\ncd html\nwget https://osprojectsite.org/files/osorg2/files/drupal-openscholar-7.x-3.90.1.tar.gz\ntar -zxvf drupal-openscholar-7.x-3.90.1.tar.gz\ncd sites/default\nmkdir files\ncp default.settings.php settings.php\nchmod -R 755 *\nsudo a2enmod rewrite\nsudo systemctl restart apache2\ncd /etc/php/5.6/apache2/\nsed -e \"s/memory_limit = 128M/memory_limit = 512M/\" php.ini > php_new.ini\nmv php_new.ini php.ini\ncd /var/www/html\nmv index.html old.html\ncd /etc/apache2\nsed '/<Directory \\/var\\/www\\/>/,/<\\/Directory>/ s/AllowOverride None/AllowOverride All/' apache2.conf > apache2_new.conf\nmv apache2_new.conf apache2.conf\nsudo systemctl restart apache2\ncd /var/www/html/profiles/openscholar/modules/contrib/oembed/\nwget https://www.drupal.org/files/oembed-2021015-1.patch\npatch -p1 < oembed-2021015-1.patch\nEOF\n", "num_lines": 59}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\nwhile getopts \"r:s\" opt; do\n    case $opt in\n        r)\n            roles=$OPTARG # coma seperated roles\n        ;;\n        s)\n            subscription=$OPTARG #optional subscription ID\n        ;;\n    esac\ndone\n\n[[ $# -eq 0 || -z $roles ]] && { echo \"Usage: $0 -r <comma seperated role(s)>\"; exit 1; }\n\n# install jq if not installed\nif ! command -v jq &> /dev/null\nthen\n    echo \"jq command not found. attempting to download jq binary\"\n    pth=$(pwd)\n    export PATH=$PATH:$pth\n    if [[ \"$OSTYPE\" == \"linux-gnu\"* ]]; then\n        curl -LO https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64 jq\n    elif [[ \"$OSTYPE\" == \"darwin\"* ]]; then\n        curl -LO https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64 jq\n    else\n        echo \"Unsupported OS type. Exiting...\"\n        exit 1\n    fi\n    chmod +x jq\nfi\n\nIFS=','; rolesArr=($roles); unset IFS;\nrole1=\"${rolesArr[0]}\"\nsubscriptionId=$( az account show -o json | jq -r '.id' )\n\n# Create service principal with first\nspJson=$(az ad sp create-for-rbac --role=\"$role1\" --scopes=\"/subscriptions/$subscriptionId\")\naadClientId=$(echo $spJson | jq -r '.appId')\naadClientSecret=$(echo $spJson | jq -r '.password')\n\n# Get object object id\nobjectId=$( az ad sp list --filter \"appId eq '$aadClientId'\" | jq '.[0].objectId' -r )\n\n# assign roles \nfor role in \"${rolesArr[@]}\"\ndo\n    echo \"Creating role $role\"\n    az role assignment create --role \"$role\" --assignee-object-id $objectId\ndone\n\necho \" Creation Complete \"\n\necho \" - ClientID => $aadClientId\"\necho \" - ClientSecret => $aadClientSecret\"\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho $(date) \" - ############## Starting Script ####################\"\n\nset -e\n\nexport SUDOUSER=$1\nexport OPENSHIFTPASSWORD=$2\nexport SSHKEY=$3\nexport WORKERCOUNT=$4\nexport MASTERCOUNT=$5\nexport SUBSCRIPTIONID=$6\nexport TENANTID=$7\nexport AADCLIENTID=$8\nexport AADSECRET=$9\nexport RESOURCEGROUPNAME=${10}\nexport LOCATION=${11}\nexport VIRTUALNETWORKNAME=${12}\nexport PXSPECURL=${13}\nexport STORAGEOPTION=${14}\nexport NFSHOSTNAME=${15}\nexport SINGLEORMULTI=${16}\nexport ARTIFACTSLOCATION=${17::-1}\nexport ARTIFACTSTOKEN=\\\"${18}\\\"\nexport BASEDOMAIN=${19}\nexport MASTERINSTANCETYPE=${20}\nexport WORKERINSTANCETYPE=${21}\nexport CLUSTERNAME=${22}\nexport CLUSTERNETWORKCIDR=${23}\nexport HOSTADDRESSPREFIX=${24}\nexport VIRTUALNETWORKCIDR=${25}\nexport SERVICENETWORKCIDR=${26}\nexport BASEDOMAINRG=${27}\nexport NETWORKRG=${28}\nexport MASTERSUBNETNAME=${29}\nexport WORKERSUBNETNAME=${30}\nexport PULLSECRET=${31}\nexport FIPS=${32}\nexport PUBLISH=${33}\nexport OPENSHIFTUSER=${34}\n\n#Var\nexport INSTALLERHOME=/home/$SUDOUSER/.openshift\n\n# Grow Root File System\nyum -y install cloud-utils-growpart.noarch\necho $(date) \" - Grow Root FS\"\n\nrootdev=`findmnt --target / -o SOURCE -n`\nrootdrivename=`lsblk -no pkname $rootdev`\nrootdrive=\"/dev/\"$rootdrivename\nname=`lsblk  $rootdev -o NAME | tail -1`\npart_number=${name#*${rootdrivename}}\n\ngrowpart $rootdrive $part_number -u on\nxfs_growfs $rootdev\n\nif [ $? -eq 0 ]\nthen\n    echo $(date) \" - Root File System successfully extended\"\nelse\n    echo $(date) \" - Root File System failed to be grown\"\n\texit 20\nfi\n\necho $(date) \" - Install Podman\"\nyum install -y podman\necho $(date) \" - Install Podman Complete\"\n\necho $(date) \" - Install httpd-tools\"\nyum install -y httpd-tools\necho $(date) \" - Install httpd-tools Complete\"\n\necho $(date) \" - Download Binaries\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.openshift\"\n\nrunuser -l $SUDOUSER -c \"wget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.3.18/openshift-install-linux-4.3.18.tar.gz\"\nrunuser -l $SUDOUSER -c \"wget https://mirror.openshift.com/pub/openshift-v4/clients/ocp/4.3.18/openshift-client-linux-4.3.18.tar.gz\"\nrunuser -l $SUDOUSER -c \"tar -xvf openshift-install-linux-4.3.18.tar.gz -C $INSTALLERHOME\"\nrunuser -l $SUDOUSER -c \"sudo tar -xvf openshift-client-linux-4.3.18.tar.gz -C /usr/bin\"\n\nchmod +x /usr/bin/kubectl\nchmod +x /usr/bin/oc\nchmod +x $INSTALLERHOME/openshift-install\necho $(date) \" - Download Binaries Done.\"\n\necho $(date) \" - Setup Azure Credentials for OCP\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.azure\"\nrunuser -l $SUDOUSER -c \"touch /home/$SUDOUSER/.azure/osServicePrincipal.json\"\ncat > /home/$SUDOUSER/.azure/osServicePrincipal.json <<EOF\n{\"subscriptionId\":\"$SUBSCRIPTIONID\",\"clientId\":\"$AADCLIENTID\",\"clientSecret\":\"$AADSECRET\",\"tenantId\":\"$TENANTID\"}\nEOF\necho $(date) \" - Setup Azure Credentials for OCP - Complete\"\n\necho $(date) \" - Setup Install config\"\nrunuser -l $SUDOUSER -c \"mkdir -p $INSTALLERHOME/openshiftfourx\"\nrunuser -l $SUDOUSER -c \"touch $INSTALLERHOME/openshiftfourx/install-config.yaml\"\nzones=\"\"\nif [[ $SINGLEORMULTI == \"az\" ]]; then\nzones=\"zones:\n      - '1'\n      - '2'\n      - '3'\"\nfi\ncat > $INSTALLERHOME/openshiftfourx/install-config.yaml <<EOF\napiVersion: v1\nbaseDomain: $BASEDOMAIN\ncompute:\n- hyperthreading: Enabled\n  name: worker\n  platform: \n    azure:\n      type: $WORKERINSTANCETYPE\n      osDisk:\n        diskSizeGB: 256\n      $zones\n  replicas: $WORKERCOUNT\ncontrolPlane:\n  hyperthreading: Enabled\n  name: master\n  platform: \n    azure:\n      type: $MASTERINSTANCETYPE\n      osDisk:\n        diskSizeGB: 256\n      $zones\n  replicas: $MASTERCOUNT\nmetadata:\n  creationTimestamp: null\n  name: $CLUSTERNAME\nnetworking:\n  clusterNetwork:\n  - cidr: $CLUSTERNETWORKCIDR\n    hostPrefix: $HOSTADDRESSPREFIX\n  machineCIDR: $VIRTUALNETWORKCIDR\n  networkType: OpenShiftSDN\n  serviceNetwork:\n  - $SERVICENETWORKCIDR\nplatform:\n  azure:\n    baseDomainResourceGroupName: $BASEDOMAINRG\n    region: $LOCATION\n    networkResourceGroupName: $NETWORKRG\n    virtualNetwork: $VIRTUALNETWORKNAME\n    controlPlaneSubnet: $MASTERSUBNETNAME\n    computeSubnet: $WORKERSUBNETNAME\npullSecret: '$PULLSECRET'\nfips: $FIPS\npublish: $PUBLISH\nsshKey: |\n  $SSHKEY\nEOF\necho $(date) \" - Setup Install config - Complete\"\n\necho $(date) \" - Install OCP\"\nrunuser -l $SUDOUSER -c \"$INSTALLERHOME/openshift-install create cluster --dir=$INSTALLERHOME/openshiftfourx --log-level=debug\"\nrunuser -l $SUDOUSER -c \"sleep 120\"\necho $(date) \" - OCP Install Complete\"\n\necho $(date) \" - Kube Config setup\"\nrunuser -l $SUDOUSER -c \"mkdir -p /home/$SUDOUSER/.kube\"\nrunuser -l $SUDOUSER -c \"cp $INSTALLERHOME/openshiftfourx/auth/kubeconfig /home/$SUDOUSER/.kube/config\"\necho $(date) \"Kube Config setup done\"\n\necho $(date) \" - Setting up Cluster Autoscaler\"\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/cluster-autoscaler.yaml <<EOF\napiVersion: 'autoscaling.openshift.io/v1'\nkind: 'ClusterAutoscaler'\nmetadata:\n  name: 'default'\nspec:\n  podPriorityThreshold: -10\n  resourceLimits:\n    maxNodesTotal: 24\n    cores:\n      min: 48\n      max: 128\n    memory:\n      min: 128\n      max: 512\n  scaleDown: \n    enabled: true\n    delayAfterAdd: '3m'\n    delayAfterDelete: '2m'\n    delayAfterFailure: '30s'\n    unneededTime: '60s'\nEOF\"\nrunuser -l $SUDOUSER -c \"oc project openshift-machine-api\"\nrunuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/cluster-autoscaler.yaml\"\necho $(date) \" - Cluster Autoscaler setup complete\"\n\necho $(date) \" - Setting up Machine Autoscaler\"\nclusterid=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}' --config /home/$SUDOUSER/.kube/config)\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/machine-autoscaler.yaml <<EOF\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}1\n  namespace: 'openshift-machine-api'\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}1\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}2\n  namespace: openshift-machine-api\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}2\n---\nkind: MachineAutoscaler\napiVersion: autoscaling.openshift.io/v1beta1\nmetadata:\n  name: ${clusterid}-worker-${LOCATION}3\n  namespace: openshift-machine-api\nspec:\n  minReplicas: 1\n  maxReplicas: 12\n  scaleTargetRef:\n    apiVersion: machine.openshift.io/v1beta1\n    kind: MachineSet\n    name: ${clusterid}-worker-${LOCATION}3\nEOF\"\nrunuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/machine-autoscaler.yaml\"\necho $(date) \" - Machine Autoscaler setup complete\"\n\necho $(date) \" - Setting up Machine health checks\"\nclusterid=$(oc get machineset -n openshift-machine-api -o jsonpath='{.items[0].metadata.labels.machine\\.openshift\\.io/cluster-api-cluster}' --config /home/$SUDOUSER/.kube/config)\nrunuser -l $SUDOUSER -c \"cat > $INSTALLERHOME/openshiftfourx/machine-health-check.yaml <<EOF\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}1\n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}1\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}2 \n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}2\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\n---\napiVersion: machine.openshift.io/v1beta1\nkind: MachineHealthCheck\nmetadata:\n  name: health-check-worker-${LOCATION}3 \n  namespace: openshift-machine-api\nspec:\n  selector:\n    matchLabels:\n      machine.openshift.io/cluster-api-machine-role: worker\n      machine.openshift.io/cluster-api-machine-type: worker\n      machine.openshift.io/cluster-api-machineset: ${clusterid}-worker-${LOCATION}3\n  unhealthyConditions:\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"False\\\"\n  - type:    \\\"Ready\\\"\n    timeout: \\\"300s\\\"\n    status: \\\"Unknown\\\"\n  maxUnhealthy: \\\"30%\\\"\nEOF\"\nrunuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/machine-health-check.yaml\"\necho $(date) \" - Machine Health Check setup complete\"\n\necho $(date) \" - Setting up $STORAGEOPTION\"\nif [[ $STORAGEOPTION == \"portworx\" ]]; then\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/px-install.yaml$ARTIFACTSTOKEN -O $INSTALLERHOME/openshiftfourx/px-install.yaml\"\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/px-storageclasses.yaml$ARTIFACTSTOKEN -O $INSTALLERHOME/openshiftfourx/px-storageclasses.yaml\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/px-install.yaml\"\n  runuser -l $SUDOUSER -c \"sleep 30\"\n  runuser -l $SUDOUSER -c \"oc apply -f '$PXSPECURL'\"\n  runuser -l $SUDOUSER -c \"oc create -f $INSTALLERHOME/openshiftfourx/px-storageclasses.yaml\"\nfi\n\nif [[ $STORAGEOPTION == \"nfs\" ]]; then\n  runuser -l $SUDOUSER -c \"oc adm policy add-scc-to-user hostmount-anyuid system:serviceaccount:kube-system:nfs-client-provisioner\"\n  runuser -l $SUDOUSER -c \"wget $ARTIFACTSLOCATION/scripts/nfs-template.yaml$ARTIFACTSTOKEN -O  $INSTALLERHOME/openshiftfourx/nfs-template.yaml\"\n  runuser -l $SUDOUSER -c \"oc process -f $INSTALLERHOME/openshiftfourx/nfs-template.yaml -p NFS_SERVER=$(getent hosts $NFSHOSTNAME | awk '{ print $1 }') -p NFS_PATH=/exports/home | oc create -n kube-system -f -\"\nfi\necho $(date) \" - Setting up $STORAGEOPTION - Done\"\n\necho $(date) \" - Creating $OPENSHIFTUSER user\"\nrunuser -l $SUDOUSER -c \"htpasswd -c -B -b /tmp/.htpasswd '$OPENSHIFTUSER' '$OPENSHIFTPASSWORD'\"\nrunuser -l $SUDOUSER -c \"sleep 3\"\nrunuser -l $SUDOUSER -c \"oc create secret generic htpass-secret --from-file=htpasswd=/tmp/.htpasswd -n openshift-config\"\nrunuser -l $SUDOUSER -c \"cat >  $INSTALLERHOME/openshiftfourx/auth.yaml <<EOF\napiVersion: config.openshift.io/v1\nkind: OAuth\nmetadata:\n  name: cluster\nspec:\n  tokenConfig:\n    accessTokenMaxAgeSeconds: 172800\n  identityProviders:\n  - name: htpasswdProvider \n    challenge: true \n    login: true \n    mappingMethod: claim \n    type: HTPasswd\n    htpasswd:\n      fileData:\n        name: htpass-secret\nEOF\"\nrunuser -l $SUDOUSER -c \"oc apply -f $INSTALLERHOME/openshiftfourx/auth.yaml\"\nrunuser -l $SUDOUSER -c \"oc adm policy add-cluster-role-to-user cluster-admin '$OPENSHIFTUSER'\"\n\necho $(date) \" - #################### Script Complete #####################\"\n", "num_lines": 348}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\nyum install -y nfs-utils\nyum install -y rpcbind\nsystemctl unmask firewalld\nsystemctl start firewalld\nsystemctl start nfs-server\nsystemctl enable nfs-server\nmkdir -p /exports/home\necho \"/exports/home *(rw,sync,subtree_check,no_root_squash)\" >> /etc/exports\nmkfs.xfs /dev/sdc\nsleep 10\nmount /dev/sdc /exports/home\nchown -R nfsnobody:nfsnobody /exports/home\nchmod -R 777 /exports/home\nexportfs -a\nfirewall-cmd --permanent --add-service=mountd\nfirewall-cmd --permanent --add-service=nfs\nfirewall-cmd --permanent --add-service=rpc-bind\nfirewall-cmd --reload\necho \"\\$(sudo blkid | grep /dev/sdc | awk '{print \\$2}') /exports/home        xfs     defaults    0 0\" >> /etc/fstab", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-server php5 php5-mysql\n\n# update bind-address for mysql\nsed -i \"s/bind-address.*/bind-address = 0.0.0.0/\" /etc/mysql/my.cnf\n\n# adding grant privileges to mysql root user from everywhere\nMYSQL=`which mysql`\n\nQ1=\"GRANT ALL ON *.* TO 'root'@'%' IDENTIFIED BY '$dbpass' WITH GRANT OPTION;\"\nQ2=\"FLUSH PRIVILEGES;\"\nSQL=\"${Q1}${Q2}\"\n\n$MYSQL -uroot -p$dbpass -e \"$SQL\"\n\nservice mysql restart\n\n# restart Apache\napachectl restart\n", "num_lines": 30}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-server php5 php5-mysql\n\n# install OpenSIS\ncd /var/www/html\nwget http://nchc.dl.sourceforge.net/project/opensis-ce/opensis6.4.zip -O opensis.zip\napt-get -y install unzip\nunzip opensis.zip\n\n# make the opensis-ce directory writable\nchown -R www-data opensis\nchmod -R 770 opensis\n\napachectl restart\n\n# add port 8000 for admin access\nperl -0777 -p -i -e 's/Listen 80/Listen 80\\nListen 8080/ig' /etc/apache2/ports.conf\nperl -0777 -p -i -e 's/\\*:80/*:80 *:8080/g' /etc/apache2/sites-enabled/000-default.conf\n\n# restart Apache\napachectl restart\n", "num_lines": 32}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-server php5 php5-mysql\n\n# install OpenSIS\ncd /var/www/html\nwget http://nchc.dl.sourceforge.net/project/opensis-ce/opensis6.4.zip -O opensis.zip\napt-get -y install unzip\nunzip opensis.zip\n\n# make the opensis-ce directory writable\nchown -R www-data opensis\nchmod -R 770 opensis\n\n# restart Apache\napachectl restart\n", "num_lines": 26}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 7.x (7.8+), RHEL 7.x (7.8+) and Ubuntu 18.04 LTS.\nMOUNTPOINT=\"/hxdata\"\n\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\nLOG=/tmp/init.log\n\nwhile getopts w:p:s: option\ndo\n  case \"${option}\"\n  in\n    w) PASSWORD=${OPTARG};;\n    p) P4PORT=${OPTARG};;\n    s) SWARMPORT=${OPTARG};;\n  esac\ndone\n\nP4PORT=\"${P4PORT:-1666}\"\nSWARMPORT=\"${SWARMPORT:-80}\"\necho \"P4PORT: $P4PORT\" >> $LOG\necho \"SWARMPORT: $SWARMPORT\" >> $LOG\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n    grep redhat /proc/version > /dev/null 2>&1\n    isredhat=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} xfs     defaults       0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n\tls \"${MOUNTPOINT}\"\n\tif [ ${?} -eq 0 ]\n\tthen\n\t\treturn\n\tfi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    DISK=\"${DISKS[0]}\"\n    do_partition ${DISK}\n    PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t xfs ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=permissive/I' /etc/selinux/config\n    setenforce 0\n}\n\nconfigure_network() {\n    # open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        disable_selinux_centos\n    elif [ $isredhat -eq 0 ];\n    then\n        disable_selinux_centos\n        firewall-cmd --zone=public --add-port=\"$SWARMPORT/tcp\" --permanent\n        firewall-cmd --zone=public --add-port=\"$P4PORT/tcp\" --permanent\n        firewall-cmd --reload\n    elif [ $isubuntu -eq 0 ];\n    then\n        disable_apparmor_ubuntu\n    fi\n}\n\n\nconfigure_helix() {\n    useradd --shell /bin/bash --home-dir /p4 --create-home perforce\n    cd \"$MOUNTPOINT\"\n    mkdir hxlogs hxmetadata hxdepots\n    chown -R perforce:perforce \"$MOUNTPOINT\"\n    cd /\n    ln -s $MOUNTPOINT/hx* .\n    chown -h perforce:perforce hx*\n\n    mkdir -p /hxdepots/reset\n    cd /hxdepots/reset\n\n    curl -k -s -O https://swarm.workshop.perforce.com/downloads/guest/perforce_software/helix-installer/azure-quickstart/src/arm_install_sdp.sh\n\n    chmod +x arm_install_sdp.sh\n    ./arm_install_sdp.sh -p4port \"${P4PORT}\" -p4adminpass \"${PASSWORD}\" -swarmport \"${SWARMPORT}\" > arm_install_sdp.log 2>&1\n}\n\ncheck_os\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0 ] && [ $isredhat -ne 0 ];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_helix\nfi\n", "num_lines": 178}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /opt/\n\necho \"PHABRICATOR UBUNTU INSTALL SCRIPT\";\necho \"This script will install Phabricator and all of its core dependencies.\";\necho \"Run it from the directory you want to install into.\";\necho\n\nROOT=`pwd`\necho \"Phabricator will be installed to: ${ROOT}.\";\n\necho \"Testing sudo...\"\nsudo true\nif [ $? -ne 0 ]\nthen\n  echo \"ERROR: You must be able to sudo to run this script.\";\n  exit 1;\nfi;\n\necho \"Installing dependencies: git, apache, mysql, php...\";\necho\n\nset +x\n\nsudo apt-get -qq update\nsudo apt-get -y install git apache2 dpkg-dev php7.0 php7.0-mysql php7.0-gd php7.0-dev php7.0-curl php7.0-cli php7.0-json libapache2-mod-php7.0 php7.0-mbstring\n\n# Enable mod_rewrite\nsudo a2enmod rewrite\n\nif [ ! -e libphutil ]\nthen\n  git clone https://github.com/phacility/libphutil.git\nelse\n  (cd libphutil && git pull --rebase)\nfi\n\nif [ ! -e arcanist ]\nthen\n  git clone https://github.com/phacility/arcanist.git\nelse\n  (cd arcanist && git pull --rebase)\nfi\n\nif [ ! -e phabricator ]\nthen\n  git clone https://github.com/phacility/phabricator.git\nelse\n  (cd phabricator && git pull --rebase)\nfi\n\nsudo echo 'mysql-server mysql-server/root_password password pass@word1' | debconf-set-selections\nsudo echo 'mysql-server mysql-server/root_password_again password pass@word1' | debconf-set-selections\nsudo apt-get -y install mysql-server\n\n\nsudo touch /etc/apache2/sites-available/phabricator.conf\n\nsudo echo \"<VirtualHost *>\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"  ServerName $1\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"  DocumentRoot /opt/phabricator/webroot\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"  RewriteEngine on\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"  RewriteRule ^/rsrc/(.*)     -                       [L,QSA]\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"  RewriteRule ^/favicon.ico   -                       [L,QSA]\" >> /etc/apache2/sites-available/phabricator.conf\nsudo echo '  RewriteRule ^(.*)$          /index.php?__path__=$1  [B,L,QSA]' >> /etc/apache2/sites-available/phabricator.conf\nsudo echo \"</VirtualHost>\" >> /etc/apache2/sites-available/phabricator.conf\n\nsudo echo '<Directory \"/opt/phabricator/webroot\">' >> /etc/apache2/apache2.conf\nsudo echo '  Require all granted' >> /etc/apache2/apache2.conf\nsudo echo \"</Directory>\" >> /etc/apache2/apache2.conf\n\nsudo a2dissite 000-default.conf\nsudo a2ensite phabricator.conf\nsudo service apache2 reload\n\n\nsudo /opt/phabricator/bin/config set mysql.user root\nsudo /opt/phabricator/bin/config set mysql.pass pass@word1\n\nsudo /opt/phabricator/bin/storage upgrade --force\n\necho\necho \"Install probably worked mostly correctly. Continue with the 'Configuration Guide':\";\necho\necho \"    https://secure.phabricator.com/book/phabricator/article/configuration_guide/\";\necho\necho \"You can delete any php5-* stuff that's left over in this directory if you want.\";\n", "num_lines": 91}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n#\n# Author: Full Scale 180 Inc.\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n#Format the data disk\nbash vm-disk-utils-0.1.sh -s\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM (If it does not exist add it)\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? == 0 ];\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hsots file if not there\n  echo \"127.0.0.1 ${HOSTNAME}\" >> /etc/hosts\nfi\n\n# Get today's date into YYYYMMDD format\nnow=$(date +\"%Y%m%d\")\n\n# Get passed in parameters $1, $2, $3, $4, and others...\nMASTERIP=\"\"\nSUBNETADDRESS=\"\"\nNODETYPE=\"\"\nREPLICATORPASSWORD=\"\"\n\n#Loop through options passed\nwhile getopts :m:s:t:p: optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    m)\n      MASTERIP=${OPTARG}\n      ;;\n  \ts) #Data storage subnet space\n      SUBNETADDRESS=${OPTARG}\n      ;;\n    t) #Type of node (MASTER/SLAVE)\n      NODETYPE=${OPTARG}\n      ;;\n    p) #Replication Password\n      REPLICATORPASSWORD=${OPTARG}\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nexport PGPASSWORD=$REPLICATORPASSWORD\n\nlogger \"NOW=$now MASTERIP=$MASTERIP SUBNETADDRESS=$SUBNETADDRESS NODETYPE=$NODETYPE\"\n\ninstall_postgresql_service() {\n\tlogger \"Start installing PostgreSQL 10...\"\n\t# Re-synchronize the package index files from their sources. An update should always be performed before an upgrade.\n\tapt-get -y update\n\n\t# Install PostgreSQL if it is not yet installed\n\tif [ $(dpkg-query -W -f='${Status}' postgresql 2>/dev/null | grep -c \"ok installed\") -eq 0 ];\n\tthen\n\t  apt-get -y install postgresql-10 postgresql-contrib-10 postgresql-client-10\n\tfi\n\n\tlogger \"Start installing PostgreSQL 10...\"\n}\n\nsetup_datadisks() {\n\n\tMOUNTPOINT=\"/datadisks/disk1\"\n\n\t# Move database files to the striped disk\n\tif [ -L /var/lib/postgresql/9.3/main ];\n\tthen\n\t\tlogger \"Symbolic link from /var/lib/postgresql/9.3/main already exists\"\n\t\techo \"Symbolic link from /var/lib/postgresql/9.3/main already exists\"\n\telse\n\t\tlogger \"Moving  data to the $MOUNTPOINT/main\"\n\t\techo \"Moving PostgreSQL data to the $MOUNTPOINT/main\"\n\t\tservice postgresql stop\n\t\t# mkdir $MOUNTPOINT/main\n\t\tmv -f /var/lib/postgresql/9.3/main $MOUNTPOINT\n\n\t\t# Create symbolic link so that configuration files continue to use the default folders\n\t\tlogger \"Create symbolic link from /var/lib/postgresql/9.3/main to $MOUNTPOINT/main\"\n\t\tln -s $MOUNTPOINT/main /var/lib/postgresql/9.3/main\n\n        chown postgres:postgres $MOUNTPOINT/main\n        chmod 0700 $MOUNTPOINT/main\n\tfi\n}\n\nconfigure_streaming_replication() {\n\tlogger \"Starting configuring PostgreSQL streaming replication...\"\n\n\t# Configure the MASTER node\n\tif [ \"$NODETYPE\" == \"MASTER\" ];\n\tthen\n\t\tlogger \"Create user replicator...\"\n\t\techo \"CREATE USER replicator WITH REPLICATION PASSWORD '$PGPASSWORD';\"\n\t\tsudo -u postgres psql -c \"CREATE USER replicator WITH REPLICATION PASSWORD '$PGPASSWORD';\"\n\tfi\n\n\t# Stop service\n\tservice postgresql stop\n\n\t# Update configuration files\n\tcd /etc/postgresql/9.3/main\n\n\tif grep -Fxq \"# install_postgresql.sh\" pg_hba.conf\n\tthen\n\t\tlogger \"Already in pg_hba.conf\"\n\t\techo \"Already in pg_hba.conf\"\n\telse\n\t\t# Allow access from other servers in the same subnet\n\t\techo \"\" >> pg_hba.conf\n\t\techo \"# install_postgresql.sh\" >> pg_hba.conf\n\t\techo \"host replication replicator $SUBNETADDRESS md5\" >> pg_hba.conf\n\t\techo \"hostssl replication replicator $SUBNETADDRESS md5\" >> pg_hba.conf\n\t\techo \"\" >> pg_hba.conf\n\n\t\tlogger \"Updated pg_hba.conf\"\n\t\techo \"Updated pg_hba.conf\"\n\tfi\n\n\tif grep -Fxq \"# install_postgresql.sh\" postgresql.conf\n\tthen\n\t\tlogger \"Already in postgresql.conf\"\n\t\techo \"Already in postgresql.conf\"\n\telse\n\t\t# Change configuration including both master and slave configuration settings\n\t\techo \"\" >> postgresql.conf\n\t\techo \"# install_postgresql.sh\" >> postgresql.conf\n\t\techo \"listen_addresses = '*'\" >> postgresql.conf\n\t\techo \"wal_level = hot_standby\" >> postgresql.conf\n\t\techo \"max_wal_senders = 10\" >> postgresql.conf\n\t\techo \"wal_keep_segments = 500\" >> postgresql.conf\n\t\techo \"archive_mode = on\" >> postgresql.conf\n\t\techo \"archive_command = 'cd .'\" >> postgresql.conf\n\t\techo \"hot_standby = on\" >> postgresql.conf\n\t\techo \"\" >> postgresql.conf\n\n\t\tlogger \"Updated postgresql.conf\"\n\t\techo \"Updated postgresql.conf\"\n\tfi\n\n\t# Synchronize the slave\n\tif [ \"$NODETYPE\" == \"SLAVE\" ];\n\tthen\n\t\t# Remove all files from the slave data directory\n\t\tlogger \"Remove all files from the slave data directory\"\n\t\tsudo -u postgres rm -rf /datadisks/disk1/main\n\n\t\t# Make a binary copy of the database cluster files while making sure the system is put in and out of backup mode automatically\n\t\tlogger \"Make binary copy of the data directory from master\"\n\t\tsudo PGPASSWORD=$PGPASSWORD -u postgres pg_basebackup -h $MASTERIP -D /datadisks/disk1/main -U replicator\n\n\t\t# Create recovery file\n\t\tlogger \"Create recovery.conf file\"\n\t\tcd /var/lib/postgresql/9.3/main/\n\n\t\tsudo -u postgres echo \"standby_mode = 'on'\" > recovery.conf\n\t\tsudo -u postgres echo \"primary_conninfo = 'host=$MASTERIP port=5432 user=replicator password=$PGPASSWORD'\" >> recovery.conf\n\t\tsudo -u postgres echo \"trigger_file = '/var/lib/postgresql/9.3/main/failover'\" >> recovery.conf\n\tfi\n\n\tlogger \"Done configuring PostgreSQL streaming replication\"\n}\n\n# MAIN ROUTINE\ninstall_postgresql_service\n\nsetup_datadisks\n\nservice postgresql start\n\nconfigure_streaming_replication\n\nservice postgresql start\n\n", "num_lines": 219}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsudo apt-get update\n#install the necessary tools\nsudo apt-get install gcc make libreadline6-dev zlib1g-dev -y\n#download postgresql source code\nwget https://ftp.postgresql.org/pub/source/v9.3.5/postgresql-9.3.5.tar.bz2 -P /tmp 2>/dev/null\ncd /tmp\ntar jxvf postgresql-9.3.5.tar.bz2\ncd postgresql-9.3.5\n\n#install postgresql\n./configure --prefix=/opt/postgresql-9.3.5\nsudo make install-world 2> /dev/null\n\n#create postgres user for postgresql\nsudo ln -s /opt/postgresql-9.3.5 /opt/pgsql\nsudo mkdir -p /opt/pgsql_data\nsudo useradd -m postgres\nsudo chown -R postgres.postgres /opt/pgsql_data\n\n#/tmp/postgres.sh contains the steps of setup the user postgres' environment, initialize the database\nsudo touch /home/postgres/.bash_profile\nsudo chown postgres.postgres /home/postgres/.bash_profile\ncat >> /tmp/postgres.sh <<EOF\ncat >> /home/postgres/.bash_profile <<EOFF\nexport PGPORT=1999\nexport PGDATA=/opt/pgsql_data\nexport LANG=en_US.utf8\nexport PGHOME=/opt/pgsql\nexport PATH=\\\\\\$PATH:\\\\\\$PGHOME/bin\nexport MANPATH=\\\\\\$MANPATH:\\\\\\$PGHOME/share/man\nexport DATA=\\`date +\"%Y%m%d%H%M\"\\`\nexport PGUSER=postgres\nalias rm='rm -i'\nalias ll='ls -lh'\nEOFF\nsource /home/postgres/.bash_profile\n\n#initialize the database\ninitdb -D \\$PGDATA -E UTF8 --locale=C -U postgres 2> /dev/null\nEOF\n\n#su to postgres to execute /tmp/postgres.sh\nsudo su - postgres -s /bin/bash /tmp/postgres.sh\n#instead we can use sudo su - postgres -c \"initdb -D \\$PGDATA -E UTF8 --locale=C -U postgres\"\n\n#postgresql configuration\ncd /tmp/postgresql-9.3.5/contrib/start-scripts\nsudo cp linux /etc/init.d/postgresql\nsudo sed -i '32s#usr/local#opt#' /etc/init.d/postgresql\nsudo sed -i '35s#usr/local/pgsql/data#opt/pgsql_data#' /etc/init.d/postgresql\nsudo chmod +x /etc/init.d/postgresql\n\n#start postgresql\nsudo /etc/init.d/postgresql start\n\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n\nsed -i \"2i$1 $2\" /etc/hosts\nsed -i \"2i$1 $3\" /etc/hosts\ncurl -k https://$3:8140/packages/current/install.bash | sudo bash\n", "num_lines": 6}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo dpkg --configure -a\nsudo apt-get install -y build-essential libssl-dev libffi-dev software-properties-common python3-pip\n\npip3 install --upgrade proxy.py\n\npython3 -m proxy > /dev/null 2>&1 &", "num_lines": 9}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nworkserver_path=/srv/workserver\nmkdir $workserver_path\ncp workserver.py $workserver_path\n\n# install python3-bottle\napt-get -y update\napt-get -y install python3-bottle\n\n# create a service\ntouch /etc/systemd/system/workserver.service\nprintf '[Unit]\\nDescription=workServer Service\\nAfter=rc-local.service\\n' >> /etc/systemd/system/workserver.service\nprintf '[Service]\\nWorkingDirectory=%s\\n' $workserver_path >> /etc/systemd/system/workserver.service\nprintf 'ExecStart=/usr/bin/python3 %s/workserver.py\\n' $workserver_path >> /etc/systemd/system/workserver.service\nprintf 'ExecReload=/bin/kill -HUP $MAINPID\\nKillMode=process\\nRestart=on-failure\\n' >> /etc/systemd/system/workserver.service\nprintf '[Install]\\nWantedBy=multi-user.target\\nAlias=workserver.service' >> /etc/systemd/system/workserver.service\nchmod +x /etc/systemd/system/workserver.service\n\nservice workserver start\n\n\n\n", "num_lines": 23}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# install required tools\nsudo apt update\nsudo apt install -y curl jq\n\nMY_RUNNER_AGENTNAME=$1\nMY_RUNNER_REPO=$2\nMY_RUNNER_TOKEN=$3\nMY_RUNNER_LOCALADMIN=$4\n\necho \"runner name: ${MY_RUNNER_AGENTNAME}\"\necho \"runner scope: ${MY_RUNNER_REPO}\"\necho \"runner user: ${MY_RUNNER_LOCALADMIN}\"\n\npushd /home/${MY_RUNNER_LOCALADMIN}\n\n# run the automation script\n# https://github.com/actions/runner/blob/master/docs/automate.md\ncurl -s https://raw.githubusercontent.com/actions/runner/automate/scripts/create-latest-svc.sh | sudo RUNNER_CFG_PAT=\"${MY_RUNNER_TOKEN}\" RUNNER_ALLOW_RUNASROOT=\"1\" bash -s -- \"${MY_RUNNER_REPO}\" \"${MY_RUNNER_AGENTNAME}\" \"${MY_RUNNER_LOCALADMIN}\"\n", "num_lines": 23}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# environment setup\nsudo locale-gen en_US en_US.UTF-8\nsudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8\nexport LANG=en_US.UTF-8\n\n# authorize ROS GPG key\nsudo apt update\nsudo apt install -y curl gnupg2 lsb-release\ncurl -sSL 'http://keyserver.ubuntu.com/pks/lookup?op=get&search=0xC1CF6E31E6BADE8868B172B4F42ED6FBAB17C654' | sudo apt-key add -\ncurl -s https://raw.githubusercontent.com/ros/rosdistro/master/ros.asc | sudo apt-key add -\n\n# add ROS package repositories to source list\nsudo sh -c 'echo \"deb http://packages.ros.org/ros2/ubuntu $(lsb_release -sc) main\" > /etc/apt/sources.list.d/ros2-latest.list'\nsudo sh -c 'echo \"deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main\" > /etc/apt/sources.list.d/ros-latest.list'\n\n# get the latest repository\nsudo apt update\n\n# install required tools\nsudo apt install -y python-rosdep\nsudo apt install -y python-pip\nsudo apt install -y python3-pip\nsudo apt install -y xvfb\n\n# install ROS distro\nsudo apt install -y ros-melodic-desktop-full\nsudo apt install -y ros-dashing-desktop\n\n# rosdep init\nsudo rosdep init\n", "num_lines": 35}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -e\n\n# install required tools\nsudo apt update\nsudo apt install -y curl jq\n\nVSTS_AGENTNAME=$1\nVSTS_ACCOUNT=$2\nVSTS_TOKEN=$3\nVSTS_POOL=$4\n\nDESTINATION=\"$HOME/vsts-agent\"\n\nmkdir -p $DESTINATION\n\n# download the latest agent\nVSTSVERSION=$(curl -s \"https://api.github.com/repos/microsoft/azure-pipelines-agent/releases/latest\" | jq -r .tag_name[1:])\necho $VSTSVERSION\ncurl -LO https://vstsagentpackage.azureedge.net/agent/${VSTSVERSION}/vsts-agent-linux-x64-${VSTSVERSION}.tar.gz\ntar -zxvf vsts-agent-linux-x64-${VSTSVERSION}.tar.gz -C $DESTINATION\n\nchmod -R 777 $DESTINATION\n\n# configure\nsudo AGENT_ALLOW_RUNASROOT=\"1\" $DESTINATION/config.sh --unattended \\\n  --agent \"$VSTS_AGENTNAME\" \\\n  --url \"https://dev.azure.com/$VSTS_ACCOUNT\" \\\n  --auth PAT \\\n  --token \"$VSTS_TOKEN\" \\\n  --pool \"$VSTS_POOL\" \\\n  --replace \\\n  --acceptTeeEula\n\necho \"configuration done\"\n\npushd $DESTINATION\n\nsudo ./svc.sh install\n\necho \"service installed\"\n\nsudo ./svc.sh start\n\necho \"service started\"\n", "num_lines": 47}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho $*\n\n# Start PowerShell config script\nexport SAFEKITCMD=\"/opt/safekit/safekit\"\nexport SAFEVAR=\"/var/safekit\"\nexport SAFEWEBCONF=\"/opt/safekit/web/conf\"\nexport SAFEBASE=\"/opt/safekit\"\nexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:/opt/safekit/private/bin\"\npwsh ./configCluster.ps1 -vmlist \"$1\" -publicipfmt \"$2\" -privateiplist \"$3\" -lblist \"$4\" -Passwd \"$5\"\n", "num_lines": 12}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Install SafeKit from `ls ./*.bin`\"\n\n\nchmod +x ./safekit*.bin\n./safekit*.bin\n\n\nyum -y localinstall ./safekit*.rpm\n#rm ./safekit*.bin ./safekit*.rpm\n\necho \"Install powershell\"\n# Register the Microsoft RedHat repository\ncurl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo\nyum update powershell\n# Install PowerShell\nyum install -y powershell\nif [ -f \"installAzureRM.ps1\" ]; then\n\tpwsh ./installAzureRM.ps1 -linux\nfi\necho \"starting CA helper service\"\ncd /opt/safekit/web/bin\n./startcaserv \"$2\"\n", "num_lines": 25}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n/opt/safekit/safekit shutdown\n/opt/safekit/safekit uninstall\n\necho \"Install SafeKit\"\nyum -y localinstall $1\n", "num_lines": 8}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho $*\n\n# Start PowerShell config script\nexport SAFEKITCMD=\"/opt/safekit/safekit\"\nexport SAFEVAR=\"/var/safekit\"\nexport SAFEWEBCONF=\"/opt/safekit/web/conf\"\nexport SAFEBASE=\"/opt/safekit\"\nexport LD_LIBRARY_PATH=\"$LD_LIBRARY_PATH:/opt/safekit/private/bin\"\npwsh ./configCluster.ps1 -vmlist \"$1\" -publicipfmt \"$2\" -privateiplist \"$3\" -lblist \"$4\" -Passwd \"$5\"\n", "num_lines": 12}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Install SafeKit from `ls ./*.bin`\"\n\n\nchmod +x ./safekit*.bin\n./safekit*.bin\n\n\nyum -y localinstall ./safekit*.rpm\n#rm ./safekit*.bin ./safekit*.rpm\n\necho \"Install powershell\"\n# Register the Microsoft RedHat repository\ncurl https://packages.microsoft.com/config/rhel/7/prod.repo | sudo tee /etc/yum.repos.d/microsoft.repo\nyum update powershell\n# Install PowerShell\nyum install -y powershell\n\nmkdir /replicated\necho \"This is a replicated file\" >/replicated/repfile.txt\n\nif [ -f \"installAzureRM.ps1\" ]; then\n\tpwsh ./installAzureRM.ps1 -linux\nfi\necho \"starting CA helper service\"\ncd /opt/safekit/web/bin\n./startcaserv \"$2\"\n", "num_lines": 29}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n/opt/safekit/safekit shutdown\n/opt/safekit/safekit uninstall\n\necho \"Install SafeKit\"\nyum -y localinstall $1\n", "num_lines": 8}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# create-mdadm <lun array> <mdadm path e.g. /dev/md127> <mount path e.g. /dbdata>\n# TODO: SWAP file\n# TODO: run /usr/sbin/SAPconf\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n\tlog \"addtofstab\"\n\tpartPath=$1\n\tlocal blkid=$(/sbin/blkid $partPath)\n\tif [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n\tthen\n\t\tlog \"Adding fstab entry\"\n\t\tlocal uuid=${BASH_REMATCH[1]};\n\t\tlocal mountCmd=\"\"\n\t\tlog \"adding fstab entry\"\n\t\tmountCmd=\"/dev/disk/by-uuid/$uuid $mountPath xfs  defaults,nofail  0  2\"\n\t\techo \"$mountCmd\" >> /etc/fstab\n\t\t$(mount $mountPath)\n\telse\n\t\tlog \"no UUID found\"\n\t\texit -1;\n\tfi\n\tlog \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\tlog \"getdevicepath\"\n\tgetdevicepathresult=\"\"\n\tlocal lun=$1\n\tlocal scsiOutput=$(lsscsi)\n\tif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n\tthen\n\t\tgetdevicepathresult=${BASH_REMATCH[1]};\n\telse\n\t\tlog \"lsscsi output not as expected for $lun\"\n\t\texit -1;\n\tfi\n\tlog \"getdevicepath done\"\n}\n\nfunction createlvm()\n{\n\tlog \"createlvm\"\n\n\tlunsA=(${1//,/ })\n\tvgName=$2\n\tlvName=$3\n\tmountPath=$4\n\n\tarraynum=${#lunsA[@]}\n\techo \"count $arraynum\"\n\tif [[ $arraynum -gt 1 ]]\n\tthen\n\t\tlog \"createlvm - creating lvm\"\n\n\t\tnumRaidDevices=0\n\t\traidDevices=\"\"\n\t\tnum=${#lunsA[@]}\n\t\tlog \"num luns $num\"\n\t\tfor ((i=0; i<num; i++))\n\t\tdo\n\t\t\tlog \"trying to find device path\"\n\t\t\tlun=${lunsA[$i]}\n\t\t\tgetdevicepath $lun\n\t\t\tdevicePath=$getdevicepathresult;\n\t\t\tif [ -n \"$devicePath\" ];\n\t\t\tthen\n\t\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t\tnumRaidDevices=$((numRaidDevices + 1))\n\t\t\t\traidDevices=\"$raidDevices $devicePath \"\n\t\t\telse\n\t\t\t\tlog \"no device path for LUN $lun\"\n\t\t\t\texit -1;\n\t\t\tfi\n\t\tdone\n\t\tlog \"num: $numRaidDevices paths: '$raidDevices'\"\n\t\t$(pvcreate $raidDevices)\n\t\t$(vgcreate $vgName $raidDevices)\n\t\t$(lvcreate --extents 100%FREE --stripes $numRaidDevices --name $lvName $vgName)\n\t\t$(mkfs -t xfs /dev/$vgName/$lvName)\n\n\t\t$(mkdir $mountPath)\n\t\taddtofstab /dev/$vgName/$lvName\n\telse\n\t\tlog \"createlvm - creating single disk\"\n\n\t\tlun=${lunsA[0]}\n\t\tgetdevicepath $lun;\n\t\tdevicePath=$getdevicepathresult;\n\t\tif [ -n \"$devicePath\" ];\n\t\tthen\n\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t# http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n\t\t\t$(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath)\n\t\t\tpartPath=\"$devicePath\"\"1\"\n\t\t\t$(mkfs -t xfs $partPath)\n\t\t\t$(mkdir $mountPath)\n\n\t\t\taddtofstab $partPath\n\t\telse\n\t\t\tlog \"no device path for LUN $lun\"\n\t\t\texit -1;\n\t\tfi\n\tfi\n\n\tlog \"createlvm done\"\n\n}\n\ndbluns=\"\"\ndbname=\"dbdata\"\nlogluns=\"\"\nlogname=\"dblog\"\n\nwhile true; do\n\tcase \"$1\" in\n    \"-DBLogLUNS\")  logluns=$2;shift 2;\n        ;;\n    \"-DBDataLUNS\")  dbluns=$2;shift 2;\n\t        ;;\n\t\"-DBDataName\")  dbname=$2;shift 2;\n        ;;\n\t\"-DBLogName\")  logname=$2;shift 2;\n        ;;\n    esac\n\tif [[ -z \"$1\" ]]; then break; fi\ndone\n\nif [[ -n \"$dbluns\" ]];\nthen\n\tcreatelvm $dbluns \"vg-$dbname\" \"lv-$dbname\" \"/$dbname\";\nfi\n\nif [[ -n \"$logluns\" ]];\nthen\n\tcreatelvm $logluns \"vg-$logname\" \"lv-$logname\" \"/$logname\";\nfi\n", "num_lines": 147}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\n\n\nlog \"noop\"\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n\n  local blkid=$(/sbin/blkid $partPath)\n\n  if [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n  then\n\n    log \"Adding fstab entry\"\n    local uuid=${BASH_REMATCH[1]};\n    local mountCmd=\"\"\n    log \"adding fstab entry\"\n    mountCmd=\"/dev/disk/by-uuid/$uuid $mount xfs  defaults,nofail  0  2\"\n    echo \"$mountCmd\" >> /etc/fstab\n    $(mount $partPath $mount)\n\n  else\n    log \"no UUID found\"\n    exit -1;\n  fi\n\n  log \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n      # http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n      $(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath) > /dev/null\n      local partPath=\"$devicePath\"\"1\"\n      $(mkfs -t xfs $partPath) > /dev/null\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab $partPath $mountPathLoc\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nexit\n", "num_lines": 201}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# create-mdadm <lun array> <mdadm path e.g. /dev/md127> <mount path e.g. /dbdata>\n# TODO: SWAP file\n# TODO: run /usr/sbin/SAPconf\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n\tlog \"addtofstab\"\n\tpartPath=$1\n\tlocal blkid=$(/sbin/blkid $partPath)\n\tif [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n\tthen\n\t\tlog \"Adding fstab entry\"\n\t\tlocal uuid=${BASH_REMATCH[1]};\n\t\tlocal mountCmd=\"\"\n\t\tlog \"adding fstab entry\"\n\t\tmountCmd=\"/dev/disk/by-uuid/$uuid $mountPath xfs  defaults,nofail  0  2\"\n\t\techo \"$mountCmd\" >> /etc/fstab\n\t\t$(mount $mountPath)\n\telse\n\t\tlog \"no UUID found\"\n\t\texit -1;\n\tfi\n\tlog \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\tlog \"getdevicepath\"\n\tgetdevicepathresult=\"\"\n\tlocal lun=$1\n\tlocal scsiOutput=$(lsscsi)\n\tif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n\tthen\n\t\tgetdevicepathresult=${BASH_REMATCH[1]};\n\telse\n\t\tlog \"lsscsi output not as expected for $lun\"\n\t\texit -1;\n\tfi\n\tlog \"getdevicepath done\"\n}\n\nfunction createlvm()\n{\n\tlog \"createlvm\"\n\n\tlunsA=(${1//,/ })\n\tvgName=$2\n\tlvName=$3\n\tmountPath=$4\n\n\tarraynum=${#lunsA[@]}\n\techo \"count $arraynum\"\n\tif [[ $arraynum -gt 1 ]]\n\tthen\n\t\tlog \"createlvm - creating lvm\"\n\n\t\tnumRaidDevices=0\n\t\traidDevices=\"\"\n\t\tnum=${#lunsA[@]}\n\t\tlog \"num luns $num\"\n\t\tfor ((i=0; i<num; i++))\n\t\tdo\n\t\t\tlog \"trying to find device path\"\n\t\t\tlun=${lunsA[$i]}\n\t\t\tgetdevicepath $lun\n\t\t\tdevicePath=$getdevicepathresult;\n\t\t\tif [ -n \"$devicePath\" ];\n\t\t\tthen\n\t\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t\tnumRaidDevices=$((numRaidDevices + 1))\n\t\t\t\traidDevices=\"$raidDevices $devicePath \"\n\t\t\telse\n\t\t\t\tlog \"no device path for LUN $lun\"\n\t\t\t\texit -1;\n\t\t\tfi\n\t\tdone\n\t\tlog \"num: $numRaidDevices paths: '$raidDevices'\"\n\t\t$(pvcreate $raidDevices)\n\t\t$(vgcreate $vgName $raidDevices)\n\t\t$(lvcreate --extents 100%FREE --stripes $numRaidDevices --name $lvName $vgName)\n\t\t$(mkfs -t xfs /dev/$vgName/$lvName)\n\n\t\t$(mkdir $mountPath)\n\t\taddtofstab /dev/$vgName/$lvName\n\telse\n\t\tlog \"createlvm - creating single disk\"\n\n\t\tlun=${lunsA[0]}\n\t\tgetdevicepath $lun;\n\t\tdevicePath=$getdevicepathresult;\n\t\tif [ -n \"$devicePath\" ];\n\t\tthen\n\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t# http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n\t\t\t$(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath)\n\t\t\tpartPath=\"$devicePath\"\"1\"\n\t\t\t$(mkfs -t xfs $partPath)\n\t\t\t$(mkdir $mountPath)\n\n\t\t\taddtofstab $partPath\n\t\telse\n\t\t\tlog \"no device path for LUN $lun\"\n\t\t\texit -1;\n\t\tfi\n\tfi\n\n\tlog \"createlvm done\"\n\n}\n\ndbluns=\"\"\ndbname=\"dbdata\"\nlogluns=\"\"\nlogname=\"dblog\"\n\nwhile true; do\n\tcase \"$1\" in\n    \"-DBLogLUNS\")  logluns=$2;shift 2;\n        ;;\n    \"-DBDataLUNS\")  dbluns=$2;shift 2;\n\t        ;;\n\t\"-DBDataName\")  dbname=$2;shift 2;\n        ;;\n\t\"-DBLogName\")  logname=$2;shift 2;\n        ;;\n    esac\n\tif [[ -z \"$1\" ]]; then break; fi\ndone\n\nvLinux=$(cat /etc/os-release)\nif [[ $vLinux =~ NAME=\\\"Oracle ]];\nthen\n    yum -y install lsscsi lvm2\nfi\n\nif [[ -n \"$dbluns\" ]];\nthen\n\tcreatelvm $dbluns \"vg-$dbname\" \"lv-$dbname\" \"/$dbname\";\nfi\n\nif [[ -n \"$logluns\" ]];\nthen\n\tcreatelvm $logluns \"vg-$logname\" \"lv-$logname\" \"/$logname\";\nfi\n", "num_lines": 153}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\n\n\nlog \"noop\"\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n\n  local blkid=$(/sbin/blkid $partPath)\n\n  if [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n  then\n\n    log \"Adding fstab entry\"\n    local uuid=${BASH_REMATCH[1]};\n    local mountCmd=\"\"\n    log \"adding fstab entry\"\n    mountCmd=\"/dev/disk/by-uuid/$uuid $mount xfs  defaults,nofail  0  2\"\n    echo \"$mountCmd\" >> /etc/fstab\n    $(mount $partPath $mount)\n\n  else\n    log \"no UUID found\"\n    exit -1;\n  fi\n\n  log \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n      # http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n      $(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath) > /dev/null\n      local partPath=\"$devicePath\"\"1\"\n      $(mkfs -t xfs $partPath) > /dev/null\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab $partPath $mountPathLoc\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nexit\n", "num_lines": 201}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\n\n\nlog \"noop\"\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n\n  local blkid=$(/sbin/blkid $partPath)\n\n  if [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n  then\n\n    log \"Adding fstab entry\"\n    local uuid=${BASH_REMATCH[1]};\n    local mountCmd=\"\"\n    log \"adding fstab entry\"\n    mountCmd=\"/dev/disk/by-uuid/$uuid $mount xfs  defaults,nofail  0  2\"\n    echo \"$mountCmd\" >> /etc/fstab\n    $(mount $partPath $mount)\n\n  else\n    log \"no UUID found\"\n    exit -1;\n  fi\n\n  log \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n      # http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n      $(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath) > /dev/null\n      local partPath=\"$devicePath\"\"1\"\n      $(mkfs -t xfs $partPath) > /dev/null\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab $partPath $mountPathLoc\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nexit\n", "num_lines": 201}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\n\n\nlog \"noop\"\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# create-mdadm <lun array> <mdadm path e.g. /dev/md127> <mount path e.g. /dbdata>\n# TODO: SWAP file\n# TODO: run /usr/sbin/SAPconf\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n\tlog \"addtofstab\"\n\tpartPath=$1\n\tlocal blkid=$(/sbin/blkid $partPath)\n\tif [[ $blkid =~  UUID=\\\"(.{36})\\\" ]]\n\tthen\n\t\tlog \"Adding fstab entry\"\n\t\tlocal uuid=${BASH_REMATCH[1]};\n\t\tlocal mountCmd=\"\"\n\t\tlog \"adding fstab entry\"\n\t\tmountCmd=\"/dev/disk/by-uuid/$uuid $mountPath xfs  defaults,nofail  0  2\"\n\t\techo \"$mountCmd\" >> /etc/fstab\n\t\t$(mount $mountPath)\n\telse\n\t\tlog \"no UUID found\"\n\t\texit -1;\n\tfi\n\tlog \"addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\tlog \"getdevicepath\"\n\tgetdevicepathresult=\"\"\n\tlocal lun=$1\n\tlocal scsiOutput=$(lsscsi)\n\tif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n\tthen\n\t\tgetdevicepathresult=${BASH_REMATCH[1]};\n\telse\n\t\tlog \"lsscsi output not as expected for $lun\"\n\t\texit -1;\n\tfi\n\tlog \"getdevicepath done\"\n}\n\nfunction createlvm()\n{\n\tlog \"createlvm\"\n\n\tlunsA=(${1//,/ })\n\tvgName=$2\n\tlvName=$3\n\tmountPath=$4\n\n\tarraynum=${#lunsA[@]}\n\techo \"count $arraynum\"\n\tif [[ $arraynum -gt 1 ]]\n\tthen\n\t\tlog \"createlvm - creating lvm\"\n\n\t\tnumRaidDevices=0\n\t\traidDevices=\"\"\n\t\tnum=${#lunsA[@]}\n\t\tlog \"num luns $num\"\n\t\tfor ((i=0; i<num; i++))\n\t\tdo\n\t\t\tlog \"trying to find device path\"\n\t\t\tlun=${lunsA[$i]}\n\t\t\tgetdevicepath $lun\n\t\t\tdevicePath=$getdevicepathresult;\n\t\t\tif [ -n \"$devicePath\" ];\n\t\t\tthen\n\t\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t\tnumRaidDevices=$((numRaidDevices + 1))\n\t\t\t\traidDevices=\"$raidDevices $devicePath \"\n\t\t\telse\n\t\t\t\tlog \"no device path for LUN $lun\"\n\t\t\t\texit -1;\n\t\t\tfi\n\t\tdone\n\t\tlog \"num: $numRaidDevices paths: '$raidDevices'\"\n\t\t$(pvcreate $raidDevices)\n\t\t$(vgcreate $vgName $raidDevices)\n\t\t$(lvcreate --extents 100%FREE --stripes $numRaidDevices --name $lvName $vgName)\n\t\t$(mkfs -t xfs /dev/$vgName/$lvName)\n\n\t\t$(mkdir $mountPath)\n\t\taddtofstab /dev/$vgName/$lvName\n\telse\n\t\tlog \"createlvm - creating single disk\"\n\n\t\tlun=${lunsA[0]}\n\t\tgetdevicepath $lun;\n\t\tdevicePath=$getdevicepathresult;\n\t\tif [ -n \"$devicePath\" ];\n\t\tthen\n\t\t\tlog \" Device Path is $devicePath\"\n\t\t\t# http://superuser.com/questions/332252/creating-and-formating-a-partition-using-a-bash-script\n\t\t\t$(echo -e \"n\\np\\n1\\n\\n\\nw\" | fdisk $devicePath)\n\t\t\tpartPath=\"$devicePath\"\"1\"\n\t\t\t$(mkfs -t xfs $partPath)\n\t\t\t$(mkdir $mountPath)\n\n\t\t\taddtofstab $partPath\n\t\telse\n\t\t\tlog \"no device path for LUN $lun\"\n\t\t\texit -1;\n\t\tfi\n\tfi\n\n\tlog \"createlvm done\"\n\n}\n\ndbluns=\"\"\ndbname=\"dbdata\"\nlogluns=\"\"\nlogname=\"dblog\"\n\nwhile true; do\n\tcase \"$1\" in\n    \"-DBLogLUNS\")  logluns=$2;shift 2;\n        ;;\n    \"-DBDataLUNS\")  dbluns=$2;shift 2;\n\t        ;;\n\t\"-DBDataName\")  dbname=$2;shift 2;\n        ;;\n\t\"-DBLogName\")  logname=$2;shift 2;\n        ;;\n    esac\n\tif [[ -z \"$1\" ]]; then break; fi\ndone\n\nvLinux=$(cat /etc/os-release)\nif [[ $vLinux =~ NAME=\\\"Oracle ]];\nthen\n    yum -y install lsscsi lvm2\nfi\n\nif [[ -n \"$dbluns\" ]];\nthen\n\tcreatelvm $dbluns \"vg-$dbname\" \"lv-$dbname\" \"/$dbname\";\nfi\n\nif [[ -n \"$logluns\" ]];\nthen\n\tcreatelvm $logluns \"vg-$logname\" \"lv-$logname\" \"/$logname\";\nfi\n", "num_lines": 153}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n\tmessage=$1\n\techo \"$message\"\n\techo \"$message\" >> /var/log/sapconfigcreate\n}\n\n\n\nlog \"noop\"\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n  log \" not adding fstab entry\"\n  log \" manual mount with 'mount $partPath $mount'\"\n  $(mount $partPath $mount)\n\n  log \" addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n\n      local partedOut=$(parted $devicePath print -s | grep 'Partition Table' | awk '{print $3}')\n      if [ \"$partedOut\" = \"unknown\" ];\n      then\n        log \"   no partition table found - creating gpt\"\n        parted $devicePath mklabel gpt -s\n      else\n        log \"  disk $devicePath already has a partition table - stopping to prevent data loss\"\n        exit -1\n      fi\n\n      local startPercent=0\n\n      for ((j=0; j<mountPathCount; j++))\n      do\n        local mountPathLoc=${mountPathA[$j]}\n        local sizeLoc=${sizeA[$j]}\n        local partNumber=$(expr $j + 1)\n        local endPercent=$( echo \"((100 - $startPercent) * $sizeLoc / 100) + $startPercent\" | bc)\n        if [ \"$sizeLoc\" = \"100\" ];\n        then\n          local endPercent=100\n        fi\n\n        log \"  Creating partition $partNumber for $mountPathLoc with size info $fdiskSize start $startPercent% end $endPercent%\"\n        parted $devicePath mkpart primary xfs $startPercent% $endPercent% -s\n\n        log \"  partition created - rereading partition table\"\n        partprobe $devicePath\n        udevadm settle\n\n        local partPath=\"$devicePath\"\"$partNumber\"\n        log \"  creating file system\"\n        mkfs.xfs $partPath -f\n        mkdir -p $mountPathLoc\n\n        addtofstab $partPath $mountPathLoc\n\n        startPercent=$endPercent\n      done\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nexit\n", "num_lines": 219}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n  log \" not adding fstab entry\"\n  log \" manual mount with 'mount $partPath $mount'\"\n  $(mount $partPath $mount)\n\n  log \" addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n\n      local partedOut=$(parted $devicePath print -s | grep 'Partition Table' | awk '{print $3}')\n      if [ \"$partedOut\" = \"unknown\" ];\n      then\n        log \"   no partition table found - creating gpt\"\n        parted $devicePath mklabel gpt -s\n      else\n        log \"  disk $devicePath already has a partition table - stopping to prevent data loss\"\n        exit -1\n      fi\n\n      local startPercent=0\n\n      for ((j=0; j<mountPathCount; j++))\n      do\n        local mountPathLoc=${mountPathA[$j]}\n        local sizeLoc=${sizeA[$j]}\n        local partNumber=$(expr $j + 1)\n        local endPercent=$( echo \"((100 - $startPercent) * $sizeLoc / 100) + $startPercent\" | bc)\n        if [ \"$sizeLoc\" = \"100\" ];\n        then\n          local endPercent=100\n        fi\n\n        log \"  Creating partition $partNumber for $mountPathLoc with size info $fdiskSize start $startPercent% end $endPercent%\"\n        parted $devicePath mkpart primary xfs $startPercent% $endPercent% -s\n\n        log \"  partition created - rereading partition table\"\n        partprobe $devicePath\n        udevadm settle\n\n        local partPath=\"$devicePath\"\"$partNumber\"\n        log \"  creating file system\"\n        mkfs.xfs $partPath -f\n        mkdir -p $mountPathLoc\n\n        addtofstab $partPath $mountPathLoc\n\n        startPercent=$endPercent\n      done\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nosVersion=$(cat /etc/os-release)\nif [[ $osVersion =~ SUSE ]]\nthen\n  systemctl restart nfsserver\n  systemctl enable nfsserver\nfi\n\nexit\n", "num_lines": 226}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nfunction log()\n{\n  message=$@\n  echo \"$message\"\n  echo \"$message\" >> /var/log/sapconfigcreate\n}\n\nfunction addtofstab()\n{\n  log \"addtofstab\"\n  partPath=$1\n  mount=$2\n  log \" not adding fstab entry\"\n  log \" manual mount with 'mount $partPath $mount'\"\n  $(mount $partPath $mount)\n\n  log \" addtofstab done\"\n}\n\nfunction getdevicepath()\n{\n\n  log \"getdevicepath\"\n  getdevicepathresult=\"\"\n  local lun=$1\n  local readlinkOutput=$(readlink /dev/disk/azure/scsi1/lun$lun)\n  local scsiOutput=$(lsscsi)\n  if [[ $readlinkOutput =~ (sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using readlink\"\n    getdevicepathresult=\"/dev/${BASH_REMATCH[1]}\";\n  elif [[ $scsiOutput =~ \\[5:0:0:$lun\\][^\\[]*(/dev/sd[a-zA-Z]{1,2}) ]];\n  then\n    log \"found device path using lsscsi\"\n    getdevicepathresult=${BASH_REMATCH[1]};\n  else\n    log \"lsscsi output not as expected for $lun\"\n    exit -1;\n  fi\n  log \"getdevicepath done\"\n\n}\n\nfunction createlvm()\n{\n\n  log \"createlvm\"\n\n  local lunsA=(${1//,/ })\n  local vgName=$2\n  local lvName=$3\n  local mountPathA=(${4//,/ })\n  local sizeA=(${5//,/ })\n\n  local lunsCount=${#lunsA[@]}\n  local mountPathCount=${#mountPathA[@]}\n  local sizeCount=${#sizeA[@]}\n  log \"count $lunsCount $mountPathCount $sizeCount\"\n  if [[ $lunsCount -gt 1 ]]\n  then\n    log \"createlvm - creating lvm\"\n\n    local numRaidDevices=0\n    local raidDevices=\"\"\n    log \"num luns $lunsCount\"\n\n    for ((i=0; i<lunsCount; i++))\n    do\n      log \"trying to find device path\"\n      local lun=${lunsA[$i]}\n      getdevicepath $lun\n      local devicePath=$getdevicepathresult;\n\n      if [ -n \"$devicePath\" ];\n      then\n        log \" Device Path is $devicePath\"\n        numRaidDevices=$((numRaidDevices + 1))\n        raidDevices=\"$raidDevices $devicePath \"\n      else\n        log \"no device path for LUN $lun\"\n        exit -1;\n      fi\n    done\n\n    log \"num: $numRaidDevices paths: '$raidDevices'\"\n    $(pvcreate $raidDevices)\n    $(vgcreate $vgName $raidDevices)\n\n    for ((j=0; j<mountPathCount; j++))\n    do\n      local mountPathLoc=${mountPathA[$j]}\n      local sizeLoc=${sizeA[$j]}\n      local lvNameLoc=\"$lvName-$j\"\n      $(lvcreate --extents $sizeLoc%FREE --stripes $numRaidDevices --name $lvNameLoc $vgName)\n      $(mkfs -t xfs /dev/$vgName/$lvNameLoc)\n      $(mkdir -p $mountPathLoc)\n\n      addtofstab /dev/$vgName/$lvNameLoc $mountPathLoc\n    done\n\n  else\n    log \"createlvm - creating single disk\"\n\n    local lun=${lunsA[0]}\n    local mountPathLoc=${mountPathA[0]}\n    getdevicepath $lun;\n    local devicePath=$getdevicepathresult;\n    if [ -n \"$devicePath\" ];\n    then\n      log \" Device Path is $devicePath\"\n\n      local partedOut=$(parted $devicePath print -s | grep 'Partition Table' | awk '{print $3}')\n      if [ \"$partedOut\" = \"unknown\" ];\n      then\n        log \"   no partition table found - creating gpt\"\n        parted $devicePath mklabel gpt -s\n      else\n        log \"  disk $devicePath already has a partition table - stopping to prevent data loss\"\n        exit -1\n      fi\n\n      local startPercent=0\n\n      for ((j=0; j<mountPathCount; j++))\n      do\n        local mountPathLoc=${mountPathA[$j]}\n        local sizeLoc=${sizeA[$j]}\n        local partNumber=$(expr $j + 1)\n        local endPercent=$( echo \"((100 - $startPercent) * $sizeLoc / 100) + $startPercent\" | bc)\n        if [ \"$sizeLoc\" = \"100\" ];\n        then\n          local endPercent=100\n        fi\n\n        log \"  Creating partition $partNumber for $mountPathLoc with size info $fdiskSize start $startPercent% end $endPercent%\"\n        parted $devicePath mkpart primary xfs $startPercent% $endPercent% -s\n\n        log \"  partition created - rereading partition table\"\n        partprobe $devicePath\n        udevadm settle\n\n        local partPath=\"$devicePath\"\"$partNumber\"\n        log \"  creating file system\"\n        mkfs.xfs $partPath -f\n        mkdir -p $mountPathLoc\n\n        addtofstab $partPath $mountPathLoc\n\n        startPercent=$endPercent\n      done\n    else\n      log \"no device path for LUN $lun\"\n      exit -1;\n    fi\n  fi\n\n  log \"createlvm done\"\n}\n\nlog $@\n\nluns=\"\"\nnames=\"\"\npaths=\"\"\nsizes=\"\"\n\nwhile true;\ndo\n  case \"$1\" in\n    \"-luns\")  luns=$2;shift 2;log \"found luns\"\n    ;;\n    \"-names\")  names=$2;shift 2;log \"found names\"\n    ;;\n    \"-paths\")  paths=$2;shift 2;log \"found paths\"\n    ;;\n    \"-sizes\")  sizes=$2;shift 2;log \"found sizes\"\n    ;;\n    *) log \"unknown parameter $1\";shift 1;\n    ;;\n  esac\n\n  if [[ -z \"$1\" ]];\n  then\n    break;\n  fi\ndone\n\nlunsSplit=(${luns//#/ })\nnamesSplit=(${names//#/ })\npathsSplit=(${paths//#/ })\nsizesSplit=(${sizes//#/ })\n\nlunsCount=${#lunsSplit[@]}\nnamesCount=${#namesSplit[@]}\npathsCount=${#pathsSplit[@]}\nsizesCount=${#sizesSplit[@]}\n\nlog \"count $lunsCount $namesCount $pathsCount $sizesCount\"\n\nif [[ $lunsCount -eq $namesCount && $namesCount -eq $pathsCount && $pathsCount -eq $sizesCount ]]\nthen\n  for ((ipart=0; ipart<lunsCount; ipart++))\n  do\n    lun=${lunsSplit[$ipart]}\n    name=${namesSplit[$ipart]}\n    path=${pathsSplit[$ipart]}\n    size=${sizesSplit[$ipart]}\n\n    log \"creating disk with $lun $name $path $size\"\n    createlvm $lun \"vg-$name\" \"lv-$name\" \"$path\" \"$size\";\n  done\nelse\n  log \"count not equal\"\nfi\n\nexit\n", "num_lines": 219}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 1 - Ansible Startup Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n##Error handling functions\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\nfail_if_error_phrase() {\n  [ $1 != 0 ] && {\n    unset PASSPHRASE\n    exit 10\n  }\n}\n\n## Facter Installation For Dynamic Values\nyum install ruby wget -y\nwget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm\nrpm  --reinstall -vh facter-2.*.rpm\nfail_if_error $? \"Facter Installation failed\"\n\n#Facter Variables and Declaration\nenvironmentLocation=\"/etc/facter/facts.d/variables.txt\"\n\nif [ -f $environmentLocation ]; then\n\trm -f $environmentLocation\nfi\n\ncat << EOF > $environmentLocation\nazure_storage_account=$1\nazure_storage_files_share=$2\nviyarepo_folder=$3\napp_name=$4\ndomain_name=$5\nansible_vmname=$6\nmicroservices_vmname=$7\ncascontroller_vmname=$8\nspre_vmname=${9}\ncasworker_vmname=${10}\nsaspwd=${11}\ncaspwd=${12}\nkv_vault_name=${13}\nsecret_pvt_keyname=${14}\nsecret_pub_keyname=${15}\ncas_nodes=${16}\nmid_name=${17}\nartifact_loc=${18}\ncompute_name=${19}\nmeta_name=${20}\nstgacc_secr_name=${21}\ncifs_server_fqdn=${22}\nEOF\n\n#Defining variables with facter values\nazure_storage_account=`facter azure_storage_account`\ncifs_server_fqdn=`facter cifs_server_fqdn`\nazure_storage_files_share=`facter azure_storage_files_share`\nDIRECTORY_NFS_SHARE=\"sasdepot\"\nsas_home=\"/sas/install\"\nkey_vault_name=`facter kv_vault_name`\nsecret_pvt_keyname=`facter secret_pvt_keyname`\nsecret_pub_keyname=`facter secret_pub_keyname`\nRootCAKey=\"RootCA.key\"\nRootCRT=\"RootCA.crt\"\nServerKey=\"sasqs.key\"\nServerCRT=\"sasqs.crt\"\nServerCSR=\"sasqs.csr\"\nssl_path=\"/opt/ssl\"\ncert_name=\"`facter app_name`sas94\"\n\n\n\n##Updating the Azure Cli Repo\nrpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n##Installing the azure CLI\nyum install azure-cli -y\nfail_if_error $? \"Azure Cli Installation failed\"\n\n##Ansible Installation\nif ! type -p ansible;  then\n    # install Ansible\n    curl --retry 10 --max-time 60 --fail --silent --show-error \"https://bootstrap.pypa.io/get-pip.py\" -o \"get-pip.py\"\n    python get-pip.py\n    pip install 'ansible==2.8.3'\n\tfail_if_error $? \"Pip Installation failed\"\nfi\n\n##Stop & Disable the firewalld(Iptables)\nsystemctl stop firewalld\nsystemctl disable firewalld\n\n##Installing RedHat required packages\nyum -y install java-1.8.0-openjdk yum-utils firefox xclock x11* xauth git python compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet\nfail_if_error $? \"Error: Rhel packages install Failed\"\n\n##Volume Mount for opt-sas\nif [ ! -d \"$sas_home\" ]; then\n    sudo mkdir -p $sas_home\nfi\nlsblk /dev/disk/azure/scsi1/lun0\nif [ $? -eq 0 ]; then \n    df -h | grep $sas_home\n\tif [ $? -eq 0 ]; then\n\t\techo \"Disk for $sas_home already mounted.\"\n    else\n        mkfs.xfs /dev/disk/azure/scsi1/lun0\n\t\tmount /dev/disk/azure/scsi1/lun0 $sas_home\n\t\tfail_if_error $? \"Error:Failed to mount $sas_home\"\n\t\t## Adding Fstab Entries\n\t\techo \"/dev/disk/azure/scsi1/lun0   $sas_home   xfs       defaults        0 0\"  >> /etc/fstab\n        echo \"Disk for $sas_home located and mounted.\"\n    fi\nelse\n    echo \"ERROR: $sas_home disk(lun0) disk failed to mount or disk not available.\"\n    exit 1\nfi\n\n#Setting up hostname for Ansible Controller\nansible_host=`facter app_name``facter ansible_vmname`.`facter domain_name`\nhostnamectl set-hostname --static ${ansible_host}\nif [ $? -eq 0 ]; then\n    echo \"hostname update successful\"\n    if [ -f /etc/hostname ]; then\n        chattr -i /etc/hostname\n        rm -f /etc/hostname\n        echo ${ansible_host} > /etc/hostname\n        chattr +i /etc/hostname\n    fi\n    if [ -f /etc/sysconfig/network ]; then\n        echo \"HOSTNAME=${ansible_host}\" >> /etc/sysconfig/network\n    fi\n    echo \"Restart Network Service\"\n    /etc/init.d/network restart\nelse\n    echo \"Hostname Update failed\"\nfi\naz login --identity\nfail_if_error $? \"Error: Az login Failed\"\nstgacc_secr_name=`facter stgacc_secr_name`\nazure_storage_files_password=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\n#Mounting File Share for SAS Viya Installation\necho \"setup cifs\"\nif [ ! -d \"/etc/smbcredentials\" ]; then\n    sudo mkdir /etc/smbcredentials\nfi\nchmod 700 /etc/smbcredentials\nif [ ! -f \"/etc/smbcredentials/\"${azure_storage_account}\".cred\" ]; then\n    echo \"username=${azure_storage_account}\" >> /etc/smbcredentials/${azure_storage_account}.cred\n    echo \"password=${azure_storage_files_password}\" >> /etc/smbcredentials/${azure_storage_account}.cred\nfi\nchmod 600 \"/etc/smbcredentials/${azure_storage_account}.cred\"\n\nmkdir -p \"/${DIRECTORY_NFS_SHARE}\"\nmount -t cifs //${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  -o vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,serverino\nfail_if_error $? \"Error: SAS Depot Mount Failed\"\n\n#Passworless SSH Authentication and SSL Certificate Generation\nexport RANDFILE=$ssl_path/.rnd\necho \"server_cn=`facter app_name``facter mid_name`.`facter domain_name`\" > /etc/facter/facts.d/server_cn.txt\necho -e y | ssh-keygen -t rsa -q -f ~/.ssh/id_rsa -N \"\"\nfail_if_error $? \"ERROR: Key generation failed.\"\n\n## Uploading the keys to key vault\naz keyvault secret set -n ${secret_pub_keyname} --value \"`cat ~/.ssh/id_rsa.pub`\" --vault-name ${key_vault_name}\nfail_if_error $? \"ERROR:Key Vault, Public Key Upload Failed.\"\n\n\naz keyvault secret set -n ${secret_pvt_keyname} --value \"`cat ~/.ssh/id_rsa`\" --vault-name ${key_vault_name}\nfail_if_error $? \"ERROR: Key Vault, Private Key Upload Failed.\"\n\n##self-signed SSL Certificates\nif [ ! -d \"$ssl_path\" ]; then\n    sudo mkdir -p $ssl_path\nfi\n# Generate a passphrase\nexport PASSPHRASE=$(head -c 500 /dev/urandom | tr -dc a-z0-9A-Z | head -c 16; echo)\n# Certificate details; replace items in angle brackets with your own info\nsubj=\"\nC=UK\nST=Lon\nO=IT\nlocalityName=Marlow\ncommonName=RootCA\norganizationalUnitName=QS\n\"\n##CA\ncat > $ssl_path/CA.cfg << EOF\n[ v3_ca ]\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always,issuer\nbasicConstraints = CA:true,pathlen:3\nEOF\n\n# Generate the server root key\nopenssl genrsa -des3 -passout env:PASSPHRASE -out $ssl_path/$RootCAKey 2048\nfail_if_error_phrase $?\n\n# Generate the CSR\nopenssl req \\\n    -new \\\n    -subj \"$(echo -n \"$subj\" | tr \"\\n\" \"/\")\" \\\n    -key $ssl_path/$RootCAKey \\\n    -out $ssl_path/RootCA.csr \\\n    -passin env:PASSPHRASE\nfail_if_error_phrase $?\ncp $ssl_path/$RootCAKey $ssl_path/${RootCAKey}.org\nfail_if_error_phrase $?\n# Strip the password so we don't have to type it every time we restart Apache\nopenssl rsa -in $ssl_path/${RootCAKey}.org -out $ssl_path/${RootCAKey} -passin env:PASSPHRASE\nfail_if_error_phrase $?\n# Generate the cert (good for 10 years)\nopenssl x509 -req -days 3650 -in $ssl_path/RootCA.csr -extfile $ssl_path/CA.cfg -extensions v3_ca -signkey $ssl_path/$RootCAKey -out $ssl_path/$RootCRT\nfail_if_error_phrase $?\n\nserver_cn=`facter server_cn`\n# Generate the server sas key\nopenssl genrsa -des3 -passout env:PASSPHRASE -out $ssl_path/$ServerKey 2048\nfail_if_error_phrase $?\n# Certificate details; replace items in angle brackets with your own info\nserversubj=\"\nC=UK\nST=Lon\nO=IT\nlocalityName=Marlow\ncommonName=$server_cn\norganizationalUnitName=QS\n\"\n\n# Generate the server private key\nopenssl genrsa -des3 -out $ssl_path/$ServerKey -passout env:PASSPHRASE 2048\nfail_if_error_phrase $?\n# Generate the Server CSR\nopenssl req \\\n    -new \\\n    -batch \\\n    -subj \"$(echo -n \"$serversubj\" | tr \"\\n\" \"/\")\" \\\n    -key $ssl_path/$ServerKey \\\n    -out $ssl_path/$ServerCSR \\\n    -passin env:PASSPHRASE\nfail_if_error_phrase $?\ncp $ssl_path/$ServerKey $ssl_path/${ServerKey}.org\nfail_if_error_phrase $?\n# Strip the password so we don't have to type it every time we restart Apache\nopenssl rsa -in $ssl_path/${ServerKey}.org -out $ssl_path/$ServerKey -passin env:PASSPHRASE\nfail_if_error_phrase $?\n\n# Generate the cert (good for 10 years)\nopenssl x509 -req -days 3650 -in $ssl_path/$ServerCSR -CA $ssl_path/RootCA.crt -CAkey $ssl_path/RootCA.key -set_serial 1 -out $ssl_path/$ServerCRT\nfail_if_error_phrase $?\n# Bundle\ncat $ssl_path/$ServerCRT $ssl_path/RootCA.crt > $ssl_path/${cert_name}bundle.crt\nfail_if_error_phrase $?\n\n## Creating pfx file\nopenssl pkcs12 -export -out ${ssl_path}/${server_cn}.pfx -inkey ${ssl_path}/$ServerKey -in ${ssl_path}/${cert_name}bundle.crt -passout pass:\nfail_if_error_phrase $?\n\n# Uploading Self Signed certificate to Key Vault\naz keyvault certificate import --file $ssl_path/${server_cn}.pfx --name $cert_name --vault-name $key_vault_name\n\necho \"*** Phase 1 Completed - Ansible Startup Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 266}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 2 -  Ansible SAS 94 SSL Certs Copy `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n# Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n# Variables\nmeta_host_name=`facter app_name``facter meta_name`\nmid_host_name=`facter app_name``facter mid_name`\ncompute_host_name=`facter app_name``facter compute_name`\n\n# SSL Certificates & encryption keys copy\nscp -o StrictHostKeyChecking=no /opt/ssl/*.key ${meta_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${meta_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${meta_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no ${meta_host_name}:/root/enc* .\nfail_if_error $? \"Error: Passwordless SSH for Meta Failed\"\n\nscp -o StrictHostKeyChecking=no /opt/ssl/*.key ${compute_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${compute_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no enc* ${compute_host_name}:/root/\nfail_if_error $? \"Error: Passwordless SSH for Compute Failed\"\n\nscp -o StrictHostKeyChecking=no /opt/ssl/*.crt ${mid_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no /opt/ssl/*.key ${mid_host_name}:/home/sasinst/\nscp -o StrictHostKeyChecking=no enc* ${mid_host_name}:/root/\nfail_if_error $? \"Error: Passwordless SSH for Mid Failed\"\n\n# Deleting Unwanted resources\nrm -rf /opt/ssl/*.key\nrm -rf /opt/ssl/*.crt\nrm -rf /root/enc*\n\necho \"*** Completed Phase 2 -  Ansible SAS 94 SSL Certs Copy `date +'%Y-%m-%d_%H-%M-%S'` ***\"", "num_lines": 40}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 3 - SAS Compute Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n##Error handling function\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Local Variables\napp_name=`facter application_name`\nartifact_loc=`facter artifact_loc`\ndepot_loc=`facter sasdepot_folder`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\nconf_prop=${resource_dir}/compute_config.properties\ncert_prop=${resource_dir}/ssl_cert.properties\n\n##Replace crt in certupdatemid.properties\ncp -p ${res_dir}/ssl_cert.properties ${resource_dir}\nsed -i \"s|certname|${app_name}|g\" ${resource_dir}/ssl_cert.properties\n\n## Password Update\nencsasextpw=$(</root/encext.txt)\nsed -i \"s/changeextpass/${encsasextpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated successfully.\"\nencsasintpw=$(</root/encint.txt)\nsed -i \"s/changeintpass/${encsasintpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated succesfully.\"\nrm -f /root/enc*.txt\n\n\n#Add certificate to trustedstore\nsu - sasinst -c \"time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\nfail_if_error $? \"ERROR: SAS certificate update failed. Please check logs\"\n\n##SAS Configuration\nif [ -f ${conf_prop} ]; then\n    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then\n        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        if [ $? -eq 0 ]; then\n            echo \"SAS Compute Server Configuration has been completed succesfully.\"\n            sed -i \"s|-WORK /tmp|-WORK /saswork|g\" /opt/sas/home/SASFoundation/9.4/sasv9.cfg\n            su - sasinst -c \"/opt/sas/config/Lev1/ObjectSpawner/ObjectSpawner.sh stop > /var/logs/ObjectSpawnerstop.txt\"\n            sleep 10\n            su - sasinst -c \"/opt/sas/config/Lev1/ObjectSpawner/ObjectSpawner.sh start > /var/logs/ObjectSpawnerstart.txt\"\n        else\n            fail_if_error 1 \"ERROR: SAS Compute Server Configuration has failed. Please check logs\"\n            \n        fi\n    else\n        telnet -apln |grep 8581\n        if [ $? -eq 0 ]; then\n            echo \"SAS Compute Server is Up. Proceeding to Next Phase.\"\n        else \n            echo \"SAS Compute Server has been configured. Starting Services now.\"\n            su - sasinst -c \"/opt/sas/config/Lev1/sas.servers start\"\n            echo \"SAS Compute Services have been started.\"\n        fi\n    fi\nelse\n    fail_if_error 1 \"ERROR: SAS Config Properties file not found. Exiting Now.\"\n    \nfi\necho \"*** Phase 3 - SAS Compute Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"", "num_lines": 69}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 2 - SAS Compute Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Global Variables\ndepot_loc=`facter sasdepot_folder`\nstore_name=`facter storage_account_name`\nstore_loc=`facter file_share_name`   \nkey_vault_name=`facter key_vault_name`\nstgacc_secr_name=`facter stgacc_secr_name`\napp_name=`facter application_name`\nsas_role=`facter sas_role`\ndomain_name=`facter domain_name` \ndepot_loc=`facter sasdepot_folder` \nsas_sid=`facter sas_sid`\nartifact_loc=`facter artifact_loc`\nmeta_host=`facter meta_hostname`\ncompute_host=`facter compute_hostname`\nmid_host=`facter mid_hostname`\nsasint_secret_name=`facter sasint_secret_name`\nsasext_secret_name=`facter sasext_secret_name`\npub_keyname=`facter pub_keyname`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\ncifs_server_fqdn=`facter cifs_server_fqdn`\ninst_prop=$resource_dir/compute_install.properties\nconf_prop=$resource_dir/compute_config.properties\n\n# Getting the password\naz login --identity\nfail_if_error $? \"Error: AZ login failed\"\nsasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nsasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nstore_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`   \necho `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '\"' -f4` >> ~/.ssh/authorized_keys\nfail_if_error $? \"Error: Key Vault Access failed\"\n\n#Creating SAS group\ncat /etc/group |grep -w sas\nif [ $? -eq 0 ]; then\n    echo \"SAS Group exists\"\nelse\n    groupadd -g 5001 sas\n    fail_if_error $? \"Error: failed to create sas group\"\nfi\n\n##Creating SAS internal Users\nusername=(\"sasinst\" \"sassrv\" \"sasdemo\")\nuserid=(\"1002\" \"1003\" \"1005\")\nfor ((i=0;i<${#username[@]};++i));\ndo\n    if [ ! -f /home/${username[$i]} ]; then\n        useradd -u ${userid[$i]} -g sas ${username[$i]}\n        fail_if_error $? \"ERROR: failed to create ${username[$i]} User\"\n        echo ${sasextpw} | passwd ${username[$i]} --stdin\n    else \n        echo \"User ${username[$i]} exists\"\n    fi\ndone\n\n##Set permissions for opt-sas and sasdepot directories\nif [ ! -d /opt/sas/home ]; then \n    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config\nfi\nchmod 775 /opt/sas -R\nchown -R sasinst:sas /opt/sas\nchown -R sasinst:sas /sasdata\necho \"Permissions for opt-sas and sasdepot have been set.\"\n\n##Mount Azure File Share for SASDepot\ndf -h | grep -w /sasdepot\nif [ $? -eq 0 ]; then\n    echo \"SASDepot already mounted.\"\nelse\n    if [ ! -d \"/etc/smbcredentials\" ]; then\n        sudo mkdir /etc/smbcredentials\n    fi\n    if [ ! -f \"/etc/smbcredentials/store.cred\" ]; then\n        echo \"username=${store_name}\" >> /etc/smbcredentials/store.cred\n        echo \"password=${store_key}\" >> /etc/smbcredentials/store.cred\n    fi\n    sudo chmod 600 /etc/smbcredentials/store.cred\n    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino\n    fail_if_error $? \"ERROR: Failed to mount Azure file Share\"\nfi\n\nlsblk |grep -w /saswork\nif [ $? -eq 0 ]; then\n    chmod 775 /saswork\n    chown sasinst:sas /saswork\n    echo \"SASWork has been located and mounted on /mnt/resource successfully.\"\nelse\n    echo \"ERROR: Failed to mount SASWork volume from Instance Store.\"\nfi\n\n#copyign SID file to local directories from SASDepot\ncp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/\nif [ ! -d $res_dir ]; then\n    mkdir -p $res_dir\nfi\n\n#Downloading the plan file and property files required for SAS install\ntar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}\ncp -p ${res_dir}/plan.xml ${resource_dir}\ncp -p ${res_dir}/compute_* ${resource_dir}\nchown -R sasinst:sas ${resource_dir}\n\n#Altering the property files\nsed -i \"s/domain_name/${domain_name}/g\" $resource_dir/*.properties\nsed -i \"s/host_name/${compute_host}/g\" $resource_dir/*.properties\nsed -i \"s/meta_host/${meta_host}/g\" $resource_dir/*.properties\nsed -i \"s/mid_host/${mid_host}/g\" $resource_dir/*.properties\nsed -i \"s|sas_plan_file_path|/opt/sas/resources/plan.xml|g\" $resource_dir/*.properties\nsed -i \"s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g\" $resource_dir/*.properties\n\n#SAS Installation\nif [ -d /opt/sas/temp ]; then \n    chown sasinst /opt/sas/temp\nelse\n    mkdir -p /opt/sas/temp\n    chown sasinst /opt/sas/temp\nfi\n\nif [ -f ${inst_prop} ]; then\n    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        if [ $? -eq 0 ]; then\n            echo \"SAS Compute Server installation has been completed succesfully.\"\n            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n            echo \"Setuid script has been run successfully.\"\n        else\n            echo \"ERROR: SAS Compute Server installation has failed. Please check logs\"\n            exit 1\n        fi\n    else \n        echo \"SAS Installation Completed. Proceeding to Configuration stage.\"\n    fi\nelse\n    echo \"SAS Install Properties file not found. Exiting Now.\"\n    exit 1\nfi\n\necho \"*** Phase 2 - SAS Compute Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 152}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 3 SAS Meta Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Variables\napp_name=`facter application_name`\nartifact_loc=`facter artifact_loc`\ndepot_loc=`facter sasdepot_folder`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\ninst_prop=${resource_dir}/meta_install.properties\nconf_prop=${resource_dir}/meta_config.properties\ncert_prop=${resource_dir}/ssl_cert.properties\n\ncp -p ${res_dir}/ssl_cert.properties ${resource_dir}\n\n##Altering the certificate in property file\nsed -i \"s|certname|${app_name}|g\" ${resource_dir}/ssl_cert.properties\n#Add certificate to trustedstore\nsu - sasinst -c \"time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\nfail_if_error $? \"ERROR: SAS certificate update failed. Please check logs\"\n\n##SAS Meta Configuration\nif [ -f ${conf_prop} ]; then\n    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then\n        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        fail_if_error $? \"ERROR: SAS Metadata Server Configuration has failed. Please check logs\"\n    else\n        telnet -apln |grep 8561\n        if [ $? -eq 0 ]; then\n            echo \"SAS Metadata Server is Up. Proceeding to Next Phase.\"\n        else \n            echo \"SAS Metadata Server has been configured. Starting Services now.\"\n            su - sasinst -c \"/opt/sas/config/Lev1/sas.servers start\"\n            echo \"SAS Metadata Services have been started.\"\n        fi\n    fi\nelse\n    fail_if_error 1 \"ERROR: SAS Config Properties file not found. Exiting Now.\"\nfi\n\necho \"*** Phase 3 - SAS Meta Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"", "num_lines": 51}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 2 - SAS Meta Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Global Variables\ndepot_loc=`facter sasdepot_folder`\nstore_name=`facter storage_account_name`  \nstore_loc=`facter file_share_name`   \nkey_vault_name=`facter key_vault_name`\nstgacc_secr_name=`facter stgacc_secr_name`\napp_name=`facter application_name` \nsas_role=`facter sas_role` \ndomain_name=`facter domain_name` \ndepot_loc=`facter sasdepot_folder`\nsas_sid=`facter sas_sid`\nartifact_loc=`facter artifact_loc`\nmeta_host=`facter meta_hostname`\nmid_host=`facter mid_hostname`\nsasint_secret_name=`facter sasint_secret_name`\nsasext_secret_name=`facter sasext_secret_name`\npub_keyname=`facter pub_keyname`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\ncifs_server_fqdn=`facter cifs_server_fqdn`\ninst_prop=${resource_dir}/meta_install.properties\nconf_prop=${resource_dir}/meta_config.properties\n\n\n# Getting the password\naz login --identity\nfail_if_error $? \"Error: AZ login failed\"\nsasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nsasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nstore_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4` \necho `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '\"' -f4` >> ~/.ssh/authorized_keys\nfail_if_error $? \"Error: Key vault access failed\"\n\n\n#Creating sas group\ncat /etc/group |grep -w sas\nif [ $? -eq 0 ]; then\n    echo \"SAS Group exists\"\nelse\n    groupadd -g 5001 sas\n    fail_if_error $? \"ERROR: Failed to create sas group\"\nfi\n\n##Creating SAS internal Users\nusername=(\"sasinst\" \"sassrv\" \"sasdemo\")\nuserid=(\"1002\" \"1003\" \"1005\")\nfor ((i=0;i<${#username[@]};++i));\ndo\n    if [ ! -f /home/${username[$i]} ]; then\n        useradd -u ${userid[$i]} -g sas ${username[$i]}\n        fail_if_error $? \"ERROR: failed to create ${username[$i]} User\"\n        echo ${sasextpw} | passwd ${username[$i]} --stdin\n    else \n        echo \"User ${username[$i]} exists\"\n    fi\ndone\n\n\n##Set permissions for opt-sas and sasdepot directories\nif [ ! -d /opt/sas/home ]; then\n    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config\n    fail_if_error $? \"ERROR: SAS Software directories creation failed\"\nfi\nchmod 775 /opt/sas -R\nchown -R sasinst:sas /opt/sas\nchown -R sasinst:sas /sasdata\necho \"Permissions for opt-sas and sasdepot have been set.\"\n\n##Mount Azure File Share for SASDepot\ndf -h | grep -w /sasdepot\nif [ $? -eq 0 ]; then\n    echo \"SASDepot already mounted.\"\nelse\n    if [ ! -d \"/etc/smbcredentials\" ]; then\n        sudo mkdir /etc/smbcredentials\n    fi\n    if [ ! -f \"/etc/smbcredentials/store.cred\" ]; then\n        echo \"username=${store_name}\" >> /etc/smbcredentials/store.cred\n        echo \"password=${store_key}\" >> /etc/smbcredentials/store.cred\n    fi\n    sudo chmod 600 /etc/smbcredentials/store.cred\n    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino\n    fail_if_error $? \"ERROR: Failed to mount Azure file share\"\nfi\n\n#copyign SID file to local directories from SASDepot\ncp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/\n#Downloading Meta Install Property files\nif [ ! -d $res_dir ]; then\n    mkdir -p $res_dir\nfi\n\n#Extracting the property files\ntar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}\ncp -p ${res_dir}/plan.xml ${resource_dir}\ncp -p ${res_dir}/meta_* ${resource_dir}\nchown -R sasinst:sas ${resource_dir}\n\n##Chaning the settings in property files\nsed -i \"s/domain_name/${domain_name}/g\" $resource_dir/*.properties\nsed -i \"s/host_name/${meta_host}/g\" $resource_dir/*.properties\nsed -i \"s/mid_host/${mid_host}/g\" $resource_dir/*.properties\nsed -i \"s|sas_plan_file_path|/opt/sas/resources/plan.xml|g\" $resource_dir/*.properties\nsed -i \"s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g\" $resource_dir/*.properties\n\n#SAS Installation\nif [ -d /opt/sas/temp ]; then\n    chown sasinst /opt/sas/temp\nelse\n    mkdir -p /opt/sas/temp\n    chown sasinst /opt/sas/temp\nfi\n\nif [ -f ${inst_prop} ]; then\n    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        if [ $? -eq 0 ]; then\n            echo \"SAS Metadata Server installation has been completed succesfully.\"\n            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n            echo \"Setuid script has b-een run successfully.\"\n        else\n            echo \"ERROR: SAS Metadata Server installation has failed. Please check logs\"\n            exit 1\n        fi\n    else\n        echo \"SAS Installation Completed. Proceeding to Configuration stage.\"\n    fi\nelse\n    echo \"SAS Install Properties file not found. Exiting Now.\"\n    exit 1\nfi\n\nsasextpw=`echo \"\\\"\"${sasextpw}\"\\\"\"`\nsasintpw=`echo \"\\\"\"${sasintpw}\"\\\"\"`\n##Encrypting sasextpw password\necho  \"filename pwfile '/root/encext.txt'; proc pwencode in=${sasextpw} out=pwfile; run;\" > /root/encext.sas\n/opt/sas/home/SASFoundation/9.4/bin/sas_u8 -sysin /root/encext.sas -log /root/sasencext.log\nfail_if_error $? \"ERROR: SAS External Password encryption failed.\"\nencsasextpw=$(</root/encext.txt)\nsed -i \"s/changeextpass/${encsasextpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated successfully.\"\n##Encrypting sasintpw password\necho  \"filename pwfile '/root/encint.txt'; proc pwencode in=${sasintpw} out=pwfile; run;\" > /root/encint.sas\n/opt/sas/home/SASFoundation/9.4/bin/sas_u8 -sysin /root/encint.sas -log /root/sasencint.log\nfail_if_error $? \"ERROR: SAS Internal Password encryption failed.\"\nencsasintpw=$(</root/encint.txt)\nsed -i \"s/changeintpass/${encsasintpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated succesfully.\"\n\necho \"*** Phase 2 - SAS Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 163}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 3 - SAS Mid-Tier Config Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Local Variables\napp_name=`facter application_name`\nartifact_loc=`facter artifact_loc`\ndepot_loc=`facter sasdepot_folder`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\nconf_prop=${resource_dir}/mid_config.properties\ncert_prop=${resource_dir}/ssl_cert.properties\n\n##Create VMWare Directories\nmkdir -p /etc/opt/vmware/vfabric/\nchown sasinst:sas /etc/opt/vmware -R\n\ncp -p ${res_dir}/ssl_cert.properties ${resource_dir}\n\n##changing the ssl setting in properties file\nsed -i \"s|certname|${app_name}|g\" ${resource_dir}/ssl_cert.properties\nsed -i \"s|certname|${app_name}|g\" ${resource_dir}/mid_config.properties\n\n## Password Update\nencsasextpw=$(</root/encext.txt)\nsed -i \"s/changeextpass/${encsasextpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated successfully.\"\nencsasintpw=$(</root/encint.txt)\nsed -i \"s/changeintpass/${encsasintpw}/g\" $resource_dir/*.properties\necho \"Encrypted password has been updated succesfully.\"\n\n#Add certificate to trustedstore\nsu - sasinst -c \"time /opt/sas/home/SASDeploymentManager/9.4/sasdm.sh -deploy -responsefile ${cert_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\nfail_if_error $? \"ERROR: SAS certificate update failed. Please check logs\"\n\n##SAS Configuration\nif [ -f ${conf_prop} ]; then\n    if [ ! -f /opt/sas/config/Lev1/sas.servers ]; then\n        sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${conf_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        fail_if_error $? \"ERROR: SAS Compute Server Configuration has failed. Please check logs\"\n    else\n        telnet -apln |grep 7980\n        if [ $? -eq 0 ]; then\n            echo \"SAS Mid-Tier Server is Up. Proceeding to Next Phase.\"\n        else \n            echo \"SAS Mid-Tier Server has been configured. Starting Services now.\"\n            su - sasinst -c \"/opt/sas/config/Lev1/sas.servers start\"\n            echo \"SAS Mid-Tier Services have been started.\"\n        fi\n    fi\nelse\n    echo \"SAS Config Properties file not found. Exiting Now.\"\n    exit 1\nfi\n\necho \"*** Phase 3 - SAS Mid-Tier Config Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"", "num_lines": 65}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 2 - SAS Mid-Tier Install Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Function for error handling\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Global Variables\ndepot_loc=`facter sasdepot_folder` \nstore_name=`facter storage_account_name`\nstore_loc=`facter file_share_name`   \napp_name=`facter application_name`  \nstgacc_secr_name=`facter stgacc_secr_name`\nsas_role=`facter sas_role`   \ndomain_name=`facter domain_name`  \ndepot_loc=`facter sasdepot_folder` \nsas_sid=`facter sas_sid` \nhost_name=\"${app_name}${sas_role}\"\nmeta_host=`facter meta_hostname`\ncompute_host=`facter compute_hostname`\nmid_host=`facter mid_hostname`\nsasint_secret_name=`facter sasint_secret_name`\nsasext_secret_name=`facter sasext_secret_name`\nkey_vault_name=`facter key_vault_name`\npub_keyname=`facter pub_keyname`\nartifact_loc=`facter artifact_loc`\nres_dir=\"/opt/sas/resources/responsefiles\"\nresource_dir=\"/opt/sas/resources\"\ncifs_server_fqdn=`facter cifs_server_fqdn`\ninst_prop=${resource_dir}/mid_install.properties\nconf_prop=${resource_dir}/mid_config.properties\n\n# Getting the password\naz login --identity\nfail_if_error $? \"ERROR: AZ Login Failed \"\nsasintpw=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nsasextpw=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\nstore_key=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`   \necho `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '\"' -f4` >> ~/.ssh/authorized_keys\n\n#SAS group creation\ncat /etc/group |grep -w sas\nif [ $? -eq 0 ]; then\n    echo \"SAS Group exists\"\nelse\n    groupadd -g 5001 sas\n    fail_if_error $? \"ERROR: SAS group creation failed\"\nfi\n\n##Creating SAS internal Users\nusername=(\"sasinst\" \"sassrv\" \"sasdemo\")\nuserid=(\"1002\" \"1003\" \"1005\")\nfor ((i=0;i<${#username[@]};++i));\ndo\n    if [ ! -f /home/${username[$i]} ]; then\n        useradd -u ${userid[$i]} -g sas ${username[$i]}\n        fail_if_error $? \"ERROR: failed to create ${username[$i]} User\"\n        echo ${sasextpw} | passwd ${username[$i]} --stdin\n    else \n        echo \"User ${username[$i]} exists\"\n    fi\ndone\n\n##Set permissions for opt-sas and sasdepot directories\nif [ ! -d /opt/sas/home ]; then \n    mkdir -p /opt/sas/resources /opt/sas/home /opt/sas/config\n    fail_if_error $? \"ERROR: SAS directories creation failed\"\nfi\nchmod 775 /opt/sas -R\nchown -R sasinst:sas /opt/sas\necho \"Permissions for opt-sas and sasdepot have been set.\"\n\n##Mount Azure File Share for SASDepot\ndf -h | grep -w /sasdepot\nif [ $? -eq 0 ]; then\n    echo \"SASDepot already mounted.\"\nelse\n    if [ ! -d \"/etc/smbcredentials\" ]; then\n        sudo mkdir /etc/smbcredentials\n    fi\n    if [ ! -f \"/etc/smbcredentials/store.cred\" ]; then\n        echo \"username=${store_name}\" >> /etc/smbcredentials/store.cred\n        echo \"password=${store_key}\" >> /etc/smbcredentials/store.cred\n    fi\n    sudo chmod 600 /etc/smbcredentials/store.cred\n    sudo mount -t cifs //${cifs_server_fqdn}/${store_loc} /sasdepot -o vers=3.0,credentials=/etc/smbcredentials/store.cred,dir_mode=0777,file_mode=0777,serverino\n    fail_if_error $? \"ERROR: Failed to Mount Azure file share\"\nfi\n\n\n#copyign SID file to local directories from SASDepot\ncp -rv /sasdepot/${depot_loc}/sid_files/${sas_sid} /opt/sas/resources/\nif [ ! -d $res_dir ]; then\n    mkdir -p $res_dir\nfi\n\n#extracting the properties files\ntar -xzvf /tmp/response-properties.tar.gz -C ${res_dir}\ncp -p ${res_dir}/plan.xml ${resource_dir}\ncp -p ${res_dir}/mid_* ${resource_dir}\nchown -R sasinst:sas ${resource_dir}\n\n#Changing the settings in property files\nsed -i \"s/domain_name/${domain_name}/g\" $resource_dir/*.properties\nsed -i \"s/host_name/${mid_host}/g\" $resource_dir/*.properties\nsed -i \"s/meta_host/${meta_host}/g\" $resource_dir/*.properties\nsed -i \"s|sas_plan_file_path|/opt/sas/resources/plan.xml|g\" $resource_dir/*.properties\nsed -i \"s|sas_license_file_path|/opt/sas/resources/${sas_sid}|g\" $resource_dir/*.properties\n\n#SAS Installation\nif [ -d /opt/sas/temp ]; then \n    chown sasinst /opt/sas/temp\nelse\n    mkdir -p /opt/sas/temp\n    chown sasinst /opt/sas/temp\nfi\n\nif [ -f ${inst_prop} ]; then\n    if [ ! -f /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh ]; then\n        su - sasinst -c \"time /sasdepot/${depot_loc}/setup.sh -deploy -responsefile ${inst_prop} -lang en -loglevel 2 -templocation /opt/sas/temp -quiet\"\n        if [ $? -eq 0 ]; then\n            echo \"SAS Mid-Tier Server installation has been completed succesfully.\"\n            sudo /opt/sas/home/SASFoundation/9.4/utilities/bin/setuid.sh\n            echo \"Setuid script has been run successfully.\"\n        else\n            echo \"ERROR: SAS Mid-Tier Server installation has failed. Please check logs\"\n            exit 1\n        fi\n    else \n        echo \"SAS Installation Completed. Proceeding to Configuration stage.\"\n    fi\nelse\n    echo \"SAS Install Properties file not found. Exiting Now.\"\n    exit 1\nfi\n\necho \"*** Phase 2 - SAS Mid-Tier Install Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 143}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\nset -x\necho \"*** Phase 1 - Pre-Reqs Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n## Functions\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n##Installing facter tool\nyum install ruby wget -y\nwget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm\nrpm  --reinstall -vh facter-2.*.rpm\nfail_if_error $? \"Error: Facter installation failed\"\n\n#Facter Variables and Declaration\nenvironmentLocation=\"/etc/facter/facts.d/variables.txt\"\n\nif [ -f $environmentLocation ]; then\n\trm -f $environmentLocation\nfi\n\ncat << EOF > $environmentLocation\napplication_name=$1\nsasdepot_folder=$2\nfile_share_name=$3\nstorage_account_name=$4\ndomain_name=$5\nlocation=$6\nsasint_secret_name=$7\nsasext_secret_name=$8\nkey_vault_name=$9\npvt_keyname=${10}\npub_keyname=${11}\nmid_name=${12}\nmeta_name=${13}\ncompute_name=${14}\nsas_sid=${15}\nsas_role=${16}\nartifact_loc=${17}\nstgacc_secr_name=${18}\ncifs_server_fqdn=${19}\nmid_hostname=${1}${12}\nmeta_hostname=${1}${13}\ncompute_hostname=${1}${14}\nEOF\n\n\n#Updating the Azure Cli Repo\nrpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n# Installing the azure CLI\nyum install azure-cli -y\nfail_if_error $? \"Error: Azure cli installation failed\"\n\n#Stop & Disable the firewalld(Iptables)\nsystemctl stop firewalld\nsystemctl disable firewalld\n\nmeta_hostname=`facter meta_hostname`\nmid_hostname=`facter mid_hostname`\ncompute_hostname=`facter compute_hostname`\ndomain_name=`facter domain_name`\nsas_role=`facter sas_role`\nsas_home=\"/opt/sas\"\n\n\nhostname_setup() {\n\thostnamectl set-hostname --static ${1}.${domain_name}\n\tif [ $? -eq 0 ]; then\n    \techo \"hostname update successful\"\n    \tif [ -f /etc/hostname ]; then\n        \tchattr -i /etc/hostname\n        \trm -f /etc/hostname\n        \techo ${1}.${domain_name} > /etc/hostname\n        \tchattr +i /etc/hostname\n    \tfi\n    \tif [ -f /etc/sysconfig/network ]; then\n    \t    echo \"HOSTNAME=${1}.${domain_name}\" >> /etc/sysconfig/network\n    \tfi\n   \t\techo \"Restart Network Service\"\n   \t\t/etc/init.d/network restart\n\telse\n \t   echo \"Hostname Update failed\"\nfi\n}\n\nif [ $sas_role == meta ]; then\n\thostname_setup $meta_hostname\nelif [ $sas_role == mid ]; then\n\thostname_setup $mid_hostname\nelif [ $sas_role == compute ]; then\n\thostname_setup $compute_hostname\nelse\n\techo \"ERROR: SAS ROLE is not defined\"\n\texit 1\nfi\n\n\nyum -y install java firefox xclock x11* xauth python git compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet\nfail_if_error $? \"ERROR: PreRequisites installation failed\"\n\n#System settings \nif [ -f /etc/security/limits.conf ]; then\n\tcat /etc/security/limits.conf| grep -w 500000\n\ta=`echo $?`\n\techo $a\n\tif [ \"$a\" != \"0\" ]; then\n\t\techo $a\n\t\tsed -i '$d' /etc/security/limits.conf\n\t\techo \"*               hard    nofile  500000\" >> /etc/security/limits.conf\n\t\techo \"*               soft    nofile  500000\" >> /etc/security/limits.conf\n\t\techo \"*               soft    nproc   650000\" >> /etc/security/limits.conf\n\t\techo \"*               hard    nproc   500000\" >> /etc/security/limits.conf\n\t\techo \"*               hard    stack   10240\" >> /etc/security/limits.conf\n\t\techo \"*               soft    stack   10240\" >> /etc/security/limits.conf\n\t\techo \"*               soft    stack   10240\" >> /etc/security/limits.conf\n\n\t\techo \"# End of file\" >> /etc/security/limits.conf\n\tfi\nfi\nif [ -f /etc/security/limits.d/20-nproc.conf ]; then\n\tsed -i 's/4096/unlimited/g' /etc/security/limits.d/20-nproc.conf\nfi\necho \"Security Limit values updated successfully.\"\n\n##SSHD Configuration\nif [ -f /etc/ssh/sshd_config ]; then\n\tPA=\"PasswordAuthentication yes \"\n\tPRT=\"PermitRootLogin yes\"\n\tx=`grep -i PermitRootLogin /etc/ssh/sshd_config`\n\ta=`echo $?`\n\tif [ \"$a\" == \"0\" ]; then\n\t\tsed -i '/PermitRootLogin/c\\'\"${PRT}\"'' /etc/ssh/sshd_config\n\tfi\n\tx=`grep -i PasswordAuthentication /etc/ssh/sshd_config`\n\ta=`echo $?`\n\tif [ \"$a\" == \"0\" ]; then\n\t\tsed -i.bak s/PasswordAuthentication' 'no/PasswordAuthentication' 'yes/g /etc/ssh/sshd_config\n\tfi\nfi\nsystemctl restart sshd\necho \"SSHD Configuration updated successfully.\"\n\n\n##Set Semaphore values\necho \"kernel.sem=512 32000 256 1024\" >> /etc/sysctl.conf\necho \"net.core.somaxconn=2048\" >> /etc/sysctl.conf\necho \"Semaphore values updated successfully.\"\n\n#Set default timeout values\nsed -i.bak -e 's/#DefaultTimeoutStartSec=90s/DefaultTimeoutStartSec=1800s/g' /etc/systemd/system.conf\nsed -i.bak -e 's/#DefaultTimeoutStopSec=90s/DefaultTimeoutStartSec=1800s/g' /etc/systemd/system.conf\necho \"Timeout values updated successfully.\"\n\n#Enable yum cache\nsed -i.bak -e 's/keepcache=0/keepcache=1/g' /etc/yum.conf\necho \"Yum Cache value updated successfully.\"\n\n#Set MaxStartups\nsed -i.bak -e 's/#MaxStartups 10:30:100/MaxStartups 100/g' /etc/ssh/sshd_config\necho \"Max Startups value updated successfully.\"\n\n###Configure SELINUX\nsetenforce 0\nsed -i.bak -e 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config\necho \"SELINUX set to permissive.\"\n\n##Create Mount Points\nif [ ! -d $sas_home ]; then\n\tsudo mkdir -p $sas_home\nfi\nif [ ! -d \"/sasdepot\" ]; then\n\tsudo mkdir /sasdepot\nfi\n\necho \"SAS Directories created successfully.\"\n\n##Volume Mount for opt-sas and sasdata\nlsblk /dev/disk/azure/scsi1/lun0\nif [ $? -eq 0 ] \nthen\n\tdf -h | grep $sas_home\n\tif [ $? -eq 0 ] \n\tthen\n\t\techo \"Disk for $sas_home already mounted.\"\n\telse\n\t\tmkfs.xfs /dev/disk/azure/scsi1/lun0\n\t\tmount /dev/disk/azure/scsi1/lun0 $sas_home\n\t\tfail_if_error $? \"Error:Failed to mount $sas_home\"\n\t\techo \"Disk for $sas_home located and mounted.\"\n\t\t## Adding Fstab Entries\n\t\techo \"/dev/disk/azure/scsi1/lun0  $sas_home   xfs       defaults        0 0\"  >> /etc/fstab\n\tfi\nelse\n\techo \"ERROR: $sas_home disk(lun0) is not available.\"\n\texit 1\nfi\n\n# SAS Data Volume\nlsblk /dev/disk/azure/scsi1/lun1\nif [ $? -eq 0 ] \nthen\n\tmkdir /sasdata\n\tmkfs.xfs /dev/disk/azure/scsi1/lun1\n\tmount /dev/disk/azure/scsi1/lun1 /sasdata\n\tfail_if_error $? \"Error:Failed to mount /sasdata\"\n\techo \"Disk for SASData located and mounted.\"\n\t## Adding Fstab Entries\n\techo \"/dev/disk/azure/scsi1/lun1  /sasdata   xfs       defaults        0 0\"  >> /etc/fstab\nelse\n\techo \"SASData disk not avilable on this machine.\"\nfi\n\n#PAM.D configuration for Host Authentication\nif [ ! -f /etc/pam.d/sasauth ]\nthen\n\tcp /etc/pam.d/system-auth /etc/pam.d/sasauth\n\tsed -i '/^-session/d' /etc/pam.d/sasauth\n\tsed -i '/^session/d' /etc/pam.d/sasauth\n\tsed -i '/^password/d' /etc/pam.d/sasauth\n\tif [ $? -eq 0 ] \n\tthen\n\t\techo \"PAMD configuration updated successfully.\"\n\telse\n\t\techo \"ERROR: PAMD configuration update failed.\"\n\t\texit 1\n\tfi\nelse \n\techo \"PAMD configuration exists.\"\nfi\n\necho \"*** Phase 1 - Pre-Reqs Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 236}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#set -x\n\necho \"*** Phase 5 - Viya Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n#variable declaration\napp_name=`facter app_name`\ndomain_name=`facter domain_name`\nmicroservices_vm_name=`facter microservices_vmname`\nmicroservice_host=$app_name$microservices_vm_name.$domain_name\nuser=`whoami`\nspre_vm_name=`facter spre_vmname`\nspre_host=$app_name$spre_vm_name.$domain_name\ncascontroller_vm_name=`facter cascontroller_vmname`\ncas_host=$app_name$cascontroller_vm_name.$domain_name\ncasworker_vm_name=`facter casworker_vmname`\nnodes=`facter cas_nodes`\nDIRECTORY_NFS_SHARE=\"sasdepot\"\nansible_directory=\"/sas/install\"\nplaybook_directory=\"$ansible_directory/sas_viya_playbook\"\ninventory=\"$playbook_directory/inventory.ini\"\nviyarepo_loc=`facter viyarepo_folder`\nartifact_loc=`facter artifact_loc`\nviya_ark_uri=${artifact_loc}properties/viya-ark.tar.gz\n\nif [[ -z \"$SCRIPT_PHASE\" ]]; then\n        SCRIPT_PHASE=\"$1\"\nfi\n\nif [[ \"$SCRIPT_PHASE\" -eq 1 ]]; then\n#\n##Downloading SAS Viya Orchestration CLI\n#\n        echo \"Download SAS Viya Orchestration CLI\"\n        wget https://support.sas.com/installation/viya/35/sas-orchestration-cli/lax/sas-orchestration-linux.tgz\n        if [ $? -eq 0 ]; then\n            tar -xvf sas-orchestration-linux.tgz -C $ansible_directory\n        else \n            echo \"ERROR: Download of SAS Viya Orchestration CLI failed\"\n        fi\n #\n ##Creating Viya Playbook\n #\n        $ansible_directory/sas-orchestration build --input /${DIRECTORY_NFS_SHARE}/${viyarepo_loc}/SAS_Viya_deployment_data.zip --platform redhat --repository-warehouse \"file:///${DIRECTORY_NFS_SHARE}/${viyarepo_loc}/\"\n        if [ $? -eq 0 ]; then\n                echo PWD=`pwd`\n                ##untar SAS VIYA Playbook\n                tar -xvf $PWD/SAS_Viya_playbook.tgz -C $ansible_directory\n        else\n                echo \"SAS VIYA playbook build failed\"\n        fi\n#\n##altering Ansible Config\nsed -i '/action_plugins/a host_key_checking = False' $playbook_directory/ansible.cfg\n\n#\n##Altering the Vars file \n#\n\nsed -i \"s~#CAS_DISK_CACHE~CAS_DISK_CACHE~\" $playbook_directory/vars.yml\nsed -i \"s~/tmp~/cascache~\" $playbook_directory/vars.yml\nsed -i \"/#CAS_VIRTUAL_PORT/ a newline\" $playbook_directory/vars.yml\nsed -i \"s|newline|    CASDATADIR: /sasdata|g\" $playbook_directory/vars.yml\nsed -i 's/#SASV9_CONFIGURATION/SASV9_CONFIGURATION/g' $playbook_directory/vars.yml\necho \"  1: 'WORK /saswork'\" >> $playbook_directory/vars.yml\necho \"  2: 'UTILLOC /saswork'\" >> $playbook_directory/vars.yml\nsed -i 's/#sasstudio.appserver.port/sasstudio.appserver.port/g' $playbook_directory/vars.yml\nsed -i 's/#sasstudio.appserver.https.port/sasstudio.appserver.https.port/g' $playbook_directory/vars.yml\nsed -i \"/#webdms.workspaceServer.hostName/c\\    webdms.workspaceServer.hostName: ${spre_host}\" $playbook_directory/vars.yml\nsed -i 's/#webdms.workspaceServer.port/webdms.workspaceServer.port/g' $playbook_directory/vars.yml\nsed -i 's/#FOUNDATION_CONFIGURATION/FOUNDATION_CONFIGURATION/g' $playbook_directory/vars.yml\nsed -i  \"/FOUNDATION_CONFIGURATION/a temploc\" $playbook_directory/vars.yml\nsed -i  \"s|temploc|  1: COMPUTESERVER_TMP_PATH=/saswork|g\" $playbook_directory/vars.yml\n\n#\n##Altering the Inventory file\n#\nif [ -f $inventory ]; then\n\nsed -i 's/<machine_address>/'\"$microservice_host\"'/g' $inventory\nsed -i 's/<userid>/'\"$user\"'/g' $inventory\nsed -i \"s~<keyfile>~/$user/.ssh/id_rsa consul_bind_adapter=eth0~\" $inventory\n\nsed -i \"2i$spre_vm_name ansible_host=$spre_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0\" $inventory\n\nsed -i \"3i$cascontroller_vm_name ansible_host=$cas_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0\" $inventory\n\nfor ((i=0; i < $nodes ; i++))\ndo\n  cat <<EOF >> caswork.txt\n$casworker_vm_name$i\nEOF\n  caswork_host=$app_name$casworker_vm_name$i.$domain_name\n  sed -i \"4i$casworker_vm_name$i ansible_host=$caswork_host ansible_user=$user ansible_ssh_private_key_file=/$user/.ssh/id_rsa consul_bind_adapter=eth0\" $inventory\ndone\n\nsed -i \"/\\[sas_casserver_primary\\]/{n;s/.*/$cascontroller_vm_name/}\" $inventory\nsed -i \"/\\[sas_casserver_worker\\]/r caswork.txt\" $inventory\nsed -i \"/\\[ComputeServer\\]/{n;s/.*/$spre_vm_name/}\" $inventory\nsed -i \"/\\[Operations\\]/{n;s/.*/$spre_vm_name/}\" $inventory\nsed -i \"/\\[programming\\]/{n;s/.*/$spre_vm_name/}\" $inventory\n\ncat <<EOF >> caswork.txt\n$spre_vm_name\n$cascontroller_vm_name\nEOF\nsed -i \"/\\[CommandLine\\]/r caswork.txt\" $inventory\nrm -f caswork.txt\nelse\n       echo \"ERROR: Inventory file path doesnot exist\"\nfi\n#\n##Running System Assesement using ansible playbook\n#\ncd $playbook_directory && ansible-playbook system-assessment.yml -i inventory.ini -vvv\n\nelif [[ \"$SCRIPT_PHASE\" -eq 2 ]]; then\n         mkdir /.ssh && touch /.ssh/known_hosts \n        cd $playbook_directory && ansible-playbook install-only.yml -i inventory.ini -vvv\n        echo \"*** Phase 5 Part 2 - Viya Install only ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\nelif [[ \"$SCRIPT_PHASE\" -eq 3 ]]; then\n        cd $playbook_directory && ansible-playbook site.yml -i inventory.ini -vvv\n        echo \"*** Phase 5 Part 3 - Viya Configuration ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\nelif [[ \"$SCRIPT_PHASE\" -eq 4 ]]; then\n        wget $viya_ark_uri\n        mkdir -p $playbook_directory/viya-ark\n        tar -xzvf viya-ark.tar.gz -C $playbook_directory/viya-ark/\n        ssh -tT $user@${spre_host} << EOF\necho \"export SASMAKEHOMEDIR=1\"     >> /opt/sas/viya/config/etc/spawner/default/spawner_usermods.sh\necho \"export SASHOMEDIRPERMS=0700\" >> /opt/sas/viya/config/etc/spawner/default/spawner_usermods.sh\nEOF\n\nfor s in ${microservice_host} ${spre_host} ${cas_host}\ndo \n        ssh -tT $user@$s << EOF\n. /opt/sas/viya/config/consul.conf\n/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASMAKEHOMEDIR 1\n/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASHOMEDIRPERMS 0700\nEOF\ndone\n\nfor ((i=0; i < $nodes ; i++))\ndo\n        casworker_node=$app_name$casworker_vm_name$i.$domain_name\n        ssh -tT $user@$casworker_node << EOF\n. /opt/sas/viya/config/consul.conf\n/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASMAKEHOMEDIR 1\n/opt/sas/viya/home/bin/sas-bootstrap-config --token-file /opt/sas/viya/config/etc/SASSecurityCertificateFramework/tokens/consul/default/client.token kv write config/launcher-server/global/environment/SASHOMEDIRPERMS 0700\nEOF\ndone\necho `ssh -o StrictHostKeyChecking=no $app_name$microservices_vm_name \"grep -H -r \"sasboot\" /var/log/sas/viya/saslogon/default/sas-saslogon*  | sed 's/.*code=//'\"`\nsasboot=`ssh -o StrictHostKeyChecking=no $app_name$microservices_vm_name \"grep -H -r \"sasboot\" /var/log/sas/viya/saslogon/default/sas-saslogon*  | sed 's/.*code=//'\"`\necho \"{'SAS_BOOT': '$sasboot'}\" > /var/log/sas/install/sasboot.log\necho \"#SASBOOT#\"\ncat /var/log/sas/install/sasboot.log\nfi", "num_lines": 158}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\n\necho \"*** Phase 2 - Viya-ARK Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n\n## Functions\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n#Variable declaration\npub_keyname=`facter secret_pub_keyname`\nkey_vault_name=`facter kv_vault_name`\nartifact_loc=`facter artifact_loc`\nsasint_secret_name=`facter sasintpwd`\nsasext_secret_name=`facter casintpwd`\nCODE_DIRECTORY=\"/opt/viya-ark\"\nplaybook_directory=\"$CODE_DIRECTORY/pre-install-playbook\"\n#viya_ark_file=`facter viya_ark_file`\n\n# Setting up the public key under root user for passwordless SSH\naz login --identity\nfail_if_error $? \"ERROR: Azure login failed\"\nsaspwd=`az keyvault secret show -n $sasint_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\ncaspwd=`az keyvault secret show -n $sasext_secret_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\necho `az keyvault secret show -n ${pub_keyname}  --vault-name ${key_vault_name} | grep value | cut -d '\"' -f4` >> ~/.ssh/authorized_keys\n\n#wget $viya_ark_file\n\n##untar viya-ark\nif [ ! -d ${CODE_DIRECTORY} ]; then\n    mkdir -p ${CODE_DIRECTORY}\nfi\n  tar -xzvf /tmp/viya-ark.tar.gz -C ${CODE_DIRECTORY}\n  fail_if_error $? \"viya-ark file not found\"\n#\n## Running the Ansible Playbook on the Viya Servers\n#\ncd $playbook_directory && ansible-playbook viya_pre_install_playbook.yml -i pre-install.inventory.ini  -vvv\n#\n## Setting up Password for user SAS and CAS\n#\nusername=(\"sas\" \"cas\")\npassword=(\"$saspwd\" \"$caspwd\")\nfor ((i=0;i<${#username[@]};++i));\ndo\n        if [ `sed -n \"/^${username[$i]}/p\" /etc/passwd` ]\n        then\n                echo \"Setting the password for ${username[$i]}\"\n                echo ${password[$i]} | passwd ${username[$i]}  --stdin\n    else\n                echo \"User ${username[$i]} doesn't exist\"\n        fi\ndone\n\necho \"*** Phase 2 - Viya-ARK Script ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"", "num_lines": 60}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -x\necho \"*** Phase 1 - Pre-Reqs Script Started at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n\n\n## Functions\nfail_if_error() {\n  [ $1 != 0 ] && {\n    echo $2\n    exit 10\n  }\n}\n\n## Facter Installation\nyum install ruby wget -y\nwget http://download-ib01.fedoraproject.org/pub/epel/7/x86_64/Packages/f/facter-2.4.1-1.el7.x86_64.rpm\nrpm  --reinstall -vh facter-2.*.rpm\nfail_if_error $? \"Error: Facter installation failed\"\n\n#Facter Variables and Declaration\nenvironmentLocation=\"/etc/facter/facts.d/variables.txt\"\n\nif [ -f $environmentLocation ]; then\n\trm -f $environmentLocation\nfi\n\n\n#Facter Variables and Declaration\ncat << EOF > $environmentLocation\nazure_storage_account=$1\nazure_storage_files_share=$2\nDIRECTORY_NFS_SHARE=$3\napp_name=$4\ndomain_name=$5\nansible_vmname=$6\nmicroservices_vmname=$7\ncascontroller_vmname=$8\nspre_vmname=${9}\ncasworker_vmname=${10}\nsasintpwd=${11}\ncasintpwd=${12}\nkv_vault_name=${13}\nsecret_pvt_keyname=${14}\nsecret_pub_keyname=${15}\ncas_nodes=${16}\nartifact_loc=${17}\nstgacc_secr_name=${18}\ncifs_server_fqdn=${19}\nEOF\n\n\n#Updating the Azure Cli Repo\nrpm --import https://packages.microsoft.com/keys/microsoft.asc;sh -c 'echo -e \"[azure-cli]\\nname=Azure CLI\\nbaseurl=https://packages.microsoft.com/yumrepos/azure-cli\\nenabled=1\\ngpgcheck=1\\ngpgkey=https://packages.microsoft.com/keys/microsoft.asc\" > /etc/yum.repos.d/azure-cli.repo'\n# Installing the azure CLI\nyum install azure-cli -y\nfail_if_error $? \"Error: Azure cli installation failed\"\n\nif ! type -p ansible;  then\n   # install Ansible\n    curl --retry 10 --max-time 60 --fail --silent --show-error \"https://bootstrap.pypa.io/get-pip.py\" -o \"get-pip.py\"\n    sudo python get-pip.py\n    pip install 'ansible==2.8.3'\n    fail_if_error $? \"Error: Ansible client installation is failed\"\nfi\n\n#Stop & Disable the firewalld(Iptables)\nsystemctl stop firewalld\nsystemctl disable firewalld\n\n\n#Variable Declaration\nazure_storage_account=`facter azure_storage_account`\nazure_storage_files_password=`facter azure_storage_files_password`\nazure_storage_files_share=`facter azure_storage_files_share`\nDIRECTORY_NFS_SHARE=\"sasdepot\"\napp_name=`facter app_name`\ndomain_name=`facter domain_name`\nansible_vmname=`facter ansible_vmname`\nmicroservices_vmname=`facter microservices_vmname`\ncascontroller_vmname=`facter cascontroller_vmname`\nspre_vmname=`facter spre_vmname`\nmachine_name=`curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/name?api-version=2017-08-01&format=text\"`\ncurrent_host=${app_name}${machine_name}\nsas_home=\"/opt/sas\"\nbackupdir=\"/backup\"\nsasdatadir=\"/sasdata\"\n\n\n#RhelRequired packages\nyum -y install java-1.8.0-openjdk yum-utils firefox xclock x11* xauth git python compat-glibc libpng12 lsof at numactl glibc libpng ntp apr ksh wget mlocate libXext.x86_64 libXp.x86_64 libXtst.x86_64 xorg-x11-xauth.x86_64 gcc libSM.i686 libXrender.i686 zlib.i686 nfs-utils cifs-utils telnet\nfail_if_error $? \"Error: PreRequisites installation failed\"\n\n##SSHD Configuration\nif [ -f /etc/ssh/sshd_config ]\n    then\n        PA=\"PasswordAuthentication yes \"\n        PRT=\"PermitRootLogin yes\"\n        x=`grep -i PermitRootLogin /etc/ssh/sshd_config`\n        a=`echo $?`\n    if [ \"$a\" == \"0\" ]\n        then\n            sed -i '/PermitRootLogin/c\\'\"${PRT}\"'' /etc/ssh/sshd_config\n    fi\n    x=`grep -i PasswordAuthentication /etc/ssh/sshd_config`\n    a=`echo $?`\n    if [ \"$a\" == \"0\" ]\n        then\n            sed -i.bak s/PasswordAuthentication' 'no/PasswordAuthentication' 'yes/g /etc/ssh/sshd_config\n    fi\nfi\n\n#Modifying SSHD Config Setting \nsed -i '/ClientAliveInterval/c\\ClientAliveInterval 3600' /etc/ssh/sshd_config\nsed -i 's/#MaxStartups 10:30:100/MaxStartups 100/g' /etc/ssh/sshd_config\n\nsystemctl restart sshd\necho \"SSHD Configuration updated successfully.\"\n\n\n#System settings for ulimits\nif [ -f /etc/security/limits.conf ]\nthen\n\tcat /etc/security/limits.conf| grep -w 500000\n\ta=`echo $?`\n\techo $a\n\tif [ \"$a\" != \"0\" ]\n\tthen\n\t\techo $a\n\t\tsed -i '$d' /etc/security/limits.conf\n\t\techo \"*               hard    nofile  500000\" >> /etc/security/limits.conf\n\t\techo \"*               soft    nofile  500000\" >> /etc/security/limits.conf\n\t\techo \"*               soft    nproc   650000\" >> /etc/security/limits.conf\n\t\techo \"*               hard    nproc   500000\" >> /etc/security/limits.conf\n\t\techo \"*               hard    stack   10240\" >> /etc/security/limits.conf\n\t\techo \"*               soft    stack   10240\" >> /etc/security/limits.conf\n\t\techo \"*               soft    stack   10240\" >> /etc/security/limits.conf\n\n\t\techo \"# End of file\" >> /etc/security/limits.conf\n\tfi\nfi\nif [ -f /etc/security/limits.d/20-nproc.conf ]\nthen\n\tsed -i 's/4096/unlimited/g' /etc/security/limits.d/20-nproc.conf\nfi\n\n#Static Hostname Setup for Server\necho \"setting up the new hostname on the server\"\necho $current_host\nhostnamectl set-hostname --static ${current_host}.${domain_name}\nif [ $? -eq 0 ]; then\n    echo \"hostname update successful\"\n    if [ -f /etc/hostname ]; then\n        chattr -i /etc/hostname\n        rm -f /etc/hostname\n        echo ${current_host}.${domain_name} > /etc/hostname\n        chattr +i /etc/hostname\n    fi\n    if [ -f /etc/sysconfig/network ]; then\n        echo \"HOSTNAME=${current_host}.${domain_name}\" >> /etc/sysconfig/network\n    fi\n    echo \"Restart Network Service\"\n    /etc/init.d/network restart\nelse\n    echo \"Hostname Update failed\"\nfi\n\n\n###Configure SELINUX\nsetenforce 0\nsed -i.bak -e 's/SELINUX=enforcing/SELINUX=permissive/g' /etc/selinux/config\necho \"SELINUX set to permissive.\"\n\n\n##Create Mount Points\nif [ ! -d \"$sas_home\" ]; then\n    sudo mkdir -p $sas_home\nfi\n\n##Create Mount Points\nif [ ! -d \"$backupdir\" ]; then\n    sudo mkdir -p $backupdir\nfi\n\n##Create Mount Points\nif [ ! -d \"$sasdatadir\" ]; then\n    sudo mkdir -p $sasdatadir\nfi\n\n##Volume Mount for opt-sas\nlsblk /dev/disk/azure/scsi1/lun0\nif [ $? -eq 0 ]; then \n    df -h | grep $sas_home\n\tif [ $? -eq 0 ]; then\n\t\techo \"Disk for $sas_home already mounted.\"\n    else\n        mkfs.xfs /dev/disk/azure/scsi1/lun0\n\t\tmount /dev/disk/azure/scsi1/lun0 $sas_home\n\t\tfail_if_error $? \"Error:Failed to mount $sas_home\"\n\t\t## Adding Fstab Entries\n\t\techo \"/dev/disk/azure/scsi1/lun0   $sas_home   xfs       defaults        0 0\"  >> /etc/fstab\n        echo \"Disk for $sas_home located and mounted.\"\n    fi\nelse\n    echo \"ERROR: $sas_home disk(lun0) disk failed to mount or disk not available.\"\n    #exit 1\nfi\n\n##Volume Mount for sasbackup\nlsblk /dev/disk/azure/scsi1/lun1\n    if [ $? -eq 0 ]; then\n        df -h | grep $backup\n        if [ $? -eq 0 ] \n\t    then\n                echo \"Disk for \"$backupdir\" already mounted\"\n        else\n            mkfs.xfs /dev/disk/azure/scsi1/lun1\n            mount /dev/disk/azure/scsi1/lun1 $backupdir\n            fail_if_error $? \"Error:Failed to mount $backupdir\"\n            ## Adding Fstab Entries\n            echo \"/dev/disk/azure/scsi1/lun1     $backupdir         xfs       defaults        0 0\"  >> /etc/fstab\n            echo \"Disk for $backupdir located and mounted.\"\n        fi\n    else\n        echo \"ERROR: $backupdir disk(lun1) disk failed to mount or disk not available\"\n        #exit 1\n    fi\n\n##Volume Mount for sasdata\nif [ $machine_name == $cascontroller_vmname ]; then\n    lsblk /dev/disk/azure/scsi1/lun2\n    if [ $? -eq 0 ]; then\n        df -h | grep $backup\n        if [ $? -eq 0 ] \n\t    then\n                echo \"Disk for \"$sasdatadir\" already mounted\"\n        else\n            mkfs.xfs /dev/disk/azure/scsi1/lun2\n            mount /dev/disk/azure/scsi1/lun2 $sasdatadir\n            fail_if_error $? \"Error:Failed to mount $sasdatadir\"\n            ## Adding Fstab Entries\n            echo \"/dev/disk/azure/scsi1/lun2    \"$sasdatadir\"           xfs       defaults        0 0\"  >> /etc/fstab\n            echo \"Disk for $sasdatadir located and mounted.\"\n        fi\n    else\n        echo \"ERROR: \"$sasdatadir\" disk(lun2) disk failed to mount or disk not available \"\n        #exit 1\n    fi\nfi\n\n#Mounting Azure File Share for SAS Viya Play book\nstgacc_secr_name=`facter stgacc_secr_name`\nkey_vault_name=`facter kv_vault_name`\naz login --identity\nfail_if_error $? \"Error: Az login Failed\"\nazure_storage_files_password=`az keyvault secret show -n $stgacc_secr_name --vault-name $key_vault_name | grep value | cut -d '\"' -f4`\necho \"setup cifs\"\ncifs_server_fqdn=`facter cifs_server_fqdn`\n\nif [ ! -d \"/etc/smbcredentials\" ]; then\n    sudo mkdir /etc/smbcredentials\nfi\nchmod 700 /etc/smbcredentials\nif [ ! -f \"/etc/smbcredentials/\"${azure_storage_account}\".cred\" ]; then\n    echo \"username=${azure_storage_account}\" >> /etc/smbcredentials/${azure_storage_account}.cred\n    echo \"password=${azure_storage_files_password}\" >> /etc/smbcredentials/${azure_storage_account}.cred\nfi\nchmod 600 \"/etc/smbcredentials/${azure_storage_account}.cred\"\n\nmkdir -p \"/${DIRECTORY_NFS_SHARE}\"\nmount -t cifs //${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  -o vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,serverino\nfail_if_error $? \"Error: SAS Depot Mount Failed\"\n#echo \"//${cifs_server_fqdn}/${azure_storage_files_share} /${DIRECTORY_NFS_SHARE}  cifs defaults,vers=3.0,credentials=/etc/smbcredentials/${azure_storage_account}.cred,dir_mode=0777,file_mode=0777,sec=ntlmssp 0 0\" >> /etc/fstab\n#mount -a\n\necho \"*** Phase 1 - Pre-Reqs Script Ended at `date +'%Y-%m-%d_%H-%M-%S'` ***\"\n", "num_lines": 276}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get -y update\nsudo apt-get install -y python3 python-dev python3-dev build-essential libssl-dev libffi-dev libxml2-dev libxslt-dev python3-pip\n\nsudo pip3 install scrapy", "num_lines": 6}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "\nmysqlpassword=$1\nmySqlUser=$2\nmySqlPasswordForUser=$3\n\napt-get -y update\napt-get -y install apache2 openjdk-7-jdk tomcat7\n\n#install mysql\necho mysql-server mysql-server/root_password password $mysqlpassword | sudo debconf-set-selections\necho mysql-server mysql-server/root_password_again password $mysqlpassword | sudo debconf-set-selections\n\n\napt-get purge mysql-server mysql-client mysql-common mysql-server-core-* mysql-client-core-*\nrm -rf /etc/mysql /var/lib/mysql\napt-get autoremove\napt-get autoclean\napt-get -y install mysql-client mysql-server\napt-get\tinstall libmysql-java\n\n# Allow remote connection\nsed -i \"s/bind-address.*/bind-address = 0.0.0.0/\" /etc/mysql/my.cnf\n\n#create database\nmysql -u root -p$mysqlpassword -e \"create database idp_db\";\n\n#create table\nmysql -u root -p$mysqlpassword -e \"use idp_db; create table StorageRecords(context varchar(255) NOT NULL,id varchar(255) NOT NULL,expires bigint(20) DEFAULT NULL,value longtext NOT NULL,version bigint(20) NOT NULL,PRIMARY KEY(context,id))\";\n\n#create user & grant all privileges\nmysql -u root -p$mysqlpassword -e \"create user $mySqlUser@'localhost' identified by '$mySqlPasswordForUser'\";\nmysql -u root -p$mysqlpassword -e \"grant all privileges on *.* to $mySqlUser@'localhost'\";\n\nmysql -u root -p$mysqlpassword -e \"create user $mySqlUser@'%' identified by '$mySqlPasswordForUser'\";\nmysql -u root -p$mysqlpassword -e \"grant all privileges on *.* to $mySqlUser@'%'\";\n\n#restart mysql\nservice mysql restart\n", "num_lines": 39}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "domain=$1\nlocation=$2\ndbdomain=$3\nmySqlUser=$4\nmySqlPasswordForUser=$5\n\nSITENAME=$1.$2.cloudapp.azure.com\nDBSITENAME=$3.$2.cloudapp.azure.com\n\nINSTALLDIR=/opt/shibboleth-idp\n\napt-get -y update\n\necho \"==============>Printing values of all variables\"\necho \"domain\"\necho $domain\necho \"location\"\necho $location\necho \"Sitename\"\necho $SITENAME\n\n\n#install Oracle JDK 7\necho debconf shared/accepted-oracle-license-v1-1 select true | \\\nsudo debconf-set-selections\n\necho debconf shared/accepted-oracle-license-v1-1 seen true | \\\nsudo debconf-set-selections\n\necho \"==============>Installing JDK 8\"\n\napt-get -y install python-software-properties\nadd-apt-repository -y ppa:webupd8team/java\napt-get -y update\napt-get -y install oracle-java8-installer\n\n\n#install Tomcat 8\n\necho \"==============>Installing tomcat8\"\n\napt-get -y install tomcat8\nexport JAVA_HOME=/usr/lib/jvm/java-8-oracle\nexport PATH=$PATH:$JAVA_HOME/bin\nexport JRE_HOME=/usr/lib/jvm/java-8-oracle/jre\nexport JAVA_OPTS=\"-XX:+AggressiveOpts -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:+DisableExplicitGC\"\n\nsed -i 's/#AUTHBIND=no/AUTHBIND=yes/g' /etc/default/tomcat8\n\n#generating the self signed SSL certificate for tomcat8\n\necho \"==============>Configuring SSL for tomcat8\"\n\nmkdir /usr/share/tomcat8/keystore\ncd $JAVA_HOME/bin\n\nSSLKEYPASSWORD=$(openssl rand -base64 12)\n\nkeytool -genkey -alias tomcat -keyalg RSA -keystore /usr/share/tomcat8/keystore/server.keystore -keysize 2048 -storepass $SSLKEYPASSWORD -keypass $SSLKEYPASSWORD -dname \"cn=$SITENAME, ou=shibbolethOU, o=shibbolethO, c=US\"\nsed -i -e 's,redirectPort=\"8443\",redirectPort=\"8443\" address=\"0.0.0.0\",g' /var/lib/tomcat8/conf/server.xml\nsed -i '/redirectPort=\"8443\"/a  <Connector port=\"8443\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\" maxThreads=\"150\" scheme=\"https\" secure=\"true\"  clientAuth=\"false\" sslProtocol=\"TLS\" address=\"0.0.0.0\" keystoreFile=\"/\\usr/\\share\\/tomcat8/\\keystore/\\server.keystore\" keystorePass=\"'$SSLKEYPASSWORD'\"/>' /var/lib/tomcat8/conf/server.xml\n\n\n#download jstl as it is not distributed with tomcat8 and is required by Shibboleth\n\necho \"==============>Adding JSTL to tomcat8\"\n\ncd /usr/share/tomcat8/lib\nwget http://central.maven.org/maven2/jstl/jstl/1.2/jstl-1.2.jar\nchmod 777 jstl-1.2.jar\n\n#START Shibboleth installation\n\necho \"==============> Start Shibboleth installation\"\necho \"==============> Download Shibboleth\"\n\n# install Shibboleth\nwget http://shibboleth.net/downloads/identity-provider/3.3.3/shibboleth-identity-provider-3.3.3.zip -O shibboleth.zip\njar -xf shibboleth.zip\n\ncd shibboleth-identity-provider-3.3.3\nchmod -R +x bin\n\n# generate a password for client-side encryption\necho \"idp.sealer.password = $(openssl rand -base64 12)\" >credentials.properties\nchmod 0600 credentials.properties\n\n# preconfigure settings for a typical deployment\n\necho \"==============> Generate preconfig file\"\n\ncat >temp.properties <<EOF\nidp.additionalProperties= /conf/ldap.properties, /conf/saml-nameid.properties, /conf/services.properties, /conf/credentials.properties\nidp.sealer.storePassword= %{idp.sealer.password}\nidp.sealer.keyPassword= %{idp.sealer.password}\nidp.signing.key= %{idp.home}/credentials/idp.key\nidp.signing.cert= %{idp.home}/credentials/idp.crt\nidp.encryption.key= %{idp.home}/credentials/idp.key\nidp.encryption.cert= %{idp.home}/credentials/idp.crt\nidp.entityID= https://$SITENAME/idp/shibboleth\nidp.scope= $SITENAME\nidp.consent.StorageService= shibboleth.JPAStorageService\nidp.consent.userStorageKey= shibboleth.consent.AttributeConsentStorageKey\nidp.consent.userStorageKeyAttribute= %{idp.persistentId.sourceAttribute}\nidp.consent.allowGlobal= false\nidp.consent.compareValues= true\nidp.consent.maxStoredRecords= -1\nidp.ui.fallbackLanguages= en,de,fr\nEOF\n\necho \"==============> Running the installer\"\n\n# run the installer\nSRCDIR=$(pwd)\n\nbash bin/install.sh \\\n-Didp.relying.party.present= \\\n-Didp.src.dir=. \\\n-Didp.target.dir=$INSTALLDIR \\\n-Didp.merge.properties=temp.properties \\\n-Didp.sealer.password=$(cut -d \" \" -f3 <credentials.properties) \\\n-Didp.keystore.password= \\\n-Didp.conf.filemode=644 \\\n-Didp.host.name=$SITENAME \\\n-Didp.scope=$SITENAME\n\nchown -R tomcat8 /opt/shibboleth-idp/\n\n#edit all location's port 8443 /opt/shibboleth-idp/metadata/idp.metadata\necho \"==============> Updating the urls in metadata.xml\"\n\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/Shibboleth/SSO,https://'\"$SITENAME\"':8443/idp/profile/Shibboleth/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/POST/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/POST/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/POST-SimpleSign/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/POST-SimpleSign/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/Redirect/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/Redirect/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\n\n# Use context deployment fragment for deploying idp.war file\necho \"==============> Adding application to tomcat8\"\n\necho \"<Context docBase=\\\"/opt/shibboleth-idp/war/idp.war\\\" privileged=\\\"true\\\" antiresourcelocking=\\\"false\\\" antijarlocking=\\\"false\\\" unpackwar=\\\"false\\\" swallowoutput=\\\"true\\\" />\" > /var/lib/tomcat8/conf/Catalina/localhost/idp.xml\nmv credentials.properties $INSTALLDIR/conf\n\necho -e \"\\nCreating self-signed certificate...\"\nbin/keygen.sh --lifetime 3 \\\n--certfile $INSTALLDIR/credentials/idp.crt \\\n--keyfile $INSTALLDIR/credentials/idp.key \\\n--hostname $SITENAME \\\n--uriAltName https://$SITENAME/idp/shibboleth\necho ...done\nchmod 600 $INSTALLDIR/credentials/idp.key\n\n# set owner of key file and directories\ngetent passwd tomcat8 >/dev/null && TCUSER=tomcat8 || TCUSER=tomcat\nchown $TCUSER $INSTALLDIR/credentials/idp.key\nchown $TCUSER $INSTALLDIR/credentials/sealer.*\nchown $TCUSER $INSTALLDIR/metadata\nchown $TCUSER $INSTALLDIR/logs\nchown $TCUSER $INSTALLDIR/conf/credentials.properties\n\n#allow access to public\nsed -i -e \"s~'::1/128'~'::1/128', '0.0.0.0/0'~g\" /opt/shibboleth-idp/conf/access-control.xml\n\n#add beans shibboleth.JPAStorageService, shibboleth.JPAStorageService.EntityManagerFactory, shibboleth.JPAStorageService.JPAVendorAdapter & shibboleth.JPAStorageService.DataSource\nsed -i -e 's~</beans>~<bean id=\\\"shibboleth.JPAStorageService\\\" class=\\\"org.opensaml.storage.impl.JPAStorageService\\\" p:cleanupInterval=\\\"%{idp.storage.cleanupInterval:PT10M}\\\" c:factory-ref=\\\"shibboleth.JPAStorageService.entityManagerFactory\\\" /> <bean id=\\\"shibboleth.JPAStorageService.entityManagerFactory\\\" class=\\\"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean\\\"> <property name=\\\"packagesToScan\\\" value=\\\"org.opensaml.storage.impl\\\"/> <property name=\\\"dataSource\\\" ref=\\\"shibboleth.JPAStorageService.DataSource\\\"/> <property name=\\\"jpaVendorAdapter\\\" ref=\\\"shibboleth.JPAStorageService.JPAVendorAdapter\\\"/> <property name=\\\"jpaDialect\\\"> <bean class=\\\"org.springframework.orm.jpa.vendor.HibernateJpaDialect\\\" /> </property> </bean> <bean id=\\\"shibboleth.JPAStorageService.JPAVendorAdapter\\\" class=\\\"org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter\\\"> <property name=\\\"database\\\" value=\\\"MYSQL\\\" /> </bean> <bean\tid=\\\"shibboleth.JPAStorageService.DataSource\\\" class=\\\"org.apache.tomcat.jdbc.pool.DataSource\\\" destroy-method=\\\"close\\\" lazy-init=\\\"true\\\" p:driverClassName=\\\"com.mysql.jdbc.Driver\\\" p:url=\\\"jdbc:mysql://'\"$DBSITENAME\"':3306/idp_db?autoReconnect=true\\&amp;sessionVariables=wait_timeout=31536000\\\" p:validationQuery=\\\"SELECT 1;\\\" p:username=\\\"'\"$mySqlUser\"'\\\" p:password=\\\"'\"$mySqlPasswordForUser\"'\\\" /> </beans>~g' /opt/shibboleth-idp/conf/global.xml\n\nsed -i \"s/#idp.session.StorageService.*/idp.session.StorageService = shibboleth.JPAStorageService/\" /opt/shibboleth-idp/conf/idp.properties\nsed -i \"s/#idp.consent.StorageService.*/idp.consent.StorageService = shibboleth.JPAStorageService/\" /opt/shibboleth-idp/conf/idp.properties\nsed -i \"s/#idp.replayCache.StorageService.*/idp.replayCache.StorageService = shibboleth.JPAStorageService/\" /opt/shibboleth-idp/conf/idp.properties\nsed -i \"s/#idp.artifact.StorageService.*/idp.artifact.StorageService = shibboleth.JPAStorageService/\" /opt/shibboleth-idp/conf/idp.properties\n\n#add mysql-connector-java.jar in /tomcat8/lib\ncd /usr/share/tomcat8/lib\nwget http://central.maven.org/maven2/mysql/mysql-connector-java/5.1.6/mysql-connector-java-5.1.6.jar\n\n#restart tomcat\nservice tomcat8 restart\n", "num_lines": 177}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "domain=$1\nlocation=$2\nSITENAME=$1.$2.cloudapp.azure.com\n\nINSTALLDIR=/opt/shibboleth-idp\n\napt-get -y update\n\necho \"==============>Printing values of all variables\"\necho \"domain\"\necho $domain\necho \"location\"\necho $location\necho \"Sitename\"\necho $SITENAME\n\n\n#install Oracle JDK 7\necho debconf shared/accepted-oracle-license-v1-1 select true | \\\nsudo debconf-set-selections\n\necho debconf shared/accepted-oracle-license-v1-1 seen true | \\\nsudo debconf-set-selections\n\necho \"==============>Installing JDK 8\"\n\napt-get -y install python-software-properties\nadd-apt-repository -y ppa:webupd8team/java\napt-get -y update\napt-get -y install oracle-java8-installer\n\n\n#install Tomcat 8\n\necho \"==============>Installing tomcat8\"\n\napt-get -y install tomcat8\nexport JAVA_HOME=/usr/lib/jvm/java-8-oracle\nexport PATH=$PATH:$JAVA_HOME/bin\nexport JRE_HOME=/usr/lib/jvm/java-8-oracle/jre\nexport JAVA_OPTS=\"-XX:+AggressiveOpts -Xms256m -Xmx512m -XX:MaxPermSize=256m -XX:+DisableExplicitGC\"\n\nsed -i 's/#AUTHBIND=no/AUTHBIND=yes/g' /etc/default/tomcat8\n\n#generating the self signed SSL certificate for tomcat8\n\necho \"==============>Configuring SSL for tomcat8\"\n\nmkdir /usr/share/tomcat8/keystore\ncd $JAVA_HOME/bin\n\nSSLKEYPASSWORD=$(openssl rand -base64 12)\n\nkeytool -genkey -alias tomcat -keyalg RSA -keystore /usr/share/tomcat8/keystore/server.keystore -keysize 2048 -storepass $SSLKEYPASSWORD -keypass $SSLKEYPASSWORD -dname \"cn=$SITENAME, ou=shibbolethOU, o=shibbolethO, c=US\"\nsed -i -e 's,redirectPort=\"8443\",redirectPort=\"8443\" address=\"0.0.0.0\",g' /var/lib/tomcat8/conf/server.xml\nsed -i '/redirectPort=\"8443\"/a  <Connector port=\"8443\" protocol=\"HTTP/1.1\" SSLEnabled=\"true\" maxThreads=\"150\" scheme=\"https\" secure=\"true\"  clientAuth=\"false\" sslProtocol=\"TLS\" address=\"0.0.0.0\" keystoreFile=\"/\\usr/\\share\\/tomcat8/\\keystore/\\server.keystore\" keystorePass=\"'$SSLKEYPASSWORD'\"/>' /var/lib/tomcat8/conf/server.xml\n\n#download jstl as it is not distributed with tomcat8 and is required by Shibboleth\n\necho \"==============>Adding JSTL to tomcat8\"\n\ncd /usr/share/tomcat8/lib\nwget http://central.maven.org/maven2/jstl/jstl/1.2/jstl-1.2.jar\nchmod 777 jstl-1.2.jar\n\n#START Shibboleth installation\n\necho \"==============> Start Shibboleth installation\"\necho \"==============> Download Shibboleth\"\n\n# install Shibboleth\nwget http://shibboleth.net/downloads/identity-provider/3.3.3/shibboleth-identity-provider-3.3.3.zip -O shibboleth.zip\njar -xf shibboleth.zip\n\ncd shibboleth-identity-provider-3.3.3\nchmod -R +x bin\n\n# generate a password for client-side encryption\necho \"idp.sealer.password = $(openssl rand -base64 12)\" >credentials.properties\nchmod 0600 credentials.properties\n\n# preconfigure settings for a typical deployment\n\necho \"==============> Generate preconfig file\"\n\ncat >temp.properties <<EOF\nidp.additionalProperties= /conf/ldap.properties, /conf/saml-nameid.properties, /conf/services.properties, /conf/credentials.properties\nidp.sealer.storePassword= %{idp.sealer.password}\nidp.sealer.keyPassword= %{idp.sealer.password}\nidp.signing.key= %{idp.home}/credentials/idp.key\nidp.signing.cert= %{idp.home}/credentials/idp.crt\nidp.encryption.key= %{idp.home}/credentials/idp.key\nidp.encryption.cert= %{idp.home}/credentials/idp.crt\nidp.entityID= https://$SITENAME/idp/shibboleth\nidp.scope= $SITENAME\nidp.consent.StorageService= shibboleth.JPAStorageService\nidp.consent.userStorageKey= shibboleth.consent.AttributeConsentStorageKey\nidp.consent.userStorageKeyAttribute= %{idp.persistentId.sourceAttribute}\nidp.consent.allowGlobal= false\nidp.consent.compareValues= true\nidp.consent.maxStoredRecords= -1\nidp.ui.fallbackLanguages= en,de,fr\nEOF\n\necho \"==============> Running the installer\"\n\n# run the installer\nSRCDIR=$(pwd)\n\nbash bin/install.sh \\\n-Didp.relying.party.present= \\\n-Didp.src.dir=. \\\n-Didp.target.dir=$INSTALLDIR \\\n-Didp.merge.properties=temp.properties \\\n-Didp.sealer.password=$(cut -d \" \" -f3 <credentials.properties) \\\n-Didp.keystore.password= \\\n-Didp.conf.filemode=644 \\\n-Didp.host.name=$SITENAME \\\n-Didp.scope=$SITENAME\n\nchown -R tomcat8 /opt/shibboleth-idp/\n\n#edit all location's port 8443 /opt/shibboleth-idp/metadata/idp.metadata\necho \"==============> Updating the urls in metadata.xml\"\n\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/Shibboleth/SSO,https://'\"$SITENAME\"':8443/idp/profile/Shibboleth/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/POST/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/POST/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/POST-SimpleSign/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/POST-SimpleSign/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\nsed -i -e 's,https://'\"$SITENAME\"'/idp/profile/SAML2/Redirect/SSO,https://'\"$SITENAME\"':8443/idp/profile/SAML2/Redirect/SSO,g' /opt/shibboleth-idp/metadata/idp-metadata.xml\n\n# Use context deployment fragment for deploying idp.war file\necho \"==============> Adding application to tomcat8\"\n\necho \"<Context docBase=\\\"/opt/shibboleth-idp/war/idp.war\\\" privileged=\\\"true\\\" antiresourcelocking=\\\"false\\\" antijarlocking=\\\"false\\\" unpackwar=\\\"false\\\" swallowoutput=\\\"true\\\" />\" > /var/lib/tomcat8/conf/Catalina/localhost/idp.xml\nmv credentials.properties $INSTALLDIR/conf\n\necho -e \"\\nCreating self-signed certificate...\"\nbin/keygen.sh --lifetime 3 \\\n--certfile $INSTALLDIR/credentials/idp.crt \\\n--keyfile $INSTALLDIR/credentials/idp.key \\\n--hostname $SITENAME \\\n--uriAltName https://$SITENAME/idp/shibboleth\necho ...done\nchmod 600 $INSTALLDIR/credentials/idp.key\n\n# set owner of key file and directories\ngetent passwd tomcat8 >/dev/null && TCUSER=tomcat8 || TCUSER=tomcat\nchown $TCUSER $INSTALLDIR/credentials/idp.key\nchown $TCUSER $INSTALLDIR/credentials/sealer.*\nchown $TCUSER $INSTALLDIR/metadata\nchown $TCUSER $INSTALLDIR/logs\nchown $TCUSER $INSTALLDIR/conf/credentials.properties\n\n#allow access to public\nsed -i -e \"s~'::1/128'~'::1/128', '0.0.0.0/0'~g\" /opt/shibboleth-idp/conf/access-control.xml\n\n#restart tomcat\nservice tomcat8 restart", "num_lines": 158}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements.  See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License.  You may obtain a copy of the License at\n#\n#    http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This script will obtain the Solace message broker's docker image from\n# sources and installs and runs it in a docker container\n# solace_uri specifies where to get the docker image from\n# - default (not specified): PubSub+ Standard from docker hub\n# - Other public docker registry URI\n# - solace.com/download\n# - specified location of a docker image tarball URL\n#\n\n\n\nOPTIND=1         # Reset in case getopts has been used previously in the shell.\n\n# Initialize our own variables:\ncurrent_index=\"\"\ndns_prefix=\"\"\nnumber_of_instances=\"\"\nsolace_directory=\"/tmp\"\nsolace_uri=\"solace/solace-pubsub-standard:latest\"   # default to pull latest PubSub+ standard from docker hub\nadmin_password_file=\"\"\ndisk_size=\"\"\nworkspace_id=\"\"\nis_primary=\"false\"\nmax_connections=\"100\"\nmax_queue_messages=\"100\"\nwhile getopts \"c:d:i:p:s:w:u:n:q:\" opt; do\n  case \"$opt\" in\n  c)  current_index=$OPTARG\n    ;;\n  d)  dns_prefix=$OPTARG\n    ;;\n  i)  number_of_instances=$OPTARG\n    ;;\n  p)  admin_password_file=$OPTARG\n    ;;\n  s)  disk_size=$OPTARG\n    ;;\n  u)  solace_uri=$OPTARG\n    ;;\n  w)  workspace_id=$OPTARG\n    ;;\n  n)  max_connections=$OPTARG\n    ;;\n  q)  max_queue_messages=$OPTARG\n    ;;\n  esac\ndone\n\nshift $((OPTIND-1))\n[ \"$1\" = \"--\" ] && shift\n\necho \"`date` current_index=$current_index , dns_prefix=$dns_prefix , number_of_instances=$number_of_instances , \\\n      password_file=$admin_password_file , disk_size=$disk_size , workspace_id=$workspace_id , solace_uri=$solace_uri, max_connections=$max_connections, max_queue_messages=$max_queue_messages, \\\n      Leftovers: $@\"\nexport admin_password=`cat ${admin_password_file}`\n\n# Create working dir if needed\nmkdir -p ${solace_directory}\n\n#Install the logical volume manager and jq for json parsing\nyum -y install lvm2\nyum -y install epel-release\nyum -y install jq\n\necho \"`date` INFO: RETRIEVE SOLACE DOCKER IMAGE\"\necho \"###############################################################\"\n# Determine first if solace_uri is a valid docker registry uri\n## First make sure Docker is actually up\ndocker_running=\"\"\nloop_guard=20\nloop_count=0\nwhile [ ${loop_count} != ${loop_guard} ]; do\n  docker_running=`service docker status | grep -o running`\n  if [ ${docker_running} != \"running\" ]; then\n    ((loop_count++))\n    echo \"`date` WARN: Tried to launch Solace but Docker in state ${docker_running}\"\n    sleep 5\n  elif ! docker ps | grep IMAGE; then\n    ((loop_count++))\n    echo \"`date` WARN: Docker is not ready yet - trial count: ${loop_count}\"\n    sleep 5\n  else\n    echo \"`date` INFO: Docker in state ${docker_running}\"\n    break\n  fi\ndone\nif [ ${loop_count} == ${loop_guard} ]; then\n  echo \"`date` ERROR: Docker failed to start on VM, exiting\" | tee /dev/stderr\n  exit 1\nfi\n\n## Remove any existing solace image\nif [ \"`docker images | grep solace-`\" ] ; then\n  echo \"`date` INFO: Removing existing Solace images from local docker repo\"\n  docker rmi -f `docker images | grep solace- | awk '{print $3}'`\nfi\n## Try to load solace_uri as a docker registry uri\necho \"`date` Testing ${solace_uri} for docker registry uri:\"\nif [ -z \"`docker pull ${solace_uri}`\" ] ; then\n  # If NOT in this branch then load was successful\n  echo \"`date` INFO: Found that ${solace_uri} was not a docker registry uri, retrying if it is a download link\"\n  if [[ ${solace_uri} == *\"solace.com/download\"* ]]; then\n    REAL_LINK=${solace_uri}\n    # the new download url\n    wget -O ${solace_directory}/solos.info -nv  ${solace_uri}_MD5\n  else\n    REAL_LINK=${solace_uri}\n    # an already-existing load (plus its md5 file) hosted somewhere else (e.g. in an s3 bucket)\n    wget -O ${solace_directory}/solos.info -nv  ${solace_uri}.md5\n  fi\n  IFS=' ' read -ra SOLOS_INFO <<< `cat ${solace_directory}/solos.info`\n  MD5_SUM=${SOLOS_INFO[0]}\n  SolOS_LOAD=${SOLOS_INFO[1]}\n  if [ -z ${MD5_SUM} ]; then\n    echo \"`date` ERROR: Missing md5sum for the Solace load - exiting.\" | tee /dev/stderr\n    exit 1\n  fi\n  echo \"`date` INFO: Reference md5sum is: ${MD5_SUM}\"\n\n  echo \"`date` INFO: Now download from URL provided and validate, trying up to 5 times\"\n  LOOP_COUNT=0\n  while [ $LOOP_COUNT -lt 5 ]; do\n    wget -q -O  ${solace_directory}/${SolOS_LOAD} ${REAL_LINK} || echo \"There has been an issue with downloading the Solace load\"\n    ## Check MD5\n    LOCAL_OS_INFO=`md5sum ${solace_directory}/${SolOS_LOAD}`\n    IFS=' ' read -ra SOLOS_INFO <<< ${LOCAL_OS_INFO}\n    LOCAL_MD5_SUM=${SOLOS_INFO[0]}\n    if [ -z \"${MD5_SUM}\" ] || [ \"${LOCAL_MD5_SUM}\" != \"${MD5_SUM}\" ]; then\n      echo \"`date` WARN: Possible corrupt Solace load, md5sum do not match\"\n    else\n      echo \"`date` INFO: Successfully downloaded ${SolOS_LOAD}\"\n      break\n    fi\n    ((LOOP_COUNT++))\n  done\n  if [ ${LOOP_COUNT} == 3 ]; then\n    echo \"`date` ERROR: Failed to download the Solace load, exiting\" | tee /dev/stderr\n    exit 1\n  else\n    echo \"`date` INFO: Successfully downloaded ${SolOS_LOAD}\"\n  fi\n  ## Load the image tarball\n  docker load -i ${solace_directory}/${SolOS_LOAD}\nfi\n## Image details\nexport SOLACE_IMAGE_ID=`docker images | grep solace | awk '{print $3}'`\nif [ -z \"${SOLACE_IMAGE_ID}\" ] ; then\n  echo \"`date` ERROR: Could not load a valid Solace docker image - exiting.\" | tee /dev/stderr\n  exit 1\nfi\necho \"`date` INFO: Successfully loaded ${solace_uri} to local docker repo\"\necho \"`date` INFO: Solace message broker image and tag: `docker images | grep solace | awk '{print $1,\":\",$2}'`\"\n\n# Common for all scalings\nshmsize=\"1g\"\nulimit_nofile=\"2448:422192\"\nSWAP_SIZE=\"2048\"\necho \"`date` INFO: Using shmsize: ${shmsize}, ulimit_nofile: ${ulimit_nofile}, SWAP_SIZE: ${SWAP_SIZE}\"\n\necho \"`date` INFO: Creating Swap space\"\nmkdir /var/lib/solace\ndd if=/dev/zero of=/var/lib/solace/swap count=${SWAP_SIZE} bs=1MiB\nmkswap -f /var/lib/solace/swap\nchmod 0600 /var/lib/solace/swap\nswapon -f /var/lib/solace/swap\ngrep -q 'solace\\/swap' /etc/fstab || sudo sh -c 'echo \"/var/lib/solace/swap none swap sw 0 0\" >> /etc/fstab'\n\necho \"`date` INFO: Applying TCP for WAN optimizations\"\necho '\n  net.core.rmem_max = 134217728\n  net.core.wmem_max = 134217728\n  net.ipv4.tcp_rmem = 4096 25165824 67108864\n  net.ipv4.tcp_wmem = 4096 25165824 67108864\n  net.ipv4.tcp_mtu_probing=1' | sudo tee /etc/sysctl.d/98-solace-sysctl.conf\nsudo sysctl -p /etc/sysctl.d/98-solace-sysctl.conf\n\nif [ ${number_of_instances} -gt 1 ]; then\n  echo \"`date` INFO: Configuring HA tuple\"\n  case ${current_index} in\n    0 )\n      redundancy_config=\"\\\n      --env nodetype=message_routing \\\n      --env routername=${dns_prefix}primary \\\n      --env redundancy_activestandbyrole=primary \\\n      --env redundancy_matelink_connectvia=${dns_prefix}1 \\\n      --env redundancy_authentication_presharedkey_key=$(cat ${admin_password_file} | awk '{x=$0;for(i=length;i<51;i++)x=x \"0\";}END{print x}' | base64) \\\n      --env redundancy_enable=yes \\\n      --env redundancy_group_node_${dns_prefix}primary_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}primary_connectvia=${dns_prefix}0 \\\n      --env redundancy_group_node_${dns_prefix}backup_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}backup_connectvia=${dns_prefix}1 \\\n      --env redundancy_group_node_${dns_prefix}monitor_nodetype=monitoring \\\n      --env redundancy_group_node_${dns_prefix}monitor_connectvia=${dns_prefix}2 \\\n      --env configsync_enable=yes\"\n      is_primary=\"true\"\n        ;;\n    1 )\n      redundancy_config=\"\\\n      --env nodetype=message_routing \\\n      --env routername=${dns_prefix}backup \\\n      --env redundancy_matelink_connectvia=${dns_prefix}0 \\\n      --env redundancy_activestandbyrole=backup \\\n      --env redundancy_authentication_presharedkey_key=$(cat ${admin_password_file} | awk '{x=$0;for(i=length;i<51;i++)x=x \"0\";}END{print x}' | base64) \\\n      --env redundancy_enable=yes \\\n      --env redundancy_group_node_${dns_prefix}primary_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}primary_connectvia=${dns_prefix}0 \\\n      --env redundancy_group_node_${dns_prefix}backup_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}backup_connectvia=${dns_prefix}1 \\\n      --env redundancy_group_node_${dns_prefix}monitor_nodetype=monitoring \\\n      --env redundancy_group_node_${dns_prefix}monitor_connectvia=${dns_prefix}2 \\\n      --env configsync_enable=yes\"\n        ;;\n    2 )\n      redundancy_config=\"\\\n      --env nodetype=monitoring \\\n      --env routername=${dns_prefix}monitor \\\n      --env redundancy_authentication_presharedkey_key=$(cat ${admin_password_file} | awk '{x=$0;for(i=length;i<51;i++)x=x \"0\";}END{print x}' | base64) \\\n      --env redundancy_enable=yes \\\n      --env redundancy_group_node_${dns_prefix}primary_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}primary_connectvia=${dns_prefix}0 \\\n      --env redundancy_group_node_${dns_prefix}backup_nodetype=message_routing \\\n      --env redundancy_group_node_${dns_prefix}backup_connectvia=${dns_prefix}1 \\\n      --env redundancy_group_node_${dns_prefix}monitor_nodetype=monitoring \\\n      --env redundancy_group_node_${dns_prefix}monitor_connectvia=${dns_prefix}2\"\n        ;;\n  esac\nelse\n  echo \"`date` INFO: Configuring singleton\"\n  redundancy_config=\"\"\nfi\n\n# Setup password file permissions\nchown -R 1000001 $(dirname ${admin_password_file})\nchmod 700 $(dirname ${admin_password_file})\n\nif [[ ${disk_size} == \"0\" ]]; then\n  echo \"`date` Using ephemeral volumes\"\n  #Create new volumes that the PubSub+ Message Broker container can use to consume and store data.\n  docker volume create --name=jail\n  docker volume create --name=var\n  docker volume create --name=adb\n  docker volume create --name=softAdb\n  docker volume create --name=diagnostics\n  docker volume create --name=internalSpool\n  SPOOL_MOUNT=\"-v jail:/usr/sw/jail -v var:/usr/sw/var -v softAdb:/usr/sw/internalSpool/softAdb -v adb:/usr/sw/adb -v diagnostics:/var/lib/solace/diags -v internalSpool:/usr/sw/internalSpool\"\nelse\n  echo \"`date` Using persistent volumes\"\n  # Look for unpartitioned disks\n  disk_volume=\"\"\n  DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n  for DEV in \"${DEVS[@]}\"; do\n    # Check each device if there is a \"1\" partition.\n    # If not, assume it is not partitioned.\n    if [ ! -b ${DEV}1 ]; then\n      echo \"`date` INFO: Disk device with no primary partition found\"\n      disk_volume=\"${DEV}\"\n      break\n    fi\n  done\n  if [[ ${disk_volume} == \"\" ]]; then\n    echo \"`date` INFO: Default disk device to /dev/sdc\"\n    disk_volume=\"/dev/sdc\"\n  fi\n  echo \"`date` INFO: Create primary partition on disk device ${disk_volume} of size ${disk_size} GiB\"\n  (\n    echo n # Add a new partition\n    echo p # Primary partition\n    echo 1 # Partition number\n    echo   # First sector (Accept default: 1)\n    echo   # Last sector (Accept default: varies)\n    echo w # Write changes\n  ) | sudo fdisk $disk_volume\n  mkfs.xfs  ${disk_volume}1 -m crc=0\n  UUID=`blkid -s UUID -o value ${disk_volume}1`\n  echo \"UUID=${UUID} /opt/pubsubplus xfs defaults 0 0\" >> /etc/fstab\n  mkdir /opt/pubsubplus\n  mount -a\n  mkdir /opt/pubsubplus/jail\n  mkdir /opt/pubsubplus/var\n  mkdir /opt/pubsubplus/adb\n  mkdir /opt/pubsubplus/softAdb\n  mkdir /opt/pubsubplus/diagnostics\n  mkdir /opt/pubsubplus/internalSpool\n  chown 1000001 -R /opt/pubsubplus/\n  #chmod -R 777 /opt/pubsubplus\n  SPOOL_MOUNT=\"-v /opt/pubsubplus/jail:/usr/sw/jail -v /opt/pubsubplus/var:/usr/sw/var -v /opt/pubsubplus/adb:/usr/sw/adb -v /opt/pubsubplus/softAdb:/usr/sw/internalSpool/softAdb -v /opt/pubsubplus/diagnostics:/var/lib/solace/diags -v /opt/pubsubplus/internalSpool:/usr/sw/internalSpool\"\nfi\n\nLOG_OPT=\"\"\nlogging_config=\"\"\nif [[ ${workspace_id} != \"\" ]]; then\n  SYSLOG_CONF=\"/etc/opt/microsoft/omsagent/${workspace_id}/conf/omsagent.d/syslog.conf\"\n  SYSLOG_PORT=\"\"\n  if [ -f ${SYSLOG_CONF} ]; then\n    echo \"`date` INFO: Configuration file for syslog found\"\n    SYSLOG_PORT=$(sed -n 's/.*port \\(.*\\).*/\\1/p' $SYSLOG_CONF)\n  fi\n  if [[ ${SYSLOG_PORT} == \"\" ]]; then\n    echo \"`date` INFO: Default syslog port to 25224\"\n    SYSLOG_PORT=\"25224\"\n  fi\n  echo \"`date` INFO: Configuring logging on syslog port ${SYSLOG_PORT}\"\n  LOG_OPT=\"--log-driver syslog --log-opt syslog-format=rfc3164 --log-opt syslog-address=udp://127.0.0.1:$SYSLOG_PORT\"\n  logging_config=\"\\\n    --env logging_debug_output=all \\\n    --env logging_debug_format=graylog \\\n    --env logging_command_output=all \\\n    --env logging_command_format=graylog \\\n    --env logging_system_output=all \\\n    --env logging_system_format=graylog \\\n    --env logging_event_output=all \\\n    --env logging_event_format=graylog \\\n    --env logging_kernel_output=all \\\n    --env logging_kernel_format=graylog\"\nfi\n\n#Define a create script\ntee /root/docker-create <<-EOF\n#!/bin/bash\ndocker create \\\n  --privileged=false \\\n  --net=host \\\n  --uts=host \\\n  --shm-size=${shmsize} \\\n  --ulimit core=-1 \\\n  --ulimit memlock=-1 \\\n  --ulimit nofile=${ulimit_nofile} \\\n  ${LOG_OPT} \\\n  -v $(dirname ${admin_password_file}):/run/secrets \\\n  ${SPOOL_MOUNT} \\\n  --env username_admin_globalaccesslevel=admin \\\n  --env username_admin_passwordfilepath=$(basename ${admin_password_file}) \\\n  --env \"service_ssh_port=2222\" \\\n  --env \"service_webtransport_port=8008\" \\\n  --env \"service_webtransport_tlsport=1443\" \\\n  --env \"service_semp_tlsport=1943\" \\\n  --env \"system_scaling_maxconnectioncount=${max_connections}\" \\\n  --env \"system_scaling_maxqueuemessagecount=${max_queue_messages}\" \\\n  ${logging_config} \\\n  ${redundancy_config} \\\n  --name=solace ${SOLACE_IMAGE_ID}\nEOF\n\n#Make the file executable\nchmod +x /root/docker-create\n\necho \"`date` INFO: Creating the Solace container\"\n/root/docker-create\n\n#Construct systemd for PubSub+ Message Broker\ntee /etc/systemd/system/solace-pubsubplus.service <<-EOF\n[Unit]\n  Description=solace-pubsubplus\n  Requires=docker.service\n  After=docker.service\n[Service]\n  Restart=always\n  ExecStart=/usr/bin/docker start -a solace\n  ExecStop=/usr/bin/docker stop solace\n[Install]\n  WantedBy=default.target\nEOF\n\necho \"`date` INFO: Start the Solace PubSub+ Message Broker container\"\nsystemctl daemon-reload\nsystemctl enable solace-pubsubplus\nsystemctl start solace-pubsubplus\n\n# Poll the PubSub+ Message Broker SEMP port until it is Up\nloop_guard=30\npause=10\ncount=0\necho \"`date` INFO: Wait for the Solace SEMP service to be enabled\"\nwhile [ ${count} -lt ${loop_guard} ]; do\n  online_results=`./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n    -q \"<rpc><show><service/></show></rpc>\" \\\n    -v \"/rpc-reply/rpc/show/service/services/service[name='SEMP']/enabled[text()]\"`\n\n  is_messagebroker_up=`echo ${online_results} | jq '.valueSearchResult' -`\n  echo \"`date` INFO: SEMP service 'enabled' status is: ${is_messagebroker_up}\"\n\n  run_time=$((${count} * ${pause}))\n  if [ \"${is_messagebroker_up}\" = \"\\\"true\\\"\" ]; then\n    echo \"`date` INFO: Solace message broker SEMP service is up, after ${run_time} seconds\"\n    break\n  fi\n  ((count++))\n  echo \"`date` INFO: Waited ${run_time} seconds, Solace message broker SEMP service not yet up\"\n  sleep ${pause}\ndone\n\n# Remove all VMR Secrets from the host; at this point, the VMR should have come up\n# and it won't be needing those files anymore\nrm ${admin_password_file}\n\n# Poll the redundancy status on the Primary VMR\nif [ \"${is_primary}\" = \"true\" ]; then\n  loop_guard=30\n  pause=10\n  count=0\n  mate_active_check=\"\"\n  echo \"`date` INFO: Wait for Primary to be 'Local Active' or 'Mate Active'\"\n  while [ ${count} -lt ${loop_guard} ]; do\n    online_results=`./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n        -q \"<rpc><show><redundancy><detail/></redundancy></show></rpc>\" \\\n        -v \"/rpc-reply/rpc/show/redundancy/virtual-routers/primary/status/activity[text()]\"`\n\n    local_activity=`echo ${online_results} | jq '.valueSearchResult' -`\n    echo \"`date` INFO: Local activity state is: ${local_activity}\"\n\n    run_time=$((${count} * ${pause}))\n    case \"${local_activity}\" in\n      \"\\\"Local Active\\\"\")\n        echo \"`date` INFO: Redundancy is up locally, Primary Active, after ${run_time} seconds\"\n        mate_active_check=\"Standby\"\n        break\n        ;;\n      \"\\\"Mate Active\\\"\")\n        echo \"`date` INFO: Redundancy is up locally, Backup Active, after ${run_time} seconds\"\n        mate_active_check=\"Active\"\n        break\n        ;;\n    esac\n    ((count++))\n    echo \"`date` INFO: Waited ${run_time} seconds, Redundancy not yet up\"\n    sleep ${pause}\n  done\n\n  if [ ${count} -eq ${loop_guard} ]; then\n    echo \"`date` ERROR: Solace redundancy group never came up\" | tee /dev/stderr\n    echo \"`date` ERROR: giving up! Details:\"\n    echo `curl -u admin:${admin_password} http://localhost:8080/SEMP -d \"<rpc><show><redundancy><detail/></redundancy></show></rpc>\"`\n    exit 1\n  fi\n\n  loop_guard=45\n  pause=10\n  count=0\n  echo \"`date` INFO: Wait for Backup to be 'Active' or 'Standby'\"\n  while [ ${count} -lt ${loop_guard} ]; do\n    online_results=`./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n        -q \"<rpc><show><redundancy><detail/></redundancy></show></rpc>\" \\\n        -v \"/rpc-reply/rpc/show/redundancy/virtual-routers/primary/status/detail/priority-reported-by-mate/summary[text()]\"`\n\n    mate_activity=`echo ${online_results} | jq '.valueSearchResult' -`\n    echo \"`date` INFO: Mate activity state is: ${mate_activity}\"\n\n    run_time=$((${count} * ${pause}))\n    case \"${mate_activity}\" in\n      \"\\\"Active\\\"\")\n        echo \"`date` INFO: Redundancy is up end-to-end, Backup Active, after ${run_time} seconds\"\n        mate_active_check=\"Standby\"\n        break\n        ;;\n      \"\\\"Standby\\\"\")\n        echo \"`date` INFO: Redundancy is up end-to-end, Primary Active, after ${run_time} seconds\"\n        mate_active_check=\"Active\"\n        break\n        ;;\n    esac\n    ((count++))\n    echo \"`date` INFO: Waited ${run_time} seconds, Backup not yet 'Active' or 'Standby'\"\n    sleep ${pause}\n  done\n\n  if [ ${count} -eq ${loop_guard} ]; then\n    echo \"`date` ERROR: Backup never became 'Active' or 'Standby'\" | tee /dev/stderr\n    echo \"`date` ERROR: giving up! Details:\"\n    echo `curl -u admin:${admin_password} http://localhost:8080/SEMP -d \"<rpc><show><redundancy><detail/></redundancy></show></rpc>\"`\n    exit 1\n  fi\n\n  echo \"`date` INFO: Initiating config-sync for router\"\n  ./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n    -q \"<rpc semp-version=\\\"soltr/9_8VMR\\\"><admin><config-sync><assert-master><router/></assert-master></config-sync></admin></rpc>\"\n  echo \"`date` INFO: Initiating config-sync for default vpn\"\n  ./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n    -q \"<rpc semp-version=\\\"soltr/9_8VMR\\\"><admin><config-sync><assert-master><vpn-name>*</vpn-name></assert-master></config-sync></admin></rpc>\"\n  \n  # Wait for config-sync results\n  count=0\n  echo \"`date` INFO: Waiting for config-sync connected\"\n  while [ ${count} -lt ${loop_guard} ]; do\n    online_results=`./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n            -q \"<rpc><show><config-sync></config-sync></show></rpc>\" \\\n            -v \"/rpc-reply/rpc/show/config-sync/status/oper-status\"`\n    \n    confsyncstatus_results=`echo ${online_results} | jq '.valueSearchResult' -`\n    echo \"`date` INFO: Config-sync is: ${confsyncstatus_results}\"\n  \n    run_time=$((${count} * ${pause}))\n    case \"${confsyncstatus_results}\" in\n      \"\\\"Up\\\"\")\n        echo \"`date` INFO: Config-sync is Up, after ${run_time} seconds\"\n        break\n        ;;\n    esac\n    ((count++))\n    echo \"`date` INFO: Waited ${run_time} seconds, Config-sync is not yet Up\"\n\n    if (( $count % 18 == 0 )) ; then\n      echo \"`date` INFO: Re-trying initiate config-sync for router\"\n      ./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n              -q \"<rpc semp-version=\\\"soltr/9_8VMR\\\"><admin><config-sync><assert-master><router/></assert-master></config-sync></admin></rpc>\"\n      ./semp_query.sh -n admin -p ${admin_password} -u http://localhost:8080/SEMP \\\n              -q \"<rpc semp-version=\\\"soltr/9_8VMR\\\"><admin><config-sync><assert-master><vpn-name>default</vpn-name></assert-master></config-sync></admin></rpc>\"\n    fi\n\n    sleep ${pause}\n  done\n  \n  if [ ${count} -eq ${loop_guard} ]; then\n    echo \"`date` ERROR: Config-sync never reached state \\\"Up\\\" - exiting.\" | tee /dev/stderr\n    exit 1\n  fi\n  \nfi\n\nif [ ${count} -eq ${loop_guard} ]; then\n  echo \"`date` ERROR: Solace bringup failed\" | tee /dev/stderr\n  exit 1\nfi\necho \"`date` INFO: Solace bringup complete\"\n", "num_lines": 541}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nOPTIND=1         # Reset in case getopts has been used previously in the shell.\n\n# Initialize our own variables:\ncount_search=\"\"\nname=\"\"\npassword=\"\"\nquery=\"\"\nurl=\"\"\nvalue_search=\"\"\n\nscript_name=$0\n\nwhile getopts \"c:n:p:q:u:v:\" opt; do\n  case \"$opt\" in\n  c)  count_search=$OPTARG\n    ;;\n  n)  name=$OPTARG\n    ;;\n  p)  password=$OPTARG\n    ;;\n  q)  query=$OPTARG\n    ;;\n  u)  url=$OPTARG\n    ;;\n  v)  value_search=$OPTARG\n    ;;\n  esac\ndone\n\nshift $((OPTIND-1))\n[ \"$1\" = \"--\" ] && shift\n\n#echo \"`date` INFO:${script_name}: count_search=${count_search} ,name=${name} ,password=xxx query=${query} \\\n#             ,url=${url} ,value_search=${value_search} ,Leftovers: $@\" >&2\n\nif [[ ${url} = \"\" || ${name} = \"\" || ${password} = \"\" || ${query} = \"\" ]]; then\n  echo \"`date` ERROR:${script_name}: url, name, password and query are madatory fields\" >&2\n  echo  \"{\\\"errorInfo\\\":\\\"missing parameter\\\"}\"\n  exit 1\nfi\nif [ `curl --write-out '%{http_code}' --silent --output /dev/null -u ${name}:${password} ${url} -d \"<rpc><show><version/></show></rpc>\"` != \"200\" ] ; then\n  echo  \"{\\\"errorInfo\\\":\\\"management host is not responding\\\"}\"\n  exit 1\nfi\n\nquery_response=`curl -sS -u ${name}:${password} ${url} -d \"${query}\"`\n# Validate first char of response is \"<\", otherwise no hope of being valid xml\nif [[ ${query_response:0:1} != \"<\" ]] ; then\n  echo  \"{\\\"errorInfo\\\":\\\"no valid xml returned\\\"}\"\n  exit 1\nfi\nquery_response_code=`echo $query_response | xmllint -xpath 'string(/rpc-reply/execute-result/@code)' -`\n\nif [[ -z ${query_response_code} && ${query_response_code} != \"ok\" ]]; then\n  echo  \"{\\\"errorInfo\\\":\\\"query failed -${query_response_code}-\\\"}\"\n  exit 1\nfi\n\n#echo \"`date` INFO:${script_name}: Query passed ${query_response_code}\" >&2\n\nif [[ ! -z $value_search ]]; then\n  value_result=`echo $query_response | xmllint -xpath \"string($value_search)\" -`\n  echo  \"{\\\"errorInfo\\\":\\\"\\\",\\\"valueSearchResult\\\":\\\"${value_result}\\\"}\"\n  exit 0\nfi\n\nif [[ ! -z $count_search ]]; then\n  count_line=`echo $query_response | xmllint -xpath \"$count_search\" -`\n  count_string=`echo $count_search | cut -d '\"' -f 2`\n  count_result=`echo ${count_line} | tr \"><\" \"\\n\" | grep -c ${count_string}`\n  echo  \"{\\\"errorInfo\\\":\\\"\\\",\\\"countSearchResult\\\":${count_result}}\"\n  exit 0\nfi\n", "num_lines": 76}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Import the helper method module.\nwget -O /tmp/HDInsightUtilities-v01.sh -q https://hdiconfigactions.blob.core.windows.net/linuxconfigactionmodulev01/HDInsightUtilities-v01.sh && source /tmp/HDInsightUtilities-v01.sh && rm -f /tmp/HDInsightUtilities-v01.sh\n\n# Check if the current  host is headnode.\nif [ `test_is_headnode` == 0 ]; then\n  echo  \"Spark on YARN only need to be installed on headnode, exiting ...\"\n  exit 0\nfi\n\n# In case Spark is installed, exit.\nif [ -e /usr/hdp/current/spark ]; then\n    echo \"Spark is already installed, exiting ...\"\n    exit 0\nfi\n\n# Add HADOOP environment variable into machine level configuration.\necho \"HADOOP_CONF_DIR=/etc/hadoop/conf\" | sudo tee -a /etc/environment\necho \"YARN_CONF_DIR=/etc/hadoop/conf\" | sudo tee -a /etc/environment\n\n# Add SPARK_HOME environment variable for supporting application requirments (ADAM)\necho \"SPARK_HOME=/usr/hdp/current/spark\" | sudo tee -a /etc/environment\n\n# Add SPARK bin directory to PATH variable\n\necho \"export PATH=$PATH:/usr/hdp/current/spark/bin\" | sudo tee -a /etc/profile\necho \"export PATH=$PATH:/usr/hdp/current/spark/bin\" | sudo tee -a /root/.profile\n\n# Download Spark binary to temporary location.\ndownload_file http://d3kbcqa49mib13.cloudfront.net/spark-1.4.1-bin-hadoop2.6.tgz /tmp/spark-1.4.1-bin-hadoop2.6.tgz\n\n# Untar the Spark binary and move it to proper location.\nuntar_file /tmp/spark-1.4.1-bin-hadoop2.6.tgz /usr/hdp/current\nmv /usr/hdp/current/spark-1.4.1-bin-hadoop2.6 /usr/hdp/current/spark\n\n# Remove the temporary file downloaded.\nrm -f /tmp/spark-1.4.1-bin-hadoop2.6.tgz\n\n# Update/link files/variables necessary to make Spark work on HDInsight.\n\necho \"SPARK_DIST_CLASSPATH=$(hadoop classpath)\" | sudo tee -a /etc/environment\nln -s /etc/hive/conf/hive-site.xml /usr/hdp/current/spark/conf\n\n#Determine Hortonworks Data Platform version\nHDP_VERSION=`ls /usr/hdp/ -I current`\n\n#Assign java options to support Spark\nSparkDriverJavaOpts=\"spark.driver.extraJavaOptions -Dhdp.version=$HDP_VERSION\"\nSparkYarnJavaOpts=\"spark.yarn.am.extraJavaOptions -Dhdp.version=$HDP_VERSION\"\n\n#Create file and update with default values\nSparkDefaults=\"/tmp/spark-defaults.conf\"\necho $SparkDriverJavaOpts >> $SparkDefaults\necho $SparkYarnJavaOpts >> $SparkDefaults\ntouch $SparkDefaults\n\n#Move to final destination\nmv $SparkDefaults /usr/hdp/current/spark/conf/spark-defaults.conf\n\n\n", "num_lines": 60}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Import the helper method module.\nwget -O /tmp/HDInsightUtilities-v01.sh -q https://hdiconfigactions.blob.core.windows.net/linuxconfigactionmodulev01/HDInsightUtilities-v01.sh && source /tmp/HDInsightUtilities-v01.sh && rm -f /tmp/HDInsightUtilities-v01.sh\n\n# Check if the current  host is headnode.\nif [ `test_is_headnode` == 0 ]; then\n  echo  \"Spark on YARN only need to be installed on headnode, exiting ...\"\n  exit 0\nfi\n\n# In case Spark is installed, exit.\nif [ -e /usr/hdp/current/spark ]; then\n    echo \"Spark is already installed, exiting ...\"\n    exit 0\nfi\n\n# Add HADOOP environment variable into machine level configuration.\necho \"HADOOP_CONF_DIR=/etc/hadoop/conf\" | sudo tee -a /etc/environment\necho \"YARN_CONF_DIR=/etc/hadoop/conf\" | sudo tee -a /etc/environment\n\n# Add SPARK_HOME environment variable for supporting application requirments (ADAM)\necho \"SPARK_HOME=/usr/hdp/current/spark\" | sudo tee -a /etc/environment\n\n# Add SPARK bin directory to PATH variable\n\n#echo \"export PATH=$PATH:/usr/hdp/current/spark/bin\" | sudo tee -a /etc/profile\n#echo \"export PATH=$PATH:/usr/hdp/current/spark/bin\" | sudo tee -a /root/.profile\n\n# Download Spark binary to temporary location.\ndownload_file http://d3kbcqa49mib13.cloudfront.net/spark-1.4.1-bin-hadoop2.6.tgz /tmp/spark-1.4.1-bin-hadoop2.6.tgz\n\n# Untar the Spark binary and move it to proper location.\nuntar_file /tmp/spark-1.4.1-bin-hadoop2.6.tgz /usr/hdp/current\nmv /usr/hdp/current/spark-1.4.1-bin-hadoop2.6 /usr/hdp/current/spark\n\n# Remove the temporary file downloaded.\nrm -f /tmp/spark-1.4.1-bin-hadoop2.6.tgz\n\n# Update variables/files to make Spark work on HDInsight.\necho \"SPARK_DIST_CLASSPATH=$(hadoop classpath)\" | sudo tee -a /etc/environment\nln -s /etc/hive/conf/hive-site.xml /usr/hdp/current/spark/conf\n\n\n#Determine Hortonworks Data Platform version\nHDP_VERSION=`ls /usr/hdp/ -I current`\n\n#Assign java options to support Spark\nSparkDriverJavaOpts=\"spark.driver.extraJavaOptions -Dhdp.version=$HDP_VERSION\"\nSparkYarnJavaOpts=\"spark.yarn.am.extraJavaOptions -Dhdp.version=$HDP_VERSION\"\n\n#Create file and update with default values\nSparkDefaults=\"/tmp/spark-defaults.conf\"\necho $SparkDriverJavaOpts >> $SparkDefaults\necho $SparkYarnJavaOpts >> $SparkDefaults\ntouch $SparkDefaults\n\n#Move to final destination\nmv $SparkDefaults /usr/hdp/current/spark/conf/spark-defaults.conf\n\n\n#Install Maven in preperation for ADAM\n\ndownload_file http://mirror.olnevhost.net/pub/apache/maven/maven-3/3.3.3/binaries/apache-maven-3.3.3-bin.tar.gz /tmp/apache-maven-3.3.3-bin.tar.gz\nuntar_file /tmp/apache-maven-3.3.3-bin.tar.gz /tmp\nmv /tmp/apache-maven-3.3.3 /maven\n\n#Install Git and GeneTorrent Download common packages in preperation for ADAM\napt-get install -y git libboost-filesystem1.48.0 libboost-program-options1.48.0 libboost-regex1.48.0 libboost-system1.48.0 libicu48 libxerces-c3.1 libxqilla6\ndownload_file https://cghub.ucsc.edu/software/downloads/GeneTorrent/3.8.7/GeneTorrent-download-3.8.7-207-Ubuntu12.04.x86_64.tar.gz /tmp/GeneTorrent-download-3.8.7-207-Ubuntu12.04.x86_64.tar.gz\nuntar_file /tmp/GeneTorrent-download-3.8.7-207-Ubuntu12.04.x86_64.tar.gz /tmp\nmv /tmp/cghub /cghub\n\n#Install ADAM\n#echo \"export PATH=$PATH:/usr/hdp/current/spark/bin:/maven/bin:/adam/bin\"\ncd /\ngit clone https://github.com/bigdatagenomics/adam.git\ncd adam\nexport \"MAVEN_OPTS=-Xmx512m -XX:MaxPermSize=128m\"\n/maven/bin/mvn clean package -DskipTests\n\n#Update Environment Variables\necho \"export PATH=$PATH:/usr/hdp/current/spark/bin:/maven/bin:/adam/bin:/cghub/bin\" | sudo tee -a /etc/profile\necho \"export PATH=$PATH:/usr/hdp/current/spark/bin:/maven/bin:/adam/bin:/cghub/bin\" | sudo tee -a /root/.profile\necho \"ADAM_HOME=/adam\" | sudo tee -a /etc/environment\n\n", "num_lines": 85}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"Starting Spark Setup\"\n\nISMASTER=\"-1\"\nMASTERIP=\"10.0.0.4\"\nSTORAGEACCOUNTKEY=\"\"\nSTORAGEACCOUNTNAME=\"\"\n\nwhile getopts :m:i:k:a:d:s:h optname; do\n    echo \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    m)  #Master 1 Slave 0\n      ISMASTER=${OPTARG}\n\t  ;;\n\ti)\n\t  MASTERIP=${OPTARG}\n\t  ;;\n\tk)\n\t  STORAGEACCOUNTKEY=${OPTARG}\n\t  ;;\n\ta)\n\t  STORAGEACCOUNTNAME=${OPTARG}\n\t  ;;\n  esac\ndone\n\nshow_info()\n{\n\techo \"Is a Master: $ISMASTER\"\n\techo \"Using WASB account name: $STORAGEACCOUNTNAME\"\n\techo \"Using WASB Key: $STORAGEACCOUNTKEY\"\n\techo \"Using $MASTERIP as master ip\"\n}\n\ndownload_extra_libraries()\n{\n\twget -O /tmp/azure-storage-2.0.0.jar https://valueamplifypublic.blob.core.windows.net/public/azure-storage-2.0.0.jar\n\twget -O /tmp/hadoop-azure-2.7.2.jar https://valueamplifypublic.blob.core.windows.net/public/hadoop-azure-2.7.2.jar\n\n\tmv /tmp/*.jar /srv/spark/lib\n}\n\ninstall_prerequisites()\n{\n\techo \"Working as user $USER\"\n\n\techo \"Updating Suse\"\n\tJAVAC=$(which javac)\n\tif [[ -z $JAVAC ]]; then\n\t\techo \"Installing OpenJDK\"\n\t\tsudo zypper install -y java-1_8_0-openjdk java-1_8_0-openjdk-devel\n\tfi\n\n\techo \"Downloading external libraries\"\n\tdownload_extra_libraries\n}\n\nsetup_spark_env_and_defaults()\n{\n\techo \"Setting up spark-env.sh and spark-defaults.sh\"\n\tcd /usr/local/spark/conf/\n\n\tcp -p spark-env.sh.template spark-env.sh\n\ttouch spark-env.sh\n\n\t# Main Parameters\n\techo \"export SPARK_MASTER_IP=\\\"$MASTERIP\\\"\" >> spark-env.sh\n\techo \"export SPARK_MASTER_PORT=7077\" >> spark-env.sh\n\techo \"export SPARK_PUBLIC_DNS=\\\"$MASTERIP\\\"\" >> spark-env.sh\n\t#echo \"export SPARK_EXECUTOR_INSTANCES=\\\"1\\\"\" >> spark-env.sh\n\n\t# Other Paramters\n\techo 'export SPARK_WORKER_MEMORY=\"1g\"' >> spark-env.sh\n\techo 'export SPARK_DRIVER_MEMORY=\"1g\"' >> spark-env.sh\n\techo 'export SPARK_REPL_MEM=\"2g\"' >> spark-env.sh\n\techo 'export SPARK_WORKER_PORT=9000' >> spark-env.sh\n\techo 'export SPARK_CONF_DIR=\"/usr/local/spark/conf\"' >> spark-env.sh\n\techo 'export SPARK_TMP_DIR=\"/srv/spark/tmp\"' >> spark-env.sh\n\techo 'export SPARK_PID_DIR=\"/srv/spark/pids\"' >> spark-env.sh\n\techo 'export SPARK_LOG_DIR=\"/srv/spark/logs\"' >> spark-env.sh\n\techo 'export SPARK_WORKER_DIR=\"/srv/spark/work\"' >> spark-env.sh\n\techo 'export SPARK_LOCAL_DIRS=\"/srv/spark/tmp\"' >> spark-env.sh\n\techo 'export SPARK_COMMON_OPTS=\"$SPARK_COMMON_OPTS -Dspark.kryoserializer.buffer.mb=32 \"' >> spark-env.sh\n\techo 'LOG4J=\"-Dlog4j.configuration=file://$SPARK_CONF_DIR/log4j.properties\"' >> spark-env.sh\n\techo 'export SPARK_MASTER_OPTS=\" $LOG4J -Dspark.log.file=/srv/spark/logs/master.log \"' >> spark-env.sh\n\techo 'export SPARK_WORKER_OPTS=\" $LOG4J -Dspark.log.file=/srv/spark/logs/worker.log \"' >> spark-env.sh\n\techo 'export SPARK_EXECUTOR_OPTS=\" $LOG4J -Djava.io.tmpdir=/srv/spark/tmp/executor \"' >> spark-env.sh\n\techo 'export SPARK_REPL_OPTS=\" -Djava.io.tmpdir=/srv/spark/tmp/repl/\\$USER \"' >> spark-env.sh\n\techo 'export SPARK_APP_OPTS=\" -Djava.io.tmpdir=/srv/spark/tmp/app/\\$USER \"' >> spark-env.sh\n\techo 'export PYSPARK_PYTHON=\"/usr/bin/python\"' >> spark-env.sh\n\n\t# Hadoop Related Configs\n\techo 'export HADOOP_CONF_DIR=\"/usr/local/spark/conf\"' >> spark-env.sh\n\n\t## Cnofigure Azure Blob storage / Wasb access\n\ttouch core-site.xml\n\n\techo '<?xml version=\"1.0\" encoding=\"UTF-8\"?>' >> core-site.xml\n\techo '<?xml-stylesheet type=\"text/xsl\" href=\"configuration.xsl\"?>' >> core-site.xml\n\techo '<configuration>' >> core-site.xml\n\techo '<property>' >> core-site.xml\n\techo \"<name>fs.azure.account.key.$STORAGEACCOUNTNAME.blob.core.windows.net</name>\" >> core-site.xml\n\techo \"<value>$STORAGEACCOUNTKEY</value>\" >> core-site.xml\n\techo '</property>' >> core-site.xml\n\techo '</configuration>' >> core-site.xml\n\n\t# Spark DEFAULTS\n\tcp -p spark-defaults.conf.template spark-defaults.conf\n\ttouch spark-defaults.conf\n\n\techo \"spark.master            spark://$MASTERIP:7077\" >> spark-defaults.conf\n\techo 'spark.serializer        org.apache.spark.serializer.KryoSerializer' >> spark-defaults.conf\n\n\techo 'spark.driver.extraClassPath\t/srv/spark/lib/*' >> spark-defaults.conf\n\techo 'spark.executor.extraClassPath\t/srv/spark/lib/*' >> spark-defaults.conf\n\n\tcd ~\n}\n\ninstall_spark()\n{\n\tcd ~\n\tmkdir /usr/local/sparkforsuse\n\tcd /usr/local/sparkforsuse\n\n\twget http://mirrors.advancedhosters.com/apache/spark/spark-2.0.1/spark-2.0.1-bin-hadoop2.7.tgz\n\n\ttar xvzf spark-2.0.1-bin-hadoop2.7.tgz > /tmp/spark_unzip.log\n\trm spark-2.0.1-bin-hadoop2.7.tgz\n\tmv spark-2.0.1-bin-hadoop2.7 ../\n\tcd ..\n\tcd /usr/local/\n\n\trm -rf sparkforsuse\n\n\tsudo ln -s spark-2.0.1-bin-hadoop2.7 spark\n\n\t# Adding \"spark\" user for launching master and slave processes\n\n\tsudo groupadd spark\n\tsudo useradd -g spark spark\n\t#sudo adduser spark sudo\n\tsudo mkdir /home/spark\n\tsudo chown spark:spark /home/spark\n\n\techo \"spark ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/90-cloud-init-users\n\tsudo chown -R spark:spark /usr/local/spark/\n\n\trm -f ~/.ssh/id_rsa\n\tssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys\n\n\tsudo mkdir -p /srv/spark/{logs,work,tmp,pids,lib}\n\tsudo chown -R spark:spark /srv/spark\n\tsudo chmod 4755 /srv/spark/tmp\n\n\tdownload_extra_libraries\n\n\tsetup_spark_env_and_defaults\n\n\tsudo su spark\n\trm -f ~/.ssh/id_rsa\n\tssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys\n}\n\nlaunch_spark()\n{\n\tsudo su spark\n\t# need to say yes to every question\n\tssh localhost\n\n\tcd /usr/local/spark\n\n\tif [ ${ISMASTER} -eq \"1\" ];\n\t    then\n\t\t./sbin/start-master.sh\n\t    else\n\t\t./sbin/start-slave.sh spark://$MASTERIP:7077\n\tfi\n}\n\nsetup_environment_for_all_users()\n{\n\techo \"Configuring SPARK_HOME, JAVA_HOME and PATH\"\n\n\techo 'export SPARK_HOME=\"/usr/local/spark\"' >> /etc/profile\n\techo 'export SPARK_HOME=\"/usr/local/spark\"' >> /etc/profile.local\n\n\techo 'export JAVA_HOME=/usr/lib64/jvm/java-1.8.0-openjdk-1.8.0/jre' >> /etc/profile.local\n\techo 'export JAVA_HOME=/usr/lib64/jvm/java-1.8.0-openjdk-1.8.0/jre' >> /etc/profile\n\n\techo 'export PATH=$PATH:$JAVA_HOME/bin:$SPARK_HOME/bin' >> /etc/profile.local\n\techo 'export PATH=$PATH:$JAVA_HOME/bin:$SPARK_HOME/bin' >> /etc/profile\n}\n\n\nshow_info > /tmp/install_info.log\n\ninstall_prerequisites > /tmp/install_prerequisites.log\n\ninstall_spark > /tmp/install_spark.log\n\nsetup_environment_for_all_users > /tmp/setup_environment_for_all_users.log\n\nlaunch_spark > /tmp/launch_spark.log\n", "num_lines": 206}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n# Author: Cognosys Technologies\n\n###\n### Warning! This script partitions and formats disk information be careful where you run it\n###          This script is currently under development and has only been tested on Ubuntu images in Azure\n###          This script is not currently idempotent and only works for provisioning at the moment\n\n### Remaining work items\n### -Alternate discovery options (Azure Storage)\n### -Implement Idempotency and Configuration Change Support\n### -Recovery Settings (These can be changed via API)\n\nhelp()\n{\n    #TODO: Add help text here\n    echo \"This script installs spark cluster on Ubuntu\"\n    echo \"Parameters:\"\n    echo \"-k spark version like 1.2.1\"\n    echo \"-m master 1 slave 0\"\n    echo \"-h view this help content\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n    \t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/[account-key]/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\necho \"Begin execution of spark script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    echo \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# TEMP FIX - Re-evaluate and remove when possible\n# This is an interim fix for hostname resolution in current VM\ngrep -q \"${HOSTNAME}\" /etc/hosts\nif [ $? -eq $SUCCESS ];\nthen\n  echo \"${HOSTNAME}found in /etc/hosts\"\nelse\n  echo \"${HOSTNAME} not found in /etc/hosts\"\n  # Append it to the hsots file if not there\n  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n  log \"hostname ${HOSTNAME} added to /etc/hosts\"\nfi\n\n#Script Parameters\nSPK_VERSION=\"1.2.1\"\nMASTER1SLAVE0=\"-1\"\nMASTERIP=\"10.0.0.10\"\nNUMBEROFSLAVES=\"1\"\n\n#Loop through options passed\nwhile getopts :k:m:d:s:h optname; do\n    echo \"Option $optname set with value ${OPTARG}\"\n  case $optname in\n    k)  #spark version\n      SPK_VERSION=${OPTARG}\n      ;;\n    m)  #Master 1 Slave 0\n      MASTER1SLAVE0=${OPTARG}\n      ;;\n    d)  #Master IP\n      MASTERIP=${OPTARG}\n      ;;\n    s)  #Number of Slaves\n      NUMBEROFSLAVES=${OPTARG}\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\ninstall_pre()\n{\n# First install pre-requisites\n\tsudo  apt-get -y update\n\n\techo \"Installing Java\"\n\tadd-apt-repository -y ppa:webupd8team/java\n\tapt-get -y update\n\techo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n\techo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n\tapt-get -y install oracle-java7-installer\n\tsudo ntpdate pool.ntp.org\n\tsudo apt-get -y install ntp\n\tsudo apt-get -y install python-software-properties\n\tsudo apt-get -y update\n\tsudo apt-get -y install git\n}\n\n# Install spark\ninstall_spark()\n{\n\t##Second download and install Apache Spark\n\tcd ~\n\tmkdir /usr/local/azurespark\n\tcd /usr/local/azurespark/\n\n########## to build manually for versions where prebuilt binary is not available\n#\twget http://mirror.tcpdiag.net/apache/spark/spark-1.2.1/spark-1.2.1.tgz\n#\tgunzip -c spark-1.2.1.tgz | tar -xvf -\n#\tmv spark-1.2.1 ../\n#\tcd ../spark-1.2.1/\n# this will take quite a while\n#\tsudo sbt/sbt assembly 2>&1 1>buildlog.txt\n##########\n\n\tversion=${SPK_VERSION}\n\twget https://archive.apache.org/dist/spark/spark-${version}/spark-${version}-bin-hadoop2.7.tgz\n\techo \"Unpacking Spark\"\n\ttar xvzf spark-*.tgz > /tmp/spark-ec2_spark.log\n\trm spark-*.tgz\n\tmv spark-${version}-bin-hadoop2.7 ../\n\tcd ..\n\tcd /usr/local/\n\tsudo ln -s spark-${version}-bin-hadoop2.7 spark\n\n#\tThird create a spark user with proper privileges and ssh keys.\n\n\tsudo addgroup spark\n\tsudo useradd -g spark spark\n\tsudo adduser spark sudo\n\tsudo mkdir /home/spark\n\tsudo chown spark:spark /home/spark\n\n#\tAdd to sudoers file:\n\n\techo \"spark ALL=(ALL) NOPASSWD:ALL\" >> /etc/sudoers.d/90-cloud-init-users\n\tsudo chown -R spark:spark /usr/local/spark/\n\n#\tSetting passwordless ssh for root\n\n        rm -f ~/.ssh/id_rsa\n\tssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys\n\n#\tFourth setup some Apache Spark working directories with proper user permissions\n\n\tsudo mkdir -p /srv/spark/{logs,work,tmp,pids}\n\tsudo chown -R spark:spark /srv/spark\n\tsudo chmod 4755 /srv/spark/tmp\n\n#\tFifth let\u00ef\u00bf\u00bds do a quick test\n#\tcd /usr/local/spark\n#\tbin/run-example SparkPi 10\n\n#\tNow lets adjust some Spark configuration files\n\n\tcd /usr/local/spark/conf/\n\tcp -p spark-env.sh.template spark-env.sh\n\ttouch spark-env.sh\n\n#\t========================================================\n#\techo 'SPARK-ENV.SH (ADD BELOW)' >> spark-env.sh\n\n# Can change the memory settings\n\n\techo 'export SPARK_WORKER_MEMORY=\"1g\"' >> spark-env.sh\n\techo 'export SPARK_DRIVER_MEMORY=\"1g\"' >> spark-env.sh\n\techo 'export SPARK_REPL_MEM=\"2g\"' >> spark-env.sh\n\techo 'export SPARK_WORKER_PORT=9000' >> spark-env.sh\n\techo 'export SPARK_CONF_DIR=\"/usr/local/spark/conf\"' >> spark-env.sh\n\techo 'export SPARK_TMP_DIR=\"/srv/spark/tmp\"' >> spark-env.sh\n\techo 'export SPARK_PID_DIR=\"/srv/spark/pids\"' >> spark-env.sh\n\techo 'export SPARK_LOG_DIR=\"/srv/spark/logs\"' >> spark-env.sh\n\techo 'export SPARK_WORKER_DIR=\"/srv/spark/work\"' >> spark-env.sh\n\techo 'export SPARK_LOCAL_DIRS=\"/srv/spark/tmp\"' >> spark-env.sh\n\techo 'export SPARK_COMMON_OPTS=\"$SPARK_COMMON_OPTS -Dspark.kryoserializer.buffer.mb=32 \"' >> spark-env.sh\n\techo 'LOG4J=\"-Dlog4j.configuration=file://$SPARK_CONF_DIR/log4j.properties\"' >> spark-env.sh\n\techo 'export SPARK_MASTER_OPTS=\" $LOG4J -Dspark.log.file=/srv/spark/logs/master.log \"' >> spark-env.sh\n\techo 'export SPARK_WORKER_OPTS=\" $LOG4J -Dspark.log.file=/srv/spark/logs/worker.log \"' >> spark-env.sh\n\techo 'export SPARK_EXECUTOR_OPTS=\" $LOG4J -Djava.io.tmpdir=/srv/spark/tmp/executor \"' >> spark-env.sh\n\techo 'export SPARK_REPL_OPTS=\" -Djava.io.tmpdir=/srv/spark/tmp/repl/\\$USER \"' >> spark-env.sh\n\techo 'export SPARK_APP_OPTS=\" -Djava.io.tmpdir=/srv/spark/tmp/app/\\$USER \"' >> spark-env.sh\n\techo 'export PYSPARK_PYTHON=\"/usr/bin/python\"' >> spark-env.sh\n\techo \"export SPARK_MASTER_IP=\\\"$MASTERIP\\\"\" >> spark-env.sh\n\techo 'export SPARK_MASTER_PORT=7077' >> spark-env.sh\n\techo \"export SPARK_PUBLIC_DNS=\\\"$MASTERIP\\\"\" >> spark-env.sh\n\techo \"export SPARK_WORKER_INSTANCES=\\\"${NUMBEROFSLAVES}\\\"\" >> spark-env.sh\n\t#=========================================================\n\n\tcp -p spark-defaults.conf.template spark-defaults.conf\n\ttouch spark-defaults.conf\n\n\t#=========================================================\n\t#SPARK-DEFAULTS (ADD BELOW)\n\n\techo \"spark.master            spark://${MASTERIP}:7077\" >> spark-defaults.conf\n\techo 'spark.executor.memory   512m' >> spark-defaults.conf\n\techo 'spark.eventLog.enabled  true' >> spark-defaults.conf\n\techo 'spark.serializer        org.apache.spark.serializer.KryoSerializer' >> spark-defaults.conf\n\n\t#================================================================\n\n\t#Time to start Apache Spark up\n\n\tsudo su spark\n\trm -f ~/.ssh/id_rsa\n\tssh-keygen -q -t rsa -N '' -f ~/.ssh/id_rsa && cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys\n\n\tssh localhost\n\n\tcd /usr/local/spark/sbin\n\tif [ ${MASTER1SLAVE0} -eq \"1\" ];\n\t    then\n\t\t./start-master.sh\n\t    else\n\t\t./start-slaves.sh\n\tfi\n\n#Note to stop processes do:\n\n\t#./stop-slaves.sh\n\n\t#./stop-master.sh\n}\n\n# Primary Install Tasks\n#########################\n#NOTE: These first three could be changed to run in parallel\n#      Future enhancement - (export the functions and use background/wait to run in parallel)\n\n#Install Pre requisites\n#------------------------\ninstall_pre\n\n#Install spark\n#-----------------------\ninstall_spark\n\n#========================= END ==================================\n\n", "num_lines": 268}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Install Java\n# Install Java\nsudo apt-get -y update\nsudo apt-get -y upgrade\nsudo apt-get install -y $1\nsudo apt-get -y update --fix-missing\nsudo apt-get install -y $1\n\n# Install tomcat\nsudo apt-get install -y  $2\n\n#install mysql-server 5.6\nsudo apt-get -y install mysql-server-5.6\n\n# Update and then close\nsudo apt-get -y update\nsudo apt-get -y upgrade\n\nif netstat -tulpen | grep 8080\nthen\nexit 0\nfi\n", "num_lines": 23}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# This script can be found on https://github.com/Azure/azure-quickstart-templates/blob/master/torque-cluster/azuredeploy.sh\n# This script is part of azure deploy ARM template\n# This script assumes the Linux distribution to be Ubuntu (or at least have apt-get support)\n# This script will install Torque on a Linux cluster deployed on a set of Azure VMs\n\n# Basic info\ndate > /tmp/azuredeploy.log.$$ 2>&1\nwhoami >> /tmp/azuredeploy.log.$$ 2>&1\necho $@ >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Usage\nif [ \"$#\" -ne 9 ]; then\n  echo \"Usage: $0 MASTER_NAME MASTER_IP WORKER_NAME WORKER_IP_BASE WORKER_IP_START NUM_OF_VM ADMIN_USERNAME ADMIN_PASSWORD TEMPLATE_BASE\" >> /tmp/azuredeploy.log.$$\n  exit 1\nfi\n\n# Preparation steps - hosts and ssh\n###################################\n\n# Parameters\nMASTER_NAME=$1\nMASTER_IP=$2\nWORKER_NAME=$3\nWORKER_IP_BASE=$4\nWORKER_IP_START=$5\nNUM_OF_VM=$6\nADMIN_USERNAME=$7\nADMIN_PASSWORD=$8\nTEMPLATE_BASE=$9\n\n# Update master node\necho $MASTER_IP $MASTER_NAME >> /etc/hosts\necho $MASTER_IP $MASTER_NAME > /tmp/hosts.$$\n\n# Need to disable requiretty in sudoers, I'm root so I can do this.\nsed -i \"s/Defaults\\s\\{1,\\}requiretty/Defaults \\!requiretty/g\" /etc/sudoers\n\n# Update ssh config file to ignore unknow host\n# Note all settings are for azureuser, NOT root\nsudo -u $ADMIN_USERNAME sh -c \"mkdir /home/$ADMIN_USERNAME/.ssh/;echo Host worker\\* > /home/$ADMIN_USERNAME/.ssh/config; echo StrictHostKeyChecking no >> /home/$ADMIN_USERNAME/.ssh/config; echo UserKnownHostsFile=/dev/null >> /home/$ADMIN_USERNAME/.ssh/config\"\n\n# Generate a set of sshkey under /honme/azureuser/.ssh if there is not one yet\nif ! [ -f /home/$ADMIN_USERNAME/.ssh/id_rsa ]; then\n    sudo -u $ADMIN_USERNAME sh -c \"ssh-keygen -f /home/$ADMIN_USERNAME/.ssh/id_rsa -t rsa -N ''\"\nfi\n\n# Install sshpass to automate ssh-copy-id action\nsudo yum install -y epel-release >> /tmp/azuredeploy.log.$$ 2>&1\nsudo yum install -y sshpass >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Loop through all worker nodes, update hosts file and copy ssh public key to it\n# The script make the assumption that the node is called %WORKER+<index> and have\n# static IP in sequence order\ni=0\nwhile [ $i -lt $NUM_OF_VM ]\ndo\n   workerip=`expr $i + $WORKER_IP_START`\n   echo 'I update host - '$WORKER_NAME$i >> /tmp/azuredeploy.log.$$ 2>&1\n   echo $WORKER_IP_BASE$workerip $WORKER_NAME$i >> /etc/hosts\n   echo $WORKER_IP_BASE$workerip $WORKER_NAME$i >> /tmp/hosts.$$\n   sudo -u $ADMIN_USERNAME sh -c \"sshpass -p '$ADMIN_PASSWORD' ssh-copy-id $WORKER_NAME$i\"\n   i=`expr $i + 1`\ndone\n\n# Install Torque\n################\n\n# Prep packages\nsudo -S yum install -y libtool openssl-devel libxml2-devel boost-devel gcc gcc-c++ >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Download the source package\ncd /tmp >> /tmp/azuredeploy.log.$$ 2>&1\nwget http://www.adaptivecomputing.com/index.php?wpfb_dl=2936 -O torque.tar.gz >> /tmp/azuredeploy.log.$$ 2>&1\ntar xzvf torque.tar.gz >> /tmp/azuredeploy.log.$$ 2>&1\ncd torque-5.1.1* >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Build\n./configure >> /tmp/azuredeploy.log.$$ 2>&1\nmake >> /tmp/azuredeploy.log.$$ 2>&1\nmake packages >> /tmp/azuredeploy.log.$$ 2>&1\nsudo make install >> /tmp/azuredeploy.log.$$ 2>&1\n\nexport PATH=/usr/local/bin/:/usr/local/sbin/:$PATH\n\n# Create and start trqauthd\nsudo cp contrib/init.d/trqauthd /etc/init.d/ >> /tmp/azuredeploy.log.$$ 2>&1\nsudo chkconfig --add trqauthd >> /tmp/azuredeploy.log.$$ 2>&1\nsudo sh -c \"echo /usr/local/lib > /etc/ld.so.conf.d/torque.conf\" >> /tmp/azuredeploy.log.$$ 2>&1\nsudo ldconfig >> /tmp/azuredeploy.log.$$ 2>&1\nsudo service trqauthd start >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Update config\nsudo sh -c \"echo $MASTER_NAME > /var/spool/torque/server_name\" >> /tmp/azuredeploy.log.$$ 2>&1\n\nsudo env \"PATH=$PATH\" sh -c \"echo 'y' | ./torque.setup root\" >> /tmp/azuredeploy.log.$$ 2>&1\n\nsudo sh -c \"echo $MASTER_NAME > /var/spool/torque/server_priv/nodes\" >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Start pbs_server\nsudo cp contrib/init.d/pbs_server /etc/init.d >> /tmp/azuredeploy.log.$$ 2>&1\nsudo chkconfig --add pbs_server >> /tmp/azuredeploy.log.$$ 2>&1\nsudo service pbs_server restart >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Start pbs_mom\nsudo cp contrib/init.d/pbs_mom /etc/init.d >> /tmp/azuredeploy.log.$$ 2>&1\nsudo chkconfig --add pbs_mom >> /tmp/azuredeploy.log.$$ 2>&1\nsudo service pbs_mom start >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Start pbs_sched\nsudo env \"PATH=$PATH\" pbs_sched >> /tmp/azuredeploy.log.$$ 2>&1\n\n# Push packages to compute nodes\ni=0\nwhile [ $i -lt $NUM_OF_VM ]\ndo\n  worker=$WORKER_NAME$i\n  sudo -u $ADMIN_USERNAME scp /tmp/hosts.$$ $ADMIN_USERNAME@$worker:/tmp/hosts >> /tmp/azuredeploy.log.$$ 2>&1\n  sudo -u $ADMIN_USERNAME scp torque-package-mom-linux-x86_64.sh $ADMIN_USERNAME@$worker:/tmp/. >> /tmp/azuredeploy.log.$$ 2>&1\n  sudo -u $ADMIN_USERNAME ssh -tt $worker \"echo '$ADMIN_PASSWORD' | sudo -kS sh -c 'cat /tmp/hosts>>/etc/hosts'\"\n  sudo -u $ADMIN_USERNAME ssh -tt $worker \"echo '$ADMIN_PASSWORD' | sudo -kS /tmp/torque-package-mom-linux-x86_64.sh --install\"\n  sudo -u $ADMIN_USERNAME ssh -tt $worker \"echo '$ADMIN_PASSWORD' | sudo -kS /usr/local/sbin/pbs_mom\"\n  echo $worker >> /var/spool/torque/server_priv/nodes\n  i=`expr $i + 1`\ndone\n\n# Restart pbs_server\nsudo service pbs_server restart >> /tmp/azuredeploy.log.$$ 2>&1\n\nexit 0\n", "num_lines": 132}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#################################################################\n# Update Ubuntu and install prerequisites for running Trailbot  #\n#################################################################\ncurl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -\n\nexport DEBIAN_FRONTEND=noninteractive\napt-key adv --keyserver keyserver.ubuntu.com --recv-keys 1655A0AB68576280\n\napt-get -y update\napt-get install -y git nodejs rng-tools mailutils build-essential\n\n#################################################################\n# Get the watcher code and install its npm dependencies         #\n#################################################################\ngit clone https://github.com/trailbot/watcher\ncd watcher\ngit checkout azure\nnpm install --production --ignore-scripts\n\n#################################################################\n# Fake setup                                                    #\n#################################################################\nmkdir .localstorage\necho \"[\\\"azure\\\"]\" > .localstorage/mods\necho \"vault.trailbot.io:8443\" > .localstorage/vault\necho \"$1\" > .localstorage/user_email\necho -e \"-----BEGIN PGP PUBLIC KEY BLOCK-----\\n\\n\" > .localstorage/client_pub_key\necho -e $(echo \"$2\" | sed 's/  /@/g' | cut -d@ -f2 | cut -d- -f1 | sed 's/ /\\\\n/g') >> .localstorage/client_pub_key\necho -e \"\\n-----END PGP PUBLIC KEY BLOCK-----\" >> .localstorage/client_pub_key\n\n#################################################################\n# Keypar generation                                             #\n#################################################################\nrngd -r /dev/urandom\ngpg --batch --armor --gen-key <<EOF\n  Key-Type: RSA\n  Key-Length: 4096\n  Subkey-Type: RSA\n  Subkey-Length: 4096\n  Name-Real: \"$(hostname)\"\n  Name-Email: \"watcher@$(hostname)\"\n  Expire-Date: 0\n  %no-protection\n  %secring .localstorage/watcher_priv_key\n  %pubring .localstorage/watcher_pub_key\n  %echo Generating keypar...\n  %commit\n  %echo Keypar generated successfully!\nEOF\n\n#################################################################\n# Send public key to admin via email                            #\n#################################################################\necho \"Please find enclosed the public key for the Trailbot Watcher \\\ninstalled at $(hostname)\" | mail \\\n  -a \".localstorage/watcher_pub_key\" \\\n  -s \"Successful installation of Trailbot Watcher at $(hostname)\" \\\n  $1\n\n#################################################################\n# Service creation and start up                                 #\n#################################################################\nsh scripts/service\nexit 0\n", "num_lines": 67}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nlogger -t devvm \"Install started: $?\"\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n\napt-key adv --keyserver packages.microsoft.com --recv-keys 52E16F86FEE04B979B07E28DB02C46DF417A0893\n\napt-get install -y apt-transport-https\n\napt-get update && sudo apt-get install -y azure-cli\n\nlogger -t devvm \"Azure-cli installed: $?\"\n\nsudo apt-get -y update\n\nsudo apt-get -q=2 -y install xrdp\n\nlogger -t devvm \"XRDP installed: $?\"\n\nlogger -t devvm \"Installing Mate Desktop ...\"\n\nsudo dpkg --configure -a\n\nsudo apt-add-repository -y ppa:ubuntu-mate-dev/ppa\n\nsudo apt-add-repository -y ppa:ubuntu-mate-dev/trusty-mate\n\nsudo apt-get -y update\n\nsudo apt-get -y upgrade\n\nsudo apt-get install -q=2  --no-install-recommends -m ubuntu-mate-core\n\nsudo apt-get install -q=2  --no-install-recommends -m ubuntu-mate-desktop\n\nlogger -t devvm \"Mate Desktop installed. $?\"\n\necho mate-session >~/.xsession\n\nsudo service xrdp restart\n\n# Fixes the issue with Ubuntu desktop being blank.\n\nsudo sed -i -e 's/console/anybody/g' /etc/X11/Xwrapper.config\n\nlogger -t devvm \"Mate Desktop configured. $?\"\n\nlogger -t devvm \"Installing VSCode: $?\"\n\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\n\nsudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg\n\nsudo sh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main\" > /etc/apt/sources.list.d/vscode.list'\n\nsudo apt-get update\n\nsudo apt-get install -y code\n\nlogger -t devvm \"VSCode Installed: $?\"\n\nlogger -t devvm \"Success\"\nexit 0\n", "num_lines": 64}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n/bin/date +%H:%M:%S > /home/$5/install.progress.txt\necho \"ooooo      REDHAT VSTS BUILD INSTALL      ooooo\" >> /home/$5/install.progress.txt\n\necho \"Initial basic development packages\" >> /home/$5/install.progress.txt\nyum install -y gcc > /home/$5/install.out.txt 2>&1\nyum install -y gcc-c++ >> /home/$5/install.out.txt 2>&1\nyum install -y httpd-devel >> /home/$5/install.out.txt 2>&1\nyum install -y patch readline readline-devel zlib zlib-devel >> /home/$5/install.out.txt 2>&1\nyum install -y libyaml-devel libffi-devel openssl-devel make >> /home/$5/install.out.txt 2>&1\nyum install -y bzip2 autoconf automake libtool bison iconv-devel >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Install X11 Packages\" >> /home/$5/install.progress.txt\nyum install -y xorg-x11-server-Xorg xorg-x11-xauth xorg-x11-apps\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Install OpenJDK Java packages\" >> /home/$5/install.progress.txt\nyum install -y java-1.6.0-openjdk-devel >> /home/$5/install.out.txt 2>&1\nyum install -y java-1.7.0-openjdk-devel >> /home/$5/install.out.txt 2>&1\nyum install -y java-1.8.0-openjdk-devel >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Install Default Ant and Maven\" >> /home/$5/install.progress.txt\nyum install -y ant >> /home/$5/install.out.txt 2>&1\nyum install -y maven >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Install Gradle 3.0\" >> /home/$5/install.progress.txt\nmkdir /home/$5/downloads\ncd /home/$5/downloads\nwget http://services.gradle.org/distributions/gradle-3.0-all.zip >> /home/$5/install.out.txt 2>&1\nunzip gradle-3.0-all.zip -d /opt/gradle >> /home/$5/install.out.txt 2>&1\nln -s /opt/gradle/gradle-3.0/bin/gradle /usr/local/bin\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"NodeJS, npm and gulp\" >> /home/$5/install.progress.txt\ncurl -sL https://rpm.nodesource.com/setup_6.x | bash - >> /home/$5/install.out.txt 2>&1\nyum install -y nodejs >> /home/$5/install.out.txt 2>&1\nnpm install gulp -g >> /home/$5/install.out.txt 2>&1\nnpm install gulp --save-dev >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Groovy\" >> /home/$5/install.progress.txt\nyum install -y groovy >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Install Ruby, Gems and Rails\" >> /home/$5/install.progress.txt\ngpg2 --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 >> /home/$5/install.out.txt 2>&1\ncurl -L get.rvm.io | bash -s stable >> /home/$5/install.out.txt 2>&1\n# source /etc/profile.d/rvm.sh\n/usr/local/rvm/bin/rvm install 2.3.0 >> /home/$5/install.out.txt 2>&1\n/usr/local/rvm/bin/rvm all do gem install rails >> /home/$5/install.out.txt 2>&1\n/usr/local/rvm/bin/rvm all do gem install executable-hooks >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Go Language\" >> /home/$5/install.progress.txt\nyum install -y golang >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# Install VSTS build agent dependencies\ncd /home/$5\n\necho \"Installing libunwind8 package\" >> /home/$5/install.progress.txt\nyum -y install libunwind.x86_64 icu >> /home/$5/install.out.txt 2>&1\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\nyum install -y curl-devel expat-devel gettext-devel openssl-devel zlib-devel >> /home/$5/install.out.txt 2>&1\nyum install -y gcc perl-ExtUtils-MakeMaker >> /home/$5/install.out.txt 2>&1\n\necho \"Installing and building git 2.9.2\" >> /home/$5/install.progress.txt\n\ncd /usr/src\nwget https://www.kernel.org/pub/software/scm/git/git-2.9.2.tar.gz >> /home/$5/install.out.txt 2>&1\ntar xzf git-2.9.2.tar.gz >> /home/$5/install.out.txt 2>&1\n\ncd git-2.9.2\nmake prefix=/usr/local/git all >> /home/$5/install.out.txt 2>&1\nmake prefix=/usr/local/git install >> /home/$5/install.out.txt 2>&1\nmv /usr/bin/git /usr/bin/git_Orig\nln -s /usr/local/git/bin/git /usr/bin/git\n\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# Install Docker Engine and Docker Compose\necho \"Installing Docker Engine and Docker Compose\" >> /home/$5/install.progress.txt\nyum update -y --exclude=WALinuxAgent >> /home/$5/install.out.txt 2>&1\n# yum update -y >> /home/$5/install.out.txt 2>&1\n\necho [dockerrepo] > /etc/yum.repos.d/docker.repo\necho name=Docker Repository >> /etc/yum.repos.d/docker.repo\necho baseurl=https://yum.dockerproject.org/repo/main/centos/7/ >> /etc/yum.repos.d/docker.repo\necho enabled=1 >> /etc/yum.repos.d/docker.repo\necho gpgcheck=1 >> /etc/yum.repos.d/docker.repo\necho gpgkey=https://yum.dockerproject.org/gpg >> /etc/yum.repos.d/docker.repo\n\nyum install -y docker-engine >> /home/$5/install.out.txt 2>&1\nsystemctl enable docker.service\nsystemctl start docker\nsystemctl enable docker\ngroupadd docker\nusermod -aG docker $5\n\ncurl -L https://github.com/docker/compose/releases/download/1.9.0/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\nchmod +x /usr/local/bin/docker-compose >> /home/$5/install.out.txt 2>&1\n\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install latest .NET Core\necho \"Installing latest .NET Core\" >> /home/$5/install.progress.txt\n# mkdir /home/$5/lib\n# mkdir /home/$5/lib/dotnet\n# cd /home/$5/downloads\n# wget https://dotnetcli.blob.core.windows.net/dotnet/preview/Binaries/1.0.0-preview2-003131/dotnet-dev-rhel-x64.1.0.0-preview2-003131.tar.gz >> /home/$5/install.out.txt 2>&1\n# cd /home/$5/lib/dotnet\n# tar zxfv /home/$5/downloads/dotnet-dev-rhel-x64.1.0.0-preview2-003131.tar.gz >> /home/$5/install.out.txt 2>&1\n# yum install -y scl-utils >> /home/$5/install.out.txt 2>&1\n# yum install -y rh-dotnetcore11 >> /home/$5/install.out.txt 2>&1\n# scl enable rh-dotnetcore11 bash\ncd /home/$5/downloads\ncurl -sSL -o dotnet.tar.gz https://go.microsoft.com/fwlink/?LinkID=834983 >> /home/$5/install.out.txt 2>&1\nmkdir -p /opt/dotnet\ntar zxf dotnet.tar.gz -C /opt/dotnet >> /home/$5/install.out.txt 2>&1\nln -s /opt/dotnet/dotnet /usr/local/bin\n\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Download VSTS build agent and required security patch\n\necho \"Downloading VSTS Build agent package\" >> /home/$5/install.progress.txt\n\ncd /home/$5/downloads\n\nwget https://github.com/Microsoft/vsts-agent/releases/download/v2.109.2/vsts-agent-rhel.7.2-x64-2.109.2.tar.gz >> /home/$5/install.out.txt 2>&1\n\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\necho \"Installing VSTS Build agent package\" >> /home/$5/install.progress.txt\n\n# Install VSTS agent\nmkdir /home/$5/vsts-agent\ncd /home/$5/vsts-agent\ntar xzf /home/$5/downloads/vsts-agent-rhel.7.2* >> /home/$5/install.out.txt 2>&1\n\necho \"LANG=en_US.UTF-8\" > .env\necho \"export LANG=en_US.UTF-8\" >> /home/$5/.bashrc\nexport LANG=en_US.UTF-8\necho \"JAVA_HOME=/usr/lib/jvm/java-1.8.0\" >> .env\necho \"export JAVA_HOME=/usr/lib/jvm/java-1.8.0\" >> /home/$5/.bashrc\nexport JAVA_HOME=/usr/lib/jvm/java-1.8.0\n\nexport JAVA_HOME_6_X64=/usr/lib/jvm/java-1.6.0\necho \"JAVA_HOME_6_X64=/usr/lib/jvm/java-1.6.0\" >> .env\necho \"export JAVA_HOME_6_X64=/usr/lib/jvm/java-1.6.0\" >> /home/$5/.bashrc\nexport JAVA_HOME_7_X64=/usr/lib/jvm/java-1.7.0\necho \"JAVA_HOME_7_X64=/usr/lib/jvm/java-1.7.0\" >> .env\necho \"export JAVA_HOME_7_X64=/usr/lib/jvm/java-1.7.0\" >> /home/$5/.bashrc\necho \"JAVA_HOME_8_X64=/usr/lib/jvm/java-1.8.0\" >> .env\necho \"export JAVA_HOME_8_X64=/usr/lib/jvm/java-1.8.0\" >> /home/$5/.bashrc\nexport JAVA_HOME_8_X64=/usr/lib/jvm/java-1.8.0\n\necho $PATH:/usr/local/bin:/home/$5/lib/dotnet:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.3.0/wrappers:/usr/local/rvm/gems/ruby-2.3.0/bin/ > /home/$5/vsts-agent/.path\n\necho URL: $1 > /home/$5/vsts.install.log.txt 2>&1\necho PAT: HIDDEN >> /home/$5/vsts.install.log.txt 2>&1\necho Pool: $3 >> /home/$5/vsts.install.log.txt 2>&1\necho Agent: $4 >> /home/$5/vsts.install.log.txt 2>&1\necho User: $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\n\nsed -i 's,Defaults    requiretty,#Defaults    requiretty,g' /etc/sudoers\n\necho Running Agent.Listener >> /home/$5/vsts.install.log.txt 2>&1\nsudo -u $5 -E bin/Agent.Listener configure --unattended --nostart --replace --acceptteeeula --url $1 --auth PAT --token $2 --pool $3 --agent $4 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh install >> /home/$5/vsts.install.log.txt 2>&1\nsudo -E ./svc.sh install $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\n\nsudo -E ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\n\nsed -i 's,#Defaults    requiretty,Defaults    requiretty,g' /etc/sudoers\n\ncd /home/$5\nchown -R $5.$5 .*\n# cd /home/$5/downloads\n# chown -R $5.$5 .*\n# cd /home/$5/lib\n# chown -R $5.$5 .*\n# cd /home/$5/lib/dotnet\n# chown -R $5.$5 .*\n# cd /home/$5/vsts-agent\n# chown -R $5.$5 .*\n\necho \"ALL DONE!\" >> /home/$5/install.progress.txt\n/bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n", "num_lines": 204}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Install Build Tools\nsudo /bin/date +%H:%M:%S > /home/$5/install.progress.txt\n\necho \"ooooo      FULL INSTALL      ooooo\" >> /home/$5/install.progress.txt\n\necho \"Installing build-essential package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install build-essential\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing packaging-dev package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install packaging-dev\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install Java\n\n# echo \"Installing Oracle Java 6 package\" >> /home/$5/install.progress.txt\n\n# Install Oracle Java in silent mode\n# echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n# echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n\n# sudo add-apt-repository -y ppa:webupd8team/java\n# sudo apt-get -y update\n# sudo apt-get install -y oracle-java6-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# echo \"Installing Oracle Java 7 package\" >> /home/$5/install.progress.txt\n\n# sudo apt-get install -y oracle-java7-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# echo \"Installing Oracle Java 8 package\" >> /home/$5/install.progress.txt\n\n# sudo apt-get install -y oracle-java8-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing openjdk-7-jdk package\" >> /home/$5/install.progress.txt\n\nsudo add-apt-repository -y ppa:openjdk-r/ppa\nsudo apt-get -y update\nsudo apt-get install -y openjdk-7-jdk\nsudo apt-get -y update --fix-missing\nsudo apt-get install -y openjdk-7-jdk\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing openjdk-8-jdk package\" >> /home/$5/install.progress.txt\n\nsudo add-apt-repository -y ppa:openjdk-r/ppa\nsudo apt-get -y update\nsudo apt-get install -y openjdk-8-jdk\nsudo apt-get -y update --fix-missing\nsudo apt-get install -y openjdk-8-jdk\n\nsudo ln -s /usr/lib/jvm/java-8-openjdk-amd64/ /usr/lib/jvm/default-java\n\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install Java build tools\necho \"Installing ant package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install ant\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing maven package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install maven\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing gradle package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install gradle\nsudo -u $5 /usr/bin/gradle\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# Install NodeJS, npm, and gulp\n\necho \"Installing NodeJS package\" >> /home/$5/install.progress.txt\nsudo curl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -\nsudo apt-get install -y nodejs\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing gulp package\" >> /home/$5/install.progress.txt\nsudo npm install -g gulp\nsudo -u $5 npm install gulp --save-dev\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install Ruby and Ruby on Rails\necho \"Installing Ruby and Ruby on Rails\" >> /home/$5/install.progress.txt\nsudo -u $5 gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3\nsudo -u $5 \\curl -sSL https://get.rvm.io | sudo -u $5 bash -s stable --rails\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install Go\necho \"Installing Go\" >> /home/$5/install.progress.txt\nsudo apt install -y golang-go\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\nsudo -u $5 mkdir /home/$5/downloads\nsudo -u $5 mkdir /home/$5/lib\n\n# Install latest release of .NET Core\necho \"Installing .NET\" >> /home/$5/install.progress.txt\nsudo -u $5 mkdir /home/$5/lib/dotnet\ncd /home/$5/downloads\nsudo -u $5 wget https://dotnetcli.blob.core.windows.net/dotnet/preview/Binaries/Latest/dotnet-ubuntu.16.04-x64.latest.tar.gz\ncd /home/$5/lib/dotnet\nsudo -u $5 tar zxfv /home/$5/downloads/dotnet-ubuntu.16.04-x64.latest.tar.gz\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# Install Docker Engine and Compose\necho \"Installing Docker Engine and Compose\" >> /home/$5/install.progress.txt\nsudo apt-get update\nsudo apt-get install -y apt-transport-https ca-certificates\nsudo apt-key adv --keyserver hkp://ha.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\necho \"deb https://apt.dockerproject.org/repo ubuntu-xenial main\" | sudo tee /etc/apt/sources.list.d/docker.list\nsudo apt-get update\nsudo apt-get install -y linux-image-extra-$(uname -r) linux-image-extra-virtual\nsudo apt-get install -y docker-engine\nsudo service docker start\nsudo systemctl enable docker\nsudo groupadd docker\nsudo usermod -aG docker $5\n\nsudo curl -L https://github.com/docker/compose/releases/download/1.9.0/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose\nsudo chmod +x /usr/local/bin/docker-compose\n\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# Install VSTS build agent dependencies\n\necho \"Installing libunwind8 and libcurl3 package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install libunwind8 libcurl3\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Download VSTS build agent and required security patch\n\necho \"Downloading VSTS Build agent package\" >> /home/$5/install.progress.txt\n\ncd /home/$5/downloads\n\nsudo -u $5 wget https://vstsagentpackage.azureedge.net/agent/2.144.1/vsts-agent-linux-x64-2.144.1.tar.gz\nsudo -u $5 wget http://security.ubuntu.com/ubuntu/pool/main/i/icu/libicu52_52.1-8ubuntu0.2_amd64.deb\nsudo dpkg -i libicu52_52.1-8ubuntu0.2_amd64.deb\n\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\necho \"Installing VSTS Build agent package\" >> /home/$5/install.progress.txt\n\n# Install VSTS agent\nsudo -u $5 mkdir /home/$5/vsts-agent\ncd /home/$5/vsts-agent\nsudo -u $5 tar xzf /home/$5/downloads/vsts-agent-linux*\n\necho \"LANG=en_US.UTF-8\" > .env\necho \"export LANG=en_US.UTF-8\" >> /home/$5/.bashrc\nexport LANG=en_US.UTF-8\necho \"JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> .env\necho \"export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> /home/$5/.bashrc\nexport JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\n# export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\n# echo \"JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\" >> .env\n# echo \"export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\" >> /home/$5/.bashrc\n# export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\n# export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\n# echo \"JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\" >> .env\n# echo \"export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\" >> /home/$5/.bashrc\nexport JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\necho \"JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\" >> .env\necho \"export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\" >> /home/$5/.bashrc\necho \"JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\" >> .env\necho \"export JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\" >> /home/$5/.bashrc\nexport JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\n\n# HACK - only needed if .NET and Ruby/Rails are installed\nsudo -u $5 echo $PATH:/home/$5/lib/dotnet:/home/$5/.rvm/bin > /home/$5/vsts-agent/.path\n\n# HACK - Remove NODE_ENV=production from service template file\nsudo sed -i 's,NODE_ENV=production,,g' ./bin/vsts.agent.service.template\n\necho URL: $1 > /home/$5/vsts.install.log.txt 2>&1\necho PAT: HIDDEN >> /home/$5/vsts.install.log.txt 2>&1\necho Pool: $3 >> /home/$5/vsts.install.log.txt 2>&1\necho Agent: $4 >> /home/$5/vsts.install.log.txt 2>&1\necho User: $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\n\necho Running Agent.Listener >> /home/$5/vsts.install.log.txt 2>&1\nsudo -u $5 -E bin/Agent.Listener configure --unattended --nostart --replace --acceptteeeula --url $1 --auth PAT --token $2 --pool $3 --agent $4 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh install >> /home/$5/vsts.install.log.txt 2>&1\nsudo -E ./svc.sh install $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\n\n# HACK - only need next 3 lines if installing Ruby and Rails\nsudo sed -i \"/^#!\\/bin\\/bash/a [[ -s \\\"\\/home\\/$5\\/.rvm\\/scripts\\/rvm\\\" ]] \\&\\& source \\\"\\/home\\/$5\\/.rvm\\/scripts\\/rvm\\\" \\#L1P1\" ./runsvc.sh\nsudo sed -i \"/L1P1/a echo \\`cat .path\\`:\\$MY_RUBY_HOME/bin:\\$GEM_HOME/bin > .mypath \\#L2P2\" ./runsvc.sh\nsudo sed -i \"/L2P2/a cp .mypath .path\" ./runsvc.sh\n\nsudo -E ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\n\nsudo chown -R $5.$5 .*\n\necho \"ALL DONE!\" >> /home/$5/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n", "num_lines": 215}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Install Build Tools\nsudo /bin/date +%H:%M:%S > /home/$5/install.progress.txt\n\necho \"ooooo      MINIMUM INSTALL      ooooo\" >> /home/$5/install.progress.txt\n\n# Install Java\n\n# echo \"Installing Oracle Java 6 package\" >> /home/$5/install.progress.txt\n\n# Install Oracle Java in silent mode\n# echo debconf shared/accepted-oracle-license-v1-1 select true | sudo debconf-set-selections\n# echo debconf shared/accepted-oracle-license-v1-1 seen true | sudo debconf-set-selections\n\n# sudo add-apt-repository -y ppa:webupd8team/java\n# sudo apt-get -y update\n# sudo apt-get install -y oracle-java6-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# echo \"Installing Oracle Java 7 package\" >> /home/$5/install.progress.txt\n\n# sudo apt-get install -y oracle-java7-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n# echo \"Installing Oracle Java 8 package\" >> /home/$5/install.progress.txt\n\n# sudo apt-get install -y oracle-java8-installer\n\n# sudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing openjdk-7-jdk package\" >> /home/$5/install.progress.txt\n\nsudo add-apt-repository -y ppa:openjdk-r/ppa\nsudo apt-get -y update\nsudo apt-get install -y openjdk-7-jdk\nsudo apt-get -y update --fix-missing\nsudo apt-get install -y openjdk-7-jdk\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\necho \"Installing openjdk-8-jdk package\" >> /home/$5/install.progress.txt\n\nsudo add-apt-repository -y ppa:openjdk-r/ppa\nsudo apt-get -y update\nsudo apt-get install -y openjdk-8-jdk\nsudo apt-get -y update --fix-missing\nsudo apt-get install -y openjdk-8-jdk\n\nsudo ln -s /usr/lib/jvm/java-8-openjdk-amd64/ /usr/lib/jvm/default-java\n\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Install Java build tools\n\necho \"Installing maven package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install maven\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n\nsudo -u $5 mkdir /home/$5/downloads\nsudo -u $5 mkdir /home/$5/lib\n\n# Install VSTS build agent dependencies\n\necho \"Installing libunwind8 and libcurl3 package\" >> /home/$5/install.progress.txt\nsudo apt-get -y install libunwind8 libcurl3\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\n# Download VSTS build agent and required security patch\n\necho \"Downloading VSTS Build agent package\" >> /home/$5/install.progress.txt\n\ncd /home/$5/downloads\n\n# sudo -u $5 wget https://github.com/Microsoft/vsts-agent/releases/download/v2.101.1/vsts-agent-ubuntu.14.04-x64-2.101.1.tar.gz\n# sudo -u $5 wget https://github.com/Microsoft/vsts-agent/releases/download/v2.102.1/vsts-agent-ubuntu.14.04-x64-2.102.1.tar.gz\nsudo -u $5 wget https://github.com/Microsoft/vsts-agent/releases/download/v2.104.2/vsts-agent-ubuntu.14.04-x64-2.104.2.tar.gz\nsudo -u $5 wget http://security.ubuntu.com/ubuntu/pool/main/i/icu/libicu52_52.1-8ubuntu0.2_amd64.deb\nsudo dpkg -i libicu52_52.1-8ubuntu0.2_amd64.deb\n\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n\n\necho \"Installing VSTS Build agent package\" >> /home/$5/install.progress.txt\n\n# Install VSTS agent\nsudo -u $5 mkdir /home/$5/vsts-agent\ncd /home/$5/vsts-agent\nsudo -u $5 tar xzf /home/$5/downloads/vsts-agent-ubuntu*\n\necho \"LANG=en_US.UTF-8\" > .env\necho \"export LANG=en_US.UTF-8\" >> /home/$5/.bashrc\nexport LANG=en_US.UTF-8\necho \"JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> .env\necho \"export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\" >> /home/$5/.bashrc\nexport JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\n# export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\n# echo \"JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\" >> .env\n# echo \"export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\" >> /home/$5/.bashrc\n# export JAVA_HOME_6_X64=/usr/lib/jvm/java-6-oracle\n# export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\n# echo \"JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\" >> .env\n# echo \"export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-oracle\" >> /home/$5/.bashrc\nexport JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\necho \"JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\" >> .env\necho \"export JAVA_HOME_7_X64=/usr/lib/jvm/java-7-openjdk-amd64\" >> /home/$5/.bashrc\necho \"JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\" >> .env\necho \"export JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\" >> /home/$5/.bashrc\nexport JAVA_HOME_8_X64=/usr/lib/jvm/java-8-openjdk-amd64\n\necho URL: $1 > /home/$5/vsts.install.log.txt 2>&1\necho PAT: HIDDEN >> /home/$5/vsts.install.log.txt 2>&1\necho Pool: $3 >> /home/$5/vsts.install.log.txt 2>&1\necho Agent: $4 >> /home/$5/vsts.install.log.txt 2>&1\necho User: $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running Agent.Listener >> /home/$5/vsts.install.log.txt 2>&1\nsudo -u $5 -E bin/Agent.Listener --configure --unattended --nostart --replace --acceptteeeula --url $1 --auth PAT --token $2 --pool $3 --agent $4 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh install >> /home/$5/vsts.install.log.txt 2>&1\nsudo -E ./svc.sh install $5 >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\necho Running ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\n\nsudo -E ./svc.sh start >> /home/$5/vsts.install.log.txt 2>&1\necho =============================== >> /home/$5/vsts.install.log.txt 2>&1\n\nsudo chown -R $5.$5 .*\n\necho \"ALL DONE!\" >> /home/$5/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$5/install.progress.txt\n", "num_lines": 137}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# Install Apache2, Tomcat7 and then build mod-jk package\nyum update -y --disablerepo='*' --enablerepo='*microsoft*'\nyum install -y httpd\nyum install -y tomcat \nyum install -y tomcat-webapps tomcat-admin-webapps \nyum install -y gcc \nyum install -y gcc-c++ \nyum install -y httpd-devel \nyum install -y make \nwget http://archive.apache.org/dist/tomcat/tomcat-connectors/jk/tomcat-connectors-1.2.41-src.tar.gz \ntar xvfz tomcat-connectors-1.2.41-src.tar.gz \n$PWD/tomcat-connectors-1.2.41-src/native/configure --with-apxs=/usr/bin/apxs \nmake -C $PWD/tomcat-connectors-1.2.41-src/native \nmake install -C $PWD/tomcat-connectors-1.2.41-src/native \ngroupadd --system tomcat\nuseradd -d /usr/share/tomcat -r -s /bin/false -g tomcat tomcat\n\n# Create a mod_jk config file\n\necho \"\\\n# Load mod_jk module\n# Specify the filename of the mod_jk lib\nLoadModule jk_module modules/mod_jk.so\n# Where to find workers.properties\nJkWorkersFile conf/workers.properties\n# Where to put jk logs\nJkLogFile /var/log/httpd/mod_jk.log\n# Set the jk log level [debug/error/info]\nJkLogLevel info\n# Select the log format\nJkLogStampFormat \\\"[%a %b %d %H:%M:%S %Y]\\\"\n# JkOptions indicates to send SSK KEY SIZE\nJkOptions +ForwardKeySize +ForwardURICompat -ForwardDirectories\n# JkRequestLogFormat\nJkRequestLogFormat \\\"%w %V %T\\\"\n# Mount your applications\nJkMount /* worker1\nJkShmFile /var/run/mod_jk/jk-runtime-status\" | tee /etc/httpd/conf/mod_jk.conf\n\n# Create mod_jk workers file\necho \"\\\n# Define 1 real worker using ajp13\nworker.list=worker1\nworker.worker1.type=ajp13\nworker.worker1.host=localhost\nworker.worker1.port=8009\nworker.worker1.socket_keepalive=true\nworker.worker1.lbfactor=1\nworker.worker1.connection_pool_size=50\nworker.worker1.connect_timeout=5000\nworker.worker1.prepost_timeout=5000\" | tee /etc/httpd/conf/workers.properties\n\n# Update httpd conf file with server name and mod_jk config file name\ncp /etc/httpd/conf/httpd.conf /etc/httpd/conf/ORIG_httpd.conf\nsed -i 's,#ServerName,ServerName,g' /etc/httpd/conf/httpd.conf\nsed -i \"s,www.example.com:80,`hostname`:80,g\" /etc/httpd/conf/httpd.conf\necho \"\\\n# Include mod_jk's specific configuration file\nInclude conf/mod_jk.conf\" | tee -a /etc/httpd/conf/httpd.conf\n\n# Update the server.xml file to specify the mod_jk worker\ncp /usr/share/tomcat/conf/server.xml /usr/share/tomcat/conf/ORIG_server.xml\nsed -i 's,\"localhost\">,\"localhost\" jvmRoute=\"worker1\">,g' /usr/share/tomcat/conf/server.xml\n\n# Update the permissions on the Tomcat webapps and install directory\nchown -R tomcat:tomcat /var/lib/tomcat/webapps\nchown tomcat:tomcat /usr/share/tomcat\nchown tomcat:tomcat /var/lib/tomcat\n\n# Set the default umask for Tomcat\ncp /usr/libexec/tomcat/server /usr/libexec/tomcat/ORIG_server\nsed -i 's,run start,umask 002\\n  run start,g' /usr/libexec/tomcat/server\nsystemctl daemon-reload \n\n# Configure SELinux to allow mod_jk to work\nyum install -y policycoreutils-python \nmkdir /var/run/mod_jk\n/usr/sbin/semanage fcontext -a -t httpd_var_run_t \"/var/run/mod_jk(/.*)?\" \n\n# Remove unnecessary http modules that create warnings\ncp /etc/httpd/conf.modules.d/00-proxy.conf /etc/httpd/conf.modules.d/ORIG_00-proxy.conf\nsed -i 's,LoadModule lbmethod_heartbeat,# LoadModule lbmethod_heartbeat,g' /etc/httpd/conf.modules.d/00-proxy.conf\n\n#Configure the system to run httpd and tomcat every time the server is booted:\nsystemctl enable httpd  \nsystemctl enable tomcat  \n\n# Restart the Tomcat7 and Apache2 servers:\nservice httpd start  \nservice tomcat start  \n\n# Open Red Hat software firewall for port 80:\nfirewall-cmd --zone=public --add-port=80/tcp --permanent  \nfirewall-cmd --reload  \n\n# Setup permissions for the Tomcat manager\nmv /etc/tomcat/tomcat-users.xml /etc/tomcat/ORIG_tomcat-users.xml\n\necho \"\\\n<?xml version='1.0' encoding='utf-8'?>\n<tomcat-users>\n<role rolename=\\\"tomcat\\\"/>\n<role rolename=\\\"manager-script\\\"/>\n<role rolename=\\\"manager-gui\\\"/>\n<role rolename=\\\"manager\\\"/>\n<role rolename=\\\"admin-gui\\\"/>\n<user username=\\\"tomcat\\\" password=\\\"tomcat\\\" roles=\\\"tomcat\\\"/>\n<user username=\\\"$2\\\" password=\\\"$3\\\" roles=\\\"tomcat,manager-script,manager-gui,admin-gui\\\"/>\n</tomcat-users>\" | tee -a /tmp/tomcat-users.xml\n\nmv /tmp/tomcat-users.xml /etc/tomcat\nchown root:tomcat /etc/tomcat/tomcat-users.xml\nchmod 0640 /etc/tomcat/tomcat-users.xml\n\n# Restart httpd and tomcat servers\nservice tomcat restart \nservice httpd restart \n\n# Update SSHd config to not use passwords and set default umask to be 002\ncp /etc/ssh/sshd_config /etc/ssh/ORIG_sshd_config\nsed -i 's,PasswordAuthentication yes,PasswordAuthentication no,g' /etc/ssh/sshd_config\necho \"Match User \"$1 | tee -a /etc/ssh/sshd_config\necho \"    ForceCommand internal-sftp -u 002\" | tee -a /etc/ssh/sshd_config\n\n# Change group of user to same as Tomcat \ngpasswd -d $1 $1 \ngpasswd -a $1 tomcat \nusermod -g tomcat $1 \n\n\n# Configure the default umask for SSH to enable RW for user and group\ncp /etc/pam.d/sshd /etc/pam.d/ORIG_sshd\necho \"session optional pam_umask.so umask=002\" | tee -a /etc/pam.d/sshd\n\n# Then start the SSH daemon:\nsystemctl daemon-reload \nsystemctl start sshd.service \nsystemctl enable sshd.service \n\n# Open Red Hat software firewall for port 22:\nfirewall-cmd --zone=public --add-port=22/tcp --permanent \nfirewall-cmd --reload \n\n# Create an RSA public and private key for SSH\nmkdir /home/$1/.ssh\nssh-keygen -q -N $4 -f /home/$1/.ssh/id_rsa \ncp /home/$1/.ssh/id_rsa.pub authorized_keys\nchown -R $1:tomcat /home/$1/.ssh\necho \"SSH User name:  \"$1 | tee /home/$1/vsts_ssh_info\necho \"SSH passphrase: \"$4 | tee /home/$1/vsts_ssh_info\necho \"SSH Private key:\" | tee /home/$1/vsts_ssh_info\ncat id_rsa | tee /home/$1/vsts_ssh_info\nchown $1:tomcat /home/$1/vsts_ssh_info\n\n\necho \"Installing and Configuring FTP\" \n\n# Install the vsftp package (i.e. FTP) and create some needed directories:\nyum install -y vsftpd \nmkdir /var/run/vsftpd\nmkdir /var/run/vsftpd/empty\n\n\n# Generate an SSL self-signed certificate:\nmkdir /etc/ssl/private\n# Generate SSL self-signed certificate\necho \"\\\nUS\nNC\nRaleigh\nMicrosoft\nTeam Services\n$1\n$1@\" | tee /tmp/info.txt\n\ncat /tmp/info.txt | openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout /etc/ssl/private/vsftpd.pem -out /etc/ssl/private/vsftpd.pem\nrm -f /tmp/info.txt\n\n# Backup original and create a new vsftp conf file\ncp /etc/vsftpd/vsftpd.conf /etc/vsftpd/ORIG_vsftpd.conf\necho \"\\\nlisten=NO\nlisten_ipv6=YES\nanonymous_enable=NO\nlocal_enable=YES\nwrite_enable=YES\nlocal_umask=002 # this is different than the default 022\ndirmessage_enable=YES\nuse_localtime=YES\nxferlog_enable=YES\nconnect_from_port_20=YES\nxferlog_file=/var/log/vsftpd.log\nls_recurse_enable=YES\nsecure_chroot_dir=/var/run/vsftpd/empty\npam_service_name=vsftpd\n# ftps/ssl specific cofig stuff below this line\nrsa_cert_file=/etc/ssl/private/vsftpd.pem\nrsa_private_key_file=/etc/ssl/private/vsftpd.pem\nssl_enable=YES\nallow_anon_ssl=NO\nforce_local_data_ssl=YES\nforce_local_logins_ssl=YES\nssl_tlsv1=YES\nssl_sslv2=NO\nssl_sslv3=NO\nrequire_ssl_reuse=NO\nssl_ciphers=HIGH\ndebug_ssl=YES\npasv_enable=YES\npasv_address=`wget http://ipinfo.io/ip -qO -`\npasv_min_port=13450\npasv_max_port=13454\" | tee /tmp/vsftpd.conf\n\nmv /tmp/vsftpd.conf /etc/vsftpd\nchmod 0600 /etc/vsftpd/vsftpd.conf\n\n# Configure SELinux to use Linux ACL's for file protection\nsetsebool -P allow_ftpd_full_access 1 \n\n# Open the ftp ports on the Red Hat software firewall:\nfirewall-cmd --zone=public --add-port=21/tcp --permanent \nfirewall-cmd --zone=public --add-port=13450/tcp --permanent \nfirewall-cmd --zone=public --add-port=13451/tcp --permanent \nfirewall-cmd --zone=public --add-port=13452/tcp --permanent \nfirewall-cmd --zone=public --add-port=13453/tcp --permanent \nfirewall-cmd --zone=public --add-port=13454/tcp --permanent \nfirewall-cmd --reload \n\n# Seeing a race condition timing error so sleep to deplay\nsleep 20\n\n# Restart the ftp service:\nservice vsftpd restart \nsystemctl enable vsftpd \n", "num_lines": 237}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\n# $1 - VM Host User Name\n\nsudo /bin/date +%H:%M:%S > /home/$1/install.progress.txt\necho \"ooooo      TOMCAT INSTALL      ooooo\" >> /home/$1/install.progress.txt\n\necho \"Initial Tomcat setup\" >> /home/$1/install.progress.txt\n\n# Install Apache2, Tomcat7 and mod-jk packages on an updated OS image\nsudo apt update\nsudo apt upgrade -y\nsudo apt-get install -y apache2\nsudo apt-get install -y tomcat7\nsudo apt-get install -y tomcat7-admin\nsudo apt-get install -y libapache2-mod-jk\n\n# Uncomment the Connector port=\"8009\" line\nsudo cp /etc/tomcat7/server.xml /etc/tomcat7/ORIG_server.xml\nsudo sed -i '/Connector on port 8009 -->/{n;d}' /etc/tomcat7/server.xml\nsudo sed -i '/protocol=\\\"AJP\\/1.3\\\" redirectPort=\\\"8443\\\"/{n;d}' /etc/tomcat7/server.xml\n\n# Create a new JkWorkers workers.propeties file\nsudo echo \"# Define 1 real worker using ajp13\" > /etc/apache2/workers.properties\nsudo echo \"worker.list=worker1\" >> /etc/apache2/workers.properties\nsudo echo \"worker.worker1.type=ajp13\" >> /etc/apache2/workers.properties\nsudo echo \"worker.worker1.host=localhost\" >> /etc/apache2/workers.properties\nsudo echo \"worker.worker1.port=8009\" >> /etc/apache2/workers.properties\n\n# Point to the newly created above JkWorkers file\nsudo cp /etc/apache2/mods-available/jk.conf /etc/apache2/mods-available/ORIG_jk.conf\nsudo sed -i 's,/etc/libapache2-mod-jk/workers.properties,/etc/apache2/workers.properties,g' /etc/apache2/mods-available/jk.conf\n\n# Specify the mod-jk worker\nsudo cp /etc/apache2/sites-enabled/000-default.conf /etc/apache2/sites-enabled/ORIG_000-default.conf\nsudo sed -i 's,</VirtualHost>,JkMount /* worker1\\n</VirtualHost>,g' /etc/apache2/sites-enabled/000-default.conf\n\n# Create a link to the Tomcat manager\ncd /var/lib/tomcat7/webapps\nsudo ln -s /usr/share/tomcat7-admin/manager manager\n\n# Update the permissions on the Tomcat Webapps and install directory\nsudo chown -R tomcat7.tomcat7 /var/lib/tomcat7/webapps\nsudo chown tomcat7.tomcat7 /usr/share/tomcat7\n\n# Change the default Tomcat umask to be 002 to enable owner and group access\nsudo cp /etc/init.d/tomcat7 /etc/init.d/ORIG_tomcat7\nsudo sed -i 's,umask 022,umask 002,g' /etc/init.d/tomcat7\n\n# Restart the tomcat7 and apache2 services\nsudo systemctl daemon-reload\nsudo /etc/init.d/tomcat7 restart\nsudo /etc/init.d/apache2 restart\n\necho \"Done.\" >> /home/$1/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n\necho \"Configuring Tomcat manager\" >> /home/$1/install.progress.txt\n\n# Setup permissions for the Tomcat manager\nsudo mv /etc/tomcat7/tomcat-users.xml /etc/tomcat7/ORIG_tomcat-users.xml\nsudo echo \"<?xml version='1.0' encoding='utf-8'?>\" >> /tmp/tomcat-users.xml\nsudo echo \"<tomcat-users>\" >> /tmp/tomcat-users.xml\nsudo echo \"<role rolename=\\\"tomcat\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<role rolename=\\\"manager-script\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<role rolename=\\\"manager-gui\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<role rolename=\\\"manager\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<role rolename=\\\"admin-gui\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<user username=\\\"tomcat\\\" password=\\\"tomcat\\\" roles=\\\"tomcat\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"<user username=\\\"$2\\\" password=\\\"$3\\\" roles=\\\"tomcat,manager-script,manager-gui,admin-gui\\\"/>\" >> /tmp/tomcat-users.xml\nsudo echo \"</tomcat-users>\" >> /tmp/tomcat-users.xml\nsudo mv /tmp/tomcat-users.xml /etc/tomcat7\nsudo chown root.tomcat7 /etc/tomcat7/tomcat-users.xml\nsudo chmod 0640 /etc/tomcat7/tomcat-users.xml\n\n# Restart the tomcat7 and apache2 services\nsudo /etc/init.d/tomcat7 restart\nsudo /etc/init.d/apache2 restart\n\necho \"Done.\" >> /home/$1/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n\necho \"Configuring SSH\" >> /home/$1/install.progress.txt\n\n# Change group of user to same as Tomcat 7\nsudo usermod -g tomcat7 $1\n\n# Change the default SSH umask to be 002 to enable owner and group access\nsudo cp /etc/pam.d/sshd /etc/pam.d/ORIG_sshd\nsudo sed -i 's,common-session,common-session\\nsession optional pam_umask.so umask=002,g' /etc/pam.d/sshd\n\n# Reload and restart the SSHD service\nsudo systemctl daemon-reload\nsudo service sshd restart\n\n# Create an RSA public and private key for SSH\nssh-keygen -q -N $4 -f /home/$1/.ssh/id_rsa\ncd /home/$1/.ssh\nsudo cp id_rsa.pub authorized_keys\nchown -R $1.tomcat7 .\nchown -R $1.tomcat7 *\necho \"SSH User name:  \"$1 > /home/$1/vsts_ssh_info\necho \"SSH passphrase: \"$4 >> /home/$1/vsts_ssh_info\necho \"SSH Private key:\" >> /home/$1/vsts_ssh_info\ncat id_rsa >> /home/$1/vsts_ssh_info\nchown $1.tomcat7 /home/$1/vsts_ssh_info\n\necho \"Done.\" >> /home/$1/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n\necho \"Installing and Configuring FTP\" >> /home/$1/install.progress.txt\n\n# Install vsftpd\nsudo apt-get install -y vsftpd\n\n# Generate SSL self-signed certificate\necho US > /tmp/info.txt\necho NC >> /tmp/info.txt\necho Raleigh >> /tmp/info.txt\necho Microsoft >> /tmp/info.txt\necho Team Services >> /tmp/info.txt\necho $1  >> /tmp/info.txt\necho $1@  >> /tmp/info.txt\ncat /tmp/info.txt | sudo openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout /etc/ssl/private/vsftpd.pem -out /etc/ssl/private/vsftpd.pem\nsudo rm -f /tmp/info.txt\n\n# Backup original and create a new vsftp conf file\nsudo cp /etc/vsftpd.conf /etc/ORIG_vsftpd.conf\nsudo echo \"listen=NO\" > /tmp/vsftpd.conf\nsudo echo \"listen_ipv6=YES\" >> /tmp/vsftpd.conf\nsudo echo \"anonymous_enable=NO\" >> /tmp/vsftpd.conf\nsudo echo \"local_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"write_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"local_umask=002 # this is different than the default 022\" >> /tmp/vsftpd.conf\nsudo echo \"dirmessage_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"use_localtime=YES\" >> /tmp/vsftpd.conf\nsudo echo \"xferlog_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"connect_from_port_20=YES\" >> /tmp/vsftpd.conf\nsudo echo \"xferlog_file=/var/log/vsftpd.log\" >> /tmp/vsftpd.conf\nsudo echo \"ls_recurse_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"secure_chroot_dir=/var/run/vsftpd/empty\" >> /tmp/vsftpd.conf\nsudo echo \"pam_service_name=vsftpd\" >> /tmp/vsftpd.conf\nsudo echo \"# ftps/ssl specific cofig stuff below this line\" >> /tmp/vsftpd.conf\nsudo echo \"rsa_cert_file=/etc/ssl/private/vsftpd.pem\" >> /tmp/vsftpd.conf\nsudo echo \"rsa_private_key_file=/etc/ssl/private/vsftpd.pem\" >> /tmp/vsftpd.conf\nsudo echo \"ssl_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"allow_anon_ssl=NO\" >> /tmp/vsftpd.conf\nsudo echo \"force_local_data_ssl=YES\" >> /tmp/vsftpd.conf\nsudo echo \"force_local_logins_ssl=YES\" >> /tmp/vsftpd.conf\nsudo echo \"ssl_tlsv1=YES\" >> /tmp/vsftpd.conf\nsudo echo \"ssl_sslv2=NO\" >> /tmp/vsftpd.conf\nsudo echo \"ssl_sslv3=NO\" >> /tmp/vsftpd.conf\nsudo echo \"require_ssl_reuse=NO\" >> /tmp/vsftpd.conf\nsudo echo \"ssl_ciphers=HIGH\" >> /tmp/vsftpd.conf\nsudo echo \"debug_ssl=YES\" >> /tmp/vsftpd.conf\nsudo echo \"pasv_enable=YES\" >> /tmp/vsftpd.conf\nsudo echo \"pasv_address=`wget http://ipinfo.io/ip -qO -`\" >> /tmp/vsftpd.conf\nsudo echo \"pasv_min_port=13450\" >> /tmp/vsftpd.conf\nsudo echo \"pasv_max_port=13454\" >> /tmp/vsftpd.conf\nsudo mv /tmp/vsftpd.conf /etc\n\n# Restart vsftp server\nsudo service vsftpd restart\n\necho \"ALL DONE!\" >> /home/$1/install.progress.txt\nsudo /bin/date +%H:%M:%S >> /home/$1/install.progress.txt\n\n\necho \"These original files were saved in case you want to return to default settings:\" >> /home/$1/install.progress.txt\nsudo find /etc -name ORIG_* -print >> /home/$1/install.progress.txt\n\n\nchown $1.tomcat7 /home/$1/install.progress.txt\n\n", "num_lines": 178}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nadddate() {\n    while IFS= read -r line; do\n        printf '%s %s\\n' \"$(date \"+%Y-%m-%d %H:%M:%S\")\" \"$line\";\n    done\n}\n\necho \"WILDFLY 18.0.1.Final Standalone Intallation Start...\" | adddate >> wildfly.install.log\n/bin/date +%H:%M:%S  >> wildfly.install.log\n\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToDownload=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation$pathToFile/$fileToDownload$token\"\n\nWILDFLY_USER=$9\nWILDFLY_PASSWORD=${10}\nIP_ADDR=$(hostname -I)\n\necho \"WILDFLY_USER: \" ${WILDFLY_USER} | adddate >> wildfly.install.log\n\necho \"WILDFLY Downloading...\" | adddate >> wildfly.install.log\necho \"yum install -y git unzip java\" | adddate >> wildfly.install.log\nyum install -y git unzip java | adddate >> wildfly.install.log 2>&1\necho \"yum -y install wget\" | adddate >> wildfly.install.log\nyum -y install wget | adddate >> wildfly.install.log 2>&1\nWILDFLY_RELEASE=\"18.0.1\"\necho \"wget https://download.jboss.org/wildfly/$WILDFLY_RELEASE.Final/wildfly-$WILDFLY_RELEASE.Final.tar.gz\" | adddate >> wildfly.install.log\nwget https://download.jboss.org/wildfly/$WILDFLY_RELEASE.Final/wildfly-$WILDFLY_RELEASE.Final.tar.gz >> wildfly.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Downloading WildFly Failed\" | adddate >> wildfly.install.log; exit $flag;  fi\necho \"tar xvf wildfly-$WILDFLY_RELEASE.Final.tar.gz\" | adddate >> wildfly.install.log\ntar xvf wildfly-$WILDFLY_RELEASE.Final.tar.gz | adddate >> wildfly.install.log 2>&1\n\necho \"echo \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config\" | adddate >> wildfly.install.log\necho \"AllowTcpForwarding no\" >> /etc/ssh/sshd_config | adddate >> wildfly.install.log 2>&1\necho \"systemctl restart sshd\" | adddate >> wildfly.install.log\nsystemctl restart sshd | adddate >> wildfly.install.log 2>&1\n\necho \"Sample app deploy...\" | adddate >> wildfly.install.log\necho \"wget $fileUrl\" | adddate >> wildfly.install.log\nwget $fileUrl >> wildfly.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! Sample Application Download Failed\" | adddate >> wildfly.install.log; exit $flag;  fi\necho \"/bin/cp -rf ./JBoss-EAP_on_Azure.war ./wildfly-$WILDFLY_RELEASE.Final/standalone/deployments/\" | adddate >> wildfly.install.log\n/bin/cp -rf ./JBoss-EAP_on_Azure.war ./wildfly-$WILDFLY_RELEASE.Final/standalone/deployments/ | adddate >> wildfly.install.log 2>&1\n\necho \"Configuring WILDFLY managment user...\" | adddate >> wildfly.install.log\necho \"./wildfly-$WILDFLY_RELEASE.Final/bin/add-user.sh -u WILDFLY_USER -p WILDFLY_PASSWORD -g 'guest,mgmtgroup'\" | adddate >> wildfly.install.log\n./wildfly-$WILDFLY_RELEASE.Final/bin/add-user.sh -u $WILDFLY_USER -p $WILDFLY_PASSWORD -g 'guest,mgmtgroup' >> wildfly.install.log 2>&1\nflag=$?; if [ $flag != 0 ] ; then echo  \"ERROR! WildFly management user configuration Failed\" | adddate >> wildfly.install.log; exit $flag;  fi\n\necho \"Start WILDFLY 18.0.1.Final instance...\" | adddate >> wildfly.install.log\necho \"./wildfly-$WILDFLY_RELEASE.Final/bin/standalone.sh -b $IP_ADDR -bmanagement $IP_ADDR &\" | adddate >> wildfly.install.log\n./wildfly-$WILDFLY_RELEASE.Final/bin/standalone.sh -b $IP_ADDR -bmanagement $IP_ADDR | adddate >> wildfly.install.log 2>&1 &\nsleep 20\n\necho \"Configure firewall for ports 8080, 9990...\" | adddate >> wildfly.install.log\necho \"firewall-cmd --zone=public --add-port=8080/tcp --permanent\" | adddate >> wildfly.install.log\nfirewall-cmd --zone=public --add-port=8080/tcp --permanent | adddate >> wildfly.install.log 2>&1\necho \"firewall-cmd --zone=public --add-port=9990/tcp --permanent\" | adddate >> wildfly.install.log\nfirewall-cmd --zone=public --add-port=9990/tcp --permanent | adddate >> wildfly.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> wildfly.install.log\nfirewall-cmd --reload | adddate >> wildfly.install.log 2>&1\n\necho \"Open WILDFLY software firewall for port 22...\" | adddate >> wildfly.install.log\necho \"firewall-cmd --zone=public --add-port=22/tcp --permanent\" | adddate >> wildfly.install.log\nfirewall-cmd --zone=public --add-port=22/tcp --permanent | adddate >> wildfly.install.log 2>&1\necho \"firewall-cmd --reload\" | adddate >> wildfly.install.log\nfirewall-cmd --reload | adddate >> wildfly.install.log 2>&1\n\necho \"WILDFLY 18.0.1.Final Standalone Intallation End...\" | adddate >> wildfly.install.log\n/bin/date +%H:%M:%S >> wildfly.install.log\n", "num_lines": 87}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script is only tested on CentOS 6.5 and Ubuntu 12.04 LTS with Percona XtraDB Cluster 5.6.\n# You can customize variables such as MOUNTPOINT, RAIDCHUNKSIZE and so on to your needs.\n# You can also customize it to work with other Linux flavours and versions.\n# If you customize it, copy it to either Azure blob storage or Github so that Azure\n# custom script Linux VM extension can access it, and specify its location in the\n# parameters of DeployPXC powershell script or runbook or Azure Resource Manager CRP template.\n\nNODEID=${1}\nNODEADDRESS=${2}\nMYCNFTEMPLATE=${3}\nRPLPWD=${4}\nROOTPWD=${5}\nPROBEPWD=${6}\nMASTERIP=${7}\nDBNAME=${8}\n\nMOUNTPOINT=\"/datadrive\"\nRAIDCHUNKSIZE=512\n\nRAIDDISK=\"/dev/md127\"\nRAIDPARTITION=\"/dev/md127p1\"\n# An set of disks to ignore from partitioning and formatting\nBLACKLIST=\"/dev/sda|/dev/sdb\"\n\ncheck_os() {\n    grep ubuntu /proc/version > /dev/null 2>&1\n    isubuntu=${?}\n    grep centos /proc/version > /dev/null 2>&1\n    iscentos=${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_disk_count() {\n    DISKCOUNT=0\n    for DISK in \"${DISKS[@]}\";\n    do\n        DISKCOUNT+=1\n    done;\n    echo \"$DISKCOUNT\"\n}\n\ncreate_raid0_ubuntu() {\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        wget --no-cache http://mirrors.cat.pdx.edu/ubuntu/pool/main/m/mdadm/mdadm_3.2.5-5ubuntu4_amd64.deb\n        dpkg -i mdadm_3.2.5-5ubuntu4_amd64.deb\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ncreate_raid0_centos() {\n    echo \"Creating raid0\"\n    yes | mdadm --create \"$RAIDDISK\" --name=data --level=0 --chunk=\"$RAIDCHUNKSIZE\" --raid-devices=\"$DISKCOUNT\" \"${DISKS[@]}\"\n    mdadm --detail --verbose --scan > /etc/mdadm.conf\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    DISK=${1}\n    echo \"Partitioning disk $DISK\"\n    echo \"n\np\n1\n\n\nw\n\" | fdisk \"${DISK}\"\n#> /dev/null 2>&1\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${DISK}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nconfigure_disks() {\n\tls \"${MOUNTPOINT}\"\n\tif [ ${?} -eq 0 ]\n\tthen\n\t\treturn\n\tfi\n    DISKS=($(scan_for_new_disks))\n    echo \"Disks are ${DISKS[@]}\"\n    declare -i DISKCOUNT\n    DISKCOUNT=$(get_disk_count)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT -gt 1 ];\n    then\n    \tif [ $iscentos -eq 0 ];\n    \tthen\n       \t    create_raid0_centos\n    \telif [ $isubuntu -eq 0 ];\n    \tthen\n            create_raid0_ubuntu\n    \tfi\n        do_partition ${RAIDDISK}\n        PARTITION=\"${RAIDPARTITION}\"\n    else\n        DISK=\"${DISKS[0]}\"\n        do_partition ${DISK}\n        PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n    fi\n\n    echo \"Creating filesystem on ${PARTITION}.\"\n    mkfs -t ext4 -E lazy_itable_init=1 ${PARTITION}\n    mkdir \"${MOUNTPOINT}\"\n    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n    mount \"${MOUNTPOINT}\"\n}\n\nopen_ports() {\n    iptables -A INPUT -p tcp -m tcp --dport 3306 -j ACCEPT\n    iptables -A INPUT -p tcp -m tcp --dport 9200 -j ACCEPT\n    iptables-save\n}\n\ndisable_apparmor_ubuntu() {\n    /etc/init.d/apparmor teardown\n    update-rc.d -f apparmor remove\n}\n\ndisable_selinux_centos() {\n    sed -i 's/^SELINUX=.*/SELINUX=disabled/I' /etc/selinux/config\n    setenforce 0\n}\n\nconfigure_network() {\n    open_ports\n    if [ $iscentos -eq 0 ];\n    then\n        disable_selinux_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        disable_apparmor_ubuntu\n    fi\n}\n\ncreate_mycnf() {\n    wget \"${MYCNFTEMPLATE}\" -O /etc/my.cnf\n    sed -i \"s/^server_id=.*/server_id=${NODEID}/I\" /etc/my.cnf\n    sed -i \"s/^report-host=.*/report-host=${NODEADDRESS}/I\" /etc/my.cnf\n}\n\ninstall_mysql_ubuntu() {\n    dpkg -s mysql-5.6\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    apt-get update\n    export DEBIAN_FRONTEND=noninteractive\n    wget -O mysql-5.6.deb https://dev.mysql.com/get/Downloads/MySQL-5.6/mysql-server_5.6.26-1ubuntu15.04_amd64.deb\n    dpkg -i mysql-5.6.deb\n    apt-get -y install xinetd\n}\n\ninstall_mysql_centos() {\n    rpm -qa |grep MySQL-server-5.6.26-1.el6.x86_64\n    if [ ${?} -eq 0 ];\n    then\n        return\n    fi\n    echo \"installing mysql\"\n    wget https://dev.mysql.com/get/Downloads/MySQL-5.6/MySQL-5.6.26-1.el6.x86_64.rpm-bundle.tar\n    tar -xvf MySQL-5.6.26-1.el6.x86_64.rpm-bundle.tar\n\tcurlib=$(rpm -qa |grep mysql-libs-)\n    rpm -e --nodeps $curlib\n    rpm -ivh MySQL-server-5.6.26-1.el6.x86_64.rpm\n    rpm -ivh MySQL-client-5.6.26-1.el6.x86_64.rpm\n\twget http://dev.mysql.com/get/Downloads/Connector-Python/mysql-connector-python-2.0.4-1.el6.noarch.rpm\n\trpm -ivh mysql-connector-python-2.0.4-1.el6.noarch.rpm\n\twget http://dev.mysql.com/get/Downloads/MySQLGUITools/mysql-utilities-1.5.5-1.el6.noarch.rpm\n\trpm -ivh mysql-utilities-1.5.5-1.el6.noarch.rpm\n    yum -y install xinetd\n}\n\ncreate_mysql_probe() {\nif [ ${NODEID} -eq 1 ];\nthen\n# create a probe user with minimum privilege\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nCREATE USER 'probeuser'@'%' IDENTIFIED BY '${PROBEPWD}';\nGRANT SELECT ON *.* TO 'probeuser'@'%';\nFLUSH PRIVILEGES;\nEOF\nfi\n\n# create a probe script\n    cat <<EOF >/usr/bin/mysqlprobe\n#!/bin/bash\n\nMYSQL_HOST=\"${NODEADDRESS}\"\nMYSQL_USERNAME=\"probeuser\"\nMYSQL_PASSWORD='${PROBEPWD}'\n\nERROR_MSG=\\`/usr/bin/mysqladmin --host=\\${MYSQL_HOST} --port=3306 --user=\\${MYSQL_USERNAME} --password=\\${MYSQL_PASSWORD} status 2>/dev/null\\`\n#ERROR_MSG=\\`/usr/bin/mysql --host=\\${MYSQL_HOST} --port=3306 --user=\\${MYSQL_USERNAME} --password=\\${MYSQL_PASSWORD} -e \"show databases;\" 2>/dev/null\\`\n\nif [ \"\\$ERROR_MSG\" != \"\" ]\nthen\n        # mysql is fine, return http 200\n        echo -en \"HTTP/1.1 200 OK\\r\\n\"\n        echo -en \"Content-Type: Content-Type: text/plain\\r\\n\"\n        echo -en \"Connection: close\\r\\n\"\n        echo -en \"Content-Length: 19\\r\\n\"\n        echo -en \"\\r\\n\"\n        echo -en \"MySQL is running.\\r\\n\"\n        sleep 0.1\n        exit 0\nelse\n        # mysql is down, return http 503\n        echo -en \"HTTP/1.1 503 Service Unavailable\\r\\n\"\n        echo -en \"Content-Type: Content-Type: text/plain\\r\\n\"\n        echo -en \"Connection: close\\r\\n\"\n        echo -en \"Content-Length: 16\\r\\n\"\n        echo -en \"\\r\\n\"\n        echo -en \"MySQL is down.\\r\\n\"\n        sleep 0.1\n        exit 1\nfi\nEOF\n\nchmod 755 /usr/bin/mysqlprobe\n\n# create a http service that runs the script\n    cat <<EOF >/etc/xinetd.d/mysqlprobe\n# default: on\n# description: mysqlprobe\nservice mysqlprobe\n{\n        disable = no\n        flags = REUSE\n        socket_type = stream\n        port = 9200\n        wait = no\n        user = nobody\n        server = /usr/bin/mysqlprobe\n        log_on_failure += USERID\n        only_from = 0.0.0.0/0\n        per_source = UNLIMITED\n}\nEOF\n\n# add the service to xinet\n    grep \"mysqlprobe\" /etc/services >/dev/null 2>&1\n    if [ ${?} -ne 0 ];\n    then\n        sed -i \"\\$amysqlprobe  9200\\/tcp  #mysqlprobe\" /etc/services\n    fi\n    service xinetd restart\n}\n\nconfigure_mysql_replication() {\nif [ ${NODEID} -eq 1 ];\nthen\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nCREATE USER 'rpluser'@'%' IDENTIFIED BY '${RPLPWD}';\nGRANT REPLICATION SLAVE ON *.* TO 'rpluser'@'%';\nFLUSH PRIVILEGES;\nEOF\nelse\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nchange master to master_host='${MASTERIP}', master_port=3306, master_user='rpluser', master_password='${RPLPWD}', master_auto_position=1;\nSTART slave;\nEOF\nfi\n}\n\nconfigure_mysql() {\n    /etc/init.d/mysql status\n    if [ ${?} -eq 0 ];\n    then\n       return\n    fi\n\n    mkdir \"${MOUNTPOINT}/mysql\"\n    ln -s \"${MOUNTPOINT}/mysql\" /var/lib/mysql\n    chmod o+x /var/lib/mysql\n    groupadd mysql\n    useradd -r -g mysql mysql\n    chmod o+x \"${MOUNTPOINT}/mysql\"\n    chown -R mysql:mysql \"${MOUNTPOINT}/mysql\"\n\n    if [ $iscentos -eq 0 ];\n    then\n        install_mysql_centos\n    elif [ $isubuntu -eq 0 ];\n    then\n        install_mysql_ubuntu\n    fi\n\n    create_mycnf\n    /etc/init.d/mysql start\n    mysql_secret=$(awk '/password/{print $NF}' ${HOME}/.mysql_secret)\n    mysqladmin -u root --password=${mysql_secret} password ${ROOTPWD}\nif [ ${NODEID} -eq 1 ];\nthen\n    mysql -u root -p\"${ROOTPWD}\" <<EOF\nSET PASSWORD FOR 'root'@'127.0.0.1' = PASSWORD('${ROOTPWD}');\nSET PASSWORD FOR 'root'@'::1' = PASSWORD('${ROOTPWD}');\nCREATE USER 'admin'@'%' IDENTIFIED BY '${ROOTPWD}';\nGRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' with grant option;\nFLUSH PRIVILEGES;\nCREATE DATABASE ${DBNAME};\nEOF\nfi\n    configure_mysql_replication\n    create_mysql_probe\n}\n\ncheck_os\nif [ $iscentos -ne 0 ] && [ $isubuntu -ne 0 ];\nthen\n    echo \"unsupported operating system\"\n    exit 1\nelse\n    configure_network\n    configure_disks\n    configure_mysql\n\t#yum -y erase hypervkvpd.x86_64\n\t#yum -y install microsoft-hyper-v\n#\techo \"/sbin/reboot\" | /usr/bin/at now + 3 min >/dev/null 2>&1\nfi\n\n", "num_lines": 370}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get -y update\n\nlogger \"Installing WordPress\"\n\n# Set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# Install the LAMP stack and WordPress\napt-get -y install apache2 mysql-server php libapache2-mod-php php-mysql php-imagick php-gd php-mbstring php-zip php-json wordpress\n\n# Setup WordPress\ngzip -d /usr/share/doc/wordpress/examples/setup-mysql.gz\nbash /usr/share/doc/wordpress/examples/setup-mysql -n wordpress localhost\n\nln -s /usr/share/wordpress /var/www/html/wordpress\nmv /etc/wordpress/config-localhost.php /etc/wordpress/config-default.php\n\nsed \"9idefine('FS_METHOD', 'direct');\" /etc/wordpress/config-default.php\n\n# Restart Apache\napachectl restart\n\nlogger \"Done installing WordPress; open /wordpress to configure\"\n", "num_lines": 30}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n PARAMS=(Azul_Zulu_OpenJDK-7-JDK Azul_Zulu_OpenJDK-7-JRE Azul_Zulu_OpenJDK-7-JRE-Headless\n         Azul_Zulu_OpenJDK-8-JDK Azul_Zulu_OpenJDK-8-JRE Azul_Zulu_OpenJDK-8-JRE-Headless\n         Azul_Zulu_OpenJDK-11-JDK Azul_Zulu_OpenJDK-11-JRE Azul_Zulu_OpenJDK-11-JRE-Headless\n         Azul_Zulu_OpenJDK-13-JDK Azul_Zulu_OpenJDK-13-JRE Azul_Zulu_OpenJDK-13-JRE-Headless)\n\n ZULU_PACKS=(zulu-7-azure-jdk zulu-7-azure-jre zulu-7-azure-jre-headless\n             zulu-8-azure-jdk zulu-8-azure-jre zulu-8-azure-jre-headless\n             zulu-11-azure-jdk zulu-11-azure-jre zulu-11-azure-jre-headless\n             zulu-13-azure-jdk zulu-13-azure-jre zulu-13-azure-jre-headless)\n\n ZULU_DIRS=(zulu-7-azure-amd64 zre-7-azure-amd64 zre-hl-7-azure-amd64\n            zulu-8-azure-amd64 zre-8-azure-amd64 zre-hl-8-azure-amd64\n            zulu-11-azure-amd64 zre-11-azure-amd64 zre-hl-11-azure-amd64\n            zulu-13-azure-amd64 zre-13-azure-amd64 zre-hl-13-azure-amd64)\n\n for idx in ${!PARAMS[@]}\n do\n    if [ $1 == ${PARAMS[$idx]} ]\n    then\n       ZULU_PACK=${ZULU_PACKS[$idx]}\n       ZULU_DIR=${ZULU_DIRS[$idx]}\n       break\n    fi\n done\n\n apt-get update\n apt-get -y --no-install-recommends install dirmngr gnupg software-properties-common\n apt-get -y dist-upgrade\n apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 0x219BD9C9\n apt-add-repository \"deb http://repos.azul.com/azure-only/zulu/apt stable main\"\n apt-get update\n apt-get -y --no-install-recommends install $ZULU_PACK\n rm -rf /var/lib/apt/lists/*\n\n echo \"export JAVA_HOME=/usr/lib/jvm/$ZULU_DIR\" >> /etc/bash.bashrc\n\n", "num_lines": 39}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n PARAMS=(Azul_Zulu_OpenJDK-7-JDK Azul_Zulu_OpenJDK-7-JRE Azul_Zulu_OpenJDK-7-JRE-Headless\n         Azul_Zulu_OpenJDK-8-JDK Azul_Zulu_OpenJDK-8-JRE Azul_Zulu_OpenJDK-8-JRE-Headless\n         Azul_Zulu_OpenJDK-11-JDK Azul_Zulu_OpenJDK-11-JRE Azul_Zulu_OpenJDK-11-JRE-Headless\n         Azul_Zulu_OpenJDK-13-JDK Azul_Zulu_OpenJDK-13-JRE Azul_Zulu_OpenJDK-13-JRE-Headless)\n\n ZULU_PACKS=(zulu-7-azure-jdk zulu-7-azure-jre zulu-7-azure-jre-headless\n             zulu-8-azure-jdk zulu-8-azure-jre zulu-8-azure-jre-headless\n             zulu-11-azure-jdk zulu-11-azure-jre zulu-11-azure-jre-headless\n             zulu-13-azure-jdk zulu-13-azure-jre zulu-13-azure-jre-headless)\n\n ZULU_DIRS=(zulu-7-azure zre-7-azure zre-hl-7-azure\n            zulu-8-azure zre-8-azure zre-hl-8-azure\n            zulu-11-azure zre-11-azure zre-hl-11-azure\n            zulu-13-azure zre-13-azure zre-hl-13-azure)\n\n for idx in ${!PARAMS[@]}\n do\n    if [ $1 == ${PARAMS[$idx]} ]\n    then\n       ZULU_PACK=${ZULU_PACKS[$idx]}\n       ZULU_DIR=${ZULU_DIRS[$idx]}\n       break\n    fi\n done\n\n rpm --import http://repos.azul.com/azul-repo.key\n curl http://repos.azul.com/azure-only/zulu-azure.repo -o /etc/yum.repos.d/zulu-azure.repo\n yum -q -y update\n yum -q -y upgrade\n yum -q -y install $ZULU_PACK\n\n echo \"export JAVA_HOME=/usr/lib/jvm/$ZULU_DIR\" >> /etc/bash.bashrc\n\n", "num_lines": 36}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash -e\nwhile getopts \"a:t:p:f:\" opt; do\n    case $opt in\n        a)\n            artifactsLocation=$OPTARG #base uri of the file including the container\n        ;;\n        t)\n            token=$OPTARG #saToken for the uri - use \"?\" if the artifact is not secured via sasToken\n        ;;\n        p)\n            pathToFile=$OPTARG #path to the file relative to artifactsLocation\n        ;;\n        f)\n            fileToInstall=$OPTARG #filename of the file to download from storage\n        ;;\n    esac\ndone\n\nfileUrl=\"$artifactsLocation/$pathToFile/$fileToInstall$token\"\nstagingDir=\"/staging\"\n\nmkdir -v \"$stagingDir\"\n\necho \"....................\"\necho \"path: $stagingDir/$fileToInstall\"\necho \"....................\"\necho \"uri: $fileUrl\"\necho \"....................\"\n\ncurl -v -o \"$stagingDir/$fileToInstall\" $fileUrl\n", "num_lines": 31}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "WORKSPACE_ID=$1\nPRIMARYKEY=$2\nARTIFACTS_LOCATION=$3\nDNS_NAME=$4\nSAS_TOKEN=$5\n\nCERTS_PATH=/etc/letsencrypt/live/$DNS_NAME/\n\n\n# Install required packages\napt update\napt install rsyslog-gnutls # For TLS support on rsyslog\n\napt install snapd # Recommended to install certbot\nsnap install core\nsnap refresh core\nsnap install --classic certbot # To generate TLS certificates\n\n\n# Get rsyslog configuration\nwget $ARTIFACTS_LOCATION/configs/rsyslog.conf$SAS_TOKEN\n\nmv rsyslog.conf /etc/\n\n\n# Install Sentinel agent\nwget https://raw.githubusercontent.com/Microsoft/OMS-Agent-for-Linux/master/installer/scripts/onboard_agent.sh && sh onboard_agent.sh -w $WORKSPACE_ID -s $PRIMARYKEY -d opinsights.azure.com\n\n\n# Generate TLS certificates\nln -s /snap/bin/certbot /usr/bin/certbot\n\ncertbot certonly --standalone --register-unsafely-without-email -n --agree-tos --domain $DNS_NAME\n\n\n# Move certificates in rsyslog config\ncp $CERTS_PATH/cert.pem $CERTS_PATH/chain.pem $CERTS_PATH/privkey.pem /etc/rsyslog.d/\n\n\n# Restart rsyslog service\nservice rsyslog restart\n", "num_lines": 42}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#The MIT License (MIT)\n#Copyright (c) Microsoft Corporation. All rights reserved.\n#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the Software), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n#THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n# Add Microsoft Repo\nwget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb\nsudo dpkg -i packages-microsoft-prod.deb\n\n# Add Official GoAccess Repository\necho \"deb http://deb.goaccess.io/ $(lsb_release -cs) main\" | sudo tee -a /etc/apt/sources.list.d/goaccess.list\nwget -O - https://deb.goaccess.io/gnugpg.key | sudo apt-key add -\n\napt-get -y install apt-transport-https\n\n# Update Packages\napt-get -y update\n\n#Install Libcurl3, unzip\napt-get -y install libcurl3 unzip\n\n#Install .Net Core current version\napt-get -y install aspnetcore-runtime-2.1\n\n# Install Log Processor Application\nsystemctl stop appgatewaylogprocessor\nsystemctl stop goaccess\nmkdir -p /var/log/azure/Microsoft.Azure.Networking.ApplicationGateway.LogProcessor\ntouch /var/log/azure/Microsoft.Azure.Networking.ApplicationGateway.LogProcessor/access.log\nmkdir -p /usr/share/appgatewaylogprocessor\nunzip -o AppGatewayLogProcessor.zip -d /usr/share/appgatewaylogprocessor/\nsh /usr/share/appgatewaylogprocessor/files/scripts/setup_application.sh\n\n# Setup the Template Params\necho $1 >> /usr/share/appgatewaylogprocessor/blobsasuri.key\nchmod 644 /usr/share/appgatewaylogprocessor/blobsasuri.key\necho $2 >> /usr/share/appgatewaylogprocessor/appgwlogsbloburlregex\nchmod 644 /usr/share/appgatewaylogprocessor/appgwlogsbloburlregex\n\n# Install the Application Gateway Log Processor & GoAccess Service\ncp /usr/share/appgatewaylogprocessor/files/appgatewaylogprocessor.service /etc/systemd/system/appgatewaylogprocessor.service\ncp /usr/share/appgatewaylogprocessor/files/goaccess.service /etc/systemd/system/goaccess.service\nsystemctl daemon-reload\nsudo systemctl enable appgatewaylogprocessor.service\nsudo systemctl enable goaccess.service\n\n# Start the Application Gateway Log Processor\nsystemctl start appgatewaylogprocessor\n\n# Install Apache2 and GoAccess\napt-get -y install libncursesw5-dev gcc make libgeoip-dev libtokyocabinet-dev build-essential\napt-get -y install apache2\nwget -q -O goaccess-1.2.tar.gz https://tar.goaccess.io/goaccess-1.2.tar.gz\ntar -xzvf goaccess-1.2.tar.gz\ncd goaccess-1.2/\n./configure --enable-utf8 --enable-geoip=legacy\nmake\nmake install\n\n# restart Apache\napachectl restart\n\n# Start GoAccess\nsystemctl start goaccess\n", "num_lines": 68}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "cp /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/sysconfig/network-scripts/ifcfg-eth1\nsed -i \"s/^DEVICE=.*/DEVICE=eth1/I\" \"/etc/sysconfig/network-scripts/ifcfg-eth1\"\ndefaultgw=$(ip route show |sed -n \"s/^default via //p\")\ndeclare -a gateway=(${defaultgw// / })\nsed -i \"\\$aGATEWAY=${gateway[0]}\" /etc/sysconfig/network\nservice network restart\n", "num_lines": 7}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "set -e\n\ngrep -v -G domain-name /etc/dhcp/dhclient.conf  > dhclient.tmp\necho \"supersede domain-name \\\"$1\\\";\"    >> dhclient.tmp\nsudo cp /etc/dhcp/dhclient.conf /etc/dhcp/dhclient.conf.old\nsudo cp dhclient.tmp /etc/dhcp/dhclient.conf\nsudo cp ddns-dhcphook /etc/dhcp/dhclient-exit-hooks.d\n\n# do dhcp update to update resolv.conf and register ddns\nsudo dhclient -v\n", "num_lines": 11}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n#\n#  only doing all the sudos as cloud-init doesn't run as root, likely better to use Azure VM Extensions\n#\n#  $1 is the forwarder, $2 is the vnet IP range\n#\n\ntouch /tmp/forwarderSetup_start\necho \"$@\" > /tmp/forwarderSetup_params\n\n#  Install Bind9\n#  https://www.digitalocean.com/community/tutorials/how-to-configure-bind-as-a-caching-or-forwarding-dns-server-on-ubuntu-14-04\nsudo apt-get update -y\nsudo apt-get install bind9 -y\n\n# configure Bind9 for forwarding\nsudo cat > named.conf.options << EndOFNamedConfOptions\nacl goodclients {\n    $2;\n    localhost;\n    localnets;\n};\n\noptions {\n        directory \"/var/cache/bind\";\n\n        recursion yes;\n\n        allow-query { goodclients; };\n\n        forwarders {\n            $1;\n        };\n        forward only;\n\n        dnssec-validation no; # needed for private dns zones\n\n        auth-nxdomain no;    # conform to RFC1035\n        listen-on { any; };\n};\nEndOFNamedConfOptions\n\nsudo cp named.conf.options /etc/bind\nsudo service bind9 restart\n\ntouch /tmp/forwarderSetup_end\n", "num_lines": 47}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nazure group create --name WindowsSecureRG --location \"West US\"\nazure group deployment create --resource-group WindowsSecureRG --template-uri https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/101-simple-windows-vm/azuredeploy.json\"\n", "num_lines": 5}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get -y update\napt-get install -y apache2\n\n", "num_lines": 6}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nhelp() {\n    echo \"This script installs/configures haproxy and keepalived on a Ubuntu VM\"\n    echo \"Options:\"\n    echo \"        -a Backend application VM hostname (multiple allowed)\"\n    echo \"        -p Backend application VM port (single, common for all application VMs)\"\n    echo \"        -l Load balancer DNS name\"\n    echo \"        -t Load balancer port\"\n    echo \"        -m HAproxy VM being configured as MASTER\"\n    echo \"        -b HAproxy VM being configured as BACKUP\"\n}\n\nwhile getopts \":a:p:l:t:m:b:\" opt; do\n    case $opt in\n        a)\n          APPVMS+=(\"$OPTARG\")\n          ;;\n\n        p)\n          APPVM_PORT=\"$OPTARG\"\n          ;;\n\n        l)\n          LBDNSNAME=\"$OPTARG\"\n          ;;\n\n        t)\n          LB_PORT=\"$OPTARG\"\n          ;;\n\n        m)\n          MASTERVM=\"$OPTARG\"\n          ;;\n\n        b)\n          BACKUPVM=\"$OPTARG\"\n          ;;\n\n        \\?) echo \"Invalid option: -$OPTARG\" >&2\n          help\n          ;;\n    esac\ndone\n\nsetup_haproxy() {\n    # Install haproxy\n    apt-get install -y software-properties-common\n    add-apt-repository -y ppa:vbernat/haproxy-1.6\n    apt-get update\n    apt-get install -y haproxy\n\n    # Enable haproxy (to be started during boot)\n    tmpf=`mktemp` && mv /etc/default/haproxy $tmpf && sed -e \"s/ENABLED=0/ENABLED=1/\" $tmpf > /etc/default/haproxy && chmod --reference $tmpf /etc/default/haproxy\n\n    # Setup haproxy configuration file\n    HAPROXY_CFG=/etc/haproxy/haproxy.cfg\n    cp -p $HAPROXY_CFG ${HAPROXY_CFG}.default\n\n    echo \"\nglobal\n    log 127.0.0.1   local1 notice\n    log 127.0.0.1   local0 info\n    chroot /var/lib/haproxy\n    user haproxy\n    group haproxy\n    daemon\n\ndefaults\n    log     global\n    mode    http\n    option  httplog\n    option  dontlognull\n    contimeout 5000\n    clitimeout 50000\n    srvtimeout 50000\n    errorfile 400 /etc/haproxy/errors/400.http\n    errorfile 403 /etc/haproxy/errors/403.http\n    errorfile 408 /etc/haproxy/errors/408.http\n    errorfile 500 /etc/haproxy/errors/500.http\n    errorfile 502 /etc/haproxy/errors/502.http\n    errorfile 503 /etc/haproxy/errors/503.http\n    errorfile 504 /etc/haproxy/errors/504.http\n\n# Listen on all IP addresses. This is required for load balancer probe to work\nlisten http\n    bind 0.0.0.0:$LB_PORT\n    mode tcp\n    option tcplog\n    balance roundrobin\n    maxconn 10000\" > $HAPROXY_CFG\n\n    # Add application VMs to haproxy listener configuration\n    for APPVM in \"${APPVMS[@]}\"; do\n        APPVM_IP=`host $APPVM | awk '/has address/ { print $4 }'`\n        if [[ -z $APPVM_IP ]]; then\n            echo \"Unknown hostname $APPVM. Cannot be added to $HAPROXY_CFG.\" >&2\n        else\n            echo \"    server $APPVM $APPVM_IP:$APPVM_PORT maxconn 5000 check\" >> $HAPROXY_CFG\n        fi\n    done\n\n    chmod --reference ${HAPROXY_CFG}.default\n\n    # Start haproxy service\n    service haproxy start\n}\n\nsetup_keepalived() {\n\n    MASTERVM_IP=`host $MASTERVM | awk '/has address/ { print $4 }'`\n    BACKUPVM_IP=`host $BACKUPVM | awk '/has address/ { print $4 }'`\n\n    LB_IP=`host $LBDNSNAME | awk '/has address/ { print $4 }'`\n\n    IS_MASTER=$( [[ `hostname -s` == $MASTERVM ]]; echo $? )\n\n    # keepalived uses VRRP over multicast by default, but Azure doesn't support multicast\n    # (http://feedback.azure.com/forums/217313-azure-networking/suggestions/547215-multicast-support)\n    # keepalived needs to be configured with unicast. Support for unicast was introduced only in version 1.2.8.\n    # Default version available in Ubuntu 14.04 is 1.2.7-1ubuntu1.\n\n    # Install a newer version of keepalived from a ppa.\n    add-apt-repository -y ppa:keepalived/stable && apt-get -y update && apt-get install -y keepalived\n\n    # Setup keepalived.conf\n    KEEPALIVED_CFG=/etc/keepalived/keepalived.conf\n    cp -p $KEEPALIVED_CFG ${KEEPALIVED_CFG}.default\n\n    echo \"\nvrrp_script chk_appsvc {\n    script /usr/local/sbin/keepalived-check-appsvc.sh\n    interval 1\n    fall 2\n    rise 2\n}\n\nvrrp_instance VI_1 {\n    interface eth0\n\n    authentication {\n        auth_type PASS\n        auth_pass secr3t\n    }\n\n    virtual_router_id 51\n\n    virtual_ipaddress {\n        $LB_IP\n    }\n\n    track_script {\n        chk_appsvc\n    }\n\n    notify /usr/local/sbin/keepalived-action.sh\n    notify_stop \\\"/usr/local/sbin/keepalived-action.sh INSTANCE VI_1 STOP\\\"\n\n\" > $KEEPALIVED_CFG\n\n    if [[ $IS_MASTER -eq 0 ]]; then\n        echo \"    state MASTER\" >> $KEEPALIVED_CFG\n        echo \"    priority 101\" >> $KEEPALIVED_CFG\n\n        UNICAST_SRC_IP=$MASTERVM_IP\n        UNICAST_PEER_IP=$BACKUPVM_IP\n\n    else\n        echo \"    state BACKUP\" >> $KEEPALIVED_CFG\n        echo \"    priority 100\" >> $KEEPALIVED_CFG\n\n        UNICAST_SRC_IP=$BACKUPVM_IP\n        UNICAST_PEER_IP=$MASTERVM_IP\n\n    fi\n\necho \"\n    unicast_src_ip $UNICAST_SRC_IP\n    unicast_peer {\n        $UNICAST_PEER_IP\n    }\n\n}\n\" >> $KEEPALIVED_CFG\n\n    chmod --reference ${KEEPALIVED_CFG}.default $KEEPALIVED_CFG\n\n    # Script to perform application level status check\n    cp keepalived-check-appsvc.sh /usr/local/sbin/keepalived-check-appsvc.sh\n    chmod +x /usr/local/sbin/keepalived-check-appsvc.sh\n\n    # Script to update probe status based on keepalived status\n    cp keepalived-action.sh /usr/local/sbin/keepalived-action.sh\n    chmod +x /usr/local/sbin/keepalived-action.sh\n\n    # Enable binding non local VIP\n    echo \"net.ipv4.ip_nonlocal_bind=1\" >> /etc/sysctl.conf\n    sysctl -p\n\n    # Restart keepalived\n    service keepalived stop && service keepalived start\n}\n\n\n# Setup haproxy\nsetup_haproxy\n\n# Setup keepalived\nsetup_keepalived\n\n", "num_lines": 211}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nTYPE=$1\nNAME=$2\nSTATE=$3\n\nmodify_probe_status() {\n    STATUS=$1\n\n    LB_PROBE_PORT=80\n    LB_PROBE_DEV=eth0\n\n    if [[ $STATUS == \"down\" ]]; then\n        # Add firewall rule to block LB probe port\n        /sbin/iptables -A INPUT -p tcp --dport $LB_PROBE_PORT -j REJECT -i $LB_PROBE_DEV\n    elif [[ $STATUS == \"up\" ]]; then\n        # Remove all entries to block LB probe port\n        RC=0\n        while [[ $RC -eq 0 ]]; do\n            RC=`/sbin/iptables -D INPUT -p tcp --dport $LB_PROBE_PORT -j REJECT -i $LB_PROBE_DEV 2>/dev/null; echo $?`\n        done\n    else\n        echo \"Unknown probe status\"\n    fi\n}\n\nif [[ \"$NAME\" == \"VI_1\" ]]; then\n    case $STATE in\n        \"MASTER\") modify_probe_status up\n             exit 0\n             ;;\n        \"BACKUP\"|\"STOP\") modify_probe_status down\n             exit 0\n                          ;;\n        \"FAULT\")  modify_probe_status down\n             exit 0\n             ;;\n        *)        echo \"unknown state\"\n             exit 1\n             ;;\n    esac\nelse\n        echo \"Nothing to do\"\n        exit 0\nfi\n\n", "num_lines": 47}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nURL=\"http://localhost\"\n\nif [[ `curl -s -o/dev/null --connect-timeout 0.5 $URL; echo $?` -ne 0 ]]; then\n    exit 1\nelse\n    exit 0\nfi\n\n", "num_lines": 11}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nmyNodeType=$1;\nif [ -z \"$myNodeType\" ]; then\n    echo \"[ERROR] No node type specified. Exiting!\"\n    usage\nfi\necho \"myNodeType=$myNodeType\";\n\necho \"MyNodeType=$myNodeType\" | sudo tee -a /etc/environment\n", "num_lines": 11}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# -------\n\n# install docker & kubeadm - ubuntu\n# ---------------------------------\n\nKUBEADM_TOKEN='8f07c4.2fa8f9e48b6d4036'\nKUBE_VERSION='1.17.3-00' # specify version of kubeadm, kubelet and kubectl\nKUBE_CA_VERSION='v1.17.1' # specify version of kubernetes cluster-autoscaler\n\n# setup params given to sh script\nCLIENT_ID=$1\nCLIENT_SECRET=$2\nRESOURCE_GROUP=$3\nSUB=$4\nTENANT=$5\n\nexport DEBIAN_FRONTEND=noninteractive\n\ninstallDeps() {\n    # update and upgrade packages\n    apt-get update && apt-get upgrade -y\n\n    # install docker\n    apt-get install -y docker.io\n\n    # install kubeadm\n    apt-get install -y apt-transport-https\n    curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -\n    echo \"deb https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list\n\n    apt-get update\n    apt-get install -y kubelet=${KUBE_VERSION} kubeadm=${KUBE_VERSION} kubectl=${KUBE_VERSION}\n}\n\nsetupKubeadm() {\n    export HOME=/root\n    # initialize master\n    kubeadm init --pod-network-cidr=192.168.0.0/16  --token $KUBEADM_TOKEN\n\n    # wait for kubeadm to be successfully configured\n    sleep 15\n\n    # copy /etc/kubernetes/admin.conf so we can use kubectl\n    mkdir -p /root/.kube\n    cp -i /etc/kubernetes/admin.conf /root/.kube/config\n    chown $(id -u):$(id -g) /root/.kube/config\n    export KUBECONFIG=\"/root/.kube/config\"\n    \n    echo \"export KUBECONFIG=/root/.kube/config\" >> /root/.bashrc\n\n    # install pod network\n    kubectl apply -f \"https://cloud.weave.works/k8s/net?k8s-version=$(kubectl version | base64 | tr -d '\\n')\"\n}\n\nsetupClusterAutscaler() {\ncat >/etc/cluster-vmss-autoscaler.yaml <<EOL\n---\napiVersion: v1\nkind: ServiceAccount\nmetadata:\n  labels:\n    k8s-addon: cluster-autoscaler.addons.k8s.io\n    k8s-app: cluster-autoscaler\n  name: cluster-autoscaler\n  namespace: kube-system\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRole\nmetadata:\n  name: cluster-autoscaler\n  labels:\n    k8s-addon: cluster-autoscaler.addons.k8s.io\n    k8s-app: cluster-autoscaler\nrules:\n  - apiGroups: [\"\"]\n    resources: [\"events\", \"endpoints\"]\n    verbs: [\"create\", \"patch\"]\n  - apiGroups: [\"\"]\n    resources: [\"pods/eviction\"]\n    verbs: [\"create\"]\n  - apiGroups: [\"\"]\n    resources: [\"pods/status\"]\n    verbs: [\"update\"]\n  - apiGroups: [\"\"]\n    resources: [\"endpoints\"]\n    resourceNames: [\"cluster-autoscaler\"]\n    verbs: [\"get\", \"update\"]\n  - apiGroups: [\"\"]\n    resources: [\"nodes\"]\n    verbs: [\"watch\", \"list\", \"get\", \"update\"]\n  - apiGroups: [\"\"]\n    resources:\n      - \"pods\"\n      - \"services\"\n      - \"replicationcontrollers\"\n      - \"persistentvolumeclaims\"\n      - \"persistentvolumes\"\n    verbs: [\"watch\", \"list\", \"get\"]\n  - apiGroups: [\"extensions\"]\n    resources: [\"replicasets\", \"daemonsets\"]\n    verbs: [\"watch\", \"list\", \"get\"]\n  - apiGroups: [\"policy\"]\n    resources: [\"poddisruptionbudgets\"]\n    verbs: [\"watch\", \"list\"]\n  - apiGroups: [\"apps\"]\n    resources: [\"statefulsets\", \"replicasets\", \"daemonsets\"]\n    verbs: [\"watch\", \"list\", \"get\"]\n  - apiGroups: [\"storage.k8s.io\"]\n    resources: [\"storageclasses\", \"csinodes\"]\n    verbs: [\"get\", \"list\", \"watch\"]\n  - apiGroups: [\"batch\"]\n    resources: [\"jobs\", \"cronjobs\"]\n    verbs: [\"watch\", \"list\", \"get\"]\n  - apiGroups: [\"coordination.k8s.io\"]\n    resources: [\"leases\"]\n    verbs: [\"create\"]\n  - apiGroups: [\"coordination.k8s.io\"]\n    resourceNames: [\"cluster-autoscaler\"]\n    resources: [\"leases\"]\n    verbs: [\"get\", \"update\"]\n\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: Role\nmetadata:\n  name: cluster-autoscaler\n  namespace: kube-system\n  labels:\n    k8s-addon: cluster-autoscaler.addons.k8s.io\n    k8s-app: cluster-autoscaler\nrules:\n  - apiGroups: [\"\"]\n    resources: [\"configmaps\"]\n    verbs: [\"create\",\"list\",\"watch\"]\n  - apiGroups: [\"\"]\n    resources: [\"configmaps\"]\n    resourceNames:\n      - \"cluster-autoscaler-status\"\n      - \"cluster-autoscaler-priority-expander\"\n    verbs: [\"delete\", \"get\", \"update\", \"watch\"]\n\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: ClusterRoleBinding\nmetadata:\n  name: cluster-autoscaler\n  labels:\n    k8s-addon: cluster-autoscaler.addons.k8s.io\n    k8s-app: cluster-autoscaler\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: ClusterRole\n  name: cluster-autoscaler\nsubjects:\n  - kind: ServiceAccount\n    name: cluster-autoscaler\n    namespace: kube-system\n\n---\napiVersion: rbac.authorization.k8s.io/v1\nkind: RoleBinding\nmetadata:\n  name: cluster-autoscaler\n  namespace: kube-system\n  labels:\n    k8s-addon: cluster-autoscaler.addons.k8s.io\n    k8s-app: cluster-autoscaler\nroleRef:\n  apiGroup: rbac.authorization.k8s.io\n  kind: Role\n  name: cluster-autoscaler\nsubjects:\n  - kind: ServiceAccount\n    name: cluster-autoscaler\n    namespace: kube-system\n\n---\napiVersion: v1\ndata:\n  ClientID: $(echo $CLIENT_ID | base64)\n  ClientSecret: $(echo $CLIENT_SECRET | base64)\n  ResourceGroup: $(echo $RESOURCE_GROUP | base64)\n  SubscriptionID: $(echo $SUB | base64)\n  TenantID: $(echo $TENANT | base64)\n  VMType: dm1zcw==\nkind: Secret\nmetadata:\n  name: cluster-autoscaler-azure\n  namespace: kube-system\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  labels:\n    app: cluster-autoscaler\n  name: cluster-autoscaler\n  namespace: kube-system\nspec:\n  replicas: 1\n  selector:\n    matchLabels:\n      app: cluster-autoscaler\n  template:\n    metadata:\n      labels:\n        app: cluster-autoscaler\n    spec:\n      serviceAccountName: cluster-autoscaler\n      tolerations:\n        - effect: NoSchedule\n          key: node-role.kubernetes.io/master\n      nodeSelector:\n        node-role.kubernetes.io/master: \"\"\n      containers:\n        - image: k8s.gcr.io/cluster-autoscaler:${KUBE_CA_VERSION}\n          imagePullPolicy: Always\n          name: cluster-autoscaler\n          resources:\n            limits:\n              cpu: 100m\n              memory: 300Mi\n            requests:\n              cpu: 100m\n              memory: 300Mi\n          command:\n            - ./cluster-autoscaler\n            - --v=3\n            - --logtostderr=true\n            - --cloud-provider=azure\n            - --skip-nodes-with-local-storage=false\n            - --node-group-auto-discovery=label:cluster-autoscaler-enabled=true,cluster-autoscaler-name=${RESOURCE_GROUP}\n          env:\n            - name: ARM_SUBSCRIPTION_ID\n              valueFrom:\n                secretKeyRef:\n                  key: SubscriptionID\n                  name: cluster-autoscaler-azure\n            - name: ARM_RESOURCE_GROUP\n              valueFrom:\n                secretKeyRef:\n                  key: ResourceGroup\n                  name: cluster-autoscaler-azure\n            - name: ARM_TENANT_ID\n              valueFrom:\n                secretKeyRef:\n                  key: TenantID\n                  name: cluster-autoscaler-azure\n            - name: ARM_CLIENT_ID\n              valueFrom:\n                secretKeyRef:\n                  key: ClientID\n                  name: cluster-autoscaler-azure\n            - name: ARM_CLIENT_SECRET\n              valueFrom:\n                secretKeyRef:\n                  key: ClientSecret\n                  name: cluster-autoscaler-azure\n            - name: ARM_VM_TYPE\n              valueFrom:\n                secretKeyRef:\n                  key: VMType\n                  name: cluster-autoscaler-azure\n          volumeMounts:\n            - mountPath: /etc/ssl/certs/ca-certificates.crt\n              name: ssl-certs\n              readOnly: true\n      restartPolicy: Always\n      volumes:\n        - hostPath:\n            path: /etc/ssl/certs/ca-certificates.crt\n            type: \"\"\n          name: ssl-certs\nEOL\n}\n\ninstallClusterAutoscaler() {\n    # install cluster autoscaler\n    kubectl apply -f /etc/cluster-vmss-autoscaler.yaml\n}\n\n#install flow\ninstallDeps\nsetupKubeadm\nsetupClusterAutscaler\ninstallClusterAutoscaler", "num_lines": 286}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# -------\n\n# install docker & kubeadm - ubuntu\n# ---------------------------------\n\nKUBEADM_TOKEN='8f07c4.2fa8f9e48b6d4036'\nKUBE_VERSION='1.17.3-00' # specify version of kubeadm, kubelet and kubectl\n\n# setup params given to sh script\nCLIENT_ID=$1\nCLIENT_SECRET=$2\nRESOURCE_GROUP=$3\nSUB=$4\nTENANT=$5\nRG_LOCATION=$6\nSUBNET_NAME=$7\nVNET_NAME=$8\n\nexport DEBIAN_FRONTEND=noninteractive\nexport HOME=/root\n\ninstallDeps() {\n    # update and upgrade packages\n    apt-get update && apt-get upgrade -y\n\n    # install docker\n    apt-get install -y docker.io\n\n    # install kubeadm\n    apt-get install -y apt-transport-https\n    curl -s https://packages.cloud.google.com/apt/doc/apt-key.gpg | apt-key add -\n    echo \"deb https://apt.kubernetes.io/ kubernetes-xenial main\" | sudo tee -a /etc/apt/sources.list.d/kubernetes.list\n\n    apt-get update\n    apt-get install -y kubelet=${KUBE_VERSION} kubeadm=${KUBE_VERSION} kubectl=${KUBE_VERSION}\n}\n\ncreateConfigFiles() {\n    # Write a sample provider JSON (This won't work but values are needed in the fields)\ncat >/etc/kubernetes/azure.json <<EOL\n{\n    \"cloud\":\"AzurePublicCloud\",\n    \"tenantId\": \"${TENANT}\",\n    \"subscriptionId\": \"${SUB}\",\n    \"aadClientId\": \"${CLIENT_ID}\",\n    \"aadClientSecret\": \"${CLIENT_SECRET}\",\n    \"resourceGroup\": \"${RESOURCE_GROUP}\",\n    \"location\": \"${RG_LOCATION}\",\n    \"vmType\": \"vmss\",\n    \"subnetName\": \"${SUBNET_NAME}\",\n    \"securityGroupName\": \"\",\n    \"vnetName\": \"${VNET_NAME}\",\n    \"vnetResourceGroup\": \"${RESOURCE_GROUP}\",\n    \"routeTableName\": \"\",\n    \"primaryAvailabilitySetName\": \"\",\n    \"primaryScaleSetName\": \"\",\n    \"cloudProviderBackoffMode\": \"v1\",\n    \"cloudProviderBackoff\": false,\n    \"cloudProviderBackoffRetries\": 6,\n    \"cloudProviderBackoffExponent\": 1.5,\n    \"cloudProviderBackoffDuration\": 5,\n    \"cloudProviderBackoffJitter\": 1,\n    \"cloudProviderRatelimit\": true,\n    \"cloudProviderRateLimitQPS\": 10,\n    \"cloudProviderRateLimitBucket\": 100,\n    \"cloudProviderRatelimitQPSWrite\": 10,\n    \"cloudProviderRatelimitBucketWrite\": 100,\n    \"useManagedIdentityExtension\": false,\n    \"userAssignedIdentityID\": \"\",\n    \"useInstanceMetadata\": true,\n    \"loadBalancerSku\": \"Basic\",\n    \"disableOutboundSNAT\": false,\n    \"excludeMasterFromStandardLB\": false,\n    \"providerVaultName\": \"\",\n    \"maximumLoadBalancerRuleCount\": 250,\n    \"providerKeyName\": \"k8s\",\n    \"providerKeyVersion\": \"\"\n}\nEOL\n\n# kubeadm - agent nodes\n# ---------------------\n# create kubeadm config on disk\n\ncat >/etc/kubeadm-join.yaml <<EOL\nkind: JoinConfiguration\napiVersion: kubeadm.k8s.io/v1beta2\ncaCertPath: /etc/kubernetes/pki/ca.crt\ndiscovery:\n  bootstrapToken:\n    apiServerEndpoint: 10.0.1.4:6443\n    token: ${KUBEADM_TOKEN}\n    unsafeSkipCAVerification: true\n  timeout: 5m0s\n  tlsBootstrapToken: ${KUBEADM_TOKEN}\nnodeRegistration:\n  kubeletExtraArgs:\n    cloud-config: /etc/kubernetes/azure.json\n    cloud-provider: azure\n  criSocket: /var/run/dockershim.sock\n  taints: null\nEOL\n\n}\n\njoinKubeadm() {\n    # initialize agent node\n    kubeadm join --config /etc/kubeadm-join.yaml\n}\n\ninstallDeps\ncreateConfigFiles\njoinKubeadm", "num_lines": 114}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# set up a silent install of MySQL\ndbpass=$1\n\nexport DEBIAN_FRONTEND=noninteractive\necho mysql-server-5.6 mysql-server/root_password password $dbpass | debconf-set-selections\necho mysql-server-5.6 mysql-server/root_password_again password $dbpass | debconf-set-selections\n\n# install the LAMP stack\napt-get -y install apache2 mysql-server php5 php5-mysql\n\n# write some PHP\necho \\<center\\>\\<h1\\>My Demo App\\</h1\\>\\<br/\\>\\</center\\> > /var/www/html/phpinfo.php\necho \\<\\?php phpinfo\\(\\)\\; \\?\\> >> /var/www/html/phpinfo.php\n\n# restart Apache\napachectl restart\n", "num_lines": 20}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Nginx - new server blocks\n#\n# Variables\nNGINX_AVAILABLE_VHOSTS='/etc/nginx/sites-available'\nNGINX_ENABLED_VHOSTS='/etc/nginx/sites-enabled'\nWEB_DIR='/var/www'\nWEB_USER='www-data'\nNGINX_LOG='/var/log/nginx'\n#\n#WEB_ARRAY_NAME=(\"web101\" \"web102\" \"web103\" \"web104\")\n#WEB_ARRAY_PORT=(\"8081\" \"8082\" \"8083\" \"8084\")\n\n\nWEB_ARRAY_NAME=()\nWEB_ARRAY_PORT=(\"$@\")\n#for arg in \"${WEB_ARRAY_PORT[@]}\"; do\n#\techo \"$arg\"\n#done\n#echo \"${WEB_ARRAY_PORT[*]}\"\nargc=$#\nfor (( j=0; j<$argc; j++ )); do\n    k=$(($j+1))\n    printf -v i \"%02d\" $k\n    WEB_ARRAY_NAME+=(\"web${i}\")\ndone\n#echo \"${WEB_ARRAY_NAME[*]}\"\n\nsleep 1m\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    echo \"Script executed without root permissions\"\n    echo \"You must be root to run this script.\" >&2\n    exit 3\nfi\n\n# eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\nsudo apt-get -y update\n# sudo apt upgrade\n### install and start nginx\nsudo apt-get -y install nginx \nsudo systemctl enable nginx \nsudo systemctl start nginx\n### change the homepage of nginx\necho '<style> h1 { color: blue; } </style> <h1>' > /var/www/html/index.nginx-debian.html\ncat /etc/hostname >> /var/www/html/index.nginx-debian.html\necho ' </h1>' >> /var/www/html/index.nginx-debian.html\nsed -i '/^#/! s/listen 80/listen 8080/g'  /etc/nginx/sites-enabled/default\nsed -i '/^#/! s/listen \\[::]:80/listen \\[::]:8080/g' /etc/nginx/sites-enabled/default\nsystemctl restart nginx\n\n\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n    ### Create folders \n    if [ -d \"$WEB_DIR/${WEB_ARRAY_NAME[$i]}/html\" ]; then\n      echo \"folder $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html already exists\"\n    else\n      mkdir -p $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html\n    fi\ndone\n\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n   ### Assign ownership\n   chown -R $USER:$USER $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html\ndone\n\n### Grant reading permission to all the files inside the /var/www directory\nsudo chmod -R 755 $WEB_DIR\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n   ### Reassign ownership of the web directories to NGINX user (www-data):\n   chown -R www-data:www-data $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html\ndone\n\nCOLORS=(\"darkgreen\" \"darkblue\" \"red\" \"darkviolet\" \"orangered\")\nLEN=${#COLORS[@]}\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n### Create the content you want to display on the websites hosted on Nginx server \ncat <<EOF > $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html/index.html\n<html>\n    <style> h1 { color: ${COLORS[$((i%LEN))]}; } </style> <h1>\n    <head> <title>Welcome to ${WEB_ARRAY_NAME[$i]}</title> </head>\n    <body>\n        <h1>${WEB_ARRAY_NAME[$i]} server block is working!</h1>\n    </body>\n</html>\nEOF\ndone\n\n\n### Inside the  file /etc/nginx/nginx.conf check the two lines:\n###    include /etc/nginx/conf.d/*.conf;\n###    include /etc/nginx/sites-enabled/*;\n### The line include /etc/nginx/sites-enabled/*.conf instructs NGINX to check the sites-enabled directory.\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n### Create the server blocks for the site web101\ncat <<EOF > /etc/nginx/sites-available/${WEB_ARRAY_NAME[$i]}.conf\nserver {\n        listen ${WEB_ARRAY_PORT[$i]};\n        listen [::]:${WEB_ARRAY_PORT[$i]};\n        server_name  ${WEB_ARRAY_NAME[$i]}.local;\n\n        root $WEB_DIR/${WEB_ARRAY_NAME[$i]}/html;\n        index index.html index.htm;\n        location / {\n                try_files \\$uri \\$uri/ =404;\n        }\n        access_log /var/log/nginx/${WEB_ARRAY_NAME[$i]}/access.log;\n\t    error_log /var/log/nginx/${WEB_ARRAY_NAME[$i]}/error.log;\n}\nEOF\ndone\n\n### Enable the new server block files, by creating symbolic links:\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n   ### Enable the new server block files, by creating symbolic links:\n   #ln -s /etc/nginx/sites-available/${WEB_ARRAY_NAME[$i]}.conf /etc/nginx/sites-enabled/\n   \n   web_link=\"/etc/nginx/sites-enabled/${WEB_ARRAY_NAME[$i]}.conf\"\n   if [ -L ${web_link} ] ; then\n     if [ -e ${web_link} ] ; then\n        echo \"symbolic link already exists: /etc/nginx/sites-enabled/${WEB_ARRAY_NAME[$i]}.conf\"\n     else\n        echo \"symbolic link  /etc/nginx/sites-enabled/${WEB_ARRAY_NAME[$i]}.conf is broken\"\n     fi\n   elif [ -e ${web_link} ] ; then\n     echo \" /etc/nginx/sites-enabled/${WEB_ARRAY_NAME[$i]}.conf is NOT a symbolic link \"\n   else\n     echo \"Create symbolic link: /etc/nginx/sites-enabled/${WEB_ARRAY_NAME[$i]}.conf\"\n     ln -s /etc/nginx/sites-available/${WEB_ARRAY_NAME[$i]}.conf /etc/nginx/sites-enabled/\n   fi\ndone\n\nfor i in ${!WEB_ARRAY_NAME[@]}; do\n   ### Create the folders for the logs:\n   mkdir -p /var/log/nginx/${WEB_ARRAY_NAME[$i]}/\n   chown -R www-data:adm /var/log/nginx/${WEB_ARRAY_NAME[$i]}/\ndone\n### Check errors in nginx configuration\nsudo nginx -t\n\n### Restart NGINX:\nsudo systemctl restart nginx\n", "num_lines": 152}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#\n# run the script with the follow command:\n# ./nva.sh -p 10800 -p 800 -P 10801 -V 801 -n 10.0.1.100\n############################################################\n# Help                                                     #\n############################################################\nHelp()\n{\n   # Display Help\n   echo \"Script to create VXLAN tunnels with Azure load balancer\"\n   echo\n   echo \"Syntax: scriptName -p INTERNAL_VXLAN_PORT -v INTERNAL_VNI -P EXTERNAL_VXLAN_PORT -V EXTERNAL_VNI -n IP_ADRESS_LOAD_BALANCER\"\n   echo \"        ./nva.sh -p 10800 -v 800 -P 10801 -V 801 -n 10.0.1.100\"\n   echo \"parameters:\"\n   echo \"-p   internal port VXLAN\"\n   echo \"-v   internal VNI\"\n   echo \"-P   external port VXLAN\"\n   echo \"-V   external VNI\"\n   echo\n}\n\nwhile getopts \":hp:v:P:V:n:\" options\ndo\n    case \"${options}\" in\n        h) # display Help\n            help\n            exit 2;;\n        p) tunnel_internal_port=${OPTARG}\n            ;;\n        v) \n            tunnel_internal_vni=${OPTARG}\n            ;;\n        P) \n            tunnel_external_port=${OPTARG}\n            ;;\n        V) \n            tunnel_external_vni=${OPTARG}\n            ;;\n        n) nva_lb_ip=${OPTARG}\n            ;;\n       \\?) # Invalid option\n            echo 'Error: Invalid option'\n            help\n            exit 2;;\n    esac\ndone\n### example of variables assignment\n### tunnel_internal_port=10800\n### tunnel_internal_vni=800\n### tunnel_external_port=10801\n### tunnel_external_vni=801\n### nva_lb_ip=10.0.1.100\n#\nif [ \"${UID}\" -ne 0 ];\nthen\n    echo \"Script executed without root permissions\"\n    echo \"You must be root to run this script.\" >&2\n    exit 3\nfi\n#\nsleep 1m\n\n# eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\nsudo apt-get -y update\nsudo apt-get -y install unattended-upgrades\n# sudo apt-get install net-tools\n# \n### enable IP forwarding\nsudo sed -i -e '$a\\net.ipv4.ip_forward = 1' /etc/sysctl.conf\nsysctl -p \n\n### install and start nginx\nsudo apt-get -y install nginx \nsudo systemctl enable nginx \nsudo systemctl start nginx\n### change the homepage of nginx\necho '<style> h1 { color: blue; } </style> <h1>' > /var/www/html/index.nginx-debian.html\ncat /etc/hostname >> /var/www/html/index.nginx-debian.html\necho ' </h1>' >> /var/www/html/index.nginx-debian.html\nsed -i '/^#/! s/listen 80/listen 8080/g'  /etc/nginx/sites-enabled/default\nsed -i '/^#/! s/listen \\[::]:80/listen \\[::]:8080/g' /etc/nginx/sites-enabled/default\nsudo systemctl restart nginx\n\n### create a file to setup the VXLAN tunnels\ncat <<EOF > /usr/local/bin/nvavnisetup.sh\ntunnel_internal_port=$tunnel_internal_port\ntunnel_internal_vni=$tunnel_internal_vni\ntunnel_external_port=$tunnel_external_port\ntunnel_external_vni=$tunnel_external_vni\nnva_lb_ip=$nva_lb_ip\n\n# internal tunnel\nip link add name vxlan\\${tunnel_internal_vni} type vxlan id \\${tunnel_internal_vni} remote \\${nva_lb_ip} dstport \\${tunnel_internal_port}\nip link set vxlan\\${tunnel_internal_vni} up\n\n# external tunnel\nip link add name vxlan\\${tunnel_external_vni} type vxlan id \\${tunnel_external_vni} remote \\${nva_lb_ip} dstport \\${tunnel_external_port}\nip link set vxlan\\${tunnel_external_vni} up\n\n# bridge both VXLAN interfaces together (works arounding routing between them)\nip link add br-tunnel type bridge\nip link set vxlan\\${tunnel_internal_vni} master br-tunnel\nip link set vxlan\\${tunnel_external_vni} master br-tunnel\nip link set br-tunnel up\nEOF\n\n### create a file to start the VXLAN tunnels as service\ncat <<EOF > /etc/systemd/system/nvavxlan.service\n[Unit]\nDescription=vni service\nAfter=network.target\n\n[Service]\nType=simple\nExecStart=/bin/bash /usr/local/bin/nvavnisetup.sh\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\nsudo chmod 744 /usr/local/bin/nvavnisetup.sh\nsudo chmod 664 /etc/systemd/system/nvavxlan.service\n# sudo systemctl daemon-reload\nsudo systemctl start nvavxlan.service\nsudo systemctl enable nvavxlan.service\n# sudo systemctl restart nvavxlan.service\nexit 0\n\n", "num_lines": 133}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#init and mount data disk\nif [ ! -d \"/datadisk\" ]; then\n\t(echo n; echo p; echo 1; echo; echo; echo w) | fdisk /dev/sdc > /dev/null\n\tmkfs -t ext4 /dev/sdc1 > /dev/null\n\tmkdir /datadisk\n\tmount /dev/sdc1 /datadisk\n\n\techo \"UUID=$(blkid | grep -oP '/dev/sdc1: UUID=\"*\"\\K[^\"]*')   /datadisk   ext4   defaults   1   2\" >> /etc/fstab\n\tchmod go+w /datadisk\nfi\n\n\nconfdir=/opt/vmdiskperf/\nif [ ! -d \"$confdir\" ]; then\n\tfirstrun=true\n\tmkdir \"$confdir\"\n\n\t#install fio\n\tapt-get update > /dev/null\n\tapt-get -y install fio > /dev/null\nfi\n\n#create test config\ncd \"$confdir\"\ncat << EOF > t\n[global]\nsize=$1\ndirect=1\niodepth=256\nioengine=libaio\nbs=$5\nEOF\n\nfor i in `seq 1 $4`; do\n\t\techo \"[w$i]\" >> t\n\t\techo rw=$2 >> t\n\t\techo directory=/datadisk >> t\ndone\n\n#run test\nif [ $firstrun = true ]; then\n\tfio --runtime $3 t | grep -E 'READ:|WRITE:' | tr '\\n' ';' | tr -s [:space:] | sed 's/ :/:/g' | sed 's/= /=/g'\nelse\n\tfio --runtime $3 t\nfi\n", "num_lines": 48}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ndl=cdefghijklmnopqrstuvwxyz\npart=\n\n#init and mount data disk\nif [ ! -d \"/datadisk\" ]; then\n\n\tapt-get -y update > /dev/null\n\tapt-get --no-install-recommends -y install mdadm > /dev/null\n\n\tfor i in `seq 1 $6`; do\n\n\t\t\t(echo n; echo p; echo 1; echo; echo; echo w) | fdisk /dev/sd${dl:$i-1:1} > /dev/null\n\t\t\tpart=\"$part /dev/sd${dl:$i-1:1}1\"\n\n\tdone\n\n\tmdadm --create /dev/md1 --level 0 --raid-devices $6 $part > /dev/null\n\n\tmkfs -t ext4 /dev/md1 > /dev/null\n\n\tmkdir /datadisk\n\tmount /dev/md1 /datadisk\n\n\techo \"UUID=$(blkid | grep -oP '/dev/md1: UUID=\"*\"\\K[^\"]*')   /datadisk   ext4   defaults   1   2\" >> /etc/fstab\n\tchmod go+w /datadisk\nfi\n\n\nconfdir=/opt/vmdiskperf/\nif [ ! -d \"$confdir\" ]; then\n\tfirstrun=true\n\tmkdir \"$confdir\"\n\n\t#install fio\n\tapt-get update > /dev/null\n\tapt-get -y install fio > /dev/null\nfi\n\n#create test config\ncd \"$confdir\"\ncat << EOF > t\n[global]\nsize=$1\ndirect=1\niodepth=256\nioengine=libaio\nbs=$5\nEOF\n\nfor i in `seq 1 $4`; do\n\t\techo \"[w$i]\" >> t\n\t\techo rw=$2 >> t\n\t\techo directory=/datadisk >> t\ndone\n\n#run test\nif [ $firstrun = true ]; then\n\tfio --runtime $3 t | grep -E 'READ:|WRITE:' | tr '\\n' ';' | tr -s [:space:] | sed 's/ :/:/g' | sed 's/= /=/g'\nelse\n\tfio --runtime $3 t\nfi\n", "num_lines": 64}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get passed in parameters\nnumberOfMemcachedInstances=$1\nsubnetMemcachedPrefix=$2\n\n# Create simple python script to iterate over the IPs skipping first 3\necho \"c=$numberOfMemcachedInstances\" > p.py\necho \"ip='$subnetMemcachedPrefix'\" >> p.py\necho \"octets=ip.split('/')[0].split('.')\" >> p.py\necho \"octets[3]=str(int(octets[3])+3)\" >> p.py\necho \"s=[]\" >> p.py\necho \"for i in range(0,c):\" >> p.py\necho \"  octets[3]=str(int(octets[3])+1)\" >> p.py\necho \"  s.append('.'.join(octets))\" >> p.py\necho \"print(','.join(s))\" >> p.py\n\n# Get comma delimited list of servers\nservers=$(python ./p.py)\n\n# Get today's date into YYYYMMDD format\nnow=$(date +\"%Y%m%d\")\n\necho \"Installing apache $now, numberOfMemcachedInstances=$numberOfMemcachedInstances, subnetMemcachedPrefix=$subnetMemcachedPrefix, servers=$servers\" >> /var/log/apache_install.log\n\n# Re-synchronize the package index files from their sources. An update should always be performed before an upgrade.\napt-get -y update\n\n# Install apache, php5, and php5-memcached extension\napt-get -y install apache2 php5 php5-memcached\n\n# Delete Apache index page\nrm /var/www/html/index.html\n\n# Download cache_test.php page\nwget -O /var/www/html/index.php https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/memcached-multi-vm-ubuntu/cache_test.php\n\n# Replace the placeholder with the string of comma delimited memcached server IPs that was passed to this script as a parameter\nsed -i \"s/{COMMA_DELIMITED_SERVERS_LIST}/$servers/g\" /var/www/html/index.php\n\n# restart Apache\napachectl restart\n", "num_lines": 43}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Get passed in parameters\nmemcachedIndex=$1\nprivateIP=$2\napacheIP=$3\n\n# Get today's date into YYYYMMDD format\nnow=$(date +\"%Y%m%d\")\n\n# Re-synchronize the package index files from their sources. An update should always be performed before an upgrade.\napt-get -y update\n\n# Memcached is a C program and depends on a recent version of GCC and a recent version of libevent.\napt-get -y install memcached\n\necho \"Memcached installed on $now index $memcachedIndex, private ip $privateIP, and apache ip $apacheIP\" >> /var/log/memcached_install.log\n\n# By default memcached listens on TCP and UDP ports 11211. You must not expose memcached directly to the internet.\n\n# Change memcached.conf to listen on all IPs not just 127.0.0.1 and use 512MB of RAM instead of default 64MB\nsed -i \"s/-l 127.0.0.1/#-l 127.0.0.1/g\" /etc/memcached.conf\nsed -i \"s/^-m 64$/-m 512/g\" /etc/memcached.conf\n\n# Restart memcached service with the new configuration\nservice memcached restart\n\n# Inspect running configuration by issuing a \"stats settings\" command to the proper ports\necho \"stats settings\" | nc localhost 11211 > /var/log/memcached_stats_$now.log\n", "num_lines": 30}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [  $# -eq 0 ]; then\n    echo \"You need to pass the resource group name as the first positional parameter\"\n    exit 1\nfi\n\ncd ../prereqs/\n\necho \"Creating the prerequisites to the solution\"\naz group deployment create --resource-group $1 --template-file prereq.azuredeploy.json\n\nSUBNET_ID=$(az group deployment show -g $1 -n prereq.azuredeploy --query properties.outputs.subnetId.value)\nSUBNET_ID_FILTERED=$(echo $SUBNET_ID | cut -d '\"' -f 2)\n\ncd ../nested/\n\necho \"Deploying the whole solution\"\naz group deployment create --resource-group $1 --template-file nfs-ha.json --parameters nfs-ha.param.json --parameters \"subnetId=$SUBNET_ID_FILTERED\"\n\necho \"Deployment of NFS HA server done\"\n", "num_lines": 22}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Common functions definitions\n\nfunction get_setup_params_from_configs_json\n{\n    local configs_json_path=${1}    # E.g., /var/lib/cloud/instance/moodle_on_azure_configs.json\n\n    (dpkg -l jq &> /dev/null) || (apt -y update; apt -y install jq)\n\n    # Wait for the cloud-init write-files user data file to be generated (just in case)\n    local wait_time_sec=0\n    while [ ! -f \"$configs_json_path\" ]; do\n        sleep 15\n        let \"wait_time_sec += 15\"\n        if [ \"$wait_time_sec\" -ge \"1800\" ]; then\n            echo \"Error: Cloud-init write-files didn't complete in 30 minutes!\"\n            return 1\n        fi\n    done\n\n    local json=$(cat $configs_json_path)\n    export moodleVersion=$(echo $json | jq -r .moodleProfile.version)\n    export glusterNode=$(echo $json | jq -r .fileServerProfile.glusterVmName)\n    export glusterVolume=$(echo $json | jq -r .fileServerProfile.glusterVolName)\n    export siteFQDN=$(echo $json | jq -r .siteProfile.siteURL)\n    export httpsTermination=$(echo $json | jq -r .siteProfile.httpsTermination)\n    export dbIP=$(echo $json | jq -r .dbServerProfile.fqdn)\n    export moodledbname=$(echo $json | jq -r .moodleProfile.dbName)\n    export moodledbuser=$(echo $json | jq -r .moodleProfile.dbUser)\n    export moodledbpass=$(echo $json | jq -r .moodleProfile.dbPassword)\n    export adminpass=$(echo $json | jq -r .moodleProfile.adminPassword)\n    export dbadminlogin=$(echo $json | jq -r .dbServerProfile.adminLogin)\n    export dbadminloginazure=$(echo $json | jq -r .dbServerProfile.adminLoginAzure)\n    export dbadminpass=$(echo $json | jq -r .dbServerProfile.adminPassword)\n    export storageAccountName=$(echo $json | jq -r .moodleProfile.storageAccountName)\n    export storageAccountKey=$(echo $json | jq -r .moodleProfile.storageAccountKey)\n    export azuremoodledbuser=$(echo $json | jq -r .moodleProfile.dbUserAzure)\n    export redisDns=$(echo $json | jq -r .moodleProfile.redisDns)\n    export redisAuth=$(echo $json | jq -r .moodleProfile.redisKey)\n    export elasticVm1IP=$(echo $json | jq -r .moodleProfile.elasticVm1IP)\n    export installO365pluginsSwitch=$(echo $json | jq -r .moodleProfile.installO365pluginsSwitch)\n    export dbServerType=$(echo $json | jq -r .dbServerProfile.type)\n    export fileServerType=$(echo $json | jq -r .fileServerProfile.type)\n    export mssqlDbServiceObjectiveName=$(echo $json | jq -r .dbServerProfile.mssqlDbServiceObjectiveName)\n    export mssqlDbEdition=$(echo $json | jq -r .dbServerProfile.mssqlDbEdition)\n    export mssqlDbSize=$(echo $json | jq -r .dbServerProfile.mssqlDbSize)\n    export installObjectFsSwitch=$(echo $json | jq -r .moodleProfile.installObjectFsSwitch)\n    export installGdprPluginsSwitch=$(echo $json | jq -r .moodleProfile.installGdprPluginsSwitch)\n    export thumbprintSslCert=$(echo $json | jq -r .siteProfile.thumbprintSslCert)\n    export thumbprintCaCert=$(echo $json | jq -r .siteProfile.thumbprintCaCert)\n    export searchType=$(echo $json | jq -r .moodleProfile.searchType)\n    export azureSearchKey=$(echo $json | jq -r .moodleProfile.azureSearchKey)\n    export azureSearchNameHost=$(echo $json | jq -r .moodleProfile.azureSearchNameHost)\n    export tikaVmIP=$(echo $json | jq -r .moodleProfile.tikaVmIP)\n    export syslogServer=$(echo $json | jq -r .moodleProfile.syslogServer)\n    export webServerType=$(echo $json | jq -r .moodleProfile.webServerType)\n    export htmlLocalCopySwitch=$(echo $json | jq -r .moodleProfile.htmlLocalCopySwitch)\n    export nfsVmName=$(echo $json | jq -r .fileServerProfile.nfsVmName)\n    export nfsHaLbIP=$(echo $json | jq -r .fileServerProfile.nfsHaLbIP)\n    export nfsHaExportPath=$(echo $json | jq -r .fileServerProfile.nfsHaExportPath)\n}\n\nfunction get_php_version {\n# Returns current PHP version, in the form of x.x, eg 7.0 or 7.2\n    if [ -z \"$_PHPVER\" ]; then\n        _PHPVER=`/usr/bin/php -r \"echo PHP_VERSION;\" | /usr/bin/cut -c 1,2,3`\n    fi\n    echo $_PHPVER\n}\n\nfunction install_php_mssql_driver\n{\n    # Download and build php/mssql driver\n    /usr/bin/curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -\n    /usr/bin/curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list > /etc/apt/sources.list.d/mssql-release.list\n    sudo apt-get update\n    sudo ACCEPT_EULA=Y apt-get install msodbcsql mssql-tools unixodbc-dev -y\n    echo 'export PATH=\"$PATH:/opt/mssql-tools/bin\"' >> ~/.bash_profile\n    echo 'export PATH=\"$PATH:/opt/mssql-tools/bin\"' >> ~/.bashrc\n    source ~/.bashrc\n\n    #Build mssql driver\n    /usr/bin/pear config-set php_ini `php --ini | grep \"Loaded Configuration\" | sed -e \"s|.*:\\s*||\"` system\n    /usr/bin/pecl install sqlsrv\n    /usr/bin/pecl install pdo_sqlsrv\n    PHPVER=$(get_php_version)\n    echo \"extension=sqlsrv.so\" >> /etc/php/$PHPVER/fpm/php.ini\n    echo \"extension=pdo_sqlsrv.so\" >> /etc/php/$PHPVER/fpm/php.ini\n    echo \"extension=sqlsrv.so\" >> /etc/php/$PHPVER/apache2/php.ini\n    echo \"extension=pdo_sqlsrv.so\" >> /etc/php/$PHPVER/apache2/php.ini\n    echo \"extension=sqlsrv.so\" >> /etc/php/$PHPVER/cli/php.ini\n    echo \"extension=pdo_sqlsrv.so\" >> /etc/php/$PHPVER/cli/php.ini\n}\n\nfunction check_fileServerType_param\n{\n    local fileServerType=$1\n    if [ \"$fileServerType\" != \"gluster\" -a \"$fileServerType\" != \"azurefiles\" -a \"$fileServerType\" != \"nfs\" -a \"$fileServerType\" != \"nfs-ha\" ]; then\n        echo \"Invalid fileServerType ($fileServerType) given. Only 'gluster', 'azurefiles', 'nfs' or 'nfs-ha' are allowed. Exiting\"\n        exit 1\n    fi\n}\n\nfunction create_azure_files_moodle_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n    local logFilePath=$3\n\n    az storage share create \\\n        --name moodle \\\n        --account-name $storageAccountName \\\n        --account-key $storageAccountKey \\\n        --fail-on-exist >> $logFilePath\n}\n\nfunction setup_and_mount_gluster_moodle_share\n{\n    local glusterNode=$1\n    local glusterVolume=$2\n\n    grep -q \"/moodle.*glusterfs\" /etc/fstab || echo -e $glusterNode':/'$glusterVolume'   /moodle         glusterfs       defaults,_netdev,log-level=WARNING,log-file=/var/log/gluster.log 0 0' >> /etc/fstab\n    mount /moodle\n}\n\nfunction setup_and_mount_azure_files_moodle_share\n{\n    local storageAccountName=$1\n    local storageAccountKey=$2\n\n    cat <<EOF > /etc/moodle_azure_files.credential\nusername=$storageAccountName\npassword=$storageAccountKey\nEOF\n    chmod 600 /etc/moodle_azure_files.credential\n\n    grep \"^//$storageAccountName.file.core.windows.net/moodle\\s\\s*/moodle\\s\\s*cifs\" /etc/fstab\n    if [ $? != \"0\" ]; then\n        echo -e \"\\n//$storageAccountName.file.core.windows.net/moodle   /moodle cifs    credentials=/etc/moodle_azure_files.credential,uid=www-data,gid=www-data,nofail,vers=3.0,dir_mode=0770,file_mode=0660,serverino,mfsymlinks\" >> /etc/fstab\n    fi\n    mkdir -p /moodle\n    mount /moodle\n}\n\nfunction setup_moodle_mount_dependency_for_systemd_service\n{\n  local serviceName=$1 # E.g., nginx, apache2\n  if [ -z \"$serviceName\" ]; then\n    return 1\n  fi\n\n  local systemdSvcOverrideFileDir=\"/etc/systemd/system/${serviceName}.service.d\"\n  local systemdSvcOverrideFilePath=\"${systemdSvcOverrideFileDir}/moodle_on_azure_override.conf\"\n\n  grep -q \"After=moodle.mount\" $systemdSvcOverrideFilePath &> /dev/null\n  if [ $? != \"0\" ]; then\n    mkdir -p $systemdSvcOverrideFileDir\n    cat <<EOF > $systemdSvcOverrideFilePath\n[Unit]\nAfter=moodle.mount\nEOF\n    systemctl daemon-reload\n  fi\n}\n\n# Functions for making NFS share available\n# TODO refactor these functions with the same ones in install_gluster.sh\nfunction scan_for_new_disks\n{\n    local BLACKLIST=${1}    # E.g., /dev/sda|/dev/sdb\n    declare -a RET\n    local DEVS=$(ls -1 /dev/sd*|egrep -v \"${BLACKLIST}\"|egrep -v \"[0-9]$\")\n    for DEV in ${DEVS};\n    do\n        # Check each device if there is a \"1\" partition.  If not,\n        # \"assume\" it is not partitioned.\n        if [ ! -b ${DEV}1 ];\n        then\n            RET+=\"${DEV} \"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nfunction create_raid0_ubuntu {\n    local RAIDDISK=${1}       # E.g., /dev/md1\n    local RAIDCHUNKSIZE=${2}  # E.g., 128\n    local DISKCOUNT=${3}      # E.g., 4\n    shift\n    shift\n    shift\n    local DISKS=\"$@\"\n\n    dpkg -s mdadm\n    if [ ${?} -eq 1 ];\n    then\n        echo \"installing mdadm\"\n        sudo apt-get -y -q install mdadm\n    fi\n    echo \"Creating raid0\"\n    udevadm control --stop-exec-queue\n    echo \"yes\" | mdadm --create $RAIDDISK --name=data --level=0 --chunk=$RAIDCHUNKSIZE --raid-devices=$DISKCOUNT $DISKS\n    udevadm control --start-exec-queue\n    mdadm --detail --verbose --scan > /etc/mdadm/mdadm.conf\n}\n\nfunction do_partition {\n    # This function creates one (1) primary partition on the\n    # disk device, using all available space\n    local DISK=${1}   # E.g., /dev/sdc\n\n    echo \"Partitioning disk $DISK\"\n    echo -ne \"n\\np\\n1\\n\\n\\nw\\n\" | fdisk \"${DISK}\"\n    #> /dev/null 2>&1\n\n    #\n    # Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n    # from fdisk and not from echo\n    if [ ${PIPESTATUS[1]} -ne 0 ];\n    then\n        echo \"An error occurred partitioning ${DISK}\" >&2\n        echo \"I cannot continue\" >&2\n        exit 2\n    fi\n}\n\nfunction add_local_filesystem_to_fstab {\n    local UUID=${1}\n    local MOUNTPOINT=${2}   # E.g., /moodle\n\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"\\nUUID=${UUID} ${MOUNTPOINT} ext4 defaults,noatime 0 0\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\nfunction setup_raid_disk_and_filesystem {\n    local MOUNTPOINT=${1}     # E.g., /moodle\n    local RAIDDISK=${2}       # E.g., /dev/md1\n    local RAIDPARTITION=${3}  # E.g., /dev/md1p1\n    local CREATE_FILESYSTEM=${4}  # E.g., \"\" (true) or any non-empty string (false)\n\n    local DISKS=$(scan_for_new_disks \"/dev/sda|/dev/sdb\")\n    echo \"Disks are ${DISKS}\"\n    declare -i DISKCOUNT\n    local DISKCOUNT=$(echo \"$DISKS\" | wc -w)\n    echo \"Disk count is $DISKCOUNT\"\n    if [ $DISKCOUNT = \"0\" ]; then\n        echo \"No new (unpartitioned) disks available... Returning non-zero...\"\n        return 1\n    fi\n\n    if [ $DISKCOUNT -gt 1 ]; then\n        create_raid0_ubuntu ${RAIDDISK} 128 $DISKCOUNT $DISKS\n        AZMDL_DISK=$RAIDDISK\n        if [ -z \"$CREATE_FILESYSTEM\" ]; then\n          do_partition ${RAIDDISK}\n          local PARTITION=\"${RAIDPARTITION}\"\n        fi\n    else # Just one unpartitioned disk\n        AZMDL_DISK=$DISKS\n        if [ -z \"$CREATE_FILESYSTEM\" ]; then\n          do_partition ${DISKS}\n          local PARTITION=$(fdisk -l ${DISKS}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n        fi\n    fi\n\n    echo \"Disk (RAID if multiple unpartitioned disks, or as is if only one unpartitioned disk) is set up, and env var AZMDL_DISK is set to '$AZMDL_DISK' for later reference\"\n\n    if [ -z \"$CREATE_FILESYSTEM\" ]; then\n      echo \"Creating filesystem on ${PARTITION}.\"\n      mkfs -t ext4 ${PARTITION}\n      mkdir -p \"${MOUNTPOINT}\"\n      local UUID=$(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3}'|tr -d \"\\\"\")\n      add_local_filesystem_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n      echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n      mount \"${MOUNTPOINT}\"\n    fi\n}\n\nfunction configure_nfs_server_and_export {\n    local MOUNTPOINT=${1}     # E.g., /moodle\n\n    echo \"Installing nfs server...\"\n    apt install -y nfs-kernel-server\n\n    echo \"Exporting ${MOUNTPOINT}...\"\n    grep \"^${MOUNTPOINT}\" /etc/exports > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${MOUNTPOINT} is already exported. Returning...\"\n    else\n        echo -e \"\\n${MOUNTPOINT}   *(rw,sync,no_root_squash)\" >> /etc/exports\n        systemctl restart nfs-kernel-server.service\n    fi\n}\n\nfunction configure_nfs_client_and_mount {\n    local NFS_SERVER=${1}     # E.g., controller-vm-ab12cd or IP (NFS-HA LB)\n    local NFS_DIR=${2}        # E.g., /moodle or /drbd/data\n    local MOUNTPOINT=${3}     # E.g., /moodle\n\n    apt install -y nfs-common\n    mkdir -p ${MOUNTPOINT}\n\n    grep \"^${NFS_SERVER}:${NFS_DIR}\" /etc/fstab > /dev/null 2>&1\n    if [ $? = \"0\" ]; then\n        echo \"${NFS_SERVER}:${NFS_DIR} already in /etc/fstab... skipping to add\"\n    else\n        echo -e \"\\n${NFS_SERVER}:${NFS_DIR}    ${MOUNTPOINT}    nfs    auto    0    0\" >> /etc/fstab\n    fi\n    mount ${MOUNTPOINT}\n}\n\nSERVER_TIMESTAMP_FULLPATH=\"/moodle/html/moodle/.last_modified_time.moodle_on_azure\"\nLOCAL_TIMESTAMP_FULLPATH=\"/var/www/html/moodle/.last_modified_time.moodle_on_azure\"\n\n# Create a script to sync /moodle/html/moodle (gluster/NFS) and /var/www/html/moodle (local) and set up a minutely cron job\n# Should be called by root and only on a VMSS web frontend VM\nfunction setup_html_local_copy_cron_job {\n  if [ \"$(whoami)\" != \"root\" ]; then\n    echo \"${0}: Must be run as root!\"\n    return 1\n  fi\n\n  local SYNC_SCRIPT_FULLPATH=\"/usr/local/bin/sync_moodle_html_local_copy_if_modified.sh\"\n  mkdir -p $(dirname ${SYNC_SCRIPT_FULLPATH})\n\n  local SYNC_LOG_FULLPATH=\"/var/log/moodle-html-sync.log\"\n\n  cat <<EOF > ${SYNC_SCRIPT_FULLPATH}\n#!/bin/bash\n\nsleep \\$((\\$RANDOM%30))\n\nif [ -f \"$SERVER_TIMESTAMP_FULLPATH\" ]; then\n  SERVER_TIMESTAMP=\\$(cat $SERVER_TIMESTAMP_FULLPATH)\n  if [ -f \"$LOCAL_TIMESTAMP_FULLPATH\" ]; then\n    LOCAL_TIMESTAMP=\\$(cat $LOCAL_TIMESTAMP_FULLPATH)\n  else\n    logger -p local2.notice -t moodle \"Local timestamp file ($LOCAL_TIMESTAMP_FULLPATH) does not exist. Probably first time syncing? Continuing to sync.\"\n    mkdir -p /var/www/html\n  fi\n  if [ \"\\$SERVER_TIMESTAMP\" != \"\\$LOCAL_TIMESTAMP\" ]; then\n    logger -p local2.notice -t moodle \"Server time stamp (\\$SERVER_TIMESTAMP) is different from local time stamp (\\$LOCAL_TIMESTAMP). Start syncing...\"\n    if [[ \\$(find $SYNC_LOG_FULLPATH -type f -size +20M 2> /dev/null) ]]; then\n      truncate -s 0 $SYNC_LOG_FULLPATH\n    fi\n    echo \\$(date +%Y%m%d%H%M%S) >> $SYNC_LOG_FULLPATH\n    rsync -av --delete /moodle/html/moodle /var/www/html >> $SYNC_LOG_FULLPATH\n  fi\nelse\n  logger -p local2.notice -t moodle \"Remote timestamp file ($SERVER_TIMESTAMP_FULLPATH) does not exist. Is /moodle mounted? Exiting with error.\"\n  exit 1\nfi\nEOF\n  chmod 500 ${SYNC_SCRIPT_FULLPATH}\n\n  local CRON_DESC_FULLPATH=\"/etc/cron.d/sync-moodle-html-local-copy\"\n  cat <<EOF > ${CRON_DESC_FULLPATH}\n* * * * * root ${SYNC_SCRIPT_FULLPATH}\nEOF\n  chmod 644 ${CRON_DESC_FULLPATH}\n\n  # Addition of a hook for custom script run on VMSS from shared mount to allow customised configuration of the VMSS as required\n  local CRON_DESC_FULLPATH2=\"/etc/cron.d/update-vmss-config\"\n  cat <<EOF > ${CRON_DESC_FULLPATH2}\n* * * * * root [ -f /moodle/bin/update-vmss-config ] && /bin/bash /moodle/bin/update-vmss-config\nEOF\n  chmod 644 ${CRON_DESC_FULLPATH2}\n}\n\nLAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH=\"/usr/local/bin/update_last_modified_time.moodle_on_azure.sh\"\n\n# Create a script to modify the last modified timestamp file (/moodle/html/moodle/last_modified_time.moodle_on_azure)\n# Should be called by root and only on the controller VM.\n# The moodle admin should run the generated script everytime the /moodle/html/moodle directory content is updated (e.g., moodle upgrade, config change or plugin install/upgrade)\nfunction create_last_modified_time_update_script {\n  if [ \"$(whoami)\" != \"root\" ]; then\n    echo \"${0}: Must be run as root!\"\n    return 1\n  fi\n\n  mkdir -p $(dirname $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH)\n  cat <<EOF > $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n#!/bin/bash\necho \\$(date +%Y%m%d%H%M%S) > $SERVER_TIMESTAMP_FULLPATH\nEOF\n\n  chmod +x $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n}\n\nfunction run_once_last_modified_time_update_script {\n  $LAST_MODIFIED_TIME_UPDATE_SCRIPT_FULLPATH\n}\n\n# O365 plugins are released only for 'MOODLE_xy_STABLE',\n# whereas we want to support the Moodle tagged versions (e.g., 'v3.4.2').\n# This function helps getting the stable version # (for O365 plugin ver.)\n# from a Moodle version tag. This utility function recognizes tag names\n# of the form 'vx.y.z' only.\nfunction get_o365plugin_version_from_moodle_version {\n  local moodleVersion=${1}\n  if [[ \"$moodleVersion\" =~ v([0-9]+)\\.([0-9]+)\\.([0-9]+) ]]; then\n    echo \"MOODLE_${BASH_REMATCH[1]}${BASH_REMATCH[2]}_STABLE\"\n  else\n    echo $moodleVersion\n  fi\n}\n\n# For Moodle tags (e.g., \"v3.4.2\"), the unzipped Moodle dir is no longer\n# \"moodle-$moodleVersion\", because for tags, it's without \"v\". That is,\n# it's \"moodle-3.4.2\". Therefore, we need a separate helper function for that...\nfunction get_moodle_unzip_dir_from_moodle_version {\n  local moodleVersion=${1}\n  if [[ \"$moodleVersion\" =~ v([0-9]+)\\.([0-9]+)\\.([0-9]+) ]]; then\n    echo \"moodle-${BASH_REMATCH[1]}.${BASH_REMATCH[2]}.${BASH_REMATCH[3]}\"\n  else\n    echo \"moodle-$moodleVersion\"\n  fi\n}\n\n# Long Redis cache Moodle config file generation code moved here\nfunction create_redis_configuration_in_moodledata_muc_config_php\n{\n    # create redis configuration in /moodle/moodledata/muc/config.php\n    cat <<EOF > /moodle/moodledata/muc/config.php\n<?php defined('MOODLE_INTERNAL') || die();\n \\$configuration = array (\n  'siteidentifier' => '7a142be09ea65699e4a6f6ef91c0773c',\n  'stores' =>\n  array (\n    'default_application' =>\n    array (\n      'name' => 'default_application',\n      'plugin' => 'file',\n      'configuration' =>\n      array (\n      ),\n      'features' => 30,\n      'modes' => 3,\n      'default' => true,\n      'class' => 'cachestore_file',\n      'lock' => 'cachelock_file_default',\n    ),\n    'default_session' =>\n    array (\n      'name' => 'default_session',\n      'plugin' => 'session',\n      'configuration' =>\n      array (\n      ),\n      'features' => 14,\n      'modes' => 2,\n      'default' => true,\n      'class' => 'cachestore_session',\n      'lock' => 'cachelock_file_default',\n    ),\n    'default_request' =>\n    array (\n      'name' => 'default_request',\n      'plugin' => 'static',\n      'configuration' =>\n      array (\n      ),\n      'features' => 31,\n      'modes' => 4,\n      'default' => true,\n      'class' => 'cachestore_static',\n      'lock' => 'cachelock_file_default',\n    ),\n    'redis' =>\n    array (\n      'name' => 'redis',\n      'plugin' => 'redis',\n      'configuration' =>\n      array (\n        'server' => '$redisDns',\n        'prefix' => 'moodle_prod',\n        'password' => '$redisAuth',\n        'serializer' => '1',\n      ),\n      'features' => 26,\n      'modes' => 3,\n      'mappingsonly' => false,\n      'class' => 'cachestore_redis',\n      'default' => false,\n      'lock' => 'cachelock_file_default',\n    ),\n    'local_file' =>\n    array (\n      'name' => 'local_file',\n      'plugin' => 'file',\n      'configuration' =>\n      array (\n        'path' => '/tmp/muc/moodle_prod',\n        'autocreate' => 1,\n      ),\n      'features' => 30,\n      'modes' => 3,\n      'mappingsonly' => false,\n      'class' => 'cachestore_file',\n      'default' => false,\n      'lock' => 'cachelock_file_default',\n    ),\n  ),\n  'modemappings' =>\n  array (\n    0 =>\n    array (\n      'store' => 'redis',\n      'mode' => 1,\n      'sort' => 0,\n    ),\n    1 =>\n    array (\n      'store' => 'default_session',\n      'mode' => 2,\n      'sort' => 0,\n    ),\n    2 =>\n    array (\n      'store' => 'default_request',\n      'mode' => 4,\n      'sort' => 0,\n    ),\n  ),\n  'definitions' =>\n  array (\n    'core/string' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'string',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/langmenu' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'langmenu',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/databasemeta' =>\n    array (\n      'mode' => 1,\n      'requireidentifiers' =>\n      array (\n        0 => 'dbfamily',\n      ),\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 15,\n      'component' => 'core',\n      'area' => 'databasemeta',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/eventinvalidation' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'requiredataguarantee' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'eventinvalidation',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/questiondata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'requiredataguarantee' => false,\n      'datasource' => 'question_finder',\n      'datasourcefile' => 'question/engine/bank.php',\n      'component' => 'core',\n      'area' => 'questiondata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/htmlpurifier' =>\n    array (\n      'mode' => 1,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'htmlpurifier',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/config' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'config',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/groupdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'groupdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/calendar_subscriptions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'calendar_subscriptions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/capabilities' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'capabilities',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/yuimodules' =>\n    array (\n      'mode' => 1,\n      'component' => 'core',\n      'area' => 'yuimodules',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/observers' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'observers',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/plugin_manager' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'plugin_manager',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecattree' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n      ),\n      'component' => 'core',\n      'area' => 'coursecattree',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecat' =>\n    array (\n      'mode' => 2,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n        1 => 'changesincourse',\n      ),\n      'ttl' => 600,\n      'component' => 'core',\n      'area' => 'coursecat',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/coursecatrecords' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesincoursecat',\n      ),\n      'component' => 'core',\n      'area' => 'coursecatrecords',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/coursecontacts' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'simplekeys' => true,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'coursecontacts',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/repositories' =>\n    array (\n      'mode' => 4,\n      'component' => 'core',\n      'area' => 'repositories',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/externalbadges' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'ttl' => 3600,\n      'component' => 'core',\n      'area' => 'externalbadges',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursemodinfo' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'canuselocalstore' => true,\n      'component' => 'core',\n      'area' => 'coursemodinfo',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/userselections' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'userselections',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/completion' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'ttl' => 3600,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'component' => 'core',\n      'area' => 'completion',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/coursecompletion' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'ttl' => 3600,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'core',\n      'area' => 'coursecompletion',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/navigation_expandcourse' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'navigation_expandcourse',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/suspended_userids' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'suspended_userids',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/roledefs' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'core',\n      'area' => 'roledefs',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/plugin_functions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 5,\n      'component' => 'core',\n      'area' => 'plugin_functions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/tags' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'tags',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/grade_categories' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'invalidationevents' =>\n      array (\n        0 => 'changesingradecategories',\n      ),\n      'component' => 'core',\n      'area' => 'grade_categories',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/temp_tables' =>\n    array (\n      'mode' => 4,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'component' => 'core',\n      'area' => 'temp_tables',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/tagindexbuilder' =>\n    array (\n      'mode' => 2,\n      'simplekeys' => true,\n      'simplevalues' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'ttl' => 900,\n      'invalidationevents' =>\n      array (\n        0 => 'resettagindexbuilder',\n      ),\n      'component' => 'core',\n      'area' => 'tagindexbuilder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'core/contextwithinsights' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'core',\n      'area' => 'contextwithinsights',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/message_processors_enabled' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 3,\n      'component' => 'core',\n      'area' => 'message_processors_enabled',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/message_time_last_message_between_users' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simplevalues' => true,\n      'datasource' => '\\\\core_message\\\\time_last_message_between_users',\n      'component' => 'core',\n      'area' => 'message_time_last_message_between_users',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/fontawesomeiconmapping' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'core',\n      'area' => 'fontawesomeiconmapping',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/postprocessedcss' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => false,\n      'component' => 'core',\n      'area' => 'postprocessedcss',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'core/user_group_groupings' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'component' => 'core',\n      'area' => 'user_group_groupings',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'availability_grade/scores' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'ttl' => 3600,\n      'component' => 'availability_grade',\n      'area' => 'scores',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'availability_grade/items' =>\n    array (\n      'mode' => 1,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 2,\n      'ttl' => 3600,\n      'component' => 'availability_grade',\n      'area' => 'items',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'mod_glossary/concepts' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => false,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 30,\n      'component' => 'mod_glossary',\n      'area' => 'concepts',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_googledocs/folder' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => false,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'canuselocalstore' => true,\n      'component' => 'repository_googledocs',\n      'area' => 'folder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_onedrive/folder' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => false,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'canuselocalstore' => true,\n      'component' => 'repository_onedrive',\n      'area' => 'folder',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'repository_skydrive/foldername' =>\n    array (\n      'mode' => 2,\n      'component' => 'repository_skydrive',\n      'area' => 'foldername',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'tool_mobile/plugininfo' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_mobile',\n      'area' => 'plugininfo',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_monitor/eventsubscriptions' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 10,\n      'component' => 'tool_monitor',\n      'area' => 'eventsubscriptions',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_uploadcourse/helper' =>\n    array (\n      'mode' => 4,\n      'component' => 'tool_uploadcourse',\n      'area' => 'helper',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 2,\n    ),\n    'tool_usertours/tourdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_usertours',\n      'area' => 'tourdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n    'tool_usertours/stepdata' =>\n    array (\n      'mode' => 1,\n      'simplekeys' => true,\n      'simpledata' => true,\n      'staticacceleration' => true,\n      'staticaccelerationsize' => 1,\n      'component' => 'tool_usertours',\n      'area' => 'stepdata',\n      'selectedsharingoption' => 2,\n      'userinputsharingkey' => '',\n      'sharingoptions' => 15,\n    ),\n  ),\n  'definitionmappings' =>\n  array (\n    0 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/coursemodinfo',\n      'sort' => 1,\n    ),\n    1 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/groupdata',\n      'sort' => 1,\n    ),\n    2 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/roledefs',\n      'sort' => 1,\n    ),\n    3 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_usertours/tourdata',\n      'sort' => 1,\n    ),\n    4 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'repository_onedrive/folder',\n      'sort' => 1,\n    ),\n    5 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/message_processors_enabled',\n      'sort' => 1,\n    ),\n    6 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecontacts',\n      'sort' => 1,\n    ),\n    7 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'repository_googledocs/folder',\n      'sort' => 1,\n    ),\n    8 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/questiondata',\n      'sort' => 1,\n    ),\n    9 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecat',\n      'sort' => 1,\n    ),\n    10 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/databasemeta',\n      'sort' => 1,\n    ),\n    11 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/eventinvalidation',\n      'sort' => 1,\n    ),\n    12 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecattree',\n      'sort' => 1,\n    ),\n    13 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/coursecompletion',\n      'sort' => 1,\n    ),\n    14 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/user_group_groupings',\n      'sort' => 1,\n    ),\n    15 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/capabilities',\n      'sort' => 1,\n    ),\n    16 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/yuimodules',\n      'sort' => 1,\n    ),\n    17 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/observers',\n      'sort' => 1,\n    ),\n    18 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'mod_glossary/concepts',\n      'sort' => 1,\n    ),\n    19 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/fontawesomeiconmapping',\n      'sort' => 1,\n    ),\n    20 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/config',\n      'sort' => 1,\n    ),\n    21 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_mobile/plugininfo',\n      'sort' => 1,\n    ),\n    22 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/plugin_functions',\n      'sort' => 1,\n    ),\n    23 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/postprocessedcss',\n      'sort' => 1,\n    ),\n    24 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/plugin_manager',\n      'sort' => 1,\n    ),\n    25 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_usertours/stepdata',\n      'sort' => 1,\n    ),\n    26 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'availability_grade/items',\n      'sort' => 1,\n    ),\n    27 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/string',\n      'sort' => 1,\n    ),\n    28 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/externalbadges',\n      'sort' => 1,\n    ),\n    29 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/langmenu',\n      'sort' => 1,\n    ),\n    30 =>\n    array (\n      'store' => 'local_file',\n      'definition' => 'core/htmlpurifier',\n      'sort' => 1,\n    ),\n    31 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/completion',\n      'sort' => 1,\n    ),\n    32 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/calendar_subscriptions',\n      'sort' => 1,\n    ),\n    33 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/contextwithinsights',\n      'sort' => 1,\n    ),\n    34 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'tool_monitor/eventsubscriptions',\n      'sort' => 1,\n    ),\n    35 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'core/message_time_last_message_between_users',\n      'sort' => 1,\n    ),\n    36 =>\n    array (\n      'store' => 'redis',\n      'definition' => 'availability_grade/scores',\n      'sort' => 1,\n    ),\n  ),\n  'locks' =>\n  array (\n    'cachelock_file_default' =>\n    array (\n      'name' => 'cachelock_file_default',\n      'type' => 'cachelock_file',\n      'dir' => 'filelocks',\n      'default' => true,\n    ),\n  ),\n);\nEOF\n}\n\n# Long fail2ban config command moved here\nfunction config_fail2ban\n{\n    cat <<EOF > /etc/fail2ban/jail.conf\n# Fail2Ban configuration file.\n#\n# This file was composed for Debian systems from the original one\n# provided now under /usr/share/doc/fail2ban/examples/jail.conf\n# for additional examples.\n#\n# Comments: use '#' for comment lines and ';' for inline comments\n#\n# To avoid merges during upgrades DO NOT MODIFY THIS FILE\n# and rather provide your changes in /etc/fail2ban/jail.local\n#\n\n# The DEFAULT allows a global definition of the options. They can be overridden\n# in each jail afterwards.\n\n[DEFAULT]\n\n# \"ignoreip\" can be an IP address, a CIDR mask or a DNS host. Fail2ban will not\n# ban a host which matches an address in this list. Several addresses can be\n# defined using space separator.\nignoreip = 127.0.0.1/8\n\n# \"bantime\" is the number of seconds that a host is banned.\nbantime  = 600\n\n# A host is banned if it has generated \"maxretry\" during the last \"findtime\"\n# seconds.\nfindtime = 600\nmaxretry = 3\n\n# \"backend\" specifies the backend used to get files modification.\n# Available options are \"pyinotify\", \"gamin\", \"polling\" and \"auto\".\n# This option can be overridden in each jail as well.\n#\n# pyinotify: requires pyinotify (a file alteration monitor) to be installed.\n#            If pyinotify is not installed, Fail2ban will use auto.\n# gamin:     requires Gamin (a file alteration monitor) to be installed.\n#            If Gamin is not installed, Fail2ban will use auto.\n# polling:   uses a polling algorithm which does not require external libraries.\n# auto:      will try to use the following backends, in order:\n#            pyinotify, gamin, polling.\nbackend = auto\n\n# \"usedns\" specifies if jails should trust hostnames in logs,\n#   warn when reverse DNS lookups are performed, or ignore all hostnames in logs\n#\n# yes:   if a hostname is encountered, a reverse DNS lookup will be performed.\n# warn:  if a hostname is encountered, a reverse DNS lookup will be performed,\n#        but it will be logged as a warning.\n# no:    if a hostname is encountered, will not be used for banning,\n#        but it will be logged as info.\nusedns = warn\n\n#\n# Destination email address used solely for the interpolations in\n# jail.{conf,local} configuration files.\ndestemail = root@localhost\n\n#\n# Name of the sender for mta actions\nsendername = Fail2Ban\n\n#\n# ACTIONS\n#\n\n# Default banning action (e.g. iptables, iptables-new,\n# iptables-multiport, shorewall, etc) It is used to define\n# action_* variables. Can be overridden globally or per\n# section within jail.local file\nbanaction = iptables-multiport\n\n# email action. Since 0.8.1 upstream fail2ban uses sendmail\n# MTA for the mailing. Change mta configuration parameter to mail\n# if you want to revert to conventional 'mail'.\nmta = sendmail\n\n# Default protocol\nprotocol = tcp\n\n# Specify chain where jumps would need to be added in iptables-* actions\nchain = INPUT\n\n#\n# Action shortcuts. To be used to define action parameter\n\n# The simplest action to take: ban only\naction_ = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n\n# ban & send an e-mail with whois report to the destemail.\naction_mw = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n              %(mta)s-whois[name=%(__name__)s, dest=\"%(destemail)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# ban & send an e-mail with whois report and relevant log lines\n# to the destemail.\naction_mwl = %(banaction)s[name=%(__name__)s, port=\"%(port)s\", protocol=\"%(protocol)s\", chain=\"%(chain)s\"]\n               %(mta)s-whois-lines[name=%(__name__)s, dest=\"%(destemail)s\", logpath=%(logpath)s, chain=\"%(chain)s\", sendername=\"%(sendername)s\"]\n\n# Choose default action.  To change, just override value of 'action' with the\n# interpolation to the chosen action shortcut (e.g.  action_mw, action_mwl, etc) in jail.local\n# globally (section [DEFAULT]) or per specific section\naction = %(action_)s\n\n#\n# JAILS\n#\n\n# Next jails corresponds to the standard configuration in Fail2ban 0.6 which\n# was shipped in Debian. Enable any defined here jail by including\n#\n# [SECTION_NAME]\n# enabled = true\n\n#\n# in /etc/fail2ban/jail.local.\n#\n# Optionally you may override any other parameter (e.g. banaction,\n# action, port, logpath, etc) in that section within jail.local\n\n[ssh]\n\nenabled  = true\nport     = ssh\nfilter   = sshd\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[dropbear]\n\nenabled  = false\nport     = ssh\nfilter   = dropbear\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n# Generic filter for pam. Has to be used with action which bans all ports\n# such as iptables-allports, shorewall\n[pam-generic]\n\nenabled  = false\n# pam-generic filter can be customized to monitor specific subset of 'tty's\nfilter   = pam-generic\n# port actually must be irrelevant but lets leave it all for some possible uses\nport     = all\nbanaction = iptables-allports\nport     = anyport\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n[xinetd-fail]\n\nenabled   = false\nfilter    = xinetd-fail\nport      = all\nbanaction = iptables-multiport-log\nlogpath   = /var/log/daemon.log\nmaxretry  = 2\n\n\n[ssh-ddos]\n\nenabled  = false\nport     = ssh\nfilter   = sshd-ddos\nlogpath  = /var/log/auth.log\nmaxretry = 6\n\n\n# Here we use blackhole routes for not requiring any additional kernel support\n# to store large volumes of banned IPs\n\n[ssh-route]\n\nenabled = false\nfilter = sshd\naction = route\nlogpath = /var/log/sshd.log\nmaxretry = 6\n\n# Here we use a combination of Netfilter/Iptables and IPsets\n# for storing large volumes of banned IPs\n#\n# IPset comes in two versions. See ipset -V for which one to use\n# requires the ipset package and kernel support.\n[ssh-iptables-ipset4]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto4\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n[ssh-iptables-ipset6]\n\nenabled  = false\nport     = ssh\nfilter   = sshd\nbanaction = iptables-ipset-proto6\nlogpath  = /var/log/sshd.log\nmaxretry = 6\n\n\n#\n# HTTP servers\n#\n\n[apache]\n\nenabled  = false\nport     = http,https\nfilter   = apache-auth\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n# default action is now multiport, so apache-multiport jail was left\n# for compatibility with previous (<0.7.6-2) releases\n[apache-multiport]\n\nenabled   = false\nport      = http,https\nfilter    = apache-auth\nlogpath   = /var/log/apache*/*error.log\nmaxretry  = 6\n\n[apache-noscript]\n\nenabled  = false\nport     = http,https\nfilter   = apache-noscript\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 6\n\n[apache-overflows]\n\nenabled  = false\nport     = http,https\nfilter   = apache-overflows\nlogpath  = /var/log/apache*/*error.log\nmaxretry = 2\n\n# Ban attackers that try to use PHP's URL-fopen() functionality\n# through GET/POST variables. - Experimental, with more than a year\n# of usage in production environments.\n\n[php-url-fopen]\n\nenabled = false\nport    = http,https\nfilter  = php-url-fopen\nlogpath = /var/www/*/logs/access_log\n\n# A simple PHP-fastcgi jail which works with lighttpd.\n# If you run a lighttpd server, then you probably will\n# find these kinds of messages in your error_log:\n#   ALERT \u00e2\u20ac\u201c tried to register forbidden variable \u00e2\u20ac\u02dcGLOBALS\u00e2\u20ac\u2122\n#   through GET variables (attacker '1.2.3.4', file '/var/www/default/htdocs/index.php')\n\n[lighttpd-fastcgi]\n\nenabled = false\nport    = http,https\nfilter  = lighttpd-fastcgi\nlogpath = /var/log/lighttpd/error.log\n\n# Same as above for mod_auth\n# It catches wrong authentifications\n\n[lighttpd-auth]\n\nenabled = false\nport    = http,https\nfilter  = suhosin\nlogpath = /var/log/lighttpd/error.log\n\n[nginx-http-auth]\n\nenabled = false\nfilter  = nginx-http-auth\nport    = http,https\nlogpath = /var/log/nginx/error.log\n\n# Monitor roundcube server\n\n[roundcube-auth]\n\nenabled  = false\nfilter   = roundcube-auth\nport     = http,https\nlogpath  = /var/log/roundcube/userlogins\n\n\n[sogo-auth]\n\nenabled  = false\nfilter   = sogo-auth\nport     = http, https\n# without proxy this would be:\n# port    = 20000\nlogpath  = /var/log/sogo/sogo.log\n\n\n#\n# FTP servers\n#\n\n[vsftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = vsftpd\nlogpath  = /var/log/vsftpd.log\n# or overwrite it in jails.local to be\n# logpath = /var/log/auth.log\n# if you want to rely on PAM failed login attempts\n# vsftpd's failregex should match both of those formats\nmaxretry = 6\n\n\n[proftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = proftpd\nlogpath  = /var/log/proftpd/proftpd.log\nmaxretry = 6\n\n\n[pure-ftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = pure-ftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n[wuftpd]\n\nenabled  = false\nport     = ftp,ftp-data,ftps,ftps-data\nfilter   = wuftpd\nlogpath  = /var/log/syslog\nmaxretry = 6\n\n\n#\n# Mail servers\n#\n\n[postfix]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = postfix\nlogpath  = /var/log/mail.log\n\n\n[couriersmtp]\n\nenabled  = false\nport     = smtp,ssmtp,submission\nfilter   = couriersmtp\nlogpath  = /var/log/mail.log\n\n\n#\n# Mail servers authenticators: might be used for smtp,ftp,imap servers, so\n# all relevant ports get banned\n#\n\n[courierauth]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = courierlogin\nlogpath  = /var/log/mail.log\n\n\n[sasl]\n\nenabled  = false\nport     = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter   = postfix-sasl\n# You might consider monitoring /var/log/mail.warn instead if you are\n# running postfix since it would provide the same log lines at the\n# \"warn\" level but overall at the smaller filesize.\nlogpath  = /var/log/mail.log\n\n[dovecot]\n\nenabled = false\nport    = smtp,ssmtp,submission,imap2,imap3,imaps,pop3,pop3s\nfilter  = dovecot\nlogpath = /var/log/mail.log\n\n# To log wrong MySQL access attempts add to /etc/my.cnf:\n# log-error=/var/log/mysqld.log\n# log-warning = 2\n[mysqld-auth]\n\nenabled  = false\nfilter   = mysqld-auth\nport     = 3306\nlogpath  = /var/log/mysqld.log\n\n\n# DNS Servers\n\n\n# These jails block attacks against named (bind9). By default, logging is off\n# with bind9 installation. You will need something like this:\n#\n# logging {\n#     channel security_file {\n#         file \"/var/log/named/security.log\" versions 3 size 30m;\n#         severity dynamic;\n#         print-time yes;\n#     };\n#     category security {\n#         security_file;\n#     };\n# };\n#\n# in your named.conf to provide proper logging\n\n# !!! WARNING !!!\n#   Since UDP is connection-less protocol, spoofing of IP and imitation\n#   of illegal actions is way too simple.  Thus enabling of this filter\n#   might provide an easy way for implementing a DoS against a chosen\n#   victim. See\n#    http://nion.modprobe.de/blog/archives/690-fail2ban-+-dns-fail.html\n#   Please DO NOT USE this jail unless you know what you are doing.\n#[named-refused-udp]\n#\n#enabled  = false\n#port     = domain,953\n#protocol = udp\n#filter   = named-refused\n#logpath  = /var/log/named/security.log\n\n[named-refused-tcp]\n\nenabled  = false\nport     = domain,953\nprotocol = tcp\nfilter   = named-refused\nlogpath  = /var/log/named/security.log\n\n# Multiple jails, 1 per protocol, are necessary ATM:\n# see https://github.com/fail2ban/fail2ban/issues/37\n[asterisk-tcp]\n\nenabled  = false\nfilter   = asterisk\nport     = 5060,5061\nprotocol = tcp\nlogpath  = /var/log/asterisk/messages\n\n[asterisk-udp]\n\nenabled  = false\nfilter\t = asterisk\nport     = 5060,5061\nprotocol = udp\nlogpath  = /var/log/asterisk/messages\n\n\n# Jail for more extended banning of persistent abusers\n# !!! WARNING !!!\n#   Make sure that your loglevel specified in fail2ban.conf/.local\n#   is not at DEBUG level -- which might then cause fail2ban to fall into\n#   an infinite loop constantly feeding itself with non-informative lines\n[recidive]\n\nenabled  = false\nfilter   = recidive\nlogpath  = /var/log/fail2ban.log\naction   = iptables-allports[name=recidive]\n           sendmail-whois-lines[name=recidive, logpath=/var/log/fail2ban.log]\nbantime  = 604800  ; 1 week\nfindtime = 86400   ; 1 day\nmaxretry = 5\nEOF\n}\n", "num_lines": 1860}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# Script to set up highly available NFS server on an Ubuntu 16.04 (or higher) VM\n# that should be used on Azure with the custom script extension (which runs this script as root)\n#\n\nset -e\n\n# Parameters\nNODE1NAME=$1\nNODE1IP=$2\nNODE2NAME=$3\nNODE2IP=$4\nNFS_CLIENTS_IP_RANGE=$5     # E.g., \"10.0.0.0/24\". Can be \"*\", but strongly discouraged\n\n# This VM's IP address, to detect if this VM should be the master (Node 1 is the initial master)\nMY_IP=$(hostname -i)\n\n. ./helper_functions.sh\n\nfunction setup_required_packages\n{\n    # Cleanup\n    dpkg --configure -a\n    apt-get install -f\n\n    # Upgrade\n    apt-get -y update\n    apt-get -y dist-upgrade\n\n    apt-get -y install build-essential autoconf flex nfs-kernel-server corosync pacemaker resource-agents\n\n    # Shouldn't let systemd start nfs-kernel-server (Pacemaker should do that)\n    systemctl stop nfs-kernel-server\n    systemctl disable nfs-kernel-server\n\n    # Setup static port assignments for mountd, statd, quotad, nlm (tcp), and nlm (udp) respectively:\n\tsed -i 's/^\\(RPCMOUNTDOPTS=\"--manage-gids\\)\"/\\1 -p 2000\"/g' /etc/default/nfs-kernel-server\n    sed -i 's/^STATDOPTS=.*$/STATDOPTS=\"--port 2001 --outgoing-port 2002\"/' /etc/default/nfs-common\n    if [ -f /etc/default/quota ]; then\n        sed -i 's/^RPCQUOTADOPTS=.*$/RPCQUOTADOPTS=\"-p 2003\"/' /etc/default/quota\n    fi\n\tcat <<EOF > /etc/modprobe.d/azmdl-nfs-ports.conf\noptions lockd nlm_udpport=2004 nlm_tcpport=2004\noptions nfs callback_tcpport=2005\nEOF\n\n    cat <<EOF > /etc/sysctl.d/30-azmdl-nfs-ports.conf\nfs.nfs.nlm_tcpport=2004\nfs.nfs.nlm_udpport=2004\nEOF\n    # Reread modified sysctl settings for modified NFS static ports\n    sysctl --system\n\n    # Above alone still doesn't work for static ports. Try restarting related services.\n    systemctl try-restart nfs-config.service rpcbind.service rpc-statd.service nfs-server.service\n\n    # We need to install the \"azure-lb\" command separately if the resource-agents package didn't have it.\n    pushd /usr/lib/ocf/resource.d/heartbeat\n    if [ ! -e azure-lb ]; then\n        curl -LO https://raw.githubusercontent.com/ClusterLabs/resource-agents/master/heartbeat/azure-lb\n        chmod +x ./azure-lb\n    fi\n    ln -s /bin/nc /usr/bin/nc\n    popd\n}\n\nfunction setup_drbd_module_and_tools\n{\n    # We currently have to build the DRBD kernel module, as it's not included\n    # in the default linux-azure kernels or in any Azure extra packages.\n    # We should use the packaged DRBD module once Azure starts releasing\n    # extra modules packages that include DRBD module.\n\n    pushd /tmp\n    git clone http://github.com/LINBIT/drbd-9.0\n    git clone http://github.com/LINBIT/drbd-utils\n    cd drbd-9.0\n    make && make install\n    modprobe drbd\n    cd ../drbd-utils\n    ./autogen.sh\n    ./configure --prefix=/usr --localstatedir=/var --sysconfdir=/etc\n    make tools && make install-tools\n    cd ..\n    rm -rf drbd-9.0 drbd-utils\n    popd\n}\n\nfunction setup_drbd_with_disk\n{\n    local disk=$1\n    local node1name=$2\n    local node1ip=$3\n    local node2name=$4\n    local node2ip=$5\n    local drbd_resource_name=$6\n    local drbd_device_path=$7\n    local drbd_device_mount_point=$8\n\n    # Put LVM (to gain more flexibility) on the whole disk\n    local vgname=drbdvg\n    local lvname=drbdlv\n    wipefs -af $disk\n    pvcreate $disk\n    vgcreate $vgname $disk\n    lvcreate -n $lvname -l 95%VG $vgname\n\n    # Set up DRBD config\n    cat <<EOF > /etc/drbd.d/${drbd_resource_name}.res\nresource $drbd_resource_name {\n    device      ${drbd_device_path};\n    disk        /dev/${vgname}/${lvname};\n    meta-disk   internal;\n    disk {\n        c-fill-target 1M;\n        c-max-rate 110M;\n        c-min-rate 120K;\n    }\n    net {\n        max-buffers 20k;\n    }\n    on ${node1name} {\n        address ${node1ip}:7789;\n    }\n    on ${node2name} {\n        address ${node2ip}:7789;\n    }\n}\nEOF\n\n    # Initialize DRBD's metadata and bring up the device on both nodes\n    drbdadm create-md $drbd_resource_name\n    drbdadm up $drbd_resource_name\n    drbdadm status\n\n    # On the master (initially node 1) only, force DRBD into Primary and create an ext4 file system on the DRBD device\n    if [ \"$MY_IP\" = \"$NODE1IP\" ]; then\n        drbdadm primary $drbd_resource_name --force\n        mkfs.ext4 $drbd_device_path\n        mkdir -p $drbd_device_mount_point && mount $drbd_device_path $drbd_device_mount_point\n    fi\n}\n\nfunction setup_corosync_and_pacemaker_for_nfs\n{\n    local node1ip=$1\n    local node2ip=$2\n    local drbd_resource_name=$3     # E.g., azmdlr0\n    local drbd_device_path=$4       # E.g., /dev/drbd0\n    local drbd_mount_point=$5       # E.g., /drbd\n    local nfs_export_path=$6        # E.g., /drbd/moodle\n    local nfs_client_spec=$7        # E.g., * or 10.11.22.0/24\n\n    mv /etc/corosync/corosync.conf /etc/corosync/corosync.conf.orig || true\n\n    local cluster_name=azmdl-cluster\n\n    cat <<EOF > /etc/corosync/corosync.conf\ntotem {\n    version: 2\n    secauth: off\n    cluster_name: ${cluster_name}\n    transport: udpu\n}\n\nnodelist {\n    node {\n        ring0_addr: ${node1ip}\n        nodeid: 1\n    }\n    node {\n        ring0_addr: ${node2ip}\n        nodeid: 2\n    }\n}\n\nquorum {\n    provider: corosync_votequorum\n    two_node:1\n}\n\nlogging {\n    to_syslog: yes\n}\nEOF\n\n    systemctl enable corosync pacemaker\n    systemctl restart corosync pacemaker\n\n    # TODO Should confirm if 'corosync-cfgtool -s' gives a non-loopback IP address (not 127.0.0.1), e.g.:\n    # $ corosync-cfgtool -s\n    # Printing ring status.\n    # Local node ID 2\n    # RING ID 0\n    #     id = 10.0.0.5\n    #     status = ring 0 active with no faults\n\n    # Finally, configure Pacemaker cluster resources, only on the initial master\n    if [ \"$MY_IP\" = \"$node1ip\" ]; then\n        mkdir -p ${nfs_export_path}\n        crm configure <<EOF\nprimitive p_drbd_r0 ocf:linbit:drbd \\\n    params drbd_resource=${drbd_resource_name} \\\n    op monitor interval=29s role=Master \\\n    op monitor interval=31s role=Slave \\\n    op start interval=0s timeout=240s \\\n    op stop interval=0s timeout=100s\nms ms_drbd_r0 p_drbd_r0 \\\n    meta master-max=1 master-node-max=1 clone-node-max=1 clone-max=2 notify=true\nprimitive p_fs_data Filesystem \\\n    params device=\"${drbd_device_path}\" directory=\"${drbd_mount_point}\" \\\n    fstype=ext4 options=noatime,nodiratime \\\n    op start interval=0s timeout=100s \\\n    op stop interval=0s timeout=100s \\\n    op monitor interval=10s timeout=100s\nprimitive p_nfsserver ocf:heartbeat:nfsserver \\\n    params nfs_shared_infodir=\"${drbd_mount_point}/nfs_shared_infodir\" \\\n    op start interval=0s timeout=40s \\\n    op stop interval=0s timeout=20s \\\n    op monitor interval=10s timeout=20s\nprimitive p_exportfs ocf:heartbeat:exportfs \\\n    params clientspec=\"${nfs_client_spec}\" directory=\"${nfs_export_path}\" fsid=1 \\\n    unlock_on_stop=1 options=rw,sync,no_root_squash \\\n    op start interval=0s timeout=40s \\\n    op stop interval=0s timeout=120s \\\n    op monitor interval=10s timeout=20s\nprimitive p_azure-lb azure-lb \\\n    params nc=\"/bin/nc\" port=\"61000\" \\\n    op start interval=0s timeout=20s \\\n    op stop interval=0s timeout=20s \\\n    op monitor interval=10s timeout=20s\ngroup g_services p_fs_data p_nfsserver p_exportfs p_azure-lb\ncolocation cl-g_services-with-ms_drbd_r0 inf: g_services ms_drbd_r0:Master\norder o-ms_drbd_r0-before-g_services inf: ms_drbd_r0:promote g_services:start\nproperty stonith-enabled=false\nEOF\n    fi\n    # TODO STONITH is disabled for now (two lines above). Should enable it soon.\n\n    # TODO 'crm status' should show the correctly configured/started cluster resources.\n}\n\n# Main\n\nsetup_required_packages\n\nsetup_drbd_module_and_tools\n\n# Don't create a file system, but just set up a disk (RAID if multiple unpartitioned disks)\n# AZMDL_DISK env var is set by the function as the discovered/initialized disk\nsetup_raid_disk_and_filesystem None /dev/md0 None False\n\nDRBD_RESOURCE_NAME=azmdlr0   # TODO Avoid hard-coded value\nDRBD_DEVICE_PATH=/dev/drbd0\nDRBD_MOUNT_POINT=/drbd       # TODO Avoid hard-coded value\n\nsetup_drbd_with_disk $AZMDL_DISK $NODE1NAME $NODE1IP $NODE2NAME $NODE2IP $DRBD_RESOURCE_NAME $DRBD_DEVICE_PATH $DRBD_MOUNT_POINT\n\nNFS_EXPORT_PATH=${DRBD_MOUNT_POINT}/data  # TODO Allow different export dir name -- This requires changes all along the pipeline, from the top-level template to this script...\n\nsetup_corosync_and_pacemaker_for_nfs $NODE1IP $NODE2IP $DRBD_RESOURCE_NAME $DRBD_DEVICE_PATH $DRBD_MOUNT_POINT $NFS_EXPORT_PATH \"$NFS_CLIENTS_IP_RANGE\"\n\necho \"NFS-HA setup succeeded. NFS_EXPORT_PATH=${NFS_EXPORT_PATH}, NFS_CLIENT_SPEC=${NFS_CLIENT_SPEC}\"\n", "num_lines": 265}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nuserPassword=$1\n\n# adding official OpeenVPN Access Servere repository\nsudo apt update && sudo apt -y install ca-certificates wget net-tools\nwget -qO - https://as-repository.openvpn.net/as-repo-public.gpg | sudo apt-key add -\nsudo sh -c 'echo \"deb http://as-repository.openvpn.net/as/debian bionic main\">>/etc/apt/sources.list.d/openvpn-as-repo.list'\n\n# installing the OpenVPN Serve\nsudo apt update && sudo apt -y install openvpn-as\n\n#update the password for user openvpn\nsudo echo \"openvpn:$userPassword\"|sudo chpasswd\n\n#configure server network settings\nPUBLICIP=$(curl -s ifconfig.me)\nsudo apt-get install sqlite3\nsudo sqlite3 \"/usr/local/openvpn_as/etc/db/config.db\" \"update config set value='$PUBLICIP' where name='host.name';\"\n\n#restart OpenVPN AS service\nsudo systemctl restart openvpnas\n", "num_lines": 22}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho ExamplePostInstall1.sh was run at $(date)", "num_lines": 2}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho ExamplePostInstall2.sh was run at $(date)\nif hash zypper; then\n  zypper install -y python3-pip screen\nelse\n  yum install -y python3-pip screen\n  firewall-cmd --zone=public --add-port=80/tcp --permanent\n  firewall-cmd --reload\nfi\npython3 -m pip install http.server\necho \"<html><body>Test HTTP Server Running on $(curl -H Metadata:true \"http://169.254.169.254/metadata/instance/compute/name?api-version=2017-08-01&format=text\")</body></html>\" > index.html\n/usr/bin/screen -dmS simple-web python3 -m http.server 80\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho SetupJump.sh was run at $(date) | tee -a /var/log/ExamplePostInstall3.log\necho SetupJump.sh was called with arguements: \"$@\" | tee -a /var/log/ExamplePostInstall3.log", "num_lines": 3}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Sleep 30 seconds to allow network to stabalize before attempting package install\nsleep 30\nyum install -y mdadm\nn=$(find /dev/disk/azure/scsi1/ -name \"lun*\"|wc -l)\nn=\"${n//\\ /}\"\nmdadm --create /dev/md0 --force --level=stripe --raid-devices=$n /dev/disk/azure/scsi1/lun*\nmkfs.xfs /dev/md0\nmkdir /mnt/raid0\necho \"$(blkid /dev/md0 | cut -d ' ' -f 2) /mnt/raid0 xfs defaults 0 0\" | tee -a /etc/fstab\nmount /mnt/raid0\n", "num_lines": 12}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Sleep 30 seconds to allow network to stabalize before attempting package install\nsleep 30\nzypper install -y mdadm\nn=$(find /dev/disk/azure/scsi1/ -name \"lun*\"|wc -l)\nn=\"${n//\\ /}\"\nmdadm --create /dev/md0 --force --level=stripe --raid-devices=$n /dev/disk/azure/scsi1/lun*\nmkfs.xfs /dev/md0\nmkdir /mnt/raid0\necho \"$(blkid /dev/md0 | cut -d ' ' -f 2) /mnt/raid0 xfs defaults 0 0\" | tee -a /etc/fstab\nmount /mnt/raid0\n", "num_lines": 12}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nenv ASSUME_ALWAYS_YES=YES pkg bootstrap\npkg update\npkg install -y nginx\npkg install -y php56\npkg install -y php56-pgsql-5.6.30\n\necho 'nginx_enable=\"YES\"' >> /etc/rc.conf\necho 'php_fpm_enable=\"YES\"' >> /etc/rc.conf\necho 'ifconfig_hn1=\"DHCP\"' >> /etc/rc.conf\n\nifconfig hn1 up\n\ncp /usr/local/etc/nginx/nginx.conf /usr/local/etc/nginx/nginx.conf.bak\ncp ./backend_nginx.conf /usr/local/etc/nginx/nginx.conf\n\ncp /usr/local/etc/php.ini-production /usr/local/etc/php.ini\ncp /usr/local/etc/php-fpm.conf /usr/local/etc/php-fpm.conf.bak\n\nsed -i -e 's/^listen = 127.0.0.1:9000/listen = \\/var\\/run\\/php-fpm.sock/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^;listen.owner = www/listen.owner = www/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^;listen.group = www/listen.group = www/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^;listen.mode = 0660/listen.mode = 0660/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^;events.mechanism = epoll/events.mechanism = kqueue/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^pm = dynamic/pm = static/g' /usr/local/etc/php-fpm.conf\nsed -i -e 's/^pm.max_children = 5/pm.max_children = 240/g' /usr/local/etc/php-fpm.conf\n\nre=`find / -name pgsql.so`\necho $re | sed 's./.\\\\/.g' > 1.txt\nsed -i -e \"s/^;   extension=modulename.extension/extension=`cat 1.txt`/g\" /usr/local/etc/php.ini\n\necho \"<?php\" >> /usr/local/www/nginx/index.php\necho 'echo \"Hello world!\";' >> /usr/local/www/nginx/index.php\necho \"?>\" >> /usr/local/www/nginx/index.php\n\nservice nginx restart\nservice php-fpm restart\n\nsed -i -e '/^[^#]/d' /etc/sysctl.conf\necho 'kern.ipc.soacceptqueue=4096' >> /etc/sysctl.conf\necho 'net.inet.tcp.msl=1000' >> /etc/sysctl.conf\n\necho \"/sbin/reboot\" | at + 1 minute\n", "num_lines": 45}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\ninstall_postgresql_service() {\n\techo \"Start installing PostgreSQL...\"\n\tpkg install -y postgresql93-server postgresql93-client\n\tif [ $? == 0 ];then\n\t\techo 'postgresql_enable=\"YES\"' >> /etc/rc.conf\n\t\techo 'postgresql_data=\"/stripe/postgres/data\"' >> /etc/rc.conf\n\t\tchown -R pgsql:pgsql /stripe/\n\t\tsu pgsql -c '/usr/local/bin/initdb -D /stripe/postgres/data/'\n\t\techo 'host    all             all             0.0.0.0/0               md5' >> /stripe/postgres/data/pg_hba.conf\n\t\tcp ./postgresql.conf /stripe/postgres/data/postgresql.conf\n\tfi\n\techo \"Done installing PostgreSQL...\"\n}\n\ninstall_pgbouncer_service() {\n\techo \"Start installing pgbouncer...\"\n\tpkg install -y pgbouncer\n\tif [ $? == 0 ];then\n\t\techo 'kern.ipc.semmni=512' >> /boot/loader.conf\n\t\techo 'kern.ipc.semmns=1024' >> /boot/loader.conf\n\t\techo 'kern.ipc.semmnu=512' >> /boot/loader.conf\n\n\t\techo 'pgbouncer_enable=\"yes\"' >> /etc/rc.conf\n\n\t\tsed -i -e '/^[^#]/d' /etc/sysctl.conf\n\t\techo 'kern.ipc.shm_use_phys=1' >> /etc/sysctl.conf\n\t\techo 'kern.ipc.shmmax=6442450944' >> /etc/sysctl.conf\n\t\techo 'kern.ipc.soacceptqueue=4096' >> /etc/sysctl.conf\n\t\techo 'net.inet.tcp.msl=1000' >> /etc/sysctl.conf\n\n\t\tcp ./pgbouncer.ini /usr/local/etc/pgbouncer.ini\n\tfi\n\techo \"Done installing pgbouncer...\"\n}\n\nsetup_datadisks(){\n\tdatadisks=''\n\tfor i in $(seq 2 $(($numofdisks+1)))\n\t\tdo\n\t\t\ttemp=\" /dev/da$i\"\n\t\t\tdatadisks=${datadisks}${temp}\n\tdone\n\n\tkldload geom_stripe\n\tgstripe label -v st0 $datadisks\n\tbsdlabel -wB /dev/stripe/st0\n\tnewfs -U /dev/stripe/st0a\n\tmkdir /stripe\n\tmount /dev/stripe/st0a /stripe\n\techo \"/dev/stripe/st0a /stripe ufs rw 2 2\"  >> /etc/fstab\n\techo 'geom_stripe_load=\"YES\"' >> /boot/loader.conf\n\tmkdir -p /stripe/postgres/data\n}\n\nenv ASSUME_ALWAYS_YES=YES pkg bootstrap\npkg update\n\nnumofdisks=$1\nsetup_datadisks\n\ninstall_pgbouncer_service\n\nservice pgbouncer restart\n\ninstall_postgresql_service\n\necho \"/sbin/reboot\" | at + 1 minute\n\n", "num_lines": 71}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/sh\n\nfrontendvmip1=$1\nbackendvm1ip=$2\nbackendvm2ip=$3\n\necho 'ifconfig_hn1=\"DHCP\"' >> /etc/rc.conf\nifconfig hn1 up\nenv ASSUME_ALWAYS_YES=YES pkg bootstrap\npkg update\npkg install -y nginx\n\necho 'nginx_enable=\"YES\"' >> /etc/rc.conf\necho \"$frontendvmip1\"\necho \"$backendvm1ip\"\necho \"$backendvm2ip\"\n\nmkdir -p /var/nginx/cache\n\ncp /usr/local/etc/nginx/nginx.conf /usr/local/etc/nginx/nginx.conf.bak\ncp ./frontend_nginx.conf /usr/local/etc/nginx/nginx.conf\ncp ./frontend_proxy.conf /usr/local/etc/nginx/proxy.conf\n\nsed -i -e 's/backendvm1ip/'$backendvm1ip'/g' /usr/local/etc/nginx/nginx.conf\nsed -i -e 's/backendvm2ip/'$backendvm2ip'/g' /usr/local/etc/nginx/nginx.conf\nsed -i -e 's/frontendvmip1/'$frontendvmip1'/g' /usr/local/etc/nginx/nginx.conf\n\nservice nginx restart\n\nsed -i -e '/^[^#]/d' /etc/sysctl.conf\necho 'kern.ipc.soacceptqueue=4096' >> /etc/sysctl.conf\necho 'net.inet.tcp.msl=1000' >> /etc/sysctl.conf\n\necho \"/sbin/reboot\" | at + 1 minute\n", "num_lines": 35}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo apt-get install -y apache2\nif [ \"$1\" = \"True\" ]; then\n\tif [ \"$4\" = \"16.04.0-LTS\" ]; then\n\t\tsudo apt-get install -y libapache2-mod-php\n\telse\n\t\tsudo apt-get install -y php5\n\tfi\n\tif [ \"$3\" = \"index.php\" ]; then\n\t\tsudo rm /var/www/html/index.html\n\tfi\n\tsudo service apache2 restart\nfi\necho $2 | sudo tee /var/www/html/$3\n", "num_lines": 17}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nsudo apt-get update\nsudo apt-get install -y apache2\nif [ \"$1\" = \"True\" ]; then\n\tif [ \"$4\" = \"16.04.0-LTS\" ]; then\n\t\tsudo apt-get install -y libapache2-mod-php\n\telse\n\t\tsudo apt-get install -y php5\n\tfi\n\tif [ \"$3\" = \"index.php\" ]; then\n\t\tsudo rm /var/www/html/index.html\n\tfi\n\tsudo service apache2 restart\nfi\necho $2 | sudo tee /var/www/html/$3\n", "num_lines": 17}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Custom Script for Linu#commands for installing mongo db:\n\n#Step 1 - Importing the Public Key\napt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927\n\n#Step 2 - Create source list file MongoDB:\necho \"deb http://repo.mongodb.org/apt/ubuntu \"xenial\"/mongodb-org/3.2 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.2.list\n\n#Step 3 - Update the repository\napt-get update\n\n#Step 4 - Install MongoDB\napt-get install -y mongodb-org\n\n#Start mongodb and add it as service to be started at boot time:\nsystemctl start mongod\nsystemctl enable mongod\n\n#Install Nodejs\ncurl -sL https://deb.nodesource.com/setup_6.x | sudo -E bash -\napt-get install -y nodejs\n\n#Clone todo app\nmkdir /app\ngit clone $1 /app\n\n#Install Nodejs app\ncd /app\nnpm install\n#App to be started manually by user post declaing MONGODB_URL var\n#export MONGODB_URL=\"mongodb://localhost/tododb\"\n#nom start\nexit 0\n", "num_lines": 34}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# print commands and arguments as they are executed\nset -x\n\necho \"starting ubuntu devbox install on pid $$\"\ndate\nps axjf\n\n#############\n# Parameters\n#############\n\nAZUREUSER=$1\nHOMEDIR=\"/home/$AZUREUSER\"\nVMNAME=`hostname`\necho \"User: $AZUREUSER\"\necho \"User home dir: $HOMEDIR\"\necho \"vmname: $VMNAME\"\n\n###################\n# Common Functions\n###################\n\nensureAzureNetwork()\n{\n  # ensure the host name is resolvable\n  hostResolveHealthy=1\n  for i in {1..120}; do\n    host $VMNAME\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      hostResolveHealthy=0\n      echo \"the host name resolves\"\n      break\n    fi\n    sleep 1\n  done\n  if [ $hostResolveHealthy -ne 0 ]\n  then\n    echo \"host name does not resolve, aborting install\"\n    exit 1\n  fi\n\n  # ensure the network works\n  networkHealthy=1\n  for i in {1..12}; do\n    wget -O/dev/null http://bing.com\n    if [ $? -eq 0 ]\n    then\n      # hostname has been found continue\n      networkHealthy=0\n      echo \"the network is healthy\"\n      break\n    fi\n    sleep 10\n  done\n  if [ $networkHealthy -ne 0 ]\n  then\n    echo \"the network is not healthy, aborting install\"\n    ifconfig\n    ip a\n    exit 2\n  fi\n}\nensureAzureNetwork\n\n###################################################\n# Update Ubuntu and install all necessary binaries\n###################################################\n\ntime sudo apt-get -y update\n# kill the waagent and uninstall, otherwise, adding the desktop will do this and kill this script\nsudo pkill waagent\ntime sudo apt-get -y remove walinuxagent\ntime sudo DEBIAN_FRONTEND=noninteractive apt-get -y --force-yes install ubuntu-desktop firefox vnc4server ntp nodejs npm expect gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal gnome-core\n\n#########################################\n# Setup Azure User Account including VNC\n#########################################\nsudo -i -u $AZUREUSER mkdir $HOMEDIR/bin\nsudo -i -u $AZUREUSER touch $HOMEDIR/bin/startvnc\nsudo -i -u $AZUREUSER chmod 755 $HOMEDIR/bin/startvnc\nsudo -i -u $AZUREUSER touch $HOMEDIR/bin/stopvnc\nsudo -i -u $AZUREUSER chmod 755 $HOMEDIR/bin/stopvnc\necho \"vncserver -geometry 1280x1024 -depth 16\" | sudo tee $HOMEDIR/bin/startvnc\necho \"vncserver -kill :1\" | sudo tee $HOMEDIR/bin/stopvnc\necho \"export PATH=\\$PATH:~/bin\" | sudo tee -a $HOMEDIR/.bashrc\n\nprog=/usr/bin/vncpasswd\nmypass=\"password\"\n\nsudo -i -u $AZUREUSER /usr/bin/expect <<EOF\nspawn \"$prog\"\nexpect \"Password:\"\nsend \"$mypass\\r\"\nexpect \"Verify:\"\nsend \"$mypass\\r\"\nexpect eof\nexit\nEOF\n\nsudo -i -u $AZUREUSER startvnc\nsudo -i -u $AZUREUSER stopvnc\n\necho \"#!/bin/sh\" | sudo tee $HOMEDIR/.vnc/xstartup\necho \"\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"export XKL_XMODMAP_DISABLE=1\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"unset SESSION_MANAGER\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"unset DBUS_SESSION_BUS_ADDRESS\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"xsetroot -solid grey\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"vncconfig -iconic &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"gnome-panel &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"gnome-settings-daemon &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"metacity &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"nautilus &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\necho \"gnome-terminal &\" | sudo tee -a $HOMEDIR/.vnc/xstartup\n\nsudo -i -u $AZUREUSER $HOMEDIR/bin/startvnc\n\n#####################\n# setup the Azure CLI\n#####################\ntime sudo npm install azure-cli -g\ntime sudo update-alternatives --install /usr/bin/node nodejs /usr/bin/nodejs 100\n\n####################\n# Setup Chrome\n####################\ncd /tmp\ntime wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb\ntime sudo dpkg -i google-chrome-stable_current_amd64.deb\ntime sudo apt-get -y --force-yes install -f\ntime rm /tmp/google-chrome-stable_current_amd64.deb\ndate\necho \"completed ubuntu devbox install on pid $$\"\n", "num_lines": 142}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\ntouch /etc/apt/sources.list\nsudo apt-get -y upgrade\nsudo apt-get -y update\n\n\n#install gnome desktop\nsudo apt-get install ubuntu-gnome-desktop -y\n\n#install xrdp\nsudo apt-get install xrdp -y\n\n# change access from root only to all users\nsudo sed -i 's/allowed_users=console/allowed_users=anybody/' /etc/X11/Xwrapper.config\n\n#start remote desktop session\nsudo service xrdp restart\n\n#install Azure CLI\napt-get update && sudo apt-get install -y azure-cli\nlogger -t devvm \"Azure-cli installed: $?\"\nsudo apt-get -y update\n\n#install VSCode\nlogger -t devvm \"Installing VSCode: $?\"\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\nsudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg\nsudo sh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main\" > /etc/apt/sources.list.d/vscode.list'\nsudo apt-get update\nsudo apt-get install -y code\nlogger -t devvm \"VSCode Installed: $?\"\nlogger -t devvm \"Success\"\nexit 0\n", "num_lines": 34}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nsudo apt-get update\n#install gnome desktop\n#sudo apt-get install ubuntu-desktop -y\n#install xrdp\nsudo apt-get install xrdp -y\n\n#using xfce if you are using Ubuntu version later than Ubuntu 12.04LTS\nsudo apt-get install xfce4 -y\n#sudo apt-get install xubuntu-desktop -y\nsudo echo xfce4-session >/root/.xsession\nsudo sed -i '/\\/etc\\/X11\\/Xsession/i xfce4-session' /etc/xrdp/startwm.sh\nsudo service xrdp restart\n", "num_lines": 14}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n#\n# seafile-server-installer/seafile-server-ubuntu-16-04-amd64\n#\n# Copyright 2015, Alexander Jackson <alexander.jackson@seafile.de>\n# Copyright 2016, Zheng Xie <xie.zheng@seafile.com>\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n#\n#\nusage() {\n   echo \"Usage: $0 [-u <admin_email>] [-d <full_domain>] [-p <admin_pass>] [-s <seafile_version>]\"\n   echo \"       admin_email is used to login seafile server, i.e. admin@seafile.local\"\n   echo \"       full_domain is the full qualified domain name, i.e. mybox.southeastasia.cloudapp.azure.com\"\n   echo \"       admin_pass is optional, if you do not specify it, a random string is generated\"\n   echo \"       seafile_version is optional, default 6.1.1 is used\"\n   exit 1\n}\n\nif [[ $HOME == \"\" ]]; then\n    export HOME=/root\nfi\n\nif [[ $SEAFILE_DEBUG != \"\" ]]; then\n    set -x\nfi\nset -e\n\nSEAFILE_VERSION=\"6.1.1\"\nSEAFILE_PRO=0\nZPOOL_NAME=\"MyDiskPool\"\nZFS_DATASET=\"MyData\"\n\nwhile getopts \":u:p:d:s:\" o; do\n    case \"${o}\" in\n     u)\n       SEAFILE_ADMIN=${OPTARG}\n       ;;\n     p)\n       SEAFILE_ADMIN_PW=${OPTARG}\n       ;;\n     d)\n       IP_OR_DOMAIN=${OPTARG}\n       ;;\n     s)\n       SEAFILE_VERSION=${OPTARG}\n       ;;\n     *)\n       usage\n       ;;\n    esac\ndone\nshift $((OPTIND-1))\nif [ -z \"${SEAFILE_ADMIN}\" ] || [ -z \"${IP_OR_DOMAIN}\" ]; then\n   usage\nfi\n\nclear\ncat <<EOF\n  This script installs the community edition of the Seafile Server on a Ubuntu 16.04 (Xenial) 64bit\n  - Newest Seafile server version, MariaDB, Memcached, NGINX -\n  -----------------------------------------------------------------\n  This installer is meant to run on a freshly installed machine\n  only. If you run it on a production server things can and\n  probably will go terrible wrong and you will loose valuable\n  data!\n  For questions or suggestions please contact us at\n  support@seafile.com\n  -----------------------------------------------------------------\n  Possible options:\n  1 = Seafile Community (Free) Edition (CE)\n  2 = Seafile Professional Edition (PRO)\nEOF\n\nif [[ ${SEAFILE_PRO} == \"\" ]]; then\n    PS3=\"Which Seafile version would you like to install? \"\n    select SEAFILE_SERVER_VERSION in CE PRO ABORT; do\n        case \"${SEAFILE_SERVER_VERSION}\" in\n            ABORT)\n                echo \"Aborting\"\n                break\n                ;;\n            \"\")\n                echo \"$REPLY: Wrong value. Select 1 or 2.\"\n                ;;\n            *)\n                if [[ ${SEAFILE_SERVER_VERSION} = \"PRO\" ]]; then\n                    SEAFILE_PRO=1\n                else\n                    SEAFILE_PRO=0\n                fi\n                break\n        esac\n    done\nfi\n\nis_pro() {\n    if [[ \"$SEAFILE_PRO\" == \"1\" ]]; then\n        return 0\n    else\n        return 1\n    fi\n}\n\necho\nif is_pro; then\n    echo \"This script will install Seafile Professional Edition for you.\"\nelse\n    echo \"This script will install Seafile Community Edition for you.\"\nfi\necho\n\n# -------------------------------------------\n# Vars\n# -------------------------------------------\n\nTIME_ZONE=Asia/Shanghai\n\nif is_pro; then\n    SEAFILE_SERVER_PACKAGE=seafile-pro-server_${SEAFILE_VERSION}_x86-64.tar.gz\n    if [[ ! -e /opt/$SEAFILE_SERVER_PACKAGE ]]; then\n        echo\n        echo \"You must download \\\"$SEAFILE_SERVER_PACKAGE\\\" to the /opt/ folder before running this script!\"\n        echo\n        exit 1\n    fi\n    INSTALLPATH=/opt/seafile/seafile-pro-server-${SEAFILE_VERSION}/\nelse\n    SEAFILE_SERVER_PACKAGE=seafile-server_${SEAFILE_VERSION}_x86-64.tar.gz\n    SEAFILE_SERVER_PACKAGE_URL=https://download.seadrive.org/${SEAFILE_SERVER_PACKAGE}\n    INSTALLPATH=/opt/seafile/seafile-server-${SEAFILE_VERSION}/\nfi\n\n\n# -------------------------------------------\n# Ensure we are running the installer as root\n# -------------------------------------------\nif [[ $EUID -ne 0 ]]; then\n  echo \"  Aborting because you are not root\" ; exit 1\nfi\n\n\n# -------------------------------------------\n# Abort if directory /opt/seafile/ exists\n# -------------------------------------------\nif [[ -d \"/opt/seafile/\" ]] ;\nthen\n  echo \"  Aborting because directory /opt/seafile/ already exist\" ; exit 1\nfi\n\nexport DEBIAN_FRONTEND=noninteractive\nexport LANGUAGE=en_US.UTF-8\nexport LANG=en_US.UTF-8\nexport LC_ALL=en_US.UTF-8\nlocale-gen en_US.UTF-8\ndpkg-reconfigure locales\n\n# -------------------------------------------\n# Additional requirements\n# -------------------------------------------\napt-get update\napt-get install -y python2.7 sudo python-pil python-pip python-setuptools python-imaging python-mysqldb python-ldap python-urllib3 \\\nopenjdk-8-jre memcached python-memcache pwgen curl openssl poppler-utils libpython2.7 libreoffice \\\nlibreoffice-script-provider-python ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy nginx python-requests zfsutils-linux\n\n# -------------------------------------------\n# Create seafile-data with the help of ZFS\n# -------------------------------------------\n\nzpool create -f ${ZPOOL_NAME} /dev/sdc\nzpool set cachefile=/etc/zfs/zpool.cache ${ZPOOL_NAME}\nzfs create ${ZPOOL_NAME}/${ZFS_DATASET}\nzfs set compression=gzip ${ZPOOL_NAME}/${ZFS_DATASET}\n\nrm /etc/nginx/sites-enabled/*\n\ncat > /etc/nginx/sites-available/seafile.conf <<'EOF'\nserver {\n      listen 80;\n      server_name  \"${SEAFILE_ADMIN}\";\n      proxy_set_header X-Forwarded-For $remote_addr;\n      location / {\n          fastcgi_pass    127.0.0.1:8000;\n          fastcgi_param   SCRIPT_FILENAME     $document_root$fastcgi_script_name;\n          fastcgi_param   PATH_INFO           $fastcgi_script_name;\n          fastcgi_param   SERVER_PROTOCOL     $server_protocol;\n          fastcgi_param   QUERY_STRING        $query_string;\n          fastcgi_param   REQUEST_METHOD      $request_method;\n          fastcgi_param   CONTENT_TYPE        $content_type;\n          fastcgi_param   CONTENT_LENGTH      $content_length;\n          fastcgi_param   SERVER_ADDR         $server_addr;\n          fastcgi_param   SERVER_PORT         $server_port;\n          fastcgi_param   SERVER_NAME         $server_name;\n          fastcgi_param   REMOTE_ADDR         $remote_addr;\n          access_log      /var/log/nginx/seahub.access.log;\n          error_log       /var/log/nginx/seahub.error.log;\n      }\n      location /seafhttp {\n          rewrite ^/seafhttp(.*)$ $1 break;\n          proxy_pass http://127.0.0.1:8082;\n          client_max_body_size 0;\n          proxy_connect_timeout  36000s;\n          proxy_read_timeout  36000s;\n      }\n      location /media {\n          root /opt/seafile/seafile-server-latest/seahub;\n      }\n     location /seafdav {\n        fastcgi_pass    127.0.0.1:8080;\n        fastcgi_param   SCRIPT_FILENAME     $document_root$fastcgi_script_name;\n        fastcgi_param   PATH_INFO           $fastcgi_script_name;\n        fastcgi_param   SERVER_PROTOCOL     $server_protocol;\n        fastcgi_param   QUERY_STRING        $query_string;\n        fastcgi_param   REQUEST_METHOD      $request_method;\n        fastcgi_param   CONTENT_TYPE        $content_type;\n        fastcgi_param   CONTENT_LENGTH      $content_length;\n        fastcgi_param   SERVER_ADDR         $server_addr;\n        fastcgi_param   SERVER_PORT         $server_port;\n        fastcgi_param   SERVER_NAME         $server_name;\n        fastcgi_param   REMOTE_ADDR         $remote_addr;\n        client_max_body_size 0;\n        access_log      /var/log/nginx/seafdav.access.log;\n        error_log       /var/log/nginx/seafdav.error.log;\n    }\n}\nEOF\n\nln -sf /etc/nginx/sites-available/seafile.conf /etc/nginx/sites-enabled/seafile.conf\n\nservice nginx restart\n\n\n# -------------------------------------------\n# MariaDB\n# -------------------------------------------\nif [[ -f \"/root/.my.cnf\" ]] ;\nthen\n  echo \"MariaDB installed before, skip this part\"\n  SQLROOTPW=`sed -n 's/password=//p' /root/.my.cnf`\nelse\n  DEBIAN_FRONTEND=noninteractive apt-get install -y mariadb-server\n\n  SQLROOTPW=$(pwgen)\n\n  mysqladmin -u root password $SQLROOTPW\n\n  cat > /root/.my.cnf <<EOF\n[client]\nuser=root\npassword=$SQLROOTPW\nEOF\n\n  chmod 600 /root/.my.cnf\nfi\n\n# -------------------------------------------\n# Seafile init script\n# -------------------------------------------\ncat > /etc/init.d/seafile-server <<'EOF'\n#!/bin/bash\n### BEGIN INIT INFO\n# Provides:          seafile-server\n# Required-Start:    $remote_fs $syslog mysql\n# Required-Stop:     $remote_fs $syslog\n# Default-Start:     2 3 4 5\n# Default-Stop:      0 1 6\n# Short-Description: Seafile server\n# Description:       Start Seafile server\n### END INIT INFO\n# Author: Alexander Jackson <alexander.jackson@seafile.com.de>\n# Change the value of \"seafile_dir\" to your path of seafile installation\nseafile_dir=/opt/seafile\nscript_path=${seafile_dir}/seafile-server-latest\nseafile_init_log=${seafile_dir}/logs/seafile.init.log\nseahub_init_log=${seafile_dir}/logs/seahub.init.log\n# Change the value of fastcgi to true if fastcgi is to be used\nfastcgi=true\n# Set the port of fastcgi, default is 8000. Change it if you need different.\nfastcgi_port=8000\ncase \"$1\" in\n        start)\n                ${script_path}/seafile.sh start >> ${seafile_init_log}\n                if [  $fastcgi = true ];\n                then\n                        ${script_path}/seahub.sh start-fastcgi ${fastcgi_port} >> ${seahub_init_log}\n                else\n                        ${script_path}/seahub.sh start >> ${seahub_init_log}\n                fi\n        ;;\n        restart)\n                ${script_path}/seafile.sh restart >> ${seafile_init_log}\n                if [  $fastcgi = true ];\n                then\n                        ${script_path}/seahub.sh restart-fastcgi ${fastcgi_port} >> ${seahub_init_log}\n                else\n                        ${script_path}/seahub.sh restart >> ${seahub_init_log}\n                fi\n        ;;\n        stop)\n                ${script_path}/seafile.sh $1 >> ${seafile_init_log}\n                ${script_path}/seahub.sh $1 >> ${seahub_init_log}\n        ;;\n        *)\n                echo \"Usage: /etc/init.d/seafile-server {start|stop|restart}\"\n                exit 1\n        ;;\nesac\nEOF\n\nchmod +x /etc/init.d/seafile-server\nupdate-rc.d seafile-server defaults\n\n\n# -------------------------------------------\n# Seafile\n# -------------------------------------------\nmkdir -p /opt/seafile/installed\ncd /opt/seafile/\nif ! is_pro && [[ ! -e /opt/${SEAFILE_SERVER_PACKAGE} ]]; then\n    curl -OL ${SEAFILE_SERVER_PACKAGE_URL}\nelse\n    cp /opt/${SEAFILE_SERVER_PACKAGE} .\nfi\ntar xzf ${SEAFILE_SERVER_PACKAGE}\n\nmv ${SEAFILE_SERVER_PACKAGE} installed\n\n\n# -------------------------------------------\n# Seafile DB\n# -------------------------------------------\nif [[ -f \"/opt/seafile.my.cnf\" ]] ;\nthen\n  echo \"MariaDB installed before, skip this part\"\n  SQLSEAFILEPW=`sed -n 's/password=//p' /opt/seafile.my.cnf`\nelse\n  SQLSEAFILEPW=$(pwgen)\n\n  cat > /opt/seafile.my.cnf <<EOF\n[client]\nuser=seafile\npassword=$SQLSEAFILEPW\nEOF\n\n  chmod 600 /opt/seafile.my.cnf\nfi\n\n# -------------------------------------------\n# Go to /opt/seafile/seafile-pro-server-${SEAFILE_VERSION}\n# -------------------------------------------\ncd $INSTALLPATH\n\n# -------------------------------------------\n# Vars - Don't touch these unless you really know what you are doing!\n# -------------------------------------------\nTOPDIR=$(dirname \"${INSTALLPATH}\")\nDEFAULT_CONF_DIR=${TOPDIR}/conf\n\nif [[ ! -e /${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data ]]; then\n   SEAFILE_DATA_DIR=/${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data\nelse\n   SEAFILE_DATA_DIR=/${ZPOOL_NAME}/${ZFS_DATASET}/seafile-data`date +%Y%m%d%H%M%S`\nfi\nDEST_SETTINGS_PY=${TOPDIR}/conf/seahub_settings.py\n\nmkdir -p ${DEFAULT_CONF_DIR}\n\n# -------------------------------------------\n# Create ccnet, seafile, seahub conf using setup script\n# -------------------------------------------\n\n./setup-seafile-mysql.sh auto -u seafile -w ${SQLSEAFILEPW} -r ${SQLROOTPW} -d $SEAFILE_DATA_DIR\n\n# -------------------------------------------\n# Configure Seafile WebDAV Server(SeafDAV)\n# -------------------------------------------\nsed -i 's/enabled = .*/enabled = true/' ${DEFAULT_CONF_DIR}/seafdav.conf\nsed -i 's/fastcgi = .*/fastcgi = true/' ${DEFAULT_CONF_DIR}/seafdav.conf\nsed -i 's/share_name = .*/share_name = \\/seafdav/' ${DEFAULT_CONF_DIR}/seafdav.conf\n\n# -------------------------------------------\n# Configuring seahub_settings.py\n# -------------------------------------------\ncat >> ${DEST_SETTINGS_PY} <<EOF\nCACHES = {\n    'default': {\n        'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n    'LOCATION': '127.0.0.1:11211',\n    }\n}\n# EMAIL_USE_TLS                       = False\n# EMAIL_HOST                          = 'localhost'\n# EMAIL_HOST_USER                     = ''\n# EMAIL_HOST_PASSWORD                 = ''\n# EMAIL_PORT                          = '25'\n# DEFAULT_FROM_EMAIL                  = EMAIL_HOST_USER\n# SERVER_EMAIL                        = EMAIL_HOST_USER\nTIME_ZONE                           = '${TIME_ZONE}'\nSITE_BASE                           = 'http://${IP_OR_DOMAIN}'\nSITE_NAME                           = 'Seafile Server'\nSITE_TITLE                          = 'Seafile Server'\nSITE_ROOT                           = '/'\nENABLE_SIGNUP                       = False\nACTIVATE_AFTER_REGISTRATION         = False\nSEND_EMAIL_ON_ADDING_SYSTEM_MEMBER  = True\nSEND_EMAIL_ON_RESETTING_USER_PASSWD = True\nCLOUD_MODE                          = False\nFILE_PREVIEW_MAX_SIZE               = 30 * 1024 * 1024\nSESSION_COOKIE_AGE                  = 60 * 60 * 24 * 7 * 2\nSESSION_SAVE_EVERY_REQUEST          = False\nSESSION_EXPIRE_AT_BROWSER_CLOSE     = False\nFILE_SERVER_ROOT                    = 'http://${IP_OR_DOMAIN}/seafhttp'\nEOF\n\n\n# -------------------------------------------\n# Backup check_init_admin.py befor applying changes\n# -------------------------------------------\ncp ${INSTALLPATH}/check_init_admin.py ${INSTALLPATH}/check_init_admin.py.backup\n\n\n# -------------------------------------------\n# Set admin credentials in check_init_admin.py\n# -------------------------------------------\nSEAFILE_ADMIN_PW=${SEAFILE_ADMIN_PW:-$(pwgen)}\neval \"sed -i 's/= ask_admin_email()/= \\\"${SEAFILE_ADMIN}\\\"/' ${INSTALLPATH}/check_init_admin.py\"\neval \"sed -i 's/= ask_admin_password()/= \\\"${SEAFILE_ADMIN_PW}\\\"/' ${INSTALLPATH}/check_init_admin.py\"\n\n# -------------------------------------------\n# Start and stop Seafile eco system. This generates the initial admin user.\n# -------------------------------------------\n${INSTALLPATH}/seafile.sh start\n${INSTALLPATH}/seahub.sh start\nsleep 2                         # sleep for a while, otherwise seahub will not be stopped\n${INSTALLPATH}/seahub.sh stop\nsleep 1\n${INSTALLPATH}/seafile.sh stop\n\n\n# -------------------------------------------\n# Restore original check_init_admin.py\n# -------------------------------------------\nmv ${INSTALLPATH}/check_init_admin.py.backup ${INSTALLPATH}/check_init_admin.py\n\nif is_pro; then\n    PRO_PY=${INSTALLPATH}/pro/pro.py\n    $PYTHON ${PRO_PY} setup --mysql --mysql_host=127.0.0.1 --mysql_port=3306 --mysql_user=seafile --mysql_password=${SQLSEAFILEPW} --mysql_db=seahub_db\n    sed -i 's/enabled = false/enabled = true/' ${TOPDIR}/conf/seafevents.conf\nfi\n\n# -------------------------------------------\n# Start seafile server\n# -------------------------------------------\necho \"Starting productive Seafile server\"\nservice seafile-server start\n\n\n# -------------------------------------------\n# Final report\n# -------------------------------------------\ncat > ${TOPDIR}/aio_seafile-server.log<<EOF\n  Your Seafile server is installed\n  -----------------------------------------------------------------\n  Server Address:      http://${IP_OR_DOMAIN}\n  Seafile Admin:       ${SEAFILE_ADMIN}\n  Admin Password:      ${SEAFILE_ADMIN_PW}\n  Seafile Data Dir:    ${SEAFILE_DATA_DIR}\n  Seafile DB Credentials:  Check /opt/seafile.my.cnf\n  Root DB Credentials:     Check /root/.my.cnf\n  This report is also saved to ${TOPDIR}/aio_seafile-server.log\n  Next you should manually complete the following steps\n  -----------------------------------------------------------------\n  1) Run seafile-server-change-address to add your Seafile servers DNS name\n  2) If this server is behind a firewall, you need to ensure that\n     tcp port 80 is open.\n  3) Seahub tries to send emails via the local server. Install and\n     configure Postfix for this to work.\n  Optional steps\n  -----------------------------------------------------------------\n  1) Check seahub_settings.py and customize it to fit your needs. Consult\n     http://manual.seafile.com/config/seahub_settings_py.html for possible switches.\n  2) Setup NGINX with official SSL certificate.\n  3) Secure server with iptables based firewall. For instance: UFW or shorewall\n  4) Harden system with port knocking, fail2ban, etc.\n  5) Enable unattended installation of security updates. Check\n     https://wiki.Ubuntu.org/UnattendedUpgrades for details.\n  6) Implement a backup routine for your Seafile server.\n  7) Update NGINX worker processes to reflect the number of CPU cores.\n  Seafile support options\n  -----------------------------------------------------------------\n  For free community support visit:   https://bbs.seafile.com\n  For paid commercial support visit:  https://seafile.com\nEOF\n\nchmod 600 ${TOPDIR}/aio_seafile-server.log\n\nclear\n\ncat ${TOPDIR}/aio_seafile-server.log", "num_lines": 510}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#install sysbench\napt-get update > /dev/null\napt-get -y install sysbench > /dev/null\n\n#run test\nsysbench --test=cpu --num-threads=$1 --cpu-max-prime=$2 run | grep -E 'total time:|min:|max:|avg:|percentile:' | tr '\\n' ':' | tr -d \" \" | awk -F\"=|:\" '{print $2, $4, $6, $8, $10}'\n", "num_lines": 9}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#init and mount data disk\nif [ ! -d \"/datadisk\" ]; then\n\t(echo n; echo p; echo 1; echo; echo; echo w) | fdisk /dev/sdc > /dev/null\n\tmkfs -t ext4 /dev/sdc1 > /dev/null\n\tmkdir /datadisk\n\tmount /dev/sdc1 /datadisk\n\n\techo \"UUID=$(blkid | grep -oP '/dev/sdc1: UUID=\"*\"\\K[^\"]*')   /datadisk   ext4   defaults   1   2\" >> /etc/fstab\n\tchmod go+w /datadisk\nfi\n\n\nconfdir=/opt/vmdiskperf/\nif [ ! -d \"$confdir\" ]; then\n\tfirstrun=true\n\tmkdir \"$confdir\"\n\n\t#install fio\n\tapt-get update > /dev/null\n\tapt-get -y install fio > /dev/null\nfi\n\n#create test config\ncd \"$confdir\"\ncat << EOF > t\n[global]\nsize=$1\ndirect=1\niodepth=256\nioengine=libaio\nbs=$5\nEOF\n\nfor i in `seq 1 $4`; do\n\t\techo \"[w$i]\" >> t\n\t\techo rw=$2 >> t\n\t\techo directory=/datadisk >> t\ndone\n\n#run test\nif [ $firstrun = true ]; then\n\tfio --runtime $3 t | grep -E 'READ:|WRITE:' | tr '\\n' ';' | tr -s [:space:] | sed 's/ :/:/g' | sed 's/= /=/g'\nelse\n\tfio --runtime $3 t\nfi\n", "num_lines": 48}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nwebNodeCount=$1\nzabbixServer=$2\n\n\n\ninstall_haproxy() {\n\tcd /tmp\n\tyum install wget -y\n\t\tfor((i=1;i<=5;i++))\n\t\tdo\n\t\t\twget http://www.haproxy.org/download/1.6/src/haproxy-1.6.3.tar.gz\n\t\t\tif [[ $? -eq 0 ]];then\n\t\t\t\tbreak\n\t\t\telse\n\t\t\t\tcontinue\n\t\t\tfi\n\t\tdone\n\ttar zxvf haproxy-1.6.3.tar.gz\n\tcd haproxy-1.6.3\n\tyum install gcc -y\n\tmake TARGET=linux2628 PREFIX=/usr/local/haproxy\n\tmake install PREFIX=/usr/local/haproxy\n\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tmkdir /data\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /data/ -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /data/disk1\n\t\t\t\tmount /dev/md0 /data\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\n\nconfig_haproxy() {\nhaproxyConfigFile=\"/usr/local/haproxy/haproxy.cfg\"\ncat > ${haproxyConfigFile} <<EOF\nglobal\n       maxconn 4096\n       chroot /usr/local/haproxy\n        uid 99\n        gid 99\n       daemon\n       pidfile /usr/local/haproxy/haproxy.pid\n\ndefaults\n       log    global\n        log     127.0.0.1       local3\n       mode    http\n       option  httplog\n        option  dontlognull\n        option  httpclose\n       retries 3\n       option  redispatch\n       maxconn 2000\n       timeout connect     5000\n       timeout client     50000\n       timeout server     50000\n\nfrontend http-in\n       bind *:80\n        mode    http\n        option  httplog\n        log     global\n        default_backend httppool\n\nbackend httppool\n       balance source\nEOF\n\n\n\tfor ((k=1;k<=$webNodeCount;k++))\n\tdo\n\t\tlet ip=3+$k\n\t\tsed -i \"\\$a server  web${k} 10.0.0.${ip}:80  weight 5 check inter 2000 rise 2 fall 3\" ${haproxyConfigFile}\n\t\tsed -i '$s/^/       /' ${haproxyConfigFile}\n\tdone\n\n\t#start haproxy\n\t/usr/local/haproxy/sbin/haproxy -f /usr/local/haproxy/haproxy.cfg\n}\n\n\n\n\ninstall_haproxy\ndisk_format\nconfig_haproxy\ninstall_zabbix\n", "num_lines": 151}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\n\nmysqlPassword=$1\nzabbixServer=$2\n\n\n\ninstall_mysql() {\n\n\t#get repo\n\tyum install wget -y\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\twget http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to download repo but failed. exit. try again later.\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"download repo successfully\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\tyum localinstall -y mysql-community-release-el6-5.noarch.rpm\n\n\t#install mysql 5.6\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\tyum install -y mysql-community-server\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to install mysql server but failed. exit. try again later.\"\n\t\t\t\texit 10\n\t\t\tfi\n\t\t\tyum clean all\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"installed mysql server successfully.\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t#configure my.cnf\n\tsed -i '/\\[mysqld\\]/a server-id = 1\\nlog_bin = /var/lib/mysql/mysql-bin.log' /etc/my.cnf\n\n\t#auto-start\n\tchkconfig mysqld on\n\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mysql -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mysql/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mysql\n\t\t\t\tchown -R mysql:mysql /var/lib/mysql\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\nstart_mysql() {\n\t#start mysql\n\tservice mysqld start\n\n\t#set mysql root password\n\tmysqladmin -uroot password \"$mysqlPassword\" 2> /dev/null\n\n\t#grant privileges\n\tmysql -uroot -p$mysqlPassword -e \"grant replication slave on *.* to 'repluser'@'%' identified by 'replpass';grant all privileges on *.* to 'root'@'%' identified by '$mysqlPassword';flush privileges;\"\n}\n\ninstall_mysql\ndisk_format\nstart_mysql\ninstall_zabbix\n", "num_lines": 136}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\n\nmysqlPassword=$1\nzabbixServer=$2\nmasterIP=10.0.0.20\n\n\n\ninstall_mysql() {\n\n\t#get repo\n\tyum install wget -y\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\twget http://repo.mysql.com/mysql-community-release-el6-5.noarch.rpm\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to download repo but failed. exit. try again later.\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"download repo successfully\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\tyum localinstall -y mysql-community-release-el6-5.noarch.rpm\n\n\t#install mysql 5.6\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\tyum install -y mysql-community-server\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to install mysql server but failed. exit. try again later.\"\n\t\t\t\texit 10\n\t\t\tfi\n\t\t\tyum clean all\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"installed mysql server successfully.\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t#configure my.cnf\n\tsed -i '/\\[mysqld\\]/a server-id = 2\\nlog_bin = /var/lib/mysql/mysql-bin.log\\nreplicate-ignore-db = mysql' /etc/my.cnf\n\n\t#auto-start\n\tchkconfig mysqld on\n\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/lib/mysql -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/lib/mysql/disk1\n\t\t\t\tmount /dev/md0 /var/lib/mysql\n\t\t\t\tchown -R mysql:mysql /var/lib/mysql\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\nstart_mysql() {\n\t#start mysql\n\tservice mysqld start\n\n\t#set mysql root password\n\tmysqladmin -uroot password \"$mysqlPassword\" 2> /dev/null\n\n\t#grant privileges\n\tmysql -uroot -p$mysqlPassword -e \"grant all privileges on *.* to 'root'@'%' identified by '$mysqlPassword';flush privileges;\"\n\n\t#configure slave\n\tmysql -uroot -p$mysqlPassword -e \"change master to master_host='$masterIP',master_user='repluser',master_password='replpass';start slave;\"\n\tslaveStatus=`mysql -uroot -p$mysqlPassword -e \"show slave status\\G\" |grep -i \"Running: Yes\"|wc -l`\n\tif [[ $slaveStatus -ne 2 ]];then\n\t\techo \"master-slave replication issue!\"\n\telse\n\t\techo \"master-slave configuration succeeds! \"\n\tfi\n\n}\n\ninstall_mysql\ndisk_format\ninstall_zabbix\nstart_mysql\n", "num_lines": 147}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nzabbixServer=$1\n\n\ninstall_redis() {\n\n\t#download redis\n\tcd /usr/local/\n\tyum install -y wget\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\twget http://download.redis.io/releases/redis-3.0.7.tar.gz\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to download redis but failed. exit. try again later.\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"download redis successfully\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t#install redis\n\ttar xzvf redis-3.0.7.tar.gz\n\tmv redis-3.0.7 redis\n\tcd redis\n\tyum install gcc -y\n\tmake\n\n\t#ocnfigure redis\n\tcp redis.conf /etc/\n\tsed -i 's/daemonize no/daemonize yes/' /etc/redis.conf\n\tcd src\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /data/ -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /data/\n\t\t\t\tmount /dev/md0 /data/\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\n\ninstall_redis\ndisk_format\n#start redis\n/usr/local/redis/src/redis-server /etc/redis.conf\ninstall_zabbix\n\n\n\n", "num_lines": 114}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\nzabbixServer=$1\nmasterIP=10.0.0.36\n\n\n\n\ninstall_redis() {\n\n\t#download redis\n\tcd /usr/local/\n\tyum install -y wget\n\tfor((i=1;i<=5;i++))\n\tdo\n\t\twget http://download.redis.io/releases/redis-3.0.7.tar.gz\n\t\tif [[ $? -ne 0 ]];then\n\t\t\tif [[ $i == 5 ]];then\n\t\t\t\techo \"tried 5 times to download redis but failed. exit. try again later.\"\n\t\t\t\texit 1\n\t\t\tfi\n\t\t\tcontinue\n\t\telse\n\t\t\techo \"download redis successfully\"\n\t\t\tbreak\n\t\tfi\n\tdone\n\n\t#install redis\n\ttar xzvf redis-3.0.7.tar.gz\n\tmv redis-3.0.7 redis\n\tcd redis\n\tyum install gcc -y\n\tmake\n\n\t#ocnfigure redis\n\tcp redis.conf /etc/\n\tsed -i 's/daemonize no/daemonize yes/' /etc/redis.conf\n\tsed -i \"s/# slaveof <masterip> <masterport>/slaveof $masterIP 6379/\" /etc/redis.conf\n\tcd src\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /data/ -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /data/\n\t\t\t\tmount /dev/md0 /data/\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\n\ninstall_redis\ndisk_format\n#start redis\n/usr/local/redis/src/redis-server /etc/redis.conf\ninstall_zabbix\n\n\n\n", "num_lines": 118}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash\n\n\nmysqlPassword=$1\ninsertValue=$2\nzabbixServer=$3\nmasterIP=10.0.0.20\n\n\ninstall_ap() {\n\n\n\t#install apache 2.4 php5\n\tyum install httpd php php-mysql -y\n\n\n\t#start httpd\n\tservice httpd start\n\n\t#auto-start\n\tchkconfig httpd on\n\tchkconfig firewalld off\n\tchkconfig iptables off\n\tservice firewalld stop\n\tservice iptables stop\n\n\t#set selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/sysconfig/selinux\n\tsed -i 's/^SELINUX=.*/SELINUX=disabled/' /etc/selinux/config\n\tsetenforce 0\n\n}\n\n\ndisk_format() {\n\tcd /tmp\n\tyum install wget -y\n\tfor ((j=1;j<=3;j++))\n\tdo\n\t\twget https://raw.githubusercontent.com/Azure/azure-quickstart-templates/master/shared_scripts/ubuntu/vm-disk-utils-0.1.sh\n\t\tif [[ -f /tmp/vm-disk-utils-0.1.sh ]]; then\n\t\t\tbash /tmp/vm-disk-utils-0.1.sh -b /var/www/html -s\n\t\t\tif [[ $? -eq 0 ]]; then\n\t\t\t\tsed -i 's/disk1//' /etc/fstab\n\t\t\t\tumount /var/www/html/disk1\n\t\t\t\tmount /dev/md0 /var/www/html\n\t\t\tfi\n\t\t\tbreak\n\t\telse\n\t\t\techo \"download vm-disk-utils-0.1.sh failed. try again.\"\n\t\t\tcontinue\n\t\tfi\n\tdone\n\n}\n\n\ninstall_zabbix() {\n\t#install zabbix agent\n\tcd /tmp\n\tyum install -y gcc wget > /dev/null\n\tfor((n=1;n<=5;n++))\n\tdo\n\t\twget http://jaist.dl.sourceforge.net/project/zabbix/ZABBIX%20Latest%20Stable/2.2.5/zabbix-2.2.5.tar.gz\n\t\tif [[ $? -eq 0 ]];then\n\t\t\tbreak\n\t\telse\n\t\t\tcontinue\n\t\tfi\n\tdone\n\ttar zxvf zabbix-2.2.5.tar.gz\n\tcd zabbix-2.2.5\n\tgroupadd zabbix\n\tuseradd zabbix -g zabbix -s /sbin/nologin\n\tmkdir -p /usr/local/zabbix\n\t./configure --prefix=/usr/local/zabbix --enable-agent\n\tmake install > /dev/null\n\tcp misc/init.d/fedora/core/zabbix_agentd /etc/init.d/\n\tsed -i 's/BASEDIR=\\/usr\\/local/BASEDIR=\\/usr\\/local\\/zabbix/g' /etc/init.d/zabbix_agentd\n\tsed -i '$azabbix-agent    10050/tcp\\nzabbix-agent    10050/udp' /etc/services\n\tsed -i '/^LogFile/s/tmp/var\\/log/' /usr/local/zabbix/etc/zabbix_agentd.conf\n\thostName=`hostname`\n\tsed -i \"s/^Hostname=Zabbix server/Hostname=$hostName/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\tif [[ $zabbixServer =~ ([0-9]{1,3}.){3}[0-9]{1,3} ]];then\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^ServerActive=127.0.0.1/ServerActive=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agentd.conf\n\t\tsed -i \"s/^Server=127.0.0.1/Server=$zabbixServer/\" /usr/local/zabbix/etc/zabbix_agent.conf\n\tfi\n\ttouch /var/log/zabbix_agentd.log\n\tchown zabbix:zabbix /var/log/zabbix_agentd.log\n\n\t#start zabbix agent\n\tchkconfig --add zabbix_agentd\n\tchkconfig zabbix_agentd on\n\t/etc/init.d/zabbix_agentd start\n\n}\n\n\ncreate_test_page() {\n#create test php page\ncat > /var/www/html/info.php <<EOF\n<?php\nphpinfo();\n?>\nEOF\n\n#create test php-mysql page\ncat > /var/www/html/mysql.php <<EOF\n<?php\n\\$conn = mysql_connect('$masterIP', 'root', '$mysqlPassword');\nif (!\\$conn) {\n    die('Could not connect:' . mysql_error());\n}\necho 'Connected to MySQL sucessfully!';\n\nif(mysql_query(\"create database testdb\")){\n    echo \"    Created database testdb successfully!\";\n}else{\n    echo \"    Database testdb already exists!\";\n}\n\n\\$db_selected = mysql_select_db('testdb',\\$conn);\n\nif(mysql_query(\"create table test01(name varchar(10))\")){\n    echo \"    Created table test01 successfuly!\";\n}else{\n    echo \"    Table test01 already exists!\";\n}\n\nif(mysql_query(\"insert into test01 values ('$insertValue')\")){\n    echo \"    Inserted value $insertValue into test01 successfully!\";\n}else{\n    echo \"    Inserted value $insertValue into test01 failed!\";\n}\n\n\\$result = mysql_query(\"select * from testdb.test01\");\nwhile(\\$row = mysql_fetch_array(\\$result))\n{\necho \"    Welcome \";\necho \\$row[\"name\"];\necho \"!!!\";\n}\n\nmysql_close(\\$conn)\n?>\nEOF\n\n}\n\n\n\n\ninstall_ap\ndisk_format\ncreate_test_page\ninstall_zabbix\n", "num_lines": 158}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nWEB_JOB_NAME=\"azure-api-mgmt-logs-2-moesif\"\nWEB_JOB_TYPE=\"Continuous\"\nGITHUB_RUN_BAT_URL=\"https://raw.githubusercontent.com/Moesif/ApimEventProcessor/v1/azure-app-service-webjobs/run.bat\"\nWEBDEPLOY_ZIP_FILE=apim-2-moesif-webjob-webdeploy.zip\n\nBASE_DIR=\"/tmp/build-webdeploy-pkg\"\nWEBJOB_DIR=\"app_data/Jobs/${WEB_JOB_TYPE}/${WEB_JOB_NAME}\"\n\nrm -rf ${BASE_DIR}\nmkdir -p ${BASE_DIR}\ncd ${BASE_DIR}\nmkdir -p .deploy/${WEBJOB_DIR}\ncurl -s ${GITHUB_RUN_BAT_URL} -o .deploy/${WEBJOB_DIR}/run.bat\ncd .deploy \nzip -r ../${WEBDEPLOY_ZIP_FILE} . *\ncd ..\necho \"$(pwd)/${WEBDEPLOY_ZIP_FILE} has been created\"", "num_lines": 19}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Script parameters and their defaults\nVERSION=\"3.0.0\"\nCLUSTER_NAME=\"redis-cluster\"\nIS_LAST_NODE=0\nIS_CLUSTER_AWARE=0\nINSTANCE_COUNT=1\nMASTER_NODE_COUNT=0\nSLAVE_NODE_COUNT=0\nNODE_INDEX=0\nIP_PREFIX=\"10.0.0.0\"\nLOGGING_KEY=\"[account-key]\"\nREDIS_PORT=6379\nCURRENT_DIRECTORY=$(pwd)\n\n########################################################\n# This script will install Redis from sources\n########################################################\nhelp()\n{\n\techo \"This script installs Redis Cache on the Ubuntu virtual machine image\"\n\techo \"Available parameters:\"\n\techo \"-n Cluster name\"\n\techo \"-v Redis package version\"\n\techo \"-c Number of instances\"\n\techo \"-s Number of master nodes\"\n\techo \"-s Number of slave nodes\"\n\techo \"-i Sequential node index (starting from 0)\"\n\techo \"-p Private IP address prefix\"\n\techo \"-l (Indicator of the last node)\"\n\techo \"-h Help\"\n}\n\n#############################################################################\nlog()\n{\n\t# If you want to enable this logging, uncomment the line below and specify your logging key\n\t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/${LOGGING_KEY}/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\nlog \"Begin execution of Redis installation script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts :n:v:c:m:s:i:p:lh optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n\n  case $optname in\n    n)  # Cluster name\n\t\tCLUSTER_NAME=${OPTARG}\n\t\t;;\n    v)  # Version to be installed\n\t\tVERSION=${OPTARG}\n\t\tif [[ $VERSION == 3.* ]]; then IS_CLUSTER_AWARE=1; fi\n\t\t;;\n\tc) # Number of instances\n\t\tINSTANCE_COUNT=${OPTARG}\n\t\t;;\n\tm) # Number of master nodes\n\t\tMASTER_NODE_COUNT=${OPTARG}\n\t\t;;\n\ts) # Number of slave nodes\n\t\tSLAVE_NODE_COUNT=${OPTARG}\n\t\t;;\n\ti) # Sequential node index\n\t\tNODE_INDEX=${OPTARG}\n\t\t;;\n\tp) # Private IP address prefix\n\t\tIP_PREFIX=${OPTARG}\n\t\t;;\n    l)  # Indicator of the last node\n\t\tIS_LAST_NODE=1\n\t\t;;\n    h)  # Helpful hints\n\t\thelp\n\t\texit 2\n\t\t;;\n    \\?) #unrecognized option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\n#############################################################################\ntune_system()\n{\n\tlog \"Tuning the system configuration\"\n\n\t# Ensure the source list is up-to-date\n\tapt-get -y update\n\n\t# Add local machine name to the hosts file to facilitate IP address resolution\n\tif grep -q \"${HOSTNAME}\" /etc/hosts\n\tthen\n\t  echo \"${HOSTNAME} was found in /etc/hosts\"\n\telse\n\t  echo \"${HOSTNAME} was not found in and will be added to /etc/hosts\"\n\t  # Append it to the hsots file if not there\n\t  echo \"127.0.0.1 $(hostname)\" >> /etc/hosts\n\t  log \"Hostname ${HOSTNAME} added to /etc/hosts\"\n\tfi\n}\n\n#############################################################################\ntune_memory()\n{\n\tlog \"Tuning the memory configuration\"\n\n\t# Get the supporting utilities\n\tapt-get -y install hugepages\n\n\t# Resolve a \"Background save may fail under low memory condition.\" warning\n\tsysctl vm.overcommit_memory=1\n\n\t# Disable the Transparent Huge Pages (THP) support in the kernel\n\tsudo hugeadm --thp-never\n}\n\n#############################################################################\ntune_network()\n{\n\tlog \"Tuning the network configuration\"\n\n>/etc/sysctl.conf cat << EOF\n\n\t# Disable syncookies (syncookies are not RFC compliant and can use too muche resources)\n\tnet.ipv4.tcp_syncookies = 0\n\n\t# Basic TCP tuning\n\tnet.ipv4.tcp_keepalive_time = 600\n\tnet.ipv4.tcp_synack_retries = 3\n\tnet.ipv4.tcp_syn_retries = 3\n\n\t# RFC1337\n\tnet.ipv4.tcp_rfc1337 = 1\n\n\t# Defines the local port range that is used by TCP and UDP to choose the local port\n\tnet.ipv4.ip_local_port_range = 1024 65535\n\n\t# Log packets with impossible addresses to kernel log\n\tnet.ipv4.conf.all.log_martians = 1\n\n\t# Disable Explicit Congestion Notification in TCP\n\tnet.ipv4.tcp_ecn = 0\n\n\t# Enable window scaling as defined in RFC1323\n\tnet.ipv4.tcp_window_scaling = 1\n\n\t# Enable timestamps (RFC1323)\n\tnet.ipv4.tcp_timestamps = 1\n\n\t# Enable select acknowledgments\n\tnet.ipv4.tcp_sack = 1\n\n\t# Enable FACK congestion avoidance and fast restransmission\n\tnet.ipv4.tcp_fack = 1\n\n\t# Allows TCP to send \"duplicate\" SACKs\n\tnet.ipv4.tcp_dsack = 1\n\n\t# Controls IP packet forwarding\n\tnet.ipv4.ip_forward = 0\n\n\t# No controls source route verification (RFC1812)\n\tnet.ipv4.conf.default.rp_filter = 0\n\n\t# Enable fast recycling TIME-WAIT sockets\n\tnet.ipv4.tcp_tw_recycle = 1\n\tnet.ipv4.tcp_max_syn_backlog = 20000\n\n\t# How may times to retry before killing TCP connection, closed by our side\n\tnet.ipv4.tcp_orphan_retries = 1\n\n\t# How long to keep sockets in the state FIN-WAIT-2 if we were the one closing the socket\n\tnet.ipv4.tcp_fin_timeout = 20\n\n\t# Don't cache ssthresh from previous connection\n\tnet.ipv4.tcp_no_metrics_save = 1\n\tnet.ipv4.tcp_moderate_rcvbuf = 1\n\n\t# Increase Linux autotuning TCP buffer limits\n\tnet.ipv4.tcp_rmem = 4096 87380 16777216\n\tnet.ipv4.tcp_wmem = 4096 65536 16777216\n\n\t# increase TCP max buffer size\n\tnet.core.rmem_max = 16777216\n\tnet.core.wmem_max = 16777216\n\tnet.core.netdev_max_backlog = 2500\n\n\t# Increase number of incoming connections\n\tnet.core.somaxconn = 65000\nEOF\n\n\t# Reload the networking settings\n\t/sbin/sysctl -p /etc/sysctl.conf\n}\n\n#############################################################################\ninstall_redis()\n{\n\tlog \"Installing Redis v${VERSION}\"\n\n\t# Installing build essentials (if missing) and other required tools\n\tapt-get -y install build-essential\n\n\twget http://download.redis.io/releases/redis-$VERSION.tar.gz\n\ttar xzf redis-$VERSION.tar.gz\n\tcd redis-$VERSION\n\tmake\n\tmake install prefix=/usr/local/bin/\n\n\tlog \"Redis package v${VERSION} was downloaded and built successfully\"\n}\n\n#############################################################################\nconfigure_redis()\n{\n\t# Configure the general settings\n\tsed -i \"s/^port.*$/port ${REDIS_PORT}/g\" redis.conf\n\tsed -i \"s/^daemonize no$/daemonize yes/g\" redis.conf\n\tsed -i 's/^logfile \"\"/logfile \\/var\\/log\\/redis.log/g' redis.conf\n\tsed -i \"s/^loglevel verbose$/loglevel notice/g\" redis.conf\n\tsed -i \"s/^dir \\.\\//dir \\/var\\/redis\\//g\" redis.conf\n\tsed -i \"s/\\${REDISPORT}.conf/redis.conf/g\" utils/redis_init_script\n\tsed -i \"s/_\\${REDISPORT}.pid/.pid/g\" utils/redis_init_script\n\n\t# Configure the sentinel bits\n\techo \"daemonize yes\" >> sentinel.conf\n\techo \"logfile /var/log/redis-sentinel.log\" >> sentinel.conf\n\techo \"loglevel notice\" >> sentinel.conf\n\techo \"pidfile /var/run/redis-sentinel.pid\" >> sentinel.conf\n\n\t# Create all essentials directories and copy files to the correct locations\n\tmkdir /etc/redis\n\tmkdir /var/redis\n\n\tcp redis.conf /etc/redis/redis.conf\n\tcp sentinel.conf /etc/redis/sentinel.conf\n\tcp utils/redis_init_script /etc/init.d/redis-server\n\tcp ${CURRENT_DIRECTORY}/redis-sentinel-startup.sh /etc/init.d/redis-sentinel\n\n\t# Copy the cluster configuration utility (if exists)\n\tif [ -f src/redis-trib.rb ]; then\n\t\tcp src/redis-trib.rb /usr/local/bin/\n\tfi\n\n\t# Clean up temporary files\n\tcd ..\n\trm redis-$VERSION -R\n\trm redis-$VERSION.tar.gz\n\n\tlog \"Redis configuration was applied successfully\"\n\n\t# Create service user and configure for permissions\n\tuseradd -r -s /bin/false redis\n\tchown redis:redis /var/run/redis.pid\n\tchmod 755 /etc/init.d/redis-server\n\tchmod 755 /etc/init.d/redis-sentinel\n\n\t# Start the script automatically at boot time\n\tupdate-rc.d redis-server defaults\n\n\tlog \"Redis service was created successfully\"\n}\n\n#############################################################################\nconfigure_redis_cluster()\n{\n\t# Enable the AOF persistence\n\tsed -i \"s/^appendonly no$/appendonly yes/g\" /etc/redis/redis.conf\n\n\t# Tune the RDB persistence\n\tsed -i \"s/^save.*$/# save/g\" /etc/redis/redis.conf\n\techo \"save 3600 1\" >> /etc/redis/redis.conf\n\n\t# Add cluster configuration (expected to be commented out in the default configuration file)\n\techo \"cluster-enabled yes\" >> /etc/redis/redis.conf\n\techo \"cluster-node-timeout 5000\" >> /etc/redis/redis.conf\n\techo \"cluster-config-file ${CLUSTER_NAME}.conf\" >> /etc/redis/redis.conf\n}\n\n#############################################################################\ninitialize_redis_cluster()\n{\n\t# Cluster setup must run on the last node (a nasty workaround until ARM can recognize multiple custom script extensions)\n\tif [ \"$IS_LAST_NODE\" -eq 1 ]; then\n\t\tlet REPLICA_COUNT=$SLAVE_NODE_COUNT/$MASTER_NODE_COUNT\n\t\tsudo bash redis-cluster-setup.sh -c $INSTANCE_COUNT -s $REPLICA_COUNT -p $IP_PREFIX\n\tfi\n}\n\n#############################################################################\nconfigure_redis_replication()\n{\n\tlog \"Configuring master-slave replication\"\n\n\tif [ \"$NODE_INDEX\" -lt \"$MASTER_NODE_COUNT\" ]; then\n\t\tlog \"Redis node ${HOSTNAME} is considered a MASTER, no further configuration changes are required\"\n\telse\n\t\tlog \"Redis node ${HOSTNAME} is considered a SLAVE, additional configuration changes will be made\"\n\n\t\tlet MASTER_NODE_INDEX=$NODE_INDEX%$MASTER_NODE_COUNT\n\t\tMASTER_NODE_IP=\"${IP_PREFIX}${MASTER_NODE_INDEX}\"\n\n\t\techo \"slaveof ${MASTER_NODE_IP} ${REDIS_PORT}\" >> /etc/redis/redis.conf\n\t\tlog \"Redis node ${HOSTNAME} is configured as a SLAVE of ${MASTER_NODE_IP}:${REDIS_PORT}\"\n\tfi\n}\n\n#############################################################################\nconfigure_sentinel()\n{\n\tlet MASTER_NODE_INDEX=$NODE_INDEX%$MASTER_NODE_COUNT\n\tMASTER_NODE_IP=\"${IP_PREFIX}${MASTER_NODE_INDEX}\"\n\n\t# Patch the sentinel configuration file with a new master\n\tsed -i \"s/^sentinel monitor.*$/sentinel monitor mymaster ${MASTER_NODE_IP} ${REDIS_PORT} ${MASTER_NODE_COUNT}/g\" /etc/redis/sentinel.conf\n\n\t# Make a writable log file\n\ttouch /var/log/redis-sentinel.log\n\tchown redis:redis /var/log/redis-sentinel.log\n\tchmod u+w /var/log/redis-sentinel.log\n\n\t# Change owner for /etc/redis/ to allow sentinel change the configuration files\n\tchown -R redis.redis /etc/redis/\n\n\t# Start the script automatically at boot time\n\tupdate-rc.d redis-sentinel defaults\n}\n\n#############################################################################\nstart_redis()\n{\n\t# Start the Redis daemon\n\t/etc/init.d/redis-server start\n\tlog \"Redis daemon was started successfully\"\n}\n\nstart_sentinel()\n{\n\t# Start the Redis sentinel daemon\n\t/etc/init.d/redis-sentinel start\n\tlog \"Redis sentinel daemon was started successfully\"\n}\n\n# Step1\ntune_system\ntune_memory\ntune_network\n\n# Step 2\ninstall_redis\n\n# Step 3\nconfigure_redis\n\n# Step 4\nif [ \"$IS_CLUSTER_AWARE\" -eq 1 ]; then\n\tconfigure_redis_cluster\nelse\n\tconfigure_redis_replication\n\tconfigure_sentinel\nfi\n\n# Step 5\nstart_redis\n\n# Step 6\nif [ \"$IS_CLUSTER_AWARE\" -eq 1 ]; then\n\tinitialize_redis_cluster\nelse\n\tstart_sentinel\nfi\n", "num_lines": 406}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Script parameters and their defaults\nINSTANCE_COUNT=1\nSLAVE_COUNT=0\nIP_PREFIX=\"10.0.0.\"\nREDIS_PORT=6379\nLOGGING_KEY=\"[account-key]\"\n\n########################################################\n# This script will configures a Redis cluster\n########################################################\nhelp()\n{\n\techo \"This script configures a Redis cluster on the Ubuntu virtual machine image\"\n\techo \"Available parameters:\"\n\techo \"-c Instance Count\"\n\techo \"-s Slave Count\"\n\techo \"-p Redis Node IP Prefix\"\n}\n\nlog()\n{\n\t# If you want to enable this logging add a un-comment the line below and add your account key\n\t#curl -X POST -H \"content-type:text/plain\" --data-binary \"$(date) | ${HOSTNAME} | $1\" https://logs-01.loggly.com/inputs/${LOGGING_KEY}/tag/redis-extension,${HOSTNAME}\n\techo \"$1\"\n}\n\n# Expand a list of successive IP range defined by a starting address prefix (e.g. 10.0.0.1) and the number of machines in the range\n# 10.0.0.1-3 would be converted to \"10.0.0.10 10.0.0.11 10.0.0.12\"\nexpand_ip_range() {\n    IFS='-' read -a HOST_IPS <<< \"$1\"\n\n    declare -a EXPAND_STATICIP_RANGE_RESULTS=()\n\n    for (( n=0 ; n<(\"${HOST_IPS[1]}\"+0) ; n++))\n    do\n        HOST=\"${HOST_IPS[0]}${n}:${REDIS_PORT}\"\n\t\tEXPAND_STATICIP_RANGE_RESULTS+=($HOST)\n    done\n\n    echo \"${EXPAND_STATICIP_RANGE_RESULTS[@]}\"\n}\n\nlog \"Begin execution of Redis cluster configuration script extension on ${HOSTNAME}\"\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Parse script parameters\nwhile getopts :c:s:p:h optname; do\n  log \"Option $optname set with value ${OPTARG}\"\n\n  case $optname in\n\tc) # Number of instances\n\t\tINSTANCE_COUNT=${OPTARG}\n\t\t;;\n\ts) # Number of slave nodes\n\t\tSLAVE_COUNT=${OPTARG}\n\t\t;;\n\tp) # Private IP address prefix\n\t\tIP_PREFIX=${OPTARG}\n\t\t;;\n    h)  # Helpful hints\n\t\thelp\n\t\texit 2\n\t\t;;\n    \\?) #unrecognized option - show help\n\t\techo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n\t\thelp\n\t\texit 2\n\t\t;;\n  esac\ndone\n\nlog \"Configuring Redis cluster on ${INSTANCE_COUNT} nodes with ${SLAVE_COUNT} slave(s) for every master node\"\n\n# Install the Ruby runtime that the cluster configuration script uses\napt-get -y install ruby-full\n\n# Install the Redis client gem (a pre-requisite for redis-trib.rb)\ngem install redis\n\n# Create a cluster based upon the specified host list and replica count\necho \"yes\" | /usr/local/bin/redis-trib.rb create --replicas ${SLAVE_COUNT} $(expand_ip_range \"${IP_PREFIX}-${INSTANCE_COUNT}\")\n\nlog \"Redis cluster was configured successfully\"\n", "num_lines": 114}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/sh\n### BEGIN INIT INFO\n# Provides:             redis-sentinel\n# Required-Start:       $syslog $remote_fs\n# Required-Stop:        $syslog $remote_fs\n# Should-Start:         $local_fs\n# Should-Stop:          $local_fs\n# Default-Start:        2 3 4 5\n# Default-Stop:         0 1 6\n# Short-Description:    redis-sentinel - Failover for Redis\n# Description:          redis-sentinel - Failover for Redis\n### END INIT INFO\n\nPATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\nDAEMON=/usr/local/bin/redis-sentinel\nDAEMON_ARGS=/etc/redis/sentinel.conf\nNAME=redis-sentinel\nDESC=redis-sentinel\nPIDFILE=/var/run/redis-sentinel.pid\n\ncase \"$1\" in\n  start)\n        echo -n \"Starting $DESC: \"\n        touch $PIDFILE\n        chown redis:redis $PIDFILE\n        if start-stop-daemon --start --umask 007 --pidfile $PIDFILE --chuid redis:redis --exec $DAEMON -- $DAEMON_ARGS\n        then\n                echo \"$NAME.\"\n        else\n                echo \"failed\"\n        fi\n        ;;\n  stop)\n        echo -n \"Stopping $DESC: \"\n        if start-stop-daemon --stop --retry 10 --quiet --oknodo --pidfile $PIDFILE --exec $DAEMON\n        then\n                echo \"$NAME.\"\n        else\n                echo \"failed\"\n        fi\n        rm -f $PIDFILE\n        ;;\n\n  restart|force-reload)\n        ${0} stop\n        ${0} start\n        ;;\n\n  status)\n        echo -n \"$DESC is \"\n        if start-stop-daemon --stop --quiet --signal 0 --name ${NAME} --pidfile ${PIDFILE}\n        then\n                echo \"running\"\n        else\n                echo \"not running\"\n                exit 1\n        fi\n        ;;\n\n  *)\n        echo \"Usage: /etc/init.d/$NAME {start|stop|status|restart|force-reload}\" >&2\n        exit 1\n        ;;\nesac\n\nexit 0\n", "num_lines": 67}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho 'hello'\n", "num_lines": 4}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\ncd /usr/local\ntouch privateIP.txt\n\necho $1 >> privateIP.txt\n", "num_lines": 7}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nVERSION=$1\nRELEASE=$2\nPASSWORD=$3\n\n# Install Java JDK\necho \"Installing Java JDK\"\n\n#zypper search java | grep openjdk\nzypper --non-interactive install java-1_7_0-openjdk\n\n# Retrieve Glassfish source files\necho \"Retrieving Glassfish source files\"\n\nwget http://download.java.net/glassfish/3.1.2.2/release/glassfish-$RELEASE.zip -P /tmp/\nunzip /tmp/glassfish-$RELEASE.zip -d /opt\nrm /tmp/glassfish-$RELEASE.zip\n\n# Start GlassFish Server\necho \"Starting GlassFish server\"\n\n/opt/glassfish$VERSION/bin/asadmin start-domain\n\n# Enable admin access\necho \"Enabling admin Access\"\n\ntouch /tmp/password.txt\nchmod 600 /tmp/password.txt\necho \"AS_ADMIN_PASSWORD=\" > /tmp/password.txt\necho \"AS_ADMIN_NEWPASSWORD=$PASSWORD\" >> /tmp/password.txt\n/opt/glassfish$VERSION/bin/asadmin --user admin --passwordfile /tmp/password.txt change-admin-password \\\n    --domain_name domain1\nsed -i '/^AS_ADMIN_PASSWORD=/d' /tmp/password.txt\nsed -i '/^AS_ADMIN_NEW_PASSWORD=/d' /tmp/password.txt\necho \"AS_ADMIN_PASSWORD=$PASSWORD\" > /tmp/password.txt\n/opt/glassfish$VERSION/bin/asadmin --user admin --passwordfile /tmp/password.txt enable-secure-admin\nrm /tmp/password.txt\n\n# Enable GlassFish as a service and quick initialization\necho \"Enabling GlassFish as a service\"\ntee /etc/init.d/glassfish > /dev/null <<'EOF'\n\n# Set path variable\nGLASSFISH_HOME=/opt/glassfish$VERSION\n\n# Establish service commands\ncase \"$1\" in\nstart)\n    ${GLASSFISH_HOME}/bin/asadmin start-domain domain1\n    ;;\nstop)\n    ${GLASSFISH_HOME}/bin/asadmin stop-domain domain1\n    ;;\nrestart)\n    ${GLASSFISH_HOME}/bin/asadmin stop-domain domain1\n    ${GLASSFISH_HOME}/bin/asadmin start-domain domain1\n    ;;\n*)\n    echo \"usage: $0 {start|stop|restart}\"\n    ;;\nesac\nexit 0\n\nEOF\n\nchmod 755 /etc/init.d/glassfish\n\necho \"Script complete\"\n", "num_lines": 70}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Insert code to fetch information to be returned, then write to stdout\n\n# write an array delimiter before and after the data we want\necho '#DATA#'\necho 'this is the droid you have been looking for'\necho '#DATA#'\n", "num_lines": 9}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# This script can do whatever we want it to\n\necho 'this is what we got from the previous script:'\necho $1\n", "num_lines": 7}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -x\n#set -xeuo pipefail\n\nif [[ $(id -u) -ne 0 ]] ; then\n    echo \"Must be run as root\"\n    exit 1\nfi\n\nif [ $# != 8 ]; then\n    echo \"Usage: $0 <MasterHostname> <mountFolder> <numDataDisks> <dockerVer> <dockerComposeVer> <adminUsername> <imageSku> <dockerMachineVer>\"\n    exit 1\nfi\n\n# Set user args\nMASTER_HOSTNAME=$1\n\n# Shares\nMNT_POINT=\"$2\"\nSHARE_HOME=$MNT_POINT/home\nSHARE_DATA=$MNT_POINT/data\n\nnumberofDisks=\"$3\"\ndockerVer=\"$4\"\ndockerComposeVer=\"$5\"\nuserName=\"$6\"\nskuName=\"$7\"\ndockMVer=\"$8\"\n\n\n\nsetup_dynamicdata_disks()\n{\n    mountPoint=\"$1\"\n    createdPartitions=\"\"\n\n    # Loop through and partition disks until not found\n\nif [ \"$numberofDisks\" == \"1\" ]\nthen\n   disking=( sdc )\nelif [ \"$numberofDisks\" == \"2\" ]; then\n   disking=( sdc sdd )\nelif [ \"$numberofDisks\" == \"3\" ]; then\n   disking=( sdc sdd sde )\nelif [ \"$numberofDisks\" == \"4\" ]; then\n   disking=( sdc sdd sde sdf )\nelif [ \"$numberofDisks\" == \"5\" ]; then\n   disking=( sdc sdd sde sdf sdg )\nelif [ \"$numberofDisks\" == \"6\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh )\nelif [ \"$numberofDisks\" == \"7\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi )\nelif [ \"$numberofDisks\" == \"8\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj )\nelif [ \"$numberofDisks\" == \"9\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk )\nelif [ \"$numberofDisks\" == \"10\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl )\nelif [ \"$numberofDisks\" == \"11\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm )\nelif [ \"$numberofDisks\" == \"12\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn )\nelif [ \"$numberofDisks\" == \"13\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo )\nelif [ \"$numberofDisks\" == \"14\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo sdp )\nelif [ \"$numberofDisks\" == \"15\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo sdp sdq )\nelif [ \"$numberofDisks\" == \"16\" ]; then\n   disking=( sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo sdp sdq sdr )\nfi\n\nprintf \"%s\\n\" \"${disking[@]}\"\n\nfor disk in \"${disking[@]}\"\ndo\n        fdisk -l /dev/$disk || break\n        fdisk /dev/$disk << EOF\nn\np\n1\n\n\nt\nfd\nw\nEOF\n        createdPartitions=\"$createdPartitions /dev/${disk}1\"\ndone\n\n    # Create RAID-0 volume\n    if [ -n \"$createdPartitions\" ]; then\n        devices=`echo $createdPartitions | wc -w`\n        mdadm --create /dev/md10 --level 0 --raid-devices $devices $createdPartitions\n        mkfs -t ext4 /dev/md10\n        echo \"/dev/md10 $mountPoint ext4 defaults,nofail 0 2\" >> /etc/fstab\n        mount /dev/md10\n    fi\n}\n# Creates and exports two shares on the node:\n#\n# /share/home\n# /share/data\n#\nsetup_shares()\n{\n    mkdir -p $SHARE_HOME\n    mkdir -p $SHARE_DATA\n\n   # if is_master; then\n        #setup_data_disks $SHARE_DATA\n\tsetup_dynamicdata_disks $SHARE_DATA\n        echo \"$SHARE_HOME    *(rw,async)\" >> /etc/exports\n        echo \"$SHARE_DATA    *(rw,async)\" >> /etc/exports\n\n\tif [ \"$skuName\" == \"16.04.0-LTS\" ] ; then\n\t         DEBIAN_FRONTEND=noninteractive apt-get -y \\\n\t\t  -o DPkg::Options::=--force-confdef \\\n\t\t -o DPkg::Options::=--force-confold \\\n    \t\tinstall nfs-kernel-server\n\t\t/etc/init.d/apparmor stop\n\t\t/etc/init.d/apparmor teardown\n\t\tupdate-rc.d -f apparmor remove\n\t\tapt-get -y remove apparmor\n                systemctl start rpcbind || echo \"Already enabled\"\n                systemctl start nfs-server || echo \"Already enabled\"\n                systemctl start nfs-kernel-server.service\n                systemctl enable rpcbind || echo \"Already enabled\"\n                systemctl enable nfs-server || echo \"Already enabled\"\n                systemctl enable nfs-kernel-server.service\n        else\n                systemctl start rpcbind || echo \"Already enabled\"\n                systemctl start nfs-server || echo \"Already enabled\"\n                systemctl enable rpcbind || echo \"Already enabled\"\n                systemctl enable nfs-server || echo \"Already enabled\"\n         fi\n\n\n    #else\n    #    echo \"master:$SHARE_HOME $SHARE_HOME    nfs4    rw,auto,_netdev 0 0\" >> /etc/fstab\n    #    echo \"master:$SHARE_DATA $SHARE_DATA    nfs4    rw,auto,_netdev 0 0\" >> /etc/fstab\n    #    mount -a\n    #    mount | grep \"^master:$SHARE_HOME\"\n    #    mount | grep \"^master:$SHARE_DATA\"\n    #fi\n}\n\n\nset_time()\n{\n    mv /etc/localtime /etc/localtime.bak\n    ln -s /usr/share/zoneinfo/Europe/Amsterdam /etc/localtime\n}\n\n\n# System Update.\n#\nsystem_update()\n{\n    rpm --rebuilddb\n    updatedb\n    yum clean all\n    yum -y install epel-release\n    yum  -y update --exclude=WALinuxAgent\n    #yum  -y update\n\n    set_time\n}\n\ninstall_docker()\n{\n\n    wget -qO- \"https://pgp.mit.edu/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e\"\n    rpm --import \"https://pgp.mit.edu/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e\"\n    yum install -y yum-utils\n    yum-config-manager --add-repo https://packages.docker.com/$dockerVer/yum/repo/main/centos/7\n    yum install -y docker-engine\n    systemctl stop firewalld\n    systemctl disable firewalld\n    #service docker start\n    gpasswd -a $userName docker\n    systemctl start docker\n    systemctl enable docker\n    #curl -L https://github.com/docker/compose/releases/download/$dockerComposeVer/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n     curl -L \"https://github.com/docker/compose/releases/download/$dockerComposeVer/docker-compose-$(uname -s)-$(uname -m)\" > /usr/local/bin/docker-compose\n    curl -L https://github.com/docker/machine/releases/download/v$dockMVer/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\n    chmod +x /usr/local/bin/docker-machine\n    chmod +x /usr/local/bin/docker-compose\n    export PATH=$PATH:/usr/local/bin/\n    systemctl restart docker\n}\n\ninstall_azure_cli()\n{\n    yum install -y nodejs\n    yum install -y npm\n    npm install -g azure-cli\n}\n\ninstall_docker_apps()\n{\n\n    # Setting tomcat\n    #docker run -it -dp 80:8080 -p 8009:8009  rossbachp/apache-tomcat8\n    docker run -dti --restart=always --name=azure-cli microsoft/azure-cli\n    docker run -it -d --restart=always -p 8080:8080 rancher/server\n}\n\n\n# Installs individual packages of interest.\n#\ninstall_packages()\n{\n    yum -y install zlib zlib-devel bzip2 bzip2-devel bzip2-libs openssl openssl-devel openssl-libs  nfs-utils rpcbind git libicu libicu-devel make zip unzip mdadm wget gsl bc rpm-build  readline-devel pam-devel libXtst.i686 libXtst.x86_64 make.x86_64 sysstat.x86_64 python-pip automake autoconf\\\n    binutils.x86_64 compat-libcap1.x86_64 glibc.i686 glibc.x86_64 \\\n    ksh compat-libstdc++-33 libaio.i686 libaio.x86_64 libaio-devel.i686 libaio-devel.x86_64 \\\n    libgcc.i686 libgcc.x86_64 libstdc++.i686 libstdc++.x86_64 libstdc++-devel.i686 libstdc++-devel.x86_64 libXi.i686 libXi.x86_64\n    #yum -y install icu patch ruby ruby-devel rubygems  gcc gcc-c++ gcc.x86_64 gcc-c++.x86_64 glibc-devel.i686 glibc-devel.x86_64\n}\n# Installs all required packages.\n#\ninstall_pkgs_all()\n{\n    system_update\n\n    install_packages\n\n\tif [ \"$skuName\" == \"6.5\" ] || [ \"$skuName\" == \"6.6\" ] ; then\n    \t\tinstall_azure_cli\n\telif [ \"$skuName\" == \"7.2\" ] || [ \"$skuName\" == \"7.1\" ] ; then\n\n    \t\tinstall_docker\n\n    \t\tinstall_docker_apps\n\tfi\n}\ninstall_packages_ubuntu()\n{\n\nDEBIAN_FRONTEND=noninteractive apt-get install -y zlib1g zlib1g-dev  bzip2 libbz2-dev libssl1.0.0  libssl-doc libssl1.0.0-dbg libsslcommon2 libsslcommon2-dev libssl-dev  nfs-common rpcbind git zip libicu55 libicu-dev icu-devtools unzip mdadm wget gsl-bin libgsl2  bc ruby-dev gcc make autoconf bison build-essential libyaml-dev libreadline6-dev libncurses5 libncurses5-dev libffi-dev libgdbm3 libgdbm-dev libpam0g-dev libxtst6 libxtst6-* libxtst-* libxext6 libxext6-* libxext-* git-core libelf-dev asciidoc binutils-dev fakeroot crash kexec-tools makedumpfile kernel-wedge portmap\n\nDEBIAN_FRONTEND=noninteractive apt-get -y build-dep linux\n\nDEBIAN_FRONTEND=noninteractive apt-get upgrade -y\n\nDEBIAN_FRONTEND=noninteractive update-initramfs -u\n}\ninstall_docker_ubuntu()\n{\n\n        # System Update and docker version update\n         DEBIAN_FRONTEND=noninteractive apt-get -y update\n         apt-get install -y apt-transport-https ca-certificates\n        #curl -s 'https://sks-keyservers.net/pks/lookup?op=get&search=0xee6d536cf7dc86e2d7d56f59a178ac6c6238f52e' | apt-key add --import\n        #echo \"deb https://packages.docker.com/$dockerVer/apt/repo ubuntu-trusty main\" >> /etc/apt/sources.list.d/docker.list\n         apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D\n\t echo \"deb https://packages.docker.com/${dockerVer}/apt/repo ubuntu-xenial main\" | sudo tee /etc/apt/sources.list.d/docker.list\n         #echo 'deb https://packages.docker.com/$dockerVer/apt/repo ubuntu-xenial main' > /etc/apt/sources.list.d/docker.list\n\t DEBIAN_FRONTEND=noninteractive apt-get -y update\n         DEBIAN_FRONTEND=noninteractive apt-get -y upgrade\n         apt-cache policy docker-engine\n\t groupadd docker\n\t usermod -aG docker $userName\n         #apt-get install -y docker-engine\n\t apt-get install -y --allow-unauthenticated docker-engine\n\t /etc/init.d/apparmor stop\n\t /etc/init.d/apparmor teardown\n\t update-rc.d -f apparmor remove\n\t apt-get -y remove apparmor\n         #DEBIAN_FRONTEND=noninteractive apt-get install -y --allow-unauthenticated docker-engine\n    curl -L https://github.com/docker/compose/releases/download/$dockerComposeVer/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose\n    curl -L https://github.com/docker/machine/releases/download/v$dockMVer/docker-machine-`uname -s`-`uname -m` >/usr/local/bin/docker-machine\n    chmod +x /usr/local/bin/docker-machine\n    chmod +x /usr/local/bin/docker-compose\n    export PATH=$PATH:/usr/local/bin/\n    systemctl restart docker\n}\n\n\n\n\tif [ \"$skuName\" == \"16.04.0-LTS\" ] ; then\n\t\tinstall_packages_ubuntu\n\t\tsetup_shares\n                install_docker_ubuntu\n                install_docker_apps\n\telif [ \"$skuName\" == \"6.5\" ] || [ \"$skuName\" == \"6.6\" ] || [ \"$skuName\" == \"7.2\" ] || [ \"$skuName\" == \"7.1\" ] ; then\n\t\tinstall_pkgs_all\n\t\tsetup_shares\n\tfi\n", "num_lines": 292}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwhile getopts \":i:a:c:r:\" opt; do\n  case $opt in\n    i) docker_image=\"$OPTARG\"\n    ;;\n    a) storage_account=\"$OPTARG\"\n    ;;\n    c) container_name=\"$OPTARG\"\n    ;;\n    r) resource_group=\"$OPTARG\"\n    ;;\n    p) port=\"$OPTARG\"\n    ;;\n    t) script_file=\"$OPTARG\"\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\nif [ -z $docker_image ]; then\n    docker_image=\"mcr.microsoft.com/azure-cli\"\nfi\n\nif [ -z $script_file ]; then\n    script_file=\"writeblob.sh\"\nfi\n\nfor var in storage_account resource_group\ndo\n\n    if [ -z ${!var} ]; then\n        echo \"Argument $var is not set\" >&2\n        exit 1\n    fi\n\ndone\n\n# Install Docker and then run docker image with cli.\n\nsudo apt-get update\nsudo apt-get install -y docker.io\nsudo docker run -d -v $PWD:/scripts \\\n-e STORAGE_ACCOUNT=${storage_account} \\\n-e CONTAINER_NAME=${container_name} \\\n-e RESOURCE_GROUP=${resource_group} \\\n-e PORT=${PORT} \\\n${docker_image} \"/scripts/${script_file}\"", "num_lines": 49}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z $CONTAINER_NAME ]; then\n    CONTAINER_NAME=\"msi\"\nelse\n    CONTAINER_NAME=$(echo \"$CONTAINER_NAME\"|tr '[:upper:]' '[:lower:]')\nfi\n\n# The default port for the MSI extension is 50342\n\nif [ -z $PORT ]; then\n    PORT=50342\nfi\n\nfor var in STORAGE_ACCOUNT RESOURCE_GROUP\ndo\n\n    if [ -z ${!var} ]; then\n        echo \"Argument $var is not set\" >&2\n        exit 1\n    fi\n\ndone\n\n# login using msi\n\naz login --identity\n\n# create a file and upload it to storage account using a key obtained via the logged in MSI , the MSI must have permission to perfrm these operations\n\nstorage_account_key=`az storage account keys list -n ${STORAGE_ACCOUNT} -g ${RESOURCE_GROUP}|jq '.[0].value'`\n\nif [ `az storage container exists -n ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key} |jq '.exists'` = 'false' ]; then\n    echo \"Creating container ${CONTAINER_NAME} in storage account ${STORAGE_ACCOUNT}\"\n    az storage container create -n ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key}\nfi\n\nblob_name=$(hostname|tr '[:upper:]' '[:lower:]')\nfile_name=mktemp\ndate > $file_name\naz storage blob upload --container-name ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key} --name ${blob_name} --file ${file_name}\n", "num_lines": 42}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nlogger -t devvm \"Desktop Install started: $?\"\n\nsudo apt-get -y update\n\nsudo apt-get -q=2 -y install xrdp\n\nlogger -t devvm \"XRDP installed: $?\"\n\nlogger -t devvm \"Installing Mate Desktop ...\"\n\nsudo dpkg --configure -a\n\nsudo apt-add-repository -y ppa:ubuntu-mate-dev/ppa\n\nsudo apt-add-repository -y ppa:ubuntu-mate-dev/trusty-mate\n\nsudo apt-get -y update\n\nsudo apt-get -y upgrade\n\nsudo apt-get install -q=2  --no-install-recommends -m ubuntu-mate-core\n\nsudo apt-get install -q=2  --no-install-recommends -m ubuntu-mate-desktop\n\nlogger -t devvm \"Mate Desktop installed. $?\"\n\necho mate-session >~/.xsession\n\nsudo service xrdp restart\n\n# FIxes the issue with Ubuntu desktop being blank.\n\nsudo sed -i -e 's/console/anybody/g' /etc/X11/Xwrapper.config\n\n\nlogger -t devvm \"Mate Desktop configured. $?\"\n\nlogger -t devvm \"Installing VSCode: $?\"\n\n\ncurl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg\n\nsudo mv microsoft.gpg /etc/apt/trusted.gpg.d/microsoft.gpg\n\nsudo sh -c 'echo \"deb [arch=amd64] https://packages.microsoft.com/repos/vscode stable main\" > /etc/apt/sources.list.d/vscode.list'\n\nsudo apt-get update\n\nsudo apt-get install -y code\n\nlogger -t devvm \"VSCode Installed: $?\"\n\nlogger -t devvm \"Success\"\nexit 0\n", "num_lines": 57}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\napt-get update\n\nwget -O terraform.zip https://releases.hashicorp.com/terraform/0.11.1/terraform_0.11.1_linux_amd64.zip?_ga=2.228206621.1801000149.1512425211-1345627201.1504718143\nsudo apt-get install -y jq\n\nsudo apt-get install unzip\n\nunzip terraform.zip\n\n\nTF_VERSION=$(curl -s https://checkpoint-api.hashicorp.com/v1/check/terraform | jq -r -M \".current_version\")\nwget -O terraform.zip https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_linux_amd64.zip\nwget -O terraform.sha256 https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS\nwget -O terraform.sha256.sig https://releases.hashicorp.com/terraform/${TF_VERSION}/terraform_${TF_VERSION}_SHA256SUMS.sig\ncurl -s https://keybase.io/hashicorp/pgp_keys.asc | gpg --import\ngpg --verify terraform.sha256.sig terraform.sha256\necho $(grep -Po \"[[:xdigit:]]{64}(?=\\s+terraform_${TF_VERSION}_linux_amd64.zip)\" terraform.sha256) terraform.zip | sha256sum -c\nunzip terraform.zip\nmv terraform /usr/local/bin\nrm -f terraform terraform.zip terraform.sha256 terraform.sha256.sig\nunset TF_VERSION\n\n\necho \"deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ wheezy main\" | sudo tee /etc/apt/sources.list.d/azure-cli.list\n\nsudo curl -L https://packages.microsoft.com/keys/microsoft.asc | sudo apt-key add -\n\napt-get install apt-transport-https\n\napt-get update && sudo apt-get install azure-cli\n", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Script Name: install.sh\n# Author: Greg Oliver - Microsoft github:(sebastus)\n# Version: 0.1\n# Last Modified By: Greg Oliver\n# Description:\n#  This script configures authentication for Terraform and remote state for Terraform.\n# Parameters :\n#  1 - s: Azure subscription ID\n#  2 - a: Storage account name\n#  3 - k: Storage account key (password)\n#  4 - l: MSI client id (principal id)\n#  5 - u: User account name\n#  6 - d: Ubuntu Desktop GUI for developement\n#  7 - h: help\n# Note :\n# This script has only been tested on Ubuntu 12.04 LTS & 14.04 LTS and must be root\n\nset -e\n\nlogger -t devvm \"Install started: $?\"\n\nhelp()\n{\n    echo \"This script sets up a node, and configures pre-installed Splunk Enterprise\"\n    echo \"Usage: \"\n    echo \"Parameters:\"\n    echo \"- s: Azure subscription ID\"\n    echo \"- a: Storage account name\"\n    echo \"- k: Storage account key (password)\"\n    echo \"- l: MSI client id (principal id)\"\n    echo \"- u: User account name\"\n    echo \"- d: Ubuntu Desktop GUI\"\n    echo \"- h: help\"\n}\n\n# Log method to control log output\nlog()\n{\n    echo \"`date`: $1\"\n}\n\n# You must be root to run this script\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Arguments\nwhile getopts :s:t:a:k:l:u:d: optname; do\n  if [[ $optname != 'e' && $optname != 'k' ]]; then\n    log \"Option $optname set with value ${OPTARG}\"\n  fi\n  case $optname in\n    s) #azure subscription id\n      SUBSCRIPTION_ID=${OPTARG}\n      ;;\n    t) #azure tenant id\n      TENANT_ID=${OPTARG}\n      ;;\n    a) #storage account name\n      STORAGE_ACCOUNT_NAME=${OPTARG}\n      ;;\n    k) #storage account key\n      STORAGE_ACCOUNT_KEY=${OPTARG}\n      ;;\n    l) #PrincipalId of the MSI identity\n      MSI_PRINCIPAL_ID=${OPTARG}\n      ;;\n    u) #user account name\n      USERNAME=${OPTARG}\n      ;;\n    d) #Desktop installation\n      DESKTOPINSTALL=${OPTARG}\n      ;;\n    h) #Show help\n      help\n      exit 2\n      ;;\n    \\?) #Unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nTEMPLATEFOLDER=\"/home/$USERNAME/tfTemplate\"\nREMOTESTATEFILE=\"$TEMPLATEFOLDER/remoteState.tf\"\nTFENVFILE=\"/home/$USERNAME/tfEnv.sh\"\nCREDSFILE=\"$TEMPLATEFOLDER/azureProviderAndCreds.tf\"\nPROFILEFILE=\"/home/$USERNAME/.profile\"\n\nmkdir $TEMPLATEFOLDER\n\ncp ./azureProviderAndCreds.tf $TEMPLATEFOLDER\nchmod 666 $CREDSFILE\n\ntouch $REMOTESTATEFILE\necho \"terraform {\"                                          >> $REMOTESTATEFILE\necho \" backend \\\"azurerm\\\" {\"                               >> $REMOTESTATEFILE\necho \"  storage_account_name = \\\"$STORAGE_ACCOUNT_NAME\\\"\"   >> $REMOTESTATEFILE\necho \"  container_name       = \\\"terraform-state\\\"\"         >> $REMOTESTATEFILE\necho \"  key                  = \\\"prod.terraform.tfstate\\\"\"  >> $REMOTESTATEFILE\necho \"  access_key           = \\\"$STORAGE_ACCOUNT_KEY\\\"\"    >> $REMOTESTATEFILE\necho \"  }\"                                                  >> $REMOTESTATEFILE\necho \"}\"                                                    >> $REMOTESTATEFILE\nchmod 666 $REMOTESTATEFILE\n\nchown -R $USERNAME:$USERNAME /home/$USERNAME/tfTemplate\n\n# Set these variables in the profile\necho \"export ARM_SUBSCRIPTION_ID=\\\"$SUBSCRIPTION_ID\\\"\"                                     >> $PROFILEFILE\necho \"export ARM_CLIENT_ID=\\\"$MSI_PRINCIPAL_ID\\\"\"                                          >> $PROFILEFILE\necho \"export ARM_USE_MSI=true\"                                                             >> $PROFILEFILE\necho \"export ARM_MSI_ENDPOINT=\\\"http://169.254.169.254/metadata/identity/oauth2/token\\\"\"   >> $PROFILEFILE\necho \"export ARM_TENANT_ID=\\\"$TENANT_ID\\\"\"                                                 >> $PROFILEFILE\n\n# Add contributor permissions to the MSI for entire subscription\ntouch $TFENVFILE\necho \"az login\"                                            >> $TFENVFILE\necho \"az role assignment create  --assignee \\\"$MSI_PRINCIPAL_ID\\\" --role 'b24988ac-6180-42a0-ab88-20f7382dd24c'  --scope /subscriptions/\\\"$SUBSCRIPTION_ID\\\"\"  >> $TFENVFILE\n\nchmod 755 $TFENVFILE\nchown $USERNAME:$USERNAME $TFENVFILE\n\n# create the container for remote state\nlogger -t devvm \"Creating the container for remote state\"\naz login --identity\naz storage container create -n terraform-state --account-name $STORAGE_ACCOUNT_NAME --account-key $STORAGE_ACCOUNT_KEY\nlogger -t devvm \"Container for remote state created: $?\"\n\nif [[ -v DESKTOPINSTALL ]]; then\n    echo \"Installing Mate Desktop\"\n    bash ./desktop.sh\n    echo \"Desktop installed\"\nfi\n\n", "num_lines": 142}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\napt-get -y update\n\n# install Apache2\napt-get -y install apache2\napt-get -y install mysql-server\napt-get -y install php libapache2-mod-php php-mysql\n# write some HTML\necho \\<center\\>\\<h1\\>My Demo App\\</h1\\>\\<br/\\>\\</center\\> > /var/www/html/demo.html\n\n# restart Apache\napachectl restart\n", "num_lines": 13}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n\n#!/bin/bash\n# $1 = Azure storage account name\n# $2 = Azure storage account key\n# $3 = Azure file share name\n# $4 = mountpoint path\n# $5 - username\n\n# For more details refer to https://azure.microsoft.com/en-us/documentation/articles/storage-how-to-use-files-linux/\n\n# update package lists\napt-get -y update\n\n# install cifs-utils and mount file share\napt-get install cifs-utils\nmkdir $4\nmount -t cifs //$1.file.core.windows.net/$3 $4 -o vers=3.0,username=$1,password=$2,dir_mode=0755,file_mode=0664\n\n# create a symlink from /mountpath/xxx to ~username/xxx\nlinkpoint=`echo $4 | sed 's/.*\\///'`\neval ln -s $4 ~$5/$linkpoint\n\n# create marker files for testing\necho \"hello from $HOSTNAME\" > $4/$HOSTNAME.txt\n\n\n\n", "num_lines": 29}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n# Custom Script for Linux (Ubuntu 16)\n\n# exit on any error\nset -e\n\n# functions\nupdate_app(){\n    echo \"creating folder \" $2 \"/temp\"\n    mkdir $2\n    mkdir $2/temp\n\n    if [ ${1:0:4} == \"http\" ]; then\n        cd $2/temp\n        echo \"downloading\" $1\n        wget --content-disposition $1\n    else\n        cp $1 $2/temp/\n        cd $2/temp\n    fi\n    #uncompress it\n    tar -xzvf *.tar.gz -C ../\n    cd -\n    rm -r $2/temp\n}\n\nrestart_service(){\n    # something like: systemctl restart mainsite.service\n    # this sample originally expected a specific custom image that's no longer available... so the service in question may not exist.\n    # systemctl restart $1\n    pwd\n}\n\n# script start\n\necho \"Welcome to updateapp.sh\"\necho \"Number of parameters was: \" $#\n\nif [ $# -ne 3 ]; then\n    echo usage: $0 {sasuri} {destination} {serviceName}\n        exit 1\nfi\n\necho \"downloading: \" $1 \"into \" $2\n\nupdate_app $1 $2\n\necho \"restarting service \" $3\n\nrestart_service $3\n", "num_lines": 51}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nwhile getopts \":i:a:c:r:\" opt; do\n  case $opt in\n    i) docker_image=\"$OPTARG\"\n    ;;\n    a) storage_account=\"$OPTARG\"\n    ;;\n    c) container_name=\"$OPTARG\"\n    ;;\n    r) resource_group=\"$OPTARG\"\n    ;;\n    p) port=\"$OPTARG\"\n    ;;\n    t) script_file=\"$OPTARG\"\n    ;;\n    \\?) echo \"Invalid option -$OPTARG\" >&2\n    ;;\n  esac\ndone\n\nif [ -z $docker_image ]; then\n    docker_image=\"mcr.microsoft.com/azure-cli\"\nfi\n\nif [ -z $script_file ]; then\n    script_file=\"writeblob.sh\"\nfi\n\nfor var in storage_account resource_group\ndo\n\n    if [ -z ${!var} ]; then\n        echo \"Argument $var is not set\" >&2\n        exit 1\n    fi\n\ndone\n\n# Install Docker and then run docker image with cli.\n\nsudo apt-get update\nsudo apt-get install -y docker.io\nsudo docker run -d -v $PWD:/scripts \\\n-e STORAGE_ACCOUNT=${storage_account} \\\n-e CONTAINER_NAME=${container_name} \\\n-e RESOURCE_GROUP=${resource_group} \\\n-e PORT=${PORT} \\\n${docker_image} \"/scripts/${script_file}\"", "num_lines": 49}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z $CONTAINER_NAME ]; then\n    CONTAINER_NAME=\"msi\"\nelse\n    CONTAINER_NAME=$(echo \"$CONTAINER_NAME\"|tr '[:upper:]' '[:lower:]')\nfi\n\nfor var in STORAGE_ACCOUNT RESOURCE_GROUP\ndo\n\n    if [ -z ${!var} ]; then\n        echo \"Argument $var is not set\" >&2\n        exit 1\n    fi\n\ndone\n\n# login using msi\naz login --identity\n\n# create a file and upload it to storage account using a key obtained via the logged in MSI , the MSI must have permission to perfrm these operations\nstorage_account_key=`az storage account keys list -n ${STORAGE_ACCOUNT} -g ${RESOURCE_GROUP}|jq '.[0].value'`\n\nif [ `az storage container exists -n ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key} |jq '.exists'` = 'false' ]; then\n    echo \"Creating container ${CONTAINER_NAME} in storage account ${STORAGE_ACCOUNT}\"\n    az storage container create -n ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key}\nfi\n\nblob_name=$(hostname|tr '[:upper:]' '[:lower:]')\nfile_name=mktemp\ndate > $file_name\naz storage blob upload --container-name ${CONTAINER_NAME} --account-name ${STORAGE_ACCOUNT} --account-key ${storage_account_key} --name ${blob_name} --file ${file_name}\n", "num_lines": 34}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# exit on any error\nset -e\n\necho \"Welcome to configuressl.sh\"\necho \"Number of parameters was: \" $#\n\nif [ $# -lt 1 ]; then\n    echo usage: $0 [certificatefingerprint] [CAcertificatefingerprint]\n\texit 1\nfi\n\necho \"Checking for apache2 already installed\"\nif dpkg -s apache2 > /dev/null 2>&1; then\n     echo \"Apache2 installed already - exiting\"\n     exit\nelse\n     echo \"Apache2 not installed - proceeding\"\nfi\n\n# install needed bits in a loop because a lot of installs happen\n# on VM init, so won't be able to grab the dpkg lock immediately\nuntil apt-get -y update && apt-get -y install apache2\ndo\n  echo \"Trying again\"\n  sleep 2\ndone\n\n# turn off apache until we are done with setup\n# Azure LB HTTP/s Probe will fail and not direct traffic to VM\napachectl stop\n\n# Enable ssl in apache\na2enmod ssl\na2ensite default-ssl\n\ncertprint=$1\n\n\nsslcertfilename=$certprint'.crt'\nsslkeyfilename=$certprint'.prv'\n\n\necho \"Copying SSL files\"\necho \"cert file\" $sslcertfilename\nfullpath=/var/lib/waagent/$sslcertfilename\nif [ -f $fullpath ]\nthen\n    cp $fullpath /etc/ssl/certs/\nelse\n    echo \"Cert missing: \" $fullpath\n    exit 1\nfi\n\necho \"private key file\" $sslkeyfilename\nfullpath=/var/lib/waagent/$sslkeyfilename\nif [ -f $fullpath ]\nthen\n    cp $fullpath /etc/ssl/private/\nelse\n    echo \"Private Key missing: \" $fullpath\n    exit 1\nfi\n\necho \"configuring certfile\"\nsed -i 's/#*SSLCertificateFile.*$/SSLCertificateFile \\/etc\\/ssl\\/certs\\/'$sslcertfilename'/g' /etc/apache2/sites-enabled/default-ssl.conf\necho \"keyfile\"\nsed -i 's/#*SSLCertificateKeyFile.*$/SSLCertificateKeyFile \\/etc\\/ssl\\/private\\/'$sslkeyfilename'/g' /etc/apache2/sites-enabled/default-ssl.conf\n\nif [ ! -z \"$2\" ]\n    then\n        echo \"CA cert thumbprint present. Configuring ...\"\n        cacertprint=$2\n        sslcafilename=$cacertprint'.crt'\n        echo \"CA cert file\" $sslcafilename\n        fullpath=/var/lib/waagent/$sslcafilename\n        if [ -f $fullpath ]\n        then\n            cp $fullpath /etc/ssl/certs/\n        else\n            echo \"Cert missing: \" $fullpath\n            exit 1\n        fi\n\n        echo \"Configuring Apache for CA cert\"\n        sed -i 's/#*SSLCertificateChainFile.*$/SSLCertificateChainFile \\/etc\\/ssl\\/certs\\/'$sslcafilename'/g' /etc/apache2/sites-enabled/default-ssl.conf\n    else\n        echo \"No CA thumbprint. Assuming self-signed\"\nfi\n\necho \"restarting apache\"\n# all done - turn apache on\napachectl start\n\necho \"Done!\"\n", "num_lines": 97}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nusage()\n{\n    echo \"Usage: $0 -g <resourceGroupName> -l <resourceGroupLocation> -s <scriptstorageaccount> \" 1>&2; exit 1;\n}\n\nstagecustomscript()\n{\n    azure storage account show $scriptstorageaccount -g $resourceGroupName\n    if [ $? -eq 1 ]\n    then\n        echo Creating storate account $scriptstorageaccount in RG $resourceGroupName in $resourceGroupLocation\n        azure storage account create $scriptstorageaccount -g $resourceGroupName -l $resourceGroupLocation --kind Storage --sku-name LRS\n    fi\n\n    key=$(azure storage account keys list $scriptstorageaccount -g $resourceGroupName | grep -o 'key1\\s*[^ ]*' | cut -d' ' -f3)\n    echo Uploading custom script to $scriptstorageaccount\n\n    containername='scripts'\n\n    azure storage container show -a $scriptstorageaccount -k $key $containername\n    if [ $? -eq 1 ]\n    then\n        echo Creating Container $containername\n        azure storage container create --container $containername -p Blob -a $scriptstorageaccount -k $key\n    fi\n    azure storage blob upload -f ./configuressl.sh -a $scriptstorageaccount -k $key --container $containername -q\n}\n\n# Initialize parameters specified from command line\nwhile getopts \":g:l:s:\" o; do\n\tcase \"${o}\" in\n\t\tg)\n\t\t\tresourceGroupName=${OPTARG}\n\t\t\t;;\n\t\tl)\n\t\t\tresourceGroupLocation=${OPTARG}\n\t\t\t;;\n        s) scriptstorageaccount=${OPTARG}\n            ;;\n\t\tesac\ndone\nshift $((OPTIND-1))\n\n#Prompt for parameters is some required parameters are missing\nif [ -z \"$resourceGroupName\" ]; then\n\techo \"ResourceGroupName:\"\n\tread resourceGroupName\nfi\n\nif [ -z \"$resourceGroupLocation\" ]; then\n\techo \"Enter a location below to create a new resource group else skip this\"\n\techo \"ResourceGroupLocation:\"\n\tread resourceGroupLocation\nfi\n\nif [ -z \"$scriptstorageaccount\" ]; then\n\techo \"Enter the name of the storage account below to store the custom script\"\n\techo \"scriptstorageaccount:\"\n\tread scriptstorageaccount\nfi\n\n#templateFile Path - template file to be used\ntemplateFilePath=\"azuredeploy.json\"\n\n#parameter file path\nparametersFilePath=\"azuredeploy.parameters.json\"\n\nif  [ -z \"$resourceGroupName\" ] || [ -z \"$scriptstorageaccount\" ]; then\n\techo \"Either one of subscriptionId, resourceGroupName, deploymentName, scriptstorageaccount is empty\"\n\tusage\nfi\n\n#login to azure using your credentials\n#azure login\n\n#set the default subscription id\n#azure account set $subscriptionId\n\n#switch the mode to azure resource manager\nazure config mode arm\n\n#Check for existing resource group\nif [ -z \"$resourceGroupLocation\" ] ;\nthen\n\techo \"Using existing resource group...\"\nelse\n\techo \"Creating a new resource group...\"\n\tazure group create --name $resourceGroupName --location $resourceGroupLocation\nfi\n\nstagecustomscript\n\ncp ./azuredeploy.parameters.json.template ./azuredeploy.parameters.json\n\nsed -i 's/REPLACE_SCRIPTSTORAGERG/'$resourceGroupName'/g' ./azuredeploy.parameters.json\nsed -i 's/REPLACE_SCRIPTSTORAGE/'$scriptstorageaccount'/g' ./azuredeploy.parameters.json\n\nazure config mode arm\n\n#Start deployment\necho \"Starting deployment...\"\nazure group deployment create --resource-group $resourceGroupName --template-file $templateFilePath --parameters-file $parametersFilePath\n", "num_lines": 105}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n#set -e\n\nusage()\n{\n    echo usage: keyvault.sh '<keyvaultname> <resource group name> <location> <secretname> <certpemfile> <keypemfile> <cacertpemfile>'\n    echo The cacertpem file is optional. The template will accept a self-signed cert and key.\n}\n\ncreategroup()\n{\n\n    azure group show $rgname 2> /dev/null\n    if [ $? -eq 0 ]\n    then\n        echo Resource Group $rgname already exists. Skipping creation.\n    else\n        # Create a resource group for the keyvault\n        azure group create -n $rgname -l $location\n    fi\n\n}\n\ncreatekeyvault()\n{\n\n    azure keyvault show $vaultname 2> /dev/null\n    if [ $? -eq 0 ]\n    then\n        echo Key Vault $vaultname already exists. Skipping creation.\n    else\n        echo Creating Key Vault $vaultname.\n\n        creategroup\n        # Create the key vault\n        azure keyvault create --vault-name $vaultname --resource-group $rgname --location $location\n    fi\n\n    azure keyvault set-policy -u $vaultname -g $rgname --enabled-for-template-deployment true --enabled-for-deployment true\n\n}\n\nconvertcert()\n{\n    local cert=$1\n    local key=$2\n    local pfxfile=$3\n    local pass=$4\n\n    echo Creating PFX $pfxfile\n    openssl pkcs12 -export -out $pfxfile -inkey $key -in $cert -password pass:$pass 2> /dev/null\n    if [ $? -eq 1 ]\n    then\n        echo problem converting $key and $cert to pfx\n        exit 1\n    fi\n\n    fingerprint=$(openssl x509 -in $cert -noout -fingerprint | cut -d= -f2 | sed 's/://g' )\n}\n\nconvertcacert()\n{\n    local cert=$1\n    local pfxfile=$2\n    local pass=$3\n\n    echo Creating PFX $pfxfile\n    openssl pkcs12 -export -out $pfxfile -nokeys -in $cert -password pass:$pass 2> /dev/null\n    if [ $? -eq 1 ]\n    then\n        echo problem converting $cert to pfx\n        exit 1\n    fi\n\n    fingerprint=$(openssl x509 -in $cert -noout -fingerprint | cut -d= -f2 | sed 's/://g' )\n}\n\nstoresecret()\n{\n    local secretfile=$1\n    local name=$2\n    filecontentencoded=$( cat $secretfile | base64 $base64_unwrap )\n\njson=$(cat << EOF\n{\n\"data\": \"${filecontentencoded}\",\n\"dataType\" :\"pfx\",\n\"password\": \"${pwd}\"\n}\nEOF\n)\n\n    jsonEncoded=$( echo $json | base64 $base64_unwrap )\n\n    r=$(azure keyvault secret set --vault-name $vaultname --secret-name $name --value $jsonEncoded)\n    if [ $? -eq 1 ]\n    then\n        echo problem storing secret $name in $vaultname\n        exit 1\n    fi\n\n    id=$(echo $r | grep -o 'https:\\/\\/[a-z0-9.]*/secrets\\/[a-z0-9]*/[a-z0-9]*')\n    echo Secret ID is $id\n}\n\n# We need exactly 7 parameters\nif [ \"$#\" -lt 6 ]; then\n    usage\n    exit\nfi\n\n# The base64 command on OSX does not know about the -w parameter, but outputs unwrapped base64 by default\nbase64_unwrap=\"-w 0\"\n[[ $(uname) == \"Darwin\" ]] && base64_unwrap=\"\"\n\nvaultname=$1\nrgname=$2\nlocation=$3\nsecretname=$4\ncertfile=$5\nkeyfile=$6\ncacertfile=$7\n\n# Create a random password with 33 bytes of entropy\n# I picked 33 so the last character will not be =\npwd=$(dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64)\n\ncertpfxfile=${certfile%.*crt}.pfx\ncacertpfxfile=${cacertfile%.*crt}.pfx\ncasecretname=ca$secretname\n\ncreatekeyvault\n\n# converting SSL cert to pfx\nconvertcert $certfile $keyfile $certpfxfile $pwd\ncertprint=$fingerprint\necho $certpfxfile fingerprint is $fingerprint\n# storing pfx in keyvault\necho Storing $certpfxfile as $secretname\nstoresecret $certpfxfile $secretname\ncertid=$id\nrm -f $certpfxfile\n\nif [ ! -z $cacertfile ]\nthen\n    # converting CA cert to pfx\n    convertcacert $cacertfile $cacertpfxfile $pwd\n    echo $cacertpfxfile fingerprint is $fingerprint\n    cacertprint=$fingerprint\n    # storing pfx in key vault\n    echo Storing $cacertpfxfile as $casecretname\n    storesecret $cacertpfxfile $casecretname\n    cacertid=$id\n    rm -f $cacertpfxfile\nfi\n\n# update parameters file\nsed -e 's|REPLACE_CERTURL|'$certid'|g' \\\n    -e 's|REPLACE_CACERTURL|'$cacertid'|g' \\\n    -e 's/REPLACE_CERTPRINT/'$certprint'/g' \\\n    -e 's/REPLACE_CACERTPRINT/'$cacertprint'/g' \\\n    -e 's/REPLACE_VAULTNAME/'$vaultname'/g' \\\n    -e 's/REPLACE_VAULTRG/'$rgname'/g' \\\n    azuredeploy.parameters.json.template >azuredeploy.parameters.json\n\necho Done\n", "num_lines": 168}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Configure mongodb.list file with the correct location\nsudo apt-get -y update\nsudo apt-get install -y gnupg\nwget -qO - https://www.mongodb.org/static/pgp/server-4.4.asc | sudo apt-key add -\necho \"deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu bionic/mongodb-org/4.4 multiverse\" | sudo tee /etc/apt/sources.list.d/mongodb-org-4.4.list", "num_lines": 5}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Install updates\nsudo apt-get -y update\n\n#Install Mongo DB\necho  \"sudo apt-get install -y mongodb-org\"\n", "num_lines": 6}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\necho \"line 1***\"\nsudo apt-get update \necho \"line 2***\"\nsudo apt-get install default-jre -y\necho \"line 3***\"\nwget -qO - https://artifacts.elastic.co/GPG-KEY-elasticsearch | sudo apt-key add -\necho \"line 4***\"\necho \"deb https://artifacts.elastic.co/packages/5.x/apt stable main\" | sudo tee -a /etc/apt/sources.list.d/elastic-5.x.list\necho \"line 5***\"\nexport JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64\necho \"line 6***\"\nsudo apt update && sudo apt install elasticsearch kibana logstash\necho \"line 7***\"\nsudo systemctl start elasticsearch.service\necho \"line 8***\"\nsudo systemctl start elasticsearch.service\necho \"line 9***\"\nsudo systemctl enable elasticsearch.service\necho \"line 10***\"\nsudo curl -XGET 'localhost:9200/'\necho \"line 11***\"\nsudo systemctl start logstash.service\necho \"line 12***\"\nsudo systemctl start kibana.service\necho \"line 13***\"\nsudo systemctl enable kibana.service\necho \"line 14***\"\nsudo cp /etc/elasticsearch/elasticsearch.yml /etc/elasticsearch/elasticsearch_old.yml\necho \"line 15***\"\nsudo echo \"network.host: 0.0.0.0\" >> /etc/elasticsearch/elasticsearch.yml \necho \"line 16***\"\nsudo systemctl restart elasticsearch.service\necho \"line 17***\"\nsudo systemctl start elasticsearch.service\necho \"line 18***\"\nsudo systemctl enable elasticsearch.service\necho \"line 19***\"\nsudo cp /etc/kibana/kibana.yml /etc/kibana/kibana_old.yml\necho \"line 19***\"\nprop='server.host: '\nvalue='0.0.0.0'\nsudo echo $prop$value >> /etc/kibana/kibana.yml \necho \"line 20***\"\nsudo systemctl restart kibana.service\necho \"line 21***\"\nsudo systemctl start kibana.service\necho \"line 22***\"\nsudo systemctl enable kibana.service\necho \"line 23***\"\nsudo mkdir /home/azure\ncd /home/azure\nwget http://dist.neo4j.org/neo4j-community-3.4.1-unix.tar.gz\nsudo tar -xvzf neo4j-community-3.4.1-unix.tar.gz\nsudo echo \"dbms.connector.https.listen_address=0.0.0.0:7473\" >> /home/azure/neo4j-community-3.4.1/conf/neo4j.conf\nsudo echo \"dbms.connector.http.listen_address=0.0.0.0:7474\" >> /home/azure/neo4j-community-3.4.1/conf/neo4j.conf\nsudo echo \"dbms.connector.https.listen_address=0.0.0.0:7473\" >> /home/azure/neo4j-community-3.4.1/conf/neo4j.conf\nsudo echo \"dbms.connector.bolt.listen_address=0.0.0.0:7687\" >> /home/azure/neo4j-community-3.4.1/conf/neo4j.conf\ncd /home/azure/neo4j-community-3.4.1/bin\nsudo ./neo4j start\nsudo cd /home/azure/neo4j-community-3.4.1/\nsudo cd data/dbms/\nsudo rm auth\nsudo /home/azure/neo4j-community-3.4.1/bin/neo4j-admin set-initial-password qwerty\nsudo ./neo4j restart\n", "num_lines": 66}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\neventHubsNamespaceEndpoint=$1\nblobServicePrimaryEndpoint=$2\n\n# Parameters validation\nif [[ -z $eventHubsNamespaceEndpoint ]]; then\n    echo \"eventHubsNamespaceEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\n# Eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Run nslookup to verify that public hostname of the Service Bus namespace\n# is properly mapped to the private address of the provate endpoint\nnslookup $eventHubsNamespaceEndpoint\n\n# Run nslookup to verify that public hostname of the Blob storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $blobServicePrimaryEndpoint", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -o errexit\nset -o xtrace\n\n# Install jq\ndpkg -s jq || sudo apt-get install -y jq\n\n# Install Confluent platform (includes Kafka schema registry)\nwget -qO - http://packages.confluent.io/deb/4.1/archive.key | sudo apt-key add -\nsudo add-apt-repository \"deb http://packages.confluent.io/deb/4.1 stable main\"\nsudo apt-get update\ndpkg -s confluent-platform-oss-2.11 || sudo apt-get install -y confluent-platform-oss-2.11\n\necho \"[Unit]\nDescription = Confluent Schema Registry\nAfter = network.target\nStartLimitIntervalSec=0\n\n[Service]\nType=simple\nRestart=always\nRestartSec=1\nUser=ohklvmadmin\nExecStart=/usr/bin/schema-registry-start /etc/schema-registry/schema-registry.properties\n\n[Install]\nWantedBy=multi-user.target\n\" > /etc/systemd/system/schema-registry.service\n\necho \"\nlisteners=http://0.0.0.0:8081\nkafkastore.connection.url=zk0-ohkl-h:2181,zk1-ohkl-h:2181,zk2-ohkl-h:2181\nkafkastore.topic=_schemas\ndebug=false\n\" > /etc/schema-registry/schema-registry.properties\n\nsystemctl start schema-registry\nsystemctl enable schema-registry\n\necho \"Installation successful.\"\n", "num_lines": 41}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\necho \"Empty node setup\"\n", "num_lines": 3}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#! /bin/bash\necho \"Empty node setup\"\n", "num_lines": 3}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\nkeyVaultServiceEndpoint=$1\nblobServicePrimaryEndpoint=$2\nazureEnvironment=$3\n\n# Parameter validation\nif [[ -z $keyVaultServiceEndpoint ]]; then\n    echo \"keyVaultServiceEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"keyVaultServiceEndpoint: $keyVaultServiceEndpoint\"\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"blobServicePrimaryEndpoint: $blobServicePrimaryEndpoint\"\nfi\n\nif [[ -z $azureEnvironment ]]; then\n    echo \"azureEnvironment cannot be null or empty\"\n    exit 1\nelse\n    echo \"azureEnvironment: $keyVaultServiceEndpoint\"\nfi\n\n# Extract the key vault name from the adls service primary endpoint\nkeyVaultName=$(echo \"$keyVaultServiceEndpoint\" | awk -F'.' '{print $1}')\n\nif [[ -z $keyVaultName ]]; then\n    echo \"keyVaultName cannot be null or empty\"\n    exit 1\nelse\n    echo \"keyVaultName: $keyVaultName\"\nfi\n\n# Eliminate debconf: warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Install jq\nsudo apt-get install -y --fix-missing jq\n\n# Install curl and traceroute\nsudo apt install -y curl traceroute\n\n# Install Azure CLI\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Run nslookup to verify that public hostname of the Key Vault resource\n# is properly mapped to the private address of the provate endpoint\nnslookup $keyVaultServiceEndpoint\n\n# Run nslookup to verify that public hostname of the Blob storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $blobServicePrimaryEndpoint\n\n# Set cloud environment\nif [[ ${azureEnvironment,,} == 'azureusgovernment' ]]; then\n    az cloud set --name AzureUSGovernment\nfi\n\n# Login using the virtual machine system-assigned managed identity\naz login --identity --allow-no-subscriptions\n\n# Retrieve the list of secrets\n\n# Create Event Hub subscription\naz keyvault secret list --vault-name $keyVaultName", "num_lines": 77}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\nset -e\n\n# Download and install Helm\nwget -O helm.tgz https://get.helm.sh/helm-v3.4.1-linux-amd64.tar.gz\ntar -zxvf helm.tgz\nmv linux-amd64/helm /usr/local/bin/helm\n# Install kubectl\naz aks install-cli\n\n# Get cluster credentials\naz aks get-credentials -g $RESOURCEGROUP -n $CLUSTER_NAME\n\n# Install Simple Helm Chart https://github.com/bitnami/azure-marketplace-charts\n\nhelm repo add \\\n    $HELM_REPO \\\n    $HELM_REPO_URL\n\nhelm search repo \\\n    $HELM_REPO\n\nhelm install \\\n    $HELM_APP_NAME \\\n    $HELM_APP \\\n    --set global.imagePullSecrets={emptysecret}\n\necho \\{\\\"Status\\\":\\\"Complete\\\"\\} > $AZ_SCRIPTS_OUTPUT_PATH\n", "num_lines": 29}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n##########################################################################\n##  1- Name of resource group\n\nrg=$1\n\necho \"Resource group:  $rg\"\n\necho\necho \"Deploying ARM template\"\n\naz deployment group create -n \"deploy-$(uuidgen)\" -g vp-cosmos-arm3 \\\n    --template-file main.bicep\n", "num_lines": 15}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "sudo yum install epel-release -y\nsudo yum install nginx -y\nsudo sed -i \"/        <title>Test Page for the Nginx HTTP Server on EPEL<\\/title>/c\\<title>Test Page for the Nginx HTTP Server on EPEL - ${HOSTNAME}<\\/title>\" /usr/share/nginx/html/index.html\nsudo sed -i \"/        <h1>Welcome to <strong>nginx<\\/strong> on EPEL\\!<\\/h1>/c\\        <h1>Welcome to <strong>nginx<\\/strong> on EPEL\\! ${HOSTNAME}<\\/h1>\" /usr/share/nginx/html/index.html\nsudo chkconfig nginx on\nsudo /etc/init.d/nginx start\n", "num_lines": 7}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\napt-get update -y && apt-get upgrade -y\napt-get install -y nginx\necho \"Hello World from host\" $HOSTNAME \"!\" | sudo tee -a /var/www/html/index.html\n\ntouch /etc/nginx/nginx.conf\ncat >> /etc/nginx/nginx.conf <<EOF\nstream {\n      upstream dns_servers {\n       server 168.63.129.16:53;\n}\n\nserver {\n listen x.x.x.x:53  udp;\n listen x.x.x.x:53; #tcp\n proxy_pass dns_servers;\n proxy_responses 1;\n error_log  /var/log/nginx/dns.log info;\n}\n}\nEOF\n\nmyip=`hostname -i | awk '{print $1}'`\nsed -i \"s/x.x.x.x/$myip/\" /etc/nginx/nginx.conf\n\n\nsudo nginx -t && sudo service nginx reload", "num_lines": 50}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2021 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n\n# Variables\nprivateDnsZoneName=$1\nvmName1=$2\nvmName2=$3\nadlsServicePrimaryEndpoint=$4\nblobServicePrimaryEndpoint=$5\nfileSystemName=${HOSTNAME,,}\ndirectoryName=\"documents\"\nfileName=\"${HOSTNAME,,}.txt\"\nfileContent=\"This file was written by the $HOSTNAME virtual machine via a private endpoint.\"\n\n# Parameter validation\nif [[ -z $privateDnsZoneName ]]; then\n    echo \"privateDnsZoneName cannot be null or empty\"\n    exit 1\nelse\n    echo \"privateDnsZoneName        : $privateDnsZoneName\"\nfi\n\nif [[ -z $vmName1 ]]; then\n    echo \"vmName1 cannot be null or empty\"\n    exit 1\nelse\n    echo \"vmName1                   : $vmName1\"\nfi\n\nif [[ -z $vmName2 ]]; then\n    echo \"vmName2 cannot be null or empty\"\n    exit 1\nelse\n    echo \"vmName2                   : $vmName2\"\nfi\n\nif [[ -z $adlsServicePrimaryEndpoint ]]; then\n    echo \"adlsServicePrimaryEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"adlsServicePrimaryEndpoint: $adlsServicePrimaryEndpoint\"\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint cannot be null or empty\"\n    exit 1\nelse\n    echo \"blobServicePrimaryEndpoint: $blobServicePrimaryEndpoint\"\nfi\n\nif [[ -z $fileSystemName ]]; then\n    echo \"fileSystemName parameter cannot be null or empty\"\n    exit 1\nelse\n    echo \"fileSystemName            : $fileSystemName\"\nfi\n\nif [[ -z $directoryName ]]; then\n    echo \"directoryName parameter cannot be null or empty\"\n    exit 1\nelse\n    echo \"directoryName             : $directoryName\"\nfi\n\n# Extract the adls storage account name from the adls service primary endpoint\n# Note: when using the Azure CLI, you have to use both a blob and adls private endpoint\n# because under the cover the tool uses calls to the blob REST API\nstorageAccountName=$(echo \"$adlsServicePrimaryEndpoint\" | awk -F'.' '{print $1}')\n\nif [[ -z $storageAccountName ]]; then\n    echo \"storageAccountName cannot be null or empty\"\n    exit 1\nelse\n    echo \"storageAccountName: $storageAccountName\"\nfi\n\n# Eliminate debconf: warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Install NGINX web server\nsudo apt-get install -y nginx\n\n# Change the default page of the NGINX web server\nsudo echo \"This is [$HOSTNAME] virtual machine\" > /var/www/html/index.html\n\n# Install curl and traceroute\nsudo apt-get install -y curl traceroute\n\n# Install Azure CLI\ncurl -sL https://aka.ms/InstallAzureCLIDeb | sudo bash\n\n# Run nslookup to verify that the <vm-name-1>.<private-dns-zone-name> is resolved to the private IP address of the first virtual machine\necho \"nslookup ${vmName1,,}.$privateDnsZoneName\"\nnslookup ${vmName1,,}.$privateDnsZoneName\n\n# Call the NGINX web server on the first virtual machine\necho \"curl http://${vmName1,,}.$privateDnsZoneName\"\ncurl http://${vmName1,,}.$privateDnsZoneName\n\n# Run nslookup to verify that the <vm-name-2>.<private-dns-zone-name> is resolved to the private IP address of the second virtual machine\necho \"nslookup ${vmName2,,}.$privateDnsZoneName\"\nnslookup ${vmName2,,}.$privateDnsZoneName\n\n# Call the NGINX web server on the second virtual machine\necho \"curl http://${vmName2,,}.$privateDnsZoneName\"\ncurl http://${vmName2,,}.$privateDnsZoneName\n\n# Run nslookup to verify that the <storage-account>.dfs.core.windows.net public hostname of the storage account\n# is properly mapped to <storage-account>.privatelink.dfs.core.windows.net by the privatelink.dfs.core.windows.net\n# private DNS zone and the latter is resolved to the private address by the A record\necho \"nslookup $adlsServicePrimaryEndpoint\"\nnslookup $adlsServicePrimaryEndpoint\n\n# Run nslookup to verify that the <storage-account>.blob.core.windows.net public hostname of the storage account\n# is properly mapped to <storage-account>.privatelink.blob.core.windows.net by the privatelink.blob.core.windows.net\n# private DNS zone and the latter is resolved to the private address by the A record\necho \"nslookup $blobServicePrimaryEndpoint\"\nnslookup $blobServicePrimaryEndpoint\n\n# Login using the virtual machine system-assigned managed identity\naz login --identity\n\n# Create file system for the Azure Data Lake Storage Gen2 account\necho \"Checking if the $fileSystemName file system already exists in the $storageAccountName storage account...\"\nname=$(az storage fs show \\\n    --name $fileSystemName \\\n    --account-name $storageAccountName \\\n    --auth-mode login \\\n    --query name \\\n    --output tsv 2>/dev/null)\n\nif [[ -z $name ]]; then\n    echo \"The $fileSystemName file system does not exist in the $storageAccountName storage account\"\n    echo \"Creating the $fileSystemName file system in the $storageAccountName storage account...\"\n\n    az storage fs create \\\n        --name $fileSystemName \\\n        --account-name $storageAccountName \\\n        --auth-mode login\n\n    if [[ $? == 0 ]]; then\n        echo \"The $fileSystemName file system was successfully created in the $storageAccountName storage account\"\n    else\n        echo \"Failed to create the $fileSystemName file system in the $storageAccountName storage account\"\n        exit\n    fi\nelse\n    echo \"The $fileSystemName file system already exists in the $storageAccountName storage account\"\nfi\n\n# Create a directory in the ADLS Gen2 file system\necho \"Checking if the $directoryName directory exists in the $fileSystemName file system under the $storageAccountName storage account...\"\nname=$(az storage fs directory show \\\n    --file-system $fileSystemName \\\n    --name $directoryName \\\n    --account-name $storageAccountName \\\n    --auth-mode login \\\n    --query name \\\n    --output tsv 2>/dev/null)\n\nif [[ -z $name ]]; then\n    echo \"The $directoryName directory does not exist in the $fileSystemName file system under the $storageAccountName storage account\"\n    echo \"Creating the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\n\n    az storage fs directory create \\\n        --file-system $fileSystemName \\\n        --name $directoryName \\\n        --account-name $storageAccountName \\\n        --auth-mode login\n\n    if [[ $? == 0 ]]; then\n        echo \"The directoryName directory was successfully created in the $fileSystemName file system under the $storageAccountName storage account\"\n    else\n        echo \"Failed to create the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\n        exit\n    fi\nelse\n    echo \"The $directoryName directory already exists in the $fileSystemName file system under the $storageAccountName storage account\"\nfi\n\n# Create a file to upload to the ADLS Gen2 file system in the storage account\necho \"$fileContent\" >$fileName\n\n# Upload the file to a file path in ADLS Gen2 file system.\necho \"Uploading the $filename file to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\naz storage fs file upload \\\n    --file-system $fileSystemName \\\n    --path \"$directoryName/$fileName\" \\\n    --source \"./$fileName\" \\\n    --account-name $storageAccountName \\\n    --overwrite true \\\n    --auth-mode login\n\nif [[ $? == 0 ]]; then\n    echo \"The $filename file was successfully uploaded to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\nelse\n    echo \"Failed to upload the $filename file to the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account\"\n    exit\nfi\n\n# List files and directories in the directory in the ADLS Gen2 file system.\necho \"Listing the files inside the $directoryName directory in the $fileSystemName file system under the $storageAccountName storage account...\"\naz storage fs file list \\\n    --file-system $fileSystemName \\\n    --path $directoryName \\\n    --account-name $storageAccountName \\\n    --auth-mode login\n", "num_lines": 235}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n## NOTE:\n## before running the script, customize the values of variables suitable for your deployment. \n## asn_quagga: Autonomous system number assigned to quagga\n## bgp_routerId: IP address of quagga VM\n## bgp_network1: first network advertised from quagga to the router server (inclusive of subnetmask)\n## bgp_network2: second network advertised from quagga to the router server (inclusive of subnetmask)\n## bgp_network3: third network advertised from quagga to the router server (inclusive of subnetmask)\n## routeserver_IP1: first IP address of the router server \n## routeserver_IP2: second IP address of the router server\n\nasn_quagga=65001\nbgp_routerId=10.1.4.10\nbgp_network1=10.100.1.0/24\nbgp_network2=10.100.2.0/24\nbgp_network3=10.100.3.0/24\nrouteserver_IP1=10.1.1.4\nrouteserver_IP2=10.1.1.5\n\n\nsudo apt-get -y update\n\n## Install the Quagga routing daemon\necho \"Installing quagga\"\nsudo apt-get -y install quagga\n\n##  run the updates and ensure the packages are up to date and there is no new version available for the packages\nsudo apt-get -y update --fix-missing\n\n## Enable IPv4 forwarding\necho \"net.ipv4.conf.all.forwarding=1\" | sudo tee -a /etc/sysctl.conf \necho \"net.ipv4.conf.default.forwarding=1\" | sudo tee -a /etc/sysctl.conf \nsysctl -p\n\n## Create a folder for the quagga logs\necho \"creating folder for quagga logs\"\nsudo mkdir -p /var/log/quagga && sudo chown quagga:quagga /var/log/quagga\nsudo touch /var/log/zebra.log\nsudo chown quagga:quagga /var/log/zebra.log\n\n## Create the configuration files for Quagga daemon\necho \"creating empty quagga config files\"\nsudo touch /etc/quagga/babeld.conf\nsudo touch /etc/quagga/bgpd.conf\nsudo touch /etc/quagga/isisd.conf\nsudo touch /etc/quagga/ospf6d.conf\nsudo touch /etc/quagga/ospfd.conf\nsudo touch /etc/quagga/ripd.conf\nsudo touch /etc/quagga/ripngd.conf\nsudo touch /etc/quagga/vtysh.conf\nsudo touch /etc/quagga/zebra.conf\n\n## Change the ownership and permission for configuration files, under /etc/quagga folder\necho \"assign to quagga user the ownership of config files\"\nsudo chown quagga:quagga /etc/quagga/babeld.conf && sudo chmod 640 /etc/quagga/babeld.conf\nsudo chown quagga:quagga /etc/quagga/bgpd.conf && sudo chmod 640 /etc/quagga/bgpd.conf\nsudo chown quagga:quagga /etc/quagga/isisd.conf && sudo chmod 640 /etc/quagga/isisd.conf\nsudo chown quagga:quagga /etc/quagga/ospf6d.conf && sudo chmod 640 /etc/quagga/ospf6d.conf\nsudo chown quagga:quagga /etc/quagga/ospfd.conf && sudo chmod 640 /etc/quagga/ospfd.conf\nsudo chown quagga:quagga /etc/quagga/ripd.conf && sudo chmod 640 /etc/quagga/ripd.conf\nsudo chown quagga:quagga /etc/quagga/ripngd.conf && sudo chmod 640 /etc/quagga/ripngd.conf\nsudo chown quagga:quaggavty /etc/quagga/vtysh.conf && sudo chmod 660 /etc/quagga/vtysh.conf\nsudo chown quagga:quagga /etc/quagga/zebra.conf && sudo chmod 640 /etc/quagga/zebra.conf\n\n## initial startup configuration for Quagga daemons are required\necho \"Setting up daemon startup config\"\necho 'zebra=yes' > /etc/quagga/daemons\necho 'bgpd=yes' >> /etc/quagga/daemons\necho 'ospfd=no' >> /etc/quagga/daemons\necho 'ospf6d=no' >> /etc/quagga/daemons\necho 'ripd=no' >> /etc/quagga/daemons\necho 'ripngd=no' >> /etc/quagga/daemons\necho 'isisd=no' >> /etc/quagga/daemons\necho 'babeld=no' >> /etc/quagga/daemons\n\necho \"add zebra config\"\ncat <<EOF > /etc/quagga/zebra.conf\n!\ninterface eth0\n!\ninterface lo\n!\nip forwarding\n!\nline vty\n!\nEOF\n\n\necho \"add quagga config\"\ncat <<EOF > /etc/quagga/bgpd.conf\n!\nrouter bgp $asn_quagga\n bgp router-id $bgp_routerId\n network $bgp_network1\n network $bgp_network2\n network $bgp_network3\n neighbor $routeserver_IP1 remote-as 65515\n neighbor $routeserver_IP1 soft-reconfiguration inbound\n neighbor $routeserver_IP2 remote-as 65515\n neighbor $routeserver_IP2 soft-reconfiguration inbound\n!\n address-family ipv6\n exit-address-family\n exit\n!\nline vty\n!\nEOF\n\n## to start daemons at system startup\necho \"enable zebra and quagga daemons at system startup\"\nsystemctl enable zebra.service\nsystemctl enable bgpd.service\n\n## run the daemons\necho \"start zebra and quagga daemons\"\nsystemctl start zebra \nsystemctl start bgpd  ", "num_lines": 120}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Cleanup\necho \"* Cleanup...\"\ndpkg --configure -a\napt-get install -f\n\n# Upgrade\necho \"* Upgrade..\"\napt-get -y update\napt-get -y dist-upgrade\n\n# Install Apache2\necho \"* Install Apache...\"\napt-get remove apache*\napt-get -y install apache2\n\n# Restart Apache\necho \"* Restart Apache...\"\napachectl restart\n\necho \"* Finished!\"", "num_lines": 22}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "# Create the Azure AD application.\napplication=$(az ad app create --display-name $AzureADApplicationName)\napplicationObjectId=$(jq -r '.id' <<< \"$application\")\napplicationClientId=$(jq -r '.appId' <<< \"$application\")\n\n# Create a service principal for the application.\nservicePrincipal=$(az ad sp create --id $applicationObjectId)\nservicePrincipalObjectId=$(jq -r '.id' <<< \"$servicePrincipal\")\n\n# Save the important properties as depoyment script outputs.\noutputJson=$(jq -n \\\n                --arg applicationObjectId \"$applicationObjectId\" \\\n                --arg applicationClientId \"$applicationClientId\" \\\n                --arg servicePrincipalObjectId \"$servicePrincipalObjectId\" \\\n                '{applicationObjectId: $applicationObjectId, applicationClientId: $applicationClientId, servicePrincipalObjectId: $servicePrincipalObjectId}' )\necho $outputJson > $AZ_SCRIPTS_OUTPUT_PATH\n", "num_lines": 17}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#/bin/bash -e\npassphrase=$1\n\necho -e 'y' | ssh-keygen -f scratch -N \"$passphrase\" \n\nprivateKey=$(cat scratch)\npublicKey=$(cat 'scratch.pub')\n\njson=\"{\\\"keyinfo\\\":{\\\"privateKey\\\":\\\"$privateKey\\\",\\\"publicKey\\\":\\\"$publicKey\\\"}}\"\n\necho \"$json\" > $AZ_SCRIPTS_OUTPUT_PATH\n", "num_lines": 12}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\nserviceBusNamespaceEndpoint=$1\nblobServicePrimaryEndpoint=$2\n\n# Parameters validation\nif [[ -z $serviceBusNamespaceEndpoint ]]; then\n    echo \"serviceBusNamespaceEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\n# Eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Run nslookup to verify that public hostname of the Service Bus namespace\n# is properly mapped to the private address of the provate endpoint\nnslookup $serviceBusNamespaceEndpoint\n\n# Run nslookup to verify that public hostname of the Blob storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $blobServicePrimaryEndpoint", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\nadlsServicePrimaryEndpoint=$1\nblobServicePrimaryEndpoint=$2\n\n# Parameters validation\nif [[ -z $adlsServicePrimaryEndpoint ]]; then\n    echo \"adlsServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\n# Eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Run nslookup to verify that public hostname of the ADLS Gen 2 storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $adlsServicePrimaryEndpoint\n\n# Run nslookup to verify that public hostname of the Blob storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $blobServicePrimaryEndpoint", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Variables\nfileServicePrimaryEndpoint=$1\nblobServicePrimaryEndpoint=$2\n\n# Parameters validation\nif [[ -z $fileServicePrimaryEndpoint ]]; then\n    echo \"fileServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\nif [[ -z $blobServicePrimaryEndpoint ]]; then\n    echo \"blobServicePrimaryEndpoint parameter cannot be null or empty\"\n    exit 1\nfi\n\n# Eliminate debconf warnings\necho 'debconf debconf/frontend select Noninteractive' | debconf-set-selections\n\n# Update the system\nsudo apt-get update -y\n\n# Upgrade packages\nsudo apt-get upgrade -y\n\n# Run nslookup to verify that public hostname of the Service Bus namespace\n# is properly mapped to the private address of the provate endpoint\nnslookup $fileServicePrimaryEndpoint\n\n# Run nslookup to verify that public hostname of the Blob storage account \n# is properly mapped to the private address of the provate endpoint\nnslookup $blobServicePrimaryEndpoint", "num_lines": 33}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nCUSTOM_DOMAIN=$1\n\nif [[ -z $CUSTOM_DOMAIN ]]\nthen  \n    echo \"Parameters missing.\"\n    echo \"Usage: create-certificates.sh custom_domain\"\n    echo \"Try: create-certificates.sh *.contoso.net\"\n    exit\nfi\n\ncreate_server_cert () {\n    echo \"Creating server certificate for $CUSTOM_DOMAIN.\"\n\n    EXTENSION_CONFIGURATION=\"subjectAltName=DNS:$CUSTOM_DOMAIN\"\n\n    # Create the certificate's key\n    openssl ecparam -out domain.key -name prime256v1 -genkey\n\n    # Create the CSR (Certificate Signing Request)\n    openssl req -new -sha256 -key domain.key -out domain.csr -subj \"/CN=$CUSTOM_DOMAIN\" -addext \"subjectAltName=DNS:$CUSTOM_DOMAIN\" --passin file:pass\n\n    # NOTE: The 'openssl x509' (v1.1.1 - https://www.openssl.org/docs/man1.1.1/man1/openssl-x509.html) currently doesn't support\n    #       the '-addext' option.  Thus, need to specify the Subject Alternative Name via configuration.\n    #       Instead of providing a configuration file with this sample, the 'subjectAlName' extension is added via a 'printf' statement.\n    #       An alternative is to create an extension file with the necessary extensions and provide the path to the extension file.\n    #       openssl x509 -req -days 365 -sha256 -in domain.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out domain.crt -extfile ../domain.ext\n    #\n    #       Extension file sample:\n    #       subjectAltName = DNS:*.contoso.net\n\n    # Generate the certificate with the CSR and the key and sign it with the CA's root key\n    openssl x509 -req -days 365 -sha256 -in domain.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -out domain.crt -extfile <(printf '%s' \"$EXTENSION_CONFIGURATION\")\n\n    # Export PFX file\n    openssl pkcs12 -export -out domain.pfx -inkey domain.key -in domain.crt -password file:pass\n\n    # Base64 encode PFX\n    base64 -w 0 domain.pfx > domain.pfx.txt\n}\n\ncreate_root_CA_cert () {\n    echo \"Creating root CA certificate.\"\n\n    # Create a root CA certificate\n    # Create the root key\n    openssl ecparam -out rootCA.key -name prime256v1 -genkey\n\n    # Create a Root Certificate and self-sign it\n    # Generate the CSR (Certificate Signing Request)\n    openssl req -new -sha256 -key rootCA.key -out rootCA.csr -subj \"/CN=Azure Quickstarts Sample CA\" --passin file:pass\n    \n    openssl x509 -req -sha256 -days 365 -in rootCA.csr -signkey rootCA.key -out rootCA.crt\n\n    # Base64 encode CRT\n    base64 -w 0 rootCA.crt > rootCA.crt.txt\n}\n\n# Create a new directory for the certificates\nmkdir -p .certs\ncd .certs || exit\n\n# Create password; same password is used for all certs\nopenssl rand -hex 16 > pass\n\n# Create root CA certificate\ncreate_root_CA_cert\n\n# Create server certificates\ncreate_server_cert", "num_lines": 71}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script Name: afs-utils.sh\n# Author: Hans Krijger (github:hglkrijger)\n# Version: 0.1\n# Last Modified By: Hans Krijger\n# Description:\n#  This script provides basic functionality for creating and mounting an Azure\n#  File Service share for use by Elasticsearch.\n# Note:\n# This script has only been tested on Ubuntu 14.04 LTS and must be root\n\nhelp()\n{\n    echo \"Usage: $(basename $0) -a storage_account -k access_key [-h] [-c] [-p] [-s share_name] [-b base_directory]\"\n    echo \"Options:\"\n    echo \"  -a    storage account which hosts the shares (required)\"\n    echo \"  -k    access key for the storage account (required)\"\n    echo \"  -h    this help message\"\n    echo \"  -c    create and mount afs share\"\n    echo \"  -p    persist the mount (default: non persistent)\"\n    echo \"  -s    name of the share (default: esdata00)\"\n    echo \"  -b    base directory for mount points (default: /sharedfs)\"\n}\n\nerror()\n{\n    echo \"$1\" >&2\n    exit 3\n}\n\nlog()\n{\n    echo \"$1\"\n}\n\n# issue_signed_request\n#   <verb> - GET/PUT/POST\n#   <url> - the resource uri to actually post\n#   <canonical resource> - the canonicalized resource uri\n# see https://msdn.microsoft.com/en-us/library/azure/dd179428.aspx for details\nissue_signed_request() {\n    request_method=\"$1\"\n    request_url=\"$2\"\n    canonicalized_resource=\"/${STORAGE_ACCOUNT}/$3\"\n\n    request_date=$(TZ=GMT date \"+%a, %d %h %Y %H:%M:%S %Z\")\n    storage_service_version=\"2015-04-05\"\n    authorization=\"SharedKey\"\n    file_store_url=\"file.core.windows.net\"\n    full_url=\"https://${STORAGE_ACCOUNT}.${file_store_url}/${request_url}\"\n\n    x_ms_date_h=\"x-ms-date:$request_date\"\n    x_ms_version_h=\"x-ms-version:$storage_service_version\"\n    canonicalized_headers=\"${x_ms_date_h}\\n${x_ms_version_h}\\n\"\n    content_length_header=\"Content-Length:0\"\n\n    string_to_sign=\"${request_method}\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n${canonicalized_headers}${canonicalized_resource}\"\n    decoded_hex_key=\"$(echo -n ${ACCESS_KEY} | base64 -d -w0 | xxd -p -c256)\"\n    signature=$(printf \"$string_to_sign\" | openssl dgst -sha256 -mac HMAC -macopt \"hexkey:$decoded_hex_key\" -binary |  base64 -w0)\n    authorization_header=\"Authorization: $authorization ${STORAGE_ACCOUNT}:$signature\"\n\n    curl -sw \"/status/%{http_code}/\\n\" \\\n        -X $request_method \\\n        -H \"$x_ms_date_h\" \\\n        -H \"$x_ms_version_h\" \\\n        -H \"$authorization_header\" \\\n        -H \"$content_length_header\" \\\n        $full_url\n}\n\nvalidate() {\n    if [ ! \"$1\" ];\n    then\n        error \"response was null\"\n    fi\n\n    if [[ $(echo ${1} | grep -o \"/status/2\") || $(echo ${1} | grep -o \"/status/409\") ]];\n    then\n        # response is valid or share already exists, ignore\n        return\n    else\n        # other or unknown status\n        if [ $(echo ${1} | grep -o \"/status/\") ];\n        then\n            error \"response was not valid: ${1}\"\n        else\n            error \"no response code found: ${1}\"\n        fi\n    fi\n}\n\nlist_shares() {\n    response=\"$(issue_signed_request GET ?comp=list \"\\ncomp:list\")\"\n    echo ${response}\n}\n\ncreate_share() {\n    share_name=\"$1\"\n    log \"creating share $share_name\"\n\n    # test whether share exists already\n    response=$(list_shares)\n    validate \"$response\"\n    exists=$(echo ${response} | grep -c \"<Share><Name>${share_name}</Name>\")\n\n    if [ ${exists} -eq 0 ];\n    then\n        # create share\n        response=$(issue_signed_request \"PUT\" \"${share_name}?restype=share\" \"${share_name}\\nrestype:share\")\n        validate \"$response\"\n    fi\n}\n\nmount_share() {\n    share_name=\"$1\"\n    mount_location=\"$2\"\n    persist=\"$3\"\n    creds_file=\"/etc/cifs.${share_name}\"\n    mount_options=\"vers=3.0,dir_mode=0777,file_mode=0777,credentials=${creds_file}\"\n    mount_share=\"//${STORAGE_ACCOUNT}.file.core.windows.net/${SHARE_NAME}\"\n\n    log \"creating credentials at ${creds_file}\"\n    echo \"username=${STORAGE_ACCOUNT}\" >> ${creds_file}\n    echo \"password=${ACCESS_KEY}\" >> ${creds_file}\n    chmod 600 ${creds_file}\n\n    log \"mounting share $share_name at $mount_location\"\n\n    if [ $(cat /etc/mtab | grep -o \"${mount_location}\") ];\n    then\n        error \"location ${mount_location} is already mounted\"\n    fi\n\n    [ -d \"${mount_location}\" ] || mkdir -p \"${mount_location}\"\n    mount -t cifs ${mount_share} ${mount_location} -o ${mount_options}\n\n    if [ ! $(cat /etc/mtab | grep -o \"${mount_location}\") ];\n    then\n        error \"mount failed\"\n    fi\n\n    if [ ${persist} ];\n    then\n        # create a backup of fstab\n        cp /etc/fstab /etc/fstab_backup\n\n        # update /etc/fstab\n        echo ${mount_share} ${mount_location} cifs ${mount_options} >> /etc/fstab\n\n        # test that mount works\n        umount ${mount_location}\n        mount ${mount_location}\n\n        if [ ! $(cat /etc/mtab | grep -o \"${mount_location}\") ];\n        then\n            # revert changes\n            cp /etc/fstab_backup /etc/fstab\n            error \"/etc/fstab was not configured correctly, changes reverted\"\n        fi\n    fi\n}\n\n#######################################\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    error \"You must be root to run this script.\"\nfi\n\nSTORAGE_ACCOUNT=\"\"\nACCESS_KEY=\"\"\nSHARE_NAME=\"esdata00\"\nBASE_DIRECTORY=\"/sharedfs\"\n\nwhile getopts :b:a:k:s:pch optname; do\n  log \"Option $optname set\"\n  case ${optname} in\n    b) BASE_DIRECTORY=${OPTARG};;\n    a) STORAGE_ACCOUNT=${OPTARG};;\n    k) ACCESS_KEY=${OPTARG};;\n    s) SHARE_NAME=${OPTARG};;\n    p) PERSIST=1;;\n    c) CREATE_MOUNT=1;;\n    h) help; exit 1;;\n   \\?) help; error \"Option -${OPTARG} not supported.\";;\n    :) help; error \"Option -${OPTARG} requires an argument.\";;\n  esac\ndone\n\nif [ ! ${STORAGE_ACCOUNT} ];\nthen\n    help\n    error \"Storage account is required.\"\nfi\n\nif [ ! ${ACCESS_KEY} ];\nthen\n    help\n    error \"Access key is required.\"\nfi\n\n### create and mount a share in the specified storage account\nif [ ${CREATE_MOUNT} ];\nthen\n    create_share \"$SHARE_NAME\"\n    mount_share \"$SHARE_NAME\" \"${BASE_DIRECTORY}/${SHARE_NAME}\" $PERSIST\nfi\n", "num_lines": 231}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# The MIT License (MIT)\n#\n# Copyright (c) 2015 Microsoft Azure\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in all\n# copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n# SOFTWARE.\n#\n# Script Name: vm-disk-utils.sh\n# Author: Trent Swanson - Full Scale 180 Inc github:(trentmswanson)\n# Version: 0.1\n# Last Modified By:       Trent Swanson\n# Description:\n#  This script automates the partitioning and formatting of data disks\n#  Data disks can be partitioned and formatted as seperate disks or in a RAID0 configuration\n#  The script will scan for unpartitioned and unformatted data disks and partition, format, and add fstab entries\n# Parameters :\n#  1 - b: The base directory for mount points (default: /datadisks)\n#  2 - s  Create a striped RAID0 Array (No redundancy)\n#  3 - h  Help\n#  4 - o  Mount options for mount points\n# Note :\n# This script has only been tested on Ubuntu 12.04 LTS and must be root\n\nhelp()\n{\n    echo \"Usage: $(basename $0) [-b data_base] [-h] [-s] [-o mount_options]\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"   -b         base directory for mount points (default: /datadisks)\"\n    echo \"   -h         this help message\"\n    echo \"   -s         create a striped RAID array (no redundancy)\"\n    echo \"   -o         mount options for data disk\"\n}\n\nlog()\n{\n    # Un-comment the following if you would like to enable logging to a service\n    #curl -X POST -H \"content-type:text/plain\" --data-binary \"${HOSTNAME} - $1\" https://logs-01.loggly.com/inputs/<key>/tag/es-extension,${HOSTNAME}\n    echo \"$1\"\n}\n\nif [ \"${UID}\" -ne 0 ];\nthen\n    log \"Script executed without root permissions\"\n    echo \"You must be root to run this program.\" >&2\n    exit 3\nfi\n\n# Base path for data disk mount points\nDATA_BASE=\"/datadisks\"\n# Mount options for data disk\nMOUNT_OPTIONS=\"noatime,nodiratime,nodev,noexec,nosuid,nofail\"\n# Determines wheter partition and format data disks as raid set or not\nRAID_CONFIGURATION=0\n\nwhile getopts b:sho: optname; do\n    log \"Option $optname set with value ${OPTARG}\"\n  case ${optname} in\n    b)  #set clsuter name\n      DATA_BASE=${OPTARG}\n      ;;\n    s) #Partition and format data disks as raid set\n      RAID_CONFIGURATION=1\n      ;;\n    o) #mount option\n      MOUNT_OPTIONS=${OPTARG}\n      ;;\n    h)  #show help\n      help\n      exit 2\n      ;;\n    \\?) #unrecognized option - show help\n      echo -e \\\\n\"Option -${BOLD}$OPTARG${NORM} not allowed.\"\n      help\n      exit 2\n      ;;\n  esac\ndone\n\nget_next_md_device() {\n    shopt -s extglob\n    LAST_DEVICE=$(ls -1 /dev/md+([0-9]) 2>/dev/null|sort -n|tail -n1)\n    if [ -z \"${LAST_DEVICE}\" ]; then\n        NEXT=/dev/md0\n    else\n        NUMBER=$((${LAST_DEVICE/\\/dev\\/md/}))\n        NEXT=/dev/md${NUMBER}\n    fi\n    echo ${NEXT}\n}\n\nis_partitioned() {\n    OUTPUT=$(partx -s ${1} 2>&1)\n    egrep \"partition table does not contains usable partitions|failed to read partition table\" <<< \"${OUTPUT}\" >/dev/null 2>&1\n    if [ ${?} -eq 0 ]; then\n        return 1\n    else\n        return 0\n    fi\n}\n\nhas_filesystem() {\n    DEVICE=${1}\n    OUTPUT=$(file -L -s ${DEVICE})\n    grep filesystem <<< \"${OUTPUT}\" > /dev/null 2>&1\n    return ${?}\n}\n\nscan_for_new_disks() {\n    # Looks for unpartitioned disks\n    declare -a RET\n    DEVS=($(ls -1 /dev/sd*|egrep -v \"[0-9]$\"))\n    for DEV in \"${DEVS[@]}\";\n    do\n        # The disk will be considered a candidate for partitioning\n        # and formatting if it does not have a sd?1 entry or\n        # if it does have an sd?1 entry and does not contain a filesystem\n        is_partitioned \"${DEV}\"\n        if [ ${?} -eq 0 ];\n        then\n            has_filesystem \"${DEV}1\"\n            if [ ${?} -ne 0 ];\n            then\n                RET+=\" ${DEV}\"\n            fi\n        else\n            RET+=\" ${DEV}\"\n        fi\n    done\n    echo \"${RET}\"\n}\n\nget_next_mountpoint() {\n    DIRS=$(ls -1d ${DATA_BASE}/disk* 2>/dev/null| sort --version-sort)\n    MAX=$(echo \"${DIRS}\"|tail -n 1 | tr -d \"[a-zA-Z/]\")\n    if [ -z \"${MAX}\" ];\n    then\n        echo \"${DATA_BASE}/disk1\"\n        return\n    fi\n    IDX=1\n    while [ \"${IDX}\" -lt \"${MAX}\" ];\n    do\n        NEXT_DIR=\"${DATA_BASE}/disk${IDX}\"\n        if [ ! -d \"${NEXT_DIR}\" ];\n        then\n            echo \"${NEXT_DIR}\"\n            return\n        fi\n        IDX=$(( ${IDX} + 1 ))\n    done\n    IDX=$(( ${MAX} + 1))\n    echo \"${DATA_BASE}/disk${IDX}\"\n}\n\nadd_to_fstab() {\n    UUID=${1}\n    MOUNTPOINT=${2}\n    grep \"${UUID}\" /etc/fstab >/dev/null 2>&1\n    if [ ${?} -eq 0 ];\n    then\n        echo \"Not adding ${UUID} to fstab again (it's already there!)\"\n    else\n        LINE=\"UUID=\\\"${UUID}\\\"\\t${MOUNTPOINT}\\text4\\t${MOUNT_OPTIONS}\\t1 2\"\n        echo -e \"${LINE}\" >> /etc/fstab\n    fi\n}\n\ndo_partition() {\n# This function creates one (1) primary partition on the\n# disk, using all available space\n    _disk=${1}\n    _type=${2}\n    if [ -z \"${_type}\" ]; then\n        # default to Linux partition type (ie, ext3/ext4/xfs)\n        _type=83\n    fi\n    echo \"n\np\n1\n\n\nt\n${_type}\nw\"| fdisk \"${_disk}\"\n\n#\n# Use the bash-specific $PIPESTATUS to ensure we get the correct exit code\n# from fdisk and not from echo\nif [ ${PIPESTATUS[1]} -ne 0 ];\nthen\n    echo \"An error occurred partitioning ${_disk}\" >&2\n    echo \"I cannot continue\" >&2\n    exit 2\nfi\n}\n#end do_partition\n\nscan_partition_format()\n{\n    log \"Begin scanning and formatting data disks\"\n\n    DISKS=($(scan_for_new_disks))\n\n\tif [ \"${#DISKS}\" -eq 0 ];\n\tthen\n\t    log \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\techo \"Disks are ${DISKS[@]}\"\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK}\n\t    fi\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 1 Device|tail -n 1|awk '{print $1}')\n\t    has_filesystem ${PARTITION}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"Creating filesystem on ${PARTITION}.\"\n\t#        echo \"Press Ctrl-C if you don't want to destroy all data on ${PARTITION}\"\n\t#        sleep 10\n\t        mkfs -j -t ext4 ${PARTITION}\n\t    fi\n\t    MOUNTPOINT=$(get_next_mountpoint)\n\t    echo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t    [ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n\t    read UUID FS_TYPE < <(blkid -u filesystem ${PARTITION}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\t    add_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\t    echo \"Mounting disk ${PARTITION} on ${MOUNTPOINT}\"\n\t    mount \"${MOUNTPOINT}\"\n\tdone\n}\n\ncreate_striped_volume()\n{\n    DISKS=(${@})\n\n\tif [ \"${#DISKS[@]}\" -eq 0 ];\n\tthen\n\t    log \"No unpartitioned disks without filesystems detected\"\n\t    return\n\tfi\n\n\techo \"Disks are ${DISKS[@]}\"\n\n\tdeclare -a PARTITIONS\n\n\tfor DISK in \"${DISKS[@]}\";\n\tdo\n\t    echo \"Working on ${DISK}\"\n\t    is_partitioned ${DISK}\n\t    if [ ${?} -ne 0 ];\n\t    then\n\t        echo \"${DISK} is not partitioned, partitioning\"\n\t        do_partition ${DISK} fd\n\t    fi\n\n\t    PARTITION=$(fdisk -l ${DISK}|grep -A 2 Device|tail -n 1|awk '{print $1}')\n\t    PARTITIONS+=(\"${PARTITION}\")\n\tdone\n\n    MDDEVICE=$(get_next_md_device)\n\tudevadm control --stop-exec-queue\n\tmdadm --create ${MDDEVICE} --level 0 -c 64 --raid-devices ${#PARTITIONS[@]} ${PARTITIONS[*]}\n\tudevadm control --start-exec-queue\n\n\tMOUNTPOINT=$(get_next_mountpoint)\n\techo \"Next mount point appears to be ${MOUNTPOINT}\"\n\t[ -d \"${MOUNTPOINT}\" ] || mkdir -p \"${MOUNTPOINT}\"\n\n\t#Make a file system on the new device\n\tSTRIDE=128 #(512kB stripe size) / (4kB block size)\n\tPARTITIONSNUM=${#PARTITIONS[@]}\n\tSTRIPEWIDTH=$((${STRIDE} * ${PARTITIONSNUM}))\n\n\tmkfs.ext4 -b 4096 -E stride=${STRIDE},stripe-width=${STRIPEWIDTH},nodiscard \"${MDDEVICE}\"\n\n\tread UUID FS_TYPE < <(blkid -u filesystem ${MDDEVICE}|awk -F \"[= ]\" '{print $3\" \"$5}'|tr -d \"\\\"\")\n\n\tadd_to_fstab \"${UUID}\" \"${MOUNTPOINT}\"\n\n\tmount \"${MOUNTPOINT}\"\n}\n\ncheck_mdadm() {\n    dpkg -s mdadm >/dev/null 2>&1\n    if [ ${?} -ne 0 ]; then\n        (apt-get -y update || (sleep 15; apt-get -y update)) > /dev/null\n        DEBIAN_FRONTEND=noninteractive apt-get -y install mdadm --fix-missing\n    fi\n}\n\n# Create Partitions\nDISKS=$(scan_for_new_disks)\n\nif [ \"$RAID_CONFIGURATION\" -eq 1 ]; then\n    check_mdadm\n    create_striped_volume \"${DISKS[@]}\"\nelse\n    scan_partition_format\nfi\n\n", "num_lines": 325}
{"repo_name": "azure-quickstart-templates", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\npwsh -noprofile -nologo -command \"$0/../ci-scripts/Test-LocalSample.ps1 $@ ; if (\\$error.Count) { exit 1}\"\n", "num_lines": 3}
{"repo_name": "azure-relay", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\n#\n# variables\n#\n\nRESET=\"\\033[0m\"\nRED=\"\\033[0;31m\"\nYELLOW=\"\\033[0;33m\"\nMAGENTA=\"\\033[0;95m\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n[ -z \"${DOTNET_HOME:-}\" ] && DOTNET_HOME=\"$HOME/.dotnet\"\nconfig_file=\"$DIR/korebuild.json\"\nverbose=false\nupdate=false\nrepo_path=\"$DIR\"\nchannel=''\ntools_source=''\n\n#\n# Functions\n#\n__usage() {\n    echo \"Usage: $(basename \"${BASH_SOURCE[0]}\") [options] [[--] <MSBUILD_ARG>...]\"\n    echo \"\"\n    echo \"Arguments:\"\n    echo \"    <MSBUILD_ARG>...         Arguments passed to MSBuild. Variable number of arguments allowed.\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"    --verbose                Show verbose output.\"\n    echo \"    -c|--channel <CHANNEL>   The channel of KoreBuild to download. Overrides the value from the config file..\"\n    echo \"    --config-file <FILE>     The path to the configuration file that stores values. Defaults to korebuild.json.\"\n    echo \"    -d|--dotnet-home <DIR>   The directory where .NET Core tools will be stored. Defaults to '\\$DOTNET_HOME' or '\\$HOME/.dotnet.\"\n    echo \"    --path <PATH>            The directory to build. Defaults to the directory containing the script.\"\n    echo \"    -s|--tools-source <URL>  The base url where build tools can be downloaded. Overrides the value from the config file.\"\n    echo \"    -u|--update              Update to the latest KoreBuild even if the lock file is present.\"\n    echo \"\"\n    echo \"Description:\"\n    echo \"    This function will create a file \\$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be.\"\n    echo \"    When the lockfile is not present, KoreBuild will create one using latest available version from \\$channel.\"\n\n    if [[ \"${1:-}\" != '--no-exit' ]]; then\n        exit 2\n    fi\n}\n\nget_korebuild() {\n    local version\n    local lock_file=\"$repo_path/korebuild-lock.txt\"\n    if [ ! -f \"$lock_file\" ] || [ \"$update\" = true ]; then\n        __get_remote_file \"$tools_source/korebuild/channels/$channel/latest.txt\" \"$lock_file\"\n    fi\n    version=\"$(grep 'version:*' -m 1 \"$lock_file\")\"\n    if [[ \"$version\" == '' ]]; then\n        __error \"Failed to parse version from $lock_file. Expected a line that begins with 'version:'\"\n        return 1\n    fi\n    version=\"$(echo \"${version#version:}\" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')\"\n    local korebuild_path=\"$DOTNET_HOME/buildtools/korebuild/$version\"\n\n    {\n        if [ ! -d \"$korebuild_path\" ]; then\n            mkdir -p \"$korebuild_path\"\n            local remote_path=\"$tools_source/korebuild/artifacts/$version/korebuild.$version.zip\"\n            tmpfile=\"$(mktemp)\"\n            echo -e \"${MAGENTA}Downloading KoreBuild ${version}${RESET}\"\n            if __get_remote_file \"$remote_path\" \"$tmpfile\"; then\n                unzip -q -d \"$korebuild_path\" \"$tmpfile\"\n            fi\n            rm \"$tmpfile\" || true\n        fi\n\n        source \"$korebuild_path/KoreBuild.sh\"\n    } || {\n        if [ -d \"$korebuild_path\" ]; then\n            echo \"Cleaning up after failed installation\"\n            rm -rf \"$korebuild_path\" || true\n        fi\n        return 1\n    }\n}\n\n__error() {\n    echo -e \"${RED}error: $*${RESET}\" 1>&2\n}\n\n__warn() {\n    echo -e \"${YELLOW}warning: $*${RESET}\"\n}\n\n__machine_has() {\n    hash \"$1\" > /dev/null 2>&1\n    return $?\n}\n\n__get_remote_file() {\n    local remote_path=$1\n    local local_path=$2\n\n    if [[ \"$remote_path\" != 'http'* ]]; then\n        cp \"$remote_path\" \"$local_path\"\n        return 0\n    fi\n\n    local failed=false\n    if __machine_has wget; then\n        wget --tries 10 --quiet -O \"$local_path\" \"$remote_path\" || failed=true\n    else\n        failed=true\n    fi\n\n    if [ \"$failed\" = true ] && __machine_has curl; then\n        failed=false\n        curl --retry 10 -sSL -f --create-dirs -o \"$local_path\" \"$remote_path\" || failed=true\n    fi\n\n    if [ \"$failed\" = true ]; then\n        __error \"Download failed: $remote_path\" 1>&2\n        return 1\n    fi\n}\n\n#\n# main\n#\n\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        -\\?|-h|--help)\n            __usage --no-exit\n            exit 0\n            ;;\n        -c|--channel|-Channel)\n            shift\n            channel=\"${1:-}\"\n            [ -z \"$channel\" ] && __usage\n            ;;\n        --config-file|-ConfigFile)\n            shift\n            config_file=\"${1:-}\"\n            [ -z \"$config_file\" ] && __usage\n            if [ ! -f \"$config_file\" ]; then\n                __error \"Invalid value for --config-file. $config_file does not exist.\"\n                exit 1\n            fi\n            ;;\n        -d|--dotnet-home|-DotNetHome)\n            shift\n            DOTNET_HOME=\"${1:-}\"\n            [ -z \"$DOTNET_HOME\" ] && __usage\n            ;;\n        --path|-Path)\n            shift\n            repo_path=\"${1:-}\"\n            [ -z \"$repo_path\" ] && __usage\n            ;;\n        -s|--tools-source|-ToolsSource)\n            shift\n            tools_source=\"${1:-}\"\n            [ -z \"$tools_source\" ] && __usage\n            ;;\n        -u|--update|-Update)\n            update=true\n            ;;\n        --verbose|-Verbose)\n            verbose=true\n            ;;\n        --)\n            shift\n            break\n            ;;\n        *)\n            break\n            ;;\n    esac\n    shift\ndone\n\nif ! __machine_has unzip; then\n    __error 'Missing required command: unzip'\n    exit 1\nfi\n\nif ! __machine_has curl && ! __machine_has wget; then\n    __error 'Missing required command. Either wget or curl is required.'\n    exit 1\nfi\n\n[ -z \"${config_file:-}\" ] && config_file=\"$repo_path/korebuild.json\"\nif [ -f \"$config_file\" ]; then\n    if __machine_has jq ; then\n        if jq '.' \"$config_file\" >/dev/null ; then\n            config_channel=\"$(jq -r 'select(.channel!=null) | .channel' \"$config_file\")\"\n            config_tools_source=\"$(jq -r 'select(.toolsSource!=null) | .toolsSource' \"$config_file\")\"\n        else\n            __warn \"$config_file is invalid JSON. Its settings will be ignored.\"\n        fi\n    elif __machine_has python ; then\n        if python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))\" >/dev/null ; then\n            config_channel=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')\")\"\n            config_tools_source=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')\")\"\n        else\n            __warn \"$config_file is invalid JSON. Its settings will be ignored.\"\n        fi\n    else\n        __warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.'\n    fi\n\n    [ ! -z \"${config_channel:-}\" ] && channel=\"$config_channel\"\n    [ ! -z \"${config_tools_source:-}\" ] && tools_source=\"$config_tools_source\"\nfi\n\n[ -z \"$channel\" ] && channel='dev'\n[ -z \"$tools_source\" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools'\n\nget_korebuild\ninstall_tools \"$tools_source\" \"$DOTNET_HOME\"\ninvoke_repository_build \"$repo_path\" \"$@\"\n", "num_lines": 221}
{"repo_name": "azure-relay", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nset -euo pipefail\n\n#\n# variables\n#\n\nRESET=\"\\033[0m\"\nRED=\"\\033[0;31m\"\nYELLOW=\"\\033[0;33m\"\nMAGENTA=\"\\033[0;95m\"\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n[ -z \"${DOTNET_HOME:-}\" ] && DOTNET_HOME=\"$HOME/.dotnet\"\nverbose=false\nupdate=false\nrepo_path=\"$DIR\"\nchannel=''\ntools_source=''\ntools_source_suffix=''\n\n#\n# Functions\n#\n__usage() {\n    echo \"Usage: $(basename \"${BASH_SOURCE[0]}\") command [options] [[--] <Arguments>...]\"\n    echo \"\"\n    echo \"Arguments:\"\n    echo \"    command                The command to be run.\"\n    echo \"    <Arguments>...         Arguments passed to the command. Variable number of arguments allowed.\"\n    echo \"\"\n    echo \"Options:\"\n    echo \"    --verbose                                             Show verbose output.\"\n    echo \"    -c|--channel <CHANNEL>                                The channel of KoreBuild to download. Overrides the value from the config file..\"\n    echo \"    --config-file <FILE>                                  The path to the configuration file that stores values. Defaults to korebuild.json.\"\n    echo \"    -d|--dotnet-home <DIR>                                The directory where .NET Core tools will be stored. Defaults to '\\$DOTNET_HOME' or '\\$HOME/.dotnet.\"\n    echo \"    --path <PATH>                                         The directory to build. Defaults to the directory containing the script.\"\n    echo \"    -s|--tools-source|-ToolsSource <URL>                  The base url where build tools can be downloaded. Overrides the value from the config file.\"\n    echo \"    --tools-source-suffix|-ToolsSourceSuffix <SUFFIX>     The suffix to append to tools-source. Useful for query strings.\"\n    echo \"    -u|--update                                           Update to the latest KoreBuild even if the lock file is present.\"\n    echo \"\"\n    echo \"Description:\"\n    echo \"    This function will create a file \\$DIR/korebuild-lock.txt. This lock file can be committed to source, but does not have to be.\"\n    echo \"    When the lockfile is not present, KoreBuild will create one using latest available version from \\$channel.\"\n\n    if [[ \"${1:-}\" != '--no-exit' ]]; then\n        exit 2\n    fi\n}\n\nget_korebuild() {\n    local version\n    local lock_file=\"$repo_path/korebuild-lock.txt\"\n    if [ ! -f \"$lock_file\" ] || [ \"$update\" = true ]; then\n        __get_remote_file \"$tools_source/korebuild/channels/$channel/latest.txt\" \"$lock_file\" \"$tools_source_suffix\"\n    fi\n    version=\"$(grep 'version:*' -m 1 \"$lock_file\")\"\n    if [[ \"$version\" == '' ]]; then\n        __error \"Failed to parse version from $lock_file. Expected a line that begins with 'version:'\"\n        return 1\n    fi\n    version=\"$(echo \"${version#version:}\" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')\"\n    local korebuild_path=\"$DOTNET_HOME/buildtools/korebuild/$version\"\n\n    {\n        if [ ! -d \"$korebuild_path\" ]; then\n            mkdir -p \"$korebuild_path\"\n            local remote_path=\"$tools_source/korebuild/artifacts/$version/korebuild.$version.zip\"\n            tmpfile=\"$(mktemp)\"\n            echo -e \"${MAGENTA}Downloading KoreBuild ${version}${RESET}\"\n            if __get_remote_file \"$remote_path\" \"$tmpfile\" \"$tools_source_suffix\"; then\n                unzip -q -d \"$korebuild_path\" \"$tmpfile\"\n            fi\n            rm \"$tmpfile\" || true\n        fi\n\n        source \"$korebuild_path/KoreBuild.sh\"\n    } || {\n        if [ -d \"$korebuild_path\" ]; then\n            echo \"Cleaning up after failed installation\"\n            rm -rf \"$korebuild_path\" || true\n        fi\n        return 1\n    }\n}\n\n__error() {\n    echo -e \"${RED}error: $*${RESET}\" 1>&2\n}\n\n__warn() {\n    echo -e \"${YELLOW}warning: $*${RESET}\"\n}\n\n__machine_has() {\n    hash \"$1\" > /dev/null 2>&1\n    return $?\n}\n\n__get_remote_file() {\n    local remote_path=$1\n    local local_path=$2\n    local remote_path_suffix=$3\n\n    if [[ \"$remote_path\" != 'http'* ]]; then\n        cp \"$remote_path\" \"$local_path\"\n        return 0\n    fi\n\n    local failed=false\n    if __machine_has wget; then\n        wget --tries 10 --quiet -O \"$local_path\" \"${remote_path}${remote_path_suffix}\" || failed=true\n    else\n        failed=true\n    fi\n\n    if [ \"$failed\" = true ] && __machine_has curl; then\n        failed=false\n        curl --retry 10 -sSL -f --create-dirs -o \"$local_path\" \"${remote_path}${remote_path_suffix}\" || failed=true\n    fi\n\n    if [ \"$failed\" = true ]; then\n        __error \"Download failed: $remote_path\" 1>&2\n        return 1\n    fi\n}\n\n#\n# main\n#\n\ncommand=\"${1:-}\"\nshift\n\nwhile [[ $# -gt 0 ]]; do\n    case $1 in\n        -\\?|-h|--help)\n            __usage --no-exit\n            exit 0\n            ;;\n        -c|--channel|-Channel)\n            shift\n            channel=\"${1:-}\"\n            [ -z \"$channel\" ] && __usage\n            ;;\n        --config-file|-ConfigFile)\n            shift\n            config_file=\"${1:-}\"\n            [ -z \"$config_file\" ] && __usage\n            if [ ! -f \"$config_file\" ]; then\n                __error \"Invalid value for --config-file. $config_file does not exist.\"\n                exit 1\n            fi\n            ;;\n        -d|--dotnet-home|-DotNetHome)\n            shift\n            DOTNET_HOME=\"${1:-}\"\n            [ -z \"$DOTNET_HOME\" ] && __usage\n            ;;\n        --path|-Path)\n            shift\n            repo_path=\"${1:-}\"\n            [ -z \"$repo_path\" ] && __usage\n            ;;\n        -s|--tools-source|-ToolsSource)\n            shift\n            tools_source=\"${1:-}\"\n            [ -z \"$tools_source\" ] && __usage\n            ;;\n        --tools-source-suffix|-ToolsSourceSuffix)\n            shift\n            tools_source_suffix=\"${1:-}\"\n            [ -z \"$tools_source_suffix\" ] && __usage\n            ;;\n        -u|--update|-Update)\n            update=true\n            ;;\n        --verbose|-Verbose)\n            verbose=true\n            ;;\n        --)\n            shift\n            break\n            ;;\n        *)\n            break\n            ;;\n    esac\n    shift\ndone\n\nif ! __machine_has unzip; then\n    __error 'Missing required command: unzip'\n    exit 1\nfi\n\nif ! __machine_has curl && ! __machine_has wget; then\n    __error 'Missing required command. Either wget or curl is required.'\n    exit 1\nfi\n\n[ -z \"${config_file:-}\" ] && config_file=\"$repo_path/korebuild.json\"\nif [ -f \"$config_file\" ]; then\n    if __machine_has jq ; then\n        if jq '.' \"$config_file\" >/dev/null ; then\n            config_channel=\"$(jq -r 'select(.channel!=null) | .channel' \"$config_file\")\"\n            config_tools_source=\"$(jq -r 'select(.toolsSource!=null) | .toolsSource' \"$config_file\")\"\n        else\n            __warn \"$config_file is invalid JSON. Its settings will be ignored.\"\n        fi\n    elif __machine_has python ; then\n        if python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'))\" >/dev/null ; then\n            config_channel=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['channel'] if 'channel' in obj else '')\")\"\n            config_tools_source=\"$(python -c \"import json,codecs;obj=json.load(codecs.open('$config_file', 'r', 'utf-8-sig'));print(obj['toolsSource'] if 'toolsSource' in obj else '')\")\"\n        else\n            __warn \"$config_file is invalid JSON. Its settings will be ignored.\"\n        fi\n    else\n        __warn 'Missing required command: jq or pyton. Could not parse the JSON file. Its settings will be ignored.'\n    fi\n\n    [ ! -z \"${config_channel:-}\" ] && channel=\"$config_channel\"\n    [ ! -z \"${config_tools_source:-}\" ] && tools_source=\"$config_tools_source\"\nfi\n\n[ -z \"$channel\" ] && channel='dev'\n[ -z \"$tools_source\" ] && tools_source='https://aspnetcore.blob.core.windows.net/buildtools'\n\nget_korebuild\nset_korebuildsettings \"$tools_source\" \"$DOTNET_HOME\" \"$repo_path\" \"$config_file\"\ninvoke_korebuild_command \"$command\" \"$@\"\n", "num_lines": 232}
{"repo_name": "azure-relay-aspnetserver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet build '${scriptroot}/AzureRelayServer.sln' --configuration ${BuildConfiguration}\"\ndotnet build \"${scriptroot}/AzureRelayServer.sln\" --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet build\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-relay-aspnetserver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet pack '${scriptroot}/AzureRelayServer.sln' --no-build --no-dependencies --no-restore /p:Version=${CDP_PACKAGE_VERSION_SEMANTIC:-1.0.0.0-dev} --configuration ${BuildConfiguration}\"\ndotnet pack \"${scriptroot}/AzureRelayServer.sln\" --no-build --no-dependencies --no-restore /p:Version=${CDP_PACKAGE_VERSION_SEMANTIC:-1.0.0.0-dev} --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet build\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-relay-aspnetserver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\necho \"dotnet restore '${scriptroot}/AzureRelayServer.sln'\"\ndotnet restore \"${scriptroot}/AzureRelayServer.sln\"\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet restore\" >&2\n  exit 1\nfi", "num_lines": 25}
{"repo_name": "azure-relay-aspnetserver", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet test '${scriptroot}/AzureRelayServer.sln' --no-build --no-restore --blame --logger:trx --configuration ${BuildConfiguration}\"\ndotnet test \"${scriptroot}/AzureRelayServer.sln\" --no-build --no-restore --blame --logger:trx --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet test\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\nDIR=\"$( cd \"$( dirname \"${BASH_SOURCE[0]}\" )\" && pwd )\"\n\n# Call \"sync\" between \"chmod\" and execution to prevent \"text file busy\" error in Docker (aufs)\nchmod +x \"$DIR/run.sh\"; sync\n\"$DIR/run.sh\" \"$@\"\n", "num_lines": 9}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\npushd \"${0%/*}\" > /dev/null \nif [ ! -z $BUILDVERSION ]; then _VersionProp=\"/p:VersionPrefix=$BUILDVERSION\"; fi\ndotnet restore\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=osx-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=debian.10-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=ubuntu.18.04-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=ubuntu.18.04-arm64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=ubuntu.20.04-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=ubuntu.20.04-arm64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=opensuse.15.0-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=fedora.34-x64 $_BuildProp $_VersionProp $@\ndotnet msbuild /t:Package /p:Configuration=Release /p:WindowsOnly=false /p:TargetFramework=net6.0 /p:RuntimeIdentifier=centos.9-x64 $_BuildProp $_VersionProp $@\n\npopd\n", "num_lines": 16}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nset -euo pipefail\n\ndotnet restore\ndotnet msbuild $@\n", "num_lines": 7}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ -z $AZBRIDGE_TEST_CXNSTRING ]; then \n  echo \"Skipping integration tests due to missing AZBRIDGE_TEST_CXNSTRING secret\"\n  exit 0\nfi\n\npushd test/mysql\ndotnet msbuild /t:build /p:Configuration=Debug /p:TargetFramework=net6.0 $_BuildProp $_VersionProp $@\n_RESULT=$?\nif [ $_RESULT -ne 0 ]; then \n    popd\n    exit $_RESULT\nfi\ndotnet test --verbosity=normal /p:Configuration=Debug /p:TargetFramework=net6.0 $_BuildProp $_VersionProp $@\n_RESULT=$?\nif [ $_RESULT -ne 0 ]; then \n    popd\n    exit $_RESULT\nfi\npopd\npushd test/nginx\ndotnet msbuild /t:clean,build /p:Configuration=Debug /p:TargetFramework=net6.0 $_BuildProp $_VersionProp $@\n_RESULT=$?\nif [ $_RESULT -ne 0 ]; then \n    popd\n    exit $_RESULT\nfi\ndotnet test --verbosity=normal /p:Configuration=Debug /p:TargetFramework=net6.0 $_BuildProp $_VersionProp $@\n_RESULT=$?\nif [ $_RESULT -ne 0 ]; then\n    popd\n    exit $_RESULT\nfi\npopd", "num_lines": 35}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nexport PATH=\"$PATH:/usr/share/azbridge\"\n\n# remove specified host from /etc/hosts\n\nfunction removehost() {\n    if [[ \"$1\" ]]\n    then\n        HOSTNAME=$1\n\n        if [ -n \"$(grep \"\\b$HOSTNAME\\b\" /etc/hosts)\" ]\n        then\n            echo \"$HOSTNAME Found in your /etc/hosts, Removing now...\";\n            sudo sed -i\".bak\" \"/\\b$HOSTNAME\\b/d\" /etc/hosts\n        else\n            echo \"$HOSTNAME was not found in your /etc/hosts\";\n        fi\n    else\n        echo \"Error: missing required parameters.\"\n        echo \"Usage: \"\n        echo \"  removehost domain\"\n    fi\n}\n\n#add new ip host pair to /etc/hosts\nfunction addhost() {\n    if [[ \"$1\" && \"$2\" ]]\n    then\n        IP=$1\n        HOSTNAME=$2\n\n        if [ -n \"$(grep \"\\b$HOSTNAME\\b\" /etc/hosts)\" ]\n            then\n                echo \"$HOSTNAME already exists:\";\n                echo $(grep \"\\b$HOSTNAME\\b\" /etc/hosts);\n            else\n                echo \"Adding $HOSTNAME to your /etc/hosts\";\n                printf \"%s\\t%s\\n\" \"$IP\" \"$HOSTNAME\" | sudo tee -a /etc/hosts > /dev/null;\n\n                if [ -n \"$(grep \"\\b$HOSTNAME\\b\" /etc/hosts)\" ]\n                    then\n                        echo \"$HOSTNAME was added succesfully:\";\n                        echo $(grep \"\\b$HOSTNAME\\b\" /etc/hosts);\n                    else\n                        echo \"Failed to Add $HOSTNAME, Try again!\";\n                fi\n        fi\n    else\n        echo \"Error: missing required parameters.\"\n        echo \"Usage: \"\n        echo \"  addhost ip domain\"\n    fi\n}", "num_lines": 54}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ ! -z $1 ]; then ResourceGroup=$1; fi\n\nif [ -z ${ResourceGroup+x} ]; then ResourceGroup=$AZBRIDGE_TEST_RESOURCEGROUP; fi\n\naz group delete --name $ResourceGroup --yes", "num_lines": 5}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "if [ ! -z $1 ]; then Region=$1; fi\nif [ ! -z $2 ]; then ResourceGroup=$2; fi\nif [ ! -z $3 ]; then Namespace=$3; fi\n\nd=$(date +%Y%m%d%H%M%S)\n\nif [ -z ${Region+x} ]; then Region='westeurope'; fi\nif [ -z ${ResourceGroup+x} ]; then ResourceGroup='azbridge'$d; fi\nif [ -z ${Namespace+x} ]; then Namespace=$ResourceGroup; fi\n\necho $ResourceGroup\n\naz group create --name $ResourceGroup --location $Region\naz relay namespace create --resource-group $ResourceGroup --name $Namespace\naz relay namespace authorization-rule create --resource-group $ResourceGroup --namespace-name $Namespace --name SendListen --rights Send Listen\naz relay hyco create --resource-group $ResourceGroup --namespace-name $Namespace --name a1\naz relay hyco create --resource-group $ResourceGroup --namespace-name $Namespace --name a2\nexport AZBRIDGE_TEST_CXNSTRING=$(az relay namespace authorization-rule keys list --resource-group $ResourceGroup --namespace-name $Namespace --name SendListen --query 'primaryConnectionString' -o json)\nexport AZBRIDGE_TEST_RESOURCEGROUP=$ResourceGroup\nexport AZBRIDGE_TEST_NAMESPACE=$Namespace", "num_lines": 20}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n/usr/share/azbridge/azbridge -v -l /tests/applog.log -x $AZBRIDGE_TEST_CXNSTRING -R a2:test/3306 &\nmysql-docker-entrypoint.sh $@\n", "num_lines": 5}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n/usr/share/azbridge/azbridge -v -l /tests/clientlog.log -x $AZBRIDGE_TEST_CXNSTRING -L 127.0.9.1:3306/test:a2 &\nsleep 5\nmysql --defaults-extra-file=/tests/my.cnf -h 127.0.9.1 < /tests/test.sql", "num_lines": 4}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -z $1 ]; then Operation=$1; fi\nif [ ! -z $2 ]; then ImageName=$2; fi\nif [ ! -z $3 ]; then ImageSuffix=$3; fi\nif [ ! -z $4 ]; then VersionPrefix=$4; fi\nif [ ! -z $5 ]; then VersionSuffix=$5; fi\nif [ ! -z $6 ]; then TargetFramework=$6; fi\n\nif [ -z ${Operation+x} ]; then Operation='build'; fi\nif [ -z ${ImageName+x} ]; then ImageName='ubuntu.20.04-x64'; fi\nif [ -z ${ImageSuffix+x} ]; then VersionSuffix='deb'; fi\nif [ -z ${VersionSuffix+x} ]; then VersionSuffix='preview'; fi\nif [ -z ${VersionPrefix+x} ]; then VersionPrefix='1.0.0'; fi\nif [ -z ${TargetFramework+x} ]; then TargetFramework='net6.0'; fi\n\necho $@\n\nPackageName=azbridge.$VersionPrefix-$VersionSuffix.$ImageName.$ImageSuffix\n\nif [ \"${Operation}\" == \"build\" ]; then\n    pushd \"${0%/*}\" > /dev/null \n    if [ ! -d \"tmp\" ]; then mkdir tmp; fi\n  \n    cp ../../artifacts/build/$TargetFramework/$PackageName tmp/ > /dev/null\n    docker build -q -f mysql.server.dockerfile . --tag azbridge-mysql-server --build-arg package_name=$PackageName\n    _RESULT=$?\n    if [ $_RESULT -ne 0 ]; then\n       rm -rf tmp\n       popd\n       exit $_RESULT\n    fi\n    docker build -q -f mysql.client.dockerfile . --tag azbridge-mysql-client --build-arg package_name=$PackageName\n    _RESULT=$?\n    if [ $_RESULT -ne 0 ]; then\n       rm -rf tmp\n       popd\n       exit $_RESULT\n    fi\n    rm -rf tmp\n    popd\nelse \n    if [ \"${Operation}\" == \"test\" ]; then\n        pushd \"${0%/*}\" > /dev/null \n        IMAGE_NAME=$PackageName\n        _CXNSTRING=$AZBRIDGE_TEST_CXNSTRING\n        if [ -z $_CXNSTRING ]; then \n            echo AZBRIDGE_TEST_CXNSTRING environment variable must be set to valid relay connection string\n            exit 2\n        fi\n        \n        # start the web server\n        server_name=$(docker run -v $(pwd):/tests -d -v $(pwd)/my.cnf:/etc/mysqld/conf.d/my.cnf --rm -d -e AZBRIDGE_TEST_CXNSTRING=\"$_CXNSTRING\" -e MYSQL_ROOT_PASSWORD=PaSsWoRd112233 -e MYSQL_PASSWORD=PaSsWoRd112233 -e MYSQL_USER=mysql azbridge-mysql-server:latest)\n        # wait for server to start\n        echo waiting 20 seconds\n        sleep 20\n        # run the client\n        docker run -v $(pwd):/tests -v $(pwd)/my.cnf:/home/mysql/.my.cnf --rm -i -e AZBRIDGE_TEST_CXNSTRING=\"$_CXNSTRING\" azbridge-mysql-client:latest bash /tests/run_client.sh\n        _RESULT=$?\n        # stop the web server\n        docker stop $server_name\n      \n        diff --strip-trailing-cr -B -i -w downloaded.txt index.html\n                \n        if [ $_RESULT -eq 0 ]; then \n            echo OK\n            exit 0\n        else\n            echo not ok\n            exit 1\n        fi\n    else \n        if [ \"${Operation}\" == \"clean\" ]; then\n            if [ ! -z `docker images \"azbridge-mysql-server\" -q` ]; then\n                docker rmi -f azbridge-mysql-server:latest\n            fi\n            if [ ! -z `docker images \"azbridge-mysql-client\" -q` ]; then\n                docker rmi -f azbridge-mysql-client:latest\n            fi\n        else\n            echo \"Unknown command\"\n        fi\n    fi\nfi \n", "num_lines": 85}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "/usr/share/azbridge/azbridge -v -l /tests/clientlog.log -x $AZBRIDGE_TEST_CXNSTRING -L 127.0.9.1:8088/test:a1 &\nsleep 5\nwget -O /tests/downloaded.txt http://127.0.9.1:8088 ", "num_lines": 3}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "/usr/share/azbridge/azbridge -v -l /tests/applog.log -x $AZBRIDGE_TEST_CXNSTRING -R a1:test/80 &\nsleep 5\nnginx -g 'daemon off;'\n", "num_lines": 4}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\nif [ ! -z $1 ]; then Operation=$1; fi\nif [ ! -z $2 ]; then ImageName=$2; fi\nif [ ! -z $3 ]; then ImageSuffix=$3; fi\nif [ ! -z $4 ]; then VersionPrefix=$4; fi\nif [ ! -z $5 ]; then VersionSuffix=$5; fi\nif [ ! -z $6 ]; then TargetFramework=$6; fi\n\nif [ -z ${Operation+x} ]; then Operation='build'; fi\nif [ -z ${ImageName+x} ]; then ImageName='ubuntu.18.04-x64'; fi\nif [ -z ${ImageSuffix+x} ]; then VersionSuffix='deb'; fi\nif [ -z ${VersionSuffix+x} ]; then VersionSuffix='preview'; fi\nif [ -z ${VersionPrefix+x} ]; then VersionPrefix='1.0.0'; fi\nif [ -z ${TargetFramework+x} ]; then TargetFramework='net6.0'; fi\n\necho $@\n\nPackageName=azbridge.$VersionPrefix-$VersionSuffix.$ImageName.$ImageSuffix\n\nif [ \"${Operation}\" == \"build\" ]; then\n    pushd \"${0%/*}\" > /dev/null \n    if [ ! -d \"tmp\" ]; then mkdir tmp; fi\n  \n    cp ../../artifacts/build/$TargetFramework/$PackageName tmp/ > /dev/null\n    docker build -q -f $ImageName.server.dockerfile . --tag azbridge-nginx-server-$ImageName --build-arg package_name=$PackageName\n    _RESULT=$?\n    if [ $_RESULT -ne 0 ]; then\n       rm -rf tmp\n       popd\n       exit $_RESULT\n    fi\n    docker build -q -f $ImageName.client.dockerfile . --tag azbridge-nginx-client-$ImageName --build-arg package_name=$PackageName\n    _RESULT=$?\n    if [ $_RESULT -ne 0 ]; then\n       rm -rf tmp\n       popd\n       exit $_RESULT\n    fi\n    rm -rf tmp\n    popd\nelse \n    if [ \"${Operation}\" == \"test\" ]; then\n        pushd \"${0%/*}\" > /dev/null \n        IMAGE_NAME=$PackageName\n        _CXNSTRING=$AZBRIDGE_TEST_CXNSTRING\n        if [ -z $_CXNSTRING ]; then \n            echo AZBRIDGE_TEST_CXNSTRING environment variable must be set to valid relay connection string\n            exit 2\n        fi\n        \n        # start the web server\n        server_name=$(docker run -v $(pwd):/tests --rm -d -e AZBRIDGE_TEST_CXNSTRING=\"$_CXNSTRING\" azbridge-nginx-server-$ImageName:latest bash /tests/run_nginx.sh)\n        # run the client\n        docker run -v $(pwd):/tests --rm -e AZBRIDGE_TEST_CXNSTRING=\"$_CXNSTRING\" azbridge-nginx-client-$ImageName:latest bash /tests/run_client.sh\n        # stop the web server\n        docker stop $server_name\n      \n        diff --strip-trailing-cr -B -i -w downloaded.txt index.html\n        _RESULT=$?\n        rm -f downloaded.txt\n        if [ $_RESULT -eq 0 ]; then \n            echo OK\n            exit 0\n        else\n            echo not ok\n            exit 1\n        fi\n    else \n        if [ \"${Operation}\" == \"clean\" ]; then\n            if [ ! -z `docker images \"azbridge-nginx-server-$ImageName\" -q` ]; then\n                docker rmi -f azbridge-nginx-server-$ImageName:latest\n            fi\n            if [ ! -z `docker images \"azbridge-nginx-client-$ImageName\" -q` ]; then\n                docker rmi -f azbridge-nginx-client-$ImageName:latest\n            fi\n        else\n            echo \"Unknown command\"\n        fi\n    fi\nfi ", "num_lines": 81}
{"repo_name": "azure-relay-bridge", "repo_creator": "Azure", "programming_language": "Shell", "code": "sudo ifconfig lo0 alias 127.0.97.1 up\nsudo ifconfig lo0 alias 127.0.97.2 up", "num_lines": 2}
{"repo_name": "azure-relay-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet build '${scriptroot}/Microsoft.Azure.Relay.sln' --configuration ${BuildConfiguration}\"\ndotnet build \"${scriptroot}/Microsoft.Azure.Relay.sln\" --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet build\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-relay-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet pack '${scriptroot}/Microsoft.Azure.Relay.sln' --no-build --no-dependencies --no-restore /p:Version=${CDP_PACKAGE_VERSION_SEMANTIC:-3.0.1} --configuration ${BuildConfiguration}\"\ndotnet pack \"${scriptroot}/Microsoft.Azure.Relay.sln\" --no-build --no-dependencies --no-restore /p:Version=${CDP_PACKAGE_VERSION_SEMANTIC:-3.0.1} --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet build\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-relay-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\necho \"dotnet restore '${scriptroot}/Microsoft.Azure.Relay.sln'\"\ndotnet restore \"${scriptroot}/Microsoft.Azure.Relay.sln\"\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet restore\" >&2\n  exit 1\nfi", "num_lines": 25}
{"repo_name": "azure-relay-dotnet", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n\nsource=\"${BASH_SOURCE[0]}\"\n\n# resolve $SOURCE until the file is no longer a symlink\nwhile [[ -h $source ]]; do\n  scriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n  source=\"$(readlink \"$source\")\"\n\n  # if $source was a relative symlink, we need to resolve it relative to the path where the\n  # symlink file was located\n  [[ $source != /* ]] && source=\"$scriptroot/$source\"\ndone\nscriptroot=\"$( cd -P \"$( dirname \"$source\" )\" && pwd )\"\n\nif [ ${TF_BUILD}=\"True\" ]; then\n  BuildConfiguration=\"Release\"\nelse\n  BuildConfiguration=\"Debug\"\nfi\n\necho \"dotnet test '${scriptroot}/Microsoft.Azure.Relay.sln' --no-build --no-restore --blame --logger:trx --configuration ${BuildConfiguration}\"\ndotnet test \"${scriptroot}/Microsoft.Azure.Relay.sln\" --no-build --no-restore --blame --logger:trx --configuration ${BuildConfiguration}\n\nif [ $? -eq 0 ]\nthen\n  exit 0\nelse\n  echo \"Error during running dotnet test\" >&2\n  exit 1\nfi", "num_lines": 31}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable history expansion to support passwords with '!'\nset +H\n\nINSTALLER_PATH=\nTENANT_ID=\nAPP_ID=\nKV_NAME=\nKV_CERT_THUMB=\nSCHEDULER_HOST=\nBLADE_GROUPS=\n\nOPTS=`getopt -n 'parse-options' -o t:a:k:c:h:g: --long tenantId:,applicationId:,keyVaultName:,keyVaultCertificateThumbprint:,host:,groups: -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\n\necho \"Arguments: $@\"\neval set -- \"$OPTS\"\n\nwhile true; do\n  case \"$1\" in\n    -t | --tenantId )    TENANT_ID=\"$2\"; shift 2 ;;\n    -a | --applicationId ) APP_ID=\"$2\"; shift 2 ;;\n    -k | --keyVaultName ) KV_NAME=\"$2\"; shift 2 ;;\n    -c | --keyVaultCertificateThumbprint ) KV_CERT_THUMB=\"$2\"; shift 2 ;;\n    -h | --host ) SCHEDULER_HOST=\"$2\"; shift 2 ;;\n    -g | --groups ) BLADE_GROUPS=\"$2\"; shift 2 ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\n\n# When Batch recovers a VM, or a VM is pre-empted, a new\n# VM replaces the old one.  While the compute node Id doesn't\n# change, the hostname does and we want to prevent a new host from\n# registering itself in OpenCue.  To do this we'll create a hash\n# of the pool and compute node Id which will be predictable.\nHOSTNAME_PREFIX=\"az-\"\nhash=$(echo \"$AZ_BATCH_POOL_ID-$AZ_BATCH_NODE_ID\" | md5sum | cut -c 1-8)\nnewHostname=\"${HOSTNAME_PREFIX}${hash}\"\necho \"Updating hostname `hostname` to $newHostname\"\nhostnamectl set-hostname $newHostname\n\n\n# Application Licenses\nif [ -n \"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\" ]; then\n\n    # Pay-per-use licensing requires a URL and Token to\n    # be available to the renderer.  Here we set it globally.  \n    # Any render process needs to have the below envionrment.\n    accountUrl=$AZ_BATCH_ACCOUNT_URL\n    if [[ \"$accountUrl\" == */ ]]; then\n        accountUrl=${accountUrl::-1}\n    fi\n    echo export AZ_BATCH_ACCOUNT_URL=\\\"$accountUrl\\\" > /etc/profile.d/ses.sh\n    echo export AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN=\\\"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\\\" >> /etc/profile.d/ses.sh\nfi\n\n\nif [ -n \"$SCHEDULER_HOST\" ]; then\n    echo \"Setting scheduler host to $SCHEDULER_HOST\"\n    # Add any logic to update or set the scheduler host or IP here.\nfi\n\n\nif [ -n \"$BLADE_GROUPS\" ]; then\n    groups=$(echo $BLADE_GROUPS | tr ';' ',')\n    # Set any blade groups here\nfi\n\n\n# Install Telemetry Agent\nif [ -n \"$APP_INSIGHTS_INSTRUMENTATION_KEY\" ]; then\n    # Install and setup Application Insights for CPU/GPU and process metrics.\n    # These are required for auto-scale.\n    wget -O run-linux.sh https://raw.githubusercontent.com/Azure/batch-insights/v1.3.0/scripts/run-linux.sh\n    chmod +x run-linux.sh\n    ./run-linux.sh 2>&1\nfi\n\nexit 0\n", "num_lines": 83}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable history expansion to support passwords with '!'\nset +H\n\nINSTALLER_PATH=\"$AZ_BATCH_APP_PACKAGE_deadlineclient\"\nTENANT_ID=\nAPP_ID=\nKV_NAME=\nKV_CERT_THUMB=\nDEADLINE_REPO_PATH=\nDEADLINE_REPO_USER=\nDEADLINE_LIC_SERVER=\nDEADLINE_LIC_MODE=\nDEADLINE_REGION=\nSMB_SHARES=\nNFS_SHARES=\nDOMAIN_NAME=\nDEADLINE_GROUPS=\nDEADLINE_POOLS=\nDEADLINE_EXCLUDE_LIMIT_GROUPS=\n\nOPTS=`getopt -n 'parse-options' -o i:t:a:n:p:r:u:s:m:g:d:y:l:e: --long installerPath:,tenantId:,applicationId:,keyVaultName:,keyVaultCertificateThumbprint:,deadlineRepositoryPath:,deadlineRepositoryUserName:,deadlineLicenseServer:,deadlineLicenseMode:,deadlineRegion:,domainName:,deadlineGroups:,deadlinePools:,excludeFromLimitGroups: -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\n\necho \"Arguments: $@\"\neval set -- \"$OPTS\"\n\nwhile true; do\n  case \"$1\" in\n    -i | --installerPath ) INSTALLER_PATH=\"$2\"; shift 2 ;;\n    -t | --tenantId )    TENANT_ID=\"$2\"; shift 2 ;;\n    -a | --applicationId ) APP_ID=\"$2\"; shift 2 ;;\n    -n | --keyVaultName ) KV_NAME=\"$2\"; shift 2 ;;\n    -p | --keyVaultCertificateThumbprint ) KV_CERT_THUMB=\"$2\"; shift 2 ;;\n    -r | --deadlineRepositoryPath ) DEADLINE_REPO_PATH=\"$2\"; shift 2 ;;\n    -u | --deadlineRepositoryUserName ) DEADLINE_REPO_USER=\"$2\"; shift 2 ;;\n    -s | --deadlineLicenseServer ) DEADLINE_LIC_SERVER=\"$2\"; shift 2 ;;\n    -m | --deadlineLicenseMode ) DEADLINE_LIC_MODE=\"$2\"; shift 2 ;;\n    -g | --deadlineRegion ) DEADLINE_REGION=\"$2\"; shift 2 ;;\n    -d | --domainName ) DOMAIN_NAME=\"$2\"; shift 2 ;;\n    -y | --deadlineGroups ) DEADLINE_GROUPS=\"$2\"; shift 2 ;;\n    -l | --deadlinePools ) DEADLINE_POOLS=\"$2\"; shift 2 ;;\n    -e | --excludeFromLimitGroups ) DEADLINE_EXCLUDE_LIMIT_GROUPS=\"$2\"; shift 2 ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\n# Stop the launcher and slave from starting (yet)\nsystemctl stop deadline10launcher.service\n\n# When Batch recovers a VM, or a VM is pre-empted, a new\n# VM replaces the old one.  While the compute node Id doesn't\n# change, the hostname does and we want to prevent a new host from\n# registering itself in Deadline.  To do this we'll create a hash\n# of the pool and compute node Id which will be predictable.\nhash=$(echo \"$AZ_BATCH_POOL_ID-$AZ_BATCH_NODE_ID\" | md5sum)\nnewHostname=${hash/  -}\necho \"Updating hostname from `hostname` to $newHostname\"\nhostnamectl set-hostname $newHostname\n\n# Set any app licenses system wide.\nif [ -n \"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\" ]; then\n    accountUrl=$AZ_BATCH_ACCOUNT_URL\n    if [[ \"$accountUrl\" == */ ]]; then\n        accountUrl=${accountUrl::-1}\n    fi\n    echo export AZ_BATCH_ACCOUNT_URL=\\\"$accountUrl\\\" > /etc/profile.d/ses.sh\n    echo export AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN=\\\"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\\\" >> /etc/profile.d/ses.sh\nfi\n\n\nif [ -n \"$DEADLINE_REGION\" ]; then\n    /opt/Thinkbox/Deadline10/mono/bin/mono \"/opt/Thinkbox/Deadline10/bin/deadlinecommand.exe\" SetIniFileSetting Region\nfi\n\n\nif [ -n \"$DEADLINE_GROUPS\" ]; then\n    groups=$(echo $DEADLINE_GROUPS | tr ';' ',')\n    echo \"Adding slave to group(s) $groups\"\n    /opt/Thinkbox/Deadline10/bin/deadlinecommand SetGroupsForSlave `hostname` $groups\nfi\n\n\nif [ -n \"$DEADLINE_POOLS\" ]; then\n    pools=$(echo $DEADLINE_POOLS | tr ';' ',')\n    echo \"Adding slave to pool(s) $pools\"\n    /opt/Thinkbox/Deadline10/bin/deadlinecommand SetPoolsForSlave `hostname` $pools\nfi\n\n\nif [ -n \"$DEADLINE_EXCLUDE_LIMIT_GROUPS\" ]; then\n    wget -O limitgroups.py 'https://raw.githubusercontent.com/Azure/azure-render-farm-manager/master/Scripts/Deadline/limitgroups.py'\n    limitgroups=$(echo $DEADLINE_EXCLUDE_LIMIT_GROUPS | tr ';' '\\n')\n    for group in $limitgroups; do\n        echo \"Adding slave to limit group $group\"\n        /opt/Thinkbox/Deadline10/bin/deadlinecommand -ExecuteScriptNoGui limitgroups.py --limitgroups $group --slave `hostname` --exclude\n    done\nfi\n\n# Set the Pool and Compute Node name in the slave's description and extra data\n/opt/Thinkbox/Deadline10/bin/deadlinecommand SetSlaveSetting `hostname` SlaveDescription \"Pool: $AZ_BATCH_POOL_ID, ComputeNode: $AZ_BATCH_NODE_ID\"\n/opt/Thinkbox/Deadline10/bin/deadlinecommand SetSlaveExtraInfoKeyValue `hostname` PoolName $AZ_BATCH_POOL_ID\n/opt/Thinkbox/Deadline10/bin/deadlinecommand SetSlaveExtraInfoKeyValue `hostname` ComputeNodeName $AZ_BATCH_NODE_ID\n\n# Restart the Deadline Launcher\nsystemctl start deadline10launcher.service\n\nif [ -n \"$APP_INSIGHTS_INSTRUMENTATION_KEY\" ]; then\n    # Install and setup Application Insights for CPU/GPU and process\n    # metrics\n    /bin/bash -c 'wget  -O - https://raw.githubusercontent.com/Azure/batch-insights/v1.3.0/scripts/run-linux.sh | bash'\nfi\n", "num_lines": 115}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable history expansion to support passwords with '!'\nset +H\n\nINSTALLER_PATH=\nTENANT_ID=\nAPP_ID=\nKV_NAME=\nKV_CERT_THUMB=\nCUEBOT_HOST=\nOPENCUE_GROUPS=\nOPENCUE_FACILITY=\n\nOPTS=`getopt -n 'parse-options' -o i:t:a:k:c:e:g:f: --long installerPath:,tenantId:,applicationId:,keyVaultName:,keyVaultCertificateThumbprint:,cuebotHost:,groups:,facility: -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\n\necho \"Arguments: $@\"\neval set -- \"$OPTS\"\n\nwhile true; do\n  case \"$1\" in\n    -i | --installerPath ) INSTALLER_PATH=\"$2\"; shift 2 ;;\n    -t | --tenantId )    TENANT_ID=\"$2\"; shift 2 ;;\n    -a | --applicationId ) APP_ID=\"$2\"; shift 2 ;;\n    -k | --keyVaultName ) KV_NAME=\"$2\"; shift 2 ;;\n    -c | --keyVaultCertificateThumbprint ) KV_CERT_THUMB=\"$2\"; shift 2 ;;\n    -h | --cuebotHost ) CUEBOT_HOST=\"$2\"; shift 2 ;;\n    -f | --facility ) OPENCUE_FACILITY=\"$2\"; shift 2 ;;\n    -g | --groups ) OPENCUE_GROUPS=\"$2\"; shift 2 ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\nSERVICE_NAME=\"opencue-rqd.service\"\n\n# Stop the RQD service\nsystemctl | grep $SERVICE_NAME > /dev/null\nif [ $? -eq 0 ]; then\n    systemctl stop $SERVICE_NAME\nfi\n\n# When Batch recovers a VM, or a VM is pre-empted, a new\n# VM replaces the old one.  While the compute node Id doesn't\n# change, the hostname does and we want to prevent a new host from\n# registering itself in OpenCue.  To do this we'll create a hash\n# of the pool and compute node Id which will be predictable.\nHOSTNAME_PREFIX=\"azure-\"\nhash=$(echo \"$AZ_BATCH_POOL_ID-$AZ_BATCH_NODE_ID\" | md5sum | cut -c 1-8)\nnewHostname=\"${HOSTNAME_PREFIX}${hash}\"\necho \"Updating hostname `hostname` to $newHostname\"\nhostnamectl set-hostname $newHostname\n\n\n# Set any app licenses system wide.\nif [ -n \"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\" ]; then\n    accountUrl=$AZ_BATCH_ACCOUNT_URL\n    if [[ \"$accountUrl\" == */ ]]; then\n        accountUrl=${accountUrl::-1}\n    fi\n    echo export AZ_BATCH_ACCOUNT_URL=\\\"$accountUrl\\\" > /etc/profile.d/ses.sh\n    echo export AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN=\\\"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\\\" >> /etc/profile.d/ses.sh\nfi\n\nif [ -n \"$INSTALLER_PATH\" ]; then\n\n    # Find the installer\n    installer=$(find ./$INSTALLER_PATH -name 'rqd-*-all.tar.gz' | head -1)\n\n    if [ -e \"$installer\" ]; then\n        # Install OpenCue RQD\n\n        echo \"Installing $installer\"\n\n        n=0\n        while true\n        do\n            if [ $n -ge 5 ]; then\n                echo \"Failed to install yum packages epel-release gcc python-devel time\"\n                exit 1\n            fi\n            \n            yum install -y install epel-release gcc python-devel time && break  # substitute your command here\n            \n            n=$[$n+1]\n            s=$((1 + RANDOM % 15))\n            sleep $s\n        done\n\n        n=0\n        while true\n        do\n            if [ $n -ge 5 ]; then\n                echo \"Failed to install yum packages python-pip\"\n                exit 1\n            fi\n            \n            yum install -y python-pip && break  # substitute your command here\n            \n            n=$[$n+1]\n            s=$((1 + RANDOM % 15))\n            sleep $s\n        done\n\n        tar xvfz \"$installer\"\n\n        rqd_dir=$(basename -s '.tar.gz' $installer)\n\n        cd $rqd_dir\n\n        sudo -H pip install -r requirements.txt\n\n        sudo -H python setup.py install\n\ncat > opencue-rqd.service <<'EOF'\n[Unit]\nDescription=OpenCue RQD Service\nWants=network.target\nAfter=network.target\n\n[Service]\nEnvironment=OPTIONS=\nEnvironment=BIN=/usr/bin\nEnvironmentFile=-/etc/sysconfig/opencue-rqd\nExecStart=/bin/bash -c \"${BIN}/rqd ${OPTIONS}\"\nLimitNOFILE=500000\nLimitNPROC=500000\nStandardOutput=syslog+console\nStandardError=syslog+console\nSyslogIdentifier=rqd\n\n[Install]\nWantedBy=multi-user.target\nEOF\n\n        # Copy the systemd service script\n        cp opencue-rqd.service /usr/lib/systemd/system\n\n        # Enable the service\n        systemctl enable $SERVICE_NAME\n\n        systemctl daemon-reload\n    else\n        echo \"No OpenCue installer tarball found in $INSTALLER_PATH\"\n    fi\nfi\n\nif [ -n \"$OPENCUE_FACILITY\" ]; then\n    if [ -e \"/etc/opencue/rqd.conf\" ]; then\n        grep -q '^DEFAULT_FACILITY=' /etc/opencue/rqd.conf\n        if [ $? -eq 0 ]; then\n            # Update the existing facility\n            sed -i .bak \"s/DEFAULT_FACILITY=.*/DEFAULT_FACILITY=$OPENCUE_FACILITY/\" /etc/opencue/rqd.conf\n        else\n            echo \"DEFAULT_FACILITY=$OPENCUE_FACILITY\" >> /etc/opencue/rqd.conf\n        fi\n    else\n        # Set the default facility\n        mkdir /etc/opencue\n        echo \"[Override]\" > /etc/opencue/rqd.conf\n        echo \"DEFAULT_FACILITY=$OPENCUE_FACILITY\" >> /etc/opencue/rqd.conf\n    fi\nfi\n\n\nif [ -n \"$CUEBOT_HOST\" ]; then\n    \n    echo \"Setting Cuebot host to $CUEBOT_HOST\"\n    \n    if [ -e \"/etc/opencue/rqd.conf\" ]; then\n        grep -q '^OVERRIDE_CUEBOT=' /etc/opencue/rqd.conf\n        if [ $? -eq 0 ]; then\n            # Update the existing facility\n            sed -i .bak \"s/OVERRIDE_CUEBOT=.*/OVERRIDE_CUEBOT=$CUEBOT_HOST/\" /etc/opencue/rqd.conf\n        else\n            echo \"OVERRIDE_CUEBOT=$CUEBOT_HOST\" >> /etc/opencue/rqd.conf\n        fi\n    else\n        # Set the default facility\n        mkdir /etc/opencue\n        echo \"[Override]\" > /etc/opencue/rqd.conf\n        echo \"OVERRIDE_CUEBOT=$CUEBOT_HOST\" >> /etc/opencue/rqd.conf\n    fi\nfi\n\n\nif [ -n \"$OPENCUE_GROUPS\" ]; then\n    groups=$(echo $OPENCUE_GROUPS | tr ';' ',')\n    # TODO - We need to add this RQD into the specified groups\nfi\n\n\nsystemctl start $SERVICE_NAME\n\n\nif [ -n \"$APP_INSIGHTS_INSTRUMENTATION_KEY\" ]; then\n    # Install and setup Application Insights for CPU/GPU and process metrics\n    wget -O run-linux.sh https://raw.githubusercontent.com/Azure/batch-insights/v1.3.0/scripts/run-linux.sh\n    chmod +x run-linux.sh\n    ./run-linux.sh 2>&1\nfi\n\nsystemctl status $SERVICE_NAME\n\nexit 0\n", "num_lines": 207}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\necho \"TODO\"\n\nexit 1\n", "num_lines": 6}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Allowed NFS clients IP or address range (CIDR block)\n# e.g. 10.2.0.0/24\nALLOWED_HOSTS=\"$1\"\n\n# The export path\nEXPORT=\"$2\"\n\nyum install -y nfs-utils rpcbind rsync mdadm \n\nif [ -z \"$ALLOWED_HOSTS\" ]; then\n    ALLOWED_HOSTS=\"*\"\nfi\n\nif [ -z \"$EXPORT\" ]; then\n    echo \"No export specified\"\n    exit 1\nfi\n\nmountPoint=\"$(dirname $EXPORT)\"\nmkdir -p $mountPoint\ncreatedPartitions=\"\"\n\n# Loop through and partition disks until not found\nfor disk in sdc sdd sde sdf sdg sdh sdi sdj sdk sdl sdm sdn sdo sdp sdq sdr; do\n    fdisk -l /dev/$disk || break\n    fdisk /dev/$disk << EOF\nn\np\n1\n\n\nt\nfd\nw\nEOF\n    createdPartitions=\"$createdPartitions /dev/${disk}1\"\ndone\n\nsleep 15\n\n# Create RAID-0 volume\nif [ -n \"$createdPartitions\" ]; then\n    devices=`echo $createdPartitions | wc -w`\n    mdadm --create /dev/md10 --level 0 --raid-devices $devices $createdPartitions\n    mkfs -t ext4 /dev/md10\n    echo \"/dev/md10 $mountPoint ext4 defaults,nofail 0 2\" >> /etc/fstab\n    sleep 15\n    mount /dev/md10\nfi\n\nrm /etc/exports\nmkdir -p $EXPORT\nchown nfsnobody:nfsnobody $EXPORT\nchmod -R 770 $EXPORT\necho \"$EXPORT    $ALLOWED_HOSTS(rw,sync,no_root_squash,all_squash,anonuid=65534,anongid=65534)\" >> /etc/exports\n\nsystemctl enable nfs-server.service\nsystemctl start nfs-server.service\n\necho \"Done\"\n", "num_lines": 63}
{"repo_name": "azure-render-hub", "repo_creator": "Azure", "programming_language": "Shell", "code": "#!/bin/bash\n\n# Disable history expansion to support passwords with '!'\nset +H\n\nINSTALLER_PATH=\nTENANT_ID=\nAPP_ID=\nKV_NAME=\nKV_CERT_THUMB=\nTRACTOR_ENGINE=\nTRACTOR_GROUPS=\n\nOPTS=`getopt -n 'parse-options' -o i:t:a:k:c:e:g: --long installerPath:,tenantId:,applicationId:,keyVaultName:,keyVaultCertificateThumbprint:,engineHost:,groups: -- \"$@\"`\nif [ $? != 0 ] ; then echo \"Failed parsing options.\" >&2 ; exit 1 ; fi\n\necho \"Arguments: $@\"\neval set -- \"$OPTS\"\n\nwhile true; do\n  case \"$1\" in\n    -i | --installerPath ) INSTALLER_PATH=\"$2\"; shift 2 ;;\n    -t | --tenantId )    TENANT_ID=\"$2\"; shift 2 ;;\n    -a | --applicationId ) APP_ID=\"$2\"; shift 2 ;;\n    -k | --keyVaultName ) KV_NAME=\"$2\"; shift 2 ;;\n    -c | --keyVaultCertificateThumbprint ) KV_CERT_THUMB=\"$2\"; shift 2 ;;\n    -e | --engineHost ) TRACTOR_ENGINE=\"$2\"; shift 2 ;;\n    -g | --groups ) TRACTOR_GROUPS=\"$2\"; shift 2 ;;\n    -- ) shift; break ;;\n    * ) break ;;\n  esac\ndone\n\n# Stop the blade service\nsystemctl | grep tractor-blade > /dev/null\nif [ $? -eq 0 ]; then\n    systemctl stop tractor-blade.service\nfi\n\n# When Batch recovers a VM, or a VM is pre-empted, a new\n# VM replaces the old one.  While the compute node Id doesn't\n# change, the hostname does and we want to prevent a new host from\n# registering itself in Tractor.  To do this we'll create a hash\n# of the pool and compute node Id which will be predictable.\nHOSTNAME_PREFIX=\"azure-\"\nhash=$(echo \"$AZ_BATCH_POOL_ID-$AZ_BATCH_NODE_ID\" | md5sum | cut -c 1-8)\nnewHostname=\"${HOSTNAME_PREFIX}${hash}\"\necho \"Updating hostname `hostname` to $newHostname\"\nhostnamectl set-hostname $newHostname\n\n\n# Set any app licenses system wide.\nif [ -n \"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\" ]; then\n    accountUrl=$AZ_BATCH_ACCOUNT_URL\n    if [[ \"$accountUrl\" == */ ]]; then\n        accountUrl=${accountUrl::-1}\n    fi\n    echo export AZ_BATCH_ACCOUNT_URL=\\\"$accountUrl\\\" > /etc/profile.d/ses.sh\n    echo export AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN=\\\"$AZ_BATCH_SOFTWARE_ENTITLEMENT_TOKEN\\\" >> /etc/profile.d/ses.sh\nfi\n\n\nif [ -n \"$INSTALLER_PATH\" ]; then\n\n    # Find the installer RPM\n    installer=$(find ./$INSTALLER_PATH -name 'Tractor-2.*.rpm' | head -1)\n\n    if [ -e \"$installer\" ]; then\n        # Install Tractor blade\n\n        echo \"Installing $installer\"\n\n        rpm -i $installer\n\n        # Get Tractor version, 2.2 or 2.3\n        version=$(echo $installer | grep -oP 'Tractor-\\K(2.[23])')\n\n        if [ -n \"$TRACTOR_ENGINE\" ]; then\n            echo \"Setting Tractor Engine override to $TRACTOR_ENGINE\"\n\n            # Tractor 2.3 has a bug in the systemd script that points to Tractor 2.2\n            echo \"BIN=/opt/pixar/Tractor-${version}/bin\" > /etc/sysconfig/tractor-blade\n\n            # Override the Tractor engine hostname and port, if specified.\n            echo \"OPTIONS=\\\"--engine $TRACTOR_ENGINE\\\"\" >> /etc/sysconfig/tractor-blade\n        fi\n\n        # Copy the systemd service script\n        cp /opt/pixar/Tractor-${version}/lib/SystemServices/systemd/tractor-blade.service /usr/lib/systemd/system\n\n        # Enable the service\n        systemctl enable tractor-blade.service\n\n        systemctl daemon-reload\n    else\n        echo \"No Tractor installer RPM found in $INSTALLER_PATH\"\n    fi\nfi\n\n\nif [ -n \"$TRACTOR_GROUPS\" ]; then\n    groups=$(echo $TRACTOR_GROUPS | tr ';' ',')\n    # TODO - We need to add this blade into the specified groups\nfi\n\necho \"Starting Tractor Blade service\"\n\n# Start the Tractor Blade service\nsystemctl start tractor-blade.service\n\nif [ -n \"$APP_INSIGHTS_INSTRUMENTATION_KEY\" ]; then\n    # Install and setup Application Insights for CPU/GPU and process metrics\n    wget -O run-linux.sh https://raw.githubusercontent.com/Azure/batch-insights/v1.3.0/scripts/run-linux.sh\n    chmod +x run-linux.sh\n    ./run-linux.sh 2>&1\nfi\n\nsystemctl status tractor-blade.service\n", "num_lines": 119}
{"repo_name": "azure-rest-api-specs", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#!/bin/bash\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Copying files to /usr/data/openapispecs\"\nmkdir -p /usr/data/openapispecs/.git\ncp -R /usr/data/specrepo/.git/* /usr/data/openapispecs/.git/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Running 'git checkout [$specRetrievalGitBranch] -f'\"\ngit checkout $specRetrievalGitBranch -f\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Deleting directory /usr/data/specrepo\"\nrm -R /usr/data/specrepo/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Init completed successfully. OpenAPI specs are present in /usr/data/openapispecs.\"\n", "num_lines": 19}
{"repo_name": "azure-rest-api-specs-1", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#!/bin/bash\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Copying files to /usr/data/openapispecs\"\nmkdir -p /usr/data/openapispecs/.git\ncp -R /usr/data/specrepo/.git/* /usr/data/openapispecs/.git/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Running 'git checkout [$specRetrievalGitBranch] -f'\"\ngit checkout $specRetrievalGitBranch -f\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Deleting directory /usr/data/specrepo\"\nrm -R /usr/data/specrepo/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Init completed successfully. OpenAPI specs are present in /usr/data/openapispecs.\"\n", "num_lines": 19}
{"repo_name": "azure-rest-api-specs-2", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#!/bin/bash\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Copying files to /usr/data/openapispecs\"\nmkdir -p /usr/data/openapispecs/.git\ncp -R /usr/data/specrepo/.git/* /usr/data/openapispecs/.git/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Running 'git checkout [$specRetrievalGitBranch] -f'\"\ngit checkout $specRetrievalGitBranch -f\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Deleting directory /usr/data/specrepo\"\nrm -R /usr/data/specrepo/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Init completed successfully. OpenAPI specs are present in /usr/data/openapispecs.\"\n", "num_lines": 19}
{"repo_name": "azure-rest-api-specs-2", "repo_creator": "Azure", "programming_language": "Shell", "code": "\n#!/bin/bash\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Copying files to /usr/data/openapispecs\"\nmkdir -p /usr/data/openapispecs/.git\ncp -R /usr/data/specrepo/.git/* /usr/data/openapispecs/.git/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Running 'git checkout [$specRetrievalGitBranch] -f'\"\ngit checkout $specRetrievalGitBranch -f\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Deleting directory /usr/data/specrepo\"\nrm -R /usr/data/specrepo/\n\ntimestamp=`date +%Y/%m/%d-%H:%M:%S`\necho \"[$timestamp] Init completed successfully. OpenAPI specs are present in /usr/data/openapispecs.\"\n", "num_lines": 19}
{"repo_name": "Lib", "repo_creator": "Python310", "programming_language": "Shell", "code": "# Copyright 2012-2013, Andrey Kislyuk and argcomplete contributors.\n# Licensed under the Apache License. See https://github.com/kislyuk/argcomplete for more info.\n\n# Copy of __expand_tilde_by_ref from bash-completion\n__python_argcomplete_expand_tilde_by_ref () {\n    if [ \"${!1:0:1}\" = \"~\" ]; then\n        if [ \"${!1}\" != \"${!1//\\/}\" ]; then\n            eval $1=\"${!1/%\\/*}\"/'${!1#*/}';\n        else\n            eval $1=\"${!1}\";\n        fi;\n    fi\n}\n\n# Run something, muting output or redirecting it to the debug stream\n# depending on the value of _ARC_DEBUG.\n__python_argcomplete_run() {\n    if [[ -z \"$_ARC_DEBUG\" ]]; then\n        \"$@\" 8>&1 9>&2 1>/dev/null 2>&1\n    else\n        \"$@\" 8>&1 9>&2 1>&9 2>&1\n    fi\n}\n\n_python_argcomplete_global() {\n    local executable=$1\n    __python_argcomplete_expand_tilde_by_ref executable\n\n    local ARGCOMPLETE=0\n    if [[ \"$executable\" == python* ]] || [[ \"$executable\" == pypy* ]]; then\n        if [[ \"${COMP_WORDS[1]}\" == -m ]]; then\n            if __python_argcomplete_run \"$executable\" -m argcomplete._check_module \"${COMP_WORDS[2]}\"; then\n                ARGCOMPLETE=3\n            else\n                return\n            fi\n        elif [[ -f \"${COMP_WORDS[1]}\" ]] && (head -c 1024 \"${COMP_WORDS[1]}\" | grep --quiet \"PYTHON_ARGCOMPLETE_OK\") >/dev/null 2>&1; then\n            local ARGCOMPLETE=2\n        else\n            return\n        fi\n    elif which \"$executable\" >/dev/null 2>&1; then\n        local SCRIPT_NAME=$(which \"$executable\")\n        if (type -t pyenv && [[ \"$SCRIPT_NAME\" = $(pyenv root)/shims/* ]]) >/dev/null 2>&1; then\n            local SCRIPT_NAME=$(pyenv which \"$executable\")\n        fi\n        if (head -c 1024 \"$SCRIPT_NAME\" | grep --quiet \"PYTHON_ARGCOMPLETE_OK\") >/dev/null 2>&1; then\n            local ARGCOMPLETE=1\n        elif [[ \"$(head -n 1 \"$SCRIPT_NAME\")\" =~ ^#!(.*)$ ]] && [[ \"${BASH_REMATCH[1]}\" =~ ^.*(python|pypy)[0-9\\.]*$ ]]; then\n            local interpreter=\"$BASH_REMATCH\"\n            if (head -c 1024 \"$SCRIPT_NAME\" | egrep --quiet \"(PBR Generated)|(EASY-INSTALL-(SCRIPT|ENTRY-SCRIPT|DEV-SCRIPT))\" \\\n                && \"$interpreter\" \"$(which python-argcomplete-check-easy-install-script)\" \"$SCRIPT_NAME\") >/dev/null 2>&1; then\n                local ARGCOMPLETE=1\n            elif __python_argcomplete_run \"$interpreter\" -m argcomplete._check_console_script \"$SCRIPT_NAME\"; then\n                local ARGCOMPLETE=1\n            fi\n        fi\n    fi\n\n    if [[ $ARGCOMPLETE != 0 ]]; then\n        local IFS=$(echo -e '\\v')\n        COMPREPLY=( $(_ARGCOMPLETE_IFS=\"$IFS\" \\\n            COMP_LINE=\"$COMP_LINE\" \\\n            COMP_POINT=\"$COMP_POINT\" \\\n            COMP_TYPE=\"$COMP_TYPE\" \\\n            _ARGCOMPLETE_COMP_WORDBREAKS=\"$COMP_WORDBREAKS\" \\\n            _ARGCOMPLETE=$ARGCOMPLETE \\\n            _ARGCOMPLETE_SUPPRESS_SPACE=1 \\\n            __python_argcomplete_run \"$executable\" \"${COMP_WORDS[@]:1:ARGCOMPLETE-1}\") )\n        if [[ $? != 0 ]]; then\n            unset COMPREPLY\n        elif [[ \"$COMPREPLY\" =~ [=/:]$ ]]; then\n            compopt -o nospace\n        fi\n    else\n        type -t _completion_loader | grep -q 'function' && _completion_loader \"$@\"\n    fi\n}\ncomplete -o default -o bashdefault -D -F _python_argcomplete_global\n", "num_lines": 80}
{"repo_name": "Lib", "repo_creator": "Python310", "programming_language": "Shell", "code": "#!/usr/bin/env bash\n_tqdm(){\n  local cur prv\n  cur=\"${COMP_WORDS[COMP_CWORD]}\"\n  prv=\"${COMP_WORDS[COMP_CWORD - 1]}\"\n\n  case ${prv} in\n  --bar_format|--buf_size|--colour|--comppath|--delay|--delim|--desc|--initial|--lock_args|--manpath|--maxinterval|--mininterval|--miniters|--ncols|--nrows|--position|--postfix|--smoothing|--total|--unit|--unit_divisor)\n    # await user input\n    ;;\n  \"--log\")\n    COMPREPLY=($(compgen -W       'CRITICAL FATAL ERROR WARN WARNING INFO DEBUG NOTSET' -- ${cur}))\n    ;;\n  *)\n    COMPREPLY=($(compgen -W '--ascii --bar_format --buf_size --bytes --colour --comppath --delay --delim --desc --disable --dynamic_ncols --help --initial --leave --lock_args --log --manpath --maxinterval --mininterval --miniters --ncols --nrows --null --position --postfix --smoothing --tee --total --unit --unit_divisor --unit_scale --update --update_to --version --write_bytes -h -v' -- ${cur}))\n    ;;\n  esac\n}\ncomplete -F _tqdm tqdm\n", "num_lines": 20}
{"repo_name": "Lib", "repo_creator": "Python310", "programming_language": "Shell", "code": "#!/bin/bash\nINTERPRETER_UNDER_TEST=\"$1\"\nif [[ ! -x \"${INTERPRETER_UNDER_TEST}\" ]]; then\n    echo \"Interpreter must be the command line argument.\"\n    exit 4\nfi\nEXECUTABLE=\"$0\" exec \"${INTERPRETER_UNDER_TEST}\" -E - <<END_OF_PYTHON\nimport os\nimport zipfile\n\nnamespace = {}\n\nfilename = os.environ['EXECUTABLE']\nprint(f'Opening {filename} as a zipfile.')\nwith zipfile.ZipFile(filename, mode='r') as exe_zip:\n  for file_info in exe_zip.infolist():\n    data = exe_zip.read(file_info)\n    exec(data, namespace, namespace)\n    break  # Only use the first file in the archive.\n\nprint('Favorite number in executable:', namespace[\"FAVORITE_NUMBER\"])\n\n### Archive contents will be appended after this file. ###\nEND_OF_PYTHON\n", "num_lines": 25}
{"repo_name": "tcl", "repo_creator": "Python310", "programming_language": "Shell", "code": "# tclConfig.sh --\n#\n# This shell script (for sh) is generated automatically by Tcl's\n# configure script.  It will create shell variables for most of\n# the configuration options discovered by the configure script.\n# This script is intended to be included by the configure scripts\n# for Tcl extensions so that they don't have to figure this all\n# out for themselves.\n#\n# The information in this file is specific to a single platform.\n\nTCL_DLL_FILE=\"tcl86t.dll\"\n\n# Tcl's version number.\nTCL_VERSION='8.6'\nTCL_MAJOR_VERSION='8'\nTCL_MINOR_VERSION='6'\nTCL_PATCH_LEVEL='8.6.12'\n\n# C compiler to use for compilation.\nTCL_CC='cl'\n\n# -D flags for use with the C compiler.\nTCL_DEFS='-nologo -c /D_ATL_XP_TARGETING  -W3 -wd4311 -wd4312 -wd4311 -wd4312 -FpC:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\  -fp:strict -O2 -GS -GL -MD -I\"C:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\..\\win\" -I\"C:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\..\\generic\"  -I\"C:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\..\\libtommath\"  /DTCL_TOMMATH /DMP_PREC=4 /Dinline=__inline /DHAVE_ZLIB=1 /D_CRT_SECURE_NO_DEPRECATE /D_CRT_NONSTDC_NO_DEPRECATE /DMP_FIXED_CUTOFFS /DSTDC_HEADERS /DUSE_NMAKE=1 /DHAVE_STDINT_H=1 /DHAVE_INTTYPES_H=1 /DHAVE_STDBOOL_H=1 /DTCL_THREADS=1 /DUSE_THREAD_ALLOC=1 /DNDEBUG /DTCL_CFG_OPTIMIZED /DTCL_CFG_DO64BIT   /DBUILD_tcl'\n\n# If TCL was built with debugging symbols, generated libraries contain\n# this string at the end of the library name (before the extension).\nTCL_DBGX=t\n\n# Default flags used in an optimized and debuggable build, respectively.\nTCL_CFLAGS_DEBUG='-nologo -c -W3 -YX -FpC:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\ -MDd'\nTCL_CFLAGS_OPTIMIZE='-nologo -c -W3 -YX -FpC:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\Release_AMD64_VC13\\tcl_ThreadedDynamic\\ -MD'\n\n# Default linker flags used in an optimized and debuggable build, respectively.\nTCL_LDFLAGS_DEBUG='-nologo -machine:AMD64 -debug -debugtype:cv'\nTCL_LDFLAGS_OPTIMIZE='-nologo -machine:AMD64 -release -opt:ref -opt:icf,3'\n\n# Flag, 1: we built a shared lib, 0 we didn't\nTCL_SHARED_BUILD=1\n\n# The name of the Tcl library (may be either a .a file or a shared library):\nTCL_LIB_FILE='tcl86t.lib'\n\n# Flag to indicate whether shared libraries need export files.\nTCL_NEEDS_EXP_FILE=\n\n# String that can be evaluated to generate the part of the export file\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variables\n# VERSION.  On most UNIX systems this is ${VERSION}.exp.\nTCL_EXPORT_FILE_SUFFIX='86t.lib'\n\n# Additional libraries to use when linking Tcl.\nTCL_LIBS='kernel32.lib advapi32.lib netapi32.lib user32.lib userenv.lib ws2_32.lib ucrt.lib netapi32.lib user32.lib userenv.lib ws2_32.lib'\n\n# Top-level directory in which Tcl's platform-independent files are\n# installed.\nTCL_PREFIX='C:\\A\\37\\a\\amd64'\n\n# Top-level directory in which Tcl's platform-specific files (e.g.\n# executables) are installed.\nTCL_EXEC_PREFIX='C:\\A\\37\\a\\amd64\\bin'\n\n# Flags to pass to cc when compiling the components of a shared library:\nTCL_SHLIB_CFLAGS=''\n\n# Flags to pass to cc to get warning messages\nTCL_CFLAGS_WARNING='-W3'\n\n# Extra flags to pass to cc:\nTCL_EXTRA_CFLAGS='-YX'\n\n# Base command to use for combining object files into a shared library:\nTCL_SHLIB_LD='link -nologo -machine:AMD64  -ltcg -release -opt:ref -opt:icf,3 -nodefaultlib:libucrt.lib -dll'\n\n# Base command to use for combining object files into a static library:\nTCL_STLIB_LD='lib -nologo'\n\n# Either '$LIBS' (if dependent libraries should be included when linking\n# shared libraries) or an empty string.  See Tcl's configure.in for more\n# explanation.\nTCL_SHLIB_LD_LIBS='kernel32.lib advapi32.lib netapi32.lib user32.lib userenv.lib ws2_32.lib ucrt.lib netapi32.lib user32.lib userenv.lib ws2_32.lib'\n\n# Suffix to use for the name of a shared library.\nTCL_SHLIB_SUFFIX='.dll'\n\n# Library file(s) to include in tclsh and other base applications\n# in order to provide facilities needed by DLOBJ above.\nTCL_DL_LIBS=''\n\n# Flags to pass to the compiler when linking object files into\n# an executable tclsh or tcltest binary.\nTCL_LD_FLAGS=''\n\n# Flags to pass to cc/ld, such as \"-R /usr/local/tcl/lib\", that tell the\n# run-time dynamic linker where to look for shared libraries such as\n# libtcl.so.  Used when linking applications.  Only works if there\n# is a variable \"LIB_RUNTIME_DIR\" defined in the Makefile.\nTCL_CC_SEARCH_FLAGS=''\nTCL_LD_SEARCH_FLAGS=''\n\n# Additional object files linked with Tcl to provide compatibility\n# with standard facilities from ANSI C or POSIX.\nTCL_COMPAT_OBJS=''\n\n# Name of the ranlib program to use.\nTCL_RANLIB=''\n\n# -l flag to pass to the linker to pick up the Tcl library\nTCL_LIB_FLAG=''\n\n# String to pass to linker to pick up the Tcl library from its\n# build directory.\nTCL_BUILD_LIB_SPEC=''\n\n# String to pass to linker to pick up the Tcl library from its\n# installed directory.\nTCL_LIB_SPEC='C:\\A\\37\\a\\amd64\\lib\\tcl86t.lib'\n\n# String to pass to the compiler so that an extension can\n# find installed Tcl headers.\nTCL_INCLUDE_SPEC='-IC:\\A\\37\\a\\amd64\\include'\n\n# Indicates whether a version numbers should be used in -l switches\n# (\"ok\" means it's safe to use switches like -ltcl7.5;  \"nodots\" means\n# use switches like -ltcl75).  SunOS and FreeBSD require \"nodots\", for\n# example.\nTCL_LIB_VERSIONS_OK=''\n\n# String that can be evaluated to generate the part of a shared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variables\n# VERSION and SHLIB_SUFFIX.  On most UNIX systems this is\n# ${VERSION}${SHLIB_SUFFIX}.\nTCL_SHARED_LIB_SUFFIX='86t.dll'\n\n# String that can be evaluated to generate the part of an unshared library\n# name that comes after the \"libxxx\" (includes version number, if any,\n# extension, and anything else needed).  May depend on the variable\n# VERSION.  On most UNIX systems this is ${VERSION}.a.\nTCL_UNSHARED_LIB_SUFFIX='86t.lib'\n\n# Location of the top-level source directory from which Tcl was built.\n# This is the directory that contains a README file as well as\n# subdirectories such as generic, unix, etc.  If Tcl was compiled in a\n# different place than the directory containing the source files, this\n# points to the location of the sources, not the location where Tcl was\n# compiled.\nTCL_SRC_DIR='C:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\..'\n\n# List of standard directories in which to look for packages during\n# \"package require\" commands.  Contains the \"prefix\" directory plus also\n# the \"exec_prefix\" directory, if it is different.\nTCL_PACKAGE_PATH=''\n\n# Tcl supports stub.\nTCL_SUPPORTS_STUBS=1\n\n# The name of the Tcl stub library (.a):\nTCL_STUB_LIB_FILE='tclstub86.lib'\n\n# -l flag to pass to the linker to pick up the Tcl stub library\nTCL_STUB_LIB_FLAG='tclstub86.lib'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# build directory.\nTCL_BUILD_STUB_LIB_SPEC='-LC:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\Release_AMD64_VC13 tclstub86.lib'\n\n# String to pass to linker to pick up the Tcl stub library from its\n# installed directory.\nTCL_STUB_LIB_SPEC='-LC:\\A\\37\\a\\amd64\\lib tclstub86.lib'\n\n# Path to the Tcl stub library in the build directory.\nTCL_BUILD_STUB_LIB_PATH='C:\\A\\37\\b\\externals\\tcl-core-8.6.12.0\\win\\Release_AMD64_VC13\\tclstub86.lib'\n\n# Path to the Tcl stub library in the install directory.\nTCL_STUB_LIB_PATH='C:\\A\\37\\a\\amd64\\lib\\tclstub86.lib'\n\n# Flag, 1: we built Tcl with threads enabled, 0 we didn't\nTCL_THREADS=1\n\n", "num_lines": 182}
{"repo_name": "tcl", "repo_creator": "Python310", "programming_language": "Shell", "code": "# tclooConfig.sh --\n#\n# This shell script (for sh) is generated automatically by TclOO's configure\n# script, or would be except it has no values that we substitute. It will\n# create shell variables for most of the configuration options discovered by\n# the configure script. This script is intended to be included by TEA-based\n# configure scripts for TclOO extensions so that they don't have to figure\n# this all out for themselves.\n#\n# The information in this file is specific to a single platform.\n\n# These are mostly empty because no special steps are ever needed from Tcl 8.6\n# onwards; all libraries and include files are just part of Tcl.\nTCLOO_LIB_SPEC=\"\"\nTCLOO_STUB_LIB_SPEC=\"\"\nTCLOO_INCLUDE_SPEC=\"\"\nTCLOO_PRIVATE_INCLUDE_SPEC=\"\"\nTCLOO_CFLAGS=\"\"\nTCLOO_VERSION=1.1.0\n", "num_lines": 20}
